diff --git a/.ci/format_script.sh b/.ci/format_script.sh index 67503dd8710de..4681dc52df269 100755 --- a/.ci/format_script.sh +++ b/.ci/format_script.sh @@ -3,7 +3,7 @@ set -ex echo "Running clang-format against branch $TRAVIS_BRANCH, with hash $BASE_COMMIT" -COMMIT_FILES=$(git diff --name-only $BASE_COMMIT | grep -i -v LinkDef) +COMMIT_FILES=$(git diff --name-status $BASE_COMMIT | grep -i -v LinkDef | grep -v -E '^D +' | sed -E 's,^.[[:space:]]+,,') RESULT_OUTPUT="$(git-clang-format --commit $BASE_COMMIT --diff --binary `which clang-format` $COMMIT_FILES)" if [ "$RESULT_OUTPUT" == "no modified files to format" ] \ diff --git a/.clang-format b/.clang-format index 9d4c30fcb5b23..acefcdd85cae0 100644 --- a/.clang-format +++ b/.clang-format @@ -38,7 +38,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false ColumnLimit: 120 CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 3 ContinuationIndentWidth: 3 Cpp11BracedListStyle: true diff --git a/.gitattributes b/.gitattributes index 19e21da899480..22134ff200634 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,6 +13,9 @@ *.vsixmanifest eol=crlf tree/dataframe/test/RCsvDS_test_win.csv eol=crlf +# Files in the LLVM monorepo are not normalized, avoid whitespace diffs. +interpreter/llvm-project/** -text + # Denote all files that are truly binary and should not be modified. *.png binary *.jpg binary diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 8f570a4cddd0f..2f062dc8ffdfa 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -21,7 +21,7 @@ /html/ @Axel-Naumann /icons/ @bellenot /interpreter/ @Axel-Naumann -/interpreter/llvm/ @vgvassilev +/interpreter/llvm-project/ @vgvassilev interpreter/cling/tools/packaging @vgvassilev /io/ @pcanal /io/xml/ @pcanal @linev @@ -38,9 +38,10 @@ interpreter/cling/tools/packaging @vgvassilev /tmva/ @lmoneta @sitongan /tree/ @pcanal /tutorials/ @couet -/tree/dataframe/ @eguiraud +/tree/dataframe/ @eguiraud @vepadulano /tree/readspeed/ @eguiraud /tree/ntuple/v7/ @jblomer +/tree/ntupleutil/v7/ @jblomer # Projects that span over several code modules: /bindings/r/ @omazapa diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 4be6f8628df88..0000000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: Bug report -about: Create a report to get an issue fixed -title: '' -labels: bug ---- - -- [ ] Checked for duplicates - - -### Describe the bug - - -### Expected behavior - - -### To Reproduce - - -### Setup - - -### Additional context - diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000..47e05f834ffe8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,61 @@ +name: Bug Report +description: Create a report to get an issue fixed. +labels: ["bug"] +body: + - type: markdown + attributes: + value: Thank you for taking the time to fill out this bug report! Note that since v6.28/06 you can also prefill this template using `root -q -e '.gh bug'` + - type: checkboxes + id: check-duplicates + attributes: + label: Check duplicate issues. + description: Please search in [GitHub](https://github.com/root-project/root/issues?q=is%3Aissue) AND [Jira]() for existing reports of your issue. + options: + - label: Checked for duplicates + validations: + required: true + - type: textarea + id: bug-description + attributes: + label: Description + description: A description of what the behavior is as opposed to the expected behavior. + validations: + required: true + - type: textarea + id: to-reproduce + attributes: + label: Reproducer + description: | + Step-by-step instructions to reproduce the issue. + - If possible, as a self-contained piece of code + - Don't forget to attach any required input files + - Please specify how to run your code, e.g. `root myMacro.C`, ... + validations: + required: true + - type: textarea + id: root-version + attributes: + label: ROOT version + description: On Linux/MacOS, `root -b -q | xclip -sel clip`. On Windows, `root -b -q | clip.exe` + validations: + required: true + - type: input + id: root-install-how + attributes: + label: Installation method + placeholder: Package manager (which?), pre-built binary, build from source, ... + validations: + required: true + - type: input + id: operating-system + attributes: + label: Operating system + placeholder: Windows, MacOS, Linux (which distribution?) + validations: + required: true + - type: textarea + id: additional-context + attributes: + label: Additional context + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000..9e8e53336dfbf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: ROOT forum + url: https://root-forum.cern.ch/ + about: Please ask and answer generic questions here. + - name: ROOT website + url: https://root.cern + about: Find installation instructions, documentation, tutorials here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 5cb0b1a00a0ad..0000000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: Feature request -about: Propose a new feature for ROOT -title: '' -labels: new feature ---- - -### Is your feature request related to a problem? Please describe. - - -### Describe the solution you'd like - - -### Describe alternatives you've considered - - -### Additional context - diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000000..cec39dff32452 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,27 @@ +name: Feature request +description: Propose a new feature for ROOT. +labels: ["new feature"] +body: + - type: markdown + attributes: + value: Thank you for taking the time to fill out this feature request! Note that since v6.28/06 you can also prefill this template using `root -q -e '.gh feature'` + - type: textarea + id: feature-description + attributes: + label: Feature description + description: What problem does the feature solve? How does the solution look like? + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives considered + description: Can you think of any alternative solutions to the proposed feature? + validations: + required: false + - type: textarea + id: additional-context + attributes: + label: Additional context + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/improvement_report.md b/.github/ISSUE_TEMPLATE/improvement_report.md deleted file mode 100644 index 747813e41c9b8..0000000000000 --- a/.github/ISSUE_TEMPLATE/improvement_report.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: Improvement -about: Suggest something that could be improved. -title: '' -labels: improvement ---- - -### Explain what you would like to see improved - - -### Optional: share how it could be improved - - -### To Reproduce - - -### Setup - - -### Additional context - diff --git a/.github/ISSUE_TEMPLATE/improvement_report.yml b/.github/ISSUE_TEMPLATE/improvement_report.yml new file mode 100644 index 0000000000000..340d60ee4a4b3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/improvement_report.yml @@ -0,0 +1,40 @@ +name: Improvement +description: Suggest something that could be improved. +labels: ["improvement"] +body: + - type: markdown + attributes: + value: Thank you for taking the time to fill out this improvement suggestion! Note that since v6.28/06 you can also prefill this template using `root -q -e '.gh improvement'` + - type: textarea + id: improvement-description + attributes: + label: Explain what you would like to see improved and how. + validations: + required: true + - type: textarea + id: root-version + attributes: + label: ROOT version + description: On Linux/MacOS, `root -b -q | xclip -sel clip`. On Windows, `root -b -q | clip.exe` + validations: + required: true + - type: input + id: root-install-how + attributes: + label: Installation method + placeholder: Package manager (which?), pre-built binary, build from source, ... + validations: + required: true + - type: input + id: operating-system + attributes: + label: Operating system + placeholder: Windows, MacOS, Linux (which distribution?) + validations: + required: true + - type: textarea + id: additional-context + attributes: + label: Additional context + validations: + required: false diff --git a/.github/workflows/all-branches.yml b/.github/workflows/all-branches.yml new file mode 100644 index 0000000000000..6c501dec9734e --- /dev/null +++ b/.github/workflows/all-branches.yml @@ -0,0 +1,24 @@ + +name: Trigger build on every branch + +on: + workflow_dispatch: + +jobs: + trigger_builds: + strategy: + fail-fast: false + matrix: + branch: ["master", "latest-stable", "v5-34-00-patches", "v6-18-00-patches","v6-20-00-patches", + "v6-22-00-patches","v6-24-00-patches", "v6-26-00-patches","v6-28-00-patches"] + + # stale branches: + # "v6-06-00-patches", "v6-08-00-patches", "v6-10-00-patches","v6-12-00-patches","v6-14-00-patches","v6-16-00-patches", + + + uses: ./.github/workflows/buildroot.yml + with: + base_ref: ${{ matrix.branch }} + head_ref: ${{ matrix.branch }} + incremental: true + secrets: inherit \ No newline at end of file diff --git a/.github/workflows/issues-nudge.yml b/.github/workflows/issues-nudge.yml index 937a0080284ba..234c580a24966 100644 --- a/.github/workflows/issues-nudge.yml +++ b/.github/workflows/issues-nudge.yml @@ -12,8 +12,8 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: '16' - - run: npm install octokit + node-version: '20' + - run: npm install 'octokit@^3' - run: node .github/actions/issues-nudge.js env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/llvm-diff.yml b/.github/workflows/llvm-diff.yml new file mode 100644 index 0000000000000..58f4460e323b7 --- /dev/null +++ b/.github/workflows/llvm-diff.yml @@ -0,0 +1,38 @@ +name: Diff LLVM and Clang against fork of monorepo +on: + pull_request: + paths: + - 'interpreter/llvm-project/**' + +jobs: + llvm-diff: + runs-on: ubuntu-latest + steps: + - name: Check out ROOT + uses: actions/checkout@v3 + with: + path: root + - name: Determine tag in fork of monorepo + id: determine-tag + run: | + tag_file=root/interpreter/llvm-project/llvm-project.tag + echo "tag=$(cat $tag_file)" >> $GITHUB_OUTPUT + rm $tag_file + - name: Check out llvm-project + uses: actions/checkout@v3 + with: + repository: root-project/llvm-project + ref: ${{ steps.determine-tag.outputs.tag }} + path: llvm-project + - name: Delete directories and files in llvm-project + working-directory: llvm-project + run: | + for d in bindings benchmark benchmarks gn test tests unittest unittests; do + find . -name $d -prune -exec rm -r "{}" \; + done + rm -r llvm/utils/vscode + for f in $(ls -A); do + [ -e ../root/interpreter/llvm-project/$f ] || rm -r $f + done + - name: Compare + run: diff -ur llvm-project/ root/interpreter/llvm-project/ diff --git a/.github/workflows/root-ci-config/build_root.py b/.github/workflows/root-ci-config/build_root.py new file mode 100755 index 0000000000000..2c1ab1c0e3098 --- /dev/null +++ b/.github/workflows/root-ci-config/build_root.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 + +# pylint: disable=broad-except,missing-function-docstring,line-too-long + +"""This mainly functions as a shell script, but python is used for its + superior control flow. An important requirement of the CI is easily + reproducible builds, therefore a wrapper is made for running shell + commands so that they are also logged. + + The log is printed when build fails/succeeds and needs to perfectly + reproduce the build when pasted into a shell. Therefore all file system + modifying code not executed from shell needs a shell equivalent + explicitly appended to the shell log. + e.g. `os.chdir(x)` requires `cd x` to be appended to the shell log """ + +import argparse +import datetime +import os +import shutil +import subprocess +import tarfile +from hashlib import sha1 + +import openstack + +from build_utils import ( + die, + github_log_group, + load_config, + subprocess_with_log, + upload_file +) +import build_utils + +S3CONTAINER = 'ROOT-build-artifacts' # Used for uploads +S3URL = 'https://s3.cern.ch/swift/v1/' + S3CONTAINER # Used for downloads + +try: + CONNECTION = openstack.connect(cloud='envvars') +except: + CONNECTION = None + +WINDOWS = (os.name == 'nt') +WORKDIR = (os.environ['HOME'] + '/ROOT-CI') if not WINDOWS else 'C:/ROOT-CI' +COMPRESSIONLEVEL = 6 if not WINDOWS else 1 + + +def main(): + # openstack.enable_logging(debug=True) + + # used when uploading artifacts, calculate early since build times are inconsistent + yyyy_mm_dd = datetime.datetime.today().strftime('%Y-%m-%d') + + args = parse_args() + + build_utils.log = build_utils.Tracer(args.image, args.dockeropts) + + pull_request = args.head_ref and args.head_ref != args.base_ref + + if not pull_request: + build_utils.print_info("head_ref same as base_ref, assuming non-PR build") + + cleanup_previous_build() + + # Load CMake options from .github/workflows/root-ci-config/buildconfig/[platform].txt + this_script_dir = os.path.dirname(os.path.abspath(__file__)) + + options_dict = { + **load_config(f'{this_script_dir}/buildconfig/global.txt'), + # file below overwrites values from above + **load_config(f'{this_script_dir}/buildconfig/{args.platform}.txt') + } + + if args.binaries: + options_dict = remove_gpl_options(options_dict) + + options = build_utils.cmake_options_from_dict(options_dict) + + if WINDOWS: + options = "-Thost=x64 " + options + + if args.architecture == 'x86': + options = "-AWin32 " + options + + # The sha1 of the build option string is used to find existing artifacts + # with matching build options on s3 storage. + option_hash = sha1(options.encode('utf-8')).hexdigest() + obj_prefix = f'{args.platform}/{args.base_ref}/{args.buildtype}/{option_hash}' + + # Make testing of CI in forks not impact artifacts + if 'root-project/root' not in args.repository: + obj_prefix = f"ci-testing/{args.repository.split('/')[-2]}/" + obj_prefix + print("Attempting to download") + + if args.incremental: + try: + download_artifacts(obj_prefix) + except Exception as err: + build_utils.print_warning(f'Failed to download: {err}') + args.incremental = False + + git_pull(args.repository, args.base_ref) + + if pull_request: + rebase(args.base_ref, args.head_ref) + + if not WINDOWS: + show_node_state() + + build(options, args.buildtype) + + # Build artifacts should only be uploaded for full builds, and only for + # "official" branches (master, v?-??-??-patches), i.e. not for pull_request + # We also want to upload any successful build, even if it fails testing + # later on. + if not pull_request and not args.incremental and not args.coverage: + archive_and_upload(yyyy_mm_dd, obj_prefix) + + if args.binaries: + create_binaries(args.buildtype) + + testing: bool = options_dict['testing'].lower() == "on" and options_dict['roottest'].lower() == "on" + + if testing: + extra_ctest_flags = "" + if WINDOWS: + extra_ctest_flags += "--repeat until-pass:3 " + extra_ctest_flags += "--build-config " + args.buildtype + + ctest_returncode = run_ctest(extra_ctest_flags) + + if args.coverage: + create_coverage_xml() + + if testing and ctest_returncode != 0: + handle_test_failure(ctest_returncode) + + print_trace() + +def handle_test_failure(ctest_returncode): + logloc = f'{WORKDIR}/build/Testing/Temporary/LastTestsFailed.log' + if os.path.isfile(logloc): + with open(logloc, 'r') as logf: + print("TEST FAILURES:") + print(logf.read()) + else: + print(f'Internal error: cannot find {logloc}\nAdding some debug output:') + subprocess.run(f'ls -l {WORKDIR}/build', shell=True, check=False, stderr=subprocess.STDOUT) + subprocess.run(f'ls -l {WORKDIR}/build/Testing', shell=True, check=False, stderr=subprocess.STDOUT) + subprocess.run(f'ls -l {WORKDIR}/build/Testing/Temporary', shell=True, check=False, stderr=subprocess.STDOUT) + + die(msg=f"TEST FAILURE: ctest exited with code {ctest_returncode}") + + +def parse_args(): + # it is difficult to use boolean flags from github actions, use strings to convey + # true/false for boolean arguments instead. + parser = argparse.ArgumentParser() + parser.add_argument("--platform", help="Platform to build on") + parser.add_argument("--image", default=None, help="Container image, if any") + parser.add_argument("--dockeropts", default=None, help="Extra docker options, if any") + parser.add_argument("--incremental", default="false", help="Do incremental build") + parser.add_argument("--buildtype", default="Release", help="Release|Debug|RelWithDebInfo") + parser.add_argument("--coverage", default="false", help="Create Coverage report in XML") + parser.add_argument("--base_ref", default=None, help="Ref to target branch") + parser.add_argument("--head_ref", default=None, help="Ref to feature branch; it may contain a : part") + parser.add_argument("--binaries", default="false", help="Whether to create binary artifacts") + parser.add_argument("--architecture", default=None, help="Windows only, target arch") + parser.add_argument("--repository", default="https://github.com/root-project/root.git", + help="url to repository") + + args = parser.parse_args() + + # Set argument to True if matched + args.incremental = args.incremental.lower() in ('yes', 'true', '1', 'on') + args.coverage = args.coverage.lower() in ('yes', 'true', '1', 'on') + args.binaries = args.binaries.lower() in ('yes', 'true', '1', 'on') + + if not args.base_ref: + die(os.EX_USAGE, "base_ref not specified") + + return args + + +def print_trace(): + build_utils.log.print() + +def remove_gpl_options(options_dict: dict): + gpl_options = ['fftw3', 'mathmore', 'pythia6', 'pythia8', 'unuran'] + for opt in gpl_options: + options_dict[opt] = 'off' + return options_dict + + +@github_log_group("Clean up from previous runs") +def cleanup_previous_build(): + # runners should never have root permissions but be on the safe side + if WORKDIR in ("", "/"): + die(1, "WORKDIR not set") + + if WINDOWS: + # windows + os.environ['COMSPEC'] = 'powershell.exe' + result = subprocess_with_log(f""" + $ErrorActionPreference = 'Stop' + if (Test-Path {WORKDIR}) {{ + Remove-Item -Recurse -Force -Path {WORKDIR} + }} + New-Item -Force -Type directory -Path {WORKDIR} + """) + else: + # mac/linux/POSIX + result = subprocess_with_log(f""" + rm -rf {WORKDIR} + mkdir -p {WORKDIR} + """) + + if result != 0: + die(result, "Failed to clean up previous artifacts") + + +@github_log_group("Pull/clone branch") +def git_pull(repository: str, branch: str): + returncode = 1 + + for _ in range(5): + if returncode == 0: + break + + if os.path.exists(f"{WORKDIR}/src/.git"): + returncode = subprocess_with_log(f""" + cd '{WORKDIR}/src' + git checkout {branch} + git fetch + git reset --hard @{{u}} + """) + else: + returncode = subprocess_with_log(f""" + git clone --branch {branch} --single-branch {repository} "{WORKDIR}/src" + """) + + if returncode != 0: + die(returncode, f"Failed to pull {branch}") + + +@github_log_group("Download previous build artifacts") +def download_artifacts(obj_prefix: str): + try: + tar_path = build_utils.download_latest(S3URL, obj_prefix, WORKDIR) + + print(f"\nExtracting archive {tar_path}") + + with tarfile.open(tar_path) as tar: + tar.extractall(WORKDIR) + + build_utils.log.add(f'\ncd {WORKDIR} && tar -xf {tar_path}\n') + + except Exception as err: + build_utils.print_warning("failed to download/extract:", err) + shutil.rmtree(f'{WORKDIR}/src', ignore_errors=True) + shutil.rmtree(f'{WORKDIR}/build', ignore_errors=True) + raise err + + +@github_log_group("Node state") +def show_node_state() -> None: + result = subprocess_with_log(""" + which cmake + cmake --version + which c++ || true + c++ --version || true + uname -a || true + cat /etc/os-release || true + sw_vers || true + uptime || true + df || true + """) + + if result != 0: + build_utils.print_warning("Failed to extract node state") + +# Just return the exit code in case of test failures instead of `die()`-ing; report test +# failures in main(). +@github_log_group("Run tests") +def run_ctest(extra_ctest_flags: str) -> int: + ctest_result = subprocess_with_log(f""" + cd '{WORKDIR}/build' + ctest --output-on-failure --parallel {os.cpu_count()} --output-junit TestResults.xml {extra_ctest_flags} + """) + + return ctest_result + + +@github_log_group("Archive and upload") +def archive_and_upload(archive_name, prefix): + new_archive = f"{archive_name}.tar.gz" + + os.chdir(WORKDIR) + + with tarfile.open(f"{WORKDIR}/{new_archive}", "x:gz", compresslevel=COMPRESSIONLEVEL) as targz: + targz.add("src") + targz.add("build") + + upload_file( + connection=CONNECTION, + container=S3CONTAINER, + dest_object=f"{prefix}/{new_archive}", + src_file=f"{WORKDIR}/{new_archive}" + ) + + +@github_log_group("Configure") +def cmake_configure(options, buildtype): + result = subprocess_with_log(f""" + cmake -S '{WORKDIR}/src' -B '{WORKDIR}/build' {options} -DCMAKE_BUILD_TYPE={buildtype} + """) + + if result != 0: + die(result, "Failed cmake generation step") + + +@github_log_group("Dump existing configuration") +def cmake_dump_config(): + # Print CMake cached config + result = subprocess_with_log(f""" + cmake -S '{WORKDIR}/src' -B '{WORKDIR}/build' -N -L + """) + + if result != 0: + die(result, "Failed cmake cache print step") + + +@github_log_group("Dump requested build configuration") +def dump_requested_config(options): + print(f"\nBUILD OPTIONS: {options}") + + +@github_log_group("Build") +def cmake_build(buildtype): + generator_flags = "-- '-verbosity:minimal'" if WINDOWS else "" + + result = subprocess_with_log(f""" + cmake --build '{WORKDIR}/build' --config '{buildtype}' --parallel '{os.cpu_count()}' {generator_flags} + """) + + if result != 0: + die(result, "Failed to build") + + +def build(options, buildtype): + if not os.path.isdir(f'{WORKDIR}/build'): + result = subprocess_with_log(f"mkdir {WORKDIR}/build") + + if result != 0: + die(result, "Failed to create build directory") + + if not os.path.exists(f'{WORKDIR}/build/CMakeCache.txt'): + cmake_configure(options, buildtype) + else: + cmake_dump_config() + + dump_requested_config(options) + + cmake_build(buildtype) + + +@github_log_group("Create binary packages") +def create_binaries(buildtype): + os.makedirs(f"{WORKDIR}/packages/", exist_ok=True) + result = subprocess_with_log(f""" + cd '{WORKDIR}/build' && cpack -B {WORKDIR}/packages/ --verbose -C {buildtype} + """) + + if result != 0: + die(result, "Failed to generate binary package") + + +@github_log_group("Rebase") +def rebase(base_ref, head_ref) -> None: + head_ref_src, _, head_ref_dst = head_ref.partition(":") + head_ref_dst = head_ref_dst or "__tmp" + # rebase fails unless user.email and user.name is set + result = subprocess_with_log(f""" + cd '{WORKDIR}/src' + + git config user.email "rootci@root.cern" + git config user.name 'ROOT Continous Integration' + + git fetch origin {head_ref_src}:{head_ref_dst} + git checkout {head_ref_dst} + git rebase {base_ref} + """) + + if result != 0: + die(result, "Rebase failed") + + +@github_log_group("Create Test Coverage in XML") +def create_coverage_xml() -> None: + result = subprocess_with_log(f""" + cd '{WORKDIR}/build' + gcovr --output=cobertura-cov.xml --cobertura-pretty --gcov-ignore-errors=no_working_dir_found --merge-mode-functions=merge-use-line-min --exclude-unreachable-branches --exclude-directories="roottest|runtutorials|interpreter" --exclude='.*/G__.*' --exclude='.*/(roottest|runtutorials|externals|ginclude|googletest-prefix|macosx|winnt|geombuilder|cocoa|quartz|win32gdk|x11|x11ttf|eve|fitpanel|ged|gui|guibuilder|guihtml|qtgsi|qtroot|recorder|sessionviewer|tmvagui|treeviewer|geocad|fitsio|gviz|qt|gviz3d|x3d|spectrum|spectrumpainter|dcache|hdfs|foam|genetic|mlp|quadp|splot|memstat|rpdutils|proof|odbc|llvm|test|interpreter)/.*' --gcov-exclude='.*_ACLiC_dict[.].*' '--exclude=.*_ACLiC_dict[.].*' -v -r ../src ../build + """) + + if result != 0: + die(result, "Failed to create test coverage") + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/root-ci-config/build_utils.py b/.github/workflows/root-ci-config/build_utils.py new file mode 100755 index 0000000000000..80fc60e4b0ef1 --- /dev/null +++ b/.github/workflows/root-ci-config/build_utils.py @@ -0,0 +1,224 @@ +#!/usr/bin/env false + +import json +import os +import subprocess +import sys +import textwrap +from functools import wraps +from http import HTTPStatus +from typing import Callable, Dict + +from openstack.connection import Connection +from requests import get + + +def github_log_group(title: str): + """ decorator that places function's stdout/stderr output in a + dropdown group when running on github workflows """ + def group(func: Callable): + @wraps(func) + def wrapper(*args, **kwargs): + print(f"\n::group::{title}\n") + + try: + result = func(*args, **kwargs) + except Exception as exc: + print("\n::endgroup::\n") + raise exc + + print("\n::endgroup::\n") + + return result + + return wrapper if os.getenv("GITHUB_ACTIONS") else func + + return group + + +class Tracer: + """ + Trace command invocations and print them to reproduce builds. + """ + + image = "" + docker_opts = [] + trace = "" + + def __init__(self, image: str, docker_opts: str): + self.image = image + if docker_opts: + self.docker_opts = docker_opts.split(' ') + if '--rm' in self.docker_opts: + self.docker_opts.remove('--rm') + + def add(self, command: str) -> None: + self.trace += '\n(\n' + textwrap.dedent(command.strip()) + '\n)' + + @github_log_group("To replicate this build locally") + def print(self) -> None: + if self.trace != "": + if self.image: + print(f"""\ +Grab the image: +$ docker run {' '.join(self.docker_opts)} -it {self.image} +Then: +""") + print(self.trace) + + +log = Tracer("", "") + + +def print_fancy(*values, sgr=1, **kwargs) -> None: + """prints message using select graphic rendition, defaults to bold text + https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters""" + + print(f"\033[{sgr}m", end='', **kwargs) + print(*values, end='', **kwargs) + print("\033[0m", **kwargs) + + +def print_info(*values, **kwargs): + print_fancy("Info: ", *values, sgr=90, **kwargs) + + +def print_warning(*values, **kwargs): + print_fancy("Warning: ", *values, sgr=33, **kwargs) + + +def print_error(*values, **kwargs): + print_fancy("Fatal error: ", *values, sgr=31, **kwargs) + + +def subprocess_with_log(command: str) -> int: + """Runs in shell and appends to log""" + + print_fancy(textwrap.dedent(command), sgr=1) + + print("\033[90m", end='') + + if os.name == 'nt': + command = "$env:comspec = 'cmd.exe'; " + command + + result = subprocess.run(command, shell=True, check=False, stderr=subprocess.STDOUT) + + print("\033[0m", end='') + + log.add(command) + + return result.returncode + + +def die(code: int = 1, msg: str = "") -> None: + log.print() + + print_error(f"({code}) {msg}") + + sys.exit(code) + + +def load_config(filename) -> dict: + """Loads cmake options from a file to a dictionary""" + + options = {} + + try: + file = open(filename, 'r', encoding='utf-8') + except OSError as err: + print_warning(f"couldn't load {filename}: {err.strerror}") + return {} + + with file: + for line in file: + if '=' not in line: + continue + + key, val = line.rstrip().split('=') + + if val.lower() in ["on", "off"]: + val = val.lower() + + options[key] = val + + return options + + +def cmake_options_from_dict(config: Dict[str, str]) -> str: + """Converts a dictionary of build options to string. + The output is sorted alphanumerically. + + example: {"builtin_xrootd"="on", "alien"="on"} + -> + '"-Dalien=on" -Dbuiltin_xrootd=on"' + """ + + if not config: + return '' + + output = [] + + for key, value in config.items(): + output.append(f'"-D{key}={value}"') + + output.sort() + + return ' '.join(output) + + +def upload_file(connection: Connection, container: str, dest_object: str, src_file: str) -> None: + print(f"Attempting to upload {src_file} to {dest_object}") + + if not os.path.exists(src_file): + raise Exception(f"No such file: {src_file}") + + gigabyte = 1024**3 + week_in_seconds = 60*60*24*7 + + connection.create_object( + container=container, + name=dest_object, + filename=src_file, + segment_size=5*gigabyte, + **{ + 'X-Delete-After': str(2*week_in_seconds) + } + ) + + print(f"Successfully uploaded to {dest_object}") + + +def download_file(url: str, dest: str) -> None: + print(f"\nAttempting to download {url} to {dest}") + + parent_dir = os.path.dirname(dest) + + if not os.path.exists(parent_dir): + os.makedirs(parent_dir) + + with open(dest, 'wb') as fout, get(url, timeout=300) as req: + fout.write(req.content) + + +def download_latest(url: str, prefix: str, destination: str) -> str: + """Downloads latest build artifact starting with , + and returns the file path to the downloaded file and shell_log.""" + + # https://docs.openstack.org/api-ref/object-store/#show-container-details-and-list-objects + with get(f"{url}/?prefix={prefix}&format=json", timeout=20) as req: + if req.status_code == HTTPStatus.NO_CONTENT or req.content == b'[]': + raise Exception(f"No object found with prefix: {prefix}") + + result = json.loads(req.content) + artifacts = [x['name'] for x in result if 'content_type' in x] + + latest = max(artifacts) + + download_file(f"{url}/{latest}", f"{destination}/artifacts.tar.gz") + + if os.name == 'nt': + log.add(f"\nInvoke-WebRequest {url}/{latest} -OutFile {destination}\\artifacts.tar.gz") + else: + log.add(f"\ncurl --output {destination}/artifacts.tar.gz {url}/{latest}\n") + + return f"{destination}/artifacts.tar.gz" diff --git a/.github/workflows/root-ci-config/buildconfig/fedora37.txt b/.github/workflows/root-ci-config/buildconfig/fedora37.txt new file mode 100644 index 0000000000000..55f9c219429dd --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/fedora37.txt @@ -0,0 +1,3 @@ +tmva-pymva=Off +test_distrdf_pyspark=OFF +CMAKE_CXX_STANDARD=17 diff --git a/.github/workflows/root-ci-config/buildconfig/fedora38.txt b/.github/workflows/root-ci-config/buildconfig/fedora38.txt new file mode 100644 index 0000000000000..6f8fff1aa7fe9 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/fedora38.txt @@ -0,0 +1,4 @@ +tmva-pymva=Off +test_distrdf_pyspark=OFF +pythia8=Off +CMAKE_CXX_STANDARD=20 diff --git a/.github/workflows/root-ci-config/buildconfig/fedora39.txt b/.github/workflows/root-ci-config/buildconfig/fedora39.txt new file mode 100644 index 0000000000000..28ca1cdb1fd10 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/fedora39.txt @@ -0,0 +1,3 @@ +tmva-pymva=Off +pythia8=Off +CMAKE_CXX_STANDARD=20 diff --git a/.github/workflows/root-ci-config/buildconfig/global.txt b/.github/workflows/root-ci-config/buildconfig/global.txt new file mode 100644 index 0000000000000..7e0af4410e4a0 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/global.txt @@ -0,0 +1,124 @@ +LLVM_ENABLE_ASSERTIONS=On +alien=OFF +all=OFF +arrow=OFF +asan=OFF +asimage=ON +asserts=OFF +builtin_afterimage=OFF +builtin_cfitsio=OFF +builtin_clang=ON +builtin_cling=ON +builtin_cppzmq=OFF +builtin_davix=OFF +builtin_fftw3=OFF +builtin_freetype=OFF +builtin_ftgl=OFF +builtin_gl2ps=OFF +builtin_glew=OFF +builtin_gsl=OFF +builtin_llvm=ON +builtin_lz4=OFF +builtin_lzma=OFF +builtin_nlohmannjson=OFF +builtin_openssl=OFF +builtin_openui5=ON +builtin_pcre=OFF +builtin_tbb=OFF +builtin_unuran=OFF +builtin_vc=OFF +builtin_vdt=OFF +builtin_veccore=OFF +builtin_xrootd=OFF +builtin_xxhash=OFF +builtin_zeromq=OFF +builtin_zlib=OFF +builtin_zstd=OFF +ccache=OFF +cefweb=OFF +clad=ON +clingtest=OFF +cocoa=OFF +coverage=OFF +cuda=OFF +cudnn=ON +cxxmodules=OFF +daos=OFF +dataframe=ON +davix=ON +dcache=OFF +dev=OFF +distcc=OFF +exceptions=ON +fcgi=OFF +fftw3=ON +fitsio=ON +fortran=OFF +gdml=ON +gfal=ON +gminimal=OFF +gnuinstall=OFF +gsl_shared=OFF +gviz=OFF +http=ON +imt=ON +jemalloc=OFF +libcxx=OFF +macos_native=OFF +mathmore=ON +memory_termination=OFF +minimal=OFF +minuit2=ON +mlp=ON +monalisa=OFF +mpi=OFF +mysql=ON +odbc=OFF +opengl=ON +oracle=ON +pgsql=ON +pyroot=ON +pyroot_legacy=OFF +pythia6=ON +pythia6_nolink=OFF +pythia8=ON +qt5web=OFF +qt6web=OFF +r=OFF +roofit=ON +roofit_multiprocess=OFF +root7=ON +rootbench=OFF +roottest=ON +roottest_force_checkout=ON +rpath=ON +runtime_cxxmodules=ON +shadowpw=OFF +shared=ON +soversion=OFF +spectrum=ON +sqlite=ON +ssl=ON +tcmalloc=OFF +test_distrdf_dask=ON +test_distrdf_pyspark=ON +testing=ON +tmva-cpu=ON +tmva-gpu=OFF +tmva-pymva=ON +tmva-rmva=OFF +tmva-sofie=OFF +tmva=ON +unuran=OFF +uring=OFF +vc=OFF +vdt=ON +veccore=OFF +vecgeom=OFF +webgui=ON +win_broken_tests=OFF +winrtdebug=OFF +x11=ON +xml=ON +xproofd=OFF +xrootd=ON diff --git a/.github/workflows/root-ci-config/buildconfig/mac14.txt b/.github/workflows/root-ci-config/buildconfig/mac14.txt new file mode 100644 index 0000000000000..c2c67e829dbd3 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/mac14.txt @@ -0,0 +1,33 @@ +CMAKE_CXX_STANDARD=20 +builtin_afterimage=ON +builtin_cfitsio=ON +builtin_cppzmq=ON +builtin_davix=ON +builtin_fftw3=ON +builtin_freetype=ON +builtin_ftgl=ON +builtin_gl2ps=ON +builtin_glew=ON +builtin_gsl=ON +builtin_lz4=ON +builtin_nlohmannjson=ON +builtin_tbb=ON +builtin_unuran=ON +builtin_vc=ON +builtin_vdt=ON +builtin_veccore=ON +builtin_xrootd=ON +builtin_xxhash=ON +builtin_zeromq=ON +builtin_zstd=ON +cocoa=ON +cudnn=OFF +mysql=OFF +oracle=OFF +pgsql=OFF +pythia6=OFF +pythia8=OFF +test_distrdf_dask=OFF +test_distrdf_pyspark=OFF +tmva-cpu=OFF +x11=OFF diff --git a/.github/workflows/root-ci-config/buildconfig/ubuntu18.txt b/.github/workflows/root-ci-config/buildconfig/ubuntu18.txt new file mode 100644 index 0000000000000..9808d4c4e31ae --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/ubuntu18.txt @@ -0,0 +1,2 @@ +CMAKE_CXX_STANDARD=17 +root7=OFF \ No newline at end of file diff --git a/.github/workflows/root-ci-config/buildconfig/ubuntu20.txt b/.github/workflows/root-ci-config/buildconfig/ubuntu20.txt new file mode 100644 index 0000000000000..02c74c21838cc --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/ubuntu20.txt @@ -0,0 +1 @@ +CMAKE_CXX_STANDARD=17 \ No newline at end of file diff --git a/.github/workflows/root-ci-config/buildconfig/windows.txt b/.github/workflows/root-ci-config/buildconfig/windows.txt new file mode 100644 index 0000000000000..aa0edc59d2099 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/windows.txt @@ -0,0 +1,3 @@ +CMAKE_CXX_STANDARD=17 +win_broken_tests=OFF +winrtdebug=OFF diff --git a/.github/workflows/root-ci-config/buildconfig/windows10.txt b/.github/workflows/root-ci-config/buildconfig/windows10.txt new file mode 100644 index 0000000000000..66b0671eefbe4 --- /dev/null +++ b/.github/workflows/root-ci-config/buildconfig/windows10.txt @@ -0,0 +1,42 @@ +CMAKE_CXX_STANDARD=17 +builtin_afterimage=ON +builtin_cfitsio=ON +builtin_freetype=ON +builtin_ftgl=ON +builtin_gl2ps=ON +builtin_glew=ON +builtin_gtest=ON +builtin_lz4=ON +builtin_lzma=ON +builtin_nlohmannjson=ON +builtin_pcre=ON +builtin_tbb=ON +builtin_unuran=ON +builtin_xxhash=ON +builtin_zlib=ON +builtin_zstd=ON +cudnn=OFF +davix=OFF +exceptions=ON +gfal=OFF +llvm13_broken_tests=OFF +minuit2_mpi=OFF +minuit2_omp=OFF +mysql=OFF +odbc=ON +oracle=OFF +pgsql=OFF +pyroot2=OFF +pyroot3=ON +pythia6=OFF +pythia8=OFF +runtime_cxxmodules=OFF +sqlite=OFF +ssl=OFF +test_distrdf_dask=OFF +test_distrdf_pyspark=OFF +unuran=ON +vdt=OFF +x11=OFF +xml=OFF +xrootd=OFF diff --git a/.github/workflows/root-ci.yml b/.github/workflows/root-ci.yml new file mode 100644 index 0000000000000..e3f904dcf7442 --- /dev/null +++ b/.github/workflows/root-ci.yml @@ -0,0 +1,455 @@ + +name: 'ROOT CI' + +on: + schedule: + - cron: '0 1 * * *' + + # https://github.com/root-project/root/pull/12112#issuecomment-1411004278 + pull_request: + branches: + - '**' + paths-ignore: + - 'doc/**' + - 'documentation/**' + + push: + branches: + - 'master' + - 'v*-*-*-patches' + + # Allows nightly builds to trigger one run for each branch easily + workflow_call: + inputs: + head_ref: + type: string + required: true + default: master + base_ref: + type: string + required: true + default: master + incremental: + type: boolean + required: true + default: false + binaries: + type: boolean + required: true + default: true + + # Enables manual start of workflow + workflow_dispatch: + inputs: + head_ref: + description: rebase from ... + type: string + required: true + default: master + base_ref: + description: ... to ... (can have same value) + type: string + required: true + default: master + incremental: + description: 'Do incremental build' + type: boolean + required: true + default: true + binaries: + type: boolean + required: true + default: false + +env: + PYTHONUNBUFFERED: true + OS_APPLICATION_CREDENTIAL_ID: '7f5b64a265244623a3a933308569bdba' + OS_APPLICATION_CREDENTIAL_SECRET: ${{ secrets.OS_APPLICATION_CREDENTIAL_SECRET }} + OS_AUTH_TYPE: 'v3applicationcredential' + OS_AUTH_URL: 'https://keystone.cern.ch/v3' + OS_IDENTITY_API_VERSION: 3 + OS_INTERFACE: 'public' + OS_REGION_NAME: 'cern' + +jobs: + build-macos: + if: github.repository_owner == 'root-project' || github.event_name == 'pull_request' + + permissions: + contents: read + + strategy: + fail-fast: false + matrix: + include: + - platform: mac14 + arch: ARM64 + config: Release + + name: ${{ matrix.platform }} ${{ matrix.arch }} ${{ matrix.config }} + + runs-on: # Using '[self-hosted, ..., ...]' does not work for some reason :) + - self-hosted + - macOS + - ${{ matrix.arch }} + - ${{ matrix.platform }} + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Pull Request Build + if: github.event_name == 'pull_request' + env: + INCREMENTAL: ${{ !contains(github.event.pull_request.labels.*.name, 'clean build') }} + GITHUB_PR_ORIGIN: ${{ github.event.pull_request.head.repo.clone_url }} + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.platform }} + --incremental $INCREMENTAL + --base_ref ${{ github.base_ref }} + --head_ref refs/pull/${{ github.event.pull_request.number }}/head:${{ github.event.pull_request.head.ref }} + --repository ${{ github.server_url }}/${{ github.repository }}" + + - name: Workflow dispatch + if: github.event_name == 'workflow_dispatch' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.platform }} + --incremental ${{ inputs.incremental }} + --base_ref ${{ inputs.base_ref }} + --head_ref ${{ inputs.head_ref }} + --binaries ${{ inputs.binaries }} + --repository ${{ github.server_url }}/${{ github.repository }}" + + - name: Nightly build + if: github.event_name == 'schedule' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.platform }} + --incremental false + --binaries true + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }}" + + - name: Update artifacts after push to release branch + if: github.event_name == 'push' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.platform }} + --incremental false + --base_ref ${{ github.ref_name }} + --binaries ${{ startsWith(github.ref, 'refs/tags/') }} + --repository ${{ github.server_url }}/${{ github.repository }}" + + - name: Upload test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: Test Results ${{ matrix.platform }} ${{ matrix.arch }} ${{ matrix.config }} + path: /Users/sftnight/ROOT-CI/build/TestResults.xml + + - name: Upload build artifacts + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: Test Results ${{ matrix.platform }} ${{ matrix.arch }} ${{ matrix.config }} + path: /Users/sftnight/ROOT-CI/build/TestResults.xml + + - name: Upload binaries + if: ${{ !cancelled() && (inputs.binaries || github.event_name == 'schedule' || startsWith(github.ref, 'refs/tags/')) }} + uses: actions/upload-artifact@v3 + with: + name: Binaries ${{ matrix.platform }} ${{ matrix.arch }} ${{ matrix.config }} + path: /Users/sftnight/ROOT-CI/packages/root_v* + if-no-files-found: error + + + build-windows: + if: github.repository_owner == 'root-project' || github.event_name == 'pull_request' + + permissions: + contents: read + + strategy: + fail-fast: false + matrix: + # We have to get a bit creative here: GitHub actions only allows to + # exclude partial matches, so we artificially add the event_name as + # a "constant variable" that we can use to remove the Debug entries + # for pull requests and on branch pushes. This is further complicated + # by the fact that event_name is a string, but we need an array. So + # we construct a JSON string that we can then convert into an array. + event_name: ${{ fromJSON(format('["{0}"]', github.event_name)) }} + config: ["Debug", "Release"] + target_arch: [x64, x86] + exclude: + - event_name: pull_request + config: Debug + - event_name: push + config: Debug + + name: Windows 10 ${{ matrix.target_arch }} ${{ matrix.config }} + + runs-on: # Using '[self-hosted, windows, ${{ matrix.arch }}]' does not work for some reason :) + - self-hosted + - windows + - x64 # machine host, not build target + - target${{ matrix.target_arch }} + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Pull Request Build + if: github.event_name == 'pull_request' + env: + INCREMENTAL: ${{ !contains(github.event.pull_request.labels.*.name, 'clean build') }} + GITHUB_PR_ORIGIN: ${{ github.event.pull_request.head.repo.clone_url }} + shell: cmd + run: "C:\\setenv.bat ${{ matrix.target_arch }} && + python .github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform windows10 + --incremental $INCREMENTAL + --base_ref ${{ github.base_ref }} + --head_ref refs/pull/${{ github.event.pull_request.number }}/head:${{ github.event.pull_request.head.ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + --architecture ${{ matrix.target_arch }} " + + - name: Workflow dispatch/call + if: github.event_name == 'workflow_dispatch' + shell: cmd + run: "C:\\setenv.bat ${{ matrix.target_arch }} && + python .github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform windows10 + --incremental ${{ inputs.incremental }} + --base_ref ${{ inputs.base_ref }} + --head_ref ${{ inputs.head_ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + --architecture ${{ matrix.target_arch }} " + + - name: Nightly build + if: github.event_name == 'schedule' + shell: cmd + run: "C:\\setenv.bat ${{ matrix.target_arch }} && + python .github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform windows10 + --incremental false + --binaries true + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }} + --architecture ${{ matrix.target_arch }} " + + - name: Update artifacts after push to release branch + if: github.event_name == 'push' + shell: cmd + run: "C:\\setenv.bat ${{ matrix.target_arch }} && + python .github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform windows10 + --incremental false + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }} + --architecture ${{ matrix.target_arch }} " + + - name: Upload test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: Test Results Windows ${{ matrix.target_arch }} ${{ matrix.config }} + path: C:/ROOT-CI/build/TestResults.xml + + - name: Upload binaries + if: ${{ !cancelled() && (inputs.binaries || github.event_name == 'schedule' || startsWith(github.ref, 'refs/tags/')) }} + uses: actions/upload-artifact@v3 + with: + name: Binaries ${{ matrix.target_arch }} ${{ matrix.config }} + path: C:/ROOT-CI/packages/root_v* + if-no-files-found: error + + + build-linux: + if: github.repository_owner == 'root-project' || github.event_name == 'pull_request' + + permissions: + contents: read + + strategy: + fail-fast: false + matrix: + # Specify image + config + (optional) build option overrides + # + # Available images: https://github.com/root-project/root-ci-images + # Common configs: {Release,Debug,RelWithDebInfo) + # Build options: https://root.cern/install/build_from_source/#all-build-options + include: + - image: fedora39 + config: Release + + - image: fedora38 + config: Debug + + - image: fedora37 + config: Debug + + - image: alma8 + config: Release + + - image: alma9 + config: Release + + - image: ubuntu20 + config: Release + + - image: ubuntu2304 + config: Release + + - image: ubuntu22 + config: Debug + overrides: ["imt=Off"] + + runs-on: + - self-hosted + - linux + - x64 + + name: ${{ matrix.image }} ${{ matrix.config }} ${{ join( matrix.overrides, ', ' ) }} + + container: + image: registry.cern.ch/root-ci/${{ matrix.image }}:buildready # ALSO UPDATE BELOW! + options: '--shm-size=1g -m 16g --security-opt label=disable --rm' # ALSO UPDATE BELOW! + env: + OS_APPLICATION_CREDENTIAL_ID: '7f5b64a265244623a3a933308569bdba' + OS_APPLICATION_CREDENTIAL_SECRET: ${{ secrets.OS_APPLICATION_CREDENTIAL_SECRET }} + OS_AUTH_TYPE: 'v3applicationcredential' + OS_AUTH_URL: 'https://keystone.cern.ch/v3' + OS_IDENTITY_API_VERSION: 3 + OS_INTERFACE: 'public' + OS_REGION_NAME: 'cern' + PYTHONUNBUFFERED: true + + steps: + - name: Set up Python Virtual Env + # if the `if` expr is false, `if` still has exit code 0. + # if the `if` block is entered, the block's exit code becomes the exit + # code of the `if`. + run: 'if [ -d /py-venv/ROOT-CI/bin/ ]; then . /py-venv/ROOT-CI/bin/activate && echo PATH=$PATH >> $GITHUB_ENV; fi' + + - name: Checkout + uses: actions/checkout@v3 + + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJSON(github) }} + run: echo "$GITHUB_CONTEXT" + + - name: Print debug info + run: 'printf "%s@%s\\n" "$(whoami)" "$(hostname)"; + ls -la + ' + + - name: Apply option overrides from matrix for this job + if: ${{ matrix.overrides != NaN }} + env: + OVERRIDES: ${{ join( matrix.overrides, ' ') }} + CONFIGFILE: '.github/workflows/root-ci-config/buildconfig/${{ matrix.image }}.txt' + shell: bash + run: | + set -x + + echo '' >> "$CONFIGFILE" + + for ENTRY in $OVERRIDES; do + KEY=$( echo "$ENTRY" | cut -d '=' -f 1 ) + + # Add entry to file if not exists, otherwise replace + + if grep -q "$KEY=" "$CONFIGFILE"; then + sed -i "s/$KEY=.*\$/$ENTRY/" "$CONFIGFILE" + else + echo "$ENTRY" >> "$CONFIGFILE" + fi + done + + cat "$CONFIGFILE" || true + + - uses: root-project/gcc-problem-matcher-improved@main + with: + build-directory: /github/home/ROOT-CI/src/ + + - name: Pull Request Build + if: github.event_name == 'pull_request' + env: + INCREMENTAL: ${{ !contains(github.event.pull_request.labels.*.name, 'clean build') }} + GITHUB_PR_ORIGIN: ${{ github.event.pull_request.head.repo.clone_url }} + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.image }} + --image registry.cern.ch/root-ci/${{ matrix.image }}:buildready + --dockeropts '--shm-size=1g -m 16g --security-opt label=disable --rm' + --incremental $INCREMENTAL + --base_ref ${{ github.base_ref }} + --head_ref refs/pull/${{ github.event.pull_request.number }}/head:${{ github.event.pull_request.head.ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Workflow dispatch + if: github.event_name == 'workflow_dispatch' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.image }} + --incremental ${{ inputs.incremental }} + --base_ref ${{ inputs.base_ref }} + --head_ref ${{ inputs.head_ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Nightly build + if: github.event_name == 'schedule' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.image }} + --incremental false + --binaries true + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Update artifacts after push to release branch + if: github.event_name == 'push' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype ${{ matrix.config }} + --platform ${{ matrix.image }} + --incremental false + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Upload test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: Test Results ${{ matrix.image }} ${{ matrix.config }} + path: /github/home/ROOT-CI/build/TestResults.xml + + - name: Upload binaries + if: ${{ !cancelled() && (inputs.binaries || github.event_name == 'schedule' || startsWith(github.ref, 'refs/tags/')) }} + uses: actions/upload-artifact@v3 + with: + name: Binaries ${{ matrix.image }} ${{ matrix.config }} + path: /github/home/ROOT-CI/packages/root_v* + if-no-files-found: error + + event_file: + if: github.repository_owner == 'root-project' || github.event_name == 'pull_request' + name: "Upload Event Payload" + runs-on: ubuntu-latest + steps: + - name: Upload + uses: actions/upload-artifact@v3 + with: + name: Event File + path: ${{ github.event_path }} diff --git a/.github/workflows/test-coverage.yml b/.github/workflows/test-coverage.yml new file mode 100644 index 0000000000000..4b34be7fa950e --- /dev/null +++ b/.github/workflows/test-coverage.yml @@ -0,0 +1,145 @@ + +name: 'Test Coverage' + +on: + schedule: + - cron: '0 1 * * *' + + # https://github.com/root-project/root/pull/12112#issuecomment-1411004278 + # DISABLED: takes 4 hours! Might clang-coverage be a solution? + #pull_request: + # branches: + # - 'master' + # paths-ignore: + # - 'doc/**' + # - 'documentation/**' + + workflow_call: + inputs: + head_ref: + type: string + required: true + default: master + base_ref: + type: string + required: true + default: master + + # Enables manual start of workflow + workflow_dispatch: + inputs: + head_ref: + description: rebase from ... + type: string + required: true + default: master + base_ref: + description: ... to ... (can have same value) + type: string + required: true + default: master + +env: + PYTHONUNBUFFERED: true + +jobs: + + build-linux: + if: github.repository_owner == 'root-project' || github.event_name == 'pull_request' + + permissions: + contents: read + + runs-on: + - self-hosted + - linux + - x64 + + name: Build and test to determine coverage + + container: + image: registry.cern.ch/root-ci/fedora38:buildready + options: '--security-opt label=disable --rm' + env: + OS_APPLICATION_CREDENTIAL_ID: '7f5b64a265244623a3a933308569bdba' + PYTHONUNBUFFERED: true + + steps: + - name: Install cov packages + run: | + sudo dnf -y update + sudo dnf -y install lcov + pip3 install gcovr + + - name: Checkout + uses: actions/checkout@v3 + + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJSON(github) }} + run: echo "$GITHUB_CONTEXT" + + - name: Print debug info + run: 'printf "%s@%s\\n" "$(whoami)" "$(hostname)"; + ls -la + ' + + - name: Apply option override from matrix for this job + env: + OVERRIDE: "coverage=On" + FILE: .github/workflows/root-ci-config/buildconfig/fedora38.txt + shell: bash + run: | + set -x + + echo '' >> "$FILE" + echo $OVERRIDE >> "$FILE" + cat "$FILE" || true + + - name: Pull Request Build + if: github.event_name == 'pull_request' + env: + GITHUB_PR_ORIGIN: ${{ github.event.pull_request.head.repo.clone_url }} + run: ".github/workflows/root-ci-config/build_root.py + --buildtype Debug + --platform fedora38 + --incremental false + --coverage true + --base_ref ${{ github.base_ref }} + --head_ref refs/pull/${{ github.event.pull_request.number }}/head:${{ github.event.pull_request.head.ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Workflow dispatch + if: github.event_name == 'workflow_dispatch' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype Debug + --platform fedora38 + --incremental false + --coverage true + --base_ref ${{ inputs.base_ref }} + --head_ref ${{ inputs.head_ref }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Nightly build + if: github.event_name == 'schedule' + run: ".github/workflows/root-ci-config/build_root.py + --buildtype Debug + --platform fedora38 + --incremental false + --coverage true + --base_ref ${{ github.ref_name }} + --repository ${{ github.server_url }}/${{ github.repository }} + " + + - name: Upload coverage to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@v3 + with: + env_vars: OS,PYTHON + fail_ci_if_error: true + files: /github/home/ROOT-CI/build/cobertura-cov.xml + flags: unittests + name: codecov-umbrella + verbose: true diff --git a/.github/workflows/test-result-comment.yml b/.github/workflows/test-result-comment.yml new file mode 100644 index 0000000000000..718b621512df2 --- /dev/null +++ b/.github/workflows/test-result-comment.yml @@ -0,0 +1,47 @@ + +name: Test Summary PR comment + +on: + workflow_run: + # do NOT use quotes: https://stackoverflow.com/a/72551795/17876693 + workflows: [ROOT CI] + types: + - completed +permissions: {} + +jobs: + comment-test-results: + name: Publish Test Results + + if: github.event.workflow_run.event == 'pull_request' + + runs-on: ubuntu-latest + + permissions: + checks: write + pull-requests: write + actions: read + + steps: + - name: Download and Extract Artifacts + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p artifacts && cd artifacts + + artifacts_url=${{ github.event.workflow_run.artifacts_url }} + + gh api --paginate "$artifacts_url" -q '.artifacts[] | [.name, .archive_download_url] | @tsv' | while read artifact + do + IFS=$'\t' read name url <<< "$artifact" + gh api $url > "$name.zip" + unzip -d "$name" "$name.zip" + done + + - name: Publish Test Results + uses: EnricoMi/publish-unit-test-result-action@v2 + with: + commit: ${{ github.event.workflow_run.head_sha }} + event_file: artifacts/Event File/event.json + event_name: ${{ github.event.workflow_run.event }} + files: "artifacts/**/*.xml" \ No newline at end of file diff --git a/.github/workflows/testsecurity.yml b/.github/workflows/testsecurity.yml new file mode 100644 index 0000000000000..5b55681769ba4 --- /dev/null +++ b/.github/workflows/testsecurity.yml @@ -0,0 +1,47 @@ + +name: 'Self-hosted runner security test' + +on: + workflow_dispatch: + +jobs: + no-container: + runs-on: [self-hosted, linux, x64] + steps: + - name: Print debug info + run: 'printf "%s@%s\\n" $(whoami) $(hostname); pwd; ls -la; ls -la /' + if: always() + + - name: Attempt illegal write operation + run: 'if touch /a; then false; fi' + if: always() + + - name: Attempt illegal read operation + run: 'if cd /root; then false; fi' + if: always() + + in-container: + needs: no-container + strategy: + fail-fast: false + matrix: + image: ["","","","","","","","","","","","","","","","","","","",""] + + runs-on: [self-hosted, linux, x64] + + container: + image: ubuntu + options: '-v /:/mnt/test --security-opt label=disable' + + steps: + - name: Print debug info + run: 'printf "%s@%s\\n" $(whoami) $(hostname); pwd; ls -Zla; ls -Zla /' + if: always() + + - name: Attempt illegal write operation + run: 'if touch /mnt/test/a > /dev/null; then false; fi' + if: always() + + - name: Attempt illegal read operation + run: 'if cd /mnt/test/root > /dev/null; then false; fi' + if: always() diff --git a/.gitignore b/.gitignore index 622ebd8507810..cee0406f6afc8 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,7 @@ project.xcworkspace # CLion .idea/* -cmake-build-*/ +cmake-build*/ # QtCreator CMakeLists.txt.user @@ -43,3 +43,6 @@ compile_commands.json documentation/doxygen/*.eps documentation/doxygen/*.pcm documentation/doxygen/*.jpg + +# Pycache +.github/workflows/root-ci-config/__pycache__ diff --git a/CMakeLists.txt b/CMakeLists.txt index c6544f7fdf30e..bedd4f5ca696e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. +# Copyright (C) 1995-2022, Rene Brun and Fons Rademakers. # All rights reserved. # # For the licensing terms see $ROOTSYS/LICENSE. @@ -16,19 +16,24 @@ if(WIN32) cmake_policy(SET CMP0091 OLD) endif() -if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR) +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT ALLOW_IN_SOURCE) message(FATAL_ERROR " ROOT must be built out-of-source.\n" " Please see README/INSTALL for more information.") endif() -set(policy_new CMP0072 CMP0077) +set(policy_new CMP0072 CMP0076 CMP0077 CMP0079) foreach(policy ${policy_new}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() +# ignore JAVA_ROOT when find_package(Java 1.8 ...) called +if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.27) + cmake_policy(SET CMP0144 OLD) +endif() + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.24) cmake_policy(SET CMP0135 OLD) endif() @@ -69,61 +74,9 @@ set(ROOTSYS ${CMAKE_BINARY_DIR}) set(HEADER_OUTPUT_PATH ${CMAKE_BINARY_DIR}/include) #---Set the ROOT version-------------------------------------------------------------------- -find_package(Git) -if(Git_FOUND AND EXISTS ${CMAKE_SOURCE_DIR}/.git) - execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_SOURCE_DIR}/.git describe --all - OUTPUT_VARIABLE GIT_DESCRIBE_ALL - RESULT_VARIABLE GIT_DESCRIBE_ERRCODE - ERROR_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE) -else() - set(GIT_DESCRIBE_ERRCODE "NoGit") -endif() - -function(SET_VERSION_FROM_FILE) - file(READ ${CMAKE_SOURCE_DIR}/build/version_number versionstr) - string(STRIP ${versionstr} versionstr) - string(REGEX REPLACE "([0-9]+)[.][0-9]+[/][0-9]+" "\\1" ROOT_MAJOR_VERSION ${versionstr}) - string(REGEX REPLACE "[0-9]+[.]([0-9]+)[/][0-9]+" "\\1" ROOT_MINOR_VERSION ${versionstr}) - string(REGEX REPLACE "[0-9]+[.][0-9]+[/]([0-9]+)" "\\1" ROOT_PATCH_VERSION ${versionstr}) - set(ROOT_VERSION "${ROOT_MAJOR_VERSION}.${ROOT_MINOR_VERSION}.${ROOT_PATCH_VERSION}" PARENT_SCOPE) - set(ROOT_MAJOR_VERSION "${ROOT_MAJOR_VERSION}" PARENT_SCOPE) - set(ROOT_MINOR_VERSION "${ROOT_MINOR_VERSION}" PARENT_SCOPE) - set(ROOT_PATCH_VERSION "${ROOT_PATCH_VERSION}" PARENT_SCOPE) -endfunction() +include(cmake/modules/SetROOTVersion.cmake) -if(GIT_DESCRIBE_ERRCODE) - SET_VERSION_FROM_FILE() -else() - execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_SOURCE_DIR}/.git describe --always - OUTPUT_VARIABLE GIT_DESCRIBE_ALWAYS - ERROR_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE) - string(TIMESTAMP GIT_TIMESTAMP "%b %d %Y, %H:%M:%S" UTC) - string(REGEX REPLACE "^v([0-9]+)-([0-9]+)-(.*)" "\\1.\\2.\\3" ROOT_FULL_VERSION ${GIT_DESCRIBE_ALWAYS}) - - if("${GIT_DESCRIBE_ALL}" MATCHES "^tags/v[0-9]+-[0-9]+-[0-9]+.*") - # GIT_DESCRIBE_ALWAYS: v6-16-00-rc1 - # GIT_DESCRIBE_ALL: tags/v6-16-00-rc1 - # tag might end on "-rc1" or similar; parse version number in front. - string(REGEX REPLACE "^tags/v([0-9]+)-.*" "\\1" ROOT_MAJOR_VERSION ${GIT_DESCRIBE_ALL}) - string(REGEX REPLACE "^tags/v[0-9]+-([0-9]+).*" "\\1" ROOT_MINOR_VERSION ${GIT_DESCRIBE_ALL}) - string(REGEX REPLACE "^tags/v[0-9]+-[0-9]+-([0-9]+).*" "\\1" ROOT_PATCH_VERSION ${GIT_DESCRIBE_ALL}) - elseif("${GIT_DESCRIBE_ALL}" MATCHES "/v[0-9]+-[0-9]+.*-patches$") - # GIT_DESCRIBE_ALWAYS: v6-16-00-rc1-47-g9ba56ef4a3 - # GIT_DESCRIBE_ALL: heads/v6-16-00-patches - string(REGEX REPLACE "^.*/v([0-9]+)-.*" "\\1" ROOT_MAJOR_VERSION ${GIT_DESCRIBE_ALL}) - string(REGEX REPLACE "^.*/v[0-9]+-([0-9]+).*" "\\1" ROOT_MINOR_VERSION ${GIT_DESCRIBE_ALL}) - set(ROOT_PATCH_VERSION "99") # aka head of ...-patches - else() - # GIT_DESCRIBE_ALWAYS: v6-13-04-2163-g7e8d27ea66 - # GIT_DESCRIBE_ALL: heads/master or remotes/origin/master - SET_VERSION_FROM_FILE() - set(ROOT_FULL_VERSION "${ROOT_MAJOR_VERSION}.${ROOT_MINOR_VERSION}.${ROOT_PATCH_VERSION}") - endif() - set(ROOT_VERSION "${ROOT_MAJOR_VERSION}.${ROOT_MINOR_VERSION}.${ROOT_PATCH_VERSION}") - message(STATUS "Detected ROOT_VERSION ${ROOT_VERSION}") -endif() +message(STATUS "Building ROOT version ${ROOT_FULL_VERSION}") #---Try to download a file to check internet connection----------------------------------------- message(STATUS "Checking internet connectivity") @@ -168,6 +121,99 @@ include(RootMacros) include(CheckAssembler) include(CheckIntrinsics) +# relatedrepo_GetClosestMatch(REPO_NAME ORIGIN_PREFIX UPSTREAM_PREFIX +# FETCHURL_VARIABLE FETCHREF_VARIABLE ) +# Return the clone URL and head/tag of the closest match for `repo` (e.g. roottest), based on the +# current head name. +function(relatedrepo_GetClosestMatch) + cmake_parse_arguments(_ "" "REPO_NAME;ORIGIN_PREFIX;UPSTREAM_PREFIX;FETCHURL_VARIABLE;FETCHREF_VARIABLE" "" ${ARGN}) + + set(${__FETCHURL_VARIABLE} ${__UPSTREAM_PREFIX}/${__REPO_NAME} PARENT_SCOPE) + + if(NOT IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/.git) + set(${__FETCHREF_VARIABLE} v${ROOT_MAJOR_VERSION}-${ROOT_MINOR_VERSION}-${ROOT_PATCH_VERSION} PARENT_SCOPE) + return() + endif() + + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git + rev-parse --abbrev-ref HEAD + OUTPUT_VARIABLE current_head OUTPUT_STRIP_TRAILING_WHITESPACE) + set(${__FETCHREF_VARIABLE} ${current_head} PARENT_SCOPE) + + # `current_head` is a well-known branch, e.g. master, or v6-28-00-patches. Use the matching branch + # upstream as the fork repository may be out-of-sync + string(REGEX MATCH "^(master|latest-stable|v[0-9]+-[0-9]+-[0-9]+(-patches)?)$" known_head ${current_head}) + if(NOT "${known_head}" STREQUAL "") + if("${current_head}" STREQUAL "latest-stable") + # Resolve the 'latest-stable' branch to the latest merged head/tag + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git + for-each-ref --points-at=latest-stable^2 --format=%\(refname:short\) + OUTPUT_VARIABLE current_head OUTPUT_STRIP_TRAILING_WHITESPACE) + set(${__FETCHREF_VARIABLE} ${current_head} PARENT_SCOPE) + endif() + return() + endif() + + # Otherwise, try to use a branch that matches `current_head` in the fork repository + execute_process(COMMAND ${GIT_EXECUTABLE} ls-remote --heads --tags + ${__ORIGIN_PREFIX}/${__REPO_NAME} ${current_head} OUTPUT_VARIABLE matching_refs) + if(NOT "${matching_refs}" STREQUAL "") + set(${__FETCHURL_VARIABLE} ${__ORIGIN_PREFIX}/${__REPO_NAME} PARENT_SCOPE) + return() + endif() + + # Finally, try upstream using the closest head/tag below the parent commit of the current head + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git + describe --all --abbrev=0 HEAD^ + OUTPUT_VARIABLE closest_ref ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + string(REGEX REPLACE "^(heads|tags)/" "" candidate_head "${closest_ref}") + execute_process(COMMAND ${GIT_EXECUTABLE} ls-remote --heads --tags + ${__UPSTREAM_PREFIX}/${__REPO_NAME} "${candidate_head}" OUTPUT_VARIABLE matching_refs) + if(NOT "${matching_refs}" STREQUAL "") + set(${__FETCHREF_VARIABLE} ${candidate_head} PARENT_SCOPE) + return() + endif() + set(${__FETCHREF_VARIABLE} "" PARENT_SCOPE) +endfunction() + +# relaterepo_Checkout(REPO_NAME FETCHURL FETCHREF +# [FORCE] [REPO_DIR_VARIABLE ]) +# Clone/fetch and checkout the specified `ref` from the given repository at `url`. If a local clone of the +# repository is found, refuse to update it unless the `FORCE` option is in place. +function(relatedrepo_Checkout) + cmake_parse_arguments(_ "FORCE" "REPO_NAME;FETCHURL;FETCHREF;REPO_DIR_VARIABLE" "" ${ARGN}) + + # Check whether the repository exists in the source directory or its parent + get_filename_component(source_dir ${CMAKE_CURRENT_SOURCE_DIR} REALPATH) + if(IS_DIRECTORY ${source_dir}/${__REPO_NAME}) + set(repo_dir ${source_dir}/${__REPO_NAME}) + elseif(IS_DIRECTORY ${source_dir}/../${__REPO_NAME}) + set(repo_dir ${source_dir}/../${__REPO_NAME}) + endif() + + if(NOT DEFINED repo_dir) + message(STATUS "Cloning ${__REPO_NAME} from '${__FETCHURL}' (${__FETCHREF})") + if(NOT "${__FETCHREF}" STREQUAL "") + string(PREPEND __FETCHREF "-b") + endif() + execute_process(COMMAND ${GIT_EXECUTABLE} clone ${__FETCHREF} ${__FETCHURL} + WORKING_DIRECTORY ${source_dir}) + set(repo_dir ${source_dir}/${__REPO_NAME}) + else() + message(STATUS "Found ${__REPO_NAME}: ${repo_dir}") + if(${__FORCE}) + message(STATUS "Updating ${__REPO_NAME} from '${__FETCHURL}' (${__FETCHREF})") + execute_process(COMMAND ${GIT_EXECUTABLE} fetch -fu ${__FETCHURL} ${__FETCHREF}:${__FETCHREF} + WORKING_DIRECTORY ${repo_dir}) + execute_process(COMMAND ${GIT_EXECUTABLE} checkout -f ${__FETCHREF} + WORKING_DIRECTORY ${repo_dir}) + endif() + endif() + if(DEFINED __REPO_DIR_VARIABLE) + set(${__REPO_DIR_VARIABLE} ${repo_dir} PARENT_SCOPE) + endif() +endfunction() + #---Enable asserts------------------------------------------------------------------------------ if(asserts) string(REGEX REPLACE "-[UD]NDEBUG(=.*)?" "" "CMAKE_CXX_FLAGS_${_BUILD_TYPE_UPPER}" "${CMAKE_CXX_FLAGS_${_BUILD_TYPE_UPPER}}") @@ -370,7 +416,6 @@ add_subdirectory (net) add_subdirectory (graf2d) add_subdirectory (graf3d) add_subdirectory (gui) -add_subdirectory (proof) add_subdirectory (html) add_subdirectory (montecarlo) add_subdirectory (geom) @@ -379,6 +424,9 @@ add_subdirectory (misc) add_subdirectory (main) add_subdirectory (bindings) add_subdirectory (sql) +if(proof) + add_subdirectory(proof) +endif() if(tmva) add_subdirectory(tmva) endif() @@ -521,14 +569,25 @@ endif() if(runtime_cxxmodules) ROOT_GET_LIBRARY_OUTPUT_DIR(library_output_dir) get_property(modules_idx_deps GLOBAL PROPERTY modules_idx_deps_property) - add_custom_command(OUTPUT ${library_output_dir}/modules.idx - COMMAND ${CMAKE_COMMAND} -E remove -f modules.idx modules.timestamp - COMMAND ${ld_library_path}=${library_output_dir}:$ENV{${ld_library_path}} - ROOTIGNOREPREFIX=1 ROOT_HIST=0 - $ -l -q -b - WORKING_DIRECTORY ${library_output_dir} - DEPENDS $ Cling Hist Tree Gpad Graf HistPainter move_artifacts - ${modules_idx_deps}) + if(WIN32) + add_custom_command(OUTPUT ${library_output_dir}/modules.idx + COMMAND ${CMAKE_COMMAND} -E remove -f modules.idx modules.timestamp + COMMAND set PATH=${library_output_dir} && + set ROOTIGNOREPREFIX=1 && set ROOT_HIST=0 && + $ -l -q -b + WORKING_DIRECTORY ${library_output_dir} + DEPENDS $ Cling Hist Tree Gpad Graf HistPainter move_artifacts + ${modules_idx_deps}) + else() + add_custom_command(OUTPUT ${library_output_dir}/modules.idx + COMMAND ${CMAKE_COMMAND} -E remove -f modules.idx modules.timestamp + COMMAND ${ld_library_path}=${library_output_dir}:$ENV{${ld_library_path}} + ROOTIGNOREPREFIX=1 ROOT_HIST=0 + $ -l -q -b + WORKING_DIRECTORY ${library_output_dir} + DEPENDS $ Cling Hist Tree Gpad Graf HistPainter move_artifacts + ${modules_idx_deps}) + endif() add_custom_target(modules_idx ALL DEPENDS ${library_output_dir}/modules.idx) add_dependencies(modules_idx ${modules_idx_deps}) set_property(TARGET modules_idx PROPERTY modules_idx_file ${library_output_dir}/modules.idx) @@ -580,7 +639,14 @@ if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_INSTALL_PREFIX) else() install(DIRECTORY README DESTINATION ${CMAKE_INSTALL_DOCDIR}) endif() + set(ETC_PATT_EXCL) + if(NOT roofit) + list(APPEND ETC_PATT_EXCL PATTERN HistFactorySchema.dtd EXCLUDE) + list(APPEND ETC_PATT_EXCL PATTERN RooFitHS3_wsexportkeys.json EXCLUDE) + list(APPEND ETC_PATT_EXCL PATTERN RooFitHS3_wsfactoryexpressions.json EXCLUDE) + endif() install(DIRECTORY etc/ DESTINATION ${CMAKE_INSTALL_SYSCONFDIR} USE_SOURCE_PERMISSIONS + ${ETC_PATT_EXCL} PATTERN "system.rootrc" EXCLUDE PATTERN "system.rootauthrc" EXCLUDE PATTERN "system.rootdaemonrc" EXCLUDE @@ -601,8 +667,11 @@ if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_INSTALL_PREFIX) set(MAN_PATT_EXCL PATTERN xproofd.1 EXCLUDE) endif() if(NOT fortran OR NOT CMAKE_Fortran_COMPILER) - set(MAN_PATT_EXCL ${MAN_PATT_EXCL} PATTERN h2root.1 EXCLUDE) - set(MAN_PATT_EXCL ${MAN_PATT_EXCL} PATTERN g2root.1 EXCLUDE) + list(APPEND MAN_PATT_EXCL PATTERN h2root.1 EXCLUDE) + list(APPEND MAN_PATT_EXCL PATTERN g2root.1 EXCLUDE) + endif() + if(NOT roofit) + list(APPEND MAN_PATT_EXCL PATTERN prepareHistFactory.1 EXCLUDE) endif() install(DIRECTORY man/ DESTINATION ${CMAKE_INSTALL_MANDIR} ${MAN_PATT_EXCL}) install(DIRECTORY tutorials/ DESTINATION ${CMAKE_INSTALL_TUTDIR} COMPONENT tests) @@ -610,6 +679,9 @@ if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_INSTALL_PREFIX) cmake/modules/RootMacros.cmake cmake/modules/RootTestDriver.cmake DESTINATION ${CMAKE_INSTALL_CMAKEDIR}) + install(FILES + "cmake/modules/FindVdt.cmake" + DESTINATION "${CMAKE_INSTALL_CMAKEDIR}/modules") endif() #---Add configuration files for kernel and jupyter---------------------------------------------- @@ -639,86 +711,48 @@ endif() configure_file(${CMAKE_SOURCE_DIR}/cmake/modules/CTestCustom.cmake ${CMAKE_BINARY_DIR} COPYONLY) if(testing) include(RootCTest) + set(upstreamprefix https://github.com/root-project) if(roottest) - #---Is the roottest source directory around? - if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/roottest) - set(roottestdir ${CMAKE_CURRENT_SOURCE_DIR}/roottest) + find_package(Git REQUIRED) + # The fetch URL of the 'origin' remote is used to determine the prefix for other repositories by + # removing the `/root(\.git)?` part. If `GITHUB_PR_ORIGIN` is defined in the environment, its + # value is used instead. + if(DEFINED ENV{GITHUB_PR_ORIGIN}) + set(originurl $ENV{GITHUB_PR_ORIGIN}) else() - # Need to break into two steps in case the source dir is a symlink - get_filename_component(_source_dir ${CMAKE_CURRENT_SOURCE_DIR} REALPATH) - set(roottestdir ${_source_dir}/../roottest) + execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git + remote get-url origin OUTPUT_VARIABLE originurl OUTPUT_STRIP_TRAILING_WHITESPACE) endif() - - if(IS_DIRECTORY ${roottestdir}) - file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/roottest) - add_subdirectory(${roottestdir} roottest) - else() - message("-- Could not find roottest directory! Cloning from the repository...") - - find_package(Git REQUIRED) - - if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/.git) - execute_process(COMMAND ${GIT_EXECUTABLE} for-each-ref --points-at=HEAD --count=1 --format=%\(refname:short\) - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_BRANCH OUTPUT_STRIP_TRAILING_WHITESPACE) - else() - set(GIT_BRANCH v${ROOT_MAJOR_VERSION}-${ROOT_MINOR_VERSION}-${ROOT_PATCH_VERSION}) - endif() - - # Resolve the `latest-stable` branch to the latest merged head/tag - if("${GIT_BRANCH}" STREQUAL "latest-stable") - execute_process(COMMAND ${GIT_EXECUTABLE} for-each-ref --points-at=latest-stable^2 --format=%\(refname:short\) - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_BRANCH OUTPUT_STRIP_TRAILING_WHITESPACE) - endif() - - execute_process(COMMAND - ${GIT_EXECUTABLE} ls-remote --heads --tags - https://github.com/root-project/roottest.git ${GIT_BRANCH} - OUTPUT_VARIABLE ROOTTEST_GIT_BRANCH) - - if(NOT "${ROOTTEST_GIT_BRANCH}" STREQUAL "") - set(ROOTTEST_GIT_BRANCH -b ${GIT_BRANCH}) - endif() - - execute_process(COMMAND - ${GIT_EXECUTABLE} clone ${ROOTTEST_GIT_BRANCH} - https://github.com/root-project/roottest.git - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - - if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/roottest) - message(FATAL_ERROR "Error cloning roottest") - endif() - - add_subdirectory(roottest) + string(REGEX REPLACE "/root(\.git)?$" "" originprefix ${originurl}) + relatedrepo_GetClosestMatch(REPO_NAME roottest + ORIGIN_PREFIX ${originprefix} UPSTREAM_PREFIX ${upstreamprefix} + FETCHURL_VARIABLE roottest_url FETCHREF_VARIABLE roottest_ref) + # Use `-Droottest_force_checkout=ON` to force fetch and checkout in an existing repository + if(roottest_force_checkout) + set(roottest_opts FORCE) + endif() + relatedrepo_Checkout(REPO_NAME roottest FETCHURL ${roottest_url} FETCHREF "${roottest_ref}" + REPO_DIR_VARIABLE roottest_dir ${roottest_opts}) + if(NOT IS_DIRECTORY ${roottest_dir}) + message(FATAL_ERROR "Expected roottest at '${roottest_dir}' (not a directory?)") endif() + file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/roottest) + add_subdirectory(${roottest_dir} roottest) endif() if(rootbench) find_package(Git REQUIRED) - execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_BRANCH OUTPUT_STRIP_TRAILING_WHITESPACE) - #---Is the rootbench source directory around? - if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/rootbench) - set(rootbenchdir ${CMAKE_CURRENT_SOURCE_DIR}/rootbench) - else() - # Need to break into two steps in case the source dir is a symlink - get_filename_component(_source_dir ${CMAKE_CURRENT_SOURCE_DIR} REALPATH) - set(rootbenchdir ${_source_dir}/../rootbench) + if(rootbench_force_checkout) + set(rootbench_opts FORCE) endif() - - if(IS_DIRECTORY ${rootbenchdir}) - file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/rootbench) - add_subdirectory(${rootbenchdir} rootbench) - else() - message("-- Could not find rootbench directory! Cloning from the repository...") - execute_process(COMMAND ${GIT_EXECUTABLE} clone -b ${GIT_BRANCH} - https://github.com/root-project/rootbench.git - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - add_subdirectory(rootbench) + relatedrepo_Checkout(REPO_NAME rootbench FETCHURL ${upstreamprefix} FETCHREF master + REPO_DIR_VARIABLE rootbench_dir ${rootbench_opts}) + if(NOT IS_DIRECTORY ${rootbench_dir}) + message(FATAL_ERROR "Expected rootbench at '${rootbench_dir}' (not a directory?)") endif() + file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/rootbench) + add_subdirectory(${rootbench_dir} rootbench) endif() endif() diff --git a/README.md b/README.md index df96337b9e52c..eaf1e6d873ea4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## About -The ROOT system provides a set of OO frameworks with all the functionality +The ROOT system provides a set of modules with all the functionality needed to handle and analyze large amounts of data in a very efficient way. Having the data defined as a set of objects, specialized storage methods are used to get direct access to the separate attributes of the selected objects, diff --git a/README/CREDITS b/README/CREDITS index 82fc5d5334b0a..389693fa80c43 100644 --- a/README/CREDITS +++ b/README/CREDITS @@ -1100,3 +1100,7 @@ D: contributed to TStyle::CreateGradientColorTable() N: Omar Andres Zapata Mesa E: Omar.Zapata@cern.ch D: ROOT-R, JupyROOT, TMVA + +N: Marco Meyer-conde +E: marco.meyer@cern.ch +D: contour drawing options "MOLLWEIDE" diff --git a/README/README.ALIEN b/README/README.ALIEN deleted file mode 100644 index 3bd42f82f5fcd..0000000000000 --- a/README/README.ALIEN +++ /dev/null @@ -1,130 +0,0 @@ -========================================================================= -How to use the TGrid/TAlien/TAlienFile class V1.1 - Andreas.Peters@cern.ch -========================================================================= - - -TGrid-Plugin: TAlien -==================== - -To connect to Alien you have to connect to a running API service of your -virtual organization. - -Creating instance: -a) // connecting to an API service - - TGrid::Connect("alien://pcapiserv01.cern.ch:9000","aliprod); - - // connecting to an API service which is defined already by the - environment variables: - export alien_API_HOST=... - export alien_API_PORT=... - export alien_API_USER=... - TGrid::Connect("alien://"); - - // connect to an API service with an authentication token established - previously with gShellq. - -b) TGrid::Connect("alien://",0,0,"t"); - - In case a) the authentication is private to the process, while case b) - shares the authentication(session) with the shell, which has established - the session previously. Notice that a) is not thread-safe, while b) is! - -If you have executed TGrid::Connect(), the gGrid global variable -should be set != 0. - -Some examples: - -- change the working directory - - gGrid->Cd("/alice/"); // => returns 1 for success, 0 for error - -- get the working directory - - printf("GRID Working is %d",gGrid->Pwd()); - -- list a directory - - TGridResult* result = gGrid->Ls("/alice"); - Int_t i=0; - while (result->GetFileName(i)) - printf("File %s\n",result->GetFileName(i++)); - TGridResult* result = gGrid->Ls("/alice"); - Int_t i=0; - while (result->GetFileName(i)) - printf("File %s\n",result->GetFileName(i++)); - -- get all file permissions - using the GetKey function - - TGridResult* result = gGrid->Ls("/alice","-la"); - while (result->GetFileName(i))\ - printf("The permissions are %s\n",result->GetKey(i++,"permissions") - - // => the defined keys for GetKey can be seen using result->Print(); - - -- query files under a certain namespace tree - - TGridResult* result = gGrid->Query("/alice/,"*.root"); - - -You can execute any existing command via the Command interface: - - TGridResult* result = gGrid->Command("ls -la /",0,2); - - // '0' switches of the output of stdout and stderr to the terminal - // '2' selects the result stream to be returned as TGridResult* : - '0' returns stdout, - '1' returns stderr, - '2' returns the result structure - --> This command is equivalent to: - - gGrid->Ls("/","-la"); - -You can print the stdout of the last command via: - gGrid->Stdout(); - -You can print the stderr of the last command via: - gGrid->Stderr(); - -To see the result structure of a command, you can just use the 'Print' function for the -TGridResult: - - result->Print(); - - - -TFile-Plugin: TAlienFile -======================== - -Files stored in Alien can be opened with the catalogue LFN or a GUID. -To open a file by LFN use: - - TFile* myfile = TFile::Open("alien:///alice/cern.ch/file.root"); - -or - - TFile* myfile = TFile::Open("/alien/alice/cern.ch/file.root"); - - -To open a file by GUID use: - - TFile* myfile = TFile::Open("alien://"); - -To address a certain storage element add to the URL - "?se=ALICE::CERN::Castor"; - -f.e. TFile::Open("/alien/alice/cern.ch/file.root?se=ALICE::CERN::Castor"); - - -To open a ZIP file in an archive, use: - - TFile::Open("/alien7alice/cern.ch/archivefile.zip#file.root"); - -- this assumes, that archivefile.zip is an UNCOMPRESSED zip archive containing - 'file.root'. -- remember, that archives need to have the suffix '.zip' to be understood as - such. - - diff --git a/README/ReleaseNotes/v628/index.md b/README/ReleaseNotes/v628/index.md index 09ddefc6bfea6..3a843d220e070 100644 --- a/README/ReleaseNotes/v628/index.md +++ b/README/ReleaseNotes/v628/index.md @@ -12,29 +12,48 @@ For more information, see: The following people have contributed to this new version: + Rahul Balasubramanian, NIKHEF/ATLAS,\ Bertrand Bellenot, CERN/SFT,\ Jakob Blomer, CERN/SFT,\ + Patrick Bos, Netherlands eScience Center,\ Rene Brun, CERN/SFT,\ - Will Buttinger, RAL/Atlas,\ + Carsten D. Burgard, TU Dortmund University/ATLAS,\ + Will Buttinger, RAL/ATLAS,\ Philippe Canal, FNAL,\ Olivier Couet, CERN/SFT,\ + Michel De Cian, EPFL/LHCb,\ + Mattias Ellert, Uppsala University,\ Gerri Ganis, CERN/SFT,\ Andrei Gheata, CERN/SFT,\ + Konstantin Gizdov, University of Edinburgh/LHCb,\ + Max Goblirsch, CERN/ATLAS,\ Enrico Guiraud, CERN/SFT,\ + Stephan Hageboeck, CERN/IT,\ + Jonas Hahnfeld, CERN/SFT,\ + Ahmat Mahamat Hamdan, CERN/SFT,\ + Fernando Hueso-González, University of Valencia,\ + Subham Jyoti, ITER Bhubaneswar,\ Sergey Linev, GSI,\ Javier Lopez-Gomez, CERN/SFT,\ + Enrico Lusiani, INFN/CMS,\ Pere Mato, CERN/SFT,\ Lorenzo Moneta, CERN/SFT,\ + Nicolas Morange, CNRS/ATLAS,\ Axel Naumann, CERN/SFT,\ + Hanna Olvhammar, CERN/SFT,\ Vincenzo Eduardo Padulano, CERN/SFT and UPV,\ Danilo Piparo, CERN/SFT,\ Fons Rademakers, CERN/SFT,\ Jonas Rembser, CERN/SFT,\ Enric Tejedor Saavedra, CERN/SFT,\ + Neel Shah, GSOC,\ + Sanjiban Sengupta, CERN/SFT,\ + Harshal Shende, GSOC,\ Garima Singh, Princeton/SFT,\ Matevz Tadel, UCSD/CMS,\ Vassil Vassilev, Princeton/CMS,\ - Wouter Verkerke, NIKHEF/Atlas,\ + Wouter Verkerke, NIKHEF/ATLAS,\ + Zef Wolffs, NIKHEF/ATLAS,\ Ivan Kabadzhov, CERN/SFT,\ David Poulton, Wits/SFT @@ -61,6 +80,8 @@ Please use their non-experimental counterparts `ROOT::TBufferMerger` and `ROOT:: - The `RooSimPdfBuilder` that was deprecated in ROOT 5.20 and replaced by the `RooSimWSTool` is removed. - The RDataFrame factory functions `MakeNumpyDataFrame`, `MakeCsvDataFrame`, `MakeArrowDataFrame`, `MakeNTupleDataFrame` and `MakeSqliteDataFrame` are now deprecated in favor of `FromNumpy`, `FromCSV`, `FromArrow`, `FromRNTuple` and `FromSqlite` respectively. +- The build option `alien` has been removed. +- The build options `gfal`, `gsl_shared`, `jemalloc`, `monalisa`, `pyroot_legacy`, `tcmalloc`, and `xproofd` have been deprecated. Please complain with root-dev@cern.ch should you still need one! ## rootreadspeed @@ -163,12 +184,48 @@ RNTuple is still experimental and is scheduled to become production grade in 202 ### New features - Add [`GraphAsymmErrors`](https://root.cern/doc/master/classROOT_1_1RDF_1_1RInterface.html#acea30792eef607489d498bf6547a00a6) action that fills a TGraphAsymmErrors object. +- Introduce [`RDatasetSpec`](https://root.cern/doc/master/classROOT_1_1RDF_1_1Experimental_1_1RDatasetSpec.html) as an +experimental class to specify the input dataset to an RDataFrame. +- Arbitrary metadata can be associated to the samples in the dataset specified via `RDatasetSpect`. The metadata of each +sample can then be retrieved during the execution by calling `DefinePerSample`. +- Users can create an RDataFrame with a dataset specification written in a JSON file via the factory function +[ROOT::RDF::Experimental::FromSpec](https://root.cern/doc/master/namespaceROOT_1_1RDF_1_1Experimental.html#a7193987f3c1b65c649399656cc6acce8). ### Notable bug fixes and improvements - Fix the node counter of [`SaveGraph`](https://root.cern/doc/master/namespaceROOT_1_1RDF.html#ac06a36e745255fb8744b1e0a563074c9), where previously `cling` was getting wrong static initialization. - Fix [`Graph`](https://root.cern/doc/master/classROOT_1_1RDF_1_1RInterface.html#a1ca9a94bece4767cac82968910afa02e) action (that fills a TGraph object) to properly handle containers and non-container types. - The [`RCsvDS`](https://root.cern.ch/doc/master/classROOT_1_1RDF_1_1RCsvDS.html) class now allows users to specify column types, and can properly read empty entries of csv files. +- Fixed a bug where the `Display` operation would not show the correct amount of entries requested by the user if called +together with other operations ([PR](https://github.com/root-project/root/pull/11398)). +- Requesting variations for `Stats` results with `VariationsFor` is now supported. +- Factory functions for RDataFrames reading CSV files, RNTuples, Arrow tables, etc. have been renamed in order to +increase consistency, e.g. `MakeCsvDataFrame` is now `FromCSV`. The old wording is still available but deprecated. +- The precision of `Sum`s and `Mean`s of single-precision floating point values has been greatly improved by employing +Kahan summations. +- The content of [execution logs](https://root.cern/doc/master/classROOT_1_1RDataFrame.html#rdf-logging) from RDataFrame +has been streamlined in order to make them more useful. + +### Distributed RDataFrame + +- Add support for systematic variations (e.g. `Vary` and `VariationsFor` operations) in distributed mode. +- If an instant action (e.g. `Snapshot`) is purposely made lazy by the user, distributed RDataFrame now respects this +and avoids triggering the computations right away. +- The algorithm for automatic splitting of the input dataset has been reworked, bringing the startup time cost of +distributed RDataFrame close to zero. +- A histogram model (name, title, binning) for the `Histo*D` actions is now required in distributed mode. See the +[relative PR](https://github.com/root-project/root/pull/10368) for more discussion. +- The performance of distributed RDataFrame for large computation graphs (>1000 operations) has been greatly improved. +- If the `npartitions` argument is not set by the user, the default number of tasks created by a distributed RDataFrame +is equal to the number of cores specified by the user when connecting to the cluster. +- C++ exceptions (i.e. instances of `std::exception` and derived) are now correctly propagated from the processes of the +computing nodes to the user side. +- The minimum `dask` version required to support distributed RDataFrame is 2022.8.1, since a series of critical bugs +present before that version were hindering the normal execution of the tool. Consequently, the minimum Python version +needed to include distributed RDataFrame in the ROOT build is Python 3.8. More information in the relative +[github issue](https://github.com/root-project/root/issues/11515). +- `Stats` and `StdDev` operations are now available in distributed mode. +- `GetColumnNames` operation is now available in distributed mode. ## Histogram Libraries @@ -177,6 +234,42 @@ RNTuple is still experimental and is scheduled to become production grade in 202 ## Math Libraries +### Fitter class + +Some improvements and small fixes to the internal object memory management have been applied to the `ROOT::Fit::Fitter` class. +- When setting an external FCN (objective function) to the Fitter, the function object is not cloned anymore. +- A memory leak has been fixed, when using the `GSLMultiFit` class. +- A bug has been resolved in setting fixed variables when using the linear fitter (via the `TLinearMinimizer` class). + +Support for providing the second derivatives (Hessian matrix) from the model function is added to the `Fitter` class and the corresponding function interfaces. The functionality it is then propagated in the implementation of the `FitMethod` classes and it is also added to the `Minimizer` classes for providing a user computed Hessian of the objective functions to the minimizers. Only Minuit2 (see below) has the capabilities of using this external Hessian. + +The `GradFunctor` class has been improved by providing a new constructor taking an `std::function` implementing the full gradient calculations instead of the single partial derivative. + +The specialized methods for least-square/likelihood functions such as Fumili, Fumili2 and GSLMultiFit have been improved in case of binned likelihood fits, where a better approximation is used than before. This makes these method work better (conerging with less number of function calls) for these types of fits. + +### Minuit2 + +The support for using an External Hessian calculator has been added. The external Hessian can be used for both the initial seeding, using only the diagonal part, if the strategy is equal to 1 (the default value) and in `MnHesse`, after the minimization, to compute the covariance and correlation matrices. + +The print log of Minuit2 has been improved, especially when printing vector and matrices with large number of parameters (when the print level = 3). + + +### KahanSum updates + +The `ROOT::Math::KahanSum` class was slightly modified: +- The behavior of `operator-=` and `operator+=` on a `KahanSum` were not symmetric, leading to slight bit-wise inaccuracies. In fits, where such operations are done a lot of times (e.g. through the offsetting mechanism in RooFit which subtracts a constant `KahanSum` term after each likelihood evaluation), this can add up to significant numerical divergence. An improved algorithm was implemented, based on an algorithm for combining Kahan sums and carry terms (Tian et al. 2012). (PR #11940) +- The auto-conversion to type `T` and implicit type `T` constructor in `KahanSum` made it hard to debug `KahanSum`, because it is easy to overlook implicit conversions in code, especially in lines where the type of the return value is `auto`. These auto-conversions were removed. Where necessary, they should be replaced with an explicit construction or explicit conversion to double via `Sum()`. (PR #11941) +- Binary addition and subtraction operators were added, as well as a unary negation operator. (PR #11940) +- Comparison operators `operator==` and `operator!=` were added. + +### Foam + +The usage of `TRef` in the `TFoamCell` class has ben replaced with array indices. This avoids, when generating a large number of toys requiring a re-initialization of `TFoam` an increase in the memory usage caused by `TRef`. + +### RVec + +- a number of new helper functions have been added to [RVec](https://root.cern/doc/master/classROOT_1_1VecOps_1_1RVec.html): [Range](https://root.cern/doc/master/group__vecops.html#ga59cc6e477803f2bfd7dae29e56048cc1), [Product](https://root.cern/doc/master/group__vecops.html#ga25e4c2cf5c82fe56dd6bbc86b2386b69) and Enumerate +- the [Take](https://root.cern/doc/master/group__vecops.html#gac719439afb1ec9d32a28acdc7aee5948) helper function now allows passing a default value that will be used to fill the output array in case it's longer than the input ## RooFit Libraries @@ -281,6 +374,92 @@ In the unlikely case that this causes any problem for you, please open a GitHub The `RooAbsBinning` interface for bin index lookups was changed to enable vectorized implementations. Instead of having the override `RooAbsBinning::binNumber()`, the binning implementations now have to override the `RooAbsBinning::binNumbers()` function to evaluate the bin indices of multiple values in one function call. +### Disable relative and absolute epsilon in `RooAbsRealLValue::inRange()` + +So far, the `RooAbsRealLValue::inRange()` function used the following +undocumented convention to check whether a value `x` is in the range with +limits `a` and `b`: test if `[x - eps * x, x + eps * x]` overlaps with `[a, b]`, where the +parameter `eps` is defined as `max(epsRel * x, epsAbs)`. + +The values of the relative and absolute epsilons were inconsistent among the overloads: + +* [RooAbsRealLValue::inRange(const char* rangeName)](https://root.cern.ch/doc/v626/classRooAbsRealLValue.html#ab6050a0c3e5583b9d755a38fd7fb82f7): `epsRel = 1e-8, epsAbs = 0` +* [RooAbsRealLValue::inRange(double value, const char* rangeName, double* clippedValPtr)](https://root.cern.ch/doc/v626/classRooAbsRealLValue.html#afc2a8818f433a9a4ec0c437cbdad4e8a): `epsRel = 0, epsAbs = 1e-6` +* [RooAbsRealLValue::inRange(std::span values, std::string const& rangeName, std::vector& out)](https://root.cern.ch/doc/v626/classRooAbsRealLValue.html#af9217abd0afe34364562ad0c194f5d2c): `epsRel = 0, epsAbs = 1e-6` + + +With this release, the default absolute and relative epsilon is zero to avoid confusion. +You can change them with `RooNumber::setRangeEpsRel(epsRel)` and `RooNumber::setRangeEpsAbs(epsAbs)`. + +## TMVA + +### SOFIE : Code generation for fast inference of Deep Learning models + +A large number of new features have been added in the TMVA SOFIE library. The list of all operators supported in the `RModel` class is the one provided below for the ONNX parser. + +The interface of `RModel::Generate` has been changed to +``` +RModel::Generate(Options options = Options::kDefault, int batchsize = 1)` +``` +where `Options` is a new enumeration having 3 different values: +- `kDefault = 0x0` : default case, a session class is generated and the weights are stored in a separate `.dat` file (in text format). +- `kNoSession = 0x1` : no session class is generated and the internal intermediate tensors are declared in the global namespace `TMVA_SOFIE_$ModelName`. +- `kNoWeightFile = 0x2` the weight values are not written in a separate `.dat` file, but they are included in the generated header file. + +In addition, the `RModel::Generate` function takes as an additional optional argument the batch size (default is = 1) and the inference code can then be generated for the desired batch size. + +#### SOFIE ONNX Parser + +The ONNX parser supports now several new ONNX operators. The list of the current supported ONNX operator is the following: +- Gemm +- Conv (in 1D,2D and 3D) +- RNN, GRU, LSTM +- Relu, Selu, Sigmoid, Softmax, Tanh, LeakyRelu +- BatchNormalization +- MaxPool, AveragePool, GlobalAverage +- ConvTranspose +- Gather +- Expand, Reduce +- Neg, Exp, Sqrt, Reciprocal +- Add, Sum, Mul, Div +- Reshape, Flatten, Transpose +- Squeeze, Unsqueeze, Slice +- Concat, Reduce +- Identity +- Shape + +In addition a Custom (user defined) operator is supported. An example of using a Custom operator is the program `tmva/pymva/test/EmitCustomModel.cxx`. + +The ONNX parser supports also the fusing of the operators MatMul + Add in a Gemm operator and fusing Conv + Add and ConvTranspose + Add. + +#### SOFIE Keras Parser + +The Keras parser supports now model with input batch size not defined (e.g `bathsize=-1`), and by default the model is generated with `batchsize=1`. +The Keras parser supports now in addition to the Dense layer the Conv2D layer, several activation functions (Relu, Selu, Sigmoid, Softmax, Tanh, LeakyRelu) and these other layers: BatchNormalization, Reshape, Convatenate, Add, Subtract, Multiply. +Models with Dropout layers are supported in case the Dropout is used only during training and not inference. + +For model having operators not yet supported in the Keras parser it is then reccomended to convert the Keras model to `ONNX` using the python `tf2onnx` tool. + +#### SOFIE PyTorch Parser + +If using PyTorch it is recommended to save the model directly in `ONNX` format instad of the native `.pt` format by using the `torch.onnx.export` function of PyTorch. The support for parsing directly `.pt` files is limited to the Gemm, Conv, Relu, Selu, Sigmoid and Transpose operators. + +#### SOFIE RDataFrame Integration + +The SOFIE inference is now integrated with RDataFrame, where a model can be evaluated on the columns of an input `TTree` with `RDataFrame` using the adapter functor class `SofieFunctor`. +Examples of using SOFIE with `RDataFrame` are the new tutorials (in the `tutorials/tmva` directory) `TMVA_SOFIE_RDataFrame.C` or `TMVA_SOFIE_RDataFrame.py`. `TMVA_SOFIE_RDataFrame_JIT.C` is an example where the SOFIE model is generated and compiled at runtime using ROOT Cling and evaluated using RDataFrame. + +#### RSofieReader + +`RSofieReader` is a new class, which takes as input a model file (in ONNX, Keras, PyTorch or ROOT format) and generates and compiles the C++ code for the inference at run time using the ROOT JITing capabilities of CLING. An example of using this class is the tutorial `TMVA_SOFIE_RSofieReader.C`. + +### TMVA Pythonizations + +New Pythonizations are available for TMVA allowing to replace the option string passed to several `TMVA` functions such as the `TMVA::Factory` constructor, the `DataLoader::PrepareTrainingAndTestTree` and `Factory::BookMethod` using Python function arguments. +For example instead of writing an option string `"NTrees=500:BoostType=AdaBoost"` one can use in Python `NTrees=500,BoostType='AdaBoost'`. +The new tmva tutorials `TMVA_Higgs_Classification.py`, `TMVA_CNN_Classificaion.py` and `TMVA_RNN_Classificaton.py` provide examples of using these new pythonizations. + + ## 2D Graphics Libraries - Implement the option "File": The current file name is painted on the bottom right of each plot @@ -363,6 +542,10 @@ accessing widget via configured ssh tunnel. ## Tutorials +- Several new tutorials have been added in both C++ and Python in the `tutorial/tmva` directory. + Tutorials like `TMVA_Higgs_Classification.py` shows the new pythonizations available in TMVA and + new `TMVA_SOFIE_...` tutorials show th eusage of SOFIE in both C++ or Python. + ## Class Reference Guide @@ -370,3 +553,25 @@ accessing widget via configured ssh tunnel. ## Build, Configuration and Testing Infrastructure - Building external applications that use ROOT oftentimes fail if there is a mismatch in the C++ standard between ROOT and the application. As of v6.28, suchs builds will issue a warning if the C++ standard does not match ROOT's, i.e. if there is a mismatch in the value of the `__cplusplus` preprocessor macro w.r.t. when ROOT was configured. + +## PyROOT + +- A `.rootlogon.py` file will be searched both in the current working directory and in the user's home directory. This +file is the Python equivalent of `rootlogon.C` and can be used to tweak ROOT settings when using PyROOT. +- A new pythonization for `TFile` now enables its usage as a Python context manager: +```python +from ROOT import TFile +with TFile("file1.root", "recreate") as outfile: + hout = ROOT.TH1F(...) + outfile.WriteObject(hout, "myhisto") +``` +- A new pythonization for `TDirectory::TContext` now enables its usage as a Python context manager: +```python +with TDirectory.TContext(): + # Open some file here + file = ROOT.TFile(...) + # Retrieve contents from the file + histo = file.Get("myhisto") + +# After the 'with' statement, the current directory is restored to ROOT.gROOT +``` diff --git a/README/ReleaseNotes/v630/index.md b/README/ReleaseNotes/v630/index.md new file mode 100644 index 0000000000000..63f09840c0906 --- /dev/null +++ b/README/ReleaseNotes/v630/index.md @@ -0,0 +1,331 @@ +% ROOT Version 6.30 Release Notes +% 2022-12-21 + + +## Introduction + +ROOT version 6.30/00 is scheduled for release in May, 2023. + +For more information, see: + +[http://root.cern](http://root.cern) + +The following people have contributed to this new version: + + Bertrand Bellenot, CERN/SFT,\ + Jakob Blomer, CERN/SFT,\ + Rene Brun, CERN/SFT,\ + Philippe Canal, FNAL,\ + Olivier Couet, CERN/SFT,\ + Gerri Ganis, CERN/SFT,\ + Andrei Gheata, CERN/SFT,\ + Enrico Guiraud, CERN/SFT,\ + Sergey Linev, GSI,\ + Javier Lopez-Gomez, CERN/SFT,\ + Pere Mato, CERN/SFT,\ + Lorenzo Moneta, CERN/SFT,\ + Axel Naumann, CERN/SFT,\ + Danilo Piparo, CERN/SFT,\ + Fons Rademakers, CERN/SFT,\ + Jonas Rembser, CERN/SFT,\ + Enric Tejedor Saavedra, CERN/SFT,\ + Matevz Tadel, UCSD/CMS,\ + Vassil Vassilev, Princeton/CMS,\ + Wouter Verkerke, NIKHEF/Atlas, + +## Deprecation and Removal +- `ROOT::RDF::RResultHandle::GetResultPtr` has been deprecated. Please use `RResultPtr` directly instead and only cast to `RResultHandle` in order to call `ROOT::RDF::RunGraphs`. +- The RDataFrame factory functions `MakeCsvDataFrame`, `MakeArrowDataFrame`, `MakeNTupleDataFrame` and `MakeSqliteDataFrame` that were deprecated in v6.28 have been removed. Use `FromCSV`, `FromArrow`, `FromRNTuple` or `FromSqlite` instead. +- The TStorage reallocation routine without a size (`TStorage::ReAlloc(void *ovp, size_t size`) and heap related routines (`TStorage::AddToHeap`, `TStorage::IsOnHeap`, `TStorage::GetHeapBegin`, `TStorage::GetHeapEnd`) that were deprecated in v6.02/00 have been removed. +- The deprecated `Format(const char* option, int sigDigits)` option for `RooAbsPdf::paramOn()` was removed. Please use the `Format(const char* option, ...)` overload that takes command arguments. +- The deprecated `RooAbsPdf::paramOn()` overload that directly takes a formatting string was removed. Please take the overload that uses command arguments. +- The `RooCatType` class was deprecated in ROOT 6.22 and its original `RooCatType.h` header is now removed. If you still need access to this class, please include `RooFitLegacy/RooCatTypeLegacy.h`. +- The `RooAbsString` that was only an alias for `RooStringVar` got removed. +- The `RooDataWeightedAverage` is now deprecated and will be removed in 6.32. It was only supposed to be an implementation detail of RooFits plotting that is now not necessary anymore. +- The `RooSpan` class was removed and its place in the implementation details of RooFit is now taken by `std::span`. +- The `RooAbsArg::isCloneOf()` and `RooAbsArg::getCloningAncestors()` member functions were removed because they didn't work (always returned `false` and an empty list respectively) +- `ROOT::Math::KelvinFunctions` had an incompatible license and needed to be removed without deprecation. +- The use of `ROOT_GIT_BRANCH` and `ROOT_GIT_COMMIT` have been deprecated in favor of parsing `etc/gitinfo.txt`. This later file is now generated as part of the build of ROOT; `RGitCommit.h` (defining `ROOT_GIT_BRANCH` and `ROOT_GIT_COMMIT`) is not updated anymore. This simplifies ROOT's build and release procedure. + +## Core Libraries + + +## I/O Libraries + + +## TTree Libraries + +## RNTuple +ROOT's experimental successor of TTree has seen a large number of updates during the last few months. Specifically, v6.30 includes the following changes: + +- Support for custom ROOT I/O rules that target transient members of a user-defined class (see PR [#11944](https://github.com/root-project/root/pull/11944)). If a rule only targets transient members and it was working in TTree, it should work unmodified in RNTuple. + +- Improved support for user-defined classes that behave as a collection. Specifically, RNTuple now relies on the iterator interface defined in `TVirtualCollectionProxy` (see PR [#12380](https://github.com/root-project/root/pull/12380) for details). +Note that associative collections are not yet supported. + +- Support for new field types: `std::bitset`, `std::unique_ptr`, `std::set`, `Double32_t`, scoped and unscoped enums with dictionary. + +- Full support for late model extension, which allows the RNTuple model to be extended after a `RNTupleWriter` has been created from the initial model (see PR [#12376](https://github.com/root-project/root/pull/12376)). +New top-level fields can be created at any time during the writing process. +On read-back, zero-initialized values are read for entries before the field was first seen. +The example below illustrates the use of this feature. +``` +auto model = RNTupleModel::Create(); +auto fieldPt = model->MakeField("pt", 42.0); +auto ntuple = RNTupleWriter::Recreate(std::move(model), "myNTuple", "out.ntuple"); +ntuple->Fill(); + +auto modelUpdater = ntuple->CreateModelUpdater(); +modelUpdater->BeginUpdate(); +std::array fieldArray; +modelUpdater->AddField>("array", &fieldArray); +modelUpdater->CommitUpdate(); + +// After this point, entries will have a new field of type `std::array` +ntuple->Fill(); +``` + +- Support for alternative column representations (Split / Zigzag encoding). These encodings allow for better compression and are used by default if compression is enabled. +Alternatively, users can pick a different column representation for a field by calling `RFieldBase::SetColumnRepresentative()`. + +- RNTuple now defaults to 64bit offset columns, which allow for representing large collections. +RNTuple can still use 32bit offset columns, e.g. +``` +RNTupleWriteOptions options; +options.SetHasSmallClusters(true); +auto writer = RNTupleWriter::Recreate(std::move(model), "myNTuple", "out.ntuple"); +``` + +- Support for projected fields, i.e. exposing other fields' data as a different (compatible) C++ type. +Users should provide a mapping function that maps each projected subfield in the tree to theunderlying real field, e.g. +``` +auto model = RNTupleModel::Create(); +auto fvec = model->MakeField>("vec"); + +auto aliasVec = RFieldBase::Create("aliasVec", "std::vector").Unwrap(); +model->AddProjectedField(std::move(aliasVec), [](const std::string &fieldName) { + if (fieldName == "aliasVec") return "vec"; + else return "vec._0"; +}); +``` +Projected fields are stored as part of the metadata. + +- Improvements on the internal `RField` value API. The `RFieldValue` class has been deprecated in favor of `RField::Value` and the related interfaces have changed accordingly (see [#13219](https://github.com/root-project/root/pull/13219) and [#13264](https://github.com/root-project/root/pull/13264)). +If you were not using `RField::(Read|Append)` directly, this change should not impact you. + +- The new `RNTupleImporter` class provides automatic conversion of TTree to RNTuple. +Note that not all of the C++ types supported in TTree are currently supported in RNTuple. + +- Many bug fixes and performance improvements + +Please, report any issues regarding the abovementioned features should you encounter them. +RNTuple is still experimental and is scheduled to become production grade by end of 2024. +Thus, we appreciate feedback and suggestions for improvement. + +## Histogram Libraries + + +## Math Libraries + +### Minuit2 is now the default minimizer + +Many ROOT-based frameworks and users employ Minuit2 as the minimizer of choice for a long time already. +Therefore, Minuit2 is now the default minimizer used by ROOT. +This affects also **RooFit**, which inherits the default minimizer from ROOT Math. + +The default can be changed back to the old Minuit implementation as follows: +```c++ +ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit"); +``` + +Alternatively, you can add this line to your `~/.rootrc` file: +``` +Root.Fitter: Minuit +``` + +### Behavior change of `TMath::AreEqualAbs()` + +The `TMath::AreEqualAbs()` compares two numbers for equality within a certain absolute range. +So far, it would tell you that `inf != inf` if you define `inf` as `std::numeric_limits::infinity()`, which is inconsistent with the regular `==` operator. + +This is unexpected, because one would expect that if two numbers are considered exactly equal, they would also be considered equal within any range. +Therefore, the behavior of `TMath::AreEqualAbs()` was changed to return always `true` if the `==` comparison would return `true`. + +## RooFit Libraries + +### Changes in RooFormulaVar and RooGenericPdf + +The TFormula-based RooFit classes `RooFormulaVar` and `RooGenericPdf` change a bit their behavior to be more consistent: + +1. No matter which variables you pass to the constructor, only the variables that the formula depends on are registered as value servers. +2. Similarly, the `dependents()` method of RooFormulaVar and RooGenericPdf will only return the list of actual value servers. + +### Removal of the RooGenFunction and RooMultiGenFunction classes + +The `RooGenFunction` was only a lightweight adaptor that exports a RooAbsReal as a `ROOT::Math::IGenFunction`. +The same can be easily achieved with the generic `ROOT::Math::Functor1D`, so in the spirit of not duplicating interfaces, the `RooGenFunction` is removed in this release. + +Here is an example that shows how to replace it in the unlikely case you were using it: + +```C++ +RooArgSet normSet{x}; // normalization set + +// Old way 1: create a RooGenFunction: +RooGenFunction func1{pdf, x, {}, normSet}; + +// Old way 2: use `RooAbsReal::iGenFunction()`: +std::unique_ptr func2{ + pdf.iGenFunction(x, normSet) +}; + +// How to do it now: +RooFunctor functor{pdf, x, {}, normSet}; +ROOT::Math::Functor1D func3{functor}; +// Functor1D takes by reference, so the RooFunctor also needs to stay alive. +``` + +For the same reason, the `RooMultiGenFunction` class that implements a multidimensional `ROOT::Math::IMultiGenFunction` is removed too. +It can easily be replaced by a `ROOT::Math::Functor`: + +```C++ +RooFunctor functor{pdf, observables, {}, normSet}; +ROOT::Math::Functor func4{functor, static_cast(functor.nObs())}; +// Functor takes by reference, so the RooFunctor also needs to stay alive. +``` + +### Define infinity as `std::numeric_limits::infinity()` + +RooFit has its internal representation of infinity in `RooNumber::infinity()`, which was `1e30` before. + +Now, it is defined as `std::numeric_limits::infinity()`, to be consistent with the C++ standard library and other code. + +This change also affects the `RooNumber::isInfinite()` function. + +### Remove `add(row, weight, weightError)` from RooAbsData interface + +It was not good to have this signature in RooAbsData, because the +implementations in the two derived classes RooDataHist and RooDataSet were +inconsistent. + +The RooDataSet indeed took the weight error as the third argument, but +the RooDataHist version instead took the sum of weights squared, which +is equivalent to the squared weight error. + +Therefore, the virtual `RooAbsData::add(row, weight, weightError)` function was removed. + +### Removal of `RooMomentMorphND` class + +The `RooMomentMorphND` and `RooMomentMorphFuncND` were almost exactly the same, +only that one inherited from `RooAbsPdf` and the other from `RooAbsReal`. + +Thanks to the `RooWrapperPdf`, this code duplication in the RooFit implementation can now be avoided. +Instead of using the removed `RooMomentMorphND` (which is the pdf), you now need to use the `RooMomentMorphFuncND`, +change its behavior to exactly match the formter `RooMomentMorphND`, and then wrap it into a pdf object: + +```C++ +RooMomentMorphFuncND func{}; + +func.setPdfMode(); // change behavior to be exactly like the former RooMomentMorphND + +// Pass the selfNormalized=true` flag to the wrapper because the +RooMomentMorphFuncND already normalizes itself in pdf mode. +RooWrapperPdf pdf{"pdf_name", "pdf_name", func, /*selfNormalized=*/true}; +``` + +### Removal of several internal classes from the public RooFit interface + +Several RooFit classes of which the headers are publicly exposed in the interface were only meant as implementation details of other RooFit classes. +Some of these classes are now removed from the public interface: + +1. `RooGenProdProj`, which was an implementation detail of the `RooProdPdf` +2. `RooScaledFunc`, which was an implementation detail of the plotting in RooFit + In the supposedly very rare case where you used this class in your own + implementations, just multiply the underlying RooAbsReal function with the + scale factor and create a RooRealBinding, e.g.: + ```c++ + RooProduct scaledFunc{"scaled_func", "", func, scaleFactor}; + RooRealBinding scaleBind(scaledFunc, x) ; + ``` + instead of: + ```c++ + RooRealBinding binding(func, x) ; + RooScaledFunc scaledBinding(binding, scaleFactor); + ``` +3. The `RooAbsRootFinder`, which was the base class of `RooBrentRootFinder`. + The `RooAbsRootFinder` was only used as the base class of + `RooBrentRootFinder`, which is an implementation detail of several + RooFit/RooStats functions. However, polymorphism never not relevant for root + finding, so the `RooAbsRootFinder` is removed. In the rare case where you + might have used it, please ROOT's other functionalities: RooFit is not for + root finding. +4. The `RooFormula` class, which was not meant as a user-facing class, but as a + shared implementation detail of `RooFormulaVar` and `RooGenericPdf`. +5. The `RooIntegratorBinding`, which was an implementation detail of the + `RooIntegrator2D` and `RooSegmentedIntegrator2D` classes. +6. The `RooRealAnalytic`, which was an implementation detail of the + `RooRealIntegral` class. + +### Consistent default for `Extended()` command in RooAbsPdf::fitTo() and RooAbsPdf::chi2FitTo() + +If no `RooFit::Extended()` command argument is passed, `RooAbsPdf::chi2FitTo()` +method now does an extended fit by default if the pdf is extendible. This makes +the behavior consistent with `RooAbsPdf::fitTo()`. Same applies to +`RooAbsPdf::createChi2()`. + +## 2D Graphics Libraries + +- Introduce `TAxis::ChangeLabelByValue` to set custom label defined by axis value. It works also + when axis zooming changes and position and index of correspondent axis label changes as well. + `TAxis::ChangeLabel` method to change axis label by index works as before. + +- Introduce `TCanvas::SaveAll` method. Allows to store several pads at once into different image file formats. + File name can include printf qualifier to code pad number. Also allows to store all pads in single PDF + or single ROOT file. Significantly improves performance when creating many image files using web graphics. + +- Introduce `TCanvas::UpdateAsync` method. In case of web-based canvas triggers update of the canvas on the client side, + but does not wait that real update is completed. Avoids blocking of caller thread. + Have to be used if called from other web-based widget to avoid logical dead-locks. + In case of normal canvas just canvas->Update() is performed. + + +## 3D Graphics Libraries + + +## Geometry Libraries + + +## Database Libraries + + +## Networking Libraries + + +## GUI Libraries + + +## Montecarlo Libraries + + +## PROOF Libraries + + +## Language Bindings + + +## JavaScript ROOT + + +## Tutorials + + +## Class Reference Guide + + +## Build, Configuration and Testing Infrastructure + +- If `-Droottest=ON` is specified, the ROOT build system used to clone a matching branch of the `roottest` repository. +This logic has been improved and is now as follows: +_(i)_ If the current head is a well-known branch, e.g. `master` or `v6-28-00-patches`, use the matching branch upstream; +_(ii)_ otherwise, try a branch that matches the name of the current head in the forked repository, if it exists; else try using the closest upstream head/tag below `HEAD`'s parent commit; +_(iii)_ as a last resort, if there is no preferred candidate, checkout the remote's default head. + diff --git a/bindings/experimental/distrdf/CMakeLists.txt b/bindings/experimental/distrdf/CMakeLists.txt index 2d2eff74582cf..a05f471e2949c 100644 --- a/bindings/experimental/distrdf/CMakeLists.txt +++ b/bindings/experimental/distrdf/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. +# Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. # All rights reserved. # # For the licensing terms see $ROOTSYS/LICENSE. @@ -8,13 +8,10 @@ # CMakeLists.txt file for building DistRDF ########################################################### -set(DistRDFDir python/DistRDF) -file(COPY ${DistRDFDir} DESTINATION ${localruntimedir}) - set(py_sources DistRDF/__init__.py + DistRDF/_graph_cache.py DistRDF/ComputationGraphGenerator.py - DistRDF/CppWorkflow.py DistRDF/DataFrame.py DistRDF/HeadNode.py DistRDF/Node.py @@ -29,8 +26,26 @@ set(py_sources DistRDF/Backends/Spark/Backend.py DistRDF/Backends/Dask/__init__.py DistRDF/Backends/Dask/Backend.py + DistRDF/LiveVisualize.py ) +# Add custom rules to copy the Python sources into the build directory +foreach(py_source ${py_sources}) + add_custom_command( + OUTPUT ${localruntimedir}/${py_source} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/python/${py_source} + ${localruntimedir}/${py_source} + DEPENDS python/${py_source} + COMMENT "Copying ${CMAKE_CURRENT_SOURCE_DIR}/python/${py_source}") + list(APPEND py_sources_in_localruntimedir ${localruntimedir}/${py_source}) +endforeach() + +# A custom target that depends on the Python sources being present in the build +# directory. This will be used as a dependency of the pythonization libraries, +# such that the Python sources get re-copied to the build directory when +# changed. +add_custom_target(DistRDF ALL DEPENDS ${py_sources_in_localruntimedir}) + # Compile .py files # We include DistRDF in the build only if Python 3.8+ is used, # so we can directly use the main Python executable to compile the sources diff --git a/bindings/experimental/distrdf/python/DistRDF/Backends/Base.py b/bindings/experimental/distrdf/python/DistRDF/Backends/Base.py index 343d80610eccf..1af91f383bd22 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Backends/Base.py +++ b/bindings/experimental/distrdf/python/DistRDF/Backends/Base.py @@ -23,6 +23,7 @@ # Type hints only if TYPE_CHECKING: + from DistRDF._graph_cache import ExecutionIdentifier from DistRDF.HeadNode import TaskObjects from DistRDF.Ranges import DataRange @@ -47,29 +48,15 @@ def setup_mapper(initialization_fn: Callable) -> None: def get_mergeable_values(starting_node: ROOT.RDF.RNode, range_id: int, - computation_graph_callable: Callable[[ROOT.RDF.RNode, int], List], optimized: bool) -> List: + computation_graph_callable: Callable[[ROOT.RDF.RNode, int], List], + exec_id: ExecutionIdentifier) -> List: """ Triggers the computation graph and returns a list of mergeable values. """ - if optimized: - # Create the RDF computation graph and execute it on this ranged - # dataset. The results of the actions of the graph and their types - # are returned - results, res_types = computation_graph_callable(starting_node, range_id) - - # Get RResultPtrs out of the type-erased RResultHandles by - # instantiating with the type of the value - mergeables = [ - ROOT.ROOT.Detail.RDF.GetMergeableValue(res.GetResultPtr[res_type]()) - if isinstance(res, ROOT.RDF.RResultHandle) - else res - for res, res_type in zip(results, res_types) - ] - else: - # Output of the callable - resultptr_list = computation_graph_callable(starting_node, range_id) - - mergeables = [Utils.get_mergeablevalue(resultptr) for resultptr in resultptr_list] + + actions = computation_graph_callable(starting_node, range_id, exec_id) + + mergeables = [Utils.get_mergeablevalue(action) for action in actions] return mergeables @@ -92,12 +79,11 @@ class TaskResult: def distrdf_mapper( - current_range: Union[Ranges.EmptySourceRange, Ranges.TreeRangePerc], + current_range: Ranges.DataRange, build_rdf_from_range: Callable[[Union[Ranges.EmptySourceRange, Ranges.TreeRangePerc]], TaskObjects], computation_graph_callable: Callable[[ROOT.RDF.RNode, int], List], - initialization_fn: Callable, - optimized: bool) -> TaskResult: + initialization_fn: Callable) -> TaskResult: """ Maps the computation graph to the input logical range of entries. """ @@ -110,7 +96,8 @@ def distrdf_mapper( # on the type of the head node. rdf_plus = build_rdf_from_range(current_range) if rdf_plus.rdf is not None: - mergeables = get_mergeable_values(rdf_plus.rdf, current_range.id, computation_graph_callable, optimized) + mergeables = get_mergeable_values(rdf_plus.rdf, current_range.id, computation_graph_callable, + current_range.exec_id) else: mergeables = None except ROOT.std.exception as e: @@ -118,6 +105,7 @@ def distrdf_mapper( return TaskResult(mergeables, rdf_plus.entries_in_trees) + def merge_values(mergeables_out: Iterable, mergeables_in: Iterable) -> Iterable: """ Merge values of second argument into values of first argument and return @@ -168,6 +156,7 @@ def distrdf_reducer(results_inout: TaskResult, return TaskResult(mergeables_updated, entries_in_trees_out) + class BaseBackend(ABC): """ Base class for RDataFrame distributed backends. diff --git a/bindings/experimental/distrdf/python/DistRDF/Backends/Dask/Backend.py b/bindings/experimental/distrdf/python/DistRDF/Backends/Dask/Backend.py index 32ccae2442f26..30650ac3b4b4c 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Backends/Dask/Backend.py +++ b/bindings/experimental/distrdf/python/DistRDF/Backends/Dask/Backend.py @@ -12,7 +12,9 @@ from __future__ import annotations import os -from typing import Any, Dict, Optional, TYPE_CHECKING +from typing import Any, Dict, List, Optional, Callable, TYPE_CHECKING, Union, Tuple +import math +import ROOT from DistRDF import DataFrame from DistRDF import HeadNode @@ -21,13 +23,14 @@ try: import dask - from dask.distributed import Client, get_worker, LocalCluster, progress + from dask.distributed import Client, get_worker, LocalCluster, progress, as_completed except ImportError: raise ImportError(("cannot import a Dask component. Refer to the Dask documentation " "for installation instructions.")) if TYPE_CHECKING: from dask_jobqueue import JobQueueCluster + from DistRDF import Ranges def get_total_cores_generic(client: Client) -> int: @@ -111,11 +114,63 @@ def optimize_npartitions(self) -> int: """ return get_total_cores(self.client) - def ProcessAndMerge(self, ranges, mapper, reducer): + @staticmethod + def dask_mapper(current_range: Tuple, + headers: List[str], + shared_libraries: List[str], + mapper: Callable) -> Callable: + """ + Gets the paths to the file(s) in the current executor, then + declares the headers found. + + Args: + current_range (tuple): The current range of the dataset being + processed on the executor. + + headers (list): List of header file paths. + + shared_libraries (list): List of shared library file paths. + + mapper (function): The map function to be executed on each executor. + + Returns: + function: The map function to be executed on each executor, + complete with all headers needed for the analysis. + """ + # Retrieve the current worker local directory + localdir = get_worker().local_directory + + # Get and declare headers on each worker + headers_on_executor = [ + os.path.join(localdir, os.path.basename(filepath)) + for filepath in headers + ] + Utils.declare_headers(headers_on_executor) + + # Get and declare shared libraries on each worker + shared_libs_on_ex = [ + os.path.join(localdir, os.path.basename(filepath)) + for filepath in shared_libraries + ] + Utils.declare_shared_libraries(shared_libs_on_ex) + + return mapper(current_range) + + def ProcessAndMerge(self, + ranges: List[Any], + mapper: Callable[[Ranges.DataRange, + Callable[[Union[Ranges.EmptySourceRange, Ranges.TreeRangePerc]], + Base.TaskObjects], + Callable[[ROOT.RDF.RNode, int], List], + Callable], + Base.TaskResult], + reducer: Callable[[Base.TaskResult, Base.TaskResult], Base.TaskResult], + ) -> Base.TaskResult: """ Performs map-reduce using Dask framework. Args: + ranges (list): A list of ranges to be processed. mapper (function): A function that runs the computational graph and returns a list of values. @@ -125,55 +180,11 @@ def ProcessAndMerge(self, ranges, mapper, reducer): Returns: list: A list representing the values of action nodes returned after computation (Map-Reduce). - """ - - # These need to be passed as variables, because passing `self` inside - # following `dask_mapper` function would trigger serialization errors - # like the following: - # - # AttributeError: Can't pickle local object 'DaskBackend.ProcessAndMerge..dask_mapper' - # TypeError: cannot pickle '_asyncio.Task' object - # - # Which boil down to the self.client object not being serializable - headers = self.headers - shared_libraries = self.shared_libraries - - def dask_mapper(current_range): - """ - Gets the paths to the file(s) in the current executor, then - declares the headers found. - - Args: - current_range (tuple): The current range of the dataset being - processed on the executor. - - Returns: - function: The map function to be executed on each executor, - complete with all headers needed for the analysis. - """ - # Retrieve the current worker local directory - localdir = get_worker().local_directory - - # Get and declare headers on each worker - headers_on_executor = [ - os.path.join(localdir, os.path.basename(filepath)) - for filepath in headers - ] - Utils.declare_headers(headers_on_executor) - - # Get and declare shared libraries on each worker - shared_libs_on_ex = [ - os.path.join(localdir, os.path.basename(filepath)) - for filepath in shared_libraries - ] - Utils.declare_shared_libraries(shared_libs_on_ex) - - return mapper(current_range) - - dmapper = dask.delayed(dask_mapper) + """ + dmapper = dask.delayed(DaskBackend.dask_mapper) dreducer = dask.delayed(reducer) - mergeables_lists = [dmapper(range) for range in ranges] + mergeables_lists = [dmapper(range, self.headers, self.shared_libraries, mapper) for range in ranges] while len(mergeables_lists) > 1: mergeables_lists.append( @@ -193,15 +204,159 @@ def dask_mapper(current_range): return final_results.compute() + def ProcessAndMergeLive(self, + ranges: List[Any], + mapper: Callable[[Ranges.DataRange, + Callable[[Union[Ranges.EmptySourceRange, Ranges.TreeRangePerc]], + Base.TaskObjects], + Callable[[ROOT.RDF.RNode, int], List], + Callable], + Base.TaskResult], + reducer: Callable[[Base.TaskResult, Base.TaskResult], Base.TaskResult], + drawables_info_dict: Dict[int, Tuple[List[Optional[Callable]], int, str]], + ) -> Base.TaskResult: + """ + Performs real-time map-reduce using Dask framework, retrieving the partial results + as soon as they are available, allowing real-time data representation. + + Args: + ranges (list): A list of ranges to be processed. + + mapper (function): A function that runs the computational graph + and returns a list of values. + + reducer (function): A function that merges two lists that were + returned by the mapper. + + drawables_info_dict (dict): A dictionary where keys are plot object IDs + and values are tuples containing optional callback functions, + index of the plot object, and operation name. + + Returns: + merged_results (TaskResult): The merged result of the computation. + """ + # Set up Dask mapper + dmapper = dask.delayed(DaskBackend.dask_mapper) + mergeables_lists = [dmapper(range, self.headers, self.shared_libraries, mapper) for range in ranges] + + # Compute the delayed tasks to get Dask futures that can be passed to the as_completed method + future_tasks = self.client.compute(mergeables_lists) + + # Save the current canvas + backend_pad = ROOT.TVirtualPad.TContext() + + # Set up live visualization canvas + c = self._setup_canvas(len(drawables_info_dict)) + + # Process partial results and display plots + merged_results = self._process_partial_results(c, drawables_info_dict, reducer, future_tasks) + + # Close the live visualization canvas canvas + c.Close() + + return merged_results + + def _setup_canvas(self, num_plots: int) -> ROOT.TCanvas: + """ + Set up a TCanvas for live visualization with divided pads based on the number of plots. + + Args: + num_plots (int): Number of plots to be displayed. + + Returns: + c: The initialized TCanvas object. + """ + # Define constants for canvas layout + CANVAS_WIDTH = 800 + CANVAS_HEIGHT = 400 + + canvas_rows = math.ceil(math.sqrt(num_plots)) + canvas_cols = math.ceil(num_plots / canvas_rows) + c = ROOT.TCanvas("distrdf_backend", "distrdf_backend", CANVAS_WIDTH * canvas_rows, CANVAS_HEIGHT * canvas_cols) + c.Divide(canvas_rows, canvas_cols) + + return c + + def _process_partial_results(self, + canvas: ROOT.TCanvas, + drawables_info_dict: Dict[int, Tuple[List[Optional[Callable]], int, str]], + reducer: Callable[[Base.TaskResult, Base.TaskResult], Base.TaskResult], + future_tasks: List[dask.Future]) -> Base.TaskResult: + """ + Process partial results and display plots on the provided canvas. + + Args: + canvas: The TCanvas object for displaying plots. + + drawables_info_dict (dict): A dictionary where keys are plot object IDs + and values are tuples containing optional callback functions, + index of the plot object, and operation name. + + reducer (function): A function for reducing partial results. + + future_tasks: Dask future tasks representing partial results. + + Returns: + merged_results (TaskResult): The merged result of the computation. + """ + merged_results: Base.TaskResult = None + cumulative_plots: Dict[int, Any] = {} + + # Collect all futures in batches that had arrived since the last iteration + for batch in as_completed(future_tasks, with_results=True).batches(): + for future, result in batch: + merged_results = reducer(merged_results, result) if merged_results else result + + mergeables = merged_results.mergeables + + for pad_num, (drawable_id, (callbacks_list, index, operation_name)) in enumerate(drawables_info_dict.items(), start=1): + cumulative_plots[index] = mergeables[index].GetValue() + + pad = canvas.cd(pad_num) + self._apply_callbacks_and_draw(pad, cumulative_plots, operation_name, index, callbacks_list) + + return merged_results + + def _apply_callbacks_and_draw(self, + pad: ROOT.TPad, + cumulative_plots: Dict[int, Any], + operation_name: str, + index: int, + callbacks_list: List[Optional[Callable]]) -> None: + """ + Apply callbacks and draw plots on the provided pad. + + Args: + pad: The TPad object for drawing plots. + + cumulative_plots: A dictionary of the current merged partial results. + + callbacks_list: A list of callback functions to be applied. + + operation_name (str): Name of the operation associated with the plot. + + index (int): Index of the plot in cumulative_plots dictionary. + """ + for callback in callbacks_list: + if callback is not None: + callback(cumulative_plots[index]) + + if operation_name in ["Graph", "GraphAsymmErrors"]: + cumulative_plots[index].Draw("AP") + else: + cumulative_plots[index].Draw() + + pad.Update() + def distribute_unique_paths(self, paths): """ - Dask supports sending files to the workes via the `Client.upload_file` + Dask supports sending files to the workers via the `Client.upload_file` method. Its stated purpose is to send local Python packages to the nodes, but in practice it uploads the file to the path stored in the `local_directory` attribute of each worker. """ for filepath in paths: - self.client.upload_file(filepath) + self.client.upload_file(filepath, load=False) def make_dataframe(self, *args, **kwargs): """ diff --git a/bindings/experimental/distrdf/python/DistRDF/Backends/Spark/Backend.py b/bindings/experimental/distrdf/python/DistRDF/Backends/Spark/Backend.py index 94f2f353b846a..e61945fbd1151 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Backends/Spark/Backend.py +++ b/bindings/experimental/distrdf/python/DistRDF/Backends/Spark/Backend.py @@ -12,6 +12,7 @@ from __future__ import annotations import ntpath # Filename from path (should be platform-independent) +import warnings from DistRDF import DataFrame from DistRDF import HeadNode @@ -134,6 +135,14 @@ def spark_mapper(current_range): # Map-Reduce using Spark return parallel_collection.map(spark_mapper).treeReduce(reducer) + def ProcessAndMergeLive(self, ranges, mapper, reducer, drawables_info_dict): + """ + Informs the user that the live visualization feature is not supported for the Spark backend + and refers to ProcessAndMerge to proceed with the standard map-reduce workflow. + """ + warnings.warn("The live visualization feature is not supported for the Spark backend. Skipping LiveVisualize.") + return self.ProcessAndMerge(ranges, mapper, reducer) + def distribute_unique_paths(self, paths): """ Spark supports sending files to the executors via the diff --git a/bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py b/bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py index 0ac480720464d..862d2051bcce5 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py +++ b/bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py @@ -186,7 +186,7 @@ def _(resultptr): of the dataset and the path to the partial snapshot. We can directly return the object, no extra work needed. """ - return resultptr + return SnapshotResult(resultptr.treename, resultptr.filenames) @singledispatch @@ -236,8 +236,43 @@ def _(mergeable: ROOT.Detail.RDF.RMergeableVariationsBase, node, backend): Connects the final value after distributed computation to the corresponding DistRDF node. In this overload, the node stores the reference to the mergeable variations - directly. It is then responsibility of the VariationsProxy object to access + directly. It is then responsibility of the ResultMapProxy object to access the specific varied object asked by the user, calling the right method of the RMergeableVariations class. """ node.value = mergeable + + +@singledispatch +def clone_action(result_promise, _): + """ + Clone the action held by an RResultPtr or RResultMap, registering it with + its RLoopManager. + """ + return ROOT.Internal.RDF.CloneResultAndAction(result_promise) + + +@clone_action.register(AsNumpyResult) +def _(asnumpyres, _): + asnumpyres._result_ptrs = { + col: ROOT.Internal.RDF.CloneResultAndAction(ptr) + for (col, ptr) in asnumpyres._result_ptrs.items() + } + return asnumpyres + + +@clone_action.register(SnapshotResult) +def _(snap, range_id: int): + # Create output file name for the cloned Snapshot + if snap.filenames[0].endswith(".root"): + name_with_old_id = snap.filenames[0][:-5] + else: + name_with_old_id = snap.filenames[0] + last_underscore = name_with_old_id.rfind("_") + basename = name_with_old_id[:last_underscore] + path_with_range = f"{basename}_{range_id}.root" + + # Actually clone the RDF C++ Snapshot node with the new file name + resptr = ROOT.Internal.RDF.CloneResultAndAction(snap._resultptr, path_with_range) + + return SnapshotResult(snap.treename, [path_with_range], resptr) diff --git a/bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py b/bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py index 3f62e1ee2e07a..2074656b7ce61 100644 --- a/bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py +++ b/bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py @@ -19,7 +19,8 @@ import ROOT -from DistRDF.CppWorkflow import CppWorkflow +from DistRDF._graph_cache import ExecutionIdentifier, _ACTIONS_REGISTER +from DistRDF.Backends import Utils from DistRDF.Operation import Action, AsNumpy, InstantAction, Operation, Snapshot, VariationsFor from DistRDF.PythonMergeables import SnapshotResult @@ -51,7 +52,7 @@ def _(operation: Union[Action, InstantAction], promise: Any, results: list) -> N @append_node_to_results.register def _(operation: Snapshot, promise: Any, results: list) -> None: - results.append(SnapshotResult(operation.args[0], [operation.args[1]])) + results.append(SnapshotResult(operation.args[0], [operation.args[1]], promise)) @singledispatch @@ -190,7 +191,8 @@ def generate_computation_graph(graph: Dict[int, Node], starting_node: ROOT.RDF.R return promises -def trigger_computation_graph(graph: Dict[int, Node], starting_node: ROOT.RDF.RNode, range_id: int) -> List: +def trigger_computation_graph( + graph: Dict[int, Node], starting_node: ROOT.RDF.RNode, range_id: int, exec_id: ExecutionIdentifier) -> List: """ Trigger the computation graph. @@ -213,7 +215,16 @@ def trigger_computation_graph(graph: Dict[int, Node], starting_node: ROOT.RDF.RN list: A list of objects that can be either used as or converted into mergeable values. """ - actions = generate_computation_graph(graph, starting_node, range_id) + if exec_id not in _ACTIONS_REGISTER: + # Fill the cache with the future results + actions = generate_computation_graph(graph, starting_node, range_id) + _ACTIONS_REGISTER[exec_id] = actions + else: + # Create clones according to different types of actions + actions = [ + Utils.clone_action(action, range_id) + for action in _ACTIONS_REGISTER[exec_id] + ] # Trigger computation graph with the GIL released rnode = ROOT.RDF.AsRNode(starting_node) @@ -226,30 +237,3 @@ def trigger_computation_graph(graph: Dict[int, Node], starting_node: ROOT.RDF.RN # an instance of `AsNumpyResult`. For `Snapshot`, it returns a # `SnapshotResult` return actions - - -def run_with_cppworkflow(graph: Dict[int, Node], starting_node: ROOT.RDF.RNode, range_id: int) -> Tuple[List, List[str]]: - """ - The callable that traverses the DistRDF graph nodes, generates the - code to create the same graph in C++, compiles it and runs it. - This function triggers the event loop via the CppWorkflow class. - - Args: - rdf_node (ROOT.RDF.RNode): The RDataFrame node that will serve as - the root of the computation graph. - range_id (int): Id of the current range. Needed to assign a name - to a partial Snapshot output file. - - Returns: - tuple[list, list]: the first element is the list of results of the actions - in the C++ workflow, the second element is the list of - result types corresponding to those actions. - """ - - # Generate the code of the C++ workflow - cpp_workflow = CppWorkflow(graph, starting_node, range_id) - - logger.debug(f"Generated C++ workflow is:\n{cpp_workflow}") - - # Compile and run the C++ workflow on the received RDF head node - return cpp_workflow.execute() diff --git a/bindings/experimental/distrdf/python/DistRDF/CppWorkflow.py b/bindings/experimental/distrdf/python/DistRDF/CppWorkflow.py deleted file mode 100644 index 57bc3c0a348d4..0000000000000 --- a/bindings/experimental/distrdf/python/DistRDF/CppWorkflow.py +++ /dev/null @@ -1,530 +0,0 @@ -# @author Enric Tejedor -# @date 2021-07 - -################################################################################ -# Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. # -# All rights reserved. # -# # -# For the licensing terms see $ROOTSYS/LICENSE. # -# For the list of contributors see $ROOTSYS/README/CREDITS. # -################################################################################ -from __future__ import annotations - -import os -from copy import deepcopy -from functools import singledispatch -from typing import Dict, List, NamedTuple, Tuple -from textwrap import dedent - -from DistRDF.Node import Node -from DistRDF.Operation import Action, AsNumpy, Operation, Snapshot -from DistRDF.PythonMergeables import SnapshotResult - -import ROOT - - -class _SnapshotData(NamedTuple): - res_id: int - treename: str - filename: str - - -class _PyActionData(NamedTuple): - res_id: int - operation: Operation - - -@singledispatch -def _create_lazy_op_if_needed(operation: Operation, _: int) -> Operation: - return operation - - -@_create_lazy_op_if_needed.register -def _(operation: AsNumpy, _: int) -> AsNumpy: - operation.kwargs["lazy"] = True - return operation - - -@_create_lazy_op_if_needed.register -def _(operation: Snapshot, range_id: int) -> Snapshot: - - op_modified = deepcopy(operation) - - # Retrieve filename and append range boundaries - filename = op_modified.args[1].partition(".root")[0] - path_with_range = "{}_{}.root".format(filename, range_id) - # Create a partial snapshot on the current range - op_modified.args[1] = path_with_range - - if len(op_modified.args) == 2: - # Only the first two mandatory arguments were passed - # Only the following overload is possible - # Snapshot(std::string_view treename, std::string_view filename, std::string_view columnNameRegexp = "") - op_modified.args.append("") # Append empty regex - - # Processing of RSnapshotOptions is very limited at the moment. - # An instance is created in the generated C++ code, with lazy option enabled - # by default. Here we just write a string in the position of the - # RSnapshotOptions argument, which will be detected when the code for this - # operation is generated down the line - if len(op_modified.args) == 4: - op_modified.args[3] = "lazy_options" - else: - op_modified.args.append("lazy_options") # Append RSnapshotOptions - - return op_modified - - -class CppWorkflow(object): - ''' - Class that encapsulates the generation of the code of an RDataFrame workflow - in C++, together with its compilation into a shared library and execution. - - This class is used by worker processes to execute in C++ the RDataFrame - graph they receive. This is done for the sake of performance, since running - the graph from Python necessarily relies on jitted code, which is less - optimized and thus slower than a shared library compiled with ACLiC. - - Attributes: - _CACHED_WFS (dict): uses as key the code of workflow functions that have - been already compiled and loaded by the current process, while the - value is the id of a given workflow function. Used to prevent - recompilation of already executed workflow functions. - - _FUNCTION_NAME (string): name of the function that encapsulates the - RDataFrame graph creation - - _FUNCTION_NAMESPACE (string): namespace of the function that - encapsulates the RDataFrame graph creation - - graph_nodes (Dict[int, Node]): The nodes of the computation graph. - - range_id (int): The id of the current range being processed. - - starting_node (ROOT.RDF.RNode): A reference to the C++ headnode of the - computation graph. - - _nodes_code (str): The part of the generated C++ code that includes the - representation of the nodes of the computation graph. - - _application_code (str): The final generated C++ application. - - _includes (string): include statements needed by the workflow. - - _lambdas (string): lambda functions used by the workflow. - - _lambda_id (int): counter used to generate ids for each defined lambda - function. - - _node_id (int): counter used to generate ids for each graph node. - - _py_actions (list): list that contains _PyActionData objects. - - _res_ptr_id (int): counter used to generate ids for each result - generated by graph actions. - - _snapshots (list): list that contains _SnapshotData objects - - _WF_ID_COUNTER (int): used to assign new ids to workflow functions - ''' - - _FUNCTION_NAME = '__RDF_WORKFLOW_FUNCTION__' - _FUNCTION_NAMESPACE = 'DistRDF_Internal' - - _CACHED_WFS: Dict[str, int] = {} - _WF_ID_COUNTER: int = 0 - - def __init__(self, graph_nodes: Dict[int, "Node"], starting_node: ROOT.RDF.RNode, range_id: int): - ''' - Generates the C++ code of an RDF workflow that corresponds to the - received graph and data range. - - Args: - head_node (Node): head node of a graph that represents an RDF - workflow. - range_id (int): id of the data range to be processed by this - workflow. Needed to assign a name to a partial Snapshot output - file. - ''' - - self._includes = dedent(''' - #include - #include - #include - #include "ROOT/RDataFrame.hxx" - #include "ROOT/RDFHelpers.hxx" - #include "ROOT/RResultHandle.hxx" - ''') - self._lambdas = '' - self._lambda_id = 0 - self._snapshots = [] - self._py_actions = [] - - # Generated C++ code with only the nodes of the computation graph - self._nodes_code: str = "" - # Counter to keep track of how many results the workflow is - # creating. Needed for the AsNumpy operation - self._res_ptr_id: int = 0 - # Full generated C++ application - self._application_code: str = None - - self.graph_nodes = graph_nodes - self.starting_node = ROOT.RDF.AsRNode(starting_node) - self.range_id = range_id - - self._handle_op = singledispatch(self._handle_op) - self._handle_op.register(Action, self._handle_action) - self._handle_op.register(Snapshot, self._handle_snapshot) - self._handle_op.register(AsNumpy, self._handle_asnumpy) - - # Generate the C++ workflow. - self._generate_computation_graph() - - @property - def application_code(self) -> str: - """Gather the full C++ application code in a string.""" - - if self._application_code is None: - # Gather the code for this instance only once - self._application_code = self._get_code() - return self._application_code - - def __repr__(self) -> str: - ''' - Generates a string representation for this C++ workflow. - ''' - - return self.application_code - - def _add_node(self, operation: Operation, node_id: int, parent_id: int): - """ - Generates the C++ code for a single node of the graph and adds it to the - internal string representation. Operations are first made lazy and the - Snapshot operation has special treatment to change the output filename. - """ - - operation = _create_lazy_op_if_needed(operation, self.range_id) - self._handle_op(operation, node_id, parent_id) - - def _compile(self) -> int: - ''' - Generates the workflow code C++ file and compiles it with ACLiC - into a shared library. The library is also loaded as part of the - `TSystem::CompileMacro` call. - - The name of the generated C++ file contains both a hash of its - code and the ID of the process that created it. This is done to - prevent clashes between multiple (non-sandboxed) worker processes - that try to write to the same file concurrently. - - A class-level cache keeps track of the workflows that have been already - compiled to prevent unncessary recompilation (e.g. when a worker - process runs multiple times the same workflow). - - Returns: - int: the id of the workflow function to be executed. Such id is - appended to CppWorkflow._FUNCTION_NAME to prevent name clashes - (a worker process might compile and load multiple workflow - functions). - ''' - - # TODO: Make this function thread-safe? To support Dask threaded - # workers - - code = self.application_code - this_wf_id = CppWorkflow._CACHED_WFS.get(code) - if this_wf_id is not None: - # We already compiled and loaded a workflow function with this - # code. Return the id of that function - return this_wf_id - - # We are trying to run this workflow for the first time in this - # process. First dump the code in a file with the right function name - this_wf_id = CppWorkflow._WF_ID_COUNTER - cpp_file_name = 'rdfworkflow_{wf_id}_{pid}.cxx' \ - .format(wf_id=this_wf_id, pid=os.getpid()) - final_code = code.replace(CppWorkflow._FUNCTION_NAME, CppWorkflow._FUNCTION_NAME + str(this_wf_id), 1) - - with open(cpp_file_name, 'w') as f: - f.write(final_code) - - # Now compile and load the code - if not ROOT.gSystem.CompileMacro(cpp_file_name, 'O'): - raise RuntimeError(f"Error compiling the RDataFrame workflow file: {cpp_file_name}") - - # Let the cache know there is a new workflow - CppWorkflow._CACHED_WFS[code] = this_wf_id - CppWorkflow._WF_ID_COUNTER += 1 - - return this_wf_id - - def _generate_computation_graph(self): - """ - Generates the RDataFrame computation graph from the nodes stored in the - input graph. - """ - - # Iterate over the other nodes stored in the dictionary, skipping the head - # node. We can iterate over the values knowing that the dictionary preserves - # the order in which it was created. Thus, we traverse the graph from top - # to bottom, in order to create the RDF nodes in the right order. - nodes = iter(self.graph_nodes.items()) - _ = next(nodes) - - for node_id, node in nodes: - self._add_node(node.operation, node_id, node.parent_id) - - def _get_args_call(self, operation: Operation) -> str: - ''' - Gets the arguments with which to generate the call to a given operation. - - Args: - operation (Operation): object representing the operation whose - call arguments need to be returned. - - Returns: - string: call arguments for this operation. - ''' - - # TODO - # - Do a more thorough type conversion - # - Use RDF helper functions to convert jitted strings to lambdas - - args = "" - - # Argument type conversion - for narg, arg in enumerate(operation.args): - if (narg > 0): - args += ', ' - - if arg == "lazy_options": - args += "lazy_options" - elif isinstance(arg, str): - args += '"{}"'.format(arg) - elif isinstance(arg, tuple): - args += '{' - for nelem, elem in enumerate(arg): - if nelem > 0: - args += ',' - if isinstance(elem, str): - args += '"{}"'.format(elem) - else: - args += '{}'.format(elem) - args += '}' - - return args - - def _get_args_template(self, operation: Operation) -> str: - ''' - Gets the template arguments with which to generate the call to a given - operation. - - Args: - operation (Operation): object representing the operation whose - template arguments need to be returned. - - Returns: - string: template arguments for this operation. - ''' - - # TODO: generate templated operations when possible, e.g. Max - - return '' - - def _get_code(self) -> str: - ''' - Composes the workflow generation code from the different attributes - of this class. The resulting code contains a function that will be - called to generate the RDataFrame graph. Such function returns a tuple - of three elements: - 1. A vector of results of the graph actions. - 2. A vector with the result types of those actions. - 3. A vector of RDF nodes that will be used in Python to invoke - Python-only actions on them (e.g. `AsNumpy`). - ''' - - code = ''' -{includes} - -namespace {namespace} {{ - -using CppWorkflowResult = std::tuple, - std::vector, - std::vector>; - -CppWorkflowResult {func_name}(ROOT::RDF::RNode &node0) -{{ - std::vector result_handles; - std::vector result_types; - std::vector output_nodes; - - // To make Snapshots lazy - ROOT::RDF::RSnapshotOptions lazy_options; - lazy_options.fLazy = true; - -{lambdas} - -{nodes} - - return {{ std::move(result_handles), std::move(result_types), std::move(output_nodes) }}; -}} - -}} // namespace {namespace} -'''.format(func_name=CppWorkflow._FUNCTION_NAME, - namespace=CppWorkflow._FUNCTION_NAMESPACE, - includes=self._includes, - lambdas=self._lambdas, - nodes=self._nodes_code) - - return code - - def _handle_action(self, operation: Action, node_id: int, parent_id: int): - """ - Generates the code for an Action operation. This needs the definition of - the node running the operation as in the generic case, plus storing the - RResultPtr into the vector of RResultHandles. - """ - - self._handle_op.dispatch(Operation)(operation, node_id, parent_id) - - # The result is stored in the vector of results to be returned - self._nodes_code += f"\n result_handles.emplace_back(node{node_id});" - - # The result type is stored in the vector of result types to be - # returned - err = f"Cannot get type of result {node_id} of action {operation.name} during generation of RDF C++ workflow" - self._nodes_code += ( - f'\n auto c{node_id} = TClass::GetClass(typeid(node{node_id}));' - f'\n if (c{node_id} == nullptr)' - f'\n throw std::runtime_error("{err}");' - f'\n result_types.emplace_back(c{node_id}->GetName());' - ) - - self._res_ptr_id += 1 - - def _handle_asnumpy(self, operation: AsNumpy, node_id: int, parent_id: int): - ''' - Since AsNumpy is a Python-only action, it can't be included in the - C++ workflow built by this class. Therefore, this function takes care - of saving the RDF node, generated in C++, on which an AsNumpy action - should be applied from Python. - ''' - - # Store DFS-order index of the AsNumpy operation, together with the - # operation information, for later invocation from Python - self._py_actions.append(_PyActionData(self._res_ptr_id, operation)) - - # Save parent RDF node to run AsNumpy on it later from Python - self._nodes_code += f"\n output_nodes.push_back(ROOT::RDF::AsRNode(node{parent_id}));" - - # Add placeholders to the result lists - self._nodes_code += ( - "\n result_handles.emplace_back();" - "\n result_types.emplace_back();" - ) - - self._res_ptr_id += 1 - - def _handle_op(self, operation: Operation, node_id: int, parent_id: int): - """ - Generates the code for a generic operation. - """ - - op_call = ( - f"node{parent_id}.{operation.name}{self._get_args_template(operation)}" - f"({self._get_args_call(operation)})" - ) - - self._nodes_code += f"\n auto node{node_id} = {op_call};" - - def _handle_snapshot(self, operation: Snapshot, node_id: int, parent_id: int): - ''' - Generates the code for the Snapshot operation. Stores the index of the - returned vector in which the result of this Snapshot is - stored, together with the modified file path. - ''' - - self._snapshots.append(_SnapshotData(self._res_ptr_id, operation.args[0], operation.args[1])) - self._handle_action(operation, node_id, parent_id) - - def _run_function(self, wf_id: int) -> Tuple[List, List[str]]: - ''' - Runs the workflow generation function. - - Args: - wf_id (int): identifier of the workflow function to be executed. - - Returns: - tuple: the first element is the list of results of the actions in - the C++ workflow, the second element is the list of result types - corresponding to those actions. - ''' - - ns = getattr(ROOT, CppWorkflow._FUNCTION_NAMESPACE) - func = getattr(ns, CppWorkflow._FUNCTION_NAME + str(wf_id)) - - # Run the workflow generator function - vectors = func(self.starting_node) # need to keep the tuple alive - v_results, v_res_types, v_nodes = vectors - - # Convert the vector of results into a list so that we can mix - # different types in it. - # We copy the results since the life of the original ones is tied to - # that of the vector - results = [ROOT.RDF.RResultHandle(res) for res in v_results] - - # Strip out the ROOT::RDF::RResultPtr<> part of the type - def get_result_type(s): - if s.empty(): - # Python-only actions have an empty return type in C++ - return '' - - s = str(s) - pos = s.find('<') - if pos == -1: - raise RuntimeError( - 'Error parsing the result types of RDataFrame workflow') - return s[pos+1:-1].strip() - - res_types = [get_result_type(elem) for elem in v_res_types] - - # Add Python-only actions on their corresponding nodes - for (res_ptr_id, operation), n in zip(self._py_actions, v_nodes): - operation.kwargs['lazy'] = True # make it lazy - results[res_ptr_id] = getattr(n, operation.name)(*operation.args, **operation.kwargs) - - if v_results: - # We trigger the event loop here, so make sure we release the GIL - RunGraphs = ROOT.RDF.RunGraphs - old_rg = RunGraphs.__release_gil__ - RunGraphs.__release_gil__ = True - RunGraphs(v_results) - RunGraphs.__release_gil__ = old_rg - - # Replace the RResultHandle of each Snapshot by its modified output - # path, since the latter is what we actually need in the reducer - for res_ptr_id, treename, path in self._snapshots: - results[res_ptr_id] = SnapshotResult(treename, [path]) - res_types[res_ptr_id] = None # placeholder - - # AsNumpyResult needs to be triggered before being merged - for i, operation in self._py_actions: - results[i].GetValue() - - return results, res_types - - def execute(self) -> Tuple[List, List[str]]: - ''' - Compiles the workflow generation code and executes it. - - Returns: - tuple: the first element is the list of results of the actions in - the C++ workflow, the second element is the list of result types - corresponding to those actions. - ''' - - wf_id = self._compile() - res = self._run_function(wf_id) - # TODO: it would be nice to remove all created artifacts - # after creation of the shared library. This is blocked by #10640 - return res diff --git a/bindings/experimental/distrdf/python/DistRDF/DataFrame.py b/bindings/experimental/distrdf/python/DistRDF/DataFrame.py index 00cd31fe8c7c8..bc9e80f9cb43c 100644 --- a/bindings/experimental/distrdf/python/DistRDF/DataFrame.py +++ b/bindings/experimental/distrdf/python/DistRDF/DataFrame.py @@ -35,7 +35,7 @@ def __init__(self, headnode: HeadNode) -> None: self._headnode = headnode - self._headproxy = Proxy.TransformationProxy(self._headnode) + self._headproxy = Proxy.NodeProxy(self._headnode) def __dir__(self) -> List[str]: opdir: List[str] = [ diff --git a/bindings/experimental/distrdf/python/DistRDF/HeadNode.py b/bindings/experimental/distrdf/python/DistRDF/HeadNode.py index 870a77da266b9..7bd4e9cc89294 100644 --- a/bindings/experimental/distrdf/python/DistRDF/HeadNode.py +++ b/bindings/experimental/distrdf/python/DistRDF/HeadNode.py @@ -2,6 +2,7 @@ from abc import ABC, abstractmethod import logging +import uuid import warnings from collections import Counter, deque @@ -12,7 +13,7 @@ import ROOT -from DistRDF import ComputationGraphGenerator, Ranges +from DistRDF import ComputationGraphGenerator, Ranges, _graph_cache from DistRDF.Backends.Base import distrdf_mapper, distrdf_reducer from DistRDF.Node import Node from DistRDF.Operation import Action, InstantAction, Operation @@ -89,6 +90,12 @@ def __init__(self, backend: BaseBackend, npartitions: Optional[int], localdf: RO # and so on. Thus, we need a top-down traversal. self.graph_nodes: Deque[Node] = deque([self]) + # Uniquely identify each computation graph execution of this RDataFrame + # The uuid can be set here + self.rdf_uuid = uuid.uuid4() + # The full identifier is created at the beginning of each execution + self.exec_id: _graph_cache.ExecutionIdentifier = None + # Internal attribute to keep track of the number of partitions. We also # check whether it was specified by the user when creating the dataframe. # If so, this attribute will not be updated when triggering. @@ -99,6 +106,11 @@ def __init__(self, backend: BaseBackend, npartitions: Optional[int], localdf: RO # column names. self._localdf = localdf + # A dictionary where the keys are the IDs of the objects to live visualize + # and the values are the corresponding callback functions + # This attribute only gets set in case the LiveVisualize() function is called + self.drawables_dict: Optional[Dict[int, List[Optional[Callable]]]] = None + @property def npartitions(self) -> Optional[int]: return self._npartitions @@ -180,8 +192,6 @@ def execute_graph(self) -> None: filled with the values that were computed distributedly so that they can be accessed in the application like with local RDataFrame. """ - # Check if the workflow must be generated in optimized mode - optimized = ROOT.RDF.Experimental.Distributed.optimized # Updates the number of partitions for this dataframe if the user did # not specify one initially. This is done each time the computations are @@ -189,27 +199,46 @@ def execute_graph(self) -> None: # between runs (e.g. changing the number of available cores). self.npartitions = self.backend.optimize_npartitions() - if optimized: - computation_graph_callable = partial( - ComputationGraphGenerator.run_with_cppworkflow, self._generate_graph_dict()) - else: - computation_graph_callable = partial( - ComputationGraphGenerator.trigger_computation_graph, self._generate_graph_dict()) + self.exec_id = _graph_cache.ExecutionIdentifier(self.rdf_uuid, uuid.uuid4()) + + + computation_graph_callable = partial(ComputationGraphGenerator.trigger_computation_graph, self._generate_graph_dict()) mapper = partial(distrdf_mapper, build_rdf_from_range=self._generate_rdf_creator(), computation_graph_callable=computation_graph_callable, - initialization_fn=self.backend.initialization, - optimized=optimized) + initialization_fn=self.backend.initialization) + + # List of action nodes in the same order as values + local_nodes = self._get_action_nodes() + + # Execute graph distributedly and return the aggregated results from all tasks + # using the appropriate backend method based on whether or not live visualization is enabled + if self.drawables_dict is not None: + # Prepare a dictionary with additional information for live visualization + drawables_info_dict = { + # Key: node_id + node.node_id: ( + # Tuple containing: + # 1. Callback functions passed by the user + self.drawables_dict[node.node_id], + # 2. Index of the node in the local_nodes list + i, + # 3. Name of the operation associated with the node + node.operation.name + ) + for i, node in enumerate(local_nodes) + # Filter: Only include nodes requested by the user + if node.node_id in self.drawables_dict + } + returned_values = self.backend.ProcessAndMergeLive(self._build_ranges(), mapper, distrdf_reducer, drawables_info_dict) + else: + returned_values = self.backend.ProcessAndMerge(self._build_ranges(), mapper, distrdf_reducer) - # Execute graph distributedly and return the aggregated results from all - # tasks - returned_values = self.backend.ProcessAndMerge(self._build_ranges(), mapper, distrdf_reducer) # Perform any extra checks that may be needed according to the # type of the head node final_values = self._handle_returned_values(returned_values) - # List of action nodes in the same order as values - local_nodes = self._get_action_nodes() + # Set the value of every action node for node, value in zip(local_nodes, final_values): Utils.set_value_on_node(value, node, self.backend) @@ -296,7 +325,7 @@ def _build_ranges(self) -> List[Ranges.DataRange]: "in the dataframe. Using {1} partition(s)".format(self.npartitions, self.nentries)) warnings.warn(msg, UserWarning, stacklevel=2) self.npartitions = self.nentries - return Ranges.get_balanced_ranges(self.nentries, self.npartitions) + return Ranges.get_balanced_ranges(self.nentries, self.npartitions, self.exec_id) def _generate_rdf_creator(self) -> Callable[[Ranges.DataRange], TaskObjects]: """ @@ -311,7 +340,16 @@ def build_rdf_from_range(current_range): """ Builds an RDataFrame instance for a distributed mapper. """ - return TaskObjects(ROOT.RDataFrame(nentries).Range(current_range.start, current_range.end), None) + if current_range.exec_id not in _graph_cache._RDF_REGISTER: + rdf_toprocess = ROOT.RDataFrame(nentries) + _graph_cache._RDF_REGISTER[current_range.exec_id] = rdf_toprocess + else: + rdf_toprocess = _graph_cache._RDF_REGISTER[current_range.exec_id] + + ROOT.Internal.RDF.ChangeEmptyEntryRange( + ROOT.RDF.AsRNode(rdf_toprocess), (current_range.start, current_range.end)) + + return TaskObjects(rdf_toprocess, None) return build_rdf_from_range @@ -377,6 +415,15 @@ def __init__(self, backend: BaseBackend, npartitions: Optional[int], localdf: RO if isinstance(args[0], ROOT.TTree): # RDataFrame(tree, defaultBranches = {}) self.tree = args[0] + # TTreeIndex is not supported in distributed RDataFrame + list_of_friends = self.tree.GetListOfFriends() + if list_of_friends and list_of_friends.GetEntries() > 0: + for friend_element in list_of_friends: + if friend_element.GetTree().GetTreeIndex(): + raise ValueError( + f"Friend tree '{friend_element.GetName()}' has a TTreeIndex. " + "This is not supported in distributed mode." + ) # Retrieve information about friend trees when user passes a TTree # or TChain object. fi = ROOT.Internal.TreeUtils.GetFriendInfo(args[0]) @@ -435,7 +482,7 @@ def _build_ranges(self) -> List[Ranges.DataRange]: "chunks the dataset can be split in. Some tasks could be doing no work. Consider " "setting the 'npartitions' parameter of the RDataFrame constructor to a lower value.") - return Ranges.get_percentage_ranges(self.subtreenames, self.inputfiles, self.npartitions, self.friendinfo) + return Ranges.get_percentage_ranges(self.subtreenames, self.inputfiles, self.npartitions, self.friendinfo, self.exec_id) def _generate_rdf_creator(self) -> Callable[[Ranges.DataRange], TaskObjects]: """ @@ -483,13 +530,23 @@ def build_rdf_from_range(current_range: Ranges.TreeRangePerc) -> TaskObjects: return TaskObjects(None, entries_in_trees) ds = ROOT.RDF.Experimental.RDatasetSpec() - # add a group with no name to represent the whole dataset - ds.AddGroup(("", clustered_range.treenames, clustered_range.filenames)) + # add a sample with no name to represent the whole dataset + ds.AddSample(("", clustered_range.treenames, clustered_range.filenames)) ds.WithGlobalRange((clustered_range.globalstart, clustered_range.globalend)) attach_friend_info_if_present(clustered_range, ds) - return TaskObjects(ROOT.RDataFrame(ds), entries_in_trees) + if current_range.exec_id not in _graph_cache._RDF_REGISTER: + rdf_toprocess = ROOT.RDataFrame(ds) + # Fill the cache with the new RDataFrame + _graph_cache._RDF_REGISTER[current_range.exec_id] = rdf_toprocess + else: + # Retrieve an already present RDataFrame from the cache + rdf_toprocess = _graph_cache._RDF_REGISTER[current_range.exec_id] + # Update it to the range of entries for this task + ROOT.Internal.RDF.ChangeSpec(ROOT.RDF.AsRNode(rdf_toprocess), ROOT.std.move(ds)) + + return TaskObjects(rdf_toprocess, entries_in_trees) return build_rdf_from_range diff --git a/bindings/experimental/distrdf/python/DistRDF/LiveVisualize.py b/bindings/experimental/distrdf/python/DistRDF/LiveVisualize.py new file mode 100644 index 0000000000000..f39551cc8365d --- /dev/null +++ b/bindings/experimental/distrdf/python/DistRDF/LiveVisualize.py @@ -0,0 +1,198 @@ +# @author Silia Taider +# @date 2023-08 + +################################################################################ +# Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. # +# All rights reserved. # +# # +# For the licensing terms see $ROOTSYS/LICENSE. # +# For the list of contributors see $ROOTSYS/README/CREDITS. # +################################################################################ +from __future__ import annotations + +from typing import Dict, Optional, Callable, Any +import ast +import inspect +import warnings +from functools import singledispatch, partial + + +@singledispatch +def LiveVisualize(drawable_callback_dict: Dict[Any, Optional[Callable]], + global_callback: Optional[Callable] = None) -> None: + """ + Enables real-time data representation for the given drawable objects. + The objects are drawn and updated every time a partial result returns from distributed execution. + + Args: + drawable_callback_dict (dict): A dictionary where keys are drawable objects + and values are optional corresponding callback functions. + + global_callback (function): An optional global callback function that + is applied to all drawable objects. + + Raises: + ValueError: If a passed drawable object is not valid. + """ + # Check if the objects already have a value (the computation graph has already been triggered) + if any(obj.proxied_node.value for obj in drawable_callback_dict): + warnings.warn("LiveVisualize should be called before triggering the computation graph. Skipping live visualization.") + return + + # Check if all drawables share the same headnode + unique_headnodes = list({obj.proxied_node.get_head() for obj in drawable_callback_dict}) + if len(unique_headnodes) > 1: + raise ValueError("Live visualization is not supported for operations belonging to different RDataFrame graphs.") + + global_callback_validated = process_callback(global_callback) + drawable_id_callback_dict = { + # Key: node_id of the drawable object's proxied_node + # Value: List of validated callback functions for the drawable object + obj.proxied_node.node_id: [process_callback(callback), global_callback_validated] + for obj, callback in drawable_callback_dict.items() + # Filter: Only include valid drawable objects + if is_valid_drawable(obj) + } + + unique_headnodes[0].drawables_dict = drawable_id_callback_dict + + +@LiveVisualize.register(list) +@LiveVisualize.register(tuple) +def _1(drawables, callback: Optional[Callable] = None) -> None: + """ + Wrapper function to facilitate calling LiveVisualize with a list or a tuple of drawable objects. + + Args: + drawables (list | tuple): Drawable objects to visualize. + + callback (function): An optional callback function to be applied to the drawable objects. + + Notes: + This function constructs a dictionary of drawable objects and their associated callback functions, + and then calls the main LiveVisualize function with the constructed dictionary. + """ + if callback is None: + drawable_callback_dict = {obj: None for obj in drawables} + else: + drawable_callback_dict = {obj: callback for obj in drawables} + + LiveVisualize(drawable_callback_dict) + + +def process_callback(callback: Callable) -> Callable: + """ + Process and validate a callback function. + + Args: + callback: The callback function to be validated. + + Returns: + validated_callback: The validated callback function, or None if not valid. + """ + if callback is None: + return None + + elif not callable(callback): + warnings.warn("The provided callback is not callable. Skipping callback.") + return None + + elif not has_correct_argument_count(callback): + warnings.warn("The callback function should have exactly one parameter to fill. Skipping callback.") + return None + + elif not is_callback_safe(callback): + warnings.warn("The provided callback function contains blocked actions. Skipping callback.") + return None + + return callback + + +def has_correct_argument_count(callback: Callable) -> bool: + """ + Checks if the provided callback function has exactly one unfilled argument. + + Args: + callback (Callable): The callback function to check. + + Returns: + bool: True if the callback function has exactly one unfilled argument, + False otherwise. + """ + # Get the values of the functions parameters + unfilled_parameters = [param for param in inspect.signature(callback).parameters.values() if param.default == param.empty] + if len(unfilled_parameters) != 1: + return False + + return True + + +def is_callback_safe(callback: Callable) -> bool: + """ + Checks if the provided callback function is safe for live visualization, + (does not contain blocked actions). + + Args: + callback (function): The callback function to check. + + Returns: + bool: True if the callback function is safe, + False otherwise. + """ + # Parse the callback function's source code + if isinstance(callback, partial): + callback = callback.func + callback_source_ast = ast.parse(inspect.getsource(callback)) + for node in ast.walk(callback_source_ast): + if is_action_blocked(node): + return False + + return True + + +def is_action_blocked(node: ast.AST) -> bool: + """ + Checks if the given Abstract Syntax Tree (AST) node corresponds to a blocked action. + + Args: + node (ast.AST): The AST node to check. + + Returns: + bool: True if the AST node corresponds to a blocked action, + False otherwise. + """ + BLOCKED_ACTIONS = [ "Add", "AddBinContent", "BufferFill", "Build", "ClearUnderflowAndOverflow", + "Delete", "Divide", "DoFillN", "Fill", "FillN", "FillRandom", "LabelsDeflate", + "Merge", "Multiply", "Rebin", "Rebuild", "RecursiveRemove", "Reset", "Scale", + "SetBinContent", "SetBinError", "SetBins", "SetBinsLength", "SetBuffer", + "SetCellContent", "SetCellError", "SetContent", "SetDirectory", "SetEntries", + "SetError", "SetMaximum", "SetMinimum", "Smooth", "TransformHisto", + "UpdateBinContent"] + + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in BLOCKED_ACTIONS: + return True + + return False + + +def is_valid_drawable(obj: Any) -> bool: + """ + Checks if the object is a valid drawable object for live visualization. + + Args: + obj: The object to be checked. + + Returns: + bool: True if the object is a valid drawable object for live visualization + according to the ALLOWED_OPERATIONS list , False otherwise. + """ + ALLOWED_OPERATIONS = ["Histo1D", "Histo2D", "Histo3D", + "Graph", "GraphAsymmErrors", + "Profile1D", "Profile2D"] + + if hasattr(obj, "proxied_node") and hasattr(obj.proxied_node, "operation") and hasattr(obj.proxied_node.operation, "name"): + if obj.proxied_node.operation.name in ALLOWED_OPERATIONS: + return True + + raise ValueError(f"Allowed operations are: {ALLOWED_OPERATIONS}. Skipping live visualization.") + \ No newline at end of file diff --git a/bindings/experimental/distrdf/python/DistRDF/Operation.py b/bindings/experimental/distrdf/python/DistRDF/Operation.py index a37bda9b53fb6..a578492e47fd1 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Operation.py +++ b/bindings/experimental/distrdf/python/DistRDF/Operation.py @@ -95,6 +95,7 @@ class Transformation(Operation): "DefinePerSample": Transformation, "Filter": Transformation, "Graph": Action, + "GraphAsymmErrors": Action, "Histo1D": Histo, "Histo2D": Histo, "Histo3D": Histo, diff --git a/bindings/experimental/distrdf/python/DistRDF/Proxy.py b/bindings/experimental/distrdf/python/DistRDF/Proxy.py index 7f50398ce6606..e47e7926f7745 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Proxy.py +++ b/bindings/experimental/distrdf/python/DistRDF/Proxy.py @@ -108,11 +108,11 @@ def __del__(self): self.proxied_node.has_user_references = False -class VariationsProxy(Proxy): +class ResultMapProxy(Proxy): """ - Instances of VariationsProxy act as futures of the result produced + Instances of ResultMapProxy act as futures of the result produced by a call to DistRDF.VariationsFor. The aim is to mimic the functionality of - ROOT::RDF::Experimental::RResultMap. + ROOT::RDF::Experimental::RResultMap to provide the same API usage. """ def __init__(self, node: Node): @@ -124,7 +124,7 @@ def __getattr__(self, attr): The __getattr__ of the Proxy base class is an abstract method. This class has no attributes to present to the user. """ - raise AttributeError(f"'VariationsProxy' object has no attribute '{attr}'") + raise AttributeError(f"'ResultMapProxy' object has no attribute '{attr}'") def __getitem__(self, key: str): """ @@ -161,12 +161,11 @@ def GetKeys(self) -> List[str]: return self._keys -class ActionProxy(Proxy): +class ResultPtrProxy(Proxy): """ - Instances of ActionProxy act as futures of the result produced - by some action node. They implement a lazy synchronization - mechanism, i.e., when they are accessed for the first time, - they trigger the execution of the whole RDataFrame graph. + Instances of ResultPtrProxy act as futures of the result produced + by some action node. The aim is to mimic the functionality of + ROOT::RDF::RResultPtr to provide the same API usage. """ def __getattr__(self, attr): @@ -197,20 +196,21 @@ def _call_action_result(self, *args, **kwargs): """ return getattr(self.GetValue(), self._cur_attr)(*args, **kwargs) - def create_variations(self) -> VariationsProxy: + def create_variations(self) -> ResultMapProxy: """ Creates a node responsible to signal the creation of variations in the distributed computation graph, returning a specialized proxy to that node. This function is usually called from DistRDF.VariationsFor. """ - return VariationsProxy(_create_new_node(self.proxied_node, Operation.create_op("VariationsFor"))) + return ResultMapProxy(_create_new_node(self.proxied_node, Operation.create_op("VariationsFor"))) -class TransformationProxy(Proxy): +class NodeProxy(Proxy): """ A proxy object to an non-action node. It implements acces to attributes and methods of the proxied node. It is also in charge of the creation of - a new operation node in the graph. + a new operation node in the graph. The aim is to mimic the functionality of + ROOT::RDF::RNode to provide the same API usage. """ def __getattr__(self, attr): @@ -254,14 +254,14 @@ def _create_new_op(self, *args, **kwargs): @singledispatch -def get_proxy_for(operation: Operation.Transformation, node: Node) -> TransformationProxy: +def get_proxy_for(operation: Operation.Transformation, node: Node) -> NodeProxy: """"Returns appropriate proxy for the input node""" - return TransformationProxy(node) + return NodeProxy(node) @get_proxy_for.register -def _(operation: Operation.Action, node: Node) -> ActionProxy: - return ActionProxy(node) +def _(operation: Operation.Action, node: Node) -> ResultPtrProxy: + return ResultPtrProxy(node) @get_proxy_for.register @@ -271,7 +271,7 @@ def _(operation: Operation.InstantAction, node: Node) -> Any: @get_proxy_for.register -def _(operation: Operation.Snapshot, node: Node) -> Union[ActionProxy, Any]: +def _(operation: Operation.Snapshot, node: Node) -> Union[ResultPtrProxy, Any]: if len(operation.args) == 4: # An RSnapshotOptions instance was passed as fourth argument if operation.args[3].fLazy: @@ -281,7 +281,7 @@ def _(operation: Operation.Snapshot, node: Node) -> Union[ActionProxy, Any]: @get_proxy_for.register -def _(operation: Operation.AsNumpy, node: Node) -> Union[ActionProxy, Any]: +def _(operation: Operation.AsNumpy, node: Node) -> Union[ResultPtrProxy, Any]: if operation.kwargs.get("lazy", False): return get_proxy_for.dispatch(Operation.Action)(operation, node) diff --git a/bindings/experimental/distrdf/python/DistRDF/PythonMergeables.py b/bindings/experimental/distrdf/python/DistRDF/PythonMergeables.py index 97cd678da7506..7b42a4b69f470 100644 --- a/bindings/experimental/distrdf/python/DistRDF/PythonMergeables.py +++ b/bindings/experimental/distrdf/python/DistRDF/PythonMergeables.py @@ -1,8 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import Union, List, TYPE_CHECKING import ROOT +from ROOT._pythonization._rdataframe import AsNumpyResult if TYPE_CHECKING: from DistRDF.Backends.Base import BaseBackend @@ -14,9 +15,13 @@ class SnapshotResult(object): merge it with other objects of this type. """ - def __init__(self, treename: str, filenames: list[str]) -> None: + def __init__(self, treename: str, filenames: List[str], resultptr: ROOT.RDF.RResultPtr = None) -> None: self.treename = treename self.filenames = filenames + # Transient attribute, it will be discarded before the end of the mapper + # function (in `Utils.get_mergeablevalue`) so that we don't incur in + # serialization of the RResultPtr + self._resultptr = resultptr def Merge(self, other: SnapshotResult) -> None: """ @@ -48,3 +53,7 @@ def GetValue(self, backend: BaseBackend): snapshot_chain.Add(filename) # Create a new rdf with the chain and return that to user return backend.make_dataframe(snapshot_chain) + + +# A type alias to signify any type of result that can be returned from the RDataFrame API +RDataFrameFutureResult = Union[ROOT.RDF.RResultPtr, ROOT.RDF.Experimental.RResultMap, SnapshotResult, AsNumpyResult] diff --git a/bindings/experimental/distrdf/python/DistRDF/Ranges.py b/bindings/experimental/distrdf/python/DistRDF/Ranges.py index 49f4ec0d1ef91..d27273051e11d 100644 --- a/bindings/experimental/distrdf/python/DistRDF/Ranges.py +++ b/bindings/experimental/distrdf/python/DistRDF/Ranges.py @@ -7,88 +7,80 @@ from itertools import accumulate from math import floor -from typing import Dict, List, Optional, Tuple +from typing import Dict, List, Optional, Tuple, TYPE_CHECKING + +if TYPE_CHECKING: + from DistRDF._graph_cache import ExecutionIdentifier import ROOT logger = logging.getLogger(__name__) +@dataclass class DataRange: """ A logical range of entries in which a dataset is split. Depending on the input data source, this can have different attributes. + + Attributes: + + exec_id: An identifier for the current execution. + + id: A sequential counter to identify this range. """ - pass + exec_id: ExecutionIdentifier + id: int +@dataclass class EmptySourceRange(DataRange): """ Empty source range of entries Attributes: - id (int): Sequential counter to identify this range. It is used to assign - a filename to a partial Snapshot in case it was requested. The id is - assigned in `get_balanced_ranges` to ensure that each distributed - RDataFrame run has a list of ranges with sequential ids starting from - zero. - start (int): Starting entry of this range. end (int): Ending entry of this range. """ + start: int + end: int - def __init__(self, rangeid, start, end): - """set attributes""" - self.id = rangeid - self.start = start - self.end = end - - -def get_balanced_ranges(nentries, npartitions): - """ - Builds range pairs from the given values of the number of entries in - the dataset and number of partitions required. Each range contains the - same amount of entries, except for those cases where the number of - entries is not a multiple of the partitions. - - Args: - nentries (int): The number of entries in a dataset. - - npartitions (int): The number of partititions the sequence of entries - should be split in. - Returns: - list[DistRDF.Ranges.EmptySourceRange]: Each element of the list contains - the start and end entry of the corresponding range. +@dataclass +class TreeRangePerc(DataRange): """ + Range of percentages to be considered for a list of trees. Building block + for an actual range of entries of a distributed task. - partition_size = nentries // npartitions + Attributes: - i = 0 # Iterator + treenames: List of tree names. - ranges = [] + filenames: List of files to be processed with this range. - remainder = nentries % npartitions + first_file_idx: Index of the first file that this range will consider. - rangeid = 0 # Keep track of the current range id - while i < nentries: - # Start value of current range - start = i - end = i = start + partition_size + last_file_idx: Index of the last file that this range will consider. - if remainder: - # If the modulo value is not - # exhausted, add '1' to the end - # of the current range - end = i = end + 1 - remainder -= 1 + first_tree_start_perc: Percentage of the first tree from which this range will + begin reading entries. - ranges.append(EmptySourceRange(rangeid, start, end)) - rangeid += 1 + last_tree_end_perc: Percentage of the last tree at which this range will + end reading entries. - return ranges + friendinfo: Information about friend trees of the chain built for this + range. Not None if the user provided a TTree or TChain in the + distributed RDataFrame constructor. + """ + treenames: List[str] + filenames: List[str] + first_file_idx: int + last_file_idx: int + first_tree_start_perc: float + last_tree_end_perc: float + friendinfo: Optional[ROOT.Internal.TreeUtils.RFriendInfo] @dataclass @@ -102,9 +94,6 @@ class TreeRange(DataRange): Attributes: - id: Sequential counter to identify this range. It is used to assign a - filename to a partial Snapshot in case it was requested. - treenames: List of tree names. filenames: List of files to be processed with this range. @@ -119,8 +108,6 @@ class TreeRange(DataRange): range. Not None if the user provided a TTree or TChain in the distributed RDataFrame constructor. """ - - id: int treenames: List[str] filenames: List[str] globalstart: int @@ -128,22 +115,6 @@ class TreeRange(DataRange): friendinfo: Optional[ROOT.Internal.TreeUtils.RFriendInfo] -@dataclass -class TreeRangePerc(DataRange): - """ - Range of percentages to be considered for a list of trees. Building block - for an actual range of entries of a distributed task. - """ - id: int - treenames: List[str] - filenames: List[str] - first_file_idx: int - last_file_idx: int - first_tree_start_perc: float - last_tree_end_perc: float - friendinfo: Optional[ROOT.Internal.TreeUtils.RFriendInfo] - - @dataclass class TaskTreeEntries: """ @@ -157,6 +128,50 @@ class TaskTreeEntries: trees_with_entries: Dict[str, int] = field(default_factory=dict) +def get_balanced_ranges(nentries, npartitions, exec_id: ExecutionIdentifier): + """ + Builds range pairs from the given values of the number of entries in + the dataset and number of partitions required. The `nentries` are divided + uniformly among the `npartitions`. + + Args: + nentries (int): The number of entries in a dataset. + + npartitions (int): The number of partititions the sequence of entries + should be split in. + + Returns: + list[DistRDF.Ranges.EmptySourceRange]: Each element of the list contains + the start and end entry of the corresponding range. + """ + + partition_size = nentries // npartitions + + i = 0 # Iterator + + ranges = [] + + remainder = nentries % npartitions + + rangeid = 0 # Keep track of the current range id + while i < nentries: + # Start value of current range + start = i + end = i = start + partition_size + + if remainder: + # If the modulo value is not + # exhausted, add '1' to the end + # of the current range + end = i = end + 1 + remainder -= 1 + + ranges.append(EmptySourceRange(exec_id, rangeid, start, end)) + rangeid += 1 + + return ranges + + def get_clusters_and_entries(treename: str, filename: str) -> Tuple[List[int], int]: """ Retrieve cluster boundaries and number of entries of a TTree. @@ -179,7 +194,8 @@ def get_clusters_and_entries(treename: str, filename: str) -> Tuple[List[int], i def get_percentage_ranges(treenames: List[str], filenames: List[str], npartitions: int, - friendinfo: Optional[ROOT.Internal.TreeUtils.RFriendInfo]) -> List[TreeRangePerc]: + friendinfo: Optional[ROOT.Internal.TreeUtils.RFriendInfo], + exec_id: ExecutionIdentifier) -> List[TreeRangePerc]: """ Create a list of tasks that will process the given trees partitioning them by percentages. @@ -228,8 +244,9 @@ def get_percentage_ranges(treenames: List[str], filenames: List[str], npartition # We need to transmit the full list of treenames and filenames to each # task, in order to properly align the full dataset considering friends. return [ - TreeRangePerc(rangeid, treenames, filenames, start_sample_idxs[rangeid], end_sample_idxs[rangeid], - first_tree_start_perc_tasks[rangeid], last_tree_end_perc_tasks[rangeid], friendinfo) + TreeRangePerc( + exec_id, rangeid, treenames, filenames, start_sample_idxs[rangeid], end_sample_idxs[rangeid], + first_tree_start_perc_tasks[rangeid], last_tree_end_perc_tasks[rangeid], friendinfo) for rangeid in range(npartitions) ] else: @@ -245,7 +262,7 @@ def get_percentage_ranges(treenames: List[str], filenames: List[str], npartition # equal to the number of files assigned to that task. return [ TreeRangePerc( - rangeid, tasktreenames[rangeid], taskfilenames[rangeid], 0, len(taskfilenames[rangeid]), + exec_id, rangeid, tasktreenames[rangeid], taskfilenames[rangeid], 0, len(taskfilenames[rangeid]), first_tree_start_perc_tasks[rangeid], last_tree_end_perc_tasks[rangeid], friendinfo ) for rangeid in range(npartitions) @@ -391,7 +408,7 @@ def get_clustered_range_from_percs(percrange: TreeRangePerc) -> Tuple[Optional[T entries_in_trees = TaskTreeEntries(globalend - globalstart, trees_with_entries) - treerange = TreeRange(percrange.id, percrange.treenames, percrange.filenames, - globalstart, globalend, percrange.friendinfo) + treerange = TreeRange(percrange.exec_id, percrange.id, percrange.treenames, percrange.filenames, + globalstart, globalend, percrange.friendinfo) return treerange, entries_in_trees diff --git a/bindings/experimental/distrdf/python/DistRDF/__init__.py b/bindings/experimental/distrdf/python/DistRDF/__init__.py index cf0d095e7a2c5..cb69b64dd2700 100644 --- a/bindings/experimental/distrdf/python/DistRDF/__init__.py +++ b/bindings/experimental/distrdf/python/DistRDF/__init__.py @@ -12,17 +12,17 @@ from __future__ import annotations import logging -import sys import types import concurrent.futures -from typing import TYPE_CHECKING +from typing import Iterable, TYPE_CHECKING from DistRDF.Backends import build_backends_submodules +from DistRDF.LiveVisualize import LiveVisualize if TYPE_CHECKING: - from DistRDF.Proxy import ActionProxy, VariationsProxy + from DistRDF.Proxy import ResultPtrProxy, ResultMapProxy logger = logging.getLogger(__name__) @@ -48,30 +48,7 @@ def initialize(fun, *args, **kwargs): Base.BaseBackend.register_initialization(fun, *args, **kwargs) -def create_logger(level="WARNING", log_path="./DistRDF.log"): - """DistRDF basic logger""" - logger = logging.getLogger(__name__) - - level = getattr(logging, level) - - logger.setLevel(level) - - format_string = ("%(levelname)s: %(name)s[%(asctime)s]: %(message)s") - formatter = logging.Formatter(format_string) - - stream_handler = logging.StreamHandler(sys.stdout) - stream_handler.setFormatter(formatter) - logger.addHandler(stream_handler) - - if log_path: - file_handler = logging.FileHandler(log_path) - file_handler.setFormatter(formatter) - logger.addHandler(file_handler) - - return logger - - -def RunGraphs(proxies): +def RunGraphs(proxies: Iterable) -> int: """ Trigger the execution of multiple RDataFrame computation graphs on a certain distributed backend. If the backend doesn't support multiple job @@ -83,6 +60,10 @@ def RunGraphs(proxies): actions belonging to different RDataFrame graphs will be triggered to avoid useless calls. + Return: + (int): The number of unique computation graphs executed by this call. + + Example: @code{.py} @@ -99,7 +80,7 @@ def RunGraphs(proxies): ] # Execute the 3 computation graphs - RunGraphs(histoproxies) + n_graphs_run = RunGraphs(histoproxies) # Retrieve all the histograms in one go histos = [histoproxy.GetValue() for histoproxy in histoproxies] @endcode @@ -108,9 +89,9 @@ def RunGraphs(proxies): """ # Import here to avoid circular dependencies in main module from DistRDF.Proxy import execute_graph - if not proxies: - raise ValueError("The list of result pointers passed to RunGraphs is empty.") + logger.warning("RunGraphs: Got an empty list of handles, now quitting.") + return 0 # Get proxies belonging to distinct computation graphs uniqueproxies = list({proxy.proxied_node.get_head(): proxy for proxy in proxies}.values()) @@ -121,8 +102,10 @@ def RunGraphs(proxies): futures = [executor.submit(execute_graph, proxy.proxied_node) for proxy in uniqueproxies] concurrent.futures.wait(futures) + return len(uniqueproxies) + -def VariationsFor(actionproxy: ActionProxy) -> VariationsProxy: +def VariationsFor(actionproxy: ResultPtrProxy) -> ResultMapProxy: """ Equivalent of ROOT.RDF.Experimental.VariationsFor in distributed mode. """ @@ -150,11 +133,8 @@ def create_distributed_module(parentmodule): # Inject top-level functions distributed.initialize = initialize - distributed.create_logger = create_logger distributed.RunGraphs = RunGraphs distributed.VariationsFor = VariationsFor - - # Set non-optimized default mode - distributed.optimized = False + distributed.LiveVisualize = LiveVisualize return distributed diff --git a/bindings/experimental/distrdf/python/DistRDF/_graph_cache.py b/bindings/experimental/distrdf/python/DistRDF/_graph_cache.py new file mode 100644 index 0000000000000..6d6fa2db0f486 --- /dev/null +++ b/bindings/experimental/distrdf/python/DistRDF/_graph_cache.py @@ -0,0 +1,30 @@ +from __future__ import annotations +from dataclasses import dataclass + +import uuid +from typing import Dict, TYPE_CHECKING + +if TYPE_CHECKING: + import ROOT + from DistRDF.PythonMergeables import RDataFrameFutureResult + + +@dataclass(frozen=True) +class ExecutionIdentifier: + """ + A unique identifier for the current execution of the computation graph of + a particular RDataFrame instance. The class is hashable so it can be used + as a key in dictionaries. + + Attributes: + + rdf_uuid: An identifier for the specific RDataFrame instance. + graph_uuid: An identifier for the computation graph sent to the workers for + the current execution. + """ + rdf_uuid: uuid.UUID + graph_uuid: uuid.UUID + + +_RDF_REGISTER: Dict[ExecutionIdentifier, ROOT.RDataFrame] = {} +_ACTIONS_REGISTER: Dict[ExecutionIdentifier, RDataFrameFutureResult] = {} diff --git a/bindings/experimental/distrdf/test/backend/CMakeLists.txt b/bindings/experimental/distrdf/test/backend/CMakeLists.txt index d1b6604ffbf2e..1025599f4c654 100644 --- a/bindings/experimental/distrdf/test/backend/CMakeLists.txt +++ b/bindings/experimental/distrdf/test/backend/CMakeLists.txt @@ -17,5 +17,6 @@ file(COPY 1cluster_20entries.root DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) ROOT_ADD_PYUNITTEST(distrdf_unit_backend_test_common test_common.py) ROOT_ADD_PYUNITTEST(distrdf_unit_backend_test_dist test_dist.py) +ROOT_ADD_PYUNITTEST(distrdf_unit_backend_test_graph_caching test_graph_caching.py) endif() diff --git a/bindings/experimental/distrdf/test/backend/test_graph_caching.py b/bindings/experimental/distrdf/test/backend/test_graph_caching.py new file mode 100644 index 0000000000000..82481489fd523 --- /dev/null +++ b/bindings/experimental/distrdf/test/backend/test_graph_caching.py @@ -0,0 +1,192 @@ + +import os +import unittest + +from DistRDF.Backends import Base +from DistRDF.DataFrame import RDataFrame +from DistRDF.HeadNode import get_headnode +from DistRDF._graph_cache import _ACTIONS_REGISTER, _RDF_REGISTER + + +def clear_caches(): + _RDF_REGISTER.clear() + _ACTIONS_REGISTER.clear() + + +class GraphCaching(unittest.TestCase): + """ + Different tasks run in the same process should not need to re-JIT the + computation graph. + """ + + class TestBackend(Base.BaseBackend): + + def ProcessAndMerge(self, ranges, mapper, reducer): + mergeables_lists = [mapper(range) for range in ranges] + + while len(mergeables_lists) > 1: + mergeables_lists.append( + reducer(mergeables_lists.pop(0), mergeables_lists.pop(0))) + + return mergeables_lists.pop() + + def distribute_unique_paths(self, includes_list): ... + + def make_dataframe(self, *args, **kwargs): + """This implementation is needed for the Snapshot tests.""" + npartitions = 1 + headnode = get_headnode(self, npartitions, *args) + return RDataFrame(headnode) + + def optimize_npartitions(self): ... + + def tearDown(self) -> None: + """Clear the caches in between tests.""" + clear_caches() + + def test_count_emptysource(self): + """The cache is used to count entries with an empty source.""" + nentries = 100 + backend = GraphCaching.TestBackend() + + for npartitions in range(1, 11): + # Start from a fresh cache at each subtest iteration + clear_caches() + with self.subTest(npartitions=npartitions): + headnode = get_headnode(backend, npartitions, nentries) + distrdf = RDataFrame(headnode) + # The count operation should always return the correct value + self.assertEqual(distrdf.Count().GetValue(), 100) + # There should be exactly one cached RDF and set of actions + self.assertEqual(len(_RDF_REGISTER), 1) + self.assertEqual(len(_RDF_REGISTER), len(_ACTIONS_REGISTER)) + cached_rdf = tuple(_RDF_REGISTER.values())[0] + # The RDataFrame should have run as many times as partitions + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + + def test_count_ttree(self): + """The cache is used to count entries of a TTree.""" + treename = "myTree" + filename = "4clusters.root" + nentries = 1000 + backend = GraphCaching.TestBackend() + + # The maximum number of partitions is the number of clusters + for npartitions in range(1, 4): + # Start from a fresh cache at each subtest iteration + clear_caches() + with self.subTest(npartitions=npartitions): + headnode = get_headnode(backend, npartitions, treename, filename) + distrdf = RDataFrame(headnode) + # The count operation should always return the correct value + self.assertEqual(distrdf.Count().GetValue(), nentries) + # There should be exactly one cached RDF and set of actions + self.assertEqual(len(_RDF_REGISTER), 1) + self.assertEqual(len(_RDF_REGISTER), len(_ACTIONS_REGISTER)) + cached_rdf = tuple(_RDF_REGISTER.values())[0] + # The RDataFrame should have run as many times as partitions + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + + def test_count_tchain(self): + """The cache is used to count entries of a TChain.""" + treename = "myTree" + filenames = ["4clusters.root"] * 5 + nentries = 5000 + backend = GraphCaching.TestBackend() + + # The maximum number of partitions is the number of clusters + for npartitions in range(1, 20): + # Start from a fresh cache at each subtest iteration + clear_caches() + with self.subTest(npartitions=npartitions): + headnode = get_headnode(backend, npartitions, treename, filenames) + distrdf = RDataFrame(headnode) + # The count operation should always return the correct value + self.assertEqual(distrdf.Count().GetValue(), nentries) + # There should be exactly one cached RDF and set of actions + self.assertEqual(len(_RDF_REGISTER), 1) + self.assertEqual(len(_RDF_REGISTER), len(_ACTIONS_REGISTER)) + cached_rdf = tuple(_RDF_REGISTER.values())[0] + # The RDataFrame should have run as many times as partitions + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + + def test_snapshot(self): + """The cache is used to Snapshot data.""" + treename = "myTree" + filenames = ["4clusters.root"] * 5 + nentries = 5000 + backend = GraphCaching.TestBackend() + + for npartitions in [1, 2, 4, 8, 16]: + # Start from a fresh cache at each subtest iteration + clear_caches() + + output_basename = "test_graph_caching_test_snapshot" + output_filenames = [f"{output_basename}_{i}.root" for i in range(npartitions)] + + with self.subTest(npartitions=npartitions): + headnode = get_headnode(backend, npartitions, treename, filenames) + distrdf = RDataFrame(headnode) + + output_branches = ("b1", ) + snapdf = distrdf.Snapshot(treename, f"{output_basename}.root", ["b1", ]) + + # There should be exactly one cached RDF and set of actions + self.assertEqual(len(_RDF_REGISTER), 1) + self.assertEqual(len(_RDF_REGISTER), len(_ACTIONS_REGISTER)) + cached_rdf = tuple(_RDF_REGISTER.values())[0] + # The RDataFrame should have run as many times as partitions + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + # All the correct output files should be present + for output_filename in output_filenames: + self.assertTrue(os.path.exists(output_filename)) + # The snapshotted dataframe should be usable + self.assertEqual(snapdf.Count().GetValue(), nentries) + + # Remove output files at each iteration + for output_filename in output_filenames: + os.remove(output_filename) + + def test_multiple_graphs(self): + """The caches are used with multiple executions.""" + treename = "myTree" + filenames = ["4clusters.root"] * 5 + nentries = 5000 + backend = GraphCaching.TestBackend() + + for npartitions in [1, 2, 4, 8, 16]: + # Start from a fresh cache at each subtest iteration + clear_caches() + with self.subTest(npartitions=npartitions): + headnode = get_headnode(backend, npartitions, treename, filenames) + distrdf = RDataFrame(headnode) + + self.assertEqual(distrdf.Count().GetValue(), nentries) + + distrdf = distrdf.Define("x", "2").Define("y", "3").Define("z", "x*y") + + sumx = distrdf.Sum("x") + sumy = distrdf.Sum("y") + + self.assertEqual(sumx.GetValue(), 10000) + self.assertEqual(sumy.GetValue(), 15000) + + self.assertEqual(len(_RDF_REGISTER), 2) + self.assertEqual(len(_ACTIONS_REGISTER), len(_RDF_REGISTER)) + + for cached_rdf in _RDF_REGISTER.values(): + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + + meanz = distrdf.Mean("z") + + self.assertAlmostEqual(meanz.GetValue(), 6) + + self.assertEqual(len(_RDF_REGISTER), 3) + self.assertEqual(len(_ACTIONS_REGISTER), len(_RDF_REGISTER)) + + for cached_rdf in _RDF_REGISTER.values(): + self.assertEqual(cached_rdf.GetNRuns(), npartitions) + + +if __name__ == "__main__": + unittest.main() diff --git a/bindings/experimental/distrdf/test/test_callable_generator.py b/bindings/experimental/distrdf/test/test_callable_generator.py index 674c21ad054d5..6ab386ae4d477 100644 --- a/bindings/experimental/distrdf/test/test_callable_generator.py +++ b/bindings/experimental/distrdf/test/test_callable_generator.py @@ -70,7 +70,7 @@ def test_mapper_from_graph(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Set of operations to build the graph n1 = node.Define() n2 = node.Filter().Filter() @@ -103,7 +103,7 @@ def test_mapper_with_pruning(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Set of operations to build the graph n1 = node.Define() @@ -148,7 +148,7 @@ def test_dfs_graph_with_pruning_transformations(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Graph nodes n1 = node.Define() @@ -185,7 +185,7 @@ def test_dfs_graph_with_recursive_pruning(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Graph nodes n1 = node.Define() @@ -222,7 +222,7 @@ def test_dfs_graph_with_parent_pruning(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Graph nodes n1 = node.Define() @@ -261,7 +261,7 @@ def test_dfs_graph_with_computed_values_pruning(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Graph nodes n1 = node.Define() @@ -303,7 +303,7 @@ def test_dfs_graph_without_pruning(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Graph nodes n1 = node.Define() @@ -337,7 +337,7 @@ def test_nodes_gt_python_recursion_limit(self): # Head node hn = create_dummy_headnode(1) hn.backend = ComputationGraphGeneratorTest.TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) # Create three branches n1 = node.Define() n2 = node.Filter() diff --git a/bindings/experimental/distrdf/test/test_headnode.py b/bindings/experimental/distrdf/test/test_headnode.py index c8ba935656548..adfcde661e651 100644 --- a/bindings/experimental/distrdf/test/test_headnode.py +++ b/bindings/experimental/distrdf/test/test_headnode.py @@ -14,6 +14,47 @@ def create_dummy_headnode(*args): return get_headnode(None, None, *args) +def fill_main_tree_and_indexed_friend(mainfile, auxfile): + idx = array("i", [0]) + x = array("i", [0]) + y = array("i", [0]) + + with ROOT.TFile(mainfile, "RECREATE") as f1: + main_tree = ROOT.TTree("mainTree", "mainTree") + main_tree.Branch("idx", idx, "idx/I") + main_tree.Branch("x", x, "x/I") + + idx[0] = 1 + x[0] = 1 + main_tree.Fill() + idx[0] = 1 + x[0] = 2 + main_tree.Fill() + idx[0] = 1 + x[0] = 3 + main_tree.Fill() + idx[0] = 2 + x[0] = 4 + main_tree.Fill() + idx[0] = 2 + x[0] = 5 + main_tree.Fill() + f1.WriteObject(main_tree, "mainTree") + + with ROOT.TFile(auxfile, "RECREATE") as f2: + aux_tree = ROOT.TTree("auxTree", "auxTree") + aux_tree.Branch("idx", idx, "idx/I") + aux_tree.Branch("y", y, "y/I") + + idx[0] = 2 + y[0] = 5 + aux_tree.Fill() + idx[0] = 1 + y[0] = 7 + aux_tree.Fill() + f2.WriteObject(aux_tree, "auxTree") + + class DataFrameConstructorTests(unittest.TestCase): """Check various functionalities of the HeadNode class""" @@ -163,14 +204,41 @@ def test_three_args_with_multiple_files(self): self.assertIsInstance(hn_2.defaultbranches, type(reqd_branches_vec)) self.assertIsInstance(hn_4.defaultbranches, type(reqd_branches_vec)) + def test_tree_with_friends_and_treeindex(self): + """TTreeIndex is not supported in distributed mode.""" + # See https://github.com/root-project/root/issues/7541 and + # https://bugs.llvm.org/show_bug.cgi?id=49692 : + # llvm JIT fails to catch exceptions on M1, so we disable their testing + if platform.processor() != "arm" or platform.mac_ver()[0] == '': + main_file = "distrdf_indexed_friend_main.root" + aux_file = "distrdf_indexed_friend_aux.root" + fill_main_tree_and_indexed_friend(main_file, aux_file) + + main_chain = ROOT.TChain("mainTree", "mainTree") + main_chain.Add(main_file) + aux_chain = ROOT.TChain("auxTree", "auxTree") + aux_chain.Add(aux_file) + + aux_chain.BuildIndex("idx") + main_chain.AddFriend(aux_chain) + + with self.assertRaises(ValueError) as context: + create_dummy_headnode(main_chain) + + self.assertEqual(str(context.exception), + "Friend tree 'auxTree' has a TTreeIndex. This is not supported in distributed mode.") + + # Remove unnecessary .root files + os.remove(main_file) + os.remove(aux_file) + class NumEntriesTest(unittest.TestCase): """'get_num_entries' returns the number of entries in the input dataset""" def fill_tree(self, size): - """Stores an RDataFrame object of a given size in 'data.root'.""" - tdf = ROOT.ROOT.RDataFrame(size) - tdf.Define("b1", "(double) tdfentry_").Snapshot("tree", "data.root") + """Writes a TTree with one column of type 'double' with the given size to 'data.root'.""" + ROOT.RDataFrame(size).Define("b1", "static_cast(rdfentry_)").Snapshot("tree", "data.root") def test_num_entries_two_args_case(self): """ diff --git a/bindings/experimental/distrdf/test/test_node.py b/bindings/experimental/distrdf/test/test_node.py index 22ce1124a3d40..75df0bbb846b5 100644 --- a/bindings/experimental/distrdf/test/test_node.py +++ b/bindings/experimental/distrdf/test/test_node.py @@ -42,7 +42,7 @@ def test_attr_read(self): """Function names are read accurately.""" hn = create_dummy_headnode(1) hn.backend = TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) func = node.Define # noqa: avoid PEP8 F841 self.assertEqual(node._new_op_name, "Define") @@ -50,7 +50,7 @@ def test_args_read(self): """Arguments (unnamed) are read accurately.""" hn = create_dummy_headnode(1) hn.backend = TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) newNode = node.Define(1, "b", a="1", b=2) self.assertEqual(newNode.operation.args, [1, "b"]) @@ -58,7 +58,7 @@ def test_kwargs_read(self): """Named arguments are read accurately.""" hn = create_dummy_headnode(1) hn.backend = TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) newNode = node.Define(1, "b", a="1", b=2) self.assertEqual(newNode.operation.kwargs, {"a": "1", "b": 2}) @@ -66,25 +66,25 @@ def test_kwargs_read(self): class NodeReturnTest(unittest.TestCase): """ A series of test cases to check that right objects are returned for a node - (Proxy.ActionProxy, Proxy.TransformationProxy or Node). + (Proxy.ResultPtrProxy, Proxy.NodeProxy or Node). """ def test_action_proxy_return(self): """Proxy objects are returned for action nodes.""" hn = create_dummy_headnode(1) hn.backend = TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) newNode = node.Count() - self.assertIsInstance(newNode, Proxy.ActionProxy) + self.assertIsInstance(newNode, Proxy.ResultPtrProxy) self.assertIsInstance(newNode.proxied_node, Node.Node) def test_transformation_proxy_return(self): """Node objects are returned for transformation nodes.""" hn = create_dummy_headnode(1) hn.backend = TestBackend() - node = Proxy.TransformationProxy(hn) + node = Proxy.NodeProxy(hn) newNode = node.Define(1) - self.assertIsInstance(newNode, Proxy.TransformationProxy) + self.assertIsInstance(newNode, Proxy.NodeProxy) self.assertIsInstance(newNode.proxied_node, Node.Node) diff --git a/bindings/experimental/distrdf/test/test_proxy.py b/bindings/experimental/distrdf/test/test_proxy.py index a0b43fbe8abd0..d37dc82dd1f05 100644 --- a/bindings/experimental/distrdf/test/test_proxy.py +++ b/bindings/experimental/distrdf/test/test_proxy.py @@ -30,24 +30,24 @@ class TypeReturnTest(unittest.TestCase): def test_type_return_transformation(self): """ - TransformationProxy object is of type `DistRDF.TransformationProxy` and + NodeProxy object is of type `DistRDF.NodeProxy` and wraps a node object. """ node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.TransformationProxy(node) - self.assertIsInstance(proxy, Proxy.TransformationProxy) + proxy = Proxy.NodeProxy(node) + self.assertIsInstance(proxy, Proxy.NodeProxy) self.assertIsInstance(proxy.proxied_node, Node.Node) def test_type_return_action(self): """ - ActionProxy object is of type `DistRDF.ActionProxy` and + ResultPtrProxy object is of type `DistRDF.ResultPtrProxy` and wraps a node object. """ node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.ActionProxy(node) - self.assertIsInstance(proxy, Proxy.ActionProxy) + proxy = Proxy.ResultPtrProxy(node) + self.assertIsInstance(proxy, Proxy.ResultPtrProxy) self.assertIsInstance(proxy.proxied_node, Node.Node) @@ -81,10 +81,10 @@ def optimize_npartitions(self): pass def test_attr_simple_action(self): - """ActionProxy object reads the right input attribute.""" + """ResultPtrProxy object reads the right input attribute.""" node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.ActionProxy(node) + proxy = Proxy.ResultPtrProxy(node) func = proxy.attr self.assertEqual(proxy._cur_attr, "attr") @@ -92,34 +92,34 @@ def test_attr_simple_action(self): def test_supported_transformation(self): """ - TransformationProxy object reads the right input attributes, + NodeProxy object reads the right input attributes, returning the methods of the proxied node. """ node = create_dummy_headnode(1) node.backend = AttrReadTest.TestBackend() - proxy = Proxy.TransformationProxy(node) + proxy = Proxy.NodeProxy(node) transformations = { - "Define": ["x", "tdfentry_"], - "Filter": ["tdfentry_ > 0"], + "Define": ["x", "1"], + "Filter": ["x > 0"], } for transformation, args in transformations.items(): newProxy = getattr(proxy, transformation)(*args) self.assertEqual(proxy.proxied_node._new_op_name, transformation) - self.assertIsInstance(newProxy, Proxy.TransformationProxy) + self.assertIsInstance(newProxy, Proxy.NodeProxy) self.assertEqual(newProxy.proxied_node.operation.name, transformation) self.assertEqual(newProxy.proxied_node.operation.args, args) def test_node_attr_transformation(self): """ - When a node attribute is called on a TransformationProxy object, it + When a node attribute is called on a NodeProxy object, it correctly returns the attribute of the proxied node. """ node = create_dummy_headnode(1) node.backend = AttrReadTest.TestBackend() - proxy = Proxy.TransformationProxy(node) + proxy = Proxy.NodeProxy(node) node_attributes = [ "get_head", @@ -138,11 +138,11 @@ def test_node_attr_transformation(self): def test_undefined_attr_transformation(self): """ When a non-defined Node class attribute is called on a - TransformationProxy object, it raises an AttributeError. + NodeProxy object, it raises an AttributeError. """ node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.TransformationProxy(node) + proxy = Proxy.NodeProxy(node) with self.assertRaises(AttributeError): proxy.attribute @@ -155,7 +155,7 @@ def test_proxied_node_has_user_references(self): """ node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.TransformationProxy(node) + proxy = Proxy.NodeProxy(node) self.assertTrue(node.has_user_references) proxy = None # noqa: avoid PEP8 F841 self.assertFalse(node.has_user_references) @@ -169,7 +169,7 @@ def test_return_value(self): node = create_dummy_headnode(1) node.backend = None node.value = t - proxy = Proxy.ActionProxy(node) + proxy = Proxy.ResultPtrProxy(node) self.assertEqual(proxy.val(21), 144) @@ -207,7 +207,7 @@ def test_get_value_with_existing_value(self): """ node = create_dummy_headnode(1) node.backend = None - proxy = Proxy.ActionProxy(node) + proxy = Proxy.ResultPtrProxy(node) node.value = 5 self.assertEqual(proxy.GetValue(), 5) diff --git a/bindings/experimental/distrdf/test/test_ranges.py b/bindings/experimental/distrdf/test/test_ranges.py index e334d807f1d07..e0f7da6269002 100644 --- a/bindings/experimental/distrdf/test/test_ranges.py +++ b/bindings/experimental/distrdf/test/test_ranges.py @@ -34,11 +34,11 @@ def test_nentries_multipleOf_npartitions(self): npartitions_large = 10 # First case - rng = Ranges.get_balanced_ranges(nentries_small, npartitions_small) + rng = Ranges.get_balanced_ranges(nentries_small, npartitions_small, exec_id=None) ranges_small = emptysourceranges_to_tuples(rng) # Second case - rng = Ranges.get_balanced_ranges(nentries_large, npartitions_large) + rng = Ranges.get_balanced_ranges(nentries_large, npartitions_large, exec_id=None) ranges_large = emptysourceranges_to_tuples(rng) ranges_small_reqd = [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10)] @@ -70,12 +70,12 @@ def test_nentries_not_multipleOf_npartitions(self): # Example in which fractional part of # (nentries/npartitions) >= 0.5 - rng = Ranges.get_balanced_ranges(nentries_1, npartitions) + rng = Ranges.get_balanced_ranges(nentries_1, npartitions, exec_id=None) ranges_1 = emptysourceranges_to_tuples(rng) # Example in which fractional part of # (nentries/npartitions) < 0.5 - rng = Ranges.get_balanced_ranges(nentries_2, npartitions) + rng = Ranges.get_balanced_ranges(nentries_2, npartitions, exec_id=None) ranges_2 = emptysourceranges_to_tuples(rng) # Required output pairs @@ -94,7 +94,7 @@ def test_nentries_greater_than_npartitions(self): nentries = 5 npartitions = 7 - rng = Ranges.get_balanced_ranges(nentries, npartitions) + rng = Ranges.get_balanced_ranges(nentries, npartitions, exec_id=None) ranges = emptysourceranges_to_tuples(rng) ranges_reqd = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] @@ -157,7 +157,7 @@ def test_clustered_ranges_with_one_cluster(self): filenames = ["backend/Slimmed_ntuple.root"] npartitions = 1 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -180,7 +180,7 @@ def test_npartitions_greater_than_clusters(self): filenames = ["backend/Slimmed_ntuple.root"] npartitions = 2 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] # We return one task per partition @@ -204,7 +204,7 @@ def test_clustered_ranges_with_two_clusters_two_partitions(self): filenames = ["backend/2clusters.root"] npartitions = 2 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -227,7 +227,7 @@ def test_rdataframe_with_treename_and_filename_with_globbing(self): expected_inputfiles = ["backend/2clusters.root"] extracted_inputfiles = rdf.inputfiles - percranges = Ranges.get_percentage_ranges([treename], extracted_inputfiles, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges([treename], extracted_inputfiles, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -258,7 +258,7 @@ def test_rdataframe_with_notreename_and_chain_with_subtrees(self): extracted_filenames = rdf.inputfiles percranges = Ranges.get_percentage_ranges( - extracted_subtreenames, extracted_filenames, npartitions, friendinfo=None) + extracted_subtreenames, extracted_filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -281,7 +281,7 @@ def test_clustered_ranges_with_four_clusters_four_partitions(self): filenames = ["backend/4clusters.root"] npartitions = 4 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -304,7 +304,7 @@ def test_clustered_ranges_with_many_clusters_four_partitions(self): filenames = ["backend/1000clusters.root"] npartitions = 4 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -327,7 +327,7 @@ def test_clustered_ranges_with_many_clusters_many_partitions(self): filenames = ["backend/1000clusters.root"] npartitions = 1000 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -349,7 +349,7 @@ def test_clustered_ranges_with_two_files(self): filenames = ["backend/2clusters.root", "backend/4clusters.root"] npartitions = 2 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -366,7 +366,7 @@ def test_three_files_one_partition(self): filenames = [f"distrdf_unittests_file_{i}.root" for i in range(nfiles)] npartitions = 1 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -382,7 +382,7 @@ def test_three_files_one_partition_per_file(self): filenames = [f"distrdf_unittests_file_{i}.root" for i in range(nfiles)] npartitions = nfiles - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -398,7 +398,7 @@ def test_three_files_two_partitions_per_file(self): treenames = [f"tree_{i}" for i in range(nfiles)] filenames = [f"distrdf_unittests_file_{i}.root" for i in range(nfiles)] npartitions = nfiles * 2 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -425,7 +425,7 @@ def test_three_files_partitions_equal_clusters(self): filenames = [f"distrdf_unittests_file_{i}.root" for i in range(nfiles)] npartitions = nfiles * 10 # trees have 10 clusters - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] ranges = treeranges_to_tuples(clusteredranges) @@ -473,7 +473,7 @@ def test_three_files_partitions_greater_than_clusters(self): filenames = [f"distrdf_unittests_file_{i}.root" for i in range(nfiles)] npartitions = 42 - percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None) + percranges = Ranges.get_percentage_ranges(treenames, filenames, npartitions, friendinfo=None, exec_id=None) clusteredranges = [Ranges.get_clustered_range_from_percs(percrange)[0] for percrange in percranges] # We return one task per partition diff --git a/bindings/jupyroot/CMakeLists.txt b/bindings/jupyroot/CMakeLists.txt index 49c7897817751..f59b89b5f80c5 100644 --- a/bindings/jupyroot/CMakeLists.txt +++ b/bindings/jupyroot/CMakeLists.txt @@ -42,12 +42,11 @@ foreach(val RANGE ${how_many_pythons}) # Set the suffix to '.so' and the prefix to 'lib' set_target_properties(${libname} PROPERTIES ${ROOT_LIBRARY_PROPERTIES}) if(MSVC) - list(GET python_libraries ${val} python_library) set_target_properties(${libname} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set_target_properties(${libname} PROPERTIES SUFFIX ".pyd") - target_link_libraries(${libname} PUBLIC Core ${python_library}) + target_link_libraries(${libname} PUBLIC Core ${PYTHON_LIBRARIES}) elseif(APPLE) - target_link_libraries(${libname} PUBLIC -Wl,-bind_at_load -Wl,-flat_namespace -Wl,-undefined -Wl,suppress Core) + target_link_libraries(${libname} PUBLIC -Wl,-bind_at_load -Wl,-w -Wl,-undefined -Wl,dynamic_lookup Core) else() target_link_libraries(${libname} PUBLIC -Wl,--unresolved-symbols=ignore-all Core) endif() diff --git a/bindings/jupyroot/python/JupyROOT/helpers/cppcompleter.py b/bindings/jupyroot/python/JupyROOT/helpers/cppcompleter.py index f8ec85031148b..f5b3bc3b13040 100644 --- a/bindings/jupyroot/python/JupyROOT/helpers/cppcompleter.py +++ b/bindings/jupyroot/python/JupyROOT/helpers/cppcompleter.py @@ -14,6 +14,7 @@ ################################################################################ from JupyROOT.helpers import utils +import platform import ROOT # Jit a wrapper for the ttabcom @@ -75,6 +76,7 @@ class CppCompleter(object): ... print(suggestion) TROOT::IsA TROOT::IsBatch + TROOT::IsBuilt TROOT::IsDestructed TROOT::IsEqual TROOT::IsEscaped @@ -105,8 +107,11 @@ def __init__(self): def activate(self): self.active = True if self.firstActivation: - utils.declareCppCode('#include "dlfcn.h"') - dlOpenRint = 'dlopen("libRint.so",RTLD_NOW);' + if platform.system() == 'Windows': + dlOpenRint = 'gInterpreter->LoadFile("libRint.dll");' + else: + utils.declareCppCode('#include "dlfcn.h"') + dlOpenRint = 'dlopen("libRint.so",RTLD_NOW);' utils.processCppCode(dlOpenRint) utils.declareCppCode(_TTabComHookCode) self.hook = ROOT._TTabComHook diff --git a/bindings/jupyroot/python/JupyROOT/helpers/utils.py b/bindings/jupyroot/python/JupyROOT/helpers/utils.py index 4531051108258..757caa5006153 100644 --- a/bindings/jupyroot/python/JupyROOT/helpers/utils.py +++ b/bindings/jupyroot/python/JupyROOT/helpers/utils.py @@ -37,6 +37,9 @@ cppMIME = 'text/x-c++src' +# Keep display handle for canvases to be able update them +_canvasHandles = {} + _jsMagicHighlight = """ Jupyter.CodeCell.options_default.highlight_modes['magic_{cppMIME}'] = {{'reg':[/^%%cpp/]}}; console.log("JupyROOT - %%cpp magic configured"); @@ -48,9 +51,9 @@ _jsCanvasHeight = 600 _jsCode = """ -
+
+ + + $treeview $search -$mathjax + + +$darkmode $extrastylesheet - - - - + + +
+ + +
diff --git a/documentation/doxygen/makehtmlfooter.sh b/documentation/doxygen/makehtmlfooter.sh index 7a15d13de48a7..0772c63c73f13 100755 --- a/documentation/doxygen/makehtmlfooter.sh +++ b/documentation/doxygen/makehtmlfooter.sh @@ -2,7 +2,7 @@ # Generates the HTML footer -echo '' +echo '' echo '' echo '' echo '' echo '' echo '' echo '' echo '' echo '' diff --git a/documentation/doxygen/makeimage.C b/documentation/doxygen/makeimage.C index b707e49ef63ab..9574dc2ce0225 100644 --- a/documentation/doxygen/makeimage.C +++ b/documentation/doxygen/makeimage.C @@ -46,8 +46,8 @@ void FindImageInCanvas(TCanvas *C) void makeimage(const char *MacroName, const char *ImageName, const char *OutDir, bool cp, bool py) { // Execute the macro as a C++ one or a Python one. - if (!py) gROOT->ProcessLine(Form(".x %s",MacroName)); - else gROOT->ProcessLine(Form("TPython::ExecScript(\"%s\");",MacroName)); + if (!py) gROOT->ProcessLine(TString::Format(".x %s",MacroName)); + else gROOT->ProcessLine(TString::Format("TPython::ExecScript(\"%s\");",MacroName)); // If needed, copy the macro in the documentation directory. if (cp) { diff --git a/documentation/doxygen/makeinput.sh b/documentation/doxygen/makeinput.sh index 101e72fa54095..120e096904e03 100755 --- a/documentation/doxygen/makeinput.sh +++ b/documentation/doxygen/makeinput.sh @@ -57,7 +57,6 @@ echo " ../../main/src/hadd.cxx \\" >> Doxyfile_INPUT echo " ../../math/ \\" >> Doxyfile_INPUT echo " ../../montecarlo/ \\" >> Doxyfile_INPUT echo " ../../net/doc/ \\" >> Doxyfile_INPUT -echo " ../../net/alien/ \\" >> Doxyfile_INPUT echo " ../../net/auth/ \\" >> Doxyfile_INPUT echo " ../../net/davix/ \\" >> Doxyfile_INPUT echo " ../../net/http/ \\" >> Doxyfile_INPUT diff --git a/documentation/doxygen/print_roofit_pyz_doctrings.py b/documentation/doxygen/print_roofit_pyz_doctrings.py index 77939c47fa4b4..6ea63247f2770 100644 --- a/documentation/doxygen/print_roofit_pyz_doctrings.py +++ b/documentation/doxygen/print_roofit_pyz_doctrings.py @@ -21,6 +21,11 @@ def clean_cpp_signature(sig): """Clean everything from the C++ signature that prohibits doxygen from automatically creating the correct link.""" + # If the signature doesn't include the function parameters or they are + # empty, we are done. + if not "(" in sig or "()" in sig: + return sig + def strip_defaults_from_param_sig(param_sig): # strip default parameter values split_was_at_equal_sign = [False] @@ -121,7 +126,7 @@ def member_funcs_have_doc(python_class): return funcs_have_doc # Fill separate RooFit pythonization page, starting with the introduction and table of contents... - print("\defgroup RoofitPythonizations Roofit pythonizations") + print("\defgroup RoofitPythonizations RooFit Pythonizations") print("\ingroup Roofitmain") for python_klass in _roofit.python_classes: if python_klass.__doc__ is None and not member_funcs_have_doc(python_klass): diff --git a/documentation/primer/macros/macro1.C b/documentation/primer/macros/macro1.C index 3caa54697481c..558af4c14b8a1 100644 --- a/documentation/primer/macros/macro1.C +++ b/documentation/primer/macros/macro1.C @@ -22,7 +22,7 @@ void macro1(){ // Instance of the graph TGraphErrors graph(n_points,x_vals,y_vals,nullptr,y_errs); - graph.SetTitle("Measurement XYZ;lenght [cm];Arb.Units"); + graph.SetTitle("Measurement XYZ;length [cm];Arb.Units"); // Make the plot estetically better graph.SetMarkerStyle(kOpenCircle); diff --git a/documentation/primer/macros/macro2.C b/documentation/primer/macros/macro2.C index bb2e8fad74c57..bdc0ba5256673 100644 --- a/documentation/primer/macros/macro2.C +++ b/documentation/primer/macros/macro2.C @@ -6,7 +6,7 @@ int macro2(){ "%lg %lg %lg"); graph_expected.SetTitle( "Measurement XYZ and Expectation;" - "lenght [cm];" + "length [cm];" "Arb.Units"); graph_expected.SetFillColor(kYellow); graph_expected.DrawClone("E3AL"); // E3 draws the band diff --git a/etc/Makefile.arch b/etc/Makefile.arch index cd14984b26932..2e04959a2ffe1 100644 --- a/etc/Makefile.arch +++ b/etc/Makefile.arch @@ -250,6 +250,15 @@ LDFLAGS = $(OPT) SOFLAGS = -shared endif +ifeq ($(ARCH),linuxriscv64) +# RISC-V Linux with gcc and glibc +CXX = g++ +CXXFLAGS = $(OPT) -Wall -fPIC +LD = g++ +LDFLAGS = $(OPT) +SOFLAGS = -shared +endif + ifeq ($(ARCH),freebsd4) # FreeBSD with glibc CXX = g++ @@ -277,6 +286,15 @@ LDFLAGS = $(OPT) SOFLAGS = -shared -Wl,-x endif +ifeq ($(findstring freebsd,$(ARCH)),freebsd) +# FreeBSD with libc +CXX = c++ +CXXFLAGS = $(OPT2) -W -Wall -fPIC +LD = $(CXX) +LDFLAGS = $(OPT2) +SOFLAGS = -shared -Wl,-x +endif + ifeq ($(ARCH),openbsd) # OpenBSD with libc CXX = g++ diff --git a/etc/RooFitHS3_wsexportkeys.json b/etc/RooFitHS3_wsexportkeys.json index 55bd8d41fdd29..94824e1da0406 100644 --- a/etc/RooFitHS3_wsexportkeys.json +++ b/etc/RooFitHS3_wsexportkeys.json @@ -1,93 +1,102 @@ { - "RooGaussian": { - "type": "Gaussian", + "RooAddition": { + "type": "sum", "proxies": { - "x": "x", - "mean": "mean", - "sigma": "sigma" + "set": "summands" } }, - "RooPoisson": { - "type": "Poisson", + "RooArgusBG": { + "type": "ARGUS_dist", "proxies": { - "x": "x", - "mean": "mean" + "m": "mass", + "m0": "resonance", + "c": "slope", + "p": "power" } }, - "RooExponential": { - "type": "Exponential", + "RooBernstein": { + "type": "bernstein_poly_dist", + "proxies": { + "coefList": "coefficients", + "x": "x" + } + }, + "RooBifurGauss": { + "type": "bifurkated_gaussian_dist", "proxies": { "x": "x", - "c": "c" + "mean": "mean", + "sigmaL": "sigmaL", + "sigmaR": "sigmaR" } - }, - "RooProduct": { - "type": "prod", + }, + "RooCBShape": { + "type": "crystalball_dist", "proxies": { - "compRSet": "factors", - "compCSet": "factors" + "alpha": "alpha", + "m": "m", + "m0": "m0", + "n": "n", + "sigma": "sigma" } }, - "RooProdPdf": { - "type": "pdfprod", + "RooGamma": { + "type": "gamma_dist", "proxies": { - "pdfs": "factors" + "x": "x", + "gamma": "gamma", + "beta": "beta", + "mu": "mu" } }, - "ParamHistFunc": { - "type": "paramhist", + "RooGaussian": { + "type": "gaussian_dist", "proxies": { - "dataVars": "observables", - "paramSet": "parameters" + "x": "x", + "mean": "mean", + "sigma": "sigma" } }, - "RooAddPdf": { - "type": "pdfsum", + "ParamHistFunc": { + "type": "step", "proxies": { - "refCoefNorm": "coefnormset", - "pdfs": "summands", - "coefficients": "coefficients" + "dataVars": "variables", + "paramSet": "parameters" } }, - "RooAddition": { - "type": "sum", + "RooLandau": { + "type": "landau_dist", "proxies": { - "set": "summands" + "x": "x", + "mean": "mean", + "sigma": "sigma" } }, - "RooBernstein": { - "type": "BernsteinPolynomial", + "RooPower": { + "type": "power_dist", "proxies": { "coefList": "coefficients", - "x": "x" + "expList": "exponents", + "x": "x" } - }, - "RooArgusBG": { - "type": "ARGUS", + }, + "RooProdPdf": { + "type": "product_dist", "proxies": { - "m": "mass", - "m0": "resonance", - "c": "slope", - "p": "power" + "pdfs": "factors" } }, - "RooCBShape": { - "type": "CrystalBallShape", + "RooProduct": { + "type": "product", "proxies": { - "alpha": "alpha", - "m": "m", - "m0": "m0", - "n": "n", - "sigma": "sigma" + "compRSet": "factors", + "compCSet": "factors" } }, - "RooBifurGauss": { - "type": "BifurkatedGaussian", + "RooUniform": { + "type": "uniform_dist", "proxies": { - "x": "x", - "mean": "mean", - "sigmaL": "sigmaL", - "sigmaR": "sigmaR" + "x": "x" } } } diff --git a/etc/RooFitHS3_wsfactoryexpressions.json b/etc/RooFitHS3_wsfactoryexpressions.json index 32830a46295cb..e09474b0493ee 100644 --- a/etc/RooFitHS3_wsfactoryexpressions.json +++ b/etc/RooFitHS3_wsfactoryexpressions.json @@ -1,30 +1,54 @@ { - "Gaussian": { - "class": "RooGaussian", + "ARGUS_dist": { + "class": "RooArgusBG", + "arguments": [ + "mass", + "resonance", + "slope", + "power" + ] + }, + "bernstein_poly_dist": { + "class": "RooBernstein", "arguments": [ "x", - "mean", - "sigma" + "coefficients" ] }, - "Exponential": { - "class": "RooExponential", + "bifurkated_gaussian_dist": { + "class": "RooBifurGauss", "arguments": [ "x", - "c" + "mean", + "sigmaL", + "sigmaR" ] - }, - "Poisson": { - "class": "RooPoisson", + }, + "crystalball_dist": { + "class": "RooCBShape", + "arguments": [ + "m", + "m0", + "sigma", + "alpha", + "n" + ] + }, + "gamma_dist": { + "class": "RooGamma", "arguments": [ "x", - "mean" + "gamma", + "beta", + "mu" ] }, - "prod": { - "class": "RooProduct", + "gaussian_dist": { + "class": "RooGaussian", "arguments": [ - "factors" + "x", + "mean", + "sigma" ] }, "interpolation0d": { @@ -36,52 +60,51 @@ "high" ] }, - "sum": { - "class": "RooAddition", + "landau_dist": { + "class": "RooLandau", "arguments": [ - "summands" + "x", + "mean", + "sigma" ] - }, - "paramhist": { - "class": "ParamHistFunc", + }, + "power_dist": { + "class": "RooPower", "arguments": [ - "observables", - "parameters" + "x", + "coefficients", + "exponents" ] }, - "ARGUS": { - "class": "RooArgusBG", + "product": { + "class": "RooProduct", "arguments": [ - "mass", - "resonance", - "slope", - "power" + "factors" ] }, - "BernsteinPolynomial": { - "class": "RooBernstein", + "product_dist": { + "class": "RooProdPdf", "arguments": [ - "x", - "coefficients" + "factors" ] }, - "CrystalBallShape": { - "class": "RooCBShape", + "step": { + "class": "ParamHistFunc", "arguments": [ - "m", - "m0", - "sigma", - "alpha", - "n" + "variables", + "parameters" ] }, - "BifurkatedGaussian": { - "class": "RooBifurGauss", + "sum": { + "class": "RooAddition", "arguments": [ - "x", - "mean", - "sigmaL", - "sigmaR" + "summands" + ] + }, + "uniform_dist": { + "class": "RooUniform", + "arguments": [ + "x" ] } } diff --git a/etc/gdb-backtrace.sh b/etc/gdb-backtrace.sh index fc155a7dc65e7..7fd8572e99d4f 100755 --- a/etc/gdb-backtrace.sh +++ b/etc/gdb-backtrace.sh @@ -227,8 +227,10 @@ $line" echo 'If you see question marks in one or more lines of the stack trace, try' echo 'exporting the environment variable CLING_DEBUG=1 and running again.' echo 'You may get help by asking at the ROOT forum https://root.cern/forum' + echo 'preferably using the command (.forum bug) in the ROOT prompt.' echo 'If you are really convinced it is a bug in ROOT then please submit a report' - echo 'at https://root.cern/bugs Please post the ENTIRE stack trace' + echo 'at https://root.cern/bugs or (preferably) using the command (.gh bug) in' + echo 'the ROOT prompt. Please post the ENTIRE stack trace' echo 'from above as an attachment in addition to anything else' echo 'that might help us fixing this issue.' fi @@ -242,8 +244,10 @@ $line" echo 'marks as part of the stack trace, try to recompile with debugging information' echo 'enabled and export CLING_DEBUG=1 environment variable before running.' echo 'You may get help by asking at the ROOT forum https://root.cern/forum' + echo 'preferably using the command (.forum bug) in the ROOT prompt.' echo 'Only if you are really convinced it is a bug in ROOT then please submit a' - echo 'report at https://root.cern/bugs Please post the ENTIRE stack trace' + echo 'report at https://root.cern/bugs or (preferably) using the command (.gh bug) in' + echo 'the ROOT prompt. Please post the ENTIRE stack trace' echo 'from above as an attachment in addition to anything else' echo 'that might help us fixing this issue.' fi diff --git a/etc/pdg_table.txt b/etc/pdg_table.txt index a4de696d2ce15..27f4b92739c91 100644 --- a/etc/pdg_table.txt +++ b/etc/pdg_table.txt @@ -1,7 +1,7 @@ #-------------------------------------------------------------------- # i NAME............. KF AP CLASS Q MASS WIDTH 2*I+1 I3 2*S+1 FLVR TrkCod N(dec) #-------------------------------------------------------------------- - 1 d 1 1 100 Quark -1 4.80000e-03 0.00000e+00 -100 -1 -100 -1 -1 8 + 1 d 1 1 100 Quark -1 4.670000e-03 0.000000e+00 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -13,8 +13,8 @@ 6 102 0.00000e+00 2 -24 6 W- t 7 102 0.00000e+00 2 -24 8 W- t' 8 102 0.00000e+00 2 25 1 h0 d - 2 d_bar -1 1 0 - 3 u 2 1 100 Quark 2 2.40000e-03 0.00000e+00 -100 -1 -100 -1 -1 8 + 2 d_bar -1 1 0 + 3 u 2 1 100 Quark 2 2.160000e-03 0.000000e+00 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -26,8 +26,8 @@ 6 102 0.00000e+00 2 24 5 W+ b 7 102 0.00000e+00 2 24 7 W+ b' 8 102 0.00000e+00 2 25 2 h0 u - 4 u_bar -2 3 0 - 5 s 3 1 100 Quark -1 1.04000e-01 0.00000e+00 -100 -1 -100 -1 -1 8 + 4 u_bar -2 3 0 + 5 s 3 1 100 Quark -1 9.340000e-02 0.000000e+00 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -39,8 +39,8 @@ 6 102 0.00000e+00 2 -24 6 W- t 7 102 0.00000e+00 2 -24 8 W- t' 8 102 0.00000e+00 2 25 3 h0 s - 6 s_bar -3 5 0 - 7 c 4 1 100 Quark 2 1.27000e+00 0.00000e+00 -100 -1 -100 -1 -1 8 + 6 s_bar -3 5 0 + 7 c 4 1 100 Quark 2 1.270000e+00 0.000000e+00 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -52,8 +52,8 @@ 6 102 0.00000e+00 2 24 5 W+ b 7 102 0.00000e+00 2 24 7 W+ b' 8 102 0.00000e+00 2 25 4 h0 c - 8 c_bar -4 7 0 - 9 b 5 1 100 Quark -1 4.68000e+00 0.00000e+00 -100 -1 -100 -1 -1 8 + 8 c_bar -4 7 0 + 9 b 5 1 100 Quark -1 4.180000e+00 0.000000e+00 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -65,8 +65,8 @@ 6 102 0.00000e+00 2 -24 6 W- t 7 102 0.00000e+00 2 -24 8 W- t' 8 102 0.00000e+00 2 25 5 h0 b - 10 b_bar -5 9 0 - 11 t 6 1 100 Quark 2 1.71200e+02 1.39883e+00 -100 -1 -100 -1 -1 15 + 10 b_bar -5 9 0 + 11 t 6 1 100 Quark 2 1.725000e+02 1.420000e+00 -100 -1 -100 -1 -1 15 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -85,8 +85,8 @@ 13 53 0.00000e+00 2 1000035 1000006 ~chi_40 ~t_1 14 53 0.00000e+00 2 1000021 1000006 ~g ~t_1 15 53 0.00000e+00 2 1000039 1000006 ~gravitino ~t_1 - 12 t_bar -6 11 0 - 13 b' 7 1 100 Quark -1 4.68000e+02 0.00000e+00 -100 -1 -100 -1 -1 10 + 12 t_bar -6 11 0 + 13 b' 7 1 100 Quark -1 4.680000e+02 0.000000e+00 -100 -1 -100 -1 -1 10 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -100,8 +100,8 @@ 8 102 0.00000e+00 2 25 7 h0 b' 9 0 0.00000e+00 2 -37 4 H- c 10 0 0.00000e+00 2 -37 6 H- t - 14 b'_bar -7 13 0 - 15 t' 8 1 100 Quark 2 1.71200e+02 0.00000e+00 -100 -1 -100 -1 -1 10 + 14 b'_bar -7 13 0 + 15 t' 8 1 100 Quark 2 1.712000e+02 0.000000e+00 -100 -1 -100 -1 -1 10 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -115,8 +115,8 @@ 8 102 0.00000e+00 2 25 8 h0 t' 9 0 0.00000e+00 2 37 5 H+ b 10 0 0.00000e+00 2 37 7 H+ b' - 16 t'_bar -8 15 0 - 17 e- 11 1 100 Lepton -3 5.1099891e-04 0.00000e+00 -100 -1 -100 -1 -1 4 + 16 t'_bar -8 15 0 + 17 e- 11 1 100 Lepton -3 5.109990e-04 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -125,14 +125,14 @@ 3 102 0.00000e+00 2 -24 12 W- nu_e 4 102 0.00000e+00 2 25 11 h0 e- 18 e+ -11 17 0 - 19 nu_e 12 1 100 Lepton 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 19 nu_e 12 1 100 Lepton 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 102 0.00000e+00 2 23 12 Z0 nu_e 2 102 0.00000e+00 2 24 11 W+ e- - 20 nu_e_bar -12 19 0 - 21 mu- 13 1 100 Lepton -3 1.05658e-01 0.00000e+00 -100 -1 -100 -1 -1 5 + 20 nu_e_bar -12 19 0 + 21 mu- 13 1 100 Lepton -3 1.056584e-01 2.995984e-19 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -142,14 +142,14 @@ 4 102 0.00000e+00 2 -24 14 W- nu_mu 5 102 0.00000e+00 2 25 13 h0 mu- 22 mu+ -13 21 0 - 23 nu_mu 14 1 100 Lepton 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 23 nu_mu 14 1 100 Lepton 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 102 0.00000e+00 2 23 14 Z0 nu_mu 2 102 0.00000e+00 2 24 13 W+ mu- - 24 nu_mu_bar -14 23 0 - 25 tau- 15 1 100 Lepton -3 1.77684e+00 0.00000e+00 -100 -1 -100 -1 -1 54 + 24 nu_mu_bar -14 23 0 + 25 tau- 15 1 100 Lepton -3 1.776860e+00 2.267000e-12 -100 -1 -100 -1 -1 54 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -207,15 +207,15 @@ 52 102 0.00000e+00 2 23 15 Z0 tau- 53 102 0.00000e+00 2 -24 16 W- nu_tau 54 102 0.00000e+00 2 25 15 h0 tau- - 26 tau+ -15 25 0 - 27 nu_tau 16 1 100 Lepton 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 26 tau+ -15 25 0 + 27 nu_tau 16 1 100 Lepton 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 102 0.00000e+00 2 23 16 Z0 nu_tau 2 102 0.00000e+00 2 24 15 W+ tau- - 28 nu_tau_bar -16 27 0 - 29 tau'- 17 1 100 Lepton -3 4.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 5 + 28 nu_tau_bar -16 27 0 + 29 tau'- 17 1 100 Lepton -3 4.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -224,16 +224,16 @@ 3 0 0.00000e+00 2 -24 18 W- nu'_tau 4 102 0.00000e+00 2 25 17 h0 tau'- 5 0 0.00000e+00 2 -37 18 H- nu'_tau - 30 tau'+ -17 29 0 - 31 nu'_tau 18 1 100 Lepton 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 3 + 30 tau'+ -17 29 0 + 31 nu'_tau 18 1 100 Lepton 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 102 0.00000e+00 2 23 18 Z0 nu'_tau 2 0 0.00000e+00 2 24 17 W+ tau'- 3 0 0.00000e+00 2 37 17 H+ tau'- - 32 nu'_tau_bar -18 31 0 - 33 g 21 0 100 GaugeBoson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 32 nu'_tau_bar -18 31 0 + 33 g 21 0 100 GaugeBoson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -246,7 +246,7 @@ 7 102 0.00000e+00 2 7 -7 b' b'bar 8 102 0.00000e+00 2 8 -8 t' t'bar 9 102 0.00000e+00 2 21 21 g g - 34 gamma 22 0 100 GaugeBoson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 12 + 34 gamma 22 0 100 GaugeBoson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -262,7 +262,7 @@ 10 102 0.00000e+00 2 13 -13 mu- mu+ 11 102 0.00000e+00 2 15 -15 tau- tau+ 12 102 0.00000e+00 2 17 -17 tau'- tau'+ - 35 Z0 23 0 100 GaugeBoson 0 9.11870e+01 2.48009e+00 -100 -1 -100 -1 -1 16 + 35 Z0 23 0 100 GaugeBoson 0 9.118760e+01 2.495500e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -282,7 +282,7 @@ 14 0 6.67520e-02 2 16 -16 nu_tau nu_taubar 15 0 0.00000e+00 2 17 -17 tau'- tau'+ 16 0 0.00000e+00 2 18 -18 nu'_tau nu'_taubar - 36 W+ 24 1 100 GaugeBoson 3 8.03980e+01 2.07002e+00 -100 -1 -100 -1 -1 20 + 36 W+ 24 1 100 GaugeBoson 3 8.037700e+01 2.080000e+00 -100 -1 -100 -1 -1 20 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -306,8 +306,8 @@ 18 0 1.08062e-01 2 -13 14 mu+ nu_mu 19 0 1.07983e-01 2 -15 16 tau+ nu_tau 20 0 0.00000e+00 2 -17 18 tau'+ nu'_tau - 37 W- -24 36 0 - 38 h0 25 0 100 GaugeBoson 0 8.00000e+01 2.37000e-03 -100 -1 -100 -1 -1 79 + 37 W- -24 36 0 + 38 h0 25 0 100 GaugeBoson 0 1.252500e+02 3.200000e-03 -100 -1 -100 -1 -1 79 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -390,9 +390,9 @@ 77 53 0.00000e+00 2 2000016 -2000016 ~nu_tauR ~nu_tauRbar 78 53 0.00000e+00 2 1000016 -2000016 ~nu_tauL ~nu_tauRbar 79 53 0.00000e+00 2 -1000016 2000016 ~nu_tauLbar ~nu_tauR - 39 reggeon 28 0 100 GaugeBoson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 40 pomeron 29 0 100 GaugeBoson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 41 Z'0 32 0 100 GaugeBoson 0 5.00000e+02 1.45485e+01 -100 -1 -100 -1 -1 22 + 39 reggeon 28 0 100 GaugeBoson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 40 pomeron 29 0 100 GaugeBoson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 41 Z'0 32 0 100 GaugeBoson 0 5.000000e+02 1.454850e+01 -100 -1 -100 -1 -1 22 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -418,8 +418,8 @@ 20 0 0.00000e+00 2 23 25 Z0 h0 21 0 0.00000e+00 2 25 36 h0 A0 22 0 0.00000e+00 2 35 36 H0 A0 - 42 Z"0 33 0 100 GaugeBoson 0 9.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 43 W'+ 34 1 100 GaugeBoson 3 5.00000e+02 1.66708e+01 -100 -1 -100 -1 -1 23 + 42 Z"0 33 0 100 GaugeBoson 0 9.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 43 W'+ 34 1 100 GaugeBoson 3 5.000000e+02 1.667080e+01 -100 -1 -100 -1 -1 23 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -446,8 +446,8 @@ 21 0 0.00000e+00 2 24 23 W+ Z0 22 0 0.00000e+00 2 24 22 W+ gamma 23 0 0.00000e+00 2 24 25 W+ h0 - 44 W'- -34 43 0 - 45 H0 35 0 100 GaugeBoson 0 3.00000e+02 8.42842e+00 -100 -1 -100 -1 -1 82 + 44 W'- -34 43 0 + 45 H0 35 0 100 GaugeBoson 0 3.000000e+02 8.428420e+00 -100 -1 -100 -1 -1 82 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -533,7 +533,7 @@ 80 53 0.00000e+00 2 2000016 -2000016 ~nu_tauR ~nu_tauRbar 81 53 0.00000e+00 2 1000016 -2000016 ~nu_tauL ~nu_tauRbar 82 53 0.00000e+00 2 -1000016 2000016 ~nu_tauLbar ~nu_tauR - 46 A0 36 0 100 GaugeBoson 0 3.00000e+02 4.92026e+00 -100 -1 -100 -1 -1 80 + 46 A0 36 0 100 GaugeBoson 0 3.000000e+02 4.920260e+00 -100 -1 -100 -1 -1 80 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -617,7 +617,7 @@ 78 53 0.00000e+00 2 2000016 -2000016 ~nu_tauR ~nu_tauRbar 79 53 0.00000e+00 2 1000016 -2000016 ~nu_tauL ~nu_tauRbar 80 53 0.00000e+00 2 -1000016 2000016 ~nu_tauLbar ~nu_tauR - 47 H+ 37 1 100 GaugeBoson 3 3.00000e+02 5.75967e+00 -100 -1 -100 -1 -1 27 + 47 H+ 37 1 100 GaugeBoson 3 3.000000e+02 5.759670e+00 -100 -1 -100 -1 -1 27 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -648,21 +648,21 @@ 25 53 0.00000e+00 2 -1000013 1000014 ~mu_L+ ~nu_muL 26 53 0.00000e+00 2 -1000015 1000016 ~tau_1+ ~nu_tauL 27 53 0.00000e+00 2 -2000015 1000016 ~tau_2+ ~nu_tauL - 48 H- -37 47 0 - 49 eta_tech0 38 0 100 Unknown 0 3.50000e+02 1.01580e-01 -100 -1 -100 -1 -1 3 + 48 H- -37 47 0 + 49 eta_tech0 38 0 100 Unknown 0 3.500000e+02 1.015800e-01 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 32 4.52899e-01 2 5 -5 b bbar 2 32 0.00000e+00 2 6 -6 t tbar 3 32 5.47101e-01 2 21 21 g g - 50 LQ_ue 39 1 100 Unknown -1 2.00000e+02 3.91620e-01 -100 -1 -100 -1 -1 1 + 50 LQ_ue 39 1 100 Unknown -1 2.000000e+02 3.916200e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 2 11 u e- - 51 LQ_ue_bar -39 50 0 - 52 R0 40 1 100 Unknown 0 5.00000e+03 4.17465e+02 -100 -1 -100 -1 -1 9 + 51 LQ_ue_bar -39 50 0 + 52 R0 40 1 100 Unknown 0 5.000000e+03 4.174650e+02 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -675,8 +675,8 @@ 7 0 6.99300e-02 2 11 -13 e- mu+ 8 0 6.99300e-02 2 13 -15 mu- tau+ 9 0 0.00000e+00 2 15 -17 tau- tau'+ - 53 R0_bar -40 52 0 - 54 pi_tech0 51 0 100 Unknown 0 1.10000e+02 4.10400e-02 -100 -1 -100 -1 -1 8 + 53 R0_bar -40 52 0 + 54 pi_tech0 51 0 100 Unknown 0 1.100000e+02 4.104000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -688,7 +688,7 @@ 6 0 1.77000e-04 2 13 -13 mu- mu+ 7 0 5.00550e-02 2 15 -15 tau- tau+ 8 32 3.16112e-01 2 21 21 g g - 55 pi_tech+ 52 1 100 Unknown 3 1.10000e+02 1.05000e-02 -100 -1 -100 -1 -1 6 + 55 pi_tech+ 52 1 100 Unknown 3 1.100000e+02 1.050000e-02 -100 -1 -100 -1 -1 6 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -698,8 +698,8 @@ 4 0 0.00000e+00 2 -11 12 e+ nu_e 5 0 1.73000e-04 2 -13 14 mu+ nu_mu 6 0 4.89050e-02 2 -15 16 tau+ nu_tau - 56 pi_tech- -52 55 0 - 57 pi'_tech0 53 0 100 Unknown 0 1.10000e+02 2.80700e-02 -100 -1 -100 -1 -1 8 + 56 pi_tech- -52 55 0 + 57 pi'_tech0 53 0 100 Unknown 0 1.100000e+02 2.807000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -711,7 +711,7 @@ 6 0 2.59000e-04 2 13 -13 mu- mu+ 7 0 7.31920e-02 2 15 -15 tau- tau+ 8 32 0.00000e+00 2 21 21 g g - 58 rho_tech0 54 0 100 Unknown 0 2.10000e+02 8.21010e-01 -100 -1 -100 -1 -1 24 + 58 rho_tech0 54 0 100 Unknown 0 2.100000e+02 8.210100e-01 -100 -1 -100 -1 -1 24 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -739,7 +739,7 @@ 22 0 1.03000e-03 2 16 -16 nu_tau nu_taubar 23 0 0.00000e+00 2 17 -17 tau'- tau'+ 24 0 0.00000e+00 2 18 -18 nu'_tau nu'_taubar - 59 rho_tech+ 55 1 100 Unknown 3 2.10000e+02 6.49730e-01 -100 -1 -100 -1 -1 26 + 59 rho_tech+ 55 1 100 Unknown 3 2.100000e+02 6.497300e-01 -100 -1 -100 -1 -1 26 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -769,8 +769,8 @@ 24 0 9.66100e-03 2 -13 14 mu+ nu_mu 25 0 9.66000e-03 2 -15 16 tau+ nu_tau 26 0 0.00000e+00 2 -17 18 tau'+ nu'_tau - 60 rho_tech- -55 59 0 - 61 omega_tech 56 0 100 Unknown 0 2.10000e+02 1.57500e-01 -100 -1 -100 -1 -1 24 + 60 rho_tech- -55 59 0 + 61 omega_tech 56 0 100 Unknown 0 2.100000e+02 1.575000e-01 -100 -1 -100 -1 -1 24 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -798,7 +798,7 @@ 22 0 1.11810e-02 2 16 -16 nu_tau nu_taubar 23 0 0.00000e+00 2 17 -17 tau'- tau'+ 24 0 0.00000e+00 2 18 -18 nu'_tau nu'_taubar - 62 H_L++ 61 1 100 Unknown 6 2.00000e+02 8.81610e-01 -100 -1 -100 -1 -1 7 + 62 H_L++ 61 1 100 Unknown 6 2.000000e+02 8.816100e-01 -100 -1 -100 -1 -1 7 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -809,8 +809,8 @@ 5 0 1.80500e-03 2 -13 -15 mu+ tau+ 6 0 8.12250e-01 2 -15 -15 tau+ tau+ 7 0 1.80600e-03 2 24 24 W+ W+ - 63 H_L-- -61 62 0 - 64 H_R++ 62 1 100 Unknown 6 2.00000e+02 8.80010e-01 -100 -1 -100 -1 -1 7 + 63 H_L-- -61 62 0 + 64 H_R++ 62 1 100 Unknown 6 2.000000e+02 8.800100e-01 -100 -1 -100 -1 -1 7 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -821,8 +821,8 @@ 5 0 1.80800e-03 2 -13 -15 mu+ tau+ 6 0 8.13720e-01 2 -15 -15 tau+ tau+ 7 0 0.00000e+00 2 63 63 W_R+ W_R+ - 65 H_R-- -62 64 0 - 66 W_R+ 63 1 100 Unknown 3 7.50000e+02 1.93391e+01 -100 -1 -100 -1 -1 12 + 65 H_R-- -62 64 0 + 66 W_R+ 63 1 100 Unknown 3 7.500000e+02 1.933910e+01 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -838,22 +838,22 @@ 10 0 0.00000e+00 2 -11 64 e+ nu_Re 11 0 0.00000e+00 2 -13 65 mu+ nu_Rmu 12 0 0.00000e+00 2 -15 66 tau+ nu_Rtau - 67 W_R- -63 66 0 - 68 nu_Re 64 1 100 Unknown 0 7.50000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 69 nu_Re_bar -64 68 0 - 70 nu_Rmu 65 1 100 Unknown 0 7.50000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 71 nu_Rmu_bar -65 70 0 - 72 nu_Rtau 66 1 100 Unknown 0 7.50000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 73 nu_Rtau_bar -66 72 0 - 74 specflav 81 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 75 rndmflav 82 1 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 76 rndmflav_bar -82 75 0 - 77 phasespa 83 0 100 Generator 0 1.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 67 W_R- -63 66 0 + 68 nu_Re 64 1 100 Unknown 0 7.500000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 69 nu_Re_bar -64 68 0 + 70 nu_Rmu 65 1 100 Unknown 0 7.500000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 71 nu_Rmu_bar -65 70 0 + 72 nu_Rtau 66 1 100 Unknown 0 7.500000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 73 nu_Rtau_bar -66 72 0 + 74 specflav 81 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 75 rndmflav 82 1 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 76 rndmflav_bar -82 75 0 + 77 phasespa 83 0 100 Generator 0 1.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 12 1.00000e+00 2 82 -82 rndmflav rndmflavbar - 78 c-hadron 84 1 100 Generator 2 2.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 78 c-hadron 84 1 100 Generator 2 2.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -861,8 +861,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 79 c-hadron_bar -84 78 0 - 80 b-hadron 85 1 100 Generator -1 5.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 79 c-hadron_bar -84 78 0 + 80 b-hadron 85 1 100 Generator -1 5.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -875,24 +875,24 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 81 b-hadron_bar -85 80 0 - 82 cluster 91 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 83 string 92 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 84 indep. 93 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 85 CMshower 94 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 86 SPHEaxis 95 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 87 THRUaxis 96 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 88 CLUSjet 97 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 89 CELLjet 98 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 90 table 99 0 100 Generator 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 91 rho_diff0 110 0 100 Unknown 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 92 pi0 111 0 100 Meson 0 1.34977e-01 0.00000e+00 -100 -1 -100 -1 -1 2 + 81 b-hadron_bar -85 80 0 + 82 cluster 91 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 83 string 92 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 84 indep. 93 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 85 CMshower 94 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 86 SPHEaxis 95 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 87 THRUaxis 96 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 88 CLUSjet 97 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 89 CELLjet 98 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 90 table 99 0 100 Generator 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 91 rho_diff0 110 0 100 Unknown 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 92 pi0 111 0 100 Meson 0 1.349768e-01 7.810000e-09 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 9.88000e-01 2 22 22 gamma gamma 2 2 1.20000e-02 3 22 11 -11 gamma e- e+ - 93 rho0 113 0 100 Meson 0 7.75490e-01 1.51000e-01 -100 -1 -100 -1 -1 5 + 93 rho0 113 0 100 Meson 0 7.752600e-01 1.491000e-01 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -901,7 +901,7 @@ 3 0 3.80000e-04 2 221 22 eta gamma 4 0 4.60000e-05 2 13 -13 mu- mu+ 5 0 4.50000e-05 2 11 -11 e- e+ - 94 a_20 115 0 100 Meson 0 1.31830e+00 1.07000e-01 -100 -1 -100 -1 -1 9 + 94 a_20 115 0 100 Meson 0 1.318200e+00 1.070000e-01 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -914,7 +914,7 @@ 7 0 1.22500e-02 2 310 310 K_S0 K_S0 8 0 2.80000e-03 2 111 22 pi0 gamma 9 0 5.70000e-03 2 331 111 eta' pi0 - 95 K_L0 130 0 100 Meson 0 4.976140e-01 0.00000e+00 -100 -1 -100 -1 -1 9 + 95 K_L0 130 0 100 Meson 0 4.976110e-01 1.287000e-17 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -927,23 +927,23 @@ 7 0 2.00000e-03 2 211 -211 pi+ pi- 8 0 1.00000e-03 2 111 111 pi0 pi0 9 0 6.00000e-04 2 22 22 gamma gamma - 96 pi_diffr+ 210 1 100 Meson 3 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 97 pi_diffr- -210 96 0 - 98 pi+ 211 1 100 Meson 3 1.39570e-01 2.52837e-17 -100 -1 -100 -1 -1 2 + 96 pi_diffr+ 210 1 100 Meson 3 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 97 pi_diffr- -210 96 0 + 98 pi+ 211 1 100 Meson 3 1.395704e-01 2.528400e-17 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 9.99877e-01 2 -13 14 mu+ nu_mu 2 0 1.23000e-04 2 -11 12 e+ nu_e - 99 pi- -211 98 0 - 100 rho+ 213 1 100 Meson 3 7.75490e-01 1.49000e-01 -100 -1 -100 -1 -1 2 + 99 pi- -211 98 0 + 100 rho+ 213 1 100 Meson 3 7.754900e-01 1.490000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 3 9.99550e-01 2 211 111 pi+ pi0 2 0 4.50000e-04 2 211 22 pi+ gamma - 101 rho- -213 100 0 - 102 a_2+ 215 1 100 Meson 3 1.31830e+00 1.07000e-01 -100 -1 -100 -1 -1 7 + 101 rho- -213 100 0 + 102 a_2+ 215 1 100 Meson 3 1.318300e+00 1.070000e-01 -100 -1 -100 -1 -1 7 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -954,9 +954,9 @@ 5 0 4.90000e-02 2 321 -311 K+ Kbar0 6 0 2.80000e-03 2 211 22 pi+ gamma 7 0 5.70000e-03 2 331 211 eta' pi+ - 103 a_2- -215 102 0 - 104 omega_di 220 0 100 Meson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 105 eta 221 0 100 Meson 0 5.47853e-01 0.00000e+00 -100 -1 -100 -1 -1 8 + 103 a_2- -215 102 0 + 104 omega_di 220 0 100 Meson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 105 eta 221 0 100 Meson 0 5.478620e-01 1.310000e-06 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -968,7 +968,7 @@ 6 0 1.30000e-03 4 211 -211 11 -11 pi+ pi- e- e+ 7 0 3.00000e-04 3 22 13 -13 gamma mu- mu+ 8 0 7.00000e-04 3 111 22 22 pi0 gamma gamma - 106 omega 223 0 100 Meson 0 7.82650e-01 8.43000e-03 -100 -1 -100 -1 -1 6 + 106 omega 223 0 100 Meson 0 7.826600e-01 8.680000e-03 -100 -1 -100 -1 -1 6 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -978,7 +978,7 @@ 4 0 8.30000e-04 2 221 22 eta gamma 5 0 7.00000e-05 3 111 111 22 pi0 pi0 gamma 6 0 7.00000e-05 2 11 -11 e- e+ - 107 f_2 225 0 100 Meson 0 1.27510e+00 1.85000e-01 -100 -1 -100 -1 -1 9 + 107 f_2 225 0 100 Meson 0 1.275400e+00 1.866000e-01 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -991,28 +991,28 @@ 7 0 1.15000e-02 2 310 310 K_S0 K_S0 8 0 5.00000e-03 2 221 221 eta eta 9 0 3.00000e-03 4 111 111 111 111 pi0 pi0 pi0 pi0 - 108 K_S0 310 0 100 Meson 0 4.976140e-01 0.00000e+00 -100 -1 -100 -1 -1 2 + 108 K_S0 310 0 100 Meson 0 4.976110e-01 7.350800e-15 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.86100e-01 2 211 -211 pi+ pi- 2 0 3.13900e-01 2 111 111 pi0 pi0 - 109 K0 311 1 100 Meson 0 4.97614e-01 0.00000e+00 -100 -1 -100 -1 -1 2 + 109 K0 311 1 100 Meson 0 4.976110e-01 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 1 130 K_L0 2 0 5.00000e-01 1 310 K_S0 - 110 K0_bar -311 109 0 - 111 K*0 313 1 100 Meson 0 8.96000e-01 5.05000e-02 -100 -1 -100 -1 -1 3 + 110 K0_bar -311 109 0 + 111 K*0 313 1 100 Meson 0 8.955500e-01 4.730000e-02 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 3 6.65000e-01 2 321 -211 K+ pi- 2 3 3.33000e-01 2 311 111 K0 pi0 3 0 2.00000e-03 2 311 22 K0 gamma - 112 K*0_bar -313 111 0 - 113 K*_20 315 1 100 Meson 0 1.43240e+00 1.09000e-01 -100 -1 -100 -1 -1 10 + 112 K*0_bar -313 111 0 + 113 K*_20 315 1 100 Meson 0 1.432400e+00 1.090000e-01 -100 -1 -100 -1 -1 10 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1026,8 +1026,8 @@ 8 0 2.90000e-02 2 311 113 K0 rho0 9 0 2.90000e-02 2 311 223 K0 omega 10 0 2.00000e-03 2 311 221 K0 eta - 114 K*_20_bar -315 113 0 - 115 K+ 321 1 100 Meson 3 4.93677e-01 5.31674e-17 -100 -1 -100 -1 -1 6 + 114 K*_20_bar -315 113 0 + 115 K+ 321 1 100 Meson 3 4.936770e-01 5.317000e-17 -100 -1 -100 -1 -1 6 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1037,16 +1037,16 @@ 4 0 1.73000e-02 3 211 111 111 pi+ pi0 pi0 5 42 4.82000e-02 3 12 -11 111 nu_e e+ pi0 6 42 3.18000e-02 3 14 -13 111 nu_mu mu+ pi0 - 116 K- -321 115 0 - 117 K*+ 323 1 100 Meson 3 8.91660e-01 4.98000e-02 -100 -1 -100 -1 -1 3 + 116 K- -321 115 0 + 117 K*+ 323 1 100 Meson 3 8.916700e-01 5.140000e-02 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 3 6.66000e-01 2 311 211 K0 pi+ 2 3 3.33000e-01 2 321 111 K+ pi0 3 0 1.00000e-03 2 321 22 K+ gamma - 118 K*- -323 117 0 - 119 K*_2+ 325 1 100 Meson 3 1.42560e+00 9.80000e-02 -100 -1 -100 -1 -1 11 + 118 K*- -323 117 0 + 119 K*_2+ 325 1 100 Meson 3 1.427300e+00 1.000000e-01 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1061,9 +1061,9 @@ 9 0 2.90000e-02 2 321 223 K+ omega 10 0 2.00000e-03 2 321 221 K+ eta 11 0 2.00000e-03 2 321 22 K+ gamma - 120 K*_2- -325 119 0 - 121 phi_diff 330 0 100 Meson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 122 eta' 331 0 100 Meson 0 9.57660e-01 2.00000e-04 -100 -1 -100 -1 -1 6 + 120 K*_2- -325 119 0 + 121 phi_diff 330 0 100 Meson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 122 eta' 331 0 100 Meson 0 9.577800e-01 1.880000e-04 -100 -1 -100 -1 -1 6 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1073,7 +1073,7 @@ 4 0 3.02000e-02 2 22 223 gamma omega 5 0 2.12000e-02 2 22 22 gamma gamma 6 0 1.60000e-03 3 111 111 111 pi0 pi0 pi0 - 123 phi 333 0 100 Meson 0 1.019455e+00 4.43000e-03 -100 -1 -100 -1 -1 11 + 123 phi 333 0 100 Meson 0 1.019461e+00 4.249000e-03 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1088,7 +1088,7 @@ 9 0 3.00000e-04 2 11 -11 e- e+ 10 0 2.50000e-04 2 13 -13 mu- mu+ 11 0 8.00000e-05 2 211 -211 pi+ pi- - 124 f'_2 335 0 100 Meson 0 1.52500e+00 7.60000e-02 -100 -1 -100 -1 -1 6 + 124 f'_2 335 0 100 Meson 0 1.517400e+00 8.600000e-02 -100 -1 -100 -1 -1 6 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1098,7 +1098,7 @@ 4 0 1.04000e-01 2 221 221 eta eta 5 0 4.00000e-03 2 211 -211 pi+ pi- 6 0 4.00000e-03 2 111 111 pi0 pi0 - 125 D+ 411 1 100 CharmedMeson 3 1.86962e+00 0.00000e+00 -100 -1 -100 -1 -1 63 + 125 D+ 411 1 100 CharmedMeson 3 1.869660e+00 6.370000e-13 -100 -1 -100 -1 -1 63 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1165,16 +1165,16 @@ 61 0 1.90000e-03 5 -321 113 211 211 111 K- rho0 pi+ pi+ pi0 62 0 1.50000e-03 5 211 211 211 -211 -211 pi+ pi+ pi+ pi- pi- 63 0 2.80000e-03 5 113 211 211 -211 111 rho0 pi+ pi+ pi- pi0 - 126 D- -411 125 0 - 127 D*+ 413 1 100 CharmedMeson 3 2.01027e+00 0.00000e+00 -100 -1 -100 -1 -1 3 + 126 D- -411 125 0 + 127 D*+ 413 1 100 CharmedMeson 3 2.010260e+00 8.340000e-05 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 3 6.83000e-01 2 421 211 D0 pi+ 2 3 3.06000e-01 2 411 111 D+ pi0 3 0 1.10000e-02 2 411 22 D+ gamma - 128 D*- -413 127 0 - 129 D*_2+ 415 1 100 CharmedMeson 3 2.46010e+00 2.30000e-02 -100 -1 -100 -1 -1 8 + 128 D*- -413 127 0 + 129 D*_2+ 415 1 100 CharmedMeson 3 2.460100e+00 2.300000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1186,8 +1186,8 @@ 6 0 6.00000e-02 3 413 211 -211 D*+ pi+ pi- 7 0 8.00000e-02 3 421 211 111 D0 pi+ pi0 8 0 4.00000e-02 3 411 211 -211 D+ pi+ pi- - 130 D*_2- -415 129 0 - 131 D0 421 1 100 CharmedMeson 0 1.86484e+00 0.00000e+00 -100 -1 -100 -1 -1 61 + 130 D*_2- -415 129 0 + 131 D0 421 1 100 CharmedMeson 0 1.864840e+00 1.604000e-12 -100 -1 -100 -1 -1 61 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1252,15 +1252,15 @@ 59 0 1.70000e-02 5 211 211 -211 -211 111 pi+ pi+ pi- pi- pi0 60 0 4.00000e-04 5 113 211 211 -211 -211 rho0 pi+ pi+ pi- pi- 61 0 2.80000e-03 5 321 -321 211 -211 111 K+ K- pi+ pi- pi0 - 132 D0_bar -421 131 0 - 133 D*0 423 1 100 CharmedMeson 0 2.006970e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 132 D0_bar -421 131 0 + 133 D*0 423 1 100 CharmedMeson 0 2.006850e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 3 6.19000e-01 2 421 111 D0 pi0 2 0 3.81000e-01 2 421 22 D0 gamma - 134 D*0_bar -423 133 0 - 135 D*_20 425 1 100 CharmedMeson 0 2.46110e+00 2.30000e-02 -100 -1 -100 -1 -1 8 + 134 D*0_bar -423 133 0 + 135 D*_20 425 1 100 CharmedMeson 0 2.461100e+00 4.730000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1272,8 +1272,8 @@ 6 0 6.00000e-02 3 423 211 -211 D*0 pi+ pi- 7 0 8.00000e-02 3 411 -211 111 D+ pi- pi0 8 0 4.00000e-02 3 421 211 -211 D0 pi+ pi- - 136 D*_20_bar -425 135 0 - 137 D_s+ 431 1 100 CharmedMeson 3 1.96850e+00 0.00000e+00 -100 -1 -100 -1 -1 33 + 136 D*_20_bar -425 135 0 + 137 D_s+ 431 1 100 CharmedMeson 3 1.968350e+00 1.305000e-12 -100 -1 -100 -1 -1 33 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1310,15 +1310,15 @@ 31 0 5.00000e-03 2 221 323 eta K*+ 32 13 2.50000e-01 4 2 -1 3 -3 u dbar s sbar 33 13 9.52000e-02 2 2 -1 u dbar - 138 D_s- -431 137 0 - 139 D*_s+ 433 1 100 CharmedMeson 3 2.11230e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 138 D_s- -431 137 0 + 139 D*_s+ 433 1 100 CharmedMeson 3 2.112200e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 9.40000e-01 2 431 22 D_s+ gamma 2 0 6.00000e-02 2 431 111 D_s+ pi0 - 140 D*_s- -433 139 0 - 141 D*_2s+ 435 1 100 CharmedMeson 3 2.57260e+00 1.50000e-02 -100 -1 -100 -1 -1 4 + 140 D*_s- -433 139 0 + 141 D*_2s+ 435 1 100 CharmedMeson 3 2.569100e+00 1.690000e-02 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1326,27 +1326,27 @@ 2 0 4.00000e-01 2 411 311 D+ K0 3 0 1.00000e-01 2 423 321 D*0 K+ 4 0 1.00000e-01 2 413 311 D*+ K0 - 142 D*_2s- -435 141 0 - 143 J/psi_di 440 0 100 CharmedMeson 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 144 eta_c 441 0 100 CharmedMeson 0 2.98030e+00 1.30000e-03 -100 -1 -100 -1 -1 1 + 142 D*_2s- -435 141 0 + 143 J/psi_di 440 0 100 CharmedMeson 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 144 eta_c 441 0 100 CharmedMeson 0 2.983900e+00 3.200000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 12 1.00000e+00 2 82 -82 rndmflav rndmflavbar - 145 J/psi 443 0 100 Meson 0 3.096916e+00 0.00000e+00 -100 -1 -100 -1 -1 3 + 145 J/psi 443 0 100 Meson 0 3.096900e+00 9.260000e-05 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.02000e-02 2 11 -11 e- e+ 2 0 6.01000e-02 2 13 -13 mu- mu+ 3 12 8.79700e-01 2 82 -82 rndmflav rndmflavbar - 146 chi_2c 445 0 100 CharmedMeson 0 3.55620e+00 2.00000e-03 -100 -1 -100 -1 -1 2 + 146 chi_2c 445 0 100 CharmedMeson 0 3.556170e+00 1.970000e-03 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.35000e-01 2 443 22 J/psi gamma 2 12 8.65000e-01 2 82 -82 rndmflav rndmflavbar - 147 B0 511 1 100 B-Meson 0 5.27953e+00 0.00000e+00 -100 -1 -100 -1 -1 36 + 147 B0 511 1 100 B-Meson 0 5.279660e+00 4.333000e-13 -100 -1 -100 -1 -1 36 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1386,14 +1386,14 @@ 34 13 2.00000e-02 4 4 -4 -3 1 c cbar sbar d 35 42 1.50000e-02 4 2 -1 -2 1 u dbar ubar d 36 42 5.00000e-03 4 4 -3 -2 1 c sbar ubar d - 148 B0_bar -511 147 0 - 149 B*0 513 1 100 B-Meson 0 5.32510e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 148 B0_bar -511 147 0 + 149 B*0 513 1 100 B-Meson 0 5.324710e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 511 22 B0 gamma - 150 B*0_bar -513 149 0 - 151 B*_20 515 1 100 B-Meson 0 5.74690e+00 2.00000e-02 -100 -1 -100 -1 -1 8 + 150 B*0_bar -513 149 0 + 151 B*_20 515 1 100 B-Meson 0 5.739500e+00 2.420000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1405,8 +1405,8 @@ 6 0 6.00000e-02 3 513 211 -211 B*0 pi+ pi- 7 0 8.00000e-02 3 521 -211 111 B+ pi- pi0 8 0 4.00000e-02 3 511 211 -211 B0 pi+ pi- - 152 B*_20_bar -515 151 0 - 153 B+ 521 1 100 B-Meson 3 5.27915e+00 0.00000e+00 -100 -1 -100 -1 -1 36 + 152 B*_20_bar -515 151 0 + 153 B+ 521 1 100 B-Meson 3 5.279340e+00 4.018000e-13 -100 -1 -100 -1 -1 36 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1446,14 +1446,14 @@ 34 13 2.00000e-02 4 4 -4 -3 2 c cbar sbar u 35 42 1.50000e-02 4 2 -1 -2 2 u dbar ubar u 36 42 5.00000e-03 4 4 -3 -2 2 c sbar ubar u - 154 B- -521 153 0 - 155 B*+ 523 1 100 Meson 3 5.32510e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 154 B- -521 153 0 + 155 B*+ 523 1 100 Meson 3 5.325100e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 521 22 B+ gamma - 156 B*- -523 155 0 - 157 B*_2+ 525 1 100 B-Meson 3 5.74690e+00 2.00000e-02 -100 -1 -100 -1 -1 8 + 156 B*- -523 155 0 + 157 B*_2+ 525 1 100 B-Meson 3 5.737200e+00 2.000000e-02 -100 -1 -100 -1 -1 8 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1465,8 +1465,8 @@ 6 0 6.00000e-02 3 523 211 -211 B*+ pi+ pi- 7 0 8.00000e-02 3 511 211 111 B0 pi+ pi0 8 0 4.00000e-02 3 521 211 -211 B+ pi+ pi- - 158 B*_2- -525 157 0 - 159 B_s0 531 1 100 B-Meson 0 5.36630e+00 0.00000e+00 -100 -1 -100 -1 -1 39 + 158 B*_2- -525 157 0 + 159 B_s0 531 1 100 B-Meson 0 5.366920e+00 4.327000e-13 -100 -1 -100 -1 -1 39 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1509,14 +1509,14 @@ 37 13 2.00000e-02 4 4 -4 -3 3 c cbar sbar s 38 42 1.50000e-02 4 2 -1 -2 3 u dbar ubar s 39 42 5.00000e-03 4 4 -3 -2 3 c sbar ubar s - 160 B_s0_bar -531 159 0 - 161 B*_s0 533 1 100 B-Meson 0 5.41280e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 160 B_s0_bar -531 159 0 + 161 B*_s0 533 1 100 B-Meson 0 5.415400e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 531 22 B_s0 gamma - 162 B*_s0_bar -533 161 0 - 163 B*_2s0 535 1 100 B-Meson 0 5.83970e+00 2.00000e-02 -100 -1 -100 -1 -1 4 + 162 B*_s0_bar -533 161 0 + 163 B*_2s0 535 1 100 B-Meson 0 5.839860e+00 1.490000e-03 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1524,8 +1524,8 @@ 2 0 3.00000e-01 2 511 -311 B0 Kbar0 3 0 2.00000e-01 2 523 -321 B*+ K- 4 0 2.00000e-01 2 513 -311 B*0 Kbar0 - 164 B*_2s0_bar -535 163 0 - 165 B_c+ 541 1 100 B-Meson 3 6.27600e+00 0.00000e+00 -100 -1 -100 -1 -1 31 + 164 B*_2s0_bar -535 163 0 + 165 B_c+ 541 1 100 B-Meson 3 6.274470e+00 1.291000e-12 -100 -1 -100 -1 -1 31 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1560,14 +1560,14 @@ 29 42 2.00000e-03 3 -13 14 513 mu+ nu_mu B*0 30 42 1.40000e-02 4 -1 2 1 -5 dbar u d bbar 31 42 3.00000e-03 4 -1 1 2 -5 dbar d u bbar - 166 B_c- -541 165 0 - 167 B*_c+ 543 1 100 B-Meson 3 6.60200e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 166 B_c- -541 165 0 + 167 B*_c+ 543 1 100 B-Meson 3 6.602000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 541 22 B_c+ gamma - 168 B*_c- -543 167 0 - 169 B*_2c+ 545 1 100 B-Meson 3 7.35000e+00 2.00000e-02 -100 -1 -100 -1 -1 4 + 168 B*_c- -543 167 0 + 169 B*_2c+ 545 1 100 B-Meson 3 7.350000e+00 2.000000e-02 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1575,13 +1575,13 @@ 2 0 3.00000e-01 2 521 421 B+ D0 3 0 2.00000e-01 2 513 411 B*0 D+ 4 0 2.00000e-01 2 523 421 B*+ D0 - 170 B*_2c- -545 169 0 - 171 eta_b 551 0 100 B-Meson 0 9.40000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 170 B*_2c- -545 169 0 + 171 eta_b 551 0 100 B-Meson 0 9.398700e+00 1.000000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 32 1.00000e+00 2 21 21 g g - 172 Upsilon 553 0 100 B-Meson 0 9.46030e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 172 Upsilon 553 0 100 B-Meson 0 9.460400e+00 5.400000e-05 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1594,76 +1594,76 @@ 7 32 4.50000e-02 2 4 -4 c cbar 8 4 7.74300e-01 3 21 21 21 g g g 9 4 2.90000e-02 3 22 21 21 gamma g g - 173 chi_2b 555 0 100 B-Meson 0 9.91220e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 173 chi_2b 555 0 100 B-Meson 0 9.912200e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 2.20000e-01 2 553 22 Upsilon gamma 2 32 7.80000e-01 2 21 21 g g - 174 dd_1 1103 1 100 Unknown -2 9.60000e-01 0.00000e+00 -100 -1 -100 -1 -1 0 + 174 dd_1 1103 1 100 Unknown -2 9.600000e-01 0.000000e+00 -100 -1 -100 -1 -1 0 175 dd_1_bar -1103 174 0 - 176 Delta- 1114 1 100 Unknown -3 1.23200e+00 1.20000e-01 -100 -1 -100 -1 -1 1 + 176 Delta- 1114 1 100 Unknown -3 1.232000e+00 1.170000e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 2112 -211 n0 pi- - 177 Delta-_bar -1114 176 0 - 178 ud_0 2101 1 100 Unknown 1 7.30000e-03 0.00000e+00 -100 -1 -100 -1 -1 0 - 179 ud_0_bar -2101 178 0 - 180 ud_1 2103 1 100 Unknown 1 7.20000e-03 0.00000e+00 -100 -1 -100 -1 -1 0 - 181 ud_1_bar -2103 180 0 - 182 n_diffr0 2110 1 100 Unknown 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 183 n_diffr0_bar -2110 182 0 - 184 neutron 2112 1 100 Baryon 0 9.39565e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 185 antineutron -2112 184 0 - 186 Delta0 2114 1 100 Baryon 0 1.23200e+00 1.20000e-01 -100 -1 -100 -1 -1 3 + 177 Delta-_bar -1114 176 0 + 178 ud_0 2101 1 100 Unknown 1 7.300000e-03 0.000000e+00 -100 -1 -100 -1 -1 0 + 179 ud_0_bar -2101 178 0 + 180 ud_1 2103 1 100 Unknown 1 7.200000e-03 0.000000e+00 -100 -1 -100 -1 -1 0 + 181 ud_1_bar -2103 180 0 + 182 n_diffr0 2110 1 100 Unknown 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 183 n_diffr0_bar -2110 182 0 + 184 neutron 2112 1 100 Baryon 0 9.395654e-01 7.493000e-28 -100 -1 -100 -1 -1 0 + 185 antineutron -2112 184 0 + 186 Delta0 2114 1 100 Baryon 0 1.232000e+00 1.200000e-01 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 3.31000e-01 2 2212 -211 p+ pi- 2 0 6.63000e-01 2 2112 111 n0 pi0 3 0 6.00000e-03 2 2112 22 n0 gamma - 187 Delta0_bar -2114 186 0 - 188 uu_1 2203 1 100 Unknown 4 4.80000e-03 0.00000e+00 -100 -1 -100 -1 -1 0 - 189 uu_1_bar -2203 188 0 - 190 p_diffr+ 2210 1 100 Unknown 3 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 191 p_diffr+_bar -2210 190 0 - 192 proton 2212 1 100 Baryon 3 9.38272e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 193 antiproton -2212 192 0 - 194 Delta+ 2214 1 100 Baryon 3 1.23200e+00 1.20000e-01 -100 -1 -100 -1 -1 3 + 187 Delta0_bar -2114 186 0 + 188 uu_1 2203 1 100 Unknown 4 4.800000e-03 0.000000e+00 -100 -1 -100 -1 -1 0 + 189 uu_1_bar -2203 188 0 + 190 p_diffr+ 2210 1 100 Unknown 3 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 191 p_diffr+_bar -2210 190 0 + 192 proton 2212 1 100 Baryon 3 9.382721e-01 0.000000e+00 -100 -1 -100 -1 -1 0 + 193 antiproton -2212 192 0 + 194 Delta+ 2214 1 100 Baryon 3 1.232000e+00 1.200000e-01 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.63000e-01 2 2212 111 p+ pi0 2 0 3.31000e-01 2 2112 211 n0 pi+ 3 0 6.00000e-03 2 2212 22 p+ gamma - 195 Delta+_bar -2214 194 0 - 196 Delta++ 2224 1 100 Baryon 6 1.23200e+00 1.20000e-01 -100 -1 -100 -1 -1 1 + 195 Delta+_bar -2214 194 0 + 196 Delta++ 2224 1 100 Baryon 6 1.232000e+00 1.200000e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 2212 211 p+ pi+ - 197 Delta-- -2224 196 0 - 198 sd_0 3101 1 100 Unknown -2 1.08000e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 199 sd_0_bar -3101 198 0 - 200 sd_1 3103 1 100 Unknown -2 1.08800e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 201 sd_1_bar -3103 200 0 - 202 Sigma- 3112 1 100 Baryon -3 1.19744e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 197 Delta-- -2224 196 0 + 198 sd_0 3101 1 100 Unknown -2 1.080000e-01 0.000000e+00 -100 -1 -100 -1 -1 0 + 199 sd_0_bar -3101 198 0 + 200 sd_1 3103 1 100 Unknown -2 1.088000e-01 0.000000e+00 -100 -1 -100 -1 -1 0 + 201 sd_1_bar -3103 200 0 + 202 Sigma- 3112 1 100 Baryon -3 1.197449e+00 4.450000e-15 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 9.99000e-01 2 2112 -211 n0 pi- 2 0 1.00000e-03 3 -12 11 2112 nu_ebar e- n0 - 203 Sigma-_bar -3112 202 0 - 204 Sigma*- 3114 1 100 Baryon -3 1.38720e+00 3.94000e-02 -100 -1 -100 -1 -1 3 + 203 Sigma-_bar -3112 202 0 + 204 Sigma*- 3114 1 100 Baryon -3 1.387200e+00 3.940000e-02 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 8.80000e-01 2 3122 -211 Lambda0 pi- 2 0 6.00000e-02 2 3212 -211 Sigma0 pi- 3 0 6.00000e-02 2 3112 111 Sigma- pi0 - 205 Sigma*-_bar -3114 204 0 - 206 Lambda0 3122 1 100 Baryon 0 1.11568e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 205 Sigma*-_bar -3114 204 0 + 206 Lambda0 3122 1 100 Baryon 0 1.115683e+00 2.501000e-15 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1671,44 +1671,44 @@ 2 0 3.58000e-01 2 2112 111 n0 pi0 3 0 2.00000e-03 2 2112 22 n0 gamma 4 0 1.00000e-03 3 -12 11 2212 nu_ebar e- p+ - 207 Lambda0_bar -3122 206 0 - 208 su_0 3201 1 100 Unknown 1 1.06400e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 209 su_0_bar -3201 208 0 - 210 su_1 3203 1 100 Unknown 1 1.06400e-01 0.00000e+00 -100 -1 -100 -1 -1 0 - 211 su_1_bar -3203 210 0 - 212 Sigma0 3212 1 100 Baryon 0 1.192642e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 207 Lambda0_bar -3122 206 0 + 208 su_0 3201 1 100 Unknown 1 1.064000e-01 0.000000e+00 -100 -1 -100 -1 -1 0 + 209 su_0_bar -3201 208 0 + 210 su_1 3203 1 100 Unknown 1 1.064000e-01 0.000000e+00 -100 -1 -100 -1 -1 0 + 211 su_1_bar -3203 210 0 + 212 Sigma0 3212 1 100 Baryon 0 1.192642e+00 8.900000e-06 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 3122 22 Lambda0 gamma - 213 Sigma0_bar -3212 212 0 - 214 Sigma*0 3214 1 100 Baryon 0 1.38370e+00 3.60000e-02 -100 -1 -100 -1 -1 3 + 213 Sigma0_bar -3212 212 0 + 214 Sigma*0 3214 1 100 Baryon 0 1.383700e+00 3.600000e-02 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 8.80000e-01 2 3122 111 Lambda0 pi0 2 0 6.00000e-02 2 3222 -211 Sigma+ pi- 3 0 6.00000e-02 2 3112 211 Sigma- pi+ - 215 Sigma*0_bar -3214 214 0 - 216 Sigma+ 3222 1 100 Baryon 3 1.18937e+00 0.00000e+00 -100 -1 -100 -1 -1 3 + 215 Sigma*0_bar -3214 214 0 + 216 Sigma+ 3222 1 100 Baryon 3 1.189370e+00 8.209000e-15 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.16000e-01 2 2212 111 p+ pi0 2 0 4.83000e-01 2 2112 211 n0 pi+ 3 0 1.00000e-03 2 2212 22 p+ gamma - 217 Sigma+_bar -3222 216 0 - 218 Sigma*+ 3224 1 100 Baryon 3 1.38280e+00 3.58000e-02 -100 -1 -100 -1 -1 3 + 217 Sigma+_bar -3222 216 0 + 218 Sigma*+ 3224 1 100 Baryon 3 1.382830e+00 3.620000e-02 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 8.80000e-01 2 3122 211 Lambda0 pi+ 2 0 6.00000e-02 2 3222 111 Sigma+ pi0 3 0 6.00000e-02 2 3212 211 Sigma0 pi+ - 219 Sigma*+_bar -3224 218 0 - 220 ss_1 3303 1 100 Unknown -2 2.08000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 221 ss_1_bar -3303 220 0 - 222 Xi- 3312 1 100 Baryon -3 1.32171e+00 0.00000e+00 -100 -1 -100 -1 -1 5 + 219 Sigma*+_bar -3224 218 0 + 220 ss_1 3303 1 100 Unknown -2 2.080000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 221 ss_1_bar -3303 220 0 + 222 Xi- 3312 1 100 Baryon -3 1.321710e+00 4.020000e-15 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1717,30 +1717,30 @@ 3 0 6.00000e-04 3 -12 11 3122 nu_ebar e- Lambda0 4 0 4.00000e-04 3 -14 13 3122 nu_mubar mu- Lambda0 5 0 1.00000e-04 3 -12 11 3212 nu_ebar e- Sigma0 - 223 Xi-_bar -3312 222 0 - 224 Xi*- 3314 1 100 Baryon -3 1.53500e+00 9.90000e-03 -100 -1 -100 -1 -1 2 + 223 Xi-_bar -3312 222 0 + 224 Xi*- 3314 1 100 Baryon -3 1.535000e+00 9.900000e-03 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 3322 -211 Xi0 pi- 2 0 3.33000e-01 2 3312 111 Xi- pi0 - 225 Xi*+ -3314 224 0 - 226 Xi0 3322 1 100 Baryon 0 1.31486e+00 0.00000e+00 -100 -1 -100 -1 -1 3 + 225 Xi*+ -3314 224 0 + 226 Xi0 3322 1 100 Baryon 0 1.314860e+00 2.270000e-15 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 9.95400e-01 2 3122 111 Lambda0 pi0 2 0 1.10000e-03 2 3122 22 Lambda0 gamma 3 0 3.50000e-03 2 3212 22 Sigma0 gamma - 227 Xi0_bar -3322 226 0 - 228 Xi*0 3324 1 100 Baryon 0 1.53180e+00 9.10000e-03 -100 -1 -100 -1 -1 2 + 227 Xi0_bar -3322 226 0 + 228 Xi*0 3324 1 100 Baryon 0 1.531800e+00 9.100000e-03 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 3.33000e-01 2 3322 111 Xi0 pi0 2 0 6.67000e-01 2 3312 211 Xi- pi+ - 229 Xi*0_bar -3324 228 0 - 230 Omega- 3334 1 100 Baryon -3 1.67245e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 229 Xi*0_bar -3324 228 0 + 230 Omega- 3334 1 100 Baryon -3 1.672450e+00 8.020000e-15 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1748,24 +1748,24 @@ 2 0 2.34000e-01 2 3322 -211 Xi0 pi- 3 0 8.50000e-02 2 3312 111 Xi- pi0 4 0 5.00000e-03 3 -12 11 3322 nu_ebar e- Xi0 - 231 Omega+ -3334 230 0 - 232 cd_0 4101 1 100 Unknown 1 1.96908e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 233 cd_0_bar -4101 232 0 - 234 cd_1 4103 1 100 Unknown 1 2.00808e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 235 cd_1_bar -4103 234 0 - 236 Sigma_c0 4112 1 100 CharmedBaryon 0 2.45376e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 231 Omega+ -3334 230 0 + 232 cd_0 4101 1 100 Unknown 1 1.969080e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 233 cd_0_bar -4101 232 0 + 234 cd_1 4103 1 100 Unknown 1 2.008080e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 235 cd_1_bar -4103 234 0 + 236 Sigma_c0 4112 1 100 CharmedBaryon 0 2.453750e+00 1.830000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 -211 Lambda_c+ pi- - 237 Sigma_c0_bar -4112 236 0 - 238 Sigma*_c0 4114 1 100 CharmedBaryon 0 2.51800e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 237 Sigma_c0_bar -4112 236 0 + 238 Sigma*_c0 4114 1 100 CharmedBaryon 0 2.518480e+00 1.530000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 -211 Lambda_c+ pi- - 239 Sigma*_c0_bar -4114 238 0 - 240 Lambda_c+ 4122 1 100 CharmedBaryon 3 2.28646e+00 0.00000e+00 -100 -1 -100 -1 -1 76 + 239 Sigma*_c0_bar -4114 238 0 + 240 Lambda_c+ 4122 1 100 CharmedBaryon 3 2.286460e+00 3.270000e-12 -100 -1 -100 -1 -1 76 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1845,8 +1845,8 @@ 74 13 3.00000e-02 2 1 2203 d uu_1 75 13 1.50000e-02 2 2 2101 u ud_0 76 13 1.50000e-02 2 2 2103 u ud_1 - 241 Lambda_c- -4122 240 0 - 242 Xi_c0 4132 1 100 CharmedBaryon 0 2.47100e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 241 Lambda_c- -4122 240 0 + 242 Xi_c0 4132 1 100 CharmedBaryon 0 2.470440e+00 4.330000e-12 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1854,36 +1854,36 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 243 Xi_c0_bar -4132 242 0 - 244 cu_0 4201 1 100 Unknown 4 1.96908e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 245 cu_0_bar -4201 244 0 - 246 cu_1 4203 1 100 Unknown 4 2.00808e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 247 cu_1_bar -4203 246 0 - 248 Sigma_c+ 4212 1 100 CharmedBaryon 3 2.45290e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 243 Xi_c0_bar -4132 242 0 + 244 cu_0 4201 1 100 Unknown 4 1.969080e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 245 cu_0_bar -4201 244 0 + 246 cu_1 4203 1 100 Unknown 4 2.008080e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 247 cu_1_bar -4203 246 0 + 248 Sigma_c+ 4212 1 100 CharmedBaryon 3 2.452650e+00 2.300000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 111 Lambda_c+ pi0 - 249 Sigma_c- -4212 248 0 - 250 Sigma*_c+ 4214 1 100 CharmedBaryon 3 2.51750e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 249 Sigma_c- -4212 248 0 + 250 Sigma*_c+ 4214 1 100 CharmedBaryon 3 2.517400e+00 1.720000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 111 Lambda_c+ pi0 - 251 Sigma*_c- -4214 250 0 - 252 Sigma_c++ 4222 1 100 CharmedBaryon 6 2.45402e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 251 Sigma*_c- -4214 250 0 + 252 Sigma_c++ 4222 1 100 CharmedBaryon 6 2.453970e+00 1.890000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 211 Lambda_c+ pi+ - 253 Sigma_c-- -4222 252 0 - 254 Sigma*_c++ 4224 1 100 CharmedBaryon 6 2.51840e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 253 Sigma_c-- -4222 252 0 + 254 Sigma*_c++ 4224 1 100 CharmedBaryon 6 2.518410e+00 1.478000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4122 211 Lambda_c+ pi+ - 255 Sigma*_c-- -4224 254 0 - 256 Xi_c+ 4232 1 100 CharmedBaryon 3 2.46790e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 255 Sigma*_c-- -4224 254 0 + 256 Xi_c+ 4232 1 100 CharmedBaryon 3 2.467710e+00 1.453000e-12 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1891,38 +1891,38 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 257 Xi_c- -4232 256 0 - 258 cs_0 4301 1 100 CharmedBaryon 1 2.15432e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 259 cs_0_bar -4301 258 0 - 260 cs_1 4303 1 100 Unknown 1 2.17967e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 261 cs_1_bar -4303 260 0 - 262 Xi'_c0 4312 1 100 CharmedBaryon 0 2.57800e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 257 Xi_c- -4232 256 0 + 258 cs_0 4301 1 100 CharmedBaryon 1 2.154320e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 259 cs_0_bar -4301 258 0 + 260 cs_1 4303 1 100 Unknown 1 2.179670e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 261 cs_1_bar -4303 260 0 + 262 Xi'_c0 4312 1 100 CharmedBaryon 0 2.578700e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4132 22 Xi_c0 gamma - 263 Xi'_c0_bar -4312 262 0 - 264 Xi*_c0 4314 1 100 CharmedBaryon 0 2.64610e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 263 Xi'_c0_bar -4312 262 0 + 264 Xi*_c0 4314 1 100 CharmedBaryon 0 2.646160e+00 2.350000e-03 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 4132 111 Xi_c0 pi0 2 0 5.00000e-01 2 4132 22 Xi_c0 gamma - 265 Xi*_c0_bar -4314 264 0 - 266 Xi'_c+ 4322 1 100 CharmedBaryon 3 2.57570e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 265 Xi*_c0_bar -4314 264 0 + 266 Xi'_c+ 4322 1 100 CharmedBaryon 3 2.578200e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4232 22 Xi_c+ gamma - 267 Xi'_c- -4322 266 0 - 268 Xi*_c+ 4324 1 100 CharmedBaryon 3 2.64660e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 267 Xi'_c- -4322 266 0 + 268 Xi*_c+ 4324 1 100 CharmedBaryon 3 2.645100e+00 2.140000e-03 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 4232 111 Xi_c+ pi0 2 0 5.00000e-01 2 4232 22 Xi_c+ gamma - 269 Xi*_c- -4324 268 0 - 270 Omega_c0 4332 1 100 CharmedBaryon 0 2.69750e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 269 Xi*_c- -4324 268 0 + 270 Omega_c0 4332 1 100 CharmedBaryon 0 2.695200e+00 2.460000e-12 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1930,16 +1930,16 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 271 Omega_c0_bar -4332 270 0 - 272 Omega*_c0 4334 1 100 CharmedBaryon 0 2.76830e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 271 Omega_c0_bar -4332 270 0 + 272 Omega*_c0 4334 1 100 CharmedBaryon 0 2.765900e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 4332 22 Omega_c0 gamma - 273 Omega*_c0_bar -4334 272 0 - 274 cc_1 4403 1 100 Unknown 4 3.27531e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 275 cc_1_bar -4403 274 0 - 276 Xi_cc+ 4412 1 100 CharmedBaryon 3 3.59798e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 273 Omega*_c0_bar -4334 272 0 + 274 cc_1 4403 1 100 Unknown 4 3.275310e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 275 cc_1_bar -4403 274 0 + 276 Xi_cc+ 4412 1 100 CharmedBaryon 3 3.597980e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1947,8 +1947,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 277 Xi_cc- -4412 276 0 - 278 Xi*_cc+ 4414 1 100 CharmedBaryon 3 3.65648e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 277 Xi_cc- -4412 276 0 + 278 Xi*_cc+ 4414 1 100 CharmedBaryon 3 3.656480e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1956,8 +1956,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 279 Xi*_cc- -4414 278 0 - 280 Xi_cc++ 4422 1 100 CharmedBaryon 6 3.59798e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 279 Xi*_cc- -4414 278 0 + 280 Xi_cc++ 4422 1 100 CharmedBaryon 6 3.621550e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1965,8 +1965,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 281 Xi_cc-- -4422 280 0 - 282 Xi*_cc++ 4424 1 100 CharmedBaryon 6 3.65648e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 281 Xi_cc-- -4422 280 0 + 282 Xi*_cc++ 4424 1 100 CharmedBaryon 6 3.656480e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1974,8 +1974,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 283 Xi*_cc-- -4424 282 0 - 284 Omega_cc+ 4432 1 100 CharmedBaryon 3 3.78663e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 283 Xi*_cc-- -4424 282 0 + 284 Omega_cc+ 4432 1 100 CharmedBaryon 3 3.786630e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1983,8 +1983,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 285 Omega_cc- -4432 284 0 - 286 Omega*_cc+ 4434 1 100 CharmedBaryon 3 3.82466e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 285 Omega_cc- -4432 284 0 + 286 Omega*_cc+ 4434 1 100 CharmedBaryon 3 3.824660e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -1992,8 +1992,8 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 287 Omega*_cc- -4434 286 0 - 288 Omega*_ccc++ 4444 1 100 CharmedBaryon 6 4.91594e+00 0.00000e+00 -100 -1 -100 -1 -1 4 + 287 Omega*_cc- -4434 286 0 + 288 Omega*_ccc++ 4444 1 100 CharmedBaryon 6 4.915940e+00 0.000000e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2001,24 +2001,24 @@ 2 42 8.00000e-02 4 -13 14 3 81 mu+ nu_mu s specflav 3 11 7.60000e-01 4 2 -1 3 81 u dbar s specflav 4 11 8.00000e-02 4 2 -3 3 81 u sbar s specflav - 289 Omega*_ccc-- -4444 288 0 - 290 bd_0 5101 1 100 Unknown -2 5.38897e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 291 bd_0_bar -5101 290 0 - 292 bd_1 5103 1 100 Unknown -2 5.40145e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 293 bd_1_bar -5103 292 0 - 294 Sigma_b- 5112 1 100 B-Baryon -3 5.81520e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 289 Omega*_ccc-- -4444 288 0 + 290 bd_0 5101 1 100 Unknown -2 5.388970e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 291 bd_0_bar -5101 290 0 + 292 bd_1 5103 1 100 Unknown -2 5.401450e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 293 bd_1_bar -5103 292 0 + 294 Sigma_b- 5112 1 100 B-Baryon -3 5.815640e+00 5.300000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 -211 Lambda_b0 pi- - 295 Sigma_b-_bar -5112 294 0 - 296 Sigma*_b- 5114 1 100 B-Baryon -3 5.83640e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 295 Sigma_b-_bar -5112 294 0 + 296 Sigma*_b- 5114 1 100 B-Baryon -3 5.834740e+00 1.040000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 -211 Lambda_b0 pi- - 297 Sigma*_b-_bar -5114 296 0 - 298 Lambda_b0 5122 1 100 B-Baryon 0 5.62020e+00 0.00000e+00 -100 -1 -100 -1 -1 17 + 297 Sigma*_b-_bar -5114 296 0 + 298 Lambda_b0 5122 1 100 B-Baryon 0 5.619600e+00 4.475000e-13 -100 -1 -100 -1 -1 17 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2039,8 +2039,8 @@ 15 13 2.00000e-02 4 -4 4 3 2101 cbar c s ud_0 16 42 1.50000e-02 4 -2 1 2 2101 ubar d u ud_0 17 42 5.00000e-03 4 -4 3 2 2101 cbar s u ud_0 - 299 Lambda_b0_bar -5122 298 0 - 300 Xi_b- 5132 1 100 B-Baryon -3 5.79240e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 299 Lambda_b0_bar -5122 298 0 + 300 Xi_b- 5132 1 100 B-Baryon -3 5.797000e+00 4.190000e-13 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2053,8 +2053,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 301 Xi_b+ -5132 300 0 - 302 Xi_bc0 5142 1 100 B-Baryon 0 7.00575e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 301 Xi_b+ -5132 300 0 + 302 Xi_bc0 5142 1 100 B-Baryon 0 7.005750e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2067,36 +2067,36 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 303 Xi_bc0_bar -5142 302 0 - 304 bu_0 5201 1 100 Unknown 1 5.38897e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 305 bu_0_bar -5201 304 0 - 306 bu_1 5203 1 100 Unknown 1 5.40145e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 307 bu_1_bar -5203 306 0 - 308 Sigma_b0 5212 1 100 B-Baryon 0 5.80780e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 303 Xi_bc0_bar -5142 302 0 + 304 bu_0 5201 1 100 Unknown 1 5.388970e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 305 bu_0_bar -5201 304 0 + 306 bu_1 5203 1 100 Unknown 1 5.401450e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 307 bu_1_bar -5203 306 0 + 308 Sigma_b0 5212 1 100 B-Baryon 0 5.807800e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 111 Lambda_b0 pi0 - 309 Sigma_b0_bar -5212 308 0 - 310 Sigma*_b0 5214 1 100 B-Baryon 0 5.82900e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 309 Sigma_b0_bar -5212 308 0 + 310 Sigma*_b0 5214 1 100 B-Baryon 0 5.829000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 111 Lambda_b0 pi0 - 311 Sigma*_b0_bar -5214 310 0 - 312 Sigma_b+ 5222 1 100 B-Baryon 3 5.80780e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 311 Sigma*_b0_bar -5214 310 0 + 312 Sigma_b+ 5222 1 100 B-Baryon 3 5.810560e+00 5.000000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 211 Lambda_b0 pi+ - 313 Sigma_b+_bar -5222 312 0 - 314 Sigma*_b+ 5224 1 100 B-Baryon 3 5.82900e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 313 Sigma_b+_bar -5222 312 0 + 314 Sigma*_b+ 5224 1 100 B-Baryon 3 5.830320e+00 9.400000e-03 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5122 211 Lambda_b0 pi+ - 315 Sigma*_b+_bar -5224 314 0 - 316 Xi_b0 5232 1 100 B-Baryon 0 5.79240e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 315 Sigma*_b+_bar -5224 314 0 + 316 Xi_b0 5232 1 100 B-Baryon 0 5.791900e+00 4.450000e-13 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2109,8 +2109,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 317 Xi_b0_bar -5232 316 0 - 318 Xi_bc+ 5242 1 100 B-Baryon 3 7.00575e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 317 Xi_b0_bar -5232 316 0 + 318 Xi_bc+ 5242 1 100 B-Baryon 3 7.005750e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2123,36 +2123,36 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 319 Xi_bc- -5242 318 0 - 320 bs_0 5301 1 100 Unknown -2 5.56725e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 321 bs_0_bar -5301 320 0 - 322 bs_1 5303 1 100 Unknown -2 5.57536e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 323 bs_1_bar -5303 322 0 - 324 Xi'_b- 5312 1 100 B-Baryon -3 5.96000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 319 Xi_bc- -5242 318 0 + 320 bs_0 5301 1 100 Unknown -2 5.567250e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 321 bs_0_bar -5301 320 0 + 322 bs_1 5303 1 100 Unknown -2 5.575360e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 323 bs_1_bar -5303 322 0 + 324 Xi'_b- 5312 1 100 B-Baryon -3 5.960000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5132 22 Xi_b- gamma - 325 Xi'_b+ -5312 324 0 - 326 Xi*_b- 5314 1 100 B-Baryon -3 5.97000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 325 Xi'_b+ -5312 324 0 + 326 Xi*_b- 5314 1 100 B-Baryon -3 5.970000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5132 22 Xi_b- gamma - 327 Xi*_b+ -5314 326 0 - 328 Xi'_b0 5322 1 100 B-Baryon 0 5.96000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 327 Xi*_b+ -5314 326 0 + 328 Xi'_b0 5322 1 100 B-Baryon 0 5.960000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5232 22 Xi_b0 gamma - 329 Xi'_b0_bar -5322 328 0 - 330 Xi*_b0 5324 1 100 B-Baryon 0 5.97000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 329 Xi'_b0_bar -5322 328 0 + 330 Xi*_b0 5324 1 100 B-Baryon 0 5.970000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5232 22 Xi_b0 gamma - 331 Xi*_b0_bar -5324 330 0 - 332 Omega_b- 5332 1 100 B-Baryon -3 6.12000e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 331 Xi*_b0_bar -5324 330 0 + 332 Omega_b- 5332 1 100 B-Baryon -3 6.045200e+00 4.000000e-13 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2165,14 +2165,14 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 333 Omega_b+ -5332 332 0 - 334 Omega*_b- 5334 1 100 B-Baryon -3 6.13000e+00 0.00000e+00 -100 -1 -100 -1 -1 1 + 333 Omega_b+ -5332 332 0 + 334 Omega*_b- 5334 1 100 B-Baryon -3 6.130000e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 5332 22 Omega_b- gamma - 335 Omega*_b+ -5334 334 0 - 336 Omega_bc0 5342 1 100 B-Baryon 0 7.19099e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 335 Omega*_b+ -5334 334 0 + 336 Omega_bc0 5342 1 100 B-Baryon 0 7.190990e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2185,12 +2185,12 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 337 Omega_bc0_bar -5342 336 0 - 338 bc_0 5401 1 100 Unknown 1 6.67143e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 339 bc_0_bar -5401 338 0 - 340 bc_1 5403 1 100 Unknown 1 6.67397e+00 0.00000e+00 -100 -1 -100 -1 -1 0 - 341 bc_1_bar -5403 340 0 - 342 Xi'_bc0 5412 1 100 B-Baryon 0 7.03724e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 337 Omega_bc0_bar -5342 336 0 + 338 bc_0 5401 1 100 Unknown 1 6.671430e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 339 bc_0_bar -5401 338 0 + 340 bc_1 5403 1 100 Unknown 1 6.673970e+00 0.000000e+00 -100 -1 -100 -1 -1 0 + 341 bc_1_bar -5403 340 0 + 342 Xi'_bc0 5412 1 100 B-Baryon 0 7.037240e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2203,8 +2203,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 343 Xi'_bc0_bar -5412 342 0 - 344 Xi*_bc0 5414 1 100 B-Baryon 0 7.04850e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 343 Xi'_bc0_bar -5412 342 0 + 344 Xi*_bc0 5414 1 100 B-Baryon 0 7.048500e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2217,8 +2217,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 345 Xi*_bc0_bar -5414 344 0 - 346 Xi'_bc+ 5422 1 100 B-Baryon 3 7.03724e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 345 Xi*_bc0_bar -5414 344 0 + 346 Xi'_bc+ 5422 1 100 B-Baryon 3 7.037240e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2231,8 +2231,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 347 Xi'_bc- -5422 346 0 - 348 Xi*_bc+ 5424 1 100 B-Baryon 3 7.04850e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 347 Xi'_bc- -5422 346 0 + 348 Xi*_bc+ 5424 1 100 B-Baryon 3 7.048500e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2245,8 +2245,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 349 Xi*_bc- -5424 348 0 - 350 Omega'_bc0 5432 1 100 B-Baryon 0 7.21101e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 349 Xi*_bc- -5424 348 0 + 350 Omega'_bc0 5432 1 100 B-Baryon 0 7.211010e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2259,8 +2259,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 351 Omega'_bc0_bar -5432 350 0 - 352 Omega*_bc0 5434 1 100 B-Baryon 0 7.21900e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 351 Omega'_bc0_bar -5432 350 0 + 352 Omega*_bc0 5434 1 100 B-Baryon 0 7.219000e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2273,8 +2273,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 353 Omega*_bc0_bar -5434 352 0 - 354 Omega_bcc+ 5442 1 100 B-Baryon 3 8.30945e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 353 Omega*_bc0_bar -5434 352 0 + 354 Omega_bcc+ 5442 1 100 B-Baryon 3 8.309450e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2287,8 +2287,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 355 Omega_bcc+_bar -5442 354 0 - 356 Omega*_bcc+ 5444 1 100 B-Baryon 3 8.31325e+00 0.00000e+00 -100 -1 -100 -1 -1 9 + 355 Omega_bcc+_bar -5442 354 0 + 356 Omega*_bcc+ 5444 1 100 B-Baryon 3 8.313250e+00 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2301,10 +2301,10 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 357 Omega*_bcc- -5444 356 0 - 358 bb_1 5503 1 100 Unknown -2 1.00735e+01 0.00000e+00 -100 -1 -100 -1 -1 0 - 359 bb_1_bar -5503 358 0 - 360 Xi_bb- 5512 1 100 Unknown -3 1.04227e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 357 Omega*_bcc- -5444 356 0 + 358 bb_1 5503 1 100 Unknown -2 1.007350e+01 0.000000e+00 -100 -1 -100 -1 -1 0 + 359 bb_1_bar -5503 358 0 + 360 Xi_bb- 5512 1 100 Unknown -3 1.042270e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2317,8 +2317,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 361 Xi_bb+ -5512 360 0 - 362 Xi*_bb- 5514 1 100 B-Baryon -3 1.04414e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 361 Xi_bb+ -5512 360 0 + 362 Xi*_bb- 5514 1 100 B-Baryon -3 1.044140e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2331,8 +2331,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 363 Xi*_bb+ -5514 362 0 - 364 Xi_bb0 5522 1 100 B-Baryon 0 1.04227e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 363 Xi*_bb+ -5514 362 0 + 364 Xi_bb0 5522 1 100 B-Baryon 0 1.042270e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2345,8 +2345,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 365 Xi_bb0_bar -5522 364 0 - 366 Xi*_bb0 5524 1 100 B-Baryon 0 1.04414e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 365 Xi_bb0_bar -5522 364 0 + 366 Xi*_bb0 5524 1 100 B-Baryon 0 1.044140e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2359,8 +2359,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 367 Xi*_bb0_bar -5524 366 0 - 368 Omega_bb- 5532 1 100 B-Baryon -3 1.06021e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 367 Xi*_bb0_bar -5524 366 0 + 368 Omega_bb- 5532 1 100 B-Baryon -3 1.060210e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2373,8 +2373,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 369 Omega_bb+ -5532 368 0 - 370 Omega*_bb- 5534 1 100 B-Baryon -3 1.06143e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 369 Omega_bb+ -5532 368 0 + 370 Omega*_bb- 5534 1 100 B-Baryon -3 1.061430e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2387,8 +2387,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 371 Omega*_bb+ -5534 370 0 - 372 Omega_bbc0 5542 1 100 B-Baryon 0 1.17077e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 371 Omega*_bb+ -5534 370 0 + 372 Omega_bbc0 5542 1 100 B-Baryon 0 1.170770e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2401,8 +2401,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 373 Omega_bbc0_bar -5542 372 0 - 374 Omega*_bbc0 5544 1 100 B-Baryon 0 1.17115e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 373 Omega_bbc0_bar -5542 372 0 + 374 Omega*_bbc0 5544 1 100 B-Baryon 0 1.171150e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2415,8 +2415,8 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 375 Omega*_bbc0_bar -5544 374 0 - 376 Omega*_bbb- 5554 1 100 B-Baryon -3 1.51106e+01 0.00000e+00 -100 -1 -100 -1 -1 9 + 375 Omega*_bbc0_bar -5544 374 0 + 376 Omega*_bbb- 5554 1 100 B-Baryon -3 1.511060e+01 0.000000e+00 -100 -1 -100 -1 -1 9 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2429,30 +2429,30 @@ 7 42 1.00000e-02 4 -4 4 3 81 cbar c s specflav 8 42 1.50000e-02 4 -2 1 2 81 ubar d u specflav 9 42 5.00000e-03 4 -4 3 2 81 cbar s u specflav - 377 Omega*_bbb+ -5554 376 0 - 378 a_00 10111 0 100 Unknown 0 9.83500e-01 6.00000e-02 -100 -1 -100 -1 -1 1 + 377 Omega*_bbb+ -5554 376 0 + 378 a_00 10111 0 100 Unknown 0 1.439000e+00 2.580000e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 221 111 eta pi0 - 379 b_10 10113 0 100 Unknown 0 1.22950e+00 1.42000e-01 -100 -1 -100 -1 -1 1 + 379 b_10 10113 0 100 Unknown 0 1.229500e+00 1.420000e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 223 111 omega pi0 - 380 a_0+ 10211 1 100 Unknown 3 9.83500e-01 6.00000e-02 -100 -1 -100 -1 -1 1 + 380 a_0+ 10211 1 100 Unknown 3 9.835000e-01 6.000000e-02 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 221 211 eta pi+ - 381 a_0- -10211 380 0 - 382 b_1+ 10213 1 100 Unknown 3 1.22950e+00 1.42000e-01 -100 -1 -100 -1 -1 1 + 381 a_0- -10211 380 0 + 382 b_1+ 10213 1 100 Unknown 3 1.229500e+00 1.420000e-01 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 1.00000e+00 2 223 211 omega pi+ - 383 b_1- -10213 382 0 - 384 f_0 10221 0 100 Unknown 0 1.300000e+00 0.00000e+00 -100 -1 -100 -1 -1 5 + 383 b_1- -10213 382 0 + 384 f_0 10221 0 100 Unknown 0 1.350000e+00 3.500000e-01 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2461,21 +2461,21 @@ 3 0 1.10000e-01 2 321 -321 K+ K- 4 0 5.50000e-02 2 130 130 K_L0 K_L0 5 0 5.50000e-02 2 310 310 K_S0 K_S0 - 385 h_1 10223 0 100 Unknown 0 1.17000e+00 3.60000e-01 -100 -1 -100 -1 -1 3 + 385 h_1 10223 0 100 Unknown 0 1.166000e+00 3.750000e-01 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 3.33000e-01 2 213 -211 rho+ pi- 2 0 3.34000e-01 2 113 111 rho0 pi0 3 0 3.33000e-01 2 -213 211 rho- pi+ - 386 K*_00 10311 1 100 Unknown 0 1.42000e+00 2.87000e-01 -100 -1 -100 -1 -1 2 + 386 K*_00 10311 1 100 Unknown 0 1.430000e+00 2.700000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 321 -211 K+ pi- 2 0 3.33000e-01 2 311 111 K0 pi0 - 387 K*_00_bar -10311 386 0 - 388 K_10 10313 1 100 Unknown 0 1.27200e+00 9.00000e-02 -100 -1 -100 -1 -1 5 + 387 K*_00_bar -10311 386 0 + 388 K_10 10313 1 100 Unknown 0 1.253000e+00 9.000000e-02 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2484,15 +2484,15 @@ 3 0 3.13000e-01 2 323 -211 K*+ pi- 4 0 1.57000e-01 2 313 111 K*0 pi0 5 0 1.10000e-01 2 311 223 K0 omega - 389 K_10_bar -10313 388 0 - 390 K*_0+ 10321 1 100 Unknown 3 1.42000e+00 2.87000e-01 -100 -1 -100 -1 -1 2 + 389 K_10_bar -10313 388 0 + 390 K*_0+ 10321 1 100 Unknown 3 1.420000e+00 2.870000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 311 211 K0 pi+ 2 0 3.33000e-01 2 321 111 K+ pi0 - 391 K*_0- -10321 390 0 - 392 K_1+ 10323 1 100 Unknown 3 1.27200e+00 9.00000e-02 -100 -1 -100 -1 -1 5 + 391 K*_0- -10321 390 0 + 392 K_1+ 10323 1 100 Unknown 3 1.272000e+00 9.000000e-02 -100 -1 -100 -1 -1 5 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2501,8 +2501,8 @@ 3 0 3.13000e-01 2 313 211 K*0 pi+ 4 0 1.57000e-01 2 323 111 K*+ pi0 5 0 1.10000e-01 2 321 223 K+ omega - 393 K_1- -10323 392 0 - 394 f'_0 10331 0 100 Unknown 0 1.72400e+00 2.50000e-01 -100 -1 -100 -1 -1 7 + 393 K_1- -10323 392 0 + 394 f'_0 10331 0 100 Unknown 0 1.733000e+00 1.500000e-01 -100 -1 -100 -1 -1 7 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2513,7 +2513,7 @@ 5 0 1.50000e-02 2 310 310 K_S0 K_S0 6 0 2.00000e-01 4 211 -211 211 -211 pi+ pi- pi+ pi- 7 0 2.00000e-01 4 211 -211 111 111 pi+ pi- pi0 pi0 - 395 h'_1 10333 0 100 Unknown 0 1.40000e+00 8.00000e-02 -100 -1 -100 -1 -1 4 + 395 h'_1 10333 0 100 Unknown 0 1.409000e+00 7.800000e-02 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2521,140 +2521,140 @@ 2 0 2.50000e-01 2 -313 311 K*bar0 K0 3 0 2.50000e-01 2 323 -321 K*+ K- 4 0 2.50000e-01 2 -323 321 K*- K+ - 396 D*_0+ 10411 1 100 Unknown 3 2.27200e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 396 D*_0+ 10411 1 100 Unknown 3 2.272000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 421 211 D0 pi+ 2 0 3.33000e-01 2 411 111 D+ pi0 - 397 D*_0- -10411 396 0 - 398 D_1+ 10413 1 100 Unknown 3 2.42400e+00 2.00000e-02 -100 -1 -100 -1 -1 2 + 397 D*_0- -10411 396 0 + 398 D_1+ 10413 1 100 Unknown 3 2.424000e+00 2.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 423 211 D*0 pi+ 2 0 3.33000e-01 2 413 111 D*+ pi0 - 399 D_1- -10413 398 0 - 400 D*_00 10421 1 100 Unknown 0 2.27200e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 399 D_1- -10413 398 0 + 400 D*_00 10421 1 100 Unknown 0 2.343000e+00 2.290000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 411 -211 D+ pi- 2 0 3.33000e-01 2 421 111 D0 pi0 - 401 D*_00_bar -10421 400 0 - 402 D_10 10423 1 100 Unknown 0 2.42230e+00 2.00000e-02 -100 -1 -100 -1 -1 2 + 401 D*_00_bar -10421 400 0 + 402 D_10 10423 1 100 Unknown 0 2.422100e+00 3.130000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 413 -211 D*+ pi- 2 0 3.33000e-01 2 423 111 D*0 pi0 - 403 D_10_bar -10423 402 0 - 404 D*_0s+ 10431 1 100 Unknown 3 2.3178e+00 4.60000e-03 -100 -1 -100 -1 -1 2 + 403 D_10_bar -10423 402 0 + 404 D*_0s+ 10431 1 100 Unknown 3 2.317800e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 8.00000e-01 2 431 111 D_s+ pi0 2 0 2.00000e-01 2 431 22 D_s+ gamma - 405 D*_0s- -10431 404 0 - 406 D_1s+ 10433 1 100 Unknown 3 2.53530e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 405 D*_0s- -10431 404 0 + 406 D_1s+ 10433 1 100 Unknown 3 2.535110e+00 9.200000e-04 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 423 321 D*0 K+ 2 0 5.00000e-01 2 413 311 D*+ K0 - 407 D_1s- -10433 406 0 - 408 chi_0c 10441 0 100 Unknown 0 3.41475e+00 1.40000e-02 -100 -1 -100 -1 -1 2 + 407 D_1s- -10433 406 0 + 408 chi_0c 10441 0 100 Unknown 0 3.414710e+00 1.080000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 7.00000e-03 2 443 22 J/psi gamma 2 12 9.93000e-01 2 82 -82 rndmflav rndmflavbar - 409 h_1c 10443 0 100 Unknown 0 3.52593e+00 1.00000e-02 -100 -1 -100 -1 -1 1 + 409 h_1c 10443 0 100 Unknown 0 3.525370e+00 7.800000e-04 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 12 1.00000e+00 2 82 -82 rndmflav rndmflavbar - 410 B*_00 10511 1 100 Unknown 0 5.68000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 410 B*_00 10511 1 100 Unknown 0 5.680000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 521 -211 B+ pi- 2 0 3.33000e-01 2 511 111 B0 pi0 - 411 B*_00_bar -10511 410 0 - 412 B_10 10513 1 100 Unknown 0 5.73000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 411 B*_00_bar -10511 410 0 + 412 B_10 10513 1 100 Unknown 0 5.730000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 523 -211 B*+ pi- 2 0 3.33000e-01 2 513 111 B*0 pi0 - 413 B_10_bar -10513 412 0 - 414 B*_0+ 10521 1 100 Unknown 3 5.68000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 413 B_10_bar -10513 412 0 + 414 B*_0+ 10521 1 100 Unknown 3 5.680000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 511 211 B0 pi+ 2 0 3.33000e-01 2 521 111 B+ pi0 - 415 B*_0- -10521 414 0 - 416 B_1+ 10523 1 100 Unknown 3 5.73000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 415 B*_0- -10521 414 0 + 416 B_1+ 10523 1 100 Unknown 3 5.730000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 513 211 B*0 pi+ 2 0 3.33000e-01 2 523 111 B*+ pi0 - 417 B_1- -10523 416 0 - 418 B*_0s0 10531 1 100 Unknown 0 5.92000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 417 B_1- -10523 416 0 + 418 B*_0s0 10531 1 100 Unknown 0 5.920000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 521 -321 B+ K- 2 0 5.00000e-01 2 511 -311 B0 Kbar0 - 419 B*_0s0_bar -10531 418 0 - 420 B_1s0 10533 1 100 Unknown 0 5.97000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 419 B*_0s0_bar -10531 418 0 + 420 B_1s0 10533 1 100 Unknown 0 5.970000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 523 -321 B*+ K- 2 0 5.00000e-01 2 513 -311 B*0 Kbar0 - 421 B_1s0_bar -10533 420 0 - 422 B*_0c+ 10541 1 100 Unknown 3 7.25000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 421 B_1s0_bar -10533 420 0 + 422 B*_0c+ 10541 1 100 Unknown 3 7.250000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 511 411 B0 D+ 2 0 5.00000e-01 2 521 421 B+ D0 - 423 B*_0c- -10541 422 0 - 424 B_1c+ 10543 1 100 Unknown 3 7.30000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 423 B*_0c- -10541 422 0 + 424 B_1c+ 10543 1 100 Unknown 3 7.300000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 513 411 B*0 D+ 2 0 5.00000e-01 2 523 421 B*+ D0 - 425 B_1c- -10543 424 0 - 426 chi_0b 10551 0 100 Unknown 0 9.85940e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 425 B_1c- -10543 424 0 + 426 chi_0b 10551 0 100 Unknown 0 9.859400e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 2.00000e-02 2 553 22 Upsilon gamma 2 32 9.80000e-01 2 21 21 g g - 427 h_1b 10553 0 100 Unknown 0 9.87500e+00 1.00000e-02 -100 -1 -100 -1 -1 1 + 427 h_1b 10553 0 100 Unknown 0 9.899300e+00 0.000000e+00 -100 -1 -100 -1 -1 1 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 32 1.00000e+00 2 21 21 g g - 428 a_10 20113 0 100 Unknown 0 1.23000e+00 4.00000e-01 -100 -1 -100 -1 -1 2 + 428 a_10 20113 0 100 Unknown 0 1.230000e+00 4.200000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 213 -211 rho+ pi- 2 0 5.00000e-01 2 -213 211 rho- pi+ - 429 a_1+ 20213 1 100 Unknown 3 1.23000e+00 4.00000e-01 -100 -1 -100 -1 -1 2 + 429 a_1+ 20213 1 100 Unknown 3 1.230000e+00 4.000000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 113 211 rho0 pi+ 2 0 5.00000e-01 2 213 111 rho+ pi0 - 430 a_1- -20213 429 0 - 431 f_1 20223 0 100 Unknown 0 1.28180e+00 2.50000e-02 -100 -1 -100 -1 -1 14 + 430 a_1- -20213 429 0 + 431 f_1 20223 0 100 Unknown 0 1.281900e+00 2.270000e-02 -100 -1 -100 -1 -1 14 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2672,21 +2672,21 @@ 12 0 2.40000e-02 3 311 -311 111 K0 Kbar0 pi0 13 0 2.40000e-02 3 311 -321 211 K0 K- pi+ 14 0 6.60000e-02 2 113 22 rho0 gamma - 432 K*_10 20313 1 100 Unknown 0 1.40300e+00 1.74000e-01 -100 -1 -100 -1 -1 2 + 432 K*_10 20313 1 100 Unknown 0 1.403000e+00 1.740000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 323 -211 K*+ pi- 2 0 3.33000e-01 2 313 111 K*0 pi0 - 433 K*_10_bar -20313 432 0 - 434 K*_1+ 20323 1 100 Unknown 3 1.40300e+00 1.74000e-01 -100 -1 -100 -1 -1 2 + 433 K*_10_bar -20313 432 0 + 434 K*_1+ 20323 1 100 Unknown 3 1.403000e+00 1.740000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 313 211 K*0 pi+ 2 0 3.33000e-01 2 323 111 K*+ pi0 - 435 K*_1- -20323 434 0 - 436 f'_1 20333 0 100 Unknown 0 1.42640e+00 5.30000e-02 -100 -1 -100 -1 -1 4 + 435 K*_1- -20323 434 0 + 436 f'_1 20333 0 100 Unknown 0 1.426300e+00 5.450000e-02 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2694,68 +2694,68 @@ 2 0 2.50000e-01 2 -313 311 K*bar0 K0 3 0 2.50000e-01 2 323 -321 K*+ K- 4 0 2.50000e-01 2 -323 321 K*- K+ - 437 D*_1+ 20413 1 100 Unknown 3 2.37200e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 437 D*_1+ 20413 1 100 Unknown 3 2.372000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 423 211 D*0 pi+ 2 0 3.33000e-01 2 413 111 D*+ pi0 - 438 D*_1- -20413 437 0 - 439 D*_10 20423 1 100 Unknown 0 2.37200e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 438 D*_1- -20413 437 0 + 439 D*_10 20423 1 100 Unknown 0 2.412000e+00 3.140000e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 413 -211 D*+ pi- 2 0 3.33000e-01 2 423 111 D*0 pi0 - 440 D*_10_bar -20423 439 0 - 441 D*_1s+ 20433 1 100 Unknown 3 2.4596e+00 5.50000e-03 -100 -1 -100 -1 -1 2 + 440 D*_10_bar -20423 439 0 + 441 D*_1s+ 20433 1 100 Unknown 3 2.459500e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 8.00000e-01 2 433 111 D*_s+ pi0 1 0 2.00000e-01 2 433 22 D*_s+ gamma - 442 D*_1s- -20433 441 0 - 443 chi_1c 20443 0 100 Unknown 0 3.51066e+00 9.00000e-04 -100 -1 -100 -1 -1 2 + 442 D*_1s- -20433 441 0 + 443 chi_1c 20443 0 100 Unknown 0 3.510670e+00 8.400000e-04 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 2.73000e-01 2 443 22 J/psi gamma 2 12 7.27000e-01 2 82 -82 rndmflav rndmflavbar - 444 B*_10 20513 1 100 Unknown 0 5.78000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 444 B*_10 20513 1 100 Unknown 0 5.780000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 523 -211 B*+ pi- 2 0 3.33000e-01 2 513 111 B*0 pi0 - 445 B*_10_bar -20513 444 0 - 446 B*_1+ 20523 1 100 Unknown 3 5.78000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 445 B*_10_bar -20513 444 0 + 446 B*_1+ 20523 1 100 Unknown 3 5.780000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 6.67000e-01 2 513 211 B*0 pi+ 2 0 3.33000e-01 2 523 111 B*+ pi0 - 447 B*_1- -20523 446 0 - 448 B*_1s0 20533 1 100 Unknown 0 6.02000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 447 B*_1- -20523 446 0 + 448 B*_1s0 20533 1 100 Unknown 0 6.020000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 523 -321 B*+ K- 2 0 5.00000e-01 2 513 -311 B*0 Kbar0 - 449 B*_1s0_bar -20533 448 0 - 450 B*_1c+ 20543 1 100 Unknown 3 7.30000e+00 5.00000e-02 -100 -1 -100 -1 -1 2 + 449 B*_1s0_bar -20533 448 0 + 450 B*_1c+ 20543 1 100 Unknown 3 7.300000e+00 5.000000e-02 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 5.00000e-01 2 513 411 B*0 D+ 2 0 5.00000e-01 2 523 421 B*+ D0 - 451 B*_1c- -20543 450 0 - 452 chi_1b 20553 0 100 Unknown 0 9.89280e+00 0.00000e+00 -100 -1 -100 -1 -1 2 + 451 B*_1c- -20543 450 0 + 452 chi_1b 20553 0 100 Unknown 0 9.892800e+00 0.000000e+00 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 3.50000e-01 2 553 22 Upsilon gamma 2 32 6.50000e-01 2 21 21 g g - 453 psi' 100443 0 100 Unknown 0 3.68609e+00 0.00000e+00 -100 -1 -100 -1 -1 11 + 453 psi' 100443 0 100 Unknown 0 3.686100e+00 2.940000e-04 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2770,7 +2770,7 @@ 9 0 8.70000e-02 2 20443 22 chi_1c gamma 10 0 7.80000e-02 2 445 22 chi_2c gamma 11 0 2.80000e-03 2 441 22 eta_c gamma - 454 Upsilon' 100553 0 100 Unknown 0 1.00233e+01 0.00000e+00 -100 -1 -100 -1 -1 14 + 454 Upsilon' 100553 0 100 Unknown 0 1.002340e+01 3.200000e-05 -100 -1 -100 -1 -1 14 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2788,7 +2788,7 @@ 12 0 4.30000e-02 2 10551 22 chi_0b gamma 13 0 6.70000e-02 2 20553 22 chi_1b gamma 14 0 6.60000e-02 2 555 22 chi_2b gamma - 455 ~d_L 1000001 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 12 + 455 ~d_L 1000001 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2804,8 +2804,8 @@ 10 53 0.00000e+00 2 1000002 -37 ~u_L H- 11 53 0.00000e+00 2 2000002 -37 ~u_R H- 12 53 0.00000e+00 2 1000021 1 ~g d - 456 ~d_L_bar -1000001 455 0 - 457 ~u_L 1000002 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 12 + 456 ~d_L_bar -1000001 455 0 + 457 ~u_L 1000002 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2821,8 +2821,8 @@ 10 53 0.00000e+00 2 1000001 37 ~d_L H+ 11 53 0.00000e+00 2 2000001 37 ~d_R H+ 12 53 0.00000e+00 2 1000021 2 ~g u - 458 ~u_L_bar -1000002 457 0 - 459 ~s_L 1000003 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 12 + 458 ~u_L_bar -1000002 457 0 + 459 ~s_L 1000003 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2838,8 +2838,8 @@ 10 53 0.00000e+00 2 1000004 -37 ~c_L H- 11 53 0.00000e+00 2 2000004 -37 ~c_R H- 12 53 0.00000e+00 2 1000021 3 ~g s - 460 ~s_L_bar -1000003 459 0 - 461 ~c_L 1000004 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 12 + 460 ~s_L_bar -1000003 459 0 + 461 ~c_L 1000004 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2855,8 +2855,8 @@ 10 53 0.00000e+00 2 1000003 37 ~s_L H+ 11 53 0.00000e+00 2 2000003 37 ~s_R H+ 12 53 0.00000e+00 2 1000021 4 ~g c - 462 ~c_L_bar -1000004 461 0 - 463 ~b_1 1000005 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 12 + 462 ~c_L_bar -1000004 461 0 + 463 ~b_1 1000005 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2872,8 +2872,8 @@ 10 53 0.00000e+00 2 1000006 -37 ~t_1 H- 11 53 0.00000e+00 2 2000006 -37 ~t_2 H- 12 53 0.00000e+00 2 1000021 5 ~g b - 464 ~b_1_bar -1000005 463 0 - 465 ~t_1 1000006 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 15 + 464 ~b_1_bar -1000005 463 0 + 465 ~t_1 1000006 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 15 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2892,8 +2892,8 @@ 13 53 0.00000e+00 2 1000022 4 ~chi_10 c 14 53 0.00000e+00 3 1000016 -15 5 ~nu_tauL tau+ b 15 53 0.00000e+00 3 -1000015 16 5 ~tau_1+ nu_tau b - 466 ~t_1_bar -1000006 465 0 - 467 ~e_L- 1000011 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 466 ~t_1_bar -1000006 465 0 + 467 ~e_L- 1000011 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2908,8 +2908,8 @@ 9 53 0.00000e+00 2 2000012 -24 ~nu_eR W- 10 53 0.00000e+00 2 1000012 -37 ~nu_eL H- 11 53 0.00000e+00 2 2000012 -37 ~nu_eR H- - 468 ~e_L+ -1000011 467 0 - 469 ~nu_eL 1000012 1 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 468 ~e_L+ -1000011 467 0 + 469 ~nu_eL 1000012 1 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2924,8 +2924,8 @@ 9 53 0.00000e+00 2 2000011 24 ~e_R- W+ 10 53 0.00000e+00 2 1000011 37 ~e_L- H+ 11 53 0.00000e+00 2 2000011 37 ~e_R- H+ - 470 ~nu_eL_bar -1000012 469 0 - 471 ~mu_L- 1000013 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 470 ~nu_eL_bar -1000012 469 0 + 471 ~mu_L- 1000013 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2940,8 +2940,8 @@ 9 53 0.00000e+00 2 2000014 -24 ~nu_muR W- 10 53 0.00000e+00 2 1000014 -37 ~nu_muL H- 11 53 0.00000e+00 2 2000014 -37 ~nu_muR H- - 472 ~mu_L+ -1000013 471 0 - 473 ~nu_muL 1000014 1 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 472 ~mu_L+ -1000013 471 0 + 473 ~nu_muL 1000014 1 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2956,8 +2956,8 @@ 9 53 0.00000e+00 2 2000013 24 ~mu_R- W+ 10 53 0.00000e+00 2 1000013 37 ~mu_L- H+ 11 53 0.00000e+00 2 2000013 37 ~mu_R- H+ - 474 ~nu_muL_bar -1000014 473 0 - 475 ~tau_1- 1000015 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 474 ~nu_muL_bar -1000014 473 0 + 475 ~tau_1- 1000015 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2972,8 +2972,8 @@ 9 53 0.00000e+00 2 2000016 -24 ~nu_tauR W- 10 53 0.00000e+00 2 1000016 -37 ~nu_tauL H- 11 53 0.00000e+00 2 2000016 -37 ~nu_tauR H- - 476 ~tau_1+ -1000015 475 0 - 477 ~nu_tauL 1000016 1 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 11 + 476 ~tau_1+ -1000015 475 0 + 477 ~nu_tauL 1000016 1 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 11 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -2988,8 +2988,8 @@ 9 53 0.00000e+00 2 2000015 24 ~tau_2- W+ 10 53 0.00000e+00 2 1000015 37 ~tau_1- H+ 11 53 0.00000e+00 2 2000015 37 ~tau_2- H+ - 478 ~nu_tauL_bar -1000016 477 0 - 479 ~g 1000021 0 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 61 + 478 ~nu_tauL_bar -1000016 477 0 + 479 ~g 1000021 0 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 61 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3054,7 +3054,7 @@ 59 53 0.00000e+00 3 -1000037 -3 4 ~chi_2- sbar c 60 53 0.00000e+00 3 1000037 5 -6 ~chi_2+ b tbar 61 53 0.00000e+00 3 -1000037 -5 6 ~chi_2- bbar t - 480 ~chi_10 1000022 0 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 7 + 480 ~chi_10 1000022 0 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 7 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3065,7 +3065,7 @@ 5 53 0.00000e+00 2 1000039 36 ~gravitino A0 6 53 0.00000e+00 3 4 -1 11 c dbar e- 7 53 0.00000e+00 3 1 -3 12 d sbar nu_e - 481 ~chi_20 1000023 0 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 102 + 481 ~chi_20 1000023 0 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 102 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3171,7 +3171,7 @@ 100 53 0.00000e+00 3 1000021 5 -5 ~g b bbar 101 53 0.00000e+00 3 1000021 2 -2 ~g u ubar 102 53 0.00000e+00 3 1000021 4 -4 ~g c cbar - 482 ~chi_1+ 1000024 1 100 Sparticle 3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 56 + 482 ~chi_1+ 1000024 1 100 Sparticle 3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 56 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3231,8 +3231,8 @@ 54 53 0.00000e+00 2 -2000015 16 ~tau_2+ nu_tau 55 53 0.00000e+00 3 1000021 -1 2 ~g dbar u 56 53 0.00000e+00 3 1000021 -3 4 ~g sbar c - 483 ~chi_1- -1000024 482 0 - 484 ~chi_30 1000025 0 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 118 + 483 ~chi_1- -1000024 482 0 + 484 ~chi_30 1000025 0 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 118 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3354,7 +3354,7 @@ 116 53 0.00000e+00 3 1000021 5 -5 ~g b bbar 117 53 0.00000e+00 3 1000021 2 -2 ~g u ubar 118 53 0.00000e+00 3 1000021 4 -4 ~g c cbar - 485 ~chi_40 1000035 0 100 Sparticle 0 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 134 + 485 ~chi_40 1000035 0 100 Sparticle 0 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 134 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3492,7 +3492,7 @@ 132 53 0.00000e+00 3 1000021 5 -5 ~g b bbar 133 53 0.00000e+00 3 1000021 2 -2 ~g u ubar 134 53 0.00000e+00 3 1000021 4 -4 ~g c cbar - 486 ~chi_2+ 1000037 1 100 Sparticle 3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 71 + 486 ~chi_2+ 1000037 1 100 Sparticle 3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 71 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3567,9 +3567,9 @@ 69 53 0.00000e+00 2 -2000015 16 ~tau_2+ nu_tau 70 53 0.00000e+00 3 1000021 -1 2 ~g dbar u 71 53 0.00000e+00 3 1000021 -3 4 ~g sbar c - 487 ~chi_2- -1000037 486 0 - 488 ~gravitino 1000039 0 100 Sparticle 0 5.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 489 ~d_R 2000001 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 487 ~chi_2- -1000037 486 0 + 488 ~gravitino 1000039 0 100 Sparticle 0 5.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 489 ~d_R 2000001 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3589,8 +3589,8 @@ 14 53 0.00000e+00 2 1000002 -37 ~u_L H- 15 53 0.00000e+00 2 2000002 -37 ~u_R H- 16 53 0.00000e+00 2 1000021 1 ~g d - 490 ~d_R_bar -2000001 489 0 - 491 ~u_R 2000002 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 490 ~d_R_bar -2000001 489 0 + 491 ~u_R 2000002 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3610,8 +3610,8 @@ 14 53 0.00000e+00 2 1000001 37 ~d_L H+ 15 53 0.00000e+00 2 2000001 37 ~d_R H+ 16 53 0.00000e+00 2 1000021 2 ~g u - 492 ~u_R_bar -2000002 491 0 - 493 ~s_R 2000003 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 492 ~u_R_bar -2000002 491 0 + 493 ~s_R 2000003 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3631,8 +3631,8 @@ 14 53 0.00000e+00 2 1000004 -37 ~c_L H- 15 53 0.00000e+00 2 2000004 -37 ~c_R H- 16 53 0.00000e+00 2 1000021 3 ~g s - 494 ~s_R_bar -2000003 493 0 - 495 ~c_R 2000004 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 494 ~s_R_bar -2000003 493 0 + 495 ~c_R 2000004 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3652,8 +3652,8 @@ 14 53 0.00000e+00 2 1000003 37 ~s_L H+ 15 53 0.00000e+00 2 2000003 37 ~s_R H+ 16 53 0.00000e+00 2 1000021 4 ~g c - 496 ~c_R_bar -2000004 495 0 - 497 ~b_2 2000005 1 100 Sparticle -1 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 496 ~c_R_bar -2000004 495 0 + 497 ~b_2 2000005 1 100 Sparticle -1 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3673,8 +3673,8 @@ 14 53 0.00000e+00 2 1000006 -37 ~t_1 H- 15 53 0.00000e+00 2 2000006 -37 ~t_2 H- 16 53 0.00000e+00 2 1000021 5 ~g b - 498 ~b_2_bar -2000005 497 0 - 499 ~t_2 2000006 1 100 Sparticle 2 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 16 + 498 ~b_2_bar -2000005 497 0 + 499 ~t_2 2000006 1 100 Sparticle 2 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 16 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3694,8 +3694,8 @@ 14 53 0.00000e+00 2 1000005 37 ~b_1 H+ 15 53 0.00000e+00 2 2000005 37 ~b_2 H+ 16 53 0.00000e+00 2 1000021 6 ~g t - 500 ~t_2_bar -2000006 499 0 - 501 ~e_R- 2000011 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 15 + 500 ~t_2_bar -2000006 499 0 + 501 ~e_R- 2000011 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 15 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3714,10 +3714,10 @@ 13 53 0.00000e+00 2 2000012 -24 ~nu_eR W- 14 53 0.00000e+00 2 1000012 -37 ~nu_eL H- 15 53 0.00000e+00 2 2000012 -37 ~nu_eR H- - 502 ~e_R+ -2000011 501 0 - 503 ~nu_eR 2000012 1 100 Sparticle 0 5.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 504 ~nu_eR_bar -2000012 503 0 - 505 ~mu_R- 2000013 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 15 + 502 ~e_R+ -2000011 501 0 + 503 ~nu_eR 2000012 1 100 Sparticle 0 5.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 504 ~nu_eR_bar -2000012 503 0 + 505 ~mu_R- 2000013 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 15 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3736,10 +3736,10 @@ 13 53 0.00000e+00 2 2000014 -24 ~nu_muR W- 14 53 0.00000e+00 2 1000014 -37 ~nu_muL H- 15 53 0.00000e+00 2 2000014 -37 ~nu_muR H- - 506 ~mu_R+ -2000013 505 0 - 507 ~nu_muR 2000014 1 100 Sparticle 0 5.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 508 ~nu_muR_bar -2000014 507 0 - 509 ~tau_2- 2000015 1 100 Sparticle -3 5.00000e+02 1.00000e+00 -100 -1 -100 -1 -1 15 + 506 ~mu_R+ -2000013 505 0 + 507 ~nu_muR 2000014 1 100 Sparticle 0 5.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 508 ~nu_muR_bar -2000014 507 0 + 509 ~tau_2- 2000015 1 100 Sparticle -3 5.000000e+02 1.000000e+00 -100 -1 -100 -1 -1 15 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3758,10 +3758,10 @@ 13 53 0.00000e+00 2 2000016 -24 ~nu_tauR W- 14 53 0.00000e+00 2 1000016 -37 ~nu_tauL H- 15 53 0.00000e+00 2 2000016 -37 ~nu_tauR H- - 510 ~tau_2+ -2000015 509 0 - 511 ~nu_tauR 2000016 1 100 Sparticle 0 5.00000e+02 0.00000e+00 -100 -1 -100 -1 -1 0 - 512 ~nu_tauR_bar -2000016 511 0 - 513 d* 4000001 1 100 Excited -1 4.00000e+02 2.65171e+00 -100 -1 -100 -1 -1 4 + 510 ~tau_2+ -2000015 509 0 + 511 ~nu_tauR 2000016 1 100 Sparticle 0 5.000000e+02 0.000000e+00 -100 -1 -100 -1 -1 0 + 512 ~nu_tauR_bar -2000016 511 0 + 513 d* 4000001 1 100 Excited -1 4.000000e+02 2.651710e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3769,8 +3769,8 @@ 2 0 5.29200e-03 2 22 1 gamma d 3 0 4.40390e-02 2 23 1 Z0 d 4 0 9.64490e-02 2 -24 2 W- u - 514 d*_bar -4000001 513 0 - 515 u* 4000002 1 100 Excited 2 4.00000e+02 2.65499e+00 -100 -1 -100 -1 -1 4 + 514 d*_bar -4000001 513 0 + 515 u* 4000002 1 100 Excited 2 4.000000e+02 2.654990e+00 -100 -1 -100 -1 -1 4 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3778,28 +3778,28 @@ 2 0 2.11440e-02 2 22 2 gamma u 3 0 2.93610e-02 2 23 2 Z0 u 4 0 9.63290e-02 2 24 1 W+ d - 516 u*_bar -4000002 515 0 - 517 e*- 4000011 1 100 Excited -3 4.00000e+02 4.29010e-01 -100 -1 -100 -1 -1 3 + 516 u*_bar -4000002 515 0 + 517 e*- 4000011 1 100 Excited -3 4.000000e+02 4.290100e-01 -100 -1 -100 -1 -1 3 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 2.94414e-01 2 22 11 gamma e- 2 0 1.09437e-01 2 23 11 Z0 e- 3 0 5.96149e-01 2 -24 12 W- nu_e - 518 e*+ -4000011 517 0 - 519 nu*_e0 4000012 1 100 Excited 0 4.00000e+02 4.19170e-01 -100 -1 -100 -1 -1 2 + 518 e*+ -4000011 517 0 + 519 nu*_e0 4000012 1 100 Excited 0 4.000000e+02 4.191700e-01 -100 -1 -100 -1 -1 2 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- 1 0 3.89861e-01 2 23 12 Z0 nu_e 2 0 6.10139e-01 2 24 11 W+ e- - 520 nu*_e0_bar -4000012 519 0 - 521 Rootino 0 0 100 Unknown 0 0.00000e+00 0.00000e+00 -100 -1 -100 -1 -1 0 + 520 nu*_e0_bar -4000012 519 0 + 521 Rootino 0 0 100 Unknown 0 0.000000e+00 0.000000e+00 -100 -1 -100 -1 -1 0 #--------------------------------------------------------------------------------------------------------- -# Recently added new particles without the need to reshufle index numbers +# Recently added new particles without the need to reshufle index numbers #--------------------------------------------------------------------------------------------------------- # i NAME......... PDG Anti CLASS Q MASS WIDTH 2*I+1 I3 2*S+1 FLVR TrkCod N(dec) - 522 Lambda(1520)0 3124 1 100 Baryon 0 1.51950e+00 0.01560e+00 -100 -1 -100 -1 -1 12 + 522 Lambda(1520)0 3124 1 100 Baryon 0 1.519000e+00 1.600000e-02 -100 -1 -100 -1 -1 12 #---------------------------------------------------------------------- # decay type(PY6) BR Nd daughters(codes, then names) #---------------------------------------------------------------------- @@ -3815,4 +3815,4 @@ 10 0 1.00000e-02 3 3212 111 111 Sigma0 pi0 pi0 11 0 2.00000e-02 3 3122 211 -211 Lambda0 pi+ pi- 12 0 1.10000e-02 2 3122 22 Lambda0 pi0 gamma - 523 Lambda(1520)_bar -3124 522 0 + 523 Lambda(1520)_bar -3124 522 0 diff --git a/etc/pdg_table_update.py b/etc/pdg_table_update.py new file mode 100755 index 0000000000000..b041a6985d36c --- /dev/null +++ b/etc/pdg_table_update.py @@ -0,0 +1,144 @@ +#!/usr/bin/python + +import urllib.request +import sys + +# Character positions for extracting data from "mass_width_2023.txt" +MASS_WIDTH_ID_START = 0 +MASS_WIDTH_ID_END = 8 +MASS_WIDTH_MASS_START = 33 +MASS_WIDTH_MASS_END = 51 +MASS_WIDTH_WIDTH_START = 70 +MASS_WIDTH_WIDTH_END = 88 +MASS_WIDTH_NAME_WITH_CHARGE_START = 107 +MASS_WIDTH_NAME_WITH_CHARGE_END = 128 + +#------------------------ +# Gets the text document +#------------------------ + +def getFileTextFromURL(link): + try: + with urllib.request.urlopen(link) as f: + text = f.read().decode("utf-8") + lines = text.splitlines() + return lines + except Exception as e: + print(f"Error while fetching data from URL: {e}") + return None + +#------------------------------------- +# Gets the correct Data for particles +#------------------------------------- + +def fixedParticleData(infoLine): + elements = infoLine.split() + + name = elements[1] + trueId = int(elements[2]) + + if len(elements) < 6: # If it's an Antiparticle + return f"{elements[0]:>5} {name:<16} {trueId:>6} {elements[3]:>7} {elements[4]:>5}\n" + else: # If it's not an Antiparticle + mass = float(elements[7]) + width = float(elements[8]) + + if 0 <= trueId < len(massWidthData): + if (massWidthData[trueId] is not None): + if (massWidthData[trueId].mass is not None): + mass = float(massWidthData[trueId].mass) + if massWidthData[trueId].width is not None: + width = float(massWidthData[trueId].width) + print(f"{float(elements[7]):<10e} {float(massWidthData[trueId].mass):<10e} {massWidthData[trueId].name:<10}") + + # Formatting the output line with the updated mass and width + return f"{elements[0]:>5} {name:<16} {trueId:>6} {elements[3]:>2} {elements[4]:>3} {elements[5]:<10} {elements[6]:>2} {mass:<11e} {width:<11e} {elements[9]:>3} {elements[10]:>2} {elements[11]:>3} {elements[12]:>2} {elements[13]:>4} {elements[14]:>3}\n" + +#--------------------------------- +# Save the data of the mass_width +#--------------------------------- + +def getMassWidthValues(lines): + data = [] # Array to store the data + for line in lines: + if line.startswith('*'): + continue # Skip comments + + # Extracting relevant information based on the character column positions + particleId = int(line[MASS_WIDTH_ID_START:MASS_WIDTH_ID_END].strip()) + + if line[MASS_WIDTH_MASS_START:MASS_WIDTH_MASS_END].strip(): + mass = line[MASS_WIDTH_MASS_START:MASS_WIDTH_MASS_END].strip() + else: + mass = 0.0 # No value is given + + if line[MASS_WIDTH_WIDTH_START:MASS_WIDTH_WIDTH_END].strip(): + width = line[MASS_WIDTH_WIDTH_START:MASS_WIDTH_WIDTH_END].strip() + else: + width = 0.0 # No value is given + + nameWithCharge = line[MASS_WIDTH_NAME_WITH_CHARGE_START:MASS_WIDTH_NAME_WITH_CHARGE_END].strip() + name = nameWithCharge.split()[0] # Extract only the name, excluding the charge + + # Storing the data in the dictionary + if particleId >= len(data): + while (len(data) <= particleId): + data.append(None) + data[particleId] = MWDataObj(float(mass), float(width), name) + + return data + +#------------------------------ +# Create updated pdg_table.txt +#------------------------------ + +def updateTable(massWidthData, originalTable): + if originalTable is None or massWidthData is None: + print("Data not available. Aborting table creation.") + return + + outputLines = [] + + for line in originalTable: + if line.strip().startswith('#'): + outputLines.append(f"{line}") + else: + if line.split()[0].isdigit() and line.split()[1].isdigit(): + outputLines.append(f"{line}") + else: + outputLines.append(fixedParticleData(line)) + + return outputLines + +#--------------------------------------- +# Object for the data of the mass_width +#--------------------------------------- + +class MWDataObj: + def __init__(self, mass, width, name): + self.mass = mass + self.width = width + self.name = name + +#------------------ +# Setup everything +#------------------ + +if len(sys.argv)!= 3: + print(f"Incorrect Arguments!\nUsage: {sys.argv[0]} pdgFile massWidthURL") + exit(1) + +pdgTableFile = sys.argv[1] +massUrl = sys.argv[2] + +# Fetch mass_width_2023.txt content from URLs +massDataLines = getFileTextFromURL(massUrl) +if massDataLines is None: + exit(2) +massWidthData = getMassWidthValues(massDataLines) + +with open(pdgTableFile, 'r') as file: + originalTable = file.readlines() +newTable = updateTable(massWidthData, originalTable) +with open(pdgTableFile, 'w') as file: + file.writelines(newTable) diff --git a/etc/plugins/TBrowserImp/P030_RWebBrowserImp.C b/etc/plugins/TBrowserImp/P030_RWebBrowserImp.C index 8cb946adaf412..3a69ecfcd34d1 100644 --- a/etc/plugins/TBrowserImp/P030_RWebBrowserImp.C +++ b/etc/plugins/TBrowserImp/P030_RWebBrowserImp.C @@ -1,7 +1,7 @@ void P030_RWebBrowserImp() { - gPluginMgr->AddHandler("TBrowserImp", "ROOT::Experimental::RWebBrowserImp", "ROOT::Experimental::RWebBrowserImp", + gPluginMgr->AddHandler("TBrowserImp", "ROOT::RWebBrowserImp", "ROOT::RWebBrowserImp", "ROOTBrowserv7", "NewBrowser(TBrowser *, const char *, Int_t, Int_t, UInt_t, UInt_t, Option_t *)"); - gPluginMgr->AddHandler("TBrowserImp", "ROOT::Experimental::RWebBrowserImp", "ROOT::Experimental::RWebBrowserImp", + gPluginMgr->AddHandler("TBrowserImp", "ROOT::RWebBrowserImp", "ROOT::RWebBrowserImp", "ROOTBrowserv7", "NewBrowser(TBrowser *, const char *, UInt_t, UInt_t, Option_t *)"); } diff --git a/etc/plugins/TDataSetManager/P020_TDataSetManagerAliEn.C b/etc/plugins/TDataSetManager/P020_TDataSetManagerAliEn.C deleted file mode 100644 index f931e07f6acfa..0000000000000 --- a/etc/plugins/TDataSetManager/P020_TDataSetManagerAliEn.C +++ /dev/null @@ -1,5 +0,0 @@ -void P020_TDataSetManagerAliEn() -{ - gPluginMgr->AddHandler("TDataSetManager", "^alien", "TDataSetManagerAliEn", "Proof", - "TDataSetManagerAliEn(const char *,const char *,const char *)"); -} diff --git a/etc/plugins/TFile/P070_TAlienFile.C b/etc/plugins/TFile/P070_TAlienFile.C deleted file mode 100644 index 3bd4ca6fd7643..0000000000000 --- a/etc/plugins/TFile/P070_TAlienFile.C +++ /dev/null @@ -1,5 +0,0 @@ -void P070_TAlienFile() -{ - gPluginMgr->AddHandler("TFile", "^alien:", "TAlienFile", - "RAliEn", "Open(const char*,Option_t*,const char*,Int_t,Bool_t)"); -} diff --git a/etc/plugins/TGrid/P010_TAlien.C b/etc/plugins/TGrid/P010_TAlien.C deleted file mode 100644 index d868127114784..0000000000000 --- a/etc/plugins/TGrid/P010_TAlien.C +++ /dev/null @@ -1,104 +0,0 @@ -#include - -void SetAliEnSettings() -{ - // Routine to load settings from an AliEn environment file. - - ifstream fileIn; - fileIn.open(Form("/tmp/gclient_env_%d", gSystem->GetUid())); - if (gDebug>0) {printf("P010_TAlien.C: parsing /tmp/gclient_env_$UID\n");} - TString lineS,tmp; - char line[4096]; - - while (fileIn.good()){ - fileIn.getline(line,4096,'\n'); - lineS = line; - if (lineS.IsNull()) continue; - if (lineS.Contains("export ")) { - lineS.ReplaceAll("export ",""); - - TObjArray* array = lineS.Tokenize("="); - - if (array->GetEntries() == 2) { - TObjString *strVar = (TObjString *) array->At(0); - TObjString *strVal = (TObjString *) array->At(1); - - if ((strVar)&&(strVal)) { - tmp = strVal->GetString(); - tmp.ReplaceAll("\"",""); - tmp.ReplaceAll("$LD_LIBRARY_PATH",gSystem->Getenv("LD_LIBRARY_PATH")); - tmp.ReplaceAll("$DYLD_LIBRARY_PATH",gSystem->Getenv("DYLD_LIBRARY_PATH")); - tmp.ReplaceAll(" ",""); - gSystem->Unsetenv(strVar->GetString()); - gSystem->Setenv(strVar->GetString(), tmp); - if (gDebug>0) { - Info("P010_TAlien", "setting environment %s=\"%s\"", strVar->GetString().Data(), tmp.Data()); - } - if (!strVar->GetString().CompareTo("GCLIENT_SERVER_LIST")) { - gSystem->Unsetenv("alien_API_SERVER_LIST"); - gSystem->Setenv("alien_API_SERVER_LIST", tmp); - } - } - if (array) { - delete array; - array = 0 ; - } - } else { - // parse the MONA_ stuff - TObjArray* array = lineS.Tokenize("\" "); - TString key=""; - TString val=""; - for (int i=0; i< array->GetEntries(); i++) { - if ( ((TObjString*) array->At(i))->GetString().Contains("=")) { - if (key.Length() && val.Length()) { - val.Resize(val.Length()-1); - if (gDebug>0) { - Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); - } - gSystem->Unsetenv(key); - gSystem->Setenv(key, val); - key=""; - val=""; - } - key = ((TObjString*) array->At(i))->GetString(); - key.ReplaceAll("=",""); - } else { - val+=((TObjString*) array->At(i))->GetString(); - val+=" "; - } - } - if (key.Length() && val.Length()) { - if (gDebug>0) { - Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); - } - gSystem->Unsetenv(key); - gSystem->Setenv(key, val); - } - } - } - } -} - -void P010_TAlien() -{ - TString configfeatures = gROOT->GetConfigFeatures(); - TString ralienpath = gSystem->Getenv("ROOTSYS"); - ralienpath += "/lib/"; ralienpath += "libRAliEn.so"; - - // only if ROOT was compiled with enable-alien we do library setup and configure a handler - if ((!gSystem->AccessPathName(ralienpath)) || (configfeatures.Contains("alien"))) { - // you can enforce - if ((!gSystem->Getenv("GBBOX_ENVFILE")) || - ( gSystem->Getenv("ALIEN_SOURCE_GCLIENT_ENV")) || - (!gSystem->Getenv("ALIEN_SKIP_GCLIENT_ENV")) ) { - SetAliEnSettings(); - } - - if ( ((gSystem->Load("libgapiUI.so")>=0) && (gSystem->Load("libRAliEn.so")>=0))) { - gPluginMgr->AddHandler("TGrid", "^alien", "TAlien", - "RAliEn", "TAlien(const char*,const char*,const char*,const char*)"); - } else { - Error("P010_TAlien","Please fix your loader path environment variable to be able to load libRAliEn.so"); - } - } -} diff --git a/etc/plugins/TSystem/P030_TAlienSystem.C b/etc/plugins/TSystem/P030_TAlienSystem.C deleted file mode 100644 index 7a3a344611a3e..0000000000000 --- a/etc/plugins/TSystem/P030_TAlienSystem.C +++ /dev/null @@ -1,5 +0,0 @@ -void P030_TAlienSystem() -{ - gPluginMgr->AddHandler("TSystem", "^alien:", "TAlienSystem", - "RAliEn", "TAlienSystem()"); -} diff --git a/geom/gdml/inc/TGDMLParse.h b/geom/gdml/inc/TGDMLParse.h index b97049f5ab9c3..6bead522eef65 100644 --- a/geom/gdml/inc/TGDMLParse.h +++ b/geom/gdml/inc/TGDMLParse.h @@ -29,26 +29,25 @@ class TGDMLMatrix; class TGDMLRefl : public TObject { public: - - TGDMLRefl() { + TGDMLRefl() + { fNameS = ""; fSolid = ""; fMatrix = nullptr; } - virtual ~TGDMLRefl() {} + ~TGDMLRefl() override {} - TGDMLRefl(const char* name, const char* solid, TGeoMatrix* matrix); - TGeoMatrix* GetMatrix(); + TGDMLRefl(const char *name, const char *solid, TGeoMatrix *matrix); + TGeoMatrix *GetMatrix(); private: + const char *fNameS; //! reflected solid name + const char *fSolid; //! solid name being reflected + TGeoMatrix *fMatrix; //! matrix of reflected solid - const char* fNameS; //!reflected solid name - const char* fSolid; //!solid name being reflected - TGeoMatrix *fMatrix; //!matrix of reflected solid - - ClassDef(TGDMLRefl, 0) //helper class used for the storage of reflected solids + ClassDefOverride(TGDMLRefl, 0) // helper class used for the storage of reflected solids }; /************************************************************************* @@ -58,131 +57,133 @@ class TGDMLRefl : public TObject { class TGDMLBaseTGDMMapHelper : public std::map { }; -//map's [] operator returns reference. -//to avoid ugly UB casts like static_cast(voidPtrLValue) -//I have this helper class. -template +// map's [] operator returns reference. +// to avoid ugly UB casts like static_cast(voidPtrLValue) +// I have this helper class. +template class TGDMAssignmentHelper { private: TGDMLBaseTGDMMapHelper::iterator fPosInMap; public: - TGDMAssignmentHelper(TGDMLBaseTGDMMapHelper &baseMap, const std::string &key) { - baseMap[key];//if we do not have this key-value pair before, insert it now (with zero for pointer). - //find iterator for this key now :) + TGDMAssignmentHelper(TGDMLBaseTGDMMapHelper &baseMap, const std::string &key) + { + baseMap[key]; // if we do not have this key-value pair before, insert it now (with zero for pointer). + // find iterator for this key now :) fPosInMap = baseMap.find(key); } - operator T * ()const { - return (T*)fPosInMap->second;//const_cast(static_cast(fPosInMap->second)); + operator T *() const + { + return (T *)fPosInMap->second; // const_cast(static_cast(fPosInMap->second)); } - TGDMAssignmentHelper & operator = (const T * ptr) { + TGDMAssignmentHelper &operator=(const T *ptr) + { fPosInMap->second = ptr; return *this; } }; -template +template class TGDMMapHelper : public TGDMLBaseTGDMMapHelper { public: - TGDMAssignmentHelper operator [](const std::string &key) { - return TGDMAssignmentHelper(*this, key); - } + TGDMAssignmentHelper operator[](const std::string &key) { return TGDMAssignmentHelper(*this, key); } }; class TGDMLParse : public TObject { public: - TString fWorldName; - TGeoVolume* fWorld; //top volume of geometry - int fVolID; //volume ID, incremented as assigned. - int fFILENO; //Holds which level of file the parser is at + TGeoVolume *fWorld; // top volume of geometry + int fVolID; // volume ID, incremented as assigned. + int fFILENO; // Holds which level of file the parser is at int fNunitless{0}; // Number of entities defined unitless - TXMLEngine* fFileEngine[20]; //array of dom object pointers - const char* fStartFile; //name of originating file - const char* fCurrentFile; //current file name being parsed + TXMLEngine *fFileEngine[20]; // array of dom object pointers + const char *fStartFile; // name of originating file + const char *fCurrentFile; // current file name being parsed std::string fDefault_lunit = "mm"; std::string fDefault_aunit = "rad"; TGDMLParse(); - virtual ~TGDMLParse() {} + ~TGDMLParse() override {} - static TGeoVolume* StartGDML(const char* filename) { - TGDMLParse* parser = new TGDMLParse; - TGeoVolume* world = parser->GDMLReadFile(filename); + static TGeoVolume *StartGDML(const char *filename) + { + TGDMLParse *parser = new TGDMLParse; + TGeoVolume *world = parser->GDMLReadFile(filename); return world; } - TGeoVolume* GDMLReadFile(const char* filename = "test.gdml"); + TGeoVolume *GDMLReadFile(const char *filename = "test.gdml"); private: - - const char* ParseGDML(TXMLEngine* gdml, XMLNodePointer_t node) ; - TString GetScale(const char* unit); - double GetScaleVal(const char* unit); - double Evaluate(const char* evalline); - const char* NameShort(const char* name); - double Value(const char *svalue) const; - void DefineConstants(); + const char *ParseGDML(TXMLEngine *gdml, XMLNodePointer_t node); + TString GetScale(const char *unit); + double GetScaleVal(const char *unit); + double Evaluate(const char *evalline); + const char *NameShort(const char *name); + double Value(const char *svalue) const; + void DefineConstants(); //'define' section - XMLNodePointer_t ConProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t PosProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t QuantityProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t RotProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t SclProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t MatrixProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t ConProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t PosProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t QuantityProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t RotProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t SclProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t MatrixProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); //'materials' section - XMLNodePointer_t IsoProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLNodePointer_t parentn); - XMLNodePointer_t EleProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLNodePointer_t parentn, Bool_t hasIsotopes, Bool_t hasIsotopesExtended); - XMLNodePointer_t MatProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr, int z); + XMLNodePointer_t IsoProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLNodePointer_t parentn); + XMLNodePointer_t EleProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLNodePointer_t parentn, Bool_t hasIsotopes, + Bool_t hasIsotopesExtended); + XMLNodePointer_t MatProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr, int z); //'solids' section - XMLNodePointer_t OpticalSurfaceProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t BooSolid(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr, int num); - XMLNodePointer_t Box(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Paraboloid(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Arb8(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Tube(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t CutTube(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Cone(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t ElCone(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Trap(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Trd(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Polycone(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Polyhedra(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Sphere(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Torus(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Hype(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Para(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t TwistTrap(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t ElTube(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Orb(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Xtru(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Reflection(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Ellipsoid(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t Tessellated(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t OpticalSurfaceProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t BooSolid(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr, int num); + XMLNodePointer_t Box(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Paraboloid(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Arb8(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Tube(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t CutTube(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Cone(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t ElCone(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Trap(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Trd(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Polycone(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Polyhedra(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Sphere(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Torus(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Hype(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Para(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t TwistTrap(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t ElTube(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Orb(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Xtru(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Reflection(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Ellipsoid(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t Tessellated(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t ScaledSolid(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); //'structure' section - XMLNodePointer_t VolProcess(TXMLEngine* gdml, XMLNodePointer_t node); - XMLNodePointer_t AssProcess(TXMLEngine* gdml, XMLNodePointer_t node); - XMLNodePointer_t UsrProcess(TXMLEngine* gdml, XMLNodePointer_t node); - XMLNodePointer_t SkinSurfaceProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - XMLNodePointer_t BorderSurfaceProcess(TXMLEngine* gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); - Int_t SetAxis(const char* axisString); //Set Axis for Division + XMLNodePointer_t VolProcess(TXMLEngine *gdml, XMLNodePointer_t node); + XMLNodePointer_t AssProcess(TXMLEngine *gdml, XMLNodePointer_t node); + XMLNodePointer_t UsrProcess(TXMLEngine *gdml, XMLNodePointer_t node); + XMLNodePointer_t SkinSurfaceProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + XMLNodePointer_t BorderSurfaceProcess(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr); + Int_t SetAxis(const char *axisString); // Set Axis for Division //'setup' section - XMLNodePointer_t TopProcess(TXMLEngine* gdml, XMLNodePointer_t node); + XMLNodePointer_t TopProcess(TXMLEngine *gdml, XMLNodePointer_t node); // Find defined objects by name - TGeoTranslation *GetPosition(const char *name); - TGeoRotation *GetRotation(const char *name); - TGeoScale *GetScaleObj(const char *name); - TGeoShape *GetSolid(const char *name); - TGeoVolume *GetVolume(const char *name); + TGeoTranslation *GetPosition(const char *name); + TGeoRotation *GetRotation(const char *name); + TGeoScale *GetScaleObj(const char *name); + TGeoShape *GetSolid(const char *name); + TGeoVolume *GetVolume(const char *name); typedef TGDMMapHelper PosMap; typedef TGDMMapHelper RotMap; @@ -204,25 +205,25 @@ class TGDMLParse : public TObject { typedef std::map FracMap; typedef std::map ConstMap; - PosMap fposmap; //!Map containing position names and the TGeoTranslation for it - RotMap frotmap; //!Map containing rotation names and the TGeoRotation for it - SclMap fsclmap; //!Map containing scale names and the TGeoScale for it - IsoMap fisomap; //!Map containing isotope names and the TGeoIsotope for it - EleMap felemap; //!Map containing element names and the TGeoElement for it - MatMap fmatmap; //!Map containing material names and the TGeoMaterial for it - MedMap fmedmap; //!Map containing medium names and the TGeoMedium for it - MixMap fmixmap; //!Map containing mixture names and the TGeoMixture for it - SolMap fsolmap; //!Map containing solid names and the TGeoShape for it - VolMap fvolmap; //!Map containing volume names and the TGeoVolume for it - PvolMap fpvolmap; //!Map containing placed volume names and the TGeoNode for it - ReflectionsMap freflectmap; //!Map containing reflection names and the Solid name ir references to - ReflSolidMap freflsolidmap; //!Map containing reflection names and the TGDMLRefl for it - containing refl matrix - ReflVolMap freflvolmap; //!Map containing reflected volume names and the solid ref for it - FileMap ffilemap; //!Map containing files parsed during entire parsing, with their world volume name - ConstMap fconsts; //!Map containing values of constants declared in the file - MatrixMap fmatrices; //!Map containing matrices defined in the GDML file - - ClassDef(TGDMLParse, 0) //imports GDML using DOM and binds it to ROOT + PosMap fposmap; //! Map containing position names and the TGeoTranslation for it + RotMap frotmap; //! Map containing rotation names and the TGeoRotation for it + SclMap fsclmap; //! Map containing scale names and the TGeoScale for it + IsoMap fisomap; //! Map containing isotope names and the TGeoIsotope for it + EleMap felemap; //! Map containing element names and the TGeoElement for it + MatMap fmatmap; //! Map containing material names and the TGeoMaterial for it + MedMap fmedmap; //! Map containing medium names and the TGeoMedium for it + MixMap fmixmap; //! Map containing mixture names and the TGeoMixture for it + SolMap fsolmap; //! Map containing solid names and the TGeoShape for it + VolMap fvolmap; //! Map containing volume names and the TGeoVolume for it + PvolMap fpvolmap; //! Map containing placed volume names and the TGeoNode for it + ReflectionsMap freflectmap; //! Map containing reflection names and the Solid name ir references to + ReflSolidMap freflsolidmap; //! Map containing reflection names and the TGDMLRefl for it - containing refl matrix + ReflVolMap freflvolmap; //! Map containing reflected volume names and the solid ref for it + FileMap ffilemap; //! Map containing files parsed during entire parsing, with their world volume name + ConstMap fconsts; //! Map containing values of constants declared in the file + MatrixMap fmatrices; //! Map containing matrices defined in the GDML file + + ClassDefOverride(TGDMLParse, 0) // imports GDML using DOM and binds it to ROOT }; #endif diff --git a/geom/gdml/inc/TGDMLWrite.h b/geom/gdml/inc/TGDMLWrite.h index 51c662cb68b67..b7446e8d3e3ee 100644 --- a/geom/gdml/inc/TGDMLWrite.h +++ b/geom/gdml/inc/TGDMLWrite.h @@ -56,11 +56,12 @@ class TGeoBorderSurface; class TGDMLWrite : public TObject { public: TGDMLWrite(); - virtual ~TGDMLWrite(); + ~TGDMLWrite() override; - static void StartGDMLWriting(TGeoManager * geomanager, const char* filename, TString option) { - //static function - - //options: + static void StartGDMLWriting(TGeoManager *geomanager, const char *filename, TString option) + { + // static function - + // options: // g - set by default - geant4 compatibility // f,n - if none of this two is set then naming convention is // with incremental suffix, if "f" then suffix is pointer @@ -70,22 +71,17 @@ class TGDMLWrite : public TObject { writer->WriteGDMLfile(geomanager, filename, option); delete writer; } - //wrapper of all main methods for extraction - void WriteGDMLfile(TGeoManager * geomanager, const char* filename = "test.gdml", TString option = ""); + // wrapper of all main methods for extraction + void WriteGDMLfile(TGeoManager *geomanager, const char *filename = "test.gdml", TString option = ""); // Wrapper to only selectively write one branch of the volume hierarchy to file - void WriteGDMLfile(TGeoManager * geomanager, TGeoNode* top_node, const char* filename = "test.gdml", TString option = ""); + void + WriteGDMLfile(TGeoManager *geomanager, TGeoNode *top_node, const char *filename = "test.gdml", TString option = ""); - enum ENamingType { - kelegantButSlow = 0, - kwithoutSufixNotUniq = 1, - kfastButUglySufix = 2 - }; + enum ENamingType { kelegantButSlow = 0, kwithoutSufixNotUniq = 1, kfastButUglySufix = 2 }; void SetNamingSpeed(ENamingType naming); // Ignore dummy material instance, which causes trouble reading GDML in Geant4 void SetIgnoreDummyMaterial(bool value); - void SetG4Compatibility(Bool_t G4Compatible) { - fgG4Compatibility = G4Compatible; - }; + void SetG4Compatibility(Bool_t G4Compatible) { fgG4Compatibility = G4Compatible; }; private: struct Xyz { @@ -94,142 +90,145 @@ class TGDMLWrite : public TObject { Double_t z; }; - typedef std::set SurfaceList; - typedef std::set VolList; - typedef std::set NodeList; - typedef std::map NameList; - typedef std::map NameListS; - typedef std::map NameListI; - typedef std::map NameListF; + typedef std::set SurfaceList; + typedef std::set VolList; + typedef std::set NodeList; + typedef std::map NameList; + typedef std::map NameListS; + typedef std::map NameListI; + typedef std::map NameListF; struct StructLst { NameList fLst; - }; //to store pointers + }; // to store pointers struct NameLst { - NameListS fLst; //to map pointers with names - NameListI fLstIter; //to store all the iterators for repeating names + NameListS fLst; // to map pointers with names + NameListI fLstIter; // to store all the iterators for repeating names }; - //General lists - StructLst *fIsotopeList; //list of isotopes - StructLst *fElementList; //list of elements - StructLst *fAccPatt; //list of accepted patterns for division - StructLst *fRejShape; //list of rejected shapes - SurfaceList fSurfaceList; //list of optical surfaces - VolList fVolumeList; //list of volumes - NodeList fNodeList; //list of placed volumes - - NameLst *fNameList; //list of names (pointer mapped) - - //Data members - static TGDMLWrite *fgGDMLWrite; //pointer to gdml writer - Int_t fgNamingSpeed; //input option for volume and solid naming - Int_t fIgnoreDummyMaterial; // Flag to ignore TGeo's dummy material - Bool_t fgG4Compatibility; //input option for Geant4 compatibility - XMLDocPointer_t fGdmlFile; //pointer storing xml file - TString fDefault_lunit; //Default unit of length (depends on ROOT unit system) - TString fTopVolumeName; //name of top volume - TGeoVolume *fTopVolume = nullptr; //top volume of the tree being written - TXMLEngine *fGdmlE; //xml engine pointer - - XMLNodePointer_t fDefineNode; //main node... - XMLNodePointer_t fMaterialsNode; //main node... - XMLNodePointer_t fSolidsNode; //main node... - XMLNodePointer_t fStructureNode; //main node... - Int_t fVolCnt; //count of volumes - Int_t fPhysVolCnt; //count of physical volumes - UInt_t fActNameErr; //count of name errors - UInt_t fSolCnt; //count of name solids - UInt_t fFltPrecision; //! floating point precision when writing - - static const UInt_t fgkProcBit = BIT(14); //14th bit is set when solid is processed - static const UInt_t fgkProcBitVol = BIT(19); //19th bit is set when volume is processed - static const UInt_t fgkMaxNameErr = 5; //maximum number of errors for naming - - //I. Methods processing the gGeoManager geometry object structure - //1. Main methods to extract everything from ROOT gGeoManager - XMLNodePointer_t ExtractMaterials(TList* materialsLst); //result ... - TString ExtractSolid(TGeoShape* volShape); //adds to - void ExtractVolumes(TGeoNode* topNode); //result node... + corresp. shape - void ExtractMatrices(TObjArray *matrices); //adds to - void ExtractConstants(TGeoManager *geom); //adds to - void ExtractOpticalSurfaces(TObjArray *surfaces); //adds to - void ExtractSkinSurfaces(TObjArray *surfaces); //adds to - void ExtractBorderSurfaces(TObjArray *surfaces); //adds to + // General lists + StructLst *fIsotopeList; // list of isotopes + StructLst *fElementList; // list of elements + StructLst *fAccPatt; // list of accepted patterns for division + StructLst *fRejShape; // list of rejected shapes + SurfaceList fSurfaceList; // list of optical surfaces + VolList fVolumeList; // list of volumes + NodeList fNodeList; // list of placed volumes + + NameLst *fNameList; // list of names (pointer mapped) + + // Data members + static TGDMLWrite *fgGDMLWrite; // pointer to gdml writer + Int_t fgNamingSpeed; // input option for volume and solid naming + Int_t fIgnoreDummyMaterial; // Flag to ignore TGeo's dummy material + Bool_t fgG4Compatibility; // input option for Geant4 compatibility + XMLDocPointer_t fGdmlFile; // pointer storing xml file + TString fDefault_lunit; // Default unit of length (depends on ROOT unit system) + TString fTopVolumeName; // name of top volume + TGeoVolume *fTopVolume = nullptr; // top volume of the tree being written + TXMLEngine *fGdmlE; // xml engine pointer + + XMLNodePointer_t fDefineNode; // main node... + XMLNodePointer_t fMaterialsNode; // main node... + XMLNodePointer_t fSolidsNode; // main node... + XMLNodePointer_t fStructureNode; // main node... + Int_t fVolCnt; // count of volumes + Int_t fPhysVolCnt; // count of physical volumes + UInt_t fActNameErr; // count of name errors + UInt_t fSolCnt; // count of name solids + UInt_t fFltPrecision; //! floating point precision when writing + + static const UInt_t fgkProcBit = BIT(14); // 14th bit is set when solid is processed + static const UInt_t fgkProcBitVol = BIT(19); // 19th bit is set when volume is processed + static const UInt_t fgkMaxNameErr = 5; // maximum number of errors for naming + + // I. Methods processing the gGeoManager geometry object structure + // 1. Main methods to extract everything from ROOT gGeoManager + XMLNodePointer_t ExtractMaterials(TList *materialsLst); // result ... + TString ExtractSolid(TGeoShape *volShape); // adds to + void ExtractVolumes(TGeoNode *topNode); // result node... + corresp. shape + void ExtractMatrices(TObjArray *matrices); // adds to + void ExtractConstants(TGeoManager *geom); // adds to + void ExtractOpticalSurfaces(TObjArray *surfaces); // adds to + void ExtractSkinSurfaces(TObjArray *surfaces); // adds to + void ExtractBorderSurfaces(TObjArray *surfaces); // adds to // Combined implementation to extract GDML information from the geometry tree - void WriteGDMLfile(TGeoManager * geomanager, TGeoNode* top_node, TList* materialsLst, const char* filename, TString option); + void WriteGDMLfile(TGeoManager *geomanager, TGeoNode *top_node, TList *materialsLst, const char *filename, + TString option); - //1.1 Materials sub methods - creating Nodes - XMLNodePointer_t CreateAtomN(Double_t atom, const char * unit = "g/mole"); - XMLNodePointer_t CreateDN(Double_t density, const char * unit = "g/cm3"); - XMLNodePointer_t CreateFractionN(Double_t percentage, const char * refName); + // 1.1 Materials sub methods - creating Nodes + XMLNodePointer_t CreateAtomN(Double_t atom, const char *unit = "g/mole"); + XMLNodePointer_t CreateDN(Double_t density, const char *unit = "g/cm3"); + XMLNodePointer_t CreateFractionN(Double_t percentage, const char *refName); XMLNodePointer_t CreatePropertyN(TNamed const &property); - XMLNodePointer_t CreateIsotopN(TGeoIsotope * isotope, const char * name); - XMLNodePointer_t CreateElementN(TGeoElement * element, XMLNodePointer_t materials, const char * name); - XMLNodePointer_t CreateMixtureN(TGeoMixture * mixture, XMLNodePointer_t materials, TString mname); - XMLNodePointer_t CreateMaterialN(TGeoMaterial * material, TString mname); + XMLNodePointer_t CreateIsotopN(TGeoIsotope *isotope, const char *name); + XMLNodePointer_t CreateElementN(TGeoElement *element, XMLNodePointer_t materials, const char *name); + XMLNodePointer_t CreateMixtureN(TGeoMixture *mixture, XMLNodePointer_t materials, TString mname); + XMLNodePointer_t CreateMaterialN(TGeoMaterial *material, TString mname); - - //1.2 Solids sub methods + // 1.2 Solids sub methods XMLNodePointer_t ChooseObject(TGeoShape *geoShape); XMLNodePointer_t CreateZplaneN(Double_t z, Double_t rmin, Double_t rmax); - XMLNodePointer_t CreateBoxN(TGeoBBox * geoShape); - XMLNodePointer_t CreateParaboloidN(TGeoParaboloid * geoShape); - XMLNodePointer_t CreateSphereN(TGeoSphere * geoShape); - XMLNodePointer_t CreateArb8N(TGeoArb8 * geoShape); - XMLNodePointer_t CreateConeN(TGeoConeSeg * geoShape); - XMLNodePointer_t CreateConeN(TGeoCone * geoShape); - XMLNodePointer_t CreateParaN(TGeoPara * geoShape); - XMLNodePointer_t CreateTrapN(TGeoTrap * geoShape); - XMLNodePointer_t CreateTwistedTrapN(TGeoGtra * geoShape); - XMLNodePointer_t CreateTrdN(TGeoTrd1 * geoShape); - XMLNodePointer_t CreateTrdN(TGeoTrd2 * geoShape); - XMLNodePointer_t CreateTubeN(TGeoTubeSeg * geoShape); - XMLNodePointer_t CreateCutTubeN(TGeoCtub * geoShape); - XMLNodePointer_t CreateTubeN(TGeoTube * geoShape); - XMLNodePointer_t CreatePolyconeN(TGeoPcon * geoShape); - XMLNodePointer_t CreateTorusN(TGeoTorus * geoShape); - XMLNodePointer_t CreatePolyhedraN(TGeoPgon * geoShape); - XMLNodePointer_t CreateEltubeN(TGeoEltu * geoShape); - XMLNodePointer_t CreateHypeN(TGeoHype * geoShape); - XMLNodePointer_t CreateXtrusionN(TGeoXtru * geoShape); - XMLNodePointer_t CreateEllipsoidN(TGeoCompositeShape * geoShape, TString elName); - XMLNodePointer_t CreateElConeN(TGeoScaledShape * geoShape); - XMLNodePointer_t CreateTessellatedN(TGeoTessellated * geoShape); - XMLNodePointer_t CreateOpticalSurfaceN(TGeoOpticalSurface * geoSurf); - XMLNodePointer_t CreateSkinSurfaceN(TGeoSkinSurface * geoSurf); - XMLNodePointer_t CreateBorderSurfaceN(TGeoBorderSurface * geoSurf); + XMLNodePointer_t CreateBoxN(TGeoBBox *geoShape); + XMLNodePointer_t CreateParaboloidN(TGeoParaboloid *geoShape); + XMLNodePointer_t CreateSphereN(TGeoSphere *geoShape); + XMLNodePointer_t CreateArb8N(TGeoArb8 *geoShape); + XMLNodePointer_t CreateConeN(TGeoConeSeg *geoShape); + XMLNodePointer_t CreateConeN(TGeoCone *geoShape); + XMLNodePointer_t CreateParaN(TGeoPara *geoShape); + XMLNodePointer_t CreateTrapN(TGeoTrap *geoShape); + XMLNodePointer_t CreateTwistedTrapN(TGeoGtra *geoShape); + XMLNodePointer_t CreateTrdN(TGeoTrd1 *geoShape); + XMLNodePointer_t CreateTrdN(TGeoTrd2 *geoShape); + XMLNodePointer_t CreateTubeN(TGeoTubeSeg *geoShape); + XMLNodePointer_t CreateCutTubeN(TGeoCtub *geoShape); + XMLNodePointer_t CreateTubeN(TGeoTube *geoShape); + XMLNodePointer_t CreatePolyconeN(TGeoPcon *geoShape); + XMLNodePointer_t CreateTorusN(TGeoTorus *geoShape); + XMLNodePointer_t CreatePolyhedraN(TGeoPgon *geoShape); + XMLNodePointer_t CreateEltubeN(TGeoEltu *geoShape); + XMLNodePointer_t CreateHypeN(TGeoHype *geoShape); + XMLNodePointer_t CreateXtrusionN(TGeoXtru *geoShape); + XMLNodePointer_t CreateEllipsoidN(TGeoCompositeShape *geoShape, TString elName); + XMLNodePointer_t CreateElConeN(TGeoScaledShape *geoShape); + XMLNodePointer_t CreateScaledN(TGeoScaledShape *geoShape); + XMLNodePointer_t CreateTessellatedN(TGeoTessellated *geoShape); + XMLNodePointer_t CreateOpticalSurfaceN(TGeoOpticalSurface *geoSurf); + XMLNodePointer_t CreateSkinSurfaceN(TGeoSkinSurface *geoSurf); + XMLNodePointer_t CreateBorderSurfaceN(TGeoBorderSurface *geoSurf); XMLNodePointer_t CreateCommonBoolN(TGeoCompositeShape *geoShape); - //1.3 Volume sub methods - XMLNodePointer_t CreatePhysVolN(const char * name, Int_t copyno, const char * volref, const char * posref, const char * rotref, XMLNodePointer_t scaleN); - XMLNodePointer_t CreateDivisionN(Double_t offset, Double_t width, Int_t number, const char * axis, const char * unit, const char * volref); - - XMLNodePointer_t CreateSetupN(const char * topVolName , const char * name = "default", const char * version = "1.0"); - XMLNodePointer_t StartVolumeN(const char * name, const char * solid, const char * material); - XMLNodePointer_t StartAssemblyN(const char * name); - - - //II. Utility methods - Xyz GetXYZangles(const Double_t * rotationMatrix); - //nodes to create position, rotation and similar types first-position/rotation... - XMLNodePointer_t CreatePositionN(const char * name, Xyz position, const char * type, const char * unit); - XMLNodePointer_t CreateRotationN(const char * name, Xyz rotation, const char * type = "rotation", const char * unit = "deg"); + // 1.3 Volume sub methods + XMLNodePointer_t CreatePhysVolN(const char *name, Int_t copyno, const char *volref, const char *posref, + const char *rotref, XMLNodePointer_t scaleN); + XMLNodePointer_t CreateDivisionN(Double_t offset, Double_t width, Int_t number, const char *axis, const char *unit, + const char *volref); + + XMLNodePointer_t CreateSetupN(const char *topVolName, const char *name = "default", const char *version = "1.0"); + XMLNodePointer_t StartVolumeN(const char *name, const char *solid, const char *material); + XMLNodePointer_t StartAssemblyN(const char *name); + + // II. Utility methods + Xyz GetXYZangles(const Double_t *rotationMatrix); + // nodes to create position, rotation and similar types first-position/rotation... + XMLNodePointer_t CreatePositionN(const char *name, Xyz position, const char *type, const char *unit); + XMLNodePointer_t + CreateRotationN(const char *name, Xyz rotation, const char *type = "rotation", const char *unit = "deg"); XMLNodePointer_t CreateMatrixN(TGDMLMatrix const *matrix); XMLNodePointer_t CreateConstantN(const char *name, Double_t value); - TGeoCompositeShape* CreateFakeCtub(TGeoCtub * geoShape); //create fake cut tube as intersection + TGeoCompositeShape *CreateFakeCtub(TGeoCtub *geoShape); // create fake cut tube as intersection - //check name (2nd parameter) whether it is in the list (1st parameter) + // check name (2nd parameter) whether it is in the list (1st parameter) Bool_t IsInList(NameList list, TString name2check); TString GenName(TString oldname); TString GenName(TString oldname, TString objPointer); Bool_t CanProcess(TObject *pointer); - TString GetPattAxis(Int_t divAxis, const char * pattName, TString& unit); + TString GetPattAxis(Int_t divAxis, const char *pattName, TString &unit); Bool_t IsNullParam(Double_t parValue, TString parName, TString objName); - void UnsetTemporaryBits(TGeoManager * geoMng); + void UnsetTemporaryBits(TGeoManager *geoMng); UInt_t GetFltPrecision() const { return fFltPrecision; } void SetFltPrecision(UInt_t prec) { fFltPrecision = prec; } @@ -240,13 +239,17 @@ class TGDMLWrite : public TObject { //////////////////////////////////////////////////////////////////////////////// public: // Backwards compatibility (to be removed in the future): Wrapper to only selectively write one branch - void WriteGDMLfile(TGeoManager * geomanager, TGeoVolume* top_vol, const char* filename = "test.gdml", TString option = ""); + void + WriteGDMLfile(TGeoManager *geomanager, TGeoVolume *top_vol, const char *filename = "test.gdml", TString option = ""); + private: - // Backwards compatibility (to be removed in the future): Combined implementation to extract GDML information from the geometry tree - void WriteGDMLfile(TGeoManager * geomanager, TGeoVolume* top_vol, TList* materialsLst, const char* filename, TString option); - void ExtractVolumes(TGeoVolume* topVolume); //result node... + corresp. shape + // Backwards compatibility (to be removed in the future): Combined implementation to extract GDML information from + // the geometry tree + void WriteGDMLfile(TGeoManager *geomanager, TGeoVolume *top_vol, TList *materialsLst, const char *filename, + TString option); + void ExtractVolumes(TGeoVolume *topVolume); // result node... + corresp. shape - ClassDef(TGDMLWrite, 0) //imports GDML using DOM and binds it to ROOT + ClassDefOverride(TGDMLWrite, 0) // imports GDML using DOM and binds it to ROOT }; #endif /* ROOT_TGDMLWRITE */ diff --git a/geom/gdml/src/TGDMLParse.cxx b/geom/gdml/src/TGDMLParse.cxx index bebab6ebc1d42..bd5f3ee4fa560 100644 --- a/geom/gdml/src/TGDMLParse.cxx +++ b/geom/gdml/src/TGDMLParse.cxx @@ -242,6 +242,7 @@ const char *TGDMLParse::ParseGDML(TXMLEngine *gdml, XMLNodePointer_t node) const char *parbstr = "paraboloid"; const char *intestr = "intersection"; const char *reflstr = "reflectedSolid"; + const char *ssolstr = "scaledSolid"; const char *ellistr = "ellipsoid"; const char *elcnstr = "elcone"; const char *optsstr = "opticalsurface"; @@ -374,6 +375,8 @@ const char *TGDMLParse::ParseGDML(TXMLEngine *gdml, XMLNodePointer_t node) node = BooSolid(gdml, node, attr, 3); } else if ((strcmp(name, reflstr)) == 0) { node = Reflection(gdml, node, attr); + } else if ((strcmp(name, ssolstr)) == 0) { + node = ScaledSolid(gdml, node, attr); } else if ((strcmp(name, assestr)) == 0) { node = AssProcess(gdml, node); } else if ((strcmp(name, usrstr)) == 0) { @@ -493,36 +496,36 @@ void TGDMLParse::DefineConstants() auto def_units = gGeoManager->GetDefaultUnits(); // Units used in TGeo. Note that they are based on cm/degree/GeV and they are different from Geant4 - fconsts["mm"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::mm : TGeant4Unit::mm; + fconsts["mm"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::mm : TGeant4Unit::mm; fconsts["millimeter"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::mm : TGeant4Unit::mm; - fconsts["cm"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::cm : TGeant4Unit::cm; + fconsts["cm"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::cm : TGeant4Unit::cm; fconsts["centimeter"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::cm : TGeant4Unit::cm; - fconsts["m"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::m : TGeant4Unit::m; - fconsts["meter"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::m : TGeant4Unit::m; - fconsts["km"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::km : TGeant4Unit::km; - fconsts["kilometer"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::km : TGeant4Unit::km; - fconsts["rad"] = TGeoUnit::rad; - fconsts["radian"] = TGeoUnit::rad; - fconsts["deg"] = TGeoUnit::deg; - fconsts["degree"] = TGeoUnit::deg; - fconsts["pi"] = TGeoUnit::pi; - fconsts["twopi"] = TGeoUnit::twopi; - fconsts["avogadro"] = TMath::Na(); - fconsts["gev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::GeV : TGeant4Unit::GeV; - fconsts["GeV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::GeV : TGeant4Unit::GeV; - fconsts["mev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::MeV : TGeant4Unit::MeV; - fconsts["MeV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::MeV : TGeant4Unit::MeV; - fconsts["kev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::keV : TGeant4Unit::keV; - fconsts["keV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::keV : TGeant4Unit::keV; - fconsts["ev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::eV : TGeant4Unit::eV; - fconsts["eV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::eV : TGeant4Unit::eV; - fconsts["s"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::s : TGeant4Unit::s; - fconsts["ms"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::ms : TGeant4Unit::ms; - fconsts["ns"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::ns : TGeant4Unit::ns; - fconsts["us"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::us : TGeant4Unit::us; - fconsts["kg"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::kg : TGeant4Unit::kg; - fconsts["g"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::g : TGeant4Unit::g; - fconsts["mg"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::mg : TGeant4Unit::mg; + fconsts["m"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::m : TGeant4Unit::m; + fconsts["meter"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::m : TGeant4Unit::m; + fconsts["km"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::km : TGeant4Unit::km; + fconsts["kilometer"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::km : TGeant4Unit::km; + fconsts["rad"] = TGeoUnit::rad; + fconsts["radian"] = TGeoUnit::rad; + fconsts["deg"] = TGeoUnit::deg; + fconsts["degree"] = TGeoUnit::deg; + fconsts["pi"] = TGeoUnit::pi; + fconsts["twopi"] = TGeoUnit::twopi; + fconsts["avogadro"] = TMath::Na(); + fconsts["gev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::GeV : TGeant4Unit::GeV; + fconsts["GeV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::GeV : TGeant4Unit::GeV; + fconsts["mev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::MeV : TGeant4Unit::MeV; + fconsts["MeV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::MeV : TGeant4Unit::MeV; + fconsts["kev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::keV : TGeant4Unit::keV; + fconsts["keV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::keV : TGeant4Unit::keV; + fconsts["ev"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::eV : TGeant4Unit::eV; + fconsts["eV"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::eV : TGeant4Unit::eV; + fconsts["s"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::s : TGeant4Unit::s; + fconsts["ms"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::ms : TGeant4Unit::ms; + fconsts["ns"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::ns : TGeant4Unit::ns; + fconsts["us"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::us : TGeant4Unit::us; + fconsts["kg"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::kg : TGeant4Unit::kg; + fconsts["g"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::g : TGeant4Unit::g; + fconsts["mg"] = (def_units == TGeoManager::kRootUnits) ? TGeoUnit::mg : TGeant4Unit::mg; } //////////////////////////////////////////////////////////////////////////////// @@ -597,10 +600,9 @@ XMLNodePointer_t TGDMLParse::MatrixProcess(TXMLEngine *gdml, XMLNodePointer_t no // Const Properties in GDML are matrices with size 1 not constants // This gives some ambiguity, but what can one do? - if ( coldim == 1 && valueList.size() == 1 ) { + if (coldim == 1 && valueList.size() == 1) { gGeoManager->AddProperty(name, valueList[0]); - } - else { + } else { TGDMLMatrix *matrix = new TGDMLMatrix(name, valueList.size() / coldim, coldim); matrix->SetMatrixAsString(values.c_str()); for (size_t i = 0; i < valueList.size(); ++i) @@ -733,32 +735,32 @@ Double_t TGDMLParse::GetScaleVal(const char *sunit) unit.ToLower(); if ((unit == "mm") || (unit == "millimeter") || (unit == "milimeter")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 0.1 : 1.0; + retunit = (def_units == TGeoManager::kRootUnits) ? 0.1 : 1.0; } else if ((unit == "cm") || (unit == "centimeter")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 1.0 : 10.0; + retunit = (def_units == TGeoManager::kRootUnits) ? 1.0 : 10.0; } else if ((unit == "m") || (unit == "meter")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 100.0 : 1e3; + retunit = (def_units == TGeoManager::kRootUnits) ? 100.0 : 1e3; } else if ((unit == "km") || (unit == "kilometer")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 100000.0 : 1e6; + retunit = (def_units == TGeoManager::kRootUnits) ? 100000.0 : 1e6; } else if ((unit == "rad") || (unit == "radian")) { - retunit = TMath::RadToDeg(); + retunit = TMath::RadToDeg(); } else if ((unit == "deg") || (unit == "degree")) { - retunit = 1.0; + retunit = 1.0; } else if ((unit == "ev") || (unit == "electronvolt")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 0.000000001 : 1e-6; + retunit = (def_units == TGeoManager::kRootUnits) ? 0.000000001 : 1e-6; } else if ((unit == "kev") || (unit == "kiloelectronvolt")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 0.000001 : 1e-3; + retunit = (def_units == TGeoManager::kRootUnits) ? 0.000001 : 1e-3; } else if ((unit == "mev") || (unit == "megaelectronvolt")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 0.001 : 1.0; + retunit = (def_units == TGeoManager::kRootUnits) ? 0.001 : 1.0; } else if ((unit == "gev") || (unit == "gigaelectronvolt")) { - retunit = (def_units == TGeoManager::kRootUnits) ? 1.0 : 1000.0; + retunit = (def_units == TGeoManager::kRootUnits) ? 1.0 : 1000.0; } else if (unit == "pi") { - retunit = TMath::Pi(); + retunit = TMath::Pi(); } else if (unit == "avogadro") { - retunit = TMath::Na(); + retunit = TMath::Na(); } else { - Fatal("GetScaleVal", "Unit <%s> not known", sunit); - retunit = 0; + Fatal("GetScaleVal", "Unit <%s> not known", sunit); + retunit = 0; } return retunit; } @@ -1921,7 +1923,8 @@ XMLNodePointer_t TGDMLParse::VolProcess(TXMLEngine *gdml, XMLNodePointer_t node) ffilemap[fCurrentFile] = volref; } - if (filevol) volref = filevol; + if (filevol) + volref = filevol; lv = GetVolume(volref.Data()); fFILENO = fFILENO - 1; @@ -2486,7 +2489,7 @@ XMLNodePointer_t TGDMLParse::AssProcess(TXMLEngine *gdml, XMLNodePointer_t node) pos = GetPosition(reftemp.Data()); if (!pos) Fatal("AssProcess", "Position %s not found", reftemp.Data()); - } else if (tempattr == "position") { + } else if (tempattr == "position") { attr = gdml->GetFirstAttr(subchild); PosProcess(gdml, subchild, attr); reftemp = gdml->GetAttr(subchild, "name"); @@ -4439,6 +4442,69 @@ XMLNodePointer_t TGDMLParse::Tessellated(TXMLEngine *gdml, XMLNodePointer_t node return node; } +//////////////////////////////////////////////////////////////////////////////// +/// In the solids section of the GDML file, a Scaled Solid may be +/// declared when the scaledSolid keyword is found, this function +/// is called. The scale transformation is used as internal matrix. + +XMLNodePointer_t TGDMLParse::ScaledSolid(TXMLEngine *gdml, XMLNodePointer_t node, XMLAttrPointer_t attr) +{ + TString tempattr, reftemp; + XMLAttrPointer_t childattr; + + XMLNodePointer_t child = gdml->GetChild(node); + TString solidname = ""; + TGeoShape *solid = nullptr; + TGeoScale *scl = nullptr; + + TString name; + while (attr != nullptr) { + tempattr = gdml->GetAttrName(attr); + tempattr.ToLower(); + if (tempattr == "name") { + name = gdml->GetAttrValue(attr); + } + attr = gdml->GetNextAttr(attr); + } + TString local_name = name; + if ((strcmp(fCurrentFile, fStartFile)) != 0) { + local_name = TString::Format("%s_%s", name.Data(), fCurrentFile); + } + + while (child != 0) { + tempattr = gdml->GetNodeName(child); + tempattr.ToLower(); + if (tempattr == "solidref") { + reftemp = gdml->GetAttr(child, "ref"); + if ((strcmp(fCurrentFile, fStartFile)) != 0) { + reftemp = TString::Format("%s_%s", reftemp.Data(), fCurrentFile); + } + if (fsolmap.find(reftemp.Data()) != fsolmap.end()) { + solid = fsolmap[reftemp.Data()]; + } else { + printf("Solid: %s, Not Yet Defined!\n", reftemp.Data()); + } + } else if (tempattr == "scale") { + childattr = gdml->GetFirstAttr(child); + SclProcess(gdml, child, childattr); + reftemp = gdml->GetAttr(child, "name"); + scl = GetScaleObj(reftemp.Data()); + } else if (tempattr == "scaleref") { + reftemp = gdml->GetAttr(child, "ref"); + scl = GetScaleObj(reftemp.Data()); + if (!scl) + Fatal("ScaledSolid", "Solid's scale %s not found", reftemp.Data()); + } + + child = gdml->GetNext(child); + } + + auto scaled = new TGeoScaledShape(NameShort(name), solid, scl); + fsolmap[local_name.Data()] = scaled; + + return child; +} + //////////////////////////////////////////////////////////////////////////////// /// In the solids section of the GDML file, a Reflected Solid may be /// declared when the ReflectedSolid keyword is found, this function diff --git a/geom/gdml/src/TGDMLWrite.cxx b/geom/gdml/src/TGDMLWrite.cxx index 1dab287b71947..d85dd3e256d40 100644 --- a/geom/gdml/src/TGDMLWrite.cxx +++ b/geom/gdml/src/TGDMLWrite.cxx @@ -222,9 +222,10 @@ TGDMLWrite::TGDMLWrite() fPhysVolCnt(0), fActNameErr(0), fSolCnt(0), - fFltPrecision(17) // %.17g + fFltPrecision(17) // %.17g { - if (fgGDMLWrite) delete fgGDMLWrite; + if (fgGDMLWrite) + delete fgGDMLWrite; fgGDMLWrite = this; } @@ -259,43 +260,43 @@ void TGDMLWrite::SetIgnoreDummyMaterial(bool value) } //////////////////////////////////////////////////////////////////////////////// -//wrapper of all main methods for extraction -void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, const char* filename, TString option) +// wrapper of all main methods for extraction +void TGDMLWrite::WriteGDMLfile(TGeoManager *geomanager, const char *filename, TString option) { - TList* materials = geomanager->GetListOfMaterials(); - TGeoNode* node = geomanager->GetTopNode(); - if ( !node ) { - Info("WriteGDMLfile", "Top volume does not exist!"); - return; - } - fTopVolume = node->GetVolume(); - fTopVolumeName = fTopVolume->GetName(); - WriteGDMLfile(geomanager, node, materials, filename, option); + TList *materials = geomanager->GetListOfMaterials(); + TGeoNode *node = geomanager->GetTopNode(); + if (!node) { + Info("WriteGDMLfile", "Top volume does not exist!"); + return; + } + fTopVolume = node->GetVolume(); + fTopVolumeName = fTopVolume->GetName(); + WriteGDMLfile(geomanager, node, materials, filename, option); } //////////////////////////////////////////////////////////////////////////////// // Wrapper to only selectively write one branch of the volume hierarchy to file -void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, TGeoNode* node, const char* filename, TString option) -{ - TGeoVolume* volume = node->GetVolume(); - TList materials, volumes, nodes; - MaterialExtractor extract; - if ( !volume ) { - Info("WriteGDMLfile", "Invalid Volume reference to extract GDML information!"); - return; - } - extract(volume); - for(TGeoMaterial* m : extract.materials) - materials.Add(m); - fTopVolumeName = volume->GetName(); - fTopVolume = volume; - fSurfaceList.clear(); - fVolumeList.clear(); - fNodeList.clear(); - WriteGDMLfile(geomanager, node, &materials, filename, option); - materials.Clear("nodelete"); - volumes.Clear("nodelete"); - nodes.Clear("nodelete"); +void TGDMLWrite::WriteGDMLfile(TGeoManager *geomanager, TGeoNode *node, const char *filename, TString option) +{ + TGeoVolume *volume = node->GetVolume(); + TList materials, volumes, nodes; + MaterialExtractor extract; + if (!volume) { + Info("WriteGDMLfile", "Invalid Volume reference to extract GDML information!"); + return; + } + extract(volume); + for (TGeoMaterial *m : extract.materials) + materials.Add(m); + fTopVolumeName = volume->GetName(); + fTopVolume = volume; + fSurfaceList.clear(); + fVolumeList.clear(); + fNodeList.clear(); + WriteGDMLfile(geomanager, node, &materials, filename, option); + materials.Clear("nodelete"); + volumes.Clear("nodelete"); + nodes.Clear("nodelete"); } //////////////////////////////////////////////////////////////////////////////// @@ -303,13 +304,10 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, TGeoNode* node, const c /// Creates blank GDML file and fills it with gGeoManager structure converted /// to GDML structure of xml nodes -void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, - TGeoNode* node, - TList* materialsLst, - const char* filename, +void TGDMLWrite::WriteGDMLfile(TGeoManager *geomanager, TGeoNode *node, TList *materialsLst, const char *filename, TString option) { - //option processing + // option processing option.ToLower(); if (option.Contains("g")) { SetG4Compatibility(kTRUE); @@ -332,53 +330,49 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, auto def_units = gGeoManager->GetDefaultUnits(); switch (def_units) { - case TGeoManager::kG4Units: - fDefault_lunit = "mm"; - break; - case TGeoManager::kRootUnits: - fDefault_lunit = "cm"; - break; - default: // G4 units - fDefault_lunit = "mm"; - break; - } - - //local variables + case TGeoManager::kG4Units: fDefault_lunit = "mm"; break; + case TGeoManager::kRootUnits: fDefault_lunit = "cm"; break; + default: // G4 units + fDefault_lunit = "mm"; + break; + } + + // local variables Int_t outputLayout = 1; - const char * krootNodeName = "gdml"; - const char * knsRefGeneral = "http://www.w3.org/2001/XMLSchema-instance"; - const char * knsNameGeneral = "xsi"; - const char * knsRefGdml = "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"; - const char * knsNameGdml = "xsi:noNamespaceSchemaLocation"; + const char *krootNodeName = "gdml"; + const char *knsRefGeneral = "http://www.w3.org/2001/XMLSchema-instance"; + const char *knsNameGeneral = "xsi"; + const char *knsRefGdml = "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"; + const char *knsNameGdml = "xsi:noNamespaceSchemaLocation"; // First create engine fGdmlE = new TXMLEngine; fGdmlE->SetSkipComments(kTRUE); - //create blank GDML file + // create blank GDML file fGdmlFile = fGdmlE->NewDoc(); - //create root node and add it to blank GDML file + // create root node and add it to blank GDML file XMLNodePointer_t rootNode = fGdmlE->NewChild(nullptr, nullptr, krootNodeName, nullptr); fGdmlE->DocSetRootElement(fGdmlFile, rootNode); - //add namespaces to root node + // add namespaces to root node fGdmlE->NewNS(rootNode, knsRefGeneral, knsNameGeneral); fGdmlE->NewAttr(rootNode, nullptr, knsNameGdml, knsRefGdml); - //initialize general lists and , , nodes - fIsotopeList = new StructLst; - fElementList = new StructLst; + // initialize general lists and , , nodes + fIsotopeList = new StructLst; + fElementList = new StructLst; - fNameList = new NameLst; + fNameList = new NameLst; fDefineNode = fGdmlE->NewChild(nullptr, nullptr, "define", nullptr); fSolidsNode = fGdmlE->NewChild(nullptr, nullptr, "solids", nullptr); fStructureNode = fGdmlE->NewChild(nullptr, nullptr, "structure", nullptr); //======================== - //initialize list of accepted patterns for divisions (in ExtractVolumes) - fAccPatt = new StructLst; + // initialize list of accepted patterns for divisions (in ExtractVolumes) + fAccPatt = new StructLst; fAccPatt->fLst["TGeoPatternX"] = kTRUE; fAccPatt->fLst["TGeoPatternY"] = kTRUE; fAccPatt->fLst["TGeoPatternZ"] = kTRUE; @@ -386,22 +380,22 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, fAccPatt->fLst["TGeoPatternCylPhi"] = kTRUE; //======================== - //initialize list of rejected shapes for divisions (in ExtractVolumes) - fRejShape = new StructLst; - //this shapes are rejected because, it is not possible to divide trd2 - //in Y axis and while only trd2 object is imported from GDML - //it causes a problem when TGeoTrd1 is divided in Y axis + // initialize list of rejected shapes for divisions (in ExtractVolumes) + fRejShape = new StructLst; + // this shapes are rejected because, it is not possible to divide trd2 + // in Y axis and while only trd2 object is imported from GDML + // it causes a problem when TGeoTrd1 is divided in Y axis fRejShape->fLst["TGeoTrd1"] = kTRUE; fRejShape->fLst["TGeoTrd2"] = kTRUE; //========================= - //Initialize global counters + // Initialize global counters fActNameErr = 0; fVolCnt = 0; fPhysVolCnt = 0; fSolCnt = 0; - //calling main extraction functions (with measuring time) + // calling main extraction functions (with measuring time) time_t startT, endT; startT = time(nullptr); ExtractMatrices(geomanager->GetListOfGDMLMatrices()); @@ -418,10 +412,10 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, ExtractOpticalSurfaces(geomanager->GetListOfOpticalSurfaces()); endT = time(nullptr); // - fGdmlE->AddChild(rootNode, fDefineNode); // ... - fGdmlE->AddChild(rootNode, fMaterialsNode); // ... - fGdmlE->AddChild(rootNode, fSolidsNode); // ... - fGdmlE->AddChild(rootNode, fStructureNode); // ... + fGdmlE->AddChild(rootNode, fDefineNode); // ... + fGdmlE->AddChild(rootNode, fMaterialsNode); // ... + fGdmlE->AddChild(rootNode, fSolidsNode); // ... + fGdmlE->AddChild(rootNode, fStructureNode); // ... fGdmlE->AddChild(rootNode, CreateSetupN(fTopVolumeName.Data())); // ... // Double_t tdiffI = difftime(endT, startT); @@ -429,12 +423,12 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, Info("WriteGDMLfile", "Exporting time: %s", tdiffS.Data()); //========================= - //Saving document + // Saving document fGdmlE->SaveDoc(fGdmlFile, filename, outputLayout); Info("WriteGDMLfile", "File %s saved", filename); - //cleaning + // cleaning fGdmlE->FreeDoc(fGdmlFile); - //unset processing bits: + // unset processing bits: UnsetTemporaryBits(geomanager); delete fGdmlE; } @@ -442,15 +436,16 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, //////////////////////////////////////////////////////////////////////////////// /// Method exporting GDML matrices -void TGDMLWrite::ExtractMatrices(TObjArray* matrixList) +void TGDMLWrite::ExtractMatrices(TObjArray *matrixList) { - if (!matrixList->GetEntriesFast()) return; + if (!matrixList->GetEntriesFast()) + return; XMLNodePointer_t matrixN; TIter next(matrixList); TGDMLMatrix *matrix; - while ((matrix = (TGDMLMatrix*)next())) { - matrixN = CreateMatrixN(matrix); - fGdmlE->AddChild(fDefineNode, matrixN); + while ((matrix = (TGDMLMatrix *)next())) { + matrixN = CreateMatrixN(matrix); + fGdmlE->AddChild(fDefineNode, matrixN); } } @@ -459,7 +454,8 @@ void TGDMLWrite::ExtractMatrices(TObjArray* matrixList) void TGDMLWrite::ExtractConstants(TGeoManager *geom) { - if (!geom->GetNproperties()) return; + if (!geom->GetNproperties()) + return; XMLNodePointer_t constantN; TString property; Double_t value; @@ -475,12 +471,14 @@ void TGDMLWrite::ExtractConstants(TGeoManager *geom) void TGDMLWrite::ExtractOpticalSurfaces(TObjArray *surfaces) { - if (!surfaces->GetEntriesFast()) return; + if (!surfaces->GetEntriesFast()) + return; XMLNodePointer_t surfaceN; TIter next(surfaces); TGeoOpticalSurface *surf; - while ((surf = (TGeoOpticalSurface*)next())) { - if ( fSurfaceList.find(surf) == fSurfaceList.end() ) continue; + while ((surf = (TGeoOpticalSurface *)next())) { + if (fSurfaceList.find(surf) == fSurfaceList.end()) + continue; surfaceN = CreateOpticalSurfaceN(surf); fGdmlE->AddChild(fSolidsNode, surfaceN); // Info("ExtractSkinSurfaces", "Extracted optical surface: %s",surf->GetName()); @@ -492,12 +490,14 @@ void TGDMLWrite::ExtractOpticalSurfaces(TObjArray *surfaces) void TGDMLWrite::ExtractSkinSurfaces(TObjArray *surfaces) { - if (!surfaces->GetEntriesFast()) return; + if (!surfaces->GetEntriesFast()) + return; XMLNodePointer_t surfaceN; TIter next(surfaces); TGeoSkinSurface *surf; - while ((surf = (TGeoSkinSurface*)next())) { - if ( fVolumeList.find(surf->GetVolume()) == fVolumeList.end() ) continue; + while ((surf = (TGeoSkinSurface *)next())) { + if (fVolumeList.find(surf->GetVolume()) == fVolumeList.end()) + continue; surfaceN = CreateSkinSurfaceN(surf); fGdmlE->AddChild(fStructureNode, surfaceN); fSurfaceList.insert(surf->GetSurface()); @@ -510,25 +510,28 @@ void TGDMLWrite::ExtractSkinSurfaces(TObjArray *surfaces) void TGDMLWrite::ExtractBorderSurfaces(TObjArray *surfaces) { - if (!surfaces->GetEntriesFast()) return; + if (!surfaces->GetEntriesFast()) + return; XMLNodePointer_t surfaceN; TIter next(surfaces); TGeoBorderSurface *surf; - while ((surf = (TGeoBorderSurface*)next())) { + while ((surf = (TGeoBorderSurface *)next())) { auto ia = fNodeList.find(surf->GetNode1()); auto ib = fNodeList.find(surf->GetNode2()); - if ( ia == fNodeList.end() && ib == fNodeList.end() ) { - continue; - } - else if ( ia == fNodeList.end() && ib != fNodeList.end() ) { - Warning("ExtractBorderSurfaces", "Inconsistent border surface extraction %s: Node %s" - " is not part of GDML!",surf->GetName(), surf->GetNode1()->GetName()); - continue; - } - else if ( ia != fNodeList.end() && ib == fNodeList.end() ) { - Warning("ExtractBorderSurfaces", "Inconsistent border surface extraction %s: Node %s" - " is not part of GDML!",surf->GetName(), surf->GetNode2()->GetName()); - continue; + if (ia == fNodeList.end() && ib == fNodeList.end()) { + continue; + } else if (ia == fNodeList.end() && ib != fNodeList.end()) { + Warning("ExtractBorderSurfaces", + "Inconsistent border surface extraction %s: Node %s" + " is not part of GDML!", + surf->GetName(), surf->GetNode1()->GetName()); + continue; + } else if (ia != fNodeList.end() && ib == fNodeList.end()) { + Warning("ExtractBorderSurfaces", + "Inconsistent border surface extraction %s: Node %s" + " is not part of GDML!", + surf->GetName(), surf->GetNode2()->GetName()); + continue; } surfaceN = CreateBorderSurfaceN(surf); fGdmlE->AddChild(fStructureNode, surfaceN); @@ -540,14 +543,14 @@ void TGDMLWrite::ExtractBorderSurfaces(TObjArray *surfaces) //////////////////////////////////////////////////////////////////////////////// /// Method exporting materials -XMLNodePointer_t TGDMLWrite::ExtractMaterials(TList* materialsLst) +XMLNodePointer_t TGDMLWrite::ExtractMaterials(TList *materialsLst) { Info("ExtractMaterials", "Extracting materials"); - //crate main node + // crate main node XMLNodePointer_t materialsN = fGdmlE->NewChild(nullptr, nullptr, "materials", nullptr); Int_t matcnt = 0; - //go through materials - iterator and object declaration + // go through materials - iterator and object declaration TIter next(materialsLst); TGeoMaterial *lmaterial; TGeoMedium *dummy_med = TGeoVolume::DummyMedium(); @@ -561,11 +564,11 @@ XMLNodePointer_t TGDMLWrite::ExtractMaterials(TList* materialsLst) Info("ExtractMaterials", "Skip dummy material: %s", dummy_nam.c_str()); continue; } - //generate uniq name + // generate uniq name TString lname = GenName(lmaterial->GetName(), TString::Format("%p", lmaterial)); if (lmaterial->IsMixture()) { - TGeoMixture *lmixture = (TGeoMixture *)lmaterial; + TGeoMixture *lmixture = (TGeoMixture *)lmaterial; XMLNodePointer_t mixtureN = CreateMixtureN(lmixture, materialsN, lname); fGdmlE->AddChild(materialsN, mixtureN); } else { @@ -581,13 +584,14 @@ XMLNodePointer_t TGDMLWrite::ExtractMaterials(TList* materialsLst) //////////////////////////////////////////////////////////////////////////////// /// Method creating solid to xml file and returning its name -TString TGDMLWrite::ExtractSolid(TGeoShape* volShape) +TString TGDMLWrite::ExtractSolid(TGeoShape *volShape) { XMLNodePointer_t solidN; TString solname = ""; - solidN = ChooseObject(volShape); //volume->GetShape() + solidN = ChooseObject(volShape); // volume->GetShape() fGdmlE->AddChild(fSolidsNode, solidN); - if (solidN != nullptr) fSolCnt++; + if (solidN != nullptr) + fSolCnt++; solname = fNameList->fLst[TString::Format("%p", volShape)]; if (solname.Contains("missing_")) { solname = "-1"; @@ -595,106 +599,104 @@ TString TGDMLWrite::ExtractSolid(TGeoShape* volShape) return solname; } - //////////////////////////////////////////////////////////////////////////////// /// Method extracting geometry structure recursively -void TGDMLWrite::ExtractVolumes(TGeoNode* node) +void TGDMLWrite::ExtractVolumes(TGeoNode *node) { XMLNodePointer_t volumeN, childN; - TGeoVolume * volume = node->GetVolume(); + TGeoVolume *volume = node->GetVolume(); TString volname, matname, solname, pattClsName, nodeVolNameBak; TGeoPatternFinder *pattFinder = 0; Bool_t isPattern = kFALSE; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - + fNodeList.insert(node); fVolumeList.insert(volume); - //create the name for volume/assembly + // create the name for volume/assembly if (volume == fTopVolume) { - //not needed a special function for generating name + // not needed a special function for generating name volname = volume->GetName(); fTopVolumeName = volname; - //register name to the pointer + // register name to the pointer fNameList->fLst[TString::Format("%p", volume)] = volname; } else { volname = GenName(volume->GetName(), TString::Format("%p", volume)); } - - //start to create main volume/assembly node + + // start to create main volume/assembly node if (volume->IsAssembly()) { volumeN = StartAssemblyN(volname); } else { - //get reference material and add solid to + get name + // get reference material and add solid to + get name matname = fNameList->fLst[TString::Format("%p", volume->GetMaterial())]; solname = ExtractSolid(volume->GetShape()); - //If solid is not supported or corrupted + // If solid is not supported or corrupted if (solname == "-1") { Info("ExtractVolumes", "ERROR! %s volume was not added, because solid is either not supported or corrupted", volname.Data()); - //set volume as missing volume + // set volume as missing volume fNameList->fLst[TString::Format("%p", volume)] = "missing_" + volname; return; } volumeN = StartVolumeN(volname, solname, matname); - //divisionvol can't be in assembly + // divisionvol can't be in assembly pattFinder = volume->GetFinder(); - //if found pattern + // if found pattern if (pattFinder) { pattClsName = TString::Format("%s", pattFinder->ClassName()); TString shapeCls = TString::Format("%s", volume->GetShape()->ClassName()); - //if pattern in accepted pattern list and not in shape rejected list - if ((fAccPatt->fLst[pattClsName] == kTRUE) && - (fRejShape->fLst[shapeCls] != kTRUE)) { + // if pattern in accepted pattern list and not in shape rejected list + if ((fAccPatt->fLst[pattClsName] == kTRUE) && (fRejShape->fLst[shapeCls] != kTRUE)) { isPattern = kTRUE; } } } - //get all nodes in volume + // get all nodes in volume TObjArray *nodeLst = volume->GetNodes(); TIter next(nodeLst); TGeoNode *geoNode; TString physvolname; Int_t nCnt = 0; - //loop through all nodes - while ((geoNode = (TGeoNode *) next())) { - //get volume of current node and if not processed then process it - TGeoVolume * subvol = geoNode->GetVolume(); + // loop through all nodes + while ((geoNode = (TGeoNode *)next())) { + // get volume of current node and if not processed then process it + TGeoVolume *subvol = geoNode->GetVolume(); fNodeList.insert(geoNode); if (subvol->TestAttBit(fgkProcBitVol) == kFALSE) { subvol->SetAttBit(fgkProcBitVol); ExtractVolumes(geoNode); } - //volume of this node has to exist because it was processed recursively + // volume of this node has to exist because it was processed recursively TString nodevolname = fNameList->fLst[TString::Format("%p", geoNode->GetVolume())]; if (nodevolname.Contains("missing_")) { continue; } - if (nCnt == 0) { //save name of the first node for divisionvol + if (nCnt == 0) { // save name of the first node for divisionvol nodeVolNameBak = nodevolname; } if (isPattern == kFALSE) { - //create name for node + // create name for node TString nodename, posname, rotname; nodename = GenName(geoNode->GetName(), TString::Format("%p", geoNode)); nodename = nodename + "in" + volname; - //create name for position and clear rotation + // create name for position and clear rotation posname = nodename + "pos"; rotname = ""; - //position - const Double_t * pos = geoNode->GetMatrix()->GetTranslation(); + // position + const Double_t *pos = geoNode->GetMatrix()->GetTranslation(); Xyz nodPos; nodPos.x = pos[0]; nodPos.y = pos[1]; nodPos.z = pos[2]; childN = CreatePositionN(posname.Data(), nodPos, "position", fDefault_lunit); - fGdmlE->AddChild(fDefineNode, childN); //adding node to node - //Deal with reflection + fGdmlE->AddChild(fDefineNode, childN); // adding node to node + // Deal with reflection XMLNodePointer_t scaleN = nullptr; Double_t lx, ly, lz; Double_t xangle = 0; @@ -702,14 +704,14 @@ void TGDMLWrite::ExtractVolumes(TGeoNode* node) lx = geoNode->GetMatrix()->GetRotationMatrix()[0]; ly = geoNode->GetMatrix()->GetRotationMatrix()[4]; lz = geoNode->GetMatrix()->GetRotationMatrix()[8]; - if (geoNode->GetMatrix()->IsReflection() - && TMath::Abs(lx) == 1 && TMath::Abs(ly) == 1 && TMath::Abs(lz) == 1) { + if (geoNode->GetMatrix()->IsReflection() && TMath::Abs(lx) == 1 && TMath::Abs(ly) == 1 && + TMath::Abs(lz) == 1) { scaleN = fGdmlE->NewChild(nullptr, nullptr, "scale", nullptr); fGdmlE->NewAttr(scaleN, nullptr, "name", (nodename + "scl").Data()); fGdmlE->NewAttr(scaleN, nullptr, "x", TString::Format(fltPrecision.Data(), lx)); fGdmlE->NewAttr(scaleN, nullptr, "y", TString::Format(fltPrecision.Data(), ly)); fGdmlE->NewAttr(scaleN, nullptr, "z", TString::Format(fltPrecision.Data(), lz)); - //experimentally found out, that rotation should be updated like this + // experimentally found out, that rotation should be updated like this if (lx == -1) { zangle = 180; } @@ -725,20 +727,20 @@ void TGDMLWrite::ExtractVolumes(TGeoNode* node) if ((lxyz.x != 0.0) || (lxyz.y != 0.0) || (lxyz.z != 0.0)) { rotname = nodename + "rot"; childN = CreateRotationN(rotname.Data(), lxyz); - fGdmlE->AddChild(fDefineNode, childN); //adding node to node + fGdmlE->AddChild(fDefineNode, childN); // adding node to node } // create physvol for main volume/assembly node physvolname = fNameList->fLst[TString::Format("%p", geoNode)]; - childN = CreatePhysVolN(physvolname, geoNode->GetNumber(), nodevolname.Data(), - posname.Data(), rotname.Data(), scaleN); + childN = CreatePhysVolN(physvolname, geoNode->GetNumber(), nodevolname.Data(), posname.Data(), rotname.Data(), + scaleN); fGdmlE->AddChild(volumeN, childN); } nCnt++; } - //create only one divisionvol node + // create only one divisionvol node if (isPattern && pattFinder) { - //retrieve attributes of division + // retrieve attributes of division Int_t ndiv, divaxis; Double_t offset, width, xlo, xhi; TString axis, unit; @@ -749,29 +751,27 @@ void TGDMLWrite::ExtractVolumes(TGeoNode* node) divaxis = pattFinder->GetDivAxis(); volume->GetShape()->GetAxisRange(divaxis, xlo, xhi); - //compute relative start (not positional) + // compute relative start (not positional) offset = pattFinder->GetStart() - xlo; axis = GetPattAxis(divaxis, pattClsName, unit); - //create division node + // create division node childN = CreateDivisionN(offset, width, ndiv, axis.Data(), unit.Data(), nodeVolNameBak.Data()); fGdmlE->AddChild(volumeN, childN); } fVolCnt++; - //add volume/assembly node into the node + // add volume/assembly node into the node fGdmlE->AddChild(fStructureNode, volumeN); - } //////////////////////////////////////////////////////////////////////////////// /// Creates "atom" node for GDML -XMLNodePointer_t TGDMLWrite::CreateAtomN(Double_t atom, const char * unit) +XMLNodePointer_t TGDMLWrite::CreateAtomN(Double_t atom, const char *unit) { const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); XMLNodePointer_t atomN = fGdmlE->NewChild(nullptr, nullptr, "atom", nullptr); - if ( gGeoManager->GetDefaultUnits() != TGeoManager::kRootUnits ) atom /= 1e19; // Correct for G4 unit system fGdmlE->NewAttr(atomN, nullptr, "unit", unit); fGdmlE->NewAttr(atomN, nullptr, "value", TString::Format(fltPrecision.Data(), atom)); return atomN; @@ -780,11 +780,10 @@ XMLNodePointer_t TGDMLWrite::CreateAtomN(Double_t atom, const char * unit) //////////////////////////////////////////////////////////////////////////////// /// Creates "D" density node for GDML -XMLNodePointer_t TGDMLWrite::CreateDN(Double_t density, const char * unit) +XMLNodePointer_t TGDMLWrite::CreateDN(Double_t density, const char *unit) { const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); XMLNodePointer_t densN = fGdmlE->NewChild(nullptr, nullptr, "D", nullptr); - if ( gGeoManager->GetDefaultUnits() != TGeoManager::kRootUnits ) density /= 1e16; // Correct for G4 unit system fGdmlE->NewAttr(densN, nullptr, "unit", unit); fGdmlE->NewAttr(densN, nullptr, "value", TString::Format(fltPrecision.Data(), density)); return densN; @@ -793,7 +792,7 @@ XMLNodePointer_t TGDMLWrite::CreateDN(Double_t density, const char * unit) //////////////////////////////////////////////////////////////////////////////// /// Creates "fraction" node for GDML -XMLNodePointer_t TGDMLWrite::CreateFractionN(Double_t percentage, const char * refName) +XMLNodePointer_t TGDMLWrite::CreateFractionN(Double_t percentage, const char *refName) { const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); XMLNodePointer_t fractN = fGdmlE->NewChild(nullptr, nullptr, "fraction", nullptr); @@ -807,16 +806,16 @@ XMLNodePointer_t TGDMLWrite::CreateFractionN(Double_t percentage, const char * r XMLNodePointer_t TGDMLWrite::CreatePropertyN(TNamed const &property) { - XMLNodePointer_t propertyN = fGdmlE->NewChild(nullptr, nullptr, "property", nullptr); - fGdmlE->NewAttr(propertyN, nullptr, "name", property.GetName()); - fGdmlE->NewAttr(propertyN, nullptr, "ref", property.GetTitle()); - return propertyN; + XMLNodePointer_t propertyN = fGdmlE->NewChild(nullptr, nullptr, "property", nullptr); + fGdmlE->NewAttr(propertyN, nullptr, "name", property.GetName()); + fGdmlE->NewAttr(propertyN, nullptr, "ref", property.GetTitle()); + return propertyN; } //////////////////////////////////////////////////////////////////////////////// /// Creates "isotope" node for GDML -XMLNodePointer_t TGDMLWrite::CreateIsotopN(TGeoIsotope * isotope, const char * name) +XMLNodePointer_t TGDMLWrite::CreateIsotopN(TGeoIsotope *isotope, const char *name) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "isotope", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", name); @@ -828,20 +827,20 @@ XMLNodePointer_t TGDMLWrite::CreateIsotopN(TGeoIsotope * isotope, const char * n //////////////////////////////////////////////////////////////////////////////// /// Creates "element" node for GDML -///element node and attribute +/// element node and attribute -XMLNodePointer_t TGDMLWrite::CreateElementN(TGeoElement * element, XMLNodePointer_t materials, const char * name) +XMLNodePointer_t TGDMLWrite::CreateElementN(TGeoElement *element, XMLNodePointer_t materials, const char *name) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "element", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", name); - //local associative arrays for saving isotopes and their weight - //inside element + // local associative arrays for saving isotopes and their weight + // inside element NameListF wPercentage; NameListI wCounter; if (element->HasIsotopes()) { Int_t nOfIso = element->GetNisotopes(); - //go through isotopes + // go through isotopes for (Int_t idx = 0; idx < nOfIso; idx++) { TGeoIsotope *myIsotope = element->GetIsotope(idx); if (!myIsotope) { @@ -849,33 +848,33 @@ XMLNodePointer_t TGDMLWrite::CreateElementN(TGeoElement * element, XMLNodePointe return mainN; } - //Get name of the Isotope ( + // Get name of the Isotope ( TString lname = myIsotope->GetName(); //_iso suffix is added to avoid problems with same names - //for material, element and isotopes + // for material, element and isotopes lname = TString::Format("%s_iso", lname.Data()); - //cumulates abundance, in case 2 isotopes with same names - //within one element + // cumulates abundance, in case 2 isotopes with same names + // within one element wPercentage[lname] += element->GetRelativeAbundance(idx); wCounter[lname]++; - //check whether isotope name is not in list of isotopes + // check whether isotope name is not in list of isotopes if (IsInList(fIsotopeList->fLst, lname)) { continue; } - //add isotope to list of isotopes and to main node + // add isotope to list of isotopes and to main node fIsotopeList->fLst[lname] = kTRUE; XMLNodePointer_t isoNode = CreateIsotopN(myIsotope, lname); fGdmlE->AddChild(materials, isoNode); } - //loop through asoc array of isotopes + // loop through asoc array of isotopes for (NameListI::iterator itr = wCounter.begin(); itr != wCounter.end(); ++itr) { if (itr->second > 1) { Info("CreateMixtureN", "WARNING! 2 equal isotopes in one element. Check: %s isotope of %s element", itr->first.Data(), name); } - //add fraction child to element with reference to isotope + // add fraction child to element with reference to isotope fGdmlE->AddChild(mainN, CreateFractionN(wPercentage[itr->first], itr->first.Data())); } } else { @@ -895,7 +894,7 @@ XMLNodePointer_t TGDMLWrite::CreateElementN(TGeoElement * element, XMLNodePointe //////////////////////////////////////////////////////////////////////////////// /// Creates "material" node for GDML with references to other sub elements -XMLNodePointer_t TGDMLWrite::CreateMixtureN(TGeoMixture * mixture, XMLNodePointer_t materials, TString mname) +XMLNodePointer_t TGDMLWrite::CreateMixtureN(TGeoMixture *mixture, XMLNodePointer_t materials, TString mname) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "material", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", mname); @@ -905,58 +904,58 @@ XMLNodePointer_t TGDMLWrite::CreateMixtureN(TGeoMixture * mixture, XMLNodePointe if (properties.GetSize()) { TIter next(&properties); TNamed *property; - while ((property = (TNamed*)next())) - fGdmlE->AddChild(mainN, CreatePropertyN(*property)); + while ((property = (TNamed *)next())) + fGdmlE->AddChild(mainN, CreatePropertyN(*property)); } // Write CONST properties TList const &const_properties = mixture->GetConstProperties(); if (const_properties.GetSize()) { TIter next(&const_properties); TNamed *property; - while ((property = (TNamed*)next())) - fGdmlE->AddChild(mainN, CreatePropertyN(*property)); + while ((property = (TNamed *)next())) + fGdmlE->AddChild(mainN, CreatePropertyN(*property)); } fGdmlE->AddChild(mainN, CreateDN(mixture->GetDensity())); - //local associative arrays for saving elements and their weight - //inside mixture + // local associative arrays for saving elements and their weight + // inside mixture NameListF wPercentage; NameListI wCounter; Int_t nOfElm = mixture->GetNelements(); - //go through elements + // go through elements for (Int_t idx = 0; idx < nOfElm; idx++) { TGeoElement *myElement = mixture->GetElement(idx); - //Get name of the element - //NOTE: that for element - GetTitle() returns the "name" tag - //and GetName() returns "formula" tag (see createElementN) + // Get name of the element + // NOTE: that for element - GetTitle() returns the "name" tag + // and GetName() returns "formula" tag (see createElementN) TString lname = myElement->GetTitle(); //_elm suffix is added to avoid problems with same names - //for material and element + // for material and element lname = TString::Format("%s_elm", lname.Data()); - //cumulates percentage, in case 2 elements with same names within one mixture + // cumulates percentage, in case 2 elements with same names within one mixture wPercentage[lname] += mixture->GetWmixt()[idx]; wCounter[lname]++; - //check whether element name is not in list of elements already created + // check whether element name is not in list of elements already created if (IsInList(fElementList->fLst, lname)) { continue; } - //add element to list of elements and to main node + // add element to list of elements and to main node fElementList->fLst[lname] = kTRUE; XMLNodePointer_t elmNode = CreateElementN(myElement, materials, lname); fGdmlE->AddChild(materials, elmNode); } - //loop through asoc array + // loop through asoc array for (NameListI::iterator itr = wCounter.begin(); itr != wCounter.end(); ++itr) { if (itr->second > 1) { Info("CreateMixtureN", "WARNING! 2 equal elements in one material. Check: %s element of %s material", itr->first.Data(), mname.Data()); } - //add fraction child to material with reference to element + // add fraction child to material with reference to element fGdmlE->AddChild(mainN, CreateFractionN(wPercentage[itr->first], itr->first.Data())); } @@ -966,12 +965,12 @@ XMLNodePointer_t TGDMLWrite::CreateMixtureN(TGeoMixture * mixture, XMLNodePointe //////////////////////////////////////////////////////////////////////////////// /// Creates "material" node for GDML -XMLNodePointer_t TGDMLWrite::CreateMaterialN(TGeoMaterial * material, TString mname) +XMLNodePointer_t TGDMLWrite::CreateMaterialN(TGeoMaterial *material, TString mname) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "material", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", mname); Double_t valZ = material->GetZ(); - //Z can't be zero in Geant4 so this is workaround for vacuum + // Z can't be zero in Geant4 so this is workaround for vacuum TString tmpname = mname; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); tmpname.ToLower(); @@ -980,7 +979,9 @@ XMLNodePointer_t TGDMLWrite::CreateMaterialN(TGeoMaterial * material, TString mn valZ = 1; } else { if (fgG4Compatibility == kTRUE) { - Info("CreateMaterialN", "WARNING! value of Z in %s material can't be < 1 in Geant4, that is why it was changed to 1, please check it manually! ", + Info("CreateMaterialN", + "WARNING! value of Z in %s material can't be < 1 in Geant4, that is why it was changed to 1, please " + "check it manually! ", mname.Data()); valZ = 1; } else { @@ -988,7 +989,7 @@ XMLNodePointer_t TGDMLWrite::CreateMaterialN(TGeoMaterial * material, TString mn } } } - fGdmlE->NewAttr(mainN, nullptr, "Z", TString::Format(fltPrecision.Data(), valZ)); //material->GetZ())); + fGdmlE->NewAttr(mainN, nullptr, "Z", TString::Format(fltPrecision.Data(), valZ)); // material->GetZ())); // Create properties if any: Properties according to the GDML schema MUST come first! TList const &properties = material->GetProperties(); @@ -1016,14 +1017,13 @@ XMLNodePointer_t TGDMLWrite::CreateMaterialN(TGeoMaterial * material, TString mn //////////////////////////////////////////////////////////////////////////////// /// Creates "box" node for GDML -XMLNodePointer_t TGDMLWrite::CreateBoxN(TGeoBBox * geoShape) +XMLNodePointer_t TGDMLWrite::CreateBoxN(TGeoBBox *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "box", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetDX(), "DX", lname) || - IsNullParam(geoShape->GetDY(), "DY", lname) || + if (IsNullParam(geoShape->GetDX(), "DX", lname) || IsNullParam(geoShape->GetDY(), "DY", lname) || IsNullParam(geoShape->GetDZ(), "DZ", lname)) { return nullptr; } @@ -1038,14 +1038,13 @@ XMLNodePointer_t TGDMLWrite::CreateBoxN(TGeoBBox * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "paraboloid" node for GDML -XMLNodePointer_t TGDMLWrite::CreateParaboloidN(TGeoParaboloid * geoShape) +XMLNodePointer_t TGDMLWrite::CreateParaboloidN(TGeoParaboloid *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "paraboloid", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetRhi(), "Rhi", lname) || - IsNullParam(geoShape->GetDz(), "Dz", lname)) { + if (IsNullParam(geoShape->GetRhi(), "Rhi", lname) || IsNullParam(geoShape->GetDz(), "Dz", lname)) { return nullptr; } fGdmlE->NewAttr(mainN, nullptr, "rlo", TString::Format(fltPrecision.Data(), geoShape->GetRlo())); @@ -1059,7 +1058,7 @@ XMLNodePointer_t TGDMLWrite::CreateParaboloidN(TGeoParaboloid * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "sphere" node for GDML -XMLNodePointer_t TGDMLWrite::CreateSphereN(TGeoSphere * geoShape) +XMLNodePointer_t TGDMLWrite::CreateSphereN(TGeoSphere *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "sphere", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1072,9 +1071,11 @@ XMLNodePointer_t TGDMLWrite::CreateSphereN(TGeoSphere * geoShape) fGdmlE->NewAttr(mainN, nullptr, "rmin", TString::Format(fltPrecision.Data(), geoShape->GetRmin())); fGdmlE->NewAttr(mainN, nullptr, "rmax", TString::Format(fltPrecision.Data(), geoShape->GetRmax())); fGdmlE->NewAttr(mainN, nullptr, "startphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi1())); - fGdmlE->NewAttr(mainN, nullptr, "deltaphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); + fGdmlE->NewAttr(mainN, nullptr, "deltaphi", + TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); fGdmlE->NewAttr(mainN, nullptr, "starttheta", TString::Format(fltPrecision.Data(), geoShape->GetTheta1())); - fGdmlE->NewAttr(mainN, nullptr, "deltatheta", TString::Format(fltPrecision.Data(), geoShape->GetTheta2() - geoShape->GetTheta1())); + fGdmlE->NewAttr(mainN, nullptr, "deltatheta", + TString::Format(fltPrecision.Data(), geoShape->GetTheta2() - geoShape->GetTheta1())); fGdmlE->NewAttr(mainN, nullptr, "aunit", "deg"); fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); @@ -1084,7 +1085,7 @@ XMLNodePointer_t TGDMLWrite::CreateSphereN(TGeoSphere * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "arb8" node for GDML -XMLNodePointer_t TGDMLWrite::CreateArb8N(TGeoArb8 * geoShape) +XMLNodePointer_t TGDMLWrite::CreateArb8N(TGeoArb8 *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "arb8", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1119,7 +1120,7 @@ XMLNodePointer_t TGDMLWrite::CreateArb8N(TGeoArb8 * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "cone" node for GDML from TGeoConeSeg object -XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoConeSeg * geoShape) +XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoConeSeg *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "cone", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1135,7 +1136,8 @@ XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoConeSeg * geoShape) fGdmlE->NewAttr(mainN, nullptr, "rmax1", TString::Format(fltPrecision.Data(), geoShape->GetRmax1())); fGdmlE->NewAttr(mainN, nullptr, "rmax2", TString::Format(fltPrecision.Data(), geoShape->GetRmax2())); fGdmlE->NewAttr(mainN, nullptr, "startphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi1())); - fGdmlE->NewAttr(mainN, nullptr, "deltaphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); + fGdmlE->NewAttr(mainN, nullptr, "deltaphi", + TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); fGdmlE->NewAttr(mainN, nullptr, "aunit", "deg"); fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); @@ -1145,7 +1147,7 @@ XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoConeSeg * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "cone" node for GDML from TGeoCone object -XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoCone * geoShape) +XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoCone *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "cone", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1171,7 +1173,7 @@ XMLNodePointer_t TGDMLWrite::CreateConeN(TGeoCone * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "para" node for GDML -XMLNodePointer_t TGDMLWrite::CreateParaN(TGeoPara * geoShape) +XMLNodePointer_t TGDMLWrite::CreateParaN(TGeoPara *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "para", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1192,21 +1194,21 @@ XMLNodePointer_t TGDMLWrite::CreateParaN(TGeoPara * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "trap" node for GDML -XMLNodePointer_t TGDMLWrite::CreateTrapN(TGeoTrap * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTrapN(TGeoTrap *geoShape) { XMLNodePointer_t mainN; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - //if one base equals 0 create Arb8 instead of trap + // if one base equals 0 create Arb8 instead of trap if ((geoShape->GetBl1() == 0 || geoShape->GetTl1() == 0 || geoShape->GetH1() == 0) || (geoShape->GetBl2() == 0 || geoShape->GetTl2() == 0 || geoShape->GetH2() == 0)) { mainN = CreateArb8N(geoShape); return mainN; } - //if is twisted then create arb8 + // if is twisted then create arb8 if (geoShape->IsTwisted()) { - mainN = CreateArb8N((TGeoArb8 *) geoShape); + mainN = CreateArb8N((TGeoArb8 *)geoShape); return mainN; } @@ -1238,27 +1240,27 @@ XMLNodePointer_t TGDMLWrite::CreateTrapN(TGeoTrap * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "twistedtrap" node for GDML -XMLNodePointer_t TGDMLWrite::CreateTwistedTrapN(TGeoGtra * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTwistedTrapN(TGeoGtra *geoShape) { XMLNodePointer_t mainN; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - //if one base equals 0 create Arb8 instead of twisted trap + // if one base equals 0 create Arb8 instead of twisted trap if ((geoShape->GetBl1() == 0 && geoShape->GetTl1() == 0 && geoShape->GetH1() == 0) || (geoShape->GetBl2() == 0 && geoShape->GetTl2() == 0 && geoShape->GetH2() == 0)) { - mainN = CreateArb8N((TGeoArb8 *) geoShape); + mainN = CreateArb8N((TGeoArb8 *)geoShape); return mainN; } - //if is twisted then create arb8 + // if is twisted then create arb8 if (geoShape->IsTwisted()) { - mainN = CreateArb8N((TGeoArb8 *) geoShape); + mainN = CreateArb8N((TGeoArb8 *)geoShape); return mainN; } - //if parameter twistAngle (PhiTwist) equals zero create trap node + // if parameter twistAngle (PhiTwist) equals zero create trap node if (geoShape->GetTwistAngle() == 0) { - mainN = CreateTrapN((TGeoTrap *) geoShape); + mainN = CreateTrapN((TGeoTrap *)geoShape); return mainN; } @@ -1281,13 +1283,14 @@ XMLNodePointer_t TGDMLWrite::CreateTwistedTrapN(TGeoGtra * geoShape) fGdmlE->NewAttr(mainN, nullptr, "Alph", TString::Format(fltPrecision.Data(), geoShape->GetAlpha1())); - //check if alpha1 equals to alpha2 (converting to string - to avoid problems with floats) - if (TString::Format(fltPrecision.Data(), geoShape->GetAlpha1()) != TString::Format(fltPrecision.Data(), geoShape->GetAlpha2())) { + // check if alpha1 equals to alpha2 (converting to string - to avoid problems with floats) + if (TString::Format(fltPrecision.Data(), geoShape->GetAlpha1()) != + TString::Format(fltPrecision.Data(), geoShape->GetAlpha2())) { Info("CreateTwistedTrapN", "ERROR! Object %s is not exported correctly because parameter Alpha2 is not declared in GDML schema", lname.Data()); } - //fGdmlE->NewAttr(mainN,0, "alpha2", TString::Format(fltPrecision.Data(), geoShape->GetAlpha2())); + // fGdmlE->NewAttr(mainN,0, "alpha2", TString::Format(fltPrecision.Data(), geoShape->GetAlpha2())); fGdmlE->NewAttr(mainN, nullptr, "PhiTwist", TString::Format(fltPrecision.Data(), geoShape->GetTwistAngle())); fGdmlE->NewAttr(mainN, nullptr, "aunit", "deg"); @@ -1298,7 +1301,7 @@ XMLNodePointer_t TGDMLWrite::CreateTwistedTrapN(TGeoGtra * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "trd" node for GDML from object TGeoTrd1 -XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd1 * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd1 *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "trd", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1321,7 +1324,7 @@ XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd1 * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "trd" node for GDML from object TGeoTrd2 -XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd2 * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd2 *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "trd", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1344,22 +1347,22 @@ XMLNodePointer_t TGDMLWrite::CreateTrdN(TGeoTrd2 * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "tube" node for GDML from object TGeoTubeSeg -XMLNodePointer_t TGDMLWrite::CreateTubeN(TGeoTubeSeg * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTubeN(TGeoTubeSeg *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "tube", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || - IsNullParam(geoShape->GetDz(), "Dz", lname)) { + if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || IsNullParam(geoShape->GetDz(), "Dz", lname)) { return nullptr; } fGdmlE->NewAttr(mainN, nullptr, "rmin", TString::Format(fltPrecision.Data(), geoShape->GetRmin())); fGdmlE->NewAttr(mainN, nullptr, "rmax", TString::Format(fltPrecision.Data(), geoShape->GetRmax())); - fGdmlE->NewAttr(mainN, nullptr, "z", TString::Format(fltPrecision.Data(), 2 * geoShape->GetDz())); + fGdmlE->NewAttr(mainN, nullptr, "z", TString::Format(fltPrecision.Data(), 2 * geoShape->GetDz())); fGdmlE->NewAttr(mainN, nullptr, "startphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi1())); - fGdmlE->NewAttr(mainN, nullptr, "deltaphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); + fGdmlE->NewAttr(mainN, nullptr, "deltaphi", + TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); fGdmlE->NewAttr(mainN, nullptr, "aunit", "deg"); fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); @@ -1369,7 +1372,7 @@ XMLNodePointer_t TGDMLWrite::CreateTubeN(TGeoTubeSeg * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "cutTube" node for GDML -XMLNodePointer_t TGDMLWrite::CreateCutTubeN(TGeoCtub * geoShape) +XMLNodePointer_t TGDMLWrite::CreateCutTubeN(TGeoCtub *geoShape) { XMLNodePointer_t mainN; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1377,16 +1380,15 @@ XMLNodePointer_t TGDMLWrite::CreateCutTubeN(TGeoCtub * geoShape) mainN = fGdmlE->NewChild(nullptr, nullptr, "cutTube", nullptr); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || - IsNullParam(geoShape->GetDz(), "Dz", lname)) { + if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || IsNullParam(geoShape->GetDz(), "Dz", lname)) { return nullptr; } - //This is not needed, because cutTube is already supported by Geant4 9.5 + // This is not needed, because cutTube is already supported by Geant4 9.5 if (fgG4Compatibility == kTRUE && kFALSE) { - TGeoShape * fakeCtub = CreateFakeCtub(geoShape); + TGeoShape *fakeCtub = CreateFakeCtub(geoShape); mainN = ChooseObject(fakeCtub); - //register name for cuttube shape (so it will be found during volume export) + // register name for cuttube shape (so it will be found during volume export) lname = fNameList->fLst[TString::Format("%p", fakeCtub)]; fNameList->fLst[TString::Format("%p", geoShape)] = lname; Info("CreateCutTubeN", "WARNING! %s - CutTube was replaced by intersection of TGeoTubSeg and two TGeoBBoxes", @@ -1397,7 +1399,8 @@ XMLNodePointer_t TGDMLWrite::CreateCutTubeN(TGeoCtub * geoShape) fGdmlE->NewAttr(mainN, nullptr, "rmax", TString::Format(fltPrecision.Data(), geoShape->GetRmax())); fGdmlE->NewAttr(mainN, nullptr, "z", TString::Format(fltPrecision.Data(), 2 * geoShape->GetDz())); fGdmlE->NewAttr(mainN, nullptr, "startphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi1())); - fGdmlE->NewAttr(mainN, nullptr, "deltaphi", TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); + fGdmlE->NewAttr(mainN, nullptr, "deltaphi", + TString::Format(fltPrecision.Data(), geoShape->GetPhi2() - geoShape->GetPhi1())); fGdmlE->NewAttr(mainN, nullptr, "lowX", TString::Format(fltPrecision.Data(), geoShape->GetNlow()[0])); fGdmlE->NewAttr(mainN, nullptr, "lowY", TString::Format(fltPrecision.Data(), geoShape->GetNlow()[1])); fGdmlE->NewAttr(mainN, nullptr, "lowZ", TString::Format(fltPrecision.Data(), geoShape->GetNlow()[2])); @@ -1414,14 +1417,13 @@ XMLNodePointer_t TGDMLWrite::CreateCutTubeN(TGeoCtub * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "tube" node for GDML from object TGeoTube -XMLNodePointer_t TGDMLWrite::CreateTubeN(TGeoTube * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTubeN(TGeoTube *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "tube", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || - IsNullParam(geoShape->GetDz(), "Dz", lname)) { + if (IsNullParam(geoShape->GetRmax(), "Rmax", lname) || IsNullParam(geoShape->GetDz(), "Dz", lname)) { return nullptr; } @@ -1454,7 +1456,7 @@ XMLNodePointer_t TGDMLWrite::CreateZplaneN(Double_t z, Double_t rmin, Double_t r //////////////////////////////////////////////////////////////////////////////// /// Creates "polycone" node for GDML -XMLNodePointer_t TGDMLWrite::CreatePolyconeN(TGeoPcon * geoShape) +XMLNodePointer_t TGDMLWrite::CreatePolyconeN(TGeoPcon *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "polycone", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1468,35 +1470,40 @@ XMLNodePointer_t TGDMLWrite::CreatePolyconeN(TGeoPcon * geoShape) fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); Int_t nZPlns = geoShape->GetNz(); for (Int_t it = 0; it < nZPlns; it++) { - //add zplane child node + // add zplane child node fGdmlE->AddChild(mainN, CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmin(it), geoShape->GetRmax(it))); - //compare actual plane and next plane + // compare actual plane and next plane if ((it < nZPlns - 1) && (geoShape->GetZ(it) == geoShape->GetZ(it + 1))) { - //rmin of actual is greater then rmax of next one + // rmin of actual is greater then rmax of next one // | |rmax next // __ ...| |... __ < rmin actual // | | | | if (geoShape->GetRmin(it) > geoShape->GetRmax(it + 1)) { - //adding plane from rmax next to rmin actual at the same z position + // adding plane from rmax next to rmin actual at the same z position if (fgG4Compatibility == kTRUE) { - fGdmlE->AddChild(mainN, CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmax(it + 1), geoShape->GetRmin(it))); - Info("CreatePolyconeN", "WARNING! One plane was added to %s solid to be compatible with Geant4", lname.Data()); + fGdmlE->AddChild(mainN, + CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmax(it + 1), geoShape->GetRmin(it))); + Info("CreatePolyconeN", "WARNING! One plane was added to %s solid to be compatible with Geant4", + lname.Data()); } else { - Info("CreatePolyconeN", "WARNING! Solid %s definition seems not contiguous may cause problems in Geant4", lname.Data()); + Info("CreatePolyconeN", "WARNING! Solid %s definition seems not contiguous may cause problems in Geant4", + lname.Data()); } - } - //rmin of next is greater then rmax of actual + // rmin of next is greater then rmax of actual // | | | | // | |...___...| | rmin next // | | > rmax act if (geoShape->GetRmin(it + 1) > geoShape->GetRmax(it)) { - //adding plane from rmax act to rmin next at the same z position + // adding plane from rmax act to rmin next at the same z position if (fgG4Compatibility == kTRUE) { - fGdmlE->AddChild(mainN, CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmax(it), geoShape->GetRmin(it + 1))); - Info("CreatePolyconeN", "WARNING! One plane was added to %s solid to be compatible with Geant4", lname.Data()); + fGdmlE->AddChild(mainN, + CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmax(it), geoShape->GetRmin(it + 1))); + Info("CreatePolyconeN", "WARNING! One plane was added to %s solid to be compatible with Geant4", + lname.Data()); } else { - Info("CreatePolyconeN", "WARNING! Solid %s definition seems not contiguous may cause problems in Geant4", lname.Data()); + Info("CreatePolyconeN", "WARNING! Solid %s definition seems not contiguous may cause problems in Geant4", + lname.Data()); } } } @@ -1507,7 +1514,7 @@ XMLNodePointer_t TGDMLWrite::CreatePolyconeN(TGeoPcon * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "torus" node for GDML -XMLNodePointer_t TGDMLWrite::CreateTorusN(TGeoTorus * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTorusN(TGeoTorus *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "torus", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1532,7 +1539,7 @@ XMLNodePointer_t TGDMLWrite::CreateTorusN(TGeoTorus * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "polyhedra" node for GDML -XMLNodePointer_t TGDMLWrite::CreatePolyhedraN(TGeoPgon * geoShape) +XMLNodePointer_t TGDMLWrite::CreatePolyhedraN(TGeoPgon *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "polyhedra", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1545,7 +1552,7 @@ XMLNodePointer_t TGDMLWrite::CreatePolyhedraN(TGeoPgon * geoShape) fGdmlE->NewAttr(mainN, nullptr, "aunit", "deg"); fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); for (Int_t it = 0; it < geoShape->GetNz(); it++) { - //add zplane child node + // add zplane child node fGdmlE->AddChild(mainN, CreateZplaneN(geoShape->GetZ(it), geoShape->GetRmin(it), geoShape->GetRmax(it))); } return mainN; @@ -1554,14 +1561,13 @@ XMLNodePointer_t TGDMLWrite::CreatePolyhedraN(TGeoPgon * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "eltube" node for GDML -XMLNodePointer_t TGDMLWrite::CreateEltubeN(TGeoEltu * geoShape) +XMLNodePointer_t TGDMLWrite::CreateEltubeN(TGeoEltu *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "eltube", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); TString lname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); fGdmlE->NewAttr(mainN, nullptr, "name", lname); - if (IsNullParam(geoShape->GetA(), "A", lname) || - IsNullParam(geoShape->GetB(), "B", lname) || + if (IsNullParam(geoShape->GetA(), "A", lname) || IsNullParam(geoShape->GetB(), "B", lname) || IsNullParam(geoShape->GetDz(), "Dz", lname)) { return nullptr; } @@ -1578,7 +1584,7 @@ XMLNodePointer_t TGDMLWrite::CreateEltubeN(TGeoEltu * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "hype" node for GDML -XMLNodePointer_t TGDMLWrite::CreateHypeN(TGeoHype * geoShape) +XMLNodePointer_t TGDMLWrite::CreateHypeN(TGeoHype *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "hype", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1588,7 +1594,6 @@ XMLNodePointer_t TGDMLWrite::CreateHypeN(TGeoHype * geoShape) return nullptr; } - fGdmlE->NewAttr(mainN, nullptr, "rmin", TString::Format(fltPrecision.Data(), geoShape->GetRmin())); fGdmlE->NewAttr(mainN, nullptr, "rmax", TString::Format(fltPrecision.Data(), geoShape->GetRmax())); fGdmlE->NewAttr(mainN, nullptr, "inst", TString::Format(fltPrecision.Data(), geoShape->GetStIn())); @@ -1604,7 +1609,7 @@ XMLNodePointer_t TGDMLWrite::CreateHypeN(TGeoHype * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "xtru" node for GDML -XMLNodePointer_t TGDMLWrite::CreateXtrusionN(TGeoXtru * geoShape) +XMLNodePointer_t TGDMLWrite::CreateXtrusionN(TGeoXtru *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "xtru", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1613,7 +1618,7 @@ XMLNodePointer_t TGDMLWrite::CreateXtrusionN(TGeoXtru * geoShape) fGdmlE->NewAttr(mainN, nullptr, "lunit", fDefault_lunit); XMLNodePointer_t childN; - Int_t vertNum = geoShape->GetNvert(); + Int_t vertNum = geoShape->GetNvert(); Int_t secNum = geoShape->GetNz(); if (vertNum < 3 || secNum < 2) { Info("CreateXtrusionN", "ERROR! TGeoXtru %s has only %i vertices and %i sections. It was not exported", @@ -1622,14 +1627,14 @@ XMLNodePointer_t TGDMLWrite::CreateXtrusionN(TGeoXtru * geoShape) return mainN; } for (Int_t it = 0; it < vertNum; it++) { - //add twoDimVertex child node + // add twoDimVertex child node childN = fGdmlE->NewChild(nullptr, nullptr, "twoDimVertex", nullptr); fGdmlE->NewAttr(childN, nullptr, "x", TString::Format(fltPrecision.Data(), geoShape->GetX(it))); fGdmlE->NewAttr(childN, nullptr, "y", TString::Format(fltPrecision.Data(), geoShape->GetY(it))); fGdmlE->AddChild(mainN, childN); } for (Int_t it = 0; it < secNum; it++) { - //add section child node + // add section child node childN = fGdmlE->NewChild(nullptr, nullptr, "section", nullptr); fGdmlE->NewAttr(childN, nullptr, "zOrder", TString::Format("%i", it)); fGdmlE->NewAttr(childN, nullptr, "zPosition", TString::Format(fltPrecision.Data(), geoShape->GetZ(it))); @@ -1647,18 +1652,17 @@ XMLNodePointer_t TGDMLWrite::CreateXtrusionN(TGeoXtru * geoShape) /// so when intersection of scaled sphere and TGeoBBox is found, /// it is considered as an ellipsoid -XMLNodePointer_t TGDMLWrite::CreateEllipsoidN(TGeoCompositeShape * geoShape, TString elName) +XMLNodePointer_t TGDMLWrite::CreateEllipsoidN(TGeoCompositeShape *geoShape, TString elName) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "ellipsoid", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - TGeoScaledShape *leftS = (TGeoScaledShape *)geoShape->GetBoolNode()->GetLeftShape(); //ScaledShape - TGeoBBox *rightS = (TGeoBBox *)geoShape->GetBoolNode()->GetRightShape(); //BBox - + TGeoScaledShape *leftS = (TGeoScaledShape *)geoShape->GetBoolNode()->GetLeftShape(); // ScaledShape + TGeoBBox *rightS = (TGeoBBox *)geoShape->GetBoolNode()->GetRightShape(); // BBox fGdmlE->NewAttr(mainN, nullptr, "name", elName.Data()); Double_t sx = leftS->GetScale()->GetScale()[0]; Double_t sy = leftS->GetScale()->GetScale()[1]; - Double_t radius = ((TGeoSphere *) leftS->GetShape())->GetRmax(); + Double_t radius = ((TGeoSphere *)leftS->GetShape())->GetRmax(); Double_t ax, by, cz; cz = radius; @@ -1670,7 +1674,6 @@ XMLNodePointer_t TGDMLWrite::CreateEllipsoidN(TGeoCompositeShape * geoShape, TSt Double_t zcut2 = dz + zorig; Double_t zcut1 = 2 * zorig - zcut2; - fGdmlE->NewAttr(mainN, nullptr, "ax", TString::Format(fltPrecision.Data(), ax)); fGdmlE->NewAttr(mainN, nullptr, "by", TString::Format(fltPrecision.Data(), by)); fGdmlE->NewAttr(mainN, nullptr, "cz", TString::Format(fltPrecision.Data(), cz)); @@ -1686,14 +1689,14 @@ XMLNodePointer_t TGDMLWrite::CreateEllipsoidN(TGeoCompositeShape * geoShape, TSt /// this is a special case, because elliptical cone is not defined in ROOT /// so when scaled cone is found, it is considered as a elliptical cone -XMLNodePointer_t TGDMLWrite::CreateElConeN(TGeoScaledShape * geoShape) +XMLNodePointer_t TGDMLWrite::CreateElConeN(TGeoScaledShape *geoShape) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "elcone", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); fGdmlE->NewAttr(mainN, nullptr, "name", GenName(geoShape->GetName(), TString::Format("%p", geoShape))); - Double_t zcut = ((TGeoCone *) geoShape->GetShape())->GetDz(); - Double_t rx1 = ((TGeoCone *) geoShape->GetShape())->GetRmax1(); - Double_t rx2 = ((TGeoCone *) geoShape->GetShape())->GetRmax2(); + Double_t zcut = ((TGeoCone *)geoShape->GetShape())->GetDz(); + Double_t rx1 = ((TGeoCone *)geoShape->GetShape())->GetRmax1(); + Double_t rx2 = ((TGeoCone *)geoShape->GetShape())->GetRmax2(); Double_t zmax = zcut * ((rx1 + rx2) / (rx1 - rx2)); Double_t z = zcut + zmax; @@ -1713,7 +1716,7 @@ XMLNodePointer_t TGDMLWrite::CreateElConeN(TGeoScaledShape * geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "tessellated" (tessellated shape) node for GDML -XMLNodePointer_t TGDMLWrite::CreateTessellatedN(TGeoTessellated * geoShape) +XMLNodePointer_t TGDMLWrite::CreateTessellatedN(TGeoTessellated *geoShape) { // add all vertices to the define section TString genname = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); @@ -1725,7 +1728,7 @@ XMLNodePointer_t TGDMLWrite::CreateTessellatedN(TGeoTessellated * geoShape) nodPos.y = vertex[1]; nodPos.z = vertex[2]; auto childN = CreatePositionN(posName.Data(), nodPos, "position", fDefault_lunit); - fGdmlE->AddChild(fDefineNode, childN); //adding node to node + fGdmlE->AddChild(fDefineNode, childN); // adding node to node } XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "tessellated", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", genname.Data()); @@ -1733,7 +1736,7 @@ XMLNodePointer_t TGDMLWrite::CreateTessellatedN(TGeoTessellated * geoShape) XMLNodePointer_t childN; for (Int_t it = 0; it < geoShape->GetNfacets(); it++) { - //add section child node + // add section child node auto facet = geoShape->GetFacet(it); bool triangular = facet.GetNvert() == 3; TString ntype = (triangular) ? "triangular" : "quadrangular"; @@ -1749,6 +1752,57 @@ XMLNodePointer_t TGDMLWrite::CreateTessellatedN(TGeoTessellated * geoShape) return mainN; } +//////////////////////////////////////////////////////////////////////////////// +/// Creates a scaled node for GDML + +XMLNodePointer_t TGDMLWrite::CreateScaledN(TGeoScaledShape *geoShape) +{ + XMLNodePointer_t mainN, childN, unscaledN; + const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); + TString nodeName = GenName(geoShape->GetName(), TString::Format("%p", geoShape)); + auto const scale = geoShape->GetScale()->GetScale(); + TGeoShape *unscaled = geoShape->GetShape(); + // Create the unscaled shape record + unscaledN = ChooseObject(unscaled); + // retrieve node name by their pointer to make reference + TString uname = fNameList->fLst[TString::Format("%p", unscaled)]; + + // the unplaced node appended to main structure of nodes (if they are not already there) + if (unscaledN != nullptr) { + fGdmlE->AddChild(fSolidsNode, unscaledN); + fSolCnt++; + } else { + if (uname.Contains("missing_") || uname == "") { + Info("CreateScaledN", "ERROR! Unscaled node is NULL - Scaled shape will be skipped"); + return nullptr; + } + } + + // create union node and its child nodes (or intersection or subtraction) + /* + * + * + * + */ + mainN = fGdmlE->NewChild(nullptr, nullptr, "scaledSolid", nullptr); + fGdmlE->NewAttr(mainN, nullptr, "name", nodeName); + + // (solid) + childN = fGdmlE->NewChild(nullptr, nullptr, "solidref", nullptr); + fGdmlE->NewAttr(childN, nullptr, "ref", uname); + fGdmlE->AddChild(mainN, childN); + + // + childN = fGdmlE->NewChild(nullptr, nullptr, "scale", nullptr); + fGdmlE->NewAttr(childN, nullptr, "name", (nodeName + "scl").Data()); + fGdmlE->NewAttr(childN, nullptr, "x", TString::Format(fltPrecision.Data(), scale[0])); + fGdmlE->NewAttr(childN, nullptr, "y", TString::Format(fltPrecision.Data(), scale[1])); + fGdmlE->NewAttr(childN, nullptr, "z", TString::Format(fltPrecision.Data(), scale[2])); + fGdmlE->AddChild(mainN, childN); + + return mainN; +} + //////////////////////////////////////////////////////////////////////////////// /// Creates common part of union intersection and subtraction nodes @@ -1759,30 +1813,23 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) TString lboolType; TGeoBoolNode::EGeoBoolType boolType = geoShape->GetBoolNode()->GetBooleanOperator(); switch (boolType) { - case TGeoBoolNode::kGeoUnion: - lboolType = "union"; - break; - case TGeoBoolNode::kGeoSubtraction: - lboolType = "subtraction"; - break; - case TGeoBoolNode::kGeoIntersection: - lboolType = "intersection"; - break; + case TGeoBoolNode::kGeoUnion: lboolType = "union"; break; + case TGeoBoolNode::kGeoSubtraction: lboolType = "subtraction"; break; + case TGeoBoolNode::kGeoIntersection: lboolType = "intersection"; break; } TGDMLWrite::Xyz lrot = GetXYZangles(geoShape->GetBoolNode()->GetLeftMatrix()->Inverse().GetRotationMatrix()); - const Double_t *ltr = geoShape->GetBoolNode()->GetLeftMatrix()->GetTranslation(); + const Double_t *ltr = geoShape->GetBoolNode()->GetLeftMatrix()->GetTranslation(); TGDMLWrite::Xyz rrot = GetXYZangles(geoShape->GetBoolNode()->GetRightMatrix()->Inverse().GetRotationMatrix()); - const Double_t *rtr = geoShape->GetBoolNode()->GetRightMatrix()->GetTranslation(); + const Double_t *rtr = geoShape->GetBoolNode()->GetRightMatrix()->GetTranslation(); - //specific case! - //Ellipsoid tag preparing - //if left == TGeoScaledShape AND right == TGeoBBox + // specific case! + // Ellipsoid tag preparing + // if left == TGeoScaledShape AND right == TGeoBBox // AND if TGeoScaledShape->GetShape == TGeoSphere TGeoShape *leftS = geoShape->GetBoolNode()->GetLeftShape(); TGeoShape *rightS = geoShape->GetBoolNode()->GetRightShape(); - if (strcmp(leftS->ClassName(), "TGeoScaledShape") == 0 && - strcmp(rightS->ClassName(), "TGeoBBox") == 0) { + if (strcmp(leftS->ClassName(), "TGeoScaledShape") == 0 && strcmp(rightS->ClassName(), "TGeoBBox") == 0) { if (strcmp(((TGeoScaledShape *)leftS)->GetShape()->ClassName(), "TGeoSphere") == 0) { if (lboolType == "intersection") { mainN = CreateEllipsoidN(geoShape, nodeName); @@ -1792,7 +1839,7 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) } Xyz translL, translR; - //translation + // translation translL.x = ltr[0]; translL.y = ltr[1]; translL.z = ltr[2]; @@ -1800,15 +1847,15 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) translR.y = rtr[1]; translR.z = rtr[2]; - //left and right nodes are created here also their names are created + // left and right nodes are created here also their names are created ndL = ChooseObject(geoShape->GetBoolNode()->GetLeftShape()); ndR = ChooseObject(geoShape->GetBoolNode()->GetRightShape()); - //retrieve left and right node names by their pointer to make reference + // retrieve left and right node names by their pointer to make reference TString lname = fNameList->fLst[TString::Format("%p", geoShape->GetBoolNode()->GetLeftShape())]; TString rname = fNameList->fLst[TString::Format("%p", geoShape->GetBoolNode()->GetRightShape())]; - //left and right nodes appended to main structure of nodes (if they are not already there) + // left and right nodes appended to main structure of nodes (if they are not already there) if (ndL != nullptr) { fGdmlE->AddChild(fSolidsNode, ndL); fSolCnt++; @@ -1828,7 +1875,7 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) } } - //create union node and its child nodes (or intersection or subtraction) + // create union node and its child nodes (or intersection or subtraction) /* * * @@ -1837,7 +1884,7 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) * * * - */ + */ mainN = fGdmlE->NewChild(nullptr, nullptr, lboolType.Data(), nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", nodeName); @@ -1878,7 +1925,7 @@ XMLNodePointer_t TGDMLWrite::CreateCommonBoolN(TGeoCompositeShape *geoShape) //////////////////////////////////////////////////////////////////////////////// /// Creates "opticalsurface" node for GDML -XMLNodePointer_t TGDMLWrite::CreateOpticalSurfaceN(TGeoOpticalSurface * geoSurf) +XMLNodePointer_t TGDMLWrite::CreateOpticalSurfaceN(TGeoOpticalSurface *geoSurf) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "opticalsurface", nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1894,8 +1941,8 @@ XMLNodePointer_t TGDMLWrite::CreateOpticalSurfaceN(TGeoOpticalSurface * geoSurf) if (properties.GetSize()) { TIter next(&properties); TNamed *property; - while ((property = (TNamed*)next())) - fGdmlE->AddChild(mainN, CreatePropertyN(*property)); + while ((property = (TNamed *)next())) + fGdmlE->AddChild(mainN, CreatePropertyN(*property)); } return mainN; } @@ -1903,7 +1950,7 @@ XMLNodePointer_t TGDMLWrite::CreateOpticalSurfaceN(TGeoOpticalSurface * geoSurf) //////////////////////////////////////////////////////////////////////////////// /// Creates "skinsurface" node for GDML -XMLNodePointer_t TGDMLWrite::CreateSkinSurfaceN(TGeoSkinSurface * geoSurf) +XMLNodePointer_t TGDMLWrite::CreateSkinSurfaceN(TGeoSkinSurface *geoSurf) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "skinsurface", nullptr); std::string name = make_NCName(geoSurf->GetName()); @@ -1923,7 +1970,7 @@ XMLNodePointer_t TGDMLWrite::CreateSkinSurfaceN(TGeoSkinSurface * geoSurf) //////////////////////////////////////////////////////////////////////////////// /// Creates "bordersurface" node for GDML -XMLNodePointer_t TGDMLWrite::CreateBorderSurfaceN(TGeoBorderSurface * geoSurf) +XMLNodePointer_t TGDMLWrite::CreateBorderSurfaceN(TGeoBorderSurface *geoSurf) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "bordersurface", nullptr); std::string name = make_NCName(geoSurf->GetName()); @@ -1948,7 +1995,7 @@ XMLNodePointer_t TGDMLWrite::CreateBorderSurfaceN(TGeoBorderSurface * geoSurf) //////////////////////////////////////////////////////////////////////////////// /// Creates "position" kind of node for GDML -XMLNodePointer_t TGDMLWrite::CreatePositionN(const char * name, Xyz position, const char * type, const char * unit) +XMLNodePointer_t TGDMLWrite::CreatePositionN(const char *name, Xyz position, const char *type, const char *unit) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, type, nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1963,7 +2010,7 @@ XMLNodePointer_t TGDMLWrite::CreatePositionN(const char * name, Xyz position, co //////////////////////////////////////////////////////////////////////////////// /// Creates "rotation" kind of node for GDML -XMLNodePointer_t TGDMLWrite::CreateRotationN(const char * name, Xyz rotation, const char * type, const char * unit) +XMLNodePointer_t TGDMLWrite::CreateRotationN(const char *name, Xyz rotation, const char *type, const char *unit) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, type, nullptr); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); @@ -1986,12 +2033,14 @@ XMLNodePointer_t TGDMLWrite::CreateMatrixN(TGDMLMatrix const *matrix) XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "matrix", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", matrix->GetName()); fGdmlE->NewAttr(mainN, nullptr, "coldim", TString::Format("%zu", cols)); - for(size_t i=0; iGet(i,j); - if ( j < cols-1 ) vals << ' '; - } - if ( i < rows-1 ) vals << '\n'; + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < cols; ++j) { + vals << matrix->Get(i, j); + if (j < cols - 1) + vals << ' '; + } + if (i < rows - 1) + vals << '\n'; } fGdmlE->NewAttr(mainN, nullptr, "values", vals.str().c_str()); return mainN; @@ -2013,7 +2062,7 @@ XMLNodePointer_t TGDMLWrite::CreateConstantN(const char *name, Double_t value) //////////////////////////////////////////////////////////////////////////////// /// Creates "setup" node for GDML -XMLNodePointer_t TGDMLWrite::CreateSetupN(const char * topVolName, const char * name, const char * version) +XMLNodePointer_t TGDMLWrite::CreateSetupN(const char *topVolName, const char *name, const char *version) { XMLNodePointer_t setupN = fGdmlE->NewChild(nullptr, nullptr, "setup", nullptr); fGdmlE->NewAttr(setupN, nullptr, "name", name); @@ -2026,7 +2075,7 @@ XMLNodePointer_t TGDMLWrite::CreateSetupN(const char * topVolName, const char * //////////////////////////////////////////////////////////////////////////////// /// Creates "volume" node for GDML -XMLNodePointer_t TGDMLWrite::StartVolumeN(const char * name, const char * solid, const char * material) +XMLNodePointer_t TGDMLWrite::StartVolumeN(const char *name, const char *solid, const char *material) { XMLNodePointer_t childN; XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "volume", nullptr); @@ -2046,7 +2095,7 @@ XMLNodePointer_t TGDMLWrite::StartVolumeN(const char * name, const char * solid, //////////////////////////////////////////////////////////////////////////////// /// Creates "assembly" node for GDML -XMLNodePointer_t TGDMLWrite::StartAssemblyN(const char * name) +XMLNodePointer_t TGDMLWrite::StartAssemblyN(const char *name) { XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "assembly", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", name); @@ -2057,13 +2106,14 @@ XMLNodePointer_t TGDMLWrite::StartAssemblyN(const char * name) //////////////////////////////////////////////////////////////////////////////// /// Creates "physvol" node for GDML -XMLNodePointer_t TGDMLWrite::CreatePhysVolN(const char *name, Int_t copyno, const char * volref, const char * posref, const char * rotref, XMLNodePointer_t scaleN) +XMLNodePointer_t TGDMLWrite::CreatePhysVolN(const char *name, Int_t copyno, const char *volref, const char *posref, + const char *rotref, XMLNodePointer_t scaleN) { fPhysVolCnt++; XMLNodePointer_t childN; XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "physvol", nullptr); fGdmlE->NewAttr(mainN, nullptr, "name", name); - fGdmlE->NewAttr(mainN, nullptr, "copynumber", TString::Format("%d",copyno)); + fGdmlE->NewAttr(mainN, nullptr, "copynumber", TString::Format("%d", copyno)); childN = fGdmlE->NewChild(nullptr, nullptr, "volumeref", nullptr); fGdmlE->NewAttr(childN, nullptr, "ref", volref); @@ -2073,7 +2123,7 @@ XMLNodePointer_t TGDMLWrite::CreatePhysVolN(const char *name, Int_t copyno, cons fGdmlE->NewAttr(childN, nullptr, "ref", posref); fGdmlE->AddChild(mainN, childN); - //if is not empty string add this node + // if is not empty string add this node if (strcmp(rotref, "") != 0) { childN = fGdmlE->NewChild(nullptr, nullptr, "rotationref", nullptr); fGdmlE->NewAttr(childN, nullptr, "ref", rotref); @@ -2089,21 +2139,22 @@ XMLNodePointer_t TGDMLWrite::CreatePhysVolN(const char *name, Int_t copyno, cons //////////////////////////////////////////////////////////////////////////////// /// Creates "divisionvol" node for GDML -XMLNodePointer_t TGDMLWrite::CreateDivisionN(Double_t offset, Double_t width, Int_t number, const char * axis, const char * unit, const char * volref) +XMLNodePointer_t TGDMLWrite::CreateDivisionN(Double_t offset, Double_t width, Int_t number, const char *axis, + const char *unit, const char *volref) { XMLNodePointer_t childN = 0; XMLNodePointer_t mainN = fGdmlE->NewChild(nullptr, nullptr, "divisionvol", nullptr); fGdmlE->NewAttr(mainN, nullptr, "axis", axis); fGdmlE->NewAttr(mainN, nullptr, "number", TString::Format("%i", number)); const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - if (fgG4Compatibility == kTRUE) { - //if eg. full length is 20 and width * number = 20,0001 problem in geant4 - //unit is either in cm or degrees nothing else + if (fgG4Compatibility == kTRUE) { + // if eg. full length is 20 and width * number = 20,0001 problem in geant4 + // unit is either in cm or degrees nothing else width = (floor(width * 1E4)) * 1E-4; if ((offset >= 0.) && (strcmp(axis, "kPhi") == 0)) { - Int_t offsetI = (Int_t) offset; + Int_t offsetI = (Int_t)offset; Double_t decimals = offset - offsetI; - //put to range from 0 to 360 add decimals and then put to range 0 -> -360 + // put to range from 0 to 360 add decimals and then put to range 0 -> -360 offset = (offsetI % 360) + decimals - 360; } } @@ -2117,7 +2168,6 @@ XMLNodePointer_t TGDMLWrite::CreateDivisionN(Double_t offset, Double_t width, In } fGdmlE->AddChild(mainN, childN); - return mainN; } @@ -2126,81 +2176,68 @@ XMLNodePointer_t TGDMLWrite::CreateDivisionN(Double_t offset, Double_t width, In XMLNodePointer_t TGDMLWrite::ChooseObject(TGeoShape *geoShape) { - const char * clsname = geoShape->ClassName(); + const char *clsname = geoShape->ClassName(); XMLNodePointer_t solidN; if (CanProcess((TObject *)geoShape) == kFALSE) { return nullptr; } - //process different shapes + // process different shapes if (strcmp(clsname, "TGeoBBox") == 0) { - solidN = CreateBoxN((TGeoBBox*) geoShape); + solidN = CreateBoxN((TGeoBBox *)geoShape); } else if (strcmp(clsname, "TGeoParaboloid") == 0) { - solidN = CreateParaboloidN((TGeoParaboloid*) geoShape); + solidN = CreateParaboloidN((TGeoParaboloid *)geoShape); } else if (strcmp(clsname, "TGeoSphere") == 0) { - solidN = CreateSphereN((TGeoSphere*) geoShape); + solidN = CreateSphereN((TGeoSphere *)geoShape); } else if (strcmp(clsname, "TGeoArb8") == 0) { - solidN = CreateArb8N((TGeoArb8*) geoShape); + solidN = CreateArb8N((TGeoArb8 *)geoShape); } else if (strcmp(clsname, "TGeoConeSeg") == 0) { - solidN = CreateConeN((TGeoConeSeg*) geoShape); + solidN = CreateConeN((TGeoConeSeg *)geoShape); } else if (strcmp(clsname, "TGeoCone") == 0) { - solidN = CreateConeN((TGeoCone*) geoShape); + solidN = CreateConeN((TGeoCone *)geoShape); } else if (strcmp(clsname, "TGeoPara") == 0) { - solidN = CreateParaN((TGeoPara*) geoShape); + solidN = CreateParaN((TGeoPara *)geoShape); } else if (strcmp(clsname, "TGeoTrap") == 0) { - solidN = CreateTrapN((TGeoTrap*) geoShape); + solidN = CreateTrapN((TGeoTrap *)geoShape); } else if (strcmp(clsname, "TGeoGtra") == 0) { - solidN = CreateTwistedTrapN((TGeoGtra*) geoShape); + solidN = CreateTwistedTrapN((TGeoGtra *)geoShape); } else if (strcmp(clsname, "TGeoTrd1") == 0) { - solidN = CreateTrdN((TGeoTrd1*) geoShape); + solidN = CreateTrdN((TGeoTrd1 *)geoShape); } else if (strcmp(clsname, "TGeoTrd2") == 0) { - solidN = CreateTrdN((TGeoTrd2*) geoShape); + solidN = CreateTrdN((TGeoTrd2 *)geoShape); } else if (strcmp(clsname, "TGeoTubeSeg") == 0) { - solidN = CreateTubeN((TGeoTubeSeg*) geoShape); + solidN = CreateTubeN((TGeoTubeSeg *)geoShape); } else if (strcmp(clsname, "TGeoCtub") == 0) { - solidN = CreateCutTubeN((TGeoCtub*) geoShape); + solidN = CreateCutTubeN((TGeoCtub *)geoShape); } else if (strcmp(clsname, "TGeoTube") == 0) { - solidN = CreateTubeN((TGeoTube*) geoShape); + solidN = CreateTubeN((TGeoTube *)geoShape); } else if (strcmp(clsname, "TGeoPcon") == 0) { - solidN = CreatePolyconeN((TGeoPcon*) geoShape); + solidN = CreatePolyconeN((TGeoPcon *)geoShape); } else if (strcmp(clsname, "TGeoTorus") == 0) { - solidN = CreateTorusN((TGeoTorus*) geoShape); + solidN = CreateTorusN((TGeoTorus *)geoShape); } else if (strcmp(clsname, "TGeoPgon") == 0) { - solidN = CreatePolyhedraN((TGeoPgon*) geoShape); + solidN = CreatePolyhedraN((TGeoPgon *)geoShape); } else if (strcmp(clsname, "TGeoEltu") == 0) { - solidN = CreateEltubeN((TGeoEltu*) geoShape); + solidN = CreateEltubeN((TGeoEltu *)geoShape); } else if (strcmp(clsname, "TGeoHype") == 0) { - solidN = CreateHypeN((TGeoHype*) geoShape); + solidN = CreateHypeN((TGeoHype *)geoShape); } else if (strcmp(clsname, "TGeoXtru") == 0) { - solidN = CreateXtrusionN((TGeoXtru*) geoShape); + solidN = CreateXtrusionN((TGeoXtru *)geoShape); } else if (strcmp(clsname, "TGeoTessellated") == 0) { - solidN = CreateTessellatedN((TGeoTessellated*) geoShape); + solidN = CreateTessellatedN((TGeoTessellated *)geoShape); } else if (strcmp(clsname, "TGeoScaledShape") == 0) { - TGeoScaledShape * geoscale = (TGeoScaledShape *) geoShape; - TString scaleObjClsName = geoscale->GetShape()->ClassName(); - if (scaleObjClsName == "TGeoCone") { - solidN = CreateElConeN((TGeoScaledShape*) geoShape); - } else { - Info("ChooseObject", - "ERROR! TGeoScaledShape object is not possible to process correctly. %s object is processed without scale", - scaleObjClsName.Data()); - solidN = ChooseObject(geoscale->GetShape()); - //Name has to be propagated to geoscale level pointer - fNameList->fLst[TString::Format("%p", geoscale)] = - fNameList->fLst[TString::Format("%p", geoscale->GetShape())]; - } + solidN = CreateScaledN((TGeoScaledShape *)geoShape); } else if (strcmp(clsname, "TGeoCompositeShape") == 0) { - solidN = CreateCommonBoolN((TGeoCompositeShape*) geoShape); + solidN = CreateCommonBoolN((TGeoCompositeShape *)geoShape); } else if (strcmp(clsname, "TGeoUnion") == 0) { - solidN = CreateCommonBoolN((TGeoCompositeShape*) geoShape); + solidN = CreateCommonBoolN((TGeoCompositeShape *)geoShape); } else if (strcmp(clsname, "TGeoIntersection") == 0) { - solidN = CreateCommonBoolN((TGeoCompositeShape*) geoShape); + solidN = CreateCommonBoolN((TGeoCompositeShape *)geoShape); } else if (strcmp(clsname, "TGeoSubtraction") == 0) { - solidN = CreateCommonBoolN((TGeoCompositeShape*) geoShape); + solidN = CreateCommonBoolN((TGeoCompositeShape *)geoShape); } else { - Info("ChooseObject", "ERROR! %s Solid CANNOT be processed, solid is NOT supported", - clsname); + Info("ChooseObject", "ERROR! %s Solid CANNOT be processed, solid is NOT supported", clsname); solidN = nullptr; } if (solidN == nullptr) { @@ -2208,7 +2245,8 @@ XMLNodePointer_t TGDMLWrite::ChooseObject(TGeoShape *geoShape) TString missingName = geoShape->GetName(); GenName("missing_" + missingName, TString::Format("%p", geoShape)); } else { - fNameList->fLst[TString::Format("%p", geoShape)] = "missing_" + fNameList->fLst[TString::Format("%p", geoShape)]; + fNameList->fLst[TString::Format("%p", geoShape)] = + "missing_" + fNameList->fLst[TString::Format("%p", geoShape)]; } } @@ -2218,7 +2256,7 @@ XMLNodePointer_t TGDMLWrite::ChooseObject(TGeoShape *geoShape) //////////////////////////////////////////////////////////////////////////////// /// Retrieves X Y Z angles from rotation matrix -TGDMLWrite::Xyz TGDMLWrite::GetXYZangles(const Double_t * rotationMatrix) +TGDMLWrite::Xyz TGDMLWrite::GetXYZangles(const Double_t *rotationMatrix) { TGDMLWrite::Xyz lxyz; Double_t a, b, c; @@ -2244,7 +2282,7 @@ TGDMLWrite::Xyz TGDMLWrite::GetXYZangles(const Double_t * rotationMatrix) /// Method creating cutTube as an intersection of tube and two boxes /// - not used anymore because cutube is supported in Geant4 9.5 -TGeoCompositeShape* TGDMLWrite::CreateFakeCtub(TGeoCtub* geoShape) +TGeoCompositeShape *TGDMLWrite::CreateFakeCtub(TGeoCtub *geoShape) { Double_t rmin = geoShape->GetRmin(); Double_t rmax = geoShape->GetRmax(); @@ -2259,8 +2297,7 @@ TGeoCompositeShape* TGDMLWrite::CreateFakeCtub(TGeoCtub* geoShape) Double_t z2 = geoShape->GetNhigh()[2]; TString xname = geoShape->GetName(); - - Double_t h0 = 2.*((TGeoBBox*)geoShape)->GetDZ(); + Double_t h0 = 2. * ((TGeoBBox *)geoShape)->GetDZ(); Double_t h1 = 2 * z; Double_t h2 = 2 * z; Double_t boxdx = 1E8 * (2 * rmax) + (2 * z); @@ -2269,31 +2306,29 @@ TGeoCompositeShape* TGDMLWrite::CreateFakeCtub(TGeoCtub* geoShape) TGeoBBox *B1 = new TGeoBBox((xname + "B1").Data(), boxdx, boxdx, h1); TGeoBBox *B2 = new TGeoBBox((xname + "B2").Data(), boxdx, boxdx, h2); - - //first box position parameters + // first box position parameters Double_t phi1 = 360 - TMath::ATan2(x1, y1) * TMath::RadToDeg(); Double_t theta1 = 360 - TMath::ATan2(sqrt(x1 * x1 + y1 * y1), z1) * TMath::RadToDeg(); - Double_t phi11 = TMath::ATan2(y1, x1) * TMath::RadToDeg() ; - Double_t theta11 = TMath::ATan2(z1, sqrt(x1 * x1 + y1 * y1)) * TMath::RadToDeg() ; + Double_t phi11 = TMath::ATan2(y1, x1) * TMath::RadToDeg(); + Double_t theta11 = TMath::ATan2(z1, sqrt(x1 * x1 + y1 * y1)) * TMath::RadToDeg(); - Double_t xpos1 = h1 * TMath::Cos((theta11) * TMath::DegToRad()) * TMath::Cos((phi11) * TMath::DegToRad()) * (-1); - Double_t ypos1 = h1 * TMath::Cos((theta11) * TMath::DegToRad()) * TMath::Sin((phi11) * TMath::DegToRad()) * (-1); - Double_t zpos1 = h1 * TMath::Sin((theta11) * TMath::DegToRad()) * (-1); + Double_t xpos1 = h1 * TMath::Cos((theta11)*TMath::DegToRad()) * TMath::Cos((phi11)*TMath::DegToRad()) * (-1); + Double_t ypos1 = h1 * TMath::Cos((theta11)*TMath::DegToRad()) * TMath::Sin((phi11)*TMath::DegToRad()) * (-1); + Double_t zpos1 = h1 * TMath::Sin((theta11)*TMath::DegToRad()) * (-1); - //second box position parameters + // second box position parameters Double_t phi2 = 360 - TMath::ATan2(x2, y2) * TMath::RadToDeg(); Double_t theta2 = 360 - TMath::ATan2(sqrt(x2 * x2 + y2 * y2), z2) * TMath::RadToDeg(); - Double_t phi21 = TMath::ATan2(y2, x2) * TMath::RadToDeg() ; - Double_t theta21 = TMath::ATan2(z2, sqrt(x2 * x2 + y2 * y2)) * TMath::RadToDeg() ; - - Double_t xpos2 = h2 * TMath::Cos((theta21) * TMath::DegToRad()) * TMath::Cos((phi21) * TMath::DegToRad()) * (-1); - Double_t ypos2 = h2 * TMath::Cos((theta21) * TMath::DegToRad()) * TMath::Sin((phi21) * TMath::DegToRad()) * (-1); - Double_t zpos2 = h2 * TMath::Sin((theta21) * TMath::DegToRad()) * (-1); + Double_t phi21 = TMath::ATan2(y2, x2) * TMath::RadToDeg(); + Double_t theta21 = TMath::ATan2(z2, sqrt(x2 * x2 + y2 * y2)) * TMath::RadToDeg(); + Double_t xpos2 = h2 * TMath::Cos((theta21)*TMath::DegToRad()) * TMath::Cos((phi21)*TMath::DegToRad()) * (-1); + Double_t ypos2 = h2 * TMath::Cos((theta21)*TMath::DegToRad()) * TMath::Sin((phi21)*TMath::DegToRad()) * (-1); + Double_t zpos2 = h2 * TMath::Sin((theta21)*TMath::DegToRad()) * (-1); - //positioning + // positioning TGeoTranslation *t0 = new TGeoTranslation(0, 0, 0); TGeoTranslation *t1 = new TGeoTranslation(0 + xpos1, 0 + ypos1, 0 + (zpos1 - z)); TGeoTranslation *t2 = new TGeoTranslation(0 + xpos2, 0 + ypos2, 0 + (zpos2 + z)); @@ -2304,9 +2339,9 @@ TGeoCompositeShape* TGDMLWrite::CreateFakeCtub(TGeoCtub* geoShape) r1->SetAngles(phi1, theta1, 0); r2->SetAngles(phi2, theta2, 0); - TGeoMatrix* m0 = new TGeoCombiTrans(*t0, *r0); - TGeoMatrix* m1 = new TGeoCombiTrans(*t1, *r1); - TGeoMatrix* m2 = new TGeoCombiTrans(*t2, *r2); + TGeoMatrix *m0 = new TGeoCombiTrans(*t0, *r0); + TGeoMatrix *m1 = new TGeoCombiTrans(*t1, *r1); + TGeoMatrix *m2 = new TGeoCombiTrans(*t2, *r2); TGeoCompositeShape *CS1 = new TGeoCompositeShape((xname + "CS1").Data(), new TGeoIntersection(T, B1, m0, m1)); TGeoCompositeShape *cs = new TGeoCompositeShape((xname + "CS").Data(), new TGeoIntersection(CS1, B2, m0, m2)); @@ -2329,8 +2364,8 @@ Bool_t TGDMLWrite::IsInList(NameList list, TString name2check) } //////////////////////////////////////////////////////////////////////////////// -///NCNAME basic restrictions -///Replace "$" character with empty character etc. +/// NCNAME basic restrictions +/// Replace "$" character with empty character etc. TString TGDMLWrite::GenName(TString oldname) { @@ -2351,7 +2386,7 @@ TString TGDMLWrite::GenName(TString oldname) newname = newname.ReplaceAll("[", ""); newname = newname.ReplaceAll("]", ""); newname = newname.ReplaceAll("_refl", ""); - //workaround if first letter is digit than replace it to "O" (ou character) + // workaround if first letter is digit than replace it to "O" (ou character) TString fstLet = newname(0, 1); if (fstLet.IsDigit()) { newname = "O" + newname(1, newname.Length()); @@ -2367,41 +2402,38 @@ TString TGDMLWrite::GenName(TString oldname, TString objPointer) TString newname = GenName(oldname); if (newname != oldname) { if (fgkMaxNameErr > fActNameErr) { - Info("GenName", - "WARNING! Name of the object was changed because it failed to comply with NCNAME xml datatype restrictions."); + Info("GenName", "WARNING! Name of the object was changed because it failed to comply with NCNAME xml datatype " + "restrictions."); } else if ((fgkMaxNameErr == fActNameErr)) { - Info("GenName", - "WARNING! Probably more names are going to be changed to comply with NCNAME xml datatype restriction, but it will not be displayed on the screen."); + Info("GenName", "WARNING! Probably more names are going to be changed to comply with NCNAME xml datatype " + "restriction, but it will not be displayed on the screen."); } fActNameErr++; } TString nameIter; Int_t iter = 0; switch (fgNamingSpeed) { - case kfastButUglySufix: - newname = newname + "0x" + objPointer; - break; - case kelegantButSlow: - //0 means not in the list - iter = fNameList->fLstIter[newname]; - if (iter == 0) { - nameIter = ""; - } else { - nameIter = TString::Format("0x%i", iter); - } - fNameList->fLstIter[newname]++; - newname = newname + nameIter; - break; - case kwithoutSufixNotUniq: - //no change - break; - } - //store the name (mapped to pointer) + case kfastButUglySufix: newname = newname + "0x" + objPointer; break; + case kelegantButSlow: + // 0 means not in the list + iter = fNameList->fLstIter[newname]; + if (iter == 0) { + nameIter = ""; + } else { + nameIter = TString::Format("0x%i", iter); + } + fNameList->fLstIter[newname]++; + newname = newname + nameIter; + break; + case kwithoutSufixNotUniq: + // no change + break; + } + // store the name (mapped to pointer) fNameList->fLst[objPointer] = newname; return newname; } - //////////////////////////////////////////////////////////////////////////////// /// Method which tests whether solids can be processed @@ -2416,34 +2448,32 @@ Bool_t TGDMLWrite::CanProcess(TObject *pointer) //////////////////////////////////////////////////////////////////////////////// /// Method that retrieves axis and unit along which object is divided -TString TGDMLWrite::GetPattAxis(Int_t divAxis, const char * pattName, TString& unit) +TString TGDMLWrite::GetPattAxis(Int_t divAxis, const char *pattName, TString &unit) { TString resaxis; unit = fDefault_lunit; switch (divAxis) { - case 1: - if (strcmp(pattName, "TGeoPatternX") == 0) { - return "kXAxis"; - } else if (strcmp(pattName, "TGeoPatternCylR") == 0) { - return "kRho"; - } - break; - case 2: - if (strcmp(pattName, "TGeoPatternY") == 0) { - return "kYAxis"; - } else if (strcmp(pattName, "TGeoPatternCylPhi") == 0) { - unit = "deg"; - return "kPhi"; - } - break; - case 3: - if (strcmp(pattName, "TGeoPatternZ") == 0) { - return "kZAxis"; - } - break; - default: - return "kUndefined"; - break; + case 1: + if (strcmp(pattName, "TGeoPatternX") == 0) { + return "kXAxis"; + } else if (strcmp(pattName, "TGeoPatternCylR") == 0) { + return "kRho"; + } + break; + case 2: + if (strcmp(pattName, "TGeoPatternY") == 0) { + return "kYAxis"; + } else if (strcmp(pattName, "TGeoPatternCylPhi") == 0) { + unit = "deg"; + return "kPhi"; + } + break; + case 3: + if (strcmp(pattName, "TGeoPatternZ") == 0) { + return "kZAxis"; + } + break; + default: return "kUndefined"; break; } return "kUndefined"; } @@ -2455,9 +2485,7 @@ Bool_t TGDMLWrite::IsNullParam(Double_t parValue, TString parName, TString objNa { if (parValue == 0.) { Info("IsNullParam", "ERROR! %s is NULL due to %s = %.12g, Volume based on this shape will be skipped", - objName.Data(), - parName.Data(), - parValue); + objName.Data(), parName.Data(), parValue); return kTRUE; } return kFALSE; @@ -2467,7 +2495,7 @@ Bool_t TGDMLWrite::IsNullParam(Double_t parValue, TString parName, TString objNa /// Unsetting bits that were changed in gGeoManager during export so that export /// can be run more times with the same instance of gGeoManager. -void TGDMLWrite::UnsetTemporaryBits(TGeoManager * geoMng) +void TGDMLWrite::UnsetTemporaryBits(TGeoManager *geoMng) { TIter next(geoMng->GetListOfVolumes()); TGeoVolume *vol; @@ -2475,10 +2503,8 @@ void TGDMLWrite::UnsetTemporaryBits(TGeoManager * geoMng) ((TObject *)vol->GetShape())->SetBit(fgkProcBit, kFALSE); vol->SetAttBit(fgkProcBitVol, kFALSE); } - } - //////////////////////////////////////////////////////////////////////////////// // // Backwards compatibility for old DD4hep version (to be removed in the future) @@ -2487,41 +2513,37 @@ void TGDMLWrite::UnsetTemporaryBits(TGeoManager * geoMng) //////////////////////////////////////////////////////////////////////////////// // Backwards compatibility (to be removed in the future): Wrapper to only selectively write one branch -void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, TGeoVolume* volume, const char* filename, TString option) -{ - TList materials, volumes, nodes; - MaterialExtractor extract; - if ( !volume ) { - Info("WriteGDMLfile", "Invalid Volume reference to extract GDML information!"); - return; - } - extract(volume); - for(TGeoMaterial* m : extract.materials) - materials.Add(m); - fTopVolumeName = volume->GetName(); - fTopVolume = volume; - fSurfaceList.clear(); - fVolumeList.clear(); - fNodeList.clear(); - WriteGDMLfile(geomanager, volume, &materials, filename, option); - materials.Clear("nodelete"); - volumes.Clear("nodelete"); - nodes.Clear("nodelete"); +void TGDMLWrite::WriteGDMLfile(TGeoManager *geomanager, TGeoVolume *volume, const char *filename, TString option) +{ + TList materials, volumes, nodes; + MaterialExtractor extract; + if (!volume) { + Info("WriteGDMLfile", "Invalid Volume reference to extract GDML information!"); + return; + } + extract(volume); + for (TGeoMaterial *m : extract.materials) + materials.Add(m); + fTopVolumeName = volume->GetName(); + fTopVolume = volume; + fSurfaceList.clear(); + fVolumeList.clear(); + fNodeList.clear(); + WriteGDMLfile(geomanager, volume, &materials, filename, option); + materials.Clear("nodelete"); + volumes.Clear("nodelete"); + nodes.Clear("nodelete"); } - //////////////////////////////////////////////////////////////////////////////// /// Wrapper of all exporting methods /// Creates blank GDML file and fills it with gGeoManager structure converted /// to GDML structure of xml nodes -void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, - TGeoVolume* volume, - TList* materialsLst, - const char* filename, +void TGDMLWrite::WriteGDMLfile(TGeoManager *geomanager, TGeoVolume *volume, TList *materialsLst, const char *filename, TString option) { - //option processing + // option processing option.ToLower(); if (option.Contains("g")) { SetG4Compatibility(kTRUE); @@ -2540,42 +2562,42 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, Info("WriteGDMLfile", "Potentially slow with incremental suffix naming convention set"); } - //local variables + // local variables Int_t outputLayout = 1; - const char * krootNodeName = "gdml"; - const char * knsRefGeneral = "http://www.w3.org/2001/XMLSchema-instance"; - const char * knsNameGeneral = "xsi"; - const char * knsRefGdml = "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"; - const char * knsNameGdml = "xsi:noNamespaceSchemaLocation"; + const char *krootNodeName = "gdml"; + const char *knsRefGeneral = "http://www.w3.org/2001/XMLSchema-instance"; + const char *knsNameGeneral = "xsi"; + const char *knsRefGdml = "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"; + const char *knsNameGdml = "xsi:noNamespaceSchemaLocation"; // First create engine fGdmlE = new TXMLEngine; fGdmlE->SetSkipComments(kTRUE); - //create blank GDML file + // create blank GDML file fGdmlFile = fGdmlE->NewDoc(); - //create root node and add it to blank GDML file + // create root node and add it to blank GDML file XMLNodePointer_t rootNode = fGdmlE->NewChild(nullptr, nullptr, krootNodeName, nullptr); fGdmlE->DocSetRootElement(fGdmlFile, rootNode); - //add namespaces to root node + // add namespaces to root node fGdmlE->NewNS(rootNode, knsRefGeneral, knsNameGeneral); fGdmlE->NewAttr(rootNode, nullptr, knsNameGdml, knsRefGdml); - //initialize general lists and , , nodes - fIsotopeList = new StructLst; - fElementList = new StructLst; + // initialize general lists and , , nodes + fIsotopeList = new StructLst; + fElementList = new StructLst; - fNameList = new NameLst; + fNameList = new NameLst; fDefineNode = fGdmlE->NewChild(nullptr, nullptr, "define", nullptr); fSolidsNode = fGdmlE->NewChild(nullptr, nullptr, "solids", nullptr); fStructureNode = fGdmlE->NewChild(nullptr, nullptr, "structure", nullptr); //======================== - //initialize list of accepted patterns for divisions (in ExtractVolumes) - fAccPatt = new StructLst; + // initialize list of accepted patterns for divisions (in ExtractVolumes) + fAccPatt = new StructLst; fAccPatt->fLst["TGeoPatternX"] = kTRUE; fAccPatt->fLst["TGeoPatternY"] = kTRUE; fAccPatt->fLst["TGeoPatternZ"] = kTRUE; @@ -2583,22 +2605,22 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, fAccPatt->fLst["TGeoPatternCylPhi"] = kTRUE; //======================== - //initialize list of rejected shapes for divisions (in ExtractVolumes) - fRejShape = new StructLst; - //this shapes are rejected because, it is not possible to divide trd2 - //in Y axis and while only trd2 object is imported from GDML - //it causes a problem when TGeoTrd1 is divided in Y axis + // initialize list of rejected shapes for divisions (in ExtractVolumes) + fRejShape = new StructLst; + // this shapes are rejected because, it is not possible to divide trd2 + // in Y axis and while only trd2 object is imported from GDML + // it causes a problem when TGeoTrd1 is divided in Y axis fRejShape->fLst["TGeoTrd1"] = kTRUE; fRejShape->fLst["TGeoTrd2"] = kTRUE; //========================= - //Initialize global counters + // Initialize global counters fActNameErr = 0; fVolCnt = 0; fPhysVolCnt = 0; fSolCnt = 0; - //calling main extraction functions (with measuring time) + // calling main extraction functions (with measuring time) time_t startT, endT; startT = time(nullptr); ExtractMatrices(geomanager->GetListOfGDMLMatrices()); @@ -2615,10 +2637,10 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, ExtractOpticalSurfaces(geomanager->GetListOfOpticalSurfaces()); endT = time(nullptr); // - fGdmlE->AddChild(rootNode, fDefineNode); // ... - fGdmlE->AddChild(rootNode, fMaterialsNode); // ... - fGdmlE->AddChild(rootNode, fSolidsNode); // ... - fGdmlE->AddChild(rootNode, fStructureNode); // ... + fGdmlE->AddChild(rootNode, fDefineNode); // ... + fGdmlE->AddChild(rootNode, fMaterialsNode); // ... + fGdmlE->AddChild(rootNode, fSolidsNode); // ... + fGdmlE->AddChild(rootNode, fStructureNode); // ... fGdmlE->AddChild(rootNode, CreateSetupN(fTopVolumeName.Data())); // ... // Double_t tdiffI = difftime(endT, startT); @@ -2626,23 +2648,20 @@ void TGDMLWrite::WriteGDMLfile(TGeoManager * geomanager, Info("WriteGDMLfile", "Exporting time: %s", tdiffS.Data()); //========================= - //Saving document + // Saving document fGdmlE->SaveDoc(fGdmlFile, filename, outputLayout); Info("WriteGDMLfile", "File %s saved", filename); - //cleaning + // cleaning fGdmlE->FreeDoc(fGdmlFile); - //unset processing bits: + // unset processing bits: UnsetTemporaryBits(geomanager); delete fGdmlE; } - - - //////////////////////////////////////////////////////////////////////////////// /// Method extracting geometry structure recursively -void TGDMLWrite::ExtractVolumes(TGeoVolume* volume) +void TGDMLWrite::ExtractVolumes(TGeoVolume *volume) { XMLNodePointer_t volumeN, childN; TString volname, matname, solname, pattClsName, nodeVolNameBak; @@ -2650,90 +2669,89 @@ void TGDMLWrite::ExtractVolumes(TGeoVolume* volume) Bool_t isPattern = kFALSE; const TString fltPrecision = TString::Format("%%.%dg", fFltPrecision); - //create the name for volume/assembly + // create the name for volume/assembly if (volume == fTopVolume) { - //not needed a special function for generating name + // not needed a special function for generating name volname = volume->GetName(); fTopVolumeName = volname; - //register name to the pointer + // register name to the pointer fNameList->fLst[TString::Format("%p", volume)] = volname; } else { volname = GenName(volume->GetName(), TString::Format("%p", volume)); } - //start to create main volume/assembly node + // start to create main volume/assembly node if (volume->IsAssembly()) { volumeN = StartAssemblyN(volname); } else { - //get reference material and add solid to + get name + // get reference material and add solid to + get name matname = fNameList->fLst[TString::Format("%p", volume->GetMaterial())]; solname = ExtractSolid(volume->GetShape()); - //If solid is not supported or corrupted + // If solid is not supported or corrupted if (solname == "-1") { Info("ExtractVolumes", "ERROR! %s volume was not added, because solid is either not supported or corrupted", volname.Data()); - //set volume as missing volume + // set volume as missing volume fNameList->fLst[TString::Format("%p", volume)] = "missing_" + volname; return; } volumeN = StartVolumeN(volname, solname, matname); - //divisionvol can't be in assembly + // divisionvol can't be in assembly pattFinder = volume->GetFinder(); - //if found pattern + // if found pattern if (pattFinder) { pattClsName = TString::Format("%s", pattFinder->ClassName()); TString shapeCls = TString::Format("%s", volume->GetShape()->ClassName()); - //if pattern in accepted pattern list and not in shape rejected list - if ((fAccPatt->fLst[pattClsName] == kTRUE) && - (fRejShape->fLst[shapeCls] != kTRUE)) { + // if pattern in accepted pattern list and not in shape rejected list + if ((fAccPatt->fLst[pattClsName] == kTRUE) && (fRejShape->fLst[shapeCls] != kTRUE)) { isPattern = kTRUE; } } } - //get all nodes in volume + // get all nodes in volume TObjArray *nodeLst = volume->GetNodes(); TIter next(nodeLst); TString physvolname; TGeoNode *geoNode; Int_t nCnt = 0; - //loop through all nodes - while ((geoNode = (TGeoNode *) next())) { - //get volume of current node and if not processed then process it - TGeoVolume * subvol = geoNode->GetVolume(); + // loop through all nodes + while ((geoNode = (TGeoNode *)next())) { + // get volume of current node and if not processed then process it + TGeoVolume *subvol = geoNode->GetVolume(); if (subvol->TestAttBit(fgkProcBitVol) == kFALSE) { subvol->SetAttBit(fgkProcBitVol); ExtractVolumes(subvol); } - //volume of this node has to exist because it was processed recursively + // volume of this node has to exist because it was processed recursively TString nodevolname = fNameList->fLst[TString::Format("%p", geoNode->GetVolume())]; if (nodevolname.Contains("missing_")) { continue; } - if (nCnt == 0) { //save name of the first node for divisionvol + if (nCnt == 0) { // save name of the first node for divisionvol nodeVolNameBak = nodevolname; } if (isPattern == kFALSE) { - //create name for node + // create name for node TString nodename, posname, rotname; nodename = GenName(geoNode->GetName(), TString::Format("%p", geoNode)); nodename = nodename + "in" + volname; - //create name for position and clear rotation + // create name for position and clear rotation posname = nodename + "pos"; rotname = ""; - //position - const Double_t * pos = geoNode->GetMatrix()->GetTranslation(); + // position + const Double_t *pos = geoNode->GetMatrix()->GetTranslation(); Xyz nodPos; nodPos.x = pos[0]; nodPos.y = pos[1]; nodPos.z = pos[2]; childN = CreatePositionN(posname.Data(), nodPos, "position", fDefault_lunit); - fGdmlE->AddChild(fDefineNode, childN); //adding node to node - //Deal with reflection + fGdmlE->AddChild(fDefineNode, childN); // adding node to node + // Deal with reflection XMLNodePointer_t scaleN = nullptr; Double_t lx, ly, lz; Double_t xangle = 0; @@ -2741,14 +2759,14 @@ void TGDMLWrite::ExtractVolumes(TGeoVolume* volume) lx = geoNode->GetMatrix()->GetRotationMatrix()[0]; ly = geoNode->GetMatrix()->GetRotationMatrix()[4]; lz = geoNode->GetMatrix()->GetRotationMatrix()[8]; - if (geoNode->GetMatrix()->IsReflection() - && TMath::Abs(lx) == 1 && TMath::Abs(ly) == 1 && TMath::Abs(lz) == 1) { + if (geoNode->GetMatrix()->IsReflection() && TMath::Abs(lx) == 1 && TMath::Abs(ly) == 1 && + TMath::Abs(lz) == 1) { scaleN = fGdmlE->NewChild(nullptr, nullptr, "scale", nullptr); fGdmlE->NewAttr(scaleN, nullptr, "name", (nodename + "scl").Data()); fGdmlE->NewAttr(scaleN, nullptr, "x", TString::Format(fltPrecision.Data(), lx)); fGdmlE->NewAttr(scaleN, nullptr, "y", TString::Format(fltPrecision.Data(), ly)); fGdmlE->NewAttr(scaleN, nullptr, "z", TString::Format(fltPrecision.Data(), lz)); - //experimentally found out, that rotation should be updated like this + // experimentally found out, that rotation should be updated like this if (lx == -1) { zangle = 180; } @@ -2757,27 +2775,27 @@ void TGDMLWrite::ExtractVolumes(TGeoVolume* volume) } } - //rotation + // rotation TGDMLWrite::Xyz lxyz = GetXYZangles(geoNode->GetMatrix()->GetRotationMatrix()); lxyz.x -= xangle; lxyz.z -= zangle; if ((lxyz.x != 0.0) || (lxyz.y != 0.0) || (lxyz.z != 0.0)) { rotname = nodename + "rot"; childN = CreateRotationN(rotname.Data(), lxyz); - fGdmlE->AddChild(fDefineNode, childN); //adding node to node + fGdmlE->AddChild(fDefineNode, childN); // adding node to node } - //create physvol for main volume/assembly node + // create physvol for main volume/assembly node physvolname = fNameList->fLst[TString::Format("%p", geoNode)]; - childN = CreatePhysVolN(physvolname, geoNode->GetNumber(), nodevolname.Data(), - posname.Data(), rotname.Data(), scaleN); + childN = CreatePhysVolN(physvolname, geoNode->GetNumber(), nodevolname.Data(), posname.Data(), rotname.Data(), + scaleN); fGdmlE->AddChild(volumeN, childN); } nCnt++; } - //create only one divisionvol node + // create only one divisionvol node if (isPattern && pattFinder) { - //retrieve attributes of division + // retrieve attributes of division Int_t ndiv, divaxis; Double_t offset, width, xlo, xhi; TString axis, unit; @@ -2788,16 +2806,16 @@ void TGDMLWrite::ExtractVolumes(TGeoVolume* volume) divaxis = pattFinder->GetDivAxis(); volume->GetShape()->GetAxisRange(divaxis, xlo, xhi); - //compute relative start (not positional) + // compute relative start (not positional) offset = pattFinder->GetStart() - xlo; axis = GetPattAxis(divaxis, pattClsName, unit); - //create division node + // create division node childN = CreateDivisionN(offset, width, ndiv, axis.Data(), unit.Data(), nodeVolNameBak.Data()); fGdmlE->AddChild(volumeN, childN); } fVolCnt++; - //add volume/assembly node into the node + // add volume/assembly node into the node fGdmlE->AddChild(fStructureNode, volumeN); } diff --git a/geom/geom/inc/LinkDef1.h b/geom/geom/inc/LinkDef1.h index fd6918f9176e9..58c2bcb851cf2 100644 --- a/geom/geom/inc/LinkDef1.h +++ b/geom/geom/inc/LinkDef1.h @@ -13,96 +13,96 @@ #pragma link C++ global gGeoManager; #pragma link C++ global gGeoIdentity; -#pragma link C++ class TGeoAtt+; -#pragma link C++ struct TGeoStateInfo+; -#pragma link C++ class TGeoBoolNode+; -#pragma link C++ class TGeoUnion+; -#pragma link C++ class TGeoIntersection+; -#pragma link C++ class TGeoSubtraction+; -#pragma link C++ class TGeoMedium+; -#pragma link C++ class TGeoOpticalSurface+; -#pragma link C++ enum TGeoOpticalSurface::ESurfaceType; -#pragma link C++ enum TGeoOpticalSurface::ESurfaceModel; -#pragma link C++ enum TGeoOpticalSurface::ESurfaceFinish; -#pragma link C++ class TGeoSkinSurface+; -#pragma link C++ class TGeoBorderSurface+; -#pragma link C++ class TGeoElement+; -#pragma read sourceClass="TGeoElement" targetClass="TGeoElement" version="[1-2]" source="" target="" \ - code="{ newObj->ComputeDerivedQuantities() ; }" -#pragma link C++ class TGeoElementRN+; -#pragma link C++ class TGeoIsotope+; -#pragma link C++ class TGeoDecayChannel+; -#pragma link C++ class TGeoElemIter+; -#pragma link C++ class TGeoBatemanSol+; -#pragma link C++ class TGeoElementTable+; -#pragma link C++ class TGeoMaterial+; -#pragma link C++ class TGeoMixture+; -#pragma link C++ class TGeoMatrix+; -#pragma link C++ class TGeoHMatrix+; -#pragma link C++ class TGeoTranslation+; -#pragma link C++ class TGeoRotation+; -#pragma link C++ class TGeoCombiTrans+; -#pragma link C++ class TGeoGenTrans+; -#pragma link C++ class TGeoScale+; -#pragma link C++ class TGeoIdentity+; -#pragma link C++ class TGeoVoxelFinder-; -#pragma link C++ class TGeoShape+; -#pragma link C++ class TGeoHelix+; -#pragma link C++ class TGeoHalfSpace+; -#pragma link C++ class TGeoBBox+; -#pragma link C++ class TGeoPara+; -#pragma link C++ class TGeoSphere+; -#pragma link C++ class TGeoTube+; -#pragma link C++ class TGeoTorus+; -#pragma link C++ class TGeoTubeSeg+; -#pragma read sourceClass="TGeoTubeSeg" targetClass="TGeoTubeSeg" version="[1]" source="" target="" \ - code="{ newObj->AfterStreamer() ; }" -#pragma link C++ class TGeoCtub+; -#pragma link C++ class TGeoEltu+; -#pragma link C++ class TGeoHype+; -#pragma link C++ class TGeoCone+; -#pragma link C++ class TGeoConeSeg+; -#pragma read sourceClass="TGeoConeSeg" targetClass="TGeoConeSeg" version="[1]" source="" target="" \ - code="{ newObj->AfterStreamer() ; }" -#pragma link C++ class TGeoParaboloid+; -#pragma link C++ class TGeoPcon-; -#pragma link C++ class TGeoPgon+; -#pragma link C++ class TGeoArb8-; -#pragma link C++ class TGeoTrap+; -#pragma link C++ class TGeoGtra+; -#pragma link C++ class TGeoTrd1+; -#pragma link C++ class TGeoTrd2+; -#pragma link C++ class TGeoCompositeShape+; -#pragma link C++ class TGeoPolygon+; -#pragma link C++ class TGeoXtru+; -#pragma link C++ class ROOT::Geom::Vertex_t+; -#pragma link C++ class TGeoFacet+; -#pragma link C++ class TGeoTessellated+; -#pragma link C++ class TGeoShapeAssembly+; -#pragma link C++ class TGeoScaledShape+; -#pragma link C++ class TGeoVolume-; -#pragma link C++ class TGeoVolumeAssembly+; -#pragma link C++ class TGeoVolumeMulti+; -#pragma link C++ class TGeoNode+; -#pragma link C++ class TGeoPhysicalNode+; -#pragma link C++ class TGeoPNEntry+; -#pragma link C++ class TGeoNodeMatrix+; -#pragma link C++ class TGeoNodeOffset+; -#pragma link C++ class TGeoManager-; -#pragma link C++ class TGeoRegionCut+; -#pragma link C++ class TGeoRegion+; -#pragma link C++ class TVirtualGeoPainter+; -#pragma link C++ class TVirtualGeoTrack+; -#pragma link C++ class TVirtualGeoConverter+; +#pragma link C++ class TGeoAtt + ; +#pragma link C++ struct TGeoStateInfo + ; +#pragma link C++ class TGeoBoolNode + ; +#pragma link C++ class TGeoUnion + ; +#pragma link C++ class TGeoIntersection + ; +#pragma link C++ class TGeoSubtraction + ; +#pragma link C++ class TGeoMedium + ; +#pragma link C++ class TGeoOpticalSurface + ; +#pragma link C++ enum TGeoOpticalSurface::ESurfaceType; +#pragma link C++ enum TGeoOpticalSurface::ESurfaceModel; +#pragma link C++ enum TGeoOpticalSurface::ESurfaceFinish; +#pragma link C++ class TGeoSkinSurface + ; +#pragma link C++ class TGeoBorderSurface + ; +#pragma link C++ class TGeoElement + ; +#pragma read sourceClass = "TGeoElement" targetClass = "TGeoElement" version = "[1-2]" source = "" target = "" code = \ + "{ newObj->ComputeDerivedQuantities() ; }" +#pragma link C++ class TGeoElementRN + ; +#pragma link C++ class TGeoIsotope + ; +#pragma link C++ class TGeoDecayChannel + ; +#pragma link C++ class TGeoElemIter + ; +#pragma link C++ class TGeoBatemanSol + ; +#pragma link C++ class TGeoElementTable + ; +#pragma link C++ class TGeoMaterial + ; +#pragma link C++ class TGeoMixture + ; +#pragma link C++ class TGeoMatrix + ; +#pragma link C++ class TGeoHMatrix + ; +#pragma link C++ class TGeoTranslation + ; +#pragma link C++ class TGeoRotation + ; +#pragma link C++ class TGeoCombiTrans + ; +#pragma link C++ class TGeoGenTrans + ; +#pragma link C++ class TGeoScale + ; +#pragma link C++ class TGeoIdentity + ; +#pragma link C++ class TGeoVoxelFinder - ; +#pragma link C++ class TGeoShape + ; +#pragma link C++ class TGeoHelix + ; +#pragma link C++ class TGeoHalfSpace + ; +#pragma link C++ class TGeoBBox + ; +#pragma link C++ class TGeoPara + ; +#pragma link C++ class TGeoSphere + ; +#pragma link C++ class TGeoTube + ; +#pragma link C++ class TGeoTorus + ; +#pragma link C++ class TGeoTubeSeg + ; +#pragma read sourceClass = "TGeoTubeSeg" targetClass = "TGeoTubeSeg" version = "[1]" source = "" target = "" code = \ + "{ newObj->AfterStreamer() ; }" +#pragma link C++ class TGeoCtub + ; +#pragma link C++ class TGeoEltu + ; +#pragma link C++ class TGeoHype + ; +#pragma link C++ class TGeoCone + ; +#pragma link C++ class TGeoConeSeg + ; +#pragma read sourceClass = "TGeoConeSeg" targetClass = "TGeoConeSeg" version = "[1]" source = "" target = "" code = \ + "{ newObj->AfterStreamer() ; }" +#pragma link C++ class TGeoParaboloid + ; +#pragma link C++ class TGeoPcon - ; +#pragma link C++ class TGeoPgon + ; +#pragma link C++ class TGeoArb8 - ; +#pragma link C++ class TGeoTrap + ; +#pragma link C++ class TGeoGtra + ; +#pragma link C++ class TGeoTrd1 + ; +#pragma link C++ class TGeoTrd2 + ; +#pragma link C++ class TGeoCompositeShape + ; +#pragma link C++ class TGeoPolygon + ; +#pragma link C++ class TGeoXtru + ; +#pragma link C++ class ROOT::Geom::Vertex_t + ; +#pragma link C++ class TGeoFacet + ; +#pragma link C++ class TGeoTessellated + ; +#pragma link C++ class TGeoShapeAssembly + ; +#pragma link C++ class TGeoScaledShape + ; +#pragma link C++ class TGeoVolume - ; +#pragma link C++ class TGeoVolumeAssembly + ; +#pragma link C++ class TGeoVolumeMulti + ; +#pragma link C++ class TGeoNode + ; +#pragma link C++ class TGeoPhysicalNode + ; +#pragma link C++ class TGeoPNEntry + ; +#pragma link C++ class TGeoNodeMatrix + ; +#pragma link C++ class TGeoNodeOffset + ; +#pragma link C++ class TGeoManager - ; +#pragma link C++ class TGeoRegionCut + ; +#pragma link C++ class TGeoRegion + ; +#pragma link C++ class TVirtualGeoPainter + ; +#pragma link C++ class TVirtualGeoTrack + ; +#pragma link C++ class TVirtualGeoConverter + ; #pragma link C++ class TGeoIterator; #pragma link C++ class TGeoIteratorPlugin; #pragma link C++ class TGeoBuilder; -#pragma link C++ class TGeoNavigator+; +#pragma link C++ class TGeoNavigator + ; #pragma link C++ class TGeoNavigatorArray; -#pragma link C++ class TGDMLMatrix+; -#pragma link C++ struct std::map; -#pragma link C++ struct std::pair; -#pragma link C++ struct std::map; -#pragma link C++ struct std::pair; +#pragma link C++ class TGDMLMatrix + ; +#pragma link C++ struct std::map < std::thread::id, TGeoNavigatorArray * > ; +#pragma link C++ struct std::pair < std::thread::id, TGeoNavigatorArray * > ; +#pragma link C++ struct std::map < std::thread::id, Int_t > ; +#pragma link C++ struct std::pair < std::thread::id, Int_t > ; #endif diff --git a/geom/geom/inc/LinkDef2.h b/geom/geom/inc/LinkDef2.h index 4e6ef47350435..1605f5e8abbcf 100644 --- a/geom/geom/inc/LinkDef2.h +++ b/geom/geom/inc/LinkDef2.h @@ -10,28 +10,28 @@ #ifdef __CINT__ -#pragma link C++ class TGeoPatternFinder+; -#pragma link C++ class TGeoPatternX+; -#pragma link C++ class TGeoPatternY+; -#pragma link C++ class TGeoPatternZ+; -#pragma link C++ class TGeoPatternParaX+; -#pragma link C++ class TGeoPatternParaY+; -#pragma link C++ class TGeoPatternParaZ+; -#pragma link C++ class TGeoPatternTrapZ+; -#pragma link C++ class TGeoPatternCylR+; -#pragma link C++ class TGeoPatternCylPhi-; -#pragma link C++ class TGeoPatternSphR+; -#pragma link C++ class TGeoPatternSphTheta+; -#pragma link C++ class TGeoPatternSphPhi+; -#pragma link C++ class TGeoPatternHoneycomb+; -#pragma link C++ class TGeoNodeCache+; -#pragma link C++ class TGeoCacheState+; -#pragma link C++ class TVirtualMagField+; -#pragma link C++ class TGeoUniformMagField+; +#pragma link C++ class TGeoPatternFinder + ; +#pragma link C++ class TGeoPatternX + ; +#pragma link C++ class TGeoPatternY + ; +#pragma link C++ class TGeoPatternZ + ; +#pragma link C++ class TGeoPatternParaX + ; +#pragma link C++ class TGeoPatternParaY + ; +#pragma link C++ class TGeoPatternParaZ + ; +#pragma link C++ class TGeoPatternTrapZ + ; +#pragma link C++ class TGeoPatternCylR + ; +#pragma link C++ class TGeoPatternCylPhi - ; +#pragma link C++ class TGeoPatternSphR + ; +#pragma link C++ class TGeoPatternSphTheta + ; +#pragma link C++ class TGeoPatternSphPhi + ; +#pragma link C++ class TGeoPatternHoneycomb + ; +#pragma link C++ class TGeoNodeCache + ; +#pragma link C++ class TGeoCacheState + ; +#pragma link C++ class TVirtualMagField + ; +#pragma link C++ class TGeoUniformMagField + ; #pragma link C++ class TGeoGlobalMagField; -#pragma link C++ class TGeoBranchArray+; -#pragma link C++ class TGeoExtension+; -#pragma link C++ class TGeoRCExtension+; -#pragma link C++ class TGeoParallelWorld+; +#pragma link C++ class TGeoBranchArray + ; +#pragma link C++ class TGeoExtension + ; +#pragma link C++ class TGeoRCExtension + ; +#pragma link C++ class TGeoParallelWorld + ; #endif diff --git a/geom/geom/inc/TGDMLMatrix.h b/geom/geom/inc/TGDMLMatrix.h index a79d03db6b6da..48881ca840527 100644 --- a/geom/geom/inc/TGDMLMatrix.h +++ b/geom/geom/inc/TGDMLMatrix.h @@ -14,7 +14,6 @@ #include - //////////////////////////////////////////////////////////////////////////// // // // TGDMLProperty - A property with a name and a reference name pointing // @@ -34,28 +33,27 @@ typedef TNamed TGDMLProperty; class TGDMLMatrix : public TNamed { public: TGDMLMatrix() {} - TGDMLMatrix(const char *name, size_t rows,size_t cols); - TGDMLMatrix(const TGDMLMatrix& rhs); - TGDMLMatrix& operator=(const TGDMLMatrix& rhs); - ~TGDMLMatrix() { delete [] fMatrix; } - - void Set(size_t r, size_t c, Double_t a); - Double_t Get(size_t r, size_t c) const; - size_t GetRows() const { return fNrows; } - size_t GetCols() const { return fNcols; } - void SetMatrixAsString(const char *mat) { fTitle = mat; } + TGDMLMatrix(const char *name, size_t rows, size_t cols); + TGDMLMatrix(const TGDMLMatrix &rhs); + TGDMLMatrix &operator=(const TGDMLMatrix &rhs); + ~TGDMLMatrix() override { delete[] fMatrix; } + + void Set(size_t r, size_t c, Double_t a); + Double_t Get(size_t r, size_t c) const; + size_t GetRows() const { return fNrows; } + size_t GetCols() const { return fNcols; } + void SetMatrixAsString(const char *mat) { fTitle = mat; } const char *GetMatrixAsString() const { return fTitle.Data(); } - void Print(Option_t *option="") const; - - private: + void Print(Option_t *option = "") const override; - Int_t fNelem = 0; // Number of elements - size_t fNrows = 0; // Number of rows - size_t fNcols = 0; // Number of columns - Double_t *fMatrix = nullptr; // [fNelem] Matrix elements +private: + Int_t fNelem = 0; // Number of elements + size_t fNrows = 0; // Number of rows + size_t fNcols = 0; // Number of columns + Double_t *fMatrix = nullptr; // [fNelem] Matrix elements - ClassDef(TGDMLMatrix, 1) // Class representing a matrix used temporary for GDML parsing + ClassDefOverride(TGDMLMatrix, 1) // Class representing a matrix used temporary for GDML parsing }; #endif /* ROOT_TGDMLMATRIX */ diff --git a/geom/geom/inc/TGeant4SystemOfUnits.h b/geom/geom/inc/TGeant4SystemOfUnits.h index aa55e7ba0d6ea..971b486815c4e 100644 --- a/geom/geom/inc/TGeant4SystemOfUnits.h +++ b/geom/geom/inc/TGeant4SystemOfUnits.h @@ -56,275 +56,275 @@ namespace TGeant4Unit { - // - // TGeo follows Geant3 convention as specified in manual - // "Unless otherwise specified, the following units are used throughout the program: - // centimeter, second, degree, GeV" - - // - // - // - static constexpr double pi = 3.14159265358979323846; - static constexpr double twopi = 2 * pi; - static constexpr double halfpi = pi / 2; - static constexpr double pi2 = pi * pi; - - // - // Length [L] - // - static constexpr double millimeter = 1.0; - static constexpr double millimeter2 = millimeter * millimeter; - static constexpr double millimeter3 = millimeter * millimeter * millimeter; - - static constexpr double centimeter = 10. * millimeter; // Base unit - static constexpr double centimeter2 = centimeter * centimeter; - static constexpr double centimeter3 = centimeter * centimeter * centimeter; - - static constexpr double meter = 1000. * millimeter; - static constexpr double meter2 = meter * meter; - static constexpr double meter3 = meter * meter * meter; - - static constexpr double kilometer = 1000. * meter; - static constexpr double kilometer2 = kilometer * kilometer; - static constexpr double kilometer3 = kilometer * kilometer * kilometer; - - static constexpr double parsec = 3.0856775807e+16 * meter; - - static constexpr double micrometer = 1.e-6 * meter; - static constexpr double nanometer = 1.e-9 * meter; - static constexpr double angstrom = 1.e-10 * meter; - static constexpr double fermi = 1.e-15 * meter; - - static constexpr double barn = 1.e-28 * meter2; - static constexpr double millibarn = 1.e-3 * barn; - static constexpr double microbarn = 1.e-6 * barn; - static constexpr double nanobarn = 1.e-9 * barn; - static constexpr double picobarn = 1.e-12 * barn; - - // symbols - static constexpr double nm = nanometer; - static constexpr double um = micrometer; - - static constexpr double mm = millimeter; - static constexpr double mm2 = millimeter2; - static constexpr double mm3 = millimeter3; - - static constexpr double cm = centimeter; - static constexpr double cm2 = centimeter2; - static constexpr double cm3 = centimeter3; - - static constexpr double liter = 1.e+3 * cm3; - static constexpr double L = liter; - static constexpr double dL = 1.e-1 * liter; - static constexpr double cL = 1.e-2 * liter; - static constexpr double mL = 1.e-3 * liter; - - static constexpr double m = meter; - static constexpr double m2 = meter2; - static constexpr double m3 = meter3; - - static constexpr double km = kilometer; - static constexpr double km2 = kilometer2; - static constexpr double km3 = kilometer3; - - static constexpr double pc = parsec; - - // - // Angle - // - static constexpr double degree = 1.0; // Base unit - static constexpr double radian = (180.0 / pi) * degree; - static constexpr double milliradian = 1.e-3 * radian; - - static constexpr double steradian = 1.; - - // symbols - static constexpr double rad = radian; - static constexpr double mrad = milliradian; - static constexpr double sr = steradian; - static constexpr double deg = degree; - - // - // Time [T] - // - static constexpr double nanosecond = 1.0; - static constexpr double second = 1.e+9 * nanosecond; // Base unit - static constexpr double millisecond = 1.e-3 * second; - static constexpr double microsecond = 1.e-6 * second; - static constexpr double picosecond = 1.e-12 * second; - - static constexpr double hertz = 1. / second; - static constexpr double kilohertz = 1.e+3 * hertz; - static constexpr double megahertz = 1.e+6 * hertz; - - // symbols - static constexpr double ns = nanosecond; - static constexpr double s = second; - static constexpr double ms = millisecond; - static constexpr double us = microsecond; - static constexpr double ps = picosecond; - - // - // Electric charge [Q] - // - static constexpr double eplus = 1.; // positron charge - static constexpr double e_SI = 1.602176487e-19; // positron charge in coulomb - static constexpr double coulomb = eplus / e_SI; // coulomb = 6.24150 e+18 * eplus - - // - // Energy [E] - // - static constexpr double megaelectronvolt = 1.0; - static constexpr double electronvolt = 1.e-6 * megaelectronvolt; - static constexpr double kiloelectronvolt = 1.e-3 * megaelectronvolt; - static constexpr double gigaelectronvolt = 1.e+3 * megaelectronvolt; // Base unit - static constexpr double teraelectronvolt = 1.e+6 * megaelectronvolt; - static constexpr double petaelectronvolt = 1.e+9 * megaelectronvolt; - - static constexpr double joule = electronvolt / e_SI; // joule = 6.24150 e+12 * MeV - - // symbols - static constexpr double MeV = megaelectronvolt; - static constexpr double eV = electronvolt; - static constexpr double keV = kiloelectronvolt; - static constexpr double GeV = gigaelectronvolt; - static constexpr double TeV = teraelectronvolt; - static constexpr double PeV = petaelectronvolt; - - // - // Mass [E][T^2][L^-2] - // - static constexpr double kilogram = joule * second * second / (meter * meter); - static constexpr double gram = 1.e-3 * kilogram; - static constexpr double milligram = 1.e-3 * gram; - - // symbols - static constexpr double kg = kilogram; - static constexpr double g = gram; - static constexpr double mg = milligram; - - // - // Power [E][T^-1] - // - static constexpr double watt = joule / second; // watt = 6.24150 e+3 * MeV/ns - - // - // Force [E][L^-1] - // - static constexpr double newton = joule / meter; // newton = 6.24150 e+9 * MeV/mm - - // - // Pressure [E][L^-3] - // +// +// TGeo follows Geant3 convention as specified in manual +// "Unless otherwise specified, the following units are used throughout the program: +// centimeter, second, degree, GeV" + +// +// +// +static constexpr double pi = 3.14159265358979323846; +static constexpr double twopi = 2 * pi; +static constexpr double halfpi = pi / 2; +static constexpr double pi2 = pi * pi; + +// +// Length [L] +// +static constexpr double millimeter = 1.0; +static constexpr double millimeter2 = millimeter * millimeter; +static constexpr double millimeter3 = millimeter * millimeter * millimeter; + +static constexpr double centimeter = 10. * millimeter; // Base unit +static constexpr double centimeter2 = centimeter * centimeter; +static constexpr double centimeter3 = centimeter * centimeter * centimeter; + +static constexpr double meter = 1000. * millimeter; +static constexpr double meter2 = meter * meter; +static constexpr double meter3 = meter * meter * meter; + +static constexpr double kilometer = 1000. * meter; +static constexpr double kilometer2 = kilometer * kilometer; +static constexpr double kilometer3 = kilometer * kilometer * kilometer; + +static constexpr double parsec = 3.0856775807e+16 * meter; + +static constexpr double micrometer = 1.e-6 * meter; +static constexpr double nanometer = 1.e-9 * meter; +static constexpr double angstrom = 1.e-10 * meter; +static constexpr double fermi = 1.e-15 * meter; + +static constexpr double barn = 1.e-28 * meter2; +static constexpr double millibarn = 1.e-3 * barn; +static constexpr double microbarn = 1.e-6 * barn; +static constexpr double nanobarn = 1.e-9 * barn; +static constexpr double picobarn = 1.e-12 * barn; + +// symbols +static constexpr double nm = nanometer; +static constexpr double um = micrometer; + +static constexpr double mm = millimeter; +static constexpr double mm2 = millimeter2; +static constexpr double mm3 = millimeter3; + +static constexpr double cm = centimeter; +static constexpr double cm2 = centimeter2; +static constexpr double cm3 = centimeter3; + +static constexpr double liter = 1.e+3 * cm3; +static constexpr double L = liter; +static constexpr double dL = 1.e-1 * liter; +static constexpr double cL = 1.e-2 * liter; +static constexpr double mL = 1.e-3 * liter; + +static constexpr double m = meter; +static constexpr double m2 = meter2; +static constexpr double m3 = meter3; + +static constexpr double km = kilometer; +static constexpr double km2 = kilometer2; +static constexpr double km3 = kilometer3; + +static constexpr double pc = parsec; + +// +// Angle +// +static constexpr double degree = 1.0; // Base unit +static constexpr double radian = (180.0 / pi) * degree; +static constexpr double milliradian = 1.e-3 * radian; + +static constexpr double steradian = 1.; + +// symbols +static constexpr double rad = radian; +static constexpr double mrad = milliradian; +static constexpr double sr = steradian; +static constexpr double deg = degree; + +// +// Time [T] +// +static constexpr double nanosecond = 1.0; +static constexpr double second = 1.e+9 * nanosecond; // Base unit +static constexpr double millisecond = 1.e-3 * second; +static constexpr double microsecond = 1.e-6 * second; +static constexpr double picosecond = 1.e-12 * second; + +static constexpr double hertz = 1. / second; +static constexpr double kilohertz = 1.e+3 * hertz; +static constexpr double megahertz = 1.e+6 * hertz; + +// symbols +static constexpr double ns = nanosecond; +static constexpr double s = second; +static constexpr double ms = millisecond; +static constexpr double us = microsecond; +static constexpr double ps = picosecond; + +// +// Electric charge [Q] +// +static constexpr double eplus = 1.; // positron charge +static constexpr double e_SI = 1.602176487e-19; // positron charge in coulomb +static constexpr double coulomb = eplus / e_SI; // coulomb = 6.24150 e+18 * eplus + +// +// Energy [E] +// +static constexpr double megaelectronvolt = 1.0; +static constexpr double electronvolt = 1.e-6 * megaelectronvolt; +static constexpr double kiloelectronvolt = 1.e-3 * megaelectronvolt; +static constexpr double gigaelectronvolt = 1.e+3 * megaelectronvolt; // Base unit +static constexpr double teraelectronvolt = 1.e+6 * megaelectronvolt; +static constexpr double petaelectronvolt = 1.e+9 * megaelectronvolt; + +static constexpr double joule = electronvolt / e_SI; // joule = 6.24150 e+12 * MeV + +// symbols +static constexpr double MeV = megaelectronvolt; +static constexpr double eV = electronvolt; +static constexpr double keV = kiloelectronvolt; +static constexpr double GeV = gigaelectronvolt; +static constexpr double TeV = teraelectronvolt; +static constexpr double PeV = petaelectronvolt; + +// +// Mass [E][T^2][L^-2] +// +static constexpr double kilogram = joule * second * second / (meter * meter); +static constexpr double gram = 1.e-3 * kilogram; +static constexpr double milligram = 1.e-3 * gram; + +// symbols +static constexpr double kg = kilogram; +static constexpr double g = gram; +static constexpr double mg = milligram; + +// +// Power [E][T^-1] +// +static constexpr double watt = joule / second; // watt = 6.24150 e+3 * MeV/ns + +// +// Force [E][L^-1] +// +static constexpr double newton = joule / meter; // newton = 6.24150 e+9 * MeV/mm + +// +// Pressure [E][L^-3] +// #define pascal hep_pascal // a trick to avoid warnings - static constexpr double hep_pascal = newton / m2; // pascal = 6.24150 e+3 * MeV/mm3 - static constexpr double bar = 100000 * pascal; // bar = 6.24150 e+8 * MeV/mm3 - static constexpr double atmosphere = 101325 * pascal; // atm = 6.32420 e+8 * MeV/mm3 - - // - // Electric current [Q][T^-1] - // - static constexpr double ampere = coulomb / second; // ampere = 6.24150 e+9 * eplus/ns - static constexpr double milliampere = 1.e-3 * ampere; - static constexpr double microampere = 1.e-6 * ampere; - static constexpr double nanoampere = 1.e-9 * ampere; - - // - // Electric potential [E][Q^-1] - // - static constexpr double megavolt = megaelectronvolt / eplus; - static constexpr double kilovolt = 1.e-3 * megavolt; - static constexpr double volt = 1.e-6 * megavolt; - - // - // Electric resistance [E][T][Q^-2] - // - static constexpr double ohm = volt / ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) - - // - // Electric capacitance [Q^2][E^-1] - // - static constexpr double farad = coulomb / volt; // farad = 6.24150e+24 * eplus/Megavolt - static constexpr double millifarad = 1.e-3 * farad; - static constexpr double microfarad = 1.e-6 * farad; - static constexpr double nanofarad = 1.e-9 * farad; - static constexpr double picofarad = 1.e-12 * farad; - - // - // Magnetic Flux [T][E][Q^-1] - // - static constexpr double weber = volt * second; // weber = 1000*megavolt*ns - - // - // Magnetic Field [T][E][Q^-1][L^-2] - // - static constexpr double tesla = volt * second / meter2; // tesla =0.001*megavolt*ns/mm2 - - static constexpr double gauss = 1.e-4 * tesla; - static constexpr double kilogauss = 1.e-1 * tesla; - - // - // Inductance [T^2][E][Q^-2] - // - static constexpr double henry = weber / ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 - - // - // Temperature - // - static constexpr double kelvin = 1.; - - // - // Amount of substance - // - static constexpr double mole = 1.; - - // - // Activity [T^-1] - // - static constexpr double becquerel = 1. / second; - static constexpr double curie = 3.7e+10 * becquerel; - static constexpr double kilobecquerel = 1.e+3 * becquerel; - static constexpr double megabecquerel = 1.e+6 * becquerel; - static constexpr double gigabecquerel = 1.e+9 * becquerel; - static constexpr double millicurie = 1.e-3 * curie; - static constexpr double microcurie = 1.e-6 * curie; - static constexpr double Bq = becquerel; - static constexpr double kBq = kilobecquerel; - static constexpr double MBq = megabecquerel; - static constexpr double GBq = gigabecquerel; - static constexpr double Ci = curie; - static constexpr double mCi = millicurie; - static constexpr double uCi = microcurie; - - // - // Absorbed dose [L^2][T^-2] - // - static constexpr double gray = joule / kilogram; - static constexpr double kilogray = 1.e+3 * gray; - static constexpr double milligray = 1.e-3 * gray; - static constexpr double microgray = 1.e-6 * gray; - - // - // Luminous intensity [I] - // - static constexpr double candela = 1.; - - // - // Luminous flux [I] - // - static constexpr double lumen = candela * steradian; - - // - // Illuminance [I][L^-2] - // - static constexpr double lux = lumen / meter2; - - // - // Miscellaneous - // - static constexpr double perCent = 0.01; - static constexpr double perThousand = 0.001; - static constexpr double perMillion = 0.000001; -} // namespace TGeoUnit +static constexpr double hep_pascal = newton / m2; // pascal = 6.24150 e+3 * MeV/mm3 +static constexpr double bar = 100000 * pascal; // bar = 6.24150 e+8 * MeV/mm3 +static constexpr double atmosphere = 101325 * pascal; // atm = 6.32420 e+8 * MeV/mm3 + +// +// Electric current [Q][T^-1] +// +static constexpr double ampere = coulomb / second; // ampere = 6.24150 e+9 * eplus/ns +static constexpr double milliampere = 1.e-3 * ampere; +static constexpr double microampere = 1.e-6 * ampere; +static constexpr double nanoampere = 1.e-9 * ampere; + +// +// Electric potential [E][Q^-1] +// +static constexpr double megavolt = megaelectronvolt / eplus; +static constexpr double kilovolt = 1.e-3 * megavolt; +static constexpr double volt = 1.e-6 * megavolt; + +// +// Electric resistance [E][T][Q^-2] +// +static constexpr double ohm = volt / ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) + +// +// Electric capacitance [Q^2][E^-1] +// +static constexpr double farad = coulomb / volt; // farad = 6.24150e+24 * eplus/Megavolt +static constexpr double millifarad = 1.e-3 * farad; +static constexpr double microfarad = 1.e-6 * farad; +static constexpr double nanofarad = 1.e-9 * farad; +static constexpr double picofarad = 1.e-12 * farad; + +// +// Magnetic Flux [T][E][Q^-1] +// +static constexpr double weber = volt * second; // weber = 1000*megavolt*ns + +// +// Magnetic Field [T][E][Q^-1][L^-2] +// +static constexpr double tesla = volt * second / meter2; // tesla =0.001*megavolt*ns/mm2 + +static constexpr double gauss = 1.e-4 * tesla; +static constexpr double kilogauss = 1.e-1 * tesla; + +// +// Inductance [T^2][E][Q^-2] +// +static constexpr double henry = weber / ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 + +// +// Temperature +// +static constexpr double kelvin = 1.; + +// +// Amount of substance +// +static constexpr double mole = 1.; + +// +// Activity [T^-1] +// +static constexpr double becquerel = 1. / second; +static constexpr double curie = 3.7e+10 * becquerel; +static constexpr double kilobecquerel = 1.e+3 * becquerel; +static constexpr double megabecquerel = 1.e+6 * becquerel; +static constexpr double gigabecquerel = 1.e+9 * becquerel; +static constexpr double millicurie = 1.e-3 * curie; +static constexpr double microcurie = 1.e-6 * curie; +static constexpr double Bq = becquerel; +static constexpr double kBq = kilobecquerel; +static constexpr double MBq = megabecquerel; +static constexpr double GBq = gigabecquerel; +static constexpr double Ci = curie; +static constexpr double mCi = millicurie; +static constexpr double uCi = microcurie; + +// +// Absorbed dose [L^2][T^-2] +// +static constexpr double gray = joule / kilogram; +static constexpr double kilogray = 1.e+3 * gray; +static constexpr double milligray = 1.e-3 * gray; +static constexpr double microgray = 1.e-6 * gray; + +// +// Luminous intensity [I] +// +static constexpr double candela = 1.; + +// +// Luminous flux [I] +// +static constexpr double lumen = candela * steradian; + +// +// Illuminance [I][L^-2] +// +static constexpr double lux = lumen / meter2; + +// +// Miscellaneous +// +static constexpr double perCent = 0.01; +static constexpr double perThousand = 0.001; +static constexpr double perMillion = 0.000001; +} // namespace TGeant4Unit #endif /* TGEANT4_SYSTEM_OF_UNITS_H */ diff --git a/geom/geom/inc/TGeoArb8.h b/geom/geom/inc/TGeoArb8.h index 7dd02e1700415..827a477f91720 100644 --- a/geom/geom/inc/TGeoArb8.h +++ b/geom/geom/inc/TGeoArb8.h @@ -14,164 +14,167 @@ #include "TGeoBBox.h" -class TGeoArb8 : public TGeoBBox -{ +class TGeoArb8 : public TGeoBBox { protected: enum EGeoArb8Type { -// kArb8Trd1 = BIT(25), // trd1 type -// kArb8Trd2 = BIT(26), // trd2 type + // kArb8Trd1 = BIT(25), // trd1 type + // kArb8Trd2 = BIT(26), // trd2 type kArb8Trap = BIT(27), // planar surface trapezoid - kArb8Tra = BIT(28) // general twisted trapezoid + kArb8Tra = BIT(28) // general twisted trapezoid }; // data members - Double_t fDz{0}; // half length in Z - Double_t *fTwist{nullptr}; //! [4] tangents of twist angles - Double_t fXY[8][2]; // list of vertices + Double_t fDz{0}; // half length in Z + Double_t *fTwist{nullptr}; //! [4] tangents of twist angles + Double_t fXY[8][2]; // list of vertices TGeoArb8(const TGeoArb8 &) = delete; - TGeoArb8& operator=(const TGeoArb8 &) = delete; + TGeoArb8 &operator=(const TGeoArb8 &) = delete; void CopyTwist(Double_t *twist = nullptr); public: // constructors TGeoArb8(); - TGeoArb8(Double_t dz, Double_t *vertices=nullptr); - TGeoArb8(const char *name, Double_t dz, Double_t *vertices=nullptr); + TGeoArb8(Double_t dz, Double_t *vertices = nullptr); + TGeoArb8(const char *name, Double_t dz, Double_t *vertices = nullptr); // destructor - virtual ~TGeoArb8(); + ~TGeoArb8() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - void ComputeTwist(); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - Double_t DistToPlane(const Double_t *point, const Double_t *dir, Int_t ipl, Bool_t in) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual Int_t GetByteCount() const {return 100;} - Double_t GetClosestEdge(const Double_t *point, Double_t *vert, Int_t &isegment) const; - virtual Bool_t GetPointsOnFacet(Int_t /*index*/, Int_t /*npoints*/, Double_t * /*array*/) const; - Double_t GetDz() const {return fDz;} - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - static void GetPlaneNormal(Double_t *p1, Double_t *p2, Double_t *p3, Double_t *norm); - Double_t *GetVertices() {return &fXY[0][0];} - Double_t GetTwist(Int_t iseg) const; - virtual Bool_t IsCylType() const {return kFALSE;} - static Bool_t IsSamePoint(const Double_t *p1, const Double_t *p2) {return (TMath::Abs(p1[0]-p2[0])<1.E-16 && TMath::Abs(p1[1]-p2[1])<1.E-16)?kTRUE:kFALSE;} - static Bool_t InsidePolygon(Double_t x, Double_t y, Double_t *pts); - virtual void InspectShape() const; - Bool_t IsTwisted() const { return !fTwist ? kFALSE : kTRUE; } - Double_t SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetPlaneVertices(Double_t zpl, Double_t *vertices) const; - virtual void SetVertex(Int_t vnum, Double_t x, Double_t y); - virtual void SetDimensions(Double_t *param); - void SetDz(Double_t dz) {fDz = dz;} - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + void ComputeTwist(); + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistToPlane(const Double_t *point, const Double_t *dir, Int_t ipl, Bool_t in) const; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + Int_t GetByteCount() const override { return 100; } + Double_t GetClosestEdge(const Double_t *point, Double_t *vert, Int_t &isegment) const; + Bool_t GetPointsOnFacet(Int_t /*index*/, Int_t /*npoints*/, Double_t * /*array*/) const override; + Double_t GetDz() const { return fDz; } + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + static void GetPlaneNormal(Double_t *p1, Double_t *p2, Double_t *p3, Double_t *norm); + Double_t *GetVertices() { return &fXY[0][0]; } + Double_t GetTwist(Int_t iseg) const; + Bool_t IsCylType() const override { return kFALSE; } + static Bool_t IsSamePoint(const Double_t *p1, const Double_t *p2) + { + return (TMath::Abs(p1[0] - p2[0]) < 1.E-16 && TMath::Abs(p1[1] - p2[1]) < 1.E-16) ? kTRUE : kFALSE; + } + static Bool_t InsidePolygon(Double_t x, Double_t y, Double_t *pts); + void InspectShape() const override; + Bool_t IsTwisted() const { return !fTwist ? kFALSE : kTRUE; } + Double_t SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) const; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetPlaneVertices(Double_t zpl, Double_t *vertices) const; + virtual void SetVertex(Int_t vnum, Double_t x, Double_t y); + void SetDimensions(Double_t *param) override; + void SetDz(Double_t dz) { fDz = dz; } + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void Sizeof3D() const override; - ClassDef(TGeoArb8, 1) // arbitrary trapezoid with 8 vertices + ClassDefOverride(TGeoArb8, 1) // arbitrary trapezoid with 8 vertices }; -class TGeoTrap : public TGeoArb8 -{ +class TGeoTrap : public TGeoArb8 { protected: // data members - Double_t fTheta; // theta angle - Double_t fPhi; // phi angle - Double_t fH1; // half length in y at low z - Double_t fBl1; // half length in x at low z and y low edge - Double_t fTl1; // half length in x at low z and y high edge - Double_t fAlpha1;// angle between centers of x edges an y axis at low z - Double_t fH2; // half length in y at high z - Double_t fBl2; // half length in x at high z and y low edge - Double_t fTl2; // half length in x at high z and y high edge - Double_t fAlpha2;// angle between centers of x edges an y axis at low z + Double_t fTheta; // theta angle + Double_t fPhi; // phi angle + Double_t fH1; // half length in y at low z + Double_t fBl1; // half length in x at low z and y low edge + Double_t fTl1; // half length in x at low z and y high edge + Double_t fAlpha1; // angle between centers of x edges an y axis at low z + Double_t fH2; // half length in y at high z + Double_t fBl2; // half length in x at high z and y low edge + Double_t fTl2; // half length in x at high z and y high edge + Double_t fAlpha2; // angle between centers of x edges an y axis at low z public: // constructors TGeoTrap(); TGeoTrap(Double_t dz, Double_t theta, Double_t phi); - TGeoTrap(Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoTrap(const char *name, Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); + TGeoTrap(Double_t dz, Double_t theta, Double_t phi, Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, + Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2); + TGeoTrap(const char *name, Double_t dz, Double_t theta, Double_t phi, Double_t h1, Double_t bl1, Double_t tl1, + Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2); // destructor - virtual ~TGeoTrap(); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - Double_t GetTheta() const {return fTheta;} - Double_t GetPhi() const {return fPhi;} - Double_t GetH1() const {return fH1;} - Double_t GetBl1() const {return fBl1;} - Double_t GetTl1() const {return fTl1;} - Double_t GetAlpha1() const {return fAlpha1;} - Double_t GetH2() const {return fH2;} - Double_t GetBl2() const {return fBl2;} - Double_t GetTl2() const {return fTl2;} - Double_t GetAlpha2() const {return fAlpha2;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void SetDimensions(Double_t *param); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); + ~TGeoTrap() override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetTheta() const { return fTheta; } + Double_t GetPhi() const { return fPhi; } + Double_t GetH1() const { return fH1; } + Double_t GetBl1() const { return fBl1; } + Double_t GetTl1() const { return fTl1; } + Double_t GetAlpha1() const { return fAlpha1; } + Double_t GetH2() const { return fH2; } + Double_t GetBl2() const { return fBl2; } + Double_t GetTl2() const { return fTl2; } + Double_t GetAlpha2() const { return fAlpha2; } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void SetDimensions(Double_t *param) override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; - ClassDef(TGeoTrap, 1) // G3 TRAP shape + ClassDefOverride(TGeoTrap, 1) // G3 TRAP shape }; -class TGeoGtra : public TGeoTrap -{ +class TGeoGtra : public TGeoTrap { protected: // data members - Double_t fTwistAngle; // twist angle in degrees + Double_t fTwistAngle; // twist angle in degrees public: // constructors TGeoGtra(); - TGeoGtra(Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoGtra(const char *name, Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); + TGeoGtra(Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, Double_t bl1, Double_t tl1, + Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2); + TGeoGtra(const char *name, Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, Double_t bl1, + Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2); // destructor - virtual ~TGeoGtra(); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - Double_t GetTwistAngle() const {return fTwistAngle;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SetDimensions(Double_t *param); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); + ~TGeoGtra() override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + Double_t GetTwistAngle() const { return fTwistAngle; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SetDimensions(Double_t *param) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; - ClassDef(TGeoGtra, 1) // G3 GTRA shape + ClassDefOverride(TGeoGtra, 1) // G3 GTRA shape }; #endif diff --git a/geom/geom/inc/TGeoAtt.h b/geom/geom/inc/TGeoAtt.h index 9d7029e98c6fb..60fa5188d1e1f 100644 --- a/geom/geom/inc/TGeoAtt.h +++ b/geom/geom/inc/TGeoAtt.h @@ -14,89 +14,83 @@ #include "Rtypes.h" -class TGeoAtt -{ +class TGeoAtt { public: - enum { - kBitMask = 0x00ffffff // bit mask + enum { + kBitMask = 0x00ffffff // bit mask }; enum EGeoVisibilityAtt { - kVisOverride = BIT(0), // volume's vis. attributes are overridden - kVisNone = BIT(1), // the volume/node is invisible, as well as daughters - kVisThis = BIT(2), // this volume/node is visible - kVisDaughters = BIT(3), // all leaves are visible - kVisOneLevel = BIT(4), // first level daughters are visible - kVisStreamed = BIT(5), // true if attributes have been streamed - kVisTouched = BIT(6), // true if attributes are changed after closing geom - kVisOnScreen = BIT(7), // true if volume is visible on screen - kVisContainers = BIT(12), // all containers visible - kVisOnly = BIT(13), // just this visible - kVisBranch = BIT(14), // only a given branch visible - kVisRaytrace = BIT(15) // raytracing flag - }; // visibility attributes + kVisOverride = BIT(0), // volume's vis. attributes are overridden + kVisNone = BIT(1), // the volume/node is invisible, as well as daughters + kVisThis = BIT(2), // this volume/node is visible + kVisDaughters = BIT(3), // all leaves are visible + kVisOneLevel = BIT(4), // first level daughters are visible + kVisStreamed = BIT(5), // true if attributes have been streamed + kVisTouched = BIT(6), // true if attributes are changed after closing geom + kVisOnScreen = BIT(7), // true if volume is visible on screen + kVisContainers = BIT(12), // all containers visible + kVisOnly = BIT(13), // just this visible + kVisBranch = BIT(14), // only a given branch visible + kVisRaytrace = BIT(15) // raytracing flag + }; // visibility attributes - enum EGeoActivityAtt { - kActOverride = BIT(8), // volume's activity attributes are overridden - kActNone = BIT(9), // the volume/node is ignored by tracking, as well as daughters - kActThis = BIT(10), // this volume/node is active for tracking - kActDaughters = BIT(11) // all leaves are active - }; // activity flags + enum EGeoActivityAtt { + kActOverride = BIT(8), // volume's activity attributes are overridden + kActNone = BIT(9), // the volume/node is ignored by tracking, as well as daughters + kActThis = BIT(10), // this volume/node is active for tracking + kActDaughters = BIT(11) // all leaves are active + }; // activity flags enum EGeoOptimizationAtt { - kUseBoundingBox = BIT(16), // use bounding box for tracking - kUseVoxels = BIT(17), // compute and use voxels - kUseGsord = BIT(18) // use slicing in G3 style - }; // tracking optimization attributes - enum EGeoSavePrimitiveAtt { - kSavePrimitiveAtt = BIT(19), - kSaveNodesAtt = BIT(20) - }; // save primitive bits -protected : -// data members - UInt_t fGeoAtt; // option flags + kUseBoundingBox = BIT(16), // use bounding box for tracking + kUseVoxels = BIT(17), // compute and use voxels + kUseGsord = BIT(18) // use slicing in G3 style + }; // tracking optimization attributes + enum EGeoSavePrimitiveAtt { kSavePrimitiveAtt = BIT(19), kSaveNodesAtt = BIT(20) }; // save primitive bits +protected: + // data members + UInt_t fGeoAtt; // option flags public: // constructors TGeoAtt(); - TGeoAtt(Option_t *vis_opt, Option_t *activity_opt="", Option_t *optimization_opt=""); + TGeoAtt(Option_t *vis_opt, Option_t *activity_opt = "", Option_t *optimization_opt = ""); // destructor virtual ~TGeoAtt(); // methods - void SetAttBit(UInt_t f) {fGeoAtt |= f & kBitMask;} - void SetAttBit(UInt_t f, Bool_t set) {(set)?SetAttBit(f):ResetAttBit(f);}; - void ResetAttBit(UInt_t f) {fGeoAtt &= ~(f & kBitMask);} - Bool_t TestAttBit(UInt_t f) const {return (Bool_t)((fGeoAtt & f) != 0);} + void SetAttBit(UInt_t f) { fGeoAtt |= f & kBitMask; } + void SetAttBit(UInt_t f, Bool_t set) { (set) ? SetAttBit(f) : ResetAttBit(f); }; + void ResetAttBit(UInt_t f) { fGeoAtt &= ~(f & kBitMask); } + Bool_t TestAttBit(UInt_t f) const { return (Bool_t)((fGeoAtt & f) != 0); } - void SetVisRaytrace(Bool_t flag=kTRUE) {SetAttBit(kVisRaytrace, flag);} - void SetVisBranch(); - virtual void SetVisContainers(Bool_t flag=kTRUE); - virtual void SetVisLeaves(Bool_t flag=kTRUE); - virtual void SetVisOnly(Bool_t flag=kTRUE); - virtual void SetVisibility(Bool_t vis=kTRUE); - void SetVisDaughters(Bool_t vis=kTRUE); - void SetVisStreamed(Bool_t vis=kTRUE); - void SetVisTouched(Bool_t vis=kTRUE); - void SetActivity(Bool_t flag=kTRUE) {SetAttBit(kActThis, flag);} - void SetActiveDaughters(Bool_t flag=kTRUE) {SetAttBit(kActDaughters,flag);} + void SetVisRaytrace(Bool_t flag = kTRUE) { SetAttBit(kVisRaytrace, flag); } + void SetVisBranch(); + virtual void SetVisContainers(Bool_t flag = kTRUE); + virtual void SetVisLeaves(Bool_t flag = kTRUE); + virtual void SetVisOnly(Bool_t flag = kTRUE); + virtual void SetVisibility(Bool_t vis = kTRUE); + void SetVisDaughters(Bool_t vis = kTRUE); + void SetVisStreamed(Bool_t vis = kTRUE); + void SetVisTouched(Bool_t vis = kTRUE); + void SetActivity(Bool_t flag = kTRUE) { SetAttBit(kActThis, flag); } + void SetActiveDaughters(Bool_t flag = kTRUE) { SetAttBit(kActDaughters, flag); } - void SetOptimization(Option_t *option); + void SetOptimization(Option_t *option); + Bool_t IsActive() const { return TestAttBit(kActThis); } + Bool_t IsActiveDaughters() const { return TestAttBit(kActDaughters); } + Bool_t IsVisRaytrace() const { return TestAttBit(kVisRaytrace); } + Bool_t IsVisible() const { return TestAttBit(kVisThis); } + Bool_t IsVisDaughters() const { return TestAttBit(kVisDaughters); } + Bool_t IsVisBranch() const { return TestAttBit(kVisBranch); } + Bool_t IsVisContainers() const { return TestAttBit(kVisContainers); } + Bool_t IsVisLeaves() const { return !TestAttBit(kVisContainers | kVisOnly | kVisBranch); } + Bool_t IsVisOnly() const { return TestAttBit(kVisOnly); } - Bool_t IsActive() const {return TestAttBit(kActThis);} - Bool_t IsActiveDaughters() const {return TestAttBit(kActDaughters);} - Bool_t IsVisRaytrace() const {return TestAttBit(kVisRaytrace);} - Bool_t IsVisible() const {return TestAttBit(kVisThis);} - Bool_t IsVisDaughters() const {return TestAttBit(kVisDaughters);} - Bool_t IsVisBranch() const {return TestAttBit(kVisBranch);} - Bool_t IsVisContainers() const {return TestAttBit(kVisContainers);} - Bool_t IsVisLeaves() const {return !TestAttBit(kVisContainers | kVisOnly | kVisBranch);} - Bool_t IsVisOnly() const {return TestAttBit(kVisOnly);} + Bool_t IsVisStreamed() const { return TestAttBit(kVisStreamed); } + Bool_t IsVisTouched() const { return TestAttBit(kVisTouched); } - Bool_t IsVisStreamed() const {return TestAttBit(kVisStreamed);} - Bool_t IsVisTouched() const {return TestAttBit(kVisTouched);} - - ClassDef(TGeoAtt, 1) // class for visibility, activity and optimization attributes for volumes/nodes + ClassDef(TGeoAtt, 1) // class for visibility, activity and optimization attributes for volumes/nodes }; #endif - diff --git a/geom/geom/inc/TGeoBBox.h b/geom/geom/inc/TGeoBBox.h index 366024626615f..88779a308d493 100644 --- a/geom/geom/inc/TGeoBBox.h +++ b/geom/geom/inc/TGeoBBox.h @@ -14,84 +14,87 @@ #include "TGeoShape.h" -class TGeoBBox : public TGeoShape -{ -protected : -// data members - Double_t fDX; // X half-length - Double_t fDY; // Y half-length - Double_t fDZ; // Z half-length - Double_t fOrigin[3]; // box origin -// methods - virtual void FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t localFrame) const; +class TGeoBBox : public TGeoShape { +protected: + // data members + Double_t fDX; // X half-length + Double_t fDY; // Y half-length + Double_t fDZ; // Z half-length + Double_t fOrigin[3]; // box origin + // methods + void FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const override; - TGeoBBox(const TGeoBBox&) = delete; - TGeoBBox& operator=(const TGeoBBox&) = delete; + TGeoBBox(const TGeoBBox &) = delete; + TGeoBBox &operator=(const TGeoBBox &) = delete; public: // constructors TGeoBBox(); - TGeoBBox(Double_t dx, Double_t dy, Double_t dz, Double_t *origin=nullptr); - TGeoBBox(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t *origin=nullptr); + TGeoBBox(Double_t dx, Double_t dy, Double_t dz, Double_t *origin = nullptr); + TGeoBBox(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t *origin = nullptr); TGeoBBox(Double_t *param); // destructor - virtual ~TGeoBBox(); + ~TGeoBBox() override; // methods - static Bool_t AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, const TGeoBBox *box2, const TGeoMatrix *mat2); - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - static Bool_t Contains(const Double_t *point, Double_t dx, Double_t dy, Double_t dz, const Double_t *origin); - virtual Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromInside(const Double_t *point,const Double_t *dir, - Double_t dx, Double_t dy, Double_t dz, const Double_t *origin, Double_t stepmax=TGeoShape::Big()); - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromOutside(const Double_t *point,const Double_t *dir, - Double_t dx, Double_t dy, Double_t dz, const Double_t *origin, Double_t stepmax=TGeoShape::Big()); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 36;} - virtual Double_t GetFacetArea(Int_t index=0) const; - virtual Bool_t GetPointsOnFacet(Int_t index, Int_t npoints, Double_t *array) const; - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const {return 8;} - virtual Double_t GetDX() const {return fDX;} - virtual Double_t GetDY() const {return fDY;} - virtual Double_t GetDZ() const {return fDZ;} - virtual const Double_t *GetOrigin() const {return fOrigin;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - virtual Bool_t IsValidBox() const {return ((fDX<0)||(fDY<0)||(fDZ<0))?kFALSE:kTRUE;} - virtual Bool_t IsNullBox() const {return ((fDX<1.E-16)&&(fDY<1.E-16)&&(fDZ<1.E-16))?kTRUE:kFALSE;} - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetBoxDimensions(Double_t dx, Double_t dy, Double_t dz, Double_t *origin=nullptr); - virtual void SetDimensions(Double_t *param); - void SetBoxPoints(Double_t *points) const; - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buffer) const; - virtual void Sizeof3D() const; + static Bool_t + AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, const TGeoBBox *box2, const TGeoMatrix *mat2); + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + static Bool_t Contains(const Double_t *point, Double_t dx, Double_t dy, Double_t dz, const Double_t *origin); + Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t DistFromInside(const Double_t *point, const Double_t *dir, Double_t dx, Double_t dy, Double_t dz, + const Double_t *origin, Double_t stepmax = TGeoShape::Big()); + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Double_t dx, Double_t dy, Double_t dz, + const Double_t *origin, Double_t stepmax = TGeoShape::Big()); + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 36; } + virtual Double_t GetFacetArea(Int_t index = 0) const; + virtual Bool_t GetPointsOnFacet(Int_t index, Int_t npoints, Double_t *array) const; + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override { return 8; } + virtual Double_t GetDX() const { return fDX; } + virtual Double_t GetDY() const { return fDY; } + virtual Double_t GetDZ() const { return fDZ; } + virtual const Double_t *GetOrigin() const { return fOrigin; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Bool_t IsValidBox() const override { return ((fDX < 0) || (fDY < 0) || (fDZ < 0)) ? kFALSE : kTRUE; } + virtual Bool_t IsNullBox() const { return ((fDX < 1.E-16) && (fDY < 1.E-16) && (fDZ < 1.E-16)) ? kTRUE : kFALSE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetBoxDimensions(Double_t dx, Double_t dy, Double_t dz, Double_t *origin = nullptr); + void SetDimensions(Double_t *param) override; + void SetBoxPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buffer) const override; + void Sizeof3D() const override; - ClassDef(TGeoBBox, 1) // box primitive + ClassDefOverride(TGeoBBox, 1) // box primitive }; #endif diff --git a/geom/geom/inc/TGeoBoolNode.h b/geom/geom/inc/TGeoBoolNode.h index 72670a5d09b9b..484f6f8846d86 100644 --- a/geom/geom/inc/TGeoBoolNode.h +++ b/geom/geom/inc/TGeoBoolNode.h @@ -22,42 +22,37 @@ class TGeoShape; class TGeoMatrix; class TGeoHMatrix; -class TGeoBoolNode : public TObject -{ +class TGeoBoolNode : public TObject { public: -enum EGeoBoolType { - kGeoUnion, - kGeoIntersection, - kGeoSubtraction -}; - struct ThreadData_t - { - Int_t fSelected; // ! selected branch + enum EGeoBoolType { kGeoUnion, kGeoIntersection, kGeoSubtraction }; + struct ThreadData_t { + Int_t fSelected; // ! selected branch ThreadData_t(); ~ThreadData_t(); }; - ThreadData_t& GetThreadData() const; - void ClearThreadData() const; - void CreateThreadData(Int_t nthreads); + ThreadData_t &GetThreadData() const; + void ClearThreadData() const; + void CreateThreadData(Int_t nthreads); + private: - TGeoBoolNode(const TGeoBoolNode&) = delete; - TGeoBoolNode& operator=(const TGeoBoolNode&) = delete; + TGeoBoolNode(const TGeoBoolNode &) = delete; + TGeoBoolNode &operator=(const TGeoBoolNode &) = delete; protected: - TGeoShape *fLeft{nullptr}; // shape on the left branch - TGeoShape *fRight{nullptr}; // shape on the right branch - TGeoMatrix *fLeftMat{nullptr}; // transformation that applies to the left branch - TGeoMatrix *fRightMat{nullptr}; // transformation that applies to the right branch - Int_t fNpoints{0}; //! number of points on the mesh - Double_t *fPoints{nullptr}; //! array of mesh points - - mutable std::vector fThreadData; //! Navigation data per thread - mutable Int_t fThreadSize{0}; //! Size for the navigation data array - mutable std::mutex fMutex; //! Mutex for thread data access -// methods - Bool_t MakeBranch(const char *expr, Bool_t left); - void AssignPoints(Int_t npoints, Double_t *points); + TGeoShape *fLeft{nullptr}; // shape on the left branch + TGeoShape *fRight{nullptr}; // shape on the right branch + TGeoMatrix *fLeftMat{nullptr}; // transformation that applies to the left branch + TGeoMatrix *fRightMat{nullptr}; // transformation that applies to the right branch + Int_t fNpoints{0}; //! number of points on the mesh + Double_t *fPoints{nullptr}; //! array of mesh points + + mutable std::vector fThreadData; //! Navigation data per thread + mutable Int_t fThreadSize{0}; //! Size for the navigation data array + mutable std::mutex fMutex; //! Mutex for thread data access + // methods + Bool_t MakeBranch(const char *expr, Bool_t left); + void AssignPoints(Int_t npoints, Double_t *points); public: // constructors @@ -66,34 +61,34 @@ enum EGeoBoolType { TGeoBoolNode(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat = nullptr, TGeoMatrix *rmat = nullptr); // destructor - virtual ~TGeoBoolNode(); + ~TGeoBoolNode() override; // methods - virtual void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) = 0; - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) = 0; - virtual Bool_t Contains(const Double_t *point) const = 0; - virtual Int_t DistanceToPrimitive(Int_t px, Int_t py) = 0; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=0, Double_t *safe=nullptr) const = 0; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=0, Double_t *safe=nullptr) const = 0; + virtual void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) = 0; + virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) = 0; + virtual Bool_t Contains(const Double_t *point) const = 0; + virtual Int_t DistanceToPrimitive(Int_t px, Int_t py) = 0; + virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const = 0; + virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const = 0; virtual EGeoBoolType GetBooleanOperator() const = 0; - virtual Int_t GetNpoints() = 0; - TGeoMatrix *GetLeftMatrix() const {return fLeftMat;} - TGeoMatrix *GetRightMatrix() const {return fRightMat;} - TGeoShape *GetLeftShape() const {return fLeft;} - TGeoShape *GetRightShape() const {return fRight;} + virtual Int_t GetNpoints() = 0; + TGeoMatrix *GetLeftMatrix() const { return fLeftMat; } + TGeoMatrix *GetRightMatrix() const { return fRightMat; } + TGeoShape *GetLeftShape() const { return fLeft; } + TGeoShape *GetRightShape() const { return fRight; } virtual TGeoBoolNode *MakeClone() const = 0; - void Paint(Option_t *option) override; - void RegisterMatrices(); - Bool_t ReplaceMatrix(TGeoMatrix *mat, TGeoMatrix *newmat); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const = 0; - void SavePrimitive(std::ostream &out, Option_t *option = "") override; - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - void SetSelected(Int_t sel); - virtual void Sizeof3D() const; - - ClassDefOverride(TGeoBoolNode, 1) // a boolean node + void Paint(Option_t *option) override; + void RegisterMatrices(); + Bool_t ReplaceMatrix(TGeoMatrix *mat, TGeoMatrix *newmat); + virtual Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const = 0; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + virtual void SetPoints(Double_t *points) const; + virtual void SetPoints(Float_t *points) const; + void SetSelected(Int_t sel); + virtual void Sizeof3D() const; + + ClassDefOverride(TGeoBoolNode, 1) // a boolean node }; ////////////////////////////////////////////////////////////////////////////// @@ -102,8 +97,7 @@ enum EGeoBoolType { // // ////////////////////////////////////////////////////////////////////////////// -class TGeoUnion : public TGeoBoolNode -{ +class TGeoUnion : public TGeoBoolNode { public: // constructors TGeoUnion(); @@ -111,27 +105,27 @@ class TGeoUnion : public TGeoBoolNode TGeoUnion(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat = nullptr, TGeoMatrix *rmat = nullptr); // destructor - virtual ~TGeoUnion(); + ~TGeoUnion() override; // methods - void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; - void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; - Bool_t Contains(const Double_t *point) const override; - Int_t DistanceToPrimitive(Int_t px, Int_t py) override; - Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe = nullptr) const override; - Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe=nullptr) const override; - EGeoBoolType GetBooleanOperator() const override {return kGeoUnion;} - Int_t GetNpoints() override; - Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const override; - void SavePrimitive(std::ostream &out, Option_t *option = "") override; - void Sizeof3D() const override; - - //CS specific + void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + Bool_t Contains(const Double_t *point) const override; + Int_t DistanceToPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; + EGeoBoolType GetBooleanOperator() const override { return kGeoUnion; } + Int_t GetNpoints() override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void Sizeof3D() const override; + + // CS specific TGeoBoolNode *MakeClone() const override; - void Paint(Option_t *option) override; + void Paint(Option_t *option) override; - ClassDefOverride(TGeoUnion, 1) // union node + ClassDefOverride(TGeoUnion, 1) // union node }; ////////////////////////////////////////////////////////////////////////////// @@ -141,8 +135,7 @@ class TGeoUnion : public TGeoBoolNode // // ////////////////////////////////////////////////////////////////////////////// -class TGeoIntersection : public TGeoBoolNode -{ +class TGeoIntersection : public TGeoBoolNode { public: // constructors TGeoIntersection(); @@ -150,27 +143,27 @@ class TGeoIntersection : public TGeoBoolNode TGeoIntersection(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat = nullptr, TGeoMatrix *rmat = nullptr); // destructor - virtual ~TGeoIntersection(); + ~TGeoIntersection() override; // methods - void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; - void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; - Bool_t Contains(const Double_t *point) const override; - Int_t DistanceToPrimitive(Int_t px, Int_t py) override; - Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe = nullptr) const override; - Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe = nullptr) const override; + void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + Bool_t Contains(const Double_t *point) const override; + Int_t DistanceToPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; EGeoBoolType GetBooleanOperator() const override { return kGeoIntersection; } - Int_t GetNpoints() override; - Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const override; - void SavePrimitive(std::ostream &out, Option_t *option = "") override; - void Sizeof3D() const override; + Int_t GetNpoints() override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void Sizeof3D() const override; - //CS specific + // CS specific TGeoBoolNode *MakeClone() const override; - void Paint(Option_t *option) override; + void Paint(Option_t *option) override; - ClassDefOverride(TGeoIntersection, 1) // intersection node + ClassDefOverride(TGeoIntersection, 1) // intersection node }; ////////////////////////////////////////////////////////////////////////////// @@ -179,8 +172,7 @@ class TGeoIntersection : public TGeoBoolNode // // ////////////////////////////////////////////////////////////////////////////// -class TGeoSubtraction : public TGeoBoolNode -{ +class TGeoSubtraction : public TGeoBoolNode { public: // constructors TGeoSubtraction(); @@ -188,27 +180,27 @@ class TGeoSubtraction : public TGeoBoolNode TGeoSubtraction(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat = nullptr, TGeoMatrix *rmat = nullptr); // destructor - virtual ~TGeoSubtraction(); + ~TGeoSubtraction() override; // methods - void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; - void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; - Bool_t Contains(const Double_t *point) const override; - Int_t DistanceToPrimitive(Int_t px, Int_t py) override; - Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe = nullptr) const override; - Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step = 0, Double_t *safe = nullptr) const override; + void ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + Bool_t Contains(const Double_t *point) const override; + Int_t DistanceToPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = 0, + Double_t *safe = nullptr) const override; EGeoBoolType GetBooleanOperator() const override { return kGeoSubtraction; } - Int_t GetNpoints() override; - Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const override; - void SavePrimitive(std::ostream &out, Option_t *option = "") override; - void Sizeof3D() const override; + Int_t GetNpoints() override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void Sizeof3D() const override; - //CS specific + // CS specific TGeoBoolNode *MakeClone() const override; - void Paint(Option_t *option) override; + void Paint(Option_t *option) override; - ClassDefOverride(TGeoSubtraction, 1) // subtraction node + ClassDefOverride(TGeoSubtraction, 1) // subtraction node }; #endif diff --git a/geom/geom/inc/TGeoBranchArray.h b/geom/geom/inc/TGeoBranchArray.h index 5bf16828ff99f..1777bc7656edd 100644 --- a/geom/geom/inc/TGeoBranchArray.h +++ b/geom/geom/inc/TGeoBranchArray.h @@ -19,25 +19,27 @@ class TGeoNavigator; class TGeoNode; -class TGeoBranchArray : public TObject -{ +class TGeoBranchArray : public TObject { protected: - Int_t fLevel; // Branch depth - Int_t fMaxLevel; // Array length - TGeoHMatrix fMatrix; // Global matrix (owned) - TGeoNode **fArray; //![fMaxLevel+1] Array of nodes - TGeoNode *fRealArray[1]; // Beginning address of the array of nodes + Int_t fLevel; // Branch depth + Int_t fMaxLevel; // Array length + TGeoHMatrix fMatrix; // Global matrix (owned) + TGeoNode **fArray; //![fMaxLevel+1] Array of nodes + TGeoNode *fRealArray[1]; // Beginning address of the array of nodes private: - TGeoBranchArray(Int_t level); // not allowed - TGeoBranchArray(const TGeoBranchArray&); // not allowed + TGeoBranchArray(Int_t level); // not allowed + TGeoBranchArray(const TGeoBranchArray &); // not allowed public: enum EGeoBATypes { - kBASelfAlloc = BIT(14) // does self allocation or not + kBASelfAlloc = BIT(14) // does self allocation or not }; // This replaces the dummy constructor to make sure that I/O can be // performed while the user is only allowed to use the static maker - TGeoBranchArray(TRootIOCtor*) : TObject(), fLevel(0), fMaxLevel(0), fMatrix(), fArray(nullptr) { fRealArray[0] = nullptr; } + TGeoBranchArray(TRootIOCtor *) : TObject(), fLevel(0), fMaxLevel(0), fMatrix(), fArray(nullptr) + { + fRealArray[0] = nullptr; + } // The static maker to be use to create an instance of the branch array static TGeoBranchArray *MakeInstance(size_t maxlevel); @@ -52,78 +54,77 @@ class TGeoBranchArray : public TObject static TGeoBranchArray *MakeCopyAt(const TGeoBranchArray &other, void *addr); // The equivalent of the destructor - static void ReleaseInstance(TGeoBranchArray *obj); + static void ReleaseInstance(TGeoBranchArray *obj); // Assignment allowed - TGeoBranchArray& operator=(const TGeoBranchArray&); + TGeoBranchArray &operator=(const TGeoBranchArray &); // Fast copy based on memcpy to destination array - void CopyTo(TGeoBranchArray *dest); + void CopyTo(TGeoBranchArray *dest); // Equivalent of sizeof function - static size_t SizeOf(size_t maxlevel) - { return (sizeof(TGeoBranchArray)+sizeof(TGeoBranchArray*)*(maxlevel)); } + static size_t SizeOf(size_t maxlevel) { return (sizeof(TGeoBranchArray) + sizeof(TGeoBranchArray *) * (maxlevel)); } // Equivalent of sizeof function static size_t SizeOfInstance(size_t maxlevel) - { return (sizeof(TGeoBranchArray)+sizeof(TGeoBranchArray*)*(maxlevel)); } + { + return (sizeof(TGeoBranchArray) + sizeof(TGeoBranchArray *) * (maxlevel)); + } - inline size_t SizeOf() const - { return (sizeof(TGeoBranchArray)+sizeof(TGeoBranchArray*)*(fMaxLevel)); } + inline size_t SizeOf() const { return (sizeof(TGeoBranchArray) + sizeof(TGeoBranchArray *) * (fMaxLevel)); } // The data start should point to the address of the first data member, // after the virtual table - void *DataStart() const {return (void*)&fLevel;} + void *DataStart() const { return (void *)&fLevel; } // The actual size of the data for an instance, excluding the virtual table - size_t DataSize() const {return SizeOf()-size_t(&fLevel)+(size_t)this;} + size_t DataSize() const { return SizeOf() - size_t(&fLevel) + (size_t)this; } // Update the internal addresses of n contiguous branch array objects, starting // with this one void UpdateArray(size_t nobj); // Destructor. Release instance to be called instead - virtual ~TGeoBranchArray() {} - - Bool_t operator ==(const TGeoBranchArray& other) const; - Bool_t operator !=(const TGeoBranchArray& other) const; - Bool_t operator >(const TGeoBranchArray& other) const; - Bool_t operator <(const TGeoBranchArray& other) const; - Bool_t operator >=(const TGeoBranchArray& other) const; - Bool_t operator <=(const TGeoBranchArray& other) const; - - void AddLevel(Int_t dindex); - static Long64_t BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value); - virtual Int_t Compare(const TObject *obj) const; - void CleanMatrix(); - TGeoNode **GetArray() const {return fArray;} - size_t GetLevel() const {return fLevel;} - size_t GetMaxLevel() const {return fMaxLevel;} - const TGeoHMatrix - *GetMatrix() const {return &fMatrix;} - TGeoNode *GetNode(Int_t level) const {return fArray[level];} - TGeoNode *GetCurrentNode() const {return fArray[fLevel];} - void GetPath(TString &path) const; - void Init(TGeoNode **branch, TGeoMatrix *global, Int_t level); - void InitFromNavigator(TGeoNavigator *nav); - virtual Bool_t IsSortable() const {return kTRUE;} - Bool_t IsOutside() const {return (fLevel<0)?kTRUE:kFALSE;} - virtual void Print(Option_t *option="") const; - static void Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down=kTRUE); - void UpdateNavigator(TGeoNavigator *nav) const; - - ClassDef(TGeoBranchArray, 4) + ~TGeoBranchArray() override {} + + Bool_t operator==(const TGeoBranchArray &other) const; + Bool_t operator!=(const TGeoBranchArray &other) const; + Bool_t operator>(const TGeoBranchArray &other) const; + Bool_t operator<(const TGeoBranchArray &other) const; + Bool_t operator>=(const TGeoBranchArray &other) const; + Bool_t operator<=(const TGeoBranchArray &other) const; + + void AddLevel(Int_t dindex); + static Long64_t BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value); + Int_t Compare(const TObject *obj) const override; + void CleanMatrix(); + TGeoNode **GetArray() const { return fArray; } + size_t GetLevel() const { return fLevel; } + size_t GetMaxLevel() const { return fMaxLevel; } + const TGeoHMatrix *GetMatrix() const { return &fMatrix; } + TGeoNode *GetNode(Int_t level) const { return fArray[level]; } + TGeoNode *GetCurrentNode() const { return fArray[fLevel]; } + void GetPath(TString &path) const; + void Init(TGeoNode **branch, TGeoMatrix *global, Int_t level); + void InitFromNavigator(TGeoNavigator *nav); + Bool_t IsSortable() const override { return kTRUE; } + Bool_t IsOutside() const { return (fLevel < 0) ? kTRUE : kFALSE; } + void Print(Option_t *option = "") const override; + static void Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down = kTRUE); + void UpdateNavigator(TGeoNavigator *nav) const; + + ClassDefOverride(TGeoBranchArray, 4) }; struct compareBAasc { compareBAasc(TGeoBranchArray **d) : fData(d) {} - bool operator ()(Int_t i1, Int_t i2) {return **(fData+i1) < **(fData+i2);} + bool operator()(Int_t i1, Int_t i2) { return **(fData + i1) < **(fData + i2); } TGeoBranchArray **fData; }; struct compareBAdesc { compareBAdesc(TGeoBranchArray **d) : fData(d) {} - bool operator ()(Int_t i1, Int_t i2) {return **(fData+i1) > **(fData+i2);} + bool operator()(Int_t i1, Int_t i2) { return **(fData + i1) > **(fData + i2); } TGeoBranchArray **fData; }; diff --git a/geom/geom/inc/TGeoBuilder.h b/geom/geom/inc/TGeoBuilder.h index e4ca71a917952..049e5412bbb24 100644 --- a/geom/geom/inc/TGeoBuilder.h +++ b/geom/geom/inc/TGeoBuilder.h @@ -23,114 +23,86 @@ class TGeoVolumeAssembly; class TGeoVolumeMulti; class TGeoManager; -class TGeoBuilder : public TObject -{ +class TGeoBuilder : public TObject { protected: - static TGeoBuilder *fgInstance; //! static pointer to singleton + static TGeoBuilder *fgInstance; //! static pointer to singleton TGeoBuilder(); - TGeoBuilder(const TGeoBuilder&) = delete; - TGeoBuilder& operator=(const TGeoBuilder&) = delete; - -private : - TGeoManager *fGeometry; //! current geometry - - void SetGeometry(TGeoManager *geom) {fGeometry = geom;} - -public : - virtual ~TGeoBuilder(); - - static TGeoBuilder *Instance(TGeoManager *geom); - - Int_t AddMaterial(TGeoMaterial *material); - Int_t AddTransformation(TGeoMatrix *matrix); - Int_t AddShape(TGeoShape *shape); - void RegisterMatrix(TGeoMatrix *matrix); - - TGeoVolume *MakeArb8(const char *name, TGeoMedium *medium, - Double_t dz, Double_t *vertices=nullptr); - TGeoVolume *MakeBox(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz); - TGeoVolume *MakeCone(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2); - TGeoVolume *MakeCons(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, - Double_t phi1, Double_t phi2); - TGeoVolume *MakeCtub(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); - TGeoVolume *MakeEltu(const char *name, TGeoMedium *medium, - Double_t a, Double_t b, Double_t dz); - TGeoVolume *MakeGtra(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoVolume *MakePara(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz, - Double_t alpha, Double_t theta, Double_t phi); - TGeoVolume *MakePcon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nz); - TGeoVolume *MakeParaboloid(const char *name, TGeoMedium *medium, - Double_t rlo, Double_t rhi, Double_t dz); - TGeoVolume *MakeHype(const char *name, TGeoMedium *medium, - Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz); - TGeoVolume *MakePgon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nedges, Int_t nz); - TGeoVolume *MakeSphere(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, - Double_t themin=0, Double_t themax=180, - Double_t phimin=0, Double_t phimax=360); - TGeoVolume *MakeTorus(const char *name, TGeoMedium *medium, Double_t r, - Double_t rmin, Double_t rmax, Double_t phi1=0, Double_t dphi=360); - TGeoVolume *MakeTrap(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoVolume *MakeTrd1(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy, Double_t dz); - TGeoVolume *MakeTrd2(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, - Double_t dz); - TGeoVolume *MakeTube(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz); - TGeoVolume *MakeTubs(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2); - TGeoVolume *MakeXtru(const char *name, TGeoMedium *medium, - Int_t nz); - TGeoVolumeAssembly *MakeVolumeAssembly(const char *name); - TGeoVolumeMulti *MakeVolumeMulti(const char *name, TGeoMedium *medium); + TGeoBuilder(const TGeoBuilder &) = delete; + TGeoBuilder &operator=(const TGeoBuilder &) = delete; + +private: + TGeoManager *fGeometry; //! current geometry + + void SetGeometry(TGeoManager *geom) { fGeometry = geom; } + +public: + ~TGeoBuilder() override; + + static TGeoBuilder *Instance(TGeoManager *geom); + + Int_t AddMaterial(TGeoMaterial *material); + Int_t AddTransformation(TGeoMatrix *matrix); + Int_t AddShape(TGeoShape *shape); + void RegisterMatrix(TGeoMatrix *matrix); + + TGeoVolume *MakeArb8(const char *name, TGeoMedium *medium, Double_t dz, Double_t *vertices = nullptr); + TGeoVolume *MakeBox(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz); + TGeoVolume *MakeCone(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2); + TGeoVolume *MakeCons(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); + TGeoVolume *MakeCtub(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, + Double_t phi2, Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); + TGeoVolume *MakeEltu(const char *name, TGeoMedium *medium, Double_t a, Double_t b, Double_t dz); + TGeoVolume *MakeGtra(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, Double_t twist, + Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, + Double_t tl2, Double_t alpha2); + TGeoVolume *MakePara(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz, Double_t alpha, + Double_t theta, Double_t phi); + TGeoVolume *MakePcon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nz); + TGeoVolume *MakeParaboloid(const char *name, TGeoMedium *medium, Double_t rlo, Double_t rhi, Double_t dz); + TGeoVolume *MakeHype(const char *name, TGeoMedium *medium, Double_t rin, Double_t stin, Double_t rout, + Double_t stout, Double_t dz); + TGeoVolume *MakePgon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nedges, Int_t nz); + TGeoVolume *MakeSphere(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t themin = 0, + Double_t themax = 180, Double_t phimin = 0, Double_t phimax = 360); + TGeoVolume *MakeTorus(const char *name, TGeoMedium *medium, Double_t r, Double_t rmin, Double_t rmax, + Double_t phi1 = 0, Double_t dphi = 360); + TGeoVolume *MakeTrap(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, Double_t h1, + Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, + Double_t alpha2); + TGeoVolume *MakeTrd1(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy, Double_t dz); + TGeoVolume * + MakeTrd2(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, Double_t dz); + TGeoVolume *MakeTube(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz); + TGeoVolume *MakeTubs(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, + Double_t phi2); + TGeoVolume *MakeXtru(const char *name, TGeoMedium *medium, Int_t nz); + TGeoVolumeAssembly *MakeVolumeAssembly(const char *name); + TGeoVolumeMulti *MakeVolumeMulti(const char *name, TGeoMedium *medium); //--- GEANT3-like geometry creation - TGeoVolume *Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step, Int_t numed=0, Option_t *option=""); - void Matrix(Int_t index, Double_t theta1, Double_t phi1, - Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3); - TGeoMaterial *Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen=0, Double_t intlen=0); - TGeoMaterial *Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, - Int_t nelem, Float_t *wmat, Int_t uid); - TGeoMaterial *Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, - Int_t nelem, Double_t *wmat, Int_t uid); - TGeoMedium *Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, - Int_t ifield, Double_t fieldm, Double_t tmaxfd, - Double_t stemax, Double_t deemax, Double_t epsil, - Double_t stmin); - void Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, - Bool_t isOnly, Float_t *upar, Int_t npar=0); - void Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, - Bool_t isOnly, Double_t *upar, Int_t npar=0); - TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, - Float_t *upar, Int_t npar=0); - TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, - Double_t *upar, Int_t npar=0); - - ClassDef(TGeoBuilder, 0) // geometry builder singleton + TGeoVolume *Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, + Int_t numed = 0, Option_t *option = ""); + void + Matrix(Int_t index, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3); + TGeoMaterial *Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen = 0, + Double_t intlen = 0); + TGeoMaterial * + Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, Int_t nelem, Float_t *wmat, Int_t uid); + TGeoMaterial * + Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, Int_t nelem, Double_t *wmat, Int_t uid); + TGeoMedium *Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, Int_t ifield, Double_t fieldm, + Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin); + void Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, + Bool_t isOnly, Float_t *upar, Int_t npar = 0); + void Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, + Bool_t isOnly, Double_t *upar, Int_t npar = 0); + TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, Float_t *upar, Int_t npar = 0); + TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, Double_t *upar, Int_t npar = 0); + + ClassDefOverride(TGeoBuilder, 0) // geometry builder singleton }; #endif - diff --git a/geom/geom/inc/TGeoCache.h b/geom/geom/inc/TGeoCache.h index a7363cb510252..9d3bce10749d3 100644 --- a/geom/geom/inc/TGeoCache.h +++ b/geom/geom/inc/TGeoCache.h @@ -25,111 +25,124 @@ struct TGeoStateInfo; class TGeoManager; class TGeoHMatrix; -class TGeoCacheState : public TObject -{ +class TGeoCacheState : public TObject { protected: - Int_t fCapacity; // maximum level stored - Int_t fLevel; // level in the current branch - Int_t fNmany; // number of overlapping nodes on current branch - Int_t fStart; // start level - Int_t fIdBranch[30]; // ID branch - Double_t fPoint[3]; // last point in master frame - Bool_t fOverlapping; // overlap flag + Int_t fCapacity; // maximum level stored + Int_t fLevel; // level in the current branch + Int_t fNmany; // number of overlapping nodes on current branch + Int_t fStart; // start level + Int_t fIdBranch[30]; // ID branch + Double_t fPoint[3]; // last point in master frame + Bool_t fOverlapping; // overlap flag - TGeoNode **fNodeBranch; // last node branch stored - TGeoHMatrix **fMatrixBranch; // global matrices for last branch - TGeoHMatrix **fMatPtr; // array of matrix pointers + TGeoNode **fNodeBranch; // last node branch stored + TGeoHMatrix **fMatrixBranch; // global matrices for last branch + TGeoHMatrix **fMatPtr; // array of matrix pointers - TGeoCacheState(const TGeoCacheState&); - TGeoCacheState& operator=(const TGeoCacheState&); + TGeoCacheState(const TGeoCacheState &); + TGeoCacheState &operator=(const TGeoCacheState &); public: TGeoCacheState(); TGeoCacheState(Int_t capacity); - virtual ~TGeoCacheState(); + ~TGeoCacheState() override; - void SetState(Int_t level, Int_t startlevel, Int_t nmany, Bool_t ovlp, Double_t *point=nullptr); - Bool_t GetState(Int_t &level, Int_t &nmany, Double_t *point) const; + void SetState(Int_t level, Int_t startlevel, Int_t nmany, Bool_t ovlp, Double_t *point = nullptr); + Bool_t GetState(Int_t &level, Int_t &nmany, Double_t *point) const; - ClassDef(TGeoCacheState, 0) // class storing the cache state + ClassDefOverride(TGeoCacheState, 0) // class storing the cache state }; -class TGeoNodeCache : public TObject -{ +class TGeoNodeCache : public TObject { private: - Int_t fGeoCacheMaxLevels;// maximum supported number of levels - Int_t fGeoCacheStackSize;// maximum size of the stack - Int_t fGeoInfoStackSize; // maximum size of the stack of info states - Int_t fLevel; // level in the current branch - Int_t fStackLevel; // current level in the stack - Int_t fInfoLevel; // current level in the stack - Int_t fCurrentID; // unique ID of current node - Int_t fIndex; // index in array of ID's - Int_t fIdBranch[100]; // current branch of indices - TString fPath; // path for current branch - TGeoNode *fTop; // top node - TGeoNode *fNode; //! current node - TGeoHMatrix *fMatrix; //! current matrix - TObjArray *fStack; // stack of cache states - TGeoHMatrix **fMatrixBranch; // current branch of global matrices - TGeoHMatrix **fMPB; // pre-built matrices - TGeoNode **fNodeBranch; // current branch of nodes - TGeoStateInfo **fInfoBranch; // current branch of nodes - TGeoStateInfo *fPWInfo; //! State info for the parallel world - Int_t *fNodeIdArray; //! array of node id's - - TGeoNodeCache(const TGeoNodeCache&) = delete; - TGeoNodeCache& operator=(const TGeoNodeCache&) = delete; + Int_t fGeoCacheMaxLevels; // maximum supported number of levels + Int_t fGeoCacheStackSize; // maximum size of the stack + Int_t fGeoInfoStackSize; // maximum size of the stack of info states + Int_t fLevel; // level in the current branch + Int_t fStackLevel; // current level in the stack + Int_t fInfoLevel; // current level in the stack + Int_t fCurrentID; // unique ID of current node + Int_t fIndex; // index in array of ID's + Int_t fIdBranch[100]; // current branch of indices + TString fPath; // path for current branch + TGeoNode *fTop; // top node + TGeoNode *fNode; //! current node + TGeoHMatrix *fMatrix; //! current matrix + TObjArray *fStack; // stack of cache states + TGeoHMatrix **fMatrixBranch; // current branch of global matrices + TGeoHMatrix **fMPB; // pre-built matrices + TGeoNode **fNodeBranch; // current branch of nodes + TGeoStateInfo **fInfoBranch; // current branch of nodes + TGeoStateInfo *fPWInfo; //! State info for the parallel world + Int_t *fNodeIdArray; //! array of node id's + + TGeoNodeCache(const TGeoNodeCache &) = delete; + TGeoNodeCache &operator=(const TGeoNodeCache &) = delete; public: TGeoNodeCache(); - TGeoNodeCache(TGeoNode *top, Bool_t nodeid=kFALSE, Int_t capacity=30); - virtual ~TGeoNodeCache(); - - void BuildIdArray(); - void BuildInfoBranch(); - void CdNode(Int_t nodeid); - Bool_t CdDown(Int_t index); - Bool_t CdDown(TGeoNode *node); - void CdTop() {fLevel=1; CdUp();} - void CdUp(); - void FillIdBranch(const Int_t *br, Int_t startlevel=0) {memcpy(fIdBranch+startlevel,br,(fLevel+1-startlevel)*sizeof(Int_t)); fIndex=fIdBranch[fLevel];} - const Int_t *GetIdBranch() const {return fIdBranch;} - void *GetBranch() const {return fNodeBranch;} - void GetBranchNames(Int_t *names) const; - void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; - void GetBranchOnlys(Int_t *isonly) const; - void *GetMatrices() const {return fMatrixBranch;} - TGeoHMatrix *GetCurrentMatrix() const {return fMatrix;} - Int_t GetCurrentNodeId() const; - TGeoNode *GetMother(Int_t up=1) const {return ((fLevel-up)>=0)?fNodeBranch[fLevel-up]:nullptr;} - TGeoHMatrix *GetMotherMatrix(Int_t up=1) const {return ((fLevel-up)>=0)?fMatrixBranch[fLevel-up]:nullptr;} - TGeoNode *GetNode() const {return fNode;} - TGeoNode *GetTopNode() const {return fTop;} - TGeoStateInfo *GetInfo(); - TGeoStateInfo *GetMakePWInfo(Int_t nd); - void ReleaseInfo(); - Int_t GetLevel() const {return fLevel;} - const char *GetPath(); - Int_t GetStackLevel() const {return fStackLevel;} - Int_t GetNodeId() const; - Bool_t HasIdArray() const { return fNodeIdArray ? kTRUE : kFALSE; } - Bool_t IsDummy() const {return kTRUE;} - - void LocalToMaster(const Double_t *local, Double_t *master) const; - void MasterToLocal(const Double_t *master, Double_t *local) const; - void LocalToMasterVect(const Double_t *local, Double_t *master) const; - void MasterToLocalVect(const Double_t *master, Double_t *local) const; - void LocalToMasterBomb(const Double_t *local, Double_t *master) const; - void MasterToLocalBomb(const Double_t *master, Double_t *local) const; - Int_t PushState(Bool_t ovlp, Int_t ntmany=0, Int_t startlevel=0, Double_t *point=nullptr); - Bool_t PopState(Int_t &nmany, Double_t *point=nullptr); - Bool_t PopState(Int_t &nmany, Int_t level, Double_t *point=nullptr); - void PopDummy(Int_t ipop=9999) {fStackLevel=(ipop>fStackLevel)?(fStackLevel-1):(ipop-1);} - void Refresh() {fNode=fNodeBranch[fLevel]; fMatrix=fMatrixBranch[fLevel];} - Bool_t RestoreState(Int_t &nmany, TGeoCacheState *state, Double_t *point=nullptr); - - ClassDef(TGeoNodeCache, 0) // cache of reusable physical nodes + TGeoNodeCache(TGeoNode *top, Bool_t nodeid = kFALSE, Int_t capacity = 30); + ~TGeoNodeCache() override; + + void BuildIdArray(); + void BuildInfoBranch(); + void CdNode(Int_t nodeid); + Bool_t CdDown(Int_t index); + Bool_t CdDown(TGeoNode *node); + void CdTop() + { + fLevel = 1; + CdUp(); + } + void CdUp(); + void FillIdBranch(const Int_t *br, Int_t startlevel = 0) + { + memcpy(fIdBranch + startlevel, br, (fLevel + 1 - startlevel) * sizeof(Int_t)); + fIndex = fIdBranch[fLevel]; + } + const Int_t *GetIdBranch() const { return fIdBranch; } + void *GetBranch() const { return fNodeBranch; } + void GetBranchNames(Int_t *names) const; + void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; + void GetBranchOnlys(Int_t *isonly) const; + void *GetMatrices() const { return fMatrixBranch; } + TGeoHMatrix *GetCurrentMatrix() const { return fMatrix; } + Int_t GetCurrentNodeId() const; + TGeoNode *GetMother(Int_t up = 1) const { return ((fLevel - up) >= 0) ? fNodeBranch[fLevel - up] : nullptr; } + TGeoHMatrix *GetMotherMatrix(Int_t up = 1) const + { + return ((fLevel - up) >= 0) ? fMatrixBranch[fLevel - up] : nullptr; + } + TGeoNode *GetNode() const { return fNode; } + TGeoNode *GetTopNode() const { return fTop; } + TGeoStateInfo *GetInfo(); + TGeoStateInfo *GetMakePWInfo(Int_t nd); + void ReleaseInfo(); + Int_t GetLevel() const { return fLevel; } + const char *GetPath(); + Int_t GetStackLevel() const { return fStackLevel; } + Int_t GetNodeId() const; + Bool_t HasIdArray() const { return fNodeIdArray ? kTRUE : kFALSE; } + Bool_t IsDummy() const { return kTRUE; } + + void LocalToMaster(const Double_t *local, Double_t *master) const; + void MasterToLocal(const Double_t *master, Double_t *local) const; + void LocalToMasterVect(const Double_t *local, Double_t *master) const; + void MasterToLocalVect(const Double_t *master, Double_t *local) const; + void LocalToMasterBomb(const Double_t *local, Double_t *master) const; + void MasterToLocalBomb(const Double_t *master, Double_t *local) const; + Int_t PushState(Bool_t ovlp, Int_t ntmany = 0, Int_t startlevel = 0, Double_t *point = nullptr); + Bool_t PopState(Int_t &nmany, Double_t *point = nullptr); + Bool_t PopState(Int_t &nmany, Int_t level, Double_t *point = nullptr); + void PopDummy(Int_t ipop = 9999) { fStackLevel = (ipop > fStackLevel) ? (fStackLevel - 1) : (ipop - 1); } + void Refresh() + { + fNode = fNodeBranch[fLevel]; + fMatrix = fMatrixBranch[fLevel]; + } + Bool_t RestoreState(Int_t &nmany, TGeoCacheState *state, Double_t *point = nullptr); + + ClassDefOverride(TGeoNodeCache, 0) // cache of reusable physical nodes }; #endif diff --git a/geom/geom/inc/TGeoCompositeShape.h b/geom/geom/inc/TGeoCompositeShape.h index 3994abfcc0d15..31ba0a86bd86a 100644 --- a/geom/geom/inc/TGeoCompositeShape.h +++ b/geom/geom/inc/TGeoCompositeShape.h @@ -24,15 +24,14 @@ class TGeoBoolNode; -class TGeoCompositeShape : public TGeoBBox -{ -private : -// data members - TGeoBoolNode *fNode; // top boolean node +class TGeoCompositeShape : public TGeoBBox { +private: + // data members + TGeoBoolNode *fNode; // top boolean node protected: TGeoCompositeShape(const TGeoCompositeShape &) = delete; - TGeoCompositeShape& operator=(const TGeoCompositeShape &) = delete; + TGeoCompositeShape &operator=(const TGeoCompositeShape &) = delete; public: // constructors @@ -41,49 +40,48 @@ private : TGeoCompositeShape(const char *expression); TGeoCompositeShape(const char *name, TGeoBoolNode *node); // destructor - virtual ~TGeoCompositeShape(); + ~TGeoCompositeShape() override; // methods - virtual Double_t Capacity() const; - virtual void ClearThreadData() const; - virtual void CreateThreadData(Int_t nthreads); - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - TGeoBoolNode *GetBoolNode() const {return fNode;} - virtual void GetBoundingCylinder(Double_t * /*param*/) const {} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - virtual void InspectShape() const; - virtual Bool_t IsComposite() const {return kTRUE;} - virtual Bool_t IsCylType() const {return kFALSE;} - void MakeNode(const char *expression); - virtual Bool_t PaintComposite(Option_t *option = "") const; - void RegisterYourself(); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t * /*param*/) {} - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ClearThreadData() const override; + void CreateThreadData(Int_t nthreads) override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + TGeoBoolNode *GetBoolNode() const { return fNode; } + void GetBoundingCylinder(Double_t * /*param*/) const override {} + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + void InspectShape() const override; + Bool_t IsComposite() const override { return kTRUE; } + Bool_t IsCylType() const override { return kFALSE; } + void MakeNode(const char *expression); + virtual Bool_t PaintComposite(Option_t *option = "") const; + void RegisterYourself(); + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t * /*param*/) override {} + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void Sizeof3D() const override; - ClassDef(TGeoCompositeShape, 1) // boolean composite shape + ClassDefOverride(TGeoCompositeShape, 1) // boolean composite shape }; - - #endif - diff --git a/geom/geom/inc/TGeoCone.h b/geom/geom/inc/TGeoCone.h index 50a875ead50b7..16ba9605e2e0b 100644 --- a/geom/geom/inc/TGeoCone.h +++ b/geom/geom/inc/TGeoCone.h @@ -14,170 +14,173 @@ #include "TGeoBBox.h" -class TGeoCone : public TGeoBBox -{ -protected : -// data members - Double_t fDz; // half length - Double_t fRmin1; // inner radius at -dz - Double_t fRmax1; // outer radius at -dz - Double_t fRmin2; // inner radius at +dz - Double_t fRmax2; // outer radius at +dz -// methods - TGeoCone(const TGeoCone&) = delete; - TGeoCone& operator=(const TGeoCone&) = delete; +class TGeoCone : public TGeoBBox { +protected: + // data members + Double_t fDz; // half length + Double_t fRmin1; // inner radius at -dz + Double_t fRmax1; // outer radius at -dz + Double_t fRmin2; // inner radius at +dz + Double_t fRmax2; // outer radius at +dz + // methods + TGeoCone(const TGeoCone &) = delete; + TGeoCone &operator=(const TGeoCone &) = delete; public: // constructors TGeoCone(); - TGeoCone(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2); - TGeoCone(const char *name, Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2); + TGeoCone(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); + TGeoCone(const char *name, Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); TGeoCone(Double_t *params); // destructor - virtual ~TGeoCone(); + ~TGeoCone() override; // methods - virtual Double_t Capacity() const; - static Double_t Capacity(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - static void DistToCone(const Double_t *point, const Double_t *dir, Double_t dz, Double_t r1, Double_t r2, Double_t &b, Double_t &delta); - static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual Int_t GetByteCount() const {return 56;} - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Double_t GetDz() const {return fDz;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - virtual Double_t GetRmin1() const {return fRmin1;} - virtual Double_t GetRmax1() const {return fRmax1;} - virtual Double_t GetRmin2() const {return fRmin2;} - virtual Double_t GetRmax2() const {return fRmax2;} - - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Int_t skipz=0); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buffer) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoCone, 1) // conical tube class - + Double_t Capacity() const override; + static Double_t Capacity(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2); + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + static void DistToCone(const Double_t *point, const Double_t *dir, Double_t dz, Double_t r1, Double_t r2, + Double_t &b, Double_t &delta); + static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2); + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + Int_t GetByteCount() const override { return 56; } + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + virtual Double_t GetDz() const { return fDz; } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + virtual Double_t GetRmin1() const { return fRmin1; } + virtual Double_t GetRmax1() const { return fRmax1; } + virtual Double_t GetRmin2() const { return fRmin2; } + virtual Double_t GetRmax2() const { return fRmax2; } + + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Int_t skipz = 0); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buffer) const override; + void Sizeof3D() const override; + + ClassDefOverride(TGeoCone, 1) // conical tube class }; -class TGeoConeSeg : public TGeoCone -{ +class TGeoConeSeg : public TGeoCone { protected: // data members - Double_t fPhi1; // first phi limit - Double_t fPhi2; // second phi limit + Double_t fPhi1; // first phi limit + Double_t fPhi2; // second phi limit // Transient trigonometric data - Double_t fS1; // sin(phi1) - Double_t fC1; // cos(phi1) - Double_t fS2; // sin(phi2) - Double_t fC2; // cos(phi2) - Double_t fSm; // sin(0.5*(phi1+phi2)) - Double_t fCm; // cos(0.5*(phi1+phi2)) - Double_t fCdfi; // cos(0.5*(phi1-phi2)) + Double_t fS1; // sin(phi1) + Double_t fC1; // cos(phi1) + Double_t fS2; // sin(phi2) + Double_t fC2; // cos(phi2) + Double_t fSm; // sin(0.5*(phi1+phi2)) + Double_t fCm; // cos(0.5*(phi1+phi2)) + Double_t fCdfi; // cos(0.5*(phi1-phi2)) - void InitTrigonometry(); + void InitTrigonometry(); public: // constructors TGeoConeSeg(); - TGeoConeSeg(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); - TGeoConeSeg(const char *name, Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); + TGeoConeSeg(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t phi1, + Double_t phi2); + TGeoConeSeg(const char *name, Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, + Double_t phi1, Double_t phi2); TGeoConeSeg(Double_t *params); // destructor - virtual ~TGeoConeSeg(); + ~TGeoConeSeg() override; // methods - virtual void AfterStreamer(); - virtual Double_t Capacity() const; - static Double_t Capacity(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, - Double_t c1, Double_t s1, Double_t c2, Double_t s2); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - static Double_t DistToCons(const Double_t *point, const Double_t *dir, Double_t r1, Double_t z1, Double_t r2, Double_t z2, Double_t phi1, Double_t phi2); - static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 64;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - Double_t GetPhi1() const {return fPhi1;} - Double_t GetPhi2() const {return fPhi2;} - virtual void InspectShape() const; - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2, Int_t skipz=0); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetConsDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buffer) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoConeSeg, 2) // conical tube segment class + void AfterStreamer() override; + Double_t Capacity() const override; + static Double_t + Capacity(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, Double_t c2, + Double_t s2); + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + static Double_t DistToCons(const Double_t *point, const Double_t *dir, Double_t r1, Double_t z1, Double_t r2, + Double_t z2, Double_t phi1, Double_t phi2); + static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, + Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, + Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 64; } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + Double_t GetPhi1() const { return fPhi1; } + Double_t GetPhi2() const { return fPhi2; } + void InspectShape() const override; + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2, Int_t skipz = 0); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetConsDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t phi1, + Double_t phi2); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buffer) const override; + void Sizeof3D() const override; + + ClassDefOverride(TGeoConeSeg, 2) // conical tube segment class }; #endif diff --git a/geom/geom/inc/TGeoElement.h b/geom/geom/inc/TGeoElement.h index b573c36a04d83..365d1a9ed73ea 100644 --- a/geom/geom/inc/TGeoElement.h +++ b/geom/geom/inc/TGeoElement.h @@ -33,32 +33,27 @@ class TGeoIsotope; // // //////////////////////////////////////////////////////////////////////////// -class TGeoElement : public TNamed -{ +class TGeoElement : public TNamed { protected: - enum EGeoElement { - kElemUsed = BIT(17), - kElemDefined = BIT(18), - kElementChecked = BIT(19) - }; + enum EGeoElement { kElemUsed = BIT(17), kElemDefined = BIT(18), kElementChecked = BIT(19) }; - Int_t fZ; // Z of element - Int_t fN; // Number of nucleons - Int_t fNisotopes; // Number of isotopes for the element - Double_t fA; // A of element - TObjArray *fIsotopes; // List of isotopes - Double_t *fAbundances; //[fNisotopes] Array of relative isotope abundances - Double_t fCoulomb; // Coulomb correction factor - Double_t fRadTsai; // Tsai formula for the radiation length + Int_t fZ; // Z of element + Int_t fN; // Number of nucleons + Int_t fNisotopes; // Number of isotopes for the element + Double_t fA; // A of element + TObjArray *fIsotopes; // List of isotopes + Double_t *fAbundances; //[fNisotopes] Array of relative isotope abundances + Double_t fCoulomb; // Coulomb correction factor + Double_t fRadTsai; // Tsai formula for the radiation length private: TGeoElement(const TGeoElement &other) = delete; TGeoElement &operator=(const TGeoElement &other) = delete; // Compute the Coulomb correction factor - void ComputeCoulombFactor(); + void ComputeCoulombFactor(); // Compute the Tsai formula for the radiation length - void ComputeLradTsaiFactor(); + void ComputeLradTsaiFactor(); public: // constructors @@ -67,35 +62,35 @@ class TGeoElement : public TNamed TGeoElement(const char *name, const char *title, Int_t nisotopes); TGeoElement(const char *name, const char *title, Int_t z, Int_t n, Double_t a); // destructor - virtual ~TGeoElement(); + ~TGeoElement() override; // methods - virtual Int_t ENDFCode() const { return 0;} - Int_t Z() const {return fZ;} - Int_t N() const {return fN;} - Double_t Neff() const; - Double_t A() const {return fA;} - void AddIsotope(TGeoIsotope *isotope, Double_t relativeAbundance); - Int_t GetNisotopes() const {return fNisotopes;} - TGeoIsotope *GetIsotope(Int_t i) const; - Double_t GetRelativeAbundance(Int_t i) const; + virtual Int_t ENDFCode() const { return 0; } + Int_t Z() const { return fZ; } + Int_t N() const { return fN; } + Double_t Neff() const; + Double_t A() const { return fA; } + void AddIsotope(TGeoIsotope *isotope, Double_t relativeAbundance); + Int_t GetNisotopes() const { return fNisotopes; } + TGeoIsotope *GetIsotope(Int_t i) const; + Double_t GetRelativeAbundance(Int_t i) const; // Calculate properties for an atomic number - void ComputeDerivedQuantities(); + void ComputeDerivedQuantities(); // Specific activity (in Bq/gram) - virtual Double_t GetSpecificActivity() const {return 0.;} - Bool_t HasIsotopes() const {return (fNisotopes==0)?kFALSE:kTRUE;} - Bool_t IsDefined() const {return TObject::TestBit(kElemDefined);} - virtual Bool_t IsRadioNuclide() const {return kFALSE;} - Bool_t IsUsed() const {return TObject::TestBit(kElemUsed);} - virtual void Print(Option_t *option = "") const; - void SetDefined(Bool_t flag=kTRUE) {TObject::SetBit(kElemDefined,flag);} - void SetUsed(Bool_t flag=kTRUE) {TObject::SetBit(kElemUsed,flag);} + virtual Double_t GetSpecificActivity() const { return 0.; } + Bool_t HasIsotopes() const { return (fNisotopes == 0) ? kFALSE : kTRUE; } + Bool_t IsDefined() const { return TObject::TestBit(kElemDefined); } + virtual Bool_t IsRadioNuclide() const { return kFALSE; } + Bool_t IsUsed() const { return TObject::TestBit(kElemUsed); } + void Print(Option_t *option = "") const override; + void SetDefined(Bool_t flag = kTRUE) { TObject::SetBit(kElemDefined, flag); } + void SetUsed(Bool_t flag = kTRUE) { TObject::SetBit(kElemUsed, flag); } static TGeoElementTable *GetElementTable(); // Coulomb correction factor - inline Double_t GetfCoulomb() const {return fCoulomb;} + inline Double_t GetfCoulomb() const { return fCoulomb; } // Tsai formula for the radiation length - inline Double_t GetfRadTsai() const {return fRadTsai;} + inline Double_t GetfRadTsai() const { return fRadTsai; } - ClassDef(TGeoElement, 3) // base element class + ClassDefOverride(TGeoElement, 3) // base element class }; //////////////////////////////////////////////////////////////////////////// @@ -105,25 +100,24 @@ class TGeoElement : public TNamed // // //////////////////////////////////////////////////////////////////////////// -class TGeoIsotope : public TNamed -{ +class TGeoIsotope : public TNamed { protected: - Int_t fZ; // atomic number - Int_t fN; // number of nucleons - Double_t fA; // atomic mass (g/mole) + Int_t fZ; // atomic number + Int_t fN; // number of nucleons + Double_t fA; // atomic mass (g/mole) public: TGeoIsotope(); TGeoIsotope(const char *name, Int_t z, Int_t n, Double_t a); - virtual ~TGeoIsotope() {} + ~TGeoIsotope() override {} - Int_t GetZ() const {return fZ;} - Int_t GetN() const {return fN;} - Double_t GetA() const {return fA;} - static TGeoIsotope *FindIsotope(const char *name); - virtual void Print(Option_t *option = "") const; + Int_t GetZ() const { return fZ; } + Int_t GetN() const { return fN; } + Double_t GetA() const { return fA; } + static TGeoIsotope *FindIsotope(const char *name); + void Print(Option_t *option = "") const override; - ClassDef(TGeoIsotope, 1) // Isotope class defined by Z,N,A + ClassDefOverride(TGeoIsotope, 1) // Isotope class defined by Z,N,A }; //////////////////////////////////////////////////////////////////////////// @@ -135,76 +129,73 @@ class TGeoIsotope : public TNamed class TGeoDecayChannel; class TGeoBatemanSol; -class TGeoElementRN : public TGeoElement -{ +class TGeoElementRN : public TGeoElement { protected: - Int_t fENDFcode; // ENDF element code - Int_t fIso; // Isomer number - Double_t fLevel; // Isomeric level - Double_t fDeltaM; // Mass excess - Double_t fHalfLife; // Half life - Double_t fNatAbun; // Natural Abundance -// char fJP[11]; // Spin-parity - Double_t fTH_F; // Hynalation toxicity - Double_t fTG_F; // Ingestion toxicity - Double_t fTH_S; // Hynalation toxicity - Double_t fTG_S; // Ingestion toxicity - Int_t fStatus; // Status code - TGeoBatemanSol *fRatio; // Time evolution of proportion by number - - TObjArray *fDecays; // List of decay modes - - void MakeName(Int_t a, Int_t z, Int_t iso); + Int_t fENDFcode; // ENDF element code + Int_t fIso; // Isomer number + Double_t fLevel; // Isomeric level + Double_t fDeltaM; // Mass excess + Double_t fHalfLife; // Half life + Double_t fNatAbun; // Natural Abundance + // char fJP[11]; // Spin-parity + Double_t fTH_F; // Hynalation toxicity + Double_t fTG_F; // Ingestion toxicity + Double_t fTH_S; // Hynalation toxicity + Double_t fTG_S; // Ingestion toxicity + Int_t fStatus; // Status code + TGeoBatemanSol *fRatio; // Time evolution of proportion by number + + TObjArray *fDecays; // List of decay modes + + void MakeName(Int_t a, Int_t z, Int_t iso); private: - TGeoElementRN(const TGeoElementRN& elem) = delete; - TGeoElementRN& operator=(const TGeoElementRN& elem) = delete; + TGeoElementRN(const TGeoElementRN &elem) = delete; + TGeoElementRN &operator=(const TGeoElementRN &elem) = delete; public: TGeoElementRN(); - TGeoElementRN(Int_t A, Int_t Z, Int_t iso, Double_t level, - Double_t deltaM, Double_t halfLife, const char* JP, - Double_t natAbun, Double_t th_f, Double_t tg_f, Double_t th_s, - Double_t tg_s, Int_t status); - virtual ~TGeoElementRN(); - - void AddDecay(Int_t decay, Int_t diso, Double_t branchingRatio, Double_t qValue); - void AddDecay(TGeoDecayChannel *dc); - void AddRatio(TGeoBatemanSol &ratio); - void ResetRatio(); - static Int_t ENDF(Int_t a, Int_t z, Int_t iso) {return 10000*z+10*a+iso;} + TGeoElementRN(Int_t A, Int_t Z, Int_t iso, Double_t level, Double_t deltaM, Double_t halfLife, const char *JP, + Double_t natAbun, Double_t th_f, Double_t tg_f, Double_t th_s, Double_t tg_s, Int_t status); + ~TGeoElementRN() override; + + void AddDecay(Int_t decay, Int_t diso, Double_t branchingRatio, Double_t qValue); + void AddDecay(TGeoDecayChannel *dc); + void AddRatio(TGeoBatemanSol &ratio); + void ResetRatio(); + static Int_t ENDF(Int_t a, Int_t z, Int_t iso) { return 10000 * z + 10 * a + iso; } // Getters - virtual Int_t ENDFCode() const {return fENDFcode;} - virtual Double_t GetSpecificActivity() const; - virtual Bool_t IsRadioNuclide() const {return kTRUE;} - Int_t MassNo() const {return (Int_t)fA;} - Int_t AtomicNo() const {return fZ;} - Int_t IsoNo() const {return fIso;} - Double_t Level() const {return fLevel;} - Double_t MassEx() const {return fDeltaM;} - Double_t HalfLife() const {return fHalfLife;} - Double_t NatAbun() const {return fNatAbun;} - const char* PJ() const {return fTitle.Data();} - Double_t TH_F() const {return fTH_F;} - Double_t TG_F() const {return fTG_F;} - Double_t TH_S() const {return fTH_S;} - Double_t TG_S() const {return fTG_S;} - Double_t Status() const {return fStatus;} - Bool_t Stable() const {return !fDecays;} - TObjArray *Decays() const {return fDecays;} - Int_t GetNdecays() const; - TGeoBatemanSol *Ratio() const {return fRatio;} + Int_t ENDFCode() const override { return fENDFcode; } + Double_t GetSpecificActivity() const override; + Bool_t IsRadioNuclide() const override { return kTRUE; } + Int_t MassNo() const { return (Int_t)fA; } + Int_t AtomicNo() const { return fZ; } + Int_t IsoNo() const { return fIso; } + Double_t Level() const { return fLevel; } + Double_t MassEx() const { return fDeltaM; } + Double_t HalfLife() const { return fHalfLife; } + Double_t NatAbun() const { return fNatAbun; } + const char *PJ() const { return fTitle.Data(); } + Double_t TH_F() const { return fTH_F; } + Double_t TG_F() const { return fTG_F; } + Double_t TH_S() const { return fTH_S; } + Double_t TG_S() const { return fTG_S; } + Double_t Status() const { return fStatus; } + Bool_t Stable() const { return !fDecays; } + TObjArray *Decays() const { return fDecays; } + Int_t GetNdecays() const; + TGeoBatemanSol *Ratio() const { return fRatio; } // Utilities - Bool_t CheckDecays() const; - Int_t DecayResult(TGeoDecayChannel *dc) const; - void FillPopulation(TObjArray *population, Double_t precision=0.001, Double_t factor=1.); - virtual void Print(Option_t *option = "") const; - static TGeoElementRN *ReadElementRN(const char *record, Int_t &ndecays); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - - ClassDef(TGeoElementRN, 2) // radionuclides class + Bool_t CheckDecays() const; + Int_t DecayResult(TGeoDecayChannel *dc) const; + void FillPopulation(TObjArray *population, Double_t precision = 0.001, Double_t factor = 1.); + void Print(Option_t *option = "") const override; + static TGeoElementRN *ReadElementRN(const char *record, Int_t &ndecays); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + + ClassDefOverride(TGeoElementRN, 2) // radionuclides class }; //////////////////////////////////////////////////////////////////////////// @@ -213,63 +204,77 @@ class TGeoElementRN : public TGeoElement // // //////////////////////////////////////////////////////////////////////////// -class TGeoDecayChannel : public TObject -{ +class TGeoDecayChannel : public TObject { private: - UInt_t fDecay; // Decay mode - Int_t fDiso; // Delta isomeric number - Double_t fBranchingRatio; // Branching Ratio - Double_t fQvalue; // Qvalue in GeV - TGeoElementRN *fParent; // Parent element - TGeoElementRN *fDaughter; // Daughter element + UInt_t fDecay; // Decay mode + Int_t fDiso; // Delta isomeric number + Double_t fBranchingRatio; // Branching Ratio + Double_t fQvalue; // Qvalue in GeV + TGeoElementRN *fParent; // Parent element + TGeoElementRN *fDaughter; // Daughter element public: enum ENuclearDecayMode { - kBitMask32 = 0xffffffff, - k2BetaMinus = BIT(0), - kBetaMinus = BIT(1), - kNeutronEm = BIT(2), - kProtonEm = BIT(3), - kAlpha = BIT(4), - kECF = BIT(5), - kElecCapt = BIT(6), - kIsoTrans = BIT(7), - kI = BIT(8), - kSpontFiss = BIT(9), - k2P = BIT(10), - k2N = BIT(11), - k2A = BIT(12), - kCarbon12 = BIT(13), - kCarbon14 = BIT(14) + kBitMask32 = 0xffffffff, + k2BetaMinus = BIT(0), + kBetaMinus = BIT(1), + kNeutronEm = BIT(2), + kProtonEm = BIT(3), + kAlpha = BIT(4), + kECF = BIT(5), + kElecCapt = BIT(6), + kIsoTrans = BIT(7), + kI = BIT(8), + kSpontFiss = BIT(9), + k2P = BIT(10), + k2N = BIT(11), + k2A = BIT(12), + kCarbon12 = BIT(13), + kCarbon14 = BIT(14) }; TGeoDecayChannel() : fDecay(0), fDiso(0), fBranchingRatio(0), fQvalue(0), fParent(nullptr), fDaughter(nullptr) {} TGeoDecayChannel(Int_t decay, Int_t diso, Double_t branchingRatio, Double_t qValue) - : fDecay(decay), fDiso(diso), fBranchingRatio(branchingRatio), fQvalue(qValue), fParent(nullptr), fDaughter(nullptr) {} - TGeoDecayChannel(const TGeoDecayChannel &dc) : TObject(dc),fDecay(dc.fDecay),fDiso(dc.fDiso),fBranchingRatio(dc.fBranchingRatio), - fQvalue(dc.fQvalue),fParent(dc.fParent),fDaughter(dc.fDaughter) {} - virtual ~TGeoDecayChannel() {} - - TGeoDecayChannel& operator=(const TGeoDecayChannel& dc); + : fDecay(decay), + fDiso(diso), + fBranchingRatio(branchingRatio), + fQvalue(qValue), + fParent(nullptr), + fDaughter(nullptr) + { + } + TGeoDecayChannel(const TGeoDecayChannel &dc) + : TObject(dc), + fDecay(dc.fDecay), + fDiso(dc.fDiso), + fBranchingRatio(dc.fBranchingRatio), + fQvalue(dc.fQvalue), + fParent(dc.fParent), + fDaughter(dc.fDaughter) + { + } + ~TGeoDecayChannel() override {} + + TGeoDecayChannel &operator=(const TGeoDecayChannel &dc); // Getters - Int_t GetIndex() const; - virtual const char *GetName() const; - UInt_t Decay() const {return fDecay;} - Double_t BranchingRatio() const {return fBranchingRatio;} - Double_t Qvalue() const {return fQvalue;} - Int_t DeltaIso() const {return fDiso;} - TGeoElementRN *Daughter() const {return fDaughter;} - TGeoElementRN *Parent() const {return fParent;} - static void DecayName(UInt_t decay, TString &name); + Int_t GetIndex() const; + const char *GetName() const override; + UInt_t Decay() const { return fDecay; } + Double_t BranchingRatio() const { return fBranchingRatio; } + Double_t Qvalue() const { return fQvalue; } + Int_t DeltaIso() const { return fDiso; } + TGeoElementRN *Daughter() const { return fDaughter; } + TGeoElementRN *Parent() const { return fParent; } + static void DecayName(UInt_t decay, TString &name); // Setters - void SetParent(TGeoElementRN *parent) {fParent = parent;} - void SetDaughter(TGeoElementRN *daughter) {fDaughter = daughter;} + void SetParent(TGeoElementRN *parent) { fParent = parent; } + void SetDaughter(TGeoElementRN *daughter) { fDaughter = daughter; } // Services - virtual void Print(Option_t *opt = " ") const; + void Print(Option_t *opt = " ") const override; static TGeoDecayChannel *ReadDecay(const char *record); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void DecayShift(Int_t &dA, Int_t &dZ, Int_t &dI) const ; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + virtual void DecayShift(Int_t &dA, Int_t &dZ, Int_t &dI) const; - ClassDef(TGeoDecayChannel,1) // Decay channel for Elements + ClassDefOverride(TGeoDecayChannel, 1) // Decay channel for Elements }; //////////////////////////////////////////////////////////////////////////////// @@ -278,45 +283,70 @@ class TGeoDecayChannel : public TObject // // //////////////////////////////////////////////////////////////////////////////// -class TGeoBatemanSol : public TObject, public TAttLine, public TAttFill, public TAttMarker -{ +class TGeoBatemanSol : public TObject, public TAttLine, public TAttFill, public TAttMarker { private: typedef struct { - Double_t cn; // Concentration for element 'i': Ni/Ntop - Double_t lambda; // Decay coef. for element 'i' + Double_t cn; // Concentration for element 'i': Ni/Ntop + Double_t lambda; // Decay coef. for element 'i' } BtCoef_t; - TGeoElementRN *fElem; // Referred RN element - TGeoElementRN *fElemTop; // Top RN element - Int_t fCsize; // Size of the array of coefficients - Int_t fNcoeff; // Number of coefficients - Double_t fFactor; // Constant factor that applies to all coefficients - Double_t fTmin; // Minimum value of the time interval - Double_t fTmax; // Maximum value of the time interval - BtCoef_t *fCoeff; //[fNcoeff] Array of coefficients + TGeoElementRN *fElem; // Referred RN element + TGeoElementRN *fElemTop; // Top RN element + Int_t fCsize; // Size of the array of coefficients + Int_t fNcoeff; // Number of coefficients + Double_t fFactor; // Constant factor that applies to all coefficients + Double_t fTmin; // Minimum value of the time interval + Double_t fTmax; // Maximum value of the time interval + BtCoef_t *fCoeff; //[fNcoeff] Array of coefficients public: - TGeoBatemanSol() : TObject(), TAttLine(), TAttFill(), TAttMarker(), fElem(nullptr), fElemTop(nullptr), fCsize(0), fNcoeff(0), fFactor(1.), fTmin(0.), fTmax(0), fCoeff(nullptr) {} + TGeoBatemanSol() + : TObject(), + TAttLine(), + TAttFill(), + TAttMarker(), + fElem(nullptr), + fElemTop(nullptr), + fCsize(0), + fNcoeff(0), + fFactor(1.), + fTmin(0.), + fTmax(0), + fCoeff(nullptr) + { + } TGeoBatemanSol(TGeoElementRN *elem); TGeoBatemanSol(const TObjArray *chain); - TGeoBatemanSol(const TGeoBatemanSol& other); - ~TGeoBatemanSol(); - - TGeoBatemanSol& operator=(const TGeoBatemanSol& other); - TGeoBatemanSol& operator+=(const TGeoBatemanSol& other); - - Double_t Concentration(Double_t time) const; - virtual void Draw(Option_t *option=""); - void GetCoeff(Int_t i, Double_t &cn, Double_t &lambda) const {cn=fCoeff[i].cn; lambda=fCoeff[i].lambda;} - void GetRange(Double_t &tmin, Double_t &tmax) const {tmin=fTmin; tmax=fTmax;} - TGeoElementRN *GetElement() const {return fElem;} - TGeoElementRN *GetTopElement() const {return fElemTop;} - Int_t GetNcoeff() const {return fNcoeff;} - virtual void Print(Option_t *option = "") const; - void SetRange(Double_t tmin=0., Double_t tmax=0.) {fTmin=tmin; fTmax=tmax;} - void SetFactor(Double_t factor) {fFactor = factor;} - void FindSolution(const TObjArray *array); - void Normalize(Double_t factor); - - ClassDef(TGeoBatemanSol,1) // Solution for the Bateman equation + TGeoBatemanSol(const TGeoBatemanSol &other); + ~TGeoBatemanSol() override; + + TGeoBatemanSol &operator=(const TGeoBatemanSol &other); + TGeoBatemanSol &operator+=(const TGeoBatemanSol &other); + + Double_t Concentration(Double_t time) const; + void Draw(Option_t *option = "") override; + void GetCoeff(Int_t i, Double_t &cn, Double_t &lambda) const + { + cn = fCoeff[i].cn; + lambda = fCoeff[i].lambda; + } + void GetRange(Double_t &tmin, Double_t &tmax) const + { + tmin = fTmin; + tmax = fTmax; + } + TGeoElementRN *GetElement() const { return fElem; } + TGeoElementRN *GetTopElement() const { return fElemTop; } + Int_t GetNcoeff() const { return fNcoeff; } + void Print(Option_t *option = "") const override; + void SetRange(Double_t tmin = 0., Double_t tmax = 0.) + { + fTmin = tmin; + fTmax = tmax; + } + void SetFactor(Double_t factor) { fFactor = factor; } + void FindSolution(const TObjArray *array); + void Normalize(Double_t factor); + + ClassDefOverride(TGeoBatemanSol, 1) // Solution for the Bateman equation }; //////////////////////////////////////////////////////////////////////////// @@ -325,39 +355,38 @@ class TGeoBatemanSol : public TObject, public TAttLine, public TAttFill, public // // //////////////////////////////////////////////////////////////////////////// -class TGeoElemIter -{ +class TGeoElemIter { private: - const TGeoElementRN *fTop; // Top element of the iteration - const TGeoElementRN *fElem; // Current element - TObjArray *fBranch; // Current branch - Int_t fLevel; // Current level - Double_t fLimitRatio; // Minimum cumulative branching ratio - Double_t fRatio; // Current ratio + const TGeoElementRN *fTop; // Top element of the iteration + const TGeoElementRN *fElem; // Current element + TObjArray *fBranch; // Current branch + Int_t fLevel; // Current level + Double_t fLimitRatio; // Minimum cumulative branching ratio + Double_t fRatio; // Current ratio protected: TGeoElemIter() : fTop(nullptr), fElem(nullptr), fBranch(nullptr), fLevel(0), fLimitRatio(0), fRatio(0) {} - TGeoElementRN *Down(Int_t ibranch); - TGeoElementRN *Up(); + TGeoElementRN *Down(Int_t ibranch); + TGeoElementRN *Up(); public: - TGeoElemIter(TGeoElementRN *top, Double_t limit=1.e-4); + TGeoElemIter(TGeoElementRN *top, Double_t limit = 1.e-4); TGeoElemIter(const TGeoElemIter &iter); virtual ~TGeoElemIter(); - TGeoElemIter &operator=(const TGeoElemIter &iter); - TGeoElementRN *operator()(); - TGeoElementRN *Next(); + TGeoElemIter &operator=(const TGeoElemIter &iter); + TGeoElementRN *operator()(); + TGeoElementRN *Next(); - TObjArray *GetBranch() const {return fBranch;} - const TGeoElementRN *GetTop() const {return fTop;} - const TGeoElementRN *GetElement() const {return fElem;} - Int_t GetLevel() const {return fLevel;} - Double_t GetRatio() const {return fRatio;} - virtual void Print(Option_t *option="") const; - void SetLimitRatio(Double_t limit) {fLimitRatio = limit;} + TObjArray *GetBranch() const { return fBranch; } + const TGeoElementRN *GetTop() const { return fTop; } + const TGeoElementRN *GetElement() const { return fElem; } + Int_t GetLevel() const { return fLevel; } + Double_t GetRatio() const { return fRatio; } + virtual void Print(Option_t *option = "") const; + void SetLimitRatio(Double_t limit) { fLimitRatio = limit; } - ClassDef(TGeoElemIter,0) // Iterator for radionuclide chains. + ClassDef(TGeoElemIter, 0) // Iterator for radionuclide chains. }; //////////////////////////////////////////////////////////////////////////// @@ -366,61 +395,56 @@ class TGeoElemIter // // //////////////////////////////////////////////////////////////////////////// -class TGeoElementTable : public TObject -{ +class TGeoElementTable : public TObject { private: -// data members - Int_t fNelements; // number of elements - Int_t fNelementsRN; // number of RN elements - Int_t fNisotopes; // number of isotopes - TObjArray *fList; // list of elements - TObjArray *fListRN; // list of RN elements - TObjArray *fIsotopes; // list of user-defined isotopes + // data members + Int_t fNelements; // number of elements + Int_t fNelementsRN; // number of RN elements + Int_t fNisotopes; // number of isotopes + TObjArray *fList; // list of elements + TObjArray *fListRN; // list of RN elements + TObjArray *fIsotopes; // list of user-defined isotopes // Map of radionuclides - typedef std::map ElementRNMap_t; - typedef ElementRNMap_t::iterator ElementRNMapIt_t; - ElementRNMap_t fElementsRN; //! map of RN elements with ENDF key + typedef std::map ElementRNMap_t; + typedef ElementRNMap_t::iterator ElementRNMapIt_t; + ElementRNMap_t fElementsRN; //! map of RN elements with ENDF key protected: - TGeoElementTable(const TGeoElementTable&); - TGeoElementTable& operator=(const TGeoElementTable&); + TGeoElementTable(const TGeoElementTable &); + TGeoElementTable &operator=(const TGeoElementTable &); public: // constructors TGeoElementTable(); TGeoElementTable(Int_t nelements); // destructor - virtual ~TGeoElementTable(); + ~TGeoElementTable() override; // methods - enum EGeoETStatus { - kETDefaultElements = BIT(14), - kETRNElements = BIT(15) - }; - void AddElement(const char *name, const char *title, Int_t z, Double_t a); - void AddElement(const char *name, const char *title, Int_t z, Int_t n, Double_t a); - void AddElement(TGeoElement *elem); - void AddElementRN(TGeoElementRN *elem); - void AddIsotope(TGeoIsotope *isotope); - void BuildDefaultElements(); - void ImportElementsRN(); - Bool_t CheckTable() const; - TGeoElement *FindElement(const char *name) const; - TGeoIsotope *FindIsotope(const char *name) const; - TGeoElement *GetElement(Int_t z) {return (TGeoElement*)fList->At(z);} - TGeoElementRN *GetElementRN(Int_t ENDFcode) const; - TGeoElementRN *GetElementRN(Int_t a, Int_t z, Int_t iso=0) const; - TObjArray *GetElementsRN() const {return fListRN;} - Bool_t HasDefaultElements() const {return TObject::TestBit(kETDefaultElements);} - Bool_t HasRNElements() const {return TObject::TestBit(kETRNElements);} - - Int_t GetNelements() const {return fNelements;} - Int_t GetNelementsRN() const {return fNelementsRN;} - void ExportElementsRN(const char *filename=""); - virtual void Print(Option_t *option = "") const; - - ClassDef(TGeoElementTable,4) // table of elements + enum EGeoETStatus { kETDefaultElements = BIT(14), kETRNElements = BIT(15) }; + void AddElement(const char *name, const char *title, Int_t z, Double_t a); + void AddElement(const char *name, const char *title, Int_t z, Int_t n, Double_t a); + void AddElement(TGeoElement *elem); + void AddElementRN(TGeoElementRN *elem); + void AddIsotope(TGeoIsotope *isotope); + void BuildDefaultElements(); + void ImportElementsRN(); + Bool_t CheckTable() const; + TGeoElement *FindElement(const char *name) const; + TGeoIsotope *FindIsotope(const char *name) const; + TGeoElement *GetElement(Int_t z) { return (TGeoElement *)fList->At(z); } + TGeoElementRN *GetElementRN(Int_t ENDFcode) const; + TGeoElementRN *GetElementRN(Int_t a, Int_t z, Int_t iso = 0) const; + TObjArray *GetElementsRN() const { return fListRN; } + Bool_t HasDefaultElements() const { return TObject::TestBit(kETDefaultElements); } + Bool_t HasRNElements() const { return TObject::TestBit(kETRNElements); } + + Int_t GetNelements() const { return fNelements; } + Int_t GetNelementsRN() const { return fNelementsRN; } + void ExportElementsRN(const char *filename = ""); + void Print(Option_t *option = "") const override; + + ClassDefOverride(TGeoElementTable, 4) // table of elements }; #endif - diff --git a/geom/geom/inc/TGeoEltu.h b/geom/geom/inc/TGeoEltu.h index 15eb0843b586d..de12d8de90182 100644 --- a/geom/geom/inc/TGeoEltu.h +++ b/geom/geom/inc/TGeoEltu.h @@ -14,10 +14,9 @@ #include "TGeoTube.h" -class TGeoEltu : public TGeoTube -{ - TGeoEltu(const TGeoEltu&) = delete; - TGeoEltu& operator=(const TGeoEltu&) = delete; +class TGeoEltu : public TGeoTube { + TGeoEltu(const TGeoEltu &) = delete; + TGeoEltu &operator=(const TGeoEltu &) = delete; public: // constructors @@ -26,44 +25,44 @@ class TGeoEltu : public TGeoTube TGeoEltu(const char *name, Double_t a, Double_t b, Double_t dz); TGeoEltu(Double_t *params); // destructor - virtual ~TGeoEltu(); + ~TGeoEltu() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetA() const {return fRmin;} - virtual Double_t GetB() const {return fRmax;} - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetEltuDimensions(Double_t a, Double_t b, Double_t dz); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - - ClassDef(TGeoEltu, 1) // elliptical tube class + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + virtual Double_t GetA() const { return fRmin; } + virtual Double_t GetB() const { return fRmax; } + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetEltuDimensions(Double_t a, Double_t b, Double_t dz); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + ClassDefOverride(TGeoEltu, 1) // elliptical tube class }; - #endif diff --git a/geom/geom/inc/TGeoExtension.h b/geom/geom/inc/TGeoExtension.h index c16dcd59adce8..67aba6f0a15c9 100644 --- a/geom/geom/inc/TGeoExtension.h +++ b/geom/geom/inc/TGeoExtension.h @@ -16,11 +16,10 @@ #include "TObject.h" -class TGeoExtension : public TObject -{ +class TGeoExtension : public TObject { protected: TGeoExtension() : TObject() {} - virtual ~TGeoExtension() {} + ~TGeoExtension() override {} public: // Method called whenever requiring a pointer to the extension @@ -28,34 +27,43 @@ class TGeoExtension : public TObject virtual TGeoExtension *Grab() = 0; // Method called always when the pointer to the extension is not needed // Equivalent to delete() - virtual void Release() const = 0; + virtual void Release() const = 0; - ClassDef(TGeoExtension, 1) // User extension for volumes and nodes + ClassDefOverride(TGeoExtension, 1) // User extension for volumes and nodes }; -class TGeoRCExtension : public TGeoExtension -{ +class TGeoRCExtension : public TGeoExtension { protected: - virtual ~TGeoRCExtension() {delete fUserObject;} + ~TGeoRCExtension() override { delete fUserObject; } + public: TGeoRCExtension() : TGeoExtension(), fRC(0), fUserObject(nullptr) { fRC++; } TGeoRCExtension(TObject *obj) : TGeoExtension(), fRC(0), fUserObject(obj) { fRC++; } - TGeoExtension *Grab() override { fRC++; return this; } - void Release() const override { assert(fRC > 0); fRC--; if (fRC==0) delete this; } - - void SetUserObject(TObject *obj) { fUserObject = obj; } - TObject *GetUserObject() const { return fUserObject; } + TGeoExtension *Grab() override + { + fRC++; + return this; + } + void Release() const override + { + assert(fRC > 0); + fRC--; + if (fRC == 0) + delete this; + } + void SetUserObject(TObject *obj) { fUserObject = obj; } + TObject *GetUserObject() const { return fUserObject; } private: // Copy constructor and assignment not allowed TGeoRCExtension(const TGeoRCExtension &) = delete; - TGeoRCExtension &operator =(const TGeoRCExtension &) = delete; - mutable Int_t fRC{0}; // Reference counter - TObject *fUserObject{nullptr}; // Attached user object + TGeoRCExtension &operator=(const TGeoRCExtension &) = delete; + mutable Int_t fRC{0}; // Reference counter + TObject *fUserObject{nullptr}; // Attached user object - ClassDefOverride(TGeoRCExtension, 1) // Reference counted extension for volumes and nodes + ClassDefOverride(TGeoRCExtension, 1) // Reference counted extension for volumes and nodes }; #endif diff --git a/geom/geom/inc/TGeoGlobalMagField.h b/geom/geom/inc/TGeoGlobalMagField.h index 6911f2272d5af..23f70f1637511 100644 --- a/geom/geom/inc/TGeoGlobalMagField.h +++ b/geom/geom/inc/TGeoGlobalMagField.h @@ -15,36 +15,39 @@ #include "TVirtualMagField.h" -class TGeoGlobalMagField : public TObject -{ +class TGeoGlobalMagField : public TObject { private: - static TGeoGlobalMagField *fgInstance; // Static pointer to the field manager; - TVirtualMagField *fField{nullptr}; // Magnetic field - Bool_t fLock{kFALSE}; // Lock flag for global field. + static TGeoGlobalMagField *fgInstance; // Static pointer to the field manager; + TVirtualMagField *fField{nullptr}; // Magnetic field + Bool_t fLock{kFALSE}; // Lock flag for global field. protected: - TGeoGlobalMagField(const TGeoGlobalMagField&) = delete; - TGeoGlobalMagField& operator=(const TGeoGlobalMagField&) = delete; - void Unlock() {fLock = kFALSE;} + TGeoGlobalMagField(const TGeoGlobalMagField &) = delete; + TGeoGlobalMagField &operator=(const TGeoGlobalMagField &) = delete; + void Unlock() { fLock = kFALSE; } public: TGeoGlobalMagField(); - virtual ~TGeoGlobalMagField(); + ~TGeoGlobalMagField() override; // Using SetField() makes a given field global. The field manager owns it from now on. - TVirtualMagField *GetField() const {return fField;} - void SetField(TVirtualMagField *field); - Bool_t IsLocked() {return fLock;} - void Lock(); + TVirtualMagField *GetField() const { return fField; } + void SetField(TVirtualMagField *field); + Bool_t IsLocked() { return fLock; } + void Lock(); // The field manager should be accessed via TGeoGlobalMagField::Instance() static TGeoGlobalMagField *Instance(); static TGeoGlobalMagField *GetInstance(); // Inline access to Field() method - void Field(const Double_t *x, Double_t *B) {if (fField) fField->Field(x,B);} + void Field(const Double_t *x, Double_t *B) + { + if (fField) + fField->Field(x, B); + } - ClassDef(TGeoGlobalMagField, 0) // Global field manager + ClassDefOverride(TGeoGlobalMagField, 0) // Global field manager }; #endif diff --git a/geom/geom/inc/TGeoHalfSpace.h b/geom/geom/inc/TGeoHalfSpace.h index 304142ad39544..787613a01b250 100644 --- a/geom/geom/inc/TGeoHalfSpace.h +++ b/geom/geom/inc/TGeoHalfSpace.h @@ -14,14 +14,13 @@ #include "TGeoBBox.h" -class TGeoHalfSpace : public TGeoBBox -{ +class TGeoHalfSpace : public TGeoBBox { private: - Double_t fP[3]; - Double_t fN[3]; + Double_t fP[3]; + Double_t fN[3]; - TGeoHalfSpace(const TGeoHalfSpace&) = delete; - TGeoHalfSpace& operator=(const TGeoHalfSpace&) = delete; + TGeoHalfSpace(const TGeoHalfSpace &) = delete; + TGeoHalfSpace &operator=(const TGeoHalfSpace &) = delete; public: // constructors @@ -29,41 +28,42 @@ class TGeoHalfSpace : public TGeoBBox TGeoHalfSpace(const char *name, Double_t *p, Double_t *n); TGeoHalfSpace(Double_t *params); // destructor - virtual ~TGeoHalfSpace(); + ~TGeoHalfSpace() override; // methods - virtual Double_t Capacity() const {return 0.;} - virtual void ComputeBBox() {} - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t *GetPoint() {return fP;} - virtual Double_t *GetNorm() {return fN;} - virtual void GetBoundingCylinder(Double_t * /*param*/) const {} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const {return 0;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t * /*points*/) const {} - virtual void SetPoints(Float_t * /*points*/) const {} - virtual void Sizeof3D() const {} + Double_t Capacity() const override { return 0.; } + void ComputeBBox() override {} + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + virtual Double_t *GetPoint() { return fP; } + virtual Double_t *GetNorm() { return fN; } + void GetBoundingCylinder(Double_t * /*param*/) const override {} + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override { return 0; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t * /*points*/) const override {} + void SetPoints(Float_t * /*points*/) const override {} + void Sizeof3D() const override {} - ClassDef(TGeoHalfSpace, 1) // half-space class + ClassDefOverride(TGeoHalfSpace, 1) // half-space class }; - #endif diff --git a/geom/geom/inc/TGeoHelix.h b/geom/geom/inc/TGeoHelix.h index a808525a5e06a..32bb9d88d534a 100644 --- a/geom/geom/inc/TGeoHelix.h +++ b/geom/geom/inc/TGeoHelix.h @@ -12,68 +12,65 @@ #ifndef ROOT_TGeoHelix #define ROOT_TGeoHelix - #include "TObject.h" class TGeoHMatrix; -class TGeoHelix : public TObject -{ -private : - Double_t fC; // curvature in XY plane - Double_t fS; // Z step of the helix / 2*PI - Double_t fStep; // current step - Double_t fPhi; // phi angle - Double_t fPointInit[3]; // initial point - Double_t fDirInit[3]; // normalized initial direction - Double_t fPoint[3]; // point after a step - Double_t fDir[3]; // direction after a step - Double_t fB[3]; // normalized direction for magnetic field - Int_t fQ; // right/left-handed (+/- 1) - "charge" - TGeoHMatrix *fMatrix{nullptr}; // transformation of local helix frame to MARS +class TGeoHelix : public TObject { +private: + Double_t fC; // curvature in XY plane + Double_t fS; // Z step of the helix / 2*PI + Double_t fStep; // current step + Double_t fPhi; // phi angle + Double_t fPointInit[3]; // initial point + Double_t fDirInit[3]; // normalized initial direction + Double_t fPoint[3]; // point after a step + Double_t fDir[3]; // direction after a step + Double_t fB[3]; // normalized direction for magnetic field + Int_t fQ; // right/left-handed (+/- 1) - "charge" + TGeoHMatrix *fMatrix{nullptr}; // transformation of local helix frame to MARS + + TGeoHelix(const TGeoHelix &) = delete; + TGeoHelix &operator=(const TGeoHelix &) = delete; - TGeoHelix(const TGeoHelix&) = delete; - TGeoHelix &operator=(const TGeoHelix&) = delete; public: - enum EGeoHelixTypes { - kHelixNeedUpdate = BIT(16), - kHelixStraight = BIT(17), - kHelixCircle = BIT(18) - }; + enum EGeoHelixTypes { kHelixNeedUpdate = BIT(16), kHelixStraight = BIT(17), kHelixCircle = BIT(18) }; // constructors TGeoHelix(); - TGeoHelix(Double_t curvature, Double_t step, Int_t charge=1); + TGeoHelix(Double_t curvature, Double_t step, Int_t charge = 1); // destructor - virtual ~TGeoHelix(); - - void InitPoint(Double_t x0, Double_t y0, Double_t z0); - void InitPoint(Double_t *point); - void InitDirection(Double_t dirx, Double_t diry, Double_t dirz, Bool_t is_normalized=kTRUE); - void InitDirection(Double_t *dir, Bool_t is_normalized=kTRUE); - - Double_t ComputeSafeStep(Double_t epsil=1E-6) const; - const Double_t *GetCurrentPoint() const {return fPoint;} - const Double_t *GetCurrentDirection() const {return fDir;} - Double_t GetXYcurvature() const {return fC;} - Double_t GetStep() const {return fStep;} - Double_t GetTotalCurvature() const; - Bool_t IsRightHanded() const {return (fQ>0)?kFALSE:kTRUE;} // a positive charge in B field makes a left-handed helix - - void ResetStep(); - Double_t StepToPlane(Double_t *point, Double_t *norm); -// Double_t *StepToPlane(Double_t a, Double_t b, Double_t c); - - void SetCharge(Int_t charge); - void SetXYcurvature(Double_t curvature); - void SetField(Double_t bx, Double_t by, Double_t bz, Bool_t is_normalized=kTRUE); - void SetHelixStep(Double_t hstep); - - void Step(Double_t step); - - void UpdateHelix(); - - ClassDef(TGeoHelix, 1) // helix class + ~TGeoHelix() override; + + void InitPoint(Double_t x0, Double_t y0, Double_t z0); + void InitPoint(Double_t *point); + void InitDirection(Double_t dirx, Double_t diry, Double_t dirz, Bool_t is_normalized = kTRUE); + void InitDirection(Double_t *dir, Bool_t is_normalized = kTRUE); + + Double_t ComputeSafeStep(Double_t epsil = 1E-6) const; + const Double_t *GetCurrentPoint() const { return fPoint; } + const Double_t *GetCurrentDirection() const { return fDir; } + Double_t GetXYcurvature() const { return fC; } + Double_t GetStep() const { return fStep; } + Double_t GetTotalCurvature() const; + Bool_t IsRightHanded() const + { + return (fQ > 0) ? kFALSE : kTRUE; + } // a positive charge in B field makes a left-handed helix + + void ResetStep(); + Double_t StepToPlane(Double_t *point, Double_t *norm); + // Double_t *StepToPlane(Double_t a, Double_t b, Double_t c); + + void SetCharge(Int_t charge); + void SetXYcurvature(Double_t curvature); + void SetField(Double_t bx, Double_t by, Double_t bz, Bool_t is_normalized = kTRUE); + void SetHelixStep(Double_t hstep); + + void Step(Double_t step); + + void UpdateHelix(); + + ClassDefOverride(TGeoHelix, 1) // helix class }; #endif - diff --git a/geom/geom/inc/TGeoHype.h b/geom/geom/inc/TGeoHype.h index 2d32dc7c57ee8..6e4987f718640 100644 --- a/geom/geom/inc/TGeoHype.h +++ b/geom/geom/inc/TGeoHype.h @@ -14,25 +14,24 @@ #include "TGeoTube.h" -class TGeoHype : public TGeoTube -{ -protected : -// data members inherited from TGeoTube: -// Double_t fRmin; // inner radius at z=0 -// Double_t fRmax; // outer radius at z=0 -// Double_t fDz; // half length - Double_t fStIn; // Stereo angle for inner surface - Double_t fStOut; // Stereo angle for inner surface +class TGeoHype : public TGeoTube { +protected: + // data members inherited from TGeoTube: + // Double_t fRmin; // inner radius at z=0 + // Double_t fRmax; // outer radius at z=0 + // Double_t fDz; // half length + Double_t fStIn; // Stereo angle for inner surface + Double_t fStOut; // Stereo angle for inner surface -private : -// Precomputed parameters: - Double_t fTin; // Tangent of stereo angle for inner surface - Double_t fTout; // Tangent of stereo angle for outer surface - Double_t fTinsq; // Squared tangent of stereo angle for inner surface - Double_t fToutsq; // Squared tangent of stereo angle for outer surface +private: + // Precomputed parameters: + Double_t fTin; // Tangent of stereo angle for inner surface + Double_t fTout; // Tangent of stereo angle for outer surface + Double_t fTinsq; // Squared tangent of stereo angle for inner surface + Double_t fToutsq; // Squared tangent of stereo angle for outer surface - TGeoHype(const TGeoHype&) = delete; - TGeoHype& operator=(const TGeoHype&) = delete; + TGeoHype(const TGeoHype &) = delete; + TGeoHype &operator=(const TGeoHype &) = delete; public: // constructors @@ -41,55 +40,56 @@ private : TGeoHype(const char *name, Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz); TGeoHype(Double_t *params); // destructor - virtual ~TGeoHype(); + ~TGeoHype() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - Int_t DistToHype(const Double_t *point, const Double_t *dir, Double_t *s, Bool_t inner, Bool_t in) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 64;} - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - Double_t GetStIn() const {return fStIn;} - Double_t GetStOut() const {return fStOut;} - Bool_t HasInner() const {return !TestShapeBit(kGeoRSeg);} - Double_t RadiusHypeSq(Double_t z, Bool_t inner) const; - Double_t ZHypeSq(Double_t r, Bool_t inner) const; - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - //virtual void Paint(Option_t *option); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - Double_t SafetyToHype(const Double_t *point, Bool_t inner, Bool_t in) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetHypeDimensions(Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoHype, 1) // hyperboloid class + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Int_t DistToHype(const Double_t *point, const Double_t *dir, Double_t *s, Bool_t inner, Bool_t in) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 64; } + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Double_t GetStIn() const { return fStIn; } + Double_t GetStOut() const { return fStOut; } + Bool_t HasInner() const { return !TestShapeBit(kGeoRSeg); } + Double_t RadiusHypeSq(Double_t z, Bool_t inner) const; + Double_t ZHypeSq(Double_t r, Bool_t inner) const; + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + // virtual void Paint(Option_t *option); + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + Double_t SafetyToHype(const Double_t *point, Bool_t inner, Bool_t in) const; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetHypeDimensions(Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; + ClassDefOverride(TGeoHype, 1) // hyperboloid class }; #endif diff --git a/geom/geom/inc/TGeoManager.h b/geom/geom/inc/TGeoManager.h index 90508c5c0bb75..1a9a7950aae23 100644 --- a/geom/geom/inc/TGeoManager.h +++ b/geom/geom/inc/TGeoManager.h @@ -41,565 +41,570 @@ class TGeoOpticalSurface; class TGeoSkinSurface; class TGeoBorderSurface; -class TGeoManager : public TNamed -{ +class TGeoManager : public TNamed { public: - enum EDefaultUnits { - kG4Units = 0, - kRootUnits = 1 - }; + enum EDefaultUnits { kG4Units = 0, kRootUnits = 1 }; protected: - static std::mutex fgMutex; //! mutex for navigator booking in MT mode - static Bool_t fgLock; //! Lock preventing a second geometry to be loaded - static Int_t fgVerboseLevel; //! Verbosity level for Info messages (no IO). - static Int_t fgMaxLevel; //! Maximum level in geometry - static Int_t fgMaxDaughters; //! Maximum number of daughters - static Int_t fgMaxXtruVert; //! Maximum number of Xtru vertices - static UInt_t fgExportPrecision; //! Precision to be used in ASCII exports - static EDefaultUnits fgDefaultUnits; //! Default units in GDML if not explicit in some tags - - TGeoManager(const TGeoManager&) = delete; - TGeoManager& operator=(const TGeoManager&) = delete; - -private : - Double_t fPhimin; //! lowest range for phi cut - Double_t fPhimax; //! highest range for phi cut - Double_t fTmin; //! lower time limit for tracks drawing - Double_t fTmax; //! upper time limit for tracks drawing - Int_t fNNodes; // total number of physical nodes - TString fPath; //! path to current node - TString fParticleName; //! particles to be drawn - Double_t fVisDensity; // transparency threshold by density - Int_t fExplodedView; // exploded view mode - Int_t fVisOption; // global visualization option - Int_t fVisLevel; // maximum visualization depth - Int_t fNsegments; // number of segments to approximate circles - Int_t fNtracks; // number of tracks - Int_t fMaxVisNodes; // maximum number of visible nodes - TVirtualGeoTrack *fCurrentTrack; //! current track - Int_t fNpdg; // number of different pdg's stored - Int_t fPdgId[1024]; // pdg conversion table - Bool_t fClosed; //! flag that geometry is closed - Bool_t fLoopVolumes; //! flag volume lists loop - Bool_t fStreamVoxels; // flag to allow voxelization I/O - Bool_t fIsGeomReading; //! flag set when reading geometry - Bool_t fIsGeomCleaning; //! flag to notify that the manager is being destructed - Bool_t fPhiCut; // flag for phi cuts - Bool_t fTimeCut; // time cut for tracks - Bool_t fDrawExtra; //! flag that the list of physical nodes has to be drawn - Bool_t fMatrixTransform; //! flag for using GL matrix - Bool_t fMatrixReflection; //! flag for GL reflections - Bool_t fActivity; //! switch ON/OFF volume activity (default OFF - all volumes active)) - Bool_t fIsNodeSelectable; //! flag that nodes are the selected objects in pad rather than volumes - TVirtualGeoPainter *fPainter; //! current painter - - TObjArray *fMatrices; //-> list of local transformations - TObjArray *fShapes; //-> list of shapes - TObjArray *fVolumes; //-> list of volumes - TObjArray *fPhysicalNodes; //-> list of physical nodes - TObjArray *fGShapes; //! list of runtime shapes - TObjArray *fGVolumes; //! list of runtime volumes - TObjArray *fTracks; //-> list of tracks attached to geometry - TObjArray *fPdgNames; //-> list of pdg names for tracks - TObjArray *fGDMLMatrices; //-> list of matrices read from GDML - TObjArray *fOpticalSurfaces; //-> list of optical surfaces read from GDML - TObjArray *fSkinSurfaces; //-> list of skin surfaces read from GDML - TObjArray *fBorderSurfaces; //-> list of border surfaces read from GDML - TList *fMaterials; //-> list of materials - TList *fMedia; //-> list of tracking media - TObjArray *fNodes; //-> current branch of nodes - TObjArray *fOverlaps; //-> list of geometrical overlaps - TObjArray *fRegions; //-> list of regions - UChar_t *fBits; //! bits used for voxelization + static std::mutex fgMutex; //! mutex for navigator booking in MT mode + static Bool_t fgLock; //! Lock preventing a second geometry to be loaded + static Int_t fgVerboseLevel; //! Verbosity level for Info messages (no IO). + static Int_t fgMaxLevel; //! Maximum level in geometry + static Int_t fgMaxDaughters; //! Maximum number of daughters + static Int_t fgMaxXtruVert; //! Maximum number of Xtru vertices + static UInt_t fgExportPrecision; //! Precision to be used in ASCII exports + static EDefaultUnits fgDefaultUnits; //! Default units in GDML if not explicit in some tags + + TGeoManager(const TGeoManager &) = delete; + TGeoManager &operator=(const TGeoManager &) = delete; + +private: + Double_t fPhimin; //! lowest range for phi cut + Double_t fPhimax; //! highest range for phi cut + Double_t fTmin; //! lower time limit for tracks drawing + Double_t fTmax; //! upper time limit for tracks drawing + Int_t fNNodes; // total number of physical nodes + TString fPath; //! path to current node + TString fParticleName; //! particles to be drawn + Double_t fVisDensity; // transparency threshold by density + Int_t fExplodedView; // exploded view mode + Int_t fVisOption; // global visualization option + Int_t fVisLevel; // maximum visualization depth + Int_t fNsegments; // number of segments to approximate circles + Int_t fNtracks; // number of tracks + Int_t fMaxVisNodes; // maximum number of visible nodes + TVirtualGeoTrack *fCurrentTrack; //! current track + Int_t fNpdg; // number of different pdg's stored + Int_t fPdgId[1024]; // pdg conversion table + Bool_t fClosed; //! flag that geometry is closed + Bool_t fLoopVolumes; //! flag volume lists loop + Bool_t fStreamVoxels; // flag to allow voxelization I/O + Bool_t fIsGeomReading; //! flag set when reading geometry + Bool_t fIsGeomCleaning; //! flag to notify that the manager is being destructed + Bool_t fPhiCut; // flag for phi cuts + Bool_t fTimeCut; // time cut for tracks + Bool_t fDrawExtra; //! flag that the list of physical nodes has to be drawn + Bool_t fMatrixTransform; //! flag for using GL matrix + Bool_t fMatrixReflection; //! flag for GL reflections + Bool_t fActivity; //! switch ON/OFF volume activity (default OFF - all volumes active)) + Bool_t fIsNodeSelectable; //! flag that nodes are the selected objects in pad rather than volumes + TVirtualGeoPainter *fPainter; //! current painter + + TObjArray *fMatrices; //-> list of local transformations + TObjArray *fShapes; //-> list of shapes + TObjArray *fVolumes; //-> list of volumes + TObjArray *fPhysicalNodes; //-> list of physical nodes + TObjArray *fGShapes; //! list of runtime shapes + TObjArray *fGVolumes; //! list of runtime volumes + TObjArray *fTracks; //-> list of tracks attached to geometry + TObjArray *fPdgNames; //-> list of pdg names for tracks + TObjArray *fGDMLMatrices; //-> list of matrices read from GDML + TObjArray *fOpticalSurfaces; //-> list of optical surfaces read from GDML + TObjArray *fSkinSurfaces; //-> list of skin surfaces read from GDML + TObjArray *fBorderSurfaces; //-> list of border surfaces read from GDML + TList *fMaterials; //-> list of materials + TList *fMedia; //-> list of tracking media + TObjArray *fNodes; //-> current branch of nodes + TObjArray *fOverlaps; //-> list of geometrical overlaps + TObjArray *fRegions; //-> list of regions + UChar_t *fBits; //! bits used for voxelization // Map of navigator arrays per thread - typedef std::map NavigatorsMap_t; - typedef NavigatorsMap_t::iterator NavigatorsMapIt_t; - typedef std::map ThreadsMap_t; - typedef ThreadsMap_t::const_iterator ThreadsMapIt_t; + typedef std::map NavigatorsMap_t; + typedef NavigatorsMap_t::iterator NavigatorsMapIt_t; + typedef std::map ThreadsMap_t; + typedef ThreadsMap_t::const_iterator ThreadsMapIt_t; // Map of constant properties - typedef std::map ConstPropMap_t; - - NavigatorsMap_t fNavigators; //! Map between thread id's and navigator arrays - static ThreadsMap_t *fgThreadId; //! Thread id's map - static Int_t fgNumThreads; //! Number of registered threads - static Bool_t fgLockNavigators; //! Lock existing navigators - TGeoNavigator *fCurrentNavigator; //! current navigator - TGeoVolume *fCurrentVolume; //! current volume - TGeoVolume *fTopVolume; //! top level volume in geometry - TGeoNode *fTopNode; //! top physical node - TGeoVolume *fMasterVolume; // master volume - TGeoHMatrix *fGLMatrix; // matrix to be used for view transformations - TObjArray *fUniqueVolumes; //-> list of unique volumes - TGeoShape *fClippingShape; //! clipping shape for raytracing - TGeoElementTable *fElementTable; //! table of elements - - Int_t fNLevel; // maximum accepted level in geometry - TGeoVolume *fPaintVolume; //! volume currently painted - TGeoVolume *fUserPaintVolume; //! - THashList *fHashVolumes; //! hash list of volumes providing fast search - THashList *fHashGVolumes; //! hash list of group volumes providing fast search - THashList *fHashPNE; //-> hash list of physical node entries - mutable TObjArray *fArrayPNE; //! array of physical node entries - Int_t fSizePNEId; // size of the array of unique ID's for PN entries - Int_t fNPNEId; // number of PN entries having a unique ID - Int_t *fKeyPNEId; //[fSizePNEId] array of uid values for PN entries - Int_t *fValuePNEId; //[fSizePNEId] array of pointers to PN entries with ID's - Int_t fMaxThreads; //! Max number of threads - Bool_t fMultiThread; //! Flag for multi-threading - Int_t fRaytraceMode; //! Raytrace mode: 0=normal, 1=pass through, 2=transparent - Bool_t fUsePWNav; // Activate usage of parallel world in navigation - TGeoParallelWorld *fParallelWorld; // Parallel world - ConstPropMap_t fProperties; // Map of user-defined constant properties -//--- private methods - Bool_t IsLoopingVolumes() const {return fLoopVolumes;} - void Init(); - Bool_t InitArrayPNE() const; - Bool_t InsertPNEId(Int_t uid, Int_t ientry); - void SetLoopVolumes(Bool_t flag=kTRUE) {fLoopVolumes=flag;} - void UpdateElements(); - void Voxelize(Option_t *option = nullptr); + typedef std::map ConstPropMap_t; + + NavigatorsMap_t fNavigators; //! Map between thread id's and navigator arrays + static ThreadsMap_t *fgThreadId; //! Thread id's map + static Int_t fgNumThreads; //! Number of registered threads + static Bool_t fgLockNavigators; //! Lock existing navigators + TGeoNavigator *fCurrentNavigator; //! current navigator + TGeoVolume *fCurrentVolume; //! current volume + TGeoVolume *fTopVolume; //! top level volume in geometry + TGeoNode *fTopNode; //! top physical node + TGeoVolume *fMasterVolume; // master volume + TGeoHMatrix *fGLMatrix; // matrix to be used for view transformations + TObjArray *fUniqueVolumes; //-> list of unique volumes + TGeoShape *fClippingShape; //! clipping shape for raytracing + TGeoElementTable *fElementTable; //! table of elements + + Int_t fNLevel; // maximum accepted level in geometry + TGeoVolume *fPaintVolume; //! volume currently painted + TGeoVolume *fUserPaintVolume; //! + THashList *fHashVolumes; //! hash list of volumes providing fast search + THashList *fHashGVolumes; //! hash list of group volumes providing fast search + THashList *fHashPNE; //-> hash list of physical node entries + mutable TObjArray *fArrayPNE; //! array of physical node entries + Int_t fSizePNEId; // size of the array of unique ID's for PN entries + Int_t fNPNEId; // number of PN entries having a unique ID + Int_t *fKeyPNEId; //[fSizePNEId] array of uid values for PN entries + Int_t *fValuePNEId; //[fSizePNEId] array of pointers to PN entries with ID's + Int_t fMaxThreads; //! Max number of threads + Bool_t fMultiThread; //! Flag for multi-threading + Int_t fRaytraceMode; //! Raytrace mode: 0=normal, 1=pass through, 2=transparent + Bool_t fUsePWNav; // Activate usage of parallel world in navigation + TGeoParallelWorld *fParallelWorld; // Parallel world + ConstPropMap_t fProperties; // Map of user-defined constant properties + //--- private methods + Bool_t IsLoopingVolumes() const { return fLoopVolumes; } + void Init(); + Bool_t InitArrayPNE() const; + Bool_t InsertPNEId(Int_t uid, Int_t ientry); + void SetLoopVolumes(Bool_t flag = kTRUE) { fLoopVolumes = flag; } + void UpdateElements(); + void Voxelize(Option_t *option = nullptr); public: // constructors TGeoManager(); TGeoManager(const char *name, const char *title); // destructor - virtual ~TGeoManager(); + ~TGeoManager() override; //--- adding geometrical objects - Int_t AddMaterial(const TGeoMaterial *material); - Int_t AddOverlap(const TNamed *ovlp); - Int_t AddRegion(TGeoRegion *region); - Int_t AddTransformation(const TGeoMatrix *matrix); - Int_t AddShape(const TGeoShape *shape); - Int_t AddTrack(Int_t id, Int_t pdgcode, TObject *particle=nullptr); - Int_t AddTrack(TVirtualGeoTrack *track); - Int_t AddVolume(TGeoVolume *volume); - TGeoNavigator *AddNavigator(); - Bool_t AddProperty(const char *property, Double_t value); - Double_t GetProperty(const char *name, Bool_t *error = nullptr) const; - Double_t GetProperty(size_t i, TString &name, Bool_t *error = nullptr) const; - Int_t GetNproperties() const { return fProperties.size(); } - void ClearOverlaps(); - void RegisterMatrix(const TGeoMatrix *matrix); - void SortOverlaps(); + Int_t AddMaterial(const TGeoMaterial *material); + Int_t AddOverlap(const TNamed *ovlp); + Int_t AddRegion(TGeoRegion *region); + Int_t AddTransformation(const TGeoMatrix *matrix); + Int_t AddShape(const TGeoShape *shape); + Int_t AddTrack(Int_t id, Int_t pdgcode, TObject *particle = nullptr); + Int_t AddTrack(TVirtualGeoTrack *track); + Int_t AddVolume(TGeoVolume *volume); + TGeoNavigator *AddNavigator(); + Bool_t AddProperty(const char *property, Double_t value); + Double_t GetProperty(const char *name, Bool_t *error = nullptr) const; + Double_t GetProperty(size_t i, TString &name, Bool_t *error = nullptr) const; + Int_t GetNproperties() const { return fProperties.size(); } + void ClearOverlaps(); + void RegisterMatrix(const TGeoMatrix *matrix); + void SortOverlaps(); //--- browsing and tree navigation - void Browse(TBrowser *b); - void SetVisibility(TObject *obj, Bool_t vis); - virtual Bool_t cd(const char *path=""); // *MENU* - Bool_t CheckPath(const char *path) const; - void CdNode(Int_t nodeid); - void CdDown(Int_t index); - void CdUp(); - void CdTop(); - void CdNext(); - void GetBranchNames(Int_t *names) const; - void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; - void GetBranchOnlys(Int_t *isonly) const; - Int_t GetNmany() const {return GetCurrentNavigator()->GetNmany();} - const char *GetPdgName(Int_t pdg) const; - void SetPdgName(Int_t pdg, const char *name); - Bool_t IsFolder() const { return kTRUE; } + void Browse(TBrowser *b) override; + void SetVisibility(TObject *obj, Bool_t vis); + virtual Bool_t cd(const char *path = ""); // *MENU* + Bool_t CheckPath(const char *path) const; + void CdNode(Int_t nodeid); + void CdDown(Int_t index); + void CdUp(); + void CdTop(); + void CdNext(); + void GetBranchNames(Int_t *names) const; + void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; + void GetBranchOnlys(Int_t *isonly) const; + Int_t GetNmany() const { return GetCurrentNavigator()->GetNmany(); } + const char *GetPdgName(Int_t pdg) const; + void SetPdgName(Int_t pdg, const char *name); + Bool_t IsFolder() const override { return kTRUE; } //--- visualization settings - virtual void Edit(Option_t *option=""); // *MENU* - void BombTranslation(const Double_t *tr, Double_t *bombtr); - void UnbombTranslation(const Double_t *tr, Double_t *bombtr); - void ClearAttributes(); // *MENU* - void DefaultAngles(); // *MENU* - void DefaultColors(); // *MENU* - TGeoShape *GetClippingShape() const {return fClippingShape;} - Int_t GetNsegments() const; - TVirtualGeoPainter *GetGeomPainter(); - TVirtualGeoPainter *GetPainter() const {return fPainter;} - Int_t GetBombMode() const {return fExplodedView;} - void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const; - Int_t GetMaxVisNodes() const {return fMaxVisNodes;} - Bool_t GetTminTmax(Double_t &tmin, Double_t &tmax) const; - Double_t GetTmax() const {return fTmax;} - TGeoVolume *GetPaintVolume() const {return fPaintVolume;} - TGeoVolume *GetUserPaintVolume() const {return fUserPaintVolume;} - Double_t GetVisDensity() const {return fVisDensity;} - Int_t GetVisLevel() const; - Int_t GetVisOption() const; - Bool_t IsInPhiRange() const; - Bool_t IsDrawingExtra() const {return fDrawExtra;} - Bool_t IsNodeSelectable() const {return fIsNodeSelectable;} - Bool_t IsVisLeaves() const {return fVisOption==1;} - void ModifiedPad() const; - void OptimizeVoxels(const char *filename="tgeovox.C"); // *MENU* - void SetClipping(Bool_t flag=kTRUE) {SetClippingShape(flag?fClippingShape:nullptr);} // *MENU* - void SetClippingShape(TGeoShape *clip); - void SetExplodedView(Int_t iopt=0); // *MENU* - void SetPhiRange(Double_t phimin=0., Double_t phimax=360.); - void SetNsegments(Int_t nseg); // *MENU* - Bool_t SetCurrentNavigator(Int_t index); - void SetBombFactors(Double_t bombx=1.3, Double_t bomby=1.3, Double_t bombz=1.3, Double_t bombr=1.3); // *MENU* - void SetPaintVolume(TGeoVolume *vol) {fPaintVolume = vol;} - void SetUserPaintVolume(TGeoVolume *vol) {fUserPaintVolume = vol;} - void SetTopVisible(Bool_t vis=kTRUE); - void SetTminTmax(Double_t tmin=0, Double_t tmax=999); - void SetDrawExtraPaths(Bool_t flag=kTRUE) {fDrawExtra=flag;} - void SetNodeSelectable(Bool_t flag=kTRUE) {fIsNodeSelectable=flag;} - void SetVisDensity(Double_t dens=0.01); // *MENU* - void SetVisLevel(Int_t level=3); // *MENU* - void SetVisOption(Int_t option=0); - void ViewLeaves(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsVisLeaves - void SaveAttributes(const char *filename="tgeoatt.C"); // *MENU* - void RestoreMasterVolume(); // *MENU* - void SetMaxVisNodes(Int_t maxnodes=10000); // *MENU* + virtual void Edit(Option_t *option = ""); // *MENU* + void BombTranslation(const Double_t *tr, Double_t *bombtr); + void UnbombTranslation(const Double_t *tr, Double_t *bombtr); + void ClearAttributes(); // *MENU* + void DefaultAngles(); // *MENU* + void DefaultColors(); // *MENU* + TGeoShape *GetClippingShape() const { return fClippingShape; } + Int_t GetNsegments() const; + TVirtualGeoPainter *GetGeomPainter(); + TVirtualGeoPainter *GetPainter() const { return fPainter; } + Int_t GetBombMode() const { return fExplodedView; } + void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const; + Int_t GetMaxVisNodes() const { return fMaxVisNodes; } + Bool_t GetTminTmax(Double_t &tmin, Double_t &tmax) const; + Double_t GetTmax() const { return fTmax; } + TGeoVolume *GetPaintVolume() const { return fPaintVolume; } + TGeoVolume *GetUserPaintVolume() const { return fUserPaintVolume; } + Double_t GetVisDensity() const { return fVisDensity; } + Int_t GetVisLevel() const; + Int_t GetVisOption() const; + Bool_t IsInPhiRange() const; + Bool_t IsDrawingExtra() const { return fDrawExtra; } + Bool_t IsNodeSelectable() const { return fIsNodeSelectable; } + Bool_t IsVisLeaves() const { return fVisOption == 1; } + void ModifiedPad() const; + void OptimizeVoxels(const char *filename = "tgeovox.C"); // *MENU* + void SetClipping(Bool_t flag = kTRUE) { SetClippingShape(flag ? fClippingShape : nullptr); } // *MENU* + void SetClippingShape(TGeoShape *clip); + void SetExplodedView(Int_t iopt = 0); // *MENU* + void SetPhiRange(Double_t phimin = 0., Double_t phimax = 360.); + void SetNsegments(Int_t nseg); // *MENU* + Bool_t SetCurrentNavigator(Int_t index); + void + SetBombFactors(Double_t bombx = 1.3, Double_t bomby = 1.3, Double_t bombz = 1.3, Double_t bombr = 1.3); // *MENU* + void SetPaintVolume(TGeoVolume *vol) { fPaintVolume = vol; } + void SetUserPaintVolume(TGeoVolume *vol) { fUserPaintVolume = vol; } + void SetTopVisible(Bool_t vis = kTRUE); + void SetTminTmax(Double_t tmin = 0, Double_t tmax = 999); + void SetDrawExtraPaths(Bool_t flag = kTRUE) { fDrawExtra = flag; } + void SetNodeSelectable(Bool_t flag = kTRUE) { fIsNodeSelectable = flag; } + void SetVisDensity(Double_t dens = 0.01); // *MENU* + void SetVisLevel(Int_t level = 3); // *MENU* + void SetVisOption(Int_t option = 0); + void ViewLeaves(Bool_t flag = kTRUE); // *TOGGLE* *GETTER=IsVisLeaves + void SaveAttributes(const char *filename = "tgeoatt.C"); // *MENU* + void RestoreMasterVolume(); // *MENU* + void SetMaxVisNodes(Int_t maxnodes = 10000); // *MENU* //--- geometry checking - void AnimateTracks(Double_t tmin=0, Double_t tmax=5E-8, Int_t nframes=200, Option_t *option="/*"); // *MENU* - void CheckBoundaryErrors(Int_t ntracks=1000000, Double_t radius=-1.); // *MENU* - void CheckBoundaryReference(Int_t icheck=-1); - void CheckGeometryFull(Int_t ntracks=1000000, Double_t vx=0., Double_t vy=0., Double_t vz=0., Option_t *option="ob"); // *MENU* - void CheckGeometry(Option_t *option=""); - void CheckOverlaps(Double_t ovlp=0.1, Option_t *option=""); // *MENU* - void CheckPoint(Double_t x=0,Double_t y=0, Double_t z=0, Option_t *option=""); // *MENU* - void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option); - void ConvertReflections(); - void DrawCurrentPoint(Int_t color=2); // *MENU* - void DrawTracks(Option_t *option=""); // *MENU* - void SetParticleName(const char *pname) {fParticleName=pname;} - const char *GetParticleName() const {return fParticleName.Data();} - void DrawPath(const char *path, Option_t *option=""); - void PrintOverlaps() const; // *MENU* - void RandomPoints(const TGeoVolume *vol, Int_t npoints=10000, Option_t *option=""); - void RandomRays(Int_t nrays=1000, Double_t startx=0, Double_t starty=0, Double_t startz=0, const char *target_vol=nullptr, Bool_t check_norm=kFALSE); - TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil=1E-5, - const char *g3path=""); - void SetNmeshPoints(Int_t npoints=1000); - void SetCheckedNode(TGeoNode *node); - void Test(Int_t npoints=1000000, Option_t *option=""); // *MENU* - void TestOverlaps(const char* path=""); // *MENU* - Double_t Weight(Double_t precision=0.01, Option_t *option="va"); // *MENU* + void AnimateTracks(Double_t tmin = 0, Double_t tmax = 5E-8, Int_t nframes = 200, Option_t *option = "/*"); // *MENU* + void CheckBoundaryErrors(Int_t ntracks = 1000000, Double_t radius = -1.); // *MENU* + void CheckBoundaryReference(Int_t icheck = -1); + void CheckGeometryFull(Int_t ntracks = 1000000, Double_t vx = 0., Double_t vy = 0., Double_t vz = 0., + Option_t *option = "ob"); // *MENU* + void CheckGeometry(Option_t *option = ""); + void CheckOverlaps(Double_t ovlp = 0.1, Option_t *option = ""); // *MENU* + void CheckPoint(Double_t x = 0, Double_t y = 0, Double_t z = 0, Option_t *option = ""); // *MENU* + void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option); + void ConvertReflections(); + void DrawCurrentPoint(Int_t color = 2); // *MENU* + void DrawTracks(Option_t *option = ""); // *MENU* + void SetParticleName(const char *pname) { fParticleName = pname; } + const char *GetParticleName() const { return fParticleName.Data(); } + void DrawPath(const char *path, Option_t *option = ""); + void PrintOverlaps() const; // *MENU* + void RandomPoints(const TGeoVolume *vol, Int_t npoints = 10000, Option_t *option = ""); + void RandomRays(Int_t nrays = 1000, Double_t startx = 0, Double_t starty = 0, Double_t startz = 0, + const char *target_vol = nullptr, Bool_t check_norm = kFALSE); + TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil = 1E-5, const char *g3path = ""); + void SetNmeshPoints(Int_t npoints = 1000); + void SetCheckedNode(TGeoNode *node); + void Test(Int_t npoints = 1000000, Option_t *option = ""); // *MENU* + void TestOverlaps(const char *path = ""); // *MENU* + Double_t Weight(Double_t precision = 0.01, Option_t *option = "va"); // *MENU* //--- GEANT3-like geometry creation - TGeoVolume *Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step, Int_t numed=0, Option_t *option=""); - void Matrix(Int_t index, Double_t theta1, Double_t phi1, - Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3); - TGeoMaterial *Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen=0, Double_t intlen=0); - TGeoMaterial *Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, - Int_t nelem, Float_t *wmat, Int_t uid); - TGeoMaterial *Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, - Int_t nelem, Double_t *wmat, Int_t uid); - TGeoMedium *Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, - Int_t ifield, Double_t fieldm, Double_t tmaxfd, - Double_t stemax, Double_t deemax, Double_t epsil, - Double_t stmin); - void Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, - Bool_t isOnly, Float_t *upar, Int_t npar=0); - void Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, - Bool_t isOnly, Double_t *upar, Int_t npar=0); - TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, - Float_t *upar, Int_t npar=0); - TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, - Double_t *upar, Int_t npar=0); - void SetVolumeAttribute(const char *name, const char *att, Int_t val); + TGeoVolume *Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, + Int_t numed = 0, Option_t *option = ""); + void + Matrix(Int_t index, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3); + TGeoMaterial *Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen = 0, + Double_t intlen = 0); + TGeoMaterial * + Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, Int_t nelem, Float_t *wmat, Int_t uid); + TGeoMaterial * + Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, Int_t nelem, Double_t *wmat, Int_t uid); + TGeoMedium *Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, Int_t ifield, Double_t fieldm, + Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin); + void Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, + Bool_t isOnly, Float_t *upar, Int_t npar = 0); + void Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, + Bool_t isOnly, Double_t *upar, Int_t npar = 0); + TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, Float_t *upar, Int_t npar = 0); + TGeoVolume *Volume(const char *name, const char *shape, Int_t nmed, Double_t *upar, Int_t npar = 0); + void SetVolumeAttribute(const char *name, const char *att, Int_t val); //--- geometry building - void BuildDefaultMaterials(); - void CloseGeometry(Option_t *option="d"); - Bool_t IsClosed() const {return fClosed;} - TGeoVolume *MakeArb8(const char *name, TGeoMedium *medium, - Double_t dz, Double_t *vertices=nullptr); - TGeoVolume *MakeBox(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz); - TGeoVolume *MakeCone(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2); - TGeoVolume *MakeCons(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, - Double_t phi1, Double_t phi2); - TGeoVolume *MakeCtub(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); - TGeoVolume *MakeEltu(const char *name, TGeoMedium *medium, - Double_t a, Double_t b, Double_t dz); - TGeoVolume *MakeGtra(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoVolume *MakePara(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz, - Double_t alpha, Double_t theta, Double_t phi); - TGeoVolume *MakePcon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nz); - TGeoVolume *MakeParaboloid(const char *name, TGeoMedium *medium, - Double_t rlo, Double_t rhi, Double_t dz); - TGeoVolume *MakeHype(const char *name, TGeoMedium *medium, - Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz); - TGeoVolume *MakePgon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nedges, Int_t nz); - TGeoVolume *MakeSphere(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, - Double_t themin=0, Double_t themax=180, - Double_t phimin=0, Double_t phimax=360); - TGeoVolume *MakeTorus(const char *name, TGeoMedium *medium, Double_t r, - Double_t rmin, Double_t rmax, Double_t phi1=0, Double_t dphi=360); - TGeoVolume *MakeTrap(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2); - TGeoVolume *MakeTrd1(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy, Double_t dz); - TGeoVolume *MakeTrd2(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, - Double_t dz); - TGeoVolume *MakeTube(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz); - TGeoVolume *MakeTubs(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2); - TGeoVolume *MakeXtru(const char *name, TGeoMedium *medium, - Int_t nz); - - TGeoPNEntry *SetAlignableEntry(const char *unique_name, const char *path, Int_t uid=-1); - TGeoPNEntry *GetAlignableEntry(const char *name) const; - TGeoPNEntry *GetAlignableEntry(Int_t index) const; - TGeoPNEntry *GetAlignableEntryByUID(Int_t uid) const; - Int_t GetNAlignable(Bool_t with_uid=kFALSE) const; - TGeoPhysicalNode *MakeAlignablePN(const char *name); - TGeoPhysicalNode *MakeAlignablePN(TGeoPNEntry *entry); - TGeoPhysicalNode *MakePhysicalNode(const char *path=nullptr); - void ClearPhysicalNodes(Bool_t mustdelete=kFALSE); - void RefreshPhysicalNodes(Bool_t lock=kTRUE); - TVirtualGeoTrack *MakeTrack(Int_t id, Int_t pdgcode, TObject *particle); - TGeoVolumeAssembly *MakeVolumeAssembly(const char *name); - TGeoVolumeMulti *MakeVolumeMulti(const char *name, TGeoMedium *medium); - void SetTopVolume(TGeoVolume *vol); + void BuildDefaultMaterials(); + void CloseGeometry(Option_t *option = "d"); + Bool_t IsClosed() const { return fClosed; } + TGeoVolume *MakeArb8(const char *name, TGeoMedium *medium, Double_t dz, Double_t *vertices = nullptr); + TGeoVolume *MakeBox(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz); + TGeoVolume *MakeCone(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2); + TGeoVolume *MakeCons(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2); + TGeoVolume *MakeCtub(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, + Double_t phi2, Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); + TGeoVolume *MakeEltu(const char *name, TGeoMedium *medium, Double_t a, Double_t b, Double_t dz); + TGeoVolume *MakeGtra(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, Double_t twist, + Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, + Double_t tl2, Double_t alpha2); + TGeoVolume *MakePara(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz, Double_t alpha, + Double_t theta, Double_t phi); + TGeoVolume *MakePcon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nz); + TGeoVolume *MakeParaboloid(const char *name, TGeoMedium *medium, Double_t rlo, Double_t rhi, Double_t dz); + TGeoVolume *MakeHype(const char *name, TGeoMedium *medium, Double_t rin, Double_t stin, Double_t rout, + Double_t stout, Double_t dz); + TGeoVolume *MakePgon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nedges, Int_t nz); + TGeoVolume *MakeSphere(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t themin = 0, + Double_t themax = 180, Double_t phimin = 0, Double_t phimax = 360); + TGeoVolume *MakeTorus(const char *name, TGeoMedium *medium, Double_t r, Double_t rmin, Double_t rmax, + Double_t phi1 = 0, Double_t dphi = 360); + TGeoVolume *MakeTrap(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, Double_t h1, + Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, + Double_t alpha2); + TGeoVolume *MakeTrd1(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy, Double_t dz); + TGeoVolume * + MakeTrd2(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, Double_t dz); + TGeoVolume *MakeTube(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz); + TGeoVolume *MakeTubs(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, + Double_t phi2); + TGeoVolume *MakeXtru(const char *name, TGeoMedium *medium, Int_t nz); + + TGeoPNEntry *SetAlignableEntry(const char *unique_name, const char *path, Int_t uid = -1); + TGeoPNEntry *GetAlignableEntry(const char *name) const; + TGeoPNEntry *GetAlignableEntry(Int_t index) const; + TGeoPNEntry *GetAlignableEntryByUID(Int_t uid) const; + Int_t GetNAlignable(Bool_t with_uid = kFALSE) const; + TGeoPhysicalNode *MakeAlignablePN(const char *name); + TGeoPhysicalNode *MakeAlignablePN(TGeoPNEntry *entry); + TGeoPhysicalNode *MakePhysicalNode(const char *path = nullptr); + void ClearPhysicalNodes(Bool_t mustdelete = kFALSE); + void RefreshPhysicalNodes(Bool_t lock = kTRUE); + TVirtualGeoTrack *MakeTrack(Int_t id, Int_t pdgcode, TObject *particle); + TGeoVolumeAssembly *MakeVolumeAssembly(const char *name); + TGeoVolumeMulti *MakeVolumeMulti(const char *name, TGeoMedium *medium); + void SetTopVolume(TGeoVolume *vol); //--- geometry queries - TGeoNode *CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skipnode); - TGeoNode *FindNextBoundary(Double_t stepmax=TGeoShape::Big(),const char *path="", Bool_t frombdr=kFALSE); - TGeoNode *FindNextDaughterBoundary(Double_t *point, Double_t *dir, Int_t &idaughter, Bool_t compmatrix=kFALSE); - TGeoNode *FindNextBoundaryAndStep(Double_t stepmax=TGeoShape::Big(), Bool_t compsafe=kFALSE); - TGeoNode *FindNode(Bool_t safe_start=kTRUE); - TGeoNode *FindNode(Double_t x, Double_t y, Double_t z); - Double_t *FindNormal(Bool_t forward=kTRUE); - Double_t *FindNormalFast(); - TGeoNode *InitTrack(const Double_t *point, const Double_t *dir); - TGeoNode *InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz); - void ResetState(); - Double_t Safety(Bool_t inside=kFALSE); - TGeoNode *SearchNode(Bool_t downwards=kFALSE, const TGeoNode *skipnode=nullptr); - TGeoNode *Step(Bool_t is_geom=kTRUE, Bool_t cross=kTRUE); - void DisableInactiveVolumes() {fActivity=kTRUE;} - void EnableInactiveVolumes() {fActivity=kFALSE;} - void SetCurrentTrack(Int_t i) {fCurrentTrack = (TVirtualGeoTrack*)fTracks->At(i);} - void SetCurrentTrack(TVirtualGeoTrack *track) {fCurrentTrack=track;} - Int_t GetNtracks() const {return fNtracks;} - TVirtualGeoTrack *GetCurrentTrack() {return fCurrentTrack;} - TVirtualGeoTrack *GetLastTrack() {return (TVirtualGeoTrack*)((fNtracks>0)?fTracks->At(fNtracks-1):nullptr);} - const Double_t *GetLastPoint() const {return GetCurrentNavigator()->GetLastPoint();} - TVirtualGeoTrack *GetTrack(Int_t index) {return (indexAt(index):nullptr;} - Int_t GetTrackIndex(Int_t id) const; - TVirtualGeoTrack *GetTrackOfId(Int_t id) const; - TVirtualGeoTrack *FindTrackWithId(Int_t id) const; - TVirtualGeoTrack *GetParentTrackOfId(Int_t id) const; - Int_t GetVirtualLevel(); - Bool_t GotoSafeLevel(); - Int_t GetSafeLevel() const; - Double_t GetSafeDistance() const {return GetCurrentNavigator()->GetSafeDistance();} - Double_t GetLastSafety() const {return GetCurrentNavigator()->GetLastSafety();} - Double_t GetStep() const {return GetCurrentNavigator()->GetStep();} - void InspectState() const; - Bool_t IsAnimatingTracks() const {return fIsGeomReading;} - Bool_t IsCheckingOverlaps() const {return GetCurrentNavigator()->IsCheckingOverlaps();} - Bool_t IsMatrixTransform() const {return fMatrixTransform;} - Bool_t IsMatrixReflection() const {return fMatrixReflection;} - Bool_t IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change=kFALSE); - Bool_t IsSameLocation() const {return GetCurrentNavigator()->IsSameLocation();} - Bool_t IsSamePoint(Double_t x, Double_t y, Double_t z) const; - Bool_t IsStartSafe() const {return GetCurrentNavigator()->IsStartSafe();} - void SetCheckingOverlaps(Bool_t flag=kTRUE) {GetCurrentNavigator()->SetCheckingOverlaps(flag);} - void SetStartSafe(Bool_t flag=kTRUE) {GetCurrentNavigator()->SetStartSafe(flag);} - void SetMatrixTransform(Bool_t on=kTRUE) {fMatrixTransform = on;} - void SetMatrixReflection(Bool_t flag=kTRUE) {fMatrixReflection = flag;} - void SetStep(Double_t step) {GetCurrentNavigator()->SetStep(step);} - Bool_t IsCurrentOverlapping() const {return GetCurrentNavigator()->IsCurrentOverlapping();} - Bool_t IsEntering() const {return GetCurrentNavigator()->IsEntering();} - Bool_t IsExiting() const {return GetCurrentNavigator()->IsExiting();} - Bool_t IsStepEntering() const {return GetCurrentNavigator()->IsStepEntering();} - Bool_t IsStepExiting() const {return GetCurrentNavigator()->IsStepExiting();} - Bool_t IsOutside() const {return GetCurrentNavigator()->IsOutside();} - Bool_t IsOnBoundary() const {return GetCurrentNavigator()->IsOnBoundary();} - Bool_t IsNullStep() const {return GetCurrentNavigator()->IsNullStep();} - Bool_t IsActivityEnabled() const {return fActivity;} - void SetOutside(Bool_t flag=kTRUE) {GetCurrentNavigator()->SetOutside(flag);} - + TGeoNode *CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skipnode); + TGeoNode *FindNextBoundary(Double_t stepmax = TGeoShape::Big(), const char *path = "", Bool_t frombdr = kFALSE); + TGeoNode *FindNextDaughterBoundary(Double_t *point, Double_t *dir, Int_t &idaughter, Bool_t compmatrix = kFALSE); + TGeoNode *FindNextBoundaryAndStep(Double_t stepmax = TGeoShape::Big(), Bool_t compsafe = kFALSE); + TGeoNode *FindNode(Bool_t safe_start = kTRUE); + TGeoNode *FindNode(Double_t x, Double_t y, Double_t z); + Double_t *FindNormal(Bool_t forward = kTRUE); + Double_t *FindNormalFast(); + TGeoNode *InitTrack(const Double_t *point, const Double_t *dir); + TGeoNode *InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz); + void ResetState(); + Double_t Safety(Bool_t inside = kFALSE); + TGeoNode *SearchNode(Bool_t downwards = kFALSE, const TGeoNode *skipnode = nullptr); + TGeoNode *Step(Bool_t is_geom = kTRUE, Bool_t cross = kTRUE); + void DisableInactiveVolumes() { fActivity = kTRUE; } + void EnableInactiveVolumes() { fActivity = kFALSE; } + void SetCurrentTrack(Int_t i) { fCurrentTrack = (TVirtualGeoTrack *)fTracks->At(i); } + void SetCurrentTrack(TVirtualGeoTrack *track) { fCurrentTrack = track; } + Int_t GetNtracks() const { return fNtracks; } + TVirtualGeoTrack *GetCurrentTrack() { return fCurrentTrack; } + TVirtualGeoTrack *GetLastTrack() + { + return (TVirtualGeoTrack *)((fNtracks > 0) ? fTracks->At(fNtracks - 1) : nullptr); + } + const Double_t *GetLastPoint() const { return GetCurrentNavigator()->GetLastPoint(); } + TVirtualGeoTrack *GetTrack(Int_t index) + { + return (index < fNtracks) ? (TVirtualGeoTrack *)fTracks->At(index) : nullptr; + } + Int_t GetTrackIndex(Int_t id) const; + TVirtualGeoTrack *GetTrackOfId(Int_t id) const; + TVirtualGeoTrack *FindTrackWithId(Int_t id) const; + TVirtualGeoTrack *GetParentTrackOfId(Int_t id) const; + Int_t GetVirtualLevel(); + Bool_t GotoSafeLevel(); + Int_t GetSafeLevel() const; + Double_t GetSafeDistance() const { return GetCurrentNavigator()->GetSafeDistance(); } + Double_t GetLastSafety() const { return GetCurrentNavigator()->GetLastSafety(); } + Double_t GetStep() const { return GetCurrentNavigator()->GetStep(); } + void InspectState() const; + Bool_t IsAnimatingTracks() const { return fIsGeomReading; } + Bool_t IsCheckingOverlaps() const { return GetCurrentNavigator()->IsCheckingOverlaps(); } + Bool_t IsMatrixTransform() const { return fMatrixTransform; } + Bool_t IsMatrixReflection() const { return fMatrixReflection; } + Bool_t IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change = kFALSE); + Bool_t IsSameLocation() const { return GetCurrentNavigator()->IsSameLocation(); } + Bool_t IsSamePoint(Double_t x, Double_t y, Double_t z) const; + Bool_t IsStartSafe() const { return GetCurrentNavigator()->IsStartSafe(); } + void SetCheckingOverlaps(Bool_t flag = kTRUE) { GetCurrentNavigator()->SetCheckingOverlaps(flag); } + void SetStartSafe(Bool_t flag = kTRUE) { GetCurrentNavigator()->SetStartSafe(flag); } + void SetMatrixTransform(Bool_t on = kTRUE) { fMatrixTransform = on; } + void SetMatrixReflection(Bool_t flag = kTRUE) { fMatrixReflection = flag; } + void SetStep(Double_t step) { GetCurrentNavigator()->SetStep(step); } + Bool_t IsCurrentOverlapping() const { return GetCurrentNavigator()->IsCurrentOverlapping(); } + Bool_t IsEntering() const { return GetCurrentNavigator()->IsEntering(); } + Bool_t IsExiting() const { return GetCurrentNavigator()->IsExiting(); } + Bool_t IsStepEntering() const { return GetCurrentNavigator()->IsStepEntering(); } + Bool_t IsStepExiting() const { return GetCurrentNavigator()->IsStepExiting(); } + Bool_t IsOutside() const { return GetCurrentNavigator()->IsOutside(); } + Bool_t IsOnBoundary() const { return GetCurrentNavigator()->IsOnBoundary(); } + Bool_t IsNullStep() const { return GetCurrentNavigator()->IsNullStep(); } + Bool_t IsActivityEnabled() const { return fActivity; } + void SetOutside(Bool_t flag = kTRUE) { GetCurrentNavigator()->SetOutside(flag); } //--- cleaning - void CleanGarbage(); - void ClearShape(const TGeoShape *shape); - void ClearTracks() {fTracks->Delete(); fNtracks=0;} - void ClearNavigators(); - void RemoveMaterial(Int_t index); - void RemoveNavigator(const TGeoNavigator *nav); - void ResetUserData(); - + void CleanGarbage(); + void ClearShape(const TGeoShape *shape); + void ClearTracks() + { + fTracks->Delete(); + fNtracks = 0; + } + void ClearNavigators(); + void RemoveMaterial(Int_t index); + void RemoveNavigator(const TGeoNavigator *nav); + void ResetUserData(); //--- utilities - Int_t CountNodes(const TGeoVolume *vol=nullptr, Int_t nlevels=10000, Int_t option=0); - void CountLevels(); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - static Int_t Parse(const char* expr, TString &expr1, TString &expr2, TString &expr3); - Int_t ReplaceVolume(TGeoVolume *vorig, TGeoVolume *vnew); - Int_t TransformVolumeToAssembly(const char *vname); - UChar_t *GetBits() {return fBits;} - virtual Int_t GetByteCount(Option_t *option=nullptr); - void SetAllIndex(); - static Int_t GetMaxDaughters(); - static Int_t GetMaxLevels(); - static Int_t GetMaxXtruVert(); - Int_t GetMaxThreads() const {return fMaxThreads-1;} - void SetMaxThreads(Int_t nthreads); - Int_t GetRTmode() const {return fRaytraceMode;} - void SetRTmode(Int_t mode); // *MENU* - Bool_t IsMultiThread() const {return fMultiThread;} - static void SetNavigatorsLock(Bool_t flag); - static Int_t ThreadId(); - static Int_t GetNumThreads(); - static void ClearThreadsMap(); - void ClearThreadData() const; - void CreateThreadData() const; + Int_t CountNodes(const TGeoVolume *vol = nullptr, Int_t nlevels = 10000, Int_t option = 0); + void CountLevels(); + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + static Int_t Parse(const char *expr, TString &expr1, TString &expr2, TString &expr3); + Int_t ReplaceVolume(TGeoVolume *vorig, TGeoVolume *vnew); + Int_t TransformVolumeToAssembly(const char *vname); + UChar_t *GetBits() { return fBits; } + virtual Int_t GetByteCount(Option_t *option = nullptr); + void SetAllIndex(); + static Int_t GetMaxDaughters(); + static Int_t GetMaxLevels(); + static Int_t GetMaxXtruVert(); + Int_t GetMaxThreads() const { return fMaxThreads - 1; } + void SetMaxThreads(Int_t nthreads); + Int_t GetRTmode() const { return fRaytraceMode; } + void SetRTmode(Int_t mode); // *MENU* + Bool_t IsMultiThread() const { return fMultiThread; } + static void SetNavigatorsLock(Bool_t flag); + static Int_t ThreadId(); + static Int_t GetNumThreads(); + static void ClearThreadsMap(); + void ClearThreadData() const; + void CreateThreadData() const; //--- I/O - virtual Int_t Export(const char *filename, const char *name="", Option_t *option="vg"); - static void LockGeometry(); - static void UnlockGeometry(); - static Int_t GetVerboseLevel(); - static void SetVerboseLevel(Int_t vl); - static TGeoManager *Import(const char *filename, const char *name="", Option_t *option=""); - static Bool_t IsLocked(); - static void SetExportPrecision(UInt_t prec); - static UInt_t GetExportPrecision(); - static void SetDefaultUnits(EDefaultUnits new_value); - static EDefaultUnits GetDefaultUnits(); - static Bool_t LockDefaultUnits(Bool_t new_value); - Bool_t IsStreamingVoxels() const {return fStreamVoxels;} - Bool_t IsCleaning() const {return fIsGeomCleaning;} + virtual Int_t Export(const char *filename, const char *name = "", Option_t *option = "vg"); + static void LockGeometry(); + static void UnlockGeometry(); + static Int_t GetVerboseLevel(); + static void SetVerboseLevel(Int_t vl); + static TGeoManager *Import(const char *filename, const char *name = "", Option_t *option = ""); + static Bool_t IsLocked(); + static void SetExportPrecision(UInt_t prec); + static UInt_t GetExportPrecision(); + static void SetDefaultUnits(EDefaultUnits new_value); + static EDefaultUnits GetDefaultUnits(); + static Bool_t LockDefaultUnits(Bool_t new_value); + Bool_t IsStreamingVoxels() const { return fStreamVoxels; } + Bool_t IsCleaning() const { return fIsGeomCleaning; } //--- list getters - TObjArray *GetListOfNodes() {return fNodes;} - TObjArray *GetListOfPhysicalNodes() {return fPhysicalNodes;} - TObjArray *GetListOfOverlaps() {return fOverlaps;} - TObjArray *GetListOfMatrices() const {return fMatrices;} - TList *GetListOfMaterials() const {return fMaterials;} - TList *GetListOfMedia() const {return fMedia;} - TObjArray *GetListOfVolumes() const {return fVolumes;} - TObjArray *GetListOfGVolumes() const {return fGVolumes;} - TObjArray *GetListOfShapes() const {return fShapes;} - TObjArray *GetListOfGShapes() const {return fGShapes;} - TObjArray *GetListOfUVolumes() const {return fUniqueVolumes;} - TObjArray *GetListOfTracks() const {return fTracks;} - TObjArray *GetListOfGDMLMatrices() const {return fGDMLMatrices;} - TObjArray *GetListOfOpticalSurfaces() const {return fOpticalSurfaces;} - TObjArray *GetListOfSkinSurfaces() const {return fSkinSurfaces;} - TObjArray *GetListOfBorderSurfaces() const {return fBorderSurfaces;} - TObjArray *GetListOfRegions() const {return fRegions;} - TGeoNavigatorArray *GetListOfNavigators() const; - TGeoElementTable *GetElementTable(); + TObjArray *GetListOfNodes() { return fNodes; } + TObjArray *GetListOfPhysicalNodes() { return fPhysicalNodes; } + TObjArray *GetListOfOverlaps() { return fOverlaps; } + TObjArray *GetListOfMatrices() const { return fMatrices; } + TList *GetListOfMaterials() const { return fMaterials; } + TList *GetListOfMedia() const { return fMedia; } + TObjArray *GetListOfVolumes() const { return fVolumes; } + TObjArray *GetListOfGVolumes() const { return fGVolumes; } + TObjArray *GetListOfShapes() const { return fShapes; } + TObjArray *GetListOfGShapes() const { return fGShapes; } + TObjArray *GetListOfUVolumes() const { return fUniqueVolumes; } + TObjArray *GetListOfTracks() const { return fTracks; } + TObjArray *GetListOfGDMLMatrices() const { return fGDMLMatrices; } + TObjArray *GetListOfOpticalSurfaces() const { return fOpticalSurfaces; } + TObjArray *GetListOfSkinSurfaces() const { return fSkinSurfaces; } + TObjArray *GetListOfBorderSurfaces() const { return fBorderSurfaces; } + TObjArray *GetListOfRegions() const { return fRegions; } + TGeoNavigatorArray *GetListOfNavigators() const; + TGeoElementTable *GetElementTable(); //--- modeler state getters/setters - void DoBackupState(); - void DoRestoreState(); - TGeoNode *GetNode(Int_t level) const {return (TGeoNode*)fNodes->UncheckedAt(level);} - Int_t GetNodeId() const {return GetCurrentNavigator()->GetNodeId();} - TGeoNode *GetNextNode() const {return GetCurrentNavigator()->GetNextNode();} - TGeoNode *GetMother(Int_t up=1) const {return GetCurrentNavigator()->GetMother(up);} - TGeoHMatrix *GetMotherMatrix(Int_t up=1) const {return GetCurrentNavigator()->GetMotherMatrix(up);} - TGeoHMatrix *GetHMatrix(); - TGeoHMatrix *GetCurrentMatrix() const {return GetCurrentNavigator()->GetCurrentMatrix();} - TGeoHMatrix *GetGLMatrix() const {return fGLMatrix;} - TGeoNavigator *GetCurrentNavigator() const; - TGeoNode *GetCurrentNode() const {return GetCurrentNavigator()->GetCurrentNode();} - Int_t GetCurrentNodeId() const; - const Double_t *GetCurrentPoint() const {return GetCurrentNavigator()->GetCurrentPoint();} - const Double_t *GetCurrentDirection() const {return GetCurrentNavigator()->GetCurrentDirection();} - TGeoVolume *GetCurrentVolume() const {return GetCurrentNavigator()->GetCurrentVolume();} - const Double_t *GetCldirChecked() const {return GetCurrentNavigator()->GetCldirChecked();} - const Double_t *GetCldir() const {return GetCurrentNavigator()->GetCldir();} - const Double_t *GetNormal() const {return GetCurrentNavigator()->GetNormal();} - Int_t GetLevel() const {return GetCurrentNavigator()->GetLevel();} - Int_t GetMaxLevel() const {return fNLevel;} - const char *GetPath() const; - Int_t GetStackLevel() const {return GetCurrentNavigator()->GetStackLevel();} - TGeoVolume *GetMasterVolume() const {return fMasterVolume;} - TGeoVolume *GetTopVolume() const {return fTopVolume;} - TGeoNode *GetTopNode() const {return fTopNode;} - TGeoPhysicalNode *GetPhysicalNode(Int_t i) const {return (TGeoPhysicalNode*)fPhysicalNodes->UncheckedAt(i);} - void SetCurrentPoint(Double_t *point) {GetCurrentNavigator()->SetCurrentPoint(point);} - void SetCurrentPoint(Double_t x, Double_t y, Double_t z) {GetCurrentNavigator()->SetCurrentPoint(x,y,z);} - void SetLastPoint(Double_t x, Double_t y, Double_t z) {GetCurrentNavigator()->SetLastPoint(x,y,z);} - void SetCurrentDirection(Double_t *dir) {GetCurrentNavigator()->SetCurrentDirection(dir);} - void SetCurrentDirection(Double_t nx, Double_t ny, Double_t nz) {GetCurrentNavigator()->SetCurrentDirection(nx,ny,nz);} - void SetCldirChecked(Double_t *dir) {GetCurrentNavigator()->SetCldirChecked(dir);} + void DoBackupState(); + void DoRestoreState(); + TGeoNode *GetNode(Int_t level) const { return (TGeoNode *)fNodes->UncheckedAt(level); } + Int_t GetNodeId() const { return GetCurrentNavigator()->GetNodeId(); } + TGeoNode *GetNextNode() const { return GetCurrentNavigator()->GetNextNode(); } + TGeoNode *GetMother(Int_t up = 1) const { return GetCurrentNavigator()->GetMother(up); } + TGeoHMatrix *GetMotherMatrix(Int_t up = 1) const { return GetCurrentNavigator()->GetMotherMatrix(up); } + TGeoHMatrix *GetHMatrix(); + TGeoHMatrix *GetCurrentMatrix() const { return GetCurrentNavigator()->GetCurrentMatrix(); } + TGeoHMatrix *GetGLMatrix() const { return fGLMatrix; } + TGeoNavigator *GetCurrentNavigator() const; + TGeoNode *GetCurrentNode() const { return GetCurrentNavigator()->GetCurrentNode(); } + Int_t GetCurrentNodeId() const; + const Double_t *GetCurrentPoint() const { return GetCurrentNavigator()->GetCurrentPoint(); } + const Double_t *GetCurrentDirection() const { return GetCurrentNavigator()->GetCurrentDirection(); } + TGeoVolume *GetCurrentVolume() const { return GetCurrentNavigator()->GetCurrentVolume(); } + const Double_t *GetCldirChecked() const { return GetCurrentNavigator()->GetCldirChecked(); } + const Double_t *GetCldir() const { return GetCurrentNavigator()->GetCldir(); } + const Double_t *GetNormal() const { return GetCurrentNavigator()->GetNormal(); } + Int_t GetLevel() const { return GetCurrentNavigator()->GetLevel(); } + Int_t GetMaxLevel() const { return fNLevel; } + const char *GetPath() const; + Int_t GetStackLevel() const { return GetCurrentNavigator()->GetStackLevel(); } + TGeoVolume *GetMasterVolume() const { return fMasterVolume; } + TGeoVolume *GetTopVolume() const { return fTopVolume; } + TGeoNode *GetTopNode() const { return fTopNode; } + TGeoPhysicalNode *GetPhysicalNode(Int_t i) const { return (TGeoPhysicalNode *)fPhysicalNodes->UncheckedAt(i); } + void SetCurrentPoint(Double_t *point) { GetCurrentNavigator()->SetCurrentPoint(point); } + void SetCurrentPoint(Double_t x, Double_t y, Double_t z) { GetCurrentNavigator()->SetCurrentPoint(x, y, z); } + void SetLastPoint(Double_t x, Double_t y, Double_t z) { GetCurrentNavigator()->SetLastPoint(x, y, z); } + void SetCurrentDirection(Double_t *dir) { GetCurrentNavigator()->SetCurrentDirection(dir); } + void SetCurrentDirection(Double_t nx, Double_t ny, Double_t nz) + { + GetCurrentNavigator()->SetCurrentDirection(nx, ny, nz); + } + void SetCldirChecked(Double_t *dir) { GetCurrentNavigator()->SetCldirChecked(dir); } //--- point/vector reference frame conversion - void LocalToMaster(const Double_t *local, Double_t *master) const {GetCurrentNavigator()->LocalToMaster(local, master);} - void LocalToMasterVect(const Double_t *local, Double_t *master) const {GetCurrentNavigator()->LocalToMasterVect(local, master);} - void LocalToMasterBomb(const Double_t *local, Double_t *master) const {GetCurrentNavigator()->LocalToMasterBomb(local, master);} - void MasterToLocal(const Double_t *master, Double_t *local) const {GetCurrentNavigator()->MasterToLocal(master, local);} - void MasterToLocalVect(const Double_t *master, Double_t *local) const {GetCurrentNavigator()->MasterToLocalVect(master, local);} - void MasterToLocalBomb(const Double_t *master, Double_t *local) const {GetCurrentNavigator()->MasterToLocalBomb(master, local);} - void MasterToTop(const Double_t *master, Double_t *top) const; - void TopToMaster(const Double_t *top, Double_t *master) const; + void LocalToMaster(const Double_t *local, Double_t *master) const + { + GetCurrentNavigator()->LocalToMaster(local, master); + } + void LocalToMasterVect(const Double_t *local, Double_t *master) const + { + GetCurrentNavigator()->LocalToMasterVect(local, master); + } + void LocalToMasterBomb(const Double_t *local, Double_t *master) const + { + GetCurrentNavigator()->LocalToMasterBomb(local, master); + } + void MasterToLocal(const Double_t *master, Double_t *local) const + { + GetCurrentNavigator()->MasterToLocal(master, local); + } + void MasterToLocalVect(const Double_t *master, Double_t *local) const + { + GetCurrentNavigator()->MasterToLocalVect(master, local); + } + void MasterToLocalBomb(const Double_t *master, Double_t *local) const + { + GetCurrentNavigator()->MasterToLocalBomb(master, local); + } + void MasterToTop(const Double_t *master, Double_t *top) const; + void TopToMaster(const Double_t *top, Double_t *master) const; //--- general use getters/setters - TGeoMaterial *FindDuplicateMaterial(const TGeoMaterial *mat) const; - TGeoVolume *FindVolumeFast(const char*name, Bool_t multi=kFALSE); - TGeoMaterial *GetMaterial(const char *matname) const; - TGeoMaterial *GetMaterial(Int_t id) const; - TGeoMedium *GetMedium(const char *medium) const; - TGeoMedium *GetMedium(Int_t numed) const; - Int_t GetMaterialIndex(const char *matname) const; + TGeoMaterial *FindDuplicateMaterial(const TGeoMaterial *mat) const; + TGeoVolume *FindVolumeFast(const char *name, Bool_t multi = kFALSE); + TGeoMaterial *GetMaterial(const char *matname) const; + TGeoMaterial *GetMaterial(Int_t id) const; + TGeoMedium *GetMedium(const char *medium) const; + TGeoMedium *GetMedium(Int_t numed) const; + Int_t GetMaterialIndex(const char *matname) const; //--- GDML object accessors - TGDMLMatrix *GetGDMLMatrix(const char *name) const; - void AddGDMLMatrix(TGDMLMatrix *mat); - TGeoOpticalSurface *GetOpticalSurface(const char *name) const; - void AddOpticalSurface(TGeoOpticalSurface *optsurf); - TGeoSkinSurface *GetSkinSurface(const char *name) const; - void AddSkinSurface(TGeoSkinSurface *surf); - TGeoBorderSurface *GetBorderSurface(const char *name) const; - void AddBorderSurface(TGeoBorderSurface *surf); - -// TGeoShape *GetShape(const char *name) const; - TGeoVolume *GetVolume(const char*name) const; - TGeoVolume *GetVolume(Int_t uid) const {return (TGeoVolume*)fUniqueVolumes->At(uid);} - int GetNregions() const {return fRegions->GetEntriesFast();} - TGeoRegion *GetRegion(int i) {return (TGeoRegion*)fRegions->At(i);} - Int_t GetUID(const char *volname) const; - Int_t GetNNodes() {if (!fNNodes) CountNodes(); return fNNodes;} - TGeoNodeCache *GetCache() const {return GetCurrentNavigator()->GetCache();} -// void SetCache(const TGeoNodeCache *cache) {fCache = (TGeoNodeCache*)cache;} - void SetAnimateTracks(Bool_t flag=kTRUE) {fIsGeomReading=flag;} - virtual ULong_t SizeOf(const TGeoNode *node, Option_t *option); // size of the geometry in memory - void SelectTrackingMedia(); + TGDMLMatrix *GetGDMLMatrix(const char *name) const; + void AddGDMLMatrix(TGDMLMatrix *mat); + TGeoOpticalSurface *GetOpticalSurface(const char *name) const; + void AddOpticalSurface(TGeoOpticalSurface *optsurf); + TGeoSkinSurface *GetSkinSurface(const char *name) const; + void AddSkinSurface(TGeoSkinSurface *surf); + TGeoBorderSurface *GetBorderSurface(const char *name) const; + void AddBorderSurface(TGeoBorderSurface *surf); + + // TGeoShape *GetShape(const char *name) const; + TGeoVolume *GetVolume(const char *name) const; + TGeoVolume *GetVolume(Int_t uid) const { return (TGeoVolume *)fUniqueVolumes->At(uid); } + int GetNregions() const { return fRegions->GetEntriesFast(); } + TGeoRegion *GetRegion(int i) { return (TGeoRegion *)fRegions->At(i); } + Int_t GetUID(const char *volname) const; + Int_t GetNNodes() + { + if (!fNNodes) + CountNodes(); + return fNNodes; + } + TGeoNodeCache *GetCache() const { return GetCurrentNavigator()->GetCache(); } + // void SetCache(const TGeoNodeCache *cache) {fCache = (TGeoNodeCache*)cache;} + void SetAnimateTracks(Bool_t flag = kTRUE) { fIsGeomReading = flag; } + virtual ULong_t SizeOf(const TGeoNode *node, Option_t *option); // size of the geometry in memory + void SelectTrackingMedia(); //--- stack manipulation - Int_t PushPath(Int_t startlevel=0) {return GetCurrentNavigator()->PushPath(startlevel);} - Bool_t PopPath() {return GetCurrentNavigator()->PopPath();} - Bool_t PopPath(Int_t index) {return GetCurrentNavigator()->PopPath(index);} - Int_t PushPoint(Int_t startlevel=0) {return GetCurrentNavigator()->PushPoint(startlevel);} - Bool_t PopPoint() {return GetCurrentNavigator()->PopPoint();} - Bool_t PopPoint(Int_t index) {return GetCurrentNavigator()->PopPoint(index);} - void PopDummy(Int_t ipop=9999) {return GetCurrentNavigator()->PopDummy(ipop);} + Int_t PushPath(Int_t startlevel = 0) { return GetCurrentNavigator()->PushPath(startlevel); } + Bool_t PopPath() { return GetCurrentNavigator()->PopPath(); } + Bool_t PopPath(Int_t index) { return GetCurrentNavigator()->PopPath(index); } + Int_t PushPoint(Int_t startlevel = 0) { return GetCurrentNavigator()->PushPoint(startlevel); } + Bool_t PopPoint() { return GetCurrentNavigator()->PopPoint(); } + Bool_t PopPoint(Int_t index) { return GetCurrentNavigator()->PopPoint(index); } + void PopDummy(Int_t ipop = 9999) { return GetCurrentNavigator()->PopDummy(ipop); } //--- parallel world navigation - TGeoParallelWorld *CreateParallelWorld(const char *name); - TGeoParallelWorld *GetParallelWorld() const {return fParallelWorld;} - void SetUseParallelWorldNav(Bool_t flag); - Bool_t IsParallelWorldNav() const {return fUsePWNav;} + TGeoParallelWorld *CreateParallelWorld(const char *name); + TGeoParallelWorld *GetParallelWorld() const { return fParallelWorld; } + void SetUseParallelWorldNav(Bool_t flag); + Bool_t IsParallelWorldNav() const { return fUsePWNav; } - ClassDef(TGeoManager, 17) // geometry manager + ClassDefOverride(TGeoManager, 17) // geometry manager }; R__EXTERN TGeoManager *gGeoManager; #endif - diff --git a/geom/geom/inc/TGeoMaterial.h b/geom/geom/inc/TGeoMaterial.h index eaabbaf9602b8..63d4bd61f7aa3 100644 --- a/geom/geom/inc/TGeoMaterial.h +++ b/geom/geom/inc/TGeoMaterial.h @@ -28,195 +28,205 @@ class TGeoExtension; class TGDMLMatrix; // Some units used in G4 -static const Double_t STP_temperature = 273.15; // [K] -static const Double_t STP_pressure = 6.32420e+8; // [MeV/mm3] +static const Double_t STP_temperature = 273.15; // [K] +static const Double_t STP_pressure = 6.32420e+8; // [MeV/mm3] -class TGeoMaterial : public TNamed, - public TAttFill -{ +class TGeoMaterial : public TNamed, public TAttFill { public: - enum EGeoMaterial { - kMatUsed = BIT(17), - kMatSavePrimitive = BIT(18) - }; - enum EGeoMaterialState { - kMatStateUndefined, - kMatStateSolid, - kMatStateLiquid, - kMatStateGas - }; + enum EGeoMaterial { kMatUsed = BIT(17), kMatSavePrimitive = BIT(18) }; + enum EGeoMaterialState { kMatStateUndefined, kMatStateSolid, kMatStateLiquid, kMatStateGas }; protected: - Int_t fIndex; // material index - Double_t fA; // A of material - Double_t fZ; // Z of material - Double_t fDensity; // density of material - Double_t fRadLen; // radiation length - Double_t fIntLen; // interaction length - Double_t fTemperature; // temperature - Double_t fPressure; // pressure - EGeoMaterialState fState; // material state - TObject *fShader; // shader with optical properties - TObject *fCerenkov; // pointer to class with Cerenkov properties - TGeoElement *fElement; // pointer to element composing the material - TList fProperties; // user-defined properties - TList fConstProperties; // user-defined constant properties - TGeoExtension *fUserExtension; //! Transient user-defined extension to materials - TGeoExtension *fFWExtension; //! Transient framework-defined extension to materials - -// methods - TGeoMaterial(const TGeoMaterial&); - TGeoMaterial& operator=(const TGeoMaterial&); + Int_t fIndex; // material index + Double_t fA; // A of material + Double_t fZ; // Z of material + Double_t fDensity; // density of material + Double_t fRadLen; // radiation length + Double_t fIntLen; // interaction length + Double_t fTemperature; // temperature + Double_t fPressure; // pressure + EGeoMaterialState fState; // material state + TObject *fShader; // shader with optical properties + TObject *fCerenkov; // pointer to class with Cerenkov properties + TGeoElement *fElement; // pointer to element composing the material + TList fProperties; // user-defined properties + TList fConstProperties; // user-defined constant properties + TGeoExtension *fUserExtension; //! Transient user-defined extension to materials + TGeoExtension *fFWExtension; //! Transient framework-defined extension to materials + // methods + TGeoMaterial(const TGeoMaterial &); + TGeoMaterial &operator=(const TGeoMaterial &); public: // constructors TGeoMaterial(); TGeoMaterial(const char *name); - TGeoMaterial(const char *name, Double_t a, Double_t z, - Double_t rho, Double_t radlen=0, Double_t intlen=0); - TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, - EGeoMaterialState state, Double_t temperature=STP_temperature, Double_t pressure=STP_pressure); + TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, Double_t radlen = 0, Double_t intlen = 0); + TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, EGeoMaterialState state, + Double_t temperature = STP_temperature, Double_t pressure = STP_pressure); TGeoMaterial(const char *name, TGeoElement *elem, Double_t rho); // destructor - virtual ~TGeoMaterial(); + ~TGeoMaterial() override; // methods - static Double_t Coulomb(Double_t z); + static Double_t Coulomb(Double_t z); // radioactive mixture evolution - virtual TGeoMaterial *DecayMaterial(Double_t time, Double_t precision=0.001); - virtual void FillMaterialEvolution(TObjArray *population, Double_t precision=0.001); + virtual TGeoMaterial *DecayMaterial(Double_t time, Double_t precision = 0.001); + virtual void FillMaterialEvolution(TObjArray *population, Double_t precision = 0.001); // getters & setters - bool AddProperty(const char *property, const char *ref); - bool AddConstProperty(const char *property, const char *ref); - Int_t GetNproperties() const { return fProperties.GetSize(); } - Int_t GetNconstProperties() const { return fConstProperties.GetSize(); } - const char *GetPropertyRef(const char *property) const; - const char *GetPropertyRef(Int_t i) const { return (fProperties.At(i) ? fProperties.At(i)->GetTitle() : nullptr); } - Double_t GetConstProperty(const char *property, Bool_t *error = nullptr) const; - Double_t GetConstProperty(Int_t i, Bool_t *error = nullptr) const; - const char *GetConstPropertyRef(const char *property) const; - const char *GetConstPropertyRef(Int_t i) const { return (fConstProperties.At(i) ? fConstProperties.At(i)->GetTitle() : nullptr); } - TList const &GetProperties() const { return fProperties; } - TList const &GetConstProperties() const { return fConstProperties; } - TGDMLMatrix* GetProperty(const char* name) const; - TGDMLMatrix* GetProperty(Int_t i) const; - virtual Int_t GetByteCount() const {return sizeof(*this);} - virtual Double_t GetA() const {return fA;} - virtual Double_t GetZ() const {return fZ;} - virtual Int_t GetDefaultColor() const; - virtual Double_t GetDensity() const {return fDensity;} - virtual Int_t GetNelements() const {return 1;} - TGeoElement *GetElement() const; - virtual TGeoElement *GetElement(Int_t i) const; - virtual void GetElementProp(Double_t &a, Double_t &z, Double_t &w, Int_t i=0); - TGeoElement *GetBaseElement() const {return fElement;} - const char *GetPointerName() const; - virtual Double_t GetRadLen() const {return fRadLen;} - virtual Double_t GetIntLen() const {return fIntLen;} - Int_t GetIndex(); - virtual TObject *GetCerenkovProperties() const {return fCerenkov;} - Char_t GetTransparency() const {return (fFillStyle<3000 || fFillStyle>3100)?0:Char_t(fFillStyle-3000);} - Double_t GetTemperature() const {return fTemperature;} - Double_t GetPressure() const {return fPressure;} - EGeoMaterialState GetState() const {return fState;} - virtual Double_t GetSpecificActivity(Int_t) const {return 0.;} - TGeoExtension *GetUserExtension() const {return fUserExtension;} - TGeoExtension *GetFWExtension() const {return fFWExtension;} - TGeoExtension *GrabUserExtension() const; - TGeoExtension *GrabFWExtension() const; - virtual Bool_t IsEq(const TGeoMaterial *other) const; - Bool_t IsUsed() const {return TObject::TestBit(kMatUsed);} - virtual Bool_t IsMixture() const {return kFALSE;} - virtual void Print(const Option_t *option="") const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetA(Double_t a) {fA = a; SetRadLen(0);} - virtual void SetZ(Double_t z) {fZ = z; SetRadLen(0);} - virtual void SetDensity(Double_t density) {fDensity = density; SetRadLen(0);} - void SetIndex(Int_t index) {fIndex=index;} - virtual void SetCerenkovProperties(TObject* cerenkov) {fCerenkov = cerenkov;} - void SetRadLen(Double_t radlen, Double_t intlen=0.); - void SetUsed(Bool_t flag=kTRUE) {TObject::SetBit(kMatUsed, flag);} - void SetTransparency(Char_t transparency=0) {fFillStyle = 3000+transparency;} - void SetTemperature(Double_t temperature) {fTemperature = temperature;} - void SetPressure(Double_t pressure) {fPressure = pressure;} - void SetState(EGeoMaterialState state) {fState = state;} - void SetUserExtension(TGeoExtension *ext); - void SetFWExtension(TGeoExtension *ext); - static Double_t ScreenFactor(Double_t z); - - - - ClassDef(TGeoMaterial, 7) // base material class - -//***** Need to add classes and globals to LinkDef.h ***** + bool AddProperty(const char *property, const char *ref); + bool AddConstProperty(const char *property, const char *ref); + Int_t GetNproperties() const { return fProperties.GetSize(); } + Int_t GetNconstProperties() const { return fConstProperties.GetSize(); } + const char *GetPropertyRef(const char *property) const; + const char *GetPropertyRef(Int_t i) const { return (fProperties.At(i) ? fProperties.At(i)->GetTitle() : nullptr); } + Double_t GetConstProperty(const char *property, Bool_t *error = nullptr) const; + Double_t GetConstProperty(Int_t i, Bool_t *error = nullptr) const; + const char *GetConstPropertyRef(const char *property) const; + const char *GetConstPropertyRef(Int_t i) const + { + return (fConstProperties.At(i) ? fConstProperties.At(i)->GetTitle() : nullptr); + } + TList const &GetProperties() const { return fProperties; } + TList const &GetConstProperties() const { return fConstProperties; } + TGDMLMatrix *GetProperty(const char *name) const; + TGDMLMatrix *GetProperty(Int_t i) const; + virtual Int_t GetByteCount() const { return sizeof(*this); } + virtual Double_t GetA() const { return fA; } + virtual Double_t GetZ() const { return fZ; } + virtual Int_t GetDefaultColor() const; + virtual Double_t GetDensity() const { return fDensity; } + virtual Int_t GetNelements() const { return 1; } + TGeoElement *GetElement() const; + virtual TGeoElement *GetElement(Int_t i) const; + virtual void GetElementProp(Double_t &a, Double_t &z, Double_t &w, Int_t i = 0); + TGeoElement *GetBaseElement() const { return fElement; } + const char *GetPointerName() const; + virtual Double_t GetRadLen() const { return fRadLen; } + virtual Double_t GetIntLen() const { return fIntLen; } + Int_t GetIndex(); + virtual TObject *GetCerenkovProperties() const { return fCerenkov; } + Char_t GetTransparency() const { return (fFillStyle < 3000 || fFillStyle > 3100) ? 0 : Char_t(fFillStyle - 3000); } + Double_t GetTemperature() const { return fTemperature; } + Double_t GetPressure() const { return fPressure; } + EGeoMaterialState GetState() const { return fState; } + virtual Double_t GetSpecificActivity(Int_t) const { return 0.; } + TGeoExtension *GetUserExtension() const { return fUserExtension; } + TGeoExtension *GetFWExtension() const { return fFWExtension; } + TGeoExtension *GrabUserExtension() const; + TGeoExtension *GrabFWExtension() const; + virtual Bool_t IsEq(const TGeoMaterial *other) const; + Bool_t IsUsed() const { return TObject::TestBit(kMatUsed); } + virtual Bool_t IsMixture() const { return kFALSE; } + void Print(const Option_t *option = "") const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + virtual void SetA(Double_t a) + { + fA = a; + SetRadLen(0); + } + virtual void SetZ(Double_t z) + { + fZ = z; + SetRadLen(0); + } + virtual void SetDensity(Double_t density) + { + fDensity = density; + SetRadLen(0); + } + void SetIndex(Int_t index) { fIndex = index; } + virtual void SetCerenkovProperties(TObject *cerenkov) { fCerenkov = cerenkov; } + void SetRadLen(Double_t radlen, Double_t intlen = 0.); + void SetUsed(Bool_t flag = kTRUE) { TObject::SetBit(kMatUsed, flag); } + void SetTransparency(Char_t transparency = 0) { fFillStyle = 3000 + transparency; } + void SetTemperature(Double_t temperature) { fTemperature = temperature; } + void SetPressure(Double_t pressure) { fPressure = pressure; } + void SetState(EGeoMaterialState state) { fState = state; } + void SetUserExtension(TGeoExtension *ext); + void SetFWExtension(TGeoExtension *ext); + static Double_t ScreenFactor(Double_t z); + + ClassDefOverride(TGeoMaterial, 7) // base material class + + //***** Need to add classes and globals to LinkDef.h ***** }; - -class TGeoMixture : public TGeoMaterial -{ -protected : -// data members - Int_t fNelements; // number of elements - Double_t *fZmixture; // [fNelements] array of Z of the elements - Double_t *fAmixture; // [fNelements] array of A of the elements - Double_t *fWeights; // [fNelements] array of relative proportions by mass - Int_t *fNatoms; // [fNelements] array of numbers of atoms - Double_t *fVecNbOfAtomsPerVolume; //[fNelements] array of numbers of atoms per unit volume - TObjArray *fElements; // array of elements composing the mixture -// methods - TGeoMixture(const TGeoMixture&) = delete; - TGeoMixture& operator=(const TGeoMixture&) = delete; - void AverageProperties(); +class TGeoMixture : public TGeoMaterial { +protected: + // data members + Int_t fNelements; // number of elements + Double_t *fZmixture; // [fNelements] array of Z of the elements + Double_t *fAmixture; // [fNelements] array of A of the elements + Double_t *fWeights; // [fNelements] array of relative proportions by mass + Int_t *fNatoms; // [fNelements] array of numbers of atoms + Double_t *fVecNbOfAtomsPerVolume; //[fNelements] array of numbers of atoms per unit volume + TObjArray *fElements; // array of elements composing the mixture + // methods + TGeoMixture(const TGeoMixture &) = delete; + TGeoMixture &operator=(const TGeoMixture &) = delete; + void AverageProperties(); public: // constructors TGeoMixture(); - TGeoMixture(const char *name, Int_t nel, Double_t rho=-1); + TGeoMixture(const char *name, Int_t nel, Double_t rho = -1); // destructor - virtual ~TGeoMixture(); + ~TGeoMixture() override; // methods for adding elements - void AddElement(Double_t a, Double_t z, Double_t weight); - void AddElement(TGeoMaterial *mat, Double_t weight); - void AddElement(TGeoElement *elem, Double_t weight); - void AddElement(TGeoElement *elem, Int_t natoms); + void AddElement(Double_t a, Double_t z, Double_t weight); + void AddElement(TGeoMaterial *mat, Double_t weight); + void AddElement(TGeoElement *elem, Double_t weight); + void AddElement(TGeoElement *elem, Int_t natoms); // backward compatibility for defining elements - void DefineElement(Int_t iel, Double_t a, Double_t z, Double_t weight); - void DefineElement(Int_t iel, TGeoElement *elem, Double_t weight); - void DefineElement(Int_t iel, Int_t z, Int_t natoms); + void DefineElement(Int_t iel, Double_t a, Double_t z, Double_t weight); + void DefineElement(Int_t iel, TGeoElement *elem, Double_t weight); + void DefineElement(Int_t iel, Int_t z, Int_t natoms); // radioactive mixture evolution - virtual TGeoMaterial *DecayMaterial(Double_t time, Double_t precision=0.001); - virtual void FillMaterialEvolution(TObjArray *population, Double_t precision=0.001); + TGeoMaterial *DecayMaterial(Double_t time, Double_t precision = 0.001) override; + void FillMaterialEvolution(TObjArray *population, Double_t precision = 0.001) override; // getters - virtual Int_t GetByteCount() const {return 48+12*fNelements;} - virtual TGeoElement *GetElement(Int_t i=0) const; - virtual void GetElementProp(Double_t &a, Double_t &z, Double_t &w, Int_t i=0) {a=fAmixture[i]; z=fZmixture[i]; w=fWeights[i];} - virtual Int_t GetNelements() const {return fNelements;} - Double_t *GetZmixt() const {return fZmixture;} - Double_t *GetAmixt() const {return fAmixture;} - Double_t *GetWmixt() const {return fWeights;} - Int_t *GetNmixt() const {return fNatoms;} - virtual Double_t GetSpecificActivity(Int_t i=-1) const; + Int_t GetByteCount() const override { return 48 + 12 * fNelements; } + TGeoElement *GetElement(Int_t i = 0) const override; + void GetElementProp(Double_t &a, Double_t &z, Double_t &w, Int_t i = 0) override + { + a = fAmixture[i]; + z = fZmixture[i]; + w = fWeights[i]; + } + Int_t GetNelements() const override { return fNelements; } + Double_t *GetZmixt() const { return fZmixture; } + Double_t *GetAmixt() const { return fAmixture; } + Double_t *GetWmixt() const { return fWeights; } + Int_t *GetNmixt() const { return fNatoms; } + Double_t GetSpecificActivity(Int_t i = -1) const override; // utilities - virtual Bool_t IsEq(const TGeoMaterial *other) const; - virtual Bool_t IsMixture() const {return kTRUE;} - virtual void Print(const Option_t *option="") const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetA(Double_t a) {fA = a;} - virtual void SetZ(Double_t z) {fZ = z;} - virtual void SetDensity(Double_t density) {fDensity = density; AverageProperties();} - void ComputeDerivedQuantities(); - void ComputeRadiationLength(); - void ComputeNuclearInterLength(); - - ClassDef(TGeoMixture, 3) // material mixtures + Bool_t IsEq(const TGeoMaterial *other) const override; + Bool_t IsMixture() const override { return kTRUE; } + void Print(const Option_t *option = "") const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetA(Double_t a) override { fA = a; } + void SetZ(Double_t z) override { fZ = z; } + void SetDensity(Double_t density) override + { + fDensity = density; + AverageProperties(); + } + void ComputeDerivedQuantities(); + void ComputeRadiationLength(); + void ComputeNuclearInterLength(); + + ClassDefOverride(TGeoMixture, 3) // material mixtures }; inline void TGeoMixture::DefineElement(Int_t, Double_t a, Double_t z, Double_t weight) - {return AddElement(a,z,weight);} +{ + return AddElement(a, z, weight); +} inline void TGeoMixture::DefineElement(Int_t, TGeoElement *elem, Double_t weight) - {return AddElement(elem,weight);} - +{ + return AddElement(elem, weight); +} #endif - diff --git a/geom/geom/inc/TGeoMatrix.h b/geom/geom/inc/TGeoMatrix.h index e66900463c28a..eac7ad81e34e9 100644 --- a/geom/geom/inc/TGeoMatrix.h +++ b/geom/geom/inc/TGeoMatrix.h @@ -21,13 +21,11 @@ #include "TNamed.h" //--- globals -const Double_t kNullVector[3] = {0.0, 0.0, 0.0}; +const Double_t kNullVector[3] = {0.0, 0.0, 0.0}; -const Double_t kIdentityMatrix[3*3] = {1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0}; +const Double_t kIdentityMatrix[3 * 3] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; -const Double_t kUnitScale[3] = {1.0, 1.0, 1.0}; +const Double_t kUnitScale[3] = {1.0, 1.0, 1.0}; class TGeoHMatrix; @@ -37,76 +35,73 @@ class TGeoHMatrix; // // //////////////////////////////////////////////////////////////////////////// -class TGeoMatrix : public TNamed -{ +class TGeoMatrix : public TNamed { public: -enum EGeoTransfTypes { - kGeoIdentity = 0, - kGeoShared = BIT(14), - kGeoTranslation = BIT(17), - kGeoRotation = BIT(18), - kGeoScale = BIT(19), - kGeoReflection = BIT(20), - kGeoRegistered = BIT(21), - kGeoSavePrimitive = BIT(22), - kGeoMatrixOwned = BIT(23), - kGeoCombiTrans = kGeoTranslation | kGeoRotation, - kGeoGenTrans = kGeoTranslation | kGeoRotation | kGeoScale, - kGeoMatrixBits = kGeoShared | kGeoGenTrans | kGeoReflection | kGeoRegistered | kGeoSavePrimitive | kGeoMatrixOwned -}; + enum EGeoTransfTypes { + kGeoIdentity = 0, + kGeoShared = BIT(14), + kGeoTranslation = BIT(17), + kGeoRotation = BIT(18), + kGeoScale = BIT(19), + kGeoReflection = BIT(20), + kGeoRegistered = BIT(21), + kGeoSavePrimitive = BIT(22), + kGeoMatrixOwned = BIT(23), + kGeoCombiTrans = kGeoTranslation | kGeoRotation, + kGeoGenTrans = kGeoTranslation | kGeoRotation | kGeoScale, + kGeoMatrixBits = kGeoShared | kGeoGenTrans | kGeoReflection | kGeoRegistered | kGeoSavePrimitive | kGeoMatrixOwned + }; protected: TGeoMatrix(const TGeoMatrix &other); -public : +public: TGeoMatrix(); TGeoMatrix(const char *name); - virtual ~TGeoMatrix(); - - Bool_t IsIdentity() const {return !TestBit(kGeoGenTrans);} - Bool_t IsTranslation() const {return TestBit(kGeoTranslation);} - Bool_t IsRotation() const {return TestBit(kGeoRotation);} - Bool_t IsReflection() const {return TestBit(kGeoReflection);} - Bool_t IsScale() const {return TestBit(kGeoScale);} - Bool_t IsShared() const {return TestBit(kGeoShared);} - Bool_t IsOwned() const {return TestBit(kGeoMatrixOwned);} - Bool_t IsCombi() const {return (TestBit(kGeoTranslation) - && TestBit(kGeoRotation));} - Bool_t IsGeneral() const {return (TestBit(kGeoTranslation) - && TestBit(kGeoRotation) && TestBit(kGeoScale));} - Bool_t IsRegistered() const {return TestBit(kGeoRegistered);} - Bool_t IsRotAboutZ() const; - void GetHomogenousMatrix(Double_t *hmat) const; - const char *GetPointerName() const; - - virtual Int_t GetByteCount() const; - virtual const Double_t *GetTranslation() const = 0; - virtual const Double_t *GetRotationMatrix() const = 0; - virtual const Double_t *GetScale() const = 0; - virtual TGeoHMatrix Inverse() const = 0; - virtual void LocalToMaster(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterBomb(const Double_t *local, Double_t *master) const; - virtual TGeoMatrix *MakeClone() const = 0; - virtual void MasterToLocal(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalBomb(const Double_t *master, Double_t *local) const; - static void Normalize(Double_t *vect); - void Print(Option_t *option="") const; // *MENU* - virtual void RotateX(Double_t) {} - virtual void RotateY(Double_t) {} - virtual void RotateZ(Double_t) {} - virtual void ReflectX(Bool_t leftside,Bool_t rotonly=kFALSE); - virtual void ReflectY(Bool_t leftside,Bool_t rotonly=kFALSE); - virtual void ReflectZ(Bool_t leftside,Bool_t rotonly=kFALSE); - virtual void RegisterYourself(); - void SetDefaultName(); - virtual void SetDx(Double_t) {} - virtual void SetDy(Double_t) {} - virtual void SetDz(Double_t) {} - void SetShared(Bool_t flag=kTRUE) {SetBit(kGeoShared, flag);} - - ClassDef(TGeoMatrix, 1) // base geometrical transformation class + ~TGeoMatrix() override; + + Bool_t IsIdentity() const { return !TestBit(kGeoGenTrans); } + Bool_t IsTranslation() const { return TestBit(kGeoTranslation); } + Bool_t IsRotation() const { return TestBit(kGeoRotation); } + Bool_t IsReflection() const { return TestBit(kGeoReflection); } + Bool_t IsScale() const { return TestBit(kGeoScale); } + Bool_t IsShared() const { return TestBit(kGeoShared); } + Bool_t IsOwned() const { return TestBit(kGeoMatrixOwned); } + Bool_t IsCombi() const { return (TestBit(kGeoTranslation) && TestBit(kGeoRotation)); } + Bool_t IsGeneral() const { return (TestBit(kGeoTranslation) && TestBit(kGeoRotation) && TestBit(kGeoScale)); } + Bool_t IsRegistered() const { return TestBit(kGeoRegistered); } + Bool_t IsRotAboutZ() const; + void GetHomogenousMatrix(Double_t *hmat) const; + const char *GetPointerName() const; + + virtual Int_t GetByteCount() const; + virtual const Double_t *GetTranslation() const = 0; + virtual const Double_t *GetRotationMatrix() const = 0; + virtual const Double_t *GetScale() const = 0; + virtual TGeoHMatrix Inverse() const = 0; + virtual void LocalToMaster(const Double_t *local, Double_t *master) const; + virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const; + virtual void LocalToMasterBomb(const Double_t *local, Double_t *master) const; + virtual TGeoMatrix *MakeClone() const = 0; + virtual void MasterToLocal(const Double_t *master, Double_t *local) const; + virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const; + virtual void MasterToLocalBomb(const Double_t *master, Double_t *local) const; + static void Normalize(Double_t *vect); + void Print(Option_t *option = "") const override; // *MENU* + virtual void RotateX(Double_t) {} + virtual void RotateY(Double_t) {} + virtual void RotateZ(Double_t) {} + virtual void ReflectX(Bool_t leftside, Bool_t rotonly = kFALSE); + virtual void ReflectY(Bool_t leftside, Bool_t rotonly = kFALSE); + virtual void ReflectZ(Bool_t leftside, Bool_t rotonly = kFALSE); + virtual void RegisterYourself(); + void SetDefaultName(); + virtual void SetDx(Double_t) {} + virtual void SetDy(Double_t) {} + virtual void SetDz(Double_t) {} + void SetShared(Bool_t flag = kTRUE) { SetBit(kGeoShared, flag); } + + ClassDefOverride(TGeoMatrix, 1) // base geometrical transformation class }; //////////////////////////////////////////////////////////////////////////// @@ -118,50 +113,49 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoTranslation : public TGeoMatrix -{ +class TGeoTranslation : public TGeoMatrix { protected: - Double_t fTranslation[3]; // translation vector -public : + Double_t fTranslation[3]; // translation vector +public: TGeoTranslation(); TGeoTranslation(const TGeoTranslation &other); TGeoTranslation(const TGeoMatrix &other); TGeoTranslation(Double_t dx, Double_t dy, Double_t dz); TGeoTranslation(const char *name, Double_t dx, Double_t dy, Double_t dz); - virtual ~TGeoTranslation() {} - - TGeoTranslation &operator =(const TGeoTranslation &other) {return TGeoTranslation::operator=((TGeoMatrix&)other);} - TGeoTranslation &operator =(const TGeoMatrix &matrix); - TGeoTranslation &operator *=(const TGeoTranslation &other); - TGeoTranslation operator *(const TGeoTranslation &right) const; - TGeoHMatrix operator *(const TGeoMatrix &right) const; - Bool_t operator ==(const TGeoTranslation &other) const; - - void Add(const TGeoTranslation *other); - TGeoHMatrix Inverse() const; - virtual void LocalToMaster(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterBomb(const Double_t *local, Double_t *master) const; - virtual TGeoMatrix *MakeClone() const; - virtual void MasterToLocal(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalBomb(const Double_t *master, Double_t *local) const; - virtual void RotateX(Double_t angle); - virtual void RotateY(Double_t angle); - virtual void RotateZ(Double_t angle); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void Subtract(const TGeoTranslation *other); - void SetTranslation(Double_t dx, Double_t dy, Double_t dz); - void SetTranslation(const TGeoMatrix &other); - virtual void SetDx(Double_t dx) {SetTranslation(dx, fTranslation[1], fTranslation[2]);} - virtual void SetDy(Double_t dy) {SetTranslation(fTranslation[0], dy, fTranslation[2]);} - virtual void SetDz(Double_t dz) {SetTranslation(fTranslation[0], fTranslation[1], dz);} - - virtual const Double_t *GetTranslation() const {return &fTranslation[0];} - virtual const Double_t *GetRotationMatrix() const {return &kIdentityMatrix[0];} - virtual const Double_t *GetScale() const {return &kUnitScale[0];} - - ClassDef(TGeoTranslation, 1) // translation class + ~TGeoTranslation() override {} + + TGeoTranslation &operator=(const TGeoTranslation &other) { return TGeoTranslation::operator=((TGeoMatrix &)other); } + TGeoTranslation &operator=(const TGeoMatrix &matrix); + TGeoTranslation &operator*=(const TGeoTranslation &other); + TGeoTranslation operator*(const TGeoTranslation &right) const; + TGeoHMatrix operator*(const TGeoMatrix &right) const; + Bool_t operator==(const TGeoTranslation &other) const; + + void Add(const TGeoTranslation *other); + TGeoHMatrix Inverse() const override; + void LocalToMaster(const Double_t *local, Double_t *master) const override; + void LocalToMasterVect(const Double_t *local, Double_t *master) const override; + void LocalToMasterBomb(const Double_t *local, Double_t *master) const override; + TGeoMatrix *MakeClone() const override; + void MasterToLocal(const Double_t *master, Double_t *local) const override; + void MasterToLocalVect(const Double_t *master, Double_t *local) const override; + void MasterToLocalBomb(const Double_t *master, Double_t *local) const override; + void RotateX(Double_t angle) override; + void RotateY(Double_t angle) override; + void RotateZ(Double_t angle) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void Subtract(const TGeoTranslation *other); + void SetTranslation(Double_t dx, Double_t dy, Double_t dz); + void SetTranslation(const TGeoMatrix &other); + void SetDx(Double_t dx) override { SetTranslation(dx, fTranslation[1], fTranslation[2]); } + void SetDy(Double_t dy) override { SetTranslation(fTranslation[0], dy, fTranslation[2]); } + void SetDz(Double_t dz) override { SetTranslation(fTranslation[0], fTranslation[1], dz); } + + const Double_t *GetTranslation() const override { return &fTranslation[0]; } + const Double_t *GetRotationMatrix() const override { return &kIdentityMatrix[0]; } + const Double_t *GetScale() const override { return &kUnitScale[0]; } + + ClassDefOverride(TGeoTranslation, 1) // translation class }; //////////////////////////////////////////////////////////////////////////// @@ -171,66 +165,81 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoRotation : public TGeoMatrix -{ +class TGeoRotation : public TGeoMatrix { protected: - Double_t fRotationMatrix[3*3]; // rotation matrix + Double_t fRotationMatrix[3 * 3]; // rotation matrix - void CheckMatrix(); -public : + void CheckMatrix(); + +public: TGeoRotation(); TGeoRotation(const TGeoRotation &other); TGeoRotation(const TGeoMatrix &other); TGeoRotation(const char *name); -// TGeoRotation(const char *name, Double_t *matrix) ; + // TGeoRotation(const char *name, Double_t *matrix) ; TGeoRotation(const char *name, Double_t phi, Double_t theta, Double_t psi); - TGeoRotation(const char *name, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3); - virtual ~TGeoRotation() {} - - TGeoRotation &operator =(const TGeoRotation &other) {return TGeoRotation::operator=((TGeoMatrix&)other);} - TGeoRotation &operator =(const TGeoMatrix &other); - TGeoRotation &operator *=(const TGeoRotation &other); - TGeoRotation operator *(const TGeoRotation &other) const; - TGeoHMatrix operator *(const TGeoMatrix &right) const; - Bool_t operator ==(const TGeoRotation &other) const; - - Bool_t IsValid() const; - TGeoHMatrix Inverse() const; - void Clear(Option_t *option =""); - Double_t Determinant() const; - void FastRotZ(const Double_t *sincos); - void GetAngles(Double_t &theta1, Double_t &phi1, Double_t &theta2, Double_t &phi2, - Double_t &theta3, Double_t &phi3) const; - void GetAngles(Double_t &phi, Double_t &theta, Double_t &psi) const; - Double_t GetPhiRotation(Bool_t fixX=kFALSE) const; - virtual void LocalToMaster(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const {TGeoRotation::LocalToMaster(local, master);} - virtual void LocalToMasterBomb(const Double_t *local, Double_t *master) const {TGeoRotation::LocalToMaster(local, master);} - virtual TGeoMatrix *MakeClone() const; - virtual void MasterToLocal(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const {TGeoRotation::MasterToLocal(master, local);} - virtual void MasterToLocalBomb(const Double_t *master, Double_t *local) const {TGeoRotation::MasterToLocal(master, local);} - void MultiplyBy(const TGeoRotation *rot, Bool_t after=kTRUE); - virtual void RotateX(Double_t angle); - virtual void RotateY(Double_t angle); - virtual void RotateZ(Double_t angle); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void ReflectX(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectY(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectZ(Bool_t leftside, Bool_t rotonly=kFALSE); - void SetAngles(Double_t phi, Double_t theta, Double_t psi); - void SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3); - void SetMatrix(const Double_t *rot) {memcpy(&fRotationMatrix[0], rot, 9*sizeof(Double_t));CheckMatrix();} - void SetRotation(const TGeoMatrix &other); - void GetInverse(Double_t *invmat) const; - - virtual const Double_t *GetTranslation() const {return &kNullVector[0];} - virtual const Double_t *GetRotationMatrix() const {return &fRotationMatrix[0];} - virtual const Double_t *GetScale() const {return &kUnitScale[0];} - - ClassDef(TGeoRotation, 1) // rotation class + TGeoRotation(const char *name, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, + Double_t phi3); + ~TGeoRotation() override {} + + TGeoRotation &operator=(const TGeoRotation &other) { return TGeoRotation::operator=((TGeoMatrix &)other); } + TGeoRotation &operator=(const TGeoMatrix &other); + TGeoRotation &operator*=(const TGeoRotation &other); + TGeoRotation operator*(const TGeoRotation &other) const; + TGeoHMatrix operator*(const TGeoMatrix &right) const; + Bool_t operator==(const TGeoRotation &other) const; + + Bool_t IsValid() const; + TGeoHMatrix Inverse() const override; + void Clear(Option_t *option = "") override; + Double_t Determinant() const; + void FastRotZ(const Double_t *sincos); + void GetAngles(Double_t &theta1, Double_t &phi1, Double_t &theta2, Double_t &phi2, Double_t &theta3, + Double_t &phi3) const; + void GetAngles(Double_t &phi, Double_t &theta, Double_t &psi) const; + Double_t GetPhiRotation(Bool_t fixX = kFALSE) const; + void LocalToMaster(const Double_t *local, Double_t *master) const override; + void LocalToMasterVect(const Double_t *local, Double_t *master) const override + { + TGeoRotation::LocalToMaster(local, master); + } + void LocalToMasterBomb(const Double_t *local, Double_t *master) const override + { + TGeoRotation::LocalToMaster(local, master); + } + TGeoMatrix *MakeClone() const override; + void MasterToLocal(const Double_t *master, Double_t *local) const override; + void MasterToLocalVect(const Double_t *master, Double_t *local) const override + { + TGeoRotation::MasterToLocal(master, local); + } + void MasterToLocalBomb(const Double_t *master, Double_t *local) const override + { + TGeoRotation::MasterToLocal(master, local); + } + void MultiplyBy(const TGeoRotation *rot, Bool_t after = kTRUE); + void RotateX(Double_t angle) override; + void RotateY(Double_t angle) override; + void RotateZ(Double_t angle) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void ReflectX(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectY(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectZ(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void SetAngles(Double_t phi, Double_t theta, Double_t psi); + void SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3); + void SetMatrix(const Double_t *rot) + { + memcpy(&fRotationMatrix[0], rot, 9 * sizeof(Double_t)); + CheckMatrix(); + } + void SetRotation(const TGeoMatrix &other); + void GetInverse(Double_t *invmat) const; + + const Double_t *GetTranslation() const override { return &kNullVector[0]; } + const Double_t *GetRotationMatrix() const override { return &fRotationMatrix[0]; } + const Double_t *GetScale() const override { return &kUnitScale[0]; } + + ClassDefOverride(TGeoRotation, 1) // rotation class }; //////////////////////////////////////////////////////////////////////////// @@ -241,44 +250,61 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoScale : public TGeoMatrix -{ +class TGeoScale : public TGeoMatrix { protected: - Double_t fScale[3]; // scale (x, y, z) -public : + Double_t fScale[3]; // scale (x, y, z) +public: TGeoScale(); TGeoScale(const TGeoScale &other); TGeoScale(const TGeoMatrix &other); TGeoScale(Double_t sx, Double_t sy, Double_t sz); TGeoScale(const char *name, Double_t sx, Double_t sy, Double_t sz); - virtual ~TGeoScale(); - - TGeoScale &operator =(const TGeoScale &other) {return TGeoScale::operator=((TGeoMatrix&)other);} - TGeoScale &operator =(const TGeoMatrix &other); - TGeoScale &operator *=(const TGeoScale &other); - TGeoScale operator *(const TGeoScale &other) const; - TGeoHMatrix operator *(const TGeoMatrix &right) const; - Bool_t operator ==(const TGeoScale &other) const; - - TGeoHMatrix Inverse() const; - void SetScale(Double_t sx, Double_t sy, Double_t sz); - void SetScale(const TGeoMatrix &other); - virtual void LocalToMaster(const Double_t *local, Double_t *master) const; - Double_t LocalToMaster(Double_t dist, const Double_t *dir=nullptr) const; - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const {TGeoScale::LocalToMaster(local, master);} - virtual TGeoMatrix *MakeClone() const; - virtual void MasterToLocal(const Double_t *master, Double_t *local) const; - Double_t MasterToLocal(Double_t dist, const Double_t *dir=nullptr) const; - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const {TGeoScale::MasterToLocal(master, local);} - virtual void ReflectX(Bool_t, Bool_t) {fScale[0]=-fScale[0]; SetBit(kGeoReflection, !IsReflection());} - virtual void ReflectY(Bool_t, Bool_t) {fScale[1]=-fScale[1]; SetBit(kGeoReflection, !IsReflection());} - virtual void ReflectZ(Bool_t, Bool_t) {fScale[2]=-fScale[2]; SetBit(kGeoReflection, !IsReflection());} - - virtual const Double_t *GetTranslation() const {return &kNullVector[0];} - virtual const Double_t *GetRotationMatrix() const {return &kIdentityMatrix[0];} - virtual const Double_t *GetScale() const {return &fScale[0];} - - ClassDef(TGeoScale, 1) // scaling class + ~TGeoScale() override; + + TGeoScale &operator=(const TGeoScale &other) { return TGeoScale::operator=((TGeoMatrix &)other); } + TGeoScale &operator=(const TGeoMatrix &other); + TGeoScale &operator*=(const TGeoScale &other); + TGeoScale operator*(const TGeoScale &other) const; + TGeoHMatrix operator*(const TGeoMatrix &right) const; + Bool_t operator==(const TGeoScale &other) const; + + TGeoHMatrix Inverse() const override; + void SetScale(Double_t sx, Double_t sy, Double_t sz); + void SetScale(const TGeoMatrix &other); + void LocalToMaster(const Double_t *local, Double_t *master) const override; + Double_t LocalToMaster(Double_t dist, const Double_t *dir = nullptr) const; + void LocalToMasterVect(const Double_t *local, Double_t *master) const override + { + TGeoScale::LocalToMaster(local, master); + } + TGeoMatrix *MakeClone() const override; + void MasterToLocal(const Double_t *master, Double_t *local) const override; + Double_t MasterToLocal(Double_t dist, const Double_t *dir = nullptr) const; + void MasterToLocalVect(const Double_t *master, Double_t *local) const override + { + TGeoScale::MasterToLocal(master, local); + } + void ReflectX(Bool_t, Bool_t) override + { + fScale[0] = -fScale[0]; + SetBit(kGeoReflection, !IsReflection()); + } + void ReflectY(Bool_t, Bool_t) override + { + fScale[1] = -fScale[1]; + SetBit(kGeoReflection, !IsReflection()); + } + void ReflectZ(Bool_t, Bool_t) override + { + fScale[2] = -fScale[2]; + SetBit(kGeoReflection, !IsReflection()); + } + + const Double_t *GetTranslation() const override { return &kNullVector[0]; } + const Double_t *GetRotationMatrix() const override { return &kIdentityMatrix[0]; } + const Double_t *GetScale() const override { return &fScale[0]; } + + ClassDefOverride(TGeoScale, 1) // scaling class }; //////////////////////////////////////////////////////////////////////////// @@ -288,56 +314,55 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoCombiTrans : public TGeoMatrix -{ +class TGeoCombiTrans : public TGeoMatrix { protected: - Double_t fTranslation[3]; // translation vector - TGeoRotation *fRotation; // rotation matrix -public : + Double_t fTranslation[3]; // translation vector + TGeoRotation *fRotation; // rotation matrix +public: TGeoCombiTrans(); - TGeoCombiTrans(const TGeoCombiTrans &other) : TGeoCombiTrans((TGeoMatrix&)other) {} + TGeoCombiTrans(const TGeoCombiTrans &other) : TGeoCombiTrans((TGeoMatrix &)other) {} TGeoCombiTrans(const TGeoMatrix &other); TGeoCombiTrans(const TGeoTranslation &tr, const TGeoRotation &rot); TGeoCombiTrans(const char *name); TGeoCombiTrans(Double_t dx, Double_t dy, Double_t dz, TGeoRotation *rot); TGeoCombiTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, TGeoRotation *rot); - TGeoCombiTrans& operator =(const TGeoCombiTrans &other) {return TGeoCombiTrans::operator=((TGeoMatrix&)other);} - TGeoCombiTrans& operator =(const TGeoMatrix &matrix); - TGeoCombiTrans &operator *=(const TGeoMatrix &other); - TGeoCombiTrans operator *(const TGeoMatrix &other) const; - Bool_t operator ==(const TGeoMatrix &other) const; - - virtual ~TGeoCombiTrans(); - - void Clear(Option_t *option =""); - TGeoHMatrix Inverse() const; - virtual TGeoMatrix *MakeClone() const; - void Multiply(const TGeoMatrix *right); - virtual void RegisterYourself(); - virtual void RotateX(Double_t angle); - virtual void RotateY(Double_t angle); - virtual void RotateZ(Double_t angle); - virtual void ReflectX(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectY(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectZ(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDx(Double_t dx) {SetTranslation(dx, fTranslation[1], fTranslation[2]);} - virtual void SetDy(Double_t dy) {SetTranslation(fTranslation[0], dy, fTranslation[2]);} - virtual void SetDz(Double_t dz) {SetTranslation(fTranslation[0], fTranslation[1], dz);} - void SetTranslation(const TGeoTranslation &tr); - void SetTranslation(Double_t dx, Double_t dy, Double_t dz); - void SetTranslation(Double_t *vect); - void SetRotation(const TGeoRotation &other); - void SetRotation(const TGeoRotation *rot); - - TGeoRotation *GetRotation() const {return fRotation;} - - virtual const Double_t *GetTranslation() const {return &fTranslation[0];} - virtual const Double_t *GetRotationMatrix() const; - virtual const Double_t *GetScale() const {return &kUnitScale[0];} - - ClassDef(TGeoCombiTrans, 1) // rotation + translation + TGeoCombiTrans &operator=(const TGeoCombiTrans &other) { return TGeoCombiTrans::operator=((TGeoMatrix &)other); } + TGeoCombiTrans &operator=(const TGeoMatrix &matrix); + TGeoCombiTrans &operator*=(const TGeoMatrix &other); + TGeoCombiTrans operator*(const TGeoMatrix &other) const; + Bool_t operator==(const TGeoMatrix &other) const; + + ~TGeoCombiTrans() override; + + void Clear(Option_t *option = "") override; + TGeoHMatrix Inverse() const override; + TGeoMatrix *MakeClone() const override; + void Multiply(const TGeoMatrix *right); + void RegisterYourself() override; + void RotateX(Double_t angle) override; + void RotateY(Double_t angle) override; + void RotateZ(Double_t angle) override; + void ReflectX(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectY(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectZ(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDx(Double_t dx) override { SetTranslation(dx, fTranslation[1], fTranslation[2]); } + void SetDy(Double_t dy) override { SetTranslation(fTranslation[0], dy, fTranslation[2]); } + void SetDz(Double_t dz) override { SetTranslation(fTranslation[0], fTranslation[1], dz); } + void SetTranslation(const TGeoTranslation &tr); + void SetTranslation(Double_t dx, Double_t dy, Double_t dz); + void SetTranslation(Double_t *vect); + void SetRotation(const TGeoRotation &other); + void SetRotation(const TGeoRotation *rot); + + TGeoRotation *GetRotation() const { return fRotation; } + + const Double_t *GetTranslation() const override { return &fTranslation[0]; } + const Double_t *GetRotationMatrix() const override; + const Double_t *GetScale() const override { return &kUnitScale[0]; } + + ClassDefOverride(TGeoCombiTrans, 1) // rotation + translation }; //////////////////////////////////////////////////////////////////////////// @@ -347,29 +372,27 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoGenTrans : public TGeoCombiTrans -{ +class TGeoGenTrans : public TGeoCombiTrans { protected: - Double_t fScale[3]; // scale (x, y, z) -public : + Double_t fScale[3]; // scale (x, y, z) +public: TGeoGenTrans(); TGeoGenTrans(const char *name); - TGeoGenTrans(Double_t dx, Double_t dy, Double_t dz, - Double_t sx, Double_t sy, Double_t sz, TGeoRotation *rot); - TGeoGenTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, - Double_t sx, Double_t sy, Double_t sz, TGeoRotation *rot); - virtual ~TGeoGenTrans(); - - void Clear(Option_t *option =""); - TGeoHMatrix Inverse() const; - void SetScale(Double_t sx, Double_t sy, Double_t sz); - void SetScale(Double_t *scale) {memcpy(&fScale[0], scale, 3*sizeof(Double_t));} - virtual TGeoMatrix *MakeClone() const {return nullptr;} - Bool_t Normalize(); - - virtual const Double_t *GetScale() const {return &fScale[0];} - - ClassDef(TGeoGenTrans, 1) // rotation + translation + scale + TGeoGenTrans(Double_t dx, Double_t dy, Double_t dz, Double_t sx, Double_t sy, Double_t sz, TGeoRotation *rot); + TGeoGenTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t sx, Double_t sy, Double_t sz, + TGeoRotation *rot); + ~TGeoGenTrans() override; + + void Clear(Option_t *option = "") override; + TGeoHMatrix Inverse() const override; + void SetScale(Double_t sx, Double_t sy, Double_t sz); + void SetScale(Double_t *scale) { memcpy(&fScale[0], scale, 3 * sizeof(Double_t)); } + TGeoMatrix *MakeClone() const override { return nullptr; } + Bool_t Normalize(); + + const Double_t *GetScale() const override { return &fScale[0]; } + + ClassDefOverride(TGeoGenTrans, 1) // rotation + translation + scale }; //////////////////////////////////////////////////////////////////////////// @@ -380,34 +403,49 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoIdentity : public TGeoMatrix -{ +class TGeoIdentity : public TGeoMatrix { private: // no data members -public : +public: TGeoIdentity(); TGeoIdentity(const char *name); - virtual ~TGeoIdentity() {} - - TGeoHMatrix Inverse() const; - virtual void LocalToMaster(const Double_t *local, Double_t *master) const {memcpy(master, local, 3*sizeof(Double_t));} - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const {memcpy(master, local, 3*sizeof(Double_t));} - virtual void LocalToMasterBomb(const Double_t *local, Double_t *master) const {TGeoIdentity::LocalToMaster(local, master);} - virtual TGeoMatrix *MakeClone() const {return nullptr;} - virtual void MasterToLocal(const Double_t *master, Double_t *local) const {memcpy(local, master, 3*sizeof(Double_t));} - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const {memcpy(local, master, 3*sizeof(Double_t));} - virtual void MasterToLocalBomb(const Double_t *master, Double_t *local) const {TGeoIdentity::MasterToLocal(master, local);} - - virtual const Double_t *GetTranslation() const {return &kNullVector[0];} - virtual const Double_t *GetRotationMatrix() const {return &kIdentityMatrix[0];} - virtual const Double_t *GetScale() const {return &kUnitScale[0];} - virtual void SavePrimitive(std::ostream &, Option_t * = "") {} - - ClassDef(TGeoIdentity, 1) // identity transformation class + ~TGeoIdentity() override {} + + TGeoHMatrix Inverse() const override; + void LocalToMaster(const Double_t *local, Double_t *master) const override + { + memcpy(master, local, 3 * sizeof(Double_t)); + } + void LocalToMasterVect(const Double_t *local, Double_t *master) const override + { + memcpy(master, local, 3 * sizeof(Double_t)); + } + void LocalToMasterBomb(const Double_t *local, Double_t *master) const override + { + TGeoIdentity::LocalToMaster(local, master); + } + TGeoMatrix *MakeClone() const override { return nullptr; } + void MasterToLocal(const Double_t *master, Double_t *local) const override + { + memcpy(local, master, 3 * sizeof(Double_t)); + } + void MasterToLocalVect(const Double_t *master, Double_t *local) const override + { + memcpy(local, master, 3 * sizeof(Double_t)); + } + void MasterToLocalBomb(const Double_t *master, Double_t *local) const override + { + TGeoIdentity::MasterToLocal(master, local); + } + + const Double_t *GetTranslation() const override { return &kNullVector[0]; } + const Double_t *GetRotationMatrix() const override { return &kIdentityMatrix[0]; } + const Double_t *GetScale() const override { return &kUnitScale[0]; } + void SavePrimitive(std::ostream &, Option_t * = "") override {} + + ClassDefOverride(TGeoIdentity, 1) // identity transformation class }; - - //////////////////////////////////////////////////////////////////////////// // // // TGeoHMatrix - Matrix class used for computing global transformations // @@ -417,65 +455,85 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoHMatrix : public TGeoMatrix -{ +class TGeoHMatrix : public TGeoMatrix { private: - Double_t fTranslation[3]; // translation component - Double_t fRotationMatrix[9]; // rotation matrix - Double_t fScale[3]; // scale component + Double_t fTranslation[3]; // translation component + Double_t fRotationMatrix[9]; // rotation matrix + Double_t fScale[3]; // scale component -public : +public: TGeoHMatrix(); - TGeoHMatrix(const TGeoHMatrix &other) : TGeoHMatrix((TGeoMatrix&)other) {} + TGeoHMatrix(const TGeoHMatrix &other) : TGeoHMatrix((TGeoMatrix &)other) {} TGeoHMatrix(const TGeoMatrix &matrix); TGeoHMatrix(const char *name); - virtual ~TGeoHMatrix(); - - TGeoHMatrix& operator =(const TGeoHMatrix &other) {return TGeoHMatrix::operator=((TGeoMatrix&)other);} - TGeoHMatrix& operator =(const TGeoMatrix *other); - TGeoHMatrix& operator =(const TGeoMatrix &other); - TGeoHMatrix& operator *=(const TGeoMatrix &other); - TGeoHMatrix operator *(const TGeoMatrix &other) const; - Bool_t operator ==(const TGeoMatrix &other) const; - - void Clear(Option_t *option =""); - void CopyFrom(const TGeoMatrix *other); - Double_t Determinant() const; - void FastRotZ(const Double_t *sincos); - TGeoHMatrix Inverse() const; - virtual TGeoMatrix *MakeClone() const; - void Multiply(const TGeoMatrix *right); - void Multiply(const TGeoMatrix &right) {Multiply(&right);} - void MultiplyLeft(const TGeoMatrix *left); - void MultiplyLeft(const TGeoMatrix &left) {MultiplyLeft(&left);} - - virtual void RotateX(Double_t angle); - virtual void RotateY(Double_t angle); - virtual void RotateZ(Double_t angle); - virtual void ReflectX(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectY(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void ReflectZ(Bool_t leftside, Bool_t rotonly=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDx(Double_t dx) {fTranslation[0] = dx; SetBit(kGeoTranslation);} - virtual void SetDy(Double_t dy) {fTranslation[1] = dy; SetBit(kGeoTranslation);} - virtual void SetDz(Double_t dz) {fTranslation[2] = dz; SetBit(kGeoTranslation);} - void SetTranslation(const Double_t *vect) {SetBit(kGeoTranslation); memcpy(&fTranslation[0], vect, 3*sizeof(Double_t));} - void SetRotation(const Double_t *matrix) {SetBit(kGeoRotation); memcpy(&fRotationMatrix[0], matrix, 9*sizeof(Double_t));} - void SetScale(const Double_t *scale) {SetBit(kGeoScale); memcpy(&fScale[0], scale, 3*sizeof(Double_t));} - - - virtual const Double_t *GetTranslation() const {return &fTranslation[0];} - virtual const Double_t *GetRotationMatrix() const {return &fRotationMatrix[0];} - virtual const Double_t *GetScale() const {return &fScale[0];} - - virtual Double_t *GetTranslation() {return &fTranslation[0];} - virtual Double_t *GetRotationMatrix() {return &fRotationMatrix[0];} - virtual Double_t *GetScale() {return &fScale[0];} - ClassDef(TGeoHMatrix, 1) // global matrix class + ~TGeoHMatrix() override; + + TGeoHMatrix &operator=(const TGeoHMatrix &other) { return TGeoHMatrix::operator=((TGeoMatrix &)other); } + TGeoHMatrix &operator=(const TGeoMatrix *other); + TGeoHMatrix &operator=(const TGeoMatrix &other); + TGeoHMatrix &operator*=(const TGeoMatrix &other); + TGeoHMatrix operator*(const TGeoMatrix &other) const; + Bool_t operator==(const TGeoMatrix &other) const; + + void Clear(Option_t *option = "") override; + void CopyFrom(const TGeoMatrix *other); + Double_t Determinant() const; + void FastRotZ(const Double_t *sincos); + TGeoHMatrix Inverse() const override; + TGeoMatrix *MakeClone() const override; + void Multiply(const TGeoMatrix *right); + void Multiply(const TGeoMatrix &right) { Multiply(&right); } + void MultiplyLeft(const TGeoMatrix *left); + void MultiplyLeft(const TGeoMatrix &left) { MultiplyLeft(&left); } + + void RotateX(Double_t angle) override; + void RotateY(Double_t angle) override; + void RotateZ(Double_t angle) override; + void ReflectX(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectY(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void ReflectZ(Bool_t leftside, Bool_t rotonly = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDx(Double_t dx) override + { + fTranslation[0] = dx; + SetBit(kGeoTranslation); + } + void SetDy(Double_t dy) override + { + fTranslation[1] = dy; + SetBit(kGeoTranslation); + } + void SetDz(Double_t dz) override + { + fTranslation[2] = dz; + SetBit(kGeoTranslation); + } + void SetTranslation(const Double_t *vect) + { + SetBit(kGeoTranslation); + memcpy(&fTranslation[0], vect, 3 * sizeof(Double_t)); + } + void SetRotation(const Double_t *matrix) + { + SetBit(kGeoRotation); + memcpy(&fRotationMatrix[0], matrix, 9 * sizeof(Double_t)); + } + void SetScale(const Double_t *scale) + { + SetBit(kGeoScale); + memcpy(&fScale[0], scale, 3 * sizeof(Double_t)); + } + + const Double_t *GetTranslation() const override { return &fTranslation[0]; } + const Double_t *GetRotationMatrix() const override { return &fRotationMatrix[0]; } + const Double_t *GetScale() const override { return &fScale[0]; } + + virtual Double_t *GetTranslation() { return &fTranslation[0]; } + virtual Double_t *GetRotationMatrix() { return &fRotationMatrix[0]; } + virtual Double_t *GetScale() { return &fScale[0]; } + ClassDefOverride(TGeoHMatrix, 1) // global matrix class }; - R__EXTERN TGeoIdentity *gGeoIdentity; #endif - diff --git a/geom/geom/inc/TGeoMedium.h b/geom/geom/inc/TGeoMedium.h index bd846e3cd990b..8f68205fa3134 100644 --- a/geom/geom/inc/TGeoMedium.h +++ b/geom/geom/inc/TGeoMedium.h @@ -20,43 +20,38 @@ // // //////////////////////////////////////////////////////////////////////////// -class TGeoMedium : public TNamed -{ +class TGeoMedium : public TNamed { public: - enum EGeoMedium { - kMedSavePrimitive = BIT(18) - }; + enum EGeoMedium { kMedSavePrimitive = BIT(18) }; protected: - Int_t fId; // unique Id - Double_t fParams[20]; // parameters - TGeoMaterial *fMaterial; // pointer to material + Int_t fId; // unique Id + Double_t fParams[20]; // parameters + TGeoMaterial *fMaterial; // pointer to material -// methods - TGeoMedium(const TGeoMedium&); - TGeoMedium& operator=(const TGeoMedium&); + // methods + TGeoMedium(const TGeoMedium &); + TGeoMedium &operator=(const TGeoMedium &); public: // constructors TGeoMedium(); - TGeoMedium(const char *name, Int_t numed, const TGeoMaterial *mat, Double_t *params=nullptr); - TGeoMedium(const char *name, Int_t numed, Int_t imat, Int_t isvol, Int_t ifield, - Double_t fieldm, Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin); - virtual ~TGeoMedium(); + TGeoMedium(const char *name, Int_t numed, const TGeoMaterial *mat, Double_t *params = nullptr); + TGeoMedium(const char *name, Int_t numed, Int_t imat, Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd, + Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin); + ~TGeoMedium() override; // methods - virtual Int_t GetByteCount() const {return sizeof(*this);} - Int_t GetId() const {return fId;} - Double_t GetParam(Int_t i) const {return fParams[i];} - void SetParam(Int_t i, Double_t val) {fParams[i] = val;} - const char *GetPointerName() const; - TGeoMaterial *GetMaterial() const {return fMaterial;} - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetId(Int_t id) {fId = id;} - void SetMaterial(TGeoMaterial *mat) {fMaterial = mat;} - virtual void SetCerenkovProperties(TObject* cerenkov) {fMaterial->SetCerenkovProperties(cerenkov);} - ClassDef(TGeoMedium, 1) // tracking medium - + virtual Int_t GetByteCount() const { return sizeof(*this); } + Int_t GetId() const { return fId; } + Double_t GetParam(Int_t i) const { return fParams[i]; } + void SetParam(Int_t i, Double_t val) { fParams[i] = val; } + const char *GetPointerName() const; + TGeoMaterial *GetMaterial() const { return fMaterial; } + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetId(Int_t id) { fId = id; } + void SetMaterial(TGeoMaterial *mat) { fMaterial = mat; } + virtual void SetCerenkovProperties(TObject *cerenkov) { fMaterial->SetCerenkovProperties(cerenkov); } + ClassDefOverride(TGeoMedium, 1) // tracking medium }; #endif - diff --git a/geom/geom/inc/TGeoNavigator.h b/geom/geom/inc/TGeoNavigator.h index 0c87363367b1d..dbf46801897c6 100644 --- a/geom/geom/inc/TGeoNavigator.h +++ b/geom/geom/inc/TGeoNavigator.h @@ -29,179 +29,225 @@ class TGeoVolume; class TGeoMatrix; class TGeoHMatrix; - -class TGeoNavigator : public TObject -{ +class TGeoNavigator : public TObject { protected: TGeoNavigator(const TGeoNavigator &) = delete; - TGeoNavigator& operator=(const TGeoNavigator &) = delete; - TGeoNode *FindInCluster(Int_t *cluster, Int_t nc); - Int_t GetTouchedCluster(Int_t start, Double_t *point, Int_t *check_list, - Int_t ncheck, Int_t *result); - TGeoNode *CrossDivisionCell(); - void SafetyOverlaps(); - -private : - Double_t fStep; //! step to be done from current point and direction - Double_t fSafety; //! safety radius from current point - Double_t fLastSafety; //! last computed safety radius - Double_t fNormal[3]; //! cosine of incident angle on current checked surface - Double_t fCldir[3]; //! unit vector to current closest shape - Double_t fCldirChecked[3]; //! unit vector to current checked shape - Double_t fPoint[3]; //! current point - Double_t fDirection[3]; //! current direction - Double_t fLastPoint[3]; //! last point for which safety was computed - Int_t fThreadId; //! thread id for this navigator - Int_t fLevel; //! current geometry level; - Int_t fNmany; //! number of overlapping nodes on current branch - Int_t fNextDaughterIndex; //! next daughter index after FindNextBoundary - Int_t fOverlapSize; //! current size of fOverlapClusters - Int_t fOverlapMark; //! current recursive position in fOverlapClusters - Int_t *fOverlapClusters; //! internal array for overlaps - Bool_t fSearchOverlaps; //! flag set when an overlapping cluster is searched - Bool_t fCurrentOverlapping; //! flags the type of the current node - Bool_t fStartSafe; //! flag a safe start for point classification - Bool_t fIsEntering; //! flag if current step just got into a new node - Bool_t fIsExiting; //! flag that current track is about to leave current node - Bool_t fIsStepEntering; //! flag that next geometric step will enter new volume - Bool_t fIsStepExiting; //! flag that next geometric step will exit current volume - Bool_t fIsOutside; //! flag that current point is outside geometry - Bool_t fIsOnBoundary; //! flag that current point is on some boundary - Bool_t fIsSameLocation; //! flag that a new point is in the same node as previous - Bool_t fIsNullStep; //! flag that last geometric step was null - TGeoManager *fGeometry; //! current geometry - TGeoNodeCache *fCache; //! cache of states - TGeoVolume *fCurrentVolume; //! current volume - TGeoNode *fCurrentNode; //! current node - TGeoNode *fTopNode; //! top physical node - TGeoNode *fLastNode; //! last searched node - TGeoNode *fNextNode; //! next node that will be crossed - TGeoNode *fForcedNode; //! current point is supposed to be inside this node - TGeoCacheState *fBackupState; //! backup state - TGeoHMatrix *fCurrentMatrix; //! current stored global matrix - TGeoHMatrix *fGlobalMatrix; //! current pointer to cached global matrix - TGeoHMatrix *fDivMatrix; //! current local matrix of the selected division cell - TString fPath; //! path to current node - -public : + TGeoNavigator &operator=(const TGeoNavigator &) = delete; + TGeoNode *FindInCluster(Int_t *cluster, Int_t nc); + Int_t GetTouchedCluster(Int_t start, Double_t *point, Int_t *check_list, Int_t ncheck, Int_t *result); + TGeoNode *CrossDivisionCell(); + void SafetyOverlaps(); + +private: + Double_t fStep; //! step to be done from current point and direction + Double_t fSafety; //! safety radius from current point + Double_t fLastSafety; //! last computed safety radius + Double_t fNormal[3]; //! cosine of incident angle on current checked surface + Double_t fCldir[3]; //! unit vector to current closest shape + Double_t fCldirChecked[3]; //! unit vector to current checked shape + Double_t fPoint[3]; //! current point + Double_t fDirection[3]; //! current direction + Double_t fLastPoint[3]; //! last point for which safety was computed + Int_t fThreadId; //! thread id for this navigator + Int_t fLevel; //! current geometry level; + Int_t fNmany; //! number of overlapping nodes on current branch + Int_t fNextDaughterIndex; //! next daughter index after FindNextBoundary + Int_t fOverlapSize; //! current size of fOverlapClusters + Int_t fOverlapMark; //! current recursive position in fOverlapClusters + Int_t *fOverlapClusters; //! internal array for overlaps + Bool_t fSearchOverlaps; //! flag set when an overlapping cluster is searched + Bool_t fCurrentOverlapping; //! flags the type of the current node + Bool_t fStartSafe; //! flag a safe start for point classification + Bool_t fIsEntering; //! flag if current step just got into a new node + Bool_t fIsExiting; //! flag that current track is about to leave current node + Bool_t fIsStepEntering; //! flag that next geometric step will enter new volume + Bool_t fIsStepExiting; //! flag that next geometric step will exit current volume + Bool_t fIsOutside; //! flag that current point is outside geometry + Bool_t fIsOnBoundary; //! flag that current point is on some boundary + Bool_t fIsSameLocation; //! flag that a new point is in the same node as previous + Bool_t fIsNullStep; //! flag that last geometric step was null + TGeoManager *fGeometry; //! current geometry + TGeoNodeCache *fCache; //! cache of states + TGeoVolume *fCurrentVolume; //! current volume + TGeoNode *fCurrentNode; //! current node + TGeoNode *fTopNode; //! top physical node + TGeoNode *fLastNode; //! last searched node + TGeoNode *fNextNode; //! next node that will be crossed + TGeoNode *fForcedNode; //! current point is supposed to be inside this node + TGeoCacheState *fBackupState; //! backup state + TGeoHMatrix *fCurrentMatrix; //! current stored global matrix + TGeoHMatrix *fGlobalMatrix; //! current pointer to cached global matrix + TGeoHMatrix *fDivMatrix; //! current local matrix of the selected division cell + TString fPath; //! path to current node + +public: TGeoNavigator(); - TGeoNavigator(TGeoManager* geom); - virtual ~TGeoNavigator(); - - void BuildCache(Bool_t dummy=kFALSE, Bool_t nodeid=kFALSE); - Bool_t cd(const char *path=""); - Bool_t CheckPath(const char *path) const; - void CdNode(Int_t nodeid); - void CdDown(Int_t index); - void CdDown(TGeoNode *node); - void CdUp(); - void CdTop(); - void CdNext(); - void GetBranchNames(Int_t *names) const; - void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; - void GetBranchOnlys(Int_t *isonly) const; - Int_t GetNmany() const {return fNmany;} + TGeoNavigator(TGeoManager *geom); + ~TGeoNavigator() override; + + void BuildCache(Bool_t dummy = kFALSE, Bool_t nodeid = kFALSE); + Bool_t cd(const char *path = ""); + Bool_t CheckPath(const char *path) const; + void CdNode(Int_t nodeid); + void CdDown(Int_t index); + void CdDown(TGeoNode *node); + void CdUp(); + void CdTop(); + void CdNext(); + void GetBranchNames(Int_t *names) const; + void GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const; + void GetBranchOnlys(Int_t *isonly) const; + Int_t GetNmany() const { return fNmany; } //--- geometry queries - TGeoNode *CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skipnode); - TGeoNode *FindNextBoundary(Double_t stepmax=TGeoShape::Big(),const char *path="", Bool_t frombdr=kFALSE); - TGeoNode *FindNextDaughterBoundary(Double_t *point, Double_t *dir, Int_t &idaughter, Bool_t compmatrix=kFALSE); - TGeoNode *FindNextBoundaryAndStep(Double_t stepmax=TGeoShape::Big(), Bool_t compsafe=kFALSE); - TGeoNode *FindNode(Bool_t safe_start=kTRUE); - TGeoNode *FindNode(Double_t x, Double_t y, Double_t z); - Double_t *FindNormal(Bool_t forward=kTRUE); - Double_t *FindNormalFast(); - TGeoNode *InitTrack(const Double_t *point, const Double_t *dir); - TGeoNode *InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz); - void ResetState(); - void ResetAll(); - Double_t Safety(Bool_t inside=kFALSE); - TGeoNode *SearchNode(Bool_t downwards=kFALSE, const TGeoNode *skipnode=nullptr); - TGeoNode *Step(Bool_t is_geom=kTRUE, Bool_t cross=kTRUE); - const Double_t *GetLastPoint() const {return fLastPoint;} - Int_t GetVirtualLevel(); - Bool_t GotoSafeLevel(); - Int_t GetSafeLevel() const; - Double_t GetSafeDistance() const {return fSafety;} - Double_t GetLastSafety() const {return fLastSafety;} - Double_t GetStep() const {return fStep;} - Int_t GetThreadId() const {return fThreadId;} - void InspectState() const; - Bool_t IsSafeStep(Double_t proposed, Double_t &newsafety) const; - Bool_t IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change=kFALSE); - Bool_t IsSameLocation() const {return fIsSameLocation;} - Bool_t IsSamePoint(Double_t x, Double_t y, Double_t z) const; - Bool_t IsStartSafe() const {return fStartSafe;} - void SetStartSafe(Bool_t flag=kTRUE) {fStartSafe=flag;} - void SetStep(Double_t step) {fStep=step;} - Bool_t IsCheckingOverlaps() const {return fSearchOverlaps;} - Bool_t IsCurrentOverlapping() const {return fCurrentOverlapping;} - Bool_t IsEntering() const {return fIsEntering;} - Bool_t IsExiting() const {return fIsExiting;} - Bool_t IsStepEntering() const {return fIsStepEntering;} - Bool_t IsStepExiting() const {return fIsStepExiting;} - Bool_t IsOutside() const {return fIsOutside;} - Bool_t IsOnBoundary() const {return fIsOnBoundary;} - Bool_t IsNullStep() const {return fIsNullStep;} - void SetCheckingOverlaps(Bool_t flag=kTRUE) {fSearchOverlaps = flag;} - void SetOutside(Bool_t flag=kTRUE) {fIsOutside = flag;} + TGeoNode *CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skipnode); + TGeoNode *FindNextBoundary(Double_t stepmax = TGeoShape::Big(), const char *path = "", Bool_t frombdr = kFALSE); + TGeoNode *FindNextDaughterBoundary(Double_t *point, Double_t *dir, Int_t &idaughter, Bool_t compmatrix = kFALSE); + TGeoNode *FindNextBoundaryAndStep(Double_t stepmax = TGeoShape::Big(), Bool_t compsafe = kFALSE); + TGeoNode *FindNode(Bool_t safe_start = kTRUE); + TGeoNode *FindNode(Double_t x, Double_t y, Double_t z); + Double_t *FindNormal(Bool_t forward = kTRUE); + Double_t *FindNormalFast(); + TGeoNode *InitTrack(const Double_t *point, const Double_t *dir); + TGeoNode *InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz); + void ResetState(); + void ResetAll(); + Double_t Safety(Bool_t inside = kFALSE); + TGeoNode *SearchNode(Bool_t downwards = kFALSE, const TGeoNode *skipnode = nullptr); + TGeoNode *Step(Bool_t is_geom = kTRUE, Bool_t cross = kTRUE); + const Double_t *GetLastPoint() const { return fLastPoint; } + Int_t GetVirtualLevel(); + Bool_t GotoSafeLevel(); + Int_t GetSafeLevel() const; + Double_t GetSafeDistance() const { return fSafety; } + Double_t GetLastSafety() const { return fLastSafety; } + Double_t GetStep() const { return fStep; } + Int_t GetThreadId() const { return fThreadId; } + void InspectState() const; + Bool_t IsSafeStep(Double_t proposed, Double_t &newsafety) const; + Bool_t IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change = kFALSE); + Bool_t IsSameLocation() const { return fIsSameLocation; } + Bool_t IsSamePoint(Double_t x, Double_t y, Double_t z) const; + Bool_t IsStartSafe() const { return fStartSafe; } + void SetStartSafe(Bool_t flag = kTRUE) { fStartSafe = flag; } + void SetStep(Double_t step) { fStep = step; } + Bool_t IsCheckingOverlaps() const { return fSearchOverlaps; } + Bool_t IsCurrentOverlapping() const { return fCurrentOverlapping; } + Bool_t IsEntering() const { return fIsEntering; } + Bool_t IsExiting() const { return fIsExiting; } + Bool_t IsStepEntering() const { return fIsStepEntering; } + Bool_t IsStepExiting() const { return fIsStepExiting; } + Bool_t IsOutside() const { return fIsOutside; } + Bool_t IsOnBoundary() const { return fIsOnBoundary; } + Bool_t IsNullStep() const { return fIsNullStep; } + void SetCheckingOverlaps(Bool_t flag = kTRUE) { fSearchOverlaps = flag; } + void SetOutside(Bool_t flag = kTRUE) { fIsOutside = flag; } //--- modeler state getters/setters - void DoBackupState(); - void DoRestoreState(); - Int_t GetNodeId() const {return fCache->GetNodeId();} - Int_t GetNextDaughterIndex() const {return fNextDaughterIndex;} - TGeoNode *GetNextNode() const {return fNextNode;} - TGeoNode *GetMother(Int_t up=1) const {return fCache->GetMother(up);} - TGeoHMatrix *GetMotherMatrix(Int_t up=1) const {return fCache->GetMotherMatrix(up);} - TGeoHMatrix *GetHMatrix(); - TGeoHMatrix *GetCurrentMatrix() const {return fCache->GetCurrentMatrix();} - TGeoNode *GetCurrentNode() const {return fCurrentNode;} - Int_t GetCurrentNodeId() const {return fCache->GetCurrentNodeId();} - const Double_t *GetCurrentPoint() const {return fPoint;} - const Double_t *GetCurrentDirection() const {return fDirection;} - TGeoVolume *GetCurrentVolume() const {return fCurrentNode->GetVolume();} - const Double_t *GetCldirChecked() const {return fCldirChecked;} - const Double_t *GetCldir() const {return fCldir;} - TGeoHMatrix *GetDivMatrix() const {return fDivMatrix;} -// Double_t GetNormalChecked() const {return fNormalChecked;} - const Double_t *GetNormal() const {return fNormal;} - Int_t GetLevel() const {return fLevel;} - const char *GetPath() const; - Int_t GetStackLevel() const {return fCache->GetStackLevel();} - void SetCurrentPoint(const Double_t *point) {memcpy(fPoint,point,3*sizeof(Double_t));} - void SetCurrentPoint(Double_t x, Double_t y, Double_t z) { - fPoint[0]=x; fPoint[1]=y; fPoint[2]=z;} - void SetLastPoint(Double_t x, Double_t y, Double_t z) { - fLastPoint[0]=x; fLastPoint[1]=y; fLastPoint[2]=z;} - void SetCurrentDirection(const Double_t *dir) {memcpy(fDirection,dir,3*sizeof(Double_t));} - void SetCurrentDirection(Double_t nx, Double_t ny, Double_t nz) { - fDirection[0]=nx; fDirection[1]=ny; fDirection[2]=nz;} -// void SetNormalChecked(Double_t norm) {fNormalChecked=norm;} - void SetCldirChecked(Double_t *dir) {memcpy(fCldirChecked, dir, 3*sizeof(Double_t));} - void SetLastSafetyForPoint(Double_t safe, const Double_t *point) {fLastSafety=safe; memcpy(fLastPoint,point,3*sizeof(Double_t));} - void SetLastSafetyForPoint(Double_t safe, Double_t x, Double_t y, Double_t z) {fLastSafety=safe; fLastPoint[0]=x; fLastPoint[1]=y, fLastPoint[2]=z;} + void DoBackupState(); + void DoRestoreState(); + Int_t GetNodeId() const { return fCache->GetNodeId(); } + Int_t GetNextDaughterIndex() const { return fNextDaughterIndex; } + TGeoNode *GetNextNode() const { return fNextNode; } + TGeoNode *GetMother(Int_t up = 1) const { return fCache->GetMother(up); } + TGeoHMatrix *GetMotherMatrix(Int_t up = 1) const { return fCache->GetMotherMatrix(up); } + TGeoHMatrix *GetHMatrix(); + TGeoHMatrix *GetCurrentMatrix() const { return fCache->GetCurrentMatrix(); } + TGeoNode *GetCurrentNode() const { return fCurrentNode; } + Int_t GetCurrentNodeId() const { return fCache->GetCurrentNodeId(); } + const Double_t *GetCurrentPoint() const { return fPoint; } + const Double_t *GetCurrentDirection() const { return fDirection; } + TGeoVolume *GetCurrentVolume() const { return fCurrentNode->GetVolume(); } + const Double_t *GetCldirChecked() const { return fCldirChecked; } + const Double_t *GetCldir() const { return fCldir; } + TGeoHMatrix *GetDivMatrix() const { return fDivMatrix; } + // Double_t GetNormalChecked() const {return fNormalChecked;} + const Double_t *GetNormal() const { return fNormal; } + Int_t GetLevel() const { return fLevel; } + const char *GetPath() const; + Int_t GetStackLevel() const { return fCache->GetStackLevel(); } + void SetCurrentPoint(const Double_t *point) { memcpy(fPoint, point, 3 * sizeof(Double_t)); } + void SetCurrentPoint(Double_t x, Double_t y, Double_t z) + { + fPoint[0] = x; + fPoint[1] = y; + fPoint[2] = z; + } + void SetLastPoint(Double_t x, Double_t y, Double_t z) + { + fLastPoint[0] = x; + fLastPoint[1] = y; + fLastPoint[2] = z; + } + void SetCurrentDirection(const Double_t *dir) { memcpy(fDirection, dir, 3 * sizeof(Double_t)); } + void SetCurrentDirection(Double_t nx, Double_t ny, Double_t nz) + { + fDirection[0] = nx; + fDirection[1] = ny; + fDirection[2] = nz; + } + // void SetNormalChecked(Double_t norm) {fNormalChecked=norm;} + void SetCldirChecked(Double_t *dir) { memcpy(fCldirChecked, dir, 3 * sizeof(Double_t)); } + void SetLastSafetyForPoint(Double_t safe, const Double_t *point) + { + fLastSafety = safe; + memcpy(fLastPoint, point, 3 * sizeof(Double_t)); + } + void SetLastSafetyForPoint(Double_t safe, Double_t x, Double_t y, Double_t z) + { + fLastSafety = safe; + fLastPoint[0] = x; + fLastPoint[1] = y, fLastPoint[2] = z; + } //--- point/vector reference frame conversion - void LocalToMaster(const Double_t *local, Double_t *master) const {fCache->LocalToMaster(local, master);} - void LocalToMasterVect(const Double_t *local, Double_t *master) const {fCache->LocalToMasterVect(local, master);} - void LocalToMasterBomb(const Double_t *local, Double_t *master) const {fCache->LocalToMasterBomb(local, master);} - void MasterToLocal(const Double_t *master, Double_t *local) const {fCache->MasterToLocal(master, local);} - void MasterToLocalVect(const Double_t *master, Double_t *local) const {fCache->MasterToLocalVect(master, local);} - void MasterToLocalBomb(const Double_t *master, Double_t *local) const {fCache->MasterToLocalBomb(master, local);} - void MasterToTop(const Double_t *master, Double_t *top) const; - void TopToMaster(const Double_t *top, Double_t *master) const; - TGeoNodeCache *GetCache() const {return fCache;} -// void SetCache(const TGeoNodeCache *cache) {fCache = (TGeoNodeCache*)cache;} + void LocalToMaster(const Double_t *local, Double_t *master) const { fCache->LocalToMaster(local, master); } + void LocalToMasterVect(const Double_t *local, Double_t *master) const { fCache->LocalToMasterVect(local, master); } + void LocalToMasterBomb(const Double_t *local, Double_t *master) const { fCache->LocalToMasterBomb(local, master); } + void MasterToLocal(const Double_t *master, Double_t *local) const { fCache->MasterToLocal(master, local); } + void MasterToLocalVect(const Double_t *master, Double_t *local) const { fCache->MasterToLocalVect(master, local); } + void MasterToLocalBomb(const Double_t *master, Double_t *local) const { fCache->MasterToLocalBomb(master, local); } + void MasterToTop(const Double_t *master, Double_t *top) const; + void TopToMaster(const Double_t *top, Double_t *master) const; + TGeoNodeCache *GetCache() const { return fCache; } + // void SetCache(const TGeoNodeCache *cache) {fCache = (TGeoNodeCache*)cache;} //--- stack manipulation - Int_t PushPath(Int_t startlevel=0) {return fCache->PushState(fCurrentOverlapping, startlevel, fNmany);} - Bool_t PopPath() {fCurrentOverlapping=fCache->PopState(fNmany); fCurrentNode=fCache->GetNode(); fLevel=fCache->GetLevel();fGlobalMatrix=fCache->GetCurrentMatrix();return fCurrentOverlapping;} - Bool_t PopPath(Int_t index) {fCurrentOverlapping=fCache->PopState(fNmany,index); fCurrentNode=fCache->GetNode(); fLevel=fCache->GetLevel();fGlobalMatrix=fCache->GetCurrentMatrix();return fCurrentOverlapping;} - Int_t PushPoint(Int_t startlevel=0) {return fCache->PushState(fCurrentOverlapping, startlevel,fNmany,fPoint);} - Bool_t PopPoint() {fCurrentOverlapping=fCache->PopState(fNmany,fPoint); fCurrentNode=fCache->GetNode(); fLevel=fCache->GetLevel(); fGlobalMatrix=fCache->GetCurrentMatrix();return fCurrentOverlapping;} - Bool_t PopPoint(Int_t index) {fCurrentOverlapping=fCache->PopState(fNmany,index, fPoint); fCurrentNode=fCache->GetNode(); fLevel=fCache->GetLevel(); fGlobalMatrix=fCache->GetCurrentMatrix();return fCurrentOverlapping;} - void PopDummy(Int_t ipop=9999) {fCache->PopDummy(ipop);} - - ClassDef(TGeoNavigator, 0) // geometry navigator class + Int_t PushPath(Int_t startlevel = 0) { return fCache->PushState(fCurrentOverlapping, startlevel, fNmany); } + Bool_t PopPath() + { + fCurrentOverlapping = fCache->PopState(fNmany); + fCurrentNode = fCache->GetNode(); + fLevel = fCache->GetLevel(); + fGlobalMatrix = fCache->GetCurrentMatrix(); + return fCurrentOverlapping; + } + Bool_t PopPath(Int_t index) + { + fCurrentOverlapping = fCache->PopState(fNmany, index); + fCurrentNode = fCache->GetNode(); + fLevel = fCache->GetLevel(); + fGlobalMatrix = fCache->GetCurrentMatrix(); + return fCurrentOverlapping; + } + Int_t PushPoint(Int_t startlevel = 0) { return fCache->PushState(fCurrentOverlapping, startlevel, fNmany, fPoint); } + Bool_t PopPoint() + { + fCurrentOverlapping = fCache->PopState(fNmany, fPoint); + fCurrentNode = fCache->GetNode(); + fLevel = fCache->GetLevel(); + fGlobalMatrix = fCache->GetCurrentMatrix(); + return fCurrentOverlapping; + } + Bool_t PopPoint(Int_t index) + { + fCurrentOverlapping = fCache->PopState(fNmany, index, fPoint); + fCurrentNode = fCache->GetNode(); + fLevel = fCache->GetLevel(); + fGlobalMatrix = fCache->GetCurrentMatrix(); + return fCurrentOverlapping; + } + void PopDummy(Int_t ipop = 9999) { fCache->PopDummy(ipop); } + + ClassDefOverride(TGeoNavigator, 0) // geometry navigator class }; #include "TObjArray.h" @@ -213,25 +259,23 @@ public : // // //////////////////////////////////////////////////////////////////////////// -class TGeoNavigatorArray : public TObjArray -{ +class TGeoNavigatorArray : public TObjArray { private: - TGeoNavigator *fCurrentNavigator; // Current navigator - TGeoManager *fGeoManager; // Manager to which it applies + TGeoNavigator *fCurrentNavigator; // Current navigator + TGeoManager *fGeoManager; // Manager to which it applies - TGeoNavigatorArray(const TGeoNavigatorArray&) = delete; - TGeoNavigatorArray& operator=(const TGeoNavigatorArray&) = delete; + TGeoNavigatorArray(const TGeoNavigatorArray &) = delete; + TGeoNavigatorArray &operator=(const TGeoNavigatorArray &) = delete; public: TGeoNavigatorArray() : TObjArray(), fCurrentNavigator(nullptr), fGeoManager(nullptr) {} - TGeoNavigatorArray(TGeoManager *mgr) : TObjArray(), fCurrentNavigator(nullptr), fGeoManager(mgr) {SetOwner();} - virtual ~TGeoNavigatorArray() {} + TGeoNavigatorArray(TGeoManager *mgr) : TObjArray(), fCurrentNavigator(nullptr), fGeoManager(mgr) { SetOwner(); } + ~TGeoNavigatorArray() override {} - TGeoNavigator *AddNavigator(); - inline TGeoNavigator *GetCurrentNavigator() const {return fCurrentNavigator;} - TGeoNavigator *SetCurrentNavigator(Int_t inav) {return (fCurrentNavigator=(TGeoNavigator*)At(inav));} + TGeoNavigator *AddNavigator(); + inline TGeoNavigator *GetCurrentNavigator() const { return fCurrentNavigator; } + TGeoNavigator *SetCurrentNavigator(Int_t inav) { return (fCurrentNavigator = (TGeoNavigator *)At(inav)); } - ClassDef(TGeoNavigatorArray, 0) // An array of navigators + ClassDefOverride(TGeoNavigatorArray, 0) // An array of navigators }; #endif - diff --git a/geom/geom/inc/TGeoNode.h b/geom/geom/inc/TGeoNode.h index 92374fa91d7ce..cdf92f1ec3342 100644 --- a/geom/geom/inc/TGeoNode.h +++ b/geom/geom/inc/TGeoNode.h @@ -36,29 +36,27 @@ class TGeoExtension; // // //////////////////////////////////////////////////////////////////////////// -class TGeoNode : public TNamed, - public TGeoAtt -{ +class TGeoNode : public TNamed, public TGeoAtt { protected: - TGeoVolume *fVolume = nullptr; // volume associated with this - TGeoVolume *fMother = nullptr; // mother volume - Int_t fNumber = 0; // copy number - Int_t fNovlp = 0; // number of overlaps - Int_t *fOverlaps = nullptr; //[fNovlp] list of indices for overlapping brothers - TGeoExtension *fUserExtension = nullptr; //! Transient user-defined extension to volumes - TGeoExtension *fFWExtension = nullptr; //! Transient framework-defined extension to volumes + TGeoVolume *fVolume = nullptr; // volume associated with this + TGeoVolume *fMother = nullptr; // mother volume + Int_t fNumber = 0; // copy number + Int_t fNovlp = 0; // number of overlaps + Int_t *fOverlaps = nullptr; //[fNovlp] list of indices for overlapping brothers + TGeoExtension *fUserExtension = nullptr; //! Transient user-defined extension to volumes + TGeoExtension *fFWExtension = nullptr; //! Transient framework-defined extension to volumes - void CopyOverlaps(Int_t *ovlp, Int_t novlp); + void CopyOverlaps(Int_t *ovlp, Int_t novlp); private: - TGeoNode(const TGeoNode&) = delete; - TGeoNode& operator=(const TGeoNode&) = delete; + TGeoNode(const TGeoNode &) = delete; + TGeoNode &operator=(const TGeoNode &) = delete; public: enum { kGeoNodeMatrix = BIT(14), kGeoNodeOffset = BIT(15), - kGeoNodeVC = BIT(16), + kGeoNodeVC = BIT(16), kGeoNodeOverlap = BIT(17), kGeoNodeCloned = BIT(18) }; @@ -67,80 +65,84 @@ class TGeoNode : public TNamed, TGeoNode(); TGeoNode(const TGeoVolume *vol); // destructor - virtual ~TGeoNode(); - - void Browse(TBrowser *b); - virtual void cd() const {} - void CheckOverlaps(Double_t ovlp=0.1, Option_t *option=""); // *MENU* - void CheckShapes(); - Int_t CountDaughters(Bool_t unique_volumes=kFALSE); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - void Draw(Option_t *option=""); - void DrawOnly(Option_t *option=""); - void DrawOverlaps(); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - void FillIdArray(Int_t &ifree, Int_t &nodeid, Int_t *array) const; - Int_t FindNode(const TGeoNode *node, Int_t level); - virtual Int_t GetByteCount() const {return 44;} - TGeoNode *GetDaughter(Int_t ind) const {return fVolume->GetNode(ind);} + ~TGeoNode() override; + + void Browse(TBrowser *b) override; + virtual void cd() const {} + void CheckOverlaps(Double_t ovlp = 0.1, Option_t *option = ""); // *MENU* + void CheckShapes(); + Int_t CountDaughters(Bool_t unique_volumes = kFALSE); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *option = "") override; + void DrawOnly(Option_t *option = ""); + void DrawOverlaps(); + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + void FillIdArray(Int_t &ifree, Int_t &nodeid, Int_t *array) const; + Int_t FindNode(const TGeoNode *node, Int_t level); + virtual Int_t GetByteCount() const { return 44; } + TGeoNode *GetDaughter(Int_t ind) const { return fVolume->GetNode(ind); } virtual TGeoMatrix *GetMatrix() const = 0; - Int_t GetColour() const {return fVolume->GetLineColor();} - virtual Int_t GetIndex() const {return 0;} - virtual TGeoPatternFinder *GetFinder() const {return nullptr;} - TGeoMedium *GetMedium() const {return fVolume->GetMedium();} - TGeoVolume *GetMotherVolume() const {return fMother;} - Int_t GetNdaughters() const {return fVolume->GetNdaughters();} - TObjArray *GetNodes() const {return fVolume->GetNodes();} - Int_t GetNumber() const {return fNumber;} - Int_t *GetOverlaps(Int_t &novlp) const {novlp=fNovlp; return fOverlaps;} - TGeoVolume *GetVolume() const {return fVolume;} - virtual char *GetObjectInfo(Int_t px, Int_t py) const; - virtual Int_t GetOptimalVoxels() const {return 0;} - void InspectNode() const; // *MENU* - Bool_t IsCloned() const {return TObject::TestBit(kGeoNodeCloned);} - virtual Bool_t IsFolder() const {return (GetNdaughters()?kTRUE:kFALSE);} - Bool_t IsOffset() const {return TObject::TestBit(kGeoNodeOffset);} - Bool_t IsOnScreen() const; // *MENU* - Bool_t IsOverlapping() const {return TObject::TestBit(kGeoNodeOverlap);} - Bool_t IsVirtual() const {return TObject::TestBit(kGeoNodeVC);} - Bool_t IsVisible() const {return (TGeoAtt::IsVisible() && fVolume->IsVisible());} - Bool_t IsVisDaughters() const {return (TGeoAtt::IsVisDaughters() && fVolume->IsVisDaughters());} - Bool_t MayOverlap(Int_t iother) const; - - virtual TGeoNode *MakeCopyNode() const {return nullptr;} - Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - void SaveAttributes(std::ostream &out); - void SetCurrentPoint(Double_t x, Double_t y, Double_t z) {fVolume->SetCurrentPoint(x,y,z);}// *MENU* - void SetVolume(TGeoVolume *volume) {fVolume = volume;} - void SetNumber(Int_t number) {fNumber=number;} - void SetCloned(Bool_t flag=kTRUE) {TObject::SetBit(kGeoNodeCloned, flag);} - void SetOverlapping(Bool_t flag=kTRUE) {TObject::SetBit(kGeoNodeOverlap, flag);} - void SetVirtual() {TObject::SetBit(kGeoNodeVC, kTRUE);} - void SetVisibility(Bool_t vis=kTRUE); // *MENU* - void SetInvisible() {SetVisibility(kFALSE);} // *MENU* - void SetAllInvisible() {VisibleDaughters(kFALSE);} // *MENU* - void SetMotherVolume(TGeoVolume *mother) {fMother = mother;} - void SetOverlaps(Int_t *ovlp, Int_t novlp); - void SetUserExtension(TGeoExtension *ext); - void SetFWExtension(TGeoExtension *ext); - TGeoExtension *GetUserExtension() const {return fUserExtension;} - TGeoExtension *GetFWExtension() const {return fFWExtension;} - TGeoExtension *GrabUserExtension() const; - TGeoExtension *GrabFWExtension() const; - - virtual void MasterToLocal(const Double_t *master, Double_t *local) const; - virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const; - virtual void LocalToMaster(const Double_t *local, Double_t *master) const; - virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const; - - virtual void ls(Option_t *option = "") const; - virtual void Paint(Option_t *option = ""); - void PrintCandidates() const; // *MENU* - void PrintOverlaps() const; // *MENU* - void VisibleDaughters(Bool_t vis=kTRUE); // *MENU* - - ClassDef(TGeoNode, 2) // base class for all geometry nodes + Int_t GetColour() const { return fVolume->GetLineColor(); } + virtual Int_t GetIndex() const { return 0; } + virtual TGeoPatternFinder *GetFinder() const { return nullptr; } + TGeoMedium *GetMedium() const { return fVolume->GetMedium(); } + TGeoVolume *GetMotherVolume() const { return fMother; } + Int_t GetNdaughters() const { return fVolume->GetNdaughters(); } + TObjArray *GetNodes() const { return fVolume->GetNodes(); } + Int_t GetNumber() const { return fNumber; } + Int_t *GetOverlaps(Int_t &novlp) const + { + novlp = fNovlp; + return fOverlaps; + } + TGeoVolume *GetVolume() const { return fVolume; } + char *GetObjectInfo(Int_t px, Int_t py) const override; + virtual Int_t GetOptimalVoxels() const { return 0; } + void InspectNode() const; // *MENU* + Bool_t IsCloned() const { return TObject::TestBit(kGeoNodeCloned); } + Bool_t IsFolder() const override { return (GetNdaughters() ? kTRUE : kFALSE); } + Bool_t IsOffset() const { return TObject::TestBit(kGeoNodeOffset); } + Bool_t IsOnScreen() const; // *MENU* + Bool_t IsOverlapping() const { return TObject::TestBit(kGeoNodeOverlap); } + Bool_t IsVirtual() const { return TObject::TestBit(kGeoNodeVC); } + Bool_t IsVisible() const { return (TGeoAtt::IsVisible() && fVolume->IsVisible()); } + Bool_t IsVisDaughters() const { return (TGeoAtt::IsVisDaughters() && fVolume->IsVisDaughters()); } + Bool_t MayOverlap(Int_t iother) const; + + virtual TGeoNode *MakeCopyNode() const { return nullptr; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const; + void SaveAttributes(std::ostream &out); + void SetCurrentPoint(Double_t x, Double_t y, Double_t z) { fVolume->SetCurrentPoint(x, y, z); } // *MENU* + void SetVolume(TGeoVolume *volume) { fVolume = volume; } + void SetNumber(Int_t number) { fNumber = number; } + void SetCloned(Bool_t flag = kTRUE) { TObject::SetBit(kGeoNodeCloned, flag); } + void SetOverlapping(Bool_t flag = kTRUE) { TObject::SetBit(kGeoNodeOverlap, flag); } + void SetVirtual() { TObject::SetBit(kGeoNodeVC, kTRUE); } + void SetVisibility(Bool_t vis = kTRUE) override; // *MENU* + void SetInvisible() { SetVisibility(kFALSE); } // *MENU* + void SetAllInvisible() { VisibleDaughters(kFALSE); } // *MENU* + void SetMotherVolume(TGeoVolume *mother) { fMother = mother; } + void SetOverlaps(Int_t *ovlp, Int_t novlp); + void SetUserExtension(TGeoExtension *ext); + void SetFWExtension(TGeoExtension *ext); + TGeoExtension *GetUserExtension() const { return fUserExtension; } + TGeoExtension *GetFWExtension() const { return fFWExtension; } + TGeoExtension *GrabUserExtension() const; + TGeoExtension *GrabFWExtension() const; + + virtual void MasterToLocal(const Double_t *master, Double_t *local) const; + virtual void MasterToLocalVect(const Double_t *master, Double_t *local) const; + virtual void LocalToMaster(const Double_t *local, Double_t *master) const; + virtual void LocalToMasterVect(const Double_t *local, Double_t *master) const; + + void ls(Option_t *option = "") const override; + void Paint(Option_t *option = "") override; + void PrintCandidates() const; // *MENU* + void PrintOverlaps() const; // *MENU* + void VisibleDaughters(Bool_t vis = kTRUE); // *MENU* + + ClassDefOverride(TGeoNode, 2) // base class for all geometry nodes }; //////////////////////////////////////////////////////////////////////////// @@ -149,29 +151,28 @@ class TGeoNode : public TNamed, // // //////////////////////////////////////////////////////////////////////////// -class TGeoNodeMatrix : public TGeoNode -{ +class TGeoNodeMatrix : public TGeoNode { private: - TGeoMatrix *fMatrix = nullptr; // transf. matrix of fNode in fMother system + TGeoMatrix *fMatrix = nullptr; // transf. matrix of fNode in fMother system - TGeoNodeMatrix(const TGeoNodeMatrix& gnm) = delete; - TGeoNodeMatrix& operator=(const TGeoNodeMatrix& gnm) = delete; + TGeoNodeMatrix(const TGeoNodeMatrix &gnm) = delete; + TGeoNodeMatrix &operator=(const TGeoNodeMatrix &gnm) = delete; public: // constructors TGeoNodeMatrix(); TGeoNodeMatrix(const TGeoVolume *vol, const TGeoMatrix *matrix); // destructor - virtual ~TGeoNodeMatrix(); + ~TGeoNodeMatrix() override; - virtual Int_t GetByteCount() const; - virtual Int_t GetOptimalVoxels() const; - virtual Bool_t IsFolder() const {return kTRUE;} - virtual TGeoMatrix *GetMatrix() const {return fMatrix;} - virtual TGeoNode *MakeCopyNode() const; - void SetMatrix(const TGeoMatrix *matrix); + Int_t GetByteCount() const override; + Int_t GetOptimalVoxels() const override; + Bool_t IsFolder() const override { return kTRUE; } + TGeoMatrix *GetMatrix() const override { return fMatrix; } + TGeoNode *MakeCopyNode() const override; + void SetMatrix(const TGeoMatrix *matrix); - ClassDef(TGeoNodeMatrix, 1) // a geometry node in the general case + ClassDefOverride(TGeoNodeMatrix, 1) // a geometry node in the general case }; //////////////////////////////////////////////////////////////////////////// @@ -180,32 +181,35 @@ class TGeoNodeMatrix : public TGeoNode // // //////////////////////////////////////////////////////////////////////////// -class TGeoNodeOffset : public TGeoNode -{ +class TGeoNodeOffset : public TGeoNode { private: - Double_t fOffset = 0.; // X offset for this node with respect to its mother - Int_t fIndex = 0; // index of this node in the division + Double_t fOffset = 0.; // X offset for this node with respect to its mother + Int_t fIndex = 0; // index of this node in the division TGeoPatternFinder *fFinder = nullptr; // finder for this node - TGeoNodeOffset(const TGeoNodeOffset&) = delete; - TGeoNodeOffset& operator=(const TGeoNodeOffset&) = delete; + TGeoNodeOffset(const TGeoNodeOffset &) = delete; + TGeoNodeOffset &operator=(const TGeoNodeOffset &) = delete; public: // constructors TGeoNodeOffset(); TGeoNodeOffset(const TGeoVolume *vol, Int_t index, Double_t offset); // destructor - virtual ~TGeoNodeOffset(); - - virtual void cd() const {fFinder->cd(fIndex);} - Double_t GetOffset() const {return fOffset;} - virtual Int_t GetIndex() const; - virtual TGeoPatternFinder *GetFinder() const {return fFinder;} - virtual TGeoMatrix *GetMatrix() const {cd(); return fFinder->GetMatrix();} - virtual TGeoNode *MakeCopyNode() const; - void SetFinder(TGeoPatternFinder *finder) {fFinder = finder;} - - ClassDef(TGeoNodeOffset, 1) // a geometry node with just an offset + ~TGeoNodeOffset() override; + + void cd() const override { fFinder->cd(fIndex); } + Double_t GetOffset() const { return fOffset; } + Int_t GetIndex() const override; + TGeoPatternFinder *GetFinder() const override { return fFinder; } + TGeoMatrix *GetMatrix() const override + { + cd(); + return fFinder->GetMatrix(); + } + TGeoNode *MakeCopyNode() const override; + void SetFinder(TGeoPatternFinder *finder) { fFinder = finder; } + + ClassDefOverride(TGeoNodeOffset, 1) // a geometry node with just an offset }; //////////////////////////////////////////////////////////////////////////// @@ -217,22 +221,22 @@ class TGeoNodeOffset : public TGeoNode class TGeoIterator; -class TGeoIteratorPlugin : public TObject -{ +class TGeoIteratorPlugin : public TObject { protected: const TGeoIterator *fIterator = nullptr; // Caller iterator private: // No copy TGeoIteratorPlugin(const TGeoIteratorPlugin &); TGeoIteratorPlugin &operator=(const TGeoIteratorPlugin &); + public: - TGeoIteratorPlugin() : TObject(),fIterator(nullptr) {} - virtual ~TGeoIteratorPlugin() {} + TGeoIteratorPlugin() : TObject(), fIterator(nullptr) {} + ~TGeoIteratorPlugin() override {} - virtual void ProcessNode() = 0; - void SetIterator(const TGeoIterator *iter) {fIterator = iter;} + virtual void ProcessNode() = 0; + void SetIterator(const TGeoIterator *iter) { fIterator = iter; } - ClassDef(TGeoIteratorPlugin, 0) // ABC for user plugins connecter to a geometry iterator. + ClassDefOverride(TGeoIteratorPlugin, 0) // ABC for user plugins connecter to a geometry iterator. }; //////////////////////////////////////////////////////////////////////////// @@ -241,54 +245,67 @@ class TGeoIteratorPlugin : public TObject // // //////////////////////////////////////////////////////////////////////////// -class TGeoIterator -{ +class TGeoIterator { private: - TGeoVolume *fTop = nullptr; // Top volume of the iterated branch - Bool_t fMustResume = kFALSE; // Private flag to resume from current node. - Bool_t fMustStop = kFALSE; // Private flag to signal that the iterator has finished. - Int_t fLevel = 0; // Current level in the tree - Int_t fType = 0; // Type of iteration - Int_t *fArray = nullptr; // Array of node indices for the current path - TGeoHMatrix *fMatrix = nullptr; // Current global matrix - TString fTopName; // User name for top - TGeoIteratorPlugin - *fPlugin = nullptr; // User iterator plugin - Bool_t fPluginAutoexec = kFALSE; // Plugin automatically executed during next() - - void IncreaseArray(); + TGeoVolume *fTop = nullptr; // Top volume of the iterated branch + Bool_t fMustResume = kFALSE; // Private flag to resume from current node. + Bool_t fMustStop = kFALSE; // Private flag to signal that the iterator has finished. + Int_t fLevel = 0; // Current level in the tree + Int_t fType = 0; // Type of iteration + Int_t *fArray = nullptr; // Array of node indices for the current path + TGeoHMatrix *fMatrix = nullptr; // Current global matrix + TString fTopName; // User name for top + TGeoIteratorPlugin *fPlugin = nullptr; // User iterator plugin + Bool_t fPluginAutoexec = kFALSE; // Plugin automatically executed during next() + + void IncreaseArray(); + protected: - TGeoIterator() : fTop(nullptr), fMustResume(kFALSE), fMustStop(kFALSE), fLevel(0), fType(0), - fArray(nullptr), fMatrix(nullptr), fTopName(), fPlugin(nullptr), fPluginAutoexec(kFALSE) { } + TGeoIterator() + : fTop(nullptr), + fMustResume(kFALSE), + fMustStop(kFALSE), + fLevel(0), + fType(0), + fArray(nullptr), + fMatrix(nullptr), + fTopName(), + fPlugin(nullptr), + fPluginAutoexec(kFALSE) + { + } public: TGeoIterator(TGeoVolume *top); TGeoIterator(const TGeoIterator &iter); - virtual ~TGeoIterator(); + virtual ~TGeoIterator(); - TGeoIterator &operator=(const TGeoIterator &iter); - TGeoNode *operator()(); - TGeoNode *Next(); - void Up() { if (fLevel > 0) fLevel--; } + TGeoIterator &operator=(const TGeoIterator &iter); + TGeoNode *operator()(); + TGeoNode *Next(); + void Up() + { + if (fLevel > 0) + fLevel--; + } const TGeoMatrix *GetCurrentMatrix() const; - Int_t GetIndex(Int_t i) const {return ((i<=fLevel)?fArray[i]:-1);} - Int_t GetLevel() const {return fLevel;} - TGeoNode *GetNode(Int_t level) const; - void GetPath(TString &path) const; - TGeoIteratorPlugin - *GetUserPlugin() const {return fPlugin;} - - TGeoVolume *GetTopVolume() const {return fTop;} - Int_t GetType() const {return fType;} - void Reset(TGeoVolume *top=nullptr); - void SetUserPlugin(TGeoIteratorPlugin *plugin); - void SetPluginAutoexec(Bool_t mode) {fPluginAutoexec = mode;} - void SetType(Int_t type) {fType = type;} - void SetTopName(const char* name); - void Skip(); - - ClassDef(TGeoIterator,0) //Iterator for geometry. + Int_t GetIndex(Int_t i) const { return ((i <= fLevel) ? fArray[i] : -1); } + Int_t GetLevel() const { return fLevel; } + TGeoNode *GetNode(Int_t level) const; + void GetPath(TString &path) const; + TGeoIteratorPlugin *GetUserPlugin() const { return fPlugin; } + + TGeoVolume *GetTopVolume() const { return fTop; } + Int_t GetType() const { return fType; } + void Reset(TGeoVolume *top = nullptr); + void SetUserPlugin(TGeoIteratorPlugin *plugin); + void SetPluginAutoexec(Bool_t mode) { fPluginAutoexec = mode; } + void SetType(Int_t type) { fType = type; } + void SetTopName(const char *name); + void Skip(); + + ClassDef(TGeoIterator, 0) // Iterator for geometry. }; #endif diff --git a/geom/geom/inc/TGeoOpticalSurface.h b/geom/geom/inc/TGeoOpticalSurface.h index 5d68cd195ca4c..823c06a68c4d1 100644 --- a/geom/geom/inc/TGeoOpticalSurface.h +++ b/geom/geom/inc/TGeoOpticalSurface.h @@ -115,15 +115,15 @@ class TGeoOpticalSurface : public TNamed { TGeoOpticalSurface(const char *name, ESurfaceModel model = kMglisur, ESurfaceFinish finish = kFpolished, ESurfaceType type = kTdielectric_dielectric, Double_t value = 1.0); - virtual ~TGeoOpticalSurface() {} + ~TGeoOpticalSurface() override {} // Accessors bool AddProperty(const char *property, const char *ref); const char *GetPropertyRef(const char *property); TList const &GetProperties() const { return fProperties; } Int_t GetNproperties() const { return fProperties.GetSize(); } - TGDMLMatrix* GetProperty(const char* name) const; - TGDMLMatrix* GetProperty(Int_t i) const; + TGDMLMatrix *GetProperty(const char *name) const; + TGDMLMatrix *GetProperty(Int_t i) const; ESurfaceType GetType() const { return fType; } ESurfaceModel GetModel() const { return fModel; } ESurfaceFinish GetFinish() const { return fFinish; } @@ -138,7 +138,7 @@ class TGeoOpticalSurface : public TNamed { void SetValue(Double_t value) { fValue = value; } void SetSigmaAlpha(Double_t sigmaalpha) { fSigmaAlpha = sigmaalpha; } - void Print(Option_t *option = "") const; + void Print(Option_t *option = "") const override; static ESurfaceType StringToType(const char *type); static const char *TypeToString(ESurfaceType type); @@ -147,7 +147,7 @@ class TGeoOpticalSurface : public TNamed { static ESurfaceFinish StringToFinish(const char *finish); static const char *FinishToString(ESurfaceFinish finish); - ClassDef(TGeoOpticalSurface, 1) // Class representing an optical surface + ClassDefOverride(TGeoOpticalSurface, 1) // Class representing an optical surface }; //////////////////////////////////////////////////////////////////////////// @@ -169,14 +169,14 @@ class TGeoSkinSurface : public TNamed { : TNamed(name, ref), fSurface(surf), fVolume(vol) { } - virtual ~TGeoSkinSurface() {} + ~TGeoSkinSurface() override {} TGeoOpticalSurface const *GetSurface() const { return fSurface; } TGeoVolume const *GetVolume() const { return fVolume; } - void Print(Option_t *option = "") const; + void Print(Option_t *option = "") const override; - ClassDef(TGeoSkinSurface, 1) // A surface with optical properties surrounding a volume + ClassDefOverride(TGeoSkinSurface, 1) // A surface with optical properties surrounding a volume }; //////////////////////////////////////////////////////////////////////////// @@ -200,15 +200,15 @@ class TGeoBorderSurface : public TNamed { : TNamed(name, ref), fSurface(surf), fNode1(node1), fNode2(node2) { } - virtual ~TGeoBorderSurface() {} + ~TGeoBorderSurface() override {} TGeoOpticalSurface const *GetSurface() const { return fSurface; } TGeoNode const *GetNode1() const { return fNode1; } TGeoNode const *GetNode2() const { return fNode2; } - void Print(Option_t *option = "") const; + void Print(Option_t *option = "") const override; - ClassDef(TGeoBorderSurface, 1) // A surface with optical properties betwqeen 2 touching volumes + ClassDefOverride(TGeoBorderSurface, 1) // A surface with optical properties betwqeen 2 touching volumes }; #endif // ROOT_TGeoOpticalSurface diff --git a/geom/geom/inc/TGeoPara.h b/geom/geom/inc/TGeoPara.h index 59ff3dace9e42..417ccaa91c9bc 100644 --- a/geom/geom/inc/TGeoPara.h +++ b/geom/geom/inc/TGeoPara.h @@ -14,23 +14,22 @@ #include "TGeoBBox.h" -class TGeoPara : public TGeoBBox -{ -protected : -// data members - Double_t fX; // X half-length - Double_t fY; // Y half-length - Double_t fZ; // Z half-length - Double_t fAlpha; // angle w.r.t Y from the center of low Y to the high Y - Double_t fTheta; // polar angle of segment between low and hi Z surfaces - Double_t fPhi; // azimuthal angle of segment between low and hi Z surfaces - Double_t fTxy; // tangent of XY section angle - Double_t fTxz; // tangent of XZ section angle - Double_t fTyz; // tangent of XZ section angle +class TGeoPara : public TGeoBBox { +protected: + // data members + Double_t fX; // X half-length + Double_t fY; // Y half-length + Double_t fZ; // Z half-length + Double_t fAlpha; // angle w.r.t Y from the center of low Y to the high Y + Double_t fTheta; // polar angle of segment between low and hi Z surfaces + Double_t fPhi; // azimuthal angle of segment between low and hi Z surfaces + Double_t fTxy; // tangent of XY section angle + Double_t fTxz; // tangent of XZ section angle + Double_t fTyz; // tangent of XZ section angle // methods - TGeoPara(const TGeoPara&) = delete; - TGeoPara& operator=(const TGeoPara&) = delete; + TGeoPara(const TGeoPara &) = delete; + TGeoPara &operator=(const TGeoPara &) = delete; public: // constructors @@ -39,48 +38,51 @@ protected : TGeoPara(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t alpha, Double_t theta, Double_t phi); TGeoPara(Double_t *param); // destructor - virtual ~TGeoPara(); + ~TGeoPara() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual Int_t GetByteCount() const {return 48;} - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual Int_t GetNmeshVertices() const {return 8;} - Double_t GetX() const {return fX;} - Double_t GetY() const {return fY;} - Double_t GetZ() const {return fZ;} - Double_t GetAlpha() const {return fAlpha;} - Double_t GetTheta() const {return fTheta;} - Double_t GetPhi() const {return fPhi;} - Double_t GetTxy() const {return fTxy;} - Double_t GetTxz() const {return fTxz;} - Double_t GetTyz() const {return fTyz;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + Int_t GetByteCount() const override { return 48; } + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + Int_t GetNmeshVertices() const override { return 8; } + Double_t GetX() const { return fX; } + Double_t GetY() const { return fY; } + Double_t GetZ() const { return fZ; } + Double_t GetAlpha() const { return fAlpha; } + Double_t GetTheta() const { return fTheta; } + Double_t GetPhi() const { return fPhi; } + Double_t GetTxy() const { return fTxy; } + Double_t GetTxz() const { return fTxz; } + Double_t GetTyz() const { return fTyz; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void Sizeof3D() const override; - ClassDef(TGeoPara, 1) // box primitive + ClassDefOverride(TGeoPara, 1) // box primitive }; #endif diff --git a/geom/geom/inc/TGeoParaboloid.h b/geom/geom/inc/TGeoParaboloid.h index 78335db47e34f..e740ecff1e75c 100644 --- a/geom/geom/inc/TGeoParaboloid.h +++ b/geom/geom/inc/TGeoParaboloid.h @@ -14,17 +14,16 @@ #include "TGeoBBox.h" -class TGeoParaboloid : public TGeoBBox -{ +class TGeoParaboloid : public TGeoBBox { private: - Double_t fRlo; // radius at z=-dz - Double_t fRhi; // radius at z=+dz - Double_t fDz; // range on Z axis [-dz, dz] - Double_t fA; // quadratic coeff. - Double_t fB; // Z value of parabola at x=y=0 + Double_t fRlo; // radius at z=-dz + Double_t fRhi; // radius at z=+dz + Double_t fDz; // range on Z axis [-dz, dz] + Double_t fA; // quadratic coeff. + Double_t fB; // Z value of parabola at x=y=0 - TGeoParaboloid(const TGeoParaboloid&) = delete; - TGeoParaboloid& operator=(const TGeoParaboloid&) = delete; + TGeoParaboloid(const TGeoParaboloid &) = delete; + TGeoParaboloid &operator=(const TGeoParaboloid &) = delete; public: // constructors @@ -33,50 +32,50 @@ class TGeoParaboloid : public TGeoBBox TGeoParaboloid(const char *name, Double_t rlo, Double_t rhi, Double_t dz); TGeoParaboloid(Double_t *params); // destructor - virtual ~TGeoParaboloid(); + ~TGeoParaboloid() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - Double_t DistToParaboloid(const Double_t *point, const Double_t *dir, Bool_t in) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - Double_t GetRlo() const {return fRlo;} - Double_t GetRhi() const {return fRhi;} - Double_t GetDz() const {return fDz;} + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistToParaboloid(const Double_t *point, const Double_t *dir, Bool_t in) const; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Double_t GetRlo() const { return fRlo; } + Double_t GetRhi() const { return fRhi; } + Double_t GetDz() const { return fDz; } - virtual void GetBoundingCylinder(Double_t *param) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetParaboloidDimensions(Double_t rlo, Double_t rhi, Double_t dz); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoParaboloid, 1) // paraboloid class + void GetBoundingCylinder(Double_t *param) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetParaboloidDimensions(Double_t rlo, Double_t rhi, Double_t dz); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; + ClassDefOverride(TGeoParaboloid, 1) // paraboloid class }; - #endif diff --git a/geom/geom/inc/TGeoParallelWorld.h b/geom/geom/inc/TGeoParallelWorld.h index f71ca00e29236..dcab5604f581f 100644 --- a/geom/geom/inc/TGeoParallelWorld.h +++ b/geom/geom/inc/TGeoParallelWorld.h @@ -18,60 +18,68 @@ class TGeoManager; class TGeoPhysicalNode; class TGeoVolume; -class TGeoParallelWorld : public TNamed -{ -protected : - TGeoManager *fGeoManager; // base geometry - TObjArray *fPaths; // array of paths - Bool_t fUseOverlaps; // Activated if user defined overlapping candidates - Bool_t fIsClosed; //! Closed flag - TGeoVolume *fVolume; //! helper volume - TGeoPhysicalNode *fLastState; //! Last PN touched - TObjArray *fPhysical; //! array of physical nodes +class TGeoParallelWorld : public TNamed { +protected: + TGeoManager *fGeoManager; // base geometry + TObjArray *fPaths; // array of paths + Bool_t fUseOverlaps; // Activated if user defined overlapping candidates + Bool_t fIsClosed; //! Closed flag + TGeoVolume *fVolume; //! helper volume + TGeoPhysicalNode *fLastState; //! Last PN touched + TObjArray *fPhysical; //! array of physical nodes - TGeoParallelWorld(const TGeoParallelWorld&) = delete; - TGeoParallelWorld& operator=(const TGeoParallelWorld&) = delete; + TGeoParallelWorld(const TGeoParallelWorld &) = delete; + TGeoParallelWorld &operator=(const TGeoParallelWorld &) = delete; public: // constructors - TGeoParallelWorld() : TNamed(),fGeoManager(nullptr),fPaths(nullptr),fUseOverlaps(kFALSE),fIsClosed(kFALSE),fVolume(nullptr),fLastState(nullptr),fPhysical(nullptr) {} + TGeoParallelWorld() + : TNamed(), + fGeoManager(nullptr), + fPaths(nullptr), + fUseOverlaps(kFALSE), + fIsClosed(kFALSE), + fVolume(nullptr), + fLastState(nullptr), + fPhysical(nullptr) + { + } TGeoParallelWorld(const char *name, TGeoManager *mgr); // destructor - virtual ~TGeoParallelWorld(); + ~TGeoParallelWorld() override; // API for adding components nodes - void AddNode(const char *path); + void AddNode(const char *path); // Activate/deactivate overlap usage - void SetUseOverlaps(Bool_t flag) {fUseOverlaps = flag;} - Bool_t IsUsingOverlaps() const {return fUseOverlaps;} - void ResetOverlaps() const; + void SetUseOverlaps(Bool_t flag) { fUseOverlaps = flag; } + Bool_t IsUsingOverlaps() const { return fUseOverlaps; } + void ResetOverlaps() const; // Adding overlap candidates can highly improve performance. - void AddOverlap(TGeoVolume *vol, Bool_t activate=kTRUE); - void AddOverlap(const char *volname, Bool_t activate=kTRUE); + void AddOverlap(TGeoVolume *vol, Bool_t activate = kTRUE); + void AddOverlap(const char *volname, Bool_t activate = kTRUE); // The normal PW mode (without declaring overlaps) does detect them - Int_t PrintDetectedOverlaps() const; + Int_t PrintDetectedOverlaps() const; // Closing a parallel geometry is mandatory - Bool_t CloseGeometry(); + Bool_t CloseGeometry(); // Refresh structures in case of re-alignment - void RefreshPhysicalNodes(); + void RefreshPhysicalNodes(); // Navigation interface TGeoPhysicalNode *FindNode(Double_t point[3]); - TGeoPhysicalNode *FindNextBoundary(Double_t point[3], Double_t dir[3], Double_t &step, Double_t stepmax=1.E30); - Double_t Safety(Double_t point[3], Double_t safmax=1.E30); + TGeoPhysicalNode *FindNextBoundary(Double_t point[3], Double_t dir[3], Double_t &step, Double_t stepmax = 1.E30); + Double_t Safety(Double_t point[3], Double_t safmax = 1.E30); // Getters - TGeoManager *GetGeometry() const {return fGeoManager;} - Bool_t IsClosed() const {return fIsClosed;} - TGeoVolume *GetVolume() const {return fVolume;} + TGeoManager *GetGeometry() const { return fGeoManager; } + Bool_t IsClosed() const { return fIsClosed; } + TGeoVolume *GetVolume() const { return fVolume; } // Utilities - void CheckOverlaps(Double_t ovlp=0.001); // default 10 microns - void Draw(Option_t *option); + void CheckOverlaps(Double_t ovlp = 0.001); // default 10 microns + void Draw(Option_t *option) override; - ClassDef(TGeoParallelWorld, 3) // parallel world base class + ClassDefOverride(TGeoParallelWorld, 3) // parallel world base class }; #endif - diff --git a/geom/geom/inc/TGeoPatternFinder.h b/geom/geom/inc/TGeoPatternFinder.h index df785619d6b5e..da9d01b44b95d 100644 --- a/geom/geom/inc/TGeoPatternFinder.h +++ b/geom/geom/inc/TGeoPatternFinder.h @@ -28,82 +28,77 @@ class TGeoMatrix; // // ///////////////////////////////////////////////////////////////////////////////// -class TGeoPatternFinder : public TObject -{ +class TGeoPatternFinder : public TObject { public: - struct ThreadData_t - { - TGeoMatrix *fMatrix; //! generic matrix - Int_t fCurrent; //! current division element - Int_t fNextIndex; //! index of next node + struct ThreadData_t { + TGeoMatrix *fMatrix; //! generic matrix + Int_t fCurrent; //! current division element + Int_t fNextIndex; //! index of next node ThreadData_t(); ~ThreadData_t(); + private: - ThreadData_t(const ThreadData_t&) = delete; - ThreadData_t& operator=(const ThreadData_t&) = delete; + ThreadData_t(const ThreadData_t &) = delete; + ThreadData_t &operator=(const ThreadData_t &) = delete; }; - ThreadData_t& GetThreadData() const; - void ClearThreadData() const; - void CreateThreadData(Int_t nthreads); - -protected : - enum EGeoPatternFlags { - kPatternReflected = BIT(14), - kPatternSpacedOut = BIT(15) - }; - Double_t fStep; // division step length - Double_t fStart; // starting point on divided axis - Double_t fEnd; // ending point - Int_t fNdivisions; // number of divisions - Int_t fDivIndex; // index of first div. node - TGeoVolume *fVolume; // volume to which applies + ThreadData_t &GetThreadData() const; + void ClearThreadData() const; + void CreateThreadData(Int_t nthreads); - mutable std::vector fThreadData; //! Vector of thread private transient data - mutable Int_t fThreadSize; //! Size of the thread vector - mutable std::mutex fMutex; //! Mutex for thread data +protected: + enum EGeoPatternFlags { kPatternReflected = BIT(14), kPatternSpacedOut = BIT(15) }; + Double_t fStep; // division step length + Double_t fStart; // starting point on divided axis + Double_t fEnd; // ending point + Int_t fNdivisions; // number of divisions + Int_t fDivIndex; // index of first div. node + TGeoVolume *fVolume; // volume to which applies + + mutable std::vector fThreadData; //! Vector of thread private transient data + mutable Int_t fThreadSize; //! Size of the thread vector + mutable std::mutex fMutex; //! Mutex for thread data protected: - TGeoPatternFinder(const TGeoPatternFinder&); - TGeoPatternFinder& operator=(const TGeoPatternFinder&); + TGeoPatternFinder(const TGeoPatternFinder &); + TGeoPatternFinder &operator=(const TGeoPatternFinder &); public: // constructors TGeoPatternFinder(); TGeoPatternFinder(TGeoVolume *vol, Int_t ndiv); // destructor - virtual ~TGeoPatternFinder(); + ~TGeoPatternFinder() override; // methods - virtual TGeoMatrix* CreateMatrix() const = 0; - virtual void cd(Int_t /*idiv*/) {} - virtual TGeoNode *CdNext(); - virtual TGeoNode *FindNode(Double_t * /*point*/, const Double_t * /*dir*/=nullptr) {return nullptr;} - virtual Int_t GetByteCount() const {return 36;} - Int_t GetCurrent();// {return fCurrent;} - Int_t GetDivIndex() {return fDivIndex;} - virtual Int_t GetDivAxis() {return 1;} - virtual TGeoMatrix *GetMatrix();// {return fMatrix;} - Int_t GetNdiv() const {return fNdivisions;} - Int_t GetNext() const;// {return fNextIndex;} - TGeoNode *GetNodeOffset(Int_t idiv) {return fVolume->GetNode(fDivIndex+idiv);} - Double_t GetStart() const {return fStart;} - Double_t GetStep() const {return fStep;} - Double_t GetEnd() const {return fEnd;} - TGeoVolume *GetVolume() const {return fVolume;} - virtual Bool_t IsOnBoundary(const Double_t * /*point*/) const {return kFALSE;} - Bool_t IsReflected() const {return TObject::TestBit(kPatternReflected);} - Bool_t IsSpacedOut() const {return TObject::TestBit(kPatternSpacedOut);} - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE) = 0; - void Reflect(Bool_t flag=kTRUE) {TObject::SetBit(kPatternReflected,flag);} - void SetDivIndex(Int_t index) {fDivIndex = index;} - void SetNext(Int_t index);// {fNextIndex = index;} - void SetRange(Double_t start, Double_t step, Int_t ndivisions); - void SetSpacedOut(Bool_t flag) {TObject::SetBit(kPatternSpacedOut,flag);} - void SetVolume(TGeoVolume *vol) {fVolume = vol;} - virtual void UpdateMatrix(Int_t , TGeoHMatrix &) const {} - - ClassDef(TGeoPatternFinder, 4) // patterns to divide volumes + virtual TGeoMatrix *CreateMatrix() const = 0; + virtual void cd(Int_t /*idiv*/) {} + virtual TGeoNode *CdNext(); + virtual TGeoNode *FindNode(Double_t * /*point*/, const Double_t * /*dir*/ = nullptr) { return nullptr; } + virtual Int_t GetByteCount() const { return 36; } + Int_t GetCurrent(); // {return fCurrent;} + Int_t GetDivIndex() { return fDivIndex; } + virtual Int_t GetDivAxis() { return 1; } + virtual TGeoMatrix *GetMatrix(); // {return fMatrix;} + Int_t GetNdiv() const { return fNdivisions; } + Int_t GetNext() const; // {return fNextIndex;} + TGeoNode *GetNodeOffset(Int_t idiv) { return fVolume->GetNode(fDivIndex + idiv); } + Double_t GetStart() const { return fStart; } + Double_t GetStep() const { return fStep; } + Double_t GetEnd() const { return fEnd; } + TGeoVolume *GetVolume() const { return fVolume; } + virtual Bool_t IsOnBoundary(const Double_t * /*point*/) const { return kFALSE; } + Bool_t IsReflected() const { return TObject::TestBit(kPatternReflected); } + Bool_t IsSpacedOut() const { return TObject::TestBit(kPatternSpacedOut); } + virtual TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) = 0; + void Reflect(Bool_t flag = kTRUE) { TObject::SetBit(kPatternReflected, flag); } + void SetDivIndex(Int_t index) { fDivIndex = index; } + void SetNext(Int_t index); // {fNextIndex = index;} + void SetRange(Double_t start, Double_t step, Int_t ndivisions); + void SetSpacedOut(Bool_t flag) { TObject::SetBit(kPatternSpacedOut, flag); } + void SetVolume(TGeoVolume *vol) { fVolume = vol; } + virtual void UpdateMatrix(Int_t, TGeoHMatrix &) const {} + + ClassDefOverride(TGeoPatternFinder, 4) // patterns to divide volumes }; //////////////////////////////////////////////////////////////////////////// @@ -114,8 +109,7 @@ protected : class TGeoTranslation; -class TGeoPatternX : public TGeoPatternFinder -{ +class TGeoPatternX : public TGeoPatternFinder { public: // constructors TGeoPatternX(); @@ -123,23 +117,23 @@ class TGeoPatternX : public TGeoPatternFinder TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternX(const TGeoPatternX &pf); - TGeoPatternX& operator=(const TGeoPatternX&); + TGeoPatternX &operator=(const TGeoPatternX &); // destructor - virtual ~TGeoPatternX(); + ~TGeoPatternX() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); - virtual Int_t GetDivAxis() {return 1;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternX, 1) // X division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); + Int_t GetDivAxis() override { return 1; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternX, 1) // X division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -148,8 +142,7 @@ class TGeoPatternX : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternY : public TGeoPatternFinder -{ +class TGeoPatternY : public TGeoPatternFinder { public: // constructors TGeoPatternY(); @@ -157,22 +150,22 @@ class TGeoPatternY : public TGeoPatternFinder TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternY(const TGeoPatternY &pf); - TGeoPatternY& operator=(const TGeoPatternY&); + TGeoPatternY &operator=(const TGeoPatternY &); // destructor - virtual ~TGeoPatternY(); + ~TGeoPatternY() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); - virtual Int_t GetDivAxis() {return 2;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternY, 1) // Y division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); + Int_t GetDivAxis() override { return 2; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternY, 1) // Y division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -181,8 +174,7 @@ class TGeoPatternY : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternZ : public TGeoPatternFinder -{ +class TGeoPatternZ : public TGeoPatternFinder { public: // constructors TGeoPatternZ(); @@ -190,22 +182,22 @@ class TGeoPatternZ : public TGeoPatternFinder TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternZ(const TGeoPatternZ &pf); - TGeoPatternZ& operator=(const TGeoPatternZ&); + TGeoPatternZ &operator=(const TGeoPatternZ &); // destructor - virtual ~TGeoPatternZ(); + ~TGeoPatternZ() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); - virtual Int_t GetDivAxis() {return 3;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternZ, 1) // Z division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + virtual Double_t FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext); + Int_t GetDivAxis() override { return 3; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternZ, 1) // Z division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -214,8 +206,7 @@ class TGeoPatternZ : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternParaX : public TGeoPatternFinder -{ +class TGeoPatternParaX : public TGeoPatternFinder { public: // constructors TGeoPatternParaX(); @@ -223,22 +214,22 @@ class TGeoPatternParaX : public TGeoPatternFinder TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternParaX(const TGeoPatternParaX &pf); - TGeoPatternParaX& operator=(const TGeoPatternParaX&); + TGeoPatternParaX &operator=(const TGeoPatternParaX &); // destructor - virtual ~TGeoPatternParaX(); + ~TGeoPatternParaX() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 1;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternParaX, 1) // Para X division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 1; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternParaX, 1) // Para X division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -247,11 +238,10 @@ class TGeoPatternParaX : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternParaY : public TGeoPatternFinder -{ -private : -// data members - Double_t fTxy = 0.; // tangent of alpha +class TGeoPatternParaY : public TGeoPatternFinder { +private: + // data members + Double_t fTxy = 0.; // tangent of alpha public: // constructors TGeoPatternParaY(); @@ -259,22 +249,22 @@ private : TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternParaY(const TGeoPatternParaY &pf); - TGeoPatternParaY& operator=(const TGeoPatternParaY&); + TGeoPatternParaY &operator=(const TGeoPatternParaY &); // destructor - virtual ~TGeoPatternParaY(); + ~TGeoPatternParaY() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 2;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternParaY, 1) // Para Y division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 2; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternParaY, 1) // Para Y division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -283,12 +273,11 @@ private : // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternParaZ : public TGeoPatternFinder -{ -private : -// data members - Double_t fTxz = 0.; // tangent of alpha xz - Double_t fTyz = 0.; // tangent of alpha yz +class TGeoPatternParaZ : public TGeoPatternFinder { +private: + // data members + Double_t fTxz = 0.; // tangent of alpha xz + Double_t fTyz = 0.; // tangent of alpha yz public: // constructors TGeoPatternParaZ(); @@ -296,22 +285,22 @@ private : TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternParaZ(const TGeoPatternParaZ &pf); - TGeoPatternParaZ& operator=(const TGeoPatternParaZ&); + TGeoPatternParaZ &operator=(const TGeoPatternParaZ &); // destructor - virtual ~TGeoPatternParaZ(); + ~TGeoPatternParaZ() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 3;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternParaZ, 1) // Para Z division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 3; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternParaZ, 1) // Para Z division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -320,12 +309,11 @@ private : // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternTrapZ : public TGeoPatternFinder -{ -private : -// data members - Double_t fTxz = 0.; // tangent of alpha xz - Double_t fTyz = 0.; // tangent of alpha yz +class TGeoPatternTrapZ : public TGeoPatternFinder { +private: + // data members + Double_t fTxz = 0.; // tangent of alpha xz + Double_t fTyz = 0.; // tangent of alpha yz public: // constructors TGeoPatternTrapZ(); @@ -333,35 +321,33 @@ private : TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternTrapZ(const TGeoPatternTrapZ &pf); - TGeoPatternTrapZ& operator=(const TGeoPatternTrapZ&); + TGeoPatternTrapZ &operator=(const TGeoPatternTrapZ &); // destructor - virtual ~TGeoPatternTrapZ(); + ~TGeoPatternTrapZ() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - Double_t GetTxz() const {return fTxz;} - Double_t GetTyz() const {return fTyz;} - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 3;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternTrapZ, 1) // Trap od Gtra Z division pattern + TGeoMatrix *CreateMatrix() const override; + Double_t GetTxz() const { return fTxz; } + Double_t GetTyz() const { return fTyz; } + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 3; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternTrapZ, 1) // Trap od Gtra Z division pattern }; - //////////////////////////////////////////////////////////////////////////// // // // TGeoPatternCylR - a cylindrical R divison pattern // // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternCylR : public TGeoPatternFinder -{ +class TGeoPatternCylR : public TGeoPatternFinder { public: // constructors TGeoPatternCylR(); @@ -369,21 +355,21 @@ class TGeoPatternCylR : public TGeoPatternFinder TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternCylR(const TGeoPatternCylR &pf); - TGeoPatternCylR& operator=(const TGeoPatternCylR&); + TGeoPatternCylR &operator=(const TGeoPatternCylR &); // destructor - virtual ~TGeoPatternCylR(); + ~TGeoPatternCylR() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 1;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternCylR, 1) // Cylindrical R division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 1; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternCylR, 1) // Cylindrical R division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -392,18 +378,25 @@ class TGeoPatternCylR : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternCylPhi : public TGeoPatternFinder -{ -private : -// data members - Double_t *fSinCos = nullptr; //![2*fNdivisions] table of sines/cosines +class TGeoPatternCylPhi : public TGeoPatternFinder { +private: + // data members + Double_t *fSinCos = nullptr; //![2*fNdivisions] table of sines/cosines protected: - TGeoPatternCylPhi(const TGeoPatternCylPhi& pfc) - : TGeoPatternFinder(pfc), fSinCos(pfc.fSinCos) {CreateThreadData(1);} - TGeoPatternCylPhi& operator=(const TGeoPatternCylPhi& pfc) - {if(this!=&pfc) {TGeoPatternFinder::operator=(pfc); fSinCos=pfc.fSinCos; CreateThreadData(1);} - return *this;} + TGeoPatternCylPhi(const TGeoPatternCylPhi &pfc) : TGeoPatternFinder(pfc), fSinCos(pfc.fSinCos) + { + CreateThreadData(1); + } + TGeoPatternCylPhi &operator=(const TGeoPatternCylPhi &pfc) + { + if (this != &pfc) { + TGeoPatternFinder::operator=(pfc); + fSinCos = pfc.fSinCos; + CreateThreadData(1); + } + return *this; + } public: // constructors @@ -412,19 +405,19 @@ private : TGeoPatternCylPhi(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternCylPhi(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); // destructor - virtual ~TGeoPatternCylPhi(); + ~TGeoPatternCylPhi() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 2;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternCylPhi, 1) // Cylindrical phi division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 2; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternCylPhi, 1) // Cylindrical phi division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -433,8 +426,7 @@ private : // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternSphR : public TGeoPatternFinder -{ +class TGeoPatternSphR : public TGeoPatternFinder { public: // constructors TGeoPatternSphR(); @@ -442,20 +434,20 @@ class TGeoPatternSphR : public TGeoPatternFinder TGeoPatternSphR(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternSphR(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternSphR(const TGeoPatternSphR &pf); - TGeoPatternSphR& operator=(const TGeoPatternSphR&); + TGeoPatternSphR &operator=(const TGeoPatternSphR &); // destructor - virtual ~TGeoPatternSphR(); + ~TGeoPatternSphR() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 1;} - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternSphR, 1) // spherical R division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 1; } + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternSphR, 1) // spherical R division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -464,8 +456,7 @@ class TGeoPatternSphR : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternSphTheta : public TGeoPatternFinder -{ +class TGeoPatternSphTheta : public TGeoPatternFinder { public: // constructors TGeoPatternSphTheta(); @@ -473,20 +464,20 @@ class TGeoPatternSphTheta : public TGeoPatternFinder TGeoPatternSphTheta(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternSphTheta(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); TGeoPatternSphTheta(const TGeoPatternSphTheta &pf); - TGeoPatternSphTheta& operator=(const TGeoPatternSphTheta&); + TGeoPatternSphTheta &operator=(const TGeoPatternSphTheta &); // destructor - virtual ~TGeoPatternSphTheta(); + ~TGeoPatternSphTheta() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 3;} - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternSphTheta, 1) // spherical theta division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 3; } + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternSphTheta, 1) // spherical theta division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -495,15 +486,15 @@ class TGeoPatternSphTheta : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternSphPhi : public TGeoPatternFinder -{ +class TGeoPatternSphPhi : public TGeoPatternFinder { private: - Double_t *fSinCos = nullptr; //! Sincos table + Double_t *fSinCos = nullptr; //! Sincos table protected: - TGeoPatternSphPhi(const TGeoPatternSphPhi& pfc) = delete; - TGeoPatternSphPhi& operator=(const TGeoPatternSphPhi& pfc) = delete; - Double_t *CreateSinCos(); + TGeoPatternSphPhi(const TGeoPatternSphPhi &pfc) = delete; + TGeoPatternSphPhi &operator=(const TGeoPatternSphPhi &pfc) = delete; + Double_t *CreateSinCos(); + public: // constructors TGeoPatternSphPhi(); @@ -511,19 +502,19 @@ class TGeoPatternSphPhi : public TGeoPatternFinder TGeoPatternSphPhi(TGeoVolume *vol, Int_t ndivisions, Double_t step); TGeoPatternSphPhi(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end); // destructor - virtual ~TGeoPatternSphPhi(); + ~TGeoPatternSphPhi() override; // methods - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual Int_t GetDivAxis() {return 2;} - virtual Bool_t IsOnBoundary(const Double_t *point) const; - virtual - TGeoPatternFinder *MakeCopy(Bool_t reflect=kFALSE); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; - - ClassDef(TGeoPatternSphPhi, 1) // Spherical phi division pattern + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + Int_t GetDivAxis() override { return 2; } + Bool_t IsOnBoundary(const Double_t *point) const override; + + TGeoPatternFinder *MakeCopy(Bool_t reflect = kFALSE) override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; + + ClassDefOverride(TGeoPatternSphPhi, 1) // Spherical phi division pattern }; //////////////////////////////////////////////////////////////////////////// @@ -532,33 +523,32 @@ class TGeoPatternSphPhi : public TGeoPatternFinder // // //////////////////////////////////////////////////////////////////////////// -class TGeoPatternHoneycomb : public TGeoPatternFinder -{ -private : -// data members - Int_t fNrows; // number of rows - Int_t fAxisOnRows; // axis along each row - Int_t *fNdivisions; // [fNrows] number of divisions for each row - Double_t *fStart; // [fNrows] starting points for each row +class TGeoPatternHoneycomb : public TGeoPatternFinder { +private: + // data members + Int_t fNrows; // number of rows + Int_t fAxisOnRows; // axis along each row + Int_t *fNdivisions; // [fNrows] number of divisions for each row + Double_t *fStart; // [fNrows] starting points for each row protected: - TGeoPatternHoneycomb(const TGeoPatternHoneycomb&); - TGeoPatternHoneycomb& operator=(const TGeoPatternHoneycomb&); + TGeoPatternHoneycomb(const TGeoPatternHoneycomb &); + TGeoPatternHoneycomb &operator=(const TGeoPatternHoneycomb &); public: // constructors TGeoPatternHoneycomb(); TGeoPatternHoneycomb(TGeoVolume *vol, Int_t nrows); // destructor - virtual ~TGeoPatternHoneycomb(); + ~TGeoPatternHoneycomb() override; // methods - TGeoPatternFinder *MakeCopy(Bool_t) {return nullptr;} - virtual TGeoMatrix* CreateMatrix() const; - virtual void cd(Int_t idiv); - virtual TGeoNode *FindNode(Double_t *point, const Double_t *dir=nullptr); - virtual void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const; + TGeoPatternFinder *MakeCopy(Bool_t) override { return nullptr; } + TGeoMatrix *CreateMatrix() const override; + void cd(Int_t idiv) override; + TGeoNode *FindNode(Double_t *point, const Double_t *dir = nullptr) override; + void UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const override; - ClassDef(TGeoPatternHoneycomb, 1) // pattern for honeycomb divisions + ClassDefOverride(TGeoPatternHoneycomb, 1) // pattern for honeycomb divisions }; #endif diff --git a/geom/geom/inc/TGeoPcon.h b/geom/geom/inc/TGeoPcon.h index a097b791d87d5..93125f7c9ae64 100644 --- a/geom/geom/inc/TGeoPcon.h +++ b/geom/geom/inc/TGeoPcon.h @@ -14,31 +14,30 @@ #include "TGeoBBox.h" -class TGeoPcon : public TGeoBBox -{ +class TGeoPcon : public TGeoBBox { protected: // data members - Int_t fNz = 0; // number of z planes (at least two) - Double_t fPhi1 = 0; // lower phi limit (converted to [0,2*pi) - Double_t fDphi = 0; // phi range - Double_t *fRmin = nullptr; //[fNz] pointer to array of inner radii - Double_t *fRmax = nullptr; //[fNz] pointer to array of outer radii - Double_t *fZ = nullptr; //[fNz] pointer to array of Z planes positions - Bool_t fFullPhi = false; //! Full phi range flag - Double_t fC1 = 0; //! Cosine of phi1 - Double_t fS1 = 0; //! Sine of phi1 - Double_t fC2 = 0; //! Cosine of phi1+dphi - Double_t fS2 = 0; //! Sine of phi1+dphi - Double_t fCm = 0; //! Cosine of (phi1+phi2)/2 - Double_t fSm = 0; //! Sine of (phi1+phi2)/2 - Double_t fCdphi = 0; //! Cosine of dphi + Int_t fNz = 0; // number of z planes (at least two) + Double_t fPhi1 = 0; // lower phi limit (converted to [0,2*pi) + Double_t fDphi = 0; // phi range + Double_t *fRmin = nullptr; //[fNz] pointer to array of inner radii + Double_t *fRmax = nullptr; //[fNz] pointer to array of outer radii + Double_t *fZ = nullptr; //[fNz] pointer to array of Z planes positions + Bool_t fFullPhi = false; //! Full phi range flag + Double_t fC1 = 0; //! Cosine of phi1 + Double_t fS1 = 0; //! Sine of phi1 + Double_t fC2 = 0; //! Cosine of phi1+dphi + Double_t fS2 = 0; //! Sine of phi1+dphi + Double_t fCm = 0; //! Cosine of (phi1+phi2)/2 + Double_t fSm = 0; //! Sine of (phi1+phi2)/2 + Double_t fCdphi = 0; //! Cosine of dphi // methods - TGeoPcon(const TGeoPcon&) = delete; - TGeoPcon& operator=(const TGeoPcon&) = delete; + TGeoPcon(const TGeoPcon &) = delete; + TGeoPcon &operator=(const TGeoPcon &) = delete; - Bool_t HasInsideSurface() const; - void SetSegsAndPolsNoInside(TBuffer3D &buff) const; + Bool_t HasInsideSurface() const; + void SetSegsAndPolsNoInside(TBuffer3D &buff) const; public: // constructors @@ -48,63 +47,66 @@ class TGeoPcon : public TGeoBBox TGeoPcon(const char *name, Double_t phi, Double_t dphi, Int_t nz); TGeoPcon(Double_t *params); // destructor - virtual ~TGeoPcon(); + ~TGeoPcon() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual void DefineSection(Int_t snum, Double_t z, Double_t rmin, Double_t rmax); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - Double_t DistToSegZ(const Double_t *point, const Double_t *dir, Int_t &iz) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 60+12*fNz;} - Double_t GetPhi1() const {return fPhi1;} - Double_t GetDphi() const {return fDphi;} - Int_t GetNz() const {return fNz;} - virtual Int_t GetNsegments() const; - Double_t *GetRmin() const {return fRmin;} - Double_t GetRmin(Int_t ipl) const; - Double_t *GetRmax() const {return fRmax;} - Double_t GetRmax(Int_t ipl) const; - Double_t *GetZ() const {return fZ;} - Double_t GetZ(Int_t ipl) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - Double_t &Phi1() {return fPhi1;} - Double_t &Dphi() {return fDphi;} - Double_t &Rmin(Int_t ipl) {return fRmin[ipl];} - Double_t &Rmax(Int_t ipl) {return fRmax[ipl];} - Double_t &Z(Int_t ipl) {return fZ[ipl];} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - Double_t SafetyToSegment(const Double_t *point, Int_t ipl, Bool_t in=kTRUE, Double_t safmin=TGeoShape::Big()) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + virtual void DefineSection(Int_t snum, Double_t z, Double_t rmin, Double_t rmax); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistToSegZ(const Double_t *point, const Double_t *dir, Int_t &iz) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 60 + 12 * fNz; } + Double_t GetPhi1() const { return fPhi1; } + Double_t GetDphi() const { return fDphi; } + Int_t GetNz() const { return fNz; } + virtual Int_t GetNsegments() const; + Double_t *GetRmin() const { return fRmin; } + Double_t GetRmin(Int_t ipl) const; + Double_t *GetRmax() const { return fRmax; } + Double_t GetRmax(Int_t ipl) const; + Double_t *GetZ() const { return fZ; } + Double_t GetZ(Int_t ipl) const; + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t &Phi1() { return fPhi1; } + Double_t &Dphi() { return fDphi; } + Double_t &Rmin(Int_t ipl) { return fRmin[ipl]; } + Double_t &Rmax(Int_t ipl) { return fRmax[ipl]; } + Double_t &Z(Int_t ipl) { return fZ[ipl]; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + Double_t + SafetyToSegment(const Double_t *point, Int_t ipl, Bool_t in = kTRUE, Double_t safmin = TGeoShape::Big()) const; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; - ClassDef(TGeoPcon, 1) // polycone class + ClassDefOverride(TGeoPcon, 1) // polycone class }; #endif diff --git a/geom/geom/inc/TGeoPgon.h b/geom/geom/inc/TGeoPgon.h index 9f68f8cc65d62..cece6926f8591 100644 --- a/geom/geom/inc/TGeoPgon.h +++ b/geom/geom/inc/TGeoPgon.h @@ -17,42 +17,47 @@ #include #include -class TGeoPgon : public TGeoPcon -{ +class TGeoPgon : public TGeoPcon { public: - struct ThreadData_t - { - Int_t *fIntBuffer; //![fNedges+4] temporary int buffer array - Double_t *fDblBuffer; //![fNedges+4] temporary double buffer array + struct ThreadData_t { + Int_t *fIntBuffer; //![fNedges+4] temporary int buffer array + Double_t *fDblBuffer; //![fNedges+4] temporary double buffer array ThreadData_t(); ~ThreadData_t(); }; - ThreadData_t& GetThreadData() const; - void ClearThreadData() const; - void CreateThreadData(Int_t nthreads); + ThreadData_t &GetThreadData() const; + void ClearThreadData() const override; + void CreateThreadData(Int_t nthreads) override; protected: // data members - Int_t fNedges; // number of edges (at least one) - mutable std::vector fThreadData; //! Navigation data per thread - mutable Int_t fThreadSize; //! Size for the navigation data array - mutable std::mutex fMutex; //! Mutex for thread data + Int_t fNedges; // number of edges (at least one) + mutable std::vector fThreadData; //! Navigation data per thread + mutable Int_t fThreadSize; //! Size for the navigation data array + mutable std::mutex fMutex; //! Mutex for thread data // internal utility methods - Int_t GetPhiCrossList(const Double_t *point, const Double_t *dir, Int_t istart, Double_t *sphi, Int_t *iphi, Double_t stepmax=TGeoShape::Big()) const; - Bool_t IsCrossingSlice(const Double_t *point, const Double_t *dir, Int_t iphi, Double_t sstart, Int_t &ipl, Double_t &snext, Double_t stepmax) const; - void LocatePhi(const Double_t *point, Int_t &ipsec) const; - Double_t Rpg(Double_t z, Int_t ipl, Bool_t inner, Double_t &a, Double_t &b) const; - Double_t Rproj(Double_t z,const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, Double_t &a, Double_t &b) const; - Bool_t SliceCrossing(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, Double_t &snext, Double_t stepmax) const; - Bool_t SliceCrossingIn(const Double_t *point, const Double_t *dir, Int_t ipl, Int_t nphi, Int_t *iphi, Double_t *sphi, Double_t &snext, Double_t stepmax) const; - Bool_t SliceCrossingZ(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, Double_t &snext, Double_t stepmax) const; - Bool_t SliceCrossingInZ(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, Double_t &snext, Double_t stepmax) const; - void SetSegsAndPolsNoInside(TBuffer3D &buff) const; + Int_t GetPhiCrossList(const Double_t *point, const Double_t *dir, Int_t istart, Double_t *sphi, Int_t *iphi, + Double_t stepmax = TGeoShape::Big()) const; + Bool_t IsCrossingSlice(const Double_t *point, const Double_t *dir, Int_t iphi, Double_t sstart, Int_t &ipl, + Double_t &snext, Double_t stepmax) const; + void LocatePhi(const Double_t *point, Int_t &ipsec) const; + Double_t Rpg(Double_t z, Int_t ipl, Bool_t inner, Double_t &a, Double_t &b) const; + Double_t Rproj(Double_t z, const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, Double_t &a, + Double_t &b) const; + Bool_t SliceCrossing(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, + Double_t &snext, Double_t stepmax) const; + Bool_t SliceCrossingIn(const Double_t *point, const Double_t *dir, Int_t ipl, Int_t nphi, Int_t *iphi, + Double_t *sphi, Double_t &snext, Double_t stepmax) const; + Bool_t SliceCrossingZ(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, + Double_t &snext, Double_t stepmax) const; + Bool_t SliceCrossingInZ(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *sphi, + Double_t &snext, Double_t stepmax) const; + void SetSegsAndPolsNoInside(TBuffer3D &buff) const; - TGeoPgon(const TGeoPgon&) = delete; - TGeoPgon& operator=(const TGeoPgon&) = delete; + TGeoPgon(const TGeoPgon &) = delete; + TGeoPgon &operator=(const TGeoPgon &) = delete; public: // constructors @@ -61,46 +66,56 @@ class TGeoPgon : public TGeoPcon TGeoPgon(const char *name, Double_t phi, Double_t dphi, Int_t nedges, Int_t nz); TGeoPgon(Double_t *params); // destructor - virtual ~TGeoPgon(); + ~TGeoPgon() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 64+12*fNz;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - Int_t GetNedges() const {return fNedges;} - virtual Int_t GetNmeshVertices() const; - virtual Int_t GetNsegments() const {return fNedges;} - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const {return TGeoBBox::GetPointsOnSegments(npoints,array);} - virtual void InspectShape() const; - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - Double_t SafetyToSegment(const Double_t *point, Int_t ipl, Int_t iphi, Bool_t in, Double_t safphi, Double_t safmin=TGeoShape::Big()) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - void SetNedges(Int_t ne) {if (ne>2) fNedges=ne;} - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 64 + 12 * fNz; } + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNedges() const { return fNedges; } + Int_t GetNmeshVertices() const override; + Int_t GetNsegments() const override { return fNedges; } + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override + { + return TGeoBBox::GetPointsOnSegments(npoints, array); + } + void InspectShape() const override; + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + Double_t SafetyToSegment(const Double_t *point, Int_t ipl, Int_t iphi, Bool_t in, Double_t safphi, + Double_t safmin = TGeoShape::Big()) const; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetNedges(Int_t ne) + { + if (ne > 2) + fNedges = ne; + } + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; - ClassDef(TGeoPgon, 1) // polygone class + ClassDefOverride(TGeoPgon, 1) // polygone class }; #endif diff --git a/geom/geom/inc/TGeoPhysicalNode.h b/geom/geom/inc/TGeoPhysicalNode.h index e212eeb28e0e5..42bd0a42806cc 100644 --- a/geom/geom/inc/TGeoPhysicalNode.h +++ b/geom/geom/inc/TGeoPhysicalNode.h @@ -32,65 +32,62 @@ class TObjArray; // // ////////////////////////////////////////////////////////////////////////////// -class TGeoPhysicalNode : public TNamed, - public TAttLine -{ +class TGeoPhysicalNode : public TNamed, public TAttLine { protected: - Int_t fLevel; // depth in the geometry tree - TObjArray *fMatrices; // global transformation matrices - TObjArray *fNodes; // branch of nodes - TGeoHMatrix *fMatrixOrig; // original local matrix of the last node in the path + Int_t fLevel; // depth in the geometry tree + TObjArray *fMatrices; // global transformation matrices + TObjArray *fNodes; // branch of nodes + TGeoHMatrix *fMatrixOrig; // original local matrix of the last node in the path - TGeoPhysicalNode(const TGeoPhysicalNode&) = delete; - TGeoPhysicalNode& operator=(const TGeoPhysicalNode&) = delete; + TGeoPhysicalNode(const TGeoPhysicalNode &) = delete; + TGeoPhysicalNode &operator=(const TGeoPhysicalNode &) = delete; - void SetAligned(Bool_t flag=kTRUE) {TObject::SetBit(kGeoPNodeAligned,flag);} - Bool_t SetPath(const char *path); - void SetBranchAsState(); + void SetAligned(Bool_t flag = kTRUE) { TObject::SetBit(kGeoPNodeAligned, flag); } + Bool_t SetPath(const char *path); + void SetBranchAsState(); public: enum { - kGeoPNodeFull = BIT(10), // full branch is visible (default only last node) - kGeoPNodeVisible = BIT(11), // this node is visible (default) - kGeoPNodeVolAtt = BIT(12), // preserve volume attributes (default) - kGeoPNodeAligned = BIT(13) // alignment bit + kGeoPNodeFull = BIT(10), // full branch is visible (default only last node) + kGeoPNodeVisible = BIT(11), // this node is visible (default) + kGeoPNodeVolAtt = BIT(12), // preserve volume attributes (default) + kGeoPNodeAligned = BIT(13) // alignment bit }; // constructors TGeoPhysicalNode(); TGeoPhysicalNode(const char *path); // destructor - virtual ~TGeoPhysicalNode(); - - Bool_t Align(TGeoMatrix *newmat=nullptr, TGeoShape *newshape=nullptr, Bool_t check=kFALSE, Double_t ovlp=0.001); - void cd() const; - void Draw(Option_t *option=""); - Int_t GetLevel() const {return fLevel;} - TGeoHMatrix *GetMatrix(Int_t level=-1) const; - TGeoHMatrix *GetOriginalMatrix() const {return fMatrixOrig;} - TGeoNode *GetMother(Int_t levup=1) const; - TGeoNode *GetNode(Int_t level=-1) const; - TGeoShape *GetShape(Int_t level=-1) const; - TGeoVolume *GetVolume(Int_t level=-1) const; - - - Bool_t IsAligned() const {return TObject::TestBit(kGeoPNodeAligned);} - Bool_t IsMatchingState(TGeoNavigator *nav) const; - Bool_t IsVolAttributes() const {return TObject::TestBit(kGeoPNodeVolAtt);} - Bool_t IsVisible() const {return TObject::TestBit(kGeoPNodeVisible);} - Bool_t IsVisibleFull() const {return TObject::TestBit(kGeoPNodeFull);} - - virtual void Print(Option_t *option="") const; - void Refresh(); - - void SetMatrixOrig(const TGeoMatrix *local); - void SetIsVolAtt(Bool_t flag=kTRUE) {TObject::SetBit(kGeoPNodeVolAtt,flag);} - void SetVisibility(Bool_t flag=kTRUE) {TObject::SetBit(kGeoPNodeVisible,flag);} - void SetVisibleFull(Bool_t flag=kTRUE) {TObject::SetBit(kGeoPNodeFull,flag);} - virtual void Paint(Option_t *option = ""); - - - ClassDef(TGeoPhysicalNode, 1) // base class for physical nodes + ~TGeoPhysicalNode() override; + + Bool_t + Align(TGeoMatrix *newmat = nullptr, TGeoShape *newshape = nullptr, Bool_t check = kFALSE, Double_t ovlp = 0.001); + void cd() const; + void Draw(Option_t *option = "") override; + Int_t GetLevel() const { return fLevel; } + TGeoHMatrix *GetMatrix(Int_t level = -1) const; + TGeoHMatrix *GetOriginalMatrix() const { return fMatrixOrig; } + TGeoNode *GetMother(Int_t levup = 1) const; + TGeoNode *GetNode(Int_t level = -1) const; + TGeoShape *GetShape(Int_t level = -1) const; + TGeoVolume *GetVolume(Int_t level = -1) const; + + Bool_t IsAligned() const { return TObject::TestBit(kGeoPNodeAligned); } + Bool_t IsMatchingState(TGeoNavigator *nav) const; + Bool_t IsVolAttributes() const { return TObject::TestBit(kGeoPNodeVolAtt); } + Bool_t IsVisible() const { return TObject::TestBit(kGeoPNodeVisible); } + Bool_t IsVisibleFull() const { return TObject::TestBit(kGeoPNodeFull); } + + void Print(Option_t *option = "") const override; + void Refresh(); + + void SetMatrixOrig(const TGeoMatrix *local); + void SetIsVolAtt(Bool_t flag = kTRUE) { TObject::SetBit(kGeoPNodeVolAtt, flag); } + void SetVisibility(Bool_t flag = kTRUE) { TObject::SetBit(kGeoPNodeVisible, flag); } + void SetVisibleFull(Bool_t flag = kTRUE) { TObject::SetBit(kGeoPNodeFull, flag); } + void Paint(Option_t *option = "") override; + + ClassDefOverride(TGeoPhysicalNode, 1) // base class for physical nodes }; /////////////////////////////////////////////////////////////////////////////// @@ -100,38 +97,45 @@ class TGeoPhysicalNode : public TNamed, // // /////////////////////////////////////////////////////////////////////////////// -class TGeoPNEntry : public TNamed -{ +class TGeoPNEntry : public TNamed { private: - enum EPNEntryFlags { - kPNEntryOwnMatrix = BIT(14) - }; - TGeoPhysicalNode *fNode; // Physical node to which this applies - const TGeoHMatrix *fMatrix; // Additional matrix - TGeoHMatrix *fGlobalOrig; // Original global matrix for the linked physical node + enum EPNEntryFlags { kPNEntryOwnMatrix = BIT(14) }; + TGeoPhysicalNode *fNode; // Physical node to which this applies + const TGeoHMatrix *fMatrix; // Additional matrix + TGeoHMatrix *fGlobalOrig; // Original global matrix for the linked physical node protected: - TGeoPNEntry(const TGeoPNEntry& pne) - : TNamed(pne), fNode(pne.fNode), fMatrix(nullptr), fGlobalOrig(nullptr) { } - TGeoPNEntry& operator=(const TGeoPNEntry& pne) - {if(this!=&pne) {TNamed::operator=(pne); fNode=pne.fNode; fMatrix=pne.fMatrix;} - return *this;} + TGeoPNEntry(const TGeoPNEntry &pne) : TNamed(pne), fNode(pne.fNode), fMatrix(nullptr), fGlobalOrig(nullptr) {} + TGeoPNEntry &operator=(const TGeoPNEntry &pne) + { + if (this != &pne) { + TNamed::operator=(pne); + fNode = pne.fNode; + fMatrix = pne.fMatrix; + } + return *this; + } public: TGeoPNEntry(); TGeoPNEntry(const char *unique_name, const char *path); - virtual ~TGeoPNEntry(); - - inline const char *GetPath() const {return GetTitle();} - const TGeoHMatrix *GetMatrix() const {return fMatrix;} - TGeoHMatrix *GetMatrixOrig() const {if (fNode) return fNode->GetOriginalMatrix(); else return nullptr;}; - TGeoHMatrix *GetGlobalOrig() const {return fGlobalOrig;} - TGeoPhysicalNode *GetPhysicalNode() const {return fNode;} - void SetMatrix(const TGeoHMatrix *matrix); - void SetPhysicalNode(TGeoPhysicalNode *node); + ~TGeoPNEntry() override; + + inline const char *GetPath() const { return GetTitle(); } + const TGeoHMatrix *GetMatrix() const { return fMatrix; } + TGeoHMatrix *GetMatrixOrig() const + { + if (fNode) + return fNode->GetOriginalMatrix(); + else + return nullptr; + }; + TGeoHMatrix *GetGlobalOrig() const { return fGlobalOrig; } + TGeoPhysicalNode *GetPhysicalNode() const { return fNode; } + void SetMatrix(const TGeoHMatrix *matrix); + void SetPhysicalNode(TGeoPhysicalNode *node); - ClassDef(TGeoPNEntry, 4) // a physical node entry with unique name + ClassDefOverride(TGeoPNEntry, 4) // a physical node entry with unique name }; #endif - diff --git a/geom/geom/inc/TGeoPolygon.h b/geom/geom/inc/TGeoPolygon.h index 0e5867358884a..917ceaa190c9b 100644 --- a/geom/geom/inc/TGeoPolygon.h +++ b/geom/geom/inc/TGeoPolygon.h @@ -16,59 +16,55 @@ class TObjArray; -class TGeoPolygon : public TObject -{ +class TGeoPolygon : public TObject { public: - enum { - kGeoConvex = BIT(9), - kGeoFinishPolygon = BIT(10), - kGeoACW = BIT(11) - }; -protected : -// data members - Int_t fNvert{0}; // number of vertices (must be defined clockwise in XY plane) - Int_t fNconvex{0}; // number of points of the outscribed convex polygon - Int_t *fInd{nullptr}; //[fNvert] list of vertex indices - Int_t *fIndc{nullptr}; //[fNconvex] indices of vertices of the outscribed convex polygon - Double_t *fX{nullptr}; //! pointer to list of current X coordinates of vertices - Double_t *fY{nullptr}; //! pointer to list of current Y coordinates of vertices - TObjArray *fDaughters{nullptr}; // list of concave daughters + enum { kGeoConvex = BIT(9), kGeoFinishPolygon = BIT(10), kGeoACW = BIT(11) }; + +protected: + // data members + Int_t fNvert{0}; // number of vertices (must be defined clockwise in XY plane) + Int_t fNconvex{0}; // number of points of the outscribed convex polygon + Int_t *fInd{nullptr}; //[fNvert] list of vertex indices + Int_t *fIndc{nullptr}; //[fNconvex] indices of vertices of the outscribed convex polygon + Double_t *fX{nullptr}; //! pointer to list of current X coordinates of vertices + Double_t *fY{nullptr}; //! pointer to list of current Y coordinates of vertices + TObjArray *fDaughters{nullptr}; // list of concave daughters private: - void ConvexCheck(); // force convexity checking - Bool_t IsSegConvex(Int_t i1, Int_t i2=-1) const; - Bool_t IsRightSided(const Double_t *point, Int_t ind1, Int_t ind2) const; - void OutscribedConvex(); + void ConvexCheck(); // force convexity checking + Bool_t IsSegConvex(Int_t i1, Int_t i2 = -1) const; + Bool_t IsRightSided(const Double_t *point, Int_t ind1, Int_t ind2) const; + void OutscribedConvex(); + + TGeoPolygon(const TGeoPolygon &) = delete; + TGeoPolygon &operator=(const TGeoPolygon &) = delete; - TGeoPolygon(const TGeoPolygon&) = delete; - TGeoPolygon &operator=(const TGeoPolygon&) = delete; public: // constructors TGeoPolygon(); TGeoPolygon(Int_t nvert); // destructor - virtual ~TGeoPolygon(); + ~TGeoPolygon() override; // methods - Double_t Area() const; - Bool_t Contains(const Double_t *point) const; - virtual void Draw(Option_t *option=""); - void FinishPolygon(); - Int_t GetNvert() const {return fNvert;} - Int_t GetNconvex() const {return fNconvex;} - Double_t *GetX() {return fX;} - Double_t *GetY() {return fY;} - void GetVertices(Double_t *x, Double_t *y) const; - void GetConvexVertices(Double_t *x, Double_t *y) const; - Bool_t IsClockwise() const {return !TObject::TestBit(kGeoACW);} - Bool_t IsConvex() const {return TObject::TestBit(kGeoConvex);} - Bool_t IsFinished() const {return TObject::TestBit(kGeoFinishPolygon);} - Bool_t IsIllegalCheck() const; - Double_t Safety(const Double_t *point, Int_t &isegment) const; - void SetConvex(Bool_t flag=kTRUE) {TObject::SetBit(kGeoConvex,flag);} - void SetXY(Double_t *x, Double_t *y); - void SetNextIndex(Int_t index=-1); + Double_t Area() const; + Bool_t Contains(const Double_t *point) const; + void Draw(Option_t *option = "") override; + void FinishPolygon(); + Int_t GetNvert() const { return fNvert; } + Int_t GetNconvex() const { return fNconvex; } + Double_t *GetX() { return fX; } + Double_t *GetY() { return fY; } + void GetVertices(Double_t *x, Double_t *y) const; + void GetConvexVertices(Double_t *x, Double_t *y) const; + Bool_t IsClockwise() const { return !TObject::TestBit(kGeoACW); } + Bool_t IsConvex() const { return TObject::TestBit(kGeoConvex); } + Bool_t IsFinished() const { return TObject::TestBit(kGeoFinishPolygon); } + Bool_t IsIllegalCheck() const; + Double_t Safety(const Double_t *point, Int_t &isegment) const; + void SetConvex(Bool_t flag = kTRUE) { TObject::SetBit(kGeoConvex, flag); } + void SetXY(Double_t *x, Double_t *y); + void SetNextIndex(Int_t index = -1); - ClassDef(TGeoPolygon, 2) // class for handling arbitrary polygons + ClassDefOverride(TGeoPolygon, 2) // class for handling arbitrary polygons }; #endif - diff --git a/geom/geom/inc/TGeoRCPtr.h b/geom/geom/inc/TGeoRCPtr.h index c25622466bef7..5ff7f9d56ea32 100644 --- a/geom/geom/inc/TGeoRCPtr.h +++ b/geom/geom/inc/TGeoRCPtr.h @@ -31,7 +31,7 @@ class MyExtension : public TGeoExtension { void print() const {printf("MyExtension object %p\n", this);} private: mutable Int_t fRC; // Reference counter - ClassDef(MyExtension,1) + ClassDefOverride(MyExtension,1) }; ~~~ @@ -61,61 +61,57 @@ Event if one forgets to call ptr2 = 0, the object gets delete when the method using ptr2 gets out of scope. */ -template -class TGeoRCPtr -{ +template +class TGeoRCPtr { public: - //Construct using a C pointer, e.g. TGeoRCPtr x = new T(); - TGeoRCPtr(T* ptr = nullptr) - : fPtr(ptr) + // Construct using a C pointer, e.g. TGeoRCPtr x = new T(); + TGeoRCPtr(T *ptr = nullptr) : fPtr(ptr) { - if(ptr) ptr->Grab(); + if (ptr) + ptr->Grab(); } - //Copy constructor - TGeoRCPtr(const TGeoRCPtr &ptr) - : fPtr(ptr.fPtr) + // Copy constructor + TGeoRCPtr(const TGeoRCPtr &ptr) : fPtr(ptr.fPtr) { - if(fPtr) fPtr->Grab(); + if (fPtr) + fPtr->Grab(); } ~TGeoRCPtr() { - if(fPtr) fPtr->Release(); + if (fPtr) + fPtr->Release(); } - //Assign a pointer, e.g. x = new T(); - TGeoRCPtr &operator=(T* ptr) + // Assign a pointer, e.g. x = new T(); + TGeoRCPtr &operator=(T *ptr) { - if(ptr) ptr->Grab(); - if(fPtr) fPtr->Release(); + if (ptr) + ptr->Grab(); + if (fPtr) + fPtr->Release(); fPtr = ptr; return (*this); } - //Assign another TGeoRCPtr - TGeoRCPtr &operator=(const TGeoRCPtr &ptr) - { - return (*this) = ptr.fPtr; - } + // Assign another TGeoRCPtr + TGeoRCPtr &operator=(const TGeoRCPtr &ptr) { return (*this) = ptr.fPtr; } - //Retrieve actual pointer - T* Get() const - { - return fPtr; - } + // Retrieve actual pointer + T *Get() const { return fPtr; } - //Some overloaded operators to facilitate dealing with an TGeoRCPtr as a conventional C pointer. - //Without these operators, one can still use the less transparent Get() method to access the pointer. - T* operator->() const {return fPtr;} //x->member - T &operator*() const {return *fPtr;} //*x, (*x).member - operator T*() const {return fPtr;} //T* y = x; - operator bool() const {return fPtr != nullptr;} //if(x) {/*x is not NULL*/} - bool operator==(const TGeoRCPtr &ptr) {return fPtr == ptr.fPtr;} - bool operator==(const T *ptr) {return fPtr == ptr;} + // Some overloaded operators to facilitate dealing with an TGeoRCPtr as a conventional C pointer. + // Without these operators, one can still use the less transparent Get() method to access the pointer. + T *operator->() const { return fPtr; } // x->member + T &operator*() const { return *fPtr; } //*x, (*x).member + operator T *() const { return fPtr; } // T* y = x; + operator bool() const { return fPtr != nullptr; } // if(x) {/*x is not NULL*/} + bool operator==(const TGeoRCPtr &ptr) { return fPtr == ptr.fPtr; } + bool operator==(const T *ptr) { return fPtr == ptr; } private: - T *fPtr; //Actual pointer + T *fPtr; // Actual pointer }; #endif diff --git a/geom/geom/inc/TGeoRegion.h b/geom/geom/inc/TGeoRegion.h index 80db6e53a54ba..3eaa6db30cecb 100644 --- a/geom/geom/inc/TGeoRegion.h +++ b/geom/geom/inc/TGeoRegion.h @@ -25,12 +25,12 @@ class TGeoRegionCut : public TNamed { TGeoRegionCut() {} TGeoRegionCut(const char *name, Double_t cut) : TNamed(name, ""), fCut(cut) {} - virtual ~TGeoRegionCut() {} + ~TGeoRegionCut() override {} Double_t GetCut() const { return fCut; } void SetCut(Double_t cut) { fCut = cut; } - ClassDef(TGeoRegionCut, 1) // A region cut + ClassDefOverride(TGeoRegionCut, 1) // A region cut }; class TGeoRegion : public TNamed { @@ -43,7 +43,7 @@ class TGeoRegion : public TNamed { TGeoRegion(const char *name, const char *title = "") : TNamed(name, title) {} TGeoRegion(const TGeoRegion &other); TGeoRegion &operator=(const TGeoRegion &other); - virtual ~TGeoRegion(); + ~TGeoRegion() override; // Volume accessors void AddVolume(TGeoVolume *vol) { fVolumes.Add(vol); } @@ -57,9 +57,9 @@ class TGeoRegion : public TNamed { int GetNcuts() const { return fCuts.GetEntriesFast(); } TGeoRegionCut *GetCut(int i) const { return (TGeoRegionCut *)fCuts.At(i); } - virtual void Print(Option_t *option = "") const; // *MENU* + void Print(Option_t *option = "") const override; // *MENU* - ClassDef(TGeoRegion, 1) // Region wrapper class + ClassDefOverride(TGeoRegion, 1) // Region wrapper class }; #endif diff --git a/geom/geom/inc/TGeoScaledShape.h b/geom/geom/inc/TGeoScaledShape.h index b3e1a612c236e..4c2c887e428ec 100644 --- a/geom/geom/inc/TGeoScaledShape.h +++ b/geom/geom/inc/TGeoScaledShape.h @@ -17,57 +17,58 @@ class TGeoScale; class TGeoShape; -class TGeoScaledShape : public TGeoBBox -{ -protected : -// data members - TGeoShape *fShape; // pointer to an existing shape - TGeoScale *fScale; // pointer to a scale transformation -// methods +class TGeoScaledShape : public TGeoBBox { +protected: + // data members + TGeoShape *fShape; // pointer to an existing shape + TGeoScale *fScale; // pointer to a scale transformation + // methods public: // constructors TGeoScaledShape(); TGeoScaledShape(const char *name, TGeoShape *shape, TGeoScale *scale); TGeoScaledShape(TGeoShape *shape, TGeoScale *scale); // destructor - virtual ~TGeoScaledShape(); + ~TGeoScaledShape() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const {return fShape->GetNmeshVertices();} - TGeoShape *GetShape() const {return fShape;} - TGeoScale *GetScale() const {return fScale;} - virtual void InspectShape() const; - virtual Bool_t IsAssembly() const; - virtual Bool_t IsCylType() const {return fShape->IsCylType();} - virtual Bool_t IsReflected() const; - virtual TBuffer3D *MakeBuffer3D() const; - static TGeoShape *MakeScaledShape(const char *name, TGeoShape *shape, TGeoScale *scale); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetScale(TGeoScale *scale) {fScale = scale;} - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buffer) const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override { return fShape->GetNmeshVertices(); } + TGeoShape *GetShape() const { return fShape; } + TGeoScale *GetScale() const { return fScale; } + void InspectShape() const override; + Bool_t IsAssembly() const override; + Bool_t IsCylType() const override { return fShape->IsCylType(); } + Bool_t IsReflected() const override; + TBuffer3D *MakeBuffer3D() const override; + static TGeoShape *MakeScaledShape(const char *name, TGeoShape *shape, TGeoScale *scale); + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetScale(TGeoScale *scale) { fScale = scale; } + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buffer) const override; - ClassDef(TGeoScaledShape, 1) // a scaled shape + ClassDefOverride(TGeoScaledShape, 1) // a scaled shape }; #endif diff --git a/geom/geom/inc/TGeoShape.h b/geom/geom/inc/TGeoShape.h index 69e5a8e246b24..507d5b499e2b5 100644 --- a/geom/geom/inc/TGeoShape.h +++ b/geom/geom/inc/TGeoShape.h @@ -22,150 +22,153 @@ class TGeoHMatrix; class TGeoVolume; class TBuffer3D; -class TGeoShape : public TNamed -{ +class TGeoShape : public TNamed { private: - static TGeoMatrix *fgTransform; // current transformation matrix that applies to shape - static Double_t fgEpsMch; // Machine round-off error + static TGeoMatrix *fgTransform; // current transformation matrix that applies to shape + static Double_t fgEpsMch; // Machine round-off error public: -enum EShapeType { - kBitMask32 = 0xffffffff, - kGeoNoShape = 0, - kGeoBad = BIT(0), - kGeoRSeg = BIT(1), - kGeoPhiSeg = BIT(2), - kGeoThetaSeg = BIT(3), - kGeoVisX = BIT(4), - kGeoVisY = BIT(5), - kGeoVisZ = BIT(6), - kGeoRunTimeShape = BIT(7), - kGeoInvalidShape = BIT(8), - kGeoTorus = BIT(9), - kGeoBox = BIT(10), - kGeoPara = BIT(11), - kGeoSph = BIT(12), - kGeoTube = BIT(13), - kGeoTubeSeg = BIT(14), - kGeoCone = BIT(15), - kGeoConeSeg = BIT(16), - kGeoPcon = BIT(17), - kGeoPgon = BIT(18), - kGeoArb8 = BIT(19), - kGeoEltu = BIT(20), - kGeoTrap = BIT(21), - kGeoCtub = BIT(22), - kGeoTrd1 = BIT(23), - kGeoTrd2 = BIT(24), - kGeoComb = BIT(25), - kGeoClosedShape = BIT(26), - kGeoXtru = BIT(27), - kGeoParaboloid = BIT(28), - kGeoHalfSpace = BIT(29), - kGeoHype = BIT(30), - kGeoSavePrimitive = BIT(20) -}; - virtual void ClearThreadData() const {} - virtual void CreateThreadData(Int_t) {} + enum EShapeType { + kBitMask32 = 0xffffffff, + kGeoNoShape = 0, + kGeoBad = BIT(0), + kGeoRSeg = BIT(1), + kGeoPhiSeg = BIT(2), + kGeoThetaSeg = BIT(3), + kGeoVisX = BIT(4), + kGeoVisY = BIT(5), + kGeoVisZ = BIT(6), + kGeoRunTimeShape = BIT(7), + kGeoInvalidShape = BIT(8), + kGeoTorus = BIT(9), + kGeoBox = BIT(10), + kGeoPara = BIT(11), + kGeoSph = BIT(12), + kGeoTube = BIT(13), + kGeoTubeSeg = BIT(14), + kGeoCone = BIT(15), + kGeoConeSeg = BIT(16), + kGeoPcon = BIT(17), + kGeoPgon = BIT(18), + kGeoArb8 = BIT(19), + kGeoEltu = BIT(20), + kGeoTrap = BIT(21), + kGeoCtub = BIT(22), + kGeoTrd1 = BIT(23), + kGeoTrd2 = BIT(24), + kGeoComb = BIT(25), + kGeoClosedShape = BIT(26), + kGeoXtru = BIT(27), + kGeoParaboloid = BIT(28), + kGeoHalfSpace = BIT(29), + kGeoHype = BIT(30), + kGeoSavePrimitive = BIT(20) + }; + virtual void ClearThreadData() const {} + virtual void CreateThreadData(Int_t) {} -protected : -// data members - Int_t fShapeId; // shape id - UInt_t fShapeBits; // shape bits -// methods - virtual void FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t localFrame) const; - Int_t GetBasicColor() const; - void SetOnBoundary(Bool_t /*flag=kTRUE*/) {} - void TransformPoints(Double_t *points, UInt_t NbPoints) const; +protected: + // data members + Int_t fShapeId; // shape id + UInt_t fShapeBits; // shape bits + // methods + virtual void FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const; + Int_t GetBasicColor() const; + void SetOnBoundary(Bool_t /*flag=kTRUE*/) {} + void TransformPoints(Double_t *points, UInt_t NbPoints) const; public: // constructors TGeoShape(); TGeoShape(const char *name); // destructor - virtual ~TGeoShape(); + ~TGeoShape() override; // methods - static Double_t Big() {return 1.E30;} - static TGeoMatrix *GetTransform(); - static void SetTransform(TGeoMatrix *matrix); - static Double_t Tolerance() {return 1.E-10;} - static Double_t ComputeEpsMch(); - static Double_t EpsMch(); - virtual void AfterStreamer() {}; - virtual Double_t Capacity() const = 0; - void CheckShape(Int_t testNo, Int_t nsamples=10000, Option_t *option=""); - virtual void ComputeBBox() = 0; - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) = 0; - virtual void ComputeNormal_v(const Double_t *, const Double_t *, Double_t *, Int_t) {} - virtual Bool_t Contains(const Double_t *point) const = 0; - virtual void Contains_v(const Double_t *, Bool_t *, Int_t) const {} - virtual Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const = 0; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py) = 0; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const = 0; - virtual void DistFromInside_v(const Double_t *, const Double_t *, Double_t *, Int_t, Double_t *) const {} - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const = 0; - virtual void DistFromOutside_v(const Double_t *, const Double_t *, Double_t *, Int_t, Double_t *) const {} - static Double_t DistToPhiMin(const Double_t *point, const Double_t *dir, Double_t s1, Double_t c1, Double_t s2, Double_t c2, - Double_t sm, Double_t cm, Bool_t in=kTRUE); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) = 0; - virtual void Draw(Option_t *option=""); // *MENU* - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - virtual const char *GetAxisName(Int_t iaxis) const = 0; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const = 0; - virtual void GetBoundingCylinder(Double_t *param) const = 0; + static Double_t Big() { return 1.E30; } + static TGeoMatrix *GetTransform(); + static void SetTransform(TGeoMatrix *matrix); + static Double_t Tolerance() { return 1.E-10; } + static Double_t ComputeEpsMch(); + static Double_t EpsMch(); + virtual void AfterStreamer(){}; + virtual Double_t Capacity() const = 0; + void CheckShape(Int_t testNo, Int_t nsamples = 10000, Option_t *option = ""); + virtual void ComputeBBox() = 0; + virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) = 0; + virtual void ComputeNormal_v(const Double_t *, const Double_t *, Double_t *, Int_t) {} + virtual Bool_t Contains(const Double_t *point) const = 0; + virtual void Contains_v(const Double_t *, Bool_t *, Int_t) const {} + virtual Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const = 0; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override = 0; + virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const = 0; + virtual void DistFromInside_v(const Double_t *, const Double_t *, Double_t *, Int_t, Double_t *) const {} + virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const = 0; + virtual void DistFromOutside_v(const Double_t *, const Double_t *, Double_t *, Int_t, Double_t *) const {} + static Double_t DistToPhiMin(const Double_t *point, const Double_t *dir, Double_t s1, Double_t c1, Double_t s2, + Double_t c2, Double_t sm, Double_t cm, Bool_t in = kTRUE); + virtual TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) = 0; + void Draw(Option_t *option = "") override; // *MENU* + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + virtual const char *GetAxisName(Int_t iaxis) const = 0; + virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const = 0; + virtual void GetBoundingCylinder(Double_t *param) const = 0; virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const = 0; - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const = 0; - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const = 0; - Int_t GetId() const {return fShapeId;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const = 0; - virtual void GetMeshNumbers(Int_t &/*nvert*/, Int_t &/*nsegs*/, Int_t &/*npols*/) const {} - virtual const char *GetName() const; - virtual Int_t GetNmeshVertices() const {return 0;} - const char *GetPointerName() const; - virtual Bool_t IsAssembly() const {return kFALSE;} - virtual Bool_t IsComposite() const {return kFALSE;} - virtual Bool_t IsCylType() const = 0; - static Bool_t IsCloseToPhi(Double_t epsil, const Double_t *point, Double_t c1, Double_t s1, Double_t c2, Double_t s2); - static Bool_t IsCrossingSemiplane(const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, Double_t &snext, Double_t &rxy); - static Bool_t IsSameWithinTolerance(Double_t a, Double_t b); - static Bool_t IsSegCrossing(Double_t x1, Double_t y1, Double_t x2, Double_t y2,Double_t x3, Double_t y3,Double_t x4, Double_t y4); - static Bool_t IsInPhiRange(const Double_t *point, Double_t phi1, Double_t phi2); - virtual Bool_t IsReflected() const {return kFALSE;} - virtual Bool_t IsVecGeom() const {return kFALSE;} - Bool_t IsRunTimeShape() const {return TestShapeBit(kGeoRunTimeShape);} - Bool_t IsValid() const {return !TestShapeBit(kGeoInvalidShape);} - virtual Bool_t IsValidBox() const = 0; - virtual void InspectShape() const = 0; - virtual TBuffer3D *MakeBuffer3D() const {return nullptr;} - static void NormalPhi(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t c1, Double_t s1, Double_t c2, Double_t s2); - virtual void Paint(Option_t *option=""); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const = 0; - virtual void Safety_v(const Double_t *, const Bool_t *, Double_t *, Int_t) const {} - static Double_t SafetyPhi(const Double_t *point, Bool_t in, Double_t phi1, Double_t phi2); - static Double_t SafetySeg(Double_t r, Double_t z, Double_t r1, Double_t z1, Double_t r2, Double_t z2, Bool_t outer); - virtual void SetDimensions(Double_t *param) = 0; - void SetId(Int_t id) {fShapeId = id;} - virtual void SetPoints(Double_t *points) const = 0; - virtual void SetPoints(Float_t *points) const = 0; - virtual void SetSegsAndPols(TBuffer3D &buff) const = 0; - void SetRuntime(Bool_t flag=kTRUE) {SetShapeBit(kGeoRunTimeShape, flag);} - Int_t ShapeDistancetoPrimitive(Int_t numpoints, Int_t px, Int_t py) const; - virtual void Sizeof3D() const = 0; + virtual Int_t GetByteCount() const = 0; + virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const = 0; + virtual Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const = 0; + Int_t GetId() const { return fShapeId; } + virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const = 0; + virtual void GetMeshNumbers(Int_t & /*nvert*/, Int_t & /*nsegs*/, Int_t & /*npols*/) const {} + const char *GetName() const override; + virtual Int_t GetNmeshVertices() const { return 0; } + const char *GetPointerName() const; + virtual Bool_t IsAssembly() const { return kFALSE; } + virtual Bool_t IsComposite() const { return kFALSE; } + virtual Bool_t IsCylType() const = 0; + static Bool_t + IsCloseToPhi(Double_t epsil, const Double_t *point, Double_t c1, Double_t s1, Double_t c2, Double_t s2); + static Bool_t IsCrossingSemiplane(const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, + Double_t &snext, Double_t &rxy); + static Bool_t IsSameWithinTolerance(Double_t a, Double_t b); + static Bool_t IsSegCrossing(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Double_t x3, Double_t y3, + Double_t x4, Double_t y4); + static Bool_t IsInPhiRange(const Double_t *point, Double_t phi1, Double_t phi2); + virtual Bool_t IsReflected() const { return kFALSE; } + virtual Bool_t IsVecGeom() const { return kFALSE; } + Bool_t IsRunTimeShape() const { return TestShapeBit(kGeoRunTimeShape); } + Bool_t IsValid() const { return !TestShapeBit(kGeoInvalidShape); } + virtual Bool_t IsValidBox() const = 0; + virtual void InspectShape() const = 0; + virtual TBuffer3D *MakeBuffer3D() const { return nullptr; } + static void NormalPhi(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t c1, Double_t s1, + Double_t c2, Double_t s2); + void Paint(Option_t *option = "") override; + virtual Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const = 0; + virtual void Safety_v(const Double_t *, const Bool_t *, Double_t *, Int_t) const {} + static Double_t SafetyPhi(const Double_t *point, Bool_t in, Double_t phi1, Double_t phi2); + static Double_t SafetySeg(Double_t r, Double_t z, Double_t r1, Double_t z1, Double_t r2, Double_t z2, Bool_t outer); + virtual void SetDimensions(Double_t *param) = 0; + void SetId(Int_t id) { fShapeId = id; } + virtual void SetPoints(Double_t *points) const = 0; + virtual void SetPoints(Float_t *points) const = 0; + virtual void SetSegsAndPols(TBuffer3D &buff) const = 0; + void SetRuntime(Bool_t flag = kTRUE) { SetShapeBit(kGeoRunTimeShape, flag); } + Int_t ShapeDistancetoPrimitive(Int_t numpoints, Int_t px, Int_t py) const; + virtual void Sizeof3D() const = 0; //----- bit manipulation - void SetShapeBit(UInt_t f, Bool_t set); - void SetShapeBit(UInt_t f) { fShapeBits |= f & kBitMask32; } - void ResetShapeBit(UInt_t f) { fShapeBits &= ~(f & kBitMask32); } - Bool_t TestShapeBit(UInt_t f) const { return (Bool_t) ((fShapeBits & f) != 0); } - Int_t TestShapeBits(UInt_t f) const { return (Int_t) (fShapeBits & f); } - void InvertShapeBit(UInt_t f) { fShapeBits ^= f & kBitMask32; } + void SetShapeBit(UInt_t f, Bool_t set); + void SetShapeBit(UInt_t f) { fShapeBits |= f & kBitMask32; } + void ResetShapeBit(UInt_t f) { fShapeBits &= ~(f & kBitMask32); } + Bool_t TestShapeBit(UInt_t f) const { return (Bool_t)((fShapeBits & f) != 0); } + Int_t TestShapeBits(UInt_t f) const { return (Int_t)(fShapeBits & f); } + void InvertShapeBit(UInt_t f) { fShapeBits ^= f & kBitMask32; } - ClassDef(TGeoShape, 2) // base class for shapes + ClassDefOverride(TGeoShape, 2) // base class for shapes }; #endif - diff --git a/geom/geom/inc/TGeoShapeAssembly.h b/geom/geom/inc/TGeoShapeAssembly.h index 02280d9067246..1f18dab6555e9 100644 --- a/geom/geom/inc/TGeoShapeAssembly.h +++ b/geom/geom/inc/TGeoShapeAssembly.h @@ -16,51 +16,52 @@ class TGeoVolumeAssembly; -class TGeoShapeAssembly : public TGeoBBox -{ -protected : -// data members - TGeoVolumeAssembly *fVolume; // assembly volume - Bool_t fBBoxOK; // has bounding box been calculated +class TGeoShapeAssembly : public TGeoBBox { +protected: + // data members + TGeoVolumeAssembly *fVolume; // assembly volume + Bool_t fBBoxOK; // has bounding box been calculated -// methods + // methods public: // constructors TGeoShapeAssembly(); TGeoShapeAssembly(TGeoVolumeAssembly *vol); // destructor - virtual ~TGeoShapeAssembly(); + ~TGeoShapeAssembly() override; // methods - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const {return 0;} - virtual void InspectShape() const; - virtual Bool_t IsAssembly() const {return kTRUE;} - virtual Bool_t IsCylType() const {return kFALSE;} - void NeedsBBoxRecompute() {fBBoxOK = kFALSE;} - void RecomputeBoxLast(); - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override { return 0; } + void InspectShape() const override; + Bool_t IsAssembly() const override { return kTRUE; } + Bool_t IsCylType() const override { return kFALSE; } + void NeedsBBoxRecompute() { fBBoxOK = kFALSE; } + void RecomputeBoxLast(); + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; - ClassDef(TGeoShapeAssembly, 2) // assembly shape + ClassDefOverride(TGeoShapeAssembly, 2) // assembly shape }; #endif diff --git a/geom/geom/inc/TGeoSphere.h b/geom/geom/inc/TGeoSphere.h index 3c4e46dae62e3..ad3692d1d0c93 100644 --- a/geom/geom/inc/TGeoSphere.h +++ b/geom/geom/inc/TGeoSphere.h @@ -14,84 +14,86 @@ #include "TGeoBBox.h" -class TGeoSphere : public TGeoBBox -{ -protected : - Int_t fNz; // number of z planes for drawing - Int_t fNseg; // number of segments for drawing - Double_t fRmin; // inner radius - Double_t fRmax; // outer radius - Double_t fTheta1; // lower theta limit - Double_t fTheta2; // higher theta limit - Double_t fPhi1; // lower phi limit - Double_t fPhi2; // higher phi limit +class TGeoSphere : public TGeoBBox { +protected: + Int_t fNz; // number of z planes for drawing + Int_t fNseg; // number of segments for drawing + Double_t fRmin; // inner radius + Double_t fRmax; // outer radius + Double_t fTheta1; // lower theta limit + Double_t fTheta2; // higher theta limit + Double_t fPhi1; // lower phi limit + Double_t fPhi2; // higher phi limit - TGeoSphere(const TGeoSphere&) = delete; - TGeoSphere& operator=(const TGeoSphere&) = delete; + TGeoSphere(const TGeoSphere &) = delete; + TGeoSphere &operator=(const TGeoSphere &) = delete; public: // constructors TGeoSphere(); - TGeoSphere(Double_t rmin, Double_t rmax, Double_t theta1=0, Double_t theta2=180, - Double_t phi1=0, Double_t phi2=360); - TGeoSphere(const char *name, Double_t rmin, Double_t rmax, Double_t theta1=0, Double_t theta2=180, - Double_t phi1=0, Double_t phi2=360); - TGeoSphere(Double_t *param, Int_t nparam=6); + TGeoSphere(Double_t rmin, Double_t rmax, Double_t theta1 = 0, Double_t theta2 = 180, Double_t phi1 = 0, + Double_t phi2 = 360); + TGeoSphere(const char *name, Double_t rmin, Double_t rmax, Double_t theta1 = 0, Double_t theta2 = 180, + Double_t phi1 = 0, Double_t phi2 = 360); + TGeoSphere(Double_t *param, Int_t nparam = 6); // destructor - virtual ~TGeoSphere(); + ~TGeoSphere() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - Double_t DistToSphere(const Double_t *point, const Double_t *dir, Double_t rsph, Bool_t check=kTRUE, Bool_t firstcross=kTRUE) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 42;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - Int_t GetNumberOfDivisions() const {return fNseg;} - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - Int_t GetNz() const {return fNz;} - virtual Double_t GetRmin() const {return fRmin;} - virtual Double_t GetRmax() const {return fRmax;} - Double_t GetTheta1() const {return fTheta1;} - Double_t GetTheta2() const {return fTheta2;} - Double_t GetPhi1() const {return fPhi1;} - Double_t GetPhi2() const {return fPhi2;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - Int_t IsOnBoundary(const Double_t *point) const; - Bool_t IsPointInside(const Double_t *point, Bool_t checkR=kTRUE, Bool_t checkTh=kTRUE, Bool_t checkPh=kTRUE) const; - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetSphDimensions(Double_t rmin, Double_t rmax, Double_t theta1, - Double_t theta2, Double_t phi1, Double_t phi2); - virtual void SetNumberOfDivisions(Int_t p); - virtual void SetDimensions(Double_t *param); - void SetDimensions(Double_t *param, Int_t nparam); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistToSphere(const Double_t *point, const Double_t *dir, Double_t rsph, Bool_t check = kTRUE, + Bool_t firstcross = kTRUE) const; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 42; } + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Int_t GetNumberOfDivisions() const { return fNseg; } + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + Int_t GetNz() const { return fNz; } + virtual Double_t GetRmin() const { return fRmin; } + virtual Double_t GetRmax() const { return fRmax; } + Double_t GetTheta1() const { return fTheta1; } + Double_t GetTheta2() const { return fTheta2; } + Double_t GetPhi1() const { return fPhi1; } + Double_t GetPhi2() const { return fPhi2; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Int_t IsOnBoundary(const Double_t *point) const; + Bool_t + IsPointInside(const Double_t *point, Bool_t checkR = kTRUE, Bool_t checkTh = kTRUE, Bool_t checkPh = kTRUE) const; + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetSphDimensions(Double_t rmin, Double_t rmax, Double_t theta1, Double_t theta2, Double_t phi1, Double_t phi2); + virtual void SetNumberOfDivisions(Int_t p); + void SetDimensions(Double_t *param) override; + void SetDimensions(Double_t *param, Int_t nparam); + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; - ClassDef(TGeoSphere, 1) // sphere class + ClassDefOverride(TGeoSphere, 1) // sphere class }; #endif diff --git a/geom/geom/inc/TGeoStateInfo.h b/geom/geom/inc/TGeoStateInfo.h index 839fa19373451..bc2f0ed684098 100644 --- a/geom/geom/inc/TGeoStateInfo.h +++ b/geom/geom/inc/TGeoStateInfo.h @@ -19,40 +19,40 @@ class TGeoPolygon; struct TGeoStateInfo; struct TGeoStateInfo { - TGeoNode *fNode; // Node to which applies + TGeoNode *fNode; // Node to which applies // Assembly data - Int_t fAsmCurrent; // Index for current entered node (assemblies) - Int_t fAsmNext; // Index for next entered node (assemblies) + Int_t fAsmCurrent; // Index for current entered node (assemblies) + Int_t fAsmNext; // Index for next entered node (assemblies) // Divisions data - Int_t fDivCurrent; // Index for the current division node - Int_t fDivNext; // Index for the next division node - TGeoTranslation fDivTrans; // Translation used by current division node - TGeoRotation fDivRot; // Rotation used by current division node - TGeoCombiTrans fDivCombi; // Combi transformation used by current division + Int_t fDivCurrent; // Index for the current division node + Int_t fDivNext; // Index for the next division node + TGeoTranslation fDivTrans; // Translation used by current division node + TGeoRotation fDivRot; // Rotation used by current division node + TGeoCombiTrans fDivCombi; // Combi transformation used by current division // Voxels data - Int_t fVoxNcandidates; // Number of candidates - Int_t fVoxCurrent; // Index of current voxel in sorted list - Int_t *fVoxCheckList; // List of candidates - UChar_t *fVoxBits1; // Bits used for list intersection - Int_t fVoxSlices[3]; // Slice indices for current voxel - Int_t fVoxInc[3]; // Slice index increment - Double_t fVoxInvdir[3]; // 1/current director cosines - Double_t fVoxLimits[3]; // Limits on X,Y,Z + Int_t fVoxNcandidates; // Number of candidates + Int_t fVoxCurrent; // Index of current voxel in sorted list + Int_t *fVoxCheckList; // List of candidates + UChar_t *fVoxBits1; // Bits used for list intersection + Int_t fVoxSlices[3]; // Slice indices for current voxel + Int_t fVoxInc[3]; // Slice index increment + Double_t fVoxInvdir[3]; // 1/current director cosines + Double_t fVoxLimits[3]; // Limits on X,Y,Z // Composite shape data - Int_t fBoolSelected; // Selected Boolean node + Int_t fBoolSelected; // Selected Boolean node // Xtru shape data - Int_t fXtruSeg; // current segment [0,fNvert-1] - Int_t fXtruIz; // current z plane [0,fNz-1] - Double_t *fXtruXc; // [fNvert] current X positions for polygon vertices - Double_t *fXtruYc; // [fNvert] current Y positions for polygon vertices - TGeoPolygon *fXtruPoly; // polygon defining section shape + Int_t fXtruSeg; // current segment [0,fNvert-1] + Int_t fXtruIz; // current z plane [0,fNz-1] + Double_t *fXtruXc; // [fNvert] current X positions for polygon vertices + Double_t *fXtruYc; // [fNvert] current Y positions for polygon vertices + TGeoPolygon *fXtruPoly; // polygon defining section shape - TGeoStateInfo(Int_t maxdaughters=0); + TGeoStateInfo(Int_t maxdaughters = 0); TGeoStateInfo(const TGeoStateInfo &other) = delete; - TGeoStateInfo & operator=(const TGeoStateInfo &other) = delete; + TGeoStateInfo &operator=(const TGeoStateInfo &other) = delete; virtual ~TGeoStateInfo(); - ClassDef(TGeoStateInfo, 0) // No I/O for this structure + ClassDef(TGeoStateInfo, 0) // No I/O for this structure }; #endif diff --git a/geom/geom/inc/TGeoSystemOfUnits.h b/geom/geom/inc/TGeoSystemOfUnits.h index 2dcb918a0cfee..b0a4391946cb6 100644 --- a/geom/geom/inc/TGeoSystemOfUnits.h +++ b/geom/geom/inc/TGeoSystemOfUnits.h @@ -60,274 +60,274 @@ namespace TGeoUnit { - // - // TGeo follows Geant3 convention as specified in manual - // "Unless otherwise specified, the following units are used throughout the program: - // centimeter, second, degree, GeV" - - // - // - // - static constexpr double pi = 3.14159265358979323846; - static constexpr double twopi = 2 * pi; - static constexpr double halfpi = pi / 2; - static constexpr double pi2 = pi * pi; - - // - // Length [L] - // - static constexpr double millimeter = 0.1; - static constexpr double millimeter2 = millimeter * millimeter; - static constexpr double millimeter3 = millimeter * millimeter * millimeter; - - static constexpr double centimeter = 10. * millimeter; // Base unit - static constexpr double centimeter2 = centimeter * centimeter; - static constexpr double centimeter3 = centimeter * centimeter * centimeter; - - static constexpr double meter = 1000. * millimeter; - static constexpr double meter2 = meter * meter; - static constexpr double meter3 = meter * meter * meter; - - static constexpr double kilometer = 1000. * meter; - static constexpr double kilometer2 = kilometer * kilometer; - static constexpr double kilometer3 = kilometer * kilometer * kilometer; - - static constexpr double parsec = 3.0856775807e+16 * meter; - - static constexpr double micrometer = 1.e-6 * meter; - static constexpr double nanometer = 1.e-9 * meter; - static constexpr double angstrom = 1.e-10 * meter; - static constexpr double fermi = 1.e-15 * meter; - - static constexpr double barn = 1.e-28 * meter2; - static constexpr double millibarn = 1.e-3 * barn; - static constexpr double microbarn = 1.e-6 * barn; - static constexpr double nanobarn = 1.e-9 * barn; - static constexpr double picobarn = 1.e-12 * barn; - - // symbols - static constexpr double nm = nanometer; - static constexpr double um = micrometer; - - static constexpr double mm = millimeter; - static constexpr double mm2 = millimeter2; - static constexpr double mm3 = millimeter3; - - static constexpr double cm = centimeter; - static constexpr double cm2 = centimeter2; - static constexpr double cm3 = centimeter3; - - static constexpr double liter = 1.e+3 * cm3; - static constexpr double L = liter; - static constexpr double dL = 1.e-1 * liter; - static constexpr double cL = 1.e-2 * liter; - static constexpr double mL = 1.e-3 * liter; - - static constexpr double m = meter; - static constexpr double m2 = meter2; - static constexpr double m3 = meter3; - - static constexpr double km = kilometer; - static constexpr double km2 = kilometer2; - static constexpr double km3 = kilometer3; - - static constexpr double pc = parsec; - - // - // Angle - // - static constexpr double degree = 1.0; // Base unit - static constexpr double radian = (180.0 / pi) * degree; - static constexpr double milliradian = 1.e-3 * radian; - - static constexpr double steradian = 1.; - - // symbols - static constexpr double rad = radian; - static constexpr double mrad = milliradian; - static constexpr double sr = steradian; - static constexpr double deg = degree; - - // - // Time [T] - // - static constexpr double nanosecond = 1.e-9; - static constexpr double second = 1.e+9 * nanosecond; // Base unit - static constexpr double millisecond = 1.e-3 * second; - static constexpr double microsecond = 1.e-6 * second; - static constexpr double picosecond = 1.e-12 * second; - - static constexpr double hertz = 1. / second; - static constexpr double kilohertz = 1.e+3 * hertz; - static constexpr double megahertz = 1.e+6 * hertz; - - // symbols - static constexpr double ns = nanosecond; - static constexpr double s = second; - static constexpr double ms = millisecond; - static constexpr double us = microsecond; - static constexpr double ps = picosecond; - - // - // Electric charge [Q] - // - static constexpr double eplus = 1.; // positron charge - static constexpr double e_SI = 1.602176487e-19; // positron charge in coulomb - static constexpr double coulomb = eplus / e_SI; // coulomb = 6.24150 e+18 * eplus - - // - // Energy [E] - // - static constexpr double megaelectronvolt = 1.e-3; - static constexpr double electronvolt = 1.e-6 * megaelectronvolt; - static constexpr double kiloelectronvolt = 1.e-3 * megaelectronvolt; - static constexpr double gigaelectronvolt = 1.e+3 * megaelectronvolt; // Base unit - static constexpr double teraelectronvolt = 1.e+6 * megaelectronvolt; - static constexpr double petaelectronvolt = 1.e+9 * megaelectronvolt; - - static constexpr double joule = electronvolt / e_SI; // joule = 6.24150 e+12 * MeV - - // symbols - static constexpr double MeV = megaelectronvolt; - static constexpr double eV = electronvolt; - static constexpr double keV = kiloelectronvolt; - static constexpr double GeV = gigaelectronvolt; - static constexpr double TeV = teraelectronvolt; - static constexpr double PeV = petaelectronvolt; - - // - // Mass [E][T^2][L^-2] - // - static constexpr double kilogram = joule * second * second / (meter * meter); - static constexpr double gram = 1.e-3 * kilogram; - static constexpr double milligram = 1.e-3 * gram; - - // symbols - static constexpr double kg = kilogram; - static constexpr double g = gram; - static constexpr double mg = milligram; - - // - // Power [E][T^-1] - // - static constexpr double watt = joule / second; // watt = 6.24150 e+3 * MeV/ns - - // - // Force [E][L^-1] - // - static constexpr double newton = joule / meter; // newton = 6.24150 e+9 * MeV/mm - - // - // Pressure [E][L^-3] - // +// +// TGeo follows Geant3 convention as specified in manual +// "Unless otherwise specified, the following units are used throughout the program: +// centimeter, second, degree, GeV" + +// +// +// +static constexpr double pi = 3.14159265358979323846; +static constexpr double twopi = 2 * pi; +static constexpr double halfpi = pi / 2; +static constexpr double pi2 = pi * pi; + +// +// Length [L] +// +static constexpr double millimeter = 0.1; +static constexpr double millimeter2 = millimeter * millimeter; +static constexpr double millimeter3 = millimeter * millimeter * millimeter; + +static constexpr double centimeter = 10. * millimeter; // Base unit +static constexpr double centimeter2 = centimeter * centimeter; +static constexpr double centimeter3 = centimeter * centimeter * centimeter; + +static constexpr double meter = 1000. * millimeter; +static constexpr double meter2 = meter * meter; +static constexpr double meter3 = meter * meter * meter; + +static constexpr double kilometer = 1000. * meter; +static constexpr double kilometer2 = kilometer * kilometer; +static constexpr double kilometer3 = kilometer * kilometer * kilometer; + +static constexpr double parsec = 3.0856775807e+16 * meter; + +static constexpr double micrometer = 1.e-6 * meter; +static constexpr double nanometer = 1.e-9 * meter; +static constexpr double angstrom = 1.e-10 * meter; +static constexpr double fermi = 1.e-15 * meter; + +static constexpr double barn = 1.e-28 * meter2; +static constexpr double millibarn = 1.e-3 * barn; +static constexpr double microbarn = 1.e-6 * barn; +static constexpr double nanobarn = 1.e-9 * barn; +static constexpr double picobarn = 1.e-12 * barn; + +// symbols +static constexpr double nm = nanometer; +static constexpr double um = micrometer; + +static constexpr double mm = millimeter; +static constexpr double mm2 = millimeter2; +static constexpr double mm3 = millimeter3; + +static constexpr double cm = centimeter; +static constexpr double cm2 = centimeter2; +static constexpr double cm3 = centimeter3; + +static constexpr double liter = 1.e+3 * cm3; +static constexpr double L = liter; +static constexpr double dL = 1.e-1 * liter; +static constexpr double cL = 1.e-2 * liter; +static constexpr double mL = 1.e-3 * liter; + +static constexpr double m = meter; +static constexpr double m2 = meter2; +static constexpr double m3 = meter3; + +static constexpr double km = kilometer; +static constexpr double km2 = kilometer2; +static constexpr double km3 = kilometer3; + +static constexpr double pc = parsec; + +// +// Angle +// +static constexpr double degree = 1.0; // Base unit +static constexpr double radian = (180.0 / pi) * degree; +static constexpr double milliradian = 1.e-3 * radian; + +static constexpr double steradian = 1.; + +// symbols +static constexpr double rad = radian; +static constexpr double mrad = milliradian; +static constexpr double sr = steradian; +static constexpr double deg = degree; + +// +// Time [T] +// +static constexpr double nanosecond = 1.e-9; +static constexpr double second = 1.e+9 * nanosecond; // Base unit +static constexpr double millisecond = 1.e-3 * second; +static constexpr double microsecond = 1.e-6 * second; +static constexpr double picosecond = 1.e-12 * second; + +static constexpr double hertz = 1. / second; +static constexpr double kilohertz = 1.e+3 * hertz; +static constexpr double megahertz = 1.e+6 * hertz; + +// symbols +static constexpr double ns = nanosecond; +static constexpr double s = second; +static constexpr double ms = millisecond; +static constexpr double us = microsecond; +static constexpr double ps = picosecond; + +// +// Electric charge [Q] +// +static constexpr double eplus = 1.; // positron charge +static constexpr double e_SI = 1.602176487e-19; // positron charge in coulomb +static constexpr double coulomb = eplus / e_SI; // coulomb = 6.24150 e+18 * eplus + +// +// Energy [E] +// +static constexpr double megaelectronvolt = 1.e-3; +static constexpr double electronvolt = 1.e-6 * megaelectronvolt; +static constexpr double kiloelectronvolt = 1.e-3 * megaelectronvolt; +static constexpr double gigaelectronvolt = 1.e+3 * megaelectronvolt; // Base unit +static constexpr double teraelectronvolt = 1.e+6 * megaelectronvolt; +static constexpr double petaelectronvolt = 1.e+9 * megaelectronvolt; + +static constexpr double joule = electronvolt / e_SI; // joule = 6.24150 e+12 * MeV + +// symbols +static constexpr double MeV = megaelectronvolt; +static constexpr double eV = electronvolt; +static constexpr double keV = kiloelectronvolt; +static constexpr double GeV = gigaelectronvolt; +static constexpr double TeV = teraelectronvolt; +static constexpr double PeV = petaelectronvolt; + +// +// Mass [E][T^2][L^-2] +// +static constexpr double kilogram = joule * second * second / (meter * meter); +static constexpr double gram = 1.e-3 * kilogram; +static constexpr double milligram = 1.e-3 * gram; + +// symbols +static constexpr double kg = kilogram; +static constexpr double g = gram; +static constexpr double mg = milligram; + +// +// Power [E][T^-1] +// +static constexpr double watt = joule / second; // watt = 6.24150 e+3 * MeV/ns + +// +// Force [E][L^-1] +// +static constexpr double newton = joule / meter; // newton = 6.24150 e+9 * MeV/mm + +// +// Pressure [E][L^-3] +// #define pascal hep_pascal // a trick to avoid warnings - static constexpr double hep_pascal = newton / m2; // pascal = 6.24150 e+3 * MeV/mm3 - static constexpr double bar = 100000 * pascal; // bar = 6.24150 e+8 * MeV/mm3 - static constexpr double atmosphere = 101325 * pascal; // atm = 6.32420 e+8 * MeV/mm3 - - // - // Electric current [Q][T^-1] - // - static constexpr double ampere = coulomb / second; // ampere = 6.24150 e+9 * eplus/ns - static constexpr double milliampere = 1.e-3 * ampere; - static constexpr double microampere = 1.e-6 * ampere; - static constexpr double nanoampere = 1.e-9 * ampere; - - // - // Electric potential [E][Q^-1] - // - static constexpr double megavolt = megaelectronvolt / eplus; - static constexpr double kilovolt = 1.e-3 * megavolt; - static constexpr double volt = 1.e-6 * megavolt; - - // - // Electric resistance [E][T][Q^-2] - // - static constexpr double ohm = volt / ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) - - // - // Electric capacitance [Q^2][E^-1] - // - static constexpr double farad = coulomb / volt; // farad = 6.24150e+24 * eplus/Megavolt - static constexpr double millifarad = 1.e-3 * farad; - static constexpr double microfarad = 1.e-6 * farad; - static constexpr double nanofarad = 1.e-9 * farad; - static constexpr double picofarad = 1.e-12 * farad; - - // - // Magnetic Flux [T][E][Q^-1] - // - static constexpr double weber = volt * second; // weber = 1000*megavolt*ns - - // - // Magnetic Field [T][E][Q^-1][L^-2] - // - static constexpr double tesla = volt * second / meter2; // tesla =0.001*megavolt*ns/mm2 - - static constexpr double gauss = 1.e-4 * tesla; - static constexpr double kilogauss = 1.e-1 * tesla; - - // - // Inductance [T^2][E][Q^-2] - // - static constexpr double henry = weber / ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 - - // - // Temperature - // - static constexpr double kelvin = 1.; - - // - // Amount of substance - // - static constexpr double mole = 1.; - - // - // Activity [T^-1] - // - static constexpr double becquerel = 1. / second; - static constexpr double curie = 3.7e+10 * becquerel; - static constexpr double kilobecquerel = 1.e+3 * becquerel; - static constexpr double megabecquerel = 1.e+6 * becquerel; - static constexpr double gigabecquerel = 1.e+9 * becquerel; - static constexpr double millicurie = 1.e-3 * curie; - static constexpr double microcurie = 1.e-6 * curie; - static constexpr double Bq = becquerel; - static constexpr double kBq = kilobecquerel; - static constexpr double MBq = megabecquerel; - static constexpr double GBq = gigabecquerel; - static constexpr double Ci = curie; - static constexpr double mCi = millicurie; - static constexpr double uCi = microcurie; - - // - // Absorbed dose [L^2][T^-2] - // - static constexpr double gray = joule / kilogram; - static constexpr double kilogray = 1.e+3 * gray; - static constexpr double milligray = 1.e-3 * gray; - static constexpr double microgray = 1.e-6 * gray; - - // - // Luminous intensity [I] - // - static constexpr double candela = 1.; - - // - // Luminous flux [I] - // - static constexpr double lumen = candela * steradian; - - // - // Illuminance [I][L^-2] - // - static constexpr double lux = lumen / meter2; - - // - // Miscellaneous - // - static constexpr double perCent = 0.01; - static constexpr double perThousand = 0.001; - static constexpr double perMillion = 0.000001; -} // namespace TGeoUnit +static constexpr double hep_pascal = newton / m2; // pascal = 6.24150 e+3 * MeV/mm3 +static constexpr double bar = 100000 * pascal; // bar = 6.24150 e+8 * MeV/mm3 +static constexpr double atmosphere = 101325 * pascal; // atm = 6.32420 e+8 * MeV/mm3 + +// +// Electric current [Q][T^-1] +// +static constexpr double ampere = coulomb / second; // ampere = 6.24150 e+9 * eplus/ns +static constexpr double milliampere = 1.e-3 * ampere; +static constexpr double microampere = 1.e-6 * ampere; +static constexpr double nanoampere = 1.e-9 * ampere; + +// +// Electric potential [E][Q^-1] +// +static constexpr double megavolt = megaelectronvolt / eplus; +static constexpr double kilovolt = 1.e-3 * megavolt; +static constexpr double volt = 1.e-6 * megavolt; + +// +// Electric resistance [E][T][Q^-2] +// +static constexpr double ohm = volt / ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) + +// +// Electric capacitance [Q^2][E^-1] +// +static constexpr double farad = coulomb / volt; // farad = 6.24150e+24 * eplus/Megavolt +static constexpr double millifarad = 1.e-3 * farad; +static constexpr double microfarad = 1.e-6 * farad; +static constexpr double nanofarad = 1.e-9 * farad; +static constexpr double picofarad = 1.e-12 * farad; + +// +// Magnetic Flux [T][E][Q^-1] +// +static constexpr double weber = volt * second; // weber = 1000*megavolt*ns + +// +// Magnetic Field [T][E][Q^-1][L^-2] +// +static constexpr double tesla = volt * second / meter2; // tesla =0.001*megavolt*ns/mm2 + +static constexpr double gauss = 1.e-4 * tesla; +static constexpr double kilogauss = 1.e-1 * tesla; + +// +// Inductance [T^2][E][Q^-2] +// +static constexpr double henry = weber / ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 + +// +// Temperature +// +static constexpr double kelvin = 1.; + +// +// Amount of substance +// +static constexpr double mole = 1.; + +// +// Activity [T^-1] +// +static constexpr double becquerel = 1. / second; +static constexpr double curie = 3.7e+10 * becquerel; +static constexpr double kilobecquerel = 1.e+3 * becquerel; +static constexpr double megabecquerel = 1.e+6 * becquerel; +static constexpr double gigabecquerel = 1.e+9 * becquerel; +static constexpr double millicurie = 1.e-3 * curie; +static constexpr double microcurie = 1.e-6 * curie; +static constexpr double Bq = becquerel; +static constexpr double kBq = kilobecquerel; +static constexpr double MBq = megabecquerel; +static constexpr double GBq = gigabecquerel; +static constexpr double Ci = curie; +static constexpr double mCi = millicurie; +static constexpr double uCi = microcurie; + +// +// Absorbed dose [L^2][T^-2] +// +static constexpr double gray = joule / kilogram; +static constexpr double kilogray = 1.e+3 * gray; +static constexpr double milligray = 1.e-3 * gray; +static constexpr double microgray = 1.e-6 * gray; + +// +// Luminous intensity [I] +// +static constexpr double candela = 1.; + +// +// Luminous flux [I] +// +static constexpr double lumen = candela * steradian; + +// +// Illuminance [I][L^-2] +// +static constexpr double lux = lumen / meter2; + +// +// Miscellaneous +// +static constexpr double perCent = 0.01; +static constexpr double perThousand = 0.001; +static constexpr double perMillion = 0.000001; +} // namespace TGeoUnit #endif /* TGEO_SYSTEM_OF_UNITS_H */ diff --git a/geom/geom/inc/TGeoTessellated.h b/geom/geom/inc/TGeoTessellated.h index 64deb80fdac07..51d48ac261073 100644 --- a/geom/geom/inc/TGeoTessellated.h +++ b/geom/geom/inc/TGeoTessellated.h @@ -116,8 +116,8 @@ class TGeoTessellated : public TGeoBBox { std::vector fVertices; // List of vertices std::vector fFacets; // List of facets - TGeoTessellated(const TGeoTessellated&) = delete; - TGeoTessellated& operator=(const TGeoTessellated&) = delete; + TGeoTessellated(const TGeoTessellated &) = delete; + TGeoTessellated &operator=(const TGeoTessellated &) = delete; public: // constructors @@ -125,9 +125,9 @@ class TGeoTessellated : public TGeoBBox { TGeoTessellated(const char *name, int nfacets = 0); TGeoTessellated(const char *name, const std::vector &vertices); // destructor - virtual ~TGeoTessellated() {} + ~TGeoTessellated() override {} - void ComputeBBox(); + void ComputeBBox() override; void CloseShape(bool check = true, bool fixFlipped = true, bool verbose = true); bool AddFacet(const Vertex_t &pt0, const Vertex_t &pt1, const Vertex_t &pt2); @@ -141,22 +141,22 @@ class TGeoTessellated : public TGeoBBox { bool IsClosedBody() const { return fClosedBody; } bool IsDefined() const { return fDefined; } - const TGeoFacet &GetFacet(int i) { return fFacets[i]; } - const Vertex_t &GetVertex(int i) { return fVertices[i]; } - - virtual void AfterStreamer(); - virtual int DistancetoPrimitive(int, int) { return 99999; } - virtual const TBuffer3D &GetBuffer3D(int reqSections, Bool_t localFrame) const; - virtual void GetMeshNumbers(int &nvert, int &nsegs, int &npols) const; - virtual int GetNmeshVertices() const { return fNvert; } - virtual void InspectShape() const {} - virtual TBuffer3D *MakeBuffer3D() const; - virtual void Print(Option_t *option = "") const; - virtual void SavePrimitive(std::ostream &, Option_t *) {} - virtual void SetPoints(double *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const {} + const TGeoFacet &GetFacet(int i) const { return fFacets[i]; } + const Vertex_t &GetVertex(int i) const { return fVertices[i]; } + + void AfterStreamer() override; + int DistancetoPrimitive(int, int) override { return 99999; } + const TBuffer3D &GetBuffer3D(int reqSections, Bool_t localFrame) const override; + void GetMeshNumbers(int &nvert, int &nsegs, int &npols) const override; + int GetNmeshVertices() const override { return fNvert; } + void InspectShape() const override {} + TBuffer3D *MakeBuffer3D() const override; + void Print(Option_t *option = "") const override; + void SavePrimitive(std::ostream &, Option_t *) override {} + void SetPoints(double *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override {} /// Resize and center the shape in a box of size maxsize void ResizeCenter(double maxsize); @@ -173,7 +173,7 @@ class TGeoTessellated : public TGeoBBox { /// Reader from .obj format static TGeoTessellated *ImportFromObjFormat(const char *objfile, bool check = false, bool verbose = false); - ClassDef(TGeoTessellated, 1) // tessellated shape class + ClassDefOverride(TGeoTessellated, 1) // tessellated shape class }; #endif diff --git a/geom/geom/inc/TGeoTorus.h b/geom/geom/inc/TGeoTorus.h index 71c1eed6a2bd3..a6a2109da5ded 100644 --- a/geom/geom/inc/TGeoTorus.h +++ b/geom/geom/inc/TGeoTorus.h @@ -14,80 +14,81 @@ #include "TGeoBBox.h" -class TGeoTorus : public TGeoBBox -{ -protected : -// data members - Double_t fR; // axial radius - Double_t fRmin; // inner radius - Double_t fRmax; // outer radius - Double_t fPhi1; // starting phi - Double_t fDphi; // phi extent -// methods - TGeoTorus(const TGeoTorus&) = delete; - TGeoTorus& operator=(const TGeoTorus&) = delete; +class TGeoTorus : public TGeoBBox { +protected: + // data members + Double_t fR; // axial radius + Double_t fRmin; // inner radius + Double_t fRmax; // outer radius + Double_t fPhi1; // starting phi + Double_t fDphi; // phi extent + // methods + TGeoTorus(const TGeoTorus &) = delete; + TGeoTorus &operator=(const TGeoTorus &) = delete; public: - virtual Double_t Capacity() const; - Double_t Daxis(const Double_t *pt, const Double_t *dir, Double_t t) const; - Double_t DDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const; - Double_t DDDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const; - Double_t ToBoundary(const Double_t *pt, const Double_t *dir, Double_t r, Bool_t in) const; - Int_t SolveCubic(Double_t a, Double_t b, Double_t c, Double_t *x) const; - Int_t SolveQuartic(Double_t a, Double_t b, Double_t c, Double_t d, Double_t *x) const; + Double_t Capacity() const override; + Double_t Daxis(const Double_t *pt, const Double_t *dir, Double_t t) const; + Double_t DDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const; + Double_t DDDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const; + Double_t ToBoundary(const Double_t *pt, const Double_t *dir, Double_t r, Bool_t in) const; + Int_t SolveCubic(Double_t a, Double_t b, Double_t c, Double_t *x) const; + Int_t SolveQuartic(Double_t a, Double_t b, Double_t c, Double_t d, Double_t *x) const; + public: // constructors TGeoTorus(); - TGeoTorus(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1=0, Double_t dphi=360); - TGeoTorus(const char * name, Double_t r, Double_t rmin, Double_t rmax, Double_t phi1=0, Double_t dphi=360); + TGeoTorus(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1 = 0, Double_t dphi = 360); + TGeoTorus(const char *name, Double_t r, Double_t rmin, Double_t rmax, Double_t phi1 = 0, Double_t dphi = 360); TGeoTorus(Double_t *params); // destructor - virtual ~TGeoTorus() {} + ~TGeoTorus() override {} // methods - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 56;} - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const {return kFALSE;} - Double_t GetR() const {return fR;} - Double_t GetRmin() const {return fRmin;} - Double_t GetRmax() const {return fRmax;} - Double_t GetPhi1() const {return fPhi1;} - Double_t GetDphi() const {return fDphi;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetTorusDimensions(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoTorus, 1) // torus class + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 56; } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + Bool_t GetPointsOnSegments(Int_t /*npoints*/, Double_t * /*array*/) const override { return kFALSE; } + Double_t GetR() const { return fR; } + Double_t GetRmin() const { return fRmin; } + Double_t GetRmax() const { return fRmax; } + Double_t GetPhi1() const { return fPhi1; } + Double_t GetDphi() const { return fDphi; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetTorusDimensions(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; + ClassDefOverride(TGeoTorus, 1) // torus class }; #endif diff --git a/geom/geom/inc/TGeoTrd1.h b/geom/geom/inc/TGeoTrd1.h index 222b8b80c7b82..9951e808e7437 100644 --- a/geom/geom/inc/TGeoTrd1.h +++ b/geom/geom/inc/TGeoTrd1.h @@ -14,18 +14,17 @@ #include "TGeoBBox.h" -class TGeoTrd1 : public TGeoBBox -{ +class TGeoTrd1 : public TGeoBBox { protected: // data members - Double_t fDx1; // half length in X at lower Z surface (-dz) - Double_t fDx2; // half length in X at higher Z surface (+dz) - Double_t fDy; // half length in Y - Double_t fDz; // half length in Z + Double_t fDx1; // half length in X at lower Z surface (-dz) + Double_t fDx2; // half length in X at higher Z surface (+dz) + Double_t fDy; // half length in Y + Double_t fDz; // half length in Z // methods - TGeoTrd1(const TGeoTrd1&) = delete; - TGeoTrd1& operator=(const TGeoTrd1&) = delete; + TGeoTrd1(const TGeoTrd1 &) = delete; + TGeoTrd1 &operator=(const TGeoTrd1 &) = delete; public: // constructors @@ -34,46 +33,49 @@ class TGeoTrd1 : public TGeoBBox TGeoTrd1(const char *name, Double_t dx1, Double_t dx2, Double_t dy, Double_t dz); TGeoTrd1(Double_t *params); // destructor - virtual ~TGeoTrd1(); + ~TGeoTrd1() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual Int_t GetByteCount() const {return 52;} - Double_t GetDx1() const {return fDx1;} - Double_t GetDx2() const {return fDx2;} - Double_t GetDy() const {return fDy;} - Double_t GetDz() const {return fDz;} - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - void GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const; - void GetOppositeCorner(const Double_t *point, Int_t inorm, Double_t *vertex, Double_t *normals) const; - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - void SetVertex(Double_t *vertex) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + Int_t GetByteCount() const override { return 52; } + Double_t GetDx1() const { return fDx1; } + Double_t GetDx2() const { return fDx2; } + Double_t GetDy() const { return fDy; } + Double_t GetDz() const { return fDz; } + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const; + void GetOppositeCorner(const Double_t *point, Int_t inorm, Double_t *vertex, Double_t *normals) const; + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetVertex(Double_t *vertex) const; + void Sizeof3D() const override; - ClassDef(TGeoTrd1, 1) // TRD1 shape class + ClassDefOverride(TGeoTrd1, 1) // TRD1 shape class }; #endif diff --git a/geom/geom/inc/TGeoTrd2.h b/geom/geom/inc/TGeoTrd2.h index 3fffb678f9456..2053ac84370b9 100644 --- a/geom/geom/inc/TGeoTrd2.h +++ b/geom/geom/inc/TGeoTrd2.h @@ -14,19 +14,18 @@ #include "TGeoBBox.h" -class TGeoTrd2 : public TGeoBBox -{ +class TGeoTrd2 : public TGeoBBox { protected: // data members - Double_t fDx1; // half length in X at lower Z surface (-dz) - Double_t fDx2; // half length in X at higher Z surface (+dz) - Double_t fDy1; // half length in Y at lower Z surface (-dz) - Double_t fDy2; // half length in Y at higher Z surface (+dz) - Double_t fDz; // half length in Z + Double_t fDx1; // half length in X at lower Z surface (-dz) + Double_t fDx2; // half length in X at higher Z surface (+dz) + Double_t fDy1; // half length in Y at lower Z surface (-dz) + Double_t fDy2; // half length in Y at higher Z surface (+dz) + Double_t fDz; // half length in Z // methods - TGeoTrd2(const TGeoTrd2&) = delete; - TGeoTrd2& operator=(const TGeoTrd2&) = delete; + TGeoTrd2(const TGeoTrd2 &) = delete; + TGeoTrd2 &operator=(const TGeoTrd2 &) = delete; public: // constructors @@ -35,47 +34,50 @@ class TGeoTrd2 : public TGeoBBox TGeoTrd2(const char *name, Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, Double_t dz); TGeoTrd2(Double_t *params); // destructor - virtual ~TGeoTrd2(); + ~TGeoTrd2() override; // methods - virtual Double_t Capacity() const; - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual Int_t GetByteCount() const {return 56;} - Double_t GetDx1() const {return fDx1;} - Double_t GetDx2() const {return fDx2;} - Double_t GetDy1() const {return fDy1;} - Double_t GetDy2() const {return fDy2;} - Double_t GetDz() const {return fDz;} - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - void GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const; - void GetOppositeCorner(const Double_t *point, Int_t inorm, Double_t *vertex, Double_t *normals) const; - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kFALSE;} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - void SetVertex(Double_t *vertex) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + Int_t GetByteCount() const override { return 56; } + Double_t GetDx1() const { return fDx1; } + Double_t GetDx2() const { return fDx2; } + Double_t GetDy1() const { return fDy1; } + Double_t GetDy2() const { return fDy2; } + Double_t GetDz() const { return fDz; } + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const; + void GetOppositeCorner(const Double_t *point, Int_t inorm, Double_t *vertex, Double_t *normals) const; + void InspectShape() const override; + Bool_t IsCylType() const override { return kFALSE; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetVertex(Double_t *vertex) const; + void Sizeof3D() const override; - ClassDef(TGeoTrd2, 1) // TRD2 shape class + ClassDefOverride(TGeoTrd2, 1) // TRD2 shape class }; #endif diff --git a/geom/geom/inc/TGeoTube.h b/geom/geom/inc/TGeoTube.h index 6b220d26d567f..9b74be46d2871 100644 --- a/geom/geom/inc/TGeoTube.h +++ b/geom/geom/inc/TGeoTube.h @@ -14,214 +14,216 @@ #include "TGeoBBox.h" -class TGeoTube : public TGeoBBox -{ -protected : -// data members - Double_t fRmin; // inner radius - Double_t fRmax; // outer radius - Double_t fDz; // half length -// methods - - TGeoTube(const TGeoTube&) = delete; - TGeoTube& operator=(const TGeoTube&) = delete; +class TGeoTube : public TGeoBBox { +protected: + // data members + Double_t fRmin; // inner radius + Double_t fRmax; // outer radius + Double_t fDz; // half length + // methods + + TGeoTube(const TGeoTube &) = delete; + TGeoTube &operator=(const TGeoTube &) = delete; public: // constructors TGeoTube(); TGeoTube(Double_t rmin, Double_t rmax, Double_t dz); - TGeoTube(const char * name, Double_t rmin, Double_t rmax, Double_t dz); + TGeoTube(const char *name, Double_t rmin, Double_t rmax, Double_t dz); TGeoTube(Double_t *params); // destructor - virtual ~TGeoTube(); + ~TGeoTube() override; // methods - virtual Double_t Capacity() const; - static Double_t Capacity(Double_t rmin, Double_t rmax, Double_t dz); - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t rmin, Double_t rmax, Double_t dz); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz); - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static void DistToTube(Double_t rsq, Double_t nsq, Double_t rdotn, Double_t radius, Double_t &b, Double_t &delta); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual const char *GetAxisName(Int_t iaxis) const; - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 48;} - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual Double_t GetRmin() const {return fRmin;} - virtual Double_t GetRmax() const {return fRmax;} - virtual Double_t GetDz() const {return fDz;} - Bool_t HasRmin() const {return (fRmin>0)?kTRUE:kFALSE;} - virtual void InspectShape() const; - virtual Bool_t IsCylType() const {return kTRUE;} - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Double_t rmax, Double_t dz, Int_t skipz=0); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetTubeDimensions(Double_t rmin, Double_t rmax, Double_t dz); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoTube, 1) // cylindrical tube class - + Double_t Capacity() const override; + static Double_t Capacity(Double_t rmin, Double_t rmax, Double_t dz); + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t rmin, Double_t rmax, + Double_t dz); + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + static Double_t + DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t + DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz); + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static void DistToTube(Double_t rsq, Double_t nsq, Double_t rdotn, Double_t radius, Double_t &b, Double_t &delta); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + const char *GetAxisName(Int_t iaxis) const override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 48; } + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + virtual Double_t GetRmin() const { return fRmin; } + virtual Double_t GetRmax() const { return fRmax; } + virtual Double_t GetDz() const { return fDz; } + Bool_t HasRmin() const { return (fRmin > 0) ? kTRUE : kFALSE; } + void InspectShape() const override; + Bool_t IsCylType() const override { return kTRUE; } + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + static Double_t + SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Double_t rmax, Double_t dz, Int_t skipz = 0); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetTubeDimensions(Double_t rmin, Double_t rmax, Double_t dz); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; + + ClassDefOverride(TGeoTube, 1) // cylindrical tube class }; -class TGeoTubeSeg : public TGeoTube -{ +class TGeoTubeSeg : public TGeoTube { protected: // data members - Double_t fPhi1; // first phi limit - Double_t fPhi2; // second phi limit + Double_t fPhi1; // first phi limit + Double_t fPhi2; // second phi limit // Transient trigonometric data - Double_t fS1; // sin(phi1) - Double_t fC1; // cos(phi1) - Double_t fS2; // sin(phi2) - Double_t fC2; // cos(phi2) - Double_t fSm; // sin(0.5*(phi1+phi2)) - Double_t fCm; // cos(0.5*(phi1+phi2)) - Double_t fCdfi; // cos(0.5*(phi1-phi2)) + Double_t fS1; // sin(phi1) + Double_t fC1; // cos(phi1) + Double_t fS2; // sin(phi2) + Double_t fC2; // cos(phi2) + Double_t fSm; // sin(0.5*(phi1+phi2)) + Double_t fCm; // cos(0.5*(phi1+phi2)) + Double_t fCdfi; // cos(0.5*(phi1-phi2)) - void InitTrigonometry(); + void InitTrigonometry(); public: // constructors TGeoTubeSeg(); - TGeoTubeSeg(Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2); - TGeoTubeSeg(const char * name, Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2); + TGeoTubeSeg(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2); + TGeoTubeSeg(const char *name, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2); TGeoTubeSeg(Double_t *params); // destructor - virtual ~TGeoTubeSeg(); + ~TGeoTubeSeg() override; // methods - virtual void AfterStreamer(); - virtual Double_t Capacity() const; - static Double_t Capacity(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2); - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t rmin, Double_t rmax, Double_t dz, - Double_t c1, Double_t s1, Double_t c2, Double_t s2); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir,Double_t rmin, Double_t rmax, Double_t dz, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi); - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual void GetBoundingCylinder(Double_t *param) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 56;} - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual Int_t GetNmeshVertices() const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - Double_t GetPhi1() const {return fPhi1;} - Double_t GetPhi2() const {return fPhi2;} - virtual void InspectShape() const; - virtual TBuffer3D *MakeBuffer3D() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2, Int_t skipz=0); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetTubsDimensions(Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; - - ClassDef(TGeoTubeSeg, 2) // cylindrical tube segment class + void AfterStreamer() override; + Double_t Capacity() const override; + static Double_t Capacity(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2); + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + static void ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t rmin, Double_t rmax, + Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2); + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + static Double_t DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, + Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, + Double_t sm, Double_t cdfi); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + static Double_t DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, + Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, + Double_t sm, Double_t cdfi); + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + void GetBoundingCylinder(Double_t *param) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 56; } + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + Int_t GetNmeshVertices() const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Double_t GetPhi1() const { return fPhi1; } + Double_t GetPhi2() const { return fPhi2; } + void InspectShape() const override; + TBuffer3D *MakeBuffer3D() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + static Double_t SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, + Double_t phi2, Int_t skipz = 0); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetTubsDimensions(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; + + ClassDefOverride(TGeoTubeSeg, 2) // cylindrical tube segment class }; -class TGeoCtub : public TGeoTubeSeg -{ +class TGeoCtub : public TGeoTubeSeg { protected: // data members - Double_t fNlow[3]; // normal to lower cut plane - Double_t fNhigh[3]; // normal to higher cut plane + Double_t fNlow[3]; // normal to lower cut plane + Double_t fNhigh[3]; // normal to higher cut plane public: // constructors TGeoCtub(); - TGeoCtub(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); - TGeoCtub(const char *name, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); + TGeoCtub(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, Double_t lx, Double_t ly, + Double_t lz, Double_t tx, Double_t ty, Double_t tz); + TGeoCtub(const char *name, Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, Double_t lx, + Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); TGeoCtub(Double_t *params); // destructor - virtual ~TGeoCtub(); + ~TGeoCtub() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual TGeoVolume *Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step); - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const; - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual Int_t GetByteCount() const {return 98;} - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const; - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - const Double_t *GetNlow() const {return &fNlow[0];} - const Double_t *GetNhigh() const {return &fNhigh[0];} - Double_t GetZcoord(Double_t xc, Double_t yc, Double_t zc) const; - virtual void InspectShape() const; - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetCtubDimensions(Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2, Double_t lx, Double_t ly, Double_t lz, - Double_t tx, Double_t ty, Double_t tz); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - - ClassDef(TGeoCtub, 1) // cut tube segment class + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + TGeoVolume * + Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) override; + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override; + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + Int_t GetByteCount() const override { return 98; } + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override; + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override; + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + const Double_t *GetNlow() const { return &fNlow[0]; } + const Double_t *GetNhigh() const { return &fNhigh[0]; } + Double_t GetZcoord(Double_t xc, Double_t yc, Double_t zc) const; + void InspectShape() const override; + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetCtubDimensions(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, Double_t lx, + Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + + ClassDefOverride(TGeoCtub, 1) // cut tube segment class }; #endif diff --git a/geom/geom/inc/TGeoTypedefs.h b/geom/geom/inc/TGeoTypedefs.h index 4af53e6c1f872..c29f33febca72 100644 --- a/geom/geom/inc/TGeoTypedefs.h +++ b/geom/geom/inc/TGeoTypedefs.h @@ -17,8 +17,8 @@ namespace Tessellated { - using Vertex_t = ROOT::Geom::Vertex_t; - using VertexVec_t = std::vector; +using Vertex_t = ROOT::Geom::Vertex_t; +using VertexVec_t = std::vector; } // namespace Tessellated diff --git a/geom/geom/inc/TGeoVolume.h b/geom/geom/inc/TGeoVolume.h index 1c9e9461580af..70ad4ce4398e3 100644 --- a/geom/geom/inc/TGeoVolume.h +++ b/geom/geom/inc/TGeoVolume.h @@ -13,7 +13,6 @@ #ifndef ROOT_TGeoVolume #define ROOT_TGeoVolume - #include "TNamed.h" #include "TGeoAtt.h" #include "TAttLine.h" @@ -41,207 +40,220 @@ class TGeoExtension; // // //////////////////////////////////////////////////////////////////////////// -class TGeoVolume : public TNamed, - public TGeoAtt, - public TAttLine, - public TAttFill, - public TAtt3D -{ -protected : - TObjArray *fNodes; // array of nodes inside this volume - TGeoShape *fShape; // shape - TGeoMedium *fMedium; // tracking medium - static TGeoMedium *fgDummyMedium; //! dummy medium - TGeoPatternFinder *fFinder; // finder object for divisions - TGeoVoxelFinder *fVoxels; // finder object for bounding boxes - TGeoManager *fGeoManager; //! pointer to TGeoManager owning this volume - - TObject *fField; //! just a hook for now - TString fOption; //! option - if any - Int_t fNumber; // volume serial number in the list of volumes - Int_t fNtotal; // total number of physical nodes - Int_t fRefCount; // reference counter - TGeoExtension *fUserExtension; //! Transient user-defined extension to volumes - TGeoExtension *fFWExtension; //! Transient framework-defined extension to volumes +class TGeoVolume : public TNamed, public TGeoAtt, public TAttLine, public TAttFill, public TAtt3D { +protected: + TObjArray *fNodes; // array of nodes inside this volume + TGeoShape *fShape; // shape + TGeoMedium *fMedium; // tracking medium + static TGeoMedium *fgDummyMedium; //! dummy medium + TGeoPatternFinder *fFinder; // finder object for divisions + TGeoVoxelFinder *fVoxels; // finder object for bounding boxes + TGeoManager *fGeoManager; //! pointer to TGeoManager owning this volume + + TObject *fField; //! just a hook for now + TString fOption; //! option - if any + Int_t fNumber; // volume serial number in the list of volumes + Int_t fNtotal; // total number of physical nodes + Int_t fRefCount; // reference counter + Char_t fTransparency; // transparency setting + TGeoExtension *fUserExtension; //! Transient user-defined extension to volumes + TGeoExtension *fFWExtension; //! Transient framework-defined extension to volumes private: - TGeoVolume(const TGeoVolume&) = delete; - TGeoVolume& operator=(const TGeoVolume&) = delete; + TGeoVolume(const TGeoVolume &) = delete; + TGeoVolume &operator=(const TGeoVolume &) = delete; public: - virtual void ClearThreadData() const; - virtual void CreateThreadData(Int_t nthreads); + virtual void ClearThreadData() const; + virtual void CreateThreadData(Int_t nthreads); public: enum EGeoVolumeTypes { - kVolumeReplicated = BIT(14), - kVolumeSelected = BIT(15), - kVolumeDiv = BIT(16), - kVolumeOverlap = BIT(17), + kVolumeReplicated = BIT(14), + kVolumeSelected = BIT(15), + kVolumeDiv = BIT(16), + kVolumeOverlap = BIT(17), kVolumeImportNodes = BIT(18), - kVolumeMulti = BIT(19), - kVoxelsXYZ = BIT(20), // not used - kVoxelsCyl = BIT(21), // not used - kVolumeClone = BIT(22), - kVolumeAdded = BIT(23), - kVolumeOC = BIT(21) // overlapping candidates + kVolumeMulti = BIT(19), + kVoxelsXYZ = BIT(20), // not used + kVoxelsCyl = BIT(21), // not used + kVolumeClone = BIT(22), + kVolumeAdded = BIT(23), + kVolumeOC = BIT(21) // overlapping candidates }; // constructors TGeoVolume(); - TGeoVolume(const char *name, const TGeoShape *shape, const TGeoMedium *med=nullptr); + TGeoVolume(const char *name, const TGeoShape *shape, const TGeoMedium *med = nullptr); // destructor - virtual ~TGeoVolume(); + ~TGeoVolume() override; // methods - virtual void cd(Int_t inode) const; - void Browse(TBrowser *b); - Double_t Capacity() const; - void CheckShapes(); - void ClearNodes() {fNodes = nullptr;} - void ClearShape(); - void CleanAll(); + virtual void cd(Int_t inode) const; + void Browse(TBrowser *b) override; + Double_t Capacity() const; + void CheckShapes(); + void ClearNodes() { fNodes = nullptr; } + void ClearShape(); + void CleanAll(); virtual TGeoVolume *CloneVolume() const; - void CloneNodesAndConnect(TGeoVolume *newmother) const; - void CheckGeometry(Int_t nrays=1, Double_t startx=0, Double_t starty=0, Double_t startz=0) const; - void CheckOverlaps(Double_t ovlp=0.1, Option_t *option="") const; // *MENU* - void CheckShape(Int_t testNo, Int_t nsamples=10000, Option_t *option=""); // *MENU* - Int_t CountNodes(Int_t nlevels=1000, Int_t option=0); - Bool_t Contains(const Double_t *point) const {return fShape->Contains(point);} - static void CreateDummyMedium(); + void CloneNodesAndConnect(TGeoVolume *newmother) const; + void CheckGeometry(Int_t nrays = 1, Double_t startx = 0, Double_t starty = 0, Double_t startz = 0) const; + void CheckOverlaps(Double_t ovlp = 0.1, Option_t *option = "") const; // *MENU* + void CheckShape(Int_t testNo, Int_t nsamples = 10000, Option_t *option = ""); // *MENU* + Int_t CountNodes(Int_t nlevels = 1000, Int_t option = 0); + Bool_t Contains(const Double_t *point) const { return fShape->Contains(point); } + static void CreateDummyMedium(); static TGeoMedium *DummyMedium(); - virtual Bool_t IsAssembly() const; - virtual Bool_t IsFolder() const; - Bool_t IsRunTime() const {return fShape->IsRunTimeShape();} - virtual Bool_t IsVolumeMulti() const {return kFALSE;} + virtual Bool_t IsAssembly() const; + Bool_t IsFolder() const override; + Bool_t IsRunTime() const { return fShape->IsRunTimeShape(); } + virtual Bool_t IsVolumeMulti() const { return kFALSE; } virtual TGeoNode * AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat = nullptr, Option_t *option = ""); // most general case - void AddNodeOffset(TGeoVolume *vol, Int_t copy_no, Double_t offset=0, Option_t *option=""); - virtual void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat=nullptr, Option_t *option=""); - - virtual TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed=0, Option_t *option=""); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void Draw(Option_t *option=""); // *MENU* - virtual void DrawOnly(Option_t *option=""); // *MENU* - TH2F *LegoPlot(Int_t ntheta=20, Double_t themin=0., Double_t themax=180., - Int_t nphi=60, Double_t phimin=0., Double_t phimax=360., - Double_t rmin=0., Double_t rmax=9999999, Option_t *option=""); // *MENU* - virtual void Paint(Option_t *option=""); - virtual void Print(Option_t *option="") const; // *MENU* - void PrintNodes() const; - void PrintVoxels() const; // *MENU* - void ReplayCreation(const TGeoVolume *other); - void SetUserExtension(TGeoExtension *ext); - void SetFWExtension(TGeoExtension *ext); - Int_t GetRefCount() const {return fRefCount;} - TGeoExtension *GetUserExtension() const {return fUserExtension;} - TGeoExtension *GetFWExtension() const {return fFWExtension;} - TGeoExtension *GrabUserExtension() const; - TGeoExtension *GrabFWExtension() const; - void Grab() {fRefCount++;} - void Release() {fRefCount--; if (fRefCount==0) delete this;} - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - - Bool_t IsActive() const {return TGeoAtt::IsActive();} - Bool_t IsActiveDaughters() const {return TGeoAtt::IsActiveDaughters();} - Bool_t IsAdded() const {return TObject::TestBit(kVolumeAdded);} - Bool_t IsOverlappingCandidate() const {return TObject::TestBit(kVolumeOC);} - Bool_t IsReplicated() const {return TObject::TestBit(kVolumeReplicated);} - Bool_t IsSelected() const {return TObject::TestBit(kVolumeSelected);} - Bool_t IsCylVoxels() const {return TObject::TestBit(kVoxelsCyl);} - Bool_t IsXYZVoxels() const {return TObject::TestBit(kVoxelsXYZ);} - Bool_t IsTopVolume() const; - Bool_t IsValid() const {return fShape->IsValid();} - virtual Bool_t IsVisible() const {return TGeoAtt::IsVisible();} - Bool_t IsVisibleDaughters() const {return TGeoAtt::IsVisDaughters();} - Bool_t IsVisContainers() const {return TGeoAtt::IsVisContainers();} - Bool_t IsVisLeaves() const {return TGeoAtt::IsVisLeaves();} - Bool_t IsVisOnly() const {return TGeoAtt::IsVisOnly();} - Bool_t IsAllInvisible() const; - Bool_t IsRaytracing() const; - static TGeoVolume *Import(const char *filename, const char *name="", Option_t *option=""); - Int_t Export(const char *filename, const char *name="", Option_t *option=""); - TGeoNode *FindNode(const char *name) const; - void FindOverlaps() const; - Bool_t FindMatrixOfDaughterVolume(TGeoVolume *vol) const; - virtual Int_t GetCurrentNodeIndex() const {return -1;} - virtual Int_t GetNextNodeIndex() const {return -1;} - TObjArray *GetNodes() {return fNodes;} - Int_t GetNdaughters() const; - Int_t GetNtotal() const {return fNtotal;} - virtual Int_t GetByteCount() const; - TGeoManager *GetGeoManager() const {return fGeoManager;} - TGeoMaterial *GetMaterial() const {return GetMedium()->GetMaterial();} - TGeoMedium *GetMedium() const {return (fMedium)?fMedium:DummyMedium();} - TObject *GetField() const {return fField;} - TGeoPatternFinder *GetFinder() const {return fFinder;} - TGeoVoxelFinder *GetVoxels() const; - const char *GetIconName() const {return fShape->GetName();} - Int_t GetIndex(const TGeoNode *node) const; - TGeoNode *GetNode(const char *name) const; - TGeoNode *GetNode(Int_t i) const {return (TGeoNode*)fNodes->UncheckedAt(i);} - Int_t GetNodeIndex(const TGeoNode *node, Int_t *check_list, Int_t ncheck) const; - Int_t GetNumber() const {return fNumber;} - virtual char *GetObjectInfo(Int_t px, Int_t py) const; - Bool_t GetOptimalVoxels() const; - Option_t *GetOption() const { return fOption.Data(); } - const char *GetPointerName() const; - Char_t GetTransparency() const { return !fMedium ? 0 : fMedium->GetMaterial()->GetTransparency(); } - TGeoShape *GetShape() const {return fShape;} - void GrabFocus(); // *MENU* - void Gsord(Int_t /*iaxis*/) {} - Bool_t IsStyleDefault() const; - void InspectMaterial() const; // *MENU* - void InspectShape() const {fShape->InspectShape();} // *MENU* + void AddNodeOffset(TGeoVolume *vol, Int_t copy_no, Double_t offset = 0, Option_t *option = ""); + virtual void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat = nullptr, Option_t *option = ""); + + virtual TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, + Int_t numed = 0, Option_t *option = ""); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *option = "") override; // *MENU* + virtual void DrawOnly(Option_t *option = ""); // *MENU* + TH2F *LegoPlot(Int_t ntheta = 20, Double_t themin = 0., Double_t themax = 180., Int_t nphi = 60, + Double_t phimin = 0., Double_t phimax = 360., Double_t rmin = 0., Double_t rmax = 9999999, + Option_t *option = ""); // *MENU* + void Paint(Option_t *option = "") override; + void Print(Option_t *option = "") const override; // *MENU* + void PrintNodes() const; + void PrintVoxels() const; // *MENU* + void ReplayCreation(const TGeoVolume *other); + void SetUserExtension(TGeoExtension *ext); + void SetFWExtension(TGeoExtension *ext); + Int_t GetRefCount() const { return fRefCount; } + TGeoExtension *GetUserExtension() const { return fUserExtension; } + TGeoExtension *GetFWExtension() const { return fFWExtension; } + TGeoExtension *GrabUserExtension() const; + TGeoExtension *GrabFWExtension() const; + void Grab() { fRefCount++; } + void Release() + { + fRefCount--; + if (fRefCount == 0) + delete this; + } + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + + Bool_t IsActive() const { return TGeoAtt::IsActive(); } + Bool_t IsActiveDaughters() const { return TGeoAtt::IsActiveDaughters(); } + Bool_t IsAdded() const { return TObject::TestBit(kVolumeAdded); } + Bool_t IsOverlappingCandidate() const { return TObject::TestBit(kVolumeOC); } + Bool_t IsReplicated() const { return TObject::TestBit(kVolumeReplicated); } + Bool_t IsSelected() const { return TObject::TestBit(kVolumeSelected); } + Bool_t IsCylVoxels() const { return TObject::TestBit(kVoxelsCyl); } + Bool_t IsXYZVoxels() const { return TObject::TestBit(kVoxelsXYZ); } + Bool_t IsTopVolume() const; + Bool_t IsValid() const { return fShape->IsValid(); } + virtual Bool_t IsVisible() const { return TGeoAtt::IsVisible(); } + Bool_t IsVisibleDaughters() const { return TGeoAtt::IsVisDaughters(); } + Bool_t IsVisContainers() const { return TGeoAtt::IsVisContainers(); } + Bool_t IsVisLeaves() const { return TGeoAtt::IsVisLeaves(); } + Bool_t IsVisOnly() const { return TGeoAtt::IsVisOnly(); } + Bool_t IsAllInvisible() const; + Bool_t IsRaytracing() const; + static TGeoVolume *Import(const char *filename, const char *name = "", Option_t *option = ""); + Int_t Export(const char *filename, const char *name = "", Option_t *option = ""); + TGeoNode *FindNode(const char *name) const; + void FindOverlaps() const; + Bool_t FindMatrixOfDaughterVolume(TGeoVolume *vol) const; + virtual Int_t GetCurrentNodeIndex() const { return -1; } + virtual Int_t GetNextNodeIndex() const { return -1; } + TObjArray *GetNodes() { return fNodes; } + Int_t GetNdaughters() const; + Int_t GetNtotal() const { return fNtotal; } + virtual Int_t GetByteCount() const; + TGeoManager *GetGeoManager() const { return fGeoManager; } + TGeoMaterial *GetMaterial() const { return GetMedium()->GetMaterial(); } + TGeoMedium *GetMedium() const { return (fMedium) ? fMedium : DummyMedium(); } + TObject *GetField() const { return fField; } + TGeoPatternFinder *GetFinder() const { return fFinder; } + TGeoVoxelFinder *GetVoxels() const; + const char *GetIconName() const override { return fShape->GetName(); } + Int_t GetIndex(const TGeoNode *node) const; + TGeoNode *GetNode(const char *name) const; + TGeoNode *GetNode(Int_t i) const { return (TGeoNode *)fNodes->UncheckedAt(i); } + Int_t GetNodeIndex(const TGeoNode *node, Int_t *check_list, Int_t ncheck) const; + Int_t GetNumber() const { return fNumber; } + char *GetObjectInfo(Int_t px, Int_t py) const override; + Bool_t GetOptimalVoxels() const; + Option_t *GetOption() const override { return fOption.Data(); } + const char *GetPointerName() const; + Char_t GetTransparency() const; + TGeoShape *GetShape() const { return fShape; } + void GrabFocus(); // *MENU* + void Gsord(Int_t /*iaxis*/) {} + Bool_t IsStyleDefault() const; + void InspectMaterial() const; // *MENU* + void InspectShape() const { fShape->InspectShape(); } // *MENU* virtual TGeoVolume *MakeCopyVolume(TGeoShape *newshape); - void MakeCopyNodes(const TGeoVolume *other); - TGeoVolume *MakeReflectedVolume(const char *newname="") const; - Bool_t OptimizeVoxels(); // *MENU* - void RandomPoints(Int_t npoints=1000000, Option_t *option=""); // *MENU* - void RandomRays(Int_t nrays=10000, Double_t startx=0, Double_t starty=0, Double_t startz=0, const char *target_vol=nullptr, Bool_t check_norm=kFALSE); // *MENU* - void Raytrace(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsRaytracing - void RegisterYourself(Option_t *option=""); - void RemoveNode(TGeoNode *node); - TGeoNode *ReplaceNode(TGeoNode *nodeorig, TGeoShape *newshape=nullptr, TGeoMatrix *newpos=nullptr, TGeoMedium *newmed=nullptr); - void SaveAs(const char *filename,Option_t *option="") const; // *MENU* - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SelectVolume(Bool_t clear = kFALSE); - void SetActivity(Bool_t flag=kTRUE) {TGeoAtt::SetActivity(flag);} - void SetActiveDaughters(Bool_t flag=kTRUE) {TGeoAtt::SetActiveDaughters(flag);} - void SetAsTopVolume(); // *TOGGLE* *GETTER=IsTopVolume - void SetAdded() {TObject::SetBit(kVolumeAdded);} - void SetReplicated() {TObject::SetBit(kVolumeReplicated);} - void SetCurrentPoint(Double_t x, Double_t y, Double_t z); - void SetCylVoxels(Bool_t flag=kTRUE) {TObject::SetBit(kVoxelsCyl, flag); TObject::SetBit(kVoxelsXYZ, !flag);} - void SetNodes(TObjArray *nodes) {fNodes = nodes; TObject::SetBit(kVolumeImportNodes);} - void SetOverlappingCandidate(Bool_t flag) {TObject::SetBit(kVolumeOC,flag);} - void SetShape(const TGeoShape *shape); - void SetTransparency(Char_t transparency=0) {if (fMedium) fMedium->GetMaterial()->SetTransparency(transparency);} // *MENU* - void SetField(TObject *field) {fField = field;} - void SetOption(const char *option); - void SetAttVisibility(Bool_t vis) {TGeoAtt::SetVisibility(vis);} - virtual void SetVisibility(Bool_t vis=kTRUE); // *TOGGLE* *GETTER=IsVisible - virtual void SetVisContainers(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsVisContainers - virtual void SetVisLeaves(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsVisLeaves - virtual void SetVisOnly(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsVisOnly - virtual void SetLineColor(Color_t lcolor); - virtual void SetLineStyle(Style_t lstyle); - virtual void SetLineWidth(Width_t lwidth); - void SetInvisible() {SetVisibility(kFALSE);} - virtual void SetMedium(TGeoMedium *medium) {fMedium = medium;} - void SetVoxelFinder(TGeoVoxelFinder *finder) {fVoxels = finder;} - void SetFinder(TGeoPatternFinder *finder) {fFinder = finder;} - void SetNumber(Int_t number) {fNumber = number;} - void SetNtotal(Int_t ntotal) {fNtotal = ntotal;} - void SortNodes(); - void UnmarkSaved(); - Bool_t Valid() const; - void VisibleDaughters(Bool_t vis=kTRUE); // *TOGGLE* *GETTER=IsVisibleDaughters - void InvisibleAll(Bool_t flag=kTRUE); // *TOGGLE* *GETTER=IsAllInvisible - void Voxelize(Option_t *option); - Double_t Weight(Double_t precision=0.01, Option_t *option="va"); // *MENU* - Double_t WeightA() const; - - ClassDef(TGeoVolume, 6) // geometry volume descriptor + void MakeCopyNodes(const TGeoVolume *other); + TGeoVolume *MakeReflectedVolume(const char *newname = "") const; + Bool_t OptimizeVoxels(); // *MENU* + void RandomPoints(Int_t npoints = 1000000, Option_t *option = ""); // *MENU* + void RandomRays(Int_t nrays = 10000, Double_t startx = 0, Double_t starty = 0, Double_t startz = 0, + const char *target_vol = nullptr, Bool_t check_norm = kFALSE); // *MENU* + void Raytrace(Bool_t flag = kTRUE); // *TOGGLE* *GETTER=IsRaytracing + void RegisterYourself(Option_t *option = ""); + void RemoveNode(TGeoNode *node); + TGeoNode *ReplaceNode(TGeoNode *nodeorig, TGeoShape *newshape = nullptr, TGeoMatrix *newpos = nullptr, + TGeoMedium *newmed = nullptr); + void ResetTransparency(Char_t transparency = -1); // *MENU* + void SaveAs(const char *filename, Option_t *option = "") const override; // *MENU* + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SelectVolume(Bool_t clear = kFALSE); + void SetActivity(Bool_t flag = kTRUE) { TGeoAtt::SetActivity(flag); } + void SetActiveDaughters(Bool_t flag = kTRUE) { TGeoAtt::SetActiveDaughters(flag); } + void SetAsTopVolume(); // *TOGGLE* *GETTER=IsTopVolume + void SetAdded() { TObject::SetBit(kVolumeAdded); } + void SetReplicated() { TObject::SetBit(kVolumeReplicated); } + void SetCurrentPoint(Double_t x, Double_t y, Double_t z); + void SetCylVoxels(Bool_t flag = kTRUE) + { + TObject::SetBit(kVoxelsCyl, flag); + TObject::SetBit(kVoxelsXYZ, !flag); + } + void SetNodes(TObjArray *nodes) + { + fNodes = nodes; + TObject::SetBit(kVolumeImportNodes); + } + void SetOverlappingCandidate(Bool_t flag) { TObject::SetBit(kVolumeOC, flag); } + void SetShape(const TGeoShape *shape); + void SetTransparency(Char_t transparency = 0); // *MENU* + void SetField(TObject *field) { fField = field; } + void SetOption(const char *option); + void SetAttVisibility(Bool_t vis) { TGeoAtt::SetVisibility(vis); } + void SetVisibility(Bool_t vis = kTRUE) override; // *TOGGLE* *GETTER=IsVisible + void SetVisContainers(Bool_t flag = kTRUE) override; // *TOGGLE* *GETTER=IsVisContainers + void SetVisLeaves(Bool_t flag = kTRUE) override; // *TOGGLE* *GETTER=IsVisLeaves + void SetVisOnly(Bool_t flag = kTRUE) override; // *TOGGLE* *GETTER=IsVisOnly + void SetLineColor(Color_t lcolor) override; + void SetLineStyle(Style_t lstyle) override; + void SetLineWidth(Width_t lwidth) override; + void SetInvisible() { SetVisibility(kFALSE); } + virtual void SetMedium(TGeoMedium *medium) { fMedium = medium; } + void SetVoxelFinder(TGeoVoxelFinder *finder) { fVoxels = finder; } + void SetFinder(TGeoPatternFinder *finder) { fFinder = finder; } + void SetNumber(Int_t number) { fNumber = number; } + void SetNtotal(Int_t ntotal) { fNtotal = ntotal; } + void SortNodes(); + void UnmarkSaved(); + Bool_t Valid() const; + void VisibleDaughters(Bool_t vis = kTRUE); // *TOGGLE* *GETTER=IsVisibleDaughters + void InvisibleAll(Bool_t flag = kTRUE); // *TOGGLE* *GETTER=IsAllInvisible + void Voxelize(Option_t *option); + Double_t Weight(Double_t precision = 0.01, Option_t *option = "va"); // *MENU* + Double_t WeightA() const; + + ClassDefOverride(TGeoVolume, 7) // geometry volume descriptor }; //////////////////////////////////////////////////////////////////////////// @@ -251,47 +263,47 @@ protected : // // //////////////////////////////////////////////////////////////////////////// -class TGeoVolumeMulti : public TGeoVolume -{ +class TGeoVolumeMulti : public TGeoVolume { private: - TObjArray *fVolumes; // list of volumes - TGeoVolumeMulti *fDivision; // division of this volume - Int_t fNumed; // medium number for divisions - Int_t fNdiv; // number of divisions - Int_t fAxis; // axis of division - Double_t fStart; // division start offset - Double_t fStep; // division step - Bool_t fAttSet; // flag attributes set - - TGeoVolumeMulti(const TGeoVolumeMulti&) = delete; - TGeoVolumeMulti& operator=(const TGeoVolumeMulti&) = delete; + TObjArray *fVolumes; // list of volumes + TGeoVolumeMulti *fDivision; // division of this volume + Int_t fNumed; // medium number for divisions + Int_t fNdiv; // number of divisions + Int_t fAxis; // axis of division + Double_t fStart; // division start offset + Double_t fStep; // division step + Bool_t fAttSet; // flag attributes set + + TGeoVolumeMulti(const TGeoVolumeMulti &) = delete; + TGeoVolumeMulti &operator=(const TGeoVolumeMulti &) = delete; public: TGeoVolumeMulti(); - TGeoVolumeMulti(const char* name, TGeoMedium *med=nullptr); - virtual ~TGeoVolumeMulti(); - - void AddVolume(TGeoVolume *vol); - TGeoVolume *GetVolume(Int_t id) const {return (TGeoVolume*)fVolumes->At(id);} - virtual TGeoNode * - AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option = ""); // most general case - virtual void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option=""); - virtual TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed=0, Option_t *option=""); - TGeoShape *GetLastShape() const; - Int_t GetNvolumes() const {return fVolumes->GetEntriesFast();} - Int_t GetAxis() const {return fNdiv;} - Int_t GetNdiv() const {return fNdiv;} - Double_t GetStart() const {return fStart;} - Double_t GetStep() const {return fStep;} - virtual Bool_t IsVolumeMulti() const {return kTRUE;} - virtual TGeoVolume *MakeCopyVolume(TGeoShape *newshape); - virtual void SetLineColor(Color_t lcolor); - virtual void SetLineStyle(Style_t lstyle); - virtual void SetLineWidth(Width_t lwidth); - virtual void SetMedium(TGeoMedium *medium); - virtual void SetVisibility(Bool_t vis=kTRUE); - - ClassDef(TGeoVolumeMulti, 3) // class to handle multiple volumes in one step + TGeoVolumeMulti(const char *name, TGeoMedium *med = nullptr); + ~TGeoVolumeMulti() override; + + void AddVolume(TGeoVolume *vol); + TGeoVolume *GetVolume(Int_t id) const { return (TGeoVolume *)fVolumes->At(id); } + TGeoNode * + AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option = "") override; // most general case + void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option = "") override; + TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed = 0, + Option_t *option = "") override; + TGeoShape *GetLastShape() const; + Int_t GetNvolumes() const { return fVolumes->GetEntriesFast(); } + Int_t GetAxis() const { return fNdiv; } + Int_t GetNdiv() const { return fNdiv; } + Double_t GetStart() const { return fStart; } + Double_t GetStep() const { return fStep; } + Bool_t IsVolumeMulti() const override { return kTRUE; } + TGeoVolume *MakeCopyVolume(TGeoShape *newshape) override; + void SetLineColor(Color_t lcolor) override; + void SetLineStyle(Style_t lstyle) override; + void SetLineWidth(Width_t lwidth) override; + void SetMedium(TGeoMedium *medium) override; + void SetVisibility(Bool_t vis = kTRUE) override; + + ClassDefOverride(TGeoVolumeMulti, 3) // class to handle multiple volumes in one step }; //////////////////////////////////////////////////////////////////////////// @@ -301,54 +313,76 @@ class TGeoVolumeMulti : public TGeoVolume // // //////////////////////////////////////////////////////////////////////////// -class TGeoVolumeAssembly : public TGeoVolume -{ +class TGeoVolumeAssembly : public TGeoVolume { public: - struct ThreadData_t - { - Int_t fCurrent; //! index of current selected node - Int_t fNext; //! index of next node to be entered + struct ThreadData_t { + Int_t fCurrent; //! index of current selected node + Int_t fNext; //! index of next node to be entered ThreadData_t(); ~ThreadData_t(); }; - ThreadData_t& GetThreadData() const; - virtual void ClearThreadData() const; - virtual void CreateThreadData(Int_t nthreads); + ThreadData_t &GetThreadData() const; + void ClearThreadData() const override; + void CreateThreadData(Int_t nthreads) override; protected: - mutable std::vector fThreadData; //! Thread specific data vector - mutable Int_t fThreadSize; //! Thread vector size - mutable std::mutex fMutex; //! Mutex for concurrent operations + mutable std::vector fThreadData; //! Thread specific data vector + mutable Int_t fThreadSize; //! Thread vector size + mutable std::mutex fMutex; //! Mutex for concurrent operations private: TGeoVolumeAssembly(const TGeoVolumeAssembly &) = delete; - TGeoVolumeAssembly& operator=(const TGeoVolumeAssembly&) = delete; + TGeoVolumeAssembly &operator=(const TGeoVolumeAssembly &) = delete; public: TGeoVolumeAssembly(); TGeoVolumeAssembly(const char *name); - virtual ~TGeoVolumeAssembly(); - - virtual TGeoNode *AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat = nullptr, Option_t *option = ""); - virtual void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option); - virtual TGeoVolume *CloneVolume() const; - virtual TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed=0, Option_t *option=""); - TGeoVolume *Divide(TGeoVolume *cell, TGeoPatternFinder *pattern, Option_t *option="spacedout"); - virtual void DrawOnly(Option_t *) {} - virtual Int_t GetCurrentNodeIndex() const; - virtual Int_t GetNextNodeIndex() const; - virtual Bool_t IsAssembly() const {return kTRUE;} - virtual Bool_t IsVisible() const {return kFALSE;} + ~TGeoVolumeAssembly() override; + + TGeoNode *AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat = nullptr, Option_t *option = "") override; + void AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option) override; + TGeoVolume *CloneVolume() const override; + TGeoVolume *Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed = 0, + Option_t *option = "") override; + TGeoVolume *Divide(TGeoVolume *cell, TGeoPatternFinder *pattern, Option_t *option = "spacedout"); + void DrawOnly(Option_t *) override {} + Int_t GetCurrentNodeIndex() const override; + Int_t GetNextNodeIndex() const override; + Bool_t IsAssembly() const override { return kTRUE; } + Bool_t IsVisible() const override { return kFALSE; } static TGeoVolumeAssembly *MakeAssemblyFromVolume(TGeoVolume *vol); - void SetCurrentNodeIndex(Int_t index); - void SetNextNodeIndex(Int_t index); + void SetCurrentNodeIndex(Int_t index); + void SetNextNodeIndex(Int_t index); - ClassDef(TGeoVolumeAssembly, 2) // an assembly of volumes + ClassDefOverride(TGeoVolumeAssembly, 2) // an assembly of volumes }; -inline Int_t TGeoVolume::GetNdaughters() const {if (!fNodes) return 0; return (fNodes->GetEntriesFast());} +inline Int_t TGeoVolume::GetNdaughters() const +{ + if (!fNodes) + return 0; + return (fNodes->GetEntriesFast()); +} -#endif +inline Char_t TGeoVolume::GetTransparency() const +{ + // If the transparency is (-1), the old default handling is applied + if ( fTransparency >= 0 ) return fTransparency; + return !fMedium ? 0 : fMedium->GetMaterial()->GetTransparency(); +} +inline void TGeoVolume::SetTransparency(Char_t transparency) +{ + if (fMedium) { + fMedium->GetMaterial()->SetTransparency(transparency); + } +} + +inline void TGeoVolume::ResetTransparency(Char_t transparency) +{ + fTransparency = transparency; +} + +#endif diff --git a/geom/geom/inc/TGeoVoxelFinder.h b/geom/geom/inc/TGeoVoxelFinder.h index df70728950994..b0fd0ba2cd26f 100644 --- a/geom/geom/inc/TGeoVoxelFinder.h +++ b/geom/geom/inc/TGeoVoxelFinder.h @@ -17,103 +17,99 @@ class TGeoVolume; struct TGeoStateInfo; -class TGeoVoxelFinder : public TObject -{ +class TGeoVoxelFinder : public TObject { public: -enum EVoxelsType { - kGeoInvalidVoxels = BIT(15), - kGeoRebuildVoxels = BIT(16) -}; + enum EVoxelsType { kGeoInvalidVoxels = BIT(15), kGeoRebuildVoxels = BIT(16) }; private: - TGeoVoxelFinder(const TGeoVoxelFinder&) = delete; - TGeoVoxelFinder& operator=(const TGeoVoxelFinder&) = delete; + TGeoVoxelFinder(const TGeoVoxelFinder &) = delete; + TGeoVoxelFinder &operator=(const TGeoVoxelFinder &) = delete; protected: - TGeoVolume *fVolume; // volume to which applies + TGeoVolume *fVolume; // volume to which applies + + Int_t fIbx; // number of different boundaries on X axis + Int_t fIby; // number of different boundaries on Y axis + Int_t fIbz; // number of different boundaries on Z axis + Int_t fNboxes; // length of boxes array + Int_t fNox; // length of array of X offsets + Int_t fNoy; // length of array of Y offsets + Int_t fNoz; // length of array of Z offsets + Int_t fNex; // length of array of X extra offsets + Int_t fNey; // length of array of Y extra offsets + Int_t fNez; // length of array of Z extra offsets + Int_t fNx; // length of array of X voxels + Int_t fNy; // length of array of Y voxels + Int_t fNz; // length of array of Z voxels + Int_t fPriority[3]; // priority for each axis + Double_t *fBoxes; //[fNboxes] list of bounding boxes + Double_t *fXb; //[fIbx] ordered array of X box boundaries + Double_t *fYb; //[fIby] ordered array of Y box boundaries + Double_t *fZb; //[fIbz] ordered array of Z box boundaries + Int_t *fOBx; //[fNox] offsets of daughter indices for slices X + Int_t *fOBy; //[fNoy] offsets of daughter indices for slices Y + Int_t *fOBz; //[fNoz] offsets of daughter indices for slices Z + Int_t *fOEx; //[fNox] offsets of extra indices for slices X + Int_t *fOEy; //[fNoy] offsets of extra indices for slices Y + Int_t *fOEz; //[fNoz] offsets of extra indices for slices Z + Int_t *fExtraX; //[fNex] indices of extra daughters in X slices + Int_t *fExtraY; //[fNey] indices of extra daughters in Y slices + Int_t *fExtraZ; //[fNez] indices of extra daughters in Z slices + Int_t *fNsliceX; //[fNox] number of candidates in X slice + Int_t *fNsliceY; //[fNoy] number of candidates in Y slice + Int_t *fNsliceZ; //[fNoz] number of candidates in Z slice + UChar_t *fIndcX; //[fNx] array of slices bits on X + UChar_t *fIndcY; //[fNy] array of slices bits on Y + UChar_t *fIndcZ; //[fNz] array of slices bits on Z - Int_t fIbx; // number of different boundaries on X axis - Int_t fIby; // number of different boundaries on Y axis - Int_t fIbz; // number of different boundaries on Z axis - Int_t fNboxes; // length of boxes array - Int_t fNox; // length of array of X offsets - Int_t fNoy; // length of array of Y offsets - Int_t fNoz; // length of array of Z offsets - Int_t fNex; // length of array of X extra offsets - Int_t fNey; // length of array of Y extra offsets - Int_t fNez; // length of array of Z extra offsets - Int_t fNx; // length of array of X voxels - Int_t fNy; // length of array of Y voxels - Int_t fNz; // length of array of Z voxels - Int_t fPriority[3]; // priority for each axis - Double_t *fBoxes; //[fNboxes] list of bounding boxes - Double_t *fXb; //[fIbx] ordered array of X box boundaries - Double_t *fYb; //[fIby] ordered array of Y box boundaries - Double_t *fZb; //[fIbz] ordered array of Z box boundaries - Int_t *fOBx; //[fNox] offsets of daughter indices for slices X - Int_t *fOBy; //[fNoy] offsets of daughter indices for slices Y - Int_t *fOBz; //[fNoz] offsets of daughter indices for slices Z - Int_t *fOEx; //[fNox] offsets of extra indices for slices X - Int_t *fOEy; //[fNoy] offsets of extra indices for slices Y - Int_t *fOEz; //[fNoz] offsets of extra indices for slices Z - Int_t *fExtraX; //[fNex] indices of extra daughters in X slices - Int_t *fExtraY; //[fNey] indices of extra daughters in Y slices - Int_t *fExtraZ; //[fNez] indices of extra daughters in Z slices - Int_t *fNsliceX; //[fNox] number of candidates in X slice - Int_t *fNsliceY; //[fNoy] number of candidates in Y slice - Int_t *fNsliceZ; //[fNoz] number of candidates in Z slice - UChar_t *fIndcX; //[fNx] array of slices bits on X - UChar_t *fIndcY; //[fNy] array of slices bits on Y - UChar_t *fIndcZ; //[fNz] array of slices bits on Z + void BuildVoxelLimits(); + Int_t *GetExtraX(Int_t islice, Bool_t left, Int_t &nextra) const; + Int_t *GetExtraY(Int_t islice, Bool_t left, Int_t &nextra) const; + Int_t *GetExtraZ(Int_t islice, Bool_t left, Int_t &nextra) const; + Bool_t GetIndices(const Double_t *point, TGeoStateInfo &td); + Int_t GetPriority(Int_t iaxis) const { return fPriority[iaxis]; } + Int_t GetNcandidates(TGeoStateInfo &td) const; + Int_t *GetValidExtra(Int_t *list, Int_t &ncheck, TGeoStateInfo &td); + Int_t *GetValidExtra(Int_t n1, UChar_t *array1, Int_t *list, Int_t &ncheck, TGeoStateInfo &td); + Int_t * + GetValidExtra(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t *list, Int_t &ncheck, TGeoStateInfo &td); + Int_t *GetVoxelCandidates(Int_t i, Int_t j, Int_t k, Int_t &ncheck, TGeoStateInfo &td); + Bool_t Intersect(Int_t n1, UChar_t *array1, Int_t &nf, Int_t *result); + Bool_t Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t &nf, Int_t *result); + Bool_t + Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t n3, UChar_t *array3, Int_t &nf, Int_t *result); + Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, TGeoStateInfo &td); + Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, TGeoStateInfo &td); + Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t n3, UChar_t *array3, + TGeoStateInfo &td); + void SortAll(Option_t *option = ""); + Bool_t Union(Int_t n1, UChar_t *array1, TGeoStateInfo &td); + Bool_t Union(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, TGeoStateInfo &td); + Bool_t Union(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t n3, UChar_t *array3, TGeoStateInfo &td); - void BuildVoxelLimits(); - Int_t *GetExtraX(Int_t islice, Bool_t left, Int_t &nextra) const; - Int_t *GetExtraY(Int_t islice, Bool_t left, Int_t &nextra) const; - Int_t *GetExtraZ(Int_t islice, Bool_t left, Int_t &nextra) const; - Bool_t GetIndices(const Double_t *point, TGeoStateInfo &td); - Int_t GetPriority(Int_t iaxis) const {return fPriority[iaxis];} - Int_t GetNcandidates( TGeoStateInfo &td) const; - Int_t *GetValidExtra(Int_t *list, Int_t &ncheck, TGeoStateInfo &td); - Int_t *GetValidExtra(Int_t n1, UChar_t *array1, Int_t *list, Int_t &ncheck, TGeoStateInfo &td); - Int_t *GetValidExtra(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t *list, Int_t &ncheck, TGeoStateInfo &td); - Int_t *GetVoxelCandidates(Int_t i, Int_t j, Int_t k, Int_t &ncheck, TGeoStateInfo &td); - Bool_t Intersect(Int_t n1, UChar_t *array1, Int_t &nf, Int_t *result); - Bool_t Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, - Int_t &nf, Int_t *result); - Bool_t Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, - Int_t n3, UChar_t *array3, Int_t &nf, Int_t *result); - Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, TGeoStateInfo &td); - Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, TGeoStateInfo &td); - Bool_t IntersectAndStore(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, - Int_t n3, UChar_t *array3, TGeoStateInfo &td); - void SortAll(Option_t *option=""); - Bool_t Union(Int_t n1, UChar_t *array1, TGeoStateInfo &td); - Bool_t Union(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, TGeoStateInfo &td); - Bool_t Union(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, - Int_t n3, UChar_t *array3, TGeoStateInfo &td); -public : +public: TGeoVoxelFinder(); TGeoVoxelFinder(TGeoVolume *vol); - virtual ~TGeoVoxelFinder(); - void DaughterToMother(Int_t id, const Double_t *local, Double_t *master) const; - virtual Double_t Efficiency(); - virtual Int_t *GetCheckList(const Double_t *point, Int_t &nelem, TGeoStateInfo &td); - Int_t *GetCheckList(Int_t &nelem, TGeoStateInfo &td) const; - virtual Int_t *GetNextCandidates(const Double_t *point, Int_t &ncheck, TGeoStateInfo &td); - virtual void FindOverlaps(Int_t inode) const; - Bool_t IsInvalid() const {return TObject::TestBit(kGeoInvalidVoxels);} - Bool_t NeedRebuild() const {return TObject::TestBit(kGeoRebuildVoxels);} - Double_t *GetBoxes() const {return fBoxes;} - Bool_t IsSafeVoxel(const Double_t *point, Int_t inode, Double_t minsafe) const; - virtual void Print(Option_t *option="") const; - void PrintVoxelLimits(const Double_t *point) const; - void SetInvalid(Bool_t flag=kTRUE) {TObject::SetBit(kGeoInvalidVoxels, flag);} - void SetNeedRebuild(Bool_t flag=kTRUE) {TObject::SetBit(kGeoRebuildVoxels, flag);} - virtual Int_t *GetNextVoxel(const Double_t *point, const Double_t *dir, Int_t &ncheck, TGeoStateInfo &td); - virtual void SortCrossedVoxels(const Double_t *point, const Double_t *dir, TGeoStateInfo &td); - virtual void Voxelize(Option_t *option=""); + ~TGeoVoxelFinder() override; + void DaughterToMother(Int_t id, const Double_t *local, Double_t *master) const; + virtual Double_t Efficiency(); + virtual Int_t *GetCheckList(const Double_t *point, Int_t &nelem, TGeoStateInfo &td); + Int_t *GetCheckList(Int_t &nelem, TGeoStateInfo &td) const; + virtual Int_t *GetNextCandidates(const Double_t *point, Int_t &ncheck, TGeoStateInfo &td); + virtual void FindOverlaps(Int_t inode) const; + Bool_t IsInvalid() const { return TObject::TestBit(kGeoInvalidVoxels); } + Bool_t NeedRebuild() const { return TObject::TestBit(kGeoRebuildVoxels); } + Double_t *GetBoxes() const { return fBoxes; } + Bool_t IsSafeVoxel(const Double_t *point, Int_t inode, Double_t minsafe) const; + void Print(Option_t *option = "") const override; + void PrintVoxelLimits(const Double_t *point) const; + void SetInvalid(Bool_t flag = kTRUE) { TObject::SetBit(kGeoInvalidVoxels, flag); } + void SetNeedRebuild(Bool_t flag = kTRUE) { TObject::SetBit(kGeoRebuildVoxels, flag); } + virtual Int_t *GetNextVoxel(const Double_t *point, const Double_t *dir, Int_t &ncheck, TGeoStateInfo &td); + virtual void SortCrossedVoxels(const Double_t *point, const Double_t *dir, TGeoStateInfo &td); + virtual void Voxelize(Option_t *option = ""); - ClassDef(TGeoVoxelFinder, 4) // voxel finder class + ClassDefOverride(TGeoVoxelFinder, 4) // voxel finder class }; #endif diff --git a/geom/geom/inc/TGeoXtru.h b/geom/geom/inc/TGeoXtru.h index e32d64adab687..368f0761e1456 100644 --- a/geom/geom/inc/TGeoXtru.h +++ b/geom/geom/inc/TGeoXtru.h @@ -19,51 +19,50 @@ class TGeoPolygon; -class TGeoXtru : public TGeoBBox -{ +class TGeoXtru : public TGeoBBox { public: - struct ThreadData_t - { - Int_t fSeg; // !current segment [0,fNvert-1] - Int_t fIz; // !current z plane [0,fNz-1] - Double_t *fXc; // ![fNvert] current X positions for polygon vertices - Double_t *fYc; // ![fNvert] current Y positions for polygon vertices - TGeoPolygon *fPoly; // !polygon defining section shape + struct ThreadData_t { + Int_t fSeg; // !current segment [0,fNvert-1] + Int_t fIz; // !current z plane [0,fNz-1] + Double_t *fXc; // ![fNvert] current X positions for polygon vertices + Double_t *fYc; // ![fNvert] current Y positions for polygon vertices + TGeoPolygon *fPoly; // !polygon defining section shape ThreadData_t(); ~ThreadData_t(); }; - ThreadData_t& GetThreadData() const; - virtual void ClearThreadData() const; - virtual void CreateThreadData(Int_t nthreads); + ThreadData_t &GetThreadData() const; + void ClearThreadData() const override; + void CreateThreadData(Int_t nthreads) override; protected: // data members - Int_t fNvert; // number of vertices of the 2D polygon (at least 3) - Int_t fNz; // number of z planes (at least two) - Double_t fZcurrent; // current Z position - Double_t *fX; //[fNvert] X positions for polygon vertices - Double_t *fY; //[fNvert] Y positions for polygon vertices - Double_t *fZ; //[fNz] array of Z planes positions - Double_t *fScale; //[fNz] array of scale factors (for each Z) - Double_t *fX0; //[fNz] array of X offsets (for each Z) - Double_t *fY0; //[fNz] array of Y offsets (for each Z) + Int_t fNvert; // number of vertices of the 2D polygon (at least 3) + Int_t fNz; // number of z planes (at least two) + Double_t fZcurrent; // current Z position + Double_t *fX; //[fNvert] X positions for polygon vertices + Double_t *fY; //[fNvert] Y positions for polygon vertices + Double_t *fZ; //[fNz] array of Z planes positions + Double_t *fScale; //[fNz] array of scale factors (for each Z) + Double_t *fX0; //[fNz] array of X offsets (for each Z) + Double_t *fY0; //[fNz] array of Y offsets (for each Z) - mutable std::vector fThreadData; //! Navigation data per thread - mutable Int_t fThreadSize; //! size of thread-specific array - mutable std::mutex fMutex; //! mutex for thread data + mutable std::vector fThreadData; //! Navigation data per thread + mutable Int_t fThreadSize; //! size of thread-specific array + mutable std::mutex fMutex; //! mutex for thread data - TGeoXtru(const TGeoXtru&) = delete; - TGeoXtru& operator=(const TGeoXtru&) = delete; + TGeoXtru(const TGeoXtru &) = delete; + TGeoXtru &operator=(const TGeoXtru &) = delete; // methods - Double_t DistToPlane(const Double_t *point, const Double_t *dir, Int_t iz, Int_t ivert, Double_t stepmax, Bool_t in) const; - void GetPlaneVertices(Int_t iz, Int_t ivert, Double_t *vert) const; - void GetPlaneNormal(const Double_t *vert, Double_t *norm) const; - Bool_t IsPointInsidePlane(const Double_t *point, Double_t *vert, Double_t *norm) const; - Double_t SafetyToSector(const Double_t *point, Int_t iz, Double_t safmin, Bool_t in); - void SetIz(Int_t iz); - void SetSeg(Int_t iseg); + Double_t + DistToPlane(const Double_t *point, const Double_t *dir, Int_t iz, Int_t ivert, Double_t stepmax, Bool_t in) const; + void GetPlaneVertices(Int_t iz, Int_t ivert, Double_t *vert) const; + void GetPlaneNormal(const Double_t *vert, Double_t *norm) const; + Bool_t IsPointInsidePlane(const Double_t *point, Double_t *vert, Double_t *norm) const; + Double_t SafetyToSector(const Double_t *point, Int_t iz, Double_t safmin, Bool_t in); + void SetIz(Int_t iz); + void SetSeg(Int_t iseg); public: // constructors @@ -71,53 +70,55 @@ class TGeoXtru : public TGeoBBox TGeoXtru(Int_t nz); TGeoXtru(Double_t *param); // destructor - virtual ~TGeoXtru(); + ~TGeoXtru() override; // methods - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize); - virtual Bool_t Contains(const Double_t *point) const; - virtual void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const; - Bool_t DefinePolygon(Int_t nvert, const Double_t *xv, const Double_t *yv); - virtual void DefineSection(Int_t snum, Double_t z, Double_t x0=0., Double_t y0=0., Double_t scale=1.); - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - void DrawPolygon(Option_t *option=""); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; -// virtual Int_t GetByteCount() const {return 60+12*fNz;} - Int_t GetNz() const {return fNz;} - Int_t GetNvert() const {return fNvert;} - Double_t GetX(Int_t i) const {return (i-1 && fX) ? fX[i] : -1.0E10;} - Double_t GetY(Int_t i) const {return (i-1 && fY) ? fY[i] : -1.0E10;} - Double_t GetXOffset(Int_t i) const {return (i-1 && fX0) ? fX0[i] : 0.0;} - Double_t GetYOffset(Int_t i) const {return (i-1 && fY0) ? fY0[i] : 0.0;} - Double_t GetScale(Int_t i) const {return (i-1 && fScale) ? fScale[i] : 1.0;} - Double_t *GetZ() const {return fZ;} - Double_t GetZ(Int_t ipl) const; - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const {return nullptr;} - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const; - virtual Int_t GetNmeshVertices() const; - virtual void InspectShape() const; - virtual TBuffer3D *MakeBuffer3D() const; - Double_t &Z(Int_t ipl) {return fZ[ipl];} - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - void SetCurrentZ(Double_t z, Int_t iz); - void SetCurrentVertices(Double_t x0, Double_t y0, Double_t scale); - virtual void SetDimensions(Double_t *param); - virtual void SetPoints(Double_t *points) const; - virtual void SetPoints(Float_t *points) const; - virtual void SetSegsAndPols(TBuffer3D &buff) const; - virtual void Sizeof3D() const; + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + void ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) override; + Bool_t Contains(const Double_t *point) const override; + void Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const override; + Bool_t DefinePolygon(Int_t nvert, const Double_t *xv, const Double_t *yv); + virtual void DefineSection(Int_t snum, Double_t z, Double_t x0 = 0., Double_t y0 = 0., Double_t scale = 1.); + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + void DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + void DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void DrawPolygon(Option_t *option = ""); + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + // virtual Int_t GetByteCount() const {return 60+12*fNz;} + Int_t GetNz() const { return fNz; } + Int_t GetNvert() const { return fNvert; } + Double_t GetX(Int_t i) const { return (i < fNvert && i > -1 && fX) ? fX[i] : -1.0E10; } + Double_t GetY(Int_t i) const { return (i < fNvert && i > -1 && fY) ? fY[i] : -1.0E10; } + Double_t GetXOffset(Int_t i) const { return (i < fNz && i > -1 && fX0) ? fX0[i] : 0.0; } + Double_t GetYOffset(Int_t i) const { return (i < fNz && i > -1 && fY0) ? fY0[i] : 0.0; } + Double_t GetScale(Int_t i) const { return (i < fNz && i > -1 && fScale) ? fScale[i] : 1.0; } + Double_t *GetZ() const { return fZ; } + Double_t GetZ(Int_t ipl) const; + TGeoShape *GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const override { return nullptr; } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override; + Int_t GetNmeshVertices() const override; + void InspectShape() const override; + TBuffer3D *MakeBuffer3D() const override; + Double_t &Z(Int_t ipl) { return fZ[ipl]; } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + void Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetCurrentZ(Double_t z, Int_t iz); + void SetCurrentVertices(Double_t x0, Double_t y0, Double_t scale); + void SetDimensions(Double_t *param) override; + void SetPoints(Double_t *points) const override; + void SetPoints(Float_t *points) const override; + void SetSegsAndPols(TBuffer3D &buff) const override; + void Sizeof3D() const override; - ClassDef(TGeoXtru, 3) // extruded polygon class + ClassDefOverride(TGeoXtru, 3) // extruded polygon class }; #endif diff --git a/geom/geom/inc/TVirtualGeoConverter.h b/geom/geom/inc/TVirtualGeoConverter.h index fc5d93eebe74b..8fe7cba518b9b 100644 --- a/geom/geom/inc/TVirtualGeoConverter.h +++ b/geom/geom/inc/TVirtualGeoConverter.h @@ -18,18 +18,18 @@ class TGeoManager; class TVirtualGeoConverter : public TObject { protected: - static TVirtualGeoConverter *fgGeoConverter; // Pointer to geometry converter - TGeoManager *fGeom; // Pointer to geometry manager + static TVirtualGeoConverter *fgGeoConverter; // Pointer to geometry converter + TGeoManager *fGeom; // Pointer to geometry manager public: TVirtualGeoConverter(TGeoManager *geom); - virtual ~TVirtualGeoConverter(); + ~TVirtualGeoConverter() override; - virtual void ConvertGeometry() {} - static TVirtualGeoConverter *Instance(TGeoManager *geom=nullptr); - static void SetConverter(const TVirtualGeoConverter *conv); - void SetGeometry(TGeoManager *geom) { fGeom = geom; } + virtual void ConvertGeometry() {} + static TVirtualGeoConverter *Instance(TGeoManager *geom = nullptr); + static void SetConverter(const TVirtualGeoConverter *conv); + void SetGeometry(TGeoManager *geom) { fGeom = geom; } - ClassDef(TVirtualGeoConverter,0) // Abstract interface for geometry converters + ClassDefOverride(TVirtualGeoConverter, 0) // Abstract interface for geometry converters }; #endif diff --git a/geom/geom/inc/TVirtualGeoPainter.h b/geom/geom/inc/TVirtualGeoPainter.h index ee77ec2d0c076..9f27a73fcfd72 100644 --- a/geom/geom/inc/TVirtualGeoPainter.h +++ b/geom/geom/inc/TVirtualGeoPainter.h @@ -32,114 +32,115 @@ class TGeoPolygon; class TVirtualGeoPainter : public TObject { protected: - static TVirtualGeoPainter *fgGeoPainter; //Pointer to class painter + static TVirtualGeoPainter *fgGeoPainter; // Pointer to class painter public: -enum EGeoVisLevel { - kGeoVisLevel = 0 -}; -enum EGeoVisOption { - kGeoVisDefault = 0, // default visualization - everything visible 3 levels down - kGeoVisLeaves = 1, // only last leaves are visible - kGeoVisOnly = 2, // only current volume is drawn - kGeoVisBranch = 3, // only a given branch is drawn - kGeoVisChanged = 4 // visibility changed -}; -enum EGeoBombOption { - kGeoNoBomb = 0, // default - no bomb - kGeoBombXYZ = 1, // explode view in cartesian coordinates - kGeoBombCyl = 2, // explode view in cylindrical coordinates (R, Z) - kGeoBombSph = 3 // explode view in spherical coordinates (R) -}; + enum EGeoVisLevel { kGeoVisLevel = 0 }; + enum EGeoVisOption { + kGeoVisDefault = 0, // default visualization - everything visible 3 levels down + kGeoVisLeaves = 1, // only last leaves are visible + kGeoVisOnly = 2, // only current volume is drawn + kGeoVisBranch = 3, // only a given branch is drawn + kGeoVisChanged = 4 // visibility changed + }; + enum EGeoBombOption { + kGeoNoBomb = 0, // default - no bomb + kGeoBombXYZ = 1, // explode view in cartesian coordinates + kGeoBombCyl = 2, // explode view in cylindrical coordinates (R, Z) + kGeoBombSph = 3 // explode view in spherical coordinates (R) + }; public: TVirtualGeoPainter(TGeoManager *manager); - virtual ~TVirtualGeoPainter(); + ~TVirtualGeoPainter() override; - virtual void AddSize3D(Int_t numpoints, Int_t numsegs, Int_t numpolys) = 0; + virtual void AddSize3D(Int_t numpoints, Int_t numsegs, Int_t numpolys) = 0; virtual TVirtualGeoTrack *AddTrack(Int_t id, Int_t pdgcode, TObject *particle) = 0; - virtual void AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset=kFALSE) = 0; - virtual void BombTranslation(const Double_t *tr, Double_t *bombtr) = 0; - virtual void CheckPoint(Double_t x=0, Double_t y=0, Double_t z=0, Option_t *option="") = 0; - virtual void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option) = 0; - virtual void CheckBoundaryErrors(Int_t ntracks=1000000, Double_t radius=-1.) = 0; - virtual void CheckBoundaryReference(Int_t icheck=-1) = 0; - virtual void CheckGeometryFull(Bool_t checkoverlaps=kTRUE, Bool_t checkcrossings=kTRUE, Int_t nrays=10000, const Double_t *vertex=nullptr) = 0; - virtual void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const = 0; - virtual void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp=0.1, Option_t *option="") const = 0; - virtual Int_t CountVisibleNodes() = 0; - virtual void DefaultAngles() = 0; - virtual void DefaultColors() = 0; - virtual Int_t DistanceToPrimitiveVol(TGeoVolume *vol, Int_t px, Int_t py) = 0; - virtual void DrawBatemanSol(TGeoBatemanSol *sol, Option_t *option="") = 0; - virtual void DrawShape(TGeoShape *shape, Option_t *option="") = 0; - virtual void DrawOnly(Option_t *option="") = 0; - virtual void DrawOverlap(void *ovlp, Option_t *option="") = 0; - virtual void DrawCurrentPoint(Int_t color) = 0; - virtual void DrawPanel() = 0; - virtual void DrawPath(const char *path, Option_t *option="") = 0; - virtual void DrawPolygon(const TGeoPolygon *poly) = 0; - virtual void DrawVolume(TGeoVolume *vol, Option_t *option="") = 0; - virtual void EditGeometry(Option_t *option="") = 0; - virtual void EstimateCameraMove(Double_t /*tmin*/, Double_t /*tmax*/, Double_t *, Double_t * ) {} - virtual void ExecuteShapeEvent(TGeoShape *shape, Int_t event, Int_t px, Int_t py) = 0; - virtual void ExecuteManagerEvent(TGeoManager *geom, Int_t event, Int_t px, Int_t py) = 0; - virtual void ExecuteVolumeEvent(TGeoVolume *volume, Int_t event, Int_t px, Int_t py) = 0; - virtual Int_t GetColor(Int_t base, Float_t light) const = 0; - virtual Int_t GetNsegments() const = 0; - virtual void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const = 0; - virtual Int_t GetBombMode() const = 0; + virtual void AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset = kFALSE) = 0; + virtual void BombTranslation(const Double_t *tr, Double_t *bombtr) = 0; + virtual void CheckPoint(Double_t x = 0, Double_t y = 0, Double_t z = 0, Option_t *option = "") = 0; + virtual void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option) = 0; + virtual void CheckBoundaryErrors(Int_t ntracks = 1000000, Double_t radius = -1.) = 0; + virtual void CheckBoundaryReference(Int_t icheck = -1) = 0; + virtual void CheckGeometryFull(Bool_t checkoverlaps = kTRUE, Bool_t checkcrossings = kTRUE, Int_t nrays = 10000, + const Double_t *vertex = nullptr) = 0; + virtual void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const = 0; + virtual void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp = 0.1, Option_t *option = "") const = 0; + virtual Int_t CountVisibleNodes() = 0; + virtual void DefaultAngles() = 0; + virtual void DefaultColors() = 0; + virtual Int_t DistanceToPrimitiveVol(TGeoVolume *vol, Int_t px, Int_t py) = 0; + virtual void DrawBatemanSol(TGeoBatemanSol *sol, Option_t *option = "") = 0; + virtual void DrawShape(TGeoShape *shape, Option_t *option = "") = 0; + virtual void DrawOnly(Option_t *option = "") = 0; + virtual void DrawOverlap(void *ovlp, Option_t *option = "") = 0; + virtual void DrawCurrentPoint(Int_t color) = 0; + virtual void DrawPanel() = 0; + virtual void DrawPath(const char *path, Option_t *option = "") = 0; + virtual void DrawPolygon(const TGeoPolygon *poly) = 0; + virtual void DrawVolume(TGeoVolume *vol, Option_t *option = "") = 0; + virtual void EditGeometry(Option_t *option = "") = 0; + virtual void EstimateCameraMove(Double_t /*tmin*/, Double_t /*tmax*/, Double_t *, Double_t *) {} + virtual void ExecuteShapeEvent(TGeoShape *shape, Int_t event, Int_t px, Int_t py) = 0; + virtual void ExecuteManagerEvent(TGeoManager *geom, Int_t event, Int_t px, Int_t py) = 0; + virtual void ExecuteVolumeEvent(TGeoVolume *volume, Int_t event, Int_t px, Int_t py) = 0; + virtual Int_t GetColor(Int_t base, Float_t light) const = 0; + virtual Int_t GetNsegments() const = 0; + virtual void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const = 0; + virtual Int_t GetBombMode() const = 0; virtual const char *GetDrawPath() const = 0; virtual TGeoVolume *GetDrawnVolume() const = 0; virtual TGeoVolume *GetTopVolume() const = 0; - virtual void GetViewAngles(Double_t &/*longitude*/, Double_t &/*latitude*/, Double_t &/*psi*/) {} - virtual Int_t GetVisLevel() const = 0; - virtual Int_t GetVisOption() const = 0; - virtual const char*GetVolumeInfo(const TGeoVolume *volume, Int_t px, Int_t py) const = 0; - virtual void GrabFocus(Int_t nfr=0, Double_t dlong=0, Double_t dlat=0, Double_t dpsi=0) =0; - virtual Double_t *GetViewBox() = 0; - virtual Bool_t IsPaintingShape() const = 0; - virtual Bool_t IsRaytracing() const = 0; - virtual Bool_t IsExplodedView() const = 0; - virtual TH2F *LegoPlot(Int_t ntheta=60, Double_t themin=0., Double_t themax=180., - Int_t nphi=90, Double_t phimin=0., Double_t phimax=360., - Double_t rmin=0., Double_t rmax=9999999, Option_t *option="") = 0; - virtual void ModifiedPad(Bool_t update=kFALSE) const = 0; - virtual void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch=nullptr, Bool_t last=kFALSE, Bool_t refresh=kFALSE, const char *msg="") = 0; - virtual void Paint(Option_t *option="") = 0; - virtual void PaintNode(TGeoNode *node, Option_t *option="", TGeoMatrix* global=nullptr) = 0; - virtual void PaintShape(TGeoShape *shape, Option_t *option="") = 0; - virtual void PaintOverlap(void *ovlp, Option_t *option="") = 0; - virtual void PrintOverlaps() const = 0; - virtual void PaintVolume(TGeoVolume *vol, Option_t *option="", TGeoMatrix* global=nullptr) = 0; - virtual void RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option="") = 0; - virtual void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, Bool_t check_norm) = 0; - virtual void Raytrace(Option_t *option="") = 0; - virtual TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char* g3path) = 0; - virtual void SetBombFactors(Double_t bombx=1.3, Double_t bomby=1.3, Double_t bombz=1.3, - Double_t bombr=1.3) = 0; - virtual void SetClippingShape(TGeoShape *shape) = 0; - virtual void SetExplodedView(Int_t iopt=0) = 0; - virtual void SetGeoManager(TGeoManager *geom) = 0; - virtual void SetIteratorPlugin(TGeoIteratorPlugin *plugin) = 0; - virtual void SetCheckedNode(TGeoNode *node) = 0; - virtual void SetNsegments(Int_t nseg=20) = 0; - virtual void SetNmeshPoints(Int_t npoints) = 0; - virtual void SetRaytracing(Bool_t flag=kTRUE) = 0; - static TVirtualGeoPainter *GeoPainter(); - static void SetPainter(const TVirtualGeoPainter *painter); - virtual void SetTopVisible(Bool_t vis=kTRUE) = 0; - virtual void SetTopVolume(TGeoVolume *vol) = 0; - virtual void SetVisLevel(Int_t level=3) = 0; - virtual void SetVisOption(Int_t option=0) = 0; - virtual Int_t ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoints, Int_t px, Int_t py) const = 0; - virtual void Test(Int_t npoints, Option_t *option) = 0; - virtual void TestOverlaps(const char *path) = 0; - virtual Bool_t TestVoxels(TGeoVolume *vol) = 0; - virtual void UnbombTranslation(const Double_t *tr, Double_t *bombtr) = 0; - virtual Double_t Weight(Double_t precision, Option_t *option="v") = 0; + virtual void GetViewAngles(Double_t & /*longitude*/, Double_t & /*latitude*/, Double_t & /*psi*/) {} + virtual Int_t GetVisLevel() const = 0; + virtual Int_t GetVisOption() const = 0; + virtual const char *GetVolumeInfo(const TGeoVolume *volume, Int_t px, Int_t py) const = 0; + virtual void GrabFocus(Int_t nfr = 0, Double_t dlong = 0, Double_t dlat = 0, Double_t dpsi = 0) = 0; + virtual Double_t *GetViewBox() = 0; + virtual Bool_t IsPaintingShape() const = 0; + virtual Bool_t IsRaytracing() const = 0; + virtual Bool_t IsExplodedView() const = 0; + virtual TH2F *LegoPlot(Int_t ntheta = 60, Double_t themin = 0., Double_t themax = 180., Int_t nphi = 90, + Double_t phimin = 0., Double_t phimax = 360., Double_t rmin = 0., Double_t rmax = 9999999, + Option_t *option = "") = 0; + virtual void ModifiedPad(Bool_t update = kFALSE) const = 0; + virtual void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch = nullptr, + Bool_t last = kFALSE, Bool_t refresh = kFALSE, const char *msg = "") = 0; + void Paint(Option_t *option = "") override = 0; + virtual void PaintNode(TGeoNode *node, Option_t *option = "", TGeoMatrix *global = nullptr) = 0; + virtual void PaintShape(TGeoShape *shape, Option_t *option = "") = 0; + virtual void PaintOverlap(void *ovlp, Option_t *option = "") = 0; + virtual void PrintOverlaps() const = 0; + virtual void PaintVolume(TGeoVolume *vol, Option_t *option = "", TGeoMatrix *global = nullptr) = 0; + virtual void RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option = "") = 0; + virtual void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, + Bool_t check_norm) = 0; + virtual void Raytrace(Option_t *option = "") = 0; + virtual TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path) = 0; + virtual void + SetBombFactors(Double_t bombx = 1.3, Double_t bomby = 1.3, Double_t bombz = 1.3, Double_t bombr = 1.3) = 0; + virtual void SetClippingShape(TGeoShape *shape) = 0; + virtual void SetExplodedView(Int_t iopt = 0) = 0; + virtual void SetGeoManager(TGeoManager *geom) = 0; + virtual void SetIteratorPlugin(TGeoIteratorPlugin *plugin) = 0; + virtual void SetCheckedNode(TGeoNode *node) = 0; + virtual void SetNsegments(Int_t nseg = 20) = 0; + virtual void SetNmeshPoints(Int_t npoints) = 0; + virtual void SetRaytracing(Bool_t flag = kTRUE) = 0; + static TVirtualGeoPainter *GeoPainter(); + static void SetPainter(const TVirtualGeoPainter *painter); + virtual void SetTopVisible(Bool_t vis = kTRUE) = 0; + virtual void SetTopVolume(TGeoVolume *vol) = 0; + virtual void SetVisLevel(Int_t level = 3) = 0; + virtual void SetVisOption(Int_t option = 0) = 0; + virtual Int_t ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoints, Int_t px, Int_t py) const = 0; + virtual void Test(Int_t npoints, Option_t *option) = 0; + virtual void TestOverlaps(const char *path) = 0; + virtual Bool_t TestVoxels(TGeoVolume *vol) = 0; + virtual void UnbombTranslation(const Double_t *tr, Double_t *bombtr) = 0; + virtual Double_t Weight(Double_t precision, Option_t *option = "v") = 0; - ClassDef(TVirtualGeoPainter,0) //Abstract interface for geometry painters + ClassDefOverride(TVirtualGeoPainter, 0) // Abstract interface for geometry painters }; #endif diff --git a/geom/geom/inc/TVirtualGeoTrack.h b/geom/geom/inc/TVirtualGeoTrack.h index c5488c99d2c83..2afce6d62e23f 100644 --- a/geom/geom/inc/TVirtualGeoTrack.h +++ b/geom/geom/inc/TVirtualGeoTrack.h @@ -20,64 +20,59 @@ #include "TAttMarker.h" -class TVirtualGeoTrack : public TObject, - public TGeoAtt, - public TAttLine, - public TAttMarker -{ +class TVirtualGeoTrack : public TObject, public TGeoAtt, public TAttLine, public TAttMarker { protected: - Int_t fPDG{0}; // track pdg code - Int_t fId{-1}; // track id - TVirtualGeoTrack *fParent{nullptr}; // id of parent - TObject *fParticle{nullptr}; // particle for this track - TObjArray *fTracks{nullptr}; // daughter tracks + Int_t fPDG{0}; // track pdg code + Int_t fId{-1}; // track id + TVirtualGeoTrack *fParent{nullptr}; // id of parent + TObject *fParticle{nullptr}; // particle for this track + TObjArray *fTracks{nullptr}; // daughter tracks - TVirtualGeoTrack(const TVirtualGeoTrack&) = delete; - TVirtualGeoTrack& operator=(const TVirtualGeoTrack&) = delete; + TVirtualGeoTrack(const TVirtualGeoTrack &) = delete; + TVirtualGeoTrack &operator=(const TVirtualGeoTrack &) = delete; public: TVirtualGeoTrack(); - TVirtualGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent=nullptr, TObject *particle=nullptr); - virtual ~TVirtualGeoTrack(); + TVirtualGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent = nullptr, TObject *particle = nullptr); + ~TVirtualGeoTrack() override; - virtual TVirtualGeoTrack *AddDaughter(Int_t id, Int_t pdgcode, TObject *particle=nullptr) = 0; - virtual Int_t AddDaughter(TVirtualGeoTrack *other) = 0; - virtual void AddPoint(Double_t x, Double_t y, Double_t z, Double_t t) = 0; + virtual TVirtualGeoTrack *AddDaughter(Int_t id, Int_t pdgcode, TObject *particle = nullptr) = 0; + virtual Int_t AddDaughter(TVirtualGeoTrack *other) = 0; + virtual void AddPoint(Double_t x, Double_t y, Double_t z, Double_t t) = 0; virtual TVirtualGeoTrack *FindTrackWithId(Int_t id) const; - Int_t GetId() const {return fId;} - virtual Int_t GetDaughterId(Int_t index) const; - TVirtualGeoTrack *GetDaughter(Int_t index) const {return (TVirtualGeoTrack*)fTracks->At(index);} - TVirtualGeoTrack *GetMother() const {return fParent;} - TObject *GetMotherParticle() const {return fParent ? fParent->GetParticle() : nullptr;} - virtual const char *GetName() const; - Int_t GetNdaughters() const {return fTracks ? fTracks->GetEntriesFast() : 0;} - virtual Int_t GetNpoints() const = 0; - Int_t GetParentId() const {return fParent?fParent->GetId():-1;} - TObject *GetParticle() const {return fParticle;} - Int_t GetPDG() const {return fPDG;} - Int_t GetLastPoint(Double_t &x, Double_t &y, Double_t &z, Double_t &t) const {return GetPoint(GetNpoints()-1,x,y,z,t);} - const Double_t *GetFirstPoint() const {return GetPoint(0);} - const Double_t *GetLastPoint() const {return GetPoint(GetNpoints()-1);} - virtual Int_t GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double_t &t) const = 0; + Int_t GetId() const { return fId; } + virtual Int_t GetDaughterId(Int_t index) const; + TVirtualGeoTrack *GetDaughter(Int_t index) const { return (TVirtualGeoTrack *)fTracks->At(index); } + TVirtualGeoTrack *GetMother() const { return fParent; } + TObject *GetMotherParticle() const { return fParent ? fParent->GetParticle() : nullptr; } + const char *GetName() const override; + Int_t GetNdaughters() const { return fTracks ? fTracks->GetEntriesFast() : 0; } + virtual Int_t GetNpoints() const = 0; + Int_t GetParentId() const { return fParent ? fParent->GetId() : -1; } + TObject *GetParticle() const { return fParticle; } + Int_t GetPDG() const { return fPDG; } + Int_t GetLastPoint(Double_t &x, Double_t &y, Double_t &z, Double_t &t) const + { + return GetPoint(GetNpoints() - 1, x, y, z, t); + } + const Double_t *GetFirstPoint() const { return GetPoint(0); } + const Double_t *GetLastPoint() const { return GetPoint(GetNpoints() - 1); } + virtual Int_t GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double_t &t) const = 0; virtual const Double_t *GetPoint(Int_t i) const = 0; - Bool_t HasPoints() const {return (GetNpoints()==0)?kFALSE:kTRUE;} - Bool_t IsInTimeRange() const; - virtual void Paint(Option_t *option="") = 0; - virtual void PaintCollect(Double_t /*time*/, Double_t * /*box*/) {} - virtual void PaintCollectTrack(Double_t /*time*/, Double_t * /*box*/) {} - virtual void PaintTrack(Option_t *option="") = 0; - virtual void ResetTrack() = 0; - void SetName(const char *name); - virtual void SetParticle(TObject *particle) {fParticle=particle;} - void SetParent(TVirtualGeoTrack *parent) {fParent = parent;} - void SetId(Int_t id) {fId = id;} - virtual void SetPDG(Int_t pdgcode) {fPDG = pdgcode;} - - ClassDef(TVirtualGeoTrack, 1) // virtual geometry tracks + Bool_t HasPoints() const { return (GetNpoints() == 0) ? kFALSE : kTRUE; } + Bool_t IsInTimeRange() const; + void Paint(Option_t *option = "") override = 0; + virtual void PaintCollect(Double_t /*time*/, Double_t * /*box*/) {} + virtual void PaintCollectTrack(Double_t /*time*/, Double_t * /*box*/) {} + virtual void PaintTrack(Option_t *option = "") = 0; + virtual void ResetTrack() = 0; + void SetName(const char *name); + virtual void SetParticle(TObject *particle) { fParticle = particle; } + void SetParent(TVirtualGeoTrack *parent) { fParent = parent; } + void SetId(Int_t id) { fId = id; } + virtual void SetPDG(Int_t pdgcode) { fPDG = pdgcode; } + + ClassDefOverride(TVirtualGeoTrack, 1) // virtual geometry tracks }; #endif - - - - diff --git a/geom/geom/inc/TVirtualMagField.h b/geom/geom/inc/TVirtualMagField.h index 6cbe7aa974f01..f2cfc8c1b8536 100644 --- a/geom/geom/inc/TVirtualMagField.h +++ b/geom/geom/inc/TVirtualMagField.h @@ -13,45 +13,52 @@ #include "TNamed.h" -class TVirtualMagField : public TNamed -{ +class TVirtualMagField : public TNamed { public: - TVirtualMagField() : TNamed() {} - TVirtualMagField(const char *name) : TNamed(name,"") {} - virtual ~TVirtualMagField(); + TVirtualMagField() : TNamed() {} + TVirtualMagField(const char *name) : TNamed(name, "") {} + ~TVirtualMagField() override; virtual void Field(const Double_t *x, Double_t *B) = 0; - ClassDef(TVirtualMagField, 1) // Abstract base field class + ClassDefOverride(TVirtualMagField, 1) // Abstract base field class }; - //////////////////////////////////////////////////////////////////////////// // // // TGeoUniformMagField - Uniform magnetic field class. // // // //////////////////////////////////////////////////////////////////////////// -class TGeoUniformMagField : public TVirtualMagField -{ +class TGeoUniformMagField : public TVirtualMagField { private: - Double_t fB[3]; // Magnetic field vector + Double_t fB[3]; // Magnetic field vector protected: - TGeoUniformMagField(const TGeoUniformMagField&) = delete; - TGeoUniformMagField& operator=(const TGeoUniformMagField&) = delete; + TGeoUniformMagField(const TGeoUniformMagField &) = delete; + TGeoUniformMagField &operator=(const TGeoUniformMagField &) = delete; public: TGeoUniformMagField(); TGeoUniformMagField(Double_t Bx, Double_t By, Double_t Bz); - virtual ~TGeoUniformMagField() {} + ~TGeoUniformMagField() override {} - void Field(const Double_t * /*x*/, Double_t *B) override {B[0]=fB[0]; B[1]=fB[1]; B[2]=fB[2];} + void Field(const Double_t * /*x*/, Double_t *B) override + { + B[0] = fB[0]; + B[1] = fB[1]; + B[2] = fB[2]; + } const Double_t *GetFieldValue() const { return &fB[0]; } - void SetFieldValue(Double_t Bx, Double_t By, Double_t Bz) {fB[0]=Bx; fB[1]=By; fB[2]=Bz;} + void SetFieldValue(Double_t Bx, Double_t By, Double_t Bz) + { + fB[0] = Bx; + fB[1] = By; + fB[2] = Bz; + } - ClassDefOverride(TGeoUniformMagField, 1) // Uniform magnetic field + ClassDefOverride(TGeoUniformMagField, 1) // Uniform magnetic field }; #endif diff --git a/geom/geom/src/TGDMLMatrix.cxx b/geom/geom/src/TGDMLMatrix.cxx index 6807868db5ac0..69e0c1293f63e 100644 --- a/geom/geom/src/TGDMLMatrix.cxx +++ b/geom/geom/src/TGDMLMatrix.cxx @@ -20,16 +20,14 @@ in double precision. #include -ClassImp(TGDMLMatrix) +ClassImp(TGDMLMatrix); //_____________________________________________________________________________ -TGDMLMatrix::TGDMLMatrix(const char *name, size_t rows,size_t cols) - : TNamed(name, "") +TGDMLMatrix::TGDMLMatrix(const char *name, size_t rows, size_t cols) : TNamed(name, "") { -// Constructor - if ((rows <= 0) || (cols <= 0)) - { - Fatal("TGDMLMatrix::TGDMLMatrix(rows,cols)", "Wrong number of rows/cols"); + // Constructor + if ((rows <= 0) || (cols <= 0)) { + Fatal("TGDMLMatrix::TGDMLMatrix(rows,cols)", "Wrong number of rows/cols"); } fNrows = rows; fNcols = cols; @@ -38,29 +36,29 @@ TGDMLMatrix::TGDMLMatrix(const char *name, size_t rows,size_t cols) } //_____________________________________________________________________________ -TGDMLMatrix::TGDMLMatrix(const TGDMLMatrix& rhs) - : TNamed(rhs), fNelem(rhs.fNelem), fNrows(rhs.fNrows), fNcols(rhs.fNcols), fMatrix(nullptr) +TGDMLMatrix::TGDMLMatrix(const TGDMLMatrix &rhs) + : TNamed(rhs), fNelem(rhs.fNelem), fNrows(rhs.fNrows), fNcols(rhs.fNcols), fMatrix(nullptr) { -// Copy constructor - if (rhs.fMatrix) - { - fMatrix = new Double_t[fNelem]; - memcpy(fMatrix, rhs.fMatrix, fNelem * sizeof(Double_t)); + // Copy constructor + if (rhs.fMatrix) { + fMatrix = new Double_t[fNelem]; + memcpy(fMatrix, rhs.fMatrix, fNelem * sizeof(Double_t)); } } //_____________________________________________________________________________ -TGDMLMatrix& TGDMLMatrix::operator=(const TGDMLMatrix& rhs) +TGDMLMatrix &TGDMLMatrix::operator=(const TGDMLMatrix &rhs) { -// Assignment - if (this == &rhs) { return *this; } + // Assignment + if (this == &rhs) { + return *this; + } TNamed::operator=(rhs); fNrows = rhs.fNrows; fNcols = rhs.fNcols; fNelem = fNrows * fNcols; - if (rhs.fMatrix) - { - delete [] fMatrix; + if (rhs.fMatrix) { + delete[] fMatrix; fMatrix = new Double_t[fNelem]; memcpy(fMatrix, rhs.fMatrix, fNelem * sizeof(Double_t)); } @@ -71,27 +69,27 @@ TGDMLMatrix& TGDMLMatrix::operator=(const TGDMLMatrix& rhs) void TGDMLMatrix::Set(size_t r, size_t c, Double_t a) { assert(r < fNrows && c < fNcols); - fMatrix[fNcols*r+c] = a; + fMatrix[fNcols * r + c] = a; } //_____________________________________________________________________________ Double_t TGDMLMatrix::Get(size_t r, size_t c) const { assert(r < fNrows && c < fNcols); - return fMatrix[fNcols*r+c]; + return fMatrix[fNcols * r + c]; } //_____________________________________________________________________________ void TGDMLMatrix::Print(Option_t *) const { -// Print info about this matrix + // Print info about this matrix printf("*** matrix: %-20s coldim = %zu rows = %zu\n", GetName(), fNcols, fNrows); if (!fTitle.IsNull()) { printf(" %s\n", fTitle.Data()); return; } for (size_t row = 0; row < fNrows; ++row) { - printf(" "); + printf(" "); for (size_t col = 0; col < fNcols; ++col) { printf("%8.3g", Get(row, col)); } diff --git a/geom/geom/src/TGeoArb8.cxx b/geom/geom/src/TGeoArb8.cxx index f9c79b7bd3ad7..430310291bccb 100644 --- a/geom/geom/src/TGeoArb8.cxx +++ b/geom/geom/src/TGeoArb8.cxx @@ -166,7 +166,7 @@ Double_t h2,Double_t bl2,Double_t tl2,Double_t alpha2); TGeoArb8::TGeoArb8() { fDz = 0; - for (Int_t i=0; i<8; i++) { + for (Int_t i = 0; i < 8; i++) { fXY[i][0] = 0.0; fXY[i][1] = 0.0; } @@ -177,20 +177,19 @@ TGeoArb8::TGeoArb8() /// Constructor. If the array of vertices is not null, this should be /// in the format : (x0, y0, x1, y1, ... , x7, y7) -TGeoArb8::TGeoArb8(Double_t dz, Double_t *vertices) - :TGeoBBox(0,0,0) +TGeoArb8::TGeoArb8(Double_t dz, Double_t *vertices) : TGeoBBox(0, 0, 0) { fDz = dz; SetShapeBit(kGeoArb8); if (vertices) { - for (Int_t i=0; i<8; i++) { - fXY[i][0] = vertices[2*i]; - fXY[i][1] = vertices[2*i+1]; + for (Int_t i = 0; i < 8; i++) { + fXY[i][0] = vertices[2 * i]; + fXY[i][1] = vertices[2 * i + 1]; } ComputeTwist(); ComputeBBox(); } else { - for (Int_t i=0; i<8; i++) { + for (Int_t i = 0; i < 8; i++) { fXY[i][0] = 0.0; fXY[i][1] = 0.0; } @@ -201,20 +200,19 @@ TGeoArb8::TGeoArb8(Double_t dz, Double_t *vertices) /// Named constructor. If the array of vertices is not null, this should be /// in the format : (x0, y0, x1, y1, ... , x7, y7) -TGeoArb8::TGeoArb8(const char *name, Double_t dz, Double_t *vertices) - :TGeoBBox(name, 0,0,0) +TGeoArb8::TGeoArb8(const char *name, Double_t dz, Double_t *vertices) : TGeoBBox(name, 0, 0, 0) { fDz = dz; SetShapeBit(kGeoArb8); if (vertices) { - for (Int_t i=0; i<8; i++) { - fXY[i][0] = vertices[2*i]; - fXY[i][1] = vertices[2*i+1]; + for (Int_t i = 0; i < 8; i++) { + fXY[i][0] = vertices[2 * i]; + fXY[i][1] = vertices[2 * i + 1]; } ComputeTwist(); ComputeBBox(); } else { - for (Int_t i=0; i<8; i++) { + for (Int_t i = 0; i < 8; i++) { fXY[i][0] = 0.0; fXY[i][1] = 0.0; } @@ -226,7 +224,8 @@ TGeoArb8::TGeoArb8(const char *name, Double_t dz, Double_t *vertices) TGeoArb8::~TGeoArb8() { - if (fTwist) delete [] fTwist; + if (fTwist) + delete[] fTwist; } //////////////////////////////////////////////////////////////////////////////// @@ -235,10 +234,11 @@ TGeoArb8::~TGeoArb8() void TGeoArb8::CopyTwist(Double_t *twist) { if (twist) { - if (!fTwist) fTwist = new Double_t[4]; - memcpy(fTwist, twist, 4*sizeof(Double_t)); + if (!fTwist) + fTwist = new Double_t[4]; + memcpy(fTwist, twist, 4 * sizeof(Double_t)); } else if (fTwist) { - delete [] fTwist; + delete[] fTwist; fTwist = nullptr; } } @@ -248,14 +248,15 @@ void TGeoArb8::CopyTwist(Double_t *twist) Double_t TGeoArb8::Capacity() const { - Int_t i,j; + Int_t i, j; Double_t capacity = 0; - for (i=0; i<4; i++) { - j = (i+1)%4; - capacity += 0.25*fDz*((fXY[i][0]+fXY[i+4][0])*(fXY[j][1]+fXY[j+4][1]) - - (fXY[j][0]+fXY[j+4][0])*(fXY[i][1]+fXY[i+4][1]) + - (1./3)*((fXY[i+4][0]-fXY[i][0])*(fXY[j+4][1]-fXY[j][1]) - - (fXY[j][0]-fXY[j+4][0])*(fXY[i][1]-fXY[i+4][1]))); + for (i = 0; i < 4; i++) { + j = (i + 1) % 4; + capacity += 0.25 * fDz * + ((fXY[i][0] + fXY[i + 4][0]) * (fXY[j][1] + fXY[j + 4][1]) - + (fXY[j][0] + fXY[j + 4][0]) * (fXY[i][1] + fXY[i + 4][1]) + + (1. / 3) * ((fXY[i + 4][0] - fXY[i][0]) * (fXY[j + 4][1] - fXY[j][1]) - + (fXY[j][0] - fXY[j + 4][0]) * (fXY[i][1] - fXY[i + 4][1]))); } return TMath::Abs(capacity); } @@ -269,17 +270,21 @@ void TGeoArb8::ComputeBBox() xmin = xmax = fXY[0][0]; ymin = ymax = fXY[0][1]; - for (Int_t i=1; i<8; i++) { - if (xmin>fXY[i][0]) xmin=fXY[i][0]; - if (xmaxfXY[i][1]) ymin=fXY[i][1]; - if (ymax fXY[i][0]) + xmin = fXY[i][0]; + if (xmax < fXY[i][0]) + xmax = fXY[i][0]; + if (ymin > fXY[i][1]) + ymin = fXY[i][1]; + if (ymax < fXY[i][1]) + ymax = fXY[i][1]; + } + fDX = 0.5 * (xmax - xmin); + fDY = 0.5 * (ymax - ymin); fDZ = fDz; - fOrigin[0] = 0.5*(xmax+xmin); - fOrigin[1] = 0.5*(ymax+ymin); + fOrigin[0] = 0.5 * (xmax + xmin); + fOrigin[1] = 0.5 * (ymax + ymin); fOrigin[2] = 0; SetShapeBit(kGeoClosedShape); } @@ -297,58 +302,59 @@ void TGeoArb8::ComputeTwist() Bool_t singleBottom = kTRUE; Bool_t singleTop = kTRUE; Int_t i; - for (i=0; i<4; i++) { - dx1 = fXY[(i+1)%4][0]-fXY[i][0]; - dy1 = fXY[(i+1)%4][1]-fXY[i][1]; - if (TMath::Abs(dx1)TGeoShape::Tolerance()) { - Error("ComputeTwist", "Shape %s type Arb8: Vertices must be defined clockwise in XY planes. Re-ordering...", GetName()); + if (sum1 > TGeoShape::Tolerance()) { + Error("ComputeTwist", "Shape %s type Arb8: Vertices must be defined clockwise in XY planes. Re-ordering...", + GetName()); Double_t xtemp, ytemp; xtemp = fXY[1][0]; ytemp = fXY[1][1]; @@ -365,11 +371,11 @@ void TGeoArb8::ComputeTwist() } // Check for illegal crossings. Bool_t illegal_cross = kFALSE; - illegal_cross = TGeoShape::IsSegCrossing(fXY[0][0],fXY[0][1],fXY[1][0],fXY[1][1], - fXY[2][0],fXY[2][1],fXY[3][0],fXY[3][1]); + illegal_cross = + TGeoShape::IsSegCrossing(fXY[0][0], fXY[0][1], fXY[1][0], fXY[1][1], fXY[2][0], fXY[2][1], fXY[3][0], fXY[3][1]); if (!illegal_cross) - illegal_cross = TGeoShape::IsSegCrossing(fXY[4][0],fXY[4][1],fXY[5][0],fXY[5][1], - fXY[6][0],fXY[6][1],fXY[7][0],fXY[7][1]); + illegal_cross = TGeoShape::IsSegCrossing(fXY[4][0], fXY[4][1], fXY[5][0], fXY[5][1], fXY[6][0], fXY[6][1], + fXY[7][0], fXY[7][1]); if (illegal_cross) { Error("ComputeTwist", "Shape %s type Arb8: Malformed polygon with crossing opposite segments", GetName()); InspectShape(); @@ -381,7 +387,7 @@ void TGeoArb8::ComputeTwist() Double_t TGeoArb8::GetTwist(Int_t iseg) const { - return (!fTwist || iseg<0 || iseg>3) ? 0. : fTwist[iseg]; + return (!fTwist || iseg < 0 || iseg > 3) ? 0. : fTwist[iseg]; } //////////////////////////////////////////////////////////////////////////////// @@ -397,25 +403,25 @@ Double_t TGeoArb8::GetClosestEdge(const Double_t *point, Double_t *vert, Int_t & Double_t p1[2], p2[2]; Double_t lsq, ssq, dx, dy, dpx, dpy, u; Double_t umin = -1.; - Double_t safe=1E30; - for (i1=0; i1<4; i1++) { - if (TGeoShape::IsSameWithinTolerance(safe,0)) { + Double_t safe = 1E30; + for (i1 = 0; i1 < 4; i1++) { + if (TGeoShape::IsSameWithinTolerance(safe, 0)) { isegment = isegmin; return umin; } - i2 = (i1+1)%4; - p1[0] = vert[2*i1]; - p1[1] = vert[2*i1+1]; - p2[0] = vert[2*i2]; - p2[1] = vert[2*i2+1]; + i2 = (i1 + 1) % 4; + p1[0] = vert[2 * i1]; + p1[1] = vert[2 * i1 + 1]; + p2[0] = vert[2 * i2]; + p2[1] = vert[2 * i2 + 1]; dx = p2[0] - p1[0]; dy = p2[1] - p1[1]; dpx = point[0] - p1[0]; dpy = point[1] - p1[1]; - lsq = dx*dx + dy*dy; + lsq = dx * dx + dy * dy; // Current segment collapsed to a point - if (TGeoShape::IsSameWithinTolerance(lsq,0)) { - ssq = dpx*dpx + dpy*dpy; + if (TGeoShape::IsSameWithinTolerance(lsq, 0)) { + ssq = dpx * dpx + dpy * dpy; if (ssq < safe) { safe = ssq; isegmin = i1; @@ -424,24 +430,24 @@ Double_t TGeoArb8::GetClosestEdge(const Double_t *point, Double_t *vert, Int_t & continue; } // Projection fraction - u = (dpx*dx + dpy*dy)/lsq; + u = (dpx * dx + dpy * dy) / lsq; // If projection of P is outside P1P2 limits, take the distance from P to the closest of P1 and P2 - if (u>1) { + if (u > 1) { // Outside, closer to P2 - dpx = point[0]-p2[0]; - dpy = point[1]-p2[1]; + dpx = point[0] - p2[0]; + dpy = point[1] - p2[1]; u = -1.; } else { - if (u>=0) { + if (u >= 0) { // Projection inside - dpx -= u*dx; - dpy -= u*dy; + dpx -= u * dx; + dpy -= u * dy; } else { // Outside, closer to P1 u = -1.; } } - ssq = dpx*dpx + dpy*dpy; + ssq = dpx * dpx + dpy * dpy; if (ssq < safe) { safe = ssq; isegmin = i1; @@ -462,10 +468,10 @@ void TGeoArb8::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Double_t x0, y0, z0, x1, y1, z1, x2, y2, z2; Double_t ax, ay, az, bx, by, bz; Double_t fn; - safc = fDz-TMath::Abs(point[2]); - if (safc<10.*TGeoShape::Tolerance()) { - memset(norm,0,3*sizeof(Double_t)); - norm[2] = (dir[2]>0)?1:(-1); + safc = fDz - TMath::Abs(point[2]); + if (safc < 10. * TGeoShape::Tolerance()) { + memset(norm, 0, 3 * sizeof(Double_t)); + norm[2] = (dir[2] > 0) ? 1 : (-1); return; } Double_t vert[8]; @@ -473,35 +479,36 @@ void TGeoArb8::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ // Get the closest edge (point should be on this edge within tolerance) Int_t iseg; Double_t frac = GetClosestEdge(point, vert, iseg); - if (frac<0) frac = 0.; - Int_t jseg = (iseg+1)%4; - x0 = vert[2*iseg]; - y0 = vert[2*iseg+1]; + if (frac < 0) + frac = 0.; + Int_t jseg = (iseg + 1) % 4; + x0 = vert[2 * iseg]; + y0 = vert[2 * iseg + 1]; z0 = point[2]; - x2 = vert[2*jseg]; - y2 = vert[2*jseg+1]; + x2 = vert[2 * jseg]; + y2 = vert[2 * jseg + 1]; z2 = point[2]; - x0 += frac*(x2-x0); - y0 += frac*(y2-y0); - x1 = fXY[iseg+4][0]; - y1 = fXY[iseg+4][1]; + x0 += frac * (x2 - x0); + y0 += frac * (y2 - y0); + x1 = fXY[iseg + 4][0]; + y1 = fXY[iseg + 4][1]; z1 = fDz; - x1 += frac*(fXY[jseg+4][0]-x1); - y1 += frac*(fXY[jseg+4][1]-y1); - ax = x1-x0; - ay = y1-y0; - az = z1-z0; - bx = x2-x0; - by = y2-y0; - bz = z2-z0; + x1 += frac * (fXY[jseg + 4][0] - x1); + y1 += frac * (fXY[jseg + 4][1] - y1); + ax = x1 - x0; + ay = y1 - y0; + az = z1 - z0; + bx = x2 - x0; + by = y2 - y0; + bz = z2 - z0; // Cross product of the vector given by the section segment (that contains the point) at z=point[2] // and the vector connecting the point projection to its correspondent on the top edge (hard to swallow, isn't it?) - norm[0] = ay*bz-az*by; - norm[1] = az*bx-ax*bz; - norm[2] = ax*by-ay*bx; - fn = TMath::Sqrt(norm[0]*norm[0]+norm[1]*norm[1]+norm[2]*norm[2]); + norm[0] = ay * bz - az * by; + norm[1] = az * bx - ax * bz; + norm[2] = ax * by - ay * bx; + fn = TMath::Sqrt(norm[0] * norm[0] + norm[1] * norm[1] + norm[2] * norm[2]); // If point is on one edge, fn may be very small and the normal does not make sense - avoid divzero - if (fn<1E-10) { + if (fn < 1E-10) { norm[0] = 1.; norm[1] = 0.; norm[2] = 0.; @@ -511,7 +518,7 @@ void TGeoArb8::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ norm[2] /= fn; } // Make sure the dot product of the normal and the direction is positive. - if (dir[0]>-2. && dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2] < 0) { + if (dir[0] > -2. && dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -524,18 +531,19 @@ void TGeoArb8::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoArb8::Contains(const Double_t *point) const { // first check Z range - if (TMath::Abs(point[2]) > fDz) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; // compute intersection between Z plane containing point and the arb8 Double_t poly[8]; // memset(&poly[0], 0, 8*sizeof(Double_t)); // SetPlaneVertices(point[2], &poly[0]); - Double_t cf = 0.5*(fDz-point[2])/fDz; + Double_t cf = 0.5 * (fDz - point[2]) / fDz; Int_t i; - for (i=0; i<4; i++) { - poly[2*i] = fXY[i+4][0]+cf*(fXY[i][0]-fXY[i+4][0]); - poly[2*i+1] = fXY[i+4][1]+cf*(fXY[i][1]-fXY[i+4][1]); + for (i = 0; i < 4; i++) { + poly[2 * i] = fXY[i + 4][0] + cf * (fXY[i][0] - fXY[i + 4][0]); + poly[2 * i + 1] = fXY[i + 4][1] + cf * (fXY[i][1] - fXY[i + 4][1]); } - return InsidePolygon(point[0],point[1],poly); + return InsidePolygon(point[0], point[1], poly); } //////////////////////////////////////////////////////////////////////////////// @@ -547,116 +555,128 @@ Bool_t TGeoArb8::Contains(const Double_t *point) const Double_t TGeoArb8::DistToPlane(const Double_t *point, const Double_t *dir, Int_t ipl, Bool_t in) const { - Double_t xa,xb,xc,xd; - Double_t ya,yb,yc,yd; - Double_t eps = 10.*TGeoShape::Tolerance(); + Double_t xa, xb, xc, xd; + Double_t ya, yb, yc, yd; + Double_t eps = 10. * TGeoShape::Tolerance(); Double_t norm[3]; Double_t dirp[3]; Double_t ndotd = 0; - Int_t j = (ipl+1)%4; - xa=fXY[ipl][0]; - ya=fXY[ipl][1]; - xb=fXY[ipl+4][0]; - yb=fXY[ipl+4][1]; - xc=fXY[j][0]; - yc=fXY[j][1]; - xd=fXY[4+j][0]; - yd=fXY[4+j][1]; - Double_t dz2 =0.5/fDz; - Double_t tx1 =dz2*(xb-xa); - Double_t ty1 =dz2*(yb-ya); - Double_t tx2 =dz2*(xd-xc); - Double_t ty2 =dz2*(yd-yc); - Double_t dzp =fDz+point[2]; - Double_t xs1 =xa+tx1*dzp; - Double_t ys1 =ya+ty1*dzp; - Double_t xs2 =xc+tx2*dzp; - Double_t ys2 =yc+ty2*dzp; - Double_t dxs =xs2-xs1; - Double_t dys =ys2-ys1; - Double_t dtx =tx2-tx1; - Double_t dty =ty2-ty1; - Double_t a=(dtx*dir[1]-dty*dir[0]+(tx1*ty2-tx2*ty1)*dir[2])*dir[2]; - Double_t signa = TMath::Sign(1.,a); - Double_t b=dxs*dir[1]-dys*dir[0]+(dtx*point[1]-dty*point[0]+ty2*xs1-ty1*xs2 - +tx1*ys2-tx2*ys1)*dir[2]; - Double_t c=dxs*point[1]-dys*point[0]+xs1*ys2-xs2*ys1; - Double_t x1,x2,y1,y2,xp,yp,zi,s; - if (TMath::Abs(a)eps) { - memcpy(dirp,dir,3*sizeof(Double_t)); + if (TMath::Abs(b) < eps) + return TGeoShape::Big(); // Track parallel to surface + s = -c / b; + if (TMath::Abs(s) < 1.E-6 && TMath::Abs(TMath::Abs(point[2]) - fDz) > eps) { + memcpy(dirp, dir, 3 * sizeof(Double_t)); dirp[0] = -3; // Compute normal pointing outside - ((TGeoArb8*)this)->ComputeNormal(point,dirp,norm); - ndotd = dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2]; - if (!in) ndotd*=-1.; - if (ndotd>0) { - s = TMath::Max(0.,s); - zi = (point[0]-xs1)*(point[0]-xs2)+(point[1]-ys1)*(point[1]-ys2); - if (zi<=0) return s; + ((TGeoArb8 *)this)->ComputeNormal(point, dirp, norm); + ndotd = dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2]; + if (!in) + ndotd *= -1.; + if (ndotd > 0) { + s = TMath::Max(0., s); + zi = (point[0] - xs1) * (point[0] - xs2) + (point[1] - ys1) * (point[1] - ys2); + if (zi <= 0) + return s; } return TGeoShape::Big(); } - if (s<0) return TGeoShape::Big(); + if (s < 0) + return TGeoShape::Big(); } else { - Double_t d=b*b-4*a*c; - if (d<0) return TGeoShape::Big(); - Double_t smin=0.5*(-b-signa*TMath::Sqrt(d))/a; - Double_t smax=0.5*(-b+signa*TMath::Sqrt(d))/a; + Double_t d = b * b - 4 * a * c; + if (d < 0) + return TGeoShape::Big(); + Double_t smin = 0.5 * (-b - signa * TMath::Sqrt(d)) / a; + Double_t smax = 0.5 * (-b + signa * TMath::Sqrt(d)) / a; s = smin; - if (TMath::Abs(s)<1.E-6 && TMath::Abs(TMath::Abs(point[2])-fDz)>eps) { - memcpy(dirp,dir,3*sizeof(Double_t)); + if (TMath::Abs(s) < 1.E-6 && TMath::Abs(TMath::Abs(point[2]) - fDz) > eps) { + memcpy(dirp, dir, 3 * sizeof(Double_t)); dirp[0] = -3; // Compute normal pointing outside - ((TGeoArb8*)this)->ComputeNormal(point,dirp,norm); - ndotd = dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2]; - if (!in) ndotd*=-1.; - if (ndotd>0) return TMath::Max(0.,s); + ((TGeoArb8 *)this)->ComputeNormal(point, dirp, norm); + ndotd = dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2]; + if (!in) + ndotd *= -1.; + if (ndotd > 0) + return TMath::Max(0., s); s = 0.; // ignore } - if (s>eps) { + if (s > eps) { // Check smin - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)eps) { - memcpy(dirp,dir,3*sizeof(Double_t)); + s = smax; + if (TMath::Abs(s) < 1.E-6 && TMath::Abs(TMath::Abs(point[2]) - fDz) > eps) { + memcpy(dirp, dir, 3 * sizeof(Double_t)); dirp[0] = -3; // Compute normal pointing outside - ((TGeoArb8*)this)->ComputeNormal(point,dirp,norm); - ndotd = dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2]; - if (!in) ndotd*=-1.; - if (ndotd>0) s = TMath::Max(0.,s); - else s = TGeoShape::Big(); + ((TGeoArb8 *)this)->ComputeNormal(point, dirp, norm); + ndotd = dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2]; + if (!in) + ndotd *= -1.; + if (ndotd > 0) + s = TMath::Max(0., s); + else + s = TGeoShape::Big(); return s; } } - if (s>eps) { + if (s > eps) { // Check smin - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)=step) return TGeoShape::Big(); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); Double_t snext; // check Z planes - if (TMath::Abs(point[2])>fDz-1.E-8) { + if (TMath::Abs(point[2]) > fDz - 1.E-8) { Double_t pt[3]; - if (point[2]*dir[2]<0) { - pt[2]=fDz*TMath::Sign(1.,point[2]); - snext = TMath::Max((pt[2]-point[2])/dir[2],0.); - for (Int_t j=0; j<2; j++) pt[j]=point[j]+snext*dir[j]; - if (Contains(&pt[0])) return snext; + if (point[2] * dir[2] < 0) { + pt[2] = fDz * TMath::Sign(1., point[2]); + snext = TMath::Max((pt[2] - point[2]) / dir[2], 0.); + for (Int_t j = 0; j < 2; j++) + pt[j] = point[j] + snext * dir[j]; + if (Contains(&pt[0])) + return snext; } } // check lateral faces Double_t dist; snext = TGeoShape::Big(); - for (Int_t i=0; i<4; i++) { + for (Int_t i = 0; i < 4; i++) { dist = DistToPlane(point, dir, i, kFALSE); - if (dist0) distz=(fDz-point[2])/dir[2]; + if (dir[2] > 0) + distz = (fDz - point[2]) / dir[2]; pt[2] = fDz; } - for (i=0; i<4; i++) { - dist=DistToPlane(point, dir, i, kTRUE); - if (dist1.E10) return 0.; + if (dist < 0 || dist > 1.E10) + return 0.; return dist; #ifdef OLDALGORITHM -//#else -// compute distance to plane ipl : -// ipl=0 : points 0,4,1,5 -// ipl=1 : points 1,5,2,6 -// ipl=2 : points 2,6,3,7 -// ipl=3 : points 3,7,0,4 + //#else + // compute distance to plane ipl : + // ipl=0 : points 0,4,1,5 + // ipl=1 : points 1,5,2,6 + // ipl=2 : points 2,6,3,7 + // ipl=3 : points 3,7,0,4 Double_t distmin; Bool_t lateral_cross = kFALSE; - if (dir[2]<0) { - distmin=(-fDz-point[2])/dir[2]; + if (dir[2] < 0) { + distmin = (-fDz - point[2]) / dir[2]; } else { - if (dir[2]>0) distmin =(fDz-point[2])/dir[2]; - else distmin = TGeoShape::Big(); - } - Double_t dz2 =0.5/fDz; - Double_t xa,xb,xc,xd; - Double_t ya,yb,yc,yd; - Double_t eps = 100.*TGeoShape::Tolerance(); - for (Int_t ipl=0;ipl<4;ipl++) { - Int_t j = (ipl+1)%4; - xa=fXY[ipl][0]; - ya=fXY[ipl][1]; - xb=fXY[ipl+4][0]; - yb=fXY[ipl+4][1]; - xc=fXY[j][0]; - yc=fXY[j][1]; - xd=fXY[4+j][0]; - yd=fXY[4+j][1]; - - Double_t tx1 =dz2*(xb-xa); - Double_t ty1 =dz2*(yb-ya); - Double_t tx2 =dz2*(xd-xc); - Double_t ty2 =dz2*(yd-yc); - Double_t dzp =fDz+point[2]; - Double_t xs1 =xa+tx1*dzp; - Double_t ys1 =ya+ty1*dzp; - Double_t xs2 =xc+tx2*dzp; - Double_t ys2 =yc+ty2*dzp; - Double_t dxs =xs2-xs1; - Double_t dys =ys2-ys1; - Double_t dtx =tx2-tx1; - Double_t dty =ty2-ty1; - Double_t a=(dtx*dir[1]-dty*dir[0]+(tx1*ty2-tx2*ty1)*dir[2])*dir[2]; - Double_t b=dxs*dir[1]-dys*dir[0]+(dtx*point[1]-dty*point[0]+ty2*xs1-ty1*xs2 - +tx1*ys2-tx2*ys1)*dir[2]; - Double_t c=dxs*point[1]-dys*point[0]+xs1*ys2-xs2*ys1; - Double_t s=TGeoShape::Big(); - if (TMath::Abs(a)eps && s < distmin) { - distmin =s; - lateral_cross=kTRUE; + if (dir[2] > 0) + distmin = (fDz - point[2]) / dir[2]; + else + distmin = TGeoShape::Big(); + } + Double_t dz2 = 0.5 / fDz; + Double_t xa, xb, xc, xd; + Double_t ya, yb, yc, yd; + Double_t eps = 100. * TGeoShape::Tolerance(); + for (Int_t ipl = 0; ipl < 4; ipl++) { + Int_t j = (ipl + 1) % 4; + xa = fXY[ipl][0]; + ya = fXY[ipl][1]; + xb = fXY[ipl + 4][0]; + yb = fXY[ipl + 4][1]; + xc = fXY[j][0]; + yc = fXY[j][1]; + xd = fXY[4 + j][0]; + yd = fXY[4 + j][1]; + + Double_t tx1 = dz2 * (xb - xa); + Double_t ty1 = dz2 * (yb - ya); + Double_t tx2 = dz2 * (xd - xc); + Double_t ty2 = dz2 * (yd - yc); + Double_t dzp = fDz + point[2]; + Double_t xs1 = xa + tx1 * dzp; + Double_t ys1 = ya + ty1 * dzp; + Double_t xs2 = xc + tx2 * dzp; + Double_t ys2 = yc + ty2 * dzp; + Double_t dxs = xs2 - xs1; + Double_t dys = ys2 - ys1; + Double_t dtx = tx2 - tx1; + Double_t dty = ty2 - ty1; + Double_t a = (dtx * dir[1] - dty * dir[0] + (tx1 * ty2 - tx2 * ty1) * dir[2]) * dir[2]; + Double_t b = dxs * dir[1] - dys * dir[0] + + (dtx * point[1] - dty * point[0] + ty2 * xs1 - ty1 * xs2 + tx1 * ys2 - tx2 * ys1) * dir[2]; + Double_t c = dxs * point[1] - dys * point[0] + xs1 * ys2 - xs2 * ys1; + Double_t s = TGeoShape::Big(); + if (TMath::Abs(a) < eps) { + if (TMath::Abs(b) < eps) + continue; + s = -c / b; + if (s > eps && s < distmin) { + distmin = s; + lateral_cross = kTRUE; } continue; } - Double_t d=b*b-4*a*c; - if (d>=0.) { - if (a>0) s=0.5*(-b-TMath::Sqrt(d))/a; - else s=0.5*(-b+TMath::Sqrt(d))/a; - if (s>eps) { + Double_t d = b * b - 4 * a * c; + if (d >= 0.) { + if (a > 0) + s = 0.5 * (-b - TMath::Sqrt(d)) / a; + else + s = 0.5 * (-b + TMath::Sqrt(d)) / a; + if (s > eps) { if (s < distmin) { distmin = s; lateral_cross = kTRUE; } } else { - if (a>0) s=0.5*(-b+TMath::Sqrt(d))/a; - else s=0.5*(-b-TMath::Sqrt(d))/a; - if (s>eps && s < distmin) { - distmin =s; + if (a > 0) + s = 0.5 * (-b + TMath::Sqrt(d)) / a; + else + s = 0.5 * (-b - TMath::Sqrt(d)) / a; + if (s > eps && s < distmin) { + distmin = s; lateral_cross = kTRUE; } } @@ -798,19 +835,22 @@ Double_t TGeoArb8::DistFromInside(const Double_t *point, const Double_t *dir, In if (!lateral_cross) { // We have to make sure that track crosses the top or bottom. - if (distmin > 1.E10) return TGeoShape::Tolerance(); + if (distmin > 1.E10) + return TGeoShape::Tolerance(); Double_t pt[2]; - pt[0] = point[0]+distmin*dir[0]; - pt[1] = point[1]+distmin*dir[1]; + pt[0] = point[0] + distmin * dir[0]; + pt[1] = point[1] + distmin * dir[1]; // Check if propagated point is in the polygon Double_t poly[8]; Int_t i = 0; - if (dir[2]>0.) i=4; - for (Int_t j=0; j<4; j++) { - poly[2*j] = fXY[j+i][0]; - poly[2*j+1] = fXY[j+i][1]; + if (dir[2] > 0.) + i = 4; + for (Int_t j = 0; j < 4; j++) { + poly[2 * j] = fXY[j + i][0]; + poly[2 * j + 1] = fXY[j + i][1]; } - if (!InsidePolygon(pt[0],pt[1],poly)) return TGeoShape::Tolerance(); + if (!InsidePolygon(pt[0], pt[1], poly)) + return TGeoShape::Tolerance(); } return distmin; #endif @@ -834,10 +874,10 @@ Double_t TGeoArb8::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xlo = 0; xhi = 0; Double_t dx = 0; - if (iaxis==3) { + if (iaxis == 3) { xlo = -fDz; xhi = fDz; - dx = xhi-xlo; + dx = xhi - xlo; return dx; } return dx; @@ -853,14 +893,14 @@ void TGeoArb8::GetBoundingCylinder(Double_t *param) const Double_t rmaxsq = 0; Double_t rsq; Int_t i; - for (i=0; i<8; i++) { - rsq = fXY[i][0]*fXY[i][0] + fXY[i][1]*fXY[i][1]; + for (i = 0; i < 8; i++) { + rsq = fXY[i][0] * fXY[i][0] + fXY[i][1] * fXY[i][1]; rmaxsq = TMath::Max(rsq, rmaxsq); } - param[0] = 0.; // Rmin - param[1] = rmaxsq; // Rmax - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[0] = 0.; // Rmin + param[1] = rmaxsq; // Rmax + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -868,7 +908,7 @@ void TGeoArb8::GetBoundingCylinder(Double_t *param) const Int_t TGeoArb8::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const { - dx=dy=dz=0; + dx = dy = dz = 0; if (mat->IsRotation()) { Error("GetFittingBox", "cannot handle parametrized rotated volumes"); return 1; // ### rotation not accepted ### @@ -886,14 +926,14 @@ Int_t TGeoArb8::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ dd[1] = parambox->GetDY(); dd[2] = parambox->GetDZ(); //-> check if Z range is fixed - if (dd[2]<0) { - dd[2] = TMath::Min(origin[2]+fDz, fDz-origin[2]); - if (dd[2]<0) { + if (dd[2] < 0) { + dd[2] = TMath::Min(origin[2] + fDz, fDz - origin[2]); + if (dd[2] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } } - if (dd[0]>=0 && dd[1]>=0) { + if (dd[0] >= 0 && dd[1] >= 0) { dx = dd[0]; dy = dd[1]; dz = dd[2]; @@ -902,14 +942,15 @@ Int_t TGeoArb8::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ //-> check now vertices at Z = origin[2] +/- dd[2] Double_t upper[8]; Double_t lower[8]; - SetPlaneVertices(origin[2]-dd[2], lower); - SetPlaneVertices(origin[2]+dd[2], upper); - for (Int_t iaxis=0; iaxis<2; iaxis++) { - if (dd[iaxis]>=0) continue; + SetPlaneVertices(origin[2] - dd[2], lower); + SetPlaneVertices(origin[2] + dd[2], upper); + for (Int_t iaxis = 0; iaxis < 2; iaxis++) { + if (dd[iaxis] >= 0) + continue; Double_t ddmin = TGeoShape::Big(); - for (Int_t ivert=0; ivert<4; ivert++) { - ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis]-lower[2*ivert+iaxis])); - ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis]-upper[2*ivert+iaxis])); + for (Int_t ivert = 0; ivert < 4; ivert++) { + ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis] - lower[2 * ivert + iaxis])); + ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis] - upper[2 * ivert + iaxis])); } dd[iaxis] = ddmin; } @@ -927,19 +968,21 @@ void TGeoArb8::GetPlaneNormal(Double_t *p1, Double_t *p2, Double_t *p3, Double_t Double_t cross = 0.; Double_t v1[3], v2[3]; Int_t i; - for (i=0; i<3; i++) { + for (i = 0; i < 3; i++) { v1[i] = p2[i] - p1[i]; v2[i] = p3[i] - p1[i]; } - norm[0] = v1[1]*v2[2]-v1[2]*v2[1]; - cross += norm[0]*norm[0]; - norm[1] = v1[2]*v2[0]-v1[0]*v2[2]; - cross += norm[1]*norm[1]; - norm[2] = v1[0]*v2[1]-v1[1]*v2[0]; - cross += norm[2]*norm[2]; - if (TMath::Abs(cross) < TGeoShape::Tolerance()) return; - cross = 1./TMath::Sqrt(cross); - for (i=0; i<3; i++) norm[i] *= cross; + norm[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross += norm[0] * norm[0]; + norm[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross += norm[1] * norm[1]; + norm[2] = v1[0] * v2[1] - v1[1] * v2[0]; + cross += norm[2] * norm[2]; + if (TMath::Abs(cross) < TGeoShape::Tolerance()) + return; + cross = 1. / TMath::Sqrt(cross); + for (i = 0; i < 3; i++) + norm[i] *= cross; } //////////////////////////////////////////////////////////////////////////////// @@ -953,54 +996,54 @@ void TGeoArb8::GetPlaneNormal(Double_t *p1, Double_t *p2, Double_t *p3, Double_t Bool_t TGeoArb8::GetPointsOnFacet(Int_t /*index*/, Int_t /*npoints*/, Double_t * /* array */) const { return kFALSE; -/* - if (index<0 || index>6) return kFALSE; - if (index==0) { - // Just generate same number of points on each facet - Int_t npts = npoints/6.; - Int_t count = 0; - for (Int_t ifacet=0; ifacet<6; ifacet++) { - if (GetPointsOnFacet(ifacet+1, npts, &array[3*count])) count += npts; - if (ifacet<5) npts = (npoints-count)/(5.-ifacet); + /* + if (index<0 || index>6) return kFALSE; + if (index==0) { + // Just generate same number of points on each facet + Int_t npts = npoints/6.; + Int_t count = 0; + for (Int_t ifacet=0; ifacet<6; ifacet++) { + if (GetPointsOnFacet(ifacet+1, npts, &array[3*count])) count += npts; + if (ifacet<5) npts = (npoints-count)/(5.-ifacet); + } + if (count>0) return kTRUE; + return kFALSE; } - if (count>0) return kTRUE; - return kFALSE; - } - Double_t z, cf; - Double_t xmin=TGeoShape::Big(); - Double_t xmax=-xmin; - Double_t ymin=TGeoShape::Big(); - Double_t ymax=-ymin; - Double_t dy=0.; - Double_t poly[8]; - Double_t point[2]; - Int_t i; - if (index==1 || index==6) { - z = (index==1)?-fDz:fDz; - cf = 0.5*(fDz-z)/fDz; - for (i=0; i<4; i++) { - poly[2*i] = fXY[i+4][0]+cf*(fXY[i][0]-fXY[i+4][0]); - poly[2*i+1] = fXY[i+4][1]+cf*(fXY[i][1]-fXY[i+4][1]); - xmin = TMath::Min(xmin, poly[2*i]); - xmax = TMath::Max(xmax, poly[2*i]); - ymin = TMath::Min(ymin, poly[2*i]); - ymax = TMath::Max(ymax, poly[2*i]); + Double_t z, cf; + Double_t xmin=TGeoShape::Big(); + Double_t xmax=-xmin; + Double_t ymin=TGeoShape::Big(); + Double_t ymax=-ymin; + Double_t dy=0.; + Double_t poly[8]; + Double_t point[2]; + Int_t i; + if (index==1 || index==6) { + z = (index==1)?-fDz:fDz; + cf = 0.5*(fDz-z)/fDz; + for (i=0; i<4; i++) { + poly[2*i] = fXY[i+4][0]+cf*(fXY[i][0]-fXY[i+4][0]); + poly[2*i+1] = fXY[i+4][1]+cf*(fXY[i][1]-fXY[i+4][1]); + xmin = TMath::Min(xmin, poly[2*i]); + xmax = TMath::Max(xmax, poly[2*i]); + ymin = TMath::Min(ymin, poly[2*i]); + ymax = TMath::Max(ymax, poly[2*i]); + } } - } - Int_t nshoot = 0; - Int_t nmiss = 0; - for (i=0; iRndm(); - point[1] = ymin + (ymax-ymin)*gRandom->Rndm(); - } + Int_t nshoot = 0; + Int_t nmiss = 0; + for (i=0; iRndm(); + point[1] = ymin + (ymax-ymin)*gRandom->Rndm(); + } - return InsidePolygon(point[0],point[1],poly); -*/ + return InsidePolygon(point[0],point[1],poly); + */ } //////////////////////////////////////////////////////////////////////////////// @@ -1008,17 +1051,18 @@ Bool_t TGeoArb8::GetPointsOnFacet(Int_t /*index*/, Int_t /*npoints*/, Double_t * Bool_t TGeoArb8::InsidePolygon(Double_t x, Double_t y, Double_t *pts) { - Int_t i,j; - Double_t x1,y1,x2,y2; + Int_t i, j; + Double_t x1, y1, x2, y2; Double_t cross; - for (i=0; i<4; i++) { - j = (i+1)%4; - x1 = pts[i<<1]; - y1 = pts[(i<<1)+1]; - x2 = pts[j<<1]; - y2 = pts[(j<<1)+1]; - cross = (x-x1)*(y2-y1)-(y-y1)*(x2-x1); - if (cross<0) return kFALSE; + for (i = 0; i < 4; i++) { + j = (i + 1) % 4; + x1 = pts[i << 1]; + y1 = pts[(i << 1) + 1]; + x2 = pts[j << 1]; + y2 = pts[(j << 1) + 1]; + cross = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1); + if (cross < 0) + return kFALSE; } return kTRUE; } @@ -1029,10 +1073,10 @@ Bool_t TGeoArb8::InsidePolygon(Double_t x, Double_t y, Double_t *pts) void TGeoArb8::InspectShape() const { printf("*** Shape %s: TGeoArb8 ***\n", GetName()); - if (IsTwisted()) printf(" = TWISTED\n"); - for (Int_t ip=0; ip<8; ip++) { - printf(" point #%i : x=%11.5f y=%11.5f z=%11.5f\n", - ip, fXY[ip][0], fXY[ip][1], fDz*((ip<4)?-1:1)); + if (IsTwisted()) + printf(" = TWISTED\n"); + for (Int_t ip = 0; ip < 8; ip++) { + printf(" point #%i : x=%11.5f y=%11.5f z=%11.5f\n", ip, fXY[ip][0], fXY[ip][1], fDz * ((ip < 4) ? -1 : 1)); } printf(" Bounding box:\n"); TGeoBBox::InspectShape(); @@ -1043,75 +1087,84 @@ void TGeoArb8::InspectShape() const Double_t TGeoArb8::Safety(const Double_t *point, Bool_t in) const { - Double_t safz = fDz-TMath::Abs(point[2]); - if (!in) safz = -safz; + Double_t safz = fDz - TMath::Abs(point[2]); + if (!in) + safz = -safz; Int_t iseg; Double_t safe = TGeoShape::Big(); Double_t lsq, ssq, dx, dy, dpx, dpy, u; if (IsTwisted()) { if (!in) { - if (!TGeoBBox::Contains(point)) return TGeoBBox::Safety(point,kFALSE); + if (!TGeoBBox::Contains(point)) + return TGeoBBox::Safety(point, kFALSE); } // Point is also in the bounding box ;-( // Compute closest distance to any segment Double_t vert[8]; Double_t *p1, *p2; - Int_t isegmin=0; + Int_t isegmin = 0; Double_t umin = 0.; - SetPlaneVertices (point[2], vert); - for (iseg=0; iseg<4; iseg++) { - if (safe1) { - dpx = point[0]-p2[0]; - dpy = point[1]-p2[1]; + lsq = dx * dx + dy * dy; + u = (dpx * dx + dpy * dy) / lsq; + if (u > 1) { + dpx = point[0] - p2[0]; + dpy = point[1] - p2[1]; } else { - if (u>=0) { - dpx -= u*dx; - dpy -= u*dy; + if (u >= 0) { + dpx -= u * dx; + dpy -= u * dy; } } - ssq = dpx*dpx + dpy*dpy; + ssq = dpx * dpx + dpy * dpy; if (ssq < safe) { isegmin = iseg; umin = u; safe = ssq; } } - if (umin<0) umin = 0.; - if (umin>1) { - isegmin = (isegmin+1)%4; + if (umin < 0) + umin = 0.; + if (umin > 1) { + isegmin = (isegmin + 1) % 4; umin = 0.; } Int_t i1 = isegmin; - Int_t i2 = (isegmin+1)%4; - Double_t dx1 = fXY[i2][0]-fXY[i1][0]; - Double_t dx2 = fXY[i2+4][0]-fXY[i1+4][0]; - Double_t dy1 = fXY[i2][1]-fXY[i1][1]; - Double_t dy2 = fXY[i2+4][1]-fXY[i1+4][1]; - dx = dx1 + umin*(dx2-dx1); - dy = dy1 + umin*(dy2-dy1); - safe *= 1.- 4.*fDz*fDz/(dx*dx+dy*dy+4.*fDz*fDz); + Int_t i2 = (isegmin + 1) % 4; + Double_t dx1 = fXY[i2][0] - fXY[i1][0]; + Double_t dx2 = fXY[i2 + 4][0] - fXY[i1 + 4][0]; + Double_t dy1 = fXY[i2][1] - fXY[i1][1]; + Double_t dy2 = fXY[i2 + 4][1] - fXY[i1 + 4][1]; + dx = dx1 + umin * (dx2 - dx1); + dy = dy1 + umin * (dy2 - dy1); + safe *= 1. - 4. * fDz * fDz / (dx * dx + dy * dy + 4. * fDz * fDz); safe = TMath::Sqrt(safe); - if (in) return TMath::Min(safz,safe); - return TMath::Max(safz,safe); + if (in) + return TMath::Min(safz, safe); + return TMath::Max(safz, safe); } Double_t saf[5]; saf[0] = safz; - for (iseg=0; iseg<4; iseg++) saf[iseg+1] = SafetyToFace(point,iseg,in); - if (in) safe = saf[TMath::LocMin(5, saf)]; - else safe = saf[TMath::LocMax(5, saf)]; - if (safe<0) return 0.; + for (iseg = 0; iseg < 4; iseg++) + saf[iseg + 1] = SafetyToFace(point, iseg, in); + if (in) + safe = saf[TMath::LocMin(5, saf)]; + else + safe = saf[TMath::LocMax(5, saf)]; + if (safe < 0) + return 0.; return safe; } @@ -1122,7 +1175,7 @@ Double_t TGeoArb8::Safety(const Double_t *point, Bool_t in) const Double_t TGeoArb8::SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) const { Double_t vertices[12]; - Int_t ipln = (iseg+1)%4; + Int_t ipln = (iseg + 1) % 4; // point 1 vertices[0] = fXY[iseg][0]; vertices[1] = fXY[iseg][1]; @@ -1132,12 +1185,12 @@ Double_t TGeoArb8::SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) co vertices[4] = fXY[ipln][1]; vertices[5] = -fDz; // point 3 - vertices[6] = fXY[ipln+4][0]; - vertices[7] = fXY[ipln+4][1]; + vertices[6] = fXY[ipln + 4][0]; + vertices[7] = fXY[ipln + 4][1]; vertices[8] = fDz; // point 4 - vertices[9] = fXY[iseg+4][0]; - vertices[10] = fXY[iseg+4][1]; + vertices[9] = fXY[iseg + 4][0]; + vertices[10] = fXY[iseg + 4][1]; vertices[11] = fDz; Double_t safe; Double_t norm[3]; @@ -1145,13 +1198,15 @@ Double_t TGeoArb8::SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) co p1 = &vertices[0]; p2 = &vertices[9]; p3 = &vertices[6]; - if (IsSamePoint(p2,p3)) { + if (IsSamePoint(p2, p3)) { p3 = &vertices[3]; - if (IsSamePoint(p1,p3)) return -TGeoShape::Big(); // skip single segment + if (IsSamePoint(p1, p3)) + return -TGeoShape::Big(); // skip single segment } - GetPlaneNormal(p1,p2,p3,norm); - safe = (point[0]-p1[0])*norm[0]+(point[1]-p1[1])*norm[1]+(point[2]-p1[2])*norm[2]; - if (in) return (-safe); + GetPlaneNormal(p1, p2, p3, norm); + safe = (point[0] - p1[0]) * norm[0] + (point[1] - p1[1]) * norm[1] + (point[2] - p1[2]) * norm[2]; + if (in) + return (-safe); return safe; } @@ -1160,7 +1215,8 @@ Double_t TGeoArb8::SafetyToFace(const Double_t *point, Int_t iseg, Bool_t in) co void TGeoArb8::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " vert[0] = " << fXY[0][0] << ";" << std::endl; @@ -1188,10 +1244,10 @@ void TGeoArb8::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) void TGeoArb8::SetPlaneVertices(Double_t zpl, Double_t *vertices) const { - Double_t cf = 0.5*(fDz-zpl)/fDz; - for (Int_t i=0; i<4; i++) { - vertices[2*i] = fXY[i+4][0]+cf*(fXY[i][0]-fXY[i+4][0]); - vertices[2*i+1] = fXY[i+4][1]+cf*(fXY[i][1]-fXY[i+4][1]); + Double_t cf = 0.5 * (fDz - zpl) / fDz; + for (Int_t i = 0; i < 4; i++) { + vertices[2 * i] = fXY[i + 4][0] + cf * (fXY[i][0] - fXY[i + 4][0]); + vertices[2 * i + 1] = fXY[i + 4][1] + cf * (fXY[i][1] - fXY[i + 4][1]); } } @@ -1204,10 +1260,10 @@ void TGeoArb8::SetPlaneVertices(Double_t zpl, Double_t *vertices) const void TGeoArb8::SetDimensions(Double_t *param) { - fDz = param[0]; - for (Int_t i=0; i<8; i++) { - fXY[i][0] = param[2*i+1]; - fXY[i][1] = param[2*i+2]; + fDz = param[0]; + for (Int_t i = 0; i < 8; i++) { + fXY[i][0] = param[2 * i + 1]; + fXY[i][1] = param[2 * i + 2]; } ComputeTwist(); ComputeBBox(); @@ -1218,10 +1274,10 @@ void TGeoArb8::SetDimensions(Double_t *param) void TGeoArb8::SetPoints(Double_t *points) const { - for (Int_t i=0; i<8; i++) { - points[3*i] = fXY[i][0]; - points[3*i+1] = fXY[i][1]; - points[3*i+2] = (i<4)?-fDz:fDz; + for (Int_t i = 0; i < 8; i++) { + points[3 * i] = fXY[i][0]; + points[3 * i + 1] = fXY[i][1]; + points[3 * i + 2] = (i < 4) ? -fDz : fDz; } } @@ -1230,10 +1286,10 @@ void TGeoArb8::SetPoints(Double_t *points) const void TGeoArb8::SetPoints(Float_t *points) const { - for (Int_t i=0; i<8; i++) { - points[3*i] = fXY[i][0]; - points[3*i+1] = fXY[i][1]; - points[3*i+2] = (i<4)?-fDz:fDz; + for (Int_t i = 0; i < 8; i++) { + points[3 * i] = fXY[i][0]; + points[3 * i + 1] = fXY[i][1]; + points[3 * i + 2] = (i < 4) ? -fDz : fDz; } } @@ -1242,7 +1298,7 @@ void TGeoArb8::SetPoints(Float_t *points) const void TGeoArb8::SetVertex(Int_t vnum, Double_t x, Double_t y) { - if (vnum<0 || vnum >7) { + if (vnum < 0 || vnum > 7) { Error("SetVertex", "Invalid vertex number"); return; } @@ -1282,7 +1338,8 @@ void TGeoArb8::Streamer(TBuffer &R__b) void TGeoArb8::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i0) distmin =(fDz-point[2])/dir[2]; - else distmin = TGeoShape::Big(); - } - Double_t xa,xb,xc; - Double_t ya,yb,yc; - for (Int_t ipl=0;ipl<4;ipl++) { - Int_t j = (ipl+1)%4; - xa=fXY[ipl][0]; - ya=fXY[ipl][1]; - xb=fXY[ipl+4][0]; - yb=fXY[ipl+4][1]; - xc=fXY[j][0]; - yc=fXY[j][1]; - Double_t ax,ay,az; - ax = xb-xa; - ay = yb-ya; - az = 2.*fDz; - Double_t bx,by; - bx = xc-xa; - by = yc-ya; - Double_t ddotn = -dir[0]*az*by + dir[1]*az*bx+dir[2]*(ax*by-ay*bx); - if (ddotn<=0) continue; // entering - Double_t saf = -(point[0]-xa)*az*by + (point[1]-ya)*az*bx + (point[2]+fDz)*(ax*by-ay*bx); - if (saf>=0.0) return 0.0; - Double_t s = -saf/ddotn; - if (s 0) + distmin = (fDz - point[2]) / dir[2]; + else + distmin = TGeoShape::Big(); + } + Double_t xa, xb, xc; + Double_t ya, yb, yc; + for (Int_t ipl = 0; ipl < 4; ipl++) { + Int_t j = (ipl + 1) % 4; + xa = fXY[ipl][0]; + ya = fXY[ipl][1]; + xb = fXY[ipl + 4][0]; + yb = fXY[ipl + 4][1]; + xc = fXY[j][0]; + yc = fXY[j][1]; + Double_t ax, ay, az; + ax = xb - xa; + ay = yb - ya; + az = 2. * fDz; + Double_t bx, by; + bx = xc - xa; + by = yc - ya; + Double_t ddotn = -dir[0] * az * by + dir[1] * az * bx + dir[2] * (ax * by - ay * bx); + if (ddotn <= 0) + continue; // entering + Double_t saf = -(point[0] - xa) * az * by + (point[1] - ya) * az * bx + (point[2] + fDz) * (ax * by - ay * bx); + if (saf >= 0.0) + return 0.0; + Double_t s = -saf / ddotn; + if (s < distmin) + distmin = s; } return distmin; } @@ -1492,111 +1572,127 @@ Double_t TGeoTrap::DistFromInside(const Double_t *point, const Double_t *dir, In //////////////////////////////////////////////////////////////////////////////// /// Compute distance from outside point to surface of the trapezoid -Double_t TGeoTrap::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTrap::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); // compute distance to get outside this shape Bool_t in = kTRUE; Double_t pts[8]; Double_t xnew, ynew, znew; - Int_t i,j; - if (point[2]<-fDz+TGeoShape::Tolerance()) { - if (dir[2] < TGeoShape::Tolerance()) return TGeoShape::Big(); + Int_t i, j; + if (point[2] < -fDz + TGeoShape::Tolerance()) { + if (dir[2] < TGeoShape::Tolerance()) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = -(fDz+point[2])/dir[2]; - xnew = point[0] + snxt*dir[0]; - ynew = point[1] + snxt*dir[1]; - for (i=0;i<4;i++) { - j = i<<1; + Double_t snxt = -(fDz + point[2]) / dir[2]; + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + for (i = 0; i < 4; i++) { + j = i << 1; pts[j] = fXY[i][0]; - pts[j+1] = fXY[i][1]; + pts[j + 1] = fXY[i][1]; } - if (InsidePolygon(xnew,ynew,pts)) return snxt; - } else if (point[2]>fDz-TGeoShape::Tolerance()) { - if (dir[2] > -TGeoShape::Tolerance()) return TGeoShape::Big(); + if (InsidePolygon(xnew, ynew, pts)) + return snxt; + } else if (point[2] > fDz - TGeoShape::Tolerance()) { + if (dir[2] > -TGeoShape::Tolerance()) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (fDz-point[2])/dir[2]; - xnew = point[0] + snxt*dir[0]; - ynew = point[1] + snxt*dir[1]; - for (i=0;i<4;i++) { - j = i<<1; - pts[j] = fXY[i+4][0]; - pts[j+1] = fXY[i+4][1]; + Double_t snxt = (fDz - point[2]) / dir[2]; + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + for (i = 0; i < 4; i++) { + j = i << 1; + pts[j] = fXY[i + 4][0]; + pts[j + 1] = fXY[i + 4][1]; } - if (InsidePolygon(xnew,ynew,pts)) return snxt; + if (InsidePolygon(xnew, ynew, pts)) + return snxt; } // check lateral faces - Double_t dz2 =0.5/fDz; - Double_t xa,xb,xc,xd; - Double_t ya,yb,yc,yd; - Double_t ax,ay,az; - Double_t bx,by; + Double_t dz2 = 0.5 / fDz; + Double_t xa, xb, xc, xd; + Double_t ya, yb, yc, yd; + Double_t ax, ay, az; + Double_t bx, by; Double_t ddotn, saf; Double_t safmin = TGeoShape::Big(); Bool_t exiting = kFALSE; - for (i=0; i<4; i++) { - j = (i+1)%4; - xa=fXY[i][0]; - ya=fXY[i][1]; - xb=fXY[i+4][0]; - yb=fXY[i+4][1]; - xc=fXY[j][0]; - yc=fXY[j][1]; - xd=fXY[4+j][0]; - yd=fXY[4+j][1]; - ax = xb-xa; - ay = yb-ya; - az = 2.*fDz; - bx = xc-xa; - by = yc-ya; - ddotn = -dir[0]*az*by + dir[1]*az*bx+dir[2]*(ax*by-ay*bx); - saf = (point[0]-xa)*az*by - (point[1]-ya)*az*bx - (point[2]+fDz)*(ax*by-ay*bx); - - if (saf<=0) { + for (i = 0; i < 4; i++) { + j = (i + 1) % 4; + xa = fXY[i][0]; + ya = fXY[i][1]; + xb = fXY[i + 4][0]; + yb = fXY[i + 4][1]; + xc = fXY[j][0]; + yc = fXY[j][1]; + xd = fXY[4 + j][0]; + yd = fXY[4 + j][1]; + ax = xb - xa; + ay = yb - ya; + az = 2. * fDz; + bx = xc - xa; + by = yc - ya; + ddotn = -dir[0] * az * by + dir[1] * az * bx + dir[2] * (ax * by - ay * bx); + saf = (point[0] - xa) * az * by - (point[1] - ya) * az * bx - (point[2] + fDz) * (ax * by - ay * bx); + + if (saf <= 0) { // face visible from point outside in = kFALSE; - if (ddotn>=0) return TGeoShape::Big(); - Double_t snxt = saf/ddotn; - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew)<=fDz) { - xnew = point[0]+snxt*dir[0]; - ynew = point[1]+snxt*dir[1]; - Double_t tx1 =dz2*(xb-xa); - Double_t ty1 =dz2*(yb-ya); - Double_t tx2 =dz2*(xd-xc); - Double_t ty2 =dz2*(yd-yc); - Double_t dzp =fDz+znew; - Double_t xs1 =xa+tx1*dzp; - Double_t ys1 =ya+ty1*dzp; - Double_t xs2 =xc+tx2*dzp; - Double_t ys2 =yc+ty2*dzp; - if (TMath::Abs(xs1-xs2)>TMath::Abs(ys1-ys2)) { - if ((xnew-xs1)*(xs2-xnew)>=0) return snxt; + if (ddotn >= 0) + return TGeoShape::Big(); + Double_t snxt = saf / ddotn; + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) <= fDz) { + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + Double_t tx1 = dz2 * (xb - xa); + Double_t ty1 = dz2 * (yb - ya); + Double_t tx2 = dz2 * (xd - xc); + Double_t ty2 = dz2 * (yd - yc); + Double_t dzp = fDz + znew; + Double_t xs1 = xa + tx1 * dzp; + Double_t ys1 = ya + ty1 * dzp; + Double_t xs2 = xc + tx2 * dzp; + Double_t ys2 = yc + ty2 * dzp; + if (TMath::Abs(xs1 - xs2) > TMath::Abs(ys1 - ys2)) { + if ((xnew - xs1) * (xs2 - xnew) >= 0) + return snxt; } else { - if ((ynew-ys1)*(ys2-ynew)>=0) return snxt; + if ((ynew - ys1) * (ys2 - ynew) >= 0) + return snxt; } } } else { - if (saf=0) exiting = kTRUE; - else exiting = kFALSE; + if (ddotn >= 0) + exiting = kTRUE; + else + exiting = kFALSE; } } } // Check also Z boundaries (point may be inside and close to Z) - Christian Hammann saf = fDz - TMath::Abs(point[2]); - if (saf>0 && saf 0)?kTRUE:kFALSE; - if (!in) return TGeoShape::Big(); - if (exiting) return TGeoShape::Big(); + if (saf > 0 && saf < safmin) + exiting = (point[2] * dir[2] > 0) ? kTRUE : kFALSE; + if (!in) + return TGeoShape::Big(); + if (exiting) + return TGeoShape::Big(); return 0.0; } @@ -1607,19 +1703,19 @@ Double_t TGeoTrap::DistFromOutside(const Double_t *point, const Double_t *dir, I /// divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoTrap::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoTrap::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached - if (iaxis!=3) { + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached + if (iaxis != 3) { Error("Divide", "cannot divide trapezoids on other axis than Z"); return 0; } - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; Double_t points_lo[8]; Double_t points_hi[8]; finder = new TGeoPatternTrapZ(voldiv, ndiv, start, end); @@ -1627,26 +1723,26 @@ TGeoVolume *TGeoTrap::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi finder->SetDivIndex(voldiv->GetNdaughters()); opt = "Z"; vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - Double_t txz = ((TGeoPatternTrapZ*)finder)->GetTxz(); - Double_t tyz = ((TGeoPatternTrapZ*)finder)->GetTyz(); - Double_t zmin, zmax, ox,oy,oz; - for (Int_t idiv=0; idivGetTxz(); + Double_t tyz = ((TGeoPatternTrapZ *)finder)->GetTyz(); + Double_t zmin, zmax, ox, oy, oz; + for (Int_t idiv = 0; idiv < ndiv; idiv++) { + zmin = start + idiv * step; + zmax = start + (idiv + 1) * step; + oz = start + idiv * step + step / 2; + ox = oz * txz; + oy = oz * tyz; SetPlaneVertices(zmin, &points_lo[0]); SetPlaneVertices(zmax, &points_hi[0]); - shape = new TGeoTrap(step/2, fTheta, fPhi); - for (Int_t vert1=0; vert1<4; vert1++) - ((TGeoArb8*)shape)->SetVertex(vert1, points_lo[2*vert1]-ox, points_lo[2*vert1+1]-oy); - for (Int_t vert2=0; vert2<4; vert2++) - ((TGeoArb8*)shape)->SetVertex(vert2+4, points_hi[2*vert2]-ox, points_hi[2*vert2+1]-oy); + shape = new TGeoTrap(step / 2, fTheta, fPhi); + for (Int_t vert1 = 0; vert1 < 4; vert1++) + ((TGeoArb8 *)shape)->SetVertex(vert1, points_lo[2 * vert1] - ox, points_lo[2 * vert1 + 1] - oy); + for (Int_t vert2 = 0; vert2 < 4; vert2++) + ((TGeoArb8 *)shape)->SetVertex(vert2 + 4, points_hi[2 * vert2] - ox, points_hi[2 * vert2 + 1] - oy); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); vmulti->AddVolume(vol); voldiv->AddNodeOffset(vol, idiv, oz, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); } return vmulti; } @@ -1657,32 +1753,47 @@ TGeoVolume *TGeoTrap::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi TGeoShape *TGeoTrap::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (mother->IsRunTimeShape()) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; } Double_t dz, h1, bl1, tl1, h2, bl2, tl2; - if (fDz<0) dz=((TGeoTrap*)mother)->GetDz(); - else dz=fDz; + if (fDz < 0) + dz = ((TGeoTrap *)mother)->GetDz(); + else + dz = fDz; - if (fH1<0) h1 = ((TGeoTrap*)mother)->GetH1(); - else h1 = fH1; + if (fH1 < 0) + h1 = ((TGeoTrap *)mother)->GetH1(); + else + h1 = fH1; - if (fH2<0) h2 = ((TGeoTrap*)mother)->GetH2(); - else h2 = fH2; + if (fH2 < 0) + h2 = ((TGeoTrap *)mother)->GetH2(); + else + h2 = fH2; - if (fBl1<0) bl1 = ((TGeoTrap*)mother)->GetBl1(); - else bl1 = fBl1; + if (fBl1 < 0) + bl1 = ((TGeoTrap *)mother)->GetBl1(); + else + bl1 = fBl1; - if (fBl2<0) bl2 = ((TGeoTrap*)mother)->GetBl2(); - else bl2 = fBl2; + if (fBl2 < 0) + bl2 = ((TGeoTrap *)mother)->GetBl2(); + else + bl2 = fBl2; - if (fTl1<0) tl1 = ((TGeoTrap*)mother)->GetTl1(); - else tl1 = fTl1; + if (fTl1 < 0) + tl1 = ((TGeoTrap *)mother)->GetTl1(); + else + tl1 = fTl1; - if (fTl2<0) tl2 = ((TGeoTrap*)mother)->GetTl2(); - else tl2 = fTl2; + if (fTl2 < 0) + tl2 = ((TGeoTrap *)mother)->GetTl2(); + else + tl2 = fTl2; return (new TGeoTrap(dz, fTheta, fPhi, h1, bl1, tl1, fAlpha1, h2, bl2, tl2, fAlpha2)); } @@ -1695,53 +1806,57 @@ Double_t TGeoTrap::Safety(const Double_t *point, Bool_t in) const Double_t saf[5]; Double_t norm[3]; // normal to current facette Int_t i, j; // current facette index - Double_t x0, y0, z0=-fDz, x1, y1, z1=fDz, x2, y2; - Double_t ax, ay, az=z1-z0, bx, by; + Double_t x0, y0, z0 = -fDz, x1, y1, z1 = fDz, x2, y2; + Double_t ax, ay, az = z1 - z0, bx, by; Double_t fn, safe; //---> compute safety for lateral planes - for (i=0; i<4; i++) { - if (in) saf[i] = TGeoShape::Big(); - else saf[i] = 0.; + for (i = 0; i < 4; i++) { + if (in) + saf[i] = TGeoShape::Big(); + else + saf[i] = 0.; x0 = fXY[i][0]; y0 = fXY[i][1]; - x1 = fXY[i+4][0]; - y1 = fXY[i+4][1]; - ax = x1-x0; - ay = y1-y0; - j = (i+1)%4; + x1 = fXY[i + 4][0]; + y1 = fXY[i + 4][1]; + ax = x1 - x0; + ay = y1 - y0; + j = (i + 1) % 4; x2 = fXY[j][0]; y2 = fXY[j][1]; - bx = x2-x0; - by = y2-y0; - if (TMath::Abs(bx) safe) safe = saf[j]; } @@ -1753,20 +1868,22 @@ Double_t TGeoTrap::Safety(const Double_t *point, Bool_t in) const void TGeoTrap::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " theta = " << fTheta << ";" << std::endl; out << " phi = " << fPhi << ";" << std::endl; - out << " h1 = " << fH1<< ";" << std::endl; - out << " bl1 = " << fBl1<< ";" << std::endl; - out << " tl1 = " << fTl1<< ";" << std::endl; + out << " h1 = " << fH1 << ";" << std::endl; + out << " bl1 = " << fBl1 << ";" << std::endl; + out << " tl1 = " << fTl1 << ";" << std::endl; out << " alpha1 = " << fAlpha1 << ";" << std::endl; out << " h2 = " << fH2 << ";" << std::endl; - out << " bl2 = " << fBl2<< ";" << std::endl; - out << " tl2 = " << fTl2<< ";" << std::endl; + out << " bl2 = " << fBl2 << ";" << std::endl; + out << " tl2 = " << fTl2 << ";" << std::endl; out << " alpha2 = " << fAlpha2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoTrap(\"" << GetName() << "\", dz,theta,phi,h1,bl1,tl1,alpha1,h2,bl2,tl2,alpha2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoTrap(\"" << GetName() + << "\", dz,theta,phi,h1,bl1,tl1,alpha1,h2,bl2,tl2,alpha2);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -1786,9 +1903,9 @@ void TGeoTrap::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) void TGeoTrap::SetDimensions(Double_t *param) { - fDz = param[0]; + fDz = param[0]; fTheta = param[1]; - fPhi = param[2]; + fPhi = param[2]; fH1 = param[3]; fH2 = param[7]; fBl1 = param[4]; @@ -1797,40 +1914,51 @@ void TGeoTrap::SetDimensions(Double_t *param) fTl2 = param[9]; fAlpha1 = param[6]; fAlpha2 = param[10]; - Double_t tx = TMath::Tan(fTheta*TMath::DegToRad())*TMath::Cos(fPhi*TMath::DegToRad()); - Double_t ty = TMath::Tan(fTheta*TMath::DegToRad())*TMath::Sin(fPhi*TMath::DegToRad()); - Double_t ta1 = TMath::Tan(fAlpha1*TMath::DegToRad()); - Double_t ta2 = TMath::Tan(fAlpha2*TMath::DegToRad()); - fXY[0][0] = -fDz*tx-fH1*ta1-fBl1; fXY[0][1] = -fDz*ty-fH1; - fXY[1][0] = -fDz*tx+fH1*ta1-fTl1; fXY[1][1] = -fDz*ty+fH1; - fXY[2][0] = -fDz*tx+fH1*ta1+fTl1; fXY[2][1] = -fDz*ty+fH1; - fXY[3][0] = -fDz*tx-fH1*ta1+fBl1; fXY[3][1] = -fDz*ty-fH1; - fXY[4][0] = fDz*tx-fH2*ta2-fBl2; fXY[4][1] = fDz*ty-fH2; - fXY[5][0] = fDz*tx+fH2*ta2-fTl2; fXY[5][1] = fDz*ty+fH2; - fXY[6][0] = fDz*tx+fH2*ta2+fTl2; fXY[6][1] = fDz*ty+fH2; - fXY[7][0] = fDz*tx-fH2*ta2+fBl2; fXY[7][1] = fDz*ty-fH2; + Double_t tx = TMath::Tan(fTheta * TMath::DegToRad()) * TMath::Cos(fPhi * TMath::DegToRad()); + Double_t ty = TMath::Tan(fTheta * TMath::DegToRad()) * TMath::Sin(fPhi * TMath::DegToRad()); + Double_t ta1 = TMath::Tan(fAlpha1 * TMath::DegToRad()); + Double_t ta2 = TMath::Tan(fAlpha2 * TMath::DegToRad()); + fXY[0][0] = -fDz * tx - fH1 * ta1 - fBl1; + fXY[0][1] = -fDz * ty - fH1; + fXY[1][0] = -fDz * tx + fH1 * ta1 - fTl1; + fXY[1][1] = -fDz * ty + fH1; + fXY[2][0] = -fDz * tx + fH1 * ta1 + fTl1; + fXY[2][1] = -fDz * ty + fH1; + fXY[3][0] = -fDz * tx - fH1 * ta1 + fBl1; + fXY[3][1] = -fDz * ty - fH1; + fXY[4][0] = fDz * tx - fH2 * ta2 - fBl2; + fXY[4][1] = fDz * ty - fH2; + fXY[5][0] = fDz * tx + fH2 * ta2 - fTl2; + fXY[5][1] = fDz * ty + fH2; + fXY[6][0] = fDz * tx + fH2 * ta2 + fTl2; + fXY[6][1] = fDz * ty + fH2; + fXY[7][0] = fDz * tx - fH2 * ta2 + fBl2; + fXY[7][1] = fDz * ty - fH2; ComputeTwist(); - if ((fDz<0) || (fH1<0) || (fBl1<0) || (fTl1<0) || - (fH2<0) || (fBl2<0) || (fTl2<0)) { + if ((fDz < 0) || (fH1 < 0) || (fBl1 < 0) || (fTl1 < 0) || (fH2 < 0) || (fBl2 < 0) || (fTl2 < 0)) { SetShapeBit(kGeoRunTimeShape); - } - else TGeoArb8::ComputeBBox(); + } else + TGeoArb8::ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// Compute distance from array of input points having directions specified by dirs. Store output in dists -void TGeoTrap::DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t* step) const +void TGeoTrap::DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const { - for (Int_t i=0; iIsRunTimeShape()) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; } Double_t dz, h1, bl1, tl1, h2, bl2, tl2; - if (fDz<0) dz=((TGeoTrap*)mother)->GetDz(); - else dz=fDz; - if (fH1<0) - h1 = ((TGeoTrap*)mother)->GetH1(); + if (fDz < 0) + dz = ((TGeoTrap *)mother)->GetDz(); + else + dz = fDz; + if (fH1 < 0) + h1 = ((TGeoTrap *)mother)->GetH1(); else h1 = fH1; - if (fH2<0) - h2 = ((TGeoTrap*)mother)->GetH2(); + if (fH2 < 0) + h2 = ((TGeoTrap *)mother)->GetH2(); else h2 = fH2; - if (fBl1<0) - bl1 = ((TGeoTrap*)mother)->GetBl1(); + if (fBl1 < 0) + bl1 = ((TGeoTrap *)mother)->GetBl1(); else bl1 = fBl1; - if (fBl2<0) - bl2 = ((TGeoTrap*)mother)->GetBl2(); + if (fBl2 < 0) + bl2 = ((TGeoTrap *)mother)->GetBl2(); else bl2 = fBl2; - if (fTl1<0) - tl1 = ((TGeoTrap*)mother)->GetTl1(); + if (fTl1 < 0) + tl1 = ((TGeoTrap *)mother)->GetTl1(); else tl1 = fTl1; - if (fTl2<0) - tl2 = ((TGeoTrap*)mother)->GetTl2(); + if (fTl2 < 0) + tl2 = ((TGeoTrap *)mother)->GetTl2(); else tl2 = fTl2; - return (new TGeoGtra(dz, fTheta, fPhi, fTwistAngle ,h1, bl1, tl1, fAlpha1, h2, bl2, tl2, fAlpha2)); + return (new TGeoGtra(dz, fTheta, fPhi, fTwistAngle, h1, bl1, tl1, fAlpha1, h2, bl2, tl2, fAlpha2)); } //////////////////////////////////////////////////////////////////////////////// @@ -2015,7 +2159,7 @@ TGeoShape *TGeoGtra::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/ Double_t TGeoGtra::Safety(const Double_t *point, Bool_t in) const { - return TGeoArb8::Safety(point,in); + return TGeoArb8::Safety(point, in); } //////////////////////////////////////////////////////////////////////////////// @@ -2023,21 +2167,23 @@ Double_t TGeoGtra::Safety(const Double_t *point, Bool_t in) const void TGeoGtra::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " theta = " << fTheta << ";" << std::endl; out << " phi = " << fPhi << ";" << std::endl; out << " twist = " << fTwistAngle << ";" << std::endl; - out << " h1 = " << fH1<< ";" << std::endl; - out << " bl1 = " << fBl1<< ";" << std::endl; - out << " tl1 = " << fTl1<< ";" << std::endl; + out << " h1 = " << fH1 << ";" << std::endl; + out << " bl1 = " << fBl1 << ";" << std::endl; + out << " tl1 = " << fTl1 << ";" << std::endl; out << " alpha1 = " << fAlpha1 << ";" << std::endl; out << " h2 = " << fH2 << ";" << std::endl; - out << " bl2 = " << fBl2<< ";" << std::endl; - out << " tl2 = " << fTl2<< ";" << std::endl; + out << " bl2 = " << fBl2 << ";" << std::endl; + out << " tl2 = " << fTl2 << ";" << std::endl; out << " alpha2 = " << fAlpha2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoGtra(\"" << GetName() << "\", dz,theta,phi,twist,h1,bl1,tl1,alpha1,h2,bl2,tl2,alpha2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoGtra(\"" << GetName() + << "\", dz,theta,phi,twist,h1,bl1,tl1,alpha1,h2,bl2,tl2,alpha2);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -2060,51 +2206,60 @@ void TGeoGtra::SetDimensions(Double_t *param) { TGeoTrap::SetDimensions(param); fTwistAngle = param[11]; - Double_t x,y; + Double_t x, y; Double_t twist = fTwistAngle; - Double_t th = fTheta*TMath::DegToRad(); - Double_t ph = fPhi*TMath::DegToRad(); + Double_t th = fTheta * TMath::DegToRad(); + Double_t ph = fPhi * TMath::DegToRad(); // Coordinates of the center of the bottom face - Double_t xc = -fDz*TMath::Sin(th)*TMath::Cos(ph); - Double_t yc = -fDz*TMath::Sin(th)*TMath::Sin(ph); + Double_t xc = -fDz * TMath::Sin(th) * TMath::Cos(ph); + Double_t yc = -fDz * TMath::Sin(th) * TMath::Sin(ph); Int_t i; - for (i=0; i<4; i++) { + for (i = 0; i < 4; i++) { x = fXY[i][0] - xc; y = fXY[i][1] - yc; - fXY[i][0] = x*TMath::Cos(-0.5*twist*TMath::DegToRad()) + y*TMath::Sin(-0.5*twist*TMath::DegToRad()) + xc; - fXY[i][1] = -x*TMath::Sin(-0.5*twist*TMath::DegToRad()) + y*TMath::Cos(-0.5*twist*TMath::DegToRad()) + yc; + fXY[i][0] = + x * TMath::Cos(-0.5 * twist * TMath::DegToRad()) + y * TMath::Sin(-0.5 * twist * TMath::DegToRad()) + xc; + fXY[i][1] = + -x * TMath::Sin(-0.5 * twist * TMath::DegToRad()) + y * TMath::Cos(-0.5 * twist * TMath::DegToRad()) + yc; } // Coordinates of the center of the top face xc = -xc; yc = -yc; - for (i=4; i<8; i++) { + for (i = 4; i < 8; i++) { x = fXY[i][0] - xc; y = fXY[i][1] - yc; - fXY[i][0] = x*TMath::Cos(0.5*twist*TMath::DegToRad()) + y*TMath::Sin(0.5*twist*TMath::DegToRad()) + xc; - fXY[i][1] = -x*TMath::Sin(0.5*twist*TMath::DegToRad()) + y*TMath::Cos(0.5*twist*TMath::DegToRad()) + yc; + fXY[i][0] = + x * TMath::Cos(0.5 * twist * TMath::DegToRad()) + y * TMath::Sin(0.5 * twist * TMath::DegToRad()) + xc; + fXY[i][1] = + -x * TMath::Sin(0.5 * twist * TMath::DegToRad()) + y * TMath::Cos(0.5 * twist * TMath::DegToRad()) + yc; } ComputeTwist(); - if ((fDz<0) || (fH1<0) || (fBl1<0) || (fTl1<0) || - (fH2<0) || (fBl2<0) || (fTl2<0)) SetShapeBit(kGeoRunTimeShape); - else TGeoArb8::ComputeBBox(); + if ((fDz < 0) || (fH1 < 0) || (fBl1 < 0) || (fTl1 < 0) || (fH2 < 0) || (fBl2 < 0) || (fTl2 < 0)) + SetShapeBit(kGeoRunTimeShape); + else + TGeoArb8::ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// Compute distance from array of input points having directions specified by dirs. Store output in dists -void TGeoGtra::DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t* step) const +void TGeoGtra::DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, + Double_t *step) const { - for (Int_t i=0; iIsClosed()) SetVisTouched(kTRUE); + if (vis) + SetAttBit(kVisThis); + else + ResetAttBit(kVisThis); + if (gGeoManager && gGeoManager->IsClosed()) + SetVisTouched(kTRUE); } //////////////////////////////////////////////////////////////////////////////// /// Set visibility for the daughters. void TGeoAtt::SetVisDaughters(Bool_t vis) { - if (vis) SetAttBit(kVisDaughters); - else ResetAttBit(kVisDaughters); - if (gGeoManager && gGeoManager->IsClosed()) SetVisTouched(kTRUE); + if (vis) + SetAttBit(kVisDaughters); + else + ResetAttBit(kVisDaughters); + if (gGeoManager && gGeoManager->IsClosed()) + SetVisTouched(kTRUE); } //////////////////////////////////////////////////////////////////////////////// /// Mark attributes as "streamed to file". void TGeoAtt::SetVisStreamed(Bool_t vis) { - if (vis) SetAttBit(kVisStreamed); - else ResetAttBit(kVisStreamed); + if (vis) + SetAttBit(kVisStreamed); + else + ResetAttBit(kVisStreamed); } //////////////////////////////////////////////////////////////////////////////// /// Mark visualization attributes as "modified". void TGeoAtt::SetVisTouched(Bool_t vis) { - if (vis) SetAttBit(kVisTouched); - else ResetAttBit(kVisTouched); + if (vis) + SetAttBit(kVisTouched); + else + ResetAttBit(kVisTouched); } //////////////////////////////////////////////////////////////////////////////// /// Set optimization flags. -void TGeoAtt::SetOptimization(Option_t * /*option*/) -{ -} - +void TGeoAtt::SetOptimization(Option_t * /*option*/) {} diff --git a/geom/geom/src/TGeoBBox.cxx b/geom/geom/src/TGeoBBox.cxx index 14e473efa427c..d95b8900d1a64 100644 --- a/geom/geom/src/TGeoBBox.cxx +++ b/geom/geom/src/TGeoBBox.cxx @@ -171,8 +171,7 @@ TGeoBBox::TGeoBBox() //////////////////////////////////////////////////////////////////////////////// /// Constructor where half-lengths are provided. -TGeoBBox::TGeoBBox(Double_t dx, Double_t dy, Double_t dz, Double_t *origin) - :TGeoShape("") +TGeoBBox::TGeoBBox(Double_t dx, Double_t dy, Double_t dz, Double_t *origin) : TGeoShape("") { SetShapeBit(TGeoShape::kGeoBox); fOrigin[0] = fOrigin[1] = fOrigin[2] = 0.0; @@ -182,8 +181,7 @@ TGeoBBox::TGeoBBox(Double_t dx, Double_t dy, Double_t dz, Double_t *origin) //////////////////////////////////////////////////////////////////////////////// /// Constructor with shape name. -TGeoBBox::TGeoBBox(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t *origin) - :TGeoShape(name) +TGeoBBox::TGeoBBox(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t *origin) : TGeoShape(name) { SetShapeBit(TGeoShape::kGeoBox); fOrigin[0] = fOrigin[1] = fOrigin[2] = 0.0; @@ -196,8 +194,7 @@ TGeoBBox::TGeoBBox(const char *name, Double_t dx, Double_t dy, Double_t dz, Doub /// - param[1] - half-length in y /// - param[2] - half-length in z -TGeoBBox::TGeoBBox(Double_t *param) - :TGeoShape("") +TGeoBBox::TGeoBBox(Double_t *param) : TGeoShape("") { SetShapeBit(TGeoShape::kGeoBox); fOrigin[0] = fOrigin[1] = fOrigin[2] = 0.0; @@ -207,14 +204,13 @@ TGeoBBox::TGeoBBox(Double_t *param) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoBBox::~TGeoBBox() -{ -} +TGeoBBox::~TGeoBBox() {} //////////////////////////////////////////////////////////////////////////////// /// Check if 2 positioned boxes overlap. -Bool_t TGeoBBox::AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, const TGeoBBox *box2, const TGeoMatrix *mat2) +Bool_t +TGeoBBox::AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, const TGeoBBox *box2, const TGeoMatrix *mat2) { Double_t master[3]; Double_t local[3]; @@ -224,31 +220,33 @@ Bool_t TGeoBBox::AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, co // Convert center of first box to the local frame of second mat1->LocalToMaster(o1, master); mat2->MasterToLocal(master, local); - if (TGeoBBox::Contains(local,box2->GetDX(),box2->GetDY(),box2->GetDZ(),o2)) return kTRUE; - Double_t distsq = (local[0]-o2[0])*(local[0]-o2[0]) + - (local[1]-o2[1])*(local[1]-o2[1]) + - (local[2]-o2[2])*(local[2]-o2[2]); + if (TGeoBBox::Contains(local, box2->GetDX(), box2->GetDY(), box2->GetDZ(), o2)) + return kTRUE; + Double_t distsq = (local[0] - o2[0]) * (local[0] - o2[0]) + (local[1] - o2[1]) * (local[1] - o2[1]) + + (local[2] - o2[2]) * (local[2] - o2[2]); // Compute distance between box centers and compare with max value - Double_t rmaxsq = (box1->GetDX()+box2->GetDX())*(box1->GetDX()+box2->GetDX()) + - (box1->GetDY()+box2->GetDY())*(box1->GetDY()+box2->GetDY()) + - (box1->GetDZ()+box2->GetDZ())*(box1->GetDZ()+box2->GetDZ()); - if (distsq > rmaxsq + TGeoShape::Tolerance()) return kFALSE; + Double_t rmaxsq = (box1->GetDX() + box2->GetDX()) * (box1->GetDX() + box2->GetDX()) + + (box1->GetDY() + box2->GetDY()) * (box1->GetDY() + box2->GetDY()) + + (box1->GetDZ() + box2->GetDZ()) * (box1->GetDZ() + box2->GetDZ()); + if (distsq > rmaxsq + TGeoShape::Tolerance()) + return kFALSE; // We are still not sure: shoot a ray from the center of "1" towards the // center of 2. Double_t dir[3]; mat1->LocalToMaster(o1, ldir1); mat2->LocalToMaster(o2, ldir2); - distsq = 1./TMath::Sqrt(distsq); - dir[0] = (ldir2[0]-ldir1[0])*distsq; - dir[1] = (ldir2[1]-ldir1[1])*distsq; - dir[2] = (ldir2[2]-ldir1[2])*distsq; + distsq = 1. / TMath::Sqrt(distsq); + dir[0] = (ldir2[0] - ldir1[0]) * distsq; + dir[1] = (ldir2[1] - ldir1[1]) * distsq; + dir[2] = (ldir2[2] - ldir1[2]) * distsq; mat1->MasterToLocalVect(dir, ldir1); mat2->MasterToLocalVect(dir, ldir2); // Distance to exit from o1 - Double_t dist1 = TGeoBBox::DistFromInside(o1,ldir1,box1->GetDX(),box1->GetDY(),box1->GetDZ(),o1); + Double_t dist1 = TGeoBBox::DistFromInside(o1, ldir1, box1->GetDX(), box1->GetDY(), box1->GetDZ(), o1); // Distance to enter from o2 - Double_t dist2 = TGeoBBox::DistFromOutside(local,ldir2,box2->GetDX(),box2->GetDY(),box2->GetDZ(),o2); - if (dist1 > dist2) return kTRUE; + Double_t dist2 = TGeoBBox::DistFromOutside(local, ldir2, box2->GetDX(), box2->GetDY(), box2->GetDZ(), o2); + if (dist1 > dist2) + return kTRUE; return kFALSE; } @@ -257,7 +255,7 @@ Bool_t TGeoBBox::AreOverlapping(const TGeoBBox *box1, const TGeoMatrix *mat1, co Double_t TGeoBBox::Capacity() const { - return (8.*fDX*fDY*fDZ); + return (8. * fDX * fDY * fDZ); } //////////////////////////////////////////////////////////////////////////////// @@ -265,14 +263,14 @@ Double_t TGeoBBox::Capacity() const void TGeoBBox::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - memset(norm,0,3*sizeof(Double_t)); + memset(norm, 0, 3 * sizeof(Double_t)); Double_t saf[3]; Int_t i; - saf[0]=TMath::Abs(TMath::Abs(point[0]-fOrigin[0])-fDX); - saf[1]=TMath::Abs(TMath::Abs(point[1]-fOrigin[1])-fDY); - saf[2]=TMath::Abs(TMath::Abs(point[2]-fOrigin[2])-fDZ); - i = TMath::LocMin(3,saf); - norm[i] = (dir[i]>0)?1:(-1); + saf[0] = TMath::Abs(TMath::Abs(point[0] - fOrigin[0]) - fDX); + saf[1] = TMath::Abs(TMath::Abs(point[1] - fOrigin[1]) - fDY); + saf[2] = TMath::Abs(TMath::Abs(point[2] - fOrigin[2]) - fDZ); + i = TMath::LocMin(3, saf); + norm[i] = (dir[i] > 0) ? 1 : (-1); } //////////////////////////////////////////////////////////////////////////////// @@ -281,21 +279,27 @@ void TGeoBBox::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoBBox::CouldBeCrossed(const Double_t *point, const Double_t *dir) const { Double_t mind = fDX; - if (fDY=(do2-rmax2)*dirnorm) return kTRUE; + if (doct <= 0) + return kFALSE; + Double_t dirnorm = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; + if ((doct * doct) >= (do2 - rmax2) * dirnorm) + return kTRUE; return kFALSE; } @@ -314,43 +318,41 @@ Int_t TGeoBBox::DistancetoPrimitive(Int_t px, Int_t py) /// to created division cell volume. In case a wrong division axis is supplied, /// returns pointer to volume to be divided. -TGeoVolume *TGeoBBox::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoBBox::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached - Double_t end = start+ndiv*step; + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- divide on X - shape = new TGeoBBox(step/2., fDY, fDZ); - finder = new TGeoPatternX(voldiv, ndiv, start, end); - opt = "X"; - break; - case 2: //--- divide on Y - shape = new TGeoBBox(fDX, step/2., fDZ); - finder = new TGeoPatternY(voldiv, ndiv, start, end); - opt = "Y"; - break; - case 3: //--- divide on Z - shape = new TGeoBBox(fDX, fDY, step/2.); - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - opt = "Z"; - break; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + case 1: //--- divide on X + shape = new TGeoBBox(step / 2., fDY, fDZ); + finder = new TGeoPatternX(voldiv, ndiv, start, end); + opt = "X"; + break; + case 2: //--- divide on Y + shape = new TGeoBBox(fDX, step / 2., fDZ); + finder = new TGeoPatternY(voldiv, ndiv, start, end); + opt = "Y"; + break; + case 3: //--- divide on Z + shape = new TGeoBBox(fDX, fDY, step / 2.); + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + opt = "Z"; + break; + default: Error("Divide", "Wrong axis type for division"); return 0; } vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); voldiv->SetFinder(finder); finder->SetDivIndex(voldiv->GetNdaughters()); - for (Int_t ic=0; icAddNodeOffset(vol, ic, start+step/2.+ic*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); + for (Int_t ic = 0; ic < ndiv; ic++) { + voldiv->AddNodeOffset(vol, ic, start + step / 2. + ic * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); } return vmulti; } @@ -358,18 +360,19 @@ TGeoVolume *TGeoBBox::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi //////////////////////////////////////////////////////////////////////////////// /// Compute bounding box - nothing to do in this case. -void TGeoBBox::ComputeBBox() -{ -} +void TGeoBBox::ComputeBBox() {} //////////////////////////////////////////////////////////////////////////////// /// Test if point is inside this shape. Bool_t TGeoBBox::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]-fOrigin[2]) > fDZ) return kFALSE; - if (TMath::Abs(point[0]-fOrigin[0]) > fDX) return kFALSE; - if (TMath::Abs(point[1]-fOrigin[1]) > fDY) return kFALSE; + if (TMath::Abs(point[2] - fOrigin[2]) > fDZ) + return kFALSE; + if (TMath::Abs(point[0] - fOrigin[0]) > fDX) + return kFALSE; + if (TMath::Abs(point[1] - fOrigin[1]) > fDY) + return kFALSE; return kTRUE; } @@ -379,9 +382,12 @@ Bool_t TGeoBBox::Contains(const Double_t *point) const Bool_t TGeoBBox::Contains(const Double_t *point, Double_t dx, Double_t dy, Double_t dz, const Double_t *origin) { - if (TMath::Abs(point[2]-origin[2]) > dz) return kFALSE; - if (TMath::Abs(point[0]-origin[0]) > dx) return kFALSE; - if (TMath::Abs(point[1]-origin[1]) > dy) return kFALSE; + if (TMath::Abs(point[2] - origin[2]) > dz) + return kFALSE; + if (TMath::Abs(point[0] - origin[0]) > dx) + return kFALSE; + if (TMath::Abs(point[1] - origin[1]) > dy) + return kFALSE; return kTRUE; } @@ -389,34 +395,43 @@ Bool_t TGeoBBox::Contains(const Double_t *point, Double_t dx, Double_t dy, Doubl /// Compute distance from inside point to surface of the box. /// Boundary safe algorithm. -Double_t TGeoBBox::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoBBox::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - Double_t s,smin,saf[6]; + Double_t s, smin, saf[6]; Double_t newpt[3]; Int_t i; - for (i=0; i<3; i++) newpt[i] = point[i] - fOrigin[i]; - saf[0] = fDX+newpt[0]; - saf[1] = fDX-newpt[0]; - saf[2] = fDY+newpt[1]; - saf[3] = fDY-newpt[1]; - saf[4] = fDZ+newpt[2]; - saf[5] = fDZ-newpt[2]; - if (iact<3 && safe) { + for (i = 0; i < 3; i++) + newpt[i] = point[i] - fOrigin[i]; + saf[0] = fDX + newpt[0]; + saf[1] = fDX - newpt[0]; + saf[2] = fDY + newpt[1]; + saf[3] = fDY - newpt[1]; + saf[4] = fDZ + newpt[2]; + saf[5] = fDZ - newpt[2]; + if (iact < 3 && safe) { smin = saf[0]; // compute safe distance - for (i=1;i<6;i++) if (saf[i] < smin) smin = saf[i]; + for (i = 1; i < 6; i++) + if (saf[i] < smin) + smin = saf[i]; *safe = smin; - if (smin<0) *safe = 0.0; - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (smin < 0) + *safe = 0.0; + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // compute distance to surface - smin=TGeoShape::Big(); - for (i=0; i<3; i++) { - if (dir[i]!=0) { - s = (dir[i]>0)?(saf[(i<<1)+1]/dir[i]):(-saf[i<<1]/dir[i]); - if (s < 0) return 0.0; - if (s < smin) smin = s; + smin = TGeoShape::Big(); + for (i = 0; i < 3; i++) { + if (dir[i] != 0) { + s = (dir[i] > 0) ? (saf[(i << 1) + 1] / dir[i]) : (-saf[i << 1] / dir[i]); + if (s < 0) + return 0.0; + if (s < smin) + smin = s; } } return smin; @@ -426,26 +441,29 @@ Double_t TGeoBBox::DistFromInside(const Double_t *point, const Double_t *dir, In /// Compute distance from inside point to surface of the box. /// Boundary safe algorithm. -Double_t TGeoBBox::DistFromInside(const Double_t *point,const Double_t *dir, - Double_t dx, Double_t dy, Double_t dz, const Double_t *origin, Double_t /*stepmax*/) +Double_t TGeoBBox::DistFromInside(const Double_t *point, const Double_t *dir, Double_t dx, Double_t dy, Double_t dz, + const Double_t *origin, Double_t /*stepmax*/) { - Double_t s,smin,saf[6]; + Double_t s, smin, saf[6]; Double_t newpt[3]; Int_t i; - for (i=0; i<3; i++) newpt[i] = point[i] - origin[i]; - saf[0] = dx+newpt[0]; - saf[1] = dx-newpt[0]; - saf[2] = dy+newpt[1]; - saf[3] = dy-newpt[1]; - saf[4] = dz+newpt[2]; - saf[5] = dz-newpt[2]; + for (i = 0; i < 3; i++) + newpt[i] = point[i] - origin[i]; + saf[0] = dx + newpt[0]; + saf[1] = dx - newpt[0]; + saf[2] = dy + newpt[1]; + saf[3] = dy - newpt[1]; + saf[4] = dz + newpt[2]; + saf[5] = dz - newpt[2]; // compute distance to surface - smin=TGeoShape::Big(); - for (i=0; i<3; i++) { - if (dir[i]!=0) { - s = (dir[i]>0)?(saf[(i<<1)+1]/dir[i]):(-saf[i<<1]/dir[i]); - if (s < 0) return 0.0; - if (s < smin) smin = s; + smin = TGeoShape::Big(); + for (i = 0; i < 3; i++) { + if (dir[i] != 0) { + s = (dir[i] > 0) ? (saf[(i << 1) + 1] / dir[i]) : (-saf[i << 1] / dir[i]); + if (s < 0) + return 0.0; + if (s < smin) + smin = s; } } return smin; @@ -455,61 +473,75 @@ Double_t TGeoBBox::DistFromInside(const Double_t *point,const Double_t *dir, /// Compute distance from outside point to surface of the box. /// Boundary safe algorithm. -Double_t TGeoBBox::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoBBox::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { Bool_t in = kTRUE; Double_t saf[3]; Double_t par[3]; Double_t newpt[3]; - Int_t i,j; - for (i=0; i<3; i++) newpt[i] = point[i] - fOrigin[i]; + Int_t i, j; + for (i = 0; i < 3; i++) + newpt[i] = point[i] - fOrigin[i]; par[0] = fDX; par[1] = fDY; par[2] = fDZ; - for (i=0; i<3; i++) { - saf[i] = TMath::Abs(newpt[i])-par[i]; - if (saf[i]>=step) return TGeoShape::Big(); - if (in && saf[i]>0) in=kFALSE; + for (i = 0; i < 3; i++) { + saf[i] = TMath::Abs(newpt[i]) - par[i]; + if (saf[i] >= step) + return TGeoShape::Big(); + if (in && saf[i] > 0) + in = kFALSE; } - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance if (in) { *safe = 0.0; } else { *safe = saf[0]; - if (saf[1] > *safe) *safe = saf[1]; - if (saf[2] > *safe) *safe = saf[2]; + if (saf[1] > *safe) + *safe = saf[1]; + if (saf[2] > *safe) + *safe = saf[2]; } - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // compute distance from point to box // protection in case point is actually inside box if (in) { j = 0; Double_t ss = saf[0]; - if (saf[1]>ss) { + if (saf[1] > ss) { ss = saf[1]; j = 1; } - if (saf[2]>ss) j = 2; - if (newpt[j]*dir[j]>0) return TGeoShape::Big(); // in fact exiting + if (saf[2] > ss) + j = 2; + if (newpt[j] * dir[j] > 0) + return TGeoShape::Big(); // in fact exiting return 0.0; } - for (i=0; i<3; i++) { - if (saf[i]<0) continue; - if (newpt[i]*dir[i] >= 0) continue; - Double_t snxt = saf[i]/TMath::Abs(dir[i]); + for (i = 0; i < 3; i++) { + if (saf[i] < 0) + continue; + if (newpt[i] * dir[i] >= 0) + continue; + Double_t snxt = saf[i] / TMath::Abs(dir[i]); Int_t ibreak = 0; - for (j=0; j<3; j++) { - if (j==i) continue; - Double_t coord=newpt[j]+snxt*dir[j]; - if (TMath::Abs(coord)>par[j]) { - ibreak=1; + for (j = 0; j < 3; j++) { + if (j == i) + continue; + Double_t coord = newpt[j] + snxt * dir[j]; + if (TMath::Abs(coord) > par[j]) { + ibreak = 1; break; } } - if (!ibreak) return snxt; + if (!ibreak) + return snxt; } return TGeoShape::Big(); } @@ -518,41 +550,49 @@ Double_t TGeoBBox::DistFromOutside(const Double_t *point, const Double_t *dir, I /// Compute distance from outside point to surface of the box. /// Boundary safe algorithm. -Double_t TGeoBBox::DistFromOutside(const Double_t *point,const Double_t *dir, - Double_t dx, Double_t dy, Double_t dz, const Double_t *origin, Double_t stepmax) +Double_t TGeoBBox::DistFromOutside(const Double_t *point, const Double_t *dir, Double_t dx, Double_t dy, Double_t dz, + const Double_t *origin, Double_t stepmax) { Bool_t in = kTRUE; Double_t saf[3]; Double_t par[3]; Double_t newpt[3]; - Int_t i,j; - for (i=0; i<3; i++) newpt[i] = point[i] - origin[i]; + Int_t i, j; + for (i = 0; i < 3; i++) + newpt[i] = point[i] - origin[i]; par[0] = dx; par[1] = dy; par[2] = dz; - for (i=0; i<3; i++) { - saf[i] = TMath::Abs(newpt[i])-par[i]; - if (saf[i]>=stepmax) return TGeoShape::Big(); - if (in && saf[i]>0) in=kFALSE; + for (i = 0; i < 3; i++) { + saf[i] = TMath::Abs(newpt[i]) - par[i]; + if (saf[i] >= stepmax) + return TGeoShape::Big(); + if (in && saf[i] > 0) + in = kFALSE; } // In case point is inside return ZERO - if (in) return 0.0; - Double_t coord, snxt=TGeoShape::Big(); - Int_t ibreak=0; - for (i=0; i<3; i++) { - if (saf[i]<0) continue; - if (newpt[i]*dir[i] >= 0) continue; - snxt = saf[i]/TMath::Abs(dir[i]); + if (in) + return 0.0; + Double_t coord, snxt = TGeoShape::Big(); + Int_t ibreak = 0; + for (i = 0; i < 3; i++) { + if (saf[i] < 0) + continue; + if (newpt[i] * dir[i] >= 0) + continue; + snxt = saf[i] / TMath::Abs(dir[i]); ibreak = 0; - for (j=0; j<3; j++) { - if (j==i) continue; - coord=newpt[j]+snxt*dir[j]; - if (TMath::Abs(coord)>par[j]) { - ibreak=1; + for (j = 0; j < 3; j++) { + if (j == i) + continue; + coord = newpt[j] + snxt * dir[j]; + if (TMath::Abs(coord) > par[j]) { + ibreak = 1; break; } } - if (!ibreak) return snxt; + if (!ibreak) + return snxt; } return TGeoShape::Big(); } @@ -563,14 +603,10 @@ Double_t TGeoBBox::DistFromOutside(const Double_t *point,const Double_t *dir, const char *TGeoBBox::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "X"; - case 2: - return "Y"; - case 3: - return "Z"; - default: - return "UNDEFINED"; + case 1: return "X"; + case 2: return "Y"; + case 3: return "Z"; + default: return "UNDEFINED"; } } @@ -583,21 +619,21 @@ Double_t TGeoBBox::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fOrigin[0]-fDX; - xhi = fOrigin[0]+fDX; - dx = 2*fDX; - return dx; - case 2: - xlo = fOrigin[1]-fDY; - xhi = fOrigin[1]+fDY; - dx = 2*fDY; - return dx; - case 3: - xlo = fOrigin[2]-fDZ; - xhi = fOrigin[2]+fDZ; - dx = 2*fDZ; - return dx; + case 1: + xlo = fOrigin[0] - fDX; + xhi = fOrigin[0] + fDX; + dx = 2 * fDX; + return dx; + case 2: + xlo = fOrigin[1] - fDY; + xhi = fOrigin[1] + fDY; + dx = 2 * fDY; + return dx; + case 3: + xlo = fOrigin[2] - fDZ; + xhi = fOrigin[2] + fDZ; + dx = 2 * fDZ; + return dx; } return dx; } @@ -608,10 +644,10 @@ Double_t TGeoBBox::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const void TGeoBBox::GetBoundingCylinder(Double_t *param) const { - param[0] = 0.; // Rmin - param[1] = fDX*fDX+fDY*fDY; // Rmax - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[0] = 0.; // Rmin + param[1] = fDX * fDX + fDY * fDY; // Rmax + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -624,21 +660,13 @@ Double_t TGeoBBox::GetFacetArea(Int_t index) const { Double_t area = 0.; switch (index) { - case 0: - area = 8.*(fDX*fDY + fDX*fDZ + fDY*fDZ); - return area; - case 1: - case 6: - area = 4.*fDX*fDY; - return area; - case 2: - case 4: - area = 4.*fDX*fDZ; - return area; - case 3: - case 5: - area = 4.*fDY*fDZ; - return area; + case 0: area = 8. * (fDX * fDY + fDX * fDZ + fDY * fDZ); return area; + case 1: + case 6: area = 4. * fDX * fDY; return area; + case 2: + case 4: area = 4. * fDX * fDZ; return area; + case 3: + case 5: area = 4. * fDY * fDZ; return area; } return area; } @@ -653,57 +681,60 @@ Double_t TGeoBBox::GetFacetArea(Int_t index) const Bool_t TGeoBBox::GetPointsOnFacet(Int_t index, Int_t npoints, Double_t *array) const { - if (index<0 || index>6) return kFALSE; + if (index < 0 || index > 6) + return kFALSE; Double_t surf[6]; Double_t area = 0.; - if (index==0) { - for (Int_t isurf=0; isurf<6; isurf++) { - surf[isurf] = TGeoBBox::GetFacetArea(isurf+1); - if (isurf>0) surf[isurf] += surf[isurf-1]; + if (index == 0) { + for (Int_t isurf = 0; isurf < 6; isurf++) { + surf[isurf] = TGeoBBox::GetFacetArea(isurf + 1); + if (isurf > 0) + surf[isurf] += surf[isurf - 1]; } area = surf[5]; } - for (Int_t i=0; iRndm(); - surfindex = 2+TMath::BinarySearch(6, surf, val); - if (surfindex>6) surfindex=6; + if (surfindex == 0) { + Double_t val = area * gRandom->Rndm(); + surfindex = 2 + TMath::BinarySearch(6, surf, val); + if (surfindex > 6) + surfindex = 6; } switch (surfindex) { - case 1: - point[0] = -fDX + 2*fDX*gRandom->Rndm(); - point[1] = -fDY + 2*fDY*gRandom->Rndm(); - point[2] = -fDZ; - break; - case 2: - point[0] = -fDX + 2*fDX*gRandom->Rndm(); - point[1] = -fDY; - point[2] = -fDZ + 2*fDZ*gRandom->Rndm(); - break; - case 3: - point[0] = -fDX; - point[1] = -fDY + 2*fDY*gRandom->Rndm(); - point[2] = -fDZ + 2*fDZ*gRandom->Rndm(); - break; - case 4: - point[0] = -fDX + 2*fDX*gRandom->Rndm(); - point[1] = fDY; - point[2] = -fDZ + 2*fDZ*gRandom->Rndm(); - break; - case 5: - point[0] = fDX; - point[1] = -fDY + 2*fDY*gRandom->Rndm(); - point[2] = -fDZ + 2*fDZ*gRandom->Rndm(); - break; - case 6: - point[0] = -fDX + 2*fDX*gRandom->Rndm(); - point[1] = -fDY + 2*fDY*gRandom->Rndm(); - point[2] = fDZ; - break; + case 1: + point[0] = -fDX + 2 * fDX * gRandom->Rndm(); + point[1] = -fDY + 2 * fDY * gRandom->Rndm(); + point[2] = -fDZ; + break; + case 2: + point[0] = -fDX + 2 * fDX * gRandom->Rndm(); + point[1] = -fDY; + point[2] = -fDZ + 2 * fDZ * gRandom->Rndm(); + break; + case 3: + point[0] = -fDX; + point[1] = -fDY + 2 * fDY * gRandom->Rndm(); + point[2] = -fDZ + 2 * fDZ * gRandom->Rndm(); + break; + case 4: + point[0] = -fDX + 2 * fDX * gRandom->Rndm(); + point[1] = fDY; + point[2] = -fDZ + 2 * fDZ * gRandom->Rndm(); + break; + case 5: + point[0] = fDX; + point[1] = -fDY + 2 * fDY * gRandom->Rndm(); + point[2] = -fDZ + 2 * fDZ * gRandom->Rndm(); + break; + case 6: + point[0] = -fDX + 2 * fDX * gRandom->Rndm(); + point[1] = -fDY + 2 * fDY * gRandom->Rndm(); + point[2] = fDZ; + break; } } return kTRUE; @@ -716,7 +747,7 @@ Bool_t TGeoBBox::GetPointsOnFacet(Int_t index, Int_t npoints, Double_t *array) c Bool_t TGeoBBox::GetPointsOnSegments(Int_t npoints, Double_t *array) const { - if (npointsIsRotation()) { Error("GetFittingBox", "cannot handle parametrized rotated volumes"); return 1; // ### rotation not accepted ### @@ -766,17 +800,18 @@ Int_t TGeoBBox::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ return 1; // ### wrong matrix ### } //--> now we have to get the valid range for all parametrized axis - Double_t xlo=0, xhi=0; + Double_t xlo = 0, xhi = 0; Double_t dd[3]; dd[0] = parambox->GetDX(); dd[1] = parambox->GetDY(); dd[2] = parambox->GetDZ(); - for (Int_t iaxis=0; iaxis<3; iaxis++) { - if (dd[iaxis]>=0) continue; - TGeoBBox::GetAxisRange(iaxis+1, xlo, xhi); + for (Int_t iaxis = 0; iaxis < 3; iaxis++) { + if (dd[iaxis] >= 0) + continue; + TGeoBBox::GetAxisRange(iaxis + 1, xlo, xhi); //-> compute best fitting parameter - dd[iaxis] = TMath::Min(origin[iaxis]-xlo, xhi-origin[iaxis]); - if (dd[iaxis]<0) { + dd[iaxis] = TMath::Min(origin[iaxis] - xlo, xhi - origin[iaxis]); + if (dd[iaxis] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } @@ -793,7 +828,8 @@ Int_t TGeoBBox::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ TGeoShape *TGeoBBox::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; Double_t dx, dy, dz; Int_t ierr = mother->GetFittingBox(this, mat, dx, dy, dz); if (ierr) { @@ -831,9 +867,8 @@ void TGeoBBox::InspectShape() const TBuffer3D *TGeoBBox::MakeBuffer3D() const { - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, 8, 24, 12, 36, 6, 36); - if (buff) - { + TBuffer3D *buff = new TBuffer3D(TBuffer3DTypes::kGeneric, 8, 24, 12, 36, 6, 36); + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -848,31 +883,79 @@ void TGeoBBox::SetSegsAndPols(TBuffer3D &buff) const { Int_t c = GetBasicColor(); - buff.fSegs[ 0] = c ; buff.fSegs[ 1] = 0 ; buff.fSegs[ 2] = 1 ; - buff.fSegs[ 3] = c+1 ; buff.fSegs[ 4] = 1 ; buff.fSegs[ 5] = 2 ; - buff.fSegs[ 6] = c+1 ; buff.fSegs[ 7] = 2 ; buff.fSegs[ 8] = 3 ; - buff.fSegs[ 9] = c ; buff.fSegs[10] = 3 ; buff.fSegs[11] = 0 ; - buff.fSegs[12] = c+2 ; buff.fSegs[13] = 4 ; buff.fSegs[14] = 5 ; - buff.fSegs[15] = c+2 ; buff.fSegs[16] = 5 ; buff.fSegs[17] = 6 ; - buff.fSegs[18] = c+3 ; buff.fSegs[19] = 6 ; buff.fSegs[20] = 7 ; - buff.fSegs[21] = c+3 ; buff.fSegs[22] = 7 ; buff.fSegs[23] = 4 ; - buff.fSegs[24] = c ; buff.fSegs[25] = 0 ; buff.fSegs[26] = 4 ; - buff.fSegs[27] = c+2 ; buff.fSegs[28] = 1 ; buff.fSegs[29] = 5 ; - buff.fSegs[30] = c+1 ; buff.fSegs[31] = 2 ; buff.fSegs[32] = 6 ; - buff.fSegs[33] = c+3 ; buff.fSegs[34] = 3 ; buff.fSegs[35] = 7 ; - - buff.fPols[ 0] = c ; buff.fPols[ 1] = 4 ; buff.fPols[ 2] = 0 ; - buff.fPols[ 3] = 9 ; buff.fPols[ 4] = 4 ; buff.fPols[ 5] = 8 ; - buff.fPols[ 6] = c+1 ; buff.fPols[ 7] = 4 ; buff.fPols[ 8] = 1 ; - buff.fPols[ 9] = 10 ; buff.fPols[10] = 5 ; buff.fPols[11] = 9 ; - buff.fPols[12] = c ; buff.fPols[13] = 4 ; buff.fPols[14] = 2 ; - buff.fPols[15] = 11 ; buff.fPols[16] = 6 ; buff.fPols[17] = 10 ; - buff.fPols[18] = c+1 ; buff.fPols[19] = 4 ; buff.fPols[20] = 3 ; - buff.fPols[21] = 8 ; buff.fPols[22] = 7 ; buff.fPols[23] = 11 ; - buff.fPols[24] = c+2 ; buff.fPols[25] = 4 ; buff.fPols[26] = 0 ; - buff.fPols[27] = 3 ; buff.fPols[28] = 2 ; buff.fPols[29] = 1 ; - buff.fPols[30] = c+3 ; buff.fPols[31] = 4 ; buff.fPols[32] = 4 ; - buff.fPols[33] = 5 ; buff.fPols[34] = 6 ; buff.fPols[35] = 7 ; + buff.fSegs[0] = c; + buff.fSegs[1] = 0; + buff.fSegs[2] = 1; + buff.fSegs[3] = c + 1; + buff.fSegs[4] = 1; + buff.fSegs[5] = 2; + buff.fSegs[6] = c + 1; + buff.fSegs[7] = 2; + buff.fSegs[8] = 3; + buff.fSegs[9] = c; + buff.fSegs[10] = 3; + buff.fSegs[11] = 0; + buff.fSegs[12] = c + 2; + buff.fSegs[13] = 4; + buff.fSegs[14] = 5; + buff.fSegs[15] = c + 2; + buff.fSegs[16] = 5; + buff.fSegs[17] = 6; + buff.fSegs[18] = c + 3; + buff.fSegs[19] = 6; + buff.fSegs[20] = 7; + buff.fSegs[21] = c + 3; + buff.fSegs[22] = 7; + buff.fSegs[23] = 4; + buff.fSegs[24] = c; + buff.fSegs[25] = 0; + buff.fSegs[26] = 4; + buff.fSegs[27] = c + 2; + buff.fSegs[28] = 1; + buff.fSegs[29] = 5; + buff.fSegs[30] = c + 1; + buff.fSegs[31] = 2; + buff.fSegs[32] = 6; + buff.fSegs[33] = c + 3; + buff.fSegs[34] = 3; + buff.fSegs[35] = 7; + + buff.fPols[0] = c; + buff.fPols[1] = 4; + buff.fPols[2] = 0; + buff.fPols[3] = 9; + buff.fPols[4] = 4; + buff.fPols[5] = 8; + buff.fPols[6] = c + 1; + buff.fPols[7] = 4; + buff.fPols[8] = 1; + buff.fPols[9] = 10; + buff.fPols[10] = 5; + buff.fPols[11] = 9; + buff.fPols[12] = c; + buff.fPols[13] = 4; + buff.fPols[14] = 2; + buff.fPols[15] = 11; + buff.fPols[16] = 6; + buff.fPols[17] = 10; + buff.fPols[18] = c + 1; + buff.fPols[19] = 4; + buff.fPols[20] = 3; + buff.fPols[21] = 8; + buff.fPols[22] = 7; + buff.fPols[23] = 11; + buff.fPols[24] = c + 2; + buff.fPols[25] = 4; + buff.fPols[26] = 0; + buff.fPols[27] = 3; + buff.fPols[28] = 2; + buff.fPols[29] = 1; + buff.fPols[30] = c + 3; + buff.fPols[31] = 4; + buff.fPols[32] = 4; + buff.fPols[33] = 5; + buff.fPols[34] = 6; + buff.fPols[35] = 7; } //////////////////////////////////////////////////////////////////////////////// @@ -882,17 +965,21 @@ Double_t TGeoBBox::Safety(const Double_t *point, Bool_t in) const { Double_t safe, safy, safz; if (in) { - safe = fDX - TMath::Abs(point[0]-fOrigin[0]); - safy = fDY - TMath::Abs(point[1]-fOrigin[1]); - safz = fDZ - TMath::Abs(point[2]-fOrigin[2]); - if (safy < safe) safe = safy; - if (safz < safe) safe = safz; + safe = fDX - TMath::Abs(point[0] - fOrigin[0]); + safy = fDY - TMath::Abs(point[1] - fOrigin[1]); + safz = fDZ - TMath::Abs(point[2] - fOrigin[2]); + if (safy < safe) + safe = safy; + if (safz < safe) + safe = safz; } else { - safe = -fDX + TMath::Abs(point[0]-fOrigin[0]); - safy = -fDY + TMath::Abs(point[1]-fOrigin[1]); - safz = -fDZ + TMath::Abs(point[2]-fOrigin[2]); - if (safy > safe) safe = safy; - if (safz > safe) safe = safz; + safe = -fDX + TMath::Abs(point[0] - fOrigin[0]); + safy = -fDY + TMath::Abs(point[1] - fOrigin[1]); + safz = -fDZ + TMath::Abs(point[2] - fOrigin[2]); + if (safy > safe) + safe = safy; + if (safz > safe) + safe = safz; } return safe; } @@ -902,18 +989,19 @@ Double_t TGeoBBox::Safety(const Double_t *point, Bool_t in) const void TGeoBBox::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dx = " << fDX << ";" << std::endl; out << " dy = " << fDY << ";" << std::endl; out << " dz = " << fDZ << ";" << std::endl; - if (!TGeoShape::IsSameWithinTolerance(fOrigin[0],0) || - !TGeoShape::IsSameWithinTolerance(fOrigin[1],0) || - !TGeoShape::IsSameWithinTolerance(fOrigin[2],0)) { + if (!TGeoShape::IsSameWithinTolerance(fOrigin[0], 0) || !TGeoShape::IsSameWithinTolerance(fOrigin[1], 0) || + !TGeoShape::IsSameWithinTolerance(fOrigin[2], 0)) { out << " origin[0] = " << fOrigin[0] << ";" << std::endl; out << " origin[1] = " << fOrigin[1] << ";" << std::endl; out << " origin[2] = " << fOrigin[2] << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoBBox(\"" << GetName() << "\", dx,dy,dz,origin);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoBBox(\"" << GetName() << "\", dx,dy,dz,origin);" + << std::endl; } else { out << " TGeoShape *" << GetPointerName() << " = new TGeoBBox(\"" << GetName() << "\", dx,dy,dz);" << std::endl; } @@ -933,10 +1021,11 @@ void TGeoBBox::SetBoxDimensions(Double_t dx, Double_t dy, Double_t dz, Double_t fOrigin[1] = origin[1]; fOrigin[2] = origin[2]; } - if (TMath::Abs(fDX)GetGeomPainter(); //// if (painter) painter->AddSize3D(8, 12, 6); -void TGeoBBox::Sizeof3D() const -{ -} +void TGeoBBox::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoBBox::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoBBox::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); @@ -1035,7 +1157,7 @@ const TBuffer3D & TGeoBBox::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co // TODO: A box itself has has nothing more as already described // by bounding box. How will viewer interpret? if (reqSections & TBuffer3D::kRawSizes) { - if (buffer.SetRawSizes(8, 3*8, 12, 3*12, 6, 6*6)) { + if (buffer.SetRawSizes(8, 3 * 8, 12, 3 * 12, 6, 6 * 6)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1056,12 +1178,12 @@ const TBuffer3D & TGeoBBox::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co /// Fills the supplied buffer, with sections in desired frame /// See TBuffer3D.h for explanation of sections, frame etc. -void TGeoBBox::FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t localFrame) const +void TGeoBBox::FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const { TGeoShape::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kBoundingBox) { - Double_t halfLengths[3] = { fDX, fDY, fDZ }; + Double_t halfLengths[3] = {fDX, fDY, fDZ}; buffer.SetAABoundingBox(fOrigin, halfLengths); if (!buffer.fLocalFrame) { @@ -1078,7 +1200,8 @@ void TGeoBBox::FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t localF void TGeoBBox::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i guard(fMutex); - if (tid >= fThreadSize) { - Error("GetThreadData", "Thread id=%d bigger than maximum declared thread number %d. \nUse TGeoManager::SetMaxThreads properly !!!", - tid, fThreadSize); - } - if (tid >= fThreadSize) - { - fThreadData.resize(tid + 1); - fThreadSize = tid + 1; - } - if (fThreadData[tid] == 0) - { - if (fThreadData[tid] == 0) - fThreadData[tid] = new ThreadData_t; - } -*/ + /* + std::lock_guard guard(fMutex); + if (tid >= fThreadSize) { + Error("GetThreadData", "Thread id=%d bigger than maximum declared thread number %d. \nUse + TGeoManager::SetMaxThreads properly !!!", tid, fThreadSize); + } + if (tid >= fThreadSize) + { + fThreadData.resize(tid + 1); + fThreadSize = tid + 1; + } + if (fThreadData[tid] == 0) + { + if (fThreadData[tid] == 0) + fThreadData[tid] = new ThreadData_t; + } + */ return *fThreadData[tid]; } @@ -91,9 +85,8 @@ TGeoBoolNode::ThreadData_t& TGeoBoolNode::GetThreadData() const void TGeoBoolNode::ClearThreadData() const { std::lock_guard guard(fMutex); - std::vector::iterator i = fThreadData.begin(); - while (i != fThreadData.end()) - { + std::vector::iterator i = fThreadData.begin(); + while (i != fThreadData.end()) { delete *i; ++i; } @@ -109,14 +102,16 @@ void TGeoBoolNode::CreateThreadData(Int_t nthreads) std::lock_guard guard(fMutex); fThreadData.resize(nthreads); fThreadSize = nthreads; - for (Int_t tid=0; tidCreateThreadData(nthreads); - if (fRight) fRight->CreateThreadData(nthreads); + if (fLeft) + fLeft->CreateThreadData(nthreads); + if (fRight) + fRight->CreateThreadData(nthreads); } //////////////////////////////////////////////////////////////////////////////// @@ -132,12 +127,12 @@ void TGeoBoolNode::SetSelected(Int_t sel) TGeoBoolNode::TGeoBoolNode() { - fLeft = nullptr; - fRight = nullptr; - fLeftMat = nullptr; + fLeft = nullptr; + fRight = nullptr; + fLeftMat = nullptr; fRightMat = nullptr; - fNpoints = 0; - fPoints = nullptr; + fNpoints = 0; + fPoints = nullptr; fThreadSize = 0; CreateThreadData(1); } @@ -147,12 +142,12 @@ TGeoBoolNode::TGeoBoolNode() TGeoBoolNode::TGeoBoolNode(const char *expr1, const char *expr2) { - fLeft = nullptr; - fRight = nullptr; - fLeftMat = nullptr; + fLeft = nullptr; + fRight = nullptr; + fLeftMat = nullptr; fRightMat = nullptr; - fNpoints = 0; - fPoints = nullptr; + fNpoints = 0; + fPoints = nullptr; fThreadSize = 0; CreateThreadData(1); if (!MakeBranch(expr1, kTRUE)) { @@ -171,15 +166,19 @@ TGeoBoolNode::TGeoBoolNode(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, fLeft = left; fRight = right; fLeftMat = lmat; - fNpoints = 0; - fPoints = nullptr; + fNpoints = 0; + fPoints = nullptr; fThreadSize = 0; CreateThreadData(1); - if (!fLeftMat) fLeftMat = gGeoIdentity; - else fLeftMat->RegisterYourself(); + if (!fLeftMat) + fLeftMat = gGeoIdentity; + else + fLeftMat->RegisterYourself(); fRightMat = rmat; - if (!fRightMat) fRightMat = gGeoIdentity; - else fRightMat->RegisterYourself(); + if (!fRightMat) + fRightMat = gGeoIdentity; + else + fRightMat->RegisterYourself(); if (!fLeft) { Error("ctor", "left shape is NULL"); return; @@ -196,7 +195,8 @@ TGeoBoolNode::TGeoBoolNode(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, TGeoBoolNode::~TGeoBoolNode() { - if (fPoints) delete [] fPoints; + if (fPoints) + delete[] fPoints; ClearThreadData(); } @@ -206,14 +206,14 @@ TGeoBoolNode::~TGeoBoolNode() void TGeoBoolNode::AssignPoints(Int_t npoints, Double_t *points) { if (fPoints) { - delete [] fPoints; + delete[] fPoints; fPoints = nullptr; fNpoints = 0; } if (points) { fNpoints = npoints; - fPoints = new Double_t[3*fNpoints]; - memcpy(fPoints, points, 3*fNpoints*sizeof(Double_t)); + fPoints = new Double_t[3 * fNpoints]; + memcpy(fPoints, points, 3 * fNpoints * sizeof(Double_t)); } } @@ -225,7 +225,7 @@ Bool_t TGeoBoolNode::MakeBranch(const char *expr, Bool_t left) { TString sleft, sright, stransf; Int_t boolop = TGeoManager::Parse(expr, sleft, sright, stransf); - if (boolop<0) { + if (boolop < 0) { Error("MakeBranch", "invalid expression"); return kFALSE; } @@ -236,46 +236,47 @@ Bool_t TGeoBoolNode::MakeBranch(const char *expr, Bool_t left) if (stransf.Length() == 0) { mat = gGeoIdentity; } else { - mat = (TGeoMatrix*)gGeoManager->GetListOfMatrices()->FindObject(stransf.Data()); + mat = (TGeoMatrix *)gGeoManager->GetListOfMatrices()->FindObject(stransf.Data()); } if (!mat) { Error("MakeBranch", "transformation %s not found", stransf.Data()); return kFALSE; } switch (boolop) { - case 0: - // elementary shape - shape = (TGeoShape*)gGeoManager->GetListOfShapes()->FindObject(sleft.Data()); - if (!shape) { - Error("MakeBranch", "shape %s not found", sleft.Data()); - return kFALSE; - } - break; - case 1: - // composite shape - union - newshape = sleft; - newshape += "+"; - newshape += sright; - shape = new TGeoCompositeShape(newshape.Data()); - break; - case 2: - // composite shape - difference - newshape = sleft; - newshape += "-"; - newshape += sright; - shape = new TGeoCompositeShape(newshape.Data()); - break; - case 3: - // composite shape - intersection - newshape = sleft; - newshape += "*"; - newshape += sright; - shape = new TGeoCompositeShape(newshape.Data()); - break; + case 0: + // elementary shape + shape = (TGeoShape *)gGeoManager->GetListOfShapes()->FindObject(sleft.Data()); + if (!shape) { + Error("MakeBranch", "shape %s not found", sleft.Data()); + return kFALSE; + } + break; + case 1: + // composite shape - union + newshape = sleft; + newshape += "+"; + newshape += sright; + shape = new TGeoCompositeShape(newshape.Data()); + break; + case 2: + // composite shape - difference + newshape = sleft; + newshape += "-"; + newshape += sright; + shape = new TGeoCompositeShape(newshape.Data()); + break; + case 3: + // composite shape - intersection + newshape = sleft; + newshape += "*"; + newshape += sright; + shape = new TGeoCompositeShape(newshape.Data()); + break; } if (boolop && (!shape || !shape->IsValid())) { Error("MakeBranch", "Shape %s not valid", newshape.Data()); - if (shape) delete shape; + if (shape) + delete shape; return kFALSE; } if (left) { @@ -291,17 +292,18 @@ Bool_t TGeoBoolNode::MakeBranch(const char *expr, Bool_t left) //////////////////////////////////////////////////////////////////////////////// /// Special schema for feeding the 3D buffers to the painter client. -void TGeoBoolNode::Paint(Option_t * option) +void TGeoBoolNode::Paint(Option_t *option) { - TVirtualViewer3D * viewer = gPad->GetViewer3D(); - if (!viewer) return; + TVirtualViewer3D *viewer = gPad->GetViewer3D(); + if (!viewer) + return; // Components of composite shape hierarchies for local frame viewers are painted // in coordinate frame of the top level composite shape. So we force // conversion to this. See TGeoPainter::PaintNode for loading of GLMatrix. - Bool_t localFrame = kFALSE; //viewer->PreferLocalFrame(); + Bool_t localFrame = kFALSE; // viewer->PreferLocalFrame(); - TGeoHMatrix *glmat = (TGeoHMatrix*)TGeoShape::GetTransform(); + TGeoHMatrix *glmat = (TGeoHMatrix *)TGeoShape::GetTransform(); TGeoHMatrix mat; mat = glmat; // keep a copy @@ -311,22 +313,22 @@ void TGeoBoolNode::Paint(Option_t * option) // Setup matrix and fetch/add the left component buffer glmat->Multiply(fLeftMat); - //fLeft->Paint(option); + // fLeft->Paint(option); if (TGeoCompositeShape *left = dynamic_cast(fLeft)) { left->PaintComposite(option); } else if (fLeft) { - const TBuffer3D & leftBuffer = fLeft->GetBuffer3D(TBuffer3D::kAll, localFrame); + const TBuffer3D &leftBuffer = fLeft->GetBuffer3D(TBuffer3D::kAll, localFrame); viewer->AddObject(leftBuffer); } // Setup matrix and fetch/add the right component buffer *glmat = &mat; glmat->Multiply(fRightMat); - //fRight->Paint(option); + // fRight->Paint(option); if (TGeoCompositeShape *right = dynamic_cast(fRight)) { right->PaintComposite(option); } else if (fRight) { - const TBuffer3D & rightBuffer = fRight->GetBuffer3D(TBuffer3D::kAll, localFrame); + const TBuffer3D &rightBuffer = fRight->GetBuffer3D(TBuffer3D::kAll, localFrame); viewer->AddObject(rightBuffer); } @@ -338,10 +340,14 @@ void TGeoBoolNode::Paint(Option_t * option) void TGeoBoolNode::RegisterMatrices() { - if (!fLeftMat->IsIdentity()) fLeftMat->RegisterYourself(); - if (!fRightMat->IsIdentity()) fRightMat->RegisterYourself(); - if (fLeft->IsComposite()) ((TGeoCompositeShape*)fLeft)->GetBoolNode()->RegisterMatrices(); - if (fRight->IsComposite()) ((TGeoCompositeShape*)fRight)->GetBoolNode()->RegisterMatrices(); + if (!fLeftMat->IsIdentity()) + fLeftMat->RegisterYourself(); + if (!fRightMat->IsIdentity()) + fRightMat->RegisterYourself(); + if (fLeft->IsComposite()) + ((TGeoCompositeShape *)fLeft)->GetBoolNode()->RegisterMatrices(); + if (fRight->IsComposite()) + ((TGeoCompositeShape *)fRight)->GetBoolNode()->RegisterMatrices(); } //////////////////////////////////////////////////////////////////////////////// @@ -350,8 +356,9 @@ void TGeoBoolNode::RegisterMatrices() Bool_t TGeoBoolNode::ReplaceMatrix(TGeoMatrix *mat, TGeoMatrix *newmat) { - if (mat==gGeoIdentity || newmat==gGeoIdentity) { - Error("ReplaceMatrix", "Matrices should not be gGeoIdentity. Use default matrix constructor to represent identities."); + if (mat == gGeoIdentity || newmat == gGeoIdentity) { + Error("ReplaceMatrix", + "Matrices should not be gGeoIdentity. Use default matrix constructor to represent identities."); return kFALSE; } if (!mat || !newmat) { @@ -360,11 +367,11 @@ Bool_t TGeoBoolNode::ReplaceMatrix(TGeoMatrix *mat, TGeoMatrix *newmat) } Bool_t replaced = kFALSE; if (fLeftMat == mat) { - fLeftMat = newmat; + fLeftMat = newmat; replaced = kTRUE; } if (fRightMat == mat) { - fRightMat = newmat; + fRightMat = newmat; replaced = kTRUE; } return replaced; @@ -375,15 +382,15 @@ Bool_t TGeoBoolNode::ReplaceMatrix(TGeoMatrix *mat, TGeoMatrix *newmat) void TGeoBoolNode::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - fLeft->SavePrimitive(out,option); - fRight->SavePrimitive(out,option); + fLeft->SavePrimitive(out, option); + fRight->SavePrimitive(out, option); if (!fLeftMat->IsIdentity()) { fLeftMat->RegisterYourself(); - fLeftMat->SavePrimitive(out,option); + fLeftMat->SavePrimitive(out, option); } if (!fRightMat->IsIdentity()) { fRightMat->RegisterYourself(); - fRightMat->SavePrimitive(out,option); + fRightMat->SavePrimitive(out, option); } } @@ -392,9 +399,9 @@ void TGeoBoolNode::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) void TGeoBoolNode::SetPoints(Double_t *points) const { - TGeoBoolNode *bn = (TGeoBoolNode*)this; + TGeoBoolNode *bn = (TGeoBoolNode *)this; Int_t npoints = bn->GetNpoints(); - memcpy(points, fPoints, 3*npoints*sizeof(Double_t)); + memcpy(points, fPoints, 3 * npoints * sizeof(Double_t)); } //////////////////////////////////////////////////////////////////////////////// @@ -402,9 +409,10 @@ void TGeoBoolNode::SetPoints(Double_t *points) const void TGeoBoolNode::SetPoints(Float_t *points) const { - TGeoBoolNode *bn = (TGeoBoolNode*)this; + TGeoBoolNode *bn = (TGeoBoolNode *)this; Int_t npoints = bn->GetNpoints(); - for (Int_t i=0; i<3*npoints; i++) points[i] = fPoints[i]; + for (Int_t i = 0; i < 3 * npoints; i++) + points[i] = fPoints[i]; } //////////////////////////////////////////////////////////////////////////////// @@ -446,23 +454,18 @@ void TGeoUnion::Paint(Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoUnion::TGeoUnion() -{ -} +TGeoUnion::TGeoUnion() {} //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoUnion::TGeoUnion(const char *expr1, const char *expr2) - :TGeoBoolNode(expr1, expr2) -{ -} +TGeoUnion::TGeoUnion(const char *expr1, const char *expr2) : TGeoBoolNode(expr1, expr2) {} //////////////////////////////////////////////////////////////////////////////// /// Constructor providing pointers to components TGeoUnion::TGeoUnion(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, TGeoMatrix *rmat) - :TGeoBoolNode(left,right,lmat,rmat) + : TGeoBoolNode(left, right, lmat, rmat) { if (left->TestShapeBit(TGeoShape::kGeoHalfSpace) || right->TestShapeBit(TGeoShape::kGeoHalfSpace)) { Fatal("TGeoUnion", "Unions with a half-space (%s + %s) not allowed", left->GetName(), right->GetName()); @@ -473,49 +476,61 @@ TGeoUnion::TGeoUnion(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, TGeoMa /// Destructor /// --- deletion of components handled by TGeoManager class. -TGeoUnion::~TGeoUnion() -{ -} +TGeoUnion::~TGeoUnion() {} //////////////////////////////////////////////////////////////////////////////// /// Compute bounding box corresponding to a union of two shapes. void TGeoUnion::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) { - if (((TGeoBBox*)fLeft)->IsNullBox()) fLeft->ComputeBBox(); - if (((TGeoBBox*)fRight)->IsNullBox()) fRight->ComputeBBox(); + if (((TGeoBBox *)fLeft)->IsNullBox()) + fLeft->ComputeBBox(); + if (((TGeoBBox *)fRight)->IsNullBox()) + fRight->ComputeBBox(); Double_t vert[48]; Double_t pt[3]; Int_t i; Double_t xmin, xmax, ymin, ymax, zmin, zmax; xmin = ymin = zmin = TGeoShape::Big(); xmax = ymax = zmax = -TGeoShape::Big(); - ((TGeoBBox*)fLeft)->SetBoxPoints(&vert[0]); - ((TGeoBBox*)fRight)->SetBoxPoints(&vert[24]); - for (i=0; i<8; i++) { - fLeftMat->LocalToMaster(&vert[3*i], &pt[0]); - if (pt[0]xmax) xmax=pt[0]; - if (pt[1]ymax) ymax=pt[1]; - if (pt[2]zmax) zmax=pt[2]; - } - for (i=8; i<16; i++) { - fRightMat->LocalToMaster(&vert[3*i], &pt[0]); - if (pt[0]xmax) xmax=pt[0]; - if (pt[1]ymax) ymax=pt[1]; - if (pt[2]zmax) zmax=pt[2]; - } - dx = 0.5*(xmax-xmin); - origin[0] = 0.5*(xmin+xmax); - dy = 0.5*(ymax-ymin); - origin[1] = 0.5*(ymin+ymax); - dz = 0.5*(zmax-zmin); - origin[2] = 0.5*(zmin+zmax); + ((TGeoBBox *)fLeft)->SetBoxPoints(&vert[0]); + ((TGeoBBox *)fRight)->SetBoxPoints(&vert[24]); + for (i = 0; i < 8; i++) { + fLeftMat->LocalToMaster(&vert[3 * i], &pt[0]); + if (pt[0] < xmin) + xmin = pt[0]; + if (pt[0] > xmax) + xmax = pt[0]; + if (pt[1] < ymin) + ymin = pt[1]; + if (pt[1] > ymax) + ymax = pt[1]; + if (pt[2] < zmin) + zmin = pt[2]; + if (pt[2] > zmax) + zmax = pt[2]; + } + for (i = 8; i < 16; i++) { + fRightMat->LocalToMaster(&vert[3 * i], &pt[0]); + if (pt[0] < xmin) + xmin = pt[0]; + if (pt[0] > xmax) + xmax = pt[0]; + if (pt[1] < ymin) + ymin = pt[1]; + if (pt[1] > ymax) + ymax = pt[1]; + if (pt[2] < zmin) + zmin = pt[2]; + if (pt[2] > zmax) + zmax = pt[2]; + } + dx = 0.5 * (xmax - xmin); + origin[0] = 0.5 * (xmin + xmax); + dy = 0.5 * (ymax - ymin); + origin[1] = 0.5 * (ymin + ymax); + dz = 0.5 * (zmax - zmin); + origin[2] = 0.5 * (zmin + zmax); } //////////////////////////////////////////////////////////////////////////////// @@ -526,7 +541,8 @@ Bool_t TGeoUnion::Contains(const Double_t *point) const Double_t local[3]; fLeftMat->MasterToLocal(point, &local[0]); Bool_t inside = fLeft->Contains(&local[0]); - if (inside) return kTRUE; + if (inside) + return kTRUE; fRightMat->MasterToLocal(point, &local[0]); inside = fRight->Contains(&local[0]); return inside; @@ -537,7 +553,7 @@ Bool_t TGeoUnion::Contains(const Double_t *point) const void TGeoUnion::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); norm[0] = norm[1] = 0.; norm[2] = 1.; Double_t local[3]; @@ -545,43 +561,44 @@ void TGeoUnion::ComputeNormal(const Double_t *point, const Double_t *dir, Double if (td.fSelected == 1) { fLeftMat->MasterToLocal(point, local); fLeftMat->MasterToLocalVect(dir, ldir); - fLeft->ComputeNormal(local,ldir,lnorm); + fLeft->ComputeNormal(local, ldir, lnorm); fLeftMat->LocalToMasterVect(lnorm, norm); return; } if (td.fSelected == 2) { fRightMat->MasterToLocal(point, local); fRightMat->MasterToLocalVect(dir, ldir); - fRight->ComputeNormal(local,ldir,lnorm); + fRight->ComputeNormal(local, ldir, lnorm); fRightMat->LocalToMasterVect(lnorm, norm); return; } fLeftMat->MasterToLocal(point, local); if (fLeft->Contains(local)) { fLeftMat->MasterToLocalVect(dir, ldir); - fLeft->ComputeNormal(local,ldir,lnorm); + fLeft->ComputeNormal(local, ldir, lnorm); fLeftMat->LocalToMasterVect(lnorm, norm); return; } fRightMat->MasterToLocal(point, local); if (fRight->Contains(local)) { fRightMat->MasterToLocalVect(dir, ldir); - fRight->ComputeNormal(local,ldir,lnorm); + fRight->ComputeNormal(local, ldir, lnorm); fRightMat->LocalToMasterVect(lnorm, norm); return; } // Propagate forward/backward to see which of the components is intersected first - local[0] = point[0] + 1E-5*dir[0]; - local[1] = point[1] + 1E-5*dir[1]; - local[2] = point[2] + 1E-5*dir[2]; + local[0] = point[0] + 1E-5 * dir[0]; + local[1] = point[1] + 1E-5 * dir[1]; + local[2] = point[2] + 1E-5 * dir[2]; if (!Contains(local)) { - local[0] = point[0] - 1E-5*dir[0]; - local[1] = point[1] - 1E-5*dir[1]; - local[2] = point[2] - 1E-5*dir[2]; - if (!Contains(local)) return; + local[0] = point[0] - 1E-5 * dir[0]; + local[1] = point[1] - 1E-5 * dir[1]; + local[2] = point[2] - 1E-5 * dir[2]; + if (!Contains(local)) + return; } - ComputeNormal(local,dir,norm); + ComputeNormal(local, dir, norm); } //////////////////////////////////////////////////////////////////////////////// @@ -595,76 +612,89 @@ Int_t TGeoUnion::DistanceToPrimitive(Int_t /*px*/, Int_t /*py*/) //////////////////////////////////////////////////////////////////////////////// /// Computes distance from a given point inside the shape to its boundary. -Double_t TGeoUnion::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t +TGeoUnion::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kTRUE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } Double_t local[3], local1[3], master[3], ldir[3], rdir[3], pushed[3]; - memcpy(master, point, 3*sizeof(Double_t)); + memcpy(master, point, 3 * sizeof(Double_t)); Int_t i; - TGeoBoolNode *node = (TGeoBoolNode*)this; - Double_t d1=0., d2=0., snxt=0., eps=0.; + TGeoBoolNode *node = (TGeoBoolNode *)this; + Double_t d1 = 0., d2 = 0., snxt = 0., eps = 0.; fLeftMat->MasterToLocalVect(dir, ldir); fRightMat->MasterToLocalVect(dir, rdir); fLeftMat->MasterToLocal(point, local); Bool_t inside1 = fLeft->Contains(local); - if (inside1) d1 = fLeft->DistFromInside(local, ldir, 3); - else memcpy(local1, local, 3*sizeof(Double_t)); + if (inside1) + d1 = fLeft->DistFromInside(local, ldir, 3); + else + memcpy(local1, local, 3 * sizeof(Double_t)); fRightMat->MasterToLocal(point, local); Bool_t inside2 = fRight->Contains(local); - if (inside2) d2 = fRight->DistFromInside(local, rdir, 3); + if (inside2) + d2 = fRight->DistFromInside(local, rdir, 3); if (!(inside1 | inside2)) { - // This is a pathological case when the point is on the boundary + // This is a pathological case when the point is on the boundary d1 = fLeft->DistFromOutside(local1, ldir, 3); - if (d1<1.E-3) { - eps = d1+TGeoShape::Tolerance(); - for (i=0; i<3; i++) local1[i] += eps*ldir[i]; + if (d1 < 1.E-3) { + eps = d1 + TGeoShape::Tolerance(); + for (i = 0; i < 3; i++) + local1[i] += eps * ldir[i]; inside1 = kTRUE; d1 = fLeft->DistFromInside(local1, ldir, 3); d1 += eps; } else { d2 = fRight->DistFromOutside(local, rdir, 3); - if (d2<1.E-3) { - eps = d2+TGeoShape::Tolerance(); - for (i=0; i<3; i++) local[i] += eps*rdir[i]; - inside2 = kTRUE; - d2 = fRight->DistFromInside(local, rdir, 3); - d2 += eps; - } - } + if (d2 < 1.E-3) { + eps = d2 + TGeoShape::Tolerance(); + for (i = 0; i < 3; i++) + local[i] += eps * rdir[i]; + inside2 = kTRUE; + d2 = fRight->DistFromInside(local, rdir, 3); + d2 += eps; + } + } } while (inside1 || inside2) { if (inside1 && inside2) { - if (d1SetSelected(1); // propagate to exit of left shape inside1 = kFALSE; - for (i=0; i<3; i++) master[i] += d1*dir[i]; + for (i = 0; i < 3; i++) + master[i] += d1 * dir[i]; // check if propagated point is in right shape fRightMat->MasterToLocal(master, local); inside2 = fRight->Contains(local); - if (!inside2) return snxt; + if (!inside2) + return snxt; d2 = fRight->DistFromInside(local, rdir, 3); - if (d2 < TGeoShape::Tolerance()) return snxt; + if (d2 < TGeoShape::Tolerance()) + return snxt; } else { snxt += d2; node->SetSelected(2); // propagate to exit of right shape inside2 = kFALSE; - for (i=0; i<3; i++) master[i] += d2*dir[i]; + for (i = 0; i < 3; i++) + master[i] += d2 * dir[i]; // check if propagated point is in left shape fLeftMat->MasterToLocal(master, local); inside1 = fLeft->Contains(local); - if (!inside1) return snxt; + if (!inside1) + return snxt; d1 = fLeft->DistFromInside(local, ldir, 3); - if (d1 < TGeoShape::Tolerance()) return snxt; + if (d1 < TGeoShape::Tolerance()) + return snxt; } } if (inside1) { @@ -672,34 +702,38 @@ Double_t TGeoUnion::DistFromInside(const Double_t *point, const Double_t *dir, I node->SetSelected(1); // propagate to exit of left shape inside1 = kFALSE; - for (i=0; i<3; i++) { - master[i] += d1*dir[i]; - pushed[i] = master[i]+(1.+d1)*TGeoShape::Tolerance()*dir[i]; + for (i = 0; i < 3; i++) { + master[i] += d1 * dir[i]; + pushed[i] = master[i] + (1. + d1) * TGeoShape::Tolerance() * dir[i]; } // check if propagated point is in right shape fRightMat->MasterToLocal(pushed, local); inside2 = fRight->Contains(local); - if (!inside2) return snxt; + if (!inside2) + return snxt; d2 = fRight->DistFromInside(local, rdir, 3); - if (d2 < TGeoShape::Tolerance()) return snxt; - d2 += (1.+d1)*TGeoShape::Tolerance(); + if (d2 < TGeoShape::Tolerance()) + return snxt; + d2 += (1. + d1) * TGeoShape::Tolerance(); } if (inside2) { snxt += d2; node->SetSelected(2); // propagate to exit of right shape inside2 = kFALSE; - for (i=0; i<3; i++) { - master[i] += d2*dir[i]; - pushed[i] = master[i]+(1.+d2)*TGeoShape::Tolerance()*dir[i]; + for (i = 0; i < 3; i++) { + master[i] += d2 * dir[i]; + pushed[i] = master[i] + (1. + d2) * TGeoShape::Tolerance() * dir[i]; } // check if propagated point is in left shape fLeftMat->MasterToLocal(pushed, local); inside1 = fLeft->Contains(local); - if (!inside1) return snxt; + if (!inside1) + return snxt; d1 = fLeft->DistFromInside(local, ldir, 3); - if (d1 < TGeoShape::Tolerance()) return snxt; - d1 += (1.+d2)*TGeoShape::Tolerance(); + if (d1 < TGeoShape::Tolerance()) + return snxt; + d1 += (1. + d2) * TGeoShape::Tolerance(); } } return snxt; @@ -708,16 +742,18 @@ Double_t TGeoUnion::DistFromInside(const Double_t *point, const Double_t *dir, I //////////////////////////////////////////////////////////////////////////////// /// Compute distance from a given outside point to the shape. -Double_t TGeoUnion::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t +TGeoUnion::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kFALSE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoBoolNode *node = (TGeoBoolNode*)this; + TGeoBoolNode *node = (TGeoBoolNode *)this; Double_t local[3], ldir[3], rdir[3]; Double_t d1, d2, snxt; fLeftMat->MasterToLocal(point, &local[0]); @@ -726,7 +762,7 @@ Double_t TGeoUnion::DistFromOutside(const Double_t *point, const Double_t *dir, d1 = fLeft->DistFromOutside(&local[0], &ldir[0], iact, step, safe); fRightMat->MasterToLocal(point, &local[0]); d2 = fRight->DistFromOutside(&local[0], &rdir[0], iact, step, safe); - if (d1SetSelected(1); } else { @@ -741,37 +777,42 @@ Double_t TGeoUnion::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t TGeoUnion::GetNpoints() { - Int_t itot=0; + Int_t itot = 0; Double_t point[3]; Double_t tolerance = TGeoShape::Tolerance(); - if (fNpoints) return fNpoints; + if (fNpoints) + return fNpoints; // Local points for the left shape Int_t nleft = fLeft->GetNmeshVertices(); - Double_t *points1 = new Double_t[3*nleft]; + Double_t *points1 = new Double_t[3 * nleft]; fLeft->SetPoints(points1); // Local points for the right shape Int_t nright = fRight->GetNmeshVertices(); - Double_t *points2 = new Double_t[3*nright]; + Double_t *points2 = new Double_t[3 * nright]; fRight->SetPoints(points2); - Double_t *points = new Double_t[3*(nleft+nright)]; - for (Int_t i=0; iLocalToMaster(&points1[3*i], &points[3*itot]); - fRightMat->MasterToLocal(&points[3*itot], point); - if (!fRight->Contains(point)) itot++; - } - for (Int_t i=0; iLocalToMaster(&points2[3*i], &points[3*itot]); - fLeftMat->MasterToLocal(&points[3*itot], point); - if (!fLeft->Contains(point)) itot++; + Double_t *points = new Double_t[3 * (nleft + nright)]; + for (Int_t i = 0; i < nleft; i++) { + if (TMath::Abs(points1[3 * i]) < tolerance && TMath::Abs(points1[3 * i + 1]) < tolerance) + continue; + fLeftMat->LocalToMaster(&points1[3 * i], &points[3 * itot]); + fRightMat->MasterToLocal(&points[3 * itot], point); + if (!fRight->Contains(point)) + itot++; + } + for (Int_t i = 0; i < nright; i++) { + if (TMath::Abs(points2[3 * i]) < tolerance && TMath::Abs(points2[3 * i + 1]) < tolerance) + continue; + fRightMat->LocalToMaster(&points2[3 * i], &points[3 * itot]); + fLeftMat->MasterToLocal(&points[3 * itot], point); + if (!fLeft->Contains(point)) + itot++; } AssignPoints(itot, points); - delete [] points1; - delete [] points2; - delete [] points; + delete[] points1; + delete[] points2; + delete[] points; return fNpoints; } @@ -781,18 +822,22 @@ Int_t TGeoUnion::GetNpoints() Double_t TGeoUnion::Safety(const Double_t *point, Bool_t in) const { Double_t local1[3], local2[3]; - fLeftMat->MasterToLocal(point,local1); + fLeftMat->MasterToLocal(point, local1); Bool_t in1 = fLeft->Contains(local1); - fRightMat->MasterToLocal(point,local2); + fRightMat->MasterToLocal(point, local2); Bool_t in2 = fRight->Contains(local2); Bool_t intrue = in1 | in2; - if (intrue^in) return 0.0; + if (intrue ^ in) + return 0.0; Double_t saf1 = fLeft->Safety(local1, in1); Double_t saf2 = fRight->Safety(local2, in2); - if (in1 && in2) return TMath::Min(saf1, saf2); - if (in1) return saf1; - if (in2) return saf2; - return TMath::Min(saf1,saf2); + if (in1 && in2) + return TMath::Min(saf1, saf2); + if (in1) + return saf1; + if (in2) + return saf2; + return TMath::Min(saf1, saf2); } //////////////////////////////////////////////////////////////////////////////// @@ -800,14 +845,18 @@ Double_t TGeoUnion::Safety(const Double_t *point, Bool_t in) const void TGeoUnion::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - TGeoBoolNode::SavePrimitive(out,option); + TGeoBoolNode::SavePrimitive(out, option); out << " pBoolNode = new TGeoUnion("; out << fLeft->GetPointerName() << ","; out << fRight->GetPointerName() << ","; - if (!fLeftMat->IsIdentity()) out << fLeftMat->GetPointerName() << ","; - else out << "0,"; - if (!fRightMat->IsIdentity()) out << fRightMat->GetPointerName() << ");" << std::endl; - else out << "0);" << std::endl; + if (!fLeftMat->IsIdentity()) + out << fLeftMat->GetPointerName() << ","; + else + out << "0,"; + if (!fRightMat->IsIdentity()) + out << fRightMat->GetPointerName() << ");" << std::endl; + else + out << "0);" << std::endl; } //////////////////////////////////////////////////////////////////////////////// @@ -818,7 +867,6 @@ void TGeoUnion::Sizeof3D() const TGeoBoolNode::Sizeof3D(); } - ClassImp(TGeoSubtraction); //////////////////////////////////////////////////////////////////////////////// @@ -849,23 +897,18 @@ void TGeoSubtraction::Paint(Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoSubtraction::TGeoSubtraction() -{ -} +TGeoSubtraction::TGeoSubtraction() {} //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoSubtraction::TGeoSubtraction(const char *expr1, const char *expr2) - :TGeoBoolNode(expr1, expr2) -{ -} +TGeoSubtraction::TGeoSubtraction(const char *expr1, const char *expr2) : TGeoBoolNode(expr1, expr2) {} //////////////////////////////////////////////////////////////////////////////// /// Constructor providing pointers to components TGeoSubtraction::TGeoSubtraction(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, TGeoMatrix *rmat) - :TGeoBoolNode(left,right,lmat,rmat) + : TGeoBoolNode(left, right, lmat, rmat) { if (left->TestShapeBit(TGeoShape::kGeoHalfSpace)) { Fatal("TGeoSubstraction", "Subtractions from a half-space (%s) not allowed", left->GetName()); @@ -876,17 +919,16 @@ TGeoSubtraction::TGeoSubtraction(TGeoShape *left, TGeoShape *right, TGeoMatrix * /// Destructor /// --- deletion of components handled by TGeoManager class. -TGeoSubtraction::~TGeoSubtraction() -{ -} +TGeoSubtraction::~TGeoSubtraction() {} //////////////////////////////////////////////////////////////////////////////// /// Compute bounding box corresponding to a subtraction of two shapes. void TGeoSubtraction::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) { - TGeoBBox *box = (TGeoBBox*)fLeft; - if (box->IsNullBox()) fLeft->ComputeBBox(); + TGeoBBox *box = (TGeoBBox *)fLeft; + if (box->IsNullBox()) + fLeft->ComputeBBox(); Double_t vert[24]; Double_t pt[3]; Int_t i; @@ -894,21 +936,27 @@ void TGeoSubtraction::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Doub xmin = ymin = zmin = TGeoShape::Big(); xmax = ymax = zmax = -TGeoShape::Big(); box->SetBoxPoints(&vert[0]); - for (i=0; i<8; i++) { - fLeftMat->LocalToMaster(&vert[3*i], &pt[0]); - if (pt[0]xmax) xmax=pt[0]; - if (pt[1]ymax) ymax=pt[1]; - if (pt[2]zmax) zmax=pt[2]; - } - dx = 0.5*(xmax-xmin); - origin[0] = 0.5*(xmin+xmax); - dy = 0.5*(ymax-ymin); - origin[1] = 0.5*(ymin+ymax); - dz = 0.5*(zmax-zmin); - origin[2] = 0.5*(zmin+zmax); + for (i = 0; i < 8; i++) { + fLeftMat->LocalToMaster(&vert[3 * i], &pt[0]); + if (pt[0] < xmin) + xmin = pt[0]; + if (pt[0] > xmax) + xmax = pt[0]; + if (pt[1] < ymin) + ymin = pt[1]; + if (pt[1] > ymax) + ymax = pt[1]; + if (pt[2] < zmin) + zmin = pt[2]; + if (pt[2] > zmax) + zmax = pt[2]; + } + dx = 0.5 * (xmax - xmin); + origin[0] = 0.5 * (xmin + xmax); + dy = 0.5 * (ymax - ymin); + origin[1] = 0.5 * (ymin + ymax); + dz = 0.5 * (zmax - zmin); + origin[2] = 0.5 * (zmin + zmax); } //////////////////////////////////////////////////////////////////////////////// @@ -916,49 +964,50 @@ void TGeoSubtraction::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Doub void TGeoSubtraction::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); norm[0] = norm[1] = 0.; norm[2] = 1.; Double_t local[3], ldir[3], lnorm[3]; if (td.fSelected == 1) { fLeftMat->MasterToLocal(point, local); fLeftMat->MasterToLocalVect(dir, ldir); - fLeft->ComputeNormal(local,ldir,lnorm); + fLeft->ComputeNormal(local, ldir, lnorm); fLeftMat->LocalToMasterVect(lnorm, norm); return; } if (td.fSelected == 2) { fRightMat->MasterToLocal(point, local); fRightMat->MasterToLocalVect(dir, ldir); - fRight->ComputeNormal(local,ldir,lnorm); + fRight->ComputeNormal(local, ldir, lnorm); fRightMat->LocalToMasterVect(lnorm, norm); return; } - fRightMat->MasterToLocal(point,local); + fRightMat->MasterToLocal(point, local); if (fRight->Contains(local)) { - fRightMat->MasterToLocalVect(dir,ldir); - fRight->ComputeNormal(local,ldir, lnorm); - fRightMat->LocalToMasterVect(lnorm,norm); + fRightMat->MasterToLocalVect(dir, ldir); + fRight->ComputeNormal(local, ldir, lnorm); + fRightMat->LocalToMasterVect(lnorm, norm); return; } - fLeftMat->MasterToLocal(point,local); + fLeftMat->MasterToLocal(point, local); if (!fLeft->Contains(local)) { - fLeftMat->MasterToLocalVect(dir,ldir); - fLeft->ComputeNormal(local,ldir, lnorm); - fLeftMat->LocalToMasterVect(lnorm,norm); + fLeftMat->MasterToLocalVect(dir, ldir); + fLeft->ComputeNormal(local, ldir, lnorm); + fLeftMat->LocalToMasterVect(lnorm, norm); return; } // point is inside left shape, but not inside the right - local[0] = point[0]+1E-5*dir[0]; - local[1] = point[1]+1E-5*dir[1]; - local[2] = point[2]+1E-5*dir[2]; + local[0] = point[0] + 1E-5 * dir[0]; + local[1] = point[1] + 1E-5 * dir[1]; + local[2] = point[2] + 1E-5 * dir[2]; if (Contains(local)) { - local[0] = point[0]-1E-5*dir[0]; - local[1] = point[1]-1E-5*dir[1]; - local[2] = point[2]-1E-5*dir[2]; - if (Contains(local)) return; + local[0] = point[0] - 1E-5 * dir[0]; + local[1] = point[1] - 1E-5 * dir[1]; + local[2] = point[2] - 1E-5 * dir[2]; + if (Contains(local)) + return; } - ComputeNormal(local,dir,norm); + ComputeNormal(local, dir, norm); } //////////////////////////////////////////////////////////////////////////////// @@ -969,7 +1018,8 @@ Bool_t TGeoSubtraction::Contains(const Double_t *point) const Double_t local[3]; fLeftMat->MasterToLocal(point, &local[0]); Bool_t inside = fLeft->Contains(&local[0]); - if (!inside) return kFALSE; + if (!inside) + return kFALSE; fRightMat->MasterToLocal(point, &local[0]); inside = !fRight->Contains(&local[0]); return inside; @@ -986,25 +1036,27 @@ Int_t TGeoSubtraction::DistanceToPrimitive(Int_t /*px*/, Int_t /*py*/) //////////////////////////////////////////////////////////////////////////////// /// Compute distance from a given point inside to the shape boundary. -Double_t TGeoSubtraction::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoSubtraction::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kTRUE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoBoolNode *node = (TGeoBoolNode*)this; + TGeoBoolNode *node = (TGeoBoolNode *)this; Double_t local[3], ldir[3], rdir[3]; - Double_t d1, d2, snxt=0.; + Double_t d1, d2, snxt = 0.; fLeftMat->MasterToLocal(point, &local[0]); fLeftMat->MasterToLocalVect(dir, &ldir[0]); fRightMat->MasterToLocalVect(dir, &rdir[0]); d1 = fLeft->DistFromInside(&local[0], &ldir[0], iact, step, safe); fRightMat->MasterToLocal(point, &local[0]); d2 = fRight->DistFromOutside(&local[0], &rdir[0], iact, step, safe); - if (d1SetSelected(1); } else { @@ -1017,20 +1069,22 @@ Double_t TGeoSubtraction::DistFromInside(const Double_t *point, const Double_t * //////////////////////////////////////////////////////////////////////////////// /// Compute distance from a given point outside to the shape. -Double_t TGeoSubtraction::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoSubtraction::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kFALSE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoBoolNode *node = (TGeoBoolNode*)this; + TGeoBoolNode *node = (TGeoBoolNode *)this; Double_t local[3], master[3], ldir[3], rdir[3]; - memcpy(&master[0], point, 3*sizeof(Double_t)); + memcpy(&master[0], point, 3 * sizeof(Double_t)); Int_t i; - Double_t d1, d2, snxt=0.; + Double_t d1, d2, snxt = 0.; fRightMat->MasterToLocal(point, &local[0]); fLeftMat->MasterToLocalVect(dir, &ldir[0]); fRightMat->MasterToLocalVect(dir, &rdir[0]); @@ -1042,28 +1096,32 @@ Double_t TGeoSubtraction::DistFromOutside(const Double_t *point, const Double_t // propagate to outside of '-' node->SetSelected(2); d1 = fRight->DistFromInside(&local[0], &rdir[0], iact, step, safe); - snxt += d1+epsil; - for (i=0; i<3; i++) master[i] += (d1+1E-8)*dir[i]; + snxt += d1 + epsil; + for (i = 0; i < 3; i++) + master[i] += (d1 + 1E-8) * dir[i]; epsil = 1.E-8; // now master outside '-'; check if inside '+' fLeftMat->MasterToLocal(&master[0], &local[0]); - if (fLeft->Contains(&local[0])) return snxt; + if (fLeft->Contains(&local[0])) + return snxt; } // master outside '-' and outside '+' ; find distances to both node->SetSelected(1); fLeftMat->MasterToLocal(&master[0], &local[0]); d2 = fLeft->DistFromOutside(&local[0], &ldir[0], iact, step, safe); - if (d2>1E20) return TGeoShape::Big(); + if (d2 > 1E20) + return TGeoShape::Big(); fRightMat->MasterToLocal(&master[0], &local[0]); d1 = fRight->DistFromOutside(&local[0], &rdir[0], iact, step, safe); - if (d2MasterToLocal(&master[0], &local[0]); @@ -1076,35 +1134,40 @@ Double_t TGeoSubtraction::DistFromOutside(const Double_t *point, const Double_t Int_t TGeoSubtraction::GetNpoints() { - Int_t itot=0; + Int_t itot = 0; Double_t point[3]; Double_t tolerance = TGeoShape::Tolerance(); - if (fNpoints) return fNpoints; + if (fNpoints) + return fNpoints; Int_t nleft = fLeft->GetNmeshVertices(); Int_t nright = fRight->GetNmeshVertices(); - Double_t *points = new Double_t[3*(nleft+nright)]; - Double_t *points1 = new Double_t[3*nleft]; + Double_t *points = new Double_t[3 * (nleft + nright)]; + Double_t *points1 = new Double_t[3 * nleft]; fLeft->SetPoints(points1); - for (Int_t i=0; iLocalToMaster(&points1[3*i], &points[3*itot]); - fRightMat->MasterToLocal(&points[3*itot], point); - if (!fRight->Contains(point)) itot++; - } - Double_t *points2 = new Double_t[3*nright]; + for (Int_t i = 0; i < nleft; i++) { + if (TMath::Abs(points1[3 * i]) < tolerance && TMath::Abs(points1[3 * i + 1]) < tolerance) + continue; + fLeftMat->LocalToMaster(&points1[3 * i], &points[3 * itot]); + fRightMat->MasterToLocal(&points[3 * itot], point); + if (!fRight->Contains(point)) + itot++; + } + Double_t *points2 = new Double_t[3 * nright]; fRight->SetPoints(points2); - for (Int_t i=0; iLocalToMaster(&points2[3*i], &points[3*itot]); - fLeftMat->MasterToLocal(&points[3*itot], point); - if (fLeft->Contains(point)) itot++; + for (Int_t i = 0; i < nright; i++) { + if (TMath::Abs(points2[3 * i]) < tolerance && TMath::Abs(points2[3 * i + 1]) < tolerance) + continue; + fRightMat->LocalToMaster(&points2[3 * i], &points[3 * itot]); + fLeftMat->MasterToLocal(&points[3 * itot], point); + if (fLeft->Contains(point)) + itot++; } AssignPoints(itot, points); - delete [] points1; - delete [] points2; - delete [] points; + delete[] points1; + delete[] points2; + delete[] points; return fNpoints; } @@ -1114,17 +1177,21 @@ Int_t TGeoSubtraction::GetNpoints() Double_t TGeoSubtraction::Safety(const Double_t *point, Bool_t in) const { Double_t local1[3], local2[3]; - fLeftMat->MasterToLocal(point,local1); + fLeftMat->MasterToLocal(point, local1); Bool_t in1 = fLeft->Contains(local1); - fRightMat->MasterToLocal(point,local2); + fRightMat->MasterToLocal(point, local2); Bool_t in2 = fRight->Contains(local2); Bool_t intrue = in1 && (!in2); - if (in^intrue) return 0.0; + if (in ^ intrue) + return 0.0; Double_t saf1 = fLeft->Safety(local1, in1); Double_t saf2 = fRight->Safety(local2, in2); - if (in1 && in2) return saf2; - if (in1) return TMath::Min(saf1,saf2); - if (in2) return TMath::Max(saf1,saf2); + if (in1 && in2) + return saf2; + if (in1) + return TMath::Min(saf1, saf2); + if (in2) + return TMath::Max(saf1, saf2); return saf1; } @@ -1133,14 +1200,18 @@ Double_t TGeoSubtraction::Safety(const Double_t *point, Bool_t in) const void TGeoSubtraction::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - TGeoBoolNode::SavePrimitive(out,option); + TGeoBoolNode::SavePrimitive(out, option); out << " pBoolNode = new TGeoSubtraction("; out << fLeft->GetPointerName() << ","; out << fRight->GetPointerName() << ","; - if (!fLeftMat->IsIdentity()) out << fLeftMat->GetPointerName() << ","; - else out << "0,"; - if (!fRightMat->IsIdentity()) out << fRightMat->GetPointerName() << ");" << std::endl; - else out << "0);" << std::endl; + if (!fLeftMat->IsIdentity()) + out << fLeftMat->GetPointerName() << ","; + else + out << "0,"; + if (!fRightMat->IsIdentity()) + out << fRightMat->GetPointerName() << ");" << std::endl; + else + out << "0);" << std::endl; } //////////////////////////////////////////////////////////////////////////////// @@ -1181,93 +1252,101 @@ void TGeoIntersection::Paint(Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoIntersection::TGeoIntersection() -{ -} +TGeoIntersection::TGeoIntersection() {} //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoIntersection::TGeoIntersection(const char *expr1, const char *expr2) - :TGeoBoolNode(expr1, expr2) -{ -} +TGeoIntersection::TGeoIntersection(const char *expr1, const char *expr2) : TGeoBoolNode(expr1, expr2) {} //////////////////////////////////////////////////////////////////////////////// /// Constructor providing pointers to components TGeoIntersection::TGeoIntersection(TGeoShape *left, TGeoShape *right, TGeoMatrix *lmat, TGeoMatrix *rmat) - :TGeoBoolNode(left,right,lmat,rmat) + : TGeoBoolNode(left, right, lmat, rmat) { - Bool_t hs1 = (fLeft->TestShapeBit(TGeoShape::kGeoHalfSpace))?kTRUE:kFALSE; - Bool_t hs2 = (fRight->TestShapeBit(TGeoShape::kGeoHalfSpace))?kTRUE:kFALSE; - if (hs1 && hs2) Fatal("ctor", "cannot intersect two half-spaces: %s * %s", left->GetName(), right->GetName()); + Bool_t hs1 = (fLeft->TestShapeBit(TGeoShape::kGeoHalfSpace)) ? kTRUE : kFALSE; + Bool_t hs2 = (fRight->TestShapeBit(TGeoShape::kGeoHalfSpace)) ? kTRUE : kFALSE; + if (hs1 && hs2) + Fatal("ctor", "cannot intersect two half-spaces: %s * %s", left->GetName(), right->GetName()); } //////////////////////////////////////////////////////////////////////////////// /// Destructor /// --- deletion of components handled by TGeoManager class. -TGeoIntersection::~TGeoIntersection() -{ -} +TGeoIntersection::~TGeoIntersection() {} //////////////////////////////////////////////////////////////////////////////// /// Compute bounding box corresponding to a intersection of two shapes. void TGeoIntersection::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Double_t *origin) { - Bool_t hs1 = (fLeft->TestShapeBit(TGeoShape::kGeoHalfSpace))?kTRUE:kFALSE; - Bool_t hs2 = (fRight->TestShapeBit(TGeoShape::kGeoHalfSpace))?kTRUE:kFALSE; + Bool_t hs1 = (fLeft->TestShapeBit(TGeoShape::kGeoHalfSpace)) ? kTRUE : kFALSE; + Bool_t hs2 = (fRight->TestShapeBit(TGeoShape::kGeoHalfSpace)) ? kTRUE : kFALSE; Double_t vert[48]; Double_t pt[3]; Int_t i; Double_t xmin1, xmax1, ymin1, ymax1, zmin1, zmax1; Double_t xmin2, xmax2, ymin2, ymax2, zmin2, zmax2; xmin1 = ymin1 = zmin1 = xmin2 = ymin2 = zmin2 = TGeoShape::Big(); - xmax1 = ymax1 = zmax1 = xmax2 = ymax2 = zmax2 = -TGeoShape::Big(); + xmax1 = ymax1 = zmax1 = xmax2 = ymax2 = zmax2 = -TGeoShape::Big(); if (!hs1) { - if (((TGeoBBox*)fLeft)->IsNullBox()) fLeft->ComputeBBox(); - ((TGeoBBox*)fLeft)->SetBoxPoints(&vert[0]); - for (i=0; i<8; i++) { - fLeftMat->LocalToMaster(&vert[3*i], &pt[0]); - if (pt[0]xmax1) xmax1=pt[0]; - if (pt[1]ymax1) ymax1=pt[1]; - if (pt[2]zmax1) zmax1=pt[2]; + if (((TGeoBBox *)fLeft)->IsNullBox()) + fLeft->ComputeBBox(); + ((TGeoBBox *)fLeft)->SetBoxPoints(&vert[0]); + for (i = 0; i < 8; i++) { + fLeftMat->LocalToMaster(&vert[3 * i], &pt[0]); + if (pt[0] < xmin1) + xmin1 = pt[0]; + if (pt[0] > xmax1) + xmax1 = pt[0]; + if (pt[1] < ymin1) + ymin1 = pt[1]; + if (pt[1] > ymax1) + ymax1 = pt[1]; + if (pt[2] < zmin1) + zmin1 = pt[2]; + if (pt[2] > zmax1) + zmax1 = pt[2]; } } if (!hs2) { - if (((TGeoBBox*)fRight)->IsNullBox()) fRight->ComputeBBox(); - ((TGeoBBox*)fRight)->SetBoxPoints(&vert[24]); - for (i=8; i<16; i++) { - fRightMat->LocalToMaster(&vert[3*i], &pt[0]); - if (pt[0]xmax2) xmax2=pt[0]; - if (pt[1]ymax2) ymax2=pt[1]; - if (pt[2]zmax2) zmax2=pt[2]; + if (((TGeoBBox *)fRight)->IsNullBox()) + fRight->ComputeBBox(); + ((TGeoBBox *)fRight)->SetBoxPoints(&vert[24]); + for (i = 8; i < 16; i++) { + fRightMat->LocalToMaster(&vert[3 * i], &pt[0]); + if (pt[0] < xmin2) + xmin2 = pt[0]; + if (pt[0] > xmax2) + xmax2 = pt[0]; + if (pt[1] < ymin2) + ymin2 = pt[1]; + if (pt[1] > ymax2) + ymax2 = pt[1]; + if (pt[2] < zmin2) + zmin2 = pt[2]; + if (pt[2] > zmax2) + zmax2 = pt[2]; } } if (hs1) { - dx = 0.5*(xmax2-xmin2); - origin[0] = 0.5*(xmax2+xmin2); - dy = 0.5*(ymax2-ymin2); - origin[1] = 0.5*(ymax2+ymin2); - dz = 0.5*(zmax2-zmin2); - origin[2] = 0.5*(zmax2+zmin2); + dx = 0.5 * (xmax2 - xmin2); + origin[0] = 0.5 * (xmax2 + xmin2); + dy = 0.5 * (ymax2 - ymin2); + origin[1] = 0.5 * (ymax2 + ymin2); + dz = 0.5 * (zmax2 - zmin2); + origin[2] = 0.5 * (zmax2 + zmin2); return; } if (hs2) { - dx = 0.5*(xmax1-xmin1); - origin[0] = 0.5*(xmax1+xmin1); - dy = 0.5*(ymax1-ymin1); - origin[1] = 0.5*(ymax1+ymin1); - dz = 0.5*(zmax1-zmin1); - origin[2] = 0.5*(zmax1+zmin1); + dx = 0.5 * (xmax1 - xmin1); + origin[0] = 0.5 * (xmax1 + xmin1); + dy = 0.5 * (ymax1 - ymin1); + origin[1] = 0.5 * (ymax1 + ymin1); + dz = 0.5 * (zmax1 - zmin1); + origin[2] = 0.5 * (zmax1 + zmin1); return; } Double_t sort[4]; @@ -1277,40 +1356,40 @@ void TGeoIntersection::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Dou sort[2] = xmin2; sort[3] = xmax2; TMath::Sort(4, &sort[0], &isort[0], kFALSE); - if (isort[1]%2) { + if (isort[1] % 2) { Warning("ComputeBBox", "shapes %s and %s do not intersect", fLeft->GetName(), fRight->GetName()); dx = dy = dz = 0; - memset(origin, 0, 3*sizeof(Double_t)); + memset(origin, 0, 3 * sizeof(Double_t)); return; } - dx = 0.5*(sort[isort[2]]-sort[isort[1]]); - origin[0] = 0.5*(sort[isort[1]]+sort[isort[2]]); + dx = 0.5 * (sort[isort[2]] - sort[isort[1]]); + origin[0] = 0.5 * (sort[isort[1]] + sort[isort[2]]); sort[0] = ymin1; sort[1] = ymax1; sort[2] = ymin2; sort[3] = ymax2; TMath::Sort(4, &sort[0], &isort[0], kFALSE); - if (isort[1]%2) { + if (isort[1] % 2) { Warning("ComputeBBox", "shapes %s and %s do not intersect", fLeft->GetName(), fRight->GetName()); dx = dy = dz = 0; - memset(origin, 0, 3*sizeof(Double_t)); + memset(origin, 0, 3 * sizeof(Double_t)); return; } - dy = 0.5*(sort[isort[2]]-sort[isort[1]]); - origin[1] = 0.5*(sort[isort[1]]+sort[isort[2]]); + dy = 0.5 * (sort[isort[2]] - sort[isort[1]]); + origin[1] = 0.5 * (sort[isort[1]] + sort[isort[2]]); sort[0] = zmin1; sort[1] = zmax1; sort[2] = zmin2; sort[3] = zmax2; TMath::Sort(4, &sort[0], &isort[0], kFALSE); - if (isort[1]%2) { + if (isort[1] % 2) { Warning("ComputeBBox", "shapes %s and %s do not intersect", fLeft->GetName(), fRight->GetName()); dx = dy = dz = 0; - memset(origin, 0, 3*sizeof(Double_t)); + memset(origin, 0, 3 * sizeof(Double_t)); return; } - dz = 0.5*(sort[isort[2]]-sort[isort[1]]); - origin[2] = 0.5*(sort[isort[1]]+sort[isort[2]]); + dz = 0.5 * (sort[isort[2]] - sort[isort[1]]); + origin[2] = 0.5 * (sort[isort[1]] + sort[isort[2]]); } //////////////////////////////////////////////////////////////////////////////// @@ -1318,49 +1397,50 @@ void TGeoIntersection::ComputeBBox(Double_t &dx, Double_t &dy, Double_t &dz, Dou void TGeoIntersection::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); Double_t local[3], ldir[3], lnorm[3]; norm[0] = norm[1] = 0.; norm[2] = 1.; if (td.fSelected == 1) { fLeftMat->MasterToLocal(point, local); fLeftMat->MasterToLocalVect(dir, ldir); - fLeft->ComputeNormal(local,ldir,lnorm); + fLeft->ComputeNormal(local, ldir, lnorm); fLeftMat->LocalToMasterVect(lnorm, norm); return; } if (td.fSelected == 2) { fRightMat->MasterToLocal(point, local); fRightMat->MasterToLocalVect(dir, ldir); - fRight->ComputeNormal(local,ldir,lnorm); + fRight->ComputeNormal(local, ldir, lnorm); fRightMat->LocalToMasterVect(lnorm, norm); return; } - fLeftMat->MasterToLocal(point,local); + fLeftMat->MasterToLocal(point, local); if (!fLeft->Contains(local)) { - fLeftMat->MasterToLocalVect(dir,ldir); - fLeft->ComputeNormal(local,ldir,lnorm); - fLeftMat->LocalToMasterVect(lnorm,norm); + fLeftMat->MasterToLocalVect(dir, ldir); + fLeft->ComputeNormal(local, ldir, lnorm); + fLeftMat->LocalToMasterVect(lnorm, norm); return; } - fRightMat->MasterToLocal(point,local); + fRightMat->MasterToLocal(point, local); if (!fRight->Contains(local)) { - fRightMat->MasterToLocalVect(dir,ldir); - fRight->ComputeNormal(local,ldir,lnorm); - fRightMat->LocalToMasterVect(lnorm,norm); + fRightMat->MasterToLocalVect(dir, ldir); + fRight->ComputeNormal(local, ldir, lnorm); + fRightMat->LocalToMasterVect(lnorm, norm); return; } // point is inside intersection. - local[0] = point[0] + 1E-5*dir[0]; - local[1] = point[1] + 1E-5*dir[1]; - local[2] = point[2] + 1E-5*dir[2]; + local[0] = point[0] + 1E-5 * dir[0]; + local[1] = point[1] + 1E-5 * dir[1]; + local[2] = point[2] + 1E-5 * dir[2]; if (Contains(local)) { - local[0] = point[0] - 1E-5*dir[0]; - local[1] = point[1] - 1E-5*dir[1]; - local[2] = point[2] - 1E-5*dir[2]; - if (Contains(local)) return; + local[0] = point[0] - 1E-5 * dir[0]; + local[1] = point[1] - 1E-5 * dir[1]; + local[2] = point[2] - 1E-5 * dir[2]; + if (Contains(local)) + return; } - ComputeNormal(local,dir,norm); + ComputeNormal(local, dir, norm); } //////////////////////////////////////////////////////////////////////////////// @@ -1371,7 +1451,8 @@ Bool_t TGeoIntersection::Contains(const Double_t *point) const Double_t local[3]; fLeftMat->MasterToLocal(point, &local[0]); Bool_t inside = fLeft->Contains(&local[0]); - if (!inside) return kFALSE; + if (!inside) + return kFALSE; fRightMat->MasterToLocal(point, &local[0]); inside = fRight->Contains(&local[0]); return inside; @@ -1388,25 +1469,27 @@ Int_t TGeoIntersection::DistanceToPrimitive(Int_t /*px*/, Int_t /*py*/) //////////////////////////////////////////////////////////////////////////////// /// Compute distance from a given point inside to the shape boundary. -Double_t TGeoIntersection::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoIntersection::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kTRUE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoBoolNode *node = (TGeoBoolNode*)this; + TGeoBoolNode *node = (TGeoBoolNode *)this; Double_t local[3], ldir[3], rdir[3]; - Double_t d1, d2, snxt=0.; + Double_t d1, d2, snxt = 0.; fLeftMat->MasterToLocal(point, &local[0]); fLeftMat->MasterToLocalVect(dir, &ldir[0]); fRightMat->MasterToLocalVect(dir, &rdir[0]); d1 = fLeft->DistFromInside(&local[0], &ldir[0], iact, step, safe); fRightMat->MasterToLocal(point, &local[0]); d2 = fRight->DistFromInside(&local[0], &rdir[0], iact, step, safe); - if (d1SetSelected(1); } else { @@ -1419,19 +1502,21 @@ Double_t TGeoIntersection::DistFromInside(const Double_t *point, const Double_t //////////////////////////////////////////////////////////////////////////////// /// Compute distance from a given point outside to the shape. -Double_t TGeoIntersection::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoIntersection::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { Double_t tol = TGeoShape::Tolerance(); - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance - *safe = Safety(point,kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + *safe = Safety(point, kFALSE); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoBoolNode *node = (TGeoBoolNode*)this; + TGeoBoolNode *node = (TGeoBoolNode *)this; Double_t lpt[3], rpt[3], master[3], ldir[3], rdir[3]; - memcpy(master, point, 3*sizeof(Double_t)); + memcpy(master, point, 3 * sizeof(Double_t)); Int_t i; Double_t d1 = 0.; Double_t d2 = 0.; @@ -1446,51 +1531,62 @@ Double_t TGeoIntersection::DistFromOutside(const Double_t *point, const Double_t if (inleft && inright) { // It is vey likely to have a numerical issue and the point should // be logically outside one of the shapes - d1 = fLeft->DistFromInside(lpt,ldir,3); - d2 = fRight->DistFromInside(rpt,rdir,3); - if (d1<1.E-3) inleft = kFALSE; - if (d2<1.E-3) inright = kFALSE; - if (inleft && inright) return snext; + d1 = fLeft->DistFromInside(lpt, ldir, 3); + d2 = fRight->DistFromInside(rpt, rdir, 3); + if (d1 < 1.E-3) + inleft = kFALSE; + if (d2 < 1.E-3) + inright = kFALSE; + if (inleft && inright) + return snext; } while (1) { d1 = d2 = 0; - if (!inleft) { - d1 = fLeft->DistFromOutside(lpt,ldir,3); - d1 = TMath::Max(d1,tol); - if (d1>1E20) return TGeoShape::Big(); + if (!inleft) { + d1 = fLeft->DistFromOutside(lpt, ldir, 3); + d1 = TMath::Max(d1, tol); + if (d1 > 1E20) + return TGeoShape::Big(); } if (!inright) { - d2 = fRight->DistFromOutside(rpt,rdir,3); - d2 = TMath::Max(d2,tol); - if (d2>1E20) return TGeoShape::Big(); + d2 = fRight->DistFromOutside(rpt, rdir, 3); + d2 = TMath::Max(d2, tol); + if (d2 > 1E20) + return TGeoShape::Big(); } - if (d1>d2) { + if (d1 > d2) { // propagate to left shape snext += d1; node->SetSelected(1); inleft = kTRUE; - for (i=0; i<3; i++) master[i] += d1*dir[i]; - fRightMat->MasterToLocal(master,rpt); + for (i = 0; i < 3; i++) + master[i] += d1 * dir[i]; + fRightMat->MasterToLocal(master, rpt); // Push rpt to avoid a bad boundary condition - for (i=0; i<3; i++) rpt[i] += tol*rdir[i]; + for (i = 0; i < 3; i++) + rpt[i] += tol * rdir[i]; // check if propagated point is inside right shape inright = fRight->Contains(rpt); - if (inright) return snext; + if (inright) + return snext; // here inleft=true, inright=false } else { // propagate to right shape snext += d2; node->SetSelected(2); inright = kTRUE; - for (i=0; i<3; i++) master[i] += d2*dir[i]; - fLeftMat->MasterToLocal(master,lpt); + for (i = 0; i < 3; i++) + master[i] += d2 * dir[i]; + fLeftMat->MasterToLocal(master, lpt); // Push lpt to avoid a bad boundary condition - for (i=0; i<3; i++) lpt[i] += tol*ldir[i]; + for (i = 0; i < 3; i++) + lpt[i] += tol * ldir[i]; // check if propagated point is inside left shape inleft = fLeft->Contains(lpt); - if (inleft) return snext; + if (inleft) + return snext; // here inleft=false, inright=true } } @@ -1502,35 +1598,40 @@ Double_t TGeoIntersection::DistFromOutside(const Double_t *point, const Double_t Int_t TGeoIntersection::GetNpoints() { - Int_t itot=0; + Int_t itot = 0; Double_t point[3]; Double_t tolerance = TGeoShape::Tolerance(); - if (fNpoints) return fNpoints; + if (fNpoints) + return fNpoints; Int_t nleft = fLeft->GetNmeshVertices(); Int_t nright = fRight->GetNmeshVertices(); - Double_t *points = new Double_t[3*(nleft+nright)]; - Double_t *points1 = new Double_t[3*nleft]; + Double_t *points = new Double_t[3 * (nleft + nright)]; + Double_t *points1 = new Double_t[3 * nleft]; fLeft->SetPoints(points1); - for (Int_t i=0; iLocalToMaster(&points1[3*i], &points[3*itot]); - fRightMat->MasterToLocal(&points[3*itot], point); - if (fRight->Contains(point)) itot++; - } - Double_t *points2 = new Double_t[3*nright]; + for (Int_t i = 0; i < nleft; i++) { + if (TMath::Abs(points1[3 * i]) < tolerance && TMath::Abs(points1[3 * i + 1]) < tolerance) + continue; + fLeftMat->LocalToMaster(&points1[3 * i], &points[3 * itot]); + fRightMat->MasterToLocal(&points[3 * itot], point); + if (fRight->Contains(point)) + itot++; + } + Double_t *points2 = new Double_t[3 * nright]; fRight->SetPoints(points2); - for (Int_t i=0; iLocalToMaster(&points2[3*i], &points[3*itot]); - fLeftMat->MasterToLocal(&points[3*itot], point); - if (fLeft->Contains(point)) itot++; + for (Int_t i = 0; i < nright; i++) { + if (TMath::Abs(points2[3 * i]) < tolerance && TMath::Abs(points2[3 * i + 1]) < tolerance) + continue; + fRightMat->LocalToMaster(&points2[3 * i], &points[3 * itot]); + fLeftMat->MasterToLocal(&points[3 * itot], point); + if (fLeft->Contains(point)) + itot++; } AssignPoints(itot, points); - delete [] points1; - delete [] points2; - delete [] points; + delete[] points1; + delete[] points2; + delete[] points; return fNpoints; } @@ -1540,18 +1641,22 @@ Int_t TGeoIntersection::GetNpoints() Double_t TGeoIntersection::Safety(const Double_t *point, Bool_t in) const { Double_t local1[3], local2[3]; - fLeftMat->MasterToLocal(point,local1); + fLeftMat->MasterToLocal(point, local1); Bool_t in1 = fLeft->Contains(local1); - fRightMat->MasterToLocal(point,local2); + fRightMat->MasterToLocal(point, local2); Bool_t in2 = fRight->Contains(local2); Bool_t intrue = in1 & in2; - if (in^intrue) return 0.0; + if (in ^ intrue) + return 0.0; Double_t saf1 = fLeft->Safety(local1, in1); Double_t saf2 = fRight->Safety(local2, in2); - if (in1 && in2) return TMath::Min(saf1, saf2); - if (in1) return saf2; - if (in2) return saf1; - return TMath::Max(saf1,saf2); + if (in1 && in2) + return TMath::Min(saf1, saf2); + if (in1) + return saf2; + if (in2) + return saf1; + return TMath::Max(saf1, saf2); } //////////////////////////////////////////////////////////////////////////////// @@ -1559,14 +1664,18 @@ Double_t TGeoIntersection::Safety(const Double_t *point, Bool_t in) const void TGeoIntersection::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - TGeoBoolNode::SavePrimitive(out,option); + TGeoBoolNode::SavePrimitive(out, option); out << " pBoolNode = new TGeoIntersection("; out << fLeft->GetPointerName() << ","; out << fRight->GetPointerName() << ","; - if (!fLeftMat->IsIdentity()) out << fLeftMat->GetPointerName() << ","; - else out << "0,"; - if (!fRightMat->IsIdentity()) out << fRightMat->GetPointerName() << ");" << std::endl; - else out << "0);" << std::endl; + if (!fLeftMat->IsIdentity()) + out << fLeftMat->GetPointerName() << ","; + else + out << "0,"; + if (!fRightMat->IsIdentity()) + out << fRightMat->GetPointerName() << ");" << std::endl; + else + out << "0);" << std::endl; } //////////////////////////////////////////////////////////////////////////////// diff --git a/geom/geom/src/TGeoBranchArray.cxx b/geom/geom/src/TGeoBranchArray.cxx index 77d2b8c5857df..dc067c9031a0c 100644 --- a/geom/geom/src/TGeoBranchArray.cxx +++ b/geom/geom/src/TGeoBranchArray.cxx @@ -38,13 +38,9 @@ ClassImp(TGeoBranchArray); //////////////////////////////////////////////////////////////////////////////// /// Constructor. Allocates the array with a size given by level. -TGeoBranchArray::TGeoBranchArray(Int_t maxlevel) - :fLevel(-1), - fMaxLevel(maxlevel), - fMatrix(), - fArray(&fRealArray[0]) +TGeoBranchArray::TGeoBranchArray(Int_t maxlevel) : fLevel(-1), fMaxLevel(maxlevel), fMatrix(), fArray(&fRealArray[0]) { - memset(fRealArray, 0, fMaxLevel*sizeof(TGeoNode*)); + memset(fRealArray, 0, fMaxLevel * sizeof(TGeoNode *)); } //////////////////////////////////////////////////////////////////////////////// @@ -52,14 +48,15 @@ TGeoBranchArray::TGeoBranchArray(Int_t maxlevel) /// released using ReleaseInstance. If addr is non-zero, the user promised that /// addr contains at least that many bytes: size_t needed = SizeOf(maxlevel); -TGeoBranchArray * TGeoBranchArray::MakeInstance(size_t maxlevel) +TGeoBranchArray *TGeoBranchArray::MakeInstance(size_t maxlevel) { - TGeoBranchArray* ba = 0; + TGeoBranchArray *ba = 0; size_t needed = SizeOf(maxlevel); - char *ptr = new char[ needed ]; - if (!ptr) return 0; + char *ptr = new char[needed]; + if (!ptr) + return 0; new (ptr) TGeoBranchArray(maxlevel); - ba = reinterpret_cast(ptr); + ba = reinterpret_cast(ptr); ba->SetBit(kBASelfAlloc, kTRUE); return ba; } @@ -69,50 +66,51 @@ TGeoBranchArray * TGeoBranchArray::MakeInstance(size_t maxlevel) /// released using ReleaseInstance. If addr is non-zero, the user promised that /// addr contains at least that many bytes: size_t needed = SizeOf(maxlevel); -TGeoBranchArray * TGeoBranchArray::MakeInstanceAt(size_t maxlevel, void *addr) +TGeoBranchArray *TGeoBranchArray::MakeInstanceAt(size_t maxlevel, void *addr) { - TGeoBranchArray* ba = 0; + TGeoBranchArray *ba = 0; new (addr) TGeoBranchArray(maxlevel); - ba = reinterpret_cast(addr); + ba = reinterpret_cast(addr); ba->SetBit(kBASelfAlloc, kFALSE); return ba; } - //////////////////////////////////////////////////////////////////////////////// /// Make a copy of a branch array at the location (if indicated) -TGeoBranchArray * TGeoBranchArray::MakeCopy(const TGeoBranchArray &other) +TGeoBranchArray *TGeoBranchArray::MakeCopy(const TGeoBranchArray &other) { TGeoBranchArray *copy = 0; size_t needed = SizeOf(other.fMaxLevel); - char *ptr = new char[ needed ]; - if (!ptr) return 0; + char *ptr = new char[needed]; + if (!ptr) + return 0; new (ptr) TGeoBranchArray(other.fMaxLevel); - copy = reinterpret_cast(ptr); + copy = reinterpret_cast(ptr); copy->SetBit(kBASelfAlloc, kTRUE); copy->fLevel = other.fLevel; copy->fMatrix = other.fMatrix; - if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*)); + if (other.fLevel + 1) + memcpy(copy->fArray, other.fArray, (other.fLevel + 1) * sizeof(TGeoNode *)); return copy; } //////////////////////////////////////////////////////////////////////////////// /// Make a copy of a branch array at the location (if indicated) -TGeoBranchArray * TGeoBranchArray::MakeCopyAt(const TGeoBranchArray &other, void *addr) +TGeoBranchArray *TGeoBranchArray::MakeCopyAt(const TGeoBranchArray &other, void *addr) { TGeoBranchArray *copy = 0; new (addr) TGeoBranchArray(other.fMaxLevel); - copy = reinterpret_cast(addr); + copy = reinterpret_cast(addr); copy->SetBit(kBASelfAlloc, kFALSE); copy->fLevel = other.fLevel; copy->fMatrix = other.fMatrix; - if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*)); + if (other.fLevel + 1) + memcpy(copy->fArray, other.fArray, (other.fLevel + 1) * sizeof(TGeoNode *)); return copy; } - //////////////////////////////////////////////////////////////////////////////// /// Raw memcpy of the branch array content to an existing destination. @@ -128,7 +126,8 @@ void TGeoBranchArray::CopyTo(TGeoBranchArray *dest) void TGeoBranchArray::ReleaseInstance(TGeoBranchArray *obj) { obj->~TGeoBranchArray(); - if (obj->TestBit(kBASelfAlloc)) delete [] (char*)obj; + if (obj->TestBit(kBASelfAlloc)) + delete[](char *) obj; } //////////////////////////////////////////////////////////////////////////////// @@ -139,14 +138,14 @@ void TGeoBranchArray::ReleaseInstance(TGeoBranchArray *obj) void TGeoBranchArray::UpdateArray(size_t nobj) { size_t needed = SizeOf(); -// char *where = &fArray; -// for (size_t i=0; i(where); -// *array = ((void**)where)+1; -// } - char *where = reinterpret_cast(this); - for (size_t i=0; i(where); + // char *where = &fArray; + // for (size_t i=0; i(where); + // *array = ((void**)where)+1; + // } + char *where = reinterpret_cast(this); + for (size_t i = 0; i < nobj; ++i, where += needed) { + TGeoBranchArray *obj = reinterpret_cast(where); obj->fArray = &(obj->fRealArray[0]); } } @@ -154,28 +153,27 @@ void TGeoBranchArray::UpdateArray(size_t nobj) //////////////////////////////////////////////////////////////////////////////// /// Copy constructor. Not callable anymore. Use TGeoBranchArray::MakeCopy instead -TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other) - :TObject(other), - fLevel(other.fLevel), - fMaxLevel(other.fMaxLevel), - fMatrix(other.fMatrix), - fArray(NULL) +TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray &other) + : TObject(other), fLevel(other.fLevel), fMaxLevel(other.fMaxLevel), fMatrix(other.fMatrix), fArray(NULL) { if (fMaxLevel) { - fArray = new TGeoNode*[fMaxLevel]; - if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*)); + fArray = new TGeoNode *[fMaxLevel]; + if (fLevel + 1) + memcpy(fArray, other.fArray, (fLevel + 1) * sizeof(TGeoNode *)); } } //////////////////////////////////////////////////////////////////////////////// /// Assignment. Not valid anymore. Use TGeoBranchArray::MakeCopy instead -TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other) +TGeoBranchArray &TGeoBranchArray::operator=(const TGeoBranchArray &other) { - if (&other == this) return *this; + if (&other == this) + return *this; fLevel = other.fLevel; fMatrix.CopyFrom(&other.fMatrix); - if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*)); + if (fLevel + 1) + memcpy(fArray, other.fArray, (fLevel + 1) * sizeof(TGeoNode *)); return *this; } @@ -184,83 +182,89 @@ TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other) void TGeoBranchArray::AddLevel(Int_t dindex) { - if (fLevel<0) { + if (fLevel < 0) { Error("AddLevel", "You must initialize from navigator or copy from another branch array first."); return; } - if (fLevel>fMaxLevel) { + if (fLevel > fMaxLevel) { Fatal("AddLevel", "Max level = %d reached\n", fMaxLevel); return; } fLevel++; -/* - if (fLevel+1>fMaxLevel) { - TGeoNode **array = new TGeoNode*[fLevel+1]; - memcpy(array, fArray, fLevel*sizeof(TGeoNode*)); - delete [] fArray; - fArray = array; - } -*/ - fArray[fLevel] = fArray[fLevel-1]->GetVolume()->GetNode(dindex); + /* + if (fLevel+1>fMaxLevel) { + TGeoNode **array = new TGeoNode*[fLevel+1]; + memcpy(array, fArray, fLevel*sizeof(TGeoNode*)); + delete [] fArray; + fArray = array; + } + */ + fArray[fLevel] = fArray[fLevel - 1]->GetVolume()->GetNode(dindex); } //////////////////////////////////////////////////////////////////////////////// /// Is equal operator. -Bool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator==(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value==0) return kTRUE; + if (value == 0) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// Not equal operator. -Bool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator!=(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value!=0) return kTRUE; + if (value != 0) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// Is equal operator. -Bool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator>(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value>0) return kTRUE; + if (value > 0) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// Is equal operator. -Bool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator<(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value<0) return kTRUE; + if (value < 0) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// Is equal operator. -Bool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator>=(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value>=0) return kTRUE; + if (value >= 0) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// Is equal operator. -Bool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const +Bool_t TGeoBranchArray::operator<=(const TGeoBranchArray &other) const { Int_t value = Compare(&other); - if (value<=0) return kTRUE; + if (value <= 0) + return kTRUE; return kFALSE; } @@ -272,16 +276,19 @@ Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array { Long64_t nabove, nbelow, middle; const TGeoBranchArray *pind; - nabove = n+1; + nabove = n + 1; nbelow = 0; - while(nabove-nbelow > 1) { - middle = (nabove+nbelow)/2; - pind = array[middle-1]; - if (*value == *pind) return middle-1; - if (*value < *pind) nabove = middle; - else nbelow = middle; + while (nabove - nbelow > 1) { + middle = (nabove + nbelow) / 2; + pind = array[middle - 1]; + if (*value == *pind) + return middle - 1; + if (*value < *pind) + nabove = middle; + else + nbelow = middle; } - return nbelow-1; + return nbelow - 1; } //////////////////////////////////////////////////////////////////////////////// @@ -292,26 +299,28 @@ Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array Int_t TGeoBranchArray::Compare(const TObject *obj) const { Int_t i; - TGeoBranchArray *other = (TGeoBranchArray*)obj; + TGeoBranchArray *other = (TGeoBranchArray *)obj; Int_t otherLevel = other->GetLevel(); Int_t maxLevel = TMath::Min(fLevel, otherLevel); TGeoNode **otherArray = other->GetArray(); - for (i=0; ifMaxLevel) { - Fatal("Init", "Requested level %d exceeds maximum level %d", level+1, fMaxLevel); + if (level > fMaxLevel) { + Fatal("Init", "Requested level %d exceeds maximum level %d", level + 1, fMaxLevel); return; } fLevel = level; - memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*)); + memcpy(fArray, branch, (fLevel + 1) * sizeof(TGeoNode *)); } //////////////////////////////////////////////////////////////////////////////// @@ -334,16 +343,17 @@ void TGeoBranchArray::Init(TGeoNode **branch, TGeoMatrix *global, Int_t level) void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav) { TGeoNodeCache *cache = nav->GetCache(); - const TGeoNode **branch = (const TGeoNode**)cache->GetBranch(); + const TGeoNode **branch = (const TGeoNode **)cache->GetBranch(); Int_t level = cache->GetLevel(); fMatrix.CopyFrom(cache->GetCurrentMatrix()); - if (level>fMaxLevel) { - Fatal("InitFromNavigator", "Requested level %d exceeds maximum level %d", level+1, fMaxLevel); + if (level > fMaxLevel) { + Fatal("InitFromNavigator", "Requested level %d exceeds maximum level %d", level + 1, fMaxLevel); return; } fLevel = level; - memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*)); - if (nav->IsOutside()) fLevel = -1; + memcpy(fArray, branch, (fLevel + 1) * sizeof(TGeoNode *)); + if (nav->IsOutside()) + fLevel = -1; } //////////////////////////////////////////////////////////////////////////////// @@ -352,8 +362,9 @@ void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav) void TGeoBranchArray::GetPath(TString &path) const { path = ""; - if (!fArray || !fArray[0]) return; - for (Int_t i=0; iGetName(); } @@ -374,7 +385,8 @@ void TGeoBranchArray::Print(Option_t *) const void TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down) { - for (Int_t i=0; iSetOutside(kTRUE); return;} + if (fLevel < 0) { + nav->SetOutside(kTRUE); + return; + } Int_t matchlev = 0; Int_t navlev = nav->GetLevel(); Int_t i; Int_t maxlev = TMath::Min(fLevel, navlev); - for (i=1; iGetMother(navlev-i)) break; - matchlev++; + for (i = 1; i < maxlev + 1; ++i) { + if (fArray[i] != nav->GetMother(navlev - i)) + break; + matchlev++; } // Go to matching level - for (i=0; iCdUp(); - for (i=matchlev+1; iCdDown(fArray[i]); + for (i = 0; i < navlev - matchlev; i++) + nav->CdUp(); + for (i = matchlev + 1; i < fLevel + 1; i++) + nav->CdDown(fArray[i]); } diff --git a/geom/geom/src/TGeoBuilder.cxx b/geom/geom/src/TGeoBuilder.cxx index 863f4fd941f86..e5ea93e103a40 100644 --- a/geom/geom/src/TGeoBuilder.cxx +++ b/geom/geom/src/TGeoBuilder.cxx @@ -54,8 +54,7 @@ TGeoBuilder *TGeoBuilder::fgInstance = NULL; //////////////////////////////////////////////////////////////////////////////// /// Default constructor. -TGeoBuilder::TGeoBuilder() - :fGeometry(nullptr) +TGeoBuilder::TGeoBuilder() : fGeometry(nullptr) { fgInstance = this; } @@ -77,7 +76,8 @@ TGeoBuilder *TGeoBuilder::Instance(TGeoManager *geom) printf("ERROR: Cannot create geometry builder with NULL geometry\n"); return NULL; } - if (!fgInstance) fgInstance = new TGeoBuilder(); + if (!fgInstance) + fgInstance = new TGeoBuilder(); fgInstance->SetGeometry(geom); return fgInstance; } @@ -87,7 +87,8 @@ TGeoBuilder *TGeoBuilder::Instance(TGeoManager *geom) Int_t TGeoBuilder::AddMaterial(TGeoMaterial *material) { - if (!material) return -1; + if (!material) + return -1; TList *materials = fGeometry->GetListOfMaterials(); Int_t index = materials->GetSize(); material->SetIndex(index); @@ -101,10 +102,11 @@ Int_t TGeoBuilder::AddMaterial(TGeoMaterial *material) Int_t TGeoBuilder::AddTransformation(TGeoMatrix *matrix) { Int_t index = -1; - if (!matrix) return -1; + if (!matrix) + return -1; TObjArray *matrices = fGeometry->GetListOfMatrices(); index = matrices->GetEntriesFast(); - matrices->AddAtAndExpand(matrix,index); + matrices->AddAtAndExpand(matrix, index); return index; } @@ -114,11 +116,13 @@ Int_t TGeoBuilder::AddTransformation(TGeoMatrix *matrix) Int_t TGeoBuilder::AddShape(TGeoShape *shape) { Int_t index = -1; - if (!shape) return -1; + if (!shape) + return -1; TObjArray *shapes = fGeometry->GetListOfShapes(); - if (shape->IsRunTimeShape()) shapes = fGeometry->GetListOfGShapes(); + if (shape->IsRunTimeShape()) + shapes = fGeometry->GetListOfGShapes(); index = shapes->GetEntriesFast(); - shapes->AddAtAndExpand(shape,index); + shapes->AddAtAndExpand(shape, index); return index; } @@ -128,7 +132,8 @@ Int_t TGeoBuilder::AddShape(TGeoShape *shape) void TGeoBuilder::RegisterMatrix(TGeoMatrix *matrix) { - if (matrix->IsRegistered()) return; + if (matrix->IsRegistered()) + return; TObjArray *matrices = fGeometry->GetListOfMatrices(); Int_t nmat = matrices->GetEntriesFast(); matrices->AddAtAndExpand(matrix, nmat); @@ -137,8 +142,7 @@ void TGeoBuilder::RegisterMatrix(TGeoMatrix *matrix) //////////////////////////////////////////////////////////////////////////////// /// Make an TGeoArb8 volume. -TGeoVolume *TGeoBuilder::MakeArb8(const char *name, TGeoMedium *medium, - Double_t dz, Double_t *vertices) +TGeoVolume *TGeoBuilder::MakeArb8(const char *name, TGeoMedium *medium, Double_t dz, Double_t *vertices) { TGeoArb8 *arb = new TGeoArb8(name, dz, vertices); TGeoVolume *vol = new TGeoVolume(name, arb, medium); @@ -148,8 +152,7 @@ TGeoVolume *TGeoBuilder::MakeArb8(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a box shape with given medium. -TGeoVolume *TGeoBuilder::MakeBox(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz) +TGeoVolume *TGeoBuilder::MakeBox(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz) { TGeoBBox *box = new TGeoBBox(name, dx, dy, dz); TGeoVolume *vol = 0; @@ -165,15 +168,14 @@ TGeoVolume *TGeoBuilder::MakeBox(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a parallelepiped shape with given medium. -TGeoVolume *TGeoBuilder::MakePara(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz, - Double_t alpha, Double_t theta, Double_t phi) +TGeoVolume *TGeoBuilder::MakePara(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz, + Double_t alpha, Double_t theta, Double_t phi) { - if (TMath::Abs(alpha) making box instead", name); + if (TMath::Abs(alpha) < TGeoShape::Tolerance() && TMath::Abs(theta) < TGeoShape::Tolerance()) { + Warning("MakePara", "parallelepiped %s having alpha=0, theta=0 -> making box instead", name); return MakeBox(name, medium, dx, dy, dz); } - TGeoPara *para=0; + TGeoPara *para = 0; para = new TGeoPara(name, dx, dy, dz, alpha, theta, phi); TGeoVolume *vol = 0; if (para->IsRunTimeShape()) { @@ -188,9 +190,8 @@ TGeoVolume *TGeoBuilder::MakePara(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a sphere shape with given medium -TGeoVolume *TGeoBuilder::MakeSphere(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t themin, Double_t themax, - Double_t phimin, Double_t phimax) +TGeoVolume *TGeoBuilder::MakeSphere(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t themin, + Double_t themax, Double_t phimin, Double_t phimax) { TGeoSphere *sph = new TGeoSphere(name, rmin, rmax, themin, themax, phimin, phimax); TGeoVolume *vol = new TGeoVolume(name, sph, medium); @@ -200,10 +201,10 @@ TGeoVolume *TGeoBuilder::MakeSphere(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a torus shape with given medium. -TGeoVolume *TGeoBuilder::MakeTorus(const char *name, TGeoMedium *medium, Double_t r, - Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi) +TGeoVolume *TGeoBuilder::MakeTorus(const char *name, TGeoMedium *medium, Double_t r, Double_t rmin, Double_t rmax, + Double_t phi1, Double_t dphi) { - TGeoTorus *tor = new TGeoTorus(name,r,rmin,rmax,phi1,dphi); + TGeoTorus *tor = new TGeoTorus(name, r, rmin, rmax, phi1, dphi); TGeoVolume *vol = new TGeoVolume(name, tor, medium); return vol; } @@ -211,11 +212,10 @@ TGeoVolume *TGeoBuilder::MakeTorus(const char *name, TGeoMedium *medium, Double_ //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium. -TGeoVolume *TGeoBuilder::MakeTube(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz) +TGeoVolume *TGeoBuilder::MakeTube(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz) { - if (rmin>rmax) { - Error("MakeTube", "tube %s, Rmin=%g greater than Rmax=%g", name,rmin,rmax); + if (rmin > rmax) { + Error("MakeTube", "tube %s, Rmin=%g greater than Rmax=%g", name, rmin, rmax); } TGeoTube *tube = new TGeoTube(name, rmin, rmax, dz); TGeoVolume *vol = 0; @@ -231,9 +231,8 @@ TGeoVolume *TGeoBuilder::MakeTube(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube segment shape with given medium. -TGeoVolume *TGeoBuilder::MakeTubs(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, - Double_t phi1, Double_t phi2) +TGeoVolume *TGeoBuilder::MakeTubs(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, + Double_t phi1, Double_t phi2) { TGeoTubeSeg *tubs = new TGeoTubeSeg(name, rmin, rmax, dz, phi1, phi2); TGeoVolume *vol = 0; @@ -249,8 +248,7 @@ TGeoVolume *TGeoBuilder::MakeTubs(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoBuilder::MakeEltu(const char *name, TGeoMedium *medium, - Double_t a, Double_t b, Double_t dz) +TGeoVolume *TGeoBuilder::MakeEltu(const char *name, TGeoMedium *medium, Double_t a, Double_t b, Double_t dz) { TGeoEltu *eltu = new TGeoEltu(name, a, b, dz); TGeoVolume *vol = 0; @@ -266,10 +264,10 @@ TGeoVolume *TGeoBuilder::MakeEltu(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoBuilder::MakeHype(const char *name, TGeoMedium *medium, - Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) +TGeoVolume *TGeoBuilder::MakeHype(const char *name, TGeoMedium *medium, Double_t rin, Double_t stin, Double_t rout, + Double_t stout, Double_t dz) { - TGeoHype * hype = new TGeoHype(name, rin,stin,rout,stout,dz); + TGeoHype *hype = new TGeoHype(name, rin, stin, rout, stout, dz); TGeoVolume *vol = 0; if (hype->IsRunTimeShape()) { vol = fGeometry->MakeVolumeMulti(name, medium); @@ -283,8 +281,7 @@ TGeoVolume *TGeoBuilder::MakeHype(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoBuilder::MakeParaboloid(const char *name, TGeoMedium *medium, - Double_t rlo, Double_t rhi, Double_t dz) +TGeoVolume *TGeoBuilder::MakeParaboloid(const char *name, TGeoMedium *medium, Double_t rlo, Double_t rhi, Double_t dz) { TGeoParaboloid *parab = new TGeoParaboloid(name, rlo, rhi, dz); TGeoVolume *vol = 0; @@ -300,9 +297,9 @@ TGeoVolume *TGeoBuilder::MakeParaboloid(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube segment shape with given medium -TGeoVolume *TGeoBuilder::MakeCtub(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz) +TGeoVolume *TGeoBuilder::MakeCtub(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, + Double_t phi1, Double_t phi2, Double_t lx, Double_t ly, Double_t lz, Double_t tx, + Double_t ty, Double_t tz) { TGeoCtub *ctub = new TGeoCtub(name, rmin, rmax, dz, phi1, phi2, lx, ly, lz, tx, ty, tz); TGeoVolume *vol = new TGeoVolume(name, ctub, medium); @@ -312,9 +309,8 @@ TGeoVolume *TGeoBuilder::MakeCtub(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a cone shape with given medium. -TGeoVolume *TGeoBuilder::MakeCone(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2) +TGeoVolume *TGeoBuilder::MakeCone(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2) { TGeoCone *cone = new TGeoCone(name, dz, rmin1, rmax1, rmin2, rmax2); TGeoVolume *vol = 0; @@ -330,10 +326,8 @@ TGeoVolume *TGeoBuilder::MakeCone(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a cone segment shape with given medium -TGeoVolume *TGeoBuilder::MakeCons(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, - Double_t phi1, Double_t phi2) +TGeoVolume *TGeoBuilder::MakeCons(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2) { TGeoConeSeg *cons = new TGeoConeSeg(name, dz, rmin1, rmax1, rmin2, rmax2, phi1, phi2); TGeoVolume *vol = 0; @@ -349,8 +343,7 @@ TGeoVolume *TGeoBuilder::MakeCons(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a polycone shape with given medium. -TGeoVolume *TGeoBuilder::MakePcon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nz) +TGeoVolume *TGeoBuilder::MakePcon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nz) { TGeoPcon *pcon = new TGeoPcon(name, phi, dphi, nz); TGeoVolume *vol = new TGeoVolume(name, pcon, medium); @@ -360,8 +353,8 @@ TGeoVolume *TGeoBuilder::MakePcon(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a polygone shape with given medium. -TGeoVolume *TGeoBuilder::MakePgon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nedges, Int_t nz) +TGeoVolume * +TGeoBuilder::MakePgon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nedges, Int_t nz) { TGeoPgon *pgon = new TGeoPgon(name, phi, dphi, nedges, nz); TGeoVolume *vol = new TGeoVolume(name, pgon, medium); @@ -371,8 +364,8 @@ TGeoVolume *TGeoBuilder::MakePgon(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a TGeoTrd1 shape with given medium. -TGeoVolume *TGeoBuilder::MakeTrd1(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy, Double_t dz) +TGeoVolume * +TGeoBuilder::MakeTrd1(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy, Double_t dz) { TGeoTrd1 *trd1 = new TGeoTrd1(name, dx1, dx2, dy, dz); TGeoVolume *vol = 0; @@ -388,9 +381,8 @@ TGeoVolume *TGeoBuilder::MakeTrd1(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a TGeoTrd2 shape with given medium. -TGeoVolume *TGeoBuilder::MakeTrd2(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, - Double_t dz) +TGeoVolume *TGeoBuilder::MakeTrd2(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy1, + Double_t dy2, Double_t dz) { TGeoTrd2 *trd2 = new TGeoTrd2(name, dx1, dx2, dy1, dy2, dz); TGeoVolume *vol = 0; @@ -406,13 +398,11 @@ TGeoVolume *TGeoBuilder::MakeTrd2(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a trapezoid shape with given medium. -TGeoVolume *TGeoBuilder::MakeTrap(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, +TGeoVolume *TGeoBuilder::MakeTrap(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, + Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2) { - TGeoTrap *trap = new TGeoTrap(name, dz, theta, phi, h1, bl1, tl1, alpha1, h2, bl2, - tl2, alpha2); + TGeoTrap *trap = new TGeoTrap(name, dz, theta, phi, h1, bl1, tl1, alpha1, h2, bl2, tl2, alpha2); TGeoVolume *vol = new TGeoVolume(name, trap, medium); return vol; } @@ -420,13 +410,11 @@ TGeoVolume *TGeoBuilder::MakeTrap(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a twisted trapezoid shape with given medium. -TGeoVolume *TGeoBuilder::MakeGtra(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2) +TGeoVolume *TGeoBuilder::MakeGtra(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, + Double_t twist, Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, + Double_t bl2, Double_t tl2, Double_t alpha2) { - TGeoGtra *gtra = new TGeoGtra(name, dz, theta, phi, twist, h1, bl1, tl1, alpha1, h2, bl2, - tl2, alpha2); + TGeoGtra *gtra = new TGeoGtra(name, dz, theta, phi, twist, h1, bl1, tl1, alpha1, h2, bl2, tl2, alpha2); TGeoVolume *vol = new TGeoVolume(name, gtra, medium); return vol; } @@ -457,7 +445,6 @@ TGeoVolumeMulti *TGeoBuilder::MakeVolumeMulti(const char *name, TGeoMedium *medi return (new TGeoVolumeMulti(name, medium)); } - //////////////////////////////////////////////////////////////////////////////// /// Create a new volume by dividing an existing one (GEANT3 like) /// @@ -473,8 +460,8 @@ TGeoVolumeMulti *TGeoBuilder::MakeVolumeMulti(const char *name, TGeoMedium *medi /// in full range (same effect as NDIV<=0) (GSDVS, GSDVT in G3) /// - SX - same as DVS, but from START position. (GSDVS2, GSDVT2 in G3) -TGeoVolume *TGeoBuilder::Division(const char *name, const char *mother, Int_t iaxis, - Int_t ndiv, Double_t start, Double_t step, Int_t numed, Option_t *option) +TGeoVolume *TGeoBuilder::Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, Double_t start, + Double_t step, Int_t numed, Option_t *option) { TGeoVolume *amother; TString sname = name; @@ -484,11 +471,13 @@ TGeoVolume *TGeoBuilder::Division(const char *name, const char *mother, Int_t ia smname = smname.Strip(); const char *mname = smname.Data(); - amother = (TGeoVolume*)fGeometry->GetListOfGVolumes()->FindObject(mname); - if (!amother) amother = fGeometry->GetVolume(mname); - if (amother) return amother->Divide(vname,iaxis,ndiv,start,step,numed, option); + amother = (TGeoVolume *)fGeometry->GetListOfGVolumes()->FindObject(mname); + if (!amother) + amother = fGeometry->GetVolume(mname); + if (amother) + return amother->Divide(vname, iaxis, ndiv, start, step, numed, option); - Error("Division","VOLUME: \"%s\" not defined",mname); + Error("Division", "VOLUME: \"%s\" not defined", mname); return 0; } @@ -505,11 +494,10 @@ TGeoVolume *TGeoBuilder::Division(const char *name, const char *mother, Int_t ia /// - phi3 azimuthal angle for axis Z /// -void TGeoBuilder::Matrix(Int_t index, Double_t theta1, Double_t phi1, - Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3) +void TGeoBuilder::Matrix(Int_t index, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, + Double_t phi3) { - TGeoRotation * rot = new TGeoRotation("",theta1,phi1,theta2,phi2,theta3,phi3); + TGeoRotation *rot = new TGeoRotation("", theta1, phi1, theta2, phi2, theta3, phi3); rot->SetUniqueID(index); rot->RegisterYourself(); } @@ -517,9 +505,10 @@ void TGeoBuilder::Matrix(Int_t index, Double_t theta1, Double_t phi1, //////////////////////////////////////////////////////////////////////////////// /// Create material with given A, Z and density, having an unique id. -TGeoMaterial *TGeoBuilder::Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid,Double_t radlen, Double_t intlen) +TGeoMaterial *TGeoBuilder::Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen, + Double_t intlen) { - TGeoMaterial *material = new TGeoMaterial(name,a,z,dens,radlen,intlen); + TGeoMaterial *material = new TGeoMaterial(name, a, z, dens, radlen, intlen); material->SetUniqueID(uid); return material; } @@ -528,32 +517,32 @@ TGeoMaterial *TGeoBuilder::Material(const char *name, Double_t a, Double_t z, Do /// Create mixture OR COMPOUND IMAT as composed by THE BASIC nelem /// materials defined by arrays A,Z and WMAT, having an unique id. -TGeoMaterial *TGeoBuilder::Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, - Int_t nelem, Float_t *wmat, Int_t uid) +TGeoMaterial * +TGeoBuilder::Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, Int_t nelem, Float_t *wmat, Int_t uid) { - TGeoMixture *mix = new TGeoMixture(name,nelem,dens); + TGeoMixture *mix = new TGeoMixture(name, nelem, dens); mix->SetUniqueID(uid); Int_t i; - for (i=0;iDefineElement(i,a[i],z[i],wmat[i]); + for (i = 0; i < nelem; i++) { + mix->DefineElement(i, a[i], z[i], wmat[i]); } - return (TGeoMaterial*)mix; + return (TGeoMaterial *)mix; } //////////////////////////////////////////////////////////////////////////////// /// Create mixture OR COMPOUND IMAT as composed by THE BASIC nelem /// materials defined by arrays A,Z and WMAT, having an unique id. -TGeoMaterial *TGeoBuilder::Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, - Int_t nelem, Double_t *wmat, Int_t uid) +TGeoMaterial * +TGeoBuilder::Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, Int_t nelem, Double_t *wmat, Int_t uid) { - TGeoMixture *mix = new TGeoMixture(name,nelem,dens); + TGeoMixture *mix = new TGeoMixture(name, nelem, dens); mix->SetUniqueID(uid); Int_t i; - for (i=0;iDefineElement(i,a[i],z[i],wmat[i]); + for (i = 0; i < nelem; i++) { + mix->DefineElement(i, a[i], z[i], wmat[i]); } - return (TGeoMaterial*)mix; + return (TGeoMaterial *)mix; } //////////////////////////////////////////////////////////////////////////////// @@ -576,12 +565,10 @@ TGeoMaterial *TGeoBuilder::Mixture(const char *name, Double_t *a, Double_t *z, D /// performed with g3helix; ifield = 3 if tracking performed with g3helx3. /// -TGeoMedium *TGeoBuilder::Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, - Int_t ifield, Double_t fieldm, Double_t tmaxfd, - Double_t stemax, Double_t deemax, Double_t epsil, - Double_t stmin) +TGeoMedium *TGeoBuilder::Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, Int_t ifield, Double_t fieldm, + Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin) { - return new TGeoMedium(name,numed,nmat,isvol,ifield,fieldm,tmaxfd,stemax,deemax,epsil,stmin); + return new TGeoMedium(name, numed, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, epsil, stmin); } //////////////////////////////////////////////////////////////////////////////// @@ -599,127 +586,139 @@ TGeoMedium *TGeoBuilder::Medium(const char *name, Int_t numed, Int_t nmat, Int_t /// - IROT Rotation matrix number w.r.t. mother ref. sys. /// - ISONLY ONLY/MANY flag -void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, +void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, Bool_t isOnly, Float_t *upar, Int_t npar) { - TGeoVolume *amother= 0; + TGeoVolume *amother = 0; TGeoVolume *volume = 0; // look into special volume list first - amother = fGeometry->FindVolumeFast(mother,kTRUE); - if (!amother) amother = fGeometry->FindVolumeFast(mother); + amother = fGeometry->FindVolumeFast(mother, kTRUE); + if (!amother) + amother = fGeometry->FindVolumeFast(mother); if (!amother) { TString mname = mother; mname = mname.Strip(); - Error("Node","Mother VOLUME \"%s\" not defined",mname.Data()); + Error("Node", "Mother VOLUME \"%s\" not defined", mname.Data()); return; } Int_t i; - if (npar<=0) { - //---> acting as G3 gspos - if (gDebug > 0) Info("Node","Calling gspos, mother=%s, name=%s, nr=%d, x=%g, y=%g, z=%g, irot=%d, konly=%i",mother,name,nr,x,y,z,irot,(Int_t)isOnly); + if (npar <= 0) { + //---> acting as G3 gspos + if (gDebug > 0) + Info("Node", "Calling gspos, mother=%s, name=%s, nr=%d, x=%g, y=%g, z=%g, irot=%d, konly=%i", mother, name, nr, + x, y, z, irot, (Int_t)isOnly); // look into special volume list first - volume = fGeometry->FindVolumeFast(name,kTRUE); - if (!volume) volume = fGeometry->FindVolumeFast(name); + volume = fGeometry->FindVolumeFast(name, kTRUE); + if (!volume) + volume = fGeometry->FindVolumeFast(name); if (!volume) { TString vname = name; vname = vname.Strip(); - Error("Node","VOLUME: \"%s\" not defined",vname.Data()); + Error("Node", "VOLUME: \"%s\" not defined", vname.Data()); return; } - if (((TObject*)volume)->TestBit(TGeoVolume::kVolumeMulti) && !volume->GetShape()) { + if (((TObject *)volume)->TestBit(TGeoVolume::kVolumeMulti) && !volume->GetShape()) { Error("Node", "cannot add multiple-volume object %s as node", volume->GetName()); return; } } else { - //---> acting as G3 gsposp - TGeoVolumeMulti *vmulti = (TGeoVolumeMulti*)fGeometry->FindVolumeFast(name, kTRUE); + //---> acting as G3 gsposp + TGeoVolumeMulti *vmulti = (TGeoVolumeMulti *)fGeometry->FindVolumeFast(name, kTRUE); if (!vmulti) { volume = fGeometry->FindVolumeFast(name); if (volume) { Warning("Node", "volume: %s is defined as single -> ignoring shape parameters", volume->GetName()); - Node(name,nr,mother,x,y,z,irot,isOnly, upar); + Node(name, nr, mother, x, y, z, irot, isOnly, upar); return; } TString vname = name; vname = vname.Strip(); - Error("Node","VOLUME: \"%s\" not defined ",vname.Data()); + Error("Node", "VOLUME: \"%s\" not defined ", vname.Data()); return; } TGeoMedium *medium = vmulti->GetMedium(); - TString sh = vmulti->GetTitle(); + TString sh = vmulti->GetTitle(); sh.ToLower(); if (sh.Contains("box")) { - volume = MakeBox(name,medium,upar[0],upar[1],upar[2]); + volume = MakeBox(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("trd1")) { - volume = MakeTrd1(name,medium,upar[0],upar[1],upar[2],upar[3]); + volume = MakeTrd1(name, medium, upar[0], upar[1], upar[2], upar[3]); } else if (sh.Contains("trd2")) { - volume = MakeTrd2(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTrd2(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("trap")) { - volume = MakeTrap(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeTrap(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10]); } else if (sh.Contains("gtra")) { - volume = MakeGtra(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10],upar[11]); + volume = MakeGtra(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10], upar[11]); } else if (sh.Contains("tube")) { - volume = MakeTube(name,medium,upar[0],upar[1],upar[2]); + volume = MakeTube(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("tubs")) { - volume = MakeTubs(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTubs(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cone")) { - volume = MakeCone(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeCone(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cons")) { - volume = MakeCons(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6]); + volume = MakeCons(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6]); } else if (sh.Contains("pgon")) { - volume = MakePgon(name,medium,upar[0],upar[1],(Int_t)upar[2],(Int_t)upar[3]); + volume = MakePgon(name, medium, upar[0], upar[1], (Int_t)upar[2], (Int_t)upar[3]); Int_t nz = (Int_t)upar[3]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+4],upar[3*i+5],upar[3*i+6]); + for (i = 0; i < nz; i++) { + ((TGeoPgon *)volume->GetShape())->DefineSection(i, upar[3 * i + 4], upar[3 * i + 5], upar[3 * i + 6]); } } else if (sh.Contains("pcon")) { - volume = MakePcon(name,medium,upar[0],upar[1],(Int_t)upar[2]); + volume = MakePcon(name, medium, upar[0], upar[1], (Int_t)upar[2]); Int_t nz = (Int_t)upar[2]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+3],upar[3*i+4],upar[3*i+5]); + for (i = 0; i < nz; i++) { + ((TGeoPcon *)volume->GetShape())->DefineSection(i, upar[3 * i + 3], upar[3 * i + 4], upar[3 * i + 5]); } } else if (sh.Contains("eltu")) { - volume = MakeEltu(name,medium,upar[0],upar[1],upar[2]); + volume = MakeEltu(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("sphe")) { - volume = MakeSphere(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakeSphere(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("ctub")) { - volume = MakeCtub(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeCtub(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10]); } else if (sh.Contains("para")) { - volume = MakePara(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakePara(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else { - Error("Node","cannot create shape %s",sh.Data()); + Error("Node", "cannot create shape %s", sh.Data()); } - if (!volume) return; + if (!volume) + return; vmulti->AddVolume(volume); } if (irot) { TGeoRotation *matrix = 0; TGeoMatrix *mat; TIter next(fGeometry->GetListOfMatrices()); - while ((mat=(TGeoMatrix*)next())) { - if (mat->GetUniqueID()==UInt_t(irot)) { - matrix = dynamic_cast(mat); + while ((mat = (TGeoMatrix *)next())) { + if (mat->GetUniqueID() == UInt_t(irot)) { + matrix = dynamic_cast(mat); break; } } if (!matrix) { - Fatal("Node", "Node %s/%s_%d rotation %i not found",mother, name, nr ,irot); + Fatal("Node", "Node %s/%s_%d rotation %i not found", mother, name, nr, irot); return; } - if (isOnly) amother->AddNode(volume,nr,new TGeoCombiTrans(x,y,z,matrix)); - else amother->AddNodeOverlap(volume,nr,new TGeoCombiTrans(x,y,z,matrix)); + if (isOnly) + amother->AddNode(volume, nr, new TGeoCombiTrans(x, y, z, matrix)); + else + amother->AddNodeOverlap(volume, nr, new TGeoCombiTrans(x, y, z, matrix)); } else { - if (TMath::Abs(x)AddNode(volume,nr); - else amother->AddNodeOverlap(volume,nr); + if (TMath::Abs(x) < TGeoShape::Tolerance() && TMath::Abs(y) < TGeoShape::Tolerance() && + TMath::Abs(z) < TGeoShape::Tolerance()) { + if (isOnly) + amother->AddNode(volume, nr); + else + amother->AddNodeOverlap(volume, nr); } else { - if (isOnly) amother->AddNode(volume,nr,new TGeoTranslation(x,y,z)); - else amother->AddNodeOverlap(volume,nr,new TGeoTranslation(x,y,z)); + if (isOnly) + amother->AddNode(volume, nr, new TGeoTranslation(x, y, z)); + else + amother->AddNodeOverlap(volume, nr, new TGeoTranslation(x, y, z)); } } } @@ -739,127 +738,139 @@ void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, /// - IROT Rotation matrix number w.r.t. mother ref. sys. /// - ISONLY ONLY/MANY flag -void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, +void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, Bool_t isOnly, Double_t *upar, Int_t npar) { - TGeoVolume *amother= 0; + TGeoVolume *amother = 0; TGeoVolume *volume = 0; // look into special volume list first - amother = fGeometry->FindVolumeFast(mother,kTRUE); - if (!amother) amother = fGeometry->FindVolumeFast(mother); + amother = fGeometry->FindVolumeFast(mother, kTRUE); + if (!amother) + amother = fGeometry->FindVolumeFast(mother); if (!amother) { TString mname = mother; mname = mname.Strip(); - Error("Node","Mother VOLUME \"%s\" not defined",mname.Data()); + Error("Node", "Mother VOLUME \"%s\" not defined", mname.Data()); return; } Int_t i; - if (npar<=0) { - //---> acting as G3 gspos - if (gDebug > 0) Info("Node","Calling gspos, mother=%s, name=%s, nr=%d, x=%g, y=%g, z=%g, irot=%d, konly=%i",mother,name,nr,x,y,z,irot,(Int_t)isOnly); + if (npar <= 0) { + //---> acting as G3 gspos + if (gDebug > 0) + Info("Node", "Calling gspos, mother=%s, name=%s, nr=%d, x=%g, y=%g, z=%g, irot=%d, konly=%i", mother, name, nr, + x, y, z, irot, (Int_t)isOnly); // look into special volume list first - volume = fGeometry->FindVolumeFast(name,kTRUE); - if (!volume) volume = fGeometry->FindVolumeFast(name); + volume = fGeometry->FindVolumeFast(name, kTRUE); + if (!volume) + volume = fGeometry->FindVolumeFast(name); if (!volume) { TString vname = name; vname = vname.Strip(); - Error("Node","VOLUME: \"%s\" not defined",vname.Data()); + Error("Node", "VOLUME: \"%s\" not defined", vname.Data()); return; } - if (((TObject*)volume)->TestBit(TGeoVolume::kVolumeMulti) && !volume->GetShape()) { + if (((TObject *)volume)->TestBit(TGeoVolume::kVolumeMulti) && !volume->GetShape()) { Error("Node", "cannot add multiple-volume object %s as node", volume->GetName()); return; } } else { - //---> acting as G3 gsposp - TGeoVolumeMulti *vmulti = (TGeoVolumeMulti*)fGeometry->FindVolumeFast(name, kTRUE); + //---> acting as G3 gsposp + TGeoVolumeMulti *vmulti = (TGeoVolumeMulti *)fGeometry->FindVolumeFast(name, kTRUE); if (!vmulti) { volume = fGeometry->FindVolumeFast(name); if (volume) { Warning("Node", "volume: %s is defined as single -> ignoring shape parameters", volume->GetName()); - Node(name,nr,mother,x,y,z,irot,isOnly, upar); + Node(name, nr, mother, x, y, z, irot, isOnly, upar); return; } TString vname = name; vname = vname.Strip(); - Error("Node","VOLUME: \"%s\" not defined ",vname.Data()); + Error("Node", "VOLUME: \"%s\" not defined ", vname.Data()); return; } TGeoMedium *medium = vmulti->GetMedium(); - TString sh = vmulti->GetTitle(); + TString sh = vmulti->GetTitle(); sh.ToLower(); if (sh.Contains("box")) { - volume = MakeBox(name,medium,upar[0],upar[1],upar[2]); + volume = MakeBox(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("trd1")) { - volume = MakeTrd1(name,medium,upar[0],upar[1],upar[2],upar[3]); + volume = MakeTrd1(name, medium, upar[0], upar[1], upar[2], upar[3]); } else if (sh.Contains("trd2")) { - volume = MakeTrd2(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTrd2(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("trap")) { - volume = MakeTrap(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeTrap(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10]); } else if (sh.Contains("gtra")) { - volume = MakeGtra(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10],upar[11]); + volume = MakeGtra(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10], upar[11]); } else if (sh.Contains("tube")) { - volume = MakeTube(name,medium,upar[0],upar[1],upar[2]); + volume = MakeTube(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("tubs")) { - volume = MakeTubs(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTubs(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cone")) { - volume = MakeCone(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeCone(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cons")) { - volume = MakeCons(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6]); + volume = MakeCons(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6]); } else if (sh.Contains("pgon")) { - volume = MakePgon(name,medium,upar[0],upar[1],(Int_t)upar[2],(Int_t)upar[3]); + volume = MakePgon(name, medium, upar[0], upar[1], (Int_t)upar[2], (Int_t)upar[3]); Int_t nz = (Int_t)upar[3]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+4],upar[3*i+5],upar[3*i+6]); + for (i = 0; i < nz; i++) { + ((TGeoPgon *)volume->GetShape())->DefineSection(i, upar[3 * i + 4], upar[3 * i + 5], upar[3 * i + 6]); } } else if (sh.Contains("pcon")) { - volume = MakePcon(name,medium,upar[0],upar[1],(Int_t)upar[2]); + volume = MakePcon(name, medium, upar[0], upar[1], (Int_t)upar[2]); Int_t nz = (Int_t)upar[2]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+3],upar[3*i+4],upar[3*i+5]); + for (i = 0; i < nz; i++) { + ((TGeoPcon *)volume->GetShape())->DefineSection(i, upar[3 * i + 3], upar[3 * i + 4], upar[3 * i + 5]); } } else if (sh.Contains("eltu")) { - volume = MakeEltu(name,medium,upar[0],upar[1],upar[2]); + volume = MakeEltu(name, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("sphe")) { - volume = MakeSphere(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakeSphere(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("ctub")) { - volume = MakeCtub(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeCtub(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], + upar[8], upar[9], upar[10]); } else if (sh.Contains("para")) { - volume = MakePara(name,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakePara(name, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else { - Error("Node","cannot create shape %s",sh.Data()); + Error("Node", "cannot create shape %s", sh.Data()); } - if (!volume) return; + if (!volume) + return; vmulti->AddVolume(volume); } if (irot) { TGeoRotation *matrix = 0; TGeoMatrix *mat; TIter next(fGeometry->GetListOfMatrices()); - while ((mat=(TGeoMatrix*)next())) { - if (mat->GetUniqueID()==UInt_t(irot)) { - matrix = dynamic_cast(mat); + while ((mat = (TGeoMatrix *)next())) { + if (mat->GetUniqueID() == UInt_t(irot)) { + matrix = dynamic_cast(mat); break; } } if (!matrix) { - Fatal("Node", "Node %s/%s_%d rotation %i not found",mother, name, nr ,irot); + Fatal("Node", "Node %s/%s_%d rotation %i not found", mother, name, nr, irot); return; } - if (isOnly) amother->AddNode(volume,nr,new TGeoCombiTrans(x,y,z,matrix)); - else amother->AddNodeOverlap(volume,nr,new TGeoCombiTrans(x,y,z,matrix)); + if (isOnly) + amother->AddNode(volume, nr, new TGeoCombiTrans(x, y, z, matrix)); + else + amother->AddNodeOverlap(volume, nr, new TGeoCombiTrans(x, y, z, matrix)); } else { - if (TMath::Abs(x)AddNode(volume,nr); - else amother->AddNodeOverlap(volume,nr); + if (TMath::Abs(x) < TGeoShape::Tolerance() && TMath::Abs(y) < TGeoShape::Tolerance() && + TMath::Abs(z) < TGeoShape::Tolerance()) { + if (isOnly) + amother->AddNode(volume, nr); + else + amother->AddNodeOverlap(volume, nr); } else { - if (isOnly) amother->AddNode(volume,nr,new TGeoTranslation(x,y,z)); - else amother->AddNodeOverlap(volume,nr,new TGeoTranslation(x,y,z)); + if (isOnly) + amother->AddNode(volume, nr, new TGeoTranslation(x, y, z)); + else + amother->AddNodeOverlap(volume, nr, new TGeoTranslation(x, y, z)); } } } @@ -872,14 +883,13 @@ void TGeoBuilder::Node(const char *name, Int_t nr, const char *mother, /// - NPAR Number of shape parameters /// - UPAR Vector containing shape parameters -TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, - Float_t *upar, Int_t npar) +TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, Float_t *upar, Int_t npar) { Int_t i; TGeoVolume *volume = 0; TGeoMedium *medium = fGeometry->GetMedium(nmed); if (!medium) { - Error("Volume","cannot create volume: %s, medium: %d is unknown",name,nmed); + Error("Volume", "cannot create volume: %s, medium: %d is unknown", name, nmed); return 0; } TString sh = shape; @@ -888,11 +898,11 @@ TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, const char *vname = sname.Data(); if (npar <= 0) { //--- create a TGeoVolumeMulti - volume = MakeVolumeMulti(vname,medium); + volume = MakeVolumeMulti(vname, medium); volume->SetTitle(shape); - TGeoVolumeMulti *vmulti = (TGeoVolumeMulti*)fGeometry->GetListOfGVolumes()->FindObject(vname); + TGeoVolumeMulti *vmulti = (TGeoVolumeMulti *)fGeometry->GetListOfGVolumes()->FindObject(vname); if (!vmulti) { - Error("Volume","volume multi: %s not created",vname); + Error("Volume", "volume multi: %s not created", vname); return 0; } return vmulti; @@ -900,55 +910,57 @@ TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, //---> create a normal volume sh.ToLower(); if (sh.Contains("box")) { - volume = MakeBox(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeBox(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("trd1")) { - volume = MakeTrd1(vname,medium,upar[0],upar[1],upar[2],upar[3]); + volume = MakeTrd1(vname, medium, upar[0], upar[1], upar[2], upar[3]); } else if (sh.Contains("trd2")) { - volume = MakeTrd2(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTrd2(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("trap")) { - volume = MakeTrap(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeTrap(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10]); } else if (sh.Contains("gtra")) { - volume = MakeGtra(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10],upar[11]); + volume = MakeGtra(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10], upar[11]); } else if (sh.Contains("tube")) { - volume = MakeTube(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeTube(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("tubs")) { - volume = MakeTubs(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTubs(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cone")) { - volume = MakeCone(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeCone(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cons")) { - volume = MakeCons(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6]); + volume = MakeCons(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6]); } else if (sh.Contains("pgon")) { - volume = MakePgon(vname,medium,upar[0],upar[1],(Int_t)upar[2],(Int_t)upar[3]); + volume = MakePgon(vname, medium, upar[0], upar[1], (Int_t)upar[2], (Int_t)upar[3]); Int_t nz = (Int_t)upar[3]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+4],upar[3*i+5],upar[3*i+6]); + for (i = 0; i < nz; i++) { + ((TGeoPgon *)volume->GetShape())->DefineSection(i, upar[3 * i + 4], upar[3 * i + 5], upar[3 * i + 6]); } } else if (sh.Contains("pcon")) { - volume = MakePcon(vname,medium,upar[0],upar[1],(Int_t)upar[2]); + volume = MakePcon(vname, medium, upar[0], upar[1], (Int_t)upar[2]); Int_t nz = (Int_t)upar[2]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+3],upar[3*i+4],upar[3*i+5]); + for (i = 0; i < nz; i++) { + ((TGeoPcon *)volume->GetShape())->DefineSection(i, upar[3 * i + 3], upar[3 * i + 4], upar[3 * i + 5]); } } else if (sh.Contains("eltu")) { - volume = MakeEltu(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeEltu(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("sphe")) { - volume = MakeSphere(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakeSphere(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("ctub")) { - volume = MakeCtub(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeCtub(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10]); } else if (sh.Contains("para")) { - volume = MakePara(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakePara(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("tor")) { - volume = MakeTorus(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTorus(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } if (!volume) { - Error("Volume","volume: %s not created",vname); + Error("Volume", "volume: %s not created", vname); return 0; } return volume; } - //////////////////////////////////////////////////////////////////////////////// /// Create a volume in GEANT3 style. /// - NAME Volume name @@ -957,14 +969,13 @@ TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, /// - NPAR Number of shape parameters /// - UPAR Vector containing shape parameters -TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, - Double_t *upar, Int_t npar) +TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, Double_t *upar, Int_t npar) { Int_t i; TGeoVolume *volume = 0; TGeoMedium *medium = fGeometry->GetMedium(nmed); if (!medium) { - Error("Volume","cannot create volume: %s, medium: %d is unknown",name,nmed); + Error("Volume", "cannot create volume: %s, medium: %d is unknown", name, nmed); return 0; } TString sh = shape; @@ -973,11 +984,11 @@ TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, const char *vname = sname.Data(); if (npar <= 0) { //--- create a TGeoVolumeMulti - volume = MakeVolumeMulti(vname,medium); + volume = MakeVolumeMulti(vname, medium); volume->SetTitle(shape); - TGeoVolumeMulti *vmulti = (TGeoVolumeMulti*)fGeometry->GetListOfGVolumes()->FindObject(vname); + TGeoVolumeMulti *vmulti = (TGeoVolumeMulti *)fGeometry->GetListOfGVolumes()->FindObject(vname); if (!vmulti) { - Error("Volume","volume multi: %s not created",vname); + Error("Volume", "volume multi: %s not created", vname); return 0; } return vmulti; @@ -985,51 +996,53 @@ TGeoVolume *TGeoBuilder::Volume(const char *name, const char *shape, Int_t nmed, //---> create a normal volume sh.ToLower(); if (sh.Contains("box")) { - volume = MakeBox(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeBox(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("trd1")) { - volume = MakeTrd1(vname,medium,upar[0],upar[1],upar[2],upar[3]); + volume = MakeTrd1(vname, medium, upar[0], upar[1], upar[2], upar[3]); } else if (sh.Contains("trd2")) { - volume = MakeTrd2(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTrd2(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("trap")) { - volume = MakeTrap(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeTrap(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10]); } else if (sh.Contains("gtra")) { - volume = MakeGtra(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10],upar[11]); + volume = MakeGtra(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10], upar[11]); } else if (sh.Contains("tube")) { - volume = MakeTube(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeTube(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("tubs")) { - volume = MakeTubs(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTubs(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cone")) { - volume = MakeCone(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeCone(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } else if (sh.Contains("cons")) { - volume = MakeCons(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6]); + volume = MakeCons(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6]); } else if (sh.Contains("pgon")) { - volume = MakePgon(vname,medium,upar[0],upar[1],(Int_t)upar[2],(Int_t)upar[3]); + volume = MakePgon(vname, medium, upar[0], upar[1], (Int_t)upar[2], (Int_t)upar[3]); Int_t nz = (Int_t)upar[3]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+4],upar[3*i+5],upar[3*i+6]); + for (i = 0; i < nz; i++) { + ((TGeoPgon *)volume->GetShape())->DefineSection(i, upar[3 * i + 4], upar[3 * i + 5], upar[3 * i + 6]); } } else if (sh.Contains("pcon")) { - volume = MakePcon(vname,medium,upar[0],upar[1],(Int_t)upar[2]); + volume = MakePcon(vname, medium, upar[0], upar[1], (Int_t)upar[2]); Int_t nz = (Int_t)upar[2]; - for (i=0;iGetShape())->DefineSection(i,upar[3*i+3],upar[3*i+4],upar[3*i+5]); + for (i = 0; i < nz; i++) { + ((TGeoPcon *)volume->GetShape())->DefineSection(i, upar[3 * i + 3], upar[3 * i + 4], upar[3 * i + 5]); } } else if (sh.Contains("eltu")) { - volume = MakeEltu(vname,medium,upar[0],upar[1],upar[2]); + volume = MakeEltu(vname, medium, upar[0], upar[1], upar[2]); } else if (sh.Contains("sphe")) { - volume = MakeSphere(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakeSphere(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("ctub")) { - volume = MakeCtub(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5],upar[6],upar[7],upar[8],upar[9],upar[10]); + volume = MakeCtub(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5], upar[6], upar[7], upar[8], + upar[9], upar[10]); } else if (sh.Contains("para")) { - volume = MakePara(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4],upar[5]); + volume = MakePara(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4], upar[5]); } else if (sh.Contains("tor")) { - volume = MakeTorus(vname,medium,upar[0],upar[1],upar[2],upar[3],upar[4]); + volume = MakeTorus(vname, medium, upar[0], upar[1], upar[2], upar[3], upar[4]); } if (!volume) { - Error("Volume","volume: %s not created",vname); + Error("Volume", "volume: %s not created", vname); return 0; } return volume; } - diff --git a/geom/geom/src/TGeoCache.cxx b/geom/geom/src/TGeoCache.cxx index d1d57d1fc7530..c169742418a5f 100644 --- a/geom/geom/src/TGeoCache.cxx +++ b/geom/geom/src/TGeoCache.cxx @@ -17,7 +17,7 @@ #include "TGeoVolume.h" #include "TObject.h" -//const Int_t kN3 = 3*sizeof(Double_t); +// const Int_t kN3 = 3*sizeof(Double_t); ClassImp(TGeoNodeCache); @@ -33,26 +33,27 @@ Special pool of reusable nodes TGeoNodeCache::TGeoNodeCache() { - fGeoCacheMaxLevels = 100; - fGeoCacheStackSize = 10; - fGeoInfoStackSize = 100; - fLevel = 0; - fStackLevel = 0; - fInfoLevel = 0; - fCurrentID = 0; - fIndex = 0; - fPath = ""; - fTop = 0; - fNode = 0; - fMatrix = 0; - fStack = 0; + fGeoCacheMaxLevels = 100; + fGeoCacheStackSize = 10; + fGeoInfoStackSize = 100; + fLevel = 0; + fStackLevel = 0; + fInfoLevel = 0; + fCurrentID = 0; + fIndex = 0; + fPath = ""; + fTop = 0; + fNode = 0; + fMatrix = 0; + fStack = 0; fMatrixBranch = 0; - fMPB = 0; - fNodeBranch = 0; - fInfoBranch = 0; - fPWInfo = 0; + fMPB = 0; + fNodeBranch = 0; + fInfoBranch = 0; + fPWInfo = 0; fNodeIdArray = 0; - for (Int_t i=0; i<100; i++) fIdBranch[i] = 0; + for (Int_t i = 0; i < 100; i++) + fIdBranch[i] = 0; } //////////////////////////////////////////////////////////////////////////////// @@ -60,38 +61,40 @@ TGeoNodeCache::TGeoNodeCache() TGeoNodeCache::TGeoNodeCache(TGeoNode *top, Bool_t nodeid, Int_t capacity) { - fGeoCacheMaxLevels = capacity; - fGeoCacheStackSize = 10; - fGeoInfoStackSize = 100; - fLevel = 0; - fStackLevel = 0; - fInfoLevel = 0; - fCurrentID = 0; - fIndex = 0; - fPath = ""; - fTop = top; - fNode = top; + fGeoCacheMaxLevels = capacity; + fGeoCacheStackSize = 10; + fGeoInfoStackSize = 100; + fLevel = 0; + fStackLevel = 0; + fInfoLevel = 0; + fCurrentID = 0; + fIndex = 0; + fPath = ""; + fTop = top; + fNode = top; fStack = new TObjArray(fGeoCacheStackSize); - for (Int_t ist=0; istAdd(new TGeoCacheState(fGeoCacheMaxLevels)); // !obsolete 100 fMatrixBranch = new TGeoHMatrix *[fGeoCacheMaxLevels]; fMPB = new TGeoHMatrix *[fGeoCacheMaxLevels]; - fNodeBranch = new TGeoNode*[fGeoCacheMaxLevels]; - fInfoBranch = new TGeoStateInfo*[fGeoInfoStackSize]; - for (Int_t i=0; iDelete(); delete fStack; } - if (fMatrixBranch) delete [] fMatrixBranch; + if (fMatrixBranch) + delete[] fMatrixBranch; if (fMPB) { - for (Int_t i=0; iGetNNodes(); - //if (nnodes>3E7) return; - if (fNodeIdArray) delete [] fNodeIdArray; - Info("BuildIDArray","--- node ID tracking enabled, size=%lu Bytes\n", ULong_t((2*nnodes+1)*sizeof(Int_t))); - fNodeIdArray = new Int_t[2*nnodes+1]; + // if (nnodes>3E7) return; + if (fNodeIdArray) + delete[] fNodeIdArray; + Info("BuildIDArray", "--- node ID tracking enabled, size=%lu Bytes\n", ULong_t((2 * nnodes + 1) * sizeof(Int_t))); + fNodeIdArray = new Int_t[2 * nnodes + 1]; fNodeIdArray[0] = 0; - Int_t ifree = 1; + Int_t ifree = 1; Int_t nodeid = 0; gGeoManager->GetTopNode()->FillIdArray(ifree, nodeid, fNodeIdArray); gGeoManager->CdTop(); @@ -141,9 +149,11 @@ void TGeoNodeCache::BuildIdArray() void TGeoNodeCache::BuildInfoBranch() { - if (!fInfoBranch) fInfoBranch = new TGeoStateInfo*[fGeoInfoStackSize]; - else if (fInfoBranch[0]) return; - for (Int_t i=0; iGetCache()->BuildIdArray()"); + Error("CdNode", "Navigation based on physical node unique id disabled.\n To enable, use: " + "gGeoManager->GetCache()->BuildIdArray()"); return; } Int_t *arr = fNodeIdArray; - if (nodeid == arr[fIndex]) return; - while (fLevel>0) { + if (nodeid == arr[fIndex]) + return; + while (fLevel > 0) { gGeoManager->CdUp(); - if (nodeid == arr[fIndex]) return; + if (nodeid == arr[fIndex]) + return; } gGeoManager->CdTop(); Int_t currentID = 0; Int_t nd = GetNode()->GetNdaughters(); Int_t nabove, nbelow, middle; - while (nodeid!=currentID && nd) { - nabove = nd+1; + while (nodeid != currentID && nd) { + nabove = nd + 1; nbelow = 0; - while (nabove-nbelow > 1) { - middle = (nabove+nbelow)>>1; - currentID = arr[arr[fIndex+middle]]; + while (nabove - nbelow > 1) { + middle = (nabove + nbelow) >> 1; + currentID = arr[arr[fIndex + middle]]; if (nodeid == currentID) { - gGeoManager->CdDown(middle-1); + gGeoManager->CdDown(middle - 1); return; } - if (nodeid < currentID) nabove = middle; - else nbelow = middle; + if (nodeid < currentID) + nabove = middle; + else + nbelow = middle; } - gGeoManager->CdDown(nbelow-1); + gGeoManager->CdDown(nbelow - 1); currentID = arr[fIndex]; nd = GetNode()->GetNdaughters(); } @@ -202,15 +219,16 @@ void TGeoNodeCache::CdNode(Int_t nodeid) { Bool_t TGeoNodeCache::CdDown(Int_t index) { TGeoNode *newnode = fNode->GetDaughter(index); - if (!newnode) return kFALSE; + if (!newnode) + return kFALSE; fLevel++; if (fNodeIdArray) { - fIndex = fNodeIdArray[fIndex+index+1]; + fIndex = fNodeIdArray[fIndex + index + 1]; fIdBranch[fLevel] = fIndex; } fNode = newnode; fNodeBranch[fLevel] = fNode; - TGeoMatrix *local = newnode->GetMatrix(); + TGeoMatrix *local = newnode->GetMatrix(); TGeoHMatrix *newmat = fMPB[fLevel]; if (!local->IsIdentity()) { newmat->CopyFrom(fMatrix); @@ -226,16 +244,17 @@ Bool_t TGeoNodeCache::CdDown(Int_t index) Bool_t TGeoNodeCache::CdDown(TGeoNode *newnode) { - if (!newnode) return kFALSE; + if (!newnode) + return kFALSE; fLevel++; if (fNodeIdArray) { Int_t index = fNode->GetVolume()->GetIndex(newnode); - fIndex = fNodeIdArray[fIndex+index+1]; + fIndex = fNodeIdArray[fIndex + index + 1]; fIdBranch[fLevel] = fIndex; } fNode = newnode; fNodeBranch[fLevel] = fNode; - TGeoMatrix *local = newnode->GetMatrix(); + TGeoMatrix *local = newnode->GetMatrix(); TGeoHMatrix *newmat = fMPB[fLevel]; if (!local->IsIdentity()) { newmat->CopyFrom(fMatrix); @@ -251,9 +270,11 @@ Bool_t TGeoNodeCache::CdDown(TGeoNode *newnode) void TGeoNodeCache::CdUp() { - if (!fLevel) return; + if (!fLevel) + return; fLevel--; - if (fNodeIdArray) fIndex = fIdBranch[fLevel]; + if (fNodeIdArray) + fIndex = fIdBranch[fLevel]; fNode = fNodeBranch[fLevel]; fMatrix = fMatrixBranch[fLevel]; } @@ -263,7 +284,8 @@ void TGeoNodeCache::CdUp() Int_t TGeoNodeCache::GetCurrentNodeId() const { - if (fNodeIdArray) return fNodeIdArray[fIndex]; + if (fNodeIdArray) + return fNodeIdArray[fIndex]; return GetNodeId(); } @@ -272,8 +294,8 @@ Int_t TGeoNodeCache::GetCurrentNodeId() const Int_t TGeoNodeCache::GetNodeId() const { - Longptr_t id=0; - for (Int_t level=0;levelGetVolume()->GetName(); memcpy(&names[i], name, sizeof(Int_t)); } @@ -295,8 +317,8 @@ void TGeoNodeCache::GetBranchNames(Int_t *names) const void TGeoNodeCache::GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) const { - for (Int_t i=0; iGetNumber(); + for (Int_t i = 0; i < fLevel + 1; i++) { + copyNumbers[i] = fNodeBranch[i]->GetNumber(); volumeNumbers[i] = fNodeBranch[i]->GetVolume()->GetNumber(); } } @@ -307,9 +329,10 @@ void TGeoNodeCache::GetBranchNumbers(Int_t *copyNumbers, Int_t *volumeNumbers) c void TGeoNodeCache::GetBranchOnlys(Int_t *isonly) const { Bool_t ismany = kFALSE; - for (Int_t i=0; iIsOffset()) ismany=fNodeBranch[i]->IsOverlapping(); - isonly[i] = (ismany)?0:1; + for (Int_t i = 0; i < fLevel + 1; i++) { + if (!fNodeBranch[i]->IsOffset()) + ismany = fNodeBranch[i]->IsOverlapping(); + isonly[i] = (ismany) ? 0 : 1; } } @@ -318,12 +341,12 @@ void TGeoNodeCache::GetBranchOnlys(Int_t *isonly) const TGeoStateInfo *TGeoNodeCache::GetInfo() { - if (fInfoLevel==fGeoInfoStackSize-1) { - TGeoStateInfo **infoBranch = new TGeoStateInfo*[2*fGeoInfoStackSize]; - memcpy(infoBranch, fInfoBranch, fGeoInfoStackSize*sizeof(TGeoStateInfo*)); - for (Int_t i=fGeoInfoStackSize; i<2*fGeoInfoStackSize; i++) + if (fInfoLevel == fGeoInfoStackSize - 1) { + TGeoStateInfo **infoBranch = new TGeoStateInfo *[2 * fGeoInfoStackSize]; + memcpy(infoBranch, fInfoBranch, fGeoInfoStackSize * sizeof(TGeoStateInfo *)); + for (Int_t i = fGeoInfoStackSize; i < 2 * fGeoInfoStackSize; i++) infoBranch[i] = new TGeoStateInfo(); - delete [] fInfoBranch; + delete[] fInfoBranch; fInfoBranch = infoBranch; fGeoInfoStackSize *= 2; } @@ -344,7 +367,7 @@ void TGeoNodeCache::ReleaseInfo() const char *TGeoNodeCache::GetPath() { fPath = ""; - for (Int_t level=0;levelGetName(); } @@ -356,11 +379,11 @@ const char *TGeoNodeCache::GetPath() Int_t TGeoNodeCache::PushState(Bool_t ovlp, Int_t startlevel, Int_t nmany, Double_t *point) { - if (fStackLevel>=fGeoCacheStackSize) { - for (Int_t ist=0; ist= fGeoCacheStackSize) { + for (Int_t ist = 0; ist < fGeoCacheStackSize; ist++) fStack->Add(new TGeoCacheState(fGeoCacheMaxLevels)); } - ((TGeoCacheState*)fStack->At(fStackLevel))->SetState(fLevel,startlevel,nmany,ovlp,point); + ((TGeoCacheState *)fStack->At(fStackLevel))->SetState(fLevel, startlevel, nmany, ovlp, point); return ++fStackLevel; } @@ -369,10 +392,11 @@ Int_t TGeoNodeCache::PushState(Bool_t ovlp, Int_t startlevel, Int_t nmany, Doubl Bool_t TGeoNodeCache::PopState(Int_t &nmany, Double_t *point) { - if (!fStackLevel) return 0; - Bool_t ovlp = ((TGeoCacheState*)fStack->At(--fStackLevel))->GetState(fLevel,nmany,point); + if (!fStackLevel) + return 0; + Bool_t ovlp = ((TGeoCacheState *)fStack->At(--fStackLevel))->GetState(fLevel, nmany, point); Refresh(); -// return (fStackLevel+1); + // return (fStackLevel+1); return ovlp; } @@ -381,8 +405,9 @@ Bool_t TGeoNodeCache::PopState(Int_t &nmany, Double_t *point) Bool_t TGeoNodeCache::PopState(Int_t &nmany, Int_t level, Double_t *point) { - if (level<=0) return 0; - Bool_t ovlp = ((TGeoCacheState*)fStack->At(level-1))->GetState(fLevel,nmany,point); + if (level <= 0) + return 0; + Bool_t ovlp = ((TGeoCacheState *)fStack->At(level - 1))->GetState(fLevel, nmany, point); Refresh(); return ovlp; } @@ -392,7 +417,7 @@ Bool_t TGeoNodeCache::PopState(Int_t &nmany, Int_t level, Double_t *point) Bool_t TGeoNodeCache::RestoreState(Int_t &nmany, TGeoCacheState *state, Double_t *point) { - Bool_t ovlp = state->GetState(fLevel,nmany,point); + Bool_t ovlp = state->GetState(fLevel, nmany, point); Refresh(); return ovlp; } @@ -426,7 +451,7 @@ void TGeoNodeCache::LocalToMasterVect(const Double_t *local, Double_t *master) c void TGeoNodeCache::MasterToLocalVect(const Double_t *master, Double_t *local) const { - fMatrix->MasterToLocalVect(master,local); + fMatrix->MasterToLocalVect(master, local); } //////////////////////////////////////////////////////////////////////////////// @@ -463,8 +488,8 @@ TGeoCacheState::TGeoCacheState() fLevel = 0; fNmany = 0; fStart = 0; - memset(fIdBranch, 0, 30*sizeof(Int_t)); - memset(fPoint, 0, 3*sizeof(Int_t)); + memset(fIdBranch, 0, 30 * sizeof(Int_t)); + memset(fPoint, 0, 3 * sizeof(Int_t)); fOverlapping = kFALSE; fNodeBranch = 0; fMatrixBranch = 0; @@ -480,36 +505,38 @@ TGeoCacheState::TGeoCacheState(Int_t capacity) fLevel = 0; fNmany = 0; fStart = 0; - memset(fIdBranch, 0, 30*sizeof(Int_t)); - memset(fPoint, 0, 3*sizeof(Int_t)); + memset(fIdBranch, 0, 30 * sizeof(Int_t)); + memset(fPoint, 0, 3 * sizeof(Int_t)); fOverlapping = kFALSE; fNodeBranch = new TGeoNode *[capacity]; fMatrixBranch = new TGeoHMatrix *[capacity]; fMatPtr = new TGeoHMatrix *[capacity]; - for (Int_t i=0; iGetCache(); - if (cache->HasIdArray()) memcpy(fIdBranch, cache->GetIdBranch()+fStart, (level+1-fStart)*sizeof(Int_t)); - TGeoNode **node_branch = (TGeoNode **) cache->GetBranch(); - TGeoHMatrix **mat_branch = (TGeoHMatrix **) cache->GetMatrices(); - Int_t nelem = level+1-fStart; - memcpy(fNodeBranch, node_branch+fStart, nelem*sizeof(TGeoNode *)); - memcpy(fMatPtr, mat_branch+fStart, nelem*sizeof(TGeoHMatrix *)); + if (cache->HasIdArray()) + memcpy(fIdBranch, cache->GetIdBranch() + fStart, (level + 1 - fStart) * sizeof(Int_t)); + TGeoNode **node_branch = (TGeoNode **)cache->GetBranch(); + TGeoHMatrix **mat_branch = (TGeoHMatrix **)cache->GetMatrices(); + Int_t nelem = level + 1 - fStart; + memcpy(fNodeBranch, node_branch + fStart, nelem * sizeof(TGeoNode *)); + memcpy(fMatPtr, mat_branch + fStart, nelem * sizeof(TGeoHMatrix *)); TGeoHMatrix *last = 0; TGeoHMatrix *current; - for (Int_t i=0; iGetCache(); - if (cache->HasIdArray()) cache->FillIdBranch(fIdBranch, fStart); - TGeoNode **node_branch = (TGeoNode **) cache->GetBranch(); - TGeoHMatrix **mat_branch = (TGeoHMatrix **) cache->GetMatrices(); - Int_t nelem = level+1-fStart; - memcpy(node_branch+fStart, fNodeBranch, nelem*sizeof(TGeoNode *)); - memcpy(mat_branch+fStart, fMatPtr, (level+1-fStart)*sizeof(TGeoHMatrix *)); + if (cache->HasIdArray()) + cache->FillIdBranch(fIdBranch, fStart); + TGeoNode **node_branch = (TGeoNode **)cache->GetBranch(); + TGeoHMatrix **mat_branch = (TGeoHMatrix **)cache->GetMatrices(); + Int_t nelem = level + 1 - fStart; + memcpy(node_branch + fStart, fNodeBranch, nelem * sizeof(TGeoNode *)); + memcpy(mat_branch + fStart, fMatPtr, (level + 1 - fStart) * sizeof(TGeoHMatrix *)); TGeoHMatrix *last = 0; TGeoHMatrix *current; - for (Int_t i=0; iClearThreadData(); + if (fNode) + fNode->ClearThreadData(); } //////////////////////////////////////////////////////////////////////////////// @@ -208,28 +208,27 @@ void TGeoCompositeShape::ClearThreadData() const void TGeoCompositeShape::CreateThreadData(Int_t nthreads) { - if (fNode) fNode->CreateThreadData(nthreads); + if (fNode) + fNode->CreateThreadData(nthreads); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoCompositeShape::TGeoCompositeShape() - :TGeoBBox(0, 0, 0) +TGeoCompositeShape::TGeoCompositeShape() : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoComb); - fNode = 0; + fNode = 0; } //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoCompositeShape::TGeoCompositeShape(const char *name, const char *expression) - :TGeoBBox(0, 0, 0) +TGeoCompositeShape::TGeoCompositeShape(const char *name, const char *expression) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoComb); SetName(name); - fNode = 0; + fNode = 0; MakeNode(expression); if (!fNode) { Error("ctor", "Composite %s: cannot parse expression: %s", name, expression); @@ -241,11 +240,10 @@ TGeoCompositeShape::TGeoCompositeShape(const char *name, const char *expression) //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoCompositeShape::TGeoCompositeShape(const char *expression) - :TGeoBBox(0, 0, 0) +TGeoCompositeShape::TGeoCompositeShape(const char *expression) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoComb); - fNode = 0; + fNode = 0; MakeNode(expression); if (!fNode) { TString message = TString::Format("Composite (no name) could not parse expression %s", expression); @@ -258,8 +256,7 @@ TGeoCompositeShape::TGeoCompositeShape(const char *expression) //////////////////////////////////////////////////////////////////////////////// /// Constructor with a Boolean node -TGeoCompositeShape::TGeoCompositeShape(const char *name, TGeoBoolNode *node) - :TGeoBBox(0,0,0) +TGeoCompositeShape::TGeoCompositeShape(const char *name, TGeoBoolNode *node) : TGeoBBox(0, 0, 0) { SetName(name); fNode = node; @@ -275,7 +272,8 @@ TGeoCompositeShape::TGeoCompositeShape(const char *name, TGeoBoolNode *node) TGeoCompositeShape::~TGeoCompositeShape() { - if (fNode) delete fNode; + if (fNode) + delete fNode; } //////////////////////////////////////////////////////////////////////////////// @@ -284,18 +282,20 @@ TGeoCompositeShape::~TGeoCompositeShape() Double_t TGeoCompositeShape::Capacity() const { Double_t pt[3]; - if (!gRandom) gRandom = new TRandom3(); - Double_t vbox = 8*fDX*fDY*fDZ; // cm3 - Int_t igen=0; + if (!gRandom) + gRandom = new TRandom3(); + Double_t vbox = 8 * fDX * fDY * fDZ; // cm3 + Int_t igen = 0; Int_t iin = 0; - while (iin<10000) { - pt[0] = fOrigin[0]-fDX+2*fDX*gRandom->Rndm(); - pt[1] = fOrigin[1]-fDY+2*fDY*gRandom->Rndm(); - pt[2] = fOrigin[2]-fDZ+2*fDZ*gRandom->Rndm(); + while (iin < 10000) { + pt[0] = fOrigin[0] - fDX + 2 * fDX * gRandom->Rndm(); + pt[1] = fOrigin[1] - fDY + 2 * fDY * gRandom->Rndm(); + pt[2] = fOrigin[2] - fDZ + 2 * fDZ * gRandom->Rndm(); igen++; - if (Contains(pt)) iin++; + if (Contains(pt)) + iin++; } - Double_t capacity = iin*vbox/igen; + Double_t capacity = iin * vbox / igen; return capacity; } @@ -304,7 +304,8 @@ Double_t TGeoCompositeShape::Capacity() const void TGeoCompositeShape::ComputeBBox() { - if(fNode) fNode->ComputeBBox(fDX, fDY, fDZ, fOrigin); + if (fNode) + fNode->ComputeBBox(fDX, fDY, fDZ, fOrigin); } //////////////////////////////////////////////////////////////////////////////// @@ -312,7 +313,8 @@ void TGeoCompositeShape::ComputeBBox() void TGeoCompositeShape::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - if (fNode) fNode->ComputeNormal(point,dir,norm); + if (fNode) + fNode->ComputeNormal(point, dir, norm); } //////////////////////////////////////////////////////////////////////////////// @@ -320,7 +322,8 @@ void TGeoCompositeShape::ComputeNormal(const Double_t *point, const Double_t *di Bool_t TGeoCompositeShape::Contains(const Double_t *point) const { - if (fNode) return fNode->Contains(point); + if (fNode) + return fNode->Contains(point); return kFALSE; } @@ -337,29 +340,32 @@ Int_t TGeoCompositeShape::DistancetoPrimitive(Int_t px, Int_t py) /// Compute distance from outside point to this composite shape. /// Check if the bounding box is crossed within the requested distance -Double_t TGeoCompositeShape::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoCompositeShape::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); - if (fNode) return fNode->DistFromOutside(point, dir, iact, step, safe); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); + if (fNode) + return fNode->DistFromOutside(point, dir, iact, step, safe); return TGeoShape::Big(); } //////////////////////////////////////////////////////////////////////////////// /// Compute distance from inside point to outside of this composite shape. -Double_t TGeoCompositeShape::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, - Double_t step, Double_t *safe) const +Double_t TGeoCompositeShape::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (fNode) return fNode->DistFromInside(point, dir, iact, step, safe); + if (fNode) + return fNode->DistFromInside(point, dir, iact, step, safe); return TGeoShape::Big(); } //////////////////////////////////////////////////////////////////////////////// /// Divide all range of iaxis in range/step cells -TGeoVolume *TGeoCompositeShape::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, Int_t /*iaxis*/, +TGeoVolume *TGeoCompositeShape::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, Int_t /*iaxis*/, Int_t /*ndiv*/, Double_t /*start*/, Double_t /*step*/) { Error("Divide", "Composite shapes cannot be divided"); @@ -393,13 +399,14 @@ void TGeoCompositeShape::InspectShape() const void TGeoCompositeShape::MakeNode(const char *expression) { - if (fNode) delete fNode; + if (fNode) + delete fNode; fNode = 0; SetTitle(expression); TString sleft, sright, smat; Int_t boolop; boolop = TGeoManager::Parse(expression, sleft, sright, smat); - if (boolop<0) { + if (boolop < 0) { // fail Error("MakeNode", "parser error"); return; @@ -407,17 +414,10 @@ void TGeoCompositeShape::MakeNode(const char *expression) if (smat.Length()) Warning("MakeNode", "no geometrical transformation allowed at this level"); switch (boolop) { - case 0: - Error("MakeNode", "Expression has no boolean operation"); - return; - case 1: - fNode = new TGeoUnion(sleft.Data(), sright.Data()); - return; - case 2: - fNode = new TGeoSubtraction(sleft.Data(), sright.Data()); - return; - case 3: - fNode = new TGeoIntersection(sleft.Data(), sright.Data()); + case 0: Error("MakeNode", "Expression has no boolean operation"); return; + case 1: fNode = new TGeoUnion(sleft.Data(), sright.Data()); return; + case 2: fNode = new TGeoSubtraction(sleft.Data(), sright.Data()); return; + case 3: fNode = new TGeoIntersection(sleft.Data(), sright.Data()); } } @@ -431,17 +431,18 @@ Bool_t TGeoCompositeShape::PaintComposite(Option_t *option) const Bool_t addChildren = kTRUE; TVirtualGeoPainter *painter = gGeoManager->GetGeomPainter(); - TVirtualViewer3D * viewer = gPad->GetViewer3D(); - if (!painter || !viewer) return kFALSE; + TVirtualViewer3D *viewer = gPad->GetViewer3D(); + if (!painter || !viewer) + return kFALSE; if (fNode) { // Fill out the buffer for the composite shape - nothing extra // over TGeoBBox Bool_t preferLocal = viewer->PreferLocalFrame(); - if (TBuffer3D::GetCSLevel()) preferLocal = kFALSE; + if (TBuffer3D::GetCSLevel()) + preferLocal = kFALSE; static TBuffer3D buffer(TBuffer3DTypes::kComposite); - FillBuffer3D(buffer, TBuffer3D::kCore|TBuffer3D::kBoundingBox, - preferLocal); + FillBuffer3D(buffer, TBuffer3D::kCore | TBuffer3D::kBoundingBox, preferLocal); Bool_t paintComponents = kTRUE; @@ -452,11 +453,14 @@ Bool_t TGeoCompositeShape::PaintComposite(Option_t *option) const TBuffer3D::IncCSLevel(); // Paint the boolean node - will add more buffers to viewer - TGeoHMatrix *matrix = (TGeoHMatrix*)TGeoShape::GetTransform(); + TGeoHMatrix *matrix = (TGeoHMatrix *)TGeoShape::GetTransform(); TGeoHMatrix backup(*matrix); - if (preferLocal) matrix->Clear(); - if (paintComponents) fNode->Paint(option); - if (preferLocal) *matrix = backup; + if (preferLocal) + matrix->Clear(); + if (paintComponents) + fNode->Paint(option); + if (preferLocal) + *matrix = backup; // Close the composite shape if (!TBuffer3D::DecCSLevel()) viewer->CloseComposite(); @@ -470,26 +474,29 @@ Bool_t TGeoCompositeShape::PaintComposite(Option_t *option) const void TGeoCompositeShape::RegisterYourself() { - if (gGeoManager->GetListOfShapes()->FindObject(this)) return; + if (gGeoManager->GetListOfShapes()->FindObject(this)) + return; gGeoManager->AddShape(this); TGeoMatrix *matrix; - TGeoShape *shape; + TGeoShape *shape; TGeoCompositeShape *comp; if (fNode) { matrix = fNode->GetLeftMatrix(); - if (!matrix->IsRegistered()) matrix->RegisterYourself(); + if (!matrix->IsRegistered()) + matrix->RegisterYourself(); else if (!gGeoManager->GetListOfMatrices()->FindObject(matrix)) { gGeoManager->GetListOfMatrices()->Add(matrix); } matrix = fNode->GetRightMatrix(); - if (!matrix->IsRegistered()) matrix->RegisterYourself(); + if (!matrix->IsRegistered()) + matrix->RegisterYourself(); else if (!gGeoManager->GetListOfMatrices()->FindObject(matrix)) { gGeoManager->GetListOfMatrices()->Add(matrix); } shape = fNode->GetLeftShape(); if (!gGeoManager->GetListOfShapes()->FindObject(shape)) { if (shape->IsComposite()) { - comp = (TGeoCompositeShape*)shape; + comp = (TGeoCompositeShape *)shape; comp->RegisterYourself(); } else { gGeoManager->AddShape(shape); @@ -498,7 +505,7 @@ void TGeoCompositeShape::RegisterYourself() shape = fNode->GetRightShape(); if (!gGeoManager->GetListOfShapes()->FindObject(shape)) { if (shape->IsComposite()) { - comp = (TGeoCompositeShape*)shape; + comp = (TGeoCompositeShape *)shape; comp->RegisterYourself(); } else { gGeoManager->AddShape(shape); @@ -513,7 +520,8 @@ void TGeoCompositeShape::RegisterYourself() Double_t TGeoCompositeShape::Safety(const Double_t *point, Bool_t in) const { - if (fNode) return fNode->Safety(point,in); + if (fNode) + return fNode->Safety(point, in); return 0.; } @@ -522,11 +530,15 @@ Double_t TGeoCompositeShape::Safety(const Double_t *point, Bool_t in) const void TGeoCompositeShape::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; - if (fNode) fNode->SavePrimitive(out,option); + if (TObject::TestBit(kGeoSavePrimitive)) + return; + if (fNode) + fNode->SavePrimitive(out, option); out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoCompositeShape(\"" << GetName() << "\", pBoolNode);" << std::endl; - if (strlen(GetTitle())) out << " " << GetPointerName() << "->SetTitle(\"" << GetTitle() << "\");" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoCompositeShape(\"" << GetName() << "\", pBoolNode);" + << std::endl; + if (strlen(GetTitle())) + out << " " << GetPointerName() << "->SetTitle(\"" << GetTitle() << "\");" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -535,7 +547,8 @@ void TGeoCompositeShape::SavePrimitive(std::ostream &out, Option_t *option /*= " void TGeoCompositeShape::SetPoints(Double_t *points) const { - if (fNode) fNode->SetPoints(points); + if (fNode) + fNode->SetPoints(points); } //////////////////////////////////////////////////////////////////////////////// @@ -543,7 +556,8 @@ void TGeoCompositeShape::SetPoints(Double_t *points) const void TGeoCompositeShape::SetPoints(Float_t *points) const { - if (fNode) fNode->SetPoints(points); + if (fNode) + fNode->SetPoints(points); } //////////////////////////////////////////////////////////////////////////////// @@ -551,7 +565,8 @@ void TGeoCompositeShape::SetPoints(Float_t *points) const void TGeoCompositeShape::Sizeof3D() const { - if (fNode) fNode->Sizeof3D(); + if (fNode) + fNode->Sizeof3D(); } //////////////////////////////////////////////////////////////////////////////// @@ -559,7 +574,8 @@ void TGeoCompositeShape::Sizeof3D() const Int_t TGeoCompositeShape::GetNmeshVertices() const { - if (!fNode) return 0; + if (!fNode) + return 0; return fNode->GetNpoints(); } @@ -570,7 +586,8 @@ Int_t TGeoCompositeShape::GetNmeshVertices() const void TGeoCompositeShape::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iSetBoxDimensions(TMath::Max(fRmax1, fRmax2), TMath::Max(fRmax1, fRmax2), fDz); - memset(fOrigin, 0, 3*sizeof(Double_t)); + memset(fOrigin, 0, 3 * sizeof(Double_t)); } //////////////////////////////////////////////////////////////////////////////// @@ -196,38 +190,38 @@ void TGeoCone::ComputeBBox() void TGeoCone::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - Double_t safr,safe,phi; - memset(norm,0,3*sizeof(Double_t)); - phi = TMath::ATan2(point[1],point[0]); + Double_t safr, safe, phi; + memset(norm, 0, 3 * sizeof(Double_t)); + phi = TMath::ATan2(point[1], point[0]); Double_t cphi = TMath::Cos(phi); Double_t sphi = TMath::Sin(phi); - Double_t ro1 = 0.5*(fRmin1+fRmin2); - Double_t tg1 = 0.5*(fRmin2-fRmin1)/fDz; - Double_t cr1 = 1./TMath::Sqrt(1.+tg1*tg1); - Double_t ro2 = 0.5*(fRmax1+fRmax2); - Double_t tg2 = 0.5*(fRmax2-fRmax1)/fDz; - Double_t cr2 = 1./TMath::Sqrt(1.+tg2*tg2); - - Double_t r=TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Double_t rin = tg1*point[2]+ro1; - Double_t rout = tg2*point[2]+ro2; - safe = TMath::Abs(fDz-TMath::Abs(point[2])); + Double_t ro1 = 0.5 * (fRmin1 + fRmin2); + Double_t tg1 = 0.5 * (fRmin2 - fRmin1) / fDz; + Double_t cr1 = 1. / TMath::Sqrt(1. + tg1 * tg1); + Double_t ro2 = 0.5 * (fRmax1 + fRmax2); + Double_t tg2 = 0.5 * (fRmax2 - fRmax1) / fDz; + Double_t cr2 = 1. / TMath::Sqrt(1. + tg2 * tg2); + + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t rin = tg1 * point[2] + ro1; + Double_t rout = tg2 * point[2] + ro2; + safe = TMath::Abs(fDz - TMath::Abs(point[2])); norm[2] = 1; - safr = (ro1>0)?(TMath::Abs((r-rin)*cr1)):TGeoShape::Big(); - if (safr 0) ? (TMath::Abs((r - rin) * cr1)) : TGeoShape::Big(); + if (safr < safe) { safe = safr; - norm[0] = cr1*cphi; - norm[1] = cr1*sphi; - norm[2] = -tg1*cr1; + norm[0] = cr1 * cphi; + norm[1] = cr1 * sphi; + norm[2] = -tg1 * cr1; } - safr = TMath::Abs((rout-r)*cr2); - if (safr0)?(TMath::Abs((r-rin)*cr1)):TGeoShape::Big(); - norm[0] = cr1*cphi; - norm[1] = cr1*sphi; - norm[2] = -tg1*cr1; - if (TMath::Abs((rout-r)*cr2) 0) ? (TMath::Abs((r - rin) * cr1)) : TGeoShape::Big(); + norm[0] = cr1 * cphi; + norm[1] = cr1 * sphi; + norm[2] = -tg1 * cr1; + if (TMath::Abs((rout - r) * cr2) < safe) { + norm[0] = cr2 * cphi; + norm[1] = cr2 * sphi; + norm[2] = -tg2 * cr2; + } + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -276,11 +270,13 @@ void TGeoCone::ComputeNormalS(const Double_t *point, const Double_t *dir, Double Bool_t TGeoCone::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fDz) return kFALSE; - Double_t r2 = point[0]*point[0]+point[1]*point[1]; - Double_t rl = 0.5*(fRmin2*(point[2]+fDz)+fRmin1*(fDz-point[2]))/fDz; - Double_t rh = 0.5*(fRmax2*(point[2]+fDz)+fRmax1*(fDz-point[2]))/fDz; - if ((r2rh*rh)) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; + Double_t r2 = point[0] * point[0] + point[1] * point[1]; + Double_t rl = 0.5 * (fRmin2 * (point[2] + fDz) + fRmin1 * (fDz - point[2])) / fDz; + Double_t rh = 0.5 * (fRmax2 * (point[2] + fDz) + fRmax1 * (fDz - point[2])) / fDz; + if ((r2 < rl * rl) || (r2 > rh * rh)) + return kFALSE; return kTRUE; } @@ -288,68 +284,81 @@ Bool_t TGeoCone::Contains(const Double_t *point) const /// Compute distance from inside point to surface of the cone (static) /// Boundary safe algorithm. -Double_t TGeoCone::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2) +Double_t TGeoCone::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2) { - if (dz<=0) return TGeoShape::Big(); + if (dz <= 0) + return TGeoShape::Big(); // compute distance to surface // Do Z Double_t sz = TGeoShape::Big(); if (dir[2]) { - sz = (TMath::Sign(dz, dir[2])-point[2])/dir[2]; - if (sz<=0) return 0.0; + sz = (TMath::Sign(dz, dir[2]) - point[2]) / dir[2]; + if (sz <= 0) + return 0.0; } - Double_t rsq=point[0]*point[0]+point[1]*point[1]; - Double_t zinv = 1./dz; - Double_t rin = 0.5*(rmin1+rmin2+(rmin2-rmin1)*point[2]*zinv); + Double_t rsq = point[0] * point[0] + point[1] * point[1]; + Double_t zinv = 1. / dz; + Double_t rin = 0.5 * (rmin1 + rmin2 + (rmin2 - rmin1) * point[2] * zinv); // Do Rmin - Double_t b,delta,zi; - if (rin>0) { + Double_t b, delta, zi; + if (rin > 0) { // Protection in case point is actually outside the cone - if (rsq < rin*(rin+TGeoShape::Tolerance())) { - Double_t ddotn = point[0]*dir[0]+point[1]*dir[1]+0.5*(rmin1-rmin2)*dir[2]*zinv*TMath::Sqrt(rsq); - if (ddotn<=0) return 0.0; + if (rsq < rin * (rin + TGeoShape::Tolerance())) { + Double_t ddotn = + point[0] * dir[0] + point[1] * dir[1] + 0.5 * (rmin1 - rmin2) * dir[2] * zinv * TMath::Sqrt(rsq); + if (ddotn <= 0) + return 0.0; } else { TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta>0) { - Double_t sr = -b-delta; - if (sr>0) { - zi = point[2]+sr*dir[2]; - if (TMath::Abs(zi)<=dz) return TMath::Min(sz,sr); + if (delta > 0) { + Double_t sr = -b - delta; + if (sr > 0) { + zi = point[2] + sr * dir[2]; + if (TMath::Abs(zi) <= dz) + return TMath::Min(sz, sr); } - sr = -b+delta; - if (sr>0) { - zi = point[2]+sr*dir[2]; - if (TMath::Abs(zi)<=dz) return TMath::Min(sz,sr); + sr = -b + delta; + if (sr > 0) { + zi = point[2] + sr * dir[2]; + if (TMath::Abs(zi) <= dz) + return TMath::Min(sz, sr); } } } } // Do Rmax - Double_t rout = 0.5*(rmax1+rmax2+(rmax2-rmax1)*point[2]*zinv); - if (rsq > rout*(rout-TGeoShape::Tolerance())) { - Double_t ddotn = point[0]*dir[0]+point[1]*dir[1]+0.5*(rmax1-rmax2)*dir[2]*zinv*TMath::Sqrt(rsq); - if (ddotn>=0) return 0.0; + Double_t rout = 0.5 * (rmax1 + rmax2 + (rmax2 - rmax1) * point[2] * zinv); + if (rsq > rout * (rout - TGeoShape::Tolerance())) { + Double_t ddotn = point[0] * dir[0] + point[1] * dir[1] + 0.5 * (rmax1 - rmax2) * dir[2] * zinv * TMath::Sqrt(rsq); + if (ddotn >= 0) + return 0.0; TGeoCone::DistToCone(point, dir, dz, rmax1, rmax2, b, delta); - if (delta<0) return 0.0; - Double_t sr = -b+delta; - if (sr<0) return sz; - if (TMath::Abs(-b-delta)>sr) return sz; - zi = point[2]+sr*dir[2]; - if (TMath::Abs(zi)<=dz) return TMath::Min(sz,sr); + if (delta < 0) + return 0.0; + Double_t sr = -b + delta; + if (sr < 0) + return sz; + if (TMath::Abs(-b - delta) > sr) + return sz; + zi = point[2] + sr * dir[2]; + if (TMath::Abs(zi) <= dz) + return TMath::Min(sz, sr); return sz; } TGeoCone::DistToCone(point, dir, dz, rmax1, rmax2, b, delta); - if (delta>0) { - Double_t sr = -b-delta; - if (sr>0) { - zi = point[2]+sr*dir[2]; - if (TMath::Abs(zi)<=dz) return TMath::Min(sz,sr); + if (delta > 0) { + Double_t sr = -b - delta; + if (sr > 0) { + zi = point[2] + sr * dir[2]; + if (TMath::Abs(zi) <= dz) + return TMath::Min(sz, sr); } - sr = -b+delta; - if (sr>TGeoShape::Tolerance()) { - zi = point[2]+sr*dir[2]; - if (TMath::Abs(zi)<=dz) return TMath::Min(sz,sr); + sr = -b + delta; + if (sr > TGeoShape::Tolerance()) { + zi = point[2] + sr * dir[2]; + if (TMath::Abs(zi) <= dz) + return TMath::Min(sz, sr); } } return sz; @@ -359,12 +368,15 @@ Double_t TGeoCone::DistFromInsideS(const Double_t *point, const Double_t *dir, D /// Compute distance from inside point to surface of the cone /// Boundary safe algorithm. -Double_t TGeoCone::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoCone::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // compute distance to surface return TGeoCone::DistFromInsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2); @@ -374,83 +386,97 @@ Double_t TGeoCone::DistFromInside(const Double_t *point, const Double_t *dir, In /// Compute distance from outside point to surface of the tube /// Boundary safe algorithm. -Double_t TGeoCone::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2) +Double_t TGeoCone::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2) { // compute distance to Z planes - if (dz<=0) return TGeoShape::Big(); + if (dz <= 0) + return TGeoShape::Big(); Double_t snxt; Double_t xp, yp, zp; Bool_t inz = kTRUE; - if (point[2]<=-dz) { - if (dir[2]<=0) return TGeoShape::Big(); - snxt = (-dz-point[2])/dir[2]; - xp = point[0]+snxt*dir[0]; - yp = point[1]+snxt*dir[1]; - Double_t r2 = xp*xp+yp*yp; - if ((r2>=rmin1*rmin1) && (r2<=rmax1*rmax1)) return snxt; + if (point[2] <= -dz) { + if (dir[2] <= 0) + return TGeoShape::Big(); + snxt = (-dz - point[2]) / dir[2]; + xp = point[0] + snxt * dir[0]; + yp = point[1] + snxt * dir[1]; + Double_t r2 = xp * xp + yp * yp; + if ((r2 >= rmin1 * rmin1) && (r2 <= rmax1 * rmax1)) + return snxt; inz = kFALSE; } else { - if (point[2]>=dz) { - if (dir[2]>=0) return TGeoShape::Big(); - snxt = (dz-point[2])/dir[2]; - xp = point[0]+snxt*dir[0]; - yp = point[1]+snxt*dir[1]; - Double_t r2 = xp*xp+yp*yp; - if ((r2>=rmin2*rmin2) && (r2<=rmax2*rmax2)) return snxt; + if (point[2] >= dz) { + if (dir[2] >= 0) + return TGeoShape::Big(); + snxt = (dz - point[2]) / dir[2]; + xp = point[0] + snxt * dir[0]; + yp = point[1] + snxt * dir[1]; + Double_t r2 = xp * xp + yp * yp; + if ((r2 >= rmin2 * rmin2) && (r2 <= rmax2 * rmax2)) + return snxt; inz = kFALSE; } } - Double_t rsq = point[0]*point[0]+point[1]*point[1]; - Double_t dzinv = 1./dz; - Double_t ro1=0.5*(rmin1+rmin2); - Bool_t hasrmin = (ro1>0)?kTRUE:kFALSE; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; + Double_t dzinv = 1. / dz; + Double_t ro1 = 0.5 * (rmin1 + rmin2); + Bool_t hasrmin = (ro1 > 0) ? kTRUE : kFALSE; Double_t tg1 = 0.; Double_t rin = 0.; - Bool_t inrmin = kTRUE; // r>=rmin + Bool_t inrmin = kTRUE; // r>=rmin if (hasrmin) { - tg1=0.5*(rmin2-rmin1)*dzinv; - rin=ro1+tg1*point[2]; - if (rin>0 && rsq 0 && rsq < rin * (rin - TGeoShape::Tolerance())) + inrmin = kFALSE; + } + Double_t ro2 = 0.5 * (rmax1 + rmax2); + Double_t tg2 = 0.5 * (rmax2 - rmax1) * dzinv; + Double_t rout = tg2 * point[2] + ro2; Bool_t inrmax = kFALSE; - if (rout>0 && rsq 0 && rsq < rout * (rout + TGeoShape::Tolerance())) + inrmax = kTRUE; Bool_t in = inz & inrmin & inrmax; - Double_t b,delta; + Double_t b, delta; // If inside cone, we are most likely on a boundary within machine precision. if (in) { - Double_t r=TMath::Sqrt(rsq); - Double_t safz = dz-TMath::Abs(point[2]); // positive - Double_t safrmin = (hasrmin)?(r-rin):TGeoShape::Big(); + Double_t r = TMath::Sqrt(rsq); + Double_t safz = dz - TMath::Abs(point[2]); // positive + Double_t safrmin = (hasrmin) ? (r - rin) : TGeoShape::Big(); Double_t safrmax = rout - r; - if (safz<=safrmin && safz<=safrmax) { + if (safz <= safrmin && safz <= safrmax) { // on Z boundary - if (point[2]*dir[2]<0) return 0.0; + if (point[2] * dir[2] < 0) + return 0.0; return TGeoShape::Big(); } - if (safrmax=0) return 0.0; + Double_t ddotn = point[0] * dir[0] + point[1] * dir[1] - tg1 * dir[2] * r; + if (ddotn >= 0) + return 0.0; // we can cross (+) solution of rmin TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta<0) return 0.0; - snxt = -b+delta; - if (snxt<0) return TGeoShape::Big(); - if (TMath::Abs(-b-delta)>snxt) return TGeoShape::Big(); - zp = point[2]+snxt*dir[2]; - if (TMath::Abs(zp)<=dz) return snxt; + if (delta < 0) + return 0.0; + snxt = -b + delta; + if (snxt < 0) + return TGeoShape::Big(); + if (TMath::Abs(-b - delta) > snxt) + return TGeoShape::Big(); + zp = point[2] + snxt * dir[2]; + if (TMath::Abs(zp) <= dz) + return snxt; return TGeoShape::Big(); } @@ -459,62 +485,75 @@ Double_t TGeoCone::DistFromOutsideS(const Double_t *point, const Double_t *dir, if (!inrmin) { // ray can cross inner cone (but not only!) TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta<0) return TGeoShape::Big(); - snxt = -b+delta; - if (snxt>0) { - zp = point[2]+snxt*dir[2]; - if (TMath::Abs(zp)<=dz) return snxt; + if (delta < 0) + return TGeoShape::Big(); + snxt = -b + delta; + if (snxt > 0) { + zp = point[2] + snxt * dir[2]; + if (TMath::Abs(zp) <= dz) + return snxt; } - snxt = -b-delta; - if (snxt>0) { - zp = point[2]+snxt*dir[2]; - if (TMath::Abs(zp)<=dz) return snxt; + snxt = -b - delta; + if (snxt > 0) { + zp = point[2] + snxt * dir[2]; + if (TMath::Abs(zp) <= dz) + return snxt; } snxt = TGeoShape::Big(); } else { if (hasrmin) { TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta>0) { - Double_t din = -b+delta; - if (din>0) { - zp = point[2]+din*dir[2]; - if (TMath::Abs(zp)<=dz) snxt = din; + if (delta > 0) { + Double_t din = -b + delta; + if (din > 0) { + zp = point[2] + din * dir[2]; + if (TMath::Abs(zp) <= dz) + snxt = din; } } } } - if (inrmax) return snxt; + if (inrmax) + return snxt; // We can cross outer cone, both solutions possible // compute distance to outer cone TGeoCone::DistToCone(point, dir, dz, rmax1, rmax2, b, delta); - if (delta<0) return snxt; - Double_t dout = -b-delta; - if (dout>0 && doutsnxt) return snxt; - zp = point[2]+dout*dir[2]; - if (TMath::Abs(zp)<=dz) return dout; + if (delta < 0) + return snxt; + Double_t dout = -b - delta; + if (dout > 0 && dout < snxt) { + zp = point[2] + dout * dir[2]; + if (TMath::Abs(zp) <= dz) + return dout; + } + dout = -b + delta; + if (dout <= 0 || dout > snxt) + return snxt; + zp = point[2] + dout * dir[2]; + if (TMath::Abs(zp) <= dz) + return dout; return snxt; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the tube -Double_t TGeoCone::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoCone::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { // compute safe radius - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); // compute distance to Z planes return TGeoCone::DistFromOutsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2); } @@ -525,31 +564,33 @@ Double_t TGeoCone::DistFromOutside(const Double_t *point, const Double_t *dir, I /// - r2, z2 - radius and Z position of upper base void TGeoCone::DistToCone(const Double_t *point, const Double_t *dir, Double_t dz, Double_t r1, Double_t r2, - Double_t &b, Double_t &delta) + Double_t &b, Double_t &delta) { b = 0; delta = -1.; - if (dz<0) return; - Double_t ro0 = 0.5*(r1+r2); - Double_t tz = 0.5*(r2-r1)/dz; - Double_t rsq = point[0]*point[0] + point[1]*point[1]; - Double_t rc = ro0 + point[2]*tz; - - Double_t a = dir[0]*dir[0] + dir[1]*dir[1] - tz*tz*dir[2]*dir[2]; - b = point[0]*dir[0] + point[1]*dir[1] - tz*rc*dir[2]; - Double_t c = rsq - rc*rc; - - if (TMath::Abs(a)0) { + delta = b * b - c; + if (delta > 0) { delta = TMath::Sqrt(delta); } else { delta = -1.; @@ -562,7 +603,7 @@ void TGeoCone::DistToCone(const Double_t *point, const Double_t *dir, Double_t d Int_t TGeoCone::DistancetoPrimitive(Int_t px, Int_t py) { Int_t n = gGeoManager->GetNsegments(); - const Int_t numPoints = 4*n; + const Int_t numPoints = 4 * n; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -574,57 +615,55 @@ Int_t TGeoCone::DistancetoPrimitive(Int_t px, Int_t py) /// was divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoCone::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoCone::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- R division - Error("Divide","division of a cone on R not implemented"); - return 0; - case 2: // --- Phi division - finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoConeSeg(fDz, fRmin1, fRmax1, fRmin2, fRmax2, -step/2, step/2); + case 1: //--- R division + Error("Divide", "division of a cone on R not implemented"); + return 0; + case 2: // --- Phi division + finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoConeSeg(fDz, fRmin1, fRmax1, fRmin2, fRmax2, -step / 2, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Z division + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + Double_t z1 = start + id * step; + Double_t z2 = start + (id + 1) * step; + Double_t rmin1n = 0.5 * (fRmin1 * (fDz - z1) + fRmin2 * (fDz + z1)) / fDz; + Double_t rmax1n = 0.5 * (fRmax1 * (fDz - z1) + fRmax2 * (fDz + z1)) / fDz; + Double_t rmin2n = 0.5 * (fRmin1 * (fDz - z2) + fRmin2 * (fDz + z2)) / fDz; + Double_t rmax2n = 0.5 * (fRmax1 * (fDz - z2) + fRmax2 * (fDz + z2)) / fDz; + shape = new TGeoCone(0.5 * step, rmin1n, rmax1n, rmin2n, rmax2n); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Z division - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "Z"; - voldiv->AddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + opt = "Z"; + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "Wrong axis type for division"); return 0; } } @@ -634,14 +673,10 @@ TGeoVolume *TGeoCone::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi const char *TGeoCone::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "R"; - case 2: - return "PHI"; - case 3: - return "Z"; - default: - return "undefined"; + case 1: return "R"; + case 2: return "PHI"; + case 3: return "Z"; + default: return "undefined"; } } @@ -654,15 +689,15 @@ Double_t TGeoCone::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 2: - xlo = 0.; - xhi = 360.; - return 360.; - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 2: + xlo = 0.; + xhi = 360.; + return 360.; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -677,8 +712,8 @@ void TGeoCone::GetBoundingCylinder(Double_t *param) const param[0] *= param[0]; param[1] = TMath::Max(fRmax1, fRmax2); // Rmax param[1] *= param[1]; - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -687,7 +722,8 @@ void TGeoCone::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoCone::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoCone)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; @@ -698,15 +734,16 @@ TGeoShape *TGeoCone::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/ rmin2 = fRmin2; rmax2 = fRmax2; dz = fDz; - if (fDz<0) dz=((TGeoCone*)mother)->GetDz(); - if (fRmin1<0) - rmin1 = ((TGeoCone*)mother)->GetRmin1(); - if (fRmax1<0) - rmax1 = ((TGeoCone*)mother)->GetRmax1(); - if (fRmin2<0) - rmin2 = ((TGeoCone*)mother)->GetRmin2(); - if (fRmax2<0) - rmax2 = ((TGeoCone*)mother)->GetRmax2(); + if (fDz < 0) + dz = ((TGeoCone *)mother)->GetDz(); + if (fRmin1 < 0) + rmin1 = ((TGeoCone *)mother)->GetRmin1(); + if (fRmax1 < 0) + rmax1 = ((TGeoCone *)mother)->GetRmax1(); + if (fRmin2 < 0) + rmin2 = ((TGeoCone *)mother)->GetRmin2(); + if (fRmax2 < 0) + rmax2 = ((TGeoCone *)mother)->GetRmax2(); return (new TGeoCone(GetName(), dz, rmin1, rmax1, rmin2, rmax2)); } @@ -718,34 +755,40 @@ TGeoShape *TGeoCone::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/ Bool_t TGeoCone::GetPointsOnSegments(Int_t npoints, Double_t *array) const { - if (npoints > (npoints/2)*2) { - Error("GetPointsOnSegments","Npoints must be even number"); + if (npoints > (npoints / 2) * 2) { + Error("GetPointsOnSegments", "Npoints must be even number"); return kFALSE; } - Bool_t hasrmin = (fRmin1>0 || fRmin2>0)?kTRUE:kFALSE; + Bool_t hasrmin = (fRmin1 > 0 || fRmin2 > 0) ? kTRUE : kFALSE; Int_t nc = 0; - if (hasrmin) nc = (Int_t)TMath::Sqrt(0.5*npoints); - else nc = (Int_t)TMath::Sqrt(1.*npoints); - Double_t dphi = TMath::TwoPi()/nc; + if (hasrmin) + nc = (Int_t)TMath::Sqrt(0.5 * npoints); + else + nc = (Int_t)TMath::Sqrt(1. * npoints); + Double_t dphi = TMath::TwoPi() / nc; Double_t phi = 0; Int_t ntop = 0; - if (hasrmin) ntop = npoints/2 - nc*(nc-1); - else ntop = npoints - nc*(nc-1); - Double_t dz = 2*fDz/(nc-1); + if (hasrmin) + ntop = npoints / 2 - nc * (nc - 1); + else + ntop = npoints - nc * (nc - 1); + Double_t dz = 2 * fDz / (nc - 1); Double_t z = 0; Int_t icrt = 0; Int_t nphi = nc; Double_t rmin = 0.; Double_t rmax = 0.; // loop z sections - for (Int_t i=0; iGetNsegments(); - Int_t nbPnts = 4*n; - Int_t nbSegs = 8*n; - Int_t nbPols = 4*n; - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, - nbSegs, 3*nbSegs, - nbPols, 6*nbPols); - - if (buff) - { + Int_t nbPnts = 4 * n; + Int_t nbSegs = 8 * n; + Int_t nbPols = 4 * n; + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -803,78 +842,78 @@ TBuffer3D *TGeoCone::MakeBuffer3D() const void TGeoCone::SetSegsAndPols(TBuffer3D &buffer) const { - Int_t i,j; + Int_t i, j; Int_t n = gGeoManager->GetNsegments(); Int_t c = GetBasicColor(); for (i = 0; i < 4; i++) { for (j = 0; j < n; j++) { - buffer.fSegs[(i*n+j)*3 ] = c; - buffer.fSegs[(i*n+j)*3+1] = i*n+j; - buffer.fSegs[(i*n+j)*3+2] = i*n+j+1; + buffer.fSegs[(i * n + j) * 3] = c; + buffer.fSegs[(i * n + j) * 3 + 1] = i * n + j; + buffer.fSegs[(i * n + j) * 3 + 2] = i * n + j + 1; } - buffer.fSegs[(i*n+j-1)*3+2] = i*n; + buffer.fSegs[(i * n + j - 1) * 3 + 2] = i * n; } for (i = 4; i < 6; i++) { for (j = 0; j < n; j++) { - buffer.fSegs[(i*n+j)*3 ] = c+1; - buffer.fSegs[(i*n+j)*3+1] = (i-4)*n+j; - buffer.fSegs[(i*n+j)*3+2] = (i-2)*n+j; + buffer.fSegs[(i * n + j) * 3] = c + 1; + buffer.fSegs[(i * n + j) * 3 + 1] = (i - 4) * n + j; + buffer.fSegs[(i * n + j) * 3 + 2] = (i - 2) * n + j; } } for (i = 6; i < 8; i++) { for (j = 0; j < n; j++) { - buffer.fSegs[(i*n+j)*3 ] = c; - buffer.fSegs[(i*n+j)*3+1] = 2*(i-6)*n+j; - buffer.fSegs[(i*n+j)*3+2] = (2*(i-6)+1)*n+j; + buffer.fSegs[(i * n + j) * 3] = c; + buffer.fSegs[(i * n + j) * 3 + 1] = 2 * (i - 6) * n + j; + buffer.fSegs[(i * n + j) * 3 + 2] = (2 * (i - 6) + 1) * n + j; } } Int_t indx = 0; - i=0; + i = 0; for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+5] = i*n+j; - buffer.fPols[indx+4] = (4+i)*n+j; - buffer.fPols[indx+3] = (2+i)*n+j; - buffer.fPols[indx+2] = (4+i)*n+j+1; - } - buffer.fPols[indx+2] = (4+i)*n; - i=1; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 5] = i * n + j; + buffer.fPols[indx + 4] = (4 + i) * n + j; + buffer.fPols[indx + 3] = (2 + i) * n + j; + buffer.fPols[indx + 2] = (4 + i) * n + j + 1; + } + buffer.fPols[indx + 2] = (4 + i) * n; + i = 1; for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = i*n+j; - buffer.fPols[indx+3] = (4+i)*n+j; - buffer.fPols[indx+4] = (2+i)*n+j; - buffer.fPols[indx+5] = (4+i)*n+j+1; - } - buffer.fPols[indx+5] = (4+i)*n; - i=2; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = i * n + j; + buffer.fPols[indx + 3] = (4 + i) * n + j; + buffer.fPols[indx + 4] = (2 + i) * n + j; + buffer.fPols[indx + 5] = (4 + i) * n + j + 1; + } + buffer.fPols[indx + 5] = (4 + i) * n; + i = 2; for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c+i; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = (i-2)*2*n+j; - buffer.fPols[indx+3] = (4+i)*n+j; - buffer.fPols[indx+4] = ((i-2)*2+1)*n+j; - buffer.fPols[indx+5] = (4+i)*n+j+1; - } - buffer.fPols[indx+5] = (4+i)*n; - i=3; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c + i; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = (i - 2) * 2 * n + j; + buffer.fPols[indx + 3] = (4 + i) * n + j; + buffer.fPols[indx + 4] = ((i - 2) * 2 + 1) * n + j; + buffer.fPols[indx + 5] = (4 + i) * n + j + 1; + } + buffer.fPols[indx + 5] = (4 + i) * n; + i = 3; for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c+i; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+5] = (i-2)*2*n+j; - buffer.fPols[indx+4] = (4+i)*n+j; - buffer.fPols[indx+3] = ((i-2)*2+1)*n+j; - buffer.fPols[indx+2] = (4+i)*n+j+1; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c + i; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 5] = (i - 2) * 2 * n + j; + buffer.fPols[indx + 4] = (4 + i) * n + j; + buffer.fPols[indx + 3] = ((i - 2) * 2 + 1) * n + j; + buffer.fPols[indx + 2] = (4 + i) * n + j + 1; } - buffer.fPols[indx+2] = (4+i)*n; + buffer.fPols[indx + 2] = (4 + i) * n; } //////////////////////////////////////////////////////////////////////////////// @@ -884,13 +923,14 @@ void TGeoCone::SetSegsAndPols(TBuffer3D &buffer) const Double_t TGeoCone::Safety(const Double_t *point, Bool_t in) const { Double_t saf[4]; - Double_t r=TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - saf[0] = TGeoShape::SafetySeg(r,point[2], fRmin1, -fDz, fRmax1, -fDz, !in); - saf[1] = TGeoShape::SafetySeg(r,point[2], fRmax2, fDz, fRmin2, fDz, !in); - saf[2] = TGeoShape::SafetySeg(r,point[2], fRmin2, fDz, fRmin1, -fDz, !in); - saf[3] = TGeoShape::SafetySeg(r,point[2], fRmax1, -fDz, fRmax2, fDz, !in); - Double_t safety = saf[TMath::LocMin(4,saf)]; - if (safety>1.E20) safety = 0.; + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + saf[0] = TGeoShape::SafetySeg(r, point[2], fRmin1, -fDz, fRmax1, -fDz, !in); + saf[1] = TGeoShape::SafetySeg(r, point[2], fRmax2, fDz, fRmin2, fDz, !in); + saf[2] = TGeoShape::SafetySeg(r, point[2], fRmin2, fDz, fRmin1, -fDz, !in); + saf[3] = TGeoShape::SafetySeg(r, point[2], fRmax1, -fDz, fRmax2, fDz, !in); + Double_t safety = saf[TMath::LocMin(4, saf)]; + if (safety > 1.E20) + safety = 0.; return safety; } @@ -902,32 +942,32 @@ Double_t TGeoCone::SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double Double_t rmin2, Double_t rmax2, Int_t skipz) { Double_t saf[4]; - Double_t r=TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); -// Double_t rin = tg1*point[2]+ro1; -// Double_t rout = tg2*point[2]+ro2; + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + // Double_t rin = tg1*point[2]+ro1; + // Double_t rout = tg2*point[2]+ro2; switch (skipz) { - case 1: // skip lower Z plane - saf[0] = TGeoShape::Big(); - saf[1] = TGeoShape::SafetySeg(r,point[2], rmax2, dz, rmin2, dz, !in); - break; - case 2: // skip upper Z plane - saf[0] = TGeoShape::SafetySeg(r,point[2], rmin1, -dz, rmax1, -dz, !in); - saf[1] = TGeoShape::Big(); - break; - case 3: // skip both - saf[0] = saf[1] = TGeoShape::Big(); - break; - default: - saf[0] = TGeoShape::SafetySeg(r,point[2], rmin1, -dz, rmax1, -dz, !in); - saf[1] = TGeoShape::SafetySeg(r,point[2], rmax2, dz, rmin2, dz, !in); + case 1: // skip lower Z plane + saf[0] = TGeoShape::Big(); + saf[1] = TGeoShape::SafetySeg(r, point[2], rmax2, dz, rmin2, dz, !in); + break; + case 2: // skip upper Z plane + saf[0] = TGeoShape::SafetySeg(r, point[2], rmin1, -dz, rmax1, -dz, !in); + saf[1] = TGeoShape::Big(); + break; + case 3: // skip both + saf[0] = saf[1] = TGeoShape::Big(); + break; + default: + saf[0] = TGeoShape::SafetySeg(r, point[2], rmin1, -dz, rmax1, -dz, !in); + saf[1] = TGeoShape::SafetySeg(r, point[2], rmax2, dz, rmin2, dz, !in); } // Safety to inner part - if (rmin1>0 || rmin2>0) - saf[2] = TGeoShape::SafetySeg(r,point[2], rmin2, dz, rmin1, -dz, !in); + if (rmin1 > 0 || rmin2 > 0) + saf[2] = TGeoShape::SafetySeg(r, point[2], rmin2, dz, rmin1, -dz, !in); else saf[2] = TGeoShape::Big(); - saf[3] = TGeoShape::SafetySeg(r,point[2], rmax1, -dz, rmax2, dz, !in); - return saf[TMath::LocMin(4,saf)]; + saf[3] = TGeoShape::SafetySeg(r, point[2], rmax1, -dz, rmax2, dz, !in); + return saf[TMath::LocMin(4, saf)]; } //////////////////////////////////////////////////////////////////////////////// @@ -935,27 +975,28 @@ Double_t TGeoCone::SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double void TGeoCone::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " rmin1 = " << fRmin1 << ";" << std::endl; out << " rmax1 = " << fRmax1 << ";" << std::endl; out << " rmin2 = " << fRmin2 << ";" << std::endl; out << " rmax2 = " << fRmax2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoCone(\"" << GetName() << "\", dz,rmin1,rmax1,rmin2,rmax2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoCone(\"" << GetName() + << "\", dz,rmin1,rmax1,rmin2,rmax2);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } //////////////////////////////////////////////////////////////////////////////// /// Set cone dimensions. -void TGeoCone::SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2) +void TGeoCone::SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2) { - if (rmin1>=0) { - if (rmax1>0) { - if (rmin1<=rmax1) { - // normal rmin/rmax + if (rmin1 >= 0) { + if (rmax1 > 0) { + if (rmin1 <= rmax1) { + // normal rmin/rmax fRmin1 = rmin1; fRmax1 = rmax1; } else { @@ -974,10 +1015,10 @@ void TGeoCone::SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, fRmin1 = rmin1; fRmax1 = rmax1; } - if (rmin2>=0) { - if (rmax2>0) { - if (rmin2<=rmax2) { - // normal rmin/rmax + if (rmin2 >= 0) { + if (rmax2 > 0) { + if (rmin2 <= rmax2) { + // normal rmin/rmax fRmin2 = rmin2; fRmax2 = rmax2; } else { @@ -997,7 +1038,7 @@ void TGeoCone::SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, fRmax2 = rmax2; } - fDz = dz; + fDz = dz; } //////////////////////////////////////////////////////////////////////////////// @@ -1005,7 +1046,7 @@ void TGeoCone::SetConeDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, void TGeoCone::SetDimensions(Double_t *param) { - Double_t dz = param[0]; + Double_t dz = param[0]; Double_t rmin1 = param[1]; Double_t rmax1 = param[2]; Double_t rmin2 = param[3]; @@ -1022,34 +1063,34 @@ void TGeoCone::SetPoints(Double_t *points) const Int_t j, n; n = gGeoManager->GetNsegments(); - dphi = 360./n; - dz = fDz; + dphi = 360. / n; + dz = fDz; Int_t indx = 0; if (points) { for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmin1 * TMath::Cos(phi); points[indx++] = fRmin1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmax1 * TMath::Cos(phi); points[indx++] = fRmax1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmin2 * TMath::Cos(phi); points[indx++] = fRmin2 * TMath::Sin(phi); points[indx++] = dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmax2 * TMath::Cos(phi); points[indx++] = fRmax2 * TMath::Sin(phi); points[indx++] = dz; @@ -1066,34 +1107,34 @@ void TGeoCone::SetPoints(Float_t *points) const Int_t j, n; n = gGeoManager->GetNsegments(); - dphi = 360./n; - dz = fDz; + dphi = 360. / n; + dz = fDz; Int_t indx = 0; if (points) { for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmin1 * TMath::Cos(phi); points[indx++] = fRmin1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmax1 * TMath::Cos(phi); points[indx++] = fRmax1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmin2 * TMath::Cos(phi); points[indx++] = fRmin2 * TMath::Sin(phi); points[indx++] = dz; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); + phi = j * dphi * TMath::DegToRad(); points[indx++] = fRmax2 * TMath::Cos(phi); points[indx++] = fRmax2 * TMath::Sin(phi); points[indx++] = dz; @@ -1107,9 +1148,9 @@ void TGeoCone::SetPoints(Float_t *points) const void TGeoCone::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { Int_t n = gGeoManager->GetNsegments(); - nvert = n*4; - nsegs = n*8; - npols = n*4; + nvert = n * 4; + nsegs = n * 8; + npols = n * 4; } //////////////////////////////////////////////////////////////////////////////// @@ -1118,21 +1159,19 @@ void TGeoCone::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoCone::GetNmeshVertices() const { Int_t n = gGeoManager->GetNsegments(); - Int_t numPoints = n*4; + Int_t numPoints = n * 4; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// Fill size of this 3-D object -void TGeoCone::Sizeof3D() const -{ -} +void TGeoCone::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoCone::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoCone::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); @@ -1140,10 +1179,10 @@ const TBuffer3D & TGeoCone::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co if (reqSections & TBuffer3D::kRawSizes) { Int_t n = gGeoManager->GetNsegments(); - Int_t nbPnts = 4*n; - Int_t nbSegs = 8*n; - Int_t nbPols = 4*n; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t nbPnts = 4 * n; + Int_t nbSegs = 8 * n; + Int_t nbPols = 4 * n; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1169,7 +1208,8 @@ const TBuffer3D & TGeoCone::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoCone::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i0)?(TMath::Abs((r-rin)*cr1)):TGeoShape::Big(); - saf[2] = TMath::Abs((rout-r)*cr2); - Int_t i = TMath::LocMin(3,saf); - if (((fPhi2-fPhi1)<360.) && TGeoShape::IsCloseToPhi(saf[i], point,fC1,fS1,fC2,fS2)) { - TGeoShape::NormalPhi(point,dir,norm,fC1,fS1,fC2,fS2); + Double_t ro1 = 0.5 * (fRmin1 + fRmin2); + Double_t tg1 = 0.5 * (fRmin2 - fRmin1) / fDz; + Double_t cr1 = 1. / TMath::Sqrt(1. + tg1 * tg1); + Double_t ro2 = 0.5 * (fRmax1 + fRmax2); + Double_t tg2 = 0.5 * (fRmax2 - fRmax1) / fDz; + Double_t cr2 = 1. / TMath::Sqrt(1. + tg2 * tg2); + + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t rin = tg1 * point[2] + ro1; + Double_t rout = tg2 * point[2] + ro2; + saf[0] = TMath::Abs(fDz - TMath::Abs(point[2])); + saf[1] = (ro1 > 0) ? (TMath::Abs((r - rin) * cr1)) : TGeoShape::Big(); + saf[2] = TMath::Abs((rout - r) * cr2); + Int_t i = TMath::LocMin(3, saf); + if (((fPhi2 - fPhi1) < 360.) && TGeoShape::IsCloseToPhi(saf[i], point, fC1, fS1, fC2, fS2)) { + TGeoShape::NormalPhi(point, dir, norm, fC1, fS1, fC2, fS2); return; } - if (i==0) { + if (i == 0) { norm[0] = norm[1] = 0.; - norm[2] = TMath::Sign(1.,dir[2]); + norm[2] = TMath::Sign(1., dir[2]); return; } - Double_t phi = TMath::ATan2(point[1],point[0]); + Double_t phi = TMath::ATan2(point[1], point[0]); Double_t cphi = TMath::Cos(phi); Double_t sphi = TMath::Sin(phi); - if (i==1) { - norm[0] = cr1*cphi; - norm[1] = cr1*sphi; - norm[2] = -tg1*cr1; + if (i == 1) { + norm[0] = cr1 * cphi; + norm[1] = cr1 * sphi; + norm[2] = -tg1 * cr1; } else { - norm[0] = cr2*cphi; - norm[1] = cr2*sphi; - norm[2] = -tg2*cr2; + norm[0] = cr2 * cphi; + norm[1] = cr2 * sphi; + norm[2] = -tg2 * cr2; } - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -1419,44 +1485,44 @@ void TGeoConeSeg::ComputeNormal(const Double_t *point, const Double_t *dir, Doub //////////////////////////////////////////////////////////////////////////////// /// Compute normal to closest surface from POINT. -void TGeoConeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, - Double_t c1, Double_t s1, Double_t c2, Double_t s2) +void TGeoConeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t dz, + Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, + Double_t s1, Double_t c2, Double_t s2) { Double_t saf[2]; - Double_t ro1 = 0.5*(rmin1+rmin2); - Double_t tg1 = 0.5*(rmin2-rmin1)/dz; - Double_t cr1 = 1./TMath::Sqrt(1.+tg1*tg1); - Double_t ro2 = 0.5*(rmax1+rmax2); - Double_t tg2 = 0.5*(rmax2-rmax1)/dz; - Double_t cr2 = 1./TMath::Sqrt(1.+tg2*tg2); - - Double_t r=TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Double_t rin = tg1*point[2]+ro1; - Double_t rout = tg2*point[2]+ro2; - saf[0] = (ro1>0)?(TMath::Abs((r-rin)*cr1)):TGeoShape::Big(); - saf[1] = TMath::Abs((rout-r)*cr2); - Int_t i = TMath::LocMin(2,saf); - if (TGeoShape::IsCloseToPhi(saf[i], point,c1,s1,c2,s2)) { - TGeoShape::NormalPhi(point,dir,norm,c1,s1,c2,s2); + Double_t ro1 = 0.5 * (rmin1 + rmin2); + Double_t tg1 = 0.5 * (rmin2 - rmin1) / dz; + Double_t cr1 = 1. / TMath::Sqrt(1. + tg1 * tg1); + Double_t ro2 = 0.5 * (rmax1 + rmax2); + Double_t tg2 = 0.5 * (rmax2 - rmax1) / dz; + Double_t cr2 = 1. / TMath::Sqrt(1. + tg2 * tg2); + + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t rin = tg1 * point[2] + ro1; + Double_t rout = tg2 * point[2] + ro2; + saf[0] = (ro1 > 0) ? (TMath::Abs((r - rin) * cr1)) : TGeoShape::Big(); + saf[1] = TMath::Abs((rout - r) * cr2); + Int_t i = TMath::LocMin(2, saf); + if (TGeoShape::IsCloseToPhi(saf[i], point, c1, s1, c2, s2)) { + TGeoShape::NormalPhi(point, dir, norm, c1, s1, c2, s2); return; } - Double_t phi = TMath::ATan2(point[1],point[0]); + Double_t phi = TMath::ATan2(point[1], point[0]); Double_t cphi = TMath::Cos(phi); Double_t sphi = TMath::Sin(phi); - if (i==0) { - norm[0] = cr1*cphi; - norm[1] = cr1*sphi; - norm[2] = -tg1*cr1; + if (i == 0) { + norm[0] = cr1 * cphi; + norm[1] = cr1 * sphi; + norm[2] = -tg1 * cr1; } else { - norm[0] = cr2*cphi; - norm[1] = cr2*sphi; - norm[2] = -tg2*cr2; + norm[0] = cr2 * cphi; + norm[1] = cr2 * sphi; + norm[2] = -tg2 * cr2; } - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -1468,15 +1534,20 @@ void TGeoConeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Dou Bool_t TGeoConeSeg::Contains(const Double_t *point) const { - if (!TGeoCone::Contains(point)) return kFALSE; + if (!TGeoCone::Contains(point)) + return kFALSE; Double_t dphi = fPhi2 - fPhi1; - if (dphi >= 360.) return kTRUE; + if (dphi >= 360.) + return kTRUE; Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - if (phi < 0 ) phi+=360.; - Double_t ddp = phi-fPhi1; - if (ddp < 0) ddp+=360.; -// if (ddp > 360) ddp-=360; - if (ddp > dphi) return kFALSE; + if (phi < 0) + phi += 360.; + Double_t ddp = phi - fPhi1; + if (ddp < 0) + ddp += 360.; + // if (ddp > 360) ddp-=360; + if (ddp > dphi) + return kFALSE; return kTRUE; } @@ -1486,70 +1557,83 @@ Bool_t TGeoConeSeg::Contains(const Double_t *point) const /// - r2, z2 - radius and Z position of upper base /// - phi1, phi2 - phi limits -Double_t TGeoConeSeg::DistToCons(const Double_t *point, const Double_t *dir, Double_t r1, Double_t z1, Double_t r2, Double_t z2, Double_t phi1, Double_t phi2) +Double_t TGeoConeSeg::DistToCons(const Double_t *point, const Double_t *dir, Double_t r1, Double_t z1, Double_t r2, + Double_t z2, Double_t phi1, Double_t phi2) { - Double_t dz = z2-z1; - if (dz<=0) { + Double_t dz = z2 - z1; + if (dz <= 0) { return TGeoShape::Big(); } Double_t dphi = phi2 - phi1; Bool_t hasphi = kTRUE; - if (dphi >= 360.) hasphi=kFALSE; - if (dphi < 0) dphi+=360.; -// printf("phi1=%f phi2=%f dphi=%f\n", phi1, phi2, dphi); - - Double_t ro0 = 0.5*(r1+r2); - Double_t fz = (r2-r1)/dz; - Double_t r0sq = point[0]*point[0] + point[1]*point[1]; - Double_t rc = ro0 + fz*(point[2]-0.5*(z1+z2)); - - Double_t a = dir[0]*dir[0] + dir[1]*dir[1] - fz*fz*dir[2]*dir[2]; - Double_t b = point[0]*dir[0] + point[1]*dir[1] - fz*rc*dir[2]; - Double_t c = r0sq - rc*rc; - - if (a==0) return TGeoShape::Big(); - a = 1./a; + if (dphi >= 360.) + hasphi = kFALSE; + if (dphi < 0) + dphi += 360.; + // printf("phi1=%f phi2=%f dphi=%f\n", phi1, phi2, dphi); + + Double_t ro0 = 0.5 * (r1 + r2); + Double_t fz = (r2 - r1) / dz; + Double_t r0sq = point[0] * point[0] + point[1] * point[1]; + Double_t rc = ro0 + fz * (point[2] - 0.5 * (z1 + z2)); + + Double_t a = dir[0] * dir[0] + dir[1] * dir[1] - fz * fz * dir[2] * dir[2]; + Double_t b = point[0] * dir[0] + point[1] * dir[1] - fz * rc * dir[2]; + Double_t c = r0sq - rc * rc; + + if (a == 0) + return TGeoShape::Big(); + a = 1. / a; b *= a; c *= a; - Double_t delta = b*b - c; - if (delta<0) return TGeoShape::Big(); + Double_t delta = b * b - c; + if (delta < 0) + return TGeoShape::Big(); delta = TMath::Sqrt(delta); - Double_t snxt = -b-delta; + Double_t snxt = -b - delta; Double_t ptnew[3]; Double_t ddp, phi; - if (snxt>0) { + if (snxt > 0) { // check Z range - ptnew[2] = point[2] + snxt*dir[2]; - if (((ptnew[2]-z1)*(ptnew[2]-z2)) < 0) { - // check phi range - if (!hasphi) return snxt; - ptnew[0] = point[0] + snxt*dir[0]; - ptnew[1] = point[1] + snxt*dir[1]; + ptnew[2] = point[2] + snxt * dir[2]; + if (((ptnew[2] - z1) * (ptnew[2] - z2)) < 0) { + // check phi range + if (!hasphi) + return snxt; + ptnew[0] = point[0] + snxt * dir[0]; + ptnew[1] = point[1] + snxt * dir[1]; phi = TMath::ATan2(ptnew[1], ptnew[0]) * TMath::RadToDeg(); - if (phi < 0 ) phi+=360.; - ddp = phi-phi1; - if (ddp < 0) ddp+=360.; + if (phi < 0) + phi += 360.; + ddp = phi - phi1; + if (ddp < 0) + ddp += 360.; // printf("snxt1=%f phi=%f ddp=%f\n", snxt, phi, ddp); - if (ddp<=dphi) return snxt; + if (ddp <= dphi) + return snxt; } } - snxt = -b+delta; - if (snxt>0) { + snxt = -b + delta; + if (snxt > 0) { // check Z range - ptnew[2] = point[2] + snxt*dir[2]; - if (((ptnew[2]-z1)*(ptnew[2]-z2)) < 0) { - // check phi range - if (!hasphi) return snxt; - ptnew[0] = point[0] + snxt*dir[0]; - ptnew[1] = point[1] + snxt*dir[1]; + ptnew[2] = point[2] + snxt * dir[2]; + if (((ptnew[2] - z1) * (ptnew[2] - z2)) < 0) { + // check phi range + if (!hasphi) + return snxt; + ptnew[0] = point[0] + snxt * dir[0]; + ptnew[1] = point[1] + snxt * dir[1]; phi = TMath::ATan2(ptnew[1], ptnew[0]) * TMath::RadToDeg(); - if (phi < 0 ) phi+=360.; - ddp = phi-phi1; - if (ddp < 0) ddp+=360.; + if (phi < 0) + phi += 360.; + ddp = phi - phi1; + if (ddp < 0) + ddp += 360.; // printf("snxt2=%f phi=%f ddp=%f\n", snxt, phi, ddp); - if (ddp<=dphi) return snxt; + if (ddp <= dphi) + return snxt; } } return TGeoShape::Big(); @@ -1558,262 +1642,308 @@ Double_t TGeoConeSeg::DistToCons(const Double_t *point, const Double_t *dir, Dou //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the tube segment -Double_t TGeoConeSeg::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi) +Double_t TGeoConeSeg::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, + Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi) { - if (dz<=0) return TGeoShape::Big(); + if (dz <= 0) + return TGeoShape::Big(); // Do Z - Double_t scone = TGeoCone::DistFromInsideS(point,dir,dz,rmin1,rmax1,rmin2,rmax2); - if (scone<=0) return 0.0; + Double_t scone = TGeoCone::DistFromInsideS(point, dir, dz, rmin1, rmax1, rmin2, rmax2); + if (scone <= 0) + return 0.0; Double_t sfmin = TGeoShape::Big(); - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t cpsi=point[0]*cm+point[1]*sm; - if (cpsi>r*cdfi+TGeoShape::Tolerance()) { + Double_t cpsi = point[0] * cm + point[1] * sm; + if (cpsi > r * cdfi + TGeoShape::Tolerance()) { sfmin = TGeoShape::DistToPhiMin(point, dir, s1, c1, s2, c2, sm, cm); - return TMath::Min(scone,sfmin); + return TMath::Min(scone, sfmin); } // Point on the phi boundary or outside // which one: phi1 or phi2 Double_t ddotn, xi, yi; - if (TMath::Abs(point[1]-s1*r) < TMath::Abs(point[1]-s2*r)) { - ddotn = s1*dir[0]-c1*dir[1]; - if (ddotn>=0) return 0.0; - ddotn = -s2*dir[0]+c2*dir[1]; - if (ddotn<=0) return scone; - sfmin = s2*point[0]-c2*point[1]; - if (sfmin<=0) return scone; + if (TMath::Abs(point[1] - s1 * r) < TMath::Abs(point[1] - s2 * r)) { + ddotn = s1 * dir[0] - c1 * dir[1]; + if (ddotn >= 0) + return 0.0; + ddotn = -s2 * dir[0] + c2 * dir[1]; + if (ddotn <= 0) + return scone; + sfmin = s2 * point[0] - c2 * point[1]; + if (sfmin <= 0) + return scone; sfmin /= ddotn; - if (sfmin >= scone) return scone; - xi = point[0]+sfmin*dir[0]; - yi = point[1]+sfmin*dir[1]; - if (yi*cm-xi*sm<0) return scone; + if (sfmin >= scone) + return scone; + xi = point[0] + sfmin * dir[0]; + yi = point[1] + sfmin * dir[1]; + if (yi * cm - xi * sm < 0) + return scone; return sfmin; } - ddotn = -s2*dir[0]+c2*dir[1]; - if (ddotn>=0) return 0.0; - ddotn = s1*dir[0]-c1*dir[1]; - if (ddotn<=0) return scone; - sfmin = -s1*point[0]+c1*point[1]; - if (sfmin<=0) return scone; + ddotn = -s2 * dir[0] + c2 * dir[1]; + if (ddotn >= 0) + return 0.0; + ddotn = s1 * dir[0] - c1 * dir[1]; + if (ddotn <= 0) + return scone; + sfmin = -s1 * point[0] + c1 * point[1]; + if (sfmin <= 0) + return scone; sfmin /= ddotn; - if (sfmin >= scone) return scone; - xi = point[0]+sfmin*dir[0]; - yi = point[1]+sfmin*dir[1]; - if (yi*cm-xi*sm>0) return scone; + if (sfmin >= scone) + return scone; + xi = point[0] + sfmin * dir[0]; + yi = point[1] + sfmin * dir[1]; + if (yi * cm - xi * sm > 0) + return scone; return sfmin; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the tube segment -Double_t TGeoConeSeg::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoConeSeg::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { - *safe = TGeoConeSeg::SafetyS(point, kTRUE, fDz,fRmin1,fRmax1,fRmin2,fRmax2,fPhi1,fPhi2); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact < 3 && safe) { + *safe = TGeoConeSeg::SafetyS(point, kTRUE, fDz, fRmin1, fRmax1, fRmin2, fRmax2, fPhi1, fPhi2); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } - if ((fPhi2-fPhi1)>=360.) return TGeoCone::DistFromInsideS(point,dir,fDz,fRmin1,fRmax1,fRmin2,fRmax2); + if ((fPhi2 - fPhi1) >= 360.) + return TGeoCone::DistFromInsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2); // compute distance to surface - return TGeoConeSeg::DistFromInsideS(point,dir,fDz,fRmin1,fRmax1,fRmin2,fRmax2,fC1,fS1,fC2,fS2,fCm,fSm,fCdfi); + return TGeoConeSeg::DistFromInsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2, fC1, fS1, fC2, fS2, fCm, fSm, + fCdfi); } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of arbitrary tube -Double_t TGeoConeSeg::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, - Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi) +Double_t TGeoConeSeg::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t dz, Double_t rmin1, + Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t c1, Double_t s1, + Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi) { - if (dz<=0) return TGeoShape::Big(); + if (dz <= 0) + return TGeoShape::Big(); Double_t r2, cpsi; // check Z planes Double_t xi, yi, zi; - Double_t b,delta; + Double_t b, delta; zi = dz - TMath::Abs(point[2]); - Double_t rin,rout; + Double_t rin, rout; Double_t s = TGeoShape::Big(); - Double_t snxt=TGeoShape::Big(); + Double_t snxt = TGeoShape::Big(); Bool_t in = kFALSE; - Bool_t inz = (zi<0)?kFALSE:kTRUE; + Bool_t inz = (zi < 0) ? kFALSE : kTRUE; if (!inz) { - if (point[2]*dir[2]>=0) return TGeoShape::Big(); - s = -zi/TMath::Abs(dir[2]); - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if (dir[2]>0) { + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); + s = -zi / TMath::Abs(dir[2]); + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if (dir[2] > 0) { rin = rmin1; rout = rmax1; } else { rin = rmin2; rout = rmax2; } - if ((rin*rin<=r2) && (r2<=rout*rout)) { - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) return s; + if ((rin * rin <= r2) && (r2 <= rout * rout)) { + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + return s; } } - Double_t zinv = 1./dz; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t zinv = 1. / dz; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t ro1=0.5*(rmin1+rmin2); - Bool_t hasrmin = (ro1>0)?kTRUE:kFALSE; + Double_t ro1 = 0.5 * (rmin1 + rmin2); + Bool_t hasrmin = (ro1 > 0) ? kTRUE : kFALSE; Double_t tg1 = 0.0; Bool_t inrmin = kFALSE; rin = 0.0; if (hasrmin) { - tg1=0.5*(rmin2-rmin1)*zinv; - rin = ro1+tg1*point[2]; - if (rsq > rin*(rin-TGeoShape::Tolerance())) inrmin=kTRUE; + tg1 = 0.5 * (rmin2 - rmin1) * zinv; + rin = ro1 + tg1 * point[2]; + if (rsq > rin * (rin - TGeoShape::Tolerance())) + inrmin = kTRUE; } else { inrmin = kTRUE; } - Double_t ro2=0.5*(rmax1+rmax2); - Double_t tg2=0.5*(rmax2-rmax1)*zinv; - rout = ro2+tg2*point[2]; + Double_t ro2 = 0.5 * (rmax1 + rmax2); + Double_t tg2 = 0.5 * (rmax2 - rmax1) * zinv; + rout = ro2 + tg2 * point[2]; Bool_t inrmax = kFALSE; - if (r < rout+TGeoShape::Tolerance()) inrmax = kTRUE; + if (r < rout + TGeoShape::Tolerance()) + inrmax = kTRUE; Bool_t inphi = kFALSE; - cpsi=point[0]*cm+point[1]*sm; - if (cpsi>r*cdfi-TGeoShape::Tolerance()) inphi = kTRUE; + cpsi = point[0] * cm + point[1] * sm; + if (cpsi > r * cdfi - TGeoShape::Tolerance()) + inphi = kTRUE; in = inz & inrmin & inrmax & inphi; // If inside, we are most likely on a boundary within machine precision. if (in) { - Double_t safphi = (cpsi-r*cdfi)*TMath::Sqrt(1.-cdfi*cdfi); - Double_t safrmin = (hasrmin)?TMath::Abs(r-rin):(TGeoShape::Big()); - Double_t safrmax = TMath::Abs(r-rout); + Double_t safphi = (cpsi - r * cdfi) * TMath::Sqrt(1. - cdfi * cdfi); + Double_t safrmin = (hasrmin) ? TMath::Abs(r - rin) : (TGeoShape::Big()); + Double_t safrmax = TMath::Abs(r - rout); // check if on Z boundaries - if (zi point[0]*c2 + point[1]*s2) { - un = dir[0]*s1-dir[1]*c1; - if (un < 0) return 0.0; - if (cdfi>=0) return TGeoShape::Big(); - un = -dir[0]*s2+dir[1]*c2; - if (un<0) { - s = -point[0]*s2+point[1]*c2; - if (s>0) { + if (point[0] * c1 + point[1] * s1 > point[0] * c2 + point[1] * s2) { + un = dir[0] * s1 - dir[1] * c1; + if (un < 0) + return 0.0; + if (cdfi >= 0) + return TGeoShape::Big(); + un = -dir[0] * s2 + dir[1] * c2; + if (un < 0) { + s = -point[0] * s2 + point[1] * c2; + if (s > 0) { s /= (-un); - zi = point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - if ((yi*cm-xi*sm)>0) { - r2=xi*xi+yi*yi; - rin = ro1+tg1*zi; - rout = ro2+tg2*zi; - if ((rin*rin<=r2) && (rout*rout>=r2)) return s; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((yi * cm - xi * sm) > 0) { + r2 = xi * xi + yi * yi; + rin = ro1 + tg1 * zi; + rout = ro2 + tg2 * zi; + if ((rin * rin <= r2) && (rout * rout >= r2)) + return s; } } } } } else { - un = -dir[0]*s2+dir[1]*c2; - if (un < 0) return 0.0; - if (cdfi>=0) return TGeoShape::Big(); - un = dir[0]*s1-dir[1]*c1; - if (un<0) { - s = point[0]*s1-point[1]*c1; - if (s>0) { + un = -dir[0] * s2 + dir[1] * c2; + if (un < 0) + return 0.0; + if (cdfi >= 0) + return TGeoShape::Big(); + un = dir[0] * s1 - dir[1] * c1; + if (un < 0) { + s = point[0] * s1 - point[1] * c1; + if (s > 0) { s /= (-un); - zi = point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - if ((yi*cm-xi*sm)<0) { - r2=xi*xi+yi*yi; - rin = ro1+tg1*zi; - rout = ro2+tg2*zi; - if ((rin*rin<=r2) && (rout*rout>=r2)) return s; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((yi * cm - xi * sm) < 0) { + r2 = xi * xi + yi * yi; + rin = ro1 + tg1 * zi; + rout = ro2 + tg2 * zi; + if ((rin * rin <= r2) && (rout * rout >= r2)) + return s; } } } } } // We may also cross rmin, second solution coming from outside - Double_t ddotn = point[0]*dir[0]+point[1]*dir[1]-tg1*dir[2]*r; - if (ddotn>=0) return TGeoShape::Big(); - if (cdfi>=0) return TGeoShape::Big(); + Double_t ddotn = point[0] * dir[0] + point[1] * dir[1] - tg1 * dir[2] * r; + if (ddotn >= 0) + return TGeoShape::Big(); + if (cdfi >= 0) + return TGeoShape::Big(); TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta<0) return TGeoShape::Big(); - snxt = -b-delta; - if (snxt<0) return TGeoShape::Big(); - snxt = -b+delta; - zi = point[2]+snxt*dir[2]; - if (TMath::Abs(zi)>dz) return TGeoShape::Big(); - xi = point[0]+snxt*dir[0]; - yi = point[1]+snxt*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) return snxt; + if (delta < 0) + return TGeoShape::Big(); + snxt = -b - delta; + if (snxt < 0) + return TGeoShape::Big(); + snxt = -b + delta; + zi = point[2] + snxt * dir[2]; + if (TMath::Abs(zi) > dz) + return TGeoShape::Big(); + xi = point[0] + snxt * dir[0]; + yi = point[1] + snxt * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + return snxt; return TGeoShape::Big(); } // We are on rmin boundary: we may cross again rmin or a phi facette - Double_t ddotn = point[0]*dir[0]+point[1]*dir[1]-tg1*dir[2]*r; - if (ddotn>=0) return 0.0; + Double_t ddotn = point[0] * dir[0] + point[1] * dir[1] - tg1 * dir[2] * r; + if (ddotn >= 0) + return 0.0; TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta<0) return 0.0; - snxt = -b+delta; - if (snxt<0) return TGeoShape::Big(); - if (TMath::Abs(-b-delta)>snxt) return TGeoShape::Big(); - zi = point[2]+snxt*dir[2]; - if (TMath::Abs(zi)>dz) return TGeoShape::Big(); + if (delta < 0) + return 0.0; + snxt = -b + delta; + if (snxt < 0) + return TGeoShape::Big(); + if (TMath::Abs(-b - delta) > snxt) + return TGeoShape::Big(); + zi = point[2] + snxt * dir[2]; + if (TMath::Abs(zi) > dz) + return TGeoShape::Big(); // OK, we cross rmin at snxt - check if within phi range - xi = point[0]+snxt*dir[0]; - yi = point[1]+snxt*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) return snxt; + xi = point[0] + snxt * dir[0]; + yi = point[1] + snxt * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + return snxt; // we cross rmin in the phi gap - we may cross a phi facette - if (cdfi>=0) return TGeoShape::Big(); - Double_t un=-dir[0]*s1+dir[1]*c1; + if (cdfi >= 0) + return TGeoShape::Big(); + Double_t un = -dir[0] * s1 + dir[1] * c1; if (un > 0) { - s=point[0]*s1-point[1]*c1; - if (s>=0) { + s = point[0] * s1 - point[1] * c1; + if (s >= 0) { s /= un; - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - if ((yi*cm-xi*sm)<=0) { - r2=xi*xi+yi*yi; - rin = ro1+tg1*zi; - rout = ro2+tg2*zi; - if ((rin*rin<=r2) && (rout*rout>=r2)) return s; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((yi * cm - xi * sm) <= 0) { + r2 = xi * xi + yi * yi; + rin = ro1 + tg1 * zi; + rout = ro2 + tg2 * zi; + if ((rin * rin <= r2) && (rout * rout >= r2)) + return s; } } } } - un=dir[0]*s2-dir[1]*c2; + un = dir[0] * s2 - dir[1] * c2; if (un > 0) { - s=(point[1]*c2-point[0]*s2)/un; - if (s>=0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - if ((yi*cm-xi*sm)>=0) { - r2=xi*xi+yi*yi; - rin = ro1+tg1*zi; - rout = ro2+tg2*zi; - if ((rin*rin<=r2) && (rout*rout>=r2)) return s; + s = (point[1] * c2 - point[0] * s2) / un; + if (s >= 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((yi * cm - xi * sm) >= 0) { + r2 = xi * xi + yi * yi; + rin = ro1 + tg1 * zi; + rout = ro2 + tg2 * zi; + if ((rin * rin <= r2) && (rout * rout >= r2)) + return s; } } } @@ -1826,27 +1956,29 @@ Double_t TGeoConeSeg::DistFromOutsideS(const Double_t *point, const Double_t *di if (!inrmax) { // check crossing with outer cone TGeoCone::DistToCone(point, dir, dz, rmax1, rmax2, b, delta); - if (delta>=0) { - s = -b-delta; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) return s; // rmax crossing + if (delta >= 0) { + s = -b - delta; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + return s; // rmax crossing } } - s = -b+delta; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) sr1=s; + s = -b + delta; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + sr1 = s; } } } @@ -1854,64 +1986,76 @@ Double_t TGeoConeSeg::DistFromOutsideS(const Double_t *point, const Double_t *di // check crossing with inner cone Double_t sr2 = TGeoShape::Big(); TGeoCone::DistToCone(point, dir, dz, rmin1, rmin2, b, delta); - if (delta>=0) { - s = -b-delta; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) sr2=s; + if (delta >= 0) { + s = -b - delta; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + sr2 = s; } } - if (sr2>1E10) { - s = -b+delta; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - cpsi=xi*cm+yi*sm; - if (cpsi>=(cdfi*TMath::Sqrt(r2))) sr2=s; + if (sr2 > 1E10) { + s = -b + delta; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + cpsi = xi * cm + yi * sm; + if (cpsi >= (cdfi * TMath::Sqrt(r2))) + sr2 = s; } } } } - snxt = TMath::Min(sr1,sr2); + snxt = TMath::Min(sr1, sr2); // Check phi crossing - s = TGeoShape::DistToPhiMin(point,dir,s1,c1,s2,c2,sm,cm,kFALSE); - if (s>snxt) return snxt; - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)>dz) return snxt; - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - rout = ro2+tg2*zi; - if (r2>rout*rout) return snxt; - rin = ro1+tg1*zi; - if (r2>=rin*rin) return s; // phi crossing + s = TGeoShape::DistToPhiMin(point, dir, s1, c1, s2, c2, sm, cm, kFALSE); + if (s > snxt) + return snxt; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) > dz) + return snxt; + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + rout = ro2 + tg2 * zi; + if (r2 > rout * rout) + return snxt; + rin = ro1 + tg1 * zi; + if (r2 >= rin * rin) + return s; // phi crossing return snxt; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the tube -Double_t TGeoConeSeg::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoConeSeg::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { // compute safe radius - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); - if ((fPhi2-fPhi1)>=360.) return TGeoCone::DistFromOutsideS(point,dir,fDz,fRmin1,fRmax1,fRmin2,fRmax2); - return TGeoConeSeg::DistFromOutsideS(point,dir,fDz,fRmin1,fRmax1,fRmin2,fRmax2,fC1,fS1,fC2,fS2,fCm,fSm,fCdfi); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); + if ((fPhi2 - fPhi1) >= 360.) + return TGeoCone::DistFromOutsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2); + return TGeoConeSeg::DistFromOutsideS(point, dir, fDz, fRmin1, fRmax1, fRmin2, fRmax2, fC1, fS1, fC2, fS2, fCm, fSm, + fCdfi); } //////////////////////////////////////////////////////////////////////////////// @@ -1919,8 +2063,8 @@ Double_t TGeoConeSeg::DistFromOutside(const Double_t *point, const Double_t *dir Int_t TGeoConeSeg::DistancetoPrimitive(Int_t px, Int_t py) { - Int_t n = gGeoManager->GetNsegments()+1; - const Int_t numPoints = 4*n; + Int_t n = gGeoManager->GetNsegments() + 1; + const Int_t numPoints = 4 * n; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -1932,60 +2076,59 @@ Int_t TGeoConeSeg::DistancetoPrimitive(Int_t px, Int_t py) /// was divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoConeSeg::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoConeSeg::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Double_t dphi; Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- R division - Error("Divide","division of a cone segment on R not implemented"); - return 0; - case 2: //--- Phi division - dphi = fPhi2-fPhi1; - if (dphi<0) dphi+=360.; - finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoConeSeg(fDz, fRmin1, fRmax1, fRmin2, fRmax2, -step/2, step/2); + case 1: //--- R division + Error("Divide", "division of a cone segment on R not implemented"); + return 0; + case 2: //--- Phi division + dphi = fPhi2 - fPhi1; + if (dphi < 0) + dphi += 360.; + finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoConeSeg(fDz, fRmin1, fRmax1, fRmin2, fRmax2, -step / 2, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Z division + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + Double_t z1 = start + id * step; + Double_t z2 = start + (id + 1) * step; + Double_t rmin1n = 0.5 * (fRmin1 * (fDz - z1) + fRmin2 * (fDz + z1)) / fDz; + Double_t rmax1n = 0.5 * (fRmax1 * (fDz - z1) + fRmax2 * (fDz + z1)) / fDz; + Double_t rmin2n = 0.5 * (fRmin1 * (fDz - z2) + fRmin2 * (fDz + z2)) / fDz; + Double_t rmax2n = 0.5 * (fRmax1 * (fDz - z2) + fRmax2 * (fDz + z2)) / fDz; + shape = new TGeoConeSeg(step / 2, rmin1n, rmax1n, rmin2n, rmax2n, fPhi1, fPhi2); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Z division - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "Z"; - voldiv->AddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + opt = "Z"; + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "Wrong axis type for division"); return 0; } } @@ -1998,16 +2141,16 @@ Double_t TGeoConeSeg::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) co xhi = 0; Double_t dx = 0; switch (iaxis) { - case 2: - xlo = fPhi1; - xhi = fPhi2; - dx = xhi-xlo; - return dx; - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 2: + xlo = fPhi1; + xhi = fPhi2; + dx = xhi - xlo; + return dx; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -2022,9 +2165,10 @@ void TGeoConeSeg::GetBoundingCylinder(Double_t *param) const param[0] *= param[0]; param[1] = TMath::Max(fRmax1, fRmax2); // Rmax param[1] *= param[1]; - param[2] = (fPhi1<0)?(fPhi1+360.):fPhi1; // Phi1 - param[3] = fPhi2; // Phi2 - while (param[3]TestShapeBit(kGeoConeSeg)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; @@ -2044,15 +2189,16 @@ TGeoShape *TGeoConeSeg::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*ma rmin2 = fRmin2; rmax2 = fRmax2; dz = fDz; - if (fDz<0) dz=((TGeoCone*)mother)->GetDz(); - if (fRmin1<0) - rmin1 = ((TGeoCone*)mother)->GetRmin1(); - if ((fRmax1<0) || (fRmax1GetRmax1(); - if (fRmin2<0) - rmin2 = ((TGeoCone*)mother)->GetRmin2(); - if ((fRmax2<0) || (fRmax2GetRmax2(); + if (fDz < 0) + dz = ((TGeoCone *)mother)->GetDz(); + if (fRmin1 < 0) + rmin1 = ((TGeoCone *)mother)->GetRmin1(); + if ((fRmax1 < 0) || (fRmax1 < fRmin1)) + rmax1 = ((TGeoCone *)mother)->GetRmax1(); + if (fRmin2 < 0) + rmin2 = ((TGeoCone *)mother)->GetRmin2(); + if ((fRmax2 < 0) || (fRmax2 < fRmin2)) + rmax2 = ((TGeoCone *)mother)->GetRmax2(); return (new TGeoConeSeg(GetName(), dz, rmin1, rmax1, rmin2, rmax2, fPhi1, fPhi2)); } @@ -2074,23 +2220,20 @@ void TGeoConeSeg::InspectShape() const TGeoBBox::InspectShape(); } - /////////////////////////////////////////////////////////////////////////////// - /// Creates a TBuffer3D describing *this* shape. - /// Coordinates are in local reference frame. +/////////////////////////////////////////////////////////////////////////////// +/// Creates a TBuffer3D describing *this* shape. +/// Coordinates are in local reference frame. TBuffer3D *TGeoConeSeg::MakeBuffer3D() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = 4*n; - Int_t nbSegs = 2*nbPnts; - Int_t nbPols = nbPnts-2; - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, - nbSegs, 3*nbSegs, - nbPols, 6*nbPols); - - if (buff) - { + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 2 * nbPnts; + Int_t nbPols = nbPnts - 2; + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -2104,82 +2247,82 @@ TBuffer3D *TGeoConeSeg::MakeBuffer3D() const void TGeoConeSeg::SetSegsAndPols(TBuffer3D &buffer) const { Int_t i, j; - Int_t n = gGeoManager->GetNsegments()+1; + Int_t n = gGeoManager->GetNsegments() + 1; Int_t c = GetBasicColor(); - memset(buffer.fSegs, 0, buffer.NbSegs()*3*sizeof(Int_t)); + memset(buffer.fSegs, 0, buffer.NbSegs() * 3 * sizeof(Int_t)); for (i = 0; i < 4; i++) { for (j = 1; j < n; j++) { - buffer.fSegs[(i*n+j-1)*3 ] = c; - buffer.fSegs[(i*n+j-1)*3+1] = i*n+j-1; - buffer.fSegs[(i*n+j-1)*3+2] = i*n+j; + buffer.fSegs[(i * n + j - 1) * 3] = c; + buffer.fSegs[(i * n + j - 1) * 3 + 1] = i * n + j - 1; + buffer.fSegs[(i * n + j - 1) * 3 + 2] = i * n + j; } } for (i = 4; i < 6; i++) { for (j = 0; j < n; j++) { - buffer.fSegs[(i*n+j)*3 ] = c+1; - buffer.fSegs[(i*n+j)*3+1] = (i-4)*n+j; - buffer.fSegs[(i*n+j)*3+2] = (i-2)*n+j; + buffer.fSegs[(i * n + j) * 3] = c + 1; + buffer.fSegs[(i * n + j) * 3 + 1] = (i - 4) * n + j; + buffer.fSegs[(i * n + j) * 3 + 2] = (i - 2) * n + j; } } for (i = 6; i < 8; i++) { for (j = 0; j < n; j++) { - buffer.fSegs[(i*n+j)*3 ] = c; - buffer.fSegs[(i*n+j)*3+1] = 2*(i-6)*n+j; - buffer.fSegs[(i*n+j)*3+2] = (2*(i-6)+1)*n+j; + buffer.fSegs[(i * n + j) * 3] = c; + buffer.fSegs[(i * n + j) * 3 + 1] = 2 * (i - 6) * n + j; + buffer.fSegs[(i * n + j) * 3 + 2] = (2 * (i - 6) + 1) * n + j; } } Int_t indx = 0; - memset(buffer.fPols, 0, buffer.NbPols()*6*sizeof(Int_t)); + memset(buffer.fPols, 0, buffer.NbPols() * 6 * sizeof(Int_t)); i = 0; - for (j = 0; j < n-1; j++) { + for (j = 0; j < n - 1; j++) { buffer.fPols[indx++] = c; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = (4+i)*n+j+1; - buffer.fPols[indx++] = (2+i)*n+j; - buffer.fPols[indx++] = (4+i)*n+j; - buffer.fPols[indx++] = i*n+j; + buffer.fPols[indx++] = (4 + i) * n + j + 1; + buffer.fPols[indx++] = (2 + i) * n + j; + buffer.fPols[indx++] = (4 + i) * n + j; + buffer.fPols[indx++] = i * n + j; } i = 1; - for (j = 0; j < n-1; j++) { + for (j = 0; j < n - 1; j++) { buffer.fPols[indx++] = c; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = i*n+j; - buffer.fPols[indx++] = (4+i)*n+j; - buffer.fPols[indx++] = (2+i)*n+j; - buffer.fPols[indx++] = (4+i)*n+j+1; + buffer.fPols[indx++] = i * n + j; + buffer.fPols[indx++] = (4 + i) * n + j; + buffer.fPols[indx++] = (2 + i) * n + j; + buffer.fPols[indx++] = (4 + i) * n + j + 1; } i = 2; - for (j = 0; j < n-1; j++) { - buffer.fPols[indx++] = c+i; + for (j = 0; j < n - 1; j++) { + buffer.fPols[indx++] = c + i; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = (i-2)*2*n+j; - buffer.fPols[indx++] = (4+i)*n+j; - buffer.fPols[indx++] = ((i-2)*2+1)*n+j; - buffer.fPols[indx++] = (4+i)*n+j+1; + buffer.fPols[indx++] = (i - 2) * 2 * n + j; + buffer.fPols[indx++] = (4 + i) * n + j; + buffer.fPols[indx++] = ((i - 2) * 2 + 1) * n + j; + buffer.fPols[indx++] = (4 + i) * n + j + 1; } i = 3; - for (j = 0; j < n-1; j++) { - buffer.fPols[indx++] = c+i; + for (j = 0; j < n - 1; j++) { + buffer.fPols[indx++] = c + i; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = (4+i)*n+j+1; - buffer.fPols[indx++] = ((i-2)*2+1)*n+j; - buffer.fPols[indx++] = (4+i)*n+j; - buffer.fPols[indx++] = (i-2)*2*n+j; + buffer.fPols[indx++] = (4 + i) * n + j + 1; + buffer.fPols[indx++] = ((i - 2) * 2 + 1) * n + j; + buffer.fPols[indx++] = (4 + i) * n + j; + buffer.fPols[indx++] = (i - 2) * 2 * n + j; } - buffer.fPols[indx++] = c+2; + buffer.fPols[indx++] = c + 2; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = 6*n; - buffer.fPols[indx++] = 4*n; - buffer.fPols[indx++] = 7*n; - buffer.fPols[indx++] = 5*n; - buffer.fPols[indx++] = c+2; + buffer.fPols[indx++] = 6 * n; + buffer.fPols[indx++] = 4 * n; + buffer.fPols[indx++] = 7 * n; + buffer.fPols[indx++] = 5 * n; + buffer.fPols[indx++] = c + 2; buffer.fPols[indx++] = 4; - buffer.fPols[indx++] = 6*n-1; - buffer.fPols[indx++] = 8*n-1; - buffer.fPols[indx++] = 5*n-1; - buffer.fPols[indx++] = 7*n-1; + buffer.fPols[indx++] = 6 * n - 1; + buffer.fPols[indx++] = 8 * n - 1; + buffer.fPols[indx++] = 5 * n - 1; + buffer.fPols[indx++] = 7 * n - 1; } //////////////////////////////////////////////////////////////////////////////// @@ -2188,11 +2331,14 @@ void TGeoConeSeg::SetSegsAndPols(TBuffer3D &buffer) const Double_t TGeoConeSeg::Safety(const Double_t *point, Bool_t in) const { - Double_t safe = TGeoCone::Safety(point,in); - if ((fPhi2-fPhi1)>=360.) return safe; + Double_t safe = TGeoCone::Safety(point, in); + if ((fPhi2 - fPhi1) >= 360.) + return safe; Double_t safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); - if (in) return TMath::Min(safe, safphi); - if (safe>1.E10) return safphi; + if (in) + return TMath::Min(safe, safphi); + if (safe > 1.E10) + return safphi; return TMath::Max(safe, safphi); } @@ -2202,11 +2348,14 @@ Double_t TGeoConeSeg::Safety(const Double_t *point, Bool_t in) const Double_t TGeoConeSeg::SafetyS(const Double_t *point, Bool_t in, Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2, Int_t skipz) { - Double_t safe = TGeoCone::SafetyS(point,in,dz,rmin1,rmax1,rmin2,rmax2,skipz); - if ((phi2-phi1)>=360.) return safe; - Double_t safphi = TGeoShape::SafetyPhi(point,in,phi1,phi2); - if (in) return TMath::Min(safe, safphi); - if (safe>1.E10) return safphi; + Double_t safe = TGeoCone::SafetyS(point, in, dz, rmin1, rmax1, rmin2, rmax2, skipz); + if ((phi2 - phi1) >= 360.) + return safe; + Double_t safphi = TGeoShape::SafetyPhi(point, in, phi1, phi2); + if (in) + return TMath::Min(safe, safphi); + if (safe > 1.E10) + return safphi; return TMath::Max(safe, safphi); } @@ -2215,7 +2364,8 @@ Double_t TGeoConeSeg::SafetyS(const Double_t *point, Bool_t in, Double_t dz, Dou void TGeoConeSeg::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " rmin1 = " << fRmin1 << ";" << std::endl; @@ -2224,26 +2374,30 @@ void TGeoConeSeg::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""* out << " rmax2 = " << fRmax2 << ";" << std::endl; out << " phi1 = " << fPhi1 << ";" << std::endl; out << " phi2 = " << fPhi2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoConeSeg(\"" << GetName() << "\", dz,rmin1,rmax1,rmin2,rmax2,phi1,phi2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoConeSeg(\"" << GetName() + << "\", dz,rmin1,rmax1,rmin2,rmax2,phi1,phi2);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } //////////////////////////////////////////////////////////////////////////////// /// Set dimensions of the cone segment. -void TGeoConeSeg::SetConsDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2) +void TGeoConeSeg::SetConsDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, Double_t rmin2, Double_t rmax2, + Double_t phi1, Double_t phi2) { - fDz = dz; + fDz = dz; fRmin1 = rmin1; fRmax1 = rmax1; fRmin2 = rmin2; fRmax2 = rmax2; fPhi1 = phi1; - while (fPhi1<0) fPhi1+=360.; + while (fPhi1 < 0) + fPhi1 += 360.; fPhi2 = phi2; - while (fPhi2<=fPhi1) fPhi2+=360.; - if (TGeoShape::IsSameWithinTolerance(fPhi1,fPhi2)) Fatal("SetConsDimensions", "In shape %s invalid phi1=%g, phi2=%g\n", GetName(), fPhi1, fPhi2); + while (fPhi2 <= fPhi1) + fPhi2 += 360.; + if (TGeoShape::IsSameWithinTolerance(fPhi1, fPhi2)) + Fatal("SetConsDimensions", "In shape %s invalid phi1=%g, phi2=%g\n", GetName(), fPhi1, fPhi2); InitTrigonometry(); } @@ -2252,14 +2406,14 @@ void TGeoConeSeg::SetConsDimensions(Double_t dz, Double_t rmin1, Double_t rmax1, void TGeoConeSeg::SetDimensions(Double_t *param) { - Double_t dz = param[0]; + Double_t dz = param[0]; Double_t rmin1 = param[1]; Double_t rmax1 = param[2]; Double_t rmin2 = param[3]; Double_t rmax2 = param[4]; - Double_t phi1 = param[5]; - Double_t phi2 = param[6]; - SetConsDimensions(dz, rmin1, rmax1,rmin2, rmax2, phi1, phi2); + Double_t phi1 = param[5]; + Double_t phi2 = param[6]; + SetConsDimensions(dz, rmin1, rmax1, rmin2, rmax2, phi1, phi2); } //////////////////////////////////////////////////////////////////////////////// @@ -2268,38 +2422,38 @@ void TGeoConeSeg::SetDimensions(Double_t *param) void TGeoConeSeg::SetPoints(Double_t *points) const { Int_t j, n; - Float_t dphi,phi,phi1, phi2,dz; + Float_t dphi, phi, phi1, phi2, dz; - n = gGeoManager->GetNsegments()+1; - dz = fDz; + n = gGeoManager->GetNsegments() + 1; + dz = fDz; phi1 = fPhi1; phi2 = fPhi2; - dphi = (phi2-phi1)/(n-1); + dphi = (phi2 - phi1) / (n - 1); Int_t indx = 0; if (points) { for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin1 * TMath::Cos(phi); points[indx++] = fRmin1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax1 * TMath::Cos(phi); points[indx++] = fRmax1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin2 * TMath::Cos(phi); points[indx++] = fRmin2 * TMath::Sin(phi); points[indx++] = dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax2 * TMath::Cos(phi); points[indx++] = fRmax2 * TMath::Sin(phi); points[indx++] = dz; @@ -2313,38 +2467,38 @@ void TGeoConeSeg::SetPoints(Double_t *points) const void TGeoConeSeg::SetPoints(Float_t *points) const { Int_t j, n; - Float_t dphi,phi,phi1, phi2,dz; + Float_t dphi, phi, phi1, phi2, dz; - n = gGeoManager->GetNsegments()+1; - dz = fDz; + n = gGeoManager->GetNsegments() + 1; + dz = fDz; phi1 = fPhi1; phi2 = fPhi2; - dphi = (phi2-phi1)/(n-1); + dphi = (phi2 - phi1) / (n - 1); Int_t indx = 0; if (points) { for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin1 * TMath::Cos(phi); points[indx++] = fRmin1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax1 * TMath::Cos(phi); points[indx++] = fRmax1 * TMath::Sin(phi); points[indx++] = -dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin2 * TMath::Cos(phi); points[indx++] = fRmin2 * TMath::Sin(phi); points[indx++] = dz; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax2 * TMath::Cos(phi); points[indx++] = fRmax2 * TMath::Sin(phi); points[indx++] = dz; @@ -2357,10 +2511,10 @@ void TGeoConeSeg::SetPoints(Float_t *points) const void TGeoConeSeg::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - Int_t n = gGeoManager->GetNsegments()+1; - nvert = n*4; - nsegs = n*8; - npols = n*4-2; + Int_t n = gGeoManager->GetNsegments() + 1; + nvert = n * 4; + nsegs = n * 8; + npols = n * 4 - 2; } //////////////////////////////////////////////////////////////////////////////// @@ -2368,33 +2522,31 @@ void TGeoConeSeg::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoConeSeg::GetNmeshVertices() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t numPoints = n*4; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t numPoints = n * 4; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// Fill size of this 3-D object -void TGeoConeSeg::Sizeof3D() const -{ -} +void TGeoConeSeg::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoConeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoConeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kRawSizes) { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = 4*n; - Int_t nbSegs = 2*nbPnts; - Int_t nbPols = nbPnts-2; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 2 * nbPnts; + Int_t nbPols = nbPnts - 2; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -2418,33 +2570,33 @@ const TBuffer3D & TGeoConeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) Bool_t TGeoConeSeg::GetPointsOnSegments(Int_t npoints, Double_t *array) const { - if (npoints > (npoints/2)*2) { - Error("GetPointsOnSegments","Npoints must be even number"); + if (npoints > (npoints / 2) * 2) { + Error("GetPointsOnSegments", "Npoints must be even number"); return kFALSE; } - Int_t nc = (Int_t)TMath::Sqrt(0.5*npoints); - Double_t dphi = (fPhi2-fPhi1)*TMath::DegToRad()/(nc-1); + Int_t nc = (Int_t)TMath::Sqrt(0.5 * npoints); + Double_t dphi = (fPhi2 - fPhi1) * TMath::DegToRad() / (nc - 1); Double_t phi = 0; Double_t phi1 = fPhi1 * TMath::DegToRad(); - Int_t ntop = npoints/2 - nc*(nc-1); - Double_t dz = 2*fDz/(nc-1); + Int_t ntop = npoints / 2 - nc * (nc - 1); + Double_t dz = 2 * fDz / (nc - 1); Double_t z = 0; Double_t rmin = 0.; Double_t rmax = 0.; Int_t icrt = 0; Int_t nphi = nc; // loop z sections - for (Int_t i=0; i(fZ+0.5) - 1 ; // The static cast comes from G4lrint - static const Double_t log184 = TMath::Log(184.15); + Double_t alpha_rcl2 = + TGeoManager::kRootUnits == TGeoManager::GetDefaultUnits() ? TGeoUnit::alpha_rcl2 : TGeant4Unit::alpha_rcl2; + Int_t iz = static_cast(fZ + 0.5) - 1; // The static cast comes from G4lrint + static const Double_t log184 = TMath::Log(184.15); static const Double_t log1194 = TMath::Log(1194.); - if (iz <= 3) { Lrad = Lrad_light[iz] ; Lprad = Lprad_light[iz] ; } - else { Lrad = log184 - logZ3 ; Lprad = log1194 - 2*logZ3;} + if (iz <= 3) { + Lrad = Lrad_light[iz]; + Lprad = Lprad_light[iz]; + } else { + Lrad = log184 - logZ3; + Lprad = log1194 - 2 * logZ3; + } - fRadTsai = 4*alpha_rcl2*fZ*(fZ*(Lrad-fCoulomb) + Lprad); + fRadTsai = 4 * alpha_rcl2 * fZ * (fZ * (Lrad - fCoulomb) + Lprad); } //////////////////////////////////////////////////////////////////////////////// /// Print this isotope void TGeoElement::Print(Option_t *option) const { - printf("Element: %s Z=%d N=%f A=%f [g/mole]\n", GetName(), fZ,Neff(),fA); + printf("Element: %s Z=%d N=%f A=%f [g/mole]\n", GetName(), fZ, Neff(), fA); if (HasIsotopes()) { - for (Int_t i=0; iIsotope %s, abundance=%f :\n", iso->GetName(), fAbundances[i]); iso->Print(option); @@ -257,9 +249,10 @@ void TGeoElement::AddIsotope(TGeoIsotope *isotope, Double_t relativeAbundance) } Int_t ncurrent = 0; TGeoIsotope *isocrt; - for (ncurrent=0; ncurrentAt(ncurrent)) break; - if (ncurrent==fNisotopes) { + for (ncurrent = 0; ncurrent < fNisotopes; ncurrent++) + if (!fIsotopes->At(ncurrent)) + break; + if (ncurrent == fNisotopes) { // User requested overwriting a standard element - we need to extend dynamically the support arrays Double_t *abundances = new Double_t[fNisotopes + 1]; memcpy(abundances, fAbundances, fNisotopes * sizeof(Double_t)); @@ -268,23 +261,23 @@ void TGeoElement::AddIsotope(TGeoIsotope *isotope, Double_t relativeAbundance) fNisotopes++; } // Check Z of the new isotope - if ((fZ!=0) && (isotope->GetZ()!=fZ)) { - Fatal("AddIsotope", "Trying to add isotope %s with different Z to the same element %s", - isotope->GetName(), GetName()); + if ((fZ != 0) && (isotope->GetZ() != fZ)) { + Fatal("AddIsotope", "Trying to add isotope %s with different Z to the same element %s", isotope->GetName(), + GetName()); return; } else { fZ = isotope->GetZ(); } fIsotopes->Add(isotope); fAbundances[ncurrent] = relativeAbundance; - if (ncurrent==fNisotopes-1) { + if (ncurrent == fNisotopes - 1) { Double_t weight = 0.0; Double_t aeff = 0.0; Double_t neff = 0.0; - for (Int_t i=0; iAt(i); - aeff += fAbundances[i]*isocrt->GetA(); - neff += fAbundances[i]*isocrt->GetN(); + for (Int_t i = 0; i < fNisotopes; i++) { + isocrt = (TGeoIsotope *)fIsotopes->At(i); + aeff += fAbundances[i] * isocrt->GetA(); + neff += fAbundances[i] * isocrt->GetN(); weight += fAbundances[i]; } aeff /= weight; @@ -300,13 +293,14 @@ void TGeoElement::AddIsotope(TGeoIsotope *isotope, Double_t relativeAbundance) Double_t TGeoElement::Neff() const { - if (!fNisotopes) return fN; + if (!fNisotopes) + return fN; TGeoIsotope *isocrt; Double_t weight = 0.0; Double_t neff = 0.0; - for (Int_t i=0; iAt(i); - neff += fAbundances[i]*isocrt->GetN(); + for (Int_t i = 0; i < fNisotopes; i++) { + isocrt = (TGeoIsotope *)fIsotopes->At(i); + neff += fAbundances[i] * isocrt->GetN(); weight += fAbundances[i]; } neff /= weight; @@ -318,8 +312,8 @@ Double_t TGeoElement::Neff() const TGeoIsotope *TGeoElement::GetIsotope(Int_t i) const { - if (i>=0 && iAt(i); + if (i >= 0 && i < fNisotopes) { + return (TGeoIsotope *)fIsotopes->At(i); } return nullptr; } @@ -329,7 +323,8 @@ TGeoIsotope *TGeoElement::GetIsotope(Int_t i) const Double_t TGeoElement::GetRelativeAbundance(Int_t i) const { - if (i>=0 && i= 0 && i < fNisotopes) + return fAbundances[i]; return 0.0; } @@ -338,25 +333,17 @@ ClassImp(TGeoIsotope); //////////////////////////////////////////////////////////////////////////////// /// Dummy I/O constructor -TGeoIsotope::TGeoIsotope() - :TNamed(), - fZ(0), - fN(0), - fA(0) -{ -} +TGeoIsotope::TGeoIsotope() : TNamed(), fZ(0), fN(0), fA(0) {} //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoIsotope::TGeoIsotope(const char *name, Int_t z, Int_t n, Double_t a) - :TNamed(name,""), - fZ(z), - fN(n), - fA(a) +TGeoIsotope::TGeoIsotope(const char *name, Int_t z, Int_t n, Double_t a) : TNamed(name, ""), fZ(z), fN(n), fA(a) { - if (z<1) Fatal("ctor", "Not allowed Z=%d (<1) for isotope: %s", z,name); - if (nAddIsotope(this); } @@ -366,7 +353,8 @@ TGeoIsotope::TGeoIsotope(const char *name, Int_t z, Int_t n, Double_t a) TGeoIsotope *TGeoIsotope::FindIsotope(const char *name) { TGeoElementTable *elTable = TGeoElement::GetElementTable(); - if (!elTable) return 0; + if (!elTable) + return 0; return elTable->FindIsotope(name); } @@ -375,7 +363,7 @@ TGeoIsotope *TGeoIsotope::FindIsotope(const char *name) void TGeoIsotope::Print(Option_t *) const { - printf("Isotope: %s Z=%d N=%d A=%f [g/mole]\n", GetName(), fZ,fN,fA); + printf("Isotope: %s Z=%d N=%d A=%f [g/mole]\n", GetName(), fZ, fN, fA); } ClassImp(TGeoElementRN); @@ -385,49 +373,50 @@ ClassImp(TGeoElementRN); TGeoElementRN::TGeoElementRN() { - TObject::SetBit(kElementChecked,kFALSE); + TObject::SetBit(kElementChecked, kFALSE); fENDFcode = 0; - fIso = 0; - fLevel = 0; - fDeltaM = 0; + fIso = 0; + fLevel = 0; + fDeltaM = 0; fHalfLife = 0; - fNatAbun = 0; - fTH_F = 0; - fTG_F = 0; - fTH_S = 0; - fTG_S = 0; - fStatus = 0; - fRatio = 0; - fDecays = 0; + fNatAbun = 0; + fTH_F = 0; + fTG_F = 0; + fTH_S = 0; + fTG_S = 0; + fStatus = 0; + fRatio = 0; + fDecays = 0; } //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoElementRN::TGeoElementRN(Int_t aa, Int_t zz, Int_t iso, Double_t level, - Double_t deltaM, Double_t halfLife, const char* JP, - Double_t natAbun, Double_t th_f, Double_t tg_f, Double_t th_s, - Double_t tg_s, Int_t status) - :TGeoElement("", JP, zz, aa) -{ - TObject::SetBit(kElementChecked,kFALSE); - fENDFcode = ENDF(aa,zz,iso); - fIso = iso; - fLevel = level; - fDeltaM = deltaM; +TGeoElementRN::TGeoElementRN(Int_t aa, Int_t zz, Int_t iso, Double_t level, Double_t deltaM, Double_t halfLife, + const char *JP, Double_t natAbun, Double_t th_f, Double_t tg_f, Double_t th_s, + Double_t tg_s, Int_t status) + : TGeoElement("", JP, zz, aa) +{ + TObject::SetBit(kElementChecked, kFALSE); + fENDFcode = ENDF(aa, zz, iso); + fIso = iso; + fLevel = level; + fDeltaM = deltaM; fHalfLife = halfLife; - fTitle = JP; - if (!fTitle.Length()) fTitle = "?"; - fNatAbun = natAbun; - fTH_F = th_f; - fTG_F = tg_f; - fTH_S = th_s; - fTG_S = tg_s; - fStatus = status; - fDecays = 0; - fRatio = 0; - MakeName(aa,zz,iso); - if ((TMath::Abs(fHalfLife)<1.e-30) || fHalfLife<-1) Warning("ctor","Element %s has T1/2=%g [s]", fName.Data(), fHalfLife); + fTitle = JP; + if (!fTitle.Length()) + fTitle = "?"; + fNatAbun = natAbun; + fTH_F = th_f; + fTG_F = tg_f; + fTH_S = th_s; + fTG_S = tg_s; + fStatus = status; + fDecays = 0; + fRatio = 0; + MakeName(aa, zz, iso); + if ((TMath::Abs(fHalfLife) < 1.e-30) || fHalfLife < -1) + Warning("ctor", "Element %s has T1/2=%g [s]", fName.Data(), fHalfLife); } //////////////////////////////////////////////////////////////////////////////// @@ -439,7 +428,8 @@ TGeoElementRN::~TGeoElementRN() fDecays->Delete(); delete fDecays; } - if (fRatio) delete fRatio; + if (fRatio) + delete fRatio; } //////////////////////////////////////////////////////////////////////////////// @@ -447,15 +437,16 @@ TGeoElementRN::~TGeoElementRN() void TGeoElementRN::AddDecay(Int_t decay, Int_t diso, Double_t branchingRatio, Double_t qValue) { - if (branchingRatio<1E-20) { + if (branchingRatio < 1E-20) { TString decayName; TGeoDecayChannel::DecayName(decay, decayName); - Warning("AddDecay", "Decay %s of %s has BR=0. Not added.", decayName.Data(),fName.Data()); + Warning("AddDecay", "Decay %s of %s has BR=0. Not added.", decayName.Data(), fName.Data()); return; } - TGeoDecayChannel *dc = new TGeoDecayChannel(decay,diso,branchingRatio, qValue); + TGeoDecayChannel *dc = new TGeoDecayChannel(decay, diso, branchingRatio, qValue); dc->SetParent(this); - if (!fDecays) fDecays = new TObjArray(5); + if (!fDecays) + fDecays = new TObjArray(5); fDecays->Add(dc); } @@ -465,7 +456,8 @@ void TGeoElementRN::AddDecay(Int_t decay, Int_t diso, Double_t branchingRatio, D void TGeoElementRN::AddDecay(TGeoDecayChannel *dc) { dc->SetParent(this); - if (!fDecays) fDecays = new TObjArray(5); + if (!fDecays) + fDecays = new TObjArray(5); fDecays->Add(dc); } @@ -474,7 +466,8 @@ void TGeoElementRN::AddDecay(TGeoDecayChannel *dc) Int_t TGeoElementRN::GetNdecays() const { - if (!fDecays) return 0; + if (!fDecays) + return 0; return fDecays->GetEntriesFast(); } @@ -484,7 +477,7 @@ Int_t TGeoElementRN::GetNdecays() const Double_t TGeoElementRN::GetSpecificActivity() const { static const Double_t ln2 = TMath::Log(2.); - Double_t sa = (fHalfLife>0 && fA>0)?(ln2*TMath::Na()/fHalfLife/fA):0.; + Double_t sa = (fHalfLife > 0 && fA > 0) ? (ln2 * TMath::Na() / fHalfLife / fA) : 0.; return sa; } @@ -493,8 +486,9 @@ Double_t TGeoElementRN::GetSpecificActivity() const Bool_t TGeoElementRN::CheckDecays() const { - if (TObject::TestBit(kElementChecked)) return kTRUE; - TObject *oelem = (TObject*)this; + if (TObject::TestBit(kElementChecked)) + return kTRUE; + TObject *oelem = (TObject *)this; TGeoDecayChannel *dc; TGeoElementRN *elem; TGeoElementTable *table = GetElementTable(); @@ -505,31 +499,31 @@ Bool_t TGeoElementRN::CheckDecays() const } Bool_t resultOK = kTRUE; if (!fDecays) { - oelem->SetBit(kElementChecked,kTRUE); + oelem->SetBit(kElementChecked, kTRUE); return resultOK; } Double_t br = 0.; Int_t decayResult = 0; TIter next(fDecays); - while ((dc=(TGeoDecayChannel*)next())) { + while ((dc = (TGeoDecayChannel *)next())) { br += dc->BranchingRatio(); decayResult = DecayResult(dc); if (decayResult) { elem = table->GetElementRN(decayResult); if (!elem) { - TGeoDecayChannel::DecayName(dc->Decay(),decayName); - Error("CheckDecays", "Element after decay %s of %s not found in DB", decayName.Data(),fName.Data()); + TGeoDecayChannel::DecayName(dc->Decay(), decayName); + Error("CheckDecays", "Element after decay %s of %s not found in DB", decayName.Data(), fName.Data()); return kFALSE; } dc->SetDaughter(elem); resultOK = elem->CheckDecays(); } } - if (TMath::Abs(br-100) > 1.E-3) { + if (TMath::Abs(br - 100) > 1.E-3) { Warning("CheckDecays", "BR for decays of element %s sum-up = %f", fName.Data(), br); resultOK = kFALSE; } - oelem->SetBit(kElementChecked,kTRUE); + oelem->SetBit(kElementChecked, kTRUE); return resultOK; } @@ -540,8 +534,9 @@ Int_t TGeoElementRN::DecayResult(TGeoDecayChannel *dc) const { Int_t da, dz, diso; dc->DecayShift(da, dz, diso); - if (da == -99 || dz == -99) return 0; - return ENDF(Int_t(fA)+da,fZ+dz,fIso+diso); + if (da == -99 || dz == -99) + return 0; + return ENDF(Int_t(fA) + da, fZ + dz, fIso + diso); } //////////////////////////////////////////////////////////////////////////////// @@ -559,12 +554,14 @@ void TGeoElementRN::FillPopulation(TObjArray *population, Double_t precision, Do TGeoBatemanSol s(this); s.Normalize(factor); AddRatio(s); - if (!population->FindObject(this)) population->Add(this); - while ((elem=next())) { + if (!population->FindObject(this)) + population->Add(this); + while ((elem = next())) { TGeoBatemanSol ratio(next.GetBranch()); ratio.Normalize(factor); elem->AddRatio(ratio); - if (!population->FindObject(elem)) population->Add(elem); + if (!population->FindObject(elem)) + population->Add(elem); } } @@ -574,16 +571,21 @@ void TGeoElementRN::FillPopulation(TObjArray *population, Double_t precision, Do void TGeoElementRN::MakeName(Int_t a, Int_t z, Int_t iso) { fName = ""; - if (z==0 && a==1) { + if (z == 0 && a == 1) { fName = "neutron"; return; } - if (z>=1 && z<= gMaxElem) fName += TString::Format("%3d-%s-",z,gElName[z-1]); - else fName = "?? -?? -"; - if (a>=1 && a<=999) fName += TString::Format("%3.3d",a); - else fName += "??"; - if (iso>0 && iso= 1 && z <= gMaxElem) + fName += TString::Format("%3d-%s-", z, gElName[z - 1]); + else + fName = "?? -?? -"; + if (a >= 1 && a <= 999) + fName += TString::Format("%3.3d", a); + else + fName += "??"; + if (iso > 0 && iso < gMaxLevel) + fName += TString::Format("%c", gLevName[iso]); + fName.ReplaceAll(" ", ""); } //////////////////////////////////////////////////////////////////////////////// @@ -591,26 +593,30 @@ void TGeoElementRN::MakeName(Int_t a, Int_t z, Int_t iso) void TGeoElementRN::Print(Option_t *option) const { - printf("\n%-12s ",fName.Data()); - printf("ENDF=%d; ",fENDFcode); - printf("A=%d; ",(Int_t)fA); - printf("Z=%d; ",fZ); - printf("Iso=%d; ",fIso); - printf("Level=%g[MeV]; ",fLevel); - printf("Dmass=%g[MeV]; ",fDeltaM); - if (fHalfLife>0) printf("Hlife=%g[s]\n",fHalfLife); - else printf("Hlife=INF\n"); - printf("%13s"," "); - printf("J/P=%s; ",fTitle.Data()); - printf("Abund=%g; ",fNatAbun); - printf("Htox=%g; ",fTH_F); - printf("Itox=%g; ",fTG_F); - printf("Stat=%d\n",fStatus); - if(!fDecays) return; + printf("\n%-12s ", fName.Data()); + printf("ENDF=%d; ", fENDFcode); + printf("A=%d; ", (Int_t)fA); + printf("Z=%d; ", fZ); + printf("Iso=%d; ", fIso); + printf("Level=%g[MeV]; ", fLevel); + printf("Dmass=%g[MeV]; ", fDeltaM); + if (fHalfLife > 0) + printf("Hlife=%g[s]\n", fHalfLife); + else + printf("Hlife=INF\n"); + printf("%13s", " "); + printf("J/P=%s; ", fTitle.Data()); + printf("Abund=%g; ", fNatAbun); + printf("Htox=%g; ", fTH_F); + printf("Itox=%g; ", fTG_F); + printf("Stat=%d\n", fStatus); + if (!fDecays) + return; printf("Decay modes:\n"); TIter next(fDecays); TGeoDecayChannel *dc; - while ((dc=(TGeoDecayChannel*)next())) dc->Print(option); + while ((dc = (TGeoDecayChannel *)next())) + dc->Print(option); } //////////////////////////////////////////////////////////////////////////////// @@ -618,13 +624,13 @@ void TGeoElementRN::Print(Option_t *option) const TGeoElementRN *TGeoElementRN::ReadElementRN(const char *line, Int_t &ndecays) { - Int_t a,z,iso,status; + Int_t a, z, iso, status; Double_t level, deltaM, halfLife, natAbun, th_f, tg_f, th_s, tg_s; - char name[20],jp[20]; - sscanf(&line[0], "%s%d%d%d%lg%lg%lg%s%lg%lg%lg%lg%lg%d%d", name,&a,&z,&iso,&level,&deltaM, - &halfLife,jp,&natAbun,&th_f,&tg_f,&th_s,&tg_s,&status,&ndecays); - TGeoElementRN *elem = new TGeoElementRN(a,z,iso,level,deltaM,halfLife, - jp,natAbun,th_f,tg_f,th_s,tg_s,status); + char name[20], jp[20]; + sscanf(&line[0], "%s%d%d%d%lg%lg%lg%s%lg%lg%lg%lg%lg%d%d", name, &a, &z, &iso, &level, &deltaM, &halfLife, jp, + &natAbun, &th_f, &tg_f, &th_s, &tg_s, &status, &ndecays); + TGeoElementRN *elem = + new TGeoElementRN(a, z, iso, level, deltaM, halfLife, jp, natAbun, th_f, tg_f, th_s, tg_s, status); return elem; } @@ -633,11 +639,17 @@ TGeoElementRN *TGeoElementRN::ReadElementRN(const char *line, Int_t &ndecays) void TGeoElementRN::SavePrimitive(std::ostream &out, Option_t *option) { - if (!strcmp(option,"h")) { + if (!strcmp(option, "h")) { // print a header if requested - out << "#====================================================================================================================================" << std::endl; - out << "# Name A Z ISO LEV[MeV] DM[MeV] T1/2[s] J/P ABUND[%] HTOX ITOX HTOX ITOX STAT NDCY" << std::endl; - out << "#====================================================================================================================================" << std::endl; + out << "#========================================================================================================" + "============================" + << std::endl; + out << "# Name A Z ISO LEV[MeV] DM[MeV] T1/2[s] J/P ABUND[%] HTOX ITOX " + "HTOX ITOX STAT NDCY" + << std::endl; + out << "#========================================================================================================" + "============================" + << std::endl; } out << std::setw(11) << fName.Data(); out << std::setw(5) << (Int_t)fA; @@ -654,13 +666,15 @@ void TGeoElementRN::SavePrimitive(std::ostream &out, Option_t *option) out << std::setw(10) << std::setiosflags(std::ios::fixed) << std::setprecision(5) << fTG_S; out << std::setw(5) << fStatus; Int_t ndecays = 0; - if (fDecays) ndecays = fDecays->GetEntries(); + if (fDecays) + ndecays = fDecays->GetEntries(); out << std::setw(5) << ndecays; out << std::endl; if (fDecays) { TIter next(fDecays); TGeoDecayChannel *dc; - while ((dc=(TGeoDecayChannel*)next())) dc->SavePrimitive(out); + while ((dc = (TGeoDecayChannel *)next())) + dc->SavePrimitive(out); } } @@ -669,8 +683,10 @@ void TGeoElementRN::SavePrimitive(std::ostream &out, Option_t *option) void TGeoElementRN::AddRatio(TGeoBatemanSol &ratio) { - if (!fRatio) fRatio = new TGeoBatemanSol(ratio); - else *fRatio += ratio; + if (!fRatio) + fRatio = new TGeoBatemanSol(ratio); + else + *fRatio += ratio; } //////////////////////////////////////////////////////////////////////////////// @@ -688,18 +704,18 @@ ClassImp(TGeoDecayChannel); //////////////////////////////////////////////////////////////////////////////// /// Assignment. -///assignment operator +/// assignment operator -TGeoDecayChannel& TGeoDecayChannel::operator=(const TGeoDecayChannel& dc) +TGeoDecayChannel &TGeoDecayChannel::operator=(const TGeoDecayChannel &dc) { - if(this!=&dc) { + if (this != &dc) { TObject::operator=(dc); - fDecay = dc.fDecay; - fDiso = dc.fDiso; + fDecay = dc.fDecay; + fDiso = dc.fDiso; fBranchingRatio = dc.fBranchingRatio; - fQvalue = dc.fQvalue; - fParent = dc.fParent; - fDaughter = dc.fDaughter; + fQvalue = dc.fQvalue; + fParent = dc.fParent; + fDaughter = dc.fDaughter; } return *this; } @@ -711,10 +727,12 @@ const char *TGeoDecayChannel::GetName() const { static TString name = ""; name = ""; - if (!fDecay) return gDecayName[gMaxDecay]; - for (Int_t i=0; iAdd(iter.fBranch->At(i)); + for (Int_t i = 0; i < fLevel; i++) + fBranch->Add(iter.fBranch->At(i)); } } @@ -837,7 +857,8 @@ TGeoElemIter::TGeoElemIter(const TGeoElemIter &iter) TGeoElemIter::~TGeoElemIter() { - if (fBranch) delete fBranch; + if (fBranch) + delete fBranch; } //////////////////////////////////////////////////////////////////////////////// @@ -845,13 +866,15 @@ TGeoElemIter::~TGeoElemIter() TGeoElemIter &TGeoElemIter::operator=(const TGeoElemIter &iter) { - if (&iter == this) return *this; - fTop = iter.fTop; - fElem = iter.fElem; + if (&iter == this) + return *this; + fTop = iter.fTop; + fElem = iter.fElem; fLevel = iter.fLevel; if (iter.fBranch) { fBranch = new TObjArray(10); - for (Int_t i=0; iAdd(iter.fBranch->At(i)); + for (Int_t i = 0; i < fLevel; i++) + fBranch->Add(iter.fBranch->At(i)); } fLimitRatio = iter.fLimitRatio; fRatio = iter.fRatio; @@ -875,15 +898,16 @@ TGeoElementRN *TGeoElemIter::Up() Int_t ind, nd; while (fLevel) { // Current decay channel - dc = (TGeoDecayChannel*)fBranch->At(fLevel-1); + dc = (TGeoDecayChannel *)fBranch->At(fLevel - 1); ind = dc->GetIndex(); nd = dc->Parent()->GetNdecays(); - fRatio /= 0.01*dc->BranchingRatio(); + fRatio /= 0.01 * dc->BranchingRatio(); fElem = dc->Parent(); fBranch->RemoveAt(--fLevel); ind++; - while (indDecays()->At(ibranch); - if (!dc->Daughter()) return nullptr; - Double_t br = 0.01*fRatio*dc->BranchingRatio(); - if (br < fLimitRatio) return nullptr; + if (!fElem) + return nullptr; + TGeoDecayChannel *dc = (TGeoDecayChannel *)fElem->Decays()->At(ibranch); + if (!dc->Daughter()) + return nullptr; + Double_t br = 0.01 * fRatio * dc->BranchingRatio(); + if (br < fLimitRatio) + return nullptr; fLevel++; fRatio = br; fBranch->Add(dc); fElem = dc->Daughter(); - return (TGeoElementRN*)fElem; + return (TGeoElementRN *)fElem; } //////////////////////////////////////////////////////////////////////////////// @@ -913,10 +940,13 @@ TGeoElementRN *TGeoElemIter::Down(Int_t ibranch) TGeoElementRN *TGeoElemIter::Next() { - if (!fElem) return nullptr; + if (!fElem) + return nullptr; // Check if this is the first iteration. Int_t nd = fElem->GetNdecays(); - for (Int_t i=0; iAt(i); + printf("=== Chain with %g %%\n", 100 * fRatio); + for (Int_t i = 0; i < fLevel; i++) { + dc = (TGeoDecayChannel *)fBranch->At(i); elem = dc->Parent(); - printf("%s%s (%g%% %s) T1/2=%g\n", indent.Data(), elem->GetName(),dc->BranchingRatio(),dc->GetName(),elem->HalfLife()); + printf("%s%s (%g%% %s) T1/2=%g\n", indent.Data(), elem->GetName(), dc->BranchingRatio(), dc->GetName(), + elem->HalfLife()); indent += " "; - if (i==fLevel-1) { + if (i == fLevel - 1) { elem = dc->Daughter(); printf("%s%s\n", indent.Data(), elem->GetName()); } @@ -951,8 +982,8 @@ TGeoElementTable::TGeoElementTable() fNelements = 0; fNelementsRN = 0; fNisotopes = 0; - fList = 0; - fListRN = 0; + fList = 0; + fListRN = 0; fIsotopes = 0; } @@ -965,38 +996,38 @@ TGeoElementTable::TGeoElementTable(Int_t /*nelements*/) fNelementsRN = 0; fNisotopes = 0; fList = new TObjArray(128); - fListRN = 0; + fListRN = 0; fIsotopes = 0; BuildDefaultElements(); -// BuildElementsRN(); + // BuildElementsRN(); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoElementTable::TGeoElementTable(const TGeoElementTable& get) : - TObject(get), - fNelements(get.fNelements), - fNelementsRN(get.fNelementsRN), - fNisotopes(get.fNisotopes), - fList(get.fList), - fListRN(get.fListRN), - fIsotopes(0) +TGeoElementTable::TGeoElementTable(const TGeoElementTable &get) + : TObject(get), + fNelements(get.fNelements), + fNelementsRN(get.fNelementsRN), + fNisotopes(get.fNisotopes), + fList(get.fList), + fListRN(get.fListRN), + fIsotopes(0) { } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoElementTable& TGeoElementTable::operator=(const TGeoElementTable& get) +TGeoElementTable &TGeoElementTable::operator=(const TGeoElementTable &get) { - if(this!=&get) { + if (this != &get) { TObject::operator=(get); - fNelements=get.fNelements; - fNelementsRN=get.fNelementsRN; - fNisotopes=get.fNisotopes; - fList=get.fList; - fListRN=get.fListRN; + fNelements = get.fNelements; + fNelementsRN = get.fNelementsRN; + fNisotopes = get.fNisotopes; + fList = get.fList; + fListRN = get.fListRN; fIsotopes = 0; } return *this; @@ -1026,8 +1057,9 @@ TGeoElementTable::~TGeoElementTable() void TGeoElementTable::AddElement(const char *name, const char *title, Int_t z, Double_t a) { - if (!fList) fList = new TObjArray(128); - fList->AddAtAndExpand(new TGeoElement(name,title,z,a), fNelements++); + if (!fList) + fList = new TObjArray(128); + fList->AddAtAndExpand(new TGeoElement(name, title, z, a), fNelements++); } //////////////////////////////////////////////////////////////////////////////// @@ -1035,8 +1067,9 @@ void TGeoElementTable::AddElement(const char *name, const char *title, Int_t z, void TGeoElementTable::AddElement(const char *name, const char *title, Int_t z, Int_t n, Double_t a) { - if (!fList) fList = new TObjArray(128); - fList->AddAtAndExpand(new TGeoElement(name,title,z,n,a), fNelements++); + if (!fList) + fList = new TObjArray(128); + fList->AddAtAndExpand(new TGeoElement(name, title, z, n, a), fNelements++); } //////////////////////////////////////////////////////////////////////////////// @@ -1044,11 +1077,12 @@ void TGeoElementTable::AddElement(const char *name, const char *title, Int_t z, void TGeoElementTable::AddElement(TGeoElement *elem) { - if (!fList) fList = new TObjArray(128); + if (!fList) + fList = new TObjArray(128); TGeoElement *orig = FindElement(elem->GetName()); if (orig) { - Error("AddElement", "Found element with same name: %s (%s). Cannot add to table.", - orig->GetName(), orig->GetTitle()); + Error("AddElement", "Found element with same name: %s (%s). Cannot add to table.", orig->GetName(), + orig->GetTitle()); return; } fList->AddAtAndExpand(elem, fNelements++); @@ -1059,9 +1093,11 @@ void TGeoElementTable::AddElement(TGeoElement *elem) void TGeoElementTable::AddElementRN(TGeoElementRN *elem) { - if (!fListRN) fListRN = new TObjArray(3600); - if (HasRNElements() && GetElementRN(elem->ENDFCode())) return; -// elem->Print(); + if (!fListRN) + fListRN = new TObjArray(3600); + if (HasRNElements() && GetElementRN(elem->ENDFCode())) + return; + // elem->Print(); fListRN->Add(elem); fNelementsRN++; fElementsRN.insert(ElementRNMap_t::value_type(elem->ENDFCode(), elem)); @@ -1073,10 +1109,11 @@ void TGeoElementTable::AddElementRN(TGeoElementRN *elem) void TGeoElementTable::AddIsotope(TGeoIsotope *isotope) { if (FindIsotope(isotope->GetName())) { - Error("AddIsotope", "Isotope with the same name: %s already in table. Not adding.",isotope->GetName()); + Error("AddIsotope", "Isotope with the same name: %s already in table. Not adding.", isotope->GetName()); return; } - if (!fIsotopes) fIsotopes = new TObjArray(); + if (!fIsotopes) + fIsotopes = new TObjArray(); fIsotopes->Add(isotope); } @@ -1085,122 +1122,123 @@ void TGeoElementTable::AddIsotope(TGeoIsotope *isotope) void TGeoElementTable::BuildDefaultElements() { - if (HasDefaultElements()) return; - AddElement("VACUUM","VACUUM" ,0, 0, 0.0); - AddElement("H" ,"HYDROGEN" ,1, 1, 1.00794); - AddElement("HE" ,"HELIUM" ,2, 4, 4.002602); - AddElement("LI" ,"LITHIUM" ,3, 7, 6.941); - AddElement("BE" ,"BERYLLIUM" ,4, 9, 9.01218); - AddElement("B" ,"BORON" ,5, 11, 10.811); - AddElement("C" ,"CARBON" ,6, 12, 12.0107); - AddElement("N" ,"NITROGEN" ,7, 14, 14.00674); - AddElement("O" ,"OXYGEN" ,8, 16, 15.9994); - AddElement("F" ,"FLUORINE" ,9, 19, 18.9984032); - AddElement("NE" ,"NEON" ,10, 20, 20.1797); - AddElement("NA" ,"SODIUM" ,11, 23, 22.989770); - AddElement("MG" ,"MAGNESIUM" ,12, 24, 24.3050); - AddElement("AL" ,"ALUMINIUM" ,13, 27, 26.981538); - AddElement("SI" ,"SILICON" ,14, 28, 28.0855); - AddElement("P" ,"PHOSPHORUS" ,15, 31, 30.973761); - AddElement("S" ,"SULFUR" ,16, 32, 32.066); - AddElement("CL" ,"CHLORINE" ,17, 35, 35.4527); - AddElement("AR" ,"ARGON" ,18, 40, 39.948); - AddElement("K" ,"POTASSIUM" ,19, 39, 39.0983); - AddElement("CA" ,"CALCIUM" ,20, 40, 40.078); - AddElement("SC" ,"SCANDIUM" ,21, 45, 44.955910); - AddElement("TI" ,"TITANIUM" ,22, 48, 47.867); - AddElement("V" ,"VANADIUM" ,23, 51, 50.9415); - AddElement("CR" ,"CHROMIUM" ,24, 52, 51.9961); - AddElement("MN" ,"MANGANESE" ,25, 55, 54.938049); - AddElement("FE" ,"IRON" ,26, 56, 55.845); - AddElement("CO" ,"COBALT" ,27, 59, 58.933200); - AddElement("NI" ,"NICKEL" ,28, 59, 58.6934); - AddElement("CU" ,"COPPER" ,29, 64, 63.546); - AddElement("ZN" ,"ZINC" ,30, 65, 65.39); - AddElement("GA" ,"GALLIUM" ,31, 70, 69.723); - AddElement("GE" ,"GERMANIUM" ,32, 73, 72.61); - AddElement("AS" ,"ARSENIC" ,33, 75, 74.92160); - AddElement("SE" ,"SELENIUM" ,34, 79, 78.96); - AddElement("BR" ,"BROMINE" ,35, 80, 79.904); - AddElement("KR" ,"KRYPTON" ,36, 84, 83.80); - AddElement("RB" ,"RUBIDIUM" ,37, 85, 85.4678); - AddElement("SR" ,"STRONTIUM" ,38, 88, 87.62); - AddElement("Y" ,"YTTRIUM" ,39, 89, 88.90585); - AddElement("ZR" ,"ZIRCONIUM" ,40, 91, 91.224); - AddElement("NB" ,"NIOBIUM" ,41, 93, 92.90638); - AddElement("MO" ,"MOLYBDENUM" ,42, 96, 95.94); - AddElement("TC" ,"TECHNETIUM" ,43, 98, 98.0); - AddElement("RU" ,"RUTHENIUM" ,44, 101, 101.07); - AddElement("RH" ,"RHODIUM" ,45, 103, 102.90550); - AddElement("PD" ,"PALLADIUM" ,46, 106, 106.42); - AddElement("AG" ,"SILVER" ,47, 108, 107.8682); - AddElement("CD" ,"CADMIUM" ,48, 112, 112.411); - AddElement("IN" ,"INDIUM" ,49, 115, 114.818); - AddElement("SN" ,"TIN" ,50, 119, 118.710); - AddElement("SB" ,"ANTIMONY" ,51, 122, 121.760); - AddElement("TE" ,"TELLURIUM" ,52, 128, 127.60); - AddElement("I" ,"IODINE" ,53, 127, 126.90447); - AddElement("XE" ,"XENON" ,54, 131, 131.29); - AddElement("CS" ,"CESIUM" ,55, 133, 132.90545); - AddElement("BA" ,"BARIUM" ,56, 137, 137.327); - AddElement("LA" ,"LANTHANUM" ,57, 139, 138.9055); - AddElement("CE" ,"CERIUM" ,58, 140, 140.116); - AddElement("PR" ,"PRASEODYMIUM" ,59, 141, 140.90765); - AddElement("ND" ,"NEODYMIUM" ,60, 144, 144.24); - AddElement("PM" ,"PROMETHIUM" ,61, 145, 145.0); - AddElement("SM" ,"SAMARIUM" ,62, 150, 150.36); - AddElement("EU" ,"EUROPIUM" ,63, 152, 151.964); - AddElement("GD" ,"GADOLINIUM" ,64, 157, 157.25); - AddElement("TB" ,"TERBIUM" ,65, 159, 158.92534); - AddElement("DY" ,"DYSPROSIUM" ,66, 162, 162.50); - AddElement("HO" ,"HOLMIUM" ,67, 165, 164.93032); - AddElement("ER" ,"ERBIUM" ,68, 167, 167.26); - AddElement("TM" ,"THULIUM" ,69, 169, 168.93421); - AddElement("YB" ,"YTTERBIUM" ,70, 173, 173.04); - AddElement("LU" ,"LUTETIUM" ,71, 175, 174.967); - AddElement("HF" ,"HAFNIUM" ,72, 178, 178.49); - AddElement("TA" ,"TANTALUM" ,73, 181, 180.9479); - AddElement("W" ,"TUNGSTEN" ,74, 184, 183.84); - AddElement("RE" ,"RHENIUM" ,75, 186, 186.207); - AddElement("OS" ,"OSMIUM" ,76, 190, 190.23); - AddElement("IR" ,"IRIDIUM" ,77, 192, 192.217); - AddElement("PT" ,"PLATINUM" ,78, 195, 195.078); - AddElement("AU" ,"GOLD" ,79, 197, 196.96655); - AddElement("HG" ,"MERCURY" ,80, 200, 200.59); - AddElement("TL" ,"THALLIUM" ,81, 204, 204.3833); - AddElement("PB" ,"LEAD" ,82, 207, 207.2); - AddElement("BI" ,"BISMUTH" ,83, 209, 208.98038); - AddElement("PO" ,"POLONIUM" ,84, 209, 209.0); - AddElement("AT" ,"ASTATINE" ,85, 210, 210.0); - AddElement("RN" ,"RADON" ,86, 222, 222.0); - AddElement("FR" ,"FRANCIUM" ,87, 223, 223.0); - AddElement("RA" ,"RADIUM" ,88, 226, 226.0); - AddElement("AC" ,"ACTINIUM" ,89, 227, 227.0); - AddElement("TH" ,"THORIUM" ,90, 232, 232.0381); - AddElement("PA" ,"PROTACTINIUM" ,91, 231, 231.03588); - AddElement("U" ,"URANIUM" ,92, 238, 238.0289); - AddElement("NP" ,"NEPTUNIUM" ,93, 237, 237.0); - AddElement("PU" ,"PLUTONIUM" ,94, 244, 244.0); - AddElement("AM" ,"AMERICIUM" ,95, 243, 243.0); - AddElement("CM" ,"CURIUM" ,96, 247, 247.0); - AddElement("BK" ,"BERKELIUM" ,97, 247, 247.0); - AddElement("CF" ,"CALIFORNIUM",98, 251, 251.0); - AddElement("ES" ,"EINSTEINIUM",99, 252, 252.0); - AddElement("FM" ,"FERMIUM" ,100, 257, 257.0); - AddElement("MD" ,"MENDELEVIUM",101, 258, 258.0); - AddElement("NO" ,"NOBELIUM" ,102, 259, 259.0); - AddElement("LR" ,"LAWRENCIUM" ,103, 262, 262.0); - AddElement("RF" ,"RUTHERFORDIUM",104, 261, 261.0); - AddElement("DB" ,"DUBNIUM" ,105, 262, 262.0); - AddElement("SG" ,"SEABORGIUM" ,106, 263, 263.0); - AddElement("BH" ,"BOHRIUM" ,107, 262, 262.0); - AddElement("HS" ,"HASSIUM" ,108, 265, 265.0); - AddElement("MT" ,"MEITNERIUM" ,109, 266, 266.0); - AddElement("UUN" ,"UNUNNILIUM" ,110, 269, 269.0); - AddElement("UUU" ,"UNUNUNIUM" ,111, 272, 272.0); - AddElement("UUB" ,"UNUNBIUM" ,112, 277, 277.0); - - TObject::SetBit(kETDefaultElements,kTRUE); + if (HasDefaultElements()) + return; + AddElement("VACUUM", "VACUUM", 0, 0, 0.0); + AddElement("H", "HYDROGEN", 1, 1, 1.00794); + AddElement("HE", "HELIUM", 2, 4, 4.002602); + AddElement("LI", "LITHIUM", 3, 7, 6.941); + AddElement("BE", "BERYLLIUM", 4, 9, 9.01218); + AddElement("B", "BORON", 5, 11, 10.811); + AddElement("C", "CARBON", 6, 12, 12.0107); + AddElement("N", "NITROGEN", 7, 14, 14.00674); + AddElement("O", "OXYGEN", 8, 16, 15.9994); + AddElement("F", "FLUORINE", 9, 19, 18.9984032); + AddElement("NE", "NEON", 10, 20, 20.1797); + AddElement("NA", "SODIUM", 11, 23, 22.989770); + AddElement("MG", "MAGNESIUM", 12, 24, 24.3050); + AddElement("AL", "ALUMINIUM", 13, 27, 26.981538); + AddElement("SI", "SILICON", 14, 28, 28.0855); + AddElement("P", "PHOSPHORUS", 15, 31, 30.973761); + AddElement("S", "SULFUR", 16, 32, 32.066); + AddElement("CL", "CHLORINE", 17, 35, 35.4527); + AddElement("AR", "ARGON", 18, 40, 39.948); + AddElement("K", "POTASSIUM", 19, 39, 39.0983); + AddElement("CA", "CALCIUM", 20, 40, 40.078); + AddElement("SC", "SCANDIUM", 21, 45, 44.955910); + AddElement("TI", "TITANIUM", 22, 48, 47.867); + AddElement("V", "VANADIUM", 23, 51, 50.9415); + AddElement("CR", "CHROMIUM", 24, 52, 51.9961); + AddElement("MN", "MANGANESE", 25, 55, 54.938049); + AddElement("FE", "IRON", 26, 56, 55.845); + AddElement("CO", "COBALT", 27, 59, 58.933200); + AddElement("NI", "NICKEL", 28, 59, 58.6934); + AddElement("CU", "COPPER", 29, 64, 63.546); + AddElement("ZN", "ZINC", 30, 65, 65.39); + AddElement("GA", "GALLIUM", 31, 70, 69.723); + AddElement("GE", "GERMANIUM", 32, 73, 72.61); + AddElement("AS", "ARSENIC", 33, 75, 74.92160); + AddElement("SE", "SELENIUM", 34, 79, 78.96); + AddElement("BR", "BROMINE", 35, 80, 79.904); + AddElement("KR", "KRYPTON", 36, 84, 83.80); + AddElement("RB", "RUBIDIUM", 37, 85, 85.4678); + AddElement("SR", "STRONTIUM", 38, 88, 87.62); + AddElement("Y", "YTTRIUM", 39, 89, 88.90585); + AddElement("ZR", "ZIRCONIUM", 40, 91, 91.224); + AddElement("NB", "NIOBIUM", 41, 93, 92.90638); + AddElement("MO", "MOLYBDENUM", 42, 96, 95.94); + AddElement("TC", "TECHNETIUM", 43, 98, 98.0); + AddElement("RU", "RUTHENIUM", 44, 101, 101.07); + AddElement("RH", "RHODIUM", 45, 103, 102.90550); + AddElement("PD", "PALLADIUM", 46, 106, 106.42); + AddElement("AG", "SILVER", 47, 108, 107.8682); + AddElement("CD", "CADMIUM", 48, 112, 112.411); + AddElement("IN", "INDIUM", 49, 115, 114.818); + AddElement("SN", "TIN", 50, 119, 118.710); + AddElement("SB", "ANTIMONY", 51, 122, 121.760); + AddElement("TE", "TELLURIUM", 52, 128, 127.60); + AddElement("I", "IODINE", 53, 127, 126.90447); + AddElement("XE", "XENON", 54, 131, 131.29); + AddElement("CS", "CESIUM", 55, 133, 132.90545); + AddElement("BA", "BARIUM", 56, 137, 137.327); + AddElement("LA", "LANTHANUM", 57, 139, 138.9055); + AddElement("CE", "CERIUM", 58, 140, 140.116); + AddElement("PR", "PRASEODYMIUM", 59, 141, 140.90765); + AddElement("ND", "NEODYMIUM", 60, 144, 144.24); + AddElement("PM", "PROMETHIUM", 61, 145, 145.0); + AddElement("SM", "SAMARIUM", 62, 150, 150.36); + AddElement("EU", "EUROPIUM", 63, 152, 151.964); + AddElement("GD", "GADOLINIUM", 64, 157, 157.25); + AddElement("TB", "TERBIUM", 65, 159, 158.92534); + AddElement("DY", "DYSPROSIUM", 66, 162, 162.50); + AddElement("HO", "HOLMIUM", 67, 165, 164.93032); + AddElement("ER", "ERBIUM", 68, 167, 167.26); + AddElement("TM", "THULIUM", 69, 169, 168.93421); + AddElement("YB", "YTTERBIUM", 70, 173, 173.04); + AddElement("LU", "LUTETIUM", 71, 175, 174.967); + AddElement("HF", "HAFNIUM", 72, 178, 178.49); + AddElement("TA", "TANTALUM", 73, 181, 180.9479); + AddElement("W", "TUNGSTEN", 74, 184, 183.84); + AddElement("RE", "RHENIUM", 75, 186, 186.207); + AddElement("OS", "OSMIUM", 76, 190, 190.23); + AddElement("IR", "IRIDIUM", 77, 192, 192.217); + AddElement("PT", "PLATINUM", 78, 195, 195.078); + AddElement("AU", "GOLD", 79, 197, 196.96655); + AddElement("HG", "MERCURY", 80, 200, 200.59); + AddElement("TL", "THALLIUM", 81, 204, 204.3833); + AddElement("PB", "LEAD", 82, 207, 207.2); + AddElement("BI", "BISMUTH", 83, 209, 208.98038); + AddElement("PO", "POLONIUM", 84, 209, 209.0); + AddElement("AT", "ASTATINE", 85, 210, 210.0); + AddElement("RN", "RADON", 86, 222, 222.0); + AddElement("FR", "FRANCIUM", 87, 223, 223.0); + AddElement("RA", "RADIUM", 88, 226, 226.0); + AddElement("AC", "ACTINIUM", 89, 227, 227.0); + AddElement("TH", "THORIUM", 90, 232, 232.0381); + AddElement("PA", "PROTACTINIUM", 91, 231, 231.03588); + AddElement("U", "URANIUM", 92, 238, 238.0289); + AddElement("NP", "NEPTUNIUM", 93, 237, 237.0); + AddElement("PU", "PLUTONIUM", 94, 244, 244.0); + AddElement("AM", "AMERICIUM", 95, 243, 243.0); + AddElement("CM", "CURIUM", 96, 247, 247.0); + AddElement("BK", "BERKELIUM", 97, 247, 247.0); + AddElement("CF", "CALIFORNIUM", 98, 251, 251.0); + AddElement("ES", "EINSTEINIUM", 99, 252, 252.0); + AddElement("FM", "FERMIUM", 100, 257, 257.0); + AddElement("MD", "MENDELEVIUM", 101, 258, 258.0); + AddElement("NO", "NOBELIUM", 102, 259, 259.0); + AddElement("LR", "LAWRENCIUM", 103, 262, 262.0); + AddElement("RF", "RUTHERFORDIUM", 104, 261, 261.0); + AddElement("DB", "DUBNIUM", 105, 262, 262.0); + AddElement("SG", "SEABORGIUM", 106, 263, 263.0); + AddElement("BH", "BOHRIUM", 107, 262, 262.0); + AddElement("HS", "HASSIUM", 108, 265, 265.0); + AddElement("MT", "MEITNERIUM", 109, 266, 266.0); + AddElement("UUN", "UNUNNILIUM", 110, 269, 269.0); + AddElement("UUU", "UNUNUNIUM", 111, 272, 272.0); + AddElement("UUB", "UNUNBIUM", 112, 277, 277.0); + + TObject::SetBit(kETDefaultElements, kTRUE); } //////////////////////////////////////////////////////////////////////////////// @@ -1208,23 +1246,25 @@ void TGeoElementTable::BuildDefaultElements() void TGeoElementTable::ImportElementsRN() { - if (HasRNElements()) return; + if (HasRNElements()) + return; TGeoElementRN *elem; TString rnf = "RadioNuclides.txt"; gSystem->PrependPathName(TROOT::GetEtcDir(), rnf); FILE *fp = fopen(rnf, "r"); if (!fp) { - Error("ImportElementsRN","File RadioNuclides.txt not found"); + Error("ImportElementsRN", "File RadioNuclides.txt not found"); return; } char line[150]; Int_t ndecays = 0; Int_t i; - while (fgets(&line[0],140,fp)) { - if (line[0]=='#') continue; + while (fgets(&line[0], 140, fp)) { + if (line[0] == '#') + continue; elem = TGeoElementRN::ReadElementRN(line, ndecays); - for (i=0; iAddDecay(dc); } AddElementRN(elem); -// elem->Print(); + // elem->Print(); } - TObject::SetBit(kETRNElements,kTRUE); + TObject::SetBit(kETRNElements, kTRUE); CheckTable(); fclose(fp); } @@ -1245,12 +1285,14 @@ void TGeoElementTable::ImportElementsRN() Bool_t TGeoElementTable::CheckTable() const { - if (!HasRNElements()) return HasDefaultElements(); + if (!HasRNElements()) + return HasDefaultElements(); TGeoElementRN *elem; Bool_t result = kTRUE; TIter next(fListRN); - while ((elem=(TGeoElementRN*)next())) { - if (!elem->CheckDecays()) result = kFALSE; + while ((elem = (TGeoElementRN *)next())) { + if (!elem->CheckDecays()) + result = kFALSE; } return result; } @@ -1260,9 +1302,11 @@ Bool_t TGeoElementTable::CheckTable() const void TGeoElementTable::ExportElementsRN(const char *filename) { - if (!HasRNElements()) return; + if (!HasRNElements()) + return; TString sname = filename; - if (!sname.Length()) sname = "RadioNuclides.txt"; + if (!sname.Length()) + sname = "RadioNuclides.txt"; std::ofstream out; out.open(sname.Data(), std::ios::out); if (!out.good()) { @@ -1272,10 +1316,12 @@ void TGeoElementTable::ExportElementsRN(const char *filename) TGeoElementRN *elem; TIter next(fListRN); - Int_t i=0; - while ((elem=(TGeoElementRN*)next())) { - if ((i%48)==0) elem->SavePrimitive(out,"h"); - else elem->SavePrimitive(out); + Int_t i = 0; + while ((elem = (TGeoElementRN *)next())) { + if ((i % 48) == 0) + elem->SavePrimitive(out, "h"); + else + elem->SavePrimitive(out); i++; } out.close(); @@ -1288,17 +1334,20 @@ void TGeoElementTable::ExportElementsRN(const char *filename) TGeoElement *TGeoElementTable::FindElement(const char *name) const { TGeoElement *elem; - elem = (TGeoElement*)fList->FindObject(name); - if (elem) return elem; + elem = (TGeoElement *)fList->FindObject(name); + if (elem) + return elem; // Search case insensitive by element name TString s(name); s.ToUpper(); - elem = (TGeoElement*)fList->FindObject(s.Data()); - if (elem) return elem; + elem = (TGeoElement *)fList->FindObject(s.Data()); + if (elem) + return elem; // Search by full name TIter next(fList); - while ((elem=(TGeoElement*)next())) { - if (s == elem->GetTitle()) return elem; + while ((elem = (TGeoElement *)next())) { + if (s == elem->GetTitle()) + return elem; } return 0; } @@ -1308,8 +1357,9 @@ TGeoElement *TGeoElementTable::FindElement(const char *name) const TGeoIsotope *TGeoElementTable::FindIsotope(const char *name) const { - if (!fIsotopes) return nullptr; - return (TGeoIsotope*)fIsotopes->FindObject(name); + if (!fIsotopes) + return nullptr; + return (TGeoIsotope *)fIsotopes->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -1318,12 +1368,14 @@ TGeoIsotope *TGeoElementTable::FindIsotope(const char *name) const TGeoElementRN *TGeoElementTable::GetElementRN(Int_t ENDFcode) const { if (!HasRNElements()) { - TGeoElementTable *table = (TGeoElementTable*)this; + TGeoElementTable *table = (TGeoElementTable *)this; table->ImportElementsRN(); - if (!fListRN) return 0; + if (!fListRN) + return 0; } ElementRNMap_t::const_iterator it = fElementsRN.find(ENDFcode); - if (it != fElementsRN.end()) return it->second; + if (it != fElementsRN.end()) + return it->second; return 0; } @@ -1332,7 +1384,7 @@ TGeoElementRN *TGeoElementTable::GetElementRN(Int_t ENDFcode) const TGeoElementRN *TGeoElementTable::GetElementRN(Int_t a, Int_t z, Int_t iso) const { - return GetElementRN(TGeoElementRN::ENDF(a,z,iso)); + return GetElementRN(TGeoElementRN::ENDF(a, z, iso)); } //////////////////////////////////////////////////////////////////////////////// @@ -1349,28 +1401,32 @@ void TGeoElementTable::Print(Option_t *option) const opt.ToUpper(); Int_t induser = HasDefaultElements() ? 113 : 0; // Default elements - if (opt=="" || opt=="D") { - if (induser) printf("================\nDefault elements\n================\n"); - for (Int_t iel=0; ielAt(iel)->Print(); + if (opt == "" || opt == "D") { + if (induser) + printf("================\nDefault elements\n================\n"); + for (Int_t iel = 0; iel < induser; ++iel) + fList->At(iel)->Print(); } // Isotopes - if (opt=="" || opt=="I") { + if (opt == "" || opt == "I") { if (fIsotopes) { printf("================\nIsotopes\n================\n"); fIsotopes->Print(); } } // Radio-nuclides - if (opt=="" || opt=="R") { + if (opt == "" || opt == "R") { if (HasRNElements()) { printf("================\nRadio-nuclides\n================\n"); fListRN->Print(); } } // User-defined elements - if (opt=="" || opt=="U") { - if (fNelements>induser) printf("================\nUser elements\n================\n"); - for (Int_t iel=induser; ielAt(iel)->Print(); + if (opt == "" || opt == "U") { + if (fNelements > induser) + printf("================\nUser elements\n================\n"); + for (Int_t iel = induser; iel < fNelements; ++iel) + fList->At(iel)->Print(); } } @@ -1380,45 +1436,55 @@ ClassImp(TGeoBatemanSol); /// Default ctor. TGeoBatemanSol::TGeoBatemanSol(TGeoElementRN *elem) - :TObject(), TAttLine(), TAttFill(), TAttMarker(), - fElem(elem), - fElemTop(elem), - fCsize(10), - fNcoeff(0), - fFactor(1.), - fTmin(0.), - fTmax(0.), - fCoeff(nullptr) + : TObject(), + TAttLine(), + TAttFill(), + TAttMarker(), + fElem(elem), + fElemTop(elem), + fCsize(10), + fNcoeff(0), + fFactor(1.), + fTmin(0.), + fTmax(0.), + fCoeff(nullptr) { fCoeff = new BtCoef_t[fCsize]; fNcoeff = 1; fCoeff[0].cn = 1.; Double_t t12 = elem->HalfLife(); - if (t12 == 0.) t12 = 1.e-30; - if (elem->Stable()) fCoeff[0].lambda = 0.; - else fCoeff[0].lambda = TMath::Log(2.)/t12; + if (t12 == 0.) + t12 = 1.e-30; + if (elem->Stable()) + fCoeff[0].lambda = 0.; + else + fCoeff[0].lambda = TMath::Log(2.) / t12; } //////////////////////////////////////////////////////////////////////////////// /// Default ctor. TGeoBatemanSol::TGeoBatemanSol(const TObjArray *chain) - :TObject(), TAttLine(), TAttFill(), TAttMarker(), - fElem(nullptr), - fElemTop(nullptr), - fCsize(0), - fNcoeff(0), - fFactor(1.), - fTmin(0.), - fTmax(0.), - fCoeff(nullptr) -{ - TGeoDecayChannel *dc = (TGeoDecayChannel*)chain->At(0); - if (dc) fElemTop = dc->Parent(); - dc = (TGeoDecayChannel*)chain->At(chain->GetEntriesFast()-1); + : TObject(), + TAttLine(), + TAttFill(), + TAttMarker(), + fElem(nullptr), + fElemTop(nullptr), + fCsize(0), + fNcoeff(0), + fFactor(1.), + fTmin(0.), + fTmax(0.), + fCoeff(nullptr) +{ + TGeoDecayChannel *dc = (TGeoDecayChannel *)chain->At(0); + if (dc) + fElemTop = dc->Parent(); + dc = (TGeoDecayChannel *)chain->At(chain->GetEntriesFast() - 1); if (dc) { fElem = dc->Daughter(); - fCsize = chain->GetEntriesFast()+1; + fCsize = chain->GetEntriesFast() + 1; fCoeff = new BtCoef_t[fCsize]; FindSolution(chain); } @@ -1427,20 +1493,23 @@ TGeoBatemanSol::TGeoBatemanSol(const TObjArray *chain) //////////////////////////////////////////////////////////////////////////////// /// Copy constructor. -TGeoBatemanSol::TGeoBatemanSol(const TGeoBatemanSol& other) - :TObject(other), TAttLine(other), TAttFill(other), TAttMarker(other), - fElem(other.fElem), - fElemTop(other.fElemTop), - fCsize(other.fCsize), - fNcoeff(other.fNcoeff), - fFactor(other.fFactor), - fTmin(other.fTmin), - fTmax(other.fTmax), - fCoeff(nullptr) +TGeoBatemanSol::TGeoBatemanSol(const TGeoBatemanSol &other) + : TObject(other), + TAttLine(other), + TAttFill(other), + TAttMarker(other), + fElem(other.fElem), + fElemTop(other.fElemTop), + fCsize(other.fCsize), + fNcoeff(other.fNcoeff), + fFactor(other.fFactor), + fTmin(other.fTmin), + fTmax(other.fTmax), + fCoeff(nullptr) { if (fCsize) { fCoeff = new BtCoef_t[fCsize]; - for (Int_t i=0; i fCsize) { fCsize = ncoeff; coeff = new BtCoef_t[ncoeff]; - for (i=0; iGetGeomPainter()->DrawBatemanSol(this, option); } @@ -1557,74 +1630,84 @@ void TGeoBatemanSol::Draw(Option_t *option) void TGeoBatemanSol::FindSolution(const TObjArray *array) { fNcoeff = 0; - if (!array || !array->GetEntriesFast()) return; + if (!array || !array->GetEntriesFast()) + return; Int_t n = array->GetEntriesFast(); - TGeoDecayChannel *dc = (TGeoDecayChannel*)array->At(n-1); + TGeoDecayChannel *dc = (TGeoDecayChannel *)array->At(n - 1); TGeoElementRN *elem = dc->Daughter(); if (elem != fElem) { Error("FindSolution", "Last element in the list must be %s\n", fElem->GetName()); return; } - Int_t i,j; - Int_t order = n+1; + Int_t i, j; + Int_t order = n + 1; if (!fCoeff) { fCsize = order; fCoeff = new BtCoef_t[fCsize]; } if (fCsize < order) { - delete [] fCoeff; + delete[] fCoeff; fCsize = order; fCoeff = new BtCoef_t[fCsize]; } Double_t *lambda = new Double_t[order]; - Double_t *br = new Double_t[n]; + Double_t *br = new Double_t[n]; Double_t halflife; - for (i=0; iAt(i); + for (i = 0; i < n; i++) { + dc = (TGeoDecayChannel *)array->At(i); elem = dc->Parent(); br[i] = 0.01 * dc->BranchingRatio(); halflife = elem->HalfLife(); - if (halflife==0.) halflife = 1.e-30; - if (elem->Stable()) lambda[i] = 0.; - else lambda[i] = TMath::Log(2.)/halflife; - if (i==n-1) { + if (halflife == 0.) + halflife = 1.e-30; + if (elem->Stable()) + lambda[i] = 0.; + else + lambda[i] = TMath::Log(2.) / halflife; + if (i == n - 1) { elem = dc->Daughter(); halflife = elem->HalfLife(); - if (halflife==0.) halflife = 1.e-30; - if (elem->Stable()) lambda[n] = 0.; - else lambda[n] = TMath::Log(2.)/halflife; + if (halflife == 0.) + halflife = 1.e-30; + if (elem->Stable()) + lambda[n] = 0.; + else + lambda[n] = TMath::Log(2.) / halflife; } } // Check if we have equal lambdas - for (i=0; i #include "TGeoManager.h" @@ -61,8 +60,7 @@ TGeoEltu::TGeoEltu() //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying X and Y semiaxis length -TGeoEltu::TGeoEltu(Double_t a, Double_t b, Double_t dz) - :TGeoTube(0, 0, 0) +TGeoEltu::TGeoEltu(Double_t a, Double_t b, Double_t dz) : TGeoTube(0, 0, 0) { SetShapeBit(TGeoShape::kGeoEltu); SetEltuDimensions(a, b, dz); @@ -72,8 +70,7 @@ TGeoEltu::TGeoEltu(Double_t a, Double_t b, Double_t dz) //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying X and Y semiaxis length -TGeoEltu::TGeoEltu(const char *name, Double_t a, Double_t b, Double_t dz) - :TGeoTube(name,0.,b,dz) +TGeoEltu::TGeoEltu(const char *name, Double_t a, Double_t b, Double_t dz) : TGeoTube(name, 0., b, dz) { SetName(name); SetShapeBit(TGeoShape::kGeoEltu); @@ -97,16 +94,14 @@ TGeoEltu::TGeoEltu(Double_t *param) //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoEltu::~TGeoEltu() -{ -} +TGeoEltu::~TGeoEltu() {} //////////////////////////////////////////////////////////////////////////////// /// Computes capacity of the shape in [length^3] Double_t TGeoEltu::Capacity() const { - Double_t capacity = 2.*TMath::Pi()*fDz*fRmin*fRmax; + Double_t capacity = 2. * TMath::Pi() * fDz * fRmin * fRmax; return capacity; } @@ -127,17 +122,17 @@ void TGeoEltu::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ { Double_t a = fRmin; Double_t b = fRmax; - Double_t safr = TMath::Abs(TMath::Sqrt(point[0]*point[0]/(a*a)+point[1]*point[1]/(b*b))-1.); - safr *= TMath::Min(a,b); - Double_t safz = TMath::Abs(fDz-TMath::Abs(point[2])); - if (safz fDz) return kFALSE; - Double_t r2 = (point[0]*point[0])/(fRmin*fRmin)+(point[1]*point[1])/(fRmax*fRmax); - if (r2>1.) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; + Double_t r2 = (point[0] * point[0]) / (fRmin * fRmin) + (point[1] * point[1]) / (fRmax * fRmax); + if (r2 > 1.) + return kFALSE; return kTRUE; } @@ -158,154 +155,176 @@ Bool_t TGeoEltu::Contains(const Double_t *point) const Int_t TGeoEltu::DistancetoPrimitive(Int_t px, Int_t py) { Int_t n = gGeoManager->GetNsegments(); - const Int_t numPoints=4*n; + const Int_t numPoints = 4 * n; return ShapeDistancetoPrimitive(numPoints, px, py); } //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the tube -Double_t TGeoEltu::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoEltu::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - Double_t a2=fRmin*fRmin; - Double_t b2=fRmax*fRmax; - Double_t safz1=fDz-point[2]; - Double_t safz2=fDz+point[2]; - - if (iact<3 && safe) { - Double_t x0=TMath::Abs(point[0]); - Double_t y0=TMath::Abs(point[1]); - Double_t x1=x0; - Double_t y1=TMath::Sqrt((fRmin-x0)*(fRmin+x0))*fRmax/fRmin; - Double_t y2=y0; - Double_t x2=TMath::Sqrt((fRmax-y0)*(fRmax+y0))*fRmin/fRmax; - Double_t d1=(x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); - Double_t d2=(x2-x0)*(x2-x0)+(y2-y0)*(y2-y0); - Double_t x3,y3; - - Double_t safz = TMath::Min(safz1,safz2); - for (Int_t i=0; i<8; i++) { - if (fRmaxstep)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // compute distance to surface // Do Z Double_t snxt = TGeoShape::Big(); - if (dir[2]>0) { - snxt=safz1/dir[2]; + if (dir[2] > 0) { + snxt = safz1 / dir[2]; } else { - if (dir[2]<0) snxt=-safz2/dir[2]; + if (dir[2] < 0) + snxt = -safz2 / dir[2]; } Double_t sz = snxt; - Double_t xz=point[0]+dir[0]*sz; - Double_t yz=point[1]+dir[1]*sz; - if ((xz*xz/a2+yz*yz/b2)<=1) return snxt; + Double_t xz = point[0] + dir[0] * sz; + Double_t yz = point[1] + dir[1] * sz; + if ((xz * xz / a2 + yz * yz / b2) <= 1) + return snxt; // do elliptical surface Double_t tolerance = TGeoShape::Tolerance(); - Double_t u=dir[0]*dir[0]*b2+dir[1]*dir[1]*a2; - Double_t v=point[0]*dir[0]*b2+point[1]*dir[1]*a2; - Double_t w=point[0]*point[0]*b2+point[1]*point[1]*a2-a2*b2; - Double_t d=v*v-u*w; - if (d<0 || TGeoShape::IsSameWithinTolerance(u,0)) return tolerance; - Double_t sd=TMath::Sqrt(d); - snxt = (-v+sd)/u; - - if (snxt<0) return tolerance; + Double_t u = dir[0] * dir[0] * b2 + dir[1] * dir[1] * a2; + Double_t v = point[0] * dir[0] * b2 + point[1] * dir[1] * a2; + Double_t w = point[0] * point[0] * b2 + point[1] * point[1] * a2 - a2 * b2; + Double_t d = v * v - u * w; + if (d < 0 || TGeoShape::IsSameWithinTolerance(u, 0)) + return tolerance; + Double_t sd = TMath::Sqrt(d); + snxt = (-v + sd) / u; + + if (snxt < 0) + return tolerance; return snxt; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the tube and safe distance -Double_t TGeoEltu::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoEltu::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - Double_t safz=TMath::Abs(point[2])-fDz; - Double_t a2=fRmin*fRmin; - Double_t b2=fRmax*fRmax; - if (iact<3 && safe) { - Double_t x0=TMath::Abs(point[0]); - Double_t y0=TMath::Abs(point[1]); - *safe=0.; - if ((x0*x0/a2+y0*y0/b2)>=1) { - Double_t phi1=0; - Double_t phi2=0.5*TMath::Pi(); + Double_t safz = TMath::Abs(point[2]) - fDz; + Double_t a2 = fRmin * fRmin; + Double_t b2 = fRmax * fRmax; + if (iact < 3 && safe) { + Double_t x0 = TMath::Abs(point[0]); + Double_t y0 = TMath::Abs(point[1]); + *safe = 0.; + if ((x0 * x0 / a2 + y0 * y0 / b2) >= 1) { + Double_t phi1 = 0; + Double_t phi2 = 0.5 * TMath::Pi(); Double_t phi3; - Double_t x3=0.,y3=0.,d; - for (Int_t i=0; i<10; i++) { - phi3=(phi1+phi2)*0.5; - x3=fRmin*TMath::Cos(phi3); - y3=fRmax*TMath::Sin(phi3); - d=y3*a2*(x0-x3)-x3*b2*(y0-y3); - if (d<0) phi1=phi3; - else phi2=phi3; + Double_t x3 = 0., y3 = 0., d; + for (Int_t i = 0; i < 10; i++) { + phi3 = (phi1 + phi2) * 0.5; + x3 = fRmin * TMath::Cos(phi3); + y3 = fRmax * TMath::Sin(phi3); + d = y3 * a2 * (x0 - x3) - x3 * b2 * (y0 - y3); + if (d < 0) + phi1 = phi3; + else + phi2 = phi3; } - *safe=TMath::Sqrt((x0-x3)*(x0-x3)+(y0-y3)*(y0-y3)); + *safe = TMath::Sqrt((x0 - x3) * (x0 - x3) + (y0 - y3) * (y0 - y3)); } - if (safz>0) { - *safe=TMath::Sqrt((*safe)*(*safe)+safz*safz); + if (safz > 0) { + *safe = TMath::Sqrt((*safe) * (*safe) + safz * safz); } - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step < *safe)) + return TGeoShape::Big(); } // compute vector distance Double_t zi, tau; - Double_t epsil = 10.*TGeoShape::Tolerance(); + Double_t epsil = 10. * TGeoShape::Tolerance(); if (safz > -epsil) { // point beyond the z limit (up or down) // Check if direction is outgoing - if (point[2]*dir[2]>0) return TGeoShape::Big(); + if (point[2] * dir[2] > 0) + return TGeoShape::Big(); // Check if direction is perpendicular to Z axis - if (TGeoShape::IsSameWithinTolerance(dir[2],0)) return TGeoShape::Big(); + if (TGeoShape::IsSameWithinTolerance(dir[2], 0)) + return TGeoShape::Big(); // select +z or -z depending on the side of the point zi = (point[2] > 0) ? fDz : -fDz; // Distance to zi plane position - tau = (zi-point[2])/dir[2]; + tau = (zi - point[2]) / dir[2]; // Extrapolated coordinates at the z position of the end plane. - Double_t xz=point[0]+dir[0]*tau; - Double_t yz=point[1]+dir[1]*tau; - if ((xz*xz/a2+yz*yz/b2)<1) return tau; + Double_t xz = point[0] + dir[0] * tau; + Double_t yz = point[1] + dir[1] * tau; + if ((xz * xz / a2 + yz * yz / b2) < 1) + return tau; } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); - Double_t u=dir[0]*dir[0]*b2+dir[1]*dir[1]*a2; // positive - if (TGeoShape::IsSameWithinTolerance(u,0)) return TGeoShape::Big(); - Double_t v=point[0]*dir[0]*b2+point[1]*dir[1]*a2; - Double_t w=point[0]*point[0]*b2+point[1]*point[1]*a2-a2*b2; - Double_t d=v*v-u*w; - if (d<0) return TGeoShape::Big(); - Double_t dsq=TMath::Sqrt(d); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); + Double_t u = dir[0] * dir[0] * b2 + dir[1] * dir[1] * a2; // positive + if (TGeoShape::IsSameWithinTolerance(u, 0)) + return TGeoShape::Big(); + Double_t v = point[0] * dir[0] * b2 + point[1] * dir[1] * a2; + Double_t w = point[0] * point[0] * b2 + point[1] * point[1] * a2 - a2 * b2; + Double_t d = v * v - u * w; + if (d < 0) + return TGeoShape::Big(); + Double_t dsq = TMath::Sqrt(d); // Biggest solution - if negative, or very close to boundary // no crossing (just exiting, no re-entering possible) - tau = (-v+dsq)/u; - if (tau < epsil) return TGeoShape::Big(); + tau = (-v + dsq) / u; + if (tau < epsil) + return TGeoShape::Big(); // only entering crossing must be considered (smallest) - tau = (-v-dsq)/u; - zi=point[2]+tau*dir[2]; + tau = (-v - dsq) / u; + zi = point[2] + tau * dir[2]; // If the crossing point is not in the Z range, there is no crossing - if ((TMath::Abs(zi)-fDz)>0) return TGeoShape::Big(); + if ((TMath::Abs(zi) - fDz) > 0) + return TGeoShape::Big(); // crossing is backwards (point inside the ellipse) in Z range - if (tau < 0) return 0.; + if (tau < 0) + return 0.; // Point is outside and crossing the elliptical tube in Z range return tau; } @@ -326,11 +345,11 @@ TGeoVolume *TGeoEltu::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, void TGeoEltu::GetBoundingCylinder(Double_t *param) const { - param[0] = 0.; // Rmin + param[0] = 0.; // Rmin param[1] = TMath::Max(fRmin, fRmax); // Rmax param[1] *= param[1]; - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -339,7 +358,8 @@ void TGeoEltu::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoEltu::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoEltu)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; @@ -348,11 +368,12 @@ TGeoShape *TGeoEltu::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/ a = fRmin; b = fRmax; dz = fDz; - if (fDz<0) dz=((TGeoEltu*)mother)->GetDz(); - if (fRmin<0) - a = ((TGeoEltu*)mother)->GetA(); - if (fRmax<0) - a = ((TGeoEltu*)mother)->GetB(); + if (fDz < 0) + dz = ((TGeoEltu *)mother)->GetDz(); + if (fRmin < 0) + a = ((TGeoEltu *)mother)->GetA(); + if (fRmax < 0) + a = ((TGeoEltu *)mother)->GetB(); return (new TGeoEltu(a, b, dz)); } @@ -380,43 +401,47 @@ Double_t TGeoEltu::Safety(const Double_t *point, Bool_t /*in*/) const Double_t y0 = TMath::Abs(point[1]); Double_t x1, y1, dx, dy; Double_t safr, safz; - Double_t onepls = 1.+TGeoShape::Tolerance(); - Double_t onemin = 1.-TGeoShape::Tolerance(); - Double_t sqdist = x0*x0/(fRmin*fRmin)+y0*y0/(fRmax*fRmax); + Double_t onepls = 1. + TGeoShape::Tolerance(); + Double_t onemin = 1. - TGeoShape::Tolerance(); + Double_t sqdist = x0 * x0 / (fRmin * fRmin) + y0 * y0 / (fRmax * fRmax); Bool_t in = kTRUE; - if (sqdist>onepls) in = kFALSE; - else if (sqdist onepls) + in = kFALSE; + else if (sqdist < onemin) + in = kTRUE; + else + return 0.; if (in) { - x1 = fRmin*TMath::Sqrt(1.-(y0*y0)/(fRmax*fRmax)); - y1 = fRmax*TMath::Sqrt(1.-(x0*x0)/(fRmin*fRmin)); - dx = x1-x0; - dy = y1-y0; - if (TMath::Abs(dx)GetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; - Double_t cph,sph; + Double_t cph, sph; dz = fDz; Int_t indx = 0; - Double_t r2,r; - Double_t a2=fRmin*fRmin; - Double_t b2=fRmax*fRmax; + Double_t r2, r; + Double_t a2 = fRmin * fRmin; + Double_t b2 = fRmax * fRmax; if (points) { for (j = 0; j < n; j++) { - points[indx+6*n] = points[indx] = 0; + points[indx + 6 * n] = points[indx] = 0; indx++; - points[indx+6*n] = points[indx] = 0; + points[indx + 6 * n] = points[indx] = 0; indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - sph=TMath::Sin(phi); - cph=TMath::Cos(phi); - r2=(a2*b2)/(b2+(a2-b2)*sph*sph); - r=TMath::Sqrt(r2); - points[indx+6*n] = points[indx] = r*cph; + phi = j * dphi * TMath::DegToRad(); + sph = TMath::Sin(phi); + cph = TMath::Cos(phi); + r2 = (a2 * b2) / (b2 + (a2 - b2) * sph * sph); + r = TMath::Sqrt(r2); + points[indx + 6 * n] = points[indx] = r * cph; indx++; - points[indx+6*n] = points[indx] = r*sph; + points[indx + 6 * n] = points[indx] = r * sph; indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } @@ -509,7 +535,7 @@ void TGeoEltu::SetPoints(Double_t *points) const void TGeoEltu::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - TGeoTube::GetMeshNumbers(nvert,nsegs,npols); + TGeoTube::GetMeshNumbers(nvert, nsegs, npols); } //////////////////////////////////////////////////////////////////////////////// @@ -529,38 +555,38 @@ void TGeoEltu::SetPoints(Float_t *points) const Int_t j, n; n = gGeoManager->GetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; - Double_t cph,sph; + Double_t cph, sph; dz = fDz; Int_t indx = 0; - Double_t r2,r; - Double_t a2=fRmin*fRmin; - Double_t b2=fRmax*fRmax; + Double_t r2, r; + Double_t a2 = fRmin * fRmin; + Double_t b2 = fRmax * fRmax; if (points) { for (j = 0; j < n; j++) { - points[indx+6*n] = points[indx] = 0; + points[indx + 6 * n] = points[indx] = 0; indx++; - points[indx+6*n] = points[indx] = 0; + points[indx + 6 * n] = points[indx] = 0; indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - sph=TMath::Sin(phi); - cph=TMath::Cos(phi); - r2=(a2*b2)/(b2+(a2-b2)*sph*sph); - r=TMath::Sqrt(r2); - points[indx+6*n] = points[indx] = r*cph; + phi = j * dphi * TMath::DegToRad(); + sph = TMath::Sin(phi); + cph = TMath::Cos(phi); + r2 = (a2 * b2) / (b2 + (a2 - b2) * sph * sph); + r = TMath::Sqrt(r2); + points[indx + 6 * n] = points[indx] = r * cph; indx++; - points[indx+6*n] = points[indx] = r*sph; + points[indx + 6 * n] = points[indx] = r * sph; indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } @@ -569,17 +595,17 @@ void TGeoEltu::SetPoints(Float_t *points) const //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoEltu::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoEltu::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kRawSizes) { Int_t n = gGeoManager->GetNsegments(); - Int_t nbPnts = 4*n; - Int_t nbSegs = 8*n; - Int_t nbPols = 4*n; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t nbPnts = 4 * n; + Int_t nbSegs = 8 * n; + Int_t nbPols = 4 * n; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -602,7 +628,8 @@ const TBuffer3D & TGeoEltu::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoEltu::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i", fField->GetName()); + if (fField) + Info("SetField", "Global magnetic field set to <%s>", fField->GetName()); } //////////////////////////////////////////////////////////////////////////////// @@ -115,7 +117,8 @@ TGeoGlobalMagField *TGeoGlobalMagField::GetInstance() TGeoGlobalMagField *TGeoGlobalMagField::Instance() { - if (fgInstance) return fgInstance; + if (fgInstance) + return fgInstance; return new TGeoGlobalMagField(); } diff --git a/geom/geom/src/TGeoHalfSpace.cxx b/geom/geom/src/TGeoHalfSpace.cxx index 644901e573313..90f7bcd5337f8 100644 --- a/geom/geom/src/TGeoHalfSpace.cxx +++ b/geom/geom/src/TGeoHalfSpace.cxx @@ -39,29 +39,27 @@ TGeoHalfSpace::TGeoHalfSpace() { SetShapeBit(TGeoShape::kGeoHalfSpace); SetShapeBit(TGeoShape::kGeoInvalidShape); - memset(fP, 0, 3*sizeof(Double_t)); - memset(fN, 0, 3*sizeof(Double_t)); + memset(fP, 0, 3 * sizeof(Double_t)); + memset(fN, 0, 3 * sizeof(Double_t)); } //////////////////////////////////////////////////////////////////////////////// /// Constructor with name, point on the plane and normal -TGeoHalfSpace::TGeoHalfSpace(const char *name, Double_t *p, Double_t *n) - :TGeoBBox(name, 0,0,0) +TGeoHalfSpace::TGeoHalfSpace(const char *name, Double_t *p, Double_t *n) : TGeoBBox(name, 0, 0, 0) { SetShapeBit(TGeoShape::kGeoHalfSpace); SetShapeBit(TGeoShape::kGeoInvalidShape); Double_t param[6]; - memcpy(param, p, 3*sizeof(Double_t)); - memcpy(¶m[3], n, 3*sizeof(Double_t)); + memcpy(param, p, 3 * sizeof(Double_t)); + memcpy(¶m[3], n, 3 * sizeof(Double_t)); SetDimensions(param); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying minimum and maximum radius -TGeoHalfSpace::TGeoHalfSpace(Double_t *param) - :TGeoBBox(0,0,0) +TGeoHalfSpace::TGeoHalfSpace(Double_t *param) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoHalfSpace); SetShapeBit(TGeoShape::kGeoInvalidShape); @@ -71,17 +69,15 @@ TGeoHalfSpace::TGeoHalfSpace(Double_t *param) //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoHalfSpace::~TGeoHalfSpace() -{ -} +TGeoHalfSpace::~TGeoHalfSpace() {} //////////////////////////////////////////////////////////////////////////////// /// Compute normal to closest surface from POINT. void TGeoHalfSpace::ComputeNormal(const Double_t * /*point*/, const Double_t *dir, Double_t *norm) { - memcpy(norm, fN, 3*sizeof(Double_t)); - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + memcpy(norm, fN, 3 * sizeof(Double_t)); + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -94,11 +90,12 @@ void TGeoHalfSpace::ComputeNormal(const Double_t * /*point*/, const Double_t *di Bool_t TGeoHalfSpace::Contains(const Double_t *point) const { Double_t r[3]; - r[0] = fP[0]-point[0]; - r[1] = fP[1]-point[1]; - r[2] = fP[2]-point[2]; - Double_t rdotn = r[0]*fN[0]+r[1]*fN[1]+r[2]*fN[2]; - if (rdotn < 0) return kFALSE; + r[0] = fP[0] - point[0]; + r[1] = fP[1] - point[1]; + r[2] = fP[2] - point[2]; + Double_t rdotn = r[0] * fN[0] + r[1] * fN[1] + r[2] * fN[2]; + if (rdotn < 0) + return kFALSE; return kTRUE; } @@ -113,48 +110,58 @@ Int_t TGeoHalfSpace::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/) //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to the plane -Double_t TGeoHalfSpace::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoHalfSpace::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { Double_t r[3]; - r[0] = fP[0]-point[0]; - r[1] = fP[1]-point[1]; - r[2] = fP[2]-point[2]; - Double_t rdotn = r[0]*fN[0]+r[1]*fN[1]+r[2]*fN[2]; - if (iact<3 && safe) { + r[0] = fP[0] - point[0]; + r[1] = fP[1] - point[1]; + r[2] = fP[2] - point[2]; + Double_t rdotn = r[0] * fN[0] + r[1] * fN[1] + r[2] * fN[2]; + if (iact < 3 && safe) { *safe = rdotn; - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // compute distance to plane Double_t snxt = TGeoShape::Big(); - Double_t ddotn = dir[0]*fN[0]+dir[1]*fN[1]+dir[2]*fN[2]; - if (TMath::Abs(ddotn)LocalToMaster(vect, fPoint); - Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2]; - Double_t f = -TMath::Sqrt(1.-ddb*ddb); - vect[0] = f*TMath::Sin(fPhi); - vect[1] = fQ*f*TMath::Cos(fPhi); + Double_t ddb = fDirInit[0] * fB[0] + fDirInit[1] * fB[1] + fDirInit[2] * fB[2]; + Double_t f = -TMath::Sqrt(1. - ddb * ddb); + vect[0] = f * TMath::Sin(fPhi); + vect[1] = fQ * f * TMath::Cos(fPhi); vect[2] = ddb; TMath::Normalize(vect); fMatrix->LocalToMasterVect(vect, fDir); @@ -288,28 +296,32 @@ Double_t TGeoHelix::StepToPlane(Double_t *point, Double_t *norm) Double_t snext = 1.E30; Double_t dx, dy, dz; Double_t ddn, pdn; - if (TObject::TestBit(kHelixNeedUpdate)) UpdateHelix(); + if (TObject::TestBit(kHelixNeedUpdate)) + UpdateHelix(); dx = point[0] - fPoint[0]; dy = point[1] - fPoint[1]; dz = point[2] - fPoint[2]; - pdn = dx*norm[0]+dy*norm[1]+dz*norm[2]; - ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2]; + pdn = dx * norm[0] + dy * norm[1] + dz * norm[2]; + ddn = fDir[0] * norm[0] + fDir[1] * norm[1] + fDir[2] * norm[2]; if (TObject::TestBit(kHelixStraight)) { // propagate straight line to plane - if ((pdn*ddn) <= 0) return snext; - snext = pdn/ddn; + if ((pdn * ddn) <= 0) + return snext; + snext = pdn / ddn; Step(snext); return snext; } - Double_t r = 1./fC; + Double_t r = 1. / fC; Double_t dist; Double_t safety = TMath::Abs(pdn); Double_t safestep = ComputeSafeStep(); snext = 1.E30; - Bool_t approaching = (ddn*pdn>0)?kTRUE:kFALSE; - if (approaching) snext = pdn/ddn; - else if (safety > 2.*r) return snext; + Bool_t approaching = (ddn * pdn > 0) ? kTRUE : kFALSE; + if (approaching) + snext = pdn / ddn; + else if (safety > 2. * r) + return snext; while (snext > safestep) { dist = TMath::Max(safety, safestep); Step(dist); @@ -317,13 +329,14 @@ Double_t TGeoHelix::StepToPlane(Double_t *point, Double_t *norm) dx = point[0] - fPoint[0]; dy = point[1] - fPoint[1]; dz = point[2] - fPoint[2]; - pdn = dx*norm[0]+dy*norm[1]+dz*norm[2]; - ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2]; + pdn = dx * norm[0] + dy * norm[1] + dz * norm[2]; + ddn = fDir[0] * norm[0] + fDir[1] * norm[1] + fDir[2] * norm[2]; safety = TMath::Abs(pdn); - approaching = (ddn*pdn>0)?kTRUE:kFALSE; + approaching = (ddn * pdn > 0) ? kTRUE : kFALSE; snext = 1.E30; - if (approaching) snext = pdn/ddn; - else if (safety > 2.*r) { + if (approaching) + snext = pdn / ddn; + else if (safety > 2. * r) { ResetStep(); return snext; } @@ -340,12 +353,12 @@ void TGeoHelix::UpdateHelix() { TObject::SetBit(kHelixNeedUpdate, kFALSE); fStep = 0.; - memcpy(fPoint, fPointInit, 3*sizeof(Double_t)); - memcpy(fDir, fDirInit, 3*sizeof(Double_t)); + memcpy(fPoint, fPointInit, 3 * sizeof(Double_t)); + memcpy(fDir, fDirInit, 3 * sizeof(Double_t)); Double_t rot[9]; Double_t tr[3]; - Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2]; - if ((1.-TMath::Abs(ddb))Clear(); @@ -354,22 +367,22 @@ void TGeoHelix::UpdateHelix() rot[2] = fB[0]; rot[5] = fB[1]; rot[8] = fB[2]; - if (ddb < 0) fS = -TMath::Abs(fS); - Double_t fy = - fQ*TMath::Sqrt(1.-ddb*ddb); - fy = 1./fy; - rot[1] = fy*(fDirInit[0]-fB[0]*ddb); - rot[4] = fy*(fDirInit[1]-fB[1]*ddb); - rot[7] = fy*(fDirInit[2]-fB[2]*ddb); - - rot[0] = rot[4]*rot[8] - rot[7]*rot[5]; - rot[3] = rot[7]*rot[2] - rot[1]*rot[8]; - rot[6] = rot[1]*rot[5] - rot[4]*rot[2]; - - tr[0] = fPointInit[0] - rot[0]/fC; - tr[1] = fPointInit[1] - rot[3]/fC; - tr[2] = fPointInit[2] - rot[6]/fC; + if (ddb < 0) + fS = -TMath::Abs(fS); + Double_t fy = -fQ * TMath::Sqrt(1. - ddb * ddb); + fy = 1. / fy; + rot[1] = fy * (fDirInit[0] - fB[0] * ddb); + rot[4] = fy * (fDirInit[1] - fB[1] * ddb); + rot[7] = fy * (fDirInit[2] - fB[2] * ddb); + + rot[0] = rot[4] * rot[8] - rot[7] * rot[5]; + rot[3] = rot[7] * rot[2] - rot[1] * rot[8]; + rot[6] = rot[1] * rot[5] - rot[4] * rot[2]; + + tr[0] = fPointInit[0] - rot[0] / fC; + tr[1] = fPointInit[1] - rot[3] / fC; + tr[2] = fPointInit[2] - rot[6] / fC; fMatrix->SetTranslation(tr); fMatrix->SetRotation(rot); - } diff --git a/geom/geom/src/TGeoHype.cxx b/geom/geom/src/TGeoHype.cxx index 698da5f491826..031ac9494eadd 100644 --- a/geom/geom/src/TGeoHype.cxx +++ b/geom/geom/src/TGeoHype.cxx @@ -9,7 +9,6 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ - #include #include "TGeoManager.h" @@ -55,27 +54,25 @@ End_Macro The hyperbolic surface equation is taken in the form: ~~~{.cpp} -r2 - z2tan2() = r2min +r^2 - z^2 * tan(st)^2 = rmin^2 ~~~ - `r,z:` cylindrical coordinates for a point on the surface -- `:` stereo angle between the hyperbola asymptotic lines and Z axis -- `r2min:` minimum distance between hyperbola and Z axis (at `z=0`) +- `st:` stereo angle between the hyperbola asymptotic lines and Z axis +- `rmin:` minimum distance between hyperbola and Z axis (at `z=0`) -The input parameters represent: +The input parameters for a hyperboloid represent: -- `rin, stin:` minimum radius and tangent of stereo angle for inner - surface -- `rout, stout:` minimum radius and tangent of stereo angle for outer - surface +- `rin, stin:` minimum radius and stereo angle in degrees for the inner surface +- `rout, stout:` minimum radius and stereo angle in degrees for the outer surface - `dz:` half length in Z (bounding planes positions at `+/-dz`) The following conditions are mandatory in order to avoid intersections between the inner and outer hyperbolic surfaces in the range `+/-dz`: -- `rin0` -- `rin2 + dz2*stin2 > rout2 + dz2*stout2` +- `rin < rout` +- `rout > 0` +- `rin^2 + dz^2 * tan(stin)^2 > rout^2 + dz^2 * tan(stout)^2` Particular cases: @@ -100,29 +97,29 @@ TGeoHype::TGeoHype() fToutsq = 0.; } - //////////////////////////////////////////////////////////////////////////////// /// Constructor specifying hyperboloid parameters. -TGeoHype::TGeoHype(Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) - :TGeoTube(rin, rout, dz) +TGeoHype::TGeoHype(Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) : TGeoTube(rin, rout, dz) { SetShapeBit(TGeoShape::kGeoHype); SetHypeDimensions(rin, stin, rout, stout, dz); // dz<0 can be used to force dz of hyperboloid fit the container volume - if (fDz<0) SetShapeBit(kGeoRunTimeShape); + if (fDz < 0) + SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// Constructor specifying parameters and name. -TGeoHype::TGeoHype(const char *name,Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) - :TGeoTube(name, rin, rout, dz) +TGeoHype::TGeoHype(const char *name, Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) + : TGeoTube(name, rin, rout, dz) { SetShapeBit(TGeoShape::kGeoHype); SetHypeDimensions(rin, stin, rout, stout, dz); // dz<0 can be used to force dz of hyperboloid fit the container volume - if (fDz<0) SetShapeBit(kGeoRunTimeShape); + if (fDz < 0) + SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } @@ -134,30 +131,28 @@ TGeoHype::TGeoHype(const char *name,Double_t rin, Double_t stin, Double_t rout, /// - param[3] = rout /// - param[4] = stout -TGeoHype::TGeoHype(Double_t *param) - :TGeoTube(param[1],param[3],param[0]) +TGeoHype::TGeoHype(Double_t *param) : TGeoTube(param[1], param[3], param[0]) { SetShapeBit(TGeoShape::kGeoHype); SetDimensions(param); // dz<0 can be used to force dz of hyperboloid fit the container volume - if (fDz<0) SetShapeBit(kGeoRunTimeShape); + if (fDz < 0) + SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoHype::~TGeoHype() -{ -} +TGeoHype::~TGeoHype() {} //////////////////////////////////////////////////////////////////////////////// /// Computes capacity of the shape in [length^3] Double_t TGeoHype::Capacity() const { - Double_t capacity = 2.*TMath::Pi()*fDz*(fRmax*fRmax-fRmin*fRmin) + - (2.*TMath::Pi()/3.)*fDz*fDz*fDz*(fToutsq-fTinsq); + Double_t capacity = 2. * TMath::Pi() * fDz * (fRmax * fRmax - fRmin * fRmin) + + (2. * TMath::Pi() / 3.) * fDz * fDz * fDz * (fToutsq - fTinsq); return capacity; } @@ -166,14 +161,14 @@ Double_t TGeoHype::Capacity() const void TGeoHype::ComputeBBox() { - if (fRmin<0.) { - Warning("ComputeBBox", "Shape %s has invalid rmin=%g ! SET TO 0.", GetName(),fRmin); + if (fRmin < 0.) { + Warning("ComputeBBox", "Shape %s has invalid rmin=%g ! SET TO 0.", GetName(), fRmin); fRmin = 0.; } - if ((fRmin>fRmax) || (fRmin*fRmin+fTinsq*fDz*fDz > fRmax*fRmax+fToutsq*fDz*fDz)) { + if ((fRmin > fRmax) || (fRmin * fRmin + fTinsq * fDz * fDz > fRmax * fRmax + fToutsq * fDz * fDz)) { SetShapeBit(kGeoInvalidShape); - Error("ComputeBBox", "Shape %s hyperbolic surfaces are malformed: rin=%g, stin=%g, rout=%g, stout=%g", - GetName(), fRmin, fStIn, fRmax, fStOut); + Error("ComputeBBox", "Shape %s hyperbolic surfaces are malformed: rin=%g, stin=%g, rout=%g, stout=%g", GetName(), + fRmin, fStIn, fRmax, fStOut); return; } @@ -187,31 +182,32 @@ void TGeoHype::ComputeBBox() void TGeoHype::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t rin = (HasInner())?(TMath::Sqrt(RadiusHypeSq(point[2],kTRUE))):0.; - Double_t rout = TMath::Sqrt(RadiusHypeSq(point[2],kFALSE)); - saf[0] = TMath::Abs(fDz-TMath::Abs(point[2])); - saf[1] = (HasInner())?TMath::Abs(rin-r):TGeoShape::Big(); - saf[2] = TMath::Abs(rout-r); - Int_t i = TMath::LocMin(3,saf); - if (i==0 || r<1.E-10) { + Double_t rin = (HasInner()) ? (TMath::Sqrt(RadiusHypeSq(point[2], kTRUE))) : 0.; + Double_t rout = TMath::Sqrt(RadiusHypeSq(point[2], kFALSE)); + saf[0] = TMath::Abs(fDz - TMath::Abs(point[2])); + saf[1] = (HasInner()) ? TMath::Abs(rin - r) : TGeoShape::Big(); + saf[2] = TMath::Abs(rout - r); + Int_t i = TMath::LocMin(3, saf); + if (i == 0 || r < 1.E-10) { norm[0] = norm[1] = 0.; - norm[2] = TMath::Sign(1.,dir[2]); + norm[2] = TMath::Sign(1., dir[2]); return; } - Double_t t = (i==1)?fTinsq:fToutsq;; - t *= -point[2]/r; - Double_t ct = TMath::Sqrt(1./(1.+t*t)); + Double_t t = (i == 1) ? fTinsq : fToutsq; + ; + t *= -point[2] / r; + Double_t ct = TMath::Sqrt(1. / (1. + t * t)); Double_t st = t * ct; Double_t phi = TMath::ATan2(point[1], point[0]); Double_t cphi = TMath::Cos(phi); Double_t sphi = TMath::Sin(phi); - norm[0] = ct*cphi; - norm[1] = ct*sphi; + norm[0] = ct * cphi; + norm[1] = ct * sphi; norm[2] = st; - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -223,13 +219,17 @@ void TGeoHype::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoHype::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fDz) return kFALSE; - Double_t r2 = point[0]*point[0]+point[1]*point[1]; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; + Double_t r2 = point[0] * point[0] + point[1] * point[1]; Double_t routsq = RadiusHypeSq(point[2], kFALSE); - if (r2>routsq) return kFALSE; - if (!HasInner()) return kTRUE; + if (r2 > routsq) + return kFALSE; + if (!HasInner()) + return kTRUE; Double_t rinsq = RadiusHypeSq(point[2], kTRUE); - if (r2step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // compute distance to surface // Do Z Double_t sz = TGeoShape::Big(); - if (dir[2]>0) { - sz = (fDz-point[2])/dir[2]; - if (sz<=0.) return 0.; + if (dir[2] > 0) { + sz = (fDz - point[2]) / dir[2]; + if (sz <= 0.) + return 0.; } else { - if (dir[2]<0) { - sz = -(fDz+point[2])/dir[2]; - if (sz<=0.) return 0.; + if (dir[2] < 0) { + sz = -(fDz + point[2]) / dir[2]; + if (sz <= 0.) + return 0.; } } - // Do R Double_t srin = TGeoShape::Big(); Double_t srout = TGeoShape::Big(); @@ -274,43 +278,49 @@ Double_t TGeoHype::DistFromInside(const Double_t *point, const Double_t *dir, In Double_t s[2]; Int_t npos; npos = DistToHype(point, dir, s, kTRUE, kTRUE); - if (npos) srin = s[0]; + if (npos) + srin = s[0]; npos = DistToHype(point, dir, s, kFALSE, kTRUE); - if (npos) srout = s[0]; + if (npos) + srout = s[0]; sr = TMath::Min(srin, srout); - return TMath::Min(sz,sr); + return TMath::Min(sz, sr); } - //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the hyperboloid. -Double_t TGeoHype::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoHype::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); // find distance to shape // Do Z Double_t xi, yi, zi; - if (TMath::Abs(point[2])>=fDz) { + if (TMath::Abs(point[2]) >= fDz) { // We might find Z plane crossing - if ((point[2]*dir[2]) < 0) { + if ((point[2] * dir[2]) < 0) { // Compute distance to Z (always positive) - Double_t sz = (TMath::Abs(point[2])-fDz)/TMath::Abs(dir[2]); + Double_t sz = (TMath::Abs(point[2]) - fDz) / TMath::Abs(dir[2]); // Extrapolate - xi = point[0]+sz*dir[0]; - yi = point[1]+sz*dir[1]; - Double_t r2 = xi*xi + yi*yi; + xi = point[0] + sz * dir[0]; + yi = point[1] + sz * dir[1]; + Double_t r2 = xi * xi + yi * yi; Double_t rmin2 = RadiusHypeSq(fDz, kTRUE); if (r2 >= rmin2) { Double_t rmax2 = RadiusHypeSq(fDz, kFALSE); - if (r2 <= rmax2) return sz; + if (r2 <= rmax2) + return sz; } } } @@ -321,20 +331,24 @@ Double_t TGeoHype::DistFromOutside(const Double_t *point, const Double_t *dir, I Int_t npos; npos = DistToHype(point, dir, s, kTRUE, kFALSE); if (npos) { - zi = point[2] + s[0]*dir[2]; - if (TMath::Abs(zi) <= fDz) sin = s[0]; - else if (npos==2) { - zi = point[2] + s[1]*dir[2]; - if (TMath::Abs(zi) <= fDz) sin = s[1]; + zi = point[2] + s[0] * dir[2]; + if (TMath::Abs(zi) <= fDz) + sin = s[0]; + else if (npos == 2) { + zi = point[2] + s[1] * dir[2]; + if (TMath::Abs(zi) <= fDz) + sin = s[1]; } } npos = DistToHype(point, dir, s, kFALSE, kFALSE); if (npos) { - zi = point[2] + s[0]*dir[2]; - if (TMath::Abs(zi) <= fDz) sout = s[0]; - else if (npos==2) { - zi = point[2] + s[1]*dir[2]; - if (TMath::Abs(zi) <= fDz) sout = s[1]; + zi = point[2] + s[0] * dir[2]; + if (TMath::Abs(zi) <= fDz) + sout = s[0]; + else if (npos == 2) { + zi = point[2] + s[1] * dir[2]; + if (TMath::Abs(zi) <= fDz) + sout = s[1]; } } return TMath::Min(sin, sout); @@ -348,46 +362,55 @@ Int_t TGeoHype::DistToHype(const Double_t *point, const Double_t *dir, Double_t { Double_t r0, t0, snext; if (inner) { - if (!HasInner()) return 0; + if (!HasInner()) + return 0; r0 = fRmin; t0 = fTinsq; } else { r0 = fRmax; t0 = fToutsq; } - Double_t a = dir[0]*dir[0] + dir[1]*dir[1] - t0*dir[2]*dir[2]; - Double_t b = t0*point[2]*dir[2] - point[0]*dir[0] - point[1]*dir[1]; - Double_t c = point[0]*point[0] + point[1]*point[1] - t0*point[2]*point[2] - r0*r0; + Double_t a = dir[0] * dir[0] + dir[1] * dir[1] - t0 * dir[2] * dir[2]; + Double_t b = t0 * point[2] * dir[2] - point[0] * dir[0] - point[1] * dir[1]; + Double_t c = point[0] * point[0] + point[1] * point[1] - t0 * point[2] * point[2] - r0 * r0; if (TMath::Abs(a) < TGeoShape::Tolerance()) { - if (TMath::Abs(b) < TGeoShape::Tolerance()) return 0; - snext = 0.5*c/b; - if (snext < 0.) return 0; + if (TMath::Abs(b) < TGeoShape::Tolerance()) + return 0; + snext = 0.5 * c / b; + if (snext < 0.) + return 0; s[0] = snext; return 1; } - Double_t delta = b*b - a*c; - Double_t ainv = 1./a; + Double_t delta = b * b - a * c; + Double_t ainv = 1. / a; Int_t npos = 0; - if (delta < 0.) return 0; + if (delta < 0.) + return 0; delta = TMath::Sqrt(delta); - Double_t sone = TMath::Sign(1.,ainv); + Double_t sone = TMath::Sign(1., ainv); Int_t i = -1; - while (i<2) { - snext = (b + i*sone*delta)*ainv; + while (i < 2) { + snext = (b + i * sone * delta) * ainv; i += 2; - if (snext<0) continue; - if (snext<1.E-8) { - Double_t r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Double_t t = (inner)?fTinsq:fToutsq; - t *= -point[2]/r; + if (snext < 0) + continue; + if (snext < 1.E-8) { + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t t = (inner) ? fTinsq : fToutsq; + t *= -point[2] / r; Double_t phi = TMath::ATan2(point[1], point[0]); - Double_t ndotd = TMath::Cos(phi)*dir[0]+TMath::Sin(phi)*dir[1]+t*dir[2]; - if (inner) ndotd *= -1; - if (in) ndotd *= -1; - if (ndotd<0) s[npos++] = snext; - } else s[npos++] = snext; + Double_t ndotd = TMath::Cos(phi) * dir[0] + TMath::Sin(phi) * dir[1] + t * dir[2]; + if (inner) + ndotd *= -1; + if (in) + ndotd *= -1; + if (ndotd < 0) + s[npos++] = snext; + } else + s[npos++] = snext; } return npos; } @@ -411,21 +434,21 @@ Double_t TGeoHype::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: // R - xlo = fRmin; - xhi = TMath::Sqrt(RadiusHypeSq(fDz, kFALSE)); - dx = xhi-xlo; - return dx; - case 2: // Phi - xlo = 0; - xhi = 360; - dx = 360; - return dx; - case 3: // Z - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 1: // R + xlo = fRmin; + xhi = TMath::Sqrt(RadiusHypeSq(fDz, kFALSE)); + dx = xhi - xlo; + return dx; + case 2: // Phi + xlo = 0; + xhi = 360; + dx = 360; + return dx; + case 3: // Z + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -440,8 +463,8 @@ void TGeoHype::GetBoundingCylinder(Double_t *param) const param[0] *= param[0]; param[1] = TMath::Sqrt(RadiusHypeSq(fDz, kFALSE)); // Rmax param[1] *= param[1]; - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -450,12 +473,14 @@ void TGeoHype::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoHype::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return nullptr; + if (!TestShapeBit(kGeoRunTimeShape)) + return nullptr; Double_t dz = fDz; - Double_t zmin,zmax; + Double_t zmin, zmax; if (fDz < 0) { - mother->GetAxisRange(3,zmin,zmax); - if (zmax<0) return nullptr; + mother->GetAxisRange(3, zmin, zmax); + if (zmax < 0) + return nullptr; dz = zmax; } else { Error("GetMakeRuntimeShape", "Shape %s does not have negative Z range", GetName()); @@ -489,14 +514,13 @@ TBuffer3D *TGeoHype::MakeBuffer3D() const { Int_t n = gGeoManager->GetNsegments(); Bool_t hasRmin = HasInner(); - Int_t nbPnts = (hasRmin)?(2*n*n):(n*n+2); - Int_t nbSegs = (hasRmin)?(4*n*n):(n*(2*n+1)); - Int_t nbPols = (hasRmin)?(2*n*n):(n*(n+1)); - - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols); - if (buff) - { + Int_t nbPnts = (hasRmin) ? (2 * n * n) : (n * n + 2); + Int_t nbSegs = (hasRmin) ? (4 * n * n) : (n * (2 * n + 1)); + Int_t nbPols = (hasRmin) ? (2 * n * n) : (n * (n + 1)); + + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -514,7 +538,7 @@ void TGeoHype::SetSegsAndPols(TBuffer3D &buff) const n = gGeoManager->GetNsegments(); Bool_t hasRmin = HasInner(); Int_t irin = 0; - Int_t irout = (hasRmin)?(n*n):2; + Int_t irout = (hasRmin) ? (n * n) : 2; // Fill segments // Case hasRmin: // Inner circles: [isin = 0], n (per circle) * n ( circles) @@ -547,66 +571,68 @@ void TGeoHype::SetSegsAndPols(TBuffer3D &buff) const // seg[j] = [irin+1] and [irout+n*(n-1) + j] Int_t isin = 0; - Int_t isgenin = (hasRmin)?(isin+n*n):0; - Int_t isout = (hasRmin)?(isgenin+n*(n-1)):0; - Int_t isgenout = isout+n*n; - Int_t islo = isgenout+n*(n-1); + Int_t isgenin = (hasRmin) ? (isin + n * n) : 0; + Int_t isout = (hasRmin) ? (isgenin + n * (n - 1)) : 0; + Int_t isgenout = isout + n * n; + Int_t islo = isgenout + n * (n - 1); Int_t ishi = islo + n; Int_t npt = 0; // Fill inner circle segments (n*n) if (hasRmin) { - for (i=0; i safe) safe = safrmin; - safrmax = SafetyToHype(point, kFALSE,in); - if (safrmax > safe) safe = safrmax; + if (safrmin > safe) + safe = safrmin; + safrmax = SafetyToHype(point, kFALSE, in); + if (safrmax > safe) + safe = safrmax; } return safe; } @@ -764,33 +795,40 @@ Double_t TGeoHype::Safety(const Double_t *point, Bool_t in) const Double_t TGeoHype::SafetyToHype(const Double_t *point, Bool_t inner, Bool_t in) const { Double_t r, rsq, rhsq, rh, dr, tsq, saf; - if (inner && !HasInner()) return (in)?TGeoShape::Big():-TGeoShape::Big(); - rsq = point[0]*point[0]+point[1]*point[1]; + if (inner && !HasInner()) + return (in) ? TGeoShape::Big() : -TGeoShape::Big(); + rsq = point[0] * point[0] + point[1] * point[1]; r = TMath::Sqrt(rsq); rhsq = RadiusHypeSq(point[2], inner); rh = TMath::Sqrt(rhsq); dr = r - rh; if (inner) { - if (!in && dr>0) return -TGeoShape::Big(); - if (TMath::Abs(fStIn) < TGeoShape::Tolerance()) return TMath::Abs(dr); - if (fRmin 0) + return -TGeoShape::Big(); + if (TMath::Abs(fStIn) < TGeoShape::Tolerance()) + return TMath::Abs(dr); + if (fRmin < TGeoShape::Tolerance()) + return TMath::Abs(dr / TMath::Sqrt(1. + fTinsq)); tsq = fTinsq; } else { - if (!in && dr<0) return -TGeoShape::Big(); - if (TMath::Abs(fStOut) < TGeoShape::Tolerance()) return TMath::Abs(dr); + if (!in && dr < 0) + return -TGeoShape::Big(); + if (TMath::Abs(fStOut) < TGeoShape::Tolerance()) + return TMath::Abs(dr); tsq = fToutsq; } - if (TMath::Abs(dr) approximate safety with distance to tangent to hyperbola in z = |point[2]| Double_t m; - if (dr<0) { - m = rh/(tsq*TMath::Abs(point[2])); - saf = -m*dr/TMath::Sqrt(1.+m*m); + if (dr < 0) { + m = rh / (tsq * TMath::Abs(point[2])); + saf = -m * dr / TMath::Sqrt(1. + m * m); return saf; } // 2. dr>0 => approximate safety with distance from point to segment P1(r(z0),z0) and P2(r0, z(r0)) - m = (TMath::Sqrt(ZHypeSq(r,inner)) - TMath::Abs(point[2]))/dr; - saf = m*dr/TMath::Sqrt(1.+m*m); + m = (TMath::Sqrt(ZHypeSq(r, inner)) - TMath::Abs(point[2])) / dr; + saf = m * dr / TMath::Sqrt(1. + m * m); return saf; } @@ -799,14 +837,16 @@ Double_t TGeoHype::SafetyToHype(const Double_t *point, Bool_t inner, Bool_t in) void TGeoHype::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rin = " << fRmin << ";" << std::endl; out << " stin = " << fStIn << ";" << std::endl; out << " rout = " << fRmax << ";" << std::endl; out << " stout = " << fStOut << ";" << std::endl; out << " dz = " << fDz << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoHype(\"" << GetName() << "\",rin,stin,rout,stout,dz);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoHype(\"" << GetName() << "\",rin,stin,rout,stout,dz);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -817,15 +857,17 @@ void TGeoHype::SetHypeDimensions(Double_t rin, Double_t stin, Double_t rout, Dou { fRmin = rin; fRmax = rout; - fDz = dz; + fDz = dz; fStIn = stin; fStOut = stout; - fTin = TMath::Tan(fStIn*TMath::DegToRad()); - fTinsq = fTin*fTin; - fTout = TMath::Tan(fStOut*TMath::DegToRad()); - fToutsq = fTout*fTout; - if ((fRmin==0) && (fStIn==0)) SetShapeBit(kGeoRSeg, kTRUE); - else SetShapeBit(kGeoRSeg, kFALSE); + fTin = TMath::Tan(fStIn * TMath::DegToRad()); + fTinsq = fTin * fTin; + fTout = TMath::Tan(fStOut * TMath::DegToRad()); + fToutsq = fTout * fTout; + if ((fRmin == 0) && (fStIn == 0)) + SetShapeBit(kGeoRSeg, kTRUE); + else + SetShapeBit(kGeoRSeg, kFALSE); } //////////////////////////////////////////////////////////////////////////////// @@ -851,23 +893,24 @@ void TGeoHype::SetDimensions(Double_t *param) void TGeoHype::SetPoints(Double_t *points) const { - Double_t z,dz,r; - Int_t i,j, n; - if (!points) return; + Double_t z, dz, r; + Int_t i, j, n; + if (!points) + return; n = gGeoManager->GetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; - dz = 2.*fDz/(n-1); + dz = 2. * fDz / (n - 1); Int_t indx = 0; if (HasInner()) { // Inner surface points - for (i=0; iGetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; - dz = 2.*fDz/(n-1); + dz = 2. * fDz / (n - 1); Int_t indx = 0; if (HasInner()) { // Inner surface points - for (i=0; iGetNsegments(); Bool_t hasRmin = HasInner(); - nvert = (hasRmin)?(2*n*n):(n*n+2); - nsegs = (hasRmin)?(4*n*n):(n*(2*n+1)); - npols = (hasRmin)?(2*n*n):(n*(n+1)); + nvert = (hasRmin) ? (2 * n * n) : (n * n + 2); + nsegs = (hasRmin) ? (4 * n * n) : (n * (2 * n + 1)); + npols = (hasRmin) ? (2 * n * n) : (n * (n + 1)); } //////////////////////////////////////////////////////////////////////////////// @@ -960,21 +1004,19 @@ void TGeoHype::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoHype::GetNmeshVertices() const { Int_t n = gGeoManager->GetNsegments(); - Int_t numPoints = (HasRmin())?(2*n*n):(n*n+2); + Int_t numPoints = (HasRmin()) ? (2 * n * n) : (n * n + 2); return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoHype::Sizeof3D() const -{ -} +void TGeoHype::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoHype::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoHype::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); @@ -983,10 +1025,10 @@ const TBuffer3D & TGeoHype::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co if (reqSections & TBuffer3D::kRawSizes) { Int_t n = gGeoManager->GetNsegments(); Bool_t hasRmin = HasInner(); - Int_t nbPnts = (hasRmin)?(2*n*n):(n*n+2); - Int_t nbSegs = (hasRmin)?(4*n*n):(n*(2*n+1)); - Int_t nbPols = (hasRmin)?(2*n*n):(n*(n+1)); - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t nbPnts = (hasRmin) ? (2 * n * n) : (n * n + 2); + Int_t nbSegs = (hasRmin) ? (4 * n * n) : (n * (2 * n + 1)); + Int_t nbPols = (hasRmin) ? (2 * n * n) : (n * (n + 1)); + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1010,7 +1052,8 @@ const TBuffer3D & TGeoHype::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoHype::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iGetListOfGeometries()->FindObject(this)) gROOT->GetListOfGeometries()->Add(this); - if (!gROOT->GetListOfBrowsables()->FindObject(this)) gROOT->GetListOfBrowsables()->Add(this); + if (!gROOT->GetListOfGeometries()->FindObject(this)) + gROOT->GetListOfGeometries()->Add(this); + if (!gROOT->GetListOfBrowsables()->FindObject(this)) + gROOT->GetListOfBrowsables()->Add(this); Init(); gGeoIdentity = new TGeoIdentity("Identity"); BuildDefaultMaterials(); - if (fgVerboseLevel>0) Info("TGeoManager","Geometry %s, %s created", GetName(), GetTitle()); + if (fgVerboseLevel > 0) + Info("TGeoManager", "Geometry %s, %s created", GetName(), GetTitle()); } //////////////////////////////////////////////////////////////////////////////// @@ -410,13 +414,15 @@ TGeoManager::TGeoManager(const char *name, const char *title) void TGeoManager::Init() { if (gGeoManager) { - Warning("Init","Deleting previous geometry: %s/%s",gGeoManager->GetName(),gGeoManager->GetTitle()); + Warning("Init", "Deleting previous geometry: %s/%s", gGeoManager->GetName(), gGeoManager->GetTitle()); delete gGeoManager; - if (fgLock) Fatal("Init", "New geometry created while the old one locked !!!"); + if (fgLock) + Fatal("Init", "New geometry created while the old one locked !!!"); } gGeoManager = this; - if (!fgThreadId) fgThreadId = new TGeoManager::ThreadsMap_t; + if (!fgThreadId) + fgThreadId = new TGeoManager::ThreadsMap_t; fTimeCut = kFALSE; fTmin = 0.; fTmax = 999.; @@ -431,9 +437,9 @@ void TGeoManager::Init() fLoopVolumes = kFALSE; fBits = new UChar_t[50000]; // max 25000 nodes per volume fCurrentNavigator = 0; - fHashPNE = new THashList(256,3); + fHashPNE = new THashList(256, 3); fArrayPNE = 0; - fMaterials = new THashList(200,3); + fMaterials = new THashList(200, 3); fMatrices = new TObjArray(256); fNodes = new TObjArray(30); fOverlaps = new TObjArray(256); @@ -446,7 +452,7 @@ void TGeoManager::Init() fGVolumes = new TObjArray(256); fGShapes = new TObjArray(256); fTracks = new TObjArray(256); - fMedia = new THashList(200,3); + fMedia = new THashList(200, 3); fNtracks = 0; fNpdg = 0; fPdgNames = 0; @@ -454,7 +460,7 @@ void TGeoManager::Init() fOpticalSurfaces = new TObjArray(); fSkinSurfaces = new TObjArray(); fBorderSurfaces = new TObjArray(); - memset(fPdgId, 0, 1024*sizeof(Int_t)); + memset(fPdgId, 0, 1024 * sizeof(Int_t)); fCurrentTrack = 0; fCurrentVolume = 0; fTopVolume = 0; @@ -496,50 +502,105 @@ void TGeoManager::Init() TGeoManager::~TGeoManager() { - if (gGeoManager != this) gGeoManager = this; + if (gGeoManager != this) + gGeoManager = this; fIsGeomCleaning = kTRUE; - if (gROOT->GetListOfFiles()) { //in case this function is called from TROOT destructor + if (gROOT->GetListOfFiles()) { // in case this function is called from TROOT destructor gROOT->GetListOfGeometries()->Remove(this); gROOT->GetListOfBrowsables()->Remove(this); } -// TSeqCollection *brlist = gROOT->GetListOfBrowsers(); -// TIter next(brlist); -// TBrowser *browser = 0; -// while ((browser=(TBrowser*)next())) browser->RecursiveRemove(this); + // TSeqCollection *brlist = gROOT->GetListOfBrowsers(); + // TIter next(brlist); + // TBrowser *browser = 0; + // while ((browser=(TBrowser*)next())) browser->RecursiveRemove(this); ClearThreadsMap(); ClearThreadData(); delete TGeoBuilder::Instance(this); - if (fBits) delete [] fBits; + if (fBits) + delete[] fBits; SafeDelete(fNodes); SafeDelete(fTopNode); - if (fOverlaps) {fOverlaps->Delete(); SafeDelete(fOverlaps);} - if (fRegions) {fRegions->Delete(); SafeDelete(fRegions);} - if (fMaterials) {fMaterials->Delete(); SafeDelete(fMaterials);} + if (fOverlaps) { + fOverlaps->Delete(); + SafeDelete(fOverlaps); + } + if (fRegions) { + fRegions->Delete(); + SafeDelete(fRegions); + } + if (fMaterials) { + fMaterials->Delete(); + SafeDelete(fMaterials); + } SafeDelete(fElementTable); - if (fMedia) {fMedia->Delete(); SafeDelete(fMedia);} - if (fHashVolumes) { fHashVolumes->Clear("nodelete"); SafeDelete(fHashVolumes); } - if (fHashGVolumes) { fHashGVolumes->Clear("nodelete"); SafeDelete(fHashGVolumes); } - if (fHashPNE) {fHashPNE->Delete(); SafeDelete(fHashPNE);} - if (fArrayPNE) {delete fArrayPNE;} - if (fVolumes) {fVolumes->Delete(); SafeDelete(fVolumes);} - if (fShapes) {fShapes->Delete(); SafeDelete( fShapes );} - if (fPhysicalNodes) {fPhysicalNodes->Delete(); SafeDelete( fPhysicalNodes );} - if (fMatrices) {fMatrices->Delete(); SafeDelete( fMatrices );} - if (fTracks) {fTracks->Delete(); SafeDelete( fTracks );} - SafeDelete( fUniqueVolumes ); - if (fPdgNames) {fPdgNames->Delete(); SafeDelete( fPdgNames );} - if (fGDMLMatrices) {fGDMLMatrices->Delete(); SafeDelete( fGDMLMatrices );} - if (fOpticalSurfaces) {fOpticalSurfaces->Delete(); SafeDelete( fOpticalSurfaces );} - if (fSkinSurfaces) {fSkinSurfaces->Delete(); SafeDelete( fSkinSurfaces );} - if (fBorderSurfaces) {fBorderSurfaces->Delete(); SafeDelete( fBorderSurfaces );} + if (fMedia) { + fMedia->Delete(); + SafeDelete(fMedia); + } + if (fHashVolumes) { + fHashVolumes->Clear("nodelete"); + SafeDelete(fHashVolumes); + } + if (fHashGVolumes) { + fHashGVolumes->Clear("nodelete"); + SafeDelete(fHashGVolumes); + } + if (fHashPNE) { + fHashPNE->Delete(); + SafeDelete(fHashPNE); + } + if (fArrayPNE) { + delete fArrayPNE; + } + if (fVolumes) { + fVolumes->Delete(); + SafeDelete(fVolumes); + } + if (fShapes) { + fShapes->Delete(); + SafeDelete(fShapes); + } + if (fPhysicalNodes) { + fPhysicalNodes->Delete(); + SafeDelete(fPhysicalNodes); + } + if (fMatrices) { + fMatrices->Delete(); + SafeDelete(fMatrices); + } + if (fTracks) { + fTracks->Delete(); + SafeDelete(fTracks); + } + SafeDelete(fUniqueVolumes); + if (fPdgNames) { + fPdgNames->Delete(); + SafeDelete(fPdgNames); + } + if (fGDMLMatrices) { + fGDMLMatrices->Delete(); + SafeDelete(fGDMLMatrices); + } + if (fOpticalSurfaces) { + fOpticalSurfaces->Delete(); + SafeDelete(fOpticalSurfaces); + } + if (fSkinSurfaces) { + fSkinSurfaces->Delete(); + SafeDelete(fSkinSurfaces); + } + if (fBorderSurfaces) { + fBorderSurfaces->Delete(); + SafeDelete(fBorderSurfaces); + } ClearNavigators(); CleanGarbage(); - SafeDelete( fPainter ); - SafeDelete( fGLMatrix ); + SafeDelete(fPainter); + SafeDelete(fGLMatrix); if (fSizePNEId) { - delete [] fKeyPNEId; - delete [] fValuePNEId; + delete[] fKeyPNEId; + delete[] fValuePNEId; } delete fParallelWorld; fIsGeomCleaning = kFALSE; @@ -552,7 +613,7 @@ TGeoManager::~TGeoManager() Int_t TGeoManager::AddMaterial(const TGeoMaterial *material) { - return TGeoBuilder::Instance(this)->AddMaterial((TGeoMaterial*)material); + return TGeoBuilder::Instance(this)->AddMaterial((TGeoMaterial *)material); } //////////////////////////////////////////////////////////////////////////////// @@ -561,7 +622,7 @@ Int_t TGeoManager::AddMaterial(const TGeoMaterial *material) Int_t TGeoManager::AddOverlap(const TNamed *ovlp) { Int_t size = fOverlaps->GetEntriesFast(); - fOverlaps->Add((TObject*)ovlp); + fOverlaps->Add((TObject *)ovlp); return size; } @@ -569,15 +630,15 @@ Int_t TGeoManager::AddOverlap(const TNamed *ovlp) /// Add a new region of volumes. Int_t TGeoManager::AddRegion(TGeoRegion *region) { - Int_t size = fRegions->GetEntriesFast(); - fRegions->Add(region); - return size; + Int_t size = fRegions->GetEntriesFast(); + fRegions->Add(region); + return size; } //////////////////////////////////////////////////////////////////////////////// /// Add a user-defined property. Returns true if added, false if existing. -Bool_t TGeoManager::AddProperty(const char* property, Double_t value) +Bool_t TGeoManager::AddProperty(const char *property, Double_t value) { auto pos = fProperties.insert(ConstPropMap_t::value_type(property, value)); if (!pos.second) { @@ -594,10 +655,12 @@ Double_t TGeoManager::GetProperty(const char *property, Bool_t *error) const { auto pos = fProperties.find(property); if (pos == fProperties.end()) { - if (error) *error = kTRUE; + if (error) + *error = kTRUE; return 0.; } - if (error) *error = kFALSE; + if (error) + *error = kFALSE; return pos->second; } @@ -608,13 +671,18 @@ Double_t TGeoManager::GetProperty(size_t i, TString &name, Bool_t *error) const { // This is a quite inefficient way to access map elements, but needed for the GDML writer to if (i >= fProperties.size()) { - if (error) *error = kTRUE; + if (error) + *error = kTRUE; return 0.; } size_t pos = 0; auto it = fProperties.begin(); - while (pos < i) { ++it; ++pos; } - if (error) *error = kFALSE; + while (pos < i) { + ++it; + ++pos; + } + if (error) + *error = kFALSE; name = (*it).first; return (*it).second; } @@ -624,7 +692,7 @@ Double_t TGeoManager::GetProperty(size_t i, TString &name, Bool_t *error) const Int_t TGeoManager::AddTransformation(const TGeoMatrix *matrix) { - return TGeoBuilder::Instance(this)->AddTransformation((TGeoMatrix*)matrix); + return TGeoBuilder::Instance(this)->AddTransformation((TGeoMatrix *)matrix); } //////////////////////////////////////////////////////////////////////////////// @@ -632,7 +700,7 @@ Int_t TGeoManager::AddTransformation(const TGeoMatrix *matrix) Int_t TGeoManager::AddShape(const TGeoShape *shape) { - return TGeoBuilder::Instance(this)->AddShape((TGeoShape*)shape); + return TGeoBuilder::Instance(this)->AddShape((TGeoShape *)shape); } //////////////////////////////////////////////////////////////////////////////// @@ -643,7 +711,7 @@ Int_t TGeoManager::AddShape(const TGeoShape *shape) Int_t TGeoManager::AddTrack(Int_t id, Int_t pdgcode, TObject *particle) { Int_t index = fNtracks; - fTracks->AddAtAndExpand(GetGeomPainter()->AddTrack(id,pdgcode,particle),fNtracks++); + fTracks->AddAtAndExpand(GetGeomPainter()->AddTrack(id, pdgcode, particle), fNtracks++); return index; } @@ -653,7 +721,7 @@ Int_t TGeoManager::AddTrack(Int_t id, Int_t pdgcode, TObject *particle) Int_t TGeoManager::AddTrack(TVirtualGeoTrack *track) { Int_t index = fNtracks; - fTracks->AddAtAndExpand(track,fNtracks++); + fTracks->AddAtAndExpand(track, fNtracks++); return index; } @@ -663,7 +731,7 @@ Int_t TGeoManager::AddTrack(TVirtualGeoTrack *track) TVirtualGeoTrack *TGeoManager::MakeTrack(Int_t id, Int_t pdgcode, TObject *particle) { - TVirtualGeoTrack *track = GetGeomPainter()->AddTrack(id,pdgcode,particle); + TVirtualGeoTrack *track = GetGeomPainter()->AddTrack(id, pdgcode, particle); return track; } @@ -677,18 +745,19 @@ Int_t TGeoManager::AddVolume(TGeoVolume *volume) return -1; } Int_t uid = fUniqueVolumes->GetEntriesFast(); - if (!uid) uid++; + if (!uid) + uid++; if (!fCurrentVolume) { fCurrentVolume = volume; - fUniqueVolumes->AddAtAndExpand(volume,uid); + fUniqueVolumes->AddAtAndExpand(volume, uid); } else { if (!strcmp(volume->GetName(), fCurrentVolume->GetName())) { uid = fCurrentVolume->GetNumber(); } else { fCurrentVolume = volume; Int_t olduid = GetUID(volume->GetName()); - if (olduid<0) { - fUniqueVolumes->AddAtAndExpand(volume,uid); + if (olduid < 0) { + fUniqueVolumes->AddAtAndExpand(volume, uid); } else { uid = olduid; } @@ -707,7 +776,7 @@ Int_t TGeoManager::AddVolume(TGeoVolume *volume) fHashVolumes->Add(volume); } Int_t index = list->GetEntriesFast(); - list->AddAtAndExpand(volume,index); + list->AddAtAndExpand(volume, index); return uid; } @@ -717,18 +786,24 @@ Int_t TGeoManager::AddVolume(TGeoVolume *volume) TGeoNavigator *TGeoManager::AddNavigator() { - if (fMultiThread) { TGeoManager::ThreadId(); fgMutex.lock(); } + if (fMultiThread) { + TGeoManager::ThreadId(); + fgMutex.lock(); + } std::thread::id threadId = std::this_thread::get_id(); NavigatorsMap_t::const_iterator it = fNavigators.find(threadId); TGeoNavigatorArray *array = 0; - if (it != fNavigators.end()) array = it->second; + if (it != fNavigators.end()) + array = it->second; else { array = new TGeoNavigatorArray(this); fNavigators.insert(NavigatorsMap_t::value_type(threadId, array)); } TGeoNavigator *nav = array->AddNavigator(); - if (fClosed) nav->GetCache()->BuildInfoBranch(); - if (fMultiThread) fgMutex.unlock(); + if (fClosed) + nav->GetCache()->BuildInfoBranch(); + if (fMultiThread) + fgMutex.unlock(); return nav; } @@ -737,13 +812,16 @@ TGeoNavigator *TGeoManager::AddNavigator() TGeoNavigator *TGeoManager::GetCurrentNavigator() const { - TTHREAD_TLS(TGeoNavigator*) tnav = 0; - if (!fMultiThread) return fCurrentNavigator; + TTHREAD_TLS(TGeoNavigator *) tnav = 0; + if (!fMultiThread) + return fCurrentNavigator; TGeoNavigator *nav = tnav; // TTHREAD_TLS_GET(TGeoNavigator*,tnav); - if (nav) return nav; + if (nav) + return nav; std::thread::id threadId = std::this_thread::get_id(); NavigatorsMap_t::const_iterator it = fNavigators.find(threadId); - if (it == fNavigators.end()) return 0; + if (it == fNavigators.end()) + return 0; TGeoNavigatorArray *array = it->second; nav = array->GetCurrentNavigator(); tnav = nav; // TTHREAD_TLS_SET(TGeoNavigator*,tnav,nav); @@ -757,7 +835,8 @@ TGeoNavigatorArray *TGeoManager::GetListOfNavigators() const { std::thread::id threadId = std::this_thread::get_id(); NavigatorsMap_t::const_iterator it = fNavigators.find(threadId); - if (it == fNavigators.end()) return 0; + if (it == fNavigators.end()) + return 0; TGeoNavigatorArray *array = it->second; return array; } @@ -781,7 +860,8 @@ Bool_t TGeoManager::SetCurrentNavigator(Int_t index) std::cout << " thread id: " << threadId << std::endl; return kFALSE; } - if (!fMultiThread) fCurrentNavigator = nav; + if (!fMultiThread) + fCurrentNavigator = nav; return kTRUE; } @@ -798,15 +878,17 @@ void TGeoManager::SetNavigatorsLock(Bool_t flag) void TGeoManager::ClearNavigators() { - if (fMultiThread) fgMutex.lock(); + if (fMultiThread) + fgMutex.lock(); TGeoNavigatorArray *arr = 0; - for (NavigatorsMap_t::iterator it = fNavigators.begin(); - it != fNavigators.end(); ++it) { + for (NavigatorsMap_t::iterator it = fNavigators.begin(); it != fNavigators.end(); ++it) { arr = (*it).second; - if (arr) delete arr; + if (arr) + delete arr; } fNavigators.clear(); - if (fMultiThread) fgMutex.unlock(); + if (fMultiThread) + fgMutex.unlock(); } //////////////////////////////////////////////////////////////////////////////// @@ -814,20 +896,24 @@ void TGeoManager::ClearNavigators() void TGeoManager::RemoveNavigator(const TGeoNavigator *nav) { - if (fMultiThread) fgMutex.lock(); + if (fMultiThread) + fgMutex.lock(); for (NavigatorsMap_t::iterator it = fNavigators.begin(); it != fNavigators.end(); ++it) { TGeoNavigatorArray *arr = (*it).second; if (arr) { - if ((TGeoNavigator*)arr->Remove((TObject*)nav)) { + if ((TGeoNavigator *)arr->Remove((TObject *)nav)) { delete nav; - if (!arr->GetEntries()) fNavigators.erase(it); - if (fMultiThread) fgMutex.unlock(); + if (!arr->GetEntries()) + fNavigators.erase(it); + if (fMultiThread) + fgMutex.unlock(); return; } } } Error("Remove navigator", "Navigator %p not found", nav); - if (fMultiThread) fgMutex.unlock(); + if (fMultiThread) + fgMutex.unlock(); } //////////////////////////////////////////////////////////////////////////////// @@ -853,8 +939,8 @@ void TGeoManager::SetMaxThreads(Int_t nthreads) ClearThreadsMap(); ClearThreadData(); } - fMaxThreads = nthreads+1; - if (fMaxThreads>0) { + fMaxThreads = nthreads + 1; + if (fMaxThreads > 0) { fMultiThread = kTRUE; CreateThreadData(); } @@ -864,11 +950,13 @@ void TGeoManager::SetMaxThreads(Int_t nthreads) void TGeoManager::ClearThreadData() const { - if (!fMaxThreads) return; + if (!fMaxThreads) + return; fgMutex.lock(); TIter next(fVolumes); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) vol->ClearThreadData(); + while ((vol = (TGeoVolume *)next())) + vol->ClearThreadData(); fgMutex.unlock(); } @@ -877,11 +965,13 @@ void TGeoManager::ClearThreadData() const void TGeoManager::CreateThreadData() const { - if (!fMaxThreads) return; + if (!fMaxThreads) + return; fgMutex.lock(); TIter next(fVolumes); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) vol->CreateThreadData(fMaxThreads); + while ((vol = (TGeoVolume *)next())) + vol->CreateThreadData(fMaxThreads); fgMutex.unlock(); } @@ -891,9 +981,11 @@ void TGeoManager::CreateThreadData() const void TGeoManager::ClearThreadsMap() { - if (gGeoManager && !gGeoManager->IsMultiThread()) return; + if (gGeoManager && !gGeoManager->IsMultiThread()) + return; fgMutex.lock(); - if (!fgThreadId->empty()) fgThreadId->clear(); + if (!fgThreadId->empty()) + fgThreadId->clear(); fgNumThreads = 0; fgMutex.unlock(); } @@ -906,11 +998,14 @@ Int_t TGeoManager::ThreadId() { TTHREAD_TLS(Int_t) tid = -1; Int_t ttid = tid; // TTHREAD_TLS_GET(Int_t,tid); - if (ttid > -1) return ttid; - if (gGeoManager && !gGeoManager->IsMultiThread()) return 0; + if (ttid > -1) + return ttid; + if (gGeoManager && !gGeoManager->IsMultiThread()) + return 0; std::thread::id threadId = std::this_thread::get_id(); TGeoManager::ThreadsMapIt_t it = fgThreadId->find(threadId); - if (it != fgThreadId->end()) return it->second; + if (it != fgThreadId->end()) + return it->second; // Map needs to be updated. fgMutex.lock(); (*fgThreadId)[threadId] = fgNumThreads; @@ -925,24 +1020,34 @@ Int_t TGeoManager::ThreadId() void TGeoManager::Browse(TBrowser *b) { - if (!b) return; - if (fMaterials) b->Add(fMaterials, "Materials"); - if (fMedia) b->Add(fMedia, "Media"); - if (fMatrices) b->Add(fMatrices, "Local transformations"); - if (fOverlaps) b->Add(fOverlaps, "Illegal overlaps"); - if (fTracks) b->Add(fTracks, "Tracks"); - if (fMasterVolume) b->Add(fMasterVolume, "Master Volume", fMasterVolume->IsVisible()); - if (fTopVolume) b->Add(fTopVolume, "Top Volume", fTopVolume->IsVisible()); - if (fTopNode) b->Add(fTopNode); + if (!b) + return; + if (fMaterials) + b->Add(fMaterials, "Materials"); + if (fMedia) + b->Add(fMedia, "Media"); + if (fMatrices) + b->Add(fMatrices, "Local transformations"); + if (fOverlaps) + b->Add(fOverlaps, "Illegal overlaps"); + if (fTracks) + b->Add(fTracks, "Tracks"); + if (fMasterVolume) + b->Add(fMasterVolume, "Master Volume", fMasterVolume->IsVisible()); + if (fTopVolume) + b->Add(fTopVolume, "Top Volume", fTopVolume->IsVisible()); + if (fTopNode) + b->Add(fTopNode); TString browserImp(gEnv->GetValue("Browser.Name", "TRootBrowserLite")); - TQObject::Connect(browserImp.Data(), "Checked(TObject*,Bool_t)", - "TGeoManager", this, "SetVisibility(TObject*,Bool_t)"); + TQObject::Connect(browserImp.Data(), "Checked(TObject*,Bool_t)", "TGeoManager", this, + "SetVisibility(TObject*,Bool_t)"); } //////////////////////////////////////////////////////////////////////////////// /// Append a pad for this geometry. -void TGeoManager::Edit(Option_t *option) { +void TGeoManager::Edit(Option_t *option) +{ AppendPad(""); GetGeomPainter()->EditGeometry(option); } @@ -952,14 +1057,15 @@ void TGeoManager::Edit(Option_t *option) { void TGeoManager::SetVisibility(TObject *obj, Bool_t vis) { - if(obj->IsA() == TGeoVolume::Class()) { - TGeoVolume *vol = (TGeoVolume *) obj; + if (obj->IsA() == TGeoVolume::Class()) { + TGeoVolume *vol = (TGeoVolume *)obj; vol->SetVisibility(vis); } else { if (obj->InheritsFrom(TGeoNode::Class())) { - TGeoNode *node = (TGeoNode *) obj; + TGeoNode *node = (TGeoNode *)obj; node->SetVisibility(vis); - } else return; + } else + return; } GetGeomPainter()->ModifiedPad(kTRUE); } @@ -969,7 +1075,8 @@ void TGeoManager::SetVisibility(TObject *obj, Bool_t vis) void TGeoManager::BombTranslation(const Double_t *tr, Double_t *bombtr) { - if (fPainter) fPainter->BombTranslation(tr, bombtr); + if (fPainter) + fPainter->BombTranslation(tr, bombtr); return; } @@ -978,7 +1085,8 @@ void TGeoManager::BombTranslation(const Double_t *tr, Double_t *bombtr) void TGeoManager::UnbombTranslation(const Double_t *tr, Double_t *bombtr) { - if (fPainter) fPainter->UnbombTranslation(tr, bombtr); + if (fPainter) + fPainter->UnbombTranslation(tr, bombtr); return; } @@ -1004,7 +1112,7 @@ void TGeoManager::DoRestoreState() void TGeoManager::RegisterMatrix(const TGeoMatrix *matrix) { - return TGeoBuilder::Instance(this)->RegisterMatrix((TGeoMatrix*)matrix); + return TGeoBuilder::Instance(this)->RegisterMatrix((TGeoMatrix *)matrix); } //////////////////////////////////////////////////////////////////////////////// @@ -1015,66 +1123,75 @@ void TGeoManager::RegisterMatrix(const TGeoMatrix *matrix) Int_t TGeoManager::ReplaceVolume(TGeoVolume *vorig, TGeoVolume *vnew) { Int_t nref = 0; - if (!vorig || !vnew) return nref; + if (!vorig || !vnew) + return nref; TGeoMedium *morig = vorig->GetMedium(); Bool_t checkmed = kFALSE; - if (morig) checkmed = kTRUE; + if (morig) + checkmed = kTRUE; TGeoMedium *mnew = vnew->GetMedium(); // Try to limit the damage produced by incorrect usage. if (!mnew && !vnew->IsAssembly()) { - Error("ReplaceVolume","Replacement volume %s has no medium and it is not an assembly", - vnew->GetName()); + Error("ReplaceVolume", "Replacement volume %s has no medium and it is not an assembly", vnew->GetName()); return nref; } if (mnew && checkmed) { if (mnew->GetId() != morig->GetId()) - Warning("ReplaceVolume","Replacement volume %s has different medium than original volume %s", - vnew->GetName(), vorig->GetName()); + Warning("ReplaceVolume", "Replacement volume %s has different medium than original volume %s", vnew->GetName(), + vorig->GetName()); checkmed = kFALSE; } // Medium checking now performed only if replacement is an assembly and old volume a real one. // Check result is dependent on positioning. Int_t nvol = fVolumes->GetEntriesFast(); - Int_t i,j,nd; + Int_t i, j, nd; Int_t ierr = 0; TGeoVolume *vol; TGeoNode *node; TGeoVoxelFinder *voxels; - for (i=0; iAt(i); - if (!vol) continue; - if (vol==vorig || vol==vnew) continue; + for (i = 0; i < nvol; i++) { + vol = (TGeoVolume *)fVolumes->At(i); + if (!vol) + continue; + if (vol == vorig || vol == vnew) + continue; nd = vol->GetNdaughters(); - for (j=0; jGetNode(j); if (node->GetVolume() == vorig) { if (checkmed) { mnew = node->GetMotherVolume()->GetMedium(); - if (mnew && mnew->GetId()!=morig->GetId()) ierr++; + if (mnew && mnew->GetId() != morig->GetId()) + ierr++; } nref++; if (node->IsOverlapping()) { node->SetOverlapping(kFALSE); - Info("ReplaceVolume","%s replaced with assembly and declared NON-OVERLAPPING!",node->GetName()); + Info("ReplaceVolume", "%s replaced with assembly and declared NON-OVERLAPPING!", node->GetName()); } node->SetVolume(vnew); voxels = node->GetMotherVolume()->GetVoxels(); - if (voxels) voxels->SetNeedRebuild(); + if (voxels) + voxels->SetNeedRebuild(); } else { if (node->GetMotherVolume() == vorig) { nref++; node->SetMotherVolume(vnew); if (node->IsOverlapping()) { node->SetOverlapping(kFALSE); - Info("ReplaceVolume","%s inside substitute assembly %s declared NON-OVERLAPPING!",node->GetName(),vnew->GetName()); + Info("ReplaceVolume", "%s inside substitute assembly %s declared NON-OVERLAPPING!", node->GetName(), + vnew->GetName()); } } } } } - if (ierr) Warning("ReplaceVolume", "Volumes should not be replaced with assemblies if they are positioned in containers having a different medium ID.\n %i occurrences for assembly replacing volume %s", - ierr, vorig->GetName()); + if (ierr) + Warning("ReplaceVolume", + "Volumes should not be replaced with assemblies if they are positioned in containers having a different " + "medium ID.\n %i occurrences for assembly replacing volume %s", + ierr, vorig->GetName()); return nref; } @@ -1093,7 +1210,7 @@ Int_t TGeoManager::TransformVolumeToAssembly(const char *vname) Int_t indmax = fVolumes->GetEntries(); Bool_t replace = kTRUE; TGeoVolume *transformed; - while (indexIsAssembly()) Warning("TransformVolumeToAssembly", "Volume %s already assembly", toTransform->GetName()); if (!toTransform->GetNdaughters()) - Warning("TransformVolumeToAssembly", "Volume %s has no daughters, cannot transform", toTransform->GetName()); + Warning("TransformVolumeToAssembly", "Volume %s has no daughters, cannot transform", + toTransform->GetName()); if (toTransform->IsVolumeMulti()) Warning("TransformVolumeToAssembly", "Volume %s divided, cannot transform", toTransform->GetName()); } } index++; - if (index >= indmax) return count; - toTransform = (TGeoVolume*)fVolumes->At(index); - if (!strcmp(toTransform->GetName(),vname)) replace = kTRUE; + if (index >= indmax) + return count; + toTransform = (TGeoVolume *)fVolumes->At(index); + if (!strcmp(toTransform->GetName(), vname)) + replace = kTRUE; } return count; } @@ -1133,8 +1253,8 @@ Int_t TGeoManager::TransformVolumeToAssembly(const char *vname) /// in full range (same effect as NDIV<=0) (GSDVS, GSDVT in G3) /// - SX - same as DVS, but from START position. (GSDVS2, GSDVT2 in G3) -TGeoVolume *TGeoManager::Division(const char *name, const char *mother, Int_t iaxis, - Int_t ndiv, Double_t start, Double_t step, Int_t numed, Option_t *option) +TGeoVolume *TGeoManager::Division(const char *name, const char *mother, Int_t iaxis, Int_t ndiv, Double_t start, + Double_t step, Int_t numed, Option_t *option) { return TGeoBuilder::Instance(this)->Division(name, mother, iaxis, ndiv, start, step, numed, option); } @@ -1151,9 +1271,8 @@ TGeoVolume *TGeoManager::Division(const char *name, const char *mother, Int_t ia /// - phi3 azimuthal angle for axis Z /// -void TGeoManager::Matrix(Int_t index, Double_t theta1, Double_t phi1, - Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3) +void TGeoManager::Matrix(Int_t index, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, + Double_t phi3) { TGeoBuilder::Instance(this)->Matrix(index, theta1, phi1, theta2, phi2, theta3, phi3); } @@ -1161,18 +1280,18 @@ void TGeoManager::Matrix(Int_t index, Double_t theta1, Double_t phi1, //////////////////////////////////////////////////////////////////////////////// /// Create material with given A, Z and density, having an unique id. -TGeoMaterial *TGeoManager::Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid,Double_t radlen, Double_t intlen) +TGeoMaterial *TGeoManager::Material(const char *name, Double_t a, Double_t z, Double_t dens, Int_t uid, Double_t radlen, + Double_t intlen) { return TGeoBuilder::Instance(this)->Material(name, a, z, dens, uid, radlen, intlen); - } //////////////////////////////////////////////////////////////////////////////// /// Create mixture OR COMPOUND IMAT as composed by THE BASIC nelem /// materials defined by arrays A,Z and WMAT, having an unique id. -TGeoMaterial *TGeoManager::Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, - Int_t nelem, Float_t *wmat, Int_t uid) +TGeoMaterial * +TGeoManager::Mixture(const char *name, Float_t *a, Float_t *z, Double_t dens, Int_t nelem, Float_t *wmat, Int_t uid) { return TGeoBuilder::Instance(this)->Mixture(name, a, z, dens, nelem, wmat, uid); } @@ -1181,8 +1300,8 @@ TGeoMaterial *TGeoManager::Mixture(const char *name, Float_t *a, Float_t *z, Dou /// Create mixture OR COMPOUND IMAT as composed by THE BASIC nelem /// materials defined by arrays A,Z and WMAT, having an unique id. -TGeoMaterial *TGeoManager::Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, - Int_t nelem, Double_t *wmat, Int_t uid) +TGeoMaterial * +TGeoManager::Mixture(const char *name, Double_t *a, Double_t *z, Double_t dens, Int_t nelem, Double_t *wmat, Int_t uid) { return TGeoBuilder::Instance(this)->Mixture(name, a, z, dens, nelem, wmat, uid); } @@ -1207,12 +1326,11 @@ TGeoMaterial *TGeoManager::Mixture(const char *name, Double_t *a, Double_t *z, D /// performed with g3helix; ifield = 3 if tracking performed with g3helx3. /// -TGeoMedium *TGeoManager::Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, - Int_t ifield, Double_t fieldm, Double_t tmaxfd, - Double_t stemax, Double_t deemax, Double_t epsil, - Double_t stmin) +TGeoMedium *TGeoManager::Medium(const char *name, Int_t numed, Int_t nmat, Int_t isvol, Int_t ifield, Double_t fieldm, + Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin) { - return TGeoBuilder::Instance(this)->Medium(name, numed, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, epsil, stmin); + return TGeoBuilder::Instance(this)->Medium(name, numed, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, epsil, + stmin); } //////////////////////////////////////////////////////////////////////////////// @@ -1230,8 +1348,7 @@ TGeoMedium *TGeoManager::Medium(const char *name, Int_t numed, Int_t nmat, Int_t /// - IROT Rotation matrix number w.r.t. mother ref. sys. /// - ISONLY ONLY/MANY flag -void TGeoManager::Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, +void TGeoManager::Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, Bool_t isOnly, Float_t *upar, Int_t npar) { TGeoBuilder::Instance(this)->Node(name, nr, mother, x, y, z, irot, isOnly, upar, npar); @@ -1252,12 +1369,10 @@ void TGeoManager::Node(const char *name, Int_t nr, const char *mother, /// - IROT Rotation matrix number w.r.t. mother ref. sys. /// - ISONLY ONLY/MANY flag -void TGeoManager::Node(const char *name, Int_t nr, const char *mother, - Double_t x, Double_t y, Double_t z, Int_t irot, +void TGeoManager::Node(const char *name, Int_t nr, const char *mother, Double_t x, Double_t y, Double_t z, Int_t irot, Bool_t isOnly, Double_t *upar, Int_t npar) { TGeoBuilder::Instance(this)->Node(name, nr, mother, x, y, z, irot, isOnly, upar, npar); - } //////////////////////////////////////////////////////////////////////////////// @@ -1268,8 +1383,7 @@ void TGeoManager::Node(const char *name, Int_t nr, const char *mother, /// - NPAR Number of shape parameters /// - UPAR Vector containing shape parameters -TGeoVolume *TGeoManager::Volume(const char *name, const char *shape, Int_t nmed, - Float_t *upar, Int_t npar) +TGeoVolume *TGeoManager::Volume(const char *name, const char *shape, Int_t nmed, Float_t *upar, Int_t npar) { return TGeoBuilder::Instance(this)->Volume(name, shape, nmed, upar, npar); } @@ -1282,8 +1396,7 @@ TGeoVolume *TGeoManager::Volume(const char *name, const char *shape, Int_t nmed, /// - NPAR Number of shape parameters /// - UPAR Vector containing shape parameters -TGeoVolume *TGeoManager::Volume(const char *name, const char *shape, Int_t nmed, - Double_t *upar, Int_t npar) +TGeoVolume *TGeoManager::Volume(const char *name, const char *shape, Int_t nmed, Double_t *upar, Int_t npar) { return TGeoBuilder::Instance(this)->Volume(name, shape, nmed, upar, npar); } @@ -1296,39 +1409,41 @@ void TGeoManager::SetAllIndex() Int_t index = 1; TIter next(fMaterials); TGeoMaterial *mater; - while ((mater=(TGeoMaterial*)next())) { + while ((mater = (TGeoMaterial *)next())) { mater->SetUniqueID(index++); mater->ResetBit(TGeoMaterial::kMatSavePrimitive); } index = 1; TIter next1(fMedia); TGeoMedium *med; - while ((med=(TGeoMedium*)next1())) { + while ((med = (TGeoMedium *)next1())) { med->SetUniqueID(index++); med->ResetBit(TGeoMedium::kMedSavePrimitive); } index = 1; TIter next2(fShapes); TGeoShape *shape; - while ((shape=(TGeoShape*)next2())) { + while ((shape = (TGeoShape *)next2())) { shape->SetUniqueID(index++); - if (shape->IsComposite()) ((TGeoCompositeShape*)shape)->GetBoolNode()->RegisterMatrices(); + if (shape->IsComposite()) + ((TGeoCompositeShape *)shape)->GetBoolNode()->RegisterMatrices(); } TIter next3(fMatrices); TGeoMatrix *matrix; - while ((matrix=(TGeoMatrix*)next3())) { + while ((matrix = (TGeoMatrix *)next3())) { matrix->RegisterYourself(); } TIter next4(fMatrices); index = 1; - while ((matrix=(TGeoMatrix*)next4())) { + while ((matrix = (TGeoMatrix *)next4())) { matrix->SetUniqueID(index++); matrix->ResetBit(TGeoMatrix::kGeoSavePrimitive); } TIter next5(fVolumes); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next5())) vol->UnmarkSaved(); + while ((vol = (TGeoVolume *)next5())) + vol->UnmarkSaved(); } //////////////////////////////////////////////////////////////////////////////// @@ -1337,17 +1452,20 @@ void TGeoManager::SetAllIndex() void TGeoManager::ClearAttributes() { - if (gPad) delete gPad; + if (gPad) + delete gPad; gPad = 0; SetVisOption(0); SetVisLevel(3); SetExplodedView(0); SetBombFactors(); - if (!gStyle) return; + if (!gStyle) + return; TIter next(fVolumes); TGeoVolume *vol = 0; - while ((vol=(TGeoVolume*)next())) { - if (!vol->IsVisTouched()) continue; + while ((vol = (TGeoVolume *)next())) { + if (!vol->IsVisTouched()) + continue; vol->SetVisTouched(kFALSE); } } @@ -1364,76 +1482,92 @@ void TGeoManager::CloseGeometry(Option_t *option) return; } if (!fMasterVolume) { - Error("CloseGeometry","you MUST call SetTopVolume() first !"); + Error("CloseGeometry", "you MUST call SetTopVolume() first !"); return; } - if (!gROOT->GetListOfGeometries()->FindObject(this)) gROOT->GetListOfGeometries()->Add(this); - if (!gROOT->GetListOfBrowsables()->FindObject(this)) gROOT->GetListOfBrowsables()->Add(this); -// TSeqCollection *brlist = gROOT->GetListOfBrowsers(); -// TIter next(brlist); -// TBrowser *browser = 0; -// while ((browser=(TBrowser*)next())) browser->Refresh(); + if (!gROOT->GetListOfGeometries()->FindObject(this)) + gROOT->GetListOfGeometries()->Add(this); + if (!gROOT->GetListOfBrowsables()->FindObject(this)) + gROOT->GetListOfBrowsables()->Add(this); + // TSeqCollection *brlist = gROOT->GetListOfBrowsers(); + // TIter next(brlist); + // TBrowser *browser = 0; + // while ((browser=(TBrowser*)next())) browser->Refresh(); TString opt(option); opt.ToLower(); -// Bool_t dummy = opt.Contains("d"); + // Bool_t dummy = opt.Contains("d"); Bool_t nodeid = opt.Contains("i"); // Create a geometry navigator if not present TGeoNavigator *nav = 0; Int_t nnavigators = 0; // Check if the geometry is streamed from file if (fIsGeomReading) { - if (fgVerboseLevel>0) Info("CloseGeometry","Geometry loaded from file..."); - gGeoIdentity=(TGeoIdentity *)fMatrices->At(0); - if (!fElementTable) fElementTable = new TGeoElementTable(200); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "Geometry loaded from file..."); + gGeoIdentity = (TGeoIdentity *)fMatrices->At(0); + if (!fElementTable) + fElementTable = new TGeoElementTable(200); if (!fTopNode) { if (!fMasterVolume) { Error("CloseGeometry", "Master volume not streamed"); return; } SetTopVolume(fMasterVolume); - if (fStreamVoxels && fgVerboseLevel>0) Info("CloseGeometry","Voxelization retrieved from file"); + if (fStreamVoxels && fgVerboseLevel > 0) + Info("CloseGeometry", "Voxelization retrieved from file"); } // Create a geometry navigator if not present - if (!GetCurrentNavigator()) fCurrentNavigator = AddNavigator(); + if (!GetCurrentNavigator()) + fCurrentNavigator = AddNavigator(); nnavigators = GetListOfNavigators()->GetEntriesFast(); if (!opt.Contains("nv")) { Voxelize("ALL"); } CountLevels(); - for (Int_t i=0; iAt(i); + for (Int_t i = 0; i < nnavigators; i++) { + nav = (TGeoNavigator *)GetListOfNavigators()->At(i); nav->GetCache()->BuildInfoBranch(); - if (nodeid) nav->GetCache()->BuildIdArray(); + if (nodeid) + nav->GetCache()->BuildIdArray(); } if (!fHashVolumes) { Int_t nvol = fVolumes->GetEntriesFast(); Int_t ngvol = fGVolumes->GetEntriesFast(); - fHashVolumes = new THashList(nvol+1); - fHashGVolumes = new THashList(ngvol+1); + fHashVolumes = new THashList(nvol + 1); + fHashGVolumes = new THashList(ngvol + 1); Int_t i; - for (i=0; iAddLast(fGVolumes->At(i)); - for (i=0; iAddLast(fVolumes->At(i)); + for (i = 0; i < ngvol; i++) + fHashGVolumes->AddLast(fGVolumes->At(i)); + for (i = 0; i < nvol; i++) + fHashVolumes->AddLast(fVolumes->At(i)); } fClosed = kTRUE; if (fParallelWorld) { - if (fgVerboseLevel>0) Info("CloseGeometry","Recreating parallel world %s ...",fParallelWorld->GetName()); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "Recreating parallel world %s ...", fParallelWorld->GetName()); fParallelWorld->CloseGeometry(); } - if (fgVerboseLevel>0) Info("CloseGeometry","%i nodes/ %i volume UID's in %s", fNNodes, fUniqueVolumes->GetEntriesFast()-1, GetTitle()); - if (fgVerboseLevel>0) Info("CloseGeometry","----------------modeler ready----------------"); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "%i nodes/ %i volume UID's in %s", fNNodes, fUniqueVolumes->GetEntriesFast() - 1, + GetTitle()); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "----------------modeler ready----------------"); return; } // Create a geometry navigator if not present - if (!GetCurrentNavigator()) fCurrentNavigator = AddNavigator(); + if (!GetCurrentNavigator()) + fCurrentNavigator = AddNavigator(); nnavigators = GetListOfNavigators()->GetEntriesFast(); SelectTrackingMedia(); CheckGeometry(); - if (fgVerboseLevel>0) Info("CloseGeometry","Counting nodes..."); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "Counting nodes..."); fNNodes = CountNodes(); - fNLevel = fMasterVolume->CountNodes(1,3)+1; - if (fNLevel<30) fNLevel = 100; + fNLevel = fMasterVolume->CountNodes(1, 3) + 1; + if (fNLevel < 30) + fNLevel = 100; // BuildIdArray(); // avoid voxelization if requested to speed up geometry startup @@ -1446,17 +1580,20 @@ void TGeoManager::CloseGeometry(Option_t *option) vol->SortNodes(); } } - if (fgVerboseLevel>0) Info("CloseGeometry","Building cache..."); + if (fgVerboseLevel > 0) + Info("CloseGeometry", "Building cache..."); CountLevels(); - for (Int_t i=0; iAt(i); + for (Int_t i = 0; i < nnavigators; i++) { + nav = (TGeoNavigator *)GetListOfNavigators()->At(i); nav->GetCache()->BuildInfoBranch(); - if (nodeid) nav->GetCache()->BuildIdArray(); + if (nodeid) + nav->GetCache()->BuildIdArray(); } fClosed = kTRUE; - if (fgVerboseLevel>0) { - Info("CloseGeometry","%i nodes/ %i volume UID's in %s", fNNodes, fUniqueVolumes->GetEntriesFast()-1, GetTitle()); - Info("CloseGeometry","----------------modeler ready----------------"); + if (fgVerboseLevel > 0) { + Info("CloseGeometry", "%i nodes/ %i volume UID's in %s", fNNodes, fUniqueVolumes->GetEntriesFast() - 1, + GetTitle()); + Info("CloseGeometry", "----------------modeler ready----------------"); } } @@ -1477,7 +1614,8 @@ void TGeoManager::ClearOverlaps() void TGeoManager::ClearShape(const TGeoShape *shape) { - if (fShapes->FindObject(shape)) fShapes->Remove((TGeoShape*)shape); + if (fShapes->FindObject(shape)) + fShapes->Remove((TGeoShape *)shape); delete shape; } @@ -1486,14 +1624,16 @@ void TGeoManager::ClearShape(const TGeoShape *shape) void TGeoManager::CleanGarbage() { - if (!fGVolumes && !fGShapes) return; - Int_t i,nentries; + if (!fGVolumes && !fGShapes) + return; + Int_t i, nentries; if (fGVolumes) { nentries = fGVolumes->GetEntries(); TGeoVolume *vol = 0; - for (i=0; iAt(i); - if (vol) vol->SetFinder(0); + for (i = 0; i < nentries; i++) { + vol = (TGeoVolume *)fGVolumes->At(i); + if (vol) + vol->SetFinder(0); } fGVolumes->Delete(); delete fGVolumes; @@ -1580,31 +1720,34 @@ Bool_t TGeoManager::CheckPath(const char *path) const void TGeoManager::ConvertReflections() { - if (!fTopNode) return; - if (fgVerboseLevel>0) Info("ConvertReflections", "Converting reflections in: %s - %s ...", GetName(), GetTitle()); + if (!fTopNode) + return; + if (fgVerboseLevel > 0) + Info("ConvertReflections", "Converting reflections in: %s - %s ...", GetName(), GetTitle()); TGeoIterator next(fTopVolume); TGeoNode *node; TGeoNodeMatrix *nodematrix; TGeoMatrix *matrix, *mclone; TGeoVolume *reflected; - while ((node=next())) { + while ((node = next())) { matrix = node->GetMatrix(); if (matrix->IsReflection()) { -// printf("%s before\n", node->GetName()); -// matrix->Print(); + // printf("%s before\n", node->GetName()); + // matrix->Print(); mclone = new TGeoCombiTrans(*matrix); mclone->RegisterYourself(); // Reflect just the rotation component mclone->ReflectZ(kFALSE, kTRUE); - nodematrix = (TGeoNodeMatrix*)node; + nodematrix = (TGeoNodeMatrix *)node; nodematrix->SetMatrix(mclone); -// printf("%s after\n", node->GetName()); -// node->GetMatrix()->Print(); + // printf("%s after\n", node->GetName()); + // node->GetMatrix()->Print(); reflected = node->GetVolume()->MakeReflectedVolume(); node->SetVolume(reflected); } } - if (fgVerboseLevel>0) Info("ConvertReflections", "Done"); + if (fgVerboseLevel > 0) + Info("ConvertReflections", "Done"); } //////////////////////////////////////////////////////////////////////////////// @@ -1618,33 +1761,38 @@ void TGeoManager::CountLevels() return; } TGeoIterator next(fTopVolume); - Bool_t fixrefs = fIsGeomReading && (fMasterVolume->GetRefCount()==1); - if (fMasterVolume->GetRefCount()>1) fMasterVolume->Release(); - if (fgVerboseLevel>1 && fixrefs) Info("CountLevels", "Fixing volume reference counts"); + Bool_t fixrefs = fIsGeomReading && (fMasterVolume->GetRefCount() == 1); + if (fMasterVolume->GetRefCount() > 1) + fMasterVolume->Release(); + if (fgVerboseLevel > 1 && fixrefs) + Info("CountLevels", "Fixing volume reference counts"); TGeoNode *node; Int_t maxlevel = 1; Int_t maxnodes = fTopVolume->GetNdaughters(); Int_t maxvertices = 1; - while ((node=next())) { + while ((node = next())) { if (fixrefs) { node->GetVolume()->Grab(); - for (Int_t ibit=10; ibit<14; ibit++) { - node->SetBit(BIT(ibit+4), node->TestBit(BIT(ibit))); -// node->ResetBit(BIT(ibit)); // cannot overwrite old crap for reproducibility + for (Int_t ibit = 10; ibit < 14; ibit++) { + node->SetBit(BIT(ibit + 4), node->TestBit(BIT(ibit))); + // node->ResetBit(BIT(ibit)); // cannot overwrite old crap for reproducibility } } if (node->GetNdaughters() > maxnodes) maxnodes = node->GetNdaughters(); - if (next.GetLevel()>maxlevel) maxlevel = next.GetLevel(); - if (node->GetVolume()->GetShape()->IsA()==TGeoXtru::Class()) { - TGeoXtru *xtru = (TGeoXtru*)node->GetVolume()->GetShape(); - if (xtru->GetNvert()>maxvertices) maxvertices = xtru->GetNvert(); + if (next.GetLevel() > maxlevel) + maxlevel = next.GetLevel(); + if (node->GetVolume()->GetShape()->IsA() == TGeoXtru::Class()) { + TGeoXtru *xtru = (TGeoXtru *)node->GetVolume()->GetShape(); + if (xtru->GetNvert() > maxvertices) + maxvertices = xtru->GetNvert(); } } fgMaxLevel = maxlevel; fgMaxDaughters = maxnodes; fgMaxXtruVert = maxvertices; - if (fgVerboseLevel>0) Info("CountLevels", "max level = %d, max placements = %d", fgMaxLevel, fgMaxDaughters); + if (fgVerboseLevel > 0) + Info("CountLevels", "max level = %d, max placements = %d", fgMaxLevel, fgMaxDaughters); } //////////////////////////////////////////////////////////////////////////////// @@ -1656,7 +1804,7 @@ Int_t TGeoManager::CountNodes(const TGeoVolume *vol, Int_t nlevels, Int_t option if (!vol) { top = fTopVolume; } else { - top = (TGeoVolume*)vol; + top = (TGeoVolume *)vol; } Int_t count = top->CountNodes(nlevels, option); return count; @@ -1667,7 +1815,8 @@ Int_t TGeoManager::CountNodes(const TGeoVolume *vol, Int_t nlevels, Int_t option void TGeoManager::DefaultAngles() { - if (fPainter) fPainter->DefaultAngles(); + if (fPainter) + fPainter->DefaultAngles(); } //////////////////////////////////////////////////////////////////////////////// @@ -1675,7 +1824,8 @@ void TGeoManager::DefaultAngles() void TGeoManager::DrawCurrentPoint(Int_t color) { - if (fPainter) fPainter->DrawCurrentPoint(color); + if (fPainter) + fPainter->DrawCurrentPoint(color); } //////////////////////////////////////////////////////////////////////////////// @@ -1685,49 +1835,55 @@ void TGeoManager::AnimateTracks(Double_t tmin, Double_t tmax, Int_t nframes, Opt { SetAnimateTracks(); GetGeomPainter(); - if (tmin<0 || tmin>=tmax || nframes<1) return; + if (tmin < 0 || tmin >= tmax || nframes < 1) + return; Double_t *box = fPainter->GetViewBox(); box[0] = box[1] = box[2] = 0; box[3] = box[4] = box[5] = 100; - Double_t dt = (tmax-tmin)/Double_t(nframes); + Double_t dt = (tmax - tmin) / Double_t(nframes); Double_t delt = 2E-9; Double_t t = tmin; Int_t i, j; TString opt(option); - Bool_t save = kFALSE, geomanim=kFALSE; + Bool_t save = kFALSE, geomanim = kFALSE; TString fname; - if (opt.Contains("/S")) save = kTRUE; + if (opt.Contains("/S")) + save = kTRUE; - if (opt.Contains("/G")) geomanim = kTRUE; - SetTminTmax(0,0); + if (opt.Contains("/G")) + geomanim = kTRUE; + SetTminTmax(0, 0); DrawTracks(opt.Data()); - Double_t start[6] = {0,0,0,0,0,0}; - Double_t end[6] = {0,0,0,0,0,0}; - Double_t dd[6] = {0,0,0,0,0,0}; - Double_t dlat=0, dlong=0, dpsi=0; + Double_t start[6] = {0, 0, 0, 0, 0, 0}; + Double_t end[6] = {0, 0, 0, 0, 0, 0}; + Double_t dd[6] = {0, 0, 0, 0, 0, 0}; + Double_t dlat = 0, dlong = 0, dpsi = 0; if (geomanim) { - fPainter->EstimateCameraMove(tmin+5*dt, tmin+15*dt, start, end); - for (i=0; i<3; i++) { - start[i+3] = 20 + 1.3*start[i+3]; - end[i+3] = 20 + 0.9*end[i+3]; + fPainter->EstimateCameraMove(tmin + 5 * dt, tmin + 15 * dt, start, end); + for (i = 0; i < 3; i++) { + start[i + 3] = 20 + 1.3 * start[i + 3]; + end[i + 3] = 20 + 0.9 * end[i + 3]; } - for (i=0; i<6; i++) { - dd[i] = (end[i]-start[i])/10.; + for (i = 0; i < 6; i++) { + dd[i] = (end[i] - start[i]) / 10.; } - memcpy(box, start, 6*sizeof(Double_t)); - fPainter->GetViewAngles(dlong,dlat,dpsi); - dlong = (-206-dlong)/Double_t(nframes); - dlat = (126-dlat)/Double_t(nframes); - dpsi = (75-dpsi)/Double_t(nframes); + memcpy(box, start, 6 * sizeof(Double_t)); + fPainter->GetViewAngles(dlong, dlat, dpsi); + dlong = (-206 - dlong) / Double_t(nframes); + dlat = (126 - dlat) / Double_t(nframes); + dpsi = (75 - dpsi) / Double_t(nframes); fPainter->GrabFocus(); } - for (i=0; iSetTminTmax(t-delt,t); + for (i = 0; i < nframes; i++) { + if (t - delt < 0) + SetTminTmax(t - delt, t); + else + gGeoManager->SetTminTmax(t - delt, t); if (geomanim) { - for (j=0; j<6; j++) box[j]+=dd[j]; - fPainter->GrabFocus(1,dlong,dlat,dpsi); + for (j = 0; j < 6; j++) + box[j] += dd[j]; + fPainter->GrabFocus(1, dlong, dlat, dpsi); } else { ModifiedPad(); } @@ -1747,12 +1903,13 @@ void TGeoManager::AnimateTracks(Double_t tmin, Double_t tmax, Int_t nframes, Opt void TGeoManager::DrawTracks(Option_t *option) { TVirtualGeoTrack *track; - //SetVisLevel(1); - //SetVisOption(1); + // SetVisLevel(1); + // SetVisOption(1); SetAnimateTracks(); - for (Int_t i=0; iDraw(option); + if (track) + track->Draw(option); } SetAnimateTracks(kFALSE); ModifiedPad(); @@ -1763,7 +1920,8 @@ void TGeoManager::DrawTracks(Option_t *option) void TGeoManager::DrawPath(const char *path, Option_t *option) { - if (!fTopVolume) return; + if (!fTopVolume) + return; fTopVolume->SetVisBranch(); GetGeomPainter()->DrawPath(path, option); } @@ -1773,7 +1931,7 @@ void TGeoManager::DrawPath(const char *path, Option_t *option) void TGeoManager::RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option) { - GetGeomPainter()->RandomPoints((TGeoVolume*)vol, npoints, option); + GetGeomPainter()->RandomPoints((TGeoVolume *)vol, npoints, option); } //////////////////////////////////////////////////////////////////////////////// @@ -1787,7 +1945,7 @@ void TGeoManager::Test(Int_t npoints, Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Geometry overlap checker based on sampling. -void TGeoManager::TestOverlaps(const char* path) +void TGeoManager::TestOverlaps(const char *path) { GetGeomPainter()->TestOverlaps(path); } @@ -1805,10 +1963,12 @@ void TGeoManager::GetBranchNames(Int_t *names) const const char *TGeoManager::GetPdgName(Int_t pdg) const { - static char defaultname[5] = { "XXX" }; - if (!fPdgNames || !pdg) return defaultname; - for (Int_t i=0; iAt(i)->GetName(); + static char defaultname[5] = {"XXX"}; + if (!fPdgNames || !pdg) + return defaultname; + for (Int_t i = 0; i < fNpdg; i++) { + if (fPdgId[i] == pdg) + return fPdgNames->At(i)->GetName(); } return defaultname; } @@ -1818,13 +1978,15 @@ const char *TGeoManager::GetPdgName(Int_t pdg) const void TGeoManager::SetPdgName(Int_t pdg, const char *name) { - if (!pdg) return; + if (!pdg) + return; if (!fPdgNames) { fPdgNames = new TObjArray(1024); } - if (!strcmp(name, GetPdgName(pdg))) return; + if (!strcmp(name, GetPdgName(pdg))) + return; // store pdg name - if (fNpdg>1023) { + if (fNpdg > 1023) { Warning("SetPdgName", "No more than 256 different pdg codes allowed"); return; } @@ -1838,7 +2000,7 @@ void TGeoManager::SetPdgName(Int_t pdg, const char *name) TGDMLMatrix *TGeoManager::GetGDMLMatrix(const char *name) const { - return (TGDMLMatrix*)fGDMLMatrices->FindObject(name); + return (TGDMLMatrix *)fGDMLMatrices->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -1857,7 +2019,7 @@ void TGeoManager::AddGDMLMatrix(TGDMLMatrix *mat) TGeoOpticalSurface *TGeoManager::GetOpticalSurface(const char *name) const { - return (TGeoOpticalSurface*)fOpticalSurfaces->FindObject(name); + return (TGeoOpticalSurface *)fOpticalSurfaces->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -1876,7 +2038,7 @@ void TGeoManager::AddOpticalSurface(TGeoOpticalSurface *optsurf) TGeoSkinSurface *TGeoManager::GetSkinSurface(const char *name) const { - return (TGeoSkinSurface*)fSkinSurfaces->FindObject(name); + return (TGeoSkinSurface *)fSkinSurfaces->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -1895,7 +2057,7 @@ void TGeoManager::AddSkinSurface(TGeoSkinSurface *surf) TGeoBorderSurface *TGeoManager::GetBorderSurface(const char *name) const { - return (TGeoBorderSurface*)fBorderSurfaces->FindObject(name); + return (TGeoBorderSurface *)fBorderSurfaces->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -1974,7 +2136,8 @@ Int_t TGeoManager::GetNumThreads() TGeoHMatrix *TGeoManager::GetHMatrix() { - if (!GetCurrentNavigator()) return NULL; + if (!GetCurrentNavigator()) + return NULL; return GetCurrentNavigator()->GetHMatrix(); } @@ -2014,15 +2177,17 @@ Int_t TGeoManager::GetVirtualLevel() TVirtualGeoTrack *TGeoManager::FindTrackWithId(Int_t id) const { - TVirtualGeoTrack* trk = 0; + TVirtualGeoTrack *trk = 0; trk = GetTrackOfId(id); - if (trk) return trk; + if (trk) + return trk; // need recursive search TIter next(fTracks); - TVirtualGeoTrack* prim; - while ((prim = (TVirtualGeoTrack*)next())) { + TVirtualGeoTrack *prim; + while ((prim = (TVirtualGeoTrack *)next())) { trk = prim->FindTrackWithId(id); - if (trk) return trk; + if (trk) + return trk; } return NULL; } @@ -2033,9 +2198,10 @@ TVirtualGeoTrack *TGeoManager::FindTrackWithId(Int_t id) const TVirtualGeoTrack *TGeoManager::GetTrackOfId(Int_t id) const { TVirtualGeoTrack *track; - for (Int_t i=0; iUncheckedAt(i))) { - if (track->GetId() == id) return track; + if (track->GetId() == id) + return track; } } return 0; @@ -2047,8 +2213,9 @@ TVirtualGeoTrack *TGeoManager::GetTrackOfId(Int_t id) const TVirtualGeoTrack *TGeoManager::GetParentTrackOfId(Int_t id) const { TVirtualGeoTrack *track = fCurrentTrack; - while ((track=track->GetMother())) { - if (track->GetId()==id) return track; + while ((track = track->GetMother())) { + if (track->GetId() == id) + return track; } return 0; } @@ -2059,9 +2226,10 @@ TVirtualGeoTrack *TGeoManager::GetParentTrackOfId(Int_t id) const Int_t TGeoManager::GetTrackIndex(Int_t id) const { TVirtualGeoTrack *track; - for (Int_t i=0; iUncheckedAt(i))) { - if (track->GetId() == id) return i; + if (track->GetId() == id) + return i; } } return -1; @@ -2090,33 +2258,36 @@ void TGeoManager::DefaultColors() { const Int_t nmax = 110; Int_t col[nmax]; - for (Int_t i=0;iGetMedium(); - if (!med) continue; + if (!med) + continue; TGeoMaterial *mat = med->GetMaterial(); Int_t matZ = (Int_t)mat->GetZ(); vol->SetLineColor(col[matZ]); - if (mat->GetDensity()<0.1) vol->SetTransparency(60); + if (mat->GetDensity() < 0.1) + vol->SetTransparency(60); } } @@ -2136,32 +2307,45 @@ void TGeoManager::SetVolumeAttribute(const char *name, const char *att, Int_t va { TGeoVolume *volume; Bool_t all = kFALSE; - if (strstr(name,"*")) all=kTRUE; - Int_t ivo=0; + if (strstr(name, "*")) + all = kTRUE; + Int_t ivo = 0; TIter next(fVolumes); TString chatt = att; chatt.ToLower(); - while ((volume=(TGeoVolume*)next())) { - if (strcmp(volume->GetName(), name) && !all) continue; + while ((volume = (TGeoVolume *)next())) { + if (strcmp(volume->GetName(), name) && !all) + continue; ivo++; - if (chatt.Contains("colo")) volume->SetLineColor(val); - if (chatt.Contains("lsty")) volume->SetLineStyle(val); - if (chatt.Contains("lwid")) volume->SetLineWidth(val); - if (chatt.Contains("fill")) volume->SetFillColor(val); - if (chatt.Contains("seen")) volume->SetVisibility(val); + if (chatt.Contains("colo")) + volume->SetLineColor(val); + if (chatt.Contains("lsty")) + volume->SetLineStyle(val); + if (chatt.Contains("lwid")) + volume->SetLineWidth(val); + if (chatt.Contains("fill")) + volume->SetFillColor(val); + if (chatt.Contains("seen")) + volume->SetVisibility(val); } TIter next1(fGVolumes); - while ((volume=(TGeoVolume*)next1())) { - if (strcmp(volume->GetName(), name) && !all) continue; + while ((volume = (TGeoVolume *)next1())) { + if (strcmp(volume->GetName(), name) && !all) + continue; ivo++; - if (chatt.Contains("colo")) volume->SetLineColor(val); - if (chatt.Contains("lsty")) volume->SetLineStyle(val); - if (chatt.Contains("lwid")) volume->SetLineWidth(val); - if (chatt.Contains("fill")) volume->SetFillColor(val); - if (chatt.Contains("seen")) volume->SetVisibility(val); + if (chatt.Contains("colo")) + volume->SetLineColor(val); + if (chatt.Contains("lsty")) + volume->SetLineStyle(val); + if (chatt.Contains("lwid")) + volume->SetLineWidth(val); + if (chatt.Contains("fill")) + volume->SetFillColor(val); + if (chatt.Contains("seen")) + volume->SetVisibility(val); } if (!ivo) { - Warning("SetVolumeAttribute","volume: %s does not exist",name); + Warning("SetVolumeAttribute", "volume: %s does not exist", name); } } @@ -2170,7 +2354,8 @@ void TGeoManager::SetVolumeAttribute(const char *name, const char *att, Int_t va void TGeoManager::SetBombFactors(Double_t bombx, Double_t bomby, Double_t bombz, Double_t bombr) { - if (fPainter) fPainter->SetBombFactors(bombx, bomby, bombz, bombr); + if (fPainter) + fPainter->SetBombFactors(bombx, bomby, bombz, bombr); } //////////////////////////////////////////////////////////////////////////////// @@ -2180,7 +2365,8 @@ void TGeoManager::SetClippingShape(TGeoShape *shape) { TVirtualGeoPainter *painter = GetGeomPainter(); if (shape) { - if (fClippingShape && (fClippingShape!=shape)) ClearShape(fClippingShape); + if (fClippingShape && (fClippingShape != shape)) + ClearShape(fClippingShape); fClippingShape = shape; } painter->SetClippingShape(shape); @@ -2189,20 +2375,24 @@ void TGeoManager::SetClippingShape(TGeoShape *shape) //////////////////////////////////////////////////////////////////////////////// /// set the maximum number of visible nodes. -void TGeoManager::SetMaxVisNodes(Int_t maxnodes) { +void TGeoManager::SetMaxVisNodes(Int_t maxnodes) +{ fMaxVisNodes = maxnodes; - if (maxnodes>0 && fgVerboseLevel>0) - Info("SetMaxVisNodes","Automatic visible depth for %d visible nodes", maxnodes); - if (!fPainter) return; + if (maxnodes > 0 && fgVerboseLevel > 0) + Info("SetMaxVisNodes", "Automatic visible depth for %d visible nodes", maxnodes); + if (!fPainter) + return; fPainter->CountVisibleNodes(); Int_t level = fPainter->GetVisLevel(); - if (level != fVisLevel) fVisLevel = level; + if (level != fVisLevel) + fVisLevel = level; } //////////////////////////////////////////////////////////////////////////////// /// make top volume visible on screen -void TGeoManager::SetTopVisible(Bool_t vis) { +void TGeoManager::SetTopVisible(Bool_t vis) +{ GetGeomPainter(); fPainter->SetTopVisible(vis); } @@ -2210,7 +2400,8 @@ void TGeoManager::SetTopVisible(Bool_t vis) { //////////////////////////////////////////////////////////////////////////////// /// Assign a given node to be checked for overlaps. Any other overlaps will be ignored. -void TGeoManager::SetCheckedNode(TGeoNode *node) { +void TGeoManager::SetCheckedNode(TGeoNode *node) +{ GetGeomPainter()->SetCheckedNode(node); } @@ -2230,9 +2421,12 @@ void TGeoManager::SetNmeshPoints(Int_t npoints) /// - option=2 path is drawn /// - option=4 visibility changed -void TGeoManager::SetVisOption(Int_t option) { - if ((option>=0) && (option<3)) fVisOption=option; - if (fPainter) fPainter->SetVisOption(option); +void TGeoManager::SetVisOption(Int_t option) +{ + if ((option >= 0) && (option < 3)) + fVisOption = option; + if (fPainter) + fPainter->SetVisOption(option); } //////////////////////////////////////////////////////////////////////////////// @@ -2240,8 +2434,10 @@ void TGeoManager::SetVisOption(Int_t option) { void TGeoManager::ViewLeaves(Bool_t flag) { - if (flag) SetVisOption(1); - else SetVisOption(0); + if (flag) + SetVisOption(1); + else + SetVisOption(0); } //////////////////////////////////////////////////////////////////////////////// @@ -2251,19 +2447,22 @@ void TGeoManager::ViewLeaves(Bool_t flag) void TGeoManager::SetVisDensity(Double_t density) { fVisDensity = density; - if (fPainter) fPainter->ModifiedPad(); + if (fPainter) + fPainter->ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// /// set default level down to which visualization is performed -void TGeoManager::SetVisLevel(Int_t level) { - if (level>0) { +void TGeoManager::SetVisLevel(Int_t level) +{ + if (level > 0) { fVisLevel = level; fMaxVisNodes = 0; - if (fgVerboseLevel>0) - Info("SetVisLevel","Automatic visible depth disabled"); - if (fPainter) fPainter->CountVisibleNodes(); + if (fgVerboseLevel > 0) + Info("SetVisLevel", "Automatic visible depth disabled"); + if (fPainter) + fPainter->CountVisibleNodes(); } else { SetMaxVisNodes(); } @@ -2283,12 +2482,13 @@ void TGeoManager::SortOverlaps() void TGeoManager::OptimizeVoxels(const char *filename) { if (!fTopNode) { - Error("OptimizeVoxels","Geometry must be closed first"); + Error("OptimizeVoxels", "Geometry must be closed first"); return; } std::ofstream out; TString fname = filename; - if (fname.IsNull()) fname = "tgeovox.C"; + if (fname.IsNull()) + fname = "tgeovox.C"; out.open(fname, std::ios::out); if (!out.good()) { Error("OptimizeVoxels", "cannot open file"); @@ -2298,24 +2498,25 @@ void TGeoManager::OptimizeVoxels(const char *filename) TDatime t; TString sname(fname); sname.ReplaceAll(".C", ""); - out << sname.Data()<<"()"<GetVersion()<<" : "<"<GetVersion() << " : " << t.AsString() << std::endl; + out << "//=== Voxel optimization for " << GetTitle() << " geometry" << std::endl; + out << "//===== " << std::endl; + out << " TGeoVolume *vol = 0;" << std::endl; + out << " // parse all voxelized volumes" << std::endl; TGeoVolume *vol = 0; Bool_t cyltype; TIter next(fVolumes); - while ((vol=(TGeoVolume*)next())) { - if (!vol->GetVoxels()) continue; - out<<" vol = gGeoManager->GetVolume(\""<GetName()<<"\");"<GetVoxels()) + continue; + out << " vol = gGeoManager->GetVolume(\"" << vol->GetName() << "\");" << std::endl; cyltype = vol->OptimizeVoxels(); if (cyltype) { - out<<" vol->SetCylVoxels();"<SetCylVoxels();" << std::endl; } else { - out<<" vol->SetCylVoxels(kFALSE);"<SetCylVoxels(kFALSE);" << std::endl; } } out << "}" << std::endl; @@ -2342,8 +2543,9 @@ Int_t TGeoManager::Parse(const char *expr, TString &expr1, TString &expr2, TStri TString e0 = ""; expr3 = ""; // eliminate blanks - for (i=0; i< len; i++) { - if (startstr(i)==' ') continue; + for (i = 0; i < len; i++) { + if (startstr(i) == ' ') + continue; e0 += startstr(i, 1); } Int_t level = 0; @@ -2356,106 +2558,111 @@ Int_t TGeoManager::Parse(const char *expr, TString &expr1, TString &expr2, TStri Int_t lastpp = 0; Bool_t foundmat = kFALSE; // check/eliminate parentheses - while (iloop==1) { + while (iloop == 1) { iloop = 0; lastop = 0; lastdp = 0; lastpp = 0; len = e0.Length(); - for (i=0; iError("Parse","parentheses does not match"); + if (level != 0) { + if (gGeoManager) + gGeoManager->Error("Parse", "parentheses does not match"); return -1; } - if (iloop==1 && (e0(0)=='(') && (e0(len-1)==')')) { + if (iloop == 1 && (e0(0) == '(') && (e0(len - 1) == ')')) { // eliminate extra parentheses - e0=e0(1, len-2); + e0 = e0(1, len - 2); continue; } - if (foundmat) break; - if (((lastop==0) && (lastdp>0)) || ((lastpp>0) && (lastdp>lastpp) && (indop 0)) || ((lastpp > 0) && (lastdp > lastpp) && (indop < lastpp))) { + expr3 = e0(lastdp + 1, len - lastdp); + e0 = e0(0, lastdp); foundmat = kTRUE; iloop = 1; continue; - } else break; + } else + break; } // loop expression and search parentheses/operators levmin = 999; - for (i=0; iGetVersion()<<" : "<"<GetVersion() << " : " << t.AsString() << std::endl; + out << "//=== Attributes for " << GetTitle() << " geometry" << std::endl; + out << "//===== " << std::endl; // save current top volume - out << " TGeoVolume *top = gGeoManager->GetVolume(\""<GetName()<<"\");"<ClearAttributes();"<GetGeomPainter();"<SetVisOption("<SetVisLevel("<SetExplodedView("<GetVolume(\"" << fTopVolume->GetName() << "\");" << std::endl; + out << " TGeoVolume *vol = 0;" << std::endl; + out << " TGeoNode *node = 0;" << std::endl; + out << " // clear all volume attributes and get painter" << std::endl; + out << " gGeoManager->ClearAttributes();" << std::endl; + out << " gGeoManager->GetGeomPainter();" << std::endl; + out << " // set visualization modes and bomb factors" << std::endl; + out << " gGeoManager->SetVisOption(" << GetVisOption() << ");" << std::endl; + out << " gGeoManager->SetVisLevel(" << GetVisLevel() << ");" << std::endl; + out << " gGeoManager->SetExplodedView(" << GetBombMode() << ");" << std::endl; Double_t bombx, bomby, bombz, bombr; GetBombFactors(bombx, bomby, bombz, bombr); - out << " gGeoManager->SetBombFactors("<GetListOfVolumes());"<SetBombFactors(" << bombx << "," << bomby << "," << bombz << "," << bombr << ");" + << std::endl; + out << " // iterate volumes container and set new attributes" << std::endl; + // out << " TIter next(gGeoManager->GetListOfVolumes());"<SaveAttributes(out); TIter next(fVolumes); - while ((vol=(TGeoVolume*)next())) { + while ((vol = (TGeoVolume *)next())) { vol->SetVisStreamed(kFALSE); } - out << " // draw top volume with new settings"<Draw();"<x3d();"<Draw();" << std::endl; + out << " gPad->x3d();" << std::endl; out << "}" << std::endl; out.close(); } @@ -2545,7 +2753,7 @@ TGeoNode *TGeoManager::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsafe TGeoNode *TGeoManager::FindNextBoundary(Double_t stepmax, const char *path, Bool_t frombdr) { // convert current point and direction to local reference - return GetCurrentNavigator()->FindNextBoundary(stepmax,path, frombdr); + return GetCurrentNavigator()->FindNextBoundary(stepmax, path, frombdr); } //////////////////////////////////////////////////////////////////////////////// @@ -2607,7 +2815,7 @@ Double_t *TGeoManager::FindNormal(Bool_t forward) Bool_t TGeoManager::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change) { - return GetCurrentNavigator()->IsSameLocation(x,y,z,change); + return GetCurrentNavigator()->IsSameLocation(x, y, z, change); } //////////////////////////////////////////////////////////////////////////////// @@ -2615,7 +2823,7 @@ Bool_t TGeoManager::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t ch Bool_t TGeoManager::IsSamePoint(Double_t x, Double_t y, Double_t z) const { - return GetCurrentNavigator()->IsSamePoint(x,y,z); + return GetCurrentNavigator()->IsSamePoint(x, y, z); } //////////////////////////////////////////////////////////////////////////////// @@ -2623,15 +2831,19 @@ Bool_t TGeoManager::IsSamePoint(Double_t x, Double_t y, Double_t z) const Bool_t TGeoManager::IsInPhiRange() const { - if (!fPhiCut) return kTRUE; + if (!fPhiCut) + return kTRUE; const Double_t *origin; - if (!GetCurrentNavigator() || !GetCurrentNavigator()->GetCurrentNode()) return kFALSE; - origin = ((TGeoBBox*)GetCurrentNavigator()->GetCurrentVolume()->GetShape())->GetOrigin(); + if (!GetCurrentNavigator() || !GetCurrentNavigator()->GetCurrentNode()) + return kFALSE; + origin = ((TGeoBBox *)GetCurrentNavigator()->GetCurrentVolume()->GetShape())->GetOrigin(); Double_t point[3]; LocalToMaster(origin, &point[0]); - Double_t phi = TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi+=360.; - if ((phi>=fPhimin) && (phi<=fPhimax)) return kFALSE; + Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360.; + if ((phi >= fPhimin) && (phi <= fPhimax)) + return kFALSE; return kTRUE; } @@ -2650,7 +2862,7 @@ TGeoNode *TGeoManager::InitTrack(const Double_t *point, const Double_t *dir) TGeoNode *TGeoManager::InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz) { - return GetCurrentNavigator()->InitTrack(x,y,z,nx,ny,nz); + return GetCurrentNavigator()->InitTrack(x, y, z, nx, ny, nz); } //////////////////////////////////////////////////////////////////////////////// @@ -2677,17 +2889,22 @@ Int_t TGeoManager::GetByteCount(Option_t * /*option*/) Int_t count = 0; TIter next(fVolumes); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) count += vol->GetByteCount(); + while ((vol = (TGeoVolume *)next())) + count += vol->GetByteCount(); TIter next1(fMatrices); TGeoMatrix *matrix; - while ((matrix=(TGeoMatrix*)next1())) count += matrix->GetByteCount(); + while ((matrix = (TGeoMatrix *)next1())) + count += matrix->GetByteCount(); TIter next2(fMaterials); TGeoMaterial *mat; - while ((mat=(TGeoMaterial*)next2())) count += mat->GetByteCount(); + while ((mat = (TGeoMaterial *)next2())) + count += mat->GetByteCount(); TIter next3(fMedia); TGeoMedium *med; - while ((med=(TGeoMedium*)next3())) count += med->GetByteCount(); - if (fgVerboseLevel>0) Info("GetByteCount","Total size of logical tree : %i bytes", count); + while ((med = (TGeoMedium *)next3())) + count += med->GetByteCount(); + if (fgVerboseLevel > 0) + Info("GetByteCount", "Total size of logical tree : %i bytes", count); return count; } @@ -2698,13 +2915,14 @@ TVirtualGeoPainter *TGeoManager::GetGeomPainter() { if (!fPainter) { const char *kind = "root"; - if (gROOT->IsWebDisplay() && !gROOT->IsWebDisplayBatch()) kind = "web"; + if (gROOT->IsWebDisplay() && !gROOT->IsWebDisplayBatch()) + kind = "web"; if (auto h = gROOT->GetPluginManager()->FindHandler("TVirtualGeoPainter", kind)) { if (h->LoadPlugin() == -1) { Error("GetGeomPainter", "could not load plugin for %s geo_painter", kind); return nullptr; } - fPainter = (TVirtualGeoPainter*)h->ExecPlugin(1,this); + fPainter = (TVirtualGeoPainter *)h->ExecPlugin(1, this); if (!fPainter) { Error("GetGeomPainter", "could not create %s geo_painter", kind); return nullptr; @@ -2723,7 +2941,7 @@ TGeoVolume *TGeoManager::GetVolume(const char *name) const { TString sname = name; sname = sname.Strip(); - TGeoVolume *vol = (TGeoVolume*)fVolumes->FindObject(sname.Data()); + TGeoVolume *vol = (TGeoVolume *)fVolumes->FindObject(sname.Data()); return vol; } @@ -2735,17 +2953,20 @@ TGeoVolume *TGeoManager::FindVolumeFast(const char *name, Bool_t multi) if (!fHashVolumes) { Int_t nvol = fVolumes->GetEntriesFast(); Int_t ngvol = fGVolumes->GetEntriesFast(); - fHashVolumes = new THashList(nvol+1); - fHashGVolumes = new THashList(ngvol+1); + fHashVolumes = new THashList(nvol + 1); + fHashGVolumes = new THashList(ngvol + 1); Int_t i; - for (i=0; iAddLast(fGVolumes->At(i)); - for (i=0; iAddLast(fVolumes->At(i)); + for (i = 0; i < ngvol; i++) + fHashGVolumes->AddLast(fGVolumes->At(i)); + for (i = 0; i < nvol; i++) + fHashVolumes->AddLast(fVolumes->At(i)); } TString sname = name; sname = sname.Strip(); THashList *list = fHashVolumes; - if (multi) list = fHashGVolumes; - TGeoVolume *vol = (TGeoVolume*)list->FindObject(sname.Data()); + if (multi) + list = fHashGVolumes; + TGeoVolume *vol = (TGeoVolume *)list->FindObject(sname.Data()); return vol; } @@ -2754,10 +2975,12 @@ TGeoVolume *TGeoManager::FindVolumeFast(const char *name, Bool_t multi) Int_t TGeoManager::GetUID(const char *volname) const { - TGeoManager *geom = (TGeoManager*)this; + TGeoManager *geom = (TGeoManager *)this; TGeoVolume *vol = geom->FindVolumeFast(volname, kFALSE); - if (!vol) vol = geom->FindVolumeFast(volname, kTRUE); - if (!vol) return -1; + if (!vol) + vol = geom->FindVolumeFast(volname, kTRUE); + if (!vol) + return -1; return vol->GetNumber(); } @@ -2767,12 +2990,15 @@ Int_t TGeoManager::GetUID(const char *volname) const TGeoMaterial *TGeoManager::FindDuplicateMaterial(const TGeoMaterial *mat) const { Int_t index = fMaterials->IndexOf(mat); - if (index <= 0) return 0; + if (index <= 0) + return 0; TGeoMaterial *other; - for (Int_t i=0; iAt(i); - if (other == mat) continue; - if (other->IsEq(mat)) return other; + for (Int_t i = 0; i < index; i++) { + other = (TGeoMaterial *)fMaterials->At(i); + if (other == mat) + continue; + if (other->IsEq(mat)) + return other; } return 0; } @@ -2784,7 +3010,7 @@ TGeoMaterial *TGeoManager::GetMaterial(const char *matname) const { TString sname = matname; sname = sname.Strip(); - TGeoMaterial *mat = (TGeoMaterial*)fMaterials->FindObject(sname.Data()); + TGeoMaterial *mat = (TGeoMaterial *)fMaterials->FindObject(sname.Data()); return mat; } @@ -2795,7 +3021,7 @@ TGeoMedium *TGeoManager::GetMedium(const char *medium) const { TString sname = medium; sname = sname.Strip(); - TGeoMedium *med = (TGeoMedium*)fMedia->FindObject(sname.Data()); + TGeoMedium *med = (TGeoMedium *)fMedia->FindObject(sname.Data()); return med; } @@ -2806,8 +3032,9 @@ TGeoMedium *TGeoManager::GetMedium(Int_t numed) const { TIter next(fMedia); TGeoMedium *med; - while ((med=(TGeoMedium*)next())) { - if (med->GetId()==numed) return med; + while ((med = (TGeoMedium *)next())) { + if (med->GetId() == numed) + return med; } return 0; } @@ -2817,8 +3044,9 @@ TGeoMedium *TGeoManager::GetMedium(Int_t numed) const TGeoMaterial *TGeoManager::GetMaterial(Int_t id) const { - if (id<0 || id >= fMaterials->GetSize()) return 0; - TGeoMaterial *mat = (TGeoMaterial*)fMaterials->At(id); + if (id < 0 || id >= fMaterials->GetSize()) + return 0; + TGeoMaterial *mat = (TGeoMaterial *)fMaterials->At(id); return mat; } @@ -2832,19 +3060,20 @@ Int_t TGeoManager::GetMaterialIndex(const char *matname) const Int_t id = 0; TString sname = matname; sname = sname.Strip(); - while ((mat = (TGeoMaterial*)next())) { - if (!strcmp(mat->GetName(),sname.Data())) + while ((mat = (TGeoMaterial *)next())) { + if (!strcmp(mat->GetName(), sname.Data())) return id; id++; } - return -1; // fail + return -1; // fail } //////////////////////////////////////////////////////////////////////////////// /// Randomly shoot nrays and plot intersections with surfaces for current /// top node. -void TGeoManager::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, Bool_t check_norm) +void TGeoManager::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, + Bool_t check_norm) { GetGeomPainter()->RandomRays(nrays, startx, starty, startz, target_vol, check_norm); } @@ -2855,7 +3084,8 @@ void TGeoManager::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub void TGeoManager::RemoveMaterial(Int_t index) { TObject *obj = fMaterials->At(index); - if (obj) fMaterials->Remove(obj); + if (obj) + fMaterials->Remove(obj); } //////////////////////////////////////////////////////////////////////////////// @@ -2866,7 +3096,8 @@ void TGeoManager::ResetUserData() { TIter next(fVolumes); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) vol->SetField(0); + while ((vol = (TGeoVolume *)next())) + vol->SetField(0); } //////////////////////////////////////////////////////////////////////////////// @@ -2875,7 +3106,8 @@ void TGeoManager::ResetUserData() void TGeoManager::SetRTmode(Int_t mode) { fRaytraceMode = mode; - if (fPainter && fPainter->IsRaytracing()) ModifiedPad(); + if (fPainter && fPainter->IsRaytracing()) + ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// @@ -2883,8 +3115,10 @@ void TGeoManager::SetRTmode(Int_t mode) void TGeoManager::RestoreMasterVolume() { - if (fTopVolume == fMasterVolume) return; - if (fMasterVolume) SetTopVolume(fMasterVolume); + if (fTopVolume == fMasterVolume) + return; + if (fMasterVolume) + SetTopVolume(fMasterVolume); } //////////////////////////////////////////////////////////////////////////////// @@ -2893,16 +3127,19 @@ void TGeoManager::RestoreMasterVolume() void TGeoManager::Voxelize(Option_t *option) { TGeoVolume *vol; -// TGeoVoxelFinder *vox = 0; - if (!fStreamVoxels && fgVerboseLevel>0) Info("Voxelize","Voxelizing..."); -// Int_t nentries = fVolumes->GetSize(); + // TGeoVoxelFinder *vox = 0; + if (!fStreamVoxels && fgVerboseLevel > 0) + Info("Voxelize", "Voxelizing..."); + // Int_t nentries = fVolumes->GetSize(); TIter next(fVolumes); - while ((vol = (TGeoVolume*)next())) { - if (!fIsGeomReading) vol->SortNodes(); + while ((vol = (TGeoVolume *)next())) { + if (!fIsGeomReading) + vol->SortNodes(); if (!fStreamVoxels) { vol->Voxelize(option); } - if (!fIsGeomReading) vol->FindOverlaps(); + if (!fIsGeomReading) + vol->FindOverlaps(); } } @@ -2911,15 +3148,15 @@ void TGeoManager::Voxelize(Option_t *option) void TGeoManager::ModifiedPad() const { - if (!fPainter) return; + if (!fPainter) + return; fPainter->ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// /// Make an TGeoArb8 volume. -TGeoVolume *TGeoManager::MakeArb8(const char *name, TGeoMedium *medium, - Double_t dz, Double_t *vertices) +TGeoVolume *TGeoManager::MakeArb8(const char *name, TGeoMedium *medium, Double_t dz, Double_t *vertices) { return TGeoBuilder::Instance(this)->MakeArb8(name, medium, dz, vertices); } @@ -2927,8 +3164,7 @@ TGeoVolume *TGeoManager::MakeArb8(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a box shape with given medium. -TGeoVolume *TGeoManager::MakeBox(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz) +TGeoVolume *TGeoManager::MakeBox(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz) { return TGeoBuilder::Instance(this)->MakeBox(name, medium, dx, dy, dz); } @@ -2936,9 +3172,8 @@ TGeoVolume *TGeoManager::MakeBox(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a parallelepiped shape with given medium. -TGeoVolume *TGeoManager::MakePara(const char *name, TGeoMedium *medium, - Double_t dx, Double_t dy, Double_t dz, - Double_t alpha, Double_t theta, Double_t phi) +TGeoVolume *TGeoManager::MakePara(const char *name, TGeoMedium *medium, Double_t dx, Double_t dy, Double_t dz, + Double_t alpha, Double_t theta, Double_t phi) { return TGeoBuilder::Instance(this)->MakePara(name, medium, dx, dy, dz, alpha, theta, phi); } @@ -2946,9 +3181,8 @@ TGeoVolume *TGeoManager::MakePara(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a sphere shape with given medium -TGeoVolume *TGeoManager::MakeSphere(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t themin, Double_t themax, - Double_t phimin, Double_t phimax) +TGeoVolume *TGeoManager::MakeSphere(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t themin, + Double_t themax, Double_t phimin, Double_t phimax) { return TGeoBuilder::Instance(this)->MakeSphere(name, medium, rmin, rmax, themin, themax, phimin, phimax); } @@ -2956,8 +3190,8 @@ TGeoVolume *TGeoManager::MakeSphere(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a torus shape with given medium. -TGeoVolume *TGeoManager::MakeTorus(const char *name, TGeoMedium *medium, Double_t r, - Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi) +TGeoVolume *TGeoManager::MakeTorus(const char *name, TGeoMedium *medium, Double_t r, Double_t rmin, Double_t rmax, + Double_t phi1, Double_t dphi) { return TGeoBuilder::Instance(this)->MakeTorus(name, medium, r, rmin, rmax, phi1, dphi); } @@ -2965,8 +3199,7 @@ TGeoVolume *TGeoManager::MakeTorus(const char *name, TGeoMedium *medium, Double_ //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium. -TGeoVolume *TGeoManager::MakeTube(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz) +TGeoVolume *TGeoManager::MakeTube(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz) { return TGeoBuilder::Instance(this)->MakeTube(name, medium, rmin, rmax, dz); } @@ -2975,9 +3208,8 @@ TGeoVolume *TGeoManager::MakeTube(const char *name, TGeoMedium *medium, /// Make in one step a volume pointing to a tube segment shape with given medium. /// The segment will be from phiStart to phiEnd, the angles are expressed in degree -TGeoVolume *TGeoManager::MakeTubs(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, - Double_t phiStart, Double_t phiEnd) +TGeoVolume *TGeoManager::MakeTubs(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, + Double_t phiStart, Double_t phiEnd) { return TGeoBuilder::Instance(this)->MakeTubs(name, medium, rmin, rmax, dz, phiStart, phiEnd); } @@ -2985,8 +3217,7 @@ TGeoVolume *TGeoManager::MakeTubs(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoManager::MakeEltu(const char *name, TGeoMedium *medium, - Double_t a, Double_t b, Double_t dz) +TGeoVolume *TGeoManager::MakeEltu(const char *name, TGeoMedium *medium, Double_t a, Double_t b, Double_t dz) { return TGeoBuilder::Instance(this)->MakeEltu(name, medium, a, b, dz); } @@ -2994,8 +3225,8 @@ TGeoVolume *TGeoManager::MakeEltu(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoManager::MakeHype(const char *name, TGeoMedium *medium, - Double_t rin, Double_t stin, Double_t rout, Double_t stout, Double_t dz) +TGeoVolume *TGeoManager::MakeHype(const char *name, TGeoMedium *medium, Double_t rin, Double_t stin, Double_t rout, + Double_t stout, Double_t dz) { return TGeoBuilder::Instance(this)->MakeHype(name, medium, rin, stin, rout, stout, dz); } @@ -3003,8 +3234,7 @@ TGeoVolume *TGeoManager::MakeHype(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube shape with given medium -TGeoVolume *TGeoManager::MakeParaboloid(const char *name, TGeoMedium *medium, - Double_t rlo, Double_t rhi, Double_t dz) +TGeoVolume *TGeoManager::MakeParaboloid(const char *name, TGeoMedium *medium, Double_t rlo, Double_t rhi, Double_t dz) { return TGeoBuilder::Instance(this)->MakeParaboloid(name, medium, rlo, rhi, dz); } @@ -3012,9 +3242,9 @@ TGeoVolume *TGeoManager::MakeParaboloid(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a tube segment shape with given medium -TGeoVolume *TGeoManager::MakeCtub(const char *name, TGeoMedium *medium, - Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz) +TGeoVolume *TGeoManager::MakeCtub(const char *name, TGeoMedium *medium, Double_t rmin, Double_t rmax, Double_t dz, + Double_t phi1, Double_t phi2, Double_t lx, Double_t ly, Double_t lz, Double_t tx, + Double_t ty, Double_t tz) { return TGeoBuilder::Instance(this)->MakeCtub(name, medium, rmin, rmax, dz, phi1, phi2, lx, ly, lz, tx, ty, tz); } @@ -3022,9 +3252,8 @@ TGeoVolume *TGeoManager::MakeCtub(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a cone shape with given medium. -TGeoVolume *TGeoManager::MakeCone(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2) +TGeoVolume *TGeoManager::MakeCone(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2) { return TGeoBuilder::Instance(this)->MakeCone(name, medium, dz, rmin1, rmax1, rmin2, rmax2); } @@ -3032,10 +3261,8 @@ TGeoVolume *TGeoManager::MakeCone(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a cone segment shape with given medium -TGeoVolume *TGeoManager::MakeCons(const char *name, TGeoMedium *medium, - Double_t dz, Double_t rmin1, Double_t rmax1, - Double_t rmin2, Double_t rmax2, - Double_t phi1, Double_t phi2) +TGeoVolume *TGeoManager::MakeCons(const char *name, TGeoMedium *medium, Double_t dz, Double_t rmin1, Double_t rmax1, + Double_t rmin2, Double_t rmax2, Double_t phi1, Double_t phi2) { return TGeoBuilder::Instance(this)->MakeCons(name, medium, dz, rmin1, rmax1, rmin2, rmax2, phi1, phi2); } @@ -3043,8 +3270,7 @@ TGeoVolume *TGeoManager::MakeCons(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a polycone shape with given medium. -TGeoVolume *TGeoManager::MakePcon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nz) +TGeoVolume *TGeoManager::MakePcon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nz) { return TGeoBuilder::Instance(this)->MakePcon(name, medium, phi, dphi, nz); } @@ -3052,8 +3278,8 @@ TGeoVolume *TGeoManager::MakePcon(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a polygone shape with given medium. -TGeoVolume *TGeoManager::MakePgon(const char *name, TGeoMedium *medium, - Double_t phi, Double_t dphi, Int_t nedges, Int_t nz) +TGeoVolume * +TGeoManager::MakePgon(const char *name, TGeoMedium *medium, Double_t phi, Double_t dphi, Int_t nedges, Int_t nz) { return TGeoBuilder::Instance(this)->MakePgon(name, medium, phi, dphi, nedges, nz); } @@ -3061,8 +3287,8 @@ TGeoVolume *TGeoManager::MakePgon(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a TGeoTrd1 shape with given medium. -TGeoVolume *TGeoManager::MakeTrd1(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy, Double_t dz) +TGeoVolume * +TGeoManager::MakeTrd1(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy, Double_t dz) { return TGeoBuilder::Instance(this)->MakeTrd1(name, medium, dx1, dx2, dy, dz); } @@ -3070,9 +3296,8 @@ TGeoVolume *TGeoManager::MakeTrd1(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a TGeoTrd2 shape with given medium. -TGeoVolume *TGeoManager::MakeTrd2(const char *name, TGeoMedium *medium, - Double_t dx1, Double_t dx2, Double_t dy1, Double_t dy2, - Double_t dz) +TGeoVolume *TGeoManager::MakeTrd2(const char *name, TGeoMedium *medium, Double_t dx1, Double_t dx2, Double_t dy1, + Double_t dy2, Double_t dz) { return TGeoBuilder::Instance(this)->MakeTrd2(name, medium, dx1, dx2, dy1, dy2, dz); } @@ -3080,23 +3305,23 @@ TGeoVolume *TGeoManager::MakeTrd2(const char *name, TGeoMedium *medium, //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a trapezoid shape with given medium. -TGeoVolume *TGeoManager::MakeTrap(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, +TGeoVolume *TGeoManager::MakeTrap(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, + Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, Double_t tl2, Double_t alpha2) { - return TGeoBuilder::Instance(this)->MakeTrap(name, medium, dz, theta, phi, h1, bl1, tl1, alpha1, h2, bl2, tl2, alpha2); + return TGeoBuilder::Instance(this)->MakeTrap(name, medium, dz, theta, phi, h1, bl1, tl1, alpha1, h2, bl2, tl2, + alpha2); } //////////////////////////////////////////////////////////////////////////////// /// Make in one step a volume pointing to a twisted trapezoid shape with given medium. -TGeoVolume *TGeoManager::MakeGtra(const char *name, TGeoMedium *medium, - Double_t dz, Double_t theta, Double_t phi, Double_t twist, Double_t h1, - Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, Double_t bl2, - Double_t tl2, Double_t alpha2) +TGeoVolume *TGeoManager::MakeGtra(const char *name, TGeoMedium *medium, Double_t dz, Double_t theta, Double_t phi, + Double_t twist, Double_t h1, Double_t bl1, Double_t tl1, Double_t alpha1, Double_t h2, + Double_t bl2, Double_t tl2, Double_t alpha2) { - return TGeoBuilder::Instance(this)->MakeGtra(name, medium, dz, theta, phi, twist, h1, bl1, tl1, alpha1, h2, bl2, tl2, alpha2); + return TGeoBuilder::Instance(this)->MakeGtra(name, medium, dz, theta, phi, twist, h1, bl1, tl1, alpha1, h2, bl2, tl2, + alpha2); } //////////////////////////////////////////////////////////////////////////////// @@ -3112,12 +3337,14 @@ TGeoVolume *TGeoManager::MakeXtru(const char *name, TGeoMedium *medium, Int_t nz /// and adds it to the list of alignables. An optional unique ID can be /// provided, in which case PN entries can be searched fast by uid. -TGeoPNEntry *TGeoManager::SetAlignableEntry(const char *unique_name, const char *path, - Int_t uid) +TGeoPNEntry *TGeoManager::SetAlignableEntry(const char *unique_name, const char *path, Int_t uid) { - if (!CheckPath(path)) return NULL; - if (!fHashPNE) fHashPNE = new THashList(256,3); - if (!fArrayPNE) fArrayPNE = new TObjArray(256); + if (!CheckPath(path)) + return NULL; + if (!fHashPNE) + fHashPNE = new THashList(256, 3); + if (!fArrayPNE) + fArrayPNE = new TObjArray(256); TGeoPNEntry *entry = GetAlignableEntry(unique_name); if (entry) { Error("SetAlignableEntry", "An alignable object with name %s already existing. NOT ADDED !", unique_name); @@ -3127,9 +3354,10 @@ TGeoPNEntry *TGeoManager::SetAlignableEntry(const char *unique_name, const char Int_t ientry = fHashPNE->GetSize(); fHashPNE->Add(entry); fArrayPNE->AddAtAndExpand(entry, ientry); - if (uid>=0) { + if (uid >= 0) { Bool_t added = InsertPNEId(uid, ientry); - if (!added) Error("SetAlignableEntry", "A PN entry: has already uid=%i", uid); + if (!added) + Error("SetAlignableEntry", "A PN entry: has already uid=%i", uid); } return entry; } @@ -3139,8 +3367,9 @@ TGeoPNEntry *TGeoManager::SetAlignableEntry(const char *unique_name, const char TGeoPNEntry *TGeoManager::GetAlignableEntry(const char *name) const { - if (!fHashPNE) return 0; - return (TGeoPNEntry*)fHashPNE->FindObject(name); + if (!fHashPNE) + return 0; + return (TGeoPNEntry *)fHashPNE->FindObject(name); } //////////////////////////////////////////////////////////////////////////////// @@ -3148,8 +3377,9 @@ TGeoPNEntry *TGeoManager::GetAlignableEntry(const char *name) const TGeoPNEntry *TGeoManager::GetAlignableEntry(Int_t index) const { - if (!fArrayPNE && !InitArrayPNE()) return 0; - return (TGeoPNEntry*)fArrayPNE->At(index); + if (!fArrayPNE && !InitArrayPNE()) + return 0; + return (TGeoPNEntry *)fArrayPNE->At(index); } //////////////////////////////////////////////////////////////////////////////// @@ -3157,10 +3387,12 @@ TGeoPNEntry *TGeoManager::GetAlignableEntry(Int_t index) const TGeoPNEntry *TGeoManager::GetAlignableEntryByUID(Int_t uid) const { - if (!fNPNEId || (!fArrayPNE && !InitArrayPNE())) return NULL; + if (!fNPNEId || (!fArrayPNE && !InitArrayPNE())) + return NULL; Int_t index = TMath::BinarySearch(fNPNEId, fKeyPNEId, uid); - if (index<0 || fKeyPNEId[index]!=uid) return NULL; - return (TGeoPNEntry*)fArrayPNE->At(fValuePNEId[index]); + if (index < 0 || fKeyPNEId[index] != uid) + return NULL; + return (TGeoPNEntry *)fArrayPNE->At(fValuePNEId[index]); } //////////////////////////////////////////////////////////////////////////////// @@ -3168,8 +3400,10 @@ TGeoPNEntry *TGeoManager::GetAlignableEntryByUID(Int_t uid) const Int_t TGeoManager::GetNAlignable(Bool_t with_uid) const { - if (!fHashPNE) return 0; - if (with_uid) return fNPNEId; + if (!fHashPNE) + return 0; + if (with_uid) + return fNPNEId; return fHashPNE->GetSize(); } @@ -3182,50 +3416,51 @@ Bool_t TGeoManager::InsertPNEId(Int_t uid, Int_t ientry) // Create the arrays. fSizePNEId = 128; fKeyPNEId = new Int_t[fSizePNEId]; - memset(fKeyPNEId, 0, fSizePNEId*sizeof(Int_t)); + memset(fKeyPNEId, 0, fSizePNEId * sizeof(Int_t)); fValuePNEId = new Int_t[fSizePNEId]; - memset(fValuePNEId, 0, fSizePNEId*sizeof(Int_t)); + memset(fValuePNEId, 0, fSizePNEId * sizeof(Int_t)); fKeyPNEId[fNPNEId] = uid; fValuePNEId[fNPNEId++] = ientry; return kTRUE; } // Search id in the existing array and return false if it already exists. Int_t index = TMath::BinarySearch(fNPNEId, fKeyPNEId, uid); - if (index>0 && fKeyPNEId[index]==uid) return kFALSE; + if (index > 0 && fKeyPNEId[index] == uid) + return kFALSE; // Resize the arrays and insert the value - Bool_t resize = (fNPNEId==fSizePNEId)?kTRUE:kFALSE; + Bool_t resize = (fNPNEId == fSizePNEId) ? kTRUE : kFALSE; if (resize) { // Double the size of the array fSizePNEId *= 2; // Create new arrays of keys and values Int_t *keys = new Int_t[fSizePNEId]; - memset(keys, 0, fSizePNEId*sizeof(Int_t)); + memset(keys, 0, fSizePNEId * sizeof(Int_t)); Int_t *values = new Int_t[fSizePNEId]; - memset(values, 0, fSizePNEId*sizeof(Int_t)); + memset(values, 0, fSizePNEId * sizeof(Int_t)); // Copy all keysindex; i--) { - fKeyPNEId[i+1] = fKeyPNEId[i]; - fValuePNEId[i+1] = fValuePNEId[i]; + for (i = fNPNEId - 1; i > index; i--) { + fKeyPNEId[i + 1] = fKeyPNEId[i]; + fValuePNEId[i + 1] = fValuePNEId[i]; } - fKeyPNEId[index+1] = uid; - fValuePNEId[index+1] = ientry; + fKeyPNEId[index + 1] = uid; + fValuePNEId[index + 1] = ientry; fNPNEId++; return kTRUE; } @@ -3237,7 +3472,7 @@ TGeoPhysicalNode *TGeoManager::MakeAlignablePN(const char *name) { TGeoPNEntry *entry = GetAlignableEntry(name); if (!entry) { - Error("MakeAlignablePN","No alignable object named %s found !", name); + Error("MakeAlignablePN", "No alignable object named %s found !", name); return 0; } return MakeAlignablePN(entry); @@ -3249,13 +3484,12 @@ TGeoPhysicalNode *TGeoManager::MakeAlignablePN(const char *name) TGeoPhysicalNode *TGeoManager::MakeAlignablePN(TGeoPNEntry *entry) { if (!entry) { - Error("MakeAlignablePN","No alignable object specified !"); + Error("MakeAlignablePN", "No alignable object specified !"); return 0; } const char *path = entry->GetTitle(); if (!cd(path)) { - Error("MakeAlignablePN", "Alignable object %s poins to invalid path: %s", - entry->GetName(), path); + Error("MakeAlignablePN", "Alignable object %s poins to invalid path: %s", entry->GetName(), path); return 0; } TGeoPhysicalNode *node = MakePhysicalNode(path); @@ -3291,9 +3525,12 @@ void TGeoManager::RefreshPhysicalNodes(Bool_t lock) { TIter next(gGeoManager->GetListOfPhysicalNodes()); TGeoPhysicalNode *pn; - while ((pn=(TGeoPhysicalNode*)next())) pn->Refresh(); - if (fParallelWorld && fParallelWorld->IsClosed()) fParallelWorld->RefreshPhysicalNodes(); - if (lock) LockGeometry(); + while ((pn = (TGeoPhysicalNode *)next())) + pn->Refresh(); + if (fParallelWorld && fParallelWorld->IsClosed()) + fParallelWorld->RefreshPhysicalNodes(); + if (lock) + LockGeometry(); } //////////////////////////////////////////////////////////////////////////////// @@ -3302,8 +3539,10 @@ void TGeoManager::RefreshPhysicalNodes(Bool_t lock) void TGeoManager::ClearPhysicalNodes(Bool_t mustdelete) { - if (mustdelete) fPhysicalNodes->Delete(); - else fPhysicalNodes->Clear(); + if (mustdelete) + fPhysicalNodes->Delete(); + else + fPhysicalNodes->Clear(); } //////////////////////////////////////////////////////////////////////////////// @@ -3327,8 +3566,10 @@ TGeoVolumeMulti *TGeoManager::MakeVolumeMulti(const char *name, TGeoMedium *medi void TGeoManager::SetExplodedView(Int_t ibomb) { - if ((ibomb>=0) && (ibomb<4)) fExplodedView = ibomb; - if (fPainter) fPainter->SetExplodedView(ibomb); + if ((ibomb >= 0) && (ibomb < 4)) + fExplodedView = ibomb; + if (fPainter) + fPainter->SetExplodedView(ibomb); } //////////////////////////////////////////////////////////////////////////////// @@ -3336,7 +3577,7 @@ void TGeoManager::SetExplodedView(Int_t ibomb) void TGeoManager::SetPhiRange(Double_t phimin, Double_t phimax) { - if ((phimin==0) && (phimax==360)) { + if ((phimin == 0) && (phimax == 360)) { fPhiCut = kFALSE; return; } @@ -3350,9 +3591,12 @@ void TGeoManager::SetPhiRange(Double_t phimin, Double_t phimax) void TGeoManager::SetNsegments(Int_t nseg) { - if (fNsegments==nseg) return; - if (nseg>2) fNsegments = nseg; - if (fPainter) fPainter->SetNsegments(nseg); + if (fNsegments == nseg) + return; + if (nseg > 2) + fNsegments = nseg; + if (fPainter) + fPainter->SetNsegments(nseg); } //////////////////////////////////////////////////////////////////////////////// @@ -3377,7 +3621,8 @@ void TGeoManager::BuildDefaultMaterials() TGeoElementTable *TGeoManager::GetElementTable() { - if (!fElementTable) fElementTable = new TGeoElementTable(200); + if (!fElementTable) + fElementTable = new TGeoElementTable(200); return fElementTable; } @@ -3397,8 +3642,7 @@ TGeoNode *TGeoManager::Step(Bool_t is_geom, Bool_t cross) /// shoot npoints randomly in a box of 1E-5 around current point. /// return minimum distance to points outside -TGeoNode *TGeoManager::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, - const char* g3path) +TGeoNode *TGeoManager::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path) { return GetGeomPainter()->SamplePoints(npoints, dist, epsil, g3path); } @@ -3408,31 +3652,34 @@ TGeoNode *TGeoManager::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsi void TGeoManager::SetTopVolume(TGeoVolume *vol) { - if (fTopVolume==vol) return; + if (fTopVolume == vol) + return; TSeqCollection *brlist = gROOT->GetListOfBrowsers(); TIter next(brlist); TBrowser *browser = 0; - if (fTopVolume) fTopVolume->SetTitle(""); + if (fTopVolume) + fTopVolume->SetTitle(""); fTopVolume = vol; vol->SetTitle("Top volume"); if (fTopNode) { TGeoNode *topn = fTopNode; fTopNode = 0; - while ((browser=(TBrowser*)next())) browser->RecursiveRemove(topn); + while ((browser = (TBrowser *)next())) + browser->RecursiveRemove(topn); delete topn; } else { fMasterVolume = vol; fMasterVolume->Grab(); - fUniqueVolumes->AddAtAndExpand(vol,0); - if (fgVerboseLevel>0) Info("SetTopVolume","Top volume is %s. Master volume is %s", fTopVolume->GetName(), - fMasterVolume->GetName()); + fUniqueVolumes->AddAtAndExpand(vol, 0); + if (fgVerboseLevel > 0) + Info("SetTopVolume", "Top volume is %s. Master volume is %s", fTopVolume->GetName(), fMasterVolume->GetName()); } -// fMasterVolume->FindMatrixOfDaughterVolume(vol); -// fCurrentMatrix->Print(); + // fMasterVolume->FindMatrixOfDaughterVolume(vol); + // fCurrentMatrix->Print(); fTopNode = new TGeoNodeMatrix(vol, gGeoIdentity); - fTopNode->SetName(TString::Format("%s_1",vol->GetName())); + fTopNode->SetName(TString::Format("%s_1", vol->GetName())); fTopNode->SetNumber(1); fTopNode->SetTitle("Top logical node"); fNodes->AddAt(fTopNode, 0); @@ -3442,12 +3689,14 @@ void TGeoManager::SetTopVolume(TGeoVolume *vol) } Int_t nnavigators = 0; TGeoNavigatorArray *arr = GetListOfNavigators(); - if (!arr) return; + if (!arr) + return; nnavigators = arr->GetEntriesFast(); - for (Int_t i=0; iAt(i); + for (Int_t i = 0; i < nnavigators; i++) { + TGeoNavigator *nav = (TGeoNavigator *)arr->At(i); nav->ResetAll(); - if (fClosed) nav->GetCache()->BuildInfoBranch(); + if (fClosed) + nav->GetCache()->BuildInfoBranch(); } } @@ -3456,41 +3705,41 @@ void TGeoManager::SetTopVolume(TGeoVolume *vol) void TGeoManager::SelectTrackingMedia() { -/* - Int_t nmat = fMaterials->GetSize(); - if (!nmat) {printf(" No materials !\n"); return;} - Int_t *media = new Int_t[nmat]; - memset(media, 0, nmat*sizeof(Int_t)); - Int_t imedia = 1; - TGeoMaterial *mat, *matref; - mat = (TGeoMaterial*)fMaterials->At(0); - if (mat->GetMedia()) { + /* + Int_t nmat = fMaterials->GetSize(); + if (!nmat) {printf(" No materials !\n"); return;} + Int_t *media = new Int_t[nmat]; + memset(media, 0, nmat*sizeof(Int_t)); + Int_t imedia = 1; + TGeoMaterial *mat, *matref; + mat = (TGeoMaterial*)fMaterials->At(0); + if (mat->GetMedia()) { + for (Int_t i=0; iAt(i); + mat->Print(); + } + return; + } + mat->SetMedia(imedia); + media[0] = imedia++; + mat->Print(); for (Int_t i=0; iAt(i); - mat->Print(); - } - return; - } - mat->SetMedia(imedia); - media[0] = imedia++; - mat->Print(); - for (Int_t i=0; iAt(i); - for (Int_t j=0; jAt(j); - if (mat->IsEq(matref)) { - mat->SetMedia(media[j]); - break; - } - if (j==(i-1)) { - // different material - mat->SetMedia(imedia); - media[i] = imedia++; - mat->Print(); + for (Int_t j=0; jAt(j); + if (mat->IsEq(matref)) { + mat->SetMedia(media[j]); + break; + } + if (j==(i-1)) { + // different material + mat->SetMedia(imedia); + media[i] = imedia++; + mat->Print(); + } } } - } -*/ + */ } //////////////////////////////////////////////////////////////////////////////// @@ -3518,7 +3767,7 @@ void TGeoManager::CheckBoundaryReference(Int_t icheck) void TGeoManager::CheckPoint(Double_t x, Double_t y, Double_t z, Option_t *option) { - GetGeomPainter()->CheckPoint(x,y,z,option); + GetGeomPainter()->CheckPoint(x, y, z, option); } //////////////////////////////////////////////////////////////////////////////// @@ -3562,16 +3811,16 @@ void TGeoManager::CheckGeometryFull(Int_t ntracks, Double_t vx, Double_t vy, Dou TString opt(option); opt.ToLower(); if (!opt.Length()) { - Error("CheckGeometryFull","The option string must contain a letter. See method documentation."); + Error("CheckGeometryFull", "The option string must contain a letter. See method documentation."); return; } - Bool_t checkoverlaps = opt.Contains("o"); + Bool_t checkoverlaps = opt.Contains("o"); Bool_t checkcrossings = opt.Contains("b"); Double_t vertex[3]; vertex[0] = vx; vertex[1] = vy; vertex[2] = vz; - GetGeomPainter()->CheckGeometryFull(checkoverlaps,checkcrossings,ntracks,vertex); + GetGeomPainter()->CheckGeometryFull(checkoverlaps, checkcrossings, ntracks, vertex); } //////////////////////////////////////////////////////////////////////////////// @@ -3579,26 +3828,32 @@ void TGeoManager::CheckGeometryFull(Int_t ntracks, Double_t vx, Double_t vy, Dou void TGeoManager::CheckGeometry(Option_t * /*option*/) { - if (fgVerboseLevel>0) Info("CheckGeometry","Fixing runtime shapes..."); + if (fgVerboseLevel > 0) + Info("CheckGeometry", "Fixing runtime shapes..."); TIter next(fShapes); TIter nextv(fVolumes); TGeoShape *shape; TGeoVolume *vol; Bool_t has_runtime = kFALSE; - while ((shape = (TGeoShape*)next())) { + while ((shape = (TGeoShape *)next())) { if (shape->IsRunTimeShape()) { has_runtime = kTRUE; } - if (fIsGeomReading) shape->AfterStreamer(); + if (fIsGeomReading) + shape->AfterStreamer(); if (shape->TestShapeBit(TGeoShape::kGeoPcon) || shape->TestShapeBit(TGeoShape::kGeoArb8)) - if (!shape->TestShapeBit(TGeoShape::kGeoClosedShape)) shape->ComputeBBox(); + if (!shape->TestShapeBit(TGeoShape::kGeoClosedShape)) + shape->ComputeBBox(); } - if (has_runtime) fTopNode->CheckShapes(); - else if (fgVerboseLevel>0) Info("CheckGeometry","...Nothing to fix"); + if (has_runtime) + fTopNode->CheckShapes(); + else if (fgVerboseLevel > 0) + Info("CheckGeometry", "...Nothing to fix"); // Compute bounding box for assemblies TGeoMedium *dummy = TGeoVolume::DummyMedium(); - while ((vol = (TGeoVolume*)nextv())) { - if (vol->IsAssembly()) vol->GetShape()->ComputeBBox(); + while ((vol = (TGeoVolume *)nextv())) { + if (vol->IsAssembly()) + vol->GetShape()->ComputeBBox(); else if (vol->GetMedium() == dummy) { Warning("CheckGeometry", "Volume \"%s\" has no medium: assigned dummy medium and material", vol->GetName()); vol->SetMedium(dummy); @@ -3609,13 +3864,13 @@ void TGeoManager::CheckGeometry(Option_t * /*option*/) //////////////////////////////////////////////////////////////////////////////// /// Check all geometry for illegal overlaps within a limit OVLP. -void TGeoManager::CheckOverlaps(Double_t ovlp, Option_t * option) +void TGeoManager::CheckOverlaps(Double_t ovlp, Option_t *option) { if (!fTopNode) { - Error("CheckOverlaps","Top node not set"); + Error("CheckOverlaps", "Top node not set"); return; } - fTopNode->CheckOverlaps(ovlp,option); + fTopNode->CheckOverlaps(ovlp, option); } //////////////////////////////////////////////////////////////////////////////// @@ -3623,10 +3878,12 @@ void TGeoManager::CheckOverlaps(Double_t ovlp, Option_t * option) void TGeoManager::PrintOverlaps() const { - if (!fOverlaps) return; + if (!fOverlaps) + return; Int_t novlp = fOverlaps->GetEntriesFast(); - if (!novlp) return; - TGeoManager *geom = (TGeoManager*)this; + if (!novlp) + return; + TGeoManager *geom = (TGeoManager *)this; geom->GetGeomPainter()->PrintOverlaps(); } @@ -3643,13 +3900,15 @@ Double_t TGeoManager::Weight(Double_t precision, Option_t *option) TGeoVolume *volume = fTopVolume; if (opt.Contains("v")) { if (opt.Contains("a")) { - if (fgVerboseLevel>0) Info("Weight", "Computing analytically weight of %s", volume->GetName()); + if (fgVerboseLevel > 0) + Info("Weight", "Computing analytically weight of %s", volume->GetName()); weight = volume->WeightA(); - if (fgVerboseLevel>0) Info("Weight", "Computed weight: %f [kg]\n", weight); + if (fgVerboseLevel > 0) + Info("Weight", "Computed weight: %f [kg]\n", weight); return weight; } - if (fgVerboseLevel>0) { - Info("Weight", "Estimating weight of %s with %g %% precision", fTopVolume->GetName(), 100.*precision); + if (fgVerboseLevel > 0) { + Info("Weight", "Estimating weight of %s with %g %% precision", fTopVolume->GetName(), 100. * precision); printf(" event weight err\n"); printf("========================================\n"); } @@ -3688,7 +3947,8 @@ void TGeoManager::Streamer(TBuffer &R__b) void TGeoManager::ExecuteEvent(Int_t event, Int_t px, Int_t py) { - if (!fPainter) return; + if (!fPainter) + return; fPainter->ExecuteManagerEvent(this, event, px, py); } @@ -3714,50 +3974,55 @@ Int_t TGeoManager::Export(const char *filename, const char *name, Option_t *opti { TString sfile(filename); if (sfile.Contains(".C")) { - //Save geometry as a C++ script - if (fgVerboseLevel>0) Info("Export","Exporting %s %s as C++ code", GetName(), GetTitle()); + // Save geometry as a C++ script + if (fgVerboseLevel > 0) + Info("Export", "Exporting %s %s as C++ code", GetName(), GetTitle()); fTopVolume->SaveAs(filename); return 1; } if (sfile.Contains(".gdml")) { - //Save geometry as a gdml file - if (fgVerboseLevel>0) Info("Export","Exporting %s %s as gdml code", GetName(), GetTitle()); - //C++ version - TString cmd ; + // Save geometry as a gdml file + if (fgVerboseLevel > 0) + Info("Export", "Exporting %s %s as gdml code", GetName(), GetTitle()); + // C++ version + TString cmd; cmd = TString::Format("TGDMLWrite::StartGDMLWriting(gGeoManager,\"%s\",\"%s\")", filename, option); gROOT->ProcessLineFast(cmd); return 1; } if (sfile.Contains(".root") || sfile.Contains(".xml")) { - //Save geometry as a root file - TFile *f = TFile::Open(filename,"recreate"); + // Save geometry as a root file + TFile *f = TFile::Open(filename, "recreate"); if (!f || f->IsZombie()) { - Error("Export","Cannot open file"); + Error("Export", "Cannot open file"); return 0; } TString keyname = name; - if (keyname.IsNull()) keyname = GetName(); + if (keyname.IsNull()) + keyname = GetName(); TString opt = option; opt.ToLower(); if (opt.Contains("v")) { fStreamVoxels = kTRUE; - if (fgVerboseLevel>0) Info("Export","Exporting %s %s as root file. Optimizations streamed.", GetName(), GetTitle()); + if (fgVerboseLevel > 0) + Info("Export", "Exporting %s %s as root file. Optimizations streamed.", GetName(), GetTitle()); } else { fStreamVoxels = kFALSE; - if (fgVerboseLevel>0) Info("Export","Exporting %s %s as root file. Optimizations not streamed.", GetName(), GetTitle()); + if (fgVerboseLevel > 0) + Info("Export", "Exporting %s %s as root file. Optimizations not streamed.", GetName(), GetTitle()); } const char *precision_dbl = TBufferText::GetDoubleFormat(); const char *precision_flt = TBufferText::GetFloatFormat(); TString new_format_dbl = TString::Format("%%.%dg", TGeoManager::GetExportPrecision()); if (sfile.Contains(".xml")) { - TBufferText::SetDoubleFormat(new_format_dbl.Data()); - TBufferText::SetFloatFormat(new_format_dbl.Data()); + TBufferText::SetDoubleFormat(new_format_dbl.Data()); + TBufferText::SetFloatFormat(new_format_dbl.Data()); } Int_t nbytes = Write(keyname); if (sfile.Contains(".xml")) { - TBufferText::SetFloatFormat(precision_dbl); - TBufferText::SetDoubleFormat(precision_flt); + TBufferText::SetFloatFormat(precision_dbl); + TBufferText::SetDoubleFormat(precision_flt); } fStreamVoxels = kFALSE; @@ -3810,8 +4075,8 @@ void TGeoManager::SetVerboseLevel(Int_t vl) } //////////////////////////////////////////////////////////////////////////////// -///static function -///Import a geometry from a gdml or ROOT file +/// static function +/// Import a geometry from a gdml or ROOT file /// /// - Case 1: gdml /// if filename ends with ".gdml" the foreign geometry described with gdml @@ -3832,24 +4097,26 @@ TGeoManager *TGeoManager::Import(const char *filename, const char *name, Option_ ::Warning("TGeoManager::Import", "TGeoMananager in lock mode. NOT IMPORTING new geometry"); return nullptr; } - if (!filename) return 0; - if (fgVerboseLevel>0) ::Info("TGeoManager::Import","Reading geometry from file: %s",filename); + if (!filename) + return 0; + if (fgVerboseLevel > 0) + ::Info("TGeoManager::Import", "Reading geometry from file: %s", filename); - if (gGeoManager) delete gGeoManager; + if (gGeoManager) + delete gGeoManager; gGeoManager = nullptr; - if (strstr(filename,".gdml")) { + if (strstr(filename, ".gdml")) { // import from a gdml file new TGeoManager("GDMLImport", "Geometry imported from GDML"); TString cmd = TString::Format("TGDMLParse::StartGDML(\"%s\")", filename); - TGeoVolume* world = (TGeoVolume*)gROOT->ProcessLineFast(cmd); + TGeoVolume *world = (TGeoVolume *)gROOT->ProcessLineFast(cmd); - if(world == nullptr) { + if (world == nullptr) { delete gGeoManager; gGeoManager = nullptr; ::Error("TGeoManager::Import", "Cannot read file %s", filename); - } - else { + } else { gGeoManager->SetTopVolume(world); gGeoManager->CloseGeometry(); gGeoManager->DefaultColors(); @@ -3860,28 +4127,34 @@ TGeoManager *TGeoManager::Import(const char *filename, const char *name, Option_ // in case a web file is specified, use the cacheread option to cache // this file in the cache directory TFile *f = nullptr; - if (strstr(filename,"http")) f = TFile::Open(filename,"CACHEREAD"); - else f = TFile::Open(filename); + if (strstr(filename, "http")) + f = TFile::Open(filename, "CACHEREAD"); + else + f = TFile::Open(filename); if (!f || f->IsZombie()) { ::Error("TGeoManager::Import", "Cannot open file"); return nullptr; } if (name && strlen(name) > 0) { - gGeoManager = (TGeoManager*)f->Get(name); + gGeoManager = (TGeoManager *)f->Get(name); } else { TIter next(f->GetListOfKeys()); TKey *key; - while ((key = (TKey*)next())) { - if (strcmp(key->GetClassName(),"TGeoManager") != 0) continue; - gGeoManager = (TGeoManager*)key->ReadObj(); + while ((key = (TKey *)next())) { + if (strcmp(key->GetClassName(), "TGeoManager") != 0) + continue; + gGeoManager = (TGeoManager *)key->ReadObj(); break; } } delete f; } - if (!gGeoManager) return 0; - if (!gROOT->GetListOfGeometries()->FindObject(gGeoManager)) gROOT->GetListOfGeometries()->Add(gGeoManager); - if (!gROOT->GetListOfBrowsables()->FindObject(gGeoManager)) gROOT->GetListOfBrowsables()->Add(gGeoManager); + if (!gGeoManager) + return 0; + if (!gROOT->GetListOfGeometries()->FindObject(gGeoManager)) + gROOT->GetListOfGeometries()->Add(gGeoManager); + if (!gROOT->GetListOfBrowsables()->FindObject(gGeoManager)) + gROOT->GetListOfBrowsables()->Add(gGeoManager); gGeoManager->UpdateElements(); return gGeoManager; } @@ -3891,21 +4164,24 @@ TGeoManager *TGeoManager::Import(const char *filename, const char *name, Option_ void TGeoManager::UpdateElements() { - if (!fElementTable) return; + if (!fElementTable) + return; TIter next(fMaterials); TGeoMaterial *mat; TGeoMixture *mix; TGeoElement *elem, *elem_table; Int_t i, nelem; - while ((mat=(TGeoMaterial*)next())) { + while ((mat = (TGeoMaterial *)next())) { if (mat->IsMixture()) { - mix = (TGeoMixture*)mat; + mix = (TGeoMixture *)mat; nelem = mix->GetNelements(); - for (i=0; iGetElement(i); - if (!elem) continue; + if (!elem) + continue; elem_table = fElementTable->GetElement(elem->Z()); - if (!elem_table) continue; + if (!elem_table) + continue; if (elem != elem_table) { elem_table->SetDefined(elem->IsDefined()); elem_table->SetUsed(elem->IsUsed()); @@ -3915,9 +4191,11 @@ void TGeoManager::UpdateElements() } } else { elem = mat->GetElement(); - if (!elem) continue; + if (!elem) + continue; elem_table = fElementTable->GetElement(elem->Z()); - if (!elem_table) continue; + if (!elem_table) + continue; if (elem != elem_table) { elem_table->SetDefined(elem->IsDefined()); elem_table->SetUsed(elem->IsUsed()); @@ -3934,13 +4212,13 @@ void TGeoManager::UpdateElements() Bool_t TGeoManager::InitArrayPNE() const { if (fHashPNE) { - fArrayPNE = new TObjArray(fHashPNE->GetSize()); - TIter next(fHashPNE); - TObject *obj; - while ((obj = next())) { - fArrayPNE->Add(obj); - } - return kTRUE; + fArrayPNE = new TObjArray(fHashPNE->GetSize()); + TIter next(fHashPNE); + TObject *obj; + while ((obj = next())) { + fArrayPNE->Add(obj); + } + return kTRUE; } return kFALSE; } @@ -3963,9 +4241,12 @@ void TGeoManager::SetTminTmax(Double_t tmin, Double_t tmax) { fTmin = tmin; fTmax = tmax; - if (tmin==0 && tmax==999) fTimeCut = kFALSE; - else fTimeCut = kTRUE; - if (fTracks && !IsAnimatingTracks()) ModifiedPad(); + if (tmin == 0 && tmax == 999) + fTimeCut = kFALSE; + else + fTimeCut = kTRUE; + if (fTracks && !IsAnimatingTracks()) + ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// @@ -4017,36 +4298,35 @@ void TGeoManager::SetUseParallelWorldNav(Bool_t flag) return; } // Closing the parallel world geometry is mandatory - if (fParallelWorld->CloseGeometry()) fUsePWNav=kTRUE; + if (fParallelWorld->CloseGeometry()) + fUsePWNav = kTRUE; } -Bool_t TGeoManager::LockDefaultUnits(Bool_t new_value) { - Bool_t val = gGeometryLocked; - gGeometryLocked = new_value; - return val; +Bool_t TGeoManager::LockDefaultUnits(Bool_t new_value) +{ + Bool_t val = gGeometryLocked; + gGeometryLocked = new_value; + return val; } TGeoManager::EDefaultUnits TGeoManager::GetDefaultUnits() { - return fgDefaultUnits; + return fgDefaultUnits; } void TGeoManager::SetDefaultUnits(EDefaultUnits new_value) { - if ( fgDefaultUnits == new_value ) { + if (fgDefaultUnits == new_value) { gGeometryLocked = true; return; - } - else if ( gGeometryLocked ) { - ::Fatal("TGeoManager","The system of units may only be changed once, \n" - "BEFORE any elements and materials are created! \n" - "Alternatively unlock the default units at own risk."); - } - else if ( new_value == kG4Units ) { - ::Info("TGeoManager","Changing system of units to Geant4 units (mm, ns, MeV)."); - } - else if ( new_value == kRootUnits ) { - ::Info("TGeoManager","Changing system of units to ROOT units (cm, s, GeV)."); + } else if (gGeometryLocked) { + ::Fatal("TGeoManager", "The system of units may only be changed once, \n" + "BEFORE any elements and materials are created! \n" + "Alternatively unlock the default units at own risk."); + } else if (new_value == kG4Units) { + ::Info("TGeoManager", "Changing system of units to Geant4 units (mm, ns, MeV)."); + } else if (new_value == kRootUnits) { + ::Info("TGeoManager", "Changing system of units to ROOT units (cm, s, GeV)."); } fgDefaultUnits = new_value; } @@ -4060,4 +4340,3 @@ UInt_t TGeoManager::GetExportPrecision() { return fgExportPrecision; } - diff --git a/geom/geom/src/TGeoMaterial.cxx b/geom/geom/src/TGeoMaterial.cxx index 106dd6ba265a4..d8c424c5849bf 100644 --- a/geom/geom/src/TGeoMaterial.cxx +++ b/geom/geom/src/TGeoMaterial.cxx @@ -58,25 +58,26 @@ ClassImp(TGeoMaterial); /// Default constructor. TGeoMaterial::TGeoMaterial() - :TNamed(), TAttFill(), - fIndex(0), - fA(0.), - fZ(0.), - fDensity(0.), - fRadLen(0.), - fIntLen(0.), - fTemperature(0.), - fPressure(0.), - fState(kMatStateUndefined), - fShader(NULL), - fCerenkov(NULL), - fElement(NULL), - fUserExtension(0), - fFWExtension(0) + : TNamed(), + TAttFill(), + fIndex(0), + fA(0.), + fZ(0.), + fDensity(0.), + fRadLen(0.), + fIntLen(0.), + fTemperature(0.), + fPressure(0.), + fState(kMatStateUndefined), + fShader(NULL), + fCerenkov(NULL), + fElement(NULL), + fUserExtension(0), + fFWExtension(0) { TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards SetUsed(kFALSE); - fIndex = -1; + fIndex = -1; fTemperature = STP_temperature; fPressure = STP_pressure; fState = kMatStateUndefined; @@ -88,26 +89,27 @@ TGeoMaterial::TGeoMaterial() /// \param name material name. TGeoMaterial::TGeoMaterial(const char *name) - :TNamed(name, ""), TAttFill(), - fIndex(0), - fA(0.), - fZ(0.), - fDensity(0.), - fRadLen(0.), - fIntLen(0.), - fTemperature(0.), - fPressure(0.), - fState(kMatStateUndefined), - fShader(NULL), - fCerenkov(NULL), - fElement(NULL), - fUserExtension(0), - fFWExtension(0) + : TNamed(name, ""), + TAttFill(), + fIndex(0), + fA(0.), + fZ(0.), + fDensity(0.), + fRadLen(0.), + fIntLen(0.), + fTemperature(0.), + fPressure(0.), + fState(kMatStateUndefined), + fShader(NULL), + fCerenkov(NULL), + fElement(NULL), + fUserExtension(0), + fFWExtension(0) { TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards fName = fName.Strip(); SetUsed(kFALSE); - fIndex = -1; + fIndex = -1; fTemperature = STP_temperature; fPressure = STP_pressure; fState = kMatStateUndefined; @@ -128,31 +130,31 @@ TGeoMaterial::TGeoMaterial(const char *name) /// \param radlen /// \param intlen -TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, - Double_t rho, Double_t radlen, Double_t intlen) - :TNamed(name, ""), TAttFill(), - fIndex(0), - fA(a), - fZ(z), - fDensity(rho), - fRadLen(0.), - fIntLen(0.), - fTemperature(0.), - fPressure(0.), - fState(kMatStateUndefined), - fShader(NULL), - fCerenkov(NULL), - fElement(NULL), - fUserExtension(0), - fFWExtension(0) +TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, Double_t radlen, Double_t intlen) + : TNamed(name, ""), + TAttFill(), + fIndex(0), + fA(a), + fZ(z), + fDensity(rho), + fRadLen(0.), + fIntLen(0.), + fTemperature(0.), + fPressure(0.), + fState(kMatStateUndefined), + fShader(NULL), + fCerenkov(NULL), + fElement(NULL), + fUserExtension(0), + fFWExtension(0) { TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards fName = fName.Strip(); SetUsed(kFALSE); - fIndex = -1; - fA = a; - fZ = z; - fDensity = rho; + fIndex = -1; + fA = a; + fZ = z; + fDensity = rho; fTemperature = STP_temperature; fPressure = STP_pressure; fState = kMatStateUndefined; @@ -162,7 +164,8 @@ TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, } if (fZ - Int_t(fZ) > 1E-3) Warning("ctor", "Material %s defined with fractional Z=%f", GetName(), fZ); - if (GetElement()) GetElement()->SetUsed(); + if (GetElement()) + GetElement()->SetUsed(); gGeoManager->AddMaterial(this); } @@ -177,36 +180,37 @@ TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, /// \param temperature /// \param pressure - -TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, - EGeoMaterialState state, Double_t temperature, Double_t pressure) - :TNamed(name, ""), TAttFill(), - fIndex(0), - fA(a), - fZ(z), - fDensity(rho), - fRadLen(0.), - fIntLen(0.), - fTemperature(temperature), - fPressure(pressure), - fState(state), - fShader(NULL), - fCerenkov(NULL), - fElement(NULL), - fUserExtension(0), - fFWExtension(0) +TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rho, EGeoMaterialState state, + Double_t temperature, Double_t pressure) + : TNamed(name, ""), + TAttFill(), + fIndex(0), + fA(a), + fZ(z), + fDensity(rho), + fRadLen(0.), + fIntLen(0.), + fTemperature(temperature), + fPressure(pressure), + fState(state), + fShader(NULL), + fCerenkov(NULL), + fElement(NULL), + fUserExtension(0), + fFWExtension(0) { TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards fName = fName.Strip(); SetUsed(kFALSE); - fIndex = -1; - SetRadLen(0,0); + fIndex = -1; + SetRadLen(0, 0); if (!gGeoManager) { gGeoManager = new TGeoManager("Geometry", "default geometry"); } if (fZ - Int_t(fZ) > 1E-3) Warning("ctor", "Material %s defined with fractional Z=%f", GetName(), fZ); - if (GetElement()) GetElement()->SetUsed(); + if (GetElement()) + GetElement()->SetUsed(); gGeoManager->AddMaterial(this); } @@ -218,29 +222,30 @@ TGeoMaterial::TGeoMaterial(const char *name, Double_t a, Double_t z, Double_t rh /// \param rho material density in g/cm3. TGeoMaterial::TGeoMaterial(const char *name, TGeoElement *elem, Double_t rho) - :TNamed(name, ""), TAttFill(), - fIndex(0), - fA(0.), - fZ(0.), - fDensity(rho), - fRadLen(0.), - fIntLen(0.), - fTemperature(0.), - fPressure(0.), - fState(kMatStateUndefined), - fShader(NULL), - fCerenkov(NULL), - fElement(elem), - fUserExtension(0), - fFWExtension(0) + : TNamed(name, ""), + TAttFill(), + fIndex(0), + fA(0.), + fZ(0.), + fDensity(rho), + fRadLen(0.), + fIntLen(0.), + fTemperature(0.), + fPressure(0.), + fState(kMatStateUndefined), + fShader(NULL), + fCerenkov(NULL), + fElement(elem), + fUserExtension(0), + fFWExtension(0) { TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards fName = fName.Strip(); SetUsed(kFALSE); - fIndex = -1; - fA = elem->A(); - fZ = elem->Z(); - SetRadLen(0,0); + fIndex = -1; + fA = elem->A(); + fZ = elem->Z(); + SetRadLen(0, 0); fTemperature = STP_temperature; fPressure = STP_pressure; fState = kMatStateUndefined; @@ -249,65 +254,68 @@ TGeoMaterial::TGeoMaterial(const char *name, TGeoElement *elem, Double_t rho) } if (fZ - Int_t(fZ) > 1E-3) Warning("ctor", "Material %s defined with fractional Z=%f", GetName(), fZ); - if (GetElement()) GetElement()->SetUsed(); + if (GetElement()) + GetElement()->SetUsed(); gGeoManager->AddMaterial(this); } //////////////////////////////////////////////////////////////////////////////// -TGeoMaterial::TGeoMaterial(const TGeoMaterial& gm) : - TNamed(gm), - TAttFill(gm), - fIndex(gm.fIndex), - fA(gm.fA), - fZ(gm.fZ), - fDensity(gm.fDensity), - fRadLen(gm.fRadLen), - fIntLen(gm.fIntLen), - fTemperature(gm.fTemperature), - fPressure(gm.fPressure), - fState(gm.fState), - fShader(gm.fShader), - fCerenkov(gm.fCerenkov), - fElement(gm.fElement), - fUserExtension(gm.fUserExtension->Grab()), - fFWExtension(gm.fFWExtension->Grab()) +TGeoMaterial::TGeoMaterial(const TGeoMaterial &gm) + : TNamed(gm), + TAttFill(gm), + fIndex(gm.fIndex), + fA(gm.fA), + fZ(gm.fZ), + fDensity(gm.fDensity), + fRadLen(gm.fRadLen), + fIntLen(gm.fIntLen), + fTemperature(gm.fTemperature), + fPressure(gm.fPressure), + fState(gm.fState), + fShader(gm.fShader), + fCerenkov(gm.fCerenkov), + fElement(gm.fElement), + fUserExtension(gm.fUserExtension->Grab()), + fFWExtension(gm.fFWExtension->Grab()) { - //copy constructor + // copy constructor TGeoManager::SetDefaultUnits(TGeoManager::GetDefaultUnits()); // Ensure nobody changes the units afterwards fProperties.SetOwner(); TIter next(&fProperties); TNamed *property; - while ((property = (TNamed*)next())) fProperties.Add(new TNamed(*property)); + while ((property = (TNamed *)next())) + fProperties.Add(new TNamed(*property)); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoMaterial& TGeoMaterial::operator=(const TGeoMaterial& gm) +TGeoMaterial &TGeoMaterial::operator=(const TGeoMaterial &gm) { - if(this!=&gm) { + if (this != &gm) { TNamed::operator=(gm); TAttFill::operator=(gm); - fIndex=gm.fIndex; - fA=gm.fA; - fZ=gm.fZ; - fDensity=gm.fDensity; - fRadLen=gm.fRadLen; - fIntLen=gm.fIntLen; - fTemperature=gm.fTemperature; - fPressure=gm.fPressure; - fState=gm.fState; - fShader=gm.fShader; - fCerenkov=gm.fCerenkov; - fElement=gm.fElement; + fIndex = gm.fIndex; + fA = gm.fA; + fZ = gm.fZ; + fDensity = gm.fDensity; + fRadLen = gm.fRadLen; + fIntLen = gm.fIntLen; + fTemperature = gm.fTemperature; + fPressure = gm.fPressure; + fState = gm.fState; + fShader = gm.fShader; + fCerenkov = gm.fCerenkov; + fElement = gm.fElement; fUserExtension = gm.fUserExtension->Grab(); fFWExtension = gm.fFWExtension->Grab(); fProperties.SetOwner(); TIter next(&fProperties); TNamed *property; - while ((property = (TNamed*)next())) fProperties.Add(new TNamed(*property)); + while ((property = (TNamed *)next())) + fProperties.Add(new TNamed(*property)); } return *this; } @@ -317,8 +325,14 @@ TGeoMaterial& TGeoMaterial::operator=(const TGeoMaterial& gm) TGeoMaterial::~TGeoMaterial() { - if (fUserExtension) {fUserExtension->Release(); fUserExtension=0;} - if (fFWExtension) {fFWExtension->Release(); fFWExtension=0;} + if (fUserExtension) { + fUserExtension->Release(); + fUserExtension = 0; + } + if (fFWExtension) { + fFWExtension->Release(); + fFWExtension = 0; + } } //////////////////////////////////////////////////////////////////////////////// @@ -331,16 +345,18 @@ TGeoMaterial::~TGeoMaterial() void TGeoMaterial::SetUserExtension(TGeoExtension *ext) { - if (fUserExtension) fUserExtension->Release(); + if (fUserExtension) + fUserExtension->Release(); fUserExtension = 0; - if (ext) fUserExtension = ext->Grab(); + if (ext) + fUserExtension = ext->Grab(); } //_____________________________________________________________________________ const char *TGeoMaterial::GetPropertyRef(const char *property) const { // Find reference for a given property - TNamed *prop = (TNamed*)fProperties.FindObject(property); + TNamed *prop = (TNamed *)fProperties.FindObject(property); return (prop) ? prop->GetTitle() : nullptr; } @@ -348,8 +364,9 @@ const char *TGeoMaterial::GetPropertyRef(const char *property) const TGDMLMatrix *TGeoMaterial::GetProperty(const char *property) const { // Find reference for a given property - TNamed *prop = (TNamed*)fProperties.FindObject(property); - if ( !prop ) return nullptr; + TNamed *prop = (TNamed *)fProperties.FindObject(property); + if (!prop) + return nullptr; return gGeoManager->GetGDMLMatrix(prop->GetTitle()); } @@ -357,8 +374,9 @@ TGDMLMatrix *TGeoMaterial::GetProperty(const char *property) const TGDMLMatrix *TGeoMaterial::GetProperty(Int_t i) const { // Find reference for a given property - TNamed *prop = (TNamed*)fProperties.At(i); - if ( !prop ) return nullptr; + TNamed *prop = (TNamed *)fProperties.At(i); + if (!prop) + return nullptr; return gGeoManager->GetGDMLMatrix(prop->GetTitle()); } @@ -366,7 +384,7 @@ TGDMLMatrix *TGeoMaterial::GetProperty(Int_t i) const const char *TGeoMaterial::GetConstPropertyRef(const char *property) const { // Find reference for a given constant property - TNamed *prop = (TNamed*)fConstProperties.FindObject(property); + TNamed *prop = (TNamed *)fConstProperties.FindObject(property); return (prop) ? prop->GetTitle() : nullptr; } @@ -374,9 +392,10 @@ const char *TGeoMaterial::GetConstPropertyRef(const char *property) const Double_t TGeoMaterial::GetConstProperty(const char *property, Bool_t *err) const { // Find reference for a given constant property - TNamed *prop = (TNamed*)fConstProperties.FindObject(property); + TNamed *prop = (TNamed *)fConstProperties.FindObject(property); if (!prop) { - if (err) *err = kTRUE; + if (err) + *err = kTRUE; return 0.; } return gGeoManager->GetProperty(prop->GetTitle(), err); @@ -386,9 +405,10 @@ Double_t TGeoMaterial::GetConstProperty(const char *property, Bool_t *err) const Double_t TGeoMaterial::GetConstProperty(Int_t i, Bool_t *err) const { // Find reference for a given constant property - TNamed *prop = (TNamed*)fConstProperties.At(i); + TNamed *prop = (TNamed *)fConstProperties.At(i); if (!prop) { - if (err) *err = kTRUE; + if (err) + *err = kTRUE; return 0.; } return gGeoManager->GetProperty(prop->GetTitle(), err); @@ -399,8 +419,7 @@ bool TGeoMaterial::AddProperty(const char *property, const char *ref) { fProperties.SetOwner(); if (GetPropertyRef(property)) { - Error("AddProperty", "Property %s already added to material %s", - property, GetName()); + Error("AddProperty", "Property %s already added to material %s", property, GetName()); return false; } fProperties.Add(new TNamed(property, ref)); @@ -412,8 +431,7 @@ bool TGeoMaterial::AddConstProperty(const char *property, const char *ref) { fConstProperties.SetOwner(); if (GetConstPropertyRef(property)) { - Error("AddConstProperty", "Constant property %s already added to material %s", - property, GetName()); + Error("AddConstProperty", "Constant property %s already added to material %s", property, GetName()); return false; } fConstProperties.Add(new TNamed(property, ref)); @@ -430,9 +448,11 @@ bool TGeoMaterial::AddConstProperty(const char *property, const char *ref) void TGeoMaterial::SetFWExtension(TGeoExtension *ext) { - if (fFWExtension) fFWExtension->Release(); + if (fFWExtension) + fFWExtension->Release(); fFWExtension = 0; - if (ext) fFWExtension = ext->Grab(); + if (ext) + fFWExtension = ext->Grab(); } //////////////////////////////////////////////////////////////////////////////// @@ -442,7 +462,8 @@ void TGeoMaterial::SetFWExtension(TGeoExtension *ext) TGeoExtension *TGeoMaterial::GrabUserExtension() const { - if (fUserExtension) return fUserExtension->Grab(); + if (fUserExtension) + return fUserExtension->Grab(); return 0; } @@ -453,7 +474,8 @@ TGeoExtension *TGeoMaterial::GrabUserExtension() const TGeoExtension *TGeoMaterial::GrabFWExtension() const { - if (fFWExtension) return fFWExtension->Grab(); + if (fFWExtension) + return fFWExtension->Grab(); return 0; } @@ -476,24 +498,27 @@ void TGeoMaterial::SetRadLen(Double_t radlen, Double_t intlen) fRadLen = TMath::Abs(radlen); fIntLen = TMath::Abs(intlen); // Check for vacuum - if (fA<0.9 || fZ<0.9) { - if (radlen<-1e5 || intlen<-1e-5) { - Error("SetRadLen","Material %s: user values taken for vacuum: radlen=%g or intlen=%g - too small", GetName(),fRadLen, fIntLen); + if (fA < 0.9 || fZ < 0.9) { + if (radlen < -1e5 || intlen < -1e-5) { + Error("SetRadLen", "Material %s: user values taken for vacuum: radlen=%g or intlen=%g - too small", GetName(), + fRadLen, fIntLen); return; } // Ignore positive values and take big numbers - if (radlen>=0) fRadLen = 1.E30; - if (intlen>=0) fIntLen = 1.E30; + if (radlen >= 0) + fRadLen = 1.E30; + if (intlen >= 0) + fIntLen = 1.E30; return; } TGeoManager::EDefaultUnits typ = TGeoManager::GetDefaultUnits(); // compute radlen systematically with G3 formula for a valid material if (radlen >= 0) { - //taken grom Geant3 routine GSMATE + // taken grom Geant3 routine GSMATE constexpr Double_t alr2av = 1.39621E-03; - constexpr Double_t al183 = 5.20948; - fRadLen = fA/(alr2av*fDensity*fZ*(fZ +TGeoMaterial::ScreenFactor(fZ))* - (al183-TMath::Log(fZ)/3-TGeoMaterial::Coulomb(fZ))); + constexpr Double_t al183 = 5.20948; + fRadLen = fA / (alr2av * fDensity * fZ * (fZ + TGeoMaterial::ScreenFactor(fZ)) * + (al183 - TMath::Log(fZ) / 3 - TGeoMaterial::Coulomb(fZ))); // fRadLen is in TGeo units. Apply conversion factor in requested length-units fRadLen *= (typ == TGeoManager::kRootUnits) ? TGeoUnit::cm : TGeant4Unit::cm; } @@ -506,8 +531,8 @@ void TGeoMaterial::SetRadLen(Double_t radlen, Double_t intlen) Fatal("SetRadLen", "Element not found for material %s", GetName()); return; } - Double_t nbAtomsPerVolume = TGeoUnit::Avogadro*fDensity/elem->A(); - nilinv += nbAtomsPerVolume*TMath::Power(elem->Neff(), 0.6666667); + Double_t nbAtomsPerVolume = TGeoUnit::Avogadro * fDensity / elem->A(); + nilinv += nbAtomsPerVolume * TMath::Power(elem->Neff(), 0.6666667); nilinv *= TGeoUnit::amu / lambda0; fIntLen = (nilinv <= 0) ? TGeoShape::Big() : (1.0 / nilinv); // fIntLen is in TGeo units. Apply conversion factor in requested length-units @@ -523,12 +548,12 @@ void TGeoMaterial::SetRadLen(Double_t radlen, Double_t intlen) Double_t TGeoMaterial::Coulomb(Double_t z) { - Double_t az = TGeoManager::kRootUnits == TGeoManager::GetDefaultUnits() - ? TGeoUnit::fine_structure_const*z : TGeant4Unit::fine_structure_const*z; - Double_t az2 = az*az; - Double_t az4 = az2 * az2; - Double_t fp = ( 0.0083*az4 + 0.20206 + 1./(1.+az2) ) * az2; - Double_t fm = ( 0.0020*az4 + 0.0369 ) * az4; + Double_t az = TGeoManager::kRootUnits == TGeoManager::GetDefaultUnits() ? TGeoUnit::fine_structure_const * z + : TGeant4Unit::fine_structure_const * z; + Double_t az2 = az * az; + Double_t az4 = az2 * az2; + Double_t fp = (0.0083 * az4 + 0.20206 + 1. / (1. + az2)) * az2; + Double_t fm = (0.0020 * az4 + 0.0369) * az4; return fp - fm; } @@ -537,14 +562,20 @@ Double_t TGeoMaterial::Coulomb(Double_t z) Bool_t TGeoMaterial::IsEq(const TGeoMaterial *other) const { - if (other==this) return kTRUE; - if (other->IsMixture()) return kFALSE; - if (TMath::Abs(fA-other->GetA())>1E-3) return kFALSE; - if (TMath::Abs(fZ-other->GetZ())>1E-3) return kFALSE; - if (TMath::Abs(fDensity-other->GetDensity())>1E-6) return kFALSE; - if (GetCerenkovProperties() != other->GetCerenkovProperties()) return kFALSE; -// if (fRadLen != other->GetRadLen()) return kFALSE; -// if (fIntLen != other->GetIntLen()) return kFALSE; + if (other == this) + return kTRUE; + if (other->IsMixture()) + return kFALSE; + if (TMath::Abs(fA - other->GetA()) > 1E-3) + return kFALSE; + if (TMath::Abs(fZ - other->GetZ()) > 1E-3) + return kFALSE; + if (TMath::Abs(fDensity - other->GetDensity()) > 1E-6) + return kFALSE; + if (GetCerenkovProperties() != other->GetCerenkovProperties()) + return kFALSE; + // if (fRadLen != other->GetRadLen()) return kFALSE; + // if (fIntLen != other->GetIntLen()) return kFALSE; return kTRUE; } @@ -553,8 +584,8 @@ Bool_t TGeoMaterial::IsEq(const TGeoMaterial *other) const void TGeoMaterial::Print(const Option_t * /*option*/) const { - printf("Material %s %s A=%g Z=%g rho=%g radlen=%g intlen=%g index=%i\n", GetName(), GetTitle(), - fA,fZ,fDensity, fRadLen, fIntLen, fIndex); + printf("Material %s %s A=%g Z=%g rho=%g radlen=%g intlen=%g index=%i\n", GetName(), GetTitle(), fA, fZ, fDensity, + fRadLen, fIntLen, fIndex); } //////////////////////////////////////////////////////////////////////////////// @@ -562,7 +593,8 @@ void TGeoMaterial::Print(const Option_t * /*option*/) const void TGeoMaterial::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TestBit(TGeoMaterial::kMatSavePrimitive)) return; + if (TestBit(TGeoMaterial::kMatSavePrimitive)) + return; const char *name = GetPointerName(); out << "// Material: " << GetName() << std::endl; out << " a = " << fA << ";" << std::endl; @@ -581,8 +613,8 @@ void TGeoMaterial::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= "" Int_t TGeoMaterial::GetDefaultColor() const { - Int_t id = 1+ gGeoManager->GetListOfMaterials()->IndexOf(this); - return (2+id%6); + Int_t id = 1 + gGeoManager->GetListOfMaterials()->IndexOf(this); + return (2 + id % 6); } //////////////////////////////////////////////////////////////////////////////// @@ -592,7 +624,8 @@ Int_t TGeoMaterial::GetDefaultColor() const TGeoElement *TGeoMaterial::GetElement() const { - if (fElement) return fElement; + if (fElement) + return fElement; TGeoElementTable *table = gGeoManager->GetElementTable(); return table->GetElement(Int_t(fZ)); } @@ -602,7 +635,8 @@ TGeoElement *TGeoMaterial::GetElement() const TGeoElement *TGeoMaterial::GetElement(Int_t) const { - if (fElement) return fElement; + if (fElement) + return fElement; TGeoElementTable *table = gGeoManager->GetElementTable(); return table->GetElement(Int_t(fZ)); } @@ -622,7 +656,8 @@ void TGeoMaterial::GetElementProp(Double_t &a, Double_t &z, Double_t &w, Int_t) Int_t TGeoMaterial::GetIndex() { - if (fIndex>=0) return fIndex; + if (fIndex >= 0) + return fIndex; TList *matlist = gGeoManager->GetListOfMaterials(); fIndex = matlist->IndexOf(this); return fIndex; @@ -636,43 +671,47 @@ Int_t TGeoMaterial::GetIndex() TGeoMaterial *TGeoMaterial::DecayMaterial(Double_t time, Double_t precision) { TObjArray *pop = new TObjArray(); - if (!fElement || !fElement->IsRadioNuclide()) return this; + if (!fElement || !fElement->IsRadioNuclide()) + return this; FillMaterialEvolution(pop, precision); Int_t ncomp = pop->GetEntriesFast(); - if (!ncomp) return this; + if (!ncomp) + return this; TGeoElementRN *el; Double_t *weight = new Double_t[ncomp]; Double_t amed = 0.; Int_t i; - for (i=0; iAt(i); weight[i] = el->Ratio()->Concentration(time) * el->A(); amed += weight[i]; } - Double_t rho = fDensity*amed/fA; + Double_t rho = fDensity * amed / fA; TGeoMixture *mix = 0; Int_t ncomp1 = ncomp; - for (i=0; iAt(0); - delete [] weight; + delete[] weight; delete pop; - if (ncomp1==1) return new TGeoMaterial(TString::Format("%s-evol",GetName()), el, rho); + if (ncomp1 == 1) + return new TGeoMaterial(TString::Format("%s-evol", GetName()), el, rho); return NULL; } - mix = new TGeoMixture(TString::Format("%s-evol",GetName()), ncomp, rho); - for (i=0; iAt(i); mix->AddElement(el, weight[i]); } - delete [] weight; + delete[] weight; delete pop; return mix; } @@ -710,7 +749,8 @@ void TGeoMaterial::FillMaterialEvolution(TObjArray *population, Double_t precisi TGeoElement *elem; TGeoElementRN *elemrn; TIter next(table->GetElementsRN()); - while ((elemrn=(TGeoElementRN*)next())) elemrn->ResetRatio(); + while ((elemrn = (TGeoElementRN *)next())) + elemrn->ResetRatio(); elem = GetElement(); if (!elem) { Fatal("FillMaterialEvolution", "Element not found for material %s", GetName()); @@ -720,7 +760,7 @@ void TGeoMaterial::FillMaterialEvolution(TObjArray *population, Double_t precisi population->Add(elem); return; } - elemrn = (TGeoElementRN*)elem; + elemrn = (TGeoElementRN *)elem; elemrn->FillPopulation(population, precision); } @@ -739,29 +779,29 @@ ClassImp(TGeoMixture); TGeoMixture::TGeoMixture() { fNelements = 0; - fZmixture = 0; - fAmixture = 0; - fWeights = 0; - fNatoms = 0; + fZmixture = 0; + fAmixture = 0; + fWeights = 0; + fNatoms = 0; fVecNbOfAtomsPerVolume = 0; - fElements = 0; + fElements = 0; } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoMixture::TGeoMixture(const char *name, Int_t /*nel*/, Double_t rho) - :TGeoMaterial(name) +TGeoMixture::TGeoMixture(const char *name, Int_t /*nel*/, Double_t rho) : TGeoMaterial(name) { - fZmixture = 0; - fAmixture = 0; - fWeights = 0; - fNelements = 0; - fNatoms = 0; + fZmixture = 0; + fAmixture = 0; + fWeights = 0; + fNelements = 0; + fNatoms = 0; fVecNbOfAtomsPerVolume = 0; fDensity = rho; - fElements = 0; - if (fDensity < 0) fDensity = 0.001; + fElements = 0; + if (fDensity < 0) + fDensity = 0.001; } //////////////////////////////////////////////////////////////////////////////// @@ -769,12 +809,18 @@ TGeoMixture::TGeoMixture(const char *name, Int_t /*nel*/, Double_t rho) TGeoMixture::~TGeoMixture() { - if (fZmixture) delete[] fZmixture; - if (fAmixture) delete[] fAmixture; - if (fWeights) delete[] fWeights; - if (fNatoms) delete[] fNatoms; - if (fVecNbOfAtomsPerVolume) delete[] fVecNbOfAtomsPerVolume; - if (fElements) delete fElements; + if (fZmixture) + delete[] fZmixture; + if (fAmixture) + delete[] fAmixture; + if (fWeights) + delete[] fWeights; + if (fNatoms) + delete[] fNatoms; + if (fVecNbOfAtomsPerVolume) + delete[] fVecNbOfAtomsPerVolume; + if (fElements) + delete fElements; } //////////////////////////////////////////////////////////////////////////////// @@ -791,19 +837,20 @@ void TGeoMixture::AverageProperties() Double_t nbAtomsPerVolume; fA = 0; fZ = 0; - for (Int_t j=0;jA(); - nilinv += nbAtomsPerVolume*TMath::Power(GetElement(j)->Neff(), 0.6666667); + for (Int_t j = 0; j < fNelements; j++) { + if (fWeights[j] <= 0) + continue; + fA += fWeights[j] * fAmixture[j]; + fZ += fWeights[j] * fZmixture[j]; + nbAtomsPerVolume = na * fDensity * fWeights[j] / GetElement(j)->A(); + nilinv += nbAtomsPerVolume * TMath::Power(GetElement(j)->Neff(), 0.6666667); Double_t zc = fZmixture[j]; - Double_t alz = TMath::Log(zc)/3.; - Double_t xinv = zc*(zc+TGeoMaterial::ScreenFactor(zc))* - (al183-alz-TGeoMaterial::Coulomb(zc))/fAmixture[j]; - radinv += xinv*fWeights[j]; + Double_t alz = TMath::Log(zc) / 3.; + Double_t xinv = + zc * (zc + TGeoMaterial::ScreenFactor(zc)) * (al183 - alz - TGeoMaterial::Coulomb(zc)) / fAmixture[j]; + radinv += xinv * fWeights[j]; } - radinv *= alr2av*fDensity; + radinv *= alr2av * fDensity; fRadLen = (radinv <= 0) ? TGeoShape::Big() : 1.0 / radinv; // fRadLen is in TGeo units. Apply conversion factor in requested length-units fRadLen *= (TGeoManager::GetDefaultUnits() == TGeoManager::kRootUnits) ? TGeoUnit::cm : TGeant4Unit::cm; @@ -824,18 +871,16 @@ void TGeoMixture::AddElement(Double_t a, Double_t z, Double_t weight) TGeoElementTable *table = gGeoManager->GetElementTable(); // Check preconditions - if (weight < 0e0) { + if (weight < 0e0) { Fatal("AddElement", "Cannot add element with negative weight %g to mixture %s", weight, GetName()); - } - else if ( weight < std::numeric_limits::epsilon() ) { + } else if (weight < std::numeric_limits::epsilon()) { return; - } - else if (z<1 || z>table->GetNelements()-1) { + } else if (z < 1 || z > table->GetNelements() - 1) { Fatal("AddElement", "Cannot add element having Z=%d to mixture %s", (Int_t)z, GetName()); } Int_t i; - for (i=0; i 1E-3) Warning("DefineElement", "Mixture %s has element defined with fractional Z=%f", GetName(), z); GetElement(i)->SetDefined(); table->GetElement((Int_t)z)->SetDefined(); - //compute equivalent radiation length (taken from Geant3/GSMIXT) + // compute equivalent radiation length (taken from Geant3/GSMIXT) AverageProperties(); } @@ -883,17 +928,15 @@ void TGeoMixture::AddElement(Double_t a, Double_t z, Double_t weight) void TGeoMixture::AddElement(TGeoMaterial *mat, Double_t weight) { TGeoElement *elnew, *elem; - Double_t a,z; + Double_t a, z; // Check preconditions - if (!mat) { + if (!mat) { Fatal("AddElement", "Cannot add INVALID material to mixture %s", GetName()); - } - else if (weight < 0e0) { - Fatal("AddElement", "Cannot add material %s with negative weight %g to mixture %s", - mat->GetName(), weight, GetName()); - } - else if ( weight < std::numeric_limits::epsilon() ) { + } else if (weight < 0e0) { + Fatal("AddElement", "Cannot add material %s with negative weight %g to mixture %s", mat->GetName(), weight, + GetName()); + } else if (weight < std::numeric_limits::epsilon()) { return; } if (!mat->IsMixture()) { @@ -908,19 +951,21 @@ void TGeoMixture::AddElement(TGeoMaterial *mat, Double_t weight) return; } // The material is a mixture. - TGeoMixture *mix = (TGeoMixture*)mat; + TGeoMixture *mix = (TGeoMixture *)mat; Double_t wnew; Int_t nelem = mix->GetNelements(); Bool_t elfound; - Int_t i,j; + Int_t i, j; // loop the elements of the daughter mixture - for (i=0; iGetElement(i); - if (!elnew) continue; + if (!elnew) + continue; // check if we have the element already defined in the parent mixture - for (j=0; jGetWmixt())[i]; AddElement(elnew, wnew); @@ -943,24 +989,23 @@ void TGeoMixture::AddElement(TGeoElement *elem, Double_t weight) { TGeoElement *elemold; TGeoElementTable *table = gGeoManager->GetElementTable(); - if (!fElements) fElements = new TObjArray(128); + if (!fElements) + fElements = new TObjArray(128); Bool_t exist = kFALSE; // Check preconditions - if (!elem) { + if (!elem) { Fatal("AddElement", "Cannot add INVALID element to mixture %s", GetName()); - } - else if (weight < 0e0) { - Fatal("AddElement", "Cannot add element %s with negative weight %g to mixture %s", - elem->GetName(), weight, GetName()); - } - else if ( weight < std::numeric_limits::epsilon() ) { + } else if (weight < 0e0) { + Fatal("AddElement", "Cannot add element %s with negative weight %g to mixture %s", elem->GetName(), weight, + GetName()); + } else if (weight < std::numeric_limits::epsilon()) { return; } // If previous elements were defined by A/Z, add corresponding TGeoElements - for (Int_t i=0; iAt(i); - if (!elemold) { + for (Int_t i = 0; i < fNelements; i++) { + elemold = (TGeoElement *)fElements->At(i); + if (!elemold) { // Add element with corresponding Z in the list fElements->AddAt(elemold = table->GetElement((Int_t)fZmixture[i]), i); elemold->SetDefined(); @@ -970,7 +1015,7 @@ void TGeoMixture::AddElement(TGeoElement *elem, Double_t weight) exist = kTRUE; } } - if (!exist) { + if (!exist) { fElements->AddAtAndExpand(elem, fNelements); AddElement(elem->A(), elem->Z(), weight); } else { @@ -983,22 +1028,27 @@ void TGeoMixture::AddElement(TGeoElement *elem, Double_t weight) void TGeoMixture::AddElement(TGeoElement *elem, Int_t natoms) { - Int_t i,j; + Int_t i, j; Double_t amol; TGeoElement *elemold; TGeoElementTable *table = gGeoManager->GetElementTable(); - if (!fElements) fElements = new TObjArray(128); + if (!fElements) + fElements = new TObjArray(128); // Check if the element is already defined - for (i=0; iAt(i); - if (!elemold) fElements->AddAt(table->GetElement((Int_t)fZmixture[i]), i); - else if (elemold != elem) continue; - if ((elem==elemold) || - (TMath::Abs(elem->Z()-fZmixture[i])<1.e-6 && TMath::Abs(elem->A()-fAmixture[i])<1.e-6)) { + for (i = 0; i < fNelements; i++) { + elemold = (TGeoElement *)fElements->At(i); + if (!elemold) + fElements->AddAt(table->GetElement((Int_t)fZmixture[i]), i); + else if (elemold != elem) + continue; + if ((elem == elemold) || + (TMath::Abs(elem->Z() - fZmixture[i]) < 1.e-6 && TMath::Abs(elem->A() - fAmixture[i]) < 1.e-6)) { fNatoms[i] += natoms; amol = 0.; - for (j=0; jZ(); fAmixture[iel] = elem->A(); - fNatoms[iel] = natoms; + fNatoms[iel] = natoms; fElements->AddAtAndExpand(elem, iel); amol = 0.; - for (i=0; iGetElement(elem->Z())->SetDefined(); AverageProperties(); } @@ -1059,7 +1110,7 @@ void TGeoMixture::DefineElement(Int_t /*iel*/, Int_t z, Int_t natoms) TGeoElementTable *table = gGeoManager->GetElementTable(); TGeoElement *elem = table->GetElement(z); if (!elem) { - Fatal("DefineElement", "In mixture %s, element with Z=%i not found",GetName(),z); + Fatal("DefineElement", "In mixture %s, element with Z=%i not found", GetName(), z); return; } AddElement(elem, natoms); @@ -1070,13 +1121,15 @@ void TGeoMixture::DefineElement(Int_t /*iel*/, Int_t z, Int_t natoms) TGeoElement *TGeoMixture::GetElement(Int_t i) const { - if (i<0 || i>=fNelements) { + if (i < 0 || i >= fNelements) { Error("GetElement", "Mixture %s has only %d elements", GetName(), fNelements); return 0; } TGeoElement *elem = 0; - if (fElements) elem = (TGeoElement*)fElements->At(i); - if (elem) return elem; + if (fElements) + elem = (TGeoElement *)fElements->At(i); + if (elem) + return elem; TGeoElementTable *table = gGeoManager->GetElementTable(); return table->GetElement(Int_t(fZmixture[i])); } @@ -1087,10 +1140,11 @@ TGeoElement *TGeoMixture::GetElement(Int_t i) const Double_t TGeoMixture::GetSpecificActivity(Int_t i) const { - if (i>=0 && iGetSpecificActivity(); + if (i >= 0 && i < fNelements) + return fWeights[i] * GetElement(i)->GetSpecificActivity(); Double_t sa = 0; - for (Int_t iel=0; ielGetSpecificActivity(); + for (Int_t iel = 0; iel < fNelements; iel++) { + sa += fWeights[iel] * GetElement(iel)->GetSpecificActivity(); } return sa; } @@ -1100,21 +1154,32 @@ Double_t TGeoMixture::GetSpecificActivity(Int_t i) const Bool_t TGeoMixture::IsEq(const TGeoMaterial *other) const { - if (other->IsEqual(this)) return kTRUE; - if (!other->IsMixture()) return kFALSE; - TGeoMixture *mix = (TGeoMixture*)other; - if (!mix) return kFALSE; - if (fNelements != mix->GetNelements()) return kFALSE; - if (TMath::Abs(fA-other->GetA())>1E-3) return kFALSE; - if (TMath::Abs(fZ-other->GetZ())>1E-3) return kFALSE; - if (TMath::Abs(fDensity-other->GetDensity())>1E-6) return kFALSE; - if (GetCerenkovProperties() != other->GetCerenkovProperties()) return kFALSE; -// if (fRadLen != other->GetRadLen()) return kFALSE; -// if (fIntLen != other->GetIntLen()) return kFALSE; - for (Int_t i=0; iGetZmixt())[i])>1E-3) return kFALSE; - if (TMath::Abs(fAmixture[i]-(mix->GetAmixt())[i])>1E-3) return kFALSE; - if (TMath::Abs(fWeights[i]-(mix->GetWmixt())[i])>1E-3) return kFALSE; + if (other->IsEqual(this)) + return kTRUE; + if (!other->IsMixture()) + return kFALSE; + TGeoMixture *mix = (TGeoMixture *)other; + if (!mix) + return kFALSE; + if (fNelements != mix->GetNelements()) + return kFALSE; + if (TMath::Abs(fA - other->GetA()) > 1E-3) + return kFALSE; + if (TMath::Abs(fZ - other->GetZ()) > 1E-3) + return kFALSE; + if (TMath::Abs(fDensity - other->GetDensity()) > 1E-6) + return kFALSE; + if (GetCerenkovProperties() != other->GetCerenkovProperties()) + return kFALSE; + // if (fRadLen != other->GetRadLen()) return kFALSE; + // if (fIntLen != other->GetIntLen()) return kFALSE; + for (Int_t i = 0; i < fNelements; i++) { + if (TMath::Abs(fZmixture[i] - (mix->GetZmixt())[i]) > 1E-3) + return kFALSE; + if (TMath::Abs(fAmixture[i] - (mix->GetAmixt())[i]) > 1E-3) + return kFALSE; + if (TMath::Abs(fWeights[i] - (mix->GetWmixt())[i]) > 1E-3) + return kFALSE; } return kTRUE; } @@ -1124,18 +1189,20 @@ Bool_t TGeoMixture::IsEq(const TGeoMaterial *other) const void TGeoMixture::Print(const Option_t * /*option*/) const { - printf("Mixture %s %s Aeff=%g Zeff=%g rho=%g radlen=%g intlen=%g index=%i\n", GetName(), GetTitle(), - fA,fZ,fDensity, fRadLen, fIntLen, fIndex); - for (Int_t i=0; iAt(i)) { printf(" Element #%i : %s Z=%6.2f A=%6.2f w=%6.3f\n", i, GetElement(i)->GetName(), fZmixture[i], fAmixture[i], fWeights[i]); continue; } - if (fNatoms) printf(" Element #%i : %s Z=%6.2f A=%6.2f w=%6.3f natoms=%d\n", i, GetElement(i)->GetName(),fZmixture[i], - fAmixture[i], fWeights[i], fNatoms[i]); - else printf(" Element #%i : %s Z=%6.2f A=%6.2f w=%6.3f\n", i, GetElement(i)->GetName(),fZmixture[i], - fAmixture[i], fWeights[i]); + if (fNatoms) + printf(" Element #%i : %s Z=%6.2f A=%6.2f w=%6.3f natoms=%d\n", i, GetElement(i)->GetName(), fZmixture[i], + fAmixture[i], fWeights[i], fNatoms[i]); + else + printf(" Element #%i : %s Z=%6.2f A=%6.2f w=%6.3f\n", i, GetElement(i)->GetName(), fZmixture[i], + fAmixture[i], fWeights[i]); } } @@ -1144,15 +1211,17 @@ void TGeoMixture::Print(const Option_t * /*option*/) const void TGeoMixture::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TestBit(TGeoMaterial::kMatSavePrimitive)) return; + if (TestBit(TGeoMaterial::kMatSavePrimitive)) + return; const char *name = GetPointerName(); out << "// Mixture: " << GetName() << std::endl; out << " nel = " << fNelements << ";" << std::endl; out << " density = " << fDensity << ";" << std::endl; out << " auto " << name << " = new TGeoMixture(\"" << GetName() << "\", nel, density);" << std::endl; - for (Int_t i=0; iGetName() << std::endl; + out << " a = " << fAmixture[i] << "; z = " << fZmixture[i] << "; w = " << fWeights[i] << "; // " + << el->GetName() << std::endl; out << " " << name << "->DefineElement(" << i << ",a,z,w);" << std::endl; } out << " " << name << "->SetIndex(" << GetIndex() << ");" << std::endl; @@ -1169,47 +1238,50 @@ TGeoMaterial *TGeoMixture::DecayMaterial(Double_t time, Double_t precision) TObjArray *pop = new TObjArray(); FillMaterialEvolution(pop, precision); Int_t ncomp = pop->GetEntriesFast(); - if (!ncomp) return this; + if (!ncomp) + return this; TGeoElement *elem; TGeoElementRN *el; Double_t *weight = new Double_t[ncomp]; Double_t amed = 0.; Int_t i, j; - for (i=0; iAt(i); if (!elem->IsRadioNuclide()) { j = fElements->IndexOf(elem); - weight[i] = fWeights[j]*fAmixture[0]/fWeights[0]; + weight[i] = fWeights[j] * fAmixture[0] / fWeights[0]; } else { - el = (TGeoElementRN*)elem; + el = (TGeoElementRN *)elem; weight[i] = el->Ratio()->Concentration(time) * el->A(); } amed += weight[i]; } - Double_t rho = fDensity * fWeights[0] * amed/fAmixture[0]; + Double_t rho = fDensity * fWeights[0] * amed / fAmixture[0]; TGeoMixture *mix = 0; Int_t ncomp1 = ncomp; - for (i=0; iAt(0); - delete [] weight; + delete[] weight; delete pop; - if (ncomp1==1) return new TGeoMaterial(TString::Format("%s-evol",GetName()), el, rho); + if (ncomp1 == 1) + return new TGeoMaterial(TString::Format("%s-evol", GetName()), el, rho); return NULL; } - mix = new TGeoMixture(TString::Format("%s-evol",GetName()), ncomp, rho); - for (i=0; iAt(i); mix->AddElement(el, weight[i]); } - delete [] weight; + delete[] weight; delete pop; return mix; } @@ -1247,16 +1319,17 @@ void TGeoMixture::FillMaterialEvolution(TObjArray *population, Double_t precisio TGeoElement *elem; TGeoElementRN *elemrn; TIter next(table->GetElementsRN()); - while ((elemrn=(TGeoElementRN*)next())) elemrn->ResetRatio(); + while ((elemrn = (TGeoElementRN *)next())) + elemrn->ResetRatio(); Double_t factor; - for (Int_t i=0; iIsRadioNuclide()) { population->Add(elem); continue; } - elemrn = (TGeoElementRN*)elem; - factor = fWeights[i]*fAmixture[0]/(fWeights[0]*fAmixture[i]); + elemrn = (TGeoElementRN *)elem; + factor = fWeights[i] * fAmixture[0] / (fWeights[0] * fAmixture[i]); elemrn->FillPopulation(population, precision, factor); } } @@ -1269,9 +1342,9 @@ void TGeoMixture::FillMaterialEvolution(TObjArray *population, Double_t precisio Double_t TGeoMaterial::ScreenFactor(Double_t z) { - const Double_t al183= 5.20948 , al1440 = 7.27239; - Double_t alz = TMath::Log(z)/3.; - Double_t factor = (al1440 - 2*alz) / (al183 - alz - TGeoMaterial::Coulomb(z)); + const Double_t al183 = 5.20948, al1440 = 7.27239; + Double_t alz = TMath::Log(z) / 3.; + Double_t factor = (al1440 - 2 * alz) / (al183 - alz - TGeoMaterial::Coulomb(z)); return factor; } @@ -1280,18 +1353,19 @@ Double_t TGeoMaterial::ScreenFactor(Double_t z) void TGeoMixture::ComputeDerivedQuantities() { - const Double_t Na = (TGeoManager::GetDefaultUnits()==TGeoManager::kRootUnits) - ? TGeoUnit::Avogadro : TGeant4Unit::Avogadro; + const Double_t Na = + (TGeoManager::GetDefaultUnits() == TGeoManager::kRootUnits) ? TGeoUnit::Avogadro : TGeant4Unit::Avogadro; - if ( fVecNbOfAtomsPerVolume ) delete [] fVecNbOfAtomsPerVolume; + if (fVecNbOfAtomsPerVolume) + delete[] fVecNbOfAtomsPerVolume; fVecNbOfAtomsPerVolume = new Double_t[fNelements]; // Formula taken from G4Material.cxx L312 double sumweights = 0; - for (Int_t i=0; iAt(i))->A(); + fVecNbOfAtomsPerVolume[i] = Na * fDensity * fWeights[i] / ((TGeoElement *)fElements->At(i))->A(); } if (TMath::Abs(sumweights - 1) > 0.001) Warning("ComputeDerivedQuantities", "Mixture %s: sum of weights is: %g", GetName(), sumweights); @@ -1299,17 +1373,16 @@ void TGeoMixture::ComputeDerivedQuantities() ComputeNuclearInterLength(); } - //////////////////////////////////////////////////////////////////////////////// /// Compute Radiation Length based on Geant4 formula void TGeoMixture::ComputeRadiationLength() { // Formula taken from G4Material.cxx L556 - Double_t radinv = 0.0 ; + Double_t radinv = 0.0; // GetfRadTsai is in units of cm2 due to ::alpha_rcl2. Correction must be applied to end up in TGeo cm. Double_t denom = (TGeoManager::GetDefaultUnits() == TGeoManager::kRootUnits) ? TGeoUnit::cm2 : TGeant4Unit::cm2; - for (Int_t i=0;iAt(i))->GetfRadTsai() / denom; } fRadLen = (radinv <= 0.0 ? DBL_MAX : 1.0 / radinv); @@ -1323,12 +1396,12 @@ void TGeoMixture::ComputeNuclearInterLength() { // Formula taken from G4Material.cxx L567 constexpr Double_t lambda0 = 35. * TGeoUnit::g / TGeoUnit::cm2; // [g/cm^2] - const Double_t twothird = 2.0/3.0; + const Double_t twothird = 2.0 / 3.0; Double_t NILinv = 0.0; - for (Int_t i=0; i(((TGeoElement *)fElements->At(i))->Z() + 0.5); - Double_t A = ((TGeoElement*)fElements->At(i))->Neff(); - if(1 == Z) { + Double_t A = ((TGeoElement *)fElements->At(i))->Neff(); + if (1 == Z) { NILinv += fVecNbOfAtomsPerVolume[i] * A; } else { NILinv += fVecNbOfAtomsPerVolume[i] * TMath::Exp(twothird * TMath::Log(A)); diff --git a/geom/geom/src/TGeoMatrix.cxx b/geom/geom/src/TGeoMatrix.cxx index 5d2ed066152e0..00d4e14295cab 100644 --- a/geom/geom/src/TGeoMatrix.cxx +++ b/geom/geom/src/TGeoMatrix.cxx @@ -218,8 +218,8 @@ A generic singleton matrix representing a identity transformation #include "TMath.h" TGeoIdentity *gGeoIdentity = nullptr; -const Int_t kN3 = 3*sizeof(Double_t); -const Int_t kN9 = 9*sizeof(Double_t); +const Int_t kN3 = 3 * sizeof(Double_t); +const Int_t kN9 = 9 * sizeof(Double_t); // statics and globals @@ -230,14 +230,13 @@ ClassImp(TGeoMatrix); TGeoMatrix::TGeoMatrix() { - ResetBit(kGeoMatrixBits); + ResetBit(kGeoMatrixBits); } //////////////////////////////////////////////////////////////////////////////// /// copy constructor -TGeoMatrix::TGeoMatrix(const TGeoMatrix &other) - :TNamed(other) +TGeoMatrix::TGeoMatrix(const TGeoMatrix &other) : TNamed(other) { ResetBit(kGeoRegistered); } @@ -245,10 +244,7 @@ TGeoMatrix::TGeoMatrix(const TGeoMatrix &other) //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoMatrix::TGeoMatrix(const char *name) - :TNamed(name, "") -{ -} +TGeoMatrix::TGeoMatrix(const char *name) : TNamed(name, "") {} //////////////////////////////////////////////////////////////////////////////// /// Destructor @@ -268,11 +264,15 @@ TGeoMatrix::~TGeoMatrix() Bool_t TGeoMatrix::IsRotAboutZ() const { - if (IsIdentity()) return kTRUE; + if (IsIdentity()) + return kTRUE; const Double_t *rot = GetRotationMatrix(); - if (TMath::Abs(rot[6])>1E-9) return kFALSE; - if (TMath::Abs(rot[7])>1E-9) return kFALSE; - if ((1.-TMath::Abs(rot[8]))>1E-9) return kFALSE; + if (TMath::Abs(rot[6]) > 1E-9) + return kFALSE; + if (TMath::Abs(rot[7]) > 1E-9) + return kFALSE; + if ((1. - TMath::Abs(rot[8])) > 1E-9) + return kFALSE; return kTRUE; } @@ -281,10 +281,13 @@ Bool_t TGeoMatrix::IsRotAboutZ() const Int_t TGeoMatrix::GetByteCount() const { - Int_t count = 4+28+strlen(GetName())+strlen(GetTitle()); // fId + TNamed - if (IsTranslation()) count += 12; - if (IsScale()) count += 12; - if (IsCombi() || IsGeneral()) count += 4 + 36; + Int_t count = 4 + 28 + strlen(GetName()) + strlen(GetTitle()); // fId + TNamed + if (IsTranslation()) + count += 12; + if (IsScale()) + count += 12; + if (IsCombi() || IsGeneral()) + count += 4 + 36; return count; } @@ -315,9 +318,9 @@ void TGeoMatrix::GetHomogenousMatrix(Double_t *hmat) const { Double_t *hmatrix = hmat; const Double_t *mat = GetRotationMatrix(); - for (Int_t i=0; i<3; i++) { + for (Int_t i = 0; i < 3; i++) { memcpy(hmatrix, mat, kN3); - mat += 3; + mat += 3; hmatrix += 3; *hmatrix = 0.0; hmatrix++; @@ -325,9 +328,9 @@ void TGeoMatrix::GetHomogenousMatrix(Double_t *hmat) const memcpy(hmatrix, GetTranslation(), kN3); hmatrix = hmat; if (IsScale()) { - for (Int_t i=0; i<3; i++) { + for (Int_t i = 0; i < 3; i++) { *hmatrix *= GetScale()[i]; - hmatrix += 5; + hmatrix += 5; } } hmatrix[15] = 1.; @@ -345,15 +348,13 @@ void TGeoMatrix::LocalToMaster(const Double_t *local, Double_t *master) const Int_t i; const Double_t *tr = GetTranslation(); if (!IsRotation()) { - for (i=0; i<3; i++) master[i] = tr[i] + local[i]; + for (i = 0; i < 3; i++) + master[i] = tr[i] + local[i]; return; } const Double_t *rot = GetRotationMatrix(); - for (i=0; i<3; i++) { - master[i] = tr[i] - + local[0]*rot[3*i] - + local[1]*rot[3*i+1] - + local[2]*rot[3*i+2]; + for (i = 0; i < 3; i++) { + master[i] = tr[i] + local[0] * rot[3 * i] + local[1] * rot[3 * i + 1] + local[2] * rot[3 * i + 2]; } } @@ -367,10 +368,8 @@ void TGeoMatrix::LocalToMasterVect(const Double_t *local, Double_t *master) cons return; } const Double_t *rot = GetRotationMatrix(); - for (Int_t i=0; i<3; i++) { - master[i] = local[0]*rot[3*i] - + local[1]*rot[3*i+1] - + local[2]*rot[3*i+2]; + for (Int_t i = 0; i < 3; i++) { + master[i] = local[0] * rot[3 * i] + local[1] * rot[3 * i + 1] + local[2] * rot[3 * i + 2]; } } @@ -385,18 +384,16 @@ void TGeoMatrix::LocalToMasterBomb(const Double_t *local, Double_t *master) cons } Int_t i; const Double_t *tr = GetTranslation(); - Double_t bombtr[3] = {0.,0.,0.}; + Double_t bombtr[3] = {0., 0., 0.}; gGeoManager->BombTranslation(tr, &bombtr[0]); if (!IsRotation()) { - for (i=0; i<3; i++) master[i] = bombtr[i] + local[i]; + for (i = 0; i < 3; i++) + master[i] = bombtr[i] + local[i]; return; } const Double_t *rot = GetRotationMatrix(); - for (i=0; i<3; i++) { - master[i] = bombtr[i] - + local[0]*rot[3*i] - + local[1]*rot[3*i+1] - + local[2]*rot[3*i+2]; + for (i = 0; i < 3; i++) { + master[i] = bombtr[i] + local[0] * rot[3 * i] + local[1] * rot[3 * i + 1] + local[2] * rot[3 * i + 2]; } } @@ -409,10 +406,10 @@ void TGeoMatrix::MasterToLocal(const Double_t *master, Double_t *local) const memcpy(local, master, kN3); return; } - const Double_t *tr = GetTranslation(); - Double_t mt0 = master[0]-tr[0]; - Double_t mt1 = master[1]-tr[1]; - Double_t mt2 = master[2]-tr[2]; + const Double_t *tr = GetTranslation(); + Double_t mt0 = master[0] - tr[0]; + Double_t mt1 = master[1] - tr[1]; + Double_t mt2 = master[2] - tr[2]; if (!IsRotation()) { local[0] = mt0; local[1] = mt1; @@ -420,9 +417,9 @@ void TGeoMatrix::MasterToLocal(const Double_t *master, Double_t *local) const return; } const Double_t *rot = GetRotationMatrix(); - local[0] = mt0*rot[0] + mt1*rot[3] + mt2*rot[6]; - local[1] = mt0*rot[1] + mt1*rot[4] + mt2*rot[7]; - local[2] = mt0*rot[2] + mt1*rot[5] + mt2*rot[8]; + local[0] = mt0 * rot[0] + mt1 * rot[3] + mt2 * rot[6]; + local[1] = mt0 * rot[1] + mt1 * rot[4] + mt2 * rot[7]; + local[2] = mt0 * rot[2] + mt1 * rot[5] + mt2 * rot[8]; } //////////////////////////////////////////////////////////////////////////////// @@ -435,10 +432,8 @@ void TGeoMatrix::MasterToLocalVect(const Double_t *master, Double_t *local) cons return; } const Double_t *rot = GetRotationMatrix(); - for (Int_t i=0; i<3; i++) { - local[i] = master[0]*rot[i] - + master[1]*rot[i+3] - + master[2]*rot[i+6]; + for (Int_t i = 0; i < 3; i++) { + local[i] = master[0] * rot[i] + master[1] * rot[i + 3] + master[2] * rot[i + 6]; } } @@ -452,18 +447,18 @@ void TGeoMatrix::MasterToLocalBomb(const Double_t *master, Double_t *local) cons return; } const Double_t *tr = GetTranslation(); - Double_t bombtr[3] = {0.,0.,0.}; + Double_t bombtr[3] = {0., 0., 0.}; Int_t i; gGeoManager->UnbombTranslation(tr, &bombtr[0]); if (!IsRotation()) { - for (i=0; i<3; i++) local[i] = master[i]-bombtr[i]; + for (i = 0; i < 3; i++) + local[i] = master[i] - bombtr[i]; return; } const Double_t *rot = GetRotationMatrix(); - for (i=0; i<3; i++) { - local[i] = (master[0]-bombtr[0])*rot[i] - + (master[1]-bombtr[1])*rot[i+3] - + (master[2]-bombtr[2])*rot[i+6]; + for (i = 0; i < 3; i++) { + local[i] = + (master[0] - bombtr[0]) * rot[i] + (master[1] - bombtr[1]) * rot[i + 3] + (master[2] - bombtr[2]) * rot[i + 6]; } } @@ -472,9 +467,10 @@ void TGeoMatrix::MasterToLocalBomb(const Double_t *master, Double_t *local) cons void TGeoMatrix::Normalize(Double_t *vect) { - Double_t normfactor = vect[0]*vect[0] + vect[1]*vect[1] + vect[2]*vect[2]; - if (normfactor <= 1E-10) return; - normfactor = 1./TMath::Sqrt(normfactor); + Double_t normfactor = vect[0] * vect[0] + vect[1] * vect[1] + vect[2] * vect[2]; + if (normfactor <= 1E-10) + return; + normfactor = 1. / TMath::Sqrt(normfactor); vect[0] *= normfactor; vect[1] *= normfactor; vect[2] *= normfactor; @@ -486,15 +482,15 @@ void TGeoMatrix::Normalize(Double_t *vect) void TGeoMatrix::Print(Option_t *) const { const Double_t *rot = GetRotationMatrix(); - const Double_t *tr = GetTranslation(); - printf("matrix %s - tr=%d rot=%d refl=%d scl=%d shr=%d reg=%d own=%d\n", GetName(),(Int_t)IsTranslation(), + const Double_t *tr = GetTranslation(); + printf("matrix %s - tr=%d rot=%d refl=%d scl=%d shr=%d reg=%d own=%d\n", GetName(), (Int_t)IsTranslation(), (Int_t)IsRotation(), (Int_t)IsReflection(), (Int_t)IsScale(), (Int_t)IsShared(), (Int_t)IsRegistered(), (Int_t)IsOwned()); printf("%10.6f%12.6f%12.6f Tx = %10.6f\n", rot[0], rot[1], rot[2], tr[0]); printf("%10.6f%12.6f%12.6f Ty = %10.6f\n", rot[3], rot[4], rot[5], tr[1]); printf("%10.6f%12.6f%12.6f Tz = %10.6f\n", rot[6], rot[7], rot[8], tr[2]); if (IsScale()) { - const Double_t *scl = GetScale(); + const Double_t *scl = GetScale(); printf("Sx=%10.6fSy=%12.6fSz=%12.6f\n", scl[0], scl[1], scl[2]); } } @@ -502,23 +498,17 @@ void TGeoMatrix::Print(Option_t *) const //////////////////////////////////////////////////////////////////////////////// /// Multiply by a reflection respect to YZ. -void TGeoMatrix::ReflectX(Bool_t, Bool_t) -{ -} +void TGeoMatrix::ReflectX(Bool_t, Bool_t) {} //////////////////////////////////////////////////////////////////////////////// /// Multiply by a reflection respect to ZX. -void TGeoMatrix::ReflectY(Bool_t, Bool_t) -{ -} +void TGeoMatrix::ReflectY(Bool_t, Bool_t) {} //////////////////////////////////////////////////////////////////////////////// /// Multiply by a reflection respect to XY. -void TGeoMatrix::ReflectZ(Bool_t, Bool_t) -{ -} +void TGeoMatrix::ReflectZ(Bool_t, Bool_t) {} //////////////////////////////////////////////////////////////////////////////// /// Register the matrix in the current manager, which will become the owner. @@ -548,17 +538,25 @@ void TGeoMatrix::RegisterYourself() void TGeoMatrix::SetDefaultName() { - if (!gGeoManager) return; - if (strlen(GetName())) return; + if (!gGeoManager) + return; + if (strlen(GetName())) + return; char type = 'n'; - if (IsTranslation()) type = 't'; - if (IsRotation()) type = 'r'; - if (IsScale()) type = 's'; - if (IsCombi()) type = 'c'; - if (IsGeneral()) type = 'g'; + if (IsTranslation()) + type = 't'; + if (IsRotation()) + type = 'r'; + if (IsScale()) + type = 's'; + if (IsCombi()) + type = 'c'; + if (IsGeneral()) + type = 'g'; TObjArray *matrices = gGeoManager->GetListOfMatrices(); Int_t index = 0; - if (matrices) index =matrices->GetEntriesFast() - 1; + if (matrices) + index = matrices->GetEntriesFast() - 1; TString name = TString::Format("%c%d", type, index); SetName(name); } @@ -578,14 +576,14 @@ ClassImp(TGeoTranslation); TGeoTranslation::TGeoTranslation() { - for (Int_t i=0; i<3; i++) fTranslation[i] = 0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0; } //////////////////////////////////////////////////////////////////////////////// /// Copy ctor. -TGeoTranslation::TGeoTranslation(const TGeoTranslation &other) - :TGeoMatrix(other) +TGeoTranslation::TGeoTranslation(const TGeoTranslation &other) : TGeoMatrix(other) { SetTranslation(other); } @@ -593,8 +591,7 @@ TGeoTranslation::TGeoTranslation(const TGeoTranslation &other) //////////////////////////////////////////////////////////////////////////////// /// Ctor. based on a general matrix -TGeoTranslation::TGeoTranslation(const TGeoMatrix &other) - :TGeoMatrix(other) +TGeoTranslation::TGeoTranslation(const TGeoMatrix &other) : TGeoMatrix(other) { ResetBit(kGeoRotation); ResetBit(kGeoScale); @@ -604,33 +601,34 @@ TGeoTranslation::TGeoTranslation(const TGeoMatrix &other) //////////////////////////////////////////////////////////////////////////////// /// Default constructor defining the translation -TGeoTranslation::TGeoTranslation(Double_t dx, Double_t dy, Double_t dz) - :TGeoMatrix("") +TGeoTranslation::TGeoTranslation(Double_t dx, Double_t dy, Double_t dz) : TGeoMatrix("") { - if (dx || dy || dz) SetBit(kGeoTranslation); + if (dx || dy || dz) + SetBit(kGeoTranslation); SetTranslation(dx, dy, dz); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor defining the translation -TGeoTranslation::TGeoTranslation(const char *name, Double_t dx, Double_t dy, Double_t dz) - :TGeoMatrix(name) +TGeoTranslation::TGeoTranslation(const char *name, Double_t dx, Double_t dy, Double_t dz) : TGeoMatrix(name) { - if (dx || dy || dz) SetBit(kGeoTranslation); + if (dx || dy || dz) + SetBit(kGeoTranslation); SetTranslation(dx, dy, dz); } //////////////////////////////////////////////////////////////////////////////// /// Assignment from a general matrix -TGeoTranslation& TGeoTranslation::operator = (const TGeoMatrix &matrix) +TGeoTranslation &TGeoTranslation::operator=(const TGeoMatrix &matrix) { - if (&matrix == this) return *this; + if (&matrix == this) + return *this; Bool_t registered = TestBit(kGeoRegistered); TNamed::operator=(matrix); SetTranslation(matrix); - SetBit(kGeoRegistered,registered); + SetBit(kGeoRegistered, registered); ResetBit(kGeoRotation); ResetBit(kGeoScale); return *this; @@ -645,7 +643,8 @@ TGeoTranslation &TGeoTranslation::operator*=(const TGeoTranslation &right) fTranslation[0] += tr[0]; fTranslation[1] += tr[1]; fTranslation[2] += tr[2]; - if (!IsTranslation()) SetBit(kGeoTranslation, right.IsTranslation()); + if (!IsTranslation()) + SetBit(kGeoTranslation, right.IsTranslation()); return *this; } @@ -666,13 +665,15 @@ TGeoHMatrix TGeoTranslation::operator*(const TGeoMatrix &right) const //////////////////////////////////////////////////////////////////////////////// /// Is-equal operator -Bool_t TGeoTranslation::operator ==(const TGeoTranslation &other) const +Bool_t TGeoTranslation::operator==(const TGeoTranslation &other) const { - if (&other == this) return kTRUE; + if (&other == this) + return kTRUE; const Double_t *tr = GetTranslation(); const Double_t *otr = other.GetTranslation(); - for (auto i=0; i<3; i++) - if (TMath::Abs(tr[i]-otr[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 3; i++) + if (TMath::Abs(tr[i] - otr[i]) > 1.E-10) + return kFALSE; return kTRUE; } @@ -698,7 +699,7 @@ TGeoHMatrix TGeoTranslation::Inverse() const void TGeoTranslation::Add(const TGeoTranslation *other) { const Double_t *trans = other->GetTranslation(); - for (Int_t i=0; i<3; i++) + for (Int_t i = 0; i < 3; i++) fTranslation[i] += trans[i]; } @@ -741,7 +742,7 @@ void TGeoTranslation::RotateZ(Double_t /*angle*/) void TGeoTranslation::Subtract(const TGeoTranslation *other) { const Double_t *trans = other->GetTranslation(); - for (Int_t i=0; i<3; i++) + for (Int_t i = 0; i < 3; i++) fTranslation[i] -= trans[i]; } @@ -753,8 +754,10 @@ void TGeoTranslation::SetTranslation(Double_t dx, Double_t dy, Double_t dz) fTranslation[0] = dx; fTranslation[1] = dy; fTranslation[2] = dz; - if (dx || dy || dz) SetBit(kGeoTranslation); - else ResetBit(kGeoTranslation); + if (dx || dy || dz) + SetBit(kGeoTranslation); + else + ResetBit(kGeoTranslation); } //////////////////////////////////////////////////////////////////////////////// @@ -773,7 +776,7 @@ void TGeoTranslation::SetTranslation(const TGeoMatrix &other) void TGeoTranslation::LocalToMaster(const Double_t *local, Double_t *master) const { const Double_t *tr = GetTranslation(); - for (Int_t i=0; i<3; i++) + for (Int_t i = 0; i < 3; i++) master[i] = tr[i] + local[i]; } @@ -791,9 +794,9 @@ void TGeoTranslation::LocalToMasterVect(const Double_t *local, Double_t *master) void TGeoTranslation::LocalToMasterBomb(const Double_t *local, Double_t *master) const { const Double_t *tr = GetTranslation(); - Double_t bombtr[3] = {0.,0.,0.}; + Double_t bombtr[3] = {0., 0., 0.}; gGeoManager->BombTranslation(tr, &bombtr[0]); - for (Int_t i=0; i<3; i++) + for (Int_t i = 0; i < 3; i++) master[i] = bombtr[i] + local[i]; } @@ -803,8 +806,8 @@ void TGeoTranslation::LocalToMasterBomb(const Double_t *local, Double_t *master) void TGeoTranslation::MasterToLocal(const Double_t *master, Double_t *local) const { const Double_t *tr = GetTranslation(); - for (Int_t i=0; i<3; i++) - local[i] = master[i]-tr[i]; + for (Int_t i = 0; i < 3; i++) + local[i] = master[i] - tr[i]; } //////////////////////////////////////////////////////////////////////////////// @@ -821,10 +824,10 @@ void TGeoTranslation::MasterToLocalVect(const Double_t *master, Double_t *local) void TGeoTranslation::MasterToLocalBomb(const Double_t *master, Double_t *local) const { const Double_t *tr = GetTranslation(); - Double_t bombtr[3] = {0.,0.,0.}; + Double_t bombtr[3] = {0., 0., 0.}; gGeoManager->UnbombTranslation(tr, &bombtr[0]); - for (Int_t i=0; i<3; i++) - local[i] = master[i]-bombtr[i]; + for (Int_t i = 0; i < 3; i++) + local[i] = master[i] - bombtr[i]; } //////////////////////////////////////////////////////////////////////////////// @@ -832,12 +835,14 @@ void TGeoTranslation::MasterToLocalBomb(const Double_t *master, Double_t *local) void TGeoTranslation::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TestBit(kGeoSavePrimitive)) return; + if (TestBit(kGeoSavePrimitive)) + return; out << " // Translation: " << GetName() << std::endl; out << " dx = " << fTranslation[0] << ";" << std::endl; out << " dy = " << fTranslation[1] << ";" << std::endl; out << " dz = " << fTranslation[2] << ";" << std::endl; - out << " TGeoTranslation *" << GetPointerName() << " = new TGeoTranslation(\"" << GetName() << "\",dx,dy,dz);" << std::endl; + out << " TGeoTranslation *" << GetPointerName() << " = new TGeoTranslation(\"" << GetName() << "\",dx,dy,dz);" + << std::endl; TObject::SetBit(kGeoSavePrimitive); } @@ -854,17 +859,18 @@ ClassImp(TGeoRotation); TGeoRotation::TGeoRotation() { - for (Int_t i=0; i<9; i++) { - if (i%4) fRotationMatrix[i] = 0; - else fRotationMatrix[i] = 1.0; + for (Int_t i = 0; i < 9; i++) { + if (i % 4) + fRotationMatrix[i] = 0; + else + fRotationMatrix[i] = 1.0; } } //////////////////////////////////////////////////////////////////////////////// /// Copy ctor. -TGeoRotation::TGeoRotation(const TGeoRotation &other) - :TGeoMatrix(other) +TGeoRotation::TGeoRotation(const TGeoRotation &other) : TGeoMatrix(other) { SetRotation(other); } @@ -872,8 +878,7 @@ TGeoRotation::TGeoRotation(const TGeoRotation &other) //////////////////////////////////////////////////////////////////////////////// /// Copy ctor. -TGeoRotation::TGeoRotation(const TGeoMatrix &other) - :TGeoMatrix(other) +TGeoRotation::TGeoRotation(const TGeoMatrix &other) : TGeoMatrix(other) { ResetBit(kGeoTranslation); ResetBit(kGeoScale); @@ -883,12 +888,13 @@ TGeoRotation::TGeoRotation(const TGeoMatrix &other) //////////////////////////////////////////////////////////////////////////////// /// Named rotation constructor -TGeoRotation::TGeoRotation(const char *name) - :TGeoMatrix(name) +TGeoRotation::TGeoRotation(const char *name) : TGeoMatrix(name) { - for (Int_t i=0; i<9; i++) { - if (i%4) fRotationMatrix[i] = 0; - else fRotationMatrix[i] = 1.0; + for (Int_t i = 0; i < 9; i++) { + if (i % 4) + fRotationMatrix[i] = 0; + else + fRotationMatrix[i] = 1.0; } } @@ -898,8 +904,7 @@ TGeoRotation::TGeoRotation(const char *name) /// second, psi is the rotation angle about new Z and is done third. All angles are in /// degrees. -TGeoRotation::TGeoRotation(const char *name, Double_t phi, Double_t theta, Double_t psi) - :TGeoMatrix(name) +TGeoRotation::TGeoRotation(const char *name, Double_t phi, Double_t theta, Double_t psi) : TGeoMatrix(name) { SetAngles(phi, theta, psi); } @@ -914,7 +919,7 @@ TGeoRotation::TGeoRotation(const char *name, Double_t phi, Double_t theta, Doubl TGeoRotation::TGeoRotation(const char *name, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3) - :TGeoMatrix(name) + : TGeoMatrix(name) { SetAngles(theta1, phi1, theta2, phi2, theta3, phi3); } @@ -922,13 +927,14 @@ TGeoRotation::TGeoRotation(const char *name, Double_t theta1, Double_t phi1, Dou //////////////////////////////////////////////////////////////////////////////// /// Assignment from a general matrix -TGeoRotation& TGeoRotation::operator = (const TGeoMatrix &other) +TGeoRotation &TGeoRotation::operator=(const TGeoMatrix &other) { - if (&other == this) return *this; + if (&other == this) + return *this; Bool_t registered = TestBit(kGeoRegistered); TNamed::operator=(other); SetRotation(other); - SetBit(kGeoRegistered,registered); + SetBit(kGeoRegistered, registered); ResetBit(kGeoTranslation); ResetBit(kGeoScale); return *this; @@ -939,7 +945,8 @@ TGeoRotation& TGeoRotation::operator = (const TGeoMatrix &other) TGeoRotation &TGeoRotation::operator*=(const TGeoRotation &right) { - if (!right.IsRotation()) return *this; + if (!right.IsRotation()) + return *this; MultiplyBy(&right, true); return *this; } @@ -961,13 +968,15 @@ TGeoHMatrix TGeoRotation::operator*(const TGeoMatrix &right) const //////////////////////////////////////////////////////////////////////////////// /// Is-equal operator -Bool_t TGeoRotation::operator ==(const TGeoRotation &other) const +Bool_t TGeoRotation::operator==(const TGeoRotation &other) const { - if (&other == this) return kTRUE; + if (&other == this) + return kTRUE; const Double_t *rot = GetRotationMatrix(); const Double_t *orot = other.GetRotationMatrix(); - for (auto i=0; i<9; i++) - if (TMath::Abs(rot[i]-orot[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 9; i++) + if (TMath::Abs(rot[i] - orot[i]) > 1.E-10) + return kFALSE; return kTRUE; } @@ -1000,14 +1009,16 @@ Bool_t TGeoRotation::IsValid() const { const Double_t *r = fRotationMatrix; Double_t cij; - for (Int_t i=0; i<2; i++) { - for (Int_t j=i+1; j<3; j++) { + for (Int_t i = 0; i < 2; i++) { + for (Int_t j = i + 1; j < 3; j++) { // check columns - cij = TMath::Abs(r[i]*r[j]+r[i+3]*r[j+3]+r[i+6]*r[j+6]); - if (cij>1E-4) return kFALSE; + cij = TMath::Abs(r[i] * r[j] + r[i + 3] * r[j + 3] + r[i + 6] * r[j + 6]); + if (cij > 1E-4) + return kFALSE; // check rows - cij = TMath::Abs(r[3*i]*r[3*j]+r[3*i+1]*r[3*j+1]+r[3*i+2]*r[3*j+2]); - if (cij>1E-4) return kFALSE; + cij = TMath::Abs(r[3 * i] * r[3 * j] + r[3 * i + 1] * r[3 * j + 1] + r[3 * i + 2] * r[3 * j + 2]); + if (cij > 1E-4) + return kFALSE; } } return kTRUE; @@ -1018,7 +1029,7 @@ Bool_t TGeoRotation::IsValid() const void TGeoRotation::Clear(Option_t *) { - memcpy(fRotationMatrix,kIdentityMatrix,kN9); + memcpy(fRotationMatrix, kIdentityMatrix, kN9); ResetBit(kGeoRotation); } @@ -1043,8 +1054,10 @@ void TGeoRotation::FastRotZ(const Double_t *sincos) Double_t TGeoRotation::GetPhiRotation(Bool_t fixX) const { Double_t phi; - if (fixX) phi = 180.*TMath::ATan2(-fRotationMatrix[1],fRotationMatrix[4])/TMath::Pi(); - else phi = 180.*TMath::ATan2(fRotationMatrix[3], fRotationMatrix[0])/TMath::Pi(); + if (fixX) + phi = 180. * TMath::ATan2(-fRotationMatrix[1], fRotationMatrix[4]) / TMath::Pi(); + else + phi = 180. * TMath::ATan2(fRotationMatrix[3], fRotationMatrix[0]) / TMath::Pi(); return phi; } @@ -1054,10 +1067,8 @@ Double_t TGeoRotation::GetPhiRotation(Bool_t fixX) const void TGeoRotation::LocalToMaster(const Double_t *local, Double_t *master) const { const Double_t *rot = GetRotationMatrix(); - for (Int_t i=0; i<3; i++) { - master[i] = local[0]*rot[3*i] - + local[1]*rot[3*i+1] - + local[2]*rot[3*i+2]; + for (Int_t i = 0; i < 3; i++) { + master[i] = local[0] * rot[3 * i] + local[1] * rot[3 * i + 1] + local[2] * rot[3 * i + 2]; } } @@ -1067,10 +1078,8 @@ void TGeoRotation::LocalToMaster(const Double_t *local, Double_t *master) const void TGeoRotation::MasterToLocal(const Double_t *master, Double_t *local) const { const Double_t *rot = GetRotationMatrix(); - for (Int_t i=0; i<3; i++) { - local[i] = master[0]*rot[i] - + master[1]*rot[i+3] - + master[2]*rot[i+6]; + for (Int_t i = 0; i < 3; i++) { + local[i] = master[0] * rot[i] + master[1] * rot[i + 3] + master[2] * rot[i + 6]; } } @@ -1089,19 +1098,19 @@ TGeoMatrix *TGeoRotation::MakeClone() const void TGeoRotation::RotateX(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; v[0] = fRotationMatrix[0]; v[1] = fRotationMatrix[1]; v[2] = fRotationMatrix[2]; - v[3] = c*fRotationMatrix[3]-s*fRotationMatrix[6]; - v[4] = c*fRotationMatrix[4]-s*fRotationMatrix[7]; - v[5] = c*fRotationMatrix[5]-s*fRotationMatrix[8]; - v[6] = s*fRotationMatrix[3]+c*fRotationMatrix[6]; - v[7] = s*fRotationMatrix[4]+c*fRotationMatrix[7]; - v[8] = s*fRotationMatrix[5]+c*fRotationMatrix[8]; + v[3] = c * fRotationMatrix[3] - s * fRotationMatrix[6]; + v[4] = c * fRotationMatrix[4] - s * fRotationMatrix[7]; + v[5] = c * fRotationMatrix[5] - s * fRotationMatrix[8]; + v[6] = s * fRotationMatrix[3] + c * fRotationMatrix[6]; + v[7] = s * fRotationMatrix[4] + c * fRotationMatrix[7]; + v[8] = s * fRotationMatrix[5] + c * fRotationMatrix[8]; memcpy(fRotationMatrix, v, kN9); } @@ -1112,19 +1121,19 @@ void TGeoRotation::RotateX(Double_t angle) void TGeoRotation::RotateY(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*fRotationMatrix[0]+s*fRotationMatrix[6]; - v[1] = c*fRotationMatrix[1]+s*fRotationMatrix[7]; - v[2] = c*fRotationMatrix[2]+s*fRotationMatrix[8]; + v[0] = c * fRotationMatrix[0] + s * fRotationMatrix[6]; + v[1] = c * fRotationMatrix[1] + s * fRotationMatrix[7]; + v[2] = c * fRotationMatrix[2] + s * fRotationMatrix[8]; v[3] = fRotationMatrix[3]; v[4] = fRotationMatrix[4]; v[5] = fRotationMatrix[5]; - v[6] = -s*fRotationMatrix[0]+c*fRotationMatrix[6]; - v[7] = -s*fRotationMatrix[1]+c*fRotationMatrix[7]; - v[8] = -s*fRotationMatrix[2]+c*fRotationMatrix[8]; + v[6] = -s * fRotationMatrix[0] + c * fRotationMatrix[6]; + v[7] = -s * fRotationMatrix[1] + c * fRotationMatrix[7]; + v[8] = -s * fRotationMatrix[2] + c * fRotationMatrix[8]; memcpy(fRotationMatrix, v, kN9); } @@ -1135,21 +1144,21 @@ void TGeoRotation::RotateY(Double_t angle) void TGeoRotation::RotateZ(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*fRotationMatrix[0]-s*fRotationMatrix[3]; - v[1] = c*fRotationMatrix[1]-s*fRotationMatrix[4]; - v[2] = c*fRotationMatrix[2]-s*fRotationMatrix[5]; - v[3] = s*fRotationMatrix[0]+c*fRotationMatrix[3]; - v[4] = s*fRotationMatrix[1]+c*fRotationMatrix[4]; - v[5] = s*fRotationMatrix[2]+c*fRotationMatrix[5]; + v[0] = c * fRotationMatrix[0] - s * fRotationMatrix[3]; + v[1] = c * fRotationMatrix[1] - s * fRotationMatrix[4]; + v[2] = c * fRotationMatrix[2] - s * fRotationMatrix[5]; + v[3] = s * fRotationMatrix[0] + c * fRotationMatrix[3]; + v[4] = s * fRotationMatrix[1] + c * fRotationMatrix[4]; + v[5] = s * fRotationMatrix[2] + c * fRotationMatrix[5]; v[6] = fRotationMatrix[6]; v[7] = fRotationMatrix[7]; v[8] = fRotationMatrix[8]; - memcpy(&fRotationMatrix[0],v,kN9); + memcpy(&fRotationMatrix[0], v, kN9); } //////////////////////////////////////////////////////////////////////////////// @@ -1158,13 +1167,13 @@ void TGeoRotation::RotateZ(Double_t angle) void TGeoRotation::ReflectX(Bool_t leftside, Bool_t) { if (leftside) { - fRotationMatrix[0]=-fRotationMatrix[0]; - fRotationMatrix[1]=-fRotationMatrix[1]; - fRotationMatrix[2]=-fRotationMatrix[2]; + fRotationMatrix[0] = -fRotationMatrix[0]; + fRotationMatrix[1] = -fRotationMatrix[1]; + fRotationMatrix[2] = -fRotationMatrix[2]; } else { - fRotationMatrix[0]=-fRotationMatrix[0]; - fRotationMatrix[3]=-fRotationMatrix[3]; - fRotationMatrix[6]=-fRotationMatrix[6]; + fRotationMatrix[0] = -fRotationMatrix[0]; + fRotationMatrix[3] = -fRotationMatrix[3]; + fRotationMatrix[6] = -fRotationMatrix[6]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -1176,13 +1185,13 @@ void TGeoRotation::ReflectX(Bool_t leftside, Bool_t) void TGeoRotation::ReflectY(Bool_t leftside, Bool_t) { if (leftside) { - fRotationMatrix[3]=-fRotationMatrix[3]; - fRotationMatrix[4]=-fRotationMatrix[4]; - fRotationMatrix[5]=-fRotationMatrix[5]; + fRotationMatrix[3] = -fRotationMatrix[3]; + fRotationMatrix[4] = -fRotationMatrix[4]; + fRotationMatrix[5] = -fRotationMatrix[5]; } else { - fRotationMatrix[1]=-fRotationMatrix[1]; - fRotationMatrix[4]=-fRotationMatrix[4]; - fRotationMatrix[7]=-fRotationMatrix[7]; + fRotationMatrix[1] = -fRotationMatrix[1]; + fRotationMatrix[4] = -fRotationMatrix[4]; + fRotationMatrix[7] = -fRotationMatrix[7]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -1194,13 +1203,13 @@ void TGeoRotation::ReflectY(Bool_t leftside, Bool_t) void TGeoRotation::ReflectZ(Bool_t leftside, Bool_t) { if (leftside) { - fRotationMatrix[6]=-fRotationMatrix[6]; - fRotationMatrix[7]=-fRotationMatrix[7]; - fRotationMatrix[8]=-fRotationMatrix[8]; + fRotationMatrix[6] = -fRotationMatrix[6]; + fRotationMatrix[7] = -fRotationMatrix[7]; + fRotationMatrix[8] = -fRotationMatrix[8]; } else { - fRotationMatrix[2]=-fRotationMatrix[2]; - fRotationMatrix[5]=-fRotationMatrix[5]; - fRotationMatrix[8]=-fRotationMatrix[8]; + fRotationMatrix[2] = -fRotationMatrix[2]; + fRotationMatrix[5] = -fRotationMatrix[5]; + fRotationMatrix[8] = -fRotationMatrix[8]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -1211,14 +1220,16 @@ void TGeoRotation::ReflectZ(Bool_t leftside, Bool_t) void TGeoRotation::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TestBit(kGeoSavePrimitive)) return; + if (TestBit(kGeoSavePrimitive)) + return; out << " // Rotation: " << GetName() << std::endl; - Double_t th1,ph1,th2,ph2,th3,ph3; - GetAngles(th1,ph1,th2,ph2,th3,ph3); + Double_t th1, ph1, th2, ph2, th3, ph3; + GetAngles(th1, ph1, th2, ph2, th3, ph3); out << " thx = " << th1 << "; phx = " << ph1 << ";" << std::endl; out << " thy = " << th2 << "; phy = " << ph2 << ";" << std::endl; out << " thz = " << th3 << "; phz = " << ph3 << ";" << std::endl; - out << " TGeoRotation *" << GetPointerName() << " = new TGeoRotation(\"" << GetName() << "\",thx,phx,thy,phy,thz,phz);" << std::endl; + out << " TGeoRotation *" << GetPointerName() << " = new TGeoRotation(\"" << GetName() + << "\",thx,phx,thy,phy,thz,phz);" << std::endl; TObject::SetBit(kGeoSavePrimitive); } @@ -1239,74 +1250,88 @@ void TGeoRotation::SetRotation(const TGeoMatrix &other) void TGeoRotation::SetAngles(Double_t phi, Double_t theta, Double_t psi) { - Double_t degrad = TMath::Pi()/180.; - Double_t sinphi = TMath::Sin(degrad*phi); - Double_t cosphi = TMath::Cos(degrad*phi); - Double_t sinthe = TMath::Sin(degrad*theta); - Double_t costhe = TMath::Cos(degrad*theta); - Double_t sinpsi = TMath::Sin(degrad*psi); - Double_t cospsi = TMath::Cos(degrad*psi); - - fRotationMatrix[0] = cospsi*cosphi - costhe*sinphi*sinpsi; - fRotationMatrix[1] = -sinpsi*cosphi - costhe*sinphi*cospsi; - fRotationMatrix[2] = sinthe*sinphi; - fRotationMatrix[3] = cospsi*sinphi + costhe*cosphi*sinpsi; - fRotationMatrix[4] = -sinpsi*sinphi + costhe*cosphi*cospsi; - fRotationMatrix[5] = -sinthe*cosphi; - fRotationMatrix[6] = sinpsi*sinthe; - fRotationMatrix[7] = cospsi*sinthe; - fRotationMatrix[8] = costhe; - - if (!IsValid()) Error("SetAngles", "invalid rotation (Euler angles : phi=%f theta=%f psi=%f)",phi,theta,psi); + Double_t degrad = TMath::Pi() / 180.; + Double_t sinphi = TMath::Sin(degrad * phi); + Double_t cosphi = TMath::Cos(degrad * phi); + Double_t sinthe = TMath::Sin(degrad * theta); + Double_t costhe = TMath::Cos(degrad * theta); + Double_t sinpsi = TMath::Sin(degrad * psi); + Double_t cospsi = TMath::Cos(degrad * psi); + + fRotationMatrix[0] = cospsi * cosphi - costhe * sinphi * sinpsi; + fRotationMatrix[1] = -sinpsi * cosphi - costhe * sinphi * cospsi; + fRotationMatrix[2] = sinthe * sinphi; + fRotationMatrix[3] = cospsi * sinphi + costhe * cosphi * sinpsi; + fRotationMatrix[4] = -sinpsi * sinphi + costhe * cosphi * cospsi; + fRotationMatrix[5] = -sinthe * cosphi; + fRotationMatrix[6] = sinpsi * sinthe; + fRotationMatrix[7] = cospsi * sinthe; + fRotationMatrix[8] = costhe; + + if (!IsValid()) + Error("SetAngles", "invalid rotation (Euler angles : phi=%f theta=%f psi=%f)", phi, theta, psi); CheckMatrix(); } //////////////////////////////////////////////////////////////////////////////// /// Set matrix elements in the GEANT3 way -void TGeoRotation::SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, - Double_t theta3, Double_t phi3) -{ - Double_t degrad = TMath::Pi()/180.; - fRotationMatrix[0] = TMath::Cos(degrad*phi1)*TMath::Sin(degrad*theta1); - fRotationMatrix[3] = TMath::Sin(degrad*phi1)*TMath::Sin(degrad*theta1); - fRotationMatrix[6] = TMath::Cos(degrad*theta1); - fRotationMatrix[1] = TMath::Cos(degrad*phi2)*TMath::Sin(degrad*theta2); - fRotationMatrix[4] = TMath::Sin(degrad*phi2)*TMath::Sin(degrad*theta2); - fRotationMatrix[7] = TMath::Cos(degrad*theta2); - fRotationMatrix[2] = TMath::Cos(degrad*phi3)*TMath::Sin(degrad*theta3); - fRotationMatrix[5] = TMath::Sin(degrad*phi3)*TMath::Sin(degrad*theta3); - fRotationMatrix[8] = TMath::Cos(degrad*theta3); +void TGeoRotation::SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, + Double_t phi3) +{ + Double_t degrad = TMath::Pi() / 180.; + fRotationMatrix[0] = TMath::Cos(degrad * phi1) * TMath::Sin(degrad * theta1); + fRotationMatrix[3] = TMath::Sin(degrad * phi1) * TMath::Sin(degrad * theta1); + fRotationMatrix[6] = TMath::Cos(degrad * theta1); + fRotationMatrix[1] = TMath::Cos(degrad * phi2) * TMath::Sin(degrad * theta2); + fRotationMatrix[4] = TMath::Sin(degrad * phi2) * TMath::Sin(degrad * theta2); + fRotationMatrix[7] = TMath::Cos(degrad * theta2); + fRotationMatrix[2] = TMath::Cos(degrad * phi3) * TMath::Sin(degrad * theta3); + fRotationMatrix[5] = TMath::Sin(degrad * phi3) * TMath::Sin(degrad * theta3); + fRotationMatrix[8] = TMath::Cos(degrad * theta3); // do the trick to eliminate most of the floating point errors - for (Int_t i=0; i<9; i++) { - if (TMath::Abs(fRotationMatrix[i])<1E-15) fRotationMatrix[i] = 0; - if (TMath::Abs(fRotationMatrix[i]-1)<1E-15) fRotationMatrix[i] = 1; - if (TMath::Abs(fRotationMatrix[i]+1)<1E-15) fRotationMatrix[i] = -1; - } - if (!IsValid()) Error("SetAngles", "invalid rotation (G3 angles, th1=%f phi1=%f, th2=%f ph2=%f, th3=%f phi3=%f)", - theta1,phi1,theta2,phi2,theta3,phi3); + for (Int_t i = 0; i < 9; i++) { + if (TMath::Abs(fRotationMatrix[i]) < 1E-15) + fRotationMatrix[i] = 0; + if (TMath::Abs(fRotationMatrix[i] - 1) < 1E-15) + fRotationMatrix[i] = 1; + if (TMath::Abs(fRotationMatrix[i] + 1) < 1E-15) + fRotationMatrix[i] = -1; + } + if (!IsValid()) + Error("SetAngles", "invalid rotation (G3 angles, th1=%f phi1=%f, th2=%f ph2=%f, th3=%f phi3=%f)", theta1, phi1, + theta2, phi2, theta3, phi3); CheckMatrix(); } //////////////////////////////////////////////////////////////////////////////// /// Retrieve rotation angles -void TGeoRotation::GetAngles(Double_t &theta1, Double_t &phi1, Double_t &theta2, Double_t &phi2, - Double_t &theta3, Double_t &phi3) const -{ - Double_t raddeg = 180./TMath::Pi(); - theta1 = raddeg*TMath::ACos(fRotationMatrix[6]); - theta2 = raddeg*TMath::ACos(fRotationMatrix[7]); - theta3 = raddeg*TMath::ACos(fRotationMatrix[8]); - if (TMath::Abs(fRotationMatrix[0])<1E-6 && TMath::Abs(fRotationMatrix[3])<1E-6) phi1=0.; - else phi1 = raddeg*TMath::ATan2(fRotationMatrix[3],fRotationMatrix[0]); - if (phi1<0) phi1+=360.; - if (TMath::Abs(fRotationMatrix[1])<1E-6 && TMath::Abs(fRotationMatrix[4])<1E-6) phi2=0.; - else phi2 = raddeg*TMath::ATan2(fRotationMatrix[4],fRotationMatrix[1]); - if (phi2<0) phi2+=360.; - if (TMath::Abs(fRotationMatrix[2])<1E-6 && TMath::Abs(fRotationMatrix[5])<1E-6) phi3=0.; - else phi3 = raddeg*TMath::ATan2(fRotationMatrix[5],fRotationMatrix[2]); - if (phi3<0) phi3+=360.; +void TGeoRotation::GetAngles(Double_t &theta1, Double_t &phi1, Double_t &theta2, Double_t &phi2, Double_t &theta3, + Double_t &phi3) const +{ + Double_t raddeg = 180. / TMath::Pi(); + theta1 = raddeg * TMath::ACos(fRotationMatrix[6]); + theta2 = raddeg * TMath::ACos(fRotationMatrix[7]); + theta3 = raddeg * TMath::ACos(fRotationMatrix[8]); + if (TMath::Abs(fRotationMatrix[0]) < 1E-6 && TMath::Abs(fRotationMatrix[3]) < 1E-6) + phi1 = 0.; + else + phi1 = raddeg * TMath::ATan2(fRotationMatrix[3], fRotationMatrix[0]); + if (phi1 < 0) + phi1 += 360.; + if (TMath::Abs(fRotationMatrix[1]) < 1E-6 && TMath::Abs(fRotationMatrix[4]) < 1E-6) + phi2 = 0.; + else + phi2 = raddeg * TMath::ATan2(fRotationMatrix[4], fRotationMatrix[1]); + if (phi2 < 0) + phi2 += 360.; + if (TMath::Abs(fRotationMatrix[2]) < 1E-6 && TMath::Abs(fRotationMatrix[5]) < 1E-6) + phi3 = 0.; + else + phi3 = raddeg * TMath::ATan2(fRotationMatrix[5], fRotationMatrix[2]); + if (phi3 < 0) + phi3 += 360.; } //////////////////////////////////////////////////////////////////////////////// @@ -1316,19 +1341,21 @@ void TGeoRotation::GetAngles(Double_t &phi, Double_t &theta, Double_t &psi) cons { const Double_t *m = fRotationMatrix; // Check if theta is 0 or 180. - if (TMath::Abs(1.-TMath::Abs(m[8]))<1.e-9) { - theta = TMath::ACos(m[8])*TMath::RadToDeg(); - phi = TMath::ATan2(-m[8]*m[1],m[0])*TMath::RadToDeg(); + if (TMath::Abs(1. - TMath::Abs(m[8])) < 1.e-9) { + theta = TMath::ACos(m[8]) * TMath::RadToDeg(); + phi = TMath::ATan2(-m[8] * m[1], m[0]) * TMath::RadToDeg(); psi = 0.; // convention, phi+psi matters return; } // sin(theta) != 0 - phi = TMath::ATan2(m[2],-m[5]); + phi = TMath::ATan2(m[2], -m[5]); Double_t sphi = TMath::Sin(phi); - if (TMath::Abs(sphi)<1.e-9) theta = -TMath::ASin(m[5]/TMath::Cos(phi))*TMath::RadToDeg(); - else theta = TMath::ASin(m[2]/sphi)*TMath::RadToDeg(); + if (TMath::Abs(sphi) < 1.e-9) + theta = -TMath::ASin(m[5] / TMath::Cos(phi)) * TMath::RadToDeg(); + else + theta = TMath::ASin(m[2] / sphi) * TMath::RadToDeg(); phi *= TMath::RadToDeg(); - psi = TMath::ATan2(m[6],m[7])*TMath::RadToDeg(); + psi = TMath::ATan2(m[6], m[7]) * TMath::RadToDeg(); } //////////////////////////////////////////////////////////////////////////////// @@ -1336,13 +1363,12 @@ void TGeoRotation::GetAngles(Double_t &phi, Double_t &theta, Double_t &psi) cons Double_t TGeoRotation::Determinant() const { - Double_t - det = fRotationMatrix[0]*fRotationMatrix[4]*fRotationMatrix[8] + - fRotationMatrix[3]*fRotationMatrix[7]*fRotationMatrix[2] + - fRotationMatrix[6]*fRotationMatrix[1]*fRotationMatrix[5] - - fRotationMatrix[2]*fRotationMatrix[4]*fRotationMatrix[6] - - fRotationMatrix[5]*fRotationMatrix[7]*fRotationMatrix[0] - - fRotationMatrix[8]*fRotationMatrix[1]*fRotationMatrix[3]; + Double_t det = fRotationMatrix[0] * fRotationMatrix[4] * fRotationMatrix[8] + + fRotationMatrix[3] * fRotationMatrix[7] * fRotationMatrix[2] + + fRotationMatrix[6] * fRotationMatrix[1] * fRotationMatrix[5] - + fRotationMatrix[2] * fRotationMatrix[4] * fRotationMatrix[6] - + fRotationMatrix[5] * fRotationMatrix[7] * fRotationMatrix[0] - + fRotationMatrix[8] * fRotationMatrix[1] * fRotationMatrix[3]; return det; } @@ -1352,10 +1378,13 @@ Double_t TGeoRotation::Determinant() const void TGeoRotation::CheckMatrix() { - if (Determinant() < 0) SetBit(kGeoReflection); + if (Determinant() < 0) + SetBit(kGeoReflection); Double_t dd = fRotationMatrix[0] + fRotationMatrix[4] + fRotationMatrix[8] - 3.; - if (TMath::Abs(dd) < 1.E-12) ResetBit(kGeoRotation); - else SetBit(kGeoRotation); + if (TMath::Abs(dd) < 1.E-12) + ResetBit(kGeoRotation); + else + SetBit(kGeoRotation); } //////////////////////////////////////////////////////////////////////////////// @@ -1367,9 +1396,9 @@ void TGeoRotation::GetInverse(Double_t *invmat) const Error("GetInverse", "no place to store the inverse matrix"); return; } - for (Int_t i=0; i<3; i++) { - for (Int_t j=0; j<3; j++) { - invmat[3*i+j] = fRotationMatrix[3*j+i]; + for (Int_t i = 0; i < 3; i++) { + for (Int_t j = 0; j < 3; j++) { + invmat[3 * i + j] = fRotationMatrix[3 * j + i]; } } } @@ -1383,18 +1412,18 @@ void TGeoRotation::MultiplyBy(const TGeoRotation *rot, Bool_t after) { const Double_t *matleft, *matright; SetBit(kGeoRotation); - Double_t newmat[9] = {0}; + Double_t newmat[9] = {0}; if (after) { - matleft = &fRotationMatrix[0]; + matleft = &fRotationMatrix[0]; matright = rot->GetRotationMatrix(); } else { - matleft = rot->GetRotationMatrix(); + matleft = rot->GetRotationMatrix(); matright = &fRotationMatrix[0]; } - for (Int_t i=0; i<3; i++) { - for (Int_t j=0; j<3; j++) { - for (Int_t k=0; k<3; k++) { - newmat[3*i+j] += matleft[3*i+k] * matright[3*k+j]; + for (Int_t i = 0; i < 3; i++) { + for (Int_t j = 0; j < 3; j++) { + for (Int_t k = 0; k < 3; k++) { + newmat[3 * i + j] += matleft[3 * i + k] * matright[3 * k + j]; } } } @@ -1416,14 +1445,14 @@ ClassImp(TGeoScale); TGeoScale::TGeoScale() { SetBit(kGeoScale); - for (Int_t i=0; i<3; i++) fScale[i] = 1.; + for (Int_t i = 0; i < 3; i++) + fScale[i] = 1.; } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor -TGeoScale::TGeoScale(const TGeoScale &other) - :TGeoMatrix(other) +TGeoScale::TGeoScale(const TGeoScale &other) : TGeoMatrix(other) { SetScale(other); } @@ -1431,8 +1460,7 @@ TGeoScale::TGeoScale(const TGeoScale &other) //////////////////////////////////////////////////////////////////////////////// /// Ctor. based on a general matrix -TGeoScale::TGeoScale(const TGeoMatrix &other) - :TGeoMatrix(other) +TGeoScale::TGeoScale(const TGeoMatrix &other) : TGeoMatrix(other) { ResetBit(kGeoTranslation); ResetBit(kGeoRotation); @@ -1442,8 +1470,7 @@ TGeoScale::TGeoScale(const TGeoMatrix &other) //////////////////////////////////////////////////////////////////////////////// /// default constructor -TGeoScale::TGeoScale(Double_t sx, Double_t sy, Double_t sz) - :TGeoMatrix("") +TGeoScale::TGeoScale(Double_t sx, Double_t sy, Double_t sz) : TGeoMatrix("") { SetBit(kGeoScale); SetScale(sx, sy, sz); @@ -1452,8 +1479,7 @@ TGeoScale::TGeoScale(Double_t sx, Double_t sy, Double_t sz) //////////////////////////////////////////////////////////////////////////////// /// default constructor -TGeoScale::TGeoScale(const char *name, Double_t sx, Double_t sy, Double_t sz) - :TGeoMatrix(name) +TGeoScale::TGeoScale(const char *name, Double_t sx, Double_t sy, Double_t sz) : TGeoMatrix(name) { SetBit(kGeoScale); SetScale(sx, sy, sz); @@ -1462,20 +1488,19 @@ TGeoScale::TGeoScale(const char *name, Double_t sx, Double_t sy, Double_t sz) //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoScale::~TGeoScale() -{ -} +TGeoScale::~TGeoScale() {} //////////////////////////////////////////////////////////////////////////////// /// Assignment from a general matrix -TGeoScale& TGeoScale::operator = (const TGeoMatrix &matrix) +TGeoScale &TGeoScale::operator=(const TGeoMatrix &matrix) { - if (&matrix == this) return *this; + if (&matrix == this) + return *this; Bool_t registered = TestBit(kGeoRegistered); TNamed::operator=(matrix); SetScale(matrix); - SetBit(kGeoRegistered,registered); + SetBit(kGeoRegistered, registered); ResetBit(kGeoTranslation); ResetBit(kGeoRotation); return *this; @@ -1491,7 +1516,8 @@ TGeoScale &TGeoScale::operator*=(const TGeoScale &right) fScale[1] *= scl[1]; fScale[2] *= scl[2]; SetBit(kGeoReflection, fScale[0] * fScale[1] * fScale[2] < 0); - if (!IsScale()) SetBit(kGeoScale, right.IsScale()); + if (!IsScale()) + SetBit(kGeoScale, right.IsScale()); return *this; } @@ -1512,13 +1538,15 @@ TGeoHMatrix TGeoScale::operator*(const TGeoMatrix &right) const //////////////////////////////////////////////////////////////////////////////// /// Is-equal operator -Bool_t TGeoScale::operator ==(const TGeoScale &other) const +Bool_t TGeoScale::operator==(const TGeoScale &other) const { - if (&other == this) return kTRUE; + if (&other == this) + return kTRUE; const Double_t *scl = GetScale(); const Double_t *oscl = other.GetScale(); - for (auto i=0; i<3; i++) - if (TMath::Abs(scl[i]-oscl[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 3; i++) + if (TMath::Abs(scl[i] - oscl[i]) > 1.E-10) + return kFALSE; return kTRUE; } @@ -1531,9 +1559,9 @@ TGeoHMatrix TGeoScale::Inverse() const h = *this; h.ResetBit(kGeoRegistered); Double_t scale[3]; - scale[0] = 1./fScale[0]; - scale[1] = 1./fScale[1]; - scale[2] = 1./fScale[2]; + scale[0] = 1. / fScale[0]; + scale[1] = 1. / fScale[1]; + scale[2] = 1. / fScale[2]; h.SetScale(scale); return h; } @@ -1543,15 +1571,17 @@ TGeoHMatrix TGeoScale::Inverse() const void TGeoScale::SetScale(Double_t sx, Double_t sy, Double_t sz) { - if (TMath::Abs(sx*sy*sz) < 1.E-10) { - Error("SetScale", "Invalid scale %f, %f, %f for transformation %s",sx,sy,sx,GetName()); + if (TMath::Abs(sx * sy * sz) < 1.E-10) { + Error("SetScale", "Invalid scale %f, %f, %f for transformation %s", sx, sy, sx, GetName()); return; } fScale[0] = sx; fScale[1] = sy; fScale[2] = sz; - if (sx*sy*sz<0) SetBit(kGeoReflection); - else SetBit(kGeoReflection, kFALSE); + if (sx * sy * sz < 0) + SetBit(kGeoReflection); + else + SetBit(kGeoReflection, kFALSE); } //////////////////////////////////////////////////////////////////////////////// @@ -1569,9 +1599,9 @@ void TGeoScale::SetScale(const TGeoMatrix &other) void TGeoScale::LocalToMaster(const Double_t *local, Double_t *master) const { - master[0] = local[0]*fScale[0]; - master[1] = local[1]*fScale[1]; - master[2] = local[2]*fScale[2]; + master[0] = local[0] * fScale[0]; + master[1] = local[1] * fScale[1]; + master[2] = local[2] * fScale[2]; } //////////////////////////////////////////////////////////////////////////////// @@ -1584,15 +1614,16 @@ Double_t TGeoScale::LocalToMaster(Double_t dist, const Double_t *dir) const Double_t scale; if (!dir) { scale = TMath::Abs(fScale[0]); - if (TMath::Abs(fScale[1])scale) scale = TMath::Abs(fScale[1]); - if (TMath::Abs(fScale[2])>scale) scale = TMath::Abs(fScale[2]); - scale = 1./scale; + if (TMath::Abs(fScale[1]) > scale) + scale = TMath::Abs(fScale[1]); + if (TMath::Abs(fScale[2]) > scale) + scale = TMath::Abs(fScale[2]); + scale = 1. / scale; } else { - scale = (dir[0]*dir[0])/(fScale[0]*fScale[0]) + - (dir[1]*dir[1])/(fScale[1]*fScale[1]) + - (dir[2]*dir[2])/(fScale[2]*fScale[2]); + scale = (dir[0] * dir[0]) / (fScale[0] * fScale[0]) + (dir[1] * dir[1]) / (fScale[1] * fScale[1]) + + (dir[2] * dir[2]) / (fScale[2] * fScale[2]); scale = TMath::Sqrt(scale); } - return scale*dist; + return scale * dist; } /** \class TGeoCombiTrans @@ -1649,29 +1681,30 @@ ClassImp(TGeoCombiTrans); TGeoCombiTrans::TGeoCombiTrans() { - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// /// Copy ctor from generic matrix. -TGeoCombiTrans::TGeoCombiTrans(const TGeoMatrix &other) - :TGeoMatrix(other) +TGeoCombiTrans::TGeoCombiTrans(const TGeoMatrix &other) : TGeoMatrix(other) { ResetBit(kGeoScale); if (other.IsTranslation()) { SetBit(kGeoTranslation); - memcpy(fTranslation,other.GetTranslation(),kN3); + memcpy(fTranslation, other.GetTranslation(), kN3); } else { - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; } if (other.IsRotation()) { SetBit(kGeoRotation); SetBit(kGeoMatrixOwned); fRotation = new TGeoRotation(other); - } - else fRotation = 0; + } else + fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// @@ -1684,32 +1717,33 @@ TGeoCombiTrans::TGeoCombiTrans(const TGeoTranslation &tr, const TGeoRotation &ro const Double_t *trans = tr.GetTranslation(); memcpy(fTranslation, trans, kN3); } else { - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; } if (rot.IsRotation()) { SetBit(kGeoRotation); SetBit(kGeoMatrixOwned); fRotation = new TGeoRotation(rot); SetBit(kGeoReflection, rot.TestBit(kGeoReflection)); - } - else fRotation = 0; + } else + fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// /// Named ctor. -TGeoCombiTrans::TGeoCombiTrans(const char *name) - :TGeoMatrix(name) +TGeoCombiTrans::TGeoCombiTrans(const char *name) : TGeoMatrix(name) { - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// -/// Constructor from a translation specified by X,Y,Z and a pointer to a rotation. The rotation will not be owned by this. +/// Constructor from a translation specified by X,Y,Z and a pointer to a rotation. The rotation will not be owned by +/// this. -TGeoCombiTrans::TGeoCombiTrans(Double_t dx, Double_t dy, Double_t dz, TGeoRotation *rot) - :TGeoMatrix("") +TGeoCombiTrans::TGeoCombiTrans(Double_t dx, Double_t dy, Double_t dz, TGeoRotation *rot) : TGeoMatrix("") { SetTranslation(dx, dy, dz); fRotation = 0; @@ -1720,7 +1754,7 @@ TGeoCombiTrans::TGeoCombiTrans(Double_t dx, Double_t dy, Double_t dz, TGeoRotati /// Named ctor TGeoCombiTrans::TGeoCombiTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, TGeoRotation *rot) - :TGeoMatrix(name) + : TGeoMatrix(name) { SetTranslation(dx, dy, dz); fRotation = 0; @@ -1732,13 +1766,14 @@ TGeoCombiTrans::TGeoCombiTrans(const char *name, Double_t dx, Double_t dy, Doubl TGeoCombiTrans &TGeoCombiTrans::operator=(const TGeoMatrix &matrix) { - if (&matrix == this) return *this; + if (&matrix == this) + return *this; Bool_t registered = TestBit(kGeoRegistered); Clear(); TNamed::operator=(matrix); if (matrix.IsTranslation()) { - memcpy(fTranslation,matrix.GetTranslation(),kN3); + memcpy(fTranslation, matrix.GetTranslation(), kN3); } if (matrix.IsRotation()) { if (!fRotation) { @@ -1754,11 +1789,12 @@ TGeoCombiTrans &TGeoCombiTrans::operator=(const TGeoMatrix &matrix) fRotation->SetBit(kGeoReflection, matrix.TestBit(kGeoReflection)); fRotation->SetBit(kGeoRotation); } else { - if (fRotation && TestBit(kGeoMatrixOwned)) delete fRotation; + if (fRotation && TestBit(kGeoMatrixOwned)) + delete fRotation; ResetBit(kGeoMatrixOwned); fRotation = 0; } - SetBit(kGeoRegistered,registered); + SetBit(kGeoRegistered, registered); ResetBit(kGeoScale); return *this; } @@ -1768,13 +1804,18 @@ TGeoCombiTrans &TGeoCombiTrans::operator=(const TGeoMatrix &matrix) Bool_t TGeoCombiTrans::operator==(const TGeoMatrix &other) const { - if (&other == this) return kTRUE; + if (&other == this) + return kTRUE; const Double_t *tr = GetTranslation(); const Double_t *otr = other.GetTranslation(); - for (auto i=0; i<3; i++) if (TMath::Abs(tr[i]-otr[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 3; i++) + if (TMath::Abs(tr[i] - otr[i]) > 1.E-10) + return kFALSE; const Double_t *rot = GetRotationMatrix(); const Double_t *orot = other.GetRotationMatrix(); - for (auto i=0; i<9; i++) if (TMath::Abs(rot[i]-orot[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 9; i++) + if (TMath::Abs(rot[i] - orot[i]) > 1.E-10) + return kFALSE; return kTRUE; } @@ -1800,7 +1841,8 @@ TGeoCombiTrans TGeoCombiTrans::operator*(const TGeoMatrix &right) const TGeoCombiTrans::~TGeoCombiTrans() { if (fRotation) { - if(TestBit(TGeoMatrix::kGeoMatrixOwned) && !fRotation->IsRegistered()) delete fRotation; + if (TestBit(TGeoMatrix::kGeoMatrixOwned) && !fRotation->IsRegistered()) + delete fRotation; } } @@ -1814,7 +1856,8 @@ void TGeoCombiTrans::Clear(Option_t *) memset(fTranslation, 0, kN3); } if (fRotation) { - if (TestBit(kGeoMatrixOwned)) delete fRotation; + if (TestBit(kGeoMatrixOwned)) + delete fRotation; fRotation = 0; } ResetBit(kGeoRotation); @@ -1835,9 +1878,9 @@ TGeoHMatrix TGeoCombiTrans::Inverse() const Double_t tr[3]; Double_t newrot[9]; const Double_t *rot = GetRotationMatrix(); - tr[0] = -fTranslation[0]*rot[0] - fTranslation[1]*rot[3] - fTranslation[2]*rot[6]; - tr[1] = -fTranslation[0]*rot[1] - fTranslation[1]*rot[4] - fTranslation[2]*rot[7]; - tr[2] = -fTranslation[0]*rot[2] - fTranslation[1]*rot[5] - fTranslation[2]*rot[8]; + tr[0] = -fTranslation[0] * rot[0] - fTranslation[1] * rot[3] - fTranslation[2] * rot[6]; + tr[1] = -fTranslation[0] * rot[1] - fTranslation[1] * rot[4] - fTranslation[2] * rot[7]; + tr[2] = -fTranslation[0] * rot[2] - fTranslation[1] * rot[5] - fTranslation[2] * rot[8]; h.SetTranslation(tr); newrot[0] = rot[0]; newrot[1] = rot[3]; @@ -1849,8 +1892,8 @@ TGeoHMatrix TGeoCombiTrans::Inverse() const newrot[7] = rot[5]; newrot[8] = rot[8]; h.SetRotation(newrot); - h.SetBit(kGeoTranslation,is_tr); - h.SetBit(kGeoRotation,is_rot); + h.SetBit(kGeoTranslation, is_tr); + h.SetBit(kGeoRotation, is_rot); return h; } @@ -1869,7 +1912,8 @@ TGeoMatrix *TGeoCombiTrans::MakeClone() const void TGeoCombiTrans::Multiply(const TGeoMatrix *right) { - if (right->IsIdentity()) return; + if (right->IsIdentity()) + return; TGeoHMatrix h = *this; h.Multiply(right); operator=(h); @@ -1881,7 +1925,8 @@ void TGeoCombiTrans::Multiply(const TGeoMatrix *right) void TGeoCombiTrans::RegisterYourself() { TGeoMatrix::RegisterYourself(); - if (fRotation && fRotation->IsRotation()) fRotation->RegisterYourself(); + if (fRotation && fRotation->IsRotation()) + fRotation->RegisterYourself(); } //////////////////////////////////////////////////////////////////////////////// @@ -1890,32 +1935,35 @@ void TGeoCombiTrans::RegisterYourself() void TGeoCombiTrans::RotateX(Double_t angle) { if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); const Double_t *rot = fRotation->GetRotationMatrix(); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; v[0] = rot[0]; v[1] = rot[1]; v[2] = rot[2]; - v[3] = c*rot[3]-s*rot[6]; - v[4] = c*rot[4]-s*rot[7]; - v[5] = c*rot[5]-s*rot[8]; - v[6] = s*rot[3]+c*rot[6]; - v[7] = s*rot[4]+c*rot[7]; - v[8] = s*rot[5]+c*rot[8]; + v[3] = c * rot[3] - s * rot[6]; + v[4] = c * rot[4] - s * rot[7]; + v[5] = c * rot[5] - s * rot[8]; + v[6] = s * rot[3] + c * rot[6]; + v[7] = s * rot[4] + c * rot[7]; + v[8] = s * rot[5] + c * rot[8]; fRotation->SetMatrix(v); fRotation->SetBit(kGeoRotation); - if (!IsTranslation()) return; + if (!IsTranslation()) + return; v[0] = fTranslation[0]; - v[1] = c*fTranslation[1]-s*fTranslation[2]; - v[2] = s*fTranslation[1]+c*fTranslation[2]; - memcpy(fTranslation,v,kN3); + v[1] = c * fTranslation[1] - s * fTranslation[2]; + v[2] = s * fTranslation[1] + c * fTranslation[2]; + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -1924,32 +1972,35 @@ void TGeoCombiTrans::RotateX(Double_t angle) void TGeoCombiTrans::RotateY(Double_t angle) { if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); const Double_t *rot = fRotation->GetRotationMatrix(); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*rot[0]+s*rot[6]; - v[1] = c*rot[1]+s*rot[7]; - v[2] = c*rot[2]+s*rot[8]; + v[0] = c * rot[0] + s * rot[6]; + v[1] = c * rot[1] + s * rot[7]; + v[2] = c * rot[2] + s * rot[8]; v[3] = rot[3]; v[4] = rot[4]; v[5] = rot[5]; - v[6] = -s*rot[0]+c*rot[6]; - v[7] = -s*rot[1]+c*rot[7]; - v[8] = -s*rot[2]+c*rot[8]; + v[6] = -s * rot[0] + c * rot[6]; + v[7] = -s * rot[1] + c * rot[7]; + v[8] = -s * rot[2] + c * rot[8]; fRotation->SetMatrix(v); fRotation->SetBit(kGeoRotation); - if (!IsTranslation()) return; - v[0] = c*fTranslation[0]+s*fTranslation[2]; + if (!IsTranslation()) + return; + v[0] = c * fTranslation[0] + s * fTranslation[2]; v[1] = fTranslation[1]; - v[2] = -s*fTranslation[0]+c*fTranslation[2]; - memcpy(fTranslation,v,kN3); + v[2] = -s * fTranslation[0] + c * fTranslation[2]; + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -1958,32 +2009,35 @@ void TGeoCombiTrans::RotateY(Double_t angle) void TGeoCombiTrans::RotateZ(Double_t angle) { if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); const Double_t *rot = fRotation->GetRotationMatrix(); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*rot[0]-s*rot[3]; - v[1] = c*rot[1]-s*rot[4]; - v[2] = c*rot[2]-s*rot[5]; - v[3] = s*rot[0]+c*rot[3]; - v[4] = s*rot[1]+c*rot[4]; - v[5] = s*rot[2]+c*rot[5]; + v[0] = c * rot[0] - s * rot[3]; + v[1] = c * rot[1] - s * rot[4]; + v[2] = c * rot[2] - s * rot[5]; + v[3] = s * rot[0] + c * rot[3]; + v[4] = s * rot[1] + c * rot[4]; + v[5] = s * rot[2] + c * rot[5]; v[6] = rot[6]; v[7] = rot[7]; v[8] = rot[8]; fRotation->SetMatrix(v); fRotation->SetBit(kGeoRotation); - if (!IsTranslation()) return; - v[0] = c*fTranslation[0]-s*fTranslation[1]; - v[1] = s*fTranslation[0]+c*fTranslation[1]; + if (!IsTranslation()) + return; + v[0] = c * fTranslation[0] - s * fTranslation[1]; + v[1] = s * fTranslation[0] + c * fTranslation[1]; v[2] = fTranslation[2]; - memcpy(fTranslation,v,kN3); + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -1991,10 +2045,13 @@ void TGeoCombiTrans::RotateZ(Double_t angle) void TGeoCombiTrans::ReflectX(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[0] = -fTranslation[0]; + if (leftside && !rotonly) + fTranslation[0] = -fTranslation[0]; if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); @@ -2007,10 +2064,13 @@ void TGeoCombiTrans::ReflectX(Bool_t leftside, Bool_t rotonly) void TGeoCombiTrans::ReflectY(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[1] = -fTranslation[1]; + if (leftside && !rotonly) + fTranslation[1] = -fTranslation[1]; if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); @@ -2023,10 +2083,13 @@ void TGeoCombiTrans::ReflectY(Bool_t leftside, Bool_t rotonly) void TGeoCombiTrans::ReflectZ(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[2] = -fTranslation[2]; + if (leftside && !rotonly) + fTranslation[2] = -fTranslation[2]; if (!fRotation || !TestBit(kGeoMatrixOwned)) { - if (fRotation) fRotation = new TGeoRotation(*fRotation); - else fRotation = new TGeoRotation(); + if (fRotation) + fRotation = new TGeoRotation(*fRotation); + else + fRotation = new TGeoRotation(); SetBit(kGeoMatrixOwned); } SetBit(kGeoRotation); @@ -2039,13 +2102,14 @@ void TGeoCombiTrans::ReflectZ(Bool_t leftside, Bool_t rotonly) void TGeoCombiTrans::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - if (TestBit(kGeoSavePrimitive)) return; + if (TestBit(kGeoSavePrimitive)) + return; out << " // Combi transformation: " << GetName() << std::endl; out << " dx = " << fTranslation[0] << ";" << std::endl; out << " dy = " << fTranslation[1] << ";" << std::endl; out << " dz = " << fTranslation[2] << ";" << std::endl; if (fRotation && fRotation->IsRotation()) { - fRotation->SavePrimitive(out,option); + fRotation->SavePrimitive(out, option); out << " auto " << GetPointerName() << " = new TGeoCombiTrans(\"" << GetName() << "\", dx, dy, dz, " << fRotation->GetPointerName() << ");" << std::endl; } else { @@ -2060,17 +2124,20 @@ void TGeoCombiTrans::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) void TGeoCombiTrans::SetRotation(const TGeoRotation *rot) { - if (fRotation && TestBit(kGeoMatrixOwned)) delete fRotation; + if (fRotation && TestBit(kGeoMatrixOwned)) + delete fRotation; fRotation = 0; ResetBit(TGeoMatrix::kGeoMatrixOwned); ResetBit(kGeoRotation); ResetBit(kGeoReflection); - if (!rot) return; - if (!rot->IsRotation()) return; + if (!rot) + return; + if (!rot->IsRotation()) + return; SetBit(kGeoRotation); SetBit(kGeoReflection, rot->TestBit(kGeoReflection)); - TGeoRotation *rr = (TGeoRotation*)rot; + TGeoRotation *rr = (TGeoRotation *)rot; fRotation = rr; } @@ -2079,7 +2146,8 @@ void TGeoCombiTrans::SetRotation(const TGeoRotation *rot) void TGeoCombiTrans::SetRotation(const TGeoRotation &rot) { - if (fRotation && TestBit(kGeoMatrixOwned)) delete fRotation; + if (fRotation && TestBit(kGeoMatrixOwned)) + delete fRotation; fRotation = 0; if (!rot.IsRotation()) { ResetBit(kGeoRotation); @@ -2104,7 +2172,8 @@ void TGeoCombiTrans::SetTranslation(const TGeoTranslation &tr) const Double_t *trans = tr.GetTranslation(); memcpy(fTranslation, trans, kN3); } else { - if (!IsTranslation()) return; + if (!IsTranslation()) + return; memset(fTranslation, 0, kN3); ResetBit(kGeoTranslation); } @@ -2118,8 +2187,10 @@ void TGeoCombiTrans::SetTranslation(Double_t dx, Double_t dy, Double_t dz) fTranslation[0] = dx; fTranslation[1] = dy; fTranslation[2] = dz; - if (fTranslation[0] || fTranslation[1] || fTranslation[2]) SetBit(kGeoTranslation); - else ResetBit(kGeoTranslation); + if (fTranslation[0] || fTranslation[1] || fTranslation[2]) + SetBit(kGeoTranslation); + else + ResetBit(kGeoTranslation); } //////////////////////////////////////////////////////////////////////////////// @@ -2130,8 +2201,10 @@ void TGeoCombiTrans::SetTranslation(Double_t *vect) fTranslation[0] = vect[0]; fTranslation[1] = vect[1]; fTranslation[2] = vect[2]; - if (fTranslation[0] || fTranslation[1] || fTranslation[2]) SetBit(kGeoTranslation); - else ResetBit(kGeoTranslation); + if (fTranslation[0] || fTranslation[1] || fTranslation[2]) + SetBit(kGeoTranslation); + else + ResetBit(kGeoTranslation); } //////////////////////////////////////////////////////////////////////////////// @@ -2139,7 +2212,8 @@ void TGeoCombiTrans::SetTranslation(Double_t *vect) const Double_t *TGeoCombiTrans::GetRotationMatrix() const { - if (!fRotation) return kIdentityMatrix; + if (!fRotation) + return kIdentityMatrix; return fRotation->GetRotationMatrix(); } @@ -2156,29 +2230,32 @@ ClassImp(TGeoGenTrans); TGeoGenTrans::TGeoGenTrans() { SetBit(kGeoGenTrans); - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; - for (Int_t j=0; j<3; j++) fScale[j] = 1.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; + for (Int_t j = 0; j < 3; j++) + fScale[j] = 1.0; fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoGenTrans::TGeoGenTrans(const char *name) - :TGeoCombiTrans(name) +TGeoGenTrans::TGeoGenTrans(const char *name) : TGeoCombiTrans(name) { SetBit(kGeoGenTrans); - for (Int_t i=0; i<3; i++) fTranslation[i] = 0.0; - for (Int_t j=0; j<3; j++) fScale[j] = 1.0; + for (Int_t i = 0; i < 3; i++) + fTranslation[i] = 0.0; + for (Int_t j = 0; j < 3; j++) + fScale[j] = 1.0; fRotation = 0; } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoGenTrans::TGeoGenTrans(Double_t dx, Double_t dy, Double_t dz, - Double_t sx, Double_t sy, Double_t sz, TGeoRotation *rot) - :TGeoCombiTrans("") +TGeoGenTrans::TGeoGenTrans(Double_t dx, Double_t dy, Double_t dz, Double_t sx, Double_t sy, Double_t sz, + TGeoRotation *rot) + : TGeoCombiTrans("") { SetBit(kGeoGenTrans); SetTranslation(dx, dy, dz); @@ -2189,9 +2266,9 @@ TGeoGenTrans::TGeoGenTrans(Double_t dx, Double_t dy, Double_t dz, //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoGenTrans::TGeoGenTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, - Double_t sx, Double_t sy, Double_t sz, TGeoRotation *rot) - :TGeoCombiTrans(name) +TGeoGenTrans::TGeoGenTrans(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t sx, Double_t sy, + Double_t sz, TGeoRotation *rot) + : TGeoCombiTrans(name) { SetBit(kGeoGenTrans); SetTranslation(dx, dy, dz); @@ -2202,9 +2279,7 @@ TGeoGenTrans::TGeoGenTrans(const char *name, Double_t dx, Double_t dy, Double_t //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoGenTrans::~TGeoGenTrans() -{ -} +TGeoGenTrans::~TGeoGenTrans() {} //////////////////////////////////////////////////////////////////////////////// /// clear the fields of this transformation @@ -2213,7 +2288,8 @@ void TGeoGenTrans::Clear(Option_t *) { memset(&fTranslation[0], 0, kN3); memset(&fScale[0], 0, kN3); - if (fRotation) fRotation->Clear(); + if (fRotation) + fRotation->Clear(); } //////////////////////////////////////////////////////////////////////////////// @@ -2221,7 +2297,7 @@ void TGeoGenTrans::Clear(Option_t *) void TGeoGenTrans::SetScale(Double_t sx, Double_t sy, Double_t sz) { - if (sx<1.E-5 || sy<1.E-5 || sz<1.E-5) { + if (sx < 1.E-5 || sy < 1.E-5 || sz < 1.E-5) { Error("ctor", "Invalid scale"); return; } @@ -2245,9 +2321,10 @@ TGeoHMatrix TGeoGenTrans::Inverse() const Bool_t TGeoGenTrans::Normalize() { - Double_t normfactor = fScale[0]*fScale[1]*fScale[2]; - if (normfactor <= 1E-5) return kFALSE; - for (Int_t i=0; i<3; i++) + Double_t normfactor = fScale[0] * fScale[1] * fScale[2]; + if (normfactor <= 1E-5) + return kFALSE; + for (Int_t i = 0; i < 3; i++) fScale[i] /= normfactor; return kTRUE; } @@ -2266,17 +2343,18 @@ ClassImp(TGeoIdentity); TGeoIdentity::TGeoIdentity() { - if (!gGeoIdentity) gGeoIdentity = this; + if (!gGeoIdentity) + gGeoIdentity = this; RegisterYourself(); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoIdentity::TGeoIdentity(const char *name) - :TGeoMatrix(name) +TGeoIdentity::TGeoIdentity(const char *name) : TGeoMatrix(name) { - if (!gGeoIdentity) gGeoIdentity = this; + if (!gGeoIdentity) + gGeoIdentity = this; RegisterYourself(); } @@ -2306,45 +2384,42 @@ ClassImp(TGeoHMatrix); TGeoHMatrix::TGeoHMatrix() { memset(&fTranslation[0], 0, kN3); - memcpy(fRotationMatrix,kIdentityMatrix,kN9); - memcpy(fScale,kUnitScale,kN3); + memcpy(fRotationMatrix, kIdentityMatrix, kN9); + memcpy(fScale, kUnitScale, kN3); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoHMatrix::TGeoHMatrix(const char* name) - :TGeoMatrix(name) +TGeoHMatrix::TGeoHMatrix(const char *name) : TGeoMatrix(name) { memset(&fTranslation[0], 0, kN3); - memcpy(fRotationMatrix,kIdentityMatrix,kN9); - memcpy(fScale,kUnitScale,kN3); + memcpy(fRotationMatrix, kIdentityMatrix, kN9); + memcpy(fScale, kUnitScale, kN3); } //////////////////////////////////////////////////////////////////////////////// /// assignment -TGeoHMatrix::TGeoHMatrix(const TGeoMatrix &matrix) - :TGeoMatrix(matrix) +TGeoHMatrix::TGeoHMatrix(const TGeoMatrix &matrix) : TGeoMatrix(matrix) { memset(&fTranslation[0], 0, kN3); - memcpy(fRotationMatrix,kIdentityMatrix,kN9); - memcpy(fScale,kUnitScale,kN3); - if (matrix.IsIdentity()) return; + memcpy(fRotationMatrix, kIdentityMatrix, kN9); + memcpy(fScale, kUnitScale, kN3); + if (matrix.IsIdentity()) + return; if (matrix.IsTranslation()) SetTranslation(matrix.GetTranslation()); if (matrix.IsRotation()) - memcpy(fRotationMatrix,matrix.GetRotationMatrix(),kN9); + memcpy(fRotationMatrix, matrix.GetRotationMatrix(), kN9); if (matrix.IsScale()) - memcpy(fScale,matrix.GetScale(),kN3); + memcpy(fScale, matrix.GetScale(), kN3); } //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoHMatrix::~TGeoHMatrix() -{ -} +TGeoHMatrix::~TGeoHMatrix() {} //////////////////////////////////////////////////////////////////////////////// /// assignment @@ -2359,18 +2434,20 @@ TGeoHMatrix &TGeoHMatrix::operator=(const TGeoMatrix *matrix) TGeoHMatrix &TGeoHMatrix::operator=(const TGeoMatrix &matrix) { - if (&matrix == this) return *this; + if (&matrix == this) + return *this; Clear(); Bool_t registered = TestBit(kGeoRegistered); TNamed::operator=(matrix); - if (matrix.IsIdentity()) return *this; + if (matrix.IsIdentity()) + return *this; if (matrix.IsTranslation()) - memcpy(fTranslation,matrix.GetTranslation(),kN3); + memcpy(fTranslation, matrix.GetTranslation(), kN3); if (matrix.IsRotation()) - memcpy(fRotationMatrix,matrix.GetRotationMatrix(),kN9); + memcpy(fRotationMatrix, matrix.GetRotationMatrix(), kN9); if (matrix.IsScale()) - memcpy(fScale,matrix.GetScale(),kN3); - SetBit(kGeoRegistered,registered); + memcpy(fScale, matrix.GetScale(), kN3); + SetBit(kGeoRegistered, registered); return *this; } @@ -2395,16 +2472,23 @@ TGeoHMatrix TGeoHMatrix::operator*(const TGeoMatrix &right) const Bool_t TGeoHMatrix::operator==(const TGeoMatrix &other) const { - if (&other == this) return kTRUE; + if (&other == this) + return kTRUE; const Double_t *tr = GetTranslation(); const Double_t *otr = other.GetTranslation(); - for (auto i=0; i<3; i++) if (TMath::Abs(tr[i]-otr[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 3; i++) + if (TMath::Abs(tr[i] - otr[i]) > 1.E-10) + return kFALSE; const Double_t *rot = GetRotationMatrix(); const Double_t *orot = other.GetRotationMatrix(); - for (auto i=0; i<9; i++) if (TMath::Abs(rot[i]-orot[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 9; i++) + if (TMath::Abs(rot[i] - orot[i]) > 1.E-10) + return kFALSE; const Double_t *scl = GetScale(); const Double_t *oscl = other.GetScale(); - for (auto i=0; i<3; i++) if (TMath::Abs(scl[i]-oscl[i])>1.E-10) return kFALSE; + for (auto i = 0; i < 3; i++) + if (TMath::Abs(scl[i] - oscl[i]) > 1.E-10) + return kFALSE; return kTRUE; } @@ -2416,8 +2500,8 @@ void TGeoHMatrix::CopyFrom(const TGeoMatrix *other) SetBit(kGeoTranslation, other->IsTranslation()); SetBit(kGeoRotation, other->IsRotation()); SetBit(kGeoReflection, other->IsReflection()); - memcpy(fTranslation,other->GetTranslation(),kN3); - memcpy(fRotationMatrix,other->GetRotationMatrix(),kN9); + memcpy(fTranslation, other->GetTranslation(), kN3); + memcpy(fRotationMatrix, other->GetRotationMatrix(), kN9); } //////////////////////////////////////////////////////////////////////////////// @@ -2426,13 +2510,14 @@ void TGeoHMatrix::CopyFrom(const TGeoMatrix *other) void TGeoHMatrix::Clear(Option_t *) { SetBit(kGeoReflection, kFALSE); - if (IsIdentity()) return; + if (IsIdentity()) + return; ResetBit(kGeoTranslation); ResetBit(kGeoRotation); ResetBit(kGeoScale); - memcpy(fTranslation,kNullVector,kN3); - memcpy(fRotationMatrix,kIdentityMatrix,kN9); - memcpy(fScale,kUnitScale,kN3); + memcpy(fTranslation, kNullVector, kN3); + memcpy(fRotationMatrix, kIdentityMatrix, kN9); + memcpy(fScale, kUnitScale, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -2466,9 +2551,12 @@ TGeoHMatrix TGeoHMatrix::Inverse() const h.ResetBit(kGeoRegistered); if (IsTranslation()) { Double_t tr[3]; - tr[0] = -fTranslation[0]*fRotationMatrix[0] - fTranslation[1]*fRotationMatrix[3] - fTranslation[2]*fRotationMatrix[6]; - tr[1] = -fTranslation[0]*fRotationMatrix[1] - fTranslation[1]*fRotationMatrix[4] - fTranslation[2]*fRotationMatrix[7]; - tr[2] = -fTranslation[0]*fRotationMatrix[2] - fTranslation[1]*fRotationMatrix[5] - fTranslation[2]*fRotationMatrix[8]; + tr[0] = -fTranslation[0] * fRotationMatrix[0] - fTranslation[1] * fRotationMatrix[3] - + fTranslation[2] * fRotationMatrix[6]; + tr[1] = -fTranslation[0] * fRotationMatrix[1] - fTranslation[1] * fRotationMatrix[4] - + fTranslation[2] * fRotationMatrix[7]; + tr[2] = -fTranslation[0] * fRotationMatrix[2] - fTranslation[1] * fRotationMatrix[5] - + fTranslation[2] * fRotationMatrix[8]; h.SetTranslation(tr); } if (IsRotation()) { @@ -2486,9 +2574,9 @@ TGeoHMatrix TGeoHMatrix::Inverse() const } if (IsScale()) { Double_t sc[3]; - sc[0] = 1./fScale[0]; - sc[1] = 1./fScale[1]; - sc[2] = 1./fScale[2]; + sc[0] = 1. / fScale[0]; + sc[1] = 1. / fScale[1]; + sc[2] = 1. / fScale[2]; h.SetScale(sc); } return h; @@ -2499,13 +2587,12 @@ TGeoHMatrix TGeoHMatrix::Inverse() const Double_t TGeoHMatrix::Determinant() const { - Double_t - det = fRotationMatrix[0]*fRotationMatrix[4]*fRotationMatrix[8] + - fRotationMatrix[3]*fRotationMatrix[7]*fRotationMatrix[2] + - fRotationMatrix[6]*fRotationMatrix[1]*fRotationMatrix[5] - - fRotationMatrix[2]*fRotationMatrix[4]*fRotationMatrix[6] - - fRotationMatrix[5]*fRotationMatrix[7]*fRotationMatrix[0] - - fRotationMatrix[8]*fRotationMatrix[1]*fRotationMatrix[3]; + Double_t det = fRotationMatrix[0] * fRotationMatrix[4] * fRotationMatrix[8] + + fRotationMatrix[3] * fRotationMatrix[7] * fRotationMatrix[2] + + fRotationMatrix[6] * fRotationMatrix[1] * fRotationMatrix[5] - + fRotationMatrix[2] * fRotationMatrix[4] * fRotationMatrix[6] - + fRotationMatrix[5] * fRotationMatrix[7] * fRotationMatrix[0] - + fRotationMatrix[8] * fRotationMatrix[1] * fRotationMatrix[3]; return det; } @@ -2515,58 +2602,62 @@ Double_t TGeoHMatrix::Determinant() const void TGeoHMatrix::Multiply(const TGeoMatrix *right) { - if (right->IsIdentity()) return; + if (right->IsIdentity()) + return; const Double_t *r_tra = right->GetTranslation(); const Double_t *r_rot = right->GetRotationMatrix(); const Double_t *r_scl = right->GetScale(); if (IsIdentity()) { if (right->IsRotation()) { SetBit(kGeoRotation); - memcpy(fRotationMatrix,r_rot,kN9); - if (right->IsReflection()) SetBit(kGeoReflection, !TestBit(kGeoReflection)); + memcpy(fRotationMatrix, r_rot, kN9); + if (right->IsReflection()) + SetBit(kGeoReflection, !TestBit(kGeoReflection)); } if (right->IsScale()) { SetBit(kGeoScale); - memcpy(fScale,r_scl,kN3); + memcpy(fScale, r_scl, kN3); } if (right->IsTranslation()) { SetBit(kGeoTranslation); - memcpy(fTranslation,r_tra,kN3); + memcpy(fTranslation, r_tra, kN3); } return; } Int_t i, j; Double_t new_rot[9]; - if (right->IsRotation()) { + if (right->IsRotation()) { SetBit(kGeoRotation); - if (right->IsReflection()) SetBit(kGeoReflection, !TestBit(kGeoReflection)); + if (right->IsReflection()) + SetBit(kGeoReflection, !TestBit(kGeoReflection)); } - if (right->IsScale()) SetBit(kGeoScale); - if (right->IsTranslation()) SetBit(kGeoTranslation); + if (right->IsScale()) + SetBit(kGeoScale); + if (right->IsTranslation()) + SetBit(kGeoTranslation); // new translation if (IsTranslation()) { - for (i=0; i<3; i++) { - fTranslation[i] += fRotationMatrix[3*i]*r_tra[0] - + fRotationMatrix[3*i+1]*r_tra[1] - + fRotationMatrix[3*i+2]*r_tra[2]; + for (i = 0; i < 3; i++) { + fTranslation[i] += fRotationMatrix[3 * i] * r_tra[0] + fRotationMatrix[3 * i + 1] * r_tra[1] + + fRotationMatrix[3 * i + 2] * r_tra[2]; } } if (IsRotation()) { // new rotation - for (i=0; i<3; i++) { - for (j=0; j<3; j++) { - new_rot[3*i+j] = fRotationMatrix[3*i]*r_rot[j] + - fRotationMatrix[3*i+1]*r_rot[3+j] + - fRotationMatrix[3*i+2]*r_rot[6+j]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + new_rot[3 * i + j] = fRotationMatrix[3 * i] * r_rot[j] + fRotationMatrix[3 * i + 1] * r_rot[3 + j] + + fRotationMatrix[3 * i + 2] * r_rot[6 + j]; } } - memcpy(fRotationMatrix,new_rot,kN9); + memcpy(fRotationMatrix, new_rot, kN9); } // new scale if (IsScale()) { - for (i=0; i<3; i++) fScale[i] *= r_scl[i]; + for (i = 0; i < 3; i++) + fScale[i] *= r_scl[i]; } } @@ -2576,23 +2667,25 @@ void TGeoHMatrix::Multiply(const TGeoMatrix *right) void TGeoHMatrix::MultiplyLeft(const TGeoMatrix *left) { - if (left == gGeoIdentity) return; + if (left == gGeoIdentity) + return; const Double_t *l_tra = left->GetTranslation(); const Double_t *l_rot = left->GetRotationMatrix(); const Double_t *l_scl = left->GetScale(); if (IsIdentity()) { if (left->IsRotation()) { - if (left->IsReflection()) SetBit(kGeoReflection, !TestBit(kGeoReflection)); + if (left->IsReflection()) + SetBit(kGeoReflection, !TestBit(kGeoReflection)); SetBit(kGeoRotation); - memcpy(fRotationMatrix,l_rot,kN9); + memcpy(fRotationMatrix, l_rot, kN9); } if (left->IsScale()) { SetBit(kGeoScale); - memcpy(fScale,l_scl,kN3); + memcpy(fScale, l_scl, kN3); } if (left->IsTranslation()) { SetBit(kGeoTranslation); - memcpy(fTranslation,l_tra,kN3); + memcpy(fTranslation, l_tra, kN3); } return; } @@ -2602,35 +2695,36 @@ void TGeoHMatrix::MultiplyLeft(const TGeoMatrix *left) if (left->IsRotation()) { SetBit(kGeoRotation); - if (left->IsReflection()) SetBit(kGeoReflection, !TestBit(kGeoReflection)); + if (left->IsReflection()) + SetBit(kGeoReflection, !TestBit(kGeoReflection)); } - if (left->IsScale()) SetBit(kGeoScale); - if (left->IsTranslation()) SetBit(kGeoTranslation); + if (left->IsScale()) + SetBit(kGeoScale); + if (left->IsTranslation()) + SetBit(kGeoTranslation); // new translation if (IsTranslation()) { - for (i=0; i<3; i++) { - new_tra[i] = l_tra[i] - + l_rot[3*i]* fTranslation[0] - + l_rot[3*i+1]*fTranslation[1] - + l_rot[3*i+2]*fTranslation[2]; + for (i = 0; i < 3; i++) { + new_tra[i] = l_tra[i] + l_rot[3 * i] * fTranslation[0] + l_rot[3 * i + 1] * fTranslation[1] + + l_rot[3 * i + 2] * fTranslation[2]; } - memcpy(fTranslation,new_tra,kN3); + memcpy(fTranslation, new_tra, kN3); } if (IsRotation()) { // new rotation - for (i=0; i<3; i++) { - for (j=0; j<3; j++) { - new_rot[3*i+j] = l_rot[3*i]*fRotationMatrix[j] + - l_rot[3*i+1]*fRotationMatrix[3+j] + - l_rot[3*i+2]*fRotationMatrix[6+j]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + new_rot[3 * i + j] = l_rot[3 * i] * fRotationMatrix[j] + l_rot[3 * i + 1] * fRotationMatrix[3 + j] + + l_rot[3 * i + 2] * fRotationMatrix[6 + j]; } } - memcpy(fRotationMatrix,new_rot,kN9); + memcpy(fRotationMatrix, new_rot, kN9); } // new scale if (IsScale()) { - for (i=0; i<3; i++) fScale[i] *= l_scl[i]; + for (i = 0; i < 3; i++) + fScale[i] *= l_scl[i]; } } @@ -2640,25 +2734,25 @@ void TGeoHMatrix::MultiplyLeft(const TGeoMatrix *left) void TGeoHMatrix::RotateX(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; v[0] = fRotationMatrix[0]; v[1] = fRotationMatrix[1]; v[2] = fRotationMatrix[2]; - v[3] = c*fRotationMatrix[3]-s*fRotationMatrix[6]; - v[4] = c*fRotationMatrix[4]-s*fRotationMatrix[7]; - v[5] = c*fRotationMatrix[5]-s*fRotationMatrix[8]; - v[6] = s*fRotationMatrix[3]+c*fRotationMatrix[6]; - v[7] = s*fRotationMatrix[4]+c*fRotationMatrix[7]; - v[8] = s*fRotationMatrix[5]+c*fRotationMatrix[8]; + v[3] = c * fRotationMatrix[3] - s * fRotationMatrix[6]; + v[4] = c * fRotationMatrix[4] - s * fRotationMatrix[7]; + v[5] = c * fRotationMatrix[5] - s * fRotationMatrix[8]; + v[6] = s * fRotationMatrix[3] + c * fRotationMatrix[6]; + v[7] = s * fRotationMatrix[4] + c * fRotationMatrix[7]; + v[8] = s * fRotationMatrix[5] + c * fRotationMatrix[8]; memcpy(fRotationMatrix, v, kN9); v[0] = fTranslation[0]; - v[1] = c*fTranslation[1]-s*fTranslation[2]; - v[2] = s*fTranslation[1]+c*fTranslation[2]; - memcpy(fTranslation,v,kN3); + v[1] = c * fTranslation[1] - s * fTranslation[2]; + v[2] = s * fTranslation[1] + c * fTranslation[2]; + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -2667,25 +2761,25 @@ void TGeoHMatrix::RotateX(Double_t angle) void TGeoHMatrix::RotateY(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*fRotationMatrix[0]+s*fRotationMatrix[6]; - v[1] = c*fRotationMatrix[1]+s*fRotationMatrix[7]; - v[2] = c*fRotationMatrix[2]+s*fRotationMatrix[8]; + v[0] = c * fRotationMatrix[0] + s * fRotationMatrix[6]; + v[1] = c * fRotationMatrix[1] + s * fRotationMatrix[7]; + v[2] = c * fRotationMatrix[2] + s * fRotationMatrix[8]; v[3] = fRotationMatrix[3]; v[4] = fRotationMatrix[4]; v[5] = fRotationMatrix[5]; - v[6] = -s*fRotationMatrix[0]+c*fRotationMatrix[6]; - v[7] = -s*fRotationMatrix[1]+c*fRotationMatrix[7]; - v[8] = -s*fRotationMatrix[2]+c*fRotationMatrix[8]; + v[6] = -s * fRotationMatrix[0] + c * fRotationMatrix[6]; + v[7] = -s * fRotationMatrix[1] + c * fRotationMatrix[7]; + v[8] = -s * fRotationMatrix[2] + c * fRotationMatrix[8]; memcpy(fRotationMatrix, v, kN9); - v[0] = c*fTranslation[0]+s*fTranslation[2]; + v[0] = c * fTranslation[0] + s * fTranslation[2]; v[1] = fTranslation[1]; - v[2] = -s*fTranslation[0]+c*fTranslation[2]; - memcpy(fTranslation,v,kN3); + v[2] = -s * fTranslation[0] + c * fTranslation[2]; + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -2694,25 +2788,25 @@ void TGeoHMatrix::RotateY(Double_t angle) void TGeoHMatrix::RotateZ(Double_t angle) { SetBit(kGeoRotation); - Double_t phi = angle*TMath::DegToRad(); + Double_t phi = angle * TMath::DegToRad(); Double_t c = TMath::Cos(phi); Double_t s = TMath::Sin(phi); Double_t v[9]; - v[0] = c*fRotationMatrix[0]-s*fRotationMatrix[3]; - v[1] = c*fRotationMatrix[1]-s*fRotationMatrix[4]; - v[2] = c*fRotationMatrix[2]-s*fRotationMatrix[5]; - v[3] = s*fRotationMatrix[0]+c*fRotationMatrix[3]; - v[4] = s*fRotationMatrix[1]+c*fRotationMatrix[4]; - v[5] = s*fRotationMatrix[2]+c*fRotationMatrix[5]; + v[0] = c * fRotationMatrix[0] - s * fRotationMatrix[3]; + v[1] = c * fRotationMatrix[1] - s * fRotationMatrix[4]; + v[2] = c * fRotationMatrix[2] - s * fRotationMatrix[5]; + v[3] = s * fRotationMatrix[0] + c * fRotationMatrix[3]; + v[4] = s * fRotationMatrix[1] + c * fRotationMatrix[4]; + v[5] = s * fRotationMatrix[2] + c * fRotationMatrix[5]; v[6] = fRotationMatrix[6]; v[7] = fRotationMatrix[7]; v[8] = fRotationMatrix[8]; - memcpy(&fRotationMatrix[0],v,kN9); + memcpy(&fRotationMatrix[0], v, kN9); - v[0] = c*fTranslation[0]-s*fTranslation[1]; - v[1] = s*fTranslation[0]+c*fTranslation[1]; + v[0] = c * fTranslation[0] - s * fTranslation[1]; + v[1] = s * fTranslation[0] + c * fTranslation[1]; v[2] = fTranslation[2]; - memcpy(fTranslation,v,kN3); + memcpy(fTranslation, v, kN3); } //////////////////////////////////////////////////////////////////////////////// @@ -2720,15 +2814,16 @@ void TGeoHMatrix::RotateZ(Double_t angle) void TGeoHMatrix::ReflectX(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[0] = -fTranslation[0]; + if (leftside && !rotonly) + fTranslation[0] = -fTranslation[0]; if (leftside) { - fRotationMatrix[0]=-fRotationMatrix[0]; - fRotationMatrix[1]=-fRotationMatrix[1]; - fRotationMatrix[2]=-fRotationMatrix[2]; + fRotationMatrix[0] = -fRotationMatrix[0]; + fRotationMatrix[1] = -fRotationMatrix[1]; + fRotationMatrix[2] = -fRotationMatrix[2]; } else { - fRotationMatrix[0]=-fRotationMatrix[0]; - fRotationMatrix[3]=-fRotationMatrix[3]; - fRotationMatrix[6]=-fRotationMatrix[6]; + fRotationMatrix[0] = -fRotationMatrix[0]; + fRotationMatrix[3] = -fRotationMatrix[3]; + fRotationMatrix[6] = -fRotationMatrix[6]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -2739,15 +2834,16 @@ void TGeoHMatrix::ReflectX(Bool_t leftside, Bool_t rotonly) void TGeoHMatrix::ReflectY(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[1] = -fTranslation[1]; + if (leftside && !rotonly) + fTranslation[1] = -fTranslation[1]; if (leftside) { - fRotationMatrix[3]=-fRotationMatrix[3]; - fRotationMatrix[4]=-fRotationMatrix[4]; - fRotationMatrix[5]=-fRotationMatrix[5]; + fRotationMatrix[3] = -fRotationMatrix[3]; + fRotationMatrix[4] = -fRotationMatrix[4]; + fRotationMatrix[5] = -fRotationMatrix[5]; } else { - fRotationMatrix[1]=-fRotationMatrix[1]; - fRotationMatrix[4]=-fRotationMatrix[4]; - fRotationMatrix[7]=-fRotationMatrix[7]; + fRotationMatrix[1] = -fRotationMatrix[1]; + fRotationMatrix[4] = -fRotationMatrix[4]; + fRotationMatrix[7] = -fRotationMatrix[7]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -2758,15 +2854,16 @@ void TGeoHMatrix::ReflectY(Bool_t leftside, Bool_t rotonly) void TGeoHMatrix::ReflectZ(Bool_t leftside, Bool_t rotonly) { - if (leftside && !rotonly) fTranslation[2] = -fTranslation[2]; + if (leftside && !rotonly) + fTranslation[2] = -fTranslation[2]; if (leftside) { - fRotationMatrix[6]=-fRotationMatrix[6]; - fRotationMatrix[7]=-fRotationMatrix[7]; - fRotationMatrix[8]=-fRotationMatrix[8]; + fRotationMatrix[6] = -fRotationMatrix[6]; + fRotationMatrix[7] = -fRotationMatrix[7]; + fRotationMatrix[8] = -fRotationMatrix[8]; } else { - fRotationMatrix[2]=-fRotationMatrix[2]; - fRotationMatrix[5]=-fRotationMatrix[5]; - fRotationMatrix[8]=-fRotationMatrix[8]; + fRotationMatrix[2] = -fRotationMatrix[2]; + fRotationMatrix[5] = -fRotationMatrix[5]; + fRotationMatrix[8] = -fRotationMatrix[8]; } SetBit(kGeoRotation); SetBit(kGeoReflection, !IsReflection()); @@ -2777,20 +2874,32 @@ void TGeoHMatrix::ReflectZ(Bool_t leftside, Bool_t rotonly) void TGeoHMatrix::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TestBit(kGeoSavePrimitive)) return; + if (TestBit(kGeoSavePrimitive)) + return; const Double_t *tr = fTranslation; const Double_t *rot = fRotationMatrix; out << " // HMatrix: " << GetName() << std::endl; - out << " tr[0] = " << tr[0] << "; " << "tr[1] = " << tr[1] << "; " << "tr[2] = " << tr[2] << ";" << std::endl; - out << " rot[0] =" << rot[0] << "; " << "rot[1] = " << rot[1] << "; " << "rot[2] = " << rot[2] << ";" << std::endl; - out << " rot[3] =" << rot[3] << "; " << "rot[4] = " << rot[4] << "; " << "rot[5] = " << rot[5] << ";" << std::endl; - out << " rot[6] =" << rot[6] << "; " << "rot[7] = " << rot[7] << "; " << "rot[8] = " << rot[8] << ";" << std::endl; + out << " tr[0] = " << tr[0] << "; " + << "tr[1] = " << tr[1] << "; " + << "tr[2] = " << tr[2] << ";" << std::endl; + out << " rot[0] =" << rot[0] << "; " + << "rot[1] = " << rot[1] << "; " + << "rot[2] = " << rot[2] << ";" << std::endl; + out << " rot[3] =" << rot[3] << "; " + << "rot[4] = " << rot[4] << "; " + << "rot[5] = " << rot[5] << ";" << std::endl; + out << " rot[6] =" << rot[6] << "; " + << "rot[7] = " << rot[7] << "; " + << "rot[8] = " << rot[8] << ";" << std::endl; const char *name = GetPointerName(); out << " auto " << name << " = new TGeoHMatrix(\"" << GetName() << "\");" << std::endl; out << " " << name << "->SetTranslation(tr);" << std::endl; out << " " << name << "->SetRotation(rot);" << std::endl; - if (IsTranslation()) out << " " << name << "->SetBit(TGeoMatrix::kGeoTranslation);" << std::endl; - if (IsRotation()) out << " " << name << "->SetBit(TGeoMatrix::kGeoRotation);" << std::endl; - if (IsReflection()) out << " " << name << "->SetBit(TGeoMatrix::kGeoReflection);" << std::endl; + if (IsTranslation()) + out << " " << name << "->SetBit(TGeoMatrix::kGeoTranslation);" << std::endl; + if (IsRotation()) + out << " " << name << "->SetBit(TGeoMatrix::kGeoRotation);" << std::endl; + if (IsReflection()) + out << " " << name << "->SetBit(TGeoMatrix::kGeoReflection);" << std::endl; TObject::SetBit(kGeoSavePrimitive); } diff --git a/geom/geom/src/TGeoMedium.cxx b/geom/geom/src/TGeoMedium.cxx index bdc531530e018..dfed55200b1e7 100644 --- a/geom/geom/src/TGeoMedium.cxx +++ b/geom/geom/src/TGeoMedium.cxx @@ -9,7 +9,6 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ - /** \class TGeoMedium \ingroup Materials_classes @@ -35,24 +34,27 @@ ClassImp(TGeoMedium); TGeoMedium::TGeoMedium() { - fId = 0; - for (Int_t i=0; i<20; i++) fParams[i] = 0.; - fMaterial= 0; + fId = 0; + for (Int_t i = 0; i < 20; i++) + fParams[i] = 0.; + fMaterial = 0; } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoMedium::TGeoMedium(const char *name, Int_t numed, const TGeoMaterial *mat, Double_t *params) - :TNamed(name,"") +TGeoMedium::TGeoMedium(const char *name, Int_t numed, const TGeoMaterial *mat, Double_t *params) : TNamed(name, "") { fName = fName.Strip(); - fId = numed; - for (Int_t i=0; i<20; i++) fParams[i] = 0.; - fMaterial = (TGeoMaterial*)mat; - for (Int_t i=0;i<10;i++) { - if (params) fParams[i] = params[i]; - else fParams[i] = 0; + fId = numed; + for (Int_t i = 0; i < 20; i++) + fParams[i] = 0.; + fMaterial = (TGeoMaterial *)mat; + for (Int_t i = 0; i < 10; i++) { + if (params) + fParams[i] = params[i]; + else + fParams[i] = 0; } gGeoManager->GetListOfMedia()->Add(this); } @@ -60,24 +62,26 @@ TGeoMedium::TGeoMedium(const char *name, Int_t numed, const TGeoMaterial *mat, D //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoMedium::TGeoMedium(const char *name, Int_t numed, Int_t imat, Int_t isvol, Int_t ifield, - Double_t fieldm, Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin) - :TNamed(name,"") +TGeoMedium::TGeoMedium(const char *name, Int_t numed, Int_t imat, Int_t isvol, Int_t ifield, Double_t fieldm, + Double_t tmaxfd, Double_t stemax, Double_t deemax, Double_t epsil, Double_t stmin) + : TNamed(name, "") { fName = fName.Strip(); - fId = numed; - for (Int_t i=0; i<20; i++) fParams[i] = 0.; - TIter next (gGeoManager->GetListOfMaterials()); + fId = numed; + for (Int_t i = 0; i < 20; i++) + fParams[i] = 0.; + TIter next(gGeoManager->GetListOfMaterials()); TGeoMaterial *mat; - while ((mat = (TGeoMaterial*)next())) { - if (mat->GetUniqueID() == (UInt_t)imat) break; + while ((mat = (TGeoMaterial *)next())) { + if (mat->GetUniqueID() == (UInt_t)imat) + break; } if (!mat || (mat->GetUniqueID() != (UInt_t)imat)) { fMaterial = 0; - Error("TGeoMedium", "%s, material number %d does not exist",name,imat); + Error("TGeoMedium", "%s, material number %d does not exist", name, imat); return; } - fMaterial = (TGeoMaterial*)mat; + fMaterial = (TGeoMaterial *)mat; fParams[0] = isvol; fParams[1] = ifield; fParams[2] = fieldm; @@ -90,26 +94,25 @@ TGeoMedium::TGeoMedium(const char *name, Int_t numed, Int_t imat, Int_t isvol, I } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoMedium::TGeoMedium(const TGeoMedium& gm) : - TNamed(gm), - fId(gm.fId), - fMaterial(gm.fMaterial) +TGeoMedium::TGeoMedium(const TGeoMedium &gm) : TNamed(gm), fId(gm.fId), fMaterial(gm.fMaterial) { - for(Int_t i=0; i<20; i++) fParams[i]=gm.fParams[i]; + for (Int_t i = 0; i < 20; i++) + fParams[i] = gm.fParams[i]; } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoMedium& TGeoMedium::operator=(const TGeoMedium& gm) +TGeoMedium &TGeoMedium::operator=(const TGeoMedium &gm) { - if(this!=&gm) { + if (this != &gm) { TNamed::operator=(gm); - fId=gm.fId; - for(Int_t i=0; i<20; i++) fParams[i]=gm.fParams[i]; - fMaterial=gm.fMaterial; + fId = gm.fId; + for (Int_t i = 0; i < 20; i++) + fParams[i] = gm.fParams[i]; + fMaterial = gm.fMaterial; } return *this; } @@ -117,9 +120,7 @@ TGeoMedium& TGeoMedium::operator=(const TGeoMedium& gm) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoMedium::~TGeoMedium() -{ -} +TGeoMedium::~TGeoMedium() {} //////////////////////////////////////////////////////////////////////////////// /// Provide a pointer name containing uid. @@ -136,8 +137,9 @@ const char *TGeoMedium::GetPointerName() const void TGeoMedium::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - if (TestBit(TGeoMedium::kMedSavePrimitive)) return; - fMaterial->SavePrimitive(out,option); + if (TestBit(TGeoMedium::kMedSavePrimitive)) + return; + fMaterial->SavePrimitive(out, option); out << "// Medium: " << GetName() << std::endl; out << " numed = " << fId << "; // medium number" << std::endl; out << " par[0] = " << fParams[0] << "; // isvol" << std::endl; @@ -149,6 +151,7 @@ void TGeoMedium::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) out << " par[6] = " << fParams[6] << "; // epsil" << std::endl; out << " par[7] = " << fParams[7] << "; // stmin" << std::endl; - out << " auto " << GetPointerName() << " = new TGeoMedium(\"" << GetName() << "\", numed, " << fMaterial->GetPointerName() << ", par);" << std::endl; + out << " auto " << GetPointerName() << " = new TGeoMedium(\"" << GetName() << "\", numed, " + << fMaterial->GetPointerName() << ", par);" << std::endl; SetBit(TGeoMedium::kMedSavePrimitive); } diff --git a/geom/geom/src/TGeoNavigator.cxx b/geom/geom/src/TGeoNavigator.cxx index 16f40952a6565..8e9b4add35285 100644 --- a/geom/geom/src/TGeoNavigator.cxx +++ b/geom/geom/src/TGeoNavigator.cxx @@ -45,7 +45,7 @@ gGeoManager->SetCurrentNavigator(0); static Double_t gTolerance = TGeoShape::Tolerance(); const char *kGeoOutsidePath = " "; -const Int_t kN3 = 3*sizeof(Double_t); +const Int_t kN3 = 3 * sizeof(Double_t); ClassImp(TGeoNavigator); @@ -53,44 +53,44 @@ ClassImp(TGeoNavigator); /// Constructor TGeoNavigator::TGeoNavigator() - :fStep(0.), - fSafety(0.), - fLastSafety(0.), - fThreadId(0), - fLevel(0), - fNmany(0), - fNextDaughterIndex(0), - fOverlapSize(0), - fOverlapMark(0), - fOverlapClusters(0), - fSearchOverlaps(kFALSE), - fCurrentOverlapping(kFALSE), - fStartSafe(kFALSE), - fIsEntering(kFALSE), - fIsExiting(kFALSE), - fIsStepEntering(kFALSE), - fIsStepExiting(kFALSE), - fIsOutside(kFALSE), - fIsOnBoundary(kFALSE), - fIsSameLocation(kFALSE), - fIsNullStep(kFALSE), - fGeometry(0), - fCache(0), - fCurrentVolume(0), - fCurrentNode(0), - fTopNode(0), - fLastNode(0), - fNextNode(0), - fForcedNode(0), - fBackupState(0), - fCurrentMatrix(0), - fGlobalMatrix(0), - fDivMatrix(0), - fPath() + : fStep(0.), + fSafety(0.), + fLastSafety(0.), + fThreadId(0), + fLevel(0), + fNmany(0), + fNextDaughterIndex(0), + fOverlapSize(0), + fOverlapMark(0), + fOverlapClusters(0), + fSearchOverlaps(kFALSE), + fCurrentOverlapping(kFALSE), + fStartSafe(kFALSE), + fIsEntering(kFALSE), + fIsExiting(kFALSE), + fIsStepEntering(kFALSE), + fIsStepExiting(kFALSE), + fIsOutside(kFALSE), + fIsOnBoundary(kFALSE), + fIsSameLocation(kFALSE), + fIsNullStep(kFALSE), + fGeometry(0), + fCache(0), + fCurrentVolume(0), + fCurrentNode(0), + fTopNode(0), + fLastNode(0), + fNextNode(0), + fForcedNode(0), + fBackupState(0), + fCurrentMatrix(0), + fGlobalMatrix(0), + fDivMatrix(0), + fPath() { -// dummy constructor - for (Int_t i=0; i<3; i++) { + // dummy constructor + for (Int_t i = 0; i < 3; i++) { fNormal[i] = 0.; fCldir[i] = 0.; fCldirChecked[i] = 0.; @@ -103,47 +103,47 @@ TGeoNavigator::TGeoNavigator() //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoNavigator::TGeoNavigator(TGeoManager* geom) - :fStep(0.), - fSafety(0.), - fLastSafety(0.), - fThreadId(0), - fLevel(0), - fNmany(0), - fNextDaughterIndex(-2), - fOverlapSize(1000), - fOverlapMark(0), - fOverlapClusters(0), - fSearchOverlaps(kFALSE), - fCurrentOverlapping(kFALSE), - fStartSafe(kTRUE), - fIsEntering(kFALSE), - fIsExiting(kFALSE), - fIsStepEntering(kFALSE), - fIsStepExiting(kFALSE), - fIsOutside(kFALSE), - fIsOnBoundary(kFALSE), - fIsSameLocation(kTRUE), - fIsNullStep(kFALSE), - fGeometry(geom), - fCache(0), - fCurrentVolume(0), - fCurrentNode(0), - fTopNode(0), - fLastNode(0), - fNextNode(0), - fForcedNode(0), - fBackupState(0), - fCurrentMatrix(0), - fGlobalMatrix(0), - fDivMatrix(0), - fPath() +TGeoNavigator::TGeoNavigator(TGeoManager *geom) + : fStep(0.), + fSafety(0.), + fLastSafety(0.), + fThreadId(0), + fLevel(0), + fNmany(0), + fNextDaughterIndex(-2), + fOverlapSize(1000), + fOverlapMark(0), + fOverlapClusters(0), + fSearchOverlaps(kFALSE), + fCurrentOverlapping(kFALSE), + fStartSafe(kTRUE), + fIsEntering(kFALSE), + fIsExiting(kFALSE), + fIsStepEntering(kFALSE), + fIsStepExiting(kFALSE), + fIsOutside(kFALSE), + fIsOnBoundary(kFALSE), + fIsSameLocation(kTRUE), + fIsNullStep(kFALSE), + fGeometry(geom), + fCache(0), + fCurrentVolume(0), + fCurrentNode(0), + fTopNode(0), + fLastNode(0), + fNextNode(0), + fForcedNode(0), + fBackupState(0), + fCurrentMatrix(0), + fGlobalMatrix(0), + fDivMatrix(0), + fPath() { -// Default constructor. + // Default constructor. fThreadId = TGeoManager::ThreadId(); // printf("Navigator: threadId=%d\n", fThreadId); - for (Int_t i=0; i<3; i++) { + for (Int_t i = 0; i < 3; i++) { fNormal[i] = 0.; fCldir[i] = 0.; fCldirChecked[i] = 0; @@ -164,9 +164,12 @@ TGeoNavigator::TGeoNavigator(TGeoManager* geom) TGeoNavigator::~TGeoNavigator() { - if (fCache) delete fCache; - if (fBackupState) delete fBackupState; - if (fOverlapClusters) delete [] fOverlapClusters; + if (fCache) + delete fCache; + if (fBackupState) + delete fBackupState; + if (fOverlapClusters) + delete[] fOverlapClusters; } //////////////////////////////////////////////////////////////////////////////// @@ -177,17 +180,20 @@ void TGeoNavigator::BuildCache(Bool_t /*dummy*/, Bool_t nodeid) static Bool_t first = kTRUE; Int_t verbose = TGeoManager::GetVerboseLevel(); Int_t nlevel = fGeometry->GetMaxLevel(); - if (nlevel<=0) nlevel = 100; + if (nlevel <= 0) + nlevel = 100; if (!fCache) { - if (nlevel==100) { - if (first && verbose>0) Info("BuildCache","--- Maximum geometry depth set to 100"); + if (nlevel == 100) { + if (first && verbose > 0) + Info("BuildCache", "--- Maximum geometry depth set to 100"); } else { - if (first && verbose>0) Info("BuildCache","--- Maximum geometry depth is %i", nlevel); + if (first && verbose > 0) + Info("BuildCache", "--- Maximum geometry depth is %i", nlevel); } // build cache - fCache = new TGeoNodeCache(fGeometry->GetTopNode(), nodeid, nlevel+1); + fCache = new TGeoNodeCache(fGeometry->GetTopNode(), nodeid, nlevel + 1); fGlobalMatrix = fCache->GetCurrentMatrix(); - fBackupState = new TGeoCacheState(nlevel+1); + fBackupState = new TGeoCacheState(nlevel + 1); } first = kFALSE; } @@ -200,24 +206,27 @@ void TGeoNavigator::BuildCache(Bool_t /*dummy*/, Bool_t nodeid) Bool_t TGeoNavigator::cd(const char *path) { CdTop(); - if (!path[0]) return kTRUE; + if (!path[0]) + return kTRUE; TString spath = path; TGeoVolume *vol; Int_t length = spath.Length(); Int_t ind1 = spath.Index("/"); - if (ind1 == length-1) ind1 = -1; + if (ind1 == length - 1) + ind1 = -1; Int_t ind2 = 0; Bool_t end = kFALSE; Bool_t first = kTRUE; TString name; TGeoNode *node; while (!end) { - ind2 = spath.Index("/", ind1+1); - if (ind2<0 || ind2==length-1) { - if (ind2<0) ind2 = length; - end = kTRUE; + ind2 = spath.Index("/", ind1 + 1); + if (ind2 < 0 || ind2 == length - 1) { + if (ind2 < 0) + ind2 = length; + end = kTRUE; } - name = spath(ind1+1, ind2-ind1-1); + name = spath(ind1 + 1, ind2 - ind1 - 1); vol = fCurrentNode->GetVolume(); if (first) { first = kFALSE; @@ -242,25 +251,28 @@ Bool_t TGeoNavigator::cd(const char *path) Bool_t TGeoNavigator::CheckPath(const char *path) const { - if (!path[0]) return kTRUE; + if (!path[0]) + return kTRUE; TGeoNode *crtnode = fGeometry->GetTopNode(); TString spath = path; TGeoVolume *vol; Int_t length = spath.Length(); Int_t ind1 = spath.Index("/"); - if (ind1 == length-1) ind1 = -1; + if (ind1 == length - 1) + ind1 = -1; Int_t ind2 = 0; Bool_t end = kFALSE; Bool_t first = kTRUE; TString name; TGeoNode *node; while (!end) { - ind2 = spath.Index("/", ind1+1); - if (ind2<0 || ind2==length-1) { - if (ind2<0) ind2 = length; - end = kTRUE; + ind2 = spath.Index("/", ind1 + 1); + if (ind2 < 0 || ind2 == length - 1) { + if (ind2 < 0) + ind2 = length; + end = kTRUE; } - name = spath(ind1+1, ind2-ind1-1); + name = spath(ind1 + 1, ind2 - ind1 - 1); vol = crtnode->GetVolume(); if (first) { first = kFALSE; @@ -270,7 +282,8 @@ Bool_t TGeoNavigator::CheckPath(const char *path) const } } node = vol->GetNode(name.Data()); - if (!node) return kFALSE; + if (!node) + return kFALSE; crtnode = node; ind1 = ind2; } @@ -304,7 +317,8 @@ void TGeoNavigator::CdDown(Int_t index) fCache->CdDown(index); fCurrentNode = node; fGlobalMatrix = fCache->GetCurrentMatrix(); - if (fCurrentOverlapping) fNmany++; + if (fCurrentOverlapping) + fNmany++; fLevel++; } @@ -322,7 +336,8 @@ void TGeoNavigator::CdDown(TGeoNode *node) fCache->CdDown(node); fCurrentNode = node; fGlobalMatrix = fCache->GetCurrentMatrix(); - if (fCurrentOverlapping) fNmany++; + if (fCurrentOverlapping) + fNmany++; fLevel++; } @@ -332,7 +347,8 @@ void TGeoNavigator::CdDown(TGeoNode *node) void TGeoNavigator::CdUp() { - if (!fLevel || !fCache) return; + if (!fLevel || !fCache) + return; fLevel--; if (!fLevel) { CdTop(); @@ -351,7 +367,7 @@ void TGeoNavigator::CdUp() Int_t up = 1; Bool_t offset = kTRUE; TGeoNode *mother = 0; - while (offset) { + while (offset) { mother = GetMother(up++); offset = mother->IsOffset(); } @@ -365,15 +381,18 @@ void TGeoNavigator::CdUp() void TGeoNavigator::CdTop() { - if (!fCache) return; + if (!fCache) + return; fLevel = 0; fNmany = 0; - if (fCurrentOverlapping) fLastNode = fCurrentNode; + if (fCurrentOverlapping) + fLastNode = fCurrentNode; fCurrentNode = fGeometry->GetTopNode(); fCache->CdTop(); fGlobalMatrix = fCache->GetCurrentMatrix(); fCurrentOverlapping = fCurrentNode->IsOverlapping(); - if (fCurrentOverlapping) fNmany++; + if (fCurrentOverlapping) + fNmany++; } //////////////////////////////////////////////////////////////////////////////// @@ -381,8 +400,9 @@ void TGeoNavigator::CdTop() void TGeoNavigator::CdNext() { - if (fNextDaughterIndex == -2 || !fCache) return; - if (fNextDaughterIndex == -3) { + if (fNextDaughterIndex == -2 || !fCache) + return; + if (fNextDaughterIndex == -3) { // Next node is a many - restore it DoRestoreState(); fNextDaughterIndex = -2; @@ -390,14 +410,15 @@ void TGeoNavigator::CdNext() } if (fNextDaughterIndex == -1) { CdUp(); - while (fCurrentNode->GetVolume()->IsAssembly()) CdUp(); + while (fCurrentNode->GetVolume()->IsAssembly()) + CdUp(); fNextDaughterIndex--; return; } - if (fCurrentNode && fNextDaughterIndexGetNdaughters()) { + if (fCurrentNode && fNextDaughterIndex < fCurrentNode->GetNdaughters()) { CdDown(fNextDaughterIndex); Int_t nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { CdDown(nextindex); nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); } @@ -451,19 +472,19 @@ TGeoNode *TGeoNavigator::CrossDivisionCell() if (onbound) { // Work along division axis // Get the starting point - point[0] = newpoint[0] - dir[0]*fStep*(1.-gTolerance); - point[1] = newpoint[1] - dir[1]*fStep*(1.-gTolerance); - point[2] = newpoint[2] - dir[2]*fStep*(1.-gTolerance); + point[0] = newpoint[0] - dir[0] * fStep * (1. - gTolerance); + point[1] = newpoint[1] - dir[1] * fStep * (1. - gTolerance); + point[2] = newpoint[2] - dir[2] * fStep * (1. - gTolerance); // Find which is the next crossed cell. finder->FindNode(point, dir); Int_t inext = finder->GetNext(); - if (inext<0) { + if (inext < 0) { // step fully exits the division along the division axis // Do step exits in a mother cell ? if (fCurrentNode->IsOffset()) { - Double_t dist = fCurrentNode->GetVolume()->GetShape()->DistFromInside(point,dir,3); + Double_t dist = fCurrentNode->GetVolume()->GetShape()->DistFromInside(point, dir, 3); // Do step exit also from mother cell ? - if (dist < fStep+2.*gTolerance) { + if (dist < fStep + 2. * gTolerance) { // Step exits mother on its own division axis return CrossDivisionCell(); } @@ -474,18 +495,20 @@ TGeoNode *TGeoNavigator::CrossDivisionCell() while (fCurrentNode->GetVolume()->IsAssembly()) { // Move always to mother for assemblies skip = fCurrentNode; - if (!fLevel) break; + if (!fLevel) + break; CdUp(); } return CrossBoundaryAndLocate(kFALSE, skip); } // step enters a new cell - CdDown(inext+finder->GetDivIndex()); + CdDown(inext + finder->GetDivIndex()); skip = fCurrentNode; return CrossBoundaryAndLocate(kTRUE, skip); } // step exits on an axis other than the division axis -> get next slice - if (fCurrentNode->IsOffset()) return CrossDivisionCell(); + if (fCurrentNode->IsOffset()) + return CrossDivisionCell(); return CrossBoundaryAndLocate(kFALSE, skip); } @@ -495,40 +518,42 @@ TGeoNode *TGeoNavigator::CrossDivisionCell() TGeoNode *TGeoNavigator::CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skipnode) { -// Extrapolate current point with estimated error. + // Extrapolate current point with estimated error. Double_t *tr = fGlobalMatrix->GetTranslation(); - Double_t trmax = 1.+TMath::Abs(tr[0])+TMath::Abs(tr[1])+TMath::Abs(tr[2]); - Double_t extra = 100.*(trmax+fStep)*gTolerance; + Double_t trmax = 1. + TMath::Abs(tr[0]) + TMath::Abs(tr[1]) + TMath::Abs(tr[2]); + Double_t extra = 100. * (trmax + fStep) * gTolerance; const Int_t idebug = TGeoManager::GetVerboseLevel(); TGeoNode *crtstate[10]; - Int_t level = fLevel+1; + Int_t level = fLevel + 1; Bool_t samepath = kFALSE; - for (Int_t i=0; i<10; ++i) + for (Int_t i = 0; i < 10; ++i) crtstate[i] = nullptr; if (!downwards) { - for (Int_t i=0; iGetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { CdDown(nextindex); current = fCurrentNode; nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); } - if (idebug>4) { + if (idebug > 4) { printf("CrossBoundaryAndLocate: entered %s\n", GetPath()); } return current; @@ -538,12 +563,12 @@ TGeoNode *TGeoNavigator::CrossBoundaryAndLocate(Bool_t downwards, TGeoNode *skip if (current == skipnode) { samepath = kTRUE; if (!downwards) { - level = TMath::Min(level, 10); - for (Int_t i=1; iGetVolume()->IsAssembly()) { if (!fLevel) { fIsOutside = kTRUE; - if (idebug>4) { + if (idebug > 4) { printf("CrossBoundaryAndLocate: Exited geometry\n"); } return fGeometry->GetCurrentNode(); } CdUp(); - while (fLevel && fCurrentNode->GetVolume()->IsAssembly()) CdUp(); + while (fLevel && fCurrentNode->GetVolume()->IsAssembly()) + CdUp(); if (!fLevel && fCurrentNode->GetVolume()->IsAssembly()) { fIsOutside = kTRUE; - if (idebug>4) { + if (idebug > 4) { printf("CrossBoundaryAndLocate: Exited geometry\n"); } - if (idebug>4) { + if (idebug > 4) { printf("CrossBoundaryAndLocate: entered %s\n", GetPath()); } return fCurrentNode; } return fCurrentNode; } - if (idebug>4) { + if (idebug > 4) { printf("CrossBoundaryAndLocate: entered %s\n", GetPath()); } return current; @@ -607,16 +633,17 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo TGeoNode *top_node = fGeometry->GetTopNode(); TGeoVolume *top_volume = top_node->GetVolume(); // If inside an assembly, go logically up in the hierarchy - while (fCurrentNode->GetVolume()->IsAssembly() && fLevel) CdUp(); - if (stepmax<1E29) { + while (fCurrentNode->GetVolume()->IsAssembly() && fLevel) + CdUp(); + if (stepmax < 1E29) { if (stepmax <= 0) { - stepmax = - stepmax; + stepmax = -stepmax; computeGlobal = kTRUE; } -// if (fLastSafety>0 && IsSamePoint(fPoint[0], fPoint[1], fPoint[2])) fSafety = fLastSafety; + // if (fLastSafety>0 && IsSamePoint(fPoint[0], fPoint[1], fPoint[2])) fSafety = fLastSafety; fSafety = Safety(); // Try to get out easy if proposed step within safe region - if (!frombdr && (fSafety>0) && IsSafeStep(stepmax+gTolerance, fSafety)) { + if (!frombdr && (fSafety > 0) && IsSafeStep(stepmax + gTolerance, fSafety)) { fStep = stepmax; fNextNode = fCurrentNode; return fCurrentNode; @@ -624,24 +651,26 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo fSafety = TMath::Abs(fSafety); memcpy(fLastPoint, fPoint, kN3); fLastSafety = fSafety; - if (fSafetyCopyFrom(fGlobalMatrix); - Double_t snext = TGeoShape::Big(); + if (computeGlobal) + fCurrentMatrix->CopyFrom(fGlobalMatrix); + Double_t snext = TGeoShape::Big(); Double_t safe; Double_t point[3]; Double_t dir[3]; - if (idebug>4) { - printf("TGeoManager::FindNextBoundary: point=(%19.16f, %19.16f, %19.16f)\n", - fPoint[0],fPoint[1],fPoint[2]); - printf(" dir= (%19.16f, %19.16f, %19.16f)\n", - fDirection[0], fDirection[1], fDirection[2]); + if (idebug > 4) { + printf("TGeoManager::FindNextBoundary: point=(%19.16f, %19.16f, %19.16f)\n", fPoint[0], fPoint[1], fPoint[2]); + printf(" dir= (%19.16f, %19.16f, %19.16f)\n", fDirection[0], fDirection[1], + fDirection[2]); printf(" pstep=%9.6g path=%s\n", stepmax, GetPath()); } if (path[0]) { @@ -650,39 +679,41 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo PopPath(); return 0; } - if (computeGlobal) fCurrentMatrix->CopyFrom(fGlobalMatrix); + if (computeGlobal) + fCurrentMatrix->CopyFrom(fGlobalMatrix); fNextNode = fCurrentNode; - TGeoVolume *tvol=fCurrentNode->GetVolume(); + TGeoVolume *tvol = fCurrentNode->GetVolume(); fGlobalMatrix->MasterToLocal(fPoint, &point[0]); fGlobalMatrix->MasterToLocalVect(fDirection, &dir[0]); - if (idebug>4) { + if (idebug > 4) { printf("=== To path: %s\n", path); - printf("=== local to %s: (%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", - tvol->GetName(), point[0],point[1],point[2],dir[0],dir[1],dir[2]); + printf("=== local to %s: (%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", tvol->GetName(), point[0], + point[1], point[2], dir[0], dir[1], dir[2]); } if (tvol->Contains(point)) { - if (idebug>4) printf("=== volume %s contains point\n", tvol->GetName()); - fStep=tvol->GetShape()->DistFromInside(&point[0], &dir[0], iact, fStep, &safe); + if (idebug > 4) + printf("=== volume %s contains point\n", tvol->GetName()); + fStep = tvol->GetShape()->DistFromInside(&point[0], &dir[0], iact, fStep, &safe); } else { - fStep=tvol->GetShape()->DistFromOutside(&point[0], &dir[0], iact, fStep, &safe); - if (idebug>4) { + fStep = tvol->GetShape()->DistFromOutside(&point[0], &dir[0], iact, fStep, &safe); + if (idebug > 4) { printf("=== volume %s does not contain point\n", tvol->GetName()); printf("=== distance to path: %g\n", fStep); tvol->InspectShape(); - if (fStep<1.E20) { + if (fStep < 1.E20) { Double_t newpt[3]; - newpt[0] = point[0] + fStep*dir[0]; - newpt[1] = point[1] + fStep*dir[1]; - newpt[2] = point[2] + fStep*dir[2]; - printf("=== Propagated point: (%19.16f, %19.16f, %19.16f)", newpt[0],newpt[1],newpt[2]); + newpt[0] = point[0] + fStep * dir[0]; + newpt[1] = point[1] + fStep * dir[1]; + newpt[2] = point[2] + fStep * dir[2]; + printf("=== Propagated point: (%19.16f, %19.16f, %19.16f)", newpt[0], newpt[1], newpt[2]); } while (fLevel) { CdUp(); tvol = fCurrentNode->GetVolume(); fGlobalMatrix->MasterToLocal(fPoint, &point[0]); fGlobalMatrix->MasterToLocalVect(fDirection, &dir[0]); - printf("=== local to %s: (%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", - tvol->GetName(), point[0],point[1],point[2],dir[0],dir[1],dir[2]); + printf("=== local to %s: (%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", tvol->GetName(), + point[0], point[1], point[2], dir[0], dir[1], dir[2]); if (tvol->Contains(point)) { printf("=== volume %s contains point\n", tvol->GetName()); } else { @@ -701,14 +732,15 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo if (fIsOutside) { snext = top_volume->GetShape()->DistFromOutside(fPoint, fDirection, iact, fStep, &safe); fNextNode = top_node; - if (snext < fStep-gTolerance) { + if (snext < fStep - gTolerance) { fIsStepEntering = kTRUE; fStep = snext; Int_t indnext = fNextNode->GetVolume()->GetNextNodeIndex(); fNextDaughterIndex = indnext; - while (indnext>=0) { + while (indnext >= 0) { fNextNode = fNextNode->GetDaughter(indnext); - if (computeGlobal) fCurrentMatrix->Multiply(fNextNode->GetMatrix()); + if (computeGlobal) + fCurrentMatrix->Multiply(fNextNode->GetMatrix()); indnext = fNextNode->GetVolume()->GetNextNodeIndex(); } return fNextNode; @@ -718,30 +750,30 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo fGlobalMatrix->MasterToLocal(fPoint, &point[0]); fGlobalMatrix->MasterToLocalVect(fDirection, &dir[0]); TGeoVolume *vol = fCurrentNode->GetVolume(); - if (idebug>4) { - printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", - point[0],point[1],point[2]); - printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", - dir[0],dir[1],dir[2]); + if (idebug > 4) { + printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", point[0], point[1], point[2]); + printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", dir[0], dir[1], dir[2]); } // find distance to exiting current node snext = vol->GetShape()->DistFromInside(&point[0], &dir[0], iact, fStep, &safe); - if (idebug>4) { - printf(" exiting %s shape %s at snext=%g\n", vol->GetName(), vol->GetShape()->ClassName(),snext); + if (idebug > 4) { + printf(" exiting %s shape %s at snext=%g\n", vol->GetName(), vol->GetShape()->ClassName(), snext); } - if (snext < fStep-gTolerance) { + if (snext < fStep - gTolerance) { fNextNode = fCurrentNode; fNextDaughterIndex = -1; - fIsStepExiting = kTRUE; + fIsStepExiting = kTRUE; fStep = snext; fIsStepEntering = kFALSE; - if (fStep<1E-6) return fCurrentNode; + if (fStep < 1E-6) + return fCurrentNode; } - fNextNode = (fStep<1E20)?fCurrentNode:0; + fNextNode = (fStep < 1E20) ? fCurrentNode : 0; // Find next daughter boundary for the current volume Int_t idaughter = -1; - FindNextDaughterBoundary(point,dir,idaughter,computeGlobal); - if (idaughter>=0) fNextDaughterIndex = idaughter; + FindNextDaughterBoundary(point, dir, idaughter, computeGlobal); + if (idaughter >= 0) + fNextDaughterIndex = idaughter; TGeoNode *current = 0; TGeoNode *dnode = 0; TGeoVolume *mother = 0; @@ -753,7 +785,7 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo Int_t novlps; Int_t idovlp = -1; Int_t safelevel = GetSafeLevel(); - PushPath(safelevel+1); + PushPath(safelevel + 1); while (fCurrentOverlapping) { Int_t *ovlps = fCurrentNode->GetOverlaps(novlps); CdUp(); @@ -762,18 +794,20 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo fGlobalMatrix->MasterToLocalVect(fDirection, &vecpt[0]); // check distance to out snext = TGeoShape::Big(); - if (!mother->IsAssembly()) snext = mother->GetShape()->DistFromInside(&mothpt[0], &vecpt[0], iact, fStep, &safe); - if (snextIsAssembly()) + snext = mother->GetShape()->DistFromInside(&mothpt[0], &vecpt[0], iact, fStep, &safe); + if (snext < fStep - gTolerance) { + fIsStepExiting = kTRUE; fIsStepEntering = kFALSE; fStep = snext; - if (computeGlobal) fCurrentMatrix->CopyFrom(fGlobalMatrix); + if (computeGlobal) + fCurrentMatrix->CopyFrom(fGlobalMatrix); fNextNode = fCurrentNode; fNextDaughterIndex = -3; DoBackupState(); } // check overlapping nodes - for (Int_t i=0; iGetNode(ovlps[i]); if (!current->IsOverlapping()) { current->cd(); @@ -781,12 +815,12 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo current->MasterToLocalVect(&vecpt[0], &dvec[0]); // Current point may be inside the other node - geometry error that we ignore snext = current->GetVolume()->GetShape()->DistFromOutside(&dpt[0], &dvec[0], iact, fStep, &safe); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kTRUE; + fIsStepExiting = kTRUE; fIsStepEntering = kFALSE; fStep = snext; fNextNode = current; @@ -803,9 +837,9 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo if (current->GetVolume()->Contains(dpt)) { if (current->GetVolume()->GetNdaughters()) { CdDown(ovlps[i]); - fIsStepEntering = kFALSE; - fIsStepExiting = kTRUE; - dnode = FindNextDaughterBoundary(dpt,dvec,idovlp,computeGlobal); + fIsStepEntering = kFALSE; + fIsStepExiting = kTRUE; + dnode = FindNextDaughterBoundary(dpt, dvec, idovlp, computeGlobal); if (dnode) { if (computeGlobal) { fCurrentMatrix->CopyFrom(fGlobalMatrix); @@ -815,14 +849,14 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo fNextDaughterIndex = -3; CdDown(idovlp); Int_t indnext = fCurrentNode->GetVolume()->GetNextNodeIndex(); - Int_t iup=0; - while (indnext>=0) { + Int_t iup = 0; + while (indnext >= 0) { CdDown(indnext); iup++; indnext = fCurrentNode->GetVolume()->GetNextNodeIndex(); } DoBackupState(); - while (iup>0) { + while (iup > 0) { CdUp(); iup--; } @@ -832,12 +866,12 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo } } else { snext = current->GetVolume()->GetShape()->DistFromOutside(&dpt[0], &dvec[0], iact, fStep, &safe); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kTRUE; + fIsStepExiting = kTRUE; fIsStepEntering = kFALSE; fStep = snext; fNextNode = current; @@ -852,7 +886,7 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo } // Now we are in a non-overlapping node if (fNmany) { - // We have overlaps up in the branch, check distance to exit + // We have overlaps up in the branch, check distance to exit Int_t up = 1; Int_t imother; Int_t nmany = fNmany; @@ -869,7 +903,7 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo return 0; } mup = mothernode; - imother = up+1; + imother = up + 1; offset = kFALSE; while (mup->IsOffset()) { mup = GetMother(imother++); @@ -878,10 +912,12 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo nextovlp = mup->IsOverlapping(); if (offset) { mothernode = mup; - if (nextovlp) nmany -= imother-up; - up = imother-1; + if (nextovlp) + nmany -= imother - up; + up = imother - 1; } else { - if (ovlp) nmany--; + if (ovlp) + nmany--; } if (ovlp || nextovlp) { matrix = GetMotherMatrix(up); @@ -889,18 +925,21 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo Fatal("FindNextBoundary", "Cannot find mother matrix"); return 0; } - matrix->MasterToLocal(fPoint,dpt); - matrix->MasterToLocalVect(fDirection,dvec); + matrix->MasterToLocal(fPoint, dpt); + matrix->MasterToLocalVect(fDirection, dvec); snext = TGeoShape::Big(); - if (!mothernode->GetVolume()->IsAssembly()) snext = mothernode->GetVolume()->GetShape()->DistFromInside(dpt,dvec,iact,fStep); - if (snextGetVolume()->IsAssembly()) + snext = mothernode->GetVolume()->GetShape()->DistFromInside(dpt, dvec, iact, fStep); + if (snext < fStep - gTolerance) { + fIsStepEntering = kFALSE; + fIsStepExiting = kTRUE; fStep = snext; fNextNode = mothernode; fNextDaughterIndex = -3; - if (computeGlobal) fCurrentMatrix->CopyFrom(matrix); - while (up--) CdUp(); + if (computeGlobal) + fCurrentMatrix->CopyFrom(matrix); + while (up--) + CdUp(); DoBackupState(); up = 1; currentnode = fCurrentNode; @@ -918,17 +957,17 @@ TGeoNode *TGeoNavigator::FindNextBoundary(Double_t stepmax, const char *path, Bo // Compute now the distance in case we have a parallel world Double_t parstep = TGeoShape::Big(); if (fGeometry->IsParallelWorldNav()) { -// printf("path: %s next node %s at %g\n", GetPath(), fNextNode->GetName(), fStep); + // printf("path: %s next node %s at %g\n", GetPath(), fNextNode->GetName(), fStep); TGeoPhysicalNode *pnode = fGeometry->GetParallelWorld()->FindNextBoundary(fPoint, fDirection, parstep, fStep); if (pnode) { // A boundary is hit at less than fPStep fStep = parstep; fNextNode = pnode->GetNode(); fNextDaughterIndex = -2; // No way to store it for CdNext - fIsStepEntering = kTRUE; - fIsStepExiting = kFALSE; + fIsStepEntering = kTRUE; + fIsStepExiting = kFALSE; Int_t nextindex = fNextNode->GetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { fNextNode = fNextNode->GetDaughter(nextindex); nextindex = fNextNode->GetVolume()->GetNextNodeIndex(); } @@ -952,60 +991,67 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir TGeoVolume *vol = fCurrentNode->GetVolume(); Int_t nd = vol->GetNdaughters(); - if (!nd) return 0; // No daughter - if (fGeometry->IsActivityEnabled() && !vol->IsActiveDaughters()) return 0; + if (!nd) + return 0; // No daughter + if (fGeometry->IsActivityEnabled() && !vol->IsActiveDaughters()) + return 0; Double_t lpoint[3], ldir[3]; TGeoNode *current = 0; - Int_t i=0; + Int_t i = 0; // if current volume is divided, we are in the non-divided region. We // check first if we are inside a cell in which case compute distance to next cell TGeoPatternFinder *finder = vol->GetFinder(); if (finder) { Int_t ifirst = finder->GetDivIndex(); - Int_t ilast = ifirst+finder->GetNdiv()-1; + Int_t ilast = ifirst + finder->GetNdiv() - 1; current = finder->FindNode(point); if (current) { // Point inside a cell: find distance to next cell Int_t index = current->GetIndex(); - if ((index-1) >= ifirst) ifirst = index-1; - else ifirst = -1; - if ((index+1) <= ilast) ilast = index+1; - else ilast = -1; - } - if (ifirst>=0) { + if ((index - 1) >= ifirst) + ifirst = index - 1; + else + ifirst = -1; + if ((index + 1) <= ilast) + ilast = index + 1; + else + ilast = -1; + } + if (ifirst >= 0) { current = vol->GetNode(ifirst); current->cd(); current->MasterToLocal(&point[0], lpoint); current->MasterToLocalVect(&dir[0], ldir); snext = current->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, fStep); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kFALSE; + fIsStepExiting = kFALSE; fIsStepEntering = kTRUE; - fStep=snext; + fStep = snext; fNextNode = current; nodefound = current; idaughter = ifirst; } } - if (ilast==ifirst) return nodefound; - if (ilast>=0) { + if (ilast == ifirst) + return nodefound; + if (ilast >= 0) { current = vol->GetNode(ilast); current->cd(); current->MasterToLocal(&point[0], lpoint); current->MasterToLocalVect(&dir[0], ldir); snext = current->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, fStep); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kFALSE; + fIsStepExiting = kFALSE; fIsStepEntering = kTRUE; - fStep=snext; + fStep = snext; fNextNode = current; nodefound = current; idaughter = ilast; @@ -1016,25 +1062,26 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir // if only few daughters, check all and exit TGeoVoxelFinder *voxels = vol->GetVoxels(); Int_t indnext; - if (idebug>4) printf(" Checking distance to %d daughters...\n",nd); - if (nd<5 || !voxels) { - for (i=0; i 4) + printf(" Checking distance to %d daughters...\n", nd); + if (nd < 5 || !voxels) { + for (i = 0; i < nd; i++) { current = vol->GetNode(i); - if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) continue; + if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) + continue; current->cd(); - if (voxels && voxels->IsSafeVoxel(point, i, fStep)) continue; + if (voxels && voxels->IsSafeVoxel(point, i, fStep)) + continue; current->MasterToLocal(point, lpoint); current->MasterToLocalVect(dir, ldir); - if (current->IsOverlapping() && - current->GetVolume()->Contains(lpoint) && - current->GetVolume()->GetShape()->Safety(lpoint, kTRUE) > gTolerance) continue; + if (current->IsOverlapping() && current->GetVolume()->Contains(lpoint) && + current->GetVolume()->GetShape()->Safety(lpoint, kTRUE) > gTolerance) + continue; snext = current->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, fStep); - if (snext4) { - printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", - lpoint[0],lpoint[1],lpoint[2]); - printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", - ldir[0],ldir[1],ldir[2]); + if (snext < fStep - gTolerance) { + if (idebug > 4) { + printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", lpoint[0], lpoint[1], lpoint[2]); + printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", ldir[0], ldir[1], ldir[2]); printf(" -> to: %s shape %s snext=%g\n", current->GetName(), current->GetVolume()->GetShape()->ClassName(), snext); } @@ -1043,22 +1090,24 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir fCurrentMatrix->CopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kFALSE; + fIsStepExiting = kFALSE; fIsStepEntering = kTRUE; - fStep=snext; + fStep = snext; fNextNode = current; nodefound = fNextNode; idaughter = i; - while (indnext>=0) { + while (indnext >= 0) { current = current->GetDaughter(indnext); - if (compmatrix) fCurrentMatrix->Multiply(current->GetMatrix()); + if (compmatrix) + fCurrentMatrix->Multiply(current->GetMatrix()); fNextNode = current; nodefound = current; indnext = current->GetVolume()->GetNextNodeIndex(); } } } - if (vol->IsAssembly()) ((TGeoVolumeAssembly*)vol)->SetNextNodeIndex(idaughter); + if (vol->IsAssembly()) + ((TGeoVolumeAssembly *)vol)->SetNextNodeIndex(idaughter); return nodefound; } // if current volume is voxelized, first get current voxel @@ -1067,24 +1116,24 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir Int_t *vlist = 0; TGeoStateInfo &info = *fCache->GetInfo(); voxels->SortCrossedVoxels(point, dir, info); - while ((sumcheckedGetNextVoxel(point, dir, ncheck, info))) { - for (i=0; iGetNextVoxel(point, dir, ncheck, info))) { + for (i = 0; i < ncheck; i++) { current = vol->GetNode(vlist[i]); - if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) continue; + if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) + continue; current->cd(); current->MasterToLocal(point, lpoint); current->MasterToLocalVect(dir, ldir); if (current->IsOverlapping() && current->GetVolume()->Contains(lpoint) && - current->GetVolume()->GetShape()->Safety(lpoint, kTRUE) > gTolerance) continue; + current->GetVolume()->GetShape()->Safety(lpoint, kTRUE) > gTolerance) + continue; snext = current->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, fStep); sumchecked++; -// printf("checked %d from %d : snext=%g\n", sumchecked, nd, snext); - if (snext4) { - printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", - lpoint[0],lpoint[1],lpoint[2]); - printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", - ldir[0],ldir[1],ldir[2]); + // printf("checked %d from %d : snext=%g\n", sumchecked, nd, snext); + if (snext < fStep - gTolerance) { + if (idebug > 4) { + printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", lpoint[0], lpoint[1], lpoint[2]); + printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", ldir[0], ldir[1], ldir[2]); printf(" -> to: %s shape %s snext=%g\n", current->GetName(), current->GetVolume()->GetShape()->ClassName(), snext); } @@ -1093,15 +1142,16 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir fCurrentMatrix->CopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); } - fIsStepExiting = kFALSE; + fIsStepExiting = kFALSE; fIsStepEntering = kTRUE; - fStep=snext; + fStep = snext; fNextNode = current; nodefound = fNextNode; idaughter = vlist[i]; - while (indnext>=0) { + while (indnext >= 0) { current = current->GetDaughter(indnext); - if (compmatrix) fCurrentMatrix->Multiply(current->GetMatrix()); + if (compmatrix) + fCurrentMatrix->Multiply(current->GetMatrix()); fNextNode = current; nodefound = current; indnext = current->GetVolume()->GetNextNodeIndex(); @@ -1110,7 +1160,8 @@ TGeoNode *TGeoNavigator::FindNextDaughterBoundary(Double_t *point, Double_t *dir } } fCache->ReleaseInfo(); - if (vol->IsAssembly()) ((TGeoVolumeAssembly*)vol)->SetNextNodeIndex(idaughter); + if (vol->IsAssembly()) + ((TGeoVolumeAssembly *)vol)->SetNextNodeIndex(idaughter); return nodefound; } @@ -1127,83 +1178,84 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa Int_t nextindex; Bool_t is_assembly; fForcedNode = 0; - fIsStepExiting = kFALSE; + fIsStepExiting = kFALSE; TGeoNode *skip; fIsStepEntering = kFALSE; fStep = stepmax; Double_t snext = TGeoShape::Big(); // If inside an assembly, go logically up in the hierarchy - while (fCurrentNode->GetVolume()->IsAssembly() && fLevel) CdUp(); + while (fCurrentNode->GetVolume()->IsAssembly() && fLevel) + CdUp(); if (compsafe) { // Try to get out easy if proposed step within safe region fIsOnBoundary = kFALSE; - if (IsSafeStep(stepmax+gTolerance, fSafety)) { - fPoint[0] += stepmax*fDirection[0]; - fPoint[1] += stepmax*fDirection[1]; - fPoint[2] += stepmax*fDirection[2]; + if (IsSafeStep(stepmax + gTolerance, fSafety)) { + fPoint[0] += stepmax * fDirection[0]; + fPoint[1] += stepmax * fDirection[1]; + fPoint[2] += stepmax * fDirection[2]; return fCurrentNode; } Safety(); fLastSafety = fSafety; memcpy(fLastPoint, fPoint, kN3); // If proposed step less than safety, nothing to check - if (fSafety > stepmax+gTolerance) { - fPoint[0] += stepmax*fDirection[0]; - fPoint[1] += stepmax*fDirection[1]; - fPoint[2] += stepmax*fDirection[2]; + if (fSafety > stepmax + gTolerance) { + fPoint[0] += stepmax * fDirection[0]; + fPoint[1] += stepmax * fDirection[1]; + fPoint[2] += stepmax * fDirection[2]; return fCurrentNode; } } - Double_t extra = (fIsOnBoundary)?gTolerance:0.0; + Double_t extra = (fIsOnBoundary) ? gTolerance : 0.0; fIsOnBoundary = kFALSE; - fPoint[0] += extra*fDirection[0]; - fPoint[1] += extra*fDirection[1]; - fPoint[2] += extra*fDirection[2]; + fPoint[0] += extra * fDirection[0]; + fPoint[1] += extra * fDirection[1]; + fPoint[2] += extra * fDirection[2]; fCurrentMatrix->CopyFrom(fGlobalMatrix); - if (idebug>4) { - printf("TGeoManager::FindNextBAndStep: point=(%19.16f, %19.16f, %19.16f)\n", - fPoint[0],fPoint[1],fPoint[2]); - printf(" dir= (%19.16f, %19.16f, %19.16f)\n", - fDirection[0], fDirection[1], fDirection[2]); + if (idebug > 4) { + printf("TGeoManager::FindNextBAndStep: point=(%19.16f, %19.16f, %19.16f)\n", fPoint[0], fPoint[1], fPoint[2]); + printf(" dir= (%19.16f, %19.16f, %19.16f)\n", fDirection[0], fDirection[1], + fDirection[2]); printf(" pstep=%9.6g path=%s\n", stepmax, GetPath()); } if (fIsOutside) { snext = fGeometry->GetTopVolume()->GetShape()->DistFromOutside(fPoint, fDirection, iact, fStep); - if (snext < fStep-gTolerance) { - if (snext<=0) { + if (snext < fStep - gTolerance) { + if (snext <= 0) { snext = 0.0; fStep = snext; - fPoint[0] -= extra*fDirection[0]; - fPoint[1] -= extra*fDirection[1]; - fPoint[2] -= extra*fDirection[2]; + fPoint[0] -= extra * fDirection[0]; + fPoint[1] -= extra * fDirection[1]; + fPoint[2] -= extra * fDirection[2]; } else { - fStep = snext+extra; + fStep = snext + extra; } fIsStepEntering = kTRUE; fNextNode = fGeometry->GetTopNode(); nextindex = fNextNode->GetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { CdDown(nextindex); fNextNode = fCurrentNode; nextindex = fNextNode->GetVolume()->GetNextNodeIndex(); - if (nextindex<0) fCurrentMatrix->CopyFrom(fGlobalMatrix); + if (nextindex < 0) + fCurrentMatrix->CopyFrom(fGlobalMatrix); } // Update global point - fPoint[0] += snext*fDirection[0]; - fPoint[1] += snext*fDirection[1]; - fPoint[2] += snext*fDirection[2]; + fPoint[0] += snext * fDirection[0]; + fPoint[1] += snext * fDirection[1]; + fPoint[2] += snext * fDirection[2]; fIsOnBoundary = kTRUE; fIsOutside = kFALSE; fForcedNode = fCurrentNode; return CrossBoundaryAndLocate(kTRUE, fCurrentNode); } - if (snextGetTopNode(); - fPoint[0] += (fStep-extra)*fDirection[0]; - fPoint[1] += (fStep-extra)*fDirection[1]; - fPoint[2] += (fStep-extra)*fDirection[2]; + fPoint[0] += (fStep - extra) * fDirection[0]; + fPoint[1] += (fStep - extra) * fDirection[1]; + fPoint[2] += (fStep - extra) * fDirection[2]; return fNextNode; } // top node not reachable from current point/direction @@ -1211,22 +1263,20 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fIsOnBoundary = kFALSE; return 0; } - Double_t point[3],dir[3]; + Double_t point[3], dir[3]; Int_t icrossed = -2; fGlobalMatrix->MasterToLocal(fPoint, &point[0]); fGlobalMatrix->MasterToLocalVect(fDirection, &dir[0]); TGeoVolume *vol = fCurrentNode->GetVolume(); // find distance to exiting current node - if (idebug>4) { - printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", - point[0],point[1],point[2]); - printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", - dir[0],dir[1],dir[2]); + if (idebug > 4) { + printf(" -> from local=(%19.16f, %19.16f, %19.16f)\n", point[0], point[1], point[2]); + printf(" ldir =(%19.16f, %19.16f, %19.16f)\n", dir[0], dir[1], dir[2]); } // find distance to exiting current node snext = vol->GetShape()->DistFromInside(point, dir, iact, fStep); - if (idebug>4) { - printf(" exiting %s shape %s at snext=%g\n", vol->GetName(), vol->GetShape()->ClassName(),snext); + if (idebug > 4) { + printf(" exiting %s shape %s at snext=%g\n", vol->GetName(), vol->GetShape()->ClassName(), snext); } fNextNode = fCurrentNode; if (snext <= gTolerance) { @@ -1237,21 +1287,24 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fIsStepEntering = kFALSE; fIsStepExiting = kTRUE; skip = fCurrentNode; - fPoint[0] += fStep*fDirection[0]; - fPoint[1] += fStep*fDirection[1]; - fPoint[2] += fStep*fDirection[2]; + fPoint[0] += fStep * fDirection[0]; + fPoint[1] += fStep * fDirection[1]; + fPoint[2] += fStep * fDirection[2]; is_assembly = fCurrentNode->GetVolume()->IsAssembly(); if (!fLevel && !is_assembly) { fIsOutside = kTRUE; return 0; } - if (fCurrentNode->IsOffset()) return CrossDivisionCell(); - if (fLevel) CdUp(); - else skip = 0; + if (fCurrentNode->IsOffset()) + return CrossDivisionCell(); + if (fLevel) + CdUp(); + else + skip = 0; return CrossBoundaryAndLocate(kFALSE, skip); } - if (snext < fStep-gTolerance) { + if (snext < fStep - gTolerance) { // Currently the minimum step chosen is the exiting one icrossed = -1; fStep = snext; @@ -1260,7 +1313,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa } // Find next daughter boundary for the current volume Int_t idaughter = -1; - TGeoNode *crossed = FindNextDaughterBoundary(point,dir, idaughter, kTRUE); + TGeoNode *crossed = FindNextDaughterBoundary(point, dir, idaughter, kTRUE); if (crossed) { fIsStepExiting = kFALSE; icrossed = idaughter; @@ -1276,7 +1329,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa Double_t dpt[3], dvec[3]; Int_t novlps; Int_t safelevel = GetSafeLevel(); - PushPath(safelevel+1); + PushPath(safelevel + 1); while (fCurrentOverlapping) { Int_t *ovlps = fCurrentNode->GetOverlaps(novlps); CdUp(); @@ -1285,12 +1338,13 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fGlobalMatrix->MasterToLocalVect(fDirection, &vecpt[0]); // check distance to out snext = TGeoShape::Big(); - if (!mother->IsAssembly()) snext = mother->GetShape()->DistFromInside(mothpt, vecpt, iact, fStep); - if (snextIsAssembly()) + snext = mother->GetShape()->DistFromInside(mothpt, vecpt, iact, fStep); + if (snext < fStep - gTolerance) { // exiting mother first (extrusion) icrossed = -1; PopDummy(); - PushPath(safelevel+1); + PushPath(safelevel + 1); fIsStepEntering = kFALSE; fIsStepExiting = kTRUE; fStep = snext; @@ -1298,16 +1352,16 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fNextNode = fCurrentNode; } // check overlapping nodes - for (Int_t i=0; iGetNode(ovlps[i]); if (!current->IsOverlapping()) { current->cd(); current->MasterToLocal(&mothpt[0], &dpt[0]); current->MasterToLocalVect(&vecpt[0], &dvec[0]); snext = current->GetVolume()->GetShape()->DistFromOutside(dpt, dvec, iact, fStep); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); fIsStepEntering = kFALSE; @@ -1324,13 +1378,13 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa if (current->GetVolume()->Contains(dpt)) { if (current->GetVolume()->GetNdaughters()) { CdDown(ovlps[i]); - dnode = FindNextDaughterBoundary(dpt,dvec,idaughter,kFALSE); + dnode = FindNextDaughterBoundary(dpt, dvec, idaughter, kFALSE); if (dnode) { fCurrentMatrix->CopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(dnode->GetMatrix()); icrossed = idaughter; PopDummy(); - PushPath(safelevel+1); + PushPath(safelevel + 1); fIsStepEntering = kFALSE; fIsStepExiting = kTRUE; fNextNode = dnode; @@ -1339,7 +1393,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa } } else { snext = current->GetVolume()->GetShape()->DistFromOutside(dpt, dvec, iact, fStep); - if (snextCopyFrom(fGlobalMatrix); fCurrentMatrix->Multiply(current->GetMatrix()); fIsStepEntering = kFALSE; @@ -1348,7 +1402,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fNextNode = current; icrossed = ovlps[i]; PopDummy(); - PushPath(safelevel+1); + PushPath(safelevel + 1); } } } @@ -1356,7 +1410,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa } // Now we are in a non-overlapping node if (fNmany) { - // We have overlaps up in the branch, check distance to exit + // We have overlaps up in the branch, check distance to exit Int_t up = 1; Int_t imother; Int_t nmany = fNmany; @@ -1369,7 +1423,7 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa while (nmany) { mothernode = GetMother(up); mup = mothernode; - imother = up+1; + imother = up + 1; offset = kFALSE; while (mup->IsOffset()) { mup = GetMother(imother++); @@ -1378,24 +1432,28 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa nextovlp = mup->IsOverlapping(); if (offset) { mothernode = mup; - if (nextovlp) nmany -= imother-up; - up = imother-1; + if (nextovlp) + nmany -= imother - up; + up = imother - 1; } else { - if (ovlp) nmany--; + if (ovlp) + nmany--; } if (ovlp || nextovlp) { matrix = GetMotherMatrix(up); - matrix->MasterToLocal(fPoint,dpt); - matrix->MasterToLocalVect(fDirection,dvec); + matrix->MasterToLocal(fPoint, dpt); + matrix->MasterToLocalVect(fDirection, dvec); snext = TGeoShape::Big(); - if (!mothernode->GetVolume()->IsAssembly()) snext = mothernode->GetVolume()->GetShape()->DistFromInside(dpt,dvec,iact,fStep); - fIsStepEntering = kFALSE; - fIsStepExiting = kTRUE; - if (snextGetVolume()->IsAssembly()) + snext = mothernode->GetVolume()->GetShape()->DistFromInside(dpt, dvec, iact, fStep); + fIsStepEntering = kFALSE; + fIsStepExiting = kTRUE; + if (snext < fStep - gTolerance) { fNextNode = mothernode; fCurrentMatrix->CopyFrom(matrix); fStep = snext; - while (up--) CdUp(); + while (up--) + CdUp(); PopDummy(); PushPath(); icrossed = -1; @@ -1420,16 +1478,16 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa if (pnode) { // A boundary is hit at less than fPStep fStep = parstep; - fPoint[0] += fStep*fDirection[0]; - fPoint[1] += fStep*fDirection[1]; - fPoint[2] += fStep*fDirection[2]; + fPoint[0] += fStep * fDirection[0]; + fPoint[1] += fStep * fDirection[1]; + fPoint[2] += fStep * fDirection[2]; fNextNode = pnode->GetNode(); -// icrossed = -4; // - fIsStepEntering = kTRUE; - fIsStepExiting = kFALSE; + // icrossed = -4; // + fIsStepEntering = kTRUE; + fIsStepExiting = kFALSE; cd(pnode->GetName()); nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { current = fCurrentNode; CdDown(nextindex); nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); @@ -1437,9 +1495,9 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa return fCurrentNode; } } - fPoint[0] += fStep*fDirection[0]; - fPoint[1] += fStep*fDirection[1]; - fPoint[2] += fStep*fDirection[2]; + fPoint[0] += fStep * fDirection[0]; + fPoint[1] += fStep * fDirection[1]; + fPoint[2] += fStep * fDirection[2]; fStep += extra; if (icrossed == -2) { // Nothing crossed within stepmax -> propagate and return same location @@ -1455,15 +1513,18 @@ TGeoNode *TGeoNavigator::FindNextBoundaryAndStep(Double_t stepmax, Bool_t compsa fIsOutside = kTRUE; return 0; } - if (fCurrentNode->IsOffset()) return CrossDivisionCell(); - if (fLevel) CdUp(); - else skip = 0; + if (fCurrentNode->IsOffset()) + return CrossDivisionCell(); + if (fLevel) + CdUp(); + else + skip = 0; return CrossBoundaryAndLocate(kFALSE, skip); } CdDown(icrossed); nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); - while (nextindex>=0) { + while (nextindex >= 0) { current = fCurrentNode; CdDown(nextindex); nextindex = fCurrentNode->GetVolume()->GetNextNodeIndex(); @@ -1489,7 +1550,8 @@ TGeoNode *TGeoNavigator::FindNode(Bool_t safe_start) if (found != last) { fIsSameLocation = kFALSE; } else { - if (last->IsOverlapping()) fIsSameLocation = kTRUE; + if (last->IsOverlapping()) + fIsSameLocation = kTRUE; } return found; } @@ -1514,7 +1576,8 @@ TGeoNode *TGeoNavigator::FindNode(Double_t x, Double_t y, Double_t z) if (found != last) { fIsSameLocation = kFALSE; } else { - if (last->IsOverlapping()) fIsSameLocation = kTRUE; + if (last->IsOverlapping()) + fIsSameLocation = kTRUE; } return found; } @@ -1525,13 +1588,14 @@ TGeoNode *TGeoNavigator::FindNode(Double_t x, Double_t y, Double_t z) Double_t *TGeoNavigator::FindNormalFast() { - if (!fNextNode) return 0; + if (!fNextNode) + return 0; Double_t local[3]; Double_t ldir[3]; Double_t lnorm[3]; fCurrentMatrix->MasterToLocal(fPoint, local); fCurrentMatrix->MasterToLocalVect(fDirection, ldir); - fNextNode->GetVolume()->GetShape()->ComputeNormal(local, ldir,lnorm); + fNextNode->GetVolume()->GetShape()->ComputeNormal(local, ldir, lnorm); fCurrentMatrix->LocalToMasterVect(lnorm, fNormal); return fNormal; } @@ -1564,8 +1628,8 @@ TGeoNode *TGeoNavigator::InitTrack(const Double_t *point, const Double_t *dir) TGeoNode *TGeoNavigator::InitTrack(Double_t x, Double_t y, Double_t z, Double_t nx, Double_t ny, Double_t nz) { - SetCurrentPoint(x,y,z); - SetCurrentDirection(nx,ny,nz); + SetCurrentPoint(x, y, z); + SetCurrentDirection(nx, ny, nz); return FindNode(); } @@ -1593,20 +1657,21 @@ Double_t TGeoNavigator::Safety(Bool_t inside) } Double_t point[3]; Double_t safpar = TGeoShape::Big(); - if (!inside) fSafety = TGeoShape::Big(); + if (!inside) + fSafety = TGeoShape::Big(); // Check if parallel navigation is enabled if (fGeometry->IsParallelWorldNav()) { safpar = fGeometry->GetParallelWorld()->Safety(fPoint); } if (fIsOutside) { - fSafety = fGeometry->GetTopVolume()->GetShape()->Safety(fPoint,kFALSE); + fSafety = fGeometry->GetTopVolume()->GetShape()->Safety(fPoint, kFALSE); if (fSafety < gTolerance) { fSafety = 0; fIsOnBoundary = kTRUE; return fSafety; } - return TMath::Min(fSafety,safpar); + return TMath::Min(fSafety, safpar); } //---> convert point to local reference frame of current node fGlobalMatrix->MasterToLocal(fPoint, point); @@ -1624,12 +1689,14 @@ Double_t TGeoNavigator::Safety(Bool_t inside) } //---> Check against the parallel geometry safety - if (safpar < fSafety) fSafety = safpar; + if (safpar < fSafety) + fSafety = safpar; //---> if we were just exiting, return this safety TObjArray *nodes = vol->GetNodes(); Int_t nd = fCurrentNode->GetNdaughters(); - if (!nd && !fCurrentOverlapping) return fSafety; + if (!nd && !fCurrentOverlapping) + return fSafety; TGeoNode *node; Double_t safe; Int_t id; @@ -1639,44 +1706,50 @@ Double_t TGeoNavigator::Safety(Bool_t inside) TGeoPatternFinder *finder = vol->GetFinder(); if (finder) { Int_t ifirst = finder->GetDivIndex(); - node = (TGeoNode*)nodes->UncheckedAt(ifirst); + node = (TGeoNode *)nodes->UncheckedAt(ifirst); node->cd(); safe = node->Safety(point, kFALSE); if (safe < gTolerance) { - fSafety=0; + fSafety = 0; fIsOnBoundary = kTRUE; return fSafety; } - if (safeGetNdiv()-1; - if (ilast==ifirst) return fSafety; - node = (TGeoNode*)nodes->UncheckedAt(ilast); + if (safe < fSafety) + fSafety = safe; + Int_t ilast = ifirst + finder->GetNdiv() - 1; + if (ilast == ifirst) + return fSafety; + node = (TGeoNode *)nodes->UncheckedAt(ilast); node->cd(); safe = node->Safety(point, kFALSE); if (safe < gTolerance) { - fSafety=0; + fSafety = 0; fIsOnBoundary = kTRUE; return fSafety; } - if (safe If no voxels just loop daughters TGeoVoxelFinder *voxels = vol->GetVoxels(); if (!voxels) { - for (id=0; idUncheckedAt(id); + for (id = 0; id < nd; id++) { + node = (TGeoNode *)nodes->UncheckedAt(id); safe = node->Safety(point, kFALSE); if (safe < gTolerance) { - fSafety=0; + fSafety = 0; fIsOnBoundary = kTRUE; return fSafety; } - if (safeNeedRebuild()) { @@ -1687,29 +1760,38 @@ Double_t TGeoNavigator::Safety(Bool_t inside) //---> check fast unsafe voxels Double_t *boxes = voxels->GetBoxes(); - for (id=0; id fSafety) continue; - Double_t dxyz1 = TMath::Abs(point[1]-boxes[ist+4])-boxes[ist+1]; - if (dxyz1 > fSafety) continue; - Double_t dxyz2 = TMath::Abs(point[2]-boxes[ist+5])-boxes[ist+2]; - if (dxyz2 > fSafety) continue; - if (dxyz0>0) dxyz+=dxyz0*dxyz0; - if (dxyz1>0) dxyz+=dxyz1*dxyz1; - if (dxyz2>0) dxyz+=dxyz2*dxyz2; - if (dxyz >= fSafety*fSafety) continue; - node = (TGeoNode*)nodes->UncheckedAt(id); + Double_t dxyz0 = TMath::Abs(point[0] - boxes[ist + 3]) - boxes[ist]; + if (dxyz0 > fSafety) + continue; + Double_t dxyz1 = TMath::Abs(point[1] - boxes[ist + 4]) - boxes[ist + 1]; + if (dxyz1 > fSafety) + continue; + Double_t dxyz2 = TMath::Abs(point[2] - boxes[ist + 5]) - boxes[ist + 2]; + if (dxyz2 > fSafety) + continue; + if (dxyz0 > 0) + dxyz += dxyz0 * dxyz0; + if (dxyz1 > 0) + dxyz += dxyz1 * dxyz1; + if (dxyz2 > 0) + dxyz += dxyz2 * dxyz2; + if (dxyz >= fSafety * fSafety) + continue; + node = (TGeoNode *)nodes->UncheckedAt(id); safe = node->Safety(point, kFALSE); - if (safeGetOverlaps(novlp); CdUp(); @@ -1734,12 +1816,14 @@ void TGeoNavigator::SafetyOverlaps() fGeometry->MasterToLocal(fPoint, point); contains = fCurrentNode->GetVolume()->Contains(point); safe = fCurrentNode->GetVolume()->GetShape()->Safety(point, contains); - if (safe=0) fSafety=safe; - if (!novlp || !contains) continue; + if (safe < fSafety && safe >= 0) + fSafety = safe; + if (!novlp || !contains) + continue; // we are now in the container, check safety to all candidates - for (io=0; ioGetNode(ovlp[io]); - nodeovlp->GetMatrix()->MasterToLocal(point,local); + nodeovlp->GetMatrix()->MasterToLocal(point, local); contains = nodeovlp->GetVolume()->Contains(local); if (contains) { CdDown(ovlp[io]); @@ -1748,11 +1832,12 @@ void TGeoNavigator::SafetyOverlaps() } else { safe = nodeovlp->GetVolume()->GetShape()->Safety(local, kFALSE); } - if (safe=0) fSafety=safe; + if (safe < fSafety && safe >= 0) + fSafety = safe; } } if (fNmany) { - // We have overlaps up in the branch, check distance to exit + // We have overlaps up in the branch, check distance to exit Int_t up = 1; Int_t imother; Int_t nmany = fNmany; @@ -1763,15 +1848,18 @@ void TGeoNavigator::SafetyOverlaps() while (nmany) { mother = GetMother(up); mup = mother; - imother = up+1; - while (mup->IsOffset()) mup = GetMother(imother++); + imother = up + 1; + while (mup->IsOffset()) + mup = GetMother(imother++); nextovlp = mup->IsOverlapping(); - if (crtovlp) nmany--; + if (crtovlp) + nmany--; if (crtovlp || nextovlp) { matrix = GetMotherMatrix(up); - matrix->MasterToLocal(fPoint,local); - safe = mother->GetVolume()->GetShape()->Safety(local,kTRUE); - if (safeMasterToLocal(fPoint, local); + safe = mother->GetVolume()->GetShape()->Safety(local, kTRUE); + if (safe < fSafety) + fSafety = safe; crtovlp = nextovlp; } up++; @@ -1797,8 +1885,8 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) // and synchronize with navigation state pnode->cd(); Int_t crtindex = fCurrentNode->GetVolume()->GetCurrentNodeIndex(); - while (crtindex>=0) { - // Make sure we did not end up in an assembly. + while (crtindex >= 0) { + // Make sure we did not end up in an assembly. CdDown(crtindex); crtindex = fCurrentNode->GetVolume()->GetCurrentNodeIndex(); } @@ -1809,9 +1897,9 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) fNextDaughterIndex = -2; TGeoVolume *vol = 0; Int_t idebug = TGeoManager::GetVerboseLevel(); - Bool_t inside_current = (fCurrentNode==skipnode)?kTRUE:kFALSE; + Bool_t inside_current = (fCurrentNode == skipnode) ? kTRUE : kFALSE; if (!downwards) { - // we are looking upwards until inside current node or exit + // we are looking upwards until inside current node or exit if (fGeometry->IsActivityEnabled() && !fCurrentNode->GetVolume()->IsActive()) { // We are inside an inactive volume-> go upwards CdUp(); @@ -1819,8 +1907,9 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) return SearchNode(kFALSE, skipnode); } // Check if the current point is still inside the current volume - vol=fCurrentNode->GetVolume(); - if (vol->IsAssembly()) inside_current=kTRUE; + vol = fCurrentNode->GetVolume(); + if (vol->IsAssembly()) + inside_current = kTRUE; // If the current node is not to be skipped if (!inside_current) { fGlobalMatrix->MasterToLocal(fPoint, point); @@ -1833,7 +1922,7 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) if (!inside_current) { // If not, go upwards fIsSameLocation = kFALSE; - TGeoNode *skip = fCurrentNode; // skip current node at next search + TGeoNode *skip = fCurrentNode; // skip current node at next search // check if we can go up if (!fLevel) { fIsOutside = kTRUE; @@ -1846,9 +1935,11 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) vol = fCurrentNode->GetVolume(); fGlobalMatrix->MasterToLocal(fPoint, point); if (!inside_current && downwards) { - // we are looking downwards - if (fCurrentNode == fForcedNode) inside_current = kTRUE; - else inside_current = vol->Contains(point); + // we are looking downwards + if (fCurrentNode == fForcedNode) + inside_current = kTRUE; + else + inside_current = vol->Contains(point); if (!inside_current) { fIsSameLocation = kFALSE; return 0; @@ -1857,9 +1948,9 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) fIsOutside = kFALSE; fIsSameLocation = kFALSE; } - if (idebug>4) { - printf("Search node local=(%19.16f, %19.16f, %19.16f) -> %s\n", - point[0],point[1],point[2], fCurrentNode->GetName()); + if (idebug > 4) { + printf("Search node local=(%19.16f, %19.16f, %19.16f) -> %s\n", point[0], point[1], point[2], + fCurrentNode->GetName()); } } } @@ -1872,33 +1963,37 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) } Int_t crtindex = vol->GetCurrentNodeIndex(); - while (crtindex>=0 && downwards) { + while (crtindex >= 0 && downwards) { // Make sure we did not end up in an assembly. CdDown(crtindex); vol = fCurrentNode->GetVolume(); crtindex = vol->GetCurrentNodeIndex(); - if (crtindex<0) fGlobalMatrix->MasterToLocal(fPoint, point); + if (crtindex < 0) + fGlobalMatrix->MasterToLocal(fPoint, point); } Int_t nd = vol->GetNdaughters(); // in case there are no daughters - if (!nd) return fCurrentNode; - if (fGeometry->IsActivityEnabled() && !vol->IsActiveDaughters()) return fCurrentNode; + if (!nd) + return fCurrentNode; + if (fGeometry->IsActivityEnabled() && !vol->IsActiveDaughters()) + return fCurrentNode; TGeoPatternFinder *finder = vol->GetFinder(); // point is inside the current node // first check if inside a division if (finder) { - node=finder->FindNode(point); + node = finder->FindNode(point); if (!node && fForcedNode) { // Point *HAS* to be inside a cell Double_t dir[3]; fGlobalMatrix->MasterToLocalVect(fDirection, dir); - finder->FindNode(point,dir); + finder->FindNode(point, dir); node = finder->CdNext(); - if (!node) return fCurrentNode; // inside divided volume but not in a cell + if (!node) + return fCurrentNode; // inside divided volume but not in a cell } - if (node && node!=skipnode) { + if (node && node != skipnode) { // go inside the division cell and search downwards fIsSameLocation = kFALSE; CdDown(node->GetIndex()); @@ -1907,7 +2002,8 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) } // point is not inside the division, but might be in other nodes // at the same level (NOT SUPPORTED YET) - while (fCurrentNode && fCurrentNode->IsOffset()) CdUp(); + while (fCurrentNode && fCurrentNode->IsOffset()) + CdUp(); return fCurrentNode; } // second, look if current volume is voxelized @@ -1932,23 +2028,25 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) } CdUp(); fCache->ReleaseInfo(); - return SearchNode(kFALSE,node); + return SearchNode(kFALSE, node); } // loop all nodes in voxel - for (id=0; idGetNode(check_list[id]); - if (node==skipnode) continue; - if (fGeometry->IsActivityEnabled() && !node->GetVolume()->IsActive()) continue; - if ((id<(ncheck-1)) && node->IsOverlapping()) { - // make the cluster of overlaps - if (ncheck+fOverlapMark > fOverlapSize) { - fOverlapSize = 2*(ncheck+fOverlapMark); - delete [] fOverlapClusters; + if (node == skipnode) + continue; + if (fGeometry->IsActivityEnabled() && !node->GetVolume()->IsActive()) + continue; + if ((id < (ncheck - 1)) && node->IsOverlapping()) { + // make the cluster of overlaps + if (ncheck + fOverlapMark > fOverlapSize) { + fOverlapSize = 2 * (ncheck + fOverlapMark); + delete[] fOverlapClusters; fOverlapClusters = new Int_t[fOverlapSize]; } Int_t *cluster = fOverlapClusters + fOverlapMark; Int_t nc = GetTouchedCluster(id, &point[0], check_list, ncheck, cluster); - if (nc>1) { + if (nc > 1) { fOverlapMark += nc; node = FindInCluster(cluster, nc); fOverlapMark -= nc; @@ -1978,13 +2076,15 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) } CdUp(); fCache->ReleaseInfo(); - return SearchNode(kFALSE,node); + return SearchNode(kFALSE, node); } // if there are no voxels just loop all daughters - for (id=0; idGetDaughter(id); - if (node==skipnode) continue; - if (fGeometry->IsActivityEnabled() && !node->GetVolume()->IsActive()) continue; + for (id = 0; id < nd; id++) { + node = fCurrentNode->GetDaughter(id); + if (node == skipnode) + continue; + if (fGeometry->IsActivityEnabled() && !node->GetVolume()->IsActive()) + continue; CdDown(id); fForcedNode = 0; node = SearchNode(kTRUE); @@ -2002,7 +2102,7 @@ TGeoNode *TGeoNavigator::SearchNode(Bool_t downwards, const TGeoNode *skipnode) return 0; } CdUp(); - return SearchNode(kFALSE,node); + return SearchNode(kFALSE, node); } return fCurrentNode; } @@ -2023,39 +2123,42 @@ TGeoNode *TGeoNavigator::FindInCluster(Int_t *cluster, Int_t nc) // mark this search fSearchOverlaps = kTRUE; Int_t deepest = fLevel; - Int_t deepest_virtual = fLevel-GetVirtualLevel(); + Int_t deepest_virtual = fLevel - GetVirtualLevel(); Int_t found_virtual = 0; Bool_t replace = kFALSE; Bool_t added = kFALSE; Int_t i; - for (i=0; iGetDaughter(cluster[i]); CdDown(cluster[i]); - Bool_t max_priority = (clnode==fNextNode)?kTRUE:kFALSE; + Bool_t max_priority = (clnode == fNextNode) ? kTRUE : kFALSE; found = SearchNode(kTRUE, clnode); if (!fSearchOverlaps || max_priority) { - // an only was found during the search -> exiting - // The node given by FindNextBoundary returned -> exiting + // an only was found during the search -> exiting + // The node given by FindNextBoundary returned -> exiting PopDummy(ipop); return found; } - found_virtual = fLevel-GetVirtualLevel(); + found_virtual = fLevel - GetVirtualLevel(); if (added) { - // we have put something in stack -> check it - if (found_virtual>deepest_virtual) { + // we have put something in stack -> check it + if (found_virtual > deepest_virtual) { replace = kTRUE; } else { - if (found_virtual==deepest_virtual) { - if (fLevel>deepest) { + if (found_virtual == deepest_virtual) { + if (fLevel > deepest) { replace = kTRUE; } else { - if ((fLevel==deepest) && (clnode==priority)) replace=kTRUE; - else replace = kFALSE; + if ((fLevel == deepest) && (clnode == priority)) + replace = kTRUE; + else + replace = kFALSE; } - } else replace = kFALSE; + } else + replace = kFALSE; } // if this was the last checked node - if (i==(nc-1)) { + if (i == (nc - 1)) { if (replace) { PopDummy(ipop); return found; @@ -2076,7 +2179,7 @@ TGeoNode *TGeoNavigator::FindInCluster(Int_t *cluster, Int_t nc) // restore top of cluster fCurrentOverlapping = PopPath(ipop); } else { - // the stack was clean, push new one + // the stack was clean, push new one PushPath(); added = kTRUE; deepest = fLevel; @@ -2094,34 +2197,37 @@ TGeoNode *TGeoNavigator::FindInCluster(Int_t *cluster, Int_t nc) /// of the mother. Returns number of nodes containing the point. Nodes should not be /// offsets. -Int_t TGeoNavigator::GetTouchedCluster(Int_t start, Double_t *point, - Int_t *check_list, Int_t ncheck, Int_t *result) +Int_t TGeoNavigator::GetTouchedCluster(Int_t start, Double_t *point, Int_t *check_list, Int_t ncheck, Int_t *result) { // we are in the mother reference system TGeoNode *current = fCurrentNode->GetDaughter(check_list[start]); Int_t novlps = 0; Int_t *ovlps = current->GetOverlaps(novlps); - if (!ovlps) return 0; + if (!ovlps) + return 0; Double_t local[3]; // intersect check list with overlap list Int_t ntotal = 0; current->MasterToLocal(point, &local[0]); if (current->GetVolume()->Contains(&local[0])) { - result[ntotal++]=check_list[start]; + result[ntotal++] = check_list[start]; } - Int_t jst=0, i, j; - while ((jst check if touched + Int_t jst = 0, i, j; + while ((jst < novlps) && (ovlps[jst] <= check_list[start])) + jst++; + if (jst == novlps) + return 0; + for (i = start; i < ncheck; i++) { + for (j = jst; j < novlps; j++) { + if (check_list[i] == ovlps[j]) { + // overlapping node in voxel -> check if touched current = fCurrentNode->GetDaughter(check_list[i]); - if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) continue; + if (fGeometry->IsActivityEnabled() && !current->GetVolume()->IsActive()) + continue; current->MasterToLocal(point, &local[0]); if (current->GetVolume()->Contains(&local[0])) { - result[ntotal++]=check_list[i]; + result[ntotal++] = check_list[i]; } } } @@ -2139,27 +2245,32 @@ Int_t TGeoNavigator::GetTouchedCluster(Int_t start, Double_t *point, TGeoNode *TGeoNavigator::Step(Bool_t is_geom, Bool_t cross) { Double_t epsil = 0; - if (fStep<1E-6) { - fIsNullStep=kTRUE; - if (fStep<0) fStep = 0.; + if (fStep < 1E-6) { + fIsNullStep = kTRUE; + if (fStep < 0) + fStep = 0.; } else { - fIsNullStep=kFALSE; + fIsNullStep = kFALSE; } - if (is_geom) epsil=(cross)?1E-6:-1E-6; + if (is_geom) + epsil = (cross) ? 1E-6 : -1E-6; TGeoNode *old = fCurrentNode; Int_t idold = GetNodeId(); - if (fIsOutside) old = 0; + if (fIsOutside) + old = 0; fStep += epsil; - for (Int_t i=0; i<3; i++) fPoint[i]+=fStep*fDirection[i]; + for (Int_t i = 0; i < 3; i++) + fPoint[i] += fStep * fDirection[i]; TGeoNode *current = FindNode(); if (is_geom) { - fIsEntering = (current==old)?kFALSE:kTRUE; + fIsEntering = (current == old) ? kFALSE : kTRUE; if (!fIsEntering) { Int_t id = GetNodeId(); - fIsEntering = (id==idold)?kFALSE:kTRUE; + fIsEntering = (id == idold) ? kFALSE : kTRUE; } - fIsExiting = !fIsEntering; - if (fIsEntering && fIsNullStep) fIsNullStep = kFALSE; + fIsExiting = !fIsEntering; + if (fIsEntering && fIsNullStep) + fIsNullStep = kFALSE; fIsOnBoundary = kTRUE; } else { fIsEntering = fIsExiting = kFALSE; @@ -2175,21 +2286,24 @@ TGeoNode *TGeoNavigator::Step(Bool_t is_geom, Bool_t cross) Int_t TGeoNavigator::GetVirtualLevel() { // return if the current node is ONLY - if (!fCurrentOverlapping) return 0; + if (!fCurrentOverlapping) + return 0; Int_t new_media = 0; TGeoMedium *medium = fCurrentNode->GetMedium(); Int_t virtual_level = 1; TGeoNode *mother = 0; - while ((mother=GetMother(virtual_level))) { + while ((mother = GetMother(virtual_level))) { if (!mother->IsOverlapping() && !mother->IsOffset()) { - if (!new_media) new_media=(mother->GetMedium()==medium)?0:virtual_level; + if (!new_media) + new_media = (mother->GetMedium() == medium) ? 0 : virtual_level; break; } - if (!new_media) new_media=(mother->GetMedium()==medium)?0:virtual_level; + if (!new_media) + new_media = (mother->GetMedium() == medium) ? 0 : virtual_level; virtual_level++; } - return (new_media==0)?virtual_level:(new_media-1); + return (new_media == 0) ? virtual_level : (new_media - 1); } //////////////////////////////////////////////////////////////////////////////// @@ -2197,12 +2311,14 @@ Int_t TGeoNavigator::GetVirtualLevel() Bool_t TGeoNavigator::GotoSafeLevel() { - while (fCurrentOverlapping && fLevel) CdUp(); + while (fCurrentOverlapping && fLevel) + CdUp(); Double_t point[3]; fGlobalMatrix->MasterToLocal(fPoint, point); - if (!fCurrentNode->GetVolume()->Contains(point)) return kFALSE; + if (!fCurrentNode->GetVolume()->Contains(point)) + return kFALSE; if (fNmany) { - // We still have overlaps on the branch + // We still have overlaps on the branch Int_t up = 1; Int_t imother; Int_t nmany = fNmany; @@ -2212,19 +2328,23 @@ Bool_t TGeoNavigator::GotoSafeLevel() TGeoHMatrix *matrix; while (nmany) { mother = GetMother(up); - if (!mother) return kTRUE; + if (!mother) + return kTRUE; mup = mother; - imother = up+1; - while (mup->IsOffset()) mup = GetMother(imother++); + imother = up + 1; + while (mup->IsOffset()) + mup = GetMother(imother++); nextovlp = mup->IsOverlapping(); - if (ovlp) nmany--; + if (ovlp) + nmany--; if (ovlp || nextovlp) { - // check if the point is in the next node up + // check if the point is in the next node up matrix = GetMotherMatrix(up); - matrix->MasterToLocal(fPoint,point); + matrix->MasterToLocal(fPoint, point); if (!mother->GetVolume()->Contains(point)) { up++; - while (up--) CdUp(); + while (up--) + CdUp(); return GotoSafeLevel(); } } @@ -2241,13 +2361,15 @@ Bool_t TGeoNavigator::GotoSafeLevel() Int_t TGeoNavigator::GetSafeLevel() const { Bool_t overlapping = fCurrentOverlapping; - if (!overlapping) return fLevel; + if (!overlapping) + return fLevel; Int_t level = fLevel; TGeoNode *node; while (overlapping && level) { level--; - node = GetMother(fLevel-level); - if (!node->IsOffset()) overlapping = node->IsOverlapping(); + node = GetMother(fLevel - level); + if (!node->IsOffset()) + overlapping = node->IsOverlapping(); } return level; } @@ -2257,18 +2379,19 @@ Int_t TGeoNavigator::GetSafeLevel() const void TGeoNavigator::InspectState() const { - Info("InspectState","Current path is: %s",GetPath()); + Info("InspectState", "Current path is: %s", GetPath()); Int_t level; TGeoNode *node; Bool_t is_offset, is_overlapping; - for (level=0; levelIsOffset(); is_overlapping = node->IsOverlapping(); - Info("InspectState","level %i: %s div=%i many=%i",level,node->GetName(),is_offset,is_overlapping); + Info("InspectState", "level %i: %s div=%i many=%i", level, node->GetName(), is_offset, is_overlapping); } - Info("InspectState","on_bound=%i entering=%i", fIsOnBoundary, fIsEntering); + Info("InspectState", "on_bound=%i entering=%i", fIsOnBoundary, fIsEntering); } //////////////////////////////////////////////////////////////////////////////// @@ -2278,33 +2401,36 @@ void TGeoNavigator::InspectState() const Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t change) { Double_t oldpt[3]; - if (fLastSafety>0) { - Double_t dx = (x-fLastPoint[0]); - Double_t dy = (y-fLastPoint[1]); - Double_t dz = (z-fLastPoint[2]); - Double_t dsq = dx*dx+dy*dy+dz*dz; - if (dsq 0) { + Double_t dx = (x - fLastPoint[0]); + Double_t dy = (y - fLastPoint[1]); + Double_t dz = (z - fLastPoint[2]); + Double_t dsq = dx * dx + dy * dy + dz * dz; + if (dsq < fLastSafety * fLastSafety) { if (change) { fPoint[0] = x; fPoint[1] = y; fPoint[2] = z; - memcpy(fLastPoint, fPoint, 3*sizeof(Double_t)); + memcpy(fLastPoint, fPoint, 3 * sizeof(Double_t)); fLastSafety -= TMath::Sqrt(dsq); } return kTRUE; } - if (change) fLastSafety = 0; + if (change) + fLastSafety = 0; } if (fCurrentOverlapping) { -// TGeoNode *current = fCurrentNode; + // TGeoNode *current = fCurrentNode; Int_t cid = GetCurrentNodeId(); - if (!change) PushPoint(); + if (!change) + PushPoint(); memcpy(oldpt, fPoint, kN3); - SetCurrentPoint(x,y,z); + SetCurrentPoint(x, y, z); SearchNode(); memcpy(fPoint, oldpt, kN3); - Bool_t same = (cid==GetCurrentNodeId())?kTRUE:kFALSE; - if (!change) PopPoint(); + Bool_t same = (cid == GetCurrentNodeId()) ? kTRUE : kFALSE; + if (!change) + PopPoint(); return same; } @@ -2312,24 +2438,27 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t point[0] = x; point[1] = y; point[2] = z; - if (change) memcpy(fPoint, point, kN3); + if (change) + memcpy(fPoint, point, kN3); TGeoVolume *vol = fCurrentNode->GetVolume(); if (fIsOutside) { if (vol->GetShape()->Contains(point)) { - if (!change) return kFALSE; - FindNode(x,y,z); + if (!change) + return kFALSE; + FindNode(x, y, z); return kFALSE; } return kTRUE; } Double_t local[3]; // convert to local frame - fGlobalMatrix->MasterToLocal(point,local); + fGlobalMatrix->MasterToLocal(point, local); // check if still in current volume. if (!vol->GetShape()->Contains(local)) { - if (!change) return kFALSE; + if (!change) + return kFALSE; CdUp(); - FindNode(x,y,z); + FindNode(x, y, z); return kFALSE; } @@ -2337,11 +2466,12 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t if (fGeometry->IsParallelWorldNav()) { TGeoPhysicalNode *pnode = fGeometry->GetParallelWorld()->FindNode(fPoint); if (pnode) { - if (!change) return kFALSE; + if (!change) + return kFALSE; pnode->cd(); Int_t crtindex = fCurrentNode->GetVolume()->GetCurrentNodeIndex(); - while (crtindex>=0) { - // Make sure we did not end up in an assembly. + while (crtindex >= 0) { + // Make sure we did not end up in an assembly. CdDown(crtindex); crtindex = fCurrentNode->GetVolume()->GetCurrentNodeIndex(); } @@ -2350,16 +2480,18 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t } // check if there are daughters Int_t nd = vol->GetNdaughters(); - if (!nd) return kTRUE; + if (!nd) + return kTRUE; TGeoNode *node; TGeoPatternFinder *finder = vol->GetFinder(); if (finder) { - node=finder->FindNode(local); + node = finder->FindNode(local); if (node) { - if (!change) return kFALSE; + if (!change) + return kFALSE; CdDown(node->GetIndex()); - SearchNode(kTRUE,node); + SearchNode(kTRUE, node); return kFALSE; } return kTRUE; @@ -2375,11 +2507,12 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t fCache->ReleaseInfo(); return kTRUE; } - if (!change) PushPath(); - for (Int_t id=0; idGetNode(check_list[id]); + if (!change) + PushPath(); + for (Int_t id = 0; id < ncheck; id++) { + // node = vol->GetNode(check_list[id]); CdDown(check_list[id]); - fGlobalMatrix->MasterToLocal(point,local1); + fGlobalMatrix->MasterToLocal(point, local1); if (fCurrentNode->GetVolume()->GetShape()->Contains(local1)) { if (!change) { PopPath(); @@ -2392,15 +2525,17 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t } CdUp(); } - if (!change) PopPath(); + if (!change) + PopPath(); fCache->ReleaseInfo(); return kTRUE; } Int_t id = 0; - if (!change) PushPath(); + if (!change) + PushPath(); while (fCurrentNode && fCurrentNode->GetDaughter(id++)) { - CdDown(id-1); - fGlobalMatrix->MasterToLocal(point,local1); + CdDown(id - 1); + fGlobalMatrix->MasterToLocal(point, local1); if (fCurrentNode->GetVolume()->GetShape()->Contains(local1)) { if (!change) { PopPath(); @@ -2411,11 +2546,13 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t } CdUp(); if (id == nd) { - if (!change) PopPath(); + if (!change) + PopPath(); return kTRUE; } } - if (!change) PopPath(); + if (!change) + PopPath(); return kTRUE; } @@ -2427,19 +2564,21 @@ Bool_t TGeoNavigator::IsSameLocation(Double_t x, Double_t y, Double_t z, Bool_t Bool_t TGeoNavigator::IsSafeStep(Double_t proposed, Double_t &newsafety) const { // Last safety not computed. - if (fLastSafety < gTolerance) return kFALSE; + if (fLastSafety < gTolerance) + return kFALSE; // Proposed step too small if (proposed < gTolerance) { newsafety = fLastSafety - proposed; return kTRUE; } // Normal step - Double_t dist = (fPoint[0]-fLastPoint[0])*(fPoint[0]-fLastPoint[0])+ - (fPoint[1]-fLastPoint[1])*(fPoint[1]-fLastPoint[1])+ - (fPoint[2]-fLastPoint[2])*(fPoint[2]-fLastPoint[2]); + Double_t dist = (fPoint[0] - fLastPoint[0]) * (fPoint[0] - fLastPoint[0]) + + (fPoint[1] - fLastPoint[1]) * (fPoint[1] - fLastPoint[1]) + + (fPoint[2] - fLastPoint[2]) * (fPoint[2] - fLastPoint[2]); dist = TMath::Sqrt(dist); - Double_t safe = fLastSafety - dist; - if (safe < proposed) return kFALSE; + Double_t safe = fLastSafety - dist; + if (safe < proposed) + return kFALSE; newsafety = safe; return kTRUE; } @@ -2449,9 +2588,10 @@ Bool_t TGeoNavigator::IsSafeStep(Double_t proposed, Double_t &newsafety) const Bool_t TGeoNavigator::IsSamePoint(Double_t x, Double_t y, Double_t z) const { - if (TMath::Abs(x-fLastPoint[0]) < 1.E-20) { - if (TMath::Abs(y-fLastPoint[1]) < 1.E-20) { - if (TMath::Abs(z-fLastPoint[2]) < 1.E-20) return kTRUE; + if (TMath::Abs(x - fLastPoint[0]) < 1.E-20) { + if (TMath::Abs(y - fLastPoint[1]) < 1.E-20) { + if (TMath::Abs(z - fLastPoint[2]) < 1.E-20) + return kTRUE; } } return kFALSE; @@ -2462,7 +2602,8 @@ Bool_t TGeoNavigator::IsSamePoint(Double_t x, Double_t y, Double_t z) const void TGeoNavigator::DoBackupState() { - if (fBackupState) fBackupState->SetState(fLevel,0, fNmany, fCurrentOverlapping); + if (fBackupState) + fBackupState->SetState(fLevel, 0, fNmany, fCurrentOverlapping); } //////////////////////////////////////////////////////////////////////////////// @@ -2472,9 +2613,9 @@ void TGeoNavigator::DoRestoreState() { if (fBackupState && fCache) { fCurrentOverlapping = fCache->RestoreState(fNmany, fBackupState); - fCurrentNode=fCache->GetNode(); + fCurrentNode = fCache->GetNode(); fGlobalMatrix = fCache->GetCurrentMatrix(); - fLevel=fCache->GetLevel(); + fLevel = fCache->GetLevel(); } } @@ -2495,7 +2636,8 @@ TGeoHMatrix *TGeoNavigator::GetHMatrix() const char *TGeoNavigator::GetPath() const { - if (fIsOutside) return kGeoOutsidePath; + if (fIsOutside) + return kGeoOutsidePath; return fCache->GetPath(); } @@ -2540,13 +2682,13 @@ void TGeoNavigator::ResetAll() fNextNode = 0; fPath = ""; if (fCache) { - Bool_t dummy=fCache->IsDummy(); + Bool_t dummy = fCache->IsDummy(); Bool_t nodeid = fCache->HasIdArray(); delete fCache; fCache = nullptr; delete fBackupState; fBackupState = nullptr; - BuildCache(dummy,nodeid); + BuildCache(dummy, nodeid); } } @@ -2561,6 +2703,6 @@ TGeoNavigator *TGeoNavigatorArray::AddNavigator() TGeoNavigator *nav = new TGeoNavigator(fGeoManager); nav->BuildCache(kTRUE, kFALSE); Add(nav); - SetCurrentNavigator(GetEntriesFast()-1); + SetCurrentNavigator(GetEntriesFast() - 1); return nav; } diff --git a/geom/geom/src/TGeoNode.cxx b/geom/geom/src/TGeoNode.cxx index 01351f0c0bab1..3a70f5016c53f 100644 --- a/geom/geom/src/TGeoNode.cxx +++ b/geom/geom/src/TGeoNode.cxx @@ -94,11 +94,11 @@ ClassImp(TGeoNode); TGeoNode::TGeoNode() { - fVolume = 0; - fMother = 0; - fNumber = 0; - fNovlp = 0; - fOverlaps = 0; + fVolume = 0; + fMother = 0; + fNumber = 0; + fNovlp = 0; + fOverlaps = 0; fUserExtension = 0; fFWExtension = 0; } @@ -112,13 +112,14 @@ TGeoNode::TGeoNode(const TGeoVolume *vol) Error("ctor", "volume not specified"); return; } - fVolume = (TGeoVolume*)vol; - if (fVolume->IsAdded()) fVolume->SetReplicated(); + fVolume = (TGeoVolume *)vol; + if (fVolume->IsAdded()) + fVolume->SetReplicated(); fVolume->SetAdded(); - fMother = 0; - fNumber = 0; - fNovlp = 0; - fOverlaps = 0; + fMother = 0; + fNumber = 0; + fNovlp = 0; + fOverlaps = 0; fUserExtension = 0; fFWExtension = 0; } @@ -128,9 +129,16 @@ TGeoNode::TGeoNode(const TGeoVolume *vol) TGeoNode::~TGeoNode() { - if (fOverlaps) delete [] fOverlaps; - if (fUserExtension) {fUserExtension->Release(); fUserExtension=0;} - if (fFWExtension) {fFWExtension->Release(); fFWExtension=0;} + if (fOverlaps) + delete[] fOverlaps; + if (fUserExtension) { + fUserExtension->Release(); + fUserExtension = 0; + } + if (fFWExtension) { + fFWExtension->Release(); + fFWExtension = 0; + } } //////////////////////////////////////////////////////////////////////////////// @@ -138,11 +146,13 @@ TGeoNode::~TGeoNode() void TGeoNode::Browse(TBrowser *b) { - if (!b) return; - if (!GetNdaughters()) return; + if (!b) + return; + if (!GetNdaughters()) + return; TGeoNode *daughter; TString title; - for (Int_t i=0; iAdd(daughter, daughter->GetName(), daughter->IsVisible()); } @@ -162,14 +172,17 @@ Int_t TGeoNode::CountDaughters(Bool_t unique_volumes) counter++; fVolume->SelectVolume(kFALSE); } - } else counter++; + } else + counter++; icall++; Int_t nd = fVolume->GetNdaughters(); // Count daughters recursively - for (Int_t i=0; iCountDaughters(unique_volumes); + for (Int_t i = 0; i < nd; i++) + counter += GetDaughter(i)->CountDaughters(unique_volumes); icall--; // Un-mark volumes - if (icall == 0) fVolume->SelectVolume(kTRUE); + if (icall == 0) + fVolume->SelectVolume(kTRUE); return counter; } @@ -185,21 +198,22 @@ void TGeoNode::CheckOverlaps(Double_t ovlp, Option_t *option) Bool_t sampling = kFALSE; TString opt(option); opt.ToLower(); - if (opt.Contains("s")) sampling = kTRUE; + if (opt.Contains("s")) + sampling = kTRUE; TGeoManager *geom = fVolume->GetGeoManager(); ncheck = CountDaughters(kFALSE); timer = new TStopwatch(); geom->ClearOverlaps(); geom->SetCheckingOverlaps(kTRUE); - Info("CheckOverlaps", "Checking overlaps for %s and daughters within %g", fVolume->GetName(),ovlp); + Info("CheckOverlaps", "Checking overlaps for %s and daughters within %g", fVolume->GetName(), ovlp); if (sampling) { Info("CheckOverlaps", "Checking overlaps by sampling <%s> for %s and daughters", option, fVolume->GetName()); Info("CheckOverlaps", "=== NOTE: Extrusions NOT checked with sampling option ! ==="); } timer->Start(); - geom->GetGeomPainter()->OpProgress(fVolume->GetName(),icheck,ncheck,timer,kFALSE); - fVolume->CheckOverlaps(ovlp,option); + geom->GetGeomPainter()->OpProgress(fVolume->GetName(), icheck, ncheck, timer, kFALSE); + fVolume->CheckOverlaps(ovlp, option); icheck++; TGeoIterator next(fVolume); TGeoNode *node; @@ -207,14 +221,14 @@ void TGeoNode::CheckOverlaps(Double_t ovlp, Option_t *option) TObjArray *overlaps = geom->GetListOfOverlaps(); Int_t novlps; TString msg; - while ((node=next())) { + while ((node = next())) { next.GetPath(path); icheck++; if (!node->GetVolume()->IsSelected()) { msg = TString::Format("found %d overlaps", overlaps->GetEntriesFast()); - geom->GetGeomPainter()->OpProgress(node->GetVolume()->GetName(),icheck,ncheck,timer,kFALSE, msg); + geom->GetGeomPainter()->OpProgress(node->GetVolume()->GetName(), icheck, ncheck, timer, kFALSE, msg); node->GetVolume()->SelectVolume(kFALSE); - node->GetVolume()->CheckOverlaps(ovlp,option); + node->GetVolume()->CheckOverlaps(ovlp, option); } } fVolume->SelectVolume(kTRUE); @@ -222,11 +236,11 @@ void TGeoNode::CheckOverlaps(Double_t ovlp, Option_t *option) geom->SortOverlaps(); novlps = overlaps->GetEntriesFast(); TNamed *obj; - for (i=0; iAt(i); - obj->SetName(TString::Format("ov%05d",i)); + for (i = 0; i < novlps; i++) { + obj = (TNamed *)overlaps->At(i); + obj->SetName(TString::Format("ov%05d", i)); } - geom->GetGeomPainter()->OpProgress("Check overlaps:",icheck,ncheck,timer,kTRUE); + geom->GetGeomPainter()->OpProgress("Check overlaps:", icheck, ncheck, timer, kTRUE); Info("CheckOverlaps", "Number of illegal overlaps/extrusions : %d\n", novlps); delete timer; } @@ -237,10 +251,13 @@ void TGeoNode::CheckOverlaps(Double_t ovlp, Option_t *option) Int_t TGeoNode::DistancetoPrimitive(Int_t px, Int_t py) { Int_t dist = 9999; - if (!fVolume) return dist; - if (gGeoManager != fVolume->GetGeoManager()) gGeoManager = fVolume->GetGeoManager(); + if (!fVolume) + return dist; + if (gGeoManager != fVolume->GetGeoManager()) + gGeoManager = fVolume->GetGeoManager(); TVirtualGeoPainter *painter = gGeoManager->GetPainter(); - if (!painter) return dist; + if (!painter) + return dist; dist = painter->DistanceToPrimitiveVol(fVolume, px, py); return dist; } @@ -250,9 +267,11 @@ Int_t TGeoNode::DistancetoPrimitive(Int_t px, Int_t py) void TGeoNode::ExecuteEvent(Int_t event, Int_t px, Int_t py) { - if (!fVolume) return; + if (!fVolume) + return; TVirtualGeoPainter *painter = fVolume->GetGeoManager()->GetPainter(); - if (!painter) return; + if (!painter) + return; painter->ExecuteVolumeEvent(fVolume, event, px, py); } @@ -261,10 +280,12 @@ void TGeoNode::ExecuteEvent(Int_t event, Int_t px, Int_t py) char *TGeoNode::GetObjectInfo(Int_t px, Int_t py) const { - if (!fVolume) return 0; + if (!fVolume) + return 0; TVirtualGeoPainter *painter = fVolume->GetGeoManager()->GetPainter(); - if (!painter) return 0; - return (char*)painter->GetVolumeInfo(fVolume, px, py); + if (!painter) + return 0; + return (char *)painter->GetVolumeInfo(fVolume, px, py); } //////////////////////////////////////////////////////////////////////////////// @@ -272,7 +293,8 @@ char *TGeoNode::GetObjectInfo(Int_t px, Int_t py) const Bool_t TGeoNode::IsOnScreen() const { - if (fVolume->TestAttBit(TGeoAtt::kVisOnScreen)) return kTRUE; + if (fVolume->TestAttBit(TGeoAtt::kVisOnScreen)) + return kTRUE; return kFALSE; } @@ -282,18 +304,22 @@ Bool_t TGeoNode::IsOnScreen() const void TGeoNode::InspectNode() const { printf("== Inspecting node %s ", GetName()); - if (fMother) printf("mother volume %s. ", fMother->GetName()); - if (IsOverlapping()) printf("(Node is MANY)\n"); - else printf("\n"); + if (fMother) + printf("mother volume %s. ", fMother->GetName()); + if (IsOverlapping()) + printf("(Node is MANY)\n"); + else + printf("\n"); if (fOverlaps && fMother) { printf(" possibly overlapping with : "); - for (Int_t i=0; iGetNode(fOverlaps[i])->GetName()); printf("\n"); } printf("Transformation matrix:\n"); TGeoMatrix *matrix = GetMatrix(); - if (GetMatrix()) matrix->Print(); + if (GetMatrix()) + matrix->Print(); fVolume->Print(); } @@ -304,8 +330,10 @@ void TGeoNode::CheckShapes() { fVolume->CheckShapes(); Int_t nd = GetNdaughters(); - if (!nd) return; - for (Int_t i=0; iGetNode(i)->CheckShapes(); + if (!nd) + return; + for (Int_t i = 0; i < nd; i++) + fVolume->GetNode(i)->CheckShapes(); } //////////////////////////////////////////////////////////////////////////////// @@ -334,17 +362,23 @@ void TGeoNode::Draw(Option_t *option) void TGeoNode::DrawOverlaps() { - if (!fNovlp) {printf("node %s is ONLY\n", GetName()); return;} - if (!fOverlaps) {printf("node %s no overlaps\n", GetName()); return;} + if (!fNovlp) { + printf("node %s is ONLY\n", GetName()); + return; + } + if (!fOverlaps) { + printf("node %s no overlaps\n", GetName()); + return; + } TGeoNode *node; Int_t i; Int_t nd = fMother->GetNdaughters(); - for (i=0; iGetNode(i); node->GetVolume()->SetVisibility(kFALSE); } fVolume->SetVisibility(kTRUE); - for (i=0; iGetNode(fOverlaps[i]); node->GetVolume()->SetVisibility(kTRUE); } @@ -358,40 +392,41 @@ void TGeoNode::DrawOverlaps() void TGeoNode::FillIdArray(Int_t &ifree, Int_t &nodeid, Int_t *array) const { Int_t nd = GetNdaughters(); - if (!nd) return; + if (!nd) + return; TGeoNode *daughter; Int_t istart = ifree; // start index for daughters ifree += nd; - for (Int_t id=0; idFillIdArray(ifree, nodeid, array); } } - //////////////////////////////////////////////////////////////////////////////// /// Search for a node within the branch of this one. Int_t TGeoNode::FindNode(const TGeoNode *node, Int_t level) { Int_t nd = GetNdaughters(); - if (!nd) return -1; + if (!nd) + return -1; TIter next(fVolume->GetNodes()); TGeoNode *daughter; - while ((daughter=(TGeoNode*)next())) { - if (daughter==node) { - gGeoManager->GetListOfNodes()->AddAt(daughter,level+1); - return (level+1); + while ((daughter = (TGeoNode *)next())) { + if (daughter == node) { + gGeoManager->GetListOfNodes()->AddAt(daughter, level + 1); + return (level + 1); } } next.Reset(); Int_t new_level; - while ((daughter=(TGeoNode*)next())) { - new_level = daughter->FindNode(node, level+1); - if (new_level>=0) { - gGeoManager->GetListOfNodes()->AddAt(daughter, level+1); + while ((daughter = (TGeoNode *)next())) { + new_level = daughter->FindNode(node, level + 1); + if (new_level >= 0) { + gGeoManager->GetListOfNodes()->AddAt(daughter, level + 1); return new_level; } } @@ -403,47 +438,51 @@ Int_t TGeoNode::FindNode(const TGeoNode *node, Int_t level) void TGeoNode::SaveAttributes(std::ostream &out) { - if (IsVisStreamed()) return; + if (IsVisStreamed()) + return; SetVisStreamed(kTRUE); - char quote='"'; + char quote = '"'; Bool_t voldef = kFALSE; if ((fVolume->IsVisTouched()) && (!fVolume->IsVisStreamed())) { fVolume->SetVisStreamed(kTRUE); - out << " vol = gGeoManager->GetVolume("<GetName()<GetVolume(" << quote << fVolume->GetName() << quote << ");" << std::endl; voldef = kTRUE; if (!fVolume->IsVisDaughters()) - out << " vol->SetVisDaughters(kFALSE);"<SetVisDaughters(kFALSE);" << std::endl; if (fVolume->IsVisible()) { -/* - if (fVolume->GetLineColor() != gStyle->GetLineColor()) - out<<" vol->SetLineColor("<GetLineColor()<<");"<GetLineStyle() != gStyle->GetLineStyle()) - out<<" vol->SetLineStyle("<GetLineStyle()<<");"<GetLineWidth() != gStyle->GetLineWidth()) - out<<" vol->SetLineWidth("<GetLineWidth()<<");"<GetLineColor() != gStyle->GetLineColor()) + out<<" vol->SetLineColor("<GetLineColor()<<");"<GetLineStyle() != gStyle->GetLineStyle()) + out<<" vol->SetLineStyle("<GetLineStyle()<<");"<GetLineWidth() != gStyle->GetLineWidth()) + out<<" vol->SetLineWidth("<GetLineWidth()<<");"<SetVisibility(kFALSE);"<SetVisibility(kFALSE);" << std::endl; } } - if (!IsVisDaughters()) return; + if (!IsVisDaughters()) + return; Int_t nd = GetNdaughters(); - if (!nd) return; + if (!nd) + return; TGeoNode *node; - for (Int_t i=0; iIsVisStreamed()) continue; + if (node->IsVisStreamed()) + continue; if (node->IsVisTouched()) { if (!voldef) - out << " vol = gGeoManager->GetVolume("<GetName()<GetNode("<GetVolume(" << quote << fVolume->GetName() << quote << ");" << std::endl; + out << " node = vol->GetNode(" << i << ");" << std::endl; if (!node->IsVisDaughters()) { - out<<" node->VisibleDaughters(kFALSE);"<VisibleDaughters(kFALSE);" << std::endl; node->SetVisStreamed(kTRUE); continue; } if (!node->IsVisible()) - out<<" node->SetVisibility(kFALSE);"<SetVisibility(kFALSE);" << std::endl; } node->SaveAttributes(out); node->SetVisStreamed(kTRUE); @@ -460,9 +499,11 @@ void TGeoNode::SaveAttributes(std::ostream &out) void TGeoNode::SetUserExtension(TGeoExtension *ext) { - if (fUserExtension) fUserExtension->Release(); + if (fUserExtension) + fUserExtension->Release(); fUserExtension = 0; - if (ext) fUserExtension = ext->Grab(); + if (ext) + fUserExtension = ext->Grab(); } //////////////////////////////////////////////////////////////////////////////// @@ -475,9 +516,11 @@ void TGeoNode::SetUserExtension(TGeoExtension *ext) void TGeoNode::SetFWExtension(TGeoExtension *ext) { - if (fFWExtension) fFWExtension->Release(); + if (fFWExtension) + fFWExtension->Release(); fFWExtension = 0; - if (ext) fFWExtension = ext->Grab(); + if (ext) + fFWExtension = ext->Grab(); } //////////////////////////////////////////////////////////////////////////////// @@ -487,7 +530,8 @@ void TGeoNode::SetFWExtension(TGeoExtension *ext) TGeoExtension *TGeoNode::GrabUserExtension() const { - if (fUserExtension) return fUserExtension->Grab(); + if (fUserExtension) + return fUserExtension->Grab(); return 0; } @@ -498,7 +542,8 @@ TGeoExtension *TGeoNode::GrabUserExtension() const TGeoExtension *TGeoNode::GrabFWExtension() const { - if (fFWExtension) return fFWExtension->Grab(); + if (fFWExtension) + return fFWExtension->Grab(); return 0; } //////////////////////////////////////////////////////////////////////////////// @@ -507,8 +552,11 @@ TGeoExtension *TGeoNode::GrabFWExtension() const Bool_t TGeoNode::MayOverlap(Int_t iother) const { - if (!fOverlaps) return kFALSE; - for (Int_t i=0; iGetGeomPainter(); - if (!painter) return; + if (!painter) + return; painter->PaintNode(this, option); } @@ -601,10 +648,12 @@ void TGeoNode::PrintCandidates() const return; } TString overlap = "ONLY"; - for (Int_t id=0; idGetNode(check_list[id]); - if (node->IsOverlapping()) overlap = "MANY"; - else overlap = "ONLY"; + if (node->IsOverlapping()) + overlap = "MANY"; + else + overlap = "ONLY"; printf("%i %s %s\n", check_list[id], node->GetName(), overlap.Data()); } PrintOverlaps(); @@ -615,10 +664,13 @@ void TGeoNode::PrintCandidates() const void TGeoNode::PrintOverlaps() const { - if (!fOverlaps) {printf("node %s no overlaps\n", GetName()); return;} + if (!fOverlaps) { + printf("node %s no overlaps\n", GetName()); + return; + } printf("Overlaps for node %s :\n", GetName()); TGeoNode *node; - for (Int_t i=0; iGetNode(fOverlaps[i]); printf(" %s\n", node->GetName()); } @@ -630,8 +682,8 @@ void TGeoNode::PrintOverlaps() const Double_t TGeoNode::Safety(const Double_t *point, Bool_t in) const { Double_t local[3]; - GetMatrix()->MasterToLocal(point,local); - return fVolume->GetShape()->Safety(local,in); + GetMatrix()->MasterToLocal(point, local); + return fVolume->GetShape()->Safety(local, in); } //////////////////////////////////////////////////////////////////////////////// @@ -642,7 +694,7 @@ void TGeoNode::CopyOverlaps(Int_t *src, Int_t novlp) Int_t *ovlps = nullptr; if (src && (novlp > 0)) { ovlps = new Int_t[novlp]; - memcpy(ovlps, src, novlp*sizeof(Int_t)); + memcpy(ovlps, src, novlp * sizeof(Int_t)); } SetOverlaps(ovlps, novlp); } @@ -652,7 +704,8 @@ void TGeoNode::CopyOverlaps(Int_t *src, Int_t novlp) void TGeoNode::SetOverlaps(Int_t *ovlp, Int_t novlp) { - if (fOverlaps) delete [] fOverlaps; + if (fOverlaps) + delete[] fOverlaps; fOverlaps = ovlp; fNovlp = novlp; } @@ -662,9 +715,11 @@ void TGeoNode::SetOverlaps(Int_t *ovlp, Int_t novlp) void TGeoNode::SetVisibility(Bool_t vis) { - if (gGeoManager->IsClosed()) SetVisTouched(kTRUE); + if (gGeoManager->IsClosed()) + SetVisTouched(kTRUE); TGeoAtt::SetVisibility(vis); - if (vis && !fVolume->IsVisible()) fVolume->SetVisibility(vis); + if (vis && !fVolume->IsVisible()) + fVolume->SetVisibility(vis); gGeoManager->ModifiedPad(); } @@ -673,7 +728,8 @@ void TGeoNode::SetVisibility(Bool_t vis) void TGeoNode::VisibleDaughters(Bool_t vis) { - if (gGeoManager->IsClosed()) SetVisTouched(kTRUE); + if (gGeoManager->IsClosed()) + SetVisTouched(kTRUE); SetVisDaughters(vis); gGeoManager->ModifiedPad(); } @@ -690,25 +746,23 @@ ClassImp(TGeoNodeMatrix); TGeoNodeMatrix::TGeoNodeMatrix() { - fMatrix = 0; + fMatrix = 0; } //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoNodeMatrix::TGeoNodeMatrix(const TGeoVolume *vol, const TGeoMatrix *matrix) : - TGeoNode(vol) +TGeoNodeMatrix::TGeoNodeMatrix(const TGeoVolume *vol, const TGeoMatrix *matrix) : TGeoNode(vol) { - fMatrix = (TGeoMatrix*)matrix; - if (!fMatrix) fMatrix = gGeoIdentity; + fMatrix = (TGeoMatrix *)matrix; + if (!fMatrix) + fMatrix = gGeoIdentity; } //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoNodeMatrix::~TGeoNodeMatrix() -{ -} +TGeoNodeMatrix::~TGeoNodeMatrix() {} //////////////////////////////////////////////////////////////////////////////// /// return the total size in bytes of this node @@ -716,7 +770,7 @@ TGeoNodeMatrix::~TGeoNodeMatrix() Int_t TGeoNodeMatrix::GetByteCount() const { Int_t count = 40 + 4; // TGeoNode + fMatrix -// if (fMatrix) count += fMatrix->GetByteCount(); + // if (fMatrix) count += fMatrix->GetByteCount(); return count; } @@ -728,11 +782,15 @@ Int_t TGeoNodeMatrix::GetByteCount() const Int_t TGeoNodeMatrix::GetOptimalVoxels() const { Bool_t type = fVolume->GetShape()->IsCylType(); - if (!type) return 0; - if (!fMatrix->IsRotAboutZ()) return 0; + if (!type) + return 0; + if (!fMatrix->IsRotAboutZ()) + return 0; const Double_t *transl = fMatrix->GetTranslation(); - if (TMath::Abs(transl[0])>1E-10) return 0; - if (TMath::Abs(transl[1])>1E-10) return 0; + if (TMath::Abs(transl[0]) > 1E-10) + return 0; + if (TMath::Abs(transl[1]) > 1E-10) + return 0; return 1; } @@ -752,8 +810,10 @@ TGeoNode *TGeoNodeMatrix::MakeCopyNode() const node->CopyOverlaps(fOverlaps, fNovlp); // copy VC - if (IsVirtual()) node->SetVirtual(); - if (IsOverlapping()) node->SetOverlapping(); // <--- ADDED + if (IsVirtual()) + node->SetVirtual(); + if (IsOverlapping()) + node->SetOverlapping(); // <--- ADDED // Copy extensions node->SetUserExtension(fUserExtension); node->SetFWExtension(fFWExtension); @@ -766,8 +826,9 @@ TGeoNode *TGeoNodeMatrix::MakeCopyNode() const void TGeoNodeMatrix::SetMatrix(const TGeoMatrix *matrix) { - fMatrix = (TGeoMatrix*)matrix; - if (!fMatrix) fMatrix = gGeoIdentity; + fMatrix = (TGeoMatrix *)matrix; + if (!fMatrix) + fMatrix = gGeoIdentity; } /** \class TGeoNodeOffset @@ -791,8 +852,7 @@ TGeoNodeOffset::TGeoNodeOffset() //////////////////////////////////////////////////////////////////////////////// /// Constructor. Null pointer to matrix means identity transformation -TGeoNodeOffset::TGeoNodeOffset(const TGeoVolume *vol, Int_t index, Double_t offset) : - TGeoNode(vol) +TGeoNodeOffset::TGeoNodeOffset(const TGeoVolume *vol, Int_t index, Double_t offset) : TGeoNode(vol) { TObject::SetBit(kGeoNodeOffset); fOffset = offset; @@ -803,16 +863,14 @@ TGeoNodeOffset::TGeoNodeOffset(const TGeoVolume *vol, Int_t index, Double_t offs //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoNodeOffset::~TGeoNodeOffset() -{ -} +TGeoNodeOffset::~TGeoNodeOffset() {} //////////////////////////////////////////////////////////////////////////////// /// Get the index of this offset. Int_t TGeoNodeOffset::GetIndex() const { - return (fIndex+fFinder->GetDivIndex()); + return (fIndex + fFinder->GetDivIndex()); } //////////////////////////////////////////////////////////////////////////////// @@ -827,7 +885,8 @@ TGeoNode *TGeoNodeOffset::MakeCopyNode() const node->SetMotherVolume(fMother); // set the copy number node->SetNumber(fNumber); - if (IsVirtual()) node->SetVirtual(); + if (IsVirtual()) + node->SetVirtual(); // set the finder node->SetFinder(GetFinder()); // set extensions @@ -951,12 +1010,14 @@ TGeoIterator::TGeoIterator(const TGeoIterator &iter) fMustResume = kFALSE; fMustStop = kFALSE; fType = iter.GetType(); - fArray = new Int_t[30+ 30*Int_t(fLevel/30)]; - for (Int_t i=0; iGetName(); fPlugin = iter.fPlugin; - fPluginAutoexec = iter.fPluginAutoexec;; + fPluginAutoexec = iter.fPluginAutoexec; + ; } //////////////////////////////////////////////////////////////////////////////// @@ -964,7 +1025,8 @@ TGeoIterator::TGeoIterator(const TGeoIterator &iter) TGeoIterator::~TGeoIterator() { - if (fArray) delete [] fArray; + if (fArray) + delete[] fArray; delete fMatrix; } @@ -973,20 +1035,25 @@ TGeoIterator::~TGeoIterator() TGeoIterator &TGeoIterator::operator=(const TGeoIterator &iter) { - if (&iter == this) return *this; + if (&iter == this) + return *this; fTop = iter.GetTopVolume(); fLevel = iter.GetLevel(); fMustResume = kFALSE; fMustStop = kFALSE; fType = iter.GetType(); - if (fArray) delete [] fArray; - fArray = new Int_t[30+ 30*Int_t(fLevel/30)]; - for (Int_t i=0; iGetName(); fPlugin = iter.fPlugin; - fPluginAutoexec = iter.fPluginAutoexec;; + fPluginAutoexec = iter.fPluginAutoexec; + ; return *this; } @@ -995,7 +1062,8 @@ TGeoIterator &TGeoIterator::operator=(const TGeoIterator &iter) TGeoNode *TGeoIterator::Next() { - if (fMustStop) return 0; + if (fMustStop) + return 0; TGeoNode *mother = 0; TGeoNode *next = 0; Int_t i; @@ -1007,63 +1075,73 @@ TGeoNode *TGeoIterator::Next() if (!fLevel) { fArray[++fLevel] = 0; next = fTop->GetNode(0); - if (fPlugin && fPluginAutoexec) fPlugin->ProcessNode(); + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); return next; } next = fTop->GetNode(fArray[1]); // Move to current node - for (i=2; iGetDaughter(fArray[i]); } if (fMustResume) { fMustResume = kFALSE; - if (fPlugin && fPluginAutoexec) fPlugin->ProcessNode(); + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); return next; } switch (fType) { - case 0: // default next daughter behavior - nd = next->GetNdaughters(); - if (nd) { - // First daughter next - fLevel++; - if ((fLevel%30)==0) IncreaseArray(); - fArray[fLevel] = 0; - if (fPlugin && fPluginAutoexec) fPlugin->ProcessNode(); - return next->GetDaughter(0); - } - // cd up and pick next - while (next) { - next = GetNode(fLevel-1); - if (!next) { - nd = fTop->GetNdaughters(); - if (fArray[fLevel]ProcessNode(); - return fTop->GetNode(fArray[fLevel]); - } - fMustStop = kTRUE; - return 0; - } else { - nd = next->GetNdaughters(); - if (fArray[fLevel]ProcessNode(); - return next->GetDaughter(fArray[fLevel]); - } + case 0: // default next daughter behavior + nd = next->GetNdaughters(); + if (nd) { + // First daughter next + fLevel++; + if ((fLevel % 30) == 0) + IncreaseArray(); + fArray[fLevel] = 0; + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); + return next->GetDaughter(0); + } + // cd up and pick next + while (next) { + next = GetNode(fLevel - 1); + if (!next) { + nd = fTop->GetNdaughters(); + if (fArray[fLevel] < nd - 1) { + fArray[fLevel]++; + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); + return fTop->GetNode(fArray[fLevel]); + } + fMustStop = kTRUE; + return 0; + } else { + nd = next->GetNdaughters(); + if (fArray[fLevel] < nd - 1) { + fArray[fLevel]++; + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); + return next->GetDaughter(fArray[fLevel]); } - fLevel--; - } - break; - case 1: // one level search - if (mother) nd = mother->GetNdaughters(); - if (fArray[fLevel]ProcessNode(); - if (!mother) return fTop->GetNode(fArray[fLevel]); - else return mother->GetDaughter(fArray[fLevel]); } + fLevel--; + } + break; + case 1: // one level search + if (mother) + nd = mother->GetNdaughters(); + if (fArray[fLevel] < nd - 1) { + fArray[fLevel]++; + if (fPlugin && fPluginAutoexec) + fPlugin->ProcessNode(); + if (!mother) + return fTop->GetNode(fArray[fLevel]); + else + return mother->GetDaughter(fArray[fLevel]); + } } fMustStop = kTRUE; return 0; @@ -1083,10 +1161,11 @@ TGeoNode *TGeoIterator::operator()() const TGeoMatrix *TGeoIterator::GetCurrentMatrix() const { fMatrix->Clear(); - if (!fLevel) return fMatrix; + if (!fLevel) + return fMatrix; TGeoNode *node = fTop->GetNode(fArray[1]); fMatrix->Multiply(node->GetMatrix()); - for (Int_t i=2; iGetDaughter(fArray[i]); fMatrix->Multiply(node->GetMatrix()); } @@ -1098,9 +1177,11 @@ const TGeoMatrix *TGeoIterator::GetCurrentMatrix() const TGeoNode *TGeoIterator::GetNode(Int_t level) const { - if (!level || level>fLevel) return 0; + if (!level || level > fLevel) + return 0; TGeoNode *node = fTop->GetNode(fArray[1]); - for (Int_t i=2; iGetDaughter(fArray[i]); + for (Int_t i = 2; i < level + 1; i++) + node = node->GetDaughter(fArray[i]); return node; } @@ -1110,11 +1191,12 @@ TGeoNode *TGeoIterator::GetNode(Int_t level) const void TGeoIterator::GetPath(TString &path) const { path = fTopName; - if (!fLevel) return; + if (!fLevel) + return; TGeoNode *node = fTop->GetNode(fArray[1]); path += "/"; path += node->GetName(); - for (Int_t i=2; iGetDaughter(fArray[i]); path += "/"; path += node->GetName(); @@ -1126,9 +1208,9 @@ void TGeoIterator::GetPath(TString &path) const void TGeoIterator::IncreaseArray() { - Int_t *array = new Int_t[fLevel+30]; - memcpy(array, fArray, fLevel*sizeof(Int_t)); - delete [] fArray; + Int_t *array = new Int_t[fLevel + 30]; + memcpy(array, fArray, fLevel * sizeof(Int_t)); + delete[] fArray; fArray = array; } @@ -1137,7 +1219,8 @@ void TGeoIterator::IncreaseArray() void TGeoIterator::Reset(TGeoVolume *top) { - if (top) fTop = top; + if (top) + fTop = top; fLevel = 0; fMustResume = kFALSE; fMustStop = kFALSE; @@ -1159,34 +1242,35 @@ void TGeoIterator::Skip() { fMustResume = kTRUE; TGeoNode *next = GetNode(fLevel); - if (!next) return; + if (!next) + return; Int_t nd; switch (fType) { - case 0: // default next daughter behavior - // cd up and pick next - while (next) { - next = GetNode(fLevel-1); - nd = (next==0)?fTop->GetNdaughters():next->GetNdaughters(); - if (fArray[fLevel]GetNdaughters():next->GetNdaughters(); - if (fArray[fLevel]GetNdaughters() : next->GetNdaughters(); + if (fArray[fLevel] < nd - 1) { ++fArray[fLevel]; return; } - fMustStop = kTRUE; - break; + fLevel--; + if (!fLevel) { + fMustStop = kTRUE; + return; + } + } + break; + case 1: // one level search + next = GetNode(fLevel - 1); + nd = (next == 0) ? fTop->GetNdaughters() : next->GetNdaughters(); + if (fArray[fLevel] < nd - 1) { + ++fArray[fLevel]; + return; + } + fMustStop = kTRUE; + break; } } @@ -1196,5 +1280,6 @@ void TGeoIterator::Skip() void TGeoIterator::SetUserPlugin(TGeoIteratorPlugin *plugin) { fPlugin = plugin; - if (plugin) plugin->SetIterator(this); + if (plugin) + plugin->SetIterator(this); } diff --git a/geom/geom/src/TGeoOpticalSurface.cxx b/geom/geom/src/TGeoOpticalSurface.cxx index 38c5fa79facdc..59f0545a6d281 100644 --- a/geom/geom/src/TGeoOpticalSurface.cxx +++ b/geom/geom/src/TGeoOpticalSurface.cxx @@ -9,7 +9,6 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ - /** \class TGeoOpticalSurface \ingroup Geometry_classes @@ -25,13 +24,11 @@ This is a wrapper class to G4OpticalSurface #include "TGeoNode.h" #include "TGDMLMatrix.h" -ClassImp(TGeoOpticalSurface) -ClassImp(TGeoSkinSurface) -ClassImp(TGeoBorderSurface) +ClassImp(TGeoOpticalSurface); //_____________________________________________________________________________ -TGeoOpticalSurface::TGeoOpticalSurface(const char *name, ESurfaceModel model, ESurfaceFinish finish, - ESurfaceType type, Double_t value) +TGeoOpticalSurface::TGeoOpticalSurface(const char *name, ESurfaceModel model, ESurfaceFinish finish, ESurfaceType type, + Double_t value) : TNamed(name, ""), fType(type), fModel(model), fFinish(finish), fValue(value) { // Constructor @@ -255,8 +252,9 @@ const char *TGeoOpticalSurface::GetPropertyRef(const char *property) TGDMLMatrix *TGeoOpticalSurface::GetProperty(const char *property) const { // Find reference for a given property - TNamed *prop = (TNamed*)fProperties.FindObject(property); - if ( !prop ) return nullptr; + TNamed *prop = (TNamed *)fProperties.FindObject(property); + if (!prop) + return nullptr; return gGeoManager->GetGDMLMatrix(prop->GetTitle()); } @@ -264,8 +262,9 @@ TGDMLMatrix *TGeoOpticalSurface::GetProperty(const char *property) const TGDMLMatrix *TGeoOpticalSurface::GetProperty(Int_t i) const { // Find reference for a given property - TNamed *prop = (TNamed*)fProperties.At(i); - if ( !prop ) return nullptr; + TNamed *prop = (TNamed *)fProperties.At(i); + if (!prop) + return nullptr; return gGeoManager->GetGDMLMatrix(prop->GetTitle()); } @@ -296,6 +295,8 @@ void TGeoOpticalSurface::Print(Option_t *) const } } +ClassImp(TGeoSkinSurface); + //_____________________________________________________________________________ void TGeoSkinSurface::Print(Option_t *) const { @@ -307,6 +308,8 @@ void TGeoSkinSurface::Print(Option_t *) const printf("*** skinsurface: %s surfaceproperty: %s volumeref: %s \n", GetName(), GetTitle(), fVolume->GetName()); } +ClassImp(TGeoBorderSurface); + //_____________________________________________________________________________ void TGeoBorderSurface::Print(Option_t *) const { diff --git a/geom/geom/src/TGeoPara.cxx b/geom/geom/src/TGeoPara.cxx index 147e8df301304..d443902ce097f 100644 --- a/geom/geom/src/TGeoPara.cxx +++ b/geom/geom/src/TGeoPara.cxx @@ -84,9 +84,8 @@ TGeoPara::TGeoPara() //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying minimum and maximum radius -TGeoPara::TGeoPara(Double_t dx, Double_t dy, Double_t dz, Double_t alpha, - Double_t theta, Double_t phi) - :TGeoBBox(0, 0, 0) +TGeoPara::TGeoPara(Double_t dx, Double_t dy, Double_t dz, Double_t alpha, Double_t theta, Double_t phi) + : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoPara); fX = dx; @@ -95,24 +94,24 @@ TGeoPara::TGeoPara(Double_t dx, Double_t dy, Double_t dz, Double_t alpha, fAlpha = alpha; fTheta = theta; fPhi = phi; - fTxy = TMath::Tan(alpha*TMath::DegToRad()); - Double_t tth = TMath::Tan(theta*TMath::DegToRad()); - Double_t ph = phi*TMath::DegToRad(); - fTxz = tth*TMath::Cos(ph); - fTyz = tth*TMath::Sin(ph); - if ((fX<0) || (fY<0) || (fZ<0)) { -// printf("para : %f %f %f\n", fX, fY, fZ); + fTxy = TMath::Tan(alpha * TMath::DegToRad()); + Double_t tth = TMath::Tan(theta * TMath::DegToRad()); + Double_t ph = phi * TMath::DegToRad(); + fTxz = tth * TMath::Cos(ph); + fTyz = tth * TMath::Sin(ph); + if ((fX < 0) || (fY < 0) || (fZ < 0)) { + // printf("para : %f %f %f\n", fX, fY, fZ); SetShapeBit(kGeoRunTimeShape); - } - else ComputeBBox(); + } else + ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying minimum and maximum radius -TGeoPara::TGeoPara(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t alpha, - Double_t theta, Double_t phi) - :TGeoBBox(name, 0, 0, 0) +TGeoPara::TGeoPara(const char *name, Double_t dx, Double_t dy, Double_t dz, Double_t alpha, Double_t theta, + Double_t phi) + : TGeoBBox(name, 0, 0, 0) { SetShapeBit(TGeoShape::kGeoPara); fX = dx; @@ -121,16 +120,16 @@ TGeoPara::TGeoPara(const char *name, Double_t dx, Double_t dy, Double_t dz, Doub fAlpha = alpha; fTheta = theta; fPhi = phi; - fTxy = TMath::Tan(alpha*TMath::DegToRad()); - Double_t tth = TMath::Tan(theta*TMath::DegToRad()); - Double_t ph = phi*TMath::DegToRad(); - fTxz = tth*TMath::Cos(ph); - fTyz = tth*TMath::Sin(ph); - if ((fX<0) || (fY<0) || (fZ<0)) { -// printf("para : %f %f %f\n", fX, fY, fZ); + fTxy = TMath::Tan(alpha * TMath::DegToRad()); + Double_t tth = TMath::Tan(theta * TMath::DegToRad()); + Double_t ph = phi * TMath::DegToRad(); + fTxz = tth * TMath::Cos(ph); + fTyz = tth * TMath::Sin(ph); + if ((fX < 0) || (fY < 0) || (fZ < 0)) { + // printf("para : %f %f %f\n", fX, fY, fZ); SetShapeBit(kGeoRunTimeShape); - } - else ComputeBBox(); + } else + ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// @@ -142,28 +141,27 @@ TGeoPara::TGeoPara(const char *name, Double_t dx, Double_t dy, Double_t dz, Doub /// - param[4] = theta /// - param[5] = phi -TGeoPara::TGeoPara(Double_t *param) - :TGeoBBox(0, 0, 0) +TGeoPara::TGeoPara(Double_t *param) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoPara); SetDimensions(param); - if ((fX<0) || (fY<0) || (fZ<0)) SetShapeBit(kGeoRunTimeShape); - else ComputeBBox(); + if ((fX < 0) || (fY < 0) || (fZ < 0)) + SetShapeBit(kGeoRunTimeShape); + else + ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoPara::~TGeoPara() -{ -} +TGeoPara::~TGeoPara() {} //////////////////////////////////////////////////////////////////////////////// /// Computes capacity of the shape in [length^3] Double_t TGeoPara::Capacity() const { - Double_t capacity = 8.*fX*fY*fZ; + Double_t capacity = 8. * fX * fY * fZ; return capacity; } @@ -172,11 +170,11 @@ Double_t TGeoPara::Capacity() const void TGeoPara::ComputeBBox() { - Double_t dx = fX+fY*TMath::Abs(fTxy)+fZ*TMath::Abs(fTxz); - Double_t dy = fY+fZ*TMath::Abs(fTyz); + Double_t dx = fX + fY * TMath::Abs(fTxy) + fZ * TMath::Abs(fTxz); + Double_t dy = fY + fZ * TMath::Abs(fTyz); Double_t dz = fZ; TGeoBBox::SetBoxDimensions(dx, dy, dz); - memset(fOrigin, 0, 3*sizeof(Double_t)); + memset(fOrigin, 0, 3 * sizeof(Double_t)); } //////////////////////////////////////////////////////////////////////////////// @@ -186,36 +184,36 @@ void TGeoPara::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ { Double_t saf[3]; // distance from point to higher Z face - saf[0] = TMath::Abs(fZ-TMath::Abs(point[2])); // Z + saf[0] = TMath::Abs(fZ - TMath::Abs(point[2])); // Z - Double_t yt = point[1]-fTyz*point[2]; - saf[1] = TMath::Abs(fY-TMath::Abs(yt)); // Y + Double_t yt = point[1] - fTyz * point[2]; + saf[1] = TMath::Abs(fY - TMath::Abs(yt)); // Y // cos of angle YZ - Double_t cty = 1.0/TMath::Sqrt(1.0+fTyz*fTyz); + Double_t cty = 1.0 / TMath::Sqrt(1.0 + fTyz * fTyz); - Double_t xt = point[0]-fTxz*point[2]-fTxy*yt; - saf[2] = TMath::Abs(fX-TMath::Abs(xt)); // X + Double_t xt = point[0] - fTxz * point[2] - fTxy * yt; + saf[2] = TMath::Abs(fX - TMath::Abs(xt)); // X // cos of angle XZ - Double_t ctx = 1.0/TMath::Sqrt(1.0+fTxy*fTxy+fTxz*fTxz); + Double_t ctx = 1.0 / TMath::Sqrt(1.0 + fTxy * fTxy + fTxz * fTxz); saf[2] *= ctx; saf[1] *= cty; - Int_t i = TMath::LocMin(3,saf); + Int_t i = TMath::LocMin(3, saf); switch (i) { - case 0: - norm[0] = norm[1] = 0; - norm[2] = TMath::Sign(1.,dir[2]); - return; - case 1: - norm[0] = 0; - norm[1] = cty; - norm[2] = - fTyz*cty; - break; - case 2: - norm[0] = TMath::Cos(fTheta*TMath::DegToRad())*TMath::Cos(fAlpha*TMath::DegToRad()); - norm[1] = - TMath::Cos(fTheta*TMath::DegToRad())*TMath::Sin(fAlpha*TMath::DegToRad()); - norm[2] = -TMath::Sin(fTheta*TMath::DegToRad()); + case 0: + norm[0] = norm[1] = 0; + norm[2] = TMath::Sign(1., dir[2]); + return; + case 1: + norm[0] = 0; + norm[1] = cty; + norm[2] = -fTyz * cty; + break; + case 2: + norm[0] = TMath::Cos(fTheta * TMath::DegToRad()) * TMath::Cos(fAlpha * TMath::DegToRad()); + norm[1] = -TMath::Cos(fTheta * TMath::DegToRad()) * TMath::Sin(fAlpha * TMath::DegToRad()); + norm[2] = -TMath::Sin(fTheta * TMath::DegToRad()); } - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -228,12 +226,15 @@ void TGeoPara::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoPara::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fZ) return kFALSE; + if (TMath::Abs(point[2]) > fZ) + return kFALSE; // check X and Y - Double_t yt=point[1]-fTyz*point[2]; - if (TMath::Abs(yt) > fY) return kFALSE; - Double_t xt=point[0]-fTxz*point[2]-fTxy*yt; - if (TMath::Abs(xt) > fX) return kFALSE; + Double_t yt = point[1] - fTyz * point[2]; + if (TMath::Abs(yt) > fY) + return kFALSE; + Double_t xt = point[0] - fTxz * point[2] - fTxy * yt; + if (TMath::Abs(xt) > fX) + return kFALSE; return kTRUE; } @@ -241,43 +242,52 @@ Bool_t TGeoPara::Contains(const Double_t *point) const /// compute distance from inside point to surface of the para /// Boundary safe algorithm. -Double_t TGeoPara::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoPara::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { - // compute safety + if (iact < 3 && safe) { + // compute safety *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } Double_t saf[2]; Double_t snxt = TGeoShape::Big(); Double_t s; - saf[0] = fZ+point[2]; - saf[1] = fZ-point[2]; - if (!TGeoShape::IsSameWithinTolerance(dir[2],0)) { - s = (dir[2]>0)?(saf[1]/dir[2]):(-saf[0]/dir[2]); - if (s<0) return 0.0; - if (s 0) ? (saf[1] / dir[2]) : (-saf[0] / dir[2]); + if (s < 0) + return 0.0; + if (s < snxt) + snxt = s; } // distance from point to center axis on Y - Double_t yt = point[1]-fTyz*point[2]; - saf[0] = fY+yt; - saf[1] = fY-yt; - Double_t dy = dir[1]-fTyz*dir[2]; - if (!TGeoShape::IsSameWithinTolerance(dy,0)) { - s = (dy>0)?(saf[1]/dy):(-saf[0]/dy); - if (s<0) return 0.0; - if (s 0) ? (saf[1] / dy) : (-saf[0] / dy); + if (s < 0) + return 0.0; + if (s < snxt) + snxt = s; } // distance from point to center axis on X - Double_t xt = point[0]-fTxz*point[2]-fTxy*yt; - saf[0] = fX+xt; - saf[1] = fX-xt; - Double_t dx = dir[0]-fTxz*dir[2]-fTxy*dy; - if (!TGeoShape::IsSameWithinTolerance(dx,0)) { - s = (dx>0)?(saf[1]/dx):(-saf[0]/dx); - if (s<0) return 0.0; - if (s 0) ? (saf[1] / dx) : (-saf[0] / dx); + if (s < 0) + return 0.0; + if (s < snxt) + snxt = s; } return snxt; } @@ -285,78 +295,90 @@ Double_t TGeoPara::DistFromInside(const Double_t *point, const Double_t *dir, In //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the para -Double_t TGeoPara::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoPara::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { // compute safe distance *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } Bool_t in = kTRUE; Double_t safz; - safz = TMath::Abs(point[2])-fZ; - if (safz>0) { + safz = TMath::Abs(point[2]) - fZ; + if (safz > 0) { // outside Z - if (point[2]*dir[2]>=0) return TGeoShape::Big(); + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); in = kFALSE; } - Double_t yt=point[1]-fTyz*point[2]; - Double_t safy = TMath::Abs(yt)-fY; - Double_t dy=dir[1]-fTyz*dir[2]; - if (safy>0) { - if (yt*dy>=0) return TGeoShape::Big(); + Double_t yt = point[1] - fTyz * point[2]; + Double_t safy = TMath::Abs(yt) - fY; + Double_t dy = dir[1] - fTyz * dir[2]; + if (safy > 0) { + if (yt * dy >= 0) + return TGeoShape::Big(); in = kFALSE; } - Double_t xt=point[0]-fTxy*yt-fTxz*point[2]; - Double_t safx = TMath::Abs(xt)-fX; - Double_t dx=dir[0]-fTxy*dy-fTxz*dir[2]; - if (safx>0) { - if (xt*dx>=0) return TGeoShape::Big(); + Double_t xt = point[0] - fTxy * yt - fTxz * point[2]; + Double_t safx = TMath::Abs(xt) - fX; + Double_t dx = dir[0] - fTxy * dy - fTxz * dir[2]; + if (safx > 0) { + if (xt * dx >= 0) + return TGeoShape::Big(); in = kFALSE; } // protection in case point is actually inside if (in) { - if (safz>safx && safz>safy) { - if (point[2]*dir[2]>0) return TGeoShape::Big(); + if (safz > safx && safz > safy) { + if (point[2] * dir[2] > 0) + return TGeoShape::Big(); return 0.0; } - if (safx>safy) { - if (xt*dx>0) return TGeoShape::Big(); + if (safx > safy) { + if (xt * dx > 0) + return TGeoShape::Big(); return 0.0; } - if (yt*dy>0) return TGeoShape::Big(); + if (yt * dy > 0) + return TGeoShape::Big(); return 0.0; } - Double_t xnew,ynew,znew; - if (safz>0) { - Double_t snxt = safz/TMath::Abs(dir[2]); - xnew = point[0]+snxt*dir[0]; - ynew = point[1]+snxt*dir[1]; - znew = (point[2]>0)?fZ:(-fZ); - Double_t ytn = ynew-fTyz*znew; - if (TMath::Abs(ytn)<=fY) { - Double_t xtn = xnew-fTxy*ytn-fTxz*znew; - if (TMath::Abs(xtn)<=fX) return snxt; + Double_t xnew, ynew, znew; + if (safz > 0) { + Double_t snxt = safz / TMath::Abs(dir[2]); + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + znew = (point[2] > 0) ? fZ : (-fZ); + Double_t ytn = ynew - fTyz * znew; + if (TMath::Abs(ytn) <= fY) { + Double_t xtn = xnew - fTxy * ytn - fTxz * znew; + if (TMath::Abs(xtn) <= fX) + return snxt; } } - if (safy>0) { - Double_t snxt = safy/TMath::Abs(dy); - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew)<=fZ) { - Double_t ytn = (yt>0)?fY:(-fY); - xnew = point[0]+snxt*dir[0]; - Double_t xtn = xnew-fTxy*ytn-fTxz*znew; - if (TMath::Abs(xtn)<=fX) return snxt; + if (safy > 0) { + Double_t snxt = safy / TMath::Abs(dy); + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) <= fZ) { + Double_t ytn = (yt > 0) ? fY : (-fY); + xnew = point[0] + snxt * dir[0]; + Double_t xtn = xnew - fTxy * ytn - fTxz * znew; + if (TMath::Abs(xtn) <= fX) + return snxt; } } - if (safx>0) { - Double_t snxt = safx/TMath::Abs(dx); - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew)<=fZ) { - ynew = point[1]+snxt*dir[1]; - Double_t ytn = ynew-fTyz*znew; - if (TMath::Abs(ytn)<=fY) return snxt; + if (safx > 0) { + Double_t snxt = safx / TMath::Abs(dx); + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) <= fZ) { + ynew = point[1] + snxt * dir[1]; + Double_t ytn = ynew - fTyz * znew; + if (TMath::Abs(ytn) <= fY) + return snxt; } } return TGeoShape::Big(); @@ -368,43 +390,41 @@ Double_t TGeoPara::DistFromOutside(const Double_t *point, const Double_t *dir, I /// to created division cell volume. In case a wrong division axis is supplied, /// returns pointer to volume to be divided. -TGeoVolume *TGeoPara::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoPara::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached - Double_t end=start+ndiv*step; + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- divide on X - shape = new TGeoPara(step/2, fY, fZ,fAlpha,fTheta, fPhi); - finder = new TGeoPatternParaX(voldiv, ndiv, start, end); - opt = "X"; - break; - case 2: //--- divide on Y - shape = new TGeoPara(fX, step/2, fZ, fAlpha, fTheta, fPhi); - finder = new TGeoPatternParaY(voldiv, ndiv, start, end); - opt = "Y"; - break; - case 3: //--- divide on Z - shape = new TGeoPara(fX, fY, step/2, fAlpha, fTheta, fPhi); - finder = new TGeoPatternParaZ(voldiv, ndiv, start, end); - opt = "Z"; - break; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + case 1: //--- divide on X + shape = new TGeoPara(step / 2, fY, fZ, fAlpha, fTheta, fPhi); + finder = new TGeoPatternParaX(voldiv, ndiv, start, end); + opt = "X"; + break; + case 2: //--- divide on Y + shape = new TGeoPara(fX, step / 2, fZ, fAlpha, fTheta, fPhi); + finder = new TGeoPatternParaY(voldiv, ndiv, start, end); + opt = "Y"; + break; + case 3: //--- divide on Z + shape = new TGeoPara(fX, fY, step / 2, fAlpha, fTheta, fPhi); + finder = new TGeoPatternParaZ(voldiv, ndiv, start, end); + opt = "Z"; + break; + default: Error("Divide", "Wrong axis type for division"); return 0; } vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); voldiv->SetFinder(finder); finder->SetDivIndex(voldiv->GetNdaughters()); - for (Int_t ic=0; icAddNodeOffset(vol, ic, start+step/2.+ic*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); + for (Int_t ic = 0; ic < ndiv; ic++) { + voldiv->AddNodeOffset(vol, ic, start + step / 2. + ic * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); } return vmulti; } @@ -418,21 +438,21 @@ Double_t TGeoPara::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = -fX; - xhi = fX; - dx = xhi-xlo; - return dx; - case 2: - xlo = -fY; - xhi = fY; - dx = xhi-xlo; - return dx; - case 3: - xlo = -fZ; - xhi = fZ; - dx = xhi-xlo; - return dx; + case 1: + xlo = -fX; + xhi = fX; + dx = xhi - xlo; + return dx; + case 2: + xlo = -fY; + xhi = fY; + dx = xhi - xlo; + return dx; + case 3: + xlo = -fZ; + xhi = fZ; + dx = xhi - xlo; + return dx; } return dx; } @@ -451,7 +471,7 @@ void TGeoPara::GetBoundingCylinder(Double_t *param) const Int_t TGeoPara::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const { - dx=dy=dz=0; + dx = dy = dz = 0; if (mat->IsRotation()) { Error("GetFittingBox", "cannot handle parametrized rotated volumes"); return 1; // ### rotation not accepted ### @@ -469,14 +489,14 @@ Int_t TGeoPara::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ dd[1] = parambox->GetDY(); dd[2] = parambox->GetDZ(); //-> check if Z range is fixed - if (dd[2]<0) { - dd[2] = TMath::Min(origin[2]+fZ, fZ-origin[2]); - if (dd[2]<0) { + if (dd[2] < 0) { + dd[2] = TMath::Min(origin[2] + fZ, fZ - origin[2]); + if (dd[2] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } } - if (dd[0]>=0 && dd[1]>=0) { + if (dd[0] >= 0 && dd[1] >= 0) { dx = dd[0]; dy = dd[1]; dz = dd[2]; @@ -485,31 +505,32 @@ Int_t TGeoPara::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ //-> check now range at Z = origin[2] +/- dd[2] Double_t upper[8]; Double_t lower[8]; - Double_t z=origin[2]-dd[2]; - lower[0]=z*fTxz-fTxy*fY-fX; - lower[1]=-fY+z*fTyz; - lower[2]=z*fTxz+fTxy*fY-fX; - lower[3]=fY+z*fTyz; - lower[4]=z*fTxz+fTxy*fY+fX; - lower[5]=fY+z*fTyz; - lower[6]=z*fTxz-fTxy*fY+fX; - lower[7]=-fY+z*fTyz; - z=origin[2]+dd[2]; - upper[0]=z*fTxz-fTxy*fY-fX; - upper[1]=-fY+z*fTyz; - upper[2]=z*fTxz+fTxy*fY-fX; - upper[3]=fY+z*fTyz; - upper[4]=z*fTxz+fTxy*fY+fX; - upper[5]=fY+z*fTyz; - upper[6]=z*fTxz-fTxy*fY+fX; - upper[7]=-fY+z*fTyz; - - for (Int_t iaxis=0; iaxis<2; iaxis++) { - if (dd[iaxis]>=0) continue; + Double_t z = origin[2] - dd[2]; + lower[0] = z * fTxz - fTxy * fY - fX; + lower[1] = -fY + z * fTyz; + lower[2] = z * fTxz + fTxy * fY - fX; + lower[3] = fY + z * fTyz; + lower[4] = z * fTxz + fTxy * fY + fX; + lower[5] = fY + z * fTyz; + lower[6] = z * fTxz - fTxy * fY + fX; + lower[7] = -fY + z * fTyz; + z = origin[2] + dd[2]; + upper[0] = z * fTxz - fTxy * fY - fX; + upper[1] = -fY + z * fTyz; + upper[2] = z * fTxz + fTxy * fY - fX; + upper[3] = fY + z * fTyz; + upper[4] = z * fTxz + fTxy * fY + fX; + upper[5] = fY + z * fTyz; + upper[6] = z * fTxz - fTxy * fY + fX; + upper[7] = -fY + z * fTyz; + + for (Int_t iaxis = 0; iaxis < 2; iaxis++) { + if (dd[iaxis] >= 0) + continue; Double_t ddmin = TGeoShape::Big(); - for (Int_t ivert=0; ivert<4; ivert++) { - ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis]-lower[2*ivert+iaxis])); - ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis]-upper[2*ivert+iaxis])); + for (Int_t ivert = 0; ivert < 4; ivert++) { + ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis] - lower[2 * ivert + iaxis])); + ddmin = TMath::Min(ddmin, TMath::Abs(origin[iaxis] - upper[2 * ivert + iaxis])); } dd[iaxis] = ddmin; } @@ -525,18 +546,25 @@ Int_t TGeoPara::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ TGeoShape *TGeoPara::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoPara)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; } Double_t dx, dy, dz; - if (fX<0) dx=((TGeoPara*)mother)->GetX(); - else dx=fX; - if (fY<0) dy=((TGeoPara*)mother)->GetY(); - else dy=fY; - if (fZ<0) dz=((TGeoPara*)mother)->GetZ(); - else dz=fZ; + if (fX < 0) + dx = ((TGeoPara *)mother)->GetX(); + else + dx = fX; + if (fY < 0) + dy = ((TGeoPara *)mother)->GetY(); + else + dy = fY; + if (fZ < 0) + dz = ((TGeoPara *)mother)->GetZ(); + else + dz = fZ; return (new TGeoPara(dx, dy, dz, fAlpha, fTheta, fPhi)); } @@ -564,22 +592,24 @@ Double_t TGeoPara::Safety(const Double_t *point, Bool_t in) const { Double_t saf[3]; // distance from point to higher Z face - saf[0] = fZ-TMath::Abs(point[2]); // Z + saf[0] = fZ - TMath::Abs(point[2]); // Z - Double_t yt = point[1]-fTyz*point[2]; - saf[1] = fY-TMath::Abs(yt); // Y + Double_t yt = point[1] - fTyz * point[2]; + saf[1] = fY - TMath::Abs(yt); // Y // cos of angle YZ - Double_t cty = 1.0/TMath::Sqrt(1.0+fTyz*fTyz); + Double_t cty = 1.0 / TMath::Sqrt(1.0 + fTyz * fTyz); - Double_t xt = point[0]-fTxz*point[2]-fTxy*yt; - saf[2] = fX-TMath::Abs(xt); // X + Double_t xt = point[0] - fTxz * point[2] - fTxy * yt; + saf[2] = fX - TMath::Abs(xt); // X // cos of angle XZ - Double_t ctx = 1.0/TMath::Sqrt(1.0+fTxy*fTxy+fTxz*fTxz); + Double_t ctx = 1.0 / TMath::Sqrt(1.0 + fTxy * fTxy + fTxz * fTxz); saf[2] *= ctx; saf[1] *= cty; - if (in) return saf[TMath::LocMin(3,saf)]; - for (Int_t i=0; i<3; i++) saf[i]=-saf[i]; - return saf[TMath::LocMax(3,saf)]; + if (in) + return saf[TMath::LocMin(3, saf)]; + for (Int_t i = 0; i < 3; i++) + saf[i] = -saf[i]; + return saf[TMath::LocMax(3, saf)]; } //////////////////////////////////////////////////////////////////////////////// @@ -587,15 +617,17 @@ Double_t TGeoPara::Safety(const Double_t *point, Bool_t in) const void TGeoPara::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dx = " << fX << ";" << std::endl; out << " dy = " << fY << ";" << std::endl; out << " dz = " << fZ << ";" << std::endl; - out << " alpha = " << fAlpha<< ";" << std::endl; + out << " alpha = " << fAlpha << ";" << std::endl; out << " theta = " << fTheta << ";" << std::endl; out << " phi = " << fPhi << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoPara(\"" << GetName() << "\",dx,dy,dz,alpha,theta,phi);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoPara(\"" << GetName() << "\",dx,dy,dz,alpha,theta,phi);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -604,17 +636,17 @@ void TGeoPara::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) void TGeoPara::SetDimensions(Double_t *param) { - fX = param[0]; - fY = param[1]; - fZ = param[2]; + fX = param[0]; + fY = param[1]; + fZ = param[2]; fAlpha = param[3]; fTheta = param[4]; - fPhi = param[5]; - fTxy = TMath::Tan(param[3]*TMath::DegToRad()); - Double_t tth = TMath::Tan(param[4]*TMath::DegToRad()); - Double_t ph = param[5]*TMath::DegToRad(); - fTxz = tth*TMath::Cos(ph); - fTyz = tth*TMath::Sin(ph); + fPhi = param[5]; + fTxy = TMath::Tan(param[3] * TMath::DegToRad()); + Double_t tth = TMath::Tan(param[4] * TMath::DegToRad()); + Double_t ph = param[5] * TMath::DegToRad(); + fTxz = tth * TMath::Cos(ph); + fTyz = tth * TMath::Sin(ph); } //////////////////////////////////////////////////////////////////////////////// @@ -622,18 +654,35 @@ void TGeoPara::SetDimensions(Double_t *param) void TGeoPara::SetPoints(Double_t *points) const { - if (!points) return; + if (!points) + return; Double_t txy = fTxy; Double_t txz = fTxz; Double_t tyz = fTyz; - *points++ = -fZ*txz-txy*fY-fX; *points++ = -fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz+txy*fY-fX; *points++ = +fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz+txy*fY+fX; *points++ = +fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz-txy*fY+fX; *points++ = -fY-fZ*tyz; *points++ = -fZ; - *points++ = +fZ*txz-txy*fY-fX; *points++ = -fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz+txy*fY-fX; *points++ = +fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz+txy*fY+fX; *points++ = +fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz-txy*fY+fX; *points++ = -fY+fZ*tyz; *points++ = +fZ; + *points++ = -fZ * txz - txy * fY - fX; + *points++ = -fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz + txy * fY - fX; + *points++ = +fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz + txy * fY + fX; + *points++ = +fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz - txy * fY + fX; + *points++ = -fY - fZ * tyz; + *points++ = -fZ; + *points++ = +fZ * txz - txy * fY - fX; + *points++ = -fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz + txy * fY - fX; + *points++ = +fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz + txy * fY + fX; + *points++ = +fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz - txy * fY + fX; + *points++ = -fY + fZ * tyz; + *points++ = +fZ; } //////////////////////////////////////////////////////////////////////////////// @@ -641,18 +690,35 @@ void TGeoPara::SetPoints(Double_t *points) const void TGeoPara::SetPoints(Float_t *points) const { - if (!points) return; + if (!points) + return; Double_t txy = fTxy; Double_t txz = fTxz; Double_t tyz = fTyz; - *points++ = -fZ*txz-txy*fY-fX; *points++ = -fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz+txy*fY-fX; *points++ = +fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz+txy*fY+fX; *points++ = +fY-fZ*tyz; *points++ = -fZ; - *points++ = -fZ*txz-txy*fY+fX; *points++ = -fY-fZ*tyz; *points++ = -fZ; - *points++ = +fZ*txz-txy*fY-fX; *points++ = -fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz+txy*fY-fX; *points++ = +fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz+txy*fY+fX; *points++ = +fY+fZ*tyz; *points++ = +fZ; - *points++ = +fZ*txz-txy*fY+fX; *points++ = -fY+fZ*tyz; *points++ = +fZ; + *points++ = -fZ * txz - txy * fY - fX; + *points++ = -fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz + txy * fY - fX; + *points++ = +fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz + txy * fY + fX; + *points++ = +fY - fZ * tyz; + *points++ = -fZ; + *points++ = -fZ * txz - txy * fY + fX; + *points++ = -fY - fZ * tyz; + *points++ = -fZ; + *points++ = +fZ * txz - txy * fY - fX; + *points++ = -fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz + txy * fY - fX; + *points++ = +fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz + txy * fY + fX; + *points++ = +fY + fZ * tyz; + *points++ = +fZ; + *points++ = +fZ * txz - txy * fY + fX; + *points++ = -fY + fZ * tyz; + *points++ = +fZ; } //////////////////////////////////////////////////////////////////////////////// @@ -670,7 +736,8 @@ void TGeoPara::Sizeof3D() const void TGeoPara::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; ifDz) return kFALSE; - Double_t aa = fA*(point[2]-fB); - if (aa < 0) return kFALSE; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; - if (aa < fA*fA*rsq) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; + Double_t aa = fA * (point[2] - fB); + if (aa < 0) + return kFALSE; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; + if (aa < fA * fA * rsq) + return kFALSE; return kTRUE; } @@ -194,7 +193,7 @@ Bool_t TGeoParaboloid::Contains(const Double_t *point) const Int_t TGeoParaboloid::DistancetoPrimitive(Int_t px, Int_t py) { Int_t n = gGeoManager->GetNsegments(); - const Int_t numPoints=n*(n+1)+2; + const Int_t numPoints = n * (n + 1) + 2; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -204,36 +203,43 @@ Int_t TGeoParaboloid::DistancetoPrimitive(Int_t px, Int_t py) Double_t TGeoParaboloid::DistToParaboloid(const Double_t *point, const Double_t *dir, Bool_t in) const { - Double_t rsq = point[0]*point[0]+point[1]*point[1]; - Double_t a = fA * (dir[0]*dir[0] + dir[1]*dir[1]); - Double_t b = 2.*fA*(point[0]*dir[0]+point[1]*dir[1])-dir[2]; - Double_t c = fA*rsq + fB - point[2]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; + Double_t a = fA * (dir[0] * dir[0] + dir[1] * dir[1]); + Double_t b = 2. * fA * (point[0] * dir[0] + point[1] * dir[1]) - dir[2]; + Double_t c = fA * rsq + fB - point[2]; Double_t dist = TGeoShape::Big(); - if (TMath::Abs(a)0) { - dz = (fDz-point[2])/dir[2]; + if (dir[2] < 0) { + dz = -(point[2] + fDz) / dir[2]; + } else if (dir[2] > 0) { + dz = (fDz - point[2]) / dir[2]; } Double_t dpara = DistToParaboloid(point, dir, kTRUE); return TMath::Min(dz, dpara); @@ -263,34 +272,43 @@ Double_t TGeoParaboloid::DistFromInside(const Double_t *point, const Double_t *d //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the paraboloid and safe distance -Double_t TGeoParaboloid::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoParaboloid::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (iact<3 && safe) { - // compute safe distance + if (iact < 3 && safe) { + // compute safe distance *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } Double_t xnew, ynew, znew; - if (point[2]<=-fDz) { - if (dir[2]<=0) return TGeoShape::Big(); - Double_t snxt = -(fDz+point[2])/dir[2]; + if (point[2] <= -fDz) { + if (dir[2] <= 0) + return TGeoShape::Big(); + Double_t snxt = -(fDz + point[2]) / dir[2]; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; - ynew = point[1]+snxt*dir[1]; - if ((xnew*xnew+ynew*ynew) <= fRlo*fRlo) return snxt; - } else if (point[2]>=fDz) { - if (dir[2]>=0) return TGeoShape::Big(); - Double_t snxt = (fDz-point[2])/dir[2]; + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + if ((xnew * xnew + ynew * ynew) <= fRlo * fRlo) + return snxt; + } else if (point[2] >= fDz) { + if (dir[2] >= 0) + return TGeoShape::Big(); + Double_t snxt = (fDz - point[2]) / dir[2]; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; - ynew = point[1]+snxt*dir[1]; - if ((xnew*xnew+ynew*ynew) <= fRhi*fRhi) return snxt; + xnew = point[0] + snxt * dir[0]; + ynew = point[1] + snxt * dir[1]; + if ((xnew * xnew + ynew * ynew) <= fRhi * fRhi) + return snxt; } Double_t snxt = DistToParaboloid(point, dir, kFALSE); - if (snxt > 1E20) return snxt; - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew) <= fDz) return snxt; + if (snxt > 1E20) + return snxt; + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) <= fDz) + return snxt; return TGeoShape::Big(); } @@ -298,7 +316,7 @@ Double_t TGeoParaboloid::DistFromOutside(const Double_t *point, const Double_t * /// Divide the paraboloid along one axis. TGeoVolume *TGeoParaboloid::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, Int_t /*iaxis*/, Int_t /*ndiv*/, - Double_t /*start*/, Double_t /*step*/) + Double_t /*start*/, Double_t /*step*/) { Error("Divide", "Paraboloid divisions not implemented"); return 0; @@ -310,11 +328,11 @@ TGeoVolume *TGeoParaboloid::Divide(TGeoVolume * /*voldiv*/, const char * /*divna void TGeoParaboloid::GetBoundingCylinder(Double_t *param) const { - param[0] = 0.; // Rmin - param[1] = fDX; // Rmax + param[0] = 0.; // Rmin + param[1] = fDX; // Rmax param[1] *= param[1]; - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -346,15 +364,14 @@ void TGeoParaboloid::InspectShape() const TBuffer3D *TGeoParaboloid::MakeBuffer3D() const { Int_t n = gGeoManager->GetNsegments(); - Int_t nbPnts = n*(n+1)+2; - Int_t nbSegs = n*(2*n+3); - Int_t nbPols = n*(n+2); + Int_t nbPnts = n * (n + 1) + 2; + Int_t nbSegs = n * (2 * n + 3); + Int_t nbPols = n * (n + 2); - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 2*n*5 + n*n*6); + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 2 * n * 5 + n * n * 6); - if (buff) - { + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -372,66 +389,67 @@ void TGeoParaboloid::SetSegsAndPols(TBuffer3D &buff) const Int_t c = GetBasicColor(); - Int_t nn1 = (n+1)*n+1; + Int_t nn1 = (n + 1) * n + 1; indx = 0; // Lower end-cap (n radial segments) - for (j=0; j-1.E-8) return 0.; - Double_t dz = TMath::Abs(point[2]-z0); - safr = -dr*dz/TMath::Sqrt(dr*dr+dz*dz); + if (dr > -1.E-8) + return 0.; + Double_t dz = TMath::Abs(point[2] - z0); + safr = -dr * dz / TMath::Sqrt(dr * dr + dz * dz); } else { - if (dr<1.E-8) return safz; - Double_t talf = -2.*fA*TMath::Sqrt(r0sq); - Double_t salf = talf/TMath::Sqrt(1.+talf*talf); - safr = TMath::Abs(dr*salf); + if (dr < 1.E-8) + return safz; + Double_t talf = -2. * fA * TMath::Sqrt(r0sq); + Double_t salf = talf / TMath::Sqrt(1. + talf * talf); + safr = TMath::Abs(dr * salf); } - if (in) return TMath::Min(safr,safz); - return TMath::Max(safr,safz); + if (in) + return TMath::Min(safr, safz); + return TMath::Max(safr, safz); } //////////////////////////////////////////////////////////////////////////////// @@ -470,17 +493,17 @@ Double_t TGeoParaboloid::Safety(const Double_t *point, Bool_t in) const void TGeoParaboloid::SetParaboloidDimensions(Double_t rlo, Double_t rhi, Double_t dz) { - if ((rlo<0) || (rhi<0) || (dz<=0) || TMath::Abs(rlo-rhi)=0) (rhi>=0) (rlo!=rhi) dz>0",GetName()); + Error("SetParaboloidDimensions", "Dimensions of %s invalid: check (rlo>=0) (rhi>=0) (rlo!=rhi) dz>0", GetName()); return; } fRlo = rlo; fRhi = rhi; - fDz = dz; - Double_t dd = 1./(fRhi*fRhi - fRlo*fRlo); - fA = 2.*fDz*dd; - fB = - fDz * (fRlo*fRlo + fRhi*fRhi)*dd; + fDz = dz; + Double_t dd = 1. / (fRhi * fRhi - fRlo * fRlo); + fA = 2. * fDz * dd; + fB = -fDz * (fRlo * fRlo + fRhi * fRhi) * dd; } //////////////////////////////////////////////////////////////////////////////// @@ -488,9 +511,9 @@ void TGeoParaboloid::SetParaboloidDimensions(Double_t rlo, Double_t rhi, Double_ void TGeoParaboloid::SetDimensions(Double_t *param) { - Double_t rlo = param[0]; - Double_t rhi = param[1]; - Double_t dz = param[2]; + Double_t rlo = param[0]; + Double_t rhi = param[1]; + Double_t dz = param[2]; SetParaboloidDimensions(rlo, rhi, dz); } @@ -515,13 +538,14 @@ void TGeoParaboloid::SetDimensions(Double_t *param) void TGeoParaboloid::SetPoints(Double_t *points) const { - if (!points) return; + if (!points) + return; Double_t ttmin, ttmax; ttmin = TMath::ATan2(-fDz, fRlo); ttmax = TMath::ATan2(fDz, fRhi); Int_t n = gGeoManager->GetNsegments(); - Double_t dtt = (ttmax-ttmin)/n; - Double_t dphi = 360./n; + Double_t dtt = (ttmax - ttmin) / n; + Double_t dphi = 360. / n; Double_t tt; Double_t r, z, delta; Double_t phi, sph, cph; @@ -530,25 +554,25 @@ void TGeoParaboloid::SetPoints(Double_t *points) const points[indx++] = 0; // x points[indx++] = 0; // y points[indx++] = -fDz; - for (Int_t i=0; iGetNsegments(); - nvert = n*(n+1)+2; - nsegs = n*(2*n+3); - npols = n*(n+2); + nvert = n * (n + 1) + 2; + nsegs = n * (2 * n + 3); + npols = n * (n + 2); } //////////////////////////////////////////////////////////////////////////////// @@ -575,7 +599,7 @@ void TGeoParaboloid::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) co Int_t TGeoParaboloid::GetNmeshVertices() const { Int_t n = gGeoManager->GetNsegments(); - return (n*(n+1)+2); + return (n * (n + 1) + 2); } //////////////////////////////////////////////////////////////////////////////// @@ -583,12 +607,14 @@ Int_t TGeoParaboloid::GetNmeshVertices() const void TGeoParaboloid::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rlo = " << fRlo << ";" << std::endl; out << " rhi = " << fRhi << ";" << std::endl; out << " dz = " << fDZ << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoParaboloid(\"" << GetName() << "\", rlo,rhi,dz);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoParaboloid(\"" << GetName() << "\", rlo,rhi,dz);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -597,13 +623,14 @@ void TGeoParaboloid::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= void TGeoParaboloid::SetPoints(Float_t *points) const { - if (!points) return; + if (!points) + return; Double_t ttmin, ttmax; ttmin = TMath::ATan2(-fDz, fRlo); ttmax = TMath::ATan2(fDz, fRhi); Int_t n = gGeoManager->GetNsegments(); - Double_t dtt = (ttmax-ttmin)/n; - Double_t dphi = 360./n; + Double_t dtt = (ttmax - ttmin) / n; + Double_t dphi = 360. / n; Double_t tt; Double_t r, z, delta; Double_t phi, sph, cph; @@ -612,25 +639,25 @@ void TGeoParaboloid::SetPoints(Float_t *points) const points[indx++] = 0; // x points[indx++] = 0; // y points[indx++] = -fDz; - for (Int_t i=0; iGetNsegments(); - Int_t nbPnts = n*(n+1)+2; - Int_t nbSegs = n*(2*n+3); - Int_t nbPols = n*(n+2); - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 2*n*5 + n*n*6)) { + Int_t nbPnts = n * (n + 1) + 2; + Int_t nbSegs = n * (2 * n + 3); + Int_t nbPols = n * (n + 2); + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 2 * n * 5 + n * n * 6)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -681,7 +706,8 @@ const TBuffer3D & TGeoParaboloid::GetBuffer3D(Int_t reqSections, Bool_t localFra void TGeoParaboloid::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iDelete(); delete fPhysical;} - if (fPaths) {fPaths->Delete(); delete fPaths;} + if (fPhysical) { + fPhysical->Delete(); + delete fPhysical; + } + if (fPaths) { + fPaths->Delete(); + delete fPaths; + } delete fVolume; } @@ -64,7 +70,8 @@ TGeoParallelWorld::~TGeoParallelWorld() void TGeoParallelWorld::AddNode(const char *path) { - if (fIsClosed) Fatal("AddNode", "Cannot add nodes to a closed parallel geometry"); + if (fIsClosed) + Fatal("AddNode", "Cannot add nodes to a closed parallel geometry"); if (!fGeoManager->CheckPath(path)) { Error("AddNode", "Path %s not valid.\nCannot add to parallel world!", path); return; @@ -79,7 +86,8 @@ void TGeoParallelWorld::AddNode(const char *path) void TGeoParallelWorld::AddOverlap(TGeoVolume *vol, Bool_t activate) { - if (activate) fUseOverlaps = kTRUE; + if (activate) + fUseOverlaps = kTRUE; vol->SetOverlappingCandidate(kTRUE); } @@ -90,11 +98,13 @@ void TGeoParallelWorld::AddOverlap(TGeoVolume *vol, Bool_t activate) void TGeoParallelWorld::AddOverlap(const char *volname, Bool_t activate) { - if (activate) fUseOverlaps = kTRUE; + if (activate) + fUseOverlaps = kTRUE; TIter next(fGeoManager->GetListOfVolumes()); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) { - if (!strcmp(vol->GetName(), volname)) vol->SetOverlappingCandidate(kTRUE); + while ((vol = (TGeoVolume *)next())) { + if (!strcmp(vol->GetName(), volname)) + vol->SetOverlappingCandidate(kTRUE); } } @@ -106,9 +116,10 @@ Int_t TGeoParallelWorld::PrintDetectedOverlaps() const TIter next(fGeoManager->GetListOfVolumes()); TGeoVolume *vol; Int_t noverlaps = 0; - while ((vol=(TGeoVolume*)next())) { + while ((vol = (TGeoVolume *)next())) { if (vol->IsOverlappingCandidate()) { - if (noverlaps==0) Info("PrintDetectedOverlaps", "List of detected volumes overlapping with the PW"); + if (noverlaps == 0) + Info("PrintDetectedOverlaps", "List of detected volumes overlapping with the PW"); noverlaps++; printf("volume: %s at index: %d\n", vol->GetName(), vol->GetNumber()); } @@ -123,7 +134,8 @@ void TGeoParallelWorld::ResetOverlaps() const { TIter next(fGeoManager->GetListOfVolumes()); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) vol->SetOverlappingCandidate(kFALSE); + while ((vol = (TGeoVolume *)next())) + vol->SetOverlappingCandidate(kFALSE); } //////////////////////////////////////////////////////////////////////////////// @@ -131,8 +143,10 @@ void TGeoParallelWorld::ResetOverlaps() const Bool_t TGeoParallelWorld::CloseGeometry() { - if (fIsClosed) return kTRUE; - if (!fGeoManager->IsClosed()) Fatal("CloseGeometry", "Main geometry must be closed first"); + if (fIsClosed) + return kTRUE; + if (!fGeoManager->IsClosed()) + Fatal("CloseGeometry", "Main geometry must be closed first"); if (!fPaths || !fPaths->GetEntriesFast()) { Error("CloseGeometry", "List of paths is empty"); return kFALSE; @@ -143,10 +157,14 @@ Bool_t TGeoParallelWorld::CloseGeometry() Int_t novlp = 0; TIter next(fGeoManager->GetListOfVolumes()); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) if (vol->IsOverlappingCandidate()) novlp++; + while ((vol = (TGeoVolume *)next())) + if (vol->IsOverlappingCandidate()) + novlp++; Info("CloseGeometry", "Number of declared overlaps: %d", novlp); - if (fUseOverlaps) Info("CloseGeometry", "Parallel world will use declared overlaps"); - else Info("CloseGeometry", "Parallel world will detect overlaps with other volumes"); + if (fUseOverlaps) + Info("CloseGeometry", "Parallel world will use declared overlaps"); + else + Info("CloseGeometry", "Parallel world will detect overlaps with other volumes"); return kTRUE; } @@ -160,13 +178,16 @@ void TGeoParallelWorld::RefreshPhysicalNodes() fVolume = new TGeoVolumeAssembly(GetName()); fGeoManager->GetListOfVolumes()->Remove(fVolume); // Loop physical nodes and add them to the navigation helper volume - if (fPhysical) {fPhysical->Delete(); delete fPhysical;} + if (fPhysical) { + fPhysical->Delete(); + delete fPhysical; + } fPhysical = new TObjArray(fPaths->GetEntriesFast()); TGeoPhysicalNode *pnode; TObjString *objs; TIter next(fPaths); Int_t copy = 0; - while ((objs = (TObjString*)next())) { + while ((objs = (TObjString *)next())) { pnode = new TGeoPhysicalNode(objs->GetName()); fPhysical->AddAt(pnode, copy); fVolume->AddNode(pnode->GetVolume(), copy++, new TGeoHMatrix(*pnode->GetMatrix())); @@ -181,7 +202,8 @@ void TGeoParallelWorld::RefreshPhysicalNodes() TGeoPhysicalNode *TGeoParallelWorld::FindNode(Double_t point[3]) { - if (!fIsClosed) Fatal("FindNode", "Parallel geometry must be closed first"); + if (!fIsClosed) + Fatal("FindNode", "Parallel geometry must be closed first"); TGeoNavigator *nav = fGeoManager->GetCurrentNavigator(); // Fast return if not in an overlapping candidate TGeoVoxelFinder *voxels = fVolume->GetVoxels(); @@ -192,17 +214,18 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNode(Double_t point[3]) TGeoNodeCache *cache = nav->GetCache(); TGeoStateInfo &info = *cache->GetMakePWInfo(nd); Int_t *check_list = voxels->GetCheckList(point, ncheck, info); -// cache->ReleaseInfo(); // no hierarchical use - if (!check_list) return 0; + // cache->ReleaseInfo(); // no hierarchical use + if (!check_list) + return 0; // loop all nodes in voxel TGeoNode *node; Double_t local[3]; - for (id=0; idGetNode(check_list[id]); node->MasterToLocal(point, local); if (node->GetVolume()->Contains(local)) { // We found a node containing the point - fLastState = (TGeoPhysicalNode*)fPhysical->At(node->GetNumber()); + fLastState = (TGeoPhysicalNode *)fPhysical->At(node->GetNumber()); return fLastState; } } @@ -213,21 +236,24 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNode(Double_t point[3]) /// Same functionality as TGeoNavigator::FindNextDaughterBoundary for the /// parallel world -TGeoPhysicalNode *TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_t dir[3], - Double_t &step, Double_t stepmax) +TGeoPhysicalNode * +TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_t dir[3], Double_t &step, Double_t stepmax) { - if (!fIsClosed) Fatal("FindNextBoundary", "Parallel geometry must be closed first"); + if (!fIsClosed) + Fatal("FindNextBoundary", "Parallel geometry must be closed first"); TGeoPhysicalNode *pnode = 0; TGeoNavigator *nav = fGeoManager->GetCurrentNavigator(); // Fast return if not in an overlapping candidate - if (fUseOverlaps && !nav->GetCurrentVolume()->IsOverlappingCandidate()) return 0; -// TIter next(fPhysical); + if (fUseOverlaps && !nav->GetCurrentVolume()->IsOverlappingCandidate()) + return 0; + // TIter next(fPhysical); // Ignore the request if the current state in the main geometry matches the // last touched physical node in the parallel geometry - if (fLastState && fLastState->IsMatchingState(nav)) return 0; -// while ((pnode = (TGeoPhysicalNode*)next())) { -// if (pnode->IsMatchingState(nav)) return 0; -// } + if (fLastState && fLastState->IsMatchingState(nav)) + return 0; + // while ((pnode = (TGeoPhysicalNode*)next())) { + // if (pnode->IsMatchingState(nav)) return 0; + // } step = stepmax; TGeoVoxelFinder *voxels = fVolume->GetVoxels(); Int_t idaughter = -1; // nothing crossed @@ -235,13 +261,14 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_ Int_t i; TGeoNode *current; Double_t lpoint[3], ldir[3]; -// const Double_t tolerance = TGeoShape::Tolerance(); - if (nd<5) { - // loop over daughters - for (i=0; iGetNode(i); // validate only within stepmax - if (voxels->IsSafeVoxel(point, i, stepmax)) continue; + if (voxels->IsSafeVoxel(point, i, stepmax)) + continue; current->MasterToLocal(point, lpoint); current->MasterToLocalVect(dir, ldir); Double_t snext = current->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, step); @@ -250,8 +277,8 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_ idaughter = i; } } - if (idaughter>=0) { - pnode = (TGeoPhysicalNode*)fPhysical->At(idaughter); + if (idaughter >= 0) { + pnode = (TGeoPhysicalNode *)fPhysical->At(idaughter); return pnode; } step = TGeoShape::Big(); @@ -263,12 +290,12 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_ Int_t *vlist = 0; TGeoNodeCache *cache = nav->GetCache(); TGeoStateInfo &info = *cache->GetMakePWInfo(nd); -// TGeoStateInfo &info = *cache->GetInfo(); -// cache->ReleaseInfo(); // no hierarchical use + // TGeoStateInfo &info = *cache->GetInfo(); + // cache->ReleaseInfo(); // no hierarchical use voxels->SortCrossedVoxels(point, dir, info); - while ((sumcheckedGetNextVoxel(point, dir, ncheck, info))) { - for (i=0; iAt(vlist[i]); + while ((sumchecked < nd) && (vlist = voxels->GetNextVoxel(point, dir, ncheck, info))) { + for (i = 0; i < ncheck; i++) { + pnode = (TGeoPhysicalNode *)fPhysical->At(vlist[i]); if (pnode->IsMatchingState(nav)) { step = TGeoShape::Big(); return 0; @@ -282,12 +309,12 @@ TGeoPhysicalNode *TGeoParallelWorld::FindNextBoundary(Double_t point[3], Double_ idaughter = vlist[i]; } } - if (idaughter>=0) { - pnode = (TGeoPhysicalNode*)fPhysical->At(idaughter); + if (idaughter >= 0) { + pnode = (TGeoPhysicalNode *)fPhysical->At(idaughter); // mark the overlap if (!fUseOverlaps && !nav->GetCurrentVolume()->IsOverlappingCandidate()) { - AddOverlap(nav->GetCurrentVolume(),kFALSE); -// printf("object %s overlapping with pn: %s\n", fGeoManager->GetPath(), pnode->GetName()); + AddOverlap(nav->GetCurrentVolume(), kFALSE); + // printf("object %s overlapping with pn: %s\n", fGeoManager->GetPath(), pnode->GetName()); } return pnode; } @@ -303,9 +330,11 @@ Double_t TGeoParallelWorld::Safety(Double_t point[3], Double_t safmax) { TGeoNavigator *nav = fGeoManager->GetCurrentNavigator(); // Fast return if the state matches the last one recorded - if (fLastState && fLastState->IsMatchingState(nav)) return TGeoShape::Big(); + if (fLastState && fLastState->IsMatchingState(nav)) + return TGeoShape::Big(); // Fast return if not in an overlapping candidate - if (fUseOverlaps && !nav->GetCurrentVolume()->IsOverlappingCandidate()) return TGeoShape::Big(); + if (fUseOverlaps && !nav->GetCurrentVolume()->IsOverlappingCandidate()) + return TGeoShape::Big(); Double_t local[3]; Double_t safe = safmax; Double_t safnext; @@ -316,28 +345,38 @@ Double_t TGeoParallelWorld::Safety(Double_t point[3], Double_t safmax) TGeoVoxelFinder *voxels = fVolume->GetVoxels(); //---> check fast unsafe voxels Double_t *boxes = voxels->GetBoxes(); - for (Int_t id=0; id safe) continue; - Double_t dxyz1 = TMath::Abs(point[1]-boxes[ist+4])-boxes[ist+1]; - if (dxyz1 > safe) continue; - Double_t dxyz2 = TMath::Abs(point[2]-boxes[ist+5])-boxes[ist+2]; - if (dxyz2 > safe) continue; - if (dxyz0>0) dxyz+=dxyz0*dxyz0; - if (dxyz1>0) dxyz+=dxyz1*dxyz1; - if (dxyz2>0) dxyz+=dxyz2*dxyz2; - if (dxyz >= safe*safe) continue; - pnode = (TGeoPhysicalNode*)fPhysical->At(id); + Double_t dxyz0 = TMath::Abs(point[0] - boxes[ist + 3]) - boxes[ist]; + if (dxyz0 > safe) + continue; + Double_t dxyz1 = TMath::Abs(point[1] - boxes[ist + 4]) - boxes[ist + 1]; + if (dxyz1 > safe) + continue; + Double_t dxyz2 = TMath::Abs(point[2] - boxes[ist + 5]) - boxes[ist + 2]; + if (dxyz2 > safe) + continue; + if (dxyz0 > 0) + dxyz += dxyz0 * dxyz0; + if (dxyz1 > 0) + dxyz += dxyz1 * dxyz1; + if (dxyz2 > 0) + dxyz += dxyz2 * dxyz2; + if (dxyz >= safe * safe) + continue; + pnode = (TGeoPhysicalNode *)fPhysical->At(id); // Return if inside the current node - if (pnode->IsMatchingState(nav)) return TGeoShape::Big(); + if (pnode->IsMatchingState(nav)) + return TGeoShape::Big(); current = fVolume->GetNode(id); current->MasterToLocal(point, local); // Safety to current node safnext = current->Safety(local, kFALSE); - if (safnext < tolerance) return 0.; - if (safnext < safe) safe = safnext; + if (safnext < tolerance) + return 0.; + if (safnext < safe) + safe = safnext; } return safe; } @@ -357,4 +396,3 @@ void TGeoParallelWorld::Draw(Option_t *option) { fVolume->Draw(option); } - diff --git a/geom/geom/src/TGeoPatternFinder.cxx b/geom/geom/src/TGeoPatternFinder.cxx index c7002086f90ac..63fd7430c2ae4 100644 --- a/geom/geom/src/TGeoPatternFinder.cxx +++ b/geom/geom/src/TGeoPatternFinder.cxx @@ -51,26 +51,22 @@ ClassImp(TGeoPatternSphTheta); ClassImp(TGeoPatternSphPhi); ClassImp(TGeoPatternHoneycomb); - //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoPatternFinder::ThreadData_t::ThreadData_t() : - fMatrix(0), fCurrent(-1), fNextIndex(-1) -{ -} +TGeoPatternFinder::ThreadData_t::ThreadData_t() : fMatrix(0), fCurrent(-1), fNextIndex(-1) {} //////////////////////////////////////////////////////////////////////////////// /// Destructor. TGeoPatternFinder::ThreadData_t::~ThreadData_t() { -// if (fMatrix != gGeoIdentity) delete fMatrix; + // if (fMatrix != gGeoIdentity) delete fMatrix; } //////////////////////////////////////////////////////////////////////////////// -TGeoPatternFinder::ThreadData_t& TGeoPatternFinder::GetThreadData() const +TGeoPatternFinder::ThreadData_t &TGeoPatternFinder::GetThreadData() const { Int_t tid = TGeoManager::ThreadId(); return *fThreadData[tid]; @@ -81,9 +77,8 @@ TGeoPatternFinder::ThreadData_t& TGeoPatternFinder::GetThreadData() const void TGeoPatternFinder::ClearThreadData() const { std::lock_guard guard(fMutex); - std::vector::iterator i = fThreadData.begin(); - while (i != fThreadData.end()) - { + std::vector::iterator i = fThreadData.begin(); + while (i != fThreadData.end()) { delete *i; ++i; } @@ -99,7 +94,7 @@ void TGeoPatternFinder::CreateThreadData(Int_t nthreads) std::lock_guard guard(fMutex); fThreadData.resize(nthreads); fThreadSize = nthreads; - for (Int_t tid=0; tidfMatrix = CreateMatrix(); @@ -113,11 +108,11 @@ void TGeoPatternFinder::CreateThreadData(Int_t nthreads) TGeoPatternFinder::TGeoPatternFinder() { fNdivisions = 0; - fDivIndex = 0; - fStep = 0; - fStart = 0; - fEnd = 0; - fVolume = 0; + fDivIndex = 0; + fStep = 0; + fStart = 0; + fEnd = 0; + fVolume = 0; fThreadSize = 0; } @@ -126,42 +121,42 @@ TGeoPatternFinder::TGeoPatternFinder() TGeoPatternFinder::TGeoPatternFinder(TGeoVolume *vol, Int_t ndiv) { - fVolume = vol; + fVolume = vol; fNdivisions = ndiv; - fDivIndex = 0; - fStep = 0; - fStart = 0; - fEnd = 0; + fDivIndex = 0; + fStep = 0; + fStart = 0; + fEnd = 0; fThreadSize = 0; } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternFinder::TGeoPatternFinder(const TGeoPatternFinder& pf) : - TObject(pf), - fStep(pf.fStep), - fStart(pf.fStart), - fEnd(pf.fEnd), - fNdivisions(pf.fNdivisions), - fDivIndex(pf.fDivIndex), - fVolume(pf.fVolume) +TGeoPatternFinder::TGeoPatternFinder(const TGeoPatternFinder &pf) + : TObject(pf), + fStep(pf.fStep), + fStart(pf.fStart), + fEnd(pf.fEnd), + fNdivisions(pf.fNdivisions), + fDivIndex(pf.fDivIndex), + fVolume(pf.fVolume) { } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternFinder& TGeoPatternFinder::operator=(const TGeoPatternFinder& pf) +TGeoPatternFinder &TGeoPatternFinder::operator=(const TGeoPatternFinder &pf) { - if(this!=&pf) { + if (this != &pf) { TObject::operator=(pf); - fStep=pf.fStep; - fStart=pf.fStart; - fEnd=pf.fEnd; - fNdivisions=pf.fNdivisions; - fDivIndex=pf.fDivIndex; - fVolume=pf.fVolume; + fStep = pf.fStep; + fStart = pf.fStart; + fEnd = pf.fEnd; + fNdivisions = pf.fNdivisions; + fDivIndex = pf.fDivIndex; + fVolume = pf.fVolume; } return *this; } @@ -185,7 +180,7 @@ Int_t TGeoPatternFinder::GetCurrent() //////////////////////////////////////////////////////////////////////////////// /// Return current matrix. -TGeoMatrix* TGeoPatternFinder::GetMatrix() +TGeoMatrix *TGeoPatternFinder::GetMatrix() { return GetThreadData().fMatrix; } @@ -211,8 +206,9 @@ void TGeoPatternFinder::SetNext(Int_t index) TGeoNode *TGeoPatternFinder::CdNext() { - ThreadData_t& td = GetThreadData(); - if (td.fNextIndex < 0) return NULL; + ThreadData_t &td = GetThreadData(); + if (td.fNextIndex < 0) + return NULL; cd(td.fNextIndex); return GetNodeOffset(td.fCurrent); } @@ -223,7 +219,7 @@ TGeoNode *TGeoPatternFinder::CdNext() void TGeoPatternFinder::SetRange(Double_t start, Double_t step, Int_t ndivisions) { fStart = start; - fEnd = fStart + ndivisions*step; + fEnd = fStart + ndivisions * step; fStep = step; fNdivisions = ndivisions; } @@ -243,26 +239,24 @@ TGeoPatternX::TGeoPatternX() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - Double_t dx = ((TGeoBBox*)vol->GetShape())->GetDX(); + Double_t dx = ((TGeoBBox *)vol->GetShape())->GetDX(); fStart = -dx; fEnd = dx; - fStep = 2*dx/ndivisions; + fStep = 2 * dx / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t step) : TGeoPatternFinder(vol, ndivisions) { - Double_t dx = ((TGeoBBox*)vol->GetShape())->GetDX(); + Double_t dx = ((TGeoBBox *)vol->GetShape())->GetDX(); fStart = -dx; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } @@ -270,29 +264,28 @@ TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t step) /// constructor TGeoPatternX::TGeoPatternX(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternX::TGeoPatternX(const TGeoPatternX& pf) : - TGeoPatternFinder(pf) +TGeoPatternX::TGeoPatternX(const TGeoPatternX &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternX& TGeoPatternX::operator=(const TGeoPatternX& pf) +TGeoPatternX &TGeoPatternX::operator=(const TGeoPatternX &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -302,27 +295,25 @@ TGeoPatternX& TGeoPatternX::operator=(const TGeoPatternX& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternX::~TGeoPatternX() -{ -} +TGeoPatternX::~TGeoPatternX() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternX::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; - td.fMatrix->SetDx(fStart+idiv*fStep+0.5*fStep); + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; + td.fMatrix->SetDx(fStart + idiv * fStep + 0.5 * fStep); } //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternX::CreateMatrix() const +TGeoMatrix *TGeoPatternX::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -340,7 +331,7 @@ TGeoMatrix* TGeoPatternX::CreateMatrix() const void TGeoPatternX::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - matrix.SetDx(fStart+idiv*fStep+0.5*fStep); + matrix.SetDx(fStart + idiv * fStep + 0.5 * fStep); } //////////////////////////////////////////////////////////////////////////////// @@ -348,10 +339,12 @@ void TGeoPatternX::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const Bool_t TGeoPatternX::IsOnBoundary(const Double_t *point) const { - Double_t seg = (point[0]-fStart)/fStep; + Double_t seg = (point[0] - fStart) / fStep; Double_t diff = seg - Long64_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -360,16 +353,20 @@ Bool_t TGeoPatternX::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternX::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Int_t ind = (Int_t)(1.+(point[0]-fStart)/fStep) - 1; + Int_t ind = (Int_t)(1. + (point[0] - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - if (dir[0]>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dir[0] > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -381,19 +378,22 @@ TGeoNode *TGeoPatternX::FindNode(Double_t *point, const Double_t *dir) Double_t TGeoPatternX::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); indnext = -1; Double_t dist = TGeoShape::Big(); - if (TMath::Abs(dir[0])0)?1:0; - dist = (fStep*(td.fCurrent+inc)-point[0])/dir[0]; - if (dist<0.) Error("FindNextBoundary", "Negative distance d=%g",dist); - if (!inc) inc = -1; - indnext = td.fCurrent+inc; + Int_t inc = (dir[0] > 0) ? 1 : 0; + dist = (fStep * (td.fCurrent + inc) - point[0]) / dir[0]; + if (dist < 0.) + Error("FindNextBoundary", "Negative distance d=%g", dist); + if (!inc) + inc = -1; + indnext = td.fCurrent + inc; return dist; } @@ -403,7 +403,8 @@ Double_t TGeoPatternX::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &i TGeoPatternFinder *TGeoPatternX::MakeCopy(Bool_t reflect) { TGeoPatternX *finder = new TGeoPatternX(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -421,7 +422,6 @@ void TGeoPatternX::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= "" // TGeoPatternY - a Y axis divison pattern //______________________________________________________________________________ - //////////////////////////////////////////////////////////////////////////////// /// Default constructor @@ -433,26 +433,24 @@ TGeoPatternY::TGeoPatternY() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - Double_t dy = ((TGeoBBox*)vol->GetShape())->GetDY(); + Double_t dy = ((TGeoBBox *)vol->GetShape())->GetDY(); fStart = -dy; fEnd = dy; - fStep = 2*dy/ndivisions; + fStep = 2 * dy / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t step) : TGeoPatternFinder(vol, ndivisions) { - Double_t dy = ((TGeoBBox*)vol->GetShape())->GetDY(); + Double_t dy = ((TGeoBBox *)vol->GetShape())->GetDY(); fStart = -dy; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } @@ -460,29 +458,28 @@ TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t step) /// constructor TGeoPatternY::TGeoPatternY(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternY::TGeoPatternY(const TGeoPatternY& pf) : - TGeoPatternFinder(pf) +TGeoPatternY::TGeoPatternY(const TGeoPatternY &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternY& TGeoPatternY::operator=(const TGeoPatternY& pf) +TGeoPatternY &TGeoPatternY::operator=(const TGeoPatternY &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -492,27 +489,25 @@ TGeoPatternY& TGeoPatternY::operator=(const TGeoPatternY& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternY::~TGeoPatternY() -{ -} +TGeoPatternY::~TGeoPatternY() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternY::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; - td.fMatrix->SetDy(fStart+idiv*fStep+0.5*fStep); + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; + td.fMatrix->SetDy(fStart + idiv * fStep + 0.5 * fStep); } //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternY::CreateMatrix() const +TGeoMatrix *TGeoPatternY::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -530,7 +525,7 @@ TGeoMatrix* TGeoPatternY::CreateMatrix() const void TGeoPatternY::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - matrix.SetDy(fStart+idiv*fStep+0.5*fStep); + matrix.SetDy(fStart + idiv * fStep + 0.5 * fStep); } //////////////////////////////////////////////////////////////////////////////// @@ -538,10 +533,12 @@ void TGeoPatternY::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const Bool_t TGeoPatternY::IsOnBoundary(const Double_t *point) const { - Double_t seg = (point[1]-fStart)/fStep; + Double_t seg = (point[1] - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -550,16 +547,20 @@ Bool_t TGeoPatternY::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternY::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Int_t ind = (Int_t)(1.+(point[1]-fStart)/fStep) - 1; + Int_t ind = (Int_t)(1. + (point[1] - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - if (dir[1]>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dir[1] > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -571,19 +572,22 @@ TGeoNode *TGeoPatternY::FindNode(Double_t *point, const Double_t *dir) Double_t TGeoPatternY::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); indnext = -1; Double_t dist = TGeoShape::Big(); - if (TMath::Abs(dir[1])0)?1:0; - dist = (fStep*(td.fCurrent+inc)-point[1])/dir[1]; - if (dist<0.) Error("FindNextBoundary", "Negative distance d=%g",dist); - if (!inc) inc = -1; - indnext = td.fCurrent+inc; + Int_t inc = (dir[1] > 0) ? 1 : 0; + dist = (fStep * (td.fCurrent + inc) - point[1]) / dir[1]; + if (dist < 0.) + Error("FindNextBoundary", "Negative distance d=%g", dist); + if (!inc) + inc = -1; + indnext = td.fCurrent + inc; return dist; } @@ -593,7 +597,8 @@ Double_t TGeoPatternY::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &i TGeoPatternFinder *TGeoPatternY::MakeCopy(Bool_t reflect) { TGeoPatternY *finder = new TGeoPatternY(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -611,7 +616,6 @@ void TGeoPatternY::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= "" // TGeoPatternZ - a Z axis divison pattern //______________________________________________________________________________ - //////////////////////////////////////////////////////////////////////////////// /// Default constructor @@ -622,54 +626,51 @@ TGeoPatternZ::TGeoPatternZ() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternZ::TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternZ::TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - Double_t dz = ((TGeoBBox*)vol->GetShape())->GetDZ(); + Double_t dz = ((TGeoBBox *)vol->GetShape())->GetDZ(); fStart = -dz; fEnd = dz; - fStep = 2*dz/ndivisions; + fStep = 2 * dz / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternZ::TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternZ::TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions, Double_t step) : TGeoPatternFinder(vol, ndivisions) { - Double_t dz = ((TGeoBBox*)vol->GetShape())->GetDZ(); + Double_t dz = ((TGeoBBox *)vol->GetShape())->GetDZ(); fStart = -dz; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternZ::TGeoPatternZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternZ::TGeoPatternZ(const TGeoPatternZ& pf) : - TGeoPatternFinder(pf) +TGeoPatternZ::TGeoPatternZ(const TGeoPatternZ &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternZ& TGeoPatternZ::operator=(const TGeoPatternZ& pf) +TGeoPatternZ &TGeoPatternZ::operator=(const TGeoPatternZ &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -679,26 +680,24 @@ TGeoPatternZ& TGeoPatternZ::operator=(const TGeoPatternZ& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternZ::~TGeoPatternZ() -{ -} +TGeoPatternZ::~TGeoPatternZ() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternZ::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; - td.fMatrix->SetDz(((IsReflected())?-1.:1.)*(fStart+idiv*fStep+0.5*fStep)); + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; + td.fMatrix->SetDz(((IsReflected()) ? -1. : 1.) * (fStart + idiv * fStep + 0.5 * fStep)); } //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternZ::CreateMatrix() const +TGeoMatrix *TGeoPatternZ::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -716,7 +715,7 @@ TGeoMatrix* TGeoPatternZ::CreateMatrix() const void TGeoPatternZ::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - matrix.SetDz(((IsReflected())?-1.:1.)*(fStart+idiv*fStep+0.5*fStep)); + matrix.SetDz(((IsReflected()) ? -1. : 1.) * (fStart + idiv * fStep + 0.5 * fStep)); } //////////////////////////////////////////////////////////////////////////////// @@ -724,10 +723,12 @@ void TGeoPatternZ::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const Bool_t TGeoPatternZ::IsOnBoundary(const Double_t *point) const { - Double_t seg = (point[2]-fStart)/fStep; + Double_t seg = (point[2] - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -736,16 +737,20 @@ Bool_t TGeoPatternZ::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternZ::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Int_t ind = (Int_t)(1.+(point[2]-fStart)/fStep) - 1; + Int_t ind = (Int_t)(1. + (point[2] - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - if (dir[2]>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dir[2] > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -758,18 +763,21 @@ TGeoNode *TGeoPatternZ::FindNode(Double_t *point, const Double_t *dir) Double_t TGeoPatternZ::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &indnext) { indnext = -1; - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); Double_t dist = TGeoShape::Big(); - if (TMath::Abs(dir[2])0)?1:0; - dist = (fStep*(td.fCurrent+inc)-point[2])/dir[2]; - if (dist<0.) Error("FindNextBoundary", "Negative distance d=%g",dist); - if (!inc) inc = -1; - indnext = td.fCurrent+inc; + Int_t inc = (dir[2] > 0) ? 1 : 0; + dist = (fStep * (td.fCurrent + inc) - point[2]) / dir[2]; + if (dist < 0.) + Error("FindNextBoundary", "Negative distance d=%g", dist); + if (!inc) + inc = -1; + indnext = td.fCurrent + inc; return dist; } @@ -779,7 +787,8 @@ Double_t TGeoPatternZ::FindNextBoundary(Double_t *point, Double_t *dir, Int_t &i TGeoPatternFinder *TGeoPatternZ::MakeCopy(Bool_t reflect) { TGeoPatternZ *finder = new TGeoPatternZ(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -807,54 +816,52 @@ TGeoPatternParaX::TGeoPatternParaX() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternParaX::TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternParaX::TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - Double_t dx = ((TGeoPara*)vol->GetShape())->GetX(); + Double_t dx = ((TGeoPara *)vol->GetShape())->GetX(); fStart = -dx; fEnd = dx; - fStep = 2*dx/ndivisions; + fStep = 2 * dx / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternParaX::TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - Double_t dx = ((TGeoPara*)vol->GetShape())->GetX(); + Double_t dx = ((TGeoPara *)vol->GetShape())->GetX(); fStart = -dx; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternParaX::TGeoPatternParaX(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternParaX::TGeoPatternParaX(const TGeoPatternParaX& pf) : - TGeoPatternFinder(pf) +TGeoPatternParaX::TGeoPatternParaX(const TGeoPatternParaX &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternParaX& TGeoPatternParaX::operator=(const TGeoPatternParaX& pf) +TGeoPatternParaX &TGeoPatternParaX::operator=(const TGeoPatternParaX &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -864,17 +871,15 @@ TGeoPatternParaX& TGeoPatternParaX::operator=(const TGeoPatternParaX& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternParaX::~TGeoPatternParaX() -{ -} +TGeoPatternParaX::~TGeoPatternParaX() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternParaX::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; - td.fMatrix->SetDx(fStart+idiv*fStep+0.5*fStep); + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; + td.fMatrix->SetDx(fStart + idiv * fStep + 0.5 * fStep); } //////////////////////////////////////////////////////////////////////////////// @@ -882,14 +887,16 @@ void TGeoPatternParaX::cd(Int_t idiv) Bool_t TGeoPatternParaX::IsOnBoundary(const Double_t *point) const { - Double_t txy = ((TGeoPara*)fVolume->GetShape())->GetTxy(); - Double_t txz = ((TGeoPara*)fVolume->GetShape())->GetTxz(); - Double_t tyz = ((TGeoPara*)fVolume->GetShape())->GetTyz(); - Double_t xt = point[0]-txz*point[2]-txy*(point[1]-tyz*point[2]); - Double_t seg = (xt-fStart)/fStep; + Double_t txy = ((TGeoPara *)fVolume->GetShape())->GetTxy(); + Double_t txz = ((TGeoPara *)fVolume->GetShape())->GetTxz(); + Double_t tyz = ((TGeoPara *)fVolume->GetShape())->GetTyz(); + Double_t xt = point[0] - txz * point[2] - txy * (point[1] - tyz * point[2]); + Double_t seg = (xt - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -898,25 +905,29 @@ Bool_t TGeoPatternParaX::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternParaX::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Double_t txy = ((TGeoPara*)fVolume->GetShape())->GetTxy(); - Double_t txz = ((TGeoPara*)fVolume->GetShape())->GetTxz(); - Double_t tyz = ((TGeoPara*)fVolume->GetShape())->GetTyz(); - Double_t xt = point[0]-txz*point[2]-txy*(point[1]-tyz*point[2]); - Int_t ind = (Int_t)(1.+(xt-fStart)/fStep)-1; + Double_t txy = ((TGeoPara *)fVolume->GetShape())->GetTxy(); + Double_t txz = ((TGeoPara *)fVolume->GetShape())->GetTxz(); + Double_t tyz = ((TGeoPara *)fVolume->GetShape())->GetTyz(); + Double_t xt = point[0] - txz * point[2] - txy * (point[1] - tyz * point[2]); + Int_t ind = (Int_t)(1. + (xt - fStart) / fStep) - 1; if (dir) { - Double_t ttsq = txy*txy + (txz-txy*tyz)*(txz-txy*tyz); - Double_t divdirx = 1./TMath::Sqrt(1.+ttsq); - Double_t divdiry = -txy*divdirx; - Double_t divdirz = -(txz-txy*tyz)*divdirx; - Double_t dot = dir[0]*divdirx + dir[1]*divdiry + dir[2]*divdirz; + Double_t ttsq = txy * txy + (txz - txy * tyz) * (txz - txy * tyz); + Double_t divdirx = 1. / TMath::Sqrt(1. + ttsq); + Double_t divdiry = -txy * divdirx; + Double_t divdirz = -(txz - txy * tyz) * divdirx; + Double_t dot = dir[0] * divdirx + dir[1] * divdiry + dir[2] * divdirz; td.fNextIndex = ind; - if (dot>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dot > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -928,7 +939,8 @@ TGeoNode *TGeoPatternParaX::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternParaX::MakeCopy(Bool_t reflect) { TGeoPatternParaX *finder = new TGeoPatternParaX(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -945,10 +957,10 @@ void TGeoPatternParaX::SavePrimitive(std::ostream &out, Option_t * /*option*/ /* //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternParaX::CreateMatrix() const +TGeoMatrix *TGeoPatternParaX::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -966,7 +978,7 @@ TGeoMatrix* TGeoPatternParaX::CreateMatrix() const void TGeoPatternParaX::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - matrix.SetDx(fStart+idiv*fStep+0.5*fStep); + matrix.SetDx(fStart + idiv * fStep + 0.5 * fStep); } //______________________________________________________________________________ @@ -984,56 +996,54 @@ TGeoPatternParaY::TGeoPatternParaY() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternParaY::TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternParaY::TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - fTxy = ((TGeoPara*)vol->GetShape())->GetTxy(); - Double_t dy = ((TGeoPara*)vol->GetShape())->GetY(); + fTxy = ((TGeoPara *)vol->GetShape())->GetTxy(); + Double_t dy = ((TGeoPara *)vol->GetShape())->GetY(); fStart = -dy; fEnd = dy; - fStep = 2*dy/ndivisions; + fStep = 2 * dy / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternParaY::TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fTxy = ((TGeoPara*)vol->GetShape())->GetTxy(); - Double_t dy = ((TGeoPara*)vol->GetShape())->GetY(); + fTxy = ((TGeoPara *)vol->GetShape())->GetTxy(); + Double_t dy = ((TGeoPara *)vol->GetShape())->GetY(); fStart = -dy; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternParaY::TGeoPatternParaY(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fTxy = ((TGeoPara*)vol->GetShape())->GetTxy(); - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fTxy = ((TGeoPara *)vol->GetShape())->GetTxy(); + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternParaY::TGeoPatternParaY(const TGeoPatternParaY& pf) : - TGeoPatternFinder(pf) +TGeoPatternParaY::TGeoPatternParaY(const TGeoPatternParaY &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternParaY& TGeoPatternParaY::operator=(const TGeoPatternParaY& pf) +TGeoPatternParaY &TGeoPatternParaY::operator=(const TGeoPatternParaY &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -1043,18 +1053,16 @@ TGeoPatternParaY& TGeoPatternParaY::operator=(const TGeoPatternParaY& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternParaY::~TGeoPatternParaY() -{ -} +TGeoPatternParaY::~TGeoPatternParaY() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternParaY::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); td.fCurrent = idiv; - Double_t dy = fStart+idiv*fStep+0.5*fStep; - td.fMatrix->SetDx(fTxy*dy); + Double_t dy = fStart + idiv * fStep + 0.5 * fStep; + td.fMatrix->SetDx(fTxy * dy); td.fMatrix->SetDy(dy); } @@ -1063,12 +1071,14 @@ void TGeoPatternParaY::cd(Int_t idiv) Bool_t TGeoPatternParaY::IsOnBoundary(const Double_t *point) const { - Double_t tyz = ((TGeoPara*)fVolume->GetShape())->GetTyz(); - Double_t yt = point[1]-tyz*point[2]; - Double_t seg = (yt-fStart)/fStep; + Double_t tyz = ((TGeoPara *)fVolume->GetShape())->GetTyz(); + Double_t yt = point[1] - tyz * point[2]; + Double_t seg = (yt - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -1077,21 +1087,25 @@ Bool_t TGeoPatternParaY::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternParaY::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Double_t tyz = ((TGeoPara*)fVolume->GetShape())->GetTyz(); - Double_t yt = point[1]-tyz*point[2]; - Int_t ind = (Int_t)(1.+(yt-fStart)/fStep) - 1; + Double_t tyz = ((TGeoPara *)fVolume->GetShape())->GetTyz(); + Double_t yt = point[1] - tyz * point[2]; + Int_t ind = (Int_t)(1. + (yt - fStart) / fStep) - 1; if (dir) { - Double_t divdiry = 1./TMath::Sqrt(1.+tyz*tyz); - Double_t divdirz = -tyz*divdiry; - Double_t dot = dir[1]*divdiry + dir[2]*divdirz; + Double_t divdiry = 1. / TMath::Sqrt(1. + tyz * tyz); + Double_t divdirz = -tyz * divdiry; + Double_t dot = dir[1] * divdiry + dir[2] * divdirz; td.fNextIndex = ind; - if (dot>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dot > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -1103,7 +1117,8 @@ TGeoNode *TGeoPatternParaY::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternParaY::MakeCopy(Bool_t reflect) { TGeoPatternParaY *finder = new TGeoPatternParaY(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -1120,10 +1135,10 @@ void TGeoPatternParaY::SavePrimitive(std::ostream &out, Option_t * /*option*/ /* //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternParaY::CreateMatrix() const +TGeoMatrix *TGeoPatternParaY::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -1141,8 +1156,8 @@ TGeoMatrix* TGeoPatternParaY::CreateMatrix() const void TGeoPatternParaY::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - Double_t dy = fStart+idiv*fStep+0.5*fStep; - matrix.SetDx(fTxy*dy); + Double_t dy = fStart + idiv * fStep + 0.5 * fStep; + matrix.SetDx(fTxy * dy); matrix.SetDy(dy); } @@ -1162,29 +1177,28 @@ TGeoPatternParaZ::TGeoPatternParaZ() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternParaZ::TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternParaZ::TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - fTxz = ((TGeoPara*)vol->GetShape())->GetTxz(); - fTyz = ((TGeoPara*)vol->GetShape())->GetTyz(); - Double_t dz = ((TGeoPara*)vol->GetShape())->GetZ(); + fTxz = ((TGeoPara *)vol->GetShape())->GetTxz(); + fTyz = ((TGeoPara *)vol->GetShape())->GetTyz(); + Double_t dz = ((TGeoPara *)vol->GetShape())->GetZ(); fStart = -dz; fEnd = dz; - fStep = 2*dz/ndivisions; + fStep = 2 * dz / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternParaZ::TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fTxz = ((TGeoPara*)vol->GetShape())->GetTxz(); - fTyz = ((TGeoPara*)vol->GetShape())->GetTyz(); - Double_t dz = ((TGeoPara*)vol->GetShape())->GetZ(); + fTxz = ((TGeoPara *)vol->GetShape())->GetTxz(); + fTyz = ((TGeoPara *)vol->GetShape())->GetTyz(); + Double_t dz = ((TGeoPara *)vol->GetShape())->GetZ(); fStart = -dz; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } @@ -1192,31 +1206,30 @@ TGeoPatternParaZ::TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions, Double_t s /// constructor TGeoPatternParaZ::TGeoPatternParaZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fTxz = ((TGeoPara*)vol->GetShape())->GetTxz(); - fTyz = ((TGeoPara*)vol->GetShape())->GetTyz(); - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fTxz = ((TGeoPara *)vol->GetShape())->GetTxz(); + fTyz = ((TGeoPara *)vol->GetShape())->GetTyz(); + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternParaZ::TGeoPatternParaZ(const TGeoPatternParaZ& pf) : - TGeoPatternFinder(pf) +TGeoPatternParaZ::TGeoPatternParaZ(const TGeoPatternParaZ &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternParaZ& TGeoPatternParaZ::operator=(const TGeoPatternParaZ& pf) +TGeoPatternParaZ &TGeoPatternParaZ::operator=(const TGeoPatternParaZ &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -1226,21 +1239,19 @@ TGeoPatternParaZ& TGeoPatternParaZ::operator=(const TGeoPatternParaZ& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternParaZ::~TGeoPatternParaZ() -{ -} +TGeoPatternParaZ::~TGeoPatternParaZ() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternParaZ::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); td.fCurrent = idiv; - Double_t dz = fStart+idiv*fStep+0.5*fStep; - td.fMatrix->SetDx(fTxz*dz); - td.fMatrix->SetDy(fTyz*dz); - td.fMatrix->SetDz((IsReflected())?-dz:dz); + Double_t dz = fStart + idiv * fStep + 0.5 * fStep; + td.fMatrix->SetDx(fTxz * dz); + td.fMatrix->SetDy(fTyz * dz); + td.fMatrix->SetDz((IsReflected()) ? -dz : dz); } //////////////////////////////////////////////////////////////////////////////// @@ -1248,10 +1259,12 @@ void TGeoPatternParaZ::cd(Int_t idiv) Bool_t TGeoPatternParaZ::IsOnBoundary(const Double_t *point) const { - Double_t seg = (point[2]-fStart)/fStep; + Double_t seg = (point[2] - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -1260,17 +1273,21 @@ Bool_t TGeoPatternParaZ::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternParaZ::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; Double_t zt = point[2]; - Int_t ind = (Int_t)(1.+(zt-fStart)/fStep) - 1; + Int_t ind = (Int_t)(1. + (zt - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - if (dir[2]>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dir[2] > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -1282,7 +1299,8 @@ TGeoNode *TGeoPatternParaZ::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternParaZ::MakeCopy(Bool_t reflect) { TGeoPatternParaZ *finder = new TGeoPatternParaZ(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -1299,10 +1317,10 @@ void TGeoPatternParaZ::SavePrimitive(std::ostream &out, Option_t * /*option*/ /* //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternParaZ::CreateMatrix() const +TGeoMatrix *TGeoPatternParaZ::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -1320,10 +1338,10 @@ TGeoMatrix* TGeoPatternParaZ::CreateMatrix() const void TGeoPatternParaZ::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - Double_t dz = fStart+idiv*fStep+0.5*fStep; - matrix.SetDx(fTxz*dz); - matrix.SetDy(fTyz*dz); - matrix.SetDz((IsReflected())?-dz:dz); + Double_t dz = fStart + idiv * fStep + 0.5 * fStep; + matrix.SetDx(fTxz * dz); + matrix.SetDy(fTyz * dz); + matrix.SetDz((IsReflected()) ? -dz : dz); } //______________________________________________________________________________ @@ -1342,68 +1360,64 @@ TGeoPatternTrapZ::TGeoPatternTrapZ() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternTrapZ::TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternTrapZ::TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { - Double_t theta = ((TGeoTrap*)vol->GetShape())->GetTheta(); - Double_t phi = ((TGeoTrap*)vol->GetShape())->GetPhi(); - fTxz = TMath::Tan(theta*TMath::DegToRad())*TMath::Cos(phi*TMath::DegToRad()); - fTyz = TMath::Tan(theta*TMath::DegToRad())*TMath::Sin(phi*TMath::DegToRad()); - Double_t dz = ((TGeoArb8*)vol->GetShape())->GetDz(); + Double_t theta = ((TGeoTrap *)vol->GetShape())->GetTheta(); + Double_t phi = ((TGeoTrap *)vol->GetShape())->GetPhi(); + fTxz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Cos(phi * TMath::DegToRad()); + fTyz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Sin(phi * TMath::DegToRad()); + Double_t dz = ((TGeoArb8 *)vol->GetShape())->GetDz(); fStart = -dz; fEnd = dz; - fStep = 2*dz/ndivisions; + fStep = 2 * dz / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternTrapZ::TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - Double_t theta = ((TGeoTrap*)vol->GetShape())->GetTheta(); - Double_t phi = ((TGeoTrap*)vol->GetShape())->GetPhi(); - fTxz = TMath::Tan(theta*TMath::DegToRad())*TMath::Cos(phi*TMath::DegToRad()); - fTyz = TMath::Tan(theta*TMath::DegToRad())*TMath::Sin(phi*TMath::DegToRad()); - Double_t dz = ((TGeoArb8*)vol->GetShape())->GetDz(); + Double_t theta = ((TGeoTrap *)vol->GetShape())->GetTheta(); + Double_t phi = ((TGeoTrap *)vol->GetShape())->GetPhi(); + fTxz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Cos(phi * TMath::DegToRad()); + fTyz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Sin(phi * TMath::DegToRad()); + Double_t dz = ((TGeoArb8 *)vol->GetShape())->GetDz(); fStart = -dz; - fEnd = fStart + ndivisions*step; - fStep = step; + fEnd = fStart + ndivisions * step; + fStep = step; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternTrapZ::TGeoPatternTrapZ(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) -{ - Double_t theta = ((TGeoTrap*)vol->GetShape())->GetTheta(); - Double_t phi = ((TGeoTrap*)vol->GetShape())->GetPhi(); - fTxz = TMath::Tan(theta*TMath::DegToRad())*TMath::Cos(phi*TMath::DegToRad()); - fTyz = TMath::Tan(theta*TMath::DegToRad())*TMath::Sin(phi*TMath::DegToRad()); - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + : TGeoPatternFinder(vol, ndivisions) +{ + Double_t theta = ((TGeoTrap *)vol->GetShape())->GetTheta(); + Double_t phi = ((TGeoTrap *)vol->GetShape())->GetPhi(); + fTxz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Cos(phi * TMath::DegToRad()); + fTyz = TMath::Tan(theta * TMath::DegToRad()) * TMath::Sin(phi * TMath::DegToRad()); + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternTrapZ::TGeoPatternTrapZ(const TGeoPatternTrapZ& pf) : - TGeoPatternFinder(pf), - fTxz(pf.fTxz), - fTyz(pf.fTyz) +TGeoPatternTrapZ::TGeoPatternTrapZ(const TGeoPatternTrapZ &pf) : TGeoPatternFinder(pf), fTxz(pf.fTxz), fTyz(pf.fTyz) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternTrapZ& TGeoPatternTrapZ::operator=(const TGeoPatternTrapZ& pf) +TGeoPatternTrapZ &TGeoPatternTrapZ::operator=(const TGeoPatternTrapZ &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); fTxz = pf.fTxz; fTyz = pf.fTyz; @@ -1415,20 +1429,18 @@ TGeoPatternTrapZ& TGeoPatternTrapZ::operator=(const TGeoPatternTrapZ& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternTrapZ::~TGeoPatternTrapZ() -{ -} +TGeoPatternTrapZ::~TGeoPatternTrapZ() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternTrapZ::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); td.fCurrent = idiv; - Double_t dz = fStart+idiv*fStep+0.5*fStep; - td.fMatrix->SetDx(fTxz*dz); - td.fMatrix->SetDy(fTyz*dz); - td.fMatrix->SetDz((IsReflected())?-dz:dz); + Double_t dz = fStart + idiv * fStep + 0.5 * fStep; + td.fMatrix->SetDx(fTxz * dz); + td.fMatrix->SetDy(fTyz * dz); + td.fMatrix->SetDz((IsReflected()) ? -dz : dz); } //////////////////////////////////////////////////////////////////////////////// @@ -1436,10 +1448,12 @@ void TGeoPatternTrapZ::cd(Int_t idiv) Bool_t TGeoPatternTrapZ::IsOnBoundary(const Double_t *point) const { - Double_t seg = (point[2]-fStart)/fStep; + Double_t seg = (point[2] - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -1448,17 +1462,21 @@ Bool_t TGeoPatternTrapZ::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternTrapZ::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; Double_t zt = point[2]; - Int_t ind = (Int_t)(1. + (zt-fStart)/fStep) - 1; + Int_t ind = (Int_t)(1. + (zt - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - if (dir[2]>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + if (dir[2] > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -1470,7 +1488,8 @@ TGeoNode *TGeoPatternTrapZ::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternTrapZ::MakeCopy(Bool_t reflect) { TGeoPatternTrapZ *finder = new TGeoPatternTrapZ(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -1487,10 +1506,10 @@ void TGeoPatternTrapZ::SavePrimitive(std::ostream &out, Option_t * /*option*/ /* //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternTrapZ::CreateMatrix() const +TGeoMatrix *TGeoPatternTrapZ::CreateMatrix() const { if (!IsReflected()) { - TGeoMatrix *matrix = new TGeoTranslation(0.,0.,0.); + TGeoMatrix *matrix = new TGeoTranslation(0., 0., 0.); matrix->RegisterYourself(); return matrix; } @@ -1508,10 +1527,10 @@ TGeoMatrix* TGeoPatternTrapZ::CreateMatrix() const void TGeoPatternTrapZ::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { matrix.Clear(); - Double_t dz = fStart+idiv*fStep+0.5*fStep; - matrix.SetDx(fTxz*dz); - matrix.SetDy(fTyz*dz); - matrix.SetDz((IsReflected())?-dz:dz); + Double_t dz = fStart + idiv * fStep + 0.5 * fStep; + matrix.SetDx(fTxz * dz); + matrix.SetDy(fTyz * dz); + matrix.SetDz((IsReflected()) ? -dz : dz); } //______________________________________________________________________________ @@ -1528,47 +1547,44 @@ TGeoPatternCylR::TGeoPatternCylR() //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternCylR::TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternCylR::TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// constructor -TGeoPatternCylR::TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions, Double_t step) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternCylR::TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions, Double_t step) : TGeoPatternFinder(vol, ndivisions) { - fStep = step; + fStep = step; CreateThreadData(1); -// compute start, end + // compute start, end } //////////////////////////////////////////////////////////////////////////////// /// constructor TGeoPatternCylR::TGeoPatternCylR(TGeoVolume *vol, Int_t ndivisions, Double_t start, Double_t end) - :TGeoPatternFinder(vol, ndivisions) + : TGeoPatternFinder(vol, ndivisions) { - fStart = start; - fEnd = end; - fStep = (end - start)/ndivisions; + fStart = start; + fEnd = end; + fStep = (end - start) / ndivisions; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternCylR::TGeoPatternCylR(const TGeoPatternCylR& pf) : - TGeoPatternFinder(pf) +TGeoPatternCylR::TGeoPatternCylR(const TGeoPatternCylR &pf) : TGeoPatternFinder(pf) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternCylR& TGeoPatternCylR::operator=(const TGeoPatternCylR& pf) +TGeoPatternCylR &TGeoPatternCylR::operator=(const TGeoPatternCylR &pf) { - if(this!=&pf) { + if (this != &pf) { TGeoPatternFinder::operator=(pf); CreateThreadData(1); } @@ -1578,20 +1594,20 @@ TGeoPatternCylR& TGeoPatternCylR::operator=(const TGeoPatternCylR& pf) //////////////////////////////////////////////////////////////////////////////// /// Destructor -TGeoPatternCylR::~TGeoPatternCylR() -{ -} +TGeoPatternCylR::~TGeoPatternCylR() {} //////////////////////////////////////////////////////////////////////////////// /// Checks if the current point is on division boundary Bool_t TGeoPatternCylR::IsOnBoundary(const Double_t *point) const { - Double_t r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Double_t seg = (r-fStart)/fStep; + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t seg = (r - fStart) / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -1600,8 +1616,8 @@ Bool_t TGeoPatternCylR::IsOnBoundary(const Double_t *point) const void TGeoPatternCylR::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; } //////////////////////////////////////////////////////////////////////////////// @@ -1609,19 +1625,24 @@ void TGeoPatternCylR::cd(Int_t idiv) TGeoNode *TGeoPatternCylR::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); - if (!td.fMatrix) td.fMatrix = gGeoIdentity; + ThreadData_t &td = GetThreadData(); + if (!td.fMatrix) + td.fMatrix = gGeoIdentity; TGeoNode *node = 0; - Double_t r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Int_t ind = (Int_t)(1. + (r-fStart)/fStep) - 1; + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Int_t ind = (Int_t)(1. + (r - fStart) / fStep) - 1; if (dir) { td.fNextIndex = ind; - Double_t dot = point[0]*dir[0] + point[1]*dir[1]; - if (dot>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + Double_t dot = point[0] * dir[0] + point[1] * dir[1]; + if (dot > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -1633,7 +1654,8 @@ TGeoNode *TGeoPatternCylR::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternCylR::MakeCopy(Bool_t reflect) { TGeoPatternCylR *finder = new TGeoPatternCylR(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -1650,7 +1672,7 @@ void TGeoPatternCylR::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternCylR::CreateMatrix() const +TGeoMatrix *TGeoPatternCylR::CreateMatrix() const { return gGeoIdentity; } @@ -1680,16 +1702,15 @@ TGeoPatternCylPhi::TGeoPatternCylPhi() /// constructor /// compute step, start, end -TGeoPatternCylPhi::TGeoPatternCylPhi(TGeoVolume *vol, Int_t ndivisions) - :TGeoPatternFinder(vol, ndivisions) +TGeoPatternCylPhi::TGeoPatternCylPhi(TGeoVolume *vol, Int_t ndivisions) : TGeoPatternFinder(vol, ndivisions) { fStart = 0; fEnd = 0; fStep = 0; - fSinCos = new Double_t[2*fNdivisions]; - for (Int_t i = 0; iFastRotZ(&fSinCos[2*idiv]); + ((TGeoRotation *)td.fMatrix)->FastRotZ(&fSinCos[2 * idiv]); } //////////////////////////////////////////////////////////////////////////////// @@ -1751,14 +1775,18 @@ void TGeoPatternCylPhi::cd(Int_t idiv) Bool_t TGeoPatternCylPhi::IsOnBoundary(const Double_t *point) const { - Double_t phi = TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi += 360; + Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360; Double_t ddp = phi - fStart; - if (ddp<0) ddp+=360; - Double_t seg = ddp/fStep; + if (ddp < 0) + ddp += 360; + Double_t seg = ddp / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } @@ -1767,23 +1795,29 @@ Bool_t TGeoPatternCylPhi::IsOnBoundary(const Double_t *point) const TGeoNode *TGeoPatternCylPhi::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Double_t phi = TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi += 360; -// Double_t dphi = fStep*fNdivisions; + Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360; + // Double_t dphi = fStep*fNdivisions; Double_t ddp = phi - fStart; - if (ddp<0) ddp+=360; -// if (ddp>360) ddp-=360; - Int_t ind = (Int_t)(1. + ddp/fStep) - 1; + if (ddp < 0) + ddp += 360; + // if (ddp>360) ddp-=360; + Int_t ind = (Int_t)(1. + ddp / fStep) - 1; if (dir) { td.fNextIndex = ind; - Double_t dot = point[0]*dir[1]-point[1]*dir[0]; - if (dot>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + Double_t dot = point[0] * dir[1] - point[1] * dir[0]; + if (dot > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -1795,7 +1829,8 @@ TGeoNode *TGeoPatternCylPhi::FindNode(Double_t *point, const Double_t *dir) TGeoPatternFinder *TGeoPatternCylPhi::MakeCopy(Bool_t reflect) { TGeoPatternCylPhi *finder = new TGeoPatternCylPhi(*this); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -1817,10 +1852,10 @@ void TGeoPatternCylPhi::Streamer(TBuffer &R__b) if (R__b.IsReading()) { R__b.ReadClassBuffer(TGeoPatternCylPhi::Class(), this); if (fNdivisions) { - fSinCos = new Double_t[2*fNdivisions]; - for (Int_t idiv = 0; idivFastRotZ(&fSinCos[2*idiv]); + if (!fSinCos) + CreateSinCos(); + ((TGeoRotation *)td.fMatrix)->FastRotZ(&fSinCos[2 * idiv]); } //////////////////////////////////////////////////////////////////////////////// @@ -2183,38 +2211,48 @@ void TGeoPatternSphPhi::cd(Int_t idiv) Bool_t TGeoPatternSphPhi::IsOnBoundary(const Double_t *point) const { - Double_t phi = TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi += 360; + Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360; Double_t ddp = phi - fStart; - if (ddp<0) ddp+=360; - Double_t seg = ddp/fStep; + if (ddp < 0) + ddp += 360; + Double_t seg = ddp / fStep; Double_t diff = seg - Int_t(seg); - if (diff>0.5) diff = 1.-diff; - if (diff<1e-8) return kTRUE; + if (diff > 0.5) + diff = 1. - diff; + if (diff < 1e-8) + return kTRUE; return kFALSE; } //////////////////////////////////////////////////////////////////////////////// /// find the node containing the query point -TGeoNode *TGeoPatternSphPhi::FindNode(Double_t * point, const Double_t * dir) +TGeoNode *TGeoPatternSphPhi::FindNode(Double_t *point, const Double_t *dir) { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); TGeoNode *node = 0; - Double_t phi = TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi += 360; -// Double_t dphi = fStep*fNdivisions; + Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360; + // Double_t dphi = fStep*fNdivisions; Double_t ddp = phi - fStart; - if (ddp<0) ddp+=360; -// if (ddp>360) ddp-=360; - Int_t ind = (Int_t)(1. + ddp/fStep) - 1; + if (ddp < 0) + ddp += 360; + // if (ddp>360) ddp-=360; + Int_t ind = (Int_t)(1. + ddp / fStep) - 1; if (dir) { td.fNextIndex = ind; - Double_t dot = point[0]*dir[1]-point[1]*dir[0]; - if (dot>0) td.fNextIndex++; - else td.fNextIndex--; - if ((td.fNextIndex<0) || (td.fNextIndex>=fNdivisions)) td.fNextIndex = -1; + Double_t dot = point[0] * dir[1] - point[1] * dir[0]; + if (dot > 0) + td.fNextIndex++; + else + td.fNextIndex--; + if ((td.fNextIndex < 0) || (td.fNextIndex >= fNdivisions)) + td.fNextIndex = -1; } - if ((ind<0) || (ind>=fNdivisions)) return node; + if ((ind < 0) || (ind >= fNdivisions)) + return node; node = GetNodeOffset(ind); cd(ind); return node; @@ -2225,7 +2263,8 @@ TGeoNode *TGeoPatternSphPhi::FindNode(Double_t * point, const Double_t * dir) TGeoPatternFinder *TGeoPatternSphPhi::MakeCopy(Bool_t reflect) { TGeoPatternSphPhi *finder = new TGeoPatternSphPhi(fVolume, fNdivisions, fStart, fEnd); - if (!reflect) return finder; + if (!reflect) + return finder; finder->Reflect(); return finder; } @@ -2241,7 +2280,7 @@ void TGeoPatternSphPhi::SavePrimitive(std::ostream &out, Option_t * /*option*/ / //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternSphPhi::CreateMatrix() const +TGeoMatrix *TGeoPatternSphPhi::CreateMatrix() const { if (!IsReflected()) { TGeoRotation *matrix = new TGeoRotation(); @@ -2260,9 +2299,10 @@ TGeoMatrix* TGeoPatternSphPhi::CreateMatrix() const void TGeoPatternSphPhi::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const { - if (!fSinCos) ((TGeoPatternSphPhi*)this)->CreateSinCos(); + if (!fSinCos) + ((TGeoPatternSphPhi *)this)->CreateSinCos(); matrix.Clear(); - matrix.FastRotZ(&fSinCos[2*idiv]); + matrix.FastRotZ(&fSinCos[2 * idiv]); } //______________________________________________________________________________ @@ -2274,49 +2314,48 @@ void TGeoPatternSphPhi::UpdateMatrix(Int_t idiv, TGeoHMatrix &matrix) const TGeoPatternHoneycomb::TGeoPatternHoneycomb() { - fNrows = 0; - fAxisOnRows = 0; - fNdivisions = 0; - fStart = 0; + fNrows = 0; + fAxisOnRows = 0; + fNdivisions = 0; + fStart = 0; CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoPatternHoneycomb::TGeoPatternHoneycomb(TGeoVolume *vol, Int_t nrows) - :TGeoPatternFinder(vol, nrows) +TGeoPatternHoneycomb::TGeoPatternHoneycomb(TGeoVolume *vol, Int_t nrows) : TGeoPatternFinder(vol, nrows) { fNrows = nrows; - fAxisOnRows = 0; - fNdivisions = 0; - fStart = 0; + fAxisOnRows = 0; + fNdivisions = 0; + fStart = 0; CreateThreadData(1); -// compute everything else + // compute everything else } //////////////////////////////////////////////////////////////////////////////// -///copy constructor +/// copy constructor -TGeoPatternHoneycomb::TGeoPatternHoneycomb(const TGeoPatternHoneycomb& pfh) : - TGeoPatternFinder(pfh), - fNrows(pfh.fNrows), - fAxisOnRows(pfh.fAxisOnRows), - fNdivisions(pfh.fNdivisions), - fStart(pfh.fStart) +TGeoPatternHoneycomb::TGeoPatternHoneycomb(const TGeoPatternHoneycomb &pfh) + : TGeoPatternFinder(pfh), + fNrows(pfh.fNrows), + fAxisOnRows(pfh.fAxisOnRows), + fNdivisions(pfh.fNdivisions), + fStart(pfh.fStart) { CreateThreadData(1); } //////////////////////////////////////////////////////////////////////////////// -///assignment operator +/// assignment operator -TGeoPatternHoneycomb& TGeoPatternHoneycomb::operator=(const TGeoPatternHoneycomb& pfh) +TGeoPatternHoneycomb &TGeoPatternHoneycomb::operator=(const TGeoPatternHoneycomb &pfh) { - if(this!=&pfh) { + if (this != &pfh) { TGeoPatternFinder::operator=(pfh); - fNrows=pfh.fNrows; - fAxisOnRows=pfh.fAxisOnRows; - fNdivisions=pfh.fNdivisions; - fStart=pfh.fStart; + fNrows = pfh.fNrows; + fAxisOnRows = pfh.fAxisOnRows; + fNdivisions = pfh.fNdivisions; + fStart = pfh.fStart; CreateThreadData(1); } return *this; @@ -2324,16 +2363,14 @@ TGeoPatternHoneycomb& TGeoPatternHoneycomb::operator=(const TGeoPatternHoneycomb //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoPatternHoneycomb::~TGeoPatternHoneycomb() -{ -} +TGeoPatternHoneycomb::~TGeoPatternHoneycomb() {} //////////////////////////////////////////////////////////////////////////////// /// Update current division index and global matrix to point to a given slice. void TGeoPatternHoneycomb::cd(Int_t idiv) { - ThreadData_t& td = GetThreadData(); - td.fCurrent=idiv; + ThreadData_t &td = GetThreadData(); + td.fCurrent = idiv; } //////////////////////////////////////////////////////////////////////////////// /// find the node containing the query point @@ -2346,7 +2383,7 @@ TGeoNode *TGeoPatternHoneycomb::FindNode(Double_t * /*point*/, const Double_t * //////////////////////////////////////////////////////////////////////////////// /// Return new matrix of type used by this finder. -TGeoMatrix* TGeoPatternHoneycomb::CreateMatrix() const +TGeoMatrix *TGeoPatternHoneycomb::CreateMatrix() const { return gGeoIdentity; } diff --git a/geom/geom/src/TGeoPcon.cxx b/geom/geom/src/TGeoPcon.cxx index 771cf5b04773e..0978e5d249b57 100644 --- a/geom/geom/src/TGeoPcon.cxx +++ b/geom/geom/src/TGeoPcon.cxx @@ -102,21 +102,21 @@ ClassImp(TGeoPcon); /// dummy ctor TGeoPcon::TGeoPcon() - :TGeoBBox(), - fNz(0), - fPhi1(0.), - fDphi(0.), - fRmin(nullptr), - fRmax(nullptr), - fZ(nullptr), - fFullPhi(kFALSE), - fC1(0.), - fS1(0.), - fC2(0.), - fS2(0.), - fCm(0.), - fSm(0.), - fCdphi(0.) + : TGeoBBox(), + fNz(0), + fPhi1(0.), + fDphi(0.), + fRmin(nullptr), + fRmax(nullptr), + fZ(nullptr), + fFullPhi(kFALSE), + fC1(0.), + fS1(0.), + fC2(0.), + fS2(0.), + fCm(0.), + fSm(0.), + fCdphi(0.) { SetShapeBit(TGeoShape::kGeoPcon); } @@ -125,82 +125,86 @@ TGeoPcon::TGeoPcon() /// Default constructor TGeoPcon::TGeoPcon(Double_t phi, Double_t dphi, Int_t nz) - :TGeoBBox(0, 0, 0), - fNz(nz), - fPhi1(phi), - fDphi(dphi), - fRmin(nullptr), - fRmax(nullptr), - fZ(nullptr), - fFullPhi(kFALSE), - fC1(0.), - fS1(0.), - fC2(0.), - fS2(0.), - fCm(0.), - fSm(0.), - fCdphi(0.) + : TGeoBBox(0, 0, 0), + fNz(nz), + fPhi1(phi), + fDphi(dphi), + fRmin(nullptr), + fRmax(nullptr), + fZ(nullptr), + fFullPhi(kFALSE), + fC1(0.), + fS1(0.), + fC2(0.), + fS2(0.), + fCm(0.), + fSm(0.), + fCdphi(0.) { SetShapeBit(TGeoShape::kGeoPcon); - while (fPhi1<0) fPhi1+=360.; - fRmin = new Double_t [nz]; - fRmax = new Double_t [nz]; - fZ = new Double_t [nz]; - memset(fRmin, 0, nz*sizeof(Double_t)); - memset(fRmax, 0, nz*sizeof(Double_t)); - memset(fZ, 0, nz*sizeof(Double_t)); - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) fFullPhi = kTRUE; + while (fPhi1 < 0) + fPhi1 += 360.; + fRmin = new Double_t[nz]; + fRmax = new Double_t[nz]; + fZ = new Double_t[nz]; + memset(fRmin, 0, nz * sizeof(Double_t)); + memset(fRmax, 0, nz * sizeof(Double_t)); + memset(fZ, 0, nz * sizeof(Double_t)); + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) + fFullPhi = kTRUE; Double_t phi1 = fPhi1; - Double_t phi2 = phi1+fDphi; - Double_t phim = 0.5*(phi1+phi2); - fC1 = TMath::Cos(phi1*TMath::DegToRad()); - fS1 = TMath::Sin(phi1*TMath::DegToRad()); - fC2 = TMath::Cos(phi2*TMath::DegToRad()); - fS2 = TMath::Sin(phi2*TMath::DegToRad()); - fCm = TMath::Cos(phim*TMath::DegToRad()); - fSm = TMath::Sin(phim*TMath::DegToRad()); - fCdphi = TMath::Cos(0.5*fDphi*TMath::DegToRad()); + Double_t phi2 = phi1 + fDphi; + Double_t phim = 0.5 * (phi1 + phi2); + fC1 = TMath::Cos(phi1 * TMath::DegToRad()); + fS1 = TMath::Sin(phi1 * TMath::DegToRad()); + fC2 = TMath::Cos(phi2 * TMath::DegToRad()); + fS2 = TMath::Sin(phi2 * TMath::DegToRad()); + fCm = TMath::Cos(phim * TMath::DegToRad()); + fSm = TMath::Sin(phim * TMath::DegToRad()); + fCdphi = TMath::Cos(0.5 * fDphi * TMath::DegToRad()); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor TGeoPcon::TGeoPcon(const char *name, Double_t phi, Double_t dphi, Int_t nz) - :TGeoBBox(name, 0, 0, 0), - fNz(nz), - fPhi1(phi), - fDphi(dphi), - fRmin(nullptr), - fRmax(nullptr), - fZ(nullptr), - fFullPhi(kFALSE), - fC1(0.), - fS1(0.), - fC2(0.), - fS2(0.), - fCm(0.), - fSm(0.), - fCdphi(0.) + : TGeoBBox(name, 0, 0, 0), + fNz(nz), + fPhi1(phi), + fDphi(dphi), + fRmin(nullptr), + fRmax(nullptr), + fZ(nullptr), + fFullPhi(kFALSE), + fC1(0.), + fS1(0.), + fC2(0.), + fS2(0.), + fCm(0.), + fSm(0.), + fCdphi(0.) { SetShapeBit(TGeoShape::kGeoPcon); - while (fPhi1<0) fPhi1+=360.; - fRmin = new Double_t [nz]; - fRmax = new Double_t [nz]; - fZ = new Double_t [nz]; - memset(fRmin, 0, nz*sizeof(Double_t)); - memset(fRmax, 0, nz*sizeof(Double_t)); - memset(fZ, 0, nz*sizeof(Double_t)); - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) fFullPhi = kTRUE; + while (fPhi1 < 0) + fPhi1 += 360.; + fRmin = new Double_t[nz]; + fRmax = new Double_t[nz]; + fZ = new Double_t[nz]; + memset(fRmin, 0, nz * sizeof(Double_t)); + memset(fRmax, 0, nz * sizeof(Double_t)); + memset(fZ, 0, nz * sizeof(Double_t)); + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) + fFullPhi = kTRUE; Double_t phi1 = fPhi1; - Double_t phi2 = phi1+fDphi; - Double_t phim = 0.5*(phi1+phi2); - fC1 = TMath::Cos(phi1*TMath::DegToRad()); - fS1 = TMath::Sin(phi1*TMath::DegToRad()); - fC2 = TMath::Cos(phi2*TMath::DegToRad()); - fS2 = TMath::Sin(phi2*TMath::DegToRad()); - fCm = TMath::Cos(phim*TMath::DegToRad()); - fSm = TMath::Sin(phim*TMath::DegToRad()); - fCdphi = TMath::Cos(0.5*fDphi*TMath::DegToRad()); + Double_t phi2 = phi1 + fDphi; + Double_t phim = 0.5 * (phi1 + phi2); + fC1 = TMath::Cos(phi1 * TMath::DegToRad()); + fS1 = TMath::Sin(phi1 * TMath::DegToRad()); + fC2 = TMath::Cos(phi2 * TMath::DegToRad()); + fS2 = TMath::Sin(phi2 * TMath::DegToRad()); + fCm = TMath::Cos(phim * TMath::DegToRad()); + fSm = TMath::Sin(phim * TMath::DegToRad()); + fCdphi = TMath::Cos(0.5 * fDphi * TMath::DegToRad()); } //////////////////////////////////////////////////////////////////////////////// @@ -214,21 +218,21 @@ TGeoPcon::TGeoPcon(const char *name, Double_t phi, Double_t dphi, Int_t nz) /// ... TGeoPcon::TGeoPcon(Double_t *param) - :TGeoBBox(0, 0, 0), - fNz(0), - fPhi1(0.), - fDphi(0.), - fRmin(nullptr), - fRmax(nullptr), - fZ(nullptr), - fFullPhi(kFALSE), - fC1(0.), - fS1(0.), - fC2(0.), - fS2(0.), - fCm(0.), - fSm(0.), - fCdphi(0.) + : TGeoBBox(0, 0, 0), + fNz(0), + fPhi1(0.), + fDphi(0.), + fRmin(nullptr), + fRmax(nullptr), + fZ(nullptr), + fFullPhi(kFALSE), + fC1(0.), + fS1(0.), + fC2(0.), + fS2(0.), + fCm(0.), + fSm(0.), + fCdphi(0.) { SetShapeBit(TGeoShape::kGeoPcon); SetDimensions(param); @@ -240,9 +244,18 @@ TGeoPcon::TGeoPcon(Double_t *param) TGeoPcon::~TGeoPcon() { - if (fRmin) { delete[] fRmin; fRmin = nullptr; } - if (fRmax) { delete[] fRmax; fRmax = nullptr; } - if (fZ) { delete[] fZ; fZ = nullptr; } + if (fRmin) { + delete[] fRmin; + fRmin = nullptr; + } + if (fRmax) { + delete[] fRmax; + fRmax = nullptr; + } + if (fZ) { + delete[] fZ; + fZ = nullptr; + } } //////////////////////////////////////////////////////////////////////////////// @@ -255,14 +268,15 @@ Double_t TGeoPcon::Capacity() const Double_t capacity = 0.; phi1 = fPhi1; phi2 = fPhi1 + fDphi; - for (ipl=0; iplfZ[isec+1]) { + if (fZ[isec] > fZ[isec + 1]) { InspectShape(); Fatal("ComputeBBox", "Wrong section order"); } } // Check if the last sections are valid - if (TMath::Abs(fZ[1]-fZ[0]) < TGeoShape::Tolerance() || - TMath::Abs(fZ[fNz-1]-fZ[fNz-2]) < TGeoShape::Tolerance()) { + if (TMath::Abs(fZ[1] - fZ[0]) < TGeoShape::Tolerance() || + TMath::Abs(fZ[fNz - 1] - fZ[fNz - 2]) < TGeoShape::Tolerance()) { InspectShape(); - Fatal("ComputeBBox","Shape %s at index %d: Not allowed first two or last two sections at same Z", - GetName(), gGeoManager->GetListOfShapes()->IndexOf(this)); + Fatal("ComputeBBox", "Shape %s at index %d: Not allowed first two or last two sections at same Z", GetName(), + gGeoManager->GetListOfShapes()->IndexOf(this)); } - Double_t zmin = TMath::Min(fZ[0], fZ[fNz-1]); - Double_t zmax = TMath::Max(fZ[0], fZ[fNz-1]); + Double_t zmin = TMath::Min(fZ[0], fZ[fNz - 1]); + Double_t zmax = TMath::Max(fZ[0], fZ[fNz - 1]); // find largest rmax an smallest rmin Double_t rmin, rmax; rmin = fRmin[TMath::LocMin(fNz, fRmin)]; @@ -303,14 +317,14 @@ void TGeoPcon::ComputeBBox() Double_t xc[4]; Double_t yc[4]; - xc[0] = rmax*fC1; - yc[0] = rmax*fS1; - xc[1] = rmax*fC2; - yc[1] = rmax*fS2; - xc[2] = rmin*fC1; - yc[2] = rmin*fS1; - xc[3] = rmin*fC2; - yc[3] = rmin*fS2; + xc[0] = rmax * fC1; + yc[0] = rmax * fS1; + xc[1] = rmax * fC2; + yc[1] = rmax * fS2; + xc[2] = rmin * fC1; + yc[2] = rmin * fS1; + xc[3] = rmin * fC2; + yc[3] = rmin * fS2; Double_t xmin = xc[TMath::LocMin(4, &xc[0])]; Double_t xmax = xc[TMath::LocMax(4, &xc[0])]; @@ -318,23 +332,31 @@ void TGeoPcon::ComputeBBox() Double_t ymax = yc[TMath::LocMax(4, &yc[0])]; Double_t ddp = -fPhi1; - if (ddp<0) ddp+= 360; - if (ddp<=fDphi) xmax = rmax; - ddp = 90-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp<=fDphi) ymax = rmax; - ddp = 180-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp<=fDphi) xmin = -rmax; - ddp = 270-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp<=fDphi) ymin = -rmax; - fOrigin[0] = (xmax+xmin)/2; - fOrigin[1] = (ymax+ymin)/2; - fOrigin[2] = (zmax+zmin)/2; - fDX = (xmax-xmin)/2; - fDY = (ymax-ymin)/2; - fDZ = (zmax-zmin)/2; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + xmax = rmax; + ddp = 90 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + ymax = rmax; + ddp = 180 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + xmin = -rmax; + ddp = 270 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + ymin = -rmax; + fOrigin[0] = (xmax + xmin) / 2; + fOrigin[1] = (ymax + ymin) / 2; + fOrigin[2] = (zmax + zmin) / 2; + fDX = (xmax - xmin) / 2; + fDY = (ymax - ymin) / 2; + fDZ = (zmax - zmin) / 2; SetShapeBit(kGeoClosedShape); } @@ -343,59 +365,67 @@ void TGeoPcon::ComputeBBox() void TGeoPcon::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - memset(norm,0,3*sizeof(Double_t)); + memset(norm, 0, 3 * sizeof(Double_t)); Double_t r; Double_t ptnew[3]; Double_t dz, rmin1, rmax1, rmin2, rmax2; Bool_t is_tube; Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl==(fNz-1) || ipl<0) { + if (ipl == (fNz - 1) || ipl < 0) { // point outside Z range norm[2] = TMath::Sign(1., dir[2]); return; } Int_t iplclose = ipl; - if ((fZ[ipl+1]-point[2])<(point[2]-fZ[ipl])) iplclose++; - dz = TMath::Abs(fZ[iplclose]-point[2]); - if (dz<1E-5) { - if (iplclose==0 || iplclose==(fNz-1)) { + if ((fZ[ipl + 1] - point[2]) < (point[2] - fZ[ipl])) + iplclose++; + dz = TMath::Abs(fZ[iplclose] - point[2]); + if (dz < 1E-5) { + if (iplclose == 0 || iplclose == (fNz - 1)) { norm[2] = TMath::Sign(1., dir[2]); return; } - if (iplclose==ipl && TGeoShape::IsSameWithinTolerance(fZ[ipl],fZ[ipl-1])) { - r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - if (rTMath::Min(fRmax[ipl],fRmax[ipl-1])) { + if (iplclose == ipl && TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl - 1])) { + r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + if (r < TMath::Max(fRmin[ipl], fRmin[ipl - 1]) || r > TMath::Min(fRmax[ipl], fRmax[ipl - 1])) { norm[2] = TMath::Sign(1., dir[2]); return; } } else { - if (TGeoShape::IsSameWithinTolerance(fZ[iplclose],fZ[iplclose+1])) { - r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - if (rTMath::Min(fRmax[iplclose],fRmax[iplclose+1])) { + if (TGeoShape::IsSameWithinTolerance(fZ[iplclose], fZ[iplclose + 1])) { + r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + if (r < TMath::Max(fRmin[iplclose], fRmin[iplclose + 1]) || + r > TMath::Min(fRmax[iplclose], fRmax[iplclose + 1])) { norm[2] = TMath::Sign(1., dir[2]); return; } } } } //-> Z done - memcpy(ptnew, point, 3*sizeof(Double_t)); - dz = 0.5*(fZ[ipl+1]-fZ[ipl]); - if (TGeoShape::IsSameWithinTolerance(dz,0.)) { + memcpy(ptnew, point, 3 * sizeof(Double_t)); + dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); + if (TGeoShape::IsSameWithinTolerance(dz, 0.)) { norm[2] = TMath::Sign(1., dir[2]); return; } - ptnew[2] -= 0.5*(fZ[ipl]+fZ[ipl+1]); + ptnew[2] -= 0.5 * (fZ[ipl] + fZ[ipl + 1]); rmin1 = fRmin[ipl]; rmax1 = fRmax[ipl]; - rmin2 = fRmin[ipl+1]; - rmax2 = fRmax[ipl+1]; - is_tube = (TGeoShape::IsSameWithinTolerance(rmin1,rmin2) && TGeoShape::IsSameWithinTolerance(rmax1,rmax2))?kTRUE:kFALSE; + rmin2 = fRmin[ipl + 1]; + rmax2 = fRmax[ipl + 1]; + is_tube = (TGeoShape::IsSameWithinTolerance(rmin1, rmin2) && TGeoShape::IsSameWithinTolerance(rmax1, rmax2)) + ? kTRUE + : kFALSE; if (!fFullPhi) { - if (is_tube) TGeoTubeSeg::ComputeNormalS(ptnew,dir,norm,rmin1,rmax1,dz,fC1,fS1,fC2,fS2); - else TGeoConeSeg::ComputeNormalS(ptnew,dir,norm,dz,rmin1,rmax1,rmin2,rmax2,fC1,fS1,fC2,fS2); + if (is_tube) + TGeoTubeSeg::ComputeNormalS(ptnew, dir, norm, rmin1, rmax1, dz, fC1, fS1, fC2, fS2); + else + TGeoConeSeg::ComputeNormalS(ptnew, dir, norm, dz, rmin1, rmax1, rmin2, rmax2, fC1, fS1, fC2, fS2); } else { - if (is_tube) TGeoTube::ComputeNormalS(ptnew,dir,norm,rmin1,rmax1,dz); - else TGeoCone::ComputeNormalS(ptnew,dir,norm,dz,rmin1,rmax1,rmin2,rmax2); + if (is_tube) + TGeoTube::ComputeNormalS(ptnew, dir, norm, rmin1, rmax1, dz); + else + TGeoCone::ComputeNormalS(ptnew, dir, norm, dz, rmin1, rmax1, rmin2, rmax2); } } @@ -405,40 +435,49 @@ void TGeoPcon::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoPcon::Contains(const Double_t *point) const { - if ((point[2]fZ[fNz-1])) return kFALSE; + if ((point[2] < fZ[0]) || (point[2] > fZ[fNz - 1])) + return kFALSE; // check R squared - Double_t r2 = point[0]*point[0]+point[1]*point[1]; + Double_t r2 = point[0] * point[0] + point[1] * point[1]; Int_t izl = 0; - Int_t izh = fNz-1; - Int_t izt = (fNz-1)/2; - while ((izh-izl)>1) { - if (point[2] > fZ[izt]) izl = izt; - else izh = izt; - izt = (izl+izh)>>1; + Int_t izh = fNz - 1; + Int_t izt = (fNz - 1) / 2; + while ((izh - izl) > 1) { + if (point[2] > fZ[izt]) + izl = izt; + else + izh = izt; + izt = (izl + izh) >> 1; } // the point is in the section bounded by izl and izh Z planes // compute Rmin and Rmax and test the value of R squared Double_t rmin, rmax; - if (TGeoShape::IsSameWithinTolerance(fZ[izl],fZ[izh]) && TGeoShape::IsSameWithinTolerance(point[2],fZ[izl])) { + if (TGeoShape::IsSameWithinTolerance(fZ[izl], fZ[izh]) && TGeoShape::IsSameWithinTolerance(point[2], fZ[izl])) { rmin = TMath::Min(fRmin[izl], fRmin[izh]); rmax = TMath::Max(fRmax[izl], fRmax[izh]); } else { Double_t dz = fZ[izh] - fZ[izl]; Double_t dz1 = point[2] - fZ[izl]; - rmin = (fRmin[izl]*(dz-dz1)+fRmin[izh]*dz1)/dz; - rmax = (fRmax[izl]*(dz-dz1)+fRmax[izh]*dz1)/dz; + rmin = (fRmin[izl] * (dz - dz1) + fRmin[izh] * dz1) / dz; + rmax = (fRmax[izl] * (dz - dz1) + fRmax[izh] * dz1) / dz; } - if ((r2rmax*rmax)) return kFALSE; + if ((r2 < rmin * rmin) || (r2 > rmax * rmax)) + return kFALSE; // now check phi - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) return kTRUE; - if (r2<1E-10) return kTRUE; + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) + return kTRUE; + if (r2 < 1E-10) + return kTRUE; Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - if (phi < 0) phi+=360.0; - Double_t ddp = phi-fPhi1; - if (ddp<0) ddp+=360.; - if (ddp<=fDphi) return kTRUE; + if (phi < 0) + phi += 360.0; + Double_t ddp = phi - fPhi1; + if (ddp < 0) + ddp += 360.; + if (ddp <= fDphi) + return kTRUE; return kFALSE; } @@ -447,76 +486,88 @@ Bool_t TGeoPcon::Contains(const Double_t *point) const Int_t TGeoPcon::DistancetoPrimitive(Int_t px, Int_t py) { - Int_t n = gGeoManager->GetNsegments()+1; - const Int_t numPoints = 2*n*fNz; + Int_t n = gGeoManager->GetNsegments() + 1; + const Int_t numPoints = 2 * n * fNz; return ShapeDistancetoPrimitive(numPoints, px, py); } //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the polycone -Double_t TGeoPcon::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoPcon::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } Double_t snxt = TGeoShape::Big(); Double_t sstep = 1E-6; Double_t point_new[3]; // determine which z segment contains the point - Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]+TMath::Sign(1.E-10,dir[2])); - if (ipl<0) ipl=0; - if (ipl==(fNz-1)) ipl--; - Double_t dz = 0.5*(fZ[ipl+1]-fZ[ipl]); + Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2] + TMath::Sign(1.E-10, dir[2])); + if (ipl < 0) + ipl = 0; + if (ipl == (fNz - 1)) + ipl--; + Double_t dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); Bool_t special_case = kFALSE; - if (dz<1e-9) { + if (dz < 1e-9) { // radius changing segment, make sure track is not in the XY plane if (TGeoShape::IsSameWithinTolerance(dir[2], 0)) { special_case = kTRUE; } else { - //check if a close point is still contained - point_new[0] = point[0]+sstep*dir[0]; - point_new[1] = point[1]+sstep*dir[1]; - point_new[2] = point[2]+sstep*dir[2]; - if (!Contains(point_new)) return 0.; - return (DistFromInside(point_new,dir,iact,step,safe)+sstep); + // check if a close point is still contained + point_new[0] = point[0] + sstep * dir[0]; + point_new[1] = point[1] + sstep * dir[1]; + point_new[2] = point[2] + sstep * dir[2]; + if (!Contains(point_new)) + return 0.; + return (DistFromInside(point_new, dir, iact, step, safe) + sstep); } } // determine if the current segment is a tube or a cone Bool_t intub = kTRUE; - if (!TGeoShape::IsSameWithinTolerance(fRmin[ipl],fRmin[ipl+1])) intub=kFALSE; - else if (!TGeoShape::IsSameWithinTolerance(fRmax[ipl],fRmax[ipl+1])) intub=kFALSE; + if (!TGeoShape::IsSameWithinTolerance(fRmin[ipl], fRmin[ipl + 1])) + intub = kFALSE; + else if (!TGeoShape::IsSameWithinTolerance(fRmax[ipl], fRmax[ipl + 1])) + intub = kFALSE; // determine phi segmentation - memcpy(point_new, point, 2*sizeof(Double_t)); + memcpy(point_new, point, 2 * sizeof(Double_t)); // new point in reference system of the current segment - point_new[2] = point[2]-0.5*(fZ[ipl]+fZ[ipl+1]); + point_new[2] = point[2] - 0.5 * (fZ[ipl] + fZ[ipl + 1]); if (special_case) { if (!fFullPhi) - snxt = TGeoTubeSeg::DistFromInsideS(point_new, dir, - TMath::Min(fRmin[ipl],fRmin[ipl+1]), TMath::Max(fRmax[ipl],fRmax[ipl+1]), - dz, fC1,fS1,fC2,fS2,fCm,fSm,fCdphi); + snxt = TGeoTubeSeg::DistFromInsideS(point_new, dir, TMath::Min(fRmin[ipl], fRmin[ipl + 1]), + TMath::Max(fRmax[ipl], fRmax[ipl + 1]), dz, fC1, fS1, fC2, fS2, fCm, fSm, + fCdphi); else - snxt = TGeoTube::DistFromInsideS(point_new, dir, - TMath::Min(fRmin[ipl],fRmin[ipl+1]), TMath::Max(fRmax[ipl],fRmax[ipl+1]),dz); + snxt = TGeoTube::DistFromInsideS(point_new, dir, TMath::Min(fRmin[ipl], fRmin[ipl + 1]), + TMath::Max(fRmax[ipl], fRmax[ipl + 1]), dz); return snxt; } if (intub) { if (!fFullPhi) - snxt = TGeoTubeSeg::DistFromInsideS(point_new, dir, fRmin[ipl], fRmax[ipl],dz, fC1,fS1,fC2,fS2,fCm,fSm,fCdphi); + snxt = TGeoTubeSeg::DistFromInsideS(point_new, dir, fRmin[ipl], fRmax[ipl], dz, fC1, fS1, fC2, fS2, fCm, fSm, + fCdphi); else - snxt = TGeoTube::DistFromInsideS(point_new, dir, fRmin[ipl], fRmax[ipl],dz); + snxt = TGeoTube::DistFromInsideS(point_new, dir, fRmin[ipl], fRmax[ipl], dz); } else { if (!fFullPhi) - snxt = TGeoConeSeg::DistFromInsideS(point_new,dir,dz,fRmin[ipl],fRmax[ipl],fRmin[ipl+1],fRmax[ipl+1],fC1,fS1,fC2,fS2,fCm,fSm,fCdphi); + snxt = TGeoConeSeg::DistFromInsideS(point_new, dir, dz, fRmin[ipl], fRmax[ipl], fRmin[ipl + 1], fRmax[ipl + 1], + fC1, fS1, fC2, fS2, fCm, fSm, fCdphi); else - snxt=TGeoCone::DistFromInsideS(point_new,dir,dz,fRmin[ipl],fRmax[ipl],fRmin[ipl+1], fRmax[ipl+1]); + snxt = TGeoCone::DistFromInsideS(point_new, dir, dz, fRmin[ipl], fRmax[ipl], fRmin[ipl + 1], fRmax[ipl + 1]); } - for (Int_t i=0; i<3; i++) point_new[i]=point[i]+(snxt+1E-6)*dir[i]; - if (!Contains(&point_new[0])) return snxt; + for (Int_t i = 0; i < 3; i++) + point_new[i] = point[i] + (snxt + 1E-6) * dir[i]; + if (!Contains(&point_new[0])) + return snxt; snxt += DistFromInside(&point_new[0], dir, 3) + 1E-6; return snxt; @@ -527,84 +578,102 @@ Double_t TGeoPcon::DistFromInside(const Double_t *point, const Double_t *dir, In Double_t TGeoPcon::DistToSegZ(const Double_t *point, const Double_t *dir, Int_t &iz) const { - Double_t zmin=fZ[iz]; - Double_t zmax=fZ[iz+1]; - if (TGeoShape::IsSameWithinTolerance(zmin,zmax)) { - if (TGeoShape::IsSameWithinTolerance(dir[2],0)) return TGeoShape::Big(); - Int_t istep=(dir[2]>0)?1:-1; - iz+=istep; - if (iz<0 || iz>(fNz-2)) return TGeoShape::Big(); - return DistToSegZ(point,dir,iz); + Double_t zmin = fZ[iz]; + Double_t zmax = fZ[iz + 1]; + if (TGeoShape::IsSameWithinTolerance(zmin, zmax)) { + if (TGeoShape::IsSameWithinTolerance(dir[2], 0)) + return TGeoShape::Big(); + Int_t istep = (dir[2] > 0) ? 1 : -1; + iz += istep; + if (iz < 0 || iz > (fNz - 2)) + return TGeoShape::Big(); + return DistToSegZ(point, dir, iz); } - Double_t dz=0.5*(zmax-zmin); + Double_t dz = 0.5 * (zmax - zmin); Double_t local[3]; - memcpy(&local[0], point, 3*sizeof(Double_t)); - local[2]=point[2]-0.5*(zmin+zmax); + memcpy(&local[0], point, 3 * sizeof(Double_t)); + local[2] = point[2] - 0.5 * (zmin + zmax); Double_t snxt; - Double_t rmin1=fRmin[iz]; - Double_t rmax1=fRmax[iz]; - Double_t rmin2=fRmin[iz+1]; - Double_t rmax2=fRmax[iz+1]; - - if (TGeoShape::IsSameWithinTolerance(rmin1,rmin2) && TGeoShape::IsSameWithinTolerance(rmax1,rmax2)) { - if (fFullPhi) snxt=TGeoTube::DistFromOutsideS(local, dir, rmin1, rmax1, dz); - else snxt=TGeoTubeSeg::DistFromOutsideS(local,dir,rmin1,rmax1,dz,fC1,fS1,fC2,fS2,fCm,fSm,fCdphi); + Double_t rmin1 = fRmin[iz]; + Double_t rmax1 = fRmax[iz]; + Double_t rmin2 = fRmin[iz + 1]; + Double_t rmax2 = fRmax[iz + 1]; + + if (TGeoShape::IsSameWithinTolerance(rmin1, rmin2) && TGeoShape::IsSameWithinTolerance(rmax1, rmax2)) { + if (fFullPhi) + snxt = TGeoTube::DistFromOutsideS(local, dir, rmin1, rmax1, dz); + else + snxt = TGeoTubeSeg::DistFromOutsideS(local, dir, rmin1, rmax1, dz, fC1, fS1, fC2, fS2, fCm, fSm, fCdphi); } else { - if (fFullPhi) snxt=TGeoCone::DistFromOutsideS(local,dir,dz,rmin1, rmax1,rmin2,rmax2); - else snxt=TGeoConeSeg::DistFromOutsideS(local,dir,dz,rmin1,rmax1,rmin2,rmax2,fC1,fS1,fC2,fS2,fCm,fSm,fCdphi); + if (fFullPhi) + snxt = TGeoCone::DistFromOutsideS(local, dir, dz, rmin1, rmax1, rmin2, rmax2); + else + snxt = TGeoConeSeg::DistFromOutsideS(local, dir, dz, rmin1, rmax1, rmin2, rmax2, fC1, fS1, fC2, fS2, fCm, fSm, + fCdphi); } - if (snxt<1E20) return snxt; + if (snxt < 1E20) + return snxt; // check next segment - if (TGeoShape::IsSameWithinTolerance(dir[2],0)) return TGeoShape::Big(); - Int_t istep=(dir[2]>0)?1:-1; - iz+=istep; - if (iz<0 || iz>(fNz-2)) return TGeoShape::Big(); - return DistToSegZ(point,dir,iz); + if (TGeoShape::IsSameWithinTolerance(dir[2], 0)) + return TGeoShape::Big(); + Int_t istep = (dir[2] > 0) ? 1 : -1; + iz += istep; + if (iz < 0 || iz > (fNz - 2)) + return TGeoShape::Big(); + return DistToSegZ(point, dir, iz); } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the tube -Double_t TGeoPcon::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoPcon::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if ((iact<3) && safe) { + if ((iact < 3) && safe) { *safe = Safety(point, kFALSE); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); - if (iact==0) return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); } // check if ray intersect outscribed cylinder - if ((point[2]fZ[fNz-1]) && (dir[2]>=0)) return TGeoShape::Big(); -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); - - Double_t r2 = point[0]*point[0]+point[1]*point[1]; - Double_t radmax=0; - radmax=fRmax[TMath::LocMax(fNz, fRmax)]; - if (r2>(radmax*radmax)) { - Double_t rpr=-point[0]*dir[0]-point[1]*dir[1]; - Double_t nxy=dir[0]*dir[0]+dir[1]*dir[1]; - if (rpr fZ[fNz - 1]) && (dir[2] >= 0)) + return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); + + Double_t r2 = point[0] * point[0] + point[1] * point[1]; + Double_t radmax = 0; + radmax = fRmax[TMath::LocMax(fNz, fRmax)]; + if (r2 > (radmax * radmax)) { + Double_t rpr = -point[0] * dir[0] - point[1] * dir[1]; + Double_t nxy = dir[0] * dir[0] + dir[1] * dir[1]; + if (rpr < TMath::Sqrt((r2 - radmax * radmax) * nxy)) + return TGeoShape::Big(); } // find in which Z segment we are Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]); Int_t ifirst = ipl; - if (ifirst<0) { + if (ifirst < 0) { ifirst = 0; - } else if (ifirst>=(fNz-1)) { - ifirst = fNz-2; + } else if (ifirst >= (fNz - 1)) { + ifirst = fNz - 2; } // find if point is in the phi gap - Double_t phi=0; + Double_t phi = 0; if (!fFullPhi) { phi = TMath::ATan2(point[1], point[0]); - if (phi<0) phi+=2.*TMath::Pi(); + if (phi < 0) + phi += 2. * TMath::Pi(); } // compute distance to boundary - return DistToSegZ(point,dir,ifirst); + return DistToSegZ(point, dir, ifirst); } //////////////////////////////////////////////////////////////////////////////// @@ -614,19 +683,20 @@ Double_t TGeoPcon::DistFromOutside(const Double_t *point, const Double_t *dir, I void TGeoPcon::DefineSection(Int_t snum, Double_t z, Double_t rmin, Double_t rmax) { - if ((snum<0) || (snum>=fNz)) return; - fZ[snum] = z; + if ((snum < 0) || (snum >= fNz)) + return; + fZ[snum] = z; fRmin[snum] = rmin; fRmax[snum] = rmax; - if (rmin>rmax) + if (rmin > rmax) Warning("DefineSection", "Shape %s: invalid rmin=%g rmax=%g", GetName(), rmin, rmax); - if (snum==(fNz-1)) { + if (snum == (fNz - 1)) { // Reorder sections in increasing Z order if (fZ[0] > fZ[snum]) { Int_t iz = 0; - Int_t izi = fNz-1; + Int_t izi = fNz - 1; Double_t temp; - while (izMakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoPcon(-step / 2, step, fNz); + for (is = 0; is < fNz; is++) + ((TGeoPcon *)shape)->DefineSection(is, fZ[is], fRmin[is], fRmax[is]); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Z division + // find start plane + for (ipl = 0; ipl < fNz - 1; ipl++) { + if (start < fZ[ipl]) + continue; + else { + if ((start + ndiv * step) > fZ[ipl + 1]) + continue; + } + isect = ipl; + zmin = fZ[isect]; + zmax = fZ[isect + 1]; + break; + } + if (isect < 0) { + Error("Divide", "Shape %s: cannot divide pcon on Z if divided region is not between 2 planes", GetName()); return 0; - case 2: //--- Phi division - finder = new TGeoPatternCylPhi(voldiv, ndiv, start, start+ndiv*step); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoPcon(-step/2, step, fNz); - for (is=0; isDefineSection(is, fZ[is], fRmin[is], fRmax[is]); + } + finder = new TGeoPatternZ(voldiv, ndiv, start, start + ndiv * step); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + opt = "Z"; + for (id = 0; id < ndiv; id++) { + Double_t z1 = start + id * step; + Double_t z2 = start + (id + 1) * step; + Double_t rmin1 = (fRmin[isect] * (zmax - z1) - fRmin[isect + 1] * (zmin - z1)) / (zmax - zmin); + Double_t rmax1 = (fRmax[isect] * (zmax - z1) - fRmax[isect + 1] * (zmin - z1)) / (zmax - zmin); + Double_t rmin2 = (fRmin[isect] * (zmax - z2) - fRmin[isect + 1] * (zmin - z2)) / (zmax - zmin); + Double_t rmax2 = (fRmax[isect] * (zmax - z2) - fRmax[isect + 1] * (zmin - z2)) / (zmax - zmin); + Bool_t is_tube = (TGeoShape::IsSameWithinTolerance(fRmin[isect], fRmin[isect + 1]) && + TGeoShape::IsSameWithinTolerance(fRmax[isect], fRmax[isect + 1])) + ? kTRUE + : kFALSE; + Bool_t is_seg = (fDphi < 360) ? kTRUE : kFALSE; + if (is_seg) { + if (is_tube) + shape = new TGeoTubeSeg(fRmin[isect], fRmax[isect], step / 2, fPhi1, fPhi1 + fDphi); + else + shape = new TGeoConeSeg(step / 2, rmin1, rmax1, rmin2, rmax2, fPhi1, fPhi1 + fDphi); + } else { + if (is_tube) + shape = new TGeoTube(fRmin[isect], fRmax[isect], step / 2); + else + shape = new TGeoCone(step / 2, rmin1, rmax1, rmin2, rmax2); + } vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Z division - // find start plane - for (ipl=0; iplfZ[ipl+1]) continue; - } - isect = ipl; - zmin = fZ[isect]; - zmax= fZ[isect+1]; - break; - } - if (isect<0) { - Error("Divide", "Shape %s: cannot divide pcon on Z if divided region is not between 2 planes", GetName()); - return 0; - } - finder = new TGeoPatternZ(voldiv, ndiv, start, start+ndiv*step); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - opt = "Z"; - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - voldiv->AddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "Shape %s: Wrong axis %d for division",GetName(), iaxis); - return 0; + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "Shape %s: Wrong axis %d for division", GetName(), iaxis); return 0; } } @@ -747,14 +824,10 @@ TGeoVolume *TGeoPcon::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi const char *TGeoPcon::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "R"; - case 2: - return "PHI"; - case 3: - return "Z"; - default: - return "UNDEFINED"; + case 1: return "R"; + case 2: return "PHI"; + case 3: return "Z"; + default: return "UNDEFINED"; } } @@ -767,16 +840,16 @@ Double_t TGeoPcon::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 2: - xlo = fPhi1; - xhi = fPhi1 + fDphi; - dx = fDphi; - return dx; - case 3: - xlo = fZ[0]; - xhi = fZ[fNz-1]; - dx = xhi-xlo; - return dx; + case 2: + xlo = fPhi1; + xhi = fPhi1 + fDphi; + dx = fDphi; + return dx; + case 3: + xlo = fZ[0]; + xhi = fZ[fNz - 1]; + dx = xhi - xlo; + return dx; } return dx; } @@ -787,21 +860,23 @@ Double_t TGeoPcon::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const void TGeoPcon::GetBoundingCylinder(Double_t *param) const { - param[0] = fRmin[0]; // Rmin - param[1] = fRmax[0]; // Rmax - for (Int_t i=1; i param[1]) param[1] = fRmax[i]; + param[0] = fRmin[0]; // Rmin + param[1] = fRmax[0]; // Rmax + for (Int_t i = 1; i < fNz; i++) { + if (fRmin[i] < param[0]) + param[0] = fRmin[i]; + if (fRmax[i] > param[1]) + param[1] = fRmax[i]; } param[0] *= param[0]; param[1] *= param[1]; - if (TGeoShape::IsSameWithinTolerance(fDphi,360.)) { + if (TGeoShape::IsSameWithinTolerance(fDphi, 360.)) { param[2] = 0.; param[3] = 360.; return; } - param[2] = (fPhi1<0)?(fPhi1+360.):fPhi1; // Phi1 - param[3] = param[2]+fDphi; // Phi2 + param[2] = (fPhi1 < 0) ? (fPhi1 + 360.) : fPhi1; // Phi1 + param[3] = param[2] + fDphi; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -809,8 +884,8 @@ void TGeoPcon::GetBoundingCylinder(Double_t *param) const Double_t TGeoPcon::GetRmin(Int_t ipl) const { - if (ipl<0 || ipl>(fNz-1)) { - Error("GetRmin","ipl=%i out of range (0,%i) in shape %s",ipl,fNz-1,GetName()); + if (ipl < 0 || ipl > (fNz - 1)) { + Error("GetRmin", "ipl=%i out of range (0,%i) in shape %s", ipl, fNz - 1, GetName()); return 0.; } return fRmin[ipl]; @@ -821,8 +896,8 @@ Double_t TGeoPcon::GetRmin(Int_t ipl) const Double_t TGeoPcon::GetRmax(Int_t ipl) const { - if (ipl<0 || ipl>(fNz-1)) { - Error("GetRmax","ipl=%i out of range (0,%i) in shape %s",ipl,fNz-1,GetName()); + if (ipl < 0 || ipl > (fNz - 1)) { + Error("GetRmax", "ipl=%i out of range (0,%i) in shape %s", ipl, fNz - 1, GetName()); return 0.; } return fRmax[ipl]; @@ -833,8 +908,8 @@ Double_t TGeoPcon::GetRmax(Int_t ipl) const Double_t TGeoPcon::GetZ(Int_t ipl) const { - if (ipl<0 || ipl>(fNz-1)) { - Error("GetZ","ipl=%i out of range (0,%i) in shape %s",ipl,fNz-1,GetName()); + if (ipl < 0 || ipl > (fNz - 1)) { + Error("GetZ", "ipl=%i out of range (0,%i) in shape %s", ipl, fNz - 1, GetName()); return 0.; } return fZ[ipl]; @@ -849,7 +924,7 @@ void TGeoPcon::InspectShape() const printf(" Nz = %i\n", fNz); printf(" phi1 = %11.5f\n", fPhi1); printf(" dphi = %11.5f\n", fDphi); - for (Int_t ipl=0; iplfPnts); SetSegsAndPols(*buff); } @@ -887,171 +962,172 @@ void TGeoPcon::SetSegsAndPols(TBuffer3D &buff) const } Int_t i, j; - const Int_t n = gGeoManager->GetNsegments()+1; + const Int_t n = gGeoManager->GetNsegments() + 1; Int_t nz = GetNz(); - if (nz < 2) return; - Int_t nbPnts = nz*2*n; - if (nbPnts <= 0) return; + if (nz < 2) + return; + Int_t nbPnts = nz * 2 * n; + if (nbPnts <= 0) + return; Double_t dphi = GetDphi(); - Bool_t specialCase = TGeoShape::IsSameWithinTolerance(dphi,360); + Bool_t specialCase = TGeoShape::IsSameWithinTolerance(dphi, 360); Int_t c = GetBasicColor(); Int_t indx = 0, indx2, k; - //inside & outside circles, number of segments: 2*nz*(n-1) + // inside & outside circles, number of segments: 2*nz*(n-1) // special case number of segments: 2*nz*n - for (i = 0; i < nz*2; i++) { - indx2 = i*n; + for (i = 0; i < nz * 2; i++) { + indx2 = i * n; for (j = 1; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2+j-1; - buff.fSegs[indx++] = indx2+j; + buff.fSegs[indx++] = indx2 + j - 1; + buff.fSegs[indx++] = indx2 + j; } if (specialCase) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2+j-1; + buff.fSegs[indx++] = indx2 + j - 1; buff.fSegs[indx++] = indx2; } } - //bottom & top lines, number of segments: 2*n + // bottom & top lines, number of segments: 2*n for (i = 0; i < 2; i++) { - indx2 = i*(nz-1)*2*n; + indx2 = i * (nz - 1) * 2 * n; for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2+j; - buff.fSegs[indx++] = indx2+n+j; + buff.fSegs[indx++] = indx2 + j; + buff.fSegs[indx++] = indx2 + n + j; } } - //inside & outside cylinders, number of segments: 2*(nz-1)*n - for (i = 0; i < (nz-1); i++) { - //inside cylinder - indx2 = i*n*2; + // inside & outside cylinders, number of segments: 2*(nz-1)*n + for (i = 0; i < (nz - 1); i++) { + // inside cylinder + indx2 = i * n * 2; for (j = 0; j < n; j++) { - buff.fSegs[indx++] = c+2; - buff.fSegs[indx++] = indx2+j; - buff.fSegs[indx++] = indx2+n*2+j; + buff.fSegs[indx++] = c + 2; + buff.fSegs[indx++] = indx2 + j; + buff.fSegs[indx++] = indx2 + n * 2 + j; } - //outside cylinder - indx2 = i*n*2+n; + // outside cylinder + indx2 = i * n * 2 + n; for (j = 0; j < n; j++) { - buff.fSegs[indx++] = c+3; - buff.fSegs[indx++] = indx2+j; - buff.fSegs[indx++] = indx2+n*2+j; + buff.fSegs[indx++] = c + 3; + buff.fSegs[indx++] = indx2 + j; + buff.fSegs[indx++] = indx2 + n * 2 + j; } } - //left & right sections, number of segments: 2*(nz-2) + // left & right sections, number of segments: 2*(nz-2) // special case number of segments: 0 if (!specialCase) { - for (i = 1; i < (nz-1); i++) { + for (i = 1; i < (nz - 1); i++) { for (j = 0; j < 2; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = 2*i * n + j*(n-1); - buff.fSegs[indx++] = (2*i+1) * n + j*(n-1); + buff.fSegs[indx++] = 2 * i * n + j * (n - 1); + buff.fSegs[indx++] = (2 * i + 1) * n + j * (n - 1); } } } - Int_t m = n - 1 + (specialCase ? 1 : 0); + Int_t m = n - 1 + (specialCase ? 1 : 0); indx = 0; - //bottom & top, number of polygons: 2*(n-1) + // bottom & top, number of polygons: 2*(n-1) // special case number of polygons: 2*n - for (j = 0; j < n-1; j++) { - buff.fPols[indx++] = c+3; + for (j = 0; j < n - 1; j++) { + buff.fPols[indx++] = c + 3; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*nz*m+j; - buff.fPols[indx++] = m+j; - buff.fPols[indx++] = 2*nz*m+j+1; + buff.fPols[indx++] = 2 * nz * m + j; + buff.fPols[indx++] = m + j; + buff.fPols[indx++] = 2 * nz * m + j + 1; buff.fPols[indx++] = j; } - for (j = 0; j < n-1; j++) { - buff.fPols[indx++] = c+3; + for (j = 0; j < n - 1; j++) { + buff.fPols[indx++] = c + 3; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*nz*m+n+j; - buff.fPols[indx++] = (nz*2-2)*m+j; - buff.fPols[indx++] = 2*nz*m+n+j+1; - buff.fPols[indx++] = (nz*2-2)*m+m+j; + buff.fPols[indx++] = 2 * nz * m + n + j; + buff.fPols[indx++] = (nz * 2 - 2) * m + j; + buff.fPols[indx++] = 2 * nz * m + n + j + 1; + buff.fPols[indx++] = (nz * 2 - 2) * m + m + j; } if (specialCase) { - buff.fPols[indx++] = c+3; + buff.fPols[indx++] = c + 3; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*nz*m+j; - buff.fPols[indx++] = m+j; - buff.fPols[indx++] = 2*nz*m; + buff.fPols[indx++] = 2 * nz * m + j; + buff.fPols[indx++] = m + j; + buff.fPols[indx++] = 2 * nz * m; buff.fPols[indx++] = j; - buff.fPols[indx++] = c+3; + buff.fPols[indx++] = c + 3; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*nz*m+n+j; - buff.fPols[indx++] = (nz*2-2)*m+m+j; - buff.fPols[indx++] = 2*nz*m+n; - buff.fPols[indx++] = (nz*2-2)*m+j; + buff.fPols[indx++] = 2 * nz * m + n + j; + buff.fPols[indx++] = (nz * 2 - 2) * m + m + j; + buff.fPols[indx++] = 2 * nz * m + n; + buff.fPols[indx++] = (nz * 2 - 2) * m + j; } - //inside & outside, number of polygons: (nz-1)*2*(n-1) - for (k = 0; k < (nz-1); k++) { - for (j = 0; j < n-1; j++) { + // inside & outside, number of polygons: (nz-1)*2*(n-1) + for (k = 0; k < (nz - 1); k++) { + for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*k*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+2)*n+j+1; - buff.fPols[indx++] = (2*k+2)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+2)*n+j; + buff.fPols[indx++] = 2 * k * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 2) * n + j + 1; + buff.fPols[indx++] = (2 * k + 2) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 2) * n + j; } - for (j = 0; j < n-1; j++) { - buff.fPols[indx++] = c+1; + for (j = 0; j < n - 1; j++) { + buff.fPols[indx++] = c + 1; buff.fPols[indx++] = 4; - buff.fPols[indx++] = (2*k+1)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+3)*n+j; - buff.fPols[indx++] = (2*k+3)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+3)*n+j+1; + buff.fPols[indx++] = (2 * k + 1) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 3) * n + j; + buff.fPols[indx++] = (2 * k + 3) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 3) * n + j + 1; } if (specialCase) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 2*k*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+2)*n; - buff.fPols[indx++] = (2*k+2)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+2)*n+j; + buff.fPols[indx++] = 2 * k * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 2) * n; + buff.fPols[indx++] = (2 * k + 2) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 2) * n + j; - buff.fPols[indx++] = c+1; + buff.fPols[indx++] = c + 1; buff.fPols[indx++] = 4; - buff.fPols[indx++] = (2*k+1)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+3)*n+j; - buff.fPols[indx++] = (2*k+3)*m+j; - buff.fPols[indx++] = nz*2*m+(2*k+3)*n; + buff.fPols[indx++] = (2 * k + 1) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 3) * n + j; + buff.fPols[indx++] = (2 * k + 3) * m + j; + buff.fPols[indx++] = nz * 2 * m + (2 * k + 3) * n; } } - //left & right sections, number of polygons: 2*(nz-1) + // left & right sections, number of polygons: 2*(nz-1) // special case number of polygons: 0 if (!specialCase) { - indx2 = nz*2*(n-1); - for (k = 0; k < (nz-1); k++) { - buff.fPols[indx++] = c+2; + indx2 = nz * 2 * (n - 1); + for (k = 0; k < (nz - 1); k++) { + buff.fPols[indx++] = c + 2; buff.fPols[indx++] = 4; - buff.fPols[indx++] = k==0 ? indx2 : indx2+2*nz*n+2*(k-1); - buff.fPols[indx++] = indx2+2*(k+1)*n; - buff.fPols[indx++] = indx2+2*nz*n+2*k; - buff.fPols[indx++] = indx2+(2*k+3)*n; + buff.fPols[indx++] = k == 0 ? indx2 : indx2 + 2 * nz * n + 2 * (k - 1); + buff.fPols[indx++] = indx2 + 2 * (k + 1) * n; + buff.fPols[indx++] = indx2 + 2 * nz * n + 2 * k; + buff.fPols[indx++] = indx2 + (2 * k + 3) * n; - buff.fPols[indx++] = c+2; + buff.fPols[indx++] = c + 2; buff.fPols[indx++] = 4; - buff.fPols[indx++] = k==0 ? indx2+n-1 : indx2+2*nz*n+2*(k-1)+1; - buff.fPols[indx++] = indx2+(2*k+3)*n+n-1; - buff.fPols[indx++] = indx2+2*nz*n+2*k+1; - buff.fPols[indx++] = indx2+2*(k+1)*n+n-1; + buff.fPols[indx++] = k == 0 ? indx2 + n - 1 : indx2 + 2 * nz * n + 2 * (k - 1) + 1; + buff.fPols[indx++] = indx2 + (2 * k + 3) * n + n - 1; + buff.fPols[indx++] = indx2 + 2 * nz * n + 2 * k + 1; + buff.fPols[indx++] = indx2 + 2 * (k + 1) * n + n - 1; } - buff.fPols[indx-8] = indx2+n; - buff.fPols[indx-2] = indx2+2*n-1; + buff.fPols[indx - 8] = indx2 + n; + buff.fPols[indx - 2] = indx2 + 2 * n - 1; } } - //////////////////////////////////////////////////////////////////////////////// /// Fill TBuffer3D structure for segments and polygons, when no inner surface exists @@ -1061,7 +1137,8 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const const Int_t nz = GetNz(); const Int_t nbPnts = nz * n + 2; - if ((nz < 2) || (nbPnts <= 0) || (n < 2)) return; + if ((nz < 2) || (nbPnts <= 0) || (n < 2)) + return; Int_t c = GetBasicColor(); @@ -1073,7 +1150,7 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const for (j = 1; j < n; j++) { buff.fSegs[indx++] = c; buff.fSegs[indx++] = indx2 + j - 1; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); } } @@ -1081,15 +1158,15 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const // bottom lines for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); buff.fSegs[indx++] = nbPnts - 2; } - indx2 = (nz-1) * n; + indx2 = (nz - 1) * n; // top lines for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); buff.fSegs[indx++] = nbPnts - 1; } @@ -1099,8 +1176,8 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const indx2 = i * n; for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); - buff.fSegs[indx++] = indx2 + n + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); + buff.fSegs[indx++] = indx2 + n + j % (n - 1); } } @@ -1108,7 +1185,7 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const // bottom cap indx1 = 0; // start of first z layer - indx2 = nz*(n-1); + indx2 = nz * (n - 1); for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 3; @@ -1118,8 +1195,8 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const } // top cap - indx1 = (nz-1)*(n-1); // start last z layer - indx2 = nz*(n-1) + n; + indx1 = (nz - 1) * (n - 1); // start last z layer + indx2 = nz * (n - 1) + n; for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 3; @@ -1130,14 +1207,14 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const // outside, number of polygons: (nz-1)*(n-1) for (Int_t k = 0; k < (nz - 1); k++) { - indx1 = k*(n-1); - indx2 = nz*(n-1) + n*2 + k*n; - for (j = 0; j < n-1; j++) { + indx1 = k * (n - 1); + indx2 = nz * (n - 1) + n * 2 + k * n; + for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; buff.fPols[indx++] = indx1 + j; buff.fPols[indx++] = indx2 + j; - buff.fPols[indx++] = indx1 + j + (n-1); + buff.fPols[indx++] = indx1 + j + (n - 1); buff.fPols[indx++] = indx2 + j + 1; } } @@ -1148,28 +1225,38 @@ void TGeoPcon::SetSegsAndPolsNoInside(TBuffer3D &buff) const Double_t TGeoPcon::SafetyToSegment(const Double_t *point, Int_t ipl, Bool_t in, Double_t safmin) const { - if (ipl<0 || ipl>fNz-2) return (safmin+1.); // error in input plane -// Get info about segment. - Double_t dz = 0.5*(fZ[ipl+1]-fZ[ipl]); - if (dz<1E-9) return 1E9; // radius-changing segment + if (ipl < 0 || ipl > fNz - 2) + return (safmin + 1.); // error in input plane + // Get info about segment. + Double_t dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); + if (dz < 1E-9) + return 1E9; // radius-changing segment Double_t ptnew[3]; - memcpy(ptnew, point, 3*sizeof(Double_t)); - ptnew[2] -= 0.5*(fZ[ipl]+fZ[ipl+1]); - Double_t safe = TMath::Abs(ptnew[2])-dz; - if (safe>safmin) return TGeoShape::Big(); // means: stop checking further segments + memcpy(ptnew, point, 3 * sizeof(Double_t)); + ptnew[2] -= 0.5 * (fZ[ipl] + fZ[ipl + 1]); + Double_t safe = TMath::Abs(ptnew[2]) - dz; + if (safe > safmin) + return TGeoShape::Big(); // means: stop checking further segments Double_t rmin1 = fRmin[ipl]; Double_t rmax1 = fRmax[ipl]; - Double_t rmin2 = fRmin[ipl+1]; - Double_t rmax2 = fRmax[ipl+1]; - Bool_t is_tube = (TGeoShape::IsSameWithinTolerance(rmin1,rmin2) && TGeoShape::IsSameWithinTolerance(rmax1,rmax2))?kTRUE:kFALSE; + Double_t rmin2 = fRmin[ipl + 1]; + Double_t rmax2 = fRmax[ipl + 1]; + Bool_t is_tube = (TGeoShape::IsSameWithinTolerance(rmin1, rmin2) && TGeoShape::IsSameWithinTolerance(rmax1, rmax2)) + ? kTRUE + : kFALSE; if (!fFullPhi) { - if (is_tube) safe = TGeoTubeSeg::SafetyS(ptnew,in,rmin1,rmax1, dz,fPhi1,fPhi1+fDphi,0); - else safe = TGeoConeSeg::SafetyS(ptnew,in,dz,rmin1,rmax1,rmin2,rmax2,fPhi1,fPhi1+fDphi,0); + if (is_tube) + safe = TGeoTubeSeg::SafetyS(ptnew, in, rmin1, rmax1, dz, fPhi1, fPhi1 + fDphi, 0); + else + safe = TGeoConeSeg::SafetyS(ptnew, in, dz, rmin1, rmax1, rmin2, rmax2, fPhi1, fPhi1 + fDphi, 0); } else { - if (is_tube) safe = TGeoTube::SafetyS(ptnew,in,rmin1,rmax1,dz,0); - else safe = TGeoCone::SafetyS(ptnew,in,dz,rmin1,rmax1,rmin2,rmax2,0); + if (is_tube) + safe = TGeoTube::SafetyS(ptnew, in, rmin1, rmax1, dz, 0); + else + safe = TGeoCone::SafetyS(ptnew, in, dz, rmin1, rmax1, rmin2, rmax2, 0); } - if (safe<0) safe=0; + if (safe < 0) + safe = 0; return safe; } @@ -1185,80 +1272,95 @@ Double_t TGeoPcon::Safety(const Double_t *point, Bool_t in) const Int_t ipl, iplane; if (in) { - //---> point is inside pcon + //---> point is inside pcon ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl==(fNz-1)) return 0; // point on last Z boundary - if (ipl<0) return 0; // point on first Z boundary - if (ipl>0 && TGeoShape::IsSameWithinTolerance(fZ[ipl-1],fZ[ipl]) && TGeoShape::IsSameWithinTolerance(point[2],fZ[ipl-1])) ipl--; - dz = 0.5*(fZ[ipl+1]-fZ[ipl]); - if (dz<1E-8) { + if (ipl == (fNz - 1)) + return 0; // point on last Z boundary + if (ipl < 0) + return 0; // point on first Z boundary + if (ipl > 0 && TGeoShape::IsSameWithinTolerance(fZ[ipl - 1], fZ[ipl]) && + TGeoShape::IsSameWithinTolerance(point[2], fZ[ipl - 1])) + ipl--; + dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); + if (dz < 1E-8) { // Point on a segment-changing plane - safmin = TMath::Min(point[2]-fZ[ipl-1],fZ[ipl+2]-point[2]); + safmin = TMath::Min(point[2] - fZ[ipl - 1], fZ[ipl + 2] - point[2]); saftmp = TGeoShape::Big(); - if (fDphi<360) saftmp = TGeoShape::SafetyPhi(point,in,fPhi1,fPhi1+fDphi); - if (saftmp0) safmin = TMath::Min(safmin, radius-fRmin[ipl]); - if (fRmin[ipl+1]>0) safmin = TMath::Min(safmin, radius-fRmin[ipl+1]); - safmin = TMath::Min(safmin, fRmax[ipl]-radius); - safmin = TMath::Min(safmin, fRmax[ipl+1]-radius); - if (safmin<0) safmin = 0; + if (fDphi < 360) + saftmp = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi1 + fDphi); + if (saftmp < safmin) + safmin = saftmp; + Double_t radius = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + if (fRmin[ipl] > 0) + safmin = TMath::Min(safmin, radius - fRmin[ipl]); + if (fRmin[ipl + 1] > 0) + safmin = TMath::Min(safmin, radius - fRmin[ipl + 1]); + safmin = TMath::Min(safmin, fRmax[ipl] - radius); + safmin = TMath::Min(safmin, fRmax[ipl + 1] - radius); + if (safmin < 0) + safmin = 0; return safmin; } // Check safety for current segment safmin = SafetyToSegment(point, ipl); - if (safmin>1E10) { + if (safmin > 1E10) { // something went wrong - point is not inside current segment return 0.; } - if (safmin<1E-6) return TMath::Abs(safmin); // point on radius-changing plane + if (safmin < 1E-6) + return TMath::Abs(safmin); // point on radius-changing plane // check increasing iplanes -/* - iplane = ipl+1; - saftmp = 0.; - while ((iplane=0) && saftmp<1E10) { - saftmp = TMath::Abs(SafetyToSegment(point,iplane,kFALSE,safmin)); - if (saftmp=0) && saftmp<1E10) { + saftmp = TMath::Abs(SafetyToSegment(point,iplane,kFALSE,safmin)); + if (saftmp point is outside pcon ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl<0) ipl=0; - else if (ipl==fNz-1) ipl=fNz-2; - dz = 0.5*(fZ[ipl+1]-fZ[ipl]); - if (dz<1E-8 && (ipl+2=0) && saftmp<1E10) { - saftmp = TMath::Abs(SafetyToSegment(point,iplane,kFALSE,safmin)); - if (saftmp= 0) && saftmp < 1E10) { + saftmp = TMath::Abs(SafetyToSegment(point, iplane, kFALSE, safmin)); + if (saftmp < safmin) + safmin = saftmp; iplane--; } return safmin; @@ -1269,13 +1371,14 @@ Double_t TGeoPcon::Safety(const Double_t *point, Bool_t in) const void TGeoPcon::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " phi1 = " << fPhi1 << ";" << std::endl; out << " dphi = " << fDphi << ";" << std::endl; out << " nz = " << fNz << ";" << std::endl; out << " auto " << GetPointerName() << " = new TGeoPcon(\"" << GetName() << "\", phi1, dphi, nz);" << std::endl; - for (Int_t i=0; i 2", GetName()); + fPhi1 = param[0]; + while (fPhi1 < 0) + fPhi1 += 360.; + fDphi = param[1]; + fNz = (Int_t)param[2]; + if (fNz < 2) { + Error("SetDimensions", "Pcon %s: Number of Z sections must be > 2", GetName()); return; } - if (fRmin) delete [] fRmin; - if (fRmax) delete [] fRmax; - if (fZ) delete [] fZ; - fRmin = new Double_t [fNz]; - fRmax = new Double_t [fNz]; - fZ = new Double_t [fNz]; - memset(fRmin, 0, fNz*sizeof(Double_t)); - memset(fRmax, 0, fNz*sizeof(Double_t)); - memset(fZ, 0, fNz*sizeof(Double_t)); - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) fFullPhi = kTRUE; + if (fRmin) + delete[] fRmin; + if (fRmax) + delete[] fRmax; + if (fZ) + delete[] fZ; + fRmin = new Double_t[fNz]; + fRmax = new Double_t[fNz]; + fZ = new Double_t[fNz]; + memset(fRmin, 0, fNz * sizeof(Double_t)); + memset(fRmax, 0, fNz * sizeof(Double_t)); + memset(fZ, 0, fNz * sizeof(Double_t)); + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) + fFullPhi = kTRUE; Double_t phi1 = fPhi1; - Double_t phi2 = phi1+fDphi; - Double_t phim = 0.5*(phi1+phi2); - fC1 = TMath::Cos(phi1*TMath::DegToRad()); - fS1 = TMath::Sin(phi1*TMath::DegToRad()); - fC2 = TMath::Cos(phi2*TMath::DegToRad()); - fS2 = TMath::Sin(phi2*TMath::DegToRad()); - fCm = TMath::Cos(phim*TMath::DegToRad()); - fSm = TMath::Sin(phim*TMath::DegToRad()); - fCdphi = TMath::Cos(0.5*fDphi*TMath::DegToRad()); - - for (Int_t i=0; iGetNsegments() + 1; - dphi = fDphi/(n-1); + dphi = fDphi / (n - 1); Int_t i, j; Int_t indx = 0; @@ -1339,13 +1447,13 @@ void TGeoPcon::SetPoints(Double_t *points) const for (i = 0; i < fNz; i++) { if (hasInside) for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin[i] * TMath::Cos(phi); points[indx++] = fRmin[i] * TMath::Sin(phi); points[indx++] = fZ[i]; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax[i] * TMath::Cos(phi); points[indx++] = fRmax[i] * TMath::Sin(phi); points[indx++] = fZ[i]; @@ -1358,7 +1466,7 @@ void TGeoPcon::SetPoints(Double_t *points) const points[indx++] = 0; points[indx++] = 0; - points[indx++] = fZ[GetNz()-1]; + points[indx++] = fZ[GetNz() - 1]; } } } @@ -1370,7 +1478,7 @@ void TGeoPcon::SetPoints(Float_t *points) const { Double_t phi, dphi; Int_t n = gGeoManager->GetNsegments() + 1; - dphi = fDphi/(n-1); + dphi = fDphi / (n - 1); Int_t i, j; Int_t indx = 0; @@ -1380,13 +1488,13 @@ void TGeoPcon::SetPoints(Float_t *points) const for (i = 0; i < fNz; i++) { if (hasInside) for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmin[i] * TMath::Cos(phi); points[indx++] = fRmin[i] * TMath::Sin(phi); points[indx++] = fZ[i]; } for (j = 0; j < n; j++) { - phi = (fPhi1+j*dphi)*TMath::DegToRad(); + phi = (fPhi1 + j * dphi) * TMath::DegToRad(); points[indx++] = fRmax[i] * TMath::Cos(phi); points[indx++] = fRmax[i] * TMath::Sin(phi); points[indx++] = fZ[i]; @@ -1399,7 +1507,7 @@ void TGeoPcon::SetPoints(Float_t *points) const points[indx++] = 0; points[indx++] = 0; - points[indx++] = fZ[GetNz()-1]; + points[indx++] = fZ[GetNz() - 1]; } } } @@ -1416,9 +1524,7 @@ Int_t TGeoPcon::GetNmeshVertices() const //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoPcon::Sizeof3D() const -{ -} +void TGeoPcon::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Returns true when pgon has internal surface @@ -1428,7 +1534,8 @@ Bool_t TGeoPcon::HasInsideSurface() const { // only when full 360 is used, internal part can be excluded Bool_t specialCase = TGeoShape::IsSameWithinTolerance(GetDphi(), 360); - if (!specialCase) return kTRUE; + if (!specialCase) + return kTRUE; for (Int_t i = 0; i < GetNz(); i++) if (fRmin[i] > 0.) @@ -1437,7 +1544,6 @@ Bool_t TGeoPcon::HasInsideSurface() const return kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Returns numbers of vertices, segments and polygons composing the shape mesh. @@ -1445,15 +1551,16 @@ void TGeoPcon::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { nvert = nsegs = npols = 0; - Int_t n = gGeoManager->GetNsegments()+1; + Int_t n = gGeoManager->GetNsegments() + 1; Int_t nz = GetNz(); - if (nz < 2) return; + if (nz < 2) + return; if (HasInsideSurface()) { - Bool_t specialCase = TGeoShape::IsSameWithinTolerance(GetDphi(),360); - nvert = nz*2*n; - nsegs = 4*(nz*n-1+(specialCase ? 1 : 0)); - npols = 2*(nz*n-1+(specialCase ? 1 : 0)); + Bool_t specialCase = TGeoShape::IsSameWithinTolerance(GetDphi(), 360); + nvert = nz * 2 * n; + nsegs = 4 * (nz * n - 1 + (specialCase ? 1 : 0)); + npols = 2 * (nz * n - 1 + (specialCase ? 1 : 0)); } else { nvert = nz * n + 2; nsegs = nz * (n - 1) + n * 2 + (nz - 1) * n; @@ -1464,7 +1571,7 @@ void TGeoPcon::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoPcon::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoPcon::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); @@ -1474,7 +1581,7 @@ const TBuffer3D & TGeoPcon::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co Int_t nbPnts, nbSegs, nbPols; GetMeshNumbers(nbPnts, nbSegs, nbPols); if (nbPnts > 0) { - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1500,20 +1607,21 @@ const TBuffer3D & TGeoPcon::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoPcon::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { - R__b.ReadClassBuffer(TGeoPcon::Class(),this); - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) fFullPhi = kTRUE; + R__b.ReadClassBuffer(TGeoPcon::Class(), this); + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) + fFullPhi = kTRUE; Double_t phi1 = fPhi1; - Double_t phi2 = phi1+fDphi; - Double_t phim = 0.5*(phi1+phi2); - fC1 = TMath::Cos(phi1*TMath::DegToRad()); - fS1 = TMath::Sin(phi1*TMath::DegToRad()); - fC2 = TMath::Cos(phi2*TMath::DegToRad()); - fS2 = TMath::Sin(phi2*TMath::DegToRad()); - fCm = TMath::Cos(phim*TMath::DegToRad()); - fSm = TMath::Sin(phim*TMath::DegToRad()); - fCdphi = TMath::Cos(0.5*fDphi*TMath::DegToRad()); + Double_t phi2 = phi1 + fDphi; + Double_t phim = 0.5 * (phi1 + phi2); + fC1 = TMath::Cos(phi1 * TMath::DegToRad()); + fS1 = TMath::Sin(phi1 * TMath::DegToRad()); + fC2 = TMath::Cos(phi2 * TMath::DegToRad()); + fS2 = TMath::Sin(phi2 * TMath::DegToRad()); + fCm = TMath::Cos(phim * TMath::DegToRad()); + fSm = TMath::Sin(phim * TMath::DegToRad()); + fCdphi = TMath::Cos(0.5 * fDphi * TMath::DegToRad()); } else { - R__b.WriteClassBuffer(TGeoPcon::Class(),this); + R__b.WriteClassBuffer(TGeoPcon::Class(), this); } } @@ -1524,7 +1632,8 @@ void TGeoPcon::Streamer(TBuffer &R__b) void TGeoPcon::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i @@ -69,13 +68,10 @@ polygons, between `phi1` and `phi1+dphi.` ClassImp(TGeoPgon); - //////////////////////////////////////////////////////////////////////////////// - /// Constructor. +//////////////////////////////////////////////////////////////////////////////// +/// Constructor. - TGeoPgon::ThreadData_t::ThreadData_t() - : fIntBuffer(0), fDblBuffer(0) -{ -} +TGeoPgon::ThreadData_t::ThreadData_t() : fIntBuffer(0), fDblBuffer(0) {} //////////////////////////////////////////////////////////////////////////////// /// Destructor. @@ -113,7 +109,8 @@ void TGeoPgon::ClearThreadData() const void TGeoPgon::CreateThreadData(Int_t nthreads) { - if (fThreadSize) ClearThreadData(); + if (fThreadSize) + ClearThreadData(); std::lock_guard guard(fMutex); fThreadData.resize(nthreads); fThreadSize = nthreads; @@ -199,7 +196,8 @@ Double_t TGeoPgon::Capacity() const Double_t tphi2 = TMath::Tan(0.5 * dphi * TMath::DegToRad()); for (ipl = 0; ipl < fNz - 1; ipl++) { dz = fZ[ipl + 1] - fZ[ipl]; - if (dz < TGeoShape::Tolerance()) continue; + if (dz < TGeoShape::Tolerance()) + continue; rmin1 = fRmin[ipl]; rmax1 = fRmax[ipl]; rmin2 = fRmin[ipl + 1]; @@ -258,17 +256,25 @@ void TGeoPgon::ComputeBBox() Double_t ymax = yc[TMath::LocMax(4, &yc[0])]; Double_t ddp = -phi1; - if (ddp < 0) ddp += 360; - if (ddp <= fDphi) xmax = rmax; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + xmax = rmax; ddp = 90 - phi1; - if (ddp < 0) ddp += 360; - if (ddp <= fDphi) ymax = rmax; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + ymax = rmax; ddp = 180 - phi1; - if (ddp < 0) ddp += 360; - if (ddp <= fDphi) xmin = -rmax; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + xmin = -rmax; ddp = 270 - phi1; - if (ddp < 0) ddp += 360; - if (ddp <= fDphi) ymin = -rmax; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + ymin = -rmax; fOrigin[0] = 0.5 * (xmax + xmin); fOrigin[1] = 0.5 * (ymax + ymin); fOrigin[2] = 0.5 * (zmax + zmin); @@ -289,7 +295,8 @@ void TGeoPgon::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t is_seg = (fDphi < 360) ? kTRUE : kFALSE; if (is_seg) { phi1 = fPhi1; - if (phi1 < 0) phi1 += 360; + if (phi1 < 0) + phi1 += 360; phi2 = phi1 + fDphi; phi1 *= TMath::DegToRad(); phi2 *= TMath::DegToRad(); @@ -310,12 +317,14 @@ void TGeoPgon::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ return; } Int_t iplclose = ipl; - if ((fZ[ipl + 1] - point[2]) < (point[2] - fZ[ipl])) iplclose++; + if ((fZ[ipl + 1] - point[2]) < (point[2] - fZ[ipl])) + iplclose++; dz = TMath::Abs(fZ[iplclose] - point[2]); Double_t divphi = fDphi / fNedges; Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi += 360.; + while (phi < fPhi1) + phi += 360.; Double_t ddp = phi - fPhi1; Int_t ipsec = Int_t(ddp / divphi); Double_t ph0 = (fPhi1 + divphi * (ipsec + 0.5)) * TMath::DegToRad(); @@ -378,14 +387,18 @@ void TGeoPgon::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoPgon::Contains(const Double_t *point) const { - if (point[2] < fZ[0]) return kFALSE; - if (point[2] > fZ[fNz - 1]) return kFALSE; + if (point[2] < fZ[0]) + return kFALSE; + if (point[2] > fZ[fNz - 1]) + return kFALSE; Double_t divphi = fDphi / fNedges; // now check phi Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi += 360.0; + while (phi < fPhi1) + phi += 360.0; Double_t ddp = phi - fPhi1; - if (ddp > fDphi) return kFALSE; + if (ddp > fDphi) + return kFALSE; // now find phi division Int_t ipsec = TMath::Min(Int_t(ddp / divphi), fNedges - 1); Double_t ph0 = (fPhi1 + divphi * (ipsec + 0.5)) * TMath::DegToRad(); @@ -394,8 +407,10 @@ Bool_t TGeoPgon::Contains(const Double_t *point) const // find in which Z section the point is in Int_t iz = TMath::BinarySearch(fNz, fZ, point[2]); if (iz == fNz - 1) { - if (r < fRmin[iz]) return kFALSE; - if (r > fRmax[iz]) return kFALSE; + if (r < fRmin[iz]) + return kFALSE; + if (r > fRmax[iz]) + return kFALSE; return kTRUE; } Double_t dz = fZ[iz + 1] - fZ[iz]; @@ -404,17 +419,21 @@ Bool_t TGeoPgon::Contains(const Double_t *point) const // we are at a radius-changing plane rmin = TMath::Min(fRmin[iz], fRmin[iz + 1]); rmax = TMath::Max(fRmax[iz], fRmax[iz + 1]); - if (r < rmin) return kFALSE; - if (r > rmax) return kFALSE; + if (r < rmin) + return kFALSE; + if (r > rmax) + return kFALSE; return kTRUE; } // now compute rmin and rmax and test the value of r Double_t dzrat = (point[2] - fZ[iz]) / dz; rmin = fRmin[iz] + dzrat * (fRmin[iz + 1] - fRmin[iz]); // is the point inside the 'hole' at the center of the volume ? - if (r < rmin) return kFALSE; + if (r < rmin) + return kFALSE; rmax = fRmax[iz] + dzrat * (fRmax[iz + 1] - fRmax[iz]); - if (r > rmax) return kFALSE; + if (r > rmax) + return kFALSE; return kTRUE; } @@ -423,28 +442,33 @@ Bool_t TGeoPgon::Contains(const Double_t *point) const /// compute distance from inside point to surface of the polygone /// first find out in which Z section the point is in -Double_t TGeoPgon::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, - Double_t *safe) const +Double_t +TGeoPgon::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact == 0) return TGeoShape::Big(); - if (iact == 1 && step < *safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // find current Z section Int_t ipl, ipsec; ipl = TMath::BinarySearch(fNz, fZ, point[2]); if (ipl == fNz - 1) { - if (dir[2] >= 0) return 0.; + if (dir[2] >= 0) + return 0.; ipl--; } if (ipl < 0) { // point out - if (dir[2] <= 0) return 0.; + if (dir[2] <= 0) + return 0.; ipl++; } Double_t stepmax = step; - if (!fThreadSize) ((TGeoPgon *)this)->CreateThreadData(1); + if (!fThreadSize) + ((TGeoPgon *)this)->CreateThreadData(1); ThreadData_t &td = GetThreadData(); Double_t *sph = td.fDblBuffer; Int_t *iph = td.fIntBuffer; @@ -498,12 +522,16 @@ Double_t TGeoPgon::DistFromInside(const Double_t *point, const Double_t *dir, In Double_t rproj = point[0] * cphi + point[1] * sphi; if (dir[2] > 0) { ipl = ipln + 1; - if (rproj > fRmin[ipln] && rproj < fRmin[ipln + 1]) return 0.0; - if (rproj < fRmax[ipln] && rproj > fRmax[ipln + 1]) return 0.0; + if (rproj > fRmin[ipln] && rproj < fRmin[ipln + 1]) + return 0.0; + if (rproj < fRmax[ipln] && rproj > fRmax[ipln + 1]) + return 0.0; } else { ipl = ipln - 1; - if (rproj < fRmin[ipln] && rproj > fRmin[ipln + 1]) return 0.0; - if (rproj > fRmax[ipln] && rproj < fRmax[ipln + 1]) return 0.0; + if (rproj < fRmin[ipln] && rproj > fRmin[ipln + 1]) + return 0.0; + if (rproj > fRmax[ipln] && rproj < fRmax[ipln + 1]) + return 0.0; } } @@ -511,12 +539,16 @@ Double_t TGeoPgon::DistFromInside(const Double_t *point, const Double_t *dir, In icrossed = GetPhiCrossList(point, dir, ipsec, sph, iph, stepmax); Double_t snext; if (TMath::Abs(dir[2]) < TGeoShape::Tolerance()) { - if (SliceCrossingInZ(point, dir, icrossed, iph, sph, snext, stepmax)) return snext; - if (snext > TGeoShape::Tolerance()) return TGeoShape::Big(); + if (SliceCrossingInZ(point, dir, icrossed, iph, sph, snext, stepmax)) + return snext; + if (snext > TGeoShape::Tolerance()) + return TGeoShape::Big(); return 0.; } - if (SliceCrossingIn(point, dir, ipl, icrossed, iph, sph, snext, stepmax)) return snext; - if (snext > TGeoShape::Tolerance()) return TGeoShape::Big(); + if (SliceCrossingIn(point, dir, ipl, icrossed, iph, sph, snext, stepmax)) + return snext; + if (snext > TGeoShape::Tolerance()) + return TGeoShape::Big(); return 0.; } @@ -526,9 +558,11 @@ Double_t TGeoPgon::DistFromInside(const Double_t *point, const Double_t *dir, In void TGeoPgon::LocatePhi(const Double_t *point, Int_t &ipsec) const { Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi += 360.; + while (phi < fPhi1) + phi += 360.; ipsec = Int_t(fNedges * (phi - fPhi1) / fDphi); // [0, fNedges-1] - if (ipsec > fNedges - 1) ipsec = -1; // in gap + if (ipsec > fNedges - 1) + ipsec = -1; // in gap } //////////////////////////////////////////////////////////////////////////////// @@ -561,9 +595,11 @@ Int_t TGeoPgon::GetPhiCrossList(const Double_t *point, const Double_t *dir, Int_ return 1; } phi = TMath::ATan2(dir[1], dir[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi += 360.; + while (phi < fPhi1) + phi += 360.; istart = Int_t((phi - fPhi1) / divphi); - if (istart > fNedges - 1) istart = -1; + if (istart > fNedges - 1) + istart = -1; iphi[1] = istart; sphi[1] = stepmax; return 2; @@ -579,12 +615,14 @@ Int_t TGeoPgon::GetPhiCrossList(const Double_t *point, const Double_t *dir, Int_ divphi *= TMath::DegToRad(); Double_t phi1 = fPhi1 * TMath::DegToRad(); while (crossing) { - if (istart < 0) gapdone = kTRUE; + if (istart < 0) + gapdone = kTRUE; phi = phi1 + ist * divphi; cph = TMath::Cos(phi); sph = TMath::Sin(phi); crossing = IsCrossingSemiplane(point, dir, cph, sph, sphi[icrossed], rxy); - if (!crossing) sphi[icrossed] = stepmax; + if (!crossing) + sphi[icrossed] = stepmax; iphi[icrossed++] = istart; if (crossing) { if (sphi[icrossed - 1] > stepmax) { @@ -601,7 +639,8 @@ Int_t TGeoPgon::GetPhiCrossList(const Double_t *point, const Double_t *dir, Int_ istart = fNedges - 1; } if (istart < 0) { - if (gapdone) return icrossed; + if (gapdone) + return icrossed; ist = (incsec > 0) ? 0 : fNedges; } else { ist = (incsec > 0) ? (istart + 1) : istart; @@ -618,15 +657,18 @@ Bool_t TGeoPgon::SliceCrossingInZ(const Double_t *point, const Double_t *dir, In Double_t *stepphi, Double_t &snext, Double_t stepmax) const { snext = 0.; - if (!nphi) return kFALSE; + if (!nphi) + return kFALSE; Int_t i; Double_t rmin, rmax; Double_t apg, bpg; Double_t pt[3]; - if (iphi[0] < 0 && nphi == 1) return kFALSE; + if (iphi[0] < 0 && nphi == 1) + return kFALSE; // Get current Z segment Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl < 0 || ipl == fNz - 1) return kFALSE; + if (ipl < 0 || ipl == fNz - 1) + return kFALSE; if (TMath::Abs(point[2] - fZ[ipl]) < TGeoShape::Tolerance()) { if (ipl < fNz - 2 && TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + 1])) { rmin = TMath::Min(fRmin[ipl], fRmin[ipl + 1]); @@ -670,15 +712,18 @@ Bool_t TGeoPgon::SliceCrossingInZ(const Double_t *point, const Double_t *dir, In ndot = dir[0] * cosph + dir[1] * sinph; if (!TGeoShape::IsSameWithinTolerance(ndot, 0)) { dist = (ndot > 0) ? ((rmax - rproj) / ndot) : ((rmin - rproj) / ndot); - if (dist < 0) dist = 0.; + if (dist < 0) + dist = 0.; } if (dist < (snextphi - step)) { snext = step + dist; - if (snext < stepmax) return kTRUE; + if (snext < stepmax) + return kTRUE; return kFALSE; } step = snextphi; - for (i = 0; i < 3; i++) pt[i] = point[i] + step * dir[i]; + for (i = 0; i < 3; i++) + pt[i] = point[i] + step * dir[i]; } snext = step; return kFALSE; @@ -690,15 +735,18 @@ Bool_t TGeoPgon::SliceCrossingInZ(const Double_t *point, const Double_t *dir, In Bool_t TGeoPgon::SliceCrossingZ(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *stepphi, Double_t &snext, Double_t stepmax) const { - if (!nphi) return kFALSE; + if (!nphi) + return kFALSE; Int_t i; Double_t rmin, rmax; Double_t apg, bpg; Double_t pt[3]; - if (iphi[0] < 0 && nphi == 1) return kFALSE; + if (iphi[0] < 0 && nphi == 1) + return kFALSE; // Get current Z segment Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl < 0 || ipl == fNz - 1) return kFALSE; + if (ipl < 0 || ipl == fNz - 1) + return kFALSE; if (TMath::Abs(point[2] - fZ[ipl]) < TGeoShape::Tolerance()) { if (ipl < fNz - 2 && TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + 1])) { rmin = TMath::Min(fRmin[ipl], fRmin[ipl + 1]); @@ -724,12 +772,16 @@ Bool_t TGeoPgon::SliceCrossingZ(const Double_t *point, const Double_t *dir, Int_ Double_t phi; memcpy(pt, point, 3 * sizeof(Double_t)); for (iphcrt = 0; iphcrt < nphi; iphcrt++) { - if (step > stepmax) return kFALSE; + if (step > stepmax) + return kFALSE; snextphi = stepphi[iphcrt]; if (iphi[iphcrt] < 0) { - if (iphcrt == nphi - 1) return kFALSE; - if (snextphi > stepmax) return kFALSE; - for (i = 0; i < 3; i++) pt[i] = point[i] + snextphi * dir[i]; + if (iphcrt == nphi - 1) + return kFALSE; + if (snextphi > stepmax) + return kFALSE; + for (i = 0; i < 3; i++) + pt[i] = point[i] + snextphi * dir[i]; phi = phi1 + (iphi[iphcrt + 1] + 0.5) * divphi; cosph = TMath::Cos(phi); sinph = TMath::Sin(phi); @@ -755,10 +807,12 @@ Bool_t TGeoPgon::SliceCrossingZ(const Double_t *point, const Double_t *dir, Int_ } if (dist < 1E10) { snext = step + dist; - if (snext < stepmax) return kTRUE; + if (snext < stepmax) + return kTRUE; } step = snextphi; - for (i = 0; i < 3; i++) pt[i] = point[i] + step * dir[i]; + for (i = 0; i < 3; i++) + pt[i] = point[i] + step * dir[i]; } return kFALSE; } @@ -772,12 +826,14 @@ Bool_t TGeoPgon::SliceCrossingIn(const Double_t *point, const Double_t *dir, Int Double_t *stepphi, Double_t &snext, Double_t stepmax) const { snext = 0.; - if (!nphi) return kFALSE; + if (!nphi) + return kFALSE; Int_t i; Int_t iphstart = 0; Double_t pt[3]; if (iphi[0] < 0) { - if (stepphi[0] > TGeoShape::Tolerance()) return kFALSE; + if (stepphi[0] > TGeoShape::Tolerance()) + return kFALSE; iphstart = 1; } if (nphi > 1 && iphi[1] < 0 && stepphi[0] < TGeoShape::Tolerance()) { @@ -826,9 +882,11 @@ Bool_t TGeoPgon::SliceCrossingIn(const Double_t *point, const Double_t *dir, Int if (dz < TGeoShape::Tolerance()) { rnew = apr + bpr * fZ[ipl]; rpg = (rnew - fRmin[ipl]) * (rnew - fRmin[ipl + 1]); - if (rpg <= 0) din = distz; + if (rpg <= 0) + din = distz; rpg = (rnew - fRmax[ipl]) * (rnew - fRmax[ipl + 1]); - if (rpg <= 0) dout = distz; + if (rpg <= 0) + dout = distz; distr = TMath::Min(din, dout); } else { rpgin = Rpg(pt[2], ipl, kTRUE, apgin, bpgin); @@ -858,7 +916,8 @@ Bool_t TGeoPgon::SliceCrossingIn(const Double_t *point, const Double_t *dir, Int din = -TGeoShape::Big(); } distr = TMath::Max(din, dout); - if (distr < TGeoShape::Tolerance()) distr = TGeoShape::Big(); + if (distr < TGeoShape::Tolerance()) + distr = TGeoShape::Big(); } else if (rproj > rpgout - 1.E-8) { Double_t ndotd = dir[0] * cosph + dir[1] * sinph + dir[2] * (fRmax[ipl] - fRmax[ipl + 1]) / dz; if (ndotd > 0) { @@ -869,13 +928,16 @@ Bool_t TGeoPgon::SliceCrossingIn(const Double_t *point, const Double_t *dir, Int dout = -TGeoShape::Big(); } distr = TMath::Max(din, dout); - if (distr < TGeoShape::Tolerance()) distr = TGeoShape::Big(); + if (distr < TGeoShape::Tolerance()) + distr = TGeoShape::Big(); } } } - if (distr < snext - TGeoShape::Tolerance()) distr = TGeoShape::Big(); + if (distr < snext - TGeoShape::Tolerance()) + distr = TGeoShape::Big(); if (snextphi < step + TMath::Min(distz, distr)) { - for (i = 0; i < 3; i++) pt[i] = point[i] + snextphi * dir[i]; + for (i = 0; i < 3; i++) + pt[i] = point[i] + snextphi * dir[i]; step = snextphi; snext = 0.0; break; @@ -907,10 +969,12 @@ Bool_t TGeoPgon::SliceCrossingIn(const Double_t *point, const Double_t *dir, Int Bool_t TGeoPgon::SliceCrossing(const Double_t *point, const Double_t *dir, Int_t nphi, Int_t *iphi, Double_t *stepphi, Double_t &snext, Double_t stepmax) const { - if (!nphi) return kFALSE; + if (!nphi) + return kFALSE; Int_t i; Double_t pt[3]; - if (iphi[0] < 0 && nphi == 1) return kFALSE; + if (iphi[0] < 0 && nphi == 1) + return kFALSE; Double_t snextphi = 0.; Double_t step = 0; @@ -919,19 +983,24 @@ Bool_t TGeoPgon::SliceCrossing(const Double_t *point, const Double_t *dir, Int_t Int_t ipl = TMath::BinarySearch(fNz, fZ, point[2]); if (ipl < 0) { ipl = 0; // this should never happen - if (incseg < 0) return kFALSE; + if (incseg < 0) + return kFALSE; } else { if (ipl == fNz - 1) { ipl = fNz - 2; // nor this - if (incseg > 0) return kFALSE; + if (incseg > 0) + return kFALSE; } else { if (TMath::Abs(point[2] - fZ[ipl]) < TGeoShape::Tolerance()) { // we are at the sector edge, but never inside the pgon - if ((ipl + incseg) < 0 || (ipl + incseg) > fNz - 1) return kFALSE; - if (TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + incseg])) ipl += incseg; + if ((ipl + incseg) < 0 || (ipl + incseg) > fNz - 1) + return kFALSE; + if (TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + incseg])) + ipl += incseg; // move to next clean segment if downwards if (incseg < 0) { - if (TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + 1])) ipl--; + if (TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[ipl + 1])) + ipl--; } } } @@ -949,24 +1018,30 @@ Bool_t TGeoPgon::SliceCrossing(const Double_t *point, const Double_t *dir, Int_t memcpy(pt, point, 3 * sizeof(Double_t)); for (iphcrt = 0; iphcrt < nphi; iphcrt++) { // check if step to current checked slice is too big - if (step > stepmax) return kFALSE; + if (step > stepmax) + return kFALSE; // jump over the dead sector snextphi = stepphi[iphcrt]; if (iphi[iphcrt] < 0) { - if (iphcrt == nphi - 1) return kFALSE; - if (snextphi > stepmax) return kFALSE; - for (i = 0; i < 3; i++) pt[i] = point[i] + snextphi * dir[i]; + if (iphcrt == nphi - 1) + return kFALSE; + if (snextphi > stepmax) + return kFALSE; + for (i = 0; i < 3; i++) + pt[i] = point[i] + snextphi * dir[i]; // we have a new z, so check again iz if (incseg > 0) { // loop z planes while (pt[2] > fZ[ipl + 1]) { ipl++; - if (ipl > fNz - 2) return kFALSE; + if (ipl > fNz - 2) + return kFALSE; } } else { while (pt[2] < fZ[ipl]) { ipl--; - if (ipl < 0) return kFALSE; + if (ipl < 0) + return kFALSE; } } // check if we have a crossing when entering new sector @@ -984,7 +1059,8 @@ Bool_t TGeoPgon::SliceCrossing(const Double_t *point, const Double_t *dir, Int_t snext = snextphi; return kTRUE; } - if (IsCrossingSlice(point, dir, iphi[iphcrt], step, ipl, snext, TMath::Min(snextphi, stepmax))) return kTRUE; + if (IsCrossingSlice(point, dir, iphi[iphcrt], step, ipl, snext, TMath::Min(snextphi, stepmax))) + return kTRUE; step = snextphi; } return kFALSE; @@ -996,12 +1072,15 @@ Bool_t TGeoPgon::SliceCrossing(const Double_t *point, const Double_t *dir, Int_t Bool_t TGeoPgon::IsCrossingSlice(const Double_t *point, const Double_t *dir, Int_t iphi, Double_t sstart, Int_t &ipl, Double_t &snext, Double_t stepmax) const { - if (ipl < 0 || ipl > fNz - 2) return kFALSE; - if (sstart > stepmax) return kFALSE; + if (ipl < 0 || ipl > fNz - 2) + return kFALSE; + if (sstart > stepmax) + return kFALSE; Double_t pt[3]; memcpy(pt, point, 3 * sizeof(Double_t)); if (sstart > 0) - for (Int_t i = 0; i < 3; i++) pt[i] += sstart * dir[i]; + for (Int_t i = 0; i < 3; i++) + pt[i] += sstart * dir[i]; stepmax -= sstart; Double_t step; Int_t incseg = (dir[2] > 0) ? 1 : -1; @@ -1043,7 +1122,8 @@ Bool_t TGeoPgon::IsCrossingSlice(const Double_t *point, const Double_t *dir, Int if (TGeoShape::IsSameWithinTolerance(dz, 0)) { rnew = apr + bpr * fZ[ipl]; Double_t rpg = (rnew - fRmin[ipl]) * (rnew - fRmin[ipl + 1]); - if (rpg <= 0) din = (fZ[ipl] - pt[2]) * invdir; + if (rpg <= 0) + din = (fZ[ipl] - pt[2]) * invdir; } else { Rpg(pt[2], ipl, kTRUE, apg, bpg); db = bpg - bpr; @@ -1051,7 +1131,8 @@ Bool_t TGeoPgon::IsCrossingSlice(const Double_t *point, const Double_t *dir, Int znew = (apr - apg) / db; if (znew > fZ[ipl] && znew < fZ[ipl + 1]) { din = (znew - pt[2]) * invdir; - if (din < 0) din = TGeoShape::Big(); + if (din < 0) + din = TGeoShape::Big(); } } } @@ -1068,14 +1149,17 @@ Bool_t TGeoPgon::IsCrossingSlice(const Double_t *point, const Double_t *dir, Int if (TGeoShape::IsSameWithinTolerance(dz, 0)) { rnew = apr + bpr * fZ[ipl]; Double_t rpg = (rnew - fRmax[ipl]) * (rnew - fRmax[ipl + 1]); - if (rpg <= 0) dout = (fZ[ipl] - pt[2]) * invdir; + if (rpg <= 0) + dout = (fZ[ipl] - pt[2]) * invdir; } else { Rpg(pt[2], ipl, kFALSE, apg, bpg); db = bpg - bpr; if (!TGeoShape::IsSameWithinTolerance(db, 0)) { znew = (apr - apg) / db; - if (znew > fZ[ipl] && znew < fZ[ipl + 1]) dout = (znew - pt[2]) * invdir; - if (dout < 0) dout = TGeoShape::Big(); + if (znew > fZ[ipl] && znew < fZ[ipl + 1]) + dout = (znew - pt[2]) * invdir; + if (dout < 0) + dout = TGeoShape::Big(); } } } @@ -1098,20 +1182,25 @@ Bool_t TGeoPgon::IsCrossingSlice(const Double_t *point, const Double_t *dir, Int //////////////////////////////////////////////////////////////////////////////// /// Compute distance from outside point to surface of the polygone -Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, - Double_t *safe) const +Double_t +TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact == 0) return TGeoShape::Big(); // just safety computed - if (iact == 1 && step < *safe) return TGeoShape::Big(); // safety mode + if (iact == 0) + return TGeoShape::Big(); // just safety computed + if (iact == 1 && step < *safe) + return TGeoShape::Big(); // safety mode } // Check if the bounding box is crossed within the requested distance Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist >= step) return TGeoShape::Big(); + if (sdist >= step) + return TGeoShape::Big(); // Protection for points on last Z sections - if (dir[2] <= 0 && TMath::Abs(point[2] - fZ[0]) < TGeoShape::Tolerance()) return TGeoShape::Big(); - if (dir[2] >= 0 && TMath::Abs(point[2] - fZ[fNz - 1]) < TGeoShape::Tolerance()) return TGeoShape::Big(); + if (dir[2] <= 0 && TMath::Abs(point[2] - fZ[0]) < TGeoShape::Tolerance()) + return TGeoShape::Big(); + if (dir[2] >= 0 && TMath::Abs(point[2] - fZ[fNz - 1]) < TGeoShape::Tolerance()) + return TGeoShape::Big(); // copy the current point Double_t pt[3]; memcpy(pt, point, 3 * sizeof(Double_t)); @@ -1132,13 +1221,17 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I if (r2 > (radmax * radmax) || pt[2] < fZ[0] || pt[2] > fZ[fNz - 1]) { pt[2] -= 0.5 * (fZ[0] + fZ[fNz - 1]); snext = TGeoTube::DistFromOutsideS(pt, dir, 0., radmax, 0.5 * (fZ[fNz - 1] - fZ[0])); - if (snext > 1E10) return TGeoShape::Big(); - if (snext > stepmax) return TGeoShape::Big(); + if (snext > 1E10) + return TGeoShape::Big(); + if (snext > stepmax) + return TGeoShape::Big(); stepmax -= snext; pt[2] = point[2]; - for (i = 0; i < 3; i++) pt[i] += snext * dir[i]; + for (i = 0; i < 3; i++) + pt[i] += snext * dir[i]; Bool_t checkz = (ipl < 0 && TMath::Abs(pt[2] - fZ[0]) < 1E-8) ? kTRUE : kFALSE; - if (!checkz) checkz = (ipl == fNz - 1 && TMath::Abs(pt[2] - fZ[fNz - 1]) < 1E-8) ? kTRUE : kFALSE; + if (!checkz) + checkz = (ipl == fNz - 1 && TMath::Abs(pt[2] - fZ[fNz - 1]) < 1E-8) ? kTRUE : kFALSE; if (checkz) { Double_t rmin, rmax; if (ipl < 0) { @@ -1149,17 +1242,20 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I rmax = fRmax[fNz - 1]; } Double_t phi = TMath::ATan2(pt[1], pt[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi += 360.0; + while (phi < fPhi1) + phi += 360.0; Double_t ddp = phi - fPhi1; if (ddp <= fDphi) { ipsec = Int_t(ddp / divphi); Double_t ph0 = (fPhi1 + divphi * (ipsec + 0.5)) * TMath::DegToRad(); rpr = pt[0] * TMath::Cos(ph0) + pt[1] * TMath::Sin(ph0); - if (rpr >= rmin && rpr <= rmax) return snext; + if (rpr >= rmin && rpr <= rmax) + return snext; } } } - if (!fThreadSize) ((TGeoPgon *)this)->CreateThreadData(1); + if (!fThreadSize) + ((TGeoPgon *)this)->CreateThreadData(1); ThreadData_t &td = GetThreadData(); Double_t *sph = td.fDblBuffer; Int_t *iph = td.fIntBuffer; @@ -1169,27 +1265,34 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I if (TMath::Abs(dir[2]) < TGeoShape::Tolerance()) { LocatePhi(pt, ipsec); icrossed = GetPhiCrossList(pt, dir, ipsec, sph, iph, stepmax); - if (SliceCrossingZ(pt, dir, icrossed, iph, sph, snewcross, stepmax)) return (snext + snewcross); + if (SliceCrossingZ(pt, dir, icrossed, iph, sph, snewcross, stepmax)) + return (snext + snewcross); return TGeoShape::Big(); } // Locate phi and get the phi crossing list divphi *= TMath::DegToRad(); Bool_t inphi = kTRUE; Double_t ph = TMath::ATan2(pt[1], pt[0]) * TMath::RadToDeg(); - while (ph < fPhi1) ph += 360.; + while (ph < fPhi1) + ph += 360.; ipsec = Int_t(fNedges * (ph - fPhi1) / fDphi); // [0, fNedges-1] - if (ipsec > fNedges - 1) ipsec = -1; // in gap + if (ipsec > fNedges - 1) + ipsec = -1; // in gap Double_t phim = fPhi1 + 0.5 * fDphi; Double_t ddp = TMath::Abs(ph - phim); if (fDphi < 360.0) { inphi = (ddp < 0.5 * fDphi + TGeoShape::Tolerance()) ? kTRUE : kFALSE; } ipl = TMath::BinarySearch(fNz, fZ, pt[2]); - if (ipl < 0) ipl = 0; - if (ipl == fNz - 1) ipl--; + if (ipl < 0) + ipl = 0; + if (ipl == fNz - 1) + ipl--; Bool_t inz = kTRUE; - if (pt[2] > fZ[fNz - 1] + TGeoShape::Tolerance()) inz = kFALSE; - if (pt[2] < fZ[0] - TGeoShape::Tolerance()) inz = kFALSE; + if (pt[2] > fZ[fNz - 1] + TGeoShape::Tolerance()) + inz = kFALSE; + if (pt[2] < fZ[0] - TGeoShape::Tolerance()) + inz = kFALSE; Bool_t onphi = kFALSE; if (inphi && inz) { Bool_t done = kFALSE; @@ -1199,10 +1302,14 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I Double_t sphi = TMath::Sin(phi); Double_t rproj = pt[0] * cphi + pt[1] * sphi; if (TGeoShape::IsSameWithinTolerance(dz, 0)) { - if (rproj < fRmin[ipl] && rproj > fRmin[ipl + 1] && dir[2] > 0) return 0.0; - if (rproj > fRmin[ipl] && rproj < fRmin[ipl + 1] && dir[2] < 0) return 0.0; - if (rproj > fRmax[ipl] && rproj < fRmax[ipl + 1] && dir[2] > 0) return 0.0; - if (rproj < fRmax[ipl] && rproj > fRmax[ipl + 1] && dir[2] < 0) return 0.0; + if (rproj < fRmin[ipl] && rproj > fRmin[ipl + 1] && dir[2] > 0) + return 0.0; + if (rproj > fRmin[ipl] && rproj < fRmin[ipl + 1] && dir[2] < 0) + return 0.0; + if (rproj > fRmax[ipl] && rproj < fRmax[ipl + 1] && dir[2] > 0) + return 0.0; + if (rproj < fRmax[ipl] && rproj > fRmax[ipl + 1] && dir[2] < 0) + return 0.0; done = kTRUE; } if (!done) { @@ -1227,38 +1334,50 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I // on inner boundary Double_t ndotd = dir[0] * cphi + dir[1] * sphi + dir[2] * (fRmin[ipl] - fRmin[ipl + 1]) * dzinv; // printf(" - inner ndotd=%f (>0 ->0)\n",ndotd); - if (ndotd > 0) return snext; + if (ndotd > 0) + return snext; done = kTRUE; } if (!done && safrmax < safz && safrmax < safphi) { Double_t ndotd = dir[0] * cphi + dir[1] * sphi + dir[2] * (fRmax[ipl] - fRmax[ipl + 1]) * dzinv; // printf(" - outer ndotd=%f (<0 ->0)\n",ndotd); - if (ndotd < 0) return snext; + if (ndotd < 0) + return snext; done = kTRUE; } if (!done && safz < safphi) { done = kTRUE; Int_t iplc = ipl; - if (TMath::Abs(pt[2] - fZ[ipl]) > TMath::Abs(fZ[ipl + 1] - pt[2])) iplc++; + if (TMath::Abs(pt[2] - fZ[ipl]) > TMath::Abs(fZ[ipl + 1] - pt[2])) + iplc++; if (iplc == 0 || iplc == fNz - 1) { - if (pt[2] * dir[2] < 0) return snext; + if (pt[2] * dir[2] < 0) + return snext; return TGeoShape::Big(); } else { if (TGeoShape::IsSameWithinTolerance(fZ[iplc], fZ[iplc + 1])) { if (dir[2] > 0) { - if (rproj < fRmin[iplc] && rproj > fRmin[iplc + 1]) return snext; - if (rproj > fRmax[iplc] && rproj < fRmax[iplc + 1]) return snext; + if (rproj < fRmin[iplc] && rproj > fRmin[iplc + 1]) + return snext; + if (rproj > fRmax[iplc] && rproj < fRmax[iplc + 1]) + return snext; } else { - if (rproj > fRmin[iplc] && rproj < fRmin[iplc + 1]) return snext; - if (rproj < fRmax[iplc] && rproj > fRmax[iplc + 1]) return snext; + if (rproj > fRmin[iplc] && rproj < fRmin[iplc + 1]) + return snext; + if (rproj < fRmax[iplc] && rproj > fRmax[iplc + 1]) + return snext; } } else if (TGeoShape::IsSameWithinTolerance(fZ[iplc], fZ[iplc - 1])) { if (dir[2] > 0) { - if (rproj < fRmin[iplc - 1] && rproj > fRmin[iplc]) return snext; - if (rproj > fRmax[iplc - 1] && rproj < fRmax[iplc]) return snext; + if (rproj < fRmin[iplc - 1] && rproj > fRmin[iplc]) + return snext; + if (rproj > fRmax[iplc - 1] && rproj < fRmax[iplc]) + return snext; } else { - if (rproj > fRmin[iplc - 1] && rproj < fRmin[iplc]) return snext; - if (rproj < fRmax[iplc - 1] && rproj > fRmax[iplc]) return snext; + if (rproj > fRmin[iplc - 1] && rproj < fRmin[iplc]) + return snext; + if (rproj < fRmax[iplc - 1] && rproj > fRmax[iplc]) + return snext; } } } @@ -1273,9 +1392,12 @@ Double_t TGeoPgon::DistFromOutside(const Double_t *point, const Double_t *dir, I } icrossed = GetPhiCrossList(pt, dir, ipsec, sph, iph, stepmax); if (onphi) { - if (!icrossed) return snext; - if (iph[0] < 0 && sph[0] < TGeoShape::Tolerance()) return (snext + sph[0]); - if (iph[0] >= 0 && sph[0] > 1.E-8) return snext; + if (!icrossed) + return snext; + if (iph[0] < 0 && sph[0] < TGeoShape::Tolerance()) + return (snext + sph[0]); + if (iph[0] >= 0 && sph[0] > 1.E-8) + return snext; } // Fire-up slice crossing algorithm if (SliceCrossing(pt, dir, icrossed, iph, sph, snewcross, stepmax)) { @@ -1303,8 +1425,8 @@ Int_t TGeoPgon::DistancetoPrimitive(Int_t px, Int_t py) /// Z divisions can be performed if the divided range is in between two consecutive Z planes. /// In case a wrong division axis is supplied, returns pointer to volume that was divided. -TGeoVolume *TGeoPgon::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, - Double_t step) +TGeoVolume * +TGeoPgon::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { // printf("Dividing %s : nz=%d nedges=%d phi1=%g dphi=%g (ndiv=%d iaxis=%d start=%g step=%g)\n", // voldiv->GetName(), fNz, fNedges, fPhi1, fDphi, ndiv, iaxis, start, step); @@ -1335,7 +1457,8 @@ TGeoVolume *TGeoPgon::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi shape = new TGeoPgon(-step / 2, step, nedges, fNz); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); vmulti->AddVolume(vol); - for (is = 0; is < fNz; is++) ((TGeoPgon *)shape)->DefineSection(is, fZ[is], fRmin[is], fRmax[is]); + for (is = 0; is < fNz; is++) + ((TGeoPgon *)shape)->DefineSection(is, fZ[is], fRmin[is], fRmax[is]); opt = "Phi"; for (id = 0; id < ndiv; id++) { voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); @@ -1348,7 +1471,8 @@ TGeoVolume *TGeoPgon::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi if (start < fZ[ipl]) continue; else { - if ((start + ndiv * step) > fZ[ipl + 1]) continue; + if ((start + ndiv * step) > fZ[ipl + 1]) + continue; } isect = ipl; zmin = fZ[isect]; @@ -1393,8 +1517,10 @@ void TGeoPgon::GetBoundingCylinder(Double_t *param) const param[0] = fRmin[0]; // Rmin param[1] = fRmax[0]; // Rmax for (Int_t i = 1; i < fNz; i++) { - if (fRmin[i] < param[0]) param[0] = fRmin[i]; - if (fRmax[i] > param[1]) param[1] = fRmax[i]; + if (fRmin[i] < param[0]) + param[0] = fRmin[i]; + if (fRmax[i] > param[1]) + param[1] = fRmax[i]; } Double_t divphi = fDphi / fNedges; param[1] /= TMath::Cos(0.5 * divphi * TMath::DegToRad()); @@ -1454,9 +1580,11 @@ void TGeoPgon::SetSegsAndPols(TBuffer3D &buff) const Int_t i, j; const Int_t n = GetNedges() + 1; Int_t nz = GetNz(); - if (nz < 2) return; + if (nz < 2) + return; Int_t nbPnts = nz * 2 * n; - if (nbPnts <= 0) return; + if (nbPnts <= 0) + return; Double_t dphi = GetDphi(); Bool_t specialCase = TGeoShape::IsSameWithinTolerance(dphi, 360); @@ -1622,7 +1750,6 @@ void TGeoPgon::SetSegsAndPols(TBuffer3D &buff) const } } - //////////////////////////////////////////////////////////////////////////////// /// Fill TBuffer3D structure for segments and polygons, when no inner surface exists @@ -1632,7 +1759,8 @@ void TGeoPgon::SetSegsAndPolsNoInside(TBuffer3D &buff) const const Int_t nz = GetNz(); const Int_t nbPnts = nz * n + 2; - if ((nz < 2) || (nbPnts <= 0) || (n < 2)) return; + if ((nz < 2) || (nbPnts <= 0) || (n < 2)) + return; Int_t c = GetBasicColor(); @@ -1644,7 +1772,7 @@ void TGeoPgon::SetSegsAndPolsNoInside(TBuffer3D &buff) const for (j = 1; j < n; j++) { buff.fSegs[indx++] = c; buff.fSegs[indx++] = indx2 + j - 1; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); } } @@ -1652,15 +1780,15 @@ void TGeoPgon::SetSegsAndPolsNoInside(TBuffer3D &buff) const // bottom lines for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); buff.fSegs[indx++] = nbPnts - 2; } - indx2 = (nz-1) * n; + indx2 = (nz - 1) * n; // top lines for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); buff.fSegs[indx++] = nbPnts - 1; } @@ -1670,8 +1798,8 @@ void TGeoPgon::SetSegsAndPolsNoInside(TBuffer3D &buff) const indx2 = i * n; for (j = 0; j < n; j++) { buff.fSegs[indx++] = c; - buff.fSegs[indx++] = indx2 + j % (n-1); - buff.fSegs[indx++] = indx2 + n + j % (n-1); + buff.fSegs[indx++] = indx2 + j % (n - 1); + buff.fSegs[indx++] = indx2 + n + j % (n - 1); } } @@ -1679,42 +1807,41 @@ void TGeoPgon::SetSegsAndPolsNoInside(TBuffer3D &buff) const // bottom cap indx1 = 0; // start of first z layer - indx2 = nz*(n-1); + indx2 = nz * (n - 1); for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 3; buff.fPols[indx++] = indx1 + j; - buff.fPols[indx++] = indx2 + (j+1)%(n-1); + buff.fPols[indx++] = indx2 + (j + 1) % (n - 1); buff.fPols[indx++] = indx2 + j; } // top cap - indx1 = (nz-1)*(n-1); // start last z layer - indx2 = nz*(n-1) + n; + indx1 = (nz - 1) * (n - 1); // start last z layer + indx2 = nz * (n - 1) + n; for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 3; buff.fPols[indx++] = indx1 + j; // last z layer buff.fPols[indx++] = indx2 + j; - buff.fPols[indx++] = indx2 + (j+1)%(n-1); + buff.fPols[indx++] = indx2 + (j + 1) % (n - 1); } // outside, number of polygons: (nz-1)*(n-1) for (Int_t k = 0; k < (nz - 1); k++) { - indx1 = k*(n-1); - indx2 = nz*(n-1) + n*2 + k*n; - for (j = 0; j < n-1; j++) { + indx1 = k * (n - 1); + indx2 = nz * (n - 1) + n * 2 + k * n; + for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; buff.fPols[indx++] = indx1 + j; buff.fPols[indx++] = indx2 + j; - buff.fPols[indx++] = indx1 + j + (n-1); - buff.fPols[indx++] = indx2 + (j+1)%(n-1); + buff.fPols[indx++] = indx1 + j + (n - 1); + buff.fPols[indx++] = indx2 + (j + 1) % (n - 1); } } } - //////////////////////////////////////////////////////////////////////////////// /// Computes projected pgon radius (inner or outer) corresponding to a given Z /// value. Fills corresponding coefficients of: @@ -1779,13 +1906,16 @@ Double_t TGeoPgon::SafetyToSegment(const Double_t *point, Int_t ipl, Int_t iphi, Double_t safe; Int_t i; Double_t r, rpgon, ta, calf; - if (ipl < 0 || ipl > fNz - 2) return (safmin + 1.); // error in input plane - // Get info about segment. + if (ipl < 0 || ipl > fNz - 2) + return (safmin + 1.); // error in input plane + // Get info about segment. Double_t dz = fZ[ipl + 1] - fZ[ipl]; - if (dz < 1E-9) return 1E9; // skip radius-changing segment + if (dz < 1E-9) + return 1E9; // skip radius-changing segment Double_t znew = point[2] - 0.5 * (fZ[ipl] + fZ[ipl + 1]); saf[0] = 0.5 * dz - TMath::Abs(znew); - if (-saf[0] > safmin) return TGeoShape::Big(); // means: stop checking further segments + if (-saf[0] > safmin) + return TGeoShape::Big(); // means: stop checking further segments Double_t rmin1 = fRmin[ipl]; Double_t rmax1 = fRmax[ipl]; Double_t rmin2 = fRmin[ipl + 1]; @@ -1806,10 +1936,12 @@ Double_t TGeoPgon::SafetyToSegment(const Double_t *point, Int_t ipl, Int_t iphi, Double_t rout = tg2 * znew + ro2; saf[1] = (ro1 > 0) ? ((r - rin) * cr1) : TGeoShape::Big(); saf[2] = (rout - r) * cr2; - for (i = 0; i < 3; i++) saf[i] = -saf[i]; + for (i = 0; i < 3; i++) + saf[i] = -saf[i]; safe = saf[TMath::LocMax(3, saf)]; safe = TMath::Max(safe, safphi); - if (safe < 0) safe = 0; + if (safe < 0) + safe = 0; return safe; } Double_t ph0 = (fPhi1 + divphi * (iphi + 0.5)) * TMath::DegToRad(); @@ -1830,11 +1962,13 @@ Double_t TGeoPgon::SafetyToSegment(const Double_t *point, Int_t ipl, Int_t iphi, safe = saf[TMath::LocMin(3, saf)]; safe = TMath::Min(safe, safphi); } else { - for (i = 0; i < 3; i++) saf[i] = -saf[i]; + for (i = 0; i < 3; i++) + saf[i] = -saf[i]; safe = saf[TMath::LocMax(3, saf)]; safe = TMath::Max(safe, safphi); } - if (safe < 0) safe = 0; + if (safe < 0) + safe = 0; return safe; } @@ -1852,23 +1986,28 @@ Double_t TGeoPgon::Safety(const Double_t *point, Bool_t in) const if (in) { //---> point is inside pgon ipl = TMath::BinarySearch(fNz, fZ, point[2]); - if (ipl == (fNz - 1)) return 0; // point on last Z boundary - if (ipl < 0) return 0; // point on first Z boundary + if (ipl == (fNz - 1)) + return 0; // point on last Z boundary + if (ipl < 0) + return 0; // point on first Z boundary dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); - if (dz < 1E-8) return 0; + if (dz < 1E-8) + return 0; // Check safety for current segment safmin = SafetyToSegment(point, ipl, iphi, in, safphi); if (safmin > 1E10) { // something went wrong - point is not inside current segment return TGeoShape::Big(); } - if (safmin < 1E-6) return TMath::Abs(safmin); // point on radius-changing plane + if (safmin < 1E-6) + return TMath::Abs(safmin); // point on radius-changing plane // check increasing iplanes iplane = ipl + 1; saftmp = 0.; while ((iplane < fNz - 1) && saftmp < 1E10) { saftmp = TMath::Abs(SafetyToSegment(point, iplane, iphi, kFALSE, safphi, safmin)); - if (saftmp < safmin) safmin = saftmp; + if (saftmp < safmin) + safmin = saftmp; iplane++; } // now decreasing nplanes @@ -1876,7 +2015,8 @@ Double_t TGeoPgon::Safety(const Double_t *point, Bool_t in) const saftmp = 0.; while ((iplane >= 0) && saftmp < 1E10) { saftmp = TMath::Abs(SafetyToSegment(point, iplane, iphi, kFALSE, safphi, safmin)); - if (saftmp < safmin) safmin = saftmp; + if (saftmp < safmin) + safmin = saftmp; iplane--; } return safmin; @@ -1890,18 +2030,21 @@ Double_t TGeoPgon::Safety(const Double_t *point, Bool_t in) const dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); if (dz < 1E-8) { ipl++; - if (ipl > fNz - 2) return 0.; // invalid last section + if (ipl > fNz - 2) + return 0.; // invalid last section dz = 0.5 * (fZ[ipl + 1] - fZ[ipl]); } // Check safety for current segment safmin = SafetyToSegment(point, ipl, iphi, kFALSE, safphi); - if (safmin < 1E-6) return TMath::Abs(safmin); // point on radius-changing plane + if (safmin < 1E-6) + return TMath::Abs(safmin); // point on radius-changing plane // check increasing iplanes iplane = ipl + 1; saftmp = 0.; while ((iplane < fNz - 1) && saftmp < 1E10) { saftmp = TMath::Abs(SafetyToSegment(point, iplane, iphi, kFALSE, safphi, safmin)); - if (saftmp < safmin) safmin = saftmp; + if (saftmp < safmin) + safmin = saftmp; iplane++; } // now decreasing nplanes @@ -1909,7 +2052,8 @@ Double_t TGeoPgon::Safety(const Double_t *point, Bool_t in) const saftmp = 0.; while ((iplane >= 0) && saftmp < 1E10) { saftmp = TMath::Abs(SafetyToSegment(point, iplane, iphi, kFALSE, safphi, safmin)); - if (saftmp < safmin) safmin = saftmp; + if (saftmp < safmin) + safmin = saftmp; iplane--; } return safmin; @@ -1920,13 +2064,15 @@ Double_t TGeoPgon::Safety(const Double_t *point, Bool_t in) const void TGeoPgon::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " phi1 = " << fPhi1 << ";" << std::endl; out << " dphi = " << fDphi << ";" << std::endl; out << " nedges = " << fNedges << ";" << std::endl; out << " nz = " << fNz << ";" << std::endl; - out << " auto " << GetPointerName() << " = new TGeoPgon(\"" << GetName() << "\", phi1, dphi, nedges, nz);" << std::endl; + out << " auto " << GetPointerName() << " = new TGeoPgon(\"" << GetName() << "\", phi1, dphi, nedges, nz);" + << std::endl; for (Int_t i = 0; i < fNz; i++) { out << " z = " << fZ[i] << ";" << std::endl; out << " rmin = " << fRmin[i] << ";" << std::endl; @@ -1949,16 +2095,20 @@ void TGeoPgon::SetDimensions(Double_t *param) Error("SetDimensions", "Pgon %s: Number of Z sections must be > 2", GetName()); return; } - if (fRmin) delete[] fRmin; - if (fRmax) delete[] fRmax; - if (fZ) delete[] fZ; + if (fRmin) + delete[] fRmin; + if (fRmax) + delete[] fRmax; + if (fZ) + delete[] fZ; fRmin = new Double_t[fNz]; fRmax = new Double_t[fNz]; fZ = new Double_t[fNz]; memset(fRmin, 0, fNz * sizeof(Double_t)); memset(fRmax, 0, fNz * sizeof(Double_t)); memset(fZ, 0, fNz * sizeof(Double_t)); - for (Int_t i = 0; i < fNz; i++) DefineSection(i, param[4 + 3 * i], param[5 + 3 * i], param[6 + 3 * i]); + for (Int_t i = 0; i < fNz; i++) + DefineSection(i, param[4 + 3 * i], param[5 + 3 * i], param[6 + 3 * i]); } //////////////////////////////////////////////////////////////////////////////// @@ -1999,7 +2149,7 @@ void TGeoPgon::SetPoints(Double_t *points) const points[indx++] = 0; points[indx++] = 0; - points[indx++] = fZ[GetNz()-1]; + points[indx++] = fZ[GetNz() - 1]; } } } @@ -2042,7 +2192,7 @@ void TGeoPgon::SetPoints(Float_t *points) const points[indx++] = 0; points[indx++] = 0; - points[indx++] = fZ[GetNz()-1]; + points[indx++] = fZ[GetNz() - 1]; } } } @@ -2057,7 +2207,8 @@ void TGeoPgon::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t n = GetNedges() + 1; Int_t nz = GetNz(); - if (nz < 2) return; + if (nz < 2) + return; if (HasInsideSurface()) { Bool_t specialCase = TGeoShape::IsSameWithinTolerance(GetDphi(), 360); @@ -2086,9 +2237,7 @@ Int_t TGeoPgon::GetNmeshVertices() const //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoPgon::Sizeof3D() const -{ -} +void TGeoPgon::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. @@ -2130,7 +2279,8 @@ const TBuffer3D &TGeoPgon::GetBuffer3D(Int_t reqSections, Bool_t localFrame) con void TGeoPgon::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i = 0; i < vecsize; i++) inside[i] = Contains(&points[3 * i]); + for (Int_t i = 0; i < vecsize; i++) + inside[i] = Contains(&points[3 * i]); } //////////////////////////////////////////////////////////////////////////////// @@ -2140,7 +2290,8 @@ void TGeoPgon::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) void TGeoPgon::ComputeNormal_v(const Double_t *points, const Double_t *dirs, Double_t *norms, Int_t vecsize) { - for (Int_t i = 0; i < vecsize; i++) ComputeNormal(&points[3 * i], &dirs[3 * i], &norms[3 * i]); + for (Int_t i = 0; i < vecsize; i++) + ComputeNormal(&points[3 * i], &dirs[3 * i], &norms[3 * i]); } //////////////////////////////////////////////////////////////////////////////// @@ -2149,7 +2300,8 @@ void TGeoPgon::ComputeNormal_v(const Double_t *points, const Double_t *dirs, Dou void TGeoPgon::DistFromInside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const { - for (Int_t i = 0; i < vecsize; i++) dists[i] = DistFromInside(&points[3 * i], &dirs[3 * i], 3, step[i]); + for (Int_t i = 0; i < vecsize; i++) + dists[i] = DistFromInside(&points[3 * i], &dirs[3 * i], 3, step[i]); } //////////////////////////////////////////////////////////////////////////////// @@ -2158,7 +2310,8 @@ void TGeoPgon::DistFromInside_v(const Double_t *points, const Double_t *dirs, Do void TGeoPgon::DistFromOutside_v(const Double_t *points, const Double_t *dirs, Double_t *dists, Int_t vecsize, Double_t *step) const { - for (Int_t i = 0; i < vecsize; i++) dists[i] = DistFromOutside(&points[3 * i], &dirs[3 * i], 3, step[i]); + for (Int_t i = 0; i < vecsize; i++) + dists[i] = DistFromOutside(&points[3 * i], &dirs[3 * i], 3, step[i]); } //////////////////////////////////////////////////////////////////////////////// @@ -2168,5 +2321,6 @@ void TGeoPgon::DistFromOutside_v(const Double_t *points, const Double_t *dirs, D void TGeoPgon::Safety_v(const Double_t *points, const Bool_t *inside, Double_t *safe, Int_t vecsize) const { - for (Int_t i = 0; i < vecsize; i++) safe[i] = Safety(&points[3 * i], inside[i]); + for (Int_t i = 0; i < vecsize; i++) + safe[i] = Safety(&points[3 * i], inside[i]); } diff --git a/geom/geom/src/TGeoPhysicalNode.cxx b/geom/geom/src/TGeoPhysicalNode.cxx index 3215a4ab68bd9..ac5005287478a 100644 --- a/geom/geom/src/TGeoPhysicalNode.cxx +++ b/geom/geom/src/TGeoPhysicalNode.cxx @@ -76,10 +76,10 @@ ClassImp(TGeoPhysicalNode); TGeoPhysicalNode::TGeoPhysicalNode() : TNamed() { - fLevel = 0; - fMatrices = 0; - fNodes = 0; - fMatrixOrig = 0; + fLevel = 0; + fMatrices = 0; + fNodes = 0; + fMatrixOrig = 0; SetVisibility(kTRUE); SetVisibleFull(kFALSE); SetIsVolAtt(kTRUE); @@ -89,16 +89,16 @@ TGeoPhysicalNode::TGeoPhysicalNode() : TNamed() //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoPhysicalNode::TGeoPhysicalNode(const char *path) : TNamed(path,"") +TGeoPhysicalNode::TGeoPhysicalNode(const char *path) : TNamed(path, "") { if (!path[0]) { Error("ctor", "path not valid"); return; } - fLevel = 0; + fLevel = 0; fMatrices = new TObjArray(30); - fNodes = new TObjArray(30); - fMatrixOrig = 0; + fNodes = new TObjArray(30); + fMatrixOrig = 0; SetPath(path); SetVisibility(kTRUE); SetVisibleFull(kFALSE); @@ -115,8 +115,10 @@ TGeoPhysicalNode::~TGeoPhysicalNode() fMatrices->Delete(); delete fMatrices; } - if (fNodes) delete fNodes; - if (fMatrixOrig) delete fMatrixOrig; + if (fNodes) + delete fNodes; + if (fMatrixOrig) + delete fMatrixOrig; } //////////////////////////////////////////////////////////////////////////////// @@ -132,7 +134,8 @@ TGeoPhysicalNode::~TGeoPhysicalNode() Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t check, Double_t ovlp) { - if (!newmat && !newshape) return kFALSE; + if (!newmat && !newshape) + return kFALSE; if (TGeoManager::IsLocked()) { Error("Align", "Not performed. Geometry in LOCKED mode !"); return kFALSE; @@ -143,7 +146,7 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c } TGeoNode *node = GetNode(); if (node->IsOffset()) { - Error("Align", "Cannot align division nodes: %s\n",node->GetName()); + Error("Align", "Cannot align division nodes: %s\n", node->GetName()); return kFALSE; } // Refresh the node since other Align calls may have altered the stored nodes @@ -154,20 +157,20 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c Int_t i; if (!IsAligned()) { Int_t *id = new Int_t[fLevel]; - for (i=0; iGetIndex(node); - if (id[i]<0) { - Error("Align","%s cannot align node %s",GetName(), node->GetName()); - delete [] id; + if (id[i] < 0) { + Error("Align", "%s cannot align node %s", GetName(), node->GetName()); + delete[] id; return kFALSE; } } - for (i=0; iIsCloned()) { vd = node->GetVolume(); @@ -175,13 +178,13 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c } else { vd = node->GetVolume()->CloneVolume(); if (!vd) { - delete [] id; + delete[] id; Fatal("Align", "Cannot clone volume %s", node->GetVolume()->GetName()); return kFALSE; } nnode = node->MakeCopyNode(); if (!nnode) { - delete [] id; + delete[] id; Fatal("Align", "Cannot make copy node for %s", node->GetName()); return kFALSE; } @@ -193,15 +196,15 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c gGeoManager->GetListOfGShapes()->Add(nnode); } vm->GetNodes()->RemoveAt(id[i]); - vm->GetNodes()->AddAt(nnode,id[i]); - fNodes->RemoveAt(i+1); - fNodes->AddAt(nnode,i+1); - // node->GetVolume()->Release(); + vm->GetNodes()->AddAt(nnode, id[i]); + fNodes->RemoveAt(i + 1); + fNodes->AddAt(nnode, i + 1); + // node->GetVolume()->Release(); } // Consider new cloned volume as mother and continue vm = vd; } - delete [] id; + delete[] id; } else { nnode = GetNode(); } @@ -211,7 +214,7 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c } // Now nnode is a cloned node of the one that need to be aligned - TGeoNodeMatrix *aligned = (TGeoNodeMatrix*)nnode; + TGeoNodeMatrix *aligned = (TGeoNodeMatrix *)nnode; vm = nnode->GetMotherVolume(); vd = nnode->GetVolume(); if (newmat) { @@ -221,14 +224,18 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c TGeoCompositeShape *cs; if (nnode->GetMatrix()->IsShared()) { // Now find the node having a composite shape using this shared matrix - for (i=0; iGetNode(i); - if (node==nnode) continue; - if (node->IsOffset()) continue; - if (!node->GetVolume()->GetShape()->IsComposite()) continue; + if (node == nnode) + continue; + if (node->IsOffset()) + continue; + if (!node->GetVolume()->GetShape()->IsComposite()) + continue; // We found a node having a composite shape, scan for the shared matrix - cs = (TGeoCompositeShape*)node->GetVolume()->GetShape(); - if (cs->GetBoolNode()->GetRightMatrix() != nnode->GetMatrix()) continue; + cs = (TGeoCompositeShape *)node->GetVolume()->GetShape(); + if (cs->GetBoolNode()->GetRightMatrix() != nnode->GetMatrix()) + continue; // The composite uses the matrix -> replace it TGeoCompositeShape *ncs = new TGeoCompositeShape(cs->GetName(), cs->GetBoolNode()->MakeClone()); ncs->GetBoolNode()->ReplaceMatrix(nnode->GetMatrix(), newmat); @@ -250,17 +257,19 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c gGeoManager->GetListOfGShapes()->Add(newnode); } vm->GetNodes()->RemoveAt(i); - vm->GetNodes()->AddAt(newnode,i); + vm->GetNodes()->AddAt(newnode, i); shared = kTRUE; } - if (!shared) Error("Align", "The matrix replaced for %s is not actually shared", GetName()); + if (!shared) + Error("Align", "The matrix replaced for %s is not actually shared", GetName()); } else { // The aligned node may have a composite shape containing a shared matrix if (vd->GetShape()->IsComposite()) { - cs = (TGeoCompositeShape*)vd->GetShape(); + cs = (TGeoCompositeShape *)vd->GetShape(); if (cs->GetBoolNode()->GetRightMatrix()->IsShared()) { if (!nnode->GetMatrix()->IsIdentity()) { - Error("Align", "The composite shape having a shared matrix on the subtracted branch must be positioned using identity matrix."); + Error("Align", "The composite shape having a shared matrix on the subtracted branch must be " + "positioned using identity matrix."); return kFALSE; } // We have to put the alignment matrix on top of the left branch @@ -277,33 +286,40 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c } } // Register matrix and make it the active one - if (!newmat->IsRegistered()) newmat->RegisterYourself(); + if (!newmat->IsRegistered()) + newmat->RegisterYourself(); if (aligned) { aligned->SetMatrix(newmat); // Update the global matrix for the aligned node TGeoHMatrix *global = GetMatrix(); - TGeoHMatrix *up = GetMatrix(fLevel-1); + TGeoHMatrix *up = GetMatrix(fLevel - 1); *global = up; global->Multiply(newmat); } } // Change the shape for the aligned node - if (newshape) vd->SetShape(newshape); + if (newshape) + vd->SetShape(newshape); // Re-compute bounding box of mother(s) if needed - for (i=fLevel-1; i>0; i--) { + for (i = fLevel - 1; i > 0; i--) { Bool_t dassm = vd->IsAssembly(); // is daughter assembly ? vd = GetVolume(i); - if (!vd) break; + if (!vd) + break; Bool_t cassm = vd->IsAssembly(); // is current assembly ? - if (cassm) ((TGeoShapeAssembly*)vd->GetShape())->NeedsBBoxRecompute(); - if ((cassm || dassm) && vd->GetVoxels()) vd->GetVoxels()->SetNeedRebuild(); - if (!cassm) break; + if (cassm) + ((TGeoShapeAssembly *)vd->GetShape())->NeedsBBoxRecompute(); + if ((cassm || dassm) && vd->GetVoxels()) + vd->GetVoxels()->SetNeedRebuild(); + if (!cassm) + break; } // Now we have to re-voxelize the mother volume TGeoVoxelFinder *voxels = vm->GetVoxels(); - if (voxels) voxels->SetNeedRebuild(); + if (voxels) + voxels->SetNeedRebuild(); // Eventually check for overlaps if (check) { if (voxels) { @@ -313,22 +329,29 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c // Set aligned node to be checked i = fLevel; node = GetNode(i); - if (!node) return kTRUE; + if (!node) + return kTRUE; if (node->IsOverlapping()) { - Info("Align", "The check for overlaps for node: \n%s\n cannot be performed since the node is declared possibly overlapping", + Info("Align", + "The check for overlaps for node: \n%s\n cannot be performed since the node is declared possibly " + "overlapping", GetName()); } else { gGeoManager->SetCheckedNode(node); // Check overlaps for the first non-assembly parent node - while ((node=GetNode(--i))) { - if (!node->GetVolume()->IsAssembly()) break; + while ((node = GetNode(--i))) { + if (!node->GetVolume()->IsAssembly()) + break; } if (node && node->IsOverlapping()) { - Info("Align", "The check for overlaps for assembly node: \n%s\n cannot be performed since the parent %s is declared possibly overlapping", + Info("Align", + "The check for overlaps for assembly node: \n%s\n cannot be performed since the parent %s is declared " + "possibly overlapping", GetName(), node->GetName()); node = 0; } - if (node) node->CheckOverlaps(ovlp); + if (node) + node->CheckOverlaps(ovlp); gGeoManager->SetCheckedNode(0); } } @@ -342,25 +365,25 @@ Bool_t TGeoPhysicalNode::Align(TGeoMatrix *newmat, TGeoShape *newshape, Bool_t c void TGeoPhysicalNode::cd() const { - if (GetNode(0) != gGeoManager->GetTopNode()) return; + if (GetNode(0) != gGeoManager->GetTopNode()) + return; gGeoManager->cd(fName.Data()); } //////////////////////////////////////////////////////////////////////////////// /// Draw this node. -void TGeoPhysicalNode::Draw(Option_t * /*option*/) -{ -} +void TGeoPhysicalNode::Draw(Option_t * /*option*/) {} //////////////////////////////////////////////////////////////////////////////// /// Return parent at LEVUP generation TGeoNode *TGeoPhysicalNode::GetMother(Int_t levup) const { - Int_t ind = fLevel-levup; - if (ind<0) return 0; - return (TGeoNode*)fNodes->UncheckedAt(ind); + Int_t ind = fLevel - levup; + if (ind < 0) + return 0; + return (TGeoNode *)fNodes->UncheckedAt(ind); } //////////////////////////////////////////////////////////////////////////////// @@ -368,9 +391,11 @@ TGeoNode *TGeoPhysicalNode::GetMother(Int_t levup) const TGeoHMatrix *TGeoPhysicalNode::GetMatrix(Int_t level) const { - if (level<0) return (TGeoHMatrix*)fMatrices->UncheckedAt(fLevel); - if (level>fLevel) return 0; - return (TGeoHMatrix*)fMatrices->UncheckedAt(level); + if (level < 0) + return (TGeoHMatrix *)fMatrices->UncheckedAt(fLevel); + if (level > fLevel) + return 0; + return (TGeoHMatrix *)fMatrices->UncheckedAt(level); } //////////////////////////////////////////////////////////////////////////////// @@ -378,9 +403,11 @@ TGeoHMatrix *TGeoPhysicalNode::GetMatrix(Int_t level) const TGeoNode *TGeoPhysicalNode::GetNode(Int_t level) const { - if (level<0) return (TGeoNode*)fNodes->UncheckedAt(fLevel); - if (level>fLevel) return 0; - return (TGeoNode*)fNodes->UncheckedAt(level); + if (level < 0) + return (TGeoNode *)fNodes->UncheckedAt(fLevel); + if (level > fLevel) + return 0; + return (TGeoNode *)fNodes->UncheckedAt(level); } //////////////////////////////////////////////////////////////////////////////// @@ -389,7 +416,8 @@ TGeoNode *TGeoPhysicalNode::GetNode(Int_t level) const TGeoVolume *TGeoPhysicalNode::GetVolume(Int_t level) const { TGeoNode *node = GetNode(level); - if (node) return node->GetVolume(); + if (node) + return node->GetVolume(); return 0; } @@ -399,7 +427,8 @@ TGeoVolume *TGeoPhysicalNode::GetVolume(Int_t level) const TGeoShape *TGeoPhysicalNode::GetShape(Int_t level) const { TGeoVolume *vol = GetVolume(level); - if (vol) return vol->GetShape(); + if (vol) + return vol->GetShape(); return 0; } @@ -409,8 +438,9 @@ TGeoShape *TGeoPhysicalNode::GetShape(Int_t level) const void TGeoPhysicalNode::Paint(Option_t * /*option*/) { TVirtualGeoPainter *painter = gGeoManager->GetGeomPainter(); - if (!painter) return; -// painter->PaintNode(this, option); + if (!painter) + return; + // painter->PaintNode(this, option); } //////////////////////////////////////////////////////////////////////////////// @@ -419,14 +449,18 @@ void TGeoPhysicalNode::Paint(Option_t * /*option*/) void TGeoPhysicalNode::Print(Option_t * /*option*/) const { printf("TGeoPhysicalNode: %s level=%d aligned=%d\n", fName.Data(), fLevel, IsAligned()); - for (Int_t i=0; i<=fLevel; i++) { + for (Int_t i = 0; i <= fLevel; i++) { printf(" level %d: node %s\n", i, GetNode(i)->GetName()); printf(" local matrix:\n"); - if (GetNode(i)->GetMatrix()->IsIdentity()) printf(" IDENTITY\n"); - else GetNode(i)->GetMatrix()->Print(); + if (GetNode(i)->GetMatrix()->IsIdentity()) + printf(" IDENTITY\n"); + else + GetNode(i)->GetMatrix()->Print(); printf(" global matrix:\n"); - if (GetMatrix(i)->IsIdentity()) printf(" IDENTITY\n"); - else GetMatrix(i)->Print(); + if (GetMatrix(i)->IsIdentity()) + printf(" IDENTITY\n"); + else + GetMatrix(i)->Print(); } if (IsAligned() && fMatrixOrig) { printf(" original local matrix:\n"); @@ -450,35 +484,38 @@ void TGeoPhysicalNode::SetBranchAsState() { TGeoNodeCache *cache = gGeoManager->GetCache(); if (!cache) { - Error("SetBranchAsState","no state available"); + Error("SetBranchAsState", "no state available"); return; } if (!cache->IsDummy()) { Error("SetBranchAsState", "not implemented for full cache"); return; } - if (!fNodes) fNodes = new TObjArray(30); - if (!fMatrices) fMatrices = new TObjArray(30); - TGeoHMatrix **matrices = (TGeoHMatrix **) cache->GetMatrices(); - TGeoNode **branch = (TGeoNode **) cache->GetBranch(); - - Bool_t refresh = (fLevel>0)?kTRUE:kFALSE; + if (!fNodes) + fNodes = new TObjArray(30); + if (!fMatrices) + fMatrices = new TObjArray(30); + TGeoHMatrix **matrices = (TGeoHMatrix **)cache->GetMatrices(); + TGeoNode **branch = (TGeoNode **)cache->GetBranch(); + + Bool_t refresh = (fLevel > 0) ? kTRUE : kFALSE; if (refresh) { TGeoHMatrix *current; - for (Int_t i=0; i<=fLevel; i++) { - fNodes->AddAtAndExpand(branch[i],i); - current = (TGeoHMatrix*)fMatrices->UncheckedAt(i); + for (Int_t i = 0; i <= fLevel; i++) { + fNodes->AddAtAndExpand(branch[i], i); + current = (TGeoHMatrix *)fMatrices->UncheckedAt(i); *current = *matrices[i]; } return; } fLevel = gGeoManager->GetLevel(); - for (Int_t i=0; i<=fLevel; i++) { - fNodes->AddAtAndExpand(branch[i],i); - fMatrices->AddAtAndExpand(new TGeoHMatrix(*matrices[i]),i); + for (Int_t i = 0; i <= fLevel; i++) { + fNodes->AddAtAndExpand(branch[i], i); + fMatrices->AddAtAndExpand(new TGeoHMatrix(*matrices[i]), i); } - TGeoNode *node = (TGeoNode*)fNodes->UncheckedAt(fLevel); - if (!fMatrixOrig) fMatrixOrig = new TGeoHMatrix(); + TGeoNode *node = (TGeoNode *)fNodes->UncheckedAt(fLevel); + if (!fMatrixOrig) + fMatrixOrig = new TGeoHMatrix(); *fMatrixOrig = node->GetMatrix(); } @@ -488,7 +525,8 @@ void TGeoPhysicalNode::SetBranchAsState() void TGeoPhysicalNode::SetMatrixOrig(const TGeoMatrix *local) { - if (!fMatrixOrig) fMatrixOrig = new TGeoHMatrix(); + if (!fMatrixOrig) + fMatrixOrig = new TGeoHMatrix(); if (!local) { fMatrixOrig->Clear(); return; @@ -502,7 +540,7 @@ void TGeoPhysicalNode::SetMatrixOrig(const TGeoMatrix *local) Bool_t TGeoPhysicalNode::SetPath(const char *path) { if (!gGeoManager->cd(path)) { - Error("SetPath","wrong path -> maybe RestoreMasterVolume"); + Error("SetPath", "wrong path -> maybe RestoreMasterVolume"); return kFALSE; } SetBranchAsState(); @@ -516,12 +554,13 @@ Bool_t TGeoPhysicalNode::IsMatchingState(TGeoNavigator *nav) const { TGeoNodeCache *cache = nav->GetCache(); if (!cache) { - Fatal("SetBranchAsState","no state available"); + Fatal("SetBranchAsState", "no state available"); return kFALSE; } - TGeoNode **branch = (TGeoNode **) cache->GetBranch(); - for (Int_t i=1; i<=fLevel; i++) - if (fNodes->At(i) != branch[i]) return kFALSE; + TGeoNode **branch = (TGeoNode **)cache->GetBranch(); + for (Int_t i = 1; i <= fLevel; i++) + if (fNodes->At(i) != branch[i]) + return kFALSE; return kTRUE; } @@ -540,8 +579,7 @@ TGeoPNEntry::TGeoPNEntry() //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoPNEntry::TGeoPNEntry(const char *name, const char *path) - :TNamed(name, path) +TGeoPNEntry::TGeoPNEntry(const char *name, const char *path) : TNamed(name, path) { if (!gGeoManager || !gGeoManager->IsClosed() || !gGeoManager->CheckPath(path)) { TString errmsg("Cannot define a physical node link without a closed geometry and a valid path !"); @@ -563,7 +601,8 @@ TGeoPNEntry::TGeoPNEntry(const char *name, const char *path) TGeoPNEntry::~TGeoPNEntry() { - if (fMatrix && !fMatrix->IsRegistered()) delete fMatrix; + if (fMatrix && !fMatrix->IsRegistered()) + delete fMatrix; delete fGlobalOrig; } diff --git a/geom/geom/src/TGeoPolygon.cxx b/geom/geom/src/TGeoPolygon.cxx index 8e5216caf3886..c548761a49066 100644 --- a/geom/geom/src/TGeoPolygon.cxx +++ b/geom/geom/src/TGeoPolygon.cxx @@ -64,12 +64,12 @@ ClassImp(TGeoPolygon); TGeoPolygon::TGeoPolygon() { - fNvert = 0; + fNvert = 0; fNconvex = 0; - fInd = nullptr; - fIndc = nullptr; - fX = nullptr; - fY = nullptr; + fInd = nullptr; + fIndc = nullptr; + fX = nullptr; + fY = nullptr; fDaughters = nullptr; SetConvex(kFALSE); TObject::SetBit(kGeoFinishPolygon, kFALSE); @@ -80,16 +80,16 @@ TGeoPolygon::TGeoPolygon() TGeoPolygon::TGeoPolygon(Int_t nvert) { - if (nvert<3) { + if (nvert < 3) { Fatal("Ctor", "Invalid number of vertices %i", nvert); return; } - fNvert = nvert; + fNvert = nvert; fNconvex = 0; - fInd = new Int_t[nvert]; - fIndc = nullptr; - fX = nullptr; - fY = nullptr; + fInd = new Int_t[nvert]; + fIndc = nullptr; + fX = nullptr; + fY = nullptr; fDaughters = nullptr; SetConvex(kFALSE); TObject::SetBit(kGeoFinishPolygon, kFALSE); @@ -101,8 +101,10 @@ TGeoPolygon::TGeoPolygon(Int_t nvert) TGeoPolygon::~TGeoPolygon() { - if (fInd) delete [] fInd; - if (fIndc) delete [] fIndc; + if (fInd) + delete[] fInd; + if (fIndc) + delete[] fIndc; if (fDaughters) { fDaughters->Delete(); delete fDaughters; @@ -113,13 +115,13 @@ TGeoPolygon::~TGeoPolygon() Double_t TGeoPolygon::Area() const { - Int_t ic,i,j; + Int_t ic, i, j; Double_t area = 0; // Compute area of the convex part - for (ic=0; icGetEntriesFast(); - for (i=0; iUncheckedAt(i); - if (poly->Contains(point)) return kFALSE; + for (i = 0; i < nd; i++) { + poly = (TGeoPolygon *)fDaughters->UncheckedAt(i); + if (poly->Contains(point)) + return kFALSE; } return kTRUE; } @@ -147,18 +152,19 @@ Bool_t TGeoPolygon::Contains(const Double_t *point) const void TGeoPolygon::ConvexCheck() { - if (fNvert==3) { + if (fNvert == 3) { SetConvex(); return; } - Int_t j,k; + Int_t j, k; Double_t point[2]; - for (Int_t i=0; iGetGeomPainter()->DrawPolygon(this); } @@ -184,44 +191,50 @@ void TGeoPolygon::FinishPolygon() // find outscribed convex polygon indices OutscribedConvex(); if (IsConvex()) { -// printf(" -> polygon convex -> same indices\n"); - memcpy(fIndc, fInd, fNvert*sizeof(Int_t)); + // printf(" -> polygon convex -> same indices\n"); + memcpy(fIndc, fInd, fNvert * sizeof(Int_t)); return; } -// printf(" -> polygon NOT convex\n"); + // printf(" -> polygon NOT convex\n"); // make daughters if necessary - if (IsConvex()) return; + if (IsConvex()) + return; // ... algorithm here - if (!fDaughters) fDaughters = new TObjArray(); + if (!fDaughters) + fDaughters = new TObjArray(); TGeoPolygon *poly = 0; Int_t indconv = 0; Int_t indnext, indback; Int_t nskip; while (indconv < fNconvex) { - indnext = (indconv+1)%fNconvex; - nskip = fIndc[indnext]-fIndc[indconv]; - if (nskip<0) nskip+=fNvert; - if (nskip==1) { + indnext = (indconv + 1) % fNconvex; + nskip = fIndc[indnext] - fIndc[indconv]; + if (nskip < 0) + nskip += fNvert; + if (nskip == 1) { indconv++; continue; } // gap -> make polygon - poly = new TGeoPolygon(nskip+1); - poly->SetXY(fX,fY); + poly = new TGeoPolygon(nskip + 1); + poly->SetXY(fX, fY); poly->SetNextIndex(fInd[fIndc[indconv]]); poly->SetNextIndex(fInd[fIndc[indnext]]); - indback = fIndc[indnext]-1; - if (indback < 0) indback+=fNvert; + indback = fIndc[indnext] - 1; + if (indback < 0) + indback += fNvert; while (indback != fIndc[indconv]) { poly->SetNextIndex(fInd[indback]); indback--; - if (indback < 0) indback+=fNvert; + if (indback < 0) + indback += fNvert; } poly->FinishPolygon(); fDaughters->Add(poly); indconv++; } - for (indconv=0; indconv fNvert) break; - ivnew = (iseg+2)%fNvert; + if (iseg + 2 > fNvert) + break; + ivnew = (iseg + 2) % fNvert; conv = kFALSE; // check iseg with next vertices while (ivnew) { @@ -324,31 +344,35 @@ void TGeoPolygon::OutscribedConvex() conv = kTRUE; break; } - ivnew = (ivnew+1)%fNvert; + ivnew = (ivnew + 1) % fNvert; } if (!conv) { -// Error("OutscribedConvex","NO convex line connection to vertex %d\n", iseg); + // Error("OutscribedConvex","NO convex line connection to vertex %d\n", iseg); iseg++; continue; } } else { - ivnew = (iseg+1)%fNvert; + ivnew = (iseg + 1) % fNvert; } // segment belonging to convex outscribed polygon - if (!fNconvex) indconv[fNconvex++] = iseg; - else if (indconv[fNconvex-1] != iseg) indconv[fNconvex++] = iseg; - if (iseg1) { - dpx = point[0]-p2[0]; - dpy = point[1]-p2[1]; + u = (dpx * dx + dpy * dy) / lsq; + if (u > 1) { + dpx = point[0] - p2[0]; + dpy = point[1] - p2[1]; } else { - if (u>=0) { - dpx -= u*dx; - dpy -= u*dy; + if (u >= 0) { + dpx -= u * dx; + dpy -= u * dy; } } - ssq = dpx*dpx + dpy*dpy; + ssq = dpx * dpx + dpy * dpy; if (ssq < safe) { safe = ssq; isegmin = i1; @@ -404,7 +428,8 @@ Double_t TGeoPolygon::Safety(const Double_t *point, Int_t &isegment) const } isegment = isegmin; safe = TMath::Sqrt(safe); -// printf("== segment %d: (%f, %f) - (%f, %f) safe=%f\n", isegment, fX[isegment],fY[isegment],fX[(isegment+1)%fNvert],fY[(isegment+1)%fNvert],safe); + // printf("== segment %d: (%f, %f) - (%f, %f) safe=%f\n", isegment, + // fX[isegment],fY[isegment],fX[(isegment+1)%fNvert],fY[(isegment+1)%fNvert],safe); return safe; } @@ -415,8 +440,9 @@ Double_t TGeoPolygon::Safety(const Double_t *point, Int_t &isegment) const void TGeoPolygon::SetNextIndex(Int_t index) { Int_t i; - if (index <0) { - for (i=0; i= fNvert) { @@ -425,11 +451,15 @@ void TGeoPolygon::SetNextIndex(Int_t index) } fInd[fNconvex++] = index; if (fNconvex == fNvert) { - if (!fX || !fY) return; + if (!fX || !fY) + return; Double_t area = 0.0; - for (i=0; iGetEntriesFast(); - for (i=0; iAt(i); - if (poly) poly->SetXY(x,y); + for (i = 0; i < nd; i++) { + poly = (TGeoPolygon *)fDaughters->At(i); + if (poly) + poly->SetXY(x, y); } } diff --git a/geom/geom/src/TGeoScaledShape.cxx b/geom/geom/src/TGeoScaledShape.cxx index 21fb33a8fd5c5..2e6304d02fa13 100644 --- a/geom/geom/src/TGeoScaledShape.cxx +++ b/geom/geom/src/TGeoScaledShape.cxx @@ -9,7 +9,6 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ - #include #include "TGeoManager.h" @@ -39,18 +38,16 @@ TGeoScaledShape::TGeoScaledShape() fScale = 0; } - //////////////////////////////////////////////////////////////////////////////// /// Constructor -TGeoScaledShape::TGeoScaledShape(const char *name, TGeoShape *shape, TGeoScale *scale) - :TGeoBBox(name,0,0,0) +TGeoScaledShape::TGeoScaledShape(const char *name, TGeoShape *shape, TGeoScale *scale) : TGeoBBox(name, 0, 0, 0) { fShape = shape; fScale = scale; - if (!fScale->IsRegistered()) fScale->RegisterYourself(); + if (!fScale->IsRegistered()) + fScale->RegisterYourself(); TGeoScaledShape::ComputeBBox(); - } //////////////////////////////////////////////////////////////////////////////// @@ -60,16 +57,15 @@ TGeoScaledShape::TGeoScaledShape(TGeoShape *shape, TGeoScale *scale) { fShape = shape; fScale = scale; - if (!fScale->IsRegistered()) fScale->RegisterYourself(); + if (!fScale->IsRegistered()) + fScale->RegisterYourself(); TGeoScaledShape::ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoScaledShape::~TGeoScaledShape() -{ -} +TGeoScaledShape::~TGeoScaledShape() {} //////////////////////////////////////////////////////////////////////////////// /// Computes capacity of this shape [length^3] @@ -78,7 +74,7 @@ Double_t TGeoScaledShape::Capacity() const { Double_t capacity = fShape->Capacity(); const Double_t *scale = fScale->GetScale(); - capacity *= scale[0]*scale[1]*scale[2]; + capacity *= scale[0] * scale[1] * scale[2]; return capacity; } @@ -91,8 +87,9 @@ void TGeoScaledShape::ComputeBBox() Error("ComputeBBox", "Scaled shape %s without shape", GetName()); return; } - if (fShape->IsAssembly()) fShape->ComputeBBox(); - TGeoBBox *box = (TGeoBBox*)fShape; + if (fShape->IsAssembly()) + fShape->ComputeBBox(); + TGeoBBox *box = (TGeoBBox *)fShape; const Double_t *orig = box->GetOrigin(); Double_t point[3], master[3]; point[0] = box->GetDX(); @@ -112,11 +109,11 @@ void TGeoScaledShape::ComputeBBox() void TGeoScaledShape::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { Double_t local[3], ldir[3], lnorm[3]; - fScale->MasterToLocal(point,local); - fScale->MasterToLocalVect(dir,ldir); + fScale->MasterToLocal(point, local); + fScale->MasterToLocalVect(dir, ldir); TGeoMatrix::Normalize(ldir); - fShape->ComputeNormal(local,ldir,lnorm); -// fScale->LocalToMasterVect(lnorm, norm); + fShape->ComputeNormal(local, ldir, lnorm); + // fScale->LocalToMasterVect(lnorm, norm); fScale->MasterToLocalVect(lnorm, norm); TGeoMatrix::Normalize(norm); } @@ -127,7 +124,7 @@ void TGeoScaledShape::ComputeNormal(const Double_t *point, const Double_t *dir, Bool_t TGeoScaledShape::Contains(const Double_t *point) const { Double_t local[3]; - fScale->MasterToLocal(point,local); + fScale->MasterToLocal(point, local); return fShape->Contains(local); } @@ -143,40 +140,43 @@ Int_t TGeoScaledShape::DistancetoPrimitive(Int_t px, Int_t py) //////////////////////////////////////////////////////////////////////////////// /// Compute distance from inside point to surface of the scaled shape. -Double_t TGeoScaledShape::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoScaledShape::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { Double_t local[3], ldir[3]; Double_t lstep; - fScale->MasterToLocal(point,local); + fScale->MasterToLocal(point, local); lstep = fScale->MasterToLocal(step, dir); - fScale->MasterToLocalVect(dir,ldir); + fScale->MasterToLocalVect(dir, ldir); TGeoMatrix::Normalize(ldir); - Double_t dist = fShape->DistFromInside(local,ldir, iact, lstep, safe); - if (iact<3 && safe) *safe = fScale->LocalToMaster(*safe); + Double_t dist = fShape->DistFromInside(local, ldir, iact, lstep, safe); + if (iact < 3 && safe) + *safe = fScale->LocalToMaster(*safe); dist = fScale->LocalToMaster(dist, ldir); return dist; } - //////////////////////////////////////////////////////////////////////////////// /// Compute distance from outside point to surface of the scaled shape. -Double_t TGeoScaledShape::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoScaledShape::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { Double_t local[3], ldir[3]; Double_t lstep; -// printf("DistFromOutside(%f,%f,%f, %f,%f,%f)\n", point[0], point[1], point[2], dir[0], dir[1],dir[2]); - fScale->MasterToLocal(point,local); -// printf("local: %f,%f,%f\n", local[0],local[1], local[2]); + // printf("DistFromOutside(%f,%f,%f, %f,%f,%f)\n", point[0], point[1], point[2], dir[0], dir[1],dir[2]); + fScale->MasterToLocal(point, local); + // printf("local: %f,%f,%f\n", local[0],local[1], local[2]); lstep = fScale->MasterToLocal(step, dir); - fScale->MasterToLocalVect(dir,ldir); + fScale->MasterToLocalVect(dir, ldir); TGeoMatrix::Normalize(ldir); -// printf("localdir: %f,%f,%f\n",ldir[0],ldir[1],ldir[2]); - Double_t dist = fShape->DistFromOutside(local,ldir, iact, lstep, safe); -// printf("local distance: %f\n", dist); - if (safe) *safe = fScale->LocalToMaster(*safe); + // printf("localdir: %f,%f,%f\n",ldir[0],ldir[1],ldir[2]); + Double_t dist = fShape->DistFromOutside(local, ldir, iact, lstep, safe); + // printf("local distance: %f\n", dist); + if (safe) + *safe = fScale->LocalToMaster(*safe); dist = fScale->LocalToMaster(dist, ldir); -// printf("converted distance: %f\n",dist); + // printf("converted distance: %f\n",dist); return dist; } @@ -184,7 +184,7 @@ Double_t TGeoScaledShape::DistFromOutside(const Double_t *point, const Double_t /// Cannot divide assemblies. TGeoVolume *TGeoScaledShape::Divide(TGeoVolume * /*voldiv*/, const char *divname, Int_t /*iaxis*/, Int_t /*ndiv*/, - Double_t /*start*/, Double_t /*step*/) + Double_t /*start*/, Double_t /*step*/) { Error("Divide", "Scaled shapes cannot be divided. Division volume %s not created", divname); return 0; @@ -193,12 +193,13 @@ TGeoVolume *TGeoScaledShape::Divide(TGeoVolume * /*voldiv*/, const char *divname //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoScaledShape::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoScaledShape::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { TBuffer3D &buffer = (TBuffer3D &)fShape->GetBuffer3D(reqSections, localFrame); + buffer.fScaled = kTRUE; -// TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); - Double_t halfLengths[3] = { fDX, fDY, fDZ }; + // TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); + Double_t halfLengths[3] = {fDX, fDY, fDZ}; buffer.SetAABoundingBox(fOrigin, halfLengths); if (!buffer.fLocalFrame) { TransformPoints(buffer.fBBVertex[0], 8); @@ -265,7 +266,8 @@ Bool_t TGeoScaledShape::IsReflected() const TBuffer3D *TGeoScaledShape::MakeBuffer3D() const { TBuffer3D *buff = fShape->MakeBuffer3D(); - if (buff) SetPoints(buff->fPnts); + if (buff) + SetPoints(buff->fPnts); return buff; } @@ -277,12 +279,11 @@ TGeoShape *TGeoScaledShape::MakeScaledShape(const char *name, TGeoShape *shape, TGeoShape *old_shape = shape; TGeoShape *new_shape = nullptr; if (shape->IsA() == TGeoScaledShape::Class()) { - TGeoScaledShape *sshape = (TGeoScaledShape*)shape; + TGeoScaledShape *sshape = (TGeoScaledShape *)shape; TGeoScale *old_scale = sshape->GetScale(); old_shape = sshape->GetShape(); - scale->SetScale(scale->GetScale()[0]*old_scale->GetScale()[0], - scale->GetScale()[1]*old_scale->GetScale()[1], - scale->GetScale()[2]*old_scale->GetScale()[2]); + scale->SetScale(scale->GetScale()[0] * old_scale->GetScale()[0], scale->GetScale()[1] * old_scale->GetScale()[1], + scale->GetScale()[2] * old_scale->GetScale()[2]); } if (old_shape->IsAssembly()) { // The shape is owned by the assembly, so make sure it does not register to TGeoManager @@ -309,8 +310,8 @@ void TGeoScaledShape::SetSegsAndPols(TBuffer3D &buff) const Double_t TGeoScaledShape::Safety(const Double_t *point, Bool_t in) const { Double_t local[3]; - fScale->MasterToLocal(point,local); - Double_t safe = fShape->Safety(local,in); + fScale->MasterToLocal(point, local); + Double_t safe = fShape->Safety(local, in); safe = fScale->LocalToMaster(safe); return safe; } @@ -320,7 +321,8 @@ Double_t TGeoScaledShape::Safety(const Double_t *point, Bool_t in) const void TGeoScaledShape::SavePrimitive(std::ostream &out, Option_t *option) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; if (!fShape || !fScale) { out << "##### Invalid shape or scale !. Aborting. #####" << std::endl; @@ -330,10 +332,10 @@ void TGeoScaledShape::SavePrimitive(std::ostream &out, Option_t *option) TString sname = fShape->GetPointerName(); const Double_t *sc = fScale->GetScale(); out << " // Scale factor:" << std::endl; - out << " auto pScale_" << GetPointerName() << " = new TGeoScale(\"" << fScale->GetName() - << "\"," << sc[0] << "," << sc[1] << "," << sc[2] << ");" << std::endl; - out << " TGeoScaledShape *" << GetPointerName() << " = new TGeoScaledShape(\"" - << GetName() << "\"," << sname << ", pScale_" << GetPointerName() << " );" << std::endl; + out << " auto pScale_" << GetPointerName() << " = new TGeoScale(\"" << fScale->GetName() << "\"," << sc[0] << "," + << sc[1] << "," << sc[2] << ");" << std::endl; + out << " TGeoScaledShape *" << GetPointerName() << " = new TGeoScaledShape(\"" << GetName() << "\"," << sname + << ", pScale_" << GetPointerName() << " );" << std::endl; } //////////////////////////////////////////////////////////////////////////////// @@ -344,9 +346,9 @@ void TGeoScaledShape::SetPoints(Double_t *points) const Int_t npts = fShape->GetNmeshVertices(); fShape->SetPoints(points); Double_t master[3]; - for (Int_t i=0; iLocalToMaster(&points[3*i], master); - memcpy(&points[3*i], master, 3*sizeof(Double_t)); + for (Int_t i = 0; i < npts; i++) { + fScale->LocalToMaster(&points[3 * i], master); + memcpy(&points[3 * i], master, 3 * sizeof(Double_t)); } } @@ -360,15 +362,15 @@ void TGeoScaledShape::SetPoints(Float_t *points) const Double_t master[3]; Double_t local[3]; Int_t index; - for (Int_t i=0; iLocalToMaster(local, master); points[index] = master[0]; - points[index+1] = master[1]; - points[index+2] = master[2]; + points[index + 1] = master[1]; + points[index + 2] = master[2]; } } @@ -379,7 +381,8 @@ void TGeoScaledShape::SetPoints(Float_t *points) const void TGeoScaledShape::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i 2 => compute only the distance to exiting, ignoring anything else. -#### `Double_t TGeoShape::DistFromOutside(Double_t *point[3], Double_t *dir[3], Int_t iact, Double_t step, Double_t *safe)` +#### `Double_t TGeoShape::DistFromOutside(Double_t *point[3], Double_t *dir[3], Int_t iact, Double_t step, Double_t +*safe)` computes the distance to entering a shape from a given point OUTSIDE. Acts in the same way as B). @@ -157,7 +159,7 @@ are interpreted and which is their result inside specific shape classes. ClassImp(TGeoShape); TGeoMatrix *TGeoShape::fgTransform = NULL; -Double_t TGeoShape::fgEpsMch = 2.220446049250313e-16; +Double_t TGeoShape::fgEpsMch = 2.220446049250313e-16; //////////////////////////////////////////////////////////////////////////////// /// Default constructor @@ -165,23 +167,22 @@ Double_t TGeoShape::fgEpsMch = 2.220446049250313e-16; TGeoShape::TGeoShape() { fShapeBits = 0; - fShapeId = 0; + fShapeId = 0; if (!gGeoManager) { gGeoManager = new TGeoManager("Geometry", "default geometry"); // gROOT->AddGeoManager(gGeoManager); } -// fShapeId = gGeoManager->GetListOfShapes()->GetSize(); -// gGeoManager->AddShape(this); + // fShapeId = gGeoManager->GetListOfShapes()->GetSize(); + // gGeoManager->AddShape(this); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor -TGeoShape::TGeoShape(const char *name) - :TNamed(name, "") +TGeoShape::TGeoShape(const char *name) : TNamed(name, "") { fShapeBits = 0; - fShapeId = 0; + fShapeId = 0; if (!gGeoManager) { gGeoManager = new TGeoManager("Geometry", "default geometry"); // gROOT->AddGeoManager(gGeoManager); @@ -195,7 +196,8 @@ TGeoShape::TGeoShape(const char *name) TGeoShape::~TGeoShape() { - if (gGeoManager && !gGeoManager->IsCleaning()) gGeoManager->GetListOfShapes()->Remove(this); + if (gGeoManager && !gGeoManager->IsCleaning()) + gGeoManager->GetListOfShapes()->Remove(this); } //////////////////////////////////////////////////////////////////////////////// @@ -209,10 +211,10 @@ TGeoShape::~TGeoShape() void TGeoShape::CheckShape(Int_t testNo, Int_t nsamples, Option_t *option) { if (!gGeoManager) { - Error("CheckShape","No geometry manager"); + Error("CheckShape", "No geometry manager"); return; } - TGeoShape *shape = (TGeoShape*)this; + TGeoShape *shape = (TGeoShape *)this; gGeoManager->CheckShape(shape, testNo, nsamples, option); } @@ -225,7 +227,7 @@ Double_t TGeoShape::ComputeEpsMch() Double_t temp1 = 1.0; Double_t temp2 = 1.0 + temp1; Double_t mchEps = 0.; - while (temp2>1.0) { + while (temp2 > 1.0) { mchEps = temp1; temp1 /= 2; temp2 = 1.0 + temp1; @@ -235,7 +237,7 @@ Double_t TGeoShape::ComputeEpsMch() } //////////////////////////////////////////////////////////////////////////////// -///static function returning the machine round-off error +/// static function returning the machine round-off error Double_t TGeoShape::EpsMch() { @@ -259,21 +261,26 @@ const char *TGeoShape::GetName() const Int_t TGeoShape::ShapeDistancetoPrimitive(Int_t numpoints, Int_t px, Int_t py) const { TVirtualGeoPainter *painter = gGeoManager->GetGeomPainter(); - if (!painter) return 9999; + if (!painter) + return 9999; return painter->ShapeDistancetoPrimitive(this, numpoints, px, py); } //////////////////////////////////////////////////////////////////////////////// /// True if point is closer than epsil to one of the phi planes defined by c1,s1 or c2,s2 -Bool_t TGeoShape::IsCloseToPhi(Double_t epsil, const Double_t *point, Double_t c1, Double_t s1, Double_t c2, Double_t s2) +Bool_t +TGeoShape::IsCloseToPhi(Double_t epsil, const Double_t *point, Double_t c1, Double_t s1, Double_t c2, Double_t s2) { Double_t saf1 = TGeoShape::Big(); Double_t saf2 = TGeoShape::Big(); - if (point[0]*c1+point[1]*s1 >= 0) saf1 = TMath::Abs(-point[0]*s1 + point[1]*c1); - if (point[0]*c2+point[1]*s2 >= 0) saf2 = TMath::Abs(point[0]*s2 - point[1]*c2); - Double_t saf = TMath::Min(saf1,saf2); - if (saf= 0) + saf1 = TMath::Abs(-point[0] * s1 + point[1] * c1); + if (point[0] * c2 + point[1] * s2 >= 0) + saf2 = TMath::Abs(point[0] * s2 - point[1] * c2); + Double_t saf = TMath::Min(saf1, saf2); + if (saf < epsil) + return kTRUE; return kFALSE; } @@ -283,9 +290,11 @@ Bool_t TGeoShape::IsCloseToPhi(Double_t epsil, const Double_t *point, Double_t c Bool_t TGeoShape::IsInPhiRange(const Double_t *point, Double_t phi1, Double_t phi2) { Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - while (phiphi2-phi1) return kFALSE; + while (phi < phi1) + phi += 360.; + Double_t ddp = phi - phi1; + if (ddp > phi2 - phi1) + return kFALSE; return kTRUE; } @@ -294,29 +303,32 @@ Bool_t TGeoShape::IsInPhiRange(const Double_t *point, Double_t phi1, Double_t ph /// also radius at crossing point. This might be negative in case the crossing is /// on the other side of the semiplane. -Bool_t TGeoShape::IsCrossingSemiplane(const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, Double_t &snext, Double_t &rxy) +Bool_t TGeoShape::IsCrossingSemiplane(const Double_t *point, const Double_t *dir, Double_t cphi, Double_t sphi, + Double_t &snext, Double_t &rxy) { snext = rxy = TGeoShape::Big(); Double_t nx = -sphi; Double_t ny = cphi; - Double_t rxy0 = point[0]*cphi+point[1]*sphi; - Double_t rdotn = point[0]*nx + point[1]*ny; - if (TMath::Abs(rdotn)eps) return kFALSE; + if (TMath::Abs(y3 - (a1 + b1 * x3)) > eps) + return kFALSE; // Aligned segments, are they overlapping - if ((x3-x1)*(x3-x2)<-eps || (x4-x1)*(x4-x2)<-eps || - (x1-x3)*(x1-x4)<-eps || (x2-x3)*(x2-x4)<-eps) return kTRUE; + if ((x3 - x1) * (x3 - x2) < -eps || (x4 - x1) * (x4 - x2) < -eps || (x1 - x3) * (x1 - x4) < -eps || + (x2 - x3) * (x2 - x4) < -eps) + return kTRUE; return kFALSE; } - xm = (a1-a2)/(b2-b1); - ym = (a1*b2-a2*b1)/(b2-b1); + xm = (a1 - a2) / (b2 - b1); + ym = (a1 * b2 - a2 * b1) / (b2 - b1); } } // Check if crossing point is both between A,B and C,D - Double_t check = (xm-x1)*(xm-x2)+(ym-y1)*(ym-y2); - if (check > -eps) return kFALSE; - check = (xm-x3)*(xm-x4)+(ym-y3)*(ym-y4); - if (check > -eps) return kFALSE; + Double_t check = (xm - x1) * (xm - x2) + (ym - y1) * (ym - y2); + if (check > -eps) + return kFALSE; + check = (xm - x3) * (xm - x4) + (ym - y3) * (ym - y4); + if (check > -eps) + return kFALSE; return kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from point (inside phi) to both phi planes. Return minimum. -Double_t TGeoShape::DistToPhiMin(const Double_t *point, const Double_t *dir, Double_t s1, Double_t c1, - Double_t s2, Double_t c2, Double_t sm, Double_t cm, Bool_t in) +Double_t TGeoShape::DistToPhiMin(const Double_t *point, const Double_t *dir, Double_t s1, Double_t c1, Double_t s2, + Double_t c2, Double_t sm, Double_t cm, Bool_t in) { - Double_t sfi1=TGeoShape::Big(); - Double_t sfi2=TGeoShape::Big(); - Double_t s=0; - Double_t un = dir[0]*s1-dir[1]*c1; - if (!in) un=-un; - if (un>0) { - s=-point[0]*s1+point[1]*c1; - if (!in) s=-s; - if (s>=0) { + Double_t sfi1 = TGeoShape::Big(); + Double_t sfi2 = TGeoShape::Big(); + Double_t s = 0; + Double_t un = dir[0] * s1 - dir[1] * c1; + if (!in) + un = -un; + if (un > 0) { + s = -point[0] * s1 + point[1] * c1; + if (!in) + s = -s; + if (s >= 0) { s /= un; - if (((point[0]+s*dir[0])*sm-(point[1]+s*dir[1])*cm)>=0) sfi1=s; + if (((point[0] + s * dir[0]) * sm - (point[1] + s * dir[1]) * cm) >= 0) + sfi1 = s; } } - un = -dir[0]*s2+dir[1]*c2; - if (!in) un=-un; - if (un>0) { - s=point[0]*s2-point[1]*c2; - if (!in) s=-s; - if (s>=0) { + un = -dir[0] * s2 + dir[1] * c2; + if (!in) + un = -un; + if (un > 0) { + s = point[0] * s2 - point[1] * c2; + if (!in) + s = -s; + if (s >= 0) { s /= un; - if ((-(point[0]+s*dir[0])*sm+(point[1]+s*dir[1])*cm)>=0) sfi2=s; + if ((-(point[0] + s * dir[0]) * sm + (point[1] + s * dir[1]) * cm) >= 0) + sfi2 = s; } } return TMath::Min(sfi1, sfi2); @@ -434,24 +461,27 @@ Double_t TGeoShape::DistToPhiMin(const Double_t *point, const Double_t *dir, Dou //////////////////////////////////////////////////////////////////////////////// /// Static method to compute normal to phi planes. -void TGeoShape::NormalPhi(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t c1, Double_t s1, Double_t c2, Double_t s2) +void TGeoShape::NormalPhi(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t c1, Double_t s1, + Double_t c2, Double_t s2) { Double_t saf1 = TGeoShape::Big(); Double_t saf2 = TGeoShape::Big(); - if (point[0]*c1+point[1]*s1 >= 0) saf1 = TMath::Abs(-point[0]*s1 + point[1]*c1); - if (point[0]*c2+point[1]*s2 >= 0) saf2 = TMath::Abs(point[0]*s2 - point[1]*c2); - Double_t c,s; - if (saf1= 0) + saf1 = TMath::Abs(-point[0] * s1 + point[1] * c1); + if (point[0] * c2 + point[1] * s2 >= 0) + saf2 = TMath::Abs(point[0] * s2 - point[1] * c2); + Double_t c, s; + if (saf1 < saf2) { + c = c1; + s = s1; } else { - c=c2; - s=s2; + c = c2; + s = s2; } norm[2] = 0; norm[0] = -s; norm[1] = c; - if (dir[0]*norm[0]+dir[1]*norm[1] < 0) { + if (dir[0] * norm[0] + dir[1] * norm[1] < 0) { norm[0] = s; norm[1] = -c; } @@ -464,25 +494,29 @@ void TGeoShape::NormalPhi(const Double_t *point, const Double_t *dir, Double_t * Double_t TGeoShape::SafetyPhi(const Double_t *point, Bool_t in, Double_t phi1, Double_t phi2) { Bool_t inphi = TGeoShape::IsInPhiRange(point, phi1, phi2); - if (inphi && !in) return -TGeoShape::Big(); + if (inphi && !in) + return -TGeoShape::Big(); phi1 *= TMath::DegToRad(); phi2 *= TMath::DegToRad(); Double_t c1 = TMath::Cos(phi1); Double_t s1 = TMath::Sin(phi1); Double_t c2 = TMath::Cos(phi2); Double_t s2 = TMath::Sin(phi2); - Double_t rsq = point[0]*point[0]+point[1]*point[1]; - Double_t rproj = point[0]*c1+point[1]*s1; - Double_t safsq = rsq-rproj*rproj; - if (safsq<0) return 0.; - Double_t saf1 = (rproj<0)?TGeoShape::Big():TMath::Sqrt(safsq); - rproj = point[0]*c2+point[1]*s2; - safsq = rsq-rproj*rproj; - if (safsq<0) return 0.; - Double_t saf2 = (rproj<0)?TGeoShape::Big():TMath::Sqrt(safsq); + Double_t rsq = point[0] * point[0] + point[1] * point[1]; + Double_t rproj = point[0] * c1 + point[1] * s1; + Double_t safsq = rsq - rproj * rproj; + if (safsq < 0) + return 0.; + Double_t saf1 = (rproj < 0) ? TGeoShape::Big() : TMath::Sqrt(safsq); + rproj = point[0] * c2 + point[1] * s2; + safsq = rsq - rproj * rproj; + if (safsq < 0) + return 0.; + Double_t saf2 = (rproj < 0) ? TGeoShape::Big() : TMath::Sqrt(safsq); Double_t safe = TMath::Min(saf1, saf2); // >0 - if (safe>1E10) { - if (in) return TGeoShape::Big(); + if (safe > 1E10) { + if (in) + return TGeoShape::Big(); return -TGeoShape::Big(); } return safe; @@ -493,29 +527,33 @@ Double_t TGeoShape::SafetyPhi(const Double_t *point, Bool_t in, Double_t phi1, D Double_t TGeoShape::SafetySeg(Double_t r, Double_t z, Double_t r1, Double_t z1, Double_t r2, Double_t z2, Bool_t outer) { - Double_t crossp = (z2-z1)*(r-r1)-(z-z1)*(r2-r1); + Double_t crossp = (z2 - z1) * (r - r1) - (z - z1) * (r2 - r1); crossp *= (outer) ? 1. : -1.; // Positive crossp means point on the requested side of the (1,2) segment if (crossp < -TGeoShape::Tolerance()) { -// if (((z-z1)*(z2-z)) > -1.E-10) return 0; - if (outer) return TGeoShape::Big(); - else return 0.; + // if (((z-z1)*(z2-z)) > -1.E-10) return 0; + if (outer) + return TGeoShape::Big(); + else + return 0.; } // Compute (1,P) dot (1,2) - Double_t c1 = (z-z1)*(z2-z1)+(r-r1)*(r2-r1); + Double_t c1 = (z - z1) * (z2 - z1) + (r - r1) * (r2 - r1); // Negative c1 means point (1) is closest - if (c1<1.E-10) return TMath::Sqrt((r-r1)*(r-r1)+(z-z1)*(z-z1)); + if (c1 < 1.E-10) + return TMath::Sqrt((r - r1) * (r - r1) + (z - z1) * (z - z1)); // Compute (2,P) dot (1,2) - Double_t c2 = (z-z2)*(z2-z1)+(r-r2)*(r2-r1); + Double_t c2 = (z - z2) * (z2 - z1) + (r - r2) * (r2 - r1); // Positive c2 means point (2) is closest - if (c2>-1.E-10) return TMath::Sqrt((r-r2)*(r-r2)+(z-z2)*(z-z2)); + if (c2 > -1.E-10) + return TMath::Sqrt((r - r2) * (r - r2) + (z - z2) * (z - z2)); // The closest point is between (1) and (2) - c2 = (z2-z1)*(z2-z1)+(r2-r1)*(r2-r1); + c2 = (z2 - z1) * (z2 - z1) + (r2 - r1) * (r2 - r1); // projected length factor with respect to (1,2) length - Double_t alpha = c1/c2; - Double_t rp = r1 + alpha*(r2-r1); - Double_t zp = z1 + alpha*(z2-z1); - return TMath::Sqrt((r-rp)*(r-rp)+(z-zp)*(z-zp)); + Double_t alpha = c1 / c2; + Double_t rp = r1 + alpha * (r2 - r1); + Double_t zp = z1 + alpha * (z2 - z1); + return TMath::Sqrt((r - rp) * (r - rp) + (z - zp) * (z - zp)); } //////////////////////////////////////////////////////////////////////////////// @@ -551,34 +589,39 @@ void TGeoShape::SetTransform(TGeoMatrix *matrix) void TGeoShape::TransformPoints(Double_t *points, UInt_t NbPnts) const { - UInt_t i,j; + UInt_t i, j; Double_t dmaster[3]; if (fgTransform) { for (j = 0; j < NbPnts; j++) { - i = 3*j; + i = 3 * j; fgTransform->LocalToMaster(&points[i], dmaster); - points[i] = dmaster[0]; - points[i+1] = dmaster[1]; - points[i+2] = dmaster[2]; + points[i] = dmaster[0]; + points[i + 1] = dmaster[1]; + points[i + 2] = dmaster[2]; } return; } - if (!gGeoManager) return; - Bool_t bomb = (gGeoManager->GetBombMode()==0)?kFALSE:kTRUE; + if (!gGeoManager) + return; + Bool_t bomb = (gGeoManager->GetBombMode() == 0) ? kFALSE : kTRUE; for (j = 0; j < NbPnts; j++) { - i = 3*j; + i = 3 * j; if (gGeoManager->IsMatrixTransform()) { TGeoHMatrix *glmat = gGeoManager->GetGLMatrix(); - if (bomb) glmat->LocalToMasterBomb(&points[i], dmaster); - else glmat->LocalToMaster(&points[i], dmaster); + if (bomb) + glmat->LocalToMasterBomb(&points[i], dmaster); + else + glmat->LocalToMaster(&points[i], dmaster); } else { - if (bomb) gGeoManager->LocalToMasterBomb(&points[i], dmaster); - else gGeoManager->LocalToMaster(&points[i],dmaster); + if (bomb) + gGeoManager->LocalToMasterBomb(&points[i], dmaster); + else + gGeoManager->LocalToMaster(&points[i], dmaster); } - points[i] = dmaster[0]; - points[i+1] = dmaster[1]; - points[i+2] = dmaster[2]; + points[i] = dmaster[0]; + points[i + 1] = dmaster[1]; + points[i + 2] = dmaster[2]; } } @@ -586,7 +629,7 @@ void TGeoShape::TransformPoints(Double_t *points, UInt_t NbPnts) const /// Fill the supplied buffer, with sections in desired frame /// See TBuffer3D.h for explanation of sections, frame etc. -void TGeoShape::FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t localFrame) const +void TGeoShape::FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const { // Catch this common potential error here // We have to set kRawSize (unless already done) to allocate buffer space @@ -606,21 +649,22 @@ void TGeoShape::FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t local R__ASSERT(kFALSE); return; } - const TGeoVolume * paintVolume = gGeoManager->GetPaintVolume(); - if (!paintVolume) paintVolume = gGeoManager->GetTopVolume(); + const TGeoVolume *paintVolume = gGeoManager->GetPaintVolume(); + if (!paintVolume) + paintVolume = gGeoManager->GetTopVolume(); if (!paintVolume) { buffer.fID = const_cast(this); buffer.fColor = 0; buffer.fTransparency = 0; -// R__ASSERT(kFALSE); -// return; + // R__ASSERT(kFALSE); + // return; } else { buffer.fID = const_cast(paintVolume); buffer.fColor = paintVolume->GetLineColor(); buffer.fTransparency = paintVolume->GetTransparency(); Double_t visdensity = gGeoManager->GetVisDensity(); - if (visdensity>0 && paintVolume->GetMedium()) { + if (visdensity > 0 && paintVolume->GetMedium()) { if (paintVolume->GetMaterial()->GetDensity() < visdensity) { buffer.fTransparency = 90; } @@ -628,28 +672,29 @@ void TGeoShape::FillBuffer3D(TBuffer3D & buffer, Int_t reqSections, Bool_t local } buffer.fLocalFrame = localFrame; - Bool_t r1,r2=kFALSE; + Bool_t r1, r2 = kFALSE; r1 = gGeoManager->IsMatrixReflection(); if (paintVolume && paintVolume->GetShape()) { if (paintVolume->GetShape()->IsReflected()) { - // Temporary trick to deal with reflected shapes. - // Still lighting gets wrong... - if (buffer.Type() < TBuffer3DTypes::kTube) r2 = kTRUE; + // Temporary trick to deal with reflected shapes. + // Still lighting gets wrong... + if (buffer.Type() < TBuffer3DTypes::kTube) + r2 = kTRUE; } } - buffer.fReflection = ((r1&(!r2))|(r2&!(r1))); + buffer.fReflection = ((r1 & (!r2)) | (r2 & !(r1))); // Set up local -> master translation matrix if (localFrame) { - TGeoMatrix * localMasterMat = 0; + TGeoMatrix *localMasterMat = 0; if (TGeoShape::GetTransform()) { localMasterMat = TGeoShape::GetTransform(); } else { localMasterMat = gGeoManager->GetCurrentMatrix(); - // For overlap drawing the correct matrix needs to obtained in - // from GetGLMatrix() - this should not be applied in the case - // of composite shapes + // For overlap drawing the correct matrix needs to obtained in + // from GetGLMatrix() - this should not be applied in the case + // of composite shapes if (gGeoManager->IsMatrixTransform() && !IsComposite()) { localMasterMat = gGeoManager->GetGLMatrix(); } @@ -674,10 +719,11 @@ Int_t TGeoShape::GetBasicColor() const { Int_t basicColor = 0; // TODO: Check on sensible fallback if (gGeoManager) { - const TGeoVolume * volume = gGeoManager->GetPaintVolume(); + const TGeoVolume *volume = gGeoManager->GetPaintVolume(); if (volume) { - basicColor = ((volume->GetLineColor() %8) -1) * 4; - if (basicColor < 0) basicColor = 0; + basicColor = ((volume->GetLineColor() % 8) - 1) * 4; + if (basicColor < 0) + basicColor = 0; } } return basicColor; @@ -689,7 +735,8 @@ Int_t TGeoShape::GetBasicColor() const const TBuffer3D &TGeoShape::GetBuffer3D(Int_t /*reqSections*/, Bool_t /*localFrame*/) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); - Warning("GetBuffer3D", "this must be implemented for shapes in a TGeoPainter hierarchy. This will be come a pure virtual fn eventually."); + Warning("GetBuffer3D", "this must be implemented for shapes in a TGeoPainter hierarchy. This will be come a pure " + "virtual fn eventually."); return buffer; } @@ -700,8 +747,10 @@ const char *TGeoShape::GetPointerName() const { static TString name; Int_t uid = GetUniqueID(); - if (uid) name = TString::Format("p%s_%d", GetName(),uid); - else name = TString::Format("p%s", GetName()); + if (uid) + name = TString::Format("p%s_%d", GetName(), uid); + else + name = TString::Format("p%s", GetName()); return name.Data(); } @@ -710,7 +759,8 @@ const char *TGeoShape::GetPointerName() const void TGeoShape::ExecuteEvent(Int_t event, Int_t px, Int_t py) { - if (!gGeoManager) return; + if (!gGeoManager) + return; TVirtualGeoPainter *painter = gGeoManager->GetPainter(); painter->ExecuteShapeEvent(this, event, px, py); } @@ -724,7 +774,7 @@ void TGeoShape::Draw(Option_t *option) if (option && option[0]) { painter->DrawShape(this, option); } else { - painter->DrawShape(this, gEnv->GetValue("Viewer3D.DefaultDrawOption","")); + painter->DrawShape(this, gEnv->GetValue("Viewer3D.DefaultDrawOption", "")); } } @@ -737,6 +787,6 @@ void TGeoShape::Paint(Option_t *option) if (option && option[0]) { painter->PaintShape(this, option); } else { - painter->PaintShape(this, gEnv->GetValue("Viewer3D.DefaultDrawOption","")); + painter->PaintShape(this, gEnv->GetValue("Viewer3D.DefaultDrawOption", "")); } } diff --git a/geom/geom/src/TGeoShapeAssembly.cxx b/geom/geom/src/TGeoShapeAssembly.cxx index 069415ae97f88..ef6ad5bbe1e91 100644 --- a/geom/geom/src/TGeoShapeAssembly.cxx +++ b/geom/geom/src/TGeoShapeAssembly.cxx @@ -33,27 +33,23 @@ ClassImp(TGeoShapeAssembly); TGeoShapeAssembly::TGeoShapeAssembly() { - fVolume = 0; + fVolume = 0; fBBoxOK = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Constructor specifying hyperboloid parameters. TGeoShapeAssembly::TGeoShapeAssembly(TGeoVolumeAssembly *vol) { - fVolume = vol; + fVolume = vol; fBBoxOK = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoShapeAssembly::~TGeoShapeAssembly() -{ -} +TGeoShapeAssembly::~TGeoShapeAssembly() {} //////////////////////////////////////////////////////////////////////////////// /// Compute bounding box of the assembly @@ -65,9 +61,13 @@ void TGeoShapeAssembly::ComputeBBox() return; } // Make sure bbox is computed only once or recomputed only if invalidated (by alignment) - if (fBBoxOK) return; + if (fBBoxOK) + return; Int_t nd = fVolume->GetNdaughters(); - if (!nd) {fBBoxOK = kTRUE; return;} + if (!nd) { + fBBoxOK = kTRUE; + return; + } TGeoNode *node; TGeoBBox *box; Double_t xmin, xmax, ymin, ymax, zmin, zmax; @@ -75,29 +75,37 @@ void TGeoShapeAssembly::ComputeBBox() xmax = ymax = zmax = -TGeoShape::Big(); Double_t vert[24]; Double_t pt[3]; - for (Int_t i=0; iGetNode(i); // Make sure that all assembly daughters have computed their bboxes - if (node->GetVolume()->IsAssembly()) node->GetVolume()->GetShape()->ComputeBBox(); - box = (TGeoBBox*)node->GetVolume()->GetShape(); + if (node->GetVolume()->IsAssembly()) + node->GetVolume()->GetShape()->ComputeBBox(); + box = (TGeoBBox *)node->GetVolume()->GetShape(); box->SetBoxPoints(vert); - for (Int_t ipt=0; ipt<8; ipt++) { - node->LocalToMaster(&vert[3*ipt], pt); - if (pt[0]xmax) xmax=pt[0]; - if (pt[1]ymax) ymax=pt[1]; - if (pt[2]zmax) zmax=pt[2]; + for (Int_t ipt = 0; ipt < 8; ipt++) { + node->LocalToMaster(&vert[3 * ipt], pt); + if (pt[0] < xmin) + xmin = pt[0]; + if (pt[0] > xmax) + xmax = pt[0]; + if (pt[1] < ymin) + ymin = pt[1]; + if (pt[1] > ymax) + ymax = pt[1]; + if (pt[2] < zmin) + zmin = pt[2]; + if (pt[2] > zmax) + zmax = pt[2]; } } - fDX = 0.5*(xmax-xmin); - fOrigin[0] = 0.5*(xmin+xmax); - fDY = 0.5*(ymax-ymin); - fOrigin[1] = 0.5*(ymin+ymax); - fDZ = 0.5*(zmax-zmin); - fOrigin[2] = 0.5*(zmin+zmax); - if (fDX>0 && fDY>0 && fDZ>0) fBBoxOK = kTRUE; + fDX = 0.5 * (xmax - xmin); + fOrigin[0] = 0.5 * (xmin + xmax); + fDY = 0.5 * (ymax - ymin); + fOrigin[1] = 0.5 * (ymin + ymax); + fDZ = 0.5 * (zmax - zmin); + fOrigin[2] = 0.5 * (zmin + zmax); + if (fDX > 0 && fDY > 0 && fDZ > 0) + fBBoxOK = kTRUE; } //////////////////////////////////////////////////////////////////////////////// @@ -110,40 +118,46 @@ void TGeoShapeAssembly::RecomputeBoxLast() Warning("RecomputeBoxLast", "No daughters for volume %s yet", fVolume->GetName()); return; } - TGeoNode *node = fVolume->GetNode(nd-1); + TGeoNode *node = fVolume->GetNode(nd - 1); Double_t xmin, xmax, ymin, ymax, zmin, zmax; - if (nd==1) { + if (nd == 1) { xmin = ymin = zmin = TGeoShape::Big(); xmax = ymax = zmax = -TGeoShape::Big(); } else { - xmin = fOrigin[0]-fDX; - xmax = fOrigin[0]+fDX; - ymin = fOrigin[1]-fDY; - ymax = fOrigin[1]+fDY; - zmin = fOrigin[2]-fDZ; - zmax = fOrigin[2]+fDZ; + xmin = fOrigin[0] - fDX; + xmax = fOrigin[0] + fDX; + ymin = fOrigin[1] - fDY; + ymax = fOrigin[1] + fDY; + zmin = fOrigin[2] - fDZ; + zmax = fOrigin[2] + fDZ; } Double_t vert[24]; Double_t pt[3]; - TGeoBBox *box = (TGeoBBox*)node->GetVolume()->GetShape(); - if (TGeoShape::IsSameWithinTolerance(box->GetDX(), 0) || - node->GetVolume()->IsAssembly()) node->GetVolume()->GetShape()->ComputeBBox(); + TGeoBBox *box = (TGeoBBox *)node->GetVolume()->GetShape(); + if (TGeoShape::IsSameWithinTolerance(box->GetDX(), 0) || node->GetVolume()->IsAssembly()) + node->GetVolume()->GetShape()->ComputeBBox(); box->SetBoxPoints(vert); - for (Int_t ipt=0; ipt<8; ipt++) { - node->LocalToMaster(&vert[3*ipt], pt); - if (pt[0]xmax) xmax=pt[0]; - if (pt[1]ymax) ymax=pt[1]; - if (pt[2]zmax) zmax=pt[2]; + for (Int_t ipt = 0; ipt < 8; ipt++) { + node->LocalToMaster(&vert[3 * ipt], pt); + if (pt[0] < xmin) + xmin = pt[0]; + if (pt[0] > xmax) + xmax = pt[0]; + if (pt[1] < ymin) + ymin = pt[1]; + if (pt[1] > ymax) + ymax = pt[1]; + if (pt[2] < zmin) + zmin = pt[2]; + if (pt[2] > zmax) + zmax = pt[2]; } - fDX = 0.5*(xmax-xmin); - fOrigin[0] = 0.5*(xmin+xmax); - fDY = 0.5*(ymax-ymin); - fOrigin[1] = 0.5*(ymin+ymax); - fDZ = 0.5*(zmax-zmin); - fOrigin[2] = 0.5*(zmin+zmax); + fDX = 0.5 * (xmax - xmin); + fOrigin[0] = 0.5 * (xmin + xmax); + fDY = 0.5 * (ymax - ymin); + fOrigin[1] = 0.5 * (ymin + ymax); + fDZ = 0.5 * (zmax - zmin); + fOrigin[2] = 0.5 * (zmin + zmax); fBBoxOK = kTRUE; } @@ -152,22 +166,23 @@ void TGeoShapeAssembly::RecomputeBoxLast() void TGeoShapeAssembly::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - if (!fBBoxOK) ((TGeoShapeAssembly*)this)->ComputeBBox(); + if (!fBBoxOK) + ((TGeoShapeAssembly *)this)->ComputeBBox(); Int_t inext = fVolume->GetNextNodeIndex(); - if (inext<0) { - DistFromOutside(point,dir,3); + if (inext < 0) { + DistFromOutside(point, dir, 3); inext = fVolume->GetNextNodeIndex(); - if (inext<0) { - Error("ComputeNormal","Invalid inext=%i (Ncomponents=%i)",inext,fVolume->GetNdaughters()); + if (inext < 0) { + Error("ComputeNormal", "Invalid inext=%i (Ncomponents=%i)", inext, fVolume->GetNdaughters()); return; } } TGeoNode *node = fVolume->GetNode(inext); - Double_t local[3],ldir[3],lnorm[3]; - node->MasterToLocal(point,local); - node->MasterToLocalVect(dir,ldir); - node->GetVolume()->GetShape()->ComputeNormal(local,ldir,lnorm); - node->LocalToMasterVect(lnorm,norm); + Double_t local[3], ldir[3], lnorm[3]; + node->MasterToLocal(point, local); + node->MasterToLocalVect(dir, ldir); + node->GetVolume()->GetShape()->ComputeNormal(local, ldir, lnorm); + node->LocalToMasterVect(lnorm, norm); } //////////////////////////////////////////////////////////////////////////////// @@ -175,8 +190,10 @@ void TGeoShapeAssembly::ComputeNormal(const Double_t *point, const Double_t *dir Bool_t TGeoShapeAssembly::Contains(const Double_t *point) const { - if (!fBBoxOK) ((TGeoShapeAssembly*)this)->ComputeBBox(); - if (!TGeoBBox::Contains(point)) return kFALSE; + if (!fBBoxOK) + ((TGeoShapeAssembly *)this)->ComputeBBox(); + if (!TGeoBBox::Contains(point)) + return kFALSE; TGeoVoxelFinder *voxels = fVolume->GetVoxels(); TGeoNode *node; TGeoShape *shape; @@ -192,10 +209,10 @@ Bool_t TGeoShapeAssembly::Contains(const Double_t *point) const nav->GetCache()->ReleaseInfo(); return kFALSE; } - for (id=0; idGetNode(check_list[id]); shape = node->GetVolume()->GetShape(); - node->MasterToLocal(point,local); + node->MasterToLocal(point, local); if (shape->Contains(local)) { fVolume->SetCurrentNodeIndex(check_list[id]); fVolume->SetNextNodeIndex(check_list[id]); @@ -207,10 +224,10 @@ Bool_t TGeoShapeAssembly::Contains(const Double_t *point) const return kFALSE; } Int_t nd = fVolume->GetNdaughters(); - for (id=0; idGetNode(id); shape = node->GetVolume()->GetShape(); - node->MasterToLocal(point,local); + node->MasterToLocal(point, local); if (shape->Contains(local)) { fVolume->SetCurrentNodeIndex(id); fVolume->SetNextNodeIndex(id); @@ -231,34 +248,39 @@ Int_t TGeoShapeAssembly::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/) //////////////////////////////////////////////////////////////////////////////// /// Compute distance from inside point to surface of the hyperboloid. -Double_t TGeoShapeAssembly::DistFromInside(const Double_t * /*point*/, const Double_t * /*dir*/, Int_t /*iact*/, Double_t /*step*/, Double_t * /*safe*/) const +Double_t TGeoShapeAssembly::DistFromInside(const Double_t * /*point*/, const Double_t * /*dir*/, Int_t /*iact*/, + Double_t /*step*/, Double_t * /*safe*/) const { Info("DistFromInside", "Cannot compute distance from inside the assembly (but from a component)"); return TGeoShape::Big(); } - //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the hyperboloid. /// fVolume->SetNextNodeIndex(-1); -Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { #ifdef TGEO_DEBUG - static int indent=0; + static int indent = 0; indent++; TString sindent = ""; - for (Int_t k=0; kComputeBBox(); - if (iact<3 && safe) { + if (!fBBoxOK) + ((TGeoShapeAssembly *)this)->ComputeBBox(); + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); #ifdef TGEO_DEBUG indent--; #endif - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); #ifdef TGEO_DEBUG indent++; #endif @@ -270,55 +292,63 @@ Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_ Double_t pt[3]; Int_t i; Bool_t found = kFALSE; - memcpy(pt,point,3*sizeof(Double_t)); + memcpy(pt, point, 3 * sizeof(Double_t)); #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] assembly %s checking distance to %d daughters...\n", sindent.Data(), indent, fVolume->GetName(), fVolume->GetNdaughters()); + if (idebug > 4) + printf("%s[%d] assembly %s checking distance to %d daughters...\n", sindent.Data(), indent, fVolume->GetName(), + fVolume->GetNdaughters()); #endif if (!TGeoBBox::Contains(point)) { snext = TGeoBBox::DistFromOutside(point, dir, 3, stepmax); // Approach bounding box to minimize errors - snext = TMath::Min(0.01*snext, 1.E-6); + snext = TMath::Min(0.01 * snext, 1.E-6); #ifdef TGEO_DEBUG - if (idebug>4 && snext > stepmax) printf("%s[%d] %s: bbox not crossed\n",sindent.Data(), indent, fVolume->GetName()); + if (idebug > 4 && snext > stepmax) + printf("%s[%d] %s: bbox not crossed\n", sindent.Data(), indent, fVolume->GetName()); indent--; #endif - if (snext > stepmax) return TGeoShape::Big(); + if (snext > stepmax) + return TGeoShape::Big(); #ifdef TGEO_DEBUG indent++; #endif - for (i=0; i<3; i++) pt[i] += snext*dir[i]; + for (i = 0; i < 3; i++) + pt[i] += snext * dir[i]; // if (Contains(pt)) { #ifdef TGEO_DEBUG -// if (idebug>4) printf("%s[%d] Propagation to BBox of %s entered the component %s at %f\n", sindent.Data(), indent, fVolume->GetName(), fVolume->GetNode(fVolume->GetCurrentNodeIndex())->GetName(), snext); -// indent--; +// if (idebug>4) printf("%s[%d] Propagation to BBox of %s entered the component %s at %f\n", sindent.Data(), +// indent, fVolume->GetName(), fVolume->GetNode(fVolume->GetCurrentNodeIndex())->GetName(), snext); indent--; #endif -// fVolume->SetNextNodeIndex(fVolume->GetCurrentNodeIndex()); -// return snext; -// } -// snext += TGeoShape::Tolerance(); + // fVolume->SetNextNodeIndex(fVolume->GetCurrentNodeIndex()); + // return snext; + // } + // snext += TGeoShape::Tolerance(); stepmax -= snext; } // Point represented by pt is now inside the bounding box - find distance to components Int_t nd = fVolume->GetNdaughters(); TGeoNode *node; - Double_t lpoint[3],ldir[3]; + Double_t lpoint[3], ldir[3]; TGeoVoxelFinder *voxels = fVolume->GetVoxels(); - if (nd<5 || !voxels) { - for (i=0; iGetNode(i); - if (voxels && voxels->IsSafeVoxel(pt, i, stepmax)) continue; + if (voxels && voxels->IsSafeVoxel(pt, i, stepmax)) + continue; node->MasterToLocal(pt, lpoint); node->MasterToLocalVect(dir, ldir); #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] distance to %s ...\n", sindent.Data(), indent, node->GetName()); + if (idebug > 4) + printf("%s[%d] distance to %s ...\n", sindent.Data(), indent, node->GetName()); #endif dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax); - if (dist4) { + if (idebug > 4) { printf("%s[%d] %s -> from local=(%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", - sindent.Data(), indent, fVolume->GetName(), lpoint[0],lpoint[1],lpoint[2],ldir[0],ldir[1],ldir[2]); + sindent.Data(), indent, fVolume->GetName(), lpoint[0], lpoint[1], lpoint[2], ldir[0], ldir[1], + ldir[2]); printf("%s[%d] -> (l)to: %s shape %s snext=%g\n", sindent.Data(), indent, node->GetName(), node->GetVolume()->GetShape()->ClassName(), dist); } @@ -332,13 +362,16 @@ Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_ if (found) { snext += stepmax; #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] %s: found %s at %f\n", sindent.Data(), indent, fVolume->GetName(), fVolume->GetNode(fVolume->GetNextNodeIndex())->GetName(), snext); + if (idebug > 4) + printf("%s[%d] %s: found %s at %f\n", sindent.Data(), indent, fVolume->GetName(), + fVolume->GetNode(fVolume->GetNextNodeIndex())->GetName(), snext); indent--; #endif return snext; } #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] %s: no daughter crossed\n", sindent.Data(), indent, fVolume->GetName()); + if (idebug > 4) + printf("%s[%d] %s: no daughter crossed\n", sindent.Data(), indent, fVolume->GetName()); indent--; #endif return TGeoShape::Big(); @@ -350,20 +383,22 @@ Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_ TGeoStateInfo &td = *nav->GetCache()->GetInfo(); voxels->SortCrossedVoxels(pt, dir, td); - while ((vlist=voxels->GetNextVoxel(pt, dir, ncheck, td))) { - for (i=0; iGetNextVoxel(pt, dir, ncheck, td))) { + for (i = 0; i < ncheck; i++) { node = fVolume->GetNode(vlist[i]); node->MasterToLocal(pt, lpoint); node->MasterToLocalVect(dir, ldir); #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] distance to %s ...\n", sindent.Data(), indent, node->GetName()); + if (idebug > 4) + printf("%s[%d] distance to %s ...\n", sindent.Data(), indent, node->GetName()); #endif dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax); - if (dist4) { + if (idebug > 4) { printf("%s[%d] %s -> from local=(%19.16f, %19.16f, %19.16f, %19.16f, %19.16f, %19.16f)\n", - sindent.Data(), indent, fVolume->GetName(), lpoint[0],lpoint[1],lpoint[2], ldir[0],ldir[1],ldir[2]); + sindent.Data(), indent, fVolume->GetName(), lpoint[0], lpoint[1], lpoint[2], ldir[0], ldir[1], + ldir[2]); printf("%s[%d] -> to: %s shape %s snext=%g\n", sindent.Data(), indent, node->GetName(), node->GetVolume()->GetShape()->ClassName(), dist); } @@ -378,13 +413,16 @@ Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_ if (found) { snext += stepmax; #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] %s: found %s at %f\n", sindent.Data(), indent, fVolume->GetName(), fVolume->GetNode(fVolume->GetNextNodeIndex())->GetName(), snext); + if (idebug > 4) + printf("%s[%d] %s: found %s at %f\n", sindent.Data(), indent, fVolume->GetName(), + fVolume->GetNode(fVolume->GetNextNodeIndex())->GetName(), snext); indent--; #endif return snext; } #ifdef TGEO_DEBUG - if (idebug>4) printf("%s[%d] %s: no daughter crossed\n", sindent.Data(), indent, fVolume->GetName()); + if (idebug > 4) + printf("%s[%d] %s: no daughter crossed\n", sindent.Data(), indent, fVolume->GetName()); indent--; #endif return TGeoShape::Big(); @@ -394,7 +432,7 @@ Double_t TGeoShapeAssembly::DistFromOutside(const Double_t *point, const Double_ /// Cannot divide assemblies. TGeoVolume *TGeoShapeAssembly::Divide(TGeoVolume * /*voldiv*/, const char *divname, Int_t /*iaxis*/, Int_t /*ndiv*/, - Double_t /*start*/, Double_t /*step*/) + Double_t /*start*/, Double_t /*step*/) { Error("Divide", "Assemblies cannot be divided. Division volume %s not created", divname); return 0; @@ -418,7 +456,8 @@ void TGeoShapeAssembly::InspectShape() const printf("*** Shape %s: TGeoShapeAssembly ***\n", GetName()); printf(" Volume assembly %s with %i nodes\n", fVolume->GetName(), fVolume->GetNdaughters()); printf(" Bounding box:\n"); - if (!fBBoxOK) ((TGeoShapeAssembly*)this)->ComputeBBox(); + if (!fBBoxOK) + ((TGeoShapeAssembly *)this)->ComputeBBox(); TGeoBBox::InspectShape(); } @@ -438,19 +477,20 @@ Double_t TGeoShapeAssembly::Safety(const Double_t *point, Bool_t in) const { Double_t safety = TGeoShape::Big(); Double_t pt[3], loc[3]; - if (!fBBoxOK) ((TGeoShapeAssembly*)this)->ComputeBBox(); + if (!fBBoxOK) + ((TGeoShapeAssembly *)this)->ComputeBBox(); if (in) { Int_t index = fVolume->GetCurrentNodeIndex(); TGeoVolume *vol = fVolume; TGeoNode *node; - memcpy(loc, point, 3*sizeof(Double_t)); - while (index>=0) { - memcpy(pt, loc, 3*sizeof(Double_t)); + memcpy(loc, point, 3 * sizeof(Double_t)); + while (index >= 0) { + memcpy(pt, loc, 3 * sizeof(Double_t)); node = vol->GetNode(index); - node->GetMatrix()->MasterToLocal(pt,loc); + node->GetMatrix()->MasterToLocal(pt, loc); vol = node->GetVolume(); index = vol->GetCurrentNodeIndex(); - if (index<0) { + if (index < 0) { safety = vol->GetShape()->Safety(loc, in); return safety; } @@ -461,27 +501,37 @@ Double_t TGeoShapeAssembly::Safety(const Double_t *point, Bool_t in) const TGeoVoxelFinder *voxels = fVolume->GetVoxels(); Int_t nd = fVolume->GetNdaughters(); Double_t *boxes = 0; - if (voxels) boxes = voxels->GetBoxes(); + if (voxels) + boxes = voxels->GetBoxes(); TGeoNode *node; - for (Int_t id=0; id0) { - Int_t ist = 6*id; + for (Int_t id = 0; id < nd; id++) { + if (boxes && id > 0) { + Int_t ist = 6 * id; Double_t dxyz = 0.; - Double_t dxyz0 = TMath::Abs(point[0]-boxes[ist+3])-boxes[ist]; - if (dxyz0 > safety) continue; - Double_t dxyz1 = TMath::Abs(point[1]-boxes[ist+4])-boxes[ist+1]; - if (dxyz1 > safety) continue; - Double_t dxyz2 = TMath::Abs(point[2]-boxes[ist+5])-boxes[ist+2]; - if (dxyz2 > safety) continue; - if (dxyz0>0) dxyz+=dxyz0*dxyz0; - if (dxyz1>0) dxyz+=dxyz1*dxyz1; - if (dxyz2>0) dxyz+=dxyz2*dxyz2; - if (dxyz >= safety*safety) continue; + Double_t dxyz0 = TMath::Abs(point[0] - boxes[ist + 3]) - boxes[ist]; + if (dxyz0 > safety) + continue; + Double_t dxyz1 = TMath::Abs(point[1] - boxes[ist + 4]) - boxes[ist + 1]; + if (dxyz1 > safety) + continue; + Double_t dxyz2 = TMath::Abs(point[2] - boxes[ist + 5]) - boxes[ist + 2]; + if (dxyz2 > safety) + continue; + if (dxyz0 > 0) + dxyz += dxyz0 * dxyz0; + if (dxyz1 > 0) + dxyz += dxyz1 * dxyz1; + if (dxyz2 > 0) + dxyz += dxyz2 * dxyz2; + if (dxyz >= safety * safety) + continue; } node = fVolume->GetNode(id); safe = node->Safety(point, kFALSE); - if (safe<=0.0) return 0.0; - if (safe=90)) || ((fTheta2<=90) && (fTheta1>=90))) { + r1min = TMath::Min(fRmax * st1, fRmax * st2); + r1max = TMath::Max(fRmax * st1, fRmax * st2); + r2min = TMath::Min(fRmin * st1, fRmin * st2); + r2max = TMath::Max(fRmin * st1, fRmin * st2); + if (((fTheta1 <= 90) && (fTheta2 >= 90)) || ((fTheta2 <= 90) && (fTheta1 >= 90))) { r1max = fRmax; r2max = fRmin; } @@ -171,51 +166,64 @@ void TGeoSphere::ComputeBBox() Double_t xc[4]; Double_t yc[4]; - xc[0] = rmax*TMath::Cos(fPhi1*TMath::DegToRad()); - yc[0] = rmax*TMath::Sin(fPhi1*TMath::DegToRad()); - xc[1] = rmax*TMath::Cos(fPhi2*TMath::DegToRad()); - yc[1] = rmax*TMath::Sin(fPhi2*TMath::DegToRad()); - xc[2] = rmin*TMath::Cos(fPhi1*TMath::DegToRad()); - yc[2] = rmin*TMath::Sin(fPhi1*TMath::DegToRad()); - xc[3] = rmin*TMath::Cos(fPhi2*TMath::DegToRad()); - yc[3] = rmin*TMath::Sin(fPhi2*TMath::DegToRad()); + xc[0] = rmax * TMath::Cos(fPhi1 * TMath::DegToRad()); + yc[0] = rmax * TMath::Sin(fPhi1 * TMath::DegToRad()); + xc[1] = rmax * TMath::Cos(fPhi2 * TMath::DegToRad()); + yc[1] = rmax * TMath::Sin(fPhi2 * TMath::DegToRad()); + xc[2] = rmin * TMath::Cos(fPhi1 * TMath::DegToRad()); + yc[2] = rmin * TMath::Sin(fPhi1 * TMath::DegToRad()); + xc[3] = rmin * TMath::Cos(fPhi2 * TMath::DegToRad()); + yc[3] = rmin * TMath::Sin(fPhi2 * TMath::DegToRad()); Double_t xmin = xc[TMath::LocMin(4, &xc[0])]; Double_t xmax = xc[TMath::LocMax(4, &xc[0])]; Double_t ymin = yc[TMath::LocMin(4, &yc[0])]; Double_t ymax = yc[TMath::LocMax(4, &yc[0])]; - Double_t dp = fPhi2-fPhi1; - if (dp<0) dp+=360; + Double_t dp = fPhi2 - fPhi1; + if (dp < 0) + dp += 360; Double_t ddp = -fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) xmax = rmax; - ddp = 90-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) ymax = rmax; - ddp = 180-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) xmin = -rmax; - ddp = 270-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) ymin = -rmax; - xc[0] = fRmax*TMath::Cos(fTheta1*TMath::DegToRad()); - xc[1] = fRmax*TMath::Cos(fTheta2*TMath::DegToRad()); - xc[2] = fRmin*TMath::Cos(fTheta1*TMath::DegToRad()); - xc[3] = fRmin*TMath::Cos(fTheta2*TMath::DegToRad()); + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + xmax = rmax; + ddp = 90 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + ymax = rmax; + ddp = 180 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + xmin = -rmax; + ddp = 270 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + ymin = -rmax; + xc[0] = fRmax * TMath::Cos(fTheta1 * TMath::DegToRad()); + xc[1] = fRmax * TMath::Cos(fTheta2 * TMath::DegToRad()); + xc[2] = fRmin * TMath::Cos(fTheta1 * TMath::DegToRad()); + xc[3] = fRmin * TMath::Cos(fTheta2 * TMath::DegToRad()); Double_t zmin = xc[TMath::LocMin(4, &xc[0])]; Double_t zmax = xc[TMath::LocMax(4, &xc[0])]; - - fOrigin[0] = (xmax+xmin)/2; - fOrigin[1] = (ymax+ymin)/2; - fOrigin[2] = (zmax+zmin)/2;; - fDX = (xmax-xmin)/2; - fDY = (ymax-ymin)/2; - fDZ = (zmax-zmin)/2; + fOrigin[0] = (xmax + xmin) / 2; + fOrigin[1] = (ymax + ymin) / 2; + fOrigin[2] = (zmax + zmin) / 2; + ; + fDX = (xmax - xmin) / 2; + fDY = (ymax - ymin) / 2; + fDZ = (zmax - zmin) / 2; } //////////////////////////////////////////////////////////////////////////////// @@ -223,52 +231,58 @@ void TGeoSphere::ComputeBBox() void TGeoSphere::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - Double_t rxy2 = point[0]*point[0]+point[1]*point[1]; - Double_t r2 = rxy2+point[2]*point[2]; - Double_t r=TMath::Sqrt(r2); - Bool_t rzero=kFALSE; - if (r<=1E-20) rzero=kTRUE; - //localize theta - Double_t phi=0; - Double_t th=0.; - if (!rzero) th = TMath::ACos(point[2]/r); - - //localize phi - phi=TMath::ATan2(point[1], point[0]); + Double_t rxy2 = point[0] * point[0] + point[1] * point[1]; + Double_t r2 = rxy2 + point[2] * point[2]; + Double_t r = TMath::Sqrt(r2); + Bool_t rzero = kFALSE; + if (r <= 1E-20) + rzero = kTRUE; + // localize theta + Double_t phi = 0; + Double_t th = 0.; + if (!rzero) + th = TMath::ACos(point[2] / r); + + // localize phi + phi = TMath::ATan2(point[1], point[0]); Double_t saf[4]; - saf[0]=(TGeoShape::IsSameWithinTolerance(fRmin,0) && !TestShapeBit(kGeoThetaSeg) && !TestShapeBit(kGeoPhiSeg))?TGeoShape::Big():TMath::Abs(r-fRmin); - saf[1]=TMath::Abs(fRmax-r); - saf[2]=saf[3]= TGeoShape::Big(); + saf[0] = (TGeoShape::IsSameWithinTolerance(fRmin, 0) && !TestShapeBit(kGeoThetaSeg) && !TestShapeBit(kGeoPhiSeg)) + ? TGeoShape::Big() + : TMath::Abs(r - fRmin); + saf[1] = TMath::Abs(fRmax - r); + saf[2] = saf[3] = TGeoShape::Big(); if (TestShapeBit(kGeoThetaSeg)) { - if (fTheta1>0) { - saf[2] = r*TMath::Abs(TMath::Sin(th-fTheta1*TMath::DegToRad())); + if (fTheta1 > 0) { + saf[2] = r * TMath::Abs(TMath::Sin(th - fTheta1 * TMath::DegToRad())); } - if (fTheta2<180) { - saf[3] = r*TMath::Abs(TMath::Sin(fTheta2*TMath::DegToRad()-th)); + if (fTheta2 < 180) { + saf[3] = r * TMath::Abs(TMath::Sin(fTheta2 * TMath::DegToRad() - th)); } } - Int_t i = TMath::LocMin(4,saf); + Int_t i = TMath::LocMin(4, saf); if (TestShapeBit(kGeoPhiSeg)) { - Double_t c1 = TMath::Cos(fPhi1*TMath::DegToRad()); - Double_t s1 = TMath::Sin(fPhi1*TMath::DegToRad()); - Double_t c2 = TMath::Cos(fPhi2*TMath::DegToRad()); - Double_t s2 = TMath::Sin(fPhi2*TMath::DegToRad()); - if (TGeoShape::IsCloseToPhi(saf[i], point,c1,s1,c2,s2)) { - TGeoShape::NormalPhi(point,dir,norm,c1,s1,c2,s2); + Double_t c1 = TMath::Cos(fPhi1 * TMath::DegToRad()); + Double_t s1 = TMath::Sin(fPhi1 * TMath::DegToRad()); + Double_t c2 = TMath::Cos(fPhi2 * TMath::DegToRad()); + Double_t s2 = TMath::Sin(fPhi2 * TMath::DegToRad()); + if (TGeoShape::IsCloseToPhi(saf[i], point, c1, s1, c2, s2)) { + TGeoShape::NormalPhi(point, dir, norm, c1, s1, c2, s2); return; } } - if (i>1) { - if (i==2) th=(fTheta1<90)?(fTheta1+90):(fTheta1-90); - else th=(fTheta2<90)?(fTheta2+90):(fTheta2-90); + if (i > 1) { + if (i == 2) + th = (fTheta1 < 90) ? (fTheta1 + 90) : (fTheta1 - 90); + else + th = (fTheta2 < 90) ? (fTheta2 + 90) : (fTheta2 - 90); th *= TMath::DegToRad(); } - norm[0] = TMath::Sin(th)*TMath::Cos(phi); - norm[1] = TMath::Sin(th)*TMath::Sin(phi); + norm[0] = TMath::Sin(th) * TMath::Cos(phi); + norm[1] = TMath::Sin(th) * TMath::Sin(phi); norm[2] = TMath::Cos(th); - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -288,39 +302,46 @@ Int_t TGeoSphere::IsOnBoundary(const Double_t *point) const { Int_t icode = 0; Double_t tol = TGeoShape::Tolerance(); - Double_t r2 = point[0]*point[0]+point[1]*point[1]+point[2]*point[2]; - Double_t drsqout = r2-fRmax*fRmax; + Double_t r2 = point[0] * point[0] + point[1] * point[1] + point[2] * point[2]; + Double_t drsqout = r2 - fRmax * fRmax; // Test if point is on fRmax boundary - if (TMath::Abs(drsqout)<2.*fRmax*tol) return 2; + if (TMath::Abs(drsqout) < 2. * fRmax * tol) + return 2; Double_t drsqin = r2; // Test if point is on fRmin boundary if (TestShapeBit(kGeoRSeg)) { - drsqin -= fRmin*fRmin; - if (TMath::Abs(drsqin)<2.*fRmin*tol) return 1; + drsqin -= fRmin * fRmin; + if (TMath::Abs(drsqin) < 2. * fRmin * tol) + return 1; } if (TestShapeBit(kGeoPhiSeg)) { Double_t phi = TMath::ATan2(point[1], point[0]); - if (phi<0) phi+=2*TMath::Pi(); - Double_t phi1 = fPhi1*TMath::DegToRad(); - Double_t phi2 = fPhi2*TMath::DegToRad(); - Double_t ddp = phi-phi1; - if (r2*ddp*ddp < tol*tol) return 3; + if (phi < 0) + phi += 2 * TMath::Pi(); + Double_t phi1 = fPhi1 * TMath::DegToRad(); + Double_t phi2 = fPhi2 * TMath::DegToRad(); + Double_t ddp = phi - phi1; + if (r2 * ddp * ddp < tol * tol) + return 3; ddp = phi - phi2; - if (r2*ddp*ddp < tol*tol) return 4; + if (r2 * ddp * ddp < tol * tol) + return 4; } if (TestShapeBit(kGeoThetaSeg)) { Double_t r = TMath::Sqrt(r2); - Double_t theta = TMath::ACos(point[2]/r2); - Double_t theta1 = fTheta1*TMath::DegToRad(); - Double_t theta2 = fTheta2*TMath::DegToRad(); + Double_t theta = TMath::ACos(point[2] / r2); + Double_t theta1 = fTheta1 * TMath::DegToRad(); + Double_t theta2 = fTheta2 * TMath::DegToRad(); Double_t ddt; - if (fTheta1>0) { - ddt = TMath::Abs(theta-theta1); - if (r*ddt < tol) return 5; + if (fTheta1 > 0) { + ddt = TMath::Abs(theta - theta1); + if (r * ddt < tol) + return 5; } - if (fTheta2<180) { - ddt = TMath::Abs(theta-theta2); - if (r*ddt < tol) return 6; + if (fTheta2 < 180) { + ddt = TMath::Abs(theta - theta2); + if (r * ddt < tol) + return 6; } } return icode; @@ -331,24 +352,30 @@ Int_t TGeoSphere::IsOnBoundary(const Double_t *point) const Bool_t TGeoSphere::IsPointInside(const Double_t *point, Bool_t checkR, Bool_t checkTh, Bool_t checkPh) const { - Double_t r2 = point[0]*point[0]+point[1]*point[1]+point[2]*point[2]; + Double_t r2 = point[0] * point[0] + point[1] * point[1] + point[2] * point[2]; if (checkR) { - if (TestShapeBit(kGeoRSeg) && (r2fRmax*fRmax) return kFALSE; + if (TestShapeBit(kGeoRSeg) && (r2 < fRmin * fRmin)) + return kFALSE; + if (r2 > fRmax * fRmax) + return kFALSE; } - if (r2<1E-20) return kTRUE; + if (r2 < 1E-20) + return kTRUE; if (checkPh && TestShapeBit(kGeoPhiSeg)) { Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - while (phi < fPhi1) phi+=360.; - Double_t dphi = fPhi2 -fPhi1; + while (phi < fPhi1) + phi += 360.; + Double_t dphi = fPhi2 - fPhi1; Double_t ddp = phi - fPhi1; - if (ddp > dphi) return kFALSE; + if (ddp > dphi) + return kFALSE; } if (checkTh && TestShapeBit(kGeoThetaSeg)) { - r2=TMath::Sqrt(r2); + r2 = TMath::Sqrt(r2); // check theta range - Double_t theta = TMath::ACos(point[2]/r2)*TMath::RadToDeg(); - if ((thetafTheta2)) return kFALSE; + Double_t theta = TMath::ACos(point[2] / r2) * TMath::RadToDeg(); + if ((theta < fTheta1) || (theta > fTheta2)) + return kFALSE; } return kTRUE; } @@ -359,25 +386,33 @@ Bool_t TGeoSphere::IsPointInside(const Double_t *point, Bool_t checkR, Bool_t ch Bool_t TGeoSphere::Contains(const Double_t *point) const { - Double_t r2=point[0]*point[0]+point[1]*point[1]+point[2]*point[2]; - if (TestShapeBit(kGeoRSeg) && (r2fRmax*fRmax) return kFALSE; - if (r2<1E-20) return kTRUE; + Double_t r2 = point[0] * point[0] + point[1] * point[1] + point[2] * point[2]; + if (TestShapeBit(kGeoRSeg) && (r2 < fRmin * fRmin)) + return kFALSE; + if (r2 > fRmax * fRmax) + return kFALSE; + if (r2 < 1E-20) + return kTRUE; // check phi range if (TestShapeBit(kGeoPhiSeg)) { Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - if (phi < 0 ) phi+=360.; - Double_t dphi = fPhi2 -fPhi1; - if (dphi < 0) dphi+=360.; + if (phi < 0) + phi += 360.; + Double_t dphi = fPhi2 - fPhi1; + if (dphi < 0) + dphi += 360.; Double_t ddp = phi - fPhi1; - if (ddp < 0) ddp += 360.; - if (ddp > dphi) return kFALSE; + if (ddp < 0) + ddp += 360.; + if (ddp > dphi) + return kFALSE; } if (TestShapeBit(kGeoThetaSeg)) { - r2=TMath::Sqrt(r2); + r2 = TMath::Sqrt(r2); // check theta range - Double_t theta = TMath::ACos(point[2]/r2)*TMath::RadToDeg(); - if ((thetafTheta2)) return kFALSE; + Double_t theta = TMath::ACos(point[2] / r2) * TMath::RadToDeg(); + if ((theta < fTheta1) || (theta > fTheta2)) + return kFALSE; } return kTRUE; } @@ -387,9 +422,9 @@ Bool_t TGeoSphere::Contains(const Double_t *point) const Int_t TGeoSphere::DistancetoPrimitive(Int_t px, Int_t py) { - Int_t n = fNseg+1; - Int_t nz = fNz+1; - const Int_t numPoints = 2*n*nz; + Int_t n = fNseg + 1; + Int_t nz = fNz + 1; + const Int_t numPoints = 2 * n * nz; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -397,175 +432,204 @@ Int_t TGeoSphere::DistancetoPrimitive(Int_t px, Int_t py) /// compute distance from outside point to surface of the sphere /// Check if the bounding box is crossed within the requested distance -Double_t TGeoSphere::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoSphere::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); Double_t saf[6]; - Double_t r1,r2,z1,z2,dz,si,ci; - Double_t rxy2 = point[0]*point[0]+point[1]*point[1]; + Double_t r1, r2, z1, z2, dz, si, ci; + Double_t rxy2 = point[0] * point[0] + point[1] * point[1]; Double_t rxy = TMath::Sqrt(rxy2); - r2 = rxy2+point[2]*point[2]; - Double_t r=TMath::Sqrt(r2); - Bool_t rzero=kFALSE; - Double_t phi=0; - if (r<1E-20) rzero=kTRUE; - //localize theta - Double_t th=0.; + r2 = rxy2 + point[2] * point[2]; + Double_t r = TMath::Sqrt(r2); + Bool_t rzero = kFALSE; + Double_t phi = 0; + if (r < 1E-20) + rzero = kTRUE; + // localize theta + Double_t th = 0.; if (TestShapeBit(kGeoThetaSeg) && (!rzero)) { - th = TMath::ACos(point[2]/r)*TMath::RadToDeg(); + th = TMath::ACos(point[2] / r) * TMath::RadToDeg(); } - //localize phi + // localize phi if (TestShapeBit(kGeoPhiSeg)) { - phi=TMath::ATan2(point[1], point[0])*TMath::RadToDeg(); - if (phi<0) phi+=360.; - } - if (iact<3 && safe) { - saf[0]=(rfRmax)?(r-fRmax):TGeoShape::Big(); - saf[2]=saf[3]=saf[4]=saf[5]= TGeoShape::Big(); + phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + if (phi < 0) + phi += 360.; + } + if (iact < 3 && safe) { + saf[0] = (r < fRmin) ? fRmin - r : TGeoShape::Big(); + saf[1] = (r > fRmax) ? (r - fRmax) : TGeoShape::Big(); + saf[2] = saf[3] = saf[4] = saf[5] = TGeoShape::Big(); if (TestShapeBit(kGeoThetaSeg)) { if (th < fTheta1) { - saf[2] = r*TMath::Sin((fTheta1-th)*TMath::DegToRad()); + saf[2] = r * TMath::Sin((fTheta1 - th) * TMath::DegToRad()); } if (th > fTheta2) { - saf[3] = r*TMath::Sin((th-fTheta2)*TMath::DegToRad()); + saf[3] = r * TMath::Sin((th - fTheta2) * TMath::DegToRad()); } } if (TestShapeBit(kGeoPhiSeg)) { - Double_t dph1=phi-fPhi1; - if (dph1<0) dph1+=360.; - if (dph1<=90.) saf[4]=rxy*TMath::Sin(dph1*TMath::DegToRad()); - Double_t dph2=fPhi2-phi; - if (dph2<0) dph2+=360.; - if (dph2>90.) saf[5]=rxy*TMath::Sin(dph2*TMath::DegToRad()); + Double_t dph1 = phi - fPhi1; + if (dph1 < 0) + dph1 += 360.; + if (dph1 <= 90.) + saf[4] = rxy * TMath::Sin(dph1 * TMath::DegToRad()); + Double_t dph2 = fPhi2 - phi; + if (dph2 < 0) + dph2 += 360.; + if (dph2 > 90.) + saf[5] = rxy * TMath::Sin(dph2 * TMath::DegToRad()); } *safe = saf[TMath::LocMin(6, &saf[0])]; - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // compute distance to shape // first check if any crossing at all Double_t snxt = TGeoShape::Big(); - Double_t rdotn = point[0]*dir[0]+point[1]*dir[1]+point[2]*dir[2]; - Bool_t fullsph = (!TestShapeBit(kGeoThetaSeg) && !TestShapeBit(kGeoPhiSeg))?kTRUE:kFALSE; - if (r>fRmax) { + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1] + point[2] * dir[2]; + Bool_t fullsph = (!TestShapeBit(kGeoThetaSeg) && !TestShapeBit(kGeoPhiSeg)) ? kTRUE : kFALSE; + if (r > fRmax) { Double_t b = rdotn; - Double_t c = r2-fRmax*fRmax; - Double_t d=b*b-c; - if (d<0) return TGeoShape::Big(); + Double_t c = r2 - fRmax * fRmax; + Double_t d = b * b - c; + if (d < 0) + return TGeoShape::Big(); } if (fullsph) { Bool_t inrmax = kFALSE; Bool_t inrmin = kFALSE; - if (r<=fRmax+TGeoShape::Tolerance()) inrmax = kTRUE; - if (r>=fRmin-TGeoShape::Tolerance()) inrmin = kTRUE; + if (r <= fRmax + TGeoShape::Tolerance()) + inrmax = kTRUE; + if (r >= fRmin - TGeoShape::Tolerance()) + inrmin = kTRUE; if (inrmax && inrmin) { - if ((fRmax-r) < (r-fRmin)) { - // close to Rmax - if (rdotn>=0) return TGeoShape::Big(); + if ((fRmax - r) < (r - fRmin)) { + // close to Rmax + if (rdotn >= 0) + return TGeoShape::Big(); return 0.0; // already in } // close to Rmin - if (TGeoShape::IsSameWithinTolerance(fRmin,0) || rdotn>=0) return 0.0; + if (TGeoShape::IsSameWithinTolerance(fRmin, 0) || rdotn >= 0) + return 0.0; // check second crossing of Rmin return DistToSphere(point, dir, fRmin, kFALSE, kFALSE); } } // do rmin, rmax, checking phi and theta ranges - if (rfRmax) { + if (r > fRmax) { // point outside rmax, check first cross of rmax snxt = DistToSphere(point, dir, fRmax, kTRUE); - if (snxt<1E20) return snxt; + if (snxt < 1E20) + return snxt; // now check second crossing of rmin - if (fRmin>0) snxt = DistToSphere(point, dir, fRmin, kTRUE, kFALSE); + if (fRmin > 0) + snxt = DistToSphere(point, dir, fRmin, kTRUE, kFALSE); } else { // point between rmin and rmax, check second cross of rmin - if (fRmin>0) snxt = DistToSphere(point, dir, fRmin, kTRUE, kFALSE); + if (fRmin > 0) + snxt = DistToSphere(point, dir, fRmin, kTRUE, kFALSE); } } // check theta conical surfaces Double_t ptnew[3]; - Double_t b,delta,xnew,ynew,znew, phi0, ddp; + Double_t b, delta, xnew, ynew, znew, phi0, ddp; Double_t snext = snxt; - Double_t st1=TGeoShape::Big(), st2=TGeoShape::Big(); + Double_t st1 = TGeoShape::Big(), st2 = TGeoShape::Big(); if (TestShapeBit(kGeoThetaSeg)) { - if (fTheta1>0) { - if (TGeoShape::IsSameWithinTolerance(fTheta1,90)) { - // surface is a plane - if (point[2]*dir[2]<0) { - snxt = -point[2]/dir[2]; - ptnew[0] = point[0]+snxt*dir[0]; - ptnew[1] = point[1]+snxt*dir[1]; + if (fTheta1 > 0) { + if (TGeoShape::IsSameWithinTolerance(fTheta1, 90)) { + // surface is a plane + if (point[2] * dir[2] < 0) { + snxt = -point[2] / dir[2]; + ptnew[0] = point[0] + snxt * dir[0]; + ptnew[1] = point[1] + snxt * dir[1]; ptnew[2] = 0; // check range - if (IsPointInside(&ptnew[0], kTRUE, kFALSE, kTRUE)) return TMath::Min(snxt,snext); + if (IsPointInside(&ptnew[0], kTRUE, kFALSE, kTRUE)) + return TMath::Min(snxt, snext); } } else { - si = TMath::Sin(fTheta1*TMath::DegToRad()); - ci = TMath::Cos(fTheta1*TMath::DegToRad()); - if (ci>0) { - r1 = fRmin*si; - z1 = fRmin*ci; - r2 = fRmax*si; - z2 = fRmax*ci; + si = TMath::Sin(fTheta1 * TMath::DegToRad()); + ci = TMath::Cos(fTheta1 * TMath::DegToRad()); + if (ci > 0) { + r1 = fRmin * si; + z1 = fRmin * ci; + r2 = fRmax * si; + z2 = fRmax * ci; } else { - r1 = fRmax*si; - z1 = fRmax*ci; - r2 = fRmin*si; - z2 = fRmin*ci; + r1 = fRmax * si; + z1 = fRmax * ci; + r2 = fRmin * si; + z2 = fRmin * ci; } - dz = 0.5*(z2-z1); + dz = 0.5 * (z2 - z1); ptnew[0] = point[0]; ptnew[1] = point[1]; - ptnew[2] = point[2]-0.5*(z1+z2); - Double_t zinv = 1./dz; - Double_t rin = 0.5*(r1+r2+(r2-r1)*ptnew[2]*zinv); + ptnew[2] = point[2] - 0.5 * (z1 + z2); + Double_t zinv = 1. / dz; + Double_t rin = 0.5 * (r1 + r2 + (r2 - r1) * ptnew[2] * zinv); // Protection in case point is outside - Double_t sigz = TMath::Sign(1.,point[2]); + Double_t sigz = TMath::Sign(1., point[2]); TGeoCone::DistToCone(ptnew, dir, dz, r1, r2, b, delta); Bool_t skip = kFALSE; - if (delta<0) skip = kTRUE; + if (delta < 0) + skip = kTRUE; if (!skip) { - snxt = -b-delta; - if (sigz*ci>0 && sigz*rxy2 > sigz*rin*(rin-sigz*TGeoShape::Tolerance())) { - Double_t ddotn = ptnew[0]*dir[0]+ptnew[1]*dir[1]+0.5*(r1-r2)*dir[2]*zinv*TMath::Sqrt(rxy2); - if (sigz*ddotn>=0 || -b+delta<1.E-9) skip = kTRUE; + snxt = -b - delta; + if (sigz * ci > 0 && sigz * rxy2 > sigz * rin * (rin - sigz * TGeoShape::Tolerance())) { + Double_t ddotn = + ptnew[0] * dir[0] + ptnew[1] * dir[1] + 0.5 * (r1 - r2) * dir[2] * zinv * TMath::Sqrt(rxy2); + if (sigz * ddotn >= 0 || -b + delta < 1.E-9) + skip = kTRUE; snxt = TGeoShape::Big(); } - if (snxt<1E10) { - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + st1 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) st1 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + st1 = snxt; } } } - if (!skip && st1>1E10) { - snxt = -b+delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 1E10) { + snxt = -b + delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + st1 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) st1 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + st1 = snxt; } } } @@ -573,75 +637,85 @@ Double_t TGeoSphere::DistFromOutside(const Double_t *point, const Double_t *dir, } } - if (fTheta2<180) { - if (TGeoShape::IsSameWithinTolerance(fTheta2,90)) { + if (fTheta2 < 180) { + if (TGeoShape::IsSameWithinTolerance(fTheta2, 90)) { // surface is a plane - if (point[2]*dir[2]<0) { - snxt = -point[2]/dir[2]; - ptnew[0] = point[0]+snxt*dir[0]; - ptnew[1] = point[1]+snxt*dir[1]; + if (point[2] * dir[2] < 0) { + snxt = -point[2] / dir[2]; + ptnew[0] = point[0] + snxt * dir[0]; + ptnew[1] = point[1] + snxt * dir[1]; ptnew[2] = 0; // check range - if (IsPointInside(&ptnew[0], kTRUE, kFALSE, kTRUE)) return TMath::Min(snxt,snext); + if (IsPointInside(&ptnew[0], kTRUE, kFALSE, kTRUE)) + return TMath::Min(snxt, snext); } } else { - si = TMath::Sin(fTheta2*TMath::DegToRad()); - ci = TMath::Cos(fTheta2*TMath::DegToRad()); - if (ci>0) { - r1 = fRmin*si; - z1 = fRmin*ci; - r2 = fRmax*si; - z2 = fRmax*ci; + si = TMath::Sin(fTheta2 * TMath::DegToRad()); + ci = TMath::Cos(fTheta2 * TMath::DegToRad()); + if (ci > 0) { + r1 = fRmin * si; + z1 = fRmin * ci; + r2 = fRmax * si; + z2 = fRmax * ci; } else { - r1 = fRmax*si; - z1 = fRmax*ci; - r2 = fRmin*si; - z2 = fRmin*ci; + r1 = fRmax * si; + z1 = fRmax * ci; + r2 = fRmin * si; + z2 = fRmin * ci; } - dz = 0.5*(z2-z1); + dz = 0.5 * (z2 - z1); ptnew[0] = point[0]; ptnew[1] = point[1]; - ptnew[2] = point[2]-0.5*(z1+z2); - Double_t zinv = 1./dz; - Double_t rin = 0.5*(r1+r2+(r2-r1)*ptnew[2]*zinv); + ptnew[2] = point[2] - 0.5 * (z1 + z2); + Double_t zinv = 1. / dz; + Double_t rin = 0.5 * (r1 + r2 + (r2 - r1) * ptnew[2] * zinv); // Protection in case point is outside - Double_t sigz = TMath::Sign(1.,point[2]); + Double_t sigz = TMath::Sign(1., point[2]); TGeoCone::DistToCone(ptnew, dir, dz, r1, r2, b, delta); Bool_t skip = kFALSE; - if (delta<0) skip = kTRUE; + if (delta < 0) + skip = kTRUE; if (!skip) { - snxt = -b-delta; - if (sigz*ci>0 && sigz*rxy2 < sigz*rin*(rin+sigz*TGeoShape::Tolerance())) { - Double_t ddotn = ptnew[0]*dir[0]+ptnew[1]*dir[1]+0.5*(r1-r2)*dir[2]*zinv*TMath::Sqrt(rxy2); - if (sigz*ddotn<=0 || -b+delta<1.E-9) skip = kTRUE; + snxt = -b - delta; + if (sigz * ci > 0 && sigz * rxy2 < sigz * rin * (rin + sigz * TGeoShape::Tolerance())) { + Double_t ddotn = + ptnew[0] * dir[0] + ptnew[1] * dir[1] + 0.5 * (r1 - r2) * dir[2] * zinv * TMath::Sqrt(rxy2); + if (sigz * ddotn <= 0 || -b + delta < 1.E-9) + skip = kTRUE; snxt = TGeoShape::Big(); } - if (snxt<1E10) { - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + st2 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) st2 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + st2 = snxt; } } } - if (!skip && st2>1E10) { - snxt = -b+delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 1E10) { + snxt = -b + delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + st2 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) st2 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + st2 = snxt; } } } @@ -650,43 +724,45 @@ Double_t TGeoSphere::DistFromOutside(const Double_t *point, const Double_t *dir, } } snxt = TMath::Min(st1, st2); - snxt = TMath::Min(snxt,snext); -// if (snxt<1E20) return snxt; + snxt = TMath::Min(snxt, snext); + // if (snxt<1E20) return snxt; if (TestShapeBit(kGeoPhiSeg)) { - Double_t s1 = TMath::Sin(fPhi1*TMath::DegToRad()); - Double_t c1 = TMath::Cos(fPhi1*TMath::DegToRad()); - Double_t s2 = TMath::Sin(fPhi2*TMath::DegToRad()); - Double_t c2 = TMath::Cos(fPhi2*TMath::DegToRad()); - Double_t phim = 0.5*(fPhi1+fPhi2); - Double_t sm = TMath::Sin(phim*TMath::DegToRad()); - Double_t cm = TMath::Cos(phim*TMath::DegToRad()); - Double_t s=0; + Double_t s1 = TMath::Sin(fPhi1 * TMath::DegToRad()); + Double_t c1 = TMath::Cos(fPhi1 * TMath::DegToRad()); + Double_t s2 = TMath::Sin(fPhi2 * TMath::DegToRad()); + Double_t c2 = TMath::Cos(fPhi2 * TMath::DegToRad()); + Double_t phim = 0.5 * (fPhi1 + fPhi2); + Double_t sm = TMath::Sin(phim * TMath::DegToRad()); + Double_t cm = TMath::Cos(phim * TMath::DegToRad()); + Double_t s = 0; Double_t safety, un; - safety = point[0]*s1-point[1]*c1; - if (safety>0) { - un = dir[0]*s1-dir[1]*c1; - if (un<0) { - s=-safety/un; - ptnew[0] = point[0]+s*dir[0]; - ptnew[1] = point[1]+s*dir[1]; - ptnew[2] = point[2]+s*dir[2]; - if ((ptnew[1]*cm-ptnew[0]*sm)<=0) { + safety = point[0] * s1 - point[1] * c1; + if (safety > 0) { + un = dir[0] * s1 - dir[1] * c1; + if (un < 0) { + s = -safety / un; + ptnew[0] = point[0] + s * dir[0]; + ptnew[1] = point[1] + s * dir[1]; + ptnew[2] = point[2] + s * dir[2]; + if ((ptnew[1] * cm - ptnew[0] * sm) <= 0) { Double_t sfi1 = s; - if (IsPointInside(&ptnew[0], kTRUE, kTRUE, kFALSE) && sfi10) { - un = -dir[0]*s2+dir[1]*c2; - if (un<0) { - s=-safety/un; - ptnew[0] = point[0]+s*dir[0]; - ptnew[1] = point[1]+s*dir[1]; - ptnew[2] = point[2]+s*dir[2]; - if ((ptnew[1]*cm-ptnew[0]*sm)>=0) { + safety = -point[0] * s2 + point[1] * c2; + if (safety > 0) { + un = -dir[0] * s2 + dir[1] * c2; + if (un < 0) { + s = -safety / un; + ptnew[0] = point[0] + s * dir[0]; + ptnew[1] = point[1] + s * dir[1]; + ptnew[2] = point[2] + s * dir[2]; + if ((ptnew[1] * cm - ptnew[0] * sm) >= 0) { Double_t sfi2 = s; - if (IsPointInside(&ptnew[0], kTRUE, kTRUE, kFALSE) && sfi20) { - saf[2] = r*TMath::Sin((th-fTheta1)*TMath::DegToRad()); + if (fTheta1 > 0) { + saf[2] = r * TMath::Sin((th - fTheta1) * TMath::DegToRad()); } - if (fTheta2<180) { - saf[3] = r*TMath::Sin((fTheta2-th)*TMath::DegToRad()); + if (fTheta2 < 180) { + saf[3] = r * TMath::Sin((fTheta2 - th) * TMath::DegToRad()); } } if (TestShapeBit(kGeoPhiSeg)) { - Double_t dph1=phi-fPhi1; - if (dph1<0) dph1+=360.; - if (dph1<=90.) saf[4]=rxy*TMath::Sin(dph1*TMath::DegToRad()); - Double_t dph2=fPhi2-phi; - if (dph2<0) dph2+=360.; - if (dph2<=90.) saf[5]=rxy*TMath::Sin(dph2*TMath::DegToRad()); + Double_t dph1 = phi - fPhi1; + if (dph1 < 0) + dph1 += 360.; + if (dph1 <= 90.) + saf[4] = rxy * TMath::Sin(dph1 * TMath::DegToRad()); + Double_t dph2 = fPhi2 - phi; + if (dph2 < 0) + dph2 += 360.; + if (dph2 <= 90.) + saf[5] = rxy * TMath::Sin(dph2 * TMath::DegToRad()); } *safe = saf[TMath::LocMin(6, &saf[0])]; - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // compute distance to shape if (rzero) { -// gGeoManager->SetNormalChecked(1.); + // gGeoManager->SetNormalChecked(1.); return fRmax; } // first do rmin, rmax - Double_t b,delta, xnew,ynew,znew, phi0, ddp; - Double_t rdotn = point[0]*dir[0]+point[1]*dir[1]+point[2]*dir[2]; + Double_t b, delta, xnew, ynew, znew, phi0, ddp; + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1] + point[2] * dir[2]; Double_t sn1 = TGeoShape::Big(); // Inner sphere - if (fRmin>0) { + if (fRmin > 0) { // Protection in case point is actually outside the sphere - if (r <= fRmin+TGeoShape::Tolerance()) { - if (rdotn<0) return 0.0; + if (r <= fRmin + TGeoShape::Tolerance()) { + if (rdotn < 0) + return 0.0; } else { - if (rdotn<0) sn1 = DistToSphere(point, dir, fRmin, kFALSE); + if (rdotn < 0) + sn1 = DistToSphere(point, dir, fRmin, kFALSE); } } // Outer sphere - if (r >= fRmax-TGeoShape::Tolerance()) { - if (rdotn>=0) return 0.0; + if (r >= fRmax - TGeoShape::Tolerance()) { + if (rdotn >= 0) + return 0.0; } Double_t sn2 = DistToSphere(point, dir, fRmax, kFALSE, kFALSE); Double_t sr = TMath::Min(sn1, sn2); // check theta conical surfaces sn1 = sn2 = TGeoShape::Big(); if (TestShapeBit(kGeoThetaSeg)) { - if (TGeoShape::IsSameWithinTolerance(fTheta1,90)) { - // surface is a plane - if (point[2]*dir[2]<0) sn1 = -point[2]/dir[2]; + if (TGeoShape::IsSameWithinTolerance(fTheta1, 90)) { + // surface is a plane + if (point[2] * dir[2] < 0) + sn1 = -point[2] / dir[2]; } else { - if (fTheta1>0) { - Double_t r1,r2,z1,z2,dz,ptnew[3]; - Double_t si = TMath::Sin(fTheta1*TMath::DegToRad()); - Double_t ci = TMath::Cos(fTheta1*TMath::DegToRad()); - if (ci>0) { - r1 = fRmin*si; - z1 = fRmin*ci; - r2 = fRmax*si; - z2 = fRmax*ci; + if (fTheta1 > 0) { + Double_t r1, r2, z1, z2, dz, ptnew[3]; + Double_t si = TMath::Sin(fTheta1 * TMath::DegToRad()); + Double_t ci = TMath::Cos(fTheta1 * TMath::DegToRad()); + if (ci > 0) { + r1 = fRmin * si; + z1 = fRmin * ci; + r2 = fRmax * si; + z2 = fRmax * ci; } else { - r1 = fRmax*si; - z1 = fRmax*ci; - r2 = fRmin*si; - z2 = fRmin*ci; + r1 = fRmax * si; + z1 = fRmax * ci; + r2 = fRmin * si; + z2 = fRmin * ci; } - dz = 0.5*(z2-z1); + dz = 0.5 * (z2 - z1); ptnew[0] = point[0]; ptnew[1] = point[1]; - ptnew[2] = point[2]-0.5*(z1+z2); - Double_t zinv = 1./dz; - Double_t rin = 0.5*(r1+r2+(r2-r1)*ptnew[2]*zinv); + ptnew[2] = point[2] - 0.5 * (z1 + z2); + Double_t zinv = 1. / dz; + Double_t rin = 0.5 * (r1 + r2 + (r2 - r1) * ptnew[2] * zinv); // Protection in case point is outside - Double_t sigz = TMath::Sign(1.,point[2]); - if (sigz*ci>0 && sigz*rxy2 < sigz*rin*(rin+sigz*TGeoShape::Tolerance())) { - Double_t ddotn = ptnew[0]*dir[0]+ptnew[1]*dir[1]+0.5*(r1-r2)*dir[2]*zinv*TMath::Sqrt(rxy2); - if (sigz*ddotn<=0) return 0.0; + Double_t sigz = TMath::Sign(1., point[2]); + if (sigz * ci > 0 && sigz * rxy2 < sigz * rin * (rin + sigz * TGeoShape::Tolerance())) { + Double_t ddotn = + ptnew[0] * dir[0] + ptnew[1] * dir[1] + 0.5 * (r1 - r2) * dir[2] * zinv * TMath::Sqrt(rxy2); + if (sigz * ddotn <= 0) + return 0.0; } else { TGeoCone::DistToCone(ptnew, dir, dz, r1, r2, b, delta); - if (delta>0) { - Double_t snxt = -b-delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 0) { + Double_t snxt = -b - delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + sn1 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) sn1 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + sn1 = snxt; } } - if (sn1>1E10) { - snxt = -b+delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 1E10) { + snxt = -b + delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + sn1 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) sn1 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + sn1 = snxt; } } } @@ -833,64 +931,73 @@ Double_t TGeoSphere::DistFromInside(const Double_t *point, const Double_t *dir, } } } - if (TGeoShape::IsSameWithinTolerance(fTheta2,90)) { + if (TGeoShape::IsSameWithinTolerance(fTheta2, 90)) { // surface is a plane - if (point[2]*dir[2]<0) sn1 = -point[2]/dir[2]; + if (point[2] * dir[2] < 0) + sn1 = -point[2] / dir[2]; } else { - if (fTheta2<180) { - Double_t r1,r2,z1,z2,dz,ptnew[3]; - Double_t si = TMath::Sin(fTheta2*TMath::DegToRad()); - Double_t ci = TMath::Cos(fTheta2*TMath::DegToRad()); - if (ci>0) { - r1 = fRmin*si; - z1 = fRmin*ci; - r2 = fRmax*si; - z2 = fRmax*ci; + if (fTheta2 < 180) { + Double_t r1, r2, z1, z2, dz, ptnew[3]; + Double_t si = TMath::Sin(fTheta2 * TMath::DegToRad()); + Double_t ci = TMath::Cos(fTheta2 * TMath::DegToRad()); + if (ci > 0) { + r1 = fRmin * si; + z1 = fRmin * ci; + r2 = fRmax * si; + z2 = fRmax * ci; } else { - r1 = fRmax*si; - z1 = fRmax*ci; - r2 = fRmin*si; - z2 = fRmin*ci; + r1 = fRmax * si; + z1 = fRmax * ci; + r2 = fRmin * si; + z2 = fRmin * ci; } - dz = 0.5*(z2-z1); + dz = 0.5 * (z2 - z1); ptnew[0] = point[0]; ptnew[1] = point[1]; - ptnew[2] = point[2]-0.5*(z1+z2); - Double_t zinv = 1./dz; - Double_t rin = 0.5*(r1+r2+(r2-r1)*ptnew[2]*zinv); + ptnew[2] = point[2] - 0.5 * (z1 + z2); + Double_t zinv = 1. / dz; + Double_t rin = 0.5 * (r1 + r2 + (r2 - r1) * ptnew[2] * zinv); // Protection in case point is outside - Double_t sigz = TMath::Sign(1.,point[2]); - if (sigz*ci>0 && sigz*rxy2 > sigz*rin*(rin-sigz*TGeoShape::Tolerance())) { - Double_t ddotn = ptnew[0]*dir[0]+ptnew[1]*dir[1]+0.5*(r1-r2)*dir[2]*zinv*TMath::Sqrt(rxy2); - if (sigz*ddotn>=0) return 0.0; + Double_t sigz = TMath::Sign(1., point[2]); + if (sigz * ci > 0 && sigz * rxy2 > sigz * rin * (rin - sigz * TGeoShape::Tolerance())) { + Double_t ddotn = + ptnew[0] * dir[0] + ptnew[1] * dir[1] + 0.5 * (r1 - r2) * dir[2] * zinv * TMath::Sqrt(rxy2); + if (sigz * ddotn >= 0) + return 0.0; } else { TGeoCone::DistToCone(ptnew, dir, dz, r1, r2, b, delta); - if (delta>0) { - Double_t snxt = -b-delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 0) { + Double_t snxt = -b - delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + sn2 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) sn2 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + sn2 = snxt; } } - if (sn2>1E10) { - snxt = -b+delta; - znew = ptnew[2]+snxt*dir[2]; - if (snxt>0 && TMath::Abs(znew) 1E10) { + snxt = -b + delta; + znew = ptnew[2] + snxt * dir[2]; + if (snxt > 0 && TMath::Abs(znew) < dz) { + if (!TestShapeBit(kGeoPhiSeg)) + sn2 = snxt; else { - xnew = ptnew[0]+snxt*dir[0]; - ynew = ptnew[1]+snxt*dir[1]; + xnew = ptnew[0] + snxt * dir[0]; + ynew = ptnew[1] + snxt * dir[1]; phi0 = TMath::ATan2(ynew, xnew) * TMath::RadToDeg(); - ddp = phi0-fPhi1; - while (ddp<0) ddp+=360.; - if (ddp<=fPhi2-fPhi1) sn2 = snxt; + ddp = phi0 - fPhi1; + while (ddp < 0) + ddp += 360.; + if (ddp <= fPhi2 - fPhi1) + sn2 = snxt; } } } @@ -899,16 +1006,16 @@ Double_t TGeoSphere::DistFromInside(const Double_t *point, const Double_t *dir, } } } - Double_t st = TMath::Min(sn1,sn2); + Double_t st = TMath::Min(sn1, sn2); Double_t sp = TGeoShape::Big(); if (TestShapeBit(kGeoPhiSeg)) { - Double_t s1 = TMath::Sin(fPhi1*TMath::DegToRad()); - Double_t c1 = TMath::Cos(fPhi1*TMath::DegToRad()); - Double_t s2 = TMath::Sin(fPhi2*TMath::DegToRad()); - Double_t c2 = TMath::Cos(fPhi2*TMath::DegToRad()); - Double_t phim = 0.5*(fPhi1+fPhi2); - Double_t sm = TMath::Sin(phim*TMath::DegToRad()); - Double_t cm = TMath::Cos(phim*TMath::DegToRad()); + Double_t s1 = TMath::Sin(fPhi1 * TMath::DegToRad()); + Double_t c1 = TMath::Cos(fPhi1 * TMath::DegToRad()); + Double_t s2 = TMath::Sin(fPhi2 * TMath::DegToRad()); + Double_t c2 = TMath::Cos(fPhi2 * TMath::DegToRad()); + Double_t phim = 0.5 * (fPhi1 + fPhi2); + Double_t sm = TMath::Sin(phim * TMath::DegToRad()); + Double_t cm = TMath::Cos(phim * TMath::DegToRad()); sp = TGeoShape::DistToPhiMin(point, dir, s1, c1, s2, c2, sm, cm); } Double_t snxt = TMath::Min(sr, st); @@ -919,92 +1026,97 @@ Double_t TGeoSphere::DistFromInside(const Double_t *point, const Double_t *dir, //////////////////////////////////////////////////////////////////////////////// /// compute distance to sphere of radius rsph. Direction has to be a unit vector -Double_t TGeoSphere::DistToSphere(const Double_t *point, const Double_t *dir, Double_t rsph, Bool_t check, Bool_t firstcross) const +Double_t TGeoSphere::DistToSphere(const Double_t *point, const Double_t *dir, Double_t rsph, Bool_t check, + Bool_t firstcross) const { - if (rsph<=0) return TGeoShape::Big(); - Double_t r2 = point[0]*point[0]+point[1]*point[1]+point[2]*point[2]; - Double_t b = point[0]*dir[0]+point[1]*dir[1]+point[2]*dir[2]; - Double_t c = r2-rsph*rsph; - Bool_t in = (c<=0)?kTRUE:kFALSE; + if (rsph <= 0) + return TGeoShape::Big(); + Double_t r2 = point[0] * point[0] + point[1] * point[1] + point[2] * point[2]; + Double_t b = point[0] * dir[0] + point[1] * dir[1] + point[2] * dir[2]; + Double_t c = r2 - rsph * rsph; + Bool_t in = (c <= 0) ? kTRUE : kFALSE; Double_t d; - d=b*b-c; - if (d<0) return TGeoShape::Big(); + d = b * b - c; + if (d < 0) + return TGeoShape::Big(); Double_t pt[3]; Int_t i; d = TMath::Sqrt(d); Double_t s; if (in) { - s=-b+d; + s = -b + d; } else { - s = (firstcross)?(-b-d):(-b+d); - } - if (s<0) return TGeoShape::Big(); - if (!check) return s; - for (i=0; i<3; i++) pt[i]=point[i]+s*dir[i]; + s = (firstcross) ? (-b - d) : (-b + d); + } + if (s < 0) + return TGeoShape::Big(); + if (!check) + return s; + for (i = 0; i < 3; i++) + pt[i] = point[i] + s * dir[i]; // check theta and phi ranges - if (IsPointInside(&pt[0], kFALSE)) return s; + if (IsPointInside(&pt[0], kFALSE)) + return s; return TGeoShape::Big(); } //////////////////////////////////////////////////////////////////////////////// -TGeoVolume *TGeoSphere::Divide(TGeoVolume * voldiv, const char * divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoSphere::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- R division - finder = new TGeoPatternSphR(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "R"; - voldiv->AddNodeOffset(vol, id, 0, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 2: //--- Phi division - finder = new TGeoPatternSphPhi(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoSphere(fRmin, fRmax, fTheta1, fTheta2, -step/2, step/2); + case 1: //--- R division + finder = new TGeoPatternSphR(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + shape = new TGeoSphere(start + id * step, start + (id + 1) * step, fTheta1, fTheta2, fPhi1, fPhi2); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Theta division - finder = new TGeoPatternSphTheta(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "Theta"; - voldiv->AddNodeOffset(vol, id, 0, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "In shape %s wrong axis type for division", GetName()); - return 0; + opt = "R"; + voldiv->AddNodeOffset(vol, id, 0, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 2: //--- Phi division + finder = new TGeoPatternSphPhi(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoSphere(fRmin, fRmax, fTheta1, fTheta2, -step / 2, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Theta division + finder = new TGeoPatternSphTheta(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + shape = new TGeoSphere(fRmin, fRmax, start + id * step, start + (id + 1) * step, fPhi1, fPhi2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Theta"; + voldiv->AddNodeOffset(vol, id, 0, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "In shape %s wrong axis type for division", GetName()); return 0; } } @@ -1014,14 +1126,10 @@ TGeoVolume *TGeoSphere::Divide(TGeoVolume * voldiv, const char * divname, Int_t const char *TGeoSphere::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "R"; - case 2: - return "PHI"; - case 3: - return "THETA"; - default: - return "UNDEFINED"; + case 1: return "R"; + case 2: return "PHI"; + case 3: return "THETA"; + default: return "UNDEFINED"; } } @@ -1034,21 +1142,21 @@ Double_t TGeoSphere::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) con xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fRmin; - xhi = fRmax; - dx = xhi-xlo; - return dx; - case 2: - xlo = fPhi1; - xhi = fPhi2; - dx = xhi-xlo; - return dx; - case 3: - xlo = fTheta1; - xhi = fTheta2; - dx = xhi-xlo; - return dx; + case 1: + xlo = fRmin; + xhi = fRmax; + dx = xhi - xlo; + return dx; + case 2: + xlo = fPhi1; + xhi = fPhi2; + dx = xhi - xlo; + return dx; + case 3: + xlo = fTheta1; + xhi = fTheta2; + dx = xhi - xlo; + return dx; } return dx; } @@ -1059,25 +1167,27 @@ Double_t TGeoSphere::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) con void TGeoSphere::GetBoundingCylinder(Double_t *param) const { - Double_t smin = TMath::Sin(fTheta1*TMath::DegToRad()); - Double_t smax = TMath::Sin(fTheta2*TMath::DegToRad()); - if (smin>smax) { + Double_t smin = TMath::Sin(fTheta1 * TMath::DegToRad()); + Double_t smax = TMath::Sin(fTheta2 * TMath::DegToRad()); + if (smin > smax) { Double_t a = smin; smin = smax; smax = a; } - param[0] = fRmin*smin; // Rmin + param[0] = fRmin * smin; // Rmin param[0] *= param[0]; - if (((90.-fTheta1)*(fTheta2-90.))>=0) smax = 1.; - param[1] = fRmax*smax; // Rmax + if (((90. - fTheta1) * (fTheta2 - 90.)) >= 0) + smax = 1.; + param[1] = fRmax * smax; // Rmax param[1] *= param[1]; - param[2] = (fPhi1<0)?(fPhi1+360.):fPhi1; // Phi1 + param[2] = (fPhi1 < 0) ? (fPhi1 + 360.) : fPhi1; // Phi1 param[3] = fPhi2; - if (TGeoShape::IsSameWithinTolerance(param[3]-param[2],360)) { // Phi2 + if (TGeoShape::IsSameWithinTolerance(param[3] - param[2], 360)) { // Phi2 param[2] = 0.; param[3] = 360.; } - while (param[3]0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; - - Int_t nbPnts = nlat*nlong+nup+ndown+ncenter; - if (TestShapeBit(kGeoRSeg)) nbPnts *= 2; - - Int_t nbSegs = nlat*fNseg + (nlat-1+nup+ndown)*nlong; // outer sphere - if (TestShapeBit(kGeoRSeg)) nbSegs *= 2; // inner sphere - if (TestShapeBit(kGeoPhiSeg)) nbSegs += 2*nlat+nup+ndown; // 2 phi planes - nbSegs += nlong * (2-nup - ndown); // connecting cones - - Int_t nbPols = fNz*fNseg; // outer - if (TestShapeBit(kGeoRSeg)) nbPols *=2; // inner - if (TestShapeBit(kGeoPhiSeg)) nbPols += 2*fNz; // 2 phi planes - nbPols += (2-nup-ndown)*fNseg; // connecting - - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols); - - if (buff) - { + if (TestShapeBit(kGeoPhiSeg)) + nlong++; + + Int_t nbPnts = nlat * nlong + nup + ndown + ncenter; + if (TestShapeBit(kGeoRSeg)) + nbPnts *= 2; + + Int_t nbSegs = nlat * fNseg + (nlat - 1 + nup + ndown) * nlong; // outer sphere + if (TestShapeBit(kGeoRSeg)) + nbSegs *= 2; // inner sphere + if (TestShapeBit(kGeoPhiSeg)) + nbSegs += 2 * nlat + nup + ndown; // 2 phi planes + nbSegs += nlong * (2 - nup - ndown); // connecting cones + + Int_t nbPols = fNz * fNseg; // outer + if (TestShapeBit(kGeoRSeg)) + nbPols *= 2; // inner + if (TestShapeBit(kGeoPhiSeg)) + nbPols += 2 * fNz; // 2 phi planes + nbPols += (2 - nup - ndown) * fNseg; // connecting + + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -1142,7 +1259,7 @@ TBuffer3D *TGeoSphere::MakeBuffer3D() const //////////////////////////////////////////////////////////////////////////////// /// Fill TBuffer3D structure for segments and polygons. -void TGeoSphere::SetSegsAndPols(TBuffer3D & buff) const +void TGeoSphere::SetSegsAndPols(TBuffer3D &buff) const { // Bool_t full = kTRUE; // if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; @@ -1151,10 +1268,11 @@ void TGeoSphere::SetSegsAndPols(TBuffer3D & buff) const Int_t nup = (fTheta1 > 0) ? 0 : 1; Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; + if (TestShapeBit(kGeoPhiSeg)) + nlong++; // Int_t nbPnts = nlat*nlong+nup+ndown+ncenter; // if (TestShapeBit(kGeoRSeg)) nbPnts *= 2; @@ -1177,82 +1295,82 @@ void TGeoSphere::SetSegsAndPols(TBuffer3D & buff) const // loop all segments on latitudes (except 0 and 180 degrees) // [0, nlat*fNseg) Int_t indpar = 0; - for (i=0; i0) saf[2] = r*TMath::Sin((th-fTheta1)*TMath::DegToRad()); - if (fTheta2<180) saf[3] = r*TMath::Sin((fTheta2-th)*TMath::DegToRad()); + if (fTheta1 > 0) + saf[2] = r * TMath::Sin((th - fTheta1) * TMath::DegToRad()); + if (fTheta2 < 180) + saf[3] = r * TMath::Sin((fTheta2 - th) * TMath::DegToRad()); } Double_t safphi = TGeoShape::Big(); - if (TestShapeBit(kGeoPhiSeg)) safphi = TGeoShape::SafetyPhi(point,in,fPhi1,fPhi2); + if (TestShapeBit(kGeoPhiSeg)) + safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); if (in) { - Double_t safe = saf[TMath::LocMin(4,saf)]; - return TMath::Min(safe,safphi); + Double_t safe = saf[TMath::LocMin(4, saf)]; + return TMath::Min(safe, safphi); } - for (Int_t i=0; i<4; i++) saf[i]=-saf[i]; + for (Int_t i = 0; i < 4; i++) + saf[i] = -saf[i]; Double_t safe = saf[TMath::LocMax(4, saf)]; - if (TestShapeBit(kGeoPhiSeg)) return TMath::Max(safe, safphi); + if (TestShapeBit(kGeoPhiSeg)) + return TMath::Max(safe, safphi); return safe; } @@ -1548,23 +1686,25 @@ Double_t TGeoSphere::Safety(const Double_t *point, Bool_t in) const void TGeoSphere::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rmin = " << fRmin << ";" << std::endl; out << " rmax = " << fRmax << ";" << std::endl; - out << " theta1 = " << fTheta1<< ";" << std::endl; + out << " theta1 = " << fTheta1 << ";" << std::endl; out << " theta2 = " << fTheta2 << ";" << std::endl; out << " phi1 = " << fPhi1 << ";" << std::endl; out << " phi2 = " << fPhi2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoSphere(\"" << GetName() << "\",rmin,rmax,theta1, theta2,phi1,phi2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoSphere(\"" << GetName() + << "\",rmin,rmax,theta1, theta2,phi1,phi2);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } //////////////////////////////////////////////////////////////////////////////// /// Set spherical segment dimensions. -void TGeoSphere::SetSphDimensions(Double_t rmin, Double_t rmax, Double_t theta1, - Double_t theta2, Double_t phi1, Double_t phi2) +void TGeoSphere::SetSphDimensions(Double_t rmin, Double_t rmax, Double_t theta1, Double_t theta2, Double_t phi1, + Double_t phi2) { if (rmin >= rmax) { Error("SetDimensions", "invalid parameters rmin/rmax"); @@ -1572,19 +1712,24 @@ void TGeoSphere::SetSphDimensions(Double_t rmin, Double_t rmax, Double_t theta1, } fRmin = rmin; fRmax = rmax; - if (rmin>0) SetShapeBit(kGeoRSeg); - if (theta1 >= theta2 || theta1<0 || theta1>180 || theta2>180) { + if (rmin > 0) + SetShapeBit(kGeoRSeg); + if (theta1 >= theta2 || theta1 < 0 || theta1 > 180 || theta2 > 180) { Error("SetDimensions", "invalid parameters theta1/theta2"); return; } fTheta1 = theta1; fTheta2 = theta2; - if ((theta2-theta1)<180.) SetShapeBit(kGeoThetaSeg); + if ((theta2 - theta1) < 180.) + SetShapeBit(kGeoThetaSeg); fPhi1 = phi1; - if (phi1<0) fPhi1+=360.; + if (phi1 < 0) + fPhi1 += 360.; fPhi2 = phi2; - while (fPhi2<=fPhi1) fPhi2+=360.; - if (!TGeoShape::IsSameWithinTolerance(TMath::Abs(phi2-phi1),360)) SetShapeBit(kGeoPhiSeg); + while (fPhi2 <= fPhi1) + fPhi2 += 360.; + if (!TGeoShape::IsSameWithinTolerance(TMath::Abs(phi2 - phi1), 360)) + SetShapeBit(kGeoPhiSeg); } //////////////////////////////////////////////////////////////////////////////// @@ -1598,10 +1743,14 @@ void TGeoSphere::SetDimensions(Double_t *param, Int_t nparam) Double_t theta2 = 180.; Double_t phi1 = 0; Double_t phi2 = 360.; - if (nparam > 2) theta1 = param[2]; - if (nparam > 3) theta2 = param[3]; - if (nparam > 4) phi1 = param[4]; - if (nparam > 5) phi2 = param[5]; + if (nparam > 2) + theta1 = param[2]; + if (nparam > 3) + theta2 = param[3]; + if (nparam > 4) + phi1 = param[4]; + if (nparam > 5) + phi2 = param[5]; SetSphDimensions(rmin, rmax, theta1, theta2, phi1, phi2); } @@ -1611,7 +1760,7 @@ void TGeoSphere::SetDimensions(Double_t *param, Int_t nparam) void TGeoSphere::SetDimensions(Double_t *param) { - SetDimensions(param,2); + SetDimensions(param, 2); } //////////////////////////////////////////////////////////////////////////////// @@ -1621,10 +1770,12 @@ void TGeoSphere::SetNumberOfDivisions(Int_t p) { fNseg = p; Double_t dphi = fPhi2 - fPhi1; - if (dphi<0) dphi+=360; - Double_t dtheta = TMath::Abs(fTheta2-fTheta1); - fNz = Int_t(fNseg*dtheta/dphi) +1; - if (fNz<2) fNz=2; + if (dphi < 0) + dphi += 360; + Double_t dtheta = TMath::Abs(fTheta2 - fTheta1); + fNz = Int_t(fNseg * dtheta / dphi) + 1; + if (fNz < 2) + fNz = 2; } //////////////////////////////////////////////////////////////////////////////// @@ -1637,40 +1788,43 @@ void TGeoSphere::SetPoints(Double_t *points) const return; } Bool_t full = kTRUE; - if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; + if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) + full = kFALSE; Int_t ncenter = 1; - if (full || TestShapeBit(kGeoRSeg)) ncenter = 0; - Int_t nup = (fTheta1>0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; + if (TestShapeBit(kGeoPhiSeg)) + nlong++; // total number of points on mesh is: // nlat*nlong + nup + ndown + ncenter; // in case rmin=0 // 2*(nlat*nlong + nup + ndown); // in case rmin>0 - Int_t i,j ; - Double_t phi1 = fPhi1*TMath::DegToRad(); - Double_t phi2 = fPhi2*TMath::DegToRad(); - Double_t dphi = (phi2-phi1)/fNseg; - Double_t theta1 = fTheta1*TMath::DegToRad(); - Double_t theta2 = fTheta2*TMath::DegToRad(); - Double_t dtheta = (theta2-theta1)/fNz; - Double_t z,zi,theta,phi,cphi,sphi; - Int_t indx=0; + Int_t i, j; + Double_t phi1 = fPhi1 * TMath::DegToRad(); + Double_t phi2 = fPhi2 * TMath::DegToRad(); + Double_t dphi = (phi2 - phi1) / fNseg; + Double_t theta1 = fTheta1 * TMath::DegToRad(); + Double_t theta2 = fTheta2 * TMath::DegToRad(); + Double_t dtheta = (theta2 - theta1) / fNz; + Double_t z, zi, theta, phi, cphi, sphi; + Int_t indx = 0; // FILL ALL POINTS ON OUTER SPHERE // (nlat * nlong) points // loop all latitudes except 0/180 degrees (nlat times) // ilat = [0,nlat] jlong = [0,nlong] // Index(ilat, jlong) = 3*(ilat*nlat + jlong) for (i = 0; i < nlat; i++) { - theta = theta1+(nup+i)*dtheta; - z = fRmax * TMath::Cos(theta); + theta = theta1 + (nup + i) * dtheta; + z = fRmax * TMath::Cos(theta); zi = fRmax * TMath::Sin(theta); // loop all different longitudes (nlong times) for (j = 0; j < nlong; j++) { - phi = phi1+j*dphi; + phi = phi1 + j * dphi; cphi = TMath::Cos(phi); sphi = TMath::Sin(phi); points[indx++] = zi * cphi; @@ -1694,14 +1848,14 @@ void TGeoSphere::SetPoints(Double_t *points) const // do the same for inner sphere if it exist // Start_index = 3*(nlat*nlong + nup + ndown) if (TestShapeBit(kGeoRSeg)) { - // Index(ilat, jlong) = start_index + 3*(ilat*nlat + jlong) + // Index(ilat, jlong) = start_index + 3*(ilat*nlat + jlong) for (i = 0; i < nlat; i++) { - theta = theta1+(nup+i)*dtheta; - z = fRmin * TMath::Cos(theta); + theta = theta1 + (nup + i) * dtheta; + z = fRmin * TMath::Cos(theta); zi = fRmin * TMath::Sin(theta); // loop all different longitudes (nlong times) for (j = 0; j < nlong; j++) { - phi = phi1+j*dphi; + phi = phi1 + j * dphi; cphi = TMath::Cos(phi); sphi = TMath::Sin(phi); points[indx++] = zi * cphi; @@ -1711,13 +1865,13 @@ void TGeoSphere::SetPoints(Double_t *points) const } // upper/lower points (if they exist) for inner sphere if (nup) { - // ind_up = start_index + 3*nlat*nlong + // ind_up = start_index + 3*nlat*nlong points[indx++] = 0.; points[indx++] = 0.; points[indx++] = fRmin; } if (ndown) { - // ind_down = start_index + 3*(nlat*nlong+nup) + // ind_down = start_index + 3*(nlat*nlong+nup) points[indx++] = 0.; points[indx++] = 0.; points[indx++] = -fRmin; @@ -1742,40 +1896,43 @@ void TGeoSphere::SetPoints(Float_t *points) const return; } Bool_t full = kTRUE; - if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; + if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) + full = kFALSE; Int_t ncenter = 1; - if (full || TestShapeBit(kGeoRSeg)) ncenter = 0; - Int_t nup = (fTheta1>0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; + if (TestShapeBit(kGeoPhiSeg)) + nlong++; // total number of points on mesh is: // nlat*nlong + nup + ndown + ncenter; // in case rmin=0 // 2*(nlat*nlong + nup + ndown); // in case rmin>0 - Int_t i,j ; - Double_t phi1 = fPhi1*TMath::DegToRad(); - Double_t phi2 = fPhi2*TMath::DegToRad(); - Double_t dphi = (phi2-phi1)/fNseg; - Double_t theta1 = fTheta1*TMath::DegToRad(); - Double_t theta2 = fTheta2*TMath::DegToRad(); - Double_t dtheta = (theta2-theta1)/fNz; - Double_t z,zi,theta,phi,cphi,sphi; - Int_t indx=0; + Int_t i, j; + Double_t phi1 = fPhi1 * TMath::DegToRad(); + Double_t phi2 = fPhi2 * TMath::DegToRad(); + Double_t dphi = (phi2 - phi1) / fNseg; + Double_t theta1 = fTheta1 * TMath::DegToRad(); + Double_t theta2 = fTheta2 * TMath::DegToRad(); + Double_t dtheta = (theta2 - theta1) / fNz; + Double_t z, zi, theta, phi, cphi, sphi; + Int_t indx = 0; // FILL ALL POINTS ON OUTER SPHERE // (nlat * nlong) points // loop all latitudes except 0/180 degrees (nlat times) // ilat = [0,nlat] jlong = [0,nlong] // Index(ilat, jlong) = 3*(ilat*nlat + jlong) for (i = 0; i < nlat; i++) { - theta = theta1+(nup+i)*dtheta; - z = fRmax * TMath::Cos(theta); + theta = theta1 + (nup + i) * dtheta; + z = fRmax * TMath::Cos(theta); zi = fRmax * TMath::Sin(theta); // loop all different longitudes (nlong times) for (j = 0; j < nlong; j++) { - phi = phi1+j*dphi; + phi = phi1 + j * dphi; cphi = TMath::Cos(phi); sphi = TMath::Sin(phi); points[indx++] = zi * cphi; @@ -1799,14 +1956,14 @@ void TGeoSphere::SetPoints(Float_t *points) const // do the same for inner sphere if it exist // Start_index = 3*(nlat*nlong + nup + ndown) if (TestShapeBit(kGeoRSeg)) { - // Index(ilat, jlong) = start_index + 3*(ilat*nlat + jlong) + // Index(ilat, jlong) = start_index + 3*(ilat*nlat + jlong) for (i = 0; i < nlat; i++) { - theta = theta1+(nup+i)*dtheta; - z = fRmin * TMath::Cos(theta); + theta = theta1 + (nup + i) * dtheta; + z = fRmin * TMath::Cos(theta); zi = fRmin * TMath::Sin(theta); // loop all different longitudes (nlong times) for (j = 0; j < nlong; j++) { - phi = phi1+j*dphi; + phi = phi1 + j * dphi; cphi = TMath::Cos(phi); sphi = TMath::Sin(phi); points[indx++] = zi * cphi; @@ -1816,13 +1973,13 @@ void TGeoSphere::SetPoints(Float_t *points) const } // upper/lower points (if they exist) for inner sphere if (nup) { - // ind_up = start_index + 3*nlat*nlong + // ind_up = start_index + 3*nlat*nlong points[indx++] = 0.; points[indx++] = 0.; points[indx++] = fRmin; } if (ndown) { - // ind_down = start_index + 3*(nlat*nlong+nup) + // ind_down = start_index + 3*(nlat*nlong+nup) points[indx++] = 0.; points[indx++] = 0.; points[indx++] = -fRmin; @@ -1842,32 +1999,40 @@ void TGeoSphere::SetPoints(Float_t *points) const void TGeoSphere::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - TGeoSphere * localThis = const_cast(this); + TGeoSphere *localThis = const_cast(this); localThis->SetNumberOfDivisions(gGeoManager->GetNsegments()); Bool_t full = kTRUE; - if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; + if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) + full = kFALSE; Int_t ncenter = 1; - if (full || TestShapeBit(kGeoRSeg)) ncenter = 0; - Int_t nup = (fTheta1>0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; - - nvert = nlat*nlong+nup+ndown+ncenter; - if (TestShapeBit(kGeoRSeg)) nvert *= 2; - - nsegs = nlat*fNseg + (nlat-1+nup+ndown)*nlong; // outer sphere - if (TestShapeBit(kGeoRSeg)) nsegs *= 2; // inner sphere - if (TestShapeBit(kGeoPhiSeg)) nsegs += 2*nlat+nup+ndown; // 2 phi planes - nsegs += nlong * (2-nup - ndown); // connecting cones - - npols = fNz*fNseg; // outer - if (TestShapeBit(kGeoRSeg)) npols *=2; // inner - if (TestShapeBit(kGeoPhiSeg)) npols += 2*fNz; // 2 phi planes - npols += (2-nup-ndown)*fNseg; // connecting + if (TestShapeBit(kGeoPhiSeg)) + nlong++; + + nvert = nlat * nlong + nup + ndown + ncenter; + if (TestShapeBit(kGeoRSeg)) + nvert *= 2; + + nsegs = nlat * fNseg + (nlat - 1 + nup + ndown) * nlong; // outer sphere + if (TestShapeBit(kGeoRSeg)) + nsegs *= 2; // inner sphere + if (TestShapeBit(kGeoPhiSeg)) + nsegs += 2 * nlat + nup + ndown; // 2 phi planes + nsegs += nlong * (2 - nup - ndown); // connecting cones + + npols = fNz * fNseg; // outer + if (TestShapeBit(kGeoRSeg)) + npols *= 2; // inner + if (TestShapeBit(kGeoPhiSeg)) + npols += 2 * fNz; // 2 phi planes + npols += (2 - nup - ndown) * fNseg; // connecting } //////////////////////////////////////////////////////////////////////////////// @@ -1876,81 +2041,92 @@ void TGeoSphere::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoSphere::GetNmeshVertices() const { Bool_t full = kTRUE; - if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; + if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) + full = kFALSE; Int_t ncenter = 1; - if (full || TestShapeBit(kGeoRSeg)) ncenter = 0; - Int_t nup = (fTheta1>0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; + if (TestShapeBit(kGeoPhiSeg)) + nlong++; // total number of points on mesh is: // nlat*nlong + nup + ndown + ncenter; // in case rmin=0 // 2*(nlat*nlong + nup + ndown); // in case rmin>0 Int_t numPoints = 0; - if (TestShapeBit(kGeoRSeg)) numPoints = 2*(nlat*nlong+nup+ndown); - else numPoints = nlat*nlong+nup+ndown+ncenter; + if (TestShapeBit(kGeoRSeg)) + numPoints = 2 * (nlat * nlong + nup + ndown); + else + numPoints = nlat * nlong + nup + ndown + ncenter; return numPoints; } //////////////////////////////////////////////////////////////////////////////// ////// obsolete - to be removed -void TGeoSphere::Sizeof3D() const -{ -} +void TGeoSphere::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoSphere::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoSphere::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3DSphere buffer; TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kShapeSpecific) { - buffer.fRadiusInner = fRmin; - buffer.fRadiusOuter = fRmax; - buffer.fThetaMin = fTheta1; - buffer.fThetaMax = fTheta2; - buffer.fPhiMin = fPhi1; - buffer.fPhiMax = fPhi2; + buffer.fRadiusInner = fRmin; + buffer.fRadiusOuter = fRmax; + buffer.fThetaMin = fTheta1; + buffer.fThetaMax = fTheta2; + buffer.fPhiMin = fPhi1; + buffer.fPhiMax = fPhi2; buffer.SetSectionsValid(TBuffer3D::kShapeSpecific); } if (reqSections & TBuffer3D::kRawSizes) { // We want FillBuffer to be const - TGeoSphere * localThis = const_cast(this); + TGeoSphere *localThis = const_cast(this); localThis->SetNumberOfDivisions(gGeoManager->GetNsegments()); Bool_t full = kTRUE; - if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) full = kFALSE; + if (TestShapeBit(kGeoThetaSeg) || TestShapeBit(kGeoPhiSeg)) + full = kFALSE; Int_t ncenter = 1; - if (full || TestShapeBit(kGeoRSeg)) ncenter = 0; - Int_t nup = (fTheta1>0)?0:1; - Int_t ndown = (fTheta2<180)?0:1; + if (full || TestShapeBit(kGeoRSeg)) + ncenter = 0; + Int_t nup = (fTheta1 > 0) ? 0 : 1; + Int_t ndown = (fTheta2 < 180) ? 0 : 1; // number of different latitudes, excluding 0 and 180 degrees - Int_t nlat = fNz+1-(nup+ndown); + Int_t nlat = fNz + 1 - (nup + ndown); // number of different longitudes Int_t nlong = fNseg; - if (TestShapeBit(kGeoPhiSeg)) nlong++; - - Int_t nbPnts = nlat*nlong+nup+ndown+ncenter; - if (TestShapeBit(kGeoRSeg)) nbPnts *= 2; - - Int_t nbSegs = nlat*fNseg + (nlat-1+nup+ndown)*nlong; // outer sphere - if (TestShapeBit(kGeoRSeg)) nbSegs *= 2; // inner sphere - if (TestShapeBit(kGeoPhiSeg)) nbSegs += 2*nlat+nup+ndown; // 2 phi planes - nbSegs += nlong * (2-nup - ndown); // connecting cones - - Int_t nbPols = fNz*fNseg; // outer - if (TestShapeBit(kGeoRSeg)) nbPols *=2; // inner - if (TestShapeBit(kGeoPhiSeg)) nbPols += 2*fNz; // 2 phi planes - nbPols += (2-nup-ndown)*fNseg; // connecting - - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + if (TestShapeBit(kGeoPhiSeg)) + nlong++; + + Int_t nbPnts = nlat * nlong + nup + ndown + ncenter; + if (TestShapeBit(kGeoRSeg)) + nbPnts *= 2; + + Int_t nbSegs = nlat * fNseg + (nlat - 1 + nup + ndown) * nlong; // outer sphere + if (TestShapeBit(kGeoRSeg)) + nbSegs *= 2; // inner sphere + if (TestShapeBit(kGeoPhiSeg)) + nbSegs += 2 * nlat + nup + ndown; // 2 phi planes + nbSegs += nlong * (2 - nup - ndown); // connecting cones + + Int_t nbPols = fNz * fNseg; // outer + if (TestShapeBit(kGeoRSeg)) + nbPols *= 2; // inner + if (TestShapeBit(kGeoPhiSeg)) + nbPols += 2 * fNz; // 2 phi planes + nbPols += (2 - nup - ndown) * fNseg; // connecting + + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1973,7 +2149,8 @@ const TBuffer3D & TGeoSphere::GetBuffer3D(Int_t reqSections, Bool_t localFrame) void TGeoSphere::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i0) ? maxdaughters : TGeoManager::GetMaxDaughters(); - Int_t maxXtruVert = TGeoManager::GetMaxXtruVert(); + Int_t maxDaughters = (maxdaughters > 0) ? maxdaughters : TGeoManager::GetMaxDaughters(); + Int_t maxXtruVert = TGeoManager::GetMaxXtruVert(); fVoxCheckList = new Int_t[maxDaughters]; - fVoxBits1 = new UChar_t[2 + ((maxDaughters-1)>>3)]; + fVoxBits1 = new UChar_t[2 + ((maxDaughters - 1) >> 3)]; fXtruXc = new Double_t[maxXtruVert]; fXtruYc = new Double_t[maxXtruVert]; fVoxSlices[0] = fVoxSlices[1] = fVoxSlices[2] = -1; @@ -63,8 +63,8 @@ TGeoStateInfo::TGeoStateInfo(Int_t maxdaughters) TGeoStateInfo::~TGeoStateInfo() { - delete [] fVoxCheckList; - delete [] fVoxBits1; - delete [] fXtruXc; - delete [] fXtruYc; + delete[] fVoxCheckList; + delete[] fVoxBits1; + delete[] fXtruXc; + delete[] fXtruYc; } diff --git a/geom/geom/src/TGeoTessellated.cxx b/geom/geom/src/TGeoTessellated.cxx index 480d6eb08e20d..d6414f2a157fa 100644 --- a/geom/geom/src/TGeoTessellated.cxx +++ b/geom/geom/src/TGeoTessellated.cxx @@ -33,9 +33,9 @@ for the composing faces. #include #include -ClassImp(TGeoTessellated) +ClassImp(TGeoTessellated); - using Vertex_t = Tessellated::Vertex_t; +using Vertex_t = Tessellated::Vertex_t; std::ostream &operator<<(std::ostream &os, TGeoFacet const &facet) { diff --git a/geom/geom/src/TGeoTorus.cxx b/geom/geom/src/TGeoTorus.cxx index d2757c926a1fd..c67156e069d8f 100644 --- a/geom/geom/src/TGeoTorus.cxx +++ b/geom/geom/src/TGeoTorus.cxx @@ -66,7 +66,7 @@ ClassImp(TGeoTorus); TGeoTorus::TGeoTorus() { SetShapeBit(TGeoShape::kGeoTorus); - fR = 0.0; + fR = 0.0; fRmin = 0.0; fRmax = 0.0; fPhi1 = 0.0; @@ -76,12 +76,11 @@ TGeoTorus::TGeoTorus() //////////////////////////////////////////////////////////////////////////////// /// Constructor without name. -TGeoTorus::TGeoTorus(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi) - :TGeoBBox(0, 0, 0) +TGeoTorus::TGeoTorus(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoTorus); SetTorusDimensions(r, rmin, rmax, phi1, dphi); - if ((fRmin<0) || (fRmax<0)) + if ((fRmin < 0) || (fRmax < 0)) SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } @@ -90,11 +89,11 @@ TGeoTorus::TGeoTorus(Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Do /// Constructor with name. TGeoTorus::TGeoTorus(const char *name, Double_t r, Double_t rmin, Double_t rmax, Double_t phi1, Double_t dphi) - :TGeoBBox(name, 0, 0, 0) + : TGeoBBox(name, 0, 0, 0) { SetShapeBit(TGeoShape::kGeoTorus); SetTorusDimensions(r, rmin, rmax, phi1, dphi); - if ((fRmin<0) || (fRmax<0)) + if ((fRmin < 0) || (fRmax < 0)) SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } @@ -107,12 +106,12 @@ TGeoTorus::TGeoTorus(const char *name, Double_t r, Double_t rmin, Double_t rmax, /// - param[3] = Phi1 /// - param[4] = Dphi -TGeoTorus::TGeoTorus(Double_t *param) - :TGeoBBox(0, 0, 0) +TGeoTorus::TGeoTorus(Double_t *param) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoTorus); SetDimensions(param); - if (fRmin<0 || fRmax<0) SetShapeBit(kGeoRunTimeShape); + if (fRmin < 0 || fRmax < 0) + SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } @@ -121,7 +120,7 @@ TGeoTorus::TGeoTorus(Double_t *param) Double_t TGeoTorus::Capacity() const { - Double_t capacity = (fDphi/180.)*TMath::Pi()*TMath::Pi()*fR*(fRmax*fRmax-fRmin*fRmin); + Double_t capacity = (fDphi / 180.) * TMath::Pi() * TMath::Pi() * fR * (fRmax * fRmax - fRmin * fRmin); return capacity; } @@ -131,45 +130,56 @@ Double_t TGeoTorus::Capacity() const void TGeoTorus::ComputeBBox() { fDZ = fRmax; - if (TGeoShape::IsSameWithinTolerance(fDphi,360)) { - fDX = fDY = fR+fRmax; + if (TGeoShape::IsSameWithinTolerance(fDphi, 360)) { + fDX = fDY = fR + fRmax; return; } Double_t xc[4]; Double_t yc[4]; - xc[0] = (fR+fRmax)*TMath::Cos(fPhi1*TMath::DegToRad()); - yc[0] = (fR+fRmax)*TMath::Sin(fPhi1*TMath::DegToRad()); - xc[1] = (fR+fRmax)*TMath::Cos((fPhi1+fDphi)*TMath::DegToRad()); - yc[1] = (fR+fRmax)*TMath::Sin((fPhi1+fDphi)*TMath::DegToRad()); - xc[2] = (fR-fRmax)*TMath::Cos(fPhi1*TMath::DegToRad()); - yc[2] = (fR-fRmax)*TMath::Sin(fPhi1*TMath::DegToRad()); - xc[3] = (fR-fRmax)*TMath::Cos((fPhi1+fDphi)*TMath::DegToRad()); - yc[3] = (fR-fRmax)*TMath::Sin((fPhi1+fDphi)*TMath::DegToRad()); + xc[0] = (fR + fRmax) * TMath::Cos(fPhi1 * TMath::DegToRad()); + yc[0] = (fR + fRmax) * TMath::Sin(fPhi1 * TMath::DegToRad()); + xc[1] = (fR + fRmax) * TMath::Cos((fPhi1 + fDphi) * TMath::DegToRad()); + yc[1] = (fR + fRmax) * TMath::Sin((fPhi1 + fDphi) * TMath::DegToRad()); + xc[2] = (fR - fRmax) * TMath::Cos(fPhi1 * TMath::DegToRad()); + yc[2] = (fR - fRmax) * TMath::Sin(fPhi1 * TMath::DegToRad()); + xc[3] = (fR - fRmax) * TMath::Cos((fPhi1 + fDphi) * TMath::DegToRad()); + yc[3] = (fR - fRmax) * TMath::Sin((fPhi1 + fDphi) * TMath::DegToRad()); Double_t xmin = xc[TMath::LocMin(4, &xc[0])]; Double_t xmax = xc[TMath::LocMax(4, &xc[0])]; Double_t ymin = yc[TMath::LocMin(4, &yc[0])]; Double_t ymax = yc[TMath::LocMax(4, &yc[0])]; Double_t ddp = -fPhi1; - if (ddp<0) ddp+= 360; - if (ddp<=fDphi) xmax = fR+fRmax; - ddp = 90-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=fDphi) ymax = fR+fRmax; - ddp = 180-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=fDphi) xmin = -(fR+fRmax); - ddp = 270-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=fDphi) ymin = -(fR+fRmax); - fOrigin[0] = (xmax+xmin)/2; - fOrigin[1] = (ymax+ymin)/2; + if (ddp < 0) + ddp += 360; + if (ddp <= fDphi) + xmax = fR + fRmax; + ddp = 90 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= fDphi) + ymax = fR + fRmax; + ddp = 180 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= fDphi) + xmin = -(fR + fRmax); + ddp = 270 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= fDphi) + ymin = -(fR + fRmax); + fOrigin[0] = (xmax + xmin) / 2; + fOrigin[1] = (ymax + ymin) / 2; fOrigin[2] = 0; - fDX = (xmax-xmin)/2; - fDY = (ymax-ymin)/2; + fDX = (xmax - xmin) / 2; + fDY = (ymax - ymin) / 2; } //////////////////////////////////////////////////////////////////////////////// @@ -177,38 +187,38 @@ void TGeoTorus::ComputeBBox() void TGeoTorus::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { - Double_t phi = TMath::ATan2(point[1],point[0]); - if (fDphi<360) { - Double_t phi1 = fPhi1*TMath::DegToRad(); - Double_t phi2 = (fPhi1+fDphi)*TMath::DegToRad(); + Double_t phi = TMath::ATan2(point[1], point[0]); + if (fDphi < 360) { + Double_t phi1 = fPhi1 * TMath::DegToRad(); + Double_t phi2 = (fPhi1 + fDphi) * TMath::DegToRad(); Double_t c1 = TMath::Cos(phi1); Double_t s1 = TMath::Sin(phi1); Double_t c2 = TMath::Cos(phi2); Double_t s2 = TMath::Sin(phi2); - Double_t daxis = Daxis(point,dir,0); - if ((fRmax-daxis)>1E-5) { - if (TGeoShape::IsSameWithinTolerance(fRmin,0) || (daxis-fRmin)>1E-5) { - TGeoShape::NormalPhi(point,dir,norm,c1,s1,c2,s2); + Double_t daxis = Daxis(point, dir, 0); + if ((fRmax - daxis) > 1E-5) { + if (TGeoShape::IsSameWithinTolerance(fRmin, 0) || (daxis - fRmin) > 1E-5) { + TGeoShape::NormalPhi(point, dir, norm, c1, s1, c2, s2); return; } } } Double_t r0[3]; - r0[0] = fR*TMath::Cos(phi); - r0[1] = fR*TMath::Sin(phi); + r0[0] = fR * TMath::Cos(phi); + r0[1] = fR * TMath::Sin(phi); r0[2] = 0; Double_t normsq = 0; - for (Int_t i=0; i<3; i++) { + for (Int_t i = 0; i < 3; i++) { norm[i] = point[i] - r0[i]; - normsq += norm[i]*norm[i]; + normsq += norm[i] * norm[i]; } normsq = TMath::Sqrt(normsq); norm[0] /= normsq; norm[1] /= normsq; norm[2] /= normsq; - if (dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2] < 0) { + if (dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -221,18 +231,23 @@ void TGeoTorus::ComputeNormal(const Double_t *point, const Double_t *dir, Double Bool_t TGeoTorus::Contains(const Double_t *point) const { - if (!TGeoShape::IsSameWithinTolerance(fDphi,360)) { + if (!TGeoShape::IsSameWithinTolerance(fDphi, 360)) { Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - if (phi < 0) phi+=360.0; - Double_t ddp = phi-fPhi1; - if (ddp<0) ddp+=360.; - if (ddp>fDphi) return kFALSE; + if (phi < 0) + phi += 360.0; + Double_t ddp = phi - fPhi1; + if (ddp < 0) + ddp += 360.; + if (ddp > fDphi) + return kFALSE; } - //check radius - Double_t rxy = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); - Double_t radsq = (rxy-fR)*(rxy-fR) + point[2]*point[2]; - if (radsqfRmax*fRmax) return kFALSE; + // check radius + Double_t rxy = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); + Double_t radsq = (rxy - fR) * (rxy - fR) + point[2] * point[2]; + if (radsq < fRmin * fRmin) + return kFALSE; + if (radsq > fRmax * fRmax) + return kFALSE; return kTRUE; } @@ -241,10 +256,12 @@ Bool_t TGeoTorus::Contains(const Double_t *point) const Int_t TGeoTorus::DistancetoPrimitive(Int_t px, Int_t py) { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t numPoints = n*(n-1); - if (fRmin>0) numPoints *= 2; - else if (fDphi<360) numPoints += 2; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t numPoints = n * (n - 1); + if (fRmin > 0) + numPoints *= 2; + else if (fDphi < 360) + numPoints += 2; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -254,9 +271,10 @@ Int_t TGeoTorus::DistancetoPrimitive(Int_t px, Int_t py) Double_t TGeoTorus::Daxis(const Double_t *pt, const Double_t *dir, Double_t t) const { Double_t p[3]; - for (Int_t i=0; i<3; i++) p[i] = pt[i]+t*dir[i]; - Double_t rxy = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]); - return TMath::Sqrt((rxy-fR)*(rxy-fR)+p[2]*p[2]); + for (Int_t i = 0; i < 3; i++) + p[i] = pt[i] + t * dir[i]; + Double_t rxy = TMath::Sqrt(p[0] * p[0] + p[1] * p[1]); + return TMath::Sqrt((rxy - fR) * (rxy - fR) + p[2] * p[2]); } //////////////////////////////////////////////////////////////////////////////// @@ -265,12 +283,16 @@ Double_t TGeoTorus::Daxis(const Double_t *pt, const Double_t *dir, Double_t t) c Double_t TGeoTorus::DDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const { Double_t p[3]; - for (Int_t i=0; i<3; i++) p[i] = pt[i]+t*dir[i]; - Double_t rxy = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]); - if (rxy<1E-4) return ((p[2]*dir[2]-fR*TMath::Sqrt(dir[0]*dir[0]+dir[1]*dir[1]))/TMath::Sqrt(fR*fR+p[2]*p[2])); - Double_t d = TMath::Sqrt((rxy-fR)*(rxy-fR)+p[2]*p[2]); - if (TGeoShape::IsSameWithinTolerance(d,0)) return 0.; - Double_t dd = (p[0]*dir[0]+p[1]*dir[1]+p[2]*dir[2] - (p[0]*dir[0]+p[1]*dir[1])*fR/rxy)/d; + for (Int_t i = 0; i < 3; i++) + p[i] = pt[i] + t * dir[i]; + Double_t rxy = TMath::Sqrt(p[0] * p[0] + p[1] * p[1]); + if (rxy < 1E-4) + return ((p[2] * dir[2] - fR * TMath::Sqrt(dir[0] * dir[0] + dir[1] * dir[1])) / + TMath::Sqrt(fR * fR + p[2] * p[2])); + Double_t d = TMath::Sqrt((rxy - fR) * (rxy - fR) + p[2] * p[2]); + if (TGeoShape::IsSameWithinTolerance(d, 0)) + return 0.; + Double_t dd = (p[0] * dir[0] + p[1] * dir[1] + p[2] * dir[2] - (p[0] * dir[0] + p[1] * dir[1]) * fR / rxy) / d; return dd; } @@ -280,14 +302,18 @@ Double_t TGeoTorus::DDaxis(const Double_t *pt, const Double_t *dir, Double_t t) Double_t TGeoTorus::DDDaxis(const Double_t *pt, const Double_t *dir, Double_t t) const { Double_t p[3]; - for (Int_t i=0; i<3; i++) p[i] = pt[i]+t*dir[i]; - Double_t rxy = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]); - if (rxy<1E-6) return 0; - Double_t daxis = TMath::Sqrt((rxy-fR)*(rxy-fR)+p[2]*p[2]); - if (TGeoShape::IsSameWithinTolerance(daxis,0)) return 0; - Double_t ddaxis = (p[0]*dir[0]+p[1]*dir[1]+p[2]*dir[2] - (p[0]*dir[0]+p[1]*dir[1])*fR/rxy)/daxis; - Double_t dddaxis = 1 - ddaxis*ddaxis - (1-dir[2]*dir[2])*fR/rxy + - fR*(p[0]*dir[0]+p[1]*dir[1])*(p[0]*dir[0]+p[1]*dir[1])/(rxy*rxy*rxy); + for (Int_t i = 0; i < 3; i++) + p[i] = pt[i] + t * dir[i]; + Double_t rxy = TMath::Sqrt(p[0] * p[0] + p[1] * p[1]); + if (rxy < 1E-6) + return 0; + Double_t daxis = TMath::Sqrt((rxy - fR) * (rxy - fR) + p[2] * p[2]); + if (TGeoShape::IsSameWithinTolerance(daxis, 0)) + return 0; + Double_t ddaxis = + (p[0] * dir[0] + p[1] * dir[1] + p[2] * dir[2] - (p[0] * dir[0] + p[1] * dir[1]) * fR / rxy) / daxis; + Double_t dddaxis = 1 - ddaxis * ddaxis - (1 - dir[2] * dir[2]) * fR / rxy + + fR * (p[0] * dir[0] + p[1] * dir[1]) * (p[0] * dir[0] + p[1] * dir[1]) / (rxy * rxy * rxy); dddaxis /= daxis; return dddaxis; } @@ -295,36 +321,42 @@ Double_t TGeoTorus::DDDaxis(const Double_t *pt, const Double_t *dir, Double_t t) //////////////////////////////////////////////////////////////////////////////// /// Compute distance from inside point to surface of the torus. -Double_t TGeoTorus::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTorus::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } Bool_t hasphi = (fDphi < 360); Bool_t hasrmin = (fRmin > 0); - Double_t dout = ToBoundary(point,dir,fRmax,kTRUE); -// Double_t dax = Daxis(point,dir,dout); - Double_t din = (hasrmin)?ToBoundary(point,dir,fRmin,kTRUE):TGeoShape::Big(); - Double_t snext = TMath::Min(dout,din); - if (snext>1E10) return TGeoShape::Tolerance(); + Double_t dout = ToBoundary(point, dir, fRmax, kTRUE); + // Double_t dax = Daxis(point,dir,dout); + Double_t din = (hasrmin) ? ToBoundary(point, dir, fRmin, kTRUE) : TGeoShape::Big(); + Double_t snext = TMath::Min(dout, din); + if (snext > 1E10) + return TGeoShape::Tolerance(); if (hasphi) { // Torus segment case. - Double_t c1,s1,c2,s2,cm,sm,cdfi; - Double_t phi1=fPhi1*TMath::DegToRad(); - Double_t phi2=(fPhi1+fDphi)*TMath::DegToRad(); - c1=TMath::Cos(phi1); - s1=TMath::Sin(phi1); - c2=TMath::Cos(phi2); - s2=TMath::Sin(phi2); - Double_t fio=0.5*(phi1+phi2); - cm=TMath::Cos(fio); - sm=TMath::Sin(fio); - cdfi = TMath::Cos(0.5*(phi2-phi1)); - Double_t dphi = TGeoTubeSeg::DistFromInsideS(point,dir,fR-fRmax,fR+fRmax, fRmax, c1,s1,c2,s2,cm,sm,cdfi); - Double_t daxis = Daxis(point,dir,dphi); - if (daxis>=fRmin+1.E-8 && daxis<=fRmax-1.E-8) snext=TMath::Min(snext,dphi); + Double_t c1, s1, c2, s2, cm, sm, cdfi; + Double_t phi1 = fPhi1 * TMath::DegToRad(); + Double_t phi2 = (fPhi1 + fDphi) * TMath::DegToRad(); + c1 = TMath::Cos(phi1); + s1 = TMath::Sin(phi1); + c2 = TMath::Cos(phi2); + s2 = TMath::Sin(phi2); + Double_t fio = 0.5 * (phi1 + phi2); + cm = TMath::Cos(fio); + sm = TMath::Sin(fio); + cdfi = TMath::Cos(0.5 * (phi2 - phi1)); + Double_t dphi = + TGeoTubeSeg::DistFromInsideS(point, dir, fR - fRmax, fR + fRmax, fRmax, c1, s1, c2, s2, cm, sm, cdfi); + Double_t daxis = Daxis(point, dir, dphi); + if (daxis >= fRmin + 1.E-8 && daxis <= fRmax - 1.E-8) + snext = TMath::Min(snext, dphi); } return snext; } @@ -332,51 +364,61 @@ Double_t TGeoTorus::DistFromInside(const Double_t *point, const Double_t *dir, I //////////////////////////////////////////////////////////////////////////////// /// Compute distance from outside point to surface of the torus. -Double_t TGeoTorus::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTorus::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); Double_t daxis; - Bool_t hasphi = (fDphi<360)?kTRUE:kFALSE; -// Bool_t hasrmin = (fRmin>0)?kTRUE:kFALSE; - Double_t c1=0,s1=0,c2=0,s2=0,cm=0,sm=0,cdfi=0; + Bool_t hasphi = (fDphi < 360) ? kTRUE : kFALSE; + // Bool_t hasrmin = (fRmin>0)?kTRUE:kFALSE; + Double_t c1 = 0, s1 = 0, c2 = 0, s2 = 0, cm = 0, sm = 0, cdfi = 0; Bool_t inphi = kFALSE; - Double_t phi, ddp, phi1,phi2,fio; - Double_t rxy2,dd; + Double_t phi, ddp, phi1, phi2, fio; + Double_t rxy2, dd; Double_t snext; Double_t pt[3]; Int_t i; if (hasphi) { // Torus segment case. - phi=TMath::ATan2(point[1], point[0])*TMath::RadToDeg();; - if (phi<0) phi+=360; - ddp = phi-fPhi1; - if (ddp<0) ddp+=360;; - if (ddp<=fDphi) inphi=kTRUE; - phi1=fPhi1*TMath::DegToRad(); - phi2=(fPhi1+fDphi)*TMath::DegToRad(); - c1=TMath::Cos(phi1); - s1=TMath::Sin(phi1); - c2=TMath::Cos(phi2); - s2=TMath::Sin(phi2); - fio=0.5*(phi1+phi2); - cm=TMath::Cos(fio); - sm=TMath::Sin(fio); - cdfi=TMath::Cos(0.5*(phi2-phi1)); + phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); + ; + if (phi < 0) + phi += 360; + ddp = phi - fPhi1; + if (ddp < 0) + ddp += 360; + ; + if (ddp <= fDphi) + inphi = kTRUE; + phi1 = fPhi1 * TMath::DegToRad(); + phi2 = (fPhi1 + fDphi) * TMath::DegToRad(); + c1 = TMath::Cos(phi1); + s1 = TMath::Sin(phi1); + c2 = TMath::Cos(phi2); + s2 = TMath::Sin(phi2); + fio = 0.5 * (phi1 + phi2); + cm = TMath::Cos(fio); + sm = TMath::Sin(fio); + cdfi = TMath::Cos(0.5 * (phi2 - phi1)); } // Check if we are inside or outside the bounding ring. Bool_t inbring = kFALSE; if (TMath::Abs(point[2]) <= fRmax) { - rxy2 = point[0]*point[0]+point[1]*point[1]; - if ((rxy2>=(fR-fRmax)*(fR-fRmax)) && (rxy2<=(fR+fRmax)*(fR+fRmax))) { - if (!hasphi || inphi) inbring=kTRUE; + rxy2 = point[0] * point[0] + point[1] * point[1]; + if ((rxy2 >= (fR - fRmax) * (fR - fRmax)) && (rxy2 <= (fR + fRmax) * (fR + fRmax))) { + if (!hasphi || inphi) + inbring = kTRUE; } } @@ -385,61 +427,79 @@ Double_t TGeoTorus::DistFromOutside(const Double_t *point, const Double_t *dir, Double_t eps = 1.E-8; snext = 0; daxis = -1; - memcpy(pt,point,3*sizeof(Double_t)); + memcpy(pt, point, 3 * sizeof(Double_t)); if (!inbring) { - if (hasphi) dring = TGeoTubeSeg::DistFromOutsideS(point,dir,TMath::Max(0.,fR-fRmax-eps),fR+fRmax+eps, fRmax+eps, c1,s1,c2,s2,cm,sm,cdfi); - else dring = TGeoTube::DistFromOutsideS(point,dir,TMath::Max(0.,fR-fRmax-eps),fR+fRmax+eps, fRmax+eps); + if (hasphi) + dring = TGeoTubeSeg::DistFromOutsideS(point, dir, TMath::Max(0., fR - fRmax - eps), fR + fRmax + eps, + fRmax + eps, c1, s1, c2, s2, cm, sm, cdfi); + else + dring = + TGeoTube::DistFromOutsideS(point, dir, TMath::Max(0., fR - fRmax - eps), fR + fRmax + eps, fRmax + eps); // If not crossing it, return BIG. - if (dring>1E10) return TGeoShape::Big(); + if (dring > 1E10) + return TGeoShape::Big(); snext = dring; // Check if the crossing is due to phi. - daxis = Daxis(point,dir,snext); - if (daxis>=fRmin && daxis= fRmin && daxis < fRmax) + return snext; // Not a phi crossing -> propagate until we cross the ring. - for (i=0; i<3; i++) pt[i] = point[i]+snext*dir[i]; + for (i = 0; i < 3; i++) + pt[i] = point[i] + snext * dir[i]; } // Point pt is inside the bounding ring, no phi crossing so far. // Check if we are in the hole. - if (daxis<0) daxis = Daxis(pt,dir,0); - if (daxis0) { + if (snext > 0) { // we can cross either the inner torus or exit the other hole. - snext += 0.1*eps; - for (i=0; i<3; i++) pt[i] += 0.1*eps*dir[i]; + snext += 0.1 * eps; + for (i = 0; i < 3; i++) + pt[i] += 0.1 * eps * dir[i]; } // We are in the hole from the beginning. // find first crossing with inner torus - dd = ToBoundary(pt,dir, fRmin,kFALSE); + dd = ToBoundary(pt, dir, fRmin, kFALSE); // find exit distance from inner bounding ring - if (hasphi) dring = TGeoTubeSeg::DistFromInsideS(pt,dir,fR-fRmin,fR+fRmin, fRmin, c1,s1,c2,s2,cm,sm,cdfi); - else dring = TGeoTube::DistFromInsideS(pt,dir,fR-fRmin,fR+fRmin, fRmin); - if (ddfRmax // Compute distance to exit the bounding ring (again) - if (snext>0) { + if (snext > 0) { // we can cross either the inner torus or exit the other hole. - snext += 0.1*eps; - for (i=0; i<3; i++) pt[i] += 0.1*eps*dir[i]; + snext += 0.1 * eps; + for (i = 0; i < 3; i++) + pt[i] += 0.1 * eps * dir[i]; } // Check intersection with outer torus dd = ToBoundary(pt, dir, fRmax, kFALSE); - if (hasphi) dring = TGeoTubeSeg::DistFromInsideS(pt,dir,TMath::Max(0.,fR-fRmax-eps),fR+fRmax+eps, fRmax+eps, c1,s1,c2,s2,cm,sm,cdfi); - else dring = TGeoTube::DistFromInsideS(pt,dir,TMath::Max(0.,fR-fRmax-eps),fR+fRmax+eps, fRmax+eps); - if (dd propagate - snext += dring+eps; - for (i=0; i<3; i++) pt[i] = point[i] + snext*dir[i]; - snext += DistFromOutside(pt,dir,3); + snext += dring + eps; + for (i = 0; i < 3; i++) + pt[i] = point[i] + snext * dir[i]; + snext += DistFromOutside(pt, dir, 3); return snext; } @@ -459,14 +519,10 @@ TGeoVolume *TGeoTorus::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, const char *TGeoTorus::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "R"; - case 2: - return "PHI"; - case 3: - return "Z"; - default: - return "UNDEFINED"; + case 1: return "R"; + case 2: return "PHI"; + case 3: return "Z"; + default: return "UNDEFINED"; } } @@ -479,19 +535,17 @@ Double_t TGeoTorus::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) cons xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fRmin; - xhi = fRmax; - dx = xhi-xlo; - return dx; - case 2: - xlo = fPhi1; - xhi = fPhi1+fDphi; - dx = fDphi; - return dx; - case 3: - dx = 0; - return dx; + case 1: + xlo = fRmin; + xhi = fRmax; + dx = xhi - xlo; + return dx; + case 2: + xlo = fPhi1; + xhi = fPhi1 + fDphi; + dx = fDphi; + return dx; + case 3: dx = 0; return dx; } return dx; } @@ -502,10 +556,10 @@ Double_t TGeoTorus::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) cons void TGeoTorus::GetBoundingCylinder(Double_t *param) const { - param[0] = (fR-fRmax); // Rmin - param[1] = (fR+fRmax); // Rmax - param[2] = fPhi1; // Phi1 - param[3] = fPhi1+fDphi; // Phi2 + param[0] = (fR - fRmax); // Rmin + param[1] = (fR + fRmax); // Rmax + param[2] = fPhi1; // Phi1 + param[3] = fPhi1 + fDphi; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -513,7 +567,8 @@ void TGeoTorus::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoTorus::GetMakeRuntimeShape(TGeoShape * /*mother*/, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; Error("GetMakeRuntimeShape", "parametrized toruses not supported"); return 0; } @@ -539,28 +594,29 @@ void TGeoTorus::InspectShape() const TBuffer3D *TGeoTorus::MakeBuffer3D() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = n*(n-1); - Bool_t hasrmin = (GetRmin()>0)?kTRUE:kFALSE; - Bool_t hasphi = (GetDphi()<360)?kTRUE:kFALSE; - if (hasrmin) nbPnts *= 2; - else if (hasphi) nbPnts += 2; - - Int_t nbSegs = (2*n-1)*(n-1); - Int_t nbPols = (n-1)*(n-1); + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = n * (n - 1); + Bool_t hasrmin = (GetRmin() > 0) ? kTRUE : kFALSE; + Bool_t hasphi = (GetDphi() < 360) ? kTRUE : kFALSE; + if (hasrmin) + nbPnts *= 2; + else if (hasphi) + nbPnts += 2; + + Int_t nbSegs = (2 * n - 1) * (n - 1); + Int_t nbPols = (n - 1) * (n - 1); if (hasrmin) { - nbSegs += (2*n-1)*(n-1); - nbPols += (n-1)*(n-1); + nbSegs += (2 * n - 1) * (n - 1); + nbPols += (n - 1) * (n - 1); } if (hasphi) { - nbSegs += 2*(n-1); - nbPols += 2*(n-1); + nbSegs += 2 * (n - 1); + nbPols += 2 * (n - 1); } - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols); - if (buff) - { + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -574,153 +630,153 @@ TBuffer3D *TGeoTorus::MakeBuffer3D() const void TGeoTorus::SetSegsAndPols(TBuffer3D &buff) const { Int_t i, j; - Int_t n = gGeoManager->GetNsegments()+1; + Int_t n = gGeoManager->GetNsegments() + 1; // Int_t nbPnts = n*(n-1); - Int_t indx, indp, startcap=0; - Bool_t hasrmin = (GetRmin()>0)?kTRUE:kFALSE; - Bool_t hasphi = (GetDphi()<360)?kTRUE:kFALSE; + Int_t indx, indp, startcap = 0; + Bool_t hasrmin = (GetRmin() > 0) ? kTRUE : kFALSE; + Bool_t hasphi = (GetDphi() < 360) ? kTRUE : kFALSE; // if (hasrmin) nbPnts *= 2; // else if (hasphi) nbPnts += 2; Int_t c = GetBasicColor(); - indp = n*(n-1); // start index for points on inner surface - memset(buff.fSegs, 0, buff.NbSegs()*3*sizeof(Int_t)); + indp = n * (n - 1); // start index for points on inner surface + memset(buff.fSegs, 0, buff.NbSegs() * 3 * sizeof(Int_t)); // outer surface phi circles = n*(n-1) -> [0, n*(n-1) -1] // connect point j with point j+1 on same row indx = 0; - for (i = 0; i < n; i++) { // rows [0,n-1] - for (j = 0; j < n-1; j++) { // points on a row [0, n-2] - buff.fSegs[indx+(i*(n-1)+j)*3] = c; - buff.fSegs[indx+(i*(n-1)+j)*3+1] = i*(n-1)+j; // j on row i - buff.fSegs[indx+(i*(n-1)+j)*3+2] = i*(n-1)+((j+1)%(n-1)); // j+1 on row i + for (i = 0; i < n; i++) { // rows [0,n-1] + for (j = 0; j < n - 1; j++) { // points on a row [0, n-2] + buff.fSegs[indx + (i * (n - 1) + j) * 3] = c; + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 1] = i * (n - 1) + j; // j on row i + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 2] = i * (n - 1) + ((j + 1) % (n - 1)); // j+1 on row i } } - indx += 3*n*(n-1); + indx += 3 * n * (n - 1); // outer surface generators = (n-1)*(n-1) -> [n*(n-1), (2*n-1)*(n-1) -1] // connect point j on row i with point j on row i+1 - for (i = 0; i < n-1; i++) { // rows [0, n-2] - for (j = 0; j < n-1; j++) { // points on a row [0, n-2] - buff.fSegs[indx+(i*(n-1)+j)*3] = c; - buff.fSegs[indx+(i*(n-1)+j)*3+1] = i*(n-1)+j; // j on row i - buff.fSegs[indx+(i*(n-1)+j)*3+2] = (i+1)*(n-1)+j; // j on row i+1 + for (i = 0; i < n - 1; i++) { // rows [0, n-2] + for (j = 0; j < n - 1; j++) { // points on a row [0, n-2] + buff.fSegs[indx + (i * (n - 1) + j) * 3] = c; + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 1] = i * (n - 1) + j; // j on row i + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 2] = (i + 1) * (n - 1) + j; // j on row i+1 } } - indx += 3*(n-1)*(n-1); - startcap = (2*n-1)*(n-1); + indx += 3 * (n - 1) * (n - 1); + startcap = (2 * n - 1) * (n - 1); if (hasrmin) { // inner surface phi circles = n*(n-1) -> [(2*n-1)*(n-1), (3*n-1)*(n-1) -1] // connect point j with point j+1 on same row - for (i = 0; i < n; i++) { // rows [0, n-1] - for (j = 0; j < n-1; j++) { // points on a row [0, n-2] - buff.fSegs[indx+(i*(n-1)+j)*3] = c; // lighter color - buff.fSegs[indx+(i*(n-1)+j)*3+1] = indp + i*(n-1)+j; // j on row i - buff.fSegs[indx+(i*(n-1)+j)*3+2] = indp + i*(n-1)+((j+1)%(n-1)); // j+1 on row i + for (i = 0; i < n; i++) { // rows [0, n-1] + for (j = 0; j < n - 1; j++) { // points on a row [0, n-2] + buff.fSegs[indx + (i * (n - 1) + j) * 3] = c; // lighter color + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 1] = indp + i * (n - 1) + j; // j on row i + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 2] = indp + i * (n - 1) + ((j + 1) % (n - 1)); // j+1 on row i } } - indx += 3*n*(n-1); + indx += 3 * n * (n - 1); // inner surface generators = (n-1)*n -> [(3*n-1)*(n-1), (4*n-2)*(n-1) -1] // connect point j on row i with point j on row i+1 - for (i = 0; i < n-1; i++) { // rows [0, n-2] - for (j = 0; j < n-1; j++) { // points on a row [0, n-2] - buff.fSegs[indx+(i*(n-1)+j)*3] = c; // lighter color - buff.fSegs[indx+(i*(n-1)+j)*3+1] = indp + i*(n-1)+j; // j on row i - buff.fSegs[indx+(i*(n-1)+j)*3+2] = indp + (i+1)*(n-1)+j; // j on row i+1 + for (i = 0; i < n - 1; i++) { // rows [0, n-2] + for (j = 0; j < n - 1; j++) { // points on a row [0, n-2] + buff.fSegs[indx + (i * (n - 1) + j) * 3] = c; // lighter color + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 1] = indp + i * (n - 1) + j; // j on row i + buff.fSegs[indx + (i * (n - 1) + j) * 3 + 2] = indp + (i + 1) * (n - 1) + j; // j on row i+1 } } - indx += 3*(n-1)*(n-1); - startcap = (4*n-2)*(n-1); + indx += 3 * (n - 1) * (n - 1); + startcap = (4 * n - 2) * (n - 1); } if (hasphi) { if (hasrmin) { // endcaps = 2*(n-1) -> [(4*n-2)*(n-1), 4*n*(n-1)-1] i = 0; - for (j = 0; j < n-1; j++) { - buff.fSegs[indx+j*3] = c+1; - buff.fSegs[indx+j*3+1] = (n-1)*i+j; // outer j on row 0 - buff.fSegs[indx+j*3+2] = indp+(n-1)*i+j; // inner j on row 0 + for (j = 0; j < n - 1; j++) { + buff.fSegs[indx + j * 3] = c + 1; + buff.fSegs[indx + j * 3 + 1] = (n - 1) * i + j; // outer j on row 0 + buff.fSegs[indx + j * 3 + 2] = indp + (n - 1) * i + j; // inner j on row 0 } - indx += 3*(n-1); - i = n-1; - for (j = 0; j < n-1; j++) { - buff.fSegs[indx+j*3] = c+1; - buff.fSegs[indx+j*3+1] = (n-1)*i+j; // outer j on row n-1 - buff.fSegs[indx+j*3+2] = indp+(n-1)*i+j; // inner j on row n-1 + indx += 3 * (n - 1); + i = n - 1; + for (j = 0; j < n - 1; j++) { + buff.fSegs[indx + j * 3] = c + 1; + buff.fSegs[indx + j * 3 + 1] = (n - 1) * i + j; // outer j on row n-1 + buff.fSegs[indx + j * 3 + 2] = indp + (n - 1) * i + j; // inner j on row n-1 } - indx += 3*(n-1); + indx += 3 * (n - 1); } else { i = 0; - for (j = 0; j < n-1; j++) { - buff.fSegs[indx+j*3] = c+1; - buff.fSegs[indx+j*3+1] = (n-1)*i+j; // outer j on row 0 - buff.fSegs[indx+j*3+2] = n*(n-1); // center of first endcap + for (j = 0; j < n - 1; j++) { + buff.fSegs[indx + j * 3] = c + 1; + buff.fSegs[indx + j * 3 + 1] = (n - 1) * i + j; // outer j on row 0 + buff.fSegs[indx + j * 3 + 2] = n * (n - 1); // center of first endcap } - indx += 3*(n-1); - i = n-1; - for (j = 0; j < n-1; j++) { - buff.fSegs[indx+j*3] = c+1; - buff.fSegs[indx+j*3+1] = (n-1)*i+j; // outer j on row n-1 - buff.fSegs[indx+j*3+2] = n*(n-1)+1; // center of second endcap + indx += 3 * (n - 1); + i = n - 1; + for (j = 0; j < n - 1; j++) { + buff.fSegs[indx + j * 3] = c + 1; + buff.fSegs[indx + j * 3 + 1] = (n - 1) * i + j; // outer j on row n-1 + buff.fSegs[indx + j * 3 + 2] = n * (n - 1) + 1; // center of second endcap } - indx += 3*(n-1); + indx += 3 * (n - 1); } } indx = 0; - memset(buff.fPols, 0, buff.NbPols()*6*sizeof(Int_t)); + memset(buff.fPols, 0, buff.NbPols() * 6 * sizeof(Int_t)); // outer surface = (n-1)*(n-1) -> [0, (n-1)*(n-1)-1] // normal pointing out - for (i=0; i [(n-1)*(n-1), 2*(n-1)*(n-1)-1] // normal pointing out - for (i=0; i - buff.fPols[indx++] = indp+(n-1)*i+j; // seg j on inner row i + buff.fPols[indx++] = indp + n * (n - 1) + (n - 1) * i + j; // generator j on inner row i + buff.fPols[indx++] = indp + (n - 1) * (i + 1) + j; // seg j on inner row i+1 + buff.fPols[indx++] = indp + n * (n - 1) + (n - 1) * i + ((j + 1) % (n - 1)); // generator j+1 on inner r> + buff.fPols[indx++] = indp + (n - 1) * i + j; // seg j on inner row i } } } if (hasphi) { // endcaps = 2*(n-1) -> [2*(n-1)*(n-1), 2*n*(n-1)-1] - i=0; // row 0 - Int_t np = (hasrmin)?4:3; - for (j=0; jGetNsegments()+1; + if (!points) + return; + Int_t n = gGeoManager->GetNsegments() + 1; Double_t phin, phout; - Double_t dpin = 360./(n-1); - Double_t dpout = fDphi/(n-1); - Double_t co,so,ci,si; - Bool_t havermin = (fRmin n*(n-1) points [0, 3*n*(n-1)-1] - for (i=0; i n*(n-1) points [3*n*(n-1), 6*n*(n-1)] - for (i=0; i n*(n-1) points [3*n*(n-1), 6*n*(n-1)] + for (i = 0; i < n; i++) { + phout = (fPhi1 + i * dpout) * TMath::DegToRad(); co = TMath::Cos(phout); so = TMath::Sin(phout); - for (j=0; jGetNsegments()+1; + if (!points) + return; + Int_t n = gGeoManager->GetNsegments() + 1; Double_t phin, phout; - Double_t dpin = 360./(n-1); - Double_t dpout = fDphi/(n-1); - Double_t co,so,ci,si; - Bool_t havermin = (fRmin n*(n-1) points [0, 3*n*(n-1)-1] // plane i = 0, n-1 point j = 0, n-1 ipoint = n*i + j - for (i=0; i n*(n-1) points [3*n*(n-1), 6*n*(n-1)] + // loop inner mesh -> n*(n-1) points [3*n*(n-1), 6*n*(n-1)] // plane i = 0, n-1 point j = 0, n-1 ipoint = n*n + n*i + j - for (i=0; iGetNsegments()+1; - Int_t numPoints = n*(n-1); - if (fRmin>TGeoShape::Tolerance()) numPoints *= 2; - else if (fDphi<360.) numPoints += 2; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t numPoints = n * (n - 1); + if (fRmin > TGeoShape::Tolerance()) + numPoints *= 2; + else if (fDphi < 360.) + numPoints += 2; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoTorus::Sizeof3D() const -{ -} +void TGeoTorus::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Find real solutions of the cubic equation : x^3 + a*x^2 + b*x + c = 0 @@ -936,36 +999,36 @@ void TGeoTorus::Sizeof3D() const Int_t TGeoTorus::SolveCubic(Double_t a, Double_t b, Double_t c, Double_t *x) const { - const Double_t ott = 1./3.; + const Double_t ott = 1. / 3.; const Double_t sq3 = TMath::Sqrt(3.); Int_t ireal = 1; - Double_t p = b-a*a*ott; - Double_t q = c-a*b*ott+2.*a*a*a*ott*ott*ott; - Double_t delta = 4*p*p*p+27*q*q; -// Double_t y1r, y1i, y2r, y2i; - Double_t t,u; - if (delta>=0) { + Double_t p = b - a * a * ott; + Double_t q = c - a * b * ott + 2. * a * a * a * ott * ott * ott; + Double_t delta = 4 * p * p * p + 27 * q * q; + // Double_t y1r, y1i, y2r, y2i; + Double_t t, u; + if (delta >= 0) { delta = TMath::Sqrt(delta); - t = (-3*q*sq3+delta)/(6*sq3); - u = (3*q*sq3+delta)/(6*sq3); - x[0] = TMath::Sign(1.,t)*TMath::Power(TMath::Abs(t),ott)- - TMath::Sign(1.,u)*TMath::Power(TMath::Abs(u),ott)-a*ott; + t = (-3 * q * sq3 + delta) / (6 * sq3); + u = (3 * q * sq3 + delta) / (6 * sq3); + x[0] = TMath::Sign(1., t) * TMath::Power(TMath::Abs(t), ott) - + TMath::Sign(1., u) * TMath::Power(TMath::Abs(u), ott) - a * ott; } else { delta = TMath::Sqrt(-delta); - t = -0.5*q; - u = delta/(6*sq3); - x[0] = 2.*TMath::Power(t*t+u*u,0.5*ott) * TMath::Cos(ott*TMath::ATan2(u,t)); - x[0] -= a*ott; + t = -0.5 * q; + u = delta / (6 * sq3); + x[0] = 2. * TMath::Power(t * t + u * u, 0.5 * ott) * TMath::Cos(ott * TMath::ATan2(u, t)); + x[0] -= a * ott; } - t = x[0]*x[0]+a*x[0]+b; - u = a+x[0]; - delta = u*u-4.*t; - if (delta>=0) { + t = x[0] * x[0] + a * x[0] + b; + u = a + x[0]; + delta = u * u - 4. * t; + if (delta >= 0) { ireal = 3; delta = TMath::Sqrt(delta); - x[1] = 0.5*(-u-delta); - x[2] = 0.5*(-u+delta); + x[1] = 0.5 * (-u - delta); + x[2] = 0.5 * (-u + delta); } return ireal; } @@ -978,83 +1041,90 @@ Int_t TGeoTorus::SolveCubic(Double_t a, Double_t b, Double_t c, Double_t *x) con Int_t TGeoTorus::SolveQuartic(Double_t a, Double_t b, Double_t c, Double_t d, Double_t *x) const { - Double_t e = b-3.*a*a/8.; - Double_t f = c+a*a*a/8.-0.5*a*b; - Double_t g = d-3.*a*a*a*a/256. + a*a*b/16. - a*c/4.; + Double_t e = b - 3. * a * a / 8.; + Double_t f = c + a * a * a / 8. - 0.5 * a * b; + Double_t g = d - 3. * a * a * a * a / 256. + a * a * b / 16. - a * c / 4.; Double_t xx[4]; - Int_t ind[4]; + Int_t ind[4]; Double_t delta; - Double_t h=0; + Double_t h = 0; Int_t ireal = 0; Int_t i; - if (TGeoShape::IsSameWithinTolerance(f,0)) { - delta = e*e-4.*g; - if (delta<0) return 0; + if (TGeoShape::IsSameWithinTolerance(f, 0)) { + delta = e * e - 4. * g; + if (delta < 0) + return 0; delta = TMath::Sqrt(delta); - h = 0.5*(-e-delta); - if (h>=0) { + h = 0.5 * (-e - delta); + if (h >= 0) { h = TMath::Sqrt(h); - x[ireal++] = -h-0.25*a; - x[ireal++] = h-0.25*a; + x[ireal++] = -h - 0.25 * a; + x[ireal++] = h - 0.25 * a; } - h = 0.5*(-e+delta); - if (h>=0) { + h = 0.5 * (-e + delta); + if (h >= 0) { h = TMath::Sqrt(h); - x[ireal++] = -h-0.25*a; - x[ireal++] = h-0.25*a; + x[ireal++] = -h - 0.25 * a; + x[ireal++] = h - 0.25 * a; } - if (ireal>0) { - TMath::Sort(ireal, x, ind,kFALSE); - for (i=0; i 0) { + TMath::Sort(ireal, x, ind, kFALSE); + for (i = 0; i < ireal; i++) + xx[i] = x[ind[i]]; + memcpy(x, xx, ireal * sizeof(Double_t)); } return ireal; } - if (TGeoShape::IsSameWithinTolerance(g,0)) { - x[ireal++] = -0.25*a; - ind[0] = SolveCubic(0,e,f,xx); - for (i=0; i0) { - TMath::Sort(ireal, x, ind,kFALSE); - for (i=0; i 0) { + TMath::Sort(ireal, x, ind, kFALSE); + for (i = 0; i < ireal; i++) + xx[i] = x[ind[i]]; + memcpy(x, xx, ireal * sizeof(Double_t)); } return ireal; } - - ireal = SolveCubic(2.*e, e*e-4.*g, -f*f, xx); - if (ireal==1) { - if (xx[0]<=0) return 0; + ireal = SolveCubic(2. * e, e * e - 4. * g, -f * f, xx); + if (ireal == 1) { + if (xx[0] <= 0) + return 0; h = TMath::Sqrt(xx[0]); } else { // 3 real solutions of the cubic - for (i=0; i<3; i++) { + for (i = 0; i < 3; i++) { h = xx[i]; - if (h>=0) break; + if (h >= 0) + break; } - if (h<=0) return 0; + if (h <= 0) + return 0; h = TMath::Sqrt(h); } - Double_t j = 0.5*(e+h*h-f/h); + Double_t j = 0.5 * (e + h * h - f / h); ireal = 0; - delta = h*h-4.*j; - if (delta>=0) { + delta = h * h - 4. * j; + if (delta >= 0) { delta = TMath::Sqrt(delta); - x[ireal++] = 0.5*(-h-delta)-0.25*a; - x[ireal++] = 0.5*(-h+delta)-0.25*a; + x[ireal++] = 0.5 * (-h - delta) - 0.25 * a; + x[ireal++] = 0.5 * (-h + delta) - 0.25 * a; } - delta = h*h-4.*g/j; - if (delta>=0) { + delta = h * h - 4. * g / j; + if (delta >= 0) { delta = TMath::Sqrt(delta); - x[ireal++] = 0.5*(h-delta)-0.25*a; - x[ireal++] = 0.5*(h+delta)-0.25*a; + x[ireal++] = 0.5 * (h - delta) - 0.25 * a; + x[ireal++] = 0.5 * (h + delta) - 0.25 * a; } - if (ireal>0) { - TMath::Sort(ireal, x, ind,kFALSE); - for (i=0; i 0) { + TMath::Sort(ireal, x, ind, kFALSE); + for (i = 0; i < ireal; i++) + xx[i] = x[ind[i]]; + memcpy(x, xx, ireal * sizeof(Double_t)); } return ireal; } @@ -1068,79 +1138,93 @@ Double_t TGeoTorus::ToBoundary(const Double_t *pt, const Double_t *dir, Double_t { // Compute coefficients of the quartic Double_t tol = TGeoShape::Tolerance(); - Double_t r0sq = pt[0]*pt[0]+pt[1]*pt[1]+pt[2]*pt[2]; - Double_t rdotn = pt[0]*dir[0]+pt[1]*dir[1]+pt[2]*dir[2]; - Double_t rsumsq = fR*fR+r*r; - Double_t a = 4.*rdotn; - Double_t b = 2.*(r0sq+2.*rdotn*rdotn-rsumsq+2.*fR*fR*dir[2]*dir[2]); - Double_t c = 4.*(r0sq*rdotn-rsumsq*rdotn+2.*fR*fR*pt[2]*dir[2]); - Double_t d = r0sq*r0sq-2.*r0sq*rsumsq+4.*fR*fR*pt[2]*pt[2]+(fR*fR-r*r)*(fR*fR-r*r); - - Double_t x[4],y[4]; + Double_t r0sq = pt[0] * pt[0] + pt[1] * pt[1] + pt[2] * pt[2]; + Double_t rdotn = pt[0] * dir[0] + pt[1] * dir[1] + pt[2] * dir[2]; + Double_t rsumsq = fR * fR + r * r; + Double_t a = 4. * rdotn; + Double_t b = 2. * (r0sq + 2. * rdotn * rdotn - rsumsq + 2. * fR * fR * dir[2] * dir[2]); + Double_t c = 4. * (r0sq * rdotn - rsumsq * rdotn + 2. * fR * fR * pt[2] * dir[2]); + Double_t d = r0sq * r0sq - 2. * r0sq * rsumsq + 4. * fR * fR * pt[2] * pt[2] + (fR * fR - r * r) * (fR * fR - r * r); + + Double_t x[4], y[4]; Int_t nsol = 0; - if (TMath::Abs(dir[2])<1E-3 && TMath::Abs(pt[2])<0.1*r) { - Double_t r0 = fR - TMath::Sqrt((r-pt[2])*(r+pt[2])); - Double_t b0 = (pt[0]*dir[0]+pt[1]*dir[1])/(dir[0]*dir[0]+dir[1]*dir[1]); - Double_t c0 = (pt[0]*pt[0] + (pt[1]-r0)*(pt[1]+r0))/(dir[0]*dir[0]+dir[1]*dir[1]); - Double_t delta = b0*b0-c0; - if (delta>0) { - y[nsol] = -b0-TMath::Sqrt(delta); - if (y[nsol]>-tol) nsol++; - y[nsol] = -b0+TMath::Sqrt(delta); - if (y[nsol]>-tol) nsol++; + if (TMath::Abs(dir[2]) < 1E-3 && TMath::Abs(pt[2]) < 0.1 * r) { + Double_t r0 = fR - TMath::Sqrt((r - pt[2]) * (r + pt[2])); + Double_t b0 = (pt[0] * dir[0] + pt[1] * dir[1]) / (dir[0] * dir[0] + dir[1] * dir[1]); + Double_t c0 = (pt[0] * pt[0] + (pt[1] - r0) * (pt[1] + r0)) / (dir[0] * dir[0] + dir[1] * dir[1]); + Double_t delta = b0 * b0 - c0; + if (delta > 0) { + y[nsol] = -b0 - TMath::Sqrt(delta); + if (y[nsol] > -tol) + nsol++; + y[nsol] = -b0 + TMath::Sqrt(delta); + if (y[nsol] > -tol) + nsol++; } - r0 = fR + TMath::Sqrt((r-pt[2])*(r+pt[2])); - c0 = (pt[0]*pt[0] + (pt[1]-r0)*(pt[1]+r0))/(dir[0]*dir[0]+dir[1]*dir[1]); - delta = b0*b0-c0; - if (delta>0) { - y[nsol] = -b0-TMath::Sqrt(delta); - if (y[nsol]>-tol) nsol++; - y[nsol] = -b0+TMath::Sqrt(delta); - if (y[nsol]>-tol) nsol++; + r0 = fR + TMath::Sqrt((r - pt[2]) * (r + pt[2])); + c0 = (pt[0] * pt[0] + (pt[1] - r0) * (pt[1] + r0)) / (dir[0] * dir[0] + dir[1] * dir[1]); + delta = b0 * b0 - c0; + if (delta > 0) { + y[nsol] = -b0 - TMath::Sqrt(delta); + if (y[nsol] > -tol) + nsol++; + y[nsol] = -b0 + TMath::Sqrt(delta); + if (y[nsol] > -tol) + nsol++; } if (nsol) { // Sort solutions Int_t ind[4]; - TMath::Sort(nsol, y, ind,kFALSE); - for (Int_t j=0; j0) continue; + if (ndotd > 0) + continue; } Double_t s = x[i]; Double_t eps = TGeoShape::Big(); - Double_t delta = s*s*s*s + a*s*s*s + b*s*s + c*s + d; - Double_t eps0 = -delta/(4.*s*s*s + 3.*a*s*s + 2.*b*s + c); - while (TMath::Abs(eps)>TGeoShape::Tolerance()) { - if (TMath::Abs(eps0)>100) break; + Double_t delta = s * s * s * s + a * s * s * s + b * s * s + c * s + d; + Double_t eps0 = -delta / (4. * s * s * s + 3. * a * s * s + 2. * b * s + c); + while (TMath::Abs(eps) > TGeoShape::Tolerance()) { + if (TMath::Abs(eps0) > 100) + break; s += eps0; - if (TMath::Abs(s+eps0)TMath::Abs(eps0)) break; + if (TMath::Abs(s + eps0) < TGeoShape::Tolerance()) + break; + delta = s * s * s * s + a * s * s * s + b * s * s + c * s + d; + eps = -delta / (4. * s * s * s + 3. * a * s * s + 2. * b * s + c); + if (TMath::Abs(eps) > TMath::Abs(eps0)) + break; eps0 = eps; } - if (s<-TGeoShape::Tolerance()) continue; - return TMath::Max(0.,s); + if (s < -TGeoShape::Tolerance()) + continue; + return TMath::Max(0., s); } return TGeoShape::Big(); } @@ -1150,53 +1234,57 @@ Double_t TGeoTorus::ToBoundary(const Double_t *pt, const Double_t *dir, Double_t void TGeoTorus::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - Int_t n = gGeoManager->GetNsegments()+1; - nvert = n*(n-1); - Bool_t hasrmin = (GetRmin()>0)?kTRUE:kFALSE; - Bool_t hasphi = (GetDphi()<360)?kTRUE:kFALSE; - if (hasrmin) nvert *= 2; - else if (hasphi) nvert += 2; - nsegs = (2*n-1)*(n-1); - npols = (n-1)*(n-1); + Int_t n = gGeoManager->GetNsegments() + 1; + nvert = n * (n - 1); + Bool_t hasrmin = (GetRmin() > 0) ? kTRUE : kFALSE; + Bool_t hasphi = (GetDphi() < 360) ? kTRUE : kFALSE; + if (hasrmin) + nvert *= 2; + else if (hasphi) + nvert += 2; + nsegs = (2 * n - 1) * (n - 1); + npols = (n - 1) * (n - 1); if (hasrmin) { - nsegs += (2*n-1)*(n-1); - npols += (n-1)*(n-1); + nsegs += (2 * n - 1) * (n - 1); + npols += (n - 1) * (n - 1); } if (hasphi) { - nsegs += 2*(n-1); - npols += 2*(n-1); + nsegs += 2 * (n - 1); + npols += 2 * (n - 1); } } //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoTorus::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoTorus::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kRawSizes) { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = n*(n-1); - Bool_t hasrmin = (GetRmin()>0)?kTRUE:kFALSE; - Bool_t hasphi = (GetDphi()<360)?kTRUE:kFALSE; - if (hasrmin) nbPnts *= 2; - else if (hasphi) nbPnts += 2; - - Int_t nbSegs = (2*n-1)*(n-1); - Int_t nbPols = (n-1)*(n-1); + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = n * (n - 1); + Bool_t hasrmin = (GetRmin() > 0) ? kTRUE : kFALSE; + Bool_t hasphi = (GetDphi() < 360) ? kTRUE : kFALSE; + if (hasrmin) + nbPnts *= 2; + else if (hasphi) + nbPnts += 2; + + Int_t nbSegs = (2 * n - 1) * (n - 1); + Int_t nbPols = (n - 1) * (n - 1); if (hasrmin) { - nbSegs += (2*n-1)*(n-1); - nbPols += (n-1)*(n-1); + nbSegs += (2 * n - 1) * (n - 1); + nbPols += (n - 1) * (n - 1); } if (hasphi) { - nbSegs += 2*(n-1); - nbPols += 2*(n-1); + nbSegs += 2 * (n - 1); + nbPols += 2 * (n - 1); } - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1222,7 +1310,8 @@ const TBuffer3D & TGeoTorus::GetBuffer3D(Int_t reqSections, Bool_t localFrame) c void TGeoTorus::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i=0)?1:-1; - if (safe<1E-6) return; + norm[2] = (dir[2] >= 0) ? 1 : -1; + if (safe < 1E-6) + return; // check X facettes - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - if (distx>=0) { - safe=TMath::Abs(distx-TMath::Abs(point[0]))*calf; - if (safe= 0) { + safe = TMath::Abs(distx - TMath::Abs(point[0])) * calf; + if (safe < safemin) { safemin = safe; - norm[0] = (point[0]>0)?calf:(-calf); + norm[0] = (point[0] > 0) ? calf : (-calf); norm[1] = 0; - norm[2] = calf*fx; - Double_t dot = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - if (dot<0) { + norm[2] = calf * fx; + Double_t dot = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + if (dot < 0) { norm[0] = -norm[0]; norm[2] = -norm[2]; } - if (safe<1E-6) return; + if (safe < 1E-6) + return; } } // check Y facettes - safe = TMath::Abs(fDy-TMath::Abs(point[1])); - if (safe=0)?1:-1; + norm[1] = (dir[1] >= 0) ? 1 : -1; } } @@ -186,12 +183,15 @@ void TGeoTrd1::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoTrd1::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fDz) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; // then y - if (TMath::Abs(point[1]) > fDy) return kFALSE; + if (TMath::Abs(point[1]) > fDy) + return kFALSE; // then x - Double_t dx = 0.5*(fDx2*(point[2]+fDz)+fDx1*(fDz-point[2]))/fDz; - if (TMath::Abs(point[0]) > dx) return kFALSE; + Double_t dx = 0.5 * (fDx2 * (point[2] + fDz) + fDx1 * (fDz - point[2])) / fDz; + if (TMath::Abs(point[0]) > dx) + return kFALSE; return kTRUE; } @@ -199,51 +199,60 @@ Bool_t TGeoTrd1::Contains(const Double_t *point) const /// Compute distance from inside point to surface of the trd1 /// Boundary safe algorithm. -Double_t TGeoTrd1::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTrd1::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { - // compute safe distance + if (iact < 3 && safe) { + // compute safe distance *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } //--- Compute safety first - Double_t fx = 0.5*(fDx1-fDx2)/fDz; + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; Double_t cn; - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; //--- Compute distance to this shape // first check if Z facettes are crossed Double_t dist[3]; - for (Int_t i=0; i<3; i++) dist[i]=TGeoShape::Big(); - if (dir[2]<0) { - dist[0]=-(point[2]+fDz)/dir[2]; - } else if (dir[2]>0) { - dist[0]=(fDz-point[2])/dir[2]; - } - if (dist[0]<=0) return 0.0; + for (Int_t i = 0; i < 3; i++) + dist[i] = TGeoShape::Big(); + if (dir[2] < 0) { + dist[0] = -(point[2] + fDz) / dir[2]; + } else if (dir[2] > 0) { + dist[0] = (fDz - point[2]) / dir[2]; + } + if (dist[0] <= 0) + return 0.0; // now check X facettes - cn = -dir[0]+fx*dir[2]; - if (cn>0) { - dist[1] = point[0]+distx; - if (dist[1]<=0) return 0.0; + cn = -dir[0] + fx * dir[2]; + if (cn > 0) { + dist[1] = point[0] + distx; + if (dist[1] <= 0) + return 0.0; dist[1] /= cn; } - cn = dir[0]+fx*dir[2]; - if (cn>0) { - Double_t s = distx-point[0]; - if (s<=0) return 0.0; + cn = dir[0] + fx * dir[2]; + if (cn > 0) { + Double_t s = distx - point[0]; + if (s <= 0) + return 0.0; s /= cn; - if (s0) { - dist[2]=(fDy-point[1])/dir[1]; + if (dir[1] < 0) { + dist[2] = -(point[1] + fDy) / dir[1]; + } else if (dir[1] > 0) { + dist[2] = (fDy - point[1]) / dir[1]; } - if (dist[2]<=0) return 0.0; - return dist[TMath::LocMin(3,dist)]; + if (dist[2] <= 0) + return 0.0; + return dist[TMath::LocMin(3, dist)]; } //////////////////////////////////////////////////////////////////////////////// @@ -251,38 +260,38 @@ Double_t TGeoTrd1::DistFromInside(const Double_t *point, const Double_t *dir, In void TGeoTrd1::GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const { - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t calf = 1./TMath::Sqrt(1.0+fx*fx); - Double_t salf = calf*fx; + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t calf = 1. / TMath::Sqrt(1.0 + fx * fx); + Double_t salf = calf * fx; // check visibility of X faces - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - memset(normals, 0, 9*sizeof(Double_t)); - TGeoTrd1 *trd1 = (TGeoTrd1*)this; - if (point[0]>distx) { - // hi x face visible + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; + memset(normals, 0, 9 * sizeof(Double_t)); + TGeoTrd1 *trd1 = (TGeoTrd1 *)this; + if (point[0] > distx) { + // hi x face visible trd1->SetShapeBit(kGeoVisX); - normals[0]=calf; - normals[2]=salf; + normals[0] = calf; + normals[2] = salf; } else { trd1->SetShapeBit(kGeoVisX, kFALSE); - normals[0]=-calf; - normals[2]=salf; + normals[0] = -calf; + normals[2] = salf; } - if (point[1]>fDy) { - // hi y face visible + if (point[1] > fDy) { + // hi y face visible trd1->SetShapeBit(kGeoVisY); - normals[4]=1; + normals[4] = 1; } else { trd1->SetShapeBit(kGeoVisY, kFALSE); - normals[4]=-1; + normals[4] = -1; } - if (point[2]>fDz) { - // hi z face visible + if (point[2] > fDz) { + // hi z face visible trd1->SetShapeBit(kGeoVisZ); - normals[8]=1; + normals[8] = 1; } else { trd1->SetShapeBit(kGeoVisZ, kFALSE); - normals[8]=-1; + normals[8] = -1; } SetVertex(vertex); } @@ -292,21 +301,21 @@ void TGeoTrd1::GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_ void TGeoTrd1::GetOppositeCorner(const Double_t * /*point*/, Int_t inorm, Double_t *vertex, Double_t *normals) const { - TGeoTrd1 *trd1 = (TGeoTrd1*)this; + TGeoTrd1 *trd1 = (TGeoTrd1 *)this; if (inorm != 0) { - // change x face + // change x face trd1->SetShapeBit(kGeoVisX, !TestShapeBit(kGeoVisX)); - normals[0]=-normals[0]; + normals[0] = -normals[0]; } if (inorm != 1) { - // change y face + // change y face trd1->SetShapeBit(kGeoVisY, !TestShapeBit(kGeoVisY)); - normals[4]=-normals[4]; + normals[4] = -normals[4]; } if (inorm != 2) { - // hi z face visible + // hi z face visible trd1->SetShapeBit(kGeoVisZ, !TestShapeBit(kGeoVisZ)); - normals[8]=-normals[8]; + normals[8] = -normals[8]; } SetVertex(vertex); } @@ -315,110 +324,129 @@ void TGeoTrd1::GetOppositeCorner(const Double_t * /*point*/, Int_t inorm, Double /// Compute distance from outside point to surface of the trd1 /// Boundary safe algorithm -Double_t TGeoTrd1::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTrd1::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { - // compute safe distance + if (iact < 3 && safe) { + // compute safe distance *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } // find a visible face - Double_t xnew,ynew,znew; - Double_t fx = 0.5*(fDx1-fDx2)/fDz; + Double_t xnew, ynew, znew; + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; Double_t cn; - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; Bool_t in = kTRUE; - Double_t safx = distx-TMath::Abs(point[0]); - Double_t safy = fDy-TMath::Abs(point[1]); - Double_t safz = fDz-TMath::Abs(point[2]); + Double_t safx = distx - TMath::Abs(point[0]); + Double_t safy = fDy - TMath::Abs(point[1]); + Double_t safz = fDz - TMath::Abs(point[2]); //--- Compute distance to this shape // first check if Z facettes are crossed - if (point[2]<=-fDz) { - if (dir[2]<=0) return TGeoShape::Big(); + if (point[2] <= -fDz) { + if (dir[2] <= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = -(fDz+point[2])/dir[2]; + Double_t snxt = -(fDz + point[2]) / dir[2]; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; + xnew = point[0] + snxt * dir[0]; if (TMath::Abs(xnew) <= fDx1) { - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) <= fDy) return snxt; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) <= fDy) + return snxt; } - } else if (point[2]>=fDz) { - if (dir[2]>=0) return TGeoShape::Big(); + } else if (point[2] >= fDz) { + if (dir[2] >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (fDz-point[2])/dir[2]; + Double_t snxt = (fDz - point[2]) / dir[2]; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; + xnew = point[0] + snxt * dir[0]; if (TMath::Abs(xnew) <= fDx2) { - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) <= fDy) return snxt; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) <= fDy) + return snxt; } } // check if X facettes are crossed - if (point[0]<=-distx) { - cn = -dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (point[0] <= -distx) { + cn = -dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (point[0]+distx)/cn; + Double_t snxt = (point[0] + distx) / cn; // find extrapolated Y and Z - ynew = point[1]+snxt*dir[1]; + ynew = point[1] + snxt * dir[1]; if (TMath::Abs(ynew) <= fDy) { - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew) <= fDz) return snxt; + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) <= fDz) + return snxt; } } - if (point[0]>=distx) { - cn = dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (point[0] >= distx) { + cn = dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (distx-point[0])/cn; + Double_t snxt = (distx - point[0]) / cn; // find extrapolated Y and Z - ynew = point[1]+snxt*dir[1]; + ynew = point[1] + snxt * dir[1]; if (TMath::Abs(ynew) < fDy) { - znew = point[2]+snxt*dir[2]; - if (TMath::Abs(znew) < fDz) return snxt; + znew = point[2] + snxt * dir[2]; + if (TMath::Abs(znew) < fDz) + return snxt; } } // finally check Y facettes - if (point[1]<=-fDy) { + if (point[1] <= -fDy) { cn = -dir[1]; - if (cn>=0) return TGeoShape::Big(); + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (point[1]+fDy)/cn; + Double_t snxt = (point[1] + fDy) / cn; // find extrapolated X and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - xnew = point[0]+snxt*dir[0]; - Double_t dx = 0.5*(fDx1+fDx2)-fx*znew; - if (TMath::Abs(xnew) < dx) return snxt; + xnew = point[0] + snxt * dir[0]; + Double_t dx = 0.5 * (fDx1 + fDx2) - fx * znew; + if (TMath::Abs(xnew) < dx) + return snxt; } - } else if (point[1]>=fDy) { + } else if (point[1] >= fDy) { cn = dir[1]; - if (cn>=0) return TGeoShape::Big(); + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (fDy-point[1])/cn; + Double_t snxt = (fDy - point[1]) / cn; // find extrapolated X and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - xnew = point[0]+snxt*dir[0]; - Double_t dx = 0.5*(fDx1+fDx2)-fx*znew; - if (TMath::Abs(xnew) < dx) return snxt; + xnew = point[0] + snxt * dir[0]; + Double_t dx = 0.5 * (fDx1 + fDx2) - fx * znew; + if (TMath::Abs(xnew) < dx) + return snxt; } } - if (!in) return TGeoShape::Big(); + if (!in) + return TGeoShape::Big(); // Point actually inside - if (safz=0) return TGeoShape::Big(); + if (safz < safx && safz < safy) { + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); return 0.0; } - if (safy=0) return TGeoShape::Big(); + if (safy < safx) { + if (point[1] * dir[1] >= 0) + return TGeoShape::Big(); return 0.0; } - cn = TMath::Sign(1.0,point[0])*dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + cn = TMath::Sign(1.0, point[0]) * dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); return 0.0; } @@ -429,56 +457,52 @@ Double_t TGeoTrd1::DistFromOutside(const Double_t *point, const Double_t *dir, I /// return the pointer to the volume to be divided. In case a wrong /// division axis is supplied, returns pointer to volume that was divided. -TGeoVolume *TGeoTrd1::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoTrd1::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Double_t zmin, zmax, dx1n, dx2n; Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: - Warning("Divide", "dividing a Trd1 on X not implemented"); - return 0; - case 2: - finder = new TGeoPatternY(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoTrd1(fDx1, fDx2, step/2, fDz); + case 1: Warning("Divide", "dividing a Trd1 on X not implemented"); return 0; + case 2: + finder = new TGeoPatternY(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoTrd1(fDx1, fDx2, step / 2, fDz); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Y"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + step / 2 + id * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + for (id = 0; id < ndiv; id++) { + zmin = start + id * step; + zmax = start + (id + 1) * step; + dx1n = 0.5 * (fDx1 * (fDz - zmin) + fDx2 * (fDz + zmin)) / fDz; + dx2n = 0.5 * (fDx1 * (fDz - zmax) + fDx2 * (fDz + zmax)) / fDz; + shape = new TGeoTrd1(dx1n, dx2n, fDy, step / 2.); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Y"; - for (id=0; idAddNodeOffset(vol, id, start+step/2+id*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "Z"; - voldiv->AddNodeOffset(vol, id, start+step/2+id*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + opt = "Z"; + voldiv->AddNodeOffset(vol, id, start + step / 2 + id * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "Wrong axis type for division"); return 0; } } @@ -491,16 +515,16 @@ Double_t TGeoTrd1::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 2: - xlo = -fDy; - xhi = fDy; - dx = xhi-xlo; - return dx; - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 2: + xlo = -fDy; + xhi = fDy; + dx = xhi - xlo; + return dx; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -519,7 +543,7 @@ void TGeoTrd1::GetBoundingCylinder(Double_t *param) const Int_t TGeoTrd1::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const { - dx=dy=dz=0; + dx = dy = dz = 0; if (mat->IsRotation()) { Error("GetFittingBox", "cannot handle parametrized rotated volumes"); return 1; // ### rotation not accepted ### @@ -537,35 +561,35 @@ Int_t TGeoTrd1::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ dd[1] = parambox->GetDY(); dd[2] = parambox->GetDZ(); //-> check if Z range is fixed - if (dd[2]<0) { - dd[2] = TMath::Min(origin[2]+fDz, fDz-origin[2]); - if (dd[2]<0) { + if (dd[2] < 0) { + dd[2] = TMath::Min(origin[2] + fDz, fDz - origin[2]); + if (dd[2] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } } //-> check if Y range is fixed - if (dd[1]<0) { - dd[1] = TMath::Min(origin[1]+fDy, fDy-origin[1]); - if (dd[1]<0) { + if (dd[1] < 0) { + dd[1] = TMath::Min(origin[1] + fDy, fDy - origin[1]); + if (dd[1] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } } - if (dd[0]>=0) { + if (dd[0] >= 0) { dx = dd[0]; dy = dd[1]; dz = dd[2]; return 0; } //-> check now range at Z = origin[2] +/- dd[2] - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t dx0 = 0.5*(fDx1+fDx2); - Double_t z=origin[2]-dd[2]; - dd[0] = dx0-fx*z-origin[0]; - z=origin[2]+dd[2]; - dd[0] = TMath::Min(dd[0], dx0-fx*z-origin[0]); - if (dd[0]<0) { + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t dx0 = 0.5 * (fDx1 + fDx2); + Double_t z = origin[2] - dd[2]; + dd[0] = dx0 - fx * z - origin[0]; + z = origin[2] + dd[2]; + dd[0] = TMath::Min(dd[0], dx0 - fx * z - origin[0]); + if (dd[0] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } @@ -581,20 +605,29 @@ Int_t TGeoTrd1::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ TGeoShape *TGeoTrd1::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoTrd1)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; } Double_t dx1, dx2, dy, dz; - if (fDx1<0) dx1=((TGeoTrd1*)mother)->GetDx1(); - else dx1=fDx1; - if (fDx2<0) dx2=((TGeoTrd1*)mother)->GetDx2(); - else dx2=fDx2; - if (fDy<0) dy=((TGeoTrd1*)mother)->GetDy(); - else dy=fDy; - if (fDz<0) dz=((TGeoTrd1*)mother)->GetDz(); - else dz=fDz; + if (fDx1 < 0) + dx1 = ((TGeoTrd1 *)mother)->GetDx1(); + else + dx1 = fDx1; + if (fDx2 < 0) + dx2 = ((TGeoTrd1 *)mother)->GetDx2(); + else + dx2 = fDx2; + if (fDy < 0) + dy = ((TGeoTrd1 *)mother)->GetDy(); + else + dy = fDy; + if (fDz < 0) + dz = ((TGeoTrd1 *)mother)->GetDz(); + else + dz = fDz; return (new TGeoTrd1(dx1, dx2, dy, dz)); } @@ -622,18 +655,22 @@ Double_t TGeoTrd1::Safety(const Double_t *point, Bool_t in) const Double_t saf[3]; //--- Compute safety first // check Z facettes - saf[0] = fDz-TMath::Abs(point[2]); - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t calf = 1./TMath::Sqrt(1.0+fx*fx); + saf[0] = fDz - TMath::Abs(point[2]); + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t calf = 1. / TMath::Sqrt(1.0 + fx * fx); // check X facettes - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - if (distx<0) saf[1]=TGeoShape::Big(); - else saf[1]=(distx-TMath::Abs(point[0]))*calf; + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; + if (distx < 0) + saf[1] = TGeoShape::Big(); + else + saf[1] = (distx - TMath::Abs(point[0])) * calf; // check Y facettes - saf[2] = fDy-TMath::Abs(point[1]); - if (in) return saf[TMath::LocMin(3,saf)]; - for (Int_t i=0; i<3; i++) saf[i]=-saf[i]; - return saf[TMath::LocMax(3,saf)]; + saf[2] = fDy - TMath::Abs(point[1]); + if (in) + return saf[TMath::LocMin(3, saf)]; + for (Int_t i = 0; i < 3; i++) + saf[i] = -saf[i]; + return saf[TMath::LocMax(3, saf)]; } //////////////////////////////////////////////////////////////////////////////// @@ -641,13 +678,15 @@ Double_t TGeoTrd1::Safety(const Double_t *point, Bool_t in) const void TGeoTrd1::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dx1 = " << fDx1 << ";" << std::endl; out << " dx2 = " << fDx2 << ";" << std::endl; - out << " dy = " << fDy << ";" << std::endl; - out << " dz = " << fDZ << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoTrd1(\"" << GetName() << "\", dx1,dx2,dy,dz);" << std::endl; + out << " dy = " << fDy << ";" << std::endl; + out << " dz = " << fDZ << ";" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoTrd1(\"" << GetName() << "\", dx1,dx2,dy,dz);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -658,8 +697,8 @@ void TGeoTrd1::SetDimensions(Double_t *param) { fDx1 = param[0]; fDx2 = param[1]; - fDy = param[2]; - fDz = param[3]; + fDy = param[2]; + fDz = param[3]; ComputeBBox(); } @@ -672,21 +711,21 @@ void TGeoTrd1::SetVertex(Double_t *vertex) const if (TestShapeBit(kGeoVisZ)) { vertex[0] = fDx2; vertex[2] = fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy:-fDy; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy : -fDy; } else { vertex[0] = fDx1; vertex[2] = -fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy:-fDy; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy : -fDy; } } else { if (TestShapeBit(kGeoVisZ)) { vertex[0] = -fDx2; vertex[2] = fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy:-fDy; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy : -fDy; } else { vertex[0] = -fDx1; vertex[2] = -fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy:-fDy; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy : -fDy; } } } @@ -696,15 +735,32 @@ void TGeoTrd1::SetVertex(Double_t *vertex) const void TGeoTrd1::SetPoints(Double_t *points) const { - if (!points) return; - points[ 0] = -fDx1; points[ 1] = -fDy; points[ 2] = -fDz; - points[ 3] = -fDx1; points[ 4] = fDy; points[ 5] = -fDz; - points[ 6] = fDx1; points[ 7] = fDy; points[ 8] = -fDz; - points[ 9] = fDx1; points[10] = -fDy; points[11] = -fDz; - points[12] = -fDx2; points[13] = -fDy; points[14] = fDz; - points[15] = -fDx2; points[16] = fDy; points[17] = fDz; - points[18] = fDx2; points[19] = fDy; points[20] = fDz; - points[21] = fDx2; points[22] = -fDy; points[23] = fDz; + if (!points) + return; + points[0] = -fDx1; + points[1] = -fDy; + points[2] = -fDz; + points[3] = -fDx1; + points[4] = fDy; + points[5] = -fDz; + points[6] = fDx1; + points[7] = fDy; + points[8] = -fDz; + points[9] = fDx1; + points[10] = -fDy; + points[11] = -fDz; + points[12] = -fDx2; + points[13] = -fDy; + points[14] = fDz; + points[15] = -fDx2; + points[16] = fDy; + points[17] = fDz; + points[18] = fDx2; + points[19] = fDy; + points[20] = fDz; + points[21] = fDx2; + points[22] = -fDy; + points[23] = fDz; } //////////////////////////////////////////////////////////////////////////////// @@ -712,15 +768,32 @@ void TGeoTrd1::SetPoints(Double_t *points) const void TGeoTrd1::SetPoints(Float_t *points) const { - if (!points) return; - points[ 0] = -fDx1; points[ 1] = -fDy; points[ 2] = -fDz; - points[ 3] = -fDx1; points[ 4] = fDy; points[ 5] = -fDz; - points[ 6] = fDx1; points[ 7] = fDy; points[ 8] = -fDz; - points[ 9] = fDx1; points[10] = -fDy; points[11] = -fDz; - points[12] = -fDx2; points[13] = -fDy; points[14] = fDz; - points[15] = -fDx2; points[16] = fDy; points[17] = fDz; - points[18] = fDx2; points[19] = fDy; points[20] = fDz; - points[21] = fDx2; points[22] = -fDy; points[23] = fDz; + if (!points) + return; + points[0] = -fDx1; + points[1] = -fDy; + points[2] = -fDz; + points[3] = -fDx1; + points[4] = fDy; + points[5] = -fDz; + points[6] = fDx1; + points[7] = fDy; + points[8] = -fDz; + points[9] = fDx1; + points[10] = -fDy; + points[11] = -fDz; + points[12] = -fDx2; + points[13] = -fDy; + points[14] = fDz; + points[15] = -fDx2; + points[16] = fDy; + points[17] = fDz; + points[18] = fDx2; + points[19] = fDy; + points[20] = fDz; + points[21] = fDx2; + points[22] = -fDy; + points[23] = fDz; } //////////////////////////////////////////////////////////////////////////////// @@ -738,7 +811,8 @@ void TGeoTrd1::Sizeof3D() const void TGeoTrd1::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i=0)?1:-1; - if (safe= 0) ? 1 : -1; + if (safe < TGeoShape::Tolerance()) + return; // check X facettes - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - if (distx>=0) { - safe=TMath::Abs(distx-TMath::Abs(point[0]))*calf; - if (safe= 0) { + safe = TMath::Abs(distx - TMath::Abs(point[0])) * calf; + if (safe < safemin) { safemin = safe; - norm[0] = (point[0]>0)?calf:(-calf); + norm[0] = (point[0] > 0) ? calf : (-calf); norm[1] = 0; - norm[2] = calf*fx; - Double_t dot = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - if (dot<0) { - norm[0]=-norm[0]; - norm[2]=-norm[2]; + norm[2] = calf * fx; + Double_t dot = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + if (dot < 0) { + norm[0] = -norm[0]; + norm[2] = -norm[2]; } - if (safe=0) { - safe=TMath::Abs(distx-TMath::Abs(point[1]))*calf; - if (safe= 0) { + safe = TMath::Abs(distx - TMath::Abs(point[1])) * calf; + if (safe < safemin) { norm[0] = 0; - norm[1] = (point[1]>0)?calf:(-calf); - norm[2] = calf*fy; - Double_t dot = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - if (dot<0) { - norm[1]=-norm[1]; - norm[2]=-norm[2]; + norm[1] = (point[1] > 0) ? calf : (-calf); + norm[2] = calf * fy; + Double_t dot = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + if (dot < 0) { + norm[1] = -norm[1]; + norm[2] = -norm[2]; } } } @@ -197,13 +194,16 @@ void TGeoTrd2::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoTrd2::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fDz) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; // then y - Double_t dy = 0.5*(fDy2*(point[2]+fDz)+fDy1*(fDz-point[2]))/fDz; - if (TMath::Abs(point[1]) > dy) return kFALSE; + Double_t dy = 0.5 * (fDy2 * (point[2] + fDz) + fDy1 * (fDz - point[2])) / fDz; + if (TMath::Abs(point[1]) > dy) + return kFALSE; // then x - Double_t dx = 0.5*(fDx2*(point[2]+fDz)+fDx1*(fDz-point[2]))/fDz; - if (TMath::Abs(point[0]) > dx) return kFALSE; + Double_t dx = 0.5 * (fDx2 * (point[2] + fDz) + fDx1 * (fDz - point[2])) / fDz; + if (TMath::Abs(point[0]) > dx) + return kFALSE; return kTRUE; } @@ -211,179 +211,209 @@ Bool_t TGeoTrd2::Contains(const Double_t *point) const /// Compute distance from inside point to surface of the trd2 /// Boundary safe algorithm -Double_t TGeoTrd2::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTrd2::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { - // compute safe distance + if (iact < 3 && safe) { + // compute safe distance *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t fy = 0.5*(fDy1-fDy2)/fDz; + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t fy = 0.5 * (fDy1 - fDy2) / fDz; Double_t cn; - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - Double_t disty = 0.5*(fDy1+fDy2)-fy*point[2]; + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; + Double_t disty = 0.5 * (fDy1 + fDy2) - fy * point[2]; //--- Compute distance to this shape // first check if Z facettes are crossed Double_t dist[3]; - for (Int_t i=0; i<3; i++) dist[i]=TGeoShape::Big(); - if (dir[2]<0) { - dist[0]=-(point[2]+fDz)/dir[2]; - } else if (dir[2]>0) { - dist[0]=(fDz-point[2])/dir[2]; - } - if (dist[0]<=0) return 0.0; + for (Int_t i = 0; i < 3; i++) + dist[i] = TGeoShape::Big(); + if (dir[2] < 0) { + dist[0] = -(point[2] + fDz) / dir[2]; + } else if (dir[2] > 0) { + dist[0] = (fDz - point[2]) / dir[2]; + } + if (dist[0] <= 0) + return 0.0; // now check X facettes - cn = -dir[0]+fx*dir[2]; - if (cn>0) { - dist[1] = point[0]+distx; - if (dist[1]<=0) return 0.0; + cn = -dir[0] + fx * dir[2]; + if (cn > 0) { + dist[1] = point[0] + distx; + if (dist[1] <= 0) + return 0.0; dist[1] /= cn; } - cn = dir[0]+fx*dir[2]; - if (cn>0) { - Double_t s = distx-point[0]; - if (s<=0) return 0.0; + cn = dir[0] + fx * dir[2]; + if (cn > 0) { + Double_t s = distx - point[0]; + if (s <= 0) + return 0.0; s /= cn; - if (s0) { - dist[2] = point[1]+disty; - if (dist[2]<=0) return 0.0; + cn = -dir[1] + fy * dir[2]; + if (cn > 0) { + dist[2] = point[1] + disty; + if (dist[2] <= 0) + return 0.0; dist[2] /= cn; } - cn = dir[1]+fy*dir[2]; - if (cn>0) { - Double_t s = disty-point[1]; - if (s<=0) return 0.0; + cn = dir[1] + fy * dir[2]; + if (cn > 0) { + Double_t s = disty - point[1]; + if (s <= 0) + return 0.0; s /= cn; - if (s=0) return TGeoShape::Big(); + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (fDz+point[2])/cn; + Double_t snxt = (fDz + point[2]) / cn; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; + xnew = point[0] + snxt * dir[0]; if (TMath::Abs(xnew) < fDx1) { - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) < fDy1) return snxt; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) < fDy1) + return snxt; } - } else if (point[2]>=fDz) { + } else if (point[2] >= fDz) { cn = dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (fDz-point[2])/cn; + Double_t snxt = (fDz - point[2]) / cn; // find extrapolated X and Y - xnew = point[0]+snxt*dir[0]; + xnew = point[0] + snxt * dir[0]; if (TMath::Abs(xnew) < fDx2) { - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) < fDy2) return snxt; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) < fDy2) + return snxt; } } // check if X facettes are crossed - if (point[0]<=-distx) { - cn = -dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (point[0] <= -distx) { + cn = -dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (point[0]+distx)/cn; + Double_t snxt = (point[0] + distx) / cn; // find extrapolated Y and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - Double_t dy = 0.5*(fDy1+fDy2)-fy*znew; - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) < dy) return snxt; + Double_t dy = 0.5 * (fDy1 + fDy2) - fy * znew; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) < dy) + return snxt; } } - if (point[0]>=distx) { - cn = dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (point[0] >= distx) { + cn = dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (distx-point[0])/cn; + Double_t snxt = (distx - point[0]) / cn; // find extrapolated Y and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - Double_t dy = 0.5*(fDy1+fDy2)-fy*znew; - ynew = point[1]+snxt*dir[1]; - if (TMath::Abs(ynew) < dy) return snxt; + Double_t dy = 0.5 * (fDy1 + fDy2) - fy * znew; + ynew = point[1] + snxt * dir[1]; + if (TMath::Abs(ynew) < dy) + return snxt; } } // finally check Y facettes - if (point[1]<=-disty) { - cn = -dir[1]+fy*dir[2]; + if (point[1] <= -disty) { + cn = -dir[1] + fy * dir[2]; in = kFALSE; - if (cn>=0) return TGeoShape::Big(); - Double_t snxt = (point[1]+disty)/cn; + if (cn >= 0) + return TGeoShape::Big(); + Double_t snxt = (point[1] + disty) / cn; // find extrapolated X and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - Double_t dx = 0.5*(fDx1+fDx2)-fx*znew; - xnew = point[0]+snxt*dir[0]; - if (TMath::Abs(xnew) < dx) return snxt; + Double_t dx = 0.5 * (fDx1 + fDx2) - fx * znew; + xnew = point[0] + snxt * dir[0]; + if (TMath::Abs(xnew) < dx) + return snxt; } } - if (point[1]>=disty) { - cn = dir[1]+fy*dir[2]; - if (cn>=0) return TGeoShape::Big(); + if (point[1] >= disty) { + cn = dir[1] + fy * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); in = kFALSE; - Double_t snxt = (disty-point[1])/cn; + Double_t snxt = (disty - point[1]) / cn; // find extrapolated X and Z - znew = point[2]+snxt*dir[2]; + znew = point[2] + snxt * dir[2]; if (TMath::Abs(znew) < fDz) { - Double_t dx = 0.5*(fDx1+fDx2)-fx*znew; - xnew = point[0]+snxt*dir[0]; - if (TMath::Abs(xnew) < dx) return snxt; + Double_t dx = 0.5 * (fDx1 + fDx2) - fx * znew; + xnew = point[0] + snxt * dir[0]; + if (TMath::Abs(xnew) < dx) + return snxt; } } - if (!in) return TGeoShape::Big(); + if (!in) + return TGeoShape::Big(); // Point actually inside - if (safz=0) return TGeoShape::Big(); + if (safz < safx && safz < safy) { + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); return 0.0; } - if (safy=0) return TGeoShape::Big(); + if (safy < safx) { + cn = TMath::Sign(1.0, point[1]) * dir[1] + fy * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); return 0.0; } - cn = TMath::Sign(1.0,point[0])*dir[0]+fx*dir[2]; - if (cn>=0) return TGeoShape::Big(); + cn = TMath::Sign(1.0, point[0]) * dir[0] + fx * dir[2]; + if (cn >= 0) + return TGeoShape::Big(); return 0.0; } @@ -396,11 +426,11 @@ Double_t TGeoTrd2::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -410,44 +440,44 @@ Double_t TGeoTrd2::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const void TGeoTrd2::GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_t *normals) const { - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t fy = 0.5*(fDy1-fDy2)/fDz; - Double_t calf = 1./TMath::Sqrt(1.0+fx*fx); - Double_t salf = calf*fx; - Double_t cbet = 1./TMath::Sqrt(1.0+fy*fy); - Double_t sbet = cbet*fy; + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t fy = 0.5 * (fDy1 - fDy2) / fDz; + Double_t calf = 1. / TMath::Sqrt(1.0 + fx * fx); + Double_t salf = calf * fx; + Double_t cbet = 1. / TMath::Sqrt(1.0 + fy * fy); + Double_t sbet = cbet * fy; // check visibility of X,Y faces - Double_t distx = fDx1-fx*(fDz+point[2]); - Double_t disty = fDy1-fy*(fDz+point[2]); - memset(normals, 0, 9*sizeof(Double_t)); - TGeoTrd2 *trd2 = (TGeoTrd2*)this; - if (point[0]>distx) { - // hi x face visible + Double_t distx = fDx1 - fx * (fDz + point[2]); + Double_t disty = fDy1 - fy * (fDz + point[2]); + memset(normals, 0, 9 * sizeof(Double_t)); + TGeoTrd2 *trd2 = (TGeoTrd2 *)this; + if (point[0] > distx) { + // hi x face visible trd2->SetShapeBit(kGeoVisX); - normals[0]=calf; - normals[2]=salf; + normals[0] = calf; + normals[2] = salf; } else { trd2->SetShapeBit(kGeoVisX, kFALSE); - normals[0]=-calf; - normals[2]=salf; + normals[0] = -calf; + normals[2] = salf; } - if (point[1]>disty) { - // hi y face visible + if (point[1] > disty) { + // hi y face visible trd2->SetShapeBit(kGeoVisY); - normals[4]=cbet; - normals[5]=sbet; + normals[4] = cbet; + normals[5] = sbet; } else { trd2->SetShapeBit(kGeoVisY, kFALSE); - normals[4]=-cbet; - normals[5]=sbet; + normals[4] = -cbet; + normals[5] = sbet; } - if (point[2]>fDz) { - // hi z face visible + if (point[2] > fDz) { + // hi z face visible trd2->SetShapeBit(kGeoVisZ); - normals[8]=1; + normals[8] = 1; } else { trd2->SetShapeBit(kGeoVisZ, kFALSE); - normals[8]=-1; + normals[8] = -1; } SetVertex(vertex); } @@ -457,21 +487,21 @@ void TGeoTrd2::GetVisibleCorner(const Double_t *point, Double_t *vertex, Double_ void TGeoTrd2::GetOppositeCorner(const Double_t * /*point*/, Int_t inorm, Double_t *vertex, Double_t *normals) const { - TGeoTrd2 *trd2 = (TGeoTrd2*)this; + TGeoTrd2 *trd2 = (TGeoTrd2 *)this; if (inorm != 0) { - // change x face + // change x face trd2->SetShapeBit(kGeoVisX, !TestShapeBit(kGeoVisX)); - normals[0]=-normals[0]; + normals[0] = -normals[0]; } if (inorm != 1) { - // change y face + // change y face trd2->SetShapeBit(kGeoVisY, !TestShapeBit(kGeoVisY)); - normals[4]=-normals[4]; + normals[4] = -normals[4]; } if (inorm != 2) { - // hi z face visible + // hi z face visible trd2->SetShapeBit(kGeoVisZ, !TestShapeBit(kGeoVisZ)); - normals[8]=-normals[8]; + normals[8] = -normals[8]; } SetVertex(vertex); } @@ -483,47 +513,41 @@ void TGeoTrd2::GetOppositeCorner(const Double_t * /*point*/, Int_t inorm, Double /// divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoTrd2::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoTrd2::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Double_t zmin, zmax, dx1n, dx2n, dy1n, dy2n; Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: - Warning("Divide", "dividing a Trd2 on X not implemented"); - return 0; - case 2: - Warning("Divide", "dividing a Trd2 on Y not implemented"); - return 0; - case 3: - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "Z"; - voldiv->AddNodeOffset(vol, id, start+step/2+id*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "Wrong axis type for division"); - return 0; + case 1: Warning("Divide", "dividing a Trd2 on X not implemented"); return 0; + case 2: Warning("Divide", "dividing a Trd2 on Y not implemented"); return 0; + case 3: + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + zmin = start + id * step; + zmax = start + (id + 1) * step; + dx1n = 0.5 * (fDx1 * (fDz - zmin) + fDx2 * (fDz + zmin)) / fDz; + dx2n = 0.5 * (fDx1 * (fDz - zmax) + fDx2 * (fDz + zmax)) / fDz; + dy1n = 0.5 * (fDy1 * (fDz - zmin) + fDy2 * (fDz + zmin)) / fDz; + dy2n = 0.5 * (fDy1 * (fDz - zmax) + fDy2 * (fDz + zmax)) / fDz; + shape = new TGeoTrd2(dx1n, dx2n, dy1n, dy2n, step / 2.); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Z"; + voldiv->AddNodeOffset(vol, id, start + step / 2 + id * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "Wrong axis type for division"); return 0; } } @@ -541,7 +565,7 @@ void TGeoTrd2::GetBoundingCylinder(Double_t *param) const Int_t TGeoTrd2::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const { - dx=dy=dz=0; + dx = dy = dz = 0; if (mat->IsRotation()) { Error("GetFittingBox", "cannot handle parametrized rotated volumes"); return 1; // ### rotation not accepted ### @@ -559,31 +583,31 @@ Int_t TGeoTrd2::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ dd[1] = parambox->GetDY(); dd[2] = parambox->GetDZ(); //-> check if Z range is fixed - if (dd[2]<0) { - dd[2] = TMath::Min(origin[2]+fDz, fDz-origin[2]); - if (dd[2]<0) { + if (dd[2] < 0) { + dd[2] = TMath::Min(origin[2] + fDz, fDz - origin[2]); + if (dd[2] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } } - if (dd[0]>=0 && dd[1]>=0) { + if (dd[0] >= 0 && dd[1] >= 0) { dx = dd[0]; dy = dd[1]; dz = dd[2]; return 0; } //-> check now range at Z = origin[2] +/- dd[2] - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t fy = 0.5*(fDy1-fDy2)/fDz; - Double_t dx0 = 0.5*(fDx1+fDx2); - Double_t dy0 = 0.5*(fDy1+fDy2); - Double_t z=origin[2]-dd[2]; - dd[0] = dx0-fx*z-origin[0]; - dd[1] = dy0-fy*z-origin[1]; - z=origin[2]+dd[2]; - dd[0] = TMath::Min(dd[0], dx0-fx*z-origin[0]); - dd[1] = TMath::Min(dd[1], dy0-fy*z-origin[1]); - if (dd[0]<0 || dd[1]<0) { + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t fy = 0.5 * (fDy1 - fDy2) / fDz; + Double_t dx0 = 0.5 * (fDx1 + fDx2); + Double_t dy0 = 0.5 * (fDy1 + fDy2); + Double_t z = origin[2] - dd[2]; + dd[0] = dx0 - fx * z - origin[0]; + dd[1] = dy0 - fy * z - origin[1]; + z = origin[2] + dd[2]; + dd[0] = TMath::Min(dd[0], dx0 - fx * z - origin[0]); + dd[1] = TMath::Min(dd[1], dy0 - fy * z - origin[1]); + if (dd[0] < 0 || dd[1] < 0) { Error("GetFittingBox", "wrong matrix"); return 1; } @@ -599,22 +623,33 @@ Int_t TGeoTrd2::GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_ TGeoShape *TGeoTrd2::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoTrd2)) { Error("GetMakeRuntimeShape", "invalid mother"); return 0; } Double_t dx1, dx2, dy1, dy2, dz; - if (fDx1<0) dx1=((TGeoTrd2*)mother)->GetDx1(); - else dx1=fDx1; - if (fDx2<0) dx2=((TGeoTrd2*)mother)->GetDx2(); - else dx2=fDx2; - if (fDy1<0) dy1=((TGeoTrd2*)mother)->GetDy1(); - else dy1=fDy1; - if (fDy2<0) dy2=((TGeoTrd2*)mother)->GetDy2(); - else dy2=fDy2; - if (fDz<0) dz=((TGeoTrd2*)mother)->GetDz(); - else dz=fDz; + if (fDx1 < 0) + dx1 = ((TGeoTrd2 *)mother)->GetDx1(); + else + dx1 = fDx1; + if (fDx2 < 0) + dx2 = ((TGeoTrd2 *)mother)->GetDx2(); + else + dx2 = fDx2; + if (fDy1 < 0) + dy1 = ((TGeoTrd2 *)mother)->GetDy1(); + else + dy1 = fDy1; + if (fDy2 < 0) + dy2 = ((TGeoTrd2 *)mother)->GetDy2(); + else + dy2 = fDy2; + if (fDz < 0) + dz = ((TGeoTrd2 *)mother)->GetDz(); + else + dz = fDz; return (new TGeoTrd2(dx1, dx2, dy1, dy2, dz)); } @@ -643,24 +678,30 @@ Double_t TGeoTrd2::Safety(const Double_t *point, Bool_t in) const Double_t saf[3]; //--- Compute safety first // check Z facettes - saf[0] = fDz-TMath::Abs(point[2]); - Double_t fx = 0.5*(fDx1-fDx2)/fDz; - Double_t calf = 1./TMath::Sqrt(1.0+fx*fx); + saf[0] = fDz - TMath::Abs(point[2]); + Double_t fx = 0.5 * (fDx1 - fDx2) / fDz; + Double_t calf = 1. / TMath::Sqrt(1.0 + fx * fx); // check X facettes - Double_t distx = 0.5*(fDx1+fDx2)-fx*point[2]; - if (distx<0) saf[1]=TGeoShape::Big(); - else saf[1]=(distx-TMath::Abs(point[0]))*calf; - - Double_t fy = 0.5*(fDy1-fDy2)/fDz; - calf = 1./TMath::Sqrt(1.0+fy*fy); + Double_t distx = 0.5 * (fDx1 + fDx2) - fx * point[2]; + if (distx < 0) + saf[1] = TGeoShape::Big(); + else + saf[1] = (distx - TMath::Abs(point[0])) * calf; + + Double_t fy = 0.5 * (fDy1 - fDy2) / fDz; + calf = 1. / TMath::Sqrt(1.0 + fy * fy); // check Y facettes - distx = 0.5*(fDy1+fDy2)-fy*point[2]; - if (distx<0) saf[2]=TGeoShape::Big(); - else saf[2]=(distx-TMath::Abs(point[1]))*calf; + distx = 0.5 * (fDy1 + fDy2) - fy * point[2]; + if (distx < 0) + saf[2] = TGeoShape::Big(); + else + saf[2] = (distx - TMath::Abs(point[1])) * calf; - if (in) return saf[TMath::LocMin(3,saf)]; - for (Int_t i=0; i<3; i++) saf[i]=-saf[i]; - return saf[TMath::LocMax(3,saf)]; + if (in) + return saf[TMath::LocMin(3, saf)]; + for (Int_t i = 0; i < 3; i++) + saf[i] = -saf[i]; + return saf[TMath::LocMax(3, saf)]; } //////////////////////////////////////////////////////////////////////////////// @@ -668,14 +709,16 @@ Double_t TGeoTrd2::Safety(const Double_t *point, Bool_t in) const void TGeoTrd2::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " dx1 = " << fDx1 << ";" << std::endl; out << " dx2 = " << fDx2 << ";" << std::endl; out << " dy1 = " << fDy1 << ";" << std::endl; out << " dy2 = " << fDy2 << ";" << std::endl; - out << " dz = " << fDZ << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoTrd2(\"" << GetName() << "\", dx1,dx2,dy1,dy2,dz);" << std::endl; + out << " dz = " << fDZ << ";" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoTrd2(\"" << GetName() << "\", dx1,dx2,dy1,dy2,dz);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -688,7 +731,7 @@ void TGeoTrd2::SetDimensions(Double_t *param) fDx2 = param[1]; fDy1 = param[2]; fDy2 = param[3]; - fDz = param[4]; + fDz = param[4]; ComputeBBox(); } @@ -697,15 +740,32 @@ void TGeoTrd2::SetDimensions(Double_t *param) void TGeoTrd2::SetPoints(Double_t *points) const { - if (!points) return; - points[ 0] = -fDx1; points[ 1] = -fDy1; points[ 2] = -fDz; - points[ 3] = -fDx1; points[ 4] = fDy1; points[ 5] = -fDz; - points[ 6] = fDx1; points[ 7] = fDy1; points[ 8] = -fDz; - points[ 9] = fDx1; points[10] = -fDy1; points[11] = -fDz; - points[12] = -fDx2; points[13] = -fDy2; points[14] = fDz; - points[15] = -fDx2; points[16] = fDy2; points[17] = fDz; - points[18] = fDx2; points[19] = fDy2; points[20] = fDz; - points[21] = fDx2; points[22] = -fDy2; points[23] = fDz; + if (!points) + return; + points[0] = -fDx1; + points[1] = -fDy1; + points[2] = -fDz; + points[3] = -fDx1; + points[4] = fDy1; + points[5] = -fDz; + points[6] = fDx1; + points[7] = fDy1; + points[8] = -fDz; + points[9] = fDx1; + points[10] = -fDy1; + points[11] = -fDz; + points[12] = -fDx2; + points[13] = -fDy2; + points[14] = fDz; + points[15] = -fDx2; + points[16] = fDy2; + points[17] = fDz; + points[18] = fDx2; + points[19] = fDy2; + points[20] = fDz; + points[21] = fDx2; + points[22] = -fDy2; + points[23] = fDz; } //////////////////////////////////////////////////////////////////////////////// @@ -713,15 +773,32 @@ void TGeoTrd2::SetPoints(Double_t *points) const void TGeoTrd2::SetPoints(Float_t *points) const { - if (!points) return; - points[ 0] = -fDx1; points[ 1] = -fDy1; points[ 2] = -fDz; - points[ 3] = -fDx1; points[ 4] = fDy1; points[ 5] = -fDz; - points[ 6] = fDx1; points[ 7] = fDy1; points[ 8] = -fDz; - points[ 9] = fDx1; points[10] = -fDy1; points[11] = -fDz; - points[12] = -fDx2; points[13] = -fDy2; points[14] = fDz; - points[15] = -fDx2; points[16] = fDy2; points[17] = fDz; - points[18] = fDx2; points[19] = fDy2; points[20] = fDz; - points[21] = fDx2; points[22] = -fDy2; points[23] = fDz; + if (!points) + return; + points[0] = -fDx1; + points[1] = -fDy1; + points[2] = -fDz; + points[3] = -fDx1; + points[4] = fDy1; + points[5] = -fDz; + points[6] = fDx1; + points[7] = fDy1; + points[8] = -fDz; + points[9] = fDx1; + points[10] = -fDy1; + points[11] = -fDz; + points[12] = -fDx2; + points[13] = -fDy2; + points[14] = fDz; + points[15] = -fDx2; + points[16] = fDy2; + points[17] = fDz; + points[18] = fDx2; + points[19] = fDy2; + points[20] = fDz; + points[21] = fDx2; + points[22] = -fDy2; + points[23] = fDz; } //////////////////////////////////////////////////////////////////////////////// @@ -733,21 +810,21 @@ void TGeoTrd2::SetVertex(Double_t *vertex) const if (TestShapeBit(kGeoVisZ)) { vertex[0] = fDx2; vertex[2] = fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy2:-fDy2; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy2 : -fDy2; } else { vertex[0] = fDx1; vertex[2] = -fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy1:-fDy1; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy1 : -fDy1; } } else { if (TestShapeBit(kGeoVisZ)) { vertex[0] = -fDx2; vertex[2] = fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy2:-fDy2; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy2 : -fDy2; } else { vertex[0] = -fDx1; vertex[2] = -fDz; - vertex[1] = (TestShapeBit(kGeoVisY))?fDy1:-fDy1; + vertex[1] = (TestShapeBit(kGeoVisY)) ? fDy1 : -fDy1; } } } @@ -767,7 +844,8 @@ void TGeoTrd2::Sizeof3D() const void TGeoTrd2::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iMakeCtub("CTUB",med, 20,30,40,-30,250, nlow[0], nlow[1], nlow[2], nhi[0],nhi[1],nhi[2]); - vol->SetLineWidth(2); - top->AddNode(vol,1); - gGeoManager->CloseGeometry(); + TGeoVolume *vol = gGeoManager->MakeCtub("CTUB",med, 20,30,40,-30,250, nlow[0], nlow[1], nlow[2], +nhi[0],nhi[1],nhi[2]); vol->SetLineWidth(2); top->AddNode(vol,1); gGeoManager->CloseGeometry(); gGeoManager->SetNsegments(80); top->Draw(); TView *view = gPad->GetView(); @@ -151,37 +149,34 @@ TGeoTube::TGeoTube() SetShapeBit(TGeoShape::kGeoTube); fRmin = 0.0; fRmax = 0.0; - fDz = 0.0; + fDz = 0.0; } - //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying minimum and maximum radius -TGeoTube::TGeoTube(Double_t rmin, Double_t rmax, Double_t dz) - :TGeoBBox(0, 0, 0) +TGeoTube::TGeoTube(Double_t rmin, Double_t rmax, Double_t dz) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoTube); SetTubeDimensions(rmin, rmax, dz); - if ((fDz<0) || (fRmin<0) || (fRmax<0)) { + if ((fDz < 0) || (fRmin < 0) || (fRmax < 0)) { SetShapeBit(kGeoRunTimeShape); -// if (fRmax<=fRmin) SetShapeBit(kGeoInvalidShape); -// printf("tube : dz=%f rmin=%f rmax=%f\n", dz, rmin, rmax); + // if (fRmax<=fRmin) SetShapeBit(kGeoInvalidShape); + // printf("tube : dz=%f rmin=%f rmax=%f\n", dz, rmin, rmax); } ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// Default constructor specifying minimum and maximum radius -TGeoTube::TGeoTube(const char *name, Double_t rmin, Double_t rmax, Double_t dz) - :TGeoBBox(name, 0, 0, 0) +TGeoTube::TGeoTube(const char *name, Double_t rmin, Double_t rmax, Double_t dz) : TGeoBBox(name, 0, 0, 0) { SetShapeBit(TGeoShape::kGeoTube); SetTubeDimensions(rmin, rmax, dz); - if ((fDz<0) || (fRmin<0) || (fRmax<0)) { + if ((fDz < 0) || (fRmin < 0) || (fRmax < 0)) { SetShapeBit(kGeoRunTimeShape); -// if (fRmax<=fRmin) SetShapeBit(kGeoInvalidShape); -// printf("tube : dz=%f rmin=%f rmax=%f\n", dz, rmin, rmax); + // if (fRmax<=fRmin) SetShapeBit(kGeoInvalidShape); + // printf("tube : dz=%f rmin=%f rmax=%f\n", dz, rmin, rmax); } ComputeBBox(); } @@ -192,28 +187,26 @@ TGeoTube::TGeoTube(const char *name, Double_t rmin, Double_t rmax, Double_t dz) /// - param[1] = Rmax /// - param[2] = dz -TGeoTube::TGeoTube(Double_t *param) - :TGeoBBox(0, 0, 0) +TGeoTube::TGeoTube(Double_t *param) : TGeoBBox(0, 0, 0) { SetShapeBit(TGeoShape::kGeoTube); SetDimensions(param); - if ((fDz<0) || (fRmin<0) || (fRmax<0)) SetShapeBit(kGeoRunTimeShape); + if ((fDz < 0) || (fRmin < 0) || (fRmax < 0)) + SetShapeBit(kGeoRunTimeShape); ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// /// destructor -TGeoTube::~TGeoTube() -{ -} +TGeoTube::~TGeoTube() {} //////////////////////////////////////////////////////////////////////////////// /// Computes capacity of the shape in [length^3] Double_t TGeoTube::Capacity() const { - return TGeoTube::Capacity(fRmin,fRmax, fDz); + return TGeoTube::Capacity(fRmin, fRmax, fDz); } //////////////////////////////////////////////////////////////////////////////// @@ -221,7 +214,7 @@ Double_t TGeoTube::Capacity() const Double_t TGeoTube::Capacity(Double_t rmin, Double_t rmax, Double_t dz) { - Double_t capacity = 2.*TMath::Pi()*(rmax*rmax-rmin*rmin)*dz; + Double_t capacity = 2. * TMath::Pi() * (rmax * rmax - rmin * rmin) * dz; return capacity; } @@ -240,22 +233,22 @@ void TGeoTube::ComputeBBox() void TGeoTube::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - saf[0] = TMath::Abs(fDz-TMath::Abs(point[2])); - saf[1] = (fRmin>1E-10)?TMath::Abs(r-fRmin):TGeoShape::Big(); - saf[2] = TMath::Abs(fRmax-r); - Int_t i = TMath::LocMin(3,saf); - if (i==0) { + saf[0] = TMath::Abs(fDz - TMath::Abs(point[2])); + saf[1] = (fRmin > 1E-10) ? TMath::Abs(r - fRmin) : TGeoShape::Big(); + saf[2] = TMath::Abs(fRmax - r); + Int_t i = TMath::LocMin(3, saf); + if (i == 0) { norm[0] = norm[1] = 0.; - norm[2] = TMath::Sign(1.,dir[2]); + norm[2] = TMath::Sign(1., dir[2]); return; } norm[2] = 0; Double_t phi = TMath::ATan2(point[1], point[0]); norm[0] = TMath::Cos(phi); norm[1] = TMath::Sin(phi); - if (norm[0]*dir[0]+norm[1]*dir[1]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; } @@ -264,14 +257,14 @@ void TGeoTube::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ //////////////////////////////////////////////////////////////////////////////// /// Compute normal to closest surface from POINT. -void TGeoTube::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t /*rmin*/, Double_t /*rmax*/, Double_t /*dz*/) +void TGeoTube::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t /*rmin*/, + Double_t /*rmax*/, Double_t /*dz*/) { norm[2] = 0; Double_t phi = TMath::ATan2(point[1], point[0]); norm[0] = TMath::Cos(phi); norm[1] = TMath::Sin(phi); - if (norm[0]*dir[0]+norm[1]*dir[1]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; } @@ -282,9 +275,11 @@ void TGeoTube::ComputeNormalS(const Double_t *point, const Double_t *dir, Double Bool_t TGeoTube::Contains(const Double_t *point) const { - if (TMath::Abs(point[2]) > fDz) return kFALSE; - Double_t r2 = point[0]*point[0]+point[1]*point[1]; - if ((r2fRmax*fRmax)) return kFALSE; + if (TMath::Abs(point[2]) > fDz) + return kFALSE; + Double_t r2 = point[0] * point[0] + point[1] * point[1]; + if ((r2 < fRmin * fRmin) || (r2 > fRmax * fRmax)) + return kFALSE; return kTRUE; } @@ -294,8 +289,9 @@ Bool_t TGeoTube::Contains(const Double_t *point) const Int_t TGeoTube::DistancetoPrimitive(Int_t px, Int_t py) { Int_t n = gGeoManager->GetNsegments(); - Int_t numPoints = 4*n; - if (!HasRmin()) numPoints = 2*(n+1); + Int_t numPoints = 4 * n; + if (!HasRmin()) + numPoints = 2 * (n + 1); return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -305,42 +301,49 @@ Int_t TGeoTube::DistancetoPrimitive(Int_t px, Int_t py) /// compute distance to surface /// Do Z -Double_t TGeoTube::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz) +Double_t +TGeoTube::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz) { Double_t sz = TGeoShape::Big(); if (dir[2]) { - sz = (TMath::Sign(dz, dir[2])-point[2])/dir[2]; - if (sz<=0) return 0.0; + sz = (TMath::Sign(dz, dir[2]) - point[2]) / dir[2]; + if (sz <= 0) + return 0.0; } // Do R - Double_t nsq=dir[0]*dir[0]+dir[1]*dir[1]; - if (TMath::Abs(nsq)0) { + if (rmin > 0) { // Protection in case point is actually outside the tube - if (rsq <= rmin*rmin+TGeoShape::Tolerance()) { - if (rdotn<0) return 0.0; + if (rsq <= rmin * rmin + TGeoShape::Tolerance()) { + if (rdotn < 0) + return 0.0; } else { - if (rdotn<0) { - DistToTube(rsq,nsq,rdotn,rmin,b,d); - if (d>0) { - Double_t sr = -b-d; - if (sr>0) return TMath::Min(sz,sr); + if (rdotn < 0) { + DistToTube(rsq, nsq, rdotn, rmin, b, d); + if (d > 0) { + Double_t sr = -b - d; + if (sr > 0) + return TMath::Min(sz, sr); } } } } // outer cylinder - if (rsq >= rmax*rmax-TGeoShape::Tolerance()) { - if (rdotn>=0) return 0.0; + if (rsq >= rmax * rmax - TGeoShape::Tolerance()) { + if (rdotn >= 0) + return 0.0; } - DistToTube(rsq,nsq,rdotn,rmax,b,d); - if (d>0) { - Double_t sr = -b+d; - if (sr>0) return TMath::Min(sz,sr); + DistToTube(rsq, nsq, rdotn, rmax, b, d); + if (d > 0) { + Double_t sr = -b + d; + if (sr > 0) + return TMath::Min(sz, sr); } return 0.; } @@ -349,12 +352,15 @@ Double_t TGeoTube::DistFromInsideS(const Double_t *point, const Double_t *dir, D /// Compute distance from inside point to surface of the tube /// Boundary safe algorithm. -Double_t TGeoTube::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTube::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } // compute distance to surface return DistFromInsideS(point, dir, fRmin, fRmax, fDz); @@ -365,82 +371,97 @@ Double_t TGeoTube::DistFromInside(const Double_t *point, const Double_t *dir, In /// Boundary safe algorithm. /// check Z planes -Double_t TGeoTube::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz) +Double_t +TGeoTube::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz) { - Double_t xi,yi,zi; - Double_t rmaxsq = rmax*rmax; - Double_t rminsq = rmin*rmin; + Double_t xi, yi, zi; + Double_t rmaxsq = rmax * rmax; + Double_t rminsq = rmin * rmin; zi = dz - TMath::Abs(point[2]); Bool_t in = kFALSE; - Bool_t inz = (zi<0)?kFALSE:kTRUE; + Bool_t inz = (zi < 0) ? kFALSE : kTRUE; if (!inz) { - if (point[2]*dir[2]>=0) return TGeoShape::Big(); - Double_t s = -zi/TMath::Abs(dir[2]); - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - Double_t r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) return s; + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); + Double_t s = -zi / TMath::Abs(dir[2]); + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + Double_t r2 = xi * xi + yi * yi; + if ((rminsq <= r2) && (r2 <= rmaxsq)) + return s; } - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; // check outer cyl. surface - Double_t nsq=dir[0]*dir[0]+dir[1]*dir[1]; - Double_t rdotn=point[0]*dir[0]+point[1]*dir[1]; - Double_t b,d; + Double_t nsq = dir[0] * dir[0] + dir[1] * dir[1]; + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1]; + Double_t b, d; Bool_t inrmax = kFALSE; Bool_t inrmin = kFALSE; - if (rsq<=rmaxsq+TGeoShape::Tolerance()) inrmax = kTRUE; - if (rsq>=rminsq-TGeoShape::Tolerance()) inrmin = kTRUE; + if (rsq <= rmaxsq + TGeoShape::Tolerance()) + inrmax = kTRUE; + if (rsq >= rminsq - TGeoShape::Tolerance()) + inrmin = kTRUE; in = inz & inrmin & inrmax; // If inside, we are most likely on a boundary within machine precision. if (in) { Bool_t checkout = kFALSE; Double_t r = TMath::Sqrt(rsq); - if (zi=0) return TGeoShape::Big(); + if (rdotn >= 0) + return TGeoShape::Big(); return 0.0; } - if (TGeoShape::IsSameWithinTolerance(rmin,0)) return 0.0; - if (rdotn>=0) return 0.0; + if (TGeoShape::IsSameWithinTolerance(rmin, 0)) + return 0.0; + if (rdotn >= 0) + return 0.0; // Ray exiting rmin -> check (+) solution for inner tube - if (TMath::Abs(nsq)0) { - Double_t s=-b+d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) return s; + if (d > 0) { + Double_t s = -b + d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) + return s; } } return TGeoShape::Big(); } // Check outer cylinder (only r>rmax has to be considered) - if (TMath::Abs(nsq)0) { - Double_t s=-b-d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) return s; + if (d > 0) { + Double_t s = -b - d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) + return s; } } } // check inner cylinder - if (rmin>0) { + if (rmin > 0) { DistToTube(rsq, nsq, rdotn, rmin, b, d); - if (d>0) { - Double_t s=-b+d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) return s; + if (d > 0) { + Double_t s = -b + d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) + return s; } } } @@ -452,16 +473,20 @@ Double_t TGeoTube::DistFromOutsideS(const Double_t *point, const Double_t *dir, /// Boundary safe algorithm. /// fist localize point w.r.t tube -Double_t TGeoTube::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTube::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); // find distance to shape return DistFromOutsideS(point, dir, fRmin, fRmax, fDz); } @@ -478,13 +503,13 @@ Double_t TGeoTube::DistFromOutside(const Double_t *point, const Double_t *dir, I void TGeoTube::DistToTube(Double_t rsq, Double_t nsq, Double_t rdotn, Double_t radius, Double_t &b, Double_t &delta) { - Double_t t1 = 1./nsq; - Double_t t3=rsq-(radius*radius); - b = t1*rdotn; - Double_t c =t1*t3; - delta = b*b-c; - if (delta>0) { - delta=TMath::Sqrt(delta); + Double_t t1 = 1. / nsq; + Double_t t3 = rsq - (radius * radius); + b = t1 * rdotn; + Double_t c = t1 * t3; + delta = b * b - c; + if (delta > 0) { + delta = TMath::Sqrt(delta); } else { delta = -1; } @@ -498,62 +523,60 @@ void TGeoTube::DistToTube(Double_t rsq, Double_t nsq, Double_t rdotn, Double_t r /// was divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoTube::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoTube::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- R division - finder = new TGeoPatternCylR(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "R"; - voldiv->AddNodeOffset(vol, id, 0, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 2: //--- Phi division - finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoTubeSeg(fRmin, fRmax, fDz, -step/2, step/2); - vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Z division - finder = new TGeoPatternZ(voldiv, ndiv, start, start+ndiv*step); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoTube(fRmin, fRmax, step/2); + case 1: //--- R division + finder = new TGeoPatternCylR(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + shape = new TGeoTube(start + id * step, start + (id + 1) * step, fDz); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Z"; - for (id=0; idAddNodeOffset(vol, id, start+step/2+id*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "In shape %s wrong axis type for division", GetName()); - return 0; + opt = "R"; + voldiv->AddNodeOffset(vol, id, 0, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 2: //--- Phi division + finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoTubeSeg(fRmin, fRmax, fDz, -step / 2, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Z division + finder = new TGeoPatternZ(voldiv, ndiv, start, start + ndiv * step); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoTube(fRmin, fRmax, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Z"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + step / 2 + id * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "In shape %s wrong axis type for division", GetName()); return 0; } } @@ -563,14 +586,10 @@ TGeoVolume *TGeoTube::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxi const char *TGeoTube::GetAxisName(Int_t iaxis) const { switch (iaxis) { - case 1: - return "R"; - case 2: - return "PHI"; - case 3: - return "Z"; - default: - return "UNDEFINED"; + case 1: return "R"; + case 2: return "PHI"; + case 3: return "Z"; + default: return "UNDEFINED"; } } @@ -583,21 +602,21 @@ Double_t TGeoTube::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fRmin; - xhi = fRmax; - dx = xhi-xlo; - return dx; - case 2: - xlo = 0; - xhi = 360; - dx = 360; - return dx; - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 1: + xlo = fRmin; + xhi = fRmax; + dx = xhi - xlo; + return dx; + case 2: + xlo = 0; + xhi = 360; + dx = 360; + return dx; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -612,8 +631,8 @@ void TGeoTube::GetBoundingCylinder(Double_t *param) const param[0] *= param[0]; param[1] = fRmax; // Rmax param[1] *= param[1]; - param[2] = 0.; // Phi1 - param[3] = 360.; // Phi2 + param[2] = 0.; // Phi1 + param[3] = 360.; // Phi2 } //////////////////////////////////////////////////////////////////////////////// @@ -622,24 +641,28 @@ void TGeoTube::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoTube::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; Double_t rmin, rmax, dz; - Double_t xmin,xmax; + Double_t xmin, xmax; rmin = fRmin; rmax = fRmax; dz = fDz; - if (fDz<0) { - mother->GetAxisRange(3,xmin,xmax); - if (xmax<0) return 0; - dz=xmax; - } - mother->GetAxisRange(1,xmin,xmax); - if (fRmin<0) { - if (xmin<0) return 0; + if (fDz < 0) { + mother->GetAxisRange(3, xmin, xmax); + if (xmax < 0) + return 0; + dz = xmax; + } + mother->GetAxisRange(1, xmin, xmax); + if (fRmin < 0) { + if (xmin < 0) + return 0; rmin = xmin; } - if (fRmax<0) { - if (xmax<=0) return 0; + if (fRmax < 0) { + if (xmax <= 0) + return 0; rmax = xmax; } @@ -666,18 +689,17 @@ void TGeoTube::InspectShape() const TBuffer3D *TGeoTube::MakeBuffer3D() const { Int_t n = gGeoManager->GetNsegments(); - Int_t nbPnts = 4*n; - Int_t nbSegs = 8*n; - Int_t nbPols = 4*n; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 8 * n; + Int_t nbPols = 4 * n; if (!HasRmin()) { - nbPnts = 2*(n+1); - nbSegs = 5*n; - nbPols = 3*n; - } - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols); - if (buff) - { + nbPnts = 2 * (n + 1); + nbSegs = 5 * n; + nbPols = 3 * n; + } + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -690,10 +712,11 @@ TBuffer3D *TGeoTube::MakeBuffer3D() const void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const { - Int_t i, j,indx; + Int_t i, j, indx; Int_t n = gGeoManager->GetNsegments(); - Int_t c = (((buffer.fColor) %8) -1) * 4; - if (c < 0) c = 0; + Int_t c = (((buffer.fColor) % 8) - 1) * 4; + if (c < 0) + c = 0; if (HasRmin()) { // circle segments: @@ -703,10 +726,10 @@ void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const // upper rmax circle: i=1, (3n, 4n-1) for (i = 0; i < 4; i++) { for (j = 0; j < n; j++) { - indx = 3*(i*n+j); - buffer.fSegs[indx ] = c; - buffer.fSegs[indx+1] = i*n+j; - buffer.fSegs[indx+2] = i*n+(j+1)%n; + indx = 3 * (i * n + j); + buffer.fSegs[indx] = c; + buffer.fSegs[indx + 1] = i * n + j; + buffer.fSegs[indx + 2] = i * n + (j + 1) % n; } } // Z-parallel segments @@ -714,10 +737,10 @@ void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const // outer: i=5, (5n, 6n-1) for (i = 4; i < 6; i++) { for (j = 0; j < n; j++) { - indx = 3*(i*n+j); - buffer.fSegs[indx ] = c+1; - buffer.fSegs[indx+1] = (i-4)*n+j; - buffer.fSegs[indx+2] = (i-2)*n+j; + indx = 3 * (i * n + j); + buffer.fSegs[indx] = c + 1; + buffer.fSegs[indx + 1] = (i - 4) * n + j; + buffer.fSegs[indx + 2] = (i - 2) * n + j; } } // Radial segments @@ -725,56 +748,56 @@ void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const // upper: i=7, (7n, 8n-1) for (i = 6; i < 8; i++) { for (j = 0; j < n; j++) { - indx = 3*(i*n+j); - buffer.fSegs[indx ] = c; - buffer.fSegs[indx+1] = 2*(i-6)*n+j; - buffer.fSegs[indx+2] = (2*(i-6)+1)*n+j; + indx = 3 * (i * n + j); + buffer.fSegs[indx] = c; + buffer.fSegs[indx + 1] = 2 * (i - 6) * n + j; + buffer.fSegs[indx + 2] = (2 * (i - 6) + 1) * n + j; } } // Polygons - i=0; + i = 0; // Inner lateral (0, n-1) for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = j; - buffer.fPols[indx+3] = 4*n+(j+1)%n; - buffer.fPols[indx+4] = 2*n+j; - buffer.fPols[indx+5] = 4*n+j; - } - i=1; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = j; + buffer.fPols[indx + 3] = 4 * n + (j + 1) % n; + buffer.fPols[indx + 4] = 2 * n + j; + buffer.fPols[indx + 5] = 4 * n + j; + } + i = 1; // Outer lateral (n,2n-1) for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c+1; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = n+j; - buffer.fPols[indx+3] = 5*n+j; - buffer.fPols[indx+4] = 3*n+j; - buffer.fPols[indx+5] = 5*n+(j+1)%n; - } - i=2; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c + 1; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = n + j; + buffer.fPols[indx + 3] = 5 * n + j; + buffer.fPols[indx + 4] = 3 * n + j; + buffer.fPols[indx + 5] = 5 * n + (j + 1) % n; + } + i = 2; // lower disc (2n, 3n-1) for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = j; - buffer.fPols[indx+3] = 6*n+j; - buffer.fPols[indx+4] = n+j; - buffer.fPols[indx+5] = 6*n+(j+1)%n; - } - i=3; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = j; + buffer.fPols[indx + 3] = 6 * n + j; + buffer.fPols[indx + 4] = n + j; + buffer.fPols[indx + 5] = 6 * n + (j + 1) % n; + } + i = 3; // upper disc (3n, 4n-1) for (j = 0; j < n; j++) { - indx = 6*(i*n+j); - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = 2*n+j; - buffer.fPols[indx+3] = 7*n+(j+1)%n; - buffer.fPols[indx+4] = 3*n+j; - buffer.fPols[indx+5] = 7*n+j; + indx = 6 * (i * n + j); + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = 2 * n + j; + buffer.fPols[indx + 3] = 7 * n + (j + 1) % n; + buffer.fPols[indx + 4] = 3 * n + j; + buffer.fPols[indx + 5] = 7 * n + j; } return; } @@ -784,58 +807,58 @@ void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const // upper rmax circle: i=1, (n, 2n-1) for (i = 0; i < 2; i++) { for (j = 0; j < n; j++) { - indx = 3*(i*n+j); - buffer.fSegs[indx ] = c; - buffer.fSegs[indx+1] = 2+i*n+j; - buffer.fSegs[indx+2] = 2+i*n+(j+1)%n; + indx = 3 * (i * n + j); + buffer.fSegs[indx] = c; + buffer.fSegs[indx + 1] = 2 + i * n + j; + buffer.fSegs[indx + 2] = 2 + i * n + (j + 1) % n; } } // Z-parallel segments (2n,3n-1) for (j = 0; j < n; j++) { - indx = 3*(2*n+j); - buffer.fSegs[indx ] = c+1; - buffer.fSegs[indx+1] = 2+j; - buffer.fSegs[indx+2] = 2+n+j; + indx = 3 * (2 * n + j); + buffer.fSegs[indx] = c + 1; + buffer.fSegs[indx + 1] = 2 + j; + buffer.fSegs[indx + 2] = 2 + n + j; } // Radial segments // Lower circle: i=3, (3n,4n-1) // Upper circle: i=4, (4n,5n-1) for (i = 3; i < 5; i++) { for (j = 0; j < n; j++) { - indx = 3*(i*n+j); - buffer.fSegs[indx ] = c; - buffer.fSegs[indx+1] = i-3; - buffer.fSegs[indx+2] = 2+(i-3)*n+j; + indx = 3 * (i * n + j); + buffer.fSegs[indx] = c; + buffer.fSegs[indx + 1] = i - 3; + buffer.fSegs[indx + 2] = 2 + (i - 3) * n + j; } } // Polygons // lateral (0,n-1) for (j = 0; j < n; j++) { - indx = 6*j; - buffer.fPols[indx ] = c+1; - buffer.fPols[indx+1] = 4; - buffer.fPols[indx+2] = j; - buffer.fPols[indx+3] = 2*n+j; - buffer.fPols[indx+4] = n+j; - buffer.fPols[indx+5] = 2*n+(j+1)%n; + indx = 6 * j; + buffer.fPols[indx] = c + 1; + buffer.fPols[indx + 1] = 4; + buffer.fPols[indx + 2] = j; + buffer.fPols[indx + 3] = 2 * n + j; + buffer.fPols[indx + 4] = n + j; + buffer.fPols[indx + 5] = 2 * n + (j + 1) % n; } // bottom triangles (n,2n-1) for (j = 0; j < n; j++) { - indx = 6*n + 5*j; - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 3; - buffer.fPols[indx+2] = j; - buffer.fPols[indx+3] = 3*n+(j+1)%n; - buffer.fPols[indx+4] = 3*n+j; + indx = 6 * n + 5 * j; + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 3; + buffer.fPols[indx + 2] = j; + buffer.fPols[indx + 3] = 3 * n + (j + 1) % n; + buffer.fPols[indx + 4] = 3 * n + j; } // top triangles (2n,3n-1) for (j = 0; j < n; j++) { - indx = 6*n + 5*n + 5*j; - buffer.fPols[indx ] = c; - buffer.fPols[indx+1] = 3; - buffer.fPols[indx+2] = n+j; - buffer.fPols[indx+3] = 4*n+j; - buffer.fPols[indx+4] = 4*n+(j+1)%n; + indx = 6 * n + 5 * n + 5 * j; + buffer.fPols[indx] = c; + buffer.fPols[indx + 1] = 3; + buffer.fPols[indx + 2] = n + j; + buffer.fPols[indx + 3] = 4 * n + j; + buffer.fPols[indx + 4] = 4 * n + (j + 1) % n; } } @@ -846,36 +869,42 @@ void TGeoTube::SetSegsAndPols(TBuffer3D &buffer) const Double_t TGeoTube::Safety(const Double_t *point, Bool_t in) const { #ifndef NEVER - Double_t r = TMath::Sqrt(point[0]*point[0]+point[1]*point[1]); + Double_t r = TMath::Sqrt(point[0] * point[0] + point[1] * point[1]); Double_t safe, safrmin, safrmax; if (in) { - safe = fDz-TMath::Abs(point[2]); // positive if inside - if (fRmin>1E-10) { - safrmin = r-fRmin; - if (safrmin < safe) safe = safrmin; + safe = fDz - TMath::Abs(point[2]); // positive if inside + if (fRmin > 1E-10) { + safrmin = r - fRmin; + if (safrmin < safe) + safe = safrmin; } - safrmax = fRmax-r; - if (safrmax < safe) safe = safrmax; + safrmax = fRmax - r; + if (safrmax < safe) + safe = safrmax; } else { - safe = -fDz+TMath::Abs(point[2]); - if (fRmin>1E-10) { - safrmin = -r+fRmin; - if (safrmin > safe) safe = safrmin; + safe = -fDz + TMath::Abs(point[2]); + if (fRmin > 1E-10) { + safrmin = -r + fRmin; + if (safrmin > safe) + safe = safrmin; } - safrmax = -fRmax+r; - if (safrmax > safe) safe = safrmax; + safrmax = -fRmax + r; + if (safrmax > safe) + safe = safrmax; } return safe; #else Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - saf[0] = fDz-TMath::Abs(point[2]); // positive if inside - saf[1] = (fRmin>1E-10)?(r-fRmin):TGeoShape::Big(); - saf[2] = fRmax-r; - if (in) return saf[TMath::LocMin(3,saf)]; - for (Int_t i=0; i<3; i++) saf[i]=-saf[i]; - return saf[TMath::LocMax(3,saf)]; + saf[0] = fDz - TMath::Abs(point[2]); // positive if inside + saf[1] = (fRmin > 1E-10) ? (r - fRmin) : TGeoShape::Big(); + saf[2] = fRmax - r; + if (in) + return saf[TMath::LocMin(3, saf)]; + for (Int_t i = 0; i < 3; i++) + saf[i] = -saf[i]; + return saf[TMath::LocMax(3, saf)]; #endif } @@ -886,27 +915,28 @@ Double_t TGeoTube::Safety(const Double_t *point, Bool_t in) const Double_t TGeoTube::SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Double_t rmax, Double_t dz, Int_t skipz) { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); switch (skipz) { - case 1: // skip lower Z plane - saf[0] = dz - point[2]; - break; - case 2: // skip upper Z plane - saf[0] = dz + point[2]; - break; - case 3: // skip both - saf[0] = TGeoShape::Big(); - break; - default: - saf[0] = dz-TMath::Abs(point[2]); - } - saf[1] = (rmin>1E-10)?(r-rmin):TGeoShape::Big(); - saf[2] = rmax-r; -// printf("saf0=%g saf1=%g saf2=%g in=%d skipz=%d\n", saf[0],saf[1],saf[2],in,skipz); - if (in) return saf[TMath::LocMin(3,saf)]; - for (Int_t i=0; i<3; i++) saf[i]=-saf[i]; - return saf[TMath::LocMax(3,saf)]; + case 1: // skip lower Z plane + saf[0] = dz - point[2]; + break; + case 2: // skip upper Z plane + saf[0] = dz + point[2]; + break; + case 3: // skip both + saf[0] = TGeoShape::Big(); + break; + default: saf[0] = dz - TMath::Abs(point[2]); + } + saf[1] = (rmin > 1E-10) ? (r - rmin) : TGeoShape::Big(); + saf[2] = rmax - r; + // printf("saf0=%g saf1=%g saf2=%g in=%d skipz=%d\n", saf[0],saf[1],saf[2],in,skipz); + if (in) + return saf[TMath::LocMin(3, saf)]; + for (Int_t i = 0; i < 3; i++) + saf[i] = -saf[i]; + return saf[TMath::LocMax(3, saf)]; } //////////////////////////////////////////////////////////////////////////////// @@ -914,7 +944,8 @@ Double_t TGeoTube::SafetyS(const Double_t *point, Bool_t in, Double_t rmin, Doub void TGeoTube::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rmin = " << fRmin << ";" << std::endl; out << " rmax = " << fRmax << ";" << std::endl; @@ -930,9 +961,9 @@ void TGeoTube::SetTubeDimensions(Double_t rmin, Double_t rmax, Double_t dz) { fRmin = rmin; fRmax = rmax; - fDz = dz; - if (fRmin>0 && fRmax>0 && fRmin>=fRmax) - Error("SetTubeDimensions", "In shape %s wrong rmin=%g rmax=%g", GetName(), rmin,rmax); + fDz = dz; + if (fRmin > 0 && fRmax > 0 && fRmin >= fRmax) + Error("SetTubeDimensions", "In shape %s wrong rmin=%g rmax=%g", GetName(), rmin, rmax); } //////////////////////////////////////////////////////////////////////////////// @@ -942,7 +973,7 @@ void TGeoTube::SetDimensions(Double_t *param) { Double_t rmin = param[0]; Double_t rmax = param[1]; - Double_t dz = param[2]; + Double_t dz = param[2]; SetTubeDimensions(rmin, rmax, dz); } @@ -953,29 +984,34 @@ void TGeoTube::SetDimensions(Double_t *param) Bool_t TGeoTube::GetPointsOnSegments(Int_t npoints, Double_t *array) const { - if (npoints > (npoints/2)*2) { - Error("GetPointsOnSegments","Npoints must be even number"); + if (npoints > (npoints / 2) * 2) { + Error("GetPointsOnSegments", "Npoints must be even number"); return kFALSE; } Int_t nc = 0; - if (HasRmin()) nc = (Int_t)TMath::Sqrt(0.5*npoints); - else nc = (Int_t)TMath::Sqrt(1.*npoints); - Double_t dphi = TMath::TwoPi()/nc; + if (HasRmin()) + nc = (Int_t)TMath::Sqrt(0.5 * npoints); + else + nc = (Int_t)TMath::Sqrt(1. * npoints); + Double_t dphi = TMath::TwoPi() / nc; Double_t phi = 0; Int_t ntop = 0; - if (HasRmin()) ntop = npoints/2 - nc*(nc-1); - else ntop = npoints - nc*(nc-1); - Double_t dz = 2*fDz/(nc-1); + if (HasRmin()) + ntop = npoints / 2 - nc * (nc - 1); + else + ntop = npoints - nc * (nc - 1); + Double_t dz = 2 * fDz / (nc - 1); Double_t z = 0; Int_t icrt = 0; Int_t nphi = nc; // loop z sections - for (Int_t i=0; iGetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; dz = fDz; Int_t indx = 0; @@ -1007,25 +1043,25 @@ void TGeoTube::SetPoints(Double_t *points) const // (0,n-1) lower rmin circle // (2n, 3n-1) upper rmin circle for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } // (n, 2n-1) lower rmax circle // (3n, 4n-1) upper rmax circle for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } else { @@ -1039,13 +1075,13 @@ void TGeoTube::SetPoints(Double_t *points) const // lower rmax circle (2, 2+n-1) // upper rmax circle (2+n, 2+2n-1) for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+3*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 3 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+3*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 3 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+3*n]= dz; - points[indx] =-dz; + points[indx + 3 * n] = dz; + points[indx] = -dz; indx++; } } @@ -1060,7 +1096,7 @@ void TGeoTube::SetPoints(Float_t *points) const Double_t dz; Int_t j, n; n = gGeoManager->GetNsegments(); - Double_t dphi = 360./n; + Double_t dphi = 360. / n; Double_t phi = 0; dz = fDz; Int_t indx = 0; @@ -1070,25 +1106,25 @@ void TGeoTube::SetPoints(Float_t *points) const // (0,n-1) lower rmin circle // (2n, 3n-1) upper rmin circle for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } // (n, 2n-1) lower rmax circle // (3n, 4n-1) upper rmax circle for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } else { @@ -1102,13 +1138,13 @@ void TGeoTube::SetPoints(Float_t *points) const // lower rmax circle (2, 2+n-1) // upper rmax circle (2+n, 2+2n-1) for (j = 0; j < n; j++) { - phi = j*dphi*TMath::DegToRad(); - points[indx+3*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = j * dphi * TMath::DegToRad(); + points[indx + 3 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+3*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 3 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+3*n]= dz; - points[indx] =-dz; + points[indx + 3 * n] = dz; + points[indx] = -dz; indx++; } } @@ -1121,8 +1157,9 @@ void TGeoTube::SetPoints(Float_t *points) const Int_t TGeoTube::GetNmeshVertices() const { Int_t n = gGeoManager->GetNsegments(); - Int_t numPoints = n*4; - if (!HasRmin()) numPoints = 2*(n+1); + Int_t numPoints = n * 4; + if (!HasRmin()) + numPoints = 2 * (n + 1); return numPoints; } @@ -1132,52 +1169,50 @@ Int_t TGeoTube::GetNmeshVertices() const void TGeoTube::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { Int_t n = gGeoManager->GetNsegments(); - nvert = n*4; - nsegs = n*8; - npols = n*4; + nvert = n * 4; + nsegs = n * 8; + npols = n * 4; if (!HasRmin()) { - nvert = 2*(n+1); - nsegs = 5*n; - npols = 3*n; + nvert = 2 * (n + 1); + nsegs = 5 * n; + npols = 3 * n; } else { - nvert = n*4; - nsegs = n*8; - npols = n*4; + nvert = n * 4; + nsegs = n * 8; + npols = n * 4; } } //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoTube::Sizeof3D() const -{ -} +void TGeoTube::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoTube::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoTube::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3DTube buffer; TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kShapeSpecific) { - buffer.fRadiusInner = fRmin; - buffer.fRadiusOuter = fRmax; - buffer.fHalfLength = fDz; + buffer.fRadiusInner = fRmin; + buffer.fRadiusOuter = fRmax; + buffer.fHalfLength = fDz; buffer.SetSectionsValid(TBuffer3D::kShapeSpecific); } if (reqSections & TBuffer3D::kRawSizes) { Int_t n = gGeoManager->GetNsegments(); - Int_t nbPnts = 4*n; - Int_t nbSegs = 8*n; - Int_t nbPols = 4*n; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 8 * n; + Int_t nbPols = 4 * n; if (!HasRmin()) { - nbPnts = 2*(n+1); - nbSegs = 5*n; - nbPols = 3*n; + nbPnts = 2 * (n + 1); + nbSegs = 5 * n; + nbPols = 3 * n; } - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1200,7 +1235,8 @@ const TBuffer3D & TGeoTube::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoTube::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i360) ddp-=360; - if (ddp<=dp) xmax = fRmax; - ddp = 90-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) ymax = fRmax; - ddp = 180-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) xmin = -fRmax; - ddp = 270-fPhi1; - if (ddp<0) ddp+= 360; - if (ddp>360) ddp-=360; - if (ddp<=dp) ymin = -fRmax; - fOrigin[0] = (xmax+xmin)/2; - fOrigin[1] = (ymax+ymin)/2; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + xmax = fRmax; + ddp = 90 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + ymax = fRmax; + ddp = 180 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + xmin = -fRmax; + ddp = 270 - fPhi1; + if (ddp < 0) + ddp += 360; + if (ddp > 360) + ddp -= 360; + if (ddp <= dp) + ymin = -fRmax; + fOrigin[0] = (xmax + xmin) / 2; + fOrigin[1] = (ymax + ymin) / 2; fOrigin[2] = 0; - fDX = (xmax-xmin)/2; - fDY = (ymax-ymin)/2; + fDX = (xmax - xmin) / 2; + fDY = (ymax - ymin) / 2; fDZ = fDz; } @@ -1397,26 +1446,26 @@ void TGeoTubeSeg::ComputeBBox() void TGeoTubeSeg::ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - saf[0] = TMath::Abs(fDz-TMath::Abs(point[2])); - saf[1] = (fRmin>1E-10)?TMath::Abs(r-fRmin):TGeoShape::Big(); - saf[2] = TMath::Abs(fRmax-r); - Int_t i = TMath::LocMin(3,saf); - if (((fPhi2-fPhi1)<360.) && TGeoShape::IsCloseToPhi(saf[i], point,fC1,fS1,fC2,fS2)) { - TGeoShape::NormalPhi(point,dir,norm,fC1,fS1,fC2,fS2); + saf[0] = TMath::Abs(fDz - TMath::Abs(point[2])); + saf[1] = (fRmin > 1E-10) ? TMath::Abs(r - fRmin) : TGeoShape::Big(); + saf[2] = TMath::Abs(fRmax - r); + Int_t i = TMath::LocMin(3, saf); + if (((fPhi2 - fPhi1) < 360.) && TGeoShape::IsCloseToPhi(saf[i], point, fC1, fS1, fC2, fS2)) { + TGeoShape::NormalPhi(point, dir, norm, fC1, fS1, fC2, fS2); return; } - if (i==0) { + if (i == 0) { norm[0] = norm[1] = 0.; - norm[2] = TMath::Sign(1.,dir[2]); + norm[2] = TMath::Sign(1., dir[2]); return; }; norm[2] = 0; Double_t phi = TMath::ATan2(point[1], point[0]); norm[0] = TMath::Cos(phi); norm[1] = TMath::Sin(phi); - if (norm[0]*dir[0]+norm[1]*dir[1]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; } @@ -1425,25 +1474,24 @@ void TGeoTubeSeg::ComputeNormal(const Double_t *point, const Double_t *dir, Doub //////////////////////////////////////////////////////////////////////////////// /// Compute normal to closest surface from POINT. -void TGeoTubeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, - Double_t rmin, Double_t rmax, Double_t /*dz*/, - Double_t c1, Double_t s1, Double_t c2, Double_t s2) +void TGeoTubeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Double_t *norm, Double_t rmin, + Double_t rmax, Double_t /*dz*/, Double_t c1, Double_t s1, Double_t c2, Double_t s2) { Double_t saf[2]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - saf[0] = (rmin>1E-10)?TMath::Abs(r-rmin):TGeoShape::Big(); - saf[1] = TMath::Abs(rmax-r); - Int_t i = TMath::LocMin(2,saf); - if (TGeoShape::IsCloseToPhi(saf[i], point,c1,s1,c2,s2)) { - TGeoShape::NormalPhi(point,dir,norm,c1,s1,c2,s2); + saf[0] = (rmin > 1E-10) ? TMath::Abs(r - rmin) : TGeoShape::Big(); + saf[1] = TMath::Abs(rmax - r); + Int_t i = TMath::LocMin(2, saf); + if (TGeoShape::IsCloseToPhi(saf[i], point, c1, s1, c2, s2)) { + TGeoShape::NormalPhi(point, dir, norm, c1, s1, c2, s2); return; } norm[2] = 0; Double_t phi = TMath::ATan2(point[1], point[0]); norm[0] = TMath::Cos(phi); norm[1] = TMath::Sin(phi); - if (norm[0]*dir[0]+norm[1]*dir[1]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; } @@ -1455,7 +1503,8 @@ void TGeoTubeSeg::ComputeNormalS(const Double_t *point, const Double_t *dir, Dou Bool_t TGeoTubeSeg::Contains(const Double_t *point) const { - if (!TGeoTube::Contains(point)) return kFALSE; + if (!TGeoTube::Contains(point)) + return kFALSE; return IsInPhiRange(point, fPhi1, fPhi2); } @@ -1464,8 +1513,8 @@ Bool_t TGeoTubeSeg::Contains(const Double_t *point) const Int_t TGeoTubeSeg::DistancetoPrimitive(Int_t px, Int_t py) { - Int_t n = gGeoManager->GetNsegments()+1; - const Int_t numPoints = 4*n; + Int_t n = gGeoManager->GetNsegments() + 1; + const Int_t numPoints = 4 * n; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -1474,46 +1523,58 @@ Int_t TGeoTubeSeg::DistancetoPrimitive(Int_t px, Int_t py) /// Boundary safe algorithm. /// Do Z -Double_t TGeoTubeSeg::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, Double_t dz, - Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, Double_t sm, Double_t cdfi) +Double_t TGeoTubeSeg::DistFromInsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, + Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, + Double_t sm, Double_t cdfi) { - Double_t stube = TGeoTube::DistFromInsideS(point,dir,rmin,rmax,dz); - if (stube<=0) return 0.0; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t stube = TGeoTube::DistFromInsideS(point, dir, rmin, rmax, dz); + if (stube <= 0) + return 0.0; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t cpsi=point[0]*cm+point[1]*sm; - if (cpsi>r*cdfi+TGeoShape::Tolerance()) { + Double_t cpsi = point[0] * cm + point[1] * sm; + if (cpsi > r * cdfi + TGeoShape::Tolerance()) { Double_t sfmin = TGeoShape::DistToPhiMin(point, dir, s1, c1, s2, c2, sm, cm); - return TMath::Min(stube,sfmin); + return TMath::Min(stube, sfmin); } // Point on the phi boundary or outside // which one: phi1 or phi2 Double_t ddotn, xi, yi; - if (TMath::Abs(point[1]-s1*r) < TMath::Abs(point[1]-s2*r)) { - ddotn = s1*dir[0]-c1*dir[1]; - if (ddotn>=0) return 0.0; - ddotn = -s2*dir[0]+c2*dir[1]; - if (ddotn<=0) return stube; - Double_t sfmin = s2*point[0]-c2*point[1]; - if (sfmin<=0) return stube; + if (TMath::Abs(point[1] - s1 * r) < TMath::Abs(point[1] - s2 * r)) { + ddotn = s1 * dir[0] - c1 * dir[1]; + if (ddotn >= 0) + return 0.0; + ddotn = -s2 * dir[0] + c2 * dir[1]; + if (ddotn <= 0) + return stube; + Double_t sfmin = s2 * point[0] - c2 * point[1]; + if (sfmin <= 0) + return stube; sfmin /= ddotn; - if (sfmin >= stube) return stube; - xi = point[0]+sfmin*dir[0]; - yi = point[1]+sfmin*dir[1]; - if (yi*cm-xi*sm<0) return stube; + if (sfmin >= stube) + return stube; + xi = point[0] + sfmin * dir[0]; + yi = point[1] + sfmin * dir[1]; + if (yi * cm - xi * sm < 0) + return stube; return sfmin; } - ddotn = -s2*dir[0]+c2*dir[1]; - if (ddotn>=0) return 0.0; - ddotn = s1*dir[0]-c1*dir[1]; - if (ddotn<=0) return stube; - Double_t sfmin = -s1*point[0]+c1*point[1]; - if (sfmin<=0) return stube; + ddotn = -s2 * dir[0] + c2 * dir[1]; + if (ddotn >= 0) + return 0.0; + ddotn = s1 * dir[0] - c1 * dir[1]; + if (ddotn <= 0) + return stube; + Double_t sfmin = -s1 * point[0] + c1 * point[1]; + if (sfmin <= 0) + return stube; sfmin /= ddotn; - if (sfmin >= stube) return stube; - xi = point[0]+sfmin*dir[0]; - yi = point[1]+sfmin*dir[1]; - if (yi*cm-xi*sm>0) return stube; + if (sfmin >= stube) + return stube; + xi = point[0] + sfmin * dir[0]; + yi = point[1] + sfmin * dir[1]; + if (yi * cm - xi * sm > 0) + return stube; return sfmin; } @@ -1521,17 +1582,21 @@ Double_t TGeoTubeSeg::DistFromInsideS(const Double_t *point, const Double_t *dir /// Compute distance from inside point to surface of the tube segment /// Boundary safe algorithm. -Double_t TGeoTubeSeg::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoTubeSeg::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = SafetyS(point, kTRUE, fRmin, fRmax, fDz, fPhi1, fPhi2); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); } - if ((fPhi2-fPhi1)>=360.) return TGeoTube::DistFromInsideS(point,dir,fRmin,fRmax,fDz); + if ((fPhi2 - fPhi1) >= 360.) + return TGeoTube::DistFromInsideS(point, dir, fRmin, fRmax, fDz); // compute distance to surface - return TGeoTubeSeg::DistFromInsideS(point,dir,fRmin,fRmax,fDz,fC1,fS1,fC2,fS2,fCm,fSm,fCdfi); + return TGeoTubeSeg::DistFromInsideS(point, dir, fRmin, fRmax, fDz, fC1, fS1, fC2, fS2, fCm, fSm, fCdfi); } //////////////////////////////////////////////////////////////////////////////// @@ -1539,170 +1604,191 @@ Double_t TGeoTubeSeg::DistFromInside(const Double_t *point, const Double_t *dir, /// Boundary safe algorithm. Double_t TGeoTubeSeg::DistFromOutsideS(const Double_t *point, const Double_t *dir, Double_t rmin, Double_t rmax, - Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2, - Double_t cm, Double_t sm, Double_t cdfi) + Double_t dz, Double_t c1, Double_t s1, Double_t c2, Double_t s2, Double_t cm, + Double_t sm, Double_t cdfi) { Double_t r2, cpsi, s; // check Z planes Double_t xi, yi, zi; zi = dz - TMath::Abs(point[2]); - Double_t rmaxsq = rmax*rmax; - Double_t rminsq = rmin*rmin; - Double_t snxt=TGeoShape::Big(); + Double_t rmaxsq = rmax * rmax; + Double_t rminsq = rmin * rmin; + Double_t snxt = TGeoShape::Big(); Bool_t in = kFALSE; - Bool_t inz = (zi<0)?kFALSE:kTRUE; + Bool_t inz = (zi < 0) ? kFALSE : kTRUE; if (!inz) { - if (point[2]*dir[2]>=0) return TGeoShape::Big(); - s = -zi/TMath::Abs(dir[2]); - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - cpsi=(xi*cm+yi*sm)/TMath::Sqrt(r2); - if (cpsi>=cdfi) return s; + if (point[2] * dir[2] >= 0) + return TGeoShape::Big(); + s = -zi / TMath::Abs(dir[2]); + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if ((rminsq <= r2) && (r2 <= rmaxsq)) { + cpsi = (xi * cm + yi * sm) / TMath::Sqrt(r2); + if (cpsi >= cdfi) + return s; } } // check outer cyl. surface - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t nsq=dir[0]*dir[0]+dir[1]*dir[1]; - Double_t rdotn=point[0]*dir[0]+point[1]*dir[1]; - Double_t b,d; + Double_t nsq = dir[0] * dir[0] + dir[1] * dir[1]; + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1]; + Double_t b, d; Bool_t inrmax = kFALSE; Bool_t inrmin = kFALSE; - Bool_t inphi = kFALSE; - if (rsq<=rmaxsq+TGeoShape::Tolerance()) inrmax = kTRUE; - if (rsq>=rminsq-TGeoShape::Tolerance()) inrmin = kTRUE; - cpsi=point[0]*cm+point[1]*sm; - if (cpsi>r*cdfi-TGeoShape::Tolerance()) inphi = kTRUE; + Bool_t inphi = kFALSE; + if (rsq <= rmaxsq + TGeoShape::Tolerance()) + inrmax = kTRUE; + if (rsq >= rminsq - TGeoShape::Tolerance()) + inrmin = kTRUE; + cpsi = point[0] * cm + point[1] * sm; + if (cpsi > r * cdfi - TGeoShape::Tolerance()) + inphi = kTRUE; in = inz & inrmin & inrmax & inphi; // If inside, we are most likely on a boundary within machine precision. if (in) { Bool_t checkout = kFALSE; - Double_t safphi = (cpsi-r*cdfi)*TMath::Sqrt(1.-cdfi*cdfi); -// Double_t sch, cch; + Double_t safphi = (cpsi - r * cdfi) * TMath::Sqrt(1. - cdfi * cdfi); + // Double_t sch, cch; // check if on Z boundaries - if (zi=0) return TGeoShape::Big(); + if (checkout && (rmax - r < safphi)) { + if (rdotn >= 0) + return TGeoShape::Big(); return 0.0; } - if (TMath::Abs(nsq) point[0]*c2 + point[1]*s2) { - un = dir[0]*s1-dir[1]*c1; - if (un < 0) return 0.0; - if (cdfi>=0) return TGeoShape::Big(); - un = -dir[0]*s2+dir[1]*c2; - if (un<0) { - s = -point[0]*s2+point[1]*c2; - if (s>0) { + if (point[0] * c1 + point[1] * s1 > point[0] * c2 + point[1] * s2) { + un = dir[0] * s1 - dir[1] * c1; + if (un < 0) + return 0.0; + if (cdfi >= 0) + return TGeoShape::Big(); + un = -dir[0] * s2 + dir[1] * c2; + if (un < 0) { + s = -point[0] * s2 + point[1] * c2; + if (s > 0) { s /= (-un); - zi = point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - if ((yi*cm-xi*sm)>0) return s; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if ((rminsq <= r2) && (r2 <= rmaxsq)) { + if ((yi * cm - xi * sm) > 0) + return s; } } } } } else { - un = -dir[0]*s2+dir[1]*c2; - if (un < 0) return 0.0; - if (cdfi>=0) return TGeoShape::Big(); - un = dir[0]*s1-dir[1]*c1; - if (un<0) { - s = point[0]*s1-point[1]*c1; - if (s>0) { + un = -dir[0] * s2 + dir[1] * c2; + if (un < 0) + return 0.0; + if (cdfi >= 0) + return TGeoShape::Big(); + un = dir[0] * s1 - dir[1] * c1; + if (un < 0) { + s = point[0] * s1 - point[1] * c1; + if (s > 0) { s /= (-un); - zi = point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - if ((yi*cm-xi*sm)<0) return s; + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if ((rminsq <= r2) && (r2 <= rmaxsq)) { + if ((yi * cm - xi * sm) < 0) + return s; } } } } } // We may also cross rmin, (+) solution - if (rdotn>=0) return TGeoShape::Big(); - if (cdfi>=0) return TGeoShape::Big(); + if (rdotn >= 0) + return TGeoShape::Big(); + if (cdfi >= 0) + return TGeoShape::Big(); DistToTube(rsq, nsq, rdotn, rmin, b, d); - if (d>0) { - s=-b+d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - if ((xi*cm+yi*sm) >= rmin*cdfi) return s; + if (d > 0) { + s = -b + d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((xi * cm + yi * sm) >= rmin * cdfi) + return s; } } } return TGeoShape::Big(); } // we are on rmin boundary: we may cross again rmin or a phi facette - if (rdotn>=0) return 0.0; + if (rdotn >= 0) + return 0.0; DistToTube(rsq, nsq, rdotn, rmin, b, d); - if (d>0) { - s=-b+d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { + if (d > 0) { + s = -b + d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { // now check phi range - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - if ((xi*cm+yi*sm) >= rmin*cdfi) return s; + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + if ((xi * cm + yi * sm) >= rmin * cdfi) + return s; // now we really have to check any phi crossing - Double_t un=-dir[0]*s1+dir[1]*c1; + Double_t un = -dir[0] * s1 + dir[1] * c1; if (un > 0) { - s=point[0]*s1-point[1]*c1; - if (s>=0) { + s = point[0] * s1 - point[1] * c1; + if (s >= 0) { s /= un; - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - if ((yi*cm-xi*sm)<=0) { - if (s 0) { - s=(point[1]*c2-point[0]*s2)/un; - if (s>=0 && s=0) { + s = (point[1] * c2 - point[0] * s2) / un; + if (s >= 0 && s < snxt) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if ((rminsq <= r2) && (r2 <= rmaxsq)) { + if ((yi * cm - xi * sm) >= 0) { return s; } } @@ -1716,71 +1802,77 @@ Double_t TGeoTubeSeg::DistFromOutsideS(const Double_t *point, const Double_t *di return TGeoShape::Big(); } // only r>rmax has to be considered - if (TMath::Abs(nsq)=rmax*rmax) { - if (rdotn>=0) return TGeoShape::Big(); + if (TMath::Abs(nsq) < TGeoShape::Tolerance()) + return TGeoShape::Big(); + if (rsq >= rmax * rmax) { + if (rdotn >= 0) + return TGeoShape::Big(); TGeoTube::DistToTube(rsq, nsq, rdotn, rmax, b, d); - if (d>0) { - s=-b-d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - cpsi = xi*cm+yi*sm; - if (cpsi>=rmax*cdfi) return s; + if (d > 0) { + s = -b - d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + cpsi = xi * cm + yi * sm; + if (cpsi >= rmax * cdfi) + return s; } } } } // check inner cylinder - if (rmin>0) { + if (rmin > 0) { TGeoTube::DistToTube(rsq, nsq, rdotn, rmin, b, d); - if (d>0) { - s=-b+d; - if (s>0) { - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - cpsi = xi*cm+yi*sm; - if (cpsi>=rmin*cdfi) snxt=s; + if (d > 0) { + s = -b + d; + if (s > 0) { + zi = point[2] + s * dir[2]; + if (TMath::Abs(zi) <= dz) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + cpsi = xi * cm + yi * sm; + if (cpsi >= rmin * cdfi) + snxt = s; } } } } // check phi planes - Double_t un=-dir[0]*s1+dir[1]*c1; + Double_t un = -dir[0] * s1 + dir[1] * c1; if (un > 0) { - s=point[0]*s1-point[1]*c1; - if (s>=0) { + s = point[0] * s1 - point[1] * c1; + if (s >= 0) { s /= un; - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - if ((yi*cm-xi*sm)<=0) { - if (s 0) { - s=point[1]*c2-point[0]*s2; - if (s>=0) { + s = point[1] * c2 - point[0] * s2; + if (s >= 0) { s /= un; - zi=point[2]+s*dir[2]; - if (TMath::Abs(zi)<=dz) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if ((rminsq<=r2) && (r2<=rmaxsq)) { - if ((yi*cm-xi*sm)>=0) { - if (s= 0) { + if (s < snxt) + snxt = s; } } } @@ -1793,17 +1885,22 @@ Double_t TGeoTubeSeg::DistFromOutsideS(const Double_t *point, const Double_t *di /// compute distance from outside point to surface of the tube segment /// fist localize point w.r.t tube -Double_t TGeoTubeSeg::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t TGeoTubeSeg::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, + Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = SafetyS(point, kFALSE, fRmin, fRmax, fDz, fPhi1, fPhi2); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); - if ((fPhi2-fPhi1)>=360.) return TGeoTube::DistFromOutsideS(point,dir,fRmin,fRmax,fDz); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); + if ((fPhi2 - fPhi1) >= 360.) + return TGeoTube::DistFromOutsideS(point, dir, fRmin, fRmax, fDz); // find distance to shape return TGeoTubeSeg::DistFromOutsideS(point, dir, fRmin, fRmax, fDz, fC1, fS1, fC2, fS2, fCm, fSm, fCdfi); @@ -1817,66 +1914,69 @@ Double_t TGeoTubeSeg::DistFromOutside(const Double_t *point, const Double_t *dir /// was divided. In case a wrong division axis is supplied, returns pointer to /// volume that was divided. -TGeoVolume *TGeoTubeSeg::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, - Double_t start, Double_t step) +TGeoVolume * +TGeoTubeSeg::Divide(TGeoVolume *voldiv, const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step) { - TGeoShape *shape; //--- shape to be created - TGeoVolume *vol; //--- division volume to be created - TGeoVolumeMulti *vmulti; //--- generic divided volume - TGeoPatternFinder *finder; //--- finder to be attached - TString opt = ""; //--- option to be attached + TGeoShape *shape; //--- shape to be created + TGeoVolume *vol; //--- division volume to be created + TGeoVolumeMulti *vmulti; //--- generic divided volume + TGeoPatternFinder *finder; //--- finder to be attached + TString opt = ""; //--- option to be attached Double_t dphi; Int_t id; - Double_t end = start+ndiv*step; + Double_t end = start + ndiv * step; switch (iaxis) { - case 1: //--- R division - finder = new TGeoPatternCylR(voldiv, ndiv, start, end); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - for (id=0; idGetMedium()); - vmulti->AddVolume(vol); - opt = "R"; - voldiv->AddNodeOffset(vol, id, 0, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 2: //--- Phi division - dphi = fPhi2-fPhi1; - if (dphi<0) dphi+=360.; - if (step<=0) {step=dphi/ndiv; start=fPhi1; end=fPhi2;} - finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoTubeSeg(fRmin, fRmax, fDz, -step/2, step/2); - vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); - vmulti->AddVolume(vol); - opt = "Phi"; - for (id=0; idAddNodeOffset(vol, id, start+id*step+step/2, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - case 3: //--- Z division - finder = new TGeoPatternZ(voldiv, ndiv, start, end); - voldiv->SetFinder(finder); - finder->SetDivIndex(voldiv->GetNdaughters()); - shape = new TGeoTubeSeg(fRmin, fRmax, step/2, fPhi1, fPhi2); + case 1: //--- R division + finder = new TGeoPatternCylR(voldiv, ndiv, start, end); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + for (id = 0; id < ndiv; id++) { + shape = new TGeoTubeSeg(start + id * step, start + (id + 1) * step, fDz, fPhi1, fPhi2); vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); - vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); vmulti->AddVolume(vol); - opt = "Z"; - for (id=0; idAddNodeOffset(vol, id, start+step/2+id*step, opt.Data()); - ((TGeoNodeOffset*)voldiv->GetNodes()->At(voldiv->GetNdaughters()-1))->SetFinder(finder); - } - return vmulti; - default: - Error("Divide", "In shape %s wrong axis type for division", GetName()); - return 0; + opt = "R"; + voldiv->AddNodeOffset(vol, id, 0, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 2: //--- Phi division + dphi = fPhi2 - fPhi1; + if (dphi < 0) + dphi += 360.; + if (step <= 0) { + step = dphi / ndiv; + start = fPhi1; + end = fPhi2; + } + finder = new TGeoPatternCylPhi(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoTubeSeg(fRmin, fRmax, fDz, -step / 2, step / 2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Phi"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + id * step + step / 2, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + case 3: //--- Z division + finder = new TGeoPatternZ(voldiv, ndiv, start, end); + voldiv->SetFinder(finder); + finder->SetDivIndex(voldiv->GetNdaughters()); + shape = new TGeoTubeSeg(fRmin, fRmax, step / 2, fPhi1, fPhi2); + vol = new TGeoVolume(divname, shape, voldiv->GetMedium()); + vmulti = gGeoManager->MakeVolumeMulti(divname, voldiv->GetMedium()); + vmulti->AddVolume(vol); + opt = "Z"; + for (id = 0; id < ndiv; id++) { + voldiv->AddNodeOffset(vol, id, start + step / 2 + id * step, opt.Data()); + ((TGeoNodeOffset *)voldiv->GetNodes()->At(voldiv->GetNdaughters() - 1))->SetFinder(finder); + } + return vmulti; + default: Error("Divide", "In shape %s wrong axis type for division", GetName()); return 0; } } @@ -1889,21 +1989,21 @@ Double_t TGeoTubeSeg::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) co xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fRmin; - xhi = fRmax; - dx = xhi-xlo; - return dx; - case 2: - xlo = fPhi1; - xhi = fPhi2; - dx = xhi-xlo; - return dx; - case 3: - xlo = -fDz; - xhi = fDz; - dx = xhi-xlo; - return dx; + case 1: + xlo = fRmin; + xhi = fRmax; + dx = xhi - xlo; + return dx; + case 2: + xlo = fPhi1; + xhi = fPhi2; + dx = xhi - xlo; + return dx; + case 3: + xlo = -fDz; + xhi = fDz; + dx = xhi - xlo; + return dx; } return dx; } @@ -1928,7 +2028,8 @@ void TGeoTubeSeg::GetBoundingCylinder(Double_t *param) const TGeoShape *TGeoTubeSeg::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoTube)) { Error("GetMakeRuntimeShape", "Invalid mother for shape %s", GetName()); return 0; @@ -1937,13 +2038,14 @@ TGeoShape *TGeoTubeSeg::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*ma rmin = fRmin; rmax = fRmax; dz = fDz; - if (fDz<0) dz=((TGeoTube*)mother)->GetDz(); - if (fRmin<0) - rmin = ((TGeoTube*)mother)->GetRmin(); - if ((fRmax<0) || (fRmax<=fRmin)) - rmax = ((TGeoTube*)mother)->GetRmax(); + if (fDz < 0) + dz = ((TGeoTube *)mother)->GetDz(); + if (fRmin < 0) + rmin = ((TGeoTube *)mother)->GetRmin(); + if ((fRmax < 0) || (fRmax <= fRmin)) + rmax = ((TGeoTube *)mother)->GetRmax(); - return (new TGeoTubeSeg(GetName(),rmin, rmax, dz, fPhi1, fPhi2)); + return (new TGeoTubeSeg(GetName(), rmin, rmax, dz, fPhi1, fPhi2)); } //////////////////////////////////////////////////////////////////////////////// @@ -1967,15 +2069,14 @@ void TGeoTubeSeg::InspectShape() const TBuffer3D *TGeoTubeSeg::MakeBuffer3D() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = 4*n; - Int_t nbSegs = 2*nbPnts; - Int_t nbPols = nbPnts-2; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 2 * nbPnts; + Int_t nbPols = nbPnts - 2; - TBuffer3D* buff = new TBuffer3D(TBuffer3DTypes::kGeneric, - nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols); - if (buff) - { + TBuffer3D *buff = + new TBuffer3D(TBuffer3DTypes::kGeneric, nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols); + if (buff) { SetPoints(buff->fPnts); SetSegsAndPols(*buff); } @@ -1989,82 +2090,82 @@ TBuffer3D *TGeoTubeSeg::MakeBuffer3D() const void TGeoTubeSeg::SetSegsAndPols(TBuffer3D &buff) const { Int_t i, j; - Int_t n = gGeoManager->GetNsegments()+1; + Int_t n = gGeoManager->GetNsegments() + 1; Int_t c = GetBasicColor(); - memset(buff.fSegs, 0, buff.NbSegs()*3*sizeof(Int_t)); + memset(buff.fSegs, 0, buff.NbSegs() * 3 * sizeof(Int_t)); for (i = 0; i < 4; i++) { for (j = 1; j < n; j++) { - buff.fSegs[(i*n+j-1)*3 ] = c; - buff.fSegs[(i*n+j-1)*3+1] = i*n+j-1; - buff.fSegs[(i*n+j-1)*3+2] = i*n+j; + buff.fSegs[(i * n + j - 1) * 3] = c; + buff.fSegs[(i * n + j - 1) * 3 + 1] = i * n + j - 1; + buff.fSegs[(i * n + j - 1) * 3 + 2] = i * n + j; } } for (i = 4; i < 6; i++) { for (j = 0; j < n; j++) { - buff.fSegs[(i*n+j)*3 ] = c+1; - buff.fSegs[(i*n+j)*3+1] = (i-4)*n+j; - buff.fSegs[(i*n+j)*3+2] = (i-2)*n+j; + buff.fSegs[(i * n + j) * 3] = c + 1; + buff.fSegs[(i * n + j) * 3 + 1] = (i - 4) * n + j; + buff.fSegs[(i * n + j) * 3 + 2] = (i - 2) * n + j; } } for (i = 6; i < 8; i++) { for (j = 0; j < n; j++) { - buff.fSegs[(i*n+j)*3 ] = c; - buff.fSegs[(i*n+j)*3+1] = 2*(i-6)*n+j; - buff.fSegs[(i*n+j)*3+2] = (2*(i-6)+1)*n+j; + buff.fSegs[(i * n + j) * 3] = c; + buff.fSegs[(i * n + j) * 3 + 1] = 2 * (i - 6) * n + j; + buff.fSegs[(i * n + j) * 3 + 2] = (2 * (i - 6) + 1) * n + j; } } Int_t indx = 0; - memset(buff.fPols, 0, buff.NbPols()*6*sizeof(Int_t)); + memset(buff.fPols, 0, buff.NbPols() * 6 * sizeof(Int_t)); i = 0; - for (j = 0; j < n-1; j++) { + for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; - buff.fPols[indx++] = (4+i)*n+j+1; - buff.fPols[indx++] = (2+i)*n+j; - buff.fPols[indx++] = (4+i)*n+j; - buff.fPols[indx++] = i*n+j; + buff.fPols[indx++] = (4 + i) * n + j + 1; + buff.fPols[indx++] = (2 + i) * n + j; + buff.fPols[indx++] = (4 + i) * n + j; + buff.fPols[indx++] = i * n + j; } i = 1; - for (j = 0; j < n-1; j++) { + for (j = 0; j < n - 1; j++) { buff.fPols[indx++] = c; buff.fPols[indx++] = 4; - buff.fPols[indx++] = i*n+j; - buff.fPols[indx++] = (4+i)*n+j; - buff.fPols[indx++] = (2+i)*n+j; - buff.fPols[indx++] = (4+i)*n+j+1; + buff.fPols[indx++] = i * n + j; + buff.fPols[indx++] = (4 + i) * n + j; + buff.fPols[indx++] = (2 + i) * n + j; + buff.fPols[indx++] = (4 + i) * n + j + 1; } i = 2; - for (j = 0; j < n-1; j++) { - buff.fPols[indx++] = c+i; + for (j = 0; j < n - 1; j++) { + buff.fPols[indx++] = c + i; buff.fPols[indx++] = 4; - buff.fPols[indx++] = (i-2)*2*n+j; - buff.fPols[indx++] = (4+i)*n+j; - buff.fPols[indx++] = ((i-2)*2+1)*n+j; - buff.fPols[indx++] = (4+i)*n+j+1; + buff.fPols[indx++] = (i - 2) * 2 * n + j; + buff.fPols[indx++] = (4 + i) * n + j; + buff.fPols[indx++] = ((i - 2) * 2 + 1) * n + j; + buff.fPols[indx++] = (4 + i) * n + j + 1; } i = 3; - for (j = 0; j < n-1; j++) { - buff.fPols[indx++] = c+i; + for (j = 0; j < n - 1; j++) { + buff.fPols[indx++] = c + i; buff.fPols[indx++] = 4; - buff.fPols[indx++] = (4+i)*n+j+1; - buff.fPols[indx++] = ((i-2)*2+1)*n+j; - buff.fPols[indx++] = (4+i)*n+j; - buff.fPols[indx++] = (i-2)*2*n+j; + buff.fPols[indx++] = (4 + i) * n + j + 1; + buff.fPols[indx++] = ((i - 2) * 2 + 1) * n + j; + buff.fPols[indx++] = (4 + i) * n + j; + buff.fPols[indx++] = (i - 2) * 2 * n + j; } - buff.fPols[indx++] = c+2; + buff.fPols[indx++] = c + 2; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 6*n; - buff.fPols[indx++] = 4*n; - buff.fPols[indx++] = 7*n; - buff.fPols[indx++] = 5*n; - buff.fPols[indx++] = c+2; + buff.fPols[indx++] = 6 * n; + buff.fPols[indx++] = 4 * n; + buff.fPols[indx++] = 7 * n; + buff.fPols[indx++] = 5 * n; + buff.fPols[indx++] = c + 2; buff.fPols[indx++] = 4; - buff.fPols[indx++] = 6*n-1; - buff.fPols[indx++] = 8*n-1; - buff.fPols[indx++] = 5*n-1; - buff.fPols[indx++] = 7*n-1; + buff.fPols[indx++] = 6 * n - 1; + buff.fPols[indx++] = 8 * n - 1; + buff.fPols[indx++] = 5 * n - 1; + buff.fPols[indx++] = 7 * n - 1; } //////////////////////////////////////////////////////////////////////////////// @@ -2074,44 +2175,47 @@ void TGeoTubeSeg::SetSegsAndPols(TBuffer3D &buff) const Double_t TGeoTubeSeg::Safety(const Double_t *point, Bool_t in) const { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); if (in) { - saf[0] = fDz-TMath::Abs(point[2]); - saf[1] = r-fRmin; - saf[2] = fRmax-r; - Double_t safe = saf[TMath::LocMin(3,saf)]; - if ((fPhi2-fPhi1)>=360.) return safe; - Double_t safphi = TGeoShape::SafetyPhi(point,in,fPhi1,fPhi2); + saf[0] = fDz - TMath::Abs(point[2]); + saf[1] = r - fRmin; + saf[2] = fRmax - r; + Double_t safe = saf[TMath::LocMin(3, saf)]; + if ((fPhi2 - fPhi1) >= 360.) + return safe; + Double_t safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); return TMath::Min(safe, safphi); } // Point expected to be outside - Bool_t inphi = kFALSE; - Double_t cpsi=point[0]*fCm+point[1]*fSm; - saf[0] = TMath::Abs(point[2])-fDz; - if (cpsi>r*fCdfi-TGeoShape::Tolerance()) inphi = kTRUE; + Bool_t inphi = kFALSE; + Double_t cpsi = point[0] * fCm + point[1] * fSm; + saf[0] = TMath::Abs(point[2]) - fDz; + if (cpsi > r * fCdfi - TGeoShape::Tolerance()) + inphi = kTRUE; if (inphi) { - saf[1] = fRmin-r; - saf[2] = r-fRmax; - Double_t safe = saf[TMath::LocMax(3,saf)]; + saf[1] = fRmin - r; + saf[2] = r - fRmax; + Double_t safe = saf[TMath::LocMax(3, saf)]; safe = TMath::Max(0., safe); return safe; } // Point outside the phi range // Compute projected radius of the (r,phi) position vector onto // phi1 and phi2 edges and take the maximum for choosing the side. - Double_t rproj = TMath::Max(point[0]*fC1+point[1]*fS1, point[0]*fC2+point[1]*fS2); - saf[1] = fRmin-rproj; - saf[2] = rproj-fRmax; + Double_t rproj = TMath::Max(point[0] * fC1 + point[1] * fS1, point[0] * fC2 + point[1] * fS2); + saf[1] = fRmin - rproj; + saf[2] = rproj - fRmax; Double_t safe = TMath::Max(saf[1], saf[2]); - if ((fPhi2-fPhi1)>=360.) return TMath::Max(safe,saf[0]); - if (safe>0) { + if ((fPhi2 - fPhi1) >= 360.) + return TMath::Max(safe, saf[0]); + if (safe > 0) { // rproj not within (rmin,rmax) - > no need to calculate safphi - safe = TMath::Sqrt(rsq-rproj*rproj+safe*safe); - return (saf[0]<0) ? safe : TMath::Sqrt(safe*safe+saf[0]*saf[0]); + safe = TMath::Sqrt(rsq - rproj * rproj + safe * safe); + return (saf[0] < 0) ? safe : TMath::Sqrt(safe * safe + saf[0] * saf[0]); } - Double_t safphi = TGeoShape::SafetyPhi(point,in,fPhi1,fPhi2); - return (saf[0]<0) ? safphi : TMath::Sqrt(saf[0]*saf[0]+safphi*safphi); + Double_t safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); + return (saf[0] < 0) ? safphi : TMath::Sqrt(saf[0] * saf[0] + safphi * safphi); } //////////////////////////////////////////////////////////////////////////////// @@ -2121,48 +2225,49 @@ Double_t TGeoTubeSeg::SafetyS(const Double_t *point, Bool_t in, Double_t rmin, D Double_t phi1d, Double_t phi2d, Int_t skipz) { Double_t saf[3]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); switch (skipz) { - case 1: // skip lower Z plane - saf[0] = dz - point[2]; - break; - case 2: // skip upper Z plane - saf[0] = dz + point[2]; - break; - case 3: // skip both - saf[0] = TGeoShape::Big(); - break; - default: - saf[0] = dz-TMath::Abs(point[2]); + case 1: // skip lower Z plane + saf[0] = dz - point[2]; + break; + case 2: // skip upper Z plane + saf[0] = dz + point[2]; + break; + case 3: // skip both + saf[0] = TGeoShape::Big(); + break; + default: saf[0] = dz - TMath::Abs(point[2]); } if (in) { - saf[1] = r-rmin; - saf[2] = rmax-r; - Double_t safe = saf[TMath::LocMin(3,saf)]; - if ((phi2d-phi1d)>=360.) return safe; - Double_t safphi = TGeoShape::SafetyPhi(point,in,phi1d,phi2d); + saf[1] = r - rmin; + saf[2] = rmax - r; + Double_t safe = saf[TMath::LocMin(3, saf)]; + if ((phi2d - phi1d) >= 360.) + return safe; + Double_t safphi = TGeoShape::SafetyPhi(point, in, phi1d, phi2d); return TMath::Min(safe, safphi); } // Point expected to be outside saf[0] = -saf[0]; - Bool_t inphi = kFALSE; - Double_t phi1 = phi1d*TMath::DegToRad(); - Double_t phi2 = phi2d*TMath::DegToRad(); + Bool_t inphi = kFALSE; + Double_t phi1 = phi1d * TMath::DegToRad(); + Double_t phi2 = phi2d * TMath::DegToRad(); - Double_t fio = 0.5*(phi1+phi2); + Double_t fio = 0.5 * (phi1 + phi2); Double_t cm = TMath::Cos(fio); Double_t sm = TMath::Sin(fio); - Double_t cpsi=point[0]*cm+point[1]*sm; - Double_t dfi = 0.5*(phi2-phi1); + Double_t cpsi = point[0] * cm + point[1] * sm; + Double_t dfi = 0.5 * (phi2 - phi1); Double_t cdfi = TMath::Cos(dfi); - if (cpsi>r*cdfi-TGeoShape::Tolerance()) inphi = kTRUE; + if (cpsi > r * cdfi - TGeoShape::Tolerance()) + inphi = kTRUE; if (inphi) { - saf[1] = rmin-r; - saf[2] = r-rmax; - Double_t safe = saf[TMath::LocMax(3,saf)]; + saf[1] = rmin - r; + saf[2] = r - rmax; + Double_t safe = saf[TMath::LocMax(3, saf)]; safe = TMath::Max(0., safe); return safe; } @@ -2174,18 +2279,19 @@ Double_t TGeoTubeSeg::SafetyS(const Double_t *point, Bool_t in, Double_t rmin, D Double_t c2 = TMath::Cos(phi2); Double_t s2 = TMath::Sin(phi2); - Double_t rproj = TMath::Max(point[0]*c1+point[1]*s1, point[0]*c2+point[1]*s2); - saf[1] = rmin-rproj; - saf[2] = rproj-rmax; - Double_t safe = TMath::Max(saf[1], saf[2]); - if ((phi2d-phi1d)>=360.) return TMath::Max(safe,saf[0]); - if (safe>0) { + Double_t rproj = TMath::Max(point[0] * c1 + point[1] * s1, point[0] * c2 + point[1] * s2); + saf[1] = rmin - rproj; + saf[2] = rproj - rmax; + Double_t safe = TMath::Max(saf[1], saf[2]); + if ((phi2d - phi1d) >= 360.) + return TMath::Max(safe, saf[0]); + if (safe > 0) { // rproj not within (rmin,rmax) - > no need to calculate safphi - safe = TMath::Sqrt(rsq-rproj*rproj+safe*safe); - return (saf[0]<0) ? safe : TMath::Sqrt(safe*safe+saf[0]*saf[0]); + safe = TMath::Sqrt(rsq - rproj * rproj + safe * safe); + return (saf[0] < 0) ? safe : TMath::Sqrt(safe * safe + saf[0] * saf[0]); } - Double_t safphi = TGeoShape::SafetyPhi(point,in,phi1d,phi2d); - return (saf[0]<0) ? safphi : TMath::Sqrt(saf[0]*saf[0]+safphi*safphi); + Double_t safphi = TGeoShape::SafetyPhi(point, in, phi1d, phi2d); + return (saf[0] < 0) ? safphi : TMath::Sqrt(saf[0] * saf[0] + safphi * safphi); } //////////////////////////////////////////////////////////////////////////////// @@ -2193,14 +2299,16 @@ Double_t TGeoTubeSeg::SafetyS(const Double_t *point, Bool_t in, Double_t rmin, D void TGeoTubeSeg::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rmin = " << fRmin << ";" << std::endl; out << " rmax = " << fRmax << ";" << std::endl; out << " dz = " << fDz << ";" << std::endl; out << " phi1 = " << fPhi1 << ";" << std::endl; out << " phi2 = " << fPhi2 << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoTubeSeg(\"" << GetName() << "\",rmin,rmax,dz,phi1,phi2);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoTubeSeg(\"" << GetName() << "\",rmin,rmax,dz,phi1,phi2);" + << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -2208,17 +2316,19 @@ void TGeoTubeSeg::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""* /// Set dimensions of the tube segment. /// The segment will be from phiStart to phiEnd expressed in degree. -void TGeoTubeSeg::SetTubsDimensions(Double_t rmin, Double_t rmax, Double_t dz, - Double_t phiStart, Double_t phiEnd) +void TGeoTubeSeg::SetTubsDimensions(Double_t rmin, Double_t rmax, Double_t dz, Double_t phiStart, Double_t phiEnd) { fRmin = rmin; fRmax = rmax; - fDz = dz; + fDz = dz; fPhi1 = phiStart; - if (fPhi1 < 0) fPhi1 += 360.; + if (fPhi1 < 0) + fPhi1 += 360.; fPhi2 = phiEnd; - while (fPhi2<=fPhi1) fPhi2+=360.; - if (TGeoShape::IsSameWithinTolerance(fPhi1,fPhi2)) Fatal("SetTubsDimensions", "In shape %s invalid phi1=%g, phi2=%g\n", GetName(), fPhi1, fPhi2); + while (fPhi2 <= fPhi1) + fPhi2 += 360.; + if (TGeoShape::IsSameWithinTolerance(fPhi1, fPhi2)) + Fatal("SetTubsDimensions", "In shape %s invalid phi1=%g, phi2=%g\n", GetName(), fPhi1, fPhi2); InitTrigonometry(); } @@ -2229,7 +2339,7 @@ void TGeoTubeSeg::SetDimensions(Double_t *param) { Double_t rmin = param[0]; Double_t rmax = param[1]; - Double_t dz = param[2]; + Double_t dz = param[2]; Double_t phi1 = param[3]; Double_t phi2 = param[4]; SetTubsDimensions(rmin, rmax, dz, phi1, phi2); @@ -2242,29 +2352,29 @@ void TGeoTubeSeg::SetDimensions(Double_t *param) Bool_t TGeoTubeSeg::GetPointsOnSegments(Int_t npoints, Double_t *array) const { - if (npoints > (npoints/2)*2) { - Error("GetPointsOnSegments","Npoints must be even number"); + if (npoints > (npoints / 2) * 2) { + Error("GetPointsOnSegments", "Npoints must be even number"); return kFALSE; } - Int_t nc = (Int_t)TMath::Sqrt(0.5*npoints); - Double_t dphi = (fPhi2-fPhi1)*TMath::DegToRad()/(nc-1); + Int_t nc = (Int_t)TMath::Sqrt(0.5 * npoints); + Double_t dphi = (fPhi2 - fPhi1) * TMath::DegToRad() / (nc - 1); Double_t phi = 0; Double_t phi1 = fPhi1 * TMath::DegToRad(); - Int_t ntop = npoints/2 - nc*(nc-1); - Double_t dz = 2*fDz/(nc-1); + Int_t ntop = npoints / 2 - nc * (nc - 1); + Double_t dz = 2 * fDz / (nc - 1); Double_t z = 0; Int_t icrt = 0; Int_t nphi = nc; // loop z sections - for (Int_t i=0; iGetNsegments()+1; + if (phi2 < phi1) + phi2 += 360.; + n = gGeoManager->GetNsegments() + 1; - dphi = (phi2-phi1)/(n-1); - dz = fDz; + dphi = (phi2 - phi1) / (n - 1); + dz = fDz; if (points) { Int_t indx = 0; for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } @@ -2328,33 +2439,34 @@ void TGeoTubeSeg::SetPoints(Float_t *points) const Double_t phi, phi1, phi2, dphi; phi1 = fPhi1; phi2 = fPhi2; - if (phi2GetNsegments()+1; + if (phi2 < phi1) + phi2 += 360.; + n = gGeoManager->GetNsegments() + 1; - dphi = (phi2-phi1)/(n-1); - dz = fDz; + dphi = (phi2 - phi1) / (n - 1); + dz = fDz; if (points) { Int_t indx = 0; for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= dz; - points[indx] =-dz; + points[indx + 6 * n] = dz; + points[indx] = -dz; indx++; } } @@ -2365,10 +2477,10 @@ void TGeoTubeSeg::SetPoints(Float_t *points) const void TGeoTubeSeg::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - Int_t n = gGeoManager->GetNsegments()+1; - nvert = n*4; - nsegs = n*8; - npols = n*4 - 2; + Int_t n = gGeoManager->GetNsegments() + 1; + nvert = n * 4; + nsegs = n * 8; + npols = n * 4 - 2; } //////////////////////////////////////////////////////////////////////////////// @@ -2376,41 +2488,39 @@ void TGeoTubeSeg::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoTubeSeg::GetNmeshVertices() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t numPoints = n*4; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t numPoints = n * 4; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoTubeSeg::Sizeof3D() const -{ -} +void TGeoTubeSeg::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoTubeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoTubeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3DTubeSeg buffer; TGeoBBox::FillBuffer3D(buffer, reqSections, localFrame); if (reqSections & TBuffer3D::kShapeSpecific) { // These from TBuffer3DTube / TGeoTube - buffer.fRadiusInner = fRmin; - buffer.fRadiusOuter = fRmax; - buffer.fHalfLength = fDz; - buffer.fPhiMin = fPhi1; - buffer.fPhiMax = fPhi2; + buffer.fRadiusInner = fRmin; + buffer.fRadiusOuter = fRmax; + buffer.fHalfLength = fDz; + buffer.fPhiMin = fPhi1; + buffer.fPhiMax = fPhi2; buffer.SetSectionsValid(TBuffer3D::kShapeSpecific); } if (reqSections & TBuffer3D::kRawSizes) { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = 4*n; - Int_t nbSegs = 2*nbPnts; - Int_t nbPols = nbPnts-2; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 2 * nbPnts; + Int_t nbPols = nbPnts - 2; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -2433,7 +2543,8 @@ const TBuffer3D & TGeoTubeSeg::GetBuffer3D(Int_t reqSections, Bool_t localFrame) void TGeoTubeSeg::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; i-(1E-10)) || (fNhigh[2]<1E-10)) { + if ((fNlow[2] > -(1E-10)) || (fNhigh[2] < 1E-10)) { Error("ComputeBBox", "In shape %s wrong definition of cut planes", GetName()); return; } - Double_t xc=0, yc=0; - Double_t zmin=0, zmax=0; + Double_t xc = 0, yc = 0; + Double_t zmin = 0, zmax = 0; Double_t z1; Double_t z[8]; // check if nxy is in the phi range - Double_t phi_low = TMath::ATan2(fNlow[1], fNlow[0]) *TMath::RadToDeg(); - Double_t phi_hi = TMath::ATan2(fNhigh[1], fNhigh[0]) *TMath::RadToDeg(); + Double_t phi_low = TMath::ATan2(fNlow[1], fNlow[0]) * TMath::RadToDeg(); + Double_t phi_hi = TMath::ATan2(fNhigh[1], fNhigh[0]) * TMath::RadToDeg(); Bool_t in_range_low = kFALSE; Bool_t in_range_hi = kFALSE; Int_t i; - for (i=0; i<2; i++) { - if (phi_low<0) phi_low+=360.; - Double_t dphi = fPhi2 -fPhi1; - if (dphi < 0) dphi+=360.; - Double_t ddp = phi_low-fPhi1; - if (ddp<0) ddp += 360.; + for (i = 0; i < 2; i++) { + if (phi_low < 0) + phi_low += 360.; + Double_t dphi = fPhi2 - fPhi1; + if (dphi < 0) + dphi += 360.; + Double_t ddp = phi_low - fPhi1; + if (ddp < 0) + ddp += 360.; if (ddp <= dphi) { - xc = fRmin*TMath::Cos(phi_low*TMath::DegToRad()); - yc = fRmin*TMath::Sin(phi_low*TMath::DegToRad()); + xc = fRmin * TMath::Cos(phi_low * TMath::DegToRad()); + yc = fRmin * TMath::Sin(phi_low * TMath::DegToRad()); z1 = GetZcoord(xc, yc, -fDz); - xc = fRmax*TMath::Cos(phi_low*TMath::DegToRad()); - yc = fRmax*TMath::Sin(phi_low*TMath::DegToRad()); + xc = fRmax * TMath::Cos(phi_low * TMath::DegToRad()); + yc = fRmax * TMath::Sin(phi_low * TMath::DegToRad()); z1 = TMath::Min(z1, GetZcoord(xc, yc, -fDz)); if (in_range_low) zmin = TMath::Min(zmin, z1); @@ -2584,21 +2701,25 @@ void TGeoCtub::ComputeBBox() in_range_low = kTRUE; } phi_low += 180; - if (phi_low>360) phi_low-=360.; + if (phi_low > 360) + phi_low -= 360.; } - for (i=0; i<2; i++) { - if (phi_hi<0) phi_hi+=360.; - Double_t dphi = fPhi2 -fPhi1; - if (dphi < 0) dphi+=360.; - Double_t ddp = phi_hi-fPhi1; - if (ddp<0) ddp += 360.; + for (i = 0; i < 2; i++) { + if (phi_hi < 0) + phi_hi += 360.; + Double_t dphi = fPhi2 - fPhi1; + if (dphi < 0) + dphi += 360.; + Double_t ddp = phi_hi - fPhi1; + if (ddp < 0) + ddp += 360.; if (ddp <= dphi) { - xc = fRmin*TMath::Cos(phi_hi*TMath::DegToRad()); - yc = fRmin*TMath::Sin(phi_hi*TMath::DegToRad()); + xc = fRmin * TMath::Cos(phi_hi * TMath::DegToRad()); + yc = fRmin * TMath::Sin(phi_hi * TMath::DegToRad()); z1 = GetZcoord(xc, yc, fDz); - xc = fRmax*TMath::Cos(phi_hi*TMath::DegToRad()); - yc = fRmax*TMath::Sin(phi_hi*TMath::DegToRad()); + xc = fRmax * TMath::Cos(phi_hi * TMath::DegToRad()); + yc = fRmax * TMath::Sin(phi_hi * TMath::DegToRad()); z1 = TMath::Max(z1, GetZcoord(xc, yc, fDz)); if (in_range_hi) zmax = TMath::Max(zmax, z1); @@ -2607,27 +2728,27 @@ void TGeoCtub::ComputeBBox() in_range_hi = kTRUE; } phi_hi += 180; - if (phi_hi>360) phi_hi-=360.; + if (phi_hi > 360) + phi_hi -= 360.; } - - xc = fRmin*fC1; - yc = fRmin*fS1; + xc = fRmin * fC1; + yc = fRmin * fS1; z[0] = GetZcoord(xc, yc, -fDz); z[4] = GetZcoord(xc, yc, fDz); - xc = fRmin*fC2; - yc = fRmin*fS2; + xc = fRmin * fC2; + yc = fRmin * fS2; z[1] = GetZcoord(xc, yc, -fDz); z[5] = GetZcoord(xc, yc, fDz); - xc = fRmax*fC1; - yc = fRmax*fS1; + xc = fRmax * fC1; + yc = fRmax * fS1; z[2] = GetZcoord(xc, yc, -fDz); z[6] = GetZcoord(xc, yc, fDz); - xc = fRmax*fC2; - yc = fRmax*fS2; + xc = fRmax * fC2; + yc = fRmax * fS2; z[3] = GetZcoord(xc, yc, -fDz); z[7] = GetZcoord(xc, yc, fDz); @@ -2637,14 +2758,14 @@ void TGeoCtub::ComputeBBox() else zmin = z1; - z1 = z[TMath::LocMax(4, &z[4])+4]; + z1 = z[TMath::LocMax(4, &z[4]) + 4]; if (in_range_hi) zmax = TMath::Max(zmax, z1); else zmax = z1; - fDZ = 0.5*(zmax-zmin); - fOrigin[2] = 0.5*(zmax+zmin); + fDZ = 0.5 * (zmax - zmin); + fOrigin[2] = 0.5 * (zmax + zmin); } //////////////////////////////////////////////////////////////////////////////// @@ -2654,33 +2775,34 @@ void TGeoCtub::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ { Double_t saf[4]; Bool_t isseg = kTRUE; - if (TMath::Abs(fPhi2-fPhi1-360.)<1E-8) isseg=kFALSE; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + if (TMath::Abs(fPhi2 - fPhi1 - 360.) < 1E-8) + isseg = kFALSE; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - saf[0] = TMath::Abs(point[0]*fNlow[0] + point[1]*fNlow[1] + (fDz+point[2])*fNlow[2]); - saf[1] = TMath::Abs(point[0]*fNhigh[0] + point[1]*fNhigh[1] - (fDz-point[2])*fNhigh[2]); - saf[2] = (fRmin>1E-10)?TMath::Abs(r-fRmin):TGeoShape::Big(); - saf[3] = TMath::Abs(fRmax-r); - Int_t i = TMath::LocMin(4,saf); + saf[0] = TMath::Abs(point[0] * fNlow[0] + point[1] * fNlow[1] + (fDz + point[2]) * fNlow[2]); + saf[1] = TMath::Abs(point[0] * fNhigh[0] + point[1] * fNhigh[1] - (fDz - point[2]) * fNhigh[2]); + saf[2] = (fRmin > 1E-10) ? TMath::Abs(r - fRmin) : TGeoShape::Big(); + saf[3] = TMath::Abs(fRmax - r); + Int_t i = TMath::LocMin(4, saf); if (isseg) { - if (TGeoShape::IsCloseToPhi(saf[i], point,fC1,fS1,fC2,fS2)) { - TGeoShape::NormalPhi(point,dir,norm,fC1,fS1,fC2,fS2); + if (TGeoShape::IsCloseToPhi(saf[i], point, fC1, fS1, fC2, fS2)) { + TGeoShape::NormalPhi(point, dir, norm, fC1, fS1, fC2, fS2); return; } } - if (i==0) { - memcpy(norm, fNlow, 3*sizeof(Double_t)); - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (i == 0) { + memcpy(norm, fNlow, 3 * sizeof(Double_t)); + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; } return; } - if (i==1) { - memcpy(norm, fNhigh, 3*sizeof(Double_t)); - if (norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]<0) { + if (i == 1) { + memcpy(norm, fNhigh, 3 * sizeof(Double_t)); + if (norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -2692,7 +2814,7 @@ void TGeoCtub::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Double_t phi = TMath::ATan2(point[1], point[0]); norm[0] = TMath::Cos(phi); norm[1] = TMath::Sin(phi); - if (norm[0]*dir[0]+norm[1]*dir[1]<0) { + if (norm[0] * dir[0] + norm[1] * dir[1] < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; } @@ -2704,22 +2826,28 @@ void TGeoCtub::ComputeNormal(const Double_t *point, const Double_t *dir, Double_ Bool_t TGeoCtub::Contains(const Double_t *point) const { - Double_t zin = point[0]*fNlow[0]+point[1]*fNlow[1]+(point[2]+fDz)*fNlow[2]; - if (zin>0) return kFALSE; + Double_t zin = point[0] * fNlow[0] + point[1] * fNlow[1] + (point[2] + fDz) * fNlow[2]; + if (zin > 0) + return kFALSE; // check the higher cut plane - zin = point[0]*fNhigh[0]+point[1]*fNhigh[1]+(point[2]-fDz)*fNhigh[2]; - if (zin>0) return kFALSE; + zin = point[0] * fNhigh[0] + point[1] * fNhigh[1] + (point[2] - fDz) * fNhigh[2]; + if (zin > 0) + return kFALSE; // check radius - Double_t r2 = point[0]*point[0]+point[1]*point[1]; - if ((r2fRmax*fRmax)) return kFALSE; + Double_t r2 = point[0] * point[0] + point[1] * point[1]; + if ((r2 < fRmin * fRmin) || (r2 > fRmax * fRmax)) + return kFALSE; // check phi Double_t phi = TMath::ATan2(point[1], point[0]) * TMath::RadToDeg(); - if (phi < 0 ) phi+=360.; - Double_t dphi = fPhi2 -fPhi1; - Double_t ddp = phi-fPhi1; - if (ddp<0) ddp += 360.; -// if (ddp>360) ddp-=360; - if (ddp > dphi) return kFALSE; + if (phi < 0) + phi += 360.; + Double_t dphi = fPhi2 - fPhi1; + Double_t ddp = phi - fPhi1; + if (ddp < 0) + ddp += 360.; + // if (ddp>360) ddp-=360; + if (ddp > dphi) + return kFALSE; return kTRUE; } @@ -2732,16 +2860,16 @@ Double_t TGeoCtub::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const xhi = 0; Double_t dx = 0; switch (iaxis) { - case 1: - xlo = fRmin; - xhi = fRmax; - dx = xhi-xlo; - return dx; - case 2: - xlo = fPhi1; - xhi = fPhi2; - dx = xhi-xlo; - return dx; + case 1: + xlo = fRmin; + xhi = fRmax; + dx = xhi - xlo; + return dx; + case 2: + xlo = fPhi1; + xhi = fPhi2; + dx = xhi - xlo; + return dx; } return dx; } @@ -2753,144 +2881,163 @@ Double_t TGeoCtub::GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const Double_t TGeoCtub::GetZcoord(Double_t xc, Double_t yc, Double_t zc) const { Double_t newz = 0; - if (zc<0) newz = -fDz-(xc*fNlow[0]+yc*fNlow[1])/fNlow[2]; - else newz = fDz-(xc*fNhigh[0]+yc*fNhigh[1])/fNhigh[2]; + if (zc < 0) + newz = -fDz - (xc * fNlow[0] + yc * fNlow[1]) / fNlow[2]; + else + newz = fDz - (xc * fNhigh[0] + yc * fNhigh[1]) / fNhigh[2]; return newz; } //////////////////////////////////////////////////////////////////////////////// /// compute distance from outside point to surface of the cut tube -Double_t TGeoCtub::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoCtub::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) { + if (iact < 3 && safe) { *safe = Safety(point, kFALSE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (step<=*safe)) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (step <= *safe)) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); Double_t saf[2]; - saf[0] = point[0]*fNlow[0] + point[1]*fNlow[1] + (fDz+point[2])*fNlow[2]; - saf[1] = point[0]*fNhigh[0] + point[1]*fNhigh[1] + (point[2]-fDz)*fNhigh[2]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + saf[0] = point[0] * fNlow[0] + point[1] * fNlow[1] + (fDz + point[2]) * fNlow[2]; + saf[1] = point[0] * fNhigh[0] + point[1] * fNhigh[1] + (point[2] - fDz) * fNhigh[2]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); - Double_t cpsi=0; + Double_t cpsi = 0; Bool_t tub = kFALSE; - if (TMath::Abs(fPhi2-fPhi1-360.)<1E-8) tub = kTRUE; + if (TMath::Abs(fPhi2 - fPhi1 - 360.) < 1E-8) + tub = kTRUE; // find distance to shape Double_t r2; - Double_t calf = dir[0]*fNlow[0]+dir[1]*fNlow[1]+dir[2]*fNlow[2]; + Double_t calf = dir[0] * fNlow[0] + dir[1] * fNlow[1] + dir[2] * fNlow[2]; // check Z planes Double_t xi, yi, zi, s; - if (saf[0]>0) { - if (calf<0) { - s = -saf[0]/calf; - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if (((fRmin*fRmin)<=r2) && (r2<=(fRmax*fRmax))) { - if (tub) return s; - cpsi=(xi*fCm+yi*fSm)/TMath::Sqrt(r2); - if (cpsi>=fCdfi) return s; + if (saf[0] > 0) { + if (calf < 0) { + s = -saf[0] / calf; + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if (((fRmin * fRmin) <= r2) && (r2 <= (fRmax * fRmax))) { + if (tub) + return s; + cpsi = (xi * fCm + yi * fSm) / TMath::Sqrt(r2); + if (cpsi >= fCdfi) + return s; } } } - calf = dir[0]*fNhigh[0]+dir[1]*fNhigh[1]+dir[2]*fNhigh[2]; - if (saf[1]>0) { - if (calf<0) { - s = -saf[1]/calf; - xi = point[0]+s*dir[0]; - yi = point[1]+s*dir[1]; - r2=xi*xi+yi*yi; - if (((fRmin*fRmin)<=r2) && (r2<=(fRmax*fRmax))) { - if (tub) return s; - cpsi=(xi*fCm+yi*fSm)/TMath::Sqrt(r2); - if (cpsi>=fCdfi) return s; + calf = dir[0] * fNhigh[0] + dir[1] * fNhigh[1] + dir[2] * fNhigh[2]; + if (saf[1] > 0) { + if (calf < 0) { + s = -saf[1] / calf; + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + r2 = xi * xi + yi * yi; + if (((fRmin * fRmin) <= r2) && (r2 <= (fRmax * fRmax))) { + if (tub) + return s; + cpsi = (xi * fCm + yi * fSm) / TMath::Sqrt(r2); + if (cpsi >= fCdfi) + return s; } } } // check outer cyl. surface - Double_t nsq=dir[0]*dir[0]+dir[1]*dir[1]; - if (TMath::Abs(nsq)<1E-10) return TGeoShape::Big(); - Double_t rdotn=point[0]*dir[0]+point[1]*dir[1]; - Double_t b,d; + Double_t nsq = dir[0] * dir[0] + dir[1] * dir[1]; + if (TMath::Abs(nsq) < 1E-10) + return TGeoShape::Big(); + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1]; + Double_t b, d; // only r>fRmax coming inwards has to be considered - if (r>fRmax && rdotn<0) { + if (r > fRmax && rdotn < 0) { TGeoTube::DistToTube(rsq, nsq, rdotn, fRmax, b, d); - if (d>0) { - s=-b-d; - if (s>0) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - zi=point[2]+s*dir[2]; - if ((-xi*fNlow[0]-yi*fNlow[1]-(zi+fDz)*fNlow[2])>0) { - if ((-xi*fNhigh[0]-yi*fNhigh[1]+(fDz-zi)*fNhigh[2])>0) { - if (tub) return s; - cpsi=(xi*fCm+yi*fSm)/fRmax; - if (cpsi>=fCdfi) return s; + if (d > 0) { + s = -b - d; + if (s > 0) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + zi = point[2] + s * dir[2]; + if ((-xi * fNlow[0] - yi * fNlow[1] - (zi + fDz) * fNlow[2]) > 0) { + if ((-xi * fNhigh[0] - yi * fNhigh[1] + (fDz - zi) * fNhigh[2]) > 0) { + if (tub) + return s; + cpsi = (xi * fCm + yi * fSm) / fRmax; + if (cpsi >= fCdfi) + return s; } } } } } // check inner cylinder - Double_t snxt=TGeoShape::Big(); - if (fRmin>0) { + Double_t snxt = TGeoShape::Big(); + if (fRmin > 0) { TGeoTube::DistToTube(rsq, nsq, rdotn, fRmin, b, d); - if (d>0) { - s=-b+d; - if (s>0) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - zi=point[2]+s*dir[2]; - if ((-xi*fNlow[0]-yi*fNlow[1]-(zi+fDz)*fNlow[2])>0) { - if ((-xi*fNhigh[0]-yi*fNhigh[1]+(fDz-zi)*fNhigh[2])>0) { - if (tub) return s; - cpsi=(xi*fCm+yi*fSm)/fRmin; - if (cpsi>=fCdfi) snxt=s; + if (d > 0) { + s = -b + d; + if (s > 0) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + zi = point[2] + s * dir[2]; + if ((-xi * fNlow[0] - yi * fNlow[1] - (zi + fDz) * fNlow[2]) > 0) { + if ((-xi * fNhigh[0] - yi * fNhigh[1] + (fDz - zi) * fNhigh[2]) > 0) { + if (tub) + return s; + cpsi = (xi * fCm + yi * fSm) / fRmin; + if (cpsi >= fCdfi) + snxt = s; } } } } } // check phi planes - if (tub) return snxt; - Double_t un=dir[0]*fS1-dir[1]*fC1; - if (un<-TGeoShape::Tolerance()) { - s=(point[1]*fC1-point[0]*fS1)/un; - if (s>=0) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - zi=point[2]+s*dir[2]; - if ((-xi*fNlow[0]-yi*fNlow[1]-(zi+fDz)*fNlow[2])>0) { - if ((-xi*fNhigh[0]-yi*fNhigh[1]+(fDz-zi)*fNhigh[2])>0) { - r2=xi*xi+yi*yi; - if ((fRmin*fRmin<=r2) && (r2<=fRmax*fRmax)) { - if ((yi*fCm-xi*fSm)<=0) { - if (s= 0) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + zi = point[2] + s * dir[2]; + if ((-xi * fNlow[0] - yi * fNlow[1] - (zi + fDz) * fNlow[2]) > 0) { + if ((-xi * fNhigh[0] - yi * fNhigh[1] + (fDz - zi) * fNhigh[2]) > 0) { + r2 = xi * xi + yi * yi; + if ((fRmin * fRmin <= r2) && (r2 <= fRmax * fRmax)) { + if ((yi * fCm - xi * fSm) <= 0) { + if (s < snxt) + snxt = s; } } } } } } - un=dir[0]*fS2-dir[1]*fC2; - if (un>TGeoShape::Tolerance()) { - s=(point[1]*fC2-point[0]*fS2)/un; - if (s>=0) { - xi=point[0]+s*dir[0]; - yi=point[1]+s*dir[1]; - zi=point[2]+s*dir[2]; - if ((-xi*fNlow[0]-yi*fNlow[1]-(zi+fDz)*fNlow[2])>0) { - if ((-xi*fNhigh[0]-yi*fNhigh[1]+(fDz-zi)*fNhigh[2])>0) { - r2=xi*xi+yi*yi; - if ((fRmin*fRmin<=r2) && (r2<=fRmax*fRmax)) { - if ((yi*fCm-xi*fSm)>=0) { - if (s TGeoShape::Tolerance()) { + s = (point[1] * fC2 - point[0] * fS2) / un; + if (s >= 0) { + xi = point[0] + s * dir[0]; + yi = point[1] + s * dir[1]; + zi = point[2] + s * dir[2]; + if ((-xi * fNlow[0] - yi * fNlow[1] - (zi + fDz) * fNlow[2]) > 0) { + if ((-xi * fNhigh[0] - yi * fNhigh[1] + (fDz - zi) * fNhigh[2]) > 0) { + r2 = xi * xi + yi * yi; + if ((fRmin * fRmin <= r2) && (r2 <= fRmax * fRmax)) { + if ((yi * fCm - xi * fSm) >= 0) { + if (s < snxt) + snxt = s; } } } @@ -2903,59 +3050,70 @@ Double_t TGeoCtub::DistFromOutside(const Double_t *point, const Double_t *dir, I //////////////////////////////////////////////////////////////////////////////// /// compute distance from inside point to surface of the cut tube -Double_t TGeoCtub::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoCtub::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - if (iact<3 && safe) *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if ((iact==1) && (*safe>step)) return TGeoShape::Big(); - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + if (iact < 3 && safe) + *safe = Safety(point, kTRUE); + if (iact == 0) + return TGeoShape::Big(); + if ((iact == 1) && (*safe > step)) + return TGeoShape::Big(); + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Bool_t tub = kFALSE; - if (TMath::Abs(fPhi2-fPhi1-360.)<1E-8) tub = kTRUE; + if (TMath::Abs(fPhi2 - fPhi1 - 360.) < 1E-8) + tub = kTRUE; // compute distance to surface // Do Z Double_t sz = TGeoShape::Big(); Double_t saf[2]; - saf[0] = -point[0]*fNlow[0] - point[1]*fNlow[1] - (fDz+point[2])*fNlow[2]; - saf[1] = -point[0]*fNhigh[0] - point[1]*fNhigh[1] + (fDz-point[2])*fNhigh[2]; - Double_t calf = dir[0]*fNlow[0]+dir[1]*fNlow[1]+dir[2]*fNlow[2]; - if (calf>0) sz = saf[0]/calf; + saf[0] = -point[0] * fNlow[0] - point[1] * fNlow[1] - (fDz + point[2]) * fNlow[2]; + saf[1] = -point[0] * fNhigh[0] - point[1] * fNhigh[1] + (fDz - point[2]) * fNhigh[2]; + Double_t calf = dir[0] * fNlow[0] + dir[1] * fNlow[1] + dir[2] * fNlow[2]; + if (calf > 0) + sz = saf[0] / calf; - calf = dir[0]*fNhigh[0]+dir[1]*fNhigh[1]+dir[2]*fNhigh[2]; - if (calf>0) { - Double_t sz1 = saf[1]/calf; - if (sz1 0) { + Double_t sz1 = saf[1] / calf; + if (sz1 < sz) + sz = sz1; } // Do R - Double_t nsq=dir[0]*dir[0]+dir[1]*dir[1]; + Double_t nsq = dir[0] * dir[0] + dir[1] * dir[1]; // track parallel to Z - if (TMath::Abs(nsq)<1E-10) return sz; - Double_t rdotn=point[0]*dir[0]+point[1]*dir[1]; - Double_t sr=TGeoShape::Big(); + if (TMath::Abs(nsq) < 1E-10) + return sz; + Double_t rdotn = point[0] * dir[0] + point[1] * dir[1]; + Double_t sr = TGeoShape::Big(); Double_t b, d; Bool_t skip_outer = kFALSE; // inner cylinder - if (fRmin>1E-10) { + if (fRmin > 1E-10) { TGeoTube::DistToTube(rsq, nsq, rdotn, fRmin, b, d); - if (d>0) { - sr=-b-d; - if (sr>0) skip_outer = kTRUE; + if (d > 0) { + sr = -b - d; + if (sr > 0) + skip_outer = kTRUE; } } // outer cylinder if (!skip_outer) { TGeoTube::DistToTube(rsq, nsq, rdotn, fRmax, b, d); - if (d>0) { - sr=-b+d; - if (sr<0) sr=TGeoShape::Big(); + if (d > 0) { + sr = -b + d; + if (sr < 0) + sr = TGeoShape::Big(); } else { return 0.; // already outside } } // phi planes Double_t sfmin = TGeoShape::Big(); - if (!tub) sfmin=TGeoShape::DistToPhiMin(point, dir, fS1, fC1, fS2, fC2, fSm, fCm); - return TMath::Min(TMath::Min(sz,sr), sfmin); + if (!tub) + sfmin = TGeoShape::DistToPhiMin(point, dir, fS1, fC1, fS2, fC2, fSm, fCm); + return TMath::Min(TMath::Min(sz, sr), sfmin); } //////////////////////////////////////////////////////////////////////////////// @@ -2974,7 +3132,8 @@ TGeoVolume *TGeoCtub::Divide(TGeoVolume * /*voldiv*/, const char * /*divname*/, TGeoShape *TGeoCtub::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/) const { - if (!TestShapeBit(kGeoRunTimeShape)) return 0; + if (!TestShapeBit(kGeoRunTimeShape)) + return 0; if (!mother->TestShapeBit(kGeoTube)) { Error("GetMakeRuntimeShape", "Invalid mother for shape %s", GetName()); return 0; @@ -2983,14 +3142,14 @@ TGeoShape *TGeoCtub::GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix * /*mat*/ rmin = fRmin; rmax = fRmax; dz = fDz; - if (fDz<0) dz=((TGeoTube*)mother)->GetDz(); - if (fRmin<0) - rmin = ((TGeoTube*)mother)->GetRmin(); - if ((fRmax<0) || (fRmax<=fRmin)) - rmax = ((TGeoTube*)mother)->GetRmax(); + if (fDz < 0) + dz = ((TGeoTube *)mother)->GetDz(); + if (fRmin < 0) + rmin = ((TGeoTube *)mother)->GetRmin(); + if ((fRmax < 0) || (fRmax <= fRmin)) + rmax = ((TGeoTube *)mother)->GetRmax(); - return (new TGeoCtub(rmin, rmax, dz, fPhi1, fPhi2, fNlow[0], fNlow[1], fNlow[2], - fNhigh[0], fNhigh[1], fNhigh[2])); + return (new TGeoCtub(rmin, rmax, dz, fPhi1, fPhi2, fNlow[0], fNlow[1], fNlow[2], fNhigh[0], fNhigh[1], fNhigh[2])); } //////////////////////////////////////////////////////////////////////////////// @@ -3015,33 +3174,37 @@ void TGeoCtub::InspectShape() const Double_t TGeoCtub::Safety(const Double_t *point, Bool_t in) const { Double_t saf[4]; - Double_t rsq = point[0]*point[0]+point[1]*point[1]; + Double_t rsq = point[0] * point[0] + point[1] * point[1]; Double_t r = TMath::Sqrt(rsq); Bool_t isseg = kTRUE; - if (TMath::Abs(fPhi2-fPhi1-360.)<1E-8) isseg=kFALSE; + if (TMath::Abs(fPhi2 - fPhi1 - 360.) < 1E-8) + isseg = kFALSE; - saf[0] = -point[0]*fNlow[0] - point[1]*fNlow[1] - (fDz+point[2])*fNlow[2]; - saf[1] = -point[0]*fNhigh[0] - point[1]*fNhigh[1] + (fDz-point[2])*fNhigh[2]; - saf[2] = (fRmin<1E-10 && !isseg)?TGeoShape::Big():(r-fRmin); - saf[3] = fRmax-r; + saf[0] = -point[0] * fNlow[0] - point[1] * fNlow[1] - (fDz + point[2]) * fNlow[2]; + saf[1] = -point[0] * fNhigh[0] - point[1] * fNhigh[1] + (fDz - point[2]) * fNhigh[2]; + saf[2] = (fRmin < 1E-10 && !isseg) ? TGeoShape::Big() : (r - fRmin); + saf[3] = fRmax - r; Double_t safphi = TGeoShape::Big(); - if (isseg) safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); + if (isseg) + safphi = TGeoShape::SafetyPhi(point, in, fPhi1, fPhi2); if (in) { - Double_t safe = saf[TMath::LocMin(4,saf)]; + Double_t safe = saf[TMath::LocMin(4, saf)]; return TMath::Min(safe, safphi); } - for (Int_t i=0; i<4; i++) saf[i]=-saf[i]; - Double_t safe = saf[TMath::LocMax(4,saf)]; - if (isseg) return TMath::Max(safe, safphi); + for (Int_t i = 0; i < 4; i++) + saf[i] = -saf[i]; + Double_t safe = saf[TMath::LocMax(4, saf)]; + if (isseg) + return TMath::Max(safe, safphi); return safe; } //////////////////////////////////////////////////////////////////////////////// /// set dimensions of a cut tube -void TGeoCtub::SetCtubDimensions(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, - Double_t lx, Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz) +void TGeoCtub::SetCtubDimensions(Double_t rmin, Double_t rmax, Double_t dz, Double_t phi1, Double_t phi2, Double_t lx, + Double_t ly, Double_t lz, Double_t tx, Double_t ty, Double_t tz) { SetTubsDimensions(rmin, rmax, dz, phi1, phi2); fNlow[0] = lx; @@ -3058,7 +3221,8 @@ void TGeoCtub::SetCtubDimensions(Double_t rmin, Double_t rmax, Double_t dz, Doub void TGeoCtub::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " rmin = " << fRmin << ";" << std::endl; out << " rmax = " << fRmax << ";" << std::endl; @@ -3071,7 +3235,8 @@ void TGeoCtub::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) out << " tx = " << fNhigh[0] << ";" << std::endl; out << " ty = " << fNhigh[1] << ";" << std::endl; out << " tz = " << fNhigh[2] << ";" << std::endl; - out << " TGeoShape *" << GetPointerName() << " = new TGeoCtub(\"" << GetName() << "\",rmin,rmax,dz,phi1,phi2,lx,ly,lz,tx,ty,tz);" << std::endl; + out << " TGeoShape *" << GetPointerName() << " = new TGeoCtub(\"" << GetName() + << "\",rmin,rmax,dz,phi1,phi2,lx,ly,lz,tx,ty,tz);" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -3080,8 +3245,8 @@ void TGeoCtub::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) void TGeoCtub::SetDimensions(Double_t *param) { - SetCtubDimensions(param[0], param[1], param[2], param[3], param[4], param[5], - param[6], param[7], param[8], param[9], param[10]); + SetCtubDimensions(param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], param[8], param[9], + param[10]); ComputeBBox(); } @@ -3105,33 +3270,34 @@ void TGeoCtub::SetPoints(Double_t *points) const Double_t phi, phi1, phi2, dphi; phi1 = fPhi1; phi2 = fPhi2; - if (phi2GetNsegments()+1; + if (phi2 < phi1) + phi2 += 360.; + n = gGeoManager->GetNsegments() + 1; - dphi = (phi2-phi1)/(n-1); - dz = fDz; + dphi = (phi2 - phi1) / (n - 1); + dz = fDz; if (points) { Int_t indx = 0; for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = GetZcoord(points[indx-2], points[indx-1], dz); - points[indx] = GetZcoord(points[indx-2], points[indx-1], -dz); + points[indx + 6 * n] = GetZcoord(points[indx - 2], points[indx - 1], dz); + points[indx] = GetZcoord(points[indx - 2], points[indx - 1], -dz); indx++; } for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= GetZcoord(points[indx-2], points[indx-1], dz); - points[indx] = GetZcoord(points[indx-2], points[indx-1], -dz); + points[indx + 6 * n] = GetZcoord(points[indx - 2], points[indx - 1], dz); + points[indx] = GetZcoord(points[indx - 2], points[indx - 1], -dz); indx++; } } @@ -3147,33 +3313,34 @@ void TGeoCtub::SetPoints(Float_t *points) const Double_t phi, phi1, phi2, dphi; phi1 = fPhi1; phi2 = fPhi2; - if (phi2GetNsegments()+1; + if (phi2 < phi1) + phi2 += 360.; + n = gGeoManager->GetNsegments() + 1; - dphi = (phi2-phi1)/(n-1); - dz = fDz; + dphi = (phi2 - phi1) / (n - 1); + dz = fDz; if (points) { Int_t indx = 0; for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmin * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmin * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmin * TMath::Sin(phi); indx++; - points[indx+6*n] = GetZcoord(points[indx-2], points[indx-1], dz); - points[indx] = GetZcoord(points[indx-2], points[indx-1], -dz); + points[indx + 6 * n] = GetZcoord(points[indx - 2], points[indx - 1], dz); + points[indx] = GetZcoord(points[indx - 2], points[indx - 1], -dz); indx++; } for (j = 0; j < n; j++) { - phi = (phi1+j*dphi)*TMath::DegToRad(); - points[indx+6*n] = points[indx] = fRmax * TMath::Cos(phi); + phi = (phi1 + j * dphi) * TMath::DegToRad(); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Cos(phi); indx++; - points[indx+6*n] = points[indx] = fRmax * TMath::Sin(phi); + points[indx + 6 * n] = points[indx] = fRmax * TMath::Sin(phi); indx++; - points[indx+6*n]= GetZcoord(points[indx-2], points[indx-1], dz); - points[indx] = GetZcoord(points[indx-2], points[indx-1], -dz); + points[indx + 6 * n] = GetZcoord(points[indx - 2], points[indx - 1], dz); + points[indx] = GetZcoord(points[indx - 2], points[indx - 1], -dz); indx++; } } @@ -3184,7 +3351,7 @@ void TGeoCtub::SetPoints(Float_t *points) const void TGeoCtub::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { - TGeoTubeSeg::GetMeshNumbers(nvert,nsegs,npols); + TGeoTubeSeg::GetMeshNumbers(nvert, nsegs, npols); } //////////////////////////////////////////////////////////////////////////////// @@ -3192,15 +3359,15 @@ void TGeoCtub::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoCtub::GetNmeshVertices() const { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t numPoints = n*4; + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t numPoints = n * 4; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoCtub::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoCtub::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3DCutTube buffer; @@ -3208,24 +3375,24 @@ const TBuffer3D & TGeoCtub::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co if (reqSections & TBuffer3D::kShapeSpecific) { // These from TBuffer3DCutTube / TGeoCtub - buffer.fRadiusInner = fRmin; - buffer.fRadiusOuter = fRmax; - buffer.fHalfLength = fDz; - buffer.fPhiMin = fPhi1; - buffer.fPhiMax = fPhi2; + buffer.fRadiusInner = fRmin; + buffer.fRadiusOuter = fRmax; + buffer.fHalfLength = fDz; + buffer.fPhiMin = fPhi1; + buffer.fPhiMax = fPhi2; - for (UInt_t i = 0; i < 3; i++ ) { + for (UInt_t i = 0; i < 3; i++) { buffer.fLowPlaneNorm[i] = fNlow[i]; buffer.fHighPlaneNorm[i] = fNhigh[i]; } buffer.SetSectionsValid(TBuffer3D::kShapeSpecific); } if (reqSections & TBuffer3D::kRawSizes) { - Int_t n = gGeoManager->GetNsegments()+1; - Int_t nbPnts = 4*n; - Int_t nbSegs = 2*nbPnts; - Int_t nbPols = nbPnts-2; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*nbPols)) { + Int_t n = gGeoManager->GetNsegments() + 1; + Int_t nbPnts = 4 * n; + Int_t nbSegs = 2 * nbPnts; + Int_t nbPols = nbPnts - 2; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * nbPols)) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -3248,7 +3415,8 @@ const TBuffer3D & TGeoCtub::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoCtub::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iSetName("dummy"); TGeoMaterial *dummyMaterial = new TGeoMaterial(); @@ -423,16 +424,20 @@ void TGeoVolume::CreateDummyMedium() void TGeoVolume::ClearThreadData() const { - if (fFinder) fFinder->ClearThreadData(); - if (fShape) fShape->ClearThreadData(); + if (fFinder) + fFinder->ClearThreadData(); + if (fShape) + fShape->ClearThreadData(); } //////////////////////////////////////////////////////////////////////////////// void TGeoVolume::CreateThreadData(Int_t nthreads) { - if (fFinder) fFinder->CreateThreadData(nthreads); - if (fShape) fShape->CreateThreadData(nthreads); + if (fFinder) + fFinder->CreateThreadData(nthreads); + if (fShape) + fShape->CreateThreadData(nthreads); } //////////////////////////////////////////////////////////////////////////////// @@ -447,31 +452,31 @@ TGeoMedium *TGeoVolume::DummyMedium() TGeoVolume::TGeoVolume() { - fNodes = 0; - fShape = 0; - fMedium = 0; - fFinder = 0; - fVoxels = 0; + fNodes = 0; + fShape = 0; + fMedium = 0; + fFinder = 0; + fVoxels = 0; fGeoManager = gGeoManager; - fField = 0; - fOption = ""; - fNumber = 0; - fNtotal = 0; + fField = 0; + fOption = ""; + fNumber = 0; + fNtotal = 0; fRefCount = 0; fUserExtension = 0; fFWExtension = 0; + fTransparency = -1; TObject::ResetBit(kVolumeImportNodes); } //////////////////////////////////////////////////////////////////////////////// /// default constructor -TGeoVolume::TGeoVolume(const char *name, const TGeoShape *shape, const TGeoMedium *med) - :TNamed(name, "") +TGeoVolume::TGeoVolume(const char *name, const TGeoShape *shape, const TGeoMedium *med) : TNamed(name, "") { fName = fName.Strip(); - fNodes = 0; - fShape = (TGeoShape*)shape; + fNodes = 0; + fShape = (TGeoShape *)shape; if (fShape) { if (fShape->TestShapeBit(TGeoShape::kGeoBad)) { Warning("Ctor", "volume %s has invalid shape", name); @@ -480,19 +485,22 @@ TGeoVolume::TGeoVolume(const char *name, const TGeoShape *shape, const TGeoMediu Fatal("ctor", "Shape of volume %s invalid. Aborting!", fName.Data()); } } - fMedium = (TGeoMedium*)med; - if (fMedium && fMedium->GetMaterial()) fMedium->GetMaterial()->SetUsed(); - fFinder = 0; - fVoxels = 0; + fMedium = (TGeoMedium *)med; + if (fMedium && fMedium->GetMaterial()) + fMedium->GetMaterial()->SetUsed(); + fFinder = 0; + fVoxels = 0; fGeoManager = gGeoManager; - fField = 0; - fOption = ""; - fNumber = 0; - fNtotal = 0; + fField = 0; + fOption = ""; + fNumber = 0; + fNtotal = 0; fRefCount = 0; fUserExtension = 0; fFWExtension = 0; - if (fGeoManager) fNumber = fGeoManager->AddVolume(this); + fTransparency = -1; + if (fGeoManager) + fNumber = fGeoManager->AddVolume(this); TObject::ResetBit(kVolumeImportNodes); } @@ -507,10 +515,18 @@ TGeoVolume::~TGeoVolume() } delete fNodes; } - if (fFinder && !TObject::TestBit(kVolumeImportNodes | kVolumeClone) ) delete fFinder; - if (fVoxels) delete fVoxels; - if (fUserExtension) {fUserExtension->Release(); fUserExtension=0;} - if (fFWExtension) {fFWExtension->Release(); fFWExtension=0;} + if (fFinder && !TObject::TestBit(kVolumeImportNodes | kVolumeClone)) + delete fFinder; + if (fVoxels) + delete fVoxels; + if (fUserExtension) { + fUserExtension->Release(); + fUserExtension = 0; + } + if (fFWExtension) { + fFWExtension->Release(); + fFWExtension = 0; + } } //////////////////////////////////////////////////////////////////////////////// @@ -518,31 +534,33 @@ TGeoVolume::~TGeoVolume() void TGeoVolume::Browse(TBrowser *b) { - if (!b) return; + if (!b) + return; -// if (!GetNdaughters()) b->Add(this, GetName(), IsVisible()); + // if (!GetNdaughters()) b->Add(this, GetName(), IsVisible()); TGeoVolume *daughter; TString title; - for (Int_t i=0; iGetVolume(); - if(daughter->GetTitle()[0]) { - if (daughter->IsAssembly()) title.TString::Format("Assembly with %d daughter(s)", - daughter->GetNdaughters()); + if (daughter->GetTitle()[0]) { + if (daughter->IsAssembly()) + title.TString::Format("Assembly with %d daughter(s)", daughter->GetNdaughters()); else if (daughter->GetFinder()) { TString s1 = daughter->GetFinder()->ClassName(); - s1.ReplaceAll("TGeoPattern",""); - title.TString::Format("Volume having %s shape divided in %d %s slices", - daughter->GetShape()->ClassName(),daughter->GetNdaughters(), s1.Data()); + s1.ReplaceAll("TGeoPattern", ""); + title.TString::Format("Volume having %s shape divided in %d %s slices", daughter->GetShape()->ClassName(), + daughter->GetNdaughters(), s1.Data()); - } else title.TString::Format("Volume with %s shape having %d daughter(s)", - daughter->GetShape()->ClassName(),daughter->GetNdaughters()); + } else + title.TString::Format("Volume with %s shape having %d daughter(s)", daughter->GetShape()->ClassName(), + daughter->GetNdaughters()); daughter->SetTitle(title.Data()); } b->Add(daughter, daughter->GetName(), daughter->IsVisible()); -// if (IsVisDaughters()) -// b->AddCheckBox(daughter, daughter->IsVisible()); -// else -// b->AddCheckBox(daughter, kFALSE); + // if (IsVisDaughters()) + // b->AddCheckBox(daughter, daughter->IsVisible()); + // else + // b->AddCheckBox(daughter, kFALSE); } } @@ -552,11 +570,13 @@ void TGeoVolume::Browse(TBrowser *b) Double_t TGeoVolume::Capacity() const { - if (!IsAssembly()) return fShape->Capacity(); + if (!IsAssembly()) + return fShape->Capacity(); Double_t capacity = 0.0; Int_t nd = GetNdaughters(); Int_t i; - for (i=0; iGetVolume()->Capacity(); + for (i = 0; i < nd; i++) + capacity += GetNode(i)->GetVolume()->Capacity(); return capacity; } @@ -568,8 +588,10 @@ Double_t TGeoVolume::Capacity() const void TGeoVolume::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const { TGeoVolume *old_vol = fGeoManager->GetTopVolume(); - if (old_vol!=this) fGeoManager->SetTopVolume((TGeoVolume*)this); - else old_vol=0; + if (old_vol != this) + fGeoManager->SetTopVolume((TGeoVolume *)this); + else + old_vol = 0; fGeoManager->GetTopVolume()->Draw(); TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); painter->CheckGeometry(nrays, startx, starty, startz); @@ -588,32 +610,38 @@ void TGeoVolume::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Do void TGeoVolume::CheckOverlaps(Double_t ovlp, Option_t *option) const { - if (!GetNdaughters() || fFinder) return; + if (!GetNdaughters() || fFinder) + return; Bool_t sampling = kFALSE; TString opt(option); opt.ToLower(); - if (opt.Contains("s")) sampling = kTRUE; + if (opt.Contains("s")) + sampling = kTRUE; TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); - if (!sampling) fGeoManager->SetNsegments(80); + if (!sampling) + fGeoManager->SetNsegments(80); if (!fGeoManager->IsCheckingOverlaps()) { fGeoManager->ClearOverlaps(); -// Info("CheckOverlaps", "=== Checking overlaps for volume %s ===\n", GetName()); + // Info("CheckOverlaps", "=== Checking overlaps for volume %s ===\n", GetName()); } painter->CheckOverlaps(this, ovlp, option); -// if (sampling) return; + // if (sampling) return; if (!fGeoManager->IsCheckingOverlaps()) { fGeoManager->SortOverlaps(); TObjArray *overlaps = fGeoManager->GetListOfOverlaps(); Int_t novlps = overlaps->GetEntriesFast(); TNamed *obj; TString name; - for (Int_t i=0; iAt(i); - if (novlps<1000) name = TString::Format("ov%03d", i); - else name = TString::Format("ov%06d", i); + for (Int_t i = 0; i < novlps; i++) { + obj = (TNamed *)overlaps->At(i); + if (novlps < 1000) + name = TString::Format("ov%03d", i); + else + name = TString::Format("ov%06d", i); obj->SetName(name); } - if (novlps) Info("CheckOverlaps", "Number of illegal overlaps/extrusions for volume %s: %d\n", GetName(), novlps); + if (novlps) + Info("CheckOverlaps", "Number of illegal overlaps/extrusions for volume %s: %d\n", GetName(), novlps); } } @@ -622,7 +650,7 @@ void TGeoVolume::CheckOverlaps(Double_t ovlp, Option_t *option) const void TGeoVolume::CheckShape(Int_t testNo, Int_t nsamples, Option_t *option) { - fShape->CheckShape(testNo,nsamples,option); + fShape->CheckShape(testNo, nsamples, option); } //////////////////////////////////////////////////////////////////////////////// @@ -652,23 +680,24 @@ void TGeoVolume::CheckShapes() InspectShape(); return; } - if (!fNodes) return; - Int_t nd=fNodes->GetEntriesFast(); + if (!fNodes) + return; + Int_t nd = fNodes->GetEntriesFast(); TGeoNode *node = 0; TGeoNode *new_node; const TGeoShape *shape = 0; TGeoVolume *old_vol; - for (Int_t i=0; iAt(i); + for (Int_t i = 0; i < nd; i++) { + node = (TGeoNode *)fNodes->At(i); // check if node has name - if (!node->GetName()[0]) printf("Daughter %i of volume %s - NO NAME!!!\n", - i, GetName()); + if (!node->GetName()[0]) + printf("Daughter %i of volume %s - NO NAME!!!\n", i, GetName()); old_vol = node->GetVolume(); shape = old_vol->GetShape(); if (shape->IsRunTimeShape()) { -// printf(" Node %s/%s has shape with negative parameters. \n", -// GetName(), node->GetName()); -// old_vol->InspectShape(); + // printf(" Node %s/%s has shape with negative parameters. \n", + // GetName(), node->GetName()); + // old_vol->InspectShape(); // make a copy of the node new_node = node->MakeCopyNode(); if (!new_node) { @@ -677,17 +706,16 @@ void TGeoVolume::CheckShapes() } TGeoShape *new_shape = shape->GetMakeRuntimeShape(fShape, node->GetMatrix()); if (!new_shape) { - Error("CheckShapes","cannot resolve runtime shape for volume %s/%s\n", - GetName(),old_vol->GetName()); + Error("CheckShapes", "cannot resolve runtime shape for volume %s/%s\n", GetName(), old_vol->GetName()); continue; } TGeoVolume *new_volume = old_vol->MakeCopyVolume(new_shape); -// printf(" new volume %s shape params :\n", new_volume->GetName()); -// new_volume->InspectShape(); + // printf(" new volume %s shape params :\n", new_volume->GetName()); + // new_volume->InspectShape(); new_node->SetVolume(new_volume); // decouple the old node and put the new one instead fNodes->AddAt(new_node, i); -// new_volume->CheckShapes(); + // new_volume->CheckShapes(); } } } @@ -704,44 +732,44 @@ Int_t TGeoVolume::CountNodes(Int_t nlevels, Int_t option) static Int_t maxlevel = 0; static Int_t nlev = 0; - if (option<0 || option>3) option = 0; + if (option < 0 || option > 3) + option = 0; Int_t visopt = 0; Int_t nd = GetNdaughters(); - Bool_t last = (!nlevels || !nd)?kTRUE:kFALSE; + Bool_t last = (!nlevels || !nd) ? kTRUE : kFALSE; switch (option) { - case 0: - if (fNtotal) return fNtotal; - case 1: - fNtotal = 1; - break; - case 2: - visopt = fGeoManager->GetVisOption(); - if (!IsVisDaughters()) last = kTRUE; - switch (visopt) { - case TVirtualGeoPainter::kGeoVisDefault: - fNtotal = (IsVisible())?1:0; - break; - case TVirtualGeoPainter::kGeoVisLeaves: - fNtotal = (IsVisible() && last)?1:0; - } - if (!IsVisibleDaughters()) return fNtotal; - break; - case 3: - return maxlevel; + case 0: + if (fNtotal) + return fNtotal; + case 1: fNtotal = 1; break; + case 2: + visopt = fGeoManager->GetVisOption(); + if (!IsVisDaughters()) + last = kTRUE; + switch (visopt) { + case TVirtualGeoPainter::kGeoVisDefault: fNtotal = (IsVisible()) ? 1 : 0; break; + case TVirtualGeoPainter::kGeoVisLeaves: fNtotal = (IsVisible() && last) ? 1 : 0; + } + if (!IsVisibleDaughters()) + return fNtotal; + break; + case 3: return maxlevel; } - if (last) return fNtotal; + if (last) + return fNtotal; if (gGeoManager->GetTopVolume() == this) { - maxlevel=0; + maxlevel = 0; nlev = 0; } - if (nlev>maxlevel) maxlevel = nlev; + if (nlev > maxlevel) + maxlevel = nlev; TGeoNode *node; TGeoVolume *vol; nlev++; - for (Int_t i=0; iGetVolume(); - fNtotal += vol->CountNodes(nlevels-1, option); + fNtotal += vol->CountNodes(nlevels - 1, option); } nlev--; return fNtotal; @@ -752,9 +780,12 @@ Int_t TGeoVolume::CountNodes(Int_t nlevels, Int_t option) Bool_t TGeoVolume::IsAllInvisible() const { - if (IsVisible()) return kFALSE; + if (IsVisible()) + return kFALSE; Int_t nd = GetNdaughters(); - for (Int_t i=0; iGetVolume()->IsVisible()) return kFALSE; + for (Int_t i = 0; i < nd; i++) + if (GetNode(i)->GetVolume()->IsVisible()) + return kFALSE; return kTRUE; } @@ -765,19 +796,19 @@ void TGeoVolume::InvisibleAll(Bool_t flag) { SetAttVisibility(!flag); Int_t nd = GetNdaughters(); - TObjArray *list = new TObjArray(nd+1); + TObjArray *list = new TObjArray(nd + 1); list->Add(this); TGeoVolume *vol; - for (Int_t i=0; iGetVolume(); vol->SetAttVisibility(!flag); list->Add(vol); } TIter next(gROOT->GetListOfBrowsers()); TBrowser *browser = 0; - while ((browser=(TBrowser*)next())) { - for (Int_t i=0; iAt(i); + while ((browser = (TBrowser *)next())) { + for (Int_t i = 0; i < nd + 1; i++) { + vol = (TGeoVolume *)list->At(i); browser->CheckObjectItem(vol, !flag); } browser->Refresh(); @@ -799,10 +830,14 @@ Bool_t TGeoVolume::IsFolder() const Bool_t TGeoVolume::IsStyleDefault() const { - if (!IsVisible()) return kFALSE; - if (GetLineColor() != gStyle->GetLineColor()) return kFALSE; - if (GetLineStyle() != gStyle->GetLineStyle()) return kFALSE; - if (GetLineWidth() != gStyle->GetLineWidth()) return kFALSE; + if (!IsVisible()) + return kFALSE; + if (GetLineColor() != gStyle->GetLineColor()) + return kFALSE; + if (GetLineStyle() != gStyle->GetLineStyle()) + return kFALSE; + if (GetLineWidth() != gStyle->GetLineWidth()) + return kFALSE; return kTRUE; } @@ -811,7 +846,8 @@ Bool_t TGeoVolume::IsStyleDefault() const Bool_t TGeoVolume::IsTopVolume() const { - if (fGeoManager->GetTopVolume() == this) return kTRUE; + if (fGeoManager->GetTopVolume() == this) + return kTRUE; return kFALSE; } @@ -836,13 +872,15 @@ void TGeoVolume::InspectMaterial() const TGeoVolume *TGeoVolume::Import(const char *filename, const char *name, Option_t * /*option*/) { - if (!gGeoManager) gGeoManager = new TGeoManager("geometry",""); - if (!filename) return 0; + if (!gGeoManager) + gGeoManager = new TGeoManager("geometry", ""); + if (!filename) + return 0; TGeoVolume *volume = 0; - if (strstr(filename,".gdml")) { - // import from a gdml file + if (strstr(filename, ".gdml")) { + // import from a gdml file } else { - // import from a root file + // import from a root file TDirectory::TContext ctxt; TFile *f = TFile::Open(filename); if (!f || f->IsZombie()) { @@ -850,19 +888,21 @@ TGeoVolume *TGeoVolume::Import(const char *filename, const char *name, Option_t return 0; } if (name && name[0]) { - volume = (TGeoVolume*)f->Get(name); + volume = (TGeoVolume *)f->Get(name); } else { TIter next(f->GetListOfKeys()); TKey *key; - while ((key = (TKey*)next())) { - if (strcmp(key->GetClassName(),"TGeoVolume") != 0) continue; - volume = (TGeoVolume*)key->ReadObj(); + while ((key = (TKey *)next())) { + if (strcmp(key->GetClassName(), "TGeoVolume") != 0) + continue; + volume = (TGeoVolume *)key->ReadObj(); break; } } delete f; } - if (!volume) return NULL; + if (!volume) + return NULL; volume->RegisterYourself(); return volume; } @@ -888,28 +928,30 @@ Int_t TGeoVolume::Export(const char *filename, const char *name, Option_t *optio { TString sfile(filename); if (sfile.Contains(".C")) { - //Save volume as a C++ script - Info("Export","Exporting volume %s as C++ code", GetName()); + // Save volume as a C++ script + Info("Export", "Exporting volume %s as C++ code", GetName()); SaveAs(filename, ""); return 1; } if (sfile.Contains(".gdml")) { - //Save geometry as a gdml file - Info("Export","Exporting %s as gdml code - not implemented yet", GetName()); + // Save geometry as a gdml file + Info("Export", "Exporting %s as gdml code - not implemented yet", GetName()); return 0; } if (sfile.Contains(".root") || sfile.Contains(".xml")) { - //Save volume in a root file - Info("Export","Exporting %s as root file.", GetName()); + // Save volume in a root file + Info("Export", "Exporting %s as root file.", GetName()); TString opt(option); - if (!opt.Length()) opt = "recreate"; - TFile *f = TFile::Open(filename,opt.Data()); + if (!opt.Length()) + opt = "recreate"; + TFile *f = TFile::Open(filename, opt.Data()); if (!f || f->IsZombie()) { - Error("Export","Cannot open file"); + Error("Export", "Cannot open file"); return 0; } TString keyname(name); - if (keyname.IsNull()) keyname = GetName(); + if (keyname.IsNull()) + keyname = GetName(); Int_t nbytes = Write(keyname); delete f; return nbytes; @@ -922,7 +964,8 @@ Int_t TGeoVolume::Export(const char *filename, const char *name, Option_t *optio void TGeoVolume::cd(Int_t inode) const { - if (fFinder) fFinder->cd(inode-fFinder->GetDivIndex()); + if (fFinder) + fFinder->cd(inode - fFinder->GetDivIndex()); } //////////////////////////////////////////////////////////////////////////////// @@ -932,8 +975,10 @@ void TGeoVolume::cd(Int_t inode) const TGeoNode *TGeoVolume::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t * /*option*/) { TGeoMatrix *matrix = mat; - if (matrix==0) matrix = gGeoIdentity; - else matrix->RegisterYourself(); + if (matrix == 0) + matrix = gGeoIdentity; + else + matrix->RegisterYourself(); if (!vol) { Error("AddNode", "Volume is NULL"); return 0; @@ -943,7 +988,8 @@ TGeoNode *TGeoVolume::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, O printf("### invalid volume was : %s\n", vol->GetName()); return 0; } - if (!fNodes) fNodes = new TObjArray(); + if (!fNodes) + fNodes = new TObjArray(); if (fFinder) { // volume already divided. @@ -956,8 +1002,8 @@ TGeoNode *TGeoVolume::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, O node->SetMotherVolume(this); fNodes->Add(node); TString name = TString::Format("%s_%d", vol->GetName(), copy_no); -// if (fNodes->FindObject(name)) -// Warning("AddNode", "Volume %s : added node %s with same name", GetName(), name.Data()); + // if (fNodes->FindObject(name)) + // Warning("AddNode", "Volume %s : added node %s with same name", GetName(), name.Data()); node->SetName(name); node->SetNumber(copy_no); fRefCount++; @@ -980,13 +1026,14 @@ void TGeoVolume::AddNodeOffset(TGeoVolume *vol, Int_t copy_no, Double_t offset, printf("### invalid volume was : %s\n", vol->GetName()); return; } - if (!fNodes) fNodes = new TObjArray(); + if (!fNodes) + fNodes = new TObjArray(); TGeoNode *node = new TGeoNodeOffset(vol, copy_no, offset); node->SetMotherVolume(this); fNodes->Add(node); - TString name = TString::Format("%s_%d", vol->GetName(), copy_no+1); + TString name = TString::Format("%s_%d", vol->GetName(), copy_no + 1); node->SetName(name); - node->SetNumber(copy_no+1); + node->SetNumber(copy_no + 1); vol->Grab(); } @@ -1006,14 +1053,19 @@ void TGeoVolume::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, return; } if (vol->IsAssembly()) { - Warning("AddNodeOverlap", "Declaring assembly %s as possibly overlapping inside %s not allowed. Using AddNode instead !",vol->GetName(),GetName()); + Warning("AddNodeOverlap", + "Declaring assembly %s as possibly overlapping inside %s not allowed. Using AddNode instead !", + vol->GetName(), GetName()); AddNode(vol, copy_no, mat, option); return; } TGeoMatrix *matrix = mat; - if (matrix==0) matrix = gGeoIdentity; - else matrix->RegisterYourself(); - if (!fNodes) fNodes = new TObjArray(); + if (matrix == 0) + matrix = gGeoIdentity; + else + matrix->RegisterYourself(); + if (!fNodes) + fNodes = new TObjArray(); if (fFinder) { // volume already divided. @@ -1048,71 +1100,75 @@ void TGeoVolume::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, /// in full range (same effect as NDIV<=0) (GSDVS, GSDVT in G3) /// - SX - same as DVS, but from START position. (GSDVS2, GSDVT2 in G3) -TGeoVolume *TGeoVolume::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed, Option_t *option) +TGeoVolume *TGeoVolume::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed, + Option_t *option) { if (fFinder) { - // volume already divided. - Fatal("Divide","volume %s already divided", GetName()); + // volume already divided. + Fatal("Divide", "volume %s already divided", GetName()); return 0; } TString opt(option); opt.ToLower(); TString stype = fShape->ClassName(); - if (!fNodes) fNodes = new TObjArray(); + if (!fNodes) + fNodes = new TObjArray(); Double_t xlo, xhi, range; range = fShape->GetAxisRange(iaxis, xlo, xhi); // for phi divisions correct the range if (!strcmp(fShape->GetAxisName(iaxis), "PHI")) { - if ((start-xlo)<-1E-3) start+=360.; - if (TGeoShape::IsSameWithinTolerance(range,360)) { + if ((start - xlo) < -1E-3) + start += 360.; + if (TGeoShape::IsSameWithinTolerance(range, 360)) { xlo = start; - xhi = start+range; + xhi = start + range; } } - if (range <=0) { + if (range <= 0) { InspectShape(); Fatal("Divide", "cannot divide volume %s (%s) on %s axis", GetName(), stype.Data(), fShape->GetAxisName(iaxis)); return 0; } - if (ndiv<=0 || opt.Contains("s")) { - if (step<=0) { + if (ndiv <= 0 || opt.Contains("s")) { + if (step <= 0) { Fatal("Divide", "invalid division type for volume %s : ndiv=%i, step=%g", GetName(), ndiv, step); return 0; } if (opt.Contains("x")) { - if ((xlo-start)>1E-3 || (xhi-start)<-1E-3) { - Fatal("Divide", "invalid START=%g for division on axis %s of volume %s. Range is (%g, %g)", - start, fShape->GetAxisName(iaxis), GetName(), xlo, xhi); + if ((xlo - start) > 1E-3 || (xhi - start) < -1E-3) { + Fatal("Divide", "invalid START=%g for division on axis %s of volume %s. Range is (%g, %g)", start, + fShape->GetAxisName(iaxis), GetName(), xlo, xhi); return 0; } xlo = start; - range = xhi-xlo; + range = xhi - xlo; } - ndiv = Int_t((range+0.1*step)/step); - Double_t ddx = range - ndiv*step; + ndiv = Int_t((range + 0.1 * step) / step); + Double_t ddx = range - ndiv * step; // always center the division in this case - if (ddx>1E-3) Warning("Divide", "division of volume %s on %s axis (ndiv=%d) will be centered in the full range", - GetName(), fShape->GetAxisName(iaxis), ndiv); - start = xlo + 0.5*ddx; + if (ddx > 1E-3) + Warning("Divide", "division of volume %s on %s axis (ndiv=%d) will be centered in the full range", GetName(), + fShape->GetAxisName(iaxis), ndiv); + start = xlo + 0.5 * ddx; } - if (step<=0 || opt.Contains("n")) { + if (step <= 0 || opt.Contains("n")) { if (opt.Contains("x")) { - if ((xlo-start)>1E-3 || (xhi-start)<-1E-3) { - Fatal("Divide", "invalid START=%g for division on axis %s of volume %s. Range is (%g, %g)", - start, fShape->GetAxisName(iaxis), GetName(), xlo, xhi); + if ((xlo - start) > 1E-3 || (xhi - start) < -1E-3) { + Fatal("Divide", "invalid START=%g for division on axis %s of volume %s. Range is (%g, %g)", start, + fShape->GetAxisName(iaxis), GetName(), xlo, xhi); return 0; } xlo = start; - range = xhi-xlo; + range = xhi - xlo; } - step = range/ndiv; + step = range / ndiv; start = xlo; } - Double_t end = start+ndiv*step; - if (((start-xlo)<-1E-3) || ((end-xhi)>1E-3)) { - Fatal("Divide", "division of volume %s on axis %s exceed range (%g, %g)", - GetName(), fShape->GetAxisName(iaxis), xlo, xhi); + Double_t end = start + ndiv * step; + if (((start - xlo) < -1E-3) || ((end - xhi) > 1E-3)) { + Fatal("Divide", "division of volume %s on axis %s exceed range (%g, %g)", GetName(), fShape->GetAxisName(iaxis), + xlo, xhi); return 0; } TGeoVolume *voldiv = fShape->Divide(this, divname, iaxis, ndiv, start, step); @@ -1123,7 +1179,8 @@ TGeoVolume *TGeoVolume::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Dou return voldiv; } voldiv->SetMedium(medium); - if (medium->GetMaterial()) medium->GetMaterial()->SetUsed(); + if (medium->GetMaterial()) + medium->GetMaterial()->SetUsed(); } return voldiv; } @@ -1133,10 +1190,12 @@ TGeoVolume *TGeoVolume::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Dou Int_t TGeoVolume::DistancetoPrimitive(Int_t px, Int_t py) { - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; TVirtualGeoPainter *painter = fGeoManager->GetPainter(); Int_t dist = 9999; - if (!painter) return dist; + if (!painter) + return dist; dist = painter->DistanceToPrimitiveVol(this, px, py); return dist; } @@ -1146,15 +1205,17 @@ Int_t TGeoVolume::DistancetoPrimitive(Int_t px, Int_t py) void TGeoVolume::Draw(Option_t *option) { - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; fGeoManager->SetUserPaintVolume(this); TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); TGeoAtt::SetVisRaytrace(kFALSE); - if (!IsVisContainers()) SetVisLeaves(); + if (!IsVisContainers()) + SetVisLeaves(); if (option && option[0] > 0) { painter->DrawVolume(this, option); } else { - painter->DrawVolume(this, gEnv->GetValue("Viewer3D.DefaultDrawOption","")); + painter->DrawVolume(this, gEnv->GetValue("Viewer3D.DefaultDrawOption", "")); } } @@ -1167,14 +1228,15 @@ void TGeoVolume::DrawOnly(Option_t *option) Info("DrawOnly", "Volume assemblies do not support this option."); return; } - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; SetVisOnly(); TGeoAtt::SetVisRaytrace(kFALSE); TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); if (option && option[0] > 0) { painter->DrawVolume(this, option); } else { - painter->DrawVolume(this, gEnv->GetValue("Viewer3D.DefaultDrawOption","")); + painter->DrawVolume(this, gEnv->GetValue("Viewer3D.DefaultDrawOption", "")); } } @@ -1206,11 +1268,11 @@ void TGeoVolume::Paint(Option_t *option) { TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); painter->SetTopVolume(this); -// painter->Paint(option); + // painter->Paint(option); if (option && option[0] > 0) { painter->Paint(option); } else { - painter->Paint(gEnv->GetValue("Viewer3D.DefaultDrawOption","")); + painter->Paint(gEnv->GetValue("Viewer3D.DefaultDrawOption", "")); } } @@ -1219,7 +1281,8 @@ void TGeoVolume::Paint(Option_t *option) void TGeoVolume::PrintVoxels() const { - if (fVoxels) fVoxels->Print(); + if (fVoxels) + fVoxels->Print(); } //////////////////////////////////////////////////////////////////////////////// @@ -1229,7 +1292,8 @@ void TGeoVolume::PrintVoxels() const void TGeoVolume::ReplayCreation(const TGeoVolume *other) { Int_t nd = other->GetNdaughters(); - if (!nd) return; + if (!nd) + return; TGeoPatternFinder *finder = other->GetFinder(); if (finder) { Int_t iaxis = finder->GetDivAxis(); @@ -1241,10 +1305,12 @@ void TGeoVolume::ReplayCreation(const TGeoVolume *other) voldiv->ReplayCreation(other->GetNode(0)->GetVolume()); return; } - for (Int_t i=0; iGetNode(i); - if (node->IsOverlapping()) AddNodeOverlap(node->GetVolume(), node->GetNumber(), node->GetMatrix()); - else AddNode(node->GetVolume(), node->GetNumber(), node->GetMatrix()); + if (node->IsOverlapping()) + AddNodeOverlap(node->GetVolume(), node->GetNumber(), node->GetMatrix()); + else + AddNode(node->GetVolume(), node->GetNumber(), node->GetMatrix()); } } @@ -1254,7 +1320,7 @@ void TGeoVolume::ReplayCreation(const TGeoVolume *other) void TGeoVolume::PrintNodes() const { Int_t nd = GetNdaughters(); - for (Int_t i=0; iGetName()); cd(i); GetNode(i)->GetMatrix()->Print(); @@ -1263,14 +1329,15 @@ void TGeoVolume::PrintNodes() const //////////////////////////////////////////////////////////////////////////////// /// Generate a lego plot fot the top volume, according to option. -TH2F *TGeoVolume::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, - Int_t nphi, Double_t phimin, Double_t phimax, - Double_t rmin, Double_t rmax, Option_t *option) +TH2F *TGeoVolume::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, Int_t nphi, Double_t phimin, Double_t phimax, + Double_t rmin, Double_t rmax, Option_t *option) { TVirtualGeoPainter *p = fGeoManager->GetGeomPainter(); TGeoVolume *old_vol = fGeoManager->GetTopVolume(); - if (old_vol!=this) fGeoManager->SetTopVolume(this); - else old_vol=0; + if (old_vol != this) + fGeoManager->SetTopVolume(this); + else + old_vol = 0; TH2F *hist = p->LegoPlot(ntheta, themin, themax, nphi, phimin, phimax, rmin, rmax, option); hist->Draw("lego1sph"); return hist; @@ -1281,13 +1348,14 @@ TH2F *TGeoVolume::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, void TGeoVolume::RegisterYourself(Option_t *option) { - if (fGeoManager->GetListOfVolumes()->FindObject(this)) return; + if (fGeoManager->GetListOfVolumes()->FindObject(this)) + return; // Register volume fGeoManager->AddVolume(this); // Register shape if (!fGeoManager->GetListOfShapes()->FindObject(fShape)) { if (fShape->IsComposite()) { - TGeoCompositeShape *comp = (TGeoCompositeShape*)fShape; + TGeoCompositeShape *comp = (TGeoCompositeShape *)fShape; comp->RegisterYourself(); } else { fGeoManager->AddShape(fShape); @@ -1304,16 +1372,18 @@ void TGeoVolume::RegisterYourself(Option_t *option) TGeoNode *node; Int_t nd = GetNdaughters(); Int_t i; - for (i=0; iGetMatrix(); - if (!matrix->IsRegistered()) matrix->RegisterYourself(); + if (!matrix->IsRegistered()) + matrix->RegisterYourself(); else if (!fGeoManager->GetListOfMatrices()->FindObject(matrix)) { fGeoManager->GetListOfMatrices()->Add(matrix); } } // Call RegisterYourself recursively - for (i=0; iGetVolume()->RegisterYourself(option); + for (i = 0; i < nd; i++) + GetNode(i)->GetVolume()->RegisterYourself(option); } //////////////////////////////////////////////////////////////////////////////// @@ -1321,25 +1391,34 @@ void TGeoVolume::RegisterYourself(Option_t *option) void TGeoVolume::RandomPoints(Int_t npoints, Option_t *option) { - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; TGeoVolume *old_vol = fGeoManager->GetTopVolume(); - if (old_vol!=this) fGeoManager->SetTopVolume(this); - else old_vol=0; + if (old_vol != this) + fGeoManager->SetTopVolume(this); + else + old_vol = 0; fGeoManager->RandomPoints(this, npoints, option); - if (old_vol) fGeoManager->SetTopVolume(old_vol); + if (old_vol) + fGeoManager->SetTopVolume(old_vol); } //////////////////////////////////////////////////////////////////////////////// /// Random raytracing method. -void TGeoVolume::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, Bool_t check_norm) +void TGeoVolume::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, + Bool_t check_norm) { - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; TGeoVolume *old_vol = fGeoManager->GetTopVolume(); - if (old_vol!=this) fGeoManager->SetTopVolume(this); - else old_vol=0; + if (old_vol != this) + fGeoManager->SetTopVolume(this); + else + old_vol = 0; fGeoManager->RandomRays(nrays, startx, starty, startz, target_vol, check_norm); - if (old_vol) fGeoManager->SetTopVolume(old_vol); + if (old_vol) + fGeoManager->SetTopVolume(old_vol); } //////////////////////////////////////////////////////////////////////////////// @@ -1348,9 +1427,10 @@ void TGeoVolume::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doubl void TGeoVolume::Raytrace(Bool_t flag) { TGeoAtt::SetVisRaytrace(kFALSE); - if (gGeoManager != fGeoManager) gGeoManager = fGeoManager; + if (gGeoManager != fGeoManager) + gGeoManager = fGeoManager; TVirtualGeoPainter *painter = fGeoManager->GetGeomPainter(); - Bool_t drawn = (painter->GetDrawnVolume()==this)?kTRUE:kFALSE; + Bool_t drawn = (painter->GetDrawnVolume() == this) ? kTRUE : kFALSE; if (!drawn) { painter->DrawVolume(this, ""); TGeoAtt::SetVisRaytrace(flag); @@ -1366,23 +1446,26 @@ void TGeoVolume::Raytrace(Bool_t flag) void TGeoVolume::SaveAs(const char *filename, Option_t *option) const { - if (!filename) return; + if (!filename) + return; std::ofstream out; out.open(filename, std::ios::out); if (out.bad()) { Error("SavePrimitive", "Bad file name: %s", filename); return; } - if (fGeoManager->GetTopVolume() != this) fGeoManager->SetTopVolume((TGeoVolume*)this); + if (fGeoManager->GetTopVolume() != this) + fGeoManager->SetTopVolume((TGeoVolume *)this); TString fname(filename); Int_t ind = fname.Index("."); - if (ind>0) fname.Remove(ind); - out << "void "< 0) + fname.Remove(ind); + out << "void " << fname << "() {" << std::endl; out << " gSystem->Load(\"libGeom\");" << std::endl; const UInt_t prec = TGeoManager::GetExportPrecision(); out << std::setprecision(prec); - ((TGeoVolume*)this)->SavePrimitive(out,option); + ((TGeoVolume *)this)->SavePrimitive(out, option); out << "}" << std::endl; } @@ -1396,9 +1479,11 @@ void TGeoVolume::SaveAs(const char *filename, Option_t *option) const void TGeoVolume::SetUserExtension(TGeoExtension *ext) { - if (fUserExtension) fUserExtension->Release(); + if (fUserExtension) + fUserExtension->Release(); fUserExtension = 0; - if (ext) fUserExtension = ext->Grab(); + if (ext) + fUserExtension = ext->Grab(); } //////////////////////////////////////////////////////////////////////////////// @@ -1411,9 +1496,11 @@ void TGeoVolume::SetUserExtension(TGeoExtension *ext) void TGeoVolume::SetFWExtension(TGeoExtension *ext) { - if (fFWExtension) fFWExtension->Release(); + if (fFWExtension) + fFWExtension->Release(); fFWExtension = 0; - if (ext) fFWExtension = ext->Grab(); + if (ext) + fFWExtension = ext->Grab(); } //////////////////////////////////////////////////////////////////////////////// @@ -1423,7 +1510,8 @@ void TGeoVolume::SetFWExtension(TGeoExtension *ext) TGeoExtension *TGeoVolume::GrabUserExtension() const { - if (fUserExtension) return fUserExtension->Grab(); + if (fUserExtension) + return fUserExtension->Grab(); return 0; } @@ -1434,7 +1522,8 @@ TGeoExtension *TGeoVolume::GrabUserExtension() const TGeoExtension *TGeoVolume::GrabFWExtension() const { - if (fFWExtension) return fFWExtension->Grab(); + if (fFWExtension) + return fFWExtension->Grab(); return 0; } @@ -1443,7 +1532,7 @@ TGeoExtension *TGeoVolume::GrabFWExtension() const void TGeoVolume::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { - Int_t i,icopy; + Int_t i, icopy; Int_t nd = GetNdaughters(); TGeoVolume *dvol; TGeoNode *dnode; @@ -1451,12 +1540,15 @@ void TGeoVolume::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) // check if we need to save shape/volume Bool_t mustDraw = kFALSE; - if (fGeoManager->GetGeomPainter()->GetTopVolume()==this) mustDraw = kTRUE; + if (fGeoManager->GetGeomPainter()->GetTopVolume() == this) + mustDraw = kTRUE; if (!option[0]) { fGeoManager->SetAllIndex(); - out << " new TGeoManager(\"" << fGeoManager->GetName() << "\", \"" << fGeoManager->GetTitle() << "\");" << std::endl << std::endl; -// if (mustDraw) out << " Bool_t mustDraw = kTRUE;" << std::endl; -// else out << " Bool_t mustDraw = kFALSE;" << std::endl; + out << " new TGeoManager(\"" << fGeoManager->GetName() << "\", \"" << fGeoManager->GetTitle() << "\");" + << std::endl + << std::endl; + // if (mustDraw) out << " Bool_t mustDraw = kTRUE;" << std::endl; + // else out << " Bool_t mustDraw = kFALSE;" << std::endl; out << " Double_t dx, dy, dz;" << std::endl; out << " Double_t dx1, dx2, dy1, dy2;" << std::endl; out << " Double_t vert[20], par[20];" << std::endl; @@ -1493,38 +1585,49 @@ void TGeoVolume::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) out << std::endl << " // CLOSE GEOMETRY" << std::endl; out << " gGeoManager->CloseGeometry();" << std::endl; if (mustDraw) { - if (!IsRaytracing()) out << " gGeoManager->GetTopVolume()->Draw();" << std::endl; - else out << " gGeoManager->GetTopVolume()->Raytrace();" << std::endl; + if (!IsRaytracing()) + out << " gGeoManager->GetTopVolume()->Draw();" << std::endl; + else + out << " gGeoManager->GetTopVolume()->Raytrace();" << std::endl; } return; } // check if we need to save shape/volume if (!strcmp(option, "s")) { // create the shape for this volume - if (TestAttBit(TGeoAtt::kSavePrimitiveAtt)) return; + if (TestAttBit(TGeoAtt::kSavePrimitiveAtt)) + return; if (!IsAssembly()) { - fShape->SavePrimitive(out,option); + fShape->SavePrimitive(out, option); out << " // Volume: " << GetName() << std::endl; - out << " TGeoVolume *" << GetPointerName() << " = new TGeoVolume(\"" << GetName() << "\"," << fShape->GetPointerName(); - if (fMedium) out << ", " << fMedium->GetPointerName(); + out << " TGeoVolume *" << GetPointerName() << " = new TGeoVolume(\"" << GetName() << "\"," + << fShape->GetPointerName(); + if (fMedium) + out << ", " << fMedium->GetPointerName(); out << ");" << std::endl; } else { out << " // Assembly: " << GetName() << std::endl; - out << " " << GetPointerName() << " = new TGeoVolumeAssembly(\"" << GetName() << "\"" << ");" << std::endl; + out << " " << GetPointerName() << " = new TGeoVolumeAssembly(\"" << GetName() << "\"" + << ");" << std::endl; } SaveLineAttributes(out, GetPointerName(), 1, 1, 1); - if (!IsVisible() && !IsAssembly()) out << " " << GetPointerName() << "->SetVisibility(kFALSE);" << std::endl; - if (!IsVisibleDaughters()) out << " " << GetPointerName() << "->VisibleDaughters(kFALSE);" << std::endl; - if (IsVisContainers()) out << " " << GetPointerName() << "->SetVisContainers(kTRUE);" << std::endl; - if (IsVisLeaves()) out << " " << GetPointerName() << "->SetVisLeaves(kTRUE);" << std::endl; + if (!IsVisible() && !IsAssembly()) + out << " " << GetPointerName() << "->SetVisibility(kFALSE);" << std::endl; + if (!IsVisibleDaughters()) + out << " " << GetPointerName() << "->VisibleDaughters(kFALSE);" << std::endl; + if (IsVisContainers()) + out << " " << GetPointerName() << "->SetVisContainers(kTRUE);" << std::endl; + if (IsVisLeaves()) + out << " " << GetPointerName() << "->SetVisLeaves(kTRUE);" << std::endl; SetAttBit(TGeoAtt::kSavePrimitiveAtt); } // check if we need to save the media if (!strcmp(option, "m")) { - if (fMedium) fMedium->SavePrimitive(out,option); - for (i=0; iSavePrimitive(out, option); + for (i = 0; i < nd; i++) { dvol = GetNode(i)->GetVolume(); - dvol->SavePrimitive(out,option); + dvol->SavePrimitive(out, option); } return; } @@ -1532,21 +1635,24 @@ void TGeoVolume::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) if (!strcmp(option, "x")) { if (fFinder) { dvol = GetNode(0)->GetVolume(); - dvol->SavePrimitive(out,option); + dvol->SavePrimitive(out, option); return; } - for (i=0; iGetMatrix(); - if (!matrix->IsIdentity()) matrix->SavePrimitive(out,option); - dnode->GetVolume()->SavePrimitive(out,option); + if (!matrix->IsIdentity()) + matrix->SavePrimitive(out, option); + dnode->GetVolume()->SavePrimitive(out, option); } return; } // check if we need to save volume daughters if (!strcmp(option, "d")) { - if (!nd) return; - if (TestAttBit(TGeoAtt::kSaveNodesAtt)) return; + if (!nd) + return; + if (TestAttBit(TGeoAtt::kSaveNodesAtt)) + return; SetAttBit(TGeoAtt::kSaveNodesAtt); if (fFinder) { // volume divided: generate volume->Divide() @@ -1554,31 +1660,33 @@ void TGeoVolume::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) dvol = dnode->GetVolume(); out << " TGeoVolume *" << dvol->GetPointerName() << " = "; out << GetPointerName() << "->Divide(\"" << dvol->GetName() << "\", "; - fFinder->SavePrimitive(out,option); + fFinder->SavePrimitive(out, option); if (fMedium != dvol->GetMedium()) out << ", " << dvol->GetMedium()->GetId(); out << ");" << std::endl; - dvol->SavePrimitive(out,"d"); + dvol->SavePrimitive(out, "d"); return; } - for (i=0; iGetVolume(); - dvol->SavePrimitive(out,"s"); + dvol->SavePrimitive(out, "s"); matrix = dnode->GetMatrix(); icopy = dnode->GetNumber(); // generate AddNode() out << " " << GetPointerName() << "->AddNode"; - if (dnode->IsOverlapping()) out << "Overlap"; + if (dnode->IsOverlapping()) + out << "Overlap"; out << "(" << dvol->GetPointerName() << ", " << icopy; - if (!matrix->IsIdentity()) out << ", " << matrix->GetPointerName(); + if (!matrix->IsIdentity()) + out << ", " << matrix->GetPointerName(); out << ");" << std::endl; } // Recursive loop to daughters - for (i=0; iGetVolume(); - dvol->SavePrimitive(out,"d"); + dvol->SavePrimitive(out, "d"); } } } @@ -1590,7 +1698,8 @@ void TGeoVolume::UnmarkSaved() { ResetAttBit(TGeoAtt::kSavePrimitiveAtt); ResetAttBit(TGeoAtt::kSaveNodesAtt); - if (fShape) fShape->ResetBit(TGeoShape::kGeoSavePrimitive); + if (fShape) + fShape->ResetBit(TGeoShape::kGeoSavePrimitive); } //////////////////////////////////////////////////////////////////////////////// @@ -1599,7 +1708,8 @@ void TGeoVolume::UnmarkSaved() void TGeoVolume::ExecuteEvent(Int_t event, Int_t px, Int_t py) { TVirtualGeoPainter *painter = fGeoManager->GetPainter(); - if (!painter) return; + if (!painter) + return; painter->ExecuteVolumeEvent(this, event, px, py); } @@ -1608,7 +1718,7 @@ void TGeoVolume::ExecuteEvent(Int_t event, Int_t px, Int_t py) TGeoNode *TGeoVolume::FindNode(const char *name) const { - return ((TGeoNode*)fNodes->FindObject(name)); + return ((TGeoNode *)fNodes->FindObject(name)); } //////////////////////////////////////////////////////////////////////////////// @@ -1617,9 +1727,10 @@ TGeoNode *TGeoVolume::FindNode(const char *name) const Int_t TGeoVolume::GetNodeIndex(const TGeoNode *node, Int_t *check_list, Int_t ncheck) const { TGeoNode *current = 0; - for (Int_t i=0; iAt(check_list[i]); - if (current==node) return check_list[i]; + for (Int_t i = 0; i < ncheck; i++) { + current = (TGeoNode *)fNodes->At(check_list[i]); + if (current == node) + return check_list[i]; } return -1; } @@ -1631,10 +1742,12 @@ Int_t TGeoVolume::GetIndex(const TGeoNode *node) const { TGeoNode *current = 0; Int_t nd = GetNdaughters(); - if (!nd) return -1; - for (Int_t i=0; iAt(i); - if (current==node) return i; + if (!nd) + return -1; + for (Int_t i = 0; i < nd; i++) { + current = (TGeoNode *)fNodes->At(i); + if (current == node) + return i; } return -1; } @@ -1644,10 +1757,11 @@ Int_t TGeoVolume::GetIndex(const TGeoNode *node) const char *TGeoVolume::GetObjectInfo(Int_t px, Int_t py) const { - TGeoVolume *vol = (TGeoVolume*)this; + TGeoVolume *vol = (TGeoVolume *)this; TVirtualGeoPainter *painter = fGeoManager->GetPainter(); - if (!painter) return 0; - return (char*)painter->GetVolumeInfo(vol, px, py); + if (!painter) + return 0; + return (char *)painter->GetVolumeInfo(vol, px, py); } //////////////////////////////////////////////////////////////////////////////// @@ -1656,15 +1770,17 @@ char *TGeoVolume::GetObjectInfo(Int_t px, Int_t py) const Bool_t TGeoVolume::GetOptimalVoxels() const { Int_t nd = GetNdaughters(); - if (!nd) return kFALSE; + if (!nd) + return kFALSE; Int_t id; Int_t ncyl = 0; TGeoNode *node; - for (id=0; idAt(id); + for (id = 0; id < nd; id++) { + node = (TGeoNode *)fNodes->At(id); ncyl += node->GetOptimalVoxels(); } - if (ncyl>(nd/2)) return kTRUE; + if (ncyl > (nd / 2)) + return kTRUE; return kFALSE; } @@ -1683,7 +1799,8 @@ const char *TGeoVolume::GetPointerName() const TGeoVoxelFinder *TGeoVolume::GetVoxels() const { - if (fVoxels && !fVoxels->IsInvalid()) return fVoxels; + if (fVoxels && !fVoxels->IsInvalid()) + return fVoxels; return NULL; } @@ -1693,7 +1810,8 @@ TGeoVoxelFinder *TGeoVolume::GetVoxels() const void TGeoVolume::GrabFocus() { TVirtualGeoPainter *painter = fGeoManager->GetPainter(); - if (painter) painter->GrabFocus(); + if (painter) + painter->GrabFocus(); } //////////////////////////////////////////////////////////////////////////////// @@ -1701,7 +1819,7 @@ void TGeoVolume::GrabFocus() Bool_t TGeoVolume::IsAssembly() const { - return fShape->IsAssembly(); + return fShape->IsAssembly(); } //////////////////////////////////////////////////////////////////////////////// @@ -1720,20 +1838,20 @@ TGeoVolume *TGeoVolume::CloneVolume() const vol->SetFillColor(GetFillColor()); vol->SetFillStyle(GetFillStyle()); // copy other attributes - Int_t nbits = 8*sizeof(UInt_t); - for (i=0; iSetAttBit(1<SetBit(1<SetAttBit(1 << i, TGeoAtt::TestAttBit(1 << i)); + for (i = 14; i < 24; i++) + vol->SetBit(1 << i, TestBit(1 << i)); // copy field vol->SetField(fField); // Set bits - for (i=0; iSetBit(1<SetBit(1 << i, TObject::TestBit(1 << i)); vol->SetBit(kVolumeClone); // copy nodes -// CloneNodesAndConnect(vol); + // CloneNodesAndConnect(vol); vol->MakeCopyNodes(this); // if volume is divided, copy finder vol->SetFinder(fFinder); @@ -1759,17 +1877,19 @@ TGeoVolume *TGeoVolume::CloneVolume() const void TGeoVolume::CloneNodesAndConnect(TGeoVolume *newmother) const { - if (!fNodes) return; + if (!fNodes) + return; TGeoNode *node; Int_t nd = fNodes->GetEntriesFast(); - if (!nd) return; + if (!nd) + return; // create new list of nodes TObjArray *list = new TObjArray(nd); // attach it to new volume newmother->SetNodes(list); -// ((TObject*)newmother)->SetBit(kVolumeImportNodes); - for (Int_t i=0; iSetBit(kVolumeImportNodes); + for (Int_t i = 0; i < nd; i++) { + // create copies of nodes and add them to list node = GetNode(i)->MakeCopyNode(); if (!node) { Fatal("CloneNodesAndConnect", "cannot make copy node"); @@ -1786,13 +1906,16 @@ void TGeoVolume::CloneNodesAndConnect(TGeoVolume *newmother) const void TGeoVolume::MakeCopyNodes(const TGeoVolume *other) { Int_t nd = other->GetNdaughters(); - if (!nd) return; + if (!nd) + return; if (fNodes) { - if (!TObject::TestBit(kVolumeImportNodes)) fNodes->Delete(); + if (!TObject::TestBit(kVolumeImportNodes)) + fNodes->Delete(); delete fNodes; } fNodes = new TObjArray(); - for (Int_t i=0; iAdd(other->GetNode(i)); + for (Int_t i = 0; i < nd; i++) + fNodes->Add(other->GetNode(i)); TObject::SetBit(kVolumeImportNodes); } @@ -1814,15 +1937,15 @@ TGeoVolume *TGeoVolume::MakeCopyVolume(TGeoShape *newshape) vol->SetField(fField); // if divided, copy division object if (fFinder) { -// Error("MakeCopyVolume", "volume %s divided", GetName()); + // Error("MakeCopyVolume", "volume %s divided", GetName()); vol->SetFinder(fFinder); } // Copy extensions vol->SetUserExtension(fUserExtension); vol->SetFWExtension(fFWExtension); CloneNodesAndConnect(vol); -// ((TObject*)vol)->SetBit(kVolumeImportNodes); - ((TObject*)vol)->SetBit(kVolumeClone); + // ((TObject*)vol)->SetBit(kVolumeImportNodes); + ((TObject *)vol)->SetBit(kVolumeClone); vol->SetOverlappingCandidate(IsOverlappingCandidate()); return vol; } @@ -1837,19 +1960,21 @@ TGeoVolume *TGeoVolume::MakeReflectedVolume(const char *newname) const Error("MakeReflectedVolume", "Geometry must be closed."); return NULL; } - TGeoVolume *vol = (TGeoVolume*)map.GetValue(this); + TGeoVolume *vol = (TGeoVolume *)map.GetValue(this); if (vol) { - if (newname && newname[0]) vol->SetName(newname); + if (newname && newname[0]) + vol->SetName(newname); return vol; } -// printf("Making reflection for volume: %s\n", GetName()); + // printf("Making reflection for volume: %s\n", GetName()); vol = CloneVolume(); if (!vol) { Fatal("MakeReflectedVolume", "Cannot clone volume %s\n", GetName()); return 0; } - map.Add((TObject*)this, vol); - if (newname && newname[0]) vol->SetName(newname); + map.Add((TObject *)this, vol); + if (newname && newname[0]) + vol->SetName(newname); delete vol->GetNodes(); vol->SetNodes(NULL); vol->SetBit(kVolumeImportNodes, kFALSE); @@ -1858,46 +1983,48 @@ TGeoVolume *TGeoVolume::MakeReflectedVolume(const char *newname) const // Reflect the shape (if any) and connect it. if (fShape) { TGeoShape *reflected_shape = - TGeoScaledShape::MakeScaledShape(fShape->GetName(), fShape, new TGeoScale(1.,1.,-1.)); + TGeoScaledShape::MakeScaledShape(fShape->GetName(), fShape, new TGeoScale(1., 1., -1.)); vol->SetShape(reflected_shape); } // Reflect the daughters. Int_t nd = vol->GetNdaughters(); - if (!nd) return vol; + if (!nd) + return vol; TGeoNodeMatrix *node; TGeoMatrix *local, *local_cloned; TGeoVolume *new_vol; if (!vol->GetFinder()) { - for (Int_t i=0; iGetNode(i); + for (Int_t i = 0; i < nd; i++) { + node = (TGeoNodeMatrix *)vol->GetNode(i); local = node->GetMatrix(); -// printf("%s before\n", node->GetName()); -// local->Print(); + // printf("%s before\n", node->GetName()); + // local->Print(); Bool_t reflected = local->IsReflection(); local_cloned = new TGeoCombiTrans(*local); local_cloned->RegisterYourself(); node->SetMatrix(local_cloned); if (!reflected) { - // We need to reflect only the translation and propagate to daughters. + // We need to reflect only the translation and propagate to daughters. // H' = Sz * H * Sz local_cloned->ReflectZ(kTRUE); local_cloned->ReflectZ(kFALSE); -// printf("%s after\n", node->GetName()); -// node->GetMatrix()->Print(); + // printf("%s after\n", node->GetName()); + // node->GetMatrix()->Print(); new_vol = node->GetVolume()->MakeReflectedVolume(); node->SetVolume(new_vol); continue; } // The next daughter is already reflected, so reflect on Z everything and stop local_cloned->ReflectZ(kTRUE); // rot + tr -// printf("%s already reflected... After:\n", node->GetName()); -// node->GetMatrix()->Print(); + // printf("%s already reflected... After:\n", node->GetName()); + // node->GetMatrix()->Print(); } - if (vol->GetVoxels()) vol->GetVoxels()->Voxelize(); + if (vol->GetVoxels()) + vol->GetVoxels()->Voxelize(); return vol; } // Volume is divided, so we have to reflect the division. -// printf(" ... divided %s\n", fFinder->ClassName()); + // printf(" ... divided %s\n", fFinder->ClassName()); TGeoPatternFinder *new_finder = fFinder->MakeCopy(kTRUE); if (!new_finder) { Fatal("MakeReflectedVolume", "Could not copy finder for volume %s", GetName()); @@ -1907,8 +2034,8 @@ TGeoVolume *TGeoVolume::MakeReflectedVolume(const char *newname) const vol->SetFinder(new_finder); TGeoNodeOffset *nodeoff; new_vol = 0; - for (Int_t i=0; iGetNode(i); + for (Int_t i = 0; i < nd; i++) { + nodeoff = (TGeoNodeOffset *)vol->GetNode(i); nodeoff->SetFinder(new_finder); new_vol = nodeoff->GetVolume()->MakeReflectedVolume(); nodeoff->SetVolume(new_vol); @@ -1929,7 +2056,7 @@ void TGeoVolume::SetAsTopVolume() void TGeoVolume::SetCurrentPoint(Double_t x, Double_t y, Double_t z) { - fGeoManager->SetCurrentPoint(x,y,z); + fGeoManager->SetCurrentPoint(x, y, z); } //////////////////////////////////////////////////////////////////////////////// @@ -1941,7 +2068,7 @@ void TGeoVolume::SetShape(const TGeoShape *shape) Error("SetShape", "No shape"); return; } - fShape = (TGeoShape*)shape; + fShape = (TGeoShape *)shape; } //////////////////////////////////////////////////////////////////////////////// @@ -1955,42 +2082,48 @@ void TGeoVolume::SortNodes() return; } Int_t nd = GetNdaughters(); -// printf("volume : %s, nd=%i\n", GetName(), nd); - if (!nd) return; - if (fFinder) return; -// printf("Nodes for %s\n", GetName()); + // printf("volume : %s, nd=%i\n", GetName(), nd); + if (!nd) + return; + if (fFinder) + return; + // printf("Nodes for %s\n", GetName()); Int_t id = 0; TGeoNode *node = 0; TObjArray *nodes = new TObjArray(nd); Int_t inode = 0; // first put ONLY's - for (id=0; idInheritsFrom(TGeoNodeOffset::Class()) || node->IsOverlapping()) continue; + if (node->InheritsFrom(TGeoNodeOffset::Class()) || node->IsOverlapping()) + continue; nodes->Add(node); -// printf("inode %i ONLY\n", inode); + // printf("inode %i ONLY\n", inode); inode++; } // second put overlapping nodes - for (id=0; idInheritsFrom(TGeoNodeOffset::Class()) || (!node->IsOverlapping())) continue; + if (node->InheritsFrom(TGeoNodeOffset::Class()) || (!node->IsOverlapping())) + continue; nodes->Add(node); -// printf("inode %i MANY\n", inode); + // printf("inode %i MANY\n", inode); inode++; } // third put the divided nodes if (fFinder) { fFinder->SetDivIndex(inode); - for (id=0; idInheritsFrom(TGeoNodeOffset::Class())) continue; + if (!node->InheritsFrom(TGeoNodeOffset::Class())) + continue; nodes->Add(node); -// printf("inode %i DIV\n", inode); + // printf("inode %i DIV\n", inode); inode++; } } - if (inode != nd) printf(" volume %s : number of nodes does not match!!!\n", GetName()); + if (inode != nd) + printf(" volume %s : number of nodes does not match!!!\n", GetName()); delete fNodes; fNodes = nodes; } @@ -2002,7 +2135,8 @@ void TGeoVolume::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { R__b.ReadClassBuffer(TGeoVolume::Class(), this); - if (fVoxels && fVoxels->IsInvalid()) Voxelize(""); + if (fVoxels && fVoxels->IsInvalid()) + Voxelize(""); } else { if (!fVoxels) { R__b.WriteClassBuffer(TGeoVolume::Class(), this); @@ -2056,7 +2190,8 @@ void TGeoVolume::SetLineWidth(Style_t lwidth) TGeoNode *TGeoVolume::GetNode(const char *name) const { - if (!fNodes) return 0; + if (!fNodes) + return 0; TGeoNode *node = (TGeoNode *)fNodes->FindObject(name); return node; } @@ -2066,17 +2201,20 @@ TGeoNode *TGeoVolume::GetNode(const char *name) const Int_t TGeoVolume::GetByteCount() const { - Int_t count = 28+2+6+4+0; // TNamed+TGeoAtt+TAttLine+TAttFill+TAtt3D + Int_t count = 28 + 2 + 6 + 4 + 0; // TNamed+TGeoAtt+TAttLine+TAttFill+TAtt3D count += fName.Capacity() + fTitle.Capacity(); // name+title - count += 7*sizeof(char*); // fShape + fMedium + fFinder + fField + fNodes + 2 extensions - count += fOption.Capacity(); // fOption - if (fShape) count += fShape->GetByteCount(); - if (fFinder) count += fFinder->GetByteCount(); + count += 7 * sizeof(char *); // fShape + fMedium + fFinder + fField + fNodes + 2 extensions + count += fOption.Capacity(); // fOption + if (fShape) + count += fShape->GetByteCount(); + if (fFinder) + count += fFinder->GetByteCount(); if (fNodes) { - count += 32 + 4*fNodes->GetEntries(); // TObjArray + count += 32 + 4 * fNodes->GetEntries(); // TObjArray TIter next(fNodes); TGeoNode *node; - while ((node=(TGeoNode*)next())) count += node->GetByteCount(); + while ((node = (TGeoNode *)next())) + count += node->GetByteCount(); } return count; } @@ -2087,17 +2225,20 @@ Int_t TGeoVolume::GetByteCount() const void TGeoVolume::FindOverlaps() const { if (!Valid()) { - Error("FindOverlaps","Bounding box not valid"); + Error("FindOverlaps", "Bounding box not valid"); return; } - if (!fVoxels) return; + if (!fVoxels) + return; Int_t nd = GetNdaughters(); - if (!nd) return; - TGeoNode *node=0; + if (!nd) + return; + TGeoNode *node = 0; Int_t inode = 0; - for (inode=0; inodeIsOverlapping()) continue; + if (!node->IsOverlapping()) + continue; fVoxels->FindOverlaps(inode); } } @@ -2107,11 +2248,15 @@ void TGeoVolume::FindOverlaps() const void TGeoVolume::RemoveNode(TGeoNode *node) { - if (!fNodes || !fNodes->GetEntriesFast()) return; - if (!fNodes->Remove(node)) return; + if (!fNodes || !fNodes->GetEntriesFast()) + return; + if (!fNodes->Remove(node)) + return; fNodes->Compress(); - if (fVoxels) fVoxels->SetNeedRebuild(); - if (IsAssembly()) fShape->ComputeBBox(); + if (fVoxels) + fVoxels->SetNeedRebuild(); + if (IsAssembly()) + fShape->ComputeBBox(); } //////////////////////////////////////////////////////////////////////////////// @@ -2122,16 +2267,19 @@ void TGeoVolume::RemoveNode(TGeoNode *node) TGeoNode *TGeoVolume::ReplaceNode(TGeoNode *nodeorig, TGeoShape *newshape, TGeoMatrix *newpos, TGeoMedium *newmed) { Int_t ind = GetIndex(nodeorig); - if (ind < 0) return NULL; + if (ind < 0) + return NULL; TGeoVolume *oldvol = nodeorig->GetVolume(); if (oldvol->IsAssembly()) { Error("ReplaceNode", "Cannot replace node %s since it is an assembly", nodeorig->GetName()); return NULL; } - TGeoShape *shape = oldvol->GetShape(); - if (newshape && !nodeorig->IsOffset()) shape = newshape; + TGeoShape *shape = oldvol->GetShape(); + if (newshape && !nodeorig->IsOffset()) + shape = newshape; TGeoMedium *med = oldvol->GetMedium(); - if (newmed) med = newmed; + if (newmed) + med = newmed; // Make a new volume TGeoVolume *vol = new TGeoVolume(oldvol->GetName(), shape, med); // copy volume attributes @@ -2153,14 +2301,16 @@ TGeoNode *TGeoVolume::ReplaceNode(TGeoNode *nodeorig, TGeoShape *newshape, TGeoM newnode->SetVolume(vol); // Replace the matrix if (newpos && !nodeorig->IsOffset()) { - TGeoNodeMatrix *nodemat = (TGeoNodeMatrix*)newnode; + TGeoNodeMatrix *nodemat = (TGeoNodeMatrix *)newnode; nodemat->SetMatrix(newpos); } // Replace nodeorig with new one fNodes->RemoveAt(ind); fNodes->AddAt(newnode, ind); - if (fVoxels) fVoxels->SetNeedRebuild(); - if (IsAssembly()) fShape->ComputeBBox(); + if (fVoxels) + fVoxels->SetNeedRebuild(); + if (IsAssembly()) + fShape->ComputeBBox(); return newnode; } @@ -2177,7 +2327,7 @@ void TGeoVolume::SelectVolume(Bool_t clear) Int_t i; TObject *vol; if (clear) { - for (i=0; iResetBit(TGeoVolume::kVolumeSelected); } @@ -2195,12 +2345,13 @@ void TGeoVolume::SelectVolume(Bool_t clear) void TGeoVolume::SetVisibility(Bool_t vis) { TGeoAtt::SetVisibility(vis); - if (fGeoManager->IsClosed()) SetVisTouched(kTRUE); + if (fGeoManager->IsClosed()) + SetVisTouched(kTRUE); fGeoManager->SetVisOption(4); TSeqCollection *brlist = gROOT->GetListOfBrowsers(); TIter next(brlist); TBrowser *browser = 0; - while ((browser=(TBrowser*)next())) { + while ((browser = (TBrowser *)next())) { browser->CheckObjectItem(this, vis); browser->Refresh(); } @@ -2213,8 +2364,10 @@ void TGeoVolume::SetVisContainers(Bool_t flag) { TGeoAtt::SetVisContainers(flag); if (fGeoManager && fGeoManager->IsClosed()) { - if (flag) fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisDefault); - else fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); + if (flag) + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisDefault); + else + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); } } @@ -2225,8 +2378,10 @@ void TGeoVolume::SetVisLeaves(Bool_t flag) { TGeoAtt::SetVisLeaves(flag); if (fGeoManager && fGeoManager->IsClosed()) { - if (flag) fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); - else fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisDefault); + if (flag) + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); + else + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisDefault); } } @@ -2235,11 +2390,14 @@ void TGeoVolume::SetVisLeaves(Bool_t flag) void TGeoVolume::SetVisOnly(Bool_t flag) { - if (IsAssembly()) return; + if (IsAssembly()) + return; TGeoAtt::SetVisOnly(flag); if (fGeoManager && fGeoManager->IsClosed()) { - if (flag) fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisOnly); - else fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); + if (flag) + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisOnly); + else + fGeoManager->SetVisOption(TVirtualGeoPainter::kGeoVisLeaves); } } @@ -2257,16 +2415,19 @@ Bool_t TGeoVolume::Valid() const Bool_t TGeoVolume::FindMatrixOfDaughterVolume(TGeoVolume *vol) const { - if (vol == this) return kTRUE; + if (vol == this) + return kTRUE; Int_t nd = GetNdaughters(); - if (!nd) return kFALSE; + if (!nd) + return kFALSE; TGeoHMatrix *global = fGeoManager->GetHMatrix(); - if (!global) return kFALSE; + if (!global) + return kFALSE; TGeoNode *dnode; TGeoVolume *dvol; TGeoMatrix *local; Int_t i; - for (i=0; iGetVolume(); if (dvol == vol) { @@ -2275,10 +2436,11 @@ Bool_t TGeoVolume::FindMatrixOfDaughterVolume(TGeoVolume *vol) const return kTRUE; } } - for (i=0; iGetVolume(); - if (dvol->FindMatrixOfDaughterVolume(vol)) return kTRUE; + if (dvol->FindMatrixOfDaughterVolume(vol)) + return kTRUE; } return kFALSE; } @@ -2289,7 +2451,8 @@ Bool_t TGeoVolume::FindMatrixOfDaughterVolume(TGeoVolume *vol) const void TGeoVolume::VisibleDaughters(Bool_t vis) { SetVisDaughters(vis); - if (fGeoManager->IsClosed()) SetVisTouched(kTRUE); + if (fGeoManager->IsClosed()) + SetVisTouched(kTRUE); fGeoManager->SetVisOption(4); } @@ -2303,15 +2466,19 @@ void TGeoVolume::Voxelize(Option_t *option) return; } // do not voxelize divided volumes - if (fFinder) return; + if (fFinder) + return; // or final leaves Int_t nd = GetNdaughters(); - if (!nd) return; + if (!nd) + return; // If this is an assembly, re-compute bounding box - if (IsAssembly()) fShape->ComputeBBox(); + if (IsAssembly()) + fShape->ComputeBBox(); // delete old voxelization if any if (fVoxels) { - if (!TObject::TestBit(kVolumeClone)) delete fVoxels; + if (!TObject::TestBit(kVolumeClone)) + delete fVoxels; fVoxels = 0; } // Create the voxels structure @@ -2332,10 +2499,13 @@ void TGeoVolume::Voxelize(Option_t *option) Double_t TGeoVolume::Weight(Double_t precision, Option_t *option) { TGeoVolume *top = fGeoManager->GetTopVolume(); - if (top != this) fGeoManager->SetTopVolume(this); - else top = 0; - Double_t weight = fGeoManager->Weight(precision, option); - if (top) fGeoManager->SetTopVolume(top); + if (top != this) + fGeoManager->SetTopVolume(this); + else + top = 0; + Double_t weight = fGeoManager->Weight(precision, option); + if (top) + fGeoManager->SetTopVolume(top); return weight; } @@ -2349,29 +2519,30 @@ Double_t TGeoVolume::WeightA() const Int_t i; Int_t nd = GetNdaughters(); TGeoVolume *daughter; - for (i=0; iGetVolume(); weight += daughter->WeightA(); capacity -= daughter->Capacity(); } Double_t density = 0.0; if (!IsAssembly()) { - if (fMedium) density = fMedium->GetMaterial()->GetDensity(); - if (density<0.01) density = 0.0; // do not weight gases + if (fMedium) + density = fMedium->GetMaterial()->GetDensity(); + if (density < 0.01) + density = 0.0; // do not weight gases } - weight += 0.001*capacity * density; //[kg] + weight += 0.001 * capacity * density; //[kg] return weight; } ClassImp(TGeoVolumeMulti); - //////////////////////////////////////////////////////////////////////////////// /// dummy constructor TGeoVolumeMulti::TGeoVolumeMulti() { - fVolumes = 0; + fVolumes = 0; fDivision = 0; fNumed = 0; fNdiv = 0; @@ -2399,7 +2570,7 @@ TGeoVolumeMulti::TGeoVolumeMulti(const char *name, TGeoMedium *med) SetName(name); SetMedium(med); fGeoManager->AddVolume(this); -// printf("--- volume multi %s created\n", name); + // printf("--- volume multi %s created\n", name); } //////////////////////////////////////////////////////////////////////////////// @@ -2407,7 +2578,8 @@ TGeoVolumeMulti::TGeoVolumeMulti(const char *name, TGeoMedium *med) TGeoVolumeMulti::~TGeoVolumeMulti() { - if (fVolumes) delete fVolumes; + if (fVolumes) + delete fVolumes; } //////////////////////////////////////////////////////////////////////////////// @@ -2417,34 +2589,35 @@ TGeoVolumeMulti::~TGeoVolumeMulti() void TGeoVolumeMulti::AddVolume(TGeoVolume *vol) { Int_t idx = fVolumes->GetEntriesFast(); - fVolumes->AddAtAndExpand(vol,idx); - vol->SetUniqueID(idx+1); + fVolumes->AddAtAndExpand(vol, idx); + vol->SetUniqueID(idx + 1); TGeoVolumeMulti *div; TGeoVolume *cell; if (fDivision) { - div = (TGeoVolumeMulti*)vol->Divide(fDivision->GetName(), fAxis, fNdiv, fStart, fStep, fNumed, fOption.Data()); + div = (TGeoVolumeMulti *)vol->Divide(fDivision->GetName(), fAxis, fNdiv, fStart, fStep, fNumed, fOption.Data()); if (!div) { Fatal("AddVolume", "Cannot divide volume %s", vol->GetName()); return; } - for (Int_t i=0; iGetNvolumes(); i++) { + for (Int_t i = 0; i < div->GetNvolumes(); i++) { cell = div->GetVolume(i); fDivision->AddVolume(cell); } } if (fNodes) { Int_t nd = fNodes->GetEntriesFast(); - for (Int_t id=0; idAt(id); + for (Int_t id = 0; id < nd; id++) { + TGeoNode *node = (TGeoNode *)fNodes->At(id); Bool_t many = node->IsOverlapping(); - if (many) vol->AddNodeOverlap(node->GetVolume(), node->GetNumber(), node->GetMatrix()); - else vol->AddNode(node->GetVolume(), node->GetNumber(), node->GetMatrix()); + if (many) + vol->AddNodeOverlap(node->GetVolume(), node->GetNumber(), node->GetMatrix()); + else + vol->AddNode(node->GetVolume(), node->GetNumber(), node->GetMatrix()); } } -// vol->MakeCopyNodes(this); + // vol->MakeCopyNodes(this); } - //////////////////////////////////////////////////////////////////////////////// /// Add a new node to the list of nodes. This is the usual method for adding /// daughters inside the container volume. @@ -2454,7 +2627,7 @@ TGeoNode *TGeoVolumeMulti::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *m TGeoNode *n = TGeoVolume::AddNode(vol, copy_no, mat, option); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *volume = 0; - for (Int_t ivo=0; ivoSetLineColor(GetLineColor()); volume->SetLineStyle(GetLineStyle()); @@ -2475,7 +2648,7 @@ void TGeoVolumeMulti::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix TGeoVolume::AddNodeOverlap(vol, copy_no, mat, option); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *volume = 0; - for (Int_t ivo=0; ivoSetLineColor(GetLineColor()); volume->SetLineStyle(GetLineStyle()); @@ -2483,7 +2656,7 @@ void TGeoVolumeMulti::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix volume->SetVisibility(IsVisible()); volume->AddNodeOverlap(vol, copy_no, mat, option); } -// printf("--- vmulti %s : node ovlp %s added to %i components\n", GetName(), vol->GetName(), nvolumes); + // printf("--- vmulti %s : node ovlp %s added to %i components\n", GetName(), vol->GetName(), nvolumes); } //////////////////////////////////////////////////////////////////////////////// @@ -2491,15 +2664,17 @@ void TGeoVolumeMulti::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix TGeoShape *TGeoVolumeMulti::GetLastShape() const { - TGeoVolume *vol = GetVolume(fVolumes->GetEntriesFast()-1); - if (!vol) return 0; + TGeoVolume *vol = GetVolume(fVolumes->GetEntriesFast() - 1); + if (!vol) + return 0; return vol->GetShape(); } //////////////////////////////////////////////////////////////////////////////// /// division of multiple volumes -TGeoVolume *TGeoVolumeMulti::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, Int_t numed, const char *option) +TGeoVolume *TGeoVolumeMulti::Divide(const char *divname, Int_t iaxis, Int_t ndiv, Double_t start, Double_t step, + Int_t numed, const char *option) { if (fDivision) { Error("Divide", "volume %s already divided", GetName()); @@ -2528,22 +2703,24 @@ TGeoVolume *TGeoVolumeMulti::Divide(const char *divname, Int_t iaxis, Int_t ndiv } TGeoVolume *vol = 0; fDivision = new TGeoVolumeMulti(divname, medium); - if (medium) fNumed = medium->GetId(); + if (medium) + fNumed = medium->GetId(); fOption = option; fAxis = iaxis; fNdiv = ndiv; fStart = start; fStep = step; - for (Int_t ivo=0; ivoSetLineColor(GetLineColor()); vol->SetLineStyle(GetLineStyle()); vol->SetLineWidth(GetLineWidth()); vol->SetVisibility(IsVisible()); - fDivision->AddVolume(vol->Divide(divname,iaxis,ndiv,start,step, numed, option)); + fDivision->AddVolume(vol->Divide(divname, iaxis, ndiv, start, step, numed, option)); } -// printf("--- volume multi %s (%i volumes) divided\n", GetName(), nvolumes); - if (numed) fDivision->SetMedium(medium); + // printf("--- volume multi %s (%i volumes) divided\n", GetName(), nvolumes); + if (numed) + fDivision->SetMedium(medium); return fDivision; } @@ -2554,7 +2731,7 @@ TGeoVolume *TGeoVolumeMulti::Divide(const char *divname, Int_t iaxis, Int_t ndiv TGeoVolume *TGeoVolumeMulti::MakeCopyVolume(TGeoShape *newshape) { TGeoVolume *vol = new TGeoVolume(GetName(), newshape, fMedium); - Int_t i=0; + Int_t i = 0; // copy volume attributes vol->SetVisibility(IsVisible()); vol->SetLineColor(GetLineColor()); @@ -2568,34 +2745,37 @@ TGeoVolume *TGeoVolumeMulti::MakeCopyVolume(TGeoShape *newshape) vol->SetUserExtension(fUserExtension); vol->SetFWExtension(fFWExtension); // if divided, copy division object -// if (fFinder) { -// Error("MakeCopyVolume", "volume %s divided", GetName()); -// vol->SetFinder(fFinder); -// } + // if (fFinder) { + // Error("MakeCopyVolume", "volume %s divided", GetName()); + // vol->SetFinder(fFinder); + // } if (fDivision) { TGeoVolume *cell; - TGeoVolumeMulti *div = (TGeoVolumeMulti*)vol->Divide(fDivision->GetName(), fAxis, fNdiv, fStart, fStep, fNumed, fOption.Data()); + TGeoVolumeMulti *div = + (TGeoVolumeMulti *)vol->Divide(fDivision->GetName(), fAxis, fNdiv, fStart, fStep, fNumed, fOption.Data()); if (!div) { Fatal("MakeCopyVolume", "Cannot divide volume %s", vol->GetName()); return 0; } - for (i=0; iGetNvolumes(); i++) { + for (i = 0; i < div->GetNvolumes(); i++) { cell = div->GetVolume(i); fDivision->AddVolume(cell); } } - if (!fNodes) return vol; + if (!fNodes) + return vol; TGeoNode *node; Int_t nd = fNodes->GetEntriesFast(); - if (!nd) return vol; + if (!nd) + return vol; // create new list of nodes TObjArray *list = new TObjArray(); // attach it to new volume vol->SetNodes(list); - ((TObject*)vol)->SetBit(kVolumeImportNodes); - for (i=0; iSetBit(kVolumeImportNodes); + for (i = 0; i < nd; i++) { + // create copies of nodes and add them to list node = GetNode(i)->MakeCopyNode(); if (!node) { Fatal("MakeCopyNode", "cannot make copy node for daughter %d of %s", i, GetName()); @@ -2615,7 +2795,7 @@ void TGeoVolumeMulti::SetLineColor(Color_t lcolor) TGeoVolume::SetLineColor(lcolor); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *vol = 0; - for (Int_t ivo=0; ivoSetLineColor(lcolor); } @@ -2629,7 +2809,7 @@ void TGeoVolumeMulti::SetLineStyle(Style_t lstyle) TGeoVolume::SetLineStyle(lstyle); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *vol = 0; - for (Int_t ivo=0; ivoSetLineStyle(lstyle); } @@ -2643,7 +2823,7 @@ void TGeoVolumeMulti::SetLineWidth(Width_t lwidth) TGeoVolume::SetLineWidth(lwidth); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *vol = 0; - for (Int_t ivo=0; ivoSetLineWidth(lwidth); } @@ -2657,13 +2837,12 @@ void TGeoVolumeMulti::SetMedium(TGeoMedium *med) TGeoVolume::SetMedium(med); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *vol = 0; - for (Int_t ivo=0; ivoSetMedium(med); } } - //////////////////////////////////////////////////////////////////////////////// /// Set visibility for all components. @@ -2672,7 +2851,7 @@ void TGeoVolumeMulti::SetVisibility(Bool_t vis) TGeoVolume::SetVisibility(vis); Int_t nvolumes = fVolumes->GetEntriesFast(); TGeoVolume *vol = 0; - for (Int_t ivo=0; ivoSetVisibility(vis); } @@ -2683,21 +2862,16 @@ ClassImp(TGeoVolumeAssembly); //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoVolumeAssembly::ThreadData_t::ThreadData_t() : - fCurrent(-1), fNext(-1) -{ -} +TGeoVolumeAssembly::ThreadData_t::ThreadData_t() : fCurrent(-1), fNext(-1) {} //////////////////////////////////////////////////////////////////////////////// /// Destructor. -TGeoVolumeAssembly::ThreadData_t::~ThreadData_t() -{ -} +TGeoVolumeAssembly::ThreadData_t::~ThreadData_t() {} //////////////////////////////////////////////////////////////////////////////// -TGeoVolumeAssembly::ThreadData_t& TGeoVolumeAssembly::GetThreadData() const +TGeoVolumeAssembly::ThreadData_t &TGeoVolumeAssembly::GetThreadData() const { Int_t tid = TGeoManager::ThreadId(); return *fThreadData[tid]; @@ -2709,9 +2883,8 @@ void TGeoVolumeAssembly::ClearThreadData() const { std::lock_guard guard(fMutex); TGeoVolume::ClearThreadData(); - std::vector::iterator i = fThreadData.begin(); - while (i != fThreadData.end()) - { + std::vector::iterator i = fThreadData.begin(); + while (i != fThreadData.end()) { delete *i; ++i; } @@ -2727,7 +2900,7 @@ void TGeoVolumeAssembly::CreateThreadData(Int_t nthreads) // Create assembly thread data here fThreadData.resize(nthreads); fThreadSize = nthreads; - for (Int_t tid=0; tidAddVolume(this); + if (fGeoManager) + fNumber = fGeoManager->AddVolume(this); fThreadSize = 0; CreateThreadData(1); } @@ -2794,7 +2966,8 @@ TGeoVolumeAssembly::TGeoVolumeAssembly(const char *name) TGeoVolumeAssembly::~TGeoVolumeAssembly() { ClearThreadData(); - if (fShape) delete fShape; + if (fShape) + delete fShape; } //////////////////////////////////////////////////////////////////////////////// @@ -2804,7 +2977,7 @@ TGeoNode *TGeoVolumeAssembly::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix { TGeoNode *node = TGeoVolume::AddNode(vol, copy_no, mat, option); // ((TGeoShapeAssembly*)fShape)->RecomputeBoxLast(); - ((TGeoShapeAssembly*)fShape)->NeedsBBoxRecompute(); + ((TGeoShapeAssembly *)fShape)->NeedsBBoxRecompute(); return node; } @@ -2813,7 +2986,9 @@ TGeoNode *TGeoVolumeAssembly::AddNode(TGeoVolume *vol, Int_t copy_no, TGeoMatrix void TGeoVolumeAssembly::AddNodeOverlap(TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t *option) { - Warning("AddNodeOverlap", "Declaring assembly %s as possibly overlapping inside %s not allowed. Using AddNode instead !",vol->GetName(),GetName()); + Warning("AddNodeOverlap", + "Declaring assembly %s as possibly overlapping inside %s not allowed. Using AddNode instead !", + vol->GetName(), GetName()); AddNode(vol, copy_no, mat, option); } @@ -2826,22 +3001,22 @@ TGeoVolume *TGeoVolumeAssembly::CloneVolume() const TGeoVolume *vol = new TGeoVolumeAssembly(GetName()); Int_t i; // copy other attributes - Int_t nbits = 8*sizeof(UInt_t); - for (i=0; iSetAttBit(1<SetBit(1<SetAttBit(1 << i, TGeoAtt::TestAttBit(1 << i)); + for (i = 14; i < 24; i++) + vol->SetBit(1 << i, TestBit(1 << i)); // copy field vol->SetField(fField); // Set bits - for (i=0; iSetBit(1<SetBit(1 << i, TObject::TestBit(1 << i)); vol->SetBit(kVolumeClone); // make copy nodes vol->MakeCopyNodes(this); -// CloneNodesAndConnect(vol); - ((TGeoShapeAssembly*)vol->GetShape())->NeedsBBoxRecompute(); + // CloneNodesAndConnect(vol); + ((TGeoShapeAssembly *)vol->GetShape())->NeedsBBoxRecompute(); // copy voxels TGeoVoxelFinder *voxels = 0; if (fVoxels) { @@ -2861,7 +3036,7 @@ TGeoVolume *TGeoVolumeAssembly::CloneVolume() const TGeoVolume *TGeoVolumeAssembly::Divide(const char *, Int_t, Int_t, Double_t, Double_t, Int_t, Option_t *) { - Error("Divide","Assemblies cannot be divided"); + Error("Divide", "Assemblies cannot be divided"); return 0; } @@ -2881,17 +3056,19 @@ TGeoVolume *TGeoVolumeAssembly::Divide(TGeoVolume *cell, TGeoPatternFinder *patt return NULL; } Int_t ncells = pattern->GetNdiv(); - if (!ncells || pattern->GetStep()<=0) { + if (!ncells || pattern->GetStep() <= 0) { Error("Divide", "Pattern finder for dividing assembly %s not initialized. Use SetRange() method.", GetName()); return NULL; } fFinder = pattern; TString opt(option); opt.ToLower(); - if (opt.Contains("spacedout")) fFinder->SetSpacedOut(kTRUE); - else fFinder->SetSpacedOut(kFALSE); + if (opt.Contains("spacedout")) + fFinder->SetSpacedOut(kTRUE); + else + fFinder->SetSpacedOut(kFALSE); // Position volumes - for (Int_t i=0; icd(i); TGeoNodeOffset *node = new TGeoNodeOffset(cell, i, 0.); node->SetFinder(fFinder); @@ -2905,27 +3082,29 @@ TGeoVolume *TGeoVolumeAssembly::Divide(TGeoVolume *cell, TGeoPatternFinder *patt TGeoVolumeAssembly *TGeoVolumeAssembly::MakeAssemblyFromVolume(TGeoVolume *volorig) { - if (volorig->IsAssembly() || volorig->IsVolumeMulti()) return 0; + if (volorig->IsAssembly() || volorig->IsVolumeMulti()) + return 0; Int_t nd = volorig->GetNdaughters(); - if (!nd) return 0; + if (!nd) + return 0; TGeoVolumeAssembly *vol = new TGeoVolumeAssembly(volorig->GetName()); Int_t i; // copy other attributes - Int_t nbits = 8*sizeof(UInt_t); - for (i=0; iSetAttBit(1<TestAttBit(1<SetBit(1<TestBit(1<SetAttBit(1 << i, volorig->TestAttBit(1 << i)); + for (i = 14; i < 24; i++) + vol->SetBit(1 << i, volorig->TestBit(1 << i)); // copy field vol->SetField(volorig->GetField()); // Set bits - for (i=0; iSetBit(1<TestBit(1<SetBit(1 << i, volorig->TestBit(1 << i)); vol->SetBit(kVolumeClone); // make copy nodes vol->MakeCopyNodes(volorig); -// volorig->CloneNodesAndConnect(vol); + // volorig->CloneNodesAndConnect(vol); vol->GetShape()->ComputeBBox(); // copy voxels TGeoVoxelFinder *voxels = 0; diff --git a/geom/geom/src/TGeoVoxelFinder.cxx b/geom/geom/src/TGeoVoxelFinder.cxx index 1072aecb48417..dea63fbfa5f30 100644 --- a/geom/geom/src/TGeoVoxelFinder.cxx +++ b/geom/geom/src/TGeoVoxelFinder.cxx @@ -38,40 +38,40 @@ ClassImp(TGeoVoxelFinder); TGeoVoxelFinder::TGeoVoxelFinder() { - fVolume = 0; - fNboxes = 0; - fIbx = 0; - fIby = 0; - fIbz = 0; - fNox = 0; - fNoy = 0; - fNoz = 0; - fNex = 0; - fNey = 0; - fNez = 0; - fNx = 0; - fNy = 0; - fNz = 0; - fBoxes = 0; - fXb = 0; - fYb = 0; - fZb = 0; - fOBx = 0; - fOBy = 0; - fOBz = 0; - fOEx = 0; - fOEy = 0; - fOEz = 0; - fIndcX = 0; - fIndcY = 0; - fIndcZ = 0; - fExtraX = 0; - fExtraY = 0; - fExtraZ = 0; + fVolume = 0; + fNboxes = 0; + fIbx = 0; + fIby = 0; + fIbz = 0; + fNox = 0; + fNoy = 0; + fNoz = 0; + fNex = 0; + fNey = 0; + fNez = 0; + fNx = 0; + fNy = 0; + fNz = 0; + fBoxes = 0; + fXb = 0; + fYb = 0; + fZb = 0; + fOBx = 0; + fOBy = 0; + fOBz = 0; + fOEx = 0; + fOEy = 0; + fOEz = 0; + fIndcX = 0; + fIndcY = 0; + fIndcZ = 0; + fExtraX = 0; + fExtraY = 0; + fExtraZ = 0; fNsliceX = 0; fNsliceY = 0; fNsliceZ = 0; - memset(fPriority, 0, 3*sizeof(Int_t)); + memset(fPriority, 0, 3 * sizeof(Int_t)); SetInvalid(kFALSE); } //////////////////////////////////////////////////////////////////////////////// @@ -83,41 +83,41 @@ TGeoVoxelFinder::TGeoVoxelFinder(TGeoVolume *vol) Fatal("TGeoVoxelFinder", "Null pointer for volume"); return; // To make code checkers happy } - fVolume = vol; + fVolume = vol; fVolume->SetCylVoxels(kFALSE); - fNboxes = 0; - fIbx = 0; - fIby = 0; - fIbz = 0; - fNox = 0; - fNoy = 0; - fNoz = 0; - fNex = 0; - fNey = 0; - fNez = 0; - fNx = 0; - fNy = 0; - fNz = 0; - fBoxes = 0; - fXb = 0; - fYb = 0; - fZb = 0; - fOBx = 0; - fOBy = 0; - fOBz = 0; - fOEx = 0; - fOEy = 0; - fOEz = 0; - fIndcX = 0; - fIndcY = 0; - fIndcZ = 0; - fExtraX = 0; - fExtraY = 0; - fExtraZ = 0; + fNboxes = 0; + fIbx = 0; + fIby = 0; + fIbz = 0; + fNox = 0; + fNoy = 0; + fNoz = 0; + fNex = 0; + fNey = 0; + fNez = 0; + fNx = 0; + fNy = 0; + fNz = 0; + fBoxes = 0; + fXb = 0; + fYb = 0; + fZb = 0; + fOBx = 0; + fOBy = 0; + fOBz = 0; + fOEx = 0; + fOEy = 0; + fOEz = 0; + fIndcX = 0; + fIndcY = 0; + fIndcZ = 0; + fExtraX = 0; + fExtraY = 0; + fExtraZ = 0; fNsliceX = 0; fNsliceY = 0; fNsliceZ = 0; - memset(fPriority, 0, 3*sizeof(Int_t)); + memset(fPriority, 0, 3 * sizeof(Int_t)); SetNeedRebuild(); } @@ -126,29 +126,48 @@ TGeoVoxelFinder::TGeoVoxelFinder(TGeoVolume *vol) TGeoVoxelFinder::~TGeoVoxelFinder() { - if (fOBx) delete [] fOBx; - if (fOBy) delete [] fOBy; - if (fOBz) delete [] fOBz; - if (fOEx) delete [] fOEx; - if (fOEy) delete [] fOEy; - if (fOEz) delete [] fOEz; -// printf("OBx OBy OBz...\n"); - if (fBoxes) delete [] fBoxes; -// printf("boxes...\n"); - if (fXb) delete [] fXb; - if (fYb) delete [] fYb; - if (fZb) delete [] fZb; -// printf("Xb Yb Zb...\n"); - if (fNsliceX) delete [] fNsliceX; - if (fNsliceY) delete [] fNsliceY; - if (fNsliceZ) delete [] fNsliceZ; - if (fIndcX) delete [] fIndcX; - if (fIndcY) delete [] fIndcY; - if (fIndcZ) delete [] fIndcZ; - if (fExtraX) delete [] fExtraX; - if (fExtraY) delete [] fExtraY; - if (fExtraZ) delete [] fExtraZ; -// printf("IndX IndY IndZ...\n"); + if (fOBx) + delete[] fOBx; + if (fOBy) + delete[] fOBy; + if (fOBz) + delete[] fOBz; + if (fOEx) + delete[] fOEx; + if (fOEy) + delete[] fOEy; + if (fOEz) + delete[] fOEz; + // printf("OBx OBy OBz...\n"); + if (fBoxes) + delete[] fBoxes; + // printf("boxes...\n"); + if (fXb) + delete[] fXb; + if (fYb) + delete[] fYb; + if (fZb) + delete[] fZb; + // printf("Xb Yb Zb...\n"); + if (fNsliceX) + delete[] fNsliceX; + if (fNsliceY) + delete[] fNsliceY; + if (fNsliceZ) + delete[] fNsliceZ; + if (fIndcX) + delete[] fIndcX; + if (fIndcY) + delete[] fIndcY; + if (fIndcZ) + delete[] fIndcZ; + if (fExtraX) + delete[] fExtraX; + if (fExtraY) + delete[] fExtraY; + if (fExtraZ) + delete[] fExtraZ; + // printf("IndX IndY IndZ...\n"); } //////////////////////////////////////////////////////////////////////////////// @@ -160,7 +179,7 @@ Int_t TGeoVoxelFinder::GetNcandidates(TGeoStateInfo &td) const //////////////////////////////////////////////////////////////////////////////// -Int_t* TGeoVoxelFinder::GetCheckList(Int_t &nelem, TGeoStateInfo &td) const +Int_t *TGeoVoxelFinder::GetCheckList(Int_t &nelem, TGeoStateInfo &td) const { nelem = td.fVoxNcandidates; return td.fVoxCheckList; @@ -172,41 +191,45 @@ Int_t* TGeoVoxelFinder::GetCheckList(Int_t &nelem, TGeoStateInfo &td) const void TGeoVoxelFinder::BuildVoxelLimits() { Int_t nd = fVolume->GetNdaughters(); - if (!nd) return; + if (!nd) + return; Int_t id; TGeoNode *node; - if (fBoxes) delete [] fBoxes; - fNboxes = 6*nd; + if (fBoxes) + delete[] fBoxes; + fNboxes = 6 * nd; fBoxes = new Double_t[fNboxes]; Double_t vert[24] = {0}; Double_t pt[3] = {0}; Double_t xyz[6] = {0}; -// printf("boundaries for %s :\n", GetName()); + // printf("boundaries for %s :\n", GetName()); TGeoBBox *box = 0; - for (id=0; idGetNode(id); -// if (!strcmp(node->ClassName(), "TGeoNodeOffset") continue; - box = (TGeoBBox*)node->GetVolume()->GetShape(); + // if (!strcmp(node->ClassName(), "TGeoNodeOffset") continue; + box = (TGeoBBox *)node->GetVolume()->GetShape(); box->SetBoxPoints(&vert[0]); - for (Int_t point=0; point<8; point++) { - DaughterToMother(id, &vert[3*point], &pt[0]); + for (Int_t point = 0; point < 8; point++) { + DaughterToMother(id, &vert[3 * point], &pt[0]); if (!point) { xyz[0] = xyz[1] = pt[0]; xyz[2] = xyz[3] = pt[1]; xyz[4] = xyz[5] = pt[2]; continue; } - for (Int_t j=0; j<3; j++) { - if (pt[j] < xyz[2*j]) xyz[2*j]=pt[j]; - if (pt[j] > xyz[2*j+1]) xyz[2*j+1]=pt[j]; + for (Int_t j = 0; j < 3; j++) { + if (pt[j] < xyz[2 * j]) + xyz[2 * j] = pt[j]; + if (pt[j] > xyz[2 * j + 1]) + xyz[2 * j + 1] = pt[j]; } } - fBoxes[6*id] = 0.5*(xyz[1]-xyz[0]); // dX - fBoxes[6*id+1] = 0.5*(xyz[3]-xyz[2]); // dY - fBoxes[6*id+2] = 0.5*(xyz[5]-xyz[4]); // dZ - fBoxes[6*id+3] = 0.5*(xyz[0]+xyz[1]); // Ox - fBoxes[6*id+4] = 0.5*(xyz[2]+xyz[3]); // Oy - fBoxes[6*id+5] = 0.5*(xyz[4]+xyz[5]); // Oz + fBoxes[6 * id] = 0.5 * (xyz[1] - xyz[0]); // dX + fBoxes[6 * id + 1] = 0.5 * (xyz[3] - xyz[2]); // dY + fBoxes[6 * id + 2] = 0.5 * (xyz[5] - xyz[4]); // dZ + fBoxes[6 * id + 3] = 0.5 * (xyz[0] + xyz[1]); // Ox + fBoxes[6 * id + 4] = 0.5 * (xyz[2] + xyz[3]); // Oy + fBoxes[6 * id + 5] = 0.5 * (xyz[4] + xyz[5]); // Oz } } @@ -217,8 +240,10 @@ void TGeoVoxelFinder::BuildVoxelLimits() void TGeoVoxelFinder::DaughterToMother(Int_t id, const Double_t *local, Double_t *master) const { TGeoMatrix *mat = fVolume->GetNode(id)->GetMatrix(); - if (!mat) memcpy(master,local,3*sizeof(Double_t)); - else mat->LocalToMaster(local, master); + if (!mat) + memcpy(master, local, 3 * sizeof(Double_t)); + else + mat->LocalToMaster(local, master); } //////////////////////////////////////////////////////////////////////////////// /// Computes squared distance from POINT to the voxel(s) containing node INODE. Returns 0 @@ -227,18 +252,20 @@ void TGeoVoxelFinder::DaughterToMother(Int_t id, const Double_t *local, Double_t Bool_t TGeoVoxelFinder::IsSafeVoxel(const Double_t *point, Int_t inode, Double_t minsafe) const { if (NeedRebuild()) { - TGeoVoxelFinder *vox = (TGeoVoxelFinder*)this; + TGeoVoxelFinder *vox = (TGeoVoxelFinder *)this; vox->Voxelize(); fVolume->FindOverlaps(); } - Double_t dxyz, minsafe2=minsafe*minsafe; - Int_t ist = 6*inode; + Double_t dxyz, minsafe2 = minsafe * minsafe; + Int_t ist = 6 * inode; Int_t i; Double_t rsq = 0; - for (i=0; i<3; i++) { - dxyz = TMath::Abs(point[i]-fBoxes[ist+i+3])-fBoxes[ist+i]; - if (dxyz>-1E-6) rsq+=dxyz*dxyz; - if (rsq > minsafe2*(1.+TGeoShape::Tolerance())) return kTRUE; + for (i = 0; i < 3; i++) { + dxyz = TMath::Abs(point[i] - fBoxes[ist + i + 3]) - fBoxes[ist + i]; + if (dxyz > -1E-6) + rsq += dxyz * dxyz; + if (rsq > minsafe2 * (1. + TGeoShape::Tolerance())) + return kTRUE; } return kFALSE; } @@ -258,31 +285,37 @@ Double_t TGeoVoxelFinder::Efficiency() Double_t effslice = 0; Int_t id; if (fPriority[0]) { - for (id=0; idGetNdaughters(); Int_t *ovlps = 0; - Int_t *otmp = new Int_t[nd-1]; + Int_t *otmp = new Int_t[nd - 1]; Int_t novlp = 0; TGeoNode *node = fVolume->GetNode(inode); - xmin = fBoxes[6*inode+3] - fBoxes[6*inode]; - xmax = fBoxes[6*inode+3] + fBoxes[6*inode]; - ymin = fBoxes[6*inode+4] - fBoxes[6*inode+1]; - ymax = fBoxes[6*inode+4] + fBoxes[6*inode+1]; - zmin = fBoxes[6*inode+5] - fBoxes[6*inode+2]; - zmax = fBoxes[6*inode+5] + fBoxes[6*inode+2]; + xmin = fBoxes[6 * inode + 3] - fBoxes[6 * inode]; + xmax = fBoxes[6 * inode + 3] + fBoxes[6 * inode]; + ymin = fBoxes[6 * inode + 4] - fBoxes[6 * inode + 1]; + ymax = fBoxes[6 * inode + 4] + fBoxes[6 * inode + 1]; + zmin = fBoxes[6 * inode + 5] - fBoxes[6 * inode + 2]; + zmax = fBoxes[6 * inode + 5] + fBoxes[6 * inode + 2]; // loop on brothers - for (Int_t ib=0; ibSetOverlaps(ovlps, 0); return; } ovlps = new Int_t[novlp]; - memcpy(ovlps, otmp, novlp*sizeof(Int_t)); - delete [] otmp; + memcpy(ovlps, otmp, novlp * sizeof(Int_t)); + delete[] otmp; node->SetOverlaps(ovlps, novlp); } @@ -350,37 +388,41 @@ Bool_t TGeoVoxelFinder::GetIndices(const Double_t *point, TGeoStateInfo &td) td.fVoxSlices[0] = -2; // -2 means 'all daughters in slice' td.fVoxSlices[1] = -2; td.fVoxSlices[2] = -2; - Bool_t flag=kTRUE; + Bool_t flag = kTRUE; if (fPriority[0]) { td.fVoxSlices[0] = TMath::BinarySearch(fIbx, fXb, point[0]); - if ((td.fVoxSlices[0]<0) || (td.fVoxSlices[0]>=fIbx-1)) { + if ((td.fVoxSlices[0] < 0) || (td.fVoxSlices[0] >= fIbx - 1)) { // outside slices - flag=kFALSE; + flag = kFALSE; } else { - if (fPriority[0]==2) { + if (fPriority[0] == 2) { // nothing in current slice - if (!fNsliceX[td.fVoxSlices[0]]) flag = kFALSE; + if (!fNsliceX[td.fVoxSlices[0]]) + flag = kFALSE; } } } if (fPriority[1]) { td.fVoxSlices[1] = TMath::BinarySearch(fIby, fYb, point[1]); - if ((td.fVoxSlices[1]<0) || (td.fVoxSlices[1]>=fIby-1)) { + if ((td.fVoxSlices[1] < 0) || (td.fVoxSlices[1] >= fIby - 1)) { // outside slices - flag=kFALSE; + flag = kFALSE; } else { - if (fPriority[1]==2) { + if (fPriority[1] == 2) { // nothing in current slice - if (!fNsliceY[td.fVoxSlices[1]]) flag = kFALSE; + if (!fNsliceY[td.fVoxSlices[1]]) + flag = kFALSE; } } } if (fPriority[2]) { td.fVoxSlices[2] = TMath::BinarySearch(fIbz, fZb, point[2]); - if ((td.fVoxSlices[2]<0) || (td.fVoxSlices[2]>=fIbz-1)) return kFALSE; - if (fPriority[2]==2) { + if ((td.fVoxSlices[2] < 0) || (td.fVoxSlices[2] >= fIbz - 1)) + return kFALSE; + if (fPriority[2] == 2) { // nothing in current slice - if (!fNsliceZ[td.fVoxSlices[2]]) return kFALSE; + if (!fNsliceZ[td.fVoxSlices[2]]) + return kFALSE; } } return flag; @@ -394,13 +436,14 @@ Int_t *TGeoVoxelFinder::GetExtraX(Int_t islice, Bool_t left, Int_t &nextra) cons { Int_t *list = 0; nextra = 0; - if (fPriority[0]!=2) return list; + if (fPriority[0] != 2) + return list; if (left) { nextra = fExtraX[fOEx[islice]]; - list = &fExtraX[fOEx[islice]+2]; + list = &fExtraX[fOEx[islice] + 2]; } else { - nextra = fExtraX[fOEx[islice]+1]; - list = &fExtraX[fOEx[islice]+2+fExtraX[fOEx[islice]]]; + nextra = fExtraX[fOEx[islice] + 1]; + list = &fExtraX[fOEx[islice] + 2 + fExtraX[fOEx[islice]]]; } return list; } @@ -413,13 +456,14 @@ Int_t *TGeoVoxelFinder::GetExtraY(Int_t islice, Bool_t left, Int_t &nextra) cons { Int_t *list = 0; nextra = 0; - if (fPriority[1]!=2) return list; + if (fPriority[1] != 2) + return list; if (left) { nextra = fExtraY[fOEy[islice]]; - list = &fExtraY[fOEy[islice]+2]; + list = &fExtraY[fOEy[islice] + 2]; } else { - nextra = fExtraY[fOEy[islice]+1]; - list = &fExtraY[fOEy[islice]+2+fExtraY[fOEy[islice]]]; + nextra = fExtraY[fOEy[islice] + 1]; + list = &fExtraY[fOEy[islice] + 2 + fExtraY[fOEy[islice]]]; } return list; } @@ -432,13 +476,14 @@ Int_t *TGeoVoxelFinder::GetExtraZ(Int_t islice, Bool_t left, Int_t &nextra) cons { Int_t *list = 0; nextra = 0; - if (fPriority[2]!=2) return list; + if (fPriority[2] != 2) + return list; if (left) { nextra = fExtraZ[fOEz[islice]]; - list = &fExtraZ[fOEz[islice]+2]; + list = &fExtraZ[fOEz[islice] + 2]; } else { - nextra = fExtraZ[fOEz[islice]+1]; - list = &fExtraZ[fOEz[islice]+2+fExtraZ[fOEz[islice]]]; + nextra = fExtraZ[fOEz[islice] + 1]; + list = &fExtraZ[fOEz[islice] + 2 + fExtraZ[fOEz[islice]]]; } return list; } @@ -452,12 +497,13 @@ Int_t *TGeoVoxelFinder::GetValidExtra(Int_t *list, Int_t &ncheck, TGeoStateInfo Int_t icand; UInt_t bitnumber, loc; UChar_t bit, byte; - for (icand=0; icand>3; - bit = bitnumber%8; - byte = (~td.fVoxBits1[loc]) & (1<> 3; + bit = bitnumber % 8; + byte = (~td.fVoxBits1[loc]) & (1 << bit); + if (byte) + td.fVoxCheckList[td.fVoxNcandidates++] = list[icand]; } ncheck = td.fVoxNcandidates; return td.fVoxCheckList; @@ -472,12 +518,13 @@ Int_t *TGeoVoxelFinder::GetValidExtra(Int_t /*n1*/, UChar_t *array1, Int_t *list Int_t icand; UInt_t bitnumber, loc; UChar_t bit, byte; - for (icand=0; icand>3; - bit = bitnumber%8; - byte = (~td.fVoxBits1[loc]) & array1[loc] & (1<> 3; + bit = bitnumber % 8; + byte = (~td.fVoxBits1[loc]) & array1[loc] & (1 << bit); + if (byte) + td.fVoxCheckList[td.fVoxNcandidates++] = list[icand]; } ncheck = td.fVoxNcandidates; return td.fVoxCheckList; @@ -486,18 +533,20 @@ Int_t *TGeoVoxelFinder::GetValidExtra(Int_t /*n1*/, UChar_t *array1, Int_t *list //////////////////////////////////////////////////////////////////////////////// /// Get extra candidates that are contained in array1 but not in current check list -Int_t *TGeoVoxelFinder::GetValidExtra(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t *list, Int_t &ncheck, TGeoStateInfo &td) +Int_t *TGeoVoxelFinder::GetValidExtra(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t *list, + Int_t &ncheck, TGeoStateInfo &td) { td.fVoxNcandidates = 0; Int_t icand; UInt_t bitnumber, loc; UChar_t bit, byte; - for (icand=0; icand>3; - bit = bitnumber%8; - byte = (~td.fVoxBits1[loc]) & array1[loc] & array2[loc] & (1<> 3; + bit = bitnumber % 8; + byte = (~td.fVoxBits1[loc]) & array1[loc] & array2[loc] & (1 << bit); + if (byte) + td.fVoxCheckList[td.fVoxNcandidates++] = list[icand]; } ncheck = td.fVoxNcandidates; return td.fVoxCheckList; @@ -514,19 +563,22 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, fVolume->FindOverlaps(); } ncheck = 0; - if (td.fVoxLimits[0]<0) return 0; - if (td.fVoxLimits[1]<0) return 0; - if (td.fVoxLimits[2]<0) return 0; + if (td.fVoxLimits[0] < 0) + return 0; + if (td.fVoxLimits[1] < 0) + return 0; + if (td.fVoxLimits[2] < 0) + return 0; Int_t dind[3]; // new slices //---> start from old slices - memcpy(&dind[0], &td.fVoxSlices[0], 3*sizeof(Int_t)); + memcpy(&dind[0], &td.fVoxSlices[0], 3 * sizeof(Int_t)); Double_t dmin[3]; // distances to get to next X,Y, Z slices. dmin[0] = dmin[1] = dmin[2] = TGeoShape::Big(); //---> max. possible step to be considered Double_t maxstep = TMath::Min(gGeoManager->GetStep(), td.fVoxLimits[TMath::LocMin(3, td.fVoxLimits)]); -// printf("1- maxstep=%g\n", maxstep); - Bool_t isXlimit=kFALSE, isYlimit=kFALSE, isZlimit=kFALSE; - Bool_t isForcedX=kFALSE, isForcedY=kFALSE, isForcedZ=kFALSE; + // printf("1- maxstep=%g\n", maxstep); + Bool_t isXlimit = kFALSE, isYlimit = kFALSE, isZlimit = kFALSE; + Bool_t isForcedX = kFALSE, isForcedY = kFALSE, isForcedZ = kFALSE; Double_t dforced[3]; dforced[0] = dforced[1] = dforced[2] = TGeoShape::Big(); Int_t iforced = 0; @@ -535,39 +587,43 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, if (fPriority[0] && td.fVoxInc[0]) { //---> increment/decrement slice dind[0] += td.fVoxInc[0]; - if (td.fVoxInc[0]==1) { - if (dind[0]<0 || dind[0]>fIbx-1) return 0; // outside range - dmin[0] = (fXb[dind[0]]-point[0])*td.fVoxInvdir[0]; + if (td.fVoxInc[0] == 1) { + if (dind[0] < 0 || dind[0] > fIbx - 1) + return 0; // outside range + dmin[0] = (fXb[dind[0]] - point[0]) * td.fVoxInvdir[0]; } else { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>fIbx-1) return 0; // outside range - dmin[0] = (fXb[td.fVoxSlices[0]]-point[0])*td.fVoxInvdir[0]; + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] > fIbx - 1) + return 0; // outside range + dmin[0] = (fXb[td.fVoxSlices[0]] - point[0]) * td.fVoxInvdir[0]; } - isXlimit = (dmin[0]>maxstep)?kTRUE:kFALSE; -// printf("---> X : priority=%i, slice=%i/%i inc=%i\n", -// fPriority[0], td.fVoxSlices[0], fIbx-2, td.fVoxInc[0]); -// printf("2- step to next X (%i) = %g\n", (Int_t)isXlimit, dmin[0]); + isXlimit = (dmin[0] > maxstep) ? kTRUE : kFALSE; + // printf("---> X : priority=%i, slice=%i/%i inc=%i\n", + // fPriority[0], td.fVoxSlices[0], fIbx-2, td.fVoxInc[0]); + // printf("2- step to next X (%i) = %g\n", (Int_t)isXlimit, dmin[0]); //---> check if propagation to next slice on this axis is forced - if ((td.fVoxSlices[0]==-1) || (td.fVoxSlices[0]==fIbx-1)) { + if ((td.fVoxSlices[0] == -1) || (td.fVoxSlices[0] == fIbx - 1)) { isForcedX = kTRUE; dforced[0] = dmin[0]; iforced++; -// printf(" FORCED 1\n"); - if (isXlimit) return 0; + // printf(" FORCED 1\n"); + if (isXlimit) + return 0; } else { - if (fPriority[0]==2) { + if (fPriority[0] == 2) { // if no candidates in current slice, force next slice - if (fNsliceX[td.fVoxSlices[0]]==0) { + if (fNsliceX[td.fVoxSlices[0]] == 0) { isForcedX = kTRUE; dforced[0] = dmin[0]; iforced++; -// printf(" FORCED 2\n"); - if (isXlimit) return 0; + // printf(" FORCED 2\n"); + if (isXlimit) + return 0; } } } } else { // no slices on this axis -> bounding box limit -// printf(" No slice on X\n"); + // printf(" No slice on X\n"); dmin[0] = td.fVoxLimits[0]; isXlimit = kTRUE; } @@ -575,40 +631,44 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, if (fPriority[1] && td.fVoxInc[1]) { //---> increment/decrement slice dind[1] += td.fVoxInc[1]; - if (td.fVoxInc[1]==1) { - if (dind[1]<0 || dind[1]>fIby-1) return 0; // outside range - dmin[1] = (fYb[dind[1]]-point[1])*td.fVoxInvdir[1]; + if (td.fVoxInc[1] == 1) { + if (dind[1] < 0 || dind[1] > fIby - 1) + return 0; // outside range + dmin[1] = (fYb[dind[1]] - point[1]) * td.fVoxInvdir[1]; } else { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>fIby-1) return 0; // outside range - dmin[1] = (fYb[td.fVoxSlices[1]]-point[1])*td.fVoxInvdir[1]; + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] > fIby - 1) + return 0; // outside range + dmin[1] = (fYb[td.fVoxSlices[1]] - point[1]) * td.fVoxInvdir[1]; } - isYlimit = (dmin[1]>maxstep)?kTRUE:kFALSE; -// printf("---> Y : priority=%i, slice=%i/%i inc=%i\n", -// fPriority[1], td.fVoxSlices[1], fIby-2, td.fVoxInc[1]); -// printf("3- step to next Y (%i) = %g\n", (Int_t)isYlimit, dmin[1]); + isYlimit = (dmin[1] > maxstep) ? kTRUE : kFALSE; + // printf("---> Y : priority=%i, slice=%i/%i inc=%i\n", + // fPriority[1], td.fVoxSlices[1], fIby-2, td.fVoxInc[1]); + // printf("3- step to next Y (%i) = %g\n", (Int_t)isYlimit, dmin[1]); //---> check if propagation to next slice on this axis is forced - if ((td.fVoxSlices[1]==-1) || (td.fVoxSlices[1]==fIby-1)) { + if ((td.fVoxSlices[1] == -1) || (td.fVoxSlices[1] == fIby - 1)) { isForcedY = kTRUE; dforced[1] = dmin[1]; iforced++; -// printf(" FORCED 1\n"); - if (isYlimit) return 0; + // printf(" FORCED 1\n"); + if (isYlimit) + return 0; } else { - if (fPriority[1]==2) { + if (fPriority[1] == 2) { // if no candidates in current slice, force next slice - if (fNsliceY[td.fVoxSlices[1]]==0) { + if (fNsliceY[td.fVoxSlices[1]] == 0) { isForcedY = kTRUE; dforced[1] = dmin[1]; iforced++; -// printf(" FORCED 2\n"); - if (isYlimit) return 0; + // printf(" FORCED 2\n"); + if (isYlimit) + return 0; } } } } else { // no slices on this axis -> bounding box limit -// printf(" No slice on Y\n"); + // printf(" No slice on Y\n"); dmin[1] = td.fVoxLimits[1]; isYlimit = kTRUE; } @@ -616,40 +676,44 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, if (fPriority[2] && td.fVoxInc[2]) { //---> increment/decrement slice dind[2] += td.fVoxInc[2]; - if (td.fVoxInc[2]==1) { - if (dind[2]<0 || dind[2]>fIbz-1) return 0; // outside range - dmin[2] = (fZb[dind[2]]-point[2])*td.fVoxInvdir[2]; + if (td.fVoxInc[2] == 1) { + if (dind[2] < 0 || dind[2] > fIbz - 1) + return 0; // outside range + dmin[2] = (fZb[dind[2]] - point[2]) * td.fVoxInvdir[2]; } else { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>fIbz-1) return 0; // outside range - dmin[2] = (fZb[td.fVoxSlices[2]]-point[2])*td.fVoxInvdir[2]; + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] > fIbz - 1) + return 0; // outside range + dmin[2] = (fZb[td.fVoxSlices[2]] - point[2]) * td.fVoxInvdir[2]; } - isZlimit = (dmin[2]>maxstep)?kTRUE:kFALSE; -// printf("---> Z : priority=%i, slice=%i/%i inc=%i\n", -// fPriority[2], td.fVoxSlices[2], fIbz-2, td.fVoxInc[2]); -// printf("4- step to next Z (%i) = %g\n", (Int_t)isZlimit, dmin[2]); + isZlimit = (dmin[2] > maxstep) ? kTRUE : kFALSE; + // printf("---> Z : priority=%i, slice=%i/%i inc=%i\n", + // fPriority[2], td.fVoxSlices[2], fIbz-2, td.fVoxInc[2]); + // printf("4- step to next Z (%i) = %g\n", (Int_t)isZlimit, dmin[2]); //---> check if propagation to next slice on this axis is forced - if ((td.fVoxSlices[2]==-1) || (td.fVoxSlices[2]==fIbz-1)) { + if ((td.fVoxSlices[2] == -1) || (td.fVoxSlices[2] == fIbz - 1)) { isForcedZ = kTRUE; dforced[2] = dmin[2]; iforced++; -// printf(" FORCED 1\n"); - if (isZlimit) return 0; + // printf(" FORCED 1\n"); + if (isZlimit) + return 0; } else { - if (fPriority[2]==2) { + if (fPriority[2] == 2) { // if no candidates in current slice, force next slice - if (fNsliceZ[td.fVoxSlices[2]]==0) { + if (fNsliceZ[td.fVoxSlices[2]] == 0) { isForcedZ = kTRUE; dforced[2] = dmin[2]; iforced++; -// printf(" FORCED 2\n"); - if (isZlimit) return 0; + // printf(" FORCED 2\n"); + if (isZlimit) + return 0; } } } } else { // no slices on this axis -> bounding box limit -// printf(" No slice on Z\n"); + // printf(" No slice on Z\n"); dmin[2] = td.fVoxLimits[2]; isZlimit = kTRUE; } @@ -659,29 +723,29 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, Double_t dslice = 0; Int_t islice = 0; if (iforced) { - // some slice is forced + // some slice is forced if (isForcedX) { - // X forced + // X forced dslice = dforced[0]; islice = 0; if (isForcedY) { - // X+Y forced - if (dforced[1]>dslice) { + // X+Y forced + if (dforced[1] > dslice) { dslice = dforced[1]; islice = 1; } if (isForcedZ) { - // X+Y+Z forced - if (dforced[2]>dslice) { + // X+Y+Z forced + if (dforced[2] > dslice) { dslice = dforced[2]; islice = 2; } } } else { - // X forced + // X forced if (isForcedZ) { - // X+Z forced - if (dforced[2]>dslice) { + // X+Z forced + if (dforced[2] > dslice) { dslice = dforced[2]; islice = 2; } @@ -689,138 +753,109 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, } } else { if (isForcedY) { - // Y forced + // Y forced dslice = dforced[1]; islice = 1; if (isForcedZ) { - // Y+Z forced - if (dforced[2]>dslice) { + // Y+Z forced + if (dforced[2] > dslice) { dslice = dforced[2]; islice = 2; } } } else { - // Z forced + // Z forced dslice = dforced[2]; islice = 2; } } } else { - // Nothing forced -> get minimum distance + // Nothing forced -> get minimum distance islice = TMath::LocMin(3, dmin); dslice = dmin[islice]; - if (dslice>=maxstep) { -// printf("DSLICE > MAXSTEP -> EXIT\n"); + if (dslice >= maxstep) { + // printf("DSLICE > MAXSTEP -> EXIT\n"); return 0; } } -// printf("5- islicenext=%i DSLICE=%g\n", islice, dslice); + // printf("5- islicenext=%i DSLICE=%g\n", islice, dslice); Double_t xptnew; Int_t *new_list; // list of new candidates UChar_t *slice1 = 0; UChar_t *slice2 = 0; - Int_t ndd[2] = {0,0}; + Int_t ndd[2] = {0, 0}; Int_t islices = 0; Bool_t left; switch (islice) { - case 0: - if (isXlimit) return 0; - // increment/decrement X slice - td.fVoxSlices[0]=dind[0]; - if (iforced) { - // we have to recompute Y and Z slices - if (dslice>td.fVoxLimits[1]) return 0; - if (dslice>td.fVoxLimits[2]) return 0; - if ((dslice>dmin[1]) && td.fVoxInc[1]) { - xptnew = point[1]+dslice/td.fVoxInvdir[1]; - // printf(" recomputing Y slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[1] += td.fVoxInc[1]; - if (td.fVoxInc[1]==1) { - if (td.fVoxSlices[1]<-1 || td.fVoxSlices[1]>fIby-2) break; // outside range - if (fYb[td.fVoxSlices[1]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>fIby-1) break; // outside range - if (fYb[td.fVoxSlices[1]]<= xptnew) break; - } - } - // printf(" %i/%i\n", td.fVoxSlices[1], fIby-2); - } - if ((dslice>dmin[2]) && td.fVoxInc[2]) { - xptnew = point[2]+dslice/td.fVoxInvdir[2]; - // printf(" recomputing Z slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[2] += td.fVoxInc[2]; - if (td.fVoxInc[2]==1) { - if (td.fVoxSlices[2]<-1 || td.fVoxSlices[2]>fIbz-2) break; // outside range - if (fZb[td.fVoxSlices[2]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>fIbz-1) break; // outside range - if (fZb[td.fVoxSlices[2]]<= xptnew) break; - } + case 0: + if (isXlimit) + return 0; + // increment/decrement X slice + td.fVoxSlices[0] = dind[0]; + if (iforced) { + // we have to recompute Y and Z slices + if (dslice > td.fVoxLimits[1]) + return 0; + if (dslice > td.fVoxLimits[2]) + return 0; + if ((dslice > dmin[1]) && td.fVoxInc[1]) { + xptnew = point[1] + dslice / td.fVoxInvdir[1]; + // printf(" recomputing Y slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[1] += td.fVoxInc[1]; + if (td.fVoxInc[1] == 1) { + if (td.fVoxSlices[1] < -1 || td.fVoxSlices[1] > fIby - 2) + break; // outside range + if (fYb[td.fVoxSlices[1] + 1] >= xptnew) + break; + } else { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] > fIby - 1) + break; // outside range + if (fYb[td.fVoxSlices[1]] <= xptnew) + break; } - // printf(" %i/%i\n", td.fVoxSlices[2], fIbz-2); } + // printf(" %i/%i\n", td.fVoxSlices[1], fIby-2); } - // new indices are set -> Get new candidates - if (fPriority[0]==1) { - // we are entering the unique slice on this axis - //---> intersect and store Y and Z - if (fPriority[1]==2) { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>=fIby-1) return td.fVoxCheckList; // outside range - ndd[0] = fNsliceY[td.fVoxSlices[1]]; - if (!ndd[0]) return td.fVoxCheckList; - slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; - islices++; - } - if (fPriority[2]==2) { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>=fIbz-1) return td.fVoxCheckList; // outside range - ndd[1] = fNsliceZ[td.fVoxSlices[2]]; - if (!ndd[1]) return td.fVoxCheckList; - islices++; - if (slice1) { - slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + if ((dslice > dmin[2]) && td.fVoxInc[2]) { + xptnew = point[2] + dslice / td.fVoxInvdir[2]; + // printf(" recomputing Z slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[2] += td.fVoxInc[2]; + if (td.fVoxInc[2] == 1) { + if (td.fVoxSlices[2] < -1 || td.fVoxSlices[2] > fIbz - 2) + break; // outside range + if (fZb[td.fVoxSlices[2] + 1] >= xptnew) + break; } else { - slice1 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; - ndd[0] = ndd[1]; + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] > fIbz - 1) + break; // outside range + if (fZb[td.fVoxSlices[2]] <= xptnew) + break; } } - if (islices<=1) { - IntersectAndStore(ndd[0], slice1, td); - } else { - IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); - } - ncheck = td.fVoxNcandidates; - return td.fVoxCheckList; + // printf(" %i/%i\n", td.fVoxSlices[2], fIbz-2); } - // We got into a new slice -> Get only new candidates - left = (td.fVoxInc[0]>0)?kTRUE:kFALSE; - new_list = GetExtraX(td.fVoxSlices[0], left, ncheck); -// printf(" New list on X : %i new candidates\n", ncheck); - if (!ncheck) return td.fVoxCheckList; - if (fPriority[1]==2) { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>=fIby-1) { - ncheck = 0; + } + // new indices are set -> Get new candidates + if (fPriority[0] == 1) { + // we are entering the unique slice on this axis + //---> intersect and store Y and Z + if (fPriority[1] == 2) { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] >= fIby - 1) return td.fVoxCheckList; // outside range - } ndd[0] = fNsliceY[td.fVoxSlices[1]]; - if (!ndd[0]) { - ncheck = 0; + if (!ndd[0]) return td.fVoxCheckList; - } slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; islices++; } - if (fPriority[2]==2) { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>=fIbz-1) { - ncheck = 0; + if (fPriority[2] == 2) { + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] >= fIbz - 1) return td.fVoxCheckList; // outside range - } ndd[1] = fNsliceZ[td.fVoxSlices[2]]; - if (!ndd[1]) { - ncheck = 0; + if (!ndd[1]) return td.fVoxCheckList; - } islices++; if (slice1) { slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; @@ -829,110 +864,127 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, ndd[0] = ndd[1]; } } - if (!islices) return GetValidExtra(new_list, ncheck, td); - if (islices==1) { - return GetValidExtra(ndd[0], slice1, new_list, ncheck,td); + if (islices <= 1) { + IntersectAndStore(ndd[0], slice1, td); } else { - return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); + } + ncheck = td.fVoxNcandidates; + return td.fVoxCheckList; + } + // We got into a new slice -> Get only new candidates + left = (td.fVoxInc[0] > 0) ? kTRUE : kFALSE; + new_list = GetExtraX(td.fVoxSlices[0], left, ncheck); + // printf(" New list on X : %i new candidates\n", ncheck); + if (!ncheck) + return td.fVoxCheckList; + if (fPriority[1] == 2) { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] >= fIby - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[0] = fNsliceY[td.fVoxSlices[1]]; + if (!ndd[0]) { + ncheck = 0; + return td.fVoxCheckList; } - case 1: - if (isYlimit) return 0; - // increment/decrement Y slice - td.fVoxSlices[1]=dind[1]; - if (iforced) { + slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; + islices++; + } + if (fPriority[2] == 2) { + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] >= fIbz - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[1] = fNsliceZ[td.fVoxSlices[2]]; + if (!ndd[1]) { + ncheck = 0; + return td.fVoxCheckList; + } + islices++; + if (slice1) { + slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + } else { + slice1 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + ndd[0] = ndd[1]; + } + } + if (!islices) + return GetValidExtra(new_list, ncheck, td); + if (islices == 1) { + return GetValidExtra(ndd[0], slice1, new_list, ncheck, td); + } else { + return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + } + case 1: + if (isYlimit) + return 0; + // increment/decrement Y slice + td.fVoxSlices[1] = dind[1]; + if (iforced) { // we have to recompute X and Z slices - if (dslice>td.fVoxLimits[0]) return 0; - if (dslice>td.fVoxLimits[2]) return 0; - if ((dslice>dmin[0]) && td.fVoxInc[0]) { - xptnew = point[0]+dslice/td.fVoxInvdir[0]; -// printf(" recomputing X slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[0] += td.fVoxInc[0]; - if (td.fVoxInc[0]==1) { - if (td.fVoxSlices[0]<-1 || td.fVoxSlices[0]>fIbx-2) break; // outside range - if (fXb[td.fVoxSlices[0]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>fIbx-1) break; // outside range - if (fXb[td.fVoxSlices[0]]<= xptnew) break; - } - } -// printf(" %i/%i\n", td.fVoxSlices[0], fIbx-2); - } - if ((dslice>dmin[2]) && td.fVoxInc[2]) { - xptnew = point[2]+dslice/td.fVoxInvdir[2]; -// printf(" recomputing Z slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[2] += td.fVoxInc[2]; - if (td.fVoxInc[2]==1) { - if (td.fVoxSlices[2]<-1 || td.fVoxSlices[2]>fIbz-2) break; // outside range - if (fZb[td.fVoxSlices[2]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>fIbz-1) break; // outside range - if (fZb[td.fVoxSlices[2]]<= xptnew) break; - } + if (dslice > td.fVoxLimits[0]) + return 0; + if (dslice > td.fVoxLimits[2]) + return 0; + if ((dslice > dmin[0]) && td.fVoxInc[0]) { + xptnew = point[0] + dslice / td.fVoxInvdir[0]; + // printf(" recomputing X slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[0] += td.fVoxInc[0]; + if (td.fVoxInc[0] == 1) { + if (td.fVoxSlices[0] < -1 || td.fVoxSlices[0] > fIbx - 2) + break; // outside range + if (fXb[td.fVoxSlices[0] + 1] >= xptnew) + break; + } else { + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] > fIbx - 1) + break; // outside range + if (fXb[td.fVoxSlices[0]] <= xptnew) + break; } -// printf(" %i/%i\n", td.fVoxSlices[2], fIbz-2); } + // printf(" %i/%i\n", td.fVoxSlices[0], fIbx-2); } - // new indices are set -> Get new candidates - if (fPriority[1]==1) { - // we are entering the unique slice on this axis - //---> intersect and store X and Z - if (fPriority[0]==2) { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>=fIbx-1) return td.fVoxCheckList; // outside range - ndd[0] = fNsliceX[td.fVoxSlices[0]]; - if (!ndd[0]) return td.fVoxCheckList; - slice1 = &fIndcX[fOBx[td.fVoxSlices[0]]]; - islices++; - } - if (fPriority[2]==2) { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>=fIbz-1) return td.fVoxCheckList; // outside range - ndd[1] = fNsliceZ[td.fVoxSlices[2]]; - if (!ndd[1]) return td.fVoxCheckList; - islices++; - if (slice1) { - slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + if ((dslice > dmin[2]) && td.fVoxInc[2]) { + xptnew = point[2] + dslice / td.fVoxInvdir[2]; + // printf(" recomputing Z slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[2] += td.fVoxInc[2]; + if (td.fVoxInc[2] == 1) { + if (td.fVoxSlices[2] < -1 || td.fVoxSlices[2] > fIbz - 2) + break; // outside range + if (fZb[td.fVoxSlices[2] + 1] >= xptnew) + break; } else { - slice1 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; - ndd[0] = ndd[1]; + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] > fIbz - 1) + break; // outside range + if (fZb[td.fVoxSlices[2]] <= xptnew) + break; } } - if (islices<=1) { - IntersectAndStore(ndd[0], slice1, td); - } else { - IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); - } - ncheck = td.fVoxNcandidates; - return td.fVoxCheckList; + // printf(" %i/%i\n", td.fVoxSlices[2], fIbz-2); } - // We got into a new slice -> Get only new candidates - left = (td.fVoxInc[1]>0)?kTRUE:kFALSE; - new_list = GetExtraY(td.fVoxSlices[1], left, ncheck); -// printf(" New list on Y : %i new candidates\n", ncheck); - if (!ncheck) return td.fVoxCheckList; - if (fPriority[0]==2) { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>=fIbx-1) { - ncheck = 0; + } + // new indices are set -> Get new candidates + if (fPriority[1] == 1) { + // we are entering the unique slice on this axis + //---> intersect and store X and Z + if (fPriority[0] == 2) { + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] >= fIbx - 1) return td.fVoxCheckList; // outside range - } ndd[0] = fNsliceX[td.fVoxSlices[0]]; - if (!ndd[0]) { - ncheck = 0; + if (!ndd[0]) return td.fVoxCheckList; - } slice1 = &fIndcX[fOBx[td.fVoxSlices[0]]]; islices++; } - if (fPriority[2]==2) { - if (td.fVoxSlices[2]<0 || td.fVoxSlices[2]>=fIbz-1) { - ncheck = 0; + if (fPriority[2] == 2) { + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] >= fIbz - 1) return td.fVoxCheckList; // outside range - } ndd[1] = fNsliceZ[td.fVoxSlices[2]]; - if (!ndd[1]) { - ncheck = 0; + if (!ndd[1]) return td.fVoxCheckList; - } islices++; if (slice1) { slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; @@ -941,110 +993,127 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, ndd[0] = ndd[1]; } } - if (!islices) return GetValidExtra(new_list, ncheck, td); - if (islices==1) { - return GetValidExtra(ndd[0], slice1, new_list, ncheck, td); + if (islices <= 1) { + IntersectAndStore(ndd[0], slice1, td); } else { - return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); } - case 2: - if (isZlimit) return 0; - // increment/decrement Z slice - td.fVoxSlices[2]=dind[2]; - if (iforced) { - // we have to recompute Y and X slices - if (dslice>td.fVoxLimits[1]) return 0; - if (dslice>td.fVoxLimits[0]) return 0; - if ((dslice>dmin[1]) && td.fVoxInc[1]) { - xptnew = point[1]+dslice/td.fVoxInvdir[1]; - // printf(" recomputing Y slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[1] += td.fVoxInc[1]; - if (td.fVoxInc[1]==1) { - if (td.fVoxSlices[1]<-1 || td.fVoxSlices[1]>fIby-2) break; // outside range - if (fYb[td.fVoxSlices[1]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>fIby-1) break; // outside range - if (fYb[td.fVoxSlices[1]]<= xptnew) break; - } - } - // printf(" %i/%i\n", td.fVoxSlices[1], fIby-2); - } - if ((dslice>dmin[0]) && td.fVoxInc[0]) { - xptnew = point[0]+dslice/td.fVoxInvdir[0]; - // printf(" recomputing X slice, pos=%g\n", xptnew); - while (1) { - td.fVoxSlices[0] += td.fVoxInc[0]; - if (td.fVoxInc[0]==1) { - if (td.fVoxSlices[0]<-1 || td.fVoxSlices[0]>fIbx-2) break; // outside range - if (fXb[td.fVoxSlices[0]+1]>=xptnew) break; - } else { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>fIbx-1) break; // outside range - if (fXb[td.fVoxSlices[0]]<= xptnew) break; - } + ncheck = td.fVoxNcandidates; + return td.fVoxCheckList; + } + // We got into a new slice -> Get only new candidates + left = (td.fVoxInc[1] > 0) ? kTRUE : kFALSE; + new_list = GetExtraY(td.fVoxSlices[1], left, ncheck); + // printf(" New list on Y : %i new candidates\n", ncheck); + if (!ncheck) + return td.fVoxCheckList; + if (fPriority[0] == 2) { + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] >= fIbx - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[0] = fNsliceX[td.fVoxSlices[0]]; + if (!ndd[0]) { + ncheck = 0; + return td.fVoxCheckList; + } + slice1 = &fIndcX[fOBx[td.fVoxSlices[0]]]; + islices++; + } + if (fPriority[2] == 2) { + if (td.fVoxSlices[2] < 0 || td.fVoxSlices[2] >= fIbz - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[1] = fNsliceZ[td.fVoxSlices[2]]; + if (!ndd[1]) { + ncheck = 0; + return td.fVoxCheckList; + } + islices++; + if (slice1) { + slice2 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + } else { + slice1 = &fIndcZ[fOBz[td.fVoxSlices[2]]]; + ndd[0] = ndd[1]; + } + } + if (!islices) + return GetValidExtra(new_list, ncheck, td); + if (islices == 1) { + return GetValidExtra(ndd[0], slice1, new_list, ncheck, td); + } else { + return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + } + case 2: + if (isZlimit) + return 0; + // increment/decrement Z slice + td.fVoxSlices[2] = dind[2]; + if (iforced) { + // we have to recompute Y and X slices + if (dslice > td.fVoxLimits[1]) + return 0; + if (dslice > td.fVoxLimits[0]) + return 0; + if ((dslice > dmin[1]) && td.fVoxInc[1]) { + xptnew = point[1] + dslice / td.fVoxInvdir[1]; + // printf(" recomputing Y slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[1] += td.fVoxInc[1]; + if (td.fVoxInc[1] == 1) { + if (td.fVoxSlices[1] < -1 || td.fVoxSlices[1] > fIby - 2) + break; // outside range + if (fYb[td.fVoxSlices[1] + 1] >= xptnew) + break; + } else { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] > fIby - 1) + break; // outside range + if (fYb[td.fVoxSlices[1]] <= xptnew) + break; } -// printf(" %i/%i\n", td.fVoxSlices[0], fIbx-2); } + // printf(" %i/%i\n", td.fVoxSlices[1], fIby-2); } - // new indices are set -> Get new candidates - if (fPriority[2]==1) { - // we are entering the unique slice on this axis - //---> intersect and store Y and X - if (fPriority[1]==2) { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>=fIby-1) return td.fVoxCheckList; // outside range - ndd[0] = fNsliceY[td.fVoxSlices[1]]; - if (!ndd[0]) return td.fVoxCheckList; - slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; - islices++; - } - if (fPriority[0]==2) { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>=fIbx-1) return td.fVoxCheckList; // outside range - ndd[1] = fNsliceX[td.fVoxSlices[0]]; - if (!ndd[1]) return td.fVoxCheckList; - islices++; - if (slice1) { - slice2 = &fIndcX[fOBx[td.fVoxSlices[0]]]; + if ((dslice > dmin[0]) && td.fVoxInc[0]) { + xptnew = point[0] + dslice / td.fVoxInvdir[0]; + // printf(" recomputing X slice, pos=%g\n", xptnew); + while (1) { + td.fVoxSlices[0] += td.fVoxInc[0]; + if (td.fVoxInc[0] == 1) { + if (td.fVoxSlices[0] < -1 || td.fVoxSlices[0] > fIbx - 2) + break; // outside range + if (fXb[td.fVoxSlices[0] + 1] >= xptnew) + break; } else { - slice1 = &fIndcX[fOBx[td.fVoxSlices[0]]]; - ndd[0] = ndd[1]; + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] > fIbx - 1) + break; // outside range + if (fXb[td.fVoxSlices[0]] <= xptnew) + break; } } - if (islices<=1) { - IntersectAndStore(ndd[0], slice1, td); - } else { - IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); - } - ncheck = td.fVoxNcandidates; - return td.fVoxCheckList; + // printf(" %i/%i\n", td.fVoxSlices[0], fIbx-2); } - // We got into a new slice -> Get only new candidates - left = (td.fVoxInc[2]>0)?kTRUE:kFALSE; - new_list = GetExtraZ(td.fVoxSlices[2], left, ncheck); -// printf(" New list on Z : %i new candidates\n", ncheck); - if (!ncheck) return td.fVoxCheckList; - if (fPriority[1]==2) { - if (td.fVoxSlices[1]<0 || td.fVoxSlices[1]>=fIby-1) { - ncheck = 0; + } + // new indices are set -> Get new candidates + if (fPriority[2] == 1) { + // we are entering the unique slice on this axis + //---> intersect and store Y and X + if (fPriority[1] == 2) { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] >= fIby - 1) return td.fVoxCheckList; // outside range - } ndd[0] = fNsliceY[td.fVoxSlices[1]]; - if (!ndd[0]) { - ncheck = 0; + if (!ndd[0]) return td.fVoxCheckList; - } slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; islices++; } - if (fPriority[0]==2) { - if (td.fVoxSlices[0]<0 || td.fVoxSlices[0]>=fIbx-1) { - ncheck = 0; + if (fPriority[0] == 2) { + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] >= fIbx - 1) return td.fVoxCheckList; // outside range - } ndd[1] = fNsliceX[td.fVoxSlices[0]]; - if (!ndd[1]) { - ncheck = 0; + if (!ndd[1]) return td.fVoxCheckList; - } islices++; if (slice1) { slice2 = &fIndcX[fOBx[td.fVoxSlices[0]]]; @@ -1053,14 +1122,59 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, ndd[0] = ndd[1]; } } - if (!islices) return GetValidExtra(new_list, ncheck, td); - if (islices==1) { - return GetValidExtra(ndd[0], slice1, new_list, ncheck, td); + if (islices <= 1) { + IntersectAndStore(ndd[0], slice1, td); + } else { + IntersectAndStore(ndd[0], slice1, ndd[1], slice2, td); + } + ncheck = td.fVoxNcandidates; + return td.fVoxCheckList; + } + // We got into a new slice -> Get only new candidates + left = (td.fVoxInc[2] > 0) ? kTRUE : kFALSE; + new_list = GetExtraZ(td.fVoxSlices[2], left, ncheck); + // printf(" New list on Z : %i new candidates\n", ncheck); + if (!ncheck) + return td.fVoxCheckList; + if (fPriority[1] == 2) { + if (td.fVoxSlices[1] < 0 || td.fVoxSlices[1] >= fIby - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[0] = fNsliceY[td.fVoxSlices[1]]; + if (!ndd[0]) { + ncheck = 0; + return td.fVoxCheckList; + } + slice1 = &fIndcY[fOBy[td.fVoxSlices[1]]]; + islices++; + } + if (fPriority[0] == 2) { + if (td.fVoxSlices[0] < 0 || td.fVoxSlices[0] >= fIbx - 1) { + ncheck = 0; + return td.fVoxCheckList; // outside range + } + ndd[1] = fNsliceX[td.fVoxSlices[0]]; + if (!ndd[1]) { + ncheck = 0; + return td.fVoxCheckList; + } + islices++; + if (slice1) { + slice2 = &fIndcX[fOBx[td.fVoxSlices[0]]]; } else { - return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + slice1 = &fIndcX[fOBx[td.fVoxSlices[0]]]; + ndd[0] = ndd[1]; } - default: - Error("GetNextCandidates", "Invalid islice=%i inside %s", islice, fVolume->GetName()); + } + if (!islices) + return GetValidExtra(new_list, ncheck, td); + if (islices == 1) { + return GetValidExtra(ndd[0], slice1, new_list, ncheck, td); + } else { + return GetValidExtra(ndd[0], slice1, ndd[1], slice2, new_list, ncheck, td); + } + default: Error("GetNextCandidates", "Invalid islice=%i inside %s", islice, fVolume->GetName()); } return 0; } @@ -1071,132 +1185,129 @@ Int_t *TGeoVoxelFinder::GetNextCandidates(const Double_t *point, Int_t &ncheck, void TGeoVoxelFinder::SortCrossedVoxels(const Double_t *point, const Double_t *dir, TGeoStateInfo &td) { if (NeedRebuild()) { - TGeoVoxelFinder *vox = (TGeoVoxelFinder*)this; + TGeoVoxelFinder *vox = (TGeoVoxelFinder *)this; vox->Voxelize(); fVolume->FindOverlaps(); } td.fVoxCurrent = 0; -// printf("###Sort crossed voxels for %s\n", fVolume->GetName()); + // printf("###Sort crossed voxels for %s\n", fVolume->GetName()); td.fVoxNcandidates = 0; - Int_t loc = 1+((fVolume->GetNdaughters()-1)>>3); -// printf(" LOC=%i\n", loc*sizeof(UChar_t)); -// UChar_t *bits = gGeoManager->GetBits(); + Int_t loc = 1 + ((fVolume->GetNdaughters() - 1) >> 3); + // printf(" LOC=%i\n", loc*sizeof(UChar_t)); + // UChar_t *bits = gGeoManager->GetBits(); memset(td.fVoxBits1, 0, loc); - memset(td.fVoxInc, 0, 3*sizeof(Int_t)); - for (Int_t i=0; i<3; i++) { + memset(td.fVoxInc, 0, 3 * sizeof(Int_t)); + for (Int_t i = 0; i < 3; i++) { td.fVoxInvdir[i] = TGeoShape::Big(); - if (TMath::Abs(dir[i])<1E-10) continue; - td.fVoxInc[i] = (dir[i]>0)?1:-1; - td.fVoxInvdir[i] = 1./dir[i]; + if (TMath::Abs(dir[i]) < 1E-10) + continue; + td.fVoxInc[i] = (dir[i] > 0) ? 1 : -1; + td.fVoxInvdir[i] = 1. / dir[i]; } Bool_t flag = GetIndices(point, td); - TGeoBBox *box = (TGeoBBox*)(fVolume->GetShape()); + TGeoBBox *box = (TGeoBBox *)(fVolume->GetShape()); const Double_t *box_orig = box->GetOrigin(); - if (td.fVoxInc[0]==0) { + if (td.fVoxInc[0] == 0) { td.fVoxLimits[0] = TGeoShape::Big(); } else { - if (td.fVoxSlices[0]==-2) { + if (td.fVoxSlices[0] == -2) { // no slice on this axis -> get limit to bounding box limit - td.fVoxLimits[0] = (box_orig[0]-point[0]+td.fVoxInc[0]*box->GetDX())*td.fVoxInvdir[0]; + td.fVoxLimits[0] = (box_orig[0] - point[0] + td.fVoxInc[0] * box->GetDX()) * td.fVoxInvdir[0]; } else { - if (td.fVoxInc[0]==1) { - td.fVoxLimits[0] = (fXb[fIbx-1]-point[0])*td.fVoxInvdir[0]; + if (td.fVoxInc[0] == 1) { + td.fVoxLimits[0] = (fXb[fIbx - 1] - point[0]) * td.fVoxInvdir[0]; } else { - td.fVoxLimits[0] = (fXb[0]-point[0])*td.fVoxInvdir[0]; + td.fVoxLimits[0] = (fXb[0] - point[0]) * td.fVoxInvdir[0]; } } } - if (td.fVoxInc[1]==0) { + if (td.fVoxInc[1] == 0) { td.fVoxLimits[1] = TGeoShape::Big(); } else { - if (td.fVoxSlices[1]==-2) { + if (td.fVoxSlices[1] == -2) { // no slice on this axis -> get limit to bounding box limit - td.fVoxLimits[1] = (box_orig[1]-point[1]+td.fVoxInc[1]*box->GetDY())*td.fVoxInvdir[1]; + td.fVoxLimits[1] = (box_orig[1] - point[1] + td.fVoxInc[1] * box->GetDY()) * td.fVoxInvdir[1]; } else { - if (td.fVoxInc[1]==1) { - td.fVoxLimits[1] = (fYb[fIby-1]-point[1])*td.fVoxInvdir[1]; + if (td.fVoxInc[1] == 1) { + td.fVoxLimits[1] = (fYb[fIby - 1] - point[1]) * td.fVoxInvdir[1]; } else { - td.fVoxLimits[1] = (fYb[0]-point[1])*td.fVoxInvdir[1]; + td.fVoxLimits[1] = (fYb[0] - point[1]) * td.fVoxInvdir[1]; } } } - if (td.fVoxInc[2]==0) { + if (td.fVoxInc[2] == 0) { td.fVoxLimits[2] = TGeoShape::Big(); } else { - if (td.fVoxSlices[2]==-2) { + if (td.fVoxSlices[2] == -2) { // no slice on this axis -> get limit to bounding box limit - td.fVoxLimits[2] = (box_orig[2]-point[2]+td.fVoxInc[2]*box->GetDZ())*td.fVoxInvdir[2]; + td.fVoxLimits[2] = (box_orig[2] - point[2] + td.fVoxInc[2] * box->GetDZ()) * td.fVoxInvdir[2]; } else { - if (td.fVoxInc[2]==1) { - td.fVoxLimits[2] = (fZb[fIbz-1]-point[2])*td.fVoxInvdir[2]; + if (td.fVoxInc[2] == 1) { + td.fVoxLimits[2] = (fZb[fIbz - 1] - point[2]) * td.fVoxInvdir[2]; } else { - td.fVoxLimits[2] = (fZb[0]-point[2])*td.fVoxInvdir[2]; + td.fVoxLimits[2] = (fZb[0] - point[2]) * td.fVoxInvdir[2]; } } } if (!flag) { -// printf(" NO candidates in first voxel\n"); -// printf(" bits[0]=%i\n", bits[0]); + // printf(" NO candidates in first voxel\n"); + // printf(" bits[0]=%i\n", bits[0]); return; } -// printf(" current slices : %i %i %i\n", td.fVoxSlices[0], td.fVoxSlices[1], td.fVoxSlices[2]); + // printf(" current slices : %i %i %i\n", td.fVoxSlices[0], td.fVoxSlices[1], td.fVoxSlices[2]); Int_t nd[3]; Int_t islices = 0; - memset(&nd[0], 0, 3*sizeof(Int_t)); + memset(&nd[0], 0, 3 * sizeof(Int_t)); UChar_t *slicex = 0; - if (fPriority[0]==2) { + if (fPriority[0] == 2) { nd[0] = fNsliceX[td.fVoxSlices[0]]; - slicex=&fIndcX[fOBx[td.fVoxSlices[0]]]; + slicex = &fIndcX[fOBx[td.fVoxSlices[0]]]; islices++; } UChar_t *slicey = 0; - if (fPriority[1]==2) { + if (fPriority[1] == 2) { nd[1] = fNsliceY[td.fVoxSlices[1]]; islices++; if (slicex) { - slicey=&fIndcY[fOBy[td.fVoxSlices[1]]]; + slicey = &fIndcY[fOBy[td.fVoxSlices[1]]]; } else { - slicex=&fIndcY[fOBy[td.fVoxSlices[1]]]; + slicex = &fIndcY[fOBy[td.fVoxSlices[1]]]; nd[0] = nd[1]; } } UChar_t *slicez = 0; - if (fPriority[2]==2) { + if (fPriority[2] == 2) { nd[2] = fNsliceZ[td.fVoxSlices[2]]; islices++; if (slicex && slicey) { - slicez=&fIndcZ[fOBz[td.fVoxSlices[2]]]; + slicez = &fIndcZ[fOBz[td.fVoxSlices[2]]]; } else { if (slicex) { - slicey=&fIndcZ[fOBz[td.fVoxSlices[2]]]; + slicey = &fIndcZ[fOBz[td.fVoxSlices[2]]]; nd[1] = nd[2]; } else { - slicex=&fIndcZ[fOBz[td.fVoxSlices[2]]]; + slicex = &fIndcZ[fOBz[td.fVoxSlices[2]]]; nd[0] = nd[2]; } } } -// printf("Ndaughters in first voxel : %i %i %i\n", nd[0], nd[1], nd[2]); + // printf("Ndaughters in first voxel : %i %i %i\n", nd[0], nd[1], nd[2]); switch (islices) { - case 0: - Error("SortCrossedVoxels", "no slices for %s", fVolume->GetName()); -// printf("Slices :(%i,%i,%i) Priority:(%i,%i,%i)\n", td.fVoxSlices[0], td.fVoxSlices[1], td.fVoxSlices[2], fPriority[0], fPriority[1], fPriority[2]); - return; - case 1: - IntersectAndStore(nd[0], slicex, td); - break; - case 2: - IntersectAndStore(nd[0], slicex, nd[1], slicey, td); - break; - default: - IntersectAndStore(nd[0], slicex, nd[1], slicey, nd[2], slicez, td); - } -// printf(" bits[0]=%i END\n", bits[0]); -// if (td.fVoxNcandidates) { -// printf(" candidates for first voxel :\n"); -// for (Int_t i=0; iGetName()); + // printf("Slices :(%i,%i,%i) Priority:(%i,%i,%i)\n", td.fVoxSlices[0], td.fVoxSlices[1], + // td.fVoxSlices[2], fPriority[0], fPriority[1], fPriority[2]); + return; + case 1: IntersectAndStore(nd[0], slicex, td); break; + case 2: IntersectAndStore(nd[0], slicex, nd[1], slicey, td); break; + default: IntersectAndStore(nd[0], slicex, nd[1], slicey, nd[2], slicez, td); + } + // printf(" bits[0]=%i END\n", bits[0]); + // if (td.fVoxNcandidates) { + // printf(" candidates for first voxel :\n"); + // for (Int_t i=0; iGetNdaughters() == 1) { if (fXb) { - if (point[0]fXb[1]) return 0; + if (point[0] < fXb[0] || point[0] > fXb[1]) + return 0; } if (fYb) { - if (point[1]fYb[1]) return 0; + if (point[1] < fYb[0] || point[1] > fYb[1]) + return 0; } if (fZb) { - if (point[2]fZb[1]) return 0; + if (point[2] < fZb[0] || point[2] > fZb[1]) + return 0; } td.fVoxCheckList[0] = 0; nelem = 1; @@ -1227,14 +1341,16 @@ Int_t *TGeoVoxelFinder::GetCheckList(const Double_t *point, Int_t &nelem, TGeoSt UChar_t *slice1 = 0; UChar_t *slice2 = 0; UChar_t *slice3 = 0; - Int_t nd[3] = {0,0,0}; + Int_t nd[3] = {0, 0, 0}; Int_t im; if (fPriority[0]) { im = TMath::BinarySearch(fIbx, fXb, point[0]); - if ((im==-1) || (im==fIbx-1)) return 0; - if (fPriority[0]==2) { + if ((im == -1) || (im == fIbx - 1)) + return 0; + if (fPriority[0] == 2) { nd[0] = fNsliceX[im]; - if (!nd[0]) return 0; + if (!nd[0]) + return 0; nslices++; slice1 = &fIndcX[fOBx[im]]; } @@ -1242,10 +1358,12 @@ Int_t *TGeoVoxelFinder::GetCheckList(const Double_t *point, Int_t &nelem, TGeoSt if (fPriority[1]) { im = TMath::BinarySearch(fIby, fYb, point[1]); - if ((im==-1) || (im==fIby-1)) return 0; - if (fPriority[1]==2) { + if ((im == -1) || (im == fIby - 1)) + return 0; + if (fPriority[1] == 2) { nd[1] = fNsliceY[im]; - if (!nd[1]) return 0; + if (!nd[1]) + return 0; nslices++; if (slice1) { slice2 = &fIndcY[fOBy[im]]; @@ -1258,10 +1376,12 @@ Int_t *TGeoVoxelFinder::GetCheckList(const Double_t *point, Int_t &nelem, TGeoSt if (fPriority[2]) { im = TMath::BinarySearch(fIbz, fZb, point[2]); - if ((im==-1) || (im==fIbz-1)) return 0; - if (fPriority[2]==2) { + if ((im == -1) || (im == fIbz - 1)) + return 0; + if (fPriority[2] == 2) { nd[2] = fNsliceZ[im]; - if (!nd[2]) return 0; + if (!nd[2]) + return 0; nslices++; if (slice1 && slice2) { slice3 = &fIndcZ[fOBz[im]]; @@ -1277,22 +1397,16 @@ Int_t *TGeoVoxelFinder::GetCheckList(const Double_t *point, Int_t &nelem, TGeoSt } } nelem = 0; -// Int_t i = 0; + // Int_t i = 0; Bool_t intersect = kFALSE; switch (nslices) { - case 0: - Error("GetCheckList", "No slices for %s", fVolume->GetName()); - return 0; - case 1: - intersect = Intersect(nd[0], slice1, nelem, td.fVoxCheckList); - break; - case 2: - intersect = Intersect(nd[0], slice1, nd[1], slice2, nelem, td.fVoxCheckList); - break; - default: - intersect = Intersect(nd[0], slice1, nd[1], slice2, nd[2], slice3, nelem, td.fVoxCheckList); - } - if (intersect) return td.fVoxCheckList; + case 0: Error("GetCheckList", "No slices for %s", fVolume->GetName()); return 0; + case 1: intersect = Intersect(nd[0], slice1, nelem, td.fVoxCheckList); break; + case 2: intersect = Intersect(nd[0], slice1, nd[1], slice2, nelem, td.fVoxCheckList); break; + default: intersect = Intersect(nd[0], slice1, nd[1], slice2, nd[2], slice3, nelem, td.fVoxCheckList); + } + if (intersect) + return td.fVoxCheckList; return 0; } @@ -1304,18 +1418,20 @@ Int_t *TGeoVoxelFinder::GetVoxelCandidates(Int_t i, Int_t j, Int_t k, Int_t &nch UChar_t *slice1 = 0; UChar_t *slice2 = 0; UChar_t *slice3 = 0; - Int_t nd[3] = {0,0,0}; + Int_t nd[3] = {0, 0, 0}; Int_t nslices = 0; - if (fPriority[0]==2) { + if (fPriority[0] == 2) { nd[0] = fNsliceX[i]; - if (!nd[0]) return 0; + if (!nd[0]) + return 0; nslices++; slice1 = &fIndcX[fOBx[i]]; } - if (fPriority[1]==2) { + if (fPriority[1] == 2) { nd[1] = fNsliceY[j]; - if (!nd[1]) return 0; + if (!nd[1]) + return 0; nslices++; if (slice1) { slice2 = &fIndcY[fOBy[j]]; @@ -1325,9 +1441,10 @@ Int_t *TGeoVoxelFinder::GetVoxelCandidates(Int_t i, Int_t j, Int_t k, Int_t &nch } } - if (fPriority[2]==2) { + if (fPriority[2] == 2) { nd[2] = fNsliceZ[k]; - if (!nd[2]) return 0; + if (!nd[2]) + return 0; nslices++; if (slice1 && slice2) { slice3 = &fIndcZ[fOBz[k]]; @@ -1343,19 +1460,13 @@ Int_t *TGeoVoxelFinder::GetVoxelCandidates(Int_t i, Int_t j, Int_t k, Int_t &nch } Bool_t intersect = kFALSE; switch (nslices) { - case 0: - Error("GetCheckList", "No slices for %s", fVolume->GetName()); - return 0; - case 1: - intersect = Intersect(nd[0], slice1, ncheck, td.fVoxCheckList); - break; - case 2: - intersect = Intersect(nd[0], slice1, nd[1], slice2, ncheck, td.fVoxCheckList); - break; - default: - intersect = Intersect(nd[0], slice1, nd[1], slice2, nd[2], slice3, ncheck, td.fVoxCheckList); - } - if (intersect) return td.fVoxCheckList; + case 0: Error("GetCheckList", "No slices for %s", fVolume->GetName()); return 0; + case 1: intersect = Intersect(nd[0], slice1, ncheck, td.fVoxCheckList); break; + case 2: intersect = Intersect(nd[0], slice1, nd[1], slice2, ncheck, td.fVoxCheckList); break; + default: intersect = Intersect(nd[0], slice1, nd[1], slice2, nd[2], slice3, ncheck, td.fVoxCheckList); + } + if (intersect) + return td.fVoxCheckList; return 0; } @@ -1369,17 +1480,17 @@ Int_t *TGeoVoxelFinder::GetNextVoxel(const Double_t *point, const Double_t * /*d Voxelize(); fVolume->FindOverlaps(); } - if (td.fVoxCurrent==0) { -// printf(">>> first voxel, %i candidates\n", ncheck); -// printf(" bits[0]=%i\n", gGeoManager->GetBits()[0]); + if (td.fVoxCurrent == 0) { + // printf(">>> first voxel, %i candidates\n", ncheck); + // printf(" bits[0]=%i\n", gGeoManager->GetBits()[0]); td.fVoxCurrent++; ncheck = td.fVoxNcandidates; return td.fVoxCheckList; } td.fVoxCurrent++; -// printf(">>> voxel %i\n", td.fCurrentVoxel); + // printf(">>> voxel %i\n", td.fCurrentVoxel); // Get slices for next voxel -// printf("before - td.fSlices : %i %i %i\n", td.fSlices[0], td.fSlices[1], td.fSlices[2]); + // printf("before - td.fSlices : %i %i %i\n", td.fSlices[0], td.fSlices[1], td.fSlices[2]); return GetNextCandidates(point, ncheck, td); } @@ -1390,24 +1501,26 @@ Bool_t TGeoVoxelFinder::Intersect(Int_t n1, UChar_t *array1, Int_t &nf, Int_t *r { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan nf = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; Bool_t ibreak = kFALSE; - for (current_byte=0; current_byteGetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); if (!array1) { - memset(td.fVoxBits1, 0xFF, nbytes*sizeof(UChar_t)); - while (td.fVoxNcandidatesGetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; Bool_t ibreak = kFALSE; - for (current_byte=0; current_byte0); + return (td.fVoxNcandidates > 0); } //////////////////////////////////////////////////////////////////////////////// @@ -1493,23 +1610,24 @@ Bool_t TGeoVoxelFinder::Union(Int_t n1, UChar_t *array1, TGeoStateInfo &td) Bool_t TGeoVoxelFinder::Union(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, TGeoStateInfo &td) { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; - for (current_byte=0; current_byte0); + return (td.fVoxNcandidates > 0); } //////////////////////////////////////////////////////////////////////////////// @@ -1517,26 +1635,28 @@ Bool_t TGeoVoxelFinder::Union(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar /// printf("Union - three slices\n"); /// printf("n1=%i n2=%i n3=%i\n", n1,n2,n3); -Bool_t TGeoVoxelFinder::Union(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t /*n3*/, UChar_t *array3, TGeoStateInfo &td) +Bool_t TGeoVoxelFinder::Union(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t /*n3*/, + UChar_t *array3, TGeoStateInfo &td) { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; - for (current_byte=0; current_byte0); + return (td.fVoxNcandidates > 0); } //////////////////////////////////////////////////////////////////////////////// @@ -1546,111 +1666,120 @@ Bool_t TGeoVoxelFinder::Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t * { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan nf = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; Bool_t ibreak = kFALSE; - for (current_byte=0; current_byte0); + return (nf > 0); } //////////////////////////////////////////////////////////////////////////////// /// return the list of nodes corresponding to the intersection of two arrays of bits -Bool_t TGeoVoxelFinder::IntersectAndStore(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, TGeoStateInfo &td) +Bool_t +TGeoVoxelFinder::IntersectAndStore(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, TGeoStateInfo &td) { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); -// memset(bits, 0, nbytes*sizeof(UChar_t)); + Int_t nbytes = 1 + ((nd - 1) >> 3); + // memset(bits, 0, nbytes*sizeof(UChar_t)); Int_t current_byte; Int_t current_bit; Int_t icand; UChar_t byte; - for (current_byte=0; current_byte0); + return (td.fVoxNcandidates > 0); } //////////////////////////////////////////////////////////////////////////////// /// return the list of nodes corresponding to the intersection of three arrays of bits -Bool_t TGeoVoxelFinder::Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t n3, UChar_t *array3, Int_t &nf, Int_t *result) +Bool_t TGeoVoxelFinder::Intersect(Int_t n1, UChar_t *array1, Int_t n2, UChar_t *array2, Int_t n3, UChar_t *array3, + Int_t &nf, Int_t *result) { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan nf = 0; - Int_t nbytes = 1+((nd-1)>>3); + Int_t nbytes = 1 + ((nd - 1) >> 3); Int_t current_byte; Int_t current_bit; UChar_t byte; Bool_t ibreak = kFALSE; - for (current_byte=0; current_byte0); + return (nf > 0); } //////////////////////////////////////////////////////////////////////////////// /// return the list of nodes corresponding to the intersection of three arrays of bits -Bool_t TGeoVoxelFinder::IntersectAndStore(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t /*n3*/, UChar_t *array3, TGeoStateInfo &td) +Bool_t TGeoVoxelFinder::IntersectAndStore(Int_t /*n1*/, UChar_t *array1, Int_t /*n2*/, UChar_t *array2, Int_t /*n3*/, + UChar_t *array3, TGeoStateInfo &td) { Int_t nd = fVolume->GetNdaughters(); // also number of bits to scan -// UChar_t *bits = gGeoManager->GetBits(); + // UChar_t *bits = gGeoManager->GetBits(); td.fVoxNcandidates = 0; - Int_t nbytes = 1+((nd-1)>>3); -// memset(bits, 0, nbytes*sizeof(UChar_t)); + Int_t nbytes = 1 + ((nd - 1) >> 3); + // memset(bits, 0, nbytes*sizeof(UChar_t)); Int_t current_byte; Int_t current_bit; Int_t icand; UChar_t byte; - for (current_byte=0; current_byte0); + return (td.fVoxNcandidates > 0); } //////////////////////////////////////////////////////////////////////////////// /// order bounding boxes along x, y, z @@ -1658,10 +1787,10 @@ Bool_t TGeoVoxelFinder::IntersectAndStore(Int_t /*n1*/, UChar_t *array1, Int_t / void TGeoVoxelFinder::SortAll(Option_t *) { Int_t nd = fVolume->GetNdaughters(); - Int_t nperslice = 1+(nd-1)/(8*sizeof(UChar_t)); /*Nbytes per slice*/ - Int_t nmaxslices = 2*nd+1; // max number of slices on each axis + Int_t nperslice = 1 + (nd - 1) / (8 * sizeof(UChar_t)); /*Nbytes per slice*/ + Int_t nmaxslices = 2 * nd + 1; // max number of slices on each axis Double_t xmin, xmax, ymin, ymax, zmin, zmax; - TGeoBBox *box = (TGeoBBox*)fVolume->GetShape(); // bounding box for volume + TGeoBBox *box = (TGeoBBox *)fVolume->GetShape(); // bounding box for volume // compute range on X, Y, Z according to volume bounding box xmin = (box->GetOrigin())[0] - box->GetDX(); xmax = (box->GetOrigin())[0] + box->GetDX(); @@ -1669,36 +1798,42 @@ void TGeoVoxelFinder::SortAll(Option_t *) ymax = (box->GetOrigin())[1] + box->GetDY(); zmin = (box->GetOrigin())[2] - box->GetDZ(); zmax = (box->GetOrigin())[2] + box->GetDZ(); - if ((xmin>=xmax) || (ymin>=ymax) || (zmin>=zmax)) { + if ((xmin >= xmax) || (ymin >= ymax) || (zmin >= zmax)) { Error("SortAll", "Wrong bounding box for volume %s", fVolume->GetName()); return; } Int_t id; // compute boundaries coordinates on X,Y,Z - Double_t *boundaries = new Double_t[6*nd]; // list of different boundaries - for (id=0; idGetName()); + return; } - Int_t *index = new Int_t[2*nd]; // indexes for sorted boundaries on one axis - UChar_t *ind = new UChar_t[nmaxslices*nperslice]; // ind[fOBx[i]] = ndghts in slice fInd[i]--fInd[i+1] - Int_t *extra = new Int_t[nmaxslices*4]; + + Int_t *index = new Int_t[2 * nd]; // indexes for sorted boundaries on one axis + UChar_t *ind = new UChar_t[nmaxslices * nperslice]; // ind[fOBx[i]] = ndghts in slice fInd[i]--fInd[i+1] + Int_t *extra = new Int_t[nmaxslices * 4]; // extra[fOEx[i]] = nextra_to_left (i/i-1) // extra[fOEx[i]+1] = nextra_to_right (i/i+1) // Int_t *extra_to_left = extra[fOEx[i]+2] // Int_t *extra_to_right = extra[fOEx[i]+2+nextra_to_left] - Double_t *temp = new Double_t[2*nd]; // temporary array to store sorted boundary positions - Int_t current = 0; + Double_t *temp = new Double_t[2 * nd]; // temporary array to store sorted boundary positions + Int_t current = 0; Int_t indextra = 0; Int_t nleft, nright; - Int_t *extra_left = new Int_t[nd]; + Int_t *extra_left = new Int_t[nd]; Int_t *extra_right = new Int_t[nd]; Double_t xxmin, xxmax, xbmin, xbmax, ddx1, ddx2; UChar_t *bits; @@ -1707,372 +1842,425 @@ void TGeoVoxelFinder::SortAll(Option_t *) // sort x boundaries Int_t ib = 0; // total number of DIFFERENT boundaries - TMath::Sort(2*nd, &boundaries[0], &index[0], kFALSE); + TMath::Sort(2 * nd, &boundaries[0], &index[0], kFALSE); // compact common boundaries - for (id=0; id<2*nd; id++) { - if (!ib) {temp[ib++] = boundaries[index[id]]; continue;} - if (TMath::Abs(temp[ib-1]-boundaries[index[id]])>1E-10) + for (id = 0; id < 2 * nd; id++) { + if (!ib) { + temp[ib++] = boundaries[index[id]]; + continue; + } + if (TMath::Abs(temp[ib - 1] - boundaries[index[id]]) > 1E-10) temp[ib++] = boundaries[index[id]]; } // now find priority if (ib < 2) { Error("SortAll", "Cannot voxelize %s :less than 2 boundaries on X", fVolume->GetName()); - delete [] boundaries; - delete [] index; - delete [] ind; - delete [] temp; - delete [] extra; - delete [] extra_left; - delete [] extra_right; + delete[] boundaries; + delete[] index; + delete[] ind; + delete[] temp; + delete[] extra; + delete[] extra_left; + delete[] extra_right; SetInvalid(); return; } if (ib == 2) { - // check range - if (((temp[0]-xmin)<1E-10) && ((temp[1]-xmax)>-1E-10)) { - // ordering on this axis makes no sense. Clear all arrays. - fPriority[0] = 0; // always skip this axis - if (fIndcX) delete [] fIndcX; + // check range + if (((temp[0] - xmin) < 1E-10) && ((temp[1] - xmax) > -1E-10)) { + // ordering on this axis makes no sense. Clear all arrays. + fPriority[0] = 0; // always skip this axis + if (fIndcX) + delete[] fIndcX; fIndcX = 0; fNx = 0; - if (fXb) delete [] fXb; + if (fXb) + delete[] fXb; fXb = 0; fIbx = 0; - if (fOBx) delete [] fOBx; + if (fOBx) + delete[] fOBx; fOBx = 0; fNox = 0; } else { fPriority[0] = 1; // all in one slice } } else { - fPriority[0] = 2; // check all + fPriority[0] = 2; // check all } // store compacted boundaries if (fPriority[0]) { - if (fXb) delete [] fXb; + if (fXb) + delete[] fXb; fXb = new Double_t[ib]; - memcpy(fXb, &temp[0], ib*sizeof(Double_t)); + memcpy(fXb, &temp[0], ib * sizeof(Double_t)); fIbx = ib; } //--- now build the lists of nodes in each slice of X axis - if (fPriority[0]==2) { - memset(ind, 0, (nmaxslices*nperslice)*sizeof(UChar_t)); - if (fOBx) delete [] fOBx; - fNox = fIbx-1; // number of different slices + if (fPriority[0] == 2) { + memset(ind, 0, (nmaxslices * nperslice) * sizeof(UChar_t)); + if (fOBx) + delete[] fOBx; + fNox = fIbx - 1; // number of different slices fOBx = new Int_t[fNox]; // offsets in ind - if (fOEx) delete [] fOEx; + if (fOEx) + delete[] fOEx; fOEx = new Int_t[fNox]; // offsets in extra - if (fNsliceX) delete [] fNsliceX; + if (fNsliceX) + delete[] fNsliceX; fNsliceX = new Int_t[fNox]; - current = 0; + current = 0; indextra = 0; //--- now loop all slices - for (id=0; id-1E-10) continue; - ddx2 = xbmax-xxmin; - if (ddx2<1E-10) continue; + xxmax = fXb[id + 1]; + for (Int_t ic = 0; ic < nd; ic++) { + xbmin = fBoxes[6 * ic + 3] - fBoxes[6 * ic]; + xbmax = fBoxes[6 * ic + 3] + fBoxes[6 * ic]; + ddx1 = xbmin - xxmax; + if (ddx1 > -1E-10) + continue; + ddx2 = xbmax - xxmin; + if (ddx2 < 1E-10) + continue; // daughter ic in interval //---> set the bit fNsliceX[id]++; bitnumber = (UInt_t)ic; - loc = bitnumber/8; - bit = bitnumber%8; - bits[loc] |= 1< chech if it is extra to left/right //--- left - ddx1 = xbmin-xxmin; - ddx2 = xbmax-xxmax; - if ((id==0) || (ddx1>-1E-10)) { + ddx1 = xbmin - xxmin; + ddx2 = xbmax - xxmax; + if ((id == 0) || (ddx1 > -1E-10)) { extra_left[nleft++] = ic; } //---right - if ((id==(fNoz-1)) || (ddx2<1E-10)) { + if ((id == (fNoz - 1)) || (ddx2 < 1E-10)) { extra_right[nright++] = ic; } } //--- compute offset of next slice - if (fNsliceX[id]>0) current += nperslice; + if (fNsliceX[id] > 0) + current += nperslice; //--- copy extra candidates extra[indextra] = nleft; - extra[indextra+1] = nright; - if (nleft) memcpy(&extra[indextra+2], extra_left, nleft*sizeof(Int_t)); - if (nright) memcpy(&extra[indextra+2+nleft], extra_right, nright*sizeof(Int_t)); - indextra += 2+nleft+nright; + extra[indextra + 1] = nright; + if (nleft) + memcpy(&extra[indextra + 2], extra_left, nleft * sizeof(Int_t)); + if (nright) + memcpy(&extra[indextra + 2 + nleft], extra_right, nright * sizeof(Int_t)); + indextra += 2 + nleft + nright; } - if (fIndcX) delete [] fIndcX; + if (fIndcX) + delete[] fIndcX; fNx = current; fIndcX = new UChar_t[current]; - memcpy(fIndcX, ind, current*sizeof(UChar_t)); - if (fExtraX) delete [] fExtraX; + memcpy(fIndcX, ind, current * sizeof(UChar_t)); + if (fExtraX) + delete[] fExtraX; fNex = indextra; - if (indextra>nmaxslices*4) printf("Woops!!!\n"); + if (indextra > nmaxslices * 4) + printf("Woops!!!\n"); fExtraX = new Int_t[indextra]; - memcpy(fExtraX, extra, indextra*sizeof(Int_t)); + memcpy(fExtraX, extra, indextra * sizeof(Int_t)); } // sort y boundaries ib = 0; - TMath::Sort(2*nd, &boundaries[2*nd], &index[0], kFALSE); + TMath::Sort(2 * nd, &boundaries[2 * nd], &index[0], kFALSE); // compact common boundaries - for (id=0; id<2*nd; id++) { - if (!ib) {temp[ib++] = boundaries[2*nd+index[id]]; continue;} - if (TMath::Abs(temp[ib-1]-boundaries[2*nd+index[id]])>1E-10) - temp[ib++]=boundaries[2*nd+index[id]]; + for (id = 0; id < 2 * nd; id++) { + if (!ib) { + temp[ib++] = boundaries[2 * nd + index[id]]; + continue; + } + if (TMath::Abs(temp[ib - 1] - boundaries[2 * nd + index[id]]) > 1E-10) + temp[ib++] = boundaries[2 * nd + index[id]]; } // now find priority on Y if (ib < 2) { Error("SortAll", "Cannot voxelize %s :less than 2 boundaries on Y", fVolume->GetName()); - delete [] boundaries; - delete [] index; - delete [] ind; - delete [] temp; - delete [] extra; - delete [] extra_left; - delete [] extra_right; + delete[] boundaries; + delete[] index; + delete[] ind; + delete[] temp; + delete[] extra; + delete[] extra_left; + delete[] extra_right; SetInvalid(); return; } if (ib == 2) { - // check range - if (((temp[0]-ymin)<1E-10) && ((temp[1]-ymax)>-1E-10)) { - // ordering on this axis makes no sense. Clear all arrays. + // check range + if (((temp[0] - ymin) < 1E-10) && ((temp[1] - ymax) > -1E-10)) { + // ordering on this axis makes no sense. Clear all arrays. fPriority[1] = 0; // always skip this axis - if (fIndcY) delete [] fIndcY; + if (fIndcY) + delete[] fIndcY; fIndcY = 0; fNy = 0; - if (fYb) delete [] fYb; + if (fYb) + delete[] fYb; fYb = 0; fIby = 0; - if (fOBy) delete [] fOBy; + if (fOBy) + delete[] fOBy; fOBy = 0; fNoy = 0; } else { fPriority[1] = 1; // all in one slice } } else { - fPriority[1] = 2; // check all + fPriority[1] = 2; // check all } // store compacted boundaries if (fPriority[1]) { - if (fYb) delete [] fYb; + if (fYb) + delete[] fYb; fYb = new Double_t[ib]; - memcpy(fYb, &temp[0], ib*sizeof(Double_t)); + memcpy(fYb, &temp[0], ib * sizeof(Double_t)); fIby = ib; } - - if (fPriority[1]==2) { - //--- now build the lists of nodes in each slice of Y axis - memset(ind, 0, (nmaxslices*nperslice)*sizeof(UChar_t)); - if (fOBy) delete [] fOBy; - fNoy = fIby-1; // number of different slices + if (fPriority[1] == 2) { + //--- now build the lists of nodes in each slice of Y axis + memset(ind, 0, (nmaxslices * nperslice) * sizeof(UChar_t)); + if (fOBy) + delete[] fOBy; + fNoy = fIby - 1; // number of different slices fOBy = new Int_t[fNoy]; // offsets in ind - if (fOEy) delete [] fOEy; + if (fOEy) + delete[] fOEy; fOEy = new Int_t[fNoy]; // offsets in extra - if (fNsliceY) delete [] fNsliceY; + if (fNsliceY) + delete[] fNsliceY; fNsliceY = new Int_t[fNoy]; current = 0; indextra = 0; //--- now loop all slices - for (id=0; id-1E-10) continue; - ddx2 = xbmax-xxmin; - if (ddx2<1E-10) continue; + xxmax = fYb[id + 1]; + for (Int_t ic = 0; ic < nd; ic++) { + xbmin = fBoxes[6 * ic + 4] - fBoxes[6 * ic + 1]; + xbmax = fBoxes[6 * ic + 4] + fBoxes[6 * ic + 1]; + ddx1 = xbmin - xxmax; + if (ddx1 > -1E-10) + continue; + ddx2 = xbmax - xxmin; + if (ddx2 < 1E-10) + continue; // daughter ic in interval //---> set the bit fNsliceY[id]++; bitnumber = (UInt_t)ic; - loc = bitnumber/8; - bit = bitnumber%8; - bits[loc] |= 1< check if it is extra to left/right //--- left - ddx1 = xbmin-xxmin; - ddx2 = xbmax-xxmax; - if ((id==0) || (ddx1>-1E-10)) { + ddx1 = xbmin - xxmin; + ddx2 = xbmax - xxmax; + if ((id == 0) || (ddx1 > -1E-10)) { extra_left[nleft++] = ic; } //---right - if ((id==(fNoz-1)) || (ddx2<1E-10)) { + if ((id == (fNoz - 1)) || (ddx2 < 1E-10)) { extra_right[nright++] = ic; } } //--- compute offset of next slice - if (fNsliceY[id]>0) current += nperslice; + if (fNsliceY[id] > 0) + current += nperslice; //--- copy extra candidates extra[indextra] = nleft; - extra[indextra+1] = nright; - if (nleft) memcpy(&extra[indextra+2], extra_left, nleft*sizeof(Int_t)); - if (nright) memcpy(&extra[indextra+2+nleft], extra_right, nright*sizeof(Int_t)); - indextra += 2+nleft+nright; + extra[indextra + 1] = nright; + if (nleft) + memcpy(&extra[indextra + 2], extra_left, nleft * sizeof(Int_t)); + if (nright) + memcpy(&extra[indextra + 2 + nleft], extra_right, nright * sizeof(Int_t)); + indextra += 2 + nleft + nright; } - if (fIndcY) delete [] fIndcY; + if (fIndcY) + delete[] fIndcY; fNy = current; fIndcY = new UChar_t[current]; - memcpy(fIndcY, &ind[0], current*sizeof(UChar_t)); - if (fExtraY) delete [] fExtraY; + memcpy(fIndcY, &ind[0], current * sizeof(UChar_t)); + if (fExtraY) + delete[] fExtraY; fNey = indextra; - if (indextra>nmaxslices*4) printf("Woops!!!\n"); + if (indextra > nmaxslices * 4) + printf("Woops!!!\n"); fExtraY = new Int_t[indextra]; - memcpy(fExtraY, extra, indextra*sizeof(Int_t)); + memcpy(fExtraY, extra, indextra * sizeof(Int_t)); } // sort z boundaries ib = 0; - TMath::Sort(2*nd, &boundaries[4*nd], &index[0], kFALSE); + TMath::Sort(2 * nd, &boundaries[4 * nd], &index[0], kFALSE); // compact common boundaries - for (id=0; id<2*nd; id++) { - if (!ib) {temp[ib++] = boundaries[4*nd+index[id]]; continue;} - if ((TMath::Abs(temp[ib-1]-boundaries[4*nd+index[id]]))>1E-10) - temp[ib++]=boundaries[4*nd+index[id]]; + for (id = 0; id < 2 * nd; id++) { + if (!ib) { + temp[ib++] = boundaries[4 * nd + index[id]]; + continue; + } + if ((TMath::Abs(temp[ib - 1] - boundaries[4 * nd + index[id]])) > 1E-10) + temp[ib++] = boundaries[4 * nd + index[id]]; } // now find priority on Z if (ib < 2) { Error("SortAll", "Cannot voxelize %s :less than 2 boundaries on Z", fVolume->GetName()); - delete [] boundaries; - delete [] index; - delete [] ind; - delete [] temp; - delete [] extra; - delete [] extra_left; - delete [] extra_right; + delete[] boundaries; + delete[] index; + delete[] ind; + delete[] temp; + delete[] extra; + delete[] extra_left; + delete[] extra_right; SetInvalid(); return; } if (ib == 2) { - // check range - if (((temp[0]-zmin)<1E-10) && ((temp[1]-zmax)>-1E-10)) { - // ordering on this axis makes no sense. Clear all arrays. + // check range + if (((temp[0] - zmin) < 1E-10) && ((temp[1] - zmax) > -1E-10)) { + // ordering on this axis makes no sense. Clear all arrays. fPriority[2] = 0; - if (fIndcZ) delete [] fIndcZ; + if (fIndcZ) + delete[] fIndcZ; fIndcZ = 0; fNz = 0; - if (fZb) delete [] fZb; + if (fZb) + delete[] fZb; fZb = 0; fIbz = 0; - if (fOBz) delete [] fOBz; + if (fOBz) + delete[] fOBz; fOBz = 0; fNoz = 0; } else { fPriority[2] = 1; // all in one slice } } else { - fPriority[2] = 2; // check all + fPriority[2] = 2; // check all } // store compacted boundaries if (fPriority[2]) { - if (fZb) delete [] fZb; + if (fZb) + delete[] fZb; fZb = new Double_t[ib]; - memcpy(fZb, &temp[0], ib*sizeof(Double_t)); + memcpy(fZb, &temp[0], ib * sizeof(Double_t)); fIbz = ib; } - - if (fPriority[2]==2) { - //--- now build the lists of nodes in each slice of Y axis - memset(ind, 0, (nmaxslices*nperslice)*sizeof(UChar_t)); - if (fOBz) delete [] fOBz; - fNoz = fIbz-1; // number of different slices + if (fPriority[2] == 2) { + //--- now build the lists of nodes in each slice of Y axis + memset(ind, 0, (nmaxslices * nperslice) * sizeof(UChar_t)); + if (fOBz) + delete[] fOBz; + fNoz = fIbz - 1; // number of different slices fOBz = new Int_t[fNoz]; // offsets in ind - if (fOEz) delete [] fOEz; + if (fOEz) + delete[] fOEz; fOEz = new Int_t[fNoz]; // offsets in extra - if (fNsliceZ) delete [] fNsliceZ; + if (fNsliceZ) + delete[] fNsliceZ; fNsliceZ = new Int_t[fNoz]; current = 0; indextra = 0; //--- now loop all slices - for (id=0; id-1E-10) continue; - ddx2 = xbmax-xxmin; - if (ddx2<1E-10) continue; + xxmax = fZb[id + 1]; + for (Int_t ic = 0; ic < nd; ic++) { + xbmin = fBoxes[6 * ic + 5] - fBoxes[6 * ic + 2]; + xbmax = fBoxes[6 * ic + 5] + fBoxes[6 * ic + 2]; + ddx1 = xbmin - xxmax; + if (ddx1 > -1E-10) + continue; + ddx2 = xbmax - xxmin; + if (ddx2 < 1E-10) + continue; // daughter ic in interval //---> set the bit fNsliceZ[id]++; bitnumber = (UInt_t)ic; - loc = bitnumber/8; - bit = bitnumber%8; - bits[loc] |= 1< check if it is extra to left/right //--- left - ddx1 = xbmin-xxmin; - ddx2 = xbmax-xxmax; - if ((id==0) || (ddx1>-1E-10)) { + ddx1 = xbmin - xxmin; + ddx2 = xbmax - xxmax; + if ((id == 0) || (ddx1 > -1E-10)) { extra_left[nleft++] = ic; } //---right - if ((id==(fNoz-1)) || (ddx2<1E-10)) { + if ((id == (fNoz - 1)) || (ddx2 < 1E-10)) { extra_right[nright++] = ic; } } //--- compute offset of next slice - if (fNsliceZ[id]>0) current += nperslice; + if (fNsliceZ[id] > 0) + current += nperslice; //--- copy extra candidates extra[indextra] = nleft; - extra[indextra+1] = nright; - if (nleft) memcpy(&extra[indextra+2], extra_left, nleft*sizeof(Int_t)); - if (nright) memcpy(&extra[indextra+2+nleft], extra_right, nright*sizeof(Int_t)); - indextra += 2+nleft+nright; + extra[indextra + 1] = nright; + if (nleft) + memcpy(&extra[indextra + 2], extra_left, nleft * sizeof(Int_t)); + if (nright) + memcpy(&extra[indextra + 2 + nleft], extra_right, nright * sizeof(Int_t)); + indextra += 2 + nleft + nright; } - if (fIndcZ) delete [] fIndcZ; + if (fIndcZ) + delete[] fIndcZ; fNz = current; fIndcZ = new UChar_t[current]; - memcpy(fIndcZ, &ind[0], current*sizeof(UChar_t)); - if (fExtraZ) delete [] fExtraZ; + memcpy(fIndcZ, &ind[0], current * sizeof(UChar_t)); + if (fExtraZ) + delete[] fExtraZ; fNez = indextra; - if (indextra>nmaxslices*4) printf("Woops!!!\n"); + if (indextra > nmaxslices * 4) + printf("Woops!!!\n"); fExtraZ = new Int_t[indextra]; - memcpy(fExtraZ, extra, indextra*sizeof(Int_t)); + memcpy(fExtraZ, extra, indextra * sizeof(Int_t)); } - delete [] boundaries; - delete [] index; - delete [] temp; - delete [] ind; - delete [] extra; - delete [] extra_left; - delete [] extra_right; + delete[] boundaries; + delete[] index; + delete[] temp; + delete[] ind; + delete[] extra; + delete[] extra_left; + delete[] extra_right; if ((!fPriority[0]) && (!fPriority[1]) && (!fPriority[2])) { SetInvalid(); - if (nd>1) Error("SortAll", "Volume %s: Cannot make slices on any axis", fVolume->GetName()); + if (nd > 1) + Error("SortAll", "Volume %s: Cannot make slices on any axis", fVolume->GetName()); } } @@ -2082,7 +2270,7 @@ void TGeoVoxelFinder::SortAll(Option_t *) void TGeoVoxelFinder::Print(Option_t *) const { if (NeedRebuild()) { - TGeoVoxelFinder *vox = (TGeoVoxelFinder*)this; + TGeoVoxelFinder *vox = (TGeoVoxelFinder *)this; vox->Voxelize(); fVolume->FindOverlaps(); } @@ -2090,91 +2278,100 @@ void TGeoVoxelFinder::Print(Option_t *) const Int_t nd = fVolume->GetNdaughters(); printf("Voxels for volume %s (nd=%i)\n", fVolume->GetName(), fVolume->GetNdaughters()); printf("priority : x=%i y=%i z=%i\n", fPriority[0], fPriority[1], fPriority[2]); -// return; + // return; Int_t nextra; - Int_t nbytes = 1+((fVolume->GetNdaughters()-1)>>3); + Int_t nbytes = 1 + ((fVolume->GetNdaughters() - 1) >> 3); UChar_t byte, bit; UChar_t *slice; printf("XXX\n"); - if (fPriority[0]==2) { - for (id=0; idVoxelize(); fVolume->FindOverlaps(); } - Int_t im=0; + Int_t im = 0; if (fPriority[0]) { im = TMath::BinarySearch(fIbx, fXb, point[0]); - if ((im==-1) || (im==fIbx-1)) { + if ((im == -1) || (im == fIbx - 1)) { printf("Voxel X limits: OUT\n"); } else { - printf("Voxel X limits: %g %g\n", fXb[im], fXb[im+1]); + printf("Voxel X limits: %g %g\n", fXb[im], fXb[im + 1]); } } if (fPriority[1]) { im = TMath::BinarySearch(fIby, fYb, point[1]); - if ((im==-1) || (im==fIby-1)) { + if ((im == -1) || (im == fIby - 1)) { printf("Voxel Y limits: OUT\n"); } else { - printf("Voxel Y limits: %g %g\n", fYb[im], fYb[im+1]); + printf("Voxel Y limits: %g %g\n", fYb[im], fYb[im + 1]); } } if (fPriority[2]) { im = TMath::BinarySearch(fIbz, fZb, point[2]); - if ((im==-1) || (im==fIbz-1)) { + if ((im == -1) || (im == fIbz - 1)) { printf("Voxel Z limits: OUT\n"); } else { - printf("Voxel Z limits: %g %g\n", fZb[im], fZb[im+1]); + printf("Voxel Z limits: %g %g\n", fZb[im], fZb[im + 1]); } } } @@ -2220,12 +2417,14 @@ void TGeoVoxelFinder::PrintVoxelLimits(const Double_t *point) const void TGeoVoxelFinder::Voxelize(Option_t * /*option*/) { - if (fVolume->IsAssembly()) fVolume->GetShape()->ComputeBBox(); + if (fVolume->IsAssembly()) + fVolume->GetShape()->ComputeBBox(); Int_t nd = fVolume->GetNdaughters(); TGeoVolume *vd; - for (Int_t i=0; iGetNode(i)->GetVolume(); - if (vd->IsAssembly()) vd->GetShape()->ComputeBBox(); + if (vd->IsAssembly()) + vd->GetShape()->ComputeBBox(); } BuildVoxelLimits(); SortAll(); @@ -2245,9 +2444,9 @@ void TGeoVoxelFinder::Streamer(TBuffer &R__b) } // Process old versions of the voxel finder. Just read the data // from the buffer in a temp variable then mark voxels as garbage. - UChar_t *dummy = new UChar_t[R__c-2]; - R__b.ReadFastArray(dummy, R__c-2); - delete [] dummy; + UChar_t *dummy = new UChar_t[R__c - 2]; + R__b.ReadFastArray(dummy, R__c - 2); + delete[] dummy; SetInvalid(kTRUE); } else { R__b.WriteClassBuffer(TGeoVoxelFinder::Class(), this); diff --git a/geom/geom/src/TGeoXtru.cxx b/geom/geom/src/TGeoXtru.cxx index d7e5a1ec82fe7..e5dde72f84e6d 100644 --- a/geom/geom/src/TGeoXtru.cxx +++ b/geom/geom/src/TGeoXtru.cxx @@ -105,26 +105,24 @@ ClassImp(TGeoXtru); //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoXtru::ThreadData_t::ThreadData_t() : - fSeg(0), fIz(0), fXc(0), fYc(0), fPoly(0) -{ -} +TGeoXtru::ThreadData_t::ThreadData_t() : fSeg(0), fIz(0), fXc(0), fYc(0), fPoly(0) {} //////////////////////////////////////////////////////////////////////////////// /// Destructor. TGeoXtru::ThreadData_t::~ThreadData_t() { - delete [] fXc; - delete [] fYc; + delete[] fXc; + delete[] fYc; delete fPoly; } //////////////////////////////////////////////////////////////////////////////// -TGeoXtru::ThreadData_t& TGeoXtru::GetThreadData() const +TGeoXtru::ThreadData_t &TGeoXtru::GetThreadData() const { - if (!fThreadSize) ((TGeoXtru*)this)->CreateThreadData(1); + if (!fThreadSize) + ((TGeoXtru *)this)->CreateThreadData(1); Int_t tid = TGeoManager::ThreadId(); return *fThreadData[tid]; } @@ -134,9 +132,8 @@ TGeoXtru::ThreadData_t& TGeoXtru::GetThreadData() const void TGeoXtru::ClearThreadData() const { std::lock_guard guard(fMutex); - std::vector::iterator i = fThreadData.begin(); - while (i != fThreadData.end()) - { + std::vector::iterator i = fThreadData.begin(); + while (i != fThreadData.end()) { delete *i; ++i; } @@ -152,14 +149,14 @@ void TGeoXtru::CreateThreadData(Int_t nthreads) std::lock_guard guard(fMutex); fThreadData.resize(nthreads); fThreadSize = nthreads; - for (Int_t tid=0; tidSetXY(td.fXc, td.fYc); // initialize with current coordinates td.fPoly->FinishPolygon(); @@ -189,18 +186,18 @@ void TGeoXtru::SetSeg(Int_t iseg) /// dummy ctor TGeoXtru::TGeoXtru() - :TGeoBBox(), - fNvert(0), - fNz(0), - fZcurrent(0.), - fX(0), - fY(0), - fZ(0), - fScale(0), - fX0(0), - fY0(0), - fThreadData(0), - fThreadSize(0) + : TGeoBBox(), + fNvert(0), + fNz(0), + fZcurrent(0.), + fX(0), + fY(0), + fZ(0), + fScale(0), + fX0(0), + fY0(0), + fThreadData(0), + fThreadSize(0) { SetShapeBit(TGeoShape::kGeoXtru); } @@ -209,21 +206,21 @@ TGeoXtru::TGeoXtru() /// Default constructor TGeoXtru::TGeoXtru(Int_t nz) - :TGeoBBox(0, 0, 0), - fNvert(0), - fNz(nz), - fZcurrent(0.), - fX(0), - fY(0), - fZ(new Double_t[nz]), - fScale(new Double_t[nz]), - fX0(new Double_t[nz]), - fY0(new Double_t[nz]), - fThreadData(0), - fThreadSize(0) + : TGeoBBox(0, 0, 0), + fNvert(0), + fNz(nz), + fZcurrent(0.), + fX(0), + fY(0), + fZ(new Double_t[nz]), + fScale(new Double_t[nz]), + fX0(new Double_t[nz]), + fY0(new Double_t[nz]), + fThreadData(0), + fThreadSize(0) { SetShapeBit(TGeoShape::kGeoXtru); - if (nz<2) { + if (nz < 2) { Error("ctor", "Cannot create TGeoXtru %s with less than 2 Z planes", GetName()); SetShapeBit(TGeoShape::kGeoBad); return; @@ -245,18 +242,18 @@ TGeoXtru::TGeoXtru(Int_t nz) /// - param[4*(nz-1)+4] = scalen TGeoXtru::TGeoXtru(Double_t *param) - :TGeoBBox(0, 0, 0), - fNvert(0), - fNz(0), - fZcurrent(0.), - fX(0), - fY(0), - fZ(0), - fScale(0), - fX0(0), - fY0(0), - fThreadData(0), - fThreadSize(0) + : TGeoBBox(0, 0, 0), + fNvert(0), + fNz(0), + fZcurrent(0.), + fX(0), + fY(0), + fZ(0), + fScale(0), + fX0(0), + fY0(0), + fThreadData(0), + fThreadSize(0) { SetShapeBit(TGeoShape::kGeoXtru); SetDimensions(param); @@ -267,12 +264,30 @@ TGeoXtru::TGeoXtru(Double_t *param) TGeoXtru::~TGeoXtru() { - if (fX) {delete[] fX; fX = 0;} - if (fY) {delete[] fY; fY = 0;} - if (fZ) {delete[] fZ; fZ = 0;} - if (fScale) {delete[] fScale; fScale = 0;} - if (fX0) {delete[] fX0; fX0 = 0;} - if (fY0) {delete[] fY0; fY0 = 0;} + if (fX) { + delete[] fX; + fX = 0; + } + if (fY) { + delete[] fY; + fY = 0; + } + if (fZ) { + delete[] fZ; + fZ = 0; + } + if (fScale) { + delete[] fScale; + fScale = 0; + } + if (fX0) { + delete[] fX0; + fX0 = 0; + } + if (fY0) { + delete[] fY0; + fY0 = 0; + } ClearThreadData(); } @@ -281,19 +296,20 @@ TGeoXtru::~TGeoXtru() Double_t TGeoXtru::Capacity() const { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); Int_t iz; Double_t capacity = 0; Double_t area, dz, sc1, sc2; - TGeoXtru *xtru = (TGeoXtru*)this; - xtru->SetCurrentVertices(0.,0.,1.); + TGeoXtru *xtru = (TGeoXtru *)this; + xtru->SetCurrentVertices(0., 0., 1.); area = td.fPoly->Area(); - for (iz=0; izxmax) xmax=td.fXc[j]; - if (td.fYc[j]ymax) ymax=td.fYc[j]; + for (Int_t j = 0; j < fNvert; j++) { + if (td.fXc[j] < xmin) + xmin = td.fXc[j]; + if (td.fXc[j] > xmax) + xmax = td.fXc[j]; + if (td.fYc[j] < ymin) + ymin = td.fYc[j]; + if (td.fYc[j] > ymax) + ymax = td.fYc[j]; } } - fOrigin[0] = 0.5*(xmin+xmax); - fOrigin[1] = 0.5*(ymin+ymax); - fOrigin[2] = 0.5*(zmin+zmax); - fDX = 0.5*(xmax-xmin); - fDY = 0.5*(ymax-ymin); - fDZ = 0.5*(zmax-zmin); + fOrigin[0] = 0.5 * (xmin + xmax); + fOrigin[1] = 0.5 * (ymin + ymax); + fOrigin[2] = 0.5 * (zmin + zmax); + fDX = 0.5 * (xmax - xmin); + fDY = 0.5 * (ymax - ymin); + fDZ = 0.5 * (zmax - zmin); } //////////////////////////////////////////////////////////////////////////////// @@ -337,17 +357,17 @@ void TGeoXtru::ComputeBBox() void TGeoXtru::ComputeNormal(const Double_t * /*point*/, const Double_t *dir, Double_t *norm) { - ThreadData_t& td = GetThreadData(); - if (td.fIz<0) { - memset(norm,0,3*sizeof(Double_t)); - norm[2] = (dir[2]>0)?1:-1; + ThreadData_t &td = GetThreadData(); + if (td.fIz < 0) { + memset(norm, 0, 3 * sizeof(Double_t)); + norm[2] = (dir[2] > 0) ? 1 : -1; return; } Double_t vert[12]; GetPlaneVertices(td.fIz, td.fSeg, vert); GetPlaneNormal(vert, norm); - Double_t ndotd = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - if (ndotd<0) { + Double_t ndotd = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + if (ndotd < 0) { norm[0] = -norm[0]; norm[1] = -norm[1]; norm[2] = -norm[2]; @@ -359,28 +379,33 @@ void TGeoXtru::ComputeNormal(const Double_t * /*point*/, const Double_t *dir, Do Bool_t TGeoXtru::Contains(const Double_t *point) const { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); // Check Z range - TGeoXtru *xtru = (TGeoXtru*)this; - if (point[2]fZ[fNz-1]) return kFALSE; + TGeoXtru *xtru = (TGeoXtru *)this; + if (point[2] < fZ[0]) + return kFALSE; + if (point[2] > fZ[fNz - 1]) + return kFALSE; Int_t iz = TMath::BinarySearch(fNz, fZ, point[2]); - if (iz<0 || iz==fNz-1) return kFALSE; - if (TGeoShape::IsSameWithinTolerance(point[2],fZ[iz])) { + if (iz < 0 || iz == fNz - 1) + return kFALSE; + if (TGeoShape::IsSameWithinTolerance(point[2], fZ[iz])) { xtru->SetIz(-1); - xtru->SetCurrentVertices(fX0[iz],fY0[iz], fScale[iz]); - if (td.fPoly->Contains(point)) return kTRUE; - if (iz>1 && TGeoShape::IsSameWithinTolerance(fZ[iz],fZ[iz-1])) { - xtru->SetCurrentVertices(fX0[iz-1],fY0[iz-1], fScale[iz-1]); + xtru->SetCurrentVertices(fX0[iz], fY0[iz], fScale[iz]); + if (td.fPoly->Contains(point)) + return kTRUE; + if (iz > 1 && TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz - 1])) { + xtru->SetCurrentVertices(fX0[iz - 1], fY0[iz - 1], fScale[iz - 1]); return td.fPoly->Contains(point); - } else if (izSetCurrentVertices(fX0[iz+1],fY0[iz+1], fScale[iz+1]); + } else if (iz < fNz - 2 && TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz + 1])) { + xtru->SetCurrentVertices(fX0[iz + 1], fY0[iz + 1], fScale[iz + 1]); return td.fPoly->Contains(point); } } xtru->SetCurrentZ(point[2], iz); - if (TMath::Abs(point[2]-fZ[iz])SetIz(-1); + if (TMath::Abs(point[2] - fZ[iz]) < TGeoShape::Tolerance() || + TMath::Abs(fZ[iz + 1] - point[2]) < TGeoShape::Tolerance()) + xtru->SetIz(-1); // Now td.fXc,fYc represent the vertices of the section at point[2] return td.fPoly->Contains(point); } @@ -390,7 +415,7 @@ Bool_t TGeoXtru::Contains(const Double_t *point) const Int_t TGeoXtru::DistancetoPrimitive(Int_t px, Int_t py) { - const Int_t numPoints = fNvert*fNz; + const Int_t numPoints = fNvert * fNz; return ShapeDistancetoPrimitive(numPoints, px, py); } @@ -398,63 +423,73 @@ Int_t TGeoXtru::DistancetoPrimitive(Int_t px, Int_t py) /// Draw the section polygon. void TGeoXtru::DrawPolygon(Option_t *option) - { - ThreadData_t& td = GetThreadData(); - if (td.fPoly) td.fPoly->Draw(option); +{ + ThreadData_t &td = GetThreadData(); + if (td.fPoly) + td.fPoly->Draw(option); } //////////////////////////////////////////////////////////////////////////////// /// Compute distance to a Xtru lateral surface. -Double_t TGeoXtru::DistToPlane(const Double_t *point, const Double_t *dir, Int_t iz, Int_t ivert, Double_t stepmax, Bool_t in) const +Double_t TGeoXtru::DistToPlane(const Double_t *point, const Double_t *dir, Int_t iz, Int_t ivert, Double_t stepmax, + Bool_t in) const { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); Double_t snext; Double_t vert[12]; Double_t norm[3]; Double_t znew; Double_t pt[3]; Double_t safe; - if (TGeoShape::IsSameWithinTolerance(fZ[iz],fZ[iz+1]) && !in) { - TGeoXtru *xtru = (TGeoXtru*)this; - snext = (fZ[iz]-point[2])/dir[2]; - if (snext<0) return TGeoShape::Big(); - pt[0] = point[0]+snext*dir[0]; - pt[1] = point[1]+snext*dir[1]; - pt[2] = point[2]+snext*dir[2]; - if (dir[2] < 0.) xtru->SetCurrentVertices(fX0[iz], fY0[iz], fScale[iz]); - else xtru->SetCurrentVertices(fX0[iz+1], fY0[iz+1], fScale[iz+1]); - if (!td.fPoly->Contains(pt)) return TGeoShape::Big(); + if (TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz + 1]) && !in) { + TGeoXtru *xtru = (TGeoXtru *)this; + snext = (fZ[iz] - point[2]) / dir[2]; + if (snext < 0) + return TGeoShape::Big(); + pt[0] = point[0] + snext * dir[0]; + pt[1] = point[1] + snext * dir[1]; + pt[2] = point[2] + snext * dir[2]; + if (dir[2] < 0.) + xtru->SetCurrentVertices(fX0[iz], fY0[iz], fScale[iz]); + else + xtru->SetCurrentVertices(fX0[iz + 1], fY0[iz + 1], fScale[iz + 1]); + if (!td.fPoly->Contains(pt)) + return TGeoShape::Big(); return snext; } GetPlaneVertices(iz, ivert, vert); GetPlaneNormal(vert, norm); - Double_t ndotd = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; + Double_t ndotd = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; if (in) { - if (ndotd<=0) return TGeoShape::Big(); - safe = (vert[0]-point[0])*norm[0]+ - (vert[1]-point[1])*norm[1]+ - (vert[2]-point[2])*norm[2]; - if (safe<-1.E-8) return TGeoShape::Big(); // direction outwards plane + if (ndotd <= 0) + return TGeoShape::Big(); + safe = (vert[0] - point[0]) * norm[0] + (vert[1] - point[1]) * norm[1] + (vert[2] - point[2]) * norm[2]; + if (safe < -1.E-8) + return TGeoShape::Big(); // direction outwards plane } else { ndotd = -ndotd; - if (ndotd<=0) return TGeoShape::Big(); - safe = (point[0]-vert[0])*norm[0]+ - (point[1]-vert[1])*norm[1]+ - (point[2]-vert[2])*norm[2]; - if (safe<-1.E-8) return TGeoShape::Big(); // direction outwards plane + if (ndotd <= 0) + return TGeoShape::Big(); + safe = (point[0] - vert[0]) * norm[0] + (point[1] - vert[1]) * norm[1] + (point[2] - vert[2]) * norm[2]; + if (safe < -1.E-8) + return TGeoShape::Big(); // direction outwards plane } - snext = safe/ndotd; - if (snext>stepmax) return TGeoShape::Big(); - if (fZ[iz]fZ[iz+1]) return TGeoShape::Big(); + snext = safe / ndotd; + if (snext > stepmax) + return TGeoShape::Big(); + if (fZ[iz] < fZ[iz + 1]) { + znew = point[2] + snext * dir[2]; + if (znew < fZ[iz]) + return TGeoShape::Big(); + if (znew > fZ[iz + 1]) + return TGeoShape::Big(); } - pt[0] = point[0]+snext*dir[0]; - pt[1] = point[1]+snext*dir[1]; - pt[2] = point[2]+snext*dir[2]; - if (!IsPointInsidePlane(pt, vert, norm)) return TGeoShape::Big(); + pt[0] = point[0] + snext * dir[0]; + pt[1] = point[1] + snext * dir[1]; + pt[2] = point[2] + snext * dir[2]; + if (!IsPointInsidePlane(pt, vert, norm)) + return TGeoShape::Big(); return TMath::Max(snext, 0.); } @@ -462,89 +497,98 @@ Double_t TGeoXtru::DistToPlane(const Double_t *point, const Double_t *dir, Int_t /// compute distance from inside point to surface of the polycone /// locate Z segment -Double_t TGeoXtru::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoXtru::DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - ThreadData_t& td = GetThreadData(); - if (iact<3 && safe) { + ThreadData_t &td = GetThreadData(); + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } - TGeoXtru *xtru = (TGeoXtru*)this; + TGeoXtru *xtru = (TGeoXtru *)this; Int_t iz = TMath::BinarySearch(fNz, fZ, point[2]); if (iz < 0) { - if (dir[2]<=0) { + if (dir[2] <= 0) { xtru->SetIz(-1); return 0.; } iz = 0; } - if (iz==fNz-1) { - if (dir[2]>=0) { + if (iz == fNz - 1) { + if (dir[2] >= 0) { xtru->SetIz(-1); return 0.; } iz--; } else { - if (iz>0) { - if (TGeoShape::IsSameWithinTolerance(point[2],fZ[iz])) { - if (TGeoShape::IsSameWithinTolerance(fZ[iz],fZ[iz+1]) && dir[2]<0) iz++; - else if (TGeoShape::IsSameWithinTolerance(fZ[iz],fZ[iz-1]) && dir[2]>0) iz--; + if (iz > 0) { + if (TGeoShape::IsSameWithinTolerance(point[2], fZ[iz])) { + if (TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz + 1]) && dir[2] < 0) + iz++; + else if (TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz - 1]) && dir[2] > 0) + iz--; } } } Bool_t convex = td.fPoly->IsConvex(); -// Double_t stepmax = step; -// if (stepmax>TGeoShape::Big()) stepmax = TGeoShape::Big(); + // Double_t stepmax = step; + // if (stepmax>TGeoShape::Big()) stepmax = TGeoShape::Big(); Double_t snext = TGeoShape::Big(); Double_t dist, sz; Double_t pt[3]; Int_t iv, ipl, inext; // we treat the special case when dir[2]=0 - if (TGeoShape::IsSameWithinTolerance(dir[2],0)) { - for (iv=0; ivSetIz(-1); - dist = DistToPlane(point,dir,iz,iv,TGeoShape::Big(),kTRUE); - if (distSetSeg(iv); - if (convex) return snext; + if (convex) + return snext; } } - if (snext < 1.E10) return snext; + if (snext < 1.E10) + return snext; return TGeoShape::Tolerance(); } // normal case - Int_t incseg = (dir[2]>0)?1:-1; + Int_t incseg = (dir[2] > 0) ? 1 : -1; Int_t iznext = iz; Bool_t zexit = kFALSE; - while (iz>=0 && iz= 0 && iz < fNz - 1) { // find the distance to current segment end Z surface - ipl = iz+((incseg+1)>>1); // next plane - inext = ipl+incseg; // next next plane - sz = (fZ[ipl]-point[2])/dir[2]; - if (sz> 1); // next plane + inext = ipl + incseg; // next next plane + sz = (fZ[ipl] - point[2]) / dir[2]; + if (sz < snext) { iznext += incseg; // we cross the next Z section before stepmax - pt[0] = point[0]+sz*dir[0]; - pt[1] = point[1]+sz*dir[1]; - xtru->SetCurrentVertices(fX0[ipl],fY0[ipl],fScale[ipl]); + pt[0] = point[0] + sz * dir[0]; + pt[1] = point[1] + sz * dir[1]; + xtru->SetCurrentVertices(fX0[ipl], fY0[ipl], fScale[ipl]); if (td.fPoly->Contains(pt)) { // ray gets through next polygon - is it the last one? - if (ipl==0 || ipl==fNz-1) { + if (ipl == 0 || ipl == fNz - 1) { xtru->SetIz(-1); - if (convex) return sz; + if (convex) + return sz; zexit = kTRUE; snext = sz; } // maybe a Z discontinuity - check this - if (!zexit && TGeoShape::IsSameWithinTolerance(fZ[ipl],fZ[inext])) { - xtru->SetCurrentVertices(fX0[inext],fY0[inext],fScale[inext]); + if (!zexit && TGeoShape::IsSameWithinTolerance(fZ[ipl], fZ[inext])) { + xtru->SetCurrentVertices(fX0[inext], fY0[inext], fScale[inext]); // if we do not cross the next polygone, we are out if (!td.fPoly->Contains(pt)) { xtru->SetIz(-1); - if (convex) return sz; + if (convex) + return sz; zexit = kTRUE; snext = sz; } else { @@ -553,20 +597,22 @@ Double_t TGeoXtru::DistFromInside(const Double_t *point, const Double_t *dir, In } } } else { - iznext = fNz-1; // stop + iznext = fNz - 1; // stop } // ray may cross the lateral surfaces of section iz - for (iv=0; ivSetIz(iz); xtru->SetSeg(iv); snext = dist; - if (convex) return snext; + if (convex) + return snext; zexit = kTRUE; } } - if (zexit) return snext; + if (zexit) + return snext; iz = iznext; } return TGeoShape::Tolerance(); @@ -576,65 +622,82 @@ Double_t TGeoXtru::DistFromInside(const Double_t *point, const Double_t *dir, In /// compute distance from outside point to surface of the tube /// Warning("DistFromOutside", "not implemented"); -Double_t TGeoXtru::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const +Double_t +TGeoXtru::DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const { - ThreadData_t& td = GetThreadData(); - if (iact<3 && safe) { + ThreadData_t &td = GetThreadData(); + if (iact < 3 && safe) { *safe = Safety(point, kTRUE); - if (iact==0) return TGeoShape::Big(); - if (iact==1 && step<*safe) return TGeoShape::Big(); + if (iact == 0) + return TGeoShape::Big(); + if (iact == 1 && step < *safe) + return TGeoShape::Big(); } -// Check if the bounding box is crossed within the requested distance - Double_t sdist = TGeoBBox::DistFromOutside(point,dir, fDX, fDY, fDZ, fOrigin, step); - if (sdist>=step) return TGeoShape::Big(); + // Check if the bounding box is crossed within the requested distance + Double_t sdist = TGeoBBox::DistFromOutside(point, dir, fDX, fDY, fDZ, fOrigin, step); + if (sdist >= step) + return TGeoShape::Big(); Double_t stepmax = step; - if (stepmax>TGeoShape::Big()) stepmax = TGeoShape::Big(); + if (stepmax > TGeoShape::Big()) + stepmax = TGeoShape::Big(); Double_t snext = 0.; Int_t i, iv; Double_t pt[3]; - memcpy(pt,point,3*sizeof(Double_t)); - TGeoXtru *xtru = (TGeoXtru*)this; + memcpy(pt, point, 3 * sizeof(Double_t)); + TGeoXtru *xtru = (TGeoXtru *)this; // We might get out easy with Z checks Int_t iz = TMath::BinarySearch(fNz, fZ, point[2]); - if (iz<0) { - if (dir[2]<=0) return TGeoShape::Big(); + if (iz < 0) { + if (dir[2] <= 0) + return TGeoShape::Big(); // propagate to first Z plane - snext = (fZ[0] - point[2])/dir[2]; - if (snext>stepmax) return TGeoShape::Big(); - for (i=0; i<3; i++) pt[i] = point[i] + snext*dir[i]; - xtru->SetCurrentVertices(fX0[0],fY0[0],fScale[0]); + snext = (fZ[0] - point[2]) / dir[2]; + if (snext > stepmax) + return TGeoShape::Big(); + for (i = 0; i < 3; i++) + pt[i] = point[i] + snext * dir[i]; + xtru->SetCurrentVertices(fX0[0], fY0[0], fScale[0]); if (td.fPoly->Contains(pt)) { xtru->SetIz(-1); return snext; } - iz=0; // valid starting value = first segment + iz = 0; // valid starting value = first segment stepmax -= snext; } else { - if (iz==fNz-1) { - if (dir[2]>=0) return TGeoShape::Big(); + if (iz == fNz - 1) { + if (dir[2] >= 0) + return TGeoShape::Big(); // propagate to last Z plane - snext = (fZ[fNz-1] - point[2])/dir[2]; - if (snext>stepmax) return TGeoShape::Big(); - for (i=0; i<3; i++) pt[i] = point[i] + snext*dir[i]; - xtru->SetCurrentVertices(fX0[fNz-1],fY0[fNz-1],fScale[fNz-1]); + snext = (fZ[fNz - 1] - point[2]) / dir[2]; + if (snext > stepmax) + return TGeoShape::Big(); + for (i = 0; i < 3; i++) + pt[i] = point[i] + snext * dir[i]; + xtru->SetCurrentVertices(fX0[fNz - 1], fY0[fNz - 1], fScale[fNz - 1]); if (td.fPoly->Contains(pt)) { xtru->SetIz(-1); return snext; } - iz = fNz-2; // valid value = last segment + iz = fNz - 2; // valid value = last segment stepmax -= snext; } } // Check if the bounding box is missed by the track if (!TGeoBBox::Contains(pt)) { - Double_t dist = TGeoBBox::DistFromOutside(pt,dir,3); - if (dist>stepmax) return TGeoShape::Big(); - if (dist>1E-6) dist-=1E-6; // decrease snext to make sure we do not cross the xtru - else dist = 0; - for (i=0; i<3; i++) pt[i] += dist*dir[i]; // we are now closer + Double_t dist = TGeoBBox::DistFromOutside(pt, dir, 3); + if (dist > stepmax) + return TGeoShape::Big(); + if (dist > 1E-6) + dist -= 1E-6; // decrease snext to make sure we do not cross the xtru + else + dist = 0; + for (i = 0; i < 3; i++) + pt[i] += dist * dir[i]; // we are now closer iz = TMath::BinarySearch(fNz, fZ, pt[2]); - if (iz<0) iz=0; - else if (iz==fNz-1) iz = fNz-2; + if (iz < 0) + iz = 0; + else if (iz == fNz - 1) + iz = fNz - 2; snext += dist; stepmax -= dist; } @@ -643,38 +706,43 @@ Double_t TGeoXtru::DistFromOutside(const Double_t *point, const Double_t *dir, I // - first solve particular case dir[2]=0 Bool_t convex = td.fPoly->IsConvex(); Bool_t hit = kFALSE; - if (TGeoShape::IsSameWithinTolerance(dir[2],0)) { + if (TGeoShape::IsSameWithinTolerance(dir[2], 0)) { // loop lateral planes to see if we cross something xtru->SetIz(iz); - for (iv=0; ivSetSeg(iv); - if (convex) return (snext+dist); + if (convex) + return (snext + dist); stepmax = dist; hit = kTRUE; } } - if (hit) return (snext+stepmax); + if (hit) + return (snext + stepmax); return TGeoShape::Big(); } // general case - Int_t incseg = (dir[2]>0)?1:-1; - while (iz>=0 && iz 0) ? 1 : -1; + while (iz >= 0 && iz < fNz - 1) { // compute distance to lateral planes xtru->SetIz(iz); - if (TGeoShape::IsSameWithinTolerance(fZ[iz],fZ[iz+1])) xtru->SetIz(-1); - for (iv=0; ivSetIz(-1); + for (iv = 0; iv < fNvert; iv++) { + Double_t dist = DistToPlane(pt, dir, iz, iv, stepmax, kFALSE); + if (dist < stepmax) { // HIT xtru->SetSeg(iv); - if (convex) return (snext+dist); + if (convex) + return (snext + dist); stepmax = dist; hit = kTRUE; } } - if (hit) return (snext+stepmax); + if (hit) + return (snext + stepmax); iz += incseg; } return TGeoShape::Big(); @@ -690,28 +758,29 @@ Double_t TGeoXtru::DistFromOutside(const Double_t *point, const Double_t *dir, I Bool_t TGeoXtru::DefinePolygon(Int_t nvert, const Double_t *xv, const Double_t *yv) { - if (nvert<3) { - Error("DefinePolygon","In shape %s cannot create polygon with less than 3 vertices", GetName()); + if (nvert < 3) { + Error("DefinePolygon", "In shape %s cannot create polygon with less than 3 vertices", GetName()); SetShapeBit(TGeoShape::kGeoBad); return kFALSE; } - for (Int_t i=0; i=fNz)) return; - fZ[snum] = z; + if ((snum < 0) || (snum >= fNz)) + return; + fZ[snum] = z; fX0[snum] = x0; fY0[snum] = y0; fScale[snum] = scale; if (snum) { - if (fZ[snum](fNz-1)) { - Error("GetZ","In shape %s, ipl=%i out of range (0,%i)",GetName(),ipl,fNz-1); + if (ipl < 0 || ipl > (fNz - 1)) { + Error("GetZ", "In shape %s, ipl=%i out of range (0,%i)", GetName(), ipl, fNz - 1); return 0.; } return fZ[ipl]; @@ -761,21 +833,23 @@ void TGeoXtru::GetPlaneNormal(const Double_t *vert, Double_t *norm) const { Double_t cross = 0.; Double_t v1[3], v2[3]; - v1[0] = vert[9]-vert[0]; - v1[1] = vert[10]-vert[1]; - v1[2] = vert[11]-vert[2]; - v2[0] = vert[3]-vert[0]; - v2[1] = vert[4]-vert[1]; - v2[2] = vert[5]-vert[2]; - norm[0] = v1[1]*v2[2]-v1[2]*v2[1]; - cross += norm[0]*norm[0]; - norm[1] = v1[2]*v2[0]-v1[0]*v2[2]; - cross += norm[1]*norm[1]; - norm[2] = v1[0]*v2[1]-v1[1]*v2[0]; - cross += norm[2]*norm[2]; - if (cross < TGeoShape::Tolerance()) return; - cross = 1./TMath::Sqrt(cross); - for (Int_t i=0; i<3; i++) norm[i] *= cross; + v1[0] = vert[9] - vert[0]; + v1[1] = vert[10] - vert[1]; + v1[2] = vert[11] - vert[2]; + v2[0] = vert[3] - vert[0]; + v2[1] = vert[4] - vert[1]; + v2[2] = vert[5] - vert[2]; + norm[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross += norm[0] * norm[0]; + norm[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross += norm[1] * norm[1]; + norm[2] = v1[0] * v2[1] - v1[1] * v2[0]; + cross += norm[2] * norm[2]; + if (cross < TGeoShape::Tolerance()) + return; + cross = 1. / TMath::Sqrt(cross); + for (Int_t i = 0; i < 3; i++) + norm[i] *= cross; } //////////////////////////////////////////////////////////////////////////////// @@ -784,51 +858,51 @@ void TGeoXtru::GetPlaneNormal(const Double_t *vert, Double_t *norm) const void TGeoXtru::GetPlaneVertices(Int_t iz, Int_t ivert, Double_t *vert) const { - ThreadData_t& td = GetThreadData(); - Double_t x,y,z1,z2; - Int_t iv1 = (ivert+1)%fNvert; + ThreadData_t &td = GetThreadData(); + Double_t x, y, z1, z2; + Int_t iv1 = (ivert + 1) % fNvert; Int_t icrt = 0; z1 = fZ[iz]; - z2 = fZ[iz+1]; + z2 = fZ[iz + 1]; if (td.fPoly->IsClockwise()) { - x = fX[ivert]*fScale[iz]+fX0[iz]; - y = fY[ivert]*fScale[iz]+fY0[iz]; + x = fX[ivert] * fScale[iz] + fX0[iz]; + y = fY[ivert] * fScale[iz] + fY0[iz]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z1; - x = fX[iv1]*fScale[iz]+fX0[iz]; - y = fY[iv1]*fScale[iz]+fY0[iz]; + x = fX[iv1] * fScale[iz] + fX0[iz]; + y = fY[iv1] * fScale[iz] + fY0[iz]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z1; - x = fX[iv1]*fScale[iz+1]+fX0[iz+1]; - y = fY[iv1]*fScale[iz+1]+fY0[iz+1]; + x = fX[iv1] * fScale[iz + 1] + fX0[iz + 1]; + y = fY[iv1] * fScale[iz + 1] + fY0[iz + 1]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z2; - x = fX[ivert]*fScale[iz+1]+fX0[iz+1]; - y = fY[ivert]*fScale[iz+1]+fY0[iz+1]; + x = fX[ivert] * fScale[iz + 1] + fX0[iz + 1]; + y = fY[ivert] * fScale[iz + 1] + fY0[iz + 1]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z2; } else { - x = fX[iv1]*fScale[iz]+fX0[iz]; - y = fY[iv1]*fScale[iz]+fY0[iz]; + x = fX[iv1] * fScale[iz] + fX0[iz]; + y = fY[iv1] * fScale[iz] + fY0[iz]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z1; - x = fX[ivert]*fScale[iz]+fX0[iz]; - y = fY[ivert]*fScale[iz]+fY0[iz]; + x = fX[ivert] * fScale[iz] + fX0[iz]; + y = fY[ivert] * fScale[iz] + fY0[iz]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z1; - x = fX[ivert]*fScale[iz+1]+fX0[iz+1]; - y = fY[ivert]*fScale[iz+1]+fY0[iz+1]; + x = fX[ivert] * fScale[iz + 1] + fX0[iz + 1]; + y = fY[ivert] * fScale[iz + 1] + fY0[iz + 1]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z2; - x = fX[iv1]*fScale[iz+1]+fX0[iz+1]; - y = fY[iv1]*fScale[iz+1]+fY0[iz+1]; + x = fX[iv1] * fScale[iz + 1] + fX0[iz + 1]; + y = fY[iv1] * fScale[iz + 1] + fY0[iz + 1]; vert[icrt++] = x; vert[icrt++] = y; vert[icrt++] = z2; @@ -841,20 +915,20 @@ Bool_t TGeoXtru::IsPointInsidePlane(const Double_t *point, Double_t *vert, Doubl { Double_t v1[3], v2[3]; Double_t cross; - Int_t j,k; - for (Int_t i=0; i<4; i++) { // loop vertices - j = 3*i; - k = 3*((i+1)%4); - v1[0] = point[0]-vert[j]; - v1[1] = point[1]-vert[j+1]; - v1[2] = point[2]-vert[j+2]; - v2[0] = vert[k]-vert[j]; - v2[1] = vert[k+1]-vert[j+1]; - v2[2] = vert[k+2]-vert[j+2]; - cross = (v1[1]*v2[2]-v1[2]*v2[1])*norm[0]+ - (v1[2]*v2[0]-v1[0]*v2[2])*norm[1]+ - (v1[0]*v2[1]-v1[1]*v2[0])*norm[2]; - if (cross<0) return kFALSE; + Int_t j, k; + for (Int_t i = 0; i < 4; i++) { // loop vertices + j = 3 * i; + k = 3 * ((i + 1) % 4); + v1[0] = point[0] - vert[j]; + v1[1] = point[1] - vert[j + 1]; + v1[2] = point[2] - vert[j + 2]; + v2[0] = vert[k] - vert[j]; + v2[1] = vert[k + 1] - vert[j + 1]; + v2[2] = vert[k + 2] - vert[j + 2]; + cross = (v1[1] * v2[2] - v1[2] * v2[1]) * norm[0] + (v1[2] * v2[0] - v1[0] * v2[2]) * norm[1] + + (v1[0] * v2[1] - v1[1] * v2[0]) * norm[2]; + if (cross < 0) + return kFALSE; } return kTRUE; } @@ -867,10 +941,11 @@ void TGeoXtru::InspectShape() const printf("*** Shape %s: TGeoXtru ***\n", GetName()); printf(" Nz = %i\n", fNz); printf(" List of (x,y) of polygon vertices:\n"); - for (Int_t ivert = 0; ivertfPnts); SetSegsAndPols(*buff); } @@ -907,59 +981,59 @@ void TGeoXtru::SetSegsAndPols(TBuffer3D &buff) const Int_t nvert = GetNvert(); Int_t c = GetBasicColor(); - Int_t i,j; + Int_t i, j; Int_t indx = 0, indx2, k; - for (i=0; i= 0; --j) { - buff.fPols[indx++] = indx2+j; + buff.fPols[indx++] = indx2 + j; } buff.fPols[indx++] = c; buff.fPols[indx++] = nvert; - indx2 = (nz-1)*nvert; + indx2 = (nz - 1) * nvert; - for (j=0; jsafmin) return TGeoShape::Big(); + if (TGeoShape::IsSameWithinTolerance(fZ[iz], fZ[iz + 1])) { + safz = TMath::Abs(point[2] - fZ[iz]); + if (safz > safmin) + return TGeoShape::Big(); SetCurrentVertices(fX0[iz], fY0[iz], fScale[iz]); saf1 = td.fPoly->Safety(point, iseg); in1 = td.fPoly->Contains(point); -// if (!in1 && saf1>safmin) return TGeoShape::Big(); - SetCurrentVertices(fX0[iz+1], fY0[iz+1], fScale[iz+1]); + // if (!in1 && saf1>safmin) return TGeoShape::Big(); + SetCurrentVertices(fX0[iz + 1], fY0[iz + 1], fScale[iz + 1]); saf2 = td.fPoly->Safety(point, iseg); in2 = td.fPoly->Contains(point); - if ((in1&!in2)|(in2&!in1)) { + if ((in1 & !in2) | (in2 & !in1)) { safe = safz; } else { - safe = TMath::Min(saf1,saf2); + safe = TMath::Min(saf1, saf2); safe = TMath::Max(safe, safz); } - if (safe>safmin) return TGeoShape::Big(); + if (safe > safmin) + return TGeoShape::Big(); return safe; } // normal case - safz = fZ[iz]-point[2]; - if (safz>safmin) return TGeoShape::Big(); - if (safz<0) { - saf1 = point[2]-fZ[iz+1]; - if (saf1>safmin) return TGeoShape::Big(); - if (saf1<0) { + safz = fZ[iz] - point[2]; + if (safz > safmin) + return TGeoShape::Big(); + if (safz < 0) { + saf1 = point[2] - fZ[iz + 1]; + if (saf1 > safmin) + return TGeoShape::Big(); + if (saf1 < 0) { safz = TMath::Max(safz, saf1); // we are in between the 2 Z segments - we ignore safz } else { safz = saf1; @@ -1009,21 +1087,26 @@ Double_t TGeoXtru::SafetyToSector(const Double_t *point, Int_t iz, Double_t safm Bool_t found = kFALSE; Double_t vert[12]; Double_t norm[3]; -// printf("plane %d: safz=%f in=%d\n", iz, safz, in); - for (iseg=0; isegsafmin) continue; + if (safe > safmin) + continue; safmin = safe; found = kTRUE; } - if (found) return safmin; + if (found) + return safmin; return TGeoShape::Big(); } @@ -1037,38 +1120,42 @@ Double_t TGeoXtru::Safety(const Double_t *point, Bool_t in) const Double_t safmin = TGeoShape::Big(); Double_t safe; Double_t safz = TGeoShape::Big(); - TGeoXtru *xtru = (TGeoXtru*)this; + TGeoXtru *xtru = (TGeoXtru *)this; Int_t iz; if (in) { - safmin = TMath::Min(point[2]-fZ[0], fZ[fNz-1]-point[2]); - for (iz=0; izSafetyToSector(point, iz, safmin, in); - if (safeSafetyToSector(point,i,safmin, in); - if (safeSafetyToSector(point, i, safmin, in); + if (safe < safmin) + safmin = safe; } // loop segments from iz-1 down - for (i=iz-1; i>=0; i--) { - safe = xtru->SafetyToSector(point,i,safmin, in); - if (safe= 0; i--) { + safe = xtru->SafetyToSector(point, i, safmin, in); + if (safe < safmin) + safmin = safe; } safe = TMath::Min(safmin, safz); return safe; @@ -1079,16 +1166,18 @@ Double_t TGeoXtru::Safety(const Double_t *point, Bool_t in) const void TGeoXtru::SavePrimitive(std::ostream &out, Option_t * /*option*/ /*= ""*/) { - if (TObject::TestBit(kGeoSavePrimitive)) return; + if (TObject::TestBit(kGeoSavePrimitive)) + return; out << " // Shape: " << GetName() << " type: " << ClassName() << std::endl; out << " auto " << GetPointerName() << " = new TGeoXtru(" << fNz << ");" << std::endl; out << " " << GetPointerName() << "->SetName(\"" << GetName() << "\");" << std::endl; - for (Int_t i=0; iDefinePolygon(" << fNvert << ", xvert, yvert);" << std::endl; - for (Int_t i=0; iDefineSection(" << i << ", " << fZ[i] << ", " << fX0[i] << ", " << fY0[i] << ", " << fScale[i] << ");" << std::endl; + for (Int_t i = 0; i < fNz; i++) + out << " " << GetPointerName() << "->DefineSection(" << i << ", " << fZ[i] << ", " << fX0[i] << ", " << fY0[i] + << ", " << fScale[i] << ");" << std::endl; TObject::SetBit(TGeoShape::kGeoSavePrimitive); } @@ -1100,18 +1189,18 @@ void TGeoXtru::SetCurrentZ(Double_t z, Int_t iz) Double_t x0, y0, scale, a, b; Int_t ind1, ind2; ind1 = iz; - ind2 = iz+1; - Double_t invdz = 1./(fZ[ind2]-fZ[ind1]); - a = (fX0[ind1]*fZ[ind2]-fX0[ind2]*fZ[ind1])*invdz; - b = (fX0[ind2]-fX0[ind1])*invdz; - x0 = a+b*z; - a = (fY0[ind1]*fZ[ind2]-fY0[ind2]*fZ[ind1])*invdz; - b = (fY0[ind2]-fY0[ind1])*invdz; - y0 = a+b*z; - a = (fScale[ind1]*fZ[ind2]-fScale[ind2]*fZ[ind1])*invdz; - b = (fScale[ind2]-fScale[ind1])*invdz; - scale = a+b*z; - SetCurrentVertices(x0,y0,scale); + ind2 = iz + 1; + Double_t invdz = 1. / (fZ[ind2] - fZ[ind1]); + a = (fX0[ind1] * fZ[ind2] - fX0[ind2] * fZ[ind1]) * invdz; + b = (fX0[ind2] - fX0[ind1]) * invdz; + x0 = a + b * z; + a = (fY0[ind1] * fZ[ind2] - fY0[ind2] * fZ[ind1]) * invdz; + b = (fY0[ind2] - fY0[ind1]) * invdz; + y0 = a + b * z; + a = (fScale[ind1] * fZ[ind2] - fScale[ind2] * fZ[ind1]) * invdz; + b = (fScale[ind2] - fScale[ind1]) * invdz; + scale = a + b * z; + SetCurrentVertices(x0, y0, scale); } //////////////////////////////////////////////////////////////////////////////// @@ -1119,10 +1208,10 @@ void TGeoXtru::SetCurrentZ(Double_t z, Int_t iz) void TGeoXtru::SetCurrentVertices(Double_t x0, Double_t y0, Double_t scale) { - ThreadData_t& td = GetThreadData(); - for (Int_t i=0; iSetCurrentVertices(fX0[i], fY0[i], fScale[i]); @@ -1180,8 +1273,8 @@ void TGeoXtru::SetPoints(Double_t *points) const } } else { for (j = 0; j < fNvert; j++) { - points[indx++] = td.fXc[fNvert-1-j]; - points[indx++] = td.fYc[fNvert-1-j]; + points[indx++] = td.fXc[fNvert - 1 - j]; + points[indx++] = td.fYc[fNvert - 1 - j]; points[indx++] = fZ[i]; } } @@ -1194,10 +1287,10 @@ void TGeoXtru::SetPoints(Double_t *points) const void TGeoXtru::SetPoints(Float_t *points) const { - ThreadData_t& td = GetThreadData(); + ThreadData_t &td = GetThreadData(); Int_t i, j; Int_t indx = 0; - TGeoXtru *xtru = (TGeoXtru*)this; + TGeoXtru *xtru = (TGeoXtru *)this; if (points) { for (i = 0; i < fNz; i++) { xtru->SetCurrentVertices(fX0[i], fY0[i], fScale[i]); @@ -1209,8 +1302,8 @@ void TGeoXtru::SetPoints(Float_t *points) const } } else { for (j = 0; j < fNvert; j++) { - points[indx++] = td.fXc[fNvert-1-j]; - points[indx++] = td.fYc[fNvert-1-j]; + points[indx++] = td.fXc[fNvert - 1 - j]; + points[indx++] = td.fYc[fNvert - 1 - j]; points[indx++] = fZ[i]; } } @@ -1225,9 +1318,9 @@ void TGeoXtru::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const { Int_t nz = GetNz(); Int_t nv = GetNvert(); - nvert = nz*nv; - nsegs = nv*(2*nz-1); - npols = nv*(nz-1)+2; + nvert = nz * nv; + nsegs = nv * (2 * nz - 1); + npols = nv * (nz - 1) + 2; } //////////////////////////////////////////////////////////////////////////////// @@ -1235,21 +1328,19 @@ void TGeoXtru::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const Int_t TGeoXtru::GetNmeshVertices() const { - Int_t numPoints = fNz*fNvert; + Int_t numPoints = fNz * fNvert; return numPoints; } //////////////////////////////////////////////////////////////////////////////// /// fill size of this 3-D object -void TGeoXtru::Sizeof3D() const -{ -} +void TGeoXtru::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Fills a static 3D buffer and returns a reference. -const TBuffer3D & TGeoXtru::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const +const TBuffer3D &TGeoXtru::GetBuffer3D(Int_t reqSections, Bool_t localFrame) const { static TBuffer3D buffer(TBuffer3DTypes::kGeneric); @@ -1258,10 +1349,10 @@ const TBuffer3D & TGeoXtru::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co if (reqSections & TBuffer3D::kRawSizes) { Int_t nz = GetNz(); Int_t nvert = GetNvert(); - Int_t nbPnts = nz*nvert; - Int_t nbSegs = nvert*(2*nz-1); - Int_t nbPols = nvert*(nz-1)+2; - if (buffer.SetRawSizes(nbPnts, 3*nbPnts, nbSegs, 3*nbSegs, nbPols, 6*(nbPols-2)+2*(2+nvert))) { + Int_t nbPnts = nz * nvert; + Int_t nbSegs = nvert * (2 * nz - 1); + Int_t nbPols = nvert * (nz - 1) + 2; + if (buffer.SetRawSizes(nbPnts, 3 * nbPnts, nbSegs, 3 * nbSegs, nbPols, 6 * (nbPols - 2) + 2 * (2 + nvert))) { buffer.SetSectionsValid(TBuffer3D::kRawSizes); } } @@ -1286,7 +1377,8 @@ const TBuffer3D & TGeoXtru::GetBuffer3D(Int_t reqSections, Bool_t localFrame) co void TGeoXtru::Contains_v(const Double_t *points, Bool_t *inside, Int_t vecsize) const { - for (Int_t i=0; iGetPluginManager()->FindHandler("TVirtualGeoConverter"))) { if (h->LoadPlugin() == -1) { ::Error("TVirtualGeoConverter::Instance()", - "\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - "It appears that you are missing or having outdated support for VecGeom package. " - "To enable it, configure ROOT with:\n" - " -Dvecgeom -DCMAKE_PREFIX_PATH=/lib/CMake/VecGeom" - "\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + "\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + "It appears that you are missing or having outdated support for VecGeom package. " + "To enable it, configure ROOT with:\n" + " -Dvecgeom -DCMAKE_PREFIX_PATH=/lib/CMake/VecGeom" + "\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); return 0; } - fgGeoConverter = (TVirtualGeoConverter*)h->ExecPlugin(1,mgr); + fgGeoConverter = (TVirtualGeoConverter *)h->ExecPlugin(1, mgr); } } - if (fgGeoConverter) fgGeoConverter->SetGeometry(mgr); + if (fgGeoConverter) + fgGeoConverter->SetGeometry(mgr); return fgGeoConverter; } @@ -77,5 +75,5 @@ TVirtualGeoConverter *TVirtualGeoConverter::Instance(TGeoManager *geom) void TVirtualGeoConverter::SetConverter(const TVirtualGeoConverter *converter) { - fgGeoConverter = (TVirtualGeoConverter*)converter; + fgGeoConverter = (TVirtualGeoConverter *)converter; } diff --git a/geom/geom/src/TVirtualGeoPainter.cxx b/geom/geom/src/TVirtualGeoPainter.cxx index 01c52444572d6..6e0700f6a1e77 100644 --- a/geom/geom/src/TVirtualGeoPainter.cxx +++ b/geom/geom/src/TVirtualGeoPainter.cxx @@ -20,16 +20,14 @@ Abstract class for geometry painters #include "TPluginManager.h" #include "TGeoManager.h" -TVirtualGeoPainter *TVirtualGeoPainter::fgGeoPainter = 0; +TVirtualGeoPainter *TVirtualGeoPainter::fgGeoPainter = 0; ClassImp(TVirtualGeoPainter); //////////////////////////////////////////////////////////////////////////////// /// Geometry painter default constructor -TVirtualGeoPainter::TVirtualGeoPainter(TGeoManager *) -{ -} +TVirtualGeoPainter::TVirtualGeoPainter(TGeoManager *) {} //////////////////////////////////////////////////////////////////////////////// /// Geometry painter default destructor @@ -39,7 +37,6 @@ TVirtualGeoPainter::~TVirtualGeoPainter() fgGeoPainter = 0; } - //////////////////////////////////////////////////////////////////////////////// /// Static function returning a pointer to the geometry painter. /// The painter will paint objects from the specified geometry. @@ -53,7 +50,7 @@ TVirtualGeoPainter *TVirtualGeoPainter::GeoPainter() if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualGeoPainter"))) { if (h->LoadPlugin() == -1) return 0; - fgGeoPainter = (TVirtualGeoPainter*)h->ExecPlugin(1,gGeoManager); + fgGeoPainter = (TVirtualGeoPainter *)h->ExecPlugin(1, gGeoManager); } } return fgGeoPainter; @@ -64,5 +61,5 @@ TVirtualGeoPainter *TVirtualGeoPainter::GeoPainter() void TVirtualGeoPainter::SetPainter(const TVirtualGeoPainter *painter) { - fgGeoPainter = (TVirtualGeoPainter*)painter; + fgGeoPainter = (TVirtualGeoPainter *)painter; } diff --git a/geom/geom/src/TVirtualGeoTrack.cxx b/geom/geom/src/TVirtualGeoTrack.cxx index 4b5a0682d9642..7830865ce5503 100644 --- a/geom/geom/src/TVirtualGeoTrack.cxx +++ b/geom/geom/src/TVirtualGeoTrack.cxx @@ -32,11 +32,11 @@ ClassImp(TVirtualGeoTrack); TVirtualGeoTrack::TVirtualGeoTrack() { - fPDG = 0; - fId = -1; - fParent = 0; - fParticle = 0; - fTracks = 0; + fPDG = 0; + fId = -1; + fParent = 0; + fParticle = 0; + fTracks = 0; } //////////////////////////////////////////////////////////////////////////////// @@ -45,11 +45,11 @@ TVirtualGeoTrack::TVirtualGeoTrack() TVirtualGeoTrack::TVirtualGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent, TObject *particle) { - fPDG = pdgcode; - fId = id; - fParent = parent; - fParticle = particle; - fTracks = 0; + fPDG = pdgcode; + fId = id; + fParent = parent; + fParticle = particle; + fTracks = 0; } //////////////////////////////////////////////////////////////////////////////// @@ -82,19 +82,22 @@ Int_t TVirtualGeoTrack::GetDaughterId(Int_t index) const TVirtualGeoTrack *TVirtualGeoTrack::FindTrackWithId(Int_t id) const { - TVirtualGeoTrack* trk=0; - if (GetId()==id) { - trk = (TVirtualGeoTrack*)this; + TVirtualGeoTrack *trk = 0; + if (GetId() == id) { + trk = (TVirtualGeoTrack *)this; return trk; } - TVirtualGeoTrack* kid=0; + TVirtualGeoTrack *kid = 0; Int_t nd = GetNdaughters(); - for (Int_t i=0; iFindTrackWithId(id); - if (trk!=0) break; + if (trk != 0) + break; } } return trk; @@ -114,13 +117,17 @@ const char *TVirtualGeoTrack::GetName() const Bool_t TVirtualGeoTrack::IsInTimeRange() const { Double_t tmin, tmax; - Bool_t timecut = gGeoManager->GetTminTmax(tmin,tmax); - if (!timecut) return kTRUE; + Bool_t timecut = gGeoManager->GetTminTmax(tmin, tmax); + if (!timecut) + return kTRUE; const Double_t *point = GetFirstPoint(); - if (!point) return kFALSE; - if (point[3]>tmax) return kFALSE; + if (!point) + return kFALSE; + if (point[3] > tmax) + return kFALSE; point = GetLastPoint(); - if (point[3]AddFrame(new TGLabel(f1, "DX"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxDx = new TGNumberEntry(f1, 0., 5, kBOX_X); fBoxDx->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fBoxDx->GetNumberEntry(); + nef = (TGTextEntry *)fBoxDx->GetNumberEntry(); nef->SetToolTipText("Enter the box half-length in X"); fBoxDx->Associate(this); - f1->AddFrame(fBoxDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fBoxDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dy - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxDy = new TGNumberEntry(f2, 0., 5, kBOX_Y); fBoxDy->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fBoxDy->GetNumberEntry(); + nef = (TGTextEntry *)fBoxDy->GetNumberEntry(); nef->SetToolTipText("Enter the box half-length in Y"); fBoxDy->Associate(this); - f2->AddFrame(fBoxDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f2->AddFrame(fBoxDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dx - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxDz = new TGNumberEntry(f3, 0., 5, kBOX_Z); fBoxDz->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fBoxDz->GetNumberEntry(); + nef = (TGTextEntry *)fBoxDz->GetNumberEntry(); nef->SetToolTipText("Enter the box half-length in Z"); fBoxDz->Associate(this); - f3->AddFrame(fBoxDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f3->AddFrame(fBoxDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); MakeTitle("Box origin"); compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for dx - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "OX"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxOx = new TGNumberEntry(f1, 0., 5, kBOX_OX); - nef = (TGTextEntry*)fBoxOx->GetNumberEntry(); + nef = (TGTextEntry *)fBoxOx->GetNumberEntry(); nef->SetToolTipText("Enter the box origin X coordinate"); fBoxOx->Associate(this); - f1->AddFrame(fBoxOx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fBoxOx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dy - f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "OY"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxOy = new TGNumberEntry(f2, 0., 5, kBOX_OY); - nef = (TGTextEntry*)fBoxOy->GetNumberEntry(); + nef = (TGTextEntry *)fBoxOy->GetNumberEntry(); nef->SetToolTipText("Enter the box origin Y coordinate"); fBoxOy->Associate(this); - f2->AddFrame(fBoxOy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f2->AddFrame(fBoxOy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dx - f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "OZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fBoxOz = new TGNumberEntry(f3, 0., 5, kBOX_OZ); - nef = (TGTextEntry*)fBoxOz->GetNumberEntry(); + nef = (TGTextEntry *)fBoxOz->GetNumberEntry(); nef->SetToolTipText("Enter the box origin Z coordinate"); fBoxOz->Associate(this); - f3->AddFrame(fBoxOz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f3->AddFrame(fBoxOz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -154,9 +146,9 @@ TGeoBBoxEditor::TGeoBBoxEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -169,7 +161,7 @@ TGeoBBoxEditor::~TGeoBBoxEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -197,23 +189,23 @@ void TGeoBBoxEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Update editor for a new selected box. -void TGeoBBoxEditor::SetModel(TObject* obj) +void TGeoBBoxEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoBBox::Class())) { + if (obj == 0 || (obj->IsA() != TGeoBBox::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoBBox*)obj; + fShape = (TGeoBBox *)obj; fDxi = fShape->GetDX(); fDyi = fShape->GetDY(); fDzi = fShape->GetDZ(); - memcpy(fOrigi, fShape->GetOrigin(), 3*sizeof(Double_t)); + memcpy(fOrigi, fShape->GetOrigin(), 3 * sizeof(Double_t)); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -227,7 +219,8 @@ void TGeoBBoxEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -240,7 +233,7 @@ Bool_t TGeoBBoxEditor::IsDelayed() const } //////////////////////////////////////////////////////////////////////////////// -///Slot for name. +/// Slot for name. void TGeoBBoxEditor::DoName() { @@ -248,12 +241,13 @@ void TGeoBBoxEditor::DoName() } //////////////////////////////////////////////////////////////////////////////// -///Slot for applying current parameters. +/// Slot for applying current parameters. void TGeoBBoxEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t dx = fBoxDx->GetNumber(); Double_t dy = fBoxDy->GetNumber(); Double_t dz = fBoxDz->GetNumber(); @@ -272,16 +266,17 @@ void TGeoBBoxEditor::DoApply() fPad->GetView()->ShowAxis(); } else { const Double_t *origin = fShape->GetOrigin(); - view->SetRange(origin[0]-fShape->GetDX(), origin[1]-fShape->GetDY(), origin[2]-fShape->GetDZ(), - origin[0]+fShape->GetDX(), origin[1]+fShape->GetDY(), origin[2]+fShape->GetDZ()); + view->SetRange(origin[0] - fShape->GetDX(), origin[1] - fShape->GetDY(), origin[2] - fShape->GetDZ(), + origin[0] + fShape->GetDX(), origin[1] + fShape->GetDY(), origin[2] + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } //////////////////////////////////////////////////////////////////////////////// -///Slot for modifying current parameters. +/// Slot for modifying current parameters. void TGeoBBoxEditor::DoModified() { @@ -305,72 +300,76 @@ void TGeoBBoxEditor::DoUndo() } //////////////////////////////////////////////////////////////////////////////// -///Slot for Dx modification. +/// Slot for Dx modification. void TGeoBBoxEditor::DoDx() { Double_t dx = fBoxDx->GetNumber(); - if (dx<=0) { - dx=0.1; + if (dx <= 0) { + dx = 0.1; fBoxDx->SetNumber(dx); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Dy modification. +/// Slot for Dy modification. void TGeoBBoxEditor::DoDy() { Double_t dy = fBoxDy->GetNumber(); - if (dy<=0) { - dy=0.1; + if (dy <= 0) { + dy = 0.1; fBoxDy->SetNumber(dy); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Dz modification. +/// Slot for Dz modification. void TGeoBBoxEditor::DoDz() { Double_t dz = fBoxDz->GetNumber(); - if (dz<=0) { - dz=0.1; + if (dz <= 0) { + dz = 0.1; fBoxDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Ox modification. +/// Slot for Ox modification. void TGeoBBoxEditor::DoOx() { DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Oy modification. +/// Slot for Oy modification. void TGeoBBoxEditor::DoOy() { DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Oz modification. +/// Slot for Oz modification. void TGeoBBoxEditor::DoOz() { DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - - diff --git a/geom/geombuilder/src/TGeoConeEditor.cxx b/geom/geombuilder/src/TGeoConeEditor.cxx index f8d0fb57e88d3..3f55272c3c07b 100644 --- a/geom/geombuilder/src/TGeoConeEditor.cxx +++ b/geom/geombuilder/src/TGeoConeEditor.cxx @@ -20,7 +20,6 @@ Editor for a TGeoCone. */ - #include "TGeoConeEditor.h" #include "TGeoTabManager.h" #include "TGeoCone.h" @@ -36,19 +35,15 @@ Editor for a TGeoCone. ClassImp(TGeoConeEditor); -enum ETGeoConeWid { - kCONE_NAME, kCONE_RMIN1, kCONE_RMIN2, kCONE_RMAX1, kCONE_RMAX2, kCONE_Z, - kCONE_APPLY, kCONE_UNDO -}; +enum ETGeoConeWid { kCONE_NAME, kCONE_RMIN1, kCONE_RMIN2, kCONE_RMAX1, kCONE_RMAX2, kCONE_Z, kCONE_APPLY, kCONE_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for volume editor -TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fRmini1 = fRmaxi1 = fRmini2 = fRmaxi2 = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -71,19 +66,19 @@ TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Rmin1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmin1 = new TGNumberEntry(f1, 0., 5, kCONE_RMIN1); fERmin1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmin1->GetNumberEntry(); + nef = (TGTextEntry *)fERmin1->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius"); fERmin1->Associate(this); fERmin1->Resize(100, fERmin1->GetDefaultHeight()); f1->AddFrame(fERmin1, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); - // Number entry for Rmax1 + // Number entry for Rmax1 f1 = new TGCompositeFrame(compxyz, 155, 30, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "Rmax1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmax1 = new TGNumberEntry(f1, 0., 5, kCONE_RMAX1); fERmax1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmax1->GetNumberEntry(); + nef = (TGTextEntry *)fERmax1->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius"); fERmax1->Associate(this); fERmax1->Resize(100, fERmax1->GetDefaultHeight()); @@ -95,7 +90,7 @@ TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Rmin2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmin2 = new TGNumberEntry(f1, 0., 5, kCONE_RMIN2); fERmin2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmin2->GetNumberEntry(); + nef = (TGTextEntry *)fERmin2->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius"); fERmin2->Associate(this); fERmin2->Resize(100, fERmin2->GetDefaultHeight()); @@ -107,7 +102,7 @@ TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Rmax2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmax2 = new TGNumberEntry(f1, 0., 5, kCONE_RMAX2); fERmax2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmax1->GetNumberEntry(); + nef = (TGTextEntry *)fERmax1->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius"); fERmax2->Associate(this); fERmax2->Resize(100, fERmax2->GetDefaultHeight()); @@ -119,21 +114,21 @@ TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDz = new TGNumberEntry(f1, 0., 5, kCONE_Z); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the cone half-lenth in Z"); fEDz->Associate(this); fEDz->Resize(100, fEDz->GetDefaultHeight()); f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Delayed draw fDFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(fDFrame, "Delayed draw"); - fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 2, 2)); - AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); + AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons fBFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -141,9 +136,9 @@ TGeoConeEditor::TGeoConeEditor(const TGWindow *p, Int_t width, fBFrame->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(fBFrame, "Undo"); - fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -156,7 +151,7 @@ TGeoConeEditor::~TGeoConeEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -182,17 +177,16 @@ void TGeoConeEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoConeEditor::SetModel(TObject* obj) +void TGeoConeEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoCone::Class())) { + if (obj == 0 || (obj->IsA() != TGeoCone::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoCone*)obj; + fShape = (TGeoCone *)obj; fRmini1 = fShape->GetRmin1(); fRmini2 = fShape->GetRmin2(); fRmaxi1 = fShape->GetRmax1(); @@ -208,7 +202,8 @@ void TGeoConeEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -229,22 +224,27 @@ void TGeoConeEditor::DoName() } //////////////////////////////////////////////////////////////////////////////// -///Slot for applying current parameters. +/// Slot for applying current parameters. void TGeoConeEditor::DoApply() { fApply->SetEnabled(kFALSE); const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin1 = fERmin1->GetNumber(); Double_t rmin2 = fERmin2->GetNumber(); Double_t rmax1 = fERmax1->GetNumber(); Double_t rmax2 = fERmax2->GetNumber(); Double_t dz = fEDz->GetNumber(); - if (rmin1<0 || rmin1>rmax1) return; - if (rmin2<0 || rmin2>rmax2) return; - if (dz<=0) return; - if (rmin1==rmax1 && rmin2==rmax2) return; + if (rmin1 < 0 || rmin1 > rmax1) + return; + if (rmin2 < 0 || rmin2 > rmax2) + return; + if (dz <= 0) + return; + if (rmin1 == rmax1 && rmin2 == rmax2) + return; fShape->SetConeDimensions(dz, rmin1, rmax1, rmin2, rmax2); fShape->ComputeBBox(); fUndo->SetEnabled(); @@ -252,12 +252,13 @@ void TGeoConeEditor::DoApply() if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } //////////////////////////////////////////////////////////////////////////////// -///Slot for modifying current parameters. +/// Slot for modifying current parameters. void TGeoConeEditor::DoModified() { @@ -286,16 +287,17 @@ void TGeoConeEditor::DoRmin1() { Double_t rmin1 = fERmin1->GetNumber(); Double_t rmax1 = fERmax1->GetNumber(); - if (rmin1<0) { + if (rmin1 < 0) { rmin1 = 0; fERmin1->SetNumber(rmin1); } - if (rmin1>rmax1) { + if (rmin1 > rmax1) { rmin1 = rmax1; fERmin1->SetNumber(rmin1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -305,12 +307,13 @@ void TGeoConeEditor::DoRmax1() { Double_t rmin1 = fERmin1->GetNumber(); Double_t rmax1 = fERmax1->GetNumber(); - if (rmax1SetNumber(rmax1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -320,16 +323,17 @@ void TGeoConeEditor::DoRmin2() { Double_t rmin2 = fERmin2->GetNumber(); Double_t rmax2 = fERmax2->GetNumber(); - if (rmin2<0) { + if (rmin2 < 0) { rmin2 = 0; fERmin2->SetNumber(rmin2); } - if (rmin2>rmax2) { + if (rmin2 > rmax2) { rmin2 = rmax2; fERmin2->SetNumber(rmin2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -339,12 +343,13 @@ void TGeoConeEditor::DoRmax2() { Double_t rmin2 = fERmin2->GetNumber(); Double_t rmax2 = fERmax2->GetNumber(); - if (rmax2SetNumber(rmax2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -353,12 +358,13 @@ void TGeoConeEditor::DoRmax2() void TGeoConeEditor::DoDz() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } /** \class TGeoConeSegEditor @@ -374,24 +380,22 @@ Editor for a cone segment. ClassImp(TGeoConeSegEditor); -enum ETGeoConeSegWid { - kCONESEG_PHI1, kCONESEG_PHI2, kCONESEG_PHI -}; +enum ETGeoConeSegWid { kCONESEG_PHI1, kCONESEG_PHI2, kCONESEG_PHI }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for cone segment editor -TGeoConeSegEditor::TGeoConeSegEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) - : TGeoConeEditor(p, width, height, options | kVerticalFrame, back) +TGeoConeSegEditor::TGeoConeSegEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGeoConeEditor(p, width, height, options | kVerticalFrame, back) { fLock = kFALSE; MakeTitle("Phi range"); TGTextEntry *nef; - TGCompositeFrame *compxyz = new TGCompositeFrame(this, 155, 110, kHorizontalFrame | kFixedWidth | kFixedHeight | kRaisedFrame); + TGCompositeFrame *compxyz = + new TGCompositeFrame(this, 155, 110, kHorizontalFrame | kFixedWidth | kFixedHeight | kRaisedFrame); // Vertical slider - fSPhi = new TGDoubleVSlider(compxyz,100); - fSPhi->SetRange(0.,720.); + fSPhi = new TGDoubleVSlider(compxyz, 100); + fSPhi->SetRange(0., 720.); fSPhi->Resize(fSPhi->GetDefaultWidth(), 100); compxyz->AddFrame(fSPhi, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 135, 100, kVerticalFrame | kFixedHeight); @@ -399,7 +403,7 @@ TGeoConeSegEditor::TGeoConeSegEditor(const TGWindow *p, Int_t width, fEPhi1 = new TGNumberEntry(f1, 0., 5, kCONESEG_PHI1); fEPhi1->Resize(100, fEPhi1->GetDefaultHeight()); fEPhi1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi1->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi1->GetNumberEntry(); nef->SetToolTipText("Enter the phi1 value"); fEPhi1->Associate(this); f1->AddFrame(fEPhi1, new TGLayoutHints(kLHintsTop | kLHintsRight, 2, 2, 2, 2)); @@ -407,14 +411,14 @@ TGeoConeSegEditor::TGeoConeSegEditor(const TGWindow *p, Int_t width, fEPhi2 = new TGNumberEntry(f1, 0., 5, kCONESEG_PHI2); fEPhi2->Resize(100, fEPhi2->GetDefaultHeight()); fEPhi2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi2->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi2->GetNumberEntry(); nef->SetToolTipText("Enter the phi2 value"); fEPhi2->Associate(this); f1->AddFrame(fEPhi2, new TGLayoutHints(kLHintsBottom | kLHintsRight, 2, 2, 2, 2)); f1->AddFrame(new TGLabel(f1, "Phi max."), new TGLayoutHints(kLHintsBottom, 0, 0, 6, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); -// compxyz->Resize(150,150); + // compxyz->Resize(150,150); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); TGeoTabManager::MoveFrame(fDFrame, this); TGeoTabManager::MoveFrame(fBFrame, this); @@ -429,7 +433,7 @@ TGeoConeSegEditor::~TGeoConeSegEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -440,39 +444,39 @@ TGeoConeSegEditor::~TGeoConeSegEditor() void TGeoConeSegEditor::ConnectSignals2Slots() { TGeoConeEditor::ConnectSignals2Slots(); - Disconnect(fApply, "Clicked()",(TGeoConeEditor*)this, "DoApply()"); - Disconnect(fUndo, "Clicked()",(TGeoConeEditor*)this, "DoUndo()"); + Disconnect(fApply, "Clicked()", (TGeoConeEditor *)this, "DoApply()"); + Disconnect(fUndo, "Clicked()", (TGeoConeEditor *)this, "DoUndo()"); fApply->Connect("Clicked()", "TGeoConeSegEditor", this, "DoApply()"); fUndo->Connect("Clicked()", "TGeoConeSegEditor", this, "DoUndo()"); fEPhi1->Connect("ValueSet(Long_t)", "TGeoConeSegEditor", this, "DoPhi1()"); fEPhi2->Connect("ValueSet(Long_t)", "TGeoConeSegEditor", this, "DoPhi2()"); -// fEPhi1->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoConeSegEditor", this, "DoPhi1()"); -// fEPhi2->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoConeSegEditor", this, "DoPhi2()"); - fSPhi->Connect("PositionChanged()","TGeoConeSegEditor", this, "DoPhi()"); + // fEPhi1->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoConeSegEditor", this, "DoPhi1()"); + // fEPhi2->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoConeSegEditor", this, "DoPhi2()"); + fSPhi->Connect("PositionChanged()", "TGeoConeSegEditor", this, "DoPhi()"); } //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoConeSegEditor::SetModel(TObject* obj) +void TGeoConeSegEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoConeSeg::Class())) { + if (obj == 0 || (obj->IsA() != TGeoConeSeg::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoCone*)obj; + fShape = (TGeoCone *)obj; fRmini1 = fShape->GetRmin1(); fRmaxi1 = fShape->GetRmax1(); fRmini2 = fShape->GetRmin2(); fRmaxi2 = fShape->GetRmax2(); fDzi = fShape->GetDz(); fNamei = fShape->GetName(); - fPmini = ((TGeoConeSeg*)fShape)->GetPhi1(); - fPmaxi = ((TGeoConeSeg*)fShape)->GetPhi2(); + fPmini = ((TGeoConeSeg *)fShape)->GetPhi1(); + fPmaxi = ((TGeoConeSeg *)fShape)->GetPhi2(); fShapeName->SetText(fShape->GetName()); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); fERmin1->SetNumber(fRmini1); fERmax1->SetNumber(fRmaxi1); fERmin2->SetNumber(fRmini2); @@ -481,31 +485,34 @@ void TGeoConeSegEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } //////////////////////////////////////////////////////////////////////////////// -///Slot for Phi1 +/// Slot for Phi1 void TGeoConeSegEditor::DoPhi1() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi1 > 360-1.e-10) { + if (phi1 > 360 - 1.e-10) { phi1 = 0.; fEPhi1->SetNumber(phi1); } - if (phi2SetNumber(phi1); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -515,20 +522,22 @@ void TGeoConeSegEditor::DoPhi2() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi2-phi1 > 360.) { + if (phi2 - phi1 > 360.) { phi2 -= 360.; fEPhi2->SetNumber(phi2); } - if (phi2SetNumber(phi2); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -542,8 +551,10 @@ void TGeoConeSegEditor::DoPhi() fEPhi1->SetNumber(fSPhi->GetMinPosition()); fLock = kTRUE; fEPhi2->SetNumber(fSPhi->GetMaxPosition()); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -553,33 +564,37 @@ void TGeoConeSegEditor::DoApply() { fApply->SetEnabled(kFALSE); const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin1 = fERmin1->GetNumber(); Double_t rmax1 = fERmax1->GetNumber(); - if (rmin1<0 || rmax1GetNumber(); Double_t rmax2 = fERmax2->GetNumber(); - if (rmin2<0 || rmax2GetNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if ((phi2-phi1) > 360.001) { + if ((phi2 - phi1) > 360.001) { phi1 = 0.; phi2 = 360.; fEPhi1->SetNumber(phi1); fEPhi2->SetNumber(phi2); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); + fSPhi->SetPosition(phi1, phi2); fLock = kFALSE; } - ((TGeoConeSeg*)fShape)->SetConsDimensions(dz, rmin1, rmax1, rmin2,rmax2, phi1, phi2); + ((TGeoConeSeg *)fShape)->SetConsDimensions(dz, rmin1, rmax1, rmin2, rmax2, phi1, phi2); fShape->ComputeBBox(); fUndo->SetEnabled(); if (fPad) { if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -595,12 +610,8 @@ void TGeoConeSegEditor::DoUndo() fEDz->SetNumber(fDzi); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); DoApply(); fUndo->SetEnabled(kFALSE); fApply->SetEnabled(kFALSE); } - - - - diff --git a/geom/geombuilder/src/TGeoEltuEditor.cxx b/geom/geombuilder/src/TGeoEltuEditor.cxx index 7d959d30d5321..10703d7662782 100644 --- a/geom/geombuilder/src/TGeoEltuEditor.cxx +++ b/geom/geombuilder/src/TGeoEltuEditor.cxx @@ -34,19 +34,15 @@ Editor for a TGeoEltu. ClassImp(TGeoEltuEditor); -enum ETGeoEltuWid { - kELTU_NAME, kELTU_A, kELTU_B, kELTU_DZ, - kELTU_APPLY, kELTU_UNDO -}; +enum ETGeoEltuWid { kELTU_NAME, kELTU_A, kELTU_B, kELTU_DZ, kELTU_APPLY, kELTU_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for para editor -TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fAi = fBi = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -68,7 +64,7 @@ TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, fEA = new TGNumberEntry(f1, 0., 5, kELTU_A); fEA->SetNumAttr(TGNumberFormat::kNEAPositive); fEA->Resize(100, fEA->GetDefaultHeight()); - nef = (TGTextEntry*)fEA->GetNumberEntry(); + nef = (TGTextEntry *)fEA->GetNumberEntry(); nef->SetToolTipText("Enter the semi-axis of the ellipse along x"); fEA->Associate(this); f1->AddFrame(fEA, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -80,7 +76,7 @@ TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, fEB = new TGNumberEntry(f1, 0., 5, kELTU_B); fEB->SetNumAttr(TGNumberFormat::kNEAPositive); fEB->Resize(100, fEB->GetDefaultHeight()); - nef = (TGTextEntry*)fEB->GetNumberEntry(); + nef = (TGTextEntry *)fEB->GetNumberEntry(); nef->SetToolTipText("Enter the semi-axis of the ellipse along y"); fEB->Associate(this); f1->AddFrame(fEB, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -92,7 +88,7 @@ TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, fEDz = new TGNumberEntry(f1, 0., 5, kELTU_DZ); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); fEDz->Resize(100, fEDz->GetDefaultHeight()); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Z"); fEDz->Associate(this); f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -101,8 +97,8 @@ TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -110,9 +106,9 @@ TGeoEltuEditor::TGeoEltuEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -125,7 +121,7 @@ TGeoEltuEditor::~TGeoEltuEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -150,18 +146,19 @@ void TGeoEltuEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoEltuEditor::SetModel(TObject* obj) +void TGeoEltuEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoEltu::Class())) { + if (obj == 0 || (obj->IsA() != TGeoEltu::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoEltu*)obj; + fShape = (TGeoEltu *)obj; fAi = fShape->GetA(); fBi = fShape->GetB(); fDzi = fShape->GetDz(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -172,7 +169,8 @@ void TGeoEltuEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -198,7 +196,8 @@ Bool_t TGeoEltuEditor::IsDelayed() const void TGeoEltuEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t a = fEA->GetNumber(); Double_t b = fEB->GetNumber(); Double_t z = fEDz->GetNumber(); @@ -217,11 +216,12 @@ void TGeoEltuEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -257,7 +257,8 @@ void TGeoEltuEditor::DoA() fEA->SetNumber(a); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -271,7 +272,8 @@ void TGeoEltuEditor::DoB() fEB->SetNumber(b); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -285,6 +287,6 @@ void TGeoEltuEditor::DoDz() fEDz->SetNumber(z); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - diff --git a/geom/geombuilder/src/TGeoGedFrame.cxx b/geom/geombuilder/src/TGeoGedFrame.cxx index 9b0145d6c7bc2..2d6b0468da831 100644 --- a/geom/geombuilder/src/TGeoGedFrame.cxx +++ b/geom/geombuilder/src/TGeoGedFrame.cxx @@ -19,10 +19,8 @@ ClassImp(TGeoGedFrame); //////////////////////////////////////////////////////////////////////////////// /// Constructor. -TGeoGedFrame::TGeoGedFrame(const TGWindow *p, Int_t width, Int_t height, - UInt_t options, Pixel_t back) : - TGedFrame(p, width, height, options, back), - fTab(0), fTabMgr(0), fPad(0) +TGeoGedFrame::TGeoGedFrame(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGedFrame(p, width, height, options, back), fTab(0), fTabMgr(0), fPad(0) { fTab = fGedEditor->GetTab(); fPad = fGedEditor->GetPad(); @@ -35,12 +33,12 @@ TGeoGedFrame::TGeoGedFrame(const TGWindow *p, Int_t width, Int_t height, void TGeoGedFrame::SetActive(Bool_t active) { if (active) - ((TGCompositeFrame*)GetParent())->ShowFrame(this); + ((TGCompositeFrame *)GetParent())->ShowFrame(this); else - ((TGCompositeFrame*)GetParent())->HideFrame(this); + ((TGCompositeFrame *)GetParent())->HideFrame(this); -// no need to call for every single editor Layout of TGMainFrame -// ((TGMainFrame*)GetMainFrame())->Layout(); + // no need to call for every single editor Layout of TGMainFrame + // ((TGMainFrame*)GetMainFrame())->Layout(); // to avoid that the user changes options on a deactivated Tab if (fTab->IsEnabled(fTab->GetCurrent())) diff --git a/geom/geombuilder/src/TGeoHypeEditor.cxx b/geom/geombuilder/src/TGeoHypeEditor.cxx index 960a6ece47ac6..3265e337fbc82 100644 --- a/geom/geombuilder/src/TGeoHypeEditor.cxx +++ b/geom/geombuilder/src/TGeoHypeEditor.cxx @@ -35,19 +35,15 @@ Editor for a TGeoHype. ClassImp(TGeoHypeEditor); -enum ETGeoHypeWid { - kHYPE_NAME, kHYPE_RIN, kHYPE_ROUT, kHYPE_DZ, kHYPE_STIN, - kHYPE_STOUT, kHYPE_APPLY, kHYPE_UNDO -}; +enum ETGeoHypeWid { kHYPE_NAME, kHYPE_RIN, kHYPE_ROUT, kHYPE_DZ, kHYPE_STIN, kHYPE_STOUT, kHYPE_APPLY, kHYPE_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for Hype editor -TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fRini = fRouti = fStIni = fStOuti = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -69,7 +65,7 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, fERin = new TGNumberEntry(f1, 0., 5, kHYPE_RIN); fERin->SetNumAttr(TGNumberFormat::kNEAPositive); fERin->Resize(100, fERin->GetDefaultHeight()); - nef = (TGTextEntry*)fERin->GetNumberEntry(); + nef = (TGTextEntry *)fERin->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius "); fERin->Associate(this); f1->AddFrame(fERin, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -81,7 +77,7 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, fERout = new TGNumberEntry(f1, 0., 5, kHYPE_ROUT); fERout->SetNumAttr(TGNumberFormat::kNEAPositive); fERout->Resize(100, fERout->GetDefaultHeight()); - nef = (TGTextEntry*)fERout->GetNumberEntry(); + nef = (TGTextEntry *)fERout->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius"); fERout->Associate(this); f1->AddFrame(fERout, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -93,7 +89,7 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, fEDz = new TGNumberEntry(f1, 0., 5, kHYPE_DZ); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); fEDz->Resize(100, fEDz->GetDefaultHeight()); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Dz"); fEDz->Associate(this); f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -104,7 +100,7 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "StIn"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEStIn = new TGNumberEntry(f1, 0., 5, kHYPE_STIN); fEStIn->Resize(100, fEStIn->GetDefaultHeight()); - nef = (TGTextEntry*)fEStIn->GetNumberEntry(); + nef = (TGTextEntry *)fEStIn->GetNumberEntry(); nef->SetToolTipText("Enter the stereo angle for inner surface"); fEStIn->Associate(this); f1->AddFrame(fEStIn, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -116,7 +112,7 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, fEStOut = new TGNumberEntry(f1, 0., 5, kHYPE_STOUT); fEStOut->SetNumAttr(TGNumberFormat::kNEAPositive); fEStOut->Resize(100, fEStOut->GetDefaultHeight()); - nef = (TGTextEntry*)fEStOut->GetNumberEntry(); + nef = (TGTextEntry *)fEStOut->GetNumberEntry(); nef->SetToolTipText("Enter the stereo angle for outer surface"); fEStOut->Associate(this); f1->AddFrame(fEStOut, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -125,8 +121,8 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -134,9 +130,9 @@ TGeoHypeEditor::TGeoHypeEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -149,7 +145,7 @@ TGeoHypeEditor::~TGeoHypeEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -175,24 +171,24 @@ void TGeoHypeEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoHypeEditor::SetModel(TObject* obj) +void TGeoHypeEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoHype::Class())) { + if (obj == 0 || (obj->IsA() != TGeoHype::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoHype*)obj; + fShape = (TGeoHype *)obj; fRini = fShape->GetRmin(); fRouti = fShape->GetRmax(); fDzi = fShape->GetDz(); fStIni = fShape->GetStIn(); fStOuti = fShape->GetStOut(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -205,7 +201,8 @@ void TGeoHypeEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -231,16 +228,17 @@ void TGeoHypeEditor::DoName() void TGeoHypeEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rin = fERin->GetNumber(); Double_t rout = fERout->GetNumber(); Double_t dz = fEDz->GetNumber(); Double_t stin = fEStIn->GetNumber(); Double_t stout = fEStOut->GetNumber(); - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - if ((dz<=0) || (rin<0) || (rin>rout) || - (rin*rin+tin*tin*dz*dz > rout*rout+tout*tout*dz*dz)) { + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + if ((dz <= 0) || (rin < 0) || (rin > rout) || + (rin * rin + tin * tin * dz * dz > rout * rout + tout * tout * dz * dz)) { fUndo->SetEnabled(); fApply->SetEnabled(kFALSE); return; @@ -262,11 +260,12 @@ void TGeoHypeEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -303,20 +302,21 @@ void TGeoHypeEditor::DoRin() Double_t dz = fEDz->GetNumber(); Double_t stin = fEStIn->GetNumber(); Double_t stout = fEStOut->GetNumber(); - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - if (rin<0) { + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + if (rin < 0) { rin = 0; fERin->SetNumber(rin); } - Double_t rinmax = TMath::Sqrt((rout*rout+tout*tout*dz*dz)/(tin*tin*dz*dz)); + Double_t rinmax = TMath::Sqrt((rout * rout + tout * tout * dz * dz) / (tin * tin * dz * dz)); rinmax = TMath::Min(rinmax, rout); if (rin > rinmax) { - rin = rinmax-1.e-6; + rin = rinmax - 1.e-6; fERin->SetNumber(rin); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -329,16 +329,17 @@ void TGeoHypeEditor::DoRout() Double_t dz = fEDz->GetNumber(); Double_t stin = fEStIn->GetNumber(); Double_t stout = fEStOut->GetNumber(); - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - Double_t routmin = TMath::Sqrt((rin*rin+tin*tin*dz*dz)/(tout*tout*dz*dz)); - routmin = TMath::Max(routmin,rin); + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + Double_t routmin = TMath::Sqrt((rin * rin + tin * tin * dz * dz) / (tout * tout * dz * dz)); + routmin = TMath::Max(routmin, rin); if (rout < routmin) { - rout = routmin+1.e-6; + rout = routmin + 1.e-6; fERout->SetNumber(rout); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -351,23 +352,24 @@ void TGeoHypeEditor::DoDz() Double_t dz = fEDz->GetNumber(); Double_t stin = fEStIn->GetNumber(); Double_t stout = fEStOut->GetNumber(); - if (TMath::Abs(stin-stout)<1.e-6) { - stin = stout+1.; + if (TMath::Abs(stin - stout) < 1.e-6) { + stin = stout + 1.; fEStIn->SetNumber(stin); } - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - if (dz<=0) { + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } - Double_t dzmax = TMath::Sqrt((rout*rout-rin*rin)/(tin*tin-tout*tout)); - if (dz>dzmax) { + Double_t dzmax = TMath::Sqrt((rout * rout - rin * rin) / (tin * tin - tout * tout)); + if (dz > dzmax) { dz = dzmax; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -384,16 +386,17 @@ void TGeoHypeEditor::DoStIn() stin = 89.; fEStIn->SetNumber(stin); } - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - Double_t tinmax = TMath::Sqrt(tout*tout+(rout*rout-rin*rin)/(dz*dz)); - if (tin>tinmax) { - tin = tinmax-1.e-6; - stin = TMath::RadToDeg()*TMath::ATan(tin); + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + Double_t tinmax = TMath::Sqrt(tout * tout + (rout * rout - rin * rin) / (dz * dz)); + if (tin > tinmax) { + tin = tinmax - 1.e-6; + stin = TMath::RadToDeg() * TMath::ATan(tin); fEStIn->SetNumber(stin); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -410,20 +413,21 @@ void TGeoHypeEditor::DoStOut() stout = 89; fEStOut->SetNumber(stout); } - Double_t tin = TMath::Tan(stin*TMath::DegToRad()); - Double_t tout = TMath::Tan(stout*TMath::DegToRad()); - Double_t tinmin = TMath::Sqrt((rout*rout-rin*rin)/(dz*dz)); + Double_t tin = TMath::Tan(stin * TMath::DegToRad()); + Double_t tout = TMath::Tan(stout * TMath::DegToRad()); + Double_t tinmin = TMath::Sqrt((rout * rout - rin * rin) / (dz * dz)); if (tin < tinmin) { tin = tinmin; - stin = TMath::RadToDeg()*TMath::ATan(tin); + stin = TMath::RadToDeg() * TMath::ATan(tin); fEStIn->SetNumber(stin); } - Double_t toutmin = TMath::Sqrt(tin*tin -tinmin*tinmin); + Double_t toutmin = TMath::Sqrt(tin * tin - tinmin * tinmin); if (tout < toutmin) { - tout = toutmin+1.e-6; - stout = TMath::RadToDeg()*TMath::ATan(tout); + tout = toutmin + 1.e-6; + stout = TMath::RadToDeg() * TMath::ATan(tout); fEStOut->SetNumber(stout); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } diff --git a/geom/geombuilder/src/TGeoManagerEditor.cxx b/geom/geombuilder/src/TGeoManagerEditor.cxx index 7e6b751e4a307..91d0d2777d22d 100644 --- a/geom/geombuilder/src/TGeoManagerEditor.cxx +++ b/geom/geombuilder/src/TGeoManagerEditor.cxx @@ -86,34 +86,80 @@ following categories: ClassImp(TGeoManagerEditor); enum ETGeoVolumeWid { - kMANAGER_NAME, kMANAGER_TITLE, - kMANAGER_SHAPE_SELECT, kMANAGER_MEDIA_SELECT,kMANAGER_MATERIAL_SELECT, kMANAGER_ELEMENT_SELECT, - kMANAGER_SHAPE_SELECT2, kMANAGER_MEDIUM_SELECT2, kMANAGER_VOLUME_SELECT, - kMANAGER_EDIT_SHAPE, kMANAGER_EDIT_MEDIUM, kMANAGER_DENSITY_SELECT, kMANAGER_NELEM_SELECT, - kMANAGER_MATERIAL_SELECT2, kMANAGER_MEDIUM_SELECT, kMANAGER_MATRIX_SELECT, kMANAGER_TOP_SELECT, - kEXPORT_ROOT, kEXPORT_C, kEXPORT_GEOMETRY, - kCAT_GENERAL, kCAT_SHAPES, kCAT_VOLUMES, kCAT_MEDIA, kCAT_MATERIALS, kCAT_MATRICES, - kCREATE_BOX, kCREATE_PARA, kCREATE_TRD1, kCREATE_TRD2, - kCREATE_TRAP, kCREATE_GTRA, kCREATE_XTRU, kCREATE_ARB8, - kCREATE_TUBE, kCREATE_TUBS, kCREATE_CONE, kCREATE_CONS, - kCREATE_SPHE, kCREATE_CTUB, kCREATE_ELTU, kCREATE_TORUS, - kCREATE_PCON, kCREATE_PGON, kCREATE_HYPE, kCREATE_PARAB, kCREATE_COMP, - kCREATE_MATERIAL, kCREATE_MIXTURE, kCREATE_MEDIUM, kCREATE_VOLUME, kCREATE_ASSEMBLY, - kCREATE_TRANSLATION, kCREATE_ROTATION, kCREATE_COMBI, - kMEDIUM_NAME, kMEDIUM_ID, kMATRIX_NAME, kMATERIAL_NAME, kVOLUME_NAME, - kMANAGER_APPLY, kMANAGER_CANCEL, kMANAGER_UNDO + kMANAGER_NAME, + kMANAGER_TITLE, + kMANAGER_SHAPE_SELECT, + kMANAGER_MEDIA_SELECT, + kMANAGER_MATERIAL_SELECT, + kMANAGER_ELEMENT_SELECT, + kMANAGER_SHAPE_SELECT2, + kMANAGER_MEDIUM_SELECT2, + kMANAGER_VOLUME_SELECT, + kMANAGER_EDIT_SHAPE, + kMANAGER_EDIT_MEDIUM, + kMANAGER_DENSITY_SELECT, + kMANAGER_NELEM_SELECT, + kMANAGER_MATERIAL_SELECT2, + kMANAGER_MEDIUM_SELECT, + kMANAGER_MATRIX_SELECT, + kMANAGER_TOP_SELECT, + kEXPORT_ROOT, + kEXPORT_C, + kEXPORT_GEOMETRY, + kCAT_GENERAL, + kCAT_SHAPES, + kCAT_VOLUMES, + kCAT_MEDIA, + kCAT_MATERIALS, + kCAT_MATRICES, + kCREATE_BOX, + kCREATE_PARA, + kCREATE_TRD1, + kCREATE_TRD2, + kCREATE_TRAP, + kCREATE_GTRA, + kCREATE_XTRU, + kCREATE_ARB8, + kCREATE_TUBE, + kCREATE_TUBS, + kCREATE_CONE, + kCREATE_CONS, + kCREATE_SPHE, + kCREATE_CTUB, + kCREATE_ELTU, + kCREATE_TORUS, + kCREATE_PCON, + kCREATE_PGON, + kCREATE_HYPE, + kCREATE_PARAB, + kCREATE_COMP, + kCREATE_MATERIAL, + kCREATE_MIXTURE, + kCREATE_MEDIUM, + kCREATE_VOLUME, + kCREATE_ASSEMBLY, + kCREATE_TRANSLATION, + kCREATE_ROTATION, + kCREATE_COMBI, + kMEDIUM_NAME, + kMEDIUM_ID, + kMATRIX_NAME, + kMATERIAL_NAME, + kVOLUME_NAME, + kMANAGER_APPLY, + kMANAGER_CANCEL, + kMANAGER_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for manager editor. -TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options | kVerticalFrame, back) { fGeometry = gGeoManager; - fTabMgr = 0; - fTab = 0; + fTabMgr = 0; + fTab = 0; fConnectedCanvas = 0; fIsModified = kFALSE; @@ -126,8 +172,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, TGCompositeFrame *container; Pixel_t color; // General settings - TGShutterItem *si = new TGShutterItem(fCategories, new TGHotString("General"),kCAT_GENERAL); - container = (TGCompositeFrame*)si->GetContainer(); + TGShutterItem *si = new TGShutterItem(fCategories, new TGHotString("General"), kCAT_GENERAL); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); // TextEntry for manager name @@ -188,9 +234,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, f7->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); container->AddFrame(f7, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); - - si = new TGShutterItem(fCategories, new TGHotString("Shapes"),kCAT_SHAPES); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Shapes"), kCAT_SHAPES); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -217,7 +262,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fShapeButton[4]->SetToolTipText("Create a general trapezoid"); fShapeButton[5] = new TGPictureButton(f1, fClient->GetPicture("geogtra_t.xpm"), kCREATE_GTRA); fShapeButton[5]->SetToolTipText("Create a general twisted trapezoid"); - for (ipict=0; ipict<6; ipict++) f1->AddFrame(fShapeButton[ipict],lhb); + for (ipict = 0; ipict < 6; ipict++) + f1->AddFrame(fShapeButton[ipict], lhb); container->AddFrame(f1, lhf1); f1 = new TGCompositeFrame(container, 118, 30, kHorizontalFrame); fShapeButton[6] = new TGPictureButton(f1, fClient->GetPicture("geoxtru_t.xpm"), kCREATE_XTRU); @@ -232,7 +278,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fShapeButton[10]->SetToolTipText("Create a conical pipe"); fShapeButton[11] = new TGPictureButton(f1, fClient->GetPicture("geoconeseg_t.xpm"), kCREATE_CONS); fShapeButton[11]->SetToolTipText("Create a conical pipe within a phi range"); - for (ipict=0; ipict<6; ipict++) f1->AddFrame(fShapeButton[ipict+6],lhb); + for (ipict = 0; ipict < 6; ipict++) + f1->AddFrame(fShapeButton[ipict + 6], lhb); container->AddFrame(f1, lhf1); f1 = new TGCompositeFrame(container, 118, 30, kHorizontalFrame); fShapeButton[12] = new TGPictureButton(f1, fClient->GetPicture("geosphere_t.xpm"), kCREATE_SPHE); @@ -247,7 +294,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fShapeButton[16]->SetToolTipText("Create a polycone shape"); fShapeButton[17] = new TGPictureButton(f1, fClient->GetPicture("geopgon_t.xpm"), kCREATE_PGON); fShapeButton[17]->SetToolTipText("Create a polygon shape"); - for (ipict=0; ipict<6; ipict++) f1->AddFrame(fShapeButton[ipict+12],lhb); + for (ipict = 0; ipict < 6; ipict++) + f1->AddFrame(fShapeButton[ipict + 12], lhb); container->AddFrame(f1, lhf1); f1 = new TGCompositeFrame(container, 118, 30, kHorizontalFrame); fShapeButton[18] = new TGPictureButton(f1, fClient->GetPicture("geohype_t.xpm"), kCREATE_HYPE); @@ -256,7 +304,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fShapeButton[19]->SetToolTipText("Create a paraboloid"); fShapeButton[20] = new TGPictureButton(f1, fClient->GetPicture("geocomposite_t.xpm"), kCREATE_COMP); fShapeButton[20]->SetToolTipText("Create a composite shape"); - for (ipict=0; ipict<3; ipict++) f1->AddFrame(fShapeButton[ipict+18],lhb); + for (ipict = 0; ipict < 3; ipict++) + f1->AddFrame(fShapeButton[ipict + 18], lhb); container->AddFrame(f1, lhf1); // List of shapes @@ -286,8 +335,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, container->AddFrame(f2, new TGLayoutHints(kLHintsLeft, 0, 0, 6, 0)); // Volumes category - si = new TGShutterItem(fCategories, new TGHotString("Volumes"),kCAT_VOLUMES); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Volumes"), kCAT_VOLUMES); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -340,7 +389,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fVolumeButton[0]->SetToolTipText("Create a new volume from shape and medium"); fVolumeButton[1] = new TGPictureButton(f1, fClient->GetPicture("geoassembly_t.xpm"), kCREATE_ASSEMBLY); fVolumeButton[1]->SetToolTipText("Create a new volume assembly having the selected name"); - for (ipict=0; ipict<2; ipict++) f1->AddFrame(fVolumeButton[ipict],lhb); + for (ipict = 0; ipict < 2; ipict++) + f1->AddFrame(fVolumeButton[ipict], lhb); container->AddFrame(f1, lhf1); // List of volumes f3 = new TGCompositeFrame(container, 155, 10, kVerticalFrame | kFixedWidth); @@ -375,8 +425,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, container->AddFrame(f3, new TGLayoutHints(kLHintsLeft, 0, 0, 6, 0)); // Materials category - si = new TGShutterItem(fCategories, new TGHotString("Materials"),kCAT_MATERIALS); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Materials"), kCAT_MATERIALS); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -403,9 +453,9 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, TGeoElementTable *table = gGeoManager->GetElementTable(); if (table) { TGeoElement *element; - for (Int_t i=0; iGetNelements(); i++) { + for (Int_t i = 0; i < table->GetNelements(); i++) { element = table->GetElement(i); - fElementList->AddEntry(element->GetTitle(),i); + fElementList->AddEntry(element->GetTitle(), i); } } fElementList->Select(0); @@ -417,8 +467,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fEntryDensity = new TGNumberEntry(f1, 0., 5, kMANAGER_DENSITY_SELECT); fEntryDensity->SetNumStyle(TGNumberFormat::kNESRealThree); fEntryDensity->SetNumAttr(TGNumberFormat::kNEANonNegative); - fEntryDensity->Resize(100,fEntryDensity->GetDefaultHeight()); - TGTextEntry *nef = (TGTextEntry*)fEntryDensity->GetNumberEntry(); + fEntryDensity->Resize(100, fEntryDensity->GetDefaultHeight()); + TGTextEntry *nef = (TGTextEntry *)fEntryDensity->GetNumberEntry(); nef->SetToolTipText("Enter material/mixture density"); fEntryDensity->SetNumber(0); fEntryDensity->Associate(this); @@ -432,7 +482,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fMaterialButton[0]->SetToolTipText("Create a new material from element and density"); fMaterialButton[1] = new TGPictureButton(f1, fClient->GetPicture("geomixture_t.xpm"), kCREATE_MIXTURE); fMaterialButton[1]->SetToolTipText("Create a new mixture with selected density"); - for (ipict=0; ipict<2; ipict++) f1->AddFrame(fMaterialButton[ipict],lhb); + for (ipict = 0; ipict < 2; ipict++) + f1->AddFrame(fMaterialButton[ipict], lhb); container->AddFrame(f1, lhf1); // List of materials @@ -461,8 +512,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, f4->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); container->AddFrame(f4, new TGLayoutHints(kLHintsLeft, 0, 0, 6, 0)); - si = new TGShutterItem(fCategories, new TGHotString("Media"),kCAT_MEDIA); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Media"), kCAT_MEDIA); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -484,12 +535,12 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fMediumId = new TGNumberEntry(f1, 0., 5, kMEDIUM_ID); fMediumId->SetNumStyle(TGNumberFormat::kNESInteger); fMediumId->SetNumAttr(TGNumberFormat::kNEAPositive); - fMediumId->Resize(35,fMediumId->GetDefaultHeight()); - nef = (TGTextEntry*)fMediumId->GetNumberEntry(); + fMediumId->Resize(35, fMediumId->GetDefaultHeight()); + nef = (TGTextEntry *)fMediumId->GetNumberEntry(); nef->SetToolTipText("Enter medium ID"); fMediumId->SetNumber(fGeometry->GetListOfMedia()->GetSize()); fMediumId->Associate(this); - f1->AddFrame(fMediumId, new TGLayoutHints(kLHintsRight, 2, 2, 2 ,2)); + f1->AddFrame(fMediumId, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); f1->AddFrame(new TGLabel(f1, "ID"), new TGLayoutHints(kLHintsRight, 1, 1, 6, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 0)); // ComboBox for materials @@ -515,7 +566,7 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, // List of media f5 = new TGCompositeFrame(container, 155, 10, kVerticalFrame | kFixedWidth); - f1 = new TGCompositeFrame(f5, 145, 10, kHorizontalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(f5, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(label = new TGLabel(f1, "Existing media"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); gClient->GetColorByName("#ff0000", color); @@ -540,8 +591,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, container->AddFrame(f5, new TGLayoutHints(kLHintsLeft, 0, 0, 6, 0)); // Matrix category - si = new TGShutterItem(fCategories, new TGHotString("Matrices"),kCAT_MATRICES); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Matrices"), kCAT_MATRICES); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); // Name entry @@ -568,7 +619,8 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, fMatrixButton[1]->SetToolTipText("Create a rotation"); fMatrixButton[2] = new TGPictureButton(f1, fClient->GetPicture("geocombi_t.xpm"), kCREATE_COMBI); fMatrixButton[2]->SetToolTipText("Create a rotation + translation"); - for (ipict=0; ipict<3; ipict++) f1->AddFrame(fMatrixButton[ipict],lhb); + for (ipict = 0; ipict < 3; ipict++) + f1->AddFrame(fMatrixButton[ipict], lhb); container->AddFrame(f1, lhf1); // List of matrices f6 = new TGCompositeFrame(container, 155, 10, kVerticalFrame | kFixedWidth); @@ -596,14 +648,14 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, f6->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); container->AddFrame(f6, new TGLayoutHints(kLHintsLeft, 0, 0, 6, 0)); - fCategories->Resize(163,370); + fCategories->Resize(163, 370); AddFrame(fCategories, new TGLayoutHints(kLHintsLeft, 0, 0, 4, 4)); fVolumeTab = CreateEditorTabSubFrame("Volume"); // Set the fTab and disconnect editor from the canvas. fTab = fGedEditor->GetTab(); - TCanvas* edCanvas = fGedEditor->GetCanvas(); + TCanvas *edCanvas = fGedEditor->GetCanvas(); fGedEditor->DisconnectFromCanvas(); if (edCanvas != fConnectedCanvas) { DisconnectSelected(); @@ -619,26 +671,27 @@ TGeoManagerEditor::TGeoManagerEditor(const TGWindow *p, Int_t width, TGeoManagerEditor::~TGeoManagerEditor() { TGCompositeFrame *cont; - cont = (TGCompositeFrame*)fCategories->GetItem("General")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("General")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("General")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Shapes")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Shapes")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Shapes")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Volumes")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Volumes")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Volumes")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Materials")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Materials")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Materials")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Media")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Media")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Media")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Matrices")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Matrices")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Matrices")->SetCleanup(0); - delete fExportOption[0]; delete fExportOption[1]; + delete fExportOption[0]; + delete fExportOption[1]; Cleanup(); @@ -652,10 +705,10 @@ TGeoManagerEditor::~TGeoManagerEditor() /// Connected to TCanvas::Selected. TGeoManagerEditor takes this /// function from TGedEditor and only uses it if obj is a TGeoVolume. -void TGeoManagerEditor::SelectedSlot(TVirtualPad* /*pad*/, TObject* obj, Int_t event) +void TGeoManagerEditor::SelectedSlot(TVirtualPad * /*pad*/, TObject *obj, Int_t event) { if (event == kButton1 && obj->InheritsFrom(TGeoVolume::Class())) { - TGeoVolume* v = (TGeoVolume*) obj; + TGeoVolume *v = (TGeoVolume *)obj; fTabMgr->SetVolTabEnabled(); fTabMgr->SetTab(); fTabMgr->GetVolumeEditor(v); @@ -667,8 +720,8 @@ void TGeoManagerEditor::ConnectSelected(TCanvas *c) { // Connect to TCanvas::Selected. - c->Connect("Selected(TVirtualPad*,TObject*,Int_t)", "TGeoManagerEditor", - this, "SelectedSlot(TVirtualPad*,TObject*,Int_t)"); + c->Connect("Selected(TVirtualPad*,TObject*,Int_t)", "TGeoManagerEditor", this, + "SelectedSlot(TVirtualPad*,TObject*,Int_t)"); } void TGeoManagerEditor::DisconnectSelected() @@ -676,9 +729,8 @@ void TGeoManagerEditor::DisconnectSelected() // Disconnect from TCanvas::Selected. if (fConnectedCanvas) - Disconnect(fConnectedCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", - this, "SelectedSlot(TVirtualPad*,TObject*,Int_t)"); - + Disconnect(fConnectedCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, + "SelectedSlot(TVirtualPad*,TObject*,Int_t)"); } //////////////////////////////////////////////////////////////////////////////// @@ -740,9 +792,9 @@ void TGeoManagerEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Refresh editor according the selected obj. -void TGeoManagerEditor::SetModel(TObject* obj) +void TGeoManagerEditor::SetModel(TObject *obj) { - fGeometry = (TGeoManager*)obj; + fGeometry = (TGeoManager *)obj; fManagerName->SetText(fGeometry->GetName()); fManagerTitle->SetText(fGeometry->GetTitle()); fMatrixName->SetText(TString::Format("matrix%i", fGeometry->GetListOfMatrices()->GetEntries())); @@ -750,10 +802,13 @@ void TGeoManagerEditor::SetModel(TObject* obj) fMediumName->SetText(TString::Format("medium%i", fGeometry->GetListOfMedia()->GetSize())); fVolumeName->SetText(TString::Format("volume%i", fGeometry->GetListOfVolumes()->GetEntries())); // Check if master volume can be set - if (fGeometry->GetMasterVolume()) fSetTopVolume->SetEnabled(kFALSE); - else fSetTopVolume->SetEnabled(kTRUE); + if (fGeometry->GetMasterVolume()) + fSetTopVolume->SetEnabled(kFALSE); + else + fSetTopVolume->SetEnabled(kTRUE); // Check if geometry is already closed - if (!fGeometry->IsClosed()) fCloseGeometry->SetEnabled(kTRUE); + if (!fGeometry->IsClosed()) + fCloseGeometry->SetEnabled(kTRUE); else { fCloseGeometry->SetEnabled(kFALSE); fBSelTop->SetEnabled(kFALSE); @@ -763,14 +818,22 @@ void TGeoManagerEditor::SetModel(TObject* obj) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kFALSE); else fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); - if (!fGeometry->GetListOfShapes()->GetEntries()) ShowSelectShape(kFALSE); - else ShowSelectShape(); - if (!fGeometry->GetListOfVolumes()->GetEntries()) ShowSelectVolume(kFALSE); - else ShowSelectVolume(); - if (!fGeometry->GetListOfMedia()->GetSize()) ShowSelectMedium(kFALSE); - else ShowSelectMedium(); - if (!fGeometry->GetListOfMatrices()->GetEntries()) ShowSelectMatrix(kFALSE); - else ShowSelectMatrix(); + if (!fGeometry->GetListOfShapes()->GetEntries()) + ShowSelectShape(kFALSE); + else + ShowSelectShape(); + if (!fGeometry->GetListOfVolumes()->GetEntries()) + ShowSelectVolume(kFALSE); + else + ShowSelectVolume(); + if (!fGeometry->GetListOfMedia()->GetSize()) + ShowSelectMedium(kFALSE); + else + ShowSelectMedium(); + if (!fGeometry->GetListOfMatrices()->GetEntries()) + ShowSelectMatrix(kFALSE); + else + ShowSelectMatrix(); // Check if media category can be activated if (!fGeometry->GetListOfMaterials()->GetSize()) { @@ -785,9 +848,10 @@ void TGeoManagerEditor::SetModel(TObject* obj) fCategories->Layout(); if (fTabMgr == 0) { fTabMgr = TGeoTabManager::GetMakeTabManager(fGedEditor); - fTabMgr->fVolumeTab = fVolumeTab; + fTabMgr->fVolumeTab = fVolumeTab; } - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); // SetActive(); } @@ -810,8 +874,10 @@ void TGeoManagerEditor::DoExportGeometry() s = s.Strip(); s.Remove(20); const char *name; - if (asroot) name = TString::Format("%s.root", s.Data()); - else name = TString::Format("%s.C", s.Data()); + if (asroot) + name = TString::Format("%s.root", s.Data()); + else + name = TString::Format("%s.C", s.Data()); fGeometry->Export(name); } @@ -821,7 +887,7 @@ void TGeoManagerEditor::DoExportGeometry() void TGeoManagerEditor::DoCreateBox() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoBBox(TString::Format("box_%i",id), 1., 1., 1.); + fSelectedShape = new TGeoBBox(TString::Format("box_%i", id), 1., 1., 1.); ShowSelectShape(); // Check if volumes category can be activated if (fGeometry->GetListOfMedia()->GetSize()) @@ -835,7 +901,7 @@ void TGeoManagerEditor::DoCreateBox() void TGeoManagerEditor::DoCreatePara() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoPara(TString::Format("para_%i",id), 1., 1., 1., 30., 20., 45.); + fSelectedShape = new TGeoPara(TString::Format("para_%i", id), 1., 1., 1., 30., 20., 45.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -848,7 +914,7 @@ void TGeoManagerEditor::DoCreatePara() void TGeoManagerEditor::DoCreateTrd1() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTrd1(TString::Format("trd1_%i",id), 0.5, 1., 1., 1.); + fSelectedShape = new TGeoTrd1(TString::Format("trd1_%i", id), 0.5, 1., 1., 1.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -861,7 +927,7 @@ void TGeoManagerEditor::DoCreateTrd1() void TGeoManagerEditor::DoCreateTrd2() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTrd2(TString::Format("trd2_%i",id), 0.5, 1., 0.5, 1., 1.); + fSelectedShape = new TGeoTrd2(TString::Format("trd2_%i", id), 0.5, 1., 0.5, 1., 1.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -874,7 +940,7 @@ void TGeoManagerEditor::DoCreateTrd2() void TGeoManagerEditor::DoCreateTrap() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTrap(TString::Format("trap_%i",id), 1., 15., 45., 0.5, 0.3, 0.5, 30., 0.5, 0.3, 0.5, 30.); + fSelectedShape = new TGeoTrap(TString::Format("trap_%i", id), 1., 15., 45., 0.5, 0.3, 0.5, 30., 0.5, 0.3, 0.5, 30.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -887,7 +953,8 @@ void TGeoManagerEditor::DoCreateTrap() void TGeoManagerEditor::DoCreateGtra() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoGtra(TString::Format("gtra_%i",id), 1., 15., 45., 45.,0.5, 0.3, 0.5, 30., 0.5, 0.3, 0.5, 30.); + fSelectedShape = + new TGeoGtra(TString::Format("gtra_%i", id), 1., 15., 45., 45., 0.5, 0.3, 0.5, 30., 0.5, 0.3, 0.5, 30.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -897,17 +964,13 @@ void TGeoManagerEditor::DoCreateGtra() //////////////////////////////////////////////////////////////////////////////// /// Create an extruded polygone. -void TGeoManagerEditor::DoCreateXtru() -{ -} +void TGeoManagerEditor::DoCreateXtru() {} //////////////////////////////////////////////////////////////////////////////// /// Create an arbitrary polygone with maximum 8 vertices sitting on 2 parallel /// planes -void TGeoManagerEditor::DoCreateArb8() -{ -} +void TGeoManagerEditor::DoCreateArb8() {} //////////////////////////////////////////////////////////////////////////////// /// Create a tube. @@ -915,7 +978,7 @@ void TGeoManagerEditor::DoCreateArb8() void TGeoManagerEditor::DoCreateTube() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTube(TString::Format("tube_%i",id), 0.5, 1., 1.); + fSelectedShape = new TGeoTube(TString::Format("tube_%i", id), 0.5, 1., 1.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -928,7 +991,7 @@ void TGeoManagerEditor::DoCreateTube() void TGeoManagerEditor::DoCreateTubs() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTubeSeg(TString::Format("tubs_%i",id), 0.5, 1., 1.,0.,45.); + fSelectedShape = new TGeoTubeSeg(TString::Format("tubs_%i", id), 0.5, 1., 1., 0., 45.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -941,7 +1004,7 @@ void TGeoManagerEditor::DoCreateTubs() void TGeoManagerEditor::DoCreateCone() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoCone(TString::Format("cone_%i",id), 0.5, 0.5, 1., 1.5, 2.); + fSelectedShape = new TGeoCone(TString::Format("cone_%i", id), 0.5, 0.5, 1., 1.5, 2.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -954,7 +1017,7 @@ void TGeoManagerEditor::DoCreateCone() void TGeoManagerEditor::DoCreateCons() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoConeSeg(TString::Format("cons_%i",id), 0.5, 0.5, 1., 1.5, 2.,0.,45.); + fSelectedShape = new TGeoConeSeg(TString::Format("cons_%i", id), 0.5, 0.5, 1., 1.5, 2., 0., 45.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -967,7 +1030,7 @@ void TGeoManagerEditor::DoCreateCons() void TGeoManagerEditor::DoCreateSphe() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoSphere(TString::Format("sphere_%i",id), 0.5, 1., 0., 180., 0.,360.); + fSelectedShape = new TGeoSphere(TString::Format("sphere_%i", id), 0.5, 1., 0., 180., 0., 360.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -980,7 +1043,7 @@ void TGeoManagerEditor::DoCreateSphe() void TGeoManagerEditor::DoCreateCtub() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoCtub(TString::Format("ctub_%i",id), 0.5, 1., 1.,0.,45.,0.,0.,-1,0.,0.,1); + fSelectedShape = new TGeoCtub(TString::Format("ctub_%i", id), 0.5, 1., 1., 0., 45., 0., 0., -1, 0., 0., 1); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -993,7 +1056,7 @@ void TGeoManagerEditor::DoCreateCtub() void TGeoManagerEditor::DoCreateEltu() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoEltu(TString::Format("para_%i",id), 1., 2., 1.5 ); + fSelectedShape = new TGeoEltu(TString::Format("para_%i", id), 1., 2., 1.5); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -1006,12 +1069,11 @@ void TGeoManagerEditor::DoCreateEltu() void TGeoManagerEditor::DoCreateTorus() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoTorus(TString::Format("torus_%i",id), 10., 1., 1.5, 0, 360.); + fSelectedShape = new TGeoTorus(TString::Format("torus_%i", id), 10., 1., 1.5, 0, 360.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); DoEditShape(); - } //////////////////////////////////////////////////////////////////////////////// @@ -1020,9 +1082,9 @@ void TGeoManagerEditor::DoCreateTorus() void TGeoManagerEditor::DoCreatePcon() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoPcon(TString::Format("pcon_%i",id), 0., 360., 2); - ((TGeoPcon*)fSelectedShape)->DefineSection(0, -1, 0.5, 1.); - ((TGeoPcon*)fSelectedShape)->DefineSection(1, 1, 0.2, 0.5); + fSelectedShape = new TGeoPcon(TString::Format("pcon_%i", id), 0., 360., 2); + ((TGeoPcon *)fSelectedShape)->DefineSection(0, -1, 0.5, 1.); + ((TGeoPcon *)fSelectedShape)->DefineSection(1, 1, 0.2, 0.5); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -1035,9 +1097,9 @@ void TGeoManagerEditor::DoCreatePcon() void TGeoManagerEditor::DoCreatePgon() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoPgon(TString::Format("pgon_%i",id), 0., 360.,6,2); - ((TGeoPcon*)fSelectedShape)->DefineSection(0, -1, 0.5, 1.); - ((TGeoPcon*)fSelectedShape)->DefineSection(1, 1, 0.2, 0.5); + fSelectedShape = new TGeoPgon(TString::Format("pgon_%i", id), 0., 360., 6, 2); + ((TGeoPcon *)fSelectedShape)->DefineSection(0, -1, 0.5, 1.); + ((TGeoPcon *)fSelectedShape)->DefineSection(1, 1, 0.2, 0.5); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -1050,7 +1112,7 @@ void TGeoManagerEditor::DoCreatePgon() void TGeoManagerEditor::DoCreateHype() { Int_t id = gGeoManager->GetListOfShapes()->GetEntries(); - fSelectedShape = new TGeoHype(TString::Format("hype_%i",id), 1., 15., 2., 30., 5.); + fSelectedShape = new TGeoHype(TString::Format("hype_%i", id), 1., 15., 2., 30., 5.); ShowSelectShape(); if (fGeometry->GetListOfMedia()->GetSize()) fCategories->GetItem("Volumes")->GetButton()->SetEnabled(kTRUE); @@ -1060,16 +1122,12 @@ void TGeoManagerEditor::DoCreateHype() //////////////////////////////////////////////////////////////////////////////// /// Create a paraboloid. -void TGeoManagerEditor::DoCreateParab() -{ -} +void TGeoManagerEditor::DoCreateParab() {} //////////////////////////////////////////////////////////////////////////////// /// Create a composite shape. -void TGeoManagerEditor::DoCreateComposite() -{ -} +void TGeoManagerEditor::DoCreateComposite() {} //////////////////////////////////////////////////////////////////////////////// /// Create a new material. @@ -1110,7 +1168,8 @@ void TGeoManagerEditor::DoCreateMixture() void TGeoManagerEditor::DoCreateMedium() { Int_t id = fMediumId->GetIntNumber(); - if (!fSelectedMaterial2) return; + if (!fSelectedMaterial2) + return; const char *name = fMediumName->GetText(); fSelectedMedium = new TGeoMedium(name, id, fSelectedMaterial2); ShowSelectMedium(); @@ -1154,7 +1213,8 @@ void TGeoManagerEditor::DoCreateRotation() void TGeoManagerEditor::DoCreateVolume() { const char *name = fVolumeName->GetText(); - if (!fSelectedShape2 || !fSelectedMedium2) return; + if (!fSelectedShape2 || !fSelectedMedium2) + return; fSelectedVolume = new TGeoVolume(name, fSelectedShape2, fSelectedMedium2); fLSelVolume->SetText(name); ShowSelectVolume(); @@ -1195,7 +1255,8 @@ void TGeoManagerEditor::DoCreateCombi() void TGeoManagerEditor::DoSetTopVolume() { - if (!fSelectedVolume) return; + if (!fSelectedVolume) + return; fGeometry->SetTopVolume(fSelectedVolume); fSetTopVolume->SetEnabled(kFALSE); } @@ -1205,7 +1266,8 @@ void TGeoManagerEditor::DoSetTopVolume() void TGeoManagerEditor::DoEditShape() { - if (!fSelectedShape) return; + if (!fSelectedShape) + return; fTabMgr->GetShapeEditor(fSelectedShape); fSelectedShape->Draw(); fTabMgr->GetPad()->GetView()->ShowAxis(); @@ -1231,7 +1293,8 @@ void TGeoManagerEditor::DoEditVolume() void TGeoManagerEditor::DoEditMedium() { - if (!fSelectedMedium) return; + if (!fSelectedMedium) + return; fTabMgr->GetMediumEditor(fSelectedMedium); } @@ -1240,7 +1303,8 @@ void TGeoManagerEditor::DoEditMedium() void TGeoManagerEditor::DoEditMaterial() { - if (!fSelectedMaterial) return; + if (!fSelectedMaterial) + return; fTabMgr->GetMaterialEditor(fSelectedMaterial); } @@ -1249,7 +1313,8 @@ void TGeoManagerEditor::DoEditMaterial() void TGeoManagerEditor::DoEditMatrix() { - if (!fSelectedMatrix) return; + if (!fSelectedMatrix) + return; fTabMgr->GetMatrixEditor(fSelectedMatrix); } @@ -1259,10 +1324,12 @@ void TGeoManagerEditor::DoEditMatrix() void TGeoManagerEditor::DoSelectMatrix() { TGeoMatrix *matrix = fSelectedMatrix; - new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200,300); - fSelectedMatrix = (TGeoMatrix*)TGeoMatrixDialog::GetSelected(); - if (fSelectedMatrix) fLSelMatrix->SetText(fSelectedMatrix->GetName()); - else fSelectedMatrix = matrix; + new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200, 300); + fSelectedMatrix = (TGeoMatrix *)TGeoMatrixDialog::GetSelected(); + if (fSelectedMatrix) + fLSelMatrix->SetText(fSelectedMatrix->GetName()); + else + fSelectedMatrix = matrix; } //////////////////////////////////////////////////////////////////////////////// @@ -1271,10 +1338,12 @@ void TGeoManagerEditor::DoSelectMatrix() void TGeoManagerEditor::DoSelectShape() { TGeoShape *shape = fSelectedShape; - new TGeoShapeDialog(fBSelShape, gClient->GetRoot(), 200,300); - fSelectedShape = (TGeoShape*)TGeoShapeDialog::GetSelected(); - if (fSelectedShape) fLSelShape->SetText(fSelectedShape->GetName()); - else fSelectedShape = shape; + new TGeoShapeDialog(fBSelShape, gClient->GetRoot(), 200, 300); + fSelectedShape = (TGeoShape *)TGeoShapeDialog::GetSelected(); + if (fSelectedShape) + fLSelShape->SetText(fSelectedShape->GetName()); + else + fSelectedShape = shape; } //////////////////////////////////////////////////////////////////////////////// @@ -1283,10 +1352,12 @@ void TGeoManagerEditor::DoSelectShape() void TGeoManagerEditor::DoSelectShape2() { TGeoShape *shape = fSelectedShape2; - new TGeoShapeDialog(fBSelShape2, gClient->GetRoot(), 200,300); - fSelectedShape2 = (TGeoShape*)TGeoShapeDialog::GetSelected(); - if (fSelectedShape2) fLSelShape2->SetText(fSelectedShape2->GetName()); - else fSelectedShape2 = shape; + new TGeoShapeDialog(fBSelShape2, gClient->GetRoot(), 200, 300); + fSelectedShape2 = (TGeoShape *)TGeoShapeDialog::GetSelected(); + if (fSelectedShape2) + fLSelShape2->SetText(fSelectedShape2->GetName()); + else + fSelectedShape2 = shape; } //////////////////////////////////////////////////////////////////////////////// @@ -1295,10 +1366,12 @@ void TGeoManagerEditor::DoSelectShape2() void TGeoManagerEditor::DoSelectMaterial() { TGeoMaterial *mat = fSelectedMaterial; - new TGeoMaterialDialog(fBSelMaterial, gClient->GetRoot(), 200,300); - fSelectedMaterial = (TGeoMaterial*)TGeoMaterialDialog::GetSelected(); - if (fSelectedMaterial) fLSelMaterial->SetText(fSelectedMaterial->GetName()); - else fSelectedMaterial = mat; + new TGeoMaterialDialog(fBSelMaterial, gClient->GetRoot(), 200, 300); + fSelectedMaterial = (TGeoMaterial *)TGeoMaterialDialog::GetSelected(); + if (fSelectedMaterial) + fLSelMaterial->SetText(fSelectedMaterial->GetName()); + else + fSelectedMaterial = mat; } //////////////////////////////////////////////////////////////////////////////// @@ -1307,10 +1380,12 @@ void TGeoManagerEditor::DoSelectMaterial() void TGeoManagerEditor::DoSelectMaterial2() { TGeoMaterial *mat = fSelectedMaterial2; - new TGeoMaterialDialog(fBSelMaterial2, gClient->GetRoot(), 200,300); - fSelectedMaterial2 = (TGeoMaterial*)TGeoMaterialDialog::GetSelected(); - if (fSelectedMaterial2) fLSelMaterial2->SetText(fSelectedMaterial2->GetName()); - else fSelectedMaterial2 = mat; + new TGeoMaterialDialog(fBSelMaterial2, gClient->GetRoot(), 200, 300); + fSelectedMaterial2 = (TGeoMaterial *)TGeoMaterialDialog::GetSelected(); + if (fSelectedMaterial2) + fLSelMaterial2->SetText(fSelectedMaterial2->GetName()); + else + fSelectedMaterial2 = mat; } //////////////////////////////////////////////////////////////////////////////// @@ -1319,10 +1394,12 @@ void TGeoManagerEditor::DoSelectMaterial2() void TGeoManagerEditor::DoSelectMedium() { TGeoMedium *med = fSelectedMedium; - new TGeoMediumDialog(fBSelMedium, gClient->GetRoot(), 200,300); - fSelectedMedium = (TGeoMedium*)TGeoMediumDialog::GetSelected(); - if (fSelectedMedium) fLSelMedium->SetText(fSelectedMedium->GetName()); - else fSelectedMedium = med; + new TGeoMediumDialog(fBSelMedium, gClient->GetRoot(), 200, 300); + fSelectedMedium = (TGeoMedium *)TGeoMediumDialog::GetSelected(); + if (fSelectedMedium) + fLSelMedium->SetText(fSelectedMedium->GetName()); + else + fSelectedMedium = med; } //////////////////////////////////////////////////////////////////////////////// @@ -1331,10 +1408,12 @@ void TGeoManagerEditor::DoSelectMedium() void TGeoManagerEditor::DoSelectMedium2() { TGeoMedium *med = fSelectedMedium2; - new TGeoMediumDialog(fBSelMedium2, gClient->GetRoot(), 200,300); - fSelectedMedium2 = (TGeoMedium*)TGeoMediumDialog::GetSelected(); - if (fSelectedMedium2) fLSelMedium2->SetText(fSelectedMedium2->GetName()); - else fSelectedMedium2 = med; + new TGeoMediumDialog(fBSelMedium2, gClient->GetRoot(), 200, 300); + fSelectedMedium2 = (TGeoMedium *)TGeoMediumDialog::GetSelected(); + if (fSelectedMedium2) + fLSelMedium2->SetText(fSelectedMedium2->GetName()); + else + fSelectedMedium2 = med; } //////////////////////////////////////////////////////////////////////////////// @@ -1343,10 +1422,12 @@ void TGeoManagerEditor::DoSelectMedium2() void TGeoManagerEditor::DoSelectVolume() { TGeoVolume *vol = fSelectedVolume; - new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200,300); - fSelectedVolume = (TGeoVolume*)TGeoVolumeDialog::GetSelected(); - if (fSelectedVolume) fLSelVolume->SetText(fSelectedVolume->GetName()); - else fSelectedVolume = vol; + new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200, 300); + fSelectedVolume = (TGeoVolume *)TGeoVolumeDialog::GetSelected(); + if (fSelectedVolume) + fLSelVolume->SetText(fSelectedVolume->GetName()); + else + fSelectedVolume = vol; } //////////////////////////////////////////////////////////////////////////////// @@ -1355,11 +1436,14 @@ void TGeoManagerEditor::DoSelectVolume() void TGeoManagerEditor::DoSelectTopVolume() { TGeoVolume *vol = fGeometry->GetTopVolume(); - new TGeoVolumeDialog(fBSelTop, gClient->GetRoot(), 200,300); - fSelectedVolume = (TGeoVolume*)TGeoVolumeDialog::GetSelected(); - if (fSelectedVolume) fLSelTop->SetText(fSelectedVolume->GetName()); - else fSelectedVolume = vol; - if (fSelectedVolume && (fSelectedVolume != vol)) fGeometry->SetTopVolume(fSelectedVolume); + new TGeoVolumeDialog(fBSelTop, gClient->GetRoot(), 200, 300); + fSelectedVolume = (TGeoVolume *)TGeoVolumeDialog::GetSelected(); + if (fSelectedVolume) + fLSelTop->SetText(fSelectedVolume->GetName()); + else + fSelectedVolume = vol; + if (fSelectedVolume && (fSelectedVolume != vol)) + fGeometry->SetTopVolume(fSelectedVolume); } //////////////////////////////////////////////////////////////////////////////// @@ -1367,7 +1451,8 @@ void TGeoManagerEditor::DoSelectTopVolume() void TGeoManagerEditor::DoCloseGeometry() { - if (!fGeometry->IsClosed()) fGeometry->CloseGeometry(); + if (!fGeometry->IsClosed()) + fGeometry->CloseGeometry(); fCloseGeometry->SetEnabled(kFALSE); } @@ -1376,9 +1461,11 @@ void TGeoManagerEditor::DoCloseGeometry() void TGeoManagerEditor::ShowSelectShape(Bool_t show) { - TGCompositeFrame *cont = (TGCompositeFrame*)fCategories->GetItem("Shapes")->GetContainer(); - if (show) cont->ShowFrame(f2); - else cont->HideFrame(f2); + TGCompositeFrame *cont = (TGCompositeFrame *)fCategories->GetItem("Shapes")->GetContainer(); + if (show) + cont->ShowFrame(f2); + else + cont->HideFrame(f2); } //////////////////////////////////////////////////////////////////////////////// @@ -1386,12 +1473,16 @@ void TGeoManagerEditor::ShowSelectShape(Bool_t show) void TGeoManagerEditor::ShowSelectVolume(Bool_t show) { - TGCompositeFrame *cont = (TGCompositeFrame*)fCategories->GetItem("General")->GetContainer(); - if (show) cont->ShowFrame(f7); - else cont->HideFrame(f7); - cont = (TGCompositeFrame*)fCategories->GetItem("Volumes")->GetContainer(); - if (show) cont->ShowFrame(f3); - else cont->HideFrame(f3); + TGCompositeFrame *cont = (TGCompositeFrame *)fCategories->GetItem("General")->GetContainer(); + if (show) + cont->ShowFrame(f7); + else + cont->HideFrame(f7); + cont = (TGCompositeFrame *)fCategories->GetItem("Volumes")->GetContainer(); + if (show) + cont->ShowFrame(f3); + else + cont->HideFrame(f3); } //////////////////////////////////////////////////////////////////////////////// @@ -1399,9 +1490,11 @@ void TGeoManagerEditor::ShowSelectVolume(Bool_t show) void TGeoManagerEditor::ShowSelectMaterial(Bool_t show) { - TGCompositeFrame *cont = (TGCompositeFrame*)fCategories->GetItem("Materials")->GetContainer(); - if (show) cont->ShowFrame(f4); - else cont->HideFrame(f4); + TGCompositeFrame *cont = (TGCompositeFrame *)fCategories->GetItem("Materials")->GetContainer(); + if (show) + cont->ShowFrame(f4); + else + cont->HideFrame(f4); } //////////////////////////////////////////////////////////////////////////////// @@ -1409,9 +1502,11 @@ void TGeoManagerEditor::ShowSelectMaterial(Bool_t show) void TGeoManagerEditor::ShowSelectMedium(Bool_t show) { - TGCompositeFrame *cont = (TGCompositeFrame*)fCategories->GetItem("Media")->GetContainer(); - if (show) cont->ShowFrame(f5); - else cont->HideFrame(f5); + TGCompositeFrame *cont = (TGCompositeFrame *)fCategories->GetItem("Media")->GetContainer(); + if (show) + cont->ShowFrame(f5); + else + cont->HideFrame(f5); } //////////////////////////////////////////////////////////////////////////////// @@ -1419,16 +1514,14 @@ void TGeoManagerEditor::ShowSelectMedium(Bool_t show) void TGeoManagerEditor::ShowSelectMatrix(Bool_t show) { - TGCompositeFrame *cont = (TGCompositeFrame*)fCategories->GetItem("Matrices")->GetContainer(); - if (show) cont->ShowFrame(f6); - else cont->HideFrame(f6); + TGCompositeFrame *cont = (TGCompositeFrame *)fCategories->GetItem("Matrices")->GetContainer(); + if (show) + cont->ShowFrame(f6); + else + cont->HideFrame(f6); } - //////////////////////////////////////////////////////////////////////////////// /// Dummy static function, used to load plugin -void TGeoManagerEditor::LoadLib() -{ - -} +void TGeoManagerEditor::LoadLib() {} diff --git a/geom/geombuilder/src/TGeoMaterialEditor.cxx b/geom/geombuilder/src/TGeoMaterialEditor.cxx index 6f75b2438de13..d9cf5f49fadc4 100644 --- a/geom/geombuilder/src/TGeoMaterialEditor.cxx +++ b/geom/geombuilder/src/TGeoMaterialEditor.cxx @@ -33,27 +33,31 @@ Editors for materials. ClassImp(TGeoMaterialEditor); enum ETGeoMaterialWid { - kMATERIAL_NAME, kMATERIAL_A, kMATERIAL_Z, kMATERIAL_RHO, - kMATERIAL_RAD, kMATERIAL_ABS, kMATERIAL_STATE, kMATERIAL_TEMP, kMATERIAL_PRES, - kMATERIAL_APPLY, kMATERIAL_CANCEL, kMATERIAL_UNDO + kMATERIAL_NAME, + kMATERIAL_A, + kMATERIAL_Z, + kMATERIAL_RHO, + kMATERIAL_RAD, + kMATERIAL_ABS, + kMATERIAL_STATE, + kMATERIAL_TEMP, + kMATERIAL_PRES, + kMATERIAL_APPLY, + kMATERIAL_CANCEL, + kMATERIAL_UNDO }; -enum ETGeoMaterialStates { - kMAT_UNDEFINED, kMAT_SOLID, kMAT_LIQUID, kMAT_GAS -}; +enum ETGeoMaterialStates { kMAT_UNDEFINED, kMAT_SOLID, kMAT_LIQUID, kMAT_GAS }; -enum ETGeoMixtureWid { - kMIX_ELEM, kMIX_CHK1, kMIX_FRAC, kMIX_CHK2, kMIX_NATOMS, kMIX_ADDELEM -}; +enum ETGeoMixtureWid { kMIX_ELEM, kMIX_CHK1, kMIX_FRAC, kMIX_CHK2, kMIX_NATOMS, kMIX_ADDELEM }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for material editor. -TGeoMaterialEditor::TGeoMaterialEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoMaterialEditor::TGeoMaterialEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fMaterial = 0; + fMaterial = 0; fAi = fZi = 0; fDensityi = 0.0; fNamei = ""; @@ -70,28 +74,25 @@ TGeoMaterialEditor::TGeoMaterialEditor(const TGWindow *p, Int_t width, TGTextEntry *nef; MakeTitle("Material properties"); - TGCompositeFrame *f1 = new TGCompositeFrame(this, 118, 10, kHorizontalFrame | - kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = new TGCompositeFrame(this, 118, 10, kHorizontalFrame | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "A"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatA = new TGNumberEntry(f1, 0., 6, kMATERIAL_A, TGNumberFormat::kNESRealThree); - nef = (TGTextEntry*)fMatA->GetNumberEntry(); + nef = (TGTextEntry *)fMatA->GetNumberEntry(); nef->SetToolTipText("Enter the atomic mass"); fMatA->Associate(this); f1->AddFrame(fMatA, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); f1->AddFrame(new TGLabel(f1, "Z"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatZ = new TGNumberEntry(f1, 0., 4, kMATERIAL_Z, TGNumberFormat::kNESInteger); - nef = (TGTextEntry*)fMatZ->GetNumberEntry(); + nef = (TGTextEntry *)fMatZ->GetNumberEntry(); nef->SetToolTipText("Enter the atomic charge"); fMatZ->Associate(this); f1->AddFrame(fMatZ, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - f1->Resize(150,30); + f1->Resize(150, 30); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1)); - TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Combo box for material state - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "State"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatState = new TGComboBox(f1, kMATERIAL_STATE); fMatState->AddEntry("Undefined", TGeoMaterial::kMatStateUndefined); @@ -99,70 +100,65 @@ TGeoMaterialEditor::TGeoMaterialEditor(const TGWindow *p, Int_t width, fMatState->AddEntry("Liquid", TGeoMaterial::kMatStateLiquid); fMatState->AddEntry("Gas", TGeoMaterial::kMatStateGas); fMatState->Resize(90, fMaterialName->GetDefaultHeight()); - f1->AddFrame(fMatState, new TGLayoutHints(kLHintsRight , 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f1->AddFrame(fMatState, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for density - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "Density"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatDensity = new TGNumberEntry(f1, 0., 5, kMATERIAL_RHO, TGNumberFormat::kNESRealThree); fMatDensity->Resize(90, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fMatDensity->GetNumberEntry(); + nef = (TGTextEntry *)fMatDensity->GetNumberEntry(); nef->SetToolTipText("Enter material density in [g/cm3]"); fMatDensity->Associate(this); f1->AddFrame(fMatDensity, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for temperature - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "Temperature"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatTemperature = new TGNumberEntry(f1, 0., 5, kMATERIAL_TEMP, TGNumberFormat::kNESRealTwo); fMatTemperature->Resize(90, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fMatTemperature->GetNumberEntry(); + nef = (TGTextEntry *)fMatTemperature->GetNumberEntry(); nef->SetToolTipText("Enter material temperature in [Kelvin]"); fMatTemperature->Associate(this); f1->AddFrame(fMatTemperature, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for pressure - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "Pressure"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatPressure = new TGNumberEntry(f1, 0., 5, kMATERIAL_PRES, TGNumberFormat::kNESRealThree); fMatPressure->Resize(90, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fMatPressure->GetNumberEntry(); + nef = (TGTextEntry *)fMatPressure->GetNumberEntry(); nef->SetToolTipText("Enter material pressure in [bar]"); fMatPressure->Associate(this); f1->AddFrame(fMatPressure, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for radiation length - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "RadLen"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatRadLen = new TGNumberEntry(f1, 0., 5, kMATERIAL_RAD); fMatRadLen->Resize(90, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fMatRadLen->GetNumberEntry(); + nef = (TGTextEntry *)fMatRadLen->GetNumberEntry(); nef->SetToolTipText("Computed radiation length"); fMatRadLen->Associate(this); f1->AddFrame(fMatRadLen, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for absorption length - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "AbsLen"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fMatAbsLen = new TGNumberEntry(f1, 0., 5, kMATERIAL_ABS); fMatAbsLen->Resize(90, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fMatAbsLen->GetNumberEntry(); + nef = (TGTextEntry *)fMatAbsLen->GetNumberEntry(); nef->SetToolTipText("Absorption length"); fMatAbsLen->Associate(this); f1->AddFrame(fMatAbsLen, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 0, 0, 2, 2)); // Buttons @@ -171,9 +167,9 @@ TGeoMaterialEditor::TGeoMaterialEditor(const TGWindow *p, Int_t width, f23->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 1, 1)); fApply->Associate(this); fUndo = new TGTextButton(f23, " Undo "); - f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 1, 1)); + f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); fUndo->Associate(this); - AddFrame(f23, new TGLayoutHints(kLHintsLeft, 0, 0, 4, 4)); + AddFrame(f23, new TGLayoutHints(kLHintsLeft, 0, 0, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -186,7 +182,7 @@ TGeoMaterialEditor::~TGeoMaterialEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -213,19 +209,19 @@ void TGeoMaterialEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected material. -void TGeoMaterialEditor::SetModel(TObject* obj) +void TGeoMaterialEditor::SetModel(TObject *obj) { if (obj == 0 || !(obj->InheritsFrom(TGeoMaterial::Class()))) { SetActive(kFALSE); return; } - fMaterial = (TGeoMaterial*)obj; + fMaterial = (TGeoMaterial *)obj; fAi = fMaterial->GetA(); fZi = (Int_t)fMaterial->GetZ(); fStatei = (Int_t)fMaterial->GetState(); fDensityi = fMaterial->GetDensity(); fTempi = fMaterial->GetTemperature(); - fPresi = fMaterial->GetPressure()/6.2415e+8; + fPresi = fMaterial->GetPressure() / 6.2415e+8; fNamei = fMaterial->GetName(); fMaterialName->SetText(fMaterial->GetName()); fMatA->SetNumber(fAi); @@ -239,7 +235,8 @@ void TGeoMaterialEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -275,11 +272,12 @@ void TGeoMaterialEditor::DoZ() Int_t z = (Int_t)fMatZ->GetNumber(); TGeoElementTable *table = gGeoManager->GetElementTable(); if (z >= table->GetNelements()) { - z = table->GetNelements()-1; + z = table->GetNelements() - 1; fMatZ->SetNumber(z); } TGeoElement *elem = table->GetElement(z); - if (!elem) return; + if (!elem) + return; Double_t a = elem->A(); fMatA->SetNumber(a); DoModified(); @@ -340,7 +338,7 @@ void TGeoMaterialEditor::DoApply() fMaterial->SetZ(fMatZ->GetNumber()); fMaterial->SetDensity(fMatDensity->GetNumber()); fMaterial->SetTemperature(fMatTemperature->GetNumber()); - fMaterial->SetPressure(6.2415e+8*fMatPressure->GetNumber()); + fMaterial->SetPressure(6.2415e+8 * fMatPressure->GetNumber()); fMaterial->SetState((TGeoMaterial::EGeoMaterialState)fMatState->GetSelected()); fMaterial->SetRadLen(fMatRadLen->GetNumber(), fMatAbsLen->GetNumber()); fMatRadLen->SetNumber(fMaterial->GetRadLen()); @@ -367,7 +365,7 @@ void TGeoMaterialEditor::DoUndo() fMatTemperature->SetNumber(fTempi); fMaterial->SetTemperature(fTempi); fMatPressure->SetNumber(fPresi); - fMaterial->SetPressure(fPresi*6.2415e+8); + fMaterial->SetPressure(fPresi * 6.2415e+8); fMatRadLen->SetNumber(fMaterial->GetRadLen()); fMatAbsLen->SetNumber(fMaterial->GetIntLen()); fApply->SetEnabled(kFALSE); @@ -394,78 +392,75 @@ ClassImp(TGeoMixtureEditor); //////////////////////////////////////////////////////////////////////////////// /// Constructor for mixture editor. -TGeoMixtureEditor::TGeoMixtureEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoMixtureEditor::TGeoMixtureEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoMaterialEditor(p, width, height, options | kVerticalFrame, back) { fMixture = 0; - TGCompositeFrame *compxyz=0, *f1=0; + TGCompositeFrame *compxyz = 0, *f1 = 0; TGTextEntry *nef; MakeTitle("Mixture settings"); fNelem = new TGLabel(this, "Number of elements: 0"); - AddFrame(fNelem, new TGLayoutHints(kLHintsLeft , 6, 2, 2, 2)); + AddFrame(fNelem, new TGLayoutHints(kLHintsLeft, 6, 2, 2, 2)); compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Combo box for selecting elements - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); fMixElem = new TGComboBox(f1, kMIX_ELEM); TGeoElementTable *table = gGeoManager->GetElementTable(); if (table) { TGeoElement *element; - for (Int_t i=0; iGetNelements(); i++) { + for (Int_t i = 0; i < table->GetNelements(); i++) { element = table->GetElement(i); - if (element) fMixElem->AddEntry(element->GetTitle(),i); + if (element) + fMixElem->AddEntry(element->GetTitle(), i); } } fMixElem->Select(0); fMixElem->Resize(90, fMaterialName->GetDefaultHeight()); - f1->AddFrame(fMixElem, new TGLayoutHints(kLHintsLeft , 2, 2, 1, 1)); + f1->AddFrame(fMixElem, new TGLayoutHints(kLHintsLeft, 2, 2, 1, 1)); TGCompositeFrame *comp1 = new TGCompositeFrame(f1, 118, 30, kVerticalFrame); fAelem = new TGLabel(comp1, "A = 0"); - comp1->AddFrame(fAelem, new TGLayoutHints(kLHintsRight , 2, 2, 2, 0)); + comp1->AddFrame(fAelem, new TGLayoutHints(kLHintsRight, 2, 2, 2, 0)); fZelem = new TGLabel(comp1, "Z = 0"); - comp1->AddFrame(fZelem, new TGLayoutHints(kLHintsRight , 2, 2, 2, 0)); - f1->AddFrame(comp1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX| kLHintsExpandY , 2, 2, 0, 0)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 0, 0)); + comp1->AddFrame(fZelem, new TGLayoutHints(kLHintsRight, 2, 2, 2, 0)); + f1->AddFrame(comp1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 0, 0)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 0, 0)); // Fraction by weight - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); fChkFraction = new TGCheckButton(f1, "% weight"); fChkFraction->SetDown(kTRUE); - f1->AddFrame(fChkFraction, new TGLayoutHints(kLHintsLeft , 2, 2, 6, 1)); + f1->AddFrame(fChkFraction, new TGLayoutHints(kLHintsLeft, 2, 2, 6, 1)); fNEFraction = new TGNumberEntry(f1, 0., 5, kMIX_FRAC, TGNumberFormat::kNESRealThree); fNEFraction->SetFormat(TGNumberFormat::kNESRealThree, TGNumberFormat::kNEANonNegative); fNEFraction->Resize(65, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fNEFraction->GetNumberEntry(); + nef = (TGTextEntry *)fNEFraction->GetNumberEntry(); nef->SetToolTipText("Enter fraction by weight of this element"); fNEFraction->SetNumber(0.); fNEFraction->Associate(this); f1->AddFrame(fNEFraction, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Fraction by number of atoms - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); fChkNatoms = new TGCheckButton(f1, "N. atoms"); fChkNatoms->SetDown(kFALSE); f1->AddFrame(fChkNatoms, new TGLayoutHints(kLHintsLeft, 2, 2, 6, 1)); fNENatoms = new TGNumberEntry(f1, 0., 5, kMIX_NATOMS); fNENatoms->SetFormat(TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative); fNENatoms->Resize(65, fMaterialName->GetDefaultHeight()); - nef = (TGTextEntry*)fNENatoms->GetNumberEntry(); + nef = (TGTextEntry *)fNENatoms->GetNumberEntry(); nef->SetToolTipText("Enter number of atoms for this element"); fNENatoms->SetNumber(0); fNENatoms->Associate(this); f1->AddFrame(fNENatoms, new TGLayoutHints(kLHintsRight, 2, 2, 1, 1)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Button for adding the element fBAddElem = new TGTextButton(compxyz, "Add component"); fBAddElem->Associate(this); - compxyz->AddFrame(fBAddElem, new TGLayoutHints(kLHintsRight , 2, 2, 2, 0)); + compxyz->AddFrame(fBAddElem, new TGLayoutHints(kLHintsRight, 2, 2, 2, 0)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 0, 0, 1, 1)); // List view with all components @@ -503,14 +498,14 @@ void TGeoMixtureEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected mixture. -void TGeoMixtureEditor::SetModel(TObject* obj) +void TGeoMixtureEditor::SetModel(TObject *obj) { if (obj == 0 || !(obj->InheritsFrom(TGeoMixture::Class()))) { SetActive(kFALSE); return; } TGeoMaterialEditor::SetModel(obj); - fMixture = (TGeoMixture*)fMaterial; + fMixture = (TGeoMixture *)fMaterial; UpdateElements(); } @@ -547,7 +542,8 @@ void TGeoMixtureEditor::DoChkNatoms() void TGeoMixtureEditor::DoFraction() { - if (fMixture->GetNelements() && fMixture->GetNmixt()) return; + if (fMixture->GetNelements() && fMixture->GetNmixt()) + return; fChkFraction->SetDown(kTRUE); fChkNatoms->SetDown(kFALSE); } @@ -557,7 +553,8 @@ void TGeoMixtureEditor::DoFraction() void TGeoMixtureEditor::DoNatoms() { - if (fMixture->GetNelements() && !fMixture->GetNmixt()) return; + if (fMixture->GetNelements() && !fMixture->GetNmixt()) + return; fChkFraction->SetDown(kFALSE); fChkNatoms->SetDown(kTRUE); } @@ -572,8 +569,8 @@ void TGeoMixtureEditor::DoSelectElement(Int_t ielem) Error("DoSelectElement", "No element at index %d", ielem); return; } - TString z = TString::Format("Z=%d",el->Z()); - TString a = TString::Format("A=%d",(Int_t)el->A()); + TString z = TString::Format("Z=%d", el->Z()); + TString a = TString::Format("A=%d", (Int_t)el->A()); fAelem->SetText(a.Data()); fZelem->SetText(z.Data()); } @@ -585,13 +582,18 @@ void TGeoMixtureEditor::DoAddElem() { Bool_t byfraction = fChkFraction->IsDown(); Int_t natoms = (Int_t)fNENatoms->GetNumber(); - if (!byfraction && natoms<=0) return; + if (!byfraction && natoms <= 0) + return; Double_t frac = fNEFraction->GetNumber(); - if (byfraction && frac<=0) return; + if (byfraction && frac <= 0) + return; TGeoElement *el = gGeoManager->GetElementTable()->GetElement(fMixElem->GetSelected()); - if (!el) return; - if (byfraction) fMixture->AddElement(el, frac); - else fMixture->AddElement(el, natoms); + if (!el) + return; + if (byfraction) + fMixture->AddElement(el, frac); + else + fMixture->AddElement(el, natoms); fTabMgr->GetMaterialEditor(fMixture); } @@ -605,9 +607,9 @@ void TGeoMixtureEditor::DoApply1() fMaterial->SetDensity(fMatDensity->GetNumber()); fMaterial->SetTemperature(fMatTemperature->GetNumber()); - fMaterial->SetPressure(6.2415e+8*fMatPressure->GetNumber()); + fMaterial->SetPressure(6.2415e+8 * fMatPressure->GetNumber()); fMaterial->SetState((TGeoMaterial::EGeoMaterialState)fMatState->GetSelected()); -// fMaterial->SetRadLen(fMatRadLen->GetNumber(), fMatAbsLen->GetNumber()); + // fMaterial->SetRadLen(fMatRadLen->GetNumber(), fMatAbsLen->GetNumber()); fMatRadLen->SetNumber(fMaterial->GetRadLen()); fMatAbsLen->SetNumber(fMaterial->GetIntLen()); fUndo->SetEnabled(); @@ -628,7 +630,7 @@ void TGeoMixtureEditor::DoUndo1() fMatTemperature->SetNumber(fTempi); fMaterial->SetTemperature(fTempi); fMatPressure->SetNumber(fPresi); - fMaterial->SetPressure(fPresi*6.2415e+8); + fMaterial->SetPressure(fPresi * 6.2415e+8); fMatRadLen->SetNumber(fMaterial->GetRadLen()); fMatAbsLen->SetNumber(fMaterial->GetIntLen()); fApply->SetEnabled(kFALSE); @@ -642,15 +644,15 @@ void TGeoMixtureEditor::UpdateElements() { fComps->RemoveAll(); Int_t nelem = fMixture->GetNelements(); - for (Int_t i=0; iGetNmixt())?kFALSE:kTRUE; + Bool_t byfrac = (fMixture->GetNmixt()) ? kFALSE : kTRUE; if (byfrac) - s.TString::Format("%d-%s-%d: Wmass = %g %%", (Int_t)fMixture->GetZmixt()[i], fMixture->GetElement(i)->GetName(), - (Int_t)fMixture->GetAmixt()[i],fMixture->GetWmixt()[i]); + s.TString::Format("%d-%s-%d: Wmass = %g %%", (Int_t)fMixture->GetZmixt()[i], + fMixture->GetElement(i)->GetName(), (Int_t)fMixture->GetAmixt()[i], fMixture->GetWmixt()[i]); else s.TString::Format("%d-%s-%d: Natoms = %d", (Int_t)fMixture->GetZmixt()[i], fMixture->GetElement(i)->GetName(), - (Int_t)fMixture->GetAmixt()[i],fMixture->GetNmixt()[i]); + (Int_t)fMixture->GetAmixt()[i], fMixture->GetNmixt()[i]); TGLabel *label = new TGLabel(fComps, s); label->SetTextJustify(kTextLeft | kTextCenterY); diff --git a/geom/geombuilder/src/TGeoMatrixEditor.cxx b/geom/geombuilder/src/TGeoMatrixEditor.cxx index d70df63b46d0b..bd071f0e58b91 100644 --- a/geom/geombuilder/src/TGeoMatrixEditor.cxx +++ b/geom/geombuilder/src/TGeoMatrixEditor.cxx @@ -29,19 +29,25 @@ Editor for a TGeoTranslation. ClassImp(TGeoTranslationEditor); enum ETGeoMatrixWid { - kMATRIX_NAME, kMATRIX_DX, kMATRIX_DY, kMATRIX_DZ, - kMATRIX_PHI, kMATRIX_THETA, kMATRIX_PSI, - kMATRIX_APPLY, kMATRIX_CANCEL, kMATRIX_UNDO + kMATRIX_NAME, + kMATRIX_DX, + kMATRIX_DY, + kMATRIX_DZ, + kMATRIX_PHI, + kMATRIX_THETA, + kMATRIX_PSI, + kMATRIX_APPLY, + kMATRIX_CANCEL, + kMATRIX_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for translation editor -TGeoTranslationEditor::TGeoTranslationEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTranslationEditor::TGeoTranslationEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fTranslation = 0; + fTranslation = 0; fDxi = fDyi = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -59,39 +65,39 @@ TGeoTranslationEditor::TGeoTranslationEditor(const TGWindow *p, Int_t width, MakeTitle("Translations on axes"); TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for dx - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDx = new TGNumberEntry(f1, 0., 5, kMATRIX_DX); - nef = (TGTextEntry*)fTransDx->GetNumberEntry(); + nef = (TGTextEntry *)fTransDx->GetNumberEntry(); nef->SetToolTipText("Enter the translation on X"); fTransDx->Associate(this); - f1->AddFrame(fTransDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fTransDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for dy - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDy = new TGNumberEntry(f2, 0., 5, kMATRIX_DY); - nef = (TGTextEntry*)fTransDy->GetNumberEntry(); + nef = (TGTextEntry *)fTransDy->GetNumberEntry(); nef->SetToolTipText("Enter the translation on Y"); fTransDy->Associate(this); - f2->AddFrame(fTransDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f2->AddFrame(fTransDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for dx - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDz = new TGNumberEntry(f3, 0., 5, kMATRIX_DZ); - nef = (TGTextEntry*)fTransDz->GetNumberEntry(); + nef = (TGTextEntry *)fTransDz->GetNumberEntry(); nef->SetToolTipText("Enter the translation on Z"); fTransDz->Associate(this); - f3->AddFrame(fTransDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f3->AddFrame(fTransDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); // Buttons @@ -103,9 +109,9 @@ TGeoTranslationEditor::TGeoTranslationEditor(const TGWindow *p, Int_t width, f23->AddFrame(fCancel, new TGLayoutHints(kLHintsCenterX, 2, 2, 4, 4)); fCancel->Associate(this); fUndo = new TGTextButton(f23, " &Undo "); - f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); + AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); fUndo->SetSize(fCancel->GetSize()); fApply->SetSize(fCancel->GetSize()); } @@ -119,7 +125,7 @@ TGeoTranslationEditor::~TGeoTranslationEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -142,22 +148,22 @@ void TGeoTranslationEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the new matrix. -void TGeoTranslationEditor::SetModel(TObject* obj) +void TGeoTranslationEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTranslation::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTranslation::Class())) { SetActive(kFALSE); return; } - fTranslation = (TGeoTranslation*)obj; + fTranslation = (TGeoTranslation *)obj; fDxi = fTranslation->GetTranslation()[0]; fDyi = fTranslation->GetTranslation()[1]; fDzi = fTranslation->GetTranslation()[2]; const char *sname = fTranslation->GetName(); - if (!strcmp(sname, fTranslation->ClassName())) fTransName->SetText("no_name"); + if (!strcmp(sname, fTranslation->ClassName())) + fTransName->SetText("no_name"); else { fTransName->SetText(sname); fNamei = sname; @@ -169,7 +175,8 @@ void TGeoTranslationEditor::SetModel(TObject* obj) fUndo->SetEnabled(kFALSE); fCancel->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -179,7 +186,8 @@ void TGeoTranslationEditor::SetModel(TObject* obj) void TGeoTranslationEditor::DoName() { const char *name = fTransName->GetText(); - if (!strcmp(name, "no_name") || !strcmp(name, fTranslation->GetName())) return; + if (!strcmp(name, "no_name") || !strcmp(name, fTranslation->GetName())) + return; fTranslation->SetName(name); } @@ -192,10 +200,11 @@ Bool_t TGeoTranslationEditor::DoParameters() Double_t dy = fTransDy->GetNumber(); Double_t dz = fTransDz->GetNumber(); Bool_t changed = kFALSE; - if (dx != fTranslation->GetTranslation()[0] || - dy != fTranslation->GetTranslation()[1] || - dz != fTranslation->GetTranslation()[2]) changed = kTRUE; - if (!changed) return kFALSE; + if (dx != fTranslation->GetTranslation()[0] || dy != fTranslation->GetTranslation()[1] || + dz != fTranslation->GetTranslation()[2]) + changed = kTRUE; + if (!changed) + return kFALSE; fUndo->SetEnabled(); fTranslation->SetTranslation(dx, dy, dz); if (fPad) { @@ -223,8 +232,10 @@ void TGeoTranslationEditor::DoApply() void TGeoTranslationEditor::DoCancel() { - if (!fNamei.Length()) fTransName->SetText("no_name"); - else fTransName->SetText(fNamei.Data()); + if (!fNamei.Length()) + fTransName->SetText("no_name"); + else + fTransName->SetText(fNamei.Data()); fTransDx->SetNumber(fDxi); fTransDy->SetNumber(fDyi); fTransDz->SetNumber(fDzi); @@ -239,7 +250,8 @@ void TGeoTranslationEditor::DoCancel() void TGeoTranslationEditor::DoModified() { fApply->SetEnabled(); - if (fUndo->GetState()==kButtonDisabled) fCancel->SetEnabled(); + if (fUndo->GetState() == kButtonDisabled) + fCancel->SetEnabled(); } //////////////////////////////////////////////////////////////////////////////// @@ -290,11 +302,10 @@ ClassImp(TGeoRotationEditor); //////////////////////////////////////////////////////////////////////////////// /// Constructor for rotation editor -TGeoRotationEditor::TGeoRotationEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoRotationEditor::TGeoRotationEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fRotation = 0; + fRotation = 0; fPhii = fThetai = fPsii = 0.0; fAngleX = fAngleY = fAngleZ = 0.0; fNamei = ""; @@ -313,57 +324,56 @@ TGeoRotationEditor::TGeoRotationEditor(const TGWindow *p, Int_t width, MakeTitle("Euler angles"); TGCompositeFrame *compxyz = new TGCompositeFrame(this, 140, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for phi angle - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, " PHI "), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotPhi = new TGNumberEntry(f1, 0., 5, kMATRIX_PHI); - nef = (TGTextEntry*)fRotPhi->GetNumberEntry(); + nef = (TGTextEntry *)fRotPhi->GetNumberEntry(); nef->SetToolTipText("Modify the first rotation angle about Z"); fRotPhi->Associate(this); fRotPhi->Resize(90, fRotPhi->GetDefaultHeight()); - f1->AddFrame(fRotPhi, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fRotPhi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for theta angle - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "THETA"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotTheta = new TGNumberEntry(f2, 0., 5, kMATRIX_THETA); - nef = (TGTextEntry*)fRotTheta->GetNumberEntry(); + nef = (TGTextEntry *)fRotTheta->GetNumberEntry(); nef->SetToolTipText("Modify the second rotation angle about the new X"); fRotTheta->Associate(this); fRotTheta->Resize(90, fRotTheta->GetDefaultHeight()); - f2->AddFrame(fRotTheta, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f2->AddFrame(fRotTheta, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for psi angle - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, " PSI "), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotPsi = new TGNumberEntry(f3, 0., 5, kMATRIX_PSI); - nef = (TGTextEntry*)fRotPsi->GetNumberEntry(); + nef = (TGTextEntry *)fRotPsi->GetNumberEntry(); nef->SetToolTipText("Modify the third rotation angle about Z"); fRotPsi->Associate(this); fRotPsi->Resize(90, fRotPsi->GetDefaultHeight()); - f3->AddFrame(fRotPsi, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f3->AddFrame(fRotPsi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,compxyz->GetDefaultHeight()); + compxyz->Resize(150, compxyz->GetDefaultHeight()); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); MakeTitle("Rotate about axis"); compxyz = new TGCompositeFrame(this, 140, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for rotation angle about one axis - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "ANGLE"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotAxis = new TGNumberEntry(f1, 0., 5, kMATRIX_DX); - nef = (TGTextEntry*)fRotAxis->GetNumberEntry(); + nef = (TGTextEntry *)fRotAxis->GetNumberEntry(); nef->SetToolTipText("Enter the new rotation angle about the selected axis"); fRotAxis->Associate(this); fRotAxis->Resize(90, fRotAxis->GetDefaultHeight()); - f1->AddFrame(fRotAxis, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fRotAxis, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Radio buttons group for axis selection TGHButtonGroup *bg1 = new TGHButtonGroup(compxyz, " Axis "); @@ -372,12 +382,11 @@ TGeoRotationEditor::TGeoRotationEditor(const TGWindow *p, Int_t width, fRotZ = new TGRadioButton(bg1, " &Z ", kMATRIX_DZ); bg1->SetRadioButtonExclusive(); bg1->Show(); - compxyz->AddFrame(bg1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + compxyz->AddFrame(bg1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,compxyz->GetDefaultHeight()); + compxyz->Resize(150, compxyz->GetDefaultHeight()); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); - // Buttons TGCompositeFrame *f23 = new TGCompositeFrame(this, 118, 20, kHorizontalFrame | kSunkenFrame | kDoubleBorder); fApply = new TGTextButton(f23, "Apply"); @@ -387,9 +396,9 @@ TGeoRotationEditor::TGeoRotationEditor(const TGWindow *p, Int_t width, f23->AddFrame(fCancel, new TGLayoutHints(kLHintsCenterX, 2, 2, 4, 4)); fCancel->Associate(this); fUndo = new TGTextButton(f23, " Undo "); - f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); + AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); fUndo->SetSize(fCancel->GetSize()); fApply->SetSize(fCancel->GetSize()); } @@ -403,7 +412,7 @@ TGeoRotationEditor::~TGeoRotationEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -424,20 +433,20 @@ void TGeoRotationEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected rotation. -void TGeoRotationEditor::SetModel(TObject* obj) +void TGeoRotationEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoRotation::Class())) { + if (obj == 0 || (obj->IsA() != TGeoRotation::Class())) { SetActive(kFALSE); return; } - fRotation = (TGeoRotation*)obj; + fRotation = (TGeoRotation *)obj; fRotation->GetAngles(fPhii, fThetai, fPsii); const char *sname = fRotation->GetName(); - if (!strcmp(sname, fRotation->ClassName())) fRotName->SetText("no_name"); + if (!strcmp(sname, fRotation->ClassName())) + fRotName->SetText("no_name"); else { fRotName->SetText(sname); fNamei = sname; @@ -451,7 +460,8 @@ void TGeoRotationEditor::SetModel(TObject* obj) fUndo->SetEnabled(kFALSE); fCancel->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -461,7 +471,8 @@ void TGeoRotationEditor::SetModel(TObject* obj) void TGeoRotationEditor::DoName() { const char *name = fRotName->GetText(); - if (!strcmp(name, "no_name") || !strcmp(name, fRotation->GetName())) return; + if (!strcmp(name, "no_name") || !strcmp(name, fRotation->GetName())) + return; fRotation->SetName(name); } @@ -470,8 +481,10 @@ void TGeoRotationEditor::DoName() void TGeoRotationEditor::DoRotPhi() { - if (fRotPhi->GetNumber() < 0.) fRotPhi->SetNumber(fRotPhi->GetNumber()+360.); - if (fRotPhi->GetNumber() >= 360.) fRotPhi->SetNumber(fRotPhi->GetNumber()-360.); + if (fRotPhi->GetNumber() < 0.) + fRotPhi->SetNumber(fRotPhi->GetNumber() + 360.); + if (fRotPhi->GetNumber() >= 360.) + fRotPhi->SetNumber(fRotPhi->GetNumber() - 360.); DoModified(); } @@ -480,8 +493,10 @@ void TGeoRotationEditor::DoRotPhi() void TGeoRotationEditor::DoRotTheta() { - if (fRotTheta->GetNumber() < 0.) fRotTheta->SetNumber(fRotTheta->GetNumber()+360.); - if (fRotTheta->GetNumber() >= 360.) fRotTheta->SetNumber(fRotTheta->GetNumber()-360.); + if (fRotTheta->GetNumber() < 0.) + fRotTheta->SetNumber(fRotTheta->GetNumber() + 360.); + if (fRotTheta->GetNumber() >= 360.) + fRotTheta->SetNumber(fRotTheta->GetNumber() - 360.); DoModified(); } @@ -490,8 +505,10 @@ void TGeoRotationEditor::DoRotTheta() void TGeoRotationEditor::DoRotPsi() { - if (fRotPsi->GetNumber() < 0.) fRotPsi->SetNumber(fRotPsi->GetNumber()+360.); - if (fRotPsi->GetNumber() >= 360.) fRotPsi->SetNumber(fRotPsi->GetNumber()-360.); + if (fRotPsi->GetNumber() < 0.) + fRotPsi->SetNumber(fRotPsi->GetNumber() + 360.); + if (fRotPsi->GetNumber() >= 360.) + fRotPsi->SetNumber(fRotPsi->GetNumber() - 360.); DoModified(); } @@ -500,8 +517,10 @@ void TGeoRotationEditor::DoRotPsi() void TGeoRotationEditor::DoRotAngle() { - if (fRotAxis->GetNumber() < 0.) fRotAxis->SetNumber(fRotAxis->GetNumber()+360.); - if (fRotAxis->GetNumber() >= 360.) fRotAxis->SetNumber(fRotAxis->GetNumber()-360.); + if (fRotAxis->GetNumber() < 0.) + fRotAxis->SetNumber(fRotAxis->GetNumber() + 360.); + if (fRotAxis->GetNumber() >= 360.) + fRotAxis->SetNumber(fRotAxis->GetNumber() - 360.); DoModified(); } @@ -515,17 +534,29 @@ Bool_t TGeoRotationEditor::DoParameters() Double_t psi = fRotPsi->GetNumber(); Double_t angle = fRotAxis->GetNumber(); Double_t phi0 = 0., theta0 = 0., psi0 = 0.; - fRotation->GetAngles(phi0,theta0,psi0); + fRotation->GetAngles(phi0, theta0, psi0); Bool_t changed = kFALSE; - if (phi != psi0 || theta != theta0 || psi != psi0) changed = kTRUE; - if (changed) fRotation->SetAngles(phi, theta, psi); + if (phi != psi0 || theta != theta0 || psi != psi0) + changed = kTRUE; + if (changed) + fRotation->SetAngles(phi, theta, psi); // Check if we have to rotate about one axis if (angle != 0.0) { - if (fRotX->IsOn()) {fRotation->RotateX(angle); changed = kTRUE;} - if (fRotY->IsOn()) {fRotation->RotateY(angle); changed = kTRUE;} - if (fRotZ->IsOn()) {fRotation->RotateZ(angle); changed = kTRUE;} + if (fRotX->IsOn()) { + fRotation->RotateX(angle); + changed = kTRUE; + } + if (fRotY->IsOn()) { + fRotation->RotateY(angle); + changed = kTRUE; + } + if (fRotZ->IsOn()) { + fRotation->RotateZ(angle); + changed = kTRUE; + } } - if (!changed) return kFALSE; + if (!changed) + return kFALSE; fRotAxis->SetNumber(0.0); fUndo->SetEnabled(); if (fPad) { @@ -553,8 +584,10 @@ void TGeoRotationEditor::DoApply() void TGeoRotationEditor::DoCancel() { - if (!fNamei.Length()) fRotName->SetText("no_name"); - else fRotName->SetText(fNamei.Data()); + if (!fNamei.Length()) + fRotName->SetText("no_name"); + else + fRotName->SetText(fNamei.Data()); fRotPhi->SetNumber(fPhii); fRotTheta->SetNumber(fThetai); fRotPsi->SetNumber(fPsii); @@ -570,7 +603,8 @@ void TGeoRotationEditor::DoCancel() void TGeoRotationEditor::DoModified() { fApply->SetEnabled(); - if (fUndo->GetState()==kButtonDisabled) fCancel->SetEnabled(); + if (fUndo->GetState() == kButtonDisabled) + fCancel->SetEnabled(); } //////////////////////////////////////////////////////////////////////////////// @@ -597,11 +631,10 @@ ClassImp(TGeoCombiTransEditor); //////////////////////////////////////////////////////////////////////////////// /// Constructor for combi matrix editor -TGeoCombiTransEditor::TGeoCombiTransEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoCombiTransEditor::TGeoCombiTransEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fCombi = 0; + fCombi = 0; fPhii = fThetai = fPsii = 0.0; fDxi = fDyi = fDzi = 0.0; fAngleX = fAngleY = fAngleZ = 0.0; @@ -621,96 +654,91 @@ TGeoCombiTransEditor::TGeoCombiTransEditor(const TGWindow *p, Int_t width, MakeTitle("Translations on axes"); TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for dx - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDx = new TGNumberEntry(f1, 0., 5, kMATRIX_DX); - nef = (TGTextEntry*)fTransDx->GetNumberEntry(); + nef = (TGTextEntry *)fTransDx->GetNumberEntry(); nef->SetToolTipText("Enter the translation on X"); fTransDx->Associate(this); - f1->AddFrame(fTransDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fTransDx, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for dy - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDy = new TGNumberEntry(f2, 0., 5, kMATRIX_DY); - nef = (TGTextEntry*)fTransDy->GetNumberEntry(); + nef = (TGTextEntry *)fTransDy->GetNumberEntry(); nef->SetToolTipText("Enter the translation on Y"); fTransDy->Associate(this); - f2->AddFrame(fTransDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f2->AddFrame(fTransDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for dx - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fTransDz = new TGNumberEntry(f3, 0., 5, kMATRIX_DZ); - nef = (TGTextEntry*)fTransDz->GetNumberEntry(); + nef = (TGTextEntry *)fTransDz->GetNumberEntry(); nef->SetToolTipText("Enter the translation on Z"); fTransDz->Associate(this); - f3->AddFrame(fTransDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f3->AddFrame(fTransDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); - MakeTitle("Euler angles"); compxyz = new TGCompositeFrame(this, 140, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for phi angle - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, " PHI "), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotPhi = new TGNumberEntry(f1, 0., 5, kMATRIX_PHI); - nef = (TGTextEntry*)fRotPhi->GetNumberEntry(); + nef = (TGTextEntry *)fRotPhi->GetNumberEntry(); nef->SetToolTipText("Modify the first rotation angle about Z"); fRotPhi->Associate(this); fRotPhi->Resize(90, fRotPhi->GetDefaultHeight()); - f1->AddFrame(fRotPhi, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fRotPhi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for theta angle - f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "THETA"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotTheta = new TGNumberEntry(f2, 0., 5, kMATRIX_THETA); - nef = (TGTextEntry*)fRotTheta->GetNumberEntry(); + nef = (TGTextEntry *)fRotTheta->GetNumberEntry(); nef->SetToolTipText("Modify the second rotation angle about the new X"); fRotTheta->Associate(this); fRotTheta->Resize(90, fRotTheta->GetDefaultHeight()); - f2->AddFrame(fRotTheta, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f2->AddFrame(fRotTheta, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Number entry for psi angle - f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, " PSI "), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotPsi = new TGNumberEntry(f3, 0., 5, kMATRIX_PSI); - nef = (TGTextEntry*)fRotPsi->GetNumberEntry(); + nef = (TGTextEntry *)fRotPsi->GetNumberEntry(); nef->SetToolTipText("Modify the third rotation angle about Z"); fRotPsi->Associate(this); fRotPsi->Resize(90, fRotPsi->GetDefaultHeight()); - f3->AddFrame(fRotPsi, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f3->AddFrame(fRotPsi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,compxyz->GetDefaultHeight()); + compxyz->Resize(150, compxyz->GetDefaultHeight()); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); MakeTitle("Rotate about axis"); compxyz = new TGCompositeFrame(this, 140, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for rotation angle about one axis - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "ANGLE"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fRotAxis = new TGNumberEntry(f1, 0., 5, kMATRIX_DX); - nef = (TGTextEntry*)fRotAxis->GetNumberEntry(); + nef = (TGTextEntry *)fRotAxis->GetNumberEntry(); nef->SetToolTipText("Enter the new rotation angle about the selected axis"); fRotAxis->Associate(this); fRotAxis->Resize(90, fRotAxis->GetDefaultHeight()); - f1->AddFrame(fRotAxis, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + f1->AddFrame(fRotAxis, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); // Radio buttons group for axis selection TGHButtonGroup *bg1 = new TGHButtonGroup(compxyz, " Axis "); @@ -719,12 +747,11 @@ TGeoCombiTransEditor::TGeoCombiTransEditor(const TGWindow *p, Int_t width, fRotZ = new TGRadioButton(bg1, " &Z ", kMATRIX_DZ); bg1->SetRadioButtonExclusive(); bg1->Show(); - compxyz->AddFrame(bg1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 2, 2)); + compxyz->AddFrame(bg1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); - compxyz->Resize(150,compxyz->GetDefaultHeight()); + compxyz->Resize(150, compxyz->GetDefaultHeight()); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); - // Buttons TGCompositeFrame *f23 = new TGCompositeFrame(this, 118, 20, kHorizontalFrame | kSunkenFrame | kDoubleBorder); fApply = new TGTextButton(f23, "&Apply"); @@ -734,9 +761,9 @@ TGeoCombiTransEditor::TGeoCombiTransEditor(const TGWindow *p, Int_t width, f23->AddFrame(fCancel, new TGLayoutHints(kLHintsCenterX, 2, 2, 4, 4)); fCancel->Associate(this); fUndo = new TGTextButton(f23, " &Undo "); - f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); + AddFrame(f23, new TGLayoutHints(kLHintsLeft, 6, 6, 2, 2)); fUndo->SetSize(fCancel->GetSize()); fApply->SetSize(fCancel->GetSize()); } @@ -750,7 +777,7 @@ TGeoCombiTransEditor::~TGeoCombiTransEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -777,21 +804,22 @@ void TGeoCombiTransEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected combi matrix. -void TGeoCombiTransEditor::SetModel(TObject* obj) +void TGeoCombiTransEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoCombiTrans::Class())) { + if (obj == 0 || (obj->IsA() != TGeoCombiTrans::Class())) { SetActive(kFALSE); return; } - fCombi = (TGeoCombiTrans*)obj; + fCombi = (TGeoCombiTrans *)obj; TGeoRotation *rot = fCombi->GetRotation(); - if (rot) rot->GetAngles(fPhii, fThetai, fPsii); + if (rot) + rot->GetAngles(fPhii, fThetai, fPsii); const char *sname = fCombi->GetName(); - if (!strcmp(sname, fCombi->ClassName())) fRotName->SetText("no_name"); + if (!strcmp(sname, fCombi->ClassName())) + fRotName->SetText("no_name"); else { fRotName->SetText(sname); fNamei = sname; @@ -813,7 +841,8 @@ void TGeoCombiTransEditor::SetModel(TObject* obj) fUndo->SetEnabled(kFALSE); fCancel->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -823,7 +852,8 @@ void TGeoCombiTransEditor::SetModel(TObject* obj) void TGeoCombiTransEditor::DoName() { const char *name = fRotName->GetText(); - if (!strcmp(name, "no_name") || !strcmp(name, fCombi->GetName())) return; + if (!strcmp(name, "no_name") || !strcmp(name, fCombi->GetName())) + return; fCombi->SetName(name); } @@ -832,8 +862,10 @@ void TGeoCombiTransEditor::DoName() void TGeoCombiTransEditor::DoRotPhi() { - if (fRotPhi->GetNumber() < 0.) fRotPhi->SetNumber(fRotPhi->GetNumber()+360.); - if (fRotPhi->GetNumber() >= 360.) fRotPhi->SetNumber(fRotPhi->GetNumber()-360.); + if (fRotPhi->GetNumber() < 0.) + fRotPhi->SetNumber(fRotPhi->GetNumber() + 360.); + if (fRotPhi->GetNumber() >= 360.) + fRotPhi->SetNumber(fRotPhi->GetNumber() - 360.); DoModified(); } @@ -842,8 +874,10 @@ void TGeoCombiTransEditor::DoRotPhi() void TGeoCombiTransEditor::DoRotTheta() { - if (fRotTheta->GetNumber() < 0.) fRotTheta->SetNumber(fRotTheta->GetNumber()+360.); - if (fRotTheta->GetNumber() >= 360.) fRotTheta->SetNumber(fRotTheta->GetNumber()-360.); + if (fRotTheta->GetNumber() < 0.) + fRotTheta->SetNumber(fRotTheta->GetNumber() + 360.); + if (fRotTheta->GetNumber() >= 360.) + fRotTheta->SetNumber(fRotTheta->GetNumber() - 360.); DoModified(); } @@ -852,8 +886,10 @@ void TGeoCombiTransEditor::DoRotTheta() void TGeoCombiTransEditor::DoRotPsi() { - if (fRotPsi->GetNumber() < 0.) fRotPsi->SetNumber(fRotPsi->GetNumber()+360.); - if (fRotPsi->GetNumber() >= 360.) fRotPsi->SetNumber(fRotPsi->GetNumber()-360.); + if (fRotPsi->GetNumber() < 0.) + fRotPsi->SetNumber(fRotPsi->GetNumber() + 360.); + if (fRotPsi->GetNumber() >= 360.) + fRotPsi->SetNumber(fRotPsi->GetNumber() - 360.); DoModified(); } @@ -862,8 +898,10 @@ void TGeoCombiTransEditor::DoRotPsi() void TGeoCombiTransEditor::DoRotAngle() { - if (fRotAxis->GetNumber() < 0.) fRotAxis->SetNumber(fRotAxis->GetNumber()+360.); - if (fRotAxis->GetNumber() >= 360.) fRotAxis->SetNumber(fRotAxis->GetNumber()-360.); + if (fRotAxis->GetNumber() < 0.) + fRotAxis->SetNumber(fRotAxis->GetNumber() + 360.); + if (fRotAxis->GetNumber() >= 360.) + fRotAxis->SetNumber(fRotAxis->GetNumber() - 360.); DoModified(); } @@ -876,36 +914,50 @@ Bool_t TGeoCombiTransEditor::DoParameters() Double_t dy = fTransDy->GetNumber(); Double_t dz = fTransDz->GetNumber(); Bool_t changedtr = kFALSE; - if (dx != fCombi->GetTranslation()[0] || - dy != fCombi->GetTranslation()[1] || - dz != fCombi->GetTranslation()[2]) changedtr = kTRUE; - if (changedtr) fCombi->SetTranslation(dx, dy, dz); + if (dx != fCombi->GetTranslation()[0] || dy != fCombi->GetTranslation()[1] || dz != fCombi->GetTranslation()[2]) + changedtr = kTRUE; + if (changedtr) + fCombi->SetTranslation(dx, dy, dz); Double_t phi = fRotPhi->GetNumber(); Double_t theta = fRotTheta->GetNumber(); Double_t psi = fRotPsi->GetNumber(); Double_t angle = fRotAxis->GetNumber(); Double_t phi0 = 0., theta0 = 0., psi0 = 0.; TGeoRotation *rot = fCombi->GetRotation(); - if (rot) rot->GetAngles(phi0,theta0,psi0); + if (rot) + rot->GetAngles(phi0, theta0, psi0); else { - if (phi!=fPhii || theta!=fThetai || psi!=fPsii) { - TGeoRotation r("rot",10.,0.,0.); + if (phi != fPhii || theta != fThetai || psi != fPsii) { + TGeoRotation r("rot", 10., 0., 0.); fCombi->SetRotation(r); rot = fCombi->GetRotation(); - rot->SetAngles(0.,0.,0.); + rot->SetAngles(0., 0., 0.); } } Bool_t changed = kFALSE; - if (phi != psi0 || theta != theta0 || psi != psi0) changed = kTRUE; - if (changed && rot) rot->SetAngles(phi, theta, psi); + if (phi != psi0 || theta != theta0 || psi != psi0) + changed = kTRUE; + if (changed && rot) + rot->SetAngles(phi, theta, psi); // Check if we have to rotate about one axis if (angle != 0.0) { - if (fRotX->IsOn()) {fCombi->RotateX(angle); changed = kTRUE;} - if (fRotY->IsOn()) {fCombi->RotateY(angle); changed = kTRUE;} - if (fRotZ->IsOn()) {fCombi->RotateZ(angle); changed = kTRUE;} + if (fRotX->IsOn()) { + fCombi->RotateX(angle); + changed = kTRUE; + } + if (fRotY->IsOn()) { + fCombi->RotateY(angle); + changed = kTRUE; + } + if (fRotZ->IsOn()) { + fCombi->RotateZ(angle); + changed = kTRUE; + } } - if (changedtr) changed = kTRUE; - if (!changed) return kFALSE; + if (changedtr) + changed = kTRUE; + if (!changed) + return kFALSE; fRotAxis->SetNumber(0.0); fUndo->SetEnabled(); if (fPad) { @@ -933,8 +985,10 @@ void TGeoCombiTransEditor::DoApply() void TGeoCombiTransEditor::DoCancel() { - if (!fNamei.Length()) fRotName->SetText("no_name"); - else fRotName->SetText(fNamei.Data()); + if (!fNamei.Length()) + fRotName->SetText("no_name"); + else + fRotName->SetText(fNamei.Data()); fTransDx->SetNumber(fDxi); fTransDy->SetNumber(fDyi); fTransDz->SetNumber(fDzi); @@ -953,7 +1007,8 @@ void TGeoCombiTransEditor::DoCancel() void TGeoCombiTransEditor::DoModified() { fApply->SetEnabled(); - if (fUndo->GetState()==kButtonDisabled) fCancel->SetEnabled(); + if (fUndo->GetState() == kButtonDisabled) + fCancel->SetEnabled(); } //////////////////////////////////////////////////////////////////////////////// @@ -991,4 +1046,3 @@ void TGeoCombiTransEditor::DoDz() { DoModified(); } - diff --git a/geom/geombuilder/src/TGeoMediumEditor.cxx b/geom/geombuilder/src/TGeoMediumEditor.cxx index e525b9cdb2946..f48ba89f714fd 100644 --- a/geom/geombuilder/src/TGeoMediumEditor.cxx +++ b/geom/geombuilder/src/TGeoMediumEditor.cxx @@ -32,21 +32,30 @@ Editor class for TGeo tracking media. ClassImp(TGeoMediumEditor); enum ETGeoMediumWid { - kMED_NAME, kMED_ID, kMED_MATSEL, - kMED_SENS, kMED_FLDOPT, kMED_EDIT_MAT, - kMED_FIELDM, kMED_TMAX, kMED_STEMAX, - kMED_DEEMAX, kMED_EPSIL, kMED_STMIN, - kMED_APPLY, kMED_CANCEL, kMED_UNDO + kMED_NAME, + kMED_ID, + kMED_MATSEL, + kMED_SENS, + kMED_FLDOPT, + kMED_EDIT_MAT, + kMED_FIELDM, + kMED_TMAX, + kMED_STEMAX, + kMED_DEEMAX, + kMED_EPSIL, + kMED_STMIN, + kMED_APPLY, + kMED_CANCEL, + kMED_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for medium editor -TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fMedium = 0; + fMedium = 0; fIsEditable = kFALSE; fIsModified = kFALSE; Pixel_t color; @@ -62,11 +71,11 @@ TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, TGTextEntry *nef; -// Composite frame for medium ID and sensitivity + // Composite frame for medium ID and sensitivity TGCompositeFrame *f1 = new TGCompositeFrame(this, 120, 30, kHorizontalFrame | kRaisedFrame); f1->AddFrame(new TGLabel(f1, "ID"), new TGLayoutHints(kLHintsLeft, 4, 1, 6, 0)); fMedId = new TGNumberEntry(f1, 0., 1, kMED_ID); - nef = (TGTextEntry*)fMedId->GetNumberEntry(); + nef = (TGTextEntry *)fMedId->GetNumberEntry(); nef->SetToolTipText("Enter the medium ID"); fMedId->Associate(this); f1->AddFrame(fMedId, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); @@ -99,8 +108,8 @@ TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, fEditMaterial->Associate(this); AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 0, 0)); -// Combo box for magnetic field option - f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + // Combo box for magnetic field option + f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(label = new TGLabel(f1, "Mag. field option"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); gClient->GetColorByName("#ff0000", color); @@ -110,8 +119,7 @@ TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, fMagfldOption->Resize(135, fMedName->GetDefaultHeight()); AddFrame(fMagfldOption, new TGLayoutHints(kLHintsLeft, 3, 1, 2, 2)); - -// Number entries for other settings + // Number entries for other settings f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFixedWidth | kOwnBackground); f1->AddFrame(label = new TGLabel(f1, "Medium cuts"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); @@ -121,78 +129,77 @@ TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, TGCompositeFrame *compxyz = new TGCompositeFrame(this, 130, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for fieldm - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "FIELDM"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedFieldm = new TGNumberEntry(f1, 0., 5, kMED_FIELDM); - nef = (TGTextEntry*)fMedFieldm->GetNumberEntry(); + nef = (TGTextEntry *)fMedFieldm->GetNumberEntry(); nef->SetToolTipText("Maximum magnetic field [kilogauss]"); fMedFieldm->Associate(this); fMedFieldm->Resize(90, fMedFieldm->GetDefaultHeight()); - f1->AddFrame(fMedFieldm, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f1->AddFrame(fMedFieldm, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for tmaxfd - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "TMAXFD"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedTmaxfd = new TGNumberEntry(f2, 0., 5, kMED_TMAX); - nef = (TGTextEntry*)fMedTmaxfd->GetNumberEntry(); + nef = (TGTextEntry *)fMedTmaxfd->GetNumberEntry(); nef->SetToolTipText("Maximum angle per step due to field [deg]"); fMedTmaxfd->Associate(this); fMedTmaxfd->Resize(90, fMedTmaxfd->GetDefaultHeight()); - f2->AddFrame(fMedTmaxfd, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f2->AddFrame(fMedTmaxfd, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for stemax - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "STEMAX"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedStemax = new TGNumberEntry(f3, 0., 5, kMED_STEMAX); - nef = (TGTextEntry*)fMedStemax->GetNumberEntry(); + nef = (TGTextEntry *)fMedStemax->GetNumberEntry(); nef->SetToolTipText("Maximum step allowed [cm]"); fMedStemax->Associate(this); fMedStemax->Resize(90, fMedStemax->GetDefaultHeight()); - f3->AddFrame(fMedStemax, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f3->AddFrame(fMedStemax, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for deemax - TGCompositeFrame *f4 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f4 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f4->AddFrame(new TGLabel(f4, "DEEMAX"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedDeemax = new TGNumberEntry(f4, 0., 5, kMED_DEEMAX); - nef = (TGTextEntry*)fMedDeemax->GetNumberEntry(); + nef = (TGTextEntry *)fMedDeemax->GetNumberEntry(); nef->SetToolTipText("Maximum fraction of energy lost in a step"); fMedDeemax->Associate(this); fMedDeemax->Resize(90, fMedDeemax->GetDefaultHeight()); - f4->AddFrame(fMedDeemax, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f4, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f4->AddFrame(fMedDeemax, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f4, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for epsil - TGCompositeFrame *f5 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f5 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f5->AddFrame(new TGLabel(f5, "EPSIL"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedEpsil = new TGNumberEntry(f5, 0., 5, kMED_EPSIL); - nef = (TGTextEntry*)fMedEpsil->GetNumberEntry(); + nef = (TGTextEntry *)fMedEpsil->GetNumberEntry(); nef->SetToolTipText("Tracking precision [cm]"); fMedEpsil->Associate(this); fMedEpsil->Resize(90, fMedEpsil->GetDefaultHeight()); - f5->AddFrame(fMedEpsil, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f5, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f5->AddFrame(fMedEpsil, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f5, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); // Number entry for stmin - TGCompositeFrame *f6 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f6 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f6->AddFrame(new TGLabel(f6, "STMIN"), new TGLayoutHints(kLHintsLeft, 1, 1, 4, 0)); fMedStmin = new TGNumberEntry(f6, 0., 5, kMED_STMIN); - nef = (TGTextEntry*)fMedStmin->GetNumberEntry(); + nef = (TGTextEntry *)fMedStmin->GetNumberEntry(); nef->SetToolTipText("Minimum step due to continuous processes [cm]"); fMedStmin->Associate(this); fMedStmin->Resize(90, fMedStmin->GetDefaultHeight()); - f6->AddFrame(fMedStmin, new TGLayoutHints(kLHintsRight | kFixedWidth , 2, 2, 2, 2)); - compxyz->AddFrame(f6, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 1, 1)); + f6->AddFrame(fMedStmin, new TGLayoutHints(kLHintsRight | kLHintsExpandY, 2, 2, 2, 2)); + compxyz->AddFrame(f6, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 1, 1)); - compxyz->Resize(160,50); + compxyz->Resize(160, 50); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); // Buttons @@ -201,9 +208,9 @@ TGeoMediumEditor::TGeoMediumEditor(const TGWindow *p, Int_t width, f23->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f23, " &Undo "); - f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f23->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f23, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f23, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); } //////////////////////////////////////////////////////////////////////////////// @@ -214,10 +221,9 @@ TGeoMediumEditor::~TGeoMediumEditor() TGFrameElement *el; TIter next(GetList()); while ((el = (TGFrameElement *)next())) { - if (el->fFrame->IsA() == TGCompositeFrame::Class() || - el->fFrame->IsA() == TGHorizontalFrame::Class() || + if (el->fFrame->IsA() == TGCompositeFrame::Class() || el->fFrame->IsA() == TGHorizontalFrame::Class() || el->fFrame->IsA() == TGVerticalFrame::Class()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -243,27 +249,29 @@ void TGeoMediumEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoMediumEditor::SetModel(TObject* obj) +void TGeoMediumEditor::SetModel(TObject *obj) { - if (obj == 0 || !(obj->IsA()==TGeoMedium::Class())) { + if (obj == 0 || !(obj->IsA() == TGeoMedium::Class())) { SetActive(kFALSE); return; } - fMedium = (TGeoMedium*)obj; + fMedium = (TGeoMedium *)obj; const char *sname = fMedium->GetName(); - if (!strcmp(sname, fMedium->ClassName())) fMedName->SetText(""); - else fMedName->SetText(sname); + if (!strcmp(sname, fMedium->ClassName())) + fMedName->SetText(""); + else + fMedName->SetText(sname); fMedId->SetNumber(fMedium->GetId()); Int_t isvol = (Int_t)fMedium->GetParam(0); - fMedSensitive->SetState((isvol==0)?kButtonUp:kButtonDown); + fMedSensitive->SetState((isvol == 0) ? kButtonUp : kButtonDown); fSelectedMaterial = fMedium->GetMaterial(); - if (fSelectedMaterial) fLSelMaterial->SetText(fSelectedMaterial->GetName()); + if (fSelectedMaterial) + fLSelMaterial->SetText(fSelectedMaterial->GetName()); if (!fMagfldOption->GetNumberOfEntries()) { fMagfldOption->AddEntry("No field", 0); @@ -275,24 +283,12 @@ void TGeoMediumEditor::SetModel(TObject* obj) } Int_t ifld = (Int_t)fMedium->GetParam(1); switch (ifld) { - case 0: - fMagfldOption->Select(0); - break; - case -1: - fMagfldOption->Select(1); - break; - case 1: - fMagfldOption->Select(2); - break; - case 2: - fMagfldOption->Select(3); - break; - case 3: - fMagfldOption->Select(4); - break; - default: - fMagfldOption->Select(5); - break; + case 0: fMagfldOption->Select(0); break; + case -1: fMagfldOption->Select(1); break; + case 1: fMagfldOption->Select(2); break; + case 2: fMagfldOption->Select(3); break; + case 3: fMagfldOption->Select(4); break; + default: fMagfldOption->Select(5); break; } fMedFieldm->SetNumber(fMedium->GetParam(2)); @@ -305,8 +301,8 @@ void TGeoMediumEditor::SetModel(TObject* obj) fUndo->SetEnabled(kFALSE); fIsModified = kFALSE; - - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -324,16 +320,15 @@ void TGeoMediumEditor::DoEditMaterial() void TGeoMediumEditor::DoMedName() { const char *name = fMedName->GetText(); - if (!name[0] || !strcmp(name, fMedium->GetName())) return; + if (!name[0] || !strcmp(name, fMedium->GetName())) + return; fMedium->SetName(name); } //////////////////////////////////////////////////////////////////////////////// /// Slot for medium id. -void TGeoMediumEditor::DoMedId() -{ -} +void TGeoMediumEditor::DoMedId() {} //////////////////////////////////////////////////////////////////////////////// /// Select the material component. @@ -341,10 +336,12 @@ void TGeoMediumEditor::DoMedId() void TGeoMediumEditor::DoSelectMaterial() { TGeoMaterial *material = fSelectedMaterial; - new TGeoMaterialDialog(fBSelMaterial, gClient->GetRoot(), 200,300); - fSelectedMaterial = (TGeoMaterial*)TGeoMaterialDialog::GetSelected(); - if (fSelectedMaterial) fLSelMaterial->SetText(fSelectedMaterial->GetName()); - else fSelectedMaterial = material; + new TGeoMaterialDialog(fBSelMaterial, gClient->GetRoot(), 200, 300); + fSelectedMaterial = (TGeoMaterial *)TGeoMaterialDialog::GetSelected(); + if (fSelectedMaterial) + fLSelMaterial->SetText(fSelectedMaterial->GetName()); + else + fSelectedMaterial = material; } //////////////////////////////////////////////////////////////////////////////// @@ -416,12 +413,14 @@ void TGeoMediumEditor::DoStmin() void TGeoMediumEditor::DoApply() { - if (!fIsModified) return; - Double_t isvol = (fMedSensitive->IsOn())?1:0; + if (!fIsModified) + return; + Double_t isvol = (fMedSensitive->IsOn()) ? 1 : 0; Double_t ifield = fMagfldOption->GetSelected(); - if (ifield>0) { + if (ifield > 0) { ifield -= 1.; - if (ifield < 1.) ifield -= 1.; + if (ifield < 1.) + ifield -= 1.; } Double_t fieldm = fMedFieldm->GetNumber(); Double_t tmaxfd = fMedTmaxfd->GetNumber(); @@ -430,22 +429,21 @@ void TGeoMediumEditor::DoApply() Double_t epsil = fMedEpsil->GetNumber(); Double_t stmin = fMedStmin->GetNumber(); - fMedium->SetParam(0,isvol); - fMedium->SetParam(1,ifield); - fMedium->SetParam(2,fieldm); - fMedium->SetParam(3,tmaxfd); - fMedium->SetParam(4,stemax); - fMedium->SetParam(5,deemax); - fMedium->SetParam(6,epsil); - fMedium->SetParam(7,stmin); - if (strcmp(fMedium->GetName(), fMedName->GetText())) fMedium->SetName(fMedName->GetText()); - if (fMedium->GetId() != fMedId->GetIntNumber()) fMedium->SetId(fMedId->GetIntNumber()); + fMedium->SetParam(0, isvol); + fMedium->SetParam(1, ifield); + fMedium->SetParam(2, fieldm); + fMedium->SetParam(3, tmaxfd); + fMedium->SetParam(4, stemax); + fMedium->SetParam(5, deemax); + fMedium->SetParam(6, epsil); + fMedium->SetParam(7, stmin); + if (strcmp(fMedium->GetName(), fMedName->GetText())) + fMedium->SetName(fMedName->GetText()); + if (fMedium->GetId() != fMedId->GetIntNumber()) + fMedium->SetId(fMedId->GetIntNumber()); } //////////////////////////////////////////////////////////////////////////////// /// Slot for undoing last operation. -void TGeoMediumEditor::DoUndo() -{ -} - +void TGeoMediumEditor::DoUndo() {} diff --git a/geom/geombuilder/src/TGeoNodeEditor.cxx b/geom/geombuilder/src/TGeoNodeEditor.cxx index d56fa8b44b35c..289736060e74c 100644 --- a/geom/geombuilder/src/TGeoNodeEditor.cxx +++ b/geom/geombuilder/src/TGeoNodeEditor.cxx @@ -31,18 +31,22 @@ Editor class for TGeoNode objects. ClassImp(TGeoNodeEditor); enum ETGeoNodeWid { - kNODE_NAME, kNODE_ID, kNODE_VOLSEL, kNODE_MVOLSEL, - kNODE_MATRIX, kNODE_EDIT_VOL, kNODE_EDIT_MATRIX + kNODE_NAME, + kNODE_ID, + kNODE_VOLSEL, + kNODE_MVOLSEL, + kNODE_MATRIX, + kNODE_EDIT_VOL, + kNODE_EDIT_MATRIX }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for node editor -TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fNode = 0; + fNode = 0; fIsEditable = kTRUE; Pixel_t color; @@ -57,14 +61,13 @@ TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, f1->AddFrame(fNodeName, new TGLayoutHints(kLHintsLeft, 3, 1, 2, 5)); f1->AddFrame(new TGLabel(f1, "ID"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fNodeNumber = new TGNumberEntry(f1, 0., 1, kNODE_ID); - nef = (TGTextEntry*)fNodeNumber->GetNumberEntry(); + nef = (TGTextEntry *)fNodeNumber->GetNumberEntry(); nef->SetToolTipText("Enter the node copy number"); fNodeNumber->Associate(this); - f1->AddFrame(fNodeNumber, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fNodeNumber, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 3, 3, 2, 5)); - -// Mother volume selection + // Mother volume selection MakeTitle("Mother volume"); f1 = new TGCompositeFrame(this, 155, 30, kHorizontalFrame | kFixedWidth); fSelectedMother = 0; @@ -82,7 +85,7 @@ TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, fEditMother->Associate(this); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 2)); -// Volume selection + // Volume selection MakeTitle("Volume"); f1 = new TGCompositeFrame(this, 155, 30, kHorizontalFrame | kFixedWidth); fSelectedVolume = 0; @@ -100,7 +103,7 @@ TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, fEditVolume->Associate(this); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 2)); -// Matrix selection + // Matrix selection MakeTitle("Matrix"); f1 = new TGCompositeFrame(this, 155, 30, kHorizontalFrame | kFixedWidth); fSelectedMatrix = 0; @@ -124,9 +127,9 @@ TGeoNodeEditor::TGeoNodeEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -139,7 +142,7 @@ TGeoNodeEditor::~TGeoNodeEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -161,33 +164,36 @@ void TGeoNodeEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to a editable object. -void TGeoNodeEditor::SetModel(TObject* obj) +void TGeoNodeEditor::SetModel(TObject *obj) { if (obj == 0 || !obj->InheritsFrom(TGeoNode::Class())) { SetActive(kFALSE); return; } - fNode = (TGeoNode*)obj; + fNode = (TGeoNode *)obj; const char *sname = fNode->GetName(); fNodeName->SetText(sname); fNodeNumber->SetNumber(fNode->GetNumber()); fSelectedMother = fNode->GetMotherVolume(); - if (fSelectedMother) fLSelMother->SetText(fSelectedMother->GetName()); + if (fSelectedMother) + fLSelMother->SetText(fSelectedMother->GetName()); fSelectedVolume = fNode->GetVolume(); - if (fSelectedVolume) fLSelVolume->SetText(fSelectedVolume->GetName()); + if (fSelectedVolume) + fLSelVolume->SetText(fSelectedVolume->GetName()); fSelectedMatrix = fNode->GetMatrix(); - if (fSelectedMatrix) fLSelMatrix->SetText(fSelectedMatrix->GetName()); + if (fSelectedMatrix) + fLSelMatrix->SetText(fSelectedMatrix->GetName()); fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -197,10 +203,12 @@ void TGeoNodeEditor::SetModel(TObject* obj) void TGeoNodeEditor::DoSelectMother() { TGeoVolume *vol = fSelectedMother; - new TGeoVolumeDialog(fBSelMother, gClient->GetRoot(), 200,300); - fSelectedMother = (TGeoVolume*)TGeoVolumeDialog::GetSelected(); - if (fSelectedMother) fLSelMother->SetText(fSelectedMother->GetName()); - else fSelectedMother = vol; + new TGeoVolumeDialog(fBSelMother, gClient->GetRoot(), 200, 300); + fSelectedMother = (TGeoVolume *)TGeoVolumeDialog::GetSelected(); + if (fSelectedMother) + fLSelMother->SetText(fSelectedMother->GetName()); + else + fSelectedMother = vol; } //////////////////////////////////////////////////////////////////////////////// @@ -209,10 +217,12 @@ void TGeoNodeEditor::DoSelectMother() void TGeoNodeEditor::DoSelectVolume() { TGeoVolume *vol = fSelectedVolume; - new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200,300); - fSelectedVolume = (TGeoVolume*)TGeoVolumeDialog::GetSelected(); - if (fSelectedVolume) fLSelVolume->SetText(fSelectedVolume->GetName()); - else fSelectedVolume = vol; + new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200, 300); + fSelectedVolume = (TGeoVolume *)TGeoVolumeDialog::GetSelected(); + if (fSelectedVolume) + fLSelVolume->SetText(fSelectedVolume->GetName()); + else + fSelectedVolume = vol; } //////////////////////////////////////////////////////////////////////////////// @@ -221,10 +231,12 @@ void TGeoNodeEditor::DoSelectVolume() void TGeoNodeEditor::DoSelectMatrix() { TGeoMatrix *matrix = fSelectedMatrix; - new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200,300); - fSelectedMatrix = (TGeoMatrix*)TGeoMatrixDialog::GetSelected(); - if (fSelectedMatrix) fLSelMatrix->SetText(fSelectedMatrix->GetName()); - else fSelectedMatrix = matrix; + new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200, 300); + fSelectedMatrix = (TGeoMatrix *)TGeoMatrixDialog::GetSelected(); + if (fSelectedMatrix) + fLSelMatrix->SetText(fSelectedMatrix->GetName()); + else + fSelectedMatrix = matrix; } //////////////////////////////////////////////////////////////////////////////// @@ -262,7 +274,8 @@ void TGeoNodeEditor::DoEditVolume() void TGeoNodeEditor::DoEditMatrix() { - if (!fSelectedMatrix) return; + if (!fSelectedMatrix) + return; fTabMgr->GetMatrixEditor(fSelectedMatrix); } @@ -272,28 +285,22 @@ void TGeoNodeEditor::DoEditMatrix() void TGeoNodeEditor::DoNodeName() { const char *name = fNodeName->GetText(); - if (!name[0] || !strcmp(name, fNode->GetName())) return; + if (!name[0] || !strcmp(name, fNode->GetName())) + return; fNode->SetName(name); } //////////////////////////////////////////////////////////////////////////////// /// Change node copy number -void TGeoNodeEditor::DoNodeNumber() -{ -} +void TGeoNodeEditor::DoNodeNumber() {} //////////////////////////////////////////////////////////////////////////////// /// Slot for applying modifications. -void TGeoNodeEditor::DoApply() -{ -} +void TGeoNodeEditor::DoApply() {} //////////////////////////////////////////////////////////////////////////////// /// Slot for undoing last operation. -void TGeoNodeEditor::DoUndo() -{ -} - +void TGeoNodeEditor::DoUndo() {} diff --git a/geom/geombuilder/src/TGeoParaEditor.cxx b/geom/geombuilder/src/TGeoParaEditor.cxx index 08607111cb8e6..f0938a13df7bb 100644 --- a/geom/geombuilder/src/TGeoParaEditor.cxx +++ b/geom/geombuilder/src/TGeoParaEditor.cxx @@ -35,18 +35,24 @@ Editor for a TGeoPara. ClassImp(TGeoParaEditor); enum ETGeoParaWid { - kPARA_NAME, kPARA_X, kPARA_Y, kPARA_Z, kPARA_ALPHA, - kPARA_THETA, kPARA_PHI, kPARA_APPLY, kPARA_UNDO + kPARA_NAME, + kPARA_X, + kPARA_Y, + kPARA_Z, + kPARA_ALPHA, + kPARA_THETA, + kPARA_PHI, + kPARA_APPLY, + kPARA_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for para editor -TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fXi = fYi = fZi = fAlphai = fThetai = fPhii = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -68,7 +74,7 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, fEDx = new TGNumberEntry(f1, 0., 5, kPARA_X); fEDx->SetNumAttr(TGNumberFormat::kNEAPositive); fEDx->Resize(100, fEDx->GetDefaultHeight()); - nef = (TGTextEntry*)fEDx->GetNumberEntry(); + nef = (TGTextEntry *)fEDx->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in X"); fEDx->Associate(this); f1->AddFrame(fEDx, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -80,7 +86,7 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, fEDy = new TGNumberEntry(f1, 0., 5, kPARA_Y); fEDy->SetNumAttr(TGNumberFormat::kNEAPositive); fEDy->Resize(100, fEDy->GetDefaultHeight()); - nef = (TGTextEntry*)fEDy->GetNumberEntry(); + nef = (TGTextEntry *)fEDy->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Y"); fEDy->Associate(this); f1->AddFrame(fEDy, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -92,7 +98,7 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, fEDz = new TGNumberEntry(f1, 0., 5, kPARA_Z); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); fEDz->Resize(100, fEDz->GetDefaultHeight()); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Z"); fEDz->Associate(this); f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -103,7 +109,7 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Alpha"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEAlpha = new TGNumberEntry(f1, 0., 5, kPARA_ALPHA); fEAlpha->Resize(100, fEAlpha->GetDefaultHeight()); - nef = (TGTextEntry*)fEAlpha->GetNumberEntry(); + nef = (TGTextEntry *)fEAlpha->GetNumberEntry(); nef->SetToolTipText("Enter the angle with respect to Y axis [deg]"); fEAlpha->Associate(this); f1->AddFrame(fEAlpha, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -115,19 +121,19 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, fETheta = new TGNumberEntry(f1, 0., 5, kPARA_THETA); fETheta->SetNumAttr(TGNumberFormat::kNEAPositive); fETheta->Resize(100, fETheta->GetDefaultHeight()); - nef = (TGTextEntry*)fETheta->GetNumberEntry(); + nef = (TGTextEntry *)fETheta->GetNumberEntry(); nef->SetToolTipText("Enter the theta angle of the para axis [deg]"); fETheta->Associate(this); f1->AddFrame(fETheta, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - // Number entry for Phi + // Number entry for Phi f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "Phi"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEPhi = new TGNumberEntry(f1, 0., 5, kPARA_PHI); fEPhi->SetNumAttr(TGNumberFormat::kNEAPositive); fEPhi->Resize(100, fEPhi->GetDefaultHeight()); - nef = (TGTextEntry*)fEPhi->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi->GetNumberEntry(); nef->SetToolTipText("Enter the phi angle of the para axis [deg]"); fEPhi->Associate(this); f1->AddFrame(fEPhi, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -136,8 +142,8 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -145,9 +151,9 @@ TGeoParaEditor::TGeoParaEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -160,7 +166,7 @@ TGeoParaEditor::~TGeoParaEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -188,17 +194,16 @@ void TGeoParaEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoParaEditor::SetModel(TObject* obj) +void TGeoParaEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoPara::Class())) { + if (obj == 0 || (obj->IsA() != TGeoPara::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoPara*)obj; + fShape = (TGeoPara *)obj; fXi = fShape->GetX(); fYi = fShape->GetY(); fZi = fShape->GetZ(); @@ -206,7 +211,8 @@ void TGeoParaEditor::SetModel(TObject* obj) fThetai = fShape->GetTheta(); fPhii = fShape->GetPhi(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -220,7 +226,8 @@ void TGeoParaEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -246,7 +253,8 @@ void TGeoParaEditor::DoName() void TGeoParaEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t dx = fEDx->GetNumber(); Double_t dy = fEDy->GetNumber(); Double_t dz = fEDz->GetNumber(); @@ -271,11 +279,12 @@ void TGeoParaEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -309,12 +318,13 @@ void TGeoParaEditor::DoUndo() void TGeoParaEditor::DoX() { Double_t dx = fEDx->GetNumber(); - if (dx<=0) { + if (dx <= 0) { dx = 0.1; fEDx->SetNumber(dx); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -323,12 +333,13 @@ void TGeoParaEditor::DoX() void TGeoParaEditor::DoY() { Double_t dy = fEDy->GetNumber(); - if (dy<=0) { + if (dy <= 0) { dy = 0.1; fEDy->SetNumber(dy); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -337,12 +348,13 @@ void TGeoParaEditor::DoY() void TGeoParaEditor::DoZ() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -351,12 +363,13 @@ void TGeoParaEditor::DoZ() void TGeoParaEditor::DoAlpha() { Double_t alpha = fEAlpha->GetNumber(); - if (TMath::Abs(alpha)>=90) { - alpha = 89.9*TMath::Sign(1.,alpha); + if (TMath::Abs(alpha) >= 90) { + alpha = 89.9 * TMath::Sign(1., alpha); fEAlpha->SetNumber(alpha); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -365,16 +378,17 @@ void TGeoParaEditor::DoAlpha() void TGeoParaEditor::DoTheta() { Double_t theta = fETheta->GetNumber(); - if (theta<0) { + if (theta < 0) { theta = 0; fETheta->SetNumber(theta); } - if (theta>180) { + if (theta > 180) { theta = 180; fETheta->SetNumber(theta); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -383,11 +397,11 @@ void TGeoParaEditor::DoTheta() void TGeoParaEditor::DoPhi() { Double_t phi = fEPhi->GetNumber(); - if (phi<0 || phi>360) { + if (phi < 0 || phi > 360) { phi = 0; fEPhi->SetNumber(phi); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - diff --git a/geom/geombuilder/src/TGeoPconEditor.cxx b/geom/geombuilder/src/TGeoPconEditor.cxx index 787dcf964b491..ed51b68612c77 100644 --- a/geom/geombuilder/src/TGeoPconEditor.cxx +++ b/geom/geombuilder/src/TGeoPconEditor.cxx @@ -35,18 +35,15 @@ Editor for a TGeoPcon. ClassImp(TGeoPconEditor); -enum ETGeoPconWid { - kPCON_NAME, kPCON_NZ, kPCON_PHI1, kPCON_DPHI, kPCON_APPLY, kPCON_UNDO -}; +enum ETGeoPconWid { kPCON_NAME, kPCON_NZ, kPCON_PHI1, kPCON_DPHI, kPCON_APPLY, kPCON_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for polycone editor -TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fNsections = 0; fSections = 0; fNsecti = 0; @@ -58,7 +55,7 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, fIsModified = kFALSE; fIsShapeEditable = kFALSE; - fLHsect = new TGLayoutHints(kLHintsTop | kLHintsLeft, 0,0,2,2); + fLHsect = new TGLayoutHints(kLHintsTop | kLHintsLeft, 0, 0, 2, 2); // TextEntry for shape name MakeTitle("Name"); @@ -76,8 +73,8 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, fENz = new TGNumberEntry(f1, 0., 5, kPCON_NZ); fENz->SetNumAttr(TGNumberFormat::kNEAPositive); fENz->SetNumStyle(TGNumberFormat::kNESInteger); - fENz->Resize(100,fENz->GetDefaultHeight()); - nef = (TGTextEntry*)fENz->GetNumberEntry(); + fENz->Resize(100, fENz->GetDefaultHeight()); + nef = (TGTextEntry *)fENz->GetNumberEntry(); nef->SetToolTipText("Enter the number of Z sections"); fENz->Associate(this); f1->AddFrame(fENz, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); @@ -87,8 +84,8 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "Phi1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEPhi1 = new TGNumberEntry(f1, 0., 5, kPCON_PHI1); - fEPhi1->Resize(100,fEPhi1->GetDefaultHeight()); - nef = (TGTextEntry*)fEPhi1->GetNumberEntry(); + fEPhi1->Resize(100, fEPhi1->GetDefaultHeight()); + nef = (TGTextEntry *)fEPhi1->GetNumberEntry(); nef->SetToolTipText("Enter the starting phi angle [deg]"); fEPhi1->Associate(this); f1->AddFrame(fEPhi1, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); @@ -99,8 +96,8 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Dphi"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDPhi = new TGNumberEntry(f1, 0., 5, kPCON_DPHI); fEDPhi->SetNumAttr(TGNumberFormat::kNEAPositive); - fEDPhi->Resize(100,fEDPhi->GetDefaultHeight()); - nef = (TGTextEntry*)fEDPhi->GetNumberEntry(); + fEDPhi->Resize(100, fEDPhi->GetDefaultHeight()); + nef = (TGTextEntry *)fEDPhi->GetNumberEntry(); nef->SetToolTipText("Enter the phi range [deg]"); fEDPhi->Associate(this); f1->AddFrame(fEDPhi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); @@ -108,7 +105,7 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, // TGCanvas containing sections MakeTitle("Pcon sections"); - fCan = new TGCanvas(this, 160, 200, kSunkenFrame | kDoubleBorder); + fCan = new TGCanvas(this, 160, 200, kSunkenFrame | kDoubleBorder); TGCompositeFrame *cont = new TGCompositeFrame(fCan->GetViewPort(), 155, 20, kVerticalFrame | kFixedWidth); fCan->SetContainer(cont); // labels for #i, Z, Rmin, Rmax @@ -117,7 +114,7 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Z"), new TGLayoutHints(kLHintsLeft, 2, 20, 6, 0)); f1->AddFrame(new TGLabel(f1, "Rmin"), new TGLayoutHints(kLHintsLeft, 2, 20, 6, 0)); f1->AddFrame(new TGLabel(f1, "Rmax"), new TGLayoutHints(kLHintsLeft, 2, 10, 6, 0)); - cont->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 0,0,0,0)); + cont->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); CreateSections(2); AddFrame(fCan, new TGLayoutHints(kLHintsLeft, 0, 0, 4, 4)); @@ -125,8 +122,8 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, // Delayed draw fDFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(fDFrame, "Delayed draw"); - fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons fBFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -134,9 +131,9 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, fBFrame->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(fBFrame, "Undo"); - fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -145,15 +142,19 @@ TGeoPconEditor::TGeoPconEditor(const TGWindow *p, Int_t width, TGeoPconEditor::~TGeoPconEditor() { - if (fSections) delete fSections; - if (fZi) delete [] fZi; - if (fRmini) delete [] fRmini; - if (fRmaxi) delete [] fRmaxi; + if (fSections) + delete fSections; + if (fZi) + delete[] fZi; + if (fRmini) + delete[] fRmini; + if (fRmaxi) + delete[] fRmaxi; TGFrameElement *el; TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -172,20 +173,21 @@ void TGeoPconEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to a given pcon. -void TGeoPconEditor::SetModel(TObject* obj) +void TGeoPconEditor::SetModel(TObject *obj) { if (obj == 0 || (obj->IsA() != TGeoPcon::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoPcon*)obj; + fShape = (TGeoPcon *)obj; const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); - else fShapeName->SetText(sname); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); + else + fShapeName->SetText(sname); Int_t nsections = fShape->GetNz(); fNsecti = nsections; @@ -200,7 +202,8 @@ void TGeoPconEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -209,27 +212,29 @@ void TGeoPconEditor::SetModel(TObject* obj) void TGeoPconEditor::CreateSections(Int_t inew) { - if (inew == fNsections) return; - if (!fSections) fSections = new TObjArray(8); - TGCompositeFrame *cont = (TGCompositeFrame*)fCan->GetContainer(); + if (inew == fNsections) + return; + if (!fSections) + fSections = new TObjArray(8); + TGCompositeFrame *cont = (TGCompositeFrame *)fCan->GetContainer(); TGeoPconSection *sect; Int_t isect; // new sections requested - if (inew>fNsections) { - for (isect=fNsections; isect fNsections) { + for (isect = fNsections; isect < inew; isect++) { sect = new TGeoPconSection(cont, 150, 10, isect); fSections->Add(sect); cont->AddFrame(sect, fLHsect); sect->Connect("Changed(Int_t)", "TGeoPconEditor", this, "DoSectionChange(Int_t)"); } } else { - // some sections need to be removed - for (isect=inew; isectAt(isect); + // some sections need to be removed + for (isect = inew; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); sect->HideDaughters(); cont->HideFrame(sect); cont->RemoveFrame(sect); -// sect->Disconnect("Changed(Int_t)", "TGeoPconEditor", this, "DoSectionChange(Int_t)"); + // sect->Disconnect("Changed(Int_t)", "TGeoPconEditor", this, "DoSectionChange(Int_t)"); fSections->RemoveAt(isect); delete sect; } @@ -249,16 +254,17 @@ Bool_t TGeoPconEditor::CheckSections(Bool_t change) TGeoPconSection *sect; Double_t zmin = 0; Double_t rmin = 0, rmax = 1.; - for (Int_t isect=0; isectAt(isect); - if (isect && (sect->GetZ()SetZ(zmin+1.); + for (Int_t isect = 0; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); + if (isect && (sect->GetZ() < zmin)) { + if (!change) + return kFALSE; + sect->SetZ(zmin + 1.); } zmin = sect->GetZ(); - if (sect->GetRmin()<0 || - (sect->GetRmax()<0) || ((sect->GetRmin()==0) && (sect->GetRmax()==0))) { - if (!change) return kFALSE; + if (sect->GetRmin() < 0 || (sect->GetRmax() < 0) || ((sect->GetRmin() == 0) && (sect->GetRmax() == 0))) { + if (!change) + return kFALSE; sect->SetRmin(rmin); sect->SetRmax(rmax); } @@ -273,15 +279,18 @@ Bool_t TGeoPconEditor::CheckSections(Bool_t change) void TGeoPconEditor::UpdateSections() { - if (fZi) delete [] fZi; - if (fRmini) delete [] fRmini; - if (fRmaxi) delete [] fRmaxi; + if (fZi) + delete[] fZi; + if (fRmini) + delete[] fRmini; + if (fRmaxi) + delete[] fRmaxi; fZi = new Double_t[fNsections]; fRmini = new Double_t[fNsections]; fRmaxi = new Double_t[fNsections]; TGeoPconSection *sect; - for (Int_t isect=0; isectAt(isect); + for (Int_t isect = 0; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); sect->SetZ(fShape->GetZ(isect)); fZi[isect] = fShape->GetZ(isect); sect->SetRmin(fShape->GetRmin(isect)); @@ -313,31 +322,34 @@ void TGeoPconEditor::DoName() void TGeoPconEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); fApply->SetEnabled(kFALSE); fUndo->SetEnabled(); - if (!CheckSections()) return; + if (!CheckSections()) + return; // check if number of sections changed Bool_t recreate = kFALSE; Int_t nz = fENz->GetIntNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t dphi = fEDPhi->GetNumber(); - if (nz != fShape->GetNz()) recreate = kTRUE; + if (nz != fShape->GetNz()) + recreate = kTRUE; TGeoPconSection *sect; Int_t isect; if (recreate) { - Double_t *array = new Double_t[3*(nz+1)]; + Double_t *array = new Double_t[3 * (nz + 1)]; array[0] = phi1; array[1] = dphi; array[2] = nz; - for (isect=0; isectAt(isect); - array[3+3*isect] = sect->GetZ(); - array[4+3*isect] = sect->GetRmin(); - array[5+3*isect] = sect->GetRmax(); + for (isect = 0; isect < nz; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); + array[3 + 3 * isect] = sect->GetZ(); + array[4 + 3 * isect] = sect->GetRmin(); + array[5 + 3 * isect] = sect->GetRmax(); } fShape->SetDimensions(array); - delete [] array; + delete[] array; if (fPad) { if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { TView *view = fPad->GetView(); @@ -346,19 +358,22 @@ void TGeoPconEditor::DoApply() fPad->GetView()->ShowAxis(); } else { const Double_t *orig = fShape->GetOrigin(); - view->SetRange(orig[0]-fShape->GetDX(), orig[1]-fShape->GetDY(), orig[2]-fShape->GetDZ(), - orig[0]+fShape->GetDX(), orig[1]+fShape->GetDY(), orig[2]+fShape->GetDZ()); + view->SetRange(orig[0] - fShape->GetDX(), orig[1] - fShape->GetDY(), orig[2] - fShape->GetDZ(), + orig[0] + fShape->GetDX(), orig[1] + fShape->GetDY(), orig[2] + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } return; } // No need to call SetDimensions - if (TMath::Abs(phi1-fShape->GetPhi1())>1.e-6) fShape->Phi1() = phi1; - if (TMath::Abs(dphi-fShape->GetDphi())>1.e-6) fShape->Dphi() = dphi; - for (isect=0; isectAt(isect); + if (TMath::Abs(phi1 - fShape->GetPhi1()) > 1.e-6) + fShape->Phi1() = phi1; + if (TMath::Abs(dphi - fShape->GetDphi()) > 1.e-6) + fShape->Dphi() = dphi; + for (isect = 0; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); fShape->Z(isect) = sect->GetZ(); fShape->Rmin(isect) = sect->GetRmin(); fShape->Rmax(isect) = sect->GetRmax(); @@ -372,11 +387,12 @@ void TGeoPconEditor::DoApply() fPad->GetView()->ShowAxis(); } else { const Double_t *orig = fShape->GetOrigin(); - view->SetRange(orig[0]-fShape->GetDX(), orig[1]-fShape->GetDY(), orig[2]-fShape->GetDZ(), - orig[0]+fShape->GetDX(), orig[1]+fShape->GetDY(), orig[2]+fShape->GetDZ()); + view->SetRange(orig[0] - fShape->GetDX(), orig[1] - fShape->GetDY(), orig[2] - fShape->GetDZ(), + orig[0] + fShape->GetDX(), orig[1] + fShape->GetDY(), orig[2] + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -385,21 +401,24 @@ void TGeoPconEditor::DoApply() void TGeoPconEditor::DoSectionChange(Int_t isect) { - TGeoPconSection *sect, *sectlo=0, *secthi=0; - sect = (TGeoPconSection*)fSections->At(isect); - if (isect) sectlo = (TGeoPconSection*)fSections->At(isect-1); - if (isectAt(isect+1); + TGeoPconSection *sect, *sectlo = 0, *secthi = 0; + sect = (TGeoPconSection *)fSections->At(isect); + if (isect) + sectlo = (TGeoPconSection *)fSections->At(isect - 1); + if (isect < fNsections - 1) + secthi = (TGeoPconSection *)fSections->At(isect + 1); Double_t z = sect->GetZ(); - if (sectlo && zGetZ()) { + if (sectlo && z < sectlo->GetZ()) { z = sectlo->GetZ(); sect->SetZ(z); } - if (secthi && z>secthi->GetZ()) { + if (secthi && z > secthi->GetZ()) { z = secthi->GetZ(); sect->SetZ(z); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -415,7 +434,8 @@ void TGeoPconEditor::DoNz() CreateSections(nz); CheckSections(kTRUE); DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -425,10 +445,13 @@ void TGeoPconEditor::DoPhi() { Double_t phi1 = fEPhi1->GetNumber(); Double_t dphi = fEDPhi->GetNumber(); - if (TMath::Abs(phi1)>360) fEPhi1->SetNumber(0); - if (dphi>360) fEDPhi->SetNumber(360); + if (TMath::Abs(phi1) > 360) + fEPhi1->SetNumber(0); + if (dphi > 360) + fEDPhi->SetNumber(360); DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -449,8 +472,8 @@ void TGeoPconEditor::DoUndo() fEPhi1->SetNumber(fPhi1i); fEDPhi->SetNumber(fDPhii); TGeoPconSection *sect; - for (Int_t isect=0; isectAt(isect); + for (Int_t isect = 0; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); sect->SetZ(fZi[isect]); sect->SetRmin(fRmini[isect]); sect->SetRmax(fRmaxi[isect]); @@ -473,33 +496,33 @@ ClassImp(TGeoPconSection); /// Constructor. TGeoPconSection::TGeoPconSection(const TGWindow *p, UInt_t w, UInt_t h, Int_t id) - :TGCompositeFrame(p,w,h,kHorizontalFrame | kFixedWidth) + : TGCompositeFrame(p, w, h, kHorizontalFrame | kFixedWidth) { fNumber = id; TGTextEntry *nef; // Label with number - AddFrame(new TGLabel(this, TString::Format("#%i",id)), new TGLayoutHints(kLHintsLeft, 2, 4, 6, 0)); + AddFrame(new TGLabel(this, TString::Format("#%i", id)), new TGLayoutHints(kLHintsLeft, 2, 4, 6, 0)); // Z entry fEZ = new TGNumberEntry(this, 0., 5); - fEZ->Resize(40,fEZ->GetDefaultHeight()); - nef = (TGTextEntry*)fEZ->GetNumberEntry(); + fEZ->Resize(40, fEZ->GetDefaultHeight()); + nef = (TGTextEntry *)fEZ->GetNumberEntry(); nef->SetToolTipText("Enter the Z position"); fEZ->Associate(this); AddFrame(fEZ, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); // Rmin entry fERmin = new TGNumberEntry(this, 0., 5); fERmin->SetNumAttr(TGNumberFormat::kNEAPositive); - fERmin->Resize(40,fERmin->GetDefaultHeight()); - nef = (TGTextEntry*)fERmin->GetNumberEntry(); + fERmin->Resize(40, fERmin->GetDefaultHeight()); + nef = (TGTextEntry *)fERmin->GetNumberEntry(); nef->SetToolTipText("Enter the minimum radius"); fERmin->Associate(this); AddFrame(fERmin, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); // Rmax entry fERmax = new TGNumberEntry(this, 0., 5); fERmax->SetNumAttr(TGNumberFormat::kNEAPositive); - fERmax->Resize(40,fERmax->GetDefaultHeight()); - nef = (TGTextEntry*)fERmax->GetNumberEntry(); + fERmax->Resize(40, fERmax->GetDefaultHeight()); + nef = (TGTextEntry *)fERmax->GetNumberEntry(); nef->SetToolTipText("Enter the maximum radius"); fERmax->Associate(this); AddFrame(fERmax, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); @@ -608,7 +631,8 @@ void TGeoPconSection::DoRmin() { Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmin>rmax-1.e-8) fERmin->SetNumber(rmax); + if (rmin > rmax - 1.e-8) + fERmin->SetNumber(rmax); Changed(fNumber); } @@ -619,6 +643,7 @@ void TGeoPconSection::DoRmax() { Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmaxSetNumber(rmin); + if (rmax < rmin + 1.e-8) + fERmax->SetNumber(rmin); Changed(fNumber); } diff --git a/geom/geombuilder/src/TGeoPgonEditor.cxx b/geom/geombuilder/src/TGeoPgonEditor.cxx index 6af2384fb67b4..45c25437b3418 100644 --- a/geom/geombuilder/src/TGeoPgonEditor.cxx +++ b/geom/geombuilder/src/TGeoPgonEditor.cxx @@ -33,15 +33,12 @@ Editor for a TGeoPgon. ClassImp(TGeoPgonEditor); -enum ETGeoPgonWid { - kPGON_NEDGES -}; +enum ETGeoPgonWid { kPGON_NEDGES }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for polygone editor -TGeoPgonEditor::TGeoPgonEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoPgonEditor::TGeoPgonEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoPconEditor(p, width, height, options | kVerticalFrame, back) { fNedgesi = 0; @@ -61,7 +58,7 @@ TGeoPgonEditor::~TGeoPgonEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -69,20 +66,22 @@ TGeoPgonEditor::~TGeoPgonEditor() //////////////////////////////////////////////////////////////////////////////// /// Connect to a given pgon. -void TGeoPgonEditor::SetModel(TObject* obj) +void TGeoPgonEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoPgon::Class())) { + if (obj == 0 || (obj->IsA() != TGeoPgon::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoPcon*)obj; + fShape = (TGeoPcon *)obj; const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); - else fShapeName->SetText(sname); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); + else + fShapeName->SetText(sname); Int_t nsections = fShape->GetNz(); fNsecti = nsections; - fNedgesi = ((TGeoPgon*)fShape)->GetNedges(); + fNedgesi = ((TGeoPgon *)fShape)->GetNedges(); fENz->SetNumber(nsections); fENedges->SetNumber(fNedgesi); fEPhi1->SetNumber(fShape->GetPhi1()); @@ -95,7 +94,8 @@ void TGeoPgonEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -104,35 +104,38 @@ void TGeoPgonEditor::SetModel(TObject* obj) void TGeoPgonEditor::DoApply() { - TGeoPgon *shape = (TGeoPgon*)fShape; + TGeoPgon *shape = (TGeoPgon *)fShape; const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); fApply->SetEnabled(kFALSE); fUndo->SetEnabled(); - if (!CheckSections()) return; + if (!CheckSections()) + return; // check if number of sections changed Bool_t recreate = kFALSE; Int_t nz = fENz->GetIntNumber(); Int_t nedges = fENedges->GetIntNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t dphi = fEDPhi->GetNumber(); - if (nz != fShape->GetNz()) recreate = kTRUE; + if (nz != fShape->GetNz()) + recreate = kTRUE; TGeoPconSection *sect; Int_t isect; if (recreate) { - Double_t *array = new Double_t[3*(nz+1)+1]; + Double_t *array = new Double_t[3 * (nz + 1) + 1]; array[0] = phi1; array[1] = dphi; array[2] = nedges; array[3] = nz; - for (isect=0; isectAt(isect); - array[4+3*isect] = sect->GetZ(); - array[5+3*isect] = sect->GetRmin(); - array[6+3*isect] = sect->GetRmax(); + for (isect = 0; isect < nz; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); + array[4 + 3 * isect] = sect->GetZ(); + array[5 + 3 * isect] = sect->GetRmin(); + array[6 + 3 * isect] = sect->GetRmax(); } shape->SetDimensions(array); - delete [] array; + delete[] array; if (fPad) { if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { TView *view = fPad->GetView(); @@ -141,20 +144,24 @@ void TGeoPgonEditor::DoApply() fPad->GetView()->ShowAxis(); } else { const Double_t *orig = fShape->GetOrigin(); - view->SetRange(orig[0]-fShape->GetDX(), orig[1]-fShape->GetDY(), orig[2]-fShape->GetDZ(), - orig[0]+fShape->GetDX(), orig[1]+fShape->GetDY(), orig[2]+fShape->GetDZ()); + view->SetRange(orig[0] - fShape->GetDX(), orig[1] - fShape->GetDY(), orig[2] - fShape->GetDZ(), + orig[0] + fShape->GetDX(), orig[1] + fShape->GetDY(), orig[2] + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } return; } // No need to call SetDimensions - if (TMath::Abs(phi1-fShape->GetPhi1())>1.e-6) fShape->Phi1() = phi1; - if (TMath::Abs(dphi-fShape->GetDphi())>1.e-6) fShape->Dphi() = dphi; - if (nedges != shape->GetNedges()) shape->SetNedges(nedges); - for (isect=0; isectAt(isect); + if (TMath::Abs(phi1 - fShape->GetPhi1()) > 1.e-6) + fShape->Phi1() = phi1; + if (TMath::Abs(dphi - fShape->GetDphi()) > 1.e-6) + fShape->Dphi() = dphi; + if (nedges != shape->GetNedges()) + shape->SetNedges(nedges); + for (isect = 0; isect < fNsections; isect++) { + sect = (TGeoPconSection *)fSections->At(isect); fShape->Z(isect) = sect->GetZ(); fShape->Rmin(isect) = sect->GetRmin(); fShape->Rmax(isect) = sect->GetRmax(); @@ -168,11 +175,12 @@ void TGeoPgonEditor::DoApply() fPad->GetView()->ShowAxis(); } else { const Double_t *orig = fShape->GetOrigin(); - view->SetRange(orig[0]-fShape->GetDX(), orig[1]-fShape->GetDY(), orig[2]-fShape->GetDZ(), - orig[0]+fShape->GetDX(), orig[1]+fShape->GetDY(), orig[2]+fShape->GetDZ()); + view->SetRange(orig[0] - fShape->GetDX(), orig[1] - fShape->GetDY(), orig[2] - fShape->GetDZ(), + orig[0] + fShape->GetDX(), orig[1] + fShape->GetDY(), orig[2] + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -196,8 +204,8 @@ void TGeoPgonEditor::CreateEdges() fENedges = new TGNumberEntry(f1, 0., 5, kPGON_NEDGES); fENedges->SetNumAttr(TGNumberFormat::kNEAPositive); fENedges->SetNumStyle(TGNumberFormat::kNESInteger); - fENedges->Resize(100,fENedges->GetDefaultHeight()); - nef = (TGTextEntry*)fENedges->GetNumberEntry(); + fENedges->Resize(100, fENedges->GetDefaultHeight()); + nef = (TGTextEntry *)fENedges->GetNumberEntry(); nef->SetToolTipText("Enter the number of edges of the polygon"); fENedges->Associate(this); f1->AddFrame(fENedges, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); @@ -215,6 +223,6 @@ void TGeoPgonEditor::DoNedges() fENedges->SetNumber(nedges); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - diff --git a/geom/geombuilder/src/TGeoSphereEditor.cxx b/geom/geombuilder/src/TGeoSphereEditor.cxx index ef028fdf9cf03..0e14a0ce109e8 100644 --- a/geom/geombuilder/src/TGeoSphereEditor.cxx +++ b/geom/geombuilder/src/TGeoSphereEditor.cxx @@ -36,19 +36,26 @@ Editor for a TGeoSphere. ClassImp(TGeoSphereEditor); enum ETGeoSphereWid { - kSPHERE_NAME, kSPHERE_RMIN, kSPHERE_RMAX, kSPHERE_THETA1, - kSPHERE_THETA2, kSPHERE_PHI1, kSPHERE_PHI2, kSPHERE_PHI, kSPHERE_THETA, - kSPHERE_APPLY, kSPHERE_UNDO + kSPHERE_NAME, + kSPHERE_RMIN, + kSPHERE_RMAX, + kSPHERE_THETA1, + kSPHERE_THETA2, + kSPHERE_PHI1, + kSPHERE_PHI2, + kSPHERE_PHI, + kSPHERE_THETA, + kSPHERE_APPLY, + kSPHERE_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for sphere editor -TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fRmini = fRmaxi = fTheta1i = fTheta2i = fPhi1i = fPhi2i = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -67,45 +74,43 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, MakeTitle("Sphere dimensions"); TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame); // Number entry for rmin - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kOwnBackground); + TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "Rmin"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmin = new TGNumberEntry(f1, 0., 5, kSPHERE_RMIN); fERmin->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmin->GetNumberEntry(); + nef = (TGTextEntry *)fERmin->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius"); fERmin->Associate(this); fERmin->Resize(100, fERmin->GetDefaultHeight()); - f1->AddFrame(fERmin, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fERmin, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for Rmax - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "Rmax"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmax = new TGNumberEntry(f1, 0., 5, kSPHERE_RMAX); fERmax->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmax->GetNumberEntry(); + nef = (TGTextEntry *)fERmax->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius"); fERmax->Associate(this); fERmax->Resize(100, fERmax->GetDefaultHeight()); f1->AddFrame(fERmax, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); MakeTitle("Phi/theta range"); - TGCompositeFrame *f11 = new TGCompositeFrame(this, 150,200, kHorizontalFrame); + TGCompositeFrame *f11 = new TGCompositeFrame(this, 150, 200, kHorizontalFrame); compxyz = new TGCompositeFrame(f11, 75, 200, kHorizontalFrame | kRaisedFrame); // Vertical slider - fSPhi = new TGDoubleVSlider(compxyz,140); - fSPhi->SetRange(0.,720.); + fSPhi = new TGDoubleVSlider(compxyz, 140); + fSPhi->SetRange(0., 720.); compxyz->AddFrame(fSPhi, new TGLayoutHints(kLHintsLeft | kLHintsExpandY, 2, 2, 4, 4)); f1 = new TGCompositeFrame(compxyz, 50, 200, kVerticalFrame); f1->AddFrame(new TGLabel(f1, "Phi min."), new TGLayoutHints(kLHintsTop | kLHintsLeft, 2, 2, 2, 2)); fEPhi1 = new TGNumberEntry(f1, 0., 5, kSPHERE_PHI1); fEPhi1->Resize(30, fEPhi1->GetDefaultHeight()); fEPhi1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi1->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi1->GetNumberEntry(); nef->SetToolTipText("Enter the phi1 value"); fEPhi1->Associate(this); f1->AddFrame(fEPhi1, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); @@ -113,7 +118,7 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, fEPhi2 = new TGNumberEntry(f1, 0., 5, kSPHERE_PHI2); fEPhi2->Resize(30, fEPhi2->GetDefaultHeight()); fEPhi2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi2->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi2->GetNumberEntry(); nef->SetToolTipText("Enter the phi2 value"); fEPhi2->Associate(this); fEPhi2->Resize(30, fEPhi2->GetDefaultHeight()); @@ -121,20 +126,20 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Phi max."), new TGLayoutHints(kLHintsBottom | kLHintsLeft, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2)); - compxyz->Resize(75,150); - f11->AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 0,0,0,0)); + compxyz->Resize(75, 150); + f11->AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); compxyz = new TGCompositeFrame(f11, 75, 200, kHorizontalFrame | kRaisedFrame); // Vertical slider - fSTheta = new TGDoubleVSlider(compxyz,140); - fSTheta->SetRange(0.,180.); + fSTheta = new TGDoubleVSlider(compxyz, 140); + fSTheta->SetRange(0., 180.); compxyz->AddFrame(fSTheta, new TGLayoutHints(kLHintsLeft | kLHintsExpandY, 2, 2, 4, 4)); f1 = new TGCompositeFrame(compxyz, 50, 200, kVerticalFrame); f1->AddFrame(new TGLabel(f1, "Theta min."), new TGLayoutHints(kLHintsTop | kLHintsLeft, 2, 2, 2, 2)); fETheta1 = new TGNumberEntry(f1, 0., 5, kSPHERE_THETA1); fETheta1->Resize(30, fETheta1->GetDefaultHeight()); fETheta1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fETheta1->GetNumberEntry(); + nef = (TGTextEntry *)fETheta1->GetNumberEntry(); nef->SetToolTipText("Enter the theta1 value"); fETheta1->Associate(this); f1->AddFrame(fETheta1, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); @@ -142,14 +147,14 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, fETheta2 = new TGNumberEntry(f1, 0., 5, kSPHERE_THETA2); fETheta2->Resize(30, fETheta2->GetDefaultHeight()); fETheta2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fETheta2->GetNumberEntry(); + nef = (TGTextEntry *)fETheta2->GetNumberEntry(); nef->SetToolTipText("Enter the theta2 value"); fETheta2->Associate(this); f1->AddFrame(fETheta2, new TGLayoutHints(kLHintsBottom | kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2)); f1->AddFrame(new TGLabel(f1, "Theta max."), new TGLayoutHints(kLHintsBottom | kLHintsLeft, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2)); - compxyz->Resize(75,150); + compxyz->Resize(75, 150); f11->AddFrame(compxyz, new TGLayoutHints(kLHintsRight, 0, 0, 0, 0)); AddFrame(f11, new TGLayoutHints(kLHintsLeft, 0, 0, 0, 0)); @@ -157,8 +162,8 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -166,9 +171,9 @@ TGeoSphereEditor::TGeoSphereEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -181,7 +186,7 @@ TGeoSphereEditor::~TGeoSphereEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -205,17 +210,16 @@ void TGeoSphereEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to a given sphere. -void TGeoSphereEditor::SetModel(TObject* obj) +void TGeoSphereEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoSphere::Class())) { + if (obj == 0 || (obj->IsA() != TGeoSphere::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoSphere*)obj; + fShape = (TGeoSphere *)obj; fRmini = fShape->GetRmin(); fRmaxi = fShape->GetRmax(); fPhi1i = fShape->GetPhi1(); @@ -236,7 +240,8 @@ void TGeoSphereEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -262,23 +267,24 @@ void TGeoSphereEditor::DoName() void TGeoSphereEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if ((phi2-phi1) > 360.001) { + if ((phi2 - phi1) > 360.001) { phi1 = 0.; phi2 = 360.; fEPhi1->SetNumber(phi1); fEPhi2->SetNumber(phi2); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); + fSPhi->SetPosition(phi1, phi2); fLock = kFALSE; } Double_t theta1 = fETheta1->GetNumber(); Double_t theta2 = fETheta2->GetNumber(); - fShape->SetSphDimensions(rmin, rmax, theta1,theta2,phi1,phi2); + fShape->SetSphDimensions(rmin, rmax, theta1, theta2, phi1, phi2); fShape->ComputeBBox(); fUndo->SetEnabled(); fApply->SetEnabled(kFALSE); @@ -286,7 +292,8 @@ void TGeoSphereEditor::DoApply() if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -307,10 +314,10 @@ void TGeoSphereEditor::DoUndo() fERmax->SetNumber(fRmaxi); fEPhi1->SetNumber(fPhi1i); fEPhi2->SetNumber(fPhi2i); - fSPhi->SetPosition(fPhi1i,fPhi2i); + fSPhi->SetPosition(fPhi1i, fPhi2i); fETheta1->SetNumber(fTheta1i); fETheta2->SetNumber(fTheta2i); - fSTheta->SetPosition(fTheta1i,fTheta2i); + fSTheta->SetPosition(fTheta1i, fTheta2i); DoApply(); fUndo->SetEnabled(kFALSE); fApply->SetEnabled(kFALSE); @@ -332,7 +339,8 @@ void TGeoSphereEditor::DoRmin() fERmin->SetNumber(rmin); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -346,12 +354,13 @@ void TGeoSphereEditor::DoRmax() rmax = 0.1; fERmax->SetNumber(rmax); } - if (rmax < rmin+1.e-10) { + if (rmax < rmin + 1.e-10) { rmax = rmin + 0.1; fERmax->SetNumber(rmax); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -361,20 +370,22 @@ void TGeoSphereEditor::DoPhi1() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi1 > 360-1.e-10) { + if (phi1 > 360 - 1.e-10) { phi1 = 0.; fEPhi1->SetNumber(phi1); } - if (phi2SetNumber(phi1); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -384,20 +395,22 @@ void TGeoSphereEditor::DoPhi2() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi2-phi1 > 360.) { + if (phi2 - phi1 > 360.) { phi2 -= 360.; fEPhi2->SetNumber(phi2); } - if (phi2SetNumber(phi2); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -411,8 +424,10 @@ void TGeoSphereEditor::DoPhi() fEPhi1->SetNumber(fSPhi->GetMinPosition()); fLock = kTRUE; fEPhi2->SetNumber(fSPhi->GetMaxPosition()); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -422,16 +437,18 @@ void TGeoSphereEditor::DoTheta1() { Double_t theta1 = fETheta1->GetNumber(); Double_t theta2 = fETheta2->GetNumber(); - if (theta2SetNumber(theta2); } if (!fLock) { DoModified(); fLock = kTRUE; - fSTheta->SetPosition(theta1,theta2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSTheta->SetPosition(theta1, theta2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -441,16 +458,18 @@ void TGeoSphereEditor::DoTheta2() { Double_t theta1 = fETheta1->GetNumber(); Double_t theta2 = fETheta2->GetNumber(); - if (theta2SetNumber(theta1); } if (!fLock) { DoModified(); fLock = kTRUE; - fSTheta->SetPosition(theta1,theta2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSTheta->SetPosition(theta1, theta2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -464,6 +483,8 @@ void TGeoSphereEditor::DoTheta() fETheta1->SetNumber(fSTheta->GetMinPosition()); fLock = kTRUE; fETheta2->SetNumber(fSTheta->GetMaxPosition()); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } diff --git a/geom/geombuilder/src/TGeoTabManager.cxx b/geom/geombuilder/src/TGeoTabManager.cxx index 0b07ad042f9a1..825e26ae9f81a 100644 --- a/geom/geombuilder/src/TGeoTabManager.cxx +++ b/geom/geombuilder/src/TGeoTabManager.cxx @@ -75,10 +75,14 @@ TGeoTabManager::TGeoTabManager(TGedEditor *ged) TGeoTabManager::~TGeoTabManager() { fgEditorToMgrMap.Remove(fGedEditor); - if (fShapePanel) delete fShapePanel; - if (fMaterialPanel) delete fMaterialPanel; - if (fMatrixPanel) delete fMatrixPanel; - if (fMediumPanel) delete fMediumPanel; + if (fShapePanel) + delete fShapePanel; + if (fMaterialPanel) + delete fMaterialPanel; + if (fMatrixPanel) + delete fMatrixPanel; + if (fMediumPanel) + delete fMediumPanel; } //////////////////////////////////////////////////////////////////////////////// @@ -91,11 +95,11 @@ void TGeoTabManager::Cleanup(TGCompositeFrame *frame) TList *list = frame->GetList(); Int_t nframes = list->GetSize(); TClass *cl; - for (Int_t i=0; iAt(i); cl = el->fFrame->IsA(); - if (cl==TGCompositeFrame::Class() || cl==TGHorizontalFrame::Class() || cl==TGVerticalFrame::Class()) - Cleanup((TGCompositeFrame*)el->fFrame); + if (cl == TGCompositeFrame::Class() || cl == TGHorizontalFrame::Class() || cl == TGVerticalFrame::Class()) + Cleanup((TGCompositeFrame *)el->fFrame); } frame->Cleanup(); } @@ -105,8 +109,10 @@ void TGeoTabManager::Cleanup(TGCompositeFrame *frame) void TGeoTabManager::GetShapeEditor(TGeoShape *shape) { - if (!shape) return; - if (!fShapePanel) fShapePanel = new TGeoTransientPanel(fGedEditor, "Shape", shape); + if (!shape) + return; + if (!fShapePanel) + fShapePanel = new TGeoTransientPanel(fGedEditor, "Shape", shape); else { fShapePanel->SetModel(shape); fShapePanel->Show(); @@ -118,7 +124,8 @@ void TGeoTabManager::GetShapeEditor(TGeoShape *shape) void TGeoTabManager::GetVolumeEditor(TGeoVolume *volume) { - if (!volume || !fVolumeTab) return; + if (!volume || !fVolumeTab) + return; GetEditors(TAttLine::Class()); GetEditors(TGeoVolume::Class()); fVolumeTab->MapSubwindows(); @@ -131,8 +138,10 @@ void TGeoTabManager::GetVolumeEditor(TGeoVolume *volume) void TGeoTabManager::GetMatrixEditor(TGeoMatrix *matrix) { - if (!matrix) return; - if (!fMatrixPanel) fMatrixPanel = new TGeoTransientPanel(fGedEditor, "Matrix", matrix); + if (!matrix) + return; + if (!fMatrixPanel) + fMatrixPanel = new TGeoTransientPanel(fGedEditor, "Matrix", matrix); else { fMatrixPanel->SetModel(matrix); fMatrixPanel->Show(); @@ -144,8 +153,10 @@ void TGeoTabManager::GetMatrixEditor(TGeoMatrix *matrix) void TGeoTabManager::GetMediumEditor(TGeoMedium *medium) { - if (!medium) return; - if (!fMediumPanel) fMediumPanel = new TGeoTransientPanel(fGedEditor, "Medium", medium); + if (!medium) + return; + if (!fMediumPanel) + fMediumPanel = new TGeoTransientPanel(fGedEditor, "Medium", medium); else { fMediumPanel->SetModel(medium); fMediumPanel->Show(); @@ -158,10 +169,13 @@ void TGeoTabManager::GetMediumEditor(TGeoMedium *medium) void TGeoTabManager::GetMaterialEditor(TGeoMaterial *material) { - if (!material) return; + if (!material) + return; TString name = "Material"; - if (material->IsMixture()) name = "Mixture"; - if (!fMaterialPanel) fMaterialPanel = new TGeoTransientPanel(fGedEditor, name.Data(), material); + if (material->IsMixture()) + name = "Mixture"; + if (!fMaterialPanel) + fMaterialPanel = new TGeoTransientPanel(fGedEditor, name.Data(), material); else { fMaterialPanel->SetModel(material); fMaterialPanel->Show(); @@ -175,16 +189,18 @@ void TGeoTabManager::GetMaterialEditor(TGeoMaterial *material) void TGeoTabManager::GetEditors(TClass *cl) { - TClass *class2 = TClass::GetClass(TString::Format("%sEditor",cl->GetName())); + TClass *class2 = TClass::GetClass(TString::Format("%sEditor", cl->GetName())); if (class2 && class2->InheritsFrom(TGedFrame::Class())) { TGFrameElement *fr; TIter next(fVolumeTab->GetList()); - while ((fr = (TGFrameElement *) next())) if (fr->fFrame->IsA() == class2) return; + while ((fr = (TGFrameElement *)next())) + if (fr->fFrame->IsA() == class2) + return; TGClient *client = fGedEditor->GetClient(); - TGWindow *exroot = (TGWindow*) client->GetRoot(); + TGWindow *exroot = (TGWindow *)client->GetRoot(); client->SetRoot(fVolumeTab); TGedEditor::SetFrameCreator(fGedEditor); - TGedFrame* gfr = reinterpret_cast(class2->New()); + TGedFrame *gfr = reinterpret_cast(class2->New()); gfr->SetModelClass(cl); TGedEditor::SetFrameCreator(0); client->SetRoot(exroot); @@ -199,10 +215,11 @@ void TGeoTabManager::GetEditors(TClass *cl) TGeoTabManager *TGeoTabManager::GetMakeTabManager(TGedEditor *ged) { - if (!ged) return NULL; - TPair *pair = (TPair*) fgEditorToMgrMap.FindObject(ged); + if (!ged) + return NULL; + TPair *pair = (TPair *)fgEditorToMgrMap.FindObject(ged); if (pair) { - return (TGeoTabManager*) pair->Value(); + return (TGeoTabManager *)pair->Value(); } else { TGeoTabManager *tabmgr = new TGeoTabManager(ged); // added to fgEditorToMgrMap in ctor return tabmgr; @@ -218,9 +235,10 @@ Int_t TGeoTabManager::GetTabIndex() const TString tabname = "Volume"; TGTabElement *tel; - for (Int_t i=0; iGetTabTab(i); - if (tel && !strcmp(tel->GetString(),tabname.Data())) return i; + if (tel && !strcmp(tel->GetString(), tabname.Data())) + return i; } return 0; } @@ -233,8 +251,9 @@ void TGeoTabManager::MoveFrame(TGCompositeFrame *fr, TGCompositeFrame *p) TList *list = p->GetList(); TIter next(list); TGFrameElement *el = 0; - while ((el=(TGFrameElement*)next())) { - if (el->fFrame == fr) break; + while ((el = (TGFrameElement *)next())) { + if (el->fFrame == fr) + break; } if (el) { list->Remove(el); @@ -256,10 +275,10 @@ void TGeoTabManager::SetVolTabEnabled(Bool_t flag) void TGeoTabManager::SetModel(TObject *model) { TGCompositeFrame *tab = fVolumeTab; - fVolume = (TGeoVolume*)model; + fVolume = (TGeoVolume *)model; TGFrameElement *el; TIter next(tab->GetList()); - while ((el = (TGFrameElement *) next())) { + while ((el = (TGFrameElement *)next())) { if ((el->fFrame)->InheritsFrom(TGedFrame::Class())) { ((TGedFrame *)(el->fFrame))->SetModel(model); } @@ -279,7 +298,7 @@ ClassImp(TGeoTreeDialog); TObject *TGeoTreeDialog::fgSelectedObj = 0; //////////////////////////////////////////////////////////////////////////////// -///static; return selected object +/// static; return selected object TObject *TGeoTreeDialog::GetSelected() { @@ -290,33 +309,32 @@ TObject *TGeoTreeDialog::GetSelected() /// Constructor TGeoTreeDialog::TGeoTreeDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGTransientFrame(main, main, w, h) + : TGTransientFrame(main, main, w, h) { fgSelectedObj = 0; - fCanvas = new TGCanvas(this, 100, 200, kSunkenFrame | kDoubleBorder); + fCanvas = new TGCanvas(this, 100, 200, kSunkenFrame | kDoubleBorder); fLT = new TGListTree(fCanvas->GetViewPort(), 100, 200); fLT->Associate(this); fCanvas->SetContainer(fLT); - AddFrame(fCanvas, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2,2,2,2)); - f1 = new TGCompositeFrame(this, 100, 10, kHorizontalFrame | kLHintsExpandX); + AddFrame(fCanvas, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2)); + f1 = new TGCompositeFrame(this, 100, 10, kHorizontalFrame | kFitWidth); fObjLabel = new TGLabel(f1, "Selected: -none-"); Pixel_t color; gClient->GetColorByName("#0000ff", color); fObjLabel->SetTextColor(color); fObjLabel->ChangeOptions(kSunkenFrame | kDoubleBorder); - f1->AddFrame(fObjLabel, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2,2,2,2)); + f1->AddFrame(fObjLabel, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 2, 2, 2, 2)); fClose = new TGTextButton(f1, "&Close"); fClose->Associate(this); - f1->AddFrame(fClose, new TGLayoutHints(kLHintsRight, 2,2,2,2)); - AddFrame(f1, new TGLayoutHints(kLHintsBottom | kLHintsExpandX, 2,2,2,2)); + f1->AddFrame(fClose, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); + AddFrame(f1, new TGLayoutHints(kLHintsBottom | kLHintsExpandX, 2, 2, 2, 2)); Int_t ww = caller->GetWidth(); Window_t wdum; - Int_t ax, ay; - gVirtualX->TranslateCoordinates(caller->GetId(), main->GetId(), 0,0,ax,ay,wdum); + Int_t ax, ay; + gVirtualX->TranslateCoordinates(caller->GetId(), main->GetId(), 0, 0, ax, ay, wdum); Move(ax + ww, ay); SetWMPosition(ax, ay); - } //////////////////////////////////////////////////////////////////////////////// @@ -356,7 +374,7 @@ ClassImp(TGeoVolumeDialog); /// Ctor. TGeoVolumeDialog::TGeoVolumeDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGeoTreeDialog(caller, main, w, h) + : TGeoTreeDialog(caller, main, w, h) { BuildListTree(); ConnectSignalsToSlots(); @@ -376,7 +394,7 @@ void TGeoVolumeDialog::BuildListTree() const TGPicture *pic_fldo = gClient->GetPicture("ofolder_t.xpm"); const TGPicture *pic_file = gClient->GetPicture("mdi_default.xpm"); const TGPicture *pic_fileo = gClient->GetPicture("fileopen.xpm"); - TGListTreeItem *parent_item=0; + TGListTreeItem *parent_item = 0; TGeoVolume *parent_vol = gGeoManager->GetMasterVolume(); TGeoVolume *vol; // Existing volume hierarchy @@ -398,14 +416,16 @@ void TGeoVolumeDialog::BuildListTree() parent_item->SetTipText("Select a volume from the list of unconnected volumes"); TIter next1(gGeoManager->GetListOfVolumes()); Bool_t found = kFALSE; - while ((vol=(TGeoVolume*)next1())) { - if (vol->IsAdded()) continue; + while ((vol = (TGeoVolume *)next1())) { + if (vol->IsAdded()) + continue; fLT->AddItem(parent_item, vol->GetName(), vol, pic_fileo, pic_file); found = kTRUE; } if (found) { -// fLT->OpenItem(parent_item); - if (!parent_vol) fLT->SetSelected(parent_item->GetFirstChild()); + // fLT->OpenItem(parent_item); + if (!parent_vol) + fLT->SetSelected(parent_item->GetFirstChild()); } } @@ -423,34 +443,44 @@ void TGeoVolumeDialog::DoClose() void TGeoVolumeDialog::DoItemClick(TGListTreeItem *item, Int_t btn) { - if (btn!=kButton1) return; + if (btn != kButton1) + return; DoSelect(item); - if (!item || !item->GetUserData()) return; + if (!item || !item->GetUserData()) + return; const TGPicture *pic_fld = gClient->GetPicture("folder_t.xpm"); const TGPicture *pic_fldo = gClient->GetPicture("ofolder_t.xpm"); const TGPicture *pic_file = gClient->GetPicture("mdi_default.xpm"); const TGPicture *pic_fileo = gClient->GetPicture("fileopen.xpm"); - TGeoVolume *parent_vol = (TGeoVolume*)item->GetUserData(); + TGeoVolume *parent_vol = (TGeoVolume *)item->GetUserData(); TGeoVolume *vol; TGeoNode *crtnode; TGListTreeItem *daughter_item; - Int_t i,j,ind,icopy; + Int_t i, j, ind, icopy; Int_t nd = parent_vol->GetNdaughters(); - for (i=0; iGetNode(i); vol = crtnode->GetVolume(); // check if the volume is replicated in the parent ind = parent_vol->GetIndex(crtnode); - for (j=0; jGetNode(j)->GetVolume() == vol) break; - if (iGetNode(j)->GetVolume() == vol) + break; + if (i < ind) + continue; icopy++; - for (j=ind+1; jGetNode(j)->GetVolume() == vol) icopy++; - daughter_item = fLT->AddItem(item, ((icopy>1)?(TString::Format("%s (%i)",vol->GetName(),icopy)).Data():vol->GetName()), - vol,((vol->GetNdaughters())?pic_fldo:pic_fileo), ((vol->GetNdaughters())?pic_fld:pic_file)); - if (strlen(vol->GetTitle())) daughter_item->SetTipText(vol->GetTitle()); + for (j = ind + 1; j < nd; j++) + if (parent_vol->GetNode(j)->GetVolume() == vol) + icopy++; + daughter_item = fLT->AddItem( + item, ((icopy > 1) ? (TString::Format("%s (%i)", vol->GetName(), icopy)).Data() : vol->GetName()), vol, + ((vol->GetNdaughters()) ? pic_fldo : pic_fileo), ((vol->GetNdaughters()) ? pic_fld : pic_file)); + if (strlen(vol->GetTitle())) + daughter_item->SetTipText(vol->GetTitle()); } - if (nd) gClient->NeedRedraw(fLT); + if (nd) + gClient->NeedRedraw(fLT); } //////////////////////////////////////////////////////////////////////////////// @@ -459,8 +489,7 @@ void TGeoVolumeDialog::DoItemClick(TGListTreeItem *item, Int_t btn) void TGeoVolumeDialog::ConnectSignalsToSlots() { fClose->Connect("Clicked()", "TGeoVolumeDialog", this, "DoClose()"); - fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoVolumeDialog", this, - "DoItemClick(TGListTreeItem *, Int_t)"); + fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoVolumeDialog", this, "DoItemClick(TGListTreeItem *, Int_t)"); } ClassImp(TGeoShapeDialog); @@ -469,7 +498,7 @@ ClassImp(TGeoShapeDialog); /// Ctor. TGeoShapeDialog::TGeoShapeDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGeoTreeDialog(caller, main, w, h) + : TGeoTreeDialog(caller, main, w, h) { BuildListTree(); ConnectSignalsToSlots(); @@ -488,25 +517,27 @@ void TGeoShapeDialog::BuildListTree() const TGPicture *pic_fld = gClient->GetPicture("folder_t.xpm"); const TGPicture *pic_fldo = gClient->GetPicture("ofolder_t.xpm"); const TGPicture *pic_shape; - TGListTreeItem *parent_item=0; + TGListTreeItem *parent_item = 0; TGeoShape *shape; const char *shapename; TString fld_name; Int_t nshapes = gGeoManager->GetListOfShapes()->GetEntriesFast(); - if (!nshapes) return; + if (!nshapes) + return; // Existing shapes - for (Int_t i=0; iGetListOfShapes()->At(i); - if (!shape) continue; + for (Int_t i = 0; i < nshapes; i++) { + shape = (TGeoShape *)gGeoManager->GetListOfShapes()->At(i); + if (!shape) + continue; shapename = shape->IsA()->GetName(); pic_shape = fClient->GetMimeTypeList()->GetIcon(shapename, kTRUE); fld_name = shapename; // e.g. "TGeoBBox" - fld_name.Remove(0,4); // remove "TGeo" part -> "BBox" + fld_name.Remove(0, 4); // remove "TGeo" part -> "BBox" fld_name += " Shapes"; parent_item = fLT->FindChildByName(NULL, fld_name.Data()); if (!parent_item) { parent_item = fLT->AddItem(NULL, fld_name.Data(), pic_fldo, pic_fld); - parent_item->SetTipText(TString::Format("List of %s shapes",fld_name.Data())); + parent_item->SetTipText(TString::Format("List of %s shapes", fld_name.Data())); } fLT->AddItem(parent_item, shape->GetName(), shape, pic_shape, pic_shape); } @@ -526,9 +557,11 @@ void TGeoShapeDialog::DoClose() void TGeoShapeDialog::DoItemClick(TGListTreeItem *item, Int_t btn) { - if (btn!=kButton1) return; + if (btn != kButton1) + return; DoSelect(item); - if (!item || !item->GetUserData()) return; + if (!item || !item->GetUserData()) + return; } //////////////////////////////////////////////////////////////////////////////// @@ -537,8 +570,7 @@ void TGeoShapeDialog::DoItemClick(TGListTreeItem *item, Int_t btn) void TGeoShapeDialog::ConnectSignalsToSlots() { fClose->Connect("Clicked()", "TGeoShapeDialog", this, "DoClose()"); - fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoShapeDialog", this, - "DoItemClick(TGListTreeItem *, Int_t)"); + fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoShapeDialog", this, "DoItemClick(TGListTreeItem *, Int_t)"); } ClassImp(TGeoMediumDialog); @@ -547,7 +579,7 @@ ClassImp(TGeoMediumDialog); /// Ctor. TGeoMediumDialog::TGeoMediumDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGeoTreeDialog(caller, main, w, h) + : TGeoTreeDialog(caller, main, w, h) { BuildListTree(); ConnectSignalsToSlots(); @@ -563,13 +595,15 @@ TGeoMediumDialog::TGeoMediumDialog(TGFrame *caller, const TGWindow *main, UInt_t void TGeoMediumDialog::BuildListTree() { - const TGPicture *pic_med = gClient->GetPicture("geomedium_t.xpm");; + const TGPicture *pic_med = gClient->GetPicture("geomedium_t.xpm"); + ; TGeoMedium *med; Int_t nmed = gGeoManager->GetListOfMedia()->GetSize(); - if (!nmed) return; + if (!nmed) + return; // Existing media - for (Int_t i=0; iGetListOfMedia()->At(i); + for (Int_t i = 0; i < nmed; i++) { + med = (TGeoMedium *)gGeoManager->GetListOfMedia()->At(i); fLT->AddItem(NULL, med->GetName(), med, pic_med, pic_med); } } @@ -588,10 +622,12 @@ void TGeoMediumDialog::DoClose() void TGeoMediumDialog::DoItemClick(TGListTreeItem *item, Int_t btn) { - if (btn!=kButton1) return; + if (btn != kButton1) + return; DoSelect(item); - if (!item || !item->GetUserData()) return; - //gClient->NeedRedraw(fLT); + if (!item || !item->GetUserData()) + return; + // gClient->NeedRedraw(fLT); } //////////////////////////////////////////////////////////////////////////////// @@ -600,8 +636,7 @@ void TGeoMediumDialog::DoItemClick(TGListTreeItem *item, Int_t btn) void TGeoMediumDialog::ConnectSignalsToSlots() { fClose->Connect("Clicked()", "TGeoMediumDialog", this, "DoClose()"); - fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMediumDialog", this, - "DoItemClick(TGListTreeItem *, Int_t)"); + fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMediumDialog", this, "DoItemClick(TGListTreeItem *, Int_t)"); } ClassImp(TGeoMaterialDialog); @@ -610,7 +645,7 @@ ClassImp(TGeoMaterialDialog); /// Ctor. TGeoMaterialDialog::TGeoMaterialDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGeoTreeDialog(caller, main, w, h) + : TGeoTreeDialog(caller, main, w, h) { BuildListTree(); ConnectSignalsToSlots(); @@ -626,13 +661,15 @@ TGeoMaterialDialog::TGeoMaterialDialog(TGFrame *caller, const TGWindow *main, UI void TGeoMaterialDialog::BuildListTree() { - const TGPicture *pic_mat = gClient->GetPicture("geomaterial_t.xpm");; + const TGPicture *pic_mat = gClient->GetPicture("geomaterial_t.xpm"); + ; TGeoMaterial *mat; Int_t nmat = gGeoManager->GetListOfMaterials()->GetSize(); - if (!nmat) return; + if (!nmat) + return; // Existing materials - for (Int_t i=0; iGetListOfMaterials()->At(i); + for (Int_t i = 0; i < nmat; i++) { + mat = (TGeoMaterial *)gGeoManager->GetListOfMaterials()->At(i); fLT->AddItem(NULL, mat->GetName(), mat, pic_mat, pic_mat); } } @@ -651,10 +688,12 @@ void TGeoMaterialDialog::DoClose() void TGeoMaterialDialog::DoItemClick(TGListTreeItem *item, Int_t btn) { - if (btn!=kButton1) return; + if (btn != kButton1) + return; DoSelect(item); - if (!item || !item->GetUserData()) return; - //gClient->NeedRedraw(fLT); + if (!item || !item->GetUserData()) + return; + // gClient->NeedRedraw(fLT); } //////////////////////////////////////////////////////////////////////////////// @@ -663,8 +702,7 @@ void TGeoMaterialDialog::DoItemClick(TGListTreeItem *item, Int_t btn) void TGeoMaterialDialog::ConnectSignalsToSlots() { fClose->Connect("Clicked()", "TGeoMaterialDialog", this, "DoClose()"); - fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMaterialDialog", this, - "DoItemClick(TGListTreeItem *, Int_t)"); + fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMaterialDialog", this, "DoItemClick(TGListTreeItem *, Int_t)"); } ClassImp(TGeoMatrixDialog); @@ -673,7 +711,7 @@ ClassImp(TGeoMatrixDialog); /// Ctor. TGeoMatrixDialog::TGeoMatrixDialog(TGFrame *caller, const TGWindow *main, UInt_t w, UInt_t h) - :TGeoTreeDialog(caller, main, w, h) + : TGeoTreeDialog(caller, main, w, h) { BuildListTree(); ConnectSignalsToSlots(); @@ -693,37 +731,40 @@ void TGeoMatrixDialog::BuildListTree() const TGPicture *pic_rot = gClient->GetPicture("georotation_t.xpm"); const TGPicture *pic_combi = gClient->GetPicture("geocombi_t.xpm"); const TGPicture *pic; - TGListTreeItem *parent_item=0; + TGListTreeItem *parent_item = 0; TGeoMatrix *matrix; Int_t nmat = gGeoManager->GetListOfMatrices()->GetEntriesFast(); - if (!nmat) return; + if (!nmat) + return; // Existing matrices - for (Int_t i=0; iGetListOfMatrices()->At(i); - if (matrix->IsIdentity()) continue; - if (!strcmp(matrix->IsA()->GetName(),"TGeoTranslation")) { + for (Int_t i = 0; i < nmat; i++) { + matrix = (TGeoMatrix *)gGeoManager->GetListOfMatrices()->At(i); + if (matrix->IsIdentity()) + continue; + if (!strcmp(matrix->IsA()->GetName(), "TGeoTranslation")) { pic = pic_tr; parent_item = fLT->FindChildByName(NULL, "Translations"); if (!parent_item) { parent_item = fLT->AddItem(NULL, "Translations", pic, pic); parent_item->SetTipText("List of translations"); } - } else if (!strcmp(matrix->IsA()->GetName(),"TGeoRotation")) { + } else if (!strcmp(matrix->IsA()->GetName(), "TGeoRotation")) { pic = pic_rot; parent_item = fLT->FindChildByName(NULL, "Rotations"); if (!parent_item) { parent_item = fLT->AddItem(NULL, "Rotations", pic, pic); parent_item->SetTipText("List of rotations"); } - } else if (!strcmp(matrix->IsA()->GetName(),"TGeoCombiTrans") || - !strcmp(matrix->IsA()->GetName(),"TGeoHMatrix")) { + } else if (!strcmp(matrix->IsA()->GetName(), "TGeoCombiTrans") || + !strcmp(matrix->IsA()->GetName(), "TGeoHMatrix")) { pic = pic_combi; parent_item = fLT->FindChildByName(NULL, "Combined"); if (!parent_item) { parent_item = fLT->AddItem(NULL, "Combined", pic, pic); parent_item->SetTipText("List of combined transformations"); } - } else continue; + } else + continue; fLT->AddItem(parent_item, matrix->GetName(), matrix, pic, pic); } } @@ -742,10 +783,12 @@ void TGeoMatrixDialog::DoClose() void TGeoMatrixDialog::DoItemClick(TGListTreeItem *item, Int_t btn) { - if (btn!=kButton1) return; + if (btn != kButton1) + return; DoSelect(item); - if (!item || !item->GetUserData()) return; - //gClient->NeedRedraw(fLT); + if (!item || !item->GetUserData()) + return; + // gClient->NeedRedraw(fLT); } //////////////////////////////////////////////////////////////////////////////// @@ -754,8 +797,7 @@ void TGeoMatrixDialog::DoItemClick(TGListTreeItem *item, Int_t btn) void TGeoMatrixDialog::ConnectSignalsToSlots() { fClose->Connect("Clicked()", "TGeoMatrixDialog", this, "DoClose()"); - fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMatrixDialog", this, - "DoItemClick(TGListTreeItem *, Int_t)"); + fLT->Connect("Clicked(TGListTreeItem *, Int_t)", "TGeoMatrixDialog", this, "DoItemClick(TGListTreeItem *, Int_t)"); } ClassImp(TGeoTransientPanel); @@ -763,8 +805,8 @@ ClassImp(TGeoTransientPanel); //////////////////////////////////////////////////////////////////////////////// /// Transient panel ctor. -TGeoTransientPanel::TGeoTransientPanel(TGedEditor* ged, const char *name, TObject *obj) - :TGMainFrame(gClient->GetRoot(),175,20) +TGeoTransientPanel::TGeoTransientPanel(TGedEditor *ged, const char *name, TObject *obj) + : TGMainFrame(gClient->GetRoot(), 175, 20) { fGedEditor = ged; fModel = obj; @@ -775,17 +817,16 @@ TGeoTransientPanel::TGeoTransientPanel(TGedEditor* ged, const char *name, TObjec fTab->Associate(fCan); fTabContainer = fTab->AddTab(name); fStyle = new TGCompositeFrame(fTabContainer, 110, 30, kVerticalFrame); - fTabContainer->AddFrame(fStyle, new TGLayoutHints(kLHintsTop | kLHintsExpandX,\ - 5, 0, 2, 2)); + fTabContainer->AddFrame(fStyle, new TGLayoutHints(kLHintsTop | kLHintsExpandX, 5, 0, 2, 2)); TString wname = name; wname += " Editor"; SetWindowName(wname.Data()); SetModel(fModel); fClose = new TGTextButton(this, "Close"); - AddFrame(fClose, new TGLayoutHints(kLHintsBottom | kLHintsRight, 0,10,5,5)); + AddFrame(fClose, new TGLayoutHints(kLHintsBottom | kLHintsRight, 0, 10, 5, 5)); MapSubwindows(); Layout(); - Resize(fTabContainer->GetDefaultWidth()+30, fTabContainer->GetDefaultHeight()+65); + Resize(fTabContainer->GetDefaultWidth() + 30, fTabContainer->GetDefaultHeight() + 65); MapWindow(); gROOT->GetListOfCleanups()->Add(this); fClose->Connect("Clicked()", "TGeoTransientPanel", this, "Hide()"); @@ -818,17 +859,18 @@ void TGeoTransientPanel::CloseWindow() void TGeoTransientPanel::GetEditors(TClass *cl) { - TClass *class2 = TClass::GetClass(TString::Format("%sEditor",cl->GetName())); + TClass *class2 = TClass::GetClass(TString::Format("%sEditor", cl->GetName())); if (class2 && class2->InheritsFrom(TGedFrame::Class())) { TGFrameElement *fr; TIter next(fStyle->GetList()); - while ((fr = (TGFrameElement *) next())) - if (fr->fFrame->IsA() == class2) return; + while ((fr = (TGFrameElement *)next())) + if (fr->fFrame->IsA() == class2) + return; TGClient *client = fGedEditor->GetClient(); - TGWindow *exroot = (TGWindow*) client->GetRoot(); + TGWindow *exroot = (TGWindow *)client->GetRoot(); client->SetRoot(fStyle); TGedEditor::SetFrameCreator(fGedEditor); - TGedFrame* gfr = reinterpret_cast(class2->New()); + TGedFrame *gfr = reinterpret_cast(class2->New()); gfr->SetModelClass(cl); TGedEditor::SetFrameCreator(0); client->SetRoot(exroot); @@ -842,17 +884,18 @@ void TGeoTransientPanel::GetEditors(TClass *cl) void TGeoTransientPanel::SetModel(TObject *model) { - if (!model) return; + if (!model) + return; fModel = model; GetEditors(model->IsA()); TGFrameElement *el; TIter next(fStyle->GetList()); - while ((el = (TGFrameElement *) next())) { + while ((el = (TGFrameElement *)next())) { if ((el->fFrame)->InheritsFrom(TGedFrame::Class())) { ((TGedFrame *)(el->fFrame))->SetModel(model); } } - Resize(fTabContainer->GetDefaultWidth()+30, fTabContainer->GetDefaultHeight()+65); + Resize(fTabContainer->GetDefaultWidth() + 30, fTabContainer->GetDefaultHeight() + 65); } //////////////////////////////////////////////////////////////////////////////// @@ -878,5 +921,3 @@ void TGeoTransientPanel::DeleteEditors() { fStyle->Cleanup(); } - - diff --git a/geom/geombuilder/src/TGeoTorusEditor.cxx b/geom/geombuilder/src/TGeoTorusEditor.cxx index 73597164e2859..aee7b4ee7bd38 100644 --- a/geom/geombuilder/src/TGeoTorusEditor.cxx +++ b/geom/geombuilder/src/TGeoTorusEditor.cxx @@ -35,18 +35,23 @@ Editor for a TGeoTorus. ClassImp(TGeoTorusEditor); enum ETGeoTorusWid { - kTORUS_NAME, kTORUS_R, kTORUS_RMIN, kTORUS_RMAX, kTORUS_PHI1, - kTORUS_DPHI, kTORUS_APPLY, kTORUS_UNDO + kTORUS_NAME, + kTORUS_R, + kTORUS_RMIN, + kTORUS_RMAX, + kTORUS_PHI1, + kTORUS_DPHI, + kTORUS_APPLY, + kTORUS_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for torus editor -TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fRi = fRmini = fRmaxi = fPhi1i = fDphii = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -68,7 +73,7 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, fER = new TGNumberEntry(f1, 0., 5, kTORUS_R); fER->SetNumAttr(TGNumberFormat::kNEAPositive); fER->Resize(100, fER->GetDefaultHeight()); - nef = (TGTextEntry*)fER->GetNumberEntry(); + nef = (TGTextEntry *)fER->GetNumberEntry(); nef->SetToolTipText("Enter the axial radius R"); fER->Associate(this); f1->AddFrame(fER, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -80,7 +85,7 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, fERmin = new TGNumberEntry(f1, 0., 5, kTORUS_RMIN); fERmin->SetNumAttr(TGNumberFormat::kNEAPositive); fERmin->Resize(100, fERmin->GetDefaultHeight()); - nef = (TGTextEntry*)fERmin->GetNumberEntry(); + nef = (TGTextEntry *)fERmin->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius Rmin"); fERmin->Associate(this); f1->AddFrame(fERmin, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -92,7 +97,7 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, fERmax = new TGNumberEntry(f1, 0., 5, kTORUS_RMAX); fERmax->SetNumAttr(TGNumberFormat::kNEAPositive); fERmax->Resize(100, fERmax->GetDefaultHeight()); - nef = (TGTextEntry*)fERmax->GetNumberEntry(); + nef = (TGTextEntry *)fERmax->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius Rmax"); fERmax->Associate(this); f1->AddFrame(fERmax, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -104,7 +109,7 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, fEPhi1 = new TGNumberEntry(f1, 0., 5, kTORUS_PHI1); fEPhi1->SetNumAttr(TGNumberFormat::kNEANonNegative); fEPhi1->Resize(100, fEPhi1->GetDefaultHeight()); - nef = (TGTextEntry*)fEPhi1->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi1->GetNumberEntry(); nef->SetToolTipText("Enter the starting phi angle[deg]"); fEPhi1->Associate(this); f1->AddFrame(fEPhi1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -116,7 +121,7 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, fEDphi = new TGNumberEntry(f1, 0., 5, kTORUS_DPHI); fEDphi->SetNumAttr(TGNumberFormat::kNEAPositive); fEDphi->Resize(100, fEDphi->GetDefaultHeight()); - nef = (TGTextEntry*)fEDphi->GetNumberEntry(); + nef = (TGTextEntry *)fEDphi->GetNumberEntry(); nef->SetToolTipText("Enter the extent phi Dphi [deg]"); fEDphi->Associate(this); f1->AddFrame(fEDphi, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -125,8 +130,8 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -134,9 +139,9 @@ TGeoTorusEditor::TGeoTorusEditor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -149,7 +154,7 @@ TGeoTorusEditor::~TGeoTorusEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -175,24 +180,24 @@ void TGeoTorusEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTorusEditor::SetModel(TObject* obj) +void TGeoTorusEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTorus::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTorus::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTorus*)obj; + fShape = (TGeoTorus *)obj; fRi = fShape->GetR(); fRmini = fShape->GetRmin(); fRmaxi = fShape->GetRmax(); fPhi1i = fShape->GetPhi1(); fDphii = fShape->GetDphi(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -205,7 +210,8 @@ void TGeoTorusEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -231,7 +237,8 @@ void TGeoTorusEditor::DoName() void TGeoTorusEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t r = fER->GetNumber(); Double_t rmax = fERmax->GetNumber(); Double_t rmin = fERmin->GetNumber(); @@ -254,11 +261,12 @@ void TGeoTorusEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -292,12 +300,13 @@ void TGeoTorusEditor::DoR() { Double_t r = fER->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rSetNumber(r); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -307,12 +316,13 @@ void TGeoTorusEditor::DoRmin() { Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmin>rmax) { - rmin = rmax-0.1; + if (rmin > rmax) { + rmin = rmax - 0.1; fERmin->SetNumber(rmin); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -323,16 +333,17 @@ void TGeoTorusEditor::DoRmax() Double_t r = fER->GetNumber(); Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmax<=rmin) { - rmax = rmin+0.1; + if (rmax <= rmin) { + rmax = rmin + 0.1; fERmax->SetNumber(rmax); } - if (rmax>r) { + if (rmax > r) { rmax = r; fERmax->SetNumber(rmax); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -341,12 +352,13 @@ void TGeoTorusEditor::DoRmax() void TGeoTorusEditor::DoPhi1() { Double_t phi = fEPhi1->GetNumber(); - if (phi<0 || phi>360) { + if (phi < 0 || phi > 360) { phi = 0; fEPhi1->SetNumber(phi); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -355,11 +367,11 @@ void TGeoTorusEditor::DoPhi1() void TGeoTorusEditor::DoDphi() { Double_t dphi = fEDphi->GetNumber(); - if (dphi<=0 || dphi>360) { + if (dphi <= 0 || dphi > 360) { dphi = 1; fEDphi->SetNumber(dphi); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - diff --git a/geom/geombuilder/src/TGeoTrapEditor.cxx b/geom/geombuilder/src/TGeoTrapEditor.cxx index 6746b7831b1a5..8cd1c2f956e41 100644 --- a/geom/geombuilder/src/TGeoTrapEditor.cxx +++ b/geom/geombuilder/src/TGeoTrapEditor.cxx @@ -35,18 +35,27 @@ Editor for a TGeoTrap. ClassImp(TGeoTrapEditor); enum ETGeoTrapWid { - kTRAP_NAME, kTRAP_H1, kTRAP_BL1, kTRAP_TL1, kTRAP_DZ, kTRAP_ALPHA1, - kTRAP_SC1, kTRAP_SC2, kTRAP_THETA, kTRAP_PHI, kTRAP_APPLY, kTRAP_UNDO + kTRAP_NAME, + kTRAP_H1, + kTRAP_BL1, + kTRAP_TL1, + kTRAP_DZ, + kTRAP_ALPHA1, + kTRAP_SC1, + kTRAP_SC2, + kTRAP_THETA, + kTRAP_PHI, + kTRAP_APPLY, + kTRAP_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for para editor -TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fH1i = fBl1i = fTl1i = fDzi = fAlpha1i = fThetai = fPhii = fSci = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -68,7 +77,7 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, fEH1 = new TGNumberEntry(f1, 0., 5, kTRAP_H1); fEH1->SetNumAttr(TGNumberFormat::kNEAPositive); fEH1->Resize(100, fEH1->GetDefaultHeight()); - nef = (TGTextEntry*)fEH1->GetNumberEntry(); + nef = (TGTextEntry *)fEH1->GetNumberEntry(); nef->SetToolTipText("Enter the half length in y at low z"); fEH1->Associate(this); f1->AddFrame(fEH1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -80,7 +89,7 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, fEBl1 = new TGNumberEntry(f1, 0., 5, kTRAP_BL1); fEBl1->SetNumAttr(TGNumberFormat::kNEAPositive); fEBl1->Resize(100, fEBl1->GetDefaultHeight()); - nef = (TGTextEntry*)fEBl1->GetNumberEntry(); + nef = (TGTextEntry *)fEBl1->GetNumberEntry(); nef->SetToolTipText("Enter the half length in x at low z and y low edge"); fEBl1->Associate(this); f1->AddFrame(fEBl1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -92,43 +101,43 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, fETl1 = new TGNumberEntry(f1, 0., 5, kTRAP_TL1); fETl1->SetNumAttr(TGNumberFormat::kNEAPositive); fETl1->Resize(100, fETl1->GetDefaultHeight()); - nef = (TGTextEntry*)fETl1->GetNumberEntry(); + nef = (TGTextEntry *)fETl1->GetNumberEntry(); nef->SetToolTipText("Enter the half length in x at low z and y high edge"); fETl1->Associate(this); f1->AddFrame(fETl1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - // Number entry for scale factor + // Number entry for scale factor f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "SC1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fESc1 = new TGNumberEntry(f1, 0., 5, kTRAP_SC1); fESc1->SetNumAttr(TGNumberFormat::kNEAPositive); fESc1->Resize(100, fESc1->GetDefaultHeight()); - nef = (TGTextEntry*)fESc1->GetNumberEntry(); + nef = (TGTextEntry *)fESc1->GetNumberEntry(); nef->SetToolTipText("Enter the scale factor for lower Z face"); fESc1->Associate(this); f1->AddFrame(fESc1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - // Number entry for scale factor + // Number entry for scale factor f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "SC2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fESc2 = new TGNumberEntry(f1, 0., 5, kTRAP_SC2); fESc2->SetNumAttr(TGNumberFormat::kNEAPositive); fESc2->Resize(100, fESc2->GetDefaultHeight()); - nef = (TGTextEntry*)fESc2->GetNumberEntry(); + nef = (TGTextEntry *)fESc2->GetNumberEntry(); nef->SetToolTipText("Enter the scale factor for upper Z face"); fESc2->Associate(this); f1->AddFrame(fESc2, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - // Number entry for dz + // Number entry for dz f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDz = new TGNumberEntry(f1, 0., 5, kTRAP_DZ); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); fEDz->Resize(100, fEDz->GetDefaultHeight()); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Z"); fEDz->Associate(this); f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -139,7 +148,7 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "ALPHA"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEAlpha1 = new TGNumberEntry(f1, 0., 5, kTRAP_ALPHA1); fEAlpha1->Resize(100, fEAlpha1->GetDefaultHeight()); - nef = (TGTextEntry*)fEAlpha1->GetNumberEntry(); + nef = (TGTextEntry *)fEAlpha1->GetNumberEntry(); nef->SetToolTipText("Enter angle between centers of x edges an y axis at low z"); fEAlpha1->Associate(this); f1->AddFrame(fEAlpha1, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -151,19 +160,19 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, fETheta = new TGNumberEntry(f1, 0., 5, kTRAP_THETA); fETheta->SetNumAttr(TGNumberFormat::kNEAPositive); fETheta->Resize(100, fETheta->GetDefaultHeight()); - nef = (TGTextEntry*)fETheta->GetNumberEntry(); + nef = (TGTextEntry *)fETheta->GetNumberEntry(); nef->SetToolTipText("Enter initial theta"); fETheta->Associate(this); f1->AddFrame(fETheta, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - // Number entry for Phi + // Number entry for Phi f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "Phi"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEPhi = new TGNumberEntry(f1, 0., 5, kTRAP_PHI); fEPhi->SetNumAttr(TGNumberFormat::kNEAPositive); fEPhi->Resize(100, fEPhi->GetDefaultHeight()); - nef = (TGTextEntry*)fEPhi->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi->GetNumberEntry(); nef->SetToolTipText("Enter initial phi"); fEPhi->Associate(this); f1->AddFrame(fEPhi, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -172,8 +181,8 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, // Delayed draw fDFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(fDFrame, "Delayed draw"); - fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons fBFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -181,9 +190,9 @@ TGeoTrapEditor::TGeoTrapEditor(const TGWindow *p, Int_t width, fBFrame->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(fBFrame, "Undo"); - fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -196,7 +205,7 @@ TGeoTrapEditor::~TGeoTrapEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -233,26 +242,27 @@ void TGeoTrapEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTrapEditor::SetModel(TObject* obj) +void TGeoTrapEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTrap::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTrap::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTrap*)obj; + fShape = (TGeoTrap *)obj; fH1i = fShape->GetH1(); fBl1i = fShape->GetBl1(); fTl1i = fShape->GetTl1(); fDzi = fShape->GetDz(); Double_t h2i = fShape->GetH2(); -// Double_t bl2i = fShape->GetBl2(); -// Double_t tl2i = fShape->GetTl2(); - fSci = h2i/fH1i; + // Double_t bl2i = fShape->GetBl2(); + // Double_t tl2i = fShape->GetTl2(); + fSci = h2i / fH1i; fAlpha1i = fShape->GetAlpha1(); fThetai = fShape->GetTheta(); fPhii = fShape->GetPhi(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -269,7 +279,8 @@ void TGeoTrapEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -295,15 +306,16 @@ void TGeoTrapEditor::DoName() void TGeoTrapEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t sc1 = fESc1->GetNumber(); Double_t sc2 = fESc2->GetNumber(); - Double_t h1 = sc1*fEH1->GetNumber(); - Double_t bl1 = sc1*fEBl1->GetNumber(); - Double_t tl1 = sc1*fETl1->GetNumber(); - Double_t h2 = sc2*fEH1->GetNumber(); - Double_t bl2 = sc2*fEBl1->GetNumber(); - Double_t tl2 = sc2*fETl1->GetNumber(); + Double_t h1 = sc1 * fEH1->GetNumber(); + Double_t bl1 = sc1 * fEBl1->GetNumber(); + Double_t tl1 = sc1 * fETl1->GetNumber(); + Double_t h2 = sc2 * fEH1->GetNumber(); + Double_t bl2 = sc2 * fEBl1->GetNumber(); + Double_t tl2 = sc2 * fETl1->GetNumber(); Double_t dz = fEDz->GetNumber(); Double_t alpha1 = fEAlpha1->GetNumber(); Double_t theta = fETheta->GetNumber(); @@ -331,11 +343,12 @@ void TGeoTrapEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -372,12 +385,13 @@ void TGeoTrapEditor::DoUndo() void TGeoTrapEditor::DoH1() { Double_t h1 = fEH1->GetNumber(); - if (h1<=0) { + if (h1 <= 0) { h1 = 0.1; fEH1->SetNumber(h1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -386,12 +400,13 @@ void TGeoTrapEditor::DoH1() void TGeoTrapEditor::DoBl1() { Double_t bl1 = fEBl1->GetNumber(); - if (bl1<=0) { + if (bl1 <= 0) { bl1 = 0.1; fEBl1->SetNumber(bl1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -400,12 +415,13 @@ void TGeoTrapEditor::DoBl1() void TGeoTrapEditor::DoTl1() { Double_t tl1 = fETl1->GetNumber(); - if (tl1<=0) { + if (tl1 <= 0) { tl1 = 0.1; fETl1->SetNumber(tl1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -414,12 +430,13 @@ void TGeoTrapEditor::DoTl1() void TGeoTrapEditor::DoDz() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -428,12 +445,13 @@ void TGeoTrapEditor::DoDz() void TGeoTrapEditor::DoSc1() { Double_t sc1 = fESc1->GetNumber(); - if (sc1<=0) { + if (sc1 <= 0) { sc1 = 0.1; fESc1->SetNumber(sc1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -442,12 +460,13 @@ void TGeoTrapEditor::DoSc1() void TGeoTrapEditor::DoSc2() { Double_t sc2 = fESc2->GetNumber(); - if (sc2<=0) { + if (sc2 <= 0) { sc2 = 0.1; fESc2->SetNumber(sc2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -456,12 +475,13 @@ void TGeoTrapEditor::DoSc2() void TGeoTrapEditor::DoAlpha1() { Double_t alpha1 = fEAlpha1->GetNumber(); - if (TMath::Abs(alpha1)>=90) { - alpha1 = 89.9*TMath::Sign(1.,alpha1); + if (TMath::Abs(alpha1) >= 90) { + alpha1 = 89.9 * TMath::Sign(1., alpha1); fEAlpha1->SetNumber(alpha1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -470,16 +490,17 @@ void TGeoTrapEditor::DoAlpha1() void TGeoTrapEditor::DoTheta() { Double_t theta = fETheta->GetNumber(); - if (theta<0) { + if (theta < 0) { theta = 0; fETheta->SetNumber(theta); } - if (theta>180) { + if (theta > 180) { theta = 180; fETheta->SetNumber(theta); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -488,19 +509,18 @@ void TGeoTrapEditor::DoTheta() void TGeoTrapEditor::DoPhi() { Double_t phi = fEPhi->GetNumber(); - if (phi<0 || phi>360) { + if (phi < 0 || phi > 360) { phi = 0; fEPhi->SetNumber(phi); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } ClassImp(TGeoGtraEditor); -enum ETGeoGtraWid { - kGTRA_TWIST -}; +enum ETGeoGtraWid { kGTRA_TWIST }; /** \class TGeoGtraEditor \ingroup Geometry_builder @@ -516,8 +536,7 @@ Editor for a TGeoGtra. //////////////////////////////////////////////////////////////////////////////// /// Constructor for gtra editor -TGeoGtraEditor::TGeoGtraEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoGtraEditor::TGeoGtraEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoTrapEditor(p, width, height, options, back) { fTwisti = 0; @@ -527,7 +546,7 @@ TGeoGtraEditor::TGeoGtraEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "TWIST"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fETwist = new TGNumberEntry(f1, 0., 5, kGTRA_TWIST); fETwist->Resize(100, fETwist->GetDefaultHeight()); - nef = (TGTextEntry*)fETwist->GetNumberEntry(); + nef = (TGTextEntry *)fETwist->GetNumberEntry(); nef->SetToolTipText("Enter twist angle"); fETwist->Associate(this); f1->AddFrame(fETwist, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); @@ -546,7 +565,7 @@ TGeoGtraEditor::~TGeoGtraEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -554,27 +573,28 @@ TGeoGtraEditor::~TGeoGtraEditor() //////////////////////////////////////////////////////////////////////////////// /// Connect to a given twisted trapezoid. -void TGeoGtraEditor::SetModel(TObject* obj) +void TGeoGtraEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoGtra::Class())) { + if (obj == 0 || (obj->IsA() != TGeoGtra::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTrap*)obj; + fShape = (TGeoTrap *)obj; fH1i = fShape->GetH1(); fBl1i = fShape->GetBl1(); fTl1i = fShape->GetTl1(); fDzi = fShape->GetDz(); Double_t h2i = fShape->GetH2(); -// Double_t bl2i = fShape->GetBl2(); -// Double_t tl2i = fShape->GetTl2(); - fSci = h2i/fH1i; + // Double_t bl2i = fShape->GetBl2(); + // Double_t tl2i = fShape->GetTl2(); + fSci = h2i / fH1i; fAlpha1i = fShape->GetAlpha1(); fThetai = fShape->GetTheta(); fPhii = fShape->GetPhi(); - fTwisti = ((TGeoGtra*)fShape)->GetTwistAngle(); + fTwisti = ((TGeoGtra *)fShape)->GetTwistAngle(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -592,7 +612,8 @@ void TGeoGtraEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -602,15 +623,16 @@ void TGeoGtraEditor::SetModel(TObject* obj) void TGeoGtraEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t sc1 = fESc1->GetNumber(); Double_t sc2 = fESc2->GetNumber(); - Double_t h1 = sc1*fEH1->GetNumber(); - Double_t bl1 = sc1*fEBl1->GetNumber(); - Double_t tl1 = sc1*fETl1->GetNumber(); - Double_t h2 = sc2*fEH1->GetNumber(); - Double_t bl2 = sc2*fEBl1->GetNumber(); - Double_t tl2 = sc2*fETl1->GetNumber(); + Double_t h1 = sc1 * fEH1->GetNumber(); + Double_t bl1 = sc1 * fEBl1->GetNumber(); + Double_t tl1 = sc1 * fETl1->GetNumber(); + Double_t h2 = sc2 * fEH1->GetNumber(); + Double_t bl2 = sc2 * fEBl1->GetNumber(); + Double_t tl2 = sc2 * fETl1->GetNumber(); Double_t dz = fEDz->GetNumber(); Double_t alpha1 = fEAlpha1->GetNumber(); Double_t theta = fETheta->GetNumber(); @@ -629,7 +651,7 @@ void TGeoGtraEditor::DoApply() param[6] = alpha1; param[10] = alpha1; param[11] = twist; - TGeoGtra *shape = (TGeoGtra*)fShape; + TGeoGtra *shape = (TGeoGtra *)fShape; shape->SetDimensions(param); shape->ComputeBBox(); fUndo->SetEnabled(); @@ -641,11 +663,12 @@ void TGeoGtraEditor::DoApply() fShape->Draw(); fPad->GetView()->ShowAxis(); } else { - view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), - fShape->GetDX(), fShape->GetDY(), fShape->GetDZ()); + view->SetRange(-fShape->GetDX(), -fShape->GetDY(), -fShape->GetDZ(), fShape->GetDX(), fShape->GetDY(), + fShape->GetDZ()); Update(); } - } else Update(); + } else + Update(); } } @@ -675,10 +698,11 @@ void TGeoGtraEditor::DoUndo() void TGeoGtraEditor::DoTwist() { Double_t twist = fETwist->GetNumber(); - if (twist<=-180 || twist>=180) { + if (twist <= -180 || twist >= 180) { twist = 0.; fETwist->SetNumber(twist); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } diff --git a/geom/geombuilder/src/TGeoTrd1Editor.cxx b/geom/geombuilder/src/TGeoTrd1Editor.cxx index e74a34d1692f2..75157186ed3ac 100644 --- a/geom/geombuilder/src/TGeoTrd1Editor.cxx +++ b/geom/geombuilder/src/TGeoTrd1Editor.cxx @@ -34,19 +34,15 @@ Editor for a TGeoTrd1. ClassImp(TGeoTrd1Editor); -enum ETGeoTrd1Wid { - kTRD1_NAME, kTRD1_X1, kTRD1_X2, kTRD1_Y, kTRD1_Z, - kTRD1_APPLY, kTRD1_UNDO -}; +enum ETGeoTrd1Wid { kTRD1_NAME, kTRD1_X1, kTRD1_X2, kTRD1_Y, kTRD1_Z, kTRD1_APPLY, kTRD1_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for trd1 editor -TGeoTrd1Editor::TGeoTrd1Editor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTrd1Editor::TGeoTrd1Editor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fDxi1 = fDxi2 = fDyi = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -65,61 +61,60 @@ TGeoTrd1Editor::TGeoTrd1Editor(const TGWindow *p, Int_t width, TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for dx1 - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDx1 = new TGNumberEntry(f1, 0., 5, kTRD1_X1); fEDx1->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDx1->GetNumberEntry(); + nef = (TGTextEntry *)fEDx1->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in X1"); fEDx1->Associate(this); - f1->AddFrame(fEDx1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fEDx1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dx2 - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDx2 = new TGNumberEntry(f1, 0., 5, kTRD1_X2); fEDx2->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDx2->GetNumberEntry(); + nef = (TGTextEntry *)fEDx2->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in X2"); fEDx2->Associate(this); - f1->AddFrame(fEDx2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fEDx2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dy - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDy = new TGNumberEntry(f2, 0., 5, kTRD1_Y); fEDy->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDy->GetNumberEntry(); + nef = (TGTextEntry *)fEDy->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Y"); fEDy->Associate(this); - f2->AddFrame(fEDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f2->AddFrame(fEDy, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dz - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDz = new TGNumberEntry(f3, 0., 5, kTRD1_Z); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Z"); fEDz->Associate(this); - f3->AddFrame(fEDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f3->AddFrame(fEDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -127,9 +122,9 @@ TGeoTrd1Editor::TGeoTrd1Editor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -142,7 +137,7 @@ TGeoTrd1Editor::~TGeoTrd1Editor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -166,23 +161,23 @@ void TGeoTrd1Editor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTrd1Editor::SetModel(TObject* obj) +void TGeoTrd1Editor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTrd1::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTrd1::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTrd1*)obj; + fShape = (TGeoTrd1 *)obj; fDxi1 = fShape->GetDx1(); fDxi2 = fShape->GetDx2(); fDyi = fShape->GetDy(); fDzi = fShape->GetDz(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -194,8 +189,8 @@ void TGeoTrd1Editor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -221,7 +216,8 @@ void TGeoTrd1Editor::DoName() void TGeoTrd1Editor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); Double_t dy = fEDy->GetNumber(); @@ -239,7 +235,8 @@ void TGeoTrd1Editor::DoApply() if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -272,16 +269,17 @@ void TGeoTrd1Editor::DoDx1() { Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); - if (dx1<0) { + if (dx1 < 0) { dx1 = 0; fEDx1->SetNumber(dx1); } - if (dx1<1.e-6 && dx2<1.e-6) { + if (dx1 < 1.e-6 && dx2 < 1.e-6) { dx1 = 0.1; fEDx1->SetNumber(dx1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -291,16 +289,17 @@ void TGeoTrd1Editor::DoDx2() { Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); - if (dx2<0) { + if (dx2 < 0) { dx2 = 0; fEDx2->SetNumber(dx2); } - if (dx1<1.e-6 && dx2<1.e-6) { + if (dx1 < 1.e-6 && dx2 < 1.e-6) { dx2 = 0.1; fEDx2->SetNumber(dx2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -309,12 +308,13 @@ void TGeoTrd1Editor::DoDx2() void TGeoTrd1Editor::DoDy() { Double_t dy = fEDy->GetNumber(); - if (dy<=0) { + if (dy <= 0) { dy = 0.1; fEDy->SetNumber(dy); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -323,12 +323,11 @@ void TGeoTrd1Editor::DoDy() void TGeoTrd1Editor::DoDz() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - - diff --git a/geom/geombuilder/src/TGeoTrd2Editor.cxx b/geom/geombuilder/src/TGeoTrd2Editor.cxx index d47a32720f889..54151f019450b 100644 --- a/geom/geombuilder/src/TGeoTrd2Editor.cxx +++ b/geom/geombuilder/src/TGeoTrd2Editor.cxx @@ -34,19 +34,15 @@ Editor for a TGeoTrd2. ClassImp(TGeoTrd2Editor); -enum ETGeoTrd2Wid { - kTRD2_NAME, kTRD2_X1, kTRD2_X2, kTRD2_Y1, kTRD2_Y2, kTRD2_Z, - kTRD2_APPLY, kTRD2_UNDO -}; +enum ETGeoTrd2Wid { kTRD2_NAME, kTRD2_X1, kTRD2_X2, kTRD2_Y1, kTRD2_Y2, kTRD2_Z, kTRD2_APPLY, kTRD2_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for trd2 editor -TGeoTrd2Editor::TGeoTrd2Editor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTrd2Editor::TGeoTrd2Editor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fDxi1 = fDxi2 = fDyi1 = fDyi2 = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -65,73 +61,71 @@ TGeoTrd2Editor::TGeoTrd2Editor(const TGWindow *p, Int_t width, TGCompositeFrame *compxyz = new TGCompositeFrame(this, 118, 30, kVerticalFrame | kRaisedFrame | kDoubleBorder); // Number entry for dx1 - TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f1 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDx1 = new TGNumberEntry(f1, 0., 5, kTRD2_X1); fEDx1->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDx1->GetNumberEntry(); + nef = (TGTextEntry *)fEDx1->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in X1"); fEDx1->Associate(this); - f1->AddFrame(fEDx1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fEDx1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dx2 - f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f1 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, "DX2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDx2 = new TGNumberEntry(f1, 0., 5, kTRD2_X2); fEDx2->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDx2->GetNumberEntry(); + nef = (TGTextEntry *)fEDx2->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in X2"); fEDx2->Associate(this); - f1->AddFrame(fEDx2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f1->AddFrame(fEDx2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dy1 - TGCompositeFrame *f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f2 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY1"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDy1 = new TGNumberEntry(f2, 0., 5, kTRD2_Y1); fEDy1->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDy1->GetNumberEntry(); + nef = (TGTextEntry *)fEDy1->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Y1"); fEDy1->Associate(this); - f2->AddFrame(fEDy1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f2->AddFrame(fEDy1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dy2 - f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + f2 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f2->AddFrame(new TGLabel(f2, "DY2"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDy2 = new TGNumberEntry(f2, 0., 5, kTRD2_Y2); fEDy2->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDy2->GetNumberEntry(); + nef = (TGTextEntry *)fEDy2->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Y2"); fEDy2->Associate(this); - f2->AddFrame(fEDy2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f2->AddFrame(fEDy2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f2, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); // Number entry for dz - TGCompositeFrame *f3 = new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | - kLHintsExpandX | kFixedWidth | kOwnBackground); + TGCompositeFrame *f3 = + new TGCompositeFrame(compxyz, 118, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f3->AddFrame(new TGLabel(f3, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDz = new TGNumberEntry(f3, 0., 5, kTRD2_Z); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the half-length in Z"); fEDz->Associate(this); - f3->AddFrame(fEDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); - compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + f3->AddFrame(fEDz, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); + compxyz->AddFrame(f3, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); - compxyz->Resize(150,30); + compxyz->Resize(150, 30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Delayed draw f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(f1, "Delayed draw"); - f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + f1->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Buttons f1 = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -139,9 +133,9 @@ TGeoTrd2Editor::TGeoTrd2Editor(const TGWindow *p, Int_t width, f1->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(f1, "Undo"); - f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + f1->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(f1, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -154,7 +148,7 @@ TGeoTrd2Editor::~TGeoTrd2Editor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -180,24 +174,24 @@ void TGeoTrd2Editor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTrd2Editor::SetModel(TObject* obj) +void TGeoTrd2Editor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTrd2::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTrd2::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTrd2*)obj; + fShape = (TGeoTrd2 *)obj; fDxi1 = fShape->GetDx1(); fDxi2 = fShape->GetDx2(); fDyi1 = fShape->GetDy1(); fDyi2 = fShape->GetDy2(); fDzi = fShape->GetDz(); const char *sname = fShape->GetName(); - if (!strcmp(sname, fShape->ClassName())) fShapeName->SetText("-no_name"); + if (!strcmp(sname, fShape->ClassName())) + fShapeName->SetText("-no_name"); else { fShapeName->SetText(sname); fNamei = sname; @@ -210,7 +204,8 @@ void TGeoTrd2Editor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -236,7 +231,8 @@ void TGeoTrd2Editor::DoName() void TGeoTrd2Editor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); Double_t dy1 = fEDy1->GetNumber(); @@ -256,7 +252,8 @@ void TGeoTrd2Editor::DoApply() if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -290,16 +287,17 @@ void TGeoTrd2Editor::DoDx1() { Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); - if (dx1<0) { + if (dx1 < 0) { dx1 = 0; fEDx1->SetNumber(dx1); } - if (dx1<1.e-6 && dx2<1.e-6) { + if (dx1 < 1.e-6 && dx2 < 1.e-6) { dx1 = 0.1; fEDx1->SetNumber(dx1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -309,16 +307,17 @@ void TGeoTrd2Editor::DoDx2() { Double_t dx1 = fEDx1->GetNumber(); Double_t dx2 = fEDx2->GetNumber(); - if (dx2<0) { + if (dx2 < 0) { dx2 = 0; fEDx2->SetNumber(dx2); } - if (dx1<1.e-6 && dx2<1.e-6) { + if (dx1 < 1.e-6 && dx2 < 1.e-6) { dx2 = 0.1; fEDx2->SetNumber(dx2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -328,16 +327,17 @@ void TGeoTrd2Editor::DoDy1() { Double_t dy1 = fEDy1->GetNumber(); Double_t dy2 = fEDy2->GetNumber(); - if (dy1<0) { + if (dy1 < 0) { dy1 = 0; fEDy1->SetNumber(dy1); } - if (dy1<1.e-6 && dy2<1.e-6) { + if (dy1 < 1.e-6 && dy2 < 1.e-6) { dy1 = 0.1; fEDy1->SetNumber(dy1); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -347,16 +347,17 @@ void TGeoTrd2Editor::DoDy2() { Double_t dy1 = fEDy1->GetNumber(); Double_t dy2 = fEDy2->GetNumber(); - if (dy2<0) { + if (dy2 < 0) { dy2 = 0; fEDy2->SetNumber(dy2); } - if (dy1<1.e-6 && dy2<1.e-6) { + if (dy1 < 1.e-6 && dy2 < 1.e-6) { dy2 = 0.1; fEDy2->SetNumber(dy2); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -365,12 +366,11 @@ void TGeoTrd2Editor::DoDy2() void TGeoTrd2Editor::DoDz() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } - - diff --git a/geom/geombuilder/src/TGeoTubeEditor.cxx b/geom/geombuilder/src/TGeoTubeEditor.cxx index 35090f5b6aafb..b0423718c60cb 100644 --- a/geom/geombuilder/src/TGeoTubeEditor.cxx +++ b/geom/geombuilder/src/TGeoTubeEditor.cxx @@ -36,19 +36,15 @@ Editor for a TGeoTube. ClassImp(TGeoTubeEditor); -enum ETGeoTubeWid { - kTUBE_NAME, kTUBE_RMIN, kTUBE_RMAX, kTUBE_Z, - kTUBE_APPLY, kTUBE_UNDO -}; +enum ETGeoTubeWid { kTUBE_NAME, kTUBE_RMIN, kTUBE_RMAX, kTUBE_Z, kTUBE_APPLY, kTUBE_UNDO }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for tube editor -TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { - fShape = 0; + fShape = 0; fRmini = fRmaxi = fDzi = 0.0; fNamei = ""; fIsModified = kFALSE; @@ -70,11 +66,11 @@ TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Rmin"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmin = new TGNumberEntry(f1, 0., 5, kTUBE_RMIN); fERmin->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmin->GetNumberEntry(); + nef = (TGTextEntry *)fERmin->GetNumberEntry(); nef->SetToolTipText("Enter the inner radius"); fERmin->Associate(this); - fERmin->Resize(100,fERmin->GetDefaultHeight()); - f1->AddFrame(fERmin, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + fERmin->Resize(100, fERmin->GetDefaultHeight()); + f1->AddFrame(fERmin, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); // Number entry for Rmax @@ -82,11 +78,11 @@ TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "Rmax"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fERmax = new TGNumberEntry(f1, 0., 5, kTUBE_RMAX); fERmax->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fERmax->GetNumberEntry(); + nef = (TGTextEntry *)fERmax->GetNumberEntry(); nef->SetToolTipText("Enter the outer radius"); fERmax->Associate(this); - fERmax->Resize(100,fERmax->GetDefaultHeight()); - f1->AddFrame(fERmax, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + fERmax->Resize(100, fERmax->GetDefaultHeight()); + f1->AddFrame(fERmax, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); // Number entry for dz @@ -94,21 +90,21 @@ TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "DZ"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEDz = new TGNumberEntry(f1, 0., 5, kTUBE_Z); fEDz->SetNumAttr(TGNumberFormat::kNEAPositive); - nef = (TGTextEntry*)fEDz->GetNumberEntry(); + nef = (TGTextEntry *)fEDz->GetNumberEntry(); nef->SetToolTipText("Enter the tube half-lenth in Z"); fEDz->Associate(this); - fEDz->Resize(100,fEDz->GetDefaultHeight()); - f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + fEDz->Resize(100, fEDz->GetDefaultHeight()); + f1->AddFrame(fEDz, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); -// compxyz->Resize(150,30); + // compxyz->Resize(150,30); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); // Delayed draw fDFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame); fDelayed = new TGCheckButton(fDFrame, "Delayed draw"); - fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft , 2, 2, 4, 4)); - AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + fDFrame->AddFrame(fDelayed, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); + AddFrame(fDFrame, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); // Buttons fBFrame = new TGCompositeFrame(this, 155, 10, kHorizontalFrame | kFixedWidth); @@ -116,9 +112,9 @@ TGeoTubeEditor::TGeoTubeEditor(const TGWindow *p, Int_t width, fBFrame->AddFrame(fApply, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); fApply->Associate(this); fUndo = new TGTextButton(fBFrame, "Undo"); - fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); + fBFrame->AddFrame(fUndo, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); fUndo->Associate(this); - AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); + AddFrame(fBFrame, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); fUndo->SetSize(fApply->GetSize()); } @@ -131,7 +127,7 @@ TGeoTubeEditor::~TGeoTubeEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -153,17 +149,16 @@ void TGeoTubeEditor::ConnectSignals2Slots() fInit = kFALSE; } - //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTubeEditor::SetModel(TObject* obj) +void TGeoTubeEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTube::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTube::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTube*)obj; + fShape = (TGeoTube *)obj; fRmini = fShape->GetRmin(); fRmaxi = fShape->GetRmax(); fDzi = fShape->GetDz(); @@ -175,7 +170,8 @@ void TGeoTubeEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -201,7 +197,8 @@ void TGeoTubeEditor::DoName() void TGeoTubeEditor::DoApply() { const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); Double_t dz = fEDz->GetNumber(); @@ -213,7 +210,8 @@ void TGeoTubeEditor::DoApply() if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -245,12 +243,13 @@ void TGeoTubeEditor::DoRmin() { Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmaxSetNumber(rmin); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -264,12 +263,13 @@ void TGeoTubeEditor::DoRmax() rmax = 0.1; fERmax->SetNumber(rmax); } - if (rmaxSetNumber(rmax); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -278,12 +278,13 @@ void TGeoTubeEditor::DoRmax() void TGeoTubeEditor::DoDz() { Double_t dz = fEDz->GetNumber(); - if (dz<=0) { + if (dz <= 0) { dz = 0.1; fEDz->SetNumber(dz); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } /** \class TGeoTubeSegEditor @@ -299,24 +300,22 @@ Editor for a TGeoTubeSeg. ClassImp(TGeoTubeSegEditor); -enum ETGeoTubeSegWid { - kTUBESEG_PHI1, kTUBESEG_PHI2, kTUBESEG_PHI -}; +enum ETGeoTubeSegWid { kTUBESEG_PHI1, kTUBESEG_PHI2, kTUBESEG_PHI }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for tube segment editor -TGeoTubeSegEditor::TGeoTubeSegEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) - : TGeoTubeEditor(p, width, height, options | kVerticalFrame, back) +TGeoTubeSegEditor::TGeoTubeSegEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGeoTubeEditor(p, width, height, options | kVerticalFrame, back) { fLock = kFALSE; MakeTitle("Phi range"); TGTextEntry *nef; - TGCompositeFrame *compxyz = new TGCompositeFrame(this, 155, 110, kHorizontalFrame | kFixedWidth | kFixedHeight | kRaisedFrame); + TGCompositeFrame *compxyz = + new TGCompositeFrame(this, 155, 110, kHorizontalFrame | kFixedWidth | kFixedHeight | kRaisedFrame); // Vertical slider - fSPhi = new TGDoubleVSlider(compxyz,100); - fSPhi->SetRange(0.,720.); + fSPhi = new TGDoubleVSlider(compxyz, 100); + fSPhi->SetRange(0., 720.); fSPhi->Resize(fSPhi->GetDefaultWidth(), 100); compxyz->AddFrame(fSPhi, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); TGCompositeFrame *f1 = new TGCompositeFrame(compxyz, 135, 100, kVerticalFrame | kFixedHeight); @@ -324,7 +323,7 @@ TGeoTubeSegEditor::TGeoTubeSegEditor(const TGWindow *p, Int_t width, fEPhi1 = new TGNumberEntry(f1, 0., 5, kTUBESEG_PHI1); fEPhi1->Resize(100, fEPhi1->GetDefaultHeight()); fEPhi1->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi1->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi1->GetNumberEntry(); nef->SetToolTipText("Enter the phi1 value"); fEPhi1->Associate(this); f1->AddFrame(fEPhi1, new TGLayoutHints(kLHintsTop | kLHintsRight, 2, 2, 2, 2)); @@ -332,14 +331,14 @@ TGeoTubeSegEditor::TGeoTubeSegEditor(const TGWindow *p, Int_t width, fEPhi2 = new TGNumberEntry(f1, 0., 5, kTUBESEG_PHI2); fEPhi2->Resize(100, fEPhi2->GetDefaultHeight()); fEPhi2->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhi2->GetNumberEntry(); + nef = (TGTextEntry *)fEPhi2->GetNumberEntry(); nef->SetToolTipText("Enter the phi2 value"); fEPhi2->Associate(this); f1->AddFrame(fEPhi2, new TGLayoutHints(kLHintsBottom | kLHintsRight, 2, 2, 2, 2)); f1->AddFrame(new TGLabel(f1, "Phi max."), new TGLayoutHints(kLHintsBottom, 0, 0, 6, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); -// compxyz->Resize(150,150); + // compxyz->Resize(150,150); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 6, 6, 4, 4)); TGeoTabManager::MoveFrame(fDFrame, this); TGeoTabManager::MoveFrame(fBFrame, this); @@ -354,7 +353,7 @@ TGeoTubeSegEditor::~TGeoTubeSegEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -365,44 +364,45 @@ TGeoTubeSegEditor::~TGeoTubeSegEditor() void TGeoTubeSegEditor::ConnectSignals2Slots() { TGeoTubeEditor::ConnectSignals2Slots(); - Disconnect(fApply, "Clicked()",(TGeoTubeEditor*)this, "DoApply()"); - Disconnect(fUndo, "Clicked()",(TGeoTubeEditor*)this, "DoUndo()"); + Disconnect(fApply, "Clicked()", (TGeoTubeEditor *)this, "DoApply()"); + Disconnect(fUndo, "Clicked()", (TGeoTubeEditor *)this, "DoUndo()"); fApply->Connect("Clicked()", "TGeoTubeSegEditor", this, "DoApply()"); fUndo->Connect("Clicked()", "TGeoTubeSegEditor", this, "DoUndo()"); fEPhi1->Connect("ValueSet(Long_t)", "TGeoTubeSegEditor", this, "DoPhi1()"); fEPhi2->Connect("ValueSet(Long_t)", "TGeoTubeSegEditor", this, "DoPhi2()"); -// fEPhi1->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoTubeSegEditor", this, "DoPhi1()"); -// fEPhi2->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoTubeSegEditor", this, "DoPhi2()"); - fSPhi->Connect("PositionChanged()","TGeoTubeSegEditor", this, "DoPhi()"); + // fEPhi1->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoTubeSegEditor", this, "DoPhi1()"); + // fEPhi2->GetNumberEntry()->Connect("TextChanged(const char *)","TGeoTubeSegEditor", this, "DoPhi2()"); + fSPhi->Connect("PositionChanged()", "TGeoTubeSegEditor", this, "DoPhi()"); } //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoTubeSegEditor::SetModel(TObject* obj) +void TGeoTubeSegEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoTubeSeg::Class())) { + if (obj == 0 || (obj->IsA() != TGeoTubeSeg::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTube*)obj; + fShape = (TGeoTube *)obj; fRmini = fShape->GetRmin(); fRmaxi = fShape->GetRmax(); fDzi = fShape->GetDz(); fNamei = fShape->GetName(); - fPmini = ((TGeoTubeSeg*)fShape)->GetPhi1(); - fPmaxi = ((TGeoTubeSeg*)fShape)->GetPhi2(); + fPmini = ((TGeoTubeSeg *)fShape)->GetPhi1(); + fPmaxi = ((TGeoTubeSeg *)fShape)->GetPhi2(); fShapeName->SetText(fShape->GetName()); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); fERmin->SetNumber(fRmini); fERmax->SetNumber(fRmaxi); fEDz->SetNumber(fDzi); fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -413,20 +413,22 @@ void TGeoTubeSegEditor::DoPhi1() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi1 > 360-1.e-10) { + if (phi1 > 360 - 1.e-10) { phi1 = 0.; fEPhi1->SetNumber(phi1); } - if (phi2SetNumber(phi1); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -436,20 +438,22 @@ void TGeoTubeSegEditor::DoPhi2() { Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if (phi2-phi1 > 360.) { + if (phi2 - phi1 > 360.) { phi2 -= 360.; fEPhi2->SetNumber(phi2); } - if (phi2SetNumber(phi2); } if (!fLock) { DoModified(); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + fSPhi->SetPosition(phi1, phi2); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -463,8 +467,10 @@ void TGeoTubeSegEditor::DoPhi() fEPhi1->SetNumber(fSPhi->GetMinPosition()); fLock = kTRUE; fEPhi2->SetNumber(fSPhi->GetMaxPosition()); - } else fLock = kFALSE; - if (!IsDelayed()) DoApply(); + } else + fLock = kFALSE; + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -474,30 +480,33 @@ void TGeoTubeSegEditor::DoApply() { fApply->SetEnabled(kFALSE); const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmin<0 || rmaxGetNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if ((phi2-phi1) > 360.001) { + if ((phi2 - phi1) > 360.001) { phi1 = 0.; phi2 = 360.; fEPhi1->SetNumber(phi1); fEPhi2->SetNumber(phi2); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); + fSPhi->SetPosition(phi1, phi2); fLock = kFALSE; } - ((TGeoTubeSeg*)fShape)->SetTubsDimensions(rmin, rmax, dz, phi1, phi2); + ((TGeoTubeSeg *)fShape)->SetTubsDimensions(rmin, rmax, dz, phi1, phi2); fShape->ComputeBBox(); fUndo->SetEnabled(); if (fPad) { if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -511,7 +520,7 @@ void TGeoTubeSegEditor::DoUndo() fEDz->SetNumber(fDzi); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); DoApply(); fUndo->SetEnabled(kFALSE); fApply->SetEnabled(kFALSE); @@ -530,16 +539,13 @@ Editor for a TGeoCtub. ClassImp(TGeoCtubEditor); -enum ETGeoCtubSegWid { - kCTUB_THLO, kCTUB_PHLO, kCTUB_THHI, kCTUB_PHHI -}; +enum ETGeoCtubSegWid { kCTUB_THLO, kCTUB_PHLO, kCTUB_THHI, kCTUB_PHHI }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for cut tube editor -TGeoCtubEditor::TGeoCtubEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) - : TGeoTubeSegEditor(p, width, height, options, back) +TGeoCtubEditor::TGeoCtubEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) + : TGeoTubeSegEditor(p, width, height, options, back) { MakeTitle("Theta/phi low"); TGTextEntry *nef; @@ -549,26 +555,26 @@ TGeoCtubEditor::TGeoCtubEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "TH_LO"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEThlo = new TGNumberEntry(f1, 0., 5, kCTUB_THLO); fEThlo->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEThlo->GetNumberEntry(); + nef = (TGTextEntry *)fEThlo->GetNumberEntry(); nef->SetToolTipText("Enter the theta angle of the lower plane normal"); fEThlo->Associate(this); fEThlo->Connect("ValueSet(Long_t)", "TGeoCtubEditor", this, "DoThlo()"); - nef->Connect("TextChanged(const char *)","TGeoCtubEditor", this, "DoModified()"); - fEThlo->Resize(100,fEThlo->GetDefaultHeight()); - f1->AddFrame(fEThlo, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + nef->Connect("TextChanged(const char *)", "TGeoCtubEditor", this, "DoModified()"); + fEThlo->Resize(100, fEThlo->GetDefaultHeight()); + f1->AddFrame(fEThlo, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); f1 = new TGCompositeFrame(compxyz, 155, 30, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "PH_LO"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEPhlo = new TGNumberEntry(f1, 0., 5, kCTUB_PHLO); fEPhlo->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhlo->GetNumberEntry(); + nef = (TGTextEntry *)fEPhlo->GetNumberEntry(); nef->SetToolTipText("Enter the phi angle of the lower plane normal"); fEPhlo->Associate(this); fEPhlo->Connect("ValueSet(Long_t)", "TGeoCtubEditor", this, "DoPhlo()"); - nef->Connect("TextChanged(const char *)","TGeoCtubEditor", this, "DoModified()"); - fEPhlo->Resize(100,fEPhlo->GetDefaultHeight()); - f1->AddFrame(fEPhlo, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + nef->Connect("TextChanged(const char *)", "TGeoCtubEditor", this, "DoModified()"); + fEPhlo->Resize(100, fEPhlo->GetDefaultHeight()); + f1->AddFrame(fEPhlo, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); @@ -579,27 +585,27 @@ TGeoCtubEditor::TGeoCtubEditor(const TGWindow *p, Int_t width, f1->AddFrame(new TGLabel(f1, "TH_HI"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEThhi = new TGNumberEntry(f1, 0., 5, kCTUB_THHI); fEThhi->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEThhi->GetNumberEntry(); + nef = (TGTextEntry *)fEThhi->GetNumberEntry(); nef->SetToolTipText("Enter the theta angle of the upper plane normal"); fEThhi->Associate(this); fEThhi->Connect("ValueSet(Long_t)", "TGeoCtubEditor", this, "DoThhi()"); - nef->Connect("TextChanged(const char *)","TGeoCtubEditor", this, "DoModified()"); - fEThhi->Resize(100,fEThhi->GetDefaultHeight()); - f1->AddFrame(fEThhi, new TGLayoutHints(kLHintsRight , 2, 2, 2, 2)); + nef->Connect("TextChanged(const char *)", "TGeoCtubEditor", this, "DoModified()"); + fEThhi->Resize(100, fEThhi->GetDefaultHeight()); + f1->AddFrame(fEThhi, new TGLayoutHints(kLHintsRight, 2, 2, 2, 2)); compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); f1 = new TGCompositeFrame(compxyz, 155, 30, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "PH_HI"), new TGLayoutHints(kLHintsLeft, 1, 1, 6, 0)); fEPhhi = new TGNumberEntry(f1, 0., 5, kCTUB_PHHI); fEPhhi->SetNumAttr(TGNumberFormat::kNEANonNegative); - nef = (TGTextEntry*)fEPhhi->GetNumberEntry(); + nef = (TGTextEntry *)fEPhhi->GetNumberEntry(); nef->SetToolTipText("Enter the phi angle of the upper plane normal"); fEPhhi->Associate(this); fEPhhi->Connect("ValueSet(Long_t)", "TGeoCtubEditor", this, "DoPhhi()"); - nef->Connect("TextChanged(const char *)","TGeoCtubEditor", this, "DoModified()"); - fEPhhi->Resize(100,fEPhhi->GetDefaultHeight()); - f1->AddFrame(fEPhhi, new TGLayoutHints(kLHintsRight , 2, 2, 4, 4)); - compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX , 2, 2, 4, 4)); + nef->Connect("TextChanged(const char *)", "TGeoCtubEditor", this, "DoModified()"); + fEPhhi->Resize(100, fEPhhi->GetDefaultHeight()); + f1->AddFrame(fEPhhi, new TGLayoutHints(kLHintsRight, 2, 2, 4, 4)); + compxyz->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 4, 4)); AddFrame(compxyz, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); TGeoTabManager::MoveFrame(fDFrame, this); TGeoTabManager::MoveFrame(fBFrame, this); @@ -614,7 +620,7 @@ TGeoCtubEditor::~TGeoCtubEditor() TIter next(GetList()); while ((el = (TGFrameElement *)next())) { if (el->fFrame->IsComposite()) - TGeoTabManager::Cleanup((TGCompositeFrame*)el->fFrame); + TGeoTabManager::Cleanup((TGCompositeFrame *)el->fFrame); } Cleanup(); } @@ -622,21 +628,21 @@ TGeoCtubEditor::~TGeoCtubEditor() //////////////////////////////////////////////////////////////////////////////// /// Connect to the selected object. -void TGeoCtubEditor::SetModel(TObject* obj) +void TGeoCtubEditor::SetModel(TObject *obj) { - if (obj == 0 || (obj->IsA()!=TGeoCtub::Class())) { + if (obj == 0 || (obj->IsA() != TGeoCtub::Class())) { SetActive(kFALSE); return; } - fShape = (TGeoTube*)obj; + fShape = (TGeoTube *)obj; fRmini = fShape->GetRmin(); fRmaxi = fShape->GetRmax(); fDzi = fShape->GetDz(); fNamei = fShape->GetName(); - fPmini = ((TGeoTubeSeg*)fShape)->GetPhi1(); - fPmaxi = ((TGeoTubeSeg*)fShape)->GetPhi2(); - const Double_t *nlo = ((TGeoCtub*)fShape)->GetNlow(); - const Double_t *nhi = ((TGeoCtub*)fShape)->GetNhigh(); + fPmini = ((TGeoTubeSeg *)fShape)->GetPhi1(); + fPmaxi = ((TGeoTubeSeg *)fShape)->GetPhi2(); + const Double_t *nlo = ((TGeoCtub *)fShape)->GetNlow(); + const Double_t *nhi = ((TGeoCtub *)fShape)->GetNhigh(); fThlo = TMath::RadToDeg() * TMath::ACos(nlo[2]); fPhlo = TMath::RadToDeg() * TMath::ATan2(nlo[1], nlo[0]); fThhi = TMath::RadToDeg() * TMath::ACos(nhi[2]); @@ -645,7 +651,7 @@ void TGeoCtubEditor::SetModel(TObject* obj) fShapeName->SetText(fShape->GetName()); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); fERmin->SetNumber(fRmini); fERmax->SetNumber(fRmaxi); fEDz->SetNumber(fDzi); @@ -656,7 +662,8 @@ void TGeoCtubEditor::SetModel(TObject* obj) fApply->SetEnabled(kFALSE); fUndo->SetEnabled(kFALSE); - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); } @@ -666,10 +673,17 @@ void TGeoCtubEditor::SetModel(TObject* obj) void TGeoCtubEditor::DoThlo() { Double_t thlo = fEThlo->GetNumber(); - if (thlo <= 90.) {thlo = 91.; fEThlo->SetNumber(thlo);} - if (thlo > 180.) {thlo = 180.; fEThlo->SetNumber(thlo);} + if (thlo <= 90.) { + thlo = 91.; + fEThlo->SetNumber(thlo); + } + if (thlo > 180.) { + thlo = 180.; + fEThlo->SetNumber(thlo); + } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -683,7 +697,8 @@ void TGeoCtubEditor::DoPhlo() fEPhlo->SetNumber(phlo); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -692,9 +707,13 @@ void TGeoCtubEditor::DoPhlo() void TGeoCtubEditor::DoThhi() { Double_t thhi = fEThhi->GetNumber(); - if (thhi >= 90.) {thhi = 89.; fEThhi->SetNumber(thhi);} + if (thhi >= 90.) { + thhi = 89.; + fEThhi->SetNumber(thhi); + } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -708,7 +727,8 @@ void TGeoCtubEditor::DoPhhi() fEPhhi->SetNumber(phhi); } DoModified(); - if (!IsDelayed()) DoApply(); + if (!IsDelayed()) + DoApply(); } //////////////////////////////////////////////////////////////////////////////// @@ -718,40 +738,43 @@ void TGeoCtubEditor::DoApply() { fApply->SetEnabled(kFALSE); const char *name = fShapeName->GetText(); - if (strcmp(name,fShape->GetName())) fShape->SetName(name); + if (strcmp(name, fShape->GetName())) + fShape->SetName(name); Double_t rmin = fERmin->GetNumber(); Double_t rmax = fERmax->GetNumber(); - if (rmin<0 || rmaxGetNumber(); Double_t phi1 = fEPhi1->GetNumber(); Double_t phi2 = fEPhi2->GetNumber(); - if ((phi2-phi1) > 360.001) { + if ((phi2 - phi1) > 360.001) { phi1 = 0.; phi2 = 360.; fEPhi1->SetNumber(phi1); fEPhi2->SetNumber(phi2); fLock = kTRUE; - fSPhi->SetPosition(phi1,phi2); + fSPhi->SetPosition(phi1, phi2); fLock = kFALSE; } - Double_t thlo = TMath::DegToRad()*fEThlo->GetNumber(); - Double_t phlo = TMath::DegToRad()*fEPhlo->GetNumber(); - Double_t thhi = TMath::DegToRad()*fEThhi->GetNumber(); - Double_t phhi = TMath::DegToRad()*fEPhhi->GetNumber(); - Double_t lx = TMath::Sin(thlo)*TMath::Cos(phlo); - Double_t ly = TMath::Sin(thlo)*TMath::Sin(phlo); + Double_t thlo = TMath::DegToRad() * fEThlo->GetNumber(); + Double_t phlo = TMath::DegToRad() * fEPhlo->GetNumber(); + Double_t thhi = TMath::DegToRad() * fEThhi->GetNumber(); + Double_t phhi = TMath::DegToRad() * fEPhhi->GetNumber(); + Double_t lx = TMath::Sin(thlo) * TMath::Cos(phlo); + Double_t ly = TMath::Sin(thlo) * TMath::Sin(phlo); Double_t lz = TMath::Cos(thlo); - Double_t tx = TMath::Sin(thhi)*TMath::Cos(phhi); - Double_t ty = TMath::Sin(thhi)*TMath::Sin(phhi); + Double_t tx = TMath::Sin(thhi) * TMath::Cos(phhi); + Double_t ty = TMath::Sin(thhi) * TMath::Sin(phhi); Double_t tz = TMath::Cos(thhi); - ((TGeoCtub*)fShape)->SetCtubDimensions(rmin, rmax, dz, phi1, phi2, lx,ly,lz,tx,ty,tz); + ((TGeoCtub *)fShape)->SetCtubDimensions(rmin, rmax, dz, phi1, phi2, lx, ly, lz, tx, ty, tz); fShape->ComputeBBox(); fUndo->SetEnabled(); if (fPad) { if (gGeoManager && gGeoManager->GetPainter() && gGeoManager->GetPainter()->IsPaintingShape()) { fShape->Draw(); fPad->GetView()->ShowAxis(); - } else Update(); + } else + Update(); } } @@ -765,7 +788,7 @@ void TGeoCtubEditor::DoUndo() fEDz->SetNumber(fDzi); fEPhi1->SetNumber(fPmini); fEPhi2->SetNumber(fPmaxi); - fSPhi->SetPosition(fPmini,fPmaxi); + fSPhi->SetPosition(fPmini, fPmaxi); fEThlo->SetNumber(fThlo); fEPhlo->SetNumber(fPhlo); fEThhi->SetNumber(fThhi); diff --git a/geom/geombuilder/src/TGeoVolumeEditor.cxx b/geom/geombuilder/src/TGeoVolumeEditor.cxx index f69779226b2c4..3ddbdae036dfa 100644 --- a/geom/geombuilder/src/TGeoVolumeEditor.cxx +++ b/geom/geombuilder/src/TGeoVolumeEditor.cxx @@ -58,22 +58,39 @@ split vertically by a shutter: ClassImp(TGeoVolumeEditor); enum ETGeoVolumeWid { - kVOL_NAME, kVOL_TITLE, kVOL_SHAPE_SELECT, kVOL_MEDIA_SELECT, kVOL_NODE_SELECT, - kVOL_VOL_SELECT, kVOL_MATRIX_SELECT, kVOL_EDIT_SHAPE, kVOL_EDIT_MEDIUM, kVOL_NODEID, - kVOL_APPLY, kVOL_CANCEL, kVOL_UNDO, kVOL_VISLEVEL, kVOL_DIVSTART, kVOL_DIVEND, - kVOL_DIVSTEP, kVOL_DIVN, kCAT_GENERAL, kCAT_DAUGHTERS, kCAT_DIVISION, kCAT_VIS, + kVOL_NAME, + kVOL_TITLE, + kVOL_SHAPE_SELECT, + kVOL_MEDIA_SELECT, + kVOL_NODE_SELECT, + kVOL_VOL_SELECT, + kVOL_MATRIX_SELECT, + kVOL_EDIT_SHAPE, + kVOL_EDIT_MEDIUM, + kVOL_NODEID, + kVOL_APPLY, + kVOL_CANCEL, + kVOL_UNDO, + kVOL_VISLEVEL, + kVOL_DIVSTART, + kVOL_DIVEND, + kVOL_DIVSTEP, + kVOL_DIVN, + kCAT_GENERAL, + kCAT_DAUGHTERS, + kCAT_DIVISION, + kCAT_VIS, kDIV_NAME }; //////////////////////////////////////////////////////////////////////////////// /// Constructor for volume editor. -TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, - Int_t height, UInt_t options, Pixel_t back) +TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGeoGedFrame(p, width, height, options | kVerticalFrame, back) { fGeometry = 0; - fVolume = 0; + fVolume = 0; fIsModified = kFALSE; fIsAssembly = kFALSE; @@ -86,8 +103,8 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, TGLabel *label; // General settings - TGShutterItem *si = new TGShutterItem(fCategories, new TGHotString("Properties"),kCAT_GENERAL); - container = (TGCompositeFrame*)si->GetContainer(); + TGShutterItem *si = new TGShutterItem(fCategories, new TGHotString("Properties"), kCAT_GENERAL); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -146,8 +163,8 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, container->AddFrame(f1, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 2, 2, 0, 0)); // List of daughters - si = new TGShutterItem(fCategories, new TGHotString("Daughters"),kCAT_DAUGHTERS); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Daughters"), kCAT_DAUGHTERS); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); @@ -219,8 +236,8 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, fCopyNumber = new TGNumberEntry(f1, 0., 5, kVOL_NODEID); fCopyNumber->SetNumStyle(TGNumberFormat::kNESInteger); fCopyNumber->SetNumAttr(TGNumberFormat::kNEANonNegative); - fCopyNumber->Resize(20,fCopyNumber->GetDefaultHeight()); - TGTextEntry *nef = (TGTextEntry*)fCopyNumber->GetNumberEntry(); + fCopyNumber->Resize(20, fCopyNumber->GetDefaultHeight()); + TGTextEntry *nef = (TGTextEntry *)fCopyNumber->GetNumberEntry(); nef->SetToolTipText("Enter node copy number"); fCopyNumber->Associate(this); f1->AddFrame(fCopyNumber, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); @@ -230,39 +247,39 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 2)); // Visualization - si = new TGShutterItem(fCategories, new TGHotString("Visualization"),kCAT_VIS); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Visualization"), kCAT_VIS); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(/* label = */ new TGLabel(f1, "Visibility"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); -// gClient->GetColorByName("#ff0000", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#ff0000", color); + // label->SetTextColor(color); container->AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame | kDoubleBorder); fBVis[0] = new TGCheckButton(f1, "Volume"); fBVis[1] = new TGCheckButton(f1, "Nodes"); - f1->AddFrame(fBVis[0], new TGLayoutHints(kLHintsLeft, 2, 2, 0 ,0)); - f1->AddFrame(fBVis[1], new TGLayoutHints(kLHintsRight, 2, 2, 0 ,0)); + f1->AddFrame(fBVis[0], new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); + f1->AddFrame(fBVis[1], new TGLayoutHints(kLHintsRight, 2, 2, 0, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(new TGLabel(f1, "Depth"), new TGLayoutHints(kLHintsLeft, 2, 2, 4, 0)); -// gClient->GetColorByName("#0000ff", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#0000ff", color); + // label->SetTextColor(color); fEVisLevel = new TGNumberEntry(f1, 0, 5, kVOL_VISLEVEL); fEVisLevel->SetNumStyle(TGNumberFormat::kNESInteger); fEVisLevel->SetNumAttr(TGNumberFormat::kNEAPositive); - fEVisLevel->Resize(40,fEVisLevel->GetDefaultHeight()); - nef = (TGTextEntry*)fEVisLevel->GetNumberEntry(); + fEVisLevel->Resize(40, fEVisLevel->GetDefaultHeight()); + nef = (TGTextEntry *)fEVisLevel->GetNumberEntry(); nef->SetToolTipText("Set visibility level here"); fEVisLevel->SetNumber(3); fEVisLevel->Associate(this); - f1->AddFrame(fEVisLevel, new TGLayoutHints(kLHintsLeft, 2, 2, 0 ,0)); - fBAuto = new TGCheckButton(f1,"Auto"); + f1->AddFrame(fEVisLevel, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); + fBAuto = new TGCheckButton(f1, "Auto"); f1->AddFrame(fBAuto, new TGLayoutHints(kLHintsRight, 0, 0, 2, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); @@ -276,13 +293,13 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, container->AddFrame(bg, new TGLayoutHints(kLHintsLeft, 2, 2, 0, 0)); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth | kSunkenFrame | kDoubleBorder); - fBRaytrace = new TGCheckButton(f1,"Raytrace"); + fBRaytrace = new TGCheckButton(f1, "Raytrace"); f1->AddFrame(fBRaytrace, new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); // Division - si = new TGShutterItem(fCategories, new TGHotString("Division"),kCAT_DIVISION); - container = (TGCompositeFrame*)si->GetContainer(); + si = new TGShutterItem(fCategories, new TGHotString("Division"), kCAT_DIVISION); + container = (TGCompositeFrame *)si->GetContainer(); container->SetBackgroundColor(GetDefaultFrameBackground()); fCategories->AddItem(si); // TextEntry for division name @@ -316,53 +333,52 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(/* label = */ new TGLabel(f1, "Division parameters"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); -// gClient->GetColorByName("#ff0000", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#ff0000", color); + // label->SetTextColor(color); container->AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(/* label = */ new TGLabel(f1, "From"), new TGLayoutHints(kLHintsLeft, 2, 2, 4, 0)); -// gClient->GetColorByName("#0000ff", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#0000ff", color); + // label->SetTextColor(color); fEDivFrom = new TGNumberEntry(f1, 0, 5, kVOL_DIVSTART); -// fEDivFrom->SetNumStyle(TGNumberFormat::kNESInteger); -// fEDivFrom->SetNumAttr(TGNumberFormat::kNEAPositive); - fEDivFrom->Resize(100,fEDivFrom->GetDefaultHeight()); - nef = (TGTextEntry*)fEDivFrom->GetNumberEntry(); + // fEDivFrom->SetNumStyle(TGNumberFormat::kNESInteger); + // fEDivFrom->SetNumAttr(TGNumberFormat::kNEAPositive); + fEDivFrom->Resize(100, fEDivFrom->GetDefaultHeight()); + nef = (TGTextEntry *)fEDivFrom->GetNumberEntry(); nef->SetToolTipText("Set start value"); fEDivFrom->Associate(this); - f1->AddFrame(fEDivFrom, new TGLayoutHints(kLHintsRight, 2, 2, 0 ,0)); + f1->AddFrame(fEDivFrom, new TGLayoutHints(kLHintsRight, 2, 2, 0, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(/* label = */ new TGLabel(f1, "Step"), new TGLayoutHints(kLHintsLeft, 2, 2, 4, 0)); -// gClient->GetColorByName("#0000ff", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#0000ff", color); + // label->SetTextColor(color); fEDivStep = new TGNumberEntry(f1, 0, 5, kVOL_DIVSTEP); -// fEDivFrom->SetNumStyle(TGNumberFormat::kNESInteger); + // fEDivFrom->SetNumStyle(TGNumberFormat::kNESInteger); fEDivStep->SetNumAttr(TGNumberFormat::kNEANonNegative); - fEDivStep->Resize(100,fEDivStep->GetDefaultHeight()); - nef = (TGTextEntry*)fEDivStep->GetNumberEntry(); + fEDivStep->Resize(100, fEDivStep->GetDefaultHeight()); + nef = (TGTextEntry *)fEDivStep->GetNumberEntry(); nef->SetToolTipText("Set division step"); fEDivStep->Associate(this); - f1->AddFrame(fEDivStep, new TGLayoutHints(kLHintsRight, 2, 2, 0 ,0)); + f1->AddFrame(fEDivStep, new TGLayoutHints(kLHintsRight, 2, 2, 0, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame |kFixedWidth); + f1 = new TGCompositeFrame(container, 155, 10, kHorizontalFrame | kFixedWidth); f1->AddFrame(/* label = */ new TGLabel(f1, "Nslices"), new TGLayoutHints(kLHintsLeft, 2, 2, 4, 0)); -// gClient->GetColorByName("#0000ff", color); -// label->SetTextColor(color); + // gClient->GetColorByName("#0000ff", color); + // label->SetTextColor(color); fEDivN = new TGNumberEntry(f1, 0, 5, kVOL_DIVN); fEDivN->SetNumStyle(TGNumberFormat::kNESInteger); fEDivN->SetNumAttr(TGNumberFormat::kNEAPositive); - fEDivN->Resize(100,fEDivN->GetDefaultHeight()); - nef = (TGTextEntry*)fEDivN->GetNumberEntry(); + fEDivN->Resize(100, fEDivN->GetDefaultHeight()); + nef = (TGTextEntry *)fEDivN->GetNumberEntry(); nef->SetToolTipText("Set number of slices"); fEDivN->Associate(this); - f1->AddFrame(fEDivN, new TGLayoutHints(kLHintsRight, 2, 2, 0 ,0)); + f1->AddFrame(fEDivN, new TGLayoutHints(kLHintsRight, 2, 2, 0, 0)); container->AddFrame(f1, new TGLayoutHints(kLHintsLeft, 2, 2, 4, 4)); - - fCategories->Resize(163,340); + fCategories->Resize(163, 340); AddFrame(fCategories, new TGLayoutHints(kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 0, 0, 4, 4)); fCategories->Layout(); @@ -375,21 +391,25 @@ TGeoVolumeEditor::TGeoVolumeEditor(const TGWindow *p, Int_t width, TGeoVolumeEditor::~TGeoVolumeEditor() { TGCompositeFrame *cont; - cont = (TGCompositeFrame*)fCategories->GetItem("Properties")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Properties")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Properties")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Daughters")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Daughters")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Daughters")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Visualization")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Visualization")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Visualization")->SetCleanup(0); - cont = (TGCompositeFrame*)fCategories->GetItem("Division")->GetContainer(); + cont = (TGCompositeFrame *)fCategories->GetItem("Division")->GetContainer(); TGeoTabManager::Cleanup(cont); fCategories->GetItem("Division")->SetCleanup(0); - delete fBView[0]; delete fBView[1]; delete fBView[2]; - delete fBDiv [0]; delete fBDiv [1]; delete fBDiv [2]; + delete fBView[0]; + delete fBView[1]; + delete fBView[2]; + delete fBDiv[0]; + delete fBDiv[1]; + delete fBDiv[2]; Cleanup(); } @@ -429,29 +449,31 @@ void TGeoVolumeEditor::ConnectSignals2Slots() //////////////////////////////////////////////////////////////////////////////// /// Connect to the picked volume. -void TGeoVolumeEditor::SetModel(TObject* obj) +void TGeoVolumeEditor::SetModel(TObject *obj) { if (obj == 0 || !obj->InheritsFrom(TGeoVolume::Class())) { SetActive(kFALSE); return; } - fVolume = (TGeoVolume*)obj; + fVolume = (TGeoVolume *)obj; fGeometry = fVolume->GetGeoManager(); const char *vname = fVolume->GetName(); fVolumeName->SetText(vname); fSelectedShape = fVolume->GetShape(); - if (fSelectedShape) fLSelShape->SetText(fSelectedShape->GetName()); + if (fSelectedShape) + fLSelShape->SetText(fSelectedShape->GetName()); fSelectedMedium = fVolume->GetMedium(); - if (fSelectedMedium) fLSelMedium->SetText(fSelectedMedium->GetName()); + if (fSelectedMedium) + fLSelMedium->SetText(fSelectedMedium->GetName()); - fNodeList->RemoveEntries(0, fNodeList->GetNumberOfEntries()+1); + fNodeList->RemoveEntries(0, fNodeList->GetNumberOfEntries() + 1); TIter next2(fVolume->GetNodes()); TGeoNode *node; Int_t icrt = 0; - while ((node=(TGeoNode*)next2())) + while ((node = (TGeoNode *)next2())) fNodeList->AddEntry(node->GetName(), icrt++); fNodeList->Select(0); - fCopyNumber->SetNumber(fVolume->GetNdaughters()+1); + fCopyNumber->SetNumber(fVolume->GetNdaughters() + 1); if (!fVolume->GetNdaughters() || fVolume->GetFinder()) { fEditMatrix->SetEnabled(kFALSE); fRemoveNode->SetEnabled(kFALSE); @@ -459,29 +481,30 @@ void TGeoVolumeEditor::SetModel(TObject* obj) fEditMatrix->SetEnabled(kTRUE); fRemoveNode->SetEnabled(kTRUE); } - if (!fSelectedVolume) fAddNode->SetEnabled(kFALSE); + if (!fSelectedVolume) + fAddNode->SetEnabled(kFALSE); if (fVolume->IsAssembly()) { fBSelShape->SetEnabled(kFALSE); fBSelMedium->SetEnabled(kFALSE); } - fBVis[0]->SetState((fVolume->IsVisible())?kButtonDown:kButtonUp); - fBVis[1]->SetState((fVolume->IsVisibleDaughters())?kButtonDown:kButtonUp); - fBView[0]->SetState((fVolume->IsVisContainers())?kButtonDown:kButtonUp, kTRUE); - fBView[1]->SetState((fVolume->IsVisLeaves())?kButtonDown:kButtonUp, kTRUE); - fBView[2]->SetState((fVolume->IsVisOnly())?kButtonDown:kButtonUp, kTRUE); - fBRaytrace->SetState((fVolume->IsRaytracing())?kButtonDown:kButtonUp); - fBAuto->SetState((fGeometry->GetVisLevel())?kButtonUp:kButtonDown); + fBVis[0]->SetState((fVolume->IsVisible()) ? kButtonDown : kButtonUp); + fBVis[1]->SetState((fVolume->IsVisibleDaughters()) ? kButtonDown : kButtonUp); + fBView[0]->SetState((fVolume->IsVisContainers()) ? kButtonDown : kButtonUp, kTRUE); + fBView[1]->SetState((fVolume->IsVisLeaves()) ? kButtonDown : kButtonUp, kTRUE); + fBView[2]->SetState((fVolume->IsVisOnly()) ? kButtonDown : kButtonUp, kTRUE); + fBRaytrace->SetState((fVolume->IsRaytracing()) ? kButtonDown : kButtonUp); + fBAuto->SetState((fGeometry->GetVisLevel()) ? kButtonUp : kButtonDown); fEVisLevel->SetNumber(fGeometry->GetVisLevel()); fApplyDiv->SetEnabled(kFALSE); if ((!fVolume->GetFinder() && fVolume->GetNdaughters()) || fVolume->IsAssembly()) { fCategories->GetItem("Division")->GetButton()->SetEnabled(kFALSE); } else { fCategories->GetItem("Division")->GetButton()->SetEnabled(kTRUE); - Double_t start=0., step=0., end = 0.; + Double_t start = 0., step = 0., end = 0.; Int_t ndiv = 2, iaxis = 1; TString axis_name; - for (Int_t i=0; i<3; i++) { - axis_name = fVolume->GetShape()->GetAxisName(i+1); + for (Int_t i = 0; i < 3; i++) { + axis_name = fVolume->GetShape()->GetAxisName(i + 1); fBDiv[i]->SetText(axis_name); } @@ -493,24 +516,26 @@ void TGeoVolumeEditor::SetModel(TObject* obj) ndiv = fVolume->GetFinder()->GetNdiv(); } else { fDivName->SetText("Enter name"); - fSelectedShape->GetAxisRange(iaxis,start,end); + fSelectedShape->GetAxisRange(iaxis, start, end); step = 0; } - fBDiv[iaxis-1]->SetState(kButtonDown, kTRUE); + fBDiv[iaxis - 1]->SetState(kButtonDown, kTRUE); fEDivFrom->SetNumber(start); fEDivStep->SetNumber(step); fEDivN->SetNumber(ndiv); } - if (fInit) ConnectSignals2Slots(); + if (fInit) + ConnectSignals2Slots(); SetActive(); - if (GetParent()==fTabMgr->GetVolumeTab()) fTab->Layout(); + if (GetParent() == fTabMgr->GetVolumeTab()) + fTab->Layout(); } //////////////////////////////////////////////////////////////////////////////// /// Add editors to fGedFrame and exclude TLineEditor. -void TGeoVolumeEditor::ActivateBaseClassEditors(TClass* cl) +void TGeoVolumeEditor::ActivateBaseClassEditors(TClass *cl) { fGedEditor->ExcludeClassEditor(TAttFill::Class()); TGedFrame::ActivateBaseClassEditors(cl); @@ -530,10 +555,12 @@ void TGeoVolumeEditor::DoVolumeName() void TGeoVolumeEditor::DoSelectShape() { TGeoShape *shape = fSelectedShape; - new TGeoShapeDialog(fBSelShape, gClient->GetRoot(), 200,300); - fSelectedShape = (TGeoShape*)TGeoShapeDialog::GetSelected(); - if (fSelectedShape) fLSelShape->SetText(fSelectedShape->GetName()); - else fSelectedShape = shape; + new TGeoShapeDialog(fBSelShape, gClient->GetRoot(), 200, 300); + fSelectedShape = (TGeoShape *)TGeoShapeDialog::GetSelected(); + if (fSelectedShape) + fLSelShape->SetText(fSelectedShape->GetName()); + else + fSelectedShape = shape; } //////////////////////////////////////////////////////////////////////////////// @@ -542,10 +569,12 @@ void TGeoVolumeEditor::DoSelectShape() void TGeoVolumeEditor::DoSelectMedium() { TGeoMedium *med = fSelectedMedium; - new TGeoMediumDialog(fBSelMedium, gClient->GetRoot(), 200,300); - fSelectedMedium = (TGeoMedium*)TGeoMediumDialog::GetSelected(); - if (fSelectedMedium) fLSelMedium->SetText(fSelectedMedium->GetName()); - else fSelectedMedium = med; + new TGeoMediumDialog(fBSelMedium, gClient->GetRoot(), 200, 300); + fSelectedMedium = (TGeoMedium *)TGeoMediumDialog::GetSelected(); + if (fSelectedMedium) + fLSelMedium->SetText(fSelectedMedium->GetName()); + else + fSelectedMedium = med; } //////////////////////////////////////////////////////////////////////////////// @@ -554,10 +583,12 @@ void TGeoVolumeEditor::DoSelectMedium() void TGeoVolumeEditor::DoSelectMatrix() { TGeoMatrix *matrix = fSelectedMatrix; - new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200,300); - fSelectedMatrix = (TGeoMatrix*)TGeoMatrixDialog::GetSelected(); - if (fSelectedMatrix) fLSelMatrix->SetText(fSelectedMatrix->GetName()); - else fSelectedMatrix = matrix; + new TGeoMatrixDialog(fBSelMatrix, gClient->GetRoot(), 200, 300); + fSelectedMatrix = (TGeoMatrix *)TGeoMatrixDialog::GetSelected(); + if (fSelectedMatrix) + fLSelMatrix->SetText(fSelectedMatrix->GetName()); + else + fSelectedMatrix = matrix; } //////////////////////////////////////////////////////////////////////////////// @@ -566,15 +597,16 @@ void TGeoVolumeEditor::DoSelectMatrix() void TGeoVolumeEditor::DoSelectVolume() { TGeoVolume *vol = fSelectedVolume; - new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200,300); - fSelectedVolume = (TGeoVolume*)TGeoVolumeDialog::GetSelected(); - if (fSelectedVolume) fLSelVolume->SetText(fSelectedVolume->GetName()); - else fSelectedVolume = vol; + new TGeoVolumeDialog(fBSelVolume, gClient->GetRoot(), 200, 300); + fSelectedVolume = (TGeoVolume *)TGeoVolumeDialog::GetSelected(); + if (fSelectedVolume) + fLSelVolume->SetText(fSelectedVolume->GetName()); + else + fSelectedVolume = vol; if (fSelectedVolume) fAddNode->SetEnabled(kTRUE); } - //////////////////////////////////////////////////////////////////////////////// /// Edit the shape of the volume. @@ -596,9 +628,11 @@ void TGeoVolumeEditor::DoEditMedium() void TGeoVolumeEditor::DoEditMatrix() { - if (!fVolume->GetNdaughters()) return; + if (!fVolume->GetNdaughters()) + return; Int_t i = fNodeList->GetSelected(); - if (i<0) return; + if (i < 0) + return; fTabMgr->GetMatrixEditor(fVolume->GetNode(i)->GetMatrix()); } @@ -607,14 +641,16 @@ void TGeoVolumeEditor::DoEditMatrix() void TGeoVolumeEditor::DoAddNode() { - if (!fSelectedVolume || fVolume->GetFinder()) return; + if (!fSelectedVolume || fVolume->GetFinder()) + return; Int_t icopy = fCopyNumber->GetIntNumber(); fVolume->AddNode(fSelectedVolume, icopy, fSelectedMatrix); Int_t nd = fVolume->GetNdaughters(); - fNodeList->AddEntry(fVolume->GetNode(nd-1)->GetName(), nd-1); - fNodeList->Select(nd-1); - fCopyNumber->SetNumber(nd+1); - if (fSelectedMatrix) fEditMatrix->SetEnabled(kTRUE); + fNodeList->AddEntry(fVolume->GetNode(nd - 1)->GetName(), nd - 1); + fNodeList->Select(nd - 1); + fCopyNumber->SetNumber(nd + 1); + if (fSelectedMatrix) + fEditMatrix->SetEnabled(kTRUE); fRemoveNode->SetEnabled(kTRUE); fGeometry->SetTopVisible(); fEditMatrix->SetEnabled(kTRUE); @@ -633,25 +669,26 @@ void TGeoVolumeEditor::DoRemoveNode() return; } Int_t i = fNodeList->GetSelected(); - if (i<0) return; + if (i < 0) + return; fVolume->RemoveNode(fVolume->GetNode(i)); - fNodeList->RemoveEntries(0, fNodeList->GetNumberOfEntries()+1); + fNodeList->RemoveEntries(0, fNodeList->GetNumberOfEntries() + 1); TIter next(fVolume->GetNodes()); TGeoNode *node; i = 0; - while ((node=(TGeoNode*)next())) + while ((node = (TGeoNode *)next())) fNodeList->AddEntry(node->GetName(), i++); fNodeList->Select(0); - fCopyNumber->SetNumber(fVolume->GetNdaughters()+1); + fCopyNumber->SetNumber(fVolume->GetNdaughters() + 1); if (!fVolume->GetNdaughters()) { fRemoveNode->SetEnabled(kFALSE); fEditMatrix->SetEnabled(kFALSE); fCategories->GetItem("Division")->GetButton()->SetEnabled(kTRUE); - Double_t start=0., step=0., end=0.; + Double_t start = 0., step = 0., end = 0.; Int_t ndiv = 2, iaxis = 1; - fSelectedShape->GetAxisRange(iaxis,start,end); - step = end-start; - fBDiv[iaxis-1]->SetState(kButtonDown, kTRUE); + fSelectedShape->GetAxisRange(iaxis, start, end); + step = end - start; + fBDiv[iaxis - 1]->SetState(kButtonDown, kTRUE); fEDivFrom->SetNumber(start); fEDivStep->SetNumber(step); fEDivN->SetNumber(ndiv); @@ -664,8 +701,9 @@ void TGeoVolumeEditor::DoRemoveNode() void TGeoVolumeEditor::DoVisVolume() { - Bool_t on = (fBVis[0]->GetState()==kButtonDown)?kTRUE:kFALSE; - if (fVolume->IsVisible() == on) return; + Bool_t on = (fBVis[0]->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (fVolume->IsVisible() == on) + return; fVolume->SetVisibility(on); Update(); } @@ -675,8 +713,9 @@ void TGeoVolumeEditor::DoVisVolume() void TGeoVolumeEditor::DoVisDaughters() { - Bool_t on = (fBVis[1]->GetState()==kButtonDown)?kTRUE:kFALSE; - if (fVolume->IsVisibleDaughters() == on) return; + Bool_t on = (fBVis[1]->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (fVolume->IsVisibleDaughters() == on) + return; fVolume->VisibleDaughters(on); Update(); } @@ -686,10 +725,13 @@ void TGeoVolumeEditor::DoVisDaughters() void TGeoVolumeEditor::DoVisAuto() { - Bool_t on = (fBAuto->GetState()==kButtonDown)?kTRUE:kFALSE; - if ((fGeometry->GetVisLevel()==0) == on) return; - if (on) fGeometry->SetVisLevel(0); - else fGeometry->SetVisLevel(fEVisLevel->GetIntNumber()); + Bool_t on = (fBAuto->GetState() == kButtonDown) ? kTRUE : kFALSE; + if ((fGeometry->GetVisLevel() == 0) == on) + return; + if (on) + fGeometry->SetVisLevel(0); + else + fGeometry->SetVisLevel(fEVisLevel->GetIntNumber()); Update(); } @@ -708,9 +750,11 @@ void TGeoVolumeEditor::DoVisLevel() void TGeoVolumeEditor::DoViewAll() { - Bool_t on = (fBView[0]->GetState()==kButtonDown)?kTRUE:kFALSE; - if (!on) return; - if (fVolume->IsVisContainers() == on) return; + Bool_t on = (fBView[0]->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (!on) + return; + if (fVolume->IsVisContainers() == on) + return; if (fVolume->IsRaytracing()) { fVolume->Raytrace(kFALSE); fBRaytrace->SetState(kButtonUp); @@ -724,9 +768,11 @@ void TGeoVolumeEditor::DoViewAll() void TGeoVolumeEditor::DoViewLeaves() { - Bool_t on = (fBView[1]->GetState()==kButtonDown)?kTRUE:kFALSE; - if (!on) return; - if (fVolume->IsVisLeaves() == on) return; + Bool_t on = (fBView[1]->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (!on) + return; + if (fVolume->IsVisLeaves() == on) + return; if (fVolume->IsRaytracing()) { fVolume->Raytrace(kFALSE); fBRaytrace->SetState(kButtonUp); @@ -740,9 +786,11 @@ void TGeoVolumeEditor::DoViewLeaves() void TGeoVolumeEditor::DoViewOnly() { - Bool_t on = (fBView[2]->GetState()==kButtonDown)?kTRUE:kFALSE; - if (!on) return; - if (fVolume->IsVisOnly() == on) return; + Bool_t on = (fBView[2]->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (!on) + return; + if (fVolume->IsVisOnly() == on) + return; if (fVolume->IsRaytracing()) { fVolume->Raytrace(kFALSE); fBRaytrace->SetState(kButtonUp); @@ -756,8 +804,9 @@ void TGeoVolumeEditor::DoViewOnly() void TGeoVolumeEditor::DoRaytrace() { - Bool_t on = (fBRaytrace->GetState()==kButtonDown)?kTRUE:kFALSE; - if (fVolume->IsRaytracing() == on) return; + Bool_t on = (fBRaytrace->GetState() == kButtonDown) ? kTRUE : kFALSE; + if (fVolume->IsRaytracing() == on) + return; fVolume->Raytrace(on); Update(); } @@ -776,9 +825,10 @@ void TGeoVolumeEditor::DoDivName() void TGeoVolumeEditor::DoDivSelAxis() { Int_t iaxis = 1; - for (Int_t i=0; i<3; i++) { - if (fBDiv[i]->GetState()!=kButtonDown) continue; - iaxis = i+1; + for (Int_t i = 0; i < 3; i++) { + if (fBDiv[i]->GetState() != kButtonDown) + continue; + iaxis = i + 1; break; } TGeoShape *shape = fVolume->GetShape(); @@ -805,9 +855,10 @@ void TGeoVolumeEditor::DoDivFromTo() Double_t min, max, xlo, xhi, step; Int_t iaxis = 1; Int_t ndiv; - for (Int_t i=0; i<3; i++) { - if (fBDiv[i]->GetState()!=kButtonDown) continue; - iaxis = i+1; + for (Int_t i = 0; i < 3; i++) { + if (fBDiv[i]->GetState() != kButtonDown) + continue; + iaxis = i + 1; break; } TGeoShape *shape = fVolume->GetShape(); @@ -816,24 +867,24 @@ void TGeoVolumeEditor::DoDivFromTo() return; } shape->GetAxisRange(iaxis, xlo, xhi); - if (xhi-xlo <= 0) { + if (xhi - xlo <= 0) { fApplyDiv->SetEnabled(kFALSE); return; } min = fEDivFrom->GetNumber(); step = fEDivStep->GetNumber(); ndiv = fEDivN->GetIntNumber(); - if (minSetNumber(xlo); } - max = min + ndiv*step; - if (max>xhi) { + max = min + ndiv * step; + if (max > xhi) { max = xhi; - step = (max-min)/ndiv; + step = (max - min) / ndiv; fEDivStep->SetNumber(step); } - if (min>=max) { + if (min >= max) { fApplyDiv->SetEnabled(kFALSE); return; } @@ -847,9 +898,10 @@ void TGeoVolumeEditor::DoDivStep() { Double_t min, max, xlo, xhi; Int_t iaxis = 1; - for (Int_t i=0; i<3; i++) { - if (fBDiv[i]->GetState()!=kButtonDown) continue; - iaxis = i+1; + for (Int_t i = 0; i < 3; i++) { + if (fBDiv[i]->GetState() != kButtonDown) + continue; + iaxis = i + 1; break; } TGeoShape *shape = fVolume->GetShape(); @@ -858,14 +910,14 @@ void TGeoVolumeEditor::DoDivStep() return; } shape->GetAxisRange(iaxis, xlo, xhi); - if (xhi-xlo <= 0) { + if (xhi - xlo <= 0) { fApplyDiv->SetEnabled(kFALSE); return; } min = fEDivFrom->GetNumber(); Double_t step = fEDivStep->GetNumber(); Int_t ndiv = fEDivN->GetIntNumber(); - max = min + ndiv*step; + max = min + ndiv * step; // Check if ndiv*step < max-min if (max <= xhi) { @@ -874,7 +926,7 @@ void TGeoVolumeEditor::DoDivStep() } // Step too big - set value to fit range max = xhi; - step = (max-min)/ndiv; + step = (max - min) / ndiv; fEDivStep->SetNumber(step); if (step < 0) { fApplyDiv->SetEnabled(kFALSE); @@ -890,9 +942,10 @@ void TGeoVolumeEditor::DoDivN() { Double_t min, max, xlo, xhi; Int_t iaxis = 1; - for (Int_t i=0; i<3; i++) { - if (fBDiv[i]->GetState()!=kButtonDown) continue; - iaxis = i+1; + for (Int_t i = 0; i < 3; i++) { + if (fBDiv[i]->GetState() != kButtonDown) + continue; + iaxis = i + 1; break; } TGeoShape *shape = fVolume->GetShape(); @@ -901,26 +954,26 @@ void TGeoVolumeEditor::DoDivN() return; } shape->GetAxisRange(iaxis, xlo, xhi); - if (xhi-xlo <= 0) { + if (xhi - xlo <= 0) { fApplyDiv->SetEnabled(kFALSE); return; } Double_t step = fEDivStep->GetNumber(); // If step=0 it is discounted - if (step==0) { + if (step == 0) { fApplyDiv->SetEnabled(kTRUE); return; } Int_t ndiv = fEDivN->GetIntNumber(); min = fEDivFrom->GetNumber(); - max = min + ndiv*step; + max = min + ndiv * step; // Check if ndiv*step < max-min if (max <= xhi) { fApplyDiv->SetEnabled(kTRUE); return; } max = xhi; - ndiv = (Int_t)((max-min)/step); + ndiv = (Int_t)((max - min) / step); fEDivN->SetNumber(ndiv); fApplyDiv->SetEnabled(kTRUE); } @@ -933,9 +986,10 @@ void TGeoVolumeEditor::DoApplyDiv() Double_t xlo, xhi, step; Int_t iaxis = 1; Int_t ndiv; - for (Int_t i=0; i<3; i++) { - if (fBDiv[i]->GetState()!=kButtonDown) continue; - iaxis = i+1; + for (Int_t i = 0; i < 3; i++) { + if (fBDiv[i]->GetState() != kButtonDown) + continue; + iaxis = i + 1; break; } TGeoShape *shape = fVolume->GetShape(); @@ -944,7 +998,7 @@ void TGeoVolumeEditor::DoApplyDiv() return; } shape->GetAxisRange(iaxis, xlo, xhi); - if (xhi-xlo <= 0) { + if (xhi - xlo <= 0) { fApplyDiv->SetEnabled(kFALSE); return; } @@ -953,7 +1007,7 @@ void TGeoVolumeEditor::DoApplyDiv() ndiv = fEDivN->GetIntNumber(); TGeoPatternFinder *finder = fVolume->GetFinder(); if (finder) { - // we have to remove first the existing division + // we have to remove first the existing division TObjArray *nodes = fVolume->GetNodes(); nodes->Delete(); nodes->Clear(); @@ -964,5 +1018,5 @@ void TGeoVolumeEditor::DoApplyDiv() fApplyDiv->SetEnabled(kFALSE); fGeometry->SetTopVisible(); Update(); -// fVolume->Draw(); + // fVolume->Draw(); } diff --git a/geom/geompainter/inc/LinkDef.h b/geom/geompainter/inc/LinkDef.h index 1aa615d69602d..4f66975fd9620 100644 --- a/geom/geompainter/inc/LinkDef.h +++ b/geom/geompainter/inc/LinkDef.h @@ -13,9 +13,9 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class TGeoPainter+; -#pragma link C++ class TGeoChecker+; -#pragma link C++ class TGeoTrack+; -#pragma link C++ class TGeoOverlap+; +#pragma link C++ class TGeoPainter + ; +#pragma link C++ class TGeoChecker + ; +#pragma link C++ class TGeoTrack + ; +#pragma link C++ class TGeoOverlap + ; #endif diff --git a/geom/geompainter/inc/TGeoChecker.h b/geom/geompainter/inc/TGeoChecker.h index 9edf19fe9f705..16e17e4734dec 100644 --- a/geom/geompainter/inc/TGeoChecker.h +++ b/geom/geompainter/inc/TGeoChecker.h @@ -34,66 +34,70 @@ class TStopwatch; // // /////////////////////////////////////////////////////////////////////////// -class TGeoChecker : public TObject -{ -private : -// data members - TGeoManager *fGeoManager; // pointer to geometry manager - TGeoVolume *fVsafe; // volume to which a safety sphere node was added - TBuffer3D *fBuff1; // Buffer containing mesh vertices for first volume - TBuffer3D *fBuff2; // Buffer containing mesh vertices for second volume - Bool_t fFullCheck; // Full overlap checking - Double_t *fVal1; //! Array of number of crossings per volume. - Double_t *fVal2; //! Array of timing per volume. - Bool_t *fFlags; //! Array of flags per volume. - TStopwatch *fTimer; //! Timer - TGeoNode *fSelectedNode; //! Selected node for overlap checking - Int_t fNchecks; //! Number of checks for current volume - Int_t fNmeshPoints; //! Number of points on mesh to be checked -// methods - void CleanPoints(Double_t *points, Int_t &numPoints) const; - Int_t NChecksPerVolume(TGeoVolume *vol); - Int_t PropagateInGeom(Double_t *, Double_t *); - void Score(TGeoVolume *, Int_t, Double_t); - Double_t TimingPerVolume(TGeoVolume *); +class TGeoChecker : public TObject { +private: + // data members + TGeoManager *fGeoManager; // pointer to geometry manager + TGeoVolume *fVsafe; // volume to which a safety sphere node was added + TBuffer3D *fBuff1; // Buffer containing mesh vertices for first volume + TBuffer3D *fBuff2; // Buffer containing mesh vertices for second volume + Bool_t fFullCheck; // Full overlap checking + Double_t *fVal1; //! Array of number of crossings per volume. + Double_t *fVal2; //! Array of timing per volume. + Bool_t *fFlags; //! Array of flags per volume. + TStopwatch *fTimer; //! Timer + TGeoNode *fSelectedNode; //! Selected node for overlap checking + Int_t fNchecks; //! Number of checks for current volume + Int_t fNmeshPoints; //! Number of points on mesh to be checked + // methods + void CleanPoints(Double_t *points, Int_t &numPoints) const; + Int_t NChecksPerVolume(TGeoVolume *vol); + Int_t PropagateInGeom(Double_t *, Double_t *); + void Score(TGeoVolume *, Int_t, Double_t); + Double_t TimingPerVolume(TGeoVolume *); + public: // constructors TGeoChecker(); TGeoChecker(TGeoManager *geom); // destructor - virtual ~TGeoChecker(); + ~TGeoChecker() override; // methods - virtual void CheckBoundaryErrors(Int_t ntracks=1000000, Double_t radius=-1.); - virtual void CheckBoundaryReference(Int_t icheck=-1); - void CheckGeometryFull(Bool_t checkoverlaps=kTRUE, Bool_t checkcrossings=kTRUE, Int_t nrays=10000, const Double_t *vertex=nullptr); - void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const; - void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp=0.1, Option_t *option=""); - void CheckOverlapsBySampling(TGeoVolume *vol, Double_t ovlp=0.1, Int_t npoints=1000000) const; - void CheckPoint(Double_t x=0, Double_t y=0, Double_t z=0, Option_t *option=""); - void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option); - Double_t CheckVoxels(TGeoVolume *vol, TGeoVoxelFinder *voxels, Double_t *xyz, Int_t npoints); - TH2F *LegoPlot(Int_t ntheta=60, Double_t themin=0., Double_t themax=180., - Int_t nphi=90, Double_t phimin=0., Double_t phimax=360., - Double_t rmin=0., Double_t rmax=9999999, Option_t *option=""); - void PrintOverlaps() const; - void RandomPoints(TGeoVolume *vol, Int_t npoints, Option_t *option); - void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol=nullptr, Bool_t check_norm=kFALSE); - TGeoOverlap *MakeCheckOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, TGeoMatrix *mat1, TGeoMatrix *mat2, Bool_t isovlp, Double_t ovlp); - void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch=nullptr, Bool_t last=kFALSE, Bool_t refresh=kFALSE, const char *msg=""); - TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char* g3path); - void ShapeDistances(TGeoShape *shape, Int_t nsamples, Option_t *option); - void ShapeSafety(TGeoShape *shape, Int_t nsamples, Option_t *option); - void ShapeNormal(TGeoShape *shape, Int_t nsamples, Option_t *option); - Double_t *ShootRay(Double_t *start, Double_t dirx, Double_t diry, Double_t dirz, Double_t *array, Int_t &nelem, Int_t &dim, Double_t *enpoint=nullptr) const; - void SetSelectedNode(TGeoNode *node) {fSelectedNode=node;} - void SetNmeshPoints(Int_t npoints=1000); - void Test(Int_t npoints, Option_t *option); - void TestOverlaps(const char *path); - Bool_t TestVoxels(TGeoVolume *vol, Int_t npoints=1000000); - Double_t Weight(Double_t precision=0.01, Option_t *option="v"); + virtual void CheckBoundaryErrors(Int_t ntracks = 1000000, Double_t radius = -1.); + virtual void CheckBoundaryReference(Int_t icheck = -1); + void CheckGeometryFull(Bool_t checkoverlaps = kTRUE, Bool_t checkcrossings = kTRUE, Int_t nrays = 10000, + const Double_t *vertex = nullptr); + void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const; + void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp = 0.1, Option_t *option = ""); + void CheckOverlapsBySampling(TGeoVolume *vol, Double_t ovlp = 0.1, Int_t npoints = 1000000) const; + void CheckPoint(Double_t x = 0, Double_t y = 0, Double_t z = 0, Option_t *option = ""); + void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option); + Double_t CheckVoxels(TGeoVolume *vol, TGeoVoxelFinder *voxels, Double_t *xyz, Int_t npoints); + TH2F *LegoPlot(Int_t ntheta = 60, Double_t themin = 0., Double_t themax = 180., Int_t nphi = 90, + Double_t phimin = 0., Double_t phimax = 360., Double_t rmin = 0., Double_t rmax = 9999999, + Option_t *option = ""); + void PrintOverlaps() const; + void RandomPoints(TGeoVolume *vol, Int_t npoints, Option_t *option); + void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol = nullptr, + Bool_t check_norm = kFALSE); + TGeoOverlap *MakeCheckOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, TGeoMatrix *mat1, + TGeoMatrix *mat2, Bool_t isovlp, Double_t ovlp); + void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch = nullptr, + Bool_t last = kFALSE, Bool_t refresh = kFALSE, const char *msg = ""); + TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path); + void ShapeDistances(TGeoShape *shape, Int_t nsamples, Option_t *option); + void ShapeSafety(TGeoShape *shape, Int_t nsamples, Option_t *option); + void ShapeNormal(TGeoShape *shape, Int_t nsamples, Option_t *option); + Double_t *ShootRay(Double_t *start, Double_t dirx, Double_t diry, Double_t dirz, Double_t *array, Int_t &nelem, + Int_t &dim, Double_t *enpoint = nullptr) const; + void SetSelectedNode(TGeoNode *node) { fSelectedNode = node; } + void SetNmeshPoints(Int_t npoints = 1000); + void Test(Int_t npoints, Option_t *option); + void TestOverlaps(const char *path); + Bool_t TestVoxels(TGeoVolume *vol, Int_t npoints = 1000000); + Double_t Weight(Double_t precision = 0.01, Option_t *option = "v"); - ClassDef(TGeoChecker, 2) // a simple geometry checker + ClassDefOverride(TGeoChecker, 2) // a simple geometry checker }; #endif - diff --git a/geom/geompainter/inc/TGeoOverlap.h b/geom/geompainter/inc/TGeoOverlap.h index 09ab461a34738..ace911ac642f2 100644 --- a/geom/geompainter/inc/TGeoOverlap.h +++ b/geom/geompainter/inc/TGeoOverlap.h @@ -34,68 +34,67 @@ class TGeoVolume; class TPolyMarker3D; class TBrowser; -class TGeoOverlap : public TNamed, - public TAttLine, - public TAttFill, - public TAtt3D -{ +class TGeoOverlap : public TNamed, public TAttLine, public TAttFill, public TAtt3D { public: -enum EOverlapType { - kGeoOverlap = BIT(14), - kGeoExtrusion = BIT(15) -}; + enum EOverlapType { kGeoOverlap = BIT(14), kGeoExtrusion = BIT(15) }; private: - TGeoOverlap(const TGeoOverlap&) = delete; - TGeoOverlap& operator=(const TGeoOverlap&) = delete; + TGeoOverlap(const TGeoOverlap &) = delete; + TGeoOverlap &operator=(const TGeoOverlap &) = delete; protected: - Double_t fOverlap; // overlap distance - TGeoVolume *fVolume1; // first volume - TGeoVolume *fVolume2; // second volume - TGeoHMatrix *fMatrix1; // positioning matrix for first volume - TGeoHMatrix *fMatrix2; // positioning matrix for second volume - TPolyMarker3D *fMarker; // points in the overlapping region + Double_t fOverlap; // overlap distance + TGeoVolume *fVolume1; // first volume + TGeoVolume *fVolume2; // second volume + TGeoHMatrix *fMatrix1; // positioning matrix for first volume + TGeoHMatrix *fMatrix2; // positioning matrix for second volume + TPolyMarker3D *fMarker; // points in the overlapping region public: TGeoOverlap(); - TGeoOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, - const TGeoMatrix *matrix1, const TGeoMatrix *matrix2, - Bool_t isovlp=kTRUE, Double_t ovlp=0.01); - virtual ~TGeoOverlap(); - - void Browse(TBrowser *b); - virtual Int_t Compare(const TObject *obj) const; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void Draw(Option_t *option=""); // *MENU* - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - TPolyMarker3D *GetPolyMarker() const {return fMarker;} - TGeoVolume *GetFirstVolume() const {return fVolume1;} - TGeoVolume *GetSecondVolume() const {return fVolume2;} - TGeoHMatrix *GetFirstMatrix() const {return fMatrix1;} - TGeoHMatrix *GetSecondMatrix() const {return fMatrix2;} - Double_t GetOverlap() const {return fOverlap;} - Bool_t IsExtrusion() const {return TObject::TestBit(kGeoExtrusion);} - Bool_t IsOverlap() const {return TObject::TestBit(kGeoOverlap);} - Bool_t IsFolder() const {return kFALSE;} - virtual Bool_t IsSortable() const {return kTRUE;} - virtual void Paint(Option_t *option=""); - virtual void Print(Option_t *option="") const; // *MENU* - virtual void PrintInfo() const; - virtual void Sizeof3D() const; - void SampleOverlap(Int_t npoints=1000000); // *MENU* - void SetIsExtrusion(Bool_t flag=kTRUE) {TObject::SetBit(kGeoExtrusion,flag); TObject::SetBit(kGeoOverlap,!flag);} - void SetIsOverlap(Bool_t flag=kTRUE) {TObject::SetBit(kGeoOverlap,flag); TObject::SetBit(kGeoExtrusion,!flag);} - void SetNextPoint(Double_t x, Double_t y, Double_t z); - void SetFirstVolume(TGeoVolume *vol) {fVolume1=vol;} - void SetSecondVolume(TGeoVolume *vol) {fVolume2=vol;} - void SetFirstMatrix(TGeoMatrix *matrix) {*fMatrix1 = matrix;} - void SetSecondMatrix(TGeoMatrix *matrix) {*fMatrix2 = matrix;} - void SetOverlap(Double_t ovlp) {fOverlap=ovlp;} - void Validate() const; // *MENU* - - ClassDef(TGeoOverlap, 2) // base class for geometical overlaps + TGeoOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, const TGeoMatrix *matrix1, + const TGeoMatrix *matrix2, Bool_t isovlp = kTRUE, Double_t ovlp = 0.01); + ~TGeoOverlap() override; + + void Browse(TBrowser *b) override; + Int_t Compare(const TObject *obj) const override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *option = "") override; // *MENU* + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + TPolyMarker3D *GetPolyMarker() const { return fMarker; } + TGeoVolume *GetFirstVolume() const { return fVolume1; } + TGeoVolume *GetSecondVolume() const { return fVolume2; } + TGeoHMatrix *GetFirstMatrix() const { return fMatrix1; } + TGeoHMatrix *GetSecondMatrix() const { return fMatrix2; } + Double_t GetOverlap() const { return fOverlap; } + Bool_t IsExtrusion() const { return TObject::TestBit(kGeoExtrusion); } + Bool_t IsOverlap() const { return TObject::TestBit(kGeoOverlap); } + Bool_t IsFolder() const override { return kFALSE; } + Bool_t IsSortable() const override { return kTRUE; } + void Paint(Option_t *option = "") override; + void Print(Option_t *option = "") const override; // *MENU* + virtual void PrintInfo() const; + void Sizeof3D() const override; + void SampleOverlap(Int_t npoints = 1000000); // *MENU* + void SetIsExtrusion(Bool_t flag = kTRUE) + { + TObject::SetBit(kGeoExtrusion, flag); + TObject::SetBit(kGeoOverlap, !flag); + } + void SetIsOverlap(Bool_t flag = kTRUE) + { + TObject::SetBit(kGeoOverlap, flag); + TObject::SetBit(kGeoExtrusion, !flag); + } + void SetNextPoint(Double_t x, Double_t y, Double_t z); + void SetFirstVolume(TGeoVolume *vol) { fVolume1 = vol; } + void SetSecondVolume(TGeoVolume *vol) { fVolume2 = vol; } + void SetFirstMatrix(TGeoMatrix *matrix) { *fMatrix1 = matrix; } + void SetSecondMatrix(TGeoMatrix *matrix) { *fMatrix2 = matrix; } + void SetOverlap(Double_t ovlp) { fOverlap = ovlp; } + void Validate() const; // *MENU* + + ClassDefOverride(TGeoOverlap, 2) // base class for geometical overlaps }; #endif - diff --git a/geom/geompainter/inc/TGeoPainter.h b/geom/geompainter/inc/TGeoPainter.h index cc335fcd46c85..846630255af18 100644 --- a/geom/geompainter/inc/TGeoPainter.h +++ b/geom/geompainter/inc/TGeoPainter.h @@ -19,7 +19,6 @@ // // ////////////////////////////////////////////////////////////////////////// - #include "TVirtualGeoPainter.h" #include "TGeoManager.h" @@ -39,137 +38,149 @@ class TGeoPolygon; class TGeoPainter : public TVirtualGeoPainter { private: - Double_t fBombX; // bomb factor on X - Double_t fBombY; // bomb factor on Y - Double_t fBombZ; // bomb factor on Z - Double_t fBombR; // bomb factor on radius (cyl or sph) - Double_t fCheckedBox[6]; // bounding box of checked node - Double_t fMat[9]; // view rotation matrix - Int_t fNsegments; // number of segments approximating circles - Int_t fNVisNodes; // number of visible nodes - Int_t fVisLevel; // depth for drawing - Int_t fVisOption; // global visualization option - Int_t fExplodedView; // type of exploding current view - Bool_t fVisLock; // lock for adding visible volumes - Bool_t fTopVisible; // set top volume visible - Bool_t fPaintingOverlaps; // lock overlaps painting - Bool_t fIsRaytracing; // raytracing flag - Bool_t fIsPaintingShape; // flag for shape painting - TString fVisBranch; // drawn branch - TString fVolInfo; // volume info - TGeoNode *fCheckedNode; // checked node - TGeoOverlap *fOverlap; // current overlap - TGeoHMatrix *fGlobal; // current global matrix - TBuffer3D *fBuffer; // buffer used for painting - TGeoManager *fGeoManager; // geometry to which applies - TGeoChecker *fChecker; // geometry checker - TGeoShape *fClippingShape; // clipping shape - TGeoVolume *fTopVolume; // top drawn volume - TGeoVolume *fLastVolume; // last drawn volume - TGeoIteratorPlugin *fPlugin; // User iterator plugin for changing pain volume properties - TObjArray *fVisVolumes; // list of visible volumes - Bool_t fIsEditable; // flag that geometry is editable + Double_t fBombX; // bomb factor on X + Double_t fBombY; // bomb factor on Y + Double_t fBombZ; // bomb factor on Z + Double_t fBombR; // bomb factor on radius (cyl or sph) + Double_t fCheckedBox[6]; // bounding box of checked node + Double_t fMat[9]; // view rotation matrix + Int_t fNsegments; // number of segments approximating circles + Int_t fNVisNodes; // number of visible nodes + Int_t fVisLevel; // depth for drawing + Int_t fVisOption; // global visualization option + Int_t fExplodedView; // type of exploding current view + Bool_t fVisLock; // lock for adding visible volumes + Bool_t fTopVisible; // set top volume visible + Bool_t fPaintingOverlaps; // lock overlaps painting + Bool_t fIsRaytracing; // raytracing flag + Bool_t fIsPaintingShape; // flag for shape painting + TString fVisBranch; // drawn branch + TString fVolInfo; // volume info + TGeoNode *fCheckedNode; // checked node + TGeoOverlap *fOverlap; // current overlap + TGeoHMatrix *fGlobal; // current global matrix + TBuffer3D *fBuffer; // buffer used for painting + TGeoManager *fGeoManager; // geometry to which applies + TGeoChecker *fChecker; // geometry checker + TGeoShape *fClippingShape; // clipping shape + TGeoVolume *fTopVolume; // top drawn volume + TGeoVolume *fLastVolume; // last drawn volume + TGeoIteratorPlugin *fPlugin; // User iterator plugin for changing pain volume properties + TObjArray *fVisVolumes; // list of visible volumes + Bool_t fIsEditable; // flag that geometry is editable - void DefineColors() const; - void LocalToMasterVect(const Double_t *local, Double_t *master) const; + void DefineColors() const; + void LocalToMasterVect(const Double_t *local, Double_t *master) const; protected: - void ClearVisibleVolumes(); + void ClearVisibleVolumes(); public: TGeoPainter(TGeoManager *manager); - virtual ~TGeoPainter(); + ~TGeoPainter() override; - void AddSize3D(Int_t numpoints, Int_t numsegs, Int_t numpolys) override; + void AddSize3D(Int_t numpoints, Int_t numsegs, Int_t numpolys) override; TVirtualGeoTrack *AddTrack(Int_t id, Int_t pdgcode, TObject *part) override; - void AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset=kFALSE) override; - void BombTranslation(const Double_t *tr, Double_t *bombtr) override; - void CheckBoundaryErrors(Int_t ntracks=1000000, Double_t radius=-1.) override; - void CheckBoundaryReference(Int_t icheck=-1) override; - void CheckGeometryFull(Bool_t checkoverlaps=kTRUE, Bool_t checkcrossings=kTRUE, Int_t nrays=10000, const Double_t *vertex=nullptr) override; - void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const override; - void CheckEdit(); - void CheckPoint(Double_t x=0, Double_t y=0, Double_t z=0, Option_t *option="") override; - void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option) override; - void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp=0.1, Option_t *option="") const override; - Int_t CountNodes(TGeoVolume *vol, Int_t level) const; - Int_t CountVisibleNodes() override; - void DefaultAngles() override; - void DefaultColors() override; - Int_t DistanceToPrimitiveVol(TGeoVolume *vol, Int_t px, Int_t py) override; - void Draw(Option_t *option="") override; - void DrawBatemanSol(TGeoBatemanSol *sol, Option_t *option="") override; - void DrawOverlap(void *ovlp, Option_t *option="") override; - void DrawCurrentPoint(Int_t color) override; - void DrawOnly(Option_t *option="") override; - void DrawPanel() override; - void DrawPath(const char *path, Option_t *option="") override; - void DrawPolygon(const TGeoPolygon *poly) override; - void DrawShape(TGeoShape *shape, Option_t *option="") override; - void DrawVolume(TGeoVolume *vol, Option_t *option="") override; - void EditGeometry(Option_t *option="") override; - void EstimateCameraMove(Double_t tmin, Double_t tmax, Double_t *start, Double_t *end) override; - void ExecuteManagerEvent(TGeoManager *geom, Int_t event, Int_t px, Int_t py) override; - void ExecuteShapeEvent(TGeoShape *shape, Int_t event, Int_t px, Int_t py) override; - void ExecuteVolumeEvent(TGeoVolume *volume, Int_t event, Int_t px, Int_t py) override; + void AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset = kFALSE) override; + void BombTranslation(const Double_t *tr, Double_t *bombtr) override; + void CheckBoundaryErrors(Int_t ntracks = 1000000, Double_t radius = -1.) override; + void CheckBoundaryReference(Int_t icheck = -1) override; + void CheckGeometryFull(Bool_t checkoverlaps = kTRUE, Bool_t checkcrossings = kTRUE, Int_t nrays = 10000, + const Double_t *vertex = nullptr) override; + void CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, Double_t startz) const override; + void CheckEdit(); + void CheckPoint(Double_t x = 0, Double_t y = 0, Double_t z = 0, Option_t *option = "") override; + void CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option) override; + void CheckOverlaps(const TGeoVolume *vol, Double_t ovlp = 0.1, Option_t *option = "") const override; + Int_t CountNodes(TGeoVolume *vol, Int_t level) const; + Int_t CountVisibleNodes() override; + void DefaultAngles() override; + void DefaultColors() override; + Int_t DistanceToPrimitiveVol(TGeoVolume *vol, Int_t px, Int_t py) override; + void Draw(Option_t *option = "") override; + void DrawBatemanSol(TGeoBatemanSol *sol, Option_t *option = "") override; + void DrawOverlap(void *ovlp, Option_t *option = "") override; + void DrawCurrentPoint(Int_t color) override; + void DrawOnly(Option_t *option = "") override; + void DrawPanel() override; + void DrawPath(const char *path, Option_t *option = "") override; + void DrawPolygon(const TGeoPolygon *poly) override; + void DrawShape(TGeoShape *shape, Option_t *option = "") override; + void DrawVolume(TGeoVolume *vol, Option_t *option = "") override; + void EditGeometry(Option_t *option = "") override; + void EstimateCameraMove(Double_t tmin, Double_t tmax, Double_t *start, Double_t *end) override; + void ExecuteManagerEvent(TGeoManager *geom, Int_t event, Int_t px, Int_t py) override; + void ExecuteShapeEvent(TGeoShape *shape, Int_t event, Int_t px, Int_t py) override; + void ExecuteVolumeEvent(TGeoVolume *volume, Int_t event, Int_t px, Int_t py) override; const char *GetVolumeInfo(const TGeoVolume *volume, Int_t px, Int_t py) const override; - void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const override - {bombx=fBombX; bomby=fBombY; bombz=fBombZ; bombr=fBombR;} - Int_t GetBombMode() const override {return fExplodedView;} - TGeoNode *GetCheckedNode() {return fCheckedNode;} - TGeoChecker *GetChecker(); - Int_t GetColor(Int_t base, Float_t light) const override; - const char *GetDrawPath() const override {return fVisBranch.Data();} + void GetBombFactors(Double_t &bombx, Double_t &bomby, Double_t &bombz, Double_t &bombr) const override + { + bombx = fBombX; + bomby = fBombY; + bombz = fBombZ; + bombr = fBombR; + } + Int_t GetBombMode() const override { return fExplodedView; } + TGeoNode *GetCheckedNode() { return fCheckedNode; } + TGeoChecker *GetChecker(); + Int_t GetColor(Int_t base, Float_t light) const override; + const char *GetDrawPath() const override { return fVisBranch.Data(); } TGeoVolume *GetDrawnVolume() const override; - TGeoVolume *GetTopVolume() const override {return fTopVolume;} - Int_t GetVisLevel() const override {return fVisLevel;} - Int_t GetVisOption() const override {return fVisOption;} - Int_t GetNsegments() const override {return fNsegments;} - void GrabFocus(Int_t nfr=0, Double_t dlong=0, Double_t dlat=0, Double_t dpsi=0) override; - Double_t *GetViewBox() override {return &fCheckedBox[0];} - void GetViewAngles(Double_t &longitude, Double_t &latitude, Double_t &psi) override; - Bool_t IsExplodedView() const override {return (fExplodedView==kGeoVisDefault)?kFALSE:kTRUE;} - Bool_t IsRaytracing() const override {return fIsRaytracing;} - Bool_t IsPaintingShape() const override {return fIsPaintingShape;} - TH2F *LegoPlot(Int_t ntheta=60, Double_t themin=0., Double_t themax=180., - Int_t nphi=90, Double_t phimin=0., Double_t phimax=360., - Double_t rmin=0., Double_t rmax=9999999, Option_t *option="") override; - void Lock(Bool_t flag = kTRUE) { fVisLock = flag; } - void ModifiedPad(Bool_t update=kFALSE) const override; - void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch=nullptr, Bool_t last=kFALSE, Bool_t refresh=kFALSE, const char *msg="") override; - void Paint(Option_t *option="") override; - void PaintNode(TGeoNode *node, Option_t *option="", TGeoMatrix *global=nullptr) override; - Bool_t PaintShape(const TGeoShape & shape, Option_t * option) const; - void PaintShape(TGeoShape *shape, Option_t *option="") override; - void PaintOverlap(void *ovlp, Option_t *option="") override; - void PaintVolume(TGeoVolume *vol, Option_t *option="", TGeoMatrix *global=nullptr) override; - void PrintOverlaps() const override; - void PaintPhysicalNode(TGeoPhysicalNode *node, Option_t *option=""); - void RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option="") override; - void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol = nullptr, Bool_t check_norm = kFALSE) override; - void Raytrace(Option_t *option="") override; - TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char* g3path) override; - void SetBombFactors(Double_t bombx=1.3, Double_t bomby=1.3, Double_t bombz=1.3, Double_t bombr=1.3) override; - void SetClippingShape(TGeoShape *shape) override {fClippingShape = shape;} - void SetExplodedView(Int_t iopt=0) override; - void SetNsegments(Int_t nseg=20) override; - void SetNmeshPoints(Int_t npoints) override; - void SetGeoManager(TGeoManager *geom) override {fGeoManager=geom;} - void SetIteratorPlugin(TGeoIteratorPlugin *plugin) override {fPlugin = plugin; ModifiedPad();} - void SetCheckedNode(TGeoNode *node) override; - void SetRaytracing(Bool_t flag=kTRUE) override {fIsRaytracing = flag;} - void SetTopVisible(Bool_t vis=kTRUE) override; - void SetTopVolume(TGeoVolume *vol) override {fTopVolume = vol;} - void SetVisLevel(Int_t level=3) override; - void SetVisOption(Int_t option=0) override; - Int_t ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoints, Int_t px, Int_t py) const override; - void Test(Int_t npoints, Option_t *option) override; - void TestOverlaps(const char *path) override; - Bool_t TestVoxels(TGeoVolume *vol) override; - void UnbombTranslation(const Double_t *tr, Double_t *bombtr) override; - Double_t Weight(Double_t precision, Option_t *option="v") override; + TGeoVolume *GetTopVolume() const override { return fTopVolume; } + Int_t GetVisLevel() const override { return fVisLevel; } + Int_t GetVisOption() const override { return fVisOption; } + Int_t GetNsegments() const override { return fNsegments; } + void GrabFocus(Int_t nfr = 0, Double_t dlong = 0, Double_t dlat = 0, Double_t dpsi = 0) override; + Double_t *GetViewBox() override { return &fCheckedBox[0]; } + void GetViewAngles(Double_t &longitude, Double_t &latitude, Double_t &psi) override; + Bool_t IsExplodedView() const override { return (fExplodedView == kGeoVisDefault) ? kFALSE : kTRUE; } + Bool_t IsRaytracing() const override { return fIsRaytracing; } + Bool_t IsPaintingShape() const override { return fIsPaintingShape; } + TH2F *LegoPlot(Int_t ntheta = 60, Double_t themin = 0., Double_t themax = 180., Int_t nphi = 90, + Double_t phimin = 0., Double_t phimax = 360., Double_t rmin = 0., Double_t rmax = 9999999, + Option_t *option = "") override; + void Lock(Bool_t flag = kTRUE) { fVisLock = flag; } + void ModifiedPad(Bool_t update = kFALSE) const override; + void OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch = nullptr, + Bool_t last = kFALSE, Bool_t refresh = kFALSE, const char *msg = "") override; + void Paint(Option_t *option = "") override; + void PaintNode(TGeoNode *node, Option_t *option = "", TGeoMatrix *global = nullptr) override; + Bool_t PaintShape(const TGeoShape &shape, Option_t *option) const; + void PaintShape(TGeoShape *shape, Option_t *option = "") override; + void PaintOverlap(void *ovlp, Option_t *option = "") override; + void PaintVolume(TGeoVolume *vol, Option_t *option = "", TGeoMatrix *global = nullptr) override; + void PrintOverlaps() const override; + void PaintPhysicalNode(TGeoPhysicalNode *node, Option_t *option = ""); + void RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option = "") override; + void RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol = nullptr, + Bool_t check_norm = kFALSE) override; + void Raytrace(Option_t *option = "") override; + TGeoNode *SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path) override; + void SetBombFactors(Double_t bombx = 1.3, Double_t bomby = 1.3, Double_t bombz = 1.3, Double_t bombr = 1.3) override; + void SetClippingShape(TGeoShape *shape) override { fClippingShape = shape; } + void SetExplodedView(Int_t iopt = 0) override; + void SetNsegments(Int_t nseg = 20) override; + void SetNmeshPoints(Int_t npoints) override; + void SetGeoManager(TGeoManager *geom) override { fGeoManager = geom; } + void SetIteratorPlugin(TGeoIteratorPlugin *plugin) override + { + fPlugin = plugin; + ModifiedPad(); + } + void SetCheckedNode(TGeoNode *node) override; + void SetRaytracing(Bool_t flag = kTRUE) override { fIsRaytracing = flag; } + void SetTopVisible(Bool_t vis = kTRUE) override; + void SetTopVolume(TGeoVolume *vol) override { fTopVolume = vol; } + void SetVisLevel(Int_t level = 3) override; + void SetVisOption(Int_t option = 0) override; + Int_t ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoints, Int_t px, Int_t py) const override; + void Test(Int_t npoints, Option_t *option) override; + void TestOverlaps(const char *path) override; + Bool_t TestVoxels(TGeoVolume *vol) override; + void UnbombTranslation(const Double_t *tr, Double_t *bombtr) override; + Double_t Weight(Double_t precision, Option_t *option = "v") override; - ClassDefOverride(TGeoPainter,0) //geometry painter + ClassDefOverride(TGeoPainter, 0) // geometry painter }; #endif diff --git a/geom/geompainter/inc/TGeoTrack.h b/geom/geompainter/inc/TGeoTrack.h index 6c3cc0cc2927c..9e37c21d84a87 100644 --- a/geom/geompainter/inc/TGeoTrack.h +++ b/geom/geompainter/inc/TGeoTrack.h @@ -23,64 +23,59 @@ // // ///////////////////////////////////////////////////////////////////////////// -class TGeoTrack : public TVirtualGeoTrack -{ +class TGeoTrack : public TVirtualGeoTrack { public: - -enum EGeoParticleActions { - kGeoPDefault = BIT(7), - kGeoPOnelevel = BIT(8), - kGeoPAllDaughters = BIT(9), - kGeoPType = BIT(10), - kGeoPDrawn = BIT(11) -}; - -private : - Int_t fPointsSize; // capacity of points array - Int_t fNpoints; // number of stored points - Double_t *fPoints; //[fNpoints] array of points (x,y,z,t) belonging to this track + enum EGeoParticleActions { + kGeoPDefault = BIT(7), + kGeoPOnelevel = BIT(8), + kGeoPAllDaughters = BIT(9), + kGeoPType = BIT(10), + kGeoPDrawn = BIT(11) + }; + +private: + Int_t fPointsSize; // capacity of points array + Int_t fNpoints; // number of stored points + Double_t *fPoints; //[fNpoints] array of points (x,y,z,t) belonging to this track protected: - TGeoTrack(const TGeoTrack&) = delete; - TGeoTrack& operator=(const TGeoTrack&) = delete; + TGeoTrack(const TGeoTrack &) = delete; + TGeoTrack &operator=(const TGeoTrack &) = delete; public: TGeoTrack(); - TGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent=nullptr, TObject *particle=nullptr); - virtual ~TGeoTrack(); - - virtual TVirtualGeoTrack *AddDaughter(Int_t id, Int_t pdgcode, TObject *particle=nullptr); - virtual Int_t AddDaughter(TVirtualGeoTrack *other); - virtual void AddPoint(Double_t x, Double_t y, Double_t z, Double_t t); - virtual void AnimateTrack(Double_t tmin=0, Double_t tmax=5E-8, Double_t nframes=200, Option_t *option="/*"); // *MENU* - void Browse(TBrowser *b); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void Draw(Option_t *option=""); // *MENU* - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - virtual char *GetObjectInfo(Int_t px, Int_t py) const; - virtual Int_t GetNpoints() const {return (fNpoints>>2);} - virtual Int_t GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double_t &t) const; - virtual const Double_t *GetPoint(Int_t i) const; - Int_t GetPoint(Double_t tof, Double_t *point, Int_t istart=0) const; - Bool_t IsFolder() const {return (GetNdaughters()>0)?kTRUE:kFALSE;} - virtual void Paint(Option_t *option=""); - virtual void PaintCollect(Double_t time, Double_t *box); - virtual void PaintCollectTrack(Double_t time, Double_t *box); - void PaintMarker(Double_t *point, Option_t *option=""); - virtual void PaintTrack(Option_t *option=""); - virtual void Print(Option_t *option="") const; // *MENU* - virtual void ResetTrack(); - Int_t SearchPoint(Double_t time, Int_t istart=0) const; - void SetBits(Bool_t is_default=kTRUE, Bool_t is_onelevel=kFALSE, - Bool_t is_all=kFALSE, Bool_t is_type=kFALSE); - Int_t Size(Int_t &imin, Int_t &imax); - virtual void Sizeof3D() const; - - ClassDef(TGeoTrack, 1) // geometry tracks class + TGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent = nullptr, TObject *particle = nullptr); + ~TGeoTrack() override; + + TVirtualGeoTrack *AddDaughter(Int_t id, Int_t pdgcode, TObject *particle = nullptr) override; + Int_t AddDaughter(TVirtualGeoTrack *other) override; + void AddPoint(Double_t x, Double_t y, Double_t z, Double_t t) override; + virtual void + AnimateTrack(Double_t tmin = 0, Double_t tmax = 5E-8, Double_t nframes = 200, Option_t *option = "/*"); // *MENU* + void Browse(TBrowser *b) override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *option = "") override; // *MENU* + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + char *GetObjectInfo(Int_t px, Int_t py) const override; + Int_t GetNpoints() const override { return (fNpoints >> 2); } + Int_t GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double_t &t) const override; + const Double_t *GetPoint(Int_t i) const override; + Int_t GetPoint(Double_t tof, Double_t *point, Int_t istart = 0) const; + Bool_t IsFolder() const override { return (GetNdaughters() > 0) ? kTRUE : kFALSE; } + void Paint(Option_t *option = "") override; + void PaintCollect(Double_t time, Double_t *box) override; + void PaintCollectTrack(Double_t time, Double_t *box) override; + void PaintMarker(Double_t *point, Option_t *option = ""); + void PaintTrack(Option_t *option = "") override; + void Print(Option_t *option = "") const override; // *MENU* + void ResetTrack() override; + Int_t SearchPoint(Double_t time, Int_t istart = 0) const; + void + SetBits(Bool_t is_default = kTRUE, Bool_t is_onelevel = kFALSE, Bool_t is_all = kFALSE, Bool_t is_type = kFALSE); + Int_t Size(Int_t &imin, Int_t &imax); + virtual void Sizeof3D() const; + + ClassDefOverride(TGeoTrack, 1) // geometry tracks class }; #endif - - - - diff --git a/geom/geompainter/src/TGeoChecker.cxx b/geom/geompainter/src/TGeoChecker.cxx index f5338358d2047..cf68caf52f0d6 100644 --- a/geom/geompainter/src/TGeoChecker.cxx +++ b/geom/geompainter/src/TGeoChecker.cxx @@ -94,19 +94,19 @@ ClassImp(TGeoChecker); /// Default constructor TGeoChecker::TGeoChecker() - :TObject(), - fGeoManager(NULL), - fVsafe(NULL), - fBuff1(NULL), - fBuff2(NULL), - fFullCheck(kFALSE), - fVal1(NULL), - fVal2(NULL), - fFlags(NULL), - fTimer(NULL), - fSelectedNode(NULL), - fNchecks(0), - fNmeshPoints(1000) + : TObject(), + fGeoManager(NULL), + fVsafe(NULL), + fBuff1(NULL), + fBuff2(NULL), + fFullCheck(kFALSE), + fVal1(NULL), + fVal2(NULL), + fFlags(NULL), + fTimer(NULL), + fSelectedNode(NULL), + fNchecks(0), + fNmeshPoints(1000) { } @@ -114,22 +114,22 @@ TGeoChecker::TGeoChecker() /// Constructor for a given geometry TGeoChecker::TGeoChecker(TGeoManager *geom) - :TObject(), - fGeoManager(geom), - fVsafe(NULL), - fBuff1(NULL), - fBuff2(NULL), - fFullCheck(kFALSE), - fVal1(NULL), - fVal2(NULL), - fFlags(NULL), - fTimer(NULL), - fSelectedNode(NULL), - fNchecks(0), - fNmeshPoints(1000) + : TObject(), + fGeoManager(geom), + fVsafe(NULL), + fBuff1(NULL), + fBuff2(NULL), + fFullCheck(kFALSE), + fVal1(NULL), + fVal2(NULL), + fFlags(NULL), + fTimer(NULL), + fSelectedNode(NULL), + fNchecks(0), + fNmeshPoints(1000) { - fBuff1 = new TBuffer3D(TBuffer3DTypes::kGeneric,500,3*500,0,0,0,0); - fBuff2 = new TBuffer3D(TBuffer3DTypes::kGeneric,500,3*500,0,0,0,0); + fBuff1 = new TBuffer3D(TBuffer3DTypes::kGeneric, 500, 3 * 500, 0, 0, 0, 0); + fBuff2 = new TBuffer3D(TBuffer3DTypes::kGeneric, 500, 3 * 500, 0, 0, 0, 0); } //////////////////////////////////////////////////////////////////////////////// @@ -137,15 +137,19 @@ TGeoChecker::TGeoChecker(TGeoManager *geom) TGeoChecker::~TGeoChecker() { - if (fBuff1) delete fBuff1; - if (fBuff2) delete fBuff2; - if (fTimer) delete fTimer; + if (fBuff1) + delete fBuff1; + if (fBuff2) + delete fBuff2; + if (fTimer) + delete fTimer; } //////////////////////////////////////////////////////////////////////////////// /// Print current operation progress. -void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch, Bool_t last, Bool_t refresh, const char *msg) +void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch, Bool_t last, + Bool_t refresh, const char *msg) { static Long64_t icount = 0; static TString oname; @@ -156,23 +160,26 @@ void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size static TStopwatch *owatch = 0; static Bool_t oneoftwo = kFALSE; static Int_t nrefresh = 0; - const char symbol[4] = {'=','\\','|','/'}; + const char symbol[4] = {'=', '\\', '|', '/'}; char progress[11] = " "; - Int_t ichar = icount%4; + Int_t ichar = icount % 4; TString message(msg); message += " "; if (!refresh) { nrefresh = 0; - if (!size) return; + if (!size) + return; owatch = watch; oname = opname; ocurrent = TMath::Abs(current); osize = TMath::Abs(size); - if (ocurrent > osize) ocurrent=osize; + if (ocurrent > osize) + ocurrent = osize; } else { nrefresh++; - if (!osize) return; + if (!osize) + return; } icount++; Double_t time = 0.; @@ -182,13 +189,13 @@ void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size if (owatch && !last) { owatch->Stop(); time = owatch->RealTime(); - hours = (Int_t)(time/3600.); - time -= 3600*hours; - minutes = (Int_t)(time/60.); - time -= 60*minutes; + hours = (Int_t)(time / 3600.); + time -= 3600 * hours; + minutes = (Int_t)(time / 60.); + time -= 60 * minutes; seconds = (Int_t)time; - if (refresh) { - if (oseconds==seconds) { + if (refresh) { + if (oseconds == seconds) { owatch->Continue(); return; } @@ -198,27 +205,38 @@ void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size } if (refresh && oneoftwo) { nname = oname; - if (fNchecks <= nrefresh) fNchecks = nrefresh+1; - Int_t pctdone = (Int_t)(100.*nrefresh/fNchecks); + if (fNchecks <= nrefresh) + fNchecks = nrefresh + 1; + Int_t pctdone = (Int_t)(100. * nrefresh / fNchecks); oname = TString::Format(" == %3d%% ==", pctdone); } - Double_t percent = 100.0*ocurrent/osize; - Int_t nchar = Int_t(percent/10); - if (nchar>10) nchar=10; + Double_t percent = 100.0 * ocurrent / osize; + Int_t nchar = Int_t(percent / 10); + if (nchar > 10) + nchar = 10; Int_t i; - for (i=0; i0.) fprintf(stderr, "[%6.2f %%] TIME %.2d:%.2d:%.2d %s\r", percent, hours, minutes, seconds, message.Data()); - else fprintf(stderr, "[%6.2f %%] %s\r", percent, message.Data()); - if (refresh && oneoftwo) oname = nname; - if (owatch) owatch->Continue(); + if (size < 10000) + fprintf(stderr, "%s [%10s] %4lld ", oname.Data(), progress, ocurrent); + else if (size < 100000) + fprintf(stderr, "%s [%10s] %5lld ", oname.Data(), progress, ocurrent); + else + fprintf(stderr, "%s [%10s] %7lld ", oname.Data(), progress, ocurrent); + if (time > 0.) + fprintf(stderr, "[%6.2f %%] TIME %.2d:%.2d:%.2d %s\r", percent, hours, minutes, seconds, message.Data()); + else + fprintf(stderr, "[%6.2f %%] %s\r", percent, message.Data()); + if (refresh && oneoftwo) + oname = nname; + if (owatch) + owatch->Continue(); if (last) { icount = 0; owatch = 0; @@ -239,7 +257,7 @@ void TGeoChecker::OpProgress(const char *opname, Long64_t current, Long64_t size void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) { TGeoVolume *tvol = fGeoManager->GetTopVolume(); - Info("CheckBoundaryErrors", "Top volume is %s",tvol->GetName()); + Info("CheckBoundaryErrors", "Top volume is %s", tvol->GetName()); const TGeoShape *shape = tvol->GetShape(); TGeoBBox *box = (TGeoBBox *)shape; Double_t dl[3]; @@ -252,13 +270,13 @@ void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) Char_t cdir[10]; // Tree part - TFile *f=new TFile("geobugs.root","recreate"); - TTree *bug=new TTree("bug","Geometrical problems"); - bug->Branch("pos",xyz,"xyz[3]/D"); - bug->Branch("dir",dir,"dir[3]/D"); - bug->Branch("push",&relp,"push/D"); - bug->Branch("path",&path,"path/C"); - bug->Branch("cdir",&cdir,"cdir/C"); + TFile *f = new TFile("geobugs.root", "recreate"); + TTree *bug = new TTree("bug", "Geometrical problems"); + bug->Branch("pos", xyz, "xyz[3]/D"); + bug->Branch("dir", dir, "dir[3]/D"); + bug->Branch("push", &relp, "push/D"); + bug->Branch("path", &path, "path/C"); + bug->Branch("cdir", &cdir, "cdir/C"); dl[0] = box->GetDX(); dl[1] = box->GetDY(); @@ -266,42 +284,44 @@ void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) ori[0] = (box->GetOrigin())[0]; ori[1] = (box->GetOrigin())[1]; ori[2] = (box->GetOrigin())[2]; - if (radius>0) + if (radius > 0) dl[0] = dl[1] = dl[2] = radius; TH1::AddDirectory(kFALSE); - TH1F *hnew = new TH1F("hnew","Precision pushing",30,-20.,10.); - TH1F *hold = new TH1F("hold","Precision pulling", 30,-20.,10.); - TH2F *hplotS = new TH2F("hplotS","Problematic points",100,-dl[0],dl[0],100,-dl[1],dl[1]); + TH1F *hnew = new TH1F("hnew", "Precision pushing", 30, -20., 10.); + TH1F *hold = new TH1F("hold", "Precision pulling", 30, -20., 10.); + TH2F *hplotS = new TH2F("hplotS", "Problematic points", 100, -dl[0], dl[0], 100, -dl[1], dl[1]); gStyle->SetOptStat(111111); TGeoNode *node = 0; - Long_t igen=0; - Long_t itry=0; - Long_t n100 = ntracks/100; - Double_t rad = TMath::Sqrt(dl[0]*dl[0]+dl[1]*dl[1]); + Long_t igen = 0; + Long_t itry = 0; + Long_t n100 = ntracks / 100; + Double_t rad = TMath::Sqrt(dl[0] * dl[0] + dl[1] * dl[1]); printf("Random box : %f, %f, %f, %f, %f, %f\n", ori[0], ori[1], ori[2], dl[0], dl[1], dl[2]); printf("Start... %i points\n", ntracks); - if (!fTimer) fTimer = new TStopwatch(); + if (!fTimer) + fTimer = new TStopwatch(); fTimer->Reset(); fTimer->Start(); - while (igenRndm(); - Double_t r = rad*gRandom->Rndm(); - xyz[0] = ori[0] + r*TMath::Cos(phi1); - xyz[1] = ori[1] + r*TMath::Sin(phi1); - Double_t z = (1.-2.*gRandom->Rndm()); - xyz[2] = ori[2]+dl[2]*z*TMath::Abs(z); + while (igen < ntracks) { + Double_t phi1 = TMath::TwoPi() * gRandom->Rndm(); + Double_t r = rad * gRandom->Rndm(); + xyz[0] = ori[0] + r * TMath::Cos(phi1); + xyz[1] = ori[1] + r * TMath::Sin(phi1); + Double_t z = (1. - 2. * gRandom->Rndm()); + xyz[2] = ori[2] + dl[2] * z * TMath::Abs(z); ++itry; fGeoManager->SetCurrentPoint(xyz); node = fGeoManager->FindNode(); - if (!node || node==fGeoManager->GetTopNode()) continue; + if (!node || node == fGeoManager->GetTopNode()) + continue; ++igen; - if (n100 && !(igen%n100)) - OpProgress("Sampling progress:",igen, ntracks, fTimer); - Double_t cost = 1.-2.*gRandom->Rndm(); - Double_t sint = TMath::Sqrt((1.+cost)*(1.-cost)); - Double_t phi = TMath::TwoPi()*gRandom->Rndm(); + if (n100 && !(igen % n100)) + OpProgress("Sampling progress:", igen, ntracks, fTimer); + Double_t cost = 1. - 2. * gRandom->Rndm(); + Double_t sint = TMath::Sqrt((1. + cost) * (1. - cost)); + Double_t phi = TMath::TwoPi() * gRandom->Rndm(); dir[0] = sint * TMath::Cos(phi); dir[1] = sint * TMath::Sin(phi); dir[2] = cost; @@ -310,20 +330,21 @@ void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) Double_t step = fGeoManager->GetStep(); relp = 1.e-21; - for(Int_t i=0; i<30; ++i) { - relp *=10.; - for(Int_t j=0; j<3; ++j) nxyz[j]=xyz[j]+step*(1.+relp)*dir[j]; - if(!fGeoManager->IsSameLocation(nxyz[0],nxyz[1],nxyz[2])) { - hnew->Fill(i-20.); - if(i>15) { - const Double_t* norm = fGeoManager->FindNormal(); - strncpy(path,fGeoManager->GetPath(),1024); + for (Int_t i = 0; i < 30; ++i) { + relp *= 10.; + for (Int_t j = 0; j < 3; ++j) + nxyz[j] = xyz[j] + step * (1. + relp) * dir[j]; + if (!fGeoManager->IsSameLocation(nxyz[0], nxyz[1], nxyz[2])) { + hnew->Fill(i - 20.); + if (i > 15) { + const Double_t *norm = fGeoManager->FindNormal(); + strncpy(path, fGeoManager->GetPath(), 1024); path[1023] = '\0'; - Double_t dotp = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - printf("Forward error i=%d p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", - i,xyz[0],xyz[1],xyz[2],step,dotp,path); - hplotS->Fill(xyz[0],xyz[1],(Double_t)i); - strncpy(cdir,"Forward",10); + Double_t dotp = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + printf("Forward error i=%d p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", i, xyz[0], xyz[1], xyz[2], + step, dotp, path); + hplotS->Fill(xyz[0], xyz[1], (Double_t)i); + strncpy(cdir, "Forward", 10); bug->Fill(); } break; @@ -331,19 +352,20 @@ void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) } relp = -1.e-21; - for(Int_t i=0; i<30; ++i) { - relp *=10.; - for(Int_t j=0; j<3; ++j) nxyz[j]=xyz[j]+step*(1.+relp)*dir[j]; - if(fGeoManager->IsSameLocation(nxyz[0],nxyz[1],nxyz[2])) { - hold->Fill(i-20.); - if(i>15) { - const Double_t* norm = fGeoManager->FindNormal(); - strncpy(path,fGeoManager->GetPath(),1024); + for (Int_t i = 0; i < 30; ++i) { + relp *= 10.; + for (Int_t j = 0; j < 3; ++j) + nxyz[j] = xyz[j] + step * (1. + relp) * dir[j]; + if (fGeoManager->IsSameLocation(nxyz[0], nxyz[1], nxyz[2])) { + hold->Fill(i - 20.); + if (i > 15) { + const Double_t *norm = fGeoManager->FindNormal(); + strncpy(path, fGeoManager->GetPath(), 1024); path[1023] = '\0'; - Double_t dotp = norm[0]*dir[0]+norm[1]*dir[1]+norm[2]*dir[2]; - printf("Backward error i=%d p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", - i,xyz[0],xyz[1],xyz[2],step,dotp,path); - strncpy(cdir,"Backward",10); + Double_t dotp = norm[0] * dir[0] + norm[1] * dir[1] + norm[2] * dir[2]; + printf("Backward error i=%d p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", i, xyz[0], xyz[1], xyz[2], + step, dotp, path); + strncpy(cdir, "Backward", 10); bug->Fill(); } break; @@ -352,25 +374,27 @@ void TGeoChecker::CheckBoundaryErrors(Int_t ntracks, Double_t radius) } fTimer->Stop(); - if (itry) printf("CPU time/point = %5.2emus: Real time/point = %5.2emus\n", - 1000000.*fTimer->CpuTime()/itry,1000000.*fTimer->RealTime()/itry); + if (itry) + printf("CPU time/point = %5.2emus: Real time/point = %5.2emus\n", 1000000. * fTimer->CpuTime() / itry, + 1000000. * fTimer->RealTime() / itry); bug->Write(); delete bug; - bug=0; + bug = 0; delete f; CheckBoundaryReference(); - if (itry) printf("Effic = %3.1f%%\n",(100.*igen)/itry); - TCanvas *c1 = new TCanvas("c1","Results",600,800); - c1->Divide(1,2); + if (itry) + printf("Effic = %3.1f%%\n", (100. * igen) / itry); + TCanvas *c1 = new TCanvas("c1", "Results", 600, 800); + c1->Divide(1, 2); c1->cd(1); gPad->SetLogy(); hold->Draw(); c1->cd(2); gPad->SetLogy(); hnew->Draw(); - /*TCanvas *c3 = */new TCanvas("c3","Plot",600,600); + /*TCanvas *c3 = */ new TCanvas("c3", "Plot", 600, 600); hplotS->Draw("cont0"); } @@ -389,43 +413,46 @@ void TGeoChecker::CheckBoundaryReference(Int_t icheck) Char_t path[1024]; Char_t cdir[10]; // Tree part - TFile *f=new TFile("geobugs.root","read"); - TTree *bug=(TTree*)f->Get("bug"); - bug->SetBranchAddress("pos",xyz); - bug->SetBranchAddress("dir",dir); - bug->SetBranchAddress("push",&push); - bug->SetBranchAddress("path",&path); - bug->SetBranchAddress("cdir",&cdir); + TFile *f = new TFile("geobugs.root", "read"); + TTree *bug = (TTree *)f->Get("bug"); + bug->SetBranchAddress("pos", xyz); + bug->SetBranchAddress("dir", dir); + bug->SetBranchAddress("push", &push); + bug->SetBranchAddress("path", &path); + bug->SetBranchAddress("cdir", &cdir); Int_t nentries = (Int_t)bug->GetEntries(); - printf("nentries %d\n",nentries); - if (icheck<0) { - for (Int_t i=0;iGetEntry(i); - printf("%-9s error push=%g p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", - cdir,push,xyz[0],xyz[1],xyz[2],1.,1.,path); + printf("%-9s error push=%g p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", cdir, push, xyz[0], xyz[1], + xyz[2], 1., 1., path); } } else { - if (icheck>=nentries) return; + if (icheck >= nentries) + return; Int_t idebug = TGeoManager::GetVerboseLevel(); TGeoManager::SetVerboseLevel(5); bug->GetEntry(icheck); - printf("%-9s error push=%g p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", - cdir,push,xyz[0],xyz[1],xyz[2],1.,1.,path); + printf("%-9s error push=%g p=%5.4f %5.4f %5.4f s=%5.4f dot=%5.4f path=%s\n", cdir, push, xyz[0], xyz[1], xyz[2], + 1., 1., path); fGeoManager->SetCurrentPoint(xyz); fGeoManager->SetCurrentDirection(dir); fGeoManager->FindNode(); TGeoNode *next = fGeoManager->FindNextBoundary(); Double_t step = fGeoManager->GetStep(); - for (Int_t j=0; j<3; j++) nxyz[j]=xyz[j]+step*(1.+0.1*push)*dir[j]; - Bool_t change = !fGeoManager->IsSameLocation(nxyz[0],nxyz[1],nxyz[2]); + for (Int_t j = 0; j < 3; j++) + nxyz[j] = xyz[j] + step * (1. + 0.1 * push) * dir[j]; + Bool_t change = !fGeoManager->IsSameLocation(nxyz[0], nxyz[1], nxyz[2]); printf("step=%g in: %s\n", step, fGeoManager->GetPath()); - printf(" -> next = %s push=%g change=%d\n", next->GetName(),push, (UInt_t)change); + printf(" -> next = %s push=%g change=%d\n", next->GetName(), push, (UInt_t)change); next->GetVolume()->InspectShape(); next->GetVolume()->DrawOnly(); if (next != fGeoManager->GetCurrentNode()) { Int_t index1 = fGeoManager->GetCurrentVolume()->GetIndex(next); - if (index1>=0) fGeoManager->CdDown(index1); + if (index1 >= 0) + fGeoManager->CdDown(index1); } TPolyMarker3D *pm = new TPolyMarker3D(); fGeoManager->MasterToLocal(xyz, lnext); @@ -435,7 +462,8 @@ void TGeoChecker::CheckBoundaryReference(Int_t icheck) pm->SetMarkerColor(kRed); pm->Draw("SAME"); TPolyMarker3D *pm1 = new TPolyMarker3D(); - for (Int_t j=0; j<3; j++) nxyz[j]=xyz[j]+step*dir[j]; + for (Int_t j = 0; j < 3; j++) + nxyz[j] = xyz[j] + step * dir[j]; fGeoManager->MasterToLocal(nxyz, lnext); pm1->SetNextPoint(lnext[0], lnext[1], lnext[2]); pm1->SetMarkerStyle(2); @@ -475,22 +503,23 @@ void TGeoChecker::CheckBoundaryReference(Int_t icheck) void TGeoChecker::CheckGeometryFull(Bool_t checkoverlaps, Bool_t checkcrossings, Int_t ntracks, const Double_t *vertex) { Int_t nuid = fGeoManager->GetListOfUVolumes()->GetEntries(); - if (!fTimer) fTimer = new TStopwatch(); + if (!fTimer) + fTimer = new TStopwatch(); Int_t i; Double_t value; fFlags = new Bool_t[nuid]; - memset(fFlags, 0, nuid*sizeof(Bool_t)); + memset(fFlags, 0, nuid * sizeof(Bool_t)); TGeoVolume *vol; - TCanvas *c = new TCanvas("overlaps", "Overlaps by sampling", 800,800); + TCanvas *c = new TCanvas("overlaps", "Overlaps by sampling", 800, 800); -// STAGE 1: Overlap checking by sampling per volume + // STAGE 1: Overlap checking by sampling per volume if (checkoverlaps) { printf("====================================================================\n"); printf("STAGE 1: Overlap checking by sampling within 10 microns\n"); printf("====================================================================\n"); fGeoManager->CheckOverlaps(0.001, "s"); - // STAGE 2: Global overlap/extrusion checking + // STAGE 2: Global overlap/extrusion checking printf("====================================================================\n"); printf("STAGE 2: Global overlap/extrusion checking within 10 microns\n"); printf("====================================================================\n"); @@ -498,7 +527,7 @@ void TGeoChecker::CheckGeometryFull(Bool_t checkoverlaps, Bool_t checkcrossings, } if (!checkcrossings) { - delete [] fFlags; + delete[] fFlags; fFlags = 0; delete c; return; @@ -506,131 +535,136 @@ void TGeoChecker::CheckGeometryFull(Bool_t checkoverlaps, Bool_t checkcrossings, fVal1 = new Double_t[nuid]; fVal2 = new Double_t[nuid]; - memset(fVal1, 0, nuid*sizeof(Double_t)); - memset(fVal2, 0, nuid*sizeof(Double_t)); + memset(fVal1, 0, nuid * sizeof(Double_t)); + memset(fVal2, 0, nuid * sizeof(Double_t)); // STAGE 3: How many crossings per volume in a realistic case ? // Ignore volumes with no daughters // Generate rays from vertex in phi=[0,2*pi] theta=[0,pi] -// Int_t ntracks = 1000000; + // Int_t ntracks = 1000000; printf("====================================================================\n"); - printf("STAGE 3: Propagating %i tracks starting from vertex\n and counting number of boundary crossings...\n", ntracks); + printf("STAGE 3: Propagating %i tracks starting from vertex\n and counting number of boundary crossings...\n", + ntracks); printf("====================================================================\n"); Int_t nbound = 0; Double_t theta, phi; Double_t point[3], dir[3]; - memset(point, 0, 3*sizeof(Double_t)); - if (vertex) memcpy(point, vertex, 3*sizeof(Double_t)); + memset(point, 0, 3 * sizeof(Double_t)); + if (vertex) + memcpy(point, vertex, 3 * sizeof(Double_t)); fTimer->Reset(); fTimer->Start(); - for (i=0; iRndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); - if ((i%100)==0) OpProgress("Transporting tracks",i, ntracks, fTimer); -// if ((i%1000)==0) printf("... remaining tracks %i\n", ntracks-i); - nbound += PropagateInGeom(point,dir); + for (i = 0; i < ntracks; i++) { + phi = 2. * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); + if ((i % 100) == 0) + OpProgress("Transporting tracks", i, ntracks, fTimer); + // if ((i%1000)==0) printf("... remaining tracks %i\n", ntracks-i); + nbound += PropagateInGeom(point, dir); } if (!nbound) { printf("No boundary crossed\n"); return; } fTimer->Stop(); - Double_t time1 = fTimer->CpuTime() *1.E6; - Double_t time2 = time1/ntracks; - Double_t time3 = time1/nbound; - OpProgress("Transporting tracks",ntracks, ntracks, fTimer, kTRUE); + Double_t time1 = fTimer->CpuTime() * 1.E6; + Double_t time2 = time1 / ntracks; + Double_t time3 = time1 / nbound; + OpProgress("Transporting tracks", ntracks, ntracks, fTimer, kTRUE); printf("Time for crossing %i boundaries: %g [ms]\n", nbound, time1); printf("Time per track for full geometry traversal: %g [ms], per crossing: %g [ms]\n", time2, time3); -// STAGE 4: How much time per volume: + // STAGE 4: How much time per volume: printf("====================================================================\n"); printf("STAGE 4: How much navigation time per volume per next+safety call\n"); printf("====================================================================\n"); TGeoIterator next(fGeoManager->GetTopVolume()); - TGeoNode*current; + TGeoNode *current; TString path; vol = fGeoManager->GetTopVolume(); - memset(fFlags, 0, nuid*sizeof(Bool_t)); + memset(fFlags, 0, nuid * sizeof(Bool_t)); TStopwatch timer; timer.Start(); i = 0; char volname[30]; - strncpy(volname, vol->GetName(),15); + strncpy(volname, vol->GetName(), 15); volname[15] = '\0'; - OpProgress(volname,i++, nuid, &timer); + OpProgress(volname, i++, nuid, &timer); Score(vol, 1, TimingPerVolume(vol)); - while ((current=next())) { + while ((current = next())) { vol = current->GetVolume(); Int_t uid = vol->GetNumber(); - if (fFlags[uid]) continue; + if (fFlags[uid]) + continue; fFlags[uid] = kTRUE; next.GetPath(path); fGeoManager->cd(path.Data()); - strncpy(volname, vol->GetName(),15); + strncpy(volname, vol->GetName(), 15); volname[15] = '\0'; - OpProgress(volname,i++, nuid, &timer); - Score(vol,1,TimingPerVolume(vol)); + OpProgress(volname, i++, nuid, &timer); + Score(vol, 1, TimingPerVolume(vol)); } - OpProgress("STAGE 4 completed",i, nuid, &timer, kTRUE); + OpProgress("STAGE 4 completed", i, nuid, &timer, kTRUE); // Draw some histos Double_t time_tot_pertrack = 0.; - TCanvas *c1 = new TCanvas("c2","ncrossings",10,10,900,500); + TCanvas *c1 = new TCanvas("c2", "ncrossings", 10, 10, 900, 500); c1->SetGrid(); c1->SetTopMargin(0.15); TFile *f = new TFile("statistics.root", "RECREATE"); - TH1F *h = new TH1F("h","number of boundary crossings per volume",3,0,3); + TH1F *h = new TH1F("h", "number of boundary crossings per volume", 3, 0, 3); h->SetStats(0); h->SetFillColor(38); h->SetCanExtend(TH1::kAllAxes); - memset(fFlags, 0, nuid*sizeof(Bool_t)); - for (i=0; iGetVolume(i); - if (!vol->GetNdaughters()) continue; - time_tot_pertrack += fVal1[i]*fVal2[i]; + if (!vol->GetNdaughters()) + continue; + time_tot_pertrack += fVal1[i] * fVal2[i]; h->Fill(vol->GetName(), (Int_t)fVal1[i]); } time_tot_pertrack /= ntracks; h->LabelsDeflate(); - h->LabelsOption(">","X"); + h->LabelsOption(">", "X"); h->Draw(); - - TCanvas *c2 = new TCanvas("c3","time spent per volume in navigation",10,10,900,500); + TCanvas *c2 = new TCanvas("c3", "time spent per volume in navigation", 10, 10, 900, 500); c2->SetGrid(); c2->SetTopMargin(0.15); - TH2F *h2 = new TH2F("h2", "time per FNB call vs. ndaughters", 100, 0,100,100,0,15); + TH2F *h2 = new TH2F("h2", "time per FNB call vs. ndaughters", 100, 0, 100, 100, 0, 15); h2->SetStats(0); h2->SetMarkerStyle(2); - TH1F *h1 = new TH1F("h1","percent of time spent per volume",3,0,3); + TH1F *h1 = new TH1F("h1", "percent of time spent per volume", 3, 0, 3); h1->SetStats(0); h1->SetFillColor(38); h1->SetCanExtend(TH1::kAllAxes); - for (i=0; iGetVolume(i); - if (!vol || !vol->GetNdaughters()) continue; - value = fVal1[i]*fVal2[i]/ntracks/time_tot_pertrack; + if (!vol || !vol->GetNdaughters()) + continue; + value = fVal1[i] * fVal2[i] / ntracks / time_tot_pertrack; h1->Fill(vol->GetName(), value); h2->Fill(vol->GetNdaughters(), fVal2[i]); } h1->LabelsDeflate(); - h1->LabelsOption(">","X"); + h1->LabelsOption(">", "X"); h1->Draw(); - TCanvas *c3 = new TCanvas("c4","timing vs. ndaughters",10,10,900,500); + TCanvas *c3 = new TCanvas("c4", "timing vs. ndaughters", 10, 10, 900, 500); c3->SetGrid(); c3->SetTopMargin(0.15); h2->Draw(); f->Write(); - delete [] fFlags; + delete[] fFlags; fFlags = 0; - delete [] fVal1; + delete[] fVal1; fVal1 = 0; - delete [] fVal2; + delete[] fVal2; fVal2 = 0; delete fTimer; fTimer = 0; @@ -648,23 +682,24 @@ Int_t TGeoChecker::PropagateInGeom(Double_t *start, Double_t *dir) Int_t nzero = 0; Int_t nhits = 0; while (!fGeoManager->IsOutside()) { - if (nzero>3) { - // Problems in trying to cross a boundary + if (nzero > 3) { + // Problems in trying to cross a boundary printf("Error in trying to cross boundary of %s\n", current->GetName()); return nhits; } current = fGeoManager->FindNextBoundaryAndStep(TGeoShape::Big(), kFALSE); - if (!current || fGeoManager->IsOutside()) return nhits; + if (!current || fGeoManager->IsOutside()) + return nhits; Double_t step = fGeoManager->GetStep(); - if (step<2.*TGeoShape::Tolerance()) { + if (step < 2. * TGeoShape::Tolerance()) { nzero++; continue; - } - else nzero = 0; + } else + nzero = 0; // Generate the hit nhits++; TGeoVolume *vol = current->GetVolume(); - Score(vol,0,1.); + Score(vol, 0, 1.); Int_t iup = 1; TGeoNode *mother = fGeoManager->GetMother(iup++); while (mother && mother->GetVolume()->IsAssembly()) { @@ -682,20 +717,18 @@ void TGeoChecker::Score(TGeoVolume *vol, Int_t ifield, Double_t value) { Int_t uid = vol->GetNumber(); switch (ifield) { - case 0: - fVal1[uid] += value; - break; - case 1: - fVal2[uid] += value; + case 0: fVal1[uid] += value; break; + case 1: fVal2[uid] += value; } } //////////////////////////////////////////////////////////////////////////////// /// Set number of points to be generated on the shape outline when checking for overlaps. -void TGeoChecker::SetNmeshPoints(Int_t npoints) { +void TGeoChecker::SetNmeshPoints(Int_t npoints) +{ fNmeshPoints = npoints; - if (npoints<1000) { + if (npoints < 1000) { Error("SetNmeshPoints", "Cannot allow less than 1000 points for checking - set to 1000"); fNmeshPoints = 1000; } @@ -718,22 +751,22 @@ Double_t TGeoChecker::TimingPerVolume(TGeoVolume *vol) Double_t oz = (box->GetOrigin())[2]; Double_t point[3], dir[3], lpt[3], ldir[3]; Double_t pstep = 0.; - pstep = TMath::Max(pstep,dz); + pstep = TMath::Max(pstep, dz); Double_t theta, phi; Int_t idaughter; fTimer->Start(); - for (Int_t i=0; i<1000000; i++) { - lpt[0] = ox-dx+2*dx*gRandom->Rndm(); - lpt[1] = oy-dy+2*dy*gRandom->Rndm(); - lpt[2] = oz-dz+2*dz*gRandom->Rndm(); - fGeoManager->GetCurrentMatrix()->LocalToMaster(lpt,point); - fGeoManager->SetCurrentPoint(point[0],point[1],point[2]); - phi = 2*TMath::Pi()*gRandom->Rndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - ldir[0]=TMath::Sin(theta)*TMath::Cos(phi); - ldir[1]=TMath::Sin(theta)*TMath::Sin(phi); - ldir[2]=TMath::Cos(theta); - fGeoManager->GetCurrentMatrix()->LocalToMasterVect(ldir,dir); + for (Int_t i = 0; i < 1000000; i++) { + lpt[0] = ox - dx + 2 * dx * gRandom->Rndm(); + lpt[1] = oy - dy + 2 * dy * gRandom->Rndm(); + lpt[2] = oz - dz + 2 * dz * gRandom->Rndm(); + fGeoManager->GetCurrentMatrix()->LocalToMaster(lpt, point); + fGeoManager->SetCurrentPoint(point[0], point[1], point[2]); + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + ldir[0] = TMath::Sin(theta) * TMath::Cos(phi); + ldir[1] = TMath::Sin(theta) * TMath::Sin(phi); + ldir[2] = TMath::Cos(theta); + fGeoManager->GetCurrentMatrix()->LocalToMasterVect(ldir, dir); fGeoManager->SetCurrentDirection(dir); fGeoManager->SetStep(pstep); fGeoManager->ResetState(); @@ -744,14 +777,15 @@ Double_t TGeoChecker::TimingPerVolume(TGeoVolume *vol) // dist = vol->GetShape()->DistFromOutside(lpt,ldir,3,pstep); // if (dist>=pstep) continue; } else { - vol->GetShape()->DistFromInside(lpt,ldir,3,pstep); + vol->GetShape()->DistFromInside(lpt, ldir, 3, pstep); } - if (!vol->GetNdaughters()) vol->GetShape()->Safety(lpt, inside); + if (!vol->GetNdaughters()) + vol->GetShape()->Safety(lpt, inside); } if (vol->GetNdaughters()) { fGeoManager->Safety(); - fGeoManager->FindNextDaughterBoundary(point,dir,idaughter,kFALSE); + fGeoManager->FindNextDaughterBoundary(point, dir, idaughter, kFALSE); } } fTimer->Stop(); @@ -759,9 +793,11 @@ Double_t TGeoChecker::TimingPerVolume(TGeoVolume *vol) Int_t uid = vol->GetNumber(); Int_t ncrossings = (Int_t)fVal1[uid]; if (!vol->GetNdaughters()) - printf("Time for volume %s (shape=%s): %g [ms] ndaughters=%d ncross=%d\n", vol->GetName(), vol->GetShape()->GetName(), time_per_track, vol->GetNdaughters(), ncrossings); + printf("Time for volume %s (shape=%s): %g [ms] ndaughters=%d ncross=%d\n", vol->GetName(), + vol->GetShape()->GetName(), time_per_track, vol->GetNdaughters(), ncrossings); else - printf("Time for volume %s (assemb=%d): %g [ms] ndaughters=%d ncross=%d\n", vol->GetName(), vol->IsAssembly(), time_per_track, vol->GetNdaughters(), ncrossings); + printf("Time for volume %s (assemb=%d): %g [ms] ndaughters=%d ncross=%d\n", vol->GetName(), vol->IsAssembly(), + time_per_track, vol->GetNdaughters(), ncrossings); return time_per_track; } @@ -777,8 +813,8 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D Double_t dir[3]; Double_t dummy[3]; Double_t eps = 0.; - Double_t *array1 = new Double_t[3*1000]; - Double_t *array2 = new Double_t[3*1000]; + Double_t *array1 = new Double_t[3 * 1000]; + Double_t *array2 = new Double_t[3 * 1000]; TObjArray *pma = new TObjArray(); TPolyMarker3D *pm; pm = new TPolyMarker3D(); @@ -797,70 +833,76 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D pm->SetMarkerSize(0.4); pma->AddAt(pm, 2); Int_t nelem1, nelem2; - Int_t dim1=1000, dim2=1000; - if ((startx==0) && (starty==0) && (startz==0)) eps=1E-3; - start[0] = startx+eps; - start[1] = starty+eps; - start[2] = startz+eps; - Int_t n10=nrays/10; - Double_t theta,phi; + Int_t dim1 = 1000, dim2 = 1000; + if ((startx == 0) && (starty == 0) && (startz == 0)) + eps = 1E-3; + start[0] = startx + eps; + start[1] = starty + eps; + start[2] = startz + eps; + Int_t n10 = nrays / 10; + Double_t theta, phi; Double_t dw, dwmin, dx, dy, dz; Int_t ist1, ist2, ifound; - for (i=0; iRndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); // shoot direct ray - nelem1=nelem2=0; -// printf("DIRECT %i\n", i); + nelem1 = nelem2 = 0; + // printf("DIRECT %i\n", i); array1 = ShootRay(&start[0], dir[0], dir[1], dir[2], array1, nelem1, dim1); - if (!nelem1) continue; -// for (j=0; jAt(0); - pm->SetNextPoint(array1[3*j], array1[3*j+1], array1[3*j+2]); + for (j = 0; j < nelem1; j++) { + pm = (TPolyMarker3D *)pma->At(0); + pm->SetNextPoint(array1[3 * j], array1[3 * j + 1], array1[3 * j + 2]); } continue; } -// printf("BACKWARDS\n"); - Int_t k=nelem2>>1; - for (j=0; j> 1; + for (j = 0; j < k; j++) { + memcpy(&dummy[0], &array2[3 * j], 3 * sizeof(Double_t)); + memcpy(&array2[3 * j], &array2[3 * (nelem2 - 1 - j)], 3 * sizeof(Double_t)); + memcpy(&array2[3 * (nelem2 - 1 - j)], &dummy[0], 3 * sizeof(Double_t)); } -// for (j=0; jSetCurrentPoint(&array1[3*ist1]); + dx = array1[3 * ist1] - array2[3 * ist2]; + dy = array1[3 * ist1 + 1] - array2[3 * ist2 + 1]; + dz = array1[3 * ist1 + 2] - array2[3 * ist2 + 2]; + dw = dx * dir[0] + dy * dir[1] + dz * dir[2]; + fGeoManager->SetCurrentPoint(&array1[3 * ist1]); fGeoManager->FindNode(); -// printf("%i : %s (%g, %g, %g)\n", ist1, fGeoManager->GetPath(), -// array1[3*ist1], array1[3*ist1+1], array1[3*ist1+2]); - if (TMath::Abs(dw)<1E-4) { -// printf(" matching %i (%g, %g, %g)\n", ist2, array2[3*ist2], array2[3*ist2+1], array2[3*ist2+2]); + // printf("%i : %s (%g, %g, %g)\n", ist1, fGeoManager->GetPath(), + // array1[3*ist1], array1[3*ist1+1], array1[3*ist1+2]); + if (TMath::Abs(dw) < 1E-4) { + // printf(" matching %i (%g, %g, %g)\n", ist2, array2[3*ist2], array2[3*ist2+1], array2[3*ist2+2]); ist2++; } else { - printf("### NOT MATCHING %i f:(%f, %f, %f) b:(%f %f %f) DCLOSE=%f\n", ist2, array1[3*ist1], array1[3*ist1+1], array1[3*ist1+2], array2[3*ist2], array2[3*ist2+1], array2[3*ist2+2],dw); - pm = (TPolyMarker3D*)pma->At(0); - pm->SetNextPoint(array2[3*ist2], array2[3*ist2+1], array2[3*ist2+2]); - if (dw<0) { + printf("### NOT MATCHING %i f:(%f, %f, %f) b:(%f %f %f) DCLOSE=%f\n", ist2, array1[3 * ist1], + array1[3 * ist1 + 1], array1[3 * ist1 + 2], array2[3 * ist2], array2[3 * ist2 + 1], + array2[3 * ist2 + 2], dw); + pm = (TPolyMarker3D *)pma->At(0); + pm->SetNextPoint(array2[3 * ist2], array2[3 * ist2 + 1], array2[3 * ist2 + 2]); + if (dw < 0) { // first boundary missed on way back } else { // first boundary different on way back @@ -868,44 +910,45 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D } } - while ((ist1SetCurrentPoint(&array1[3*ist1+3]); + while ((ist1 < nelem1 - 1) && (ist2 < nelem2)) { + fGeoManager->SetCurrentPoint(&array1[3 * ist1 + 3]); fGeoManager->FindNode(); -// printf("%i : %s (%g, %g, %g)\n", ist1+1, fGeoManager->GetPath(), -// array1[3*ist1+3], array1[3*ist1+4], array1[3*ist1+5]); + // printf("%i : %s (%g, %g, %g)\n", ist1+1, fGeoManager->GetPath(), + // array1[3*ist1+3], array1[3*ist1+4], array1[3*ist1+5]); - dx = array1[3*ist1+3]-array1[3*ist1]; - dy = array1[3*ist1+4]-array1[3*ist1+1]; - dz = array1[3*ist1+5]-array1[3*ist1+2]; + dx = array1[3 * ist1 + 3] - array1[3 * ist1]; + dy = array1[3 * ist1 + 4] - array1[3 * ist1 + 1]; + dz = array1[3 * ist1 + 5] - array1[3 * ist1 + 2]; // distance to next point - dwmin = dx+dir[0]+dy*dir[1]+dz*dir[2]; - while (ist2SetCurrentPoint(&array2[3*ist2]); + // extra boundary found on way back + fGeoManager->SetCurrentPoint(&array2[3 * ist2]); fGeoManager->FindNode(); - pm = (TPolyMarker3D*)pma->At(2); - pm->SetNextPoint(array2[3*ist2], array2[3*ist2+1], array2[3*ist2+2]); + pm = (TPolyMarker3D *)pma->At(2); + pm->SetNextPoint(array2[3 * ist2], array2[3 * ist2 + 1], array2[3 * ist2 + 2]); printf("### EXTRA BOUNDARY %i : %s found at DCLOSE=%f\n", ist2, fGeoManager->GetPath(), dw); ist2++; continue; @@ -913,10 +956,10 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D } else { if (!ifound) { // point ist1+1 not found on way back - fGeoManager->SetCurrentPoint(&array1[3*ist1+3]); + fGeoManager->SetCurrentPoint(&array1[3 * ist1 + 3]); fGeoManager->FindNode(); - pm = (TPolyMarker3D*)pma->At(1); - pm->SetNextPoint(array2[3*ist1+3], array2[3*ist1+4], array2[3*ist1+5]); + pm = (TPolyMarker3D *)pma->At(1); + pm->SetNextPoint(array2[3 * ist1 + 3], array2[3 * ist1 + 4], array2[3 * ist1 + 5]); printf("### BOUNDARY MISSED BACK #########################\n"); ist1++; break; @@ -928,18 +971,18 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D } } } - pm = (TPolyMarker3D*)pma->At(0); + pm = (TPolyMarker3D *)pma->At(0); pm->Draw("SAME"); - pm = (TPolyMarker3D*)pma->At(1); + pm = (TPolyMarker3D *)pma->At(1); pm->Draw("SAME"); - pm = (TPolyMarker3D*)pma->At(2); + pm = (TPolyMarker3D *)pma->At(2); pm->Draw("SAME"); if (gPad) { gPad->Modified(); gPad->Update(); } - delete [] array1; - delete [] array2; + delete[] array1; + delete[] array2; delete pma; // markers are drawn on the pad } @@ -949,17 +992,18 @@ void TGeoChecker::CheckGeometry(Int_t nrays, Double_t startx, Double_t starty, D void TGeoChecker::CleanPoints(Double_t *points, Int_t &numPoints) const { Int_t ipoint = 0; - Int_t j, k=0; + Int_t j, k = 0; Double_t rsq; - for (Int_t i=0; iIsAssembly() || vol2->IsAssembly()) @@ -975,11 +1020,11 @@ TGeoOverlap *TGeoChecker::MakeCheckOverlap(const char *name, TGeoVolume *vol1, T if (dynamic_cast(vol1->GetShape()) || dynamic_cast(vol2->GetShape())) return nullptr; Int_t numPoints1 = fBuff1->NbPnts(); - Int_t numSegs1 = fBuff1->NbSegs(); - Int_t numPols1 = fBuff1->NbPols(); + Int_t numSegs1 = fBuff1->NbSegs(); + Int_t numPols1 = fBuff1->NbPols(); Int_t numPoints2 = fBuff2->NbPnts(); - Int_t numSegs2 = fBuff2->NbSegs(); - Int_t numPols2 = fBuff2->NbPols(); + Int_t numSegs2 = fBuff2->NbSegs(); + Int_t numPols2 = fBuff2->NbPols(); Int_t ip; Bool_t extrude, isextrusion, isoverlapping; Double_t *points1 = fBuff1->fPnts; @@ -990,92 +1035,98 @@ TGeoOverlap *TGeoChecker::MakeCheckOverlap(const char *name, TGeoVolume *vol1, T Double_t tolerance = TGeoShape::Tolerance(); TGeoShape *shape1 = vol1->GetShape(); TGeoShape *shape2 = vol2->GetShape(); - OpProgress("refresh", 0,0,NULL,kFALSE,kTRUE); + OpProgress("refresh", 0, 0, NULL, kFALSE, kTRUE); shape1->GetMeshNumbers(numPoints1, numSegs1, numPols1); - if (fBuff1->fID != (TObject*)shape1) { + if (fBuff1->fID != (TObject *)shape1) { // Fill first buffer. - fBuff1->SetRawSizes(TMath::Max(numPoints1,fNmeshPoints), 3*TMath::Max(numPoints1,fNmeshPoints), 0, 0, 0, 0); + fBuff1->SetRawSizes(TMath::Max(numPoints1, fNmeshPoints), 3 * TMath::Max(numPoints1, fNmeshPoints), 0, 0, 0, 0); points1 = fBuff1->fPnts; if (shape1->GetPointsOnSegments(fNmeshPoints, points1)) { numPoints1 = fNmeshPoints; } else { shape1->SetPoints(points1); } -// if (shape1->InheritsFrom(TGeoPcon::Class())) { -// CleanPoints(points1, numPoints1); -// fBuff1->SetRawSizes(numPoints1, 3*numPoints1,0, 0, 0, 0); -// } + // if (shape1->InheritsFrom(TGeoPcon::Class())) { + // CleanPoints(points1, numPoints1); + // fBuff1->SetRawSizes(numPoints1, 3*numPoints1,0, 0, 0, 0); + // } fBuff1->fID = shape1; } shape2->GetMeshNumbers(numPoints2, numSegs2, numPols2); - if (fBuff2->fID != (TObject*)shape2) { + if (fBuff2->fID != (TObject *)shape2) { // Fill second buffer. - fBuff2->SetRawSizes(TMath::Max(numPoints2,fNmeshPoints), 3*TMath::Max(numPoints2,fNmeshPoints), 0, 0, 0,0); + fBuff2->SetRawSizes(TMath::Max(numPoints2, fNmeshPoints), 3 * TMath::Max(numPoints2, fNmeshPoints), 0, 0, 0, 0); points2 = fBuff2->fPnts; if (shape2->GetPointsOnSegments(fNmeshPoints, points2)) { numPoints2 = fNmeshPoints; } else { shape2->SetPoints(points2); } -// if (shape2->InheritsFrom(TGeoPcon::Class())) { -// CleanPoints(points2, numPoints2); -// fBuff1->SetRawSizes(numPoints2, 3*numPoints2,0,0,0,0); -// } + // if (shape2->InheritsFrom(TGeoPcon::Class())) { + // CleanPoints(points2, numPoints2); + // fBuff1->SetRawSizes(numPoints2, 3*numPoints2,0,0,0,0); + // } fBuff2->fID = shape2; } if (!isovlp) { - // Extrusion case. Test vol2 extrude vol1. - isextrusion=kFALSE; + // Extrusion case. Test vol2 extrude vol1. + isextrusion = kFALSE; // loop all points of the daughter - for (ip=0; ipLocalToMaster(local, point); mat1->MasterToLocal(point, local); extrude = !shape1->Contains(local); if (extrude) { safety = shape1->Safety(local, kFALSE); - if (safetySetNextPoint(point[0],point[1],point[2]); + nodeovlp = new TGeoOverlap(name, vol1, vol2, mat1, mat2, kFALSE, safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); fGeoManager->AddOverlap(nodeovlp); } else { - if (safety>nodeovlp->GetOverlap()) nodeovlp->SetOverlap(safety); - nodeovlp->SetNextPoint(point[0],point[1],point[2]); - } + if (safety > nodeovlp->GetOverlap()) + nodeovlp->SetOverlap(safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); + } } } // loop all points of the mother - for (ip=0; ipLocalToMaster(local, point); mat2->MasterToLocal(point, local1); extrude = shape2->Contains(local1); if (extrude) { // skip points on mother mesh that have no neighborhood outside mother - safety = shape1->Safety(local,kTRUE); - if (safety>1E-6) { + safety = shape1->Safety(local, kTRUE); + if (safety > 1E-6) { extrude = kFALSE; } else { - safety = shape2->Safety(local1,kTRUE); - if (safetySafety(local1, kTRUE); + if (safety < ovlp) + extrude = kFALSE; } } if (extrude) { if (!isextrusion) { isextrusion = kTRUE; - nodeovlp = new TGeoOverlap(name, vol1,vol2,mat1,mat2,kFALSE,safety); - nodeovlp->SetNextPoint(point[0],point[1],point[2]); + nodeovlp = new TGeoOverlap(name, vol1, vol2, mat1, mat2, kFALSE, safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); fGeoManager->AddOverlap(nodeovlp); } else { - if (safety>nodeovlp->GetOverlap()) nodeovlp->SetOverlap(safety); - nodeovlp->SetNextPoint(point[0],point[1],point[2]); + if (safety > nodeovlp->GetOverlap()) + nodeovlp->SetOverlap(safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); } } } @@ -1084,48 +1135,54 @@ TGeoOverlap *TGeoChecker::MakeCheckOverlap(const char *name, TGeoVolume *vol1, T // Check overlap isoverlapping = kFALSE; // loop all points of first candidate - for (ip=0; ipLocalToMaster(local, point); mat2->MasterToLocal(point, local); // now point in local reference of second Bool_t overlap = shape2->Contains(local); if (overlap) { safety = shape2->Safety(local, kTRUE); - if (safetySetNextPoint(point[0],point[1],point[2]); + nodeovlp = new TGeoOverlap(name, vol1, vol2, mat1, mat2, kTRUE, safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); fGeoManager->AddOverlap(nodeovlp); } else { - if (safety>nodeovlp->GetOverlap()) nodeovlp->SetOverlap(safety); - nodeovlp->SetNextPoint(point[0],point[1],point[2]); + if (safety > nodeovlp->GetOverlap()) + nodeovlp->SetOverlap(safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); } } } // loop all points of second candidate - for (ip=0; ipLocalToMaster(local, point); mat1->MasterToLocal(point, local); // now point in local reference of first Bool_t overlap = shape1->Contains(local); if (overlap) { safety = shape1->Safety(local, kTRUE); - if (safetySetNextPoint(point[0],point[1],point[2]); + nodeovlp = new TGeoOverlap(name, vol1, vol2, mat1, mat2, kTRUE, safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); fGeoManager->AddOverlap(nodeovlp); } else { - if (safety>nodeovlp->GetOverlap()) nodeovlp->SetOverlap(safety); - nodeovlp->SetNextPoint(point[0],point[1],point[2]); + if (safety > nodeovlp->GetOverlap()) + nodeovlp->SetOverlap(safety); + nodeovlp->SetNextPoint(point[0], point[1], point[2]); } } } @@ -1139,14 +1196,16 @@ TGeoOverlap *TGeoChecker::MakeCheckOverlap(const char *name, TGeoVolume *vol1, T void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, Int_t npoints) const { Int_t nd = vol->GetNdaughters(); - if (nd<2) return; + if (nd < 2) + return; TGeoVoxelFinder *voxels = vol->GetVoxels(); - if (!voxels) return; + if (!voxels) + return; if (voxels->NeedRebuild()) { voxels->Voxelize(); vol->FindOverlaps(); } - TGeoBBox *box = (TGeoBBox*)vol->GetShape(); + TGeoBBox *box = (TGeoBBox *)vol->GetShape(); TGeoShape *shape; TGeoNode *node; Double_t dx = box->GetDX(); @@ -1160,7 +1219,7 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, Int_t ipoint = 0; Int_t itry = 0; Int_t iovlp = 0; - Int_t id=0, id0=0, id1=0; + Int_t id = 0, id0 = 0, id1 = 0; Bool_t in, incrt; Double_t safe; TString name1 = ""; @@ -1169,17 +1228,17 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, TGeoNode *node1, *node2; Int_t novlps = 0; TGeoHMatrix mat1, mat2; -// Int_t tid = TGeoManager::ThreadId(); + // Int_t tid = TGeoManager::ThreadId(); TGeoNavigator *nav = fGeoManager->GetCurrentNavigator(); TGeoStateInfo &td = *nav->GetCache()->GetInfo(); while (ipoint < npoints) { - // Shoot randomly in the bounding box. - pt[0] = orig[0] - dx + 2.*dx*gRandom->Rndm(); - pt[1] = orig[1] - dy + 2.*dy*gRandom->Rndm(); - pt[2] = orig[2] - dz + 2.*dz*gRandom->Rndm(); + // Shoot randomly in the bounding box. + pt[0] = orig[0] - dx + 2. * dx * gRandom->Rndm(); + pt[1] = orig[1] - dy + 2. * dy * gRandom->Rndm(); + pt[2] = orig[2] - dz + 2. * dz * gRandom->Rndm(); if (!vol->Contains(pt)) { itry++; - if (itry>10000 && !ipoint) { + if (itry > 10000 && !ipoint) { Error("CheckOverlapsBySampling", "No point inside volume!!! - aborting"); break; } @@ -1189,16 +1248,19 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, in = kFALSE; ipoint++; check_list = voxels->GetCheckList(pt, ncheck, td); - if (!check_list || ncheck<2) continue; - for (id=0; idGetNode(id0); + node = vol->GetNode(id0); // Ignore MANY's - if (node->IsOverlapping()) continue; - node->GetMatrix()->MasterToLocal(pt,local); + if (node->IsOverlapping()) + continue; + node->GetMatrix()->MasterToLocal(pt, local); shape = node->GetVolume()->GetShape(); incrt = shape->Contains(local); - if (!incrt) continue; + if (!incrt) + continue; if (!in) { in = kTRUE; id1 = id0; @@ -1206,15 +1268,16 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, } // The point is inside 2 or more daughters, check safety safe = shape->Safety(local, kTRUE); -// if (safe < ovlp) continue; + // if (safe < ovlp) continue; // We really have found an overlap -> store the point in a container iovlp++; if (!novlps) { - if (flags) delete [] flags; // should never happen - flags = new TGeoOverlap*[nd*nd]; - memset(flags, 0, nd*nd*sizeof(TGeoOverlap*)); + if (flags) + delete[] flags; // should never happen + flags = new TGeoOverlap *[nd * nd]; + memset(flags, 0, nd * nd * sizeof(TGeoOverlap *)); } - TGeoOverlap *nodeovlp = flags[nd*id1+id0]; + TGeoOverlap *nodeovlp = flags[nd * id1 + id0]; if (!nodeovlp) { novlps++; node1 = vol->GetNode(id1); @@ -1237,25 +1300,29 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, mat2.Multiply(node2->GetMatrix()); cindex = node2->GetVolume()->GetCurrentNodeIndex(); } - nodeovlp = new TGeoOverlap(TString::Format("Volume %s: node %s overlapping %s", - vol->GetName(), name1.Data(), name2.Data()), node1->GetVolume(),node2->GetVolume(), - &mat1,&mat2, kTRUE, safe); - flags[nd*id1+id0] = nodeovlp; + nodeovlp = new TGeoOverlap( + TString::Format("Volume %s: node %s overlapping %s", vol->GetName(), name1.Data(), name2.Data()), + node1->GetVolume(), node2->GetVolume(), &mat1, &mat2, kTRUE, safe); + flags[nd * id1 + id0] = nodeovlp; fGeoManager->AddOverlap(nodeovlp); } // Max 100 points per marker - if (nodeovlp->GetPolyMarker()->GetN()<100) nodeovlp->SetNextPoint(pt[0],pt[1],pt[2]); - if (nodeovlp->GetOverlap()SetOverlap(safe); + if (nodeovlp->GetPolyMarker()->GetN() < 100) + nodeovlp->SetNextPoint(pt[0], pt[1], pt[2]); + if (nodeovlp->GetOverlap() < safe) + nodeovlp->SetOverlap(safe); } } nav->GetCache()->ReleaseInfo(); - if (flags) delete [] flags; - if (!novlps) return; + if (flags) + delete[] flags; + if (!novlps) + return; Double_t capacity = vol->GetShape()->Capacity(); - capacity *= Double_t(iovlp)/Double_t(npoints); - Double_t err = 1./TMath::Sqrt(Double_t(iovlp)); - Info("CheckOverlapsBySampling", "#Found %d overlaps adding-up to %g +/- %g [cm3] for daughters of %s", - novlps, capacity, err*capacity, vol->GetName()); + capacity *= Double_t(iovlp) / Double_t(npoints); + Double_t err = 1. / TMath::Sqrt(Double_t(iovlp)); + Info("CheckOverlapsBySampling", "#Found %d overlaps adding-up to %g +/- %g [cm3] for daughters of %s", novlps, + capacity, err * capacity, vol->GetName()); } //////////////////////////////////////////////////////////////////////////////// @@ -1263,9 +1330,11 @@ void TGeoChecker::CheckOverlapsBySampling(TGeoVolume *vol, Double_t /* ovlp */, Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) { - if (vol->GetFinder()) return 0; + if (vol->GetFinder()) + return 0; UInt_t nd = vol->GetNdaughters(); - if (!nd) return 0; + if (!nd) + return 0; Bool_t is_assembly = vol->IsAssembly(); TGeoIterator next1(vol); TGeoIterator next2(vol); @@ -1273,7 +1342,7 @@ Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) TGeoNode *node; UInt_t id; if (!is_assembly) { - while ((node=next1())) { + while ((node = next1())) { if (node->IsOverlapping()) { next1.Skip(); continue; @@ -1285,36 +1354,41 @@ Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) } } // now check if the daughters overlap with each other - if (nd<2) return nchecks; + if (nd < 2) + return nchecks; TGeoVoxelFinder *vox = vol->GetVoxels(); - if (!vox) return nchecks; - + if (!vox) + return nchecks; TGeoNode *node1, *node01, *node02; Int_t novlp; Int_t *ovlps; Int_t ko; UInt_t io; - for (id=0; idGetNode(id); - if (node01->IsOverlapping()) continue; + if (node01->IsOverlapping()) + continue; vox->FindOverlaps(id); ovlps = node01->GetOverlaps(novlp); - if (!ovlps) continue; - for (ko=0; koGetNode(io); - if (node02->IsOverlapping()) continue; + if (node02->IsOverlapping()) + continue; // We have to check node against node1, but they may be assemblies if (node01->GetVolume()->IsAssembly()) { next1.Reset(node01->GetVolume()); - while ((node=next1())) { + while ((node = next1())) { if (!node->GetVolume()->IsAssembly()) { if (node02->GetVolume()->IsAssembly()) { next2.Reset(node02->GetVolume()); - while ((node1=next2())) { + while ((node1 = next2())) { if (!node1->GetVolume()->IsAssembly()) { nchecks++; next2.Skip(); @@ -1330,7 +1404,7 @@ Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) // node not assembly if (node02->GetVolume()->IsAssembly()) { next2.Reset(node02->GetVolume()); - while ((node1=next2())) { + while ((node1 = next2())) { if (!node1->GetVolume()->IsAssembly()) { nchecks++; next2.Skip(); @@ -1342,7 +1416,7 @@ Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) } } } - node01->SetOverlaps(0,0); + node01->SetOverlaps(0, 0); } return nchecks; } @@ -1352,53 +1426,60 @@ Int_t TGeoChecker::NChecksPerVolume(TGeoVolume *vol) void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t *option) { - if (vol->GetFinder()) return; + if (vol->GetFinder()) + return; UInt_t nd = vol->GetNdaughters(); - if (!nd) return; + if (!nd) + return; TGeoShape::SetTransform(gGeoIdentity); - fNchecks = NChecksPerVolume((TGeoVolume*)vol); + fNchecks = NChecksPerVolume((TGeoVolume *)vol); Bool_t sampling = kFALSE; TString opt(option); opt.ToLower(); - if (opt.Contains("s")) sampling = kTRUE; - if (opt.Contains("f")) fFullCheck = kTRUE; - else fFullCheck = kFALSE; + if (opt.Contains("s")) + sampling = kTRUE; + if (opt.Contains("f")) + fFullCheck = kTRUE; + else + fFullCheck = kFALSE; if (sampling) { opt = opt.Strip(TString::kLeading, 's'); Int_t npoints = atoi(opt.Data()); - if (!npoints) npoints = 1000000; - CheckOverlapsBySampling((TGeoVolume*)vol, ovlp, npoints); + if (!npoints) + npoints = 1000000; + CheckOverlapsBySampling((TGeoVolume *)vol, ovlp, npoints); return; } Bool_t is_assembly = vol->IsAssembly(); - TGeoIterator next1((TGeoVolume*)vol); - TGeoIterator next2((TGeoVolume*)vol); + TGeoIterator next1((TGeoVolume *)vol); + TGeoIterator next2((TGeoVolume *)vol); TString path; // first, test if daughters extrude their container - TGeoNode * node, *nodecheck; - TGeoChecker *checker = (TGeoChecker*)this; + TGeoNode *node, *nodecheck; + TGeoChecker *checker = (TGeoChecker *)this; -// TGeoOverlap *nodeovlp = 0; + // TGeoOverlap *nodeovlp = 0; UInt_t id; Int_t level; -// Check extrusion only for daughters of a non-assembly volume + // Check extrusion only for daughters of a non-assembly volume if (!is_assembly) { - while ((node=next1())) { + while ((node = next1())) { if (node->IsOverlapping()) { next1.Skip(); continue; } if (!node->GetVolume()->IsAssembly()) { if (fSelectedNode) { - // We have to check only overlaps of the selected node (or real daughters if an assembly) + // We have to check only overlaps of the selected node (or real daughters if an assembly) if ((fSelectedNode != node) && (!fSelectedNode->GetVolume()->IsAssembly())) { next1.Skip(); continue; } if (node != fSelectedNode) { level = next1.GetLevel(); - while ((nodecheck=next1.GetNode(level--))) { - if (nodecheck == fSelectedNode) break; + while ((nodecheck = next1.GetNode(level--))) { + if (nodecheck == fSelectedNode) + break; } if (!nodecheck) { next1.Skip(); @@ -1407,18 +1488,20 @@ void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * } } next1.GetPath(path); - checker->MakeCheckOverlap(TString::Format("%s extruded by: %s", vol->GetName(),path.Data()), - (TGeoVolume*)vol,node->GetVolume(),gGeoIdentity,(TGeoMatrix*)next1.GetCurrentMatrix(),kFALSE,ovlp); + checker->MakeCheckOverlap(TString::Format("%s extruded by: %s", vol->GetName(), path.Data()), + (TGeoVolume *)vol, node->GetVolume(), gGeoIdentity, + (TGeoMatrix *)next1.GetCurrentMatrix(), kFALSE, ovlp); next1.Skip(); } } } // now check if the daughters overlap with each other - if (nd<2) return; + if (nd < 2) + return; TGeoVoxelFinder *vox = vol->GetVoxels(); if (!vox) { - Warning("CheckOverlaps", "Volume %s with %i daughters but not voxelized", vol->GetName(),nd); + Warning("CheckOverlaps", "Volume %s with %i daughters but not voxelized", vol->GetName(), nd); return; } if (vox->NeedRebuild()) { @@ -1432,56 +1515,66 @@ void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * Int_t *ovlps; Int_t ko; UInt_t io; - for (id=0; idGetNode(id); - if (node01->IsOverlapping()) continue; + if (node01->IsOverlapping()) + continue; vox->FindOverlaps(id); ovlps = node01->GetOverlaps(novlp); - if (!ovlps) continue; + if (!ovlps) + continue; next1.SetTopName(node01->GetName()); path = node01->GetName(); - for (ko=0; koGetNode(io); - if (node02->IsOverlapping()) continue; + if (node02->IsOverlapping()) + continue; // Try to fasten-up things... -// if (!TGeoBBox::AreOverlapping((TGeoBBox*)node01->GetVolume()->GetShape(), node01->GetMatrix(), -// (TGeoBBox*)node02->GetVolume()->GetShape(), node02->GetMatrix())) continue; + // if (!TGeoBBox::AreOverlapping((TGeoBBox*)node01->GetVolume()->GetShape(), node01->GetMatrix(), + // (TGeoBBox*)node02->GetVolume()->GetShape(), node02->GetMatrix())) + // continue; next2.SetTopName(node02->GetName()); path1 = node02->GetName(); // We have to check node against node1, but they may be assemblies if (node01->GetVolume()->IsAssembly()) { next1.Reset(node01->GetVolume()); - while ((node=next1())) { + while ((node = next1())) { if (!node->GetVolume()->IsAssembly()) { next1.GetPath(path); hmat1 = node01->GetMatrix(); hmat1 *= *next1.GetCurrentMatrix(); if (node02->GetVolume()->IsAssembly()) { next2.Reset(node02->GetVolume()); - while ((node1=next2())) { + while ((node1 = next2())) { if (!node1->GetVolume()->IsAssembly()) { if (fSelectedNode) { - // We have to check only overlaps of the selected node (or real daughters if an assembly) - if ((fSelectedNode != node) && (fSelectedNode != node1) && (!fSelectedNode->GetVolume()->IsAssembly())) { + // We have to check only overlaps of the selected node (or real daughters if an assembly) + if ((fSelectedNode != node) && (fSelectedNode != node1) && + (!fSelectedNode->GetVolume()->IsAssembly())) { next2.Skip(); continue; } if ((fSelectedNode != node1) && (fSelectedNode != node)) { level = next2.GetLevel(); - while ((nodecheck=next2.GetNode(level--))) { - if (nodecheck == fSelectedNode) break; + while ((nodecheck = next2.GetNode(level--))) { + if (nodecheck == fSelectedNode) + break; } - if (node02 == fSelectedNode) nodecheck = node02; + if (node02 == fSelectedNode) + nodecheck = node02; if (!nodecheck) { level = next1.GetLevel(); - while ((nodecheck=next1.GetNode(level--))) { - if (nodecheck == fSelectedNode) break; + while ((nodecheck = next1.GetNode(level--))) { + if (nodecheck == fSelectedNode) + break; } } - if (node01 == fSelectedNode) nodecheck = node01; + if (node01 == fSelectedNode) + nodecheck = node01; if (!nodecheck) { next2.Skip(); continue; @@ -1491,32 +1584,39 @@ void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * next2.GetPath(path1); hmat2 = node02->GetMatrix(); hmat2 *= *next2.GetCurrentMatrix(); - checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(),path.Data(),vol->GetName(),path1.Data()), - node->GetVolume(),node1->GetVolume(),&hmat1,&hmat2,kTRUE,ovlp); + checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(), + path.Data(), vol->GetName(), path1.Data()), + node->GetVolume(), node1->GetVolume(), &hmat1, &hmat2, kTRUE, + ovlp); next2.Skip(); } } } else { if (fSelectedNode) { - // We have to check only overlaps of the selected node (or real daughters if an assembly) - if ((fSelectedNode != node) && (fSelectedNode != node02) && (!fSelectedNode->GetVolume()->IsAssembly())) { + // We have to check only overlaps of the selected node (or real daughters if an assembly) + if ((fSelectedNode != node) && (fSelectedNode != node02) && + (!fSelectedNode->GetVolume()->IsAssembly())) { next1.Skip(); continue; } if ((fSelectedNode != node) && (fSelectedNode != node02)) { level = next1.GetLevel(); - while ((nodecheck=next1.GetNode(level--))) { - if (nodecheck == fSelectedNode) break; + while ((nodecheck = next1.GetNode(level--))) { + if (nodecheck == fSelectedNode) + break; } - if (node01 == fSelectedNode) nodecheck = node01; + if (node01 == fSelectedNode) + nodecheck = node01; if (!nodecheck) { next1.Skip(); continue; } } } - checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(),path.Data(),vol->GetName(),path1.Data()), - node->GetVolume(),node02->GetVolume(),&hmat1,node02->GetMatrix(),kTRUE,ovlp); + checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(), path.Data(), + vol->GetName(), path1.Data()), + node->GetVolume(), node02->GetVolume(), &hmat1, node02->GetMatrix(), + kTRUE, ovlp); } next1.Skip(); } @@ -1525,20 +1625,23 @@ void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * // node not assembly if (node02->GetVolume()->IsAssembly()) { next2.Reset(node02->GetVolume()); - while ((node1=next2())) { + while ((node1 = next2())) { if (!node1->GetVolume()->IsAssembly()) { if (fSelectedNode) { - // We have to check only overlaps of the selected node (or real daughters if an assembly) - if ((fSelectedNode != node1) && (fSelectedNode != node01) && (!fSelectedNode->GetVolume()->IsAssembly())) { + // We have to check only overlaps of the selected node (or real daughters if an assembly) + if ((fSelectedNode != node1) && (fSelectedNode != node01) && + (!fSelectedNode->GetVolume()->IsAssembly())) { next2.Skip(); continue; } if ((fSelectedNode != node1) && (fSelectedNode != node01)) { level = next2.GetLevel(); - while ((nodecheck=next2.GetNode(level--))) { - if (nodecheck == fSelectedNode) break; + while ((nodecheck = next2.GetNode(level--))) { + if (nodecheck == fSelectedNode) + break; } - if (node02 == fSelectedNode) nodecheck = node02; + if (node02 == fSelectedNode) + nodecheck = node02; if (!nodecheck) { next2.Skip(); continue; @@ -1548,20 +1651,24 @@ void TGeoChecker::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * next2.GetPath(path1); hmat2 = node02->GetMatrix(); hmat2 *= *next2.GetCurrentMatrix(); - checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(),path.Data(),vol->GetName(),path1.Data()), - node01->GetVolume(),node1->GetVolume(),node01->GetMatrix(),&hmat2,kTRUE,ovlp); + checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(), path.Data(), + vol->GetName(), path1.Data()), + node01->GetVolume(), node1->GetVolume(), node01->GetMatrix(), &hmat2, + kTRUE, ovlp); next2.Skip(); } } } else { // node1 also not assembly - if (fSelectedNode && (fSelectedNode != node01) && (fSelectedNode != node02)) continue; - checker->MakeCheckOverlap(TString::Format("%s/%s overlapping %s/%s", vol->GetName(),path.Data(),vol->GetName(),path1.Data()), - node01->GetVolume(),node02->GetVolume(),node01->GetMatrix(),node02->GetMatrix(),kTRUE,ovlp); + if (fSelectedNode && (fSelectedNode != node01) && (fSelectedNode != node02)) + continue; + checker->MakeCheckOverlap( + TString::Format("%s/%s overlapping %s/%s", vol->GetName(), path.Data(), vol->GetName(), path1.Data()), + node01->GetVolume(), node02->GetVolume(), node01->GetMatrix(), node02->GetMatrix(), kTRUE, ovlp); } } } - node01->SetOverlaps(0,0); + node01->SetOverlaps(0, 0); } } @@ -1573,7 +1680,8 @@ void TGeoChecker::PrintOverlaps() const TIter next(fGeoManager->GetListOfOverlaps()); TGeoOverlap *ov; printf("=== Overlaps for %s ===\n", fGeoManager->GetName()); - while ((ov=(TGeoOverlap*)next())) ov->PrintInfo(); + while ((ov = (TGeoOverlap *)next())) + ov->PrintInfo(); } //////////////////////////////////////////////////////////////////////////////// @@ -1591,24 +1699,26 @@ void TGeoChecker::CheckPoint(Double_t x, Double_t y, Double_t z, Option_t *) TGeoVolume *vol = fGeoManager->GetTopVolume(); if (fVsafe) { TGeoNode *old = fVsafe->GetNode("SAFETY_1"); - if (old) fVsafe->GetNodes()->RemoveAt(vol->GetNdaughters()-1); + if (old) + fVsafe->GetNodes()->RemoveAt(vol->GetNdaughters() - 1); } -// if (vol != fGeoManager->GetMasterVolume()) fGeoManager->RestoreMasterVolume(); + // if (vol != fGeoManager->GetMasterVolume()) fGeoManager->RestoreMasterVolume(); TGeoNode *node = fGeoManager->FindNode(point[0], point[1], point[2]); fGeoManager->MasterToLocal(point, local); // get current node printf("=== Check current point : (%g, %g, %g) ===\n", point[0], point[1], point[2]); printf(" - path : %s\n", fGeoManager->GetPath()); // get corresponding volume - if (node) vol = node->GetVolume(); + if (node) + vol = node->GetVolume(); // compute safety distance (distance to boundary ignored) Double_t close = fGeoManager->Safety(); printf("Safety radius : %f\n", close); - if (close>1E-4) { - TGeoVolume *sph = fGeoManager->MakeSphere("SAFETY", vol->GetMedium(), 0, close, 0,180,0,360); + if (close > 1E-4) { + TGeoVolume *sph = fGeoManager->MakeSphere("SAFETY", vol->GetMedium(), 0, close, 0, 180, 0, 360); sph->SetLineColor(2); sph->SetLineStyle(3); - vol->AddNode(sph,1,new TGeoTranslation(local[0], local[1], local[2])); + vol->AddNode(sph, 1, new TGeoTranslation(local[0], local[1], local[2])); fVsafe = vol; } TPolyMarker3D *pm = new TPolyMarker3D(); @@ -1616,10 +1726,13 @@ void TGeoChecker::CheckPoint(Double_t x, Double_t y, Double_t z, Option_t *) pm->SetMarkerStyle(8); pm->SetMarkerSize(0.5); pm->SetNextPoint(local[0], local[1], local[2]); - if (vol->GetNdaughters()<2) fGeoManager->SetTopVisible(); - else fGeoManager->SetTopVisible(kFALSE); + if (vol->GetNdaughters() < 2) + fGeoManager->SetTopVisible(); + else + fGeoManager->SetTopVisible(kFALSE); fGeoManager->SetVisLevel(1); - if (!vol->IsVisible()) vol->SetVisibility(kTRUE); + if (!vol->IsVisible()) + vol->SetVisibility(kTRUE); vol->Draw(); pm->Draw("SAME"); gPad->Modified(); @@ -1639,17 +1752,10 @@ void TGeoChecker::CheckPoint(Double_t x, Double_t y, Double_t z, Option_t *) void TGeoChecker::CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Option_t *option) { switch (testNo) { - case 1: - ShapeDistances(shape, nsamples, option); - break; - case 2: - ShapeSafety(shape, nsamples, option); - break; - case 3: - ShapeNormal(shape, nsamples, option); - break; - default: - Error("CheckShape", "Test number %d not existent", testNo); + case 1: ShapeDistances(shape, nsamples, option); break; + case 2: ShapeSafety(shape, nsamples, option); break; + case 3: ShapeNormal(shape, nsamples, option); break; + default: Error("CheckShape", "Test number %d not existent", testNo); } } @@ -1664,145 +1770,159 @@ void TGeoChecker::CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Opt void TGeoChecker::ShapeDistances(TGeoShape *shape, Int_t nsamples, Option_t *) { - Double_t dx = ((TGeoBBox*)shape)->GetDX(); - Double_t dy = ((TGeoBBox*)shape)->GetDY(); - Double_t dz = ((TGeoBBox*)shape)->GetDZ(); - Double_t dmax = 2.*TMath::Sqrt(dx*dx+dy*dy+dz*dz); + Double_t dx = ((TGeoBBox *)shape)->GetDX(); + Double_t dy = ((TGeoBBox *)shape)->GetDY(); + Double_t dz = ((TGeoBBox *)shape)->GetDZ(); + Double_t dmax = 2. * TMath::Sqrt(dx * dx + dy * dy + dz * dz); Double_t d1, d2, dmove, dnext; Int_t itot = 0; // Number of tracks shot for every point inside the shape const Int_t kNtracks = 1000; - Int_t n10 = nsamples/10; - Int_t i,j; + Int_t n10 = nsamples / 10; + Int_t i, j; Double_t point[3], pnew[3]; Double_t dir[3], dnew[3]; Double_t theta, phi, delta; TPolyMarker3D *pmfrominside = 0; TPolyMarker3D *pmfromoutside = 0; - TH1D *hist = new TH1D("hTest1", "Residual distance from inside/outside",200,-20, 0); + TH1D *hist = new TH1D("hTest1", "Residual distance from inside/outside", 200, -20, 0); hist->GetXaxis()->SetTitle("delta[cm] - first bin=overflow"); hist->GetYaxis()->SetTitle("count"); hist->SetMarkerStyle(kFullCircle); - if (!fTimer) fTimer = new TStopwatch(); + if (!fTimer) + fTimer = new TStopwatch(); fTimer->Reset(); fTimer->Start(); - while (itotUniform(-dx,dx); - point[1] = gRandom->Uniform(-dy,dy); - point[2] = gRandom->Uniform(-dz,dz); + point[0] = gRandom->Uniform(-dx, dx); + point[1] = gRandom->Uniform(-dy, dy); + point[2] = gRandom->Uniform(-dz, dz); inside = shape->Contains(point); } itot++; if (n10) { - if ((itot%n10) == 0) printf("%i percent\n", Int_t(100*itot/nsamples)); + if ((itot % n10) == 0) + printf("%i percent\n", Int_t(100 * itot / nsamples)); } - for (i=0; iRndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); + for (i = 0; i < kNtracks; i++) { + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); dmove = dmax; // We have track direction, compute distance from inside - d1 = shape->DistFromInside(point,dir,3); - if (d1>dmove || d1DistFromInside(point, dir, 3); + if (d1 > dmove || d1 < TGeoShape::Tolerance()) { // Bad distance or bbox size, to debug - new TCanvas("shape01", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + new TCanvas("shape01", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); shape->Draw(); - printf("DistFromInside: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) %f/%f(max)\n", - point[0],point[1],point[2],dir[0],dir[1],dir[2], d1,dmove); + printf("DistFromInside: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) %f/%f(max)\n", point[0], + point[1], point[2], dir[0], dir[1], dir[2], d1, dmove); pmfrominside = new TPolyMarker3D(2); pmfrominside->SetMarkerColor(kRed); pmfrominside->SetMarkerStyle(24); pmfrominside->SetMarkerSize(0.4); - pmfrominside->SetNextPoint(point[0],point[1],point[2]); - for (j=0; j<3; j++) pnew[j] = point[j] + d1*dir[j]; - pmfrominside->SetNextPoint(pnew[0],pnew[1],pnew[2]); + pmfrominside->SetNextPoint(point[0], point[1], point[2]); + for (j = 0; j < 3; j++) + pnew[j] = point[j] + d1 * dir[j]; + pmfrominside->SetNextPoint(pnew[0], pnew[1], pnew[2]); pmfrominside->Draw(); return; } // Propagate BEFORE the boundary and make sure that DistFromOutside // does not return 0 (!!!) // Check if there is a second crossing - for (j=0; j<3; j++) pnew[j] = point[j] + (d1-TGeoShape::Tolerance())*dir[j]; - dnext = shape->DistFromOutside(pnew,dir,3); - if (d1+dnextDistFromOutside(pnew, dir, 3); + if (d1 + dnext < dmax) + dmove = d1 + 0.5 * dnext; // Move point and swap direction - for (j=0; j<3; j++) { - pnew[j] = point[j] + dmove*dir[j]; + for (j = 0; j < 3; j++) { + pnew[j] = point[j] + dmove * dir[j]; dnew[j] = -dir[j]; } // Compute now distance from outside - d2 = shape->DistFromOutside(pnew,dnew,3); - delta = dmove-d1-d2; - if (TMath::Abs(delta)>1E-6 || dnext<2.*TGeoShape::Tolerance()) { + d2 = shape->DistFromOutside(pnew, dnew, 3); + delta = dmove - d1 - d2; + if (TMath::Abs(delta) > 1E-6 || dnext < 2. * TGeoShape::Tolerance()) { // Error->debug this - new TCanvas("shape01", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + new TCanvas("shape01", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); shape->Draw(); - printf("Error: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) d1=%f d2=%f dmove=%f\n", - point[0],point[1],point[2],dir[0],dir[1],dir[2], d1,d2,dmove); - if (dnext<2.*TGeoShape::Tolerance()) { + printf("Error: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) d1=%f d2=%f dmove=%f\n", point[0], + point[1], point[2], dir[0], dir[1], dir[2], d1, d2, dmove); + if (dnext < 2. * TGeoShape::Tolerance()) { printf(" (*)DistFromOutside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) dnext = %f\n", - point[0]+(d1-TGeoShape::Tolerance())*dir[0], - point[1]+(d1-TGeoShape::Tolerance())*dir[1], - point[2]+(d1-TGeoShape::Tolerance())*dir[2], dir[0],dir[1],dir[2],dnext); + point[0] + (d1 - TGeoShape::Tolerance()) * dir[0], + point[1] + (d1 - TGeoShape::Tolerance()) * dir[1], + point[2] + (d1 - TGeoShape::Tolerance()) * dir[2], dir[0], dir[1], dir[2], dnext); } else { printf(" DistFromOutside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) dnext = %f\n", - point[0]+d1*dir[0],point[1]+d1*dir[1], point[2]+d1*dir[2], dir[0],dir[1],dir[2],dnext); + point[0] + d1 * dir[0], point[1] + d1 * dir[1], point[2] + d1 * dir[2], dir[0], dir[1], dir[2], + dnext); } - printf(" DistFromOutside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) = %f\n", - pnew[0],pnew[1],pnew[2],dnew[0],dnew[1],dnew[2], d2); + printf(" DistFromOutside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) = %f\n", pnew[0], pnew[1], + pnew[2], dnew[0], dnew[1], dnew[2], d2); pmfrominside = new TPolyMarker3D(2); pmfrominside->SetMarkerStyle(24); pmfrominside->SetMarkerSize(0.4); pmfrominside->SetMarkerColor(kRed); - pmfrominside->SetNextPoint(point[0],point[1],point[2]); - for (j=0; j<3; j++) point[j] += d1*dir[j]; - pmfrominside->SetNextPoint(point[0],point[1],point[2]); + pmfrominside->SetNextPoint(point[0], point[1], point[2]); + for (j = 0; j < 3; j++) + point[j] += d1 * dir[j]; + pmfrominside->SetNextPoint(point[0], point[1], point[2]); pmfrominside->Draw(); pmfromoutside = new TPolyMarker3D(2); pmfromoutside->SetMarkerStyle(20); pmfromoutside->SetMarkerStyle(7); pmfromoutside->SetMarkerSize(0.3); pmfromoutside->SetMarkerColor(kBlue); - pmfromoutside->SetNextPoint(pnew[0],pnew[1],pnew[2]); - for (j=0; j<3; j++) pnew[j] += d2*dnew[j]; - if (d2<1E10) pmfromoutside->SetNextPoint(pnew[0],pnew[1],pnew[2]); + pmfromoutside->SetNextPoint(pnew[0], pnew[1], pnew[2]); + for (j = 0; j < 3; j++) + pnew[j] += d2 * dnew[j]; + if (d2 < 1E10) + pmfromoutside->SetNextPoint(pnew[0], pnew[1], pnew[2]); pmfromoutside->Draw(); return; } // Compute distance from inside which should be bigger than d1 - for (j=0; j<3; j++) pnew[j] += (d2-TGeoShape::Tolerance())*dnew[j]; - dnext = shape->DistFromInside(pnew,dnew,3); - if (dnextdmax) { - new TCanvas("shape01", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + for (j = 0; j < 3; j++) + pnew[j] += (d2 - TGeoShape::Tolerance()) * dnew[j]; + dnext = shape->DistFromInside(pnew, dnew, 3); + if (dnext < d1 - TGeoShape::Tolerance() || dnext > dmax) { + new TCanvas("shape01", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); shape->Draw(); - printf("Error DistFromInside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) d1=%f d1p=%f\n", - pnew[0],pnew[1],pnew[2],dnew[0],dnew[1],dnew[2],d1,dnext); + printf("Error DistFromInside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) d1=%f d1p=%f\n", pnew[0], + pnew[1], pnew[2], dnew[0], dnew[1], dnew[2], d1, dnext); pmfrominside = new TPolyMarker3D(2); pmfrominside->SetMarkerStyle(24); pmfrominside->SetMarkerSize(0.4); pmfrominside->SetMarkerColor(kRed); - pmfrominside->SetNextPoint(point[0],point[1],point[2]); - for (j=0; j<3; j++) point[j] += d1*dir[j]; - pmfrominside->SetNextPoint(point[0],point[1],point[2]); + pmfrominside->SetNextPoint(point[0], point[1], point[2]); + for (j = 0; j < 3; j++) + point[j] += d1 * dir[j]; + pmfrominside->SetNextPoint(point[0], point[1], point[2]); pmfrominside->Draw(); pmfromoutside = new TPolyMarker3D(2); pmfromoutside->SetMarkerStyle(20); pmfromoutside->SetMarkerStyle(7); pmfromoutside->SetMarkerSize(0.3); pmfromoutside->SetMarkerColor(kBlue); - pmfromoutside->SetNextPoint(pnew[0],pnew[1],pnew[2]); - for (j=0; j<3; j++) pnew[j] += dnext*dnew[j]; - if (d2<1E10) pmfromoutside->SetNextPoint(pnew[0],pnew[1],pnew[2]); + pmfromoutside->SetNextPoint(pnew[0], pnew[1], pnew[2]); + for (j = 0; j < 3; j++) + pnew[j] += dnext * dnew[j]; + if (d2 < 1E10) + pmfromoutside->SetNextPoint(pnew[0], pnew[1], pnew[2]); pmfromoutside->Draw(); return; } - if (TMath::Abs(delta) < 1E-20) delta = 1E-30; - hist->Fill(TMath::Max(TMath::Log(TMath::Abs(delta)),-20.)); + if (TMath::Abs(delta) < 1E-20) + delta = 1E-30; + hist->Fill(TMath::Max(TMath::Log(TMath::Abs(delta)), -20.)); } } fTimer->Stop(); @@ -1819,12 +1939,12 @@ void TGeoChecker::ShapeDistances(TGeoShape *shape, Int_t nsamples, Option_t *) void TGeoChecker::ShapeSafety(TGeoShape *shape, Int_t nsamples, Option_t *) { - Double_t dx = ((TGeoBBox*)shape)->GetDX(); - Double_t dy = ((TGeoBBox*)shape)->GetDY(); - Double_t dz = ((TGeoBBox*)shape)->GetDZ(); + Double_t dx = ((TGeoBBox *)shape)->GetDX(); + Double_t dy = ((TGeoBBox *)shape)->GetDY(); + Double_t dz = ((TGeoBBox *)shape)->GetDZ(); // Number of tracks shot for every point inside the shape const Int_t kNtracks = 1000; - Int_t n10 = nsamples/10; + Int_t n10 = nsamples / 10; Int_t i; Double_t dist; Double_t point[3]; @@ -1832,46 +1952,50 @@ void TGeoChecker::ShapeSafety(TGeoShape *shape, Int_t nsamples, Option_t *) Double_t theta, phi; TPolyMarker3D *pm1 = 0; TPolyMarker3D *pm2 = 0; - if (!fTimer) fTimer = new TStopwatch(); + if (!fTimer) + fTimer = new TStopwatch(); fTimer->Reset(); fTimer->Start(); Int_t itot = 0; - while (itotUniform(-2*dx,2*dx); - point[1] = gRandom->Uniform(-2*dy,2*dy); - point[2] = gRandom->Uniform(-2*dz,2*dz); + point[0] = gRandom->Uniform(-2 * dx, 2 * dx); + point[1] = gRandom->Uniform(-2 * dy, 2 * dy); + point[2] = gRandom->Uniform(-2 * dz, 2 * dz); inside = shape->Contains(point); Double_t safe = shape->Safety(point, inside); itot++; if (n10) { - if ((itot%n10) == 0) printf("%i percent\n", Int_t(100*itot/nsamples)); + if ((itot % n10) == 0) + printf("%i percent\n", Int_t(100 * itot / nsamples)); } - for (i=0; iRndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); - if (inside) dist = shape->DistFromInside(point,dir,3); - else dist = shape->DistFromOutside(point,dir,3); - if (distGetName(),shape->ClassName()), 1000, 800); + for (i = 0; i < kNtracks; i++) { + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); + if (inside) + dist = shape->DistFromInside(point, dir, 3); + else + dist = shape->DistFromOutside(point, dir, 3); + if (dist < safe) { + printf("Error safety (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) safe=%f dist=%f\n", point[0], + point[1], point[2], dir[0], dir[1], dir[2], safe, dist); + new TCanvas("shape02", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); shape->Draw(); pm1 = new TPolyMarker3D(2); pm1->SetMarkerStyle(24); pm1->SetMarkerSize(0.4); pm1->SetMarkerColor(kRed); - pm1->SetNextPoint(point[0],point[1],point[2]); - pm1->SetNextPoint(point[0]+safe*dir[0],point[1]+safe*dir[1],point[2]+safe*dir[2]); + pm1->SetNextPoint(point[0], point[1], point[2]); + pm1->SetNextPoint(point[0] + safe * dir[0], point[1] + safe * dir[1], point[2] + safe * dir[2]); pm1->Draw(); pm2 = new TPolyMarker3D(1); pm2->SetMarkerStyle(7); pm2->SetMarkerSize(0.3); pm2->SetMarkerColor(kBlue); - pm2->SetNextPoint(point[0]+dist*dir[0],point[1]+dist*dir[1],point[2]+dist*dir[2]); + pm2->SetNextPoint(point[0] + dist * dir[0], point[1] + dist * dir[1], point[2] + dist * dir[2]); pm2->Draw(); return; } @@ -1889,140 +2013,151 @@ void TGeoChecker::ShapeSafety(TGeoShape *shape, Int_t nsamples, Option_t *) void TGeoChecker::ShapeNormal(TGeoShape *shape, Int_t nsamples, Option_t *) { - Double_t dx = ((TGeoBBox*)shape)->GetDX(); - Double_t dy = ((TGeoBBox*)shape)->GetDY(); - Double_t dz = ((TGeoBBox*)shape)->GetDZ(); - Double_t dmax = 2.*TMath::Sqrt(dx*dx+dy*dy+dz*dz); + Double_t dx = ((TGeoBBox *)shape)->GetDX(); + Double_t dy = ((TGeoBBox *)shape)->GetDY(); + Double_t dz = ((TGeoBBox *)shape)->GetDZ(); + Double_t dmax = 2. * TMath::Sqrt(dx * dx + dy * dy + dz * dz); // Number of tracks shot for every point inside the shape const Int_t kNtracks = 1000; - Int_t n10 = nsamples/10; - Int_t itot = 0, errcnt = 0, errsame=0; + Int_t n10 = nsamples / 10; + Int_t itot = 0, errcnt = 0, errsame = 0; Int_t i; Double_t dist, olddist, safe, dot; Double_t theta, phi, ndotd; - Double_t *spoint = new Double_t[3*nsamples]; - Double_t *sdir = new Double_t[3*nsamples]; - while (itotUniform(-dx,dx); - spoint[3*itot+1] = gRandom->Uniform(-dy,dy); - spoint[3*itot+2] = gRandom->Uniform(-dz,dz); - inside = shape->Contains(&spoint[3*itot]); + spoint[3 * itot] = gRandom->Uniform(-dx, dx); + spoint[3 * itot + 1] = gRandom->Uniform(-dy, dy); + spoint[3 * itot + 2] = gRandom->Uniform(-dz, dz); + inside = shape->Contains(&spoint[3 * itot]); } - phi = 2*TMath::Pi()*gRandom->Rndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - sdir[3*itot] = TMath::Sin(theta)*TMath::Cos(phi); - sdir[3*itot+1] = TMath::Sin(theta)*TMath::Sin(phi); - sdir[3*itot+2] = TMath::Cos(theta); + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + sdir[3 * itot] = TMath::Sin(theta) * TMath::Cos(phi); + sdir[3 * itot + 1] = TMath::Sin(theta) * TMath::Sin(phi); + sdir[3 * itot + 2] = TMath::Cos(theta); itot++; } - Double_t point[3],newpoint[3], oldpoint[3]; + Double_t point[3], newpoint[3], oldpoint[3]; Double_t dir[3], olddir[3]; Double_t norm[3], newnorm[3], oldnorm[3]; TCanvas *errcanvas = 0; TPolyMarker3D *pm1 = 0; TPolyMarker3D *pm2 = 0; pm2 = new TPolyMarker3D(); -// pm2->SetMarkerStyle(24); + // pm2->SetMarkerStyle(24); pm2->SetMarkerSize(0.2); pm2->SetMarkerColor(kBlue); - if (!fTimer) fTimer = new TStopwatch(); + if (!fTimer) + fTimer = new TStopwatch(); fTimer->Reset(); fTimer->Start(); - for (itot = 0; itot0) break; - dist = shape->DistFromInside(point,dir,3); - for (Int_t j=0; j<3; j++) { - newpoint[j] = point[j] + dist*dir[j]; + for (i = 0; i < kNtracks; i++) { + if (errcnt > 0) + break; + dist = shape->DistFromInside(point, dir, 3); + for (Int_t j = 0; j < 3; j++) { + newpoint[j] = point[j] + dist * dir[j]; } - shape->ComputeNormal(newpoint,dir,newnorm); + shape->ComputeNormal(newpoint, dir, newnorm); - dot = olddir[0]*oldnorm[0]+olddir[1]*oldnorm[1]+ olddir[2]*oldnorm[2]; - if (!shape->Contains(point) && shape->Safety(point,kFALSE)>1.E-3) { + dot = olddir[0] * oldnorm[0] + olddir[1] * oldnorm[1] + olddir[2] * oldnorm[2]; + if (!shape->Contains(point) && shape->Safety(point, kFALSE) > 1.E-3) { errcnt++; printf("Error point outside (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) =%g olddist=%g\n", - point[0],point[1],point[2], dir[0], dir[1], dir[2], dist, olddist); - printf(" old point: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f)\n", - oldpoint[0],oldpoint[1],oldpoint[2], olddir[0], olddir[1], olddir[2]); - if (!errcanvas) errcanvas = new TCanvas("shape_err03", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + point[0], point[1], point[2], dir[0], dir[1], dir[2], dist, olddist); + printf(" old point: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f)\n", oldpoint[0], + oldpoint[1], oldpoint[2], olddir[0], olddir[1], olddir[2]); + if (!errcanvas) + errcanvas = + new TCanvas("shape_err03", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); if (!pm1) { pm1 = new TPolyMarker3D(); pm1->SetMarkerStyle(24); pm1->SetMarkerSize(0.4); pm1->SetMarkerColor(kRed); } - pm1->SetNextPoint(point[0],point[1],point[2]); - pm1->SetNextPoint(oldpoint[0],oldpoint[1],oldpoint[2]); + pm1->SetNextPoint(point[0], point[1], point[2]); + pm1->SetNextPoint(oldpoint[0], oldpoint[1], oldpoint[2]); break; } - if ((dist1.E-3) || dist>dmax) { + if ((dist < TGeoShape::Tolerance() && olddist * dot > 1.E-3) || dist > dmax) { errsame++; - if (errsame>1) { + if (errsame > 1) { errcnt++; printf("Error DistFromInside(%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f) =%g olddist=%g\n", - point[0],point[1],point[2], dir[0], dir[1], dir[2], dist, olddist); + point[0], point[1], point[2], dir[0], dir[1], dir[2], dist, olddist); printf(" new norm: (%g, %g, %g)\n", newnorm[0], newnorm[1], newnorm[2]); - printf(" old point: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f)\n", - oldpoint[0],oldpoint[1],oldpoint[2], olddir[0], olddir[1], olddir[2]); + printf(" old point: (%19.15f, %19.15f, %19.15f, %19.15f, %19.15f, %19.15f)\n", oldpoint[0], + oldpoint[1], oldpoint[2], olddir[0], olddir[1], olddir[2]); printf(" old norm: (%g, %g, %g)\n", oldnorm[0], oldnorm[1], oldnorm[2]); - if (!errcanvas) errcanvas = new TCanvas("shape_err03", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + if (!errcanvas) + errcanvas = + new TCanvas("shape_err03", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); if (!pm1) { pm1 = new TPolyMarker3D(); pm1->SetMarkerStyle(24); pm1->SetMarkerSize(0.4); pm1->SetMarkerColor(kRed); } - pm1->SetNextPoint(point[0],point[1],point[2]); - pm1->SetNextPoint(oldpoint[0],oldpoint[1],oldpoint[2]); + pm1->SetNextPoint(point[0], point[1], point[2]); + pm1->SetNextPoint(oldpoint[0], oldpoint[1], oldpoint[2]); break; } - } else errsame = 0; + } else + errsame = 0; olddist = dist; - for (Int_t j=0; j<3; j++) { + for (Int_t j = 0; j < 3; j++) { oldpoint[j] = point[j]; - point[j] += dist*dir[j]; + point[j] += dist * dir[j]; } safe = shape->Safety(point, kTRUE); - if (safe>1.E-3) { + if (safe > 1.E-3) { errcnt++; - printf("Error safety (%19.15f, %19.15f, %19.15f) safe=%g\n", - point[0],point[1],point[2], safe); - if (!errcanvas) errcanvas = new TCanvas("shape_err03", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + printf("Error safety (%19.15f, %19.15f, %19.15f) safe=%g\n", point[0], point[1], point[2], safe); + if (!errcanvas) + errcanvas = + new TCanvas("shape_err03", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); if (!pm1) { pm1 = new TPolyMarker3D(); pm1->SetMarkerStyle(24); pm1->SetMarkerSize(0.4); pm1->SetMarkerColor(kRed); } - pm1->SetNextPoint(point[0],point[1],point[2]); + pm1->SetNextPoint(point[0], point[1], point[2]); break; } // Compute normal - shape->ComputeNormal(point,dir,norm); - memcpy(oldnorm, norm, 3*sizeof(Double_t)); - memcpy(olddir, dir, 3*sizeof(Double_t)); + shape->ComputeNormal(point, dir, norm); + memcpy(oldnorm, norm, 3 * sizeof(Double_t)); + memcpy(olddir, dir, 3 * sizeof(Double_t)); while (1) { - phi = 2*TMath::Pi()*gRandom->Rndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); - ndotd = dir[0]*norm[0]+dir[1]*norm[1]+dir[2]*norm[2]; - if (ndotd<0) break; // backwards, still inside shape + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); + ndotd = dir[0] * norm[0] + dir[1] * norm[1] + dir[2] * norm[2]; + if (ndotd < 0) + break; // backwards, still inside shape } - if ((itot%10) == 0) pm2->SetNextPoint(point[0],point[1],point[2]); + if ((itot % 10) == 0) + pm2->SetNextPoint(point[0], point[1], point[2]); } } fTimer->Stop(); @@ -2032,72 +2167,75 @@ void TGeoChecker::ShapeNormal(TGeoShape *shape, Int_t nsamples, Option_t *) pm1->Draw(); } - new TCanvas("shape03", Form("Shape %s (%s)",shape->GetName(),shape->ClassName()), 1000, 800); + new TCanvas("shape03", Form("Shape %s (%s)", shape->GetName(), shape->ClassName()), 1000, 800); pm2->Draw(); - delete [] spoint; - delete [] sdir; + delete[] spoint; + delete[] sdir; } //////////////////////////////////////////////////////////////////////////////// /// Generate a lego plot fot the top volume, according to option. -TH2F *TGeoChecker::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, - Int_t nphi, Double_t phimin, Double_t phimax, - Double_t /*rmin*/, Double_t /*rmax*/, Option_t *option) +TH2F *TGeoChecker::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, Int_t nphi, Double_t phimin, + Double_t phimax, Double_t /*rmin*/, Double_t /*rmax*/, Option_t *option) { TH2F *hist = new TH2F("lego", option, nphi, phimin, phimax, ntheta, themin, themax); - Double_t degrad = TMath::Pi()/180.; + Double_t degrad = TMath::Pi() / 180.; Double_t theta, phi, step, matprop, x; Double_t start[3]; Double_t dir[3]; TGeoNode *startnode, *endnode; - Int_t i; // loop index for phi - Int_t j; // loop index for theta + Int_t i; // loop index for phi + Int_t j; // loop index for theta Int_t ntot = ntheta * nphi; - Int_t n10 = ntot/10; - Int_t igen = 0, iloop=0; + Int_t n10 = ntot / 10; + Int_t igen = 0, iloop = 0; printf("=== Lego plot sph. => nrays=%i\n", ntot); - for (i=1; i<=nphi; i++) { - for (j=1; j<=ntheta; j++) { + for (i = 1; i <= nphi; i++) { + for (j = 1; j <= ntheta; j++) { igen++; if (n10) { - if ((igen%n10) == 0) printf("%i percent\n", Int_t(100*igen/ntot)); + if ((igen % n10) == 0) + printf("%i percent\n", Int_t(100 * igen / ntot)); } x = 0; theta = hist->GetYaxis()->GetBinCenter(j); - phi = hist->GetXaxis()->GetBinCenter(i)+1E-3; + phi = hist->GetXaxis()->GetBinCenter(i) + 1E-3; start[0] = start[1] = start[2] = 1E-3; - dir[0]=TMath::Sin(theta*degrad)*TMath::Cos(phi*degrad); - dir[1]=TMath::Sin(theta*degrad)*TMath::Sin(phi*degrad); - dir[2]=TMath::Cos(theta*degrad); + dir[0] = TMath::Sin(theta * degrad) * TMath::Cos(phi * degrad); + dir[1] = TMath::Sin(theta * degrad) * TMath::Sin(phi * degrad); + dir[2] = TMath::Cos(theta * degrad); fGeoManager->InitTrack(&start[0], &dir[0]); startnode = fGeoManager->GetCurrentNode(); - if (fGeoManager->IsOutside()) startnode=0; + if (fGeoManager->IsOutside()) + startnode = 0; if (startnode) { matprop = startnode->GetVolume()->GetMaterial()->GetRadLen(); } else { matprop = 0.; } fGeoManager->FindNextBoundary(); -// fGeoManager->IsStepEntering(); + // fGeoManager->IsStepEntering(); // find where we end-up endnode = fGeoManager->Step(); step = fGeoManager->GetStep(); - while (step<1E10) { + while (step < 1E10) { // now see if we can make an other step - iloop=0; + iloop = 0; while (!fGeoManager->IsEntering()) { iloop++; fGeoManager->SetStep(1E-3); step += 1E-3; endnode = fGeoManager->Step(); } - if (iloop>1000) printf("%i steps\n", iloop); - if (matprop>0) { - x += step/matprop; + if (iloop > 1000) + printf("%i steps\n", iloop); + if (matprop > 0) { + x += step / matprop; } - if (endnode==0 && step>1E10) break; + if (endnode == 0 && step > 1E10) + break; // generate an extra step to cross boundary startnode = endnode; if (startnode) { @@ -2121,7 +2259,8 @@ TH2F *TGeoChecker::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, void TGeoChecker::RandomPoints(TGeoVolume *vol, Int_t npoints, Option_t *option) { - if (!vol) return; + if (!vol) + return; vol->VisibleDaughters(kTRUE); vol->Draw(); TString opt = option; @@ -2140,68 +2279,77 @@ void TGeoChecker::RandomPoints(TGeoVolume *vol, Int_t npoints, Option_t *option) printf("Random box : %f, %f, %f\n", dx, dy, dz); TGeoNode *node = 0; printf("Start... %i points\n", npoints); - Int_t i=0; - Int_t igen=0; + Int_t i = 0; + Int_t igen = 0; Int_t ic = 0; - Int_t n10 = npoints/10; - Double_t ratio=0; - while (igenRndm(); - xyz[1] = oy-dy+2*dy*gRandom->Rndm(); - xyz[2] = oz-dz+2*dz*gRandom->Rndm(); + Int_t n10 = npoints / 10; + Double_t ratio = 0; + while (igen < npoints) { + xyz[0] = ox - dx + 2 * dx * gRandom->Rndm(); + xyz[1] = oy - dy + 2 * dy * gRandom->Rndm(); + xyz[2] = oz - dz + 2 * dz * gRandom->Rndm(); fGeoManager->SetCurrentPoint(xyz); igen++; if (n10) { - if ((igen%n10) == 0) printf("%i percent\n", Int_t(100*igen/npoints)); + if ((igen % n10) == 0) + printf("%i percent\n", Int_t(100 * igen / npoints)); } node = fGeoManager->FindNode(); - if (!node) continue; - if (!node->IsOnScreen()) continue; + if (!node) + continue; + if (!node->IsOnScreen()) + continue; // draw only points in overlapping/non-overlapping volumes - if (opt.Contains("many") && !node->IsOverlapping()) continue; - if (opt.Contains("only") && node->IsOverlapping()) continue; + if (opt.Contains("many") && !node->IsOverlapping()) + continue; + if (opt.Contains("only") && node->IsOverlapping()) + continue; ic = node->GetColour(); - if ((ic<0) || (ic>=128)) ic = 1; - marker = (TPolyMarker3D*)pm->At(ic); + if ((ic < 0) || (ic >= 128)) + ic = 1; + marker = (TPolyMarker3D *)pm->At(ic); if (!marker) { marker = new TPolyMarker3D(); marker->SetMarkerColor(ic); -// marker->SetMarkerStyle(8); -// marker->SetMarkerSize(0.4); + // marker->SetMarkerStyle(8); + // marker->SetMarkerSize(0.4); pm->AddAt(marker, ic); } marker->SetNextPoint(xyz[0], xyz[1], xyz[2]); i++; } printf("Number of visible points : %i\n", i); - if (igen) ratio = (Double_t)i/(Double_t)igen; + if (igen) + ratio = (Double_t)i / (Double_t)igen; printf("efficiency : %g\n", ratio); - for (Int_t m=0; m<128; m++) { - marker = (TPolyMarker3D*)pm->At(m); - if (marker) marker->Draw("SAME"); + for (Int_t m = 0; m < 128; m++) { + marker = (TPolyMarker3D *)pm->At(m); + if (marker) + marker->Draw("SAME"); } fGeoManager->GetTopVolume()->VisibleDaughters(kFALSE); printf("---Daughters of %s made invisible.\n", fGeoManager->GetTopVolume()->GetName()); printf("---Make them visible with : gGeoManager->GetTopVolume()->VisibleDaughters();\n"); delete pm; - delete [] xyz; + delete[] xyz; } //////////////////////////////////////////////////////////////////////////////// /// Randomly shoot nrays from point (startx,starty,startz) and plot intersections /// with surfaces for current top node. -void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, Bool_t check_norm) +void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, + Bool_t check_norm) { TObjArray *pm = new TObjArray(128); TString starget = target_vol; TPolyLine3D *line = 0; TPolyLine3D *normline = 0; - TGeoVolume *vol=fGeoManager->GetTopVolume(); -// vol->VisibleDaughters(kTRUE); + TGeoVolume *vol = fGeoManager->GetTopVolume(); + // vol->VisibleDaughters(kTRUE); Bool_t random = kFALSE; - if (nrays<=0) { + if (nrays <= 0) { nrays = 100000; random = kTRUE; } @@ -2211,50 +2359,54 @@ void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub vol->Draw(); printf("Start... %i rays\n", nrays); TGeoNode *startnode, *endnode; - Bool_t vis1,vis2; - Int_t i=0; + Bool_t vis1, vis2; + Int_t i = 0; Int_t ipoint, inull; - Int_t itot=0; - Int_t n10=nrays/10; - Double_t theta,phi, step, normlen; - Double_t ox = ((TGeoBBox*)vol->GetShape())->GetOrigin()[0]; - Double_t oy = ((TGeoBBox*)vol->GetShape())->GetOrigin()[1]; - Double_t oz = ((TGeoBBox*)vol->GetShape())->GetOrigin()[2]; - Double_t dx = ((TGeoBBox*)vol->GetShape())->GetDX(); - Double_t dy = ((TGeoBBox*)vol->GetShape())->GetDY(); - Double_t dz = ((TGeoBBox*)vol->GetShape())->GetDZ(); - normlen = TMath::Max(dx,dy); - normlen = TMath::Max(normlen,dz); + Int_t itot = 0; + Int_t n10 = nrays / 10; + Double_t theta, phi, step, normlen; + Double_t ox = ((TGeoBBox *)vol->GetShape())->GetOrigin()[0]; + Double_t oy = ((TGeoBBox *)vol->GetShape())->GetOrigin()[1]; + Double_t oz = ((TGeoBBox *)vol->GetShape())->GetOrigin()[2]; + Double_t dx = ((TGeoBBox *)vol->GetShape())->GetDX(); + Double_t dy = ((TGeoBBox *)vol->GetShape())->GetDY(); + Double_t dz = ((TGeoBBox *)vol->GetShape())->GetDZ(); + normlen = TMath::Max(dx, dy); + normlen = TMath::Max(normlen, dz); normlen *= 0.05; - while (itotRndm(); - start[1] = oy-dy+2*dy*gRandom->Rndm(); - start[2] = oz-dz+2*dz*gRandom->Rndm(); + start[0] = ox - dx + 2 * dx * gRandom->Rndm(); + start[1] = oy - dy + 2 * dy * gRandom->Rndm(); + start[2] = oz - dz + 2 * dz * gRandom->Rndm(); } else { start[0] = startx; start[1] = starty; start[2] = startz; } - phi = 2*TMath::Pi()*gRandom->Rndm(); - theta= TMath::ACos(1.-2.*gRandom->Rndm()); - dir[0]=TMath::Sin(theta)*TMath::Cos(phi); - dir[1]=TMath::Sin(theta)*TMath::Sin(phi); - dir[2]=TMath::Cos(theta); - startnode = fGeoManager->InitTrack(start[0],start[1],start[2], dir[0],dir[1],dir[2]); + phi = 2 * TMath::Pi() * gRandom->Rndm(); + theta = TMath::ACos(1. - 2. * gRandom->Rndm()); + dir[0] = TMath::Sin(theta) * TMath::Cos(phi); + dir[1] = TMath::Sin(theta) * TMath::Sin(phi); + dir[2] = TMath::Cos(theta); + startnode = fGeoManager->InitTrack(start[0], start[1], start[2], dir[0], dir[1], dir[2]); line = 0; - if (fGeoManager->IsOutside()) startnode=0; + if (fGeoManager->IsOutside()) + startnode = 0; vis1 = kFALSE; if (target_vol) { - if (startnode && starget==startnode->GetVolume()->GetName()) vis1 = kTRUE; + if (startnode && starget == startnode->GetVolume()->GetName()) + vis1 = kTRUE; } else { - if (startnode && startnode->IsOnScreen()) vis1 = kTRUE; + if (startnode && startnode->IsOnScreen()) + vis1 = kTRUE; } if (vis1) { line = new TPolyLine3D(2); @@ -2263,35 +2415,40 @@ void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub i++; pm->Add(line); } - while ((endnode=fGeoManager->FindNextBoundaryAndStep())) { + while ((endnode = fGeoManager->FindNextBoundaryAndStep())) { step = fGeoManager->GetStep(); - if (step5) break; + if (step < TGeoShape::Tolerance()) + inull++; + else + inull = 0; + if (inull > 5) + break; const Double_t *normal = 0; if (check_norm) { normal = fGeoManager->FindNormalFast(); - if (!normal) break; + if (!normal) + break; } vis2 = kFALSE; if (target_vol) { - if (starget==endnode->GetVolume()->GetName()) vis2 = kTRUE; - } else if (endnode->IsOnScreen()) vis2 = kTRUE; - if (ipoint>0) { - // old visible node had an entry point -> finish segment + if (starget == endnode->GetVolume()->GetName()) + vis2 = kTRUE; + } else if (endnode->IsOnScreen()) + vis2 = kTRUE; + if (ipoint > 0) { + // old visible node had an entry point -> finish segment line->SetPoint(ipoint, point[0], point[1], point[2]); if (!vis2 && check_norm) { normline = new TPolyLine3D(2); normline->SetLineColor(kBlue); normline->SetLineWidth(1); normline->SetPoint(0, point[0], point[1], point[2]); - normline->SetPoint(1, point[0]+normal[0]*normlen, - point[1]+normal[1]*normlen, - point[2]+normal[2]*normlen); + normline->SetPoint(1, point[0] + normal[0] * normlen, point[1] + normal[1] * normlen, + point[2] + normal[2] * normlen); pm->Add(normline); } ipoint = 0; - line = 0; + line = 0; } if (vis2) { // create new segment @@ -2304,24 +2461,25 @@ void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub normline->SetLineColor(kBlue); normline->SetLineWidth(2); normline->SetPoint(0, point[0], point[1], point[2]); - normline->SetPoint(1, point[0]+normal[0]*normlen, - point[1]+normal[1]*normlen, - point[2]+normal[2]*normlen); + normline->SetPoint(1, point[0] + normal[0] * normlen, point[1] + normal[1] * normlen, + point[2] + normal[2] * normlen); } pm->Add(line); - if (!random) pm->Add(normline); + if (!random) + pm->Add(normline); } } } // draw all segments - for (Int_t m=0; mGetEntriesFast(); m++) { - line = (TPolyLine3D*)pm->At(m); - if (line) line->Draw("SAME"); + for (Int_t m = 0; m < pm->GetEntriesFast(); m++) { + line = (TPolyLine3D *)pm->At(m); + if (line) + line->Draw("SAME"); } printf("number of segments : %i\n", i); -// fGeoManager->GetTopVolume()->VisibleDaughters(kFALSE); -// printf("---Daughters of %s made invisible.\n", fGeoManager->GetTopVolume()->GetName()); -// printf("---Make them visible with : gGeoManager->GetTopVolume()->VisibleDaughters();\n"); + // fGeoManager->GetTopVolume()->VisibleDaughters(kFALSE); + // printf("---Daughters of %s made invisible.\n", fGeoManager->GetTopVolume()->GetName()); + // printf("---Make them visible with : gGeoManager->GetTopVolume()->VisibleDaughters();\n"); delete pm; } @@ -2331,16 +2489,19 @@ void TGeoChecker::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub /// make sure that path to current node is updated /// get the response of tgeo -TGeoNode *TGeoChecker::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, - const char* g3path) +TGeoNode *TGeoChecker::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path) { TGeoNode *node = fGeoManager->FindNode(); TGeoNode *nodegeo = 0; TGeoNode *nodeg3 = 0; TGeoNode *solg3 = 0; - if (!node) {dist=-1; return 0;} + if (!node) { + dist = -1; + return 0; + } Bool_t hasg3 = kFALSE; - if (strlen(g3path)) hasg3 = kTRUE; + if (strlen(g3path)) + hasg3 = kTRUE; TString geopath = fGeoManager->GetPath(); dist = 1E10; TString common = ""; @@ -2353,20 +2514,23 @@ TGeoNode *TGeoChecker::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsi Double_t dist1 = 0; // initialize size of random box to epsil Double_t eps[3]; - eps[0] = epsil; eps[1]=epsil; eps[2]=epsil; + eps[0] = epsil; + eps[1] = epsil; + eps[2] = epsil; const Double_t *pointg = fGeoManager->GetCurrentPoint(); if (hasg3) { TString spath = geopath; TString name = ""; - Int_t index=0; - while (index>=0) { - index = spath.Index("/", index+1); - if (index>0) { + Int_t index = 0; + while (index >= 0) { + index = spath.Index("/", index + 1); + if (index > 0) { name = spath(0, index); if (strstr(g3path, name.Data())) { common = name; continue; - } else break; + } else + break; } } // if g3 response was given, cd to common path @@ -2381,59 +2545,65 @@ TGeoNode *TGeoChecker::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsi nodeg3 = fGeoManager->GetCurrentNode(); fGeoManager->CdUp(); } - if (!nodegeo) return 0; - if (!nodeg3) return 0; + if (!nodegeo) + return 0; + if (!nodeg3) + return 0; fGeoManager->cd(common.Data()); fGeoManager->MasterToLocal(fGeoManager->GetCurrentPoint(), &point[0]); Double_t xyz[3], local[3]; - for (Int_t i=0; iRndm(); - xyz[1] = point[1] - eps[1] + 2*eps[1]*gRandom->Rndm(); - xyz[2] = point[2] - eps[2] + 2*eps[2]*gRandom->Rndm(); + for (Int_t i = 0; i < npoints; i++) { + xyz[0] = point[0] - eps[0] + 2 * eps[0] * gRandom->Rndm(); + xyz[1] = point[1] - eps[1] + 2 * eps[1] * gRandom->Rndm(); + xyz[2] = point[2] - eps[2] + 2 * eps[2] * gRandom->Rndm(); nodeg3->MasterToLocal(&xyz[0], &local[0]); - if (!nodeg3->GetVolume()->Contains(&local[0])) continue; - dist1 = TMath::Sqrt((xyz[0]-point[0])*(xyz[0]-point[0])+ - (xyz[1]-point[1])*(xyz[1]-point[1])+(xyz[2]-point[2])*(xyz[2]-point[2])); - if (dist1GetVolume()->Contains(&local[0])) + continue; + dist1 = TMath::Sqrt((xyz[0] - point[0]) * (xyz[0] - point[0]) + (xyz[1] - point[1]) * (xyz[1] - point[1]) + + (xyz[2] - point[2]) * (xyz[2] - point[2])); + if (dist1 < dist) { + // save node and closest point dist = dist1; node_close = solg3; // make the random box smaller - eps[0] = TMath::Abs(point[0]-pointg[0]); - eps[1] = TMath::Abs(point[1]-pointg[1]); - eps[2] = TMath::Abs(point[2]-pointg[2]); + eps[0] = TMath::Abs(point[0] - pointg[0]); + eps[1] = TMath::Abs(point[1] - pointg[1]); + eps[2] = TMath::Abs(point[2] - pointg[2]); } } } - if (!node_close) dist = -1; + if (!node_close) + dist = -1; return node_close; } // save current point - memcpy(&point[0], pointg, 3*sizeof(Double_t)); - for (Int_t i=0; iSetCurrentPoint(point[0] - eps[0] + 2*eps[0]*gRandom->Rndm(), - point[1] - eps[1] + 2*eps[1]*gRandom->Rndm(), - point[2] - eps[2] + 2*eps[2]*gRandom->Rndm()); + fGeoManager->SetCurrentPoint(point[0] - eps[0] + 2 * eps[0] * gRandom->Rndm(), + point[1] - eps[1] + 2 * eps[1] * gRandom->Rndm(), + point[2] - eps[2] + 2 * eps[2] * gRandom->Rndm()); // check if new node is different from the old one - if (node1!=node) { - dist1 = TMath::Sqrt((point[0]-pointg[0])*(point[0]-pointg[0])+ - (point[1]-pointg[1])*(point[1]-pointg[1])+(point[2]-pointg[2])*(point[2]-pointg[2])); - if (dist1FindNode(point[0], point[1], point[2]); // really needed ? - if (!node_close) dist=-1; + fGeoManager->FindNode(point[0], point[1], point[2]); // really needed ? + if (!node_close) + dist = -1; return node_close; } @@ -2441,16 +2611,17 @@ TGeoNode *TGeoChecker::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsi /// Shoot one ray from start point with direction (dirx,diry,dirz). Fills input array /// with points just after boundary crossings. -Double_t *TGeoChecker::ShootRay(Double_t *start, Double_t dirx, Double_t diry, Double_t dirz, Double_t *array, Int_t &nelem, Int_t &dim, Double_t *endpoint) const +Double_t *TGeoChecker::ShootRay(Double_t *start, Double_t dirx, Double_t diry, Double_t dirz, Double_t *array, + Int_t &nelem, Int_t &dim, Double_t *endpoint) const { -// Int_t array_dimension = 3*dim; + // Int_t array_dimension = 3*dim; nelem = 0; Int_t istep = 0; if (!dim) { printf("empty input array\n"); return array; } -// fGeoManager->CdTop(); + // fGeoManager->CdTop(); const Double_t *point = fGeoManager->GetCurrentPoint(); TGeoNode *endnode; Bool_t is_entering; @@ -2461,72 +2632,75 @@ Double_t *TGeoChecker::ShootRay(Double_t *start, Double_t dirx, Double_t diry, D dir[2] = dirz; fGeoManager->InitTrack(start, &dir[0]); fGeoManager->GetCurrentNode(); -// printf("Start : (%f,%f,%f)\n", point[0], point[1], point[2]); + // printf("Start : (%f,%f,%f)\n", point[0], point[1], point[2]); fGeoManager->FindNextBoundary(); step = fGeoManager->GetStep(); -// printf("---next : at step=%f\n", step); - if (step>1E10) return array; + // printf("---next : at step=%f\n", step); + if (step > 1E10) + return array; endnode = fGeoManager->Step(); is_entering = fGeoManager->IsEntering(); - while (step<1E10) { + while (step < 1E10) { if (endpoint) { - forward = dirx*(endpoint[0]-point[0])+diry*(endpoint[1]-point[1])+dirz*(endpoint[2]-point[2]); - if (forward<1E-3) { -// printf("exit : Passed start point. nelem=%i\n", nelem); + forward = dirx * (endpoint[0] - point[0]) + diry * (endpoint[1] - point[1]) + dirz * (endpoint[2] - point[2]); + if (forward < 1E-3) { + // printf("exit : Passed start point. nelem=%i\n", nelem); return array; } } if (is_entering) { - if (nelem>=dim) { - Double_t *temparray = new Double_t[3*(dim+20)]; - memcpy(temparray, array, 3*dim*sizeof(Double_t)); - delete [] array; + if (nelem >= dim) { + Double_t *temparray = new Double_t[3 * (dim + 20)]; + memcpy(temparray, array, 3 * dim * sizeof(Double_t)); + delete[] array; array = temparray; - dim += 20; + dim += 20; } - memcpy(&array[3*nelem], point, 3*sizeof(Double_t)); -// printf("%i (%f, %f, %f) step=%f\n", nelem, point[0], point[1], point[2], step); + memcpy(&array[3 * nelem], point, 3 * sizeof(Double_t)); + // printf("%i (%f, %f, %f) step=%f\n", nelem, point[0], point[1], point[2], step); nelem++; } else { - if (endnode==0 && step>1E10) { -// printf("exit : NULL endnode. nelem=%i\n", nelem); + if (endnode == 0 && step > 1E10) { + // printf("exit : NULL endnode. nelem=%i\n", nelem); return array; } if (!fGeoManager->IsEntering()) { -// if (startnode) printf("stepping %f from (%f, %f, %f) inside %s...\n", step,point[0], point[1], point[2], startnode->GetName()); -// else printf("stepping %f from (%f, %f, %f) OUTSIDE...\n", step,point[0], point[1], point[2]); + // if (startnode) printf("stepping %f from (%f, %f, %f) inside %s...\n", step,point[0], point[1], + // point[2], startnode->GetName()); else printf("stepping %f from (%f, %f, %f) OUTSIDE...\n", + // step,point[0], point[1], point[2]); istep = 0; } while (!fGeoManager->IsEntering()) { istep++; - if (istep>1E3) { -// Error("ShootRay", "more than 1000 steps. Step was %f", step); + if (istep > 1E3) { + // Error("ShootRay", "more than 1000 steps. Step was %f", step); nelem = 0; return array; } fGeoManager->SetStep(1E-5); endnode = fGeoManager->Step(); } - if (istep>0) printf("%i steps\n", istep); - if (nelem>=dim) { - Double_t *temparray = new Double_t[3*(dim+20)]; - memcpy(temparray, array, 3*dim*sizeof(Double_t)); - delete [] array; + if (istep > 0) + printf("%i steps\n", istep); + if (nelem >= dim) { + Double_t *temparray = new Double_t[3 * (dim + 20)]; + memcpy(temparray, array, 3 * dim * sizeof(Double_t)); + delete[] array; array = temparray; dim += 20; } - memcpy(&array[3*nelem], point, 3*sizeof(Double_t)); -// if (endnode) printf("%i (%f, %f, %f) step=%f\n", nelem, point[0], point[1], point[2], step); + memcpy(&array[3 * nelem], point, 3 * sizeof(Double_t)); + // if (endnode) printf("%i (%f, %f, %f) step=%f\n", nelem, point[0], point[1], point[2], step); nelem++; } fGeoManager->FindNextBoundary(); step = fGeoManager->GetStep(); -// printf("---next at step=%f\n", step); + // printf("---next at step=%f\n", step); endnode = fGeoManager->Step(); is_entering = fGeoManager->IsEntering(); } return array; -// printf("exit : INFINITE step. nelem=%i\n", nelem); + // printf("exit : INFINITE step. nelem=%i\n", nelem); } //////////////////////////////////////////////////////////////////////////////// @@ -2535,23 +2709,24 @@ Double_t *TGeoChecker::ShootRay(Double_t *start, Double_t dirx, Double_t diry, D void TGeoChecker::Test(Int_t npoints, Option_t *option) { Bool_t recheck = !strcmp(option, "RECHECK"); - if (recheck) printf("RECHECK\n"); + if (recheck) + printf("RECHECK\n"); const TGeoShape *shape = fGeoManager->GetTopVolume()->GetShape(); - Double_t dx = ((TGeoBBox*)shape)->GetDX(); - Double_t dy = ((TGeoBBox*)shape)->GetDY(); - Double_t dz = ((TGeoBBox*)shape)->GetDZ(); - Double_t ox = (((TGeoBBox*)shape)->GetOrigin())[0]; - Double_t oy = (((TGeoBBox*)shape)->GetOrigin())[1]; - Double_t oz = (((TGeoBBox*)shape)->GetOrigin())[2]; - Double_t *xyz = new Double_t[3*npoints]; + Double_t dx = ((TGeoBBox *)shape)->GetDX(); + Double_t dy = ((TGeoBBox *)shape)->GetDY(); + Double_t dz = ((TGeoBBox *)shape)->GetDZ(); + Double_t ox = (((TGeoBBox *)shape)->GetOrigin())[0]; + Double_t oy = (((TGeoBBox *)shape)->GetOrigin())[1]; + Double_t oz = (((TGeoBBox *)shape)->GetOrigin())[2]; + Double_t *xyz = new Double_t[3 * npoints]; TStopwatch *timer = new TStopwatch(); printf("Random box : %f, %f, %f\n", dx, dy, dz); timer->Start(kFALSE); Int_t i; - for (i=0; iRndm(); - xyz[3*i+1] = oy-dy+2*dy*gRandom->Rndm(); - xyz[3*i+2] = oz-dz+2*dz*gRandom->Rndm(); + for (i = 0; i < npoints; i++) { + xyz[3 * i] = ox - dx + 2 * dx * gRandom->Rndm(); + xyz[3 * i + 1] = oy - dy + 2 * dy * gRandom->Rndm(); + xyz[3 * i + 2] = oz - dz + 2 * dz * gRandom->Rndm(); } timer->Stop(); printf("Generation time :\n"); @@ -2560,14 +2735,15 @@ void TGeoChecker::Test(Int_t npoints, Option_t *option) TGeoNode *node, *node1; printf("Start... %i points\n", npoints); timer->Start(kFALSE); - for (i=0; iSetCurrentPoint(xyz+3*i); - if (recheck) fGeoManager->CdTop(); + for (i = 0; i < npoints; i++) { + fGeoManager->SetCurrentPoint(xyz + 3 * i); + if (recheck) + fGeoManager->CdTop(); node = fGeoManager->FindNode(); if (recheck) { node1 = fGeoManager->FindNode(); if (node1 != node) { - printf("Difference for x=%g y=%g z=%g\n", xyz[3*i], xyz[3*i+1], xyz[3*i+2]); + printf("Difference for x=%g y=%g z=%g\n", xyz[3 * i], xyz[3 * i + 1], xyz[3 * i + 2]); printf(" from top : %s\n", node->GetName()); printf(" redo : %s\n", fGeoManager->GetPath()); } @@ -2575,18 +2751,20 @@ void TGeoChecker::Test(Int_t npoints, Option_t *option) } timer->Stop(); timer->Print(); - delete [] xyz; + delete[] xyz; delete timer; } //////////////////////////////////////////////////////////////////////////////// /// Geometry overlap checker based on sampling. -void TGeoChecker::TestOverlaps(const char* path) +void TGeoChecker::TestOverlaps(const char *path) { - if (fGeoManager->GetTopVolume()!=fGeoManager->GetMasterVolume()) fGeoManager->RestoreMasterVolume(); + if (fGeoManager->GetTopVolume() != fGeoManager->GetMasterVolume()) + fGeoManager->RestoreMasterVolume(); printf("Checking overlaps for path :\n"); - if (!fGeoManager->cd(path)) return; + if (!fGeoManager->cd(path)) + return; TGeoNode *checked = fGeoManager->GetCurrentNode(); checked->InspectNode(); // shoot 1E4 points in the shape of the current volume @@ -2602,97 +2780,106 @@ void TGeoChecker::TestOverlaps(const char* path) TPolyMarker3D *marker = 0; TPolyMarker3D *markthis = new TPolyMarker3D(); markthis->SetMarkerColor(5); - TNtuple *ntpl = new TNtuple("ntpl","random points","x:y:z"); + TNtuple *ntpl = new TNtuple("ntpl", "random points", "x:y:z"); TGeoShape *shape = fGeoManager->GetCurrentNode()->GetVolume()->GetShape(); Double_t *point = new Double_t[3]; - Double_t dx = ((TGeoBBox*)shape)->GetDX(); - Double_t dy = ((TGeoBBox*)shape)->GetDY(); - Double_t dz = ((TGeoBBox*)shape)->GetDZ(); - Double_t ox = (((TGeoBBox*)shape)->GetOrigin())[0]; - Double_t oy = (((TGeoBBox*)shape)->GetOrigin())[1]; - Double_t oz = (((TGeoBBox*)shape)->GetOrigin())[2]; - Double_t *xyz = new Double_t[3*npoints]; - Int_t i=0; + Double_t dx = ((TGeoBBox *)shape)->GetDX(); + Double_t dy = ((TGeoBBox *)shape)->GetDY(); + Double_t dz = ((TGeoBBox *)shape)->GetDZ(); + Double_t ox = (((TGeoBBox *)shape)->GetOrigin())[0]; + Double_t oy = (((TGeoBBox *)shape)->GetOrigin())[1]; + Double_t oz = (((TGeoBBox *)shape)->GetOrigin())[2]; + Double_t *xyz = new Double_t[3 * npoints]; + Int_t i = 0; printf("Generating %i points inside %s\n", npoints, fGeoManager->GetPath()); - while (iRndm(); - point[1] = oy-dy+2*dy*gRandom->Rndm(); - point[2] = oz-dz+2*dz*gRandom->Rndm(); - if (!shape->Contains(point)) continue; + while (i < npoints) { + point[0] = ox - dx + 2 * dx * gRandom->Rndm(); + point[1] = oy - dy + 2 * dy * gRandom->Rndm(); + point[2] = oz - dz + 2 * dz * gRandom->Rndm(); + if (!shape->Contains(point)) + continue; // convert each point to MARS -// printf("local %9.3f %9.3f %9.3f\n", point[0], point[1], point[2]); - fGeoManager->LocalToMaster(point, &xyz[3*i]); -// printf("master %9.3f %9.3f %9.3f\n", xyz[3*i], xyz[3*i+1], xyz[3*i+2]); - xmin = TMath::Min(xmin, xyz[3*i]); - xmax = TMath::Max(xmax, xyz[3*i]); - ymin = TMath::Min(ymin, xyz[3*i+1]); - ymax = TMath::Max(ymax, xyz[3*i+1]); - zmin = TMath::Min(zmin, xyz[3*i+2]); - zmax = TMath::Max(zmax, xyz[3*i+2]); + // printf("local %9.3f %9.3f %9.3f\n", point[0], point[1], point[2]); + fGeoManager->LocalToMaster(point, &xyz[3 * i]); + // printf("master %9.3f %9.3f %9.3f\n", xyz[3*i], xyz[3*i+1], xyz[3*i+2]); + xmin = TMath::Min(xmin, xyz[3 * i]); + xmax = TMath::Max(xmax, xyz[3 * i]); + ymin = TMath::Min(ymin, xyz[3 * i + 1]); + ymax = TMath::Max(ymax, xyz[3 * i + 1]); + zmin = TMath::Min(zmin, xyz[3 * i + 2]); + zmax = TMath::Max(zmax, xyz[3 * i + 2]); i++; } - delete [] point; - ntpl->Fill(xmin,ymin,zmin); - ntpl->Fill(xmax,ymin,zmin); - ntpl->Fill(xmin,ymax,zmin); - ntpl->Fill(xmax,ymax,zmin); - ntpl->Fill(xmin,ymin,zmax); - ntpl->Fill(xmax,ymin,zmax); - ntpl->Fill(xmin,ymax,zmax); - ntpl->Fill(xmax,ymax,zmax); + delete[] point; + ntpl->Fill(xmin, ymin, zmin); + ntpl->Fill(xmax, ymin, zmin); + ntpl->Fill(xmin, ymax, zmin); + ntpl->Fill(xmax, ymax, zmin); + ntpl->Fill(xmin, ymin, zmax); + ntpl->Fill(xmax, ymin, zmax); + ntpl->Fill(xmin, ymax, zmax); + ntpl->Fill(xmax, ymax, zmax); ntpl->Draw("z:y:x"); // shoot the poins in the geometry TGeoNode *node; TString cpath; - Int_t ic=0; + Int_t ic = 0; TObjArray *overlaps = new TObjArray(); printf("using FindNode...\n"); - for (Int_t j=0; jCdTop(); - fGeoManager->SetCurrentPoint(&xyz[3*j]); + fGeoManager->SetCurrentPoint(&xyz[3 * j]); node = fGeoManager->FindNode(); cpath = fGeoManager->GetPath(); if (cpath.Contains(path)) { - markthis->SetNextPoint(xyz[3*j], xyz[3*j+1], xyz[3*j+2]); + markthis->SetNextPoint(xyz[3 * j], xyz[3 * j + 1], xyz[3 * j + 2]); continue; } // current point is found in an overlapping node - if (!node) ic=128; - else ic = node->GetVolume()->GetLineColor(); - if (ic >= 128) ic = 0; - marker = (TPolyMarker3D*)pm->At(ic); + if (!node) + ic = 128; + else + ic = node->GetVolume()->GetLineColor(); + if (ic >= 128) + ic = 0; + marker = (TPolyMarker3D *)pm->At(ic); if (!marker) { marker = new TPolyMarker3D(); marker->SetMarkerColor(ic); pm->AddAt(marker, ic); } // draw the overlapping point - marker->SetNextPoint(xyz[3*j], xyz[3*j+1], xyz[3*j+2]); + marker->SetNextPoint(xyz[3 * j], xyz[3 * j + 1], xyz[3 * j + 2]); if (node) { - if (overlaps->IndexOf(node) < 0) overlaps->Add(node); + if (overlaps->IndexOf(node) < 0) + overlaps->Add(node); } } // draw all overlapping points -// for (Int_t m=0; m<128; m++) { -// marker = (TPolyMarker3D*)pm->At(m); -// if (marker) marker->Draw("SAME"); -// } + // for (Int_t m=0; m<128; m++) { + // marker = (TPolyMarker3D*)pm->At(m); + // if (marker) marker->Draw("SAME"); + // } markthis->Draw("SAME"); - if (gPad) gPad->Update(); + if (gPad) + gPad->Update(); // display overlaps if (overlaps->GetEntriesFast()) { printf("list of overlapping nodes :\n"); - for (i=0; iGetEntriesFast(); i++) { - node = (TGeoNode*)overlaps->At(i); - if (node->IsOverlapping()) printf("%s MANY\n", node->GetName()); - else printf("%s ONLY\n", node->GetName()); + for (i = 0; i < overlaps->GetEntriesFast(); i++) { + node = (TGeoNode *)overlaps->At(i); + if (node->IsOverlapping()) + printf("%s MANY\n", node->GetName()); + else + printf("%s ONLY\n", node->GetName()); } - } else printf("No overlaps\n"); + } else + printf("No overlaps\n"); delete ntpl; delete pm; - delete [] xyz; + delete[] xyz; delete overlaps; } @@ -2704,9 +2891,10 @@ Double_t TGeoChecker::Weight(Double_t precision, Option_t *option) { TList *matlist = fGeoManager->GetListOfMaterials(); Int_t nmat = matlist->GetSize(); - if (!nmat) return 0; + if (!nmat) + return 0; Int_t *nin = new Int_t[nmat]; - memset(nin, 0, nmat*sizeof(Int_t)); + memset(nin, 0, nmat * sizeof(Int_t)); TString opt = option; opt.ToLower(); Bool_t isverbose = opt.Contains("v"); @@ -2717,59 +2905,60 @@ Double_t TGeoChecker::Weight(Double_t precision, Option_t *option) Double_t ox = (box->GetOrigin())[0]; Double_t oy = (box->GetOrigin())[1]; Double_t oz = (box->GetOrigin())[2]; - Double_t x,y,z; + Double_t x, y, z; TGeoNode *node; TGeoMaterial *mat; - Double_t vbox = 0.000008*dx*dy*dz; // m3 + Double_t vbox = 0.000008 * dx * dy * dz; // m3 Bool_t end = kFALSE; - Double_t weight=0, sigma, eps, dens; - Double_t eps0=1.; + Double_t weight = 0, sigma, eps, dens; + Double_t eps0 = 1.; Int_t indmat; - Int_t igen=0; + Int_t igen = 0; Int_t iin = 0; while (!end) { - x = ox-dx+2*dx*gRandom->Rndm(); - y = oy-dy+2*dy*gRandom->Rndm(); - z = oz-dz+2*dz*gRandom->Rndm(); - node = fGeoManager->FindNode(x,y,z); + x = ox - dx + 2 * dx * gRandom->Rndm(); + y = oy - dy + 2 * dy * gRandom->Rndm(); + z = oz - dz + 2 * dz * gRandom->Rndm(); + node = fGeoManager->FindNode(x, y, z); igen++; - if (!node) continue; + if (!node) + continue; mat = node->GetVolume()->GetMedium()->GetMaterial(); indmat = mat->GetIndex(); - if (indmat<0) continue; + if (indmat < 0) + continue; nin[indmat]++; iin++; - if ((iin%100000)==0 || igen>1E8) { + if ((iin % 100000) == 0 || igen > 1E8) { weight = 0; sigma = 0; - for (indmat=0; indmatAt(indmat); + for (indmat = 0; indmat < nmat; indmat++) { + mat = (TGeoMaterial *)matlist->At(indmat); dens = mat->GetDensity(); // [g/cm3] - if (dens<1E-2) dens=0; - dens *= 1000.; // [kg/m3] - weight += dens*Double_t(nin[indmat]); - sigma += dens*dens*nin[indmat]; + if (dens < 1E-2) + dens = 0; + dens *= 1000.; // [kg/m3] + weight += dens * Double_t(nin[indmat]); + sigma += dens * dens * nin[indmat]; } - sigma = TMath::Sqrt(sigma); - eps = sigma/weight; - weight *= vbox/Double_t(igen); - sigma *= vbox/Double_t(igen); - if (eps1E8) { - if (isverbose) { - printf("=== Weight of %s : %g +/- %g [kg]\n", - fGeoManager->GetTopVolume()->GetName(), weight, sigma); - } - end = kTRUE; - } else { - if (isverbose && eps<0.5*eps0) { - printf("%8dK: %14.7g kg %g %%\n", - igen/1000, weight, eps*100); + sigma = TMath::Sqrt(sigma); + eps = sigma / weight; + weight *= vbox / Double_t(igen); + sigma *= vbox / Double_t(igen); + if (eps < precision || igen > 1E8) { + if (isverbose) { + printf("=== Weight of %s : %g +/- %g [kg]\n", fGeoManager->GetTopVolume()->GetName(), weight, sigma); + } + end = kTRUE; + } else { + if (isverbose && eps < 0.5 * eps0) { + printf("%8dK: %14.7g kg %g %%\n", igen / 1000, weight, eps * 100); eps0 = eps; } } } } - delete [] nin; + delete[] nin; return weight; } //////////////////////////////////////////////////////////////////////////////// @@ -2789,17 +2978,21 @@ Double_t TGeoChecker::CheckVoxels(TGeoVolume *vol, TGeoVoxelFinder *voxels, Doub TGeoNavigator *nav = fGeoManager->GetCurrentNavigator(); TGeoStateInfo &td = *nav->GetCache()->GetInfo(); timer.Start(); - for (Int_t i=0; iContains(point)) continue; + for (Int_t i = 0; i < npoints; i++) { + point = xyz + 3 * i; + if (!shape->Contains(point)) + continue; checklist = voxels->GetCheckList(point, ncheck, td); - if (!checklist) continue; - if (!ncheck) continue; - for (Int_t id=0; idGetNode(checklist[id]); matrix = node->GetMatrix(); matrix->MasterToLocal(point, &local[0]); - if (node->GetVolume()->GetShape()->Contains(&local[0])) break; + if (node->GetVolume()->GetShape()->Contains(&local[0])) + break; } } nav->GetCache()->ReleaseInfo(); diff --git a/geom/geompainter/src/TGeoOverlap.cxx b/geom/geompainter/src/TGeoOverlap.cxx index adc453d8a5c96..4ea308115f727 100644 --- a/geom/geompainter/src/TGeoOverlap.cxx +++ b/geom/geompainter/src/TGeoOverlap.cxx @@ -43,29 +43,28 @@ TGeoOverlap::TGeoOverlap() fVolume2 = 0; fMatrix1 = 0; fMatrix2 = 0; - fMarker = 0; + fMarker = 0; } //////////////////////////////////////////////////////////////////////////////// /// Creates a named overlap belonging to volume VOL and having the size OVLP. -TGeoOverlap::TGeoOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, - const TGeoMatrix *matrix1, const TGeoMatrix *matrix2, - Bool_t isovlp, Double_t ovlp) - :TNamed("",name) +TGeoOverlap::TGeoOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, const TGeoMatrix *matrix1, + const TGeoMatrix *matrix2, Bool_t isovlp, Double_t ovlp) + : TNamed("", name) { fOverlap = ovlp; - fVolume1 = vol1; - fVolume2 = vol2; + fVolume1 = vol1; + fVolume2 = vol2; fMatrix1 = new TGeoHMatrix(); *fMatrix1 = matrix1; fMatrix2 = new TGeoHMatrix(); *fMatrix2 = matrix2; - fMarker = new TPolyMarker3D(); + fMarker = new TPolyMarker3D(); fMarker->SetMarkerColor(2); SetIsOverlap(isovlp); fMarker->SetMarkerStyle(6); -// fMarker->SetMarkerSize(0.5); + // fMarker->SetMarkerSize(0.5); } //////////////////////////////////////////////////////////////////////////////// @@ -73,9 +72,12 @@ TGeoOverlap::TGeoOverlap(const char *name, TGeoVolume *vol1, TGeoVolume *vol2, TGeoOverlap::~TGeoOverlap() { - if (fMarker) delete fMarker; - if (fMatrix1) delete fMatrix1; - if (fMatrix2) delete fMatrix2; + if (fMarker) + delete fMarker; + if (fMatrix1) + delete fMatrix1; + if (fMatrix2) + delete fMatrix2; } //////////////////////////////////////////////////////////////////////////////// @@ -83,7 +85,8 @@ TGeoOverlap::~TGeoOverlap() void TGeoOverlap::Browse(TBrowser *b) { - if (!b) return; + if (!b) + return; Draw(); } @@ -96,17 +99,19 @@ void TGeoOverlap::Browse(TBrowser *b) Int_t TGeoOverlap::Compare(const TObject *obj) const { TGeoOverlap *other = 0; - other = (TGeoOverlap*)obj; + other = (TGeoOverlap *)obj; if (!other) { Error("Compare", "other object is not TGeoOverlap"); return 0; } if (IsExtrusion()) { - if (other->IsExtrusion()) return (fOverlap<=other->GetOverlap())?1:-1; + if (other->IsExtrusion()) + return (fOverlap <= other->GetOverlap()) ? 1 : -1; return -1; } else { - if (other->IsExtrusion()) return 1; - return (fOverlap<=other->GetOverlap())?1:-1; + if (other->IsExtrusion()) + return 1; + return (fOverlap <= other->GetOverlap()) ? 1 : -1; } } @@ -163,7 +168,7 @@ void TGeoOverlap::Print(Option_t *) const void TGeoOverlap::PrintInfo() const { - printf(" = Overlap %s: %s ovlp=%g\n", GetName(), GetTitle(),fOverlap); + printf(" = Overlap %s: %s ovlp=%g\n", GetName(), GetTitle(), fOverlap); } //////////////////////////////////////////////////////////////////////////////// @@ -171,7 +176,7 @@ void TGeoOverlap::PrintInfo() const void TGeoOverlap::SetNextPoint(Double_t x, Double_t y, Double_t z) { - fMarker->SetNextPoint(x,y,z); + fMarker->SetNextPoint(x, y, z); } //////////////////////////////////////////////////////////////////////////////// @@ -182,7 +187,7 @@ void TGeoOverlap::SampleOverlap(Int_t npoints) Draw(); // Select bounding box of the second volume (may extrude first) TPolyMarker3D *marker = 0; - TGeoBBox *box = (TGeoBBox*)fVolume2->GetShape(); + TGeoBBox *box = (TGeoBBox *)fVolume2->GetShape(); Double_t dx = box->GetDX(); Double_t dy = box->GetDY(); Double_t dz = box->GetDZ(); @@ -193,13 +198,13 @@ void TGeoOverlap::SampleOverlap(Int_t npoints) Int_t itry = 0; Int_t iovlp = 0; while (ipoint < npoints) { - // Shoot randomly in the bounding box. - pt[0] = orig[0] - dx + 2.*dx*gRandom->Rndm(); - pt[1] = orig[1] - dy + 2.*dy*gRandom->Rndm(); - pt[2] = orig[2] - dz + 2.*dz*gRandom->Rndm(); + // Shoot randomly in the bounding box. + pt[0] = orig[0] - dx + 2. * dx * gRandom->Rndm(); + pt[1] = orig[1] - dy + 2. * dy * gRandom->Rndm(); + pt[2] = orig[2] - dz + 2. * dz * gRandom->Rndm(); if (!fVolume2->Contains(pt)) { itry++; - if (itry>10000 && !ipoint) { + if (itry > 10000 && !ipoint) { Error("SampleOverlap", "No point inside volume!!! - aborting"); break; } @@ -210,8 +215,10 @@ void TGeoOverlap::SampleOverlap(Int_t npoints) fMatrix2->LocalToMaster(pt, master); fMatrix1->MasterToLocal(master, pt); Bool_t in = fVolume1->Contains(pt); - if (IsOverlap() && !in) continue; - if (!IsOverlap() && in) continue; + if (IsOverlap() && !in) + continue; + if (!IsOverlap() && in) + continue; // The point is in the overlapping region. iovlp++; if (!marker) { @@ -220,15 +227,15 @@ void TGeoOverlap::SampleOverlap(Int_t npoints) } marker->SetNextPoint(master[0], master[1], master[2]); } - if (!iovlp) return; + if (!iovlp) + return; marker->Draw("SAME"); gPad->Modified(); gPad->Update(); Double_t capacity = fVolume1->GetShape()->Capacity(); - capacity *= Double_t(iovlp)/Double_t(npoints); - Double_t err = 1./TMath::Sqrt(Double_t(iovlp)); - Info("SampleOverlap", "#Overlap %s has %g +/- %g [cm3]", - GetName(), capacity, err*capacity); + capacity *= Double_t(iovlp) / Double_t(npoints); + Double_t err = 1. / TMath::Sqrt(Double_t(iovlp)); + Info("SampleOverlap", "#Overlap %s has %g +/- %g [cm3]", GetName(), capacity, err * capacity); } //////////////////////////////////////////////////////////////////////////////// @@ -247,22 +254,20 @@ void TGeoOverlap::Validate() const { Double_t point[3]; Double_t local[3]; - Double_t safe1,safe2; + Double_t safe1, safe2; Int_t npoints = fMarker->GetN(); - for (Int_t i=0; iGetPoint(i, point[0], point[1], point[2]); if (IsExtrusion()) { - fMatrix1->MasterToLocal(point,local); + fMatrix1->MasterToLocal(point, local); safe1 = fVolume1->GetShape()->Safety(local, kFALSE); printf("point %d: safe1=%f\n", i, safe1); } else { - fMatrix1->MasterToLocal(point,local); + fMatrix1->MasterToLocal(point, local); safe1 = fVolume1->GetShape()->Safety(local, kTRUE); - fMatrix2->MasterToLocal(point,local); + fMatrix2->MasterToLocal(point, local); safe2 = fVolume2->GetShape()->Safety(local, kTRUE); - printf("point %d: safe1=%f safe2=%f\n", i, safe1,safe2); + printf("point %d: safe1=%f safe2=%f\n", i, safe1, safe2); } } } - - diff --git a/geom/geompainter/src/TGeoPainter.cxx b/geom/geompainter/src/TGeoPainter.cxx index 1a8add0356a66..d668d48c8d27f 100644 --- a/geom/geompainter/src/TGeoPainter.cxx +++ b/geom/geompainter/src/TGeoPainter.cxx @@ -65,7 +65,8 @@ ClassImp(TGeoPainter); TGeoPainter::TGeoPainter(TGeoManager *manager) : TVirtualGeoPainter(manager) { TVirtualGeoPainter::SetPainter(this); - if (manager) fGeoManager = manager; + if (manager) + fGeoManager = manager; else { Error("ctor", "No geometry loaded"); return; @@ -89,12 +90,12 @@ TGeoPainter::TGeoPainter(TGeoManager *manager) : TVirtualGeoPainter(manager) fVisVolumes = new TObjArray(); fOverlap = nullptr; fGlobal = new TGeoHMatrix(); - fBuffer = new TBuffer3D(TBuffer3DTypes::kGeneric,20,3*20,0,0,0,0); + fBuffer = new TBuffer3D(TBuffer3DTypes::kGeneric, 20, 3 * 20, 0, 0, 0, 0); fClippingShape = nullptr; fLastVolume = nullptr; fTopVolume = nullptr; fIsPaintingShape = kFALSE; - memset(&fCheckedBox[0], 0, 6*sizeof(Double_t)); + memset(&fCheckedBox[0], 0, 6 * sizeof(Double_t)); fCheckedNode = fGeoManager->GetTopNode(); fChecker = new TGeoChecker(fGeoManager); @@ -106,11 +107,13 @@ TGeoPainter::TGeoPainter(TGeoManager *manager) : TVirtualGeoPainter(manager) TGeoPainter::~TGeoPainter() { - if (fChecker) delete fChecker; + if (fChecker) + delete fChecker; delete fVisVolumes; delete fGlobal; delete fBuffer; - if (fPlugin) delete fPlugin; + if (fPlugin) + delete fPlugin; } //////////////////////////////////////////////////////////////////////////////// /// Add numpoints, numsegs, numpolys to the global 3D size. @@ -118,15 +121,15 @@ TGeoPainter::~TGeoPainter() void TGeoPainter::AddSize3D(Int_t numpoints, Int_t numsegs, Int_t numpolys) { gSize3D.numPoints += numpoints; - gSize3D.numSegs += numsegs; - gSize3D.numPolys += numpolys; + gSize3D.numSegs += numsegs; + gSize3D.numPolys += numpolys; } //////////////////////////////////////////////////////////////////////////////// /// Create a primary TGeoTrack. TVirtualGeoTrack *TGeoPainter::AddTrack(Int_t id, Int_t pdgcode, TObject *particle) { - return (TVirtualGeoTrack*)(new TGeoTrack(id,pdgcode,0,particle)); + return (TVirtualGeoTrack *)(new TGeoTrack(id, pdgcode, 0, particle)); } //////////////////////////////////////////////////////////////////////////////// @@ -135,27 +138,30 @@ TVirtualGeoTrack *TGeoPainter::AddTrack(Int_t id, Int_t pdgcode, TObject *partic void TGeoPainter::AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset) { static Int_t npoints = 0; - static Double_t xmin[3] = {0,0,0}; - static Double_t xmax[3] = {0,0,0}; + static Double_t xmin[3] = {0, 0, 0}; + static Double_t xmax[3] = {0, 0, 0}; Int_t i; if (reset) { - memset(box, 0, 6*sizeof(Double_t)); - memset(xmin, 0, 3*sizeof(Double_t)); - memset(xmax, 0, 3*sizeof(Double_t)); + memset(box, 0, 6 * sizeof(Double_t)); + memset(xmin, 0, 3 * sizeof(Double_t)); + memset(xmax, 0, 3 * sizeof(Double_t)); npoints = 0; return; } - if (npoints==0) { - for (i=0; i<3; i++) xmin[i]=xmax[i]=0; + if (npoints == 0) { + for (i = 0; i < 3; i++) + xmin[i] = xmax[i] = 0; npoints++; } npoints++; - Double_t ninv = 1./Double_t(npoints); - for (i=0; i<3; i++) { - box[i] += ninv*(point[i]-box[i]); - if (point[i]xmax[i]) xmax[i]=point[i]; - box[i+3] = 0.5*(xmax[i]-xmin[i]); + Double_t ninv = 1. / Double_t(npoints); + for (i = 0; i < 3; i++) { + box[i] += ninv * (point[i] - box[i]); + if (point[i] < xmin[i]) + xmin[i] = point[i]; + if (point[i] > xmax[i]) + xmax[i] = point[i]; + box[i + 3] = 0.5 * (xmax[i] - xmin[i]); } } @@ -164,27 +170,25 @@ void TGeoPainter::AddTrackPoint(Double_t *point, Double_t *box, Bool_t reset) void TGeoPainter::BombTranslation(const Double_t *tr, Double_t *bombtr) { - memcpy(bombtr, tr, 3*sizeof(Double_t)); + memcpy(bombtr, tr, 3 * sizeof(Double_t)); switch (fExplodedView) { - case kGeoNoBomb: - return; - case kGeoBombXYZ: - bombtr[0] *= fBombX; - bombtr[1] *= fBombY; - bombtr[2] *= fBombZ; - return; - case kGeoBombCyl: - bombtr[0] *= fBombR; - bombtr[1] *= fBombR; - bombtr[2] *= fBombZ; - return; - case kGeoBombSph: - bombtr[0] *= fBombR; - bombtr[1] *= fBombR; - bombtr[2] *= fBombR; - return; - default: - return; + case kGeoNoBomb: return; + case kGeoBombXYZ: + bombtr[0] *= fBombX; + bombtr[1] *= fBombY; + bombtr[2] *= fBombZ; + return; + case kGeoBombCyl: + bombtr[0] *= fBombR; + bombtr[1] *= fBombR; + bombtr[2] *= fBombZ; + return; + case kGeoBombSph: + bombtr[0] *= fBombR; + bombtr[1] *= fBombR; + bombtr[2] *= fBombR; + return; + default: return; } } @@ -213,7 +217,7 @@ void TGeoPainter::CheckBoundaryReference(Int_t icheck) void TGeoPainter::CheckGeometryFull(Bool_t checkoverlaps, Bool_t checkcrossings, Int_t ntracks, const Double_t *vertex) { - fChecker->CheckGeometryFull(checkoverlaps,checkcrossings,ntracks,vertex); + fChecker->CheckGeometryFull(checkoverlaps, checkcrossings, ntracks, vertex); } //////////////////////////////////////////////////////////////////////////////// @@ -237,7 +241,7 @@ void TGeoPainter::CheckOverlaps(const TGeoVolume *vol, Double_t ovlp, Option_t * void TGeoPainter::CheckPoint(Double_t x, Double_t y, Double_t z, Option_t *option) { - fChecker->CheckPoint(x,y,z,option); + fChecker->CheckPoint(x, y, z, option); } //////////////////////////////////////////////////////////////////////////////// @@ -253,21 +257,21 @@ void TGeoPainter::CheckShape(TGeoShape *shape, Int_t testNo, Int_t nsamples, Opt } //////////////////////////////////////////////////////////////////////////////// -///Clear the list of visible volumes -///reset the kVisOnScreen bit for volumes previously in the list +/// Clear the list of visible volumes +/// reset the kVisOnScreen bit for volumes previously in the list void TGeoPainter::ClearVisibleVolumes() { - if (!fVisVolumes) return; + if (!fVisVolumes) + return; TIter next(fVisVolumes); TGeoVolume *vol; - while ((vol = (TGeoVolume*)next())) { + while ((vol = (TGeoVolume *)next())) { vol->ResetAttBit(TGeoAtt::kVisOnScreen); } fVisVolumes->Clear(); } - //////////////////////////////////////////////////////////////////////////////// /// Define 100 colors with increasing light intensities for each basic color (1-7) /// Register these colors at indexes starting with 1000. @@ -277,7 +281,7 @@ void TGeoPainter::DefineColors() const static Int_t color = 0; if (!color) { TColor::InitializeColors(); - for (auto icol=1; icol<10; ++icol) + for (auto icol = 1; icol < 10; ++icol) color = GetColor(icol, 0.5); } } @@ -295,34 +299,37 @@ Int_t TGeoPainter::GetColor(Int_t base, Float_t light) const Int_t color = base; // Search color in the map auto it = colmap.find(base); - if (it != colmap.end()) return (it->second + light*(ncolors-1)); + if (it != colmap.end()) + return (it->second + light * (ncolors - 1)); // Get color pointer if stored - TColor* col_base = gROOT->GetColor(base); + TColor *col_base = gROOT->GetColor(base); if (!col_base) { // If color not defined, use gray palette it = colmap.find(kBlack); - if (it != colmap.end()) return (it->second + light*(ncolors-1)); + if (it != colmap.end()) + return (it->second + light * (ncolors - 1)); col_base = gROOT->GetColor(kBlack); color = 1; } // Create a color palette for col_base - Float_t r=0., g=0., b=0., h=0., l=0., s=0.; + Float_t r = 0., g = 0., b = 0., h = 0., l = 0., s = 0.; Double_t red[2], green[2], blue[2]; Double_t stop[] = {0., 1.0}; - if (col_base) col_base->GetRGB(r,g,b); - TColor::RGB2HLS(r,g,b,h,l,s); - TColor::HLS2RGB(h,lmin,s,r,g,b); + if (col_base) + col_base->GetRGB(r, g, b); + TColor::RGB2HLS(r, g, b, h, l, s); + TColor::HLS2RGB(h, lmin, s, r, g, b); red[0] = r; green[0] = g; blue[0] = b; - TColor::HLS2RGB(h,lmax,s,r,g,b); + TColor::HLS2RGB(h, lmax, s, r, g, b); red[1] = r; green[1] = g; blue[1] = b; Int_t color_map_idx = TColor::CreateGradientColorTable(2, stop, red, green, blue, ncolors, 1., kFALSE); colmap[color] = color_map_idx; - return (color_map_idx + light*(ncolors-1)); + return (color_map_idx + light * (ncolors - 1)); } //////////////////////////////////////////////////////////////////////////////// @@ -330,7 +337,8 @@ Int_t TGeoPainter::GetColor(Int_t base, Float_t light) const TGeoVolume *TGeoPainter::GetDrawnVolume() const { - if (!gPad) return nullptr; + if (!gPad) + return nullptr; return fTopVolume; } @@ -343,9 +351,11 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py const Int_t inaxis = 7; const Int_t maxdist = 5; - if (fTopVolume != volume) fTopVolume = volume; + if (fTopVolume != volume) + fTopVolume = volume; TView *view = gPad->GetView(); - if (!view) return big; + if (!view) + return big; TGeoBBox *box; fGlobal->Clear(); TGeoShape::SetTransform(fGlobal); @@ -355,24 +365,28 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); // return if point not in user area - if (px < puxmin - inaxis) return big; - if (py > puymin + inaxis) return big; - if (px > puxmax + inaxis) return big; - if (py < puymax - inaxis) return big; + if (px < puxmin - inaxis) + return big; + if (py > puymin + inaxis) + return big; + if (px > puxmax + inaxis) + return big; + if (py < puymax - inaxis) + return big; fCheckedNode = fGeoManager->GetTopNode(); gPad->SetSelected(view); Int_t dist = big; -// Int_t id; + // Int_t id; if (fPaintingOverlaps) { TGeoVolume *crt; crt = fOverlap->GetFirstVolume(); *fGlobal = fOverlap->GetFirstMatrix(); - dist = crt->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { gPad->SetSelected(crt); - box = (TGeoBBox*)crt->GetShape(); + box = (TGeoBBox *)crt->GetShape(); fGlobal->LocalToMaster(box->GetOrigin(), &fCheckedBox[0]); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); @@ -381,10 +395,10 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py } crt = fOverlap->GetSecondVolume(); *fGlobal = fOverlap->GetSecondMatrix(); - dist = crt->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { gPad->SetSelected(crt); - box = (TGeoBBox*)crt->GetShape(); + box = (TGeoBBox *)crt->GetShape(); fGlobal->LocalToMaster(box->GetOrigin(), &fCheckedBox[0]); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); @@ -393,14 +407,14 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py } return big; } - // Compute distance to the right edge - if ((puxmax+inaxis-px) < 40) { - if ((py-puymax+inaxis) < 40) { + // Compute distance to the right edge + if ((puxmax + inaxis - px) < 40) { + if ((py - puymax + inaxis) < 40) { // when the mouse points to the (40x40) right corner of the pad, the manager class is selected gPad->SetSelected(fGeoManager); fVolInfo = fGeoManager->GetName(); - box = (TGeoBBox*)volume->GetShape(); - memcpy(fCheckedBox, box->GetOrigin(), 3*sizeof(Double_t)); + box = (TGeoBBox *)volume->GetShape(); + memcpy(fCheckedBox, box->GetOrigin(), 3 * sizeof(Double_t)); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -409,8 +423,8 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py // when the mouse points to the (40 pix) right edge of the pad, the top volume is selected gPad->SetSelected(volume); fVolInfo = volume->GetName(); - box = (TGeoBBox*)volume->GetShape(); - memcpy(fCheckedBox, box->GetOrigin(), 3*sizeof(Double_t)); + box = (TGeoBBox *)volume->GetShape(); + memcpy(fCheckedBox, box->GetOrigin(), 3 * sizeof(Double_t)); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -419,23 +433,26 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py TGeoVolume *vol = volume; Bool_t vis = vol->IsVisible(); -// Bool_t drawDaughters = kTRUE; + // Bool_t drawDaughters = kTRUE; // Do we need to check a branch only? if (volume->IsVisBranch()) { - if (!fGeoManager->IsClosed()) return big; + if (!fGeoManager->IsClosed()) + return big; fGeoManager->PushPath(); fGeoManager->cd(fVisBranch.Data()); while (fGeoManager->GetLevel()) { vol = fGeoManager->GetCurrentVolume(); *fGlobal = gGeoManager->GetCurrentMatrix(); - dist = vol->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { fVolInfo = fVisBranch; - box = (TGeoBBox*)vol->GetShape(); + box = (TGeoBBox *)vol->GetShape(); fGeoManager->LocalToMaster(box->GetOrigin(), &fCheckedBox[0]); fCheckedNode = gGeoManager->GetCurrentNode(); - if (fGeoManager->IsNodeSelectable()) gPad->SetSelected(fCheckedNode); - else gPad->SetSelected(vol); + if (fGeoManager->IsNodeSelectable()) + gPad->SetSelected(fCheckedNode); + else + gPad->SetSelected(vol); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -450,12 +467,12 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py // Do I need to look for the top volume ? if ((fTopVisible && vis) || !vol->GetNdaughters() || !vol->IsVisDaughters() || vol->IsVisOnly()) { - dist = vol->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { fVolInfo = vol->GetName(); gPad->SetSelected(vol); - box = (TGeoBBox*)vol->GetShape(); - memcpy(fCheckedBox, box->GetOrigin(), 3*sizeof(Double_t)); + box = (TGeoBBox *)vol->GetShape(); + memcpy(fCheckedBox, box->GetOrigin(), 3 * sizeof(Double_t)); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -467,28 +484,30 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py // Iterate the volume content TGeoIterator next(vol); - next.SetTopName(TString::Format("%s_1",vol->GetName())); + next.SetTopName(TString::Format("%s_1", vol->GetName())); TGeoNode *daughter; Int_t level, nd; Bool_t last; - while ((daughter=next())) { + while ((daughter = next())) { vol = daughter->GetVolume(); level = next.GetLevel(); nd = daughter->GetNdaughters(); vis = daughter->IsVisible(); if (volume->IsVisContainers()) { - if (vis && level<=fVisLevel) { + if (vis && level <= fVisLevel) { *fGlobal = next.GetCurrentMatrix(); - dist = vol->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { next.GetPath(fVolInfo); - box = (TGeoBBox*)vol->GetShape(); + box = (TGeoBBox *)vol->GetShape(); fGlobal->LocalToMaster(box->GetOrigin(), &fCheckedBox[0]); fCheckedNode = daughter; - if (fGeoManager->IsNodeSelectable()) gPad->SetSelected(fCheckedNode); - else gPad->SetSelected(vol); + if (fGeoManager->IsNodeSelectable()) + gPad->SetSelected(fCheckedNode); + else + gPad->SetSelected(vol); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -497,22 +516,24 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py } } // Check if we have to skip this branch - if (level==fVisLevel || !daughter->IsVisDaughters()) { + if (level == fVisLevel || !daughter->IsVisDaughters()) { next.Skip(); continue; } } else if (volume->IsVisLeaves()) { - last = ((nd==0) || (level==fVisLevel) || (!daughter->IsVisDaughters()))?kTRUE:kFALSE; + last = ((nd == 0) || (level == fVisLevel) || (!daughter->IsVisDaughters())) ? kTRUE : kFALSE; if (vis && last) { *fGlobal = next.GetCurrentMatrix(); - dist = vol->GetShape()->DistancetoPrimitive(px,py); - if (distGetShape()->DistancetoPrimitive(px, py); + if (dist < maxdist) { next.GetPath(fVolInfo); - box = (TGeoBBox*)vol->GetShape(); + box = (TGeoBBox *)vol->GetShape(); fGlobal->LocalToMaster(box->GetOrigin(), &fCheckedBox[0]); fCheckedNode = daughter; - if (fGeoManager->IsNodeSelectable()) gPad->SetSelected(fCheckedNode); - else gPad->SetSelected(vol); + if (fGeoManager->IsNodeSelectable()) + gPad->SetSelected(fCheckedNode); + else + gPad->SetSelected(vol); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -521,7 +542,8 @@ Int_t TGeoPainter::DistanceToPrimitiveVol(TGeoVolume *volume, Int_t px, Int_t py } } // Check if we have to skip the branch - if (last || !daughter->IsVisDaughters()) next.Skip(); + if (last || !daughter->IsVisDaughters()) + next.Skip(); } } return dist; @@ -535,8 +557,9 @@ void TGeoPainter::DefaultAngles() if (gPad) { Int_t irep; TView *view = gPad->GetView(); - if (!view) return; - view->SetView(-206,126,75,irep); + if (!view) + return; + view->SetView(-206, 126, 75, irep); ModifiedPad(); } } @@ -548,7 +571,7 @@ void TGeoPainter::DefaultColors() { TIter next(fGeoManager->GetListOfVolumes()); TGeoVolume *vol; - while ((vol=(TGeoVolume*)next())) + while ((vol = (TGeoVolume *)next())) vol->SetLineColor(vol->GetMaterial()->GetDefaultColor()); ModifiedPad(); } @@ -565,7 +588,8 @@ Int_t TGeoPainter::CountNodes(TGeoVolume *volume, Int_t rlevel) const if ((fTopVisible && vis) || !vol->GetNdaughters() || !vol->IsVisDaughters() || vol->IsVisOnly()) count++; // Is this the only volume? - if (volume->IsVisOnly()) return count; + if (volume->IsVisOnly()) + return count; // Do we need to check a branch only? if (volume->IsVisBranch()) { @@ -581,23 +605,26 @@ Int_t TGeoPainter::CountNodes(TGeoVolume *volume, Int_t rlevel) const Int_t level, nd; Bool_t last; - while ((daughter=next())) { -// vol = daughter->GetVolume(); + while ((daughter = next())) { + // vol = daughter->GetVolume(); level = next.GetLevel(); nd = daughter->GetNdaughters(); vis = daughter->IsVisible(); if (volume->IsVisContainers()) { - if (vis && level<=rlevel) count++; + if (vis && level <= rlevel) + count++; // Check if we have to skip this branch - if (level==rlevel || !daughter->IsVisDaughters()) { + if (level == rlevel || !daughter->IsVisDaughters()) { next.Skip(); continue; } } else if (volume->IsVisLeaves()) { - last = ((nd==0) || (level==rlevel) || (!daughter->IsVisDaughters()))?kTRUE:kFALSE; - if (vis && last) count++; + last = ((nd == 0) || (level == rlevel) || (!daughter->IsVisDaughters())) ? kTRUE : kFALSE; + if (vis && last) + count++; // Check if we have to skip the branch - if (last) next.Skip(); + if (last) + next.Skip(); } } return count; @@ -610,23 +637,23 @@ Int_t TGeoPainter::CountVisibleNodes() { Int_t maxnodes = fGeoManager->GetMaxVisNodes(); Int_t vislevel = fGeoManager->GetVisLevel(); -// TGeoVolume *top = fGeoManager->GetTopVolume(); + // TGeoVolume *top = fGeoManager->GetTopVolume(); TGeoVolume *top = fTopVolume; - if (maxnodes <= 0 && top) { + if (maxnodes <= 0 && top) { fNVisNodes = CountNodes(top, vislevel); SetVisLevel(vislevel); return fNVisNodes; } - //if (the total number of nodes of the top volume is less than maxnodes + // if (the total number of nodes of the top volume is less than maxnodes // we can visualize everything. - //recompute the best visibility level + // recompute the best visibility level if (!top) { SetVisLevel(vislevel); return 0; } fNVisNodes = -1; Bool_t again = kFALSE; - for (Int_t level = 1;level<20;level++) { + for (Int_t level = 1; level < 20; level++) { vislevel = level; Int_t nnodes = CountNodes(top, level); if (top->IsVisOnly() || top->IsVisBranch()) { @@ -639,7 +666,8 @@ Int_t TGeoPainter::CountVisibleNodes() break; } if (nnodes == fNVisNodes) { - if (again) break; + if (again) + break; again = kTRUE; } fNVisNodes = nnodes; @@ -653,11 +681,14 @@ Int_t TGeoPainter::CountVisibleNodes() void TGeoPainter::CheckEdit() { - if (fIsEditable) return; - if (!TClass::GetClass("TGedEditor")) return; + if (fIsEditable) + return; + if (!TClass::GetClass("TGedEditor")) + return; TPluginHandler *h; if ((h = gROOT->GetPluginManager()->FindHandler("TGeoManagerEditor"))) { - if (h->LoadPlugin() == -1) return; + if (h->LoadPlugin() == -1) + return; h->ExecPlugin(0); } fIsEditable = kTRUE; @@ -668,14 +699,17 @@ void TGeoPainter::CheckEdit() void TGeoPainter::EditGeometry(Option_t *option) { - if (!gPad) return; + if (!gPad) + return; if (!fIsEditable) { - if (!option[0]) gPad->GetCanvas()->GetCanvasImp()->ShowEditor(); - else TVirtualPadEditor::ShowEditor(); + if (!option[0]) + gPad->GetCanvas()->GetCanvasImp()->ShowEditor(); + else + TVirtualPadEditor::ShowEditor(); CheckEdit(); } gPad->SetSelected(fGeoManager); - gPad->GetCanvas()->Selected(gPad,fGeoManager,kButton1Down); + gPad->GetCanvas()->Selected(gPad, fGeoManager, kButton1Down); } //////////////////////////////////////////////////////////////////////////////// @@ -692,31 +726,35 @@ void TGeoPainter::Draw(Option_t *option) void TGeoPainter::DrawBatemanSol(TGeoBatemanSol *sol, Option_t *option) { Int_t ncoeff = sol->GetNcoeff(); - if (!ncoeff) return; - Double_t tlo=0., thi=0.; - Double_t cn=0., lambda=0.; + if (!ncoeff) + return; + Double_t tlo = 0., thi = 0.; + Double_t cn = 0., lambda = 0.; Int_t i; sol->GetRange(tlo, thi); - Bool_t autorange = (thi==0.)?kTRUE:kFALSE; + Bool_t autorange = (thi == 0.) ? kTRUE : kFALSE; // Try to find the optimum range in time. - if (autorange) tlo = 0.; + if (autorange) + tlo = 0.; sol->GetCoeff(0, cn, lambda); Double_t lambdamin = lambda; TString formula = ""; - for (i=0; iGetCoeff(i, cn, lambda); - formula += TString::Format("%g*exp(-%g*x)",cn, lambda); - if (i < ncoeff-1) formula += "+"; - if (lambda < lambdamin && - lambda > 0.) lambdamin = lambda; - } - if (autorange) thi = 10./lambdamin; + formula += TString::Format("%g*exp(-%g*x)", cn, lambda); + if (i < ncoeff - 1) + formula += "+"; + if (lambda < lambdamin && lambda > 0.) + lambdamin = lambda; + } + if (autorange) + thi = 10. / lambdamin; // Create a function - TF1 *func = new TF1(TString::Format("conc%s",sol->GetElement()->GetName()), formula.Data(), tlo,thi); - func->SetTitle(formula + ";time[s]" + TString::Format(";Concentration_of_%s",sol->GetElement()->GetName())); + TF1 *func = new TF1(TString::Format("conc%s", sol->GetElement()->GetName()), formula.Data(), tlo, thi); + func->SetTitle(formula + ";time[s]" + TString::Format(";Concentration_of_%s", sol->GetElement()->GetName())); func->SetMinimum(1.e-3); - func->SetMaximum(1.25*TMath::Max(sol->Concentration(tlo), sol->Concentration(thi))); + func->SetMaximum(1.25 * TMath::Max(sol->Concentration(tlo), sol->Concentration(thi))); func->SetLineColor(sol->GetLineColor()); func->SetLineStyle(sol->GetLineStyle()); func->SetLineWidth(sol->GetLineWidth()); @@ -737,42 +775,43 @@ void TGeoPainter::DrawPolygon(const TGeoPolygon *poly) return; } Int_t nconv = poly->GetNconvex(); - Double_t *x = new Double_t[nvert+1]; - Double_t *y = new Double_t[nvert+1]; - poly->GetVertices(x,y); + Double_t *x = new Double_t[nvert + 1]; + Double_t *y = new Double_t[nvert + 1]; + poly->GetVertices(x, y); x[nvert] = x[0]; y[nvert] = y[0]; - TGraph *g1 = new TGraph(nvert+1, x,y); - g1->SetTitle(Form("Polygon with %d vertices (outscribed %d)",nvert, nconv)); + TGraph *g1 = new TGraph(nvert + 1, x, y); + g1->SetTitle(Form("Polygon with %d vertices (outscribed %d)", nvert, nconv)); g1->SetLineColor(kRed); g1->SetMarkerColor(kRed); g1->SetMarkerStyle(4); g1->SetMarkerSize(0.8); - delete [] x; - delete [] y; + delete[] x; + delete[] y; Double_t *xc = 0; Double_t *yc = 0; TGraph *g2 = 0; if (nconv && !poly->IsConvex()) { - xc = new Double_t[nconv+1]; - yc = new Double_t[nconv+1]; - poly->GetConvexVertices(xc,yc); + xc = new Double_t[nconv + 1]; + yc = new Double_t[nconv + 1]; + poly->GetConvexVertices(xc, yc); xc[nconv] = xc[0]; yc[nconv] = yc[0]; - g2 = new TGraph(nconv+1, xc,yc); + g2 = new TGraph(nconv + 1, xc, yc); g2->SetLineColor(kBlue); g2->SetLineColor(kBlue); g2->SetMarkerColor(kBlue); g2->SetMarkerStyle(21); g2->SetMarkerSize(0.4); - delete [] xc; - delete [] yc; + delete[] xc; + delete[] yc; } if (!gPad) { gROOT->MakeDefCanvas(); } g1->Draw("ALP"); - if (g2) g2->Draw("LP"); + if (g2) + g2->Draw("LP"); } //////////////////////////////////////////////////////////////////////////////// @@ -783,8 +822,8 @@ void TGeoPainter::DrawVolume(TGeoVolume *vol, Option_t *option) fTopVolume = vol; fLastVolume = nullptr; fIsPaintingShape = kFALSE; -// if (fVisOption==kGeoVisOnly || -// fVisOption==kGeoVisBranch) fGeoManager->SetVisOption(kGeoVisLeaves); + // if (fVisOption==kGeoVisOnly || + // fVisOption==kGeoVisBranch) fGeoManager->SetVisOption(kGeoVisLeaves); CountVisibleNodes(); TString opt = option; opt.ToLower(); @@ -795,34 +834,38 @@ void TGeoPainter::DrawVolume(TGeoVolume *vol, Option_t *option) ClearVisibleVolumes(); fVisLock = kFALSE; } - Bool_t has_pad = (gPad==0)?kFALSE:kTRUE; + Bool_t has_pad = (gPad == 0) ? kFALSE : kTRUE; // Clear pad if option "same" not given if (!gPad) { gROOT->MakeDefCanvas(); } - if (!opt.Contains("same")) gPad->Clear(); + if (!opt.Contains("same")) + gPad->Clear(); // append this volume to pad fTopVolume->AppendPad(option); // Create a 3-D view TView *view = gPad->GetView(); if (!view) { - view = TView::CreateView(11,0,0); + view = TView::CreateView(11, 0, 0); // Set the view to perform a first autorange (frame) draw. // TViewer3DPad will revert view to normal painting after this view->SetAutoRange(kTRUE); - if (has_pad) gPad->Update(); + if (has_pad) + gPad->Update(); } - if (!opt.Contains("same")) Paint("range"); - else Paint(opt); + if (!opt.Contains("same")) + Paint("range"); + else + Paint(opt); view->SetAutoRange(kFALSE); // If we are drawing into the pad, then the view needs to be // set to perspective -// if (!view->IsPerspective()) view->SetPerspective(); + // if (!view->IsPerspective()) view->SetPerspective(); fLastVolume = fTopVolume; - // Create a 3D viewer to paint us + // Create a 3D viewer to paint us gPad->GetViewer3D(option); } @@ -837,25 +880,27 @@ void TGeoPainter::DrawShape(TGeoShape *shape, Option_t *option) fOverlap = nullptr; fIsPaintingShape = kTRUE; - Bool_t has_pad = (gPad==0)?kFALSE:kTRUE; + Bool_t has_pad = (gPad == 0) ? kFALSE : kTRUE; // Clear pad if option "same" not given if (!gPad) { gROOT->MakeDefCanvas(); } - if (!opt.Contains("same")) gPad->Clear(); + if (!opt.Contains("same")) + gPad->Clear(); // append this shape to pad shape->AppendPad(option); // Create a 3-D view TView *view = gPad->GetView(); if (!view) { - view = TView::CreateView(11,0,0); + view = TView::CreateView(11, 0, 0); // Set the view to perform a first autorange (frame) draw. // TViewer3DPad will revert view to normal painting after this view->SetAutoRange(kTRUE); - if (has_pad) gPad->Update(); + if (has_pad) + gPad->Update(); } - PaintShape(shape,"range"); + PaintShape(shape, "range"); view->SetAutoRange(kFALSE); view->SetPerspective(); // Create a 3D viewer to paint us @@ -869,8 +914,9 @@ void TGeoPainter::DrawOverlap(void *ovlp, Option_t *option) { TString opt = option; fIsPaintingShape = kFALSE; - TGeoOverlap *overlap = (TGeoOverlap*)ovlp; - if (!overlap) return; + TGeoOverlap *overlap = (TGeoOverlap *)ovlp; + if (!overlap) + return; fPaintingOverlaps = kTRUE; fOverlap = overlap; @@ -879,36 +925,37 @@ void TGeoPainter::DrawOverlap(void *ovlp, Option_t *option) ClearVisibleVolumes(); fVisLock = kFALSE; } - Bool_t has_pad = (gPad==0)?kFALSE:kTRUE; + Bool_t has_pad = (gPad == 0) ? kFALSE : kTRUE; // Clear pad if option "same" not given if (!gPad) { gROOT->MakeDefCanvas(); } - if (!opt.Contains("same")) gPad->Clear(); + if (!opt.Contains("same")) + gPad->Clear(); // append this volume to pad overlap->AppendPad(option); // Create a 3-D view - // Create a 3D viewer to paint us + // Create a 3D viewer to paint us gPad->GetViewer3D(option); TView *view = gPad->GetView(); if (!view) { - view = TView::CreateView(11,0,0); + view = TView::CreateView(11, 0, 0); // Set the view to perform a first autorange (frame) draw. // TViewer3DPad will revert view to normal painting after this view->SetAutoRange(kTRUE); PaintOverlap(ovlp, "range"); overlap->GetPolyMarker()->Draw("SAME"); - if (has_pad) gPad->Update(); + if (has_pad) + gPad->Update(); } // If we are drawing into the pad, then the view needs to be // set to perspective -// if (!view->IsPerspective()) view->SetPerspective(); + // if (!view->IsPerspective()) view->SetPerspective(); fVisLock = kTRUE; } - //////////////////////////////////////////////////////////////////////////////// /// Draw only one volume. @@ -922,12 +969,13 @@ void TGeoPainter::DrawOnly(Option_t *option) } fPaintingOverlaps = kFALSE; fIsPaintingShape = kFALSE; - Bool_t has_pad = (gPad==0)?kFALSE:kTRUE; + Bool_t has_pad = (gPad == 0) ? kFALSE : kTRUE; // Clear pad if option "same" not given if (!gPad) { gROOT->MakeDefCanvas(); } - if (!opt.Contains("same")) gPad->Clear(); + if (!opt.Contains("same")) + gPad->Clear(); // append this volume to pad fTopVolume = fGeoManager->GetCurrentVolume(); fTopVolume->AppendPad(option); @@ -935,17 +983,18 @@ void TGeoPainter::DrawOnly(Option_t *option) // Create a 3-D view TView *view = gPad->GetView(); if (!view) { - view = TView::CreateView(11,0,0); + view = TView::CreateView(11, 0, 0); // Set the view to perform a first autorange (frame) draw. // TViewer3DPad will revert view to normal painting after this view->SetAutoRange(kTRUE); fVisOption = kGeoVisOnly; - if (has_pad) gPad->Update(); + if (has_pad) + gPad->Update(); } // If we are drawing into the pad, then the view needs to be // set to perspective -// if (!view->IsPerspective()) view->SetPerspective(); + // if (!view->IsPerspective()) view->SetPerspective(); fVisLock = kTRUE; } @@ -954,8 +1003,10 @@ void TGeoPainter::DrawOnly(Option_t *option) void TGeoPainter::DrawCurrentPoint(Int_t color) { - if (!gPad) return; - if (!gPad->GetView()) return; + if (!gPad) + return; + if (!gPad->GetView()) + return; TPolyMarker3D *pm = new TPolyMarker3D(); pm->SetMarkerColor(color); const Double_t *point = fGeoManager->GetCurrentPoint(); @@ -967,21 +1018,19 @@ void TGeoPainter::DrawCurrentPoint(Int_t color) //////////////////////////////////////////////////////////////////////////////// -void TGeoPainter::DrawPanel() -{ -} +void TGeoPainter::DrawPanel() {} //////////////////////////////////////////////////////////////////////////////// /// Draw all volumes for a given path. void TGeoPainter::DrawPath(const char *path, Option_t *option) { - fVisOption=kGeoVisBranch; - fVisBranch=path; + fVisOption = kGeoVisBranch; + fVisBranch = path; fIsPaintingShape = kFALSE; fTopVolume = fGeoManager->GetTopVolume(); fTopVolume->SetVisRaytrace(kFALSE); - DrawVolume(fTopVolume,option); + DrawVolume(fTopVolume, option); } //////////////////////////////////////////////////////////////////////////////// @@ -989,27 +1038,32 @@ void TGeoPainter::DrawPath(const char *path, Option_t *option) void TGeoPainter::EstimateCameraMove(Double_t tmin, Double_t tmax, Double_t *start, Double_t *end) { - if (!gPad) return; + if (!gPad) + return; TIter next(gPad->GetListOfPrimitives()); TVirtualGeoTrack *track; TObject *obj; Int_t ntracks = 0; Double_t *point = 0; AddTrackPoint(point, start, kTRUE); - while ((obj=next())) { - if (strcmp(obj->ClassName(), "TGeoTrack")) continue; - track = (TVirtualGeoTrack*)obj; + while ((obj = next())) { + if (strcmp(obj->ClassName(), "TGeoTrack")) + continue; + track = (TVirtualGeoTrack *)obj; ntracks++; track->PaintCollect(tmin, start); } - if (!ntracks) return; + if (!ntracks) + return; next.Reset(); AddTrackPoint(point, end, kTRUE); - while ((obj=next())) { - if (strcmp(obj->ClassName(), "TGeoTrack")) continue; - track = (TVirtualGeoTrack*)obj; - if (!track) continue; + while ((obj = next())) { + if (strcmp(obj->ClassName(), "TGeoTrack")) + continue; + track = (TVirtualGeoTrack *)obj; + if (!track) + continue; track->PaintCollect(tmax, end); } } @@ -1019,11 +1073,13 @@ void TGeoPainter::EstimateCameraMove(Double_t tmin, Double_t tmax, Double_t *sta void TGeoPainter::ExecuteManagerEvent(TGeoManager * /*geom*/, Int_t event, Int_t /*px*/, Int_t /*py*/) { - if (!gPad) return; + if (!gPad) + return; gPad->SetCursor(kPointer); switch (event) { - case kButton1Down: - if (!fIsEditable) CheckEdit(); + case kButton1Down: + if (!fIsEditable) + CheckEdit(); } } @@ -1032,11 +1088,13 @@ void TGeoPainter::ExecuteManagerEvent(TGeoManager * /*geom*/, Int_t event, Int_t void TGeoPainter::ExecuteShapeEvent(TGeoShape * /*shape*/, Int_t event, Int_t /*px*/, Int_t /*py*/) { - if (!gPad) return; + if (!gPad) + return; gPad->SetCursor(kHand); switch (event) { - case kButton1Down: - if (!fIsEditable) CheckEdit(); + case kButton1Down: + if (!fIsEditable) + CheckEdit(); } } @@ -1045,37 +1103,39 @@ void TGeoPainter::ExecuteShapeEvent(TGeoShape * /*shape*/, Int_t event, Int_t /* void TGeoPainter::ExecuteVolumeEvent(TGeoVolume * /*volume*/, Int_t event, Int_t /*px*/, Int_t /*py*/) { - if (!gPad) return; - if (!fIsEditable) CheckEdit(); -// if (fIsRaytracing) return; -// Bool_t istop = (volume==fTopVolume)?kTRUE:kFALSE; -// if (istop) gPad->SetCursor(kHand); -// else gPad->SetCursor(kPointer); + if (!gPad) + return; + if (!fIsEditable) + CheckEdit(); + // if (fIsRaytracing) return; + // Bool_t istop = (volume==fTopVolume)?kTRUE:kFALSE; + // if (istop) gPad->SetCursor(kHand); + // else gPad->SetCursor(kPointer); gPad->SetCursor(kHand); -// static Int_t width, color; + // static Int_t width, color; switch (event) { case kMouseEnter: -// width = volume->GetLineWidth(); -// color = volume->GetLineColor(); + // width = volume->GetLineWidth(); + // color = volume->GetLineColor(); break; case kMouseLeave: -// volume->SetLineWidth(width); -// volume->SetLineColor(color); + // volume->SetLineWidth(width); + // volume->SetLineColor(color); break; case kButton1Down: -// volume->SetLineWidth(3); -// volume->SetLineColor(2); -// gPad->Modified(); -// gPad->Update(); + // volume->SetLineWidth(3); + // volume->SetLineColor(2); + // gPad->Modified(); + // gPad->Update(); break; case kButton1Up: -// volume->SetLineWidth(width); -// volume->SetLineColor(color); -// gPad->Modified(); -// gPad->Update(); + // volume->SetLineWidth(width); + // volume->SetLineColor(color); + // gPad->Modified(); + // gPad->Update(); break; case kButton1Double: @@ -1092,21 +1152,26 @@ const char *TGeoPainter::GetVolumeInfo(const TGeoVolume *volume, Int_t /*px*/, I { static TString info; info = ""; - if (!gPad) return info; + if (!gPad) + return info; if (fPaintingOverlaps) { if (!fOverlap) { - info = "wrong overlapping flag"; + info = "wrong overlapping flag"; return info; } TString ovtype, name; - if (fOverlap->IsExtrusion()) ovtype="EXTRUSION"; - else ovtype = "OVERLAP"; - if (volume==fOverlap->GetFirstVolume()) name=volume->GetName(); - else name=fOverlap->GetSecondVolume()->GetName(); + if (fOverlap->IsExtrusion()) + ovtype = "EXTRUSION"; + else + ovtype = "OVERLAP"; + if (volume == fOverlap->GetFirstVolume()) + name = volume->GetName(); + else + name = fOverlap->GetSecondVolume()->GetName(); info = TString::Format("%s: %s of %g", name.Data(), ovtype.Data(), fOverlap->GetOverlap()); return info; - } - else info = TString::Format("%s, shape=%s", fVolInfo.Data(), volume->GetShape()->ClassName()); + } else + info = TString::Format("%s, shape=%s", fVolInfo.Data(), volume->GetShape()->ClassName()); return info; } @@ -1115,7 +1180,8 @@ const char *TGeoPainter::GetVolumeInfo(const TGeoVolume *volume, Int_t /*px*/, I TGeoChecker *TGeoPainter::GetChecker() { - if (!fChecker) fChecker = new TGeoChecker(fGeoManager); + if (!fChecker) + fChecker = new TGeoChecker(fGeoManager); return fChecker; } @@ -1124,9 +1190,11 @@ TGeoChecker *TGeoPainter::GetChecker() void TGeoPainter::GetViewAngles(Double_t &longitude, Double_t &latitude, Double_t &psi) { - if (!gPad) return; + if (!gPad) + return; TView *view = gPad->GetView(); - if (!view) return; + if (!view) + return; longitude = view->GetLongitude(); latitude = view->GetLatitude(); psi = view->GetPsi(); @@ -1137,13 +1205,15 @@ void TGeoPainter::GetViewAngles(Double_t &longitude, Double_t &latitude, Double_ void TGeoPainter::GrabFocus(Int_t nfr, Double_t dlong, Double_t dlat, Double_t dpsi) { - if (!gPad) return; + if (!gPad) + return; TView *view = gPad->GetView(); - if (!view) return; + if (!view) + return; if (!fCheckedNode && !fPaintingOverlaps) { printf("Woops!!!\n"); - TGeoBBox *box = (TGeoBBox*)fGeoManager->GetTopVolume()->GetShape(); - memcpy(&fCheckedBox[0], box->GetOrigin(), 3*sizeof(Double_t)); + TGeoBBox *box = (TGeoBBox *)fGeoManager->GetTopVolume()->GetShape(); + memcpy(&fCheckedBox[0], box->GetOrigin(), 3 * sizeof(Double_t)); fCheckedBox[3] = box->GetDX(); fCheckedBox[4] = box->GetDY(); fCheckedBox[5] = box->GetDZ(); @@ -1151,12 +1221,16 @@ void TGeoPainter::GrabFocus(Int_t nfr, Double_t dlong, Double_t dlat, Double_t d view->SetPerspective(); Int_t nvols = fVisVolumes->GetEntriesFast(); Int_t nframes = nfr; - if (nfr==0) { + if (nfr == 0) { nframes = 1; - if (nvols<1500) nframes=10; - if (nvols<1000) nframes=20; - if (nvols<200) nframes = 50; - if (nvols<100) nframes = 100; + if (nvols < 1500) + nframes = 10; + if (nvols < 1000) + nframes = 20; + if (nvols < 200) + nframes = 50; + if (nvols < 100) + nframes = 100; } view->MoveFocus(&fCheckedBox[0], fCheckedBox[3], fCheckedBox[4], fCheckedBox[5], nframes, dlong, dlat, dpsi); } @@ -1164,9 +1238,8 @@ void TGeoPainter::GrabFocus(Int_t nfr, Double_t dlong, Double_t dlat, Double_t d //////////////////////////////////////////////////////////////////////////////// /// Generate a lego plot fot the top volume, according to option. -TH2F *TGeoPainter::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, - Int_t nphi, Double_t phimin, Double_t phimax, - Double_t rmin, Double_t rmax, Option_t *option) +TH2F *TGeoPainter::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, Int_t nphi, Double_t phimin, + Double_t phimax, Double_t rmin, Double_t rmax, Option_t *option) { return fChecker->LegoPlot(ntheta, themin, themax, nphi, phimin, phimax, rmin, rmax, option); } @@ -1175,8 +1248,8 @@ TH2F *TGeoPainter::LegoPlot(Int_t ntheta, Double_t themin, Double_t themax, void TGeoPainter::LocalToMasterVect(const Double_t *local, Double_t *master) const { - for (Int_t i=0; i<3; i++) - master[i] = -local[0]*fMat[i]-local[1]*fMat[i+3]-local[2]*fMat[i+6]; + for (Int_t i = 0; i < 3; i++) + master[i] = -local[0] * fMat[i] - local[1] * fMat[i + 3] - local[2] * fMat[i + 6]; } //////////////////////////////////////////////////////////////////////////////// @@ -1184,16 +1257,19 @@ void TGeoPainter::LocalToMasterVect(const Double_t *local, Double_t *master) con void TGeoPainter::ModifiedPad(Bool_t update) const { - if (!gPad) return; + if (!gPad) + return; if (update) { gPad->Update(); return; } TView *view = gPad->GetView(); - if (!view) return; + if (!view) + return; view->SetViewChanged(); gPad->Modified(); - if (gROOT->FromPopUp()) gPad->Update(); + if (gROOT->FromPopUp()) + gPad->Update(); } //////////////////////////////////////////////////////////////////////////////// @@ -1201,16 +1277,21 @@ void TGeoPainter::ModifiedPad(Bool_t update) const void TGeoPainter::Paint(Option_t *option) { - if (!fGeoManager || !fTopVolume) return; + if (!fGeoManager || !fTopVolume) + return; Bool_t is_padviewer = kTRUE; - if (gPad) is_padviewer = (!strcmp(gPad->GetViewer3D()->ClassName(),"TViewer3DPad"))?kTRUE:kFALSE; + if (gPad) + is_padviewer = (!strcmp(gPad->GetViewer3D()->ClassName(), "TViewer3DPad")) ? kTRUE : kFALSE; fIsRaytracing = fTopVolume->IsRaytracing(); - if (fTopVolume->IsVisContainers()) fVisOption = kGeoVisDefault; - else if (fTopVolume->IsVisLeaves()) fVisOption = kGeoVisLeaves; - else if (fTopVolume->IsVisOnly()) fVisOption = kGeoVisOnly; - else if (fTopVolume->IsVisBranch()) fVisOption = kGeoVisBranch; - + if (fTopVolume->IsVisContainers()) + fVisOption = kGeoVisDefault; + else if (fTopVolume->IsVisLeaves()) + fVisOption = kGeoVisLeaves; + else if (fTopVolume->IsVisOnly()) + fVisOption = kGeoVisOnly; + else if (fTopVolume->IsVisBranch()) + fVisOption = kGeoVisBranch; if (!fIsRaytracing || !is_padviewer) { if (fGeoManager->IsDrawingExtra()) { @@ -1220,17 +1301,18 @@ void TGeoPainter::Paint(Option_t *option) Int_t nnodes = nodeList->GetEntriesFast(); Int_t inode; TGeoPhysicalNode *node; - for (inode=0; inodeUncheckedAt(inode); + for (inode = 0; inode < nnodes; inode++) { + node = (TGeoPhysicalNode *)nodeList->UncheckedAt(inode); PaintPhysicalNode(node, option); } } else { - PaintVolume(fTopVolume,option); + PaintVolume(fTopVolume, option); } fVisLock = kTRUE; } // Check if we have to raytrace (only in pad) - if (fIsRaytracing && is_padviewer) Raytrace(); + if (fIsRaytracing && is_padviewer) + Raytrace(); } //////////////////////////////////////////////////////////////////////////////// @@ -1238,11 +1320,14 @@ void TGeoPainter::Paint(Option_t *option) void TGeoPainter::PaintOverlap(void *ovlp, Option_t *option) { - if (!fGeoManager) return; + if (!fGeoManager) + return; TGeoOverlap *overlap = (TGeoOverlap *)ovlp; - if (!overlap) return; + if (!overlap) + return; Int_t color, transparency; - if (fOverlap != overlap) fOverlap = overlap; + if (fOverlap != overlap) + fOverlap = overlap; TGeoShape::SetTransform(fGlobal); TGeoHMatrix *hmat = fGlobal; TGeoVolume *vol; @@ -1254,27 +1339,31 @@ void TGeoPainter::PaintOverlap(void *ovlp, Option_t *option) vol = vol1; *hmat = matrix1; fGeoManager->SetMatrixReflection(matrix1->IsReflection()); - if (!fVisLock) fVisVolumes->Add(vol); + if (!fVisLock) + fVisVolumes->Add(vol); fGeoManager->SetPaintVolume(vol); color = vol->GetLineColor(); transparency = vol->GetTransparency(); vol->SetLineColor(kGreen); vol->SetTransparency(40); - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); - PaintShape(*(vol->GetShape()),option); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); + PaintShape(*(vol->GetShape()), option); vol->SetLineColor(color); vol->SetTransparency(transparency); vol = vol2; *hmat = matrix2; fGeoManager->SetMatrixReflection(matrix2->IsReflection()); - if (!fVisLock) fVisVolumes->Add(vol); + if (!fVisLock) + fVisVolumes->Add(vol); fGeoManager->SetPaintVolume(vol); color = vol->GetLineColor(); transparency = vol->GetTransparency(); vol->SetLineColor(kBlue); vol->SetTransparency(40); - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); - PaintShape(*(vol->GetShape()),option); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); + PaintShape(*(vol->GetShape()), option); vol->SetLineColor(color); vol->SetTransparency(transparency); fGeoManager->SetMatrixReflection(kFALSE); @@ -1284,7 +1373,7 @@ void TGeoPainter::PaintOverlap(void *ovlp, Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Paint recursively a node and its content according to visualization options. -void TGeoPainter::PaintNode(TGeoNode *node, Option_t *option, TGeoMatrix* global) +void TGeoPainter::PaintNode(TGeoNode *node, Option_t *option, TGeoMatrix *global) { PaintVolume(node->GetVolume(), option, global); } @@ -1292,16 +1381,17 @@ void TGeoPainter::PaintNode(TGeoNode *node, Option_t *option, TGeoMatrix* global //////////////////////////////////////////////////////////////////////////////// /// Paint recursively a node and its content according to visualization options. -void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* global) +void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix *global) { if (fTopVolume != top) { ClearVisibleVolumes(); fVisLock = kFALSE; } fTopVolume = top; - if (!fVisLevel) return; + if (!fVisLevel) + return; TGeoVolume *vol = top; - if(global) + if (global) *fGlobal = *global; else fGlobal->Clear(); @@ -1311,33 +1401,35 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo Int_t transparency = 0; // Update pad attributes in case we need to paint VOL - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); // Do we need to draw a branch ? if (top->IsVisBranch()) { fGeoManager->PushPath(); fGeoManager->cd(fVisBranch.Data()); -// while (fGeoManager->GetLevel()) { - vol = fGeoManager->GetCurrentVolume(); - if (!fVisLock) { - fVisVolumes->Add(vol); - vol->SetAttBit(TGeoAtt::kVisOnScreen); - } - fGeoManager->SetPaintVolume(vol); - transparency = vol->GetTransparency(); - vol->SetTransparency(40); - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); - if (global) { - *fGlobal = *global; - *fGlobal *= *fGeoManager->GetCurrentMatrix(); - } else { - *fGlobal = fGeoManager->GetCurrentMatrix(); - } - fGeoManager->SetMatrixReflection(fGlobal->IsReflection()); - PaintShape(*(vol->GetShape()),option); - vol->SetTransparency(transparency); - fGeoManager->CdUp(); -// } + // while (fGeoManager->GetLevel()) { + vol = fGeoManager->GetCurrentVolume(); + if (!fVisLock) { + fVisVolumes->Add(vol); + vol->SetAttBit(TGeoAtt::kVisOnScreen); + } + fGeoManager->SetPaintVolume(vol); + transparency = vol->GetTransparency(); + vol->SetTransparency(40); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); + if (global) { + *fGlobal = *global; + *fGlobal *= *fGeoManager->GetCurrentMatrix(); + } else { + *fGlobal = fGeoManager->GetCurrentMatrix(); + } + fGeoManager->SetMatrixReflection(fGlobal->IsReflection()); + PaintShape(*(vol->GetShape()), option); + vol->SetTransparency(transparency); + fGeoManager->CdUp(); + // } fVisLock = kTRUE; fGeoManager->PopPath(); fGeoManager->SetMatrixReflection(kFALSE); @@ -1348,7 +1440,7 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo if ((fTopVisible && vis) || !top->GetNdaughters() || !top->IsVisDaughters() || top->IsVisOnly()) { fGeoManager->SetPaintVolume(vol); fGeoManager->SetMatrixReflection(fGlobal->IsReflection()); - PaintShape(*(vol->GetShape()),option); + PaintShape(*(vol->GetShape()), option); if (!fVisLock && !vol->TestAttBit(TGeoAtt::kVisOnScreen)) { fVisVolumes->Add(vol); vol->SetAttBit(TGeoAtt::kVisOnScreen); @@ -1361,13 +1453,14 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo // Iterate the volume content TGeoIterator next(vol); - if (fPlugin) next.SetUserPlugin(fPlugin); + if (fPlugin) + next.SetUserPlugin(fPlugin); TGeoNode *daughter; -// TGeoMatrix *glmat; + // TGeoMatrix *glmat; Int_t level, nd; Bool_t last; - Int_t line_color=0, line_width=0, line_style=0; - while ((daughter=next())) { + Int_t line_color = 0, line_width = 0, line_style = 0; + while ((daughter = next())) { vol = daughter->GetVolume(); fGeoManager->SetPaintVolume(vol); level = next.GetLevel(); @@ -1375,7 +1468,7 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo vis = daughter->IsVisible(); drawDaughters = kTRUE; if (top->IsVisContainers()) { - if (vis && level<=fVisLevel) { + if (vis && level <= fVisLevel) { if (fPlugin) { line_color = vol->GetLineColor(); line_width = vol->GetLineWidth(); @@ -1383,15 +1476,16 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo transparency = vol->GetTransparency(); fPlugin->ProcessNode(); } - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); if (global) { - *fGlobal = *global; + *fGlobal = *global; *fGlobal *= *next.GetCurrentMatrix(); } else { *fGlobal = next.GetCurrentMatrix(); } fGeoManager->SetMatrixReflection(fGlobal->IsReflection()); - drawDaughters = PaintShape(*(vol->GetShape()),option); + drawDaughters = PaintShape(*(vol->GetShape()), option); if (fPlugin) { vol->SetLineColor(line_color); vol->SetLineWidth(line_width); @@ -1404,12 +1498,12 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo } } // Check if we have to skip this branch - if (!drawDaughters || level==fVisLevel || !daughter->IsVisDaughters()) { + if (!drawDaughters || level == fVisLevel || !daughter->IsVisDaughters()) { next.Skip(); continue; } } else if (top->IsVisLeaves()) { - last = ((nd==0) || (level==fVisLevel) || (!daughter->IsVisDaughters()))?kTRUE:kFALSE; + last = ((nd == 0) || (level == fVisLevel) || (!daughter->IsVisDaughters())) ? kTRUE : kFALSE; if (vis && last) { if (fPlugin) { line_color = vol->GetLineColor(); @@ -1418,15 +1512,16 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo transparency = vol->GetTransparency(); fPlugin->ProcessNode(); } - if (!strstr(option,"range")) ((TAttLine*)vol)->Modify(); + if (!strstr(option, "range")) + ((TAttLine *)vol)->Modify(); if (global) { - *fGlobal = *global; + *fGlobal = *global; *fGlobal *= *next.GetCurrentMatrix(); } else { *fGlobal = next.GetCurrentMatrix(); } fGeoManager->SetMatrixReflection(fGlobal->IsReflection()); - drawDaughters = PaintShape(*(vol->GetShape()),option); + drawDaughters = PaintShape(*(vol->GetShape()), option); if (fPlugin) { vol->SetLineColor(line_color); vol->SetLineWidth(line_width); @@ -1439,10 +1534,12 @@ void TGeoPainter::PaintVolume(TGeoVolume *top, Option_t *option, TGeoMatrix* glo } } // Check if we have to skip the branch - if (!drawDaughters || last || !daughter->IsVisDaughters()) next.Skip(); + if (!drawDaughters || last || !daughter->IsVisDaughters()) + next.Skip(); } } - if (fPlugin) fPlugin->SetIterator(0); + if (fPlugin) + fPlugin->SetIterator(0); fGeoManager->SetMatrixReflection(kFALSE); fVisLock = kTRUE; } @@ -1456,7 +1553,7 @@ Bool_t TGeoPainter::PaintShape(const TGeoShape &shape, Option_t *option) const TVirtualViewer3D *viewer = gPad->GetViewer3D(); - if (!viewer || shape.IsA()==TGeoShapeAssembly::Class()) { + if (!viewer || shape.IsA() == TGeoShapeAssembly::Class()) { return addDaughters; } @@ -1467,8 +1564,8 @@ Bool_t TGeoPainter::PaintShape(const TGeoShape &shape, Option_t *option) const Bool_t localFrame = viewer->PreferLocalFrame(); // Perform first fetch of buffer from the shape and try adding it // to the viewer - const TBuffer3D & buffer = - shape.GetBuffer3D(TBuffer3D::kCore|TBuffer3D::kBoundingBox|TBuffer3D::kShapeSpecific, localFrame); + const TBuffer3D &buffer = + shape.GetBuffer3D(TBuffer3D::kCore | TBuffer3D::kBoundingBox | TBuffer3D::kShapeSpecific, localFrame); Int_t reqSections = viewer->AddObject(buffer, &addDaughters); // If the viewer requires additional sections fetch from the shape (if possible) @@ -1483,12 +1580,12 @@ Bool_t TGeoPainter::PaintShape(const TGeoShape &shape, Option_t *option) const // single buffer to here. So as a special case the TGeoCompositeShape // performs it's own painting & negotiation with the viewer. else { - const TGeoCompositeShape * composite = static_cast(&shape); + const TGeoCompositeShape *composite = static_cast(&shape); // We need the addDaughters flag returned from the viewer from paint // so can't use the normal TObject::Paint() -// TGeoHMatrix *matrix = (TGeoHMatrix*)TGeoShape::GetTransform(); -// if (viewer->PreferLocalFrame()) matrix->Clear(); + // TGeoHMatrix *matrix = (TGeoHMatrix*)TGeoShape::GetTransform(); + // if (viewer->PreferLocalFrame()) matrix->Clear(); addDaughters = composite->PaintComposite(option); } @@ -1503,7 +1600,7 @@ void TGeoPainter::PaintShape(TGeoShape *shape, Option_t *option) TGeoShape::SetTransform(fGlobal); fGlobal->Clear(); fGeoManager->SetPaintVolume(0); - PaintShape(*shape,option); + PaintShape(*shape, option); } //////////////////////////////////////////////////////////////////////////////// @@ -1511,7 +1608,8 @@ void TGeoPainter::PaintShape(TGeoShape *shape, Option_t *option) void TGeoPainter::PaintPhysicalNode(TGeoPhysicalNode *node, Option_t *option) { - if (!node->IsVisible()) return; + if (!node->IsVisible()) + return; Int_t level = node->GetLevel(); Int_t i, col, wid, sty; TGeoShape *shape; @@ -1520,50 +1618,52 @@ void TGeoPainter::PaintPhysicalNode(TGeoPhysicalNode *node, Option_t *option) TGeoVolume *vcrt; if (!node->IsVisibleFull()) { // Paint only last node in the branch - vcrt = node->GetVolume(); - if (!strstr(option,"range")) ((TAttLine*)vcrt)->Modify(); + vcrt = node->GetVolume(); + if (!strstr(option, "range")) + ((TAttLine *)vcrt)->Modify(); shape = vcrt->GetShape(); *matrix = node->GetMatrix(); fGeoManager->SetMatrixReflection(matrix->IsReflection()); fGeoManager->SetPaintVolume(vcrt); - if (!node->IsVolAttributes() && !strstr(option,"range")) { + if (!node->IsVolAttributes() && !strstr(option, "range")) { col = vcrt->GetLineColor(); wid = vcrt->GetLineWidth(); sty = vcrt->GetLineStyle(); vcrt->SetLineColor(node->GetLineColor()); vcrt->SetLineWidth(node->GetLineWidth()); vcrt->SetLineStyle(node->GetLineStyle()); - ((TAttLine*)vcrt)->Modify(); - PaintShape(*shape,option); + ((TAttLine *)vcrt)->Modify(); + PaintShape(*shape, option); vcrt->SetLineColor(col); vcrt->SetLineWidth(wid); vcrt->SetLineStyle(sty); } else { - PaintShape(*shape,option); + PaintShape(*shape, option); } } else { // Paint full branch, except top node - for (i=1;i<=level; i++) { - vcrt = node->GetVolume(i); - if (!strstr(option,"range")) ((TAttLine*)vcrt)->Modify(); + for (i = 1; i <= level; i++) { + vcrt = node->GetVolume(i); + if (!strstr(option, "range")) + ((TAttLine *)vcrt)->Modify(); shape = vcrt->GetShape(); *matrix = node->GetMatrix(i); fGeoManager->SetMatrixReflection(matrix->IsReflection()); fGeoManager->SetPaintVolume(vcrt); - if (!node->IsVolAttributes() && !strstr(option,"range")) { + if (!node->IsVolAttributes() && !strstr(option, "range")) { col = vcrt->GetLineColor(); wid = vcrt->GetLineWidth(); sty = vcrt->GetLineStyle(); vcrt->SetLineColor(node->GetLineColor()); vcrt->SetLineWidth(node->GetLineWidth()); vcrt->SetLineStyle(node->GetLineStyle()); - ((TAttLine*)vcrt)->Modify(); - PaintShape(*shape,option); + ((TAttLine *)vcrt)->Modify(); + PaintShape(*shape, option); vcrt->SetLineColor(col); vcrt->SetLineWidth(wid); vcrt->SetLineStyle(sty); } else { - PaintShape(*shape,option); + PaintShape(*shape, option); } } } @@ -1581,9 +1681,10 @@ void TGeoPainter::PrintOverlaps() const //////////////////////////////////////////////////////////////////////////////// /// Text progress bar. -void TGeoPainter::OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch, Bool_t last, Bool_t refresh, const char *msg) +void TGeoPainter::OpProgress(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch, Bool_t last, + Bool_t refresh, const char *msg) { - fChecker->OpProgress(opname,current,size,watch,last,refresh, msg); + fChecker->OpProgress(opname, current, size, watch, last, refresh, msg); } //////////////////////////////////////////////////////////////////////////////// @@ -1591,13 +1692,14 @@ void TGeoPainter::OpProgress(const char *opname, Long64_t current, Long64_t size void TGeoPainter::RandomPoints(const TGeoVolume *vol, Int_t npoints, Option_t *option) { - fChecker->RandomPoints((TGeoVolume*)vol, npoints, option); + fChecker->RandomPoints((TGeoVolume *)vol, npoints, option); } //////////////////////////////////////////////////////////////////////////////// /// Shoot nrays in the current drawn geometry -void TGeoPainter::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, Bool_t check_norm) +void TGeoPainter::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Double_t startz, const char *target_vol, + Bool_t check_norm) { fChecker->RandomRays(nrays, startx, starty, startz, target_vol, check_norm); } @@ -1607,125 +1709,134 @@ void TGeoPainter::RandomRays(Int_t nrays, Double_t startx, Double_t starty, Doub void TGeoPainter::Raytrace(Option_t *) { - if (!gPad || gPad->IsBatch()) return; + if (!gPad || gPad->IsBatch()) + return; TView *view = gPad->GetView(); - if (!view) return; + if (!view) + return; Int_t rtMode = fGeoManager->GetRTmode(); TGeoVolume *top = fGeoManager->GetTopVolume(); - if (top != fTopVolume) fGeoManager->SetTopVolume(fTopVolume); - if (!view->IsPerspective()) view->SetPerspective(); + if (top != fTopVolume) + fGeoManager->SetTopVolume(fTopVolume); + if (!view->IsPerspective()) + view->SetPerspective(); gVirtualX->SetMarkerSize(1); gVirtualX->SetMarkerStyle(1); - Bool_t inclipst=kFALSE; + Bool_t inclipst = kFALSE; Double_t krad = TMath::DegToRad(); Double_t lat = view->GetLatitude(); Double_t longit = view->GetLongitude(); Double_t psi = view->GetPsi(); - Double_t c1 = TMath::Cos(psi*krad); - Double_t s1 = TMath::Sin(psi*krad); - Double_t c2 = TMath::Cos(lat*krad); - Double_t s2 = TMath::Sin(lat*krad); - Double_t s3 = TMath::Cos(longit*krad); - Double_t c3 = -TMath::Sin(longit*krad); - fMat[0] = c1*c3 - s1*c2*s3; - fMat[1] = c1*s3 + s1*c2*c3; - fMat[2] = s1*s2; - - fMat[3] = -s1*c3 - c1*c2*s3; - fMat[4] = -s1*s3 + c1*c2*c3; - fMat[5] = c1*s2; - - fMat[6] = s2*s3; - fMat[7] = -s2*c3; + Double_t c1 = TMath::Cos(psi * krad); + Double_t s1 = TMath::Sin(psi * krad); + Double_t c2 = TMath::Cos(lat * krad); + Double_t s2 = TMath::Sin(lat * krad); + Double_t s3 = TMath::Cos(longit * krad); + Double_t c3 = -TMath::Sin(longit * krad); + fMat[0] = c1 * c3 - s1 * c2 * s3; + fMat[1] = c1 * s3 + s1 * c2 * c3; + fMat[2] = s1 * s2; + + fMat[3] = -s1 * c3 - c1 * c2 * s3; + fMat[4] = -s1 * s3 + c1 * c2 * c3; + fMat[5] = c1 * s2; + + fMat[6] = s2 * s3; + fMat[7] = -s2 * c3; fMat[8] = c2; Double_t u0, v0, du, dv; - view->GetWindow(u0,v0,du,dv); + view->GetWindow(u0, v0, du, dv); Double_t dview = view->GetDview(); Double_t dproj = view->GetDproj(); - Double_t local[3] = {0,0,1}; + Double_t local[3] = {0, 0, 1}; Double_t dir[3], normal[3]; - LocalToMasterVect(local,dir); + LocalToMasterVect(local, dir); Double_t min[3], max[3]; view->GetRange(min, max); Double_t cov[3]; - for (Int_t i=0; i<3; i++) cov[i] = 0.5*(min[i]+max[i]); + for (Int_t i = 0; i < 3; i++) + cov[i] = 0.5 * (min[i] + max[i]); Double_t cop[3]; - for (Int_t i=0; i<3; i++) cop[i] = cov[i] - dir[i]*dview; + for (Int_t i = 0; i < 3; i++) + cop[i] = cov[i] - dir[i] * dview; fGeoManager->InitTrack(cop, dir); Bool_t outside = fGeoManager->IsOutside(); fGeoManager->DoBackupState(); - if (fClippingShape) inclipst = fClippingShape->Contains(cop); + if (fClippingShape) + inclipst = fClippingShape->Contains(cop); Int_t px, py; Double_t xloc, yloc, modloc; - Int_t pxmin,pxmax, pymin,pymax; + Int_t pxmin, pxmax, pymin, pymax; pxmin = gPad->UtoAbsPixel(0); pxmax = gPad->UtoAbsPixel(1); pymin = gPad->VtoAbsPixel(1); pymax = gPad->VtoAbsPixel(0); TGeoNode *next = nullptr; TGeoNode *nextnode = nullptr; - Double_t step,steptot; + Double_t step, steptot; Double_t *norm; const Double_t *point = fGeoManager->GetCurrentPoint(); - Double_t *ppoint = (Double_t*)point; + Double_t *ppoint = (Double_t *)point; Double_t tosource[3]; Double_t calf; - Double_t phi = 45.*krad; - tosource[0] = -dir[0]*TMath::Cos(phi)+dir[1]*TMath::Sin(phi); - tosource[1] = -dir[0]*TMath::Sin(phi)-dir[1]*TMath::Cos(phi); + Double_t phi = 45. * krad; + tosource[0] = -dir[0] * TMath::Cos(phi) + dir[1] * TMath::Sin(phi); + tosource[1] = -dir[0] * TMath::Sin(phi) - dir[1] * TMath::Cos(phi); tosource[2] = -dir[2]; Bool_t done; -// Int_t istep; + // Int_t istep; Int_t base_color, color; Double_t light; - Double_t stemin=0, stemax=TGeoShape::Big(); + Double_t stemin = 0, stemax = TGeoShape::Big(); TPoint *pxy = new TPoint[1]; TGeoVolume *nextvol; Int_t up; - Int_t ntotal = pxmax*pymax; + Int_t ntotal = pxmax * pymax; Int_t nrays = 0; TStopwatch *timer = new TStopwatch(); timer->Start(); - for (px=pxmin; pxAbsPixeltoX(pxmin+pxmax-px); - xloc = xloc*du-u0; - yloc = gPad->AbsPixeltoY(pymin+pymax-py); - yloc = yloc*dv-v0; - modloc = TMath::Sqrt(xloc*xloc+yloc*yloc+dproj*dproj); - local[0] = xloc/modloc; - local[1] = yloc/modloc; - local[2] = dproj/modloc; - LocalToMasterVect(local,dir); + xloc = gPad->AbsPixeltoX(pxmin + pxmax - px); + xloc = xloc * du - u0; + yloc = gPad->AbsPixeltoY(pymin + pymax - py); + yloc = yloc * dv - v0; + modloc = TMath::Sqrt(xloc * xloc + yloc * yloc + dproj * dproj); + local[0] = xloc / modloc; + local[1] = yloc / modloc; + local[2] = dproj / modloc; + LocalToMasterVect(local, dir); fGeoManager->DoRestoreState(); fGeoManager->SetOutside(outside); fGeoManager->SetCurrentPoint(cop); fGeoManager->SetCurrentDirection(dir); -// fGeoManager->InitTrack(cop,dir); + // fGeoManager->InitTrack(cop,dir); // current ray pointing to pixel (px,py) done = kFALSE; norm = 0; // propagate to the clipping shape if any if (fClippingShape) { if (inclip) { - stemin = fClippingShape->DistFromInside(cop,dir,3); + stemin = fClippingShape->DistFromInside(cop, dir, 3); stemax = TGeoShape::Big(); } else { - stemax = fClippingShape->DistFromOutside(cop,dir,3); + stemax = fClippingShape->DistFromOutside(cop, dir, 3); stemin = 0; } } while (!done) { if (fClippingShape) { - if (stemin>1E10) break; - if (stemin>0) { + if (stemin > 1E10) + break; + if (stemin > 0) { // we are inside clipping shape fGeoManager->SetStep(stemin); next = fGeoManager->Step(); @@ -1745,38 +1856,41 @@ void TGeoPainter::Raytrace(Option_t *) up++; next = fGeoManager->GetMother(up); } - if (done) break; + if (done) + break; inclip = fClippingShape->Contains(ppoint); fGeoManager->SetStep(1E-3); while (inclip) { fGeoManager->Step(); inclip = fClippingShape->Contains(ppoint); } - stemax = fClippingShape->DistFromOutside(ppoint,dir,3); + stemax = fClippingShape->DistFromOutside(ppoint, dir, 3); } } nextnode = fGeoManager->FindNextBoundaryAndStep(); step = fGeoManager->GetStep(); - if (step>1E10) break; + if (step > 1E10) + break; steptot += step; next = nextnode; // Check the step if (fClippingShape) { - if (steptot>stemax) { + if (steptot > stemax) { steptot = 0; inclip = fClippingShape->Contains(ppoint); if (inclip) { - stemin = fClippingShape->DistFromInside(ppoint,dir,3); + stemin = fClippingShape->DistFromInside(ppoint, dir, 3); stemax = TGeoShape::Big(); continue; } else { stemin = 0; - stemax = fClippingShape->DistFromOutside(ppoint,dir,3); + stemax = fClippingShape->DistFromOutside(ppoint, dir, 3); } } } // Check if next node is visible - if (!nextnode) continue; + if (!nextnode) + continue; nextvol = nextnode->GetVolume(); if (nextvol->TestAttBit(TGeoAtt::kVisOnScreen)) { done = kTRUE; @@ -1785,33 +1899,38 @@ void TGeoPainter::Raytrace(Option_t *) break; } } - if (!done) continue; + if (!done) + continue; // current ray intersect a visible volume having color=base_color if (rtMode > 0) { fGeoManager->MasterToLocal(gGeoManager->GetCurrentPoint(), local); fGeoManager->MasterToLocalVect(gGeoManager->GetCurrentDirection(), dir); - for (Int_t i=0; i<3; ++i) local[i] += 1.E-8*dir[i]; - step = next->GetVolume()->GetShape()->DistFromInside(local,dir,3); - for (Int_t i=0; i<3; ++i) local[i] += step*dir[i]; + for (Int_t i = 0; i < 3; ++i) + local[i] += 1.E-8 * dir[i]; + step = next->GetVolume()->GetShape()->DistFromInside(local, dir, 3); + for (Int_t i = 0; i < 3; ++i) + local[i] += step * dir[i]; next->GetVolume()->GetShape()->ComputeNormal(local, dir, normal); norm = normal; } else { - if (!norm) norm = fGeoManager->FindNormalFast(); - if (!norm) continue; + if (!norm) + norm = fGeoManager->FindNormalFast(); + if (!norm) + continue; } - calf = norm[0]*tosource[0]+norm[1]*tosource[1]+norm[2]*tosource[2]; + calf = norm[0] * tosource[0] + norm[1] * tosource[1] + norm[2] * tosource[2]; light = TMath::Abs(calf); color = GetColor(base_color, light); // Now we know the color of the pixel, just draw it gVirtualX->SetMarkerColor(color); pxy[0].fX = px; pxy[0].fY = py; - gVirtualX->DrawPolyMarker(1,pxy); + gVirtualX->DrawPolyMarker(1, pxy); } } - delete [] pxy; + delete[] pxy; timer->Stop(); - fChecker->OpProgress("Raytracing",nrays,ntotal,timer,kTRUE); + fChecker->OpProgress("Raytracing", nrays, ntotal, timer, kTRUE); delete timer; } @@ -1819,8 +1938,7 @@ void TGeoPainter::Raytrace(Option_t *) /// Shoot npoints randomly in a box of 1E-5 around current point. /// Return minimum distance to points outside. -TGeoNode *TGeoPainter::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, - const char* g3path) +TGeoNode *TGeoPainter::SamplePoints(Int_t npoints, Double_t &dist, Double_t epsil, const char *g3path) { return fChecker->SamplePoints(npoints, dist, epsil, g3path); } @@ -1834,7 +1952,8 @@ void TGeoPainter::SetBombFactors(Double_t bombx, Double_t bomby, Double_t bombz, fBombY = bomby; fBombZ = bombz; fBombR = bombr; - if (IsExplodedView()) ModifiedPad(); + if (IsExplodedView()) + ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// @@ -1842,27 +1961,29 @@ void TGeoPainter::SetBombFactors(Double_t bombx, Double_t bomby, Double_t bombz, void TGeoPainter::SetExplodedView(Int_t ibomb) { - if ((ibomb<0) || (ibomb>3)) { + if ((ibomb < 0) || (ibomb > 3)) { Warning("SetExplodedView", "exploded view can be 0-3"); return; } - if ((Int_t)ibomb==fExplodedView) return; - Bool_t change = (gPad==0)?kFALSE:kTRUE; + if ((Int_t)ibomb == fExplodedView) + return; + Bool_t change = (gPad == 0) ? kFALSE : kTRUE; - if (ibomb==kGeoNoBomb) { - change &= ((fExplodedView==kGeoNoBomb)?kFALSE:kTRUE); + if (ibomb == kGeoNoBomb) { + change &= ((fExplodedView == kGeoNoBomb) ? kFALSE : kTRUE); } - if (ibomb==kGeoBombXYZ) { - change &= ((fExplodedView==kGeoBombXYZ)?kFALSE:kTRUE); + if (ibomb == kGeoBombXYZ) { + change &= ((fExplodedView == kGeoBombXYZ) ? kFALSE : kTRUE); } - if (ibomb==kGeoBombCyl) { - change &= ((fExplodedView==kGeoBombCyl)?kFALSE:kTRUE); + if (ibomb == kGeoBombCyl) { + change &= ((fExplodedView == kGeoBombCyl) ? kFALSE : kTRUE); } - if (ibomb==kGeoBombSph) { - change &= ((fExplodedView==kGeoBombSph)?kFALSE:kTRUE); + if (ibomb == kGeoBombSph) { + change &= ((fExplodedView == kGeoBombSph) ? kFALSE : kTRUE); } fExplodedView = ibomb; - if (change) ModifiedPad(); + if (change) + ModifiedPad(); } //////////////////////////////////////////////////////////////////////////////// @@ -1870,11 +1991,12 @@ void TGeoPainter::SetExplodedView(Int_t ibomb) void TGeoPainter::SetNsegments(Int_t nseg) { - if (nseg<3) { + if (nseg < 3) { Warning("SetNsegments", "number of segments should be > 2"); return; } - if (fNsegments==nseg) return; + if (fNsegments == nseg) + return; fNsegments = nseg; ModifiedPad(); } @@ -1882,7 +2004,8 @@ void TGeoPainter::SetNsegments(Int_t nseg) //////////////////////////////////////////////////////////////////////////////// /// Set number of points to be generated on the shape outline when checking for overlaps. -void TGeoPainter::SetNmeshPoints(Int_t npoints) { +void TGeoPainter::SetNmeshPoints(Int_t npoints) +{ fChecker->SetNmeshPoints(npoints); } @@ -1890,28 +2013,33 @@ void TGeoPainter::SetNmeshPoints(Int_t npoints) { /// Select a node to be checked for overlaps. All overlaps not involving it will /// be ignored. -void TGeoPainter::SetCheckedNode(TGeoNode *node) { +void TGeoPainter::SetCheckedNode(TGeoNode *node) +{ fChecker->SetSelectedNode(node); } //////////////////////////////////////////////////////////////////////////////// /// Set default level down to which visualization is performed -void TGeoPainter::SetVisLevel(Int_t level) { - if (level==fVisLevel && fLastVolume==fTopVolume) return; - fVisLevel=level; - if (!fTopVolume) return; +void TGeoPainter::SetVisLevel(Int_t level) +{ + if (level == fVisLevel && fLastVolume == fTopVolume) + return; + fVisLevel = level; + if (!fTopVolume) + return; if (fVisLock) { ClearVisibleVolumes(); fVisLock = kFALSE; } if (!fLastVolume) { -// printf("--- Drawing %6d nodes with %d visible levels\n",fNVisNodes,fVisLevel); + // printf("--- Drawing %6d nodes with %d visible levels\n",fNVisNodes,fVisLevel); return; } - if (!gPad) return; + if (!gPad) + return; if (gPad->GetView()) { -// printf("--- Drawing %6d nodes with %d visible levels\n",fNVisNodes,fVisLevel); + // printf("--- Drawing %6d nodes with %d visible levels\n",fNVisNodes,fVisLevel); ModifiedPad(); } } @@ -1921,7 +2049,8 @@ void TGeoPainter::SetVisLevel(Int_t level) { void TGeoPainter::SetTopVisible(Bool_t vis) { - if (fTopVisible==vis) return; + if (fTopVisible == vis) + return; fTopVisible = vis; ModifiedPad(); } @@ -1932,8 +2061,9 @@ void TGeoPainter::SetTopVisible(Bool_t vis) /// - option=1 leaves and nodes at vislevel drawn /// - option=2 path is drawn -void TGeoPainter::SetVisOption(Int_t option) { - if ((fVisOption<0) || (fVisOption>4)) { +void TGeoPainter::SetVisOption(Int_t option) +{ + if ((fVisOption < 0) || (fVisOption > 4)) { Warning("SetVisOption", "wrong visualization option"); return; } @@ -1948,24 +2078,20 @@ void TGeoPainter::SetVisOption(Int_t option) { } if (fTopVolume) { - TGeoAtt *att = (TGeoAtt*)fTopVolume; - att->SetAttBit(TGeoAtt::kVisBranch,kFALSE); - att->SetAttBit(TGeoAtt::kVisContainers,kFALSE); - att->SetAttBit(TGeoAtt::kVisOnly,kFALSE); + TGeoAtt *att = (TGeoAtt *)fTopVolume; + att->SetAttBit(TGeoAtt::kVisBranch, kFALSE); + att->SetAttBit(TGeoAtt::kVisContainers, kFALSE); + att->SetAttBit(TGeoAtt::kVisOnly, kFALSE); switch (option) { - case kGeoVisDefault: - att->SetAttBit(TGeoAtt::kVisContainers,kTRUE); - break; - case kGeoVisLeaves: - break; - case kGeoVisOnly: - att->SetAttBit(TGeoAtt::kVisOnly,kTRUE); - break; + case kGeoVisDefault: att->SetAttBit(TGeoAtt::kVisContainers, kTRUE); break; + case kGeoVisLeaves: break; + case kGeoVisOnly: att->SetAttBit(TGeoAtt::kVisOnly, kTRUE); break; } } - if (fVisOption==option) return; - fVisOption=option; + if (fVisOption == option) + return; + fVisOption = option; if (fVisLock) { ClearVisibleVolumes(); fVisLock = kFALSE; @@ -1982,10 +2108,13 @@ Int_t TGeoPainter::ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoi const Int_t maxdist = 5; const Int_t big = 9999; Int_t dist = big; - if (!gPad) return dist; + if (!gPad) + return dist; TView *view = gPad->GetView(); - if (!(numpoints && view)) return dist; - if (shape->IsA()==TGeoShapeAssembly::Class()) return dist; + if (!(numpoints && view)) + return dist; + if (shape->IsA() == TGeoShapeAssembly::Class()) + return dist; if (fIsPaintingShape) { Int_t puxmin = gPad->XtoAbsPixel(gPad->GetUxmin()); @@ -1993,36 +2122,45 @@ Int_t TGeoPainter::ShapeDistancetoPrimitive(const TGeoShape *shape, Int_t numpoi Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); // return if point not in user area - if (px < puxmin - inaxis) return big; - if (py > puymin + inaxis) return big; - if (px > puxmax + inaxis) return big; - if (py < puymax - inaxis) return big; - if ((puxmax+inaxis-px) < 40) { + if (px < puxmin - inaxis) + return big; + if (py > puymin + inaxis) + return big; + if (px > puxmax + inaxis) + return big; + if (py < puymax - inaxis) + return big; + if ((puxmax + inaxis - px) < 40) { // when the mouse points to the (40 pix) right edge of the pad, the manager class is selected gPad->SetSelected(fGeoManager); return 0; } } - fBuffer->SetRawSizes(numpoints, 3*numpoints, 0, 0, 0, 0); + fBuffer->SetRawSizes(numpoints, 3 * numpoints, 0, 0, 0, 0); Double_t *points = fBuffer->fPnts; shape->SetPoints(points); Double_t dpoint2, x1, y1, xndc[3]; Double_t dmaster[3]; Int_t j; - for (Int_t i=0; iLocalToMaster(&points[j], dmaster); - points[j]=dmaster[0]; points[j+1]=dmaster[1]; points[j+2]=dmaster[2]; + points[j] = dmaster[0]; + points[j + 1] = dmaster[1]; + points[j + 2] = dmaster[2]; view->WCtoNDC(&points[j], xndc); x1 = gPad->XtoAbsPixel(xndc[0]); y1 = gPad->YtoAbsPixel(xndc[1]); - dpoint2 = (px-x1)*(px-x1) + (py-y1)*(py-y1); - if (dpoint2 < dist) dist=(Int_t)dpoint2; + dpoint2 = (px - x1) * (px - x1) + (py - y1) * (py - y1); + if (dpoint2 < dist) + dist = (Int_t)dpoint2; } - if (dist > 100) return dist; + if (dist > 100) + return dist; dist = Int_t(TMath::Sqrt(Double_t(dist))); - if (distSetSelected((TObject*)shape); + if (dist < maxdist && fIsPaintingShape) + gPad->SetSelected((TObject *)shape); return dist; } @@ -2037,7 +2175,7 @@ void TGeoPainter::Test(Int_t npoints, Option_t *option) //////////////////////////////////////////////////////////////////////////////// /// Geometry overlap checker based on sampling. -void TGeoPainter::TestOverlaps(const char* path) +void TGeoPainter::TestOverlaps(const char *path) { fChecker->TestOverlaps(path); } @@ -2055,27 +2193,25 @@ Bool_t TGeoPainter::TestVoxels(TGeoVolume *vol) void TGeoPainter::UnbombTranslation(const Double_t *tr, Double_t *bombtr) { - memcpy(bombtr, tr, 3*sizeof(Double_t)); + memcpy(bombtr, tr, 3 * sizeof(Double_t)); switch (fExplodedView) { - case kGeoNoBomb: - return; - case kGeoBombXYZ: - bombtr[0] /= fBombX; - bombtr[1] /= fBombY; - bombtr[2] /= fBombZ; - return; - case kGeoBombCyl: - bombtr[0] /= fBombR; - bombtr[1] /= fBombR; - bombtr[2] /= fBombZ; - return; - case kGeoBombSph: - bombtr[0] /= fBombR; - bombtr[1] /= fBombR; - bombtr[2] /= fBombR; - return; - default: - return; + case kGeoNoBomb: return; + case kGeoBombXYZ: + bombtr[0] /= fBombX; + bombtr[1] /= fBombY; + bombtr[2] /= fBombZ; + return; + case kGeoBombCyl: + bombtr[0] /= fBombR; + bombtr[1] /= fBombR; + bombtr[2] /= fBombZ; + return; + case kGeoBombSph: + bombtr[0] /= fBombR; + bombtr[1] /= fBombR; + bombtr[2] /= fBombR; + return; + default: return; } } @@ -2086,5 +2222,3 @@ Double_t TGeoPainter::Weight(Double_t precision, Option_t *option) { return fChecker->Weight(precision, option); } - - diff --git a/geom/geompainter/src/TGeoTrack.cxx b/geom/geompainter/src/TGeoTrack.cxx index c2908ea0c2e5c..9e9781574d4ea 100644 --- a/geom/geompainter/src/TGeoTrack.cxx +++ b/geom/geompainter/src/TGeoTrack.cxx @@ -40,20 +40,20 @@ ClassImp(TGeoTrack); TGeoTrack::TGeoTrack() { fPointsSize = 0; - fNpoints = 0; - fPoints = 0; + fNpoints = 0; + fPoints = 0; } //////////////////////////////////////////////////////////////////////////////// /// Constructor. TGeoTrack::TGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent, TObject *particle) - :TVirtualGeoTrack(id,pdgcode,parent,particle) + : TVirtualGeoTrack(id, pdgcode, parent, particle) { fPointsSize = 0; - fNpoints = 0; - fPoints = 0; - if (fParent==0) { + fNpoints = 0; + fPoints = 0; + if (fParent == 0) { SetMarkerColor(2); SetMarkerStyle(8); SetMarkerSize(0.6); @@ -73,8 +73,9 @@ TGeoTrack::TGeoTrack(Int_t id, Int_t pdgcode, TVirtualGeoTrack *parent, TObject TGeoTrack::~TGeoTrack() { - if (fPoints) delete [] fPoints; -// if (gPad) gPad->GetListOfPrimitives()->Remove(this); + if (fPoints) + delete[] fPoints; + // if (gPad) gPad->GetListOfPrimitives()->Remove(this); } //////////////////////////////////////////////////////////////////////////////// @@ -82,10 +83,11 @@ TGeoTrack::~TGeoTrack() TVirtualGeoTrack *TGeoTrack::AddDaughter(Int_t id, Int_t pdgcode, TObject *particle) { - if (!fTracks) fTracks = new TObjArray(1); + if (!fTracks) + fTracks = new TObjArray(1); Int_t index = fTracks->GetEntriesFast(); - TGeoTrack *daughter = new TGeoTrack(id,pdgcode,this,particle); - fTracks->AddAtAndExpand(daughter,index); + TGeoTrack *daughter = new TGeoTrack(id, pdgcode, this, particle); + fTracks->AddAtAndExpand(daughter, index); return daughter; } @@ -94,9 +96,10 @@ TVirtualGeoTrack *TGeoTrack::AddDaughter(Int_t id, Int_t pdgcode, TObject *parti Int_t TGeoTrack::AddDaughter(TVirtualGeoTrack *other) { - if (!fTracks) fTracks = new TObjArray(1); + if (!fTracks) + fTracks = new TObjArray(1); Int_t index = fTracks->GetEntriesFast(); - fTracks->AddAtAndExpand(other,index); + fTracks->AddAtAndExpand(other, index); other->SetParent(this); return index; } @@ -106,7 +109,8 @@ Int_t TGeoTrack::AddDaughter(TVirtualGeoTrack *other) void TGeoTrack::AnimateTrack(Double_t tmin, Double_t tmax, Double_t nframes, Option_t *option) { - if (tmin<0 || tmin>=tmax || nframes<1) return; + if (tmin < 0 || tmin >= tmax || nframes < 1) + return; gGeoManager->SetAnimateTracks(); gGeoManager->SetVisLevel(1); if (!gPad) { @@ -116,9 +120,10 @@ void TGeoTrack::AnimateTrack(Double_t tmin, Double_t tmax, Double_t nframes, Opt TIter next(list); TObject *obj; while ((obj = next())) { - if (!strcmp(obj->ClassName(), "TGeoTrack")) list->Remove(obj); + if (!strcmp(obj->ClassName(), "TGeoTrack")) + list->Remove(obj); } - Double_t dt = (tmax-tmin)/Double_t(nframes); + Double_t dt = (tmax - tmin) / Double_t(nframes); Double_t delt = 2E-9; Double_t t = tmin; Bool_t geomanim = kFALSE; @@ -126,43 +131,48 @@ void TGeoTrack::AnimateTrack(Double_t tmin, Double_t tmax, Double_t nframes, Opt TString fname; TString opt(option); - if (opt.Contains("/G")) geomanim = kTRUE; - if (opt.Contains("/S")) issave = kTRUE; + if (opt.Contains("/G")) + geomanim = kTRUE; + if (opt.Contains("/S")) + issave = kTRUE; TVirtualGeoPainter *p = gGeoManager->GetGeomPainter(); Double_t *box = p->GetViewBox(); box[0] = box[1] = box[2] = 0; box[3] = box[4] = box[5] = 100; - gGeoManager->SetTminTmax(0,0); + gGeoManager->SetTminTmax(0, 0); Draw(opt.Data()); - Double_t start[6] = {0,0,0,0,0,0}; - Double_t end[6] = {0,0,0,0,0,0}; + Double_t start[6] = {0, 0, 0, 0, 0, 0}; + Double_t end[6] = {0, 0, 0, 0, 0, 0}; Int_t i, j; - Double_t dlat=0, dlong=0, dpsi=0; - Double_t dd[6] = {0,0,0,0,0,0}; + Double_t dlat = 0, dlong = 0, dpsi = 0; + Double_t dd[6] = {0, 0, 0, 0, 0, 0}; if (geomanim) { - p->EstimateCameraMove(tmin+5*dt, tmin+15*dt, start, end); - for (i=0; i<3; i++) { - start[i+3] = 20 + 1.3*start[i+3]; - end[i+3] = 20 + 0.9*end[i+3]; + p->EstimateCameraMove(tmin + 5 * dt, tmin + 15 * dt, start, end); + for (i = 0; i < 3; i++) { + start[i + 3] = 20 + 1.3 * start[i + 3]; + end[i + 3] = 20 + 0.9 * end[i + 3]; } - for (i=0; i<6; i++) { - dd[i] = (end[i]-start[i])/10.; + for (i = 0; i < 6; i++) { + dd[i] = (end[i] - start[i]) / 10.; } - memcpy(box, start, 6*sizeof(Double_t)); - p->GetViewAngles(dlong,dlat,dpsi); - dlong = (-206-dlong)/Double_t(nframes); - dlat = (126-dlat)/Double_t(nframes); - dpsi = (75-dpsi)/Double_t(nframes); + memcpy(box, start, 6 * sizeof(Double_t)); + p->GetViewAngles(dlong, dlat, dpsi); + dlong = (-206 - dlong) / Double_t(nframes); + dlat = (126 - dlat) / Double_t(nframes); + dpsi = (75 - dpsi) / Double_t(nframes); p->GrabFocus(); } - for (i=0; iSetTminTmax(0,t); - else gGeoManager->SetTminTmax(t-delt,t); + for (i = 0; i < nframes; i++) { + if (t - delt < 0) + gGeoManager->SetTminTmax(0, t); + else + gGeoManager->SetTminTmax(t - delt, t); if (geomanim) { - for (j=0; j<6; j++) box[j]+=dd[j]; - p->GrabFocus(1,dlong,dlat,dpsi); + for (j = 0; j < 6; j++) + box[j] += dd[j]; + p->GrabFocus(1, dlong, dlat, dpsi); } else { gPad->Modified(); gPad->Update(); @@ -185,11 +195,11 @@ void TGeoTrack::AddPoint(Double_t x, Double_t y, Double_t z, Double_t t) fPointsSize = 16; fPoints = new Double_t[fPointsSize]; } else { - if (fNpoints>=fPointsSize) { - Double_t *temp = new Double_t[2*fPointsSize]; - memcpy(temp, fPoints, fNpoints*sizeof(Double_t)); + if (fNpoints >= fPointsSize) { + Double_t *temp = new Double_t[2 * fPointsSize]; + memcpy(temp, fPoints, fNpoints * sizeof(Double_t)); fPointsSize *= 2; - delete [] fPoints; + delete[] fPoints; fPoints = temp; } } @@ -204,15 +214,15 @@ void TGeoTrack::AddPoint(Double_t x, Double_t y, Double_t z, Double_t t) void TGeoTrack::Browse(TBrowser *b) { - if (!b) return; + if (!b) + return; Int_t nd = GetNdaughters(); if (!nd) { b->Add(this); return; } - for (Int_t i=0; iAdd(GetDaughter(i)); - } //////////////////////////////////////////////////////////////////////////////// @@ -224,40 +234,46 @@ Int_t TGeoTrack::DistancetoPrimitive(Int_t px, Int_t py) const Int_t maxdist = 5; Int_t dist = 9999; - Int_t puxmin = gPad->XtoAbsPixel(gPad->GetUxmin()); Int_t puymin = gPad->YtoAbsPixel(gPad->GetUymin()); Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); // return if point is not in the user area - if (px < puxmin - inaxis) return dist; - if (py > puymin + inaxis) return dist; - if (px > puxmax + inaxis) return dist; - if (py < puymax - inaxis) return dist; + if (px < puxmin - inaxis) + return dist; + if (py > puymin + inaxis) + return dist; + if (px > puxmax + inaxis) + return dist; + if (py < puymax - inaxis) + return dist; TView *view = gPad->GetView(); - if (!view) return dist; + if (!view) + return dist; Int_t imin, imax; - if (TObject::TestBit(kGeoPDrawn) && Size(imin,imax)>=2) { + if (TObject::TestBit(kGeoPDrawn) && Size(imin, imax) >= 2) { Int_t i, dsegment; - Double_t x1,y1,x2,y2; + Double_t x1, y1, x2, y2; Double_t xndc[3]; - Int_t np = fNpoints>>2; - if (imin<0) imin=0; - if (imax>np-1) imax=np-1; - for (i=imin;iWCtoNDC(&fPoints[i<<2], xndc); + Int_t np = fNpoints >> 2; + if (imin < 0) + imin = 0; + if (imax > np - 1) + imax = np - 1; + for (i = imin; i < imax; i++) { + view->WCtoNDC(&fPoints[i << 2], xndc); x1 = xndc[0]; y1 = xndc[1]; - view->WCtoNDC(&fPoints[(i+1)<<2], xndc); + view->WCtoNDC(&fPoints[(i + 1) << 2], xndc); x2 = xndc[0]; y2 = xndc[1]; - dsegment = DistancetoLine(px,py,x1,y1,x2,y2); -// printf("%i: dseg=%i\n", i, dsegment); + dsegment = DistancetoLine(px, py, x1, y1, x2, y2); + // printf("%i: dseg=%i\n", i, dsegment); if (dsegment < dist) { dist = dsegment; - if (distSetSelected(this); return 0; } @@ -266,12 +282,14 @@ Int_t TGeoTrack::DistancetoPrimitive(Int_t px, Int_t py) } // check now daughters Int_t nd = GetNdaughters(); - if (!nd) return dist; + if (!nd) + return dist; TGeoTrack *track; - for (Int_t id=0; idDistancetoPrimitive(px,py); - if (distDistancetoPrimitive(px, py); + if (dist < maxdist) + return 0; } return dist; } @@ -290,7 +308,8 @@ Int_t TGeoTrack::DistancetoPrimitive(Int_t px, Int_t py) void TGeoTrack::Draw(Option_t *option) { - if (!gPad) gGeoManager->GetMasterVolume()->Draw(); + if (!gPad) + gGeoManager->GetMasterVolume()->Draw(); char *opt1 = Compress(option); // we will have to delete this ? TString opt(opt1); Bool_t is_default = kTRUE; @@ -307,10 +326,11 @@ void TGeoTrack::Draw(Option_t *option) } if (opt.Contains("/N")) { is_type = kTRUE; - Int_t ist = opt.Index("/N")+2; - Int_t ilast = opt.Index("/",ist); - if (ilast<0) ilast=opt.Length(); - TString type = opt(ist, ilast-ist); + Int_t ist = opt.Index("/N") + 2; + Int_t ilast = opt.Index("/", ist); + if (ilast < 0) + ilast = opt.Length(); + TString type = opt(ist, ilast - ist); gGeoManager->SetParticleName(type.Data()); } SetBits(is_default, is_onelevel, is_all, is_type); @@ -319,16 +339,17 @@ void TGeoTrack::Draw(Option_t *option) gPad->Modified(); gPad->Update(); } - delete [] opt1; + delete[] opt1; return; } - /////////////////////////////////////////////////////////////////////////////// - /// Event treatment. +/////////////////////////////////////////////////////////////////////////////// +/// Event treatment. void TGeoTrack::ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) { - if (!gPad) return; + if (!gPad) + return; gPad->SetCursor(kHand); } @@ -338,10 +359,10 @@ void TGeoTrack::ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) char *TGeoTrack::GetObjectInfo(Int_t /*px*/, Int_t /*py*/) const { static TString info; - Double_t x=0,y=0,z=0,t=0; - GetPoint(0,x,y,z,t); - info = TString::Format("%s (%g, %g, %g) tof=%g", GetName(),x,y,z,t); - return (char*)info.Data(); + Double_t x = 0, y = 0, z = 0, t = 0; + GetPoint(0, x, y, z, t); + info = TString::Format("%s (%g, %g, %g) tof=%g", GetName(), x, y, z, t); + return (char *)info.Data(); } //////////////////////////////////////////////////////////////////////////////// @@ -349,16 +370,16 @@ char *TGeoTrack::GetObjectInfo(Int_t /*px*/, Int_t /*py*/) const Int_t TGeoTrack::GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double_t &t) const { - Int_t np = fNpoints>>2; - if (i<0 || i>=np) { - Error("GetPoint", "no point %i, indmax=%d", i, np-1); + Int_t np = fNpoints >> 2; + if (i < 0 || i >= np) { + Error("GetPoint", "no point %i, indmax=%d", i, np - 1); return -1; } - Int_t icrt = 4*i; + Int_t icrt = 4 * i; x = fPoints[icrt]; - y = fPoints[icrt+1]; - z = fPoints[icrt+2]; - t = fPoints[icrt+3]; + y = fPoints[icrt + 1]; + z = fPoints[icrt + 2]; + t = fPoints[icrt + 3]; return i; } @@ -367,8 +388,9 @@ Int_t TGeoTrack::GetPoint(Int_t i, Double_t &x, Double_t &y, Double_t &z, Double const Double_t *TGeoTrack::GetPoint(Int_t i) const { - if (!fNpoints) return 0; - return (&fPoints[i<<2]); + if (!fNpoints) + return 0; + return (&fPoints[i << 2]); } //////////////////////////////////////////////////////////////////////////////// @@ -377,17 +399,20 @@ const Double_t *TGeoTrack::GetPoint(Int_t i) const Int_t TGeoTrack::GetPoint(Double_t tof, Double_t *point, Int_t istart) const { - Int_t np = fNpoints>>2; - if (istart>(np-2)) return (np-1); + Int_t np = fNpoints >> 2; + if (istart > (np - 2)) + return (np - 1); Int_t ip = SearchPoint(tof, istart); - if (ip<0 || ip>(np-2)) return ip; + if (ip < 0 || ip > (np - 2)) + return ip; // point in segment (ip, ip+1) where 0<=ipGetParticleName(); - if (strlen(type) && strcmp(type, GetName())) match_type=kFALSE; + if (strlen(type) && strcmp(type, GetName())) + match_type = kFALSE; } if (match_type) { - if (is_default || is_onelevel || is_all) PaintTrack(option); + if (is_default || is_onelevel || is_all) + PaintTrack(option); } // paint now daughters Int_t nd = GetNdaughters(); - if (!nd || is_default) return; + if (!nd || is_default) + return; TGeoTrack *track; - for (Int_t i=0; iIsInTimeRange()) { - track->SetBits(is_default,kFALSE,is_all,is_type); + track->SetBits(is_default, kFALSE, is_all, is_type); track->Paint(option); } } @@ -427,25 +455,29 @@ void TGeoTrack::Paint(Option_t *option) void TGeoTrack::PaintCollect(Double_t time, Double_t *box) { - Bool_t is_default = TObject::TestBit(kGeoPDefault); + Bool_t is_default = TObject::TestBit(kGeoPDefault); Bool_t is_onelevel = TObject::TestBit(kGeoPOnelevel); - Bool_t is_all = TObject::TestBit(kGeoPAllDaughters); - Bool_t is_type = TObject::TestBit(kGeoPType); - Bool_t match_type = kTRUE; + Bool_t is_all = TObject::TestBit(kGeoPAllDaughters); + Bool_t is_type = TObject::TestBit(kGeoPType); + Bool_t match_type = kTRUE; if (is_type) { const char *type = gGeoManager->GetParticleName(); - if (strlen(type) && strcmp(type, GetName())) match_type=kFALSE; + if (strlen(type) && strcmp(type, GetName())) + match_type = kFALSE; } if (match_type) { - if (is_default || is_onelevel || is_all) PaintCollectTrack(time, box); + if (is_default || is_onelevel || is_all) + PaintCollectTrack(time, box); } // loop now daughters Int_t nd = GetNdaughters(); - if (!nd || is_default) return; + if (!nd || is_default) + return; TGeoTrack *track; - for (Int_t i=0; iPaintCollect(time, box); + for (Int_t i = 0; i < nd; i++) { + track = (TGeoTrack *)GetDaughter(i); + if (track) + track->PaintCollect(time, box); } } @@ -455,14 +487,17 @@ void TGeoTrack::PaintCollect(Double_t time, Double_t *box) void TGeoTrack::PaintCollectTrack(Double_t time, Double_t *box) { TVirtualGeoPainter *painter = gGeoManager->GetGeomPainter(); - if (!painter) return; - Int_t np = fNpoints>>2; + if (!painter) + return; + Int_t np = fNpoints >> 2; Double_t point[3], local[3]; - Bool_t convert = (gGeoManager->GetTopVolume() == gGeoManager->GetMasterVolume())?kFALSE:kTRUE; + Bool_t convert = (gGeoManager->GetTopVolume() == gGeoManager->GetMasterVolume()) ? kFALSE : kTRUE; Int_t ip = GetPoint(time, point); - if (ip>=0 && ipMasterToTop(point, local); - else memcpy(local, point, 3*sizeof(Double_t)); + if (ip >= 0 && ip < np - 1) { + if (convert) + gGeoManager->MasterToTop(point, local); + else + memcpy(local, point, 3 * sizeof(Double_t)); painter->AddTrackPoint(local, box); } } @@ -475,10 +510,13 @@ void TGeoTrack::PaintMarker(Double_t *point, Option_t *) TPoint p; Double_t xndc[3]; TView *view = gPad->GetView(); - if (!view) return; + if (!view) + return; view->WCtoNDC(point, xndc); - if (xndc[0] < gPad->GetX1() || xndc[0] > gPad->GetX2()) return; - if (xndc[1] < gPad->GetY1() || xndc[1] > gPad->GetY2()) return; + if (xndc[0] < gPad->GetX1() || xndc[0] > gPad->GetX2()) + return; + if (xndc[1] < gPad->GetY1() || xndc[1] > gPad->GetY2()) + return; p.fX = gPad->XtoPixel(xndc[0]); p.fY = gPad->YtoPixel(xndc[1]); TAttMarker::Modify(); @@ -491,8 +529,8 @@ void TGeoTrack::PaintMarker(Double_t *point, Option_t *) void TGeoTrack::PaintTrack(Option_t *option) { // Check whether there is some 3D view class for this TPad -// TPadView3D *view3D = (TPadView3D*)gPad->GetView3D(); -// if (view3D) view3D->PaintGeoTrack(this,option); // to be implemented + // TPadView3D *view3D = (TPadView3D*)gPad->GetView3D(); + // if (view3D) view3D->PaintGeoTrack(this,option); // to be implemented // Check if option is 'x3d'. NOTE: This is a simple checking // but since there is no other @@ -500,25 +538,26 @@ void TGeoTrack::PaintTrack(Option_t *option) TString opt(option); opt.ToLower(); TObject::SetBit(kGeoPDrawn, kFALSE); - if (opt.Contains("x")) return; - Int_t np = fNpoints>>2; - Int_t imin=0; - Int_t imax=np-1; + if (opt.Contains("x")) + return; + Int_t np = fNpoints >> 2; + Int_t imin = 0; + Int_t imax = np - 1; Int_t ip; - Double_t start[3] = {0.,0.,0.}; - Double_t end[3] = {0.,0.,0.}; - Double_t seg[6] = {0.,0.,0.,0.,0.,0.}; - Bool_t convert = (gGeoManager->GetTopVolume() == gGeoManager->GetMasterVolume())?kFALSE:kTRUE; - Double_t tmin=0.,tmax=0.; - Bool_t is_time = gGeoManager->GetTminTmax(tmin,tmax); + Double_t start[3] = {0., 0., 0.}; + Double_t end[3] = {0., 0., 0.}; + Double_t seg[6] = {0., 0., 0., 0., 0., 0.}; + Bool_t convert = (gGeoManager->GetTopVolume() == gGeoManager->GetMasterVolume()) ? kFALSE : kTRUE; + Double_t tmin = 0., tmax = 0.; + Bool_t is_time = gGeoManager->GetTminTmax(tmin, tmax); if (is_time) { imin = GetPoint(tmin, start); - if (imin>=0 && imin find ending point + if (imin >= 0 && imin < np - 1) { + // we have a starting point -> find ending point imax = GetPoint(tmax, end, imin); - if (imax check if on the same segment with imin - if (imax==imin) { + if (imax < np - 1) { + // we also have an ending point -> check if on the same segment with imin + if (imax == imin) { // paint the virtual segment between the 2 points TAttLine::Modify(); if (convert) { @@ -533,21 +572,21 @@ void TGeoTrack::PaintTrack(Option_t *option) TAttLine::Modify(); if (convert) { gGeoManager->MasterToTop(start, &seg[0]); - gGeoManager->MasterToTop(&fPoints[(imin+1)<<2], &seg[3]); + gGeoManager->MasterToTop(&fPoints[(imin + 1) << 2], &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); - gGeoManager->MasterToTop(&fPoints[imax<<2], &seg[0]); + gGeoManager->MasterToTop(&fPoints[imax << 2], &seg[0]); gGeoManager->MasterToTop(end, &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); - for (ip=imin+1; ipMasterToTop(&fPoints[ip<<2], &seg[0]); - gGeoManager->MasterToTop(&fPoints[(ip+1)<<2], &seg[3]); + for (ip = imin + 1; ip < imax; ip++) { + gGeoManager->MasterToTop(&fPoints[ip << 2], &seg[0]); + gGeoManager->MasterToTop(&fPoints[(ip + 1) << 2], &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); } } else { - gPad->PaintLine3D(start, &fPoints[(imin+1)<<2]); - gPad->PaintLine3D(&fPoints[imax<<2], end); - for (ip=imin+1; ipPaintLine3D(&fPoints[ip<<2], &fPoints[(ip+1)<<2]); + gPad->PaintLine3D(start, &fPoints[(imin + 1) << 2]); + gPad->PaintLine3D(&fPoints[imax << 2], end); + for (ip = imin + 1; ip < imax; ip++) { + gPad->PaintLine3D(&fPoints[ip << 2], &fPoints[(ip + 1) << 2]); } } } @@ -561,43 +600,44 @@ void TGeoTrack::PaintTrack(Option_t *option) TAttLine::Modify(); if (convert) { gGeoManager->MasterToTop(start, &seg[0]); - gGeoManager->MasterToTop(&fPoints[(imin+1)<<2], &seg[3]); + gGeoManager->MasterToTop(&fPoints[(imin + 1) << 2], &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); - for (ip=imin+1; ipMasterToTop(&fPoints[ip<<2], &seg[0]); - gGeoManager->MasterToTop(&fPoints[(ip+1)<<2], &seg[3]); + for (ip = imin + 1; ip < np - 2; ip++) { + gGeoManager->MasterToTop(&fPoints[ip << 2], &seg[0]); + gGeoManager->MasterToTop(&fPoints[(ip + 1) << 2], &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); } } else { - gPad->PaintLine3D(start, &fPoints[(imin+1)<<2]); - for (ip=imin+1; ipPaintLine3D(&fPoints[ip<<2], &fPoints[(ip+1)<<2]); + gPad->PaintLine3D(start, &fPoints[(imin + 1) << 2]); + for (ip = imin + 1; ip < np - 2; ip++) { + gPad->PaintLine3D(&fPoints[ip << 2], &fPoints[(ip + 1) << 2]); } } } } else { imax = GetPoint(tmax, end); - if (imax<0 || imax>=(np-1)) return; + if (imax < 0 || imax >= (np - 1)) + return; // we have to draw just the end of the track TAttLine::Modify(); if (convert) { - for (ip=0; ipMasterToTop(&fPoints[ip<<2], &seg[0]); - gGeoManager->MasterToTop(&fPoints[(ip+1)<<2], &seg[3]); + for (ip = 0; ip < imax - 1; ip++) { + gGeoManager->MasterToTop(&fPoints[ip << 2], &seg[0]); + gGeoManager->MasterToTop(&fPoints[(ip + 1) << 2], &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); } } else { - for (ip=0; ipPaintLine3D(&fPoints[ip<<2], &fPoints[(ip+1)<<2]); + for (ip = 0; ip < imax - 1; ip++) { + gPad->PaintLine3D(&fPoints[ip << 2], &fPoints[(ip + 1) << 2]); } } if (convert) { - gGeoManager->MasterToTop(&fPoints[imax<<2], &seg[0]); + gGeoManager->MasterToTop(&fPoints[imax << 2], &seg[0]); gGeoManager->MasterToTop(end, &seg[3]); gPad->PaintLine3D(&seg[0], &seg[3]); PaintMarker(&seg[3]); } else { - gPad->PaintLine3D(&fPoints[imax<<2], end); + gPad->PaintLine3D(&fPoints[imax << 2], end); PaintMarker(end); } } @@ -607,9 +647,9 @@ void TGeoTrack::PaintTrack(Option_t *option) // paint all segments from track TObject::SetBit(kGeoPDrawn); - TAttLine::Modify(); // change attributes if necessary - for (ip=imin; ipPaintLine3D(&fPoints[ip<<2], &fPoints[(ip+1)<<2]); + TAttLine::Modify(); // change attributes if necessary + for (ip = imin; ip < imax; ip++) { + gPad->PaintLine3D(&fPoints[ip << 2], &fPoints[(ip + 1) << 2]); } } @@ -618,14 +658,14 @@ void TGeoTrack::PaintTrack(Option_t *option) void TGeoTrack::Print(Option_t * /*option*/) const { - Int_t np = fNpoints>>2; - printf(" TGeoTrack%6i : %s ===============================\n", fId,GetName()); - printf(" parent =%6i nd =%3i\n", (fParent)?fParent->GetId():-1, GetNdaughters()); - Double_t x=0,y=0,z=0,t=0; - GetPoint(0,x,y,z,t); - printf(" production vertex : (%g, %g, %g) at tof=%g\n", x,y,z,t); - GetPoint(np-1,x,y,z,t); - printf(" Npoints =%6i, last : (%g, %g, %g) at tof=%g\n\n", np,x,y,z,t); + Int_t np = fNpoints >> 2; + printf(" TGeoTrack%6i : %s ===============================\n", fId, GetName()); + printf(" parent =%6i nd =%3i\n", (fParent) ? fParent->GetId() : -1, GetNdaughters()); + Double_t x = 0, y = 0, z = 0, t = 0; + GetPoint(0, x, y, z, t); + printf(" production vertex : (%g, %g, %g) at tof=%g\n", x, y, z, t); + GetPoint(np - 1, x, y, z, t); + printf(" Npoints =%6i, last : (%g, %g, %g) at tof=%g\n\n", np, x, y, z, t); } //////////////////////////////////////////////////////////////////////////////// @@ -635,14 +675,15 @@ void TGeoTrack::Print(Option_t * /*option*/) const Int_t TGeoTrack::Size(Int_t &imin, Int_t &imax) { Double_t tmin, tmax; - Int_t np = fNpoints>>2; + Int_t np = fNpoints >> 2; imin = 0; - imax = np-1; + imax = np - 1; Int_t size = np; - if (!gGeoManager->GetTminTmax(tmin, tmax)) return size; + if (!gGeoManager->GetTminTmax(tmin, tmax)) + return size; imin = SearchPoint(tmin); imax = SearchPoint(tmax, imin); - return (imax-imin+1); + return (imax - imin + 1); } //////////////////////////////////////////////////////////////////////////////// @@ -652,24 +693,26 @@ Int_t TGeoTrack::Size(Int_t &imin, Int_t &imax) Int_t TGeoTrack::SearchPoint(Double_t time, Int_t istart) const { Int_t nabove, nbelow, middle, midloc; - Int_t np = fNpoints>>2; - nabove = np+1; + Int_t np = fNpoints >> 2; + nabove = np + 1; nbelow = istart; - while (nabove-nbelow > 1) { - middle = (nabove+nbelow)/2; - midloc = ((middle-1)<<2)+3; - if (time == fPoints[midloc]) return middle-1; - if (time < fPoints[midloc]) nabove = middle; - else nbelow = middle; + while (nabove - nbelow > 1) { + middle = (nabove + nbelow) / 2; + midloc = ((middle - 1) << 2) + 3; + if (time == fPoints[midloc]) + return middle - 1; + if (time < fPoints[midloc]) + nabove = middle; + else + nbelow = middle; } - return (nbelow-1); + return (nbelow - 1); } //////////////////////////////////////////////////////////////////////////////// /// Set drawing bits for this track -void TGeoTrack::SetBits(Bool_t is_default, Bool_t is_onelevel, - Bool_t is_all, Bool_t is_type) +void TGeoTrack::SetBits(Bool_t is_default, Bool_t is_onelevel, Bool_t is_all, Bool_t is_type) { TObject::SetBit(kGeoPDefault, is_default); TObject::SetBit(kGeoPOnelevel, is_onelevel); @@ -680,20 +723,21 @@ void TGeoTrack::SetBits(Bool_t is_default, Bool_t is_onelevel, //////////////////////////////////////////////////////////////////////////////// /// Returns 3D size for the track. -void TGeoTrack::Sizeof3D() const -{ -} +void TGeoTrack::Sizeof3D() const {} //////////////////////////////////////////////////////////////////////////////// /// Reset data for this track. void TGeoTrack::ResetTrack() { - fNpoints = 0; + fNpoints = 0; fPointsSize = 0; - if (fTracks) {fTracks->Delete(); delete fTracks;} + if (fTracks) { + fTracks->Delete(); + delete fTracks; + } fTracks = 0; - if (fPoints) delete [] fPoints; + if (fPoints) + delete[] fPoints; fPoints = 0; } - diff --git a/geom/test/test_material_units.cxx b/geom/test/test_material_units.cxx index d49b8b1f6ce02..b96ee585fa35f 100644 --- a/geom/test/test_material_units.cxx +++ b/geom/test/test_material_units.cxx @@ -19,11 +19,6 @@ struct PDG_material { double mass; // g/mole double density; // g/cm3 double length_unit; // For pdg, tgeo: 1, g4: 10 - PDG_material() = default; - PDG_material(PDG_material &&) = default; - PDG_material(const PDG_material &) = default; - ~PDG_material() = default; - PDG_material &operator=(const PDG_material &) = default; }; // Radiation/interaction length must be within 2 % of pdg values diff --git a/geom/vecgeom/CMakeLists.txt b/geom/vecgeom/CMakeLists.txt index f2c711fca59c4..2e94e13078bf0 100644 --- a/geom/vecgeom/CMakeLists.txt +++ b/geom/vecgeom/CMakeLists.txt @@ -12,10 +12,6 @@ include_directories(AFTER SYSTEM ${VECGEOM_INCLUDE_DIRS}) if ( Vc_FOUND ) include_directories( AFTER SYSTEM ${Vc_INCLUDE_DIRS}) - if (NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" - AND NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fabi-version=6") - endif() endif() ROOT_STANDARD_LIBRARY_PACKAGE(ConverterVG diff --git a/geom/vecgeom/inc/LinkDef.h b/geom/vecgeom/inc/LinkDef.h index 0b478a180e69a..1c7cf0672f769 100644 --- a/geom/vecgeom/inc/LinkDef.h +++ b/geom/vecgeom/inc/LinkDef.h @@ -12,7 +12,7 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class TGeoVGConverter+; -#pragma link C++ class TGeoVGShape+; +#pragma link C++ class TGeoVGConverter + ; +#pragma link C++ class TGeoVGShape + ; #endif diff --git a/geom/vecgeom/inc/TGeoVGConverter.h b/geom/vecgeom/inc/TGeoVGConverter.h index a5f8a7ebbea9d..a4ae68d1f50f8 100644 --- a/geom/vecgeom/inc/TGeoVGConverter.h +++ b/geom/vecgeom/inc/TGeoVGConverter.h @@ -25,11 +25,11 @@ class TGeoVGConverter : public TVirtualGeoConverter { public: TGeoVGConverter(TGeoManager *manager); - virtual ~TGeoVGConverter(); + ~TGeoVGConverter() override; - virtual void ConvertGeometry(); + void ConvertGeometry() override; - ClassDef(TGeoVGConverter,0) // VecGeom geometry converter + ClassDefOverride(TGeoVGConverter, 0) // VecGeom geometry converter }; #endif diff --git a/geom/vecgeom/inc/TGeoVGShape.h b/geom/vecgeom/inc/TGeoVGShape.h index 2f6792e527d7b..617a3f7619dc2 100644 --- a/geom/vecgeom/inc/TGeoVGShape.h +++ b/geom/vecgeom/inc/TGeoVGShape.h @@ -20,85 +20,91 @@ //////////////////////////////////////////////////////////////////////////// namespace vecgeom { - inline namespace cxx { - class Transformation3D; - class VPlacedVolume; - class VUnplacedVolume; - } -} +inline namespace cxx { +class Transformation3D; +class VPlacedVolume; +class VUnplacedVolume; +} // namespace cxx +} // namespace vecgeom -class TGeoVGShape : public TGeoBBox -{ +class TGeoVGShape : public TGeoBBox { private: - vecgeom::cxx::VPlacedVolume *fVGShape; // VecGeom placed solid - TGeoShape *fShape; // ROOT shape + vecgeom::cxx::VPlacedVolume *fVGShape; // VecGeom placed solid + TGeoShape *fShape; // ROOT shape static vecgeom::cxx::VPlacedVolume *CreateVecGeomSolid(TGeoShape *shape); TGeoVGShape(TGeoShape *shape, vecgeom::cxx::VPlacedVolume *vgshape); public: TGeoVGShape() : TGeoBBox(), fVGShape(nullptr), fShape(nullptr) {} - virtual ~TGeoVGShape(); - static vecgeom::cxx::Transformation3D * - Convert(TGeoMatrix const *const geomatrix); - static vecgeom::cxx::VUnplacedVolume * - Convert(TGeoShape const *const shape); - static TGeoVGShape *Create(TGeoShape *shape); - virtual Double_t Capacity() const; - virtual void ComputeBBox(); - virtual void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm); - virtual Bool_t Contains(const Double_t *point) const; - virtual Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const - { return fShape->CouldBeCrossed(point,dir); } - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py) - { return fShape->DistancetoPrimitive(px, py); } - virtual Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact=1, - Double_t step=TGeoShape::Big(), Double_t *safe=nullptr) const; - virtual TGeoVolume *Divide(TGeoVolume *, const char *, Int_t, Int_t, Double_t, Double_t) - { return nullptr; } - virtual void Draw(Option_t *option="") { fShape->Draw(option); } // *MENU* - virtual const char *GetAxisName(Int_t iaxis) const - { return ( fShape->GetAxisName(iaxis) ); } - virtual Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const - { return ( fShape->GetAxisRange(iaxis, xlo, xhi) ); } - virtual void GetBoundingCylinder(Double_t *param) const - { return ( fShape->GetBoundingCylinder(param) ); } - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const - { return ( fShape->GetBuffer3D(reqSections, localFrame) ); } - virtual Int_t GetByteCount() const { return ( fShape->GetByteCount() ); } - virtual Double_t Safety(const Double_t *point, Bool_t in=kTRUE) const; - virtual Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const - { return ( fShape->GetPointsOnSegments(npoints, array) ); } - virtual Int_t GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const - { return ( fShape->GetFittingBox(parambox, mat, dx, dy, dz) ); } - virtual TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const - { return ( fShape->GetMakeRuntimeShape(mother, mat) ); } - virtual void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const - { fShape->GetMeshNumbers(nvert, nsegs, npols); } - virtual const char *GetName() const - { return ( fShape->GetName() ); } - virtual Int_t GetNmeshVertices() const - {return ( fShape->GetNmeshVertices() );} - virtual Bool_t IsAssembly() const { return ( fShape->IsAssembly() ); } - virtual Bool_t IsComposite() const { return ( fShape->IsComposite() ); } - virtual Bool_t IsCylType() const { return ( fShape->IsCylType() ); } - virtual Bool_t IsReflected() const { return ( fShape->IsReflected() ); } - virtual Bool_t IsValidBox() const { return ( fShape->IsValidBox() ); } - virtual Bool_t IsVecGeom() const {return kTRUE;} - virtual void InspectShape() const; - virtual TBuffer3D *MakeBuffer3D() const { return ( fShape->MakeBuffer3D() );} - virtual void Paint(Option_t *option="") { fShape->Paint(option); } - virtual void SetDimensions(Double_t *param) { fShape->SetDimensions(param); } - virtual void SetPoints(Double_t *points) const { fShape->SetPoints(points); } - virtual void SetPoints(Float_t *points) const { fShape->SetPoints(points); } - virtual void SetSegsAndPols(TBuffer3D &buff) const { fShape->SetSegsAndPols(buff); } - virtual void Sizeof3D() const { fShape->Sizeof3D(); } + ~TGeoVGShape() override; + static vecgeom::cxx::Transformation3D *Convert(TGeoMatrix const *const geomatrix); + static vecgeom::cxx::VUnplacedVolume *Convert(TGeoShape const *const shape); + static TGeoVGShape *Create(TGeoShape *shape); + Double_t Capacity() const override; + void ComputeBBox() override; + void ComputeNormal(const Double_t *point, const Double_t *dir, Double_t *norm) override; + Bool_t Contains(const Double_t *point) const override; + Bool_t CouldBeCrossed(const Double_t *point, const Double_t *dir) const override + { + return fShape->CouldBeCrossed(point, dir); + } + Int_t DistancetoPrimitive(Int_t px, Int_t py) override { return fShape->DistancetoPrimitive(px, py); } + Double_t DistFromInside(const Double_t *point, const Double_t *dir, Int_t iact = 1, Double_t step = TGeoShape::Big(), + Double_t *safe = nullptr) const override; + Double_t DistFromOutside(const Double_t *point, const Double_t *dir, Int_t iact = 1, + Double_t step = TGeoShape::Big(), Double_t *safe = nullptr) const override; + TGeoVolume *Divide(TGeoVolume *, const char *, Int_t, Int_t, Double_t, Double_t) override { return nullptr; } + void Draw(Option_t *option = "") override { fShape->Draw(option); } // *MENU* + const char *GetAxisName(Int_t iaxis) const override { return (fShape->GetAxisName(iaxis)); } + Double_t GetAxisRange(Int_t iaxis, Double_t &xlo, Double_t &xhi) const override + { + return (fShape->GetAxisRange(iaxis, xlo, xhi)); + } + void GetBoundingCylinder(Double_t *param) const override { return (fShape->GetBoundingCylinder(param)); } + const TBuffer3D &GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override + { + return (fShape->GetBuffer3D(reqSections, localFrame)); + } + Int_t GetByteCount() const override { return (fShape->GetByteCount()); } + Double_t Safety(const Double_t *point, Bool_t in = kTRUE) const override; + Bool_t GetPointsOnSegments(Int_t npoints, Double_t *array) const override + { + return (fShape->GetPointsOnSegments(npoints, array)); + } + Int_t + GetFittingBox(const TGeoBBox *parambox, TGeoMatrix *mat, Double_t &dx, Double_t &dy, Double_t &dz) const override + { + return (fShape->GetFittingBox(parambox, mat, dx, dy, dz)); + } + TGeoShape *GetMakeRuntimeShape(TGeoShape *mother, TGeoMatrix *mat) const override + { + return (fShape->GetMakeRuntimeShape(mother, mat)); + } + void GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const override + { + fShape->GetMeshNumbers(nvert, nsegs, npols); + } + const char *GetName() const override { return (fShape->GetName()); } + Int_t GetNmeshVertices() const override { return (fShape->GetNmeshVertices()); } + Bool_t IsAssembly() const override { return (fShape->IsAssembly()); } + Bool_t IsComposite() const override { return (fShape->IsComposite()); } + Bool_t IsCylType() const override { return (fShape->IsCylType()); } + Bool_t IsReflected() const override { return (fShape->IsReflected()); } + Bool_t IsValidBox() const override { return (fShape->IsValidBox()); } + Bool_t IsVecGeom() const override { return kTRUE; } + void InspectShape() const override; + TBuffer3D *MakeBuffer3D() const override { return (fShape->MakeBuffer3D()); } + void Paint(Option_t *option = "") override { fShape->Paint(option); } + void SetDimensions(Double_t *param) override { fShape->SetDimensions(param); } + void SetPoints(Double_t *points) const override { fShape->SetPoints(points); } + void SetPoints(Float_t *points) const override { fShape->SetPoints(points); } + void SetSegsAndPols(TBuffer3D &buff) const override { fShape->SetSegsAndPols(buff); } + void Sizeof3D() const override { fShape->Sizeof3D(); } - TGeoShape *GetShape() const { return fShape; } + TGeoShape *GetShape() const { return fShape; } vecgeom::cxx::VPlacedVolume *GetVGShape() const { return fVGShape; } - ClassDef(TGeoVGShape, 0) // Adapter for a VecGeom shape + ClassDefOverride(TGeoVGShape, 0) // Adapter for a VecGeom shape }; #endif diff --git a/geom/vecgeom/src/TGeoVGConverter.cxx b/geom/vecgeom/src/TGeoVGConverter.cxx index c8a55b1cb8bae..5f8b97ab7ac71 100644 --- a/geom/vecgeom/src/TGeoVGConverter.cxx +++ b/geom/vecgeom/src/TGeoVGConverter.cxx @@ -30,9 +30,7 @@ TGeoVGConverter::TGeoVGConverter(TGeoManager *manager) : TVirtualGeoConverter(ma //////////////////////////////////////////////////////////////////////////////// /// Default destructor. -TGeoVGConverter::~TGeoVGConverter() -{ -} +TGeoVGConverter::~TGeoVGConverter() {} //////////////////////////////////////////////////////////////////////////////// /// Main geometry conversion method. @@ -43,9 +41,9 @@ void TGeoVGConverter::ConvertGeometry() // First convert the top volume TGeoVolume *top = fGeom->GetMasterVolume(); TGeoVGShape *vgshape = nullptr; - if ( !top->GetShape()->IsVecGeom() ) + if (!top->GetShape()->IsVecGeom()) vgshape = TGeoVGShape::Create(top->GetShape()); - Int_t nconverted=0; + Int_t nconverted = 0; // If shape of top volume not known by VecGeom, keep old one if (vgshape) { nconverted++; @@ -57,7 +55,8 @@ void TGeoVGConverter::ConvertGeometry() while ((node = next.Next())) { TGeoVolume *vol = node->GetVolume(); // If shape not already converted, convert it - if ( vol->GetShape()->IsVecGeom() ) continue; + if (vol->GetShape()->IsVecGeom()) + continue; // printf("Converting %s\n", vol->GetName()); vgshape = TGeoVGShape::Create(vol->GetShape()); if (vgshape) { diff --git a/geom/vecgeom/src/TGeoVGShape.cxx b/geom/vecgeom/src/TGeoVGShape.cxx index 8b933fedf9285..c3a2188d82aa5 100644 --- a/geom/vecgeom/src/TGeoVGShape.cxx +++ b/geom/vecgeom/src/TGeoVGShape.cxx @@ -33,6 +33,11 @@ Bridge class for using a VecGeom solid as TGeoShape. #include "VecGeom/volumes/UnplacedScaledShape.h" #include "VecGeom/volumes/UnplacedGenTrap.h" #include "VecGeom/volumes/UnplacedSExtruVolume.h" +#include "VecGeom/volumes/UnplacedTessellated.h" +#include "VecGeom/volumes/UnplacedEllipticalTube.h" +#include "VecGeom/volumes/UnplacedHype.h" +#include "VecGeom/volumes/UnplacedCutTube.h" + #include "TError.h" #include "TGeoManager.h" #include "TGeoMaterial.h" @@ -54,6 +59,8 @@ Bridge class for using a VecGeom solid as TGeoShape. #include "TGeoTorus.h" #include "TGeoEltu.h" #include "TGeoXtru.h" +#include "TGeoTessellated.h" +#include "TGeoHype.h" //////////////////////////////////////////////////////////////////////////////// /// Default constructor @@ -122,6 +129,7 @@ vecgeom::cxx::Transformation3D *TGeoVGShape::Convert(TGeoMatrix const *const geo vecgeom::cxx::VUnplacedVolume *TGeoVGShape::Convert(TGeoShape const *const shape) { using namespace vecgeom; + using Vector3D = vecgeom::cxx::Vector3D; VUnplacedVolume *unplaced_volume = nullptr; // THE BOX @@ -287,20 +295,36 @@ vecgeom::cxx::VUnplacedVolume *TGeoVGShape::Convert(TGeoShape const *const shape GeoManager::MakeInstance(referenced_shape, scale_root[0], scale_root[1], scale_root[2]); } - // THE ELLIPTICAL TUBE AS SCALED TUBE + // THE CUT TUBE + if (shape->IsA() == TGeoCtub::Class()) { + TGeoCtub const *const p = static_cast(shape); + auto low = p->GetNlow(); + auto high = p->GetNhigh(); + auto const bottomNormal = Vector3D{low[0], low[1], low[2]}; + auto const topNormal = Vector3D{high[0], high[1], high[2]}; + + unplaced_volume = + GeoManager::MakeInstance(p->GetRmin(), p->GetRmax(), p->GetDz(), kDegToRad * p->GetPhi1(), + kDegToRad * (p->GetPhi2() - p->GetPhi1()), bottomNormal, topNormal); + } + + // THE ELLIPTICAL TUBE if (shape->IsA() == TGeoEltu::Class()) { TGeoEltu const *const p = static_cast(shape); - // Create the corresponding unplaced tube, with: - // rmin=0, rmax=A, dz=dz, which is scaled with (1., A/B, 1.) - GenericUnplacedTube *tubeUnplaced = new GenericUnplacedTube(0, p->GetA(), p->GetDZ(), 0, kTwoPi); - unplaced_volume = new UnplacedScaledShape(tubeUnplaced, 1., p->GetB() / p->GetA(), 1.); + unplaced_volume = GeoManager::MakeInstance(p->GetA(), p->GetB(), p->GetDz()); + } + + // THE HYPERBOLOID + if (shape->IsA() == TGeoHype::Class()) { + TGeoHype const *const p = static_cast(shape); + unplaced_volume = GeoManager::MakeInstance(p->GetRmin(), p->GetRmax(), kDegToRad * p->GetStIn(), + kDegToRad * p->GetStOut(), p->GetDz()); } // THE ARB8 if (shape->IsA() == TGeoArb8::Class() || shape->IsA() == TGeoGtra::Class()) { TGeoArb8 *p = (TGeoArb8 *)(shape); // Create the corresponding GenTrap - std::vector> vertexlist; const double *vertices = p->GetVertices(); Precision verticesx[8], verticesy[8]; for (auto ivert = 0; ivert < 8; ++ivert) { @@ -338,6 +362,32 @@ vecgeom::cxx::VUnplacedVolume *TGeoVGShape::Convert(TGeoShape const *const shape } } + // THE TESSELLATED + if (shape->IsA() == TGeoTessellated::Class()) { + TGeoTessellated const *const tsl = static_cast(shape); + unplaced_volume = GeoManager::MakeInstance(); + auto vtsl = static_cast(unplaced_volume); + + for (auto i = 0; i < tsl->GetNfacets(); ++i) { + auto const &facet = tsl->GetFacet(i); + int nvert = facet.GetNvert(); + auto const &v0 = facet.GetVertex(0); + auto const &v1 = facet.GetVertex(1); + auto const &v2 = facet.GetVertex(2); + if (nvert == 3) { + vtsl->AddTriangularFacet(Vector3D(v0[0], v0[1], v0[2]), Vector3D(v1[0], v1[1], v1[2]), + Vector3D(v2[0], v2[1], v2[2])); + } else if (nvert == 4) { + auto const &v3 = facet.GetVertex(3); + vtsl->AddQuadrilateralFacet(Vector3D(v0[0], v0[1], v0[2]), Vector3D(v1[0], v1[1], v1[2]), + Vector3D(v2[0], v2[1], v2[2]), Vector3D(v3[0], v3[1], v3[2])); + } else { + return nullptr; // should never happen + } + } + vtsl->Close(); + } + // New volumes should be implemented here... if (!unplaced_volume) { printf("Unsupported shape for ROOT shape \"%s\" of type %s. " diff --git a/geom/webviewer/CMakeLists.txt b/geom/webviewer/CMakeLists.txt index 78cb3252c2d8d..e29f4c004b34c 100644 --- a/geom/webviewer/CMakeLists.txt +++ b/geom/webviewer/CMakeLists.txt @@ -4,13 +4,20 @@ # For the licensing terms see $ROOTSYS/LICENSE. # For the list of contributors see $ROOTSYS/README/CREDITS. +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(ROOTGeomViewer HEADERS ROOT/RGeomData.hxx + ROOT/RGeomHierarchy.hxx ROOT/RGeomViewer.hxx ROOT/RGeoPainter.hxx SOURCES src/RGeomData.cxx + src/RGeomHierarchy.cxx src/RGeomViewer.cxx src/RGeoPainter.cxx DEPENDENCIES @@ -19,4 +26,5 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTGeomViewer RCsg ROOTWebDisplay ROOTBrowserv7 + ${EXTRA_DICT_OPTS} ) diff --git a/geom/webviewer/inc/LinkDef.h b/geom/webviewer/inc/LinkDef.h index 84ca142f0a5fe..5ac12cb44cf06 100644 --- a/geom/webviewer/inc/LinkDef.h +++ b/geom/webviewer/inc/LinkDef.h @@ -8,26 +8,25 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ - #ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class ROOT::Experimental::RGeomNodeBase+; -#pragma link C++ class ROOT::Experimental::RGeomNode+; -#pragma link C++ class ROOT::Experimental::RGeomVisible+; -#pragma link C++ class ROOT::Experimental::RGeomRenderInfo+; -#pragma link C++ class ROOT::Experimental::RGeomRawRenderInfo+; -#pragma link C++ class ROOT::Experimental::RGeomShapeRenderInfo; -#pragma link C++ class ROOT::Experimental::RGeomDescription+; -#pragma link C++ class ROOT::Experimental::RGeomDrawing+; -#pragma link C++ class ROOT::Experimental::RGeomRequest+; -#pragma link C++ class ROOT::Experimental::RGeomNodeInfo+; -#pragma link C++ class ROOT::Experimental::RGeomConfig+; -#pragma link C++ class ROOT::Experimental::RGeoPainter+; -#pragma link C++ class ROOT::Experimental::RGeomViewer+; - +#pragma link C++ class ROOT::RGeomNodeBase+; +#pragma link C++ class ROOT::RGeomNode+; +#pragma link C++ class ROOT::RGeoItem+; +#pragma link C++ class ROOT::RGeomVisible+; +#pragma link C++ class ROOT::RGeomRenderInfo+; +#pragma link C++ class ROOT::RGeomRawRenderInfo+; +#pragma link C++ class ROOT::RGeomShapeRenderInfo+; +#pragma link C++ class ROOT::RGeomDescription+; +#pragma link C++ class ROOT::RGeomDrawing+; +#pragma link C++ class ROOT::RGeomNodeInfo+; +#pragma link C++ class ROOT::RGeomConfig+; +#pragma link C++ class ROOT::RGeoPainter+; +#pragma link C++ class ROOT::RGeomHierarchy+; +#pragma link C++ class ROOT::RGeomViewer+; #endif diff --git a/geom/webviewer/inc/ROOT/RGeoPainter.hxx b/geom/webviewer/inc/ROOT/RGeoPainter.hxx index 80886ff92bd11..b799d1d3393a3 100644 --- a/geom/webviewer/inc/ROOT/RGeoPainter.hxx +++ b/geom/webviewer/inc/ROOT/RGeoPainter.hxx @@ -1,8 +1,7 @@ -// @(#)root/eve7:$Id$ // Author: Sergey Linev, 27.02.2020 /************************************************************************* - * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -17,7 +16,6 @@ #include namespace ROOT { -namespace Experimental { class RGeoPainter : public TVirtualGeoPainter { @@ -28,7 +26,7 @@ class RGeoPainter : public TVirtualGeoPainter { public: RGeoPainter(TGeoManager *manager); - virtual ~RGeoPainter(); + ~RGeoPainter() override; void AddSize3D(Int_t, Int_t, Int_t) override {} TVirtualGeoTrack *AddTrack(Int_t, Int_t, TObject *) override { return nullptr; } @@ -114,7 +112,6 @@ public: ClassDefOverride(RGeoPainter,0) // Web-based geo painter }; -} // namespace Experimental } // namespace ROOT diff --git a/geom/webviewer/inc/ROOT/RGeomData.hxx b/geom/webviewer/inc/ROOT/RGeomData.hxx index 735f543b02872..42edebe7956f1 100644 --- a/geom/webviewer/inc/ROOT/RGeomData.hxx +++ b/geom/webviewer/inc/ROOT/RGeomData.hxx @@ -1,8 +1,7 @@ -// @(#)root/geom/webviewer:$Id$ // Author: Sergey Linev, 14.12.2018 /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -17,6 +16,10 @@ #include #include +#include + +#include "TVirtualMutex.h" + class TGeoNode; class TGeoManager; class TGeoShape; @@ -26,10 +29,15 @@ class TGeoVolume; // do not use namespace to avoid too long JSON namespace ROOT { -namespace Experimental { class RGeomBrowserIter; + +namespace Experimental { class RLogChannel; +} // namespace Experimental + +/// Log channel for Geomviewer diagnostics. +Experimental::RLogChannel &RGeomLog(); /** Base description of geometry node, required only to build hierarchy */ @@ -41,12 +49,21 @@ public: int vis{0}; ///< visibility flag, 0 - off, 1 - only when level==0, 99 - always bool nochlds{false}; ///< how far in hierarchy depth should be scanned - std::string color; ///< rgb code without rgb() prefix + std::string color; ///< rgb code in hex format + std::string material; ///< name of the material int sortid{0}; /// 0; } + + /** Returns argument for regexp */ + const char *GetArg(int kind) + { + if (kind == 1) return color.c_str(); + if (kind == 2) return material.c_str(); + return name.c_str(); + } }; /** Full node description including matrices and other attributes */ @@ -66,6 +83,39 @@ public: bool CanDisplay() const { return (vol > 0.) && (nfaces > 0); } }; +/** \class RGeoItem +\ingroup rbrowser +\brief Representation of single item in the geometry browser +*/ + +class RGeoItem : public Browsable::RItem { + +protected: + // this is part for browser, visible for I/O + int id{0}; ///< node id + std::string color; ///< color + std::string material; ///< material + int vis{0}; ///< visibility of logical node + int pvis{0}; ///< visibility of physical node + bool top{false}; ///< indicates if node selected as top + +public: + + /** Default constructor */ + RGeoItem() = default; + + RGeoItem(const std::string &_name, int _nchilds, int _nodeid, const std::string &_color, + const std::string &_material = "", int _vis = 0, int _pvis = 0) : + Browsable::RItem(_name, _nchilds), id(_nodeid), color(_color), material(_material), vis(_vis), pvis(_pvis) { + } + + // should be here, one needs virtual table for correct streaming of RRootBrowserReply + ~RGeoItem() override = default; + + void SetTop(bool on = true) { top = on; } +}; + + /** Base class for render info block */ class RGeomRenderInfo { public: @@ -78,14 +128,14 @@ class RGeomRawRenderInfo : public RGeomRenderInfo { public: std::vector raw; ///< float vertices as raw data, JSON_base64 std::vector idx; ///< vertex indexes, always triangles - virtual ~RGeomRawRenderInfo() = default; + ~RGeomRawRenderInfo() override = default; }; /** Render info with shape itself - client can produce shape better */ class RGeomShapeRenderInfo : public RGeomRenderInfo { public: TGeoShape *shape{nullptr}; ///< original shape - can be much less than binary data - virtual ~RGeomShapeRenderInfo() = default; + ~RGeomShapeRenderInfo() override = default; }; @@ -133,14 +183,7 @@ public: }; -/** Request object send from client for different operations */ -class RGeomRequest { -public: - std::string oper; ///< operation like HIGHL or HOVER - std::vector path; ///< path parameter, used with HOVER - std::vector stack; ///< stack parameter, used with HIGHL -}; - +/** Node information including rendering data */ class RGeomNodeInfo { public: std::vector path; ///< full path to node @@ -152,8 +195,17 @@ public: RGeomRenderInfo *ri{nullptr}; ///< rendering information (if applicable) }; +/** Custom settings for physical Node visibility */ +class RGeomNodeVisibility { +public: + std::vector stack; ///< path to the node + bool visible{false}; ///< visible flag + RGeomNodeVisibility(const std::vector &_stack, bool _visible) : stack(_stack), visible(_visible) {} +}; + using RGeomScanFunc_t = std::function &, bool, int)>; +using RGeomSignalFunc_t = std::function; class RGeomDescription { @@ -188,20 +240,33 @@ class RGeomDescription { }; std::vector fNodes; /// fDesc; ///< converted description, send to client - TGeoVolume *fDrawVolume{nullptr}; /// fDesc; /// fVisibility; /// fSelectedStack; /// fHighlightedStack; /// fClickedStack; /// fSortMap; /// smaller volume std::vector fShapes; ///> fSignals; /// &arr, TGeoMatrix *matr); int MarkVisible(bool on_screen = false); @@ -216,9 +281,13 @@ class RGeomDescription { ShapeDescr &MakeShapeDescr(TGeoShape *shape); + int GetUsedNSegments(int min = 20); + + int CountShapeFaces(TGeoShape *shape); + void CopyMaterialProperties(TGeoVolume *vol, RGeomNode &node); - void CollectNodes(RGeomDrawing &drawing); + void CollectNodes(RGeomDrawing &drawing, bool all_nodes = false); std::string MakeDrawingJson(RGeomDrawing &drawing, bool has_shapes = false); @@ -228,55 +297,95 @@ class RGeomDescription { TGeoVolume *GetVolume(int nodeid); + int IsPhysNodeVisible(const std::vector &stack); + public: RGeomDescription() = default; - void Build(TGeoManager *mgr, const std::string &volname = ""); + void AddSignalHandler(const void *handler, RGeomSignalFunc_t func); - void Build(TGeoVolume *vol); + void RemoveSignalHandler(const void *handler); - /** Number of unique nodes in the geometry */ - int GetNumNodes() const { return fDesc.size(); } + void IssueSignal(const void *handler, const std::string &kind); - bool IsBuild() const { return GetNumNodes() > 0; } + /** Set mutex, it must be recursive one */ + void SetMutex(TVirtualMutex *mutex) { fMutex = mutex; } + /** Return currently used mutex */ + TVirtualMutex *GetMutex() const { return fMutex; } /** Set maximal number of nodes which should be selected for drawing */ - void SetMaxVisNodes(int cnt) { fCfg.maxnumnodes = cnt; } - + void SetMaxVisNodes(int cnt) { TLockGuard lock(fMutex); fCfg.maxnumnodes = cnt; } /** Returns maximal visible number of nodes, ignored when non-positive */ - int GetMaxVisNodes() const { return fCfg.maxnumnodes; } + int GetMaxVisNodes() const { TLockGuard lock(fMutex); return fCfg.maxnumnodes; } /** Set maximal number of faces which should be selected for drawing */ - void SetMaxVisFaces(int cnt) { fCfg.maxnumfaces = cnt; } - + void SetMaxVisFaces(int cnt) { TLockGuard lock(fMutex); fCfg.maxnumfaces = cnt; } /** Returns maximal visible number of faces, ignored when non-positive */ - int GetMaxVisFaces() const { return fCfg.maxnumfaces; } + int GetMaxVisFaces() const { TLockGuard lock(fMutex); return fCfg.maxnumfaces; } /** Set maximal visible level */ - void SetVisLevel(int lvl = 3) { fCfg.vislevel = lvl; } - + void SetVisLevel(int lvl = 3) { TLockGuard lock(fMutex); fCfg.vislevel = lvl; } /** Returns maximal visible level */ - int GetVisLevel() const { return fCfg.vislevel; } + int GetVisLevel() const { TLockGuard lock(fMutex); return fCfg.vislevel; } + + /** Set draw options as string for JSROOT TGeoPainter */ + void SetTopVisible(bool on = true) { TLockGuard lock(fMutex); fCfg.showtop = on; } + /** Returns draw options, used for JSROOT TGeoPainter */ + bool GetTopVisible() const { TLockGuard lock(fMutex); return fCfg.showtop; } + + /** Instruct to build binary 3D model already on the server (true) or send TGeoShape as is to client, which can build model itself */ + void SetBuildShapes(int lvl = 1) { TLockGuard lock(fMutex); fCfg.build_shapes = lvl; } + /** Returns true if binary 3D model build already by C++ server (default) */ + int IsBuildShapes() const { TLockGuard lock(fMutex); return fCfg.build_shapes; } + + /** Set number of segments for cylindrical shapes, if 0 - default value will be used */ + void SetNSegments(int n = 0) { TLockGuard lock(fMutex); fCfg.nsegm = n; } + /** Return of segments for cylindrical shapes, if 0 - default value will be used */ + int GetNSegments() const { TLockGuard lock(fMutex); return fCfg.nsegm; } + + /** Set draw options as string for JSROOT TGeoPainter */ + void SetDrawOptions(const std::string &opt = "") { TLockGuard lock(fMutex); fCfg.drawopt = opt; } + /** Returns draw options, used for JSROOT TGeoPainter */ + std::string GetDrawOptions() const { TLockGuard lock(fMutex); return fCfg.drawopt; } + + /** Set JSON compression level for data transfer */ + void SetJsonComp(int comp = 0) { TLockGuard lock(fMutex); fJsonComp = comp; } + /** Returns JSON compression level for data transfer */ + int GetJsonComp() const { TLockGuard lock(fMutex); return fJsonComp; } /** Set preference of offline operations. * Server provides more info to client from the begin on to avoid communication */ - void SetPreferredOffline(bool on) { fPreferredOffline = on; } - + void SetPreferredOffline(bool on) { TLockGuard lock(fMutex); fPreferredOffline = on; } /** Is offline operations preferred. * After get full description, client can do most operations without extra requests */ - bool IsPreferredOffline() const { return fPreferredOffline; } + bool IsPreferredOffline() const { TLockGuard lock(fMutex); return fPreferredOffline; } + + + void Build(TGeoManager *mgr, const std::string &volname = ""); + + void Build(TGeoVolume *vol); - std::string ProduceJson(); + /** Number of unique nodes in the geometry */ + int GetNumNodes() const { TLockGuard lock(fMutex); return fDesc.size(); } + + bool IsBuild() const { return GetNumNodes() > 0; } + + std::string ProduceJson(bool all_nodes = false); bool IsPrincipalEndNode(int nodeid); std::string ProcessBrowserRequest(const std::string &req = ""); - bool HasDrawData() const { return (fDrawJson.length() > 0) && (fDrawIdCut > 0); } + bool HasDrawData() const; void ProduceDrawData(); - const std::string &GetDrawJson() const { return fDrawJson; } + void ProduceSearchData(); + std::string GetDrawJson() const { TLockGuard lock(fMutex); return fDrawJson; } + std::string GetSearch() const { TLockGuard lock(fMutex); return fSearch; } + std::string GetSearchJson() const { TLockGuard lock(fMutex); return fSearchJson; } void ClearDrawData(); + void ClearCache(); + int SearchVisibles(const std::string &find, std::string &hjson, std::string &json); int FindNodeId(const std::vector &stack); @@ -293,44 +402,69 @@ public: bool ProduceDrawingFor(int nodeid, std::string &json, bool check_volume = false); - bool ChangeNodeVisibility(int nodeid, bool selected); + bool SetHighlightedItem(const std::vector &stack) + { + TLockGuard lock(fMutex); + bool changed = fHighlightedStack != stack; + fHighlightedStack = stack; + return changed; + } + + std::vector GetHighlightedItem() const + { + TLockGuard lock(fMutex); + return fHighlightedStack; + } + + bool SetClickedItem(const std::vector &stack) + { + TLockGuard lock(fMutex); + bool changed = fClickedStack != stack; + fClickedStack = stack; + return changed; + } + + std::vector GetClickedItem() const + { + TLockGuard lock(fMutex); + return fClickedStack; + } + + bool SetActiveItem(const std::string &itemname) + { + TLockGuard lock(fMutex); + bool changed = (fActiveItemName != itemname); + fActiveItemName = itemname; + return changed; + } + + std::string GetActiveItem() const + { + TLockGuard lock(fMutex); + return fActiveItemName; + } - /** Set number of segments for cylindrical shapes, if 0 - default value will be used */ - void SetNSegments(int n = 0) { fCfg.nsegm = n; } - /** Return of segments for cylindrical shapes, if 0 - default value will be used */ - int GetNSegments() const { return fCfg.nsegm; } + bool ChangeConfiguration(const std::string &json); - /** Set JSON compression level for data transfer */ - void SetJsonComp(int comp = 0) { fJsonComp = comp; } - /** Returns JSON compression level for data transfer */ - int GetJsonComp() const { return fJsonComp; } + std::unique_ptr MakeNodeInfo(const std::vector &stack); - /** Set draw options as string for JSROOT TGeoPainter */ - void SetDrawOptions(const std::string &opt = "") { fCfg.drawopt = opt; } - /** Returns draw options, used for JSROOT TGeoPainter */ - std::string GetDrawOptions() const { return fCfg.drawopt; } + bool ChangeNodeVisibility(const std::vector &path, bool on); - /** Set draw options as string for JSROOT TGeoPainter */ - void SetTopVisible(bool on = true) { fCfg.showtop = on; } - /** Returns draw options, used for JSROOT TGeoPainter */ - bool GetTopVisible() const { return fCfg.showtop; } + bool SelectTop(const std::vector &path); - /** Instruct to build binary 3D model already on the server (true) or send TGeoShape as is to client, which can build model itself */ - void SetBuildShapes(int lvl = 1) { fCfg.build_shapes = lvl; } - /** Returns true if binary 3D model build already by C++ server (default) */ - int IsBuildShapes() const { return fCfg.build_shapes; } + bool SetPhysNodeVisibility(const std::vector &path, bool on = true); - bool ChangeConfiguration(const std::string &json); + bool SetPhysNodeVisibility(const std::string &path, bool on = true); - std::unique_ptr MakeNodeInfo(const std::vector &path); -}; + bool ClearPhysNodeVisibility(const std::vector &path); + bool ClearAllPhysVisibility(); -/// Log channel for Eve diagnostics. -RLogChannel &RGeomLog(); + bool SetSearch(const std::string &query, const std::string &json); + void SavePrimitive(std::ostream &fs, const std::string &name); +}; -} // namespace Experimental } // namespace ROOT #endif diff --git a/geom/webviewer/inc/ROOT/RGeomHierarchy.hxx b/geom/webviewer/inc/ROOT/RGeomHierarchy.hxx new file mode 100644 index 0000000000000..b1b685eeeedd9 --- /dev/null +++ b/geom/webviewer/inc/ROOT/RGeomHierarchy.hxx @@ -0,0 +1,55 @@ +// Author: Sergey Linev, 3.03.2023 + +/************************************************************************* + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#ifndef ROOT7_RGeomHierarchy +#define ROOT7_RGeomHierarchy + +#include +#include + +#include + +class TGeoManager; +class TGeoVolume; + +namespace ROOT { + +class RWebWindow; + +class RGeomHierarchy { + +protected: + + RGeomDescription &fDesc; /// fWebWindow; /// &handle); +}; + +} // namespace ROOT + +#endif diff --git a/geom/webviewer/inc/ROOT/RGeomViewer.hxx b/geom/webviewer/inc/ROOT/RGeomViewer.hxx index cda842607f17a..67a7073b8611e 100644 --- a/geom/webviewer/inc/ROOT/RGeomViewer.hxx +++ b/geom/webviewer/inc/ROOT/RGeomViewer.hxx @@ -1,8 +1,7 @@ -// @(#)root/eve7:$Id$ // Author: Sergey Linev, 13.12.2018 /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -21,9 +20,9 @@ class TGeoManager; class TGeoVolume; namespace ROOT { -namespace Experimental { class RWebWindow; +class RGeomHierarchy; class RGeomViewer { @@ -31,17 +30,25 @@ protected: TGeoManager *fGeoManager{nullptr}; /// fWebWindow; /// fWebHierarchy; /// GetStackFromJson(const std::string &json, bool node_ids = false); - void SendGeometry(unsigned connid); + void SendGeometry(unsigned connid = 0, bool first_time = false); + + void ProcessSignal(const std::string &); public: @@ -83,6 +90,10 @@ public: /** Returns default hierarchy browser visibility */ bool GetShowHierarchy() const { return fShowHierarchy; } + void SetShowColumns(bool on = true) { fShowColumns = on; } + + bool GetShowColumns() const { return fShowColumns; } + void SetDrawOptions(const std::string &opt); void Show(const RWebDisplayArgs &args = "", bool always_start_new_browser = false); @@ -91,9 +102,14 @@ public: void SaveImage(const std::string &fname = "geometry.png", int width = 0, int height = 0); + RGeomDescription &Description() { return fDesc; } + + void SaveAsMacro(const std::string &fname); + + void ClearOnClose(const std::shared_ptr &handle); + }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/geom/webviewer/src/RGeoPainter.cxx b/geom/webviewer/src/RGeoPainter.cxx index 1ab837275e233..2250a8d79a563 100644 --- a/geom/webviewer/src/RGeoPainter.cxx +++ b/geom/webviewer/src/RGeoPainter.cxx @@ -1,8 +1,7 @@ -// @(#)root/eve7:$Id$ // Author: Sergey Linev, 27.02.2020 /************************************************************************* - * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -15,7 +14,7 @@ #include "TGeoManager.h" #include "TVirtualPad.h" -using namespace ROOT::Experimental; +using namespace ROOT; RGeoPainter::RGeoPainter(TGeoManager *manager) : TVirtualGeoPainter(manager) { @@ -23,16 +22,13 @@ RGeoPainter::RGeoPainter(TGeoManager *manager) : TVirtualGeoPainter(manager) fGeoManager = manager; } -RGeoPainter::~RGeoPainter() -{ -} +RGeoPainter::~RGeoPainter() {} void RGeoPainter::SetTopVisible(Bool_t on) { fTopVisible = on ? 1 : 0; } - void RGeoPainter::SetGeoManager(TGeoManager *mgr) { if (fViewer && (fGeoManager != mgr)) @@ -55,7 +51,6 @@ void RGeoPainter::DrawVolume(TGeoVolume *vol, Option_t *opt) return; } - if (!fViewer) fViewer = std::make_shared(fGeoManager); @@ -63,7 +58,7 @@ void RGeoPainter::DrawVolume(TGeoVolume *vol, Option_t *opt) fViewer->SetGeometry(fGeoManager, vol->GetName()); std::string drawopt = ""; - if (opt && strstr(opt,"s")) + if (opt && strstr(opt, "s")) drawopt = "wire"; // specify JSROOT draw options - here clipping on X,Y,Z axes @@ -72,7 +67,6 @@ void RGeoPainter::DrawVolume(TGeoVolume *vol, Option_t *opt) if (fTopVisible >= 0) fViewer->SetTopVisible(fTopVisible > 0); - // set default limits for number of visible nodes and faces // when viewer created, initial values exported from TGeoManager // viewer->SetLimits(); diff --git a/geom/webviewer/src/RGeomData.cxx b/geom/webviewer/src/RGeomData.cxx index b7137b46f060b..52e02d2f66748 100644 --- a/geom/webviewer/src/RGeomData.cxx +++ b/geom/webviewer/src/RGeomData.cxx @@ -1,8 +1,7 @@ -// @(#)root/eve7:$Id$ // Author: Sergey Linev, 14.12.2018 /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -22,28 +21,40 @@ #include "TGeoNode.h" #include "TGeoVolume.h" #include "TGeoBBox.h" +#include "TGeoSphere.h" +#include "TGeoCone.h" +#include "TGeoTube.h" +#include "TGeoEltu.h" +#include "TGeoTorus.h" +#include "TGeoPcon.h" +#include "TGeoPgon.h" +#include "TGeoXtru.h" +#include "TGeoParaboloid.h" +#include "TGeoHype.h" +#include "TGeoTessellated.h" +#include "TGeoScaledShape.h" +#include "TGeoCompositeShape.h" #include "TGeoManager.h" #include "TGeoMatrix.h" #include "TGeoMedium.h" #include "TGeoMaterial.h" #include "TGeoBoolNode.h" -#include "TGeoCompositeShape.h" #include "TBuffer3D.h" #include "TBufferJSON.h" +#include "TRegexp.h" #include +#include -namespace ROOT { -namespace Experimental { - - -RLogChannel &RGeomLog() +ROOT::Experimental::RLogChannel &ROOT::RGeomLog() { - static RLogChannel sLog("ROOT.Geom"); + static ROOT::Experimental::RLogChannel sLog("ROOT.Geom"); return sLog; } +namespace ROOT { + /** Iterator of hierarchical geometry structures */ class RGeomBrowserIter { @@ -57,11 +68,16 @@ class RGeomBrowserIter { std::vector fStackChilds; public: - RGeomBrowserIter(RGeomDescription &desc) : fDesc(desc) {} const std::string &GetName() const { return fDesc.fDesc[fNodeId].name; } + const std::string &GetColor() const { return fDesc.fDesc[fNodeId].color; } + + const std::string &GetMaterial() const { return fDesc.fDesc[fNodeId].material; } + + int GetVisible() const { return fDesc.fDesc[fNodeId].vis; } + bool IsValid() const { return fNodeId >= 0; } int GetNodeId() const { return fNodeId; } @@ -78,11 +94,12 @@ class RGeomBrowserIter { return true; } - if (fNodeId >= (int) fDesc.fDesc.size()) + if (fNodeId >= (int)fDesc.fDesc.size()) return false; auto &node = fDesc.fDesc[fNodeId]; - if (node.chlds.size() == 0) return false; + if (node.chlds.size() == 0) + return false; fStackParents.emplace_back(fParentId); fStackChilds.emplace_back(fChild); fParentId = fNodeId; @@ -142,12 +159,15 @@ class RGeomBrowserIter { bool NextNode() { - if (Enter()) return true; + if (Enter()) + return true; - if (Next()) return true; + if (Next()) + return true; while (Leave()) { - if (Next()) return true; + if (Next()) + return true; } return false; @@ -157,7 +177,8 @@ class RGeomBrowserIter { bool Navigate(const std::string &path) { size_t pos = path.find("/"); - if (pos != 0) return false; + if (pos != 0) + return false; Reset(); // set to the top of element @@ -166,11 +187,13 @@ class RGeomBrowserIter { pos = path.find("/", last); - if (pos == std::string::npos) pos = path.length(); + if (pos == std::string::npos) + pos = path.length(); - std::string folder = path.substr(last, pos-last); + std::string folder = path.substr(last, pos - last); - if (!Enter()) return false; + if (!Enter()) + return false; bool find = false; @@ -178,7 +201,8 @@ class RGeomBrowserIter { find = (folder.compare(GetName()) == 0); } while (!find && Next()); - if (!find) return false; + if (!find) + return false; } return true; @@ -191,7 +215,8 @@ class RGeomBrowserIter { for (auto &folder : path) { - if (!Enter()) return false; + if (!Enter()) + return false; bool find = false; @@ -199,35 +224,111 @@ class RGeomBrowserIter { find = (folder.compare(GetName()) == 0); } while (!find && Next()); - if (!find) return false; + if (!find) + return false; } return true; } + /** Navigate to specified volume - find first occurrence */ + bool Navigate(TGeoVolume *vol) + { + Reset(); + + while (NextNode()) { + if (vol == fDesc.GetVolume(GetNodeId())) + return true; + } + + return false; + } /// Returns array of ids to currently selected node std::vector CurrentIds() const { std::vector res; if (IsValid()) { - for (unsigned n=1;n= 0) res.emplace_back(fParentId); + if (fParentId >= 0) + res.emplace_back(fParentId); res.emplace_back(fNodeId); } return res; } - }; -} // namespace Experimental -} // namespace ROOT +} // namespace ROOT -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; +namespace { + +int compare_stacks(const std::vector &stack1, const std::vector &stack2) +{ + unsigned len1 = stack1.size(), len2 = stack2.size(), len = (len1 < len2) ? len1 : len2, indx = 0; + while (indx < len) { + if (stack1[indx] < stack2[indx]) + return -1; + if (stack1[indx] > stack2[indx]) + return 1; + ++indx; + } + + if (len1 < len2) + return -1; + if (len1 > len2) + return 1; + + return 0; +} +} // namespace + +///////////////////////////////////////////////////////////////////// +/// Issue signal, which distributed on all handlers - excluding source handler + +void RGeomDescription::IssueSignal(const void *handler, const std::string &kind) +{ + std::vector funcs; + + { + TLockGuard lock(fMutex); + for (auto &pair : fSignals) + if (!handler || (pair.first != handler)) + funcs.emplace_back(pair.second); + } + + // invoke signal outside locked mutex to avoid any locking + for (auto func : funcs) + func(kind); +} + +///////////////////////////////////////////////////////////////////// +/// Add signal handler + +void RGeomDescription::AddSignalHandler(const void *handler, RGeomSignalFunc_t func) +{ + TLockGuard lock(fMutex); + fSignals.emplace_back(handler, func); +} + +///////////////////////////////////////////////////////////////////// +/// Remove signal handler + +void RGeomDescription::RemoveSignalHandler(const void *handler) +{ + TLockGuard lock(fMutex); + + for (auto iter = fSignals.begin(); iter != fSignals.end(); ++iter) + if (handler == iter->first) { + fSignals.erase(iter); + return; + } +} + ///////////////////////////////////////////////////////////////////// /// Pack matrix into vector, which can be send to client /// Following sizes can be used for vector: @@ -248,20 +349,19 @@ void RGeomDescription::PackMatrix(std::vector &vect, TGeoMatrix *matr) auto scale = matr->GetScale(); auto rotate = matr->GetRotationMatrix(); - bool is_translate = matr->IsA() == TGeoTranslation::Class(), - is_scale = matr->IsA() == TGeoScale::Class(), + bool is_translate = matr->IsA() == TGeoTranslation::Class(), is_scale = matr->IsA() == TGeoScale::Class(), is_rotate = matr->IsA() == TGeoRotation::Class(); if (!is_translate && !is_scale && !is_rotate) { // check if trivial matrix - auto test = [](double val, double chk) { return (val==chk) || (TMath::Abs(val-chk) < 1e-20); }; + auto test = [](double val, double chk) { return (val == chk) || (TMath::Abs(val - chk) < 1e-20); }; - bool no_scale = test(scale[0],1) && test(scale[1],1) && test(scale[2],1); - bool no_trans = test(trans[0],0) && test(trans[1],0) && test(trans[2],0); - bool no_rotate = test(rotate[0],1) && test(rotate[1],0) && test(rotate[2],0) && - test(rotate[3],0) && test(rotate[4],1) && test(rotate[5],0) && - test(rotate[6],0) && test(rotate[7],0) && test(rotate[8],1); + bool no_scale = test(scale[0], 1) && test(scale[1], 1) && test(scale[2], 1); + bool no_trans = test(trans[0], 0) && test(trans[1], 0) && test(trans[2], 0); + bool no_rotate = test(rotate[0], 1) && test(rotate[1], 0) && test(rotate[2], 0) && test(rotate[3], 0) && + test(rotate[4], 1) && test(rotate[5], 0) && test(rotate[6], 0) && test(rotate[7], 0) && + test(rotate[8], 1); if (no_scale && no_trans && no_rotate) return; @@ -294,16 +394,28 @@ void RGeomDescription::PackMatrix(std::vector &vect, TGeoMatrix *matr) if (is_rotate) { vect.resize(9); - for (int n=0;n<9;++n) + for (int n = 0; n < 9; ++n) vect[n] = rotate[n]; return; } vect.resize(16); - vect[0] = rotate[0]; vect[4] = rotate[1]; vect[8] = rotate[2]; vect[12] = trans[0]; - vect[1] = rotate[3]; vect[5] = rotate[4]; vect[9] = rotate[5]; vect[13] = trans[1]; - vect[2] = rotate[6]; vect[6] = rotate[7]; vect[10] = rotate[8]; vect[14] = trans[2]; - vect[3] = 0; vect[7] = 0; vect[11] = 0; vect[15] = 1; + vect[0] = rotate[0]; + vect[4] = rotate[1]; + vect[8] = rotate[2]; + vect[12] = trans[0]; + vect[1] = rotate[3]; + vect[5] = rotate[4]; + vect[9] = rotate[5]; + vect[13] = trans[1]; + vect[2] = rotate[6]; + vect[6] = rotate[7]; + vect[10] = rotate[8]; + vect[14] = trans[2]; + vect[3] = 0; + vect[7] = 0; + vect[11] = 0; + vect[15] = 1; } ///////////////////////////////////////////////////////////////////// @@ -313,21 +425,10 @@ void RGeomDescription::PackMatrix(std::vector &vect, TGeoMatrix *matr) void RGeomDescription::Build(TGeoManager *mgr, const std::string &volname) { ClearDescription(); - if (!mgr) return; - - auto topnode = mgr->GetTopNode(); + if (!mgr) + return; - if (!volname.empty()) { - auto vol = mgr->GetVolume(volname.c_str()); - if (vol) { - TGeoNode *node; - TGeoIterator next(mgr->GetTopVolume()); - while ((node = next()) != nullptr) { - if (node->GetVolume() == vol) break; - } - if (node) topnode = node; - } - } + TLockGuard lock(fMutex); // by top node visibility always enabled and harm logic // later visibility can be controlled by other means @@ -338,9 +439,18 @@ void RGeomDescription::Build(TGeoManager *mgr, const std::string &volname) SetNSegments(mgr->GetNsegments()); SetVisLevel(mgr->GetVisLevel()); SetMaxVisNodes(maxnodes); - SetMaxVisFaces( (maxnodes > 5000 ? 5000 : (maxnodes < 1000 ? 1000 : maxnodes)) * 100); + SetMaxVisFaces((maxnodes > 5000 ? 5000 : (maxnodes < 1000 ? 1000 : maxnodes)) * 100); + + auto topnode = mgr->GetTopNode(); BuildDescription(topnode, topnode->GetVolume()); + + if (!volname.empty()) { + auto vol = mgr->GetVolume(volname.c_str()); + RGeomBrowserIter iter(*this); + if (vol && (vol != topnode->GetVolume()) && iter.Navigate(vol)) + fSelectedStack = MakeStackByIds(iter.CurrentIds()); + } } ///////////////////////////////////////////////////////////////////// @@ -350,11 +460,15 @@ void RGeomDescription::Build(TGeoManager *mgr, const std::string &volname) void RGeomDescription::Build(TGeoVolume *vol) { ClearDescription(); + if (!vol) + return; - if (!vol) return; + TLockGuard lock(fMutex); fDrawVolume = vol; + fSelectedStack.clear(); + BuildDescription(nullptr, fDrawVolume); } @@ -363,12 +477,15 @@ void RGeomDescription::Build(TGeoVolume *vol) void RGeomDescription::ClearDescription() { + TLockGuard lock(fMutex); + fDesc.clear(); fNodes.clear(); fSortMap.clear(); ClearDrawData(); fDrawIdCut = 0; fDrawVolume = nullptr; + fSelectedStack.clear(); } ///////////////////////////////////////////////////////////////////// @@ -398,7 +515,6 @@ void RGeomDescription::BuildDescription(TGeoNode *topnode, TGeoVolume *topvolume } while ((snode = iter()) != nullptr); fDesc.reserve(fNodes.size()); - numbers.reserve(fNodes.size()); fSortMap.reserve(fNodes.size()); // array for sorting @@ -420,8 +536,9 @@ void RGeomDescription::BuildDescription(TGeoNode *topnode, TGeoVolume *topvolume auto shape = dynamic_cast(vol->GetShape()); if (shape) { - desc.vol = shape->GetDX() * shape->GetDY() * shape->GetDZ(); - desc.nfaces = 12; // TODO: get better value for each shape - excluding composite + desc.vol = TMath::Sqrt(shape->GetDX() * shape->GetDX() + shape->GetDY() * shape->GetDY() + + shape->GetDZ() * shape->GetDZ()); + desc.nfaces = CountShapeFaces(shape); } CopyMaterialProperties(vol, desc); @@ -432,7 +549,7 @@ void RGeomDescription::BuildDescription(TGeoNode *topnode, TGeoVolume *topvolume if (chlds) for (int n = 0; n <= chlds->GetLast(); ++n) { - auto chld = dynamic_cast (chlds->At(n)); + auto chld = dynamic_cast(chlds->At(n)); desc.chlds.emplace_back(chld->GetNumber() - offset); } } @@ -441,14 +558,15 @@ void RGeomDescription::BuildDescription(TGeoNode *topnode, TGeoVolume *topvolume cnt = 0; for (auto node : fNodes) { auto number = numbers[cnt++]; - if (node) node->SetNumber(number); + if (node) + node->SetNumber(number); } // sort in volume descent order - std::sort(sortarr.begin(), sortarr.end(), [](RGeomNode *a, RGeomNode * b) { return a->vol > b->vol; }); + std::sort(sortarr.begin(), sortarr.end(), [](RGeomNode *a, RGeomNode *b) { return a->vol > b->vol; }); cnt = 0; - for (auto &elem: sortarr) { + for (auto &elem : sortarr) { fSortMap.emplace_back(elem->id); elem->sortid = cnt++; // keep place in sorted array to correctly apply cut } @@ -465,7 +583,8 @@ void RGeomDescription::BuildDescription(TGeoNode *topnode, TGeoVolume *topvolume TGeoVolume *RGeomDescription::GetVolume(int nodeid) { auto node = fNodes[nodeid]; - if (node) return node->GetVolume(); + if (node) + return node->GetVolume(); return nodeid == 0 ? fDrawVolume : nullptr; } @@ -475,7 +594,7 @@ TGeoVolume *RGeomDescription::GetVolume(int nodeid) int RGeomDescription::MarkVisible(bool on_screen) { int res = 0; - for (int nodeid = 0; nodeid < (int) fNodes.size(); nodeid++) { + for (int nodeid = 0; nodeid < (int)fNodes.size(); nodeid++) { auto node = fNodes[nodeid]; auto vol = GetVolume(nodeid); @@ -497,7 +616,8 @@ int RGeomDescription::MarkVisible(bool on_screen) desc.vis = 1; } - if (desc.IsVisible() && desc.CanDisplay()) res++; + if (desc.IsVisible() && desc.CanDisplay()) + res++; } return res; @@ -516,7 +636,7 @@ void RGeomDescription::ProduceIdShifts() ScanFunc_t scan_func = [&, this](RGeomNode &node) { if (node.idshift < 0) { node.idshift = 0; - for(auto id : node.chlds) + for (auto id : node.chlds) node.idshift += scan_func(fDesc[id]); } @@ -532,22 +652,37 @@ void RGeomDescription::ProduceIdShifts() int RGeomDescription::ScanNodes(bool only_visible, int maxlvl, RGeomScanFunc_t func) { - if (fDesc.empty()) return 0; + if (fDesc.empty()) + return 0; std::vector stack; stack.reserve(25); // reserve enough space for most use-cases int counter = 0; + auto viter = fVisibility.begin(); - using ScanFunc_t = std::function; + using ScanFunc_t = std::function; + + ScanFunc_t scan_func = [&, this](int nodeid, int lvl, bool is_inside) { + if (!is_inside && (fSelectedStack == stack)) + is_inside = true; - ScanFunc_t scan_func = [&, this](int nodeid, int lvl) { auto &desc = fDesc[nodeid]; + auto desc_vis = desc.vis; int res = 0; - if (desc.nochlds && (lvl > 0)) lvl = 0; + if (desc.nochlds && (lvl > 0)) + lvl = 0; + + bool can_display = desc.CanDisplay(), scan_childs = true; + + if ((viter != fVisibility.end()) && (compare_stacks(viter->stack, stack) == 0)) { + can_display = scan_childs = viter->visible; + desc_vis = !viter->visible ? 0 : (desc.chlds.size() > 0 ? 1 : 99); + viter++; + } // same logic as in JSROOT ClonedNodes.scanVisible - bool is_visible = (lvl >= 0) && (desc.vis > lvl) && desc.CanDisplay(); + bool is_visible = (lvl >= 0) && (desc_vis > lvl) && can_display && is_inside; if (is_visible || !only_visible) if (func(desc, stack, is_visible, counter)) @@ -555,12 +690,12 @@ int RGeomDescription::ScanNodes(bool only_visible, int maxlvl, RGeomScanFunc_t f counter++; // count sequence id of current position in scan, will be used later for merging drawing lists - if ((desc.chlds.size() > 0) && ((lvl > 0) || !only_visible)) { + if ((desc.chlds.size() > 0) && (((lvl > 0) && scan_childs) || !only_visible)) { auto pos = stack.size(); stack.emplace_back(0); for (unsigned k = 0; k < desc.chlds.size(); ++k) { stack[pos] = k; // stack provides index in list of childs - res += scan_func(desc.chlds[k], lvl - 1); + res += scan_func(desc.chlds[k], is_inside ? lvl - 1 : lvl, is_inside); } stack.pop_back(); } else { @@ -570,26 +705,35 @@ int RGeomDescription::ScanNodes(bool only_visible, int maxlvl, RGeomScanFunc_t f return res; }; - if (!maxlvl && (GetVisLevel() > 0)) maxlvl = GetVisLevel(); - if (!maxlvl) maxlvl = 4; - if (maxlvl > 97) maxlvl = 97; // check while vis property of node is 99 normally + if (!maxlvl && (GetVisLevel() > 0)) + maxlvl = GetVisLevel(); + if (!maxlvl) + maxlvl = 4; + if (maxlvl > 97) + maxlvl = 97; // check while vis property of node is 99 normally - return scan_func(0, maxlvl); + return scan_func(0, maxlvl, false); } ///////////////////////////////////////////////////////////////////// /// Collect nodes which are used in visibles -void RGeomDescription::CollectNodes(RGeomDrawing &drawing) +void RGeomDescription::CollectNodes(RGeomDrawing &drawing, bool all_nodes) { - // TODO: for now reset all flags, later can be kept longer - for (auto &node : fDesc) - node.useflag = false; - drawing.cfg = &fCfg; drawing.numnodes = fDesc.size(); + if (all_nodes) { + for (auto &node : fDesc) + drawing.nodes.emplace_back(&node); + return; + } + + // TODO: for now reset all flags, later can be kept longer + for (auto &node : fDesc) + node.useflag = false; + for (auto &item : drawing.visibles) { int nodeid = 0; for (auto &chindx : item.stack) { @@ -603,6 +747,9 @@ void RGeomDescription::CollectNodes(RGeomDrawing &drawing) nodeid = node.chlds[chindx]; } + if (nodeid != item.nodeid) + printf("Nodeid mismatch %d != %d when extracting nodes for visibles\n", nodeid, item.nodeid); + auto &node = fDesc[nodeid]; if (!node.useflag) { node.useflag = true; @@ -619,6 +766,8 @@ void RGeomDescription::CollectNodes(RGeomDrawing &drawing) std::string RGeomDescription::ProcessBrowserRequest(const std::string &msg) { + TLockGuard lock(fMutex); + std::string res; auto request = TBufferJSON::FromJSON(msg); @@ -638,19 +787,20 @@ std::string RGeomDescription::ProcessBrowserRequest(const std::string &msg) int cnt = 0; for (auto &item : fDesc) - vect[cnt++]= &item; + vect[cnt++] = &item; - res = "DESCR:"s + TBufferJSON::ToJSON(&vect,GetJsonComp()).Data(); + res = "DESCR:"s + TBufferJSON::ToJSON(&vect, GetJsonComp()).Data(); - // example how iterator can be used - RGeomBrowserIter iter(*this); - int nelements = 0; - while (iter.NextNode()) - nelements++; + if (fVisibility.size() > 0) { + res += ":__PHYSICAL_VISIBILITY__:"; + res += TBufferJSON::ToJSON(&fVisibility, GetJsonComp()).Data(); + } + + res += ":__SELECTED_STACK__:"; + res += TBufferJSON::ToJSON(&fSelectedStack, GetJsonComp()).Data(); - // printf("Total number of valid nodes %d\n", nelements); } else { - std::vector temp_nodes; + std::vector temp_nodes; bool toplevel = request->path.empty(); // create temporary object for the short time @@ -669,11 +819,24 @@ std::string RGeomDescription::ProcessBrowserRequest(const std::string &msg) request->first--; } + // first element + auto stack = MakeStackByIds(iter.CurrentIds()); + while (iter.IsValid() && (request->number > 0)) { - temp_nodes.emplace_back(iter.GetName(), iter.NumChilds()); - if (toplevel) temp_nodes.back().SetExpanded(true); + int pvis = IsPhysNodeVisible(stack); + temp_nodes.emplace_back(iter.GetName(), iter.NumChilds(), iter.GetNodeId(), iter.GetColor(), + iter.GetMaterial(), iter.GetVisible(), pvis < 0 ? iter.GetVisible() : pvis); + if (toplevel) + temp_nodes.back().SetExpanded(true); + if (stack == fSelectedStack) + temp_nodes.back().SetTop(true); request->number--; - if (!iter.Next()) break; + + if (stack.size() > 0) + stack[stack.size() - 1]++; + + if (!iter.Next()) + break; } } } @@ -703,13 +866,12 @@ RGeomDescription::ShapeDescr &RGeomDescription::FindShapeDescr(TGeoShape *shape) return elem; } - //////////////////////////////////////////////////////////////////////// /// Function produces mesh for provided shape, applying matrix to the result std::unique_ptr MakeGeoMesh(TGeoMatrix *matr, TGeoShape *shape) { - TGeoCompositeShape *comp = dynamic_cast (shape); + TGeoCompositeShape *comp = dynamic_cast(shape); std::unique_ptr res; @@ -720,10 +882,10 @@ std::unique_ptr MakeGeoMesh(TGeoMatrix *matr, TGeoShape *sha Double_t *v = b3d->fPnts; Double_t buf[3]; for (UInt_t i = 0; i < b3d->NbPnts(); ++i) { - buf[0] = v[i*3]; - buf[1] = v[i*3+1]; - buf[2] = v[i*3+2]; - matr->LocalToMaster(buf, &v[i*3]); + buf[0] = v[i * 3]; + buf[1] = v[i * 3 + 1]; + buf[2] = v[i * 3 + 2]; + matr->LocalToMaster(buf, &v[i * 3]); } } @@ -732,7 +894,10 @@ std::unique_ptr MakeGeoMesh(TGeoMatrix *matr, TGeoShape *sha auto node = comp->GetBoolNode(); TGeoHMatrix mleft, mright; - if (matr) { mleft = *matr; mright = *matr; } + if (matr) { + mleft = *matr; + mright = *matr; + } mleft.Multiply(node->GetLeftMatrix()); auto left = MakeGeoMesh(&mleft, node->GetLeftShape()); @@ -740,14 +905,164 @@ std::unique_ptr MakeGeoMesh(TGeoMatrix *matr, TGeoShape *sha mright.Multiply(node->GetRightMatrix()); auto right = MakeGeoMesh(&mright, node->GetRightShape()); - if (node->IsA() == TGeoUnion::Class()) res.reset(RootCsg::BuildUnion(left.get(), right.get())); - if (node->IsA() == TGeoIntersection::Class()) res.reset(RootCsg::BuildIntersection(left.get(), right.get())); - if (node->IsA() == TGeoSubtraction::Class()) res.reset(RootCsg::BuildDifference(left.get(), right.get())); + if (node->IsA() == TGeoUnion::Class()) + res.reset(RootCsg::BuildUnion(left.get(), right.get())); + if (node->IsA() == TGeoIntersection::Class()) + res.reset(RootCsg::BuildIntersection(left.get(), right.get())); + if (node->IsA() == TGeoSubtraction::Class()) + res.reset(RootCsg::BuildDifference(left.get(), right.get())); } return res; } +///////////////////////////////////////////////////////////////////// +/// Returns really used number of cylindrical segments + +int RGeomDescription::GetUsedNSegments(int min) +{ + int nsegm = 0; + + if (GetNSegments() > 0) + nsegm = GetNSegments(); + else if (gGeoManager && (gGeoManager->GetNsegments() > 0)) + nsegm = gGeoManager->GetNsegments(); + + return nsegm > min ? nsegm : min; +} + +///////////////////////////////////////////////////////////////////// +/// Count number of faces for the shape + +int RGeomDescription::CountShapeFaces(TGeoShape *shape) +{ + if (!shape) + return 0; + + auto countTubeFaces = [this](const std::array &outerR, const std::array &innerR, + Double_t thetaLength = 360.) -> int { + auto hasrmin = (innerR[0] > 0) || (innerR[1] > 0); + + int radiusSegments = TMath::Max(4, TMath::Nint(thetaLength / 360. * GetUsedNSegments())); + + // external surface + int numfaces = radiusSegments * (((outerR[0] <= 0) || (outerR[1] <= 0)) ? 1 : 2); + + // internal surface + if (hasrmin) + numfaces += radiusSegments * (((innerR[0] <= 0) || (innerR[1] <= 0)) ? 1 : 2); + + // upper cap + if (outerR[0] > 0) + numfaces += radiusSegments * ((innerR[0] > 0) ? 2 : 1); + // bottom cup + if (outerR[1] > 0) + numfaces += radiusSegments * ((innerR[1] > 0) ? 2 : 1); + + if (thetaLength < 360) + numfaces += ((outerR[0] > innerR[0]) ? 2 : 0) + ((outerR[1] > innerR[1]) ? 2 : 0); + + return numfaces; + }; + + if (shape->IsA() == TGeoSphere::Class()) { + TGeoSphere *sphere = (TGeoSphere *)shape; + auto widthSegments = sphere->GetNumberOfDivisions(); + auto heightSegments = sphere->GetNz(); + auto phiLength = sphere->GetPhi2() - sphere->GetPhi1(); + auto noInside = sphere->GetRmin() <= 0; + + auto numoutside = widthSegments * heightSegments * 2; + auto numtop = widthSegments * (noInside ? 1 : 2); + auto numbottom = widthSegments * (noInside ? 1 : 2); + auto numcut = (phiLength == 360.) ? 0 : heightSegments * (noInside ? 2 : 4); + + return numoutside * (noInside ? 1 : 2) + numtop + numbottom + numcut; + } else if (shape->IsA() == TGeoCone::Class()) { + auto cone = (TGeoCone *)shape; + return countTubeFaces({cone->GetRmax2(), cone->GetRmax1()}, {cone->GetRmin2(), cone->GetRmin1()}); + } else if (shape->IsA() == TGeoConeSeg::Class()) { + auto cone = (TGeoConeSeg *)shape; + return countTubeFaces({cone->GetRmax2(), cone->GetRmax1()}, {cone->GetRmin2(), cone->GetRmin1()}, + cone->GetPhi2() - cone->GetPhi1()); + } else if (shape->IsA() == TGeoTube::Class()) { + auto tube = (TGeoTube *)shape; + return countTubeFaces({tube->GetRmax(), tube->GetRmax()}, {tube->GetRmin(), tube->GetRmin()}); + } else if (shape->IsA() == TGeoTubeSeg::Class()) { + auto tube = (TGeoTubeSeg *)shape; + return countTubeFaces({tube->GetRmax(), tube->GetRmax()}, {tube->GetRmin(), tube->GetRmin()}, + tube->GetPhi2() - tube->GetPhi1()); + } else if (shape->IsA() == TGeoCtub::Class()) { + auto tube = (TGeoCtub *)shape; + return countTubeFaces({tube->GetRmax(), tube->GetRmax()}, {tube->GetRmin(), tube->GetRmin()}, + tube->GetPhi2() - tube->GetPhi1()); + } else if (shape->IsA() == TGeoEltu::Class()) { + return GetUsedNSegments(4) * 4; + } else if (shape->IsA() == TGeoTorus::Class()) { + auto torus = (TGeoTorus *)shape; + auto radialSegments = GetUsedNSegments(6); + auto tubularSegments = TMath::Max(8, TMath::Nint(torus->GetDphi() / 360. * GetUsedNSegments())); + return (torus->GetRmin() > 0 ? 4 : 2) * radialSegments * (tubularSegments + (torus->GetDphi() != 360. ? 1 : 0)); + } else if (shape->IsA() == TGeoPcon::Class()) { + auto pcon = (TGeoPcon *)shape; + + bool hasrmin = false; + int radiusSegments = TMath::Max(5, TMath::Nint(pcon->GetDphi() / 360 * GetUsedNSegments())); + for (int layer = 0; layer < pcon->GetNz(); ++layer) + if (pcon->GetRmin(layer) > 0.) + hasrmin = true; + return (hasrmin ? 4 : 2) * radiusSegments * (pcon->GetNz() - 1); + } else if (shape->IsA() == TGeoPgon::Class()) { + auto pgon = (TGeoPgon *)shape; + + bool hasrmin = false; + int radiusSegments = TMath::Max(5, TMath::Nint(pgon->GetDphi() / 360 * GetUsedNSegments())); + for (int layer = 0; layer < pgon->GetNz(); ++layer) + if (pgon->GetRmin(layer) > 0.) + hasrmin = true; + return (hasrmin ? 4 : 2) * radiusSegments * (pgon->GetNz() - 1); + } else if (shape->IsA() == TGeoXtru::Class()) { + auto xtru = (TGeoXtru *)shape; + return (xtru->GetNz() - 1) * xtru->GetNvert() * 2 + xtru->GetNvert() * 3; + } else if (shape->IsA() == TGeoParaboloid::Class()) { + auto para = (TGeoParaboloid *)shape; + int radiusSegments = GetUsedNSegments(4), heightSegments = 30; + int numfaces = (heightSegments + 1) * radiusSegments * 2; + if (para->GetRlo() == 0.) + numfaces -= radiusSegments * 2; // complete layer + if (para->GetRhi() == 0.) + numfaces -= radiusSegments * 2; // complete layer + return numfaces; + } else if (shape->IsA() == TGeoHype::Class()) { + TGeoHype *hype = (TGeoHype *)shape; + if ((hype->GetStIn() == 0) && (hype->GetStOut() == 0)) + return countTubeFaces({hype->GetRmax(), hype->GetRmax()}, {hype->GetRmin(), hype->GetRmin()}); + int radiusSegments = GetUsedNSegments(4), heightSegments = 30; + return radiusSegments * (heightSegments + 1) * ((hype->GetRmin() > 0.) ? 4 : 2); + } else if (shape->IsA() == TGeoTessellated::Class()) { + auto tess = (TGeoTessellated *)shape; + int numfaces = 0; + for (int i = 0; i < tess->GetNfacets(); ++i) { + if (tess->GetFacet(i).GetNvert() == 4) + numfaces += 2; + else + numfaces += 1; + } + return numfaces; + } else if (shape->IsA() == TGeoScaledShape::Class()) { + auto scaled = (TGeoScaledShape *)shape; + return CountShapeFaces(scaled->GetShape()); + } else if (shape->IsA() == TGeoCompositeShape::Class()) { + auto comp = (TGeoCompositeShape *)shape; + if (!comp->GetBoolNode()) + return 0; + return CountShapeFaces(comp->GetBoolNode()->GetLeftShape()) + + CountShapeFaces(comp->GetBoolNode()->GetRightShape()); + } + + // many of simple shapes have 12 faces + return 12; +} ///////////////////////////////////////////////////////////////////// /// Find description object and create render information @@ -783,24 +1098,18 @@ RGeomDescription::ShapeDescr &RGeomDescription::MakeShapeDescr(TGeoShape *shape) if (old_nsegm > 0 && gGeoManager) gGeoManager->SetNsegments(old_nsegm); - Int_t num_vertices = mesh->NumberOfVertices(), num_polynoms = 0; for (unsigned polyIndex = 0; polyIndex < mesh->NumberOfPolys(); ++polyIndex) { auto size_of_polygon = mesh->SizeOfPoly(polyIndex); - if (size_of_polygon == 3) { - num_polynoms += 1; - } else if (size_of_polygon == 4) { - num_polynoms += 2; - } else { - R__LOG_ERROR(RGeomLog()) << "CSG polygon has unsupported number of vertices " << size_of_polygon; - } + if (size_of_polygon >= 3) + num_polynoms += (size_of_polygon - 2); } - Int_t index_buffer_size = num_polynoms * 3, // triangle indexes - vertex_buffer_size = num_vertices * 3; // X,Y,Z array + Int_t index_buffer_size = num_polynoms * 3, // triangle indexes + vertex_buffer_size = num_vertices * 3; // X,Y,Z array elem.nfaces = num_polynoms; @@ -808,9 +1117,9 @@ RGeomDescription::ShapeDescr &RGeomDescription::MakeShapeDescr(TGeoShape *shape) for (Int_t i = 0; i < num_vertices; ++i) { auto v = mesh->GetVertex(i); - vertices[i*3] = v[0]; - vertices[i*3+1] = v[1]; - vertices[i*3+2] = v[2]; + vertices[i * 3] = v[0]; + vertices[i * 3 + 1] = v[1]; + vertices[i * 3 + 2] = v[2]; } elem.fRawInfo.raw.resize(vertices.size() * sizeof(float)); @@ -825,20 +1134,19 @@ RGeomDescription::ShapeDescr &RGeomDescription::MakeShapeDescr(TGeoShape *shape) for (unsigned polyIndex = 0; polyIndex < mesh->NumberOfPolys(); ++polyIndex) { auto size_of_polygon = mesh->SizeOfPoly(polyIndex); - if ((size_of_polygon == 3) || (size_of_polygon == 4)) { - // add first triangle + // add first triangle + if (size_of_polygon >= 3) for (int i = 0; i < 3; ++i) indexes[pos++] = mesh->GetVertexIndex(polyIndex, i); - } - if (size_of_polygon == 4) { - // add second triangle - indexes[pos++] = mesh->GetVertexIndex(polyIndex, 0); - indexes[pos++] = mesh->GetVertexIndex(polyIndex, 2); - indexes[pos++] = mesh->GetVertexIndex(polyIndex, 3); - } + // add following triangles + if (size_of_polygon > 3) + for (unsigned vertex = 3; vertex < size_of_polygon; vertex++) { + indexes[pos++] = mesh->GetVertexIndex(polyIndex, 0); + indexes[pos++] = mesh->GetVertexIndex(polyIndex, vertex - 1); + indexes[pos++] = mesh->GetVertexIndex(polyIndex, vertex); + } } - } } @@ -850,27 +1158,36 @@ RGeomDescription::ShapeDescr &RGeomDescription::MakeShapeDescr(TGeoShape *shape) void RGeomDescription::CopyMaterialProperties(TGeoVolume *volume, RGeomNode &node) { - if (!volume) return; + if (!volume) + return; - TColor *col{nullptr}; + TColor *col = nullptr; if ((volume->GetFillColor() > 1) && (volume->GetLineColor() == 1)) col = gROOT->GetColor(volume->GetFillColor()); else if (volume->GetLineColor() >= 0) col = gROOT->GetColor(volume->GetLineColor()); - if (volume->GetMedium() && (volume->GetMedium() != TGeoVolume::DummyMedium()) && volume->GetMedium()->GetMaterial()) { + if (volume->GetMedium() && (volume->GetMedium() != TGeoVolume::DummyMedium()) && + volume->GetMedium()->GetMaterial()) { auto material = volume->GetMedium()->GetMaterial(); + node.material = material->GetName(); + auto fillstyle = material->GetFillStyle(); - if ((fillstyle>=3000) && (fillstyle<=3100)) node.opacity = (3100 - fillstyle) / 100.; - if (!col) col = gROOT->GetColor(material->GetFillColor()); + if ((fillstyle >= 3000) && (fillstyle <= 3100)) + node.opacity = (3100 - fillstyle) / 100.; + if (!col) + col = gROOT->GetColor(material->GetFillColor()); + } else { + node.material.clear(); } if (col) { - node.color = std::to_string((int)(col->GetRed()*255)) + "," + - std::to_string((int)(col->GetGreen()*255)) + "," + - std::to_string((int)(col->GetBlue()*255)); + TString colbuf; + colbuf.Form("#%02x%02x%02x", (int)(col->GetRed() * 255), (int)(col->GetGreen() * 255), + (int)(col->GetBlue() * 255)); + node.color = colbuf.Data(); if (node.opacity == 1.) node.opacity = col->GetAlpha(); } else { @@ -883,7 +1200,7 @@ void RGeomDescription::CopyMaterialProperties(TGeoVolume *volume, RGeomNode &nod void RGeomDescription::ResetRndrInfos() { - for (auto &s: fShapes) + for (auto &s : fShapes) s.reset(); } @@ -893,23 +1210,27 @@ void RGeomDescription::ResetRndrInfos() /// /// Collect all information required to draw geometry on the client /// This includes list of each visible nodes, meshes and matrixes +/// If @param all_nodes is true, all existing nodes will be provided, +/// which allows to create complete nodes hierarchy on client side /// /// Example of usage: /// /// void geom() { /// auto f = TFile::Open("file_name.root"); /// auto vol = f->Get("object_name"); -/// ROOT::Experimental::RGeomDescription desc; +/// ROOT::RGeomDescription desc; /// desc.Build(vol); /// std::ofstream fout("geom.json"); /// fout << desc.ProduceJson(); /// } /// /// In JSROOT one loads data from JSON file and call `build` function to -/// produce three.js model +/// produce three.js model. Also see example in tutorials/webgui/geom/ folder -std::string RGeomDescription::ProduceJson() +std::string RGeomDescription::ProduceJson(bool all_nodes) { + TLockGuard lock(fMutex); + std::vector viscnt(fDesc.size(), 0); int level = GetVisLevel(); @@ -936,18 +1257,20 @@ std::string RGeomDescription::ProduceJson() int totalnumfaces = 0, totalnumnodes = 0; - //for (auto &node : fDesc) + // for (auto &node : fDesc) // node.SetDisplayed(false); // build all shapes in volume decreasing order - for (auto &sid: fSortMap) { + for (auto &sid : fSortMap) { fDrawIdCut++; // auto &desc = fDesc[sid]; - if ((viscnt[sid] <= 0) || (desc.vol <= 0)) continue; + if ((viscnt[sid] <= 0) || (desc.vol <= 0)) + continue; auto shape = GetVolume(sid)->GetShape(); - if (!shape) continue; + if (!shape) + continue; // now we need to create TEveGeoPolyShape, which can provide all rendering data auto &shape_descr = MakeShapeDescr(shape); @@ -960,11 +1283,13 @@ std::string RGeomDescription::ProduceJson() // check how many faces are created totalnumfaces += shape_descr.nfaces * viscnt[sid]; - if ((GetMaxVisFaces() > 0) && (totalnumfaces > GetMaxVisFaces())) break; + if ((GetMaxVisFaces() > 0) && (totalnumfaces > GetMaxVisFaces())) + break; // also avoid too many nodes totalnumnodes += viscnt[sid]; - if ((GetMaxVisNodes() > 0) && (totalnumnodes > GetMaxVisNodes())) break; + if ((GetMaxVisNodes() > 0) && (totalnumnodes > GetMaxVisNodes())) + break; // desc.SetDisplayed(true); } @@ -977,7 +1302,7 @@ std::string RGeomDescription::ProduceJson() bool has_shape = false; ScanNodes(true, level, [&, this](RGeomNode &node, std::vector &stack, bool, int seqid) { - if (node.sortid < fDrawIdCut) { + if ((node.sortid < fDrawIdCut) && (viscnt[node.id] > 0)) { drawing.visibles.emplace_back(node.id, seqid, stack); auto &item = drawing.visibles.back(); @@ -989,23 +1314,54 @@ std::string RGeomDescription::ProduceJson() auto &sd = MakeShapeDescr(volume->GetShape()); item.ri = sd.rndr_info(); - if (sd.has_shape()) has_shape = true; + if (sd.has_shape()) + has_shape = true; } return true; }); - CollectNodes(drawing); + CollectNodes(drawing, all_nodes); return MakeDrawingJson(drawing, has_shape); } +///////////////////////////////////////////////////////////////////// +/// Check if there is draw data available + +bool RGeomDescription::HasDrawData() const +{ + TLockGuard lock(fMutex); + return (fDrawJson.length() > 0) && (fDrawIdCut > 0); +} + +///////////////////////////////////////////////////////////////////// +/// Produces search data if necessary + +void RGeomDescription::ProduceSearchData() +{ + TLockGuard lock(fMutex); + + if (fSearch.empty() || !fSearchJson.empty()) + return; + + std::string hjson; + + SearchVisibles(fSearch, hjson, fSearchJson); + + (void)hjson; // not used here +} + ///////////////////////////////////////////////////////////////////// /// Collect all information required to draw geometry on the client /// This includes list of each visible nodes, meshes and matrixes void RGeomDescription::ProduceDrawData() { - fDrawJson = "GDRAW:"s + ProduceJson(); + auto json = ProduceJson(); + + TLockGuard lock(fMutex); + + fDrawJson = "GDRAW:"s + json; } ///////////////////////////////////////////////////////////////////// @@ -1013,7 +1369,22 @@ void RGeomDescription::ProduceDrawData() void RGeomDescription::ClearDrawData() { + TLockGuard lock(fMutex); + fDrawJson.clear(); + fSearchJson.clear(); +} + +///////////////////////////////////////////////////////////////////// +/// Clear cached data, need to be clear when connection broken + +void RGeomDescription::ClearCache() +{ + ClearDrawData(); + + TLockGuard lock(fMutex); + fShapes.clear(); + fSearch.clear(); } ///////////////////////////////////////////////////////////////////// @@ -1022,15 +1393,16 @@ void RGeomDescription::ClearDrawData() bool RGeomDescription::IsPrincipalEndNode(int nodeid) { + TLockGuard lock(fMutex); + if ((nodeid < 0) || (nodeid >= (int)fDesc.size())) return false; auto &desc = fDesc[nodeid]; - return (desc.sortid < fDrawIdCut) && desc.IsVisible() && desc.CanDisplay() && (desc.chlds.size()==0); + return (desc.sortid < fDrawIdCut) && desc.IsVisible() && desc.CanDisplay() && (desc.chlds.size() == 0); } - ///////////////////////////////////////////////////////////////////// /// Search visible nodes for provided name /// If number of found elements less than 100, create description and shapes for them @@ -1038,6 +1410,8 @@ bool RGeomDescription::IsPrincipalEndNode(int nodeid) int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson, std::string &json) { + TLockGuard lock(fMutex); + hjson.clear(); json.clear(); @@ -1049,29 +1423,41 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson std::vector nodescnt(fDesc.size(), 0), viscnt(fDesc.size(), 0); int nmatches = 0; + std::string test = find; + int kind = 0; + if (test.compare(0, 2, "c:") == 0) { + test.erase(0, 2); + kind = 1; + } else if (test.compare(0, 2, "m:") == 0) { + test.erase(0, 2); + kind = 2; + } + + TRegexp regexp(test.c_str()); - auto match_func = [&find](RGeomNode &node) { - return (node.vol > 0) && (node.name.compare(0, find.length(), find) == 0); + auto match_func = [®exp, kind](RGeomNode &node) { + return (node.vol > 0) && (TString(node.GetArg(kind)).Index(regexp) >= 0); }; // first count how many times each individual node appears - ScanNodes(false, 0, [&nodescnt,&viscnt,&match_func,&nmatches](RGeomNode &node, std::vector &, bool is_vis, int) { - - if (match_func(node)) { - nmatches++; - nodescnt[node.id]++; - if (is_vis) viscnt[node.id]++; - }; - return true; - }); + ScanNodes(false, 0, + [&nodescnt, &viscnt, &match_func, &nmatches](RGeomNode &node, std::vector &, bool is_vis, int) { + if (match_func(node)) { + nmatches++; + nodescnt[node.id]++; + if (is_vis) + viscnt[node.id]++; + }; + return true; + }); // do not send too much data, limit could be made configurable later - if (nmatches==0) { + if (nmatches == 0) { hjson = "FOUND:NO"; return nmatches; } - if (nmatches > 10 * GetMaxVisNodes()) { + if ((GetMaxVisNodes() > 0) && (nmatches > 10 * GetMaxVisNodes())) { hjson = "FOUND:Too many " + std::to_string(nmatches); return nmatches; } @@ -1082,16 +1468,20 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson bool send_rawdata = true; // build all shapes in volume decreasing order - for (auto &sid: fSortMap) { - if (scnt++ < fDrawIdCut) continue; // no need to send most significant shapes + for (auto &sid : fSortMap) { + if (scnt++ < fDrawIdCut) + continue; // no need to send most significant shapes - if (viscnt[sid] == 0) continue; // this node is not used at all + if (viscnt[sid] == 0) + continue; // this node is not used at all auto &desc = fDesc[sid]; - if ((viscnt[sid] <= 0) && (desc.vol <= 0)) continue; + if ((viscnt[sid] <= 0) && (desc.vol <= 0)) + continue; auto shape = GetVolume(sid)->GetShape(); - if (!shape) continue; + if (!shape) + continue; // create shape raw data auto &shape_descr = MakeShapeDescr(shape); @@ -1104,11 +1494,17 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson // check how many faces are created totalnumfaces += shape_descr.nfaces * viscnt[sid]; - if ((GetMaxVisFaces() > 0) && (totalnumfaces > GetMaxVisFaces())) { send_rawdata = false; break; } + if ((GetMaxVisFaces() > 0) && (totalnumfaces > GetMaxVisFaces())) { + send_rawdata = false; + break; + } // also avoid too many nodes totalnumnodes += viscnt[sid]; - if ((GetMaxVisNodes() > 0) && (totalnumnodes > GetMaxVisNodes())) { send_rawdata = false; break; } + if ((GetMaxVisNodes() > 0) && (totalnumnodes > GetMaxVisNodes())) { + send_rawdata = false; + break; + } } // only for debug purposes - remove later @@ -1117,9 +1513,8 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson // finally we should create data for streaming to the client // it includes list of visible nodes and rawdata (if there is enough space) - - std::vector found_desc; /// found_map(fDesc.size(), -1); /// foundid + std::vector found_desc; /// found_map(fDesc.size(), -1); /// foundid // these are only selected nodes to produce hierarchy @@ -1146,11 +1541,12 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson if (found_map[chldid] <= 0) { int newid = found_desc.size(); found_desc.emplace_back(newid); // potentially original id can be used here - found_map[chldid] = newid; // re-map into reduced hierarchy + found_map[chldid] = newid; // re-map into reduced hierarchy found_desc.back().vis = fDesc[chldid].vis; found_desc.back().name = fDesc[chldid].name; found_desc.back().color = fDesc[chldid].color; + found_desc.back().material = fDesc[chldid].material; } auto pid = found_map[prntid]; @@ -1165,7 +1561,8 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson } // no need to add visibles - if (!is_vis) return true; + if (!is_vis) + return true; drawing.visibles.emplace_back(node.id, seqid, stack); @@ -1185,7 +1582,8 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson auto &sd = MakeShapeDescr(volume->GetShape()); item.ri = sd.rndr_info(); - if (sd.has_shape()) has_shape = true; + if (sd.has_shape()) + has_shape = true; return true; }); @@ -1203,11 +1601,14 @@ int RGeomDescription::SearchVisibles(const std::string &find, std::string &hjson int RGeomDescription::FindNodeId(const std::vector &stack) { + TLockGuard lock(fMutex); + int nodeid = 0; - for (auto &chindx: stack) { + for (auto &chindx : stack) { auto &node = fDesc[nodeid]; - if (chindx >= (int) node.chlds.size()) return -1; + if (chindx >= (int)node.chlds.size()) + return -1; nodeid = node.chlds[chindx]; } @@ -1219,8 +1620,13 @@ int RGeomDescription::FindNodeId(const std::vector &stack) std::vector RGeomDescription::MakeStackByIds(const std::vector &ids) { + TLockGuard lock(fMutex); + std::vector stack; + if (ids.size() == 0) + return stack; + if (ids[0] != 0) { printf("Wrong first id\n"); return stack; @@ -1233,7 +1639,7 @@ std::vector RGeomDescription::MakeStackByIds(const std::vector &ids) int prntid = nodeid; nodeid = ids[k]; - if (nodeid >= (int) fDesc.size()) { + if (nodeid >= (int)fDesc.size()) { printf("Wrong node id %d\n", nodeid); stack.clear(); return stack; @@ -1241,7 +1647,7 @@ std::vector RGeomDescription::MakeStackByIds(const std::vector &ids) auto &chlds = fDesc[prntid].chlds; auto pos = std::find(chlds.begin(), chlds.end(), nodeid); if (pos == chlds.end()) { - printf("Wrong id %d not a child of %d - fail to find stack num %d\n", nodeid, prntid, (int) chlds.size()); + printf("Wrong id %d not a child of %d - fail to find stack num %d\n", nodeid, prntid, (int)chlds.size()); stack.clear(); return stack; } @@ -1258,6 +1664,8 @@ std::vector RGeomDescription::MakeStackByIds(const std::vector &ids) std::vector RGeomDescription::MakeStackByPath(const std::vector &path) { + TLockGuard lock(fMutex); + std::vector res; RGeomBrowserIter iter(*this); @@ -1274,6 +1682,8 @@ std::vector RGeomDescription::MakeStackByPath(const std::vector RGeomDescription::MakeIdsByStack(const std::vector &stack) { + TLockGuard lock(fMutex); + std::vector ids; ids.emplace_back(0); @@ -1282,7 +1692,10 @@ std::vector RGeomDescription::MakeIdsByStack(const std::vector &stack) for (auto s : stack) { auto &chlds = fDesc[nodeid].chlds; - if (s >= (int) chlds.size()) { failure = true; break; } + if (s >= (int)chlds.size()) { + failure = true; + break; + } ids.emplace_back(chlds[s]); @@ -1302,6 +1715,8 @@ std::vector RGeomDescription::MakeIdsByStack(const std::vector &stack) std::vector RGeomDescription::MakePathByStack(const std::vector &stack) { + TLockGuard lock(fMutex); + std::vector path; auto ids = MakeIdsByStack(stack); @@ -1311,13 +1726,14 @@ std::vector RGeomDescription::MakePathByStack(const std::vector nodes; auto vol = GetVolume(nodeid); @@ -1332,7 +1748,6 @@ std::string RGeomDescription::ProduceModifyReply(int nodeid) return "MODIF:"s + TBufferJSON::ToJSON(&nodes, GetJsonComp()).Data(); } - ///////////////////////////////////////////////////////////////////////////////// /// Produce shape rendering data for given stack /// All nodes, which are referencing same shape will be transferred @@ -1340,6 +1755,8 @@ std::string RGeomDescription::ProduceModifyReply(int nodeid) bool RGeomDescription::ProduceDrawingFor(int nodeid, std::string &json, bool check_volume) { + TLockGuard lock(fMutex); + // only this shape is interesting TGeoVolume *vol = (nodeid < 0) ? nullptr : GetVolume(nodeid); @@ -1355,9 +1772,11 @@ bool RGeomDescription::ProduceDrawingFor(int nodeid, std::string &json, bool che // select only nodes which reference same shape if (check_volume) { - if (GetVolume(node.id) != vol) return true; + if (GetVolume(node.id) != vol) + return true; } else { - if (node.id != nodeid) return true; + if (node.id != nodeid) + return true; } drawing.visibles.emplace_back(node.id, seq_id, stack); @@ -1370,7 +1789,7 @@ bool RGeomDescription::ProduceDrawingFor(int nodeid, std::string &json, bool che }); // no any visible nodes were done - if (drawing.visibles.size()==0) { + if (drawing.visibles.size() == 0) { json.append("NO"); return false; } @@ -1384,8 +1803,10 @@ bool RGeomDescription::ProduceDrawingFor(int nodeid, std::string &json, bool che // assign shape data for (auto &item : drawing.visibles) { item.ri = sd.rndr_info(); - if (sd.has_shape()) has_shape = true; - if (sd.has_raw()) has_raw = true; + if (sd.has_shape()) + has_shape = true; + if (sd.has_raw()) + has_raw = true; } CollectNodes(drawing); @@ -1425,8 +1846,16 @@ std::string RGeomDescription::MakeDrawingJson(RGeomDrawing &drawing, bool has_sh /// Change visibility for specified element /// Returns true if changes was performed -bool RGeomDescription::ChangeNodeVisibility(int nodeid, bool selected) +bool RGeomDescription::ChangeNodeVisibility(const std::vector &path, bool selected) { + TLockGuard lock(fMutex); + + RGeomBrowserIter giter(*this); + if (!giter.Navigate(path)) + return false; + + auto nodeid = giter.GetNodeId(); + auto &dnode = fDesc[nodeid]; auto vol = GetVolume(nodeid); @@ -1438,15 +1867,25 @@ bool RGeomDescription::ChangeNodeVisibility(int nodeid, bool selected) dnode.vis = selected ? 99 : 0; vol->SetVisibility(selected); if (dnode.chlds.size() > 0) { - if (selected) dnode.vis = 1; // visibility disabled when any child + if (selected) + dnode.vis = 1; // visibility disabled when any child vol->SetVisDaughters(selected); } int id = 0; - for (auto &desc: fDesc) + for (auto &desc : fDesc) if (GetVolume(id++) == vol) desc.vis = dnode.vis; + auto stack = MakeStackByIds(giter.CurrentIds()); + + // any change in logical node visibility erase individual physical node settings + for (auto iter = fVisibility.begin(); iter != fVisibility.end(); iter++) + if (compare_stacks(iter->stack, stack) == 0) { + fVisibility.erase(iter); + break; + } + ClearDrawData(); // after change raw data is no longer valid return true; @@ -1456,8 +1895,12 @@ bool RGeomDescription::ChangeNodeVisibility(int nodeid, bool selected) /// Change visibility for specified element /// Returns true if changes was performed -std::unique_ptr RGeomDescription::MakeNodeInfo(const std::vector &path) +std::unique_ptr RGeomDescription::MakeNodeInfo(const std::vector &stack) { + auto path = MakePathByStack(stack); + + TLockGuard lock(fMutex); + std::unique_ptr res; RGeomBrowserIter iter(*this); @@ -1494,6 +1937,166 @@ std::unique_ptr RGeomDescription::MakeNodeInfo(const std::vector< return res; } +///////////////////////////////////////////////////////////////////////////////// +/// Select top node by path +/// Used by the client to change active node +/// Returns true if selected node was changed + +bool RGeomDescription::SelectTop(const std::vector &path) +{ + TLockGuard lock(fMutex); + + RGeomBrowserIter iter(*this); + + if (!iter.Navigate(path)) + return false; + + auto stack = MakeStackByIds(iter.CurrentIds()); + if (stack == fSelectedStack) + return false; + + fSelectedStack = stack; + + ClearDrawData(); + + return true; +} + +///////////////////////////////////////////////////////////////////////////////// +/// Set visibility of physical node by path +/// It overrules TGeo visibility flags - but only for specific physical node + +bool RGeomDescription::SetPhysNodeVisibility(const std::vector &path, bool on) +{ + TLockGuard lock(fMutex); + + RGeomBrowserIter giter(*this); + + if (!giter.Navigate(path)) + return false; + + auto stack = MakeStackByIds(giter.CurrentIds()); + + auto nodeid = giter.GetNodeId(); + + for (auto iter = fVisibility.begin(); iter != fVisibility.end(); iter++) { + auto res = compare_stacks(iter->stack, stack); + + if (res == 0) { + bool changed = iter->visible != on; + if (changed) { + iter->visible = on; + ClearDrawData(); + + // no need for custom settings if match with description + if ((fDesc[nodeid].vis > 0) == on) + fVisibility.erase(iter); + } + + return changed; + } + + if (res > 0) { + fVisibility.emplace(iter, stack, on); + ClearDrawData(); + return true; + } + } + + fVisibility.emplace_back(stack, on); + ClearDrawData(); + return true; +} + +///////////////////////////////////////////////////////////////////////////////// +/// Set visibility of physical node by itemname +/// itemname in string with path like "/TOP_1/SUB_2/NODE_3" + +bool RGeomDescription::SetPhysNodeVisibility(const std::string &itemname, bool on) +{ + std::vector path; + std::string::size_type p1 = 0; + + while (p1 < itemname.length()) { + if (itemname[p1] == '/') { + p1++; + continue; + } + auto p = itemname.find("/", p1); + if (p == std::string::npos) { + path.emplace_back(itemname.substr(p1)); + p1 = itemname.length(); + } else { + path.emplace_back(itemname.substr(p1, p - p1)); + p1 = p + 1; + } + } + + return SetPhysNodeVisibility(path, on); +} + +///////////////////////////////////////////////////////////////////////////////// +/// Check if there special settings for specified physical node +/// returns -1 if nothing is found + +int RGeomDescription::IsPhysNodeVisible(const std::vector &stack) +{ + for (auto &item : fVisibility) { + unsigned sz = item.stack.size(); + if (stack.size() < sz) + continue; + bool match = true; + for (unsigned n = 0; n < sz; ++n) + if (stack[n] != item.stack[n]) { + match = false; + break; + } + + if (match) + return item.visible ? 1 : 0; + } + return -1; +} + +///////////////////////////////////////////////////////////////////////////////// +/// Reset custom visibility of physical node by path + +bool RGeomDescription::ClearPhysNodeVisibility(const std::vector &path) +{ + TLockGuard lock(fMutex); + + RGeomBrowserIter giter(*this); + + if (!giter.Navigate(path)) + return false; + + auto stack = MakeStackByIds(giter.CurrentIds()); + + for (auto iter = fVisibility.begin(); iter != fVisibility.end(); iter++) + if (compare_stacks(iter->stack, stack) == 0) { + fVisibility.erase(iter); + ClearDrawData(); + return true; + } + + return false; +} + +///////////////////////////////////////////////////////////////////////////////// +/// Reset all custom visibility settings + +bool RGeomDescription::ClearAllPhysVisibility() +{ + TLockGuard lock(fMutex); + + if (fVisibility.size() == 0) + return false; + + fVisibility.clear(); + ClearDrawData(); + return true; +} + ///////////////////////////////////////////////////////////////////////////////// /// Change configuration by client /// Returns true if any parameter was really changed @@ -1501,7 +2104,10 @@ std::unique_ptr RGeomDescription::MakeNodeInfo(const std::vector< bool RGeomDescription::ChangeConfiguration(const std::string &json) { auto cfg = TBufferJSON::FromJSON(json); - if (!cfg) return false; + if (!cfg) + return false; + + TLockGuard lock(fMutex); auto json1 = TBufferJSON::ToJSON(cfg.get()); auto json2 = TBufferJSON::ToJSON(&fCfg); @@ -1516,7 +2122,50 @@ bool RGeomDescription::ChangeConfiguration(const std::string &json) return true; } +///////////////////////////////////////////////////////////////////////////////// +/// Change search query and belongs to it json string +/// Returns true if any parameter was really changed +bool RGeomDescription::SetSearch(const std::string &query, const std::string &json) +{ + TLockGuard lock(fMutex); + bool changed = (fSearch != query) || (fSearchJson != json); + fSearch = query; + fSearchJson = json; + return changed; +} +///////////////////////////////////////////////////////////////////////////////// +/// Save geometry configuration as C++ macro +void RGeomDescription::SavePrimitive(std::ostream &fs, const std::string &name) +{ + std::string prefix = " "; + + if (fCfg.vislevel != 0) + fs << prefix << name << "SetVisLevel(" << fCfg.vislevel << ");" << std::endl; + if (fCfg.maxnumnodes != 0) + fs << prefix << name << "SetMaxVisNodes(" << fCfg.maxnumnodes << ");" << std::endl; + if (fCfg.maxnumfaces != 0) + fs << prefix << name << "SetMaxVisFaces(" << fCfg.maxnumfaces << ");" << std::endl; + if (fCfg.showtop) + fs << prefix << name << "SetTopVisible(true);" << std::endl; + if (fCfg.build_shapes != 1) + fs << prefix << name << "SetBuildShapes(" << fCfg.build_shapes << ");" << std::endl; + if (fCfg.nsegm != 0) + fs << prefix << name << "SetNSegments(" << fCfg.nsegm << ");" << std::endl; + if (!fCfg.drawopt.empty()) + fs << prefix << name << "SetDrawOptions(\"" << fCfg.drawopt << "\");" << std::endl; + if (fJsonComp != 0) + fs << prefix << name << "SetJsonComp(" << fJsonComp << ");" << std::endl; + + // store custom visibility flags + for (auto &item : fVisibility) { + auto path = MakePathByStack(item.stack); + fs << prefix << name << "SetPhysNodeVisibility("; + for (int i = 0; i < (int)path.size(); ++i) + fs << (i == 0 ? "{\"" : ", \"") << path[i] << "\""; + fs << "}, " << (item.visible ? "true" : "false") << ");" << std::endl; + } +} diff --git a/geom/webviewer/src/RGeomHierarchy.cxx b/geom/webviewer/src/RGeomHierarchy.cxx new file mode 100644 index 0000000000000..54e4f08d1008a --- /dev/null +++ b/geom/webviewer/src/RGeomHierarchy.cxx @@ -0,0 +1,184 @@ +// Author: Sergey Linev, 3.03.2023 + +/************************************************************************* + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include + +#include + +#include "TBufferJSON.h" + +using namespace std::string_literals; + +using namespace ROOT; + +////////////////////////////////////////////////////////////////////////////////////////////// +/// constructor + +RGeomHierarchy::RGeomHierarchy(RGeomDescription &desc, bool use_server_threads) : fDesc(desc) +{ + fWebWindow = RWebWindow::Create(); + fWebWindow->SetDataCallBack([this](unsigned connid, const std::string &arg) { WebWindowCallback(connid, arg); }); + + fWebWindow->SetDefaultPage("file:rootui5sys/geom/index.html"); + fWebWindow->SetGeometry(600, 900); // configure predefined window geometry + + if (use_server_threads) + fWebWindow->UseServerThreads(); + + fDesc.AddSignalHandler(this, [this](const std::string &kind) { ProcessSignal(kind); }); +} + +////////////////////////////////////////////////////////////////////////////////////////////// +/// destructor + +RGeomHierarchy::~RGeomHierarchy() +{ + fDesc.RemoveSignalHandler(this); +} + +////////////////////////////////////////////////////////////////////////////////////////////// +/// Process data from client + +void RGeomHierarchy::WebWindowCallback(unsigned connid, const std::string &arg) +{ + if (arg.compare(0, 6, "BRREQ:") == 0) { + // central place for processing browser requests + auto json = fDesc.ProcessBrowserRequest(arg.substr(6)); + if (json.length() > 0) + fWebWindow->Send(connid, json); + } else if (arg.compare(0, 7, "SEARCH:") == 0) { + + std::string query = arg.substr(7); + + if (!query.empty()) { + std::string hjson, json; + fDesc.SearchVisibles(query, hjson, json); + // send reply with appropriate header - NOFOUND, FOUND0:, FOUND1: + fWebWindow->Send(0, hjson); + // inform viewer that search is changed + if (fDesc.SetSearch(query, json)) + fDesc.IssueSignal(this, json.empty() ? "ClearSearch" : "ChangeSearch"); + } else { + fDesc.SetSearch(""s, ""s); + fDesc.IssueSignal(this, "ClearSearch"); + } + + auto connids = fWebWindow->GetConnections(connid); + + for (auto id : connids) + fWebWindow->Send(id, "SETSR:"s + query); + + } else if (arg.compare(0, 7, "SETTOP:") == 0) { + auto path = TBufferJSON::FromJSON>(arg.substr(7)); + if (path && fDesc.SelectTop(*path)) { + fDesc.IssueSignal(this, "SelectTop"); + auto connids = fWebWindow->GetConnections(connid); + + for (auto id : connids) + fWebWindow->Send(id, "UPDATE"s); + } + } else if (arg.compare(0, 6, "HOVER:") == 0) { + auto path = TBufferJSON::FromJSON>(arg.substr(6)); + if (path) { + auto stack = fDesc.MakeStackByPath(*path); + if (fDesc.SetHighlightedItem(stack)) + fDesc.IssueSignal(this, "HighlightItem"); + } + } else if (arg.compare(0, 6, "CLICK:") == 0) { + auto path = TBufferJSON::FromJSON>(arg.substr(6)); + if (path) { + auto stack = fDesc.MakeStackByPath(*path); + if (fDesc.SetClickedItem(stack)) + fDesc.IssueSignal(this, "ClickItem"); + } + } else if ((arg.compare(0, 7, "SETVI0:") == 0) || (arg.compare(0, 7, "SETVI1:") == 0)) { + // change visibility for specified nodeid + + auto path = TBufferJSON::FromJSON>(arg.substr(7)); + + bool on = (arg[5] == '1'); + + if (path && fDesc.ChangeNodeVisibility(*path, on)) + fDesc.IssueSignal(this, "NodeVisibility"); + + } else if ((arg.compare(0, 5, "SHOW:") == 0) || (arg.compare(0, 5, "HIDE:") == 0)) { + auto path = TBufferJSON::FromJSON>(arg.substr(5)); + if (path && fDesc.SetPhysNodeVisibility(*path, arg.compare(0, 5, "SHOW:") == 0)) + fDesc.IssueSignal(this, "NodeVisibility"); + } else if (arg.compare(0, 6, "CLEAR:") == 0) { + auto path = TBufferJSON::FromJSON>(arg.substr(6)); + if (path && fDesc.ClearPhysNodeVisibility(*path)) + fDesc.IssueSignal(this, "NodeVisibility"); + } else if (arg == "CLEARALL"s) { + if (fDesc.ClearAllPhysVisibility()) + fDesc.IssueSignal(this, "NodeVisibility"); + } +} + +///////////////////////////////////////////////////////////////////////////////// +/// Show hierarchy in web window + +void RGeomHierarchy::Show(const RWebDisplayArgs &args) +{ + if (args.GetWidgetKind().empty()) + const_cast(&args)->SetWidgetKind("RGeomHierarchy"); + + fWebWindow->SetUserArgs("{ show_columns: true, only_hierarchy: true }"); + RWebWindow::ShowWindow(fWebWindow, args); +} + +///////////////////////////////////////////////////////////////////////////////// +/// Update client - reload hierarchy + +void RGeomHierarchy::Update() +{ + if (fWebWindow) + fWebWindow->Send(0, "RELOAD"s); +} + +///////////////////////////////////////////////////////////////////////////////// +/// Let browse to specified location + +void RGeomHierarchy::BrowseTo(const std::string &itemname) +{ + if (fWebWindow) + fWebWindow->Send(0, "ACTIV:"s + itemname); +} + +///////////////////////////////////////////////////////////////////////////////// +/// Process signals from geometry description object + +void RGeomHierarchy::ProcessSignal(const std::string &kind) +{ + if (kind == "HighlightItem") { + auto stack = fDesc.GetHighlightedItem(); + auto path = fDesc.MakePathByStack(stack); + if (stack.size() == 0) + path = {"__OFF__"}; // just clear highlight + if (fWebWindow) + fWebWindow->Send(0, "HIGHL:"s + TBufferJSON::ToJSON(&path).Data()); + } else if (kind == "NodeVisibility") { + // visibility changed from RGeomViewer, update hierarchy + if (fWebWindow) + fWebWindow->Send(0, "UPDATE"s); + } else if (kind == "ActiveItem") { + BrowseTo(fDesc.GetActiveItem()); + } +} + +////////////////////////////////////////////////////////////////////////////////////////////// +/// Set handle which will be cleared when connection is closed +/// Must be called after window is shown + +void RGeomHierarchy::ClearOnClose(const std::shared_ptr &handle) +{ + if (fWebWindow) + fWebWindow->SetClearOnClose(handle); +} diff --git a/geom/webviewer/src/RGeomViewer.cxx b/geom/webviewer/src/RGeomViewer.cxx index e8c6465fbf90c..a858048085dda 100644 --- a/geom/webviewer/src/RGeomViewer.cxx +++ b/geom/webviewer/src/RGeomViewer.cxx @@ -1,8 +1,7 @@ -// @(#)root/eve7:$Id$ // Author: Sergey Linev, 13.12.2018 /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-203, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -11,12 +10,14 @@ #include +#include #include #include #include "TSystem.h" #include "TBase64.h" #include "TROOT.h" +#include "TFile.h" #include "TEnv.h" #include "THttpServer.h" #include "TBufferJSON.h" @@ -26,7 +27,7 @@ using namespace std::string_literals; -using namespace ROOT::Experimental; +using namespace ROOT; ////////////////////////////////////////////////////////////////////////////////////////////// /// constructor @@ -39,16 +40,21 @@ RGeomViewer::RGeomViewer(TGeoManager *mgr, const std::string &volname) // this is call-back, invoked when message received via websocket fWebWindow->SetDataCallBack([this](unsigned connid, const std::string &arg) { WebWindowCallback(connid, arg); }); + fWebWindow->SetDisconnectCallBack([this](unsigned connid) { WebWindowDisconnect(connid); }); + fWebWindow->SetGeometry(900, 700); // configure predefined window geometry - fWebWindow->SetConnLimit(0); // allow any connections numbers at the same time + fWebWindow->SetConnLimit(0); // allow any connections numbers at the same time fWebWindow->SetMaxQueueLength(30); // number of allowed entries in the window queue } - fDesc.SetPreferredOffline(gEnv->GetValue("WebGui.PreferredOffline",0) != 0); + fDesc.SetPreferredOffline(gEnv->GetValue("WebGui.PreferredOffline", 0) != 0); fDesc.SetJsonComp(gEnv->GetValue("WebGui.JsonComp", TBufferJSON::kSkipTypeInfo + TBufferJSON::kNoSpaces)); fDesc.SetBuildShapes(gEnv->GetValue("WebGui.GeomBuildShapes", 1)); - if (mgr) SetGeometry(mgr, volname); + fDesc.AddSignalHandler(this, [this](const std::string &kind) { ProcessSignal(kind); }); + + if (mgr) + SetGeometry(mgr, volname); } ////////////////////////////////////////////////////////////////////////////////////////////// @@ -56,6 +62,7 @@ RGeomViewer::RGeomViewer(TGeoManager *mgr, const std::string &volname) RGeomViewer::~RGeomViewer() { + fDesc.RemoveSignalHandler(this); } ////////////////////////////////////////////////////////////////////////////////////////////// @@ -105,7 +112,10 @@ void RGeomViewer::Show(const RWebDisplayArgs &args, bool always_start_new_browse return; std::string user_args = ""; - if (!GetShowHierarchy()) user_args = "{ nobrowser: true }"; + if (!GetShowHierarchy()) + user_args = "{ nobrowser: true }"; + else if (GetShowColumns()) + user_args = "{ show_columns: true }"; fWebWindow->SetUserArgs(user_args); if (args.GetWidgetKind().empty()) @@ -130,8 +140,13 @@ std::string RGeomViewer::GetWindowAddr() const void RGeomViewer::Update() { - if (fWebWindow) - fWebWindow->Send(0, "RELOAD"); + fDesc.ClearCache(); + + // update hierarchy + if (fWebHierarchy) + fWebHierarchy->Update(); + + SendGeometry(0); } ////////////////////////////////////////////////////////////////////////////////////////////// @@ -142,8 +157,10 @@ std::vector RGeomViewer::GetStackFromJson(const std::string &json, bool nod std::vector *stack{nullptr}, res; if (TBufferJSON::FromJSON(stack, json.c_str())) { - if (node_ids) res = fDesc.MakeStackByIds(*stack); - else res = *stack; + if (node_ids) + res = fDesc.MakeStackByIds(*stack); + else + res = *stack; delete stack; } else { R__LOG_ERROR(RGeomLog()) << "Fail convert " << json << " into vector"; @@ -154,18 +171,29 @@ std::vector RGeomViewer::GetStackFromJson(const std::string &json, bool nod ////////////////////////////////////////////////////////////////////////////////////////////// /// Send data for principal geometry draw +/// Should be used when essential settings were changed in geometry description -void RGeomViewer::SendGeometry(unsigned connid) +void RGeomViewer::SendGeometry(unsigned connid, bool first_time) { if (!fDesc.HasDrawData()) fDesc.ProduceDrawData(); - auto &json = fDesc.GetDrawJson(); + // updates search data when necessary + fDesc.ProduceSearchData(); - R__LOG_DEBUG(0, RGeomLog()) << "Produce geometry JSON len: " << json.length(); + auto json0 = fDesc.GetDrawJson(); + auto json1 = fDesc.GetSearchJson(); - if (fWebWindow) - fWebWindow->Send(connid, json); + R__LOG_DEBUG(0, RGeomLog()) << "Produce geometry JSON len: " << json0.length(); + + if (!fWebWindow) + return; + + // for the first time always send full drawing + if (first_time || json1.empty()) + fWebWindow->Send(connid, json0); + else + fWebWindow->Send(connid, json1); } ////////////////////////////////////////////////////////////////////////////////////////////// @@ -185,9 +213,10 @@ void RGeomViewer::SetDrawOptions(const std::string &opt) ////////////////////////////////////////////////////////////////////////////////////////////// /// Produce PNG image of the geometry /// If web-browser is shown and drawing completed, image is requested from the browser. -/// In this case method executed asynchronously - it returns immediately and image will stored shortly afterwards when received from the client -/// Height and width parameters are ignored in that case and derived from actual drawing size in the browser. -/// Another possibility is to invoke headless browser, providing positive width and height parameter explicitely +/// In this case method executed asynchronously - it returns immediately and image will stored shortly afterwards when +/// received from the client Height and width parameters are ignored in that case and derived from actual drawing size +/// in the browser. Another possibility is to invoke headless browser, providing positive width and height parameter +/// explicitely /// void RGeomViewer::SaveImage(const std::string &fname, int width, int height) @@ -197,8 +226,10 @@ void RGeomViewer::SaveImage(const std::string &fname, int width, int height) if (connid && (width <= 0) && (height <= 0)) { fWebWindow->Send(connid, "IMAGE:"s + fname); } else { - if (width <= 0) width = 800; - if (height <= 0) height = width; + if (width <= 0) + width = 800; + if (height <= 0) + height = width; if (!fDesc.HasDrawData()) fDesc.ProduceDrawData(); @@ -215,33 +246,27 @@ void RGeomViewer::SaveImage(const std::string &fname, int width, int height) } ////////////////////////////////////////////////////////////////////////////////////////////// -/// receive data from client +/// Process data from client void RGeomViewer::WebWindowCallback(unsigned connid, const std::string &arg) { if (arg == "GETDRAW") { - SendGeometry(connid); + SendGeometry(connid, true); } else if (arg == "QUIT_ROOT") { fWebWindow->TerminateROOT(); - } else if (arg.compare(0, 7, "SEARCH:") == 0) { - - std::string query = arg.substr(7); - - std::string hjson, json; + } else if (arg.compare(0, 9, "HCHANNEL:") == 0) { - /* auto nmatches = */ fDesc.SearchVisibles(query, hjson, json); + int chid = std::stoi(arg.substr(9)); - // send reply with appropriate header - NOFOUND, FOUND0:, FOUND1: - fWebWindow->Send(connid, hjson); + if (!fWebHierarchy) + fWebHierarchy = std::make_shared(fDesc); + fWebHierarchy->Show({fWebWindow, connid, chid}); - if (!json.empty()) - fWebWindow->Send(connid, json); - - } else if (arg.compare(0,4,"GET:") == 0) { + } else if (arg.compare(0, 4, "GET:") == 0) { // provide exact shape auto stack = GetStackFromJson(arg.substr(4)); @@ -254,106 +279,161 @@ void RGeomViewer::WebWindowCallback(unsigned connid, const std::string &arg) fWebWindow->Send(connid, json); - } else if (arg.compare(0, 6, "GVREQ:") == 0) { + } else if (arg.compare(0, 10, "HIGHLIGHT:") == 0) { + auto stack = TBufferJSON::FromJSON>(arg.substr(10)); + if (stack && fDesc.SetHighlightedItem(*stack)) + fDesc.IssueSignal(this, "HighlightItem"); + } else if (arg.compare(0, 6, "IMAGE:") == 0) { + auto separ = arg.find("::", 6); + if (separ == std::string::npos) + return; - auto req = TBufferJSON::FromJSON(arg.substr(6)); + std::string fname = arg.substr(6, separ - 6); + if (fname.empty()) { + int cnt = 0; + do { + fname = "geometry"s; + if (cnt++ > 0) + fname += std::to_string(cnt); + fname += ".png"s; + } while (!gSystem->AccessPathName(fname.c_str())); + } - if (req && (req->oper == "HOVER")) { - if ((req->path.size() > 0 ) && (req->path[0] != "OFF")) - req->stack = fDesc.MakeStackByPath(req->path); - req->path.clear(); - } else if (req && (req->oper == "HIGHL")) { - if (req->stack.size() > 0) - req->path = fDesc.MakePathByStack(req->stack); - req->stack.clear(); - } else if (req && (req->oper == "INFO")) { + TString binary = TBase64::Decode(arg.c_str() + separ + 2); - auto info = fDesc.MakeNodeInfo(req->path); - if (info) - fWebWindow->Send(connid, "NINFO:"s + TBufferJSON::ToJSON(info.get(), (fDesc.GetJsonComp() % 5) + TBufferJSON::kSameSuppression).Data()); + std::ofstream ofs(fname); + ofs.write(binary.Data(), binary.Length()); + ofs.close(); - // not request but different object type is send - req.reset(nullptr); + printf("Image file %s size %d has been created\n", fname.c_str(), (int)binary.Length()); - } else { - req.reset(nullptr); - } + } else if (arg.compare(0, 4, "CFG:") == 0) { - if (req) - fWebWindow->Send(connid, "GVRPL:"s + TBufferJSON::ToJSON(req.get(), TBufferJSON::kSkipTypeInfo + TBufferJSON::kNoSpaces).Data()); + if (fDesc.ChangeConfiguration(arg.substr(4))) + SendGeometry(connid); - } else if ((arg.compare(0, 7, "SETVI0:") == 0) || (arg.compare(0, 7, "SETVI1:") == 0)) { - // change visibility for specified nodeid + } else if (arg == "RELOAD") { - auto nodeid = std::stoi(arg.substr(7)); + SendGeometry(connid); - bool selected = (arg[5] == '1'); + } else if (arg.compare(0, 9, "ACTIVATE:") == 0) { + fDesc.SetActiveItem(arg.substr(9)); + fDesc.IssueSignal(this, "ActiveItem"); + } else if (arg.compare(0, 11, "INFOACTIVE:") == 0) { + fInfoActive = (arg.substr(11) == "true"); + } else if (arg.compare(0, 11, "HIDE_ITEMS:") == 0) { + auto items = TBufferJSON::FromJSON>(arg.substr(11)); + bool changed = false; + if (items) + for (auto &itemname : *items) + if (fDesc.SetPhysNodeVisibility(itemname, false)) + changed = true; + if (changed) { + SendGeometry(connid); + fDesc.IssueSignal(this, "NodeVisibility"); + } + } else if (arg == "SAVEMACRO") { + SaveAsMacro("viewer.cxx"); + } +} - if (fDesc.ChangeNodeVisibility(nodeid, selected)) { +////////////////////////////////////////////////////////////////////////////////////////////// +/// Process disconnect event +/// Clear cache data and dependent connections - // send only modified entries, includes all nodes with same volume - std::string json0 = fDesc.ProduceModifyReply(nodeid); +void RGeomViewer::WebWindowDisconnect(unsigned) +{ + fWebHierarchy.reset(); - // when visibility disabled, client will automatically remove node from drawing - fWebWindow->Send(connid, json0); + fDesc.ClearCache(); - if (selected && fDesc.IsPrincipalEndNode(nodeid)) { - // we need to send changes in drawing elements - // there can be many elements, which reference same volume + fInfoActive = false; +} - std::string json{"APPND:"}; +////////////////////////////////////////////////////////////////////////////////////////////// +/// Process signal from geom description when it changed by any means - if (fDesc.ProduceDrawingFor(nodeid, json, true)) - fWebWindow->Send(connid, json); - } else if (selected) { +void RGeomViewer::ProcessSignal(const std::string &kind) +{ + if ((kind == "SelectTop") || (kind == "NodeVisibility")) { + SendGeometry(); + } else if (kind == "ChangeSearch") { + auto json = fDesc.GetSearchJson(); + if (json.empty()) + json = "CLRSCH"; + if (fWebWindow) + fWebWindow->Send(0, json); + } else if (kind == "ClearSearch") { + if (fWebWindow) + fWebWindow->Send(0, "CLRSCH"); // 6 letters + } else if (kind == "HighlightItem") { + auto stack = fDesc.GetHighlightedItem(); + if (fWebWindow) + fWebWindow->Send(0, "HIGHL:"s + TBufferJSON::ToJSON(&stack).Data()); + } else if (kind == "ClickItem") { + if (fInfoActive) { + auto stack = fDesc.GetClickedItem(); + auto info = fDesc.MakeNodeInfo(stack); + if (info && fWebWindow) + fWebWindow->Send( + 0, "NINFO:"s + + TBufferJSON::ToJSON(info.get(), (fDesc.GetJsonComp() % 5) + TBufferJSON::kSameSuppression).Data()); + } + } +} - // just resend full geometry - // TODO: one can improve here and send only nodes which are not exists on client - // TODO: for that one should remember all information send to client +////////////////////////////////////////////////////////////////////////////////////////////// +/// Save viewer configuration as macro - auto json = fDesc.ProcessBrowserRequest(); - if (json.length() > 0) fWebWindow->Send(connid, json); +void RGeomViewer::SaveAsMacro(const std::string &fname) +{ + std::ofstream fs(fname); + if (!fs) + return; + std::string prefix = " "; - SendGeometry(connid); - } - } - } else if (arg.compare(0,6, "BRREQ:") == 0) { + auto p = fname.find("."); + if (p > 0) { + fs << "void " << fname.substr(0, p) << "() { " << std::endl; + } else { + fs << "{" << std::endl; + } - // central place for processing browser requests + if ((fDesc.GetNumNodes() < 2000) && fGeoManager) { + fGeoManager->GetTopVolume()->SavePrimitive(fs); + fs << prefix << "gGeoManager->SetVisLevel(" << fGeoManager->GetVisLevel() << ");" << std::endl; + } else { + fs << prefix << "// geometry is too large, please provide import like:" << std::endl << std::endl; + fs << prefix << "// TGeoManager::Import(\"filename.root\");" << std::endl; + } - if (!fDesc.IsBuild()) fDesc.Build(fGeoManager); + fs << std::endl; - auto json = fDesc.ProcessBrowserRequest(arg.substr(6)); - if (json.length() > 0) fWebWindow->Send(connid, json); - } else if (arg.compare(0,6, "IMAGE:") == 0) { - auto separ = arg.find("::",6); - if (separ == std::string::npos) return; + fs << prefix << "auto viewer = std::make_shared(gGeoManager"; + if (!fSelectedVolume.empty()) + fs << ", \"" << fSelectedVolume << "\""; + fs << ");" << std::endl; - std::string fname = arg.substr(6, separ-6); - if (fname.empty()) { - int cnt = 0; - do { - fname = "geometry"s; - if (cnt++>0) fname += std::to_string(cnt); - fname += ".png"s; - } while (!gSystem->AccessPathName(fname.c_str())); - } + fDesc.SavePrimitive(fs, "viewer->Description()."); - TString binary = TBase64::Decode(arg.c_str() + separ + 2); + fs << prefix << "viewer->SetShowHierarchy(" << (fShowHierarchy ? "true" : "false") << ");" << std::endl; + fs << prefix << "viewer->SetShowColumns(" << (fShowColumns ? "true" : "false") << ");" << std::endl; - std::ofstream ofs(fname); - ofs.write(binary.Data(), binary.Length()); - ofs.close(); + fs << std::endl; - printf("Image file %s size %d has been created\n", fname.c_str(), (int) binary.Length()); + fs << prefix << "viewer->Show();" << std::endl << std::endl; - } else if (arg.compare(0,4, "CFG:") == 0) { + fs << prefix << "ROOT::Experimental::RDirectory::Heap().Add(\"geom_viewer\", viewer);" << std::endl; - if (fDesc.ChangeConfiguration(arg.substr(4))) - SendGeometry(connid); + fs << "}" << std::endl; +} - } else if (arg == "RELOAD") { +////////////////////////////////////////////////////////////////////////////////////////////// +/// Set handle which will be cleared when connection is closed +/// Must be called after window is shown - SendGeometry(connid); - } +void RGeomViewer::ClearOnClose(const std::shared_ptr &handle) +{ + if (fWebWindow) + fWebWindow->SetClearOnClose(handle); } diff --git a/graf2d/asimage/inc/TASImage.h b/graf2d/asimage/inc/TASImage.h index fbbada8efb2c2..a93f5c1298899 100644 --- a/graf2d/asimage/inc/TASImage.h +++ b/graf2d/asimage/inc/TASImage.h @@ -87,7 +87,7 @@ class TASImage : public TImage { TASImage(const char *name, const TVectorD &imageData, UInt_t width, TImagePalette *palette = nullptr); TASImage(const TASImage &img); TASImage &operator=(const TASImage &img); - virtual ~TASImage(); + ~TASImage() override; TObject *Clone(const char *newname) const override; diff --git a/graf2d/asimage/inc/TASImagePlugin.h b/graf2d/asimage/inc/TASImagePlugin.h index b00607de8b9a0..6bc7c773db52b 100644 --- a/graf2d/asimage/inc/TASImagePlugin.h +++ b/graf2d/asimage/inc/TASImagePlugin.h @@ -27,7 +27,9 @@ class TASImagePlugin : public TImagePlugin { public: TASImagePlugin(const char *ext) : TImagePlugin(ext) { } - virtual ~TASImagePlugin() { } + ~TASImagePlugin() override { ROOT::CallRecursiveRemoveIfNeeded(*this); } + + ULong_t Hash() const override { return fExtension.Hash(); } unsigned char *ReadFile(const char * /*filename*/, UInt_t & /*w*/, UInt_t & /*h*/) override { return nullptr; } Bool_t WriteFile(const char * /*filename*/, unsigned char * /*argb*/, UInt_t /*w*/, UInt_t /*h*/) override { return kFALSE; } diff --git a/graf2d/asimage/inc/TASPaletteEditor.h b/graf2d/asimage/inc/TASPaletteEditor.h index 6c5099b165462..ba28cc1c021b8 100644 --- a/graf2d/asimage/inc/TASPaletteEditor.h +++ b/graf2d/asimage/inc/TASPaletteEditor.h @@ -98,7 +98,7 @@ class TASPaletteEditor : public TPaletteEditor, public TGMainFrame { public: TASPaletteEditor(TAttImage *attImage, UInt_t w, UInt_t h); - virtual ~TASPaletteEditor(); + ~TASPaletteEditor() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t param1, Longptr_t param2) override; diff --git a/graf2d/asimage/inc/TASPluginGS.h b/graf2d/asimage/inc/TASPluginGS.h index febebff39223c..1cea966e0ea97 100644 --- a/graf2d/asimage/inc/TASPluginGS.h +++ b/graf2d/asimage/inc/TASPluginGS.h @@ -29,7 +29,9 @@ class TASPluginGS : public TASImagePlugin { public: TASPluginGS(const char *ext); - virtual ~TASPluginGS(); + ~TASPluginGS() override; + + ULong_t Hash() const override { return fExtension.Hash(); } ASImage *File2ASImage(const char *filename) override; diff --git a/graf2d/asimage/src/TASImage.cxx b/graf2d/asimage/src/TASImage.cxx index db81f23088ee5..6984204e0b486 100644 --- a/graf2d/asimage/src/TASImage.cxx +++ b/graf2d/asimage/src/TASImage.cxx @@ -1191,8 +1191,8 @@ void TASImage::Draw(Option_t *option) h = Int_t(h*cx) + 28; TString rname = GetName(); rname.ReplaceAll(".", ""); - rname += Form("\", \"%s (%d x %d)", rname.Data(), fImage->width, fImage->height); - rname = "new TCanvas(\"" + rname + Form("\", %d, %d);", w, h); + rname += TString::Format("\", \"%s (%d x %d)", rname.Data(), fImage->width, fImage->height); + rname = "new TCanvas(\"" + rname + TString::Format("\", %d, %d);", w, h); gROOT->ProcessLineFast(rname.Data()); } diff --git a/graf2d/asimage/src/TASPaletteEditor.cxx b/graf2d/asimage/src/TASPaletteEditor.cxx index 58d597120cf92..61b86652b39e5 100644 --- a/graf2d/asimage/src/TASPaletteEditor.cxx +++ b/graf2d/asimage/src/TASPaletteEditor.cxx @@ -450,7 +450,7 @@ void TASPaletteEditor::Save() else strlcpy(fn, fi.fFilename,512); - gROOT->ProcessLine(Form("gROOT->SaveObjectAs((TASPaletteEditor*)0x%zx,\"%s\",\"%s\");",(size_t)this,fn,"q")); + gROOT->ProcessLine(TString::Format("gROOT->SaveObjectAs((TASPaletteEditor*)0x%zx,\"%s\",\"%s\");",(size_t)this,fn,"q")); } } diff --git a/graf2d/asimage/src/TASPluginGS.cxx b/graf2d/asimage/src/TASPluginGS.cxx index 4bfcc428812e6..78ffb2c8d900d 100644 --- a/graf2d/asimage/src/TASPluginGS.cxx +++ b/graf2d/asimage/src/TASPluginGS.cxx @@ -64,6 +64,8 @@ TASPluginGS::TASPluginGS(const char *ext) : TASImagePlugin(ext) TASPluginGS::~TASPluginGS() { + ROOT::CallRecursiveRemoveIfNeeded(*this); + delete [] fInterpreter; fInterpreter = nullptr; } @@ -120,7 +122,7 @@ ASImage *TASPluginGS::File2ASImage(const char *filename) // command line to execute TString cmd = fInterpreter; if (eps) { - cmd += Form(" -g%dx%d", width, height); + cmd += TString::Format(" -g%dx%d", width, height); } cmd += " -dSAFER -dBATCH -dNOPAUSE -dQUIET -sDEVICE=png16m -dGraphicsAlphaBits=4 -sOutputFile=- "; cmd += filename; diff --git a/graf2d/asimage/src/libAfterImage/.depend b/graf2d/asimage/src/libAfterImage/.depend index 26d9504f3182a..2a5eb411d9a96 100644 --- a/graf2d/asimage/src/libAfterImage/.depend +++ b/graf2d/asimage/src/libAfterImage/.depend @@ -22,13 +22,6 @@ asimage.h \ asvisual.h -./asimagexml.o : \ - win32/config.h \ - config.h \ - afterimage.h \ - imencdec.h \ - pixmap.h - ./asstorage.o : \ win32/config.h \ config.h \ @@ -97,19 +90,8 @@ xpm.h \ ungif.h \ import.h \ - asimagexml.h \ transform.h -./pixmap.o : \ - win32/config.h \ - config.h \ - asvisual.h \ - blender.h \ - asimage.h \ - imencdec.h \ - ximage.h \ - transform.h \ - pixmap.h ./transform.o : \ win32/config.h \ diff --git a/graf2d/asimage/src/libAfterImage/.shared b/graf2d/asimage/src/libAfterImage/.shared index 5497d2bc9f946..5c1af64a5fd35 100644 --- a/graf2d/asimage/src/libAfterImage/.shared +++ b/graf2d/asimage/src/libAfterImage/.shared @@ -2,7 +2,6 @@ LIBAFTERIMAGE_OBJS = \ $(LIBAFTERIMAGE_PATH)/asimage.c \ $(LIBAFTERIMAGE_PATH)/ascmap.c \ $(LIBAFTERIMAGE_PATH)/asfont.c \ - $(LIBAFTERIMAGE_PATH)/asimagexml.c \ $(LIBAFTERIMAGE_PATH)/asstorage.c \ $(LIBAFTERIMAGE_PATH)/asvisual.c \ $(LIBAFTERIMAGE_PATH)/blender.c \ @@ -12,7 +11,6 @@ LIBAFTERIMAGE_OBJS = \ $(LIBAFTERIMAGE_PATH)/export.c \ $(LIBAFTERIMAGE_PATH)/imencdec.c \ $(LIBAFTERIMAGE_PATH)/import.c \ - $(LIBAFTERIMAGE_PATH)/pixmap.c \ $(LIBAFTERIMAGE_PATH)/transform.c \ $(LIBAFTERIMAGE_PATH)/ungif.c \ $(LIBAFTERIMAGE_PATH)/xcf.c \ @@ -27,7 +25,6 @@ LIBAFTERIMAGE_INCS = \ $(LIBAFTERIMAGE_PATH)/asfont.h \ $(LIBAFTERIMAGE_PATH)/asim_afterbase.h \ $(LIBAFTERIMAGE_PATH)/asimage.h \ - $(LIBAFTERIMAGE_PATH)/asimagexml.h \ $(LIBAFTERIMAGE_PATH)/asstorage.h \ $(LIBAFTERIMAGE_PATH)/asvisual.h \ $(LIBAFTERIMAGE_PATH)/blender.h \ @@ -37,7 +34,6 @@ LIBAFTERIMAGE_INCS = \ $(LIBAFTERIMAGE_PATH)/export.h \ $(LIBAFTERIMAGE_PATH)/imencdec.h \ $(LIBAFTERIMAGE_PATH)/import.h \ - $(LIBAFTERIMAGE_PATH)/pixmap.h \ $(LIBAFTERIMAGE_PATH)/transform.h \ $(LIBAFTERIMAGE_PATH)/ungif.h \ $(LIBAFTERIMAGE_PATH)/xcf.h \ diff --git a/graf2d/asimage/src/libAfterImage/CMakeLists.txt b/graf2d/asimage/src/libAfterImage/CMakeLists.txt index 1f2315752fe2e..2769d0f17c7ba 100644 --- a/graf2d/asimage/src/libAfterImage/CMakeLists.txt +++ b/graf2d/asimage/src/libAfterImage/CMakeLists.txt @@ -47,8 +47,8 @@ SET(SRC_FILES libjpeg/jdtrans.c libjpeg/jerror.c libjpeg/jfdctflt.c libjpeg/jfdctfst.c libjpeg/jfdctint.c libjpeg/jidctflt.c libjpeg/jidctfst.c libjpeg/jidctint.c libjpeg/jmemmgr.c libjpeg/jmemnobs.c libjpeg/jquant1.c libjpeg/jquant2.c libjpeg/jutils.c libungif/dgif_lib.c libungif/egif_lib.c libungif/gif_err.c libungif/gifalloc.c libungif/gif_hash.c afterbase.c ascmap.c asfont.c - asimage.c asstorage.c asimagexml.c asvisual.c blender.c bmp.c char2uni.c - export.c import.c pixmap.c transform.c ungif.c xcf.c ximage.c xpm.c draw.c + asimage.c asstorage.c asvisual.c blender.c bmp.c char2uni.c + export.c import.c transform.c ungif.c xcf.c ximage.c xpm.c draw.c imencdec.c scanline.c ) diff --git a/graf2d/asimage/src/libAfterImage/Makefile.in b/graf2d/asimage/src/libAfterImage/Makefile.in index 3eb037de3a097..7729775f54cc4 100644 --- a/graf2d/asimage/src/libAfterImage/Makefile.in +++ b/graf2d/asimage/src/libAfterImage/Makefile.in @@ -37,16 +37,16 @@ ZLIB_OBJS = zlib/adler32.o zlib/compress.o zlib/crc32.o \ LIBUNGIF_OBJS = libungif/dgif_lib.o libungif/egif_lib.o libungif/gifalloc.o \ libungif/gif_err.o libungif/gif_hash.o -AFTERIMAGE_OBJS= @AFTERBASE_C@ asimage.o ascmap.o asfont.o asimagexml.o asstorage.o \ +AFTERIMAGE_OBJS= @AFTERBASE_C@ asimage.o ascmap.o asfont.o asstorage.o \ asvisual.o blender.o bmp.o char2uni.o draw.o export.o imencdec.o import.o \ - pixmap.o scanline.o transform.o ungif.o xcf.o ximage.o xpm.o + scanline.o transform.o ungif.o xcf.o ximage.o xpm.o ################################################################ # library specifics : LIB_INCS= afterimage.h afterbase.h ascmap.h asfont.h asim_afterbase.h \ - asimage.h asimagexml.h asstorage.h asvisual.h blender.h bmp.h char2uni.h \ - draw.h export.h imencdec.h import.h pixmap.h scanline.h transform.h ungif.h \ + asimage.h asstorage.h asvisual.h blender.h bmp.h char2uni.h \ + draw.h export.h imencdec.h import.h scanline.h transform.h ungif.h \ xcf.h ximage.h xpm.h xwrap.h LIB_OBJS= @JPEG_OBJS@ @ZLIB_OBJS@ @PNG_OBJS@ @UNGIF_OBJS@ $(AFTERIMAGE_OBJS) @@ -104,7 +104,7 @@ INSTALL_SCRIPT = @INSTALL@ -m 755 INCS_EXTRA = @XPM_CFLAGS@ @JPEG_CFLAGS@ @PNG_CFLAGS@ @GIF_CFLAGS@ @TIFF_CFLAGS@ @SVG_CFLAGS@ @TTF_INCLUDES@ INCS_X = @X_CFLAGS@ -INCS_PRIVATE = +INCS_PRIVATE = INCLUDES = $(INCS_EXTRA) $(INCS_PRIVATE) $(INCS_X) USER_LD_FLAGS = @user_ldflags@ @@ -126,7 +126,7 @@ AFTER_APP_MAN_DIR = $(DESTDIR)@mandir@/man1 AFTER_SHAREDIR = $(DESTDIR)@datadir@/$(LIB_DIR_NAME) AFTER_DOC_DIR = $(AFTER_SHAREDIR)/doc -# We want to build both static and dynamic libs, as some service apps may need +# We want to build both static and dynamic libs, as some service apps may need # static library as they gets run at compile time (ASDocGen for example) # but we only install whats selected all: $(LIB_STATIC) @LIBPROG@ $(INSTALLONBUILD) apps @@ -210,7 +210,7 @@ install.inc: install.apps: install.lib @(if test -d apps; then cd apps; $(MAKE) install || exit 1; fi) -# uninstallation targets : +# uninstallation targets : # STATIC_LIB_FILES=$(LIBDIR)/$(LIB_STATIC) DYN_LIB_FILES=$(LIBDIR)/$(LIB_SHARED).$(LIBVERMAJOR) $(LIBDIR)/$(LIB_SHARED) $(LIBDIR)/$(LIB_SHARED).$(LIBVER) @@ -225,7 +225,7 @@ uninstall.dyn: @for i in $(DYN_LIB_FILES); do \ if [ -f $$i ] ; then echo $(RMF) $$i; $(RMF) $$i; fi; \ done - + uninstall.cyg: @for i in $(CYGWIN_LIB_FILES); do \ if [ -f $$i ] ; then echo $(RMF) $$i; $(RMF) $$i; fi; \ @@ -266,7 +266,7 @@ clean: @(if test -d apps; then cd apps; $(MAKE) clean || exit 1; fi) distclean: clean - $(RMF) $(LIB_SHARED) $(LIB_SHARED_CYG) $(LIB_SHARED_CYG_AR) $(LIB_STATIC) *.o *.so.* *~ *% *.bak \#* *.orig core Makefile + $(RMF) $(LIB_SHARED) $(LIB_SHARED_CYG) $(LIB_SHARED_CYG_AR) $(LIB_STATIC) *.o *.so.* *~ *% *.bak \#* *.orig core Makefile @(if test -d apps; then cd apps; $(MAKE) distclean || exit 1; fi) indent: @@ -384,7 +384,7 @@ install.man: $(INSTALL_DATA) $$page_name.man $(AFTER_MAN_DIR)/$$page_name.3x; \ done; cd ../..; \ fi - + install.doc: @if [ -d doc/html ] ; then \ diff --git a/graf2d/asimage/src/libAfterImage/afterimage.h b/graf2d/asimage/src/libAfterImage/afterimage.h index f5da60cae249c..25c6e137000fa 100644 --- a/graf2d/asimage/src/libAfterImage/afterimage.h +++ b/graf2d/asimage/src/libAfterImage/afterimage.h @@ -14,15 +14,13 @@ #include "asfont.h" #include "ximage.h" #include "transform.h" -#include "asimagexml.h" #include "import.h" #include "export.h" -#include "pixmap.h" #include "char2uni.h" /****h* libAfterImage/libAfterImage * NAME - * libAfterImage - generic imaging library originally designed for + * libAfterImage - generic imaging library originally designed for * AfterStep X Window Manager. * * PURPOSE @@ -262,7 +260,7 @@ * asimage2mask_ximage(), asimage2pixmap(), asimage2mask() * * Transformations : - * scale_asimage(), tile_asimage(), merge_layers(), + * scale_asimage(), tile_asimage(), merge_layers(), * make_gradient(), * flip_asimage(), mirror_asimage(), pad_asimage(), * blur_asimage_gauss(), fill_asimage(), adjust_asimage_hsv() diff --git a/graf2d/asimage/src/libAfterImage/asimage.h b/graf2d/asimage/src/libAfterImage/asimage.h index 50cd58318e473..962c16603b881 100644 --- a/graf2d/asimage/src/libAfterImage/asimage.h +++ b/graf2d/asimage/src/libAfterImage/asimage.h @@ -565,7 +565,7 @@ Bool asimage_replace (ASImage *im, ASImage *from); * set_asimage_vector() This function replaces contents of the vector * member of ASImage structure with new double precision data. * SYNOPSIS - * set_asimage_vector( ASImage *im, register double *vector ); + * set_asimage_vector( ASImage *im, double *vector ); * INPUTS * im - pointer to valid ASImage structure. * vector - scientific data to attach to the image. @@ -573,7 +573,7 @@ Bool asimage_replace (ASImage *im, ASImage *from); * Data must have size of width*height ahere width and height are size of * the ASImage. *********/ -Bool set_asimage_vector( ASImage *im, register double *vector ); +Bool set_asimage_vector( ASImage *im, double *vector ); /****f* libAfterImage/asimage/vectorize_asimage() * NAME * vectorize_asimage() This function replaces contents of the vector @@ -792,7 +792,7 @@ ASGradient *flip_gradient( ASGradient *orig, int flip ); * NAME * init_image_layers() - initialize set of ASImageLayer structures. * SYNOPSIS - * void init_image_layers( register ASImageLayer *l, int count ); + * void init_image_layers(ASImageLayer *l, int count ); * INPUTS * l - pointer to valid ASImageLayer structure. * count - number of elements to initialize. @@ -800,7 +800,7 @@ ASGradient *flip_gradient( ASGradient *orig, int flip ); * Initializes array on ASImageLayer structures to sensible defaults. * Basically - all zeros and merge_scanlines == alphablend_scanlines. *********/ -void init_image_layers( register ASImageLayer *l, int count ); +void init_image_layers(ASImageLayer *l, int count ); /****f* libAfterImage/asimage/create_image_layers() * NAME * create_image_layers() - allocate and initialize set of ASImageLayer's. @@ -822,7 +822,7 @@ ASImageLayer *create_image_layers( int count ); * NAME * destroy_image_layers() - destroy set of ASImageLayer structures. * SYNOPSIS - * void destroy_image_layers( register ASImageLayer *l, + * void destroy_image_layers(ASImageLayer *l, * int count, * Bool reusable ); * INPUTS @@ -836,7 +836,7 @@ ASImageLayer *create_image_layers( int count ); * If there was ASImage and/or ASImageBevel attached to it - it will be * deallocated as well. *********/ -void destroy_image_layers( register ASImageLayer *l, int count, Bool reusable ); +void destroy_image_layers(ASImageLayer *l, int count, Bool reusable ); /****f* libAfterImage/asimage/asimage_add_line() * NAME @@ -945,7 +945,7 @@ void destroy_image_layers( register ASImageLayer *l, int count, Bool reusable ); *********/ size_t asimage_add_line (ASImage * im, ColorPart color, CARD32 * data, unsigned int y); size_t asimage_add_line_mono (ASImage * im, ColorPart color, CARD8 value, unsigned int y); -size_t asimage_add_line_bgra (ASImage * im, register CARD32 * data, unsigned int y); +size_t asimage_add_line_bgra (ASImage * im, CARD32 * data, unsigned int y); ASFlagType get_asimage_chanmask( ASImage *im); int check_asimage_alpha (ASVisual *asv, ASImage *im ); @@ -1076,7 +1076,7 @@ do{ f((c1).red,(c2).red,(c3).red,(c4).red,(o1).red,(o2).red,(p),(len+(len&0x01)) #define QUANT_ERR_BITS 8 #define QUANT_ERR_MASK 0x000000FF -void copy_component( register CARD32 *src, register CARD32 *dst, int *unused, int len ); +void copy_component(CARD32 *src, CARD32 *dst, int *unused, int len ); #ifdef X_DISPLAY_MISSING typedef struct XRectangle @@ -1110,7 +1110,7 @@ XRectangle* get_asimage_channel_rects( ASImage *src, int channel, unsigned int threshold, unsigned int *rects_count_ret ); void -raw2scanline( register CARD8 *row, struct ASScanline *buf, CARD8 *gamma_table, unsigned int width, Bool grayscale, Bool do_alpha ); +raw2scanline(CARD8 *row, struct ASScanline *buf, CARD8 *gamma_table, unsigned int width, Bool grayscale, Bool do_alpha ); #ifdef __cplusplus } diff --git a/graf2d/asimage/src/libAfterImage/asimagexml.c b/graf2d/asimage/src/libAfterImage/asimagexml.c deleted file mode 100644 index 8630231a90c5f..0000000000000 --- a/graf2d/asimage/src/libAfterImage/asimagexml.c +++ /dev/null @@ -1,2490 +0,0 @@ -/* - * Copyright (c) 2001 Sasha Vasko - * Copyright (c) 2001 Eric Kowalski - * Copyright (c) 2001 Ethan Fisher - * - * This module is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - */ - -#undef LOCAL_DEBUG -#ifdef _WIN32 -#include "win32/config.h" -#else -#include "config.h" -#endif - -#include -#include -#ifdef HAVE_UNISTD_H -#include -#endif -#ifdef HAVE_STDLIB_H -#include -#endif -#ifdef HAVE_STDARG_H -#include -#endif -#include -#if TIME_WITH_SYS_TIME -# include -# include -#else -# if HAVE_SYS_TIME_H -# include -# else -# include -# endif -#endif -#ifndef _WIN32 -#include -#endif - -#ifdef _WIN32 -# include "win32/afterbase.h" -#else -# include "afterbase.h" -#endif -#include "afterimage.h" -#include "imencdec.h" - -static char* cdata_str = XML_CDATA_STR; - -/****h* libAfterImage/asimagexml - * NAME - * ascompose is a tool to compose image(s) and display/save it based on - * supplied XML input file. - * - * DESCRIPTION - * ascompose reads supplied XML data, and manipulates image accordingly. - * It could transform images from files of any supported file format, - * draw gradients, render antialiased texturized text, perform - * superimposition of arbitrary number of images, and save images into - * files of any of supported output file formats. - * - * At any point, the result of any operation could be assigned a name, - * and later on referenced under this name. - * - * At any point during the script processing, result of any operation - * could be saved into a file of any supported file types. - * - * Internal image format is 32bit ARGB with 8bit per channel. - * - * Last image referenced, will be displayed in X window, unless -n option - * is specified. If -r option is specified, then this image will be - * displayed in root window of X display, effectively setting a background - * for a desktop. If -o option is specified, this image will also be - * saved into the file or requested type. - * - * TAGS - * - * Here is the list and description of possible XML tags to use in the - * script : - * img - load image from the file. - * recall - recall previously loaded/generated image by its name. - * text - render text string into new image. - * save - save an image into the file. - * bevel - draw solid bevel frame around the image. - * gradient - render multipoint gradient. - * mirror - create mirror copy of an image. - * blur - perform gaussian blur on an image. - * rotate - rotate/flip image in 90 degree increments. - * scale - scale an image to arbitrary size. - * slice - enlarge image to arbitrary size leaving corners unchanged. - * crop - crop an image to arbitrary size. - * tile - tile an image to arbitrary size. - * hsv - adjust Hue, Saturation and Value of an image. - * pad - pad image with solid color from either or all sides. - * solid - generate new image of requested size, filled with solid - * color. - * composite - superimpose arbitrary number of images using one of 15 - * available methods. - * if - conditional processing based on value of the variables - * set - sets value of the variable - * printf - formated printing of the value of the variable - * - * Each tag generates new image as the result of the transformation - - * existing images are never modified and could be reused as many times - * as needed. See below for description of each tag. - * - * Whenever numerical values are involved, the basic math ops (add, - * subtract, multiply, divide), unary minus, and parentheses are - * supported. - * - * Operator precedence is NOT supported. Percentages are allowed, and - * apply to either width or height of the appropriate image (usually - * the refid image). - * - * Also, variables of the form $image.width and $image.height are - * supported. $image.width is the width of the image with refid "image", - * and $image.height is the height of the same image. The special - * $xroot.width and $xroot.height values are defined by the X root - * window, if there is one. This allows images to be scaled to the - * desktop size: . - * - * Each tag is only allowed to return ONE image. - * -* - *****/ - -static ASImageManager *_as_xml_image_manager = NULL ; -static ASFontManager *_as_xml_font_manager = NULL ; - -void set_xml_image_manager( ASImageManager *imman ) -{ - _as_xml_image_manager = imman ; -} -void set_xml_font_manager( ASFontManager *fontman ) -{ - _as_xml_font_manager = fontman ; -} - - - - -ASImageManager *create_generic_imageman(const char *path) -{ - ASImageManager *my_imman = NULL ; - char *path2 = copy_replace_envvar( getenv( ASIMAGE_PATH_ENVVAR ) ); - show_progress("image path is \"%s\".", path2?path2:"(null)" ); - if( path != NULL ) - my_imman = create_image_manager( NULL, SCREEN_GAMMA, path, path2, NULL ); - else - my_imman = create_image_manager( NULL, SCREEN_GAMMA, path2, NULL ); - LOCAL_DEBUG_OUT( "created image manager %p with search path \"%s\"", my_imman, my_imman->search_path[0] ); - if( path2 ) - free( path2 ); - return my_imman; -} - -ASFontManager *create_generic_fontman(Display *dpy, const char *path) -{ - ASFontManager *my_fontman ; - char *path2 = copy_replace_envvar( getenv( ASFONT_PATH_ENVVAR ) ); - if( path != NULL ) - { - if( path2 != NULL ) - { - int path_len = strlen(path); - char *full_path = safemalloc( path_len+1+strlen(path2)+1); - strcpy( full_path, path ); - full_path[path_len] = ':'; - strcpy( &(full_path[path_len+1]), path2 ); - free( path2 ); - path2 = full_path ; - }else - path2 = (char*)path ; - } - my_fontman = create_font_manager( dpy, path2, NULL ); - if( path2 && path2 != path ) - free( path2 ); - - return my_fontman; -} - -ASImage * -compose_asimage_xml_from_doc(ASVisual *asv, ASImageManager *imman, ASFontManager *fontman, xml_elem_t* doc, ASFlagType flags, int verbose, Window display_win, const char *path, int target_width, int target_height) -{ - /* Build the image(s) from the xml document structure. */ - ASImage* im = NULL; - ASImageManager *my_imman = imman, *old_as_xml_imman = _as_xml_image_manager ; - ASFontManager *my_fontman = fontman, *old_as_xml_fontman = _as_xml_font_manager ; - int my_imman_curr_dir_path_idx = MAX_SEARCH_PATHS ; - - if (doc) - { - int old_target_width = -1; - int old_target_height = -1; - xml_elem_t* ptr; - Bool local_dir_included = False ; - - asxml_var_init(); -#if (HAVE_AFTERBASE_FLAG==1) - if (verbose > 1) - { - xml_print(doc); - fprintf(stderr, "\n"); - } -#endif - - if( my_imman == NULL ) - { - if( _as_xml_image_manager == NULL ) - { - local_dir_included = True ; - _as_xml_image_manager = create_generic_imageman( path );/* we'll want to reuse it in case of recursion */ - } - my_imman = _as_xml_image_manager ; - } - - if( !local_dir_included ) - { - register int i = 0; - char **paths = my_imman->search_path ; - while( i < MAX_SEARCH_PATHS && paths[i] != NULL ) ++i; - if( i < MAX_SEARCH_PATHS ) - { - paths[i] = mystrdup(path) ; - paths[i+1] = NULL ; - my_imman_curr_dir_path_idx = i ; - } - } - - if( my_fontman == NULL ) - { - if( _as_xml_font_manager == NULL ) - _as_xml_font_manager = create_generic_fontman( asv->dpy, path ); - my_fontman = _as_xml_font_manager ; - } - - /* save old target size to be restored at the end */ - old_target_width = asxml_var_get(ASXMLVAR_TargetWidth); - old_target_height = asxml_var_get(ASXMLVAR_TargetHeight); - /* set current target size */ - asxml_var_insert(ASXMLVAR_TargetWidth, target_width); - asxml_var_insert(ASXMLVAR_TargetHeight, target_height); - - for (ptr = doc->child ; ptr ; ptr = ptr->next) { - ASImage* tmpim = build_image_from_xml(asv, my_imman, my_fontman, ptr, NULL, flags, verbose, display_win); - if (tmpim && im) safe_asimage_destroy(im); - if (tmpim) im = tmpim; - } - if (im && (target_width > 0 || target_height > 0) ) - { - int scale_width = (target_width>0)?target_width:im->width; - int scale_height = (target_height>0)?target_height:im->height; - if (im->width != scale_width || im->height != scale_height) - { - ASImage *tmp = scale_asimage( asv, im, scale_width, scale_height, ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT ); - if (tmp != NULL) - { - safe_asimage_destroy(im); - im = tmp; - } - } - } - /* restore old target size to be restored at the end */ - asxml_var_insert(ASXMLVAR_TargetWidth, old_target_width); - asxml_var_insert(ASXMLVAR_TargetHeight, old_target_height); - -LOCAL_DEBUG_OUT( "result im = %p, im->imman = %p, my_imman = %p, im->magic = %8.8lX", im, im?im->imageman:NULL, my_imman, im?im->magic:0 ); - - if( my_imman_curr_dir_path_idx < MAX_SEARCH_PATHS && my_imman->search_path[my_imman_curr_dir_path_idx]) - { - free(my_imman->search_path[my_imman_curr_dir_path_idx]); - my_imman->search_path[my_imman_curr_dir_path_idx] = NULL ; - } - - if( my_imman != imman && my_imman != old_as_xml_imman ) - {/* detach created image from imman to be destroyed : */ - if( im && im->imageman == my_imman ) - forget_asimage( im ); - destroy_image_manager(my_imman, False); - } - - if( my_fontman != fontman && my_fontman != old_as_xml_fontman ) - destroy_font_manager(my_fontman, False); - /* must restore managers to its original state */ - _as_xml_image_manager = old_as_xml_imman ; - _as_xml_font_manager = old_as_xml_fontman ; - - } - LOCAL_DEBUG_OUT( "returning im = %p, im->imman = %p, im->magic = %8.8lX", im, im?im->imageman:NULL, im?im->magic:0 ); - return im; -} - -ASImage * -compose_asimage_xml_at_size(ASVisual *asv, ASImageManager *imman, ASFontManager *fontman, char *doc_str, ASFlagType flags, int verbose, Window display_win, const char *path, int target_width, int target_height) -{ - xml_elem_t* doc = xml_parse_doc(doc_str, NULL); - ASImage *im = compose_asimage_xml_from_doc(asv, imman, fontman, doc, flags, verbose, display_win, path, target_width, target_height); - if (doc) - xml_elem_delete(NULL, doc); - return im; -} - -inline ASImage * -compose_asimage_xml(ASVisual *asv, ASImageManager *imman, ASFontManager *fontman, char *doc_str, ASFlagType flags, int verbose, Window display_win, const char *path) -{ - xml_elem_t* doc = xml_parse_doc(doc_str, NULL); - ASImage *im = compose_asimage_xml_from_doc(asv, imman, fontman, doc, flags, verbose, display_win, path, -1, -1); - if (doc) - xml_elem_delete(NULL, doc); - return im; -} - - -Bool save_asimage_to_file(const char *file2bsaved, ASImage *im, - const char *strtype, - const char *compress, - const char *opacity, - int delay, int replace) -{ - ASImageExportParams params ; - - memset( ¶ms, 0x00, sizeof(params) ); - params.gif.flags = EXPORT_ALPHA ; - if (strtype == NULL || !mystrcasecmp(strtype, "jpeg") || !mystrcasecmp(strtype, "jpg")) { - params.type = ASIT_Jpeg; - params.jpeg.quality = (compress==NULL)?-1:100-atoi(compress); - if( params.jpeg.quality > 100 ) - params.jpeg.quality = 100; - } else if (!mystrcasecmp(strtype, "bitmap") || !mystrcasecmp(strtype, "bmp")) { - params.type = ASIT_Bmp; - } else if (!mystrcasecmp(strtype, "png")) { - params.type = ASIT_Png; - params.png.compression = (compress==NULL)?-1:atoi(compress); - if( params.png.compression > 99 ) - params.png.compression = 99; - } else if (!mystrcasecmp(strtype, "xcf")) { - params.type = ASIT_Xcf; - } else if (!mystrcasecmp(strtype, "ppm")) { - params.type = ASIT_Ppm; - } else if (!mystrcasecmp(strtype, "pnm")) { - params.type = ASIT_Pnm; - } else if (!mystrcasecmp(strtype, "ico")) { - params.type = ASIT_Ico; - } else if (!mystrcasecmp(strtype, "cur")) { - params.type = ASIT_Cur; - } else if (!mystrcasecmp(strtype, "gif")) { - params.type = ASIT_Gif; - params.gif.flags |= EXPORT_APPEND ; - params.gif.opaque_threshold = (opacity==NULL)?127:atoi(opacity) ; - params.gif.dither = (compress==NULL)?3:atoi(compress)/17; - if( params.gif.dither > 6 ) - params.gif.dither = 6; - params.gif.animate_delay = delay ; - } else if (!mystrcasecmp(strtype, "xpm")) { - params.type = ASIT_Xpm; - params.xpm.opaque_threshold = (opacity==NULL)?127:atoi(opacity) ; - params.xpm.dither = (compress==NULL)?3:atoi(compress)/17; - if( params.xpm.dither > 6 ) - params.xpm.dither = 6; - } else if (!mystrcasecmp(strtype, "xbm")) { - params.type = ASIT_Xbm; - } else if (!mystrcasecmp(strtype, "tiff")) { - params.type = ASIT_Tiff; - params.tiff.compression_type = TIFF_COMPRESSION_NONE ; - if( compress ) - { - if( mystrcasecmp( compress, "deflate" ) == 0 ) - params.tiff.compression_type = TIFF_COMPRESSION_DEFLATE ; - else if( mystrcasecmp( compress, "jpeg" ) == 0 ) - params.tiff.compression_type = TIFF_COMPRESSION_JPEG ; - else if( mystrcasecmp( compress, "ojpeg" ) == 0 ) - params.tiff.compression_type = TIFF_COMPRESSION_OJPEG ; - else if( mystrcasecmp( compress, "packbits" ) == 0 ) - params.tiff.compression_type = TIFF_COMPRESSION_PACKBITS ; - } - } else { - show_error("File type not found."); - return(0); - } - - if( replace && file2bsaved ) - unlink( file2bsaved ); - - return ASImage2file(im, NULL, file2bsaved, params.type, ¶ms); - -} - -void show_asimage(ASVisual *asv, ASImage* im, Window w, long delay) -{ -#ifndef X_DISPLAY_MISSING - if ( im && w && asv) - { - Pixmap p = asimage2pixmap(asv, w, im, NULL, False); - struct timeval value; - - XSetWindowBackgroundPixmap( asv->dpy, w, p ); - XClearWindow( asv->dpy, w ); - XFlush( asv->dpy ); - XFreePixmap( asv->dpy, p ); - p = None ; - value.tv_usec = delay % 10000; - value.tv_sec = delay / 10000; - PORTABLE_SELECT (1, 0, 0, 0, &value); - } -#endif /* X_DISPLAY_MISSING */ -} - -typedef struct ASImageXMLState -{ - ASFlagType flags ; - ASVisual *asv; - ASImageManager *imman ; - ASFontManager *fontman ; - - int verbose ; - Window display_win ; - -}ASImageXMLState; - - -ASImage *commit_xml_image_built( ASImageXMLState *state, char *id, ASImage *result ) -{ - if (state && id && result) - { - char* buf = NEW_ARRAY(char, strlen(id) + 1 + 6 + 1); - if( state->verbose > 1 ) - show_progress("Storing image id [%s] with image manager %p .", id, state->imman); - sprintf(buf, "%s.width", id); - asxml_var_insert(buf, result->width); - sprintf(buf, "%s.height", id); - asxml_var_insert(buf, result->height); - free(buf); - if( result->imageman != NULL ) - { - ASImage *tmp = clone_asimage(result, SCL_DO_ALL ); - safe_asimage_destroy(result ); - result = tmp ; - } - if( result ) - { - if( !store_asimage( state->imman, result, id ) ) - { - show_warning("Failed to store image id [%s].", id); - //safe_asimage_destroy(result ); - //result = fetch_asimage( state->imman, id ); - /*show_warning("Old image with the name fetched as %p.", result);*/ - }else - { - /* normally generated image will be destroyed right away, so we need to - * increase ref count, in order to preserve it for future uses : */ - dup_asimage( result ); - } - } - } - return result; -} - -static void -translate_tag_size( const char *width_str, const char *height_str, ASImage *imtmp, ASImage *refimg, int *width_ret, int *height_ret ) -{ - int width_ref = 0; - int height_ref = 0; - int width = 0, height = 0 ; - LOCAL_DEBUG_OUT("width_str = \"%s\", height_str = \"%s\", imtmp = %p, refimg = %p", width_str?width_str:"(null)", height_str?height_str:"(null)", imtmp, refimg ); - - if( imtmp ) - { - width_ref = width = imtmp->width ; - height_ref = height = imtmp->height ; - } - if (refimg) - { - width_ref = refimg->width; - height_ref = refimg->height; - } - if( width_str ) - { - if( width_str[0] == '$' || isdigit( (int)width_str[0] ) ) - width = (int)parse_math(width_str, NULL, width); - } - if( height_str ) - { - if( height_str[0] == '$' || isdigit( (int)height_str[0] ) ) - height = (int)parse_math(height_str, NULL, height); - } - if( width_str && height_ref > 0 && mystrcasecmp(width_str,"proportional") == 0 ) - width = (width_ref * height) / height_ref ; - else if( height_str && width_ref > 0 && mystrcasecmp(height_str,"proportional") == 0 ) - height = (height_ref * width) / width_ref ; - if( width_ret ) - *width_ret = (width==0)?(imtmp?imtmp->width:(refimg?refimg->width:0)):width; - if( height_ret ) - *height_ret = (height==0)?(imtmp?imtmp->height:(refimg?refimg->height:0)):height; - - LOCAL_DEBUG_OUT("width = %d, height = %d", *width_ret, *height_ret ); - -} - -/****** libAfterImage/asimagexml/text - * NAME - * text - render text string into new image, using specific font, size - * and texture. - * SYNOPSIS - * My Text Here - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * font Optional. Default is "fixed". Font to use for text. - * point Optional. Default is 12. Size of text in points. - * fgcolor Optional. No default. The text will be drawn in this color. - * bgcolor Optional. No default. The area behind the text will be drawn - * in this color. - * fgimage Optional. No default. The text will be textured by this image. - * bgimage Optional. No default. The area behind the text will be filled - * with this image. - * spacing Optional. Default 0. Extra pixels to place between each glyph. - * type Optional. Default 0. Valid values are from 0 to 7 and each - * represeend different 3d type. - * NOTES - * without bgcolor, fgcolor, fgimage, or bgimage will NOT - * produce visible output by itself. See EXAMPLES below. - ******/ -static ASImage * -handle_asxml_tag_text( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm ) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - const char* text = NULL; - const char* font_name = "fixed"; - const char* fgimage_str = NULL; - const char* bgimage_str = NULL; - const char* fgcolor_str = NULL; - const char* bgcolor_str = NULL; - ARGB32 fgcolor = ARGB32_White, bgcolor = ARGB32_Black; - int point = 12, spacing = 0, type = AST_Plain; - unsigned int width = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "font")) font_name = ptr->parm; - else if (!strcmp(ptr->tag, "point")) point = strtol(ptr->parm, NULL, 0); - else if (!strcmp(ptr->tag, "spacing")) spacing = strtol(ptr->parm, NULL, 0); - else if (!strcmp(ptr->tag, "fgimage")) fgimage_str = ptr->parm; - else if (!strcmp(ptr->tag, "bgimage")) bgimage_str = ptr->parm; - else if (!strcmp(ptr->tag, "fgcolor")) fgcolor_str = ptr->parm; - else if (!strcmp(ptr->tag, "bgcolor")) bgcolor_str = ptr->parm; - else if (!strcmp(ptr->tag, "type")) type = strtol(ptr->parm, NULL, 0); - else if (!strcmp(ptr->tag, "width")) width = strtol(ptr->parm, NULL, 0); - } - for (ptr = doc->child ; ptr && text == NULL ; ptr = ptr->next) - if (!strcmp(ptr->tag, cdata_str)) text = ptr->parm; - - if (text && point > 0) - { - struct ASFont *font = NULL; - if( state->verbose > 1 ) - show_progress("Rendering text [%s] with font [%s] size [%d].", text, font_name, point); - if (state->fontman) font = get_asfont(state->fontman, font_name, 0, point, ASF_GuessWho); - if (font != NULL) - { - ASTextAttributes attr = {ASTA_VERSION_INTERNAL, 0, 0, ASCT_Char, 8, 0, NULL, 0, ARGB32_White, width}; - attr.type = type ; - if( IsUTF8Locale() ) - attr.char_type = ASCT_UTF8 ; - set_asfont_glyph_spacing(font, spacing, 0); - if( fgcolor_str ) - parse_argb_color(fgcolor_str, &(attr.fore_color) ); - - result = draw_fancy_text( text, font, &attr, 0, 0/*autodetect length*/ ); - if (result && fgcolor_str) { -#if 0 - result->back_color = attr.fore_color ; -#else - ASImage* fgimage = create_asimage(result->width, result->height, ASIMAGE_QUALITY_TOP); - parse_argb_color(fgcolor_str, &fgcolor); - fill_asimage(state->asv, fgimage, 0, 0, result->width, result->height, fgcolor); - move_asimage_channel(fgimage, IC_ALPHA, result, IC_ALPHA); - safe_asimage_destroy(result); - result = fgimage ; -#endif - } - if (result && fgimage_str) { - ASImage* fgimage = NULL; - fgimage = get_asimage(state->imman, fgimage_str, 0xFFFFFFFF, 100 ); - if( state->verbose > 1 ) - show_progress("Using image [%s](%p) as foreground. Text size is %dx%d", fgimage_str, fgimage, result->width, result->height); - if (fgimage) { - ASImage *tmp = tile_asimage(state->asv, fgimage, 0, 0, result->width, result->height, 0, ASA_ASImage, 100, ASIMAGE_QUALITY_TOP); - if( tmp ) - { - release_asimage( fgimage ); - fgimage = tmp ; - } - move_asimage_channel(fgimage, IC_ALPHA, result, IC_ALPHA); - safe_asimage_destroy(result); - result = fgimage; - } - } - if (result && (bgcolor_str || bgimage_str)) { - ASImageLayer layers[2]; - init_image_layers(&(layers[0]), 2); - if (bgimage_str) layers[0].im = fetch_asimage(state->imman, bgimage_str); - if (bgcolor_str) - if( parse_argb_color(bgcolor_str, &bgcolor) != bgcolor_str ) - { - if( layers[0].im != NULL ) - layers[0].im->back_color = bgcolor ; - else - layers[0].solid_color = bgcolor ; - } - result->back_color = fgcolor ; - layers[0].dst_x = 0; - layers[0].dst_y = 0; - layers[0].clip_width = result->width; - layers[0].clip_height = result->height; - layers[0].bevel = NULL; - layers[1].im = result; - layers[1].dst_x = 0; - layers[1].dst_y = 0; - layers[1].clip_width = result->width; - layers[1].clip_height = result->height; - result = merge_layers(state->asv, layers, 2, result->width, result->height, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - safe_asimage_destroy( layers[0].im ); - } - } - } - - return result; -} -/****** libAfterImage/asimagexml/composite - * NAME - * composite - superimpose arbitrary number of images on top of each - * other. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * op Optional. Default is "alphablend". The compositing operation. - * Valid values are the standard AS blending ops: add, alphablend, - * allanon, colorize, darken, diff, dissipate, hue, lighten, - * overlay, saturate, screen, sub, tint, value. - * merge Optional. Default is "expand". Valid values are "clip" and - * "expand". Determines whether final image will be expanded to - * the maximum size of the layers, or clipped to the bottom - * layer. - * keep-transparency - * Optional. Default is "0". Valid values are "0" and "1". If - * set to "1", the transparency of the bottom layer will be - * kept for the final image. - * NOTES - * All images surrounded by this tag will be composited with the given op. - * - * ATTRIBUTES - * All tags surrounded by this tag may have some of the common attributes - * in addition to their normal ones. Under no circumstances is there a - * conflict with the normal child attributes: - * - * crefid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "x" - * and "y" will be derived from the width and height of the - * crefid image. - * x Optional. Default is 0. Pixel coordinate of left edge. - * y Optional. Default is 0. Pixel coordinate of top edge. - * align Optional. Alternative to x - allowed values are right, center - * and left. - * valign Optional. Alternative to y - allowed values are top, middle - * and bottom. - * clip_x Optional. Default is 0. X Offset on infinite surface tiled - * with this image, from which to cut portion of an image to be - * used in composition. - * clip_y Optional. Default is 0. Y Offset on infinite surface tiled - * with this image, from which to cut portion of an image to be - * used in composition. - * clip_width - * Optional. Default is image width. Tile image to this width - * prior to superimposition. - * clip_height - * Optional. Default is image height. Tile image to this height - * prior to superimposition. - * tile Optional. Default is 0. If set will cause image to be tiled - * across entire composition, unless overridden by clip_width or - * clip_height. - * tint Optional. Additionally tint an image to specified color. - * Tinting can both lighten and darken an image. Tinting color - * 0 or #7f7f7f7f yields no tinting. Tinting can be performed - * on any channel, including alpha channel. - * SEE ALSO - * libAfterImage - ******/ -static ASImage * -handle_asxml_tag_composite( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm ) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - const char* pop = "alphablend"; - int keep_trans = 0; - int merge = 0; - int num = 0; - int width = 0, height = 0; - ASImageLayer *layers; -#define ASXML_ALIGN_LEFT (0x01<<0) -#define ASXML_ALIGN_RIGHT (0x01<<1) -#define ASXML_ALIGN_TOP (0x01<<2) -#define ASXML_ALIGN_BOTTOM (0x01<<3) - int *align ; - int i ; - merge_scanlines_func op_func = NULL ; - - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "op")) { pop = ptr->parm; op_func = blend_scanlines_name2func(pop); } - else if (!strcmp(ptr->tag, "keep-transparency")) keep_trans = strtol(ptr->parm, NULL, 0); - else if (!strcmp(ptr->tag, "merge") && !mystrcasecmp(ptr->parm, "clip")) merge = 1; - } - /* Find out how many subimages we have. */ - for (ptr = doc->child ; ptr ; ptr = ptr->next) - if (strcmp(ptr->tag, cdata_str)) num++; - - if( num == 0 ) - { - show_warning( "composite tag with no subimages to compose from specified!"); - return NULL; - } - - - if( op_func == NULL ) - { - LOCAL_DEBUG_OUT( "defaulting to alpha-blending%s",""); - op_func = alphablend_scanlines ; - } - /* Build the layers first. */ - layers = create_image_layers( num ); - align = safecalloc( num, sizeof(int)); - - for (num = 0, ptr = doc->child ; ptr ; ptr = ptr->next) - { - int x = 0, y = 0; - int clip_x = 0, clip_y = 0; - int clip_width = 0, clip_height = 0; - ARGB32 tint = 0; - Bool tile = False ; - xml_elem_t* sparm = NULL; - if (!strcmp(ptr->tag, cdata_str)) continue; - if( (layers[num].im = build_image_from_xml(state->asv, state->imman, state->fontman, ptr, &sparm, state->flags, state->verbose, state->display_win)) != NULL ) - { - clip_width = layers[num].im->width; - clip_height = layers[num].im->height; - } - if (sparm) - { - xml_elem_t* tmp; - const char* x_str = NULL; - const char* y_str = NULL; - const char* clip_x_str = NULL; - const char* clip_y_str = NULL; - const char* clip_width_str = NULL; - const char* clip_height_str = NULL; - const char* refid = NULL; - for (tmp = sparm ; tmp ; tmp = tmp->next) { - if (!strcmp(tmp->tag, "crefid")) refid = tmp->parm; - else if (!strcmp(tmp->tag, "x")) x_str = tmp->parm; - else if (!strcmp(tmp->tag, "y")) y_str = tmp->parm; - else if (!strcmp(tmp->tag, "clip_x")) clip_x_str = tmp->parm; - else if (!strcmp(tmp->tag, "clip_y")) clip_y_str = tmp->parm; - else if (!strcmp(tmp->tag, "clip_width")) clip_width_str = tmp->parm; - else if (!strcmp(tmp->tag, "clip_height")) clip_height_str = tmp->parm; - else if (!strcmp(tmp->tag, "tint")) parse_argb_color(tmp->parm, &tint); - else if (!strcmp(tmp->tag, "tile")) tile = True; - else if (!strcmp(tmp->tag, "align")) - { - if (!strcmp(tmp->parm, "left"))set_flags( align[num], ASXML_ALIGN_LEFT); - else if (!strcmp(tmp->parm, "right"))set_flags( align[num], ASXML_ALIGN_RIGHT); - else if (!strcmp(tmp->parm, "center"))set_flags( align[num], ASXML_ALIGN_LEFT|ASXML_ALIGN_RIGHT); - }else if (!strcmp(tmp->tag, "valign")) - { - if (!strcmp(tmp->parm, "top"))set_flags( align[num], ASXML_ALIGN_TOP) ; - else if (!strcmp(tmp->parm, "bottom"))set_flags( align[num], ASXML_ALIGN_BOTTOM); - else if (!strcmp(tmp->parm, "middle"))set_flags( align[num], ASXML_ALIGN_TOP|ASXML_ALIGN_BOTTOM); - } - } - if (refid) { - ASImage* refimg = fetch_asimage(state->imman, refid); - if (refimg) { - x = refimg->width; - y = refimg->height; - } - safe_asimage_destroy(refimg ); - } - x = x_str ? (int)parse_math(x_str, NULL, x) : 0; - y = y_str ? (int)parse_math(y_str, NULL, y) : 0; - clip_x = clip_x_str ? (int)parse_math(clip_x_str, NULL, x) : 0; - clip_y = clip_y_str ? (int)parse_math(clip_y_str, NULL, y) : 0; - if( clip_width_str ) - clip_width = (int)parse_math(clip_width_str, NULL, clip_width); - else if( tile ) - clip_width = 0 ; - if( clip_height_str ) - clip_height = (int)parse_math(clip_height_str, NULL, clip_height); - else if( tile ) - clip_height = 0 ; - } - if (layers[num].im) { - layers[num].dst_x = x; - layers[num].dst_y = y; - layers[num].clip_x = clip_x; - layers[num].clip_y = clip_y; - layers[num].clip_width = clip_width ; - layers[num].clip_height = clip_height ; - layers[num].tint = tint; - layers[num].bevel = 0; - layers[num].merge_scanlines = op_func; - if( clip_width + x > 0 ) - { - if( width < clip_width + x ) - width = clip_width + x; - }else - if (width < (int)(layers[num].im->width)) width = layers[num].im->width; - if( clip_height + y > 0 ) - { - if( height < clip_height + y ) - height = clip_height + y ; - }else - if (height < (int)(layers[num].im->height)) height = layers[num].im->height; - num++; - } - if (sparm) xml_elem_delete(NULL, sparm); - } - - if (num && merge && layers[0].im ) { - width = layers[0].im->width; - height = layers[0].im->height; - } - - - for (i = 0 ; i < num ; i++) - { - if( get_flags(align[i], ASXML_ALIGN_LEFT|ASXML_ALIGN_RIGHT ) ) - { - int im_width = ( layers[i].clip_width == 0 )? layers[i].im->width : layers[i].clip_width ; - int x = 0 ; - if( get_flags( align[i], ASXML_ALIGN_RIGHT ) ) - x = width - im_width ; - if( get_flags( align[i], ASXML_ALIGN_LEFT ) ) - x /= 2; - layers[i].dst_x = x; - } - if( get_flags(align[i], ASXML_ALIGN_TOP|ASXML_ALIGN_BOTTOM ) ) - { - int im_height = ( layers[i].clip_height == 0 )? layers[i].im->height : layers[i].clip_height; - int y = 0 ; - if( get_flags( align[i], ASXML_ALIGN_BOTTOM ) ) - y = height - im_height ; - if( get_flags( align[i], ASXML_ALIGN_TOP ) ) - y /= 2; - layers[i].dst_y = y; - } - if( layers[i].clip_width == 0 ) - layers[i].clip_width = width - layers[i].dst_x; - if( layers[i].clip_height == 0 ) - layers[i].clip_height = height - layers[i].dst_y; - } - - if (state->verbose > 1) { - show_progress("Compositing [%d] image(s) with op [%s]. Final geometry [%dx%d].", num, pop, width, height); - if (keep_trans) show_progress(" Keeping transparency."); - - for (i = 0 ; i < num ; i++) { - show_progress(" Image [%d] geometry [%dx%d+%d+%d]", i, layers[i].clip_width, layers[i].clip_height, layers[i].dst_x, layers[i].dst_y); - if (layers[i].tint) show_progress(" tint (#%08x)", (unsigned int)layers[i].tint); - } - } - - result = merge_layers( state->asv, layers, num, width, height, - ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - if (keep_trans && result && layers[0].im) - copy_asimage_channel(result, IC_ALPHA, layers[0].im, IC_ALPHA); - - while (--num >= 0 ) - safe_asimage_destroy( layers[num].im ); - - free(align); - free(layers); - - return result; -} - -/****** libAfterImage/asimagexml/img - * NAME - * img - load image from the file. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * src Required. The filename (NOT URL) of the image file to load. - * NOTES - * The special image src "xroot:" will import the background image - * of the root X window, if any. No attempt will be made to offset this - * image to fit the location of the resulting window, if one is displayed. - ******/ -static ASImage * -handle_asxml_tag_img( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, int dst_width, int dst_height) -{ - ASImage *result = NULL ; - const char* src = NULL; - xml_elem_t* ptr ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "src")) src = ptr->parm; - } - if (src && !strcmp(src, "xroot:")) { - unsigned int width, height; - Pixmap rp = GetRootPixmap(None); - if( state->verbose > 1 ) - show_progress("Getting root pixmap."); - if (rp) { - get_dpy_drawable_size( state->asv->dpy, rp, &width, &height); - result = pixmap2asimage(state->asv, rp, 0, 0, width, height, 0xFFFFFFFF, False, 100); - if( dst_width == 0 ) dst_width = width ; - if( dst_height == 0 ) dst_height = height ; - if( dst_width != (int)width || dst_height != (int)height ) - { - ASImage *tmp = scale_asimage( NULL, result, dst_width, dst_height, ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT ); - if( tmp ) - { - safe_asimage_destroy( result ); - result = tmp ; - } - } - } - } else if (src) { - if( state->verbose > 1 ) - show_progress("Loading image [%s] using imman (%p) with search path \"%s\" (dst_size = %dx%d).", src, state->imman, state->imman?state->imman->search_path[0]:"", dst_width, dst_height); - if( dst_width != 0 || dst_height != 0 ) - result = get_thumbnail_asimage( state->imman, src, dst_width, dst_height, (dst_width==0||dst_height==0)?AS_THUMBNAIL_PROPORTIONAL:0 ); - else - result = get_asimage( state->imman, src, 0xFFFFFFFF, 100 ); - } - return result; -} - -/****** libAfterImage/asimagexml/recall - * NAME - * recall - recall previously generated and named image by its id. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * srcid Required. An image ID defined with the "id" parameter for - * any previously created image. - ******/ -static ASImage * -handle_asxml_tag_recall( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - ASImage *result = NULL ; - xml_elem_t* ptr = parm ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - while ( ptr && !result ) - { - if (!strcmp(ptr->tag, "srcid")) - { - if( state->verbose > 1 ) - show_progress("Recalling image id [%s] from imman %p.", ptr->parm, state->imman); - result = fetch_asimage(state->imman, ptr->parm ); - if (!result) - show_warning("Image recall failed for id [%s].", ptr->parm); - } - ptr = ptr->next ; - } - if( result == NULL ) - { - for( ptr = parm ; ptr && !result ; ptr = ptr->next ) - if (!strcmp(ptr->tag, "default_src")) - { - if( state->verbose > 1 ) - show_progress("loading default image [%s] from imman %p.", ptr->parm, state->imman); - result = get_asimage( state->imman, ptr->parm, 0xFFFFFFFF, 100 ); - } - } - return result; -} - -/****** libAfterImage/asimagexml/release - * NAME - * release - release (destroy if possible) previously generated and named image by its id. - * SYNOPSIS - * - * ATTRIBUTES - * srcid Required. An image ID defined with the "id" parameter for - * any previously created image. - ******/ -static ASImage * -handle_asxml_tag_release( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - xml_elem_t* ptr ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) - if (!strcmp(ptr->tag, "srcid")) - { - if( state->verbose > 1 ) - show_progress("Releasing image id [%s] from imman %p.", ptr->parm, state->imman); - release_asimage_by_name(state->imman, (char*)ptr->parm ); - break; - } - return NULL; -} - -/****** libAfterImage/asimagexml/color - * NAME - * color - defines symbolic name for a color and set of variables. - * SYNOPSIS - * - * ATTRIBUTES - * name Symbolic name for the color value, to be used to refer to that color. - * argb 8 characters hex definition of the color or other symbolic color name. - * domain string to be used to prepend names of defined variables. - * NOTES - * In addition to defining symbolic name for the color this tag will define - * 7 other variables : domain.sym_name.red, domain.sym_name.green, - * domain.sym_name.blue, domain.sym_name.alpha, - * domain.sym_name.hue, domain.sym_name.saturation, - * domain.sym_name.value - ******/ -static ASImage * -handle_asxml_tag_color( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - xml_elem_t* ptr ; - char* name = NULL; - const char* argb_text = NULL; - const char* var_domain = NULL; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "name")) name = ptr->parm; - else if (!strcmp(ptr->tag, "argb")) argb_text = ptr->parm; - else if (!strcmp(ptr->tag, "domain")) var_domain = ptr->parm; - } - if (name && argb_text) - { - ARGB32 argb = ARGB32_Black; - if( parse_argb_color( argb_text, &argb ) != argb_text ) - { - char *tmp; - CARD32 hue16, sat16, val16 ; - int vd_len = var_domain?strlen(var_domain):0 ; - - tmp = safemalloc( vd_len + 1+ strlen(name )+32+1 ) ; - - if( var_domain && var_domain[0] != '\0' ) - { - if( var_domain[vd_len-1] != '.' ) - { - sprintf( tmp, "%s.", var_domain ); - ++vd_len ; - }else - strcpy( tmp, var_domain ); - } - - -#ifdef HAVE_AFTERBASE - if( state->verbose > 1 ) - show_progress("defining synonim [%s] for color value #%8.8X.", name, argb); - register_custom_color( name, argb ); -#endif - sprintf( tmp+vd_len, "%s.alpha", name ); - asxml_var_insert( tmp, ARGB32_ALPHA8(argb) ); - sprintf( tmp+vd_len, "%s.red", name ); - asxml_var_insert( tmp, ARGB32_RED8(argb) ); - sprintf( tmp+vd_len, "%s.green", name ); - asxml_var_insert( tmp, ARGB32_GREEN8(argb) ); - sprintf( tmp+vd_len, "%s.blue", name ); - asxml_var_insert( tmp, ARGB32_BLUE8(argb) ); - - hue16 = rgb2hsv( ARGB32_RED16(argb), ARGB32_GREEN16(argb), ARGB32_BLUE16(argb), &sat16, &val16 ); - - sprintf( tmp+vd_len, "%s.hue", name ); - asxml_var_insert( tmp, hue162degrees( hue16 ) ); - sprintf( tmp+vd_len, "%s.saturation", name ); - asxml_var_insert( tmp, val162percent( sat16 ) ); - sprintf( tmp+vd_len, "%s.value", name ); - asxml_var_insert( tmp, val162percent( val16 ) ); - free( tmp ); - } - } - return NULL; -} -/****** libAfterImage/asimagexml/printf - * NAME - * printf - prints variable value to standard output. - * SYNOPSIS - * - * ATTRIBUTES - * format_string Standard C format string with exactly 1 placeholder. - * var Name of the variable, which value will be printed. - * val math expression to be printed. - * NOTES - ******/ -static ASImage * -handle_asxml_tag_printf( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - xml_elem_t* ptr ; - const char* format = NULL; - const char* var = NULL; - int val = 0 ; - Bool use_val = False ; - int arg_count = 0, i; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "format")) format = ptr->parm; - else if (!strcmp(ptr->tag, "var")) { var = ptr->parm; use_val = False; } - else if (!strcmp(ptr->tag, "val")) { val = (int)parse_math(ptr->parm, NULL, 0); use_val = True; } - } - - if( format != NULL ) - { - char *interpreted_format = interpret_ctrl_codes( mystrdup(format) ); - - for( i = 0 ; format[i] != '\0' ; ++i ) - if( format[i] == '%' ) - { - if( format[i+1] != '%' ) - ++arg_count ; - else - ++i ; - } - - if( use_val && arg_count == 1) - printf( interpreted_format, val ); - else if( var != NULL && arg_count == 1 ) - printf( interpreted_format, asxml_var_get(var) ); - else if( arg_count == 0 ) - fputs( interpreted_format, stdout ); - free( interpreted_format ); - } - - return NULL; -} -/****** libAfterImage/asimagexml/set - * NAME - * set - declares variable, assigning it a numeric value of expression. - * SYNOPSIS - * - * ATTRIBUTES - * var Name of the variable, which value will be set. - * val math expression to be evaluated. - * domain (optional) variable's domain to be prepended to its name - * using format var_domain.variable_name - ******/ -static ASImage * -handle_asxml_tag_set( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - xml_elem_t* ptr ; - const char* var_domain = NULL ; - const char* var = NULL; - int val = 0 ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "var")) var = ptr->parm; - else if (!strcmp(ptr->tag, "domain")) var_domain = ptr->parm; - else if (!strcmp(ptr->tag, "val")) val = (int)parse_math(ptr->parm, NULL, 0); - } - - if( var != NULL ) - { - char *tmp = (char*)var ; - if( var_domain && var_domain[0] != '\0' ) - { - int vd_len = strlen(var_domain); - tmp = safemalloc( vd_len + 1 + strlen(var) + 1 ); - sprintf( tmp, ( var_domain[vd_len-1] != '.' )?"%s.%s":"%s%s", var_domain, var ); - } - asxml_var_insert( tmp, val ); - if( tmp != var ) - free( tmp ); - } - - return NULL; -} -/****** libAfterImage/asimagexml/if - * NAME - * if - evaluates logical expression and if result evaluates to not true(or false - * if tag is used ), handles tags within. - * SYNOPSIS - * - * [......] - * - * - * ATTRIBUTES - * val1 math expression to be evaluated. - * val2 math expression to be evaluated. - * op (optional) comparison op to be applied to values - * EXAMPLE - * ...... - ******/ -static ASImage * -handle_asxml_tag_if( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm) -{ - xml_elem_t* ptr ; - int val1 = 0, val2 = 0 ; - const char *op = NULL ; - int res = 0 ; - ASImage *im = NULL, *imtmp = NULL ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p", doc, parm ); - - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "op")) op = ptr->parm; - else if (!strcmp(ptr->tag, "val1")) val1 = (int)parse_math(ptr->parm, NULL, 0); - else if (!strcmp(ptr->tag, "val2")) val2 = (int)parse_math(ptr->parm, NULL, 0); - } - - if( op != NULL ) - { - if ( strcmp(op, "gt") == 0 ) res = (val1 > val2); - else if( strcmp(op, "lt") == 0 ) res = (val1 < val2); - else if( strcmp(op, "ge") == 0 ) res = (val1 >= val2); - else if( strcmp(op, "le") == 0 ) res = (val1 <= val2); - else if( strcmp(op, "eq") == 0 ) res = (val1 == val2); - else if( strcmp(op, "ne") == 0 ) res = (val1 != val2); - } - - if( doc->tag[0] == 'u' ) /* */ - res = !res ; - - ptr = NULL ; - for (ptr = doc->child ; ptr ; ptr = ptr->next) - { - if( strcmp(ptr->tag, res?"then":"else" ) ) - { - ptr = ptr->child ; - break; - } - if( res && ptr->next == NULL ) - ptr = doc->child ; - } - - while( ptr ) - { - imtmp = build_image_from_xml(state->asv, state->imman, state->fontman, ptr, NULL, state->flags, state->verbose, state->display_win); - if( im && imtmp ) safe_asimage_destroy( im ); - if( imtmp ) im = imtmp ; - ptr = ptr->next ; - } - return im ; -} - -/****** libAfterImage/asimagexml/gradient - * NAME - * gradient - render multipoint gradient. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * colors Required. Whitespace-separated list of colors. At least two - * colors are required. Each color in this list will be visited - * in turn, at the intervals given by the offsets attribute. - * offsets Optional. Whitespace-separated list of floating point values - * ranging from 0.0 to 1.0. The colors from the colors attribute - * are given these offsets, and the final gradient is rendered - * from the combination of the two. If both colors and offsets - * are given but the number of colors and offsets do not match, - * the minimum of the two will be used, and the other will be - * truncated to match. If offsets are not given, a smooth - * stepping from 0.0 to 1.0 will be used. - * angle Optional. Given in degrees. Default is 0. This is the - * direction of the gradient. Currently the only supported - * values are 0, 45, 90, 135, 180, 225, 270, 315. 0 means left - * to right, 90 means top to bottom, etc. - *****/ -static ASImage * -handle_asxml_tag_gradient( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - double angle = 0; - char* color_str = NULL; - char* offset_str = NULL; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, width = %d, height = %d", doc, parm, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "angle")) angle = strtod(ptr->parm, NULL); - else if (!strcmp(ptr->tag, "colors")) color_str = ptr->parm; - else if (!strcmp(ptr->tag, "offsets")) offset_str = ptr->parm; - } - if ( color_str) - { - ASGradient gradient; - int reverse = 0, npoints1 = 0, npoints2 = 0; - char* p; - angle = fmod(angle, 2 * PI); - if (angle > 2 * PI * 15 / 16 || angle < 2 * PI * 1 / 16) { - gradient.type = GRADIENT_Left2Right; - } else if (angle < 2 * PI * 3 / 16) { - gradient.type = GRADIENT_TopLeft2BottomRight; - } else if (angle < 2 * PI * 5 / 16) { - gradient.type = GRADIENT_Top2Bottom; - } else if (angle < 2 * PI * 7 / 16) { - gradient.type = GRADIENT_BottomLeft2TopRight; reverse = 1; - } else if (angle < 2 * PI * 9 / 16) { - gradient.type = GRADIENT_Left2Right; reverse = 1; - } else if (angle < 2 * PI * 11 / 16) { - gradient.type = GRADIENT_TopLeft2BottomRight; reverse = 1; - } else if (angle < 2 * PI * 13 / 16) { - gradient.type = GRADIENT_Top2Bottom; reverse = 1; - } else { - gradient.type = GRADIENT_BottomLeft2TopRight; - } - for (p = color_str ; isspace((int)*p) ; p++); - for (npoints1 = 0 ; *p ; npoints1++) { - if (*p) for ( ; *p && !isspace((int)*p) ; p++); - for ( ; isspace((int)*p) ; p++); - } - if (offset_str) { - for (p = offset_str ; isspace((int)*p) ; p++); - for (npoints2 = 0 ; *p ; npoints2++) { - if (*p) for ( ; *p && !isspace((int)*p) ; p++); - for ( ; isspace((int)*p) ; p++); - } - } - gradient.npoints = max( npoints1, npoints2 ); - if (npoints1 > 1) { - int i; - gradient.color = safecalloc(gradient.npoints, sizeof(ARGB32)); - gradient.offset = NEW_ARRAY(double, gradient.npoints); - for (p = color_str ; isspace((int)*p) ; p++); - for (npoints1 = 0 ; *p ; ) { - char* pb = p, ch; - if (*p) for ( ; *p && !isspace((int)*p) ; p++); - for ( ; isspace((int)*p) ; p++); - ch = *p; *p = '\0'; - if (parse_argb_color(pb, gradient.color + npoints1) != pb) - { - npoints1++; - }else - show_warning( "failed to parse color [%s] - defaulting to black", pb ); - *p = ch; - } - if (offset_str) { - for (p = offset_str ; isspace((int)*p) ; p++); - for (npoints2 = 0 ; *p ; ) { - char* pb = p, ch; - if (*p) for ( ; *p && !isspace((int)*p) ; p++); - ch = *p; *p = '\0'; - gradient.offset[npoints2] = strtod(pb, &pb); - if (pb == p) npoints2++; - *p = ch; - for ( ; isspace((int)*p) ; p++); - } - } else { - for (npoints2 = 0 ; npoints2 < gradient.npoints ; npoints2++) - gradient.offset[npoints2] = (double)npoints2 / (gradient.npoints - 1); - } - if (reverse) { - for (i = 0 ; i < gradient.npoints / 2 ; i++) { - int i2 = gradient.npoints - 1 - i; - ARGB32 c = gradient.color[i]; - double o = gradient.offset[i]; - gradient.color[i] = gradient.color[i2]; - gradient.color[i2] = c; - gradient.offset[i] = gradient.offset[i2]; - gradient.offset[i2] = o; - } - for (i = 0 ; i < gradient.npoints ; i++) { - gradient.offset[i] = 1.0 - gradient.offset[i]; - } - } - if (state->verbose > 1) { - show_progress("Generating [%dx%d] gradient with angle [%f] and npoints [%d/%d].", width, height, angle, npoints1, npoints2); - for (i = 0 ; i < gradient.npoints ; i++) { - show_progress(" Point [%d] has color [#%08x] and offset [%f].", i, (unsigned int)gradient.color[i], gradient.offset[i]); - } - } - result = make_gradient(state->asv, &gradient, width, height, SCL_DO_ALL, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - if( gradient.color ) - free( gradient.color ); - if( gradient.offset ) - free( gradient.offset ); - } - } - return result; -} - -/****** libAfterImage/asimagexml/solid - * NAME - * solid - generate image of specified size and fill it with solid color. - * SYNOPSIS - * - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * color Optional. Default is "#ffffffff". An image will be created - * and filled with this color. - * width Required. The image will have this width. - * height Required. The image will have this height. - * opacity Optional. Default is 100. Values from 0 to 100 represent the - * opacity of resulting image with 100 being completely opaque. - * Effectively overrides alpha component of the color setting. - ******/ -static ASImage * -handle_asxml_tag_solid( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - Bool opacity_set = False ; - int opacity = 100 ; - ARGB32 color = ARGB32_White; - CARD32 a, r, g, b ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, width = %d, height = %d", doc, parm, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "color")) parse_argb_color(ptr->parm, &color); - else if (!strcmp(ptr->tag, "opacity")) { opacity = atol(ptr->parm); opacity_set = True ; } - } - if( state->verbose > 1 ) - show_progress("Creating solid color [#%08x] image [%dx%d].", (unsigned int)color, width, height); - result = create_asimage(width, height, ASIMAGE_QUALITY_TOP); - if( opacity < 0 ) opacity = 0 ; - else if( opacity > 100 ) opacity = 100 ; - a = opacity_set? (0x000000FF * (CARD32)opacity)/100: ARGB32_ALPHA8(color); - r = ARGB32_RED8(color); - g = ARGB32_GREEN8(color); - b = ARGB32_BLUE8(color); - color = MAKE_ARGB32(a,r,g,b); - if (result) - fill_asimage(state->asv, result, 0, 0, width, height, color); - - return result; -} - - - -/****** libAfterImage/asimagexml/save - * NAME - * save - write generated/loaded image into the file of one of the - * supported types - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * dst Optional. Name of file image will be saved to. If omitted - * image will be dumped into stdout - usefull for CGI apps. - * format Optional. Ouput format of saved image. Defaults to the - * extension of the "dst" parameter. Valid values are the - * standard AS image file formats: xpm, jpg, png, gif, tiff. - * compress Optional. Compression level if supported by output file - * format. Valid values are in range of 0 - 100 and any of - * "deflate", "jpeg", "ojpeg", "packbits" for TIFF files. - * Note that JPEG and GIF will produce images with deteriorated - * quality when compress is greater then 0. For JPEG default is - * 25, for PNG default is 6 and for GIF it is 0. - * opacity Optional. Level below which pixel is considered to be - * transparent, while saving image as XPM or GIF. Valid values - * are in range 0-255. Default is 127. - * replace Optional. Causes ascompose to delete file if the file with the - * same name already exists. Valid values are 0 and 1. Default - * is 1 - files are deleted before being saved. Disable this to - * get multimage animated gifs. - * delay Optional. Delay to be stored in GIF image. This could be used - * to create animated gifs. Note that you have to set replace="0" - * and then write several images into the GIF file with the same - * name. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - *******/ -static ASImage * -handle_asxml_tag_save( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - const char* dst = NULL; - const char* ext = NULL; - const char* compress = NULL ; - const char* opacity = NULL ; - int delay = 0 ; - int replace = 1; - /* */ - int autoext = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p", doc, parm, imtmp ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "dst")) dst = ptr->parm; - else if (!strcmp(ptr->tag, "format")) ext = ptr->parm; - else if (!strncmp(ptr->tag, "compress", 8)) compress = ptr->parm; - else if (!strcmp(ptr->tag, "opacity")) opacity = ptr->parm; - else if (!strcmp(ptr->tag, "delay")) delay = atoi(ptr->parm); - else if (!strcmp(ptr->tag, "replace")) replace = atoi(ptr->parm); - } - if (dst && !ext) { - ext = strrchr(dst, '.'); - if (ext) ext++; - autoext = 1; - } - - result = imtmp; - - if ( autoext && ext ) - show_warning("No format given. File extension [%s] used as format.", ext); - if( state->verbose > 1 ) - show_progress("reSaving image to file [%s].", dst?dst:"stdout"); - if (result && get_flags( state->flags, ASIM_XML_ENABLE_SAVE) ) - { - if( state->verbose > 1 ) - show_progress("Saving image to file [%s].", dst?dst:"stdout"); - if( !save_asimage_to_file(dst, result, ext, compress, opacity, delay, replace)) - show_error("Unable to save image into file [%s].", dst?dst:"stdout"); - } - - return result; -} - -/****** libAfterImage/asimagexml/background - * NAME - * background - set image's background color. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * color Required. Color to be used for background - fills all the - * spaces in image with missing pixels. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_background( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - ARGB32 argb = ARGB32_Black; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p", doc, parm, imtmp ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "color")) parse_argb_color( ptr->parm, &argb ); - } - if (imtmp) { - result = clone_asimage( imtmp, SCL_DO_ALL ); - result->back_color = argb ; - } - if( state->verbose > 1 ) - show_progress( "Setting back_color for image %p to 0x%8.8X", result, argb ); - return result; -} - -/****** libAfterImage/asimagexml/blur - * NAME - * blur - perform a gaussian blurr on an image. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * horz Optional. Horizontal radius of the blur in pixels. - * vert Optional. Vertical radius of the blur in pixels. - * channels Optional. Applys blur only on listed color channels: - * a - alpha, - * r - red, - * g - green, - * b - blue - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_blur( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - int horz = 0, vert = 0; - int filter = SCL_DO_ALL; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p", doc, parm, imtmp ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "horz")) horz = atoi(ptr->parm); - else if (!strcmp(ptr->tag, "vert")) vert = atoi(ptr->parm); - else if (!strcmp(ptr->tag, "channels")) - { - int i = 0 ; - char *str = &(ptr->parm[0]) ; - filter = 0 ; - while( str[i] != '\0' ) - { - if( str[i] == 'a' ) - filter |= SCL_DO_ALPHA ; - else if( str[i] == 'r' ) - filter |= SCL_DO_RED ; - else if( str[i] == 'g' ) - filter |= SCL_DO_GREEN ; - else if( str[i] == 'b' ) - filter |= SCL_DO_BLUE ; - ++i ; - } - } - } - result = blur_asimage_gauss(state->asv, imtmp, horz, vert, filter, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - if( state->verbose > 1 ) - show_progress("Blurrer image with radii %d, %d.", horz, vert); - return result; -} - - - -/****** libAfterImage/asimagexml/bevel - * NAME - * bevel - draws solid bevel frame around the image. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * colors Optional. Whitespace-separated list of colors. Exactly two - * colors are required. Default is "#ffdddddd #ff555555". The - * first color is the color of the upper and left edges, and the - * second is the color of the lower and right edges. - * borders Optional. Whitespace-separated list of integer values. - * Default is "10 10 10 10". The values represent the offsets - * toward the center of the image of each border: left, top, - * right, bottom. - * solid Optional - default is 1. If set to 0 will draw bevel gradually - * fading into the image. - * outline Optional - default is 0. If set to 1 will draw bevel around the - * image vs. inside the image. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_bevel( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - char* color_str = NULL; - char* border_str = NULL; - int solid = 1, outline = 0 ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "colors")) color_str = ptr->parm; - else if (!strcmp(ptr->tag, "border")) border_str = ptr->parm; - else if (!strcmp(ptr->tag, "solid")) solid = atoi(ptr->parm); - else if (!strcmp(ptr->tag, "outline")) outline = atoi(ptr->parm); - } - if (imtmp) - { - ASImageBevel bevel; - ASImageLayer layer; - memset( &bevel, 0x00, sizeof(ASImageBevel) ); - if( solid ) - bevel.type = BEVEL_SOLID_INLINE; - bevel.hi_color = 0xffdddddd; - bevel.lo_color = 0xff555555; - if( outline ) - bevel.top_outline = bevel.left_outline = bevel.right_outline = bevel.bottom_outline = 10; - else - bevel.top_inline = bevel.left_inline = bevel.right_inline = bevel.bottom_inline = 10; - if (color_str) { - char* p = color_str; - while (isspace((int)*p)) p++; - p = (char*)parse_argb_color(p, &bevel.hi_color); - while (isspace((int)*p)) p++; - parse_argb_color(p, &bevel.lo_color); - } - if (border_str) { - char* p = (char*)border_str; - if( outline ) - { - bevel.left_outline = (unsigned short)parse_math(p, &p, width); - bevel.top_outline = (unsigned short)parse_math(p, &p, height); - bevel.right_outline = (unsigned short)parse_math(p, &p, width); - bevel.bottom_outline = (unsigned short)parse_math(p, &p, height); - }else - { - bevel.left_inline = (unsigned short)parse_math(p, &p, width); - bevel.top_inline = (unsigned short)parse_math(p, &p, height); - bevel.right_inline = (unsigned short)parse_math(p, &p, width); - bevel.bottom_inline = (unsigned short)parse_math(p, &p, height); - } - } - bevel.hihi_color = bevel.hi_color; - bevel.hilo_color = bevel.hi_color; - bevel.lolo_color = bevel.lo_color; - if( state->verbose > 1 ) - show_progress("Generating bevel with offsets [%d %d %d %d] and colors [#%08x #%08x].", bevel.left_inline, bevel.top_inline, bevel.right_inline, bevel.bottom_inline, (unsigned int)bevel.hi_color, (unsigned int)bevel.lo_color); - init_image_layers( &layer, 1 ); - layer.im = imtmp; - if( width <= bevel.left_outline+bevel.right_outline ) - layer.clip_width = 1; - else - layer.clip_width = width-(bevel.left_outline+bevel.right_outline); - if( height <= bevel.top_outline+bevel.bottom_outline ) - layer.clip_height = 1; - else - layer.clip_height = height-(bevel.top_outline+bevel.bottom_outline); - layer.bevel = &bevel; - result = merge_layers(state->asv, &layer, 1, - width, height, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - } - return result; -} - -/****** libAfterImage/asimagexml/mirror - * NAME - * mirror - create new image as mirror copy of an old one. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * dir Required. Possible values are "vertical" and "horizontal". - * The image will be flipped over the x-axis if dir is vertical, - * and flipped over the y-axis if dir is horizontal. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_mirror( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - int dir = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "dir")) dir = !mystrcasecmp(ptr->parm, "vertical"); - } - result = mirror_asimage(state->asv, imtmp, 0, 0, width, height, dir, - ASA_ASImage, - 0, ASIMAGE_QUALITY_DEFAULT); - if( state->verbose > 1 ) - show_progress("Mirroring image [%sally].", dir ? "horizont" : "vertic"); - return result; -} - -/****** libAfterImage/asimagexml/rotate - * NAME - * rotate - rotate an image in 90 degree increments (flip). - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * angle Required. Given in degrees. Possible values are currently - * "90", "180", and "270". Rotates the image through the given - * angle. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_rotate( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr ; - double angle = 0; - int dir = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - if (!strcmp(ptr->tag, "angle")) angle = strtod(ptr->parm, NULL); - - angle = fmod(angle, 2 * PI); - if (angle > 2 * PI * 7 / 8 || angle < 2 * PI * 1 / 8) - dir = 0; - else if (angle < 2 * PI * 3 / 8) - dir = FLIP_VERTICAL; - else if (angle < 2 * PI * 5 / 8) - dir = FLIP_UPSIDEDOWN; - else - dir = FLIP_VERTICAL | FLIP_UPSIDEDOWN; - if (dir) - { - if( get_flags(dir, FLIP_VERTICAL)) - { - int tmp = width ; - width = height ; - height = tmp ; - } - result = flip_asimage(state->asv, imtmp, 0, 0, width, height, dir, ASA_ASImage, 0, ASIMAGE_QUALITY_DEFAULT); - if( state->verbose > 1 ) - show_progress("Rotating image [%f degrees].", angle); - } else - result = imtmp; - - return result; -} - -/****** libAfterImage/asimagexml/scale - * NAME - * scale - scale image to arbitrary size - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Required. The image will be scaled to this width. - * height Required. The image will be scaled to this height. - * src_x Optional. Default is 0. X Offset on infinite surface tiled - * with this image, from which to cut portion of an image to be - * used in scaling. - * src_y Optional. Default is 0. Y Offset on infinite surface tiled - * with this image, from which to cut portion of an image to be - * used in scaling. - * src_width - * Optional. Default is image width. Tile image to this width - * prior to scaling. - * src_height - * Optional. Default is image height. Tile image to this height - * prior to scaling. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - * If you want to keep image proportions while scaling - use "proportional" - * instead of specific size for particular dimention. - ******/ -static ASImage * -handle_asxml_tag_scale( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int src_x = 0, src_y = 0 ; - int src_width = 0, src_height = 0 ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "src_x")) src_x = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "src_y")) src_y = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "src_width")) src_width = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "src_height")) src_height = (int)parse_math(ptr->parm, NULL, width); - } - if( state->verbose > 1 ) - show_progress("Scaling image to [%dx%d].", width, height); - result = scale_asimage2( state->asv, imtmp, - src_x, src_y, src_width, src_height, - width, height, - ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT); - return result; -} -/****** libAfterImage/asimagexml/slice - * NAME - * slice - slice image to arbitrary size leaving corners unchanged - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Required. The image will be scaled to this width. - * height Required. The image will be scaled to this height. - * x_start Optional. Position at which vertical image slicing begins. - * Corresponds to the right side of the left corners. - * x_end Optional. Position at which vertical image slicing end. - * Corresponds to the left side of the right corners. - * y_start Optional. Position at which horisontal image slicing begins. - * Corresponds to the bottom side of the top corners. - * y_end Optional. Position at which horisontal image slicing end. - * Corresponds to the top side of the bottom corners. - * scale Optional. If set to 1 will cause middle portion of the - * image to be scaled instead of tiled. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - * Contents of the image between x_start and x_end will be tiled - * horizontally. Contents of the image between y_start and y_end will be - * tiled vertically. This is usefull to get background images to fit the - * size of the text or a widget, while preserving its borders undistorted, - * which is the usuall result of simple scaling. - * If you want to keep image proportions while resizing-use "proportional" - * instead of specific size for particular dimention. - ******/ -static ASImage * -handle_asxml_tag_slice( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int x_start = 0, x_end = 0 ; - int y_start = 0, y_end = 0 ; - Bool scale = False ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "x_start")) x_start = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "x_end")) x_end = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "y_start")) y_start = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "y_end")) y_end = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "scale")) scale = (ptr->parm[0] == '1'); - } - - if( state->verbose > 1 ) - show_progress("Slicing image to [%dx%d].", width, height); - result = slice_asimage2( state->asv, imtmp, x_start, x_end, y_start, y_end, width, height, - scale, ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT); - return result; -} - -/****** libAfterImage/asimagexml/pixelize - * NAME - * pixelize - pixelize image using arbitrary pixel size - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Required. The image will be scaled to this width. - * height Required. The image will be scaled to this height. - * clip_x Optional. Offset into original image. - * clip_y Optional. Offset into original image. - * pixel_width Required. Horizontal pixelization step; - * pixel_height Required. Vertical pixelization step; - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - * If you want to keep image proportions while resizing-use "proportional" - * instead of specific size for particular dimention. - ******/ -static ASImage * -handle_asxml_tag_pixelize( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int clip_x = 0, clip_y = 0 ; - int pixel_width = 1, pixel_height = 1 ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "clip_x")) clip_x = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "clip_y")) clip_y = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "pixel_width")) pixel_width = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "pixel_height")) pixel_height = (int)parse_math(ptr->parm, NULL, height); - } - - if( state->verbose > 1 ) - show_progress("Pixelizing image to [%dx%d] using pixel size %dx%d.", - width, height, pixel_width, pixel_height); - result = pixelize_asimage (state->asv, imtmp, clip_x, clip_y, width, height, - pixel_width, pixel_height, - ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT); - return result; -} - -/****** libAfterImage/asimagexml/color2alpha - * NAME - * color2alpha - set alpha channel based on color closeness to specified color - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Required. The image will be scaled to this width. - * height Required. The image will be scaled to this height. - * clip_x Optional. Offset into original image. - * clip_y Optional. Offset into original image. - * color Required. Color to match against. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - * If you want to keep image proportions while resizing-use "proportional" - * instead of specific size for particular dimention. - ******/ -static ASImage * -handle_asxml_tag_color2alpha( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int clip_x = 0, clip_y = 0 ; - ARGB32 color; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "clip_x")) clip_x = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "clip_y")) clip_y = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "color")) parse_argb_color(ptr->parm, &color); - } - - if( state->verbose > 1 ) - show_progress("color2alpha image to [%dx%d] using color #%8.8X.", width, height, color); - result = color2alpha_asimage (state->asv, imtmp, clip_x, clip_y, width, height, - color, - ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT); - return result; -} - -/****** libAfterImage/asimagexml/crop - * NAME - * crop - crop image to arbitrary area within it. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * srcx Optional. Default is "0". Skip this many pixels from the left. - * srcy Optional. Default is "0". Skip this many pixels from the top. - * width Optional. Default is "100%". Keep this many pixels wide. - * height Optional. Default is "100%". Keep this many pixels tall. - * tint Optional. Additionally tint an image to specified color. - * Tinting can both lighten and darken an image. Tinting color - * 0 or #7f7f7f7f yeilds no tinting. Tinting can be performed on - * any channel, including alpha channel. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_crop( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - ARGB32 tint = 0 ; - int srcx = 0, srcy = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "srcx")) srcx = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "srcy")) srcy = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "tint")) parse_argb_color(ptr->parm, &tint); - } - if( state->verbose > 1 ) - show_progress("Cropping image to [%dx%d].", width, height); - result = tile_asimage(state->asv, imtmp, srcx, srcy, width, height, tint, ASA_ASImage, 100, ASIMAGE_QUALITY_TOP); - return result; -} - -/****** libAfterImage/asimagexml/tile - * NAME - * tile - tile an image to specified area. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Optional. Default is "100%". The image will be tiled to this - * width. - * height Optional. Default is "100%". The image will be tiled to this - * height. - * x_origin Optional. Horizontal position on infinite surface, covered - * with tiles of the image, from which to cut out resulting - * image. - * y_origin Optional. Vertical position on infinite surface, covered - * with tiles of the image, from which to cut out resulting - * image. - * tint Optional. Additionally tint an image to specified color. - * Tinting can both lighten and darken an image. Tinting color - * 0 or #7f7f7f7f yields no tinting. Tinting can be performed - * on any channel, including alpha channel. - * complement Optional. Will use color that is the complement to tint color - * for the tinting, if set to 1. Default is 0. - * - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_tile( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int xorig = 0, yorig = 0; - ARGB32 tint = 0 ; - char *complement_str = NULL ; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "x_origin")) xorig = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "y_origin")) yorig = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "tint")) parse_argb_color(ptr->parm, &tint); - else if (!strcmp(ptr->tag, "complement")) complement_str = ptr->parm; - } - if( complement_str ) - { - register char *ptr = complement_str ; - CARD32 a = ARGB32_ALPHA8(tint), - r = ARGB32_RED8(tint), - g = ARGB32_GREEN8(tint), - b = ARGB32_BLUE8(tint) ; - while( *ptr ) - { - if( *ptr == 'a' ) a = ~a ; - else if( *ptr == 'r' ) r = ~r ; - else if( *ptr == 'g' ) g = ~g ; - else if( *ptr == 'b' ) b = ~b ; - ++ptr ; - } - - tint = MAKE_ARGB32(a, r, g, b ); - } - if( state->verbose > 1 ) - show_progress("Tiling image to [%dx%d].", width, height); - result = tile_asimage(state->asv, imtmp, xorig, yorig, width, height, tint, ASA_ASImage, 100, ASIMAGE_QUALITY_TOP); - return result; -} - -/****** libAfterImage/asimagexml/hsv - * NAME - * hsv - adjust Hue, Saturation and/or Value of an image and optionally - * tile an image to arbitrary area. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * width Optional. Default is "100%". The image will be tiled to this - * width. - * height Optional. Default is "100%". The image will be tiled to this - * height. - * x_origin Optional. Horizontal position on infinite surface, covered - * with tiles of the image, from which to cut out resulting - * image. - * y_origin Optional. Vertical position on infinite surface, covered - * with tiles of the image, from which to cut out resulting - * image. - * affected_hue Optional. Limits effects to the renage of hues around - * this hue. If numeric value is specified - it is treated as - * degrees on 360 degree circle, with : - * red = 0, - * yellow = 60, - * green = 120, - * cyan = 180, - * blue = 240, - * magenta = 300. - * If colorname or value preceded with # is specified here - it - * will be treated as RGB color and converted into hue - * automagically. - * affected_radius - * Optional. Value in degrees to be used in order to - * calculate the range of affected hues. Range is determined by - * substracting and adding this value from/to affected_hue. - * hue_offset - * Optional. Value by which to adjust the hue. - * saturation_offset - * Optional. Value by which to adjust the saturation. - * value_offset - * Optional. Value by which to adjust the value. - * NOTES - * One of the Offsets must be not 0, in order for operation to be - * performed. - * - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_hsv( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - int affected_hue = 0, affected_radius = 360 ; - int hue_offset = 0, saturation_offset = 0, value_offset = 0 ; - int xorig = 0, yorig = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (!strcmp(ptr->tag, "x_origin")) xorig = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "y_origin")) yorig = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "affected_hue")) - { - if( isdigit( (int)ptr->parm[0] ) ) - affected_hue = (int)parse_math(ptr->parm, NULL, 360); - else - { - ARGB32 color = 0; - if( parse_argb_color( ptr->parm, &color ) != ptr->parm ) - { - affected_hue = rgb2hue( ARGB32_RED16(color), - ARGB32_GREEN16(color), - ARGB32_BLUE16(color)); - affected_hue = hue162degrees( affected_hue ); - } - } - } - else if (!strcmp(ptr->tag, "affected_radius")) affected_radius = (int)parse_math(ptr->parm, NULL, 360); - else if (!strcmp(ptr->tag, "hue_offset")) hue_offset = (int)parse_math(ptr->parm, NULL, 360); - else if (!strcmp(ptr->tag, "saturation_offset"))saturation_offset = (int)parse_math(ptr->parm, NULL, 100); - else if (!strcmp(ptr->tag, "value_offset")) value_offset = (int)parse_math(ptr->parm, NULL, 100); - } - if( hue_offset == -1 && saturation_offset == -1 ) - { - hue_offset = 0 ; - saturation_offset = -99 ; - } - if (hue_offset!=0 || saturation_offset != 0 || value_offset != 0 ) - { - result = adjust_asimage_hsv(state->asv, imtmp, xorig, yorig, width, height, - affected_hue, affected_radius, - hue_offset, saturation_offset, value_offset, - ASA_ASImage, 100, ASIMAGE_QUALITY_TOP); - } - if( state->verbose > 1 ) - show_progress("adjusted HSV of the image by [%d,%d,%d] affected hues are %+d-%+d.result = %p", hue_offset, saturation_offset, value_offset, affected_hue-affected_radius, affected_hue+affected_radius, result); - return result; -} - -/****** libAfterImage/asimagexml/pad - * NAME - * pad - pad an image with solid color rectangles. - * SYNOPSIS - * - * ATTRIBUTES - * id Optional. Image will be given this name for future reference. - * width Optional. The result will have this width. - * height Optional. The result will have this height. - * refid Optional. An image ID defined with the "id" parameter for - * any previously created image. If set, percentages in "width" - * and "height" will be derived from the width and height of the - * refid image. - * left Optional. Size to add to the left of the image. - * top Optional. Size to add to the top of the image. - * right Optional. Size to add to the right of the image. - * bottom Optional. Size to add to the bottom of the image. - * color Optional. Color value to fill added areas with. It could be - * transparent of course. Default is #FF000000 - totally black. - * NOTES - * This tag applies to the first image contained within the tag. Any - * further images will be discarded. - ******/ -static ASImage * -handle_asxml_tag_pad( ASImageXMLState *state, xml_elem_t* doc, xml_elem_t* parm, ASImage *imtmp, int width, int height) -{ - ASImage *result = NULL ; - xml_elem_t* ptr; - ARGB32 color = ARGB32_Black; - int left = 0, top = 0, right = 0, bottom = 0; - LOCAL_DEBUG_OUT("doc = %p, parm = %p, imtmp = %p, width = %d, height = %d", doc, parm, imtmp, width, height ); - for (ptr = parm ; ptr ; ptr = ptr->next) { - if (!strcmp(ptr->tag, "left")) left = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "top")) top = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "right")) right = (int)parse_math(ptr->parm, NULL, width); - else if (!strcmp(ptr->tag, "bottom")) bottom = (int)parse_math(ptr->parm, NULL, height); - else if (!strcmp(ptr->tag, "color")) parse_argb_color(ptr->parm, &color); - } - if( state->verbose > 1 ) - show_progress("Padding image to [%dx%d%+d%+d].", width+left+right, height+top+bottom, left, top); - if (left > 0 || top > 0 || right > 0 || bottom > 0 ) - result = pad_asimage(state->asv, imtmp, left, top, width+left+right, height+top+bottom, - color, ASA_ASImage, 100, ASIMAGE_QUALITY_DEFAULT); - return result; -} - -#define REPLACE_STRING(str,val) do {if(str)free(str);(str) = (val);}while(0) - -/* Each tag is only allowed to return ONE image. */ -ASImage* -build_image_from_xml( ASVisual *asv, ASImageManager *imman, ASFontManager *fontman, xml_elem_t* doc, xml_elem_t** rparm, ASFlagType flags, int verbose, Window display_win) -{ - xml_elem_t* ptr; - char* id = NULL; - ASImage* result = NULL; - ASImageXMLState state ; - - if( IsCDATA(doc) ) return NULL ; - - memset( &state, 0x00, sizeof(state)); - state.flags = flags ; - state.asv = asv ; - state.imman = imman ; - state.fontman = fontman ; - state.verbose = verbose ; - state.display_win = display_win ; - - if( doc ) - { - xml_elem_t* parm = xml_parse_parm(doc->parm, NULL); - xml_elem_t* ptr ; - char* refid = NULL; - char* width_str = NULL; - char* height_str = NULL; - ASImage *refimg = NULL ; - int width = 0, height = 0 ; - LOCAL_DEBUG_OUT("parm = %p", parm); - - for (ptr = parm ; ptr ; ptr = ptr->next) - { - if (ptr->tag[0] == 'i' && ptr->tag[1] == 'd' && ptr->tag[2] == '\0') - REPLACE_STRING(id,mystrdup(ptr->parm)); - else if (strcmp(ptr->tag, "refid") == 0 ) refid = ptr->parm ; - else if (strcmp(ptr->tag, "width") == 0 ) width_str = ptr->parm ; - else if (strcmp(ptr->tag, "height") == 0 ) height_str = ptr->parm ; - } - - if( id ) - if( (result = fetch_asimage( imman, id)) != NULL ) - { - free( id ); - xml_elem_delete(NULL, parm); - return result ; - } - - if( refid ) - refimg = fetch_asimage( imman, refid); - - if (!strcmp(doc->tag, "composite")) - result = handle_asxml_tag_composite( &state, doc, parm ); - else if (!strcmp(doc->tag, "text")) - result = handle_asxml_tag_text( &state, doc, parm ); - else if (!strcmp(doc->tag, "img")) - { - translate_tag_size( width_str, height_str, NULL, refimg, &width, &height ); - result = handle_asxml_tag_img( &state, doc, parm, width, height ); - }else if (!strcmp(doc->tag, "recall")) - result = handle_asxml_tag_recall( &state, doc, parm ); - else if (!strcmp(doc->tag, "release")) - result = handle_asxml_tag_release( &state, doc, parm ); - else if (!strcmp(doc->tag, "color")) - result = handle_asxml_tag_color( &state, doc, parm ); - else if (!strcmp(doc->tag, "printf")) - result = handle_asxml_tag_printf( &state, doc, parm ); - else if (!strcmp(doc->tag, "set")) - result = handle_asxml_tag_set( &state, doc, parm ); - else if (!strcmp(doc->tag, "if") || !strcmp(doc->tag, "unless") ) - result = handle_asxml_tag_if( &state, doc, parm ); - else if ( !strcmp(doc->tag, "gradient") ) - { - translate_tag_size( width_str, height_str, NULL, refimg, &width, &height ); - if( width > 0 && height > 0 ) - result = handle_asxml_tag_gradient( &state, doc, parm, width, height ); - }else if (!strcmp(doc->tag, "solid")) - { - translate_tag_size( width_str, height_str, NULL, refimg, &width, &height ); - if( width > 0 && height > 0 ) - result = handle_asxml_tag_solid( &state, doc, parm, width, height); - }else - { - ASImage *imtmp = NULL ; - - for (ptr = doc->child ; ptr && !imtmp ; ptr = ptr->next) - imtmp = build_image_from_xml(asv, imman, fontman, ptr, NULL, flags, verbose, display_win); - - if( imtmp ) - { - if (imtmp && !strcmp(doc->tag, "save")) - result = handle_asxml_tag_save( &state, doc, parm, imtmp ); - else if (imtmp && !strcmp(doc->tag, "background")) - result = handle_asxml_tag_background( &state, doc, parm, imtmp ); - else if (imtmp && !strcmp(doc->tag, "blur")) - result = handle_asxml_tag_blur( &state, doc, parm, imtmp ); - else - { - translate_tag_size( width_str, height_str, imtmp, refimg, &width, &height ); - - if ( width > 0 && height > 0 ) - { -#define HANDLE_SIZED_TAG(ttag) \ - else if( !strcmp(doc->tag, #ttag) ) result = handle_asxml_tag_##ttag( &state, doc, parm, imtmp, width, height ) - if (0){} - HANDLE_SIZED_TAG(bevel); - HANDLE_SIZED_TAG(mirror); - HANDLE_SIZED_TAG(rotate); - HANDLE_SIZED_TAG(scale); - HANDLE_SIZED_TAG(slice); - HANDLE_SIZED_TAG(crop); - HANDLE_SIZED_TAG(tile); - HANDLE_SIZED_TAG(hsv); - HANDLE_SIZED_TAG(pad); - HANDLE_SIZED_TAG(pixelize); - HANDLE_SIZED_TAG(color2alpha); -#undef HANDLE_SIZED_TAG - } - } - - if( result != imtmp ) - safe_asimage_destroy(imtmp); - } - } - - if( refimg ) - release_asimage( refimg ); - - if (rparm) *rparm = parm; - else xml_elem_delete(NULL, parm); - } - LOCAL_DEBUG_OUT("result = %p, id = \"%s\"", result, id?id:"(null)" ); - - - - /* No match so far... see if one of our children can do any better.*/ - if (!result && doc ) - { - xml_elem_t* tparm = NULL; - for (ptr = doc->child ; ptr && !result ; ptr = ptr->next) - { - xml_elem_t* sparm = NULL; - result = build_image_from_xml(asv, imman, fontman, ptr, &sparm, flags, verbose, display_win); - if (result) - { - if (tparm) xml_elem_delete(NULL, tparm); - tparm = sparm; - }else - if (sparm) xml_elem_delete(NULL, sparm); - - } - if (rparm) - { - if( *rparm ) xml_elem_delete(NULL, *rparm); *rparm = tparm; - }else - xml_elem_delete(NULL, tparm); - } - - LOCAL_DEBUG_OUT("result = %p", result ); - result = commit_xml_image_built( &state, id, result ); - if( id ) - free( id ); - LOCAL_DEBUG_OUT("result = %p", result ); - if( result ) - { - LOCAL_DEBUG_OUT("result's size = %dx%d", result->width, result->height ); - } - return result; -} - - - - diff --git a/graf2d/asimage/src/libAfterImage/asimagexml.h b/graf2d/asimage/src/libAfterImage/asimagexml.h deleted file mode 100644 index 2ec1d71a2f800..0000000000000 --- a/graf2d/asimage/src/libAfterImage/asimagexml.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef ASIMAGEXML_HEADER_FILE_INCLUDED -#define ASIMAGEXML_HEADER_FILE_INCLUDED - -#include "asimage.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* We don't trust the math library to actually provide this number.*/ -#undef PI -#define PI 180 - - -#define ASIM_XML_ENABLE_SAVE (0x01<<0) -#define ASIM_XML_ENABLE_SHOW (0x01<<1) - - -struct ASImageManager ; -struct ASFontManager ; -struct xml_elem_t; - -void set_xml_image_manager( struct ASImageManager *imman ); -void set_xml_font_manager( struct ASFontManager *fontman ); -struct ASImageManager *create_generic_imageman(const char *path); -struct ASFontManager *create_generic_fontman(Display *dpy, const char *path); - - -ASImage * -compose_asimage_xml(ASVisual *asv, - struct ASImageManager *imman, - struct ASFontManager *fontman, - char *doc_str, ASFlagType flags, - int verbose, Window display_win, - const char *path); - - -#define ASXMLVAR_TargetWidth "target.width" -#define ASXMLVAR_TargetHeight "target.height" - - -ASImage * -compose_asimage_xml_at_size(ASVisual *asv, - struct ASImageManager *imman, - struct ASFontManager *fontman, - char *doc_str, - ASFlagType flags, - int verbose, - Window display_win, - const char *path, - int target_width, - int target_height); - -ASImage * -compose_asimage_xml_from_doc(ASVisual *asv, - struct ASImageManager *imman, - struct ASFontManager *fontman, - struct xml_elem_t* doc, - ASFlagType flags, - int verbose, - Window display_win, - const char *path, - int target_width, int target_height); - -void show_asimage(ASVisual *asv, ASImage* im, Window w, long delay); -ASImage* build_image_from_xml( ASVisual *asv, - struct ASImageManager *imman, - struct ASFontManager *fontman, - struct xml_elem_t* doc, struct xml_elem_t** rparm, - ASFlagType flags, int verbose, Window display_win); -Bool save_asimage_to_file(const char* file2bsaved, ASImage *im, - const char* strtype, - const char *compress, - const char *opacity, - int delay, int replace); - - -#ifdef __cplusplus -} -#endif - -#endif /*#ifndef ASIMAGEXML_HEADER_FILE_INCLUDED*/ - - diff --git a/graf2d/asimage/src/libAfterImage/asvisual.h b/graf2d/asimage/src/libAfterImage/asvisual.h index e1f44d03185fc..0f80ab5ea4ae1 100644 --- a/graf2d/asimage/src/libAfterImage/asvisual.h +++ b/graf2d/asimage/src/libAfterImage/asvisual.h @@ -309,19 +309,19 @@ void pixel2color16bgr(ASVisual *asv, unsigned long pixel, CARD32 *red, CARD32 *g void pixel2color15rgb(ASVisual *asv, unsigned long pixel, CARD32 *red, CARD32 *green, CARD32 *blue); void pixel2color15bgr(ASVisual *asv, unsigned long pixel, CARD32 *red, CARD32 *green, CARD32 *blue); -void ximage2scanline32( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void ximage2scanline16( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void ximage2scanline15( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void ximage2scanline_pseudo3bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void ximage2scanline_pseudo6bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void ximage2scanline_pseudo12bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); - -void scanline2ximage32( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void scanline2ximage16( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void scanline2ximage15( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void scanline2ximage_pseudo3bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void scanline2ximage_pseudo6bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); -void scanline2ximage_pseudo12bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, register unsigned char *xim_data ); +void ximage2scanline32( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void ximage2scanline16( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void ximage2scanline15( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void ximage2scanline_pseudo3bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void ximage2scanline_pseudo6bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void ximage2scanline_pseudo12bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); + +void scanline2ximage32( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void scanline2ximage16( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void scanline2ximage15( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void scanline2ximage_pseudo3bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void scanline2ximage_pseudo6bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); +void scanline2ximage_pseudo12bpp( ASVisual *asv, XImage *xim, struct ASScanline *sl, int y, unsigned char *xim_data ); /****f* libAfterImage/query_screen_visual() * NAME diff --git a/graf2d/asimage/src/libAfterImage/import.c b/graf2d/asimage/src/libAfterImage/import.c index 9092c426d00e3..49aa5d8af7cec 100644 --- a/graf2d/asimage/src/libAfterImage/import.c +++ b/graf2d/asimage/src/libAfterImage/import.c @@ -121,7 +121,6 @@ #include "xpm.h" #include "ungif.h" #include "import.h" -#include "asimagexml.h" #include "transform.h" #ifdef jmpbuf @@ -183,7 +182,7 @@ const char *as_image_file_type_names[ASIT_Unknown+1] = "Unknown" }; -char *locate_image_file_in_path( const char *file, ASImageImportParams *iparams ) +char *locate_image_file_in_path( const char *file, ASImageImportParams *iparams ) { int filename_len ; char *realfilename = NULL, *tmp = NULL ; @@ -197,7 +196,7 @@ char *locate_image_file_in_path( const char *file, ASImageImportParams *iparams { filename_len = strlen(file); #ifdef _WIN32 - for( i = 0 ; iparams->search_path[i] != NULL ; ++i ) + for( i = 0 ; iparams->search_path[i] != NULL ; ++i ) unix_path2dos_path( iparams->search_path[i] ); #endif @@ -254,13 +253,13 @@ file2ASImage_extra( const char *file, ASImageImportParams *iparams ) char *realfilename ; ASImage *im = NULL; ASImageImportParams dummy_iparams = {0}; - + if( iparams == NULL ) iparams = &dummy_iparams ; - realfilename = locate_image_file_in_path( file, iparams ); - - if( realfilename != NULL ) + realfilename = locate_image_file_in_path( file, iparams ); + + if( realfilename != NULL ) { ASImageFileTypes file_type = check_image_type( realfilename ); @@ -275,15 +274,15 @@ file2ASImage_extra( const char *file, ASImageImportParams *iparams ) }else show_error( "Support for the format of image file \"%s\" has not been implemented yet.", realfilename ); /* returned image must not be tracked by any ImageManager yet !!! */ - if( im != NULL && im->imageman != NULL ) + if( im != NULL && im->imageman != NULL ) { - if( im->ref_count == 1 ) + if( im->ref_count == 1 ) { forget_asimage( im ); }else { - ASImage *tmp = clone_asimage( im , 0xFFFFFFFF); - if( tmp ) + ASImage *tmp = clone_asimage( im , 0xFFFFFFFF); + if( tmp ) { release_asimage( im ); im = tmp ; @@ -292,7 +291,7 @@ file2ASImage_extra( const char *file, ASImageImportParams *iparams ) } #ifndef NO_DEBUG_OUTPUT - if( im != NULL ) + if( im != NULL ) show_progress( "image loaded from \"%s\"", realfilename ); #endif free( realfilename ); @@ -302,9 +301,9 @@ file2ASImage_extra( const char *file, ASImageImportParams *iparams ) return im; } -void init_asimage_import_params( ASImageImportParams *iparams ) +void init_asimage_import_params( ASImageImportParams *iparams ) { - if( iparams ) + if( iparams ) { iparams->flags = 0 ; iparams->width = 0 ; @@ -332,16 +331,16 @@ file2ASImage( const char *file, ASFlagType what, double gamma, unsigned int comp iparams.compression = compression ; iparams.search_path = &(paths[0]); #if 0 - iparams.width = 1024 ; - iparams.height = -1 ; + iparams.width = 1024 ; + iparams.height = -1 ; iparams.flags |= AS_IMPORT_SCALED_H|AS_IMPORT_SCALED_V ; #endif va_start (ap, compression); for( i = 0 ; i < MAX_SEARCH_PATHS ; i++ ) - { + { if( (paths[i] = va_arg(ap,char*)) == NULL ) break; - } + } paths[MAX_SEARCH_PATHS] = NULL ; va_end (ap); @@ -409,12 +408,12 @@ get_asimage_file_type( ASImageManager* imageman, const char *file ) { ASImageImportParams iparams ; char *realfilename ; - + init_asimage_import_params( &iparams ); iparams.search_path = imageman?&(imageman->search_path[0]):NULL; - realfilename = locate_image_file_in_path( file, &iparams ); - - if( realfilename != NULL ) + realfilename = locate_image_file_in_path( file, &iparams ); + + if( realfilename != NULL ) { file_type = check_image_type( realfilename ); free( realfilename ); @@ -437,24 +436,24 @@ get_asimage( ASImageManager* imageman, const char *file, ASFlagType what, unsign store_asimage( imageman, im, file ); set_flags( im->flags, ASIM_NAME_IS_FILENAME ); } - + } return im; } -void -calculate_proportions( int src_w, int src_h, int *pdst_w, int *pdst_h ) +void +calculate_proportions( int src_w, int src_h, int *pdst_w, int *pdst_h ) { - int dst_w = pdst_w?*pdst_w:0 ; - int dst_h = pdst_h?*pdst_h:0 ; - - if( src_w > 0 && src_w >= src_h && (dst_w > 0 || dst_h <= 0)) - dst_h = (src_h*dst_w)/src_w ; - else if( src_h > 0 ) - dst_w = (src_w*dst_h)/src_h ; + int dst_w = pdst_w?*pdst_w:0 ; + int dst_h = pdst_h?*pdst_h:0 ; + + if( src_w > 0 && src_w >= src_h && (dst_w > 0 || dst_h <= 0)) + dst_h = (src_h*dst_w)/src_w ; + else if( src_h > 0 ) + dst_w = (src_w*dst_h)/src_h ; - if( pdst_w ) *pdst_w = dst_w ; - if( pdst_h ) *pdst_h = dst_h ; + if( pdst_w ) *pdst_w = dst_w ; + if( pdst_h ) *pdst_h = dst_h ; } void print_asimage_func (ASHashableValue value); @@ -462,32 +461,32 @@ ASImage * get_thumbnail_asimage( ASImageManager* imageman, const char *file, int thumb_width, int thumb_height, ASFlagType flags ) { ASImage *im = NULL ; - + if( imageman && file ) { #define AS_THUMBNAIL_NAME_FORMAT "%s_scaled_to_%dx%d" char *thumbnail_name = safemalloc( strlen(file)+sizeof(AS_THUMBNAIL_NAME_FORMAT)+32 ); ASImage *original_im = query_asimage(imageman, file ); - if( thumb_width <= 0 && thumb_height <= 0 ) + if( thumb_width <= 0 && thumb_height <= 0 ) { thumb_width = 48 ; thumb_height = 48 ; } - if( get_flags(flags, AS_THUMBNAIL_PROPORTIONAL ) ) + if( get_flags(flags, AS_THUMBNAIL_PROPORTIONAL ) ) { - if( original_im != NULL ) + if( original_im != NULL ) calculate_proportions( original_im->width, original_im->height, &thumb_width, &thumb_height ); }else { - if( thumb_width == 0 ) - thumb_width = thumb_height ; - if( thumb_height == 0 ) - thumb_height = thumb_width ; + if( thumb_width == 0 ) + thumb_width = thumb_height ; + if( thumb_height == 0 ) + thumb_height = thumb_width ; } - if( thumb_width > 0 && thumb_height > 0 ) + if( thumb_width > 0 && thumb_height > 0 ) { sprintf( thumbnail_name, AS_THUMBNAIL_NAME_FORMAT, file, thumb_width, thumb_height ) ; im = fetch_asimage(imageman, thumbnail_name ); @@ -499,43 +498,43 @@ get_thumbnail_asimage( ASImageManager* imageman, const char *file, int thumb_wid (( (int)original_im->width < thumb_width || (int)original_im->height < thumb_height ) && !get_flags( flags, AS_THUMBNAIL_DONT_ENLARGE ) ) ) { im = scale_asimage( NULL, original_im, thumb_width, thumb_height, ASA_ASImage, 100, ASIMAGE_QUALITY_FAST ); - if( im != NULL ) + if( im != NULL ) store_asimage( imageman, im, thumbnail_name ); }else im = dup_asimage( original_im ); } } } - - if( im == NULL ) + + if( im == NULL ) { - ASImage *tmp ; + ASImage *tmp ; ASImageImportParams iparams ; init_asimage_import_params( &iparams ); iparams.gamma = imageman->gamma ; iparams.search_path = &(imageman->search_path[0]); - - iparams.width = thumb_width ; - iparams.height = thumb_height ; + + iparams.width = thumb_width ; + iparams.height = thumb_height ; if( !get_flags( flags, AS_THUMBNAIL_DONT_ENLARGE|AS_THUMBNAIL_DONT_REDUCE ) ) - iparams.flags |= AS_IMPORT_RESIZED|AS_IMPORT_SCALED_BOTH ; - + iparams.flags |= AS_IMPORT_RESIZED|AS_IMPORT_SCALED_BOTH ; + if( get_flags( flags, AS_THUMBNAIL_DONT_ENLARGE ) ) - iparams.flags |= AS_IMPORT_FAST ; - + iparams.flags |= AS_IMPORT_FAST ; + tmp = file2ASImage_extra( file, &iparams ); - if( tmp ) + if( tmp ) { - im = tmp ; - if( (int)tmp->width != thumb_width || (int)tmp->height != thumb_height ) + im = tmp ; + if( (int)tmp->width != thumb_width || (int)tmp->height != thumb_height ) { - if( get_flags(flags, AS_THUMBNAIL_PROPORTIONAL ) ) + if( get_flags(flags, AS_THUMBNAIL_PROPORTIONAL ) ) { calculate_proportions( tmp->width, tmp->height, &thumb_width, &thumb_height ); sprintf( thumbnail_name, AS_THUMBNAIL_NAME_FORMAT, file, thumb_width, thumb_height ); - if( (im = query_asimage( imageman, thumbnail_name )) == NULL ) - im = tmp ; + if( (im = query_asimage( imageman, thumbnail_name )) == NULL ) + im = tmp ; } if( im == tmp ) { @@ -543,11 +542,11 @@ get_thumbnail_asimage( ASImageManager* imageman, const char *file, int thumb_wid (( (int)tmp->width < thumb_width || (int)tmp->height < thumb_height ) && !get_flags( flags, AS_THUMBNAIL_DONT_ENLARGE ) ) ) { im = scale_asimage( NULL, tmp, thumb_width, thumb_height, ASA_ASImage, 100, ASIMAGE_QUALITY_FAST ); - if( im == NULL ) + if( im == NULL ) im = tmp ; } } - } + } if( im != NULL ) { @@ -556,14 +555,14 @@ get_thumbnail_asimage( ASImageManager* imageman, const char *file, int thumb_wid else dup_asimage( im ); } - - if( im != tmp ) - destroy_asimage( &tmp ); + + if( im != tmp ) + destroy_asimage( &tmp ); } - + } - - if( thumbnail_name ) + + if( thumbnail_name ) free( thumbnail_name ); } return im; @@ -574,7 +573,7 @@ Bool reload_asimage_manager( ASImageManager *imman ) { #if (HAVE_AFTERBASE_FLAG==1) - if( imman != NULL ) + if( imman != NULL ) { ASHashIterator iter ; if( start_hash_iteration (imman->image_hash, &iter) ) @@ -587,17 +586,17 @@ reload_asimage_manager( ASImageManager *imman ) { /*fprintf( stderr, "reloading image \"%s\" ...", im->name );*/ ASImage *reloaded_im = load_image_from_path( im->name, &(imman->search_path[0]), imman->gamma); -/*fprintf( stderr, "Done. reloaded_im = %p.\n", reloaded_im );*/ - if( reloaded_im ) +/*fprintf( stderr, "Done. reloaded_im = %p.\n", reloaded_im );*/ + if( reloaded_im ) { - if( asimage_replace (im, reloaded_im) ) + if( asimage_replace (im, reloaded_im) ) free( reloaded_im ); else destroy_asimage( &reloaded_im ); - } + } } }while( next_hash_item( &iter ) ); - return True; + return True; } } #endif @@ -605,64 +604,64 @@ reload_asimage_manager( ASImageManager *imman ) } -ASImageListEntry * +ASImageListEntry * ref_asimage_list_entry( ASImageListEntry *entry ) { - if( entry ) + if( entry ) { if( IS_ASIMAGE_LIST_ENTRY(entry) ) ++(entry->ref_count); else - entry = NULL ; + entry = NULL ; } return entry; } - + ASImageListEntry * unref_asimage_list_entry( ASImageListEntry *entry ) { - if( entry ) - { + if( entry ) + { if( IS_ASIMAGE_LIST_ENTRY(entry) ) { --(entry->ref_count); if( entry->ref_count <= 0 ) { - ASImageListEntry *prev = entry->prev ; - ASImageListEntry *next = entry->next ; + ASImageListEntry *prev = entry->prev ; + ASImageListEntry *next = entry->next ; if( !IS_ASIMAGE_LIST_ENTRY(prev) ) - prev = NULL ; + prev = NULL ; if( !IS_ASIMAGE_LIST_ENTRY(next) ) - next = NULL ; - if( prev ) - prev->next = next ; - if( next ) - next->prev = prev ; + next = NULL ; + if( prev ) + prev->next = next ; + if( next ) + next->prev = prev ; - if( entry->preview ) + if( entry->preview ) safe_asimage_destroy( entry->preview ); if( entry->name ) free( entry->name ); if( entry->fullfilename ) free( entry->fullfilename ); - if( entry->buffer ) + if( entry->buffer ) destroy_asimage_list_entry_buffer( &(entry->buffer) ); memset( entry, 0x00, sizeof(ASImageListEntry)); free( entry ); - entry = NULL ; - } + entry = NULL ; + } }else entry = NULL ; } return entry; -} +} ASImageListEntry * create_asimage_list_entry() { ASImageListEntry *entry = safecalloc( 1, sizeof(ASImageListEntry)); - entry->ref_count = 1 ; - entry->magic = MAGIC_ASIMAGE_LIST_ENTRY ; + entry->ref_count = 1 ; + entry->magic = MAGIC_ASIMAGE_LIST_ENTRY ; return entry; } @@ -670,11 +669,11 @@ void destroy_asimage_list( ASImageListEntry **plist ) { if( plist ) - { + { ASImageListEntry *curr = *plist ; while( IS_ASIMAGE_LIST_ENTRY(curr) ) - { - ASImageListEntry *to_delete = curr ; + { + ASImageListEntry *to_delete = curr ; curr = curr->next ; unref_asimage_list_entry( to_delete ); } @@ -684,14 +683,14 @@ destroy_asimage_list( ASImageListEntry **plist ) void destroy_asimage_list_entry_buffer( ASImageListEntryBuffer **pbuffer ) { - if( pbuffer && *pbuffer ) - { - if( (*pbuffer)->data ) + if( pbuffer && *pbuffer ) + { + if( (*pbuffer)->data ) free( (*pbuffer)->data ) ; free( *pbuffer ); *pbuffer = NULL ; } -} +} struct ASImageListAuxData { @@ -705,23 +704,23 @@ struct ASImageListAuxData }; #ifndef _WIN32 -Bool -direntry2ASImageListEntry( const char *fname, const char *fullname, +Bool +direntry2ASImageListEntry( const char *fname, const char *fullname, struct stat *stat_info, void *aux_data) { struct ASImageListAuxData *data = (struct ASImageListAuxData*)aux_data; ASImageFileTypes file_type ; ASImageListEntry *curr ; - + if (S_ISDIR (stat_info->st_mode)) return False; - + file_type = check_image_type( fullname ); if( file_type != ASIT_Unknown && as_image_file_loaders[file_type] == NULL ) file_type = ASIT_Unknown ; curr = create_asimage_list_entry(); - *(data->pcurr) = curr ; + *(data->pcurr) = curr ; if( data->last ) data->last->next = curr ; curr->prev = data->last ; @@ -796,18 +795,18 @@ get_asimage_list( ASVisual *asv, const char *dir, { ASImageListEntry *im_list = NULL ; #ifndef _WIN32 - struct ASImageListAuxData aux_data ; - int count ; - + struct ASImageListAuxData aux_data ; + int count ; + aux_data.pcurr = &im_list; aux_data.last = NULL; aux_data.preview_type = preview_type; aux_data.preview_width = preview_width; aux_data.preview_height = preview_height; aux_data.preview_compression = preview_compression; - aux_data.asv = asv ; - - + aux_data.asv = asv ; + + if( asv == NULL || dir == NULL ) return NULL ; @@ -823,71 +822,71 @@ char *format_asimage_list_entry_details( ASImageListEntry *entry, Bool vertical { char *details_text ; - if( entry ) - { - int type = (entry->type>ASIT_Unknown)?ASIT_Unknown:entry->type ; + if( entry ) + { + int type = (entry->type>ASIT_Unknown)?ASIT_Unknown:entry->type ; details_text = safemalloc(128); - if( entry->preview ) - sprintf( details_text, vertical?"File type: %s\nSize %dx%d":"File type: %s; Size %dx%d", as_image_file_type_names[type], entry->preview->width, entry->preview->height ); - else + if( entry->preview ) + sprintf( details_text, vertical?"File type: %s\nSize %dx%d":"File type: %s; Size %dx%d", as_image_file_type_names[type], entry->preview->width, entry->preview->height ); + else sprintf( details_text, "File type: %s", as_image_file_type_names[type]); }else - details_text = mystrdup(""); + details_text = mystrdup(""); return details_text; -} +} -Bool +Bool load_asimage_list_entry_data( ASImageListEntry *entry, size_t max_bytes ) { - char * new_buffer ; + char * new_buffer ; size_t new_buffer_size ; FILE *fp; - Bool binary = False ; - if( entry == NULL ) + Bool binary = False ; + if( entry == NULL ) return False; - if( entry->buffer == NULL ) + if( entry->buffer == NULL ) entry->buffer = safecalloc( 1, sizeof(ASImageListEntryBuffer) ); if( (int)entry->buffer->size == entry->d_size || entry->buffer->size >= max_bytes ) return True; - new_buffer_size = min( max_bytes, (size_t)entry->d_size ); + new_buffer_size = min( max_bytes, (size_t)entry->d_size ); new_buffer = malloc( new_buffer_size ); - if( new_buffer == NULL ) + if( new_buffer == NULL ) return False ; - if( entry->buffer->size > 0 ) - { + if( entry->buffer->size > 0 ) + { memcpy( new_buffer, entry->buffer->data, entry->buffer->size ) ; free( entry->buffer->data ); } - entry->buffer->data = new_buffer ; + entry->buffer->data = new_buffer ; /* TODO read new_buffer_size - entry->buffer_size bytes into the end of the buffer */ fp = fopen(entry->fullfilename, "rb"); - if ( fp != NULL ) + if ( fp != NULL ) { int len = new_buffer_size - entry->buffer->size ; - if( entry->buffer->size > 0 ) + if( entry->buffer->size > 0 ) fseek( fp, entry->buffer->size, SEEK_SET ); len = fread(entry->buffer->data, 1, len, fp); - if( len > 0 ) + if( len > 0 ) entry->buffer->size += len ; fclose(fp); } - if( entry->type == ASIT_Unknown ) + if( entry->type == ASIT_Unknown ) { - int i = entry->buffer->size ; + int i = entry->buffer->size ; register char *ptr = entry->buffer->data ; - while ( --i >= 0 ) - if( !isprint(ptr[i]) && ptr[i] != '\n'&& ptr[i] != '\r'&& ptr[i] != '\t' ) + while ( --i >= 0 ) + if( !isprint(ptr[i]) && ptr[i] != '\n'&& ptr[i] != '\r'&& ptr[i] != '\t' ) break; - binary = (i >= 0); + binary = (i >= 0); }else binary = (entry->type != ASIT_Xpm && entry->type != ASIT_XMLScript && - entry->type != ASIT_HTML && entry->type != ASIT_XML ); - if( binary ) + entry->type != ASIT_HTML && entry->type != ASIT_XML ); + if( binary ) set_flags( entry->buffer->flags, ASILEB_Binary ); else clear_flags( entry->buffer->flags, ASILEB_Binary ); - + return True; @@ -906,7 +905,7 @@ locate_image_file( const char *file, char **paths ) #ifdef _WIN32 unix_path2dos_path( realfilename ); #endif - + if( CheckFile( realfilename ) != 0 ) { free( realfilename ) ; @@ -916,10 +915,10 @@ locate_image_file( const char *file, char **paths ) register int i = 0; do { - if( i > 0 ) - { + if( i > 0 ) + { show_progress( "looking for image \"%s\" in path [%s]", file, paths[i] ); - } + } realfilename = find_file( file, paths[i], R_OK ); }while( realfilename == NULL && paths[i++] != NULL ); } @@ -950,7 +949,7 @@ check_image_type( const char *realfilename ) #define FILE_HEADER_SIZE 512 /* lets check if we have compressed xpm file : */ - if( filename_len > 5 && (mystrncasecmp( realfilename+filename_len-5, ".html", 5 ) == 0 || + if( filename_len > 5 && (mystrncasecmp( realfilename+filename_len-5, ".html", 5 ) == 0 || mystrncasecmp( realfilename+filename_len-4, ".htm", 4 ) == 0 )) type = ASIT_HTML; else if( filename_len > 7 && mystrncasecmp( realfilename+filename_len-7, ".xpm.gz", 7 ) == 0 ) @@ -995,8 +994,8 @@ check_image_type( const char *realfilename ) if( type == ASIT_Unknown && bytes_in > 6 ) { if( mystrncasecmp( head, "", 6 ) == 0 ) - type = ASIT_HTML; - } + type = ASIT_HTML; + } if( type == ASIT_Unknown && bytes_in > 8 ) { if( strncmp(&(head[0]), XCF_SIGNATURE, (size_t) XCF_SIGNATURE_LEN) == 0) @@ -1017,27 +1016,27 @@ check_image_type( const char *realfilename ) while( bytes_in > 0 && type == ASIT_XMLScript ) { if( i >= bytes_in ) - { + { bytes_in = fread( &(head[0]), sizeof(CARD8), FILE_HEADER_SIZE, fp ); for( i = 0 ; i < bytes_in ; ++i ) if( !isspace(head[i]) ) break; } else if( head[i] != '<' ) type = ASIT_Unknown ; - else if( mystrncasecmp( &(head[i]), " 0 && type == ASIT_XMLScript ) @@ -1054,14 +1053,14 @@ check_image_type( const char *realfilename ) } if( i >= bytes_in ) - { + { bytes_in = fread( &(head[0]), sizeof(CARD8), FILE_HEADER_SIZE, fp ); - i = 0 ; + i = 0 ; }else break ; } break; - } + } } } } @@ -1074,7 +1073,7 @@ check_image_type( const char *realfilename ) ASImageFileTypes check_asimage_file_type( const char *realfilename ) { - if( realfilename == NULL ) + if( realfilename == NULL ) return ASIT_Unknown; return check_image_type( realfilename ); } @@ -1101,7 +1100,7 @@ xpm_file2ASImage( ASXpmFile *xpm_file, unsigned int compression ) ASFlagType alpha_flags = ASStorage_RLEDiffCompress|ASStorage_32Bit ; int old_storage_block_size = set_asstorage_block_size( NULL, xpm_file->width*xpm_file->height*3/2 ); - if( !xpm_file->full_alpha ) + if( !xpm_file->full_alpha ) alpha_flags |= ASStorage_Bitmap ; for( line = 0 ; line < xpm_file->height ; ++line ) { @@ -1206,7 +1205,7 @@ static inline void apply_gamma( register CARD8* raw, register CARD8 *gamma_table, unsigned int width ) { if( gamma_table ) - { + { register unsigned int i ; for( i = 0 ; i < width ; ++i ) raw[i] = gamma_table[raw[i]] ; @@ -1254,34 +1253,34 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) { ASFlagType rgb_flags = ASStorage_RLEDiffCompress|ASStorage_32Bit ; - if(read_fn == NULL ) - { + if(read_fn == NULL ) + { png_init_io(png_ptr, (FILE*)data); }else { png_set_read_fn(png_ptr, (void*)data, (png_rw_ptr) read_fn); - } + } png_read_info (png_ptr, info_ptr); png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); -/*fprintf( stderr, "bit_depth = %d, color_type = %d, width = %d, height = %d\n", - bit_depth, color_type, width, height); +/*fprintf( stderr, "bit_depth = %d, color_type = %d, width = %d, height = %d\n", + bit_depth, color_type, width, height); */ if (bit_depth < 8) {/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single * byte into separate bytes (useful for paletted and grayscale images). */ - if( bit_depth == 1 ) + if( bit_depth == 1 ) { set_flags( rgb_flags, ASStorage_Bitmap ); png_set_packing (png_ptr); }else { - /* even though 2 and 4 bit values get expanded into a whole bytes the - values don't get scaled accordingly !!! + /* even though 2 and 4 bit values get expanded into a whole bytes the + values don't get scaled accordingly !!! WE will have to take care of it ourselves : - */ + */ upscaled_gray = safemalloc(width+8); } }else if (bit_depth == 16) @@ -1317,16 +1316,14 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) else color_type = PNG_COLOR_TYPE_GRAY_ALPHA ; */ - if (png_get_sRGB (png_ptr, info_ptr, &intent)) - { - png_set_gamma (png_ptr, params->gamma, DEFAULT_PNG_IMAGE_GAMMA); - }else if (png_get_gAMA (png_ptr, info_ptr, &image_gamma) && bit_depth >= 8) - {/* don't gamma-correct 1, 2, 4 bpp grays as we loose data this way */ - png_set_gamma (png_ptr, params->gamma, image_gamma); - }else - { - png_set_gamma (png_ptr, params->gamma, DEFAULT_PNG_IMAGE_GAMMA); - } + if (png_get_sRGB (png_ptr, info_ptr, &intent)) { + png_set_gamma (png_ptr, params->gamma > 0 ? params->gamma : DEFAULT_PNG_IMAGE_GAMMA, DEFAULT_PNG_IMAGE_GAMMA); + } else if (png_get_gAMA (png_ptr, info_ptr, &image_gamma) && bit_depth >= 8) { + /* don't gamma-correct 1, 2, 4 bpp grays as we loose data this way */ + png_set_gamma (png_ptr, params->gamma > 0 ? params->gamma : DEFAULT_PNG_IMAGE_GAMMA , image_gamma); + } else { + png_set_gamma (png_ptr, params->gamma > 0 ? params->gamma : DEFAULT_PNG_IMAGE_GAMMA, DEFAULT_PNG_IMAGE_GAMMA); + } /* Optional call to gamma correct and add the background to the palette * and update info structure. REQUIRED if you are expecting libpng to @@ -1342,10 +1339,10 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) grayscale = ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA || color_type == PNG_COLOR_TYPE_GRAY) ; -/* fprintf( stderr, "do_alpha = %d, grayscale = %d, bit_depth = %d, color_type = %d, width = %d, height = %d\n", +/* fprintf( stderr, "do_alpha = %d, grayscale = %d, bit_depth = %d, color_type = %d, width = %d, height = %d\n", do_alpha, grayscale, bit_depth, color_type, width, height); */ - if( !do_alpha && grayscale ) + if( !do_alpha && grayscale ) clear_flags( rgb_flags, ASStorage_32Bit ); else prepare_scanline( im->width, 0, &buf, False ); @@ -1364,8 +1361,8 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) old_storage_block_size = set_asstorage_block_size( NULL, width*height*3/2 ); for (y = 0; y < height; y++) { - if( do_alpha || !grayscale ) - { + if( do_alpha || !grayscale ) + { raw2scanline( row_pointers[y], &buf, NULL, buf.width, grayscale, do_alpha ); im->channels[IC_RED][y] = store_data( NULL, (CARD8*)buf.red, buf.width*4, rgb_flags, 0); }else @@ -1397,16 +1394,16 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) }else im->channels[IC_RED][y] = store_data( NULL, row_pointers[y], row_bytes, rgb_flags, 1); } - - if( grayscale ) - { + + if( grayscale ) + { im->channels[IC_GREEN][y] = dup_data( NULL, im->channels[IC_RED][y] ); im->channels[IC_BLUE][y] = dup_data( NULL, im->channels[IC_RED][y] ); }else { - im->channels[IC_GREEN][y] = store_data( NULL, (CARD8*)buf.green, buf.width*4, rgb_flags, 0); + im->channels[IC_GREEN][y] = store_data( NULL, (CARD8*)buf.green, buf.width*4, rgb_flags, 0); im->channels[IC_BLUE][y] = store_data( NULL, (CARD8*)buf.blue, buf.width*4, rgb_flags, 0); - } + } if( do_alpha ) { @@ -1415,20 +1412,20 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) for ( i = 0 ; i < buf.width ; ++i) { if( buf.alpha[i] != 0x00FF ) - { + { if( buf.alpha[i] == 0 ) has_zero = True ; else - { + { has_nozero = True ; break; } - } + } } - if( has_zero || has_nozero ) + if( has_zero || has_nozero ) { ASFlagType alpha_flags = ASStorage_32Bit|ASStorage_RLEDiffCompress ; - if( !has_nozero ) + if( !has_nozero ) set_flags( alpha_flags, ASStorage_Bitmap ); im->channels[IC_ALPHA][y] = store_data( NULL, (CARD8*)buf.alpha, buf.width*4, alpha_flags, 0); } @@ -1438,7 +1435,7 @@ png2ASImage_int( void *data, png_rw_ptr read_fn, ASImageImportParams *params ) if (upscaled_gray) free(upscaled_gray); free (row_pointers); - if( do_alpha || !grayscale ) + if( do_alpha || !grayscale ) free_scanline(&buf, True); /* read rest of file, and get additional chunks in info_ptr - REQUIRED */ png_read_end (png_ptr, info_ptr); @@ -1461,8 +1458,8 @@ print_asimage( im, ASFLAGS_EVERYTHING, __FUNCTION__, __LINE__ ); /****** VO ******/ typedef struct ASImPNGReadBuffer { - CARD8 *buffer ; - + CARD8 *buffer ; + } ASImPNGReadBuffer; static void asim_png_read_data(png_structp png_ptr, png_bytep data, png_size_t length) @@ -1598,58 +1595,58 @@ jpeg2ASImage( const char * path, ASImageImportParams *params ) /* Adjust default decompression parameters */ cinfo.quantize_colors = FALSE; /* we don't want no stinking colormaps ! */ cinfo.output_gamma = params->gamma; - + if( get_flags( params->flags, AS_IMPORT_SCALED_BOTH ) == AS_IMPORT_SCALED_BOTH ) { - int w = params->width ; + int w = params->width ; int h = params->height ; - int ratio ; + int ratio ; if( w == 0 ) { - if( h == 0 ) + if( h == 0 ) { - w = cinfo.image_width ; - h = cinfo.image_height ; + w = cinfo.image_width ; + h = cinfo.image_height ; }else w = (cinfo.image_width * h)/cinfo.image_height ; }else if( h == 0 ) h = (cinfo.image_height * w)/cinfo.image_width ; - - ratio = cinfo.image_height/h ; + + ratio = cinfo.image_height/h ; if( ratio > (int)cinfo.image_width/w ) - ratio = cinfo.image_width/w ; - - cinfo.scale_num = 1 ; + ratio = cinfo.image_width/w ; + + cinfo.scale_num = 1 ; /* only supported values are 1, 2, 4, and 8 */ - cinfo.scale_denom = 1 ; - if( ratio >= 2 ) + cinfo.scale_denom = 1 ; + if( ratio >= 2 ) { - if( ratio >= 4 ) + if( ratio >= 4 ) { - if( ratio >= 8 ) - cinfo.scale_denom = 8 ; + if( ratio >= 8 ) + cinfo.scale_denom = 8 ; else - cinfo.scale_denom = 4 ; + cinfo.scale_denom = 4 ; }else - cinfo.scale_denom = 2 ; + cinfo.scale_denom = 2 ; } } - + if( get_flags( params->flags, AS_IMPORT_FAST ) ) {/* this does not really makes much of a difference */ - cinfo.do_fancy_upsampling = FALSE ; - cinfo.do_block_smoothing = FALSE ; - cinfo.dct_method = JDCT_IFAST ; + cinfo.do_fancy_upsampling = FALSE ; + cinfo.do_block_smoothing = FALSE ; + cinfo.dct_method = JDCT_IFAST ; } - + /* Step 5: Start decompressor */ (void)jpeg_start_decompress (&cinfo); LOCAL_DEBUG_OUT("stored image size %dx%d", cinfo.output_width, cinfo.output_height); im = create_asimage( cinfo.output_width, cinfo.output_height, params->compression ); - - if( cinfo.output_components != 1 ) + + if( cinfo.output_components != 1 ) prepare_scanline( im->width, 0, &buf, False ); /* Make a one-row-high sample array that will go away when done with image */ @@ -1673,14 +1670,14 @@ jpeg2ASImage( const char * path, ASImageImportParams *params ) * more than one scanline at a time if that's more convenient. */ (void)jpeg_read_scanlines (&cinfo, buffer, 1); - if( cinfo.output_components==1 ) - { + if( cinfo.output_components==1 ) + { apply_gamma( (CARD8*)buffer[0], params->gamma_table, im->width ); im->channels[IC_RED][y] = store_data( NULL, (CARD8*)buffer[0], im->width, ASStorage_RLEDiffCompress, 0); im->channels[IC_GREEN][y] = dup_data( NULL, im->channels[IC_RED][y] ); im->channels[IC_BLUE][y] = dup_data( NULL, im->channels[IC_RED][y] ); }else - { + { raw2scanline( (CARD8*)buffer[0], &buf, params->gamma_table, im->width, (cinfo.output_components==1), False); im->channels[IC_RED][y] = store_data( NULL, (CARD8*)buf.red, buf.width*4, ASStorage_32BitRLE, 0); im->channels[IC_GREEN][y] = store_data( NULL, (CARD8*)buf.green, buf.width*4, ASStorage_32BitRLE, 0); @@ -1696,7 +1693,7 @@ jpeg2ASImage( const char * path, ASImageImportParams *params ) */ } set_asstorage_block_size( NULL, old_storage_block_size ); - if( cinfo.output_components != 1 ) + if( cinfo.output_components != 1 ) free_scanline(&buf, True); SHOW_TIME("read",started); @@ -1883,23 +1880,23 @@ gif_interlaced2y(int line /* 0 -- (height - 1) */, int height) int lines_in_current_pass; /* pass 1 */ lines_in_current_pass = height / 8 + (height%8?1:0); - if (line < lines_in_current_pass) + if (line < lines_in_current_pass) return line * 8; - + passed_lines = lines_in_current_pass; /* pass 2 */ - if (height > 4) + if (height > 4) { lines_in_current_pass = (height - 4) / 8 + ((height - 4)%8 ? 1 : 0); - if (line < lines_in_current_pass + passed_lines) + if (line < lines_in_current_pass + passed_lines) return 4 + 8*(line - passed_lines); passed_lines += lines_in_current_pass; } /* pass 3 */ - if (height > 2) + if (height > 2) { lines_in_current_pass = (height - 2) / 4 + ((height - 2)%4 ? 1 : 0); - if (line < lines_in_current_pass + passed_lines) + if (line < lines_in_current_pass + passed_lines) return 2 + 4*(line - passed_lines); passed_lines += lines_in_current_pass; } @@ -1924,8 +1921,8 @@ gif2ASImage( const char * path, ASImageImportParams *params ) START_TIME(started); - params->return_animation_delay = 0 ; - + params->return_animation_delay = 0 ; + if ((fp = open_image_file(path)) == NULL) return NULL; #if (GIFLIB_MAJOR>=5) @@ -1936,7 +1933,7 @@ gif2ASImage( const char * path, ASImageImportParams *params ) { SavedImage *sp = NULL ; int count = 0 ; - + status = get_gif_saved_images(gif, params->subimage, &sp, &count ); if( status == GIF_OK && sp != NULL && count > 0 ) { @@ -1950,7 +1947,7 @@ gif2ASImage( const char * path, ASImageImportParams *params ) #ifdef DEBUG_TRANSP_GIF fprintf( stderr, "%d: func = %X, bytes[0] = 0x%X\n", y, sp->ExtensionBlocks[y].Function, sp->ExtensionBlocks[y].Bytes[0]); #endif - if( sp->ExtensionBlocks[y].Function == GRAPHICS_EXT_FUNC_CODE ) + if( sp->ExtensionBlocks[y].Function == GRAPHICS_EXT_FUNC_CODE ) { if( sp->ExtensionBlocks[y].Bytes[0]&0x01 ) { @@ -1959,16 +1956,16 @@ gif2ASImage( const char * path, ASImageImportParams *params ) fprintf( stderr, "transp = %u\n", transparent ); #endif } - params->return_animation_delay = (((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_GCE_DELAY_BYTE_LOW])&0x00FF) + + params->return_animation_delay = (((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_GCE_DELAY_BYTE_LOW])&0x00FF) + ((((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_GCE_DELAY_BYTE_HIGH])<<8)&0x00FF00); }else if( sp->ExtensionBlocks[y].Function == APPLICATION_EXT_FUNC_CODE && sp->ExtensionBlocks[y].ByteCount == 11 ) /* application extension */ { - if( strncmp((const char*)(&sp->ExtensionBlocks[y].Bytes[0]), "NETSCAPE2.0", 11 ) == 0 ) + if( strncmp((const char*)(&sp->ExtensionBlocks[y].Bytes[0]), "NETSCAPE2.0", 11 ) == 0 ) { ++y ; if( y < (unsigned int)sp->ExtensionBlockCount && sp->ExtensionBlocks[y].ByteCount == 3 ) { - params->return_animation_repeats = (((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_NETSCAPE_REPEAT_BYTE_LOW])&0x00FF) + + params->return_animation_repeats = (((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_NETSCAPE_REPEAT_BYTE_LOW])&0x00FF) + ((((unsigned int) sp->ExtensionBlocks[y].Bytes[GIF_NETSCAPE_REPEAT_BYTE_HIGH])<<8)&0x00FF00); #ifdef DEBUG_TRANSP_GIF @@ -1992,9 +1989,9 @@ gif2ASImage( const char * path, ASImageImportParams *params ) int image_y; CARD8 *r = NULL, *g = NULL, *b = NULL, *a = NULL ; int old_storage_block_size ; - r = safemalloc( width ); - g = safemalloc( width ); - b = safemalloc( width ); + r = safemalloc( width ); + g = safemalloc( width ); + b = safemalloc( width ); a = safemalloc( width ); im = create_asimage( width, height, params->compression ); @@ -2015,14 +2012,14 @@ gif2ASImage( const char * path, ASImageImportParams *params ) a[x] = 0 ; }else a[x] = 0x00FF ; - + r[x] = cmap->Colors[c].Red; g[x] = cmap->Colors[c].Green; b[x] = cmap->Colors[c].Blue; } row_pointer += x ; im->channels[IC_RED][image_y] = store_data( NULL, r, width, ASStorage_RLEDiffCompress, 0); - im->channels[IC_GREEN][image_y] = store_data( NULL, g, width, ASStorage_RLEDiffCompress, 0); + im->channels[IC_GREEN][image_y] = store_data( NULL, g, width, ASStorage_RLEDiffCompress, 0); im->channels[IC_BLUE][image_y] = store_data( NULL, b, width, ASStorage_RLEDiffCompress, 0); if( do_alpha ) im->channels[IC_ALPHA][image_y] = store_data( NULL, a, im->width, ASStorage_RLEDiffCompress|ASStorage_Bitmap, 0); @@ -2034,7 +2031,7 @@ gif2ASImage( const char * path, ASImageImportParams *params ) free(r); } free_gif_saved_images( sp, count ); - }else if( status != GIF_OK ) + }else if( status != GIF_OK ) #if (GIFLIB_MAJOR>=5) ASIM_PrintGifError(status); #else @@ -2098,7 +2095,7 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) { TIFFClose(tif); show_error("Image file \"%s\" does not contain subimage %d.", path, params->subimage); - return NULL ; + return NULL ; } TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); @@ -2108,32 +2105,32 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) if( !TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits) ) bits = 8 ; if( !TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip ) ) - rows_per_strip = height ; + rows_per_strip = height ; if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photo) ) photo = 0 ; - + #ifndef PHOTOMETRIC_CFA -#define PHOTOMETRIC_CFA 32803 +#define PHOTOMETRIC_CFA 32803 #endif - + TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar_config); - + if( TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width) || TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_length) ) { show_error( "Tiled TIFF image format is not supported yet." ); TIFFClose(tif); - return NULL; - } + return NULL; + } - if( rows_per_strip == 0 || rows_per_strip > height ) + if( rows_per_strip == 0 || rows_per_strip > height ) rows_per_strip = height ; - if( depth <= 0 ) + if( depth <= 0 ) depth = 4 ; if( depth <= 2 && get_flags( photo, PHOTOMETRIC_RGB) ) depth += 2 ; - LOCAL_DEBUG_OUT ("size = %ldx%ld, depth = %d, bits = %d, rps = %ld, photo = %d, tile_size = %dx%d, config = %d", + LOCAL_DEBUG_OUT ("size = %ldx%ld, depth = %d, bits = %d, rps = %ld, photo = %d, tile_size = %dx%d, config = %d", width, height, depth, bits, rows_per_strip, photo, tile_width, tile_length, planar_config); if( width < MAX_IMPORT_IMAGE_SIZE && height < MAX_IMPORT_IMAGE_SIZE ) { @@ -2145,20 +2142,20 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) ASFlagType store_flags = ASStorage_RLEDiffCompress ; int first_row = 0 ; int old_storage_block_size; - if( bits == 1 ) + if( bits == 1 ) set_flags( store_flags, ASStorage_Bitmap ); - + im = create_asimage( width, height, params->compression ); old_storage_block_size = set_asstorage_block_size( NULL, im->width*im->height*3/2 ); - - if( depth == 2 || depth == 4 ) + + if( depth == 2 || depth == 4 ) a = safemalloc( width ); - r = safemalloc( width ); - if( depth > 2 ) + r = safemalloc( width ); + if( depth > 2 ) { - g = safemalloc( width ); - b = safemalloc( width ); - } + g = safemalloc( width ); + b = safemalloc( width ); + } if (photo == PHOTOMETRIC_CFA) {/* need alternative - more complicated method */ Bool success = False; @@ -2171,7 +2168,7 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) if (strip && imout) { int cfa_type = 0; - ASIMStripLoader line_loaders[2][2] = + ASIMStripLoader line_loaders[2][2] = { {decode_RG_12_be, decode_GB_12_be}, {decode_BG_12_be, decode_GR_12_be} }; @@ -2196,15 +2193,15 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) data = _TIFFmalloc(data_size); } - if (planar_config == PLANARCONFIG_CONTIG) + if (planar_config == PLANARCONFIG_CONTIG) { for (strip_no = 0; strip_no < TIFFNumberOfStrips(tif); strip_no++) { int bytes_in; if (bits == 12) /* can't use libTIFF's function - it can't handle 12bit data ! */ { - /* PENTAX cameras claim that data is compressed as runlength packbits - - it is not in fact run-length, which confuses libTIFF + /* PENTAX cameras claim that data is compressed as runlength packbits - + it is not in fact run-length, which confuses libTIFF */ bytes_in = TIFFReadRawStrip(tif, strip_no, data+loaded_data_size, data_size-loaded_data_size); }else @@ -2213,12 +2210,12 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) LOCAL_DEBUG_OUT( "strip size = %d, bytes_in = %d, bytes_per_row = %d", bc[strip_no], bytes_in, bytes_per_row); if (bytes_in >= 0) loaded_data_size += bytes_in; - else + else { LOCAL_DEBUG_OUT( "failed reading strip %d", strip_no); } - } - } else if (planar_config == PLANARCONFIG_SEPARATE) + } + } else if (planar_config == PLANARCONFIG_SEPARATE) { /* TODO: do something with split channels */ } @@ -2234,8 +2231,8 @@ LOCAL_DEBUG_OUT( "strip size = %d, bytes_in = %d, bytes_per_row = %d", bc[strip_ do { offset = data_row * bytes_per_row; - int loaded_rows = load_asim_strip (strip, (CARD8*)data + offset, loaded_data_size-offset, - data_row, bytes_per_row, + int loaded_rows = load_asim_strip (strip, (CARD8*)data + offset, loaded_data_size-offset, + data_row, bytes_per_row, line_loaders[cfa_type], line_loaders_num[cfa_type]); if (loaded_rows == 0) @@ -2253,20 +2250,20 @@ LOCAL_DEBUG_OUT( "strip size = %d, bytes_in = %d, bytes_per_row = %d", bc[strip_ set_flags (strip->lines[0]->flags, SCL_DO_RED); set_flags (strip->lines[1]->flags, SCL_DO_BLUE); } -#endif +#endif //clear_flags (strip->lines[0]->flags, SCL_DO_GREEN|SCL_DO_BLUE); imout->output_image_scanline( imout, strip->lines[0], 1); - + advance_asim_strip (strip); - } + } data_row += loaded_rows; }while (offset < loaded_data_size); success = True; } } destroy_asim_strip (&strip); - stop_image_output( &imout ); + stop_image_output( &imout ); if (!success) destroy_asimage (&im); @@ -2277,7 +2274,7 @@ LOCAL_DEBUG_OUT( "strip size = %d, bytes_in = %d, bytes_per_row = %d", bc[strip_ { register CARD32 *row = data ; int y = first_row + rows_per_strip ; - if( y > height ) + if( y > height ) y = height ; while( --y >= first_row ) { @@ -2285,27 +2282,27 @@ LOCAL_DEBUG_OUT( "strip size = %d, bytes_in = %d, bytes_per_row = %d", bc[strip_ for( x = 0 ; x < width ; ++x ) { CARD32 c = row[x] ; - if( depth == 4 || depth == 2 ) + if( depth == 4 || depth == 2 ) a[x] = TIFFGetA(c); r[x] = TIFFGetR(c); - if( depth > 2 ) + if( depth > 2 ) { g[x] = TIFFGetG(c); b[x] = TIFFGetB(c); } } im->channels[IC_RED][y] = store_data( NULL, r, width, store_flags, 0); - if( depth > 2 ) + if( depth > 2 ) { - im->channels[IC_GREEN][y] = store_data( NULL, g, width, store_flags, 0); + im->channels[IC_GREEN][y] = store_data( NULL, g, width, store_flags, 0); im->channels[IC_BLUE][y] = store_data( NULL, b, width, store_flags, 0); }else { - im->channels[IC_GREEN][y] = dup_data( NULL, im->channels[IC_RED][y]); + im->channels[IC_GREEN][y] = dup_data( NULL, im->channels[IC_RED][y]); im->channels[IC_BLUE][y] = dup_data( NULL, im->channels[IC_RED][y]); - } + } - if( depth == 4 || depth == 2 ) + if( depth == 4 || depth == 2 ) im->channels[IC_ALPHA][y] = store_data( NULL, a, width, store_flags, 0); row += width ; } @@ -2346,42 +2343,26 @@ tiff2ASImage( const char * path, ASImageImportParams *params ) static ASImage * load_xml2ASImage( ASImageManager *imman, const char *path, unsigned int compression, int width, int height ) { - ASVisual fake_asv ; - char *slash, *curr_path = NULL ; - char *doc_str = NULL ; - ASImage *im = NULL ; - - memset( &fake_asv, 0x00, sizeof(ASVisual) ); - if( (slash = strrchr( path, '/' )) != NULL ) - curr_path = mystrndup( path, slash-path ); - - if((doc_str = load_file(path)) == NULL ) - show_error( "unable to load file \"%s\" file is either too big or is not readable.\n", path ); - else - { - im = compose_asimage_xml_at_size(&fake_asv, imman, NULL, doc_str, 0, 0, None, curr_path, width, height); - free( doc_str ); - } - - if( curr_path ) - free( curr_path ); - return im ; + // Incompatible license + fprintf(stderr, "ERROR in load_xml2ASImage: XML import is disabled.\n"); + ASImage *im = NULL ; + return im; } ASImage * xml2ASImage( const char *path, ASImageImportParams *params ) { - int width = -1, height = -1 ; + int width = -1, height = -1 ; static ASImage *im = NULL ; START_TIME(started); if( get_flags( params->flags, AS_IMPORT_SCALED_H ) ) width = (params->width <= 0)?((params->height<=0)?-1:params->height):params->width ; - + if( get_flags( params->flags, AS_IMPORT_SCALED_V ) ) height = (params->height <= 0)?((params->width <= 0)?-1:params->width):params->height ; - + im = load_xml2ASImage( NULL, path, params->compression, width, height ); SHOW_TIME("image loading",started); @@ -2393,36 +2374,36 @@ ASImage * svg2ASImage( const char * path, ASImageImportParams *params ) { static int gType_inited = 0; - + ASImage *im = NULL; GdkPixbuf *pixbuf; int channels ; - Bool do_alpha ; - int width = -1, height = -1 ; - + Bool do_alpha ; + int width = -1, height = -1 ; + START_TIME(started); #if 1 /* Damn gtk mess... must init once atleast.. can we just init several times or do we bork then? */ - if (gType_inited == 0) + if (gType_inited == 0) { g_type_init(); gType_inited = 1; } - + if( get_flags( params->flags, AS_IMPORT_SCALED_H ) ) width = (params->width <= 0)?((params->height<=0)?-1:params->height):params->width ; - + if( get_flags( params->flags, AS_IMPORT_SCALED_V ) ) height = (params->height <= 0)?((params->width <= 0)?-1:params->width):params->height ; - + if( (pixbuf = rsvg_pixbuf_from_file_at_size( path, width, height, NULL)) == NULL ) return NULL ; - + channels = gdk_pixbuf_get_n_channels(pixbuf) ; do_alpha = gdk_pixbuf_get_has_alpha(pixbuf) ; if ( ((channels == 4 && do_alpha) ||(channels == 3 && !do_alpha)) && - gdk_pixbuf_get_bits_per_sample(pixbuf) == 8 ) + gdk_pixbuf_get_bits_per_sample(pixbuf) == 8 ) { int width, height; register CARD8 *row = gdk_pixbuf_get_pixels(pixbuf); @@ -2433,16 +2414,16 @@ svg2ASImage( const char * path, ASImageImportParams *params ) width = gdk_pixbuf_get_width(pixbuf); height = gdk_pixbuf_get_height(pixbuf); - r = safemalloc( width ); - g = safemalloc( width ); - b = safemalloc( width ); + r = safemalloc( width ); + g = safemalloc( width ); + b = safemalloc( width ); if( do_alpha ) a = safemalloc( width ); im = create_asimage(width, height, params->compression ); old_storage_block_size = set_asstorage_block_size( NULL, im->width*im->height*3/2 ); - for (y = 0; y < height; ++y) + for (y = 0; y < height; ++y) { int x, i = 0 ; for( x = 0 ; x < width ; ++x ) @@ -2450,11 +2431,11 @@ svg2ASImage( const char * path, ASImageImportParams *params ) r[x] = row[i++]; g[x] = row[i++]; b[x] = row[i++]; - if( do_alpha ) + if( do_alpha ) a[x] = row[i++]; } im->channels[IC_RED][y] = store_data( NULL, r, width, ASStorage_RLEDiffCompress, 0); - im->channels[IC_GREEN][y] = store_data( NULL, g, width, ASStorage_RLEDiffCompress, 0); + im->channels[IC_GREEN][y] = store_data( NULL, g, width, ASStorage_RLEDiffCompress, 0); im->channels[IC_BLUE][y] = store_data( NULL, b, width, ASStorage_RLEDiffCompress, 0); if( do_alpha ) @@ -2473,10 +2454,10 @@ svg2ASImage( const char * path, ASImageImportParams *params ) if( a ) free(a); } - + if (pixbuf) gdk_pixbuf_unref(pixbuf); -#endif +#endif SHOW_TIME("image loading",started); return im ; @@ -2507,14 +2488,14 @@ typedef struct ASTGAHeader #define TGA_RLETrueColorImage 10 #define TGA_RLEBWImage 11 CARD8 ImageType; - struct + struct { CARD16 FirstEntryIndex ; - CARD16 ColorMapLength ; /* number of entries */ - CARD8 ColorMapEntrySize ; /* number of bits per entry */ + CARD16 ColorMapLength ; /* number of entries */ + CARD8 ColorMapEntrySize ; /* number of bits per entry */ }ColormapSpec; struct - { + { CARD16 XOrigin; CARD16 YOrigin; CARD16 Width; @@ -2530,21 +2511,21 @@ typedef struct ASTGAHeader typedef struct ASTGAColorMap { int bytes_per_entry; - int bytes_total ; - CARD8 *data ; + int bytes_total ; + CARD8 *data ; }ASTGAColorMap; typedef struct ASTGAImageData { int bytes_per_pixel; int image_size; - int bytes_total ; - CARD8 *data ; + int bytes_total ; + CARD8 *data ; }ASTGAImageData; static Bool load_tga_colormapped(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ) { - + return True; } @@ -2556,63 +2537,63 @@ static Bool load_tga_truecolor(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cm CARD32 *b = buf->blue ; int bpp = (tga->ImageSpec.Depth+7)/8; int bpl = buf->width*bpp; - if( fread( read_buf, 1, bpl, infile ) != (unsigned int)bpl ) + if( fread( read_buf, 1, bpl, infile ) != (unsigned int)bpl ) return False; - if( bpp == 3 ) - { + if( bpp == 3 ) + { unsigned int i; if( gamma_table ) - for( i = 0 ; i < buf->width ; ++i ) + for( i = 0 ; i < buf->width ; ++i ) { - b[i] = gamma_table[*(read_buf++)]; - g[i] = gamma_table[*(read_buf++)]; - r[i] = gamma_table[*(read_buf++)]; - } + b[i] = gamma_table[*(read_buf++)]; + g[i] = gamma_table[*(read_buf++)]; + r[i] = gamma_table[*(read_buf++)]; + } else - for( i = 0 ; i < buf->width ; ++i ) + for( i = 0 ; i < buf->width ; ++i ) { - b[i] = *(read_buf++); - g[i] = *(read_buf++); - r[i] = *(read_buf++); - } + b[i] = *(read_buf++); + g[i] = *(read_buf++); + r[i] = *(read_buf++); + } set_flags( buf->flags, SCL_DO_RED|SCL_DO_GREEN|SCL_DO_BLUE ); }else if( bpp == 4 ) { unsigned int i; - for( i = 0 ; i < buf->width ; ++i ) + for( i = 0 ; i < buf->width ; ++i ) { - b[i] = *(read_buf++); - g[i] = *(read_buf++); - r[i] = *(read_buf++); - a[i] = *(read_buf++); - } + b[i] = *(read_buf++); + g[i] = *(read_buf++); + r[i] = *(read_buf++); + a[i] = *(read_buf++); + } set_flags( buf->flags, SCL_DO_RED|SCL_DO_GREEN|SCL_DO_BLUE|SCL_DO_ALPHA ); - } + } return True; } static Bool load_tga_bw(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ) { - + return True; } static Bool load_tga_rle_colormapped(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ) { - + return True; } static Bool load_tga_rle_truecolor(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ) { - + return True; } static Bool load_tga_rle_bw(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ) { - + return True; } @@ -2632,37 +2613,37 @@ tga2ASImage( const char * path, ASImageImportParams *params ) if ((infile = open_image_file(path)) == NULL) return NULL; - if( fread( &tga, 1, 3, infile ) == 3 ) - if( fread( &tga.ColormapSpec, 1, 5, infile ) == 5 ) - if( fread( &tga.ImageSpec, 1, 10, infile ) == 10 ) + if( fread( &tga, 1, 3, infile ) == 3 ) + if( fread( &tga.ColormapSpec, 1, 5, infile ) == 5 ) + if( fread( &tga.ImageSpec, 1, 10, infile ) == 10 ) { Bool success = True ; Bool (*load_row_func)(FILE *infile, ASTGAHeader *tga, ASTGAColorMap *cmap, ASScanline *buf, CARD8 *read_buf, CARD8 *gamma_table ); - if( tga.IDLength > 0 ) + if( tga.IDLength > 0 ) success = (fseek( infile, tga.IDLength, SEEK_CUR )==0); - if( success && tga.ColorMapType != 0 ) + if( success && tga.ColorMapType != 0 ) { cmap = safecalloc( 1, sizeof(ASTGAColorMap)); cmap->bytes_per_entry = (tga.ColormapSpec.ColorMapEntrySize+7)/8; - cmap->bytes_total = cmap->bytes_per_entry*tga.ColormapSpec.ColorMapLength; + cmap->bytes_total = cmap->bytes_per_entry*tga.ColormapSpec.ColorMapLength; cmap->data = safemalloc( cmap->bytes_total); success = ( fread( cmap->data, 1, cmap->bytes_total, infile ) == (unsigned int)cmap->bytes_total ); }else if( tga.ImageSpec.Depth != 24 && tga.ImageSpec.Depth != 32 ) success = False ; - - if( success ) + + if( success ) { success = False; if( tga.ImageType != TGA_NoImageData ) - { - width = tga.ImageSpec.Width ; - height = tga.ImageSpec.Height ; + { + width = tga.ImageSpec.Width ; + height = tga.ImageSpec.Height ; if( width < MAX_IMPORT_IMAGE_SIZE && height < MAX_IMPORT_IMAGE_SIZE ) success = True; } } - switch( tga.ImageType ) + switch( tga.ImageType ) { case TGA_ColormappedImage :load_row_func = load_tga_colormapped ; break ; case TGA_TrueColorImage :load_row_func = load_tga_truecolor ; break ; @@ -2672,10 +2653,10 @@ tga2ASImage( const char * path, ASImageImportParams *params ) case TGA_RLEBWImage :load_row_func = load_tga_rle_bw ; break ; default: load_row_func = NULL ; - } - - if( success && load_row_func != NULL ) - { + } + + if( success && load_row_func != NULL ) + { ASImageOutput *imout ; int old_storage_block_size; im = create_asimage( width, height, params->compression ); @@ -2686,15 +2667,15 @@ tga2ASImage( const char * path, ASImageImportParams *params ) destroy_asimage( &im ); success = False; }else - { + { ASScanline buf; int y ; - CARD8 *read_buf = safemalloc( width*4*2 ); + CARD8 *read_buf = safemalloc( width*4*2 ); prepare_scanline( im->width, 0, &buf, True ); - if( !get_flags( tga.ImageSpec.Descriptor, TGA_TopToBottom ) ) + if( !get_flags( tga.ImageSpec.Descriptor, TGA_TopToBottom ) ) toggle_image_output_direction( imout ); - for( y = 0 ; y < height ; ++y ) - { + for( y = 0 ; y < height ; ++y ) + { if( !load_row_func( infile, &tga, cmap, &buf, read_buf, params->gamma_table ) ) break; imout->output_image_scanline( imout, &buf, 1); @@ -2702,11 +2683,11 @@ tga2ASImage( const char * path, ASImageImportParams *params ) stop_image_output( &imout ); free_scanline( &buf, True ); free( read_buf ); - } + } set_asstorage_block_size( NULL, old_storage_block_size ); - } - } + } + } if( im == NULL ) show_error( "invalid or unsupported TGA format in image file \"%s\"", path ); @@ -2729,33 +2710,33 @@ convert_argb2ASImage( ASVisual *asv, int width, int height, ARGB32 *argb, CARD8 destroy_asimage( &im ); return NULL; }else - { + { ASScanline buf; int y ; int old_storage_block_size = set_asstorage_block_size( NULL, im->width*im->height*3 ); prepare_scanline( im->width, 0, &buf, True ); - for( y = 0 ; y < height ; ++y ) - { + for( y = 0 ; y < height ; ++y ) + { int x ; - for( x = 0 ; x < width ; ++x ) + for( x = 0 ; x < width ; ++x ) { ARGB32 c = argb[x]; - buf.alpha[x] = ARGB32_ALPHA8(c); - buf.red[x] = ARGB32_RED8(c); - buf.green[x] = ARGB32_GREEN8(c); - buf.blue[x] = ARGB32_BLUE8(c); - } - argb += width ; + buf.alpha[x] = ARGB32_ALPHA8(c); + buf.red[x] = ARGB32_RED8(c); + buf.green[x] = ARGB32_GREEN8(c); + buf.blue[x] = ARGB32_BLUE8(c); + } + argb += width ; set_flags( buf.flags, SCL_DO_RED|SCL_DO_GREEN|SCL_DO_BLUE|SCL_DO_ALPHA ); imout->output_image_scanline( imout, &buf, 1); } set_asstorage_block_size( NULL, old_storage_block_size ); stop_image_output( &imout ); free_scanline( &buf, True ); - } - - return im ; + } + + return im ; } @@ -2763,7 +2744,7 @@ ASImage * argb2ASImage( const char *path, ASImageImportParams *params ) { ASVisual fake_asv ; - long argb_data_len = -1; + long argb_data_len = -1; char *argb_data = NULL ; ASImage *im = NULL ; @@ -2782,9 +2763,9 @@ argb2ASImage( const char *path, ASImageImportParams *params ) }else im = convert_argb2ASImage( &fake_asv, width, height, (ARGB32*)argb_data+2, params->gamma_table ); } - if( argb_data ) + if( argb_data ) free( argb_data ); - + return im ; } diff --git a/graf2d/asimage/src/libAfterImage/libAfterImage.dsp b/graf2d/asimage/src/libAfterImage/libAfterImage.dsp index 893542dca4472..9f24ff975ddb8 100644 --- a/graf2d/asimage/src/libAfterImage/libAfterImage.dsp +++ b/graf2d/asimage/src/libAfterImage/libAfterImage.dsp @@ -7,19 +7,19 @@ CFG=libAfterImage - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run -!MESSAGE +!MESSAGE !MESSAGE NMAKE /f "libAfterImage.mak". -!MESSAGE +!MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE +!MESSAGE !MESSAGE NMAKE /f "libAfterImage.mak" CFG="libAfterImage - Win32 Debug" -!MESSAGE +!MESSAGE !MESSAGE Possible choices for configuration are: -!MESSAGE +!MESSAGE !MESSAGE "libAfterImage - Win32 Release" (based on "Win32 (x86) Static Library") !MESSAGE "libAfterImage - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE +!MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 @@ -75,7 +75,7 @@ LIB32=link.exe -lib # ADD BASE LIB32 /nologo # ADD LIB32 /nologo -!ENDIF +!ENDIF # Begin Target @@ -434,10 +434,6 @@ SOURCE=.\asimage.c # End Source File # Begin Source File -SOURCE=.\asimagexml.c -# End Source File -# Begin Source File - SOURCE=.\asstorage.c # End Source File # Begin Source File @@ -470,10 +466,6 @@ SOURCE=.\import.c # End Source File # Begin Source File -SOURCE=.\pixmap.c -# End Source File -# Begin Source File - SOURCE=.\transform.c # End Source File # Begin Source File @@ -522,10 +514,6 @@ SOURCE=.\asimage.h # End Source File # Begin Source File -SOURCE=.\asimagexml.h -# End Source File -# Begin Source File - SOURCE=.\asvisual.h # End Source File # Begin Source File @@ -558,10 +546,6 @@ SOURCE=.\import.h # End Source File # Begin Source File -SOURCE=.\pixmap.h -# End Source File -# Begin Source File - SOURCE=.\transform.h # End Source File # Begin Source File diff --git a/graf2d/asimage/src/libAfterImage/libAfterImage.mak b/graf2d/asimage/src/libAfterImage/libAfterImage.mak index a65d11112e675..d6844e6c4c1ed 100644 --- a/graf2d/asimage/src/libAfterImage/libAfterImage.mak +++ b/graf2d/asimage/src/libAfterImage/libAfterImage.mak @@ -2,28 +2,28 @@ !IF "$(CFG)" == "" CFG=libAfterImage - Win32 Debug !MESSAGE No configuration specified. Defaulting to libAfterImage - Win32 Debug. -!ENDIF +!ENDIF !IF "$(CFG)" != "libAfterImage - Win32 Release" && "$(CFG)" != "libAfterImage - Win32 Debug" !MESSAGE Invalid configuration "$(CFG)" specified. !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE +!MESSAGE !MESSAGE NMAKE /f "libAfterImage.mak" CFG="libAfterImage - Win32 Debug" -!MESSAGE +!MESSAGE !MESSAGE Possible choices for configuration are: -!MESSAGE +!MESSAGE !MESSAGE "libAfterImage - Win32 Release" (based on "Win32 (x86) Static Library") !MESSAGE "libAfterImage - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE +!MESSAGE !ERROR An invalid configuration is specified. -!ENDIF +!ENDIF !IF "$(OS)" == "Windows_NT" NULL= -!ELSE +!ELSE NULL=nul -!ENDIF +!ENDIF CPP=cl.exe RSC=rc.exe @@ -47,11 +47,11 @@ DISTCLEAN: CLEAN CPP_PROJ=$(FREETYPEDIRI) /nologo /W3 /O2 /D "WIN32" /D "NDEBUG" /D "NO_DEBUG_OUTPUT" /D "_MBCS" /D "_LIB" /Fp"$(INTDIR)\libAfterImage.pch" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c $(NMAKECXXFLAGS) BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\libAfterImage.bsc" +BSC32_FLAGS=/nologo /o"$(OUTDIR)\libAfterImage.bsc" BSC32_SBRS= \ - + LIB32=link.exe -lib -LIB32_FLAGS=/nologo /out:"libAfterImage.lib" +LIB32_FLAGS=/nologo /out:"libAfterImage.lib" LIB32_OBJS= \ "$(INTDIR)\png.obj" \ "$(INTDIR)\pngerror.obj" \ @@ -126,14 +126,12 @@ LIB32_OBJS= \ "$(INTDIR)\asfont.obj" \ "$(INTDIR)\asimage.obj" \ "$(INTDIR)\asstorage.obj" \ - "$(INTDIR)\asimagexml.obj" \ "$(INTDIR)\asvisual.obj" \ "$(INTDIR)\blender.obj" \ "$(INTDIR)\bmp.obj" \ "$(INTDIR)\char2uni.obj" \ "$(INTDIR)\export.obj" \ "$(INTDIR)\import.obj" \ - "$(INTDIR)\pixmap.obj" \ "$(INTDIR)\transform.obj" \ "$(INTDIR)\ungif.obj" \ "$(INTDIR)\xcf.obj" \ @@ -170,11 +168,11 @@ DISTCLEAN: CLEAN CPP_PROJ=$(FREETYPEDIRI) /nologo /W3 /Gm /ZI /Od /D "WIN32" /D "_DEBUG" /D "NO_DEBUG_OUTPUT" /D "_MBCS" /D "_LIB" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c $(NMAKECXXFLAGS) BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\libAfterImage.bsc" +BSC32_FLAGS=/nologo /o"$(OUTDIR)\libAfterImage.bsc" BSC32_SBRS= \ - + LIB32=link.exe -lib -LIB32_FLAGS=/nologo /out:"$(OUTDIR)\libAfterImage.lib" +LIB32_FLAGS=/nologo /out:"$(OUTDIR)\libAfterImage.lib" LIB32_OBJS= \ "$(INTDIR)\png.obj" \ "$(INTDIR)\pngerror.obj" \ @@ -249,14 +247,12 @@ LIB32_OBJS= \ "$(INTDIR)\asfont.obj" \ "$(INTDIR)\asimage.obj" \ "$(INTDIR)\asstorage.obj" \ - "$(INTDIR)\asimagexml.obj" \ "$(INTDIR)\asvisual.obj" \ "$(INTDIR)\blender.obj" \ "$(INTDIR)\bmp.obj" \ "$(INTDIR)\char2uni.obj" \ "$(INTDIR)\export.obj" \ "$(INTDIR)\import.obj" \ - "$(INTDIR)\pixmap.obj" \ "$(INTDIR)\transform.obj" \ "$(INTDIR)\ungif.obj" \ "$(INTDIR)\xcf.obj" \ @@ -271,46 +267,46 @@ LIB32_OBJS= \ $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) << -!ENDIF +!ENDIF .c{$(INTDIR)}.obj:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< - $(CPP_PROJ) $< + $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("libAfterImage.dep") !INCLUDE "libAfterImage.dep" -!ELSE +!ELSE !MESSAGE Cannot find "libAfterImage.dep" -!ENDIF -!ENDIF +!ENDIF +!ENDIF !IF "$(CFG)" == "libAfterImage - Win32 Release" || "$(CFG)" == "libAfterImage - Win32 Debug" @@ -741,14 +737,11 @@ SOURCE=.\asimage.c "$(INTDIR)\asimage.obj" : $(SOURCE) "$(INTDIR)" + SOURCE=.\asstorage.c "$(INTDIR)\asstorage.obj" : $(SOURCE) "$(INTDIR)" -SOURCE=.\asimagexml.c - -"$(INTDIR)\asimagexml.obj" : $(SOURCE) "$(INTDIR)" - SOURCE=.\asvisual.c @@ -785,13 +778,6 @@ SOURCE=.\import.c "$(INTDIR)\import.obj" : $(SOURCE) "$(INTDIR)" -SOURCE=.\pixmap.c - -"$(INTDIR)\pixmap.obj" : $(SOURCE) "$(INTDIR)" - - -SOURCE=.\transform.c - "$(INTDIR)\transform.obj" : $(SOURCE) "$(INTDIR)" @@ -823,5 +809,5 @@ SOURCE=.\scanline.c "$(INTDIR)\scanline.obj" : $(SOURCE) "$(INTDIR)" -!ENDIF +!ENDIF diff --git a/graf2d/asimage/src/libAfterImage/pixmap.c b/graf2d/asimage/src/libAfterImage/pixmap.c deleted file mode 100644 index 87bbbd4cb9a7b..0000000000000 --- a/graf2d/asimage/src/libAfterImage/pixmap.c +++ /dev/null @@ -1,791 +0,0 @@ -/*--------------------------------*-C-*---------------------------------* - * File: pixmap.c - *----------------------------------------------------------------------* - * Copyright (c) 1999 Ethan Fischer - * Copyright (c) 1999 Sasha Vasko - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - *---------------------------------------------------------------------*/ -/*---------------------------------------------------------------------* - * Originally written: - * 1999 Sasha Vasko - *----------------------------------------------------------------------*/ - -#ifdef _WIN32 -#include "win32/config.h" -#else -#include "config.h" -#endif - -/*#define LOCAL_DEBUG */ -/* #define DO_CLOCKING */ - -#ifdef DO_CLOCKING -#if TIME_WITH_SYS_TIME -# include -# include -#else -# if HAVE_SYS_TIME_H -# include -# else -# include -# endif -#endif -#endif -#ifdef HAVE_UNISTD_H -#include -#endif -#ifdef HAVE_STDLIB_H -#include -#endif -#ifdef HAVE_STDARG_H -#include -#endif - - -#ifdef _WIN32 -# include "win32/afterbase.h" -#else -# include "afterbase.h" -#endif -#include "asvisual.h" -#include "blender.h" -#include "asimage.h" -#include "imencdec.h" -#include "ximage.h" -#include "transform.h" -#include "pixmap.h" - - -/*#define CREATE_TRG_PIXMAP(asv,w,h) XCreatePixmap(dpy, RootWindow(dpy,DefaultScreen(dpy)), (w), (h), DefaultDepth(dpy,DefaultScreen(dpy)))*/ -#define CREATE_TRG_PIXMAP(asv,w,h) create_visual_pixmap(asv,RootWindow(asv->dpy,DefaultScreen(asv->dpy)),(w),(h),0) - - -/**************************************************************************** - * - * fill part of a pixmap with the root pixmap, offset properly to look - * "transparent" - * - ***************************************************************************/ -int -FillPixmapWithTile (Pixmap pixmap, Pixmap tile, int x, int y, int width, int height, int tile_x, int tile_y) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - if (tile != None && pixmap != None) - { - GC gc; - XGCValues gcv; - - gcv.tile = tile; - gcv.fill_style = FillTiled; - gcv.ts_x_origin = -tile_x; - gcv.ts_y_origin = -tile_y; - gc = XCreateGC (dpy, tile, GCFillStyle | GCTile | GCTileStipXOrigin | GCTileStipYOrigin, &gcv); - XFillRectangle (dpy, pixmap, gc, x, y, width, height); - XFreeGC (dpy, gc); - return 1; - } -#endif - return 0; -} - -Pixmap -GetRootPixmap (Atom id) -{ - Pixmap currentRootPixmap = None; -#ifndef X_DISPLAY_MISSING - static Atom root_pmap_atom = None ; - Display *dpy = get_default_asvisual()->dpy; - if (id == None) - { - if( root_pmap_atom == None ) - root_pmap_atom = XInternAtom (dpy, "_XROOTPMAP_ID", True); - id = root_pmap_atom ; - } - - if (id != None) - { - Atom act_type; - int act_format; - unsigned long nitems, bytes_after; - unsigned char *prop = NULL; - -/*fprintf(stderr, "\n aterm GetRootPixmap(): root pixmap is set"); */ - if (XGetWindowProperty ( dpy, RootWindow(dpy,DefaultScreen(dpy)), id, 0, 1, False, XA_PIXMAP, - &act_type, &act_format, &nitems, &bytes_after, - &prop) == Success) - { - if (prop) - { - currentRootPixmap = *((Pixmap *) prop); - XFree (prop); -/*fprintf(stderr, "\n aterm GetRootPixmap(): root pixmap is [%lu]", currentRootPixmap); */ - } - } - } -#endif - return currentRootPixmap; -} - -#ifndef X_DISPLAY_MISSING -static int -pixmap_error_handler (Display * dpy, XErrorEvent * error) -{ -#ifdef DEBUG_IMAGING - show_error ("XError # %u, in resource %lu, Request: %d.%d", - error->error_code, error->resourceid, error->request_code, error->minor_code); -#endif - return 0; -} -#endif - -Pixmap -ValidatePixmap (Pixmap p, int bSetHandler, int bTransparent, unsigned int *pWidth, unsigned int *pHeight) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - int (*oldXErrorHandler) (Display *, XErrorEvent *) = NULL; - /* we need to check if pixmap is still valid */ - Window root; - int junk; - unsigned int ujunk ; - if (bSetHandler) - oldXErrorHandler = XSetErrorHandler (pixmap_error_handler); - - if (bTransparent) - p = GetRootPixmap (None); - if (!pWidth) - pWidth = &ujunk; - if (!pHeight) - pHeight = &ujunk; - - if (p != None) - { - if (!XGetGeometry (dpy, p, &root, &junk, &junk, pWidth, pHeight, &ujunk, &ujunk)) - p = None; - } - if(bSetHandler) - XSetErrorHandler (oldXErrorHandler); - - return p; -#else - return None ; -#endif -} - -int -GetRootDimensions (int *width, int *height) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - if( dpy ) - { - *height = XDisplayHeight(dpy, DefaultScreen(dpy) ); - *width = XDisplayWidth(dpy, DefaultScreen(dpy) ); - } - return 1 ; -#else - return 0; -#endif -} - -int -GetWinPosition (Window w, int *x, int *y) -{ - return get_dpy_window_position( get_default_asvisual()->dpy, None, w, NULL, NULL, x, y ); -} - -ARGB32 -shading2tint32(ShadingInfo * shading) -{ - if( shading && !NO_NEED_TO_SHADE(*shading)) - { - CARD16 r16 = ((shading->tintColor.red*shading->shading / 100)>>9)&0x00FF ; - CARD16 g16 = ((shading->tintColor.green*shading->shading / 100)>>9)&0x00FF ; - CARD16 b16 = ((shading->tintColor.blue*shading->shading / 100)>>9)&0x00FF ; - CARD16 a16 = ((0x0000007F*shading->shading / 100))&0x00FF ; - return MAKE_ARGB32(a16,r16,g16,b16); - } - return TINT_LEAVE_SAME ; -} - -Pixmap -scale_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - - if (src != None) - { - ASImage *src_im ; - src_im = pixmap2ximage(asv, src, 0, 0, src_w, src_h, AllPlanes, 0 ); - if( src_im ) - { - if( src_w != width || src_h != height ) - { - ASImage *tmp = scale_asimage( asv, src_im, width, height, - (tint != TINT_LEAVE_SAME)?ASA_ASImage:ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - destroy_asimage( &src_im ); - src_im = tmp; - } - if( src_im && tint != TINT_LEAVE_SAME ) - { - ASImage *tinted = tile_asimage ( asv, src_im, 0, 0, - width, height, tint, - ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - destroy_asimage( &src_im ); - src_im = tinted ; - } - if( src_im ) - { - trg = asimage2pixmap(asv, None, src_im, gc, True); - destroy_asimage( &src_im ); - } - } - } -#endif - return trg; -} - -Pixmap -ScalePixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading) -{ - Pixmap p = None ; -#ifndef X_DISPLAY_MISSING - p = scale_pixmap( get_default_asvisual(), src, src_w, src_h, width, height, gc, shading2tint32(shading) ); -#endif - return p; -} - - -void -copyshade_drawable_area( ASVisual *asv, Drawable src, Pixmap trg, - int x, int y, int w, int h, - int trg_x, int trg_y, - GC gc, ARGB32 tint) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - if( tint == TINT_LEAVE_SAME || asv == NULL ) - { - XCopyArea (dpy, src, trg, gc, x, y, w, h, trg_x, trg_y); - }else - { - ASImage *src_im = pixmap2ximage( asv, src, x, y, w, h, AllPlanes, 0 ); - if( src_im ) - { - ASImage *tinted = tile_asimage ( asv, src_im, 0, 0, - w, h, tint, - ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - destroy_asimage( &src_im ); - if( tinted ) - { - asimage2drawable( asv, trg, tinted, gc, - 0, 0, trg_x, trg_y, - w, h, True ); - destroy_asimage( &tinted ); - } - } - } -#endif -} - -void -CopyAndShadeArea ( Drawable src, Pixmap trg, - int x, int y, int w, int h, - int trg_x, int trg_y, - GC gc, ShadingInfo * shading) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - ARGB32 tint = shading2tint32( shading ); - - if (x < 0 || y < 0) - return; - - if( tint == TINT_LEAVE_SAME ) - { - XCopyArea (dpy, src, trg, gc, x, y, w, h, trg_x, trg_y); - }else - { - copyshade_drawable_area( get_default_asvisual(), src, trg, x, y, w, h, trg_x, trg_y, gc, tint ); - } -#endif -} - -void -tile_pixmap (ASVisual *asv, Pixmap src, Pixmap trg, int src_w, int src_h, int x, int y, int w, int h, GC gc, ARGB32 tint) -{ -#ifndef X_DISPLAY_MISSING - int tile_x, tile_y, left_w, bott_h; - - tile_x = x % src_w; - tile_y = y % src_h; - left_w = MIN (src_w - tile_x, w); - bott_h = MIN (src_h - tile_y, h); - -/*fprintf( stderr, "\nShadeTiledPixmap(): tile_x = %d, tile_y = %d, left_w = %d, bott_h = %d, SRC = %dx%d TRG=%dx%d", tile_x, tile_y, left_w, bott_h, src_w, src_h, w, h); */ - - /* We don't really want to do simple tile_asimage here since if tint is notint , - * then we could get by with simple XCopyArea !!! - */ - copyshade_drawable_area( asv, src, trg, tile_x, tile_y, left_w, bott_h, 0, 0, gc, tint); - if (bott_h < h) - { /* right-top parts */ - copyshade_drawable_area( asv, src, trg, tile_x, 0, left_w, h - bott_h, 0, bott_h, gc, tint); - } - if (left_w < w) - { /* left-bott parts */ - copyshade_drawable_area( asv, src, trg, 0, tile_y, w - left_w, bott_h, left_w, 0, gc, tint); - if (bott_h < h) /* left-top parts */ - copyshade_drawable_area( asv, src, trg, 0, 0, w - left_w, h - bott_h, left_w, bott_h, gc, tint); - } -#endif -} - -void -ShadeTiledPixmap (Pixmap src, Pixmap trg, int src_w, int src_h, int x, int y, int w, int h, GC gc, ShadingInfo * shading) -{ -#ifndef X_DISPLAY_MISSING - ARGB32 tint = shading2tint32( shading ); - tile_pixmap (get_default_asvisual(), src, trg, src_w, src_h, x, y, w, h, gc, tint); -#endif -} - -Pixmap -shade_pixmap (ASVisual *asv, Pixmap src, int x, int y, int width, int height, GC gc, ARGB32 tint) -{ -#ifndef X_DISPLAY_MISSING - - Pixmap trg = CREATE_TRG_PIXMAP (asv, width, height); - - if (trg != None) - copyshade_drawable_area (asv, src, trg, x, y, width, height, 0, 0, gc, tint); - return trg; -#else - return None ; -#endif -} - -Pixmap -ShadePixmap (Pixmap src, int x, int y, int width, int height, GC gc, ShadingInfo * shading) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - ARGB32 tint = shading2tint32( shading ); - - trg = CREATE_TRG_PIXMAP (get_default_asvisual(), width, height); - if (trg != None) - { - copyshade_drawable_area (get_default_asvisual(), src, trg, x, y, width, height, 0, 0, gc, tint); - } -#endif - return trg; -} - -Pixmap -center_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - - int x, y, w, h, src_x = 0, src_y = 0; - /* create target pixmap of the size of the window */ - trg = CREATE_TRG_PIXMAP (asv,width, height); - if (trg != None) - { - /* fill it with background color */ - XFillRectangle (dpy, trg, gc, 0, 0, width, height); - /* place image at the center of it */ - x = (width - src_w) >> 1; - y = (height - src_h) >> 1; - if (x < 0) - { - src_x -= x; - w = MIN (width, src_w + x); - x = 0; - }else - w = MIN (width, src_w); - if (y < 0) - { - src_y -= y; - h = MIN (height, src_h + y); - y = 0; - }else - h = MIN (height, src_h); - - copyshade_drawable_area ( asv, src, trg, src_x, src_y, w, h, x, y, gc, tint); - } -#endif - return trg; -} - -Pixmap -CenterPixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - ARGB32 tint = shading2tint32( shading ); - - trg = center_pixmap( get_default_asvisual(), src, src_w, src_h, width, height, gc, tint ); -#endif - return trg ; -} - -Pixmap -grow_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint ) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - - int w, h; - /* create target pixmap of the size of the window */ - trg = CREATE_TRG_PIXMAP (asv,width, height); - if (trg != None) - { - /* fill it with background color */ - XFillRectangle (dpy, trg, gc, 0, 0, width, height); - /* place image at the center of it */ - w = MIN (width, src_w); - h = MIN (height, src_h); - - copyshade_drawable_area(asv, src, trg, 0, 0, w, h, 0, 0, gc, tint); - } -#endif - return trg; -} - -Pixmap -GrowPixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading) -{ - Pixmap trg = None; -#ifndef X_DISPLAY_MISSING - ARGB32 tint = shading2tint32( shading ); - - trg = grow_pixmap( get_default_asvisual(), src, src_w, src_h, width, height, gc, tint ); -#endif - return trg ; -} - -/**************************************************************************** - * grab a section of the screen and darken it - ***************************************************************************/ -static Pixmap -cut_pixmap ( ASVisual *asv, Pixmap src, Pixmap trg, - int x, int y, - unsigned int src_w, unsigned int src_h, - unsigned int width, unsigned int height, - GC gc, ARGB32 tint ) -{ -#ifndef X_DISPLAY_MISSING - Display *dpy = get_default_asvisual()->dpy; - - Bool my_pixmap = (trg == None )?True:False ; - int screen_w, screen_h ; - int w = width, h = height; - int offset_x = 0, offset_y = 0; - int screen = DefaultScreen(dpy); - - if (width < 2 || height < 2 ) - return trg; - - screen_w = DisplayWidth( dpy, screen ); - screen_h = DisplayHeight( dpy, screen ); - - while( x+(int)width < 0 ) x+= screen_w ; - while( x >= screen_w ) x-= screen_w ; - while( y+(int)height < 0 ) y+= screen_h ; - while( y >= screen_h ) y-= screen_h ; - - if( x < 0 ) - { - offset_x = (-x); - w -= offset_x ; - x = 0 ; - } - if( y < 0 ) - { - offset_y = (-y) ; - h -= offset_y; - y = 0 ; - } - if( x+w >= screen_w ) - w = screen_w - x ; - - if( y+height >= screen_h ) - h = screen_h - y ; - if( (src_w == 0 || src_h == 0) && src != None ) - { - Window root; - unsigned int dum; - int dummy; - if (!XGetGeometry (dpy, src, &root, &dummy, &dummy, &src_w, &src_h, &dum, &dum)) - src = None ; - } - - if (src == None) /* we don't have root pixmap ID */ - { /* we want to create Overrideredirect window overlapping out window - with background type of Parent Relative and then grab it */ - XSetWindowAttributes attr ; - XEvent event ; - int tick_count = 0 ; - Bool grabbed = False ; - - attr.background_pixmap = ParentRelative ; - attr.backing_store = Always ; - attr.event_mask = ExposureMask ; - attr.override_redirect = True ; - src = create_visual_window(asv, RootWindow(dpy,screen), x, y, w, h, - 0, CopyFromParent, - CWBackPixmap|CWBackingStore|CWOverrideRedirect|CWEventMask, - &attr); - - if( src == None ) return trg ; - XGrabServer( dpy ); - grabbed = True ; - XMapRaised( dpy, src ); - XSync(dpy, False ); - start_ticker(1); - /* now we have to wait for our window to become mapped - waiting for Expose */ - for( tick_count = 0 ; !XCheckWindowEvent( dpy, src, ExposureMask, &event ) && tick_count < 100 ; tick_count++) - wait_tick(); - if( tick_count < 100 ) - { - if( trg == None ) trg = CREATE_TRG_PIXMAP (asv,width, height); - if (trg != None) - { /* custom code to cut area, so to ungrab server ASAP */ - if (tint != TINT_LEAVE_SAME) - { - ASImage *src_im = pixmap2ximage( asv, src, 0, 0, w, h, AllPlanes, 0 ); - XDestroyWindow( dpy, src ); - src = None ; - XUngrabServer( dpy ); - grabbed = False ; - if (src_im != NULL) - { - ASImage *tinted = tile_asimage ( asv, src_im, 0, 0, - w, h, tint, - ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - destroy_asimage( &src_im ); - asimage2drawable( asv, trg, tinted, gc, - 0, 0, offset_x, offset_y, - w, h, True ); - destroy_asimage( &tinted ); - }else if( my_pixmap ) - { - XFreePixmap( dpy, trg ); - trg = None ; - } - }else - XCopyArea (dpy, src, trg, gc, 0, 0, w, h, offset_x, offset_y); - } - } - if( src ) - XDestroyWindow( dpy, src ); - if( grabbed ) - XUngrabServer( dpy ); - return trg ; - } - /* we have root pixmap ID */ - /* find out our coordinates relative to the root window */ - if (x + w > src_w || y + h > src_h) - { /* tiled pixmap processing here */ - Pixmap tmp ; - w = MIN (w, (int)src_w); - h = MIN (h, (int)src_h); - - tmp = CREATE_TRG_PIXMAP (asv, w, h); - if (tmp != None) - { - tile_pixmap (asv, src, tmp, src_w, src_h, x, y, w, h, gc, tint); - if( trg == None ) - { - if( (trg = CREATE_TRG_PIXMAP (asv, w+offset_x, h+offset_y)) != None ) - XCopyArea (dpy, tmp, trg, gc, 0, 0, w, h, offset_x, offset_y); - }else - FillPixmapWithTile( trg, tmp, offset_x, offset_y, width, height, 0, 0 ); - - XFreePixmap( dpy, tmp ); - return trg; - } - } - - /* create target pixmap of the size of the window */ - if( trg == None ) - trg = CREATE_TRG_PIXMAP (asv, width, height); - if (trg != None) - { /* cut area */ - copyshade_drawable_area( asv, src, trg, x, y, w, h, offset_x, offset_y, gc, tint); - } - return trg; -#else - return None ; -#endif -} - -static Pixmap -CutPixmap ( Pixmap src, Pixmap trg, - int x, int y, - unsigned int src_w, unsigned int src_h, - unsigned int width, unsigned int height, - GC gc, ShadingInfo * shading) -{ - Pixmap res = None; -#ifndef X_DISPLAY_MISSING - ARGB32 tint = shading2tint32( shading ); - res = cut_pixmap( get_default_asvisual(), src, trg, x, y, src_w, src_h, width, height, gc, tint ); -#endif - return res ; -} - -Pixmap -cut_win_pixmap (ASVisual *asv, Window win, Drawable src, int src_w, int src_h, int width, - int height, GC gc, ARGB32 tint) -{ - int x = 0, y = 0; - - if (!get_dpy_window_position( asv->dpy, None, win, NULL, NULL, &x, &y)) - return None; - - return cut_pixmap( asv, src, None, x, y, src_w, src_h, width, height, gc, tint ); -} - -Pixmap -CutWinPixmap (Window win, Drawable src, int src_w, int src_h, int width, - int height, GC gc, ShadingInfo * shading) -{ - int x = 0, y = 0; - - if (!get_dpy_window_position( get_default_asvisual()->dpy, None, win, NULL, NULL, &x, &y)) - return None; - - return CutPixmap( src, None, x, y, src_w, src_h, width, height, gc, shading ); -} - -/* PROTO */ -int -fill_with_darkened_background (ASVisual *asv, Pixmap * pixmap, ARGB32 tint, int x, int y, int width, int height, int root_x, int root_y, int bDiscardOriginal, ASImage *root_im) -{ -#ifndef X_DISPLAY_MISSING - unsigned int root_w, root_h; - Pixmap root_pixmap; - Display *dpy = get_default_asvisual()->dpy; - int screen = DefaultScreen(dpy); - - /* added by Sasha on 02/24/1999 to use transparency&shading provided by - libasimage 1.1 */ - root_pixmap = ValidatePixmap (None, 1, 1, &root_w, &root_h); - - if (root_pixmap != None) - { - if (*pixmap == None) - { - *pixmap = create_visual_pixmap(asv, RootWindow (dpy, screen), width, height, 0); - bDiscardOriginal = 1; - } - - if ( tint != TINT_LEAVE_SAME) - { - ASImage *src_im = (root_im == NULL)?pixmap2ximage( asv, root_pixmap, 0, 0, root_w, root_h, AllPlanes, 0 ):root_im; - if( root_im ) - { - ASImage *tinted = tile_asimage ( asv, src_im, -root_x, -root_y, - width, height, tint, - ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - if( root_im != src_im ) - destroy_asimage( &src_im ); - if( tinted ) - { - asimage2drawable( asv, *pixmap, tinted, NULL, - 0, 0, x, y, - width, height, True ); - destroy_asimage( &tinted ); - } - } - }else - FillPixmapWithTile (*pixmap, root_pixmap, x, y, width, height, root_x, root_y); - return 1; - } -#endif - return 0; -} - -/**************************************************************************** - * grab a section of the screen and combine it with an XImage - ***************************************************************************/ -int -fill_with_pixmapped_background (ASVisual *asv, Pixmap * pixmap, ASImage *image, int x, int y, int width, int height, int root_x, int root_y, int bDiscardOriginal, ASImage *root_im) -{ -#ifndef X_DISPLAY_MISSING - unsigned int root_w, root_h; - Pixmap root_pixmap; - int screen = DefaultScreen(asv->dpy); - - root_pixmap = ValidatePixmap (None, 1, 1, &root_w, &root_h); - if (root_pixmap != None) - { - ASImageLayer layers[2]; - ASImage *merged_im ; - - init_image_layers( &layers[0], 2 ); - layers[0].merge_scanlines = allanon_scanlines ; - layers[0].im = root_im ?root_im: - pixmap2ximage( asv, root_pixmap, 0, 0, root_w, root_h, AllPlanes, 0 ); - layers[0].dst_x = x ; - layers[0].dst_y = y ; - layers[0].clip_x = root_x ; - layers[0].clip_y = root_y ; - layers[0].clip_width = width ; - layers[0].clip_height = height ; - - layers[1].im = image ; - layers[1].dst_x = x ; - layers[1].dst_y = y ; - layers[1].clip_x = 0 ; - layers[1].clip_y = 0 ; - layers[1].clip_width = width ; - layers[1].clip_height = height ; - - merged_im = merge_layers( asv, &layers[0], 2, - width, height, - ASA_XImage, - 0, ASIMAGE_QUALITY_DEFAULT ); - if( root_im != layers[0].im ) - destroy_asimage( &(layers[0].im) ); - - if( merged_im ) - { - if (*pixmap == None) - *pixmap = create_visual_pixmap (asv, RootWindow (asv->dpy, screen), width, height, 0); - - asimage2drawable( asv, *pixmap, merged_im, NULL, - 0, 0, x, y, - width, height, True ); - destroy_asimage( &merged_im ); - } - return 1; - } -#endif - return 0; -} -/************************************************/ diff --git a/graf2d/asimage/src/libAfterImage/pixmap.h b/graf2d/asimage/src/libAfterImage/pixmap.h deleted file mode 100644 index 9449c2eac18a5..0000000000000 --- a/graf2d/asimage/src/libAfterImage/pixmap.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef LIBAFTERIMAGE_PIXMAP_H_HEADER_FILE_INCLUDED -#define LIBAFTERIMAGE_PIXMAP_H_HEADER_FILE_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct ShadingInfo -{ - XColor tintColor; - unsigned int shading; -} -ShadingInfo; - -#define NO_NEED_TO_SHADE(o) ((o).shading==100 && (o).tintColor.red==0xFFFF && (o).tintColor.green==0xFFFF && (o).tintColor.blue == 0xFFFF) -int FillPixmapWithTile (Pixmap pixmap, Pixmap tile, int x, int y, int width, int height, int tile_x, int tile_y); -Pixmap GetRootPixmap (Atom id); -Pixmap ValidatePixmap (Pixmap p, int bSetHandler, int bTransparent, unsigned int *pWidth, unsigned int *pHeight); -int GetRootDimensions (int *width, int *height); -int GetWinPosition (Window w, int *x, int *y); -ARGB32 shading2tint32(ShadingInfo * shading); -Pixmap scale_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint); -Pixmap ScalePixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading); -void copyshade_drawable_area( ASVisual *asv, Drawable src, Pixmap trg, - int x, int y, int w, int h, - int trg_x, int trg_y, - GC gc, ARGB32 tint); -void CopyAndShadeArea ( Drawable src, Pixmap trg, - int x, int y, int w, int h, - int trg_x, int trg_y, - GC gc, ShadingInfo * shading); -void tile_pixmap (ASVisual *asv, Pixmap src, Pixmap trg, int src_w, int src_h, int x, int y, int w, int h, GC gc, ARGB32 tint); -void ShadeTiledPixmap (Pixmap src, Pixmap trg, int src_w, int src_h, int x, int y, int w, int h, GC gc, ShadingInfo * shading); -Pixmap shade_pixmap (ASVisual *asv, Pixmap src, int x, int y, int width, int height, GC gc, ARGB32 tint); -Pixmap ShadePixmap (Pixmap src, int x, int y, int width, int height, GC gc, ShadingInfo * shading); -Pixmap center_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint); -Pixmap CenterPixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading); -Pixmap grow_pixmap (ASVisual *asv, Pixmap src, int src_w, int src_h, int width, int height, GC gc, ARGB32 tint ); -Pixmap GrowPixmap (Pixmap src, int src_w, int src_h, int width, int height, GC gc, ShadingInfo * shading); -Pixmap cut_win_pixmap ( ASVisual *asv, Window win, Drawable src, int src_w, int src_h, int width, - int height, GC gc, ARGB32 tint); -Pixmap CutWinPixmap ( Window win, Drawable src, int src_w, int src_h, int width, - int height, GC gc, ShadingInfo * shading); -int fill_with_darkened_background (ASVisual *asv, Pixmap * pixmap, ARGB32 tint, int x, int y, int width, int height, int root_x, int root_y, int bDiscardOriginal, ASImage *root_im); -int fill_with_pixmapped_background (ASVisual *asv, Pixmap * pixmap, ASImage *image, int x, int y, int width, int height, int root_x, int root_y, int bDiscardOriginal, ASImage *root_im); -/************************************************/ - -#ifdef __cplusplus -} -#endif - - -#endif /* #ifndef LIBAFTERIMAGE_PIXMAP_H_HEADER_FILE_INCLUDED */ - diff --git a/graf2d/asimage/src/libAfterImage/ungif.c b/graf2d/asimage/src/libAfterImage/ungif.c index 237aacd1701a3..ddc835af0ad4f 100644 --- a/graf2d/asimage/src/libAfterImage/ungif.c +++ b/graf2d/asimage/src/libAfterImage/ungif.c @@ -188,6 +188,7 @@ get_gif_saved_images( GifFileType *gif, int subimage, SavedImage **ret, int *ret GifByteType *ExtData; #if (GIFLIB_MAJOR>=5) int ExtCode; + size_t Len; #endif SavedImage temp_save; int curr_image = 0, ret_count = *ret_images ; @@ -229,9 +230,10 @@ get_gif_saved_images( GifFileType *gif, int subimage, SavedImage **ret, int *ret { /* Create an extension block with our data */ #if (GIFLIB_MAJOR>=5) - if ((status = GifAddExtensionBlock(&temp_save.ExtensionBlockCount, &temp_save.ExtensionBlocks, - ExtCode, sizeof(ExtData), ExtData)) == GIF_OK) - status = DGifGetExtension(gif,&ExtCode,&ExtData); + Len = EGifGCBToExtension(gif, ExtData); + if ((status = GifAddExtensionBlock(&temp_save.ExtensionBlockCount, &temp_save.ExtensionBlocks, + ExtCode, Len, ExtData)) == GIF_OK) + status = DGifGetExtensionNext(gif, &ExtData); #else if ((status = AddExtensionBlock(&temp_save, ExtData[0], (char*)&(ExtData[1]))) == GIF_OK) status = DGifGetExtensionNext(gif, &ExtData); diff --git a/graf2d/cocoa/inc/TGCocoa.h b/graf2d/cocoa/inc/TGCocoa.h index 0959c3af8bc9d..d181176dc571f 100644 --- a/graf2d/cocoa/inc/TGCocoa.h +++ b/graf2d/cocoa/inc/TGCocoa.h @@ -60,24 +60,24 @@ class TGCocoa : public TVirtualX { TGCocoa(); TGCocoa(const char *name, const char *title); - ~TGCocoa(); + ~TGCocoa() override; //TVirtualX final overriders. //I split them in a group not to get lost in this fat interface. /////////////////////////////////////// //General. - virtual Bool_t Init(void *display); - virtual Int_t OpenDisplay(const char *displayName); - virtual const char *DisplayName(const char *); - virtual Int_t SupportsExtension(const char *extensionName)const; - virtual void CloseDisplay(); - virtual Display_t GetDisplay()const; - virtual Visual_t GetVisual()const; - virtual Int_t GetScreen()const; - virtual UInt_t ScreenWidthMM()const; - virtual Int_t GetDepth()const; - virtual void Update(Int_t mode); + Bool_t Init(void *display) override; + Int_t OpenDisplay(const char *displayName) override; + const char *DisplayName(const char *) override; + Int_t SupportsExtension(const char *extensionName)const override; + void CloseDisplay() override; + Display_t GetDisplay()const override; + Visual_t GetVisual()const override; + Int_t GetScreen()const override; + UInt_t ScreenWidthMM()const override; + Int_t GetDepth()const override; + void Update(Int_t mode) override; //Non-virtual functions. void ReconfigureDisplay(); @@ -87,81 +87,81 @@ class TGCocoa : public TVirtualX { /////////////////////////////////////// //Window management part: - virtual Window_t GetDefaultRootWindow()const; + Window_t GetDefaultRootWindow()const override; //-Functions used by TCanvas/TPad (work with window, selected by SelectWindow). - virtual Int_t InitWindow(ULong_t window); - virtual Window_t GetWindowID(Int_t wid);//TGCocoa simply returns wid. - virtual void SelectWindow(Int_t wid); - virtual void ClearWindow(); - virtual void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); - virtual void MoveWindow(Int_t wid, Int_t x, Int_t y); - virtual void RescaleWindow(Int_t wid, UInt_t w, UInt_t h); - virtual void ResizeWindow(Int_t wid); - virtual void UpdateWindow(Int_t mode); - virtual Window_t GetCurrentWindow()const; - virtual void CloseWindow(); - virtual Int_t AddWindow(ULong_t qwid, UInt_t w, UInt_t h); //-"Qt ROOT". - virtual void RemoveWindow(ULong_t qwid); //-"Qt ROOT". + Int_t InitWindow(ULong_t window) override; + Window_t GetWindowID(Int_t wid) override;//TGCocoa simply returns wid. + void SelectWindow(Int_t wid) override; + void ClearWindow() override; + void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; + void MoveWindow(Int_t wid, Int_t x, Int_t y) override; + void RescaleWindow(Int_t wid, UInt_t w, UInt_t h) override; + void ResizeWindow(Int_t wid) override; + void UpdateWindow(Int_t mode) override; + Window_t GetCurrentWindow()const override; + void CloseWindow() override; + Int_t AddWindow(ULong_t qwid, UInt_t w, UInt_t h) override; //-"Qt ROOT". + void RemoveWindow(ULong_t qwid) override; //-"Qt ROOT". //-Functions used by GUI. - virtual Window_t CreateWindow(Window_t parent, Int_t x, Int_t y, + Window_t CreateWindow(Window_t parent, Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t border, Int_t depth, UInt_t clss, void *visual, SetWindowAttributes_t *attr, - UInt_t wtype); + UInt_t wtype) override; - virtual void DestroyWindow(Window_t wid); - virtual void DestroySubwindows(Window_t wid); + void DestroyWindow(Window_t wid) override; + void DestroySubwindows(Window_t wid) override; - virtual void GetWindowAttributes(Window_t wid, WindowAttributes_t &attr); - virtual void ChangeWindowAttributes(Window_t wid, SetWindowAttributes_t *attr); - virtual void SelectInput(Window_t wid, UInt_t evmask);//Can also be in events-related part. + void GetWindowAttributes(Window_t wid, WindowAttributes_t &attr) override; + void ChangeWindowAttributes(Window_t wid, SetWindowAttributes_t *attr) override; + void SelectInput(Window_t wid, UInt_t evmask) override;//Can also be in events-related part. void ReparentChild(Window_t wid, Window_t pid, Int_t x, Int_t y);//Non-overrider. void ReparentTopLevel(Window_t wid, Window_t pid, Int_t x, Int_t y);//Non-overrider. - virtual void ReparentWindow(Window_t wid, Window_t pid, Int_t x, Int_t y); + void ReparentWindow(Window_t wid, Window_t pid, Int_t x, Int_t y) override; - virtual void MapWindow(Window_t wid); - virtual void MapSubwindows(Window_t wid); - virtual void MapRaised(Window_t wid); - virtual void UnmapWindow(Window_t wid); - virtual void RaiseWindow(Window_t wid); - virtual void LowerWindow(Window_t wid); + void MapWindow(Window_t wid) override; + void MapSubwindows(Window_t wid) override; + void MapRaised(Window_t wid) override; + void UnmapWindow(Window_t wid) override; + void RaiseWindow(Window_t wid) override; + void LowerWindow(Window_t wid) override; - virtual void MoveWindow(Window_t wid, Int_t x, Int_t y); - virtual void MoveResizeWindow(Window_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); - virtual void ResizeWindow(Window_t wid, UInt_t w, UInt_t h); - virtual void IconifyWindow(Window_t wid); - virtual void TranslateCoordinates(Window_t src, Window_t dest, Int_t src_x,Int_t src_y, - Int_t &dest_x, Int_t &dest_y, Window_t &child); - virtual void GetWindowSize(Drawable_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); + void MoveWindow(Window_t wid, Int_t x, Int_t y) override; + void MoveResizeWindow(Window_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void ResizeWindow(Window_t wid, UInt_t w, UInt_t h) override; + void IconifyWindow(Window_t wid) override; + void TranslateCoordinates(Window_t src, Window_t dest, Int_t src_x,Int_t src_y, + Int_t &dest_x, Int_t &dest_y, Window_t &child) override; + void GetWindowSize(Drawable_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; - virtual void SetWindowBackground(Window_t wid, ULong_t color); - virtual void SetWindowBackgroundPixmap(Window_t wid, Pixmap_t pxm); + void SetWindowBackground(Window_t wid, ULong_t color) override; + void SetWindowBackgroundPixmap(Window_t wid, Pixmap_t pxm) override; - virtual Window_t GetParent(Window_t wid)const; + Window_t GetParent(Window_t wid)const override; - virtual void SetWindowName(Window_t wid, char *name); - virtual void SetIconName(Window_t wid, char *name); - virtual void SetIconPixmap(Window_t wid, Pixmap_t pix); - virtual void SetClassHints(Window_t wid, char *className, char *resourceName); + void SetWindowName(Window_t wid, char *name) override; + void SetIconName(Window_t wid, char *name) override; + void SetIconPixmap(Window_t wid, Pixmap_t pix) override; + void SetClassHints(Window_t wid, char *className, char *resourceName) override; //Non-rectangular window: - virtual void ShapeCombineMask(Window_t wid, Int_t x, Int_t y, Pixmap_t mask); + void ShapeCombineMask(Window_t wid, Int_t x, Int_t y, Pixmap_t mask) override; //End window-management part. /////////////////////////////////////// ///////////////////////////// //Set of "Window manager hints". - virtual void SetMWMHints(Window_t winID, UInt_t value, UInt_t decorators, UInt_t inputMode); - virtual void SetWMPosition(Window_t winID, Int_t x, Int_t y); - virtual void SetWMSize(Window_t winID, UInt_t w, UInt_t h); - virtual void SetWMSizeHints(Window_t winID, UInt_t wMin, UInt_t hMin, UInt_t wMax, UInt_t hMax, UInt_t wInc, UInt_t hInc); - virtual void SetWMState(Window_t winID, EInitialState state); - virtual void SetWMTransientHint(Window_t winID, Window_t mainWinID); + void SetMWMHints(Window_t winID, UInt_t value, UInt_t decorators, UInt_t inputMode) override; + void SetWMPosition(Window_t winID, Int_t x, Int_t y) override; + void SetWMSize(Window_t winID, UInt_t w, UInt_t h) override; + void SetWMSizeHints(Window_t winID, UInt_t wMin, UInt_t hMin, UInt_t wMax, UInt_t hMax, UInt_t wInc, UInt_t hInc) override; + void SetWMState(Window_t winID, EInitialState state) override; + void SetWMTransientHint(Window_t winID, Window_t mainWinID) override; //"Window manager hints". ///////////////////////////// @@ -169,24 +169,24 @@ class TGCocoa : public TVirtualX { /////////////////////////////////////// //GUI-rendering part. void DrawLineAux(Drawable_t wid, const GCValues_t &gcVals, Int_t x1, Int_t y1, Int_t x2, Int_t y2);//Non-overrider. - virtual void DrawLine(Drawable_t wid, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2); + void DrawLine(Drawable_t wid, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; void DrawSegmentsAux(Drawable_t wid, const GCValues_t &gcVals, const Segment_t *segments, Int_t nSegments);//Non-overrider. - virtual void DrawSegments(Drawable_t wid, GContext_t gc, Segment_t *segments, Int_t nSegments); + void DrawSegments(Drawable_t wid, GContext_t gc, Segment_t *segments, Int_t nSegments) override; void DrawRectangleAux(Drawable_t wid, const GCValues_t &gcVals, Int_t x, Int_t y, UInt_t w, UInt_t h);//Non-overrider. - virtual void DrawRectangle(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h); + void DrawRectangle(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h) override; void FillRectangleAux(Drawable_t wid, const GCValues_t &gcVals, Int_t x, Int_t y, UInt_t w, UInt_t h);//Non-overrider. - virtual void FillRectangle(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h); + void FillRectangle(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h) override; void FillPolygonAux(Window_t wid, const GCValues_t &gcVals, const Point_t *polygon, Int_t nPoints) ;//Non-overrider. - virtual void FillPolygon(Window_t wid, GContext_t gc, Point_t *polygon, Int_t nPoints); + void FillPolygon(Window_t wid, GContext_t gc, Point_t *polygon, Int_t nPoints) override; void CopyAreaAux(Drawable_t src, Drawable_t dst, const GCValues_t &gc, Int_t srcX, Int_t srcY, UInt_t width, UInt_t height, Int_t dstX, Int_t dstY);//Non-overrider. - virtual void CopyArea(Drawable_t src, Drawable_t dst, GContext_t gc, Int_t srcX, Int_t srcY, UInt_t width, - UInt_t height, Int_t dstX, Int_t dstY); + void CopyArea(Drawable_t src, Drawable_t dst, GContext_t gc, Int_t srcX, Int_t srcY, UInt_t width, + UInt_t height, Int_t dstX, Int_t dstY) override; void DrawStringAux(Drawable_t wid, const GCValues_t &gc, Int_t x, Int_t y, const char *s, Int_t len);//Non-overrider. - virtual void DrawString(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, const char *s, Int_t len); + void DrawString(Drawable_t wid, GContext_t gc, Int_t x, Int_t y, const char *s, Int_t len) override; void ClearAreaAux(Window_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h);//Non-overrider. - virtual void ClearArea(Window_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); - virtual void ClearWindow(Window_t wid); + void ClearArea(Window_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void ClearWindow(Window_t wid) override; //End of GUI-rendering part. /////////////////////////////////////// @@ -194,113 +194,113 @@ class TGCocoa : public TVirtualX { /////////////////////////////////////// //Pixmap management. //-Used by TCanvas/TPad classes: - virtual Int_t OpenPixmap(UInt_t w, UInt_t h); - virtual Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h); - virtual void SelectPixmap(Int_t qpixid); - virtual void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos); - virtual void ClosePixmap(); + Int_t OpenPixmap(UInt_t w, UInt_t h) override; + Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h) override; + void SelectPixmap(Int_t qpixid) override; + void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos) override; + void ClosePixmap() override; //Used by GUI. - virtual Pixmap_t CreatePixmap(Drawable_t wid, UInt_t w, UInt_t h); - virtual Pixmap_t CreatePixmap(Drawable_t wid, const char *bitmap, UInt_t width, UInt_t height, + Pixmap_t CreatePixmap(Drawable_t wid, UInt_t w, UInt_t h) override; + Pixmap_t CreatePixmap(Drawable_t wid, const char *bitmap, UInt_t width, UInt_t height, ULong_t foregroundColor, ULong_t backgroundColor, - Int_t depth); - virtual Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height); - virtual Pixmap_t CreateBitmap(Drawable_t wid, const char *bitmap, - UInt_t width, UInt_t height); + Int_t depth) override; + Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height) override; + Pixmap_t CreateBitmap(Drawable_t wid, const char *bitmap, + UInt_t width, UInt_t height) override; void DeletePixmapAux(Pixmap_t pixmapID);//Non-overrider. - virtual void DeletePixmap(Pixmap_t pixmapID); + void DeletePixmap(Pixmap_t pixmapID) override; //-"Qt ROOT". - virtual Int_t AddPixmap(ULong_t pixid, UInt_t w, UInt_t h); - virtual unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); + Int_t AddPixmap(ULong_t pixid, UInt_t w, UInt_t h) override; + unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; //End of pixmap management. ///////////////////////////// ///////////////////////////// //"Images" - emulation of XCreateImage/XPutImage etc. - virtual Drawable_t CreateImage(UInt_t width, UInt_t height); - virtual void GetImageSize(Drawable_t wid, UInt_t &width, UInt_t &height); - virtual void PutPixel(Drawable_t wid, Int_t x, Int_t y, ULong_t pixel); - virtual void PutImage(Drawable_t wid, GContext_t gc, Drawable_t img, Int_t dx, Int_t dy, - Int_t x, Int_t y, UInt_t w, UInt_t h); - virtual void DeleteImage(Drawable_t img); + Drawable_t CreateImage(UInt_t width, UInt_t height) override; + void GetImageSize(Drawable_t wid, UInt_t &width, UInt_t &height) override; + void PutPixel(Drawable_t wid, Int_t x, Int_t y, ULong_t pixel) override; + void PutImage(Drawable_t wid, GContext_t gc, Drawable_t img, Int_t dx, Int_t dy, + Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void DeleteImage(Drawable_t img) override; //"Images". ///////////////////////////// ///////////////////////////// //Mouse (cursor, events, etc.) - virtual void GrabButton(Window_t wid, EMouseButton button, UInt_t modifier, + void GrabButton(Window_t wid, EMouseButton button, UInt_t modifier, UInt_t evmask, Window_t confine, Cursor_t cursor, - Bool_t grab = kTRUE); - virtual void GrabPointer(Window_t wid, UInt_t evmask, Window_t confine, + Bool_t grab = kTRUE) override; + void GrabPointer(Window_t wid, UInt_t evmask, Window_t confine, Cursor_t cursor, Bool_t grab = kTRUE, - Bool_t owner_events = kTRUE); - virtual void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t);//Noop. + Bool_t owner_events = kTRUE) override; + void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t) override;//Noop. //End of mouse related part. ///////////////////////////// ///////////////////////////// //Keyboard management. - virtual void SetKeyAutoRepeat(Bool_t on = kTRUE); - virtual void GrabKey(Window_t wid, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE); - virtual Int_t KeysymToKeycode(UInt_t keysym); - virtual Window_t GetInputFocus(); - virtual void SetInputFocus(Window_t wid); - virtual void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym); + void SetKeyAutoRepeat(Bool_t on = kTRUE) override; + void GrabKey(Window_t wid, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE) override; + Int_t KeysymToKeycode(UInt_t keysym) override; + Window_t GetInputFocus() override; + void SetInputFocus(Window_t wid) override; + void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym) override; //End of keyboard management. ///////////////////////////// ///////////////////////////// //Font management. - virtual FontStruct_t LoadQueryFont(const char *font_name); - virtual FontH_t GetFontHandle(FontStruct_t fs); - virtual void DeleteFont(FontStruct_t fs); - virtual Bool_t HasTTFonts() const; - virtual Int_t TextWidth(FontStruct_t font, const char *s, Int_t len); - virtual void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent); - virtual FontStruct_t GetFontStruct(FontH_t fh); - virtual void FreeFontStruct(FontStruct_t fs); - virtual char **ListFonts(const char *fontname, Int_t max, Int_t &count); - virtual void FreeFontNames(char **fontlist); + FontStruct_t LoadQueryFont(const char *font_name) override; + FontH_t GetFontHandle(FontStruct_t fs) override; + void DeleteFont(FontStruct_t fs) override; + Bool_t HasTTFonts() const override; + Int_t TextWidth(FontStruct_t font, const char *s, Int_t len) override; + void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent) override; + FontStruct_t GetFontStruct(FontH_t fh) override; + void FreeFontStruct(FontStruct_t fs) override; + char **ListFonts(const char *fontname, Int_t max, Int_t &count) override; + void FreeFontNames(char **fontlist) override; //End of font management. ///////////////////////////// ///////////////////////////// //Color management. - virtual Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color); - virtual Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color); - virtual void QueryColor(Colormap_t cmap, ColorStruct_t &color); - virtual void FreeColor(Colormap_t cmap, ULong_t pixel); - virtual ULong_t GetPixel(Color_t cindex); - virtual void GetPlanes(Int_t &nplanes); - virtual void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b); - virtual void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b); - virtual Colormap_t GetColormap() const; + Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color) override; + Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color) override; + void QueryColor(Colormap_t cmap, ColorStruct_t &color) override; + void FreeColor(Colormap_t cmap, ULong_t pixel) override; + ULong_t GetPixel(Color_t cindex) override; + void GetPlanes(Int_t &nplanes) override; + void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b) override; + void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b) override; + Colormap_t GetColormap() const override; //End of color management. ///////////////////////////// ///////////////////////////// //Context management. - virtual GContext_t CreateGC(Drawable_t wid, GCValues_t *gval); - virtual void SetForeground(GContext_t gc, ULong_t foreground); - virtual void ChangeGC(GContext_t gc, GCValues_t *gval); - virtual void CopyGC(GContext_t org, GContext_t dest, Mask_t mask); - virtual void GetGCValues(GContext_t gc, GCValues_t &gval); - virtual void DeleteGC(GContext_t gc); + GContext_t CreateGC(Drawable_t wid, GCValues_t *gval) override; + void SetForeground(GContext_t gc, ULong_t foreground) override; + void ChangeGC(GContext_t gc, GCValues_t *gval) override; + void CopyGC(GContext_t org, GContext_t dest, Mask_t mask) override; + void GetGCValues(GContext_t gc, GCValues_t &gval) override; + void DeleteGC(GContext_t gc) override; //Context management. ///////////////////////////// ///////////////////////////// //Cursors. - virtual Cursor_t CreateCursor(ECursor cursor); - virtual void SetCursor(Window_t wid, Cursor_t curid); - virtual void SetCursor(Int_t win, ECursor cursor); - virtual void QueryPointer(Int_t &x, Int_t &y); - virtual void QueryPointer(Window_t wid, Window_t &rootw, Window_t &childw, + Cursor_t CreateCursor(ECursor cursor) override; + void SetCursor(Window_t wid, Cursor_t curid) override; + void SetCursor(Int_t win, ECursor cursor) override; + void QueryPointer(Int_t &x, Int_t &y) override; + void QueryPointer(Window_t wid, Window_t &rootw, Window_t &childw, Int_t &root_x, Int_t &root_y, Int_t &win_x, - Int_t &win_y, UInt_t &mask); + Int_t &win_y, UInt_t &mask) override; //Cursors. ///////////////////////////// @@ -308,34 +308,34 @@ class TGCocoa : public TVirtualX { ///////////////////////////// //OpenGL. //We have a mix of Handle_t, Window_t (both are long) and Int_t (this is an obsolete version). - virtual Double_t GetOpenGLScalingFactor(); - virtual Window_t CreateOpenGLWindow(Window_t parentID, UInt_t width, UInt_t height, const std::vector > &format); - virtual Handle_t CreateOpenGLContext(Window_t windowID, Handle_t sharedContext); - virtual void CreateOpenGLContext(Int_t wid); - virtual Bool_t MakeOpenGLContextCurrent(Handle_t ctx, Window_t windowID); - virtual Handle_t GetCurrentOpenGLContext(); - virtual void FlushOpenGLBuffer(Handle_t ctxID); - - virtual void DeleteOpenGLContext(Int_t ctxID); + Double_t GetOpenGLScalingFactor() override; + Window_t CreateOpenGLWindow(Window_t parentID, UInt_t width, UInt_t height, const std::vector > &format) override; + Handle_t CreateOpenGLContext(Window_t windowID, Handle_t sharedContext) override; + void CreateOpenGLContext(Int_t wid) override; + Bool_t MakeOpenGLContextCurrent(Handle_t ctx, Window_t windowID) override; + Handle_t GetCurrentOpenGLContext() override; + void FlushOpenGLBuffer(Handle_t ctxID) override; + + void DeleteOpenGLContext(Int_t ctxID) override; //OpenGL. ///////////////////////////// ///////////////////////////// //TPad's/TCanvas' specific - "double buffer" (off-screen rendering) + 'xor' mode. - virtual void SetDoubleBuffer(Int_t wid, Int_t mode); - virtual void SetDoubleBufferOFF(); - virtual void SetDoubleBufferON(); - virtual void SetDrawMode(EDrawMode mode); + void SetDoubleBuffer(Int_t wid, Int_t mode) override; + void SetDoubleBufferOFF() override; + void SetDoubleBufferON() override; + void SetDrawMode(EDrawMode mode) override; //TPad's/TCanvas'. ///////////////////////////// ///////////////////////////// //Event management. - virtual void SendEvent(Window_t wid, Event_t *ev); - virtual void NextEvent(Event_t &event); - virtual Int_t EventsPending(); - virtual Bool_t CheckEvent(Window_t wid, EGEventType type, Event_t &ev); - virtual Handle_t GetNativeEvent() const; + void SendEvent(Window_t wid, Event_t *ev) override; + void NextEvent(Event_t &event) override; + Int_t EventsPending() override; + Bool_t CheckEvent(Window_t wid, EGEventType type, Event_t &ev) override; + Handle_t GetNativeEvent() const override; //Event management. ///////////////////////////// @@ -343,90 +343,90 @@ class TGCocoa : public TVirtualX { //"Drag and drop" and "Copy and paste" (quotes are intentional :)). //Names here are total mess, but this comes from TVirtualX interface. - virtual Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist); + Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist) override; - virtual void SetPrimarySelectionOwner(Window_t wid); - virtual Bool_t SetSelectionOwner(Window_t windowID, Atom_t &selectionID); - virtual Window_t GetPrimarySelectionOwner(); + void SetPrimarySelectionOwner(Window_t wid) override; + Bool_t SetSelectionOwner(Window_t windowID, Atom_t &selectionID) override; + Window_t GetPrimarySelectionOwner() override; - virtual void ConvertPrimarySelection(Window_t wid, Atom_t clipboard, Time_t when); - virtual void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&); - virtual Int_t GetProperty(Window_t, Atom_t, Long_t, Long_t, Bool_t, Atom_t, - Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**); - virtual void GetPasteBuffer(Window_t wid, Atom_t atom, TString &text, Int_t &nchar, - Bool_t del); + void ConvertPrimarySelection(Window_t wid, Atom_t clipboard, Time_t when) override; + void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&) override; + Int_t GetProperty(Window_t, Atom_t, Long_t, Long_t, Bool_t, Atom_t, + Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**) override; + void GetPasteBuffer(Window_t wid, Atom_t atom, TString &text, Int_t &nchar, + Bool_t del) override; - virtual void ChangeProperty(Window_t wid, Atom_t property, Atom_t type, - UChar_t *data, Int_t len); - virtual void ChangeProperties(Window_t wid, Atom_t property, Atom_t type, - Int_t format, UChar_t *data, Int_t len); - virtual void DeleteProperty(Window_t, Atom_t&); + void ChangeProperty(Window_t wid, Atom_t property, Atom_t type, + UChar_t *data, Int_t len) override; + void ChangeProperties(Window_t wid, Atom_t property, Atom_t type, + Int_t format, UChar_t *data, Int_t len) override; + void DeleteProperty(Window_t, Atom_t&) override; - virtual void SetDNDAware(Window_t, Atom_t *); - virtual Bool_t IsDNDAware(Window_t win, Atom_t *typelist); + void SetDNDAware(Window_t, Atom_t *) override; + Bool_t IsDNDAware(Window_t win, Atom_t *typelist) override; - virtual void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist); + void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist) override; //FindRWindow is in DND part, since it looks for a DND aware window. - virtual Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd); + Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd) override; //"Drag and drop" and "Copy and paste". ///////////////////////////// //The remaining bunch of functions is not sorted yet (and not implemented at the moment). - virtual UInt_t ExecCommand(TGWin32Command *code); - virtual void GetCharacterUp(Float_t &chupx, Float_t &chupy); + UInt_t ExecCommand(TGWin32Command *code) override; + void GetCharacterUp(Float_t &chupx, Float_t &chupy) override; - virtual Int_t GetDoubleBuffer(Int_t wid); + Int_t GetDoubleBuffer(Int_t wid) override; - virtual Pixmap_t ReadGIF(Int_t x0, Int_t y0, const char *file, Window_t wid); - virtual Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y); - virtual Int_t RequestString(Int_t x, Int_t y, char *text); + Pixmap_t ReadGIF(Int_t x0, Int_t y0, const char *file, Window_t wid) override; + Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y) override; + Int_t RequestString(Int_t x, Int_t y, char *text) override; - virtual void SetCharacterUp(Float_t chupx, Float_t chupy); - virtual void SetClipOFF(Int_t wid); - virtual void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); + void SetCharacterUp(Float_t chupx, Float_t chupy) override; + void SetClipOFF(Int_t wid) override; + void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; - virtual void SetTextMagnitude(Float_t mgn); + void SetTextMagnitude(Float_t mgn) override; - virtual void Sync(Int_t mode); - virtual void Warp(Int_t ix, Int_t iy, Window_t wid); - virtual Int_t WriteGIF(char *name); - virtual void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname); + void Sync(Int_t mode) override; + void Warp(Int_t ix, Int_t iy, Window_t wid) override; + Int_t WriteGIF(char *name) override; + void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname) override; - virtual Bool_t NeedRedraw(ULong_t tgwindow, Bool_t force); + Bool_t NeedRedraw(ULong_t tgwindow, Bool_t force) override; - virtual Bool_t CreatePictureFromFile(Drawable_t wid, const char *filename, + Bool_t CreatePictureFromFile(Drawable_t wid, const char *filename, Pixmap_t &pict, Pixmap_t &pict_mask, - PictureAttributes_t &attr); - virtual Bool_t CreatePictureFromData(Drawable_t wid, char **data, + PictureAttributes_t &attr) override; + Bool_t CreatePictureFromData(Drawable_t wid, char **data, Pixmap_t &pict, Pixmap_t &pict_mask, - PictureAttributes_t &attr); - virtual Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data); - virtual void DeletePictureData(void *data); - virtual void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n); - - - virtual void Bell(Int_t percent); - - virtual void WMDeleteNotify(Window_t wid); - - virtual void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n); - virtual Region_t CreateRegion(); - virtual void DestroyRegion(Region_t reg); - virtual void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest); - virtual Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding); - virtual void UnionRegion(Region_t rega, Region_t regb, Region_t result); - virtual void IntersectRegion(Region_t rega, Region_t regb, Region_t result); - virtual void SubtractRegion(Region_t rega, Region_t regb, Region_t result); - virtual void XorRegion(Region_t rega, Region_t regb, Region_t result); - virtual Bool_t EmptyRegion(Region_t reg); - virtual Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg); - virtual Bool_t EqualRegion(Region_t rega, Region_t regb); - virtual void GetRegionBox(Region_t reg, Rectangle_t *rect); + PictureAttributes_t &attr) override; + Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data) override; + void DeletePictureData(void *data) override; + void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n) override; + + + void Bell(Int_t percent) override; + + void WMDeleteNotify(Window_t wid) override; + + void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n) override; + Region_t CreateRegion() override; + void DestroyRegion(Region_t reg) override; + void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest) override; + Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding) override; + void UnionRegion(Region_t rega, Region_t regb, Region_t result) override; + void IntersectRegion(Region_t rega, Region_t regb, Region_t result) override; + void SubtractRegion(Region_t rega, Region_t regb, Region_t result) override; + void XorRegion(Region_t rega, Region_t regb, Region_t result) override; + Bool_t EmptyRegion(Region_t reg) override; + Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg) override; + Bool_t EqualRegion(Region_t rega, Region_t regb) override; + void GetRegionBox(Region_t reg, Rectangle_t *rect) override; // - virtual Bool_t IsCmdThread()const { return kTRUE; } + Bool_t IsCmdThread()const override { return kTRUE; } //Non virtual, non-overriding functions. ROOT::MacOSX::X11::EventTranslator *GetEventTranslator()const; @@ -473,7 +473,7 @@ class TGCocoa : public TVirtualX { TGCocoa(const TGCocoa &rhs); TGCocoa &operator = (const TGCocoa &rhs); - ClassDef(TGCocoa, 0); //TVirtualX for MacOS X. + ClassDefOverride(TGCocoa, 0); //TVirtualX for MacOS X. }; #endif diff --git a/graf2d/cocoa/inc/TGOSXGL.h b/graf2d/cocoa/inc/TGOSXGL.h index 98606f738c23a..80b5f3fc50199 100644 --- a/graf2d/cocoa/inc/TGOSXGL.h +++ b/graf2d/cocoa/inc/TGOSXGL.h @@ -15,37 +15,37 @@ class TGOSXGLManager : public TGLManager { public: TGOSXGLManager(); - ~TGOSXGLManager(); + ~TGOSXGLManager() override; //TGLManager's final-overriders (window + context management): - Int_t InitGLWindow(Window_t winID); - Int_t CreateGLContext(Int_t winInd); - void DeleteGLContext(Int_t devInd); - Bool_t MakeCurrent(Int_t devInd); - void Flush(Int_t ctxInd); + Int_t InitGLWindow(Window_t winID) override; + Int_t CreateGLContext(Int_t winInd) override; + void DeleteGLContext(Int_t devInd) override; + Bool_t MakeCurrent(Int_t devInd) override; + void Flush(Int_t ctxInd) override; //In case of Cocoa 'VirtulXInd' == devInd (again, legacy). - Int_t GetVirtualXInd(Int_t devInd); + Int_t GetVirtualXInd(Int_t devInd) override; //These are empty overriders, we do not have/use off-screen renreding in TCanvas/TPad anymore //(before we had 1) non-hardware glpixmaps/DIB sections and later 2) a hack with double buffer). - Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - void SelectOffScreenDevice(Int_t devInd); - void MarkForDirectCopy(Int_t devInd, Bool_t); - void ExtractViewport(Int_t devInd, Int_t *vp); - void ReadGLBuffer(Int_t devInd); + Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void SelectOffScreenDevice(Int_t devInd) override; + void MarkForDirectCopy(Int_t devInd, Bool_t) override; + void ExtractViewport(Int_t devInd, Int_t *vp) override; + void ReadGLBuffer(Int_t devInd) override; //Used by our OpenGL viewer. //In the past we had to implement this functions to deal with mt-issues on Windows. - Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox); - Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py); - char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py); - void PaintSingleObject(TVirtualGLPainter *); - void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y); - void PrintViewer(TVirtualViewer3D *vv); + Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox) override; + Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + void PaintSingleObject(TVirtualGLPainter *) override; + void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y) override; + void PrintViewer(TVirtualViewer3D *vv) override; - Bool_t HighColorFormat(Int_t /*ctxInd*/){return kFALSE;} + Bool_t HighColorFormat(Int_t /*ctxInd*/) override{return kFALSE;} private: typedef std::map CtxToWindowMap_t; @@ -54,7 +54,7 @@ class TGOSXGLManager : public TGLManager { TGOSXGLManager(const TGOSXGLManager &); TGOSXGLManager &operator = (const TGOSXGLManager &); - ClassDef(TGOSXGLManager, 0) //Cocoa specific version of TGLManager. + ClassDefOverride(TGOSXGLManager, 0) //Cocoa specific version of TGLManager. }; #endif diff --git a/graf2d/cocoa/inc/TGQuartz.h b/graf2d/cocoa/inc/TGQuartz.h index a92ca775e20de..cfe514746e096 100644 --- a/graf2d/cocoa/inc/TGQuartz.h +++ b/graf2d/cocoa/inc/TGQuartz.h @@ -36,47 +36,47 @@ class TGQuartz : public TGCocoa { TGQuartz(const char *name, const char *title); //Final-overriders for TVirtualX. - virtual void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, - EBoxMode mode); - virtual void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, - Int_t nx, Int_t ny, Int_t *ic); - virtual void DrawFillArea(Int_t n, TPoint *xy); + void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, + EBoxMode mode) override; + void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, + Int_t nx, Int_t ny, Int_t *ic) override; + void DrawFillArea(Int_t n, TPoint *xy) override; using TGCocoa::DrawLine;//There is a GUI version of DrawLine. - virtual void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2); - virtual void DrawPolyLine(Int_t n, TPoint *xy); - virtual void DrawPolyMarker(Int_t n, TPoint *xy); - virtual void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, - const char *text, ETextMode mode); - virtual void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, - const wchar_t *text, ETextMode mode); + void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; + void DrawPolyLine(Int_t n, TPoint *xy) override; + void DrawPolyMarker(Int_t n, TPoint *xy) override; + void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, + const char *text, ETextMode mode) override; + void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, + const wchar_t *text, ETextMode mode) override; //I have to override these setters, since they are alredy overriden //in TVirtualX (originally, they are declared in TAttXXX classes) //and do nothing in TVirtualX (though, they are implemented //correctly in TAttXXX classes). - virtual void SetFillColor(Color_t cindex); - virtual void SetFillStyle(Style_t style); - virtual void SetLineColor(Color_t cindex); - virtual void SetLineStyle(Style_t linestyle); - virtual void SetLineWidth(Width_t width); - virtual void SetMarkerColor(Color_t cindex); - virtual void SetMarkerSize(Float_t markersize); - virtual void SetMarkerStyle(Style_t markerstyle); - virtual void SetOpacity(Int_t percent); - virtual void SetTextAlign(Short_t talign=11); - virtual void SetTextColor(Color_t cindex); - virtual void SetTextFont(Font_t fontnumber); - virtual Int_t SetTextFont(char *fontname, ETextSetMode mode); - virtual void SetTextSize(Float_t textsize); - - virtual void GetTextExtent(UInt_t &w, UInt_t &h, char *text); - virtual Int_t GetFontAscent() const; - virtual Int_t GetFontAscent(const char *text) const; - virtual Int_t GetFontDescent() const; - virtual Int_t GetFontDescent(const char *text) const; - virtual Float_t GetTextMagnitude(); + void SetFillColor(Color_t cindex) override; + void SetFillStyle(Style_t style) override; + void SetLineColor(Color_t cindex) override; + void SetLineStyle(Style_t linestyle) override; + void SetLineWidth(Width_t width) override; + void SetMarkerColor(Color_t cindex) override; + void SetMarkerSize(Float_t markersize) override; + void SetMarkerStyle(Style_t markerstyle) override; + void SetOpacity(Int_t percent) override; + void SetTextAlign(Short_t talign=11) override; + void SetTextColor(Color_t cindex) override; + void SetTextFont(Font_t fontnumber) override; + Int_t SetTextFont(char *fontname, ETextSetMode mode) override; + void SetTextSize(Float_t textsize) override; + + void GetTextExtent(UInt_t &w, UInt_t &h, char *text) override; + Int_t GetFontAscent() const override; + Int_t GetFontAscent(const char *text) const override; + Int_t GetFontDescent() const override; + Int_t GetFontDescent(const char *text) const override; + Float_t GetTextMagnitude() override; private: @@ -105,7 +105,7 @@ class TGQuartz : public TGCocoa { TGQuartz(const TGQuartz &rhs); TGQuartz &operator = (const TGQuartz &rhs); - ClassDef(TGQuartz, 0);//2D non-GUI graphics for Mac OSX. + ClassDefOverride(TGQuartz, 0);//2D non-GUI graphics for Mac OSX. }; #endif diff --git a/graf2d/cocoa/src/FontCache.mm b/graf2d/cocoa/src/FontCache.mm index 89e5a177e4ff1..5498b87548dce 100644 --- a/graf2d/cocoa/src/FontCache.mm +++ b/graf2d/cocoa/src/FontCache.mm @@ -417,6 +417,9 @@ void CreateXLFDString(const X11::XLFDName &xlfd, std::string &xlfdString) //______________________________________________________________________________ unsigned FontCache::GetTextWidth(FontStruct_t font, const char *text, int nChars) { + if (nChars == 0) + return 0; + typedef std::vector::size_type size_type; // CTFontRef fontRef = (CTFontRef)font; diff --git a/graf2d/cocoa/src/TGCocoa.mm b/graf2d/cocoa/src/TGCocoa.mm index 08d23771c7149..cd273adba9bd4 100644 --- a/graf2d/cocoa/src/TGCocoa.mm +++ b/graf2d/cocoa/src/TGCocoa.mm @@ -2856,7 +2856,7 @@ void FixAscii(std::vector &text) //______________________________________________________________________________ Int_t TGCocoa::TextWidth(FontStruct_t font, const char *s, Int_t len) { - // Return lenght of the string "s" in pixels. Size depends on font. + // Return length of the string "s" in pixels. Size depends on font. return fPimpl->fFontManager.GetTextWidth(font, s, len); } diff --git a/graf2d/fitsio/inc/TFITS.h b/graf2d/fitsio/inc/TFITS.h index 7abc9c434ecc6..9797ae66838aa 100644 --- a/graf2d/fitsio/inc/TFITS.h +++ b/graf2d/fitsio/inc/TFITS.h @@ -105,13 +105,13 @@ class TFITSHDU : public TNamed { TFITSHDU(const char *filepath_with_filter); TFITSHDU(const char *filepath, Int_t extension_number); TFITSHDU(const char *filepath, const char *extension_name); - ~TFITSHDU(); + ~TFITSHDU() override; //Metadata access methods Int_t GetRecordNumber() const { return fNRecords; } struct HDURecord *GetRecord(const char *keyword); TString& GetKeywordValue(const char *keyword); - void Print(const Option_t *opt="") const; + void Print(const Option_t *opt="") const override; //Image readers TH1 *ReadAsHistogram(); @@ -137,12 +137,12 @@ class TFITSHDU : public TNamed { TArrayD *GetTabVarLengthVectorCell(Int_t rownum, const char *colname); //Misc - void Draw(Option_t *opt=""); + void Draw(Option_t *opt="") override; Bool_t Change(const char *filter); Bool_t Change(Int_t extension_number); - ClassDef(TFITSHDU,0) // Class interfacing FITS HDUs + ClassDefOverride(TFITSHDU,0) // Class interfacing FITS HDUs }; diff --git a/graf2d/gpad/CMakeLists.txt b/graf2d/gpad/CMakeLists.txt index 18a1c24dc2d87..016fecfa28c50 100644 --- a/graf2d/gpad/CMakeLists.txt +++ b/graf2d/gpad/CMakeLists.txt @@ -11,6 +11,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Gpad HEADERS + TAnnotation.h TAttCanvas.h TButton.h TCanvas.h @@ -31,6 +32,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Gpad TViewer3DPad.h TView.h SOURCES + src/TAnnotation.cxx src/TAttCanvas.cxx src/TButton.cxx src/TCanvas.cxx diff --git a/graf2d/gpad/inc/LinkDef.h b/graf2d/gpad/inc/LinkDef.h index eb6d25849948d..954ebcf402a08 100644 --- a/graf2d/gpad/inc/LinkDef.h +++ b/graf2d/gpad/inc/LinkDef.h @@ -14,6 +14,7 @@ #pragma link off all classes; #pragma link off all functions; +#pragma link C++ class TAnnotation+; #pragma link C++ class TAttCanvas+; #pragma link C++ class TButton+; #pragma link C++ class TCanvas-; diff --git a/graf2d/gpad/inc/TAnnotation.h b/graf2d/gpad/inc/TAnnotation.h new file mode 100644 index 0000000000000..62786c441860a --- /dev/null +++ b/graf2d/gpad/inc/TAnnotation.h @@ -0,0 +1,40 @@ +// @(#)root/gpad:$Id$ +// Author: Olivier Couet 03/05/23 + +/************************************************************************* + * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#ifndef ROOT_TAnnotation +#define ROOT_TAnnotation + + +#include "TLatex.h" + +class TAnnotation : public TLatex { + +protected: + double fZ{0}; ///< Z position of text + +public: + + TAnnotation() {} + TAnnotation(Double_t x, Double_t y, Double_t z, const char *text); + ~TAnnotation() override; + virtual TAnnotation *DrawAnnotation(Double_t x, Double_t y, Double_t z, const char *text); + void ls(Option_t *option="") const override; + void Paint(Option_t *option="") override; + void PaintAnnotation(Double_t x, Double_t y, Double_t z, Double_t angle, Double_t size, const Char_t *text); + void Print(Option_t *option="") const override; + + void SetZ(double z) { fZ = z; } // *MENU* + double GetZ() const { return fZ; } + + ClassDefOverride(TAnnotation,1) //Annotation in 2d or 3D +}; + +#endif diff --git a/graf2d/gpad/inc/TButton.h b/graf2d/gpad/inc/TButton.h index 465adc4e7435d..97fb39062c7a2 100644 --- a/graf2d/gpad/inc/TButton.h +++ b/graf2d/gpad/inc/TButton.h @@ -30,7 +30,7 @@ class TButton : public TPad, public TAttText { public: TButton(); TButton(const char *title, const char *method, Double_t x1, Double_t y1, Double_t x2, Double_t y2); - virtual ~TButton(); + ~TButton() override; void Divide(Int_t = 1, Int_t = 1, Float_t = 0.01, Float_t = 0.01, Int_t = 0) override {} void Draw(Option_t *option = "") override; void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; diff --git a/graf2d/gpad/inc/TCanvas.h b/graf2d/gpad/inc/TCanvas.h index 9f39fe8209312..f000528fa0867 100644 --- a/graf2d/gpad/inc/TCanvas.h +++ b/graf2d/gpad/inc/TCanvas.h @@ -61,6 +61,7 @@ friend class TInterpreter; Bool_t fRetained; ///< Retain structure flag Bool_t fUseGL; ///& = {}, const char *filename = "", Option_t *option = ""); + ClassDefOverride(TCanvas,8) //Graphics canvas }; diff --git a/graf2d/gpad/inc/TClassTree.h b/graf2d/gpad/inc/TClassTree.h index 098d349d0a69e..c42a76b92ae58 100644 --- a/graf2d/gpad/inc/TClassTree.h +++ b/graf2d/gpad/inc/TClassTree.h @@ -59,7 +59,7 @@ class TClassTree : public TNamed { public: TClassTree(); TClassTree(const char *name, const char *classes=""); - virtual ~TClassTree(); + ~TClassTree() override; void Draw(const char *classes ="") override; virtual Int_t FindClass(const char *classname); const char *GetClasses() const {return fClasses.Data();} diff --git a/graf2d/gpad/inc/TColorWheel.h b/graf2d/gpad/inc/TColorWheel.h index 81d2f3455688e..3b15b3c1ebdc8 100644 --- a/graf2d/gpad/inc/TColorWheel.h +++ b/graf2d/gpad/inc/TColorWheel.h @@ -51,7 +51,7 @@ class TColorWheel : public TNamed { public: TColorWheel(); - virtual ~TColorWheel(); + ~TColorWheel() override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; void Draw(Option_t *option = "") override; TCanvas *GetCanvas() const { return fCanvas; } diff --git a/graf2d/gpad/inc/TControlBar.h b/graf2d/gpad/inc/TControlBar.h index 403fceca138a3..da4da8fdef4c5 100644 --- a/graf2d/gpad/inc/TControlBar.h +++ b/graf2d/gpad/inc/TControlBar.h @@ -44,7 +44,7 @@ friend class TControlBarImp; TControlBar(); TControlBar(const char *orientation, const char *title = ""); TControlBar(const char *orientation, const char *title, Int_t x, Int_t y); - virtual ~TControlBar(); + ~TControlBar() override; void AddButton(TControlBarButton *button); void AddButton(TControlBarButton &button); diff --git a/graf2d/gpad/inc/TControlBarButton.h b/graf2d/gpad/inc/TControlBarButton.h index 2dcb6d1afdd6e..7449446db124e 100644 --- a/graf2d/gpad/inc/TControlBarButton.h +++ b/graf2d/gpad/inc/TControlBarButton.h @@ -25,7 +25,7 @@ class TControlBarButton : public TNamed { TControlBarButton(); TControlBarButton(const char *label, const char *action="", const char *hint="", const char *type="button"); - virtual ~TControlBarButton() {} + ~TControlBarButton() override {} virtual void Create() {} virtual void Action(); diff --git a/graf2d/gpad/inc/TDialogCanvas.h b/graf2d/gpad/inc/TDialogCanvas.h index 51048d4e85049..42b5bdc9af0be 100644 --- a/graf2d/gpad/inc/TDialogCanvas.h +++ b/graf2d/gpad/inc/TDialogCanvas.h @@ -30,7 +30,7 @@ class TDialogCanvas : public TCanvas, public TAttText { TDialogCanvas(); TDialogCanvas(const char *name, const char *title, Int_t ww, Int_t wh); TDialogCanvas(const char *name, const char *title, Int_t wtopx, Int_t wtopy, UInt_t ww, UInt_t wh); - virtual ~TDialogCanvas(); + ~TDialogCanvas() override; virtual void Apply(const char *action=""); virtual void BuildStandardButtons(); void Divide(Int_t nx=1, Int_t ny=1, Float_t xmargin=0.01, Float_t ymargin=0.01, Int_t color=0) override; diff --git a/graf2d/gpad/inc/TGroupButton.h b/graf2d/gpad/inc/TGroupButton.h index 7b8723d30f58f..ffd696a38450d 100644 --- a/graf2d/gpad/inc/TGroupButton.h +++ b/graf2d/gpad/inc/TGroupButton.h @@ -23,7 +23,7 @@ class TGroupButton : public TButton { public: TGroupButton(); TGroupButton(const char *groupname, const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2 ,Double_t y2); - virtual ~TGroupButton(); + ~TGroupButton() override; virtual void DisplayColorTable(const char *action, Double_t x0, Double_t y0, Double_t wc, Double_t hc); virtual void ExecuteAction(); void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; diff --git a/graf2d/gpad/inc/TInspectCanvas.h b/graf2d/gpad/inc/TInspectCanvas.h index c6f7299023f17..cd83df8306c4f 100644 --- a/graf2d/gpad/inc/TInspectCanvas.h +++ b/graf2d/gpad/inc/TInspectCanvas.h @@ -30,7 +30,7 @@ class TInspectCanvas : public TCanvas, public TAttText { public: TInspectCanvas(); TInspectCanvas(UInt_t ww, UInt_t wh); - virtual ~TInspectCanvas(); + ~TInspectCanvas() override; TButton *GetBackward() const { return fBackward; } TButton *GetForward() const { return fForward; } TObject *GetCurObject() const { return fCurObject; } diff --git a/graf2d/gpad/inc/TPad.h b/graf2d/gpad/inc/TPad.h index 09261511aa652..a11549a0f34f3 100644 --- a/graf2d/gpad/inc/TPad.h +++ b/graf2d/gpad/inc/TPad.h @@ -163,7 +163,7 @@ friend class TWebCanvas; TPad(const char *name, const char *title, Double_t xlow, Double_t ylow, Double_t xup, Double_t yup, Color_t color=-1, Short_t bordersize=-1, Short_t bordermode=-2); - virtual ~TPad(); + ~TPad() override; void AbsCoordinates(Bool_t set) override { fAbsCoord = set; } Double_t AbsPixeltoX(Int_t px) override { return fAbsPixeltoXk + px*fPixeltoX; } Double_t AbsPixeltoY(Int_t py) override { return fAbsPixeltoYk + py*fPixeltoY; } @@ -267,7 +267,7 @@ friend class TWebCanvas; void HighLight(Color_t col=kRed, Bool_t set=kTRUE) override; Bool_t HasFixedAspectRatio() const override { return fFixedAspectRatio; } Bool_t IsBatch() const override; - virtual Bool_t IsEditable() const override { return fEditable; } + Bool_t IsEditable() const override { return fEditable; } Bool_t IsFolder() const override { return kTRUE; } Bool_t IsModified() const override { return fModified; } Bool_t IsRetained() const override; @@ -363,6 +363,8 @@ friend class TWebCanvas; void ShowGuidelines(TObject *object, const Int_t event, const char mode = 'i', const bool cling = true) override; void Update() override; + void UpdateAsync() override; + Int_t UtoAbsPixel(Double_t u) const override { return Int_t(fUtoAbsPixelk + u*fUtoPixel); } Int_t VtoAbsPixel(Double_t v) const override { return Int_t(fVtoAbsPixelk + v*fVtoPixel); } Int_t UtoPixel(Double_t u) const override; @@ -386,7 +388,7 @@ friend class TWebCanvas; Int_t NextPaletteColor() override; void DrawCollideGrid(); - Bool_t PlaceBox(TObject *o, Double_t w, Double_t h, Double_t &xl, Double_t &yb) override; + Bool_t PlaceBox(TObject *o, Double_t w, Double_t h, Double_t &xl, Double_t &yb, Option_t* option = "lb") override; virtual void x3d(Option_t *type=""); // Depreciated diff --git a/graf2d/gpad/inc/TPaveClass.h b/graf2d/gpad/inc/TPaveClass.h index 77f129e461574..bdbe7a2e58104 100644 --- a/graf2d/gpad/inc/TPaveClass.h +++ b/graf2d/gpad/inc/TPaveClass.h @@ -29,7 +29,7 @@ class TPaveClass : public TPaveLabel { TPaveClass(); TPaveClass(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, const char *label, TClassTree *classtree); TPaveClass(const TPaveClass &PaveVar); - virtual ~TPaveClass(); + ~TPaveClass() override; void Copy(TObject &PaveVar) const override; virtual void DrawClasses(const char *classes="this"); // *MENU* diff --git a/graf2d/gpad/inc/TRatioPlot.h b/graf2d/gpad/inc/TRatioPlot.h index bbb64b2ecad44..c4ced1c381486 100644 --- a/graf2d/gpad/inc/TRatioPlot.h +++ b/graf2d/gpad/inc/TRatioPlot.h @@ -156,7 +156,7 @@ class TRatioPlot : public TObject { public: TRatioPlot(); - virtual ~TRatioPlot(); + ~TRatioPlot() override; TRatioPlot(TH1* h1, TH1* h2, Option_t *option = "pois"); TRatioPlot(THStack* st, TH1* h2, Option_t *option = "pois"); diff --git a/graf2d/gpad/inc/TSlider.h b/graf2d/gpad/inc/TSlider.h index 507d6c1977ce3..0b2d004076bed 100644 --- a/graf2d/gpad/inc/TSlider.h +++ b/graf2d/gpad/inc/TSlider.h @@ -29,7 +29,7 @@ class TSlider : public TPad { public: TSlider(); TSlider(const char *name, const char *title, Double_t x1, Double_t y1, Double_t x2, Double_t y2, Color_t color=16, Short_t bordersize=2, Short_t bordermode =-1); - virtual ~TSlider(); + ~TSlider() override; TObject *GetObject() const { return fObject; } Double_t GetMinimum() const { return fMinimum; } Double_t GetMaximum() const { return fMaximum; } diff --git a/graf2d/gpad/inc/TSliderBox.h b/graf2d/gpad/inc/TSliderBox.h index 4ca152581bd45..4942f865a7e92 100644 --- a/graf2d/gpad/inc/TSliderBox.h +++ b/graf2d/gpad/inc/TSliderBox.h @@ -32,7 +32,7 @@ class TSliderBox : public TWbox { TSliderBox(); TSliderBox(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, Color_t color=18, Short_t bordersize=2 ,Short_t bordermode=-1); - virtual ~TSliderBox(); + ~TSliderBox() override; void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; void SavePrimitive(std::ostream &out, Option_t *option = "") override; void SetSlider(TSlider*slider) { fSlider=slider; } diff --git a/graf2d/gpad/inc/TView.h b/graf2d/gpad/inc/TView.h index 23b3a753c569e..8f754da617d4c 100644 --- a/graf2d/gpad/inc/TView.h +++ b/graf2d/gpad/inc/TView.h @@ -27,7 +27,7 @@ class TView : public TObject, public TAttLine { public: TView() {} // NOLINT: not allowed to use = default because of TObject::kIsOnHeap detection, see ROOT-10300 - virtual ~TView() = default; + ~TView() override = default; virtual void DefinePerspectiveView() = 0; virtual void AxisVertex(Double_t ang, Double_t *av, Int_t &ix1, Int_t &ix2, Int_t &iy1, Int_t &iy2, Int_t &iz1, Int_t &iz2) = 0; diff --git a/graf2d/gpad/inc/TViewer3DPad.h b/graf2d/gpad/inc/TViewer3DPad.h index 9b81d799e5702..30933decb6ae0 100644 --- a/graf2d/gpad/inc/TViewer3DPad.h +++ b/graf2d/gpad/inc/TViewer3DPad.h @@ -27,7 +27,7 @@ class TViewer3DPad : public TVirtualViewer3D { public: TViewer3DPad(TVirtualPad & pad) : fPad(pad), fBuilding(kFALSE) {}; - ~TViewer3DPad() {}; + ~TViewer3DPad() override {}; Bool_t PreferLocalFrame() const override; void BeginScene() override; diff --git a/graf2d/gpad/src/TAnnotation.cxx b/graf2d/gpad/src/TAnnotation.cxx new file mode 100644 index 0000000000000..22e39a5009d89 --- /dev/null +++ b/graf2d/gpad/src/TAnnotation.cxx @@ -0,0 +1,134 @@ +// @(#)root/gpad:$Id$ +// Author: Olivier Couet 03/05/23 + +/************************************************************************* + * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include "TROOT.h" +#include "TAnnotation.h" +#include "TVirtualPad.h" +#include "TView.h" +#include "TVirtualViewer3D.h" + + +ClassImp(TAnnotation); + +/** \class TAnnotation +\ingroup gpad + +An annotation is a TLatex which can be drawn in a 2D or 3D space. + +Example: + +Begin_Macro(source) +{ + auto hsurf1 = new TH2F("hsurf1","3D text example ",30,-4,4,30,-20,20); + float px, py; + for (Int_t i = 0; i < 25000; i++) { + gRandom->Rannor(px,py); + hsurf1->Fill(px-1,5*py); + hsurf1->Fill(2+0.5*px,2*py-10.,0.1); + } + hsurf1->Draw("SURF1"); + int binx,biny,binz; + int bmax = hsurf1->GetMaximumBin(binx,biny,binz); + double xm = hsurf1->GetXaxis()->GetBinCenter(binx); + double ym = hsurf1->GetYaxis()->GetBinCenter(biny); + double zm = hsurf1->GetMaximum(); + auto t = new TAnnotation(xm,ym,zm,Form("Maximum = %g",zm)); + t->SetTextFont(42); + t->SetTextSize(0.03); + t->Draw(); +} +End_Macro + +Another example: + +Begin_Macro(source) +../../../tutorials/graphs/annotation3d.C +End_Macro +*/ + +//////////////////////////////////////////////////////////////////////////////// +/// annotation default constructor. + +TAnnotation::TAnnotation(Double_t x, Double_t y, Double_t z, const char *text) +{ + fX = x; + fY = y; + fZ = z; + fTitle = text; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// annotation default destructor. + + +TAnnotation::~TAnnotation() +{ +} + +//////////////////////////////////////////////////////////////////////////////// +/// List this annotation with its attributes. + +void TAnnotation::ls(Option_t *) const +{ + TROOT::IndentLevel(); + printf("OBJ: %s\t%s \tX= %f Y=%f Z=%f \n",IsA()->GetName(),GetTitle(),fX,fY,fZ); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Draw this annotation with new coordinates. + +TAnnotation *TAnnotation::DrawAnnotation(Double_t x, Double_t y, Double_t z, const char *text) +{ + TAnnotation *newannotation = new TAnnotation(x, y, z, text); + TAttText::Copy(*newannotation); + newannotation->SetBit(kCanDelete); + if (TestBit(kTextNDC)) newannotation->SetNDC(); + newannotation->AppendPad(); + return newannotation; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Paint this annotation with new coordinates. + +void TAnnotation::PaintAnnotation(Double_t x, Double_t y, Double_t z, Double_t angle, Double_t size, const Char_t *text) +{ + TView *view = gPad->GetView(); + if (!view) { + PaintLatex(x, y, angle, size, text); + } else { + Double_t xyz[3] = { x, y, z }, xpad[3]; + view->WCtoNDC(xyz, &xpad[0]); + PaintLatex(xpad[0], xpad[1], angle, size, text); + } +} + +//////////////////////////////////////////////////////////////////////////////// +/// Paint a TAnnotation. + +void TAnnotation::Paint(Option_t * /* option */ ) +{ + PaintAnnotation(fX, fY, fZ, GetTextAngle(),GetTextSize(),GetTitle()); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Dump this annotation with its attributes. + +void TAnnotation::Print(Option_t *) const +{ + printf("Annotation X=%f Y=%f Z = %f Text=%s Font=%d Size=%f",fX,fY,fZ,GetTitle(),GetTextFont(),GetTextSize()); + if (GetTextColor() != 1 ) printf(" Color=%d",GetTextColor()); + if (GetTextAlign() != 10) printf(" Align=%d",GetTextAlign()); + if (GetTextAngle() != 0 ) printf(" Angle=%f",GetTextAngle()); + printf("\n"); +} diff --git a/graf2d/gpad/src/TCanvas.cxx b/graf2d/gpad/src/TCanvas.cxx index 9baf71658026b..0585d86960f42 100644 --- a/graf2d/gpad/src/TCanvas.cxx +++ b/graf2d/gpad/src/TCanvas.cxx @@ -32,6 +32,7 @@ #include "TInterpreter.h" #include "TApplication.h" #include "TColor.h" +#include "TSystem.h" #include "TObjArray.h" #include "TVirtualPadEditor.h" #include "TVirtualViewer3D.h" @@ -161,6 +162,7 @@ TCanvas::TCanvas(Bool_t build) : TPad(), fDoubleBuffer(0) fSelectedY = 0; fRetained = kTRUE; fDrawn = kFALSE; + fUpdated = kFALSE; fSelected = nullptr; fClickSelected = nullptr; fSelectedPad = nullptr; @@ -320,21 +322,20 @@ void TCanvas::Constructor(const char *name, const char *title, Int_t form) fBatch = kTRUE; } else { //normal mode with a screen window Float_t cx = gStyle->GetScreenFactor(); - if (form < 1 || form > 5) form = 1; + if (form < 1 || form > 20) form = 1; auto factory = gROOT->IsWebDisplay() ? gBatchGuiFactory : gGuiFactory; + Int_t ux, uy, cw, ch; if (form == 1) { - UInt_t uh = UInt_t(cx*gStyle->GetCanvasDefH()); - UInt_t uw = UInt_t(cx*gStyle->GetCanvasDefW()); - Int_t ux = Int_t(cx*gStyle->GetCanvasDefX()); - Int_t uy = Int_t(cx*gStyle->GetCanvasDefY()); - fCanvasImp = factory->CreateCanvasImp(this, name, ux, uy, uw, uh); + cw = gStyle->GetCanvasDefW(); + ch = gStyle->GetCanvasDefH(); + ux = gStyle->GetCanvasDefX(); + uy = gStyle->GetCanvasDefY(); + } else { + cw = ch = 500; + ux = uy = form * 10; } - fCw = 500; - fCh = 500; - if (form == 2) fCanvasImp = factory->CreateCanvasImp(this, name, 20, 20, UInt_t(cx*500), UInt_t(cx*500)); - if (form == 3) fCanvasImp = factory->CreateCanvasImp(this, name, 30, 30, UInt_t(cx*500), UInt_t(cx*500)); - if (form == 4) fCanvasImp = factory->CreateCanvasImp(this, name, 40, 40, UInt_t(cx*500), UInt_t(cx*500)); - if (form == 5) fCanvasImp = factory->CreateCanvasImp(this, name, 50, 50, UInt_t(cx*500), UInt_t(cx*500)); + + fCanvasImp = factory->CreateCanvasImp(this, name, Int_t(cx*ux), Int_t(cx*uy), UInt_t(cx*cw), UInt_t(cx*ch)); if (!fCanvasImp) return; if (!gROOT->IsBatch() && fCanvasID == -1) @@ -574,6 +575,7 @@ void TCanvas::Init() fEventY = -1; fContextMenu = nullptr; fDrawn = kFALSE; + fUpdated = kFALSE; } //////////////////////////////////////////////////////////////////////////////// @@ -601,7 +603,7 @@ void TCanvas::Build() fCw -= 4; fCh -= 28; } else if (IsWeb()) { - // mark canvas as batch - avoid virtualx in many places + // mark canvas as batch - avoid gVirtualX in many places SetBatch(kTRUE); } else { //normal mode with a screen window @@ -718,10 +720,9 @@ TVirtualPad *TCanvas::cd(Int_t subpadnumber) TPad::cd(subpadnumber); // in case doublebuffer is off, draw directly onto display window - if (!IsBatch()) { - if (!fDoubleBuffer) - gVirtualX->SelectWindow(fCanvasID);//Ok, does not matter for glpad. - } + if (!IsBatch() && !IsWeb() && !fDoubleBuffer) + gVirtualX->SelectWindow(fCanvasID);//Ok, does not matter for glpad. + return gPad; } @@ -788,7 +789,7 @@ void TCanvas::Close(Option_t *option) if (fCanvasID != -1) { - if ((!gROOT->IsLineProcessing()) && (!gVirtualX->IsCmdThread())) { + if (!gROOT->IsLineProcessing() && !gVirtualX->IsCmdThread()) { gInterpreter->Execute(this, IsA(), "Close", option); return; } @@ -800,7 +801,7 @@ void TCanvas::Close(Option_t *option) cd(); TPad::Close(option); - if (!IsBatch()) { + if (!IsBatch() && !IsWeb()) { gVirtualX->SelectWindow(fCanvasID); //select current canvas DeleteCanvasPainter(); @@ -859,7 +860,12 @@ void TCanvas::Draw(Option_t *) TCanvas *old = (TCanvas*)gROOT->GetListOfCanvases()->FindObject(GetName()); if (old == this) { - Paint(); + if (IsWeb()) { + Modified(); + UpdateAsync(); + } else { + Paint(); + } return; } if (old) { gROOT->GetListOfCanvases()->Remove(old); delete old;} @@ -1119,6 +1125,9 @@ void TCanvas::ExecuteEvent(Int_t event, Int_t px, Int_t py) void TCanvas::FeedbackMode(Bool_t set) { + if (IsWeb()) + return; + if (set) { SetDoubleBuffer(0); // turn off double buffer mode gVirtualX->SetDrawMode(TVirtualX::kInvert); // set the drawing mode to XOR mode @@ -1173,7 +1182,7 @@ void TCanvas::ForceUpdate() void TCanvas::UseCurrentStyle() { - if ((!gROOT->IsLineProcessing()) && (!gVirtualX->IsCmdThread())) { + if (!gROOT->IsLineProcessing() && !gVirtualX->IsCmdThread()) { gInterpreter->Execute(this, IsA(), "UseCurrentStyle", ""); return; } @@ -1302,7 +1311,8 @@ void TCanvas::HandleInput(EEventType event, Int_t px, Int_t py) gPad = fSelectedPad; fSelected->ExecuteEvent(event, px, py); - gVirtualX->Update(); + if (!IsWeb()) + gVirtualX->Update(); if (fSelected && !fSelected->InheritsFrom(TAxis::Class())) { Bool_t resize = kFALSE; if (fSelected->InheritsFrom(TBox::Class())) @@ -1657,7 +1667,7 @@ void TCanvas::Resize(Option_t *) { if (fCanvasID == -1) return; - if ((!gROOT->IsLineProcessing()) && (!gVirtualX->IsCmdThread())) { + if (!gROOT->IsLineProcessing() && !gVirtualX->IsCmdThread()) { gInterpreter->Execute(this, IsA(), "Resize", ""); return; } @@ -1666,7 +1676,7 @@ void TCanvas::Resize(Option_t *) TContext ctxt(this, kTRUE); - if (!IsBatch()) { + if (!IsBatch() && !IsWeb()) { gVirtualX->SelectWindow(fCanvasID); //select current canvas gVirtualX->ResizeWindow(fCanvasID); //resize canvas and off-screen buffer @@ -1807,7 +1817,7 @@ void TCanvas::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) /// The precision can be changed (via system.rootrc) by changing the value /// of the environment variable "Canvas.SavePrecision" -void TCanvas::SaveSource(const char *filename, Option_t *option) +void TCanvas::SaveSource(const char *filename, Option_t * /*option*/) { // reset bit TClass::kClassSaved for all classes TIter next(gROOT->GetListOfClasses()); @@ -1926,7 +1936,8 @@ void TCanvas::SaveSource(const char *filename, Option_t *option) // Now recursively scan all pads of this canvas cd(); if (invalid) SetName("c1"); - TPad::SavePrimitive(out,option); + TPad::SavePrimitive(out,"toplevel"); + // Write canvas options related to pad editor out<<" "<SetSelected("<SetCanvasSize(ww, wh); fCw = ww; fCh = wh; + fCanvasImp->SetCanvasSize(ww, wh); TContext ctxt(this, kTRUE); ResizePad(); } @@ -1981,8 +1994,8 @@ void TCanvas::SetCanvasSize(UInt_t ww, UInt_t wh) void TCanvas::SetCursor(ECursor cursor) { - if (IsBatch()) return; - gVirtualX->SetCursor(fCanvasID, cursor); + if (!IsBatch() && !IsWeb()) + gVirtualX->SetCursor(fCanvasID, cursor); } //////////////////////////////////////////////////////////////////////////////// @@ -1990,7 +2003,8 @@ void TCanvas::SetCursor(ECursor cursor) void TCanvas::SetDoubleBuffer(Int_t mode) { - if (IsBatch()) return; + if (IsBatch() || IsWeb()) + return; fDoubleBuffer = mode; gVirtualX->SetDoubleBuffer(fCanvasID, mode); @@ -2167,7 +2181,7 @@ void TCanvas::SetWindowPosition(Int_t x, Int_t y) void TCanvas::SetWindowSize(UInt_t ww, UInt_t wh) { - if (fBatch) + if (fBatch && !IsWeb()) SetCanvasSize((ww + fCw) / 2, (wh + fCh) / 2); else if (fCanvasImp) fCanvasImp->SetWindowSize(ww, wh); @@ -2458,7 +2472,7 @@ void TCanvas::ToggleToolTips() Bool_t TCanvas::SupportAlpha() { return gPad && (gVirtualX->InheritsFrom("TGQuartz") || - gPad->GetGLDevice() != -1); + (gPad->GetGLDevice() != -1) || (gPad->GetCanvas() && gPad->GetCanvas()->IsWeb())); } extern "C" void ROOT_TCanvas_Update(void* TheCanvas) { @@ -2470,6 +2484,8 @@ extern "C" void ROOT_TCanvas_Update(void* TheCanvas) { void TCanvas::Update() { + fUpdated = kTRUE; + if (fUpdating) return; if (fPixmapID == -1) return; @@ -2501,7 +2517,7 @@ void TCanvas::Update() fUpdating = kTRUE; - if (!fCanvasImp->PerformUpdate()) { + if (!fCanvasImp->PerformUpdate(kFALSE)) { if (!IsBatch()) FeedbackMode(kFALSE); // Goto double buffer mode @@ -2515,6 +2531,23 @@ void TCanvas::Update() fUpdating = kFALSE; } +//////////////////////////////////////////////////////////////////////////////// +/// Asynchronous pad update. +/// In case of web-based canvas triggers update of the canvas on the client side, +/// but does not wait that real update is completed. Avoids blocking of caller thread. +/// Have to be used if called from other web-based widget to avoid logical dead-locks. +/// In case of normal canvas just canvas->Update() is performed. + +void TCanvas::UpdateAsync() +{ + fUpdated = kTRUE; + + if (IsWeb()) + fCanvasImp->PerformUpdate(kTRUE); + else + Update(); +} + //////////////////////////////////////////////////////////////////////////////// /// Used by friend class TCanvasImp. @@ -2540,7 +2573,12 @@ void TCanvas::SetGrayscale(Bool_t set /*= kTRUE*/) { if (IsGrayscale() == set) return; SetBit(kIsGrayscale, set); - Paint(); // update canvas and all sub-pads, unconditionally! + if (IsWeb()) { + Modified(); + UpdateAsync(); + } else { + Paint(); // update canvas and all sub-pads, unconditionally! + } } //////////////////////////////////////////////////////////////////////////////// @@ -2598,3 +2636,132 @@ void TCanvas::DeleteCanvasPainter() fGLDevice = -1; } } + + +//////////////////////////////////////////////////////////////////////////////// +/// Save provided pads/canvases into the image file(s) +/// Filename can include printf argument for image number - like "image%03d.png". +/// In this case images: "image000.png", "image001.png", "image002.png" will be created. +/// If pattern is not provided - it will be automatically inserted before extension except PDF and ROOT files. +/// In last case PDF or ROOT file will contain all pads. +/// Parameter option only used when output into PDF/PS files +/// If TCanvas::SaveAll() called without arguments - all existing canvases will be stored in allcanvases.pdf file. + +Bool_t TCanvas::SaveAll(const std::vector &pads, const char *filename, Option_t *option) +{ + if (pads.size() == 0) { + std::vector canvases; + TIter iter(gROOT->GetListOfCanvases()); + while (auto c = dynamic_cast(iter())) + canvases.emplace_back(c); + + if (canvases.size() == 0) { + ::Warning("TCanvas::SaveAll", "No pads are provided"); + return kFALSE; + } + + return TCanvas::SaveAll(canvases, filename && *filename ? filename : "allcanvases.pdf", option); + } + + TString fname = filename, ext; + + Bool_t hasArg = fname.Contains("%"); + + if ((pads.size() == 1) && !hasArg) { + pads[0]->SaveAs(filename); + return kTRUE; + } + + auto p = fname.Last('.'); + if (p != kNPOS) { + ext = fname(p+1, fname.Length() - p - 1); + ext.ToLower(); + } else { + p = fname.Length(); + ::Warning("TCanvas::SaveAll", "Extension is not provided in file name %s, append .png", filename); + fname.Append(".png"); + ext = "png"; + } + + if (ext != "pdf" && ext != "ps" && ext != "root" && ext != "xml" && !hasArg) { + fname.Insert(p, "%d"); + hasArg = kTRUE; + } + + static std::vector webExtensions = { "png", "json", "svg", "pdf", "jpg", "jpeg", "webp" }; + + if (gROOT->IsWebDisplay()) { + Bool_t isSupported = kFALSE; + for (auto &wext : webExtensions) { + if ((isSupported = (wext == ext))) + break; + } + + if (isSupported) { + auto cmd = TString::Format("TWebCanvas::ProduceImages( *((std::vector *) 0x%zx), \"%s\")", (size_t) &pads, fname.Data()); + + return (Bool_t) gROOT->ProcessLine(cmd); + } + + ::Warning("TCanvas::SaveAll", "TWebCanvas does not support image format %s - use normal ROOT functionality", fname.Data()); + } + + // store all pads into single PDF/PS files + if (ext == "pdf" || ext == "ps") { + for (unsigned n = 0; n < pads.size(); ++n) { + TString fn = fname; + if (hasArg) + fn = TString::Format(fname.Data(), (int) n); + else if (n == 0) + fn.Append("("); + else if (n == pads.size() - 1) + fn.Append(")"); + + pads[n]->Print(fn.Data(), option && *option ? option : ext.Data()); + } + + return kTRUE; + } + + // store all pads in single ROOT file + if ((ext == "root" || ext == "xml") && !hasArg) { + TString fn = fname; + gSystem->ExpandPathName(fn); + if (fn.IsNull()) { + fn.Form("%s.%s", pads[0]->GetName(), ext.Data()); + ::Warning("TCanvas::SaveAll", "Filename %s cannot be used - use pad name %s as pattern", fname.Data(), fn.Data()); + } + + Bool_t isError = kFALSE; + + if (!gDirectory) { + isError = kTRUE; + } else { + for (unsigned n = 0; n < pads.size(); ++n) { + auto sz = gDirectory->SaveObjectAs(pads[n], fn.Data(), n==0 ? "q" : "qa"); + if (!sz) { isError = kTRUE; break; } + } + } + + if (isError) + ::Error("TCanvas::SaveAll", "Failure to store pads in %s", filename); + else + ::Info("TCanvas::SaveAll", "ROOT file %s has been created", filename); + + return !isError; + } + + for (unsigned n = 0; n < pads.size(); ++n) { + TString fn = TString::Format(fname.Data(), (int) n); + gSystem->ExpandPathName(fn); + if (fn.IsNull()) { + fn.Form("%s%d.%s", pads[n]->GetName(), (int) n, ext.Data()); + ::Warning("TCanvas::SaveAll", "Filename %s cannot be used - use pad name %s as pattern", fname.Data(), fn.Data()); + } + + pads[n]->SaveAs(fn.Data()); + } + + return kTRUE; + +} diff --git a/graf2d/gpad/src/TInspectCanvas.cxx b/graf2d/gpad/src/TInspectCanvas.cxx index 980dee3c4ca2b..166bb24e1ca5b 100644 --- a/graf2d/gpad/src/TInspectCanvas.cxx +++ b/graf2d/gpad/src/TInspectCanvas.cxx @@ -38,7 +38,7 @@ class TInspectorObject : public TObject public: TInspectorObject(void *obj, TClass *cl) : fObj(obj),fClass(cl) {} - ~TInspectorObject() {} + ~TInspectorObject() override {} void *GetObject() const { return fObj; }; void Inspect() const override diff --git a/graf2d/gpad/src/TPad.cxx b/graf2d/gpad/src/TPad.cxx index 4dec0b0413190..188fb2d047710 100644 --- a/graf2d/gpad/src/TPad.cxx +++ b/graf2d/gpad/src/TPad.cxx @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "TROOT.h" @@ -1283,7 +1284,12 @@ void TPad::Draw(Option_t *option) if (oldMother != fMother || fPixmapID == -1) ResizePad(); } - Paint(); + if (fCanvas && fCanvas->IsWeb()) { + Modified(); + fCanvas->UpdateAsync(); + } else { + Paint(); + } if (gPad->IsRetained() && gPad != this && fMother) if (fMother->GetListOfPrimitives()) fMother->GetListOfPrimitives()->Add(this, option); @@ -1580,7 +1586,7 @@ TH1F *TPad::DrawFrame(Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax if (this != gPad) { Warning("DrawFrame", "Must be called for the current pad only"); - return gPad->DrawFrame(xmin,ymin,xmax,ymax,title); + if (gPad) return gPad->DrawFrame(xmin,ymin,xmax,ymax,title); } cd(); @@ -2266,7 +2272,7 @@ void TPad::ExecuteEventAxis(Int_t event, Int_t px, Int_t py, TAxis *axis) static Int_t axisNumber; static Double_t ratio1, ratio2; static Int_t px1old, py1old, px2old, py2old; - Int_t bin1, bin2, first, last; + Int_t nbd, inc, bin1, bin2, first, last; Double_t temp, xmin,xmax; Bool_t opaque = gPad->OpaqueMoving(); static std::unique_ptr zoombox; @@ -2402,8 +2408,10 @@ void TPad::ExecuteEventAxis(Int_t event, Int_t px, Int_t py, TAxis *axis) break; case kWheelUp: - bin1 = axis->GetFirst()+1; - bin2 = axis->GetLast()-1; + nbd = (axis->GetLast()-axis->GetFirst()); + inc = TMath::Max(nbd/100,1); + bin1 = axis->GetFirst()+inc; + bin2 = axis->GetLast()-inc; bin1 = TMath::Max(bin1, 1); bin2 = TMath::Min(bin2, axis->GetNbins()); if (bin2>bin1) { @@ -2414,8 +2422,10 @@ void TPad::ExecuteEventAxis(Int_t event, Int_t px, Int_t py, TAxis *axis) break; case kWheelDown: - bin1 = axis->GetFirst()-1; - bin2 = axis->GetLast()+1; + nbd = (axis->GetLast()-axis->GetFirst()); + inc = TMath::Max(nbd/100,1); + bin1 = axis->GetFirst()-inc; + bin2 = axis->GetLast()+inc; bin1 = TMath::Max(bin1, 1); bin2 = TMath::Min(bin2, axis->GetNbins()); if (bin2>bin1) { @@ -2824,6 +2834,18 @@ void TPad::Update() if (fCanvas) fCanvas->Update(); } +//////////////////////////////////////////////////////////////////////////////// +/// Asynchronous pad update. +/// In case of web-based canvas triggers update of the canvas on the client side, +/// but does not wait that real update is completed. Avoids blocking of caller thread. +/// Have to be used if called from other web-based widget to avoid logical dead-locks. +/// In case of normal canvas just canvas->Update() is performed. + +void TPad::UpdateAsync() +{ + if (fCanvas) fCanvas->UpdateAsync(); +} + //////////////////////////////////////////////////////////////////////////////// /// Get frame. @@ -3067,33 +3089,77 @@ Bool_t TPad::Collide(Int_t i, Int_t j, Int_t w, Int_t h) /// /// \return `true` if the box could be placed, `false` if not. /// -/// \param[in] o pointer to the box to be placed -/// \param[in] w box width to be placed -/// \param[in] h box height to be placed -/// \param[out] xl x position of the bottom left corner of the placed box -/// \param[out] yb y position of the bottom left corner of the placed box +/// \param[in] o pointer to the box to be placed +/// \param[in] w box width to be placed +/// \param[in] h box height to be placed +/// \param[out] xl x position of the bottom left corner of the placed box +/// \param[out] yb y position of the bottom left corner of the placed box +/// \param[in] option l=left, r=right, t=top, b=bottom, w=within margins. Order determines +/// priority for placement. Default is "lb" (prioritises horizontal over vertical) -Bool_t TPad::PlaceBox(TObject *o, Double_t w, Double_t h, Double_t &xl, Double_t &yb) +Bool_t TPad::PlaceBox(TObject *o, Double_t w, Double_t h, Double_t &xl, Double_t &yb, Option_t* option) { FillCollideGrid(o); Int_t iw = (int)(fCGnx*w); Int_t ih = (int)(fCGny*h); - Int_t nxmax = fCGnx-iw-1; - Int_t nymax = fCGny-ih-1; + Int_t nxbeg = 0; + Int_t nybeg = 0; + Int_t nxend = fCGnx-iw-1; + Int_t nyend = fCGny-ih-1; + Int_t dx = 1; + Int_t dy = 1; + + bool isFirstVertical = false; + bool isFirstHorizontal = false; + + for (std::size_t i = 0; option[i] != '\0'; ++i) { + char letter = std::tolower(option[i]); + if (letter == 'w') { + nxbeg += fCGnx*GetLeftMargin(); + nybeg += fCGny*GetBottomMargin(); + nxend -= fCGnx*GetRightMargin(); + nyend -= fCGny*GetTopMargin(); + } else if (letter == 't' || letter == 'b') { + isFirstVertical = !isFirstHorizontal; + // go from top to bottom instead of bottom to top + dy = letter == 't' ? -1 : 1; + } else if (letter == 'l' || letter == 'r') { + isFirstHorizontal = !isFirstVertical; + // go from right to left instead of left to right + dx = letter == 'r' ? -1 : 1; + } + } + + if(dx < 0) std::swap(nxbeg, nxend); + if(dy < 0) std::swap(nybeg, nyend); + + auto attemptPlacement = [&](Int_t i, Int_t j) { + if (Collide(i, j, iw, ih)) { + return false; + } else { + xl = (Double_t)(i) / (Double_t)(fCGnx); + yb = (Double_t)(j) / (Double_t)(fCGny); + return true; + } + }; - for (Int_t i = 0; iExec(TString::Format("epstool --quiet -t6p %s %s", psname.Data(), psname.Data()).Data()); if (strstr(opt,"EmbedFonts")) { - gSystem->Exec(TString::Format("gs -quiet -dSAFER -dNOPLATFONTS -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dUseCIEColor -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dCompatibilityLevel=1.4 -dMaxSubsetPct=100 -dSubsetFonts=true -dEmbedAllFonts=true -sOutputFile=pdf_temp.pdf -f %s", + gSystem->Exec(TString::Format("gs -quiet -dSAFER -dNOPLATFONTS -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dCompatibilityLevel=1.4 -dMaxSubsetPct=100 -dSubsetFonts=true -dEmbedAllFonts=true -sOutputFile=pdf_temp.pdf -f %s", psname.Data()).Data()); gSystem->Rename("pdf_temp.pdf", psname.Data()); } @@ -5646,22 +5712,31 @@ void TPad::SaveAs(const char *filename, Option_t * /*option*/) const //////////////////////////////////////////////////////////////////////////////// /// Save primitives in this pad on the C++ source file out. -void TPad::SavePrimitive(std::ostream &out, Option_t * /*= ""*/) +void TPad::SavePrimitive(std::ostream &out, Option_t * option /*= ""*/) { TContext ctxt(this, kFALSE); // not interactive char quote = '"'; - char lcname[100]; - const char *cname = GetName(); - size_t nch = strlen(cname); - if (nch < sizeof(lcname)) { - strlcpy(lcname, cname, sizeof(lcname)); - for(size_t k = 0; k < nch; k++) - if (lcname[k] == ' ') - lcname[k] = 0; - if (lcname[0] != 0) - cname = lcname; - else if (this == gPad->GetCanvas()) + + TString padName = GetName(); + + // check for space in the pad name + auto p = padName.Index(" "); + if (p != kNPOS) padName.Resize(p); + + TString opt = option; + if (!opt.Contains("toplevel")) { + static Int_t pcounter = 0; + padName += TString::Format("__%d", pcounter++); + padName = gInterpreter->MapCppName(padName); + } + + const char *pname = padName.Data(); + const char *cname = padName.Data(); + + if (padName.Length() == 0) { + pname = "unnamed"; + if (this == gPad->GetCanvas()) cname = "c1"; else cname = "pad"; @@ -5672,8 +5747,7 @@ void TPad::SavePrimitive(std::ostream &out, Option_t * /*= ""*/) out <<" "<Primitives in pad: "<GetName(),"Graph")) ((TGraph*)obj)->SetName(TString::Format("Graph%d",grnum++).Data()); obj->SavePrimitive(out, (Option_t *)next.GetOption()); + if (obj->InheritsFrom(TPad::Class())) { + if (opt.Contains("toplevel")) + out<<" "<cd();"<cd();"<Modified();"<GetName()<<"->cd();"<Delete(); - tmpGuideLinePad = nullptr; - return; - } + ctxt.PadDeleted(tmpGuideLinePad); + auto guidePadClicked = (object == tmpGuideLinePad); // in case of funny button click combination. tmpGuideLinePad->Delete(); tmpGuideLinePad = nullptr; + if (guidePadClicked) return; } // Get Primitives @@ -6523,9 +6600,12 @@ void TPad::Streamer(TBuffer &b) //Set the kCanDelete bit in all objects in the pad such that when the pad //is deleted all objects in the pad are deleted too. + //Also set must cleanup bit which normally set for all primitives add to pad, + // but may be reset in IO like TH1::Streamer does TIter next(fPrimitives); while ((obj = next())) { obj->SetBit(kCanDelete); + obj->SetBit(kMustCleanup); } fModified = kTRUE; diff --git a/graf2d/gpadv7/inc/ROOT/RCanvas.hxx b/graf2d/gpadv7/inc/ROOT/RCanvas.hxx index d66b11bef0f80..f7b9a7ce868f2 100644 --- a/graf2d/gpadv7/inc/ROOT/RCanvas.hxx +++ b/graf2d/gpadv7/inc/ROOT/RCanvas.hxx @@ -69,6 +69,9 @@ private: /// indicate if Show() method was called before bool fShown{false}; /// &handle); + static const std::vector> GetCanvases(); static void ReleaseHeldCanvases(); diff --git a/graf2d/gpadv7/inc/ROOT/RDisplayItem.hxx b/graf2d/gpadv7/inc/ROOT/RDisplayItem.hxx index 2933172b71d4b..a94a2a8a46695 100644 --- a/graf2d/gpadv7/inc/ROOT/RDisplayItem.hxx +++ b/graf2d/gpadv7/inc/ROOT/RDisplayItem.hxx @@ -77,7 +77,7 @@ public: const RDrawable *GetDrawable() const { return fDrawable; } - virtual ~RDrawableDisplayItem(); + ~RDrawableDisplayItem() override; }; diff --git a/graf2d/gpadv7/inc/ROOT/RVirtualCanvasPainter.hxx b/graf2d/gpadv7/inc/ROOT/RVirtualCanvasPainter.hxx index 6694d83a2e815..881f1ecf8e632 100644 --- a/graf2d/gpadv7/inc/ROOT/RVirtualCanvasPainter.hxx +++ b/graf2d/gpadv7/inc/ROOT/RVirtualCanvasPainter.hxx @@ -14,12 +14,14 @@ #include namespace ROOT { + +class RWebWindow; + namespace Experimental { using CanvasCallback_t = std::function; class RCanvas; -class RWebWindow; namespace Internal { @@ -72,7 +74,9 @@ public: /// run canvas functionality in caller thread, not needed when main thread is used virtual void Run(double tm = 0.) = 0; - virtual bool AddPanel(std::shared_ptr) { return false; } + virtual bool AddPanel(std::shared_ptr) { return false; } + + virtual void SetClearOnClose(const std::shared_ptr &) {} /// Loads the plugin that implements this class. static std::unique_ptr Create(RCanvas &canv); diff --git a/graf2d/gpadv7/src/RCanvas.cxx b/graf2d/gpadv7/src/RCanvas.cxx index 0a8bdd6966152..e6be297c5412e 100644 --- a/graf2d/gpadv7/src/RCanvas.cxx +++ b/graf2d/gpadv7/src/RCanvas.cxx @@ -20,6 +20,7 @@ #include "TList.h" #include "TROOT.h" +#include "TString.h" namespace { @@ -76,6 +77,8 @@ bool ROOT::Experimental::RCanvas::IsModified() const void ROOT::Experimental::RCanvas::Update(bool async, CanvasCallback_t callback) { + fUpdated = true; + if (fPainter) fPainter->CanvasUpdated(fModified, async, callback); } @@ -111,12 +114,12 @@ std::shared_ptr ROOT::Experimental::RCanvas::Create void ROOT::Experimental::RCanvas::Show(const std::string &where) { + fShown = true; + // Do not display canvas in batch mode if (gROOT->IsWebDisplayBatch()) return; - fShown = true; - if (fPainter) { bool isany = (fPainter->NumDisplays() > 0); @@ -177,6 +180,18 @@ bool ROOT::Experimental::RCanvas::SaveAs(const std::string &filename) return fPainter->ProduceBatchOutput(filename, width > 1 ? width : 800, height > 1 ? height : 600); } +////////////////////////////////////////////////////////////////////////// +/// Return unique identifier for the canvas +/// Used in iPython display + +std::string ROOT::Experimental::RCanvas::GetUID() const +{ + const void *ptr = this; + auto hash = TString::Hash(&ptr, sizeof(void*)); + TString fmt = TString::Format("rcanv_%x", hash); + return fmt.Data(); +} + ////////////////////////////////////////////////////////////////////////// /// Create JSON data for the canvas /// Can be used of offline display with JSROOT @@ -206,6 +221,15 @@ void ROOT::Experimental::RCanvas::Remove() } } +////////////////////////////////////////////////////////////////////////////////////////////// +/// Set handle which will be cleared when connection is closed + +void ROOT::Experimental::RCanvas::ClearOnClose(const std::shared_ptr &handle) +{ + if (fPainter) + fPainter->SetClearOnClose(handle); +} + ////////////////////////////////////////////////////////////////////////// /// Run canvas functionality for the given time (in seconds) /// Used to process canvas-related actions in the appropriate thread context. @@ -323,3 +347,4 @@ std::unique_ptr ROOT::Experimental::RChangeA return nullptr; // no need for any reply } + diff --git a/graf2d/graf/inc/TArc.h b/graf2d/graf/inc/TArc.h index 70a38432455d5..0a3f7d325bca5 100644 --- a/graf2d/graf/inc/TArc.h +++ b/graf2d/graf/inc/TArc.h @@ -30,7 +30,7 @@ class TArc : public TEllipse { TArc(Double_t x1, Double_t y1,Double_t radius , Double_t phimin=0,Double_t phimax=360); TArc(const TArc &arc); - virtual ~TArc(); + ~TArc() override; void Copy(TObject &arc) const override; virtual TArc *DrawArc(Double_t x1, Double_t y1, Double_t radius diff --git a/graf2d/graf/inc/TArrow.h b/graf2d/graf/inc/TArrow.h index 3e2db19cc36d3..32cd72eede6af 100644 --- a/graf2d/graf/inc/TArrow.h +++ b/graf2d/graf/inc/TArrow.h @@ -41,7 +41,7 @@ class TArrow : public TLine, public TAttFill { TArrow(Double_t x1, Double_t y1, Double_t x2 ,Double_t y2, Float_t arrowsize=0.05, Option_t *option=">"); TArrow(const TArrow &arrow); - virtual ~TArrow(); + ~TArrow() override; void Copy(TObject &arrow) const override; diff --git a/graf2d/graf/inc/TAttImage.h b/graf2d/graf/inc/TAttImage.h index f270b30b8f3a4..d15cd2a30b19f 100644 --- a/graf2d/graf/inc/TAttImage.h +++ b/graf2d/graf/inc/TAttImage.h @@ -44,7 +44,7 @@ class TImagePalette : public TObject { TImagePalette(const TImagePalette &palette); TImagePalette(UInt_t numPoints); TImagePalette(Int_t ncolors, Int_t *colors); - virtual ~TImagePalette(); + ~TImagePalette() override; virtual Int_t FindColor(UShort_t r, UShort_t g, UShort_t b); virtual Int_t *GetRootColors(); diff --git a/graf2d/graf/inc/TBox.h b/graf2d/graf/inc/TBox.h index 302068803520c..e84464c0e13f9 100644 --- a/graf2d/graf/inc/TBox.h +++ b/graf2d/graf/inc/TBox.h @@ -40,7 +40,7 @@ class TBox : public TObject, public TAttLine, public TAttFill, public TAttBBox2D TBox(Double_t x1, Double_t y1,Double_t x2, Double_t y2); TBox(const TBox &box); TBox& operator=(const TBox&); - virtual ~TBox(); + ~TBox() override; void Copy(TObject &box) const override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TCandle.h b/graf2d/graf/inc/TCandle.h index 2f4372caee29d..5a6c927d06600 100644 --- a/graf2d/graf/inc/TCandle.h +++ b/graf2d/graf/inc/TCandle.h @@ -16,6 +16,7 @@ #include "TAttLine.h" #include "TAttFill.h" #include "TAttMarker.h" +#include "TString.h" #include "TMath.h" @@ -79,7 +80,7 @@ class TCandle : public TAttLine, public TAttFill, public TAttMarker { int fNHistoPoints; CandleOption fOption; ///< Setting the style of the candle - char fOptionStr[128]; ///< String to draw the candle + TString fOptionStr; ///< String to draw the candle int fLogX; ///< make the candle appear logx-like int fLogY; ///< make the candle appear logy-like int fLogZ; ///< make the candle appear logz-like @@ -87,15 +88,9 @@ class TCandle : public TAttLine, public TAttFill, public TAttMarker { Double_t fAxisMin; ///< The Minimum which is visible by the axis (used by zero indicator) Double_t fAxisMax; ///< The Maximum which is visible by the axis (used by zero indicator) - static Double_t fWhiskerRange; ///< The fraction which is covered by the whiskers (0 < x < 1), default 1 - static Double_t fBoxRange; ///< The fraction which is covered by the box (0 < x < 1), default 0.5 - - static Bool_t fScaledCandle; ///< shall the box-width be scaled to each other by the integral of a box? - static Bool_t fScaledViolin; ///< shall the violin or histos be scaled to each other by the maximum height? - void Calculate(); - int GetCandleOption(const int pos) {return (fOption/(long)TMath::Power(10,pos))%10;} + int GetCandleOption(const int pos) const {return (fOption/(long)TMath::Power(10,pos))%10;} void PaintBox(Int_t nPoints, Double_t *x, Double_t *y, Bool_t swapXY); void PaintLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Bool_t swapXY); @@ -107,17 +102,17 @@ class TCandle : public TAttLine, public TAttFill, public TAttMarker { TCandle(const Double_t candlePos, const Double_t candleWidth, Long64_t n, Double_t * points); TCandle(const Double_t candlePos, const Double_t candleWidth, TH1D *proj); TCandle(const TCandle &candle); - virtual ~TCandle(); + ~TCandle() override; Double_t GetMean() const {return fMean;} Double_t GetMedian() const {return fMedian;} Double_t GetQ1() const {return fBoxUp;} Double_t GetQ2() const {return fMedian;} Double_t GetQ3() const {return fBoxDown;} - Bool_t IsHorizontal() {return (IsOption(kHorizontal)); } - Bool_t IsVertical() {return (!IsOption(kHorizontal)); } - Bool_t IsCandleScaled(); - Bool_t IsViolinScaled(); + Bool_t IsHorizontal() const {return IsOption(kHorizontal); } + Bool_t IsVertical() const {return !IsOption(kHorizontal); } + Bool_t IsCandleScaled() const; + Bool_t IsViolinScaled() const; void SetOption(CandleOption opt) { fOption = opt; } void SetLog(int x, int y, int z) { fLogX = x; fLogY = y; fLogZ = z;} @@ -137,9 +132,9 @@ class TCandle : public TAttLine, public TAttFill, public TAttMarker { virtual void SetQ3(Double_t q3) { fBoxDown = q3; } int ParseOption(char *optin); - const char *GetDrawOption() { return fOptionStr; } - long GetOption() { return fOption; } - bool IsOption(CandleOption opt); + const char *GetDrawOption() const { return fOptionStr.Data(); } + long GetOption() const { return fOption; } + bool IsOption(CandleOption opt) const; static void SetWhiskerRange(const Double_t wRange); static void SetBoxRange(const Double_t bRange); static void SetScaledCandle(const Bool_t cScale = true); diff --git a/graf2d/graf/inc/TCrown.h b/graf2d/graf/inc/TCrown.h index a1ebea73695b5..94a2eccf90818 100644 --- a/graf2d/graf/inc/TCrown.h +++ b/graf2d/graf/inc/TCrown.h @@ -23,7 +23,7 @@ class TCrown : public TEllipse { TCrown(Double_t x1, Double_t y1,Double_t radin, Double_t radout, Double_t phimin=0,Double_t phimax=360); TCrown(const TCrown &crown); - virtual ~TCrown(); + ~TCrown() override; void Copy(TObject &crown) const override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TCurlyArc.h b/graf2d/graf/inc/TCurlyArc.h index 48109cdae02a1..0bbebf394e0c0 100644 --- a/graf2d/graf/inc/TCurlyArc.h +++ b/graf2d/graf/inc/TCurlyArc.h @@ -30,7 +30,7 @@ class TCurlyArc : public TCurlyLine { TCurlyArc(Double_t x1, Double_t y1, Double_t rad, Double_t phimin, Double_t phimax, Double_t wl = .02, Double_t amp = .01); - virtual ~TCurlyArc() {} + ~TCurlyArc() override {} void Build() override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TCurlyLine.h b/graf2d/graf/inc/TCurlyLine.h index b24e19a21fc0b..e40d496766f79 100644 --- a/graf2d/graf/inc/TCurlyLine.h +++ b/graf2d/graf/inc/TCurlyLine.h @@ -37,7 +37,7 @@ class TCurlyLine : public TPolyLine, public TAttBBox2D { TCurlyLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Double_t wl = .02, Double_t amp = .01); - virtual ~TCurlyLine(){} + ~TCurlyLine() override{} virtual void Build(); Int_t DistancetoPrimitive(Int_t px, Int_t py) override; void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TCutG.h b/graf2d/graf/inc/TCutG.h index 7d9472ebc9e35..3c9a54bdf1e30 100644 --- a/graf2d/graf/inc/TCutG.h +++ b/graf2d/graf/inc/TCutG.h @@ -31,7 +31,7 @@ class TCutG : public TGraph { TCutG(const char *name, Int_t n=0); TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y); TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y); - virtual ~TCutG(); + ~TCutG() override; TCutG &operator=(const TCutG &); virtual Double_t Area() const; diff --git a/graf2d/graf/inc/TDiamond.h b/graf2d/graf/inc/TDiamond.h index 736c475207e07..7290e51d5bf60 100644 --- a/graf2d/graf/inc/TDiamond.h +++ b/graf2d/graf/inc/TDiamond.h @@ -20,7 +20,7 @@ class TDiamond : public TPaveText { TDiamond(); TDiamond(Double_t x1, Double_t y1,Double_t x2, Double_t y2); TDiamond(const TDiamond &diamond); - virtual ~TDiamond(); + ~TDiamond() override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; void Draw(Option_t *option="") override; void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TEllipse.h b/graf2d/graf/inc/TEllipse.h index ff0214ea104d3..b0912d408d2f5 100644 --- a/graf2d/graf/inc/TEllipse.h +++ b/graf2d/graf/inc/TEllipse.h @@ -39,7 +39,7 @@ class TEllipse : public TObject, public TAttLine, public TAttFill, public TAttBB TEllipse(); TEllipse(Double_t x1, Double_t y1,Double_t r1,Double_t r2=0,Double_t phimin=0, Double_t phimax=360,Double_t theta=0); TEllipse(const TEllipse &ellipse); - virtual ~TEllipse(); + ~TEllipse() override; void Copy(TObject &ellipse) const override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; void Draw(Option_t *option="") override; diff --git a/graf2d/graf/inc/TFrame.h b/graf2d/graf/inc/TFrame.h index 45aaf05df319a..c0e0df2e718fd 100644 --- a/graf2d/graf/inc/TFrame.h +++ b/graf2d/graf/inc/TFrame.h @@ -23,7 +23,7 @@ class TFrame : public TWbox { TFrame(); TFrame(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2); TFrame(const TFrame &frame); - virtual ~TFrame(); + ~TFrame() override; void Copy(TObject &frame) const override; void Draw(Option_t *option="") override; void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; diff --git a/graf2d/graf/inc/TGaxis.h b/graf2d/graf/inc/TGaxis.h index d3c5b8a36c06d..5e8f4c46ac663 100644 --- a/graf2d/graf/inc/TGaxis.h +++ b/graf2d/graf/inc/TGaxis.h @@ -19,6 +19,7 @@ class TF1; class TAxis; class TLatex; +class TAxisModLab; class TGaxis : public TLine, public TAttText { @@ -45,18 +46,14 @@ class TGaxis : public TLine, public TAttText { TAxis *fAxis; ///N notation is used - static Float_t fXAxisExpXOffset; ///GetX1() + u1 * (gPad->GetX2() - gPad->GetX1()), gPad->GetY1() + v1 * (gPad->GetY2() - gPad->GetY1()), gPad->GetX1() + u2 * (gPad->GetX2() - gPad->GetX1()), diff --git a/graf2d/graf/src/TBox.cxx b/graf2d/graf/src/TBox.cxx index be175ed280719..36616449a55a7 100644 --- a/graf2d/graf/src/TBox.cxx +++ b/graf2d/graf/src/TBox.cxx @@ -134,6 +134,7 @@ void TBox::Copy(TObject &obj) const Int_t TBox::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Int_t pxl, pyl, pxt, pyt; Int_t px1 = gPad->XtoAbsPixel(fX1); Int_t py1 = gPad->YtoAbsPixel(fY1); @@ -676,6 +677,8 @@ void TBox::Paint(Option_t *option) void TBox::PaintBox(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Option_t *option) { + if (!gPad) return; + TAttLine::Modify(); //Change line attributes only if necessary TAttFill::Modify(); //Change fill area attributes only if necessary @@ -776,7 +779,8 @@ void TBox::Streamer(TBuffer &R__b) Rectangle_t TBox::GetBBox() { - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; Int_t px1, py1, px2, py2; px1 = gPad->XtoPixel(fX1); px2 = gPad->XtoPixel(fX2); @@ -800,7 +804,7 @@ Rectangle_t TBox::GetBBox() TPoint TBox::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); if (!gPad) return (p); p.SetX(gPad->XtoPixel(TMath::Min(fX1,fX2)+0.5*(TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2)))); p.SetY(gPad->YtoPixel(TMath::Min(fY1,fY2)+0.5*(TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2)))); diff --git a/graf2d/graf/src/TCandle.cxx b/graf2d/graf/src/TCandle.cxx index 2a3f2aff5d28c..73c55ad0d6ac6 100644 --- a/graf2d/graf/src/TCandle.cxx +++ b/graf2d/graf/src/TCandle.cxx @@ -16,13 +16,9 @@ #include "TVirtualPad.h" #include "TH2D.h" #include "TRandom2.h" +#include "TStyle.h" #include "strlcpy.h" -Double_t TCandle::fWhiskerRange = 1.0; -Double_t TCandle::fBoxRange = 0.5; -Bool_t TCandle::fScaledCandle = false; -Bool_t TCandle::fScaledViolin = true; - ClassImp(TCandle); /** \class TCandle @@ -138,7 +134,6 @@ TCandle::TCandle(const Double_t candlePos, const Double_t candleWidth, Long64_t fNHistoPoints = 0; fAxisMin = 0.; fAxisMax = 0.; - snprintf(fOptionStr, sizeof(fOptionStr), " "); } //////////////////////////////////////////////////////////////////////////////// @@ -172,60 +167,64 @@ TCandle::TCandle(const Double_t candlePos, const Double_t candleWidth, TH1D *pro fNHistoPoints = 0; fAxisMin = 0.; fAxisMax = 0.; - snprintf(fOptionStr, sizeof(fOptionStr), " "); } //////////////////////////////////////////////////////////////////////////////// /// TCandle default destructor. -TCandle::~TCandle() { +TCandle::~TCandle() +{ if (fIsRaw && fProj) delete fProj; } -Bool_t TCandle::IsCandleScaled() +//////////////////////////////////////////////////////////////////////////////// +/// Returns true if candle plot should be scaled + +Bool_t TCandle::IsCandleScaled() const { - return fScaledCandle; + return gStyle->GetCandleScaled(); } -Bool_t TCandle::IsViolinScaled() +//////////////////////////////////////////////////////////////////////////////// +/// Returns true if violin plot should be scaled + +Bool_t TCandle::IsViolinScaled() const { - return fScaledViolin; + return gStyle->GetViolinScaled(); } //////////////////////////////////////////////////////////////////////////////// -/// Static function to set fWhiskerRange, by setting whisker-range, one can force +/// Static function to set WhiskerRange, by setting whisker-range, one can force /// the whiskers to cover the fraction of the distribution. /// Set wRange between 0 and 1. Default is 1 /// TCandle::SetWhiskerRange(0.95) will set all candle-charts to cover 95% of /// the distribution with the whiskers. /// Can only be used with the standard-whisker definition -void TCandle::SetWhiskerRange(const Double_t wRange) { - if (wRange < 0) fWhiskerRange = 0; - else if (wRange > 1) fWhiskerRange = 1; - else fWhiskerRange = wRange; - +void TCandle::SetWhiskerRange(const Double_t wRange) +{ + gStyle->SetCandleWhiskerRange(wRange); } //////////////////////////////////////////////////////////////////////////////// -/// Static function to set fBoxRange, by setting whisker-range, one can force the +/// Static function to set BoxRange, by setting box-range, one can force the /// box of the candle-chart to cover that given fraction of the distribution. /// Set bRange between 0 and 1. Default is 0.5 /// TCandle::SetBoxRange(0.68) will set all candle-charts to cover 68% of the /// distribution by the box -void TCandle::SetBoxRange(const Double_t bRange) { - if (bRange < 0) fBoxRange = 0; - else if (bRange > 1) fBoxRange = 1; - else fBoxRange = bRange; +void TCandle::SetBoxRange(const Double_t bRange) +{ + gStyle->SetCandleBoxRange(bRange); } //////////////////////////////////////////////////////////////////////////////// /// Static function to set scaling between candles-withs. A candle containing -/// 100 entries with be two times wider than a candle containing 50 entries +/// 100 entries will be two times wider than a candle containing 50 entries -void TCandle::SetScaledCandle(const Bool_t cScale) { - fScaledCandle = cScale; +void TCandle::SetScaledCandle(const Bool_t cScale) +{ + gStyle->SetCandleScaled(cScale); } //////////////////////////////////////////////////////////////////////////////// @@ -233,8 +232,9 @@ void TCandle::SetScaledCandle(const Bool_t cScale) { /// with a maximum bin content to 100 will be two times as high as a violin with /// a maximum bin content of 50 -void TCandle::SetScaledViolin(const Bool_t vScale) { - fScaledViolin = vScale; +void TCandle::SetScaledViolin(const Bool_t vScale) +{ + gStyle->SetViolinScaled(vScale); } //////////////////////////////////////////////////////////////////////////////// @@ -295,17 +295,17 @@ int TCandle::ParseOption(char * opt) { if (wasHorizontal && !IsHorizontal()) {fOption = (CandleOption)(fOption + kHorizontal);} memcpy(brOpen," ",brClose-brOpen+1); //Cleanup - snprintf(fOptionStr, sizeof(fOptionStr), "CANDLE%c(%ld)",direction,(long)fOption); + fOptionStr.Form("CANDLE%c(%ld)", direction, (long)fOption); } else { fOption = (CandleOption)(fOption + fallbackCandle); } } else { - snprintf(fOptionStr, sizeof(fOptionStr), "CANDLE%c%c",direction,preset); + fOptionStr.Form("CANDLE%c%c",direction,preset); } //Handle option "CANDLE" ,"CANDLEX" or "CANDLEY" to behave like "CANDLEX1" or "CANDLEY1" if (!useIndivOption && !fOption ) { fOption = fallbackCandle; - snprintf(fOptionStr, sizeof(fOptionStr), "CANDLE%c2",direction); + fOptionStr.Form("CANDLE%c2",direction); } } @@ -352,17 +352,17 @@ int TCandle::ParseOption(char * opt) { if (wasHorizontal && !IsHorizontal()) {fOption = (CandleOption)(fOption + kHorizontal);} memcpy(brOpen," ",brClose-brOpen+1); //Cleanup - snprintf(fOptionStr, sizeof(fOptionStr), "VIOLIN%c(%ld)",direction,(long)fOption); + fOptionStr.Form("VIOLIN%c(%ld)", direction, (long)fOption); } else { fOption = (CandleOption)(fOption + fallbackCandle); } } else { - snprintf(fOptionStr, sizeof(fOptionStr), "VIOLIN%c%c",direction,preset); + fOptionStr.Form("VIOLIN%c%c", direction, preset); } //Handle option "VIOLIN" ,"VIOLINX" or "VIOLINY" to behave like "VIOLINX1" or "VIOLINY1" if (!useIndivOption && !fOption ) { fOption = fallbackCandle; - snprintf(fOptionStr, sizeof(fOptionStr), "VIOLIN%c1",direction); + fOptionStr.Form("VIOLIN%c1", direction); } } @@ -393,20 +393,24 @@ void TCandle::Calculate() { // Determining the quantiles Double_t prob[5]; - if (fWhiskerRange >= 1) { + Double_t wRange = gStyle->GetCandleWhiskerRange(); + Double_t bRange = gStyle->GetCandleBoxRange(); + + + if (wRange >= 1) { prob[0] = 1e-15; prob[4] = 1-1e-15; } else { - prob[0] = 0.5 - fWhiskerRange/2.; - prob[4] = 0.5 + fWhiskerRange/2.; + prob[0] = 0.5 - wRange/2.; + prob[4] = 0.5 + wRange/2.; } - if (fBoxRange >= 1) { + if (bRange >= 1) { prob[1] = 1E-14; prob[3] = 1-1E-14; } else { - prob[1] = 0.5 - fBoxRange/2.; - prob[3] = 0.5 + fBoxRange/2.; + prob[1] = 0.5 - bRange/2.; + prob[3] = 0.5 + bRange/2.; } prob[2] = 0.5; @@ -661,6 +665,8 @@ void TCandle::Calculate() { void TCandle::Paint(Option_t *) { + if (!gPad) return; + //If something was changed before, we need to recalculate some values if (!fIsCalculated) Calculate(); @@ -834,7 +840,7 @@ void TCandle::Paint(Option_t *) //////////////////////////////////////////////////////////////////////////////// /// Return true is this option is activated in fOption -bool TCandle::IsOption(CandleOption opt) { +bool TCandle::IsOption(CandleOption opt) const { long myOpt = 9; int pos = 0; for (pos = 0; pos < 16; pos++) { @@ -844,7 +850,7 @@ bool TCandle::IsOption(CandleOption opt) { myOpt /= 9; int thisOpt = GetCandleOption(pos); - return ((thisOpt * myOpt) == opt); + return (thisOpt * myOpt) == opt; } //////////////////////////////////////////////////////////////////////////////// @@ -852,6 +858,8 @@ bool TCandle::IsOption(CandleOption opt) { void TCandle::PaintBox(Int_t nPoints, Double_t *x, Double_t *y, Bool_t swapXY) { + if (!gPad) return; + Bool_t doLogY = (!(swapXY) && fLogY) || (swapXY && fLogX); Bool_t doLogX = (!(swapXY) && fLogX) || (swapXY && fLogY); if (doLogY) { @@ -880,6 +888,8 @@ void TCandle::PaintBox(Int_t nPoints, Double_t *x, Double_t *y, Bool_t swapXY) void TCandle::PaintLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Bool_t swapXY) { + if (!gPad) return; + Bool_t doLogY = (!(swapXY) && fLogY) || (swapXY && fLogX); Bool_t doLogX = (!(swapXY) && fLogX) || (swapXY && fLogY); if (doLogY) { diff --git a/graf2d/graf/src/TCrown.cxx b/graf2d/graf/src/TCrown.cxx index 3553a857db5bd..56c72dccfafef 100644 --- a/graf2d/graf/src/TCrown.cxx +++ b/graf2d/graf/src/TCrown.cxx @@ -108,7 +108,7 @@ void TCrown::Copy(TObject &crown) const Int_t TCrown::DistancetoPrimitive(Int_t px, Int_t py) { - + if (!gPad) return 9999; const Double_t kPI = TMath::Pi(); Double_t x = gPad->PadtoX(gPad->AbsPixeltoX(px)) - fX1; Double_t y = gPad->PadtoY(gPad->AbsPixeltoY(py)) - fY1; @@ -178,6 +178,7 @@ void TCrown::ExecuteEvent(Int_t event, Int_t px, Int_t py) void TCrown::Paint(Option_t *) { + if (!gPad) return; const Double_t kPI = TMath::Pi(); const Int_t np = 40; diff --git a/graf2d/graf/src/TCurlyArc.cxx b/graf2d/graf/src/TCurlyArc.cxx index 214c2c30d0c84..35aecdcd8bd4c 100644 --- a/graf2d/graf/src/TCurlyArc.cxx +++ b/graf2d/graf/src/TCurlyArc.cxx @@ -122,6 +122,7 @@ void TCurlyArc::Build() Int_t TCurlyArc::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; // Compute distance of point to center of arc Int_t pxc = gPad->XtoAbsPixel(fX1); Int_t pyc = gPad->YtoAbsPixel(fY1); @@ -516,9 +517,11 @@ Bool_t TCurlyArc::GetDefaultIsCurly() Rectangle_t TCurlyArc::GetBBox() { + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; + Double_t R2 = fR1 * TMath::Abs(gPad->GetY2()-gPad->GetY1())/TMath::Abs(gPad->GetX2()-gPad->GetX1()); - Rectangle_t BBox; BBox.fX = gPad->XtoPixel(fX1-fR1); BBox.fY = gPad->YtoPixel(fY1+R2); BBox.fWidth = gPad->XtoPixel(fX1+fR1)-gPad->XtoPixel(fX1-fR1); @@ -531,7 +534,8 @@ Rectangle_t TCurlyArc::GetBBox() TPoint TCurlyArc::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); + if (!gPad) return (p); p.SetX(gPad->XtoPixel(fX1)); p.SetY(gPad->YtoPixel(fY1)); return(p); @@ -542,6 +546,7 @@ TPoint TCurlyArc::GetBBoxCenter() void TCurlyArc::SetBBoxCenter(const TPoint &p) { + if (!gPad) return; fX1 = gPad->PixeltoX(p.GetX()); fY1 = gPad->PixeltoY(p.GetY()-gPad->VtoPixel(0)); Build(); @@ -552,6 +557,7 @@ void TCurlyArc::SetBBoxCenter(const TPoint &p) void TCurlyArc::SetBBoxCenterX(const Int_t x) { + if (!gPad) return; fX1 = gPad->PixeltoX(x); Build(); } @@ -561,6 +567,7 @@ void TCurlyArc::SetBBoxCenterX(const Int_t x) void TCurlyArc::SetBBoxCenterY(const Int_t y) { + if (!gPad) return; fY1 = gPad->PixeltoY(y-gPad->VtoPixel(0)); Build(); } @@ -571,6 +578,7 @@ void TCurlyArc::SetBBoxCenterY(const Int_t y) void TCurlyArc::SetBBoxX1(const Int_t x) { + if (!gPad) return; Double_t x1 = gPad->PixeltoX(x); if (x1>fX1+fR1) return; @@ -584,6 +592,7 @@ void TCurlyArc::SetBBoxX1(const Int_t x) void TCurlyArc::SetBBoxX2(const Int_t x) { + if (!gPad) return; Double_t x2 = gPad->PixeltoX(x); if (x2GetY2()-gPad->GetY1())/TMath::Abs(gPad->GetX2()-gPad->GetX1()); Double_t y1 = gPad->PixeltoY(y-gPad->VtoPixel(0)); @@ -611,6 +621,7 @@ void TCurlyArc::SetBBoxY1(const Int_t y) void TCurlyArc::SetBBoxY2(const Int_t y) { + if (!gPad) return; Double_t R2 = fR1 * TMath::Abs(gPad->GetY2()-gPad->GetY1())/TMath::Abs(gPad->GetX2()-gPad->GetX1()); Double_t y2 = gPad->PixeltoY(y-gPad->VtoPixel(0)); diff --git a/graf2d/graf/src/TCurlyLine.cxx b/graf2d/graf/src/TCurlyLine.cxx index d405f14b6d3a8..51b220ebfcf40 100644 --- a/graf2d/graf/src/TCurlyLine.cxx +++ b/graf2d/graf/src/TCurlyLine.cxx @@ -463,7 +463,8 @@ Bool_t TCurlyLine::GetDefaultIsCurly() Rectangle_t TCurlyLine::GetBBox() { - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; Int_t px1, py1, px2, py2; px1 = gPad->XtoPixel(fX1); px2 = gPad->XtoPixel(fX2); @@ -487,7 +488,8 @@ Rectangle_t TCurlyLine::GetBBox() TPoint TCurlyLine::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); + if (!gPad) return (p); p.SetX(gPad->XtoPixel(TMath::Min(fX1,fX2)+0.5*(TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2)))); p.SetY(gPad->YtoPixel(TMath::Min(fY1,fY2)+0.5*(TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2)))); return(p); @@ -498,6 +500,7 @@ TPoint TCurlyLine::GetBBoxCenter() void TCurlyLine::SetBBoxCenter(const TPoint &p) { + if (!gPad) return; Double_t w = TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2); Double_t h = TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2); Double_t x1, x2, y1, y2; @@ -525,6 +528,7 @@ void TCurlyLine::SetBBoxCenter(const TPoint &p) void TCurlyLine::SetBBoxCenterX(const Int_t x) { + if (!gPad) return; Double_t w = TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2); if (fX2>fX1) { this->SetStartPoint(gPad->PixeltoX(x)-0.5*w, fY1); @@ -541,6 +545,7 @@ void TCurlyLine::SetBBoxCenterX(const Int_t x) void TCurlyLine::SetBBoxCenterY(const Int_t y) { + if (!gPad) return; Double_t h = TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2); if (fY2>fY1) { this->SetStartPoint(fX1, gPad->PixeltoY(y-gPad->VtoPixel(0))-0.5*h); @@ -558,6 +563,7 @@ void TCurlyLine::SetBBoxCenterY(const Int_t y) void TCurlyLine::SetBBoxX1(const Int_t x) { + if (!gPad) return; if (fX2>fX1) this->SetStartPoint(gPad->PixeltoX(x), fY1); else @@ -570,6 +576,7 @@ void TCurlyLine::SetBBoxX1(const Int_t x) void TCurlyLine::SetBBoxX2(const Int_t x) { + if (!gPad) return; if (fX2>fX1) this->SetEndPoint(gPad->PixeltoX(x), fY2); else @@ -581,6 +588,7 @@ void TCurlyLine::SetBBoxX2(const Int_t x) void TCurlyLine::SetBBoxY1(const Int_t y) { + if (!gPad) return; if (fY2>fY1) this->SetEndPoint(fX2, gPad->PixeltoY(y - gPad->VtoPixel(0))); else @@ -593,6 +601,7 @@ void TCurlyLine::SetBBoxY1(const Int_t y) void TCurlyLine::SetBBoxY2(const Int_t y) { + if (!gPad) return; if (fY2>fY1) this->SetStartPoint(fX1, gPad->PixeltoY(y - gPad->VtoPixel(0))); else diff --git a/graf2d/graf/src/TDiamond.cxx b/graf2d/graf/src/TDiamond.cxx index d57e5a291b100..97ef24b5df014 100644 --- a/graf2d/graf/src/TDiamond.cxx +++ b/graf2d/graf/src/TDiamond.cxx @@ -379,6 +379,7 @@ void TDiamond::ExecuteEvent(Int_t event, Int_t px, Int_t py) void TDiamond::Paint(Option_t *) { + if (!gPad) return; Double_t x[7],y[7],depx,depy; Double_t x1 = fX1; Double_t y1 = fY1; diff --git a/graf2d/graf/src/TEllipse.cxx b/graf2d/graf/src/TEllipse.cxx index 1a1a28ea48294..bbb509c3cb7a8 100644 --- a/graf2d/graf/src/TEllipse.cxx +++ b/graf2d/graf/src/TEllipse.cxx @@ -132,6 +132,7 @@ void TEllipse::Copy(TObject &obj) const Int_t TEllipse::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Double_t x = gPad->PadtoX(gPad->AbsPixeltoX(px)); Double_t y = gPad->PadtoY(gPad->AbsPixeltoY(py)); @@ -530,6 +531,7 @@ void TEllipse::PaintEllipse(Double_t x1, Double_t y1, Double_t r1, Double_t r2, Double_t phimin, Double_t phimax, Double_t theta, Option_t *option) { + if (!gPad) return; const Int_t np = 200; static Double_t x[np+3], y[np+3]; TAttLine::Modify(); //Change line attributes only if necessary @@ -663,7 +665,8 @@ void TEllipse::Streamer(TBuffer &R__b) Rectangle_t TEllipse::GetBBox() { - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; if (!gPad) return (BBox); BBox.fX = gPad->XtoPixel(fX1-fR1); BBox.fY = gPad->YtoPixel(fY1+fR2); @@ -677,7 +680,8 @@ Rectangle_t TEllipse::GetBBox() TPoint TEllipse::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); + if (!gPad) return (p); if (!gPad) return (p); p.SetX(gPad->XtoPixel(fX1)); p.SetY(gPad->YtoPixel(fY1)); @@ -718,6 +722,7 @@ void TEllipse::SetBBoxCenterY(const Int_t y) void TEllipse::SetBBoxX1(const Int_t x) { + if (!gPad) return; Double_t x1 = gPad->PixeltoX(x); if (x1>fX1+fR1) return; diff --git a/graf2d/graf/src/TFrame.cxx b/graf2d/graf/src/TFrame.cxx index ffedafae3c44f..7df00e41b357d 100644 --- a/graf2d/graf/src/TFrame.cxx +++ b/graf2d/graf/src/TFrame.cxx @@ -127,6 +127,7 @@ void TFrame::ExecuteEvent(Int_t event, Int_t px, Int_t py) void TFrame::Paint(Option_t *option) { + if (!gPad) return; const TPickerStackGuard stackGuard(this); if (!gPad->PadInHighlightMode() || (gPad->PadInHighlightMode() && this == gPad->GetSelected())) { diff --git a/graf2d/graf/src/TGaxis.cxx b/graf2d/graf/src/TGaxis.cxx index 57ea833d1ee77..a95ea1c35aac3 100644 --- a/graf2d/graf/src/TGaxis.cxx +++ b/graf2d/graf/src/TGaxis.cxx @@ -36,11 +36,6 @@ #include "strlcpy.h" #include "snprintf.h" -Int_t TGaxis::fgMaxDigits = 5; -Float_t TGaxis::fXAxisExpXOffset = 0.; -Float_t TGaxis::fXAxisExpYOffset = 0.; -Float_t TGaxis::fYAxisExpXOffset = 0.; -Float_t TGaxis::fYAxisExpYOffset = 0.; const Int_t kHori = BIT(9); ClassImp(TGaxis); @@ -390,7 +385,7 @@ And other signature is also allowed: \anchor GA12 ## Maximum Number of Digits for the axis labels -The static function `TGaxis::SetMaxDigits` sets the maximum number of +The static method `TGaxis::SetMaxDigits` sets the maximum number of digits permitted for the axis labels above which the notation with 10^N is used. For example, to accept 6 digits number like 900000 on an axis call `TGaxis::SetMaxDigits(6)`. The default value is 5. @@ -947,12 +942,11 @@ TGaxis *TGaxis::DrawAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t y } //////////////////////////////////////////////////////////////////////////////// -/// Static function returning fgMaxDigits (See SetMaxDigits). +/// Static function returning `gStyle->GetAxisMaxDigits()`. Int_t TGaxis::GetMaxDigits() { - - return fgMaxDigits; + return gStyle->GetAxisMaxDigits(); } //////////////////////////////////////////////////////////////////////////////// @@ -991,6 +985,7 @@ void TGaxis::ImportAxisAttributes(TAxis *axis) void TGaxis::Paint(Option_t *) { + if (!gPad) return; Double_t wmin = fWmin; Double_t wmax = fWmax; @@ -1014,6 +1009,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma Double_t &wmin, Double_t &wmax, Int_t &ndiv, Option_t *chopt, Double_t gridlength, Bool_t drawGridOnly) { + if (!gPad) return; const char *where = "PaintAxis"; @@ -1033,7 +1029,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma Double_t xtick = 0; Double_t xtick0, xtick1, dxtick=0; Double_t ytick, ytick0, ytick1; - Double_t wlabel, dwlabel; + Double_t wlabel, dwlabel, axis_value; Double_t xfactor, yfactor; Double_t xlabel, ylabel, dxlabel; Double_t xone, xtwo; @@ -1257,7 +1253,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma nn1 = TMath::Max(n1a,1)*nn2+1; nticks = nn1; maxDigits = (ndiv/1000000); - if (maxDigits==0) maxDigits = fgMaxDigits; + if (maxDigits==0) maxDigits = gStyle->GetAxisMaxDigits(); // Axis bining optimisation is ignored if: // - the first and the last label are equal @@ -1543,8 +1539,8 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma if (angle == 0) textaxis.SetTextAlign(21); s = 3; } - strncpy(chtemp, fAxis->GetBinLabel(i), 255); - if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp); + strlcpy(chtemp, fAxis->GetBinLabel(i), 255); + if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp, i, 0.1); textaxis.PaintLatex(fAxis->GetBinCenter(i), ymin + s*fAxis->GetLabelOffset()*(gPad->GetUymax()-gPad->GetUymin()), textaxis.GetTextAngle(), @@ -1565,8 +1561,8 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma double scale=gPad->GetWw()*gPad->GetWNDC(); if (scale>0.0) toffset = TMath::Max(toffset,(double)w/scale); } - strncpy(chtemp, fAxis->GetBinLabel(i), 255); - if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp); + strlcpy(chtemp, fAxis->GetBinLabel(i), 255); + if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp, i, 0.1); textaxis.PaintLatex(xmin + s*fAxis->GetLabelOffset()*(gPad->GetUxmax()-gPad->GetUxmin()), fAxis->GetBinCenter(i), 0, @@ -1574,8 +1570,8 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma chtemp); if (fNModLabs) ResetLabelAttributes(&textaxis); } else { - strncpy(chtemp, fAxis->GetBinLabel(i), 255); - if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp); + strlcpy(chtemp, fAxis->GetBinLabel(i), 255); + if (fNModLabs) ChangeLabelAttributes(i, fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp, i, 0.1); textaxis.PaintLatex(xmin - 3*fAxis->GetLabelOffset()*(gPad->GetUxmax()-gPad->GetUxmin()), ymin +(i-0.5)*(ymax-ymin)/nl, 0, @@ -1973,23 +1969,26 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma } if (optionM) xlabel += 0.5*dxlabel; + axis_value = wlabel; + if (!optionText && !optionTime) { snprintf(label,256,chcoded,wlabel); + label[28] = 0; wlabel += dwlabel; LabelsLimits(label,first,last); //Eliminate blanks if (label[first] == '.') { //check if '.' is preceded by a digit - strncpy(chtemp, "0",256); + strncpy(chtemp, "0", 256); strlcat(chtemp, &label[first],256); - strncpy(label, chtemp,256); + strlcpy(label, chtemp, 256); first = 1; last = strlen(label); } if (label[first] == '-' && label[first+1] == '.') { strncpy(chtemp, "-0",256); strlcat(chtemp, &label[first+1],256); - strncpy(label, chtemp, 256); + strlcpy(label, chtemp, 256); first = 1; last = strlen(label); } @@ -2051,7 +2050,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma } else { strncpy(label, "invalid", 256); } - strncpy(chtemp, &label[0], 256); + strlcpy(chtemp, &label[0], 256); first = 0; last=strlen(label)-1; wlabel = wTimeIni + (k+1)*dwlabel; } @@ -2076,8 +2075,8 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma if (!optionY || (x0 == x1)) { if (!optionText) { if (first > last) strncpy(chtemp, " ", 256); - else strncpy(chtemp, &label[first], 255); - if (fNModLabs) ChangeLabelAttributes(k+1, nlabels, &textaxis, chtemp); + else strlcpy(chtemp, &label[first], 255); + if (fNModLabs) ChangeLabelAttributes(k+1, nlabels, &textaxis, chtemp, axis_value, dwlabel*0.01); typolabel = chtemp; if (!optionTime) typolabel.ReplaceAll("-", "#minus"); if (autotoff) { @@ -2094,8 +2093,8 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma typolabel.Data()); if (fNModLabs) ResetLabelAttributes(&textaxis); } else { - strncpy(chtemp, fAxis->GetBinLabel(k+fAxis->GetFirst()), 255); - if (fNModLabs) ChangeLabelAttributes(k+fAxis->GetFirst(), fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp); + strlcpy(chtemp, fAxis->GetBinLabel(k+fAxis->GetFirst()), 255); + if (fNModLabs) ChangeLabelAttributes(k+fAxis->GetFirst(), fAxis->GetLabels()->GetSize()-1, &textaxis, chtemp, k+fAxis->GetFirst(), 0.1); if (optionText == 1) textaxis.PaintLatex(gPad->GetX1() + xx*(gPad->GetX2() - gPad->GetX1()), gPad->GetY1() + yy*(gPad->GetY2() - gPad->GetY1()), 0, @@ -2139,12 +2138,16 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma if (GetLabelFont()%10 < 2) // force TLatex mode in PaintLatex textaxis.SetTextFont((Int_t)(GetLabelFont()/10)*10+2); if (fAxis && !strcmp(fAxis->GetName(),"xaxis")) { - xx = xx + fXAxisExpXOffset; - yy = yy + fXAxisExpYOffset; + Float_t xoff = 0., yoff = 0.; + gStyle->GetExponentOffset(xoff, yoff, "x"); + xx += xoff; + yy += yoff; } if (fAxis && !strcmp(fAxis->GetName(),"yaxis")) { - xx = xx + fYAxisExpXOffset; - yy = yy + fYAxisExpYOffset; + Float_t xoff = 0., yoff = 0.; + gStyle->GetExponentOffset(xoff, yoff, "y"); + xx += xoff; + yy += yoff; } typolabel = label; typolabel.ReplaceAll("-", "#minus"); @@ -2238,6 +2241,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma if (!drawGridOnly && !optionUnlab) { // We generate labels (numeric only). + axis_value = TMath::Power(10,labelnumber); if (noExponent) { rlab = TMath::Power(10,labelnumber); snprintf(label,256, "%f", rlab); @@ -2286,7 +2290,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma if (fNModLabs) { if (changelablogid == 0) changelablognum = nbinin-j; changelablogid++; - ChangeLabelAttributes(changelablogid, changelablognum, &textaxis, chtemp); + ChangeLabelAttributes(changelablogid, changelablognum, &textaxis, chtemp, axis_value, axis_value*1e-6); } typolabel = chtemp; typolabel.ReplaceAll("-", "#minus"); @@ -2338,8 +2342,9 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma // Draw the intermediate LOG labels if requested if (moreLogLabels && !optionUnlab && !drawGridOnly && !overlap) { + axis_value = Double_t(k)*TMath::Power(10,labelnumber-1); if (noExponent) { - rlab = Double_t(k)*TMath::Power(10,labelnumber-1); + rlab = axis_value; snprintf(chtemp,256, "%g", rlab); } else { if (labelnumber-1 == 0) { @@ -2384,7 +2389,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma firstintlab = kFALSE; if (fNModLabs) { changelablogid++; - ChangeLabelAttributes(changelablogid, 0, &textaxis, chtemp); + ChangeLabelAttributes(changelablogid, 0, &textaxis, chtemp, axis_value, axis_value*1e-6); } typolabel = chtemp; typolabel.ReplaceAll("-", "#minus"); @@ -2403,7 +2408,7 @@ void TGaxis::PaintAxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t yma textaxis.GetBoundingBox(wi, hi); wi=(UInt_t)(wi*1.3); hi=(UInt_t)(hi*1.3); if (fNModLabs) { changelablogid++; - ChangeLabelAttributes(changelablogid, 0, &textaxis, chtemp); + ChangeLabelAttributes(changelablogid, 0, &textaxis, chtemp, axis_value, axis_value*1e-6); } typolabel = chtemp; typolabel.ReplaceAll("-", "#minus"); @@ -2600,6 +2605,21 @@ void TGaxis::SavePrimitive(std::ostream &out, Option_t * /*= ""*/) if (TestBit(TAxis::kNoExponent)) { out<<" gaxis->SetNoExponent();"<GetLabNum() == 0) + out<<" gaxis->ChangeLabelByValue("<GetLabValue()<<","; + else + out<<" gaxis->ChangeLabel("<GetLabNum()<<","; + out<GetAngle()<<"," + <GetSize()<<"," + <GetAlign()<<"," + <GetColor()<<"," + <GetFont()<<"," + <GetText()<Draw();"<GetLabNum() == 0) { + if (TMath::Abs(v - ml->GetLabValue()) <= eps) + return ml; + } else if (indx != 0) { + Bool_t match = ml->GetLabNum() == indx; + if (!match && (ml->GetLabNum() < 0) && (indx > 0) && (numlabels > 0)) { + if (TestBit(TAxis::kMoreLogLabels)) { + Error("FindModLab", "reverse numbering in ChangeLabel doesn't work when more log labels are requested"); + return nullptr; + } + + match = indx == (ml->GetLabNum() + 2 + numlabels); + } + if (match) return ml; + } + } + + return nullptr; +} + + //////////////////////////////////////////////////////////////////////////////// /// Define new text attributes for the label number "labNum". It allows to do a /// fine tuning of the labels. All the attributes can be changed, even the @@ -2681,7 +2733,7 @@ void TGaxis::SetFunction(const char *funcname) void TGaxis::ChangeLabel(Int_t labNum, Double_t labAngle, Double_t labSize, Int_t labAlign, Int_t labColor, Int_t labFont, - TString labText) + const TString &labText) { // special situation when mod labs taken from axis - one have to reset pointer if (fModLabs && !IsOwnedModLabs()) { @@ -2701,23 +2753,97 @@ void TGaxis::ChangeLabel(Int_t labNum, Double_t labAngle, Double_t labSize, fModLabs->SetOwner(kTRUE); } - TAxisModLab *ml = new TAxisModLab(); - ml->SetLabNum(labNum); + TAxisModLab *ml = FindModLab(labNum); + if (!ml) { + ml = new TAxisModLab(); + ml->SetLabNum(labNum); + fModLabs->Add(ml); + } + ml->SetAngle(labAngle); ml->SetSize(labSize); ml->SetAlign(labAlign); ml->SetColor(labColor); ml->SetFont(labFont); ml->SetText(labText); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Define new text attributes for the label value "labValue". It allows to do a +/// fine tuning of the labels. All the attributes can be changed, even the +/// label text itself. +/// +/// \param[in] labValue Axis value to be changed +/// \param[in] labAngle New angle value +/// \param[in] labSize New size (0 erase the label) +/// \param[in] labAlign New alignment value +/// \param[in] labColor New label color +/// \param[in] labFont New label font +/// \param[in] labText New label text +/// +/// #### Example: +/// +/// Begin_Macro(source) +/// { +/// auto c = new TCanvas("c1","Examples of TGaxis",900,100); +/// c->Range(-6,-0.1,6,0.1); +/// auto *axis = new TGaxis(-5.5,0.,5.5,0.,0.0,100,510,"S"); +/// axis->SetName("axis1"); +/// axis->SetTitle("Axis Title"); +/// axis->SetTitleSize(0.2); +/// axis->SetLabelSize(0.2); +/// axis->SetTickSize(0.15); +/// axis->SetTitleColor(kBlue); +/// axis->SetTitleFont(42); +/// axis->ChangeLabelByValue(-5.,-1,-1,-1,2); +/// axis->ChangeLabelByValue(-3.,-1,0.); +/// axis->ChangeLabelByValue(0.,30.,-1,0); +/// axis->ChangeLabelByValue(3.,-1,-1,-1,3,-1,"label for 3."); +/// axis->ChangeValue(5.,-2,-1,-1,-1,3,-1,"label for 5."); +/// axis->Draw(); +/// } +/// End_Macro +/// +/// #### Notes: +/// +/// - If an attribute should not be changed just give the value "-1". +/// - If labnum=0 the list of modified labels is reset. +/// - To erase a label set labSize to 0. +/// - If labText is not specified or is an empty string, the text label is not changed. + +void TGaxis::ChangeLabelByValue(Double_t labValue, Double_t labAngle, Double_t labSize, + Int_t labAlign, Int_t labColor, Int_t labFont, + const TString &labText) +{ + // special situation when mod labs taken from axis - one have to reset pointer + if (fModLabs && !IsOwnedModLabs()) { + fModLabs = nullptr; + fNModLabs = 0; + } - fModLabs->Add(ml); + fNModLabs++; + if (!fModLabs) { + fModLabs = new TList(); + fModLabs->SetOwner(kTRUE); + } + + TAxisModLab *ml = FindModLab(0, 0, labValue, 0.); + if (!ml) { + ml = new TAxisModLab(); + ml->SetLabValue(labValue); + fModLabs->Add(ml); + } + + ml->SetAngle(labAngle); + ml->SetSize(labSize); + ml->SetAlign(labAlign); + ml->SetColor(labColor); + ml->SetFont(labFont); + ml->SetText(labText); } -static Double_t SavedTextAngle; ///< Global variable saving the current label's text angle. Used by TGaxis::ChangeLabelAttributes. -static Double_t SavedTextSize; ///< Global variable saving the current label's text size. Used by TGaxis::ChangeLabelAttributes. -static Int_t SavedTextAlign; ///< Global variable saving the current label's text alignment. Used by TGaxis::ChangeLabelAttributes. -static Int_t SavedTextColor; ///< Global variable saving the current label's text color. Used by TGaxis::ChangeLabelAttributes. -static Int_t SavedTextFont; ///< Global variable saving the current label's text font. Used by TGaxis::ChangeLabelAttributes. + +static TAttText SavedAttText; ///< Global variable saving the current label's text angle. Used by TGaxis::ChangeLabelAttributes. //////////////////////////////////////////////////////////////////////////////// /// Helper method used by TGaxis::ChangeLabel. @@ -2727,35 +2853,23 @@ static Int_t SavedTextFont; ///< Global variable saving the current label's /// \param[in] nlabels Totals number of labels for this axis (useful when i is counted from the end) /// \param[in] t Original TLatex string holding the label to be changed /// \param[in] c Text string to be drawn +/// \param[in] value Axis value which should be changed +/// \param[in] eps Epsilon parameter for axis value, -1 means ignore axis value at all + -void TGaxis::ChangeLabelAttributes(Int_t i, Int_t nlabels, TLatex* t, char* c) +void TGaxis::ChangeLabelAttributes(Int_t i, Int_t nlabels, TLatex* t, char* c, Double_t value, Double_t eps) { - if (!fModLabs) return; + t->TAttText::Copy(SavedAttText); - TIter next(fModLabs); - while (auto ml = (TAxisModLab*)next()) { - SavedTextAngle = t->GetTextAngle(); - SavedTextSize = t->GetTextSize(); - SavedTextAlign = t->GetTextAlign(); - SavedTextColor = t->GetTextColor(); - SavedTextFont = t->GetTextFont(); - Int_t labNum = ml->GetLabNum(); - if (labNum < 0) { - if (TestBit(TAxis::kMoreLogLabels)) { - Error("ChangeLabelAttributes", "reverse numbering in ChangeLabel doesn't work when more log labels are requested"); - return; - } - labNum = nlabels + labNum + 2; - } - if (i == labNum) { - if (ml->GetAngle()>=0.) t->SetTextAngle(ml->GetAngle()); - if (ml->GetSize()>=0.) t->SetTextSize(ml->GetSize()); - if (ml->GetAlign()>0) t->SetTextAlign(ml->GetAlign()); - if (ml->GetColor()>=0) t->SetTextColor(ml->GetColor()); - if (ml->GetFont()>0) t->SetTextFont(ml->GetFont()); - if (!(ml->GetText().IsNull())) strncpy(c, (ml->GetText()).Data(), 256); - return; - } + auto ml = FindModLab(i, nlabels, value, eps); + + if (ml) { + if (ml->GetAngle()>=0.) t->SetTextAngle(ml->GetAngle()); + if (ml->GetSize()>=0.) t->SetTextSize(ml->GetSize()); + if (ml->GetAlign()>0) t->SetTextAlign(ml->GetAlign()); + if (ml->GetColor()>=0) t->SetTextColor(ml->GetColor()); + if (ml->GetFont()>0) t->SetTextFont(ml->GetFont()); + if (!ml->GetText().IsNull()) strlcpy(c, ml->GetText().Data(), 256); } } @@ -2766,11 +2880,7 @@ void TGaxis::ChangeLabelAttributes(Int_t i, Int_t nlabels, TLatex* t, char* c) void TGaxis::ResetLabelAttributes(TLatex* t) { - t->SetTextAngle(SavedTextAngle); - t->SetTextSize(SavedTextSize); - t->SetTextAlign(SavedTextAlign); - t->SetTextColor(SavedTextColor); - t->SetTextFont(SavedTextFont); + SavedAttText.Copy(*t); } //////////////////////////////////////////////////////////////////////////////// @@ -2786,8 +2896,7 @@ void TGaxis::ResetLabelAttributes(TLatex* t) void TGaxis::SetMaxDigits(Int_t maxd) { - fgMaxDigits = maxd; - if (maxd < 1) fgMaxDigits = 1; + gStyle->SetAxisMaxDigits(maxd); } //////////////////////////////////////////////////////////////////////////////// @@ -2917,25 +3026,16 @@ void TGaxis::SetTimeOffset(Double_t toffset, Option_t *option) } //////////////////////////////////////////////////////////////////////////////// -/// Static function to set X and Y offset of the axis 10^n notation. +/// Static method to set X and Y offset of the axis 10^n notation. /// It applies on axis belonging to an histogram (TAxis). It has no effect on standalone TGaxis. /// It is in % of the pad size. It can be negative. /// axis specifies which axis ("x","y"), default = "x" /// if axis="xz" set the two axes +/// Redirected to TStyle::SetExponentOffset void TGaxis::SetExponentOffset(Float_t xoff, Float_t yoff, Option_t *axis) { - TString opt = axis; - opt.ToLower(); - - if (opt.Contains("x")) { - fXAxisExpXOffset = xoff; - fXAxisExpYOffset = yoff; - } - if (opt.Contains("y")) { - fYAxisExpXOffset = xoff; - fYAxisExpYOffset = yoff; - } + gStyle->SetExponentOffset(xoff, yoff, axis); } //////////////////////////////////////////////////////////////////////////////// diff --git a/graf2d/graf/src/TGraphPolargram.cxx b/graf2d/graf/src/TGraphPolargram.cxx index c404d12ddb6f3..f1e311eb5466b 100644 --- a/graf2d/graf/src/TGraphPolargram.cxx +++ b/graf2d/graf/src/TGraphPolargram.cxx @@ -111,6 +111,7 @@ void TGraphPolargram::ChangeRangePolar(Double_t tmin, Double_t tmax) Int_t TGraphPolargram::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Int_t i; Double_t x = gPad->AbsPixeltoX(px); Double_t y = gPad->AbsPixeltoY(py); @@ -372,6 +373,8 @@ void TGraphPolargram::Paint(Option_t * chopt) void TGraphPolargram::PaintCircle(Double_t x1, Double_t y1, Double_t r, Double_t phimin, Double_t phimax, Double_t theta) { + if (!gPad) return; + Int_t i; const Int_t np = 200; // Number of point to draw circle static Double_t x[np+3], y[np+3]; @@ -404,8 +407,8 @@ void TGraphPolargram::PaintCircle(Double_t x1, Double_t y1, Double_t r, void TGraphPolargram::PaintPolarDivisions(Bool_t optionLabels) { - Int_t i, j, rnum, rden, first, last; if (!gPad) return ; + Int_t i, j, rnum, rden, first, last; gPad->RangeAxis(-1,-1,1,1); gPad->Range(-1.25,-1.25,1.25,1.25); @@ -621,6 +624,8 @@ void TGraphPolargram::PaintPolarDivisions(Bool_t optionLabels) void TGraphPolargram::PaintRadialDivisions(Bool_t drawaxis) { + if (!gPad) return ; + static char chopt[8] = ""; Int_t i,j; Int_t ndiv = TMath::Abs(fNdivRad); @@ -632,7 +637,6 @@ void TGraphPolargram::PaintRadialDivisions(Bool_t drawaxis) THLimitsFinder::Optimize(fRwrmin,fRwrmax,ndivMajor,frwrmin, frwrmax, ndivmajor,binWidth,""); - if (!gPad) return ; if (!gPad->GetLogx()) { gPad->RangeAxis(-1,-1,1,1); gPad->Range(-1.25,-1.25,1.25,1.25); diff --git a/graf2d/graf/src/TLatex.cxx b/graf2d/graf/src/TLatex.cxx index ec5e3d7bec8b3..20576fc244287 100644 --- a/graf2d/graf/src/TLatex.cxx +++ b/graf2d/graf/src/TLatex.cxx @@ -1953,6 +1953,7 @@ TLatex *TLatex::DrawLatexNDC(Double_t x, Double_t y, const char *text) void TLatex::DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, TextSpec_t spec) { + if (!gPad) return ; Double_t sinang = TMath::Sin(spec.fAngle/180*kPI); Double_t cosang = TMath::Cos(spec.fAngle/180*kPI); Double_t xOrigin = (Double_t)gPad->XtoAbsPixel(fX); @@ -1973,6 +1974,7 @@ void TLatex::DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, TextSp void TLatex::DrawCircle(Double_t x1, Double_t y1, Double_t r, TextSpec_t spec ) { + if (!gPad) return ; if (r < 1) r = 1; Double_t sinang = TMath::Sin(spec.fAngle/180*kPI); Double_t cosang = TMath::Cos(spec.fAngle/180*kPI); @@ -1991,8 +1993,8 @@ void TLatex::DrawCircle(Double_t x1, Double_t y1, Double_t r, TextSpec_t spec ) angle = Double_t(i)*dphi; dx = r*TMath::Cos(angle) +x1 -xOrigin; dy = r*TMath::Sin(angle) +y1 -yOrigin; - x[i] = gPad->AbsPixeltoX(Int_t( dx*cosang+ dy*sinang +xOrigin)); - y[i] = gPad->AbsPixeltoY(Int_t(-dx*sinang+ dy*cosang +yOrigin)); + x[i] = gPad->AbsPixeltoX(TMath::Nint( dx*cosang+ dy*sinang +xOrigin)); + y[i] = gPad->AbsPixeltoY(TMath::Nint(-dx*sinang+ dy*cosang +yOrigin)); } gPad->PaintPolyLine(np+1,x,y); } @@ -2003,6 +2005,7 @@ void TLatex::DrawCircle(Double_t x1, Double_t y1, Double_t r, TextSpec_t spec ) void TLatex::DrawParenthesis(Double_t x1, Double_t y1, Double_t r1, Double_t r2, Double_t phimin, Double_t phimax, TextSpec_t spec ) { + if (!gPad) return ; if (r1 < 1) r1 = 1; if (r2 < 1) r2 = 1; Double_t sinang = TMath::Sin(spec.fAngle/180*kPI); @@ -2033,6 +2036,7 @@ void TLatex::DrawParenthesis(Double_t x1, Double_t y1, Double_t r1, Double_t r2, void TLatex::Paint(Option_t *) { + if (!gPad) return ; Double_t xsave = fX; Double_t ysave = fY; if (TestBit(kTextNDC)) { @@ -2147,6 +2151,7 @@ void TLatex::PaintLatex(Double_t x, Double_t y, Double_t angle, Double_t size, c Int_t TLatex::PaintLatex1(Double_t x, Double_t y, Double_t angle, Double_t size, const Char_t *text1) { + if (!gPad) return 0; TString newText = text1; if( newText.Length() == 0) return 0; newText.ReplaceAll("#hbox","#mbox"); @@ -2198,8 +2203,10 @@ Int_t TLatex::PaintLatex1(Double_t x, Double_t y, Double_t angle, Double_t size, Int_t length = newText.Length() ; const Char_t *text = newText.Data() ; - fX=x; - fY=y; + Double_t xsave = fX; + Double_t ysave = fY; + fX = x; + fY = y; x = gPad->XtoAbsPixel(x); y = gPad->YtoAbsPixel(y); fShow = kFALSE ; @@ -2248,6 +2255,8 @@ Int_t TLatex::PaintLatex1(Double_t x, Double_t y, Double_t angle, Double_t size, SetLineWidth(lineW); SetLineColor(lineC); fTabSize.clear(); + fX = xsave; + fY = ysave; if (fError) return 0; return 1; } @@ -2489,6 +2498,7 @@ TLatex::TLatexFormSize TLatex::FirstParse(Double_t angle, Double_t size, const C Double_t TLatex::GetHeight() const { + if (!gPad) return 0.; Double_t w = gPad->GetAbsWNDC()*Double_t(gPad->GetWw()); Double_t h = gPad->GetAbsHNDC()*Double_t(gPad->GetWh()); if (w < h) @@ -2503,7 +2513,7 @@ Double_t TLatex::GetHeight() const Double_t TLatex::GetXsize() { - if (!gPad) return 0; + if (!gPad) return 0.; TString newText = GetTitle(); if( newText.Length() == 0) return 0; @@ -2591,7 +2601,7 @@ void TLatex::GetBoundingBox(UInt_t &w, UInt_t &h, Bool_t angle) Double_t TLatex::GetYsize() { - if (!gPad) return 0; + if (!gPad) return 0.; TString newText = GetTitle(); if( newText.Length() == 0) return 0; diff --git a/graf2d/graf/src/TLine.cxx b/graf2d/graf/src/TLine.cxx index 2b31aa7d80ca8..02c2ddd3f02ee 100644 --- a/graf2d/graf/src/TLine.cxx +++ b/graf2d/graf/src/TLine.cxx @@ -88,6 +88,7 @@ void TLine::Copy(TObject &obj) const Int_t TLine::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; if (!TestBit(kLineNDC)) return DistancetoLine(px,py,gPad->XtoPad(fX1),gPad->YtoPad(fY1),gPad->XtoPad(fX2),gPad->YtoPad(fY2)); Double_t x1 = gPad->GetX1() + fX1*(gPad->GetX2()-gPad->GetX1()); Double_t y1 = gPad->GetY1() + fY1*(gPad->GetY2()-gPad->GetY1()); @@ -387,6 +388,7 @@ void TLine::ls(Option_t *) const void TLine::Paint(Option_t *) { + if (!gPad) return; if (TestBit(kLineNDC)) PaintLineNDC(fX1,fY1,fX2,fY2); else PaintLine(gPad->XtoPad(fX1),gPad->YtoPad(fY1),gPad->XtoPad(fX2),gPad->YtoPad(fY2)); } @@ -396,6 +398,7 @@ void TLine::Paint(Option_t *) void TLine::PaintLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2) { + if (!gPad) return; TAttLine::Modify(); //Change line attributes only if necessary gPad->PaintLine(x1,y1,x2,y2); } @@ -405,6 +408,7 @@ void TLine::PaintLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2) void TLine::PaintLineNDC(Double_t u1, Double_t v1, Double_t u2, Double_t v2) { + if (!gPad) return; TAttLine::Modify(); //Change line attributes only if necessary gPad->PaintLineNDC(u1,v1,u2,v2); } @@ -474,7 +478,7 @@ void TLine::SetNDC(Bool_t isNDC) void TLine::SetHorizontal(Bool_t set /*= kTRUE*/) { SetBit(kHorizontal, set); - if (set) { + if (set && gPad) { SetVertical(kFALSE); Int_t px1 = gPad->XtoAbsPixel(fX1); Int_t px2 = gPad->XtoAbsPixel(fX2); @@ -495,7 +499,7 @@ void TLine::SetHorizontal(Bool_t set /*= kTRUE*/) void TLine::SetVertical(Bool_t set /*= kTRUE*/) { SetBit(kVertical, set); - if (set) { + if (set && gPad) { SetHorizontal(kFALSE); Int_t px1 = gPad->XtoAbsPixel(fX1); Int_t px2 = gPad->XtoAbsPixel(fX2); @@ -539,7 +543,8 @@ void TLine::Streamer(TBuffer &R__b) Rectangle_t TLine::GetBBox() { - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; Int_t px1, py1, px2, py2; px1 = gPad->XtoPixel(fX1); px2 = gPad->XtoPixel(fX2); @@ -563,7 +568,8 @@ Rectangle_t TLine::GetBBox() TPoint TLine::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); + if (!gPad) return (p); p.SetX(gPad->XtoPixel(TMath::Min(fX1,fX2)+0.5*(TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2)))); p.SetY(gPad->YtoPixel(TMath::Min(fY1,fY2)+0.5*(TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2)))); return(p); @@ -574,6 +580,7 @@ TPoint TLine::GetBBoxCenter() void TLine::SetBBoxCenter(const TPoint &p) { + if (!gPad) return; Double_t w = TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2); Double_t h = TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2); if (fX2>fX1) { @@ -599,6 +606,7 @@ void TLine::SetBBoxCenter(const TPoint &p) void TLine::SetBBoxCenterX(const Int_t x) { + if (!gPad) return; Double_t w = TMath::Max(fX1, fX2)-TMath::Min(fX1, fX2); if (fX2>fX1) { this->SetX1(gPad->PixeltoX(x)-0.5*w); @@ -615,6 +623,7 @@ void TLine::SetBBoxCenterX(const Int_t x) void TLine::SetBBoxCenterY(const Int_t y) { + if (!gPad) return; Double_t h = TMath::Max(fY1, fY2)-TMath::Min(fY1, fY2); if (fY2>fY1) { this->SetY1(gPad->PixeltoY(y-gPad->VtoPixel(0))-0.5*h); @@ -632,6 +641,7 @@ void TLine::SetBBoxCenterY(const Int_t y) void TLine::SetBBoxX1(const Int_t x) { + if (!gPad) return; if (fX2>fX1) this->SetX1(gPad->PixeltoX(x)); else @@ -644,6 +654,7 @@ void TLine::SetBBoxX1(const Int_t x) void TLine::SetBBoxX2(const Int_t x) { + if (!gPad) return; if (fX2>fX1) this->SetX2(gPad->PixeltoX(x)); else @@ -655,6 +666,7 @@ void TLine::SetBBoxX2(const Int_t x) void TLine::SetBBoxY1(const Int_t y) { + if (!gPad) return; if (fY2>fY1) this->SetY2(gPad->PixeltoY(y - gPad->VtoPixel(0))); else @@ -667,6 +679,7 @@ void TLine::SetBBoxY1(const Int_t y) void TLine::SetBBoxY2(const Int_t y) { + if (!gPad) return; if (fY2>fY1) this->SetY1(gPad->PixeltoY(y - gPad->VtoPixel(0))); else diff --git a/graf2d/graf/src/TMarker.cxx b/graf2d/graf/src/TMarker.cxx index f683cf66790c0..7a5b767fab179 100644 --- a/graf2d/graf/src/TMarker.cxx +++ b/graf2d/graf/src/TMarker.cxx @@ -171,6 +171,7 @@ void TMarker::DisplayMarkerLineWidths() Int_t TMarker::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Int_t pxm, pym; if (TestBit(kMarkerNDC)) { pxm = gPad->UtoPixel(fX); @@ -398,7 +399,8 @@ Rectangle_t TMarker::GetBBox() { Double_t size = this->GetMarkerSize(); - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; BBox.fX = gPad->XtoPixel(fX)+(Int_t)(2*size); BBox.fY = gPad->YtoPixel(fY)-(Int_t)(2*size); BBox.fWidth = 2*size; @@ -411,7 +413,7 @@ Rectangle_t TMarker::GetBBox() TPoint TMarker::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); if (!gPad) return (p); p.SetX(gPad->XtoPixel(fX)); p.SetY(gPad->YtoPixel(fY)); diff --git a/graf2d/graf/src/TMathText.cxx b/graf2d/graf/src/TMathText.cxx index a5deba61c361f..e303dbe9df8ac 100644 --- a/graf2d/graf/src/TMathText.cxx +++ b/graf2d/graf/src/TMathText.cxx @@ -477,6 +477,7 @@ void TMathText::GetAlignPoint(Double_t &x0, Double_t &y0, void TMathText::GetBoundingBox(UInt_t &w, UInt_t &h, Bool_t /*angle*/) { + if (!gPad) return; const TString newText = GetTitle(); const Int_t length = newText.Length(); const Char_t *text = newText.Data(); @@ -555,6 +556,7 @@ TMathText *TMathText::DrawMathText(Double_t x, Double_t y, const char *text) void TMathText::Paint(Option_t *) { + if (!gPad) return; Double_t xsave = fX; Double_t ysave = fY; @@ -576,6 +578,7 @@ void TMathText::Paint(Option_t *) void TMathText::PaintMathText(Double_t x, Double_t y, Double_t angle, Double_t size, const Char_t *text1) { + if (!gPad) return; Double_t saveSize = size; Int_t saveFont = fTextFont; Short_t saveAlign = fTextAlign; diff --git a/graf2d/graf/src/TPave.cxx b/graf2d/graf/src/TPave.cxx index 406e94c5f87e2..4e3bb445da304 100644 --- a/graf2d/graf/src/TPave.cxx +++ b/graf2d/graf/src/TPave.cxx @@ -207,6 +207,7 @@ void TPave::Copy(TObject &obj) const Int_t TPave::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Int_t pxl, pyl, pxt, pyt; Int_t px1 = gPad->XtoAbsPixel(fX1); Int_t py1 = gPad->YtoAbsPixel(fY1); diff --git a/graf2d/graf/src/TPaveLabel.cxx b/graf2d/graf/src/TPaveLabel.cxx index 02517312bfa01..c0c898929ae02 100644 --- a/graf2d/graf/src/TPaveLabel.cxx +++ b/graf2d/graf/src/TPaveLabel.cxx @@ -212,8 +212,10 @@ void TPaveLabel::SavePrimitive(std::ostream &out, Option_t * /*= ""*/) out<<"pl = new TPaveLabel("<PadtoX(fX1)<<","<PadtoY(fY1)<<","<PadtoX(fX2)<<","<PadtoY(fY2) - <<","<PadtoX(fX1)<<","<PadtoY(fY1)<<","<PadtoX(fX2)<<","<PadtoY(fY2) + <<","<SetBorderSize("<InheritsFrom(TText::Class())) return; TText *text = (TText*)obj; gROOT->SetSelectedPrimitive(text); - gROOT->ProcessLine(Form("((TCanvas*)0x%zx)->SetSelected((TObject*)0x%zx)", + gROOT->ProcessLine(TString::Format("((TCanvas*)0x%zx)->SetSelected((TObject*)0x%zx)", (size_t)gPad->GetCanvas(), (size_t)text)); - gROOT->ProcessLine(Form("((TCanvas*)0x%zx)->Selected((TVirtualPad*)0x%zx,(TObject*)0x%zx,1)", + gROOT->ProcessLine(TString::Format("((TCanvas*)0x%zx)->Selected((TVirtualPad*)0x%zx,(TObject*)0x%zx,1)", (size_t)gPad->GetCanvas(), (size_t)gPad, (size_t)text)); text->SetTextAttributes(); } @@ -682,6 +682,9 @@ void TPaveText::SaveLines(std::ostream &out, const char *name, Bool_t saved) Int_t nlines = GetSize(); if (nlines == 0) return; + if (!name || !*name) + name = "pt"; + // Iterate over all lines char quote = '"'; TIter next(fLines); diff --git a/graf2d/graf/src/TPavesText.cxx b/graf2d/graf/src/TPavesText.cxx index 5c870044727d6..9f5e62487f479 100644 --- a/graf2d/graf/src/TPavesText.cxx +++ b/graf2d/graf/src/TPavesText.cxx @@ -86,6 +86,7 @@ void TPavesText::Draw(Option_t *option) void TPavesText::Paint(Option_t *option) { + if (!gPad) return; // Draw the fNpaves-1 stacked paves // The spacing between paves is set to 3 times the bordersize Int_t bordersize = GetBorderSize(); diff --git a/graf2d/graf/src/TPie.cxx b/graf2d/graf/src/TPie.cxx index 73db79d7207a3..c1e5cd7c6b078 100644 --- a/graf2d/graf/src/TPie.cxx +++ b/graf2d/graf/src/TPie.cxx @@ -189,6 +189,7 @@ Int_t TPie::DistancetoPrimitive(Int_t px, Int_t py) Int_t TPie::DistancetoSlice(Int_t px, Int_t py) { + if (!gPad) return 9999; MakeSlices(); Int_t result(-1); @@ -986,9 +987,9 @@ void TPie::Paint(Option_t *option) TString tmptxt = fLabelFormat; tmptxt.ReplaceAll("%txt",fPieSlices[i]->GetTitle()); - tmptxt.ReplaceAll("%val",Form(fValueFormat.Data(),fPieSlices[i]->GetValue())); - tmptxt.ReplaceAll("%frac",Form(fFractionFormat.Data(),fPieSlices[i]->GetValue()/fSum)); - tmptxt.ReplaceAll("%perc",Form(Form("%s %s",fPercentFormat.Data(),"%s"),(fPieSlices[i]->GetValue()/fSum)*100,"%")); + tmptxt.ReplaceAll("%val",TString::Format(fValueFormat.Data(),fPieSlices[i]->GetValue())); + tmptxt.ReplaceAll("%frac",TString::Format(fFractionFormat.Data(),fPieSlices[i]->GetValue()/fSum)); + tmptxt.ReplaceAll("%perc",TString::Format(TString::Format("%s %s",fPercentFormat.Data(),"%s").Data(),(fPieSlices[i]->GetValue()/fSum)*100,"%")); textlabel.SetTitle(tmptxt.Data()); Double_t h = textlabel.GetYsize(); diff --git a/graf2d/graf/src/TPieSlice.cxx b/graf2d/graf/src/TPieSlice.cxx index 386210c726f76..c2146364e4a7e 100644 --- a/graf2d/graf/src/TPieSlice.cxx +++ b/graf2d/graf/src/TPieSlice.cxx @@ -55,6 +55,7 @@ TPieSlice::TPieSlice(const char *name, const char *title, Int_t TPieSlice::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/) { Int_t dist = 9999; + if (!gPad) return dist; if (fIsActive) { dist = 0; diff --git a/graf2d/graf/src/TPolyLine.cxx b/graf2d/graf/src/TPolyLine.cxx index 5eb6ab4dbb752..928806c883414 100644 --- a/graf2d/graf/src/TPolyLine.cxx +++ b/graf2d/graf/src/TPolyLine.cxx @@ -180,6 +180,7 @@ void TPolyLine::Copy(TObject &obj) const Int_t TPolyLine::DistancetoPrimitive(Int_t px, Int_t py) { const Int_t big = 9999; + if (!gPad) return big; const Int_t kMaxDiff = 10; // check if point is near one of the points diff --git a/graf2d/graf/src/TText.cxx b/graf2d/graf/src/TText.cxx index 58abf8fedbaaf..683b22e88453d 100644 --- a/graf2d/graf/src/TText.cxx +++ b/graf2d/graf/src/TText.cxx @@ -143,6 +143,7 @@ const void *TText::GetWcsTitle(void) const Int_t TText::DistancetoPrimitive(Int_t px, Int_t py) { + if (!gPad) return 9999; Int_t ptx, pty; TAttText::Modify(); // change text attributes only if necessary @@ -478,6 +479,7 @@ void TText::GetBoundingBox(UInt_t &w, UInt_t &h, Bool_t angle) return; } + if (!gPad) return; if (angle) { Int_t cBoxX[4], cBoxY[4]; Int_t ptx, pty; @@ -522,6 +524,7 @@ void TText::GetBoundingBox(UInt_t &w, UInt_t &h, Bool_t angle) void TText::GetTextAscentDescent(UInt_t &a, UInt_t &d, const char *text) const { + if (!gPad) return; Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t tsize; @@ -557,6 +560,7 @@ void TText::GetTextAscentDescent(UInt_t &a, UInt_t &d, const char *text) const void TText::GetTextAscentDescent(UInt_t &a, UInt_t &d, const wchar_t *text) const { + if (!gPad) return; Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t tsize; @@ -586,6 +590,7 @@ void TText::GetTextAscentDescent(UInt_t &a, UInt_t &d, const wchar_t *text) cons void TText::GetTextExtent(UInt_t &w, UInt_t &h, const char *text) const { + if (!gPad) return; Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t tsize; @@ -614,6 +619,7 @@ void TText::GetTextExtent(UInt_t &w, UInt_t &h, const char *text) const void TText::GetTextAdvance(UInt_t &a, const char *text, const Bool_t kern) const { + if (!gPad) return; Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t tsize; @@ -649,6 +655,7 @@ void TText::GetTextAdvance(UInt_t &a, const char *text, const Bool_t kern) const void TText::GetTextExtent(UInt_t &w, UInt_t &h, const wchar_t *text) const { + if (!gPad) return; Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t tsize; @@ -679,6 +686,7 @@ void TText::ls(Option_t *) const void TText::Paint(Option_t *) { + if (!gPad) return; TAttText::Modify(); //Change text attributes only if necessary if (TestBit(kTextNDC)) gPad->PaintTextNDC(fX,fY,GetTitle()); else gPad->PaintText(gPad->XtoPad(fX),gPad->YtoPad(fY),GetTitle()); @@ -883,7 +891,8 @@ Rectangle_t TText::GetBBox() case 3 : Dy = 0 ; break; } - Rectangle_t BBox; + Rectangle_t BBox{0,0,0,0}; + if (!gPad) return BBox; BBox.fX = gPad->XtoPixel(fX)-Dx; BBox.fY = gPad->YtoPixel(fY)-Dy; BBox.fWidth = w; @@ -896,7 +905,8 @@ Rectangle_t TText::GetBBox() TPoint TText::GetBBoxCenter() { - TPoint p; + TPoint p(0,0); + if (!gPad) return (p); p.SetX(gPad->XtoPixel(fX)); p.SetY(gPad->YtoPixel(fY)); return(p); @@ -907,6 +917,7 @@ TPoint TText::GetBBoxCenter() void TText::SetBBoxCenter(const TPoint &p) { + if (!gPad) return; this->SetX(gPad->PixeltoX(p.GetX())); this->SetY(gPad->PixeltoY(p.GetY()-gPad->VtoPixel(0))); } @@ -916,6 +927,7 @@ void TText::SetBBoxCenter(const TPoint &p) void TText::SetBBoxCenterX(const Int_t x) { + if (!gPad) return; this->SetX(gPad->PixeltoX(x)); } @@ -924,6 +936,7 @@ void TText::SetBBoxCenterX(const Int_t x) void TText::SetBBoxCenterY(const Int_t y) { + if (!gPad) return; this->SetY(gPad->PixeltoY(y - gPad->VtoPixel(0))); } diff --git a/graf2d/graf/src/TWbox.cxx b/graf2d/graf/src/TWbox.cxx index 16ff9b6fc1867..fbc1c42da7eea 100644 --- a/graf2d/graf/src/TWbox.cxx +++ b/graf2d/graf/src/TWbox.cxx @@ -138,6 +138,7 @@ void TWbox::PaintFrame(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Color_t color, Short_t bordersize, Short_t bordermode, Bool_t tops) { + if (!gPad) return; if (bordermode == 0) return; if (bordersize <= 0) bordersize = 2; diff --git a/graf2d/gviz/inc/TGraphEdge.h b/graf2d/gviz/inc/TGraphEdge.h index bdbd8d431edef..8b17a620b768f 100644 --- a/graf2d/gviz/inc/TGraphEdge.h +++ b/graf2d/gviz/inc/TGraphEdge.h @@ -41,22 +41,22 @@ class TGraphEdge: public TObject, public TAttLine { public: TGraphEdge(); TGraphEdge(TGraphNode *n1, TGraphNode *n2); - virtual ~TGraphEdge(); + ~TGraphEdge() override; void CreateGVEdge(GVizAgraph_t *gv); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; void SetGVEdge(GVizAgedge_t *gve) {fGVEdge = gve;} GVizAgedge_t *GetGVEdge() {return fGVEdge;} TGraphNode *GetNode1() {return fNode1;} TGraphNode *GetNode2() {return fNode2;} void Layout(); - virtual void Paint(Option_t *option=""); - virtual void SavePrimitive(std::ostream &, Option_t *); + void Paint(Option_t *option="") override; + void SavePrimitive(std::ostream &, Option_t *) override; void SaveAttributes(std::ostream &, const char*); - ClassDef(TGraphEdge,2) //Graph edge class + ClassDefOverride(TGraphEdge,2) //Graph edge class }; #endif diff --git a/graf2d/gviz/inc/TGraphNode.h b/graf2d/gviz/inc/TGraphNode.h index 19a2e5fb390ec..5df1735b61df1 100644 --- a/graf2d/gviz/inc/TGraphNode.h +++ b/graf2d/gviz/inc/TGraphNode.h @@ -40,20 +40,20 @@ class TGraphNode : public TNamed, public TAttText, public TAttFill, public TAttL TGraphNode(); TGraphNode(const char *name, const char *title=""); - virtual ~TGraphNode(); + ~TGraphNode() override; void CreateGVNode(GVizAgraph_t *gv); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; void SetGVNode(GVizAgnode_t *gvn) {fGVNode = gvn;} - virtual void SetTextAngle(Float_t) {} + void SetTextAngle(Float_t) override {} GVizAgnode_t *GetGVNode() {return fGVNode;} void Layout(); - virtual void Paint(Option_t *option=""); - virtual void SavePrimitive(std::ostream &, Option_t *); + void Paint(Option_t *option="") override; + void SavePrimitive(std::ostream &, Option_t *) override; void SaveAttributes(std::ostream &); - ClassDef(TGraphNode,2) //Graph node class + ClassDefOverride(TGraphNode,2) //Graph node class }; #endif diff --git a/graf2d/gviz/inc/TGraphStruct.h b/graf2d/gviz/inc/TGraphStruct.h index 926985fd26fc2..c7e07ea583e2f 100644 --- a/graf2d/gviz/inc/TGraphStruct.h +++ b/graf2d/gviz/inc/TGraphStruct.h @@ -34,21 +34,21 @@ class TGraphStruct : public TObject { public: TGraphStruct(); - virtual ~TGraphStruct(); + ~TGraphStruct() override; void AddEdge(TGraphEdge *edge); void AddNode(TGraphNode *node); TGraphEdge *AddEdge(TGraphNode *n1, TGraphNode *n2); TGraphNode *AddNode(const char *name, const char *title=""); - void Draw(Option_t *option=""); + void Draw(Option_t *option="") override; void DumpAsDotFile(const char *filename); TList *GetListOfNodes() const { return fNodes; } TList *GetListOfEdges() const { return fEdges; } Int_t Layout(); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; void SetMargin(Double_t m=10) {fMargin = m;} - ClassDef(TGraphStruct,2) //Graph structure class + ClassDefOverride(TGraphStruct,2) //Graph structure class }; #endif diff --git a/graf2d/postscript/inc/TImageDump.h b/graf2d/postscript/inc/TImageDump.h index 743bbddb9a7f2..987736567afce 100644 --- a/graf2d/postscript/inc/TImageDump.h +++ b/graf2d/postscript/inc/TImageDump.h @@ -32,7 +32,7 @@ class TImageDump : public TVirtualPS { public: TImageDump(); TImageDump(const char *filename, Int_t type = -111); - virtual ~TImageDump(); + ~TImageDump() override; void CellArrayBegin(Int_t W, Int_t H, Double_t x1, Double_t x2, Double_t y1, Double_t y2) override; void CellArrayFill(Int_t r, Int_t g, Int_t b) override; diff --git a/graf2d/postscript/inc/TPDF.h b/graf2d/postscript/inc/TPDF.h index 1eaebeb79a969..13dadddb95e75 100644 --- a/graf2d/postscript/inc/TPDF.h +++ b/graf2d/postscript/inc/TPDF.h @@ -52,11 +52,12 @@ class TPDF : public TVirtualPS { static Int_t fgLineJoin; ///< Appearance of joining lines static Int_t fgLineCap; ///< Appearance of line caps + static Bool_t fgObjectIsOpen; ///< Indicates if an object is open public: TPDF(); TPDF(const char *filename, Int_t type=-111); - virtual ~TPDF(); + ~TPDF() override; void CellArrayBegin(Int_t W, Int_t H, Double_t x1, Double_t x2, Double_t y1, Double_t y2) override; void CellArrayFill(Int_t r, Int_t g, Int_t b) override; @@ -76,6 +77,7 @@ class TPDF : public TVirtualPS { void DrawPS(Int_t n, Double_t *xw, Double_t *yw) override; void LineTo(Double_t x, Double_t y); void MoveTo(Double_t x, Double_t y); + void EndObject(); void FontEncode(); void NewObject(Int_t n); void NewPage() override; diff --git a/graf2d/postscript/inc/TPostScript.h b/graf2d/postscript/inc/TPostScript.h index fd4f7a8e9660c..4e49669b33cf3 100644 --- a/graf2d/postscript/inc/TPostScript.h +++ b/graf2d/postscript/inc/TPostScript.h @@ -83,7 +83,7 @@ class TPostScript : public TVirtualPS { public: TPostScript(); TPostScript(const char *filename, Int_t type=-111); - virtual ~TPostScript(); + ~TPostScript() override; void CellArrayBegin(Int_t W, Int_t H, Double_t x1, Double_t x2, Double_t y1, Double_t y2) override; diff --git a/graf2d/postscript/inc/TSVG.h b/graf2d/postscript/inc/TSVG.h index 091c297b74c7f..53c6bca38e061 100644 --- a/graf2d/postscript/inc/TSVG.h +++ b/graf2d/postscript/inc/TSVG.h @@ -33,7 +33,7 @@ class TSVG : public TVirtualPS { public: TSVG(); TSVG(const char *filename, Int_t type=-113); - virtual ~TSVG(); + ~TSVG() override; void CellArrayBegin(Int_t W, Int_t H, Double_t x1, Double_t x2, Double_t y1, Double_t y2) override; void CellArrayFill(Int_t r, Int_t g, Int_t b) override; diff --git a/graf2d/postscript/inc/TTeXDump.h b/graf2d/postscript/inc/TTeXDump.h index e31acf7ba0818..ed89353290af8 100644 --- a/graf2d/postscript/inc/TTeXDump.h +++ b/graf2d/postscript/inc/TTeXDump.h @@ -36,7 +36,7 @@ class TTeXDump : public TVirtualPS { public: TTeXDump(); TTeXDump(const char *filename, Int_t type=-113); - virtual ~TTeXDump(); + ~TTeXDump() override; void CellArrayBegin(Int_t W, Int_t H, Double_t x1, Double_t x2, Double_t y1, Double_t y2) override; void CellArrayFill(Int_t r, Int_t g, Int_t b) override; diff --git a/graf2d/postscript/src/TPDF.cxx b/graf2d/postscript/src/TPDF.cxx index b188d965224c5..0c63d73cbc212 100644 --- a/graf2d/postscript/src/TPDF.cxx +++ b/graf2d/postscript/src/TPDF.cxx @@ -94,8 +94,9 @@ const Int_t kObjFirstPage = 51; // First page object // Number of fonts const Int_t kNumberOfFonts = 15; -Int_t TPDF::fgLineJoin = 0; -Int_t TPDF::fgLineCap = 0; +Int_t TPDF::fgLineJoin = 0; +Int_t TPDF::fgLineCap = 0; +Bool_t TPDF::fgObjectIsOpen = kFALSE; ClassImp(TPDF); @@ -205,11 +206,11 @@ void TPDF::Close(Option_t *) WriteCompressedBuffer(); PrintStr("endstream@"); Int_t streamLength = fNByte-fStartStream-10; - PrintStr("endobj@"); + EndObject(); NewObject(4*(fNbPage-1)+kObjFirstPage+2); WriteInteger(streamLength, 0); PrintStr("@"); - PrintStr("endobj@"); + EndObject(); NewObject(4*(fNbPage-1)+kObjFirstPage+3); PrintStr("<<@"); if (!strstr(GetTitle(),"PDF")) { @@ -235,6 +236,7 @@ void TPDF::Close(Option_t *) PrintStr("@"); } PrintStr(">>@"); + EndObject(); NewObject(kObjOutlines); PrintStr("<<@"); @@ -251,7 +253,7 @@ void TPDF::Close(Option_t *) PrintStr(" 0 R"); PrintStr("@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); NewObject(kObjContents); PrintStr("<<@"); @@ -275,6 +277,7 @@ void TPDF::Close(Option_t *) PrintStr(" 0 R"); PrintStr("@"); PrintStr(">>@"); + EndObject(); // List of all the pages NewObject(kObjPages); @@ -291,7 +294,7 @@ void TPDF::Close(Option_t *) PrintStr(" ]"); PrintStr("@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); NewObject(kObjTransList); PrintStr("<<@"); @@ -301,7 +304,7 @@ void TPDF::Close(Option_t *) fAlphas[i],fAlphas[i],fAlphas[i],fAlphas[i])); } PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); if (fAlphas.size()) fAlphas.clear(); // Cross-Reference Table @@ -1366,6 +1369,18 @@ void TPDF::DrawPS(Int_t nn, Double_t *xw, Double_t *yw) SetLineWidth(linewidthsav); } +//////////////////////////////////////////////////////////////////////////////// +/// Close the current opened object + +void TPDF::EndObject() +{ + if (!fgObjectIsOpen) + Warning("TPDF::EndObject", "No Object currently opened."); + fgObjectIsOpen = kFALSE; + + PrintStr("endobj@"); +} + //////////////////////////////////////////////////////////////////////////////// /// Font encoding @@ -1394,7 +1409,7 @@ void TPDF::FontEncode() PrintStr("@"); } PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); } } @@ -1423,6 +1438,9 @@ void TPDF::MoveTo(Double_t x, Double_t y) void TPDF::NewObject(Int_t n) { + if (fgObjectIsOpen) + Warning("TPDF::NewObject", "An Object is already open."); + fgObjectIsOpen = kTRUE; if (!fObjPos || n >= fObjPosSize) { Int_t newN = TMath::Max(2*fObjPosSize,n+1); Int_t *saveo = new Int_t [newN]; @@ -1464,11 +1482,11 @@ void TPDF::NewPage() WriteCompressedBuffer(); PrintStr("endstream@"); Int_t streamLength = fNByte-fStartStream-10; - PrintStr("endobj@"); + EndObject(); NewObject(4*(fNbPage-2)+kObjFirstPage+2); WriteInteger(streamLength, 0); PrintStr("@"); - PrintStr("endobj@"); + EndObject(); NewObject(4*(fNbPage-2)+kObjFirstPage+3); PrintStr("<<@"); if (!strstr(GetTitle(),"PDF")) { @@ -1498,6 +1516,7 @@ void TPDF::NewPage() PrintStr("@"); } PrintStr(">>@"); + EndObject(); } // Start a new page @@ -1577,7 +1596,7 @@ void TPDF::NewPage() WriteInteger(4*(fNbPage-1)+kObjFirstPage+1); PrintStr(" 0 R@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); NewObject(4*(fNbPage-1)+kObjFirstPage+1); PrintStr("<<@"); @@ -1737,7 +1756,7 @@ void TPDF::Open(const char *fname, Int_t wtype) PrintStr(" 0 R@"); PrintStr("/PageMode /UseOutlines@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); NewObject(kObjInfo); PrintStr("<<@"); @@ -1770,7 +1789,7 @@ void TPDF::Open(const char *fname, Int_t wtype) PrintStr("@"); PrintStr("/Keywords (ROOT)@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); NewObject(kObjPageResources); PrintStr("<<@"); @@ -1801,7 +1820,7 @@ void TPDF::Open(const char *fname, Int_t wtype) PrintStr(" 0 R"); PrintStr("@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); FontEncode(); PatternEncode(); @@ -2462,10 +2481,10 @@ void TPDF::PatternEncode() } else { PrintStr("[/Pattern /DeviceRGB]@"); } - PrintStr("endobj@"); + EndObject(); NewObject(kObjPatternResourses); PrintStr("<>@"); - PrintStr("endobj@"); + EndObject(); NewObject(kObjPatternList); PrintStr("<<@"); @@ -2545,7 +2564,7 @@ void TPDF::PatternEncode() WriteInteger(patternNb++); PrintStr(" 0 R@"); PrintStr(">>@"); - PrintStr("endobj@"); + EndObject(); patternNb = kObjPattern; @@ -2559,7 +2578,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301P\241\034(\254\340\253\020m\250\020k\240\220\302e\244`\242\220\313ei\t\244r\200\272\215A\034\v \225\003\2241\202\310\030\201e\f!2\206@N0W \027@\200\001\0|c\024\357\n", 93); fNByte += 93; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P02 NewObject(patternNb++); @@ -2571,7 +2590,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211$\2121\n\2000\024C\367\234\"G\370\277\025\321+\b\016\342\340P\334tP\252\240\213\3277\332!\204\274\227\v\316\2150\032\335J\356\025\023O\241Np\247\363\021f\317\344\214\234\215\v\002+\036h\033U\326/~\243Ve\231PL\370\215\027\343\032#\006\274\002\f\0\242`\025:\n", 94); fNByte += 94; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P03 NewObject(patternNb++); @@ -2583,7 +2602,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211$\2121\n\2000\024C\367\234\"G\370\261(\366\n\202\20388\210\233\016J\025t\361\372\376\332!\204\274\227\033\342N\030\215\262\222g\303\304\313Q\347\360\240\370:f\317Y\f\\\214+**\360Dls'\177\306\274\032\257\344\256.\252\376\215\212\221\217\021\003>\001\006\0\317\243\025\254\n", 95); fNByte += 95; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P04 NewObject(patternNb++); @@ -2595,7 +2614,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\002V\231\313\005S\233\303\025\314\025\310\005\020`\0\344\270\r\274\n", 65); fNByte += 65; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P05 NewObject(patternNb++); @@ -2607,7 +2626,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\302\005Q\223\313\005\"\r\024r\270\202\271\002\271\0\002\f\0\344\320\r\274\n", 68); fNByte += 68; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P06 NewObject(patternNb++); @@ -2619,7 +2638,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\302e\nR\232\v\242@js\270\202\271\002\271\0\002\f\0\345X\r\305\n", 68); fNByte += 68; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P07 NewObject(patternNb++); @@ -2631,7 +2650,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\002\02465P\310\345\002)\0042r\270\202\271\002\271\0\002\f\0\345=\r\305\n", 70); fNByte += 70; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P08 NewObject(patternNb++); @@ -2643,7 +2662,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211D\217\261\016\3020\fDw\177\305\315L6Q\225|\003\022C\305\300Puk+\201\032$\272\360\373\330\265\323\016\271\330\367\234\344\"x\201\030\214\252\232\030+%\353VZ.jd\367\205\003x\241({]\311\324]\323|\342\006\033J\201:\306\325\230Jg\226J\261\275D\257#\337=\220\260\354k\233\351\211\217Z75\337\020\374\324\306\035\303\310\230\342x=\303\371\275\307o\332s\331\223\224\240G\330\a\365\364\027`\0\nX1}\n",141); fNByte += 141; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P09 NewObject(patternNb++); @@ -2655,7 +2674,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\002\02465P\310\005RFFz&\020\002,d\240\220\314en\256g\0065\b,\001b\230\202$\240\232\214@\362\246`\2169H\336\024\2426\231\v&\200,\n\326\030\314\025\310\005\020`\0\f@\036\227\n", 110); fNByte += 110; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P10 NewObject(patternNb++); @@ -2667,7 +2686,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\002\02465P\310\345\002)\0042r\200\332\r\241\\C \017dN.\027L\312\0\302\205\2535\205j6\205X\224\303\025\314\025\310\005\020`\0\2127\031\t\n", 95); fNByte += 95; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P11 NewObject(patternNb++); @@ -2679,7 +2698,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211\\\2171\016\3020\fEw\237\342\037\301ip\223^\001\211\001u`@l0\200(\022,\\\037;v\204\332\241\211\336\373\337V\363\246\204;\210\301H\354\337\347F'\274T\355U>\220\360U\215\003\316\027\306\2655\027=\a\306\223\304I\002m\332\330\356&\030\325\333fZ\275F\337\205\235\265O\270\032\004\331\214\336\305\270\004\227`\357i\256\223\342;]\344\255(!\372\356\205j\030\377K\335\220\344\377\210\274\306\022\330\337T{\214,\212;\301\3508\006\346\206\021O=\216|\212|\246#\375\004\030\0\216FF\207\n", 166); fNByte += 166; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P12 NewObject(patternNb++); @@ -2691,7 +2710,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211\351\203\236\002\f\0d}e\216\n", 228); fNByte += 228; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P13 NewObject(patternNb++); @@ -2703,7 +2722,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\002V\231\313\005S\233\303\005\241!\" ~0W \027@\200\001\0\331\227\020\253\n", 71); fNByte += 71; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P14 NewObject(patternNb++); @@ -2715,7 +2734,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\2114\214=\n\2000\f\205\367\234\342\035!-\241\364\f\202\20388\210\233\016J+\350\342\365M\3723\224\327\367}I\036r8A\f\206\343\372\336\203\026\334\212\006\205\027\004\237b\214X7\306\256\33032\331\240~\022y[\315\026\206\222\372\330}\264\036\253\217\335\353\240\030\b%\223\245o=X\227\346\245\355K\341\345@\3613M\364\v0\0\207o\"\261\n", 116); fNByte += 116; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P15 NewObject(patternNb++); @@ -2727,7 +2746,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211<\2211\016\3020\fEw\237\302'@\211c\267w@b@\f\f\210\2510\200(\022,\\\037\347\307\256Z\325\221\375\337\377\225\363\241\312\017\246\302\205'\274\337;\235\371\355\215\275\267\236\\\371\307\265\360\201/\327\3027o\233\361J\262\233\247~\362g\336\211zur!A]{\035}\031S\343\006p\241\226dKI\v\326\202\265\3153\331)X)\335fE\205M\235\373\327\r*\374\026\252\022\216u\223\200\361I\211\177\031\022\001#``\342GI\211\004c\221gi\246\231\247\221\247\231\247\233$XM3\315<\215<\315write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020\035k\240\220\302ej\240\0D\271 \332\314X\317B\301\330\002H\230\233*\030\231\202\310d.CC=#\020\v*\rV\235\214\254\v\210r@\264\261\031P\241\031H5D\253\021H\267\005\3104 \v\344\016\260\002\020\003lB0W \027@\200\001\0hU \305\n", 125); fNByte += 125; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P17 NewObject(patternNb++); @@ -2751,7 +2770,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020md\242\020k\240\220\002V\234\313\005S\236\303\025\314\025\310\005\020`\0\r\351\016B\n", 68); fNByte += 68; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P18 NewObject(patternNb++); @@ -2763,7 +2782,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211*\3442T\310T\3402P0P04\200\340\242T\256p\205<\240\220\027P0K\301D\241\034(\254\340\253\020md\242\020k\240\220\302\005Q\226\313\005\"\r\024r\270\202\271\002\271\0\002\f\0\016\001\016B\n", 71); fNByte += 71; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P19 NewObject(patternNb++); @@ -2775,7 +2794,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211L\216;\016\302@\fD{\237bN\020\331+6a\257\200D\201((P\252@\001R\220\240\341\372\370\263\216(\326\266f\336\330\373&\301\003\304`\b\307\373\334\351\202\227J\a\025\237\020|U\306\021\327\231q\243\306\250\214\325\372T\006\336\367\032\262\326\205\3124\264b\243$\"n.\244=\314\250!\2139\033\327\022i=\323\317\2518\332T}\347.\202\346W\373\372j\315\221\344\266\213=\237\241\344\034\361\264!\236w\344\177\271o8\323\211~\002\f\0\366\3026\233\n", 151); fNByte += 151; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P20 NewObject(patternNb++); @@ -2787,7 +2806,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211write("\r\nH\211D\2151\n\2000\fE\367\234\342\037!)\224\336Ap\020\a\aq\323A\251\202.^\337$-\025\022^\372\033^n\022\354 \006CX\274\237\215&\\\032u\032\036\020\274\032\243\307\2740V]\027\234\024\242\"\033\2642En\324\312\224bc\262\\\230\377\301\332WM\224\212(U\221\375\265\301\025\016?\350\317P\215\221\033\213o\244\201>\001\006\0\031I'f\n", 119); fNByte += 119; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P22 NewObject(patternNb++); @@ -2811,7 +2830,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211<\215=\n\204P\f\204\373\234b\216\220<\b\357\016\302\026ba!vZ(\273\v\332x}\223\274\237\"|\223a\230\271Hp\200\030\fa\211\273w\232\3617k0\363\204\3401\033\037,+c#\3170~\2244\304\327EV\243r\247\272oOcr\337\323]H\t\226\252\334\252r\255\362\257\213(\t\304\250\326\315T\267\032\275q\242\221^\001\006\0\272\367(&\n", 120); fNByte += 120; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P23 NewObject(patternNb++); @@ -2823,7 +2842,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211<\220\273\n\0021\020E\373\371\212[[M\326\331\354\344\027\004\v\261\260\020;\025\224D\320\306\337w\036\254p\363\230\223\341$\344M\005\017\020\203Q8\307\347F'\274\f\355\f>Q\3605\214=\316\005\v.\214kt\217\230;)\324\366\245Fa\213e\320v\212r\022X\006\211Fi\3242\250J\224\302\020\367h\212\254I\\\325R\225o\03143\346U\235@a\t[\202Za\tA\202E`\351~O\002\235`\351~S\202\306h.m\253\264)\232K\217t\310\017q\354\a\353\247\364\377C\356\033\372\t0\0\bm:\375\n", 171); fNByte += 171; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P24 NewObject(patternNb++); @@ -2835,7 +2854,7 @@ void TPDF::PatternEncode() fStream->write("\r\nH\211DQ9N\004A\f\314\373\025\216\211\326\343v\037_@\"@\004\004\210\f\220@\003\022$|\177\335\345j\220v\345\251\303\343*\215\312\273\024\275\\d\375?\361dM\3162\306\337\214\337Y\336n\240m\217\036\301y\343\\<,i\250\0038F\035)\347l\322\026o\377\023\353|[\254\177\343\005;\315\317ky\224\257\240n\203\374\020\225\337\240\345N\236T\272<_\344\245\304^\3238\030\tc\236E\233xO\034\363\204>\251\317\324\233\023{\352\235\376\336S\357Fl\251\017\372\207\247>xoh&_\366Ud\331\253\314D\023\332\241\211\016\205\246\235\326\236*\275\307\204z8!s\031\335\306\\\306C\306\\\225\376\312\\\225\307\252\246\356\364\273Q\347\271:\371\341l\177\311e\210\3571\211\251#\374\302H\037:\342c\241\323\2617\320 \034\250\0\302\323a{\005%\302a\373(Zx\313\026\213@\215p\324}\026=\274e\217E8s\326}\026M\036\312}\271\n0\0\215\263\207\016\n", 282); fNByte += 282; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); // P25 NewObject(patternNb++); @@ -2847,5 +2866,5 @@ void TPDF::PatternEncode() fStream->write("\r\nH\2112T\310T\3402P0P\310\34526P\0\242\034.s\004m\016\242\r\r\f\024@\030\302\002\321iZP\305`M\346\310\212\201R\0\001\006\0\206\322\017\200\n", 56); fNByte += 56; PrintStr("endstream@"); - PrintStr("endobj@"); + EndObject(); } diff --git a/graf2d/postscript/src/TPostScript.cxx b/graf2d/postscript/src/TPostScript.cxx index db6218641baa1..09ea7ffa9c384 100644 --- a/graf2d/postscript/src/TPostScript.cxx +++ b/graf2d/postscript/src/TPostScript.cxx @@ -471,7 +471,7 @@ void TPostScript::Close(Option_t *) } // Rename the file fFileName - TString tmpname = Form("%s_tmp_%d",fFileName.Data(),gSystem->GetPid()); + TString tmpname = TString::Format("%s_tmp_%d",fFileName.Data(),gSystem->GetPid()); if (gSystem->Rename( fFileName.Data() , tmpname.Data())) { Error("Text", "Cannot open temporary file: %s\n", tmpname.Data()); return; @@ -2762,14 +2762,14 @@ void TPostScript::Text(Double_t xx, Double_t yy, const char *chars) Double_t vy = (y - gPad->GetY1())/(gPad->GetY2()-gPad->GetY1()); Double_t cmy = fYsize*(gPad->GetAbsYlowNDC()+vy*gPad->GetAbsHNDC()); WriteReal((288.*cmy)/2.54); - PrintStr(Form(" t %d r ", psangle)); - if(txalh == 2) PrintStr(Form(" %d 0 t ", -psCharsLength/2)); - if(txalh == 3) PrintStr(Form(" %d 0 t ", -psCharsLength)); + PrintStr(TString::Format(" t %d r ", psangle)); + if(txalh == 2) PrintStr(TString::Format(" %d 0 t ", -psCharsLength/2)); + if(txalh == 3) PrintStr(TString::Format(" %d 0 t ", -psCharsLength)); PrintStr(gEnv->GetValue(psfont[font-1][0], psfont[font-1][1])); if (font != 15) { - PrintStr(Form(" findfont %g sf 0 0 m ",fontsize)); + PrintStr(TString::Format(" findfont %g sf 0 0 m ",fontsize)); } else { - PrintStr(Form(" findfont %g sf 0 0 m ita ",fontsize)); + PrintStr(TString::Format(" findfont %g sf 0 0 m ita ",fontsize)); } if (kerning) { @@ -2937,15 +2937,15 @@ void TPostScript::Text(Double_t xx, Double_t yy, const wchar_t *chars) // Output text position and angle. WriteInteger(XtoPS(x)); WriteInteger(YtoPS(y)); - PrintStr(Form(" t %d r ", psangle)); - if(txalh == 2) PrintStr(Form(" %d 0 t ", -psCharsLength/2)); - if(txalh == 3) PrintStr(Form(" %d 0 t ", -psCharsLength)); + PrintStr(TString::Format(" t %d r ", psangle)); + if(txalh == 2) PrintStr(TString::Format(" %d 0 t ", -psCharsLength/2)); + if(txalh == 3) PrintStr(TString::Format(" %d 0 t ", -psCharsLength)); MustEmbed[font-1] = kTRUE; // This font will be embedded in the file at EOF time. PrintStr(gEnv->GetValue(psfont[font-1][0], psfont[font-1][1])); - PrintStr(Form(" findfont %g sf 0 0 m ",fontsize)); + PrintStr(TString::Format(" findfont %g sf 0 0 m ",fontsize)); // Output text. - if (len > 1) PrintStr(Form("%d ", len)); + if (len > 1) PrintStr(TString::Format("%d ", len)); for(Int_t i = 0; i < len; i++) { // Adobe Glyph Naming Convention // http://www.adobe.com/devnet/opentype/archives/glyph.html @@ -2958,16 +2958,16 @@ void TPostScript::Text(Double_t xx, Double_t yy, const wchar_t *chars) // Named glyph from AGL 1.2 const unsigned long index = lower - adobe_glyph_ucs; - PrintStr(Form("/%s ", adobe_glyph_name[index])); + PrintStr(TString::Format("/%s ", adobe_glyph_name[index])); } else if((unsigned int)chars[i] < 0xffff) { // Unicode BMP - PrintStr(Form("/uni%04X ", + PrintStr(TString::Format("/uni%04X ", (unsigned int)chars[i])); } else { // Unicode supplemental planes - PrintStr(Form("/u%04X ", + PrintStr(TString::Format("/u%04X ", (unsigned int)chars[i])); } } diff --git a/graf2d/postscript/src/TSVG.cxx b/graf2d/postscript/src/TSVG.cxx index bf361361ce1e8..33890ad5b96f5 100644 --- a/graf2d/postscript/src/TSVG.cxx +++ b/graf2d/postscript/src/TSVG.cxx @@ -360,9 +360,9 @@ void TSVG::DrawFrame(Double_t xl, Double_t yl, Double_t xt, Double_t yt, SetColorAlpha(light); } if (fgLineJoin) - PrintStr(Form(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); + PrintStr(TString::Format(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); if (fgLineCap) - PrintStr(Form(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); + PrintStr(TString::Format(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); PrintFast(2,"/>"); //- Draw bottom&right part of the box @@ -428,9 +428,9 @@ void TSVG::DrawFrame(Double_t xl, Double_t yl, Double_t xt, Double_t yt, SetColorAlpha(dark); } if (fgLineJoin) - PrintStr(Form(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); + PrintStr(TString::Format(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); if (fgLineCap) - PrintStr(Form(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); + PrintStr(TString::Format(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); PrintFast(2,"/>"); } @@ -625,9 +625,9 @@ void TSVG::DrawPolyMarker(Int_t n, Float_t *xw, Float_t *yw) WriteReal(TMath::Max(1, Int_t(TAttMarker::GetMarkerLineWidth(fMarkerStyle))), kFALSE); PrintStr("\" fill=\"none\""); if (fgLineJoin) - PrintStr(Form(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); + PrintStr(TString::Format(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); if (fgLineCap) - PrintStr(Form(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); + PrintStr(TString::Format(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); PrintStr(">"); } Double_t ix,iy; @@ -1034,9 +1034,9 @@ void TSVG::DrawPolyMarker(Int_t n, Double_t *xw, Double_t *yw) WriteReal(TMath::Max(1, Int_t(TAttMarker::GetMarkerLineWidth(fMarkerStyle))), kFALSE); PrintStr("\" fill=\"none\""); if (fgLineJoin) - PrintStr(Form(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); + PrintStr(TString::Format(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); if (fgLineCap) - PrintStr(Form(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); + PrintStr(TString::Format(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); PrintStr(">"); } Double_t ix,iy; @@ -1494,9 +1494,9 @@ void TSVG::DrawPS(Int_t nn, Double_t *xw, Double_t *yw) } } if (fgLineJoin) - PrintStr(Form(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); + PrintStr(TString::Format(" stroke-linejoin=\"%s\"", fgLineJoin == 1 ? "round" : "bevel")); if (fgLineCap) - PrintStr(Form(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); + PrintStr(TString::Format(" stroke-linecap=\"%s\"", fgLineCap == 1 ? "round" : "square")); PrintFast(2,"/>"); } @@ -1703,7 +1703,7 @@ void TSVG::SetColorAlpha(Int_t color) if (col) { SetColor(col->GetRed(), col->GetGreen(), col->GetBlue()); Float_t a = col->GetAlpha(); - if (a<1.) PrintStr(Form(" fill-opacity=\"%3.2f\" stroke-opacity=\"%3.2f\"",a,a)); + if (a<1.) PrintStr(TString::Format(" fill-opacity=\"%3.2f\" stroke-opacity=\"%3.2f\"",a,a)); } else { SetColor(1., 1., 1.); } diff --git a/graf2d/postscript/src/TTeXDump.cxx b/graf2d/postscript/src/TTeXDump.cxx index 33c89a8815d64..4f86fcaea269f 100644 --- a/graf2d/postscript/src/TTeXDump.cxx +++ b/graf2d/postscript/src/TTeXDump.cxx @@ -447,8 +447,8 @@ void TTeXDump::DrawPolyMarker(Int_t n, Double_t *xw, Double_t *yw) if (TAttMarker::GetMarkerStyleBase(fMarkerStyle) == 23 || TAttMarker::GetMarkerStyleBase(fMarkerStyle) == 32) PrintStr(",rotate=180"); - PrintStr(Form("},mark size=%fpt", 8./3.33*(fMarkerSize - TMath::Floor(TAttMarker::GetMarkerLineWidth(fMarkerStyle)/2.)/4.))); - PrintStr(Form(", line width=%fpt", 4./3.33*TMath::Floor(TAttMarker::GetMarkerLineWidth(fMarkerStyle)/2.))); + PrintStr(TString::Format("},mark size=%fpt", 8./3.33*(fMarkerSize - TMath::Floor(TAttMarker::GetMarkerLineWidth(fMarkerStyle)/2.)/4.))); + PrintStr(TString::Format(", line width=%fpt", 4./3.33*TMath::Floor(TAttMarker::GetMarkerLineWidth(fMarkerStyle)/2.))); PrintStr(", mark="); switch (TAttMarker::GetMarkerStyleBase(fMarkerStyle)) { case 1 : diff --git a/graf2d/quartz/src/QuartzMarker.mm b/graf2d/quartz/src/QuartzMarker.mm index 16bdad6bbe994..87af296b0cb6a 100644 --- a/graf2d/quartz/src/QuartzMarker.mm +++ b/graf2d/quartz/src/QuartzMarker.mm @@ -18,10 +18,11 @@ //______________________________________________________________________________ -void DrawMarkerDot(CGContextRef ctx, unsigned n, const TPoint *xy) +void DrawMarkerDot(CGContextRef ctx, unsigned n, const TPoint *xy, + Size_t markerSize) { for (unsigned i = 0; i < n; ++i) - CGContextFillRect(ctx, CGRectMake(xy[i].fX, xy[i].fY, 1.f, 1.f)); + CGContextFillRect(ctx, CGRectMake(xy[i].fX, xy[i].fY, markerSize, markerSize)); } @@ -909,7 +910,7 @@ void DrawPolyMarker(CGContextRef ctx, unsigned nPoints, const TPoint *xy, { switch (markerStyle) { case kDot: - DrawMarkerDot(ctx, nPoints, xy); + DrawMarkerDot(ctx, nPoints, xy, markerSize); break; case kPlus: DrawMarkerPlus(ctx, nPoints, xy, markerSize); diff --git a/graf2d/win32gdk/gdk/src/gdk/makefile.msc b/graf2d/win32gdk/gdk/src/gdk/makefile.msc index 274620807f8c9..58e33321133b2 100644 --- a/graf2d/win32gdk/gdk/src/gdk/makefile.msc +++ b/graf2d/win32gdk/gdk/src/gdk/makefile.msc @@ -32,7 +32,7 @@ CC = cl -GR $(OPTIMIZE) -W3 -nologo CC = cl -nologo $(NMCXXFLAGS) !endif -LDFLAGS = /link $(LINKDEBUG) +LDFLAGS = /link $(LINKDEBUG) /ignore:4197 GLIB_VER=1.3 GTK_VER=1.3 diff --git a/graf2d/win32gdk/gdk/src/gdk/win32/makefile.msc b/graf2d/win32gdk/gdk/src/gdk/win32/makefile.msc index a46bd061b0f63..0cd5d484b5194 100644 --- a/graf2d/win32gdk/gdk/src/gdk/win32/makefile.msc +++ b/graf2d/win32gdk/gdk/src/gdk/win32/makefile.msc @@ -26,7 +26,7 @@ CC = cl -GR $(OPTIMIZE) -W3 -nologo CC = cl -nologo $(NMCXXFLAGS) !endif -LDFLAGS = /link $(LINKDEBUG) +LDFLAGS = /link $(LINKDEBUG) /ignore:4197 GLIB_VER=1.3 GTK_VER=1.3 diff --git a/graf2d/win32gdk/gdk/src/glib/gcompat.h b/graf2d/win32gdk/gdk/src/glib/gcompat.h deleted file mode 100644 index 10ef4457e1111..0000000000000 --- a/graf2d/win32gdk/gdk/src/glib/gcompat.h +++ /dev/null @@ -1,45 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * - * Copyright (C) 2000 Ali Abdin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef __G_COMPAT_H__ -#define __G_COMPAT_H__ - -#include - -G_BEGIN_DECLS - -#ifndef G_DISABLE_COMPAT_H - -#define g_date_weekday g_date_get_weekday -#define g_date_month g_date_get_month -#define g_date_year g_date_get_year -#define g_date_day g_date_get_day -#define g_date_julian g_date_get_julian -#define g_date_day_of_year g_date_get_day_of_year -#define g_date_monday_week_of_year g_date_get_monday_week_of_year -#define g_date_sunday_week_of_year g_date_get_sunday_week_of_year -#define g_date_days_in_month g_date_get_days_in_month -#define g_date_monday_weeks_in_year g_date_get_monday_weeks_in_year -#define g_date_sunday_weeks_in_year g_date_get_sunday_weeks_in_year - -#endif /* G_DISABLE_COMPAT_H */ - -G_END_DECLS - -#endif /* __G_COMPAT_H__ */ diff --git a/graf2d/win32gdk/gdk/src/iconv/makefile.msc b/graf2d/win32gdk/gdk/src/iconv/makefile.msc index f51f4d05f0ec8..da365771b85b7 100644 --- a/graf2d/win32gdk/gdk/src/iconv/makefile.msc +++ b/graf2d/win32gdk/gdk/src/iconv/makefile.msc @@ -56,7 +56,6 @@ all : \ iconv-$(ICONV_VER).dll iconv_OBJECTS = \ - relocatable.obj \ localcharset.obj \ iconv.obj \ diff --git a/graf2d/win32gdk/gdk/src/iconv/relocatable.c b/graf2d/win32gdk/gdk/src/iconv/relocatable.c deleted file mode 100644 index bfbaaaca22d72..0000000000000 --- a/graf2d/win32gdk/gdk/src/iconv/relocatable.c +++ /dev/null @@ -1,493 +0,0 @@ -/* Provide relocatable packages. - Copyright (C) 2003-2006, 2008 Free Software Foundation, Inc. - Written by Bruno Haible , 2003. - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published - by the Free Software Foundation; either version 3, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - USA. */ - - -/* Tell glibc's to provide a prototype for getline(). - This must come before because may include - , and once has been included, it's too late. */ -#ifndef _GNU_SOURCE -# define _GNU_SOURCE 1 -#endif - -#include - -/* Specification. */ -#include "relocatable.h" - -#if ENABLE_RELOCATABLE - -#include -#include -#include -#include - -#ifdef NO_XMALLOC -# define xmalloc malloc -#else -# include "xalloc.h" -#endif - -#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ -# define WIN32_LEAN_AND_MEAN -# include -#endif - -#if DEPENDS_ON_LIBCHARSET -# include -#endif -#if DEPENDS_ON_LIBICONV && HAVE_ICONV -# include -#endif -#if DEPENDS_ON_LIBINTL && ENABLE_NLS -# include -#endif - -/* Faked cheap 'bool'. */ -#undef bool -#undef false -#undef true -#define bool int -#define false 0 -#define true 1 - -/* Pathname support. - ISSLASH(C) tests whether C is a directory separator character. - IS_PATH_WITH_DIR(P) tests whether P contains a directory specification. - */ -#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__ - /* Win32, Cygwin, OS/2, DOS */ -# define ISSLASH(C) ((C) == '/' || (C) == '\\') -# define HAS_DEVICE(P) \ - ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \ - && (P)[1] == ':') -# define IS_PATH_WITH_DIR(P) \ - (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P)) -# define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0) -#else - /* Unix */ -# define ISSLASH(C) ((C) == '/') -# define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL) -# define FILE_SYSTEM_PREFIX_LEN(P) 0 -#endif - -/* Original installation prefix. */ -static char *orig_prefix; -static size_t orig_prefix_len; -/* Current installation prefix. */ -static char *curr_prefix; -static size_t curr_prefix_len; -/* These prefixes do not end in a slash. Anything that will be concatenated - to them must start with a slash. */ - -/* Sets the original and the current installation prefix of this module. - Relocation simply replaces a pathname starting with the original prefix - by the corresponding pathname with the current prefix instead. Both - prefixes should be directory names without trailing slash (i.e. use "" - instead of "/"). */ -static void -set_this_relocation_prefix (const char *orig_prefix_arg, - const char *curr_prefix_arg) -{ - if (orig_prefix_arg != NULL && curr_prefix_arg != NULL - /* Optimization: if orig_prefix and curr_prefix are equal, the - relocation is a nop. */ - && strcmp (orig_prefix_arg, curr_prefix_arg) != 0) - { - /* Duplicate the argument strings. */ - char *memory; - - orig_prefix_len = strlen (orig_prefix_arg); - curr_prefix_len = strlen (curr_prefix_arg); - memory = (char *) xmalloc (orig_prefix_len + 1 + curr_prefix_len + 1); -#ifdef NO_XMALLOC - if (memory != NULL) -#endif - { - memcpy (memory, orig_prefix_arg, orig_prefix_len + 1); - orig_prefix = memory; - memory += orig_prefix_len + 1; - memcpy (memory, curr_prefix_arg, curr_prefix_len + 1); - curr_prefix = memory; - return; - } - } - orig_prefix = NULL; - curr_prefix = NULL; - /* Don't worry about wasted memory here - this function is usually only - called once. */ -} - -/* Sets the original and the current installation prefix of the package. - Relocation simply replaces a pathname starting with the original prefix - by the corresponding pathname with the current prefix instead. Both - prefixes should be directory names without trailing slash (i.e. use "" - instead of "/"). */ -void -set_relocation_prefix (const char *orig_prefix_arg, const char *curr_prefix_arg) -{ - set_this_relocation_prefix (orig_prefix_arg, curr_prefix_arg); - - /* Now notify all dependent libraries. */ -#if DEPENDS_ON_LIBCHARSET - libcharset_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); -#endif -#if DEPENDS_ON_LIBICONV && HAVE_ICONV && _LIBICONV_VERSION >= 0x0109 - libiconv_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); -#endif -#if DEPENDS_ON_LIBINTL && ENABLE_NLS && defined libintl_set_relocation_prefix - libintl_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); -#endif -} - -#if !defined IN_LIBRARY || (defined PIC && defined INSTALLDIR) - -/* Convenience function: - Computes the current installation prefix, based on the original - installation prefix, the original installation directory of a particular - file, and the current pathname of this file. - Returns it, freshly allocated. Returns NULL upon failure. */ -#ifdef IN_LIBRARY -#define compute_curr_prefix local_compute_curr_prefix -static -#endif -char * -compute_curr_prefix (const char *orig_installprefix, - const char *orig_installdir, - const char *curr_pathname) -{ - char *curr_installdir; - const char *rel_installdir; - - if (curr_pathname == NULL) - return NULL; - - /* Determine the relative installation directory, relative to the prefix. - This is simply the difference between orig_installprefix and - orig_installdir. */ - if (strncmp (orig_installprefix, orig_installdir, strlen (orig_installprefix)) - != 0) - /* Shouldn't happen - nothing should be installed outside $(prefix). */ - return NULL; - rel_installdir = orig_installdir + strlen (orig_installprefix); - - /* Determine the current installation directory. */ - { - const char *p_base = curr_pathname + FILE_SYSTEM_PREFIX_LEN (curr_pathname); - const char *p = curr_pathname + strlen (curr_pathname); - char *q; - - while (p > p_base) - { - p--; - if (ISSLASH (*p)) - break; - } - - q = (char *) xmalloc (p - curr_pathname + 1); -#ifdef NO_XMALLOC - if (q == NULL) - return NULL; -#endif - memcpy (q, curr_pathname, p - curr_pathname); - q[p - curr_pathname] = '\0'; - curr_installdir = q; - } - - /* Compute the current installation prefix by removing the trailing - rel_installdir from it. */ - { - const char *rp = rel_installdir + strlen (rel_installdir); - const char *cp = curr_installdir + strlen (curr_installdir); - const char *cp_base = - curr_installdir + FILE_SYSTEM_PREFIX_LEN (curr_installdir); - - while (rp > rel_installdir && cp > cp_base) - { - bool same = false; - const char *rpi = rp; - const char *cpi = cp; - - while (rpi > rel_installdir && cpi > cp_base) - { - rpi--; - cpi--; - if (ISSLASH (*rpi) || ISSLASH (*cpi)) - { - if (ISSLASH (*rpi) && ISSLASH (*cpi)) - same = true; - break; - } - /* Do case-insensitive comparison if the filesystem is always or - often case-insensitive. It's better to accept the comparison - if the difference is only in case, rather than to fail. */ -#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__ - /* Win32, Cygwin, OS/2, DOS - case insignificant filesystem */ - if ((*rpi >= 'a' && *rpi <= 'z' ? *rpi - 'a' + 'A' : *rpi) - != (*cpi >= 'a' && *cpi <= 'z' ? *cpi - 'a' + 'A' : *cpi)) - break; -#else - if (*rpi != *cpi) - break; -#endif - } - if (!same) - break; - /* The last pathname component was the same. opi and cpi now point - to the slash before it. */ - rp = rpi; - cp = cpi; - } - - if (rp > rel_installdir) - { - /* Unexpected: The curr_installdir does not end with rel_installdir. */ - free (curr_installdir); - return NULL; - } - - { - size_t curr_prefix_len = cp - curr_installdir; - char *curr_prefix; - - curr_prefix = (char *) xmalloc (curr_prefix_len + 1); -#ifdef NO_XMALLOC - if (curr_prefix == NULL) - { - free (curr_installdir); - return NULL; - } -#endif - memcpy (curr_prefix, curr_installdir, curr_prefix_len); - curr_prefix[curr_prefix_len] = '\0'; - - free (curr_installdir); - - return curr_prefix; - } - } -} - -#endif /* !IN_LIBRARY || PIC */ - -#if defined PIC && defined INSTALLDIR - -/* Full pathname of shared library, or NULL. */ -static char *shared_library_fullname; - -#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ - -/* Determine the full pathname of the shared library when it is loaded. */ - -BOOL WINAPI -DllMain (HINSTANCE module_handle, DWORD event, LPVOID reserved) -{ - (void) reserved; - - if (event == DLL_PROCESS_ATTACH) - { - /* The DLL is being loaded into an application's address range. */ - static char location[MAX_PATH]; - - if (!GetModuleFileName (module_handle, location, sizeof (location))) - /* Shouldn't happen. */ - return FALSE; - - if (!IS_PATH_WITH_DIR (location)) - /* Shouldn't happen. */ - return FALSE; - - { -#if defined __CYGWIN__ - /* On Cygwin, we need to convert paths coming from Win32 system calls - to the Unix-like slashified notation. */ - static char location_as_posix_path[2 * MAX_PATH]; - /* There's no error return defined for cygwin_conv_to_posix_path. - See cygwin-api/func-cygwin-conv-to-posix-path.html. - Does it overflow the buffer of expected size MAX_PATH or does it - truncate the path? I don't know. Let's catch both. */ - cygwin_conv_to_posix_path (location, location_as_posix_path); - location_as_posix_path[MAX_PATH - 1] = '\0'; - if (strlen (location_as_posix_path) >= MAX_PATH - 1) - /* A sign of buffer overflow or path truncation. */ - return FALSE; - shared_library_fullname = strdup (location_as_posix_path); -#else - shared_library_fullname = strdup (location); -#endif - } - } - - return TRUE; -} - -#else /* Unix except Cygwin */ - -static void -find_shared_library_fullname () -{ -#if defined __linux__ && __GLIBC__ >= 2 - /* Linux has /proc/self/maps. glibc 2 has the getline() function. */ - FILE *fp; - - /* Open the current process' maps file. It describes one VMA per line. */ - fp = fopen ("/proc/self/maps", "r"); - if (fp) - { - unsigned long address = (unsigned long) &find_shared_library_fullname; - for (;;) - { - unsigned long start, end; - int c; - - if (fscanf (fp, "%lx-%lx", &start, &end) != 2) - break; - if (address >= start && address <= end - 1) - { - /* Found it. Now see if this line contains a filename. */ - while (c = getc (fp), c != EOF && c != '\n' && c != '/') - continue; - if (c == '/') - { - size_t size; - int len; - - ungetc (c, fp); - shared_library_fullname = NULL; size = 0; - len = getline (&shared_library_fullname, &size, fp); - if (len >= 0) - { - /* Success: filled shared_library_fullname. */ - if (len > 0 && shared_library_fullname[len - 1] == '\n') - shared_library_fullname[len - 1] = '\0'; - } - } - break; - } - while (c = getc (fp), c != EOF && c != '\n') - continue; - } - fclose (fp); - } -#endif -} - -#endif /* (WIN32 or Cygwin) / (Unix except Cygwin) */ - -/* Return the full pathname of the current shared library. - Return NULL if unknown. - Guaranteed to work only on Linux, Cygwin and Woe32. */ -static char * -get_shared_library_fullname () -{ -#if !(defined _WIN32 || defined __WIN32__ || defined __CYGWIN__) - static bool tried_find_shared_library_fullname; - if (!tried_find_shared_library_fullname) - { - find_shared_library_fullname (); - tried_find_shared_library_fullname = true; - } -#endif - return shared_library_fullname; -} - -#endif /* PIC */ - -/* Returns the pathname, relocated according to the current installation - directory. - The returned string is either PATHNAME unmodified or a freshly allocated - string that you can free with free() after casting it to 'char *'. */ -const char * -relocate (const char *pathname) -{ -#if defined PIC && defined INSTALLDIR - static int initialized; - - /* Initialization code for a shared library. */ - if (!initialized) - { - /* At this point, orig_prefix and curr_prefix likely have already been - set through the main program's set_program_name_and_installdir - function. This is sufficient in the case that the library has - initially been installed in the same orig_prefix. But we can do - better, to also cover the cases that 1. it has been installed - in a different prefix before being moved to orig_prefix and (later) - to curr_prefix, 2. unlike the program, it has not moved away from - orig_prefix. */ - const char *orig_installprefix = INSTALLPREFIX; - const char *orig_installdir = INSTALLDIR; - char *curr_prefix_better; - - curr_prefix_better = - compute_curr_prefix (orig_installprefix, orig_installdir, - get_shared_library_fullname ()); - - set_relocation_prefix (orig_installprefix, - curr_prefix_better != NULL - ? curr_prefix_better - : curr_prefix); - - if (curr_prefix_better != NULL) - free (curr_prefix_better); - - initialized = 1; - } -#endif - - /* Note: It is not necessary to perform case insensitive comparison here, - even for DOS-like filesystems, because the pathname argument was - typically created from the same Makefile variable as orig_prefix came - from. */ - if (orig_prefix != NULL && curr_prefix != NULL - && strncmp (pathname, orig_prefix, orig_prefix_len) == 0) - { - if (pathname[orig_prefix_len] == '\0') - { - /* pathname equals orig_prefix. */ - char *result = (char *) xmalloc (strlen (curr_prefix) + 1); - -#ifdef NO_XMALLOC - if (result != NULL) -#endif - { - strcpy (result, curr_prefix); - return result; - } - } - else if (ISSLASH (pathname[orig_prefix_len])) - { - /* pathname starts with orig_prefix. */ - const char *pathname_tail = &pathname[orig_prefix_len]; - char *result = - (char *) xmalloc (curr_prefix_len + strlen (pathname_tail) + 1); - -#ifdef NO_XMALLOC - if (result != NULL) -#endif - { - memcpy (result, curr_prefix, curr_prefix_len); - strcpy (result + curr_prefix_len, pathname_tail); - return result; - } - } - } - /* Nothing to relocate. */ - return pathname; -} - -#endif diff --git a/graf2d/win32gdk/gdk/src/iconv/relocatable.h b/graf2d/win32gdk/gdk/src/iconv/relocatable.h deleted file mode 100644 index 9d975b9d88dbc..0000000000000 --- a/graf2d/win32gdk/gdk/src/iconv/relocatable.h +++ /dev/null @@ -1,83 +0,0 @@ -/* Provide relocatable packages. - Copyright (C) 2003, 2005, 2008 Free Software Foundation, Inc. - Written by Bruno Haible , 2003. - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published - by the Free Software Foundation; either version 3, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - USA. */ - -#ifndef _RELOCATABLE_H -#define _RELOCATABLE_H - -#ifdef __cplusplus -extern "C" { -#endif - - -/* This can be enabled through the configure --enable-relocatable option. */ -#if ENABLE_RELOCATABLE - -/* When building a DLL, we must export some functions. Note that because - this is a private .h file, we don't need to use __declspec(dllimport) - in any case. */ -#if HAVE_VISIBILITY && BUILDING_DLL -# define RELOCATABLE_DLL_EXPORTED __attribute__((__visibility__("default"))) -#elif defined _MSC_VER && BUILDING_DLL -# define RELOCATABLE_DLL_EXPORTED __declspec(dllexport) -#else -# define RELOCATABLE_DLL_EXPORTED -#endif - -/* Sets the original and the current installation prefix of the package. - Relocation simply replaces a pathname starting with the original prefix - by the corresponding pathname with the current prefix instead. Both - prefixes should be directory names without trailing slash (i.e. use "" - instead of "/"). */ -extern RELOCATABLE_DLL_EXPORTED void - set_relocation_prefix (const char *orig_prefix, - const char *curr_prefix); - -/* Returns the pathname, relocated according to the current installation - directory. - The returned string is either PATHNAME unmodified or a freshly allocated - string that you can free with free() after casting it to 'char *'. */ -extern const char * relocate (const char *pathname); - -/* Memory management: relocate() potentially allocates memory, because it has - to construct a fresh pathname. If this is a problem because your program - calls relocate() frequently, think about caching the result. Or free the - return value if it was different from the argument pathname. */ - -/* Convenience function: - Computes the current installation prefix, based on the original - installation prefix, the original installation directory of a particular - file, and the current pathname of this file. - Returns it, freshly allocated. Returns NULL upon failure. */ -extern char * compute_curr_prefix (const char *orig_installprefix, - const char *orig_installdir, - const char *curr_pathname); - -#else - -/* By default, we use the hardwired pathnames. */ -#define relocate(pathname) (pathname) - -#endif - - -#ifdef __cplusplus -} -#endif - -#endif /* _RELOCATABLE_H */ diff --git a/graf2d/win32gdk/inc/TGWin32.h b/graf2d/win32gdk/inc/TGWin32.h index a52d682a5ec21..ef6e849267bb9 100644 --- a/graf2d/win32gdk/inc/TGWin32.h +++ b/graf2d/win32gdk/inc/TGWin32.h @@ -152,253 +152,253 @@ class TGWin32 : public TVirtualX { virtual ~TGWin32(); void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, - const char *text, ETextMode mode); + const char *text, ETextMode mode) override; void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, - const wchar_t *text, ETextMode mode); - void SetTextFont(Font_t fontnumber); - Int_t SetTextFont(char *fontname, ETextSetMode mode); - void SetTextSize(Float_t textsize); + const wchar_t *text, ETextMode mode) override; + void SetTextFont(Font_t fontnumber) override; + Int_t SetTextFont(char *fontname, ETextSetMode mode) override; + void SetTextSize(Float_t textsize) override; - Bool_t Init(void *display=0); + Bool_t Init(void *display=0) override; //UInt_t ExecCommand(TGWin32Command *); - void ClearWindow(); - void ClosePixmap(); - void CloseWindow(); - void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos); - void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, EBoxMode mode); - void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, Int_t nx, Int_t ny, Int_t *ic); - void DrawFillArea(Int_t n, TPoint *xy); - void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2); - void DrawPolyLine(Int_t n, TPoint *xy); - void DrawPolyMarker(Int_t n, TPoint *xy); - void GetCharacterUp(Float_t &chupx, Float_t &chupy); - Int_t GetDoubleBuffer(Int_t wid); - void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); - const char *DisplayName(const char *dpyName = 0); - ULong_t GetPixel(Color_t cindex); - void GetPlanes(Int_t &nplanes); - void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b); - virtual void GetTextExtent(UInt_t &w, UInt_t &h, char *mess); - virtual void GetTextExtent(UInt_t &, UInt_t &, wchar_t *){} - Float_t GetTextMagnitude() {return fTextMagnitude;} - Window_t GetWindowID(Int_t wid); - Bool_t HasTTFonts() const { return fHasTTFonts; } - Int_t InitWindow(ULongptr_t window); - Int_t AddPixmap(ULongptr_t pix, UInt_t w, UInt_t h); - void MoveWindow(Int_t wid, Int_t x, Int_t y); - Int_t OpenPixmap(UInt_t w, UInt_t h); - void QueryPointer(Int_t &ix, Int_t &iy); - Pixmap_t ReadGIF(Int_t x0, Int_t y0, const char *file, Window_t id=0); - Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y); - Int_t RequestString(Int_t x, Int_t y, char *text); - void RescaleWindow(Int_t wid, UInt_t w, UInt_t h); - Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h); - void ResizeWindow(Int_t wid); - void SelectWindow(Int_t wid); - void SetCharacterUp(Float_t chupx, Float_t chupy); - void SetClipOFF(Int_t wid); - void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); - void SetCursor(Int_t wid, ECursor cursor); - void SetDoubleBuffer(Int_t wid, Int_t mode); - void SetDoubleBufferOFF(); - void SetDoubleBufferON(); - void SetDrawMode(EDrawMode mode); - void SetFillColor(Color_t cindex); - void SetFillStyle(Style_t style); - void SetLineColor(Color_t cindex); - void SetLineType(Int_t n, Int_t *dash); - void SetLineStyle(Style_t linestyle); - void SetLineWidth(Width_t width); - void SetMarkerColor(Color_t cindex); - void SetMarkerSize(Float_t markersize); - void SetMarkerStyle(Style_t markerstyle); - void SetOpacity(Int_t percent); - void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b); - void SetTextAlign(Short_t talign=11); - void SetTextColor(Color_t cindex); - void SetTextMagnitude(Float_t mgn=1) { fTextMagnitude = mgn;} - void Sync(Int_t mode); - void UpdateWindow(Int_t mode); - void Warp(Int_t ix, Int_t iy, Window_t id = 0); - Int_t WriteGIF(char *name); - void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname); - Window_t GetCurrentWindow() const; + void ClearWindow() override; + void ClosePixmap() override; + void CloseWindow() override; + void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos) override; + void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, EBoxMode mode) override; + void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, Int_t nx, Int_t ny, Int_t *ic) override; + void DrawFillArea(Int_t n, TPoint *xy) override; + void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; + void DrawPolyLine(Int_t n, TPoint *xy) override; + void DrawPolyMarker(Int_t n, TPoint *xy) override; + void GetCharacterUp(Float_t &chupx, Float_t &chupy) override; + Int_t GetDoubleBuffer(Int_t wid) override; + void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; + const char *DisplayName(const char *dpyName = 0) override; + ULong_t GetPixel(Color_t cindex) override; + void GetPlanes(Int_t &nplanes) override; + void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b) override; + virtual void GetTextExtent(UInt_t &w, UInt_t &h, char *mess) override; + virtual void GetTextExtent(UInt_t &, UInt_t &, wchar_t *) override {} + Float_t GetTextMagnitude() override {return fTextMagnitude;} + Window_t GetWindowID(Int_t wid) override; + Bool_t HasTTFonts() const override { return fHasTTFonts; } + Int_t InitWindow(ULongptr_t window) override; + Int_t AddPixmap(ULongptr_t pix, UInt_t w, UInt_t h) override; + void MoveWindow(Int_t wid, Int_t x, Int_t y) override; + Int_t OpenPixmap(UInt_t w, UInt_t h) override; + void QueryPointer(Int_t &ix, Int_t &iy) override; + Pixmap_t ReadGIF(Int_t x0, Int_t y0, const char *file, Window_t id=0) override; + Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y) override; + Int_t RequestString(Int_t x, Int_t y, char *text) override; + void RescaleWindow(Int_t wid, UInt_t w, UInt_t h) override; + Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h) override; + void ResizeWindow(Int_t wid) override; + void SelectWindow(Int_t wid) override; + void SetCharacterUp(Float_t chupx, Float_t chupy) override; + void SetClipOFF(Int_t wid) override; + void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void SetCursor(Int_t wid, ECursor cursor) override; + void SetDoubleBuffer(Int_t wid, Int_t mode) override; + void SetDoubleBufferOFF() override; + void SetDoubleBufferON() override; + void SetDrawMode(EDrawMode mode) override; + void SetFillColor(Color_t cindex) override; + void SetFillStyle(Style_t style) override; + void SetLineColor(Color_t cindex) override; + void SetLineType(Int_t n, Int_t *dash) override; + void SetLineStyle(Style_t linestyle) override; + void SetLineWidth(Width_t width) override; + void SetMarkerColor(Color_t cindex) override; + void SetMarkerSize(Float_t markersize) override; + void SetMarkerStyle(Style_t markerstyle) override; + void SetOpacity(Int_t percent) override; + void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b) override; + void SetTextAlign(Short_t talign=11) override; + void SetTextColor(Color_t cindex) override; + void SetTextMagnitude(Float_t mgn=1) override { fTextMagnitude = mgn;} + void Sync(Int_t mode) override; + void UpdateWindow(Int_t mode) override; + void Warp(Int_t ix, Int_t iy, Window_t id = 0) override; + Int_t WriteGIF(char *name) override; + void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname) override; + Window_t GetCurrentWindow() const override; //---- Methods used for GUI ----- - void GetWindowAttributes(Window_t id, WindowAttributes_t &attr); - void MapWindow(Window_t id); - void MapSubwindows(Window_t id); - void MapRaised(Window_t id); - void UnmapWindow(Window_t id); - void DestroyWindow(Window_t id); - void DestroySubwindows(Window_t id); - void RaiseWindow(Window_t id); - void LowerWindow(Window_t id); - void MoveWindow(Window_t id, Int_t x, Int_t y); - void MoveResizeWindow(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h); - void ResizeWindow(Window_t id, UInt_t w, UInt_t h); - void IconifyWindow(Window_t id); - void ReparentWindow(Window_t id, Window_t pid, Int_t x, Int_t y); - void SetWindowBackground(Window_t id, ULong_t color); - void SetWindowBackgroundPixmap(Window_t id, Pixmap_t pxm); + void GetWindowAttributes(Window_t id, WindowAttributes_t &attr) override; + void MapWindow(Window_t id) override; + void MapSubwindows(Window_t id) override; + void MapRaised(Window_t id) override; + void UnmapWindow(Window_t id) override; + void DestroyWindow(Window_t id) override; + void DestroySubwindows(Window_t id) override; + void RaiseWindow(Window_t id) override; + void LowerWindow(Window_t id) override; + void MoveWindow(Window_t id, Int_t x, Int_t y) override; + void MoveResizeWindow(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void ResizeWindow(Window_t id, UInt_t w, UInt_t h) override; + void IconifyWindow(Window_t id) override; + void ReparentWindow(Window_t id, Window_t pid, Int_t x, Int_t y) override; + void SetWindowBackground(Window_t id, ULong_t color) override; + void SetWindowBackgroundPixmap(Window_t id, Pixmap_t pxm) override; Window_t CreateWindow(Window_t parent, Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t border, Int_t depth, UInt_t clss, void *visual, SetWindowAttributes_t *attr, - UInt_t wtype); - Int_t OpenDisplay(const char *dpyName=0); - void CloseDisplay(); - Display_t GetDisplay() const; - Visual_t GetVisual() const { return 0; } - Int_t GetScreen() const { return 0; } - Int_t GetDepth() const; - Colormap_t GetColormap() const { return (Colormap_t) fColormap; } - Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist); - Window_t GetDefaultRootWindow() const; - Window_t GetParent(Window_t id) const; - FontStruct_t LoadQueryFont(const char *font_name); - FontH_t GetFontHandle(FontStruct_t fs); - void DeleteFont(FontStruct_t fs); - GContext_t CreateGC(Drawable_t id, GCValues_t *gval); - void ChangeGC(GContext_t gc, GCValues_t *gval); - void CopyGC(GContext_t org, GContext_t dest, Mask_t mask); - void DeleteGC(GContext_t gc); - Cursor_t CreateCursor(ECursor cursor); - void SetCursor(Window_t id, Cursor_t curid); - Pixmap_t CreatePixmap(Drawable_t id, UInt_t w, UInt_t h); + UInt_t wtype) override; + Int_t OpenDisplay(const char *dpyName=0) override; + void CloseDisplay() override; + Display_t GetDisplay() const override; + Visual_t GetVisual() const override { return 0; } + Int_t GetScreen() const override { return 0; } + Int_t GetDepth() const override; + Colormap_t GetColormap() const override { return (Colormap_t) fColormap; } + Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist) override; + Window_t GetDefaultRootWindow() const override; + Window_t GetParent(Window_t id) const override; + FontStruct_t LoadQueryFont(const char *font_name) override; + FontH_t GetFontHandle(FontStruct_t fs) override; + void DeleteFont(FontStruct_t fs) override; + GContext_t CreateGC(Drawable_t id, GCValues_t *gval) override; + void ChangeGC(GContext_t gc, GCValues_t *gval) override; + void CopyGC(GContext_t org, GContext_t dest, Mask_t mask) override; + void DeleteGC(GContext_t gc) override; + Cursor_t CreateCursor(ECursor cursor) override; + void SetCursor(Window_t id, Cursor_t curid) override; + Pixmap_t CreatePixmap(Drawable_t id, UInt_t w, UInt_t h) override; Pixmap_t CreatePixmap(Drawable_t id, const char *bitmap, UInt_t width, UInt_t height, ULong_t forecolor, ULong_t backcolor, - Int_t depth); - Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height); + Int_t depth) override; + Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height) override; Pixmap_t CreateBitmap(Drawable_t id, const char *bitmap, - UInt_t width, UInt_t height); - void DeletePixmap(Pixmap_t pmap); + UInt_t width, UInt_t height) override; + void DeletePixmap(Pixmap_t pmap) override; Bool_t CreatePictureFromFile(Drawable_t id, const char *filename, Pixmap_t &pict, Pixmap_t &pict_mask, - PictureAttributes_t &attr); + PictureAttributes_t &attr) override; Bool_t CreatePictureFromData(Drawable_t id, char **data, Pixmap_t &pict, Pixmap_t &pict_mask, - PictureAttributes_t &attr); - Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data); - void DeletePictureData(void *data); - void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n); - Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color); - Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color); - void QueryColor(Colormap_t cmap, ColorStruct_t &color); - void FreeColor(Colormap_t cmap, ULong_t pixel); - Int_t EventsPending(); - void NextEvent(Event_t &event); - void Bell(Int_t percent); + PictureAttributes_t &attr) override; + Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data) override; + void DeletePictureData(void *data) override; + void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n) override; + Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color) override; + Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color) override; + void QueryColor(Colormap_t cmap, ColorStruct_t &color) override; + void FreeColor(Colormap_t cmap, ULong_t pixel) override; + Int_t EventsPending() override; + void NextEvent(Event_t &event) override; + void Bell(Int_t percent) override; void CopyArea(Drawable_t src, Drawable_t dest, GContext_t gc, Int_t src_x, Int_t src_y, UInt_t width, UInt_t height, - Int_t dest_x, Int_t dest_y); - void ChangeWindowAttributes(Window_t id, SetWindowAttributes_t *attr); + Int_t dest_x, Int_t dest_y) override; + void ChangeWindowAttributes(Window_t id, SetWindowAttributes_t *attr) override; void ChangeProperty(Window_t id, Atom_t property, Atom_t type, - UChar_t *data, Int_t len); - void DrawLine(Drawable_t id, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2); - void ClearArea(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h); - Bool_t CheckEvent(Window_t id, EGEventType type, Event_t &ev); - void SendEvent(Window_t id, Event_t *ev); - void WMDeleteNotify(Window_t id); - void SetKeyAutoRepeat(Bool_t on = kTRUE); - void GrabKey(Window_t id, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE); + UChar_t *data, Int_t len) override; + void DrawLine(Drawable_t id, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; + void ClearArea(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t CheckEvent(Window_t id, EGEventType type, Event_t &ev) override; + void SendEvent(Window_t id, Event_t *ev) override; + void WMDeleteNotify(Window_t id) override; + void SetKeyAutoRepeat(Bool_t on = kTRUE) override; + void GrabKey(Window_t id, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE) override; void GrabButton(Window_t id, EMouseButton button, UInt_t modifier, UInt_t evmask, Window_t confine, Cursor_t cursor, - Bool_t grab = kTRUE); + Bool_t grab = kTRUE) override; void GrabPointer(Window_t id, UInt_t evmask, Window_t confine, Cursor_t cursor, Bool_t grab = kTRUE, - Bool_t owner_events = kTRUE); - void SetWindowName(Window_t id, char *name); - void SetIconName(Window_t id, char *name); - void SetIconPixmap(Window_t id, Pixmap_t pic); - void SetClassHints(Window_t id, char *className, char *resourceName); - void SetMWMHints(Window_t id, UInt_t value, UInt_t funcs, UInt_t input); - void SetWMPosition(Window_t id, Int_t x, Int_t y); - void SetWMSize(Window_t id, UInt_t w, UInt_t h); + Bool_t owner_events = kTRUE) override; + void SetWindowName(Window_t id, char *name) override; + void SetIconName(Window_t id, char *name) override; + void SetIconPixmap(Window_t id, Pixmap_t pic) override; + void SetClassHints(Window_t id, char *className, char *resourceName) override; + void SetMWMHints(Window_t id, UInt_t value, UInt_t funcs, UInt_t input) override; + void SetWMPosition(Window_t id, Int_t x, Int_t y) override; + void SetWMSize(Window_t id, UInt_t w, UInt_t h) override; void SetWMSizeHints(Window_t id, UInt_t wmin, UInt_t hmin, - UInt_t wmax, UInt_t hmax, UInt_t winc, UInt_t hinc); - void SetWMState(Window_t id, EInitialState state); - void SetWMTransientHint(Window_t id, Window_t main_id); + UInt_t wmax, UInt_t hmax, UInt_t winc, UInt_t hinc) override; + void SetWMState(Window_t id, EInitialState state) override; + void SetWMTransientHint(Window_t id, Window_t main_id) override; void DrawString(Drawable_t id, GContext_t gc, Int_t x, Int_t y, - const char *s, Int_t len); - Int_t TextWidth(FontStruct_t font, const char *s, Int_t len); - void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent); - void GetGCValues(GContext_t gc, GCValues_t &gval); - FontStruct_t GetFontStruct(FontH_t fh); - void FreeFontStruct(FontStruct_t fs); - void ClearWindow(Window_t id); - Int_t KeysymToKeycode(UInt_t keysym); + const char *s, Int_t len) override; + Int_t TextWidth(FontStruct_t font, const char *s, Int_t len) override; + void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent) override; + void GetGCValues(GContext_t gc, GCValues_t &gval) override; + FontStruct_t GetFontStruct(FontH_t fh) override; + void FreeFontStruct(FontStruct_t fs) override; + void ClearWindow(Window_t id) override; + Int_t KeysymToKeycode(UInt_t keysym) override; void FillRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, - UInt_t w, UInt_t h); + UInt_t w, UInt_t h) override; void DrawRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, - UInt_t w, UInt_t h); - void DrawSegments(Drawable_t id, GContext_t gc, Segment_t *seg, Int_t nseg); - void SelectInput(Window_t id, UInt_t evmask); - Window_t GetInputFocus(); - void SetInputFocus(Window_t id); - Window_t GetPrimarySelectionOwner(); - void SetPrimarySelectionOwner(Window_t id); - void ConvertPrimarySelection(Window_t id, Atom_t clipboard, Time_t when); - void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym); + UInt_t w, UInt_t h) override; + void DrawSegments(Drawable_t id, GContext_t gc, Segment_t *seg, Int_t nseg) override; + void SelectInput(Window_t id, UInt_t evmask) override; + Window_t GetInputFocus() override; + void SetInputFocus(Window_t id) override; + Window_t GetPrimarySelectionOwner() override; + void SetPrimarySelectionOwner(Window_t id) override; + void ConvertPrimarySelection(Window_t id, Atom_t clipboard, Time_t when) override; + void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym) override; void GetPasteBuffer(Window_t id, Atom_t atom, TString &text, - Int_t &nchar, Bool_t del); + Int_t &nchar, Bool_t del) override; void TranslateCoordinates(Window_t src, Window_t dest, Int_t src_x, - Int_t src_y, Int_t &dest_x, Int_t &dest_y, Window_t &child); - void GetWindowSize(Drawable_t id, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); - void FillPolygon(Window_t id, GContext_t gc, Point_t *points, Int_t npnt); + Int_t src_y, Int_t &dest_x, Int_t &dest_y, Window_t &child) override; + void GetWindowSize(Drawable_t id, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; + void FillPolygon(Window_t id, GContext_t gc, Point_t *points, Int_t npnt) override; void QueryPointer(Window_t id, Window_t &rootw, Window_t &childw, Int_t &root_x, Int_t &root_y, Int_t &win_x, - Int_t &win_y, UInt_t &mask); - void SetForeground(GContext_t gc, ULong_t foreground); - void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n); - void Update(Int_t mode = 0); - Region_t CreateRegion(); - void DestroyRegion(Region_t reg); - void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest); - Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding); - void UnionRegion(Region_t rega, Region_t regb, Region_t result); - void IntersectRegion(Region_t rega, Region_t regb, Region_t result); - void SubtractRegion(Region_t rega, Region_t regb, Region_t result); - void XorRegion(Region_t rega, Region_t regb, Region_t result); - Bool_t EmptyRegion(Region_t reg); - Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg); - Bool_t EqualRegion(Region_t rega, Region_t regb); - void GetRegionBox(Region_t reg, Rectangle_t *); - char **ListFonts(const char *fontname, Int_t max, Int_t &count); - void FreeFontNames(char **fontlist); - Drawable_t CreateImage(UInt_t width, UInt_t height); - void GetImageSize(Drawable_t id, UInt_t &width, UInt_t &height); - void PutPixel(Drawable_t id, Int_t x, Int_t y, ULong_t pixel); + Int_t &win_y, UInt_t &mask) override; + void SetForeground(GContext_t gc, ULong_t foreground) override; + void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n) override; + void Update(Int_t mode = 0) override; + Region_t CreateRegion() override; + void DestroyRegion(Region_t reg) override; + void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest) override; + Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding) override; + void UnionRegion(Region_t rega, Region_t regb, Region_t result) override; + void IntersectRegion(Region_t rega, Region_t regb, Region_t result) override; + void SubtractRegion(Region_t rega, Region_t regb, Region_t result) override; + void XorRegion(Region_t rega, Region_t regb, Region_t result) override; + Bool_t EmptyRegion(Region_t reg) override; + Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg) override; + Bool_t EqualRegion(Region_t rega, Region_t regb) override; + void GetRegionBox(Region_t reg, Rectangle_t *) override; + char **ListFonts(const char *fontname, Int_t max, Int_t &count) override; + void FreeFontNames(char **fontlist) override; + Drawable_t CreateImage(UInt_t width, UInt_t height) override; + void GetImageSize(Drawable_t id, UInt_t &width, UInt_t &height) override; + void PutPixel(Drawable_t id, Int_t x, Int_t y, ULong_t pixel) override; void PutImage(Drawable_t id, GContext_t gc, Drawable_t img, Int_t dx, Int_t dy, Int_t x, Int_t y, - UInt_t w, UInt_t h); - void DeleteImage(Drawable_t img); - unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t width, UInt_t height); - Int_t AddWindow(ULongptr_t qwid, UInt_t w, UInt_t h); - void RemoveWindow(ULongptr_t qwid); - void ShapeCombineMask(Window_t id, Int_t x, Int_t y, Pixmap_t mask); - UInt_t ScreenWidthMM() const; - - void DeleteProperty(Window_t, Atom_t&); + UInt_t w, UInt_t h) override; + void DeleteImage(Drawable_t img) override; + unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t width, UInt_t height) override; + Int_t AddWindow(ULongptr_t qwid, UInt_t w, UInt_t h) override; + void RemoveWindow(ULongptr_t qwid) override; + void ShapeCombineMask(Window_t id, Int_t x, Int_t y, Pixmap_t mask) override; + UInt_t ScreenWidthMM() const override; + + void DeleteProperty(Window_t, Atom_t&) override; Int_t GetProperty(Window_t, Atom_t, Long_t, Long_t, Bool_t, Atom_t, - Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**); - void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t); - void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&); - Bool_t SetSelectionOwner(Window_t, Atom_t&); + Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**) override; + void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t) override; + void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&) override; + Bool_t SetSelectionOwner(Window_t, Atom_t&) override; void ChangeProperties(Window_t id, Atom_t property, Atom_t type, - Int_t format, UChar_t *data, Int_t len); - void SetDNDAware(Window_t win, Atom_t *typelist); - void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist); - Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd); - Bool_t IsDNDAware(Window_t win, Atom_t *typelist); + Int_t format, UChar_t *data, Int_t len) override; + void SetDNDAware(Window_t win, Atom_t *typelist) override; + void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist) override; + Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd) override; + Bool_t IsDNDAware(Window_t win, Atom_t *typelist) override; - Bool_t IsCmdThread() const; + Bool_t IsCmdThread() const override; void SetUserThreadId(ULong_t id); static void Lock(); static void Unlock(); - ClassDef(TGWin32,0) //Interface to Win32 + ClassDefOverride(TGWin32,0) //Interface to Win32 }; #endif diff --git a/graf2d/win32gdk/inc/TGWin32GL.h b/graf2d/win32gdk/inc/TGWin32GL.h index cbb2b402311c5..c46787997103b 100644 --- a/graf2d/win32gdk/inc/TGWin32GL.h +++ b/graf2d/win32gdk/inc/TGWin32GL.h @@ -24,51 +24,51 @@ class TGWin32GLManager : public TGLManager { public: TGWin32GLManager(); - ~TGWin32GLManager(); + ~TGWin32GLManager() override; //All public functions are TGLManager's final-overriders //index returned can be used as a result of gVirtualX->InitWindow - Int_t InitGLWindow(Window_t winID); + Int_t InitGLWindow(Window_t winID) override; //winInd is the index, returned by InitGLWindow - Int_t CreateGLContext(Int_t winInd); + Int_t CreateGLContext(Int_t winInd) override; //[ Off-screen rendering part //create DIB section to read GL buffer into it, //ctxInd is the index, returned by CreateGLContext - Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h); + Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; //analog of gVirtualX->SelectWindow(fPixmapID) => gVirtualGL->SelectOffScreenDevice(fPixmapID) - void SelectOffScreenDevice(Int_t devInd); + void SelectOffScreenDevice(Int_t devInd) override; //Index of DIB, valid for gVirtualX - Int_t GetVirtualXInd(Int_t devInd); + Int_t GetVirtualXInd(Int_t devInd) override; //copy DIB into window directly/by pad - void MarkForDirectCopy(Int_t devInd, Bool_t); + void MarkForDirectCopy(Int_t devInd, Bool_t) override; //Off-screen device holds sizes for glViewport - void ExtractViewport(Int_t devInd, Int_t *vp); + void ExtractViewport(Int_t devInd, Int_t *vp) override; //Read GL buffer into DIB - void ReadGLBuffer(Int_t devInd); + void ReadGLBuffer(Int_t devInd) override; //] //Make the gl context current - Bool_t MakeCurrent(Int_t devInd); + Bool_t MakeCurrent(Int_t devInd) override; //Swap buffers or "blits" DIB - void Flush(Int_t ctxInd); + void Flush(Int_t ctxInd) override; //Generic function for gl context and off-screen device deletion - void DeleteGLContext(Int_t devInd); + void DeleteGLContext(Int_t devInd) override; //functions to switch between threads in win32 //used by viewer - Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox); + Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox) override; - Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py); - char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py); + Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py) override; - void PaintSingleObject(TVirtualGLPainter *); - void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y); - void PrintViewer(TVirtualViewer3D *vv); + void PaintSingleObject(TVirtualGLPainter *) override; + void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y) override; + void PrintViewer(TVirtualViewer3D *vv) override; - Bool_t HighColorFormat(Int_t ctx); + Bool_t HighColorFormat(Int_t ctx) override; private: struct TGLContext; @@ -77,7 +77,7 @@ class TGWin32GLManager : public TGLManager { TGWin32GLManager(const TGWin32GLManager &); TGWin32GLManager &operator = (const TGWin32GLManager &); - ClassDef(TGWin32GLManager, 0) + ClassDefOverride(TGWin32GLManager, 0) }; #endif diff --git a/graf2d/win32gdk/inc/TGWin32VirtualGLProxy.h b/graf2d/win32gdk/inc/TGWin32VirtualGLProxy.h index ba5afa9c809a0..e78bf720e662a 100644 --- a/graf2d/win32gdk/inc/TGWin32VirtualGLProxy.h +++ b/graf2d/win32gdk/inc/TGWin32VirtualGLProxy.h @@ -31,25 +31,25 @@ class TGWin32GLManagerProxy : public TGLManager, public TGWin32ProxyBase public: TGWin32GLManagerProxy(); - Int_t InitGLWindow(Window_t winID); - Int_t CreateGLContext(Int_t winInd); - Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - void SelectOffScreenDevice(Int_t devInd); - Int_t GetVirtualXInd(Int_t devInd); - void MarkForDirectCopy(Int_t devInd, Bool_t); - void ExtractViewport(Int_t devInd, Int_t *vp); - void ReadGLBuffer(Int_t devInd); - Bool_t MakeCurrent(Int_t devInd); - void Flush(Int_t ctxInd); - void DeleteGLContext(Int_t devInd); - Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox); - void PaintSingleObject(TVirtualGLPainter *); - void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y); - void PrintViewer(TVirtualViewer3D *vv); - Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py); - char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py); - Bool_t HighColorFormat(Int_t ctx); + Int_t InitGLWindow(Window_t winID) override; + Int_t CreateGLContext(Int_t winInd) override; + Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void SelectOffScreenDevice(Int_t devInd) override; + Int_t GetVirtualXInd(Int_t devInd) override; + void MarkForDirectCopy(Int_t devInd, Bool_t) override; + void ExtractViewport(Int_t devInd, Int_t *vp) override; + void ReadGLBuffer(Int_t devInd) override; + Bool_t MakeCurrent(Int_t devInd) override; + void Flush(Int_t ctxInd) override; + void DeleteGLContext(Int_t devInd) override; + Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox) override; + void PaintSingleObject(TVirtualGLPainter *) override; + void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y) override; + void PrintViewer(TVirtualViewer3D *vv) override; + Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + Bool_t HighColorFormat(Int_t ctx) override; static TGLManager *ProxyObject(); static TGLManager *RealObject(); diff --git a/graf2d/win32gdk/inc/TGWin32VirtualXProxy.h b/graf2d/win32gdk/inc/TGWin32VirtualXProxy.h index 3e17faae02e94..5923de3e68a75 100644 --- a/graf2d/win32gdk/inc/TGWin32VirtualXProxy.h +++ b/graf2d/win32gdk/inc/TGWin32VirtualXProxy.h @@ -37,251 +37,251 @@ friend class TGWin32; public: TGWin32VirtualXProxy() { fMaxResponseTime = 1000; fIsVirtualX = kTRUE; } TGWin32VirtualXProxy(const char *name, const char *title) {} - virtual ~TGWin32VirtualXProxy() {} + ~TGWin32VirtualXProxy() override {} - Bool_t Init(void *display=0); - void ClearWindow(); - void ClosePixmap(); - void CloseWindow(); - void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos); - void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, EBoxMode mode); - void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, Int_t nx, Int_t ny, Int_t *ic); - void DrawFillArea(Int_t n, TPoint *xy); - void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2); - void DrawPolyLine(Int_t n, TPoint *xy); - void DrawPolyMarker(Int_t n, TPoint *xy); - void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, const char *text, ETextMode mode); - void DrawText(Int_t, Int_t, Float_t, Float_t, const wchar_t *, ETextMode){} - void GetCharacterUp(Float_t &chupx, Float_t &chupy); + Bool_t Init(void *display=0) override; + void ClearWindow() override; + void ClosePixmap() override; + void CloseWindow() override; + void CopyPixmap(Int_t wid, Int_t xpos, Int_t ypos) override; + void DrawBox(Int_t x1, Int_t y1, Int_t x2, Int_t y2, EBoxMode mode) override; + void DrawCellArray(Int_t x1, Int_t y1, Int_t x2, Int_t y2, Int_t nx, Int_t ny, Int_t *ic) override; + void DrawFillArea(Int_t n, TPoint *xy) override; + void DrawLine(Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; + void DrawPolyLine(Int_t n, TPoint *xy) override; + void DrawPolyMarker(Int_t n, TPoint *xy) override; + void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, const char *text, ETextMode mode) override; + void DrawText(Int_t, Int_t, Float_t, Float_t, const wchar_t *, ETextMode) override{} + void GetCharacterUp(Float_t &chupx, Float_t &chupy) override; EDrawMode GetDrawMode(); - Int_t GetDoubleBuffer(Int_t wid); - void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); - const char *DisplayName(const char * = 0); - Handle_t GetNativeEvent() const; - ULong_t GetPixel(Color_t cindex); - void GetPlanes(Int_t &nplanes); - void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b); - void GetTextExtent(UInt_t &w, UInt_t &h, char *mess); - void GetTextExtent(UInt_t &, UInt_t &, wchar_t *){} - Float_t GetTextMagnitude(); - Window_t GetWindowID(Int_t wid); - Bool_t HasTTFonts() const; - Int_t InitWindow(ULong_t window); - void MoveWindow(Int_t wid, Int_t x, Int_t y); - Int_t OpenPixmap(UInt_t w, UInt_t h); - void QueryPointer(Int_t &ix, Int_t &iy); + Int_t GetDoubleBuffer(Int_t wid) override; + void GetGeometry(Int_t wid, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; + const char *DisplayName(const char * = 0) override; + Handle_t GetNativeEvent() const override; + ULong_t GetPixel(Color_t cindex) override; + void GetPlanes(Int_t &nplanes) override; + void GetRGB(Int_t index, Float_t &r, Float_t &g, Float_t &b) override; + void GetTextExtent(UInt_t &w, UInt_t &h, char *mess) override; + void GetTextExtent(UInt_t &, UInt_t &, wchar_t *) override{} + Float_t GetTextMagnitude() override; + Window_t GetWindowID(Int_t wid) override; + Bool_t HasTTFonts() const override; + Int_t InitWindow(ULongptr_t window) override; + void MoveWindow(Int_t wid, Int_t x, Int_t y) override; + Int_t OpenPixmap(UInt_t w, UInt_t h) override; + void QueryPointer(Int_t &ix, Int_t &iy) override; void ReadGIF(Int_t x0, Int_t y0, const char *file); - Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y); - Int_t RequestString(Int_t x, Int_t y, char *text); - void RescaleWindow(Int_t wid, UInt_t w, UInt_t h); - Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h); - void ResizeWindow(Int_t wid); - void SelectWindow(Int_t wid); - void SetCharacterUp(Float_t chupx, Float_t chupy); - void SetClipOFF(Int_t wid); - void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h); - void SetCursor(Int_t win, ECursor cursor); - void SetDoubleBuffer(Int_t wid, Int_t mode); - void SetDoubleBufferOFF(); - void SetDoubleBufferON(); - void SetDrawMode(EDrawMode mode); - void SetFillColor(Color_t cindex); - void SetFillStyle(Style_t style); - void SetFillAttributes(); - void ResetAttFill(Option_t *option=""); - Color_t GetFillColor() const; - Style_t GetFillStyle() const; - Bool_t IsTransparent() const; - void SetLineColor(Color_t cindex); - void SetLineType(Int_t n, Int_t *dash); - void SetLineStyle(Style_t linestyle); - void SetLineWidth(Width_t width); - void SetLineAttributes(); - void ResetAttLine(Option_t *option=""); - Color_t GetLineColor() const; - Style_t GetLineStyle() const; - Width_t GetLineWidth() const; - void SetMarkerColor(Color_t cindex); - void SetMarkerSize(Float_t markersize); - void SetMarkerStyle(Style_t markerstyle); - void ResetAttMarker(Option_t *toption=""); - void SetMarkerAttributes(); - Color_t GetMarkerColor() const; - Style_t GetMarkerStyle() const; - Size_t GetMarkerSize() const; - void SetOpacity(Int_t percent); - void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b); - void SetTextAlign(Short_t talign=11); - void SetTextColor(Color_t cindex=1); - void SetTextAngle(Float_t tangle=0); - Int_t SetTextFont(char *fontname, ETextSetMode mode); - void SetTextFont(Font_t fontnumber=62); - void SetTextMagnitude(Float_t mgn); - void SetTextSize(Float_t textsize=1); - void SetTextSizePixels(Int_t npixels); - void SetTextAttributes(); - void ResetAttText(Option_t *toption=""); - Short_t GetTextAlign() const; - Float_t GetTextAngle() const; - Color_t GetTextColor() const; - Font_t GetTextFont() const; - Float_t GetTextSize() const; - void UpdateWindow(Int_t mode); - void Warp(Int_t ix, Int_t iy, Window_t id = 0); - Int_t WriteGIF(char *name); - void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname); - void GetWindowAttributes(Window_t id, WindowAttributes_t &attr); - void MapWindow(Window_t id); - void MapSubwindows(Window_t id); - void MapRaised(Window_t id); - void UnmapWindow(Window_t id); - void DestroyWindow(Window_t id); - void DestroySubwindows(Window_t id); - void RaiseWindow(Window_t id); - void LowerWindow(Window_t id); - void MoveWindow(Window_t id, Int_t x, Int_t y); - void MoveResizeWindow(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h); - void ResizeWindow(Window_t id, UInt_t w, UInt_t h); - void IconifyWindow(Window_t id); - void ReparentWindow(Window_t id, Window_t pid, Int_t x, Int_t y); - void SetWindowBackground(Window_t id, ULong_t color); - void SetWindowBackgroundPixmap(Window_t id, Pixmap_t pxm); + Int_t RequestLocator(Int_t mode, Int_t ctyp, Int_t &x, Int_t &y) override; + Int_t RequestString(Int_t x, Int_t y, char *text) override; + void RescaleWindow(Int_t wid, UInt_t w, UInt_t h) override; + Int_t ResizePixmap(Int_t wid, UInt_t w, UInt_t h) override; + void ResizeWindow(Int_t wid) override; + void SelectWindow(Int_t wid) override; + void SetCharacterUp(Float_t chupx, Float_t chupy) override; + void SetClipOFF(Int_t wid) override; + void SetClipRegion(Int_t wid, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void SetCursor(Int_t win, ECursor cursor) override; + void SetDoubleBuffer(Int_t wid, Int_t mode) override; + void SetDoubleBufferOFF() override; + void SetDoubleBufferON() override; + void SetDrawMode(EDrawMode mode) override; + void SetFillColor(Color_t cindex) override; + void SetFillStyle(Style_t style) override; + void SetFillAttributes() override; + void ResetAttFill(Option_t *option="") override; + Color_t GetFillColor() const override; + Style_t GetFillStyle() const override; + Bool_t IsTransparent() const override; + void SetLineColor(Color_t cindex) override; + void SetLineType(Int_t n, Int_t *dash) override; + void SetLineStyle(Style_t linestyle) override; + void SetLineWidth(Width_t width) override; + void SetLineAttributes() override; + void ResetAttLine(Option_t *option="") override; + Color_t GetLineColor() const override; + Style_t GetLineStyle() const override; + Width_t GetLineWidth() const override; + void SetMarkerColor(Color_t cindex) override; + void SetMarkerSize(Float_t markersize) override; + void SetMarkerStyle(Style_t markerstyle) override; + void ResetAttMarker(Option_t *toption="") override; + void SetMarkerAttributes() override; + Color_t GetMarkerColor() const override; + Style_t GetMarkerStyle() const override; + Size_t GetMarkerSize() const override; + void SetOpacity(Int_t percent) override; + void SetRGB(Int_t cindex, Float_t r, Float_t g, Float_t b) override; + void SetTextAlign(Short_t talign=11) override; + void SetTextColor(Color_t cindex=1) override; + void SetTextAngle(Float_t tangle=0) override; + Int_t SetTextFont(char *fontname, ETextSetMode mode) override; + void SetTextFont(Font_t fontnumber=62) override; + void SetTextMagnitude(Float_t mgn) override; + void SetTextSize(Float_t textsize=1) override; + void SetTextSizePixels(Int_t npixels) override; + void SetTextAttributes() override; + void ResetAttText(Option_t *toption="") override; + Short_t GetTextAlign() const override; + Float_t GetTextAngle() const override; + Color_t GetTextColor() const override; + Font_t GetTextFont() const override; + Float_t GetTextSize() const override; + void UpdateWindow(Int_t mode) override; + void Warp(Int_t ix, Int_t iy, Window_t id = 0) override; + Int_t WriteGIF(char *name) override; + void WritePixmap(Int_t wid, UInt_t w, UInt_t h, char *pxname) override; + void GetWindowAttributes(Window_t id, WindowAttributes_t &attr) override; + void MapWindow(Window_t id) override; + void MapSubwindows(Window_t id) override; + void MapRaised(Window_t id) override; + void UnmapWindow(Window_t id) override; + void DestroyWindow(Window_t id) override; + void DestroySubwindows(Window_t id) override; + void RaiseWindow(Window_t id) override; + void LowerWindow(Window_t id) override; + void MoveWindow(Window_t id, Int_t x, Int_t y) override; + void MoveResizeWindow(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void ResizeWindow(Window_t id, UInt_t w, UInt_t h) override; + void IconifyWindow(Window_t id) override; + void ReparentWindow(Window_t id, Window_t pid, Int_t x, Int_t y) override; + void SetWindowBackground(Window_t id, ULong_t color) override; + void SetWindowBackgroundPixmap(Window_t id, Pixmap_t pxm) override; Window_t CreateWindow(Window_t parent, Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t border, Int_t depth, UInt_t clss, - void *visual, SetWindowAttributes_t *attr, UInt_t wtype); - Int_t OpenDisplay(const char *dpyName=0); - void CloseDisplay(); - Display_t GetDisplay() const; - Visual_t GetVisual() const; - Int_t GetScreen() const; - Int_t GetDepth() const; - Colormap_t GetColormap() const; - Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist); - Window_t GetDefaultRootWindow() const; - Window_t GetParent(Window_t id) const; - FontStruct_t LoadQueryFont(const char *font_name); - FontH_t GetFontHandle(FontStruct_t fs); - void DeleteFont(FontStruct_t fs); - GContext_t CreateGC(Drawable_t id, GCValues_t *gval); - void ChangeGC(GContext_t gc, GCValues_t *gval); - void CopyGC(GContext_t org, GContext_t dest, Mask_t mask); - void DeleteGC(GContext_t gc); - Cursor_t CreateCursor(ECursor cursor); - void SetCursor(Window_t id, Cursor_t curid); - Pixmap_t CreatePixmap(Drawable_t id, UInt_t w, UInt_t h); + void *visual, SetWindowAttributes_t *attr, UInt_t wtype) override; + Int_t OpenDisplay(const char *dpyName=0) override; + void CloseDisplay() override; + Display_t GetDisplay() const override; + Visual_t GetVisual() const override; + Int_t GetScreen() const override; + Int_t GetDepth() const override; + Colormap_t GetColormap() const override; + Atom_t InternAtom(const char *atom_name, Bool_t only_if_exist) override; + Window_t GetDefaultRootWindow() const override; + Window_t GetParent(Window_t id) const override; + FontStruct_t LoadQueryFont(const char *font_name) override; + FontH_t GetFontHandle(FontStruct_t fs) override; + void DeleteFont(FontStruct_t fs) override; + GContext_t CreateGC(Drawable_t id, GCValues_t *gval) override; + void ChangeGC(GContext_t gc, GCValues_t *gval) override; + void CopyGC(GContext_t org, GContext_t dest, Mask_t mask) override; + void DeleteGC(GContext_t gc) override; + Cursor_t CreateCursor(ECursor cursor) override; + void SetCursor(Window_t id, Cursor_t curid) override; + Pixmap_t CreatePixmap(Drawable_t id, UInt_t w, UInt_t h) override; Pixmap_t CreatePixmap(Drawable_t id, const char *bitmap, UInt_t width, - UInt_t height, ULong_t forecolor, ULong_t backcolor, Int_t depth); - Pixmap_t CreateBitmap(Drawable_t id, const char *bitmap, UInt_t width, UInt_t height); - void DeletePixmap(Pixmap_t pmap); + UInt_t height, ULong_t forecolor, ULong_t backcolor, Int_t depth) override; + Pixmap_t CreateBitmap(Drawable_t id, const char *bitmap, UInt_t width, UInt_t height) override; + void DeletePixmap(Pixmap_t pmap) override; Bool_t CreatePictureFromFile(Drawable_t id, const char *filename, - Pixmap_t &pict, Pixmap_t &pict_mask, PictureAttributes_t &attr); + Pixmap_t &pict, Pixmap_t &pict_mask, PictureAttributes_t &attr) override; Bool_t CreatePictureFromData(Drawable_t id, char **data, - Pixmap_t &pict, Pixmap_t &pict_mask, PictureAttributes_t &attr); - Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data); - void DeletePictureData(void *data); - void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n); - Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color); - Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color); - void QueryColor(Colormap_t cmap, ColorStruct_t &color); - void FreeColor(Colormap_t cmap, ULong_t pixel); - void Bell(Int_t percent); + Pixmap_t &pict, Pixmap_t &pict_mask, PictureAttributes_t &attr) override; + Bool_t ReadPictureDataFromFile(const char *filename, char ***ret_data) override; + void DeletePictureData(void *data) override; + void SetDashes(GContext_t gc, Int_t offset, const char *dash_list, Int_t n) override; + Bool_t ParseColor(Colormap_t cmap, const char *cname, ColorStruct_t &color) override; + Bool_t AllocColor(Colormap_t cmap, ColorStruct_t &color) override; + void QueryColor(Colormap_t cmap, ColorStruct_t &color) override; + void FreeColor(Colormap_t cmap, ULong_t pixel) override; + void Bell(Int_t percent) override; void CopyArea(Drawable_t src, Drawable_t dest, GContext_t gc, Int_t src_x, - Int_t src_y, UInt_t width, UInt_t height, Int_t dest_x, Int_t dest_y); - void ChangeWindowAttributes(Window_t id, SetWindowAttributes_t *attr); - void ChangeProperty(Window_t id, Atom_t property, Atom_t type, UChar_t *data, Int_t len); - void DrawLine(Drawable_t id, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2); - void ClearArea(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h); - void WMDeleteNotify(Window_t id); - void SetKeyAutoRepeat(Bool_t on = kTRUE); - void GrabKey(Window_t id, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE); + Int_t src_y, UInt_t width, UInt_t height, Int_t dest_x, Int_t dest_y) override; + void ChangeWindowAttributes(Window_t id, SetWindowAttributes_t *attr) override; + void ChangeProperty(Window_t id, Atom_t property, Atom_t type, UChar_t *data, Int_t len) override; + void DrawLine(Drawable_t id, GContext_t gc, Int_t x1, Int_t y1, Int_t x2, Int_t y2) override; + void ClearArea(Window_t id, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void WMDeleteNotify(Window_t id) override; + void SetKeyAutoRepeat(Bool_t on = kTRUE) override; + void GrabKey(Window_t id, Int_t keycode, UInt_t modifier, Bool_t grab = kTRUE) override; void GrabButton(Window_t id, EMouseButton button, UInt_t modifier, - UInt_t evmask, Window_t confine, Cursor_t cursor, Bool_t grab = kTRUE); + UInt_t evmask, Window_t confine, Cursor_t cursor, Bool_t grab = kTRUE) override; void GrabPointer(Window_t id, UInt_t evmask, Window_t confine, - Cursor_t cursor, Bool_t grab = kTRUE, Bool_t owner_events = kTRUE); - void SetWindowName(Window_t id, char *name); - void SetIconName(Window_t id, char *name); - void SetIconPixmap(Window_t id, Pixmap_t pix); - void SetClassHints(Window_t id, char *className, char *resourceName); - void SetMWMHints(Window_t id, UInt_t value, UInt_t funcs, UInt_t input); - void SetWMPosition(Window_t id, Int_t x, Int_t y); - void SetWMSize(Window_t id, UInt_t w, UInt_t h); + Cursor_t cursor, Bool_t grab = kTRUE, Bool_t owner_events = kTRUE) override; + void SetWindowName(Window_t id, char *name) override; + void SetIconName(Window_t id, char *name) override; + void SetIconPixmap(Window_t id, Pixmap_t pix) override; + void SetClassHints(Window_t id, char *className, char *resourceName) override; + void SetMWMHints(Window_t id, UInt_t value, UInt_t funcs, UInt_t input) override; + void SetWMPosition(Window_t id, Int_t x, Int_t y) override; + void SetWMSize(Window_t id, UInt_t w, UInt_t h) override; void SetWMSizeHints(Window_t id, UInt_t wmin, UInt_t hmin, - UInt_t wmax, UInt_t hmax, UInt_t winc, UInt_t hinc); - void SetWMState(Window_t id, EInitialState state); - void SetWMTransientHint(Window_t id, Window_t main_id); - void DrawString(Drawable_t id, GContext_t gc, Int_t x, Int_t y, const char *s, Int_t len); - Int_t TextWidth(FontStruct_t font, const char *s, Int_t len); - void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent); - void GetGCValues(GContext_t gc, GCValues_t &gval); - FontStruct_t GetFontStruct(FontH_t fh); - void FreeFontStruct(FontStruct_t fs); - void ClearWindow(Window_t id); - Int_t KeysymToKeycode(UInt_t keysym); - void FillRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h); - void DrawRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h); - void DrawSegments(Drawable_t id, GContext_t gc, Segment_t *seg, Int_t nseg); - void SelectInput(Window_t id, UInt_t evmask); - Window_t GetInputFocus(); - void SetInputFocus(Window_t id); - Window_t GetPrimarySelectionOwner(); - void SetPrimarySelectionOwner(Window_t id); - void ConvertPrimarySelection(Window_t id, Atom_t clipboard, Time_t when); - void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym); - void GetPasteBuffer(Window_t id, Atom_t atom, TString &text, Int_t &nchar, Bool_t del); + UInt_t wmax, UInt_t hmax, UInt_t winc, UInt_t hinc) override; + void SetWMState(Window_t id, EInitialState state) override; + void SetWMTransientHint(Window_t id, Window_t main_id) override; + void DrawString(Drawable_t id, GContext_t gc, Int_t x, Int_t y, const char *s, Int_t len) override; + Int_t TextWidth(FontStruct_t font, const char *s, Int_t len) override; + void GetFontProperties(FontStruct_t font, Int_t &max_ascent, Int_t &max_descent) override; + void GetGCValues(GContext_t gc, GCValues_t &gval) override; + FontStruct_t GetFontStruct(FontH_t fh) override; + void FreeFontStruct(FontStruct_t fs) override; + void ClearWindow(Window_t id) override; + Int_t KeysymToKeycode(UInt_t keysym) override; + void FillRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void DrawRectangle(Drawable_t id, GContext_t gc, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void DrawSegments(Drawable_t id, GContext_t gc, Segment_t *seg, Int_t nseg) override; + void SelectInput(Window_t id, UInt_t evmask) override; + Window_t GetInputFocus() override; + void SetInputFocus(Window_t id) override; + Window_t GetPrimarySelectionOwner() override; + void SetPrimarySelectionOwner(Window_t id) override; + void ConvertPrimarySelection(Window_t id, Atom_t clipboard, Time_t when) override; + void LookupString(Event_t *event, char *buf, Int_t buflen, UInt_t &keysym) override; + void GetPasteBuffer(Window_t id, Atom_t atom, TString &text, Int_t &nchar, Bool_t del) override; void TranslateCoordinates(Window_t src, Window_t dest, Int_t src_x, - Int_t src_y, Int_t &dest_x, Int_t &dest_y, Window_t &child); - void GetWindowSize(Drawable_t id, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h); - void FillPolygon(Window_t id, GContext_t gc, Point_t *points, Int_t npnt); + Int_t src_y, Int_t &dest_x, Int_t &dest_y, Window_t &child) override; + void GetWindowSize(Drawable_t id, Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override; + void FillPolygon(Window_t id, GContext_t gc, Point_t *points, Int_t npnt) override; void QueryPointer(Window_t id, Window_t &rootw, Window_t &childw, - Int_t &root_x, Int_t &root_y, Int_t &win_x, Int_t &win_y, UInt_t &mask); - void SetForeground(GContext_t gc, ULong_t foreground); - void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n); - void Update(Int_t mode = 0); - Region_t CreateRegion(); - void DestroyRegion(Region_t reg); - void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest); - Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding); - void UnionRegion(Region_t rega, Region_t regb, Region_t result); - void IntersectRegion(Region_t rega, Region_t regb, Region_t result); - void SubtractRegion(Region_t rega, Region_t regb, Region_t result); - void XorRegion(Region_t rega, Region_t regb, Region_t result); - Bool_t EmptyRegion(Region_t reg); - Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg); - Bool_t EqualRegion(Region_t rega, Region_t regb); - void GetRegionBox(Region_t reg, Rectangle_t *rect); - char **ListFonts(const char *fontname, Int_t max, Int_t &count); - void FreeFontNames(char **fontlist); - Drawable_t CreateImage(UInt_t width, UInt_t height); - void GetImageSize(Drawable_t id, UInt_t &width, UInt_t &height); - void PutPixel(Drawable_t id, Int_t x, Int_t y, ULong_t pixel); + Int_t &root_x, Int_t &root_y, Int_t &win_x, Int_t &win_y, UInt_t &mask) override; + void SetForeground(GContext_t gc, ULong_t foreground) override; + void SetClipRectangles(GContext_t gc, Int_t x, Int_t y, Rectangle_t *recs, Int_t n) override; + void Update(Int_t mode = 0) override; + Region_t CreateRegion() override; + void DestroyRegion(Region_t reg) override; + void UnionRectWithRegion(Rectangle_t *rect, Region_t src, Region_t dest) override; + Region_t PolygonRegion(Point_t *points, Int_t np, Bool_t winding) override; + void UnionRegion(Region_t rega, Region_t regb, Region_t result) override; + void IntersectRegion(Region_t rega, Region_t regb, Region_t result) override; + void SubtractRegion(Region_t rega, Region_t regb, Region_t result) override; + void XorRegion(Region_t rega, Region_t regb, Region_t result) override; + Bool_t EmptyRegion(Region_t reg) override; + Bool_t PointInRegion(Int_t x, Int_t y, Region_t reg) override; + Bool_t EqualRegion(Region_t rega, Region_t regb) override; + void GetRegionBox(Region_t reg, Rectangle_t *rect) override; + char **ListFonts(const char *fontname, Int_t max, Int_t &count) override; + void FreeFontNames(char **fontlist) override; + Drawable_t CreateImage(UInt_t width, UInt_t height) override; + void GetImageSize(Drawable_t id, UInt_t &width, UInt_t &height) override; + void PutPixel(Drawable_t id, Int_t x, Int_t y, ULong_t pixel) override; void PutImage(Drawable_t id, GContext_t gc, Drawable_t img, - Int_t dx, Int_t dy, Int_t x, Int_t y, UInt_t w, UInt_t h); - void DeleteImage(Drawable_t img); - unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t width, UInt_t height); - Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height); - Int_t AddWindow(ULong_t qwid, UInt_t w, UInt_t h); - void RemoveWindow(ULong_t qwid); - void ShapeCombineMask(Window_t id, Int_t x, Int_t y, Pixmap_t mask); + Int_t dx, Int_t dy, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + void DeleteImage(Drawable_t img) override; + unsigned char *GetColorBits(Drawable_t wid, Int_t x, Int_t y, UInt_t width, UInt_t height) override; + Pixmap_t CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t height) override; + Int_t AddWindow(ULongptr_t qwid, UInt_t w, UInt_t h) override; + void RemoveWindow(ULongptr_t qwid) override; + void ShapeCombineMask(Window_t id, Int_t x, Int_t y, Pixmap_t mask) override; - void DeleteProperty(Window_t, Atom_t&); + void DeleteProperty(Window_t, Atom_t&) override; Int_t GetProperty(Window_t, Atom_t, Long_t, Long_t, Bool_t, Atom_t, - Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**); - void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t); - void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&); - Bool_t SetSelectionOwner(Window_t, Atom_t&); + Atom_t*, Int_t*, ULong_t*, ULong_t*, unsigned char**) override; + void ChangeActivePointerGrab(Window_t, UInt_t, Cursor_t) override; + void ConvertSelection(Window_t, Atom_t&, Atom_t&, Atom_t&, Time_t&) override; + Bool_t SetSelectionOwner(Window_t, Atom_t&) override; void ChangeProperties(Window_t id, Atom_t property, Atom_t type, - Int_t format, UChar_t *data, Int_t len); - void SetDNDAware(Window_t win, Atom_t *typelist); - void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist); - Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd); - Bool_t IsDNDAware(Window_t win, Atom_t *typelist); + Int_t format, UChar_t *data, Int_t len) override; + void SetDNDAware(Window_t win, Atom_t *typelist) override; + void SetTypeList(Window_t win, Atom_t prop, Atom_t *typelist) override; + Window_t FindRWindow(Window_t win, Window_t dragwin, Window_t input, int x, int y, int maxd) override; + Bool_t IsDNDAware(Window_t win, Atom_t *typelist) override; - Int_t EventsPending(); - void NextEvent(Event_t & event); - Bool_t CheckEvent(Window_t id, EGEventType type, Event_t &ev); - void SendEvent(Window_t id, Event_t *ev); - Bool_t IsCmdThread() const; - Window_t GetCurrentWindow() const; + Int_t EventsPending() override; + void NextEvent(Event_t & event) override; + Bool_t CheckEvent(Window_t id, EGEventType type, Event_t &ev) override; + void SendEvent(Window_t id, Event_t *ev) override; + Bool_t IsCmdThread() const override; + Window_t GetCurrentWindow() const override; static TVirtualX *RealObject(); static TVirtualX *ProxyObject(); diff --git a/graf2d/win32gdk/src/TGWin32VirtualXProxy.cxx b/graf2d/win32gdk/src/TGWin32VirtualXProxy.cxx index d2bbbb24e1f18..961942e05152a 100644 --- a/graf2d/win32gdk/src/TGWin32VirtualXProxy.cxx +++ b/graf2d/win32gdk/src/TGWin32VirtualXProxy.cxx @@ -203,7 +203,7 @@ RETURN_METHOD_ARG1(VirtualX,const char*,DisplayName,const char*,dpyName) RETURN_METHOD_ARG1(VirtualX,Bool_t,Init,void*,display) RETURN_METHOD_ARG1(VirtualX,Int_t,GetDoubleBuffer,Int_t,wid) RETURN_METHOD_ARG1(VirtualX,Window_t,GetWindowID,Int_t,wid) -RETURN_METHOD_ARG1(VirtualX,Int_t,InitWindow,ULong_t,window) +RETURN_METHOD_ARG1(VirtualX,Int_t,InitWindow,ULongptr_t,window) RETURN_METHOD_ARG1(VirtualX,Int_t,WriteGIF,char*,name) RETURN_METHOD_ARG1(VirtualX,FontStruct_t,LoadQueryFont,const char*,font_name) RETURN_METHOD_ARG1(VirtualX,FontH_t,GetFontHandle,FontStruct_t,fs) @@ -237,8 +237,8 @@ RETURN_METHOD_ARG3(VirtualX,Pixmap_t,CreatePixmap,Drawable_t,wid,UInt_t,w,UInt_t RETURN_METHOD_ARG1(VirtualX,ULong_t,GetPixel,Color_t,cindex) RETURN_METHOD_ARG5(VirtualX,unsigned char*,GetColorBits,Drawable_t,wid,Int_t,x,Int_t,y,UInt_t,width,UInt_t,height) RETURN_METHOD_ARG3(VirtualX,Pixmap_t,CreatePixmapFromData,unsigned char*,bits,UInt_t,width,UInt_t,height) -RETURN_METHOD_ARG3(VirtualX,Int_t,AddWindow,ULong_t,qwid,UInt_t,w,UInt_t,h) -VOID_METHOD_ARG1(VirtualX,RemoveWindow,ULong_t,qwid,1) +RETURN_METHOD_ARG3(VirtualX,Int_t,AddWindow,ULongptr_t,qwid,UInt_t,w,UInt_t,h) +VOID_METHOD_ARG1(VirtualX,RemoveWindow,ULongptr_t,qwid,1) VOID_METHOD_ARG4(VirtualX,ShapeCombineMask,Window_t,id,Int_t,x,Int_t,y,Pixmap_t,mask,1) VOID_METHOD_ARG2(VirtualX,DeleteProperty,Window_t,win,Atom_t&,prop,1) @@ -254,9 +254,9 @@ RETURN_METHOD_ARG2(VirtualX,Bool_t,IsDNDAware,Window_t,win,Atom_t*,typelist); //VOID_METHOD_ARG1(VirtualX,CreateOpenGLContext,Int_t,wid,1) //VOID_METHOD_ARG1(VirtualX,DeleteOpenGLContext,Int_t,wid,1) -//VOID_METHOD_ARG1(VirtualX,RemoveWindow,ULong_t,qwid,1) +//VOID_METHOD_ARG1(VirtualX,RemoveWindow,ULongptr_t,qwid,1) //RETURN_METHOD_ARG1(VirtualX,ExecCommand,UInt_t,TGWin32Command*,code) -//RETURN_METHOD_ARG3(VirtualX,Int_t,AddWindow,ULong_t,qwid,UInt_t,w,UInt_t,h) +//RETURN_METHOD_ARG3(VirtualX,Int_t,AddWindow,ULongptr_t,qwid,UInt_t,w,UInt_t,h) //////////////////////// some non-standard methods ///////////////////////////// //////////////////////////////////////////////////////////////////////////////// diff --git a/graf2d/x11/inc/TGX11.h b/graf2d/x11/inc/TGX11.h index ac9ef1fd7fa52..2df9360726256 100644 --- a/graf2d/x11/inc/TGX11.h +++ b/graf2d/x11/inc/TGX11.h @@ -159,7 +159,7 @@ class TGX11 : public TVirtualX { TGX11(); TGX11(const TGX11 &org); TGX11(const char *name, const char *title); - virtual ~TGX11(); + ~TGX11() override; Bool_t Init(void *display) override; void ClearWindow() override; diff --git a/graf2d/x11/src/GX11Gui.cxx b/graf2d/x11/src/GX11Gui.cxx index 17fa5e10e4452..ab82892d99351 100644 --- a/graf2d/x11/src/GX11Gui.cxx +++ b/graf2d/x11/src/GX11Gui.cxx @@ -808,7 +808,6 @@ void TGX11::GetWindowAttributes(Window_t id, WindowAttributes_t &attr) Int_t TGX11::OpenDisplay(const char *dpyName) { -#ifdef _REENTRANT // In some cases there can be problems due to XInitThreads, like when // using Qt, so we allow for it to be turned off if (gEnv->GetValue("X11.XInitThread", 1)) { @@ -816,7 +815,6 @@ Int_t TGX11::OpenDisplay(const char *dpyName) if (!XInitThreads()) Warning("OpenDisplay", "system has no X11 thread support"); } -#endif Display *dpy; if (!(dpy = XOpenDisplay(dpyName))) diff --git a/graf2d/x11ttf/inc/TGX11TTF.h b/graf2d/x11ttf/inc/TGX11TTF.h index 5a84220c250a4..b1ee8a664e455 100644 --- a/graf2d/x11ttf/inc/TGX11TTF.h +++ b/graf2d/x11ttf/inc/TGX11TTF.h @@ -44,7 +44,7 @@ class TGX11TTF : public TGX11 { public: TGX11TTF(const TGX11 &org); - virtual ~TGX11TTF() { } + ~TGX11TTF() override { } Bool_t Init(void *display) override; void DrawText(Int_t x, Int_t y, Float_t angle, Float_t mgn, diff --git a/graf3d/csg/src/CsgOps.cxx b/graf3d/csg/src/CsgOps.cxx index 1976862f94cdb..6b421bb09eca8 100644 --- a/graf3d/csg/src/CsgOps.cxx +++ b/graf3d/csg/src/CsgOps.cxx @@ -1665,12 +1665,12 @@ namespace RootCsg { const PLIST &Polys()const{return fPolys;} //TBaseMesh's final-overriders - UInt_t NumberOfPolys()const{return fPolys.size();} - UInt_t NumberOfVertices()const{return fVerts.size();} - UInt_t SizeOfPoly(UInt_t polyIndex)const{return fPolys[polyIndex].Size();} - const Double_t *GetVertex(UInt_t vertexNum)const{return fVerts[vertexNum].GetValue();} + UInt_t NumberOfPolys()const override{return fPolys.size();} + UInt_t NumberOfVertices()const override{return fVerts.size();} + UInt_t SizeOfPoly(UInt_t polyIndex)const override{return fPolys[polyIndex].Size();} + const Double_t *GetVertex(UInt_t vertexNum)const override{return fVerts[vertexNum].GetValue();} - Int_t GetVertexIndex(UInt_t polyNum, UInt_t vertexNum)const + Int_t GetVertexIndex(UInt_t polyNum, UInt_t vertexNum)const override { return fPolys[polyNum][vertexNum]; } diff --git a/graf3d/eve/inc/TEveArrow.h b/graf3d/eve/inc/TEveArrow.h index 151f39737e62d..a125612deffcb 100644 --- a/graf3d/eve/inc/TEveArrow.h +++ b/graf3d/eve/inc/TEveArrow.h @@ -45,9 +45,9 @@ class TEveArrow : public TEveElement, public: TEveArrow(Float_t xVec=0, Float_t yVec=0, Float_t zVec=1, Float_t xOrg=0, Float_t yOrg=0, Float_t zOrg=0); - virtual ~TEveArrow() {} + ~TEveArrow() override {} - virtual TObject* GetObject(const TEveException& ) const + TObject* GetObject(const TEveException& ) const override { const TObject* obj = this; return const_cast(obj); } void StampGeom() { ResetBBox(); AddStamp(kCBTransBBox | kCBObjProps); } @@ -73,10 +73,10 @@ class TEveArrow : public TEveElement, Int_t GetDrawQuality() const { return fDrawQuality; } void SetDrawQuality(Int_t q) { fDrawQuality = q; } - virtual void ComputeBBox(); - virtual void Paint(Option_t* option=""); + void ComputeBBox() override; + void Paint(Option_t* option="") override; - ClassDef(TEveArrow, 0); // Class for gl visualisation of arrow. + ClassDefOverride(TEveArrow, 0); // Class for gl visualisation of arrow. }; #endif diff --git a/graf3d/eve/inc/TEveArrowEditor.h b/graf3d/eve/inc/TEveArrowEditor.h index 22efa3155977d..912f364ef078c 100644 --- a/graf3d/eve/inc/TEveArrowEditor.h +++ b/graf3d/eve/inc/TEveArrowEditor.h @@ -37,16 +37,16 @@ class TEveArrowEditor : public TGedFrame public: TEveArrowEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveArrowEditor() {} + ~TEveArrowEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoTubeR(); void DoConeR(); void DoConeL(); void DoVertex(); - ClassDef(TEveArrowEditor, 0); // GUI editor for TEveArrow. + ClassDefOverride(TEveArrowEditor, 0); // GUI editor for TEveArrow. }; #endif diff --git a/graf3d/eve/inc/TEveArrowGL.h b/graf3d/eve/inc/TEveArrowGL.h index a850cff73bef4..e222194fde553 100644 --- a/graf3d/eve/inc/TEveArrowGL.h +++ b/graf3d/eve/inc/TEveArrowGL.h @@ -29,13 +29,13 @@ class TEveArrowGL : public TGLObject public: TEveArrowGL(); - virtual ~TEveArrowGL() {} + ~TEveArrowGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TEveArrowGL, 0); // GL renderer class for TEveArrow. + ClassDefOverride(TEveArrowGL, 0); // GL renderer class for TEveArrow. }; #endif diff --git a/graf3d/eve/inc/TEveBox.h b/graf3d/eve/inc/TEveBox.h index 8b18f8de138f1..3efd787e45a97 100644 --- a/graf3d/eve/inc/TEveBox.h +++ b/graf3d/eve/inc/TEveBox.h @@ -31,7 +31,7 @@ class TEveBox : public TEveShape public: TEveBox(const char* n="TEveBox", const char* t=""); - virtual ~TEveBox(); + ~TEveBox() override; void SetVertex(Int_t i, Float_t x, Float_t y, Float_t z); void SetVertex(Int_t i, const Float_t* v); @@ -40,12 +40,12 @@ class TEveBox : public TEveShape const Float_t* GetVertex(Int_t i) const { return fVertices[i]; } // For TAttBBox: - virtual void ComputeBBox(); + void ComputeBBox() override; // Projectable: - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEveBox, 0); // 3D box with arbitrary vertices. + ClassDefOverride(TEveBox, 0); // 3D box with arbitrary vertices. }; @@ -67,27 +67,27 @@ class TEveBoxProjected : public TEveShape, Int_t fBreakIdx; vVector2_t fDebugPoints; - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; static Bool_t fgDebugCornerPoints; public: TEveBoxProjected(const char* n="TEveBoxProjected", const char* t=""); - virtual ~TEveBoxProjected(); + ~TEveBoxProjected() override; // For TAttBBox: - virtual void ComputeBBox(); + void ComputeBBox() override; // Projected: - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); - virtual void UpdateProjection(); + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; + void UpdateProjection() override; - virtual TEveElement* GetProjectedAsElement() { return this; } + TEveElement* GetProjectedAsElement() override { return this; } static Bool_t GetDebugCornerPoints(); static void SetDebugCornerPoints(Bool_t d); - ClassDef(TEveBoxProjected, 0); // Projection of TEveBox. + ClassDefOverride(TEveBoxProjected, 0); // Projection of TEveBox. }; #endif diff --git a/graf3d/eve/inc/TEveBoxGL.h b/graf3d/eve/inc/TEveBoxGL.h index 308bd6e9d7fe6..3e74b7ac36a90 100644 --- a/graf3d/eve/inc/TEveBoxGL.h +++ b/graf3d/eve/inc/TEveBoxGL.h @@ -39,21 +39,21 @@ class TEveBoxGL : public TGLObject public: TEveBoxGL(); - virtual ~TEveBoxGL() {} + ~TEveBoxGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); - ClassDef(TEveBoxGL, 0); // GL renderer class for TEveBox. + ClassDefOverride(TEveBoxGL, 0); // GL renderer class for TEveBox. }; @@ -74,21 +74,21 @@ class TEveBoxProjectedGL : public TGLObject public: TEveBoxProjectedGL(); - virtual ~TEveBoxProjectedGL() {} + ~TEveBoxProjectedGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); - ClassDef(TEveBoxProjectedGL, 0); // GL renderer class for TEveBoxProjected. + ClassDefOverride(TEveBoxProjectedGL, 0); // GL renderer class for TEveBoxProjected. }; #endif diff --git a/graf3d/eve/inc/TEveBoxSet.h b/graf3d/eve/inc/TEveBoxSet.h index 06c42a9b3cbed..7b0e80214e2f6 100644 --- a/graf3d/eve/inc/TEveBoxSet.h +++ b/graf3d/eve/inc/TEveBoxSet.h @@ -65,7 +65,7 @@ class TEveBoxSet: public TEveDigitSet public: TEveBoxSet(const char* n="TEveBoxSet", const char* t=""); - virtual ~TEveBoxSet() {} + ~TEveBoxSet() override {} void Reset(EBoxType_e boxType, Bool_t valIsCol, Int_t chunkSize); void Reset(); @@ -79,7 +79,7 @@ class TEveBoxSet: public TEveDigitSet void AddHex(const TEveVector& pos, Float_t r, Float_t angle, Float_t depth); - virtual void ComputeBBox(); + void ComputeBBox() override; // virtual void Paint(Option_t* option = ""); void Test(Int_t nboxes); @@ -97,7 +97,7 @@ class TEveBoxSet: public TEveDigitSet Int_t GetBoxSkip() const { return fBoxSkip; } void SetBoxSkip(Int_t bs) { fBoxSkip = bs; } - ClassDef(TEveBoxSet, 0); // Collection of 3D primitives (fixed-size boxes, boxes of different sizes, or arbitrary sexto-epipeds); each primitive can be assigned a signal value and a TRef. + ClassDefOverride(TEveBoxSet, 0); // Collection of 3D primitives (fixed-size boxes, boxes of different sizes, or arbitrary sexto-epipeds); each primitive can be assigned a signal value and a TRef. }; #endif diff --git a/graf3d/eve/inc/TEveBoxSetGL.h b/graf3d/eve/inc/TEveBoxSetGL.h index 5127ccce25b9d..e458ec85c7389 100644 --- a/graf3d/eve/inc/TEveBoxSetGL.h +++ b/graf3d/eve/inc/TEveBoxSetGL.h @@ -35,18 +35,18 @@ class TEveBoxSetGL : public TEveDigitSetGL public: TEveBoxSetGL(); - virtual ~TEveBoxSetGL(); + ~TEveBoxSetGL() override; - virtual Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const; - virtual void DLCacheDrop(); - virtual void DLCachePurge(); + Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const override; + void DLCacheDrop() override; + void DLCachePurge() override; - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; virtual void Render(TGLRnrCtx& rnrCtx); - ClassDef(TEveBoxSetGL, 0); // GL-renderer for TEveBoxSet class. + ClassDefOverride(TEveBoxSetGL, 0); // GL-renderer for TEveBoxSet class. }; #endif diff --git a/graf3d/eve/inc/TEveBrowser.h b/graf3d/eve/inc/TEveBrowser.h index 3b5464e4a27c2..7fdbb22955d6b 100644 --- a/graf3d/eve/inc/TEveBrowser.h +++ b/graf3d/eve/inc/TEveBrowser.h @@ -39,43 +39,43 @@ class TEveListTreeItem : public TGListTreeItem public: TEveListTreeItem(TEveElement* el) : TGListTreeItem(), fElement(el) {} - virtual ~TEveListTreeItem() {} + ~TEveListTreeItem() override {} - virtual Bool_t IsActive() const { return fElement->GetSelectedLevel() != 0; } - virtual Pixel_t GetActiveColor() const; - virtual void SetActive(Bool_t) { NotSupported("SetActive"); } + Bool_t IsActive() const override { return fElement->GetSelectedLevel() != 0; } + Pixel_t GetActiveColor() const override; + void SetActive(Bool_t) override { NotSupported("SetActive"); } - virtual const char *GetText() const { return fElement->GetElementName(); } - virtual Int_t GetTextLength() const { return strlen(fElement->GetElementName()); } - virtual const char *GetTipText() const { return fElement->GetElementTitle(); } - virtual Int_t GetTipTextLength() const { return strlen(fElement->GetElementTitle()); } - virtual void SetText(const char *) { NotSupported("SetText"); } - virtual void SetTipText(const char *) { NotSupported("SetTipText"); } + const char *GetText() const override { return fElement->GetElementName(); } + Int_t GetTextLength() const override { return strlen(fElement->GetElementName()); } + const char *GetTipText() const override { return fElement->GetElementTitle(); } + Int_t GetTipTextLength() const override { return strlen(fElement->GetElementTitle()); } + void SetText(const char *) override { NotSupported("SetText"); } + void SetTipText(const char *) override { NotSupported("SetTipText"); } - virtual void SetUserData(void *, Bool_t=kFALSE) { NotSupported("SetUserData"); } - virtual void *GetUserData() const { return fElement; } + void SetUserData(void *, Bool_t=kFALSE) override { NotSupported("SetUserData"); } + void *GetUserData() const override { return fElement; } - virtual const TGPicture*GetPicture() const { return fElement->GetListTreeIcon(fOpen); } - virtual const TGPicture*GetCheckBoxPicture() const { return fElement->GetListTreeCheckBoxIcon(); } + const TGPicture*GetPicture() const override { return fElement->GetListTreeIcon(fOpen); } + const TGPicture*GetCheckBoxPicture() const override { return fElement->GetListTreeCheckBoxIcon(); } - virtual void SetPictures(const TGPicture*, const TGPicture*) { NotSupported("SetUserData"); } - virtual void SetCheckBoxPictures(const TGPicture*, const TGPicture*) { NotSupported("SetUserData"); } + void SetPictures(const TGPicture*, const TGPicture*) override { NotSupported("SetUserData"); } + void SetCheckBoxPictures(const TGPicture*, const TGPicture*) override { NotSupported("SetUserData"); } - virtual void SetCheckBox(Bool_t=kTRUE) { NotSupported("SetCheckBox"); } - virtual Bool_t HasCheckBox() const { return kTRUE; } - virtual void CheckItem(Bool_t=kTRUE) { printf("TEveListTreeItem::CheckItem - to be ignored ... all done via signal Checked().\n"); } - virtual void Toggle(); - virtual Bool_t IsChecked() const { return fElement->GetRnrState(); } + void SetCheckBox(Bool_t=kTRUE) override { NotSupported("SetCheckBox"); } + Bool_t HasCheckBox() const override { return kTRUE; } + void CheckItem(Bool_t=kTRUE) override { printf("TEveListTreeItem::CheckItem - to be ignored ... all done via signal Checked().\n"); } + void Toggle() override; + Bool_t IsChecked() const override { return fElement->GetRnrState(); } // Propagation of checked-state form children to parents. Not needed, ignore. // Item coloration (underline + minibox) - virtual Bool_t HasColor() const { return fElement->HasMainColor(); } - virtual Color_t GetColor() const { return fElement->GetMainColor(); } - virtual void SetColor(Color_t) { NotSupported("SetColor"); } - virtual void ClearColor() { NotSupported("ClearColor"); } + Bool_t HasColor() const override { return fElement->HasMainColor(); } + Color_t GetColor() const override { return fElement->GetMainColor(); } + void SetColor(Color_t) override { NotSupported("SetColor"); } + void ClearColor() override { NotSupported("ClearColor"); } - ClassDef(TEveListTreeItem,0); // Special llist-tree-item for Eve. + ClassDefOverride(TEveListTreeItem,0); // Special llist-tree-item for Eve. }; @@ -103,7 +103,7 @@ class TEveGListTreeEditorFrame : public TGMainFrame public: TEveGListTreeEditorFrame(const TGWindow *p = nullptr, Int_t width=250, Int_t height=700); - virtual ~TEveGListTreeEditorFrame(); + ~TEveGListTreeEditorFrame() override; void ConnectSignals(); void DisconnectSignals(); @@ -121,7 +121,7 @@ class TEveGListTreeEditorFrame : public TGMainFrame static void SetEditorClass(const char* edclass); - ClassDef(TEveGListTreeEditorFrame, 0); // Composite GUI frame for parallel display of a TGListTree and TEveGedEditor. + ClassDefOverride(TEveGListTreeEditorFrame, 0); // Composite GUI frame for parallel display of a TGListTree and TEveGedEditor. }; // ---------------------------------------------------------------- @@ -142,11 +142,11 @@ class TEveBrowser : public TRootBrowser public: TEveBrowser(UInt_t w, UInt_t h); - virtual ~TEveBrowser() { CloseTabs(); } + ~TEveBrowser() override { CloseTabs(); } - virtual void ReallyDelete(); - virtual void CloseTab(Int_t id); - virtual void CloseWindow(); + void ReallyDelete() override; + void CloseTab(Int_t id) override; + void CloseWindow() override; void InitPlugins(Option_t *opt="FI"); @@ -164,7 +164,7 @@ class TEveBrowser : public TRootBrowser void SanitizeTabCounts(); - ClassDef(TEveBrowser, 0); // Specialization of TRootBrowser for Eve. + ClassDefOverride(TEveBrowser, 0); // Specialization of TRootBrowser for Eve. }; #endif diff --git a/graf3d/eve/inc/TEveCalo.h b/graf3d/eve/inc/TEveCalo.h index b93df15fd280d..9a16346195c81 100644 --- a/graf3d/eve/inc/TEveCalo.h +++ b/graf3d/eve/inc/TEveCalo.h @@ -71,14 +71,14 @@ class TEveCaloViz : public TEveElement, public: TEveCaloViz(TEveCaloData* data=nullptr, const char* n="TEveCaloViz", const char* t=""); - virtual ~TEveCaloViz(); + ~TEveCaloViz() override; - virtual TEveElement* ForwardSelection(); - virtual TEveElement* ForwardEdit(); + TEveElement* ForwardSelection() override; + TEveElement* ForwardEdit() override; - virtual void Paint(Option_t* option=""); + void Paint(Option_t* option="") override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; virtual Float_t GetValToHeight() const; virtual void CellSelectionChanged() {} @@ -148,7 +148,7 @@ class TEveCaloViz : public TEveElement, Bool_t CellInEtaPhiRng (TEveCaloData::CellData_t&) const; - ClassDef(TEveCaloViz, 0); // Base-class for visualization of calorimeter eventdata. + ClassDefOverride(TEveCaloViz, 0); // Base-class for visualization of calorimeter eventdata. }; /**************************************************************************/ @@ -171,12 +171,12 @@ class TEveCalo3D : public TEveCaloViz Color_t fFrameColor; Char_t fFrameTransparency; - virtual void BuildCellIdCache(); + void BuildCellIdCache() override; public: TEveCalo3D(TEveCaloData* d=nullptr, const char* n="TEveCalo3D", const char* t="xx"); - virtual ~TEveCalo3D() {} - virtual void ComputeBBox(); + ~TEveCalo3D() override {} + void ComputeBBox() override; void SetFrameWidth(Float_t w) { fFrameWidth = w; } Float_t GetFrameWidth() const { return fFrameWidth; } @@ -191,7 +191,7 @@ class TEveCalo3D : public TEveCaloViz void SetFrameTransparency(Char_t x) { fFrameTransparency = x; } Char_t GetFrameTransparency() const { return fFrameTransparency; } - ClassDef(TEveCalo3D, 0); // Class for 3D visualization of calorimeter event data. + ClassDefOverride(TEveCalo3D, 0); // Class for 3D visualization of calorimeter event data. }; /**************************************************************************/ @@ -222,27 +222,27 @@ class TEveCalo2D : public TEveCaloViz, Float_t fMaxESumBin; Float_t fMaxEtSumBin; - virtual void BuildCellIdCache(); + void BuildCellIdCache() override; - virtual void SetDepthLocal(Float_t x) { fDepth = x; } + void SetDepthLocal(Float_t x) override { fDepth = x; } public: TEveCalo2D(const char* n="TEveCalo2D", const char* t=""); - virtual ~TEveCalo2D(); + ~TEveCalo2D() override; - virtual void SetProjection(TEveProjectionManager* proj, TEveProjectable* model); - virtual void UpdateProjection(); - virtual void ComputeBBox(); + void SetProjection(TEveProjectionManager* proj, TEveProjectable* model) override; + void UpdateProjection() override; + void ComputeBBox() override; - virtual void CellSelectionChanged(); + void CellSelectionChanged() override; - virtual void SetScaleAbs(Bool_t); + void SetScaleAbs(Bool_t) override; - virtual Float_t GetValToHeight() const; + Float_t GetValToHeight() const override; const TEveCalo2D::vBinCells_t& GetBinLists() const { return fCellLists; } - ClassDef(TEveCalo2D, 0); // Class for visualization of projected calorimeter event data. + ClassDefOverride(TEveCalo2D, 0); // Class for visualization of projected calorimeter event data. }; /**************************************************************************/ /**************************************************************************/ @@ -289,13 +289,13 @@ class TEveCaloLego : public TEveCaloViz Int_t fDrawNumberCellPixels; Int_t fCellPixelFontSize; - virtual void BuildCellIdCache(); + void BuildCellIdCache() override; public: TEveCaloLego(TEveCaloData* data=nullptr, const char* n="TEveCaloLego", const char* t=""); - virtual ~TEveCaloLego(){} + ~TEveCaloLego() override{} - virtual void ComputeBBox(); + void ComputeBBox() override; virtual void SetData(TEveCaloData* d); Color_t GetFontColor() const { return fFontColor; } @@ -348,7 +348,7 @@ class TEveCaloLego : public TEveCaloViz Int_t GetCellPixelFontSize() { return fCellPixelFontSize; } void SetCellPixelFontSize(Int_t x) { fCellPixelFontSize = x; } - ClassDef(TEveCaloLego, 0); // Class for visualization of calorimeter histogram data. + ClassDefOverride(TEveCaloLego, 0); // Class for visualization of calorimeter histogram data. }; #endif diff --git a/graf3d/eve/inc/TEveCalo2DGL.h b/graf3d/eve/inc/TEveCalo2DGL.h index 1b60542d28eb1..9d3d51c2722a4 100644 --- a/graf3d/eve/inc/TEveCalo2DGL.h +++ b/graf3d/eve/inc/TEveCalo2DGL.h @@ -45,20 +45,20 @@ class TEveCalo2DGL : public TGLObject public: TEveCalo2DGL(); - virtual ~TEveCalo2DGL() {} + ~TEveCalo2DGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; - virtual void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; + void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const override; // To support two-level selection - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual Bool_t AlwaysSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + Bool_t AlwaysSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec) override; - ClassDef(TEveCalo2DGL, 0); // GL renderer class for TEveCalo2D. + ClassDefOverride(TEveCalo2DGL, 0); // GL renderer class for TEveCalo2D. }; #endif diff --git a/graf3d/eve/inc/TEveCalo3DGL.h b/graf3d/eve/inc/TEveCalo3DGL.h index 140f3f4b42126..b868e9ccf2332 100644 --- a/graf3d/eve/inc/TEveCalo3DGL.h +++ b/graf3d/eve/inc/TEveCalo3DGL.h @@ -42,20 +42,20 @@ class TEveCalo3DGL : public TGLObject public: TEveCalo3DGL(); - virtual ~TEveCalo3DGL() {} + ~TEveCalo3DGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; - virtual void DrawHighlight(TGLRnrCtx & rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; + void DrawHighlight(TGLRnrCtx & rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const override; - virtual Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual Bool_t AlwaysSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); + Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const override; + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + Bool_t AlwaysSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec) override; - ClassDef(TEveCalo3DGL, 0); // GL renderer class for TEveCalo. + ClassDefOverride(TEveCalo3DGL, 0); // GL renderer class for TEveCalo. }; #endif diff --git a/graf3d/eve/inc/TEveCaloData.h b/graf3d/eve/inc/TEveCaloData.h index f336d099f7d03..b386bdbb32bf4 100644 --- a/graf3d/eve/inc/TEveCaloData.h +++ b/graf3d/eve/inc/TEveCaloData.h @@ -118,10 +118,10 @@ class TEveCaloData: public TEveElement, Float_t fValue; CellData_t() : CellGeom_t(), fValue(0) {} - virtual ~CellData_t() {} + ~CellData_t() override {} Float_t Value(Bool_t) const; - virtual void Dump() const; + void Dump() const override; }; @@ -172,14 +172,14 @@ class TEveCaloData: public TEveElement, public: TEveCaloData(const char* n="TEveCalData", const char* t=""); - virtual ~TEveCaloData() {} + ~TEveCaloData() override {} - virtual void UnSelected(); - virtual void UnHighlighted(); + void UnSelected() override; + void UnHighlighted() override; - virtual TString GetHighlightTooltip(); + TString GetHighlightTooltip() override; - virtual void FillImpliedSelectedSet(Set_t& impSelSet); + void FillImpliedSelectedSet(Set_t& impSelSet) override; virtual void GetCellList(Float_t etaMin, Float_t etaMax, Float_t phi, Float_t phiRng, @@ -230,7 +230,7 @@ class TEveCaloData: public TEveElement, static Float_t EtaToTheta(Float_t eta); - ClassDef(TEveCaloData, 0); // Manages calorimeter event data. + ClassDefOverride(TEveCaloData, 0); // Manages calorimeter event data. }; /**************************************************************************/ @@ -263,7 +263,7 @@ class TEveCaloDataVec: public TEveCaloData public: TEveCaloDataVec(Int_t nslices); - virtual ~TEveCaloDataVec(); + ~TEveCaloDataVec() override; Int_t AddSlice(); Int_t AddTower(Float_t etaMin, Float_t etaMax, Float_t phiMin, Float_t phiMax); @@ -274,21 +274,21 @@ class TEveCaloDataVec: public TEveCaloData std::vector& GetSliceVals(Int_t slice) { return fSliceVec[slice]; } std::vector& GetCellGeom() { return fGeomVec; } - virtual void GetCellList(Float_t etaMin, Float_t etaMax, + void GetCellList(Float_t etaMin, Float_t etaMax, Float_t phi, Float_t phiRng, - vCellId_t &out) const; + vCellId_t &out) const override; - virtual void Rebin(TAxis *ax, TAxis *ay, vCellId_t &in, Bool_t et, RebinData_t &out) const; + void Rebin(TAxis *ax, TAxis *ay, vCellId_t &in, Bool_t et, RebinData_t &out) const override; - virtual void GetCellData(const TEveCaloData::CellId_t &id, TEveCaloData::CellData_t& data) const; - virtual void GetEtaLimits(Double_t &min, Double_t &max) const { min=fEtaMin, max=fEtaMax;} - virtual void GetPhiLimits(Double_t &min, Double_t &max) const { min=fPhiMin; max=fPhiMax;} + void GetCellData(const TEveCaloData::CellId_t &id, TEveCaloData::CellData_t& data) const override; + void GetEtaLimits(Double_t &min, Double_t &max) const override { min=fEtaMin, max=fEtaMax;} + void GetPhiLimits(Double_t &min, Double_t &max) const override { min=fPhiMin; max=fPhiMax;} - virtual void DataChanged(); + void DataChanged() override; void SetAxisFromBins(Double_t epsX=0.001, Double_t epsY=0.001); - ClassDef(TEveCaloDataVec, 0); // Manages calorimeter event data. + ClassDefOverride(TEveCaloDataVec, 0); // Manages calorimeter event data. }; /**************************************************************************/ @@ -305,20 +305,20 @@ class TEveCaloDataHist: public TEveCaloData public: TEveCaloDataHist(); - virtual ~TEveCaloDataHist(); + ~TEveCaloDataHist() override; - virtual void GetCellList( Float_t etaMin, Float_t etaMax, - Float_t phi, Float_t phiRng, vCellId_t &out) const; + void GetCellList( Float_t etaMin, Float_t etaMax, + Float_t phi, Float_t phiRng, vCellId_t &out) const override; - virtual void Rebin(TAxis *ax, TAxis *ay, vCellId_t &in, Bool_t et, RebinData_t &out) const; + void Rebin(TAxis *ax, TAxis *ay, vCellId_t &in, Bool_t et, RebinData_t &out) const override; - virtual void GetCellData(const TEveCaloData::CellId_t &id, TEveCaloData::CellData_t& data) const; + void GetCellData(const TEveCaloData::CellId_t &id, TEveCaloData::CellData_t& data) const override; - virtual void GetEtaLimits(Double_t &min, Double_t &max) const; - virtual void GetPhiLimits(Double_t &min, Double_t &max) const; + void GetEtaLimits(Double_t &min, Double_t &max) const override; + void GetPhiLimits(Double_t &min, Double_t &max) const override; - virtual void DataChanged(); + void DataChanged() override; THStack* GetStack() { return fHStack; } @@ -326,7 +326,7 @@ class TEveCaloDataHist: public TEveCaloData Int_t AddHistogram(TH2F* hist); - ClassDef(TEveCaloDataHist, 0); // Manages calorimeter TH2F event data. + ClassDefOverride(TEveCaloDataHist, 0); // Manages calorimeter TH2F event data. }; #endif diff --git a/graf3d/eve/inc/TEveCaloLegoEditor.h b/graf3d/eve/inc/TEveCaloLegoEditor.h index 9f0605d55e617..e8f90ede9301e 100644 --- a/graf3d/eve/inc/TEveCaloLegoEditor.h +++ b/graf3d/eve/inc/TEveCaloLegoEditor.h @@ -53,9 +53,9 @@ class TEveCaloLegoEditor : public TGedFrame public: TEveCaloLegoEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveCaloLegoEditor() {} + ~TEveCaloLegoEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods void DoGridColor(Pixel_t color); @@ -73,7 +73,7 @@ class TEveCaloLegoEditor : public TGedFrame void DoPixelsPerBin(); void DoNormalize(); - ClassDef(TEveCaloLegoEditor, 0); // GUI editor for TEveCaloLego. + ClassDefOverride(TEveCaloLegoEditor, 0); // GUI editor for TEveCaloLego. }; #endif diff --git a/graf3d/eve/inc/TEveCaloLegoGL.h b/graf3d/eve/inc/TEveCaloLegoGL.h index ce47b2ee23e2d..2595eda687bdf 100644 --- a/graf3d/eve/inc/TEveCaloLegoGL.h +++ b/graf3d/eve/inc/TEveCaloLegoGL.h @@ -123,23 +123,23 @@ class TEveCaloLegoGL : public TGLObject public: TEveCaloLegoGL(); - virtual ~TEveCaloLegoGL(); + ~TEveCaloLegoGL() override; - virtual Bool_t SetModel(TObject* obj, const Option_t* opt = nullptr); + Bool_t SetModel(TObject* obj, const Option_t* opt = nullptr) override; - virtual void SetBBox(); + void SetBBox() override; - virtual void DLCacheDrop(); - virtual void DLCachePurge(); + void DLCacheDrop() override; + void DLCachePurge() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; - virtual void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; + void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* ps, Int_t lvl=-1) const override; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual Bool_t AlwaysSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + Bool_t AlwaysSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec) override; - ClassDef(TEveCaloLegoGL, 0); // GL renderer class for TEveCaloLego. + ClassDefOverride(TEveCaloLegoGL, 0); // GL renderer class for TEveCaloLego. }; //______________________________________________________________________________ diff --git a/graf3d/eve/inc/TEveCaloLegoOverlay.h b/graf3d/eve/inc/TEveCaloLegoOverlay.h index 5a312915ace94..6cc99b0b2d587 100644 --- a/graf3d/eve/inc/TEveCaloLegoOverlay.h +++ b/graf3d/eve/inc/TEveCaloLegoOverlay.h @@ -75,15 +75,15 @@ class TEveCaloLegoOverlay : public TGLCameraOverlay public: TEveCaloLegoOverlay(); - virtual ~TEveCaloLegoOverlay(){} + ~TEveCaloLegoOverlay() override{} //rendering - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; // event handling - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, Event_t* event) override; + void MouseLeave() override; TEveCaloLego* GetCaloLego() {return fCalo;} @@ -101,7 +101,7 @@ class TEveCaloLegoOverlay : public TGLCameraOverlay void SetFrameAttribs(Color_t frameCol, Char_t lineTransp, Char_t bgTransp); - ClassDef(TEveCaloLegoOverlay, 0); // GL-overaly control GUI for TEveCaloLego. + ClassDefOverride(TEveCaloLegoOverlay, 0); // GL-overaly control GUI for TEveCaloLego. }; #endif diff --git a/graf3d/eve/inc/TEveCaloVizEditor.h b/graf3d/eve/inc/TEveCaloVizEditor.h index 8cc3f69020895..2b304e660a093 100644 --- a/graf3d/eve/inc/TEveCaloVizEditor.h +++ b/graf3d/eve/inc/TEveCaloVizEditor.h @@ -54,9 +54,9 @@ class TEveCaloVizEditor : public TGedFrame public: TEveCaloVizEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveCaloVizEditor() {} + ~TEveCaloVizEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoMaxTowerH(); void DoScaleAbs(); @@ -71,7 +71,7 @@ class TEveCaloVizEditor : public TGedFrame void DoSliceColor(Pixel_t color); void DoSliceTransparency(Long_t transp); - ClassDef(TEveCaloVizEditor, 0); // GUI editor for TEveCaloVizEditor. + ClassDefOverride(TEveCaloVizEditor, 0); // GUI editor for TEveCaloVizEditor. }; /**************************************************************************/ @@ -89,12 +89,12 @@ class TEveCalo3DEditor : public TGedFrame public: TEveCalo3DEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveCalo3DEditor() {} + ~TEveCalo3DEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoFrameTransparency(); - ClassDef(TEveCalo3DEditor, 0); // GUI editor for TEveCalo3DEditor. + ClassDefOverride(TEveCalo3DEditor, 0); // GUI editor for TEveCalo3DEditor. }; #endif diff --git a/graf3d/eve/inc/TEveChunkManager.h b/graf3d/eve/inc/TEveChunkManager.h index 042b974ca4e37..c1a003ec0b209 100644 --- a/graf3d/eve/inc/TEveChunkManager.h +++ b/graf3d/eve/inc/TEveChunkManager.h @@ -130,14 +130,14 @@ class TEveChunkVector : public TEveChunkManager public: TEveChunkVector() : TEveChunkManager() {} TEveChunkVector(Int_t chunk_size) : TEveChunkManager(sizeof(T), chunk_size) {} - virtual ~TEveChunkVector() {} + ~TEveChunkVector() override {} void Reset(Int_t chunk_size) { Reset(sizeof(T), chunk_size); } T* At(Int_t idx) { return reinterpret_cast(Atom(idx)); } T& Ref(Int_t idx) { return *At(idx); } - ClassDef(TEveChunkVector, 1); // Templated class for specific atom classes (given as template argument). + ClassDefOverride(TEveChunkVector, 1); // Templated class for specific atom classes (given as template argument). }; #endif diff --git a/graf3d/eve/inc/TEveCompound.h b/graf3d/eve/inc/TEveCompound.h index b0000e32884c9..89f86de366dfe 100644 --- a/graf3d/eve/inc/TEveCompound.h +++ b/graf3d/eve/inc/TEveCompound.h @@ -32,24 +32,24 @@ class TEveCompound : public TEveElementList public: TEveCompound(const char* n="TEveCompound", const char* t="", Bool_t doColor=kTRUE, Bool_t doTransparency=kFALSE); - virtual ~TEveCompound() {} + ~TEveCompound() override {} void OpenCompound() { ++fCompoundOpen; } void CloseCompound() { --fCompoundOpen; } Bool_t IsCompoundOpen() const { return fCompoundOpen > 0; } - virtual void SetMainColor(Color_t color); - virtual void SetMainTransparency(Char_t t); + void SetMainColor(Color_t color) override; + void SetMainTransparency(Char_t t) override; - virtual void AddElement(TEveElement* el); - virtual void RemoveElementLocal(TEveElement* el); - virtual void RemoveElementsLocal(); + void AddElement(TEveElement* el) override; + void RemoveElementLocal(TEveElement* el) override; + void RemoveElementsLocal() override; - virtual void FillImpliedSelectedSet(Set_t& impSelSet); + void FillImpliedSelectedSet(Set_t& impSelSet) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEveCompound, 0); // Container for managing compounds of TEveElements. + ClassDefOverride(TEveCompound, 0); // Container for managing compounds of TEveElements. }; @@ -66,14 +66,14 @@ class TEveCompoundProjected : public TEveCompound, public: TEveCompoundProjected(); - virtual ~TEveCompoundProjected() {} + ~TEveCompoundProjected() override {} - virtual void SetMainColor(Color_t color); + void SetMainColor(Color_t color) override; - virtual void UpdateProjection() {} - virtual TEveElement* GetProjectedAsElement() { return this; } + void UpdateProjection() override {} + TEveElement* GetProjectedAsElement() override { return this; } - ClassDef(TEveCompoundProjected, 0); // Projected TEveCompund container. + ClassDefOverride(TEveCompoundProjected, 0); // Projected TEveCompund container. }; #endif diff --git a/graf3d/eve/inc/TEveDigitSet.h b/graf3d/eve/inc/TEveDigitSet.h index 7ed7c15981326..c014bbeafc257 100644 --- a/graf3d/eve/inc/TEveDigitSet.h +++ b/graf3d/eve/inc/TEveDigitSet.h @@ -84,9 +84,9 @@ class TEveDigitSet : public TEveElement, public: TEveDigitSet(const char* n="TEveDigitSet", const char* t=""); - virtual ~TEveDigitSet(); + ~TEveDigitSet() override; - virtual TObject* GetObject(const TEveException&) const + TObject* GetObject(const TEveException&) const override { const TObject* obj = this; return const_cast(obj); } void UseSingleColor(); @@ -94,12 +94,12 @@ class TEveDigitSet : public TEveElement, Bool_t GetAntiFlick() const { return fAntiFlick; } void SetAntiFlick(Bool_t f) { fAntiFlick = f; } - virtual void SetMainColor(Color_t color); + void SetMainColor(Color_t color) override; - virtual void UnSelected(); - virtual void UnHighlighted(); + void UnSelected() override; + void UnHighlighted() override; - virtual TString GetHighlightTooltip(); + TString GetHighlightTooltip() override; // Implemented in sub-classes: // virtual void Reset(EQuadType_e quadType, Bool_t valIsCol, Int_t chunkSize); @@ -136,7 +136,7 @@ class TEveDigitSet : public TEveElement, // Implemented in subclasses: // virtual void ComputeBBox(); - virtual void Paint(Option_t* option=""); + void Paint(Option_t* option="") override; virtual void DigitSelected(Int_t idx); virtual void SecSelected(TEveDigitSet* qs, Int_t idx); // *SIGNAL* @@ -178,7 +178,7 @@ class TEveDigitSet : public TEveElement, TooltipCB_foo GetTooltipCBFoo() const { return fTooltipCBFoo; } void SetTooltipCBFoo(TooltipCB_foo f) { fTooltipCBFoo = f; } - ClassDef(TEveDigitSet, 0); // Base-class for storage of digit collections; provides transformation matrix (TEveTrans), signal to color mapping (TEveRGBAPalette) and visual grouping (TEveFrameBox). + ClassDefOverride(TEveDigitSet, 0); // Base-class for storage of digit collections; provides transformation matrix (TEveTrans), signal to color mapping (TEveRGBAPalette) and visual grouping (TEveFrameBox). }; #endif diff --git a/graf3d/eve/inc/TEveDigitSetEditor.h b/graf3d/eve/inc/TEveDigitSetEditor.h index 41de6ddde83ef..1ede49d06cf70 100644 --- a/graf3d/eve/inc/TEveDigitSetEditor.h +++ b/graf3d/eve/inc/TEveDigitSetEditor.h @@ -46,16 +46,16 @@ class TEveDigitSetEditor : public TGedFrame public: TEveDigitSetEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveDigitSetEditor() {} + ~TEveDigitSetEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods void DoHisto(); void DoRangeHisto(); void PlotHisto(Int_t min, Int_t max); - ClassDef(TEveDigitSetEditor, 0); // Editor for TEveDigitSet class. + ClassDefOverride(TEveDigitSetEditor, 0); // Editor for TEveDigitSet class. }; #endif diff --git a/graf3d/eve/inc/TEveDigitSetGL.h b/graf3d/eve/inc/TEveDigitSetGL.h index 17492b63e81e4..9bbda50a9bffc 100644 --- a/graf3d/eve/inc/TEveDigitSetGL.h +++ b/graf3d/eve/inc/TEveDigitSetGL.h @@ -36,17 +36,17 @@ class TEveDigitSetGL : public TGLObject public: TEveDigitSetGL(); - virtual ~TEveDigitSetGL() {} + ~TEveDigitSetGL() override {} - virtual void SetBBox(); + void SetBBox() override; - virtual void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* pshp, Int_t lvl=-1) const; + void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* pshp, Int_t lvl=-1) const override; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual Bool_t AlwaysSecondarySelect() const { return ((TEveDigitSet*)fExternalObj)->GetAlwaysSecSelect(); } - virtual void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec); + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + Bool_t AlwaysSecondarySelect() const override { return ((TEveDigitSet*)fExternalObj)->GetAlwaysSecSelect(); } + void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec) override; - ClassDef(TEveDigitSetGL, 0); // GL renderer class for TEveDigitSet. + ClassDefOverride(TEveDigitSetGL, 0); // GL renderer class for TEveDigitSet. }; #endif diff --git a/graf3d/eve/inc/TEveElement.h b/graf3d/eve/inc/TEveElement.h index 1126717d651a1..b15c00ca57490 100644 --- a/graf3d/eve/inc/TEveElement.h +++ b/graf3d/eve/inc/TEveElement.h @@ -442,33 +442,33 @@ class TEveElementList : public TEveElement, TEveElementList(const char* n="TEveElementList", const char* t="", Bool_t doColor=kFALSE, Bool_t doTransparency=kFALSE); TEveElementList(const TEveElementList& e); - virtual ~TEveElementList() {} + ~TEveElementList() override {} - virtual TObject* GetObject(const TEveException& /*eh*/="TEveElementList::GetObject ") const + TObject* GetObject(const TEveException& /*eh*/="TEveElementList::GetObject ") const override { const TObject* obj = this; return const_cast(obj); } - virtual TEveElementList* CloneElement() const; + TEveElementList* CloneElement() const override; - virtual const char* GetElementName() const { return GetName(); } - virtual const char* GetElementTitle() const { return GetTitle(); } + const char* GetElementName() const override { return GetName(); } + const char* GetElementTitle() const override { return GetTitle(); } - virtual void SetElementName (const char* name) + void SetElementName (const char* name) override { TNamed::SetName(name); NameTitleChanged(); } - virtual void SetElementTitle(const char* title) + void SetElementTitle(const char* title) override { TNamed::SetTitle(title); NameTitleChanged(); } - virtual void SetElementNameTitle(const char* name, const char* title) + void SetElementNameTitle(const char* name, const char* title) override { TNamed::SetNameTitle(name, title); NameTitleChanged(); } TClass* GetChildClass() const { return fChildClass; } void SetChildClass(TClass* c) { fChildClass = c; } - virtual Bool_t AcceptElement(TEveElement* el); + Bool_t AcceptElement(TEveElement* el) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEveElementList, 0); // List of TEveElement objects with a possibility to limit the class of accepted elements. + ClassDefOverride(TEveElementList, 0); // List of TEveElement objects with a possibility to limit the class of accepted elements. }; @@ -485,12 +485,12 @@ class TEveElementListProjected : public TEveElementList, public: TEveElementListProjected(); - virtual ~TEveElementListProjected() {} + ~TEveElementListProjected() override {} - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } - ClassDef(TEveElementListProjected, 0); // Projected TEveElementList. + ClassDefOverride(TEveElementListProjected, 0); // Projected TEveElementList. }; #endif diff --git a/graf3d/eve/inc/TEveElementEditor.h b/graf3d/eve/inc/TEveElementEditor.h index 63e5a7970068e..7d244e4a043cb 100644 --- a/graf3d/eve/inc/TEveElementEditor.h +++ b/graf3d/eve/inc/TEveElementEditor.h @@ -42,9 +42,9 @@ class TEveElementEditor : public TGedFrame public: TEveElementEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveElementEditor() {} + ~TEveElementEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoRnrSelf(); void DoRnrChildren(); @@ -52,7 +52,7 @@ class TEveElementEditor : public TGedFrame void DoMainColor(Pixel_t color); void DoTransparency(); - ClassDef(TEveElementEditor, 0); // Editor for TEveElement class. + ClassDefOverride(TEveElementEditor, 0); // Editor for TEveElement class. }; #endif diff --git a/graf3d/eve/inc/TEveEventManager.h b/graf3d/eve/inc/TEveEventManager.h index a811b8a0798f0..b0db777851fd9 100644 --- a/graf3d/eve/inc/TEveEventManager.h +++ b/graf3d/eve/inc/TEveEventManager.h @@ -23,7 +23,7 @@ class TEveEventManager : public TEveElementList public: TEveEventManager(const char* n="TEveEventManager", const char* t=""); - virtual ~TEveEventManager() {} + ~TEveEventManager() override {} std::vector& GetNewEventCommands() { return fNewEventCommands; } @@ -39,7 +39,7 @@ class TEveEventManager : public TEveElementList virtual void RemoveNewEventCommand(const TString& cmd); virtual void ClearNewEventCommands(); - ClassDef(TEveEventManager, 0); // Base class for event management and navigation. + ClassDefOverride(TEveEventManager, 0); // Base class for event management and navigation. }; #endif diff --git a/graf3d/eve/inc/TEveFrameBox.h b/graf3d/eve/inc/TEveFrameBox.h index cd8c05882e461..d62c59c9cb21f 100644 --- a/graf3d/eve/inc/TEveFrameBox.h +++ b/graf3d/eve/inc/TEveFrameBox.h @@ -41,7 +41,7 @@ class TEveFrameBox : public TObject, public TEveRefBackPtr public: TEveFrameBox(); - virtual ~TEveFrameBox(); + ~TEveFrameBox() override; void SetAAQuadXY(Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dy); void SetAAQuadXZ(Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dz); @@ -85,9 +85,9 @@ class TEveFrameBox : public TObject, public TEveRefBackPtr Bool_t GetDrawBack() const { return fDrawBack; } void SetDrawBack(Bool_t f) { fDrawBack = f; } - virtual void OnZeroRefCount() { delete this; } + void OnZeroRefCount() override { delete this; } - ClassDef(TEveFrameBox, 0); // Description of a 2D or 3D frame that can be used to visually group a set of objects. + ClassDefOverride(TEveFrameBox, 0); // Description of a 2D or 3D frame that can be used to visually group a set of objects. }; #endif diff --git a/graf3d/eve/inc/TEveGValuators.h b/graf3d/eve/inc/TEveGValuators.h index 8510d41a8b108..839f164f7b743 100644 --- a/graf3d/eve/inc/TEveGValuators.h +++ b/graf3d/eve/inc/TEveGValuators.h @@ -35,7 +35,7 @@ class TEveGValuatorBase: public TGCompositeFrame, public TGWidget public: TEveGValuatorBase(const TGWindow *p, const char* title, UInt_t w, UInt_t h, Int_t widgetId=-1); - virtual ~TEveGValuatorBase() {} + ~TEveGValuatorBase() override {} virtual void Build(Bool_t connect=kTRUE) = 0; @@ -48,7 +48,7 @@ class TEveGValuatorBase: public TGCompositeFrame, public TGWidget TGLabel* GetLabel() {return fLabel;} - ClassDef(TEveGValuatorBase, 0); // Base class for composite GUI elements for setting of numeric values. + ClassDefOverride(TEveGValuatorBase, 0); // Base class for composite GUI elements for setting of numeric values. }; @@ -73,9 +73,9 @@ class TEveGValuator: public TEveGValuatorBase public: TEveGValuator(const TGWindow *p, const char* title, UInt_t w, UInt_t h, Int_t widgetId=-1); - virtual ~TEveGValuator() {} + ~TEveGValuator() override {} - virtual void Build(Bool_t connect=kTRUE); + void Build(Bool_t connect=kTRUE) override; Float_t GetValue() const { return fValue; } virtual void SetValue(Float_t v, Bool_t emit=kFALSE); @@ -99,7 +99,7 @@ class TEveGValuator: public TEveGValuatorBase void SetToolTip(const char* tip); void SetEnabled(Bool_t state); - ClassDef(TEveGValuator, 0); // Composite GUI element for single value selection (supports label, number-entry and slider). + ClassDefOverride(TEveGValuator, 0); // Composite GUI element for single value selection (supports label, number-entry and slider). }; @@ -117,9 +117,9 @@ class TEveGDoubleValuator: public TEveGValuatorBase public: TEveGDoubleValuator(const TGWindow *p, const char* title, UInt_t w, UInt_t h, Int_t widgetId=-1); - virtual ~TEveGDoubleValuator() {} + ~TEveGDoubleValuator() override {} - virtual void Build(Bool_t connect=kTRUE); + void Build(Bool_t connect=kTRUE) override; void MinEntryCallback(); void MaxEntryCallback(); @@ -141,7 +141,7 @@ class TEveGDoubleValuator: public TEveGValuatorBase Float_t GetLimitMin() const { return fMinEntry->GetNumMin(); } Float_t GetLimitMax() const { return fMaxEntry->GetNumMax(); } - ClassDef(TEveGDoubleValuator, 0); // Composite GUI element for selection of range (label, two number-entries and double-slider). + ClassDefOverride(TEveGDoubleValuator, 0); // Composite GUI element for selection of range (label, two number-entries and double-slider). }; @@ -162,7 +162,7 @@ class TEveGTriVecValuator : public TGCompositeFrame, public TGWidget public: TEveGTriVecValuator(const TGWindow *p, const char* name, UInt_t w, UInt_t h, Int_t widgetId=-1); - virtual ~TEveGTriVecValuator() {} + ~TEveGTriVecValuator() override {} void Build(Bool_t vertical, const char* lab0, const char* lab1, const char* lab2); @@ -196,7 +196,7 @@ class TEveGTriVecValuator : public TGCompositeFrame, public TGWidget void SetLimits(Float_t min, Float_t max, TGNumberFormat::EStyle nef=TGNumberFormat::kNESRealTwo); - ClassDef(TEveGTriVecValuator, 0); // Composite GUI element for setting three numerical values (label, three number-entries). + ClassDefOverride(TEveGTriVecValuator, 0); // Composite GUI element for setting three numerical values (label, three number-entries). }; #endif diff --git a/graf3d/eve/inc/TEveGedEditor.h b/graf3d/eve/inc/TEveGedEditor.h index 3603060cf4fce..78bd0add92204 100644 --- a/graf3d/eve/inc/TEveGedEditor.h +++ b/graf3d/eve/inc/TEveGedEditor.h @@ -35,7 +35,7 @@ class TEveGedEditor : public TGedEditor TEveElement *fElement; // Cached eve-element pointer. TObject *fObject; // Cached tobj pointer. - virtual TGedFrame* CreateNameFrame(const TGWindow* parent, const char* tab_name); + TGedFrame* CreateNameFrame(const TGWindow* parent, const char* tab_name) override; static Int_t fgMaxExtraEditors; static TList *fgExtraEditors; @@ -44,17 +44,17 @@ class TEveGedEditor : public TGedEditor public: TEveGedEditor(TCanvas* canvas=nullptr, UInt_t width=250, UInt_t height=400); - virtual ~TEveGedEditor(); + ~TEveGedEditor() override; - virtual void CloseWindow(); + void CloseWindow() override; TEveElement* GetEveElement() const; void DisplayElement(TEveElement* re); void DisplayObject(TObject* obj); - virtual void SetModel(TVirtualPad* pad, TObject* obj, Int_t event, Bool_t force=kFALSE); - virtual void Update(TGedFrame* gframe=nullptr); + void SetModel(TVirtualPad* pad, TObject* obj, Int_t event, Bool_t force=kFALSE) override; + void Update(TGedFrame* gframe=nullptr) override; // --- Statics for extra editors. --- @@ -66,7 +66,7 @@ class TEveGedEditor : public TGedEditor static TContextMenu* GetContextMenu(); - ClassDef(TEveGedEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. + ClassDefOverride(TEveGedEditor, 0); // Specialization of TGedEditor for proper update propagation to TEveManager. }; @@ -86,13 +86,13 @@ class TEveGedNameFrame : public TGedFrame public: TEveGedNameFrame(const TGWindow *p=nullptr, Int_t width=140, Int_t height=30, UInt_t options=kChildFrame | kHorizontalFrame); - virtual ~TEveGedNameFrame(); + ~TEveGedNameFrame() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void SpawnEditorClone(); - ClassDef(TEveGedNameFrame, 0); // Top name-frame used in EVE. + ClassDefOverride(TEveGedNameFrame, 0); // Top name-frame used in EVE. }; @@ -110,11 +110,11 @@ class TEveGedNameTextButton : public TGTextButton public: TEveGedNameTextButton(TEveGedNameFrame* p); - virtual ~TEveGedNameTextButton(); + ~TEveGedNameTextButton() override; - virtual Bool_t HandleButton(Event_t* event); + Bool_t HandleButton(Event_t* event) override; - ClassDef(TEveGedNameTextButton, 0); // Button for GED name-frame. + ClassDefOverride(TEveGedNameTextButton, 0); // Button for GED name-frame. }; #endif diff --git a/graf3d/eve/inc/TEveGeoNode.h b/graf3d/eve/inc/TEveGeoNode.h index 451f3f8f80edf..cbc6ff14d303a 100644 --- a/graf3d/eve/inc/TEveGeoNode.h +++ b/graf3d/eve/inc/TEveGeoNode.h @@ -43,31 +43,31 @@ class TEveGeoNode : public TEveElement, public: TEveGeoNode(TGeoNode* node); - virtual TObject* GetObject(const TEveException&) const + TObject* GetObject(const TEveException&) const override { const TObject* obj = this; return const_cast(obj); } - virtual const char* GetName() const; - virtual const char* GetTitle() const; - virtual const char* GetElementName() const; - virtual const char* GetElementTitle() const; + const char* GetName() const override; + const char* GetTitle() const override; + const char* GetElementName() const override; + const char* GetElementTitle() const override; TGeoNode* GetNode() const { return fNode; } - virtual void ExpandIntoListTree(TGListTree* ltree, TGListTreeItem* parent); + void ExpandIntoListTree(TGListTree* ltree, TGListTreeItem* parent) override; virtual void ExpandIntoListTrees(); virtual void ExpandIntoListTreesRecursively(); - virtual Bool_t CanEditElement() const { return kFALSE; } + Bool_t CanEditElement() const override { return kFALSE; } - virtual void AddStamp(UChar_t bits); + void AddStamp(UChar_t bits) override; - virtual Bool_t CanEditMainColor() const; - virtual void SetMainColor(Color_t color); + Bool_t CanEditMainColor() const override; + void SetMainColor(Color_t color) override; - virtual Bool_t CanEditMainTransparency() const; - virtual Char_t GetMainTransparency() const; - virtual void SetMainTransparency(Char_t t); + Bool_t CanEditMainTransparency() const override; + Char_t GetMainTransparency() const override; + void SetMainTransparency(Char_t t) override; void UpdateNode(TGeoNode* node); void UpdateVolume(TGeoVolume* volume); @@ -76,12 +76,12 @@ class TEveGeoNode : public TEveElement, void SaveExtract(const char* file, const char* name, Bool_t leafs_only); void WriteExtract(const char* name, Bool_t leafs_only); - virtual void Draw(Option_t* option=""); + void Draw(Option_t* option="") override; static Int_t GetCSGExportNSeg(); static void SetCSGExportNSeg(Int_t nseg); - ClassDef(TEveGeoNode, 0); // Wrapper for TGeoNode that allows it to be shown in GUI and controlled as a TEveElement. + ClassDefOverride(TEveGeoNode, 0); // Wrapper for TGeoNode that allows it to be shown in GUI and controlled as a TEveElement. }; //---------------------------------------------------------------- @@ -100,7 +100,7 @@ class TEveGeoTopNode : public TEveGeoNode public: TEveGeoTopNode(TGeoManager* manager, TGeoNode* node, Int_t visopt=1, Int_t vislvl=3, Int_t maxvisnds=10000); - virtual ~TEveGeoTopNode() {} + ~TEveGeoTopNode() override {} void UseNodeTrans(); @@ -113,13 +113,13 @@ class TEveGeoTopNode : public TEveGeoNode Int_t GetMaxVisNodes() const { return fMaxVisNodes; } void SetMaxVisNodes(Int_t mvn) { fMaxVisNodes = mvn; } - virtual Bool_t CanEditElement() const { return kTRUE; } - virtual Bool_t SingleRnrState() const { return kTRUE; } + Bool_t CanEditElement() const override { return kTRUE; } + Bool_t SingleRnrState() const override { return kTRUE; } - virtual void AddStamp(UChar_t bits); + void AddStamp(UChar_t bits) override; - virtual void Draw(Option_t* option=""); - virtual void Paint(Option_t* option=""); + void Draw(Option_t* option="") override; + void Paint(Option_t* option="") override; // Signals from GeoManager. // These are not available any more ... colors in list-tree not refreshed @@ -128,7 +128,7 @@ class TEveGeoTopNode : public TEveGeoNode void VolumeColChanged(TGeoVolume* volume); void NodeVisChanged(TGeoNode* node); - ClassDef(TEveGeoTopNode, 0); // Top-level TEveGeoNode with a pointer to TGeoManager and controls for steering of TGeoPainter. + ClassDefOverride(TEveGeoTopNode, 0); // Top-level TEveGeoNode with a pointer to TGeoManager and controls for steering of TGeoPainter. }; #endif diff --git a/graf3d/eve/inc/TEveGeoNodeEditor.h b/graf3d/eve/inc/TEveGeoNodeEditor.h index 0c02ad39fd348..54e15bd569a4e 100644 --- a/graf3d/eve/inc/TEveGeoNodeEditor.h +++ b/graf3d/eve/inc/TEveGeoNodeEditor.h @@ -39,16 +39,16 @@ class TEveGeoNodeEditor : public TGedFrame public: TEveGeoNodeEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveGeoNodeEditor() {} + ~TEveGeoNodeEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoVizNode(); void DoVizNodeDaughters(); void DoVizVolume(); void DoVizVolumeDaughters(); - ClassDef(TEveGeoNodeEditor, 0); // Editor for TEveGeoNode class. + ClassDefOverride(TEveGeoNodeEditor, 0); // Editor for TEveGeoNode class. }; /******************************************************************************/ @@ -68,15 +68,15 @@ class TEveGeoTopNodeEditor : public TGedFrame public: TEveGeoTopNodeEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveGeoTopNodeEditor() {} + ~TEveGeoTopNodeEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoVisOption(); void DoVisLevel(); void DoMaxVisNodes(); - ClassDef(TEveGeoTopNodeEditor, 0); // Editor for TEveGeoTopNode class. + ClassDefOverride(TEveGeoTopNodeEditor, 0); // Editor for TEveGeoTopNode class. }; #endif diff --git a/graf3d/eve/inc/TEveGeoPolyShape.h b/graf3d/eve/inc/TEveGeoPolyShape.h index a89f4ae80b450..462e8a94ca08d 100644 --- a/graf3d/eve/inc/TEveGeoPolyShape.h +++ b/graf3d/eve/inc/TEveGeoPolyShape.h @@ -33,7 +33,7 @@ class TEveGeoPolyShape : public TGeoBBox std::vector fPolyDesc; UInt_t fNbPols; - virtual void FillBuffer3D(TBuffer3D& buffer, Int_t reqSections, Bool_t localFrame) const; + void FillBuffer3D(TBuffer3D& buffer, Int_t reqSections, Bool_t localFrame) const override; struct Edge_t { @@ -55,16 +55,16 @@ class TEveGeoPolyShape : public TGeoBBox public: TEveGeoPolyShape(); - virtual ~TEveGeoPolyShape() {} + ~TEveGeoPolyShape() override {} static TEveGeoPolyShape* Construct(TGeoCompositeShape *cshp, Int_t n_seg); void SetFromFaceSet(TGLFaceSet* fs); - virtual const TBuffer3D& GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual TBuffer3D* MakeBuffer3D() const; + const TBuffer3D& GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + TBuffer3D* MakeBuffer3D() const override; - ClassDef(TEveGeoPolyShape, 1); // A shape with arbitrary tesselation for visualization of CSG shapes. + ClassDefOverride(TEveGeoPolyShape, 1); // A shape with arbitrary tesselation for visualization of CSG shapes. }; #endif diff --git a/graf3d/eve/inc/TEveGeoShape.h b/graf3d/eve/inc/TEveGeoShape.h index b79aea55413eb..b4db77a543b1e 100644 --- a/graf3d/eve/inc/TEveGeoShape.h +++ b/graf3d/eve/inc/TEveGeoShape.h @@ -40,9 +40,9 @@ class TEveGeoShape : public TEveShape public: TEveGeoShape(const char* name="TEveGeoShape", const char* title=nullptr); - virtual ~TEveGeoShape(); + ~TEveGeoShape() override; - virtual TObject* GetObject(const TEveException&) const + TObject* GetObject(const TEveException&) const override { const TObject* obj = this; return const_cast(obj); } Int_t GetNSegments() const { return fNSegments; } @@ -50,8 +50,8 @@ class TEveGeoShape : public TEveShape void SetNSegments(Int_t s); void SetShape(TGeoShape* s); - virtual void ComputeBBox(); - virtual void Paint(Option_t* option=""); + void ComputeBBox() override; + void Paint(Option_t* option="") override; void Save(const char* file, const char* name="Extract"); void SaveExtract(const char* file, const char* name); @@ -61,12 +61,12 @@ class TEveGeoShape : public TEveShape // GeoProjectable virtual TBuffer3D* MakeBuffer3D(); - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; static TGeoManager* GetGeoMangeur(); static TGeoHMatrix* GetGeoHMatrixIdentity(); - ClassDef(TEveGeoShape, 0); // Wrapper for TGeoShape with absolute positioning and color attributes allowing display of extracted TGeoShape's (without an active TGeoManager) and simplified geometries (needed for NLT projections). + ClassDefOverride(TEveGeoShape, 0); // Wrapper for TGeoShape with absolute positioning and color attributes allowing display of extracted TGeoShape's (without an active TGeoManager) and simplified geometries (needed for NLT projections). }; //------------------------------------------------------------------------------ @@ -81,19 +81,19 @@ class TEveGeoShapeProjected : public TEveShape, protected: TBuffer3D *fBuff; - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveGeoShapeProjected(); - virtual ~TEveGeoShapeProjected(); + ~TEveGeoShapeProjected() override; - virtual void SetProjection(TEveProjectionManager* proj, TEveProjectable* model); - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* proj, TEveProjectable* model) override; + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } - virtual void ComputeBBox(); + void ComputeBBox() override; - ClassDef(TEveGeoShapeProjected, 0); + ClassDefOverride(TEveGeoShapeProjected, 0); }; #endif diff --git a/graf3d/eve/inc/TEveGeoShapeExtract.h b/graf3d/eve/inc/TEveGeoShapeExtract.h index 363c4da2ee1b6..4971186fa35ff 100644 --- a/graf3d/eve/inc/TEveGeoShapeExtract.h +++ b/graf3d/eve/inc/TEveGeoShapeExtract.h @@ -35,7 +35,7 @@ class TEveGeoShapeExtract : public TNamed public: TEveGeoShapeExtract(const char* n="TEveGeoShapeExtract", const char* t=nullptr); - ~TEveGeoShapeExtract(); + ~TEveGeoShapeExtract() override; Bool_t HasElements(); void AddElement(TEveGeoShapeExtract* gse); @@ -60,7 +60,7 @@ class TEveGeoShapeExtract : public TNamed TGeoShape* GetShape() { return fShape; } TList* GetElements() { return fElements; } - ClassDef(TEveGeoShapeExtract, 2); // Globally positioned TGeoShape with rendering attributes and an optional list of daughter shape-extracts. + ClassDefOverride(TEveGeoShapeExtract, 2); // Globally positioned TGeoShape with rendering attributes and an optional list of daughter shape-extracts. }; #endif diff --git a/graf3d/eve/inc/TEveGridStepper.h b/graf3d/eve/inc/TEveGridStepper.h index bfc58beed36bc..16fd7f6a850f7 100644 --- a/graf3d/eve/inc/TEveGridStepper.h +++ b/graf3d/eve/inc/TEveGridStepper.h @@ -41,7 +41,7 @@ class TEveGridStepper : public TObject public: TEveGridStepper(Int_t sm=kSM_XYZ); - virtual ~TEveGridStepper() {} + ~TEveGridStepper() override {} void Reset(); void Subtract(TEveGridStepper& s); @@ -72,7 +72,7 @@ class TEveGridStepper : public TObject Float_t GetOy() const { return fOy; } Float_t GetOz() const { return fOz; } - ClassDef(TEveGridStepper, 1); // Provide discrete position coordinates for placement of objects on regular grids. + ClassDefOverride(TEveGridStepper, 1); // Provide discrete position coordinates for placement of objects on regular grids. }; // end class TEveGridStepper #endif diff --git a/graf3d/eve/inc/TEveGridStepperEditor.h b/graf3d/eve/inc/TEveGridStepperEditor.h index bcbe1090a813d..d7085393761b8 100644 --- a/graf3d/eve/inc/TEveGridStepperEditor.h +++ b/graf3d/eve/inc/TEveGridStepperEditor.h @@ -40,7 +40,7 @@ class TEveGridStepperSubEditor : public TGVerticalFrame public: TEveGridStepperSubEditor(const TGWindow* p); - virtual ~TEveGridStepperSubEditor() {} + ~TEveGridStepperSubEditor() override {} void SetModel(TEveGridStepper* m); @@ -49,7 +49,7 @@ class TEveGridStepperSubEditor : public TGVerticalFrame void DoNs(); void DoDs(); - ClassDef(TEveGridStepperSubEditor, 0); // Sub-editor for TEveGridStepper class. + ClassDefOverride(TEveGridStepperSubEditor, 0); // Sub-editor for TEveGridStepper class. }; @@ -65,11 +65,11 @@ class TEveGridStepperEditor : public TGedFrame public: TEveGridStepperEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveGridStepperEditor() {} + ~TEveGridStepperEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; - ClassDef(TEveGridStepperEditor, 0); // Editor for TEveGridStepper class. + ClassDefOverride(TEveGridStepperEditor, 0); // Editor for TEveGridStepper class. }; #endif diff --git a/graf3d/eve/inc/TEveJetCone.h b/graf3d/eve/inc/TEveJetCone.h index 02341a86b14db..f8c0777f939ae 100644 --- a/graf3d/eve/inc/TEveJetCone.h +++ b/graf3d/eve/inc/TEveJetCone.h @@ -46,10 +46,10 @@ class TEveJetCone : public TEveShape public: TEveJetCone(const Text_t* n="TEveJetCone", const Text_t* t=""); - virtual ~TEveJetCone() {} + ~TEveJetCone() override {} - virtual void ComputeBBox(); - virtual TClass* ProjectedClass(const TEveProjection* p) const; + void ComputeBBox() override; + TClass* ProjectedClass(const TEveProjection* p) const override; void SetApex(const TEveVector& a) { fApex = a; } void SetCylinder(Float_t r, Float_t z) { fLimits.Set(0, r, z); fThetaC = fLimits.Theta(); } @@ -61,7 +61,7 @@ class TEveJetCone : public TEveShape Int_t AddCone(Float_t eta, Float_t phi, Float_t cone_r, Float_t length=0); Int_t AddEllipticCone(Float_t eta, Float_t phi, Float_t reta, Float_t rphi, Float_t length=0); - ClassDef(TEveJetCone, 0); // Short description. + ClassDefOverride(TEveJetCone, 0); // Short description. }; @@ -79,22 +79,22 @@ class TEveJetConeProjected : public TEveShape, TEveJetConeProjected& operator=(const TEveJetConeProjected&); // Not implemented protected: - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveJetConeProjected(const char* n="TEveJetConeProjected", const char* t=""); - virtual ~TEveJetConeProjected(); + ~TEveJetConeProjected() override; // For TAttBBox: - virtual void ComputeBBox(); + void ComputeBBox() override; // Projected: - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); - virtual void UpdateProjection(); + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; + void UpdateProjection() override; - virtual TEveElement* GetProjectedAsElement() { return this; } + TEveElement* GetProjectedAsElement() override { return this; } - ClassDef(TEveJetConeProjected, 0); // Projection of TEveJetCone. + ClassDefOverride(TEveJetConeProjected, 0); // Projection of TEveJetCone. }; #endif diff --git a/graf3d/eve/inc/TEveJetConeEditor.h b/graf3d/eve/inc/TEveJetConeEditor.h index 9d75480fb443d..b47eeabce0212 100644 --- a/graf3d/eve/inc/TEveJetConeEditor.h +++ b/graf3d/eve/inc/TEveJetConeEditor.h @@ -36,14 +36,14 @@ class TEveJetConeEditor : public TGedFrame public: TEveJetConeEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveJetConeEditor() {} + ~TEveJetConeEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods // void DoXYZZ(); - ClassDef(TEveJetConeEditor, 0); // GUI editor for TEveJetCone. + ClassDefOverride(TEveJetConeEditor, 0); // GUI editor for TEveJetCone. }; #endif diff --git a/graf3d/eve/inc/TEveJetConeGL.h b/graf3d/eve/inc/TEveJetConeGL.h index bb2e838e8ffac..1bbd65a5df697 100644 --- a/graf3d/eve/inc/TEveJetConeGL.h +++ b/graf3d/eve/inc/TEveJetConeGL.h @@ -40,16 +40,16 @@ class TEveJetConeGL : public TGLObject public: TEveJetConeGL(); - virtual ~TEveJetConeGL() {} + ~TEveJetConeGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DLCacheClear(); - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DLCacheClear() override; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TEveJetConeGL, 0); // GL renderer class for TEveJetCone. + ClassDefOverride(TEveJetConeGL, 0); // GL renderer class for TEveJetCone. }; @@ -66,22 +66,22 @@ class TEveJetConeProjectedGL : public TEveJetConeGL protected: TEveJetConeProjected *fM; // Model object. - virtual void CalculatePoints() const; + void CalculatePoints() const override; void RenderOutline() const; void RenderPolygon() const; public: TEveJetConeProjectedGL(); - virtual ~TEveJetConeProjectedGL() {} + ~TEveJetConeProjectedGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TEveJetConeProjectedGL, 0); // GL renderer class for TEveJetCone. + ClassDefOverride(TEveJetConeProjectedGL, 0); // GL renderer class for TEveJetCone. }; #endif diff --git a/graf3d/eve/inc/TEveLegoEventHandler.h b/graf3d/eve/inc/TEveLegoEventHandler.h index 2d6faa59e2839..468152cf58be1 100644 --- a/graf3d/eve/inc/TEveLegoEventHandler.h +++ b/graf3d/eve/inc/TEveLegoEventHandler.h @@ -31,15 +31,15 @@ class TEveLegoEventHandler : public TGLEventHandler Float_t fTransTheta; // transition theta in radians Float_t fTheta; - virtual Bool_t Rotate(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2); + Bool_t Rotate(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2) override; public: TEveCaloLego* fLego; TEveLegoEventHandler(TGWindow *w, TObject *obj, TEveCaloLego* lego = nullptr); - virtual ~TEveLegoEventHandler() {} + ~TEveLegoEventHandler() override {} - virtual Bool_t HandleKey(Event_t *event); + Bool_t HandleKey(Event_t *event) override; Float_t GetTransTheta() {return fTransTheta;} void SetTransTheta(Float_t h) {fTransTheta=h;} @@ -47,7 +47,7 @@ class TEveLegoEventHandler : public TGLEventHandler TEveCaloLego* GetLego() { return fLego; } void SetLego( TEveCaloLego* x) { fLego = x; } - ClassDef(TEveLegoEventHandler, 0); // A GL event handler class. Switches perspective or orthographic camera. + ClassDefOverride(TEveLegoEventHandler, 0); // A GL event handler class. Switches perspective or orthographic camera. }; #endif diff --git a/graf3d/eve/inc/TEveLine.h b/graf3d/eve/inc/TEveLine.h index c5bf8c3168626..721684baee9f8 100644 --- a/graf3d/eve/inc/TEveLine.h +++ b/graf3d/eve/inc/TEveLine.h @@ -41,13 +41,13 @@ class TEveLine : public TEvePointSet, public: TEveLine(Int_t n_points=0, ETreeVarType_e tv_type=kTVT_XYZ); TEveLine(const char* name, Int_t n_points=0, ETreeVarType_e tv_type=kTVT_XYZ); - virtual ~TEveLine() {} + ~TEveLine() override {} - virtual void SetMarkerColor(Color_t col); + void SetMarkerColor(Color_t col) override; - virtual void SetLineColor(Color_t col) { SetMainColor(col); } - virtual void SetLineStyle(Style_t lstyle); - virtual void SetLineWidth(Width_t lwidth); + void SetLineColor(Color_t col) override { SetMainColor(col); } + void SetLineStyle(Style_t lstyle) override; + void SetLineWidth(Width_t lwidth) override; Bool_t GetRnrLine() const { return fRnrLine; } Bool_t GetRnrPoints() const { return fRnrPoints; } @@ -62,17 +62,17 @@ class TEveLine : public TEvePointSet, TEveVector GetLineStart() const; TEveVector GetLineEnd() const; - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; static Bool_t GetDefaultSmooth(); static void SetDefaultSmooth(Bool_t r); - ClassDef(TEveLine, 0); // An arbitrary polyline with fixed line and marker attributes. + ClassDefOverride(TEveLine, 0); // An arbitrary polyline with fixed line and marker attributes. }; @@ -88,17 +88,17 @@ class TEveLineProjected : public TEveLine, TEveLineProjected& operator=(const TEveLineProjected&); // Not implemented protected: - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveLineProjected(); - virtual ~TEveLineProjected() {} + ~TEveLineProjected() override {} - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } - ClassDef(TEveLineProjected, 0); // Projected replica of a TEveLine. + ClassDefOverride(TEveLineProjected, 0); // Projected replica of a TEveLine. }; #endif diff --git a/graf3d/eve/inc/TEveLineEditor.h b/graf3d/eve/inc/TEveLineEditor.h index 5ec66a0b38d1a..f3c84309e4ee8 100644 --- a/graf3d/eve/inc/TEveLineEditor.h +++ b/graf3d/eve/inc/TEveLineEditor.h @@ -35,15 +35,15 @@ class TEveLineEditor : public TGedFrame public: TEveLineEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveLineEditor() {} + ~TEveLineEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoRnrLine(); void DoRnrPoints(); void DoSmooth(); - ClassDef(TEveLineEditor, 0); // Editor for TEveLine class. + ClassDefOverride(TEveLineEditor, 0); // Editor for TEveLine class. }; #endif diff --git a/graf3d/eve/inc/TEveLineGL.h b/graf3d/eve/inc/TEveLineGL.h index e7805b621582f..f7272a8058074 100644 --- a/graf3d/eve/inc/TEveLineGL.h +++ b/graf3d/eve/inc/TEveLineGL.h @@ -31,16 +31,16 @@ class TEveLineGL : public TPointSet3DGL public: TEveLineGL(); - virtual ~TEveLineGL() {} + ~TEveLineGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*); - ClassDef(TEveLineGL, 0); // GL-renderer for TEveLine class. + ClassDefOverride(TEveLineGL, 0); // GL-renderer for TEveLine class. }; #endif diff --git a/graf3d/eve/inc/TEveMacro.h b/graf3d/eve/inc/TEveMacro.h index b5cb77899e24d..b486c23d5357c 100644 --- a/graf3d/eve/inc/TEveMacro.h +++ b/graf3d/eve/inc/TEveMacro.h @@ -24,13 +24,13 @@ class TEveMacro : public TMacro TEveMacro(); TEveMacro(const TEveMacro&); TEveMacro(const char* name); - virtual ~TEveMacro() {} + ~TEveMacro() override {} - virtual Longptr_t Exec(const char* params = "0", Int_t* error = nullptr); + Longptr_t Exec(const char* params = "0", Int_t* error = nullptr) override; void ResetRoot(); - ClassDef(TEveMacro, 1); // TMacro wrapper (attempting to fix issues with different macro loading and execution schemes). + ClassDefOverride(TEveMacro, 1); // TMacro wrapper (attempting to fix issues with different macro loading and execution schemes). }; #endif diff --git a/graf3d/eve/inc/TEveManager.h b/graf3d/eve/inc/TEveManager.h index 990a25c94352a..5fe32531f435b 100644 --- a/graf3d/eve/inc/TEveManager.h +++ b/graf3d/eve/inc/TEveManager.h @@ -72,11 +72,11 @@ class TEveManager { public: TExceptionHandler() : TStdExceptionHandler() { Add(); } - virtual ~TExceptionHandler() { Remove(); } + ~TExceptionHandler() override { Remove(); } - virtual EStatus Handle(std::exception& exc); + EStatus Handle(std::exception& exc) override; - ClassDef(TExceptionHandler, 0); // Exception handler for Eve exceptions. + ClassDefOverride(TExceptionHandler, 0); // Exception handler for Eve exceptions. }; protected: diff --git a/graf3d/eve/inc/TEvePad.h b/graf3d/eve/inc/TEvePad.h index dbab54083bccc..b6cc407bc0eb0 100644 --- a/graf3d/eve/inc/TEvePad.h +++ b/graf3d/eve/inc/TEvePad.h @@ -21,16 +21,16 @@ class TEvePad : public TPad TEvePad(const char* name, const char* title, Double_t xlow, Double_t ylow, Double_t xup, Double_t yup, Color_t color = -1, Short_t bordersize = -1, Short_t bordermode = -2); - virtual ~TEvePad() {} + ~TEvePad() override {} - virtual Bool_t IsBatch() const { return kTRUE; } + Bool_t IsBatch() const override { return kTRUE; } - virtual void Update() { PaintModified(); } + void Update() override { PaintModified(); } - virtual TVirtualViewer3D *GetViewer3D(Option_t * /*type*/ = "") + TVirtualViewer3D *GetViewer3D(Option_t * /*type*/ = "") override { return fViewer3D; } - ClassDef(TEvePad, 1); // Internal TEveUtil pad class (sub-class of TPad) overriding handling of updates and 3D-viewers. + ClassDefOverride(TEvePad, 1); // Internal TEveUtil pad class (sub-class of TPad) overriding handling of updates and 3D-viewers. }; #endif diff --git a/graf3d/eve/inc/TEveParamList.h b/graf3d/eve/inc/TEveParamList.h index 4446ec7dd1432..c4de6fb194c73 100644 --- a/graf3d/eve/inc/TEveParamList.h +++ b/graf3d/eve/inc/TEveParamList.h @@ -80,7 +80,7 @@ class TEveParamList : public TEveElement, public: TEveParamList(const char* n="TEveParamList", const char* t="", Bool_t doColor=kFALSE); - virtual ~TEveParamList() {} + ~TEveParamList() override {} void AddParameter(const FloatConfig_t& parameter) { fFloatParameters.push_back(parameter); } void AddParameter(const IntConfig_t& parameter) { fIntParameters.push_back(parameter); } @@ -96,7 +96,7 @@ class TEveParamList : public TEveElement, void ParamChanged(const char* name); // *SIGNAL* - ClassDef(TEveParamList, 0); // Eve element to store generic configuration information. + ClassDefOverride(TEveParamList, 0); // Eve element to store generic configuration information. }; @@ -137,15 +137,15 @@ class TEveParamListEditor : public TGedFrame public: TEveParamListEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveParamListEditor() {} + ~TEveParamListEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods void DoIntUpdate(); void DoFloatUpdate(); void DoBoolUpdate(); - ClassDef(TEveParamListEditor, 0); // GUI editor for TEveParamList. + ClassDefOverride(TEveParamListEditor, 0); // GUI editor for TEveParamList. }; #endif diff --git a/graf3d/eve/inc/TEvePlot3D.h b/graf3d/eve/inc/TEvePlot3D.h index 9c87c22642a2e..5aac9d8eb254c 100644 --- a/graf3d/eve/inc/TEvePlot3D.h +++ b/graf3d/eve/inc/TEvePlot3D.h @@ -33,7 +33,7 @@ class TEvePlot3D : public TEveElementList public: TEvePlot3D(const char* n="TEvePlot3D", const char* t=""); - virtual ~TEvePlot3D() {} + ~TEvePlot3D() override {} void SetPlot(TObject* obj, const TString& opt) { fPlot = obj; fPlotOption = opt; } @@ -50,9 +50,9 @@ class TEvePlot3D : public TEveElementList Bool_t GetLogY() const { return fLogY; } Bool_t GetLogZ() const { return fLogZ; } - virtual void Paint(Option_t* option=""); + void Paint(Option_t* option="") override; - ClassDef(TEvePlot3D, 0); // Short description. + ClassDefOverride(TEvePlot3D, 0); // Short description. }; #endif diff --git a/graf3d/eve/inc/TEvePlot3DGL.h b/graf3d/eve/inc/TEvePlot3DGL.h index 352806c66e5f3..5e39217b550aa 100644 --- a/graf3d/eve/inc/TEvePlot3DGL.h +++ b/graf3d/eve/inc/TEvePlot3DGL.h @@ -32,20 +32,20 @@ class TEvePlot3DGL : public TGLObject public: TEvePlot3DGL(); - virtual ~TEvePlot3DGL() {} + ~TEvePlot3DGL() override {} - virtual Bool_t KeepDuringSmartRefresh() const { return kFALSE; } + Bool_t KeepDuringSmartRefresh() const override { return kFALSE; } - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); - ClassDef(TEvePlot3DGL, 0); // GL renderer class for TEvePlot3D. + ClassDefOverride(TEvePlot3DGL, 0); // GL renderer class for TEvePlot3D. }; #endif diff --git a/graf3d/eve/inc/TEvePointSet.h b/graf3d/eve/inc/TEvePointSet.h index 9067f5c89af7f..7cb920e43f546 100644 --- a/graf3d/eve/inc/TEvePointSet.h +++ b/graf3d/eve/inc/TEvePointSet.h @@ -50,25 +50,25 @@ class TEvePointSet : public TEveElement, TEvePointSet(Int_t n_points=0, ETreeVarType_e tv_type=kTVT_XYZ); TEvePointSet(const char* name, Int_t n_points=0, ETreeVarType_e tv_type=kTVT_XYZ); TEvePointSet(const TEvePointSet& e); - virtual ~TEvePointSet(); + ~TEvePointSet() override; - virtual TObject* GetObject(const TEveException&) const + TObject* GetObject(const TEveException&) const override { const TObject* obj = this; return const_cast(obj); } - virtual TEvePointSet* CloneElement() const { return new TEvePointSet(*this); } + TEvePointSet* CloneElement() const override { return new TEvePointSet(*this); } virtual void ClonePoints(const TEvePointSet& e); void Reset(Int_t n_points=0, Int_t n_int_ids=0); Int_t GrowFor(Int_t n_points); - virtual const char* GetTitle() const { return fTitle; } - virtual const char* GetElementName() const { return TPointSet3D::GetName(); } - virtual const char* GetElementTitle() const { return fTitle; } - virtual void SetElementName (const char* n) { fName = n; NameTitleChanged(); } + const char* GetTitle() const override { return fTitle; } + const char* GetElementName() const override { return TPointSet3D::GetName(); } + const char* GetElementTitle() const override { return fTitle; } + void SetElementName (const char* n) override { fName = n; NameTitleChanged(); } virtual void SetTitle(const char* t) { fTitle = t; NameTitleChanged(); } - virtual void SetElementTitle(const char* t) { fTitle = t; NameTitleChanged(); } - virtual void SetElementNameTitle(const char* n, const char* t) + void SetElementTitle(const char* t) override { fTitle = t; NameTitleChanged(); } + void SetElementNameTitle(const char* n, const char* t) override { fName = n; fTitle = t; NameTitleChanged(); } Int_t GetIntIdsPerPoint() const { return fIntIdsPerPoint; } @@ -78,25 +78,25 @@ class TEvePointSet : public TEveElement, void SetPointIntIds(Int_t* ids); void SetPointIntIds(Int_t n, Int_t* ids); - virtual void SetMarkerColor(Color_t col) { SetMainColor(col); } - virtual void SetMarkerStyle(Style_t mstyle=1); - virtual void SetMarkerSize(Size_t msize=1); + void SetMarkerColor(Color_t col) override { SetMainColor(col); } + void SetMarkerStyle(Style_t mstyle=1) override; + void SetMarkerSize(Size_t msize=1) override; - virtual void Paint(Option_t* option=""); + void Paint(Option_t* option="") override; - virtual void InitFill(Int_t subIdNum); - virtual void TakeAction(TEvePointSelector*); + void InitFill(Int_t subIdNum) override; + void TakeAction(TEvePointSelector*) override; - virtual void PointSelected(Int_t id); // *SIGNAL* + void PointSelected(Int_t id) override; // *SIGNAL* - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEvePointSet, 0); // Set of 3D points with same marker attributes; optionally each point can be assigned an external TRef or a number of integer indices. + ClassDefOverride(TEvePointSet, 0); // Set of 3D points with same marker attributes; optionally each point can be assigned an external TRef or a number of integer indices. }; @@ -126,16 +126,16 @@ class TEvePointSetArray : public TEveElement, public: TEvePointSetArray(const char* name="TEvePointSetArray", const char* title=""); - virtual ~TEvePointSetArray(); + ~TEvePointSetArray() override; - virtual void RemoveElementLocal(TEveElement* el); - virtual void RemoveElementsLocal(); + void RemoveElementLocal(TEveElement* el) override; + void RemoveElementsLocal() override; - virtual void SetMarkerColor(Color_t tcolor=1); - virtual void SetMarkerStyle(Style_t mstyle=1); - virtual void SetMarkerSize(Size_t msize=1); + void SetMarkerColor(Color_t tcolor=1) override; + void SetMarkerStyle(Style_t mstyle=1) override; + void SetMarkerSize(Size_t msize=1) override; - virtual void TakeAction(TEvePointSelector*); + void TakeAction(TEvePointSelector*) override; virtual Int_t Size(Bool_t under=kFALSE, Bool_t over=kFALSE) const; @@ -159,7 +159,7 @@ class TEvePointSetArray : public TEveElement, void SetRange(Double_t min, Double_t max); - ClassDef(TEvePointSetArray, 0); // Array of TEvePointSet's filled via a common point-source; range of displayed TEvePointSet's can be controlled, based on a separating quantity provided on fill-time by a user. + ClassDefOverride(TEvePointSetArray, 0); // Array of TEvePointSet's filled via a common point-source; range of displayed TEvePointSet's can be controlled, based on a separating quantity provided on fill-time by a user. }; @@ -175,20 +175,20 @@ class TEvePointSetProjected : public TEvePointSet, TEvePointSetProjected& operator=(const TEvePointSetProjected&); // Not implemented protected: - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEvePointSetProjected(); - virtual ~TEvePointSetProjected() {} + ~TEvePointSetProjected() override {} - virtual void SetProjection(TEveProjectionManager* proj, TEveProjectable* model); - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* proj, TEveProjectable* model) override; + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } - virtual void PointSelected(Int_t id); + void PointSelected(Int_t id) override; - ClassDef(TEvePointSetProjected, 0); // Projected copy of a TEvePointSet. + ClassDefOverride(TEvePointSetProjected, 0); // Projected copy of a TEvePointSet. }; #endif diff --git a/graf3d/eve/inc/TEvePointSetArrayEditor.h b/graf3d/eve/inc/TEvePointSetArrayEditor.h index 0d7e1447d3f29..c408ef3aced9d 100644 --- a/graf3d/eve/inc/TEvePointSetArrayEditor.h +++ b/graf3d/eve/inc/TEvePointSetArrayEditor.h @@ -36,13 +36,13 @@ class TEvePointSetArrayEditor : public TGedFrame public: TEvePointSetArrayEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - ~TEvePointSetArrayEditor(); + ~TEvePointSetArrayEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoRange(); - ClassDef(TEvePointSetArrayEditor, 0); // Editor for TEvePointSetArray class. + ClassDefOverride(TEvePointSetArrayEditor, 0); // Editor for TEvePointSetArray class. }; #endif diff --git a/graf3d/eve/inc/TEvePolygonSetProjected.h b/graf3d/eve/inc/TEvePolygonSetProjected.h index 6430801122cfb..6ead476405a32 100644 --- a/graf3d/eve/inc/TEvePolygonSetProjected.h +++ b/graf3d/eve/inc/TEvePolygonSetProjected.h @@ -71,26 +71,26 @@ class TEvePolygonSetProjected : public TEveShape, Int_t fNPnts; // number of reduced and projected points TEveVector* fPnts; // reduced and projected points - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; Float_t PolygonSurfaceXY(const Polygon_t& poly) const; public: TEvePolygonSetProjected(const char* n="TEvePolygonSetProjected", const char* t=""); - virtual ~TEvePolygonSetProjected(); + ~TEvePolygonSetProjected() override; - virtual void ComputeBBox(); + void ComputeBBox() override; - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } void ProjectBuffer3D(); virtual void DumpPolys() const; void DumpBuffer3D(); - ClassDef(TEvePolygonSetProjected,0); // Set of projected polygons with outline; typically produced from a TBuffer3D. + ClassDefOverride(TEvePolygonSetProjected,0); // Set of projected polygons with outline; typically produced from a TBuffer3D. }; diff --git a/graf3d/eve/inc/TEvePolygonSetProjectedGL.h b/graf3d/eve/inc/TEvePolygonSetProjectedGL.h index f6e2ceed14e46..922070aa16a3b 100644 --- a/graf3d/eve/inc/TEvePolygonSetProjectedGL.h +++ b/graf3d/eve/inc/TEvePolygonSetProjectedGL.h @@ -41,21 +41,21 @@ class TEvePolygonSetProjectedGL : public TGLObject public: TEvePolygonSetProjectedGL(); - virtual ~TEvePolygonSetProjectedGL() {} + ~TEvePolygonSetProjectedGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; - virtual void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* pshp, Int_t lvl=-1) const; + void DrawHighlight(TGLRnrCtx& rnrCtx, const TGLPhysicalShape* pshp, Int_t lvl=-1) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } private: void DrawOutline() const; - ClassDef(TEvePolygonSetProjectedGL,0); // GL-renderer for TEvePolygonSetProjected class. + ClassDefOverride(TEvePolygonSetProjectedGL,0); // GL-renderer for TEvePolygonSetProjected class. }; #endif diff --git a/graf3d/eve/inc/TEveProjectionAxes.h b/graf3d/eve/inc/TEveProjectionAxes.h index 8be128247e57f..b78095071f572 100644 --- a/graf3d/eve/inc/TEveProjectionAxes.h +++ b/graf3d/eve/inc/TEveProjectionAxes.h @@ -51,7 +51,7 @@ class TEveProjectionAxes : public TEveElement, public: TEveProjectionAxes(TEveProjectionManager* m, Bool_t useColorSet = kTRUE); - virtual ~TEveProjectionAxes(); + ~TEveProjectionAxes() override; TEveProjectionManager* GetManager() { return fManager; } @@ -65,12 +65,12 @@ class TEveProjectionAxes : public TEveElement, void SetDrawOrigin(Bool_t x) { fDrawOrigin = x; } Bool_t GetDrawOrigin() const { return fDrawOrigin; } - virtual void Paint(Option_t* option=""); - virtual void ComputeBBox(); + void Paint(Option_t* option="") override; + void ComputeBBox() override; - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - ClassDef(TEveProjectionAxes, 0); // Class to draw scales in non-linear projections. + ClassDefOverride(TEveProjectionAxes, 0); // Class to draw scales in non-linear projections. }; #endif diff --git a/graf3d/eve/inc/TEveProjectionAxesEditor.h b/graf3d/eve/inc/TEveProjectionAxesEditor.h index 49b8be863e680..b71f945ccbc7f 100644 --- a/graf3d/eve/inc/TEveProjectionAxesEditor.h +++ b/graf3d/eve/inc/TEveProjectionAxesEditor.h @@ -39,9 +39,9 @@ class TEveProjectionAxesEditor : public TGedFrame public: TEveProjectionAxesEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveProjectionAxesEditor() {} + ~TEveProjectionAxesEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods @@ -51,7 +51,7 @@ class TEveProjectionAxesEditor : public TGedFrame void DoDrawCenter(); void DoDrawOrigin(); - ClassDef(TEveProjectionAxesEditor, 0); // GUI editor for TEveProjectionAxes. + ClassDefOverride(TEveProjectionAxesEditor, 0); // GUI editor for TEveProjectionAxes. }; #endif diff --git a/graf3d/eve/inc/TEveProjectionAxesGL.h b/graf3d/eve/inc/TEveProjectionAxesGL.h index a411096b7ffe0..79834131988e9 100644 --- a/graf3d/eve/inc/TEveProjectionAxesGL.h +++ b/graf3d/eve/inc/TEveProjectionAxesGL.h @@ -36,16 +36,16 @@ class TEveProjectionAxesGL : public TGLObject public: TEveProjectionAxesGL(); - virtual ~TEveProjectionAxesGL() {} + ~TEveProjectionAxesGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t* opt = nullptr); - virtual void SetBBox(); - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t* opt = nullptr) override; + void SetBBox() override; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } - ClassDef(TEveProjectionAxesGL, 0); // GL renderer class for TEveProjectionAxes. + ClassDefOverride(TEveProjectionAxesGL, 0); // GL renderer class for TEveProjectionAxes. }; #endif diff --git a/graf3d/eve/inc/TEveProjectionManager.h b/graf3d/eve/inc/TEveProjectionManager.h index 57ecdbe0b8068..87f3d4716d543 100644 --- a/graf3d/eve/inc/TEveProjectionManager.h +++ b/graf3d/eve/inc/TEveProjectionManager.h @@ -40,7 +40,7 @@ class TEveProjectionManager : public TEveElementList, public: TEveProjectionManager(TEveProjection::EPType_e type=TEveProjection::kPT_Unknown); - virtual ~TEveProjectionManager(); + ~TEveProjectionManager() override; void AddDependent(TEveElement* el); void RemoveDependent(TEveElement* el); @@ -59,7 +59,7 @@ class TEveProjectionManager : public TEveElementList, void SetImportEmpty(Bool_t ie) { fImportEmpty = ie; } Bool_t GetImportEmpty() const { return fImportEmpty; } - virtual Bool_t HandleElementPaste(TEveElement* el); + Bool_t HandleElementPaste(TEveElement* el) override; virtual TEveElement* ImportElementsRecurse(TEveElement* el, TEveElement* parent); @@ -72,9 +72,9 @@ class TEveProjectionManager : public TEveElementList, virtual void ProjectChildren(); virtual void ProjectChildrenRecurse(TEveElement* el); - virtual void ComputeBBox(); + void ComputeBBox() override; - ClassDef(TEveProjectionManager, 0); // Manager class for steering of projections and managing projected objects. + ClassDefOverride(TEveProjectionManager, 0); // Manager class for steering of projections and managing projected objects. }; #endif diff --git a/graf3d/eve/inc/TEveProjectionManagerEditor.h b/graf3d/eve/inc/TEveProjectionManagerEditor.h index 84e1209ec4150..34e52e1e686ef 100644 --- a/graf3d/eve/inc/TEveProjectionManagerEditor.h +++ b/graf3d/eve/inc/TEveProjectionManagerEditor.h @@ -47,9 +47,9 @@ class TEveProjectionManagerEditor : public TGedFrame public: TEveProjectionManagerEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveProjectionManagerEditor(){} + ~TEveProjectionManagerEditor() override{} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods @@ -63,7 +63,7 @@ class TEveProjectionManagerEditor : public TGedFrame void DoMaxTrackStep(); void DoCenter(); - ClassDef(TEveProjectionManagerEditor, 0); // Editor for TEveProjectionManager class. + ClassDefOverride(TEveProjectionManagerEditor, 0); // Editor for TEveProjectionManager class. }; #endif diff --git a/graf3d/eve/inc/TEveProjections.h b/graf3d/eve/inc/TEveProjections.h index 1276828c4a2cc..89ed0be46b242 100644 --- a/graf3d/eve/inc/TEveProjections.h +++ b/graf3d/eve/inc/TEveProjections.h @@ -164,23 +164,23 @@ class TEveRhoZProjection: public TEveProjection public: TEveRhoZProjection(); - virtual ~TEveRhoZProjection() {} + ~TEveRhoZProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - virtual void SetCenter(TEveVector& v); - virtual Float_t* GetProjectedCenter() { return fProjectedCenter.Arr(); } + void SetCenter(TEveVector& v) override; + Float_t* GetProjectedCenter() override { return fProjectedCenter.Arr(); } - virtual Bool_t HasSeveralSubSpaces() const { return kTRUE; } - virtual Bool_t AcceptSegment(TEveVector& v1, TEveVector& v2, Float_t tolerance) const; - virtual Int_t SubSpaceId(const TEveVector& v) const; - virtual Bool_t IsOnSubSpaceBoundrary(const TEveVector& v) const; - virtual void SetDirectionalVector(Int_t screenAxis, TEveVector& vec); + Bool_t HasSeveralSubSpaces() const override { return kTRUE; } + Bool_t AcceptSegment(TEveVector& v1, TEveVector& v2, Float_t tolerance) const override; + Int_t SubSpaceId(const TEveVector& v) const override; + Bool_t IsOnSubSpaceBoundrary(const TEveVector& v) const override; + void SetDirectionalVector(Int_t screenAxis, TEveVector& vec) override; - ClassDef(TEveRhoZProjection, 0); // Rho/Z non-linear projection. + ClassDefOverride(TEveRhoZProjection, 0); // Rho/Z non-linear projection. }; @@ -192,14 +192,14 @@ class TEveRPhiProjection : public TEveProjection { public: TEveRPhiProjection(); - virtual ~TEveRPhiProjection() {} + ~TEveRPhiProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - ClassDef(TEveRPhiProjection, 0); // XY non-linear projection. + ClassDefOverride(TEveRPhiProjection, 0); // XY non-linear projection. }; @@ -214,19 +214,19 @@ class TEveXZProjection : public TEveProjection public: TEveXZProjection(); - virtual ~TEveXZProjection() {} + ~TEveXZProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - virtual void SetCenter(TEveVector& v); - virtual Float_t* GetProjectedCenter() { return fProjectedCenter.Arr(); } + void SetCenter(TEveVector& v) override; + Float_t* GetProjectedCenter() override { return fProjectedCenter.Arr(); } - virtual void SetDirectionalVector(Int_t screenAxis, TEveVector& vec); + void SetDirectionalVector(Int_t screenAxis, TEveVector& vec) override; - ClassDef(TEveXZProjection, 0); // XZ non-linear projection. + ClassDefOverride(TEveXZProjection, 0); // XZ non-linear projection. }; @@ -241,19 +241,19 @@ class TEveYZProjection : public TEveProjection public: TEveYZProjection(); - virtual ~TEveYZProjection() {} + ~TEveYZProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - virtual void SetCenter(TEveVector& v); - virtual Float_t* GetProjectedCenter() { return fProjectedCenter.Arr(); } + void SetCenter(TEveVector& v) override; + Float_t* GetProjectedCenter() override { return fProjectedCenter.Arr(); } - virtual void SetDirectionalVector(Int_t screenAxis, TEveVector& vec); + void SetDirectionalVector(Int_t screenAxis, TEveVector& vec) override; - ClassDef(TEveYZProjection, 0); // XY non-linear projection. + ClassDefOverride(TEveYZProjection, 0); // XY non-linear projection. }; @@ -268,19 +268,19 @@ class TEveZXProjection : public TEveProjection public: TEveZXProjection(); - virtual ~TEveZXProjection() {} + ~TEveZXProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - virtual void SetCenter(TEveVector& v); - virtual Float_t* GetProjectedCenter() { return fProjectedCenter.Arr(); } + void SetCenter(TEveVector& v) override; + Float_t* GetProjectedCenter() override { return fProjectedCenter.Arr(); } - virtual void SetDirectionalVector(Int_t screenAxis, TEveVector& vec); + void SetDirectionalVector(Int_t screenAxis, TEveVector& vec) override; - ClassDef(TEveZXProjection, 0); // XZ non-linear projection. + ClassDefOverride(TEveZXProjection, 0); // XZ non-linear projection. }; @@ -295,19 +295,19 @@ class TEveZYProjection : public TEveProjection public: TEveZYProjection(); - virtual ~TEveZYProjection() {} + ~TEveZYProjection() override {} - virtual Bool_t Is2D() const { return kTRUE; } - virtual Bool_t Is3D() const { return kFALSE; } + Bool_t Is2D() const override { return kTRUE; } + Bool_t Is3D() const override { return kFALSE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - virtual void SetCenter(TEveVector& v); - virtual Float_t* GetProjectedCenter() { return fProjectedCenter.Arr(); } + void SetCenter(TEveVector& v) override; + Float_t* GetProjectedCenter() override { return fProjectedCenter.Arr(); } - virtual void SetDirectionalVector(Int_t screenAxis, TEveVector& vec); + void SetDirectionalVector(Int_t screenAxis, TEveVector& vec) override; - ClassDef(TEveZYProjection, 0); // XY non-linear projection. + ClassDefOverride(TEveZYProjection, 0); // XY non-linear projection. }; @@ -319,14 +319,14 @@ class TEve3DProjection : public TEveProjection { public: TEve3DProjection(); - virtual ~TEve3DProjection() {} + ~TEve3DProjection() override {} - virtual Bool_t Is2D() const { return kFALSE; } - virtual Bool_t Is3D() const { return kTRUE; } + Bool_t Is2D() const override { return kFALSE; } + Bool_t Is3D() const override { return kTRUE; } - virtual void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full); + void ProjectPoint(Float_t& x, Float_t& y, Float_t& z, Float_t d, EPProc_e proc = kPP_Full) override; - ClassDef(TEve3DProjection, 0); // 3D scaling "projection" + ClassDefOverride(TEve3DProjection, 0); // 3D scaling "projection" }; // AMT: temporary workaround till root pactches are integrated in CMSSW diff --git a/graf3d/eve/inc/TEveQuadSet.h b/graf3d/eve/inc/TEveQuadSet.h index bd3a58d9fc13d..4b411f980526c 100644 --- a/graf3d/eve/inc/TEveQuadSet.h +++ b/graf3d/eve/inc/TEveQuadSet.h @@ -81,7 +81,7 @@ class TEveQuadSet : public TEveDigitSet TEveQuadSet(const char* n="TEveQuadSet", const char* t=""); TEveQuadSet(EQuadType_e quadType, Bool_t valIsCol, Int_t chunkSize, const char* n="TEveQuadSet", const char* t=""); - virtual ~TEveQuadSet() {} + ~TEveQuadSet() override {} void Reset(EQuadType_e quadType, Bool_t valIsCol, Int_t chunkSize); @@ -116,11 +116,11 @@ class TEveQuadSet : public TEveDigitSet // void Test(Int_t nquads); - virtual void ComputeBBox(); + void ComputeBBox() override; // virtual void Paint(Option_t* option=""); - ClassDef(TEveQuadSet, 0); // Collection of 2D primitives (rectangles, hexagons, or lines); each primitive can be assigned a signal value and a TRef. + ClassDefOverride(TEveQuadSet, 0); // Collection of 2D primitives (rectangles, hexagons, or lines); each primitive can be assigned a signal value and a TRef. }; #endif diff --git a/graf3d/eve/inc/TEveQuadSetGL.h b/graf3d/eve/inc/TEveQuadSetGL.h index 2ee4360a12567..90f709d57a428 100644 --- a/graf3d/eve/inc/TEveQuadSetGL.h +++ b/graf3d/eve/inc/TEveQuadSetGL.h @@ -29,14 +29,14 @@ class TEveQuadSetGL : public TEveDigitSetGL public: TEveQuadSetGL(); - virtual ~TEveQuadSetGL() {} + ~TEveQuadSetGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } - ClassDef(TEveQuadSetGL, 0); // GL-renderer for TEveQuadSet class. + ClassDefOverride(TEveQuadSetGL, 0); // GL-renderer for TEveQuadSet class. }; #endif diff --git a/graf3d/eve/inc/TEveRGBAPalette.h b/graf3d/eve/inc/TEveRGBAPalette.h index e9a77af50e107..c7897eca57286 100644 --- a/graf3d/eve/inc/TEveRGBAPalette.h +++ b/graf3d/eve/inc/TEveRGBAPalette.h @@ -77,7 +77,7 @@ class TEveRGBAPalette : public TObject, TEveRGBAPalette(); TEveRGBAPalette(Int_t min, Int_t max, Bool_t interp=kTRUE, Bool_t showdef=kTRUE, Bool_t fixcolrng=kFALSE); - virtual ~TEveRGBAPalette(); + ~TEveRGBAPalette() override; void SetupColorArray() const; void ClearColorArray(); @@ -151,13 +151,13 @@ class TEveRGBAPalette : public TObject, void SetOverColorPixel(Pixel_t pix); void SetOverColorRGBA(UChar_t r, UChar_t g, UChar_t b, UChar_t a=255); - virtual void OnZeroRefCount() { delete this; } + void OnZeroRefCount() override { delete this; } // ================================================================ void MinMaxValChanged(); // *SIGNAL* - ClassDef(TEveRGBAPalette, 0); // A generic, speed-optimised mapping from value to RGBA color supporting different wrapping and range truncation modes. + ClassDefOverride(TEveRGBAPalette, 0); // A generic, speed-optimised mapping from value to RGBA color supporting different wrapping and range truncation modes. }; diff --git a/graf3d/eve/inc/TEveRGBAPaletteEditor.h b/graf3d/eve/inc/TEveRGBAPaletteEditor.h index 536f7c5cf7e58..18777c1e8df95 100644 --- a/graf3d/eve/inc/TEveRGBAPaletteEditor.h +++ b/graf3d/eve/inc/TEveRGBAPaletteEditor.h @@ -47,7 +47,7 @@ class TEveRGBAPaletteSubEditor : public TGVerticalFrame public: TEveRGBAPaletteSubEditor(const TGWindow* p); - virtual ~TEveRGBAPaletteSubEditor() {} + ~TEveRGBAPaletteSubEditor() override {} void SetModel(TEveRGBAPalette* p); @@ -64,7 +64,7 @@ class TEveRGBAPaletteSubEditor : public TGVerticalFrame void DoUnderflowAction(Int_t mode); void DoOverflowAction(Int_t mode); - ClassDef(TEveRGBAPaletteSubEditor, 0); // Sub-editor for TEveRGBAPalette class. + ClassDefOverride(TEveRGBAPaletteSubEditor, 0); // Sub-editor for TEveRGBAPalette class. }; @@ -83,11 +83,11 @@ class TEveRGBAPaletteEditor : public TGedFrame public: TEveRGBAPaletteEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveRGBAPaletteEditor() {} + ~TEveRGBAPaletteEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; - ClassDef(TEveRGBAPaletteEditor, 0); // Editor for TEveRGBAPalette class. + ClassDefOverride(TEveRGBAPaletteEditor, 0); // Editor for TEveRGBAPalette class. }; #endif diff --git a/graf3d/eve/inc/TEveRGBAPaletteOverlay.h b/graf3d/eve/inc/TEveRGBAPaletteOverlay.h index 92d14987fdcf6..84339678414fd 100644 --- a/graf3d/eve/inc/TEveRGBAPaletteOverlay.h +++ b/graf3d/eve/inc/TEveRGBAPaletteOverlay.h @@ -37,9 +37,9 @@ class TEveRGBAPaletteOverlay : public TGLOverlayElement public: TEveRGBAPaletteOverlay(TEveRGBAPalette* p, Float_t posx, Float_t posy, Float_t width, Float_t height); - virtual ~TEveRGBAPaletteOverlay() {} + ~TEveRGBAPaletteOverlay() override {} - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; TAxis& RefAxis() { return fAxis; } TGLAxisPainter& RefAxisPainter() { return fAxisPainter; } @@ -48,7 +48,7 @@ class TEveRGBAPaletteOverlay : public TGLOverlayElement void SetPosition(Float_t x, Float_t y) { fPosX = x; fPosY = y; } void SetSize(Float_t w, Float_t h) { fWidth = w; fHeight = h; } - ClassDef(TEveRGBAPaletteOverlay, 0); // Draws TEveRGBAPalette as GL overlay. + ClassDefOverride(TEveRGBAPaletteOverlay, 0); // Draws TEveRGBAPalette as GL overlay. }; #endif diff --git a/graf3d/eve/inc/TEveScalableStraightLineSet.h b/graf3d/eve/inc/TEveScalableStraightLineSet.h index b665273246c2c..32b0abb6baf25 100644 --- a/graf3d/eve/inc/TEveScalableStraightLineSet.h +++ b/graf3d/eve/inc/TEveScalableStraightLineSet.h @@ -26,13 +26,13 @@ class TEveScalableStraightLineSet : public TEveStraightLineSet public: TEveScalableStraightLineSet(const char* n="ScalableStraightLineSet", const char* t=""); - virtual ~TEveScalableStraightLineSet() {} + ~TEveScalableStraightLineSet() override {} void SetScaleCenter(Float_t x, Float_t y, Float_t z); void SetScale(Double_t scale); Double_t GetScale() const; - ClassDef(TEveScalableStraightLineSet, 0); // Straight-line-set with extra scaling. + ClassDefOverride(TEveScalableStraightLineSet, 0); // Straight-line-set with extra scaling. }; #endif diff --git a/graf3d/eve/inc/TEveScene.h b/graf3d/eve/inc/TEveScene.h index 50bf875f6912a..d0e05258c9c39 100644 --- a/graf3d/eve/inc/TEveScene.h +++ b/graf3d/eve/inc/TEveScene.h @@ -42,11 +42,11 @@ class TEveScene : public TEveElementList public: TEveScene(const char* n="TEveScene", const char* t=""); TEveScene(TGLScenePad* gl_scene, const char* n="TEveScene", const char* t=""); - virtual ~TEveScene(); + ~TEveScene() override; - virtual void CollectSceneParents(List_t& scenes); + void CollectSceneParents(List_t& scenes) override; - virtual Bool_t SingleRnrState() const { return kTRUE; } + Bool_t SingleRnrState() const override { return kTRUE; } void Changed() { fChanged = kTRUE; } Bool_t IsChanged() const { return fChanged; } @@ -60,15 +60,15 @@ class TEveScene : public TEveElementList TGLScenePad* GetGLScene() const { return fGLScene; } void SetGLScene(TGLScenePad* s) { fGLScene = s; } - virtual void SetName(const char* n); - virtual void Paint(Option_t* option = ""); + void SetName(const char* n) override; + void Paint(Option_t* option = "") override; void DestroyElementRenderers(TEveElement* element); void DestroyElementRenderers(TObject* rnrObj); - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - ClassDef(TEveScene, 0); // Reve representation of TGLScene. + ClassDefOverride(TEveScene, 0); // Reve representation of TGLScene. }; @@ -86,7 +86,7 @@ class TEveSceneList : public TEveElementList public: TEveSceneList(const char* n="TEveSceneList", const char* t=""); - virtual ~TEveSceneList() {} + ~TEveSceneList() override {} void DestroyScenes(); @@ -97,7 +97,7 @@ class TEveSceneList : public TEveElementList void ProcessSceneChanges(Bool_t dropLogicals, TExMap* stampMap); - ClassDef(TEveSceneList, 0); // List of Scenes providing common operations on TEveScene collections. + ClassDefOverride(TEveSceneList, 0); // List of Scenes providing common operations on TEveScene collections. }; #endif diff --git a/graf3d/eve/inc/TEveSceneInfo.h b/graf3d/eve/inc/TEveSceneInfo.h index 62d029bc3aede..cf796c982c4e0 100644 --- a/graf3d/eve/inc/TEveSceneInfo.h +++ b/graf3d/eve/inc/TEveSceneInfo.h @@ -34,21 +34,21 @@ class TEveSceneInfo : public TEveElement, public: TEveSceneInfo(TEveViewer* viewer, TEveScene* scene, TGLSceneInfo* sinfo); - virtual ~TEveSceneInfo() {} + ~TEveSceneInfo() override {} TEveViewer * GetViewer() const { return fViewer; } TEveScene * GetScene() const { return fScene; } TGLSceneInfo * GetGLSceneInfo() const { return fGLSceneInfo; } TGLSceneBase * GetGLScene() const; - virtual Bool_t SingleRnrState() const { return kTRUE; } + Bool_t SingleRnrState() const override { return kTRUE; } - virtual void AddStamp(UChar_t bits); + void AddStamp(UChar_t bits) override; - virtual Bool_t AcceptElement(TEveElement* el); - virtual Bool_t HandleElementPaste(TEveElement* el); + Bool_t AcceptElement(TEveElement* el) override; + Bool_t HandleElementPaste(TEveElement* el) override; - ClassDef(TEveSceneInfo, 0); // TEveUtil representation of TGLSceneInfo. + ClassDefOverride(TEveSceneInfo, 0); // TEveUtil representation of TGLSceneInfo. }; #endif diff --git a/graf3d/eve/inc/TEveSelection.h b/graf3d/eve/inc/TEveSelection.h index f19745720ea97..9b66cd81819fc 100644 --- a/graf3d/eve/inc/TEveSelection.h +++ b/graf3d/eve/inc/TEveSelection.h @@ -57,7 +57,7 @@ class TEveSelection : public TEveElementList, public: TEveSelection(const char* n="TEveSelection", const char* t=""); - virtual ~TEveSelection() {} + ~TEveSelection() override {} void SetHighlightMode(); @@ -67,13 +67,13 @@ class TEveSelection : public TEveElementList, Bool_t GetIsMaster() const { return fIsMaster; } void SetIsMaster(Bool_t m) { fIsMaster = m; } - virtual Bool_t AcceptElement(TEveElement* el); + Bool_t AcceptElement(TEveElement* el) override; - virtual void AddElement(TEveElement* el); - virtual void RemoveElement(TEveElement* el); - virtual void RemoveElementLocal(TEveElement* el); - virtual void RemoveElements(); - virtual void RemoveElementsLocal(); + void AddElement(TEveElement* el) override; + void RemoveElement(TEveElement* el) override; + void RemoveElementLocal(TEveElement* el) override; + void RemoveElements() override; + void RemoveElementsLocal() override; virtual void RemoveImpliedSelected(TEveElement* el); @@ -101,7 +101,7 @@ class TEveSelection : public TEveElementList, // ---------------------------------------------------------------- - ClassDef(TEveSelection, 0); // Container for selected and highlighted elements. + ClassDefOverride(TEveSelection, 0); // Container for selected and highlighted elements. }; #endif diff --git a/graf3d/eve/inc/TEveShape.h b/graf3d/eve/inc/TEveShape.h index 79652129f16c2..8d1117e5f2a36 100644 --- a/graf3d/eve/inc/TEveShape.h +++ b/graf3d/eve/inc/TEveShape.h @@ -45,10 +45,10 @@ class TEveShape : public TEveElementList, public: TEveShape(const char* n="TEveShape", const char* t=""); - virtual ~TEveShape(); + ~TEveShape() override; // Rendering parameters. - virtual void SetMainColor(Color_t color); + void SetMainColor(Color_t color) override; virtual Color_t GetFillColor() const { return fFillColor; } virtual Color_t GetLineColor() const { return fLineColor; } @@ -66,13 +66,13 @@ class TEveShape : public TEveElementList, // ---------------------------------------------------------------- - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; // ---------------------------------------------------------------- // Virtual from TObject - virtual void Paint(Option_t* option=""); + void Paint(Option_t* option="") override; // Abstract function from TAttBBox: // virtual void ComputeBBox(); @@ -90,7 +90,7 @@ class TEveShape : public TEveElementList, static void CheckAndFixBoxOrientationEv(TEveVector box[8]); static void CheckAndFixBoxOrientationFv(Float_t box[8][3]); - ClassDef(TEveShape, 0); // Abstract base-class for 2D/3D shapes. + ClassDefOverride(TEveShape, 0); // Abstract base-class for 2D/3D shapes. }; #endif diff --git a/graf3d/eve/inc/TEveShapeEditor.h b/graf3d/eve/inc/TEveShapeEditor.h index 448a3e4d6505e..aa0056e1ab5a3 100644 --- a/graf3d/eve/inc/TEveShapeEditor.h +++ b/graf3d/eve/inc/TEveShapeEditor.h @@ -38,16 +38,16 @@ class TEveShapeEditor : public TGedFrame public: TEveShapeEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveShapeEditor() {} + ~TEveShapeEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoLineWidth(); void DoLineColor(Pixel_t color); void DoDrawFrame(); void DoHighlightFrame(); - ClassDef(TEveShapeEditor, 0); // GUI editor for TEveShape. + ClassDefOverride(TEveShapeEditor, 0); // GUI editor for TEveShape. }; #endif diff --git a/graf3d/eve/inc/TEveStraightLineSet.h b/graf3d/eve/inc/TEveStraightLineSet.h index 9228667675d0c..d1a9878bffc05 100644 --- a/graf3d/eve/inc/TEveStraightLineSet.h +++ b/graf3d/eve/inc/TEveStraightLineSet.h @@ -85,9 +85,9 @@ class TEveStraightLineSet : public TEveElement, public: TEveStraightLineSet(const char* n="StraightLineSet", const char* t=""); - virtual ~TEveStraightLineSet() {} + ~TEveStraightLineSet() override {} - virtual void SetLineColor(Color_t col) { SetMainColor(col); } + void SetLineColor(Color_t col) override { SetMainColor(col); } Line_t* AddLine(Float_t x1, Float_t y1, Float_t z1, Float_t x2, Float_t y2, Float_t z2); Line_t* AddLine(const TEveVector& p1, const TEveVector& p2); @@ -109,15 +109,15 @@ class TEveStraightLineSet : public TEveElement, virtual void SetRnrLines(Bool_t x) { fRnrLines = x; } virtual void SetDepthTest(Bool_t x) { fDepthTest = x; } - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - virtual void ComputeBBox(); - virtual void Paint(Option_t* option=""); + void ComputeBBox() override; + void Paint(Option_t* option="") override; - ClassDef(TEveStraightLineSet, 0); // Set of straight lines with optional markers along the lines. + ClassDefOverride(TEveStraightLineSet, 0); // Set of straight lines with optional markers along the lines. }; @@ -131,17 +131,17 @@ class TEveStraightLineSetProjected : public TEveStraightLineSet, TEveStraightLineSetProjected& operator=(const TEveStraightLineSetProjected&); // Not implemented protected: - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveStraightLineSetProjected(); - virtual ~TEveStraightLineSetProjected() {} + ~TEveStraightLineSetProjected() override {} - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } - ClassDef(TEveStraightLineSetProjected, 0); // Projected copy of a TEveStraightLineSet. + ClassDefOverride(TEveStraightLineSetProjected, 0); // Projected copy of a TEveStraightLineSet. }; #endif diff --git a/graf3d/eve/inc/TEveStraightLineSetEditor.h b/graf3d/eve/inc/TEveStraightLineSetEditor.h index a80b821432a2c..ee34beec24d28 100644 --- a/graf3d/eve/inc/TEveStraightLineSetEditor.h +++ b/graf3d/eve/inc/TEveStraightLineSetEditor.h @@ -35,15 +35,15 @@ class TEveStraightLineSetEditor : public TGedFrame public: TEveStraightLineSetEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options = kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveStraightLineSetEditor() {} + ~TEveStraightLineSetEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods void DoRnrMarkers(); void DoRnrLines(); - ClassDef(TEveStraightLineSetEditor, 0); // Editor for TEveStraightLineSet class. + ClassDefOverride(TEveStraightLineSetEditor, 0); // Editor for TEveStraightLineSet class. }; #endif diff --git a/graf3d/eve/inc/TEveStraightLineSetGL.h b/graf3d/eve/inc/TEveStraightLineSetGL.h index 1a1e7ba317cfc..d13e0fae4033d 100644 --- a/graf3d/eve/inc/TEveStraightLineSetGL.h +++ b/graf3d/eve/inc/TEveStraightLineSetGL.h @@ -30,20 +30,20 @@ class TEveStraightLineSetGL : public TGLObject public: TEveStraightLineSetGL(); - virtual ~TEveStraightLineSetGL() {} + ~TEveStraightLineSetGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void Draw(TGLRnrCtx& rnrCtx) const; - virtual void DirectDraw(TGLRnrCtx& rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void Draw(TGLRnrCtx& rnrCtx) const override; + void DirectDraw(TGLRnrCtx& rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } - virtual Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec); + Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const override; + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec) override; - ClassDef(TEveStraightLineSetGL, 0); // GL-renderer for TEveStraightLineSet class. + ClassDefOverride(TEveStraightLineSetGL, 0); // GL-renderer for TEveStraightLineSet class. }; #endif diff --git a/graf3d/eve/inc/TEveText.h b/graf3d/eve/inc/TEveText.h index 9558fc23d651d..a7fdd8f34504d 100644 --- a/graf3d/eve/inc/TEveText.h +++ b/graf3d/eve/inc/TEveText.h @@ -44,7 +44,7 @@ class TEveText : public TEveElement, public: TEveText(const char* txt=""); - virtual ~TEveText() {} + ~TEveText() override {} Int_t GetFontSize() const { return fFontSize; } Int_t GetFontFile() const { return fFontFile; } @@ -69,12 +69,12 @@ class TEveText : public TEveElement, Float_t GetPolygonOffset(Int_t i) const { return fPolygonOffset[i]; } void SetPolygonOffset(Float_t factor, Float_t units); - virtual void Paint(Option_t* option=""); - virtual void ComputeBBox(); + void Paint(Option_t* option="") override; + void ComputeBBox() override; - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - ClassDef(TEveText, 0); // Class for visualisation of text with FTGL font. + ClassDefOverride(TEveText, 0); // Class for visualisation of text with FTGL font. }; #endif diff --git a/graf3d/eve/inc/TEveTextEditor.h b/graf3d/eve/inc/TEveTextEditor.h index a6bd3aa762edb..e65a3b8572245 100644 --- a/graf3d/eve/inc/TEveTextEditor.h +++ b/graf3d/eve/inc/TEveTextEditor.h @@ -44,9 +44,9 @@ class TEveTextEditor : public TGedFrame public: TEveTextEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveTextEditor() {} + ~TEveTextEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoText(const char*); @@ -58,7 +58,7 @@ class TEveTextEditor : public TGedFrame void DoAutoLighting(); void DoExtrude(); - ClassDef(TEveTextEditor, 0); // GUI editor for TEveText. + ClassDefOverride(TEveTextEditor, 0); // GUI editor for TEveText. }; #endif diff --git a/graf3d/eve/inc/TEveTextGL.h b/graf3d/eve/inc/TEveTextGL.h index 1ec86e85f2e2c..508c975a93854 100644 --- a/graf3d/eve/inc/TEveTextGL.h +++ b/graf3d/eve/inc/TEveTextGL.h @@ -30,14 +30,14 @@ class TEveTextGL : public TGLObject public: TEveTextGL(); - virtual ~TEveTextGL() {} + ~TEveTextGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TEveTextGL, 0); // GL renderer class for TEveText. + ClassDefOverride(TEveTextGL, 0); // GL renderer class for TEveText. }; #endif diff --git a/graf3d/eve/inc/TEveTrack.h b/graf3d/eve/inc/TEveTrack.h index 1799da01baa18..bb2791a74a501 100644 --- a/graf3d/eve/inc/TEveTrack.h +++ b/graf3d/eve/inc/TEveTrack.h @@ -70,9 +70,9 @@ class TEveTrack : public TEveLine TEveTrack(TEveRecTrack* t, TEveTrackPropagator* prop=nullptr); TEveTrack(TEveRecTrackD* t, TEveTrackPropagator* prop=nullptr); TEveTrack(const TEveTrack& t); - virtual ~TEveTrack(); + ~TEveTrack() override; - virtual void ComputeBBox(); + void ComputeBBox() override; virtual void SetStdTitle(); @@ -120,14 +120,14 @@ class TEveTrack : public TEveLine virtual void SecSelected(TEveTrack*); // *SIGNAL* - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEveTrack, 0); // Track with given vertex, momentum and optional referece-points (path-marks) along its path. + ClassDefOverride(TEveTrack, 0); // Track with given vertex, momentum and optional referece-points (path-marks) along its path. }; /******************************************************************************/ @@ -166,7 +166,7 @@ class TEveTrackList : public TEveElementList, public: TEveTrackList(TEveTrackPropagator* prop=nullptr); TEveTrackList(const char* name, TEveTrackPropagator* prop=nullptr); - virtual ~TEveTrackList(); + ~TEveTrackList() override; void MakeTracks(Bool_t recurse=kTRUE); void FindMomentumLimits(Bool_t recurse=kTRUE); @@ -179,19 +179,19 @@ class TEveTrackList : public TEveElementList, //-------------------------------- - virtual void SetMainColor(Color_t c); - virtual void SetLineColor(Color_t c) { SetMainColor(c); } + void SetMainColor(Color_t c) override; + void SetLineColor(Color_t c) override { SetMainColor(c); } virtual void SetLineColor(Color_t c, TEveElement* el); - virtual void SetLineWidth(Width_t w); + void SetLineWidth(Width_t w) override; virtual void SetLineWidth(Width_t w, TEveElement* el); - virtual void SetLineStyle(Style_t s); + void SetLineStyle(Style_t s) override; virtual void SetLineStyle(Style_t s, TEveElement* el); - virtual void SetMarkerColor(Color_t c); + void SetMarkerColor(Color_t c) override; virtual void SetMarkerColor(Color_t c, TEveElement* el); - virtual void SetMarkerSize(Size_t s); + void SetMarkerSize(Size_t s) override; virtual void SetMarkerSize(Size_t s, TEveElement* el); - virtual void SetMarkerStyle(Style_t s); + void SetMarkerStyle(Style_t s) override; virtual void SetMarkerStyle(Style_t s, TEveElement* el); void SetRnrLine(Bool_t rnr); @@ -219,12 +219,12 @@ class TEveTrackList : public TEveElementList, TEveTrack* FindTrackByLabel(Int_t label); // *MENU* TEveTrack* FindTrackByIndex(Int_t index); // *MENU* - virtual void CopyVizParams(const TEveElement* el); - virtual void WriteVizParams(std::ostream& out, const TString& var); + void CopyVizParams(const TEveElement* el) override; + void WriteVizParams(std::ostream& out, const TString& var) override; - virtual TClass* ProjectedClass(const TEveProjection* p) const; + TClass* ProjectedClass(const TEveProjection* p) const override; - ClassDef(TEveTrackList, 0); // A list of tracks supporting change of common attributes and selection based on track parameters. + ClassDefOverride(TEveTrackList, 0); // A list of tracks supporting change of common attributes and selection based on track parameters. }; #endif diff --git a/graf3d/eve/inc/TEveTrackEditor.h b/graf3d/eve/inc/TEveTrackEditor.h index acc5606d6b1c3..a4ef228053b0b 100644 --- a/graf3d/eve/inc/TEveTrackEditor.h +++ b/graf3d/eve/inc/TEveTrackEditor.h @@ -42,12 +42,12 @@ class TEveTrackEditor : public TGedFrame public: TEveTrackEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveTrackEditor() {} + ~TEveTrackEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoEditPropagator(); - ClassDef(TEveTrackEditor, 0); // Editor for TEveTrack class. + ClassDefOverride(TEveTrackEditor, 0); // Editor for TEveTrack class. }; @@ -78,10 +78,10 @@ class TEveTrackListEditor : public TGedFrame public: TEveTrackListEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveTrackListEditor() {} + ~TEveTrackListEditor() override {} void CreateRefsTab(); - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoRnrLine(); void DoRnrPoints(); @@ -89,7 +89,7 @@ class TEveTrackListEditor : public TGedFrame void DoPtRange(); void DoPRange(); - ClassDef(TEveTrackListEditor, 0); // Editor for TEveTrackList class. + ClassDefOverride(TEveTrackListEditor, 0); // Editor for TEveTrackList class. }; #endif diff --git a/graf3d/eve/inc/TEveTrackGL.h b/graf3d/eve/inc/TEveTrackGL.h index f7ccc6db40f9d..d954446ecb986 100644 --- a/graf3d/eve/inc/TEveTrackGL.h +++ b/graf3d/eve/inc/TEveTrackGL.h @@ -32,15 +32,15 @@ class TEveTrackGL : public TEveLineGL public: TEveTrackGL(); - virtual ~TEveTrackGL() {} + ~TEveTrackGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec); + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx& rnrCtx, TGLSelectRecord& rec) override; - ClassDef(TEveTrackGL, 0); // GL-renderer for TEveTrack class. + ClassDefOverride(TEveTrackGL, 0); // GL-renderer for TEveTrack class. }; #endif diff --git a/graf3d/eve/inc/TEveTrackProjected.h b/graf3d/eve/inc/TEveTrackProjected.h index 2d2c8ba8a0c69..9cd2aa03c8eb7 100644 --- a/graf3d/eve/inc/TEveTrackProjected.h +++ b/graf3d/eve/inc/TEveTrackProjected.h @@ -32,24 +32,24 @@ class TEveTrackProjected : public TEveTrack, protected: std::vector fBreakPoints; // indices of track break-points - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveTrackProjected(); - virtual ~TEveTrackProjected() {} + ~TEveTrackProjected() override {} - virtual void SetProjection(TEveProjectionManager* mng, TEveProjectable* model); + void SetProjection(TEveProjectionManager* mng, TEveProjectable* model) override; - virtual void UpdateProjection(); - virtual TEveElement* GetProjectedAsElement() { return this; } - virtual void MakeTrack(Bool_t recurse=kTRUE); + void UpdateProjection() override; + TEveElement* GetProjectedAsElement() override { return this; } + void MakeTrack(Bool_t recurse=kTRUE) override; void PrintLineSegments(); - virtual void SecSelected(TEveTrack*); // marked as signal in TEveTrack + void SecSelected(TEveTrack*) override; // marked as signal in TEveTrack - ClassDef(TEveTrackProjected, 0); // Projected copy of a TEveTrack. + ClassDefOverride(TEveTrackProjected, 0); // Projected copy of a TEveTrack. }; @@ -65,20 +65,20 @@ class TEveTrackListProjected : public TEveTrackList, TEveTrackListProjected& operator=(const TEveTrackListProjected&); // Not implemented protected: - virtual void SetDepthLocal(Float_t d); + void SetDepthLocal(Float_t d) override; public: TEveTrackListProjected(); - virtual ~TEveTrackListProjected() {} + ~TEveTrackListProjected() override {} - virtual void SetProjection(TEveProjectionManager* proj, TEveProjectable* model); - virtual void UpdateProjection() {} - virtual TEveElement* GetProjectedAsElement() { return this; } + void SetProjection(TEveProjectionManager* proj, TEveProjectable* model) override; + void UpdateProjection() override {} + TEveElement* GetProjectedAsElement() override { return this; } - virtual void SetDepth(Float_t d); + void SetDepth(Float_t d) override; virtual void SetDepth(Float_t d, TEveElement* el); - ClassDef(TEveTrackListProjected, 0); // Specialization of TEveTrackList for holding TEveTrackProjected objects. + ClassDefOverride(TEveTrackListProjected, 0); // Specialization of TEveTrackList for holding TEveTrackProjected objects. }; #endif diff --git a/graf3d/eve/inc/TEveTrackProjectedGL.h b/graf3d/eve/inc/TEveTrackProjectedGL.h index d2426fb076cff..0a7d2f0676930 100644 --- a/graf3d/eve/inc/TEveTrackProjectedGL.h +++ b/graf3d/eve/inc/TEveTrackProjectedGL.h @@ -30,12 +30,12 @@ class TEveTrackProjectedGL : public TEveTrackGL public: TEveTrackProjectedGL(); - virtual ~TEveTrackProjectedGL() {} + ~TEveTrackProjectedGL() override {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TEveTrackProjectedGL, 0); // GL-renderer for TEveTrackProjected class. + ClassDefOverride(TEveTrackProjectedGL, 0); // GL-renderer for TEveTrackProjected class. }; #endif diff --git a/graf3d/eve/inc/TEveTrackPropagator.h b/graf3d/eve/inc/TEveTrackPropagator.h index 9a4b3dbe9dcf5..80d0ad3204ef5 100644 --- a/graf3d/eve/inc/TEveTrackPropagator.h +++ b/graf3d/eve/inc/TEveTrackPropagator.h @@ -76,12 +76,12 @@ class TEveMagFieldConst : public TEveMagField TEveMagFieldConst(Double_t x, Double_t y, Double_t z) : TEveMagField(), fB(x, y, z) { fFieldConstant = kTRUE; } - virtual ~TEveMagFieldConst() {} + ~TEveMagFieldConst() override {} - virtual Double_t GetMaxFieldMagD() const { return fB.Mag(); }; - virtual TEveVectorD GetFieldD(Double_t /*x*/, Double_t /*y*/, Double_t /*z*/) const { return fB; } + Double_t GetMaxFieldMagD() const override { return fB.Mag(); }; + TEveVectorD GetFieldD(Double_t /*x*/, Double_t /*y*/, Double_t /*z*/) const override { return fB; } - ClassDef(TEveMagFieldConst, 0); // Interface to constant magnetic field. + ClassDefOverride(TEveMagFieldConst, 0); // Interface to constant magnetic field. }; @@ -103,14 +103,14 @@ class TEveMagFieldDuo : public TEveMagField { fFieldConstant = kFALSE; } - virtual ~TEveMagFieldDuo() {} + ~TEveMagFieldDuo() override {} - virtual Double_t GetMaxFieldMagD() const { return std::max(fBIn.Mag(), fBOut.Mag()); } + Double_t GetMaxFieldMagD() const override { return std::max(fBIn.Mag(), fBOut.Mag()); } - virtual TEveVectorD GetFieldD(Double_t x, Double_t y, Double_t /*z*/) const + TEveVectorD GetFieldD(Double_t x, Double_t y, Double_t /*z*/) const override { return ((x*x+y*y) TEveRecTrack; @@ -184,9 +184,9 @@ class TEveRecKink : public TObject fKinkIndex[0] = fKinkIndex[1] = 0; fKinkPdg[0] = fKinkPdg[1] = 0; } - virtual ~TEveRecKink() {} + ~TEveRecKink() override {} - ClassDef(TEveRecKink, 1); // Reconstructed kink (also used in VSD). + ClassDefOverride(TEveRecKink, 1); // Reconstructed kink (also used in VSD). }; @@ -215,9 +215,9 @@ class TEveRecV0 : public TObject TEveRecV0() : fStatus(), fVNeg(), fPNeg(), fVPos(), fPPos(), fVCa(), fV0Birth(), fLabel(0), fPdg(0) { fDLabel[0] = fDLabel[1] = 0; } - virtual ~TEveRecV0() {} + ~TEveRecV0() override {} - ClassDef(TEveRecV0, 1); // Reconstructed V0 (also used in VSD). + ClassDefOverride(TEveRecV0, 1); // Reconstructed V0 (also used in VSD). }; @@ -244,9 +244,9 @@ class TEveRecCascade : public TObject TEveRecCascade() : fStatus(), fVBac(), fPBac(), fCascadeVCa(), fCascadeBirth(), fLabel(0), fPdg(0), fDLabel(0) {} - virtual ~TEveRecCascade() {} + ~TEveRecCascade() override {} - ClassDef(TEveRecCascade, 1); // Reconstructed Cascade (also used in VSD). + ClassDefOverride(TEveRecCascade, 1); // Reconstructed Cascade (also used in VSD). }; @@ -266,9 +266,9 @@ class TEveMCRecCrossRef : public TObject TEveMCRecCrossRef() : fIsRec(false), fHasV0(false), fHasKink(false), fLabel(0), fNHits(0), fNClus(0) {} - virtual ~TEveMCRecCrossRef() {} + ~TEveMCRecCrossRef() override {} - ClassDef(TEveMCRecCrossRef, 1); // Cross-reference of sim/rec data per particle (also used in VSD). + ClassDefOverride(TEveMCRecCrossRef, 1); // Cross-reference of sim/rec data per particle (also used in VSD). }; diff --git a/graf3d/eve/inc/TEveViewer.h b/graf3d/eve/inc/TEveViewer.h index eba735f34af38..55c9894f3658d 100644 --- a/graf3d/eve/inc/TEveViewer.h +++ b/graf3d/eve/inc/TEveViewer.h @@ -43,10 +43,10 @@ class TEveViewer : public TEveWindowFrame public: TEveViewer(const char* n="TEveViewer", const char* t=""); - virtual ~TEveViewer(); + ~TEveViewer() override; - virtual void PreUndock(); - virtual void PostDock(); + void PreUndock() override; + void PostDock() override; TGLViewer* GetGLViewer() const { return fGLViewer; } void SetGLViewer(TGLViewer* viewer, TGFrame* frame); @@ -59,16 +59,16 @@ class TEveViewer : public TEveWindowFrame virtual void AddScene(TEveScene* scene); - virtual void RemoveElementLocal(TEveElement* el); - virtual void RemoveElementsLocal(); + void RemoveElementLocal(TEveElement* el) override; + void RemoveElementsLocal() override; - virtual TObject* GetEditorObject(const TEveException& eh="TEveViewer::GetEditorObject ") const; + TObject* GetEditorObject(const TEveException& eh="TEveViewer::GetEditorObject ") const override; - virtual Bool_t HandleElementPaste(TEveElement* el); + Bool_t HandleElementPaste(TEveElement* el) override; - virtual const TGPicture* GetListTreeIcon(Bool_t open=kFALSE); + const TGPicture* GetListTreeIcon(Bool_t open=kFALSE) override; - ClassDef(TEveViewer, 0); // Reve representation of TGLViewer. + ClassDefOverride(TEveViewer, 0); // Reve representation of TGLViewer. }; @@ -92,11 +92,11 @@ class TEveViewerList : public TEveElementList public: TEveViewerList(const char* n="TEveViewerList", const char* t=""); - virtual ~TEveViewerList(); + ~TEveViewerList() override; - virtual void AddElement(TEveElement* el); - virtual void RemoveElementLocal(TEveElement* el); - virtual void RemoveElementsLocal(); + void AddElement(TEveElement* el) override; + void RemoveElementLocal(TEveElement* el) override; + void RemoveElementsLocal() override; // -------------------------------- @@ -129,7 +129,7 @@ class TEveViewerList : public TEveElementList Bool_t UseLightColorSet() const { return fUseLightColorSet; } void SwitchColorSet(); - ClassDef(TEveViewerList, 0); // List of Viewers providing common operations on TEveViewer collections. + ClassDefOverride(TEveViewerList, 0); // List of Viewers providing common operations on TEveViewer collections. }; #endif diff --git a/graf3d/eve/inc/TEveViewerListEditor.h b/graf3d/eve/inc/TEveViewerListEditor.h index fb8696b564d52..81af27edbb616 100644 --- a/graf3d/eve/inc/TEveViewerListEditor.h +++ b/graf3d/eve/inc/TEveViewerListEditor.h @@ -32,15 +32,15 @@ class TEveViewerListEditor : public TGedFrame public: TEveViewerListEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveViewerListEditor() {} + ~TEveViewerListEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // Declare callback/slot methods void DoBrightness(); void SwitchColorSet(); - ClassDef(TEveViewerListEditor, 0); // GUI editor for TEveViewerList. + ClassDefOverride(TEveViewerListEditor, 0); // GUI editor for TEveViewerList. }; #endif diff --git a/graf3d/eve/inc/TEveWindow.h b/graf3d/eve/inc/TEveWindow.h index d68afeef52886..22412463c5abd 100644 --- a/graf3d/eve/inc/TEveWindow.h +++ b/graf3d/eve/inc/TEveWindow.h @@ -74,7 +74,7 @@ class TEveCompositeFrame : public TGCompositeFrame public: TEveCompositeFrame(TGCompositeFrame* gui_parent, TEveWindow* eve_parent); - virtual ~TEveCompositeFrame(); + ~TEveCompositeFrame() override; virtual void WindowNameChanged(const TString& name); @@ -100,7 +100,7 @@ class TEveCompositeFrame : public TGCompositeFrame UInt_t mini_bar_height = 4, Bool_t allow_top_collapse = kTRUE); - ClassDef(TEveCompositeFrame, 0); // Composite frame containing eve-window-controls and eve-windows. + ClassDefOverride(TEveCompositeFrame, 0); // Composite frame containing eve-window-controls and eve-windows. }; @@ -122,11 +122,11 @@ class TEveCompositeFrameInMainFrame : public TEveCompositeFrame public: TEveCompositeFrameInMainFrame(TGCompositeFrame* parent, TEveWindow* eve_parent, TGMainFrame* mf); - virtual ~TEveCompositeFrameInMainFrame(); + ~TEveCompositeFrameInMainFrame() override; - virtual void WindowNameChanged(const TString& name); + void WindowNameChanged(const TString& name) override; - virtual void Destroy(); + void Destroy() override; void SetOriginalSlotAndContainer(TEveWindow* slot, TEveWindow* container); @@ -136,7 +136,7 @@ class TEveCompositeFrameInMainFrame : public TEveCompositeFrame TEveWindow* GetOriginalSlot() const { return fOriginalSlot; } TEveWindow* GetOriginalContainer() const { return fOriginalContainer; } - ClassDef(TEveCompositeFrameInMainFrame, 0); // Eve-composite-frame that is contained in one tab of a TGTab. + ClassDefOverride(TEveCompositeFrameInMainFrame, 0); // Eve-composite-frame that is contained in one tab of a TGTab. }; @@ -156,11 +156,11 @@ class TEveCompositeFrameInPack : public TEveCompositeFrame public: TEveCompositeFrameInPack(TGCompositeFrame* parent, TEveWindow* eve_parent, TGPack* pack); - virtual ~TEveCompositeFrameInPack(); + ~TEveCompositeFrameInPack() override; - virtual void Destroy(); + void Destroy() override; - ClassDef(TEveCompositeFrameInPack, 0); // Eve-composite-frame that is contained in a TGPack. + ClassDefOverride(TEveCompositeFrameInPack, 0); // Eve-composite-frame that is contained in a TGPack. }; @@ -183,15 +183,15 @@ class TEveCompositeFrameInTab : public TEveCompositeFrame public: TEveCompositeFrameInTab(TGCompositeFrame* parent, TEveWindow* eve_parent, TGTab* tab); - virtual ~TEveCompositeFrameInTab(); + ~TEveCompositeFrameInTab() override; - virtual void WindowNameChanged(const TString& name); + void WindowNameChanged(const TString& name) override; - virtual void Destroy(); + void Destroy() override; - virtual void SetCurrent(Bool_t curr); + void SetCurrent(Bool_t curr) override; - ClassDef(TEveCompositeFrameInTab, 0); // Eve-composite-frame that is contained in one tab of a TGTab. + ClassDefOverride(TEveCompositeFrameInTab, 0); // Eve-composite-frame that is contained in one tab of a TGTab. }; @@ -226,13 +226,13 @@ class TEveWindow : public TEveElementList static Pixel_t fgCurrentBackgroundColor; static Pixel_t fgMiniBarBackgroundColor; - virtual void PreDeleteElement(); + void PreDeleteElement() override; public: TEveWindow(const char* n="TEveWindow", const char* t=""); - virtual ~TEveWindow(); + ~TEveWindow() override; - virtual void NameTitleChanged(); + void NameTitleChanged() override; virtual TGFrame* GetGUIFrame() = 0; virtual void PreUndock(); @@ -290,7 +290,7 @@ class TEveWindow : public TEveElementList static void SetCurrentBackgroundColor(Pixel_t p); static void SetMiniBarBackgroundColor(Pixel_t p); - ClassDef(TEveWindow, 0); // Abstract base-class for eve-windows. + ClassDefOverride(TEveWindow, 0); // Abstract base-class for eve-windows. }; @@ -308,13 +308,13 @@ class TEveWindowSlot : public TEveWindow TGTextButton *fEmptyButt; TGCompositeFrame *fEmbedBuffer; - virtual void SetCurrent(Bool_t curr); + void SetCurrent(Bool_t curr) override; public: TEveWindowSlot(const char* n="TEveWindowSlot", const char* t=""); - virtual ~TEveWindowSlot(); + ~TEveWindowSlot() override; - virtual TGFrame* GetGUIFrame(); + TGFrame* GetGUIFrame() override; TEveWindowPack* MakePack(); // *MENU* TEveWindowTab* MakeTab(); // *MENU* @@ -324,7 +324,7 @@ class TEveWindowSlot : public TEveWindow TGCompositeFrame* StartEmbedding(); TEveWindowFrame* StopEmbedding(const char* name=nullptr); - ClassDef(TEveWindowSlot, 0); // An unoccupied eve-window slot. + ClassDefOverride(TEveWindowSlot, 0); // An unoccupied eve-window slot. }; @@ -343,13 +343,13 @@ class TEveWindowFrame : public TEveWindow public: TEveWindowFrame(TGFrame* frame, const char* n="TEveWindowFrame", const char* t=""); - virtual ~TEveWindowFrame(); + ~TEveWindowFrame() override; - virtual TGFrame* GetGUIFrame() { return fGUIFrame; } + TGFrame* GetGUIFrame() override { return fGUIFrame; } TGCompositeFrame* GetGUICompositeFrame(); - ClassDef(TEveWindowFrame, 0); // Eve-window containing any TGFrame. + ClassDefOverride(TEveWindowFrame, 0); // Eve-window containing any TGFrame. }; @@ -368,13 +368,13 @@ class TEveWindowPack : public TEveWindow public: TEveWindowPack(TGPack* p, const char* n="TEveWindowPack", const char* t=""); - virtual ~TEveWindowPack(); + ~TEveWindowPack() override; - virtual TGFrame* GetGUIFrame(); + TGFrame* GetGUIFrame() override; - virtual Bool_t CanMakeNewSlots() const { return kTRUE; } + Bool_t CanMakeNewSlots() const override { return kTRUE; } virtual TEveWindowSlot* NewSlotWithWeight(Float_t w); - virtual TEveWindowSlot* NewSlot(); // *MENU* + TEveWindowSlot* NewSlot() override; // *MENU* void FlipOrientation(); // *MENU* void SetVertical(Bool_t x=kTRUE); @@ -384,7 +384,7 @@ class TEveWindowPack : public TEveWindow TGPack* GetPack() const { return fPack; } - ClassDef(TEveWindowPack, 0); // Eve-window containing a TGPack. + ClassDefOverride(TEveWindowPack, 0); // Eve-window containing a TGPack. }; @@ -403,16 +403,16 @@ class TEveWindowTab : public TEveWindow public: TEveWindowTab(TGTab* tab, const char* n="TEveWindowTab", const char* t=""); - virtual ~TEveWindowTab(); + ~TEveWindowTab() override; - virtual TGFrame* GetGUIFrame(); + TGFrame* GetGUIFrame() override; - virtual Bool_t CanMakeNewSlots() const { return kTRUE; } - virtual TEveWindowSlot* NewSlot(); // *MENU* + Bool_t CanMakeNewSlots() const override { return kTRUE; } + TEveWindowSlot* NewSlot() override; // *MENU* TGTab* GetTab() const { return fTab; } - ClassDef(TEveWindowTab, 0); // Eve-window containing a TGTab. + ClassDefOverride(TEveWindowTab, 0); // Eve-window containing a TGTab. }; @@ -434,7 +434,7 @@ class TEveContextMenu : public TContextMenu void SetupAndPopup(TGWindow* button, TObject* obj); - ClassDef(TEveContextMenu, 0) // Specialization of TContextMenu for Eve. + ClassDefOverride(TEveContextMenu, 0) // Specialization of TContextMenu for Eve. }; #endif diff --git a/graf3d/eve/inc/TEveWindowEditor.h b/graf3d/eve/inc/TEveWindowEditor.h index 8889539c0c349..4cad2e02c40a6 100644 --- a/graf3d/eve/inc/TEveWindowEditor.h +++ b/graf3d/eve/inc/TEveWindowEditor.h @@ -35,13 +35,13 @@ class TEveWindowEditor : public TGedFrame public: TEveWindowEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TEveWindowEditor() {} + ~TEveWindowEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void DoShowTitleBar(); - ClassDef(TEveWindowEditor, 0); // GUI editor for TEveWindow. + ClassDefOverride(TEveWindowEditor, 0); // GUI editor for TEveWindow. }; #endif diff --git a/graf3d/eve/inc/TEveWindowManager.h b/graf3d/eve/inc/TEveWindowManager.h index dfde751cbf539..f8d790a0b6fdc 100644 --- a/graf3d/eve/inc/TEveWindowManager.h +++ b/graf3d/eve/inc/TEveWindowManager.h @@ -33,7 +33,7 @@ class TEveWindowManager : public TEveElementList, public: TEveWindowManager(const char* n="TEveWindowManager", const char* t=""); - virtual ~TEveWindowManager(); + ~TEveWindowManager() override; void SelectWindow(TEveWindow* w); void DeleteWindow(TEveWindow* w); @@ -59,7 +59,7 @@ class TEveWindowManager : public TEveElementList, void ShowNormalEveDecorations(); void SetShowTitleBars(Bool_t state); - ClassDef(TEveWindowManager, 0); // Manager for EVE windows. + ClassDefOverride(TEveWindowManager, 0); // Manager for EVE windows. }; #endif diff --git a/graf3d/eve/src/TEveDigitSetEditor.cxx b/graf3d/eve/src/TEveDigitSetEditor.cxx index 2083742b4e96d..6684b39e6688e 100644 --- a/graf3d/eve/src/TEveDigitSetEditor.cxx +++ b/graf3d/eve/src/TEveDigitSetEditor.cxx @@ -60,7 +60,7 @@ void TEveDigitSetEditor::CreateInfoTab() TGCompositeFrame *title1 = new TGCompositeFrame(fInfoFrame, 180, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); @@ -72,8 +72,7 @@ void TEveDigitSetEditor::CreateInfoTab() fHistoButtFrame = new TGHorizontalFrame(fInfoFrame); - TGTextButton* b = 0; - b = new TGTextButton(fHistoButtFrame, "Histo"); + TGTextButton* b = new TGTextButton(fHistoButtFrame, "Histo"); b->SetToolTipText("Show histogram over full range."); fHistoButtFrame->AddFrame(b, new TGLayoutHints(kLHintsLeft|kLHintsExpandX, 1, 1, 0, 0)); b->Connect("Clicked()", "TEveDigitSetEditor", this, "DoHisto()"); diff --git a/graf3d/eve/src/TEveProjectionAxesEditor.cxx b/graf3d/eve/src/TEveProjectionAxesEditor.cxx index 0705a399cb9f4..5e62d918454e3 100644 --- a/graf3d/eve/src/TEveProjectionAxesEditor.cxx +++ b/graf3d/eve/src/TEveProjectionAxesEditor.cxx @@ -89,7 +89,7 @@ TEveProjectionAxesEditor::TEveProjectionAxesEditor(const TGWindow *p, Int_t widt TGCompositeFrame *title1 = new TGCompositeFrame(fCenterFrame, 180, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title1->AddFrame(new TGLabel(title1, "Distortion Center"), diff --git a/graf3d/eve/src/TEveTrackEditor.cxx b/graf3d/eve/src/TEveTrackEditor.cxx index c41c661437dfa..d3aabc77a96ad 100644 --- a/graf3d/eve/src/TEveTrackEditor.cxx +++ b/graf3d/eve/src/TEveTrackEditor.cxx @@ -141,7 +141,7 @@ void TEveTrackListEditor::CreateRefsTab() TGCompositeFrame *title1 = new TGCompositeFrame(fRefs, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title1->AddFrame(new TGLabel(title1, "PathMarks"), diff --git a/graf3d/eve/src/TEveTrackPropagatorEditor.cxx b/graf3d/eve/src/TEveTrackPropagatorEditor.cxx index 676dbb44bbd9e..5df2197511bc0 100644 --- a/graf3d/eve/src/TEveTrackPropagatorEditor.cxx +++ b/graf3d/eve/src/TEveTrackPropagatorEditor.cxx @@ -167,7 +167,7 @@ void TEveTrackPropagatorSubEditor::CreateRefsContainer(TGVerticalFrame* p) // First vertex. { TGCompositeFrame *vf = new TGCompositeFrame - (fRefsCont, 145, 10, kHorizontalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + (fRefsCont, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); vf->AddFrame(new TGLabel(vf, "FirstVertex"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); vf->AddFrame(new TGHorizontal3DLine(vf), @@ -188,7 +188,7 @@ void TEveTrackPropagatorSubEditor::CreateRefsContainer(TGVerticalFrame* p) // Break-points of projected tracks { TGCompositeFrame *vf = new TGCompositeFrame - (fRefsCont, 145, 10, kHorizontalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + (fRefsCont, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); vf->AddFrame(new TGLabel(vf, "BreakPoints"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); vf->AddFrame(new TGHorizontal3DLine(vf), @@ -440,7 +440,7 @@ TEveTrackPropagatorEditor::TEveTrackPropagatorEditor(const TGWindow *p, TGVerticalFrame* refsFrame = CreateEditorTabSubFrame("Refs"); { TGCompositeFrame *cf = new TGCompositeFrame - (refsFrame, 145, 10, kHorizontalFrame | kLHintsExpandX | kFixedWidth | kOwnBackground); + (refsFrame, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); cf->AddFrame(new TGLabel(cf, "PathMarks"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); cf->AddFrame(new TGHorizontal3DLine(cf), diff --git a/graf3d/eve7/CMakeLists.txt b/graf3d/eve7/CMakeLists.txt index 611f843a2abbb..73c45886976f8 100644 --- a/graf3d/eve7/CMakeLists.txt +++ b/graf3d/eve7/CMakeLists.txt @@ -4,6 +4,11 @@ # For the licensing terms see $ROOTSYS/LICENSE. # For the list of contributors see $ROOTSYS/README/CREDITS. +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(ROOTEve HEADERS ROOT/REveChunkManager.hxx @@ -127,7 +132,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTEve TreePlayer RCsg ROOTWebDisplay - ROOTBrowserv7 + ${EXTRA_DICT_OPTS} ) if(builtin_nlohmannjson) diff --git a/graf3d/eve7/inc/ROOT/REveClient.hxx b/graf3d/eve7/inc/ROOT/REveClient.hxx index b7e95152fa673..3b3fd792d7c0b 100644 --- a/graf3d/eve7/inc/ROOT/REveClient.hxx +++ b/graf3d/eve7/inc/ROOT/REveClient.hxx @@ -15,9 +15,11 @@ #include namespace ROOT { -namespace Experimental { class RWebWindow; + +namespace Experimental { + class REveScene; class REveClient { @@ -25,11 +27,11 @@ class REveClient { friend class REveScene; unsigned fId{0}; - std::shared_ptr fWebWindow; + std::shared_ptr fWebWindow; public: REveClient() = default; - REveClient(unsigned int cId, std::shared_ptr &win) : fId(cId), fWebWindow(win) {} + REveClient(unsigned int cId, std::shared_ptr &win) : fId(cId), fWebWindow(win) {} }; } // namespace Experimental diff --git a/graf3d/eve7/inc/ROOT/REveGeoPolyShape.hxx b/graf3d/eve7/inc/ROOT/REveGeoPolyShape.hxx index c67f78da7627d..21c36c6a68228 100644 --- a/graf3d/eve7/inc/ROOT/REveGeoPolyShape.hxx +++ b/graf3d/eve7/inc/ROOT/REveGeoPolyShape.hxx @@ -37,7 +37,7 @@ protected: std::vector fPolyDesc; Int_t fNbPols{0}; - virtual void FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const; + void FillBuffer3D(TBuffer3D &buffer, Int_t reqSections, Bool_t localFrame) const override; void SetFromBuff3D(const TBuffer3D &buffer); @@ -67,7 +67,7 @@ protected: public: REveGeoPolyShape() = default; - virtual ~REveGeoPolyShape() = default; + ~REveGeoPolyShape() override = default; Int_t GetNumFaces() const { return fNbPols; } @@ -79,15 +79,15 @@ public: void EnforceTriangles(); void CalculateNormals(); - virtual const TBuffer3D& GetBuffer3D(Int_t reqSections, Bool_t localFrame) const; - virtual TBuffer3D *MakeBuffer3D() const; + const TBuffer3D& GetBuffer3D(Int_t reqSections, Bool_t localFrame) const override; + TBuffer3D *MakeBuffer3D() const override; static void SetAutoEnforceTriangles(Bool_t f); static Bool_t GetAutoEnforceTriangles(); static void SetAutoCalculateNormals(Bool_t f); static Bool_t GetAutoCalculateNormals(); - ClassDef(REveGeoPolyShape, 1); // A shape with arbitrary tesselation for visualization of CSG shapes. + ClassDefOverride(REveGeoPolyShape, 1); // A shape with arbitrary tesselation for visualization of CSG shapes. }; }} diff --git a/graf3d/eve7/inc/ROOT/REveGeoShapeExtract.hxx b/graf3d/eve7/inc/ROOT/REveGeoShapeExtract.hxx index 4421d02ae6f22..d4e88284a4b0b 100644 --- a/graf3d/eve7/inc/ROOT/REveGeoShapeExtract.hxx +++ b/graf3d/eve7/inc/ROOT/REveGeoShapeExtract.hxx @@ -38,7 +38,7 @@ protected: public: REveGeoShapeExtract(const char *n = "REveGeoShapeExtract", const char *t = nullptr); - ~REveGeoShapeExtract(); + ~REveGeoShapeExtract() override; Bool_t HasElements(); void AddElement(REveGeoShapeExtract* gse); @@ -63,7 +63,7 @@ public: TGeoShape* GetShape() { return fShape; } TList* GetElements() { return fElements; } - ClassDef(REveGeoShapeExtract, 1); // Globally positioned TGeoShape with rendering attributes and an optional list of daughter shape-extracts. + ClassDefOverride(REveGeoShapeExtract, 1); // Globally positioned TGeoShape with rendering attributes and an optional list of daughter shape-extracts. }; } // namespace Experimental diff --git a/graf3d/eve7/inc/ROOT/REveManager.hxx b/graf3d/eve7/inc/ROOT/REveManager.hxx index e0b35de7bf996..5b81fe67bbb74 100644 --- a/graf3d/eve7/inc/ROOT/REveManager.hxx +++ b/graf3d/eve7/inc/ROOT/REveManager.hxx @@ -65,7 +65,7 @@ public: struct Conn { - enum EConnState {Free, Processing, WaitingResponse }; + enum EConnState {Free, WaitingResponse }; unsigned fId{0}; EConnState fState{Free}; @@ -87,12 +87,13 @@ public: class MIR { public: - MIR(const std::string& cmd, ElementId_t id, const std::string& ctype) - :fCmd(cmd), fId(id), fCtype(ctype){} + MIR(const std::string& cmd, ElementId_t id, const std::string& ctype, unsigned connid) + :fCmd(cmd), fId(id), fCtype(ctype), fConnId(connid){} std::string fCmd; ElementId_t fId; std::string fCtype; + unsigned fConnId; }; struct Logger { @@ -144,9 +145,9 @@ protected: REveSelection *fSelection{nullptr}; REveSelection *fHighlight{nullptr}; - std::shared_ptr fWebWindow; - std::vector fConnList; - std::queue > fMIRqueue; + std::shared_ptr fWebWindow; + std::vector fConnList; + std::queue > fMIRqueue; // MIR execution std::thread fMIRExecThread; @@ -163,7 +164,9 @@ protected: void MIRExecThread(); void ExecuteMIR(std::shared_ptr mir); - void PublishChanges(); + + void StreamSceneChangesToJson(); + void SendSceneChanges(); public: REveManager(); // (Bool_t map_window=kTRUE, Option_t* opt="FI"); @@ -247,7 +250,7 @@ public: void SetDefaultHtmlPage(const std::string& path); void SetClientVersion(const std::string& version); - void ScheduleMIR(const std::string &cmd, ElementId_t i, const std::string& ctype); + void ScheduleMIR(const std::string &cmd, ElementId_t i, const std::string& ctype, unsigned connid); static REveManager* Create(); static void Terminate(); @@ -261,7 +264,7 @@ public: // Access to internals, needed for low-level control in advanced // applications. - std::shared_ptr GetWebWindow() const { return fWebWindow; } + std::shared_ptr GetWebWindow() const { return fWebWindow; } // void Send(void* buff, unsigned connid); void Send(unsigned connid, const std::string &data); @@ -269,6 +272,9 @@ public: void Show(const RWebDisplayArgs &args = ""); + void DisconnectEveViewer(REveViewer*); + void ConnectEveViewer(REveViewer*); + void GetServerStatus(REveServerStatus&); bool IsRCore() const { return fIsRCore; } }; diff --git a/graf3d/eve7/inc/ROOT/REveScene.hxx b/graf3d/eve7/inc/ROOT/REveScene.hxx index 6e55ba79faa7b..81fb187e801f6 100644 --- a/graf3d/eve7/inc/ROOT/REveScene.hxx +++ b/graf3d/eve7/inc/ROOT/REveScene.hxx @@ -80,12 +80,14 @@ protected: std::vector fCommands; /// &&sub); void RemoveSubscriber(unsigned int); + bool GetMandatory() { return fMandatory; } + void SetMandatory(bool x) { fMandatory = x; } + void AddCommand(const std::string &name, const std::string &icon, const REveElement *element, const std::string &action); }; @@ -145,7 +149,6 @@ public: // void DestroyElementRenderers(REveElement* element); void AcceptChanges(bool); bool AnyChanges() const; - void ProcessSceneChanges(); }; } // namespace Experimental diff --git a/graf3d/eve7/inc/ROOT/REveTableInfo.hxx b/graf3d/eve7/inc/ROOT/REveTableInfo.hxx index ad068395730ed..4d9a5faeaa121 100644 --- a/graf3d/eve7/inc/ROOT/REveTableInfo.hxx +++ b/graf3d/eve7/inc/ROOT/REveTableInfo.hxx @@ -70,6 +70,10 @@ public: return column(label, precision, label); } + void clearColumnDefinitions(){ + fSpecs[fClassName].clear(); + } + REveTableHandle(std::string className, Specs_t &specs) :fClassName(className), fSpecs(specs) { diff --git a/graf3d/eve7/inc/ROOT/REveTrans.hxx b/graf3d/eve7/inc/ROOT/REveTrans.hxx index a584d753c0c31..1a21ba5713cd2 100644 --- a/graf3d/eve7/inc/ROOT/REveTrans.hxx +++ b/graf3d/eve7/inc/ROOT/REveTrans.hxx @@ -165,7 +165,7 @@ public: void RotateIP(Float_t *v) const; TVector3 Rotate(const TVector3 &v) const; - virtual void Print(Option_t *option = "") const; + void Print(Option_t *option = "") const override; // REveUtil stuff @@ -187,7 +187,7 @@ public: Bool_t IsScale(Double_t low = 0.9, Double_t high = 1.1) const; - ClassDef(REveTrans, 1); // Column-major 4x4 transforamtion matrix for homogeneous coordinates. + ClassDefOverride(REveTrans, 1); // Column-major 4x4 transforamtion matrix for homogeneous coordinates. }; std::ostream &operator<<(std::ostream &s, const REveTrans &t); diff --git a/graf3d/eve7/inc/ROOT/REveTreeTools.hxx b/graf3d/eve7/inc/ROOT/REveTreeTools.hxx index f38d37f7d519f..b1aed5158ecf1 100644 --- a/graf3d/eve7/inc/ROOT/REveTreeTools.hxx +++ b/graf3d/eve7/inc/ROOT/REveTreeTools.hxx @@ -34,12 +34,12 @@ protected: public: REveSelectorToEventList(TEventList *evl, const char *sel); - virtual ~REveSelectorToEventList() {} + ~REveSelectorToEventList() override {} - virtual Int_t Version() const { return 1; } - virtual Bool_t Process(Long64_t entry); + Int_t Version() const override { return 1; } + Bool_t Process(Long64_t entry) override; - ClassDef(REveSelectorToEventList, 2); // TSelector that stores entry numbers of matching TTree entries into an event-list. + ClassDefOverride(REveSelectorToEventList, 2); // TSelector that stores entry numbers of matching TTree entries into an event-list. }; ///////////////////////////////////////////////////////////////////////////////// @@ -92,11 +92,11 @@ protected: public: REvePointSelector(TTree *t = nullptr, REvePointSelectorConsumer *c = nullptr, const char *vexp = "", const char *sel = ""); - virtual ~REvePointSelector() {} + ~REvePointSelector() override {} virtual Long64_t Select(const char *selection = nullptr); virtual Long64_t Select(TTree *t, const char *selection = nullptr); - virtual void TakeAction(); + void TakeAction() override; TTree *GetTree() const { return fSelectTree; } void SetTree(TTree *t) { fSelectTree = t; } @@ -115,7 +115,7 @@ public: Int_t GetSubIdNum() const { return fSubIdNum; } - ClassDef(REvePointSelector, 2); // TSelector for direct extraction of point-like data from a Tree. + ClassDefOverride(REvePointSelector, 2); // TSelector for direct extraction of point-like data from a Tree. }; } // namespace Experimental diff --git a/graf3d/eve7/inc/ROOT/REveTypes.hxx b/graf3d/eve7/inc/ROOT/REveTypes.hxx index b3af93c5af6be..5498da002ab1e 100644 --- a/graf3d/eve7/inc/ROOT/REveTypes.hxx +++ b/graf3d/eve7/inc/ROOT/REveTypes.hxx @@ -43,7 +43,7 @@ class REveException : public std::exception { public: REveException() = default; explicit REveException(const std::string &s) : fWhat(s) {} - virtual ~REveException() noexcept {} + ~REveException() noexcept override {} void append(const std::string &s) { fWhat.append(s); } const char *what() const noexcept override { return fWhat.c_str(); } diff --git a/graf3d/eve7/inc/ROOT/REveUtil.hxx b/graf3d/eve7/inc/ROOT/REveUtil.hxx index 01f74de3c95a2..85f4c5aada0aa 100644 --- a/graf3d/eve7/inc/ROOT/REveUtil.hxx +++ b/graf3d/eve7/inc/ROOT/REveUtil.hxx @@ -138,7 +138,7 @@ protected: public: REveRefBackPtr() = default; - virtual ~REveRefBackPtr(); + ~REveRefBackPtr() override; using REveRefCnt::DecRefCount; using REveRefCnt::IncRefCount; diff --git a/graf3d/eve7/inc/ROOT/REveVSD.hxx b/graf3d/eve7/inc/ROOT/REveVSD.hxx index e9c7a0fb3cb7a..62946d400556d 100644 --- a/graf3d/eve7/inc/ROOT/REveVSD.hxx +++ b/graf3d/eve7/inc/ROOT/REveVSD.hxx @@ -69,7 +69,7 @@ public: static void DisableTObjectStreamersForVSDStruct(); - ClassDef(REveVSD, 1); // Visualization Summary Data - a collection of trees holding standard event data in experiment independent format. + ClassDefOverride(REveVSD, 1); // Visualization Summary Data - a collection of trees holding standard event data in experiment independent format. }; } // namespace Experimental diff --git a/graf3d/eve7/inc/ROOT/REveVSDStructs.hxx b/graf3d/eve7/inc/ROOT/REveVSDStructs.hxx index fd81253edc97b..95ab824af73c3 100644 --- a/graf3d/eve7/inc/ROOT/REveVSDStructs.hxx +++ b/graf3d/eve7/inc/ROOT/REveVSDStructs.hxx @@ -65,7 +65,7 @@ public: void ResetPdgCode() { fPdgCode = 0; } - ClassDef(REveMCTrack, 1); // Monte Carlo track (also used in VSD). + ClassDefOverride(REveMCTrack, 1); // Monte Carlo track (also used in VSD). }; //////////////////////////////////////////////////////////////////////////////// diff --git a/graf3d/eve7/inc/ROOT/REveViewer.hxx b/graf3d/eve7/inc/ROOT/REveViewer.hxx index 159d9661e5cb6..81aeb424c892a 100644 --- a/graf3d/eve7/inc/ROOT/REveViewer.hxx +++ b/graf3d/eve7/inc/ROOT/REveViewer.hxx @@ -28,12 +28,18 @@ class REveViewer : public REveElement { public: enum ECameraType { kCameraPerspXOZ, kCameraOrthoXOY }; + enum EAxesType {kAxesNone, kAxesOrigin, kAxesEdge }; private: REveViewer(const REveViewer&) = delete; REveViewer& operator=(const REveViewer&) = delete; ECameraType fCameraType{kCameraPerspXOZ}; + EAxesType fAxesType{kAxesNone}; + bool fBlackBackground{false}; + + bool fMandatory{true}; + std::string fPostStreamFlag; public: REveViewer(const std::string &n="REveViewer", const std::string &t=""); @@ -47,6 +53,15 @@ public: void SetCameraType(ECameraType t) { fCameraType = t; } ECameraType GetCameraType() const { return fCameraType; } + void SetAxesType(int); + void SetBlackBackground(bool); + + void DisconnectClient(); + void ConnectClient(); + + void SetMandatory(bool x); + bool GetMandatory() { return fMandatory; } + void RemoveElementLocal(REveElement *el) override; void RemoveElementsLocal() override; Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override; @@ -110,6 +125,7 @@ public: Bool_t UseLightColorSet() const { return fUseLightColorSet; } void SwitchColorSet(); + // Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override; }; } // namespace Experimental diff --git a/graf3d/eve7/src/REveDataCollection.cxx b/graf3d/eve7/src/REveDataCollection.cxx index 539c8d8ee9d77..a3e66fd1e9403 100644 --- a/graf3d/eve7/src/REveDataCollection.cxx +++ b/graf3d/eve7/src/REveDataCollection.cxx @@ -355,68 +355,58 @@ void REveDataCollection::ApplyFilter() void REveDataCollection::StreamPublicMethods(nlohmann::json &j) const { - struct PubMethods - { - void FillJSON(TClass* c, nlohmann::json & arr) - { - TString ctor = c->GetName(), dtor = "~"; - { - int i = ctor.Last(':'); - if (i != kNPOS) - { - ctor.Replace(0, i + 1, ""); - } - dtor += ctor; - } + j["fPublicFunctions"] = nlohmann::json::array(); + TMethod *meth; + TIter next(fItemClass->GetListOfAllPublicMethods()); + int cnt = 0; + while ((meth = (TMethod *)next())) { + // Filter out ctor, dtor, some ROOT stuff. + + TString m(meth->GetName()); + + if (m == "Class" || m == "Class_Name" || m == "Class_Version" || m == "Dictionary" || m == "IsA" || + m == "DeclFileName" || m == "ImplFileName" || m == "DeclFileLine" || m == "ImplFileLine" || m == "Streamer" || + m == "StreamerNVirtual" || m == "ShowMembers" || m == "CheckTObjectHashConsistency") { + continue; + } - TMethod *meth; - TIter next(c->GetListOfMethods()); - while ((meth = (TMethod*) next())) - { - // Filter out ctor, dtor, some ROOT stuff. - { - TString m(meth->GetName()); - if (m == ctor || m == dtor || - m == "Class" || m == "Class_Name" || m == "Class_Version" || m == "Dictionary" || m == "IsA" || - m == "DeclFileName" || m == "ImplFileName" || m == "DeclFileLine" || m == "ImplFileLine" || - m == "Streamer" || m == "StreamerNVirtual" || m == "ShowMembers" || - m == "CheckTObjectHashConsistency") - { - continue; - } - } - - TString ms; - TMethodArg *ma; - TIter next_ma(meth->GetListOfMethodArgs()); - while ((ma = (TMethodArg*) next_ma())) - { - if ( ! ms.IsNull()) ms += ", "; - - ms += ma->GetTypeName(); - ms += " "; - ms += ma->GetName(); - } - std::string entry(TString::Format("i.%s(%s)",meth->GetName(),ms.Data()).Data()); - nlohmann::json jm ; - jm["f"] = entry; - jm["r"] = meth->GetReturnTypeName(); - jm["c"] = c->GetName(); - arr.push_back(jm); - } - { - TBaseClass *base; - TIter blnext(c->GetListOfBases()); - while ((base = (TBaseClass*) blnext())) - { - FillJSON(base->GetClassPointer(), arr); - } - } + if (m.BeginsWith('~')) + continue; + + if (m.Contains("operator")) + continue; + + if (meth->GetListOfMethodArgs()->GetLast() > 1) + continue; + + if (strcmp(meth->GetReturnTypeName(),"void") == 0) + continue; + + TString ms; + TMethodArg *ma; + TIter next_ma(meth->GetListOfMethodArgs()); + while ((ma = (TMethodArg *)next_ma())) { + if (!ms.IsNull()) + ms += ", "; + + ms += ma->GetTypeName(); + ms += " "; + ms += ma->GetName(); } - }; - j["fPublicFunctions"] = nlohmann::json::array(); - PubMethods pm; - pm.FillJSON(fItemClass, j["fPublicFunctions"]); + std::string entry(TString::Format("i.%s(%s)", meth->GetName(), ms.Data()).Data()); + nlohmann::json jm; + jm["f"] = entry; + jm["r"] = meth->GetReturnTypeName(); + jm["c"] = meth->GetClass()->GetName(); + j["fPublicFunctions"].push_back(jm); + + if (m.Contains("charge")) + { + printf("FOUND chargw methos %s %d\n\n", m.Data(), cnt); + } + + cnt++; + } } //______________________________________________________________________________ diff --git a/graf3d/eve7/src/REveGeoShape.cxx b/graf3d/eve7/src/REveGeoShape.cxx index 173a30396cb2c..57de9ffe21049 100644 --- a/graf3d/eve7/src/REveGeoShape.cxx +++ b/graf3d/eve7/src/REveGeoShape.cxx @@ -146,26 +146,18 @@ void REveGeoShape::BuildRenderData() { if (!fShape) return; - REveGeoPolyShape *egps = nullptr; - std::unique_ptr tmp_egps; + fRenderData = std::make_unique("makeEveGeoShape"); + REveElement::BuildRenderData(); if (fCompositeShape) { - - egps = dynamic_cast(fShape); - + REveGeoPolyShape* egps = dynamic_cast(fShape); + egps->FillRenderData(*fRenderData); } else { - - tmp_egps = std::make_unique(); - + REveGeoManagerHolder gmgr(fgGeoManager); + std::unique_ptr tmp_egps = std::make_unique(); tmp_egps->BuildFromShape(fShape, fNSegments); - - egps = tmp_egps.get(); + tmp_egps->FillRenderData(*fRenderData); } - - fRenderData = std::make_unique("makeEveGeoShape"); - - REveElement::BuildRenderData(); - egps->FillRenderData(*fRenderData); } //////////////////////////////////////////////////////////////////////////////// diff --git a/graf3d/eve7/src/REveManager.cxx b/graf3d/eve7/src/REveManager.cxx index a8dd8830f08ff..3bbc903bfcec7 100644 --- a/graf3d/eve7/src/REveManager.cxx +++ b/graf3d/eve7/src/REveManager.cxx @@ -15,9 +15,9 @@ #include #include #include +#include #include #include -#include #include #include @@ -51,7 +51,20 @@ namespace REX = ROOT::Experimental; REveManager *REX::gEve = nullptr; +struct MIR_TL_Data_t +{ + std::vector addedWatch; + std::vector removedWatch; + + void reset() { + addedWatch.clear(); + removedWatch.clear(); + } +}; + thread_local std::vector gEveLogEntries; +thread_local MIR_TL_Data_t gMIRData; + /** \class REveManager \ingroup REve Central application manager for Eve. @@ -140,7 +153,7 @@ REveManager::REveManager() // !!! AMT increase threshold to enable color pick on client TColor::SetColorThreshold(0.1); - fWebWindow = RWebWindow::Create(); + fWebWindow = ROOT::RWebWindow::Create(); fWebWindow->UseServerThreads(); fWebWindow->SetDefaultPage("file:rootui5sys/eve7/index.html"); @@ -160,7 +173,7 @@ REveManager::REveManager() [this](unsigned connid) { WindowDisconnect(connid); }); fWebWindow->SetGeometry(900, 700); // configure predefined window geometry fWebWindow->SetConnLimit(100); // maximal number of connections - fWebWindow->SetMaxQueueLength(30); // number of allowed entries in the window queue + fWebWindow->SetMaxQueueLength(1000); // number of allowed entries in the window queue fMIRExecThread = std::thread{[this] { MIRExecThread(); }}; @@ -731,6 +744,8 @@ void REveManager::WindowConnect(unsigned connid) for (auto &c : fScenes->RefChildren()) { REveScene *scene = dynamic_cast(c); + if (!scene->GetMandatory()) + continue; scene->AddSubscriber(std::make_unique(connid, fWebWindow)); printf("\nEVEMNG ............. streaming scene %s [%s]\n", scene->GetCTitle(), scene->GetCName()); @@ -758,10 +773,6 @@ void REveManager::WindowConnect(unsigned connid) void REveManager::WindowDisconnect(unsigned connid) { std::unique_lock lock(fServerState.fMutex); - while (fServerState.fVal != ServerState::Waiting) - { - fServerState.fCV.wait(lock); - } auto conn = fConnList.end(); for (auto i = fConnList.begin(); i != fConnList.end(); ++i) { if (i->fId == connid) { @@ -782,6 +793,13 @@ void REveManager::WindowDisconnect(unsigned connid) fWorld->RemoveSubscriber(connid); } + // User case: someone can close browser tab as clients are updateding + // note if scene changes are in progess the new serverstate will be changes after finish those + if (fServerState.fVal == ServerState::UpdatingClients && ClientConnectionsFree()) + { + fServerState.fVal = ServerState::Waiting; + } + fServerStatus.fTLastDisconnect = std::time(nullptr); ++fServerStatus.fNDisconnects; @@ -809,9 +827,11 @@ void REveManager::WindowData(unsigned connid, const std::string &arg) R__LOG_ERROR(REveLog()) << "Internal error - no connection with id " << connid << " found"; return; } - // client status data + + if (arg.compare("__REveDoneChanges") == 0) { + // client status data std::unique_lock lock(fServerState.fMutex); for (auto &conn : fConnList) { @@ -821,17 +841,18 @@ void REveManager::WindowData(unsigned connid, const std::string &arg) } } - if (ClientConnectionsFree()) { + if (fServerState.fVal == ServerState::UpdatingClients && ClientConnectionsFree()) { fServerState.fVal = ServerState::Waiting; fServerState.fCV.notify_all(); } return; } - else if (arg.compare( 0, 10, "FILEDIALOG") == 0) + else if (ROOT::RWebWindow::IsFileDialogMessage(arg)) { - RFileDialog::Embedded(fWebWindow, arg); - return; + // file dialog + ROOT::RWebWindow::EmbedFileDialog(fWebWindow, connid, arg); + return; } nlohmann::json cj = nlohmann::json::parse(arg); @@ -842,16 +863,20 @@ void REveManager::WindowData(unsigned connid, const std::string &arg) int id = cj["fElementId"]; std::string ctype = cj["class"]; - ScheduleMIR(cmd, id, ctype); + ScheduleMIR(cmd, id, ctype, connid); } // //____________________________________________________________________ -void REveManager::ScheduleMIR(const std::string &cmd, ElementId_t id, const std::string& ctype) +void REveManager::ScheduleMIR(const std::string &cmd, ElementId_t id, const std::string& ctype, unsigned connid) { std::unique_lock lock(fServerState.fMutex); fServerStatus.fTLastMir = std::time(nullptr); - fMIRqueue.push(std::shared_ptr(new MIR(cmd, id, ctype))); + fMIRqueue.push(std::shared_ptr(new MIR(cmd, id, ctype, connid))); + + if (fMIRqueue.size() > 5) + std::cout << "Warning, REveManager::ScheduleMIR(). queue size " << fMIRqueue.size() << std::endl; + if (fServerState.fVal == ServerState::Waiting) fServerState.fCV.notify_all(); } @@ -862,21 +887,6 @@ void REveManager::ExecuteMIR(std::shared_ptr mir) { static const REveException eh("REveManager::ExecuteMIR "); - class ChangeSentry { - public: - ChangeSentry() - { - gEve->GetWorld()->BeginAcceptingChanges(); - gEve->GetScenes()->AcceptChanges(true); - } - ~ChangeSentry() - { - gEve->GetScenes()->AcceptChanges(false); - gEve->GetWorld()->EndAcceptingChanges(); - } - }; - ChangeSentry cs; - //if (gDebug > 0) ::Info("REveManager::ExecuteCommand", "MIR cmd %s", mir->fCmd.c_str()); @@ -934,17 +944,36 @@ void REveManager::ExecuteMIR(std::shared_ptr mir) } } -// -//____________________________________________________________________ -void REveManager::PublishChanges() +// Write scene change into scenes's internal json member +void REveManager::StreamSceneChangesToJson() { + if (fWorld->IsChanged()) fWorld->StreamRepresentationChanges(); + + for (auto &el : fScenes->RefChildren()) + { + REveScene* s = dynamic_cast(el); + if (s->IsChanged()) s->StreamRepresentationChanges(); + } +} + +// Send json and binary data to scene's connections +void REveManager::SendSceneChanges() +{ + // send begin message nlohmann::json jobj = {}; jobj["content"] = "BeginChanges"; fWebWindow->Send(0, jobj.dump()); - // Process changes in scenes. - fWorld->ProcessChanges(); - fScenes->ProcessSceneChanges(); + // send the change json + fWorld->SendChangesToSubscribers(); + + for (auto &el : fScenes->RefChildren()) + { + REveScene* s = dynamic_cast(el); + s->SendChangesToSubscribers(); + } + + // send end changes message and log messages jobj["content"] = "EndChanges"; if (!gEveLogEntries.empty()) { @@ -956,7 +985,7 @@ void REveManager::PublishChanges() std::stringstream strm; for (auto entry : gEveLogEntries) { nlohmann::json item = {}; - item["lvl"] = entry.fLevel; + item["lvl"] = entry.fLevel; int cappedLevel = std::min(static_cast(entry.fLevel), numLevels - 1); strm << "Server " << sTag[cappedLevel] << ":"; @@ -983,29 +1012,82 @@ void REveManager::MIRExecThread() while (true) { std::unique_lock lock(fServerState.fMutex); - abcLabel: - if (fMIRqueue.empty()) + underlock: + if (fMIRqueue.empty() || fServerState.fVal == ServerState::UpdatingScenes) { fServerState.fCV.wait(lock); - goto abcLabel; + goto underlock; } - else if (fServerState.fVal == ServerState::Waiting) + else { + // set server state and update the queue under lock + // + fServerState.fVal = ServerState::UpdatingScenes; std::shared_ptr mir = fMIRqueue.front(); + + // reset local thread related data + gMIRData.reset(); fMIRqueue.pop(); - fServerState.fVal = ServerState::UpdatingScenes; lock.unlock(); + // allow scenes to accept changes in the element + gEve->GetWorld()->BeginAcceptingChanges(); + gEve->GetScenes()->AcceptChanges(true); + ExecuteMIR(mir); + // disable scene's element changing + gEve->GetScenes()->AcceptChanges(false); + gEve->GetWorld()->EndAcceptingChanges(); + + StreamSceneChangesToJson(); + + // send changes (need to access client connection list) and set the state under lock + // lock.lock(); + + // disconnect requested scene from clients + for (auto &scene : gMIRData.removedWatch) + scene->RemoveSubscriber(mir->fConnId); + + + // connect and stream scenes to new clients + for (auto &scene : gMIRData.addedWatch) { + scene->AddSubscriber(std::make_unique(mir->fConnId, fWebWindow)); + scene->StreamElements(); + Send(mir->fConnId, scene->fOutputJson); + if (scene->fTotalBinarySize > 0) + SendBinary(mir->fConnId, &scene->fOutputBinary[0], scene->fTotalBinarySize); + } + + SendSceneChanges(); + fServerState.fVal = fConnList.empty() ? ServerState::Waiting : ServerState::UpdatingClients; - PublishChanges(); + fServerState.fCV.notify_all(); } } } +//____________________________________________________________________ +void REveManager::DisconnectEveViewer(REveViewer* view) +{ + for (auto &c : view->RefChildren()) { + REveSceneInfo *sinfo = dynamic_cast(c); + std::cout << "Disconnect scee " << sinfo->GetScene()->GetName(); + gMIRData.removedWatch.push_back(sinfo->GetScene()); + } +} +//____________________________________________________________________ +void REveManager::ConnectEveViewer(REveViewer* view) +{ + view->StampObjProps(); + for (auto &c : view->RefChildren()) { + REveSceneInfo *sinfo = dynamic_cast(c); + std::cout << "Connect scene " << sinfo->GetScene()->GetName(); + gMIRData.addedWatch.push_back(sinfo->GetScene()); + } +} //____________________________________________________________________ void REveManager::Send(unsigned connid, const std::string &data) @@ -1028,23 +1110,13 @@ bool REveManager::ClientConnectionsFree() const return true; } -void REveManager::SceneSubscriberProcessingChanges(unsigned cinnId) -{ - for (auto &conn : fConnList) { - if (conn.fId == cinnId) - { - conn.fState = Conn::WaitingResponse; - break; - } - } -} - +// called from REveScene::SendChangesToSubscribers void REveManager::SceneSubscriberWaitingResponse(unsigned cinnId) { for (auto &conn : fConnList) { if (conn.fId == cinnId) { - conn.fState = Conn::Processing; + conn.fState = Conn::WaitingResponse; break; } } @@ -1070,9 +1142,10 @@ void REveManager::Show(const RWebDisplayArgs &args) //____________________________________________________________________ void REveManager::BeginChange() { + // set server state and tag scenes to begin accepting changees { std::unique_lock lock(fServerState.fMutex); - while (fServerState.fVal != ServerState::Waiting) { + while (fServerState.fVal == ServerState::UpdatingScenes) { fServerState.fCV.wait(lock); } fServerState.fVal = ServerState::UpdatingScenes; @@ -1084,12 +1157,15 @@ void REveManager::BeginChange() //____________________________________________________________________ void REveManager::EndChange() { + // tag scene to disable accepting chages, write the change json GetScenes()->AcceptChanges(false); GetWorld()->EndAcceptingChanges(); - PublishChanges(); + StreamSceneChangesToJson(); + // set new server state under lock std::unique_lock lock(fServerState.fMutex); + SendSceneChanges(); fServerState.fVal = fConnList.empty() ? ServerState::Waiting : ServerState::UpdatingClients; fServerState.fCV.notify_all(); } diff --git a/graf3d/eve7/src/REvePointSet.cxx b/graf3d/eve7/src/REvePointSet.cxx index 6b8413ca9e014..b5e9c175f7786 100644 --- a/graf3d/eve7/src/REvePointSet.cxx +++ b/graf3d/eve7/src/REvePointSet.cxx @@ -225,6 +225,7 @@ Int_t REvePointSet::WriteCoreJson(nlohmann::json& j, Int_t rnr_offset) } j["fMarkerSize"] = GetMarkerSize(); j["fMarkerColor"] = GetMarkerColor(); + j["fMarkerStyle"] = GetMarkerStyle(); j["fSecondarySelect"] = fAlwaysSecSelect; return ret; @@ -574,6 +575,10 @@ void REvePointSetProjected::UpdateProjection() Int_t n = ps.GetSize(); Reset(n); fSize = n; + + if (n == 0) + return; + const Float_t *o = & ps.RefPoint(0).fX; Float_t *p = & fPoints[0].fX; for (Int_t i = 0; i < n; ++i, o+=3, p+=3) diff --git a/graf3d/eve7/src/REveScene.cxx b/graf3d/eve7/src/REveScene.cxx index aa7dcd7515ed6..e90a180e86a90 100644 --- a/graf3d/eve7/src/REveScene.cxx +++ b/graf3d/eve7/src/REveScene.cxx @@ -54,7 +54,14 @@ REveScene::~REveScene() REX::gEve->GetViewers()->SceneDestructing(this); REX::gEve->GetScenes()->RemoveElement(this); } +//------------------------------------------------------------------------------ + +int REveScene::WriteCoreJson(nlohmann::json &j, Int_t rnr_offset) +{ + j["Mandatory"] = fMandatory; + return REveElement::WriteCoreJson(j, rnr_offset); +} //------------------------------------------------------------------------------ void REveScene::AddSubscriber(std::unique_ptr &&sub) @@ -70,8 +77,6 @@ void REveScene::AddSubscriber(std::unique_ptr &&sub) void REveScene::RemoveSubscriber(unsigned id) { - assert(fAcceptingChanges == kFALSE); - auto pred = [&](std::unique_ptr &client) { return client->fId == id; }; @@ -99,9 +104,11 @@ void REveScene::BeginAcceptingChanges() if (HasSubscribers()) { fAcceptingChanges = kTRUE; + /* for (auto &&client : fSubscribers) { REX::gEve->SceneSubscriberProcessingChanges(client->fId); } + */ } } @@ -124,15 +131,6 @@ void REveScene::EndAcceptingChanges() fAcceptingChanges = kFALSE; } -void REveScene::ProcessChanges() -{ - if (IsChanged()) - { - StreamRepresentationChanges(); - SendChangesToSubscribers(); - } -} - void REveScene::StreamElements() { fOutputJson.clear(); @@ -235,9 +233,6 @@ void REveScene::StreamJsonRecurse(REveElement *el, nlohmann::json &jarr) void REveScene::StreamRepresentationChanges() { - fOutputJson.clear(); - fOutputBinary.clear(); - fElsWithBinaryData.clear(); fTotalBinarySize = 0; @@ -327,9 +322,11 @@ void REveScene::StreamRepresentationChanges() void REveScene::SendChangesToSubscribers() { for (auto && client : fSubscribers) { - if (gDebug > 0) - printf(" sending json, len = %d --> to conn_id = %d\n", (int) fOutputJson.size(), client->fId); - client->fWebWindow->Send(client->fId, fOutputJson); + if (fOutputJson.size()) { + if (gDebug > 0) + printf(" sending json, len = %d --> to conn_id = %d\n", (int) fOutputJson.size(), client->fId); + client->fWebWindow->Send(client->fId, fOutputJson); + } if (fTotalBinarySize) { if (gDebug > 0) printf(" sending binary, len = %d --> to conn_id = %d\n", fTotalBinarySize, client->fId); @@ -337,6 +334,9 @@ void REveScene::SendChangesToSubscribers() } REX::gEve->SceneSubscriberWaitingResponse(client->fId); } + fOutputJson.clear(); + fOutputBinary.clear(); + fTotalBinarySize = 0; } Bool_t REveScene::IsChanged() const @@ -564,21 +564,3 @@ bool REveSceneList::AnyChanges() const } return false; } - - -//////////////////////////////////////////////////////////////////////////////// -// -// Send an update of element representations -// -//////////////////////////////////////////////////////////////////////////////// - -void REveSceneList::ProcessSceneChanges() -{ - if (gDebug > 0) - ::Info("REveSceneList::ProcessSceneChanges","processing"); - - for (auto &el : fChildren) - { - ((REveScene*) el)->ProcessChanges(); - } -} diff --git a/graf3d/eve7/src/REveViewer.cxx b/graf3d/eve7/src/REveViewer.cxx index 8bb0fb3882cba..0c66b891b5d8d 100644 --- a/graf3d/eve7/src/REveViewer.cxx +++ b/graf3d/eve7/src/REveViewer.cxx @@ -101,6 +101,22 @@ void REveViewer::RemoveElementsLocal() List of Viewers providing common operations on REveViewer collections. */ +//////////////////////////////////////////////////////////////////////////////// +// +void REveViewer::SetAxesType(int at) +{ + fAxesType = (EAxesType)at; + StampObjProps(); +} + +//////////////////////////////////////////////////////////////////////////////// +// +void REveViewer::SetBlackBackground(bool x) +{ + fBlackBackground = x; + StampObjProps(); +} + //////////////////////////////////////////////////////////////////////////////// /// Stream Camera Info. /// Virtual from REveElement. @@ -113,9 +129,42 @@ int REveViewer::WriteCoreJson(nlohmann::json &j, Int_t rnr_offset) case kCameraOrthoXOY: ct = "OrthoXOY"; break; } j["CameraType"] = ct; + j["Mandatory"] = fMandatory; + j["AxesType"] = fAxesType; + j["BlackBg"] = fBlackBackground; + + j["UT_PostStream"] = "UT_EveViewerUpdate"; + return REveElement::WriteCoreJson(j, rnr_offset); } +//////////////////////////////////////////////////////////////////////////////// +/// Function called from MIR when user closes one of the viewer window. +// Client id stored in thread local data +void REveViewer::DisconnectClient() +{ + gEve->DisconnectEveViewer(this); +} +//////////////////////////////////////////////////////////////////////////////// +/// Function called from MIR when user wants to stream unsubscribed view. +// Client id stored in thread local data +void REveViewer::ConnectClient() +{ + gEve->ConnectEveViewer(this); +} + +//////////////////////////////////////////////////////////////////////////////// +/// +// Set Flag if this viewer is presented on connect +void REveViewer::SetMandatory(bool x) +{ + fMandatory = x; + for (auto &c : RefChildren()) { + REveSceneInfo *sinfo = dynamic_cast(c); + sinfo->GetScene()->GetScene()->SetMandatory(fMandatory); + } +} + //////////////////////////////////////////////////////////////////////////////// REveViewerList::REveViewerList(const std::string &n, const std::string &t) : diff --git a/graf3d/g3d/inc/TAxis3D.h b/graf3d/g3d/inc/TAxis3D.h index 2b368ca0aacd8..d2d9db8d34104 100644 --- a/graf3d/g3d/inc/TAxis3D.h +++ b/graf3d/g3d/inc/TAxis3D.h @@ -42,7 +42,7 @@ class TAxis3D : public TNamed { Bool_t fZoomMode; // Zoom mode for the entire parent TPad Bool_t fStickyZoom; // StickyZoom mode: zoom will not be disabled after zooming attempt if true - virtual void Copy(TObject &hnew) const; + void Copy(TObject &hnew) const override; void InitSet(); Bool_t SwitchZoom(); @@ -50,12 +50,12 @@ class TAxis3D : public TNamed { TAxis3D(); TAxis3D(Option_t *option); TAxis3D(const TAxis3D &axis); - virtual ~TAxis3D(){} + ~TAxis3D() override{} - virtual void Browse(TBrowser *b); + void Browse(TBrowser *b) override; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; Bool_t & StickyZoom(){return fStickyZoom;} Bool_t & Zoom(){return fZoomMode;} @@ -74,18 +74,18 @@ class TAxis3D : public TNamed { virtual void GetLowEdge(Axis_t *edge) {fAxis[0].GetLowEdge(edge);} - virtual char *GetObjectInfo(Int_t px, Int_t py) const; + char *GetObjectInfo(Int_t px, Int_t py) const override; - Option_t *GetOption() const {return fOption.Data();} + Option_t *GetOption() const override {return fOption.Data();} virtual TAxis *GetXaxis() {return &fAxis[0];} virtual TAxis *GetYaxis() {return &fAxis[1];} virtual TAxis *GetZaxis() {return &fAxis[2];} - virtual Bool_t IsFolder() const { return kTRUE;} - virtual void Paint(Option_t *option=""); + Bool_t IsFolder() const override { return kTRUE;} + void Paint(Option_t *option="") override; void PaintAxis(TGaxis *axis, Float_t ang); static Double_t *PixeltoXYZ(Double_t px, Double_t py, Double_t *point3D, TView *view = nullptr); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; virtual void SetAxisColor(Color_t color=1, Option_t *axis="*"); // *MENU* virtual void SetAxisRange(Double_t xmin, Double_t xmax, Option_t *axis="*"); @@ -104,9 +104,9 @@ class TAxis3D : public TNamed { virtual void SetZTitle(const char *title) {fAxis[2].SetTitle(title);} // *MENU* static TAxis3D *ToggleRulers(TVirtualPad *pad = nullptr); static TAxis3D *ToggleZoom(TVirtualPad *pad = nullptr); - void UseCurrentStyle(); + void UseCurrentStyle() override; - ClassDef(TAxis3D,1) //3-D ruler painting class + ClassDefOverride(TAxis3D,1) //3-D ruler painting class }; diff --git a/graf3d/g3d/inc/TBRIK.h b/graf3d/g3d/inc/TBRIK.h index 719470662419d..c9c4b9151cc38 100644 --- a/graf3d/g3d/inc/TBRIK.h +++ b/graf3d/g3d/inc/TBRIK.h @@ -30,20 +30,20 @@ class TBRIK : public TShape { Float_t fDy; // half length in y Float_t fDz; // half length in z - virtual void SetPoints(Double_t * points) const; + void SetPoints(Double_t * points) const override; public: TBRIK(); TBRIK(const char *name, const char *title, const char *material, Float_t dx, Float_t dy, Float_t dz); - virtual ~TBRIK(); + ~TBRIK() override; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections) const override; Float_t GetDx() const {return fDx;} Float_t GetDy() const {return fDy;} Float_t GetDz() const {return fDz;} - virtual void Sizeof3D() const; + void Sizeof3D() const override; - ClassDef(TBRIK,1) //TBRIK shape + ClassDefOverride(TBRIK,1) //TBRIK shape }; #endif diff --git a/graf3d/g3d/inc/TCONE.h b/graf3d/g3d/inc/TCONE.h index e0cfb2c6bfc7a..815bee5b82438 100644 --- a/graf3d/g3d/inc/TCONE.h +++ b/graf3d/g3d/inc/TCONE.h @@ -31,18 +31,18 @@ class TCONE : public TTUBE { Float_t fRmin2; // inside radius at the high z limit Float_t fRmax2; // outside radius at the high z limit - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TCONE(); TCONE(const char *name, const char *title, const char *material, Float_t dz, Float_t rmin1, Float_t rmax1, Float_t rmin2, Float_t rmax2); TCONE(const char *name, const char *title, const char *material, Float_t dz, Float_t rmax1, Float_t rmax2 =0); - virtual ~TCONE(); + ~TCONE() override; Float_t GetRmin2() const {return fRmin2;} Float_t GetRmax2() const {return fRmax2;} - ClassDef(TCONE,1) //CONE shape + ClassDefOverride(TCONE,1) //CONE shape }; #endif diff --git a/graf3d/g3d/inc/TCONS.h b/graf3d/g3d/inc/TCONS.h index daae2d87dff96..312dc332b1b5a 100644 --- a/graf3d/g3d/inc/TCONS.h +++ b/graf3d/g3d/inc/TCONS.h @@ -30,19 +30,19 @@ class TCONS : public TTUBS { Float_t fRmin2; // inside radius at the high z limit Float_t fRmax2; // outside radius at the high z limit - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TCONS(); TCONS(const char *name, const char *title, const char *material, Float_t dz, Float_t rmin1, Float_t rmax1, Float_t rmin2, Float_t rmax2, Float_t phi1, Float_t phi2); TCONS(const char *name, const char *title, const char *material, Float_t rmax1, Float_t dz , Float_t phi1, Float_t phi2, Float_t rmax2 = 0); - virtual ~TCONS(); + ~TCONS() override; virtual Float_t GetRmin2() const {return fRmin2;} virtual Float_t GetRmax2() const {return fRmax2;} - ClassDef(TCONS,1) //CONS shape + ClassDefOverride(TCONS,1) //CONS shape }; #endif diff --git a/graf3d/g3d/inc/TCTUB.h b/graf3d/g3d/inc/TCTUB.h index 28855c7699d94..81fb6e96b07ce 100644 --- a/graf3d/g3d/inc/TCTUB.h +++ b/graf3d/g3d/inc/TCTUB.h @@ -32,7 +32,7 @@ class TCTUB : public TTUBS { Float_t fCosLow[3]; // dir cosinus of surface cutting tube at low z Float_t fCosHigh[3]; // dir cosinus of surface cutting tube at high z - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TCTUB(); TCTUB(const char *name, const char *title, const char *material, Float_t rmin, @@ -42,9 +42,9 @@ class TCTUB : public TTUBS { TCTUB(const char *name, const char *title, const char *material, Float_t rmin, Float_t rmax, Float_t dz, Float_t phi1, Float_t phi2, Float_t *lowNormal, Float_t *highNormal); - virtual ~TCTUB(); + ~TCTUB() override; - ClassDef(TCTUB,2) //The Cut Tube shape + ClassDefOverride(TCTUB,2) //The Cut Tube shape }; #endif diff --git a/graf3d/g3d/inc/TELTU.h b/graf3d/g3d/inc/TELTU.h index 2607161d3cbbc..b3fe32ded8782 100644 --- a/graf3d/g3d/inc/TELTU.h +++ b/graf3d/g3d/inc/TELTU.h @@ -33,9 +33,9 @@ class TELTU : public TTUBE { public: TELTU(); TELTU(const char *name, const char *title, const char *material, Float_t rx, Float_t ry,Float_t dz); - virtual ~TELTU(); + ~TELTU() override; - ClassDef(TELTU,1) //ELTU shape + ClassDefOverride(TELTU,1) //ELTU shape }; #endif diff --git a/graf3d/g3d/inc/TGTRA.h b/graf3d/g3d/inc/TGTRA.h index f9b3187282fcf..b035f2c93957a 100644 --- a/graf3d/g3d/inc/TGTRA.h +++ b/graf3d/g3d/inc/TGTRA.h @@ -37,13 +37,13 @@ class TGTRA : public TBRIK { Float_t fTl2; // half length in x at high z and y high edge Float_t fAlpha2; // angle w.r.t. the y axis - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TGTRA(); TGTRA(const char *name, const char *title, const char *material, Float_t dz, Float_t theta, Float_t phi, Float_t twist, Float_t h1, Float_t bl1, Float_t tl1, Float_t alpha1, Float_t h2, Float_t bl2, Float_t tl2, Float_t alpha2); - virtual ~TGTRA(); + ~TGTRA() override; Float_t GetTwist() const {return fTwist;} Float_t GetH1() const {return fH1;} @@ -55,7 +55,7 @@ class TGTRA : public TBRIK { Float_t GetTl2() const {return fTl2;} Float_t GetAlpha2() const {return fAlpha2;} - ClassDef(TGTRA,1) //GTRA shape + ClassDefOverride(TGTRA,1) //GTRA shape }; #endif diff --git a/graf3d/g3d/inc/TGeometry.h b/graf3d/g3d/inc/TGeometry.h index aa77e30bcd98b..9f72f5bafb027 100644 --- a/graf3d/g3d/inc/TGeometry.h +++ b/graf3d/g3d/inc/TGeometry.h @@ -64,12 +64,12 @@ class TGeometry : public TNamed { public: TGeometry(); TGeometry(const char *name, const char *title); - virtual ~TGeometry(); - virtual void Browse(TBrowser *b); + ~TGeometry() override; + void Browse(TBrowser *b) override; virtual void cd(const char *path=nullptr); - virtual void Draw(Option_t *option=""); - virtual TObject *FindObject(const char *name) const; - virtual TObject *FindObject(const TObject *obj) const; + void Draw(Option_t *option="") override; + TObject *FindObject(const char *name) const override; + TObject *FindObject(const TObject *obj) const override; Float_t GetBomb() const {return fBomb;} Int_t GeomLevel() const {return fGeomLevel;} THashList *GetListOfShapes() const {return fShapes;} @@ -88,17 +88,17 @@ class TGeometry : public TNamed { TRotMatrix *GetCurrentPosition(Double_t *x,Double_t *y,Double_t *z) const; TRotMatrix *GetCurrentPosition(Float_t *x,Float_t *y,Float_t *z) const; Bool_t GetCurrentReflection() const; - Bool_t IsFolder() const {return kTRUE;} + Bool_t IsFolder() const override {return kTRUE;} virtual void Local2Master(Double_t *local, Double_t *master); virtual void Local2Master(Float_t *local, Float_t *master); - virtual void ls(Option_t *option="rsn2") const; + void ls(Option_t *option="rsn2") const override; virtual void Master2Local(Double_t *master, Double_t *local); virtual void Master2Local(Float_t *master, Float_t *local); virtual void Node(const char *name, const char *title, const char *shapename, Double_t x=0, Double_t y=0, Double_t z=0 , const char *matrixname="", Option_t *option=""); virtual Int_t PushLevel(){return fGeomLevel++;} virtual Int_t PopLevel(){return fGeomLevel>0?fGeomLevel--:0;} - virtual void RecursiveRemove(TObject *obj); + void RecursiveRemove(TObject *obj) override; virtual void SetBomb(Float_t bomb=1.4) {fBomb = bomb;} virtual void SetCurrentNode(TNode *node) {fCurrentNode = node;} virtual void SetGeomLevel(Int_t level=0){fGeomLevel=level;} @@ -116,7 +116,7 @@ class TGeometry : public TNamed { Double_t x, Double_t y, Double_t z, Double_t *matrix, Double_t *dxnew, Double_t *rmatnew); - ClassDef(TGeometry,2) //Structure for Matrices, Shapes and Nodes + ClassDefOverride(TGeometry,2) //Structure for Matrices, Shapes and Nodes }; diff --git a/graf3d/g3d/inc/THYPE.h b/graf3d/g3d/inc/THYPE.h index e8b815db74150..ab97508d9b646 100644 --- a/graf3d/g3d/inc/THYPE.h +++ b/graf3d/g3d/inc/THYPE.h @@ -34,11 +34,11 @@ class THYPE : public TTUBE { THYPE(); THYPE(const char *name, const char *title, const char *material, Float_t rmin, Float_t rmax, Float_t dz, Float_t phi); - virtual ~THYPE(); + ~THYPE() override; virtual Float_t GetPhi() const {return fPhi;} - ClassDef(THYPE,1) //HYPE shape + ClassDefOverride(THYPE,1) //HYPE shape }; #endif diff --git a/graf3d/g3d/inc/THelix.h b/graf3d/g3d/inc/THelix.h index f2395e3dd8061..50a613c3b9b93 100644 --- a/graf3d/g3d/inc/THelix.h +++ b/graf3d/g3d/inc/THelix.h @@ -50,14 +50,14 @@ class THelix : public TPolyLine3D { Double_t const* range=nullptr, EHelixRangeType rtype=kHelixZ, Double_t const* axis=nullptr); THelix(const THelix &helix); - virtual ~THelix(); + ~THelix() override; - virtual void Copy(TObject &helix) const; - virtual void Draw(Option_t *option=""); - Option_t *GetOption() const {return fOption.Data();} - virtual void Print(Option_t *option="") const; - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); - virtual void SetOption(Option_t *option="") {fOption = option;} + void Copy(TObject &helix) const override; + void Draw(Option_t *option="") override; + Option_t *GetOption() const override {return fOption.Data();} + void Print(Option_t *option="") const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SetOption(Option_t *option="") override {fOption = option;} virtual void SetAxis(Double_t const* axis); //Define new axis virtual void SetAxis(Double_t x, Double_t y, Double_t z); virtual void SetRange(Double_t * range, EHelixRangeType rtype=kHelixZ); @@ -66,7 +66,7 @@ class THelix : public TPolyLine3D { Double_t const* range=nullptr, EHelixRangeType type=kUnchanged, Double_t const* axis=nullptr); - ClassDef(THelix,2) //A Helix drawn as a PolyLine3D + ClassDefOverride(THelix,2) //A Helix drawn as a PolyLine3D }; #endif diff --git a/graf3d/g3d/inc/TMarker3DBox.h b/graf3d/g3d/inc/TMarker3DBox.h index 49d6a669fbee8..57c9b81f75776 100644 --- a/graf3d/g3d/inc/TMarker3DBox.h +++ b/graf3d/g3d/inc/TMarker3DBox.h @@ -58,25 +58,25 @@ class TMarker3DBox : public TObject, public TAttLine, public TAttFill, TMarker3DBox(Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dy, Float_t dz, Float_t theta, Float_t phi); - virtual ~TMarker3DBox(); + ~TMarker3DBox() override; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; TObject *GetRefObject() const {return fRefObject;} virtual void GetDirection(Float_t &theta, Float_t &phi) const {theta = fTheta; phi = fPhi;} virtual void GetPosition(Float_t &x, Float_t &y, Float_t &z) const {x=fX; y=fY, z=fZ;} virtual void GetSize(Float_t &dx, Float_t &dy, Float_t &dz) const {dx=fDx; dy=fDy; dz=fDz;} - virtual void Paint(Option_t *option); + void Paint(Option_t *option) override; static void PaintH3(TH1 *h, Option_t *option); - virtual void SavePrimitive(std::ostream &out, Option_t *option = ""); + void SavePrimitive(std::ostream &out, Option_t *option = "") override; virtual void SetPoints(Double_t *buff) const; virtual void SetDirection(Float_t theta, Float_t phi); virtual void SetPosition(Float_t x, Float_t y, Float_t z); virtual void SetSize(Float_t dx, Float_t dy, Float_t dz); virtual void SetRefObject(TObject *obj = nullptr) {fRefObject = obj;} - ClassDef(TMarker3DBox,2) //A special 3-D marker designed for event display + ClassDefOverride(TMarker3DBox,2) //A special 3-D marker designed for event display }; #endif diff --git a/graf3d/g3d/inc/TMaterial.h b/graf3d/g3d/inc/TMaterial.h index 700d496c7965d..ddb38c2c29063 100644 --- a/graf3d/g3d/inc/TMaterial.h +++ b/graf3d/g3d/inc/TMaterial.h @@ -38,7 +38,7 @@ class TMaterial : public TNamed, public TAttFill { TMaterial(); TMaterial(const char *name, const char *title, Float_t a, Float_t z, Float_t density); TMaterial(const char *name, const char *title, Float_t a, Float_t z, Float_t density, Float_t radl, Float_t inter); - virtual ~TMaterial(); + ~TMaterial() override; virtual Int_t GetNumber() const {return fNumber;} virtual Float_t GetA() const {return fA;} virtual Float_t GetZ() const {return fZ;} @@ -46,7 +46,7 @@ class TMaterial : public TNamed, public TAttFill { virtual Float_t GetRadLength() const {return fRadLength;} virtual Float_t GetInterLength() const {return fInterLength;} - ClassDef(TMaterial,3) //Materials used in the Geometry Shapes + ClassDefOverride(TMaterial,3) //Materials used in the Geometry Shapes }; #endif diff --git a/graf3d/g3d/inc/TMixture.h b/graf3d/g3d/inc/TMixture.h index ce0f9aefeede5..3179a1f2eec7e 100644 --- a/graf3d/g3d/inc/TMixture.h +++ b/graf3d/g3d/inc/TMixture.h @@ -34,7 +34,7 @@ class TMixture : public TMaterial { public: TMixture(); TMixture(const char *name, const char *title, Int_t nmixt); - virtual ~TMixture(); + ~TMixture() override; virtual void DefineElement(Int_t n, Float_t a, Float_t z, Float_t w); Int_t GetNmixt() const {return fNmixt;} @@ -42,7 +42,7 @@ class TMixture : public TMaterial { Float_t *GetZmixt() const {return fZmixt;} Float_t *GetWmixt() const {return fWmixt;} - ClassDef(TMixture,1) //Mixtures used in the Geometry Shapes + ClassDefOverride(TMixture,1) //Mixtures used in the Geometry Shapes }; #endif diff --git a/graf3d/g3d/inc/TNode.h b/graf3d/g3d/inc/TNode.h index fd62c833c5ab0..23791bd84d530 100644 --- a/graf3d/g3d/inc/TNode.h +++ b/graf3d/g3d/inc/TNode.h @@ -54,19 +54,19 @@ class TNode : public TNamed , public TAttLine, public TAttFill, public TAtt3D { const char *matrixname="", Option_t *option=""); TNode(const char *name, const char *title, TShape *shape, Double_t x=0, Double_t y=0, Double_t z=0, TRotMatrix *matrix=nullptr, Option_t *option=""); - virtual ~TNode(); - virtual void Browse(TBrowser *b); + ~TNode() override; + void Browse(TBrowser *b) override; virtual void BuildListOfNodes(); virtual void cd(const char *path=nullptr); // *MENU* - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void Draw(Option_t *option=""); // *MENU* + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *option="") override; // *MENU* virtual void DrawOnly(Option_t *option=""); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; TList *GetListOfNodes() const {return fNodes;} virtual TRotMatrix *GetMatrix() const {return fMatrix;} virtual TNode *GetNode(const char *name) const; - virtual char *GetObjectInfo(Int_t px, Int_t py) const; - const Option_t *GetOption() const { return fOption.Data();} + char *GetObjectInfo(Int_t px, Int_t py) const override; + const Option_t *GetOption() const override { return fOption.Data();} virtual TNode *GetParent() const {return fParent;} TShape *GetShape() const {return fShape;} Int_t GetVisibility() const {return fVisibility;} @@ -74,27 +74,27 @@ class TNode : public TNamed , public TAttLine, public TAttFill, public TAtt3D { virtual Double_t GetY() const {return fY;} virtual Double_t GetZ() const {return fZ;} virtual void ImportShapeAttributes(); - Bool_t IsFolder() const; + Bool_t IsFolder() const override; virtual void Local2Master(const Double_t *local, Double_t *master); virtual void Local2Master(const Float_t *local, Float_t *master); - virtual void ls(Option_t *option="2") const; // *MENU* + void ls(Option_t *option="2") const override; // *MENU* virtual void Master2Local(const Double_t *master, Double_t *local); virtual void Master2Local(const Float_t *master, Float_t *local); - virtual void Paint(Option_t *option=""); - virtual void RecursiveRemove(TObject *obj); + void Paint(Option_t *option="") override; + void RecursiveRemove(TObject *obj) override; virtual void SetMatrix(TRotMatrix *matrix=nullptr) {fMatrix = matrix;} - virtual void SetName(const char *name); + void SetName(const char *name) override; virtual void SetParent(TNode *parent); - virtual void SetNameTitle(const char *name, const char *title); + void SetNameTitle(const char *name, const char *title) override; virtual void SetPosition( Double_t x=0, Double_t y=0, Double_t z=0) {fX=x; fY=y; fZ=z;} virtual void SetVisibility(Int_t vis=1); // *MENU* - virtual void Sizeof3D() const; + void Sizeof3D() const override; virtual void UpdateMatrix(); virtual void UpdateTempMatrix(const Double_t *dx1,const Double_t *rmat1, Double_t x, Double_t y, Double_t z, Double_t *matrix, Double_t *dxnew, Double_t *rmatnew); - ClassDef(TNode,3) //Description of parameters to position a 3-D geometry object + ClassDefOverride(TNode,3) //Description of parameters to position a 3-D geometry object }; #endif diff --git a/graf3d/g3d/inc/TNodeDiv.h b/graf3d/g3d/inc/TNodeDiv.h index f97b9572012f8..21a22c154a24b 100644 --- a/graf3d/g3d/inc/TNodeDiv.h +++ b/graf3d/g3d/inc/TNodeDiv.h @@ -34,11 +34,11 @@ class TNodeDiv : public TNode { TNodeDiv(); TNodeDiv(const char *name, const char *title, const char *shapename, Int_t ndiv, Int_t axis, Option_t *option=""); TNodeDiv(const char *name, const char *title, TShape *shape, Int_t ndiv, Int_t axis, Option_t *option=""); - virtual ~TNodeDiv(); - virtual void Draw(Option_t *option=""); - virtual void Paint(Option_t *option=""); + ~TNodeDiv() override; + void Draw(Option_t *option="") override; + void Paint(Option_t *option="") override; - ClassDef(TNodeDiv,1) //Description of parameters to divide a 3-D geometry object + ClassDefOverride(TNodeDiv,1) //Description of parameters to divide a 3-D geometry object }; #endif diff --git a/graf3d/g3d/inc/TPARA.h b/graf3d/g3d/inc/TPARA.h index 51d2e5f0234de..fe7f9ee2f2b94 100644 --- a/graf3d/g3d/inc/TPARA.h +++ b/graf3d/g3d/inc/TPARA.h @@ -33,19 +33,19 @@ class TPARA : public TBRIK { Float_t fTheta; // polar angle from the centre of the low z to the high z Float_t fPhi; // polar angle from the centre of the low z to the high z - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TPARA(); TPARA(const char *name, const char *title, const char *material, Float_t dx, Float_t dy, Float_t dz, Float_t alpha, Float_t theta, Float_t phi); - virtual ~TPARA(); + ~TPARA() override; virtual Float_t GetAlpha() const {return fAlpha;} virtual Float_t GetTheta() const {return fTheta;} virtual Float_t GetPhi() const {return fPhi;} - ClassDef(TPARA,1) //PARA shape + ClassDefOverride(TPARA,1) //PARA shape }; #endif diff --git a/graf3d/g3d/inc/TPCON.h b/graf3d/g3d/inc/TPCON.h index 67b3590656e42..1504f54c5bba5 100644 --- a/graf3d/g3d/inc/TPCON.h +++ b/graf3d/g3d/inc/TPCON.h @@ -49,17 +49,17 @@ class TPCON : public TShape { virtual void MakeTableOfCoSin() const; // Create the table of the fSiTab; fCoTab virtual void FillTableOfCoSin(Double_t phi, Double_t angstep,Int_t n) const; // Fill the table of cosin - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; virtual Bool_t SetSegsAndPols(TBuffer3D & buffer) const; public: TPCON(); TPCON(const char *name, const char *title, const char *material, Float_t phi1, Float_t dphi1, Int_t nz); - virtual ~TPCON(); + ~TPCON() override; virtual void DefineSection(Int_t secNum, Float_t z, Float_t rmin, Float_t rmax); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections) const override; virtual Int_t GetNumberOfDivisions () const {if (fNdiv) return fNdiv; else return kDiv;} virtual Float_t GetPhi1() const {return fPhi1;} virtual Float_t GetDhi1() const {return fDphi1;} @@ -69,9 +69,9 @@ class TPCON : public TShape { virtual Float_t *GetDz() const {return fDz;} virtual Int_t GetNdiv() const {return fNdiv;} virtual void SetNumberOfDivisions (Int_t p); - virtual void Sizeof3D() const; + void Sizeof3D() const override; - ClassDef(TPCON,2) //PCON shape + ClassDefOverride(TPCON,2) //PCON shape }; #endif diff --git a/graf3d/g3d/inc/TPGON.h b/graf3d/g3d/inc/TPGON.h index 15f6d9119f329..d58e700d31ceb 100644 --- a/graf3d/g3d/inc/TPGON.h +++ b/graf3d/g3d/inc/TPGON.h @@ -29,14 +29,14 @@ class TPGON : public TPCON { protected: - virtual void FillTableOfCoSin(Double_t phi, Double_t angstep,Int_t n) const; // Fill the table of cosin + void FillTableOfCoSin(Double_t phi, Double_t angstep,Int_t n) const override; // Fill the table of cosin public: TPGON(); TPGON(const char *name, const char *title, const char *material, Float_t phi1, Float_t dphi1, Int_t npdv, Int_t nz); - virtual ~TPGON(); - ClassDef(TPGON,1) //PGON shape + ~TPGON() override; + ClassDefOverride(TPGON,1) //PGON shape }; #endif diff --git a/graf3d/g3d/inc/TPointSet3D.h b/graf3d/g3d/inc/TPointSet3D.h index 2d645d54cbe93..ea18f7df43b04 100644 --- a/graf3d/g3d/inc/TPointSet3D.h +++ b/graf3d/g3d/inc/TPointSet3D.h @@ -39,9 +39,9 @@ class TPointSet3D : public TPolyMarker3D, public TAttBBox TPointSet3D& operator=(const TPointSet3D& t); - virtual ~TPointSet3D(); + ~TPointSet3D() override; - virtual void ComputeBBox(); + void ComputeBBox() override; void SetPointId(TObject* id); void SetPointId(Int_t n, TObject* id); @@ -53,7 +53,7 @@ class TPointSet3D : public TPolyMarker3D, public TAttBBox virtual void PointSelected(Int_t n); - ClassDef(TPointSet3D,1); // TPolyMarker3D with direct OpenGL rendering. + ClassDefOverride(TPointSet3D,1); // TPolyMarker3D with direct OpenGL rendering. }; #endif diff --git a/graf3d/g3d/inc/TPoints3DABC.h b/graf3d/g3d/inc/TPoints3DABC.h index 7cbdcf3e75fbf..dcc769a61d469 100644 --- a/graf3d/g3d/inc/TPoints3DABC.h +++ b/graf3d/g3d/inc/TPoints3DABC.h @@ -26,13 +26,13 @@ class TPoints3DABC : public TObject { public: TPoints3DABC(){} - virtual ~TPoints3DABC(){} + ~TPoints3DABC() override{} static Int_t DistancetoLine(Int_t px, Int_t py, Float_t x1, Float_t y1, Float_t x2, Float_t y2, Int_t lineWidth = 1 ); virtual Int_t Add(Float_t x, Float_t y, Float_t z); virtual Int_t AddLast(Float_t x, Float_t y, Float_t z); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)=0; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override =0; virtual Int_t GetLastPosition()const =0; // GetN() returns the number of allocated cells if any. // GetN() > 0 shows how many cells @@ -45,7 +45,7 @@ class TPoints3DABC : public TObject { virtual Float_t GetZ(Int_t idx) const =0; virtual Float_t *GetXYZ(Float_t *xyz,Int_t idx,Int_t num=1) const; virtual const Float_t *GetXYZ(Int_t idx) =0; - virtual Option_t *GetOption() const =0; + Option_t *GetOption() const override =0; virtual void PaintPoints(Int_t n, Float_t *p,Option_t *option="") =0; virtual Int_t SetLastPosition(Int_t idx)=0; virtual Int_t SetNextPoint(Float_t x, Float_t y, Float_t z); @@ -54,7 +54,7 @@ class TPoints3DABC : public TObject { virtual Int_t SetPoints(Int_t n, Float_t *p=nullptr, Option_t *option="") =0; virtual Int_t Size() const =0; - ClassDef(TPoints3DABC,0) //A 3-D Points + ClassDefOverride(TPoints3DABC,0) //A 3-D Points }; #endif diff --git a/graf3d/g3d/inc/TPolyLine3D.h b/graf3d/g3d/inc/TPolyLine3D.h index 8ed95ad5e8834..cacdea5ac5eb4 100644 --- a/graf3d/g3d/inc/TPolyLine3D.h +++ b/graf3d/g3d/inc/TPolyLine3D.h @@ -46,7 +46,7 @@ class TPolyLine3D : public TObject, public TAttLine, public TAtt3D TPolyLine3D(Int_t n, Double_t const* x, Double_t const* y, Double_t const* z, Option_t *option=""); TPolyLine3D(const TPolyLine3D &polylin); TPolyLine3D& operator=(const TPolyLine3D &polylin); - virtual ~TPolyLine3D(); + ~TPolyLine3D() override; void Copy(TObject &polyline) const override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; diff --git a/graf3d/g3d/inc/TPolyMarker3D.h b/graf3d/g3d/inc/TPolyMarker3D.h index 4fc7aec718b47..a2e18c3fa7390 100644 --- a/graf3d/g3d/inc/TPolyMarker3D.h +++ b/graf3d/g3d/inc/TPolyMarker3D.h @@ -45,7 +45,7 @@ class TPolyMarker3D : public TObject, public TAttMarker, public TAtt3D TPolyMarker3D(Int_t n, Double_t *p, Marker_t marker=1, Option_t *option=""); TPolyMarker3D(const TPolyMarker3D &p); TPolyMarker3D& operator=(const TPolyMarker3D&); - virtual ~TPolyMarker3D(); + ~TPolyMarker3D() override; void Copy(TObject &polymarker) const override; Int_t DistancetoPrimitive(Int_t px, Int_t py) override; diff --git a/graf3d/g3d/inc/TRotMatrix.h b/graf3d/g3d/inc/TRotMatrix.h index 67554b2edad4c..ceaf6784364fc 100644 --- a/graf3d/g3d/inc/TRotMatrix.h +++ b/graf3d/g3d/inc/TRotMatrix.h @@ -49,7 +49,7 @@ class TRotMatrix : public TNamed { TRotMatrix(const char *name, const char *title, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3); - virtual ~TRotMatrix(); + ~TRotMatrix() override; virtual Double_t Determinant() const ; // returns the determinant of this matrix virtual Double_t* GetMatrix() {return &fMatrix[0];} virtual Int_t GetNumber() const {return fNumber;} @@ -61,9 +61,9 @@ class TRotMatrix : public TNamed { virtual Bool_t IsReflection() const {return TestBit(kReflection);} // Return kTRUE if this matrix defines the reflection virtual const Double_t* SetAngles(Double_t theta1, Double_t phi1,Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3); virtual void SetMatrix(const Double_t *matrix); - virtual void SetName(const char *name); + void SetName(const char *name) override; - ClassDef(TRotMatrix,2) //Rotation Matrix for 3-D geometry objects + ClassDefOverride(TRotMatrix,2) //Rotation Matrix for 3-D geometry objects }; inline void TRotMatrix::SetName(const char *) { } diff --git a/graf3d/g3d/inc/TSPHE.h b/graf3d/g3d/inc/TSPHE.h index 6eeef63f0eaf1..6bd1c5a467f53 100644 --- a/graf3d/g3d/inc/TSPHE.h +++ b/graf3d/g3d/inc/TSPHE.h @@ -47,16 +47,16 @@ class TSPHE : public TShape { Float_t faZ; // Coeff along Oz virtual void MakeTableOfCoSin() const; // Create the table of the fSiTab; fCoTab - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TSPHE(); TSPHE(const char *name, const char *title, const char *material, Float_t rmin, Float_t rmax, Float_t themin, Float_t themax, Float_t phimin, Float_t phimax); TSPHE(const char *name, const char *title, const char *material, Float_t rmax); - virtual ~TSPHE(); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; + ~TSPHE() override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections) const override; virtual Float_t GetRmin() const {return fRmin;} virtual Float_t GetRmax() const {return fRmax;} virtual Float_t GetThemin() const {return fThemin;} @@ -68,9 +68,9 @@ class TSPHE : public TShape { virtual void SetAspectRatio(Float_t factor=1.0){ fAspectRatio = factor; MakeTableOfCoSin();} virtual void SetEllipse(const Float_t *factors); virtual void SetNumberOfDivisions (Int_t p); - virtual void Sizeof3D() const; + void Sizeof3D() const override; - ClassDef(TSPHE,3) //SPHE shape + ClassDefOverride(TSPHE,3) //SPHE shape }; #endif diff --git a/graf3d/g3d/inc/TShape.h b/graf3d/g3d/inc/TShape.h index 2bc2a6d8085b5..12e92e42e536c 100644 --- a/graf3d/g3d/inc/TShape.h +++ b/graf3d/g3d/inc/TShape.h @@ -50,19 +50,19 @@ class TShape : public TNamed, public TAttLine, public TAttFill, public TAtt3D { TShape(const char *name, const char *title, const char *material); TShape(const TShape&); TShape& operator=(const TShape&); - virtual ~TShape(); + ~TShape() override; virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; TMaterial *GetMaterial() const {return fMaterial;} virtual Int_t GetNumber() const {return fNumber;} Int_t GetVisibility() const {return fVisibility;} - virtual void Paint(Option_t *option=""); - virtual void SetName(const char *name); + void Paint(Option_t *option="") override; + void SetName(const char *name) override; virtual void SetPoints(Double_t *points) const ; virtual void SetVisibility(Int_t vis) {fVisibility = vis;} // *MENU* void TransformPoints(Double_t *points, UInt_t NbPnts) const; - ClassDef(TShape,2) //Basic shape + ClassDefOverride(TShape,2) //Basic shape }; R__EXTERN TNode *gNode; diff --git a/graf3d/g3d/inc/TTRAP.h b/graf3d/g3d/inc/TTRAP.h index a00b7252c0ce5..2d82a6b6e5c77 100644 --- a/graf3d/g3d/inc/TTRAP.h +++ b/graf3d/g3d/inc/TTRAP.h @@ -41,14 +41,14 @@ class TTRAP : public TBRIK { Float_t fTl2; // half length in x at high z and y high edge Float_t fAlpha2; // angle w.r.t. the y axis - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TTRAP(); TTRAP(const char *name, const char *title, const char *material, Float_t dz, Float_t theta, Float_t phi, Float_t h1, Float_t bl1, Float_t tl1, Float_t alpha1, Float_t h2, Float_t bl2, Float_t tl2, Float_t alpha2); - virtual ~TTRAP(); + ~TTRAP() override; virtual Float_t GetH1() const {return fH1;} virtual Float_t GetBl1() const {return fBl1;} @@ -59,7 +59,7 @@ class TTRAP : public TBRIK { virtual Float_t GetTl2() const {return fTl2;} virtual Float_t GetAlpha2() const {return fAlpha2;} - ClassDef(TTRAP,1) //TRAP shape + ClassDefOverride(TTRAP,1) //TRAP shape }; #endif diff --git a/graf3d/g3d/inc/TTRD1.h b/graf3d/g3d/inc/TTRD1.h index d8edf32ad80b5..7a4e614ecc546 100644 --- a/graf3d/g3d/inc/TTRD1.h +++ b/graf3d/g3d/inc/TTRD1.h @@ -29,16 +29,16 @@ class TTRD1 : public TBRIK { protected: Float_t fDx2; // half length in x at the high z surface - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TTRD1(); TTRD1(const char *name, const char *title, const char *material, Float_t dx1, Float_t dx2, Float_t dy, Float_t dz); - virtual ~TTRD1(); + ~TTRD1() override; virtual Float_t GetDx2() const {return fDx2;} - ClassDef(TTRD1,1) //TRD1 shape + ClassDefOverride(TTRD1,1) //TRD1 shape }; #endif diff --git a/graf3d/g3d/inc/TTRD2.h b/graf3d/g3d/inc/TTRD2.h index c70aa2b2a8c0f..2325c49a28d76 100644 --- a/graf3d/g3d/inc/TTRD2.h +++ b/graf3d/g3d/inc/TTRD2.h @@ -31,18 +31,18 @@ class TTRD2 : public TBRIK { Float_t fDx2; // half length in x at the high z surface Float_t fDy2; // half length in y at the high z surface - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TTRD2(); TTRD2(const char *name, const char *title, const char *material, Float_t dx1, Float_t dx2, Float_t dy1, Float_t dy2, Float_t dz); - virtual ~TTRD2(); + ~TTRD2() override; Float_t GetDx2() const {return fDx2;} Float_t GetDy2() const {return fDy2;} - ClassDef(TTRD2,1) //TRD2 shape + ClassDefOverride(TTRD2,1) //TRD2 shape }; #endif diff --git a/graf3d/g3d/inc/TTUBE.h b/graf3d/g3d/inc/TTUBE.h index ff090ffa05f6f..83989cfb48f2a 100644 --- a/graf3d/g3d/inc/TTUBE.h +++ b/graf3d/g3d/inc/TTUBE.h @@ -48,17 +48,17 @@ class TTUBE : public TShape { TTUBE& operator=(const TTUBE&); virtual void MakeTableOfCoSin() const; // Create the table of the fSiTab; fCoTab - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; virtual void SetSegsAndPols(TBuffer3D & buffer) const; public: TTUBE(); TTUBE(const char *name, const char *title, const char *material, Float_t rmin, Float_t rmax, Float_t dz, Float_t aspect=1); TTUBE(const char *name, const char *title, const char *material, Float_t rmax, Float_t dz); - virtual ~TTUBE(); + ~TTUBE() override; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections) const override; virtual Float_t GetRmin() const {return fRmin;} virtual Float_t GetRmax() const {return fRmax;} virtual Float_t GetDz() const {return fDz;} @@ -67,9 +67,9 @@ class TTUBE : public TShape { virtual Int_t GetNumberOfDivisions () const {if (fNdiv) return fNdiv; else return kDivNum;} virtual void SetNumberOfDivisions (Int_t ndiv); virtual void SetAspectRatio(Float_t factor=1){fAspectRatio = factor;} - virtual void Sizeof3D() const; + void Sizeof3D() const override; - ClassDef(TTUBE,3) //TUBE shape + ClassDefOverride(TTUBE,3) //TUBE shape }; #endif diff --git a/graf3d/g3d/inc/TTUBS.h b/graf3d/g3d/inc/TTUBS.h index 3cb3f9affc690..7652c9b0799fc 100644 --- a/graf3d/g3d/inc/TTUBS.h +++ b/graf3d/g3d/inc/TTUBS.h @@ -30,9 +30,9 @@ class TTUBS : public TTUBE { protected: Float_t fPhi1; // first phi limit Float_t fPhi2; // second phi limit - virtual void MakeTableOfCoSin() const; // Create the table of the fSiTab; fCoTab + void MakeTableOfCoSin() const override; // Create the table of the fSiTab; fCoTab - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; public: TTUBS(); @@ -40,15 +40,15 @@ class TTUBS : public TTUBE { Float_t phi1, Float_t phi2); TTUBS(const char *name, const char *title, const char *material, Float_t rmax, Float_t dz, Float_t phi1, Float_t phi2); - virtual ~TTUBS(); + ~TTUBS() override; - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t reqSections) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t reqSections) const override; virtual Float_t GetPhi1() const {return fPhi1;} virtual Float_t GetPhi2() const {return fPhi2;} - virtual void Sizeof3D() const; + void Sizeof3D() const override; - ClassDef(TTUBS,1) //TUBS shape + ClassDefOverride(TTUBS,1) //TUBS shape }; #endif diff --git a/graf3d/g3d/inc/TView3D.h b/graf3d/g3d/inc/TView3D.h index 7e49a5a17611b..18353facadade 100644 --- a/graf3d/g3d/inc/TView3D.h +++ b/graf3d/g3d/inc/TView3D.h @@ -69,104 +69,104 @@ class TView3D : public TView { TView3D(); TView3D(Int_t system, const Double_t *rmin, const Double_t *rmax); - virtual ~TView3D(); + ~TView3D() override; - virtual void AxisVertex(Double_t ang, Double_t *av, Int_t &ix1, Int_t &ix2, Int_t &iy1, Int_t &iy2, Int_t &iz1, Int_t &iz2); - virtual void DefinePerspectiveView(); - virtual void DefineViewDirection(const Double_t *s, const Double_t *c, + void AxisVertex(Double_t ang, Double_t *av, Int_t &ix1, Int_t &ix2, Int_t &iy1, Int_t &iy2, Int_t &iz1, Int_t &iz2) override; + void DefinePerspectiveView() override; + void DefineViewDirection(const Double_t *s, const Double_t *c, Double_t cosphi, Double_t sinphi, Double_t costhe, Double_t sinthe, Double_t cospsi, Double_t sinpsi, - Double_t *tnorm, Double_t *tback); - virtual void DrawOutlineCube(TList *outline, Double_t *rmin, Double_t *rmax); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - virtual void ExecuteRotateView(Int_t event, Int_t px, Int_t py); - virtual void FindScope(Double_t *scale, Double_t *center, Int_t &irep); - virtual Int_t GetDistancetoAxis(Int_t axis, Int_t px, Int_t py, Double_t &ratio); - virtual Double_t GetDview() const {return fDview;} - virtual Double_t GetDproj() const {return fDproj;} - virtual Double_t GetExtent() const; - virtual Bool_t GetAutoRange() {return fAutoRange;} - virtual Double_t GetLatitude() {return fLatitude;} - virtual Double_t GetLongitude() {return fLongitude;} - virtual Double_t GetPsi() {return fPsi;} - virtual void GetRange (Float_t *min, Float_t *max); - virtual void GetRange (Double_t *min, Double_t *max); - virtual Double_t *GetRmax() {return fRmax;} - virtual Double_t *GetRmin() {return fRmin;} - virtual TSeqCollection *GetOutline() {return fOutline; } - virtual Double_t *GetTback() {return fTback;} - virtual Double_t *GetTN() {return fTN;} - virtual Double_t *GetTnorm() {return fTnorm;} - virtual Int_t GetSystem() {return fSystem;} - virtual void GetWindow(Double_t &u0, Double_t &v0, Double_t &du, Double_t &dv) const; - virtual Double_t GetWindowWidth() const {return 0.5*(fUVcoord[1]-fUVcoord[0]);} - virtual Double_t GetWindowHeight() const {return 0.5*(fUVcoord[3]-fUVcoord[2]);} - virtual void FindNormal(Double_t x, Double_t y, Double_t z, Double_t &zn); - virtual void FindPhiSectors(Int_t iopt, Int_t &kphi, Double_t *aphi, Int_t &iphi1, Int_t &iphi2); - virtual void FindThetaSectors(Int_t iopt, Double_t phi, Int_t &kth, Double_t *ath, Int_t &ith1, Int_t &ith2); - virtual Bool_t IsClippedNDC(Double_t *p) const; - virtual Bool_t IsPerspective() const {return TestBit(kPerspective);} - virtual Bool_t IsViewChanged() const {return fChanged;} - virtual void NDCtoWC(const Float_t *pn, Float_t *pw); - virtual void NDCtoWC(const Double_t *pn, Double_t *pw); - virtual void NormalWCtoNDC(const Float_t *pw, Float_t *pn); - virtual void NormalWCtoNDC(const Double_t *pw, Double_t *pn); - virtual void PadRange(Int_t rback); - virtual void ResizePad(); - virtual void SetAutoRange(Bool_t autorange=kTRUE) {fAutoRange=autorange;} - virtual void SetAxisNDC(const Double_t *x1, const Double_t *x2, const Double_t *y1, const Double_t *y2, const Double_t *z1, const Double_t *z2); - virtual void SetDefaultWindow(); - virtual void SetDview(Double_t dview) {fDview=dview;} - virtual void SetDproj(Double_t dproj) {fDproj=dproj;} - virtual void SetLatitude(Double_t latitude) {fLatitude = latitude;} - virtual void SetLongitude(Double_t longitude) {fLongitude = longitude;} - virtual void SetPsi(Double_t psi) {fPsi = psi;} - virtual void SetOutlineToCube(); - virtual void SetParallel(); // *MENU* - virtual void SetPerspective(); // *MENU* - virtual void SetRange(const Double_t *min, const Double_t *max); - virtual void SetRange(Double_t x0, Double_t y0, Double_t z0, Double_t x1, Double_t y1, Double_t z1, Int_t flag=0); - virtual void SetSystem(Int_t system) {fSystem = system;} - virtual void SetView(Double_t longitude, Double_t latitude, Double_t psi, Int_t &irep); - virtual void SetViewChanged(Bool_t flag=kTRUE) {fChanged = flag;} - virtual void SetWindow(Double_t u0, Double_t v0, Double_t du, Double_t dv); - virtual void WCtoNDC(const Float_t *pw, Float_t *pn); - virtual void WCtoNDC(const Double_t *pw, Double_t *pn); + Double_t *tnorm, Double_t *tback) override; + void DrawOutlineCube(TList *outline, Double_t *rmin, Double_t *rmax) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + void ExecuteRotateView(Int_t event, Int_t px, Int_t py) override; + void FindScope(Double_t *scale, Double_t *center, Int_t &irep) override; + Int_t GetDistancetoAxis(Int_t axis, Int_t px, Int_t py, Double_t &ratio) override; + Double_t GetDview() const override {return fDview;} + Double_t GetDproj() const override {return fDproj;} + Double_t GetExtent() const override; + Bool_t GetAutoRange() override {return fAutoRange;} + Double_t GetLatitude() override {return fLatitude;} + Double_t GetLongitude() override {return fLongitude;} + Double_t GetPsi() override {return fPsi;} + void GetRange (Float_t *min, Float_t *max) override; + void GetRange (Double_t *min, Double_t *max) override; + Double_t *GetRmax() override {return fRmax;} + Double_t *GetRmin() override {return fRmin;} + TSeqCollection *GetOutline() override {return fOutline; } + Double_t *GetTback() override {return fTback;} + Double_t *GetTN() override {return fTN;} + Double_t *GetTnorm() override {return fTnorm;} + Int_t GetSystem() override {return fSystem;} + void GetWindow(Double_t &u0, Double_t &v0, Double_t &du, Double_t &dv) const override; + Double_t GetWindowWidth() const override {return 0.5*(fUVcoord[1]-fUVcoord[0]);} + Double_t GetWindowHeight() const override {return 0.5*(fUVcoord[3]-fUVcoord[2]);} + void FindNormal(Double_t x, Double_t y, Double_t z, Double_t &zn) override; + void FindPhiSectors(Int_t iopt, Int_t &kphi, Double_t *aphi, Int_t &iphi1, Int_t &iphi2) override; + void FindThetaSectors(Int_t iopt, Double_t phi, Int_t &kth, Double_t *ath, Int_t &ith1, Int_t &ith2) override; + Bool_t IsClippedNDC(Double_t *p) const override; + Bool_t IsPerspective() const override {return TestBit(kPerspective);} + Bool_t IsViewChanged() const override {return fChanged;} + void NDCtoWC(const Float_t *pn, Float_t *pw) override; + void NDCtoWC(const Double_t *pn, Double_t *pw) override; + void NormalWCtoNDC(const Float_t *pw, Float_t *pn) override; + void NormalWCtoNDC(const Double_t *pw, Double_t *pn) override; + void PadRange(Int_t rback) override; + void ResizePad() override; + void SetAutoRange(Bool_t autorange=kTRUE) override {fAutoRange=autorange;} + void SetAxisNDC(const Double_t *x1, const Double_t *x2, const Double_t *y1, const Double_t *y2, const Double_t *z1, const Double_t *z2) override; + void SetDefaultWindow() override; + void SetDview(Double_t dview) override {fDview=dview;} + void SetDproj(Double_t dproj) override {fDproj=dproj;} + void SetLatitude(Double_t latitude) override {fLatitude = latitude;} + void SetLongitude(Double_t longitude) override {fLongitude = longitude;} + void SetPsi(Double_t psi) override {fPsi = psi;} + void SetOutlineToCube() override; + void SetParallel() override; // *MENU* + void SetPerspective() override; // *MENU* + void SetRange(const Double_t *min, const Double_t *max) override; + void SetRange(Double_t x0, Double_t y0, Double_t z0, Double_t x1, Double_t y1, Double_t z1, Int_t flag=0) override; + void SetSystem(Int_t system) override {fSystem = system;} + void SetView(Double_t longitude, Double_t latitude, Double_t psi, Int_t &irep) override; + void SetViewChanged(Bool_t flag=kTRUE) override {fChanged = flag;} + void SetWindow(Double_t u0, Double_t v0, Double_t du, Double_t dv) override; + void WCtoNDC(const Float_t *pw, Float_t *pn) override; + void WCtoNDC(const Double_t *pw, Double_t *pn) override; //-- - virtual void MoveFocus(Double_t *center, Double_t dx, Double_t dy, Double_t dz, Int_t nsteps=10, - Double_t dlong=0, Double_t dlat=0, Double_t dpsi=0); - virtual void MoveViewCommand(Char_t chCode, Int_t count=1); - virtual void MoveWindow(Char_t option); - - virtual void AdjustScales(TVirtualPad *pad = nullptr); - virtual void Centered3DImages(TVirtualPad *pad = nullptr); - virtual void Centered(); // *MENU* - virtual void FrontView(TVirtualPad *pad = nullptr); - virtual void Front(); // *MENU* - - virtual void ZoomIn(); // *MENU* - virtual void ZoomOut(); // *MENU* - virtual void ZoomView(TVirtualPad *pad = nullptr, Double_t zoomFactor = 1.25 ); - virtual void UnzoomView(TVirtualPad *pad = nullptr,Double_t unZoomFactor = 1.25); - - virtual void RotateView(Double_t phi, Double_t theta, TVirtualPad *pad = nullptr); - virtual void SideView(TVirtualPad *pad = nullptr); - virtual void Side(); // *MENU* - virtual void TopView(TVirtualPad *pad = nullptr); - virtual void Top(); // *MENU* - - virtual void ToggleRulers(TVirtualPad *pad = nullptr); - virtual void ShowAxis(); // *MENU* - virtual void ToggleZoom(TVirtualPad *pad = nullptr); - virtual void ZoomMove(); // *MENU* - virtual void Zoom(); // *MENU* - virtual void UnZoom(); // *MENU* + void MoveFocus(Double_t *center, Double_t dx, Double_t dy, Double_t dz, Int_t nsteps=10, + Double_t dlong=0, Double_t dlat=0, Double_t dpsi=0) override; + void MoveViewCommand(Char_t chCode, Int_t count=1) override; + void MoveWindow(Char_t option) override; + + void AdjustScales(TVirtualPad *pad = nullptr) override; + void Centered3DImages(TVirtualPad *pad = nullptr) override; + void Centered() override; // *MENU* + void FrontView(TVirtualPad *pad = nullptr) override; + void Front() override; // *MENU* + + void ZoomIn() override; // *MENU* + void ZoomOut() override; // *MENU* + void ZoomView(TVirtualPad *pad = nullptr, Double_t zoomFactor = 1.25 ) override; + void UnzoomView(TVirtualPad *pad = nullptr,Double_t unZoomFactor = 1.25) override; + + void RotateView(Double_t phi, Double_t theta, TVirtualPad *pad = nullptr) override; + void SideView(TVirtualPad *pad = nullptr) override; + void Side() override; // *MENU* + void TopView(TVirtualPad *pad = nullptr) override; + void Top() override; // *MENU* + + void ToggleRulers(TVirtualPad *pad = nullptr) override; + void ShowAxis() override; // *MENU* + void ToggleZoom(TVirtualPad *pad = nullptr) override; + void ZoomMove() override; // *MENU* + void Zoom() override; // *MENU* + void UnZoom() override; // *MENU* static void AdjustPad(TVirtualPad *pad = nullptr); - ClassDef(TView3D,3); //3-D View + ClassDefOverride(TView3D,3); //3-D View }; #endif diff --git a/graf3d/g3d/inc/TXTRU.h b/graf3d/g3d/inc/TXTRU.h index 96060aba96814..4fefcc3329ced 100644 --- a/graf3d/g3d/inc/TXTRU.h +++ b/graf3d/g3d/inc/TXTRU.h @@ -25,15 +25,15 @@ class TXTRU : public TShape { TXTRU(const char *name, const char *title, const char *material, Int_t nyx, Int_t nz); TXTRU(const TXTRU &xtru); - virtual ~TXTRU(); + ~TXTRU() override; TXTRU& operator=(const TXTRU& rhs); - virtual void Copy(TObject &xtru) const; + void Copy(TObject &xtru) const override; virtual void DefineSection(Int_t secNum, Float_t z, Float_t scale=1., Float_t x0=0., Float_t y0=0.); virtual void DefineVertex(Int_t pointNum, Float_t x, Float_t y); - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual const TBuffer3D &GetBuffer3D(Int_t) const; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + const TBuffer3D &GetBuffer3D(Int_t) const override; virtual Int_t GetNxy() const { return fNxy; } virtual Int_t GetNz() const { return fNz; } virtual Float_t GetOutlinePointX(Int_t pointNum) const; @@ -48,15 +48,15 @@ class TXTRU : public TShape { virtual Float_t *GetScale() const {return fScale; } virtual Float_t *GetX0() const {return fX0; } virtual Float_t *GetY0() const {return fY0; } - virtual void Print(Option_t *option="") const; - virtual void Sizeof3D() const; + void Print(Option_t *option="") const override; + void Sizeof3D() const override; void SplitConcavePolygon(Bool_t split = kTRUE); virtual void TruncateNxy(Int_t npts); virtual void TruncateNz(Int_t npts); protected: void CheckOrdering(); - virtual void SetPoints(Double_t *points) const; + void SetPoints(Double_t *points) const override; Int_t fNxy{0}; // number of x-y points in the cross section Int_t fNxyAlloc{0}; // number of x-y points allocated @@ -89,7 +89,7 @@ class TXTRU : public TShape { void DumpSegments(int nsegments, int *segbuff) const; void DumpPolygons(int npolygons, int *polybuff, int buffsize) const; - ClassDef(TXTRU,1) //TXTRU shape + ClassDefOverride(TXTRU,1) //TXTRU shape }; #endif diff --git a/graf3d/gl/inc/TF2GL.h b/graf3d/gl/inc/TF2GL.h index 16a093131d936..54b5f5d52779c 100644 --- a/graf3d/gl/inc/TF2GL.h +++ b/graf3d/gl/inc/TF2GL.h @@ -30,19 +30,19 @@ class TF2GL : public TGLPlot3D public: TF2GL(); - virtual ~TF2GL(); + ~TF2GL() override; - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t KeepDuringSmartRefresh() const { return kFALSE; } + Bool_t KeepDuringSmartRefresh() const override { return kFALSE; } // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*); - ClassDef(TF2GL, 0); // GL renderer for TF2 and TF3. + ClassDefOverride(TF2GL, 0); // GL renderer for TF2 and TF3. }; #endif diff --git a/graf3d/gl/inc/TGL5D.h b/graf3d/gl/inc/TGL5D.h index 4a820fc4fc82f..5cced97fd35aa 100644 --- a/graf3d/gl/inc/TGL5D.h +++ b/graf3d/gl/inc/TGL5D.h @@ -36,10 +36,10 @@ class TGL5DDataSet : public TNamed { //These are functions for TPad and //TPad's standard machinery (picking, painting). - Int_t DistancetoPrimitive(Int_t px, Int_t py); - void ExecuteEvent(Int_t event, Int_t px, Int_t py); - char *GetObjectInfo(Int_t px, Int_t py) const; - void Paint(Option_t *option); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + char *GetObjectInfo(Int_t px, Int_t py) const override; + void Paint(Option_t *option) override; //This is for editor. TGL5DPainter *GetRealPainter()const; @@ -105,7 +105,7 @@ class TGL5DDataSet : public TNamed { TGL5DDataSet(const TGL5DDataSet &rhs); TGL5DDataSet &operator = (const TGL5DDataSet &rhs); - ClassDef(TGL5DDataSet, 0)//Class to read data from TTree and create TGL5DPainter. + ClassDefOverride(TGL5DDataSet, 0)//Class to read data from TTree and create TGL5DPainter. }; #endif diff --git a/graf3d/gl/inc/TGL5DDataSetEditor.h b/graf3d/gl/inc/TGL5DDataSetEditor.h index d7d014cfa6a67..e01a42afbe2d5 100644 --- a/graf3d/gl/inc/TGL5DDataSetEditor.h +++ b/graf3d/gl/inc/TGL5DDataSetEditor.h @@ -113,9 +113,9 @@ class TGL5DDataSetEditor : public TGedFrame { public: TGL5DDataSetEditor(const TGWindow *p = nullptr, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - ~TGL5DDataSetEditor(); + ~TGL5DDataSetEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; //Slots for "Grid" tab events. void GridParametersChanged(); @@ -146,7 +146,7 @@ class TGL5DDataSetEditor : public TGedFrame { void NContoursChanged(); - ClassDef(TGL5DDataSetEditor, 0); //GUI for editing OpenGL 5D Viewer attributes + ClassDefOverride(TGL5DDataSetEditor, 0); //GUI for editing OpenGL 5D Viewer attributes }; #endif diff --git a/graf3d/gl/inc/TGL5DPainter.h b/graf3d/gl/inc/TGL5DPainter.h index 2816a3ad8a622..af9b326225ce4 100644 --- a/graf3d/gl/inc/TGL5DPainter.h +++ b/graf3d/gl/inc/TGL5DPainter.h @@ -91,12 +91,12 @@ class TGL5DPainter : public TGLPlotPainter { void RemoveSurface(SurfIter_t surf); //TGLPlotPainter final-overriders. - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &option); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &option) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; //Methods for ged. void ShowBoxCut(Bool_t show) {fBoxCut.SetActive(show);} @@ -115,15 +115,15 @@ class TGL5DPainter : public TGLPlotPainter { private: //TGLPlotPainter final-overriders. - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; //Empty overriders. - void DrawSectionXOZ()const{} - void DrawSectionYOZ()const{} - void DrawSectionXOY()const{} + void DrawSectionXOZ()const override{} + void DrawSectionYOZ()const override{} + void DrawSectionXOY()const override{} //Auxiliary functions. void SetSurfaceColor(ConstSurfIter_t surf)const; diff --git a/graf3d/gl/inc/TGLAdapter.h b/graf3d/gl/inc/TGLAdapter.h index 521043e2a3ede..cd92125cec613 100644 --- a/graf3d/gl/inc/TGLAdapter.h +++ b/graf3d/gl/inc/TGLAdapter.h @@ -21,10 +21,10 @@ class TGLAdapter : public TGLPaintDevice { public: explicit TGLAdapter(Int_t glDevice = -1); - Bool_t MakeCurrent(); - void SwapBuffers(); - const TGLFormat *GetPixelFormat()const{return nullptr;} - const TGLContext *GetContext()const{return nullptr;} + Bool_t MakeCurrent() override; + void SwapBuffers() override; + const TGLFormat *GetPixelFormat()const override{return nullptr;} + const TGLContext *GetContext()const override{return nullptr;} void SetGLDevice(Int_t glDevice) { @@ -34,16 +34,16 @@ class TGLAdapter : public TGLPaintDevice { void ReadGLBuffer(); void SelectOffScreenDevice(); void MarkForDirectCopy(Bool_t isDirect); - void ExtractViewport(Int_t *vp)const; + void ExtractViewport(Int_t *vp)const override; private: TGLAdapter(const TGLAdapter &); TGLAdapter &operator = (const TGLAdapter &); - void AddContext(TGLContext *){} - void RemoveContext(TGLContext *){} + void AddContext(TGLContext *) override{} + void RemoveContext(TGLContext *) override{} - ClassDef(TGLAdapter, 0) // Allow plot-painters to be used for gl-inpad and gl-viewer. + ClassDefOverride(TGLAdapter, 0) // Allow plot-painters to be used for gl-inpad and gl-viewer. }; #endif diff --git a/graf3d/gl/inc/TGLAnnotation.h b/graf3d/gl/inc/TGLAnnotation.h index 65c15b5426899..abacd5566e15e 100644 --- a/graf3d/gl/inc/TGLAnnotation.h +++ b/graf3d/gl/inc/TGLAnnotation.h @@ -73,7 +73,7 @@ class TGLAnnotation : public TGLOverlayElement public: TGLAnnotation(TGLViewerBase *parent, const char *text, Float_t posx, Float_t posy); TGLAnnotation(TGLViewerBase *parent, const char *text, Float_t posx, Float_t posy, TGLVector3 ref); - virtual ~TGLAnnotation(); + ~TGLAnnotation() override; void SetText(const TString& x) { fText = x; } const TString& GetText() const { return fText; } @@ -99,18 +99,18 @@ class TGLAnnotation : public TGLOverlayElement TGLFont::ETextAlignH_e GetTextAlign() const { return fTextAlign; } void SetTextAlign(TGLFont::ETextAlignH_e a) { fTextAlign = a; } - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, - Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, + Event_t* event) override; + void MouseLeave() override; void CloseEditor(); void UpdateText(); - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; - ClassDef(TGLAnnotation, 0); // GL-annotation. + ClassDefOverride(TGLAnnotation, 0); // GL-annotation. }; #endif diff --git a/graf3d/gl/inc/TGLAutoRotator.h b/graf3d/gl/inc/TGLAutoRotator.h index f511197c92c03..bb5bee021fcf6 100644 --- a/graf3d/gl/inc/TGLAutoRotator.h +++ b/graf3d/gl/inc/TGLAutoRotator.h @@ -53,7 +53,7 @@ class TGLAutoRotator : public TObject public: TGLAutoRotator(TGLViewer* v); - virtual ~TGLAutoRotator(); + ~TGLAutoRotator() override; TGLViewer* GetViewer() const { return fViewer; } TGLCamera* GetCamera() const { return fCamera; } @@ -111,7 +111,7 @@ class TGLAutoRotator : public TObject void StartImageAutoSaveWithGUISettings(); - ClassDef(TGLAutoRotator, 0); // Automatic, timer-based, rotation of GL-viewer's camera. + ClassDefOverride(TGLAutoRotator, 0); // Automatic, timer-based, rotation of GL-viewer's camera. }; #endif diff --git a/graf3d/gl/inc/TGLAxis.h b/graf3d/gl/inc/TGLAxis.h index 06f43be9d995e..c00da64b8e309 100644 --- a/graf3d/gl/inc/TGLAxis.h +++ b/graf3d/gl/inc/TGLAxis.h @@ -48,7 +48,7 @@ class TGLAxis : public TAttLine, public TAttText { public: TGLAxis(); - virtual ~TGLAxis(); + ~TGLAxis() override; void PaintGLAxis (const Double_t p1[3], const Double_t p2[3], Double_t wmin , Double_t wmax , Int_t ndiv, @@ -68,7 +68,7 @@ class TGLAxis : public TAttLine, public TAttText { void SetGridLength (Double_t grid){fGridLength = grid;} void SetLabelsAngles (Double_t a1, Double_t a2, Double_t a3); - ClassDef(TGLAxis,0) // a GL Axis + ClassDefOverride(TGLAxis,0) // a GL Axis }; #endif diff --git a/graf3d/gl/inc/TGLAxisPainter.h b/graf3d/gl/inc/TGLAxisPainter.h index 1f270bac8139e..7622347ce1b2a 100644 --- a/graf3d/gl/inc/TGLAxisPainter.h +++ b/graf3d/gl/inc/TGLAxisPainter.h @@ -146,14 +146,14 @@ class TGLAxisPainterBox : public TGLAxisPainter public: TGLAxisPainterBox(); - virtual ~TGLAxisPainterBox(); + ~TGLAxisPainterBox() override; void SetAxis3DTitlePos(TGLRnrCtx &rnrCtx); void DrawAxis3D(TGLRnrCtx &rnrCtx); void PlotStandard(TGLRnrCtx &rnrCtx, TH1* histo, const TGLBoundingBox& bbox); - ClassDef(TGLAxisPainterBox, 0); // Painter of GL axes for a 3D box. + ClassDefOverride(TGLAxisPainterBox, 0); // Painter of GL axes for a 3D box. }; #endif diff --git a/graf3d/gl/inc/TGLBoxPainter.h b/graf3d/gl/inc/TGLBoxPainter.h index 9f74a5910c7bc..e3ba456e59536 100644 --- a/graf3d/gl/inc/TGLBoxPainter.h +++ b/graf3d/gl/inc/TGLBoxPainter.h @@ -59,34 +59,34 @@ class TGLBoxPainter : public TGLPlotPainter { TGLBoxPainter(TH1 *hist, TPolyMarker3D * pm, TGLPlotCamera *camera, TGLPlotCoordinates *coord); - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //Overriders - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; //Special type of TH3: void DrawCloud()const; void SetPlotColor()const; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; void DrawPalette()const; - void DrawPaletteAxis()const; + void DrawPaletteAxis()const override; Bool_t HasSections()const; - ClassDef(TGLBoxPainter, 0)//Box painter + ClassDefOverride(TGLBoxPainter, 0)//Box painter }; #endif diff --git a/graf3d/gl/inc/TGLCamera.h b/graf3d/gl/inc/TGLCamera.h index 7851609fc05f0..aab64421cad29 100644 --- a/graf3d/gl/inc/TGLCamera.h +++ b/graf3d/gl/inc/TGLCamera.h @@ -113,7 +113,7 @@ class TGLCamera : public TObject public: TGLCamera(); TGLCamera(const TGLVector3 & hAxis, const TGLVector3 & vAxis); - virtual ~TGLCamera(); + ~TGLCamera() override; virtual Bool_t IsOrthographic() const { return kFALSE; } virtual Bool_t IsPerspective() const { return kFALSE; } @@ -213,7 +213,7 @@ class TGLCamera : public TObject // Debuging - draw frustum and interest boxes void DrawDebugAids() const; - ClassDef(TGLCamera,1); // Camera abstract base class. + ClassDefOverride(TGLCamera,1); // Camera abstract base class. }; inline const TGLPlane & TGLCamera::FrustumPlane(EFrustumPlane plane) const diff --git a/graf3d/gl/inc/TGLCameraGuide.h b/graf3d/gl/inc/TGLCameraGuide.h index c4b15366a989d..c7e9a436bcfc9 100644 --- a/graf3d/gl/inc/TGLCameraGuide.h +++ b/graf3d/gl/inc/TGLCameraGuide.h @@ -31,21 +31,21 @@ class TGLCameraGuide : public TGLOverlayElement public: TGLCameraGuide(Float_t x, Float_t y, Float_t s, ERole role=kUser, EState state=kActive); - virtual ~TGLCameraGuide() {} + ~TGLCameraGuide() override {} void SetX(Float_t x) { fXPos = x; } void SetY(Float_t y) { fYPos = y; } void SetXY(Float_t x, Float_t y) { fXPos = x; fYPos = y; } void SetSize(Float_t s) { fSize = s; } - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, - Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, + Event_t* event) override; + void MouseLeave() override; - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; - ClassDef(TGLCameraGuide, 0); // Short description. + ClassDefOverride(TGLCameraGuide, 0); // Short description. }; #endif diff --git a/graf3d/gl/inc/TGLCameraOverlay.h b/graf3d/gl/inc/TGLCameraOverlay.h index 436856ffeec0d..f080b8829cdc7 100644 --- a/graf3d/gl/inc/TGLCameraOverlay.h +++ b/graf3d/gl/inc/TGLCameraOverlay.h @@ -56,9 +56,9 @@ class TGLCameraOverlay : public TGLOverlayElement public: TGLCameraOverlay(Bool_t showOrtho=kTRUE, Bool_t showPersp=kFALSE); - virtual ~TGLCameraOverlay(); + ~TGLCameraOverlay() override; - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; TGLPlane& RefExternalRefPlane() { return fExternalRefPlane; } void UseExternalRefPlane(Bool_t x) { fUseExternalRefPlane=x; } @@ -78,7 +78,7 @@ class TGLCameraOverlay : public TGLOverlayElement TAttAxis* GetAttAxis(); - ClassDef(TGLCameraOverlay, 1); // Show coorinates of current camera frustum. + ClassDefOverride(TGLCameraOverlay, 1); // Show coorinates of current camera frustum. }; #endif diff --git a/graf3d/gl/inc/TGLClip.h b/graf3d/gl/inc/TGLClip.h index 19dbb081a1d2e..44371284d6295 100644 --- a/graf3d/gl/inc/TGLClip.h +++ b/graf3d/gl/inc/TGLClip.h @@ -50,7 +50,7 @@ class TGLClip : public TGLPhysicalShape public: TGLClip(const TGLLogicalShape & logical, const TGLMatrix & transform, const float color[4]); - virtual ~TGLClip(); + ~TGLClip() override; virtual void Modified() { TGLPhysicalShape::Modified(); IncTimeStamp(); } @@ -66,10 +66,10 @@ class TGLClip : public TGLPhysicalShape Bool_t IsValid() const { return fValid; } void Invalidate() { fValid = kFALSE; } - virtual void Draw(TGLRnrCtx & rnrCtx) const; + void Draw(TGLRnrCtx & rnrCtx) const override; virtual void PlaneSet(TGLPlaneSet_t & set) const = 0; - ClassDef(TGLClip,0); // abstract clipping object + ClassDefOverride(TGLClip,0); // abstract clipping object }; ////////////////////////////////////////////////////////////////////////// @@ -89,16 +89,16 @@ class TGLClipPlane : public TGLClip public: TGLClipPlane(); - virtual ~TGLClipPlane(); + ~TGLClipPlane() override; - virtual void Setup(const TGLBoundingBox & bbox); - virtual void Setup(const TGLVector3& point, const TGLVector3& normal); + void Setup(const TGLBoundingBox & bbox) override; + void Setup(const TGLVector3& point, const TGLVector3& normal) override; void Set(const TGLPlane & plane); - virtual void PlaneSet(TGLPlaneSet_t & set) const; + void PlaneSet(TGLPlaneSet_t & set) const override; - ClassDef(TGLClipPlane, 0); // clipping plane + ClassDefOverride(TGLClipPlane, 0); // clipping plane }; ////////////////////////////////////////////////////////////////////////// @@ -117,14 +117,14 @@ class TGLClipBox : public TGLClip public: TGLClipBox(); - virtual ~TGLClipBox(); + ~TGLClipBox() override; - virtual void Setup(const TGLBoundingBox & bbox); - virtual void Setup(const TGLVector3& min_point, const TGLVector3& max_point); + void Setup(const TGLBoundingBox & bbox) override; + void Setup(const TGLVector3& min_point, const TGLVector3& max_point) override; - virtual void PlaneSet(TGLPlaneSet_t & set) const; + void PlaneSet(TGLPlaneSet_t & set) const override; - ClassDef(TGLClipBox, 0); // clipping box + ClassDefOverride(TGLClipBox, 0); // clipping box }; ////////////////////////////////////////////////////////////////////////// @@ -156,15 +156,15 @@ class TGLClipSet : public TGLOverlayElement public: TGLClipSet(); - virtual ~TGLClipSet(); + ~TGLClipSet() override; - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t MouseStillInside(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, - Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t MouseStillInside(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, + Event_t* event) override; + void MouseLeave() override; - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; Bool_t IsClipping() const { return fCurrentClip != nullptr; } TGLClip* GetCurrentClip() const { return fCurrentClip; } @@ -192,7 +192,7 @@ class TGLClipSet : public TGLOverlayElement Bool_t GetShowClip() const { return fShowClip; } void SetShowClip(Bool_t show) { fShowClip = show; } - ClassDef(TGLClipSet, 0); // A collection of supported clip-objects + ClassDefOverride(TGLClipSet, 0); // A collection of supported clip-objects }; #endif diff --git a/graf3d/gl/inc/TGLClipSetEditor.h b/graf3d/gl/inc/TGLClipSetEditor.h index ad81f3f43fe62..b95bc5e775efe 100644 --- a/graf3d/gl/inc/TGLClipSetEditor.h +++ b/graf3d/gl/inc/TGLClipSetEditor.h @@ -49,7 +49,7 @@ class TGLClipSetSubEditor : public TGVerticalFrame public: TGLClipSetSubEditor(const TGWindow* p); - virtual ~TGLClipSetSubEditor() {} + ~TGLClipSetSubEditor() override {} void SetModel(TGLClipSet* m); @@ -61,7 +61,7 @@ class TGLClipSetSubEditor : public TGVerticalFrame void UpdateViewerClip(); void ResetViewerClip(); - ClassDef(TGLClipSetSubEditor, 0); // Sub-editor for TGLClipSet. + ClassDefOverride(TGLClipSetSubEditor, 0); // Sub-editor for TGLClipSet. }; @@ -77,11 +77,11 @@ class TGLClipSetEditor : public TGedFrame { public: TGLClipSetEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TGLClipSetEditor() {} + ~TGLClipSetEditor() override {} - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; - ClassDef(TGLClipSetEditor, 0); // GUI editor for TGLClipSet. + ClassDefOverride(TGLClipSetEditor, 0); // GUI editor for TGLClipSet. }; #endif diff --git a/graf3d/gl/inc/TGLCylinder.h b/graf3d/gl/inc/TGLCylinder.h index 0f95e1923ffc1..ce96218d44514 100644 --- a/graf3d/gl/inc/TGLCylinder.h +++ b/graf3d/gl/inc/TGLCylinder.h @@ -30,24 +30,24 @@ class TGLCylinder : public TGLLogicalShape public: TGLCylinder(const TBuffer3DTube & buffer); - ~TGLCylinder(); + ~TGLCylinder() override; - virtual UInt_t DLOffset(Short_t lod) const; + UInt_t DLOffset(Short_t lod) const override; // Cylinders support LOD (tesselation quality) adjustment along // X/Y axes (round the cylinder radius), but not along length (Z) - virtual ELODAxes SupportedLODAxes() const + ELODAxes SupportedLODAxes() const override { // return ELODAxes(kLODAxesX | kLODAxesY); // MT 2020-06-05: There seems to be a problem with TGLPhysicalShape::CalculateShapeLOD() // and LOD is set to Pixel way too early. Resetting this to kLODAxesAll. return ELODAxes(kLODAxesAll); } - virtual Short_t QuantizeShapeLOD(Short_t shapeLOD, Short_t combiLOD) const; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Short_t QuantizeShapeLOD(Short_t shapeLOD, Short_t combiLOD) const override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; private: - ClassDef(TGLCylinder,0); // a cylinderical logical shape + ClassDefOverride(TGLCylinder,0); // a cylinderical logical shape }; #endif diff --git a/graf3d/gl/inc/TGLEmbeddedViewer.h b/graf3d/gl/inc/TGLEmbeddedViewer.h index db7696aa1b351..991a3fc7715a5 100644 --- a/graf3d/gl/inc/TGLEmbeddedViewer.h +++ b/graf3d/gl/inc/TGLEmbeddedViewer.h @@ -36,12 +36,12 @@ class TGLEmbeddedViewer : public TGLViewer public: TGLEmbeddedViewer(const TGWindow *parent, TVirtualPad *pad = nullptr, Int_t border=2); TGLEmbeddedViewer(const TGWindow *parent, TVirtualPad *pad, TGedEditor *ged, Int_t border=2); - ~TGLEmbeddedViewer(); + ~TGLEmbeddedViewer() override; - virtual void CreateGLWidget(); - virtual void DestroyGLWidget(); + void CreateGLWidget() override; + void DestroyGLWidget() override; - virtual const char *GetName() const { return "GLViewer"; } + const char *GetName() const override { return "GLViewer"; } TGCompositeFrame* GetFrame() const { return fFrame; } @@ -50,7 +50,7 @@ class TGLEmbeddedViewer : public TGLViewer TGLOrthoCamera *GetOrthoZOYCamera() { return &fOrthoZOYCamera; } TGLOrthoCamera *GetOrthoZOXCamera() { return &fOrthoZOXCamera; } - ClassDef(TGLEmbeddedViewer, 0); // Embedded GL viewer. + ClassDefOverride(TGLEmbeddedViewer, 0); // Embedded GL viewer. }; #endif diff --git a/graf3d/gl/inc/TGLEventHandler.h b/graf3d/gl/inc/TGLEventHandler.h index 70f927ae8b6e5..4225c8acab1f5 100644 --- a/graf3d/gl/inc/TGLEventHandler.h +++ b/graf3d/gl/inc/TGLEventHandler.h @@ -65,23 +65,23 @@ class TGLEventHandler : public TGEventHandler public: TGLEventHandler(TGWindow *w, TObject *obj); - virtual ~TGLEventHandler(); + ~TGLEventHandler() override; - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); - virtual Bool_t HandleEvent(Event_t *event); + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + Bool_t HandleEvent(Event_t *event) override; virtual Bool_t HandleExpose(Event_t * event); - virtual Bool_t HandleFocusChange(Event_t *event); - virtual Bool_t HandleCrossing(Event_t *event); - virtual Bool_t HandleButton(Event_t * event); - virtual Bool_t HandleDoubleClick(Event_t *event); - virtual Bool_t HandleConfigureNotify(Event_t *event); - virtual Bool_t HandleKey(Event_t *event); - virtual Bool_t HandleMotion(Event_t * event); - virtual Bool_t HandleTimer(TTimer *t); + Bool_t HandleFocusChange(Event_t *event) override; + Bool_t HandleCrossing(Event_t *event) override; + Bool_t HandleButton(Event_t * event) override; + Bool_t HandleDoubleClick(Event_t *event) override; + Bool_t HandleConfigureNotify(Event_t *event) override; + Bool_t HandleKey(Event_t *event) override; + Bool_t HandleMotion(Event_t * event) override; + Bool_t HandleTimer(TTimer *t) override; virtual void StartMouseTimer(); virtual void StopMouseTimer(); virtual void ClearMouseOver(); - virtual void Repaint(); + void Repaint() override; virtual void PopupContextMenu(TGLPhysicalShape* pshp, Event_t *event, Int_t gx, Int_t gy); @@ -103,7 +103,7 @@ class TGLEventHandler : public TGEventHandler Bool_t GetArcBall() const { return fArcBall; } void SetArcBall(Bool_t a) { fArcBall = a; } - ClassDef(TGLEventHandler, 0); // Base-class and default implementation of event-handler for TGLViewer. + ClassDefOverride(TGLEventHandler, 0); // Base-class and default implementation of event-handler for TGLViewer. }; #endif diff --git a/graf3d/gl/inc/TGLFaceSet.h b/graf3d/gl/inc/TGLFaceSet.h index fa6de6289f5d9..ca2a3736bc29b 100644 --- a/graf3d/gl/inc/TGLFaceSet.h +++ b/graf3d/gl/inc/TGLFaceSet.h @@ -32,7 +32,7 @@ class TGLFaceSet : public TGLLogicalShape public: TGLFaceSet(const TBuffer3D & buffer); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; void SetFromMesh(const RootCsg::TBaseMesh *m); void CalculateNormals(); @@ -52,7 +52,7 @@ class TGLFaceSet : public TGLLogicalShape static Bool_t Eq(const Double_t *p1, const Double_t *p2); - ClassDef(TGLFaceSet,0) // a faceset logical shape + ClassDefOverride(TGLFaceSet,0) // a faceset logical shape }; #endif diff --git a/graf3d/gl/inc/TGLH2PolyPainter.h b/graf3d/gl/inc/TGLH2PolyPainter.h index 1470206ca7d88..b1c7183ee0f37 100644 --- a/graf3d/gl/inc/TGLH2PolyPainter.h +++ b/graf3d/gl/inc/TGLH2PolyPainter.h @@ -15,18 +15,18 @@ class TGLH2PolyPainter : public TGLPlotPainter { public: TGLH2PolyPainter(TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //Overriders - void InitGL()const; - void DeInitGL()const; - void DrawPlot()const; + void InitGL()const override; + void DeInitGL()const override; + void DrawPlot()const override; //Aux. functions. //Draw edges of a bin. void DrawExtrusion()const; @@ -46,11 +46,11 @@ class TGLH2PolyPainter : public TGLPlotPainter { void SetBinColor(Int_t bin)const; //Empty overriders. - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; void DrawPalette()const; - void DrawPaletteAxis()const; + void DrawPaletteAxis()const override; //Aux. staff. void FillTemporaryPolygon(const Double_t *xs, const Double_t *ys, Double_t z, Int_t n)const; @@ -67,7 +67,7 @@ class TGLH2PolyPainter : public TGLPlotPainter { Bool_t fZLog;//Change in logZ updates only bin heights. Double_t fZMin; - ClassDef(TGLH2PolyPainter, 0); //Painter class for TH2Poly. + ClassDefOverride(TGLH2PolyPainter, 0); //Painter class for TH2Poly. }; #endif diff --git a/graf3d/gl/inc/TGLHistPainter.h b/graf3d/gl/inc/TGLHistPainter.h index 52668a1e1032d..ce7d41708ef83 100644 --- a/graf3d/gl/inc/TGLHistPainter.h +++ b/graf3d/gl/inc/TGLHistPainter.h @@ -60,22 +60,23 @@ class TGLHistPainter : public TVirtualHistPainter { TGLHistPainter(TGLTH3Composition *comp); //TVirtualHistPainter final overriders - Int_t DistancetoPrimitive(Int_t px, Int_t py); - void DrawPanel(); - void ExecuteEvent(Int_t event, Int_t px, Int_t py); - TList *GetContourList(Double_t contour)const; - char *GetObjectInfo(Int_t px, Int_t py)const; - TList *GetStack()const; - Bool_t IsInside(Int_t x, Int_t y); - Bool_t IsInside(Double_t x, Double_t y); - void Paint(Option_t *option); - void PaintStat(Int_t dostat, TF1 *fit); - void ProcessMessage(const char *message, const TObject *obj); - void SetHighlight(); - void SetHistogram(TH1 *hist); - void SetStack(TList *stack); - Int_t MakeCuts(char *cutsOpt); - void SetShowProjection(const char *option, Int_t nbins); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void DrawPanel() override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + TList *GetContourList(Double_t contour)const override; + char *GetObjectInfo(Int_t px, Int_t py)const override; + TList *GetStack()const override; + Bool_t IsInside(Int_t x, Int_t y) override; + Bool_t IsInside(Double_t x, Double_t y) override; + void Paint(Option_t *option) override; + void PaintStat(Int_t dostat, TF1 *fit) override; + void ProcessMessage(const char *message, const TObject *obj) override; + void SetHighlight() override; + void SetHistogram(TH1 *hist) override; + void SetStack(TList *stack) override; + Int_t MakeCuts(char *cutsOpt) override; + void SetShowProjection(const char *option, Int_t nbins) override; + void SetShowProjectionXY(const char *option, Int_t nbinsY, Int_t nbinsX) override; TGLPlotPainter *GetRealPainter(){return fGLPainter.get();} private: @@ -91,7 +92,7 @@ class TGLHistPainter : public TVirtualHistPainter { TGLHistPainter(const TGLHistPainter &); TGLHistPainter &operator = (const TGLHistPainter &); - ClassDef(TGLHistPainter, 0) //Proxy class for GL hist painters. + ClassDefOverride(TGLHistPainter, 0) //Proxy class for GL hist painters. }; #endif diff --git a/graf3d/gl/inc/TGLLegoPainter.h b/graf3d/gl/inc/TGLLegoPainter.h index c179a3b0515ac..d51ca2fd0e834 100644 --- a/graf3d/gl/inc/TGLLegoPainter.h +++ b/graf3d/gl/inc/TGLLegoPainter.h @@ -61,12 +61,12 @@ class TGLLegoPainter : public TGLPlotPainter { TGLLegoPainter(TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); //TGLPlotPainter's final-overriders - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //Auxilary functions. @@ -75,10 +75,10 @@ class TGLLegoPainter : public TGLPlotPainter { Bool_t InitGeometryCylindrical(); Bool_t InitGeometrySpherical(); //Overriders - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; void DrawLegoCartesian()const; void DrawLegoPolar()const; @@ -87,17 +87,17 @@ class TGLLegoPainter : public TGLPlotPainter { void SetLegoColor()const; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; Bool_t ClampZ(Double_t &zVal)const; Bool_t PreparePalette()const; void DrawPalette()const; - void DrawPaletteAxis()const; + void DrawPaletteAxis()const override; - ClassDef(TGLLegoPainter, 0)//Lego painter + ClassDefOverride(TGLLegoPainter, 0)//Lego painter }; #endif diff --git a/graf3d/gl/inc/TGLLightSet.h b/graf3d/gl/inc/TGLLightSet.h index 02ccc525ae5eb..43e4b5a621d24 100644 --- a/graf3d/gl/inc/TGLLightSet.h +++ b/graf3d/gl/inc/TGLLightSet.h @@ -42,7 +42,7 @@ class TGLLightSet : public TObject public: TGLLightSet(); - virtual ~TGLLightSet() {} + ~TGLLightSet() override {} void ToggleLight(ELight light); void SetLight(ELight light, Bool_t on); @@ -61,7 +61,7 @@ class TGLLightSet : public TObject void StdSetupLights(const TGLBoundingBox& bbox, const TGLCamera& camera, Bool_t debug=kFALSE); - ClassDef(TGLLightSet, 0) // A set of OpenGL lights. + ClassDefOverride(TGLLightSet, 0) // A set of OpenGL lights. }; // endclass TGLLightSet diff --git a/graf3d/gl/inc/TGLLightSetEditor.h b/graf3d/gl/inc/TGLLightSetEditor.h index bdcf651ef55bb..6e8b487910da8 100644 --- a/graf3d/gl/inc/TGLLightSetEditor.h +++ b/graf3d/gl/inc/TGLLightSetEditor.h @@ -39,7 +39,7 @@ class TGLLightSetSubEditor : public TGVerticalFrame public: TGLLightSetSubEditor(const TGWindow* p); - virtual ~TGLLightSetSubEditor() {} + ~TGLLightSetSubEditor() override {} void SetModel(TGLLightSet* m); @@ -47,7 +47,7 @@ class TGLLightSetSubEditor : public TGVerticalFrame void DoButton(); - ClassDef(TGLLightSetSubEditor, 0) // Sub-editor for TGLLightSet. + ClassDefOverride(TGLLightSetSubEditor, 0) // Sub-editor for TGLLightSet. }; @@ -63,11 +63,11 @@ class TGLLightSetEditor : public TGedFrame public: TGLLightSetEditor(const TGWindow *p = nullptr, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - virtual ~TGLLightSetEditor(); + ~TGLLightSetEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; - ClassDef(TGLLightSetEditor, 0); // Editor for TGLLightSet. + ClassDefOverride(TGLLightSetEditor, 0); // Editor for TGLLightSet. }; // endclass TGLLightSetEditor #endif diff --git a/graf3d/gl/inc/TGLManip.h b/graf3d/gl/inc/TGLManip.h index 00db5add6ea85..a9271a916a7ff 100644 --- a/graf3d/gl/inc/TGLManip.h +++ b/graf3d/gl/inc/TGLManip.h @@ -47,7 +47,7 @@ class TGLManip : public TVirtualGLManip public: TGLManip(); TGLManip(TGLPhysicalShape* shape); - virtual ~TGLManip(); + ~TGLManip() override; UInt_t GetSelectedWidget() const { return fSelectedWidget; } void SetSelectedWidget(UInt_t s) { fSelectedWidget = s; } @@ -60,12 +60,12 @@ class TGLManip : public TVirtualGLManip virtual void Draw(const TGLCamera& camera) const = 0; // CRAPPY TVirtualGLManip TTTT, just override it here - virtual Bool_t Select(const TGLCamera&, const TGLRect&, const TGLBoundingBox&) { return kFALSE; } + Bool_t Select(const TGLCamera&, const TGLRect&, const TGLBoundingBox&) override { return kFALSE; } virtual Bool_t HandleButton(const Event_t& event, const TGLCamera& camera); virtual Bool_t HandleMotion(const Event_t& event, const TGLCamera& camera); - ClassDef(TGLManip, 0); // abstract base GL manipulator widget + ClassDefOverride(TGLManip, 0); // abstract base GL manipulator widget }; #endif diff --git a/graf3d/gl/inc/TGLManipSet.h b/graf3d/gl/inc/TGLManipSet.h index e23cbc60e00f9..e579bb8b6b7ca 100644 --- a/graf3d/gl/inc/TGLManipSet.h +++ b/graf3d/gl/inc/TGLManipSet.h @@ -35,16 +35,16 @@ class TGLManipSet : public TGLOverlayElement, public: TGLManipSet(); - virtual ~TGLManipSet(); + ~TGLManipSet() override; - virtual void SetPShape(TGLPhysicalShape* shape); + void SetPShape(TGLPhysicalShape* shape) override; - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, - Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, + Event_t* event) override; + void MouseLeave() override; - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; TGLManip* GetCurrentManip() const { return fManip[fType]; } @@ -53,7 +53,7 @@ class TGLManipSet : public TGLOverlayElement, Bool_t GetDrawBBox() const { return fDrawBBox; } void SetDrawBBox(Bool_t bb) { fDrawBBox = bb; } - ClassDef(TGLManipSet, 0); // A collection of available manipulators. + ClassDefOverride(TGLManipSet, 0); // A collection of available manipulators. }; // endclass TGLManipSet diff --git a/graf3d/gl/inc/TGLObject.h b/graf3d/gl/inc/TGLObject.h index c9f4de8a9ea74..68762287d6acd 100644 --- a/graf3d/gl/inc/TGLObject.h +++ b/graf3d/gl/inc/TGLObject.h @@ -51,16 +51,16 @@ class TGLObject : public TGLLogicalShape public: TGLObject() : TGLLogicalShape(nullptr), fMultiColor(kFALSE) {} - virtual ~TGLObject() {} + ~TGLObject() override {} - virtual Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const; + Bool_t ShouldDLCache(const TGLRnrCtx& rnrCtx) const override; // Kept from TGLLogicalShape // virtual ELODAxes SupportedLODAxes() const { return kLODAxesNone; } // Changed from TGLLogicalShape - virtual Bool_t KeepDuringSmartRefresh() const { return kTRUE; } - virtual void UpdateBoundingBox(); + Bool_t KeepDuringSmartRefresh() const override { return kTRUE; } + void UpdateBoundingBox() override; // TGLObject virtuals virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) = 0; @@ -71,7 +71,7 @@ class TGLObject : public TGLLogicalShape // Interface to class .vs. classGL map. static TClass* GetGLRenderer(TClass* isa); - ClassDef(TGLObject, 0); // Base-class for direct OpenGL renderers + ClassDefOverride(TGLObject, 0); // Base-class for direct OpenGL renderers }; #endif diff --git a/graf3d/gl/inc/TGLOrthoCamera.h b/graf3d/gl/inc/TGLOrthoCamera.h index f8a31317a4941..870d77b4f841d 100644 --- a/graf3d/gl/inc/TGLOrthoCamera.h +++ b/graf3d/gl/inc/TGLOrthoCamera.h @@ -58,24 +58,24 @@ class TGLOrthoCamera : public TGLCamera public: TGLOrthoCamera(); TGLOrthoCamera(EType type, const TGLVector3 & hAxis, const TGLVector3 & vAxis); - virtual ~TGLOrthoCamera(); + ~TGLOrthoCamera() override; - virtual Bool_t IsOrthographic() const { return kTRUE; } + Bool_t IsOrthographic() const override { return kTRUE; } - virtual void Setup(const TGLBoundingBox & box, Bool_t reset=kTRUE); - virtual void Reset(); + void Setup(const TGLBoundingBox & box, Bool_t reset=kTRUE) override; + void Reset() override; - virtual Bool_t Dolly(Int_t delta, Bool_t mod1, Bool_t mod2); - virtual Bool_t Zoom (Int_t delta, Bool_t mod1, Bool_t mod2); + Bool_t Dolly(Int_t delta, Bool_t mod1, Bool_t mod2) override; + Bool_t Zoom (Int_t delta, Bool_t mod1, Bool_t mod2) override; using TGLCamera::Truck; - virtual Bool_t Truck(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2); - virtual Bool_t Rotate(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2); - virtual void Apply(const TGLBoundingBox & sceneBox, const TGLRect * pickRect = nullptr) const; + Bool_t Truck(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2) override; + Bool_t Rotate(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2) override; + void Apply(const TGLBoundingBox & sceneBox, const TGLRect * pickRect = nullptr) const override; // External scripting control // void Configure(Double_t left, Double_t right, Double_t top, Double_t bottom); - virtual void Configure(Double_t zoom, Double_t dolly, Double_t center[3], - Double_t hRotate, Double_t vRotate); + void Configure(Double_t zoom, Double_t dolly, Double_t center[3], + Double_t hRotate, Double_t vRotate) override; void SetEnableRotate(Bool_t x) { fEnableRotate = x; } Bool_t GetEnableRotate() const { return fEnableRotate; } @@ -92,7 +92,7 @@ class TGLOrthoCamera : public TGLCamera void SetZoom(Double_t x) { fZoom = x; } Double_t GetZoom() const { return fZoom; } - ClassDef(TGLOrthoCamera,1) // Camera for orthographic view. + ClassDefOverride(TGLOrthoCamera,1) // Camera for orthographic view. }; #endif // ROOT_TGLOrthoCamera diff --git a/graf3d/gl/inc/TGLOverlayButton.h b/graf3d/gl/inc/TGLOverlayButton.h index 81e5932c9b6af..cbc78f16939ae 100644 --- a/graf3d/gl/inc/TGLOverlayButton.h +++ b/graf3d/gl/inc/TGLOverlayButton.h @@ -46,13 +46,13 @@ class TGLOverlayButton : public TGLOverlayElement, public: TGLOverlayButton(TGLViewerBase *parent, const char *text, Float_t posx, Float_t posy, Float_t width, Float_t height); - virtual ~TGLOverlayButton() { } + ~TGLOverlayButton() override { } - virtual Bool_t MouseEnter(TGLOvlSelectRecord& selRec); - virtual Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, Event_t* event); - virtual void MouseLeave(); + Bool_t MouseEnter(TGLOvlSelectRecord& selRec) override; + Bool_t Handle(TGLRnrCtx& rnrCtx, TGLOvlSelectRecord& selRec, Event_t* event) override; + void MouseLeave() override; - virtual void Render(TGLRnrCtx& rnrCtx); + void Render(TGLRnrCtx& rnrCtx) override; virtual void ResetState() { fActiveID = -1; } virtual const char *GetText() const { return fText.Data(); } @@ -67,7 +67,7 @@ class TGLOverlayButton : public TGLOverlayElement, virtual void Clicked(TGLViewerBase *viewer); // *SIGNAL* - ClassDef(TGLOverlayButton, 0); // GL-overlay button. + ClassDefOverride(TGLOverlayButton, 0); // GL-overlay button. }; #endif diff --git a/graf3d/gl/inc/TGLPShapeObj.h b/graf3d/gl/inc/TGLPShapeObj.h index 1b591787c59fa..cd8728c3de346 100644 --- a/graf3d/gl/inc/TGLPShapeObj.h +++ b/graf3d/gl/inc/TGLPShapeObj.h @@ -26,15 +26,15 @@ class TGLPShapeObj : public TObject TGLPShapeObj() : TObject(), fPShape(nullptr), fViewer(nullptr) {} TGLPShapeObj(TGLPhysicalShape* sh, TGLViewer* v) : TObject(), fPShape(sh), fViewer(v) {} - virtual ~TGLPShapeObj() {} + ~TGLPShapeObj() override {} - virtual const char* GetName() const { return "Selected"; } + const char* GetName() const override { return "Selected"; } private: TGLPShapeObj(const TGLPShapeObj &); // Not implemented TGLPShapeObj& operator=(const TGLPShapeObj &); // Not implemented - ClassDef(TGLPShapeObj, 0) // This object wraps TGLPhysicalShape (not a TObject) + ClassDefOverride(TGLPShapeObj, 0) // This object wraps TGLPhysicalShape (not a TObject) }; #endif diff --git a/graf3d/gl/inc/TGLPShapeObjEditor.h b/graf3d/gl/inc/TGLPShapeObjEditor.h index 931463428aa87..93d40207cc181 100644 --- a/graf3d/gl/inc/TGLPShapeObjEditor.h +++ b/graf3d/gl/inc/TGLPShapeObjEditor.h @@ -70,20 +70,20 @@ class TGLPShapeObjEditor : public TGedFrame, void CreateGeoControls(); void CreateColorControls(); - virtual void DoRedraw(); + void DoRedraw() override; public: TGLPShapeObjEditor(const TGWindow *p = nullptr, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - ~TGLPShapeObjEditor(); + ~TGLPShapeObjEditor() override; // Virtuals from TGLPShapeRef - virtual void SetPShape(TGLPhysicalShape * shape); - virtual void PShapeModified(); + void SetPShape(TGLPhysicalShape * shape) override; + void PShapeModified() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; // geometry void SetCenter(const Double_t *center); @@ -104,7 +104,7 @@ class TGLPShapeObjEditor : public TGedFrame, void DoColorSlider(Int_t val); void DoColorButton(); - ClassDef(TGLPShapeObjEditor, 0); //GUI for editing attributes of a physical-shape. + ClassDefOverride(TGLPShapeObjEditor, 0); //GUI for editing attributes of a physical-shape. }; #endif diff --git a/graf3d/gl/inc/TGLPadPainter.h b/graf3d/gl/inc/TGLPadPainter.h index d45a26b4b0d5c..def4c1935b3fc 100644 --- a/graf3d/gl/inc/TGLPadPainter.h +++ b/graf3d/gl/inc/TGLPadPainter.h @@ -52,75 +52,75 @@ class TGLPadPainter : public TVirtualPadPainter { //Final overriders for TVirtualPadPainter pure virtual functions. //1. Part, which simply delegates to TVirtualX. //Line attributes. - Color_t GetLineColor() const; - Style_t GetLineStyle() const; - Width_t GetLineWidth() const; + Color_t GetLineColor() const override; + Style_t GetLineStyle() const override; + Width_t GetLineWidth() const override; - void SetLineColor(Color_t lcolor); - void SetLineStyle(Style_t lstyle); - void SetLineWidth(Width_t lwidth); + void SetLineColor(Color_t lcolor) override; + void SetLineStyle(Style_t lstyle) override; + void SetLineWidth(Width_t lwidth) override; //Fill attributes. - Color_t GetFillColor() const; - Style_t GetFillStyle() const; - Bool_t IsTransparent() const; + Color_t GetFillColor() const override; + Style_t GetFillStyle() const override; + Bool_t IsTransparent() const override; - void SetFillColor(Color_t fcolor); - void SetFillStyle(Style_t fstyle); - void SetOpacity(Int_t percent); + void SetFillColor(Color_t fcolor) override; + void SetFillStyle(Style_t fstyle) override; + void SetOpacity(Int_t percent) override; //Text attributes. - Short_t GetTextAlign() const; - Float_t GetTextAngle() const; - Color_t GetTextColor() const; - Font_t GetTextFont() const; - Float_t GetTextSize() const; - Float_t GetTextMagnitude() const; - - void SetTextAlign(Short_t align); - void SetTextAngle(Float_t tangle); - void SetTextColor(Color_t tcolor); - void SetTextFont(Font_t tfont); - void SetTextSize(Float_t tsize); - void SetTextSizePixels(Int_t npixels); + Short_t GetTextAlign() const override; + Float_t GetTextAngle() const override; + Color_t GetTextColor() const override; + Font_t GetTextFont() const override; + Float_t GetTextSize() const override; + Float_t GetTextMagnitude() const override; + + void SetTextAlign(Short_t align) override; + void SetTextAngle(Float_t tangle) override; + void SetTextColor(Color_t tcolor) override; + void SetTextFont(Font_t tfont) override; + void SetTextSize(Float_t tsize) override; + void SetTextSizePixels(Int_t npixels) override; //2. "Off-screen management" part. - Int_t CreateDrawable(UInt_t w, UInt_t h); - void ClearDrawable(); - void CopyDrawable(Int_t device, Int_t px, Int_t py); - void DestroyDrawable(Int_t device); - void SelectDrawable(Int_t device); + Int_t CreateDrawable(UInt_t w, UInt_t h) override; + void ClearDrawable() override; + void CopyDrawable(Int_t device, Int_t px, Int_t py) override; + void DestroyDrawable(Int_t device) override; + void SelectDrawable(Int_t device) override; - void InitPainter(); - void InvalidateCS(); - void LockPainter(); + void InitPainter() override; + void InvalidateCS() override; + void LockPainter() override; - void DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2); - void DrawLineNDC(Double_t u1, Double_t v1, Double_t u2, Double_t v2); + void DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2) override; + void DrawLineNDC(Double_t u1, Double_t v1, Double_t u2, Double_t v2) override; - void DrawBox(Double_t x1, Double_t y1, Double_t x2, Double_t y2, EBoxMode mode); + void DrawBox(Double_t x1, Double_t y1, Double_t x2, Double_t y2, EBoxMode mode) override; //TPad needs double and float versions. - void DrawFillArea(Int_t n, const Double_t *x, const Double_t *y); - void DrawFillArea(Int_t n, const Float_t *x, const Float_t *y); + void DrawFillArea(Int_t n, const Double_t *x, const Double_t *y) override; + void DrawFillArea(Int_t n, const Float_t *x, const Float_t *y) override; //TPad needs both double and float versions of DrawPolyLine. - void DrawPolyLine(Int_t n, const Double_t *x, const Double_t *y); - void DrawPolyLine(Int_t n, const Float_t *x, const Float_t *y); - void DrawPolyLineNDC(Int_t n, const Double_t *u, const Double_t *v); + void DrawPolyLine(Int_t n, const Double_t *x, const Double_t *y) override; + void DrawPolyLine(Int_t n, const Float_t *x, const Float_t *y) override; + void DrawPolyLineNDC(Int_t n, const Double_t *u, const Double_t *v) override; //TPad needs both versions. - void DrawPolyMarker(Int_t n, const Double_t *x, const Double_t *y); - void DrawPolyMarker(Int_t n, const Float_t *x, const Float_t *y); + void DrawPolyMarker(Int_t n, const Double_t *x, const Double_t *y) override; + void DrawPolyMarker(Int_t n, const Float_t *x, const Float_t *y) override; - void DrawText(Double_t x, Double_t y, const char *text, ETextMode mode); - void DrawText(Double_t, Double_t, const wchar_t *, ETextMode); - void DrawTextNDC(Double_t x, Double_t y, const char *text, ETextMode mode); - void DrawTextNDC(Double_t, Double_t, const wchar_t *, ETextMode); + void DrawText(Double_t x, Double_t y, const char *text, ETextMode mode) override; + void DrawText(Double_t, Double_t, const wchar_t *, ETextMode) override; + void DrawTextNDC(Double_t x, Double_t y, const char *text, ETextMode mode) override; + void DrawTextNDC(Double_t, Double_t, const wchar_t *, ETextMode) override; //jpg, png, gif and bmp output. - void SaveImage(TVirtualPad *pad, const char *fileName, Int_t type) const; + void SaveImage(TVirtualPad *pad, const char *fileName, Int_t type) const override; //TASImage support. void DrawPixels(const unsigned char *pixelData, UInt_t width, UInt_t height, - Int_t dstX, Int_t dstY, Bool_t enableBlending); + Int_t dstX, Int_t dstY, Bool_t enableBlending) override; private: @@ -151,7 +151,7 @@ class TGLPadPainter : public TVirtualPadPainter { TGLPadPainter(const TGLPadPainter &rhs); TGLPadPainter & operator = (const TGLPadPainter &rhs); - ClassDef(TGLPadPainter, 0) + ClassDefOverride(TGLPadPainter, 0) }; #endif diff --git a/graf3d/gl/inc/TGLParametric.h b/graf3d/gl/inc/TGLParametric.h index ce96ea1afc823..a1c6326283bec 100644 --- a/graf3d/gl/inc/TGLParametric.h +++ b/graf3d/gl/inc/TGLParametric.h @@ -72,17 +72,17 @@ class TGLParametricEquation : public TNamed { void EvalVertex(TGLVertex3 &newVertex, Double_t u, Double_t v)const; - Int_t DistancetoPrimitive(Int_t px, Int_t py); - void ExecuteEvent(Int_t event, Int_t px, Int_t py); - char *GetObjectInfo(Int_t px, Int_t py) const; - void Paint(Option_t *option); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + char *GetObjectInfo(Int_t px, Int_t py) const override; + void Paint(Option_t *option) override; private: TGLParametricEquation(const TGLParametricEquation &); TGLParametricEquation &operator = (const TGLParametricEquation &); - ClassDef(TGLParametricEquation, 0)//Equation of parametric surface. + ClassDefOverride(TGLParametricEquation, 0)//Equation of parametric surface. }; class TGLParametricPlot : public TGLPlotPainter { @@ -112,31 +112,31 @@ class TGLParametricPlot : public TGLPlotPainter { public: TGLParametricPlot(TGLParametricEquation *equation, TGLPlotCamera *camera); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - char *GetPlotInfo(Int_t px, Int_t py); - void AddOption(const TString &option); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + char *GetPlotInfo(Int_t px, Int_t py) override; + void AddOption(const TString &option) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; void InitColors(); - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; void SetSurfaceColor()const; TGLParametricPlot(const TGLParametricPlot &); TGLParametricPlot &operator = (const TGLParametricPlot &); - ClassDef(TGLParametricPlot, 0)//Parametric plot's painter. + ClassDefOverride(TGLParametricPlot, 0)//Parametric plot's painter. }; #endif diff --git a/graf3d/gl/inc/TGLParametricEquationGL.h b/graf3d/gl/inc/TGLParametricEquationGL.h index f79f5422f392f..8ab8c25518d72 100644 --- a/graf3d/gl/inc/TGLParametricEquationGL.h +++ b/graf3d/gl/inc/TGLParametricEquationGL.h @@ -30,19 +30,19 @@ class TGLParametricEquationGL : public TGLPlot3D public: TGLParametricEquationGL(); - virtual ~TGLParametricEquationGL(); + ~TGLParametricEquationGL() override; - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t KeepDuringSmartRefresh() const { return kFALSE; } + Bool_t KeepDuringSmartRefresh() const override { return kFALSE; } // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*); - ClassDef(TGLParametricEquationGL, 0); // GL renderer for TGLParametricEquation + ClassDefOverride(TGLParametricEquationGL, 0); // GL renderer for TGLParametricEquation }; #endif diff --git a/graf3d/gl/inc/TGLPerspectiveCamera.h b/graf3d/gl/inc/TGLPerspectiveCamera.h index adf74e865e690..780b6eb7a1eca 100644 --- a/graf3d/gl/inc/TGLPerspectiveCamera.h +++ b/graf3d/gl/inc/TGLPerspectiveCamera.h @@ -34,25 +34,25 @@ class TGLPerspectiveCamera : public TGLCamera public: TGLPerspectiveCamera(); TGLPerspectiveCamera(const TGLVector3 & hAxis, const TGLVector3 & vAxis); - virtual ~TGLPerspectiveCamera(); + ~TGLPerspectiveCamera() override; - virtual Bool_t IsPerspective() const { return kTRUE; } + Bool_t IsPerspective() const override { return kTRUE; } Double_t GetFOV() const { return fFOV; } void SetFOV(Double_t fov) { fFOV = fov; } - virtual void Setup(const TGLBoundingBox & box, Bool_t reset=kTRUE); - virtual void Reset(); - virtual Bool_t Zoom (Int_t delta, Bool_t mod1, Bool_t mod2); + void Setup(const TGLBoundingBox & box, Bool_t reset=kTRUE) override; + void Reset() override; + Bool_t Zoom (Int_t delta, Bool_t mod1, Bool_t mod2) override; using TGLCamera::Truck; - virtual Bool_t Truck(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2); - virtual void Apply(const TGLBoundingBox & box, const TGLRect * pickRect = nullptr) const; + Bool_t Truck(Int_t xDelta, Int_t yDelta, Bool_t mod1, Bool_t mod2) override; + void Apply(const TGLBoundingBox & box, const TGLRect * pickRect = nullptr) const override; // External scripting control - virtual void Configure(Double_t fov, Double_t dolly, Double_t center[3], - Double_t hRotate, Double_t vRotate); + void Configure(Double_t fov, Double_t dolly, Double_t center[3], + Double_t hRotate, Double_t vRotate) override; - ClassDef(TGLPerspectiveCamera,1) // Camera for perspective view. + ClassDefOverride(TGLPerspectiveCamera,1) // Camera for perspective view. }; #endif // ROOT_TGLPerspectiveCamera diff --git a/graf3d/gl/inc/TGLPlot3D.h b/graf3d/gl/inc/TGLPlot3D.h index f0cced21554e0..fb241afce4b08 100644 --- a/graf3d/gl/inc/TGLPlot3D.h +++ b/graf3d/gl/inc/TGLPlot3D.h @@ -35,15 +35,15 @@ class TGLPlot3D : public TGLObject public: TGLPlot3D(); - virtual ~TGLPlot3D(); + ~TGLPlot3D() override; - virtual Bool_t KeepDuringSmartRefresh() const { return kFALSE; } + Bool_t KeepDuringSmartRefresh() const override { return kFALSE; } static TGLPlot3D* CreatePlot(TH3 *h, TPolyMarker3D *pm); static TGLPlot3D* CreatePlot(TObject* obj, const Option_t* opt, TVirtualPad* pad); static TGLPlot3D* CreatePlot(TObject* obj, const Option_t* opt, Bool_t logx, Bool_t logy, Bool_t logz); - ClassDef(TGLPlot3D, 0); // Short description. + ClassDefOverride(TGLPlot3D, 0); // Short description. }; #endif diff --git a/graf3d/gl/inc/TGLPlotPainter.h b/graf3d/gl/inc/TGLPlotPainter.h index d5954612d86fe..ce4e3545fc72e 100644 --- a/graf3d/gl/inc/TGLPlotPainter.h +++ b/graf3d/gl/inc/TGLPlotPainter.h @@ -149,7 +149,7 @@ class TGLTH3Slice : public TNamed { void DrawSliceTextured(Double_t pos)const; void DrawSliceFrame(Int_t low, Int_t up)const; - ClassDef(TGLTH3Slice, 0) // TH3 slice + ClassDefOverride(TGLTH3Slice, 0) // TH3 slice }; @@ -237,10 +237,10 @@ class TGLPlotPainter : public TVirtualGLPainter { virtual void InitGL()const = 0; virtual void DeInitGL()const = 0; virtual void DrawPlot()const = 0; - virtual void Paint(); + void Paint() override; //Checks, if mouse cursor is above plot. - virtual Bool_t PlotSelected(Int_t px, Int_t py); + Bool_t PlotSelected(Int_t px, Int_t py) override; //Init geometry does plot's specific initialization. virtual Bool_t InitGeometry() = 0; @@ -297,7 +297,7 @@ class TGLPlotPainter : public TVirtualGLPainter { void RestoreModelviewMatrix()const; void RestoreProjectionMatrix()const; - ClassDef(TGLPlotPainter, 0) //Base for gl plots + ClassDefOverride(TGLPlotPainter, 0) //Base for gl plots }; /* diff --git a/graf3d/gl/inc/TGLPolyLine.h b/graf3d/gl/inc/TGLPolyLine.h index 8a5692e93af6d..2f5dddddbb6ad 100644 --- a/graf3d/gl/inc/TGLPolyLine.h +++ b/graf3d/gl/inc/TGLPolyLine.h @@ -29,9 +29,9 @@ class TGLPolyLine : public TGLLogicalShape public: TGLPolyLine(const TBuffer3D & buffer); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TGLPolyLine,0) // a polyline logical shape + ClassDefOverride(TGLPolyLine,0) // a polyline logical shape }; #endif diff --git a/graf3d/gl/inc/TGLPolyMarker.h b/graf3d/gl/inc/TGLPolyMarker.h index 1d3a5373c34b4..61390941e05b7 100644 --- a/graf3d/gl/inc/TGLPolyMarker.h +++ b/graf3d/gl/inc/TGLPolyMarker.h @@ -31,14 +31,14 @@ class TGLPolyMarker : public TGLLogicalShape public: TGLPolyMarker(const TBuffer3D & buffer); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } private: void DrawStars()const; - ClassDef(TGLPolyMarker,0) // a polymarker logical shape + ClassDefOverride(TGLPolyMarker,0) // a polymarker logical shape }; #endif diff --git a/graf3d/gl/inc/TGLRotateManip.h b/graf3d/gl/inc/TGLRotateManip.h index a6c41074f88f5..5b0e508bd3d34 100644 --- a/graf3d/gl/inc/TGLRotateManip.h +++ b/graf3d/gl/inc/TGLRotateManip.h @@ -44,13 +44,13 @@ class TGLRotateManip : public TGLManip public: TGLRotateManip(); TGLRotateManip(TGLPhysicalShape* shape); - virtual ~TGLRotateManip(); + ~TGLRotateManip() override; - virtual void Draw(const TGLCamera& camera) const; - virtual Bool_t HandleButton(const Event_t& event, const TGLCamera& camera); - virtual Bool_t HandleMotion(const Event_t& event, const TGLCamera& camera); + void Draw(const TGLCamera& camera) const override; + Bool_t HandleButton(const Event_t& event, const TGLCamera& camera) override; + Bool_t HandleMotion(const Event_t& event, const TGLCamera& camera) override; - ClassDef(TGLRotateManip, 0); // GL rotation manipulator widget + ClassDefOverride(TGLRotateManip, 0); // GL rotation manipulator widget }; #endif diff --git a/graf3d/gl/inc/TGLSAFrame.h b/graf3d/gl/inc/TGLSAFrame.h index 070f793ccf8d9..19b3b6f0d69db 100644 --- a/graf3d/gl/inc/TGLSAFrame.h +++ b/graf3d/gl/inc/TGLSAFrame.h @@ -37,12 +37,12 @@ class TGLSAFrame : public TGMainFrame public: TGLSAFrame(TGLSAViewer &viewer); TGLSAFrame(const TGWindow *parent, TGLSAViewer &viewer); - virtual ~TGLSAFrame(); + ~TGLSAFrame() override; - Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); - void CloseWindow(); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; + void CloseWindow() override; - ClassDef(TGLSAFrame, 0) // GUI frame for standalone viewer + ClassDefOverride(TGLSAFrame, 0) // GUI frame for standalone viewer }; #endif diff --git a/graf3d/gl/inc/TGLSAViewer.h b/graf3d/gl/inc/TGLSAViewer.h index eee1c02b0d1a8..4ce00ba69dcae 100644 --- a/graf3d/gl/inc/TGLSAViewer.h +++ b/graf3d/gl/inc/TGLSAViewer.h @@ -96,14 +96,14 @@ class TGLSAViewer : public TGLViewer TGLSAViewer(TVirtualPad* pad, TGLFormat* format=nullptr); TGLSAViewer(const TGWindow* parent, TVirtualPad *pad, TGedEditor *ged=nullptr, TGLFormat* format=nullptr); - ~TGLSAViewer(); + ~TGLSAViewer() override; - virtual void CreateGLWidget(); - virtual void DestroyGLWidget(); + void CreateGLWidget() override; + void DestroyGLWidget() override; - virtual const char* GetName() const { return "GLViewer"; } + const char* GetName() const override { return "GLViewer"; } - virtual void SelectionChanged(); + void SelectionChanged() override; void Show(); void Close(); @@ -129,7 +129,7 @@ class TGLSAViewer : public TGLViewer static void SetMenuHidingTimeout(Long_t timeout); - ClassDef(TGLSAViewer, 0); // Standalone GL viewer. + ClassDefOverride(TGLSAViewer, 0); // Standalone GL viewer. }; #endif diff --git a/graf3d/gl/inc/TGLScaleManip.h b/graf3d/gl/inc/TGLScaleManip.h index 7d3c84f7e097c..c58526e054943 100644 --- a/graf3d/gl/inc/TGLScaleManip.h +++ b/graf3d/gl/inc/TGLScaleManip.h @@ -35,13 +35,13 @@ class TGLScaleManip : public TGLManip public: TGLScaleManip(); TGLScaleManip(TGLPhysicalShape * shape); - virtual ~TGLScaleManip(); + ~TGLScaleManip() override; - virtual void Draw(const TGLCamera & camera) const; - virtual Bool_t HandleButton(const Event_t & event, const TGLCamera & camera); - virtual Bool_t HandleMotion(const Event_t & event, const TGLCamera & camera); + void Draw(const TGLCamera & camera) const override; + Bool_t HandleButton(const Event_t & event, const TGLCamera & camera) override; + Bool_t HandleMotion(const Event_t & event, const TGLCamera & camera) override; - ClassDef(TGLScaleManip,0) // GL scaling manipulator widget + ClassDefOverride(TGLScaleManip,0) // GL scaling manipulator widget }; #endif diff --git a/graf3d/gl/inc/TGLScene.h b/graf3d/gl/inc/TGLScene.h index 7c78e7ce20a42..5c115d9c4e4af 100644 --- a/graf3d/gl/inc/TGLScene.h +++ b/graf3d/gl/inc/TGLScene.h @@ -96,7 +96,7 @@ class TGLScene : public TGLSceneBase DrawElementPtrVec_t fSelTranspElements; TSceneInfo(TGLViewerBase* view=nullptr, TGLScene* scene=nullptr); - virtual ~TSceneInfo(); + ~TSceneInfo() override; void ClearAfterRebuild(); void ClearAfterUpdate(); @@ -144,32 +144,32 @@ class TGLScene : public TGLSceneBase public: TGLScene(); - virtual ~TGLScene(); + ~TGLScene() override; - virtual void CalcBoundingBox() const; + void CalcBoundingBox() const override; - virtual TSceneInfo* CreateSceneInfo(TGLViewerBase* view); - virtual void RebuildSceneInfo(TGLRnrCtx& rnrCtx); - virtual void UpdateSceneInfo(TGLRnrCtx& rnrCtx); - virtual void LodifySceneInfo(TGLRnrCtx& rnrCtx); + TSceneInfo* CreateSceneInfo(TGLViewerBase* view) override; + void RebuildSceneInfo(TGLRnrCtx& rnrCtx) override; + void UpdateSceneInfo(TGLRnrCtx& rnrCtx) override; + void LodifySceneInfo(TGLRnrCtx& rnrCtx) override; // Rendering - virtual void PreDraw (TGLRnrCtx& rnrCtx); + void PreDraw (TGLRnrCtx& rnrCtx) override; // virtual void PreRender (TGLRnrCtx& rnrCtx); // virtual void Render (TGLRnrCtx& rnrCtx); - virtual void RenderOpaque (TGLRnrCtx& rnrCtx); - virtual void RenderTransp (TGLRnrCtx& rnrCtx); - virtual void RenderSelOpaque(TGLRnrCtx& rnrCtx); - virtual void RenderSelTransp(TGLRnrCtx& rnrCtx); - virtual void RenderSelOpaqueForHighlight(TGLRnrCtx& rnrCtx); - virtual void RenderSelTranspForHighlight(TGLRnrCtx& rnrCtx); + void RenderOpaque (TGLRnrCtx& rnrCtx) override; + void RenderTransp (TGLRnrCtx& rnrCtx) override; + void RenderSelOpaque(TGLRnrCtx& rnrCtx) override; + void RenderSelTransp(TGLRnrCtx& rnrCtx) override; + void RenderSelOpaqueForHighlight(TGLRnrCtx& rnrCtx) override; + void RenderSelTranspForHighlight(TGLRnrCtx& rnrCtx) override; virtual void RenderHighlight(TGLRnrCtx& rnrCtx, DrawElementPtrVec_t& elVec); // virtual void PostRender(TGLRnrCtx& rnrCtx); - virtual void PostDraw (TGLRnrCtx& rnrCtx); + void PostDraw (TGLRnrCtx& rnrCtx) override; virtual void RenderAllPasses(TGLRnrCtx& rnrCtx, DrawElementPtrVec_t& elVec, @@ -182,13 +182,13 @@ class TGLScene : public TGLSceneBase const TGLPlaneSet_t* clipPlanes = nullptr); // Selection - virtual Bool_t ResolveSelectRecord(TGLSelectRecord& rec, Int_t curIdx); + Bool_t ResolveSelectRecord(TGLSelectRecord& rec, Int_t curIdx) override; // Basic logical shape management virtual void AdoptLogical(TGLLogicalShape& shape); virtual Bool_t DestroyLogical(TObject* logid, Bool_t mustFind=kTRUE); virtual Int_t DestroyLogicals(); - virtual TGLLogicalShape* FindLogical(TObject* logid) const; + TGLLogicalShape* FindLogical(TObject* logid) const override; // Basic physical shape management virtual void AdoptPhysical(TGLPhysicalShape& shape); @@ -241,7 +241,7 @@ class TGLScene : public TGLSceneBase static Bool_t IsOutside(const TGLBoundingBox& box, const TGLPlaneSet_t& planes); - ClassDef(TGLScene, 0); // Standard ROOT OpenGL scene with logial/physical shapes. + ClassDefOverride(TGLScene, 0); // Standard ROOT OpenGL scene with logial/physical shapes. }; diff --git a/graf3d/gl/inc/TGLSceneBase.h b/graf3d/gl/inc/TGLSceneBase.h index 0b1caf8ba6f4f..2ed91b89d066a 100644 --- a/graf3d/gl/inc/TGLSceneBase.h +++ b/graf3d/gl/inc/TGLSceneBase.h @@ -70,13 +70,13 @@ class TGLSceneBase : public TGLLockable // : public TObject / TNamed public: TGLSceneBase(); - virtual ~TGLSceneBase(); + ~TGLSceneBase() override; void AddViewer(TGLViewerBase* viewer); void RemoveViewer(TGLViewerBase* viewer); void TagViewersChanged(); - virtual const char* LockIdStr() const; + const char* LockIdStr() const override; virtual const char *GetName() const { return fName; } virtual const char *GetTitle() const { return fTitle; } @@ -139,7 +139,7 @@ class TGLSceneBase : public TGLLockable // : public TObject / TNamed { if (!fBoundingBoxValid) CalcBoundingBox(); return fBoundingBox; } - ClassDef(TGLSceneBase, 0) // Base-class for OpenGL scenes. + ClassDefOverride(TGLSceneBase, 0) // Base-class for OpenGL scenes. }; // endclass TGLSceneBase diff --git a/graf3d/gl/inc/TGLScenePad.h b/graf3d/gl/inc/TGLScenePad.h index ef34c338e1827..6f0c056cd6813 100644 --- a/graf3d/gl/inc/TGLScenePad.h +++ b/graf3d/gl/inc/TGLScenePad.h @@ -57,7 +57,7 @@ class TGLScenePad : public TVirtualViewer3D, public TGLScene { public: TGLScenePad(TVirtualPad* pad); - virtual ~TGLScenePad() {} + ~TGLScenePad() override {} TVirtualPad* GetPad() const { return fPad; } void SetPad(TVirtualPad* p) { fPad = p; } @@ -75,27 +75,27 @@ class TGLScenePad : public TVirtualViewer3D, public TGLScene { // TVirtualViewer3D interface - virtual Bool_t CanLoopOnPrimitives() const { return kTRUE; } - virtual void PadPaint(TVirtualPad* pad); - virtual void ObjectPaint(TObject* obj, Option_t* opt=""); + Bool_t CanLoopOnPrimitives() const override { return kTRUE; } + void PadPaint(TVirtualPad* pad) override; + void ObjectPaint(TObject* obj, Option_t* opt="") override; // For now handled by viewer - virtual Int_t DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/) { return 9999; } - virtual void ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) {} + Int_t DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/) override { return 9999; } + void ExecuteEvent(Int_t /*event*/, Int_t /*px*/, Int_t /*py*/) override {} - virtual Bool_t PreferLocalFrame() const { return kTRUE; } + Bool_t PreferLocalFrame() const override { return kTRUE; } - virtual void BeginScene(); - virtual Bool_t BuildingScene() const { return CurrentLock() == kModifyLock; } - virtual void EndScene(); + void BeginScene() override; + Bool_t BuildingScene() const override { return CurrentLock() == kModifyLock; } + void EndScene() override; - virtual Int_t AddObject(const TBuffer3D& buffer, Bool_t* addChildren = nullptr); - virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D& buffer, Bool_t* addChildren = nullptr); - virtual Bool_t OpenComposite(const TBuffer3D& buffer, Bool_t* addChildren = nullptr); - virtual void CloseComposite(); - virtual void AddCompositeOp(UInt_t operation); + Int_t AddObject(const TBuffer3D& buffer, Bool_t* addChildren = nullptr) override; + Int_t AddObject(UInt_t physicalID, const TBuffer3D& buffer, Bool_t* addChildren = nullptr) override; + Bool_t OpenComposite(const TBuffer3D& buffer, Bool_t* addChildren = nullptr) override; + void CloseComposite() override; + void AddCompositeOp(UInt_t operation) override; - ClassDef(TGLScenePad, 0); // GL-scene filled via TPad-TVirtualViewer interface. + ClassDefOverride(TGLScenePad, 0); // GL-scene filled via TPad-TVirtualViewer interface. }; #endif diff --git a/graf3d/gl/inc/TGLSelectRecord.h b/graf3d/gl/inc/TGLSelectRecord.h index 43e58df11bf95..d7044db5d9c19 100644 --- a/graf3d/gl/inc/TGLSelectRecord.h +++ b/graf3d/gl/inc/TGLSelectRecord.h @@ -94,12 +94,12 @@ class TGLSelectRecord : public TGLSelectRecordBase TGLSelectRecord(); TGLSelectRecord(UInt_t* data); TGLSelectRecord(const TGLSelectRecord& rec); - virtual ~TGLSelectRecord(); + ~TGLSelectRecord() override; TGLSelectRecord& operator=(const TGLSelectRecord& rec); - virtual void Set(UInt_t* data); - virtual void Reset(); + void Set(UInt_t* data) override; + void Reset() override; Bool_t GetTransparent() const { return fTransparent; } TGLSceneInfo * GetSceneInfo() const { return fSceneInfo; } @@ -128,7 +128,7 @@ class TGLSelectRecord : public TGLSelectRecordBase static Bool_t AreSameSelectionWise(const TGLSelectRecord& r1, const TGLSelectRecord& r2); - ClassDef(TGLSelectRecord, 0) // Standard GL selection record. + ClassDefOverride(TGLSelectRecord, 0) // Standard GL selection record. }; @@ -146,17 +146,17 @@ class TGLOvlSelectRecord : public TGLSelectRecordBase TGLOvlSelectRecord(); TGLOvlSelectRecord(UInt_t* data); TGLOvlSelectRecord(const TGLOvlSelectRecord& rec); - virtual ~TGLOvlSelectRecord(); + ~TGLOvlSelectRecord() override; TGLOvlSelectRecord& operator=(const TGLOvlSelectRecord& rec); - virtual void Set(UInt_t* data); - virtual void Reset(); + void Set(UInt_t* data) override; + void Reset() override; TGLOverlayElement* GetOvlElement() const { return fOvlElement; } void SetOvlElement(TGLOverlayElement* e) { fOvlElement = e; } - ClassDef(TGLOvlSelectRecord, 0) // Standard GL overlay-selection record. + ClassDefOverride(TGLOvlSelectRecord, 0) // Standard GL overlay-selection record. }; #endif diff --git a/graf3d/gl/inc/TGLSphere.h b/graf3d/gl/inc/TGLSphere.h index 0401f10bef226..7323dcd9fa1eb 100644 --- a/graf3d/gl/inc/TGLSphere.h +++ b/graf3d/gl/inc/TGLSphere.h @@ -26,13 +26,13 @@ class TGLSphere : public TGLLogicalShape public: TGLSphere(const TBuffer3DSphere &buffer); - virtual UInt_t DLOffset(Short_t lod) const; + UInt_t DLOffset(Short_t lod) const override; - virtual ELODAxes SupportedLODAxes() const { return kLODAxesAll; } - virtual Short_t QuantizeShapeLOD(Short_t shapeLOD, Short_t combiLOD) const; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + ELODAxes SupportedLODAxes() const override { return kLODAxesAll; } + Short_t QuantizeShapeLOD(Short_t shapeLOD, Short_t combiLOD) const override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - ClassDef(TGLSphere,0); // a spherical logical shape + ClassDefOverride(TGLSphere,0); // a spherical logical shape }; #endif diff --git a/graf3d/gl/inc/TGLSurfacePainter.h b/graf3d/gl/inc/TGLSurfacePainter.h index ad2f9bce8f9e0..22c111d466cdf 100644 --- a/graf3d/gl/inc/TGLSurfacePainter.h +++ b/graf3d/gl/inc/TGLSurfacePainter.h @@ -65,18 +65,18 @@ class TGLSurfacePainter : public TGLPlotPainter { TGLSurfacePainter(TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); //TGLPlotPainter's final-overriders. - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; void SetNormals(); void SetSurfaceColor()const; @@ -87,9 +87,9 @@ class TGLSurfacePainter : public TGLPlotPainter { Bool_t InitGeometrySpherical(); void DrawProjections()const; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; void ClampZ(Double_t &zVal)const; @@ -104,11 +104,11 @@ class TGLSurfacePainter : public TGLPlotPainter { Bool_t HasProjections()const; void DrawPalette()const; - void DrawPaletteAxis()const; + void DrawPaletteAxis()const override; static TRandom *fgRandom; - ClassDef(TGLSurfacePainter, 0)//Surface painter. + ClassDefOverride(TGLSurfacePainter, 0)//Surface painter. }; #endif diff --git a/graf3d/gl/inc/TGLTF3Painter.h b/graf3d/gl/inc/TGLTF3Painter.h index 4944f87ca4eee..cfaadaa5d839c 100644 --- a/graf3d/gl/inc/TGLTF3Painter.h +++ b/graf3d/gl/inc/TGLTF3Painter.h @@ -47,18 +47,18 @@ class TGLTF3Painter : public TGLPlotPainter { public: TGLTF3Painter(TF3 *fun, TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; // void DrawToSelectionBuffer()const; void DrawDefaultPlot()const; @@ -68,11 +68,11 @@ class TGLTF3Painter : public TGLPlotPainter { void SetSurfaceColor()const; Bool_t HasSections()const; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; - ClassDef(TGLTF3Painter, 0) // GL TF3 painter. + ClassDefOverride(TGLTF3Painter, 0) // GL TF3 painter. }; /* @@ -113,22 +113,22 @@ class TGLIsoPainter : public TGLPlotPainter { TGLIsoPainter(TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); //TGLPlotPainter final-overriders. - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &option); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &option) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //TGLPlotPainter final-overriders. - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawPlot()const override; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; //Auxiliary methods. Bool_t HasSections()const; void SetSurfaceColor(Int_t ind)const; @@ -139,7 +139,7 @@ class TGLIsoPainter : public TGLPlotPainter { TGLIsoPainter(const TGLIsoPainter &); TGLIsoPainter &operator = (const TGLIsoPainter &); - ClassDef(TGLIsoPainter, 0) // Iso option for TH3. + ClassDefOverride(TGLIsoPainter, 0) // Iso option for TH3. }; #endif diff --git a/graf3d/gl/inc/TGLTH3Composition.h b/graf3d/gl/inc/TGLTH3Composition.h index a135cd7ba4490..c028c852991c8 100644 --- a/graf3d/gl/inc/TGLTH3Composition.h +++ b/graf3d/gl/inc/TGLTH3Composition.h @@ -38,10 +38,10 @@ class TGLTH3Composition : public TH3C { //These are functions for TPad and //TPad's standard machinery (picking, painting). - Int_t DistancetoPrimitive(Int_t px, Int_t py); - void ExecuteEvent(Int_t event, Int_t px, Int_t py); - char *GetObjectInfo(Int_t px, Int_t py) const; - void Paint(Option_t *option); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + char *GetObjectInfo(Int_t px, Int_t py) const override; + void Paint(Option_t *option) override; private: void CheckRanges(const TH3 *hist); @@ -54,7 +54,7 @@ class TGLTH3Composition : public TH3C { TGLTH3Composition(const TGLTH3Composition &rhs); TGLTH3Composition &operator = (const TGLTH3Composition &); - ClassDef(TGLTH3Composition, 0)//Composition of TH3 objects. + ClassDefOverride(TGLTH3Composition, 0)//Composition of TH3 objects. }; // @@ -66,24 +66,24 @@ class TGLTH3CompositionPainter: public TGLPlotPainter { TGLPlotCoordinates *coord); //TGLPlotPainter final-overriders. - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &option); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &option) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //TGLPlotPainter final-overriders. - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; //Empty overriders. - void DrawSectionXOZ()const{} - void DrawSectionYOZ()const{} - void DrawSectionXOY()const{} + void DrawSectionXOZ()const override{} + void DrawSectionYOZ()const override{} + void DrawSectionXOY()const override{} void SetColor(Int_t color)const; @@ -95,7 +95,7 @@ class TGLTH3CompositionPainter: public TGLPlotPainter { TGLTH3CompositionPainter(const TGLTH3CompositionPainter &rhs); TGLTH3CompositionPainter &operator = (const TGLTH3CompositionPainter &rhs); - ClassDef(TGLTH3CompositionPainter, 0)//Painter to draw several TH3. + ClassDefOverride(TGLTH3CompositionPainter, 0)//Painter to draw several TH3. }; diff --git a/graf3d/gl/inc/TGLText.h b/graf3d/gl/inc/TGLText.h index 3057ac8077e53..7beb3a8a5d7a8 100644 --- a/graf3d/gl/inc/TGLText.h +++ b/graf3d/gl/inc/TGLText.h @@ -32,7 +32,7 @@ class TGLText : public TAttText { public: TGLText(); TGLText(Double_t x, Double_t y, Double_t z, const char *text); - virtual ~TGLText(); + ~TGLText() override; FTFont* GetFont() { return fGLTextFont; } @@ -43,7 +43,7 @@ class TGLText : public TAttText { void BBox(const char* string, float& llx, float& lly, float& llz, float& urx, float& ury, float& urz); - ClassDef(TGLText,0) // a GL text + ClassDefOverride(TGLText,0) // a GL text }; #endif diff --git a/graf3d/gl/inc/TGLTransManip.h b/graf3d/gl/inc/TGLTransManip.h index 21182d9290e87..14ccffaa5a48c 100644 --- a/graf3d/gl/inc/TGLTransManip.h +++ b/graf3d/gl/inc/TGLTransManip.h @@ -31,12 +31,12 @@ class TGLTransManip : public TGLManip public: TGLTransManip(); TGLTransManip(TGLPhysicalShape * shape); - virtual ~TGLTransManip(); + ~TGLTransManip() override; - virtual void Draw(const TGLCamera & camera) const; - virtual Bool_t HandleMotion(const Event_t & event, const TGLCamera & camera); + void Draw(const TGLCamera & camera) const override; + Bool_t HandleMotion(const Event_t & event, const TGLCamera & camera) override; - ClassDef(TGLTransManip,0) // GL translation manipulator widget + ClassDefOverride(TGLTransManip,0) // GL translation manipulator widget }; #endif diff --git a/graf3d/gl/inc/TGLViewer.h b/graf3d/gl/inc/TGLViewer.h index 1d31766220125..6da9f237852f3 100644 --- a/graf3d/gl/inc/TGLViewer.h +++ b/graf3d/gl/inc/TGLViewer.h @@ -166,7 +166,7 @@ class TGLViewer : public TVirtualViewer3D, // Methods /////////////////////////////////////////////////////////////////////// - virtual void SetupClipObject(); + void SetupClipObject() override; // Drawing - can tidy up/remove lots when TGLManager added void InitGL(); @@ -194,31 +194,31 @@ class TGLViewer : public TVirtualViewer3D, public: TGLViewer(TVirtualPad* pad, Int_t x, Int_t y, Int_t width, Int_t height); TGLViewer(TVirtualPad* pad); - virtual ~TGLViewer(); + ~TGLViewer() override; // TVirtualViewer3D interface ... mostly a facade // Forward to TGLScenePad - virtual Bool_t CanLoopOnPrimitives() const { return kTRUE; } - virtual void PadPaint(TVirtualPad* pad); + Bool_t CanLoopOnPrimitives() const override { return kTRUE; } + void PadPaint(TVirtualPad* pad) override; // Actually used by GL-in-pad - virtual Int_t DistancetoPrimitive(Int_t px, Int_t py); - virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; // Only implemented because they're abstract ... should throw an // exception or assert they are not called. - virtual Bool_t PreferLocalFrame() const { return kTRUE; } - virtual void BeginScene() {} - virtual Bool_t BuildingScene() const { return kFALSE; } - virtual void EndScene() {} - virtual Int_t AddObject(const TBuffer3D&, Bool_t* = nullptr) { return TBuffer3D::kNone; } - virtual Int_t AddObject(UInt_t, const TBuffer3D&, Bool_t* = nullptr) { return TBuffer3D::kNone; } - virtual Bool_t OpenComposite(const TBuffer3D&, Bool_t* = nullptr) { return kFALSE; } - virtual void CloseComposite() {} - virtual void AddCompositeOp(UInt_t) {} - - virtual void PrintObjects(); - virtual void ResetCameras() { SetupCameras(kTRUE); } - virtual void ResetCamerasAfterNextUpdate() { fResetCamerasOnNextUpdate = kTRUE; } + Bool_t PreferLocalFrame() const override { return kTRUE; } + void BeginScene() override {} + Bool_t BuildingScene() const override { return kFALSE; } + void EndScene() override {} + Int_t AddObject(const TBuffer3D&, Bool_t* = nullptr) override { return TBuffer3D::kNone; } + Int_t AddObject(UInt_t, const TBuffer3D&, Bool_t* = nullptr) override { return TBuffer3D::kNone; } + Bool_t OpenComposite(const TBuffer3D&, Bool_t* = nullptr) override { return kFALSE; } + void CloseComposite() override {} + void AddCompositeOp(UInt_t) override {} + + void PrintObjects() override; + void ResetCameras() override { SetupCameras(kTRUE); } + void ResetCamerasAfterNextUpdate() override { fResetCamerasOnNextUpdate = kTRUE; } TGLWidget* GetGLWidget() { return fGLWidget; } @@ -312,9 +312,9 @@ class TGLViewer : public TVirtualViewer3D, // Request methods post cross thread request via TROOT::ProcessLineFast(). void RequestDraw(Short_t LOD = TGLRnrCtx::kLODMed); // Cross thread draw request - virtual void PreRender(); - virtual void Render(); - virtual void PostRender(); + void PreRender() override; + void Render() override; + void PostRender() override; void DoDraw(Bool_t swap_buffers=kTRUE); void DoDrawMono(Bool_t swap_buffers); void DoDrawStereo(Bool_t swap_buffers); @@ -385,14 +385,14 @@ class TGLViewer : public TVirtualViewer3D, virtual void OverlayDragFinished(); virtual void RefreshPadEditor(TObject* obj=nullptr); - virtual void RemoveOverlayElement(TGLOverlayElement* el); + void RemoveOverlayElement(TGLOverlayElement* el) override; TGLSelectRecord& GetSelRec() { return fSelRec; } TGLOvlSelectRecord& GetOvlSelRec() { return fOvlSelRec; } TGLOverlayElement* GetCurrentOvlElm() const { return fCurrentOvlElm; } void ClearCurrentOvlElm(); - ClassDef(TGLViewer,0) // Standard ROOT GL viewer. + ClassDefOverride(TGLViewer,0) // Standard ROOT GL viewer. }; @@ -407,7 +407,7 @@ class TGLRedrawTimer : public TTimer public: TGLRedrawTimer(TGLViewer & viewer) : fViewer(viewer), fRedrawLOD(TGLRnrCtx::kLODHigh), fPending(kFALSE) {} - ~TGLRedrawTimer() {} + ~TGLRedrawTimer() override {} void RequestDraw(Int_t milliSec, Short_t redrawLOD) { if (fPending) TurnOff(); else fPending = kTRUE; @@ -415,11 +415,11 @@ class TGLRedrawTimer : public TTimer TTimer::Start(milliSec, kTRUE); } Bool_t IsPending() const { return fPending; } - virtual void Stop() + void Stop() override { if (fPending) { TurnOff(); fPending = kFALSE; } } - Bool_t Notify() + Bool_t Notify() override { TurnOff(); fPending = kFALSE; diff --git a/graf3d/gl/inc/TGLViewerBase.h b/graf3d/gl/inc/TGLViewerBase.h index 360ef9613792e..5dcab1b96119f 100644 --- a/graf3d/gl/inc/TGLViewerBase.h +++ b/graf3d/gl/inc/TGLViewerBase.h @@ -83,9 +83,9 @@ class TGLViewerBase : public TGLLockable // : public TObject public: TGLViewerBase(); - virtual ~TGLViewerBase(); + ~TGLViewerBase() override; - virtual const char* LockIdStr() const; + const char* LockIdStr() const override; TGLSceneInfo* AddScene(TGLSceneBase* scene); void RemoveScene(TGLSceneBase* scene); @@ -158,7 +158,7 @@ class TGLViewerBase : public TGLLockable // : public TObject TGLRnrCtx* GetRnrCtx() const { return fRnrCtx; } TGLRnrCtx& RnrCtx() const { return *fRnrCtx; } - ClassDef(TGLViewerBase, 0); // GL Viewer base-class. + ClassDefOverride(TGLViewerBase, 0); // GL Viewer base-class. }; diff --git a/graf3d/gl/inc/TGLViewerEditor.h b/graf3d/gl/inc/TGLViewerEditor.h index a777af9a68efe..70cc4a34ba30c 100644 --- a/graf3d/gl/inc/TGLViewerEditor.h +++ b/graf3d/gl/inc/TGLViewerEditor.h @@ -122,11 +122,11 @@ class TGLViewerEditor : public TGedFrame public: TGLViewerEditor(const TGWindow *p=nullptr, Int_t width=140, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); - ~TGLViewerEditor(); + ~TGLViewerEditor() override; virtual void ViewerRedraw(); - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void SetGuides(); void DoClearColor(Pixel_t color); @@ -161,7 +161,7 @@ class TGLViewerEditor : public TGedFrame static TGNumberEntry* MakeLabeledNEntry(TGCompositeFrame* p, const char* name, Int_t labelw, Int_t nd=7, Int_t s=5); - ClassDef(TGLViewerEditor, 0); //GUI for editing TGLViewer attributes + ClassDefOverride(TGLViewerEditor, 0); //GUI for editing TGLViewer attributes }; #endif diff --git a/graf3d/gl/inc/TGLVoxelPainter.h b/graf3d/gl/inc/TGLVoxelPainter.h index 4689c2b86671c..5d34ccf584fac 100644 --- a/graf3d/gl/inc/TGLVoxelPainter.h +++ b/graf3d/gl/inc/TGLVoxelPainter.h @@ -27,27 +27,27 @@ class TGLVoxelPainter : public TGLPlotPainter { public: TGLVoxelPainter(TH1 *hist, TGLPlotCamera *camera, TGLPlotCoordinates *coord); - char *GetPlotInfo(Int_t px, Int_t py); - Bool_t InitGeometry(); - void StartPan(Int_t px, Int_t py); - void Pan(Int_t px, Int_t py); - void AddOption(const TString &stringOption); - void ProcessEvent(Int_t event, Int_t px, Int_t py); + char *GetPlotInfo(Int_t px, Int_t py) override; + Bool_t InitGeometry() override; + void StartPan(Int_t px, Int_t py) override; + void Pan(Int_t px, Int_t py) override; + void AddOption(const TString &stringOption) override; + void ProcessEvent(Int_t event, Int_t px, Int_t py) override; private: //Overriders - void InitGL()const; - void DeInitGL()const; + void InitGL()const override; + void DeInitGL()const override; - void DrawPlot()const; + void DrawPlot()const override; - void DrawSectionXOZ()const; - void DrawSectionYOZ()const; - void DrawSectionXOY()const; + void DrawSectionXOZ()const override; + void DrawSectionYOZ()const override; + void DrawSectionXOY()const override; void DrawPalette()const; - void DrawPaletteAxis()const; + void DrawPaletteAxis()const override; //Aux. functions. void FindVoxelColor(Double_t binContent, Float_t *rgba)const; @@ -58,7 +58,7 @@ class TGLVoxelPainter : public TGLPlotPainter { TF1 *fTransferFunc; - ClassDef(TGLVoxelPainter, 0)//Voxel painter + ClassDefOverride(TGLVoxelPainter, 0)//Voxel painter }; #endif diff --git a/graf3d/gl/inc/TGLWidget.h b/graf3d/gl/inc/TGLWidget.h index 463cdb054349f..6c52b1e19da7c 100644 --- a/graf3d/gl/inc/TGLWidget.h +++ b/graf3d/gl/inc/TGLWidget.h @@ -54,36 +54,36 @@ class TGLWidget : public TGFrame, public TGLPaintDevice Bool_t shareDefault, const TGLPaintDevice *shareDevice, UInt_t width, UInt_t height); - ~TGLWidget(); + ~TGLWidget() override; virtual void InitGL(); virtual void PaintGL(); - Bool_t MakeCurrent(); + Bool_t MakeCurrent() override; Bool_t ClearCurrent(); - void SwapBuffers(); - const TGLContext *GetContext()const; + void SwapBuffers() override; + const TGLContext *GetContext()const override; - const TGLFormat *GetPixelFormat()const; + const TGLFormat *GetPixelFormat()const override; //This function is public _ONLY_ for calls //via gInterpreter. Do not call it directly. void SetFormat(); //To repaint gl-widget without GUI events. - void ExtractViewport(Int_t *vp)const; + void ExtractViewport(Int_t *vp)const override; TGEventHandler *GetEventHandler() const { return fEventHandler; } void SetEventHandler(TGEventHandler *eh); - Bool_t HandleButton(Event_t *ev); - Bool_t HandleDoubleClick(Event_t *ev); - Bool_t HandleConfigureNotify(Event_t *ev); - Bool_t HandleKey(Event_t *ev); - Bool_t HandleMotion(Event_t *ev); - Bool_t HandleFocusChange(Event_t *); - Bool_t HandleCrossing(Event_t *); + Bool_t HandleButton(Event_t *ev) override; + Bool_t HandleDoubleClick(Event_t *ev) override; + Bool_t HandleConfigureNotify(Event_t *ev) override; + Bool_t HandleKey(Event_t *ev) override; + Bool_t HandleMotion(Event_t *ev) override; + Bool_t HandleFocusChange(Event_t *) override; + Bool_t HandleCrossing(Event_t *) override; - void DoRedraw(); + void DoRedraw() override; private: TGLWidget(const TGLWidget &); // Not implemented. @@ -96,12 +96,12 @@ class TGLWidget : public TGFrame, public TGLPaintDevice UInt_t width, UInt_t height, std::pair& innerData); - void AddContext(TGLContext *ctx); - void RemoveContext(TGLContext *ctx); + void AddContext(TGLContext *ctx) override; + void RemoveContext(TGLContext *ctx) override; std::pair GetInnerData()const; - ClassDef(TGLWidget, 0); //Window (widget) version of TGLPaintDevice + ClassDefOverride(TGLWidget, 0); //Window (widget) version of TGLPaintDevice }; #endif diff --git a/graf3d/gl/inc/TH2GL.h b/graf3d/gl/inc/TH2GL.h index 61f162311650a..ff925af891768 100644 --- a/graf3d/gl/inc/TH2GL.h +++ b/graf3d/gl/inc/TH2GL.h @@ -31,17 +31,17 @@ class TH2GL : public TGLPlot3D public: TH2GL(); - virtual ~TH2GL(); + ~TH2GL() override; - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*); - ClassDef(TH2GL, 0); // GL renderer for TH2. + ClassDefOverride(TH2GL, 0); // GL renderer for TH2. }; // endclass TH2GL #endif diff --git a/graf3d/gl/inc/TH3GL.h b/graf3d/gl/inc/TH3GL.h index da7376e80522a..1c96a453d74aa 100644 --- a/graf3d/gl/inc/TH3GL.h +++ b/graf3d/gl/inc/TH3GL.h @@ -35,18 +35,18 @@ class TH3GL : public TGLPlot3D public: TH3GL(); TH3GL(TH3 *h, TPolyMarker3D *pm); - virtual ~TH3GL(); + ~TH3GL() override; - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; // To support two-level selection // virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } // virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); - ClassDef(TH3GL, 0); // GL renderer class for TH3. + ClassDefOverride(TH3GL, 0); // GL renderer class for TH3. }; #endif diff --git a/graf3d/gl/inc/TPointSet3DGL.h b/graf3d/gl/inc/TPointSet3DGL.h index c0cacf95d21a4..f37b2195c170b 100644 --- a/graf3d/gl/inc/TPointSet3DGL.h +++ b/graf3d/gl/inc/TPointSet3DGL.h @@ -22,20 +22,20 @@ class TPointSet3DGL : public TGLObject public: TPointSet3DGL() : TGLObject() {} - virtual Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr); - virtual void SetBBox(); - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const; + Bool_t SetModel(TObject* obj, const Option_t *opt = nullptr) override; + void SetBBox() override; + void DirectDraw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t IgnoreSizeForOfInterest() const { return kTRUE; } + Bool_t IgnoreSizeForOfInterest() const override { return kTRUE; } - virtual Bool_t ShouldDLCache(const TGLRnrCtx & rnrCtx) const; + Bool_t ShouldDLCache(const TGLRnrCtx & rnrCtx) const override; - virtual void Draw(TGLRnrCtx & rnrCtx) const; + void Draw(TGLRnrCtx & rnrCtx) const override; - virtual Bool_t SupportsSecondarySelect() const { return kTRUE; } - virtual void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec); + Bool_t SupportsSecondarySelect() const override { return kTRUE; } + void ProcessSelection(TGLRnrCtx & rnrCtx, TGLSelectRecord & rec) override; - ClassDef(TPointSet3DGL,1) // GL renderer for TPointSet3D + ClassDefOverride(TPointSet3DGL,1) // GL renderer for TPointSet3D }; #endif diff --git a/graf3d/gl/inc/TX11GL.h b/graf3d/gl/inc/TX11GL.h index 94d9044b7b161..9ef5d2b1b3bbe 100644 --- a/graf3d/gl/inc/TX11GL.h +++ b/graf3d/gl/inc/TX11GL.h @@ -38,50 +38,50 @@ class TX11GLManager : public TGLManager { public: TX11GLManager(); - ~TX11GLManager(); + ~TX11GLManager() override; //All public functions are TGLManager's final-overriders //index returned can be used as a result of gVirtualX->InitWindow - Int_t InitGLWindow(Window_t winID); + Int_t InitGLWindow(Window_t winID) override; //winInd is the index, returned by InitGLWindow - Int_t CreateGLContext(Int_t winInd); + Int_t CreateGLContext(Int_t winInd) override; //[ Off-screen rendering part //create pixmap to read GL buffer into it, //ctxInd is the index, returned by CreateGLContext - Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h); - Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h); + Bool_t AttachOffScreenDevice(Int_t ctxInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t ResizeOffScreenDevice(Int_t devInd, Int_t x, Int_t y, UInt_t w, UInt_t h) override; //analog of gVirtualX->SelectWindow(fPixmapID) => gVirtualGL->SelectOffScreenDevice(fPixmapID) - void SelectOffScreenDevice(Int_t devInd); + void SelectOffScreenDevice(Int_t devInd) override; //Index of pixmap, valid for gVirtualX - Int_t GetVirtualXInd(Int_t devInd); + Int_t GetVirtualXInd(Int_t devInd) override; //copy pixmap into window directly/by pad - void MarkForDirectCopy(Int_t devInd, Bool_t); + void MarkForDirectCopy(Int_t devInd, Bool_t) override; //Off-screen device holds sizes for glViewport - void ExtractViewport(Int_t devInd, Int_t *vp); + void ExtractViewport(Int_t devInd, Int_t *vp) override; //Read GL buffer into pixmap - void ReadGLBuffer(Int_t devInd); + void ReadGLBuffer(Int_t devInd) override; //] //Make the gl context current - Bool_t MakeCurrent(Int_t devInd); + Bool_t MakeCurrent(Int_t devInd) override; //Sswap buffers or copies pixmap (XCopyArea) - void Flush(Int_t ctxInd); + void Flush(Int_t ctxInd) override; //Generic function for gl context and off-screen device deletion - void DeleteGLContext(Int_t devInd); + void DeleteGLContext(Int_t devInd) override; //used by viewer - Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox); + Bool_t SelectManip(TVirtualGLManip *manip, const TGLCamera *camera, const TGLRect *rect, const TGLBoundingBox *sceneBox) override; // - Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py); - char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py); + Bool_t PlotSelected(TVirtualGLPainter *plot, Int_t px, Int_t py) override; + char *GetPlotInfo(TVirtualGLPainter *plot, Int_t px, Int_t py) override; // - void PaintSingleObject(TVirtualGLPainter *); - void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y); - void PrintViewer(TVirtualViewer3D *vv); + void PaintSingleObject(TVirtualGLPainter *) override; + void PanObject(TVirtualGLPainter *o, Int_t x, Int_t y) override; + void PrintViewer(TVirtualViewer3D *vv) override; - Bool_t HighColorFormat(Int_t /*ctxInd*/){return kFALSE;} + Bool_t HighColorFormat(Int_t /*ctxInd*/) override{return kFALSE;} struct TGLContext_t; @@ -93,7 +93,7 @@ class TX11GLManager : public TGLManager { TX11GLManager(const TX11GLManager &); TX11GLManager &operator = (const TX11GLManager &); - ClassDef(TX11GLManager, 0) //X11-specific version of TGLManager + ClassDefOverride(TX11GLManager, 0) //X11-specific version of TGLManager }; diff --git a/graf3d/gl/src/TGLClip.cxx b/graf3d/gl/src/TGLClip.cxx index d77f5b6a89b11..f81d63b9ac2a6 100644 --- a/graf3d/gl/src/TGLClip.cxx +++ b/graf3d/gl/src/TGLClip.cxx @@ -24,7 +24,7 @@ namespace class TGLClipPlaneLogical : public TGLLogicalShape { protected: - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const + void DirectDraw(TGLRnrCtx & rnrCtx) const override { glBegin(rnrCtx.IsDrawPassFilled() ? GL_QUADS : GL_LINE_LOOP); glNormal3d (0.0, 0.0, 1.0); @@ -37,7 +37,7 @@ class TGLClipPlaneLogical : public TGLLogicalShape public: TGLClipPlaneLogical() : TGLLogicalShape() { fDLCache = kFALSE; } - virtual ~TGLClipPlaneLogical() {} + ~TGLClipPlaneLogical() override {} void Resize(Double_t ext) { @@ -52,7 +52,7 @@ class TGLClipPlaneLogical : public TGLLogicalShape class TGLClipBoxLogical : public TGLLogicalShape { protected: - virtual void DirectDraw(TGLRnrCtx & rnrCtx) const + void DirectDraw(TGLRnrCtx & rnrCtx) const override { glEnable(GL_NORMALIZE); fBoundingBox.Draw(rnrCtx.IsDrawPassFilled()); @@ -61,7 +61,7 @@ class TGLClipBoxLogical : public TGLLogicalShape public: TGLClipBoxLogical() : TGLLogicalShape() { fDLCache = kFALSE; } - virtual ~TGLClipBoxLogical() {} + ~TGLClipBoxLogical() override {} void Resize(const TGLVertex3 & lowVertex, const TGLVertex3 & highVertex) { diff --git a/graf3d/gl/src/TGLCylinder.cxx b/graf3d/gl/src/TGLCylinder.cxx index ab9df67607de7..9b68f7b3c451f 100644 --- a/graf3d/gl/src/TGLCylinder.cxx +++ b/graf3d/gl/src/TGLCylinder.cxx @@ -63,7 +63,7 @@ class TubeSegMesh : public TGLMesh { Double_t phi1, Double_t phi2, const TGLVector3 &l = gLowNormalDefault, const TGLVector3 &h = gHighNormalDefault); - void Draw() const; + void Draw() const override; }; //four quad strips: @@ -79,7 +79,7 @@ class TubeMesh : public TGLMesh TubeMesh(UInt_t LOD, Double_t r1, Double_t r2, Double_t r3, Double_t r4, Double_t dz, const TGLVector3 &l = gLowNormalDefault, const TGLVector3 &h = gHighNormalDefault); - void Draw() const; + void Draw() const override; }; //One quad mesh and 2 triangle funs @@ -93,7 +93,7 @@ class TCylinderMesh : public TGLMesh { TCylinderMesh(UInt_t LOD, Double_t r1, Double_t r2, Double_t dz, const TGLVector3 &l = gLowNormalDefault, const TGLVector3 &h = gHighNormalDefault); - void Draw() const; + void Draw() const override; }; //One quad mesh and 2 triangle fans @@ -107,7 +107,7 @@ class TCylinderSegMesh : public TGLMesh public: TCylinderSegMesh(UInt_t LOD, Double_t r1, Double_t r2, Double_t dz, Double_t phi1, Double_t phi2, const TGLVector3 &l = gLowNormalDefault, const TGLVector3 &h = gHighNormalDefault); - void Draw() const; + void Draw() const override; }; TGLMesh::TGLMesh(UInt_t LOD, Double_t r1, Double_t r2, Double_t r3, Double_t r4, Double_t dz, diff --git a/graf3d/gl/src/TGLEventHandler.cxx b/graf3d/gl/src/TGLEventHandler.cxx index db7759e249fa4..6ff276773dde5 100644 --- a/graf3d/gl/src/TGLEventHandler.cxx +++ b/graf3d/gl/src/TGLEventHandler.cxx @@ -509,7 +509,8 @@ Bool_t TGLEventHandler::HandleButton(Event_t * event) fGLViewer->RequestSelect(event->fX, event->fY); if (fGLViewer->fSelRec.GetN() > 0) { - TGLVector3 v(event->fX, event->fY, 0.5*fGLViewer->fSelRec.GetMinZ()); + auto scaling = TGLUtil::GetScreenScalingFactor(); + TGLVector3 v(scaling * event->fX, scaling * event->fY, 0.5*fGLViewer->fSelRec.GetMinZ()); fGLViewer->CurrentCamera().WindowToViewport(v); v = fGLViewer->CurrentCamera().ViewportToWorld(v); if (fGLViewer->GetPushAction() == TGLViewer::kPushCamCenter) diff --git a/graf3d/gl/src/TGLHistPainter.cxx b/graf3d/gl/src/TGLHistPainter.cxx index b48972dc344e6..a835daa453ba2 100644 --- a/graf3d/gl/src/TGLHistPainter.cxx +++ b/graf3d/gl/src/TGLHistPainter.cxx @@ -750,6 +750,14 @@ void TGLHistPainter::SetShowProjection(const char *option, Int_t nbins) if (fDefaultPainter.get()) fDefaultPainter->SetShowProjection(option, nbins); } +//////////////////////////////////////////////////////////////////////////////// +/// Set show projectionXY. + +void TGLHistPainter::SetShowProjectionXY(const char *option, Int_t nbinsY, Int_t nbinsX) +{ + if (fDefaultPainter.get()) fDefaultPainter->SetShowProjectionXY(option, nbinsY, nbinsX); +} + //////////////////////////////////////////////////////////////////////////////// void TGLHistPainter::PadToViewport(Bool_t /*selectionPass*/) diff --git a/graf3d/gl/src/TGLScenePad.cxx b/graf3d/gl/src/TGLScenePad.cxx index 283220b29393e..b9bd86973c26a 100644 --- a/graf3d/gl/src/TGLScenePad.cxx +++ b/graf3d/gl/src/TGLScenePad.cxx @@ -597,6 +597,11 @@ Int_t TGLScenePad::ValidateObjectBuffer(const TBuffer3D& buffer, Bool_t includeR { needRaw = kTRUE; } + // 6. The shape is scaled + else if (buffer.fScaled) + { + needRaw = kTRUE; + } if (needRaw && !buffer.SectionsValid(TBuffer3D::kRawSizes|TBuffer3D::kRaw)) { return TBuffer3D::kRawSizes|TBuffer3D::kRaw; diff --git a/graf3d/gviz3d/CMakeLists.txt b/graf3d/gviz3d/CMakeLists.txt index c07557c17c9fd..6e26ba6cf0c2b 100644 --- a/graf3d/gviz3d/CMakeLists.txt +++ b/graf3d/gviz3d/CMakeLists.txt @@ -8,6 +8,11 @@ # CMakeLists.txt file for building ROOT graf3d/gviz3d package ############################################################################ +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(Gviz3d HEADERS TStructNode.h @@ -28,4 +33,5 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Gviz3d Ged Geom RGL + ${EXTRA_DICT_OPTS} ) diff --git a/graf3d/gviz3d/inc/TStructNode.h b/graf3d/gviz3d/inc/TStructNode.h index b31484207ca75..bc0c2a31bd60f 100644 --- a/graf3d/gviz3d/inc/TStructNode.h +++ b/graf3d/gviz3d/inc/TStructNode.h @@ -57,9 +57,9 @@ class TStructNode : public TObject { public: TStructNode(TString name, TString typeName, void* pointer, TStructNode* parent, ULong_t size, ENodeType type); - ~TStructNode(); + ~TStructNode() override; - virtual Int_t Compare(const TObject* obj) const; + Int_t Compare(const TObject* obj) const override; ULong_t GetAllMembersCount() const; Float_t GetCenter() const; Float_t GetHeight() const; @@ -69,7 +69,7 @@ class TStructNode : public TObject { TList* GetMembers() const; ULong_t GetMembersCount() const; Float_t GetMiddle() const; - const char* GetName() const; + const char* GetName() const override; ENodeType GetNodeType() const; TStructNode *GetParent() const; void* GetPointer() const; @@ -86,7 +86,7 @@ class TStructNode : public TObject { Float_t GetX() const; Float_t GetY() const; Bool_t IsCollapsed() const; - virtual Bool_t IsSortable() const; + Bool_t IsSortable() const override; bool IsVisible() const; void SetAllMembersCount(ULong_t count); void SetCollapsed(Bool_t collapsed); @@ -105,7 +105,7 @@ class TStructNode : public TObject { void SetX(Float_t x); void SetY(Float_t y); - ClassDef(TStructNode,0); // Node with information about class + ClassDefOverride(TStructNode,0); // Node with information about class }; #endif diff --git a/graf3d/gviz3d/inc/TStructNodeEditor.h b/graf3d/gviz3d/inc/TStructNodeEditor.h index ca6e90f9341a6..2c8dd663a3ac9 100644 --- a/graf3d/gviz3d/inc/TStructNodeEditor.h +++ b/graf3d/gviz3d/inc/TStructNodeEditor.h @@ -46,7 +46,7 @@ class TStructNodeEditor : public TGedFrame { public: TStructNodeEditor(TList* colors, const TGWindow *p = nullptr, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - ~TStructNodeEditor(); + ~TStructNodeEditor() override; void ApplyButtonSlot(); void AutoRefreshButtonSlot(Bool_t on); @@ -54,11 +54,11 @@ class TStructNodeEditor : public TGedFrame { void DefaultButtonSlot(); void MaxLevelsValueSetSlot(Long_t); void MaxObjectsValueSetSlot(Long_t); - void SetModel(TObject* obj); + void SetModel(TObject* obj) override; void Update(Bool_t resetCamera); - void Update(); + void Update() override; - ClassDef(TStructNodeEditor, 0); // GUI fo editing TStructNode + ClassDefOverride(TStructNodeEditor, 0); // GUI fo editing TStructNode }; #endif // ROOT_TStructNodeEditor diff --git a/graf3d/gviz3d/inc/TStructNodeProperty.h b/graf3d/gviz3d/inc/TStructNodeProperty.h index 9508f302b0b74..d4e4f97012fe9 100644 --- a/graf3d/gviz3d/inc/TStructNodeProperty.h +++ b/graf3d/gviz3d/inc/TStructNodeProperty.h @@ -24,17 +24,17 @@ class TStructNodeProperty : public TNamed { public: TStructNodeProperty(const char * name, Int_t color); TStructNodeProperty(const char * name, Pixel_t pixel); - ~TStructNodeProperty(); + ~TStructNodeProperty() override; TColor GetColor() const; Pixel_t GetPixel() const; void SetColor(const TColor & color); void SetColor(Pixel_t pixel); void SetColor(Int_t color); - Int_t Compare(const TObject* obj) const; - Bool_t IsSortable() const; + Int_t Compare(const TObject* obj) const override; + Bool_t IsSortable() const override; - ClassDef(TStructNodeProperty, 1); // Class with nodes color property + ClassDefOverride(TStructNodeProperty, 1); // Class with nodes color property }; #endif diff --git a/graf3d/gviz3d/inc/TStructViewer.h b/graf3d/gviz3d/inc/TStructViewer.h index d80349ad72794..99a0281ecc246 100644 --- a/graf3d/gviz3d/inc/TStructViewer.h +++ b/graf3d/gviz3d/inc/TStructViewer.h @@ -45,9 +45,9 @@ class TStructViewer : public TObject { public: TStructViewer(void* ptr = nullptr, const char * clname = nullptr); - ~TStructViewer(); + ~TStructViewer() override; - void Draw(Option_t *option = ""); + void Draw(Option_t *option = "") override; TCanvas* GetCanvas(); TGMainFrame* GetFrame(); TColor GetColor(const char* typeName); @@ -59,7 +59,7 @@ class TStructViewer : public TObject { void SetLinksVisibility(Bool_t val); void SetPointer(void* ptr, const char* clname = nullptr); - ClassDef(TStructViewer, 0); // A 3D struct viewer + ClassDefOverride(TStructViewer, 0); // A 3D struct viewer }; #endif diff --git a/graf3d/gviz3d/inc/TStructViewerGUI.h b/graf3d/gviz3d/inc/TStructViewerGUI.h index f150ed5f9131c..c08781c13369c 100644 --- a/graf3d/gviz3d/inc/TStructViewerGUI.h +++ b/graf3d/gviz3d/inc/TStructViewerGUI.h @@ -91,14 +91,14 @@ class TStructViewerGUI : public TGMainFrame { public: TStructViewerGUI(TStructViewer* parent, TStructNode* nodePtr, TList* colors, const TGWindow *p = nullptr, UInt_t w = 800, UInt_t h = 600); - ~TStructViewerGUI(); + ~TStructViewerGUI() override; void AutoRefreshButtonSlot(Bool_t on); void BoxHeightValueSetSlot(Long_t h); - void CloseWindow(); + void CloseWindow() override; void ColorSelectedSlot(Pixel_t pixel); void DoubleClickedSlot(); - void Draw(Option_t* option = ""); + void Draw(Option_t* option = "") override; TCanvas *GetCanvas(); Int_t GetColor(TStructNode* node); TStructNodeProperty* GetDefaultColor(); @@ -118,7 +118,7 @@ class TStructViewerGUI : public TGMainFrame { void Update(Bool_t resetCamera = false); void UpdateButtonSlot(); - ClassDef(TStructViewerGUI, 0); // A GUI fo 3D struct viewer + ClassDefOverride(TStructViewerGUI, 0); // A GUI fo 3D struct viewer }; #endif diff --git a/graf3d/x3d/inc/TViewerX3D.h b/graf3d/x3d/inc/TViewerX3D.h index c4764d3b149ee..61dd9d4900995 100644 --- a/graf3d/x3d/inc/TViewerX3D.h +++ b/graf3d/x3d/inc/TViewerX3D.h @@ -73,7 +73,7 @@ friend class TX3DContainer; UInt_t width = 800, UInt_t height = 600); TViewerX3D(TVirtualPad *pad, Option_t *option, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height); - virtual ~TViewerX3D(); + ~TViewerX3D() override; Int_t ExecCommand(Int_t px, Int_t py, char command); void GetPosition(Float_t &longitude, Float_t &latitude, Float_t &psi); @@ -85,22 +85,22 @@ friend class TX3DContainer; void PaintPolyMarker(const TBuffer3D & buffer) const; // TVirtualViewer3D interface - virtual Bool_t PreferLocalFrame() const { return kFALSE; } - virtual void BeginScene(); - virtual Bool_t BuildingScene() const { return fBuildingScene; } - virtual void EndScene(); - virtual Int_t AddObject(const TBuffer3D & buffer, Bool_t * addChildren = nullptr); - virtual Int_t AddObject(UInt_t placedID, const TBuffer3D & buffer, Bool_t * addChildren = nullptr); + Bool_t PreferLocalFrame() const override { return kFALSE; } + void BeginScene() override; + Bool_t BuildingScene() const override { return fBuildingScene; } + void EndScene() override; + Int_t AddObject(const TBuffer3D & buffer, Bool_t * addChildren = nullptr) override; + Int_t AddObject(UInt_t placedID, const TBuffer3D & buffer, Bool_t * addChildren = nullptr) override; // Composite shapes not supported on this viewer currently - ignore. // Will result in a set of component shapes - virtual Bool_t OpenComposite(const TBuffer3D & /*buffer*/, Bool_t * = nullptr) { return kTRUE; } - virtual void CloseComposite() {}; - virtual void AddCompositeOp(UInt_t /*operation*/) {}; + Bool_t OpenComposite(const TBuffer3D & /*buffer*/, Bool_t * = nullptr) override { return kTRUE; } + void CloseComposite() override {}; + void AddCompositeOp(UInt_t /*operation*/) override {}; Bool_t ProcessFrameMessage(Long_t msg, Long_t parm1, Long_t parm2); - ClassDef(TViewerX3D,0) //Interface to the X3D viewer + ClassDefOverride(TViewerX3D,0) //Interface to the X3D viewer }; #endif diff --git a/graf3d/x3d/inc/TX3DFrame.h b/graf3d/x3d/inc/TX3DFrame.h index e3419065495fa..4e068c91c7880 100644 --- a/graf3d/x3d/inc/TX3DFrame.h +++ b/graf3d/x3d/inc/TX3DFrame.h @@ -28,12 +28,12 @@ class TX3DFrame : public TGMainFrame private: TViewerX3D & fViewer; - Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); - void CloseWindow(); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; + void CloseWindow() override; public: TX3DFrame(TViewerX3D & viewer, const TGWindow * win, UInt_t width, UInt_t height); - ~TX3DFrame(); + ~TX3DFrame() override; }; #endif diff --git a/graf3d/x3d/src/TViewerX3D.cxx b/graf3d/x3d/src/TViewerX3D.cxx index 37dce4215e7fe..3361ce98869b0 100644 --- a/graf3d/x3d/src/TViewerX3D.cxx +++ b/graf3d/x3d/src/TViewerX3D.cxx @@ -109,19 +109,19 @@ class TX3DContainer : public TGCompositeFrame { public: TX3DContainer(TViewerX3D *c, Window_t id, const TGWindow *parent); - Bool_t HandleButton(Event_t *ev) + Bool_t HandleButton(Event_t *ev) override { x3d_dispatch_event(gVirtualX->GetNativeEvent()); return fViewer->HandleContainerButton(ev); } - Bool_t HandleConfigureNotify(Event_t *ev) + Bool_t HandleConfigureNotify(Event_t *ev) override { TGFrame::HandleConfigureNotify(ev); return x3d_dispatch_event(gVirtualX->GetNativeEvent()); } - Bool_t HandleKey(Event_t *) + Bool_t HandleKey(Event_t *) override { return x3d_dispatch_event(gVirtualX->GetNativeEvent()); } - Bool_t HandleMotion(Event_t *) + Bool_t HandleMotion(Event_t *) override { return x3d_dispatch_event(gVirtualX->GetNativeEvent()); } - Bool_t HandleExpose(Event_t *) + Bool_t HandleExpose(Event_t *) override { return x3d_dispatch_event(gVirtualX->GetNativeEvent()); } - Bool_t HandleColormapChange(Event_t *) + Bool_t HandleColormapChange(Event_t *) override { return x3d_dispatch_event(gVirtualX->GetNativeEvent()); } }; diff --git a/gui/CMakeLists.txt b/gui/CMakeLists.txt index 3859542be1f83..0ea0684cb4846 100644 --- a/gui/CMakeLists.txt +++ b/gui/CMakeLists.txt @@ -10,7 +10,9 @@ add_subdirectory(fitpanel) add_subdirectory(guibuilder) add_subdirectory(guihtml) add_subdirectory(recorder) -add_subdirectory(sessionviewer) +if(proof) + add_subdirectory(sessionviewer) +endif() if(webgui) add_subdirectory(webdisplay) diff --git a/gui/browsable/CMakeLists.txt b/gui/browsable/CMakeLists.txt index f50d0dbfe577d..6681d206a2987 100644 --- a/gui/browsable/CMakeLists.txt +++ b/gui/browsable/CMakeLists.txt @@ -78,6 +78,15 @@ ROOT_LINKER_LIBRARY(ROOTBranchBrowseProvider Tree ) +# provider for browsing of TGeo class + +ROOT_LINKER_LIBRARY(ROOTGeoBrowseProvider + src/TGeoBrowseProvider.cxx + DEPENDENCIES + ROOTBrowsable + Geom +) + # provider for drawing of TLeaf on TCanvas ROOT_LINKER_LIBRARY(ROOTLeafDraw6Provider diff --git a/gui/browsable/inc/LinkDef.h b/gui/browsable/inc/LinkDef.h index 115d81ab0dd73..3f42a0652a88d 100644 --- a/gui/browsable/inc/LinkDef.h +++ b/gui/browsable/inc/LinkDef.h @@ -12,23 +12,23 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ namespace ROOT::Experimental::Browsable; +#pragma link C++ namespace ROOT::Browsable; -#pragma link C++ class ROOT::Experimental::Browsable::RHolder+; -#pragma link C++ class ROOT::Experimental::Browsable::RAnyObjectHolder+; -#pragma link C++ class ROOT::Experimental::Browsable::RProvider+; -#pragma link C++ class ROOT::Experimental::Browsable::RElement+; -#pragma link C++ class ROOT::Experimental::Browsable::RLevelIter+; -#pragma link C++ class ROOT::Experimental::Browsable::RGroup+; -#pragma link C++ class ROOT::Experimental::Browsable::RWrapper+; +#pragma link C++ class ROOT::Browsable::RHolder+; +#pragma link C++ class ROOT::Browsable::RAnyObjectHolder+; +#pragma link C++ class ROOT::Browsable::RProvider+; +#pragma link C++ class ROOT::Browsable::RElement+; +#pragma link C++ class ROOT::Browsable::RLevelIter+; +#pragma link C++ class ROOT::Browsable::RGroup+; +#pragma link C++ class ROOT::Browsable::RWrapper+; -#pragma link C++ class ROOT::Experimental::Browsable::RSysFile+; +#pragma link C++ class ROOT::Browsable::RSysFile+; -#pragma link C++ class ROOT::Experimental::Browsable::TObjectHolder+; -#pragma link C++ class ROOT::Experimental::Browsable::TObjectItem+; -#pragma link C++ class ROOT::Experimental::Browsable::TKeyItem+; +#pragma link C++ class ROOT::Browsable::TObjectHolder+; +#pragma link C++ class ROOT::Browsable::TObjectItem+; +#pragma link C++ class ROOT::Browsable::TKeyItem+; -#pragma link C++ class ROOT::Experimental::Browsable::RItem+; -#pragma link C++ class ROOT::Experimental::Browsable::RSysFileItem+; +#pragma link C++ class ROOT::Browsable::RItem+; +#pragma link C++ class ROOT::Browsable::RSysFileItem+; #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RAnyObjectHolder.hxx b/gui/browsable/inc/ROOT/Browsable/RAnyObjectHolder.hxx index accbecc733f9c..adcf00e21db6f 100644 --- a/gui/browsable/inc/ROOT/Browsable/RAnyObjectHolder.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RAnyObjectHolder.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RAnyObjectHolder @@ -54,13 +53,19 @@ public: fClass->Destructor(fObj); } + void Forget() final + { + fClass = nullptr; + fObj = nullptr; + fOwner = false; + } + const TClass *GetClass() const final { return fClass; } const void *GetObject() const final { return fObj; } }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RElement.hxx b/gui/browsable/inc/ROOT/Browsable/RElement.hxx index 47879e22eca41..22b786f224048 100644 --- a/gui/browsable/inc/ROOT/Browsable/RElement.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RElement.hxx @@ -15,7 +15,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { using RElementPath_t = std::vector; @@ -117,7 +116,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RGroup.hxx b/gui/browsable/inc/ROOT/Browsable/RGroup.hxx index 84ed9a30e85f7..fb17c51dfcb07 100644 --- a/gui/browsable/inc/ROOT/Browsable/RGroup.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RGroup.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RGroup @@ -49,9 +48,7 @@ public: auto &GetChilds() const { return fChilds; } }; - } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RHolder.hxx b/gui/browsable/inc/ROOT/Browsable/RHolder.hxx index 854a57c1c5a6f..e97a7a7b4a4ff 100644 --- a/gui/browsable/inc/ROOT/Browsable/RHolder.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RHolder.hxx @@ -14,11 +14,13 @@ #include namespace ROOT { -namespace Experimental { +namespace Experimental { class RLogChannel; +} // namespace Experimental + /// Log channel for Browsable diagnostics. -RLogChannel &BrowsableLog(); // implemented in RElement.cxx +ROOT::Experimental::RLogChannel &BrowsableLog(); // implemented in RElement.cxx namespace Browsable { @@ -54,6 +56,9 @@ public: /** Returns direct (temporary) object pointer */ virtual const void *GetObject() const = 0; + /** Clear all pointers without performing cleanup */ + virtual void Forget() {} + template bool InheritsFrom() const { @@ -126,7 +131,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RItem.hxx b/gui/browsable/inc/ROOT/Browsable/RItem.hxx index d9f2dfe93720c..70cbc4d8724ff 100644 --- a/gui/browsable/inc/ROOT/Browsable/RItem.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RItem.hxx @@ -13,7 +13,6 @@ #include "RtypesCore.h" namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RItem @@ -80,7 +79,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RLevelIter.hxx b/gui/browsable/inc/ROOT/Browsable/RLevelIter.hxx index f57362e7c2260..151eec42b9eb4 100644 --- a/gui/browsable/inc/ROOT/Browsable/RLevelIter.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RLevelIter.hxx @@ -13,7 +13,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { class RElement; @@ -51,7 +50,6 @@ public: } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RProvider.hxx b/gui/browsable/inc/ROOT/Browsable/RProvider.hxx index a84390f30c724..b8038e885366e 100644 --- a/gui/browsable/inc/ROOT/Browsable/RProvider.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RProvider.hxx @@ -18,9 +18,10 @@ class TVirtualPad; namespace ROOT { -namespace Experimental { +namespace Experimental { class RPadBase; +} // namespace Experimental namespace Browsable { @@ -39,6 +40,8 @@ public: virtual ~RProvider(); + using ProgressFunc_t = std::function; + class ClassArg { friend class RProvider; const TClass *cl{nullptr}; @@ -54,6 +57,20 @@ public: const std::string &GetName() const { return name; } }; + class ProgressHandle { + friend class RProvider; + void *fHandle{nullptr}; + + ProgressHandle(const ProgressHandle &) = delete; + ProgressHandle& operator=(const ProgressHandle &) = delete; + public: + explicit ProgressHandle(void *handle, ProgressFunc_t func); + ~ProgressHandle(); + void Extend(void *handle2); + }; + + friend class ProgressHandle; + static std::string GetClassIcon(const ClassArg &, bool = false); static std::string GetClassDrawOption(const ClassArg &); static bool SetClassDrawOption(const ClassArg &, const std::string &); @@ -70,6 +87,9 @@ public: static bool Draw6(TVirtualPad *subpad, std::unique_ptr &obj, const std::string &opt = ""); static bool Draw7(std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt = ""); + static void ExtendProgressHandle(void *handle, void *handle2); + static bool ReportProgress(void *handle, float progress); + protected: using FileFunc_t = std::function(const std::string &)>; @@ -96,6 +116,8 @@ private: struct StructFile { RProvider *provider{nullptr}; FileFunc_t func; }; struct StructDraw6 { RProvider *provider{nullptr}; Draw6Func_t func; }; struct StructDraw7 { RProvider *provider{nullptr}; Draw7Func_t func; }; + struct StructProgress { void *handle{nullptr}, *handle2{nullptr}; ProgressFunc_t func; }; + struct StructClass { RProvider *provider{nullptr}; bool can_have_childs{false}; @@ -108,12 +130,14 @@ private: using BrowseMap_t = std::multimap; using Draw6Map_t = std::multimap; using Draw7Map_t = std::multimap; + using ProgressVect_t = std::vector; static ClassMap_t &GetClassMap(); static FileMap_t &GetFileMap(); static BrowseMap_t &GetBrowseMap(); static Draw6Map_t &GetDraw6Map(); static Draw7Map_t &GetDraw7Map(); + static ProgressVect_t &GetProgressVect(); static BrowseNTupleFunc_t gNTupleFunc; static StructClass &GetClassEntry(const ClassArg &); @@ -134,7 +158,6 @@ private: } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/RShared.hxx b/gui/browsable/inc/ROOT/Browsable/RShared.hxx index 85ee9484fcbf4..d12e645500120 100644 --- a/gui/browsable/inc/ROOT/Browsable/RShared.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RShared.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RShared @@ -40,7 +39,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RSysFile.hxx b/gui/browsable/inc/ROOT/Browsable/RSysFile.hxx index e733c1b6c7965..068b2221901bf 100644 --- a/gui/browsable/inc/ROOT/Browsable/RSysFile.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RSysFile.hxx @@ -16,7 +16,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { class RSysDirLevelIter; @@ -66,7 +65,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RSysFileItem.hxx b/gui/browsable/inc/ROOT/Browsable/RSysFileItem.hxx index 0a8fb09cf6b7a..b985e1c7caa19 100644 --- a/gui/browsable/inc/ROOT/Browsable/RSysFileItem.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RSysFileItem.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { @@ -89,7 +88,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RUnique.hxx b/gui/browsable/inc/ROOT/Browsable/RUnique.hxx index 93db1706385ab..7f9ecbfc70347 100644 --- a/gui/browsable/inc/ROOT/Browsable/RUnique.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RUnique.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RUnique @@ -38,7 +37,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/RWrapper.hxx b/gui/browsable/inc/ROOT/Browsable/RWrapper.hxx index 99ba15edbb7c8..0c173f5014d02 100644 --- a/gui/browsable/inc/ROOT/Browsable/RWrapper.hxx +++ b/gui/browsable/inc/ROOT/Browsable/RWrapper.hxx @@ -13,7 +13,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class RWrapper @@ -59,13 +58,10 @@ public: bool IsExpandByDefault() const override { return fExapndByDefault || fElem->IsExpandByDefault(); } void SetExpandByDefault(bool on = true) { fExapndByDefault = on; } - - }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browsable/inc/ROOT/Browsable/TKeyItem.hxx b/gui/browsable/inc/ROOT/Browsable/TKeyItem.hxx index 33c3a0d094f67..fea08cd76de98 100644 --- a/gui/browsable/inc/ROOT/Browsable/TKeyItem.hxx +++ b/gui/browsable/inc/ROOT/Browsable/TKeyItem.hxx @@ -14,7 +14,6 @@ class TDirectory; namespace ROOT { -namespace Experimental { namespace Browsable { /** \class TKeyItem @@ -38,7 +37,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/TObjectElement.hxx b/gui/browsable/inc/ROOT/Browsable/TObjectElement.hxx index c9026e931be79..a02667704c52a 100644 --- a/gui/browsable/inc/ROOT/Browsable/TObjectElement.hxx +++ b/gui/browsable/inc/ROOT/Browsable/TObjectElement.hxx @@ -15,7 +15,6 @@ class TObject; class TCollection; namespace ROOT { -namespace Experimental { namespace Browsable { @@ -93,7 +92,6 @@ public: }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/TObjectHolder.hxx b/gui/browsable/inc/ROOT/Browsable/TObjectHolder.hxx index d4da82d7bde6b..5132dbd8f0a96 100644 --- a/gui/browsable/inc/ROOT/Browsable/TObjectHolder.hxx +++ b/gui/browsable/inc/ROOT/Browsable/TObjectHolder.hxx @@ -12,7 +12,6 @@ #include namespace ROOT { -namespace Experimental { namespace Browsable { /** \class TObjectHolder @@ -51,13 +50,18 @@ public: if (fOwner) delete fObj; } + void Forget() final + { + fAdjusted = fObj = nullptr; + fOwner = false; + } + const TClass *GetClass() const final { return fObj ? fObj->IsA() : nullptr; } const void *GetObject() const final { return fAdjusted; } }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/inc/ROOT/Browsable/TObjectItem.hxx b/gui/browsable/inc/ROOT/Browsable/TObjectItem.hxx index 165b90b6d9154..26263a4f71d1c 100644 --- a/gui/browsable/inc/ROOT/Browsable/TObjectItem.hxx +++ b/gui/browsable/inc/ROOT/Browsable/TObjectItem.hxx @@ -14,7 +14,6 @@ class TObject; namespace ROOT { -namespace Experimental { namespace Browsable { /** \class TObjectItem @@ -37,10 +36,10 @@ public: virtual ~TObjectItem() = default; void SetClassName(const std::string &_className) { className = _className; } + const std::string &GetClassName() const { return className; } }; } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/src/RElement.cxx b/gui/browsable/src/RElement.cxx index a57a1e9e16fda..bb9566f2ecddf 100644 --- a/gui/browsable/src/RElement.cxx +++ b/gui/browsable/src/RElement.cxx @@ -14,11 +14,12 @@ #include "TBufferJSON.h" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; using namespace std::string_literals; -ROOT::Experimental::RLogChannel &ROOT::Experimental::BrowsableLog() { - static RLogChannel sLog("ROOT.Browsable"); +ROOT::Experimental::RLogChannel &ROOT::BrowsableLog() +{ + static ROOT::Experimental::RLogChannel sLog("ROOT.Browsable"); return sLog; } diff --git a/gui/browsable/src/RFieldHolder.hxx b/gui/browsable/src/RFieldHolder.hxx index b257727c61561..cdf21f762797c 100644 --- a/gui/browsable/src/RFieldHolder.hxx +++ b/gui/browsable/src/RFieldHolder.hxx @@ -24,7 +24,7 @@ class RPageSource; } } -class RFieldHolder : public ROOT::Experimental::Browsable::RHolder { +class RFieldHolder : public ROOT::Browsable::RHolder { std::shared_ptr fNtplSource; std::string fParentName; diff --git a/gui/browsable/src/RFieldProvider.hxx b/gui/browsable/src/RFieldProvider.hxx index c36435873cf74..b240577026156 100644 --- a/gui/browsable/src/RFieldProvider.hxx +++ b/gui/browsable/src/RFieldProvider.hxx @@ -24,7 +24,7 @@ #include "RFieldHolder.hxx" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; using namespace std::string_literals; @@ -162,6 +162,14 @@ class RFieldProvider : public RProvider { void VisitUInt32Field(const RField &field) final { FillHistogram(field); } void VisitUInt64Field(const RField &field) final { FillHistogram(field); } void VisitUInt8Field(const RField &field) final { FillHistogram(field); } + void VisitCardinalityField(const ROOT::Experimental::RCardinalityField &field) final + { + if (const auto f32 = field.As32Bit()) { + FillHistogram(*f32); + } else if (const auto f64 = field.As64Bit()) { + FillHistogram(*f64); + } + } }; // class RDrawVisitor public: diff --git a/gui/browsable/src/RGroup.cxx b/gui/browsable/src/RGroup.cxx index 9223fe87648c8..f08400c5fbe88 100644 --- a/gui/browsable/src/RGroup.cxx +++ b/gui/browsable/src/RGroup.cxx @@ -13,7 +13,7 @@ #include -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; class RGroupIter : public RLevelIter { int fIndx{-1}; diff --git a/gui/browsable/src/RHistDraw7Provider.cxx b/gui/browsable/src/RHistDraw7Provider.cxx index 4102ca34b5e17..c04f9184ca41f 100644 --- a/gui/browsable/src/RHistDraw7Provider.cxx +++ b/gui/browsable/src/RHistDraw7Provider.cxx @@ -19,7 +19,7 @@ #include -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; class RV7HistDrawProvider : public RProvider { template diff --git a/gui/browsable/src/RLevelIter.cxx b/gui/browsable/src/RLevelIter.cxx index e45a28c58be99..5dea87269e018 100644 --- a/gui/browsable/src/RLevelIter.cxx +++ b/gui/browsable/src/RLevelIter.cxx @@ -11,7 +11,7 @@ #include #include -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; ///////////////////////////////////////////////////////////////////// /// Find item with specified name diff --git a/gui/browsable/src/RNTupleBrowseProvider.cxx b/gui/browsable/src/RNTupleBrowseProvider.cxx index 92768790acb1d..df5543d86e767 100644 --- a/gui/browsable/src/RNTupleBrowseProvider.cxx +++ b/gui/browsable/src/RNTupleBrowseProvider.cxx @@ -21,7 +21,7 @@ using namespace std::string_literals; -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; // ============================================================================================== diff --git a/gui/browsable/src/RNTupleDraw7Provider.cxx b/gui/browsable/src/RNTupleDraw7Provider.cxx index b7ba2d1fa902a..46febf998b681 100644 --- a/gui/browsable/src/RNTupleDraw7Provider.cxx +++ b/gui/browsable/src/RNTupleDraw7Provider.cxx @@ -13,7 +13,7 @@ #include "RFieldProvider.hxx" -using namespace ROOT::Experimental; +using namespace ROOT::Browsable; // ============================================================================================== @@ -31,7 +31,7 @@ class RNTupleDraw7Provider : public RFieldProvider { RNTupleDraw7Provider() { - RegisterDraw7(TClass::GetClass(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { + RegisterDraw7(TClass::GetClass(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { auto h1 = DrawField(dynamic_cast (obj.get())); if (!h1) return false; diff --git a/gui/browsable/src/RProvider.cxx b/gui/browsable/src/RProvider.cxx index fb86929b57998..d9033d574df13 100644 --- a/gui/browsable/src/RProvider.cxx +++ b/gui/browsable/src/RProvider.cxx @@ -15,7 +15,7 @@ #include "TClass.h" #include "TSystem.h" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; using namespace std::string_literals; RProvider::BrowseNTupleFunc_t RProvider::gNTupleFunc = nullptr; @@ -66,7 +66,14 @@ RProvider::ClassMap_t &RProvider::GetClassMap() } ////////////////////////////////////////////////////////////////////////////////// -// Returns map of registered icons base on class name +// Returns vector of registered progress functions + +RProvider::ProgressVect_t &RProvider::GetProgressVect() +{ + static RProvider::ProgressVect_t sVect; + return sVect; +} + ////////////////////////////////////////////////////////////////////////////////// // Destructor @@ -433,6 +440,66 @@ bool RProvider::CanDraw7(const ClassArg &arg) return false; } +///////////////////////////////////////////////////////////////////// +/// Create progress handle + +RProvider::ProgressHandle::ProgressHandle(void *handle, RProvider::ProgressFunc_t func) +{ + fHandle = handle; + RProvider::GetProgressVect().emplace_back(StructProgress{handle, nullptr, func}); +} + +///////////////////////////////////////////////////////////////////// +/// Destroy progress handle + +RProvider::ProgressHandle::~ProgressHandle() +{ + auto &vect = RProvider::GetProgressVect(); + auto iter = vect.begin(); + while (iter != vect.end()) { + if (iter->handle == fHandle) { + vect.erase(iter); + } else { + iter++; + } + } +} + +///////////////////////////////////////////////////////////////////// +/// Extend progress handle + +void RProvider::ProgressHandle::Extend(void *handle2) +{ + RProvider::ExtendProgressHandle(fHandle, handle2); +} + +///////////////////////////////////////////////////////////////////// +/// Extend progress handle - to be able react on sub item + +void RProvider::ExtendProgressHandle(void *handle, void *handle2) +{ + for (auto &elem : GetProgressVect()) + if (elem.handle == handle) + elem.handle2 = handle2; +} + +///////////////////////////////////////////////////////////////////// +/// Report running progress +/// Returns true if handling function was invoked +/// Method can be used to detect if there any progress handler assigned + + +bool RProvider::ReportProgress(void *handle, float progress) +{ + bool is_any = false; + for (auto &elem : GetProgressVect()) + if ((elem.handle == handle) || (elem.handle2 == handle)) { + elem.func(progress, elem.handle); + is_any = true; + } + + return is_any; +} // ============================================================================================== diff --git a/gui/browsable/src/RSysFile.cxx b/gui/browsable/src/RSysFile.cxx index 5774f6e816b73..d1fc5a38de157 100644 --- a/gui/browsable/src/RSysFile.cxx +++ b/gui/browsable/src/RSysFile.cxx @@ -39,10 +39,9 @@ using namespace std::string_literals; -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; namespace ROOT { -namespace Experimental { namespace Browsable { @@ -348,7 +347,6 @@ class RSysDirLevelIter : public RLevelIter { } // namespace Browsable -} // namespace Experimental } // namespace ROOT diff --git a/gui/browsable/src/TBranchBrowseProvider.cxx b/gui/browsable/src/TBranchBrowseProvider.cxx index 42f1f1ff76b0e..e538b9b9cbb64 100644 --- a/gui/browsable/src/TBranchBrowseProvider.cxx +++ b/gui/browsable/src/TBranchBrowseProvider.cxx @@ -19,7 +19,7 @@ #include "TBranchElement.h" #include "TBranchBrowsable.h" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; using namespace std::string_literals; diff --git a/gui/browsable/src/TDirectoryElement.cxx b/gui/browsable/src/TDirectoryElement.cxx index 1d5008ee12ede..1ff0657764097 100644 --- a/gui/browsable/src/TDirectoryElement.cxx +++ b/gui/browsable/src/TDirectoryElement.cxx @@ -29,7 +29,7 @@ using namespace std::string_literals; -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; /** \class TDirectoryLevelIter @@ -147,7 +147,7 @@ class TDirectoryLevelIter : public RLevelIter { else if (svalue == "no") fOnlyLastCycle = false; else - R__LOG_ERROR(ROOT::Experimental::BrowsableLog()) << "WebGui.LastCycle must be yes or no"; + R__LOG_ERROR(ROOT::BrowsableLog()) << "WebGui.LastCycle must be yes or no"; } } @@ -215,12 +215,19 @@ class TDirectoryElement : public TObjectElement { const TObject *CheckObject() const override { + // during TROOT destructor just forget about file reference + if (!gROOT || gROOT->TestBit(TObject::kInvalidObject)) { + ForgetObject(); + return nullptr; + } + if (!TObjectElement::CheckObject()) return nullptr; - if (fIsFile && !gROOT->GetListOfFiles()->FindObject(fObj)) - ForgetObject(); - else if (!gROOT->GetListOfFiles()->FindObject(((TDirectory *) fObj)->GetFile())) + if (fIsFile) { + if (!gROOT->GetListOfFiles()->FindObject(fObj)) + ForgetObject(); + } else if (!gROOT->GetListOfFiles()->FindObject(((TDirectory *) fObj)->GetFile())) ForgetObject(); return fObj; @@ -319,6 +326,14 @@ class TDirectoryElement : public TObjectElement { return ""s; } + std::string GetContent(const std::string &kind) override + { + if (GetContentKind(kind) == kFileName) + return fFileName; + + return ""s; + } + }; // =============================================================================================================== @@ -416,7 +431,7 @@ class TKeyElement : public TDirectoryElement { return nullptr; if (!obj_class->HasDictionary()) { - R__LOG_ERROR(ROOT::Experimental::BrowsableLog()) << "Class " << fKeyClass << " does not have dictionary, object " << fKeyName << " cannot be read"; + R__LOG_ERROR(ROOT::BrowsableLog()) << "Class " << fKeyClass << " does not have dictionary, object " << fKeyName << " cannot be read"; return nullptr; } auto dir = GetDir(); @@ -433,10 +448,13 @@ class TKeyElement : public TDirectoryElement { TObject *tobj = (TObject *) obj_class->DynamicCast(TObject::Class(), obj); if (tobj) { - if (dir->FindObject(tobj)) + bool in_dir = dir->FindObject(tobj) != nullptr, + special_class = (fKeyClass == "TGeoManager"s) || (fKeyClass == "TTree"s) || (fKeyClass == "TNtuple"s); + + if (in_dir && !special_class) dir->Remove(tobj); - return std::make_unique(tobj, fKeyClass != "TGeoManager"s); + return std::make_unique(tobj, !special_class); } return std::make_unique(obj_class, obj, true); diff --git a/gui/browsable/src/TGeoBrowseProvider.cxx b/gui/browsable/src/TGeoBrowseProvider.cxx new file mode 100644 index 0000000000000..4ef9896c3685a --- /dev/null +++ b/gui/browsable/src/TGeoBrowseProvider.cxx @@ -0,0 +1,232 @@ +// Author: Sergey Linev, 17.03.2023 + +/************************************************************************* + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include +#include +#include +#include + +#include "TGeoManager.h" +#include "TGeoVolume.h" +#include "TGeoNode.h" +#include "TROOT.h" + + +namespace ROOT { +namespace Browsable { + +//////////////////////////////////////////////////////////// +/// Representing TGeoVolume in browsables + +class TGeoVolumeElement : public TObjectElement { + +public: + TGeoVolumeElement(std::unique_ptr &br) : TObjectElement(br) {} + + TGeoVolume *GetVolume() const + { + if (!CheckObject()) return nullptr; + return dynamic_cast(fObj); + } + + bool IsFolder() const override + { + auto vol = GetVolume(); + return vol ? vol->GetNdaughters() > 0 : false; + } + + /** Get default action */ + EActionKind GetDefaultAction() const override + { + return kActGeom; + } + + /** Check if want to perform action */ + bool IsCapable(EActionKind action) const override + { + return action == kActGeom; + } + + /** Provide iterator over TGeoVolume */ + std::unique_ptr GetChildsIter() override; +}; + + +//////////////////////////////////////////////////////////// +/// Representing TGeoNode in browsables + +class TGeoNodeElement : public TObjectElement { + +public: + TGeoNodeElement(TGeoNode *node) : TObjectElement(node) {} + + TGeoNodeElement(std::unique_ptr &br) : TObjectElement(br) {} + + TGeoNode *GetNode() const + { + if (!CheckObject()) return nullptr; + return dynamic_cast(fObj); + } + + /** Get default action */ + EActionKind GetDefaultAction() const override + { + return kActGeom; + } + + /** Check if want to perform action */ + bool IsCapable(EActionKind action) const override + { + return action == kActGeom; + } + + /** Provide iterator over TGeoVolume */ + std::unique_ptr GetChildsIter() override; +}; + + +//////////////////////////////////////////////////////////// +/// Iterating over nodes in the volume + +class TGeoVolumeIter : public RLevelIter { + TGeoIterator fIter; ///GetName(); } + + bool CanItemHaveChilds() const override + { + return fCurrent ? fCurrent->IsFolder() : false; + } + + /** Returns full information for current element */ + std::shared_ptr GetElement() override + { + return std::make_shared(fCurrent); + } + + /** Returns full item information */ + std::unique_ptr CreateItem() override + { + auto item = RLevelIter::CreateItem(); + item->SetIcon("sap-icon://product"); + return item; + } +}; + + +/** Provide iterator over TGeoManager */ +std::unique_ptr TGeoVolumeElement::GetChildsIter() +{ + auto vol = GetVolume(); + return vol ? std::make_unique(vol) : nullptr; +} + +/** Provide iterator over TGeoManager */ +std::unique_ptr TGeoNodeElement::GetChildsIter() +{ + auto node = GetNode(); + return node ? std::make_unique(node->GetVolume()) : nullptr; +} + + +//////////////////////////////////////////////////////////// +/// Representing TGeoManager in browsables + +class TGeoManagerElement : public TObjectElement { + +public: + TGeoManagerElement(std::unique_ptr &br) : TObjectElement(br) {} + + const TObject *CheckObject() const override + { + // during TROOT destructor just forget about file reference + if (!gROOT || gROOT->TestBit(TObject::kInvalidObject)) { + ForgetObject(); + return nullptr; + } + + return TObjectElement::CheckObject(); + } + + TGeoManager *GetMgr() const + { + if (!CheckObject()) return nullptr; + return dynamic_cast(fObj); + } + + Long64_t GetSize() const override + { + auto mgr = GetMgr(); + return mgr ? 128 : -1; + } + + bool IsFolder() const override { return true; } + + /** Get default action */ + EActionKind GetDefaultAction() const override + { + return kActGeom; + } + + /** Check if want to perform action */ + bool IsCapable(EActionKind action) const override + { + return action == kActGeom; + } + + /** Provide iterator over TGeoManager */ + std::unique_ptr GetChildsIter() override + { + auto mgr = GetMgr(); + + return mgr ? std::make_unique(mgr->GetMasterVolume()) : nullptr; + } + +}; + + +///////////////////////////////////////////////////////////////////////////////// +/// Provider for TGeo browsing + +class TGeoBrowseProvider : public RProvider { + +public: + TGeoBrowseProvider() + { + RegisterBrowse(TGeoManager::Class(), [](std::unique_ptr &object) -> std::shared_ptr { + return std::make_shared(object); + }); + RegisterBrowse(TGeoVolume::Class(), [](std::unique_ptr &object) -> std::shared_ptr { + return std::make_shared(object); + }); + RegisterBrowse(TGeoNode::Class(), [](std::unique_ptr &object) -> std::shared_ptr { + return std::make_shared(object); + }); + } + +} newTGeoBrowseProvider; + +} // namespace Browsable +} // namespace ROOT diff --git a/gui/browsable/src/TLeafDraw7Provider.cxx b/gui/browsable/src/TLeafDraw7Provider.cxx index 5f1376de3355c..0e5ec5993e350 100644 --- a/gui/browsable/src/TLeafDraw7Provider.cxx +++ b/gui/browsable/src/TLeafDraw7Provider.cxx @@ -11,13 +11,11 @@ #include #include -using namespace ROOT::Experimental; - -/** Provider for drawing of ROOT7 classes */ +/** Provider for drawing TLeaf/TBranch in ROOT7 canvas */ class TLeafDraw7Provider : public TLeafProvider { public: - bool AddHist(std::shared_ptr &subpad, TH1 *hist, const std::string &opt) + bool AddHist(std::shared_ptr &subpad, TH1 *hist, const std::string &opt) { if (!hist) return false; @@ -32,19 +30,19 @@ class TLeafDraw7Provider : public TLeafProvider { TLeafDraw7Provider() { - RegisterDraw7(TLeaf::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { + RegisterDraw7(TLeaf::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { return AddHist(subpad, DrawLeaf(obj), opt); }); - RegisterDraw7(TBranchElement::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { + RegisterDraw7(TBranchElement::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { return AddHist(subpad, DrawBranchElement(obj), opt); }); - RegisterDraw7(TBranch::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { + RegisterDraw7(TBranch::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { return AddHist(subpad, DrawBranch(obj), opt); }); - RegisterDraw7(TVirtualBranchBrowsable::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { + RegisterDraw7(TVirtualBranchBrowsable::Class(), [this](std::shared_ptr &subpad, std::unique_ptr &obj, const std::string &opt) -> bool { return AddHist(subpad, DrawBranchBrowsable(obj), opt); }); diff --git a/gui/browsable/src/TLeafProvider.hxx b/gui/browsable/src/TLeafProvider.hxx index 10d3e39efc2c2..7411b41ebf3f5 100644 --- a/gui/browsable/src/TLeafProvider.hxx +++ b/gui/browsable/src/TLeafProvider.hxx @@ -16,12 +16,75 @@ #include "TTree.h" #include "TH1.h" #include "TDirectory.h" +#include "TSystem.h" +#include "TVirtualMonitoring.h" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; + +class TTreeDrawMonitoring : public TVirtualMonitoringWriter { + +private: + + TTreeDrawMonitoring(const TTreeDrawMonitoring&) = delete; + TTreeDrawMonitoring& operator=(const TTreeDrawMonitoring&) = delete; + + Int_t fPeriod{100}; + TTree *fTree{nullptr}; + void *fHandle2{nullptr}; + long long fLastProgressSendTm{0}; + +public: + TTreeDrawMonitoring(Int_t period, TTree *tree, void *handle2) + : TVirtualMonitoringWriter(), fPeriod(period), fTree(tree), fHandle2(handle2) + { + } + + // TFile related info. In general they are gathered and sent only sometimes as summaries + Bool_t SendFileCloseEvent(TFile * /*file*/) override { return kFALSE; } + Bool_t SendFileReadProgress(TFile * /*file*/) override { return kFALSE; } + Bool_t SendFileWriteProgress(TFile * /*file*/) override { return kFALSE; } + + Bool_t SendParameters(TList * /*valuelist*/, const char * /*identifier*/ = nullptr) override { return kFALSE; } + Bool_t SendInfoTime() override { return kFALSE; } + Bool_t SendInfoUser(const char * /*user*/ = nullptr) override { return kFALSE; } + Bool_t SendInfoDescription(const char * /*jobtag*/) override { return kFALSE; } + Bool_t SendInfoStatus(const char * /*status*/) override { return kFALSE; } + + Bool_t SendFileOpenProgress(TFile * /*file*/, TList * /*openphases*/, const char * /*openphasename*/, + Bool_t /*forcesend*/ = kFALSE) override + { + return kFALSE; + } + + Bool_t SendProcessingStatus(const char * /*status*/, Bool_t /*restarttimer*/ = kFALSE) override { return kFALSE; } + Bool_t SendProcessingProgress(Double_t nevent, Double_t /*nbytes*/, Bool_t /*force*/ = kFALSE) override + { + long long millisec = gSystem->Now(); + + if (fLastProgressSendTm && (millisec < fLastProgressSendTm + fPeriod)) + return kTRUE; + + fLastProgressSendTm = millisec; + + gSystem->ProcessEvents(); + + Double_t total = fTree->GetEntries(); + + if (total > 0) + RProvider::ReportProgress(fHandle2, nevent <= total ? nevent / total : 1.); + + return kTRUE; + } + void SetLogLevel(const char * /*loglevel*/ = "WARNING") override {} + void Verbose(Bool_t /*onoff*/) override {} +}; /** Provider for drawing of branches / leafs in the TTree */ class TLeafProvider : public RProvider { + + void *fHandle2{nullptr}; ///>htemp_tree_draw"; + auto old = gMonitoringWriter; + std::unique_ptr monitoring; + + if (fHandle2 && RProvider::ReportProgress(fHandle2, 0.)) { + monitoring = std::make_unique(50, ttree, fHandle2); + gMonitoringWriter = monitoring.get(); + } + ttree->Draw(expr2.c_str(),"","goff"); + gMonitoringWriter = old; + if (!gDirectory) return nullptr; @@ -89,7 +162,10 @@ public: expr.Remove(pos+1, 1); pos --; while ((pos > 0) && (expr[pos] != '.')) pos--; - if (pos > 0) expr.Insert(pos+1, "@"); + if (pos > 0) + expr.Insert(pos+1, "@"); + else + expr.Prepend("@"); } expr.ReplaceAll("->@","@->"); @@ -135,7 +211,6 @@ public: return true; } - TH1 *DrawBranch(const TBranch *tbranch) { TString expr, name; @@ -147,11 +222,14 @@ public: TH1 *DrawBranch(std::unique_ptr &obj) { + fHandle2 = obj.get(); return DrawBranch(obj->get_object()); } TH1 *DrawLeaf(std::unique_ptr &obj) { + fHandle2 = obj.get(); + auto tleaf = obj->get_object(); TString expr, name; @@ -225,6 +303,8 @@ public: TH1 *DrawBranchElement(std::unique_ptr &obj) { + fHandle2 = obj.get(); + auto tbranch = obj->get_object(); TString expr, name; if (!GetDrawExpr(tbranch, expr, name)) diff --git a/gui/browsable/src/TObjectDraw6Provider.cxx b/gui/browsable/src/TObjectDraw6Provider.cxx index 46d6156145f44..a8c82e80771ed 100644 --- a/gui/browsable/src/TObjectDraw6Provider.cxx +++ b/gui/browsable/src/TObjectDraw6Provider.cxx @@ -11,7 +11,7 @@ #include "TObject.h" #include "TVirtualPad.h" -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; /** Provider for drawing of ROOT6 classes */ diff --git a/gui/browsable/src/TObjectDraw7Provider.cxx b/gui/browsable/src/TObjectDraw7Provider.cxx index 0dd47c23336b1..c2620a7e326ca 100644 --- a/gui/browsable/src/TObjectDraw7Provider.cxx +++ b/gui/browsable/src/TObjectDraw7Provider.cxx @@ -12,7 +12,7 @@ #include #include -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; /** Provider for drawing of ROOT7 classes */ diff --git a/gui/browsable/src/TObjectElement.cxx b/gui/browsable/src/TObjectElement.cxx index 14acff93cfd96..1f0592006a40d 100644 --- a/gui/browsable/src/TObjectElement.cxx +++ b/gui/browsable/src/TObjectElement.cxx @@ -27,7 +27,7 @@ using namespace std::string_literals; -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; /** \class TObjectLevelIter @@ -314,7 +314,12 @@ void TObjectElement::SetObject(TObject *obj) void TObjectElement::ForgetObject() const { - const_cast(this)->fObj = nullptr; + auto elem = const_cast(this); + elem->fObj = nullptr; + if (elem->fObject) { + elem->fObject->Forget(); + elem->fObject.reset(); + } } //////////////////////////////////////////////////////////////////////////////// @@ -408,10 +413,9 @@ std::unique_ptr TObjectElement::GetObject() bool TObjectElement::IsObject(void *obj) { - if (CheckObject() == obj) - return true; + return (fObj && (fObj == obj)); - return fObject && (fObject->get_object() == obj); + // return fObject && (fObject->get_object() == obj); } //////////////////////////////////////////////////////////////////////////////// @@ -456,7 +460,7 @@ std::unique_ptr TObjectElement::CreateItem() const if (!obj) return RElement::CreateItem(); - auto isfolder = !IsHideChilds() && obj->IsFolder(); + auto isfolder = !IsHideChilds() && IsFolder(); auto item = std::make_unique(obj->GetName(), isfolder ? -1 : 0); @@ -584,9 +588,10 @@ class RTObjectProvider : public RProvider { RegisterTObject("TMultiGraph", "sap-icon://multiple-line-chart"); RegisterTObject("TCollection", "sap-icon://list", true, 0); - RegisterTObject("TGeoManager", "sap-icon://overview-chart", true, 0); - RegisterTObject("TGeoVolume", "sap-icon://product", true, 0); - RegisterTObject("TGeoNode", "sap-icon://product", true, 0); + + RegisterClass("TGeoManager", "sap-icon://overview-chart", "libROOTGeoBrowseProvider"); + RegisterClass("TGeoVolume", "sap-icon://product", "libROOTGeoBrowseProvider"); + RegisterClass("TGeoNode", "sap-icon://product", "libROOTGeoBrowseProvider"); RegisterBrowse(TFolder::Class(), [](std::unique_ptr &object) -> std::shared_ptr { return std::make_shared(object); diff --git a/gui/browsable/src/TObjectHolder.cxx b/gui/browsable/src/TObjectHolder.cxx index 010c8d630e9c0..f7b699edf548f 100644 --- a/gui/browsable/src/TObjectHolder.cxx +++ b/gui/browsable/src/TObjectHolder.cxx @@ -11,7 +11,7 @@ #include "TROOT.h" #include -using namespace ROOT::Experimental::Browsable; +using namespace ROOT::Browsable; /////////////////////////////////////////////////////////////////////////// /// Check if object is not registered in some global lists diff --git a/gui/browserv7/inc/LinkDef.h b/gui/browserv7/inc/LinkDef.h index 17bb83100b997..1828184707af6 100644 --- a/gui/browserv7/inc/LinkDef.h +++ b/gui/browserv7/inc/LinkDef.h @@ -12,14 +12,14 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class ROOT::Experimental::RBrowserRequest+; -#pragma link C++ class ROOT::Experimental::RBrowserReply+; +#pragma link C++ class ROOT::RBrowserRequest+; +#pragma link C++ class ROOT::RBrowserReply+; -#pragma link C++ class ROOT::Experimental::RBrowserData+; +#pragma link C++ class ROOT::RBrowserData+; -#pragma link C++ class ROOT::Experimental::RBrowser+; -#pragma link C++ class ROOT::Experimental::RFileDialog+; +#pragma link C++ class ROOT::RBrowser+; +#pragma link C++ class ROOT::RFileDialog+; -#pragma link C++ class ROOT::Experimental::RWebBrowserImp+; +#pragma link C++ class ROOT::RWebBrowserImp+; #endif diff --git a/gui/browserv7/inc/ROOT/RBrowser.hxx b/gui/browserv7/inc/ROOT/RBrowser.hxx index 66b1dd9ec3701..1e8740ddb52ff 100644 --- a/gui/browserv7/inc/ROOT/RBrowser.hxx +++ b/gui/browserv7/inc/ROOT/RBrowser.hxx @@ -20,12 +20,14 @@ #include namespace ROOT { -namespace Experimental { class RBrowserWidget; +class RBrowserTimer; class RBrowser { + friend class RBrowserTimer; + protected: std::string fTitle; ///> fWidgets; /// fWebWindow; /// fTimer; ///> fPostponed; /// AddWidget(const std::string &kind); std::shared_ptr AddCatchedWidget(const std::string &url, const std::string &kind); @@ -50,7 +56,7 @@ protected: void CloseTab(const std::string &name); std::string ProcessBrowserRequest(const std::string &msg); - std::string ProcessDblClick(std::vector &args); + std::string ProcessDblClick(unsigned connid, std::vector &args); std::string NewWidgetMsg(std::shared_ptr &widget); void ProcessRunMacro(const std::string &file_path); void ProcessSaveFile(const std::string &fname, const std::string &content); @@ -61,13 +67,16 @@ protected: void SendInitMsg(unsigned connid); void ProcessMsg(unsigned connid, const std::string &arg); + void SendProgress(unsigned connid, float progr); void AddInitWidget(const std::string &kind); void CheckWidgtesModified(); + void ProcessPostponedRequests(); + public: - RBrowser(bool use_rcanvas = true); + RBrowser(bool use_rcanvas = false); virtual ~RBrowser(); bool GetUseRCanvas() const { return fUseRCanvas; } @@ -92,9 +101,10 @@ public: bool ActivateWidget(const std::string &title, const std::string &kind = ""); + void ClearOnClose(const std::shared_ptr &handle); + }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/inc/ROOT/RBrowserData.hxx b/gui/browserv7/inc/ROOT/RBrowserData.hxx index c7a68fd41d060..8c34caa29b031 100644 --- a/gui/browserv7/inc/ROOT/RBrowserData.hxx +++ b/gui/browserv7/inc/ROOT/RBrowserData.hxx @@ -24,11 +24,13 @@ #include namespace ROOT { -namespace Experimental { +namespace Experimental { class RLogChannel; +} // namespace Experimental + /// Log channel for Browser diagnostics. -RLogChannel &BrowserLog(); +ROOT::Experimental::RLogChannel &BrowserLog(); class RBrowserDataCleanup; @@ -49,7 +51,7 @@ class RBrowserData { std::vector fLastSortedItems; /// fCleanupHandle; /// fCleanupHandle; /// namespace ROOT { -namespace Experimental { -/** \class ROOT::Experimental::RBrowserReply +/** \class ROOT::RBrowserReply \ingroup rbrowser \brief Reply on browser request */ @@ -33,7 +32,6 @@ public: std::vector nodes; ///< list of pointers, no ownership! }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/inc/ROOT/RBrowserRequest.hxx b/gui/browserv7/inc/ROOT/RBrowserRequest.hxx index 3c2132175e0e8..0bd2ab0cf48cf 100644 --- a/gui/browserv7/inc/ROOT/RBrowserRequest.hxx +++ b/gui/browserv7/inc/ROOT/RBrowserRequest.hxx @@ -17,9 +17,8 @@ #include namespace ROOT { -namespace Experimental { -/** \class ROOT::Experimental::RBrowserRequest +/** \class ROOT::RBrowserRequest \ingroup rbrowser \brief Request send from client to get content of path element */ @@ -37,7 +36,6 @@ public: std::string regex; ///< applied regex }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/inc/ROOT/RFileDialog.hxx b/gui/browserv7/inc/ROOT/RFileDialog.hxx index 6e60b8b02355d..2fe0ca2696b5b 100644 --- a/gui/browserv7/inc/ROOT/RFileDialog.hxx +++ b/gui/browserv7/inc/ROOT/RFileDialog.hxx @@ -21,9 +21,12 @@ #include namespace ROOT { -namespace Experimental { -/** \class ROOT::Experimental::RFileDialog +namespace Details { + class RWebWindowPlugin; +} + +/** \class ROOT::RFileDialog \ingroup rbrowser Initial message send to client to configure layout */ @@ -36,6 +39,7 @@ using RFileDialogCallback_t = std::function; /** Web-based FileDialog */ class RFileDialog { + friend class Details::RWebWindowPlugin; public: enum EDialogTypes { @@ -72,6 +76,8 @@ protected: static std::string Dialog(EDialogTypes kind, const std::string &title, const std::string &fname); + static void SetStartFunc(bool on); + public: RFileDialog(EDialogTypes kind = kOpenFile, const std::string &title = "", const std::string &fname = ""); @@ -109,11 +115,12 @@ public: static std::string SaveAs(const std::string &title = "", const std::string &fname = ""); static std::string NewFile(const std::string &title = "", const std::string &fname = ""); - static std::shared_ptr Embedded(const std::shared_ptr &window, const std::string &args); + static std::shared_ptr Embed(const std::shared_ptr &window, unsigned connid, const std::string &args); + + static bool IsMessageToStartDialog(const std::string &msg); }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/inc/ROOT/RWebBrowserImp.hxx b/gui/browserv7/inc/ROOT/RWebBrowserImp.hxx index 96c2cd0996b8f..00672bd9a098e 100644 --- a/gui/browserv7/inc/ROOT/RWebBrowserImp.hxx +++ b/gui/browserv7/inc/ROOT/RWebBrowserImp.hxx @@ -18,7 +18,6 @@ #include "ROOT/RBrowser.hxx" namespace ROOT { -namespace Experimental { class RWebBrowserImp : public TBrowserImp { @@ -44,7 +43,6 @@ public: ClassDefOverride(RWebBrowserImp,0) // browser implementation for RBrowser }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/src/RBrowser.cxx b/gui/browserv7/src/RBrowser.cxx index eb2743b827269..253df7da3e691 100644 --- a/gui/browserv7/src/RBrowser.cxx +++ b/gui/browserv7/src/RBrowser.cxx @@ -25,6 +25,7 @@ #include "TString.h" #include "TSystem.h" #include "TError.h" +#include "TTimer.h" #include "TROOT.h" #include "TBufferJSON.h" #include "TApplication.h" @@ -41,7 +42,19 @@ using namespace std::string_literals; -using namespace ROOT::Experimental; +namespace ROOT { + +class RBrowserTimer : public TTimer { +public: + RBrowser &fBrowser; ///!< browser processing postponed requests + + /// constructor + RBrowserTimer(Long_t milliSec, Bool_t mode, RBrowser &br) : TTimer(milliSec, mode), fBrowser(br) {} + + /// timeout handler + /// used to process postponed requests in main ROOT thread + void Timeout() override { fBrowser.ProcessPostponedRequests(); } +}; class RBrowserEditorWidget : public RBrowserWidget { @@ -241,8 +254,12 @@ class RBrowserCatchedWidget : public RBrowserWidget { } }; +} // namespace ROOT + +using namespace ROOT; -/** \class ROOT::Experimental::RBrowser + +/** \class ROOT::RBrowser \ingroup rbrowser \brief Web-based %ROOT files and objects browser @@ -268,6 +285,8 @@ RBrowser::RBrowser(bool use_rcanvas) fBrowsable.CreateDefaultElements(); + fTimer = std::make_unique(10, kTRUE, *this); + fWebWindow = RWebWindow::Create(); fWebWindow->SetDefaultPage("file:rootui5sys/browser/browser.html"); @@ -378,7 +397,7 @@ void RBrowser::ProcessRunMacro(const std::string &file_path) ///////////////////////////////////////////////////////////////////////////////// /// Process dbl click on browser item -std::string RBrowser::ProcessDblClick(std::vector &args) +std::string RBrowser::ProcessDblClick(unsigned connid, std::vector &args) { args.pop_back(); // remove exec string, not used now @@ -426,6 +445,11 @@ std::string RBrowser::ProcessDblClick(std::vector &args) elem->GetChildsIter(); } + fLastProgressSend = 0; + Browsable::RProvider::ProgressHandle handle(elem.get(), [this, connid](float progress, void *) { + SendProgress(connid, progress); + }); + auto widget = GetActiveWidget(); if (widget && widget->DrawElement(elem, opt)) { widget->SetPath(path); @@ -674,6 +698,26 @@ void RBrowser::SendInitMsg(unsigned connid) fWebWindow->Send(connid, msg); } +////////////////////////////////////////////////////////////////////////////////////////////// +/// Send generic progress message to the web window +/// Should show progress bar on client side + +void RBrowser::SendProgress(unsigned connid, float progr) +{ + long long millisec = gSystem->Now(); + + // let process window events + fWebWindow->Sync(); + + if ((!fLastProgressSendTm || millisec > fLastProgressSendTm - 200) && (progr > fLastProgressSend + 0.04) && fWebWindow->CanSend(connid)) { + fWebWindow->Send(connid, "PROGRESS:"s + std::to_string(progr)); + + fLastProgressSendTm = millisec; + fLastProgressSend = progr; + } +} + + ////////////////////////////////////////////////////////////////////////////////////////////// /// Return the current directory of ROOT @@ -701,6 +745,34 @@ void RBrowser::CheckWidgtesModified() widget->CheckModified(); } +////////////////////////////////////////////////////////////////////////////////////////////// +/// Process postponed requests - decouple from websocket handling +/// Only requests which can take longer time should be postponed + +void RBrowser::ProcessPostponedRequests() +{ + if (fPostponed.empty()) + return; + + auto arr = fPostponed[0]; + fPostponed.erase(fPostponed.begin(), fPostponed.begin()+1); + if (fPostponed.empty()) + fTimer->TurnOff(); + + std::string reply; + unsigned connid = std::stoul(arr.back()); arr.pop_back(); + std::string kind = arr.back(); arr.pop_back(); + + if (kind == "DBLCLK") { + reply = ProcessDblClick(connid, arr); + if (reply.empty()) reply = "NOPE"; + } + + if (!reply.empty()) + fWebWindow->Send(connid, reply); +} + + ////////////////////////////////////////////////////////////////////////////////////////////// /// Process received message from the client @@ -728,16 +800,16 @@ void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0) } else if (kind == "DBLCLK") { - std::string reply; - auto arr = TBufferJSON::FromJSON>(msg); - if (arr && (arr->size() > 2)) - reply = ProcessDblClick(*arr); - - if (reply.empty()) - reply = "NOPE"; - - fWebWindow->Send(connid, reply); + if (arr && (arr->size() > 2)) { + arr->push_back(kind); + arr->push_back(std::to_string(connid)); + fPostponed.push_back(*arr); + if (fPostponed.size() == 1) + fTimer->TurnOn(); + } else { + fWebWindow->Send(connid, "NOPE"); + } } else if (kind == "WIDGET_SELECTED") { fActiveWidgetName = msg; @@ -796,8 +868,10 @@ void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0) auto logs = GetRootLogs(); fWebWindow->Send(connid, "LOGS:"s + TBufferJSON::ToJSON(&logs, TBufferJSON::kNoSpaces).Data()); - } else if (kind == "FILEDIALOG") { - RFileDialog::Embedded(fWebWindow, arg0); + } else if (RFileDialog::IsMessageToStartDialog(arg0)) { + + RFileDialog::Embed(fWebWindow, connid, arg0); + } else if (kind == "SYNCEDITOR") { auto arr = TBufferJSON::FromJSON>(msg); if (arr && (arr->size() > 4)) { @@ -884,4 +958,10 @@ bool RBrowser::ActivateWidget(const std::string &title, const std::string &kind) return false; } +////////////////////////////////////////////////////////////////////////////////////////////// +/// Set handle which will be cleared when connection is closed +void RBrowser::ClearOnClose(const std::shared_ptr &handle) +{ + fWebWindow->SetClearOnClose(handle); +} diff --git a/gui/browserv7/src/RBrowserData.cxx b/gui/browserv7/src/RBrowserData.cxx index 99096f5deb385..5ded649ab85f9 100644 --- a/gui/browserv7/src/RBrowserData.cxx +++ b/gui/browserv7/src/RBrowserData.cxx @@ -29,16 +29,16 @@ #include #include -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; -ROOT::Experimental::RLogChannel &ROOT::Experimental::BrowserLog() { - static RLogChannel sLog("ROOT.Browser"); +ROOT::Experimental::RLogChannel &ROOT::BrowserLog() +{ + static ROOT::Experimental::RLogChannel sLog("ROOT.Browser"); return sLog; } namespace ROOT { -namespace Experimental { class RBrowserDataCleanup : public TObject { @@ -52,11 +52,11 @@ class RBrowserDataCleanup : public TObject { fData.RemoveFromCache(obj); } }; -} -} + +} // namespace ROOT -/** \class ROOT::Experimental::RBrowserData +/** \class ROOT::RBrowserData \ingroup rbrowser \brief Way to browse (hopefully) everything in %ROOT */ diff --git a/gui/browserv7/src/RBrowserGeomWidget.cxx b/gui/browserv7/src/RBrowserGeomWidget.cxx index 4d99f455ee882..7859f76b36f42 100644 --- a/gui/browserv7/src/RBrowserGeomWidget.cxx +++ b/gui/browserv7/src/RBrowserGeomWidget.cxx @@ -19,7 +19,7 @@ #include "TGeoMaterial.h" #include "TGeoMedium.h" -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; diff --git a/gui/browserv7/src/RBrowserRCanvasWidget.cxx b/gui/browserv7/src/RBrowserRCanvasWidget.cxx index d3fb9b5dba7ce..2cb0f3701a20b 100644 --- a/gui/browserv7/src/RBrowserRCanvasWidget.cxx +++ b/gui/browserv7/src/RBrowserRCanvasWidget.cxx @@ -16,28 +16,27 @@ #include -using namespace ROOT::Experimental; - using namespace std::string_literals; +using namespace ROOT::Browsable; -class RBrowserRCanvasWidget : public RBrowserWidget { +class RBrowserRCanvasWidget : public ROOT::RBrowserWidget { - std::shared_ptr fCanvas; /// fCanvas; /// &canv) : RBrowserWidget(name) + RBrowserRCanvasWidget(const std::string &name, std::shared_ptr &canv) : ROOT::RBrowserWidget(name) { fCanvas = std::move(canv); } - virtual ~RBrowserRCanvasWidget() = default; + ~RBrowserRCanvasWidget() override = default; std::string GetKind() const override { return "rcanvas"s; } @@ -56,16 +55,18 @@ class RBrowserRCanvasWidget : public RBrowserWidget { return fCanvas->GetTitle(); } - bool DrawElement(std::shared_ptr &elem, const std::string &opt = "") override + bool DrawElement(std::shared_ptr &elem, const std::string &opt = "") override { - if (!elem->IsCapable(Browsable::RElement::kActDraw7)) + if (!elem->IsCapable(RElement::kActDraw7)) return false; auto obj = elem->GetObject(); if (!obj) return false; - std::shared_ptr subpad = fCanvas; + RProvider::ExtendProgressHandle(elem.get(), obj.get()); + + std::shared_ptr subpad = fCanvas; std::string drawopt = opt; @@ -78,9 +79,9 @@ class RBrowserRCanvasWidget : public RBrowserWidget { } if (drawopt == "") - drawopt = Browsable::RProvider::GetClassDrawOption(obj->GetClass()); + drawopt = RProvider::GetClassDrawOption(obj->GetClass()); - if (Browsable::RProvider::Draw7(subpad, obj, drawopt)) { + if (RProvider::Draw7(subpad, obj, drawopt)) { fCanvas->Modified(); fCanvas->Update(true); return true; @@ -99,25 +100,25 @@ class RBrowserRCanvasWidget : public RBrowserWidget { // ====================================================================== -class RBrowserRCanvasProvider : public RBrowserWidgetProvider { +class RBrowserRCanvasProvider : public ROOT::RBrowserWidgetProvider { protected: - std::shared_ptr Create(const std::string &name) final + std::shared_ptr Create(const std::string &name) final { return std::make_shared(name); } - std::shared_ptr CreateFor(const std::string &name, std::shared_ptr &elem) final + std::shared_ptr CreateFor(const std::string &name, std::shared_ptr &elem) final { auto holder = elem->GetObject(); if (!holder) return nullptr; - auto canv = holder->get_shared(); + auto canv = holder->get_shared(); if (!canv) return nullptr; return std::make_shared(name, canv); } public: - RBrowserRCanvasProvider() : RBrowserWidgetProvider("rcanvas") {} - ~RBrowserRCanvasProvider() = default; + RBrowserRCanvasProvider() : ROOT::RBrowserWidgetProvider("rcanvas") {} + ~RBrowserRCanvasProvider() override = default; } sRBrowserRCanvasProvider; diff --git a/gui/browserv7/src/RBrowserTCanvasWidget.cxx b/gui/browserv7/src/RBrowserTCanvasWidget.cxx index 9a3932c3dba27..a76db43e2f92c 100644 --- a/gui/browserv7/src/RBrowserTCanvasWidget.cxx +++ b/gui/browserv7/src/RBrowserTCanvasWidget.cxx @@ -22,7 +22,7 @@ #include -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; @@ -97,6 +97,9 @@ class RBrowserTCanvasWidget : public RBrowserWidget { // create implementation fWebCanvas = new TWebCanvas(fCanvas.get(), "title", 0, 0, 800, 600, readonly); + // use async mode to prevent blocking inside qt5/qt6/cef + fWebCanvas->SetAsyncMode(kTRUE); + // assign implementation fCanvas->SetCanvasImp(fWebCanvas); SetPrivateCanvasFields(true); @@ -116,6 +119,9 @@ class RBrowserTCanvasWidget : public RBrowserWidget { // create implementation fWebCanvas = new TWebCanvas(fCanvas.get(), "title", 0, 0, 800, 600, readonly); + // use async mode to prevent blocking inside qt5/qt6/cef + fWebCanvas->SetAsyncMode(kTRUE); + // assign implementation fCanvas->SetCanvasImp(fWebCanvas); SetPrivateCanvasFields(true); @@ -136,6 +142,11 @@ class RBrowserTCanvasWidget : public RBrowserWidget { gROOT->GetListOfCanvases()->Remove(fCanvas.get()); + if ((fCanvas->GetCanvasID() == -1) && (fCanvas->GetCanvasImp() == fWebCanvas)) { + fCanvas->SetCanvasImp(nullptr); + delete fWebCanvas; + } + fCanvas->Close(); } @@ -170,6 +181,8 @@ class RBrowserTCanvasWidget : public RBrowserWidget { if (!obj) return false; + Browsable::RProvider::ExtendProgressHandle(elem.get(), obj.get()); + std::string drawopt = opt; // first remove all objects which may belong to removed pads @@ -205,7 +218,7 @@ class RBrowserTCanvasWidget : public RBrowserWidget { if (Browsable::RProvider::Draw6(pad, obj, drawopt)) { fObjects.emplace(pad, std::move(obj)); pad->Modified(); - fCanvas->Update(); + fCanvas->UpdateAsync(); return true; } @@ -215,7 +228,7 @@ class RBrowserTCanvasWidget : public RBrowserWidget { void CheckModified() override { if (fCanvas->IsModified()) - fCanvas->Update(); + fCanvas->UpdateAsync(); } }; diff --git a/gui/browserv7/src/RBrowserTreeWidget.cxx b/gui/browserv7/src/RBrowserTreeWidget.cxx index 4c63d6c16dcfe..621eca30de210 100644 --- a/gui/browserv7/src/RBrowserTreeWidget.cxx +++ b/gui/browserv7/src/RBrowserTreeWidget.cxx @@ -20,7 +20,7 @@ #include "TBranchBrowsable.h" #include "TLeaf.h" -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; diff --git a/gui/browserv7/src/RBrowserWidget.cxx b/gui/browserv7/src/RBrowserWidget.cxx index 7296904b95b71..993af33bd9f15 100644 --- a/gui/browserv7/src/RBrowserWidget.cxx +++ b/gui/browserv7/src/RBrowserWidget.cxx @@ -17,10 +17,8 @@ #include "TSystem.h" #include "TBufferJSON.h" - using namespace std::string_literals; -using namespace ROOT::Experimental; - +using namespace ROOT; /////////////////////////////////////////////////////////////// /// Returns string which can be send to browser client to set/change diff --git a/gui/browserv7/src/RBrowserWidget.hxx b/gui/browserv7/src/RBrowserWidget.hxx index 04e108dc9e14a..8aca96548cf05 100644 --- a/gui/browserv7/src/RBrowserWidget.hxx +++ b/gui/browserv7/src/RBrowserWidget.hxx @@ -20,11 +20,10 @@ #include namespace ROOT { -namespace Experimental { class RBrowser; -/** \class ROOT::Experimental::RBrowserWidget +/** \class ROOT::RBrowserWidget \ingroup rbrowser Abstract Web-based widget, which can be used in the RBrowser Used to embed canvas, geometry viewer and potentially any other widgets @@ -88,8 +87,6 @@ public: static std::shared_ptr CreateWidgetFor(const std::string &kind, const std::string &name, std::shared_ptr &element); }; - -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/browserv7/src/RFileDialog.cxx b/gui/browserv7/src/RFileDialog.cxx index c743ba5a80173..44a570318cc49 100644 --- a/gui/browserv7/src/RFileDialog.cxx +++ b/gui/browserv7/src/RFileDialog.cxx @@ -27,10 +27,10 @@ #include #include -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; -/** \class ROOT::Experimental::RFileDialog +/** \class ROOT::RFileDialog \ingroup rbrowser web-based FileDialog. @@ -416,17 +416,27 @@ std::string RFileDialog::NewFile(const std::string &title, const std::string &fn return Dialog(kNewFile, title, fname); } +///////////////////////////////////////////////////////////////////////////////////// +/// Check if this could be the message send by client to start new file dialog +/// If returns true, one can call RFileDialog::Embedded() to really create file dialog +/// instance inside existing widget + +bool RFileDialog::IsMessageToStartDialog(const std::string &msg) +{ + return msg.compare(0, 11, "FILEDIALOG:") == 0; +} + ///////////////////////////////////////////////////////////////////////////////////// /// Create dialog instance to use as embedded dialog inside other widget /// Embedded dialog started on the client side where FileDialogController.SaveAs() method called /// Such method immediately send message with "FILEDIALOG:" prefix -/// On the server side widget should detect such message and call RFileDialog::Embedded() +/// On the server side widget should detect such message and call RFileDialog::Embed() /// providing received string as second argument. /// Returned instance of shared_ptr may be used to assign callback when file is selected -std::shared_ptr RFileDialog::Embedded(const std::shared_ptr &window, const std::string &args) +std::shared_ptr RFileDialog::Embed(const std::shared_ptr &window, unsigned connid, const std::string &args) { - if (args.compare(0, 11, "FILEDIALOG:") != 0) + if (!IsMessageToStartDialog(args)) return nullptr; auto arr = TBufferJSON::FromJSON>(args.substr(11)); @@ -466,10 +476,41 @@ std::shared_ptr RFileDialog::Embedded(const std::shared_ptrSetNameFilters(*arr); } - dialog->Show({window, chid}); + dialog->Show({window, connid, chid}); // use callback to release pointer, actually not needed but just to avoid compiler warning dialog->SetCallback([dialog](const std::string &) mutable { dialog.reset(); }); return dialog; } + +///////////////////////////////////////////////////////////////////////////////////// +/// Set start dialog function for RWebWindow + +void RFileDialog::SetStartFunc(bool on) +{ + if (on) + RWebWindow::SetStartDialogFunc([](const std::shared_ptr &window, unsigned connid, const std::string &args) -> bool { + auto res = RFileDialog::Embed(window, connid, args); + return res ? true : false; + }); + else + RWebWindow::SetStartDialogFunc(nullptr); +} + + +///////////////////////////////////////////////////////////////////////////////////// + +namespace ROOT { +namespace Details { + +class RWebWindowPlugin { +public: + RWebWindowPlugin() { RFileDialog::SetStartFunc(true); } + + ~RWebWindowPlugin() { RFileDialog::SetStartFunc(false); } +} sRWebWindowPlugin; + +} +} + diff --git a/gui/browserv7/src/RWebBrowserImp.cxx b/gui/browserv7/src/RWebBrowserImp.cxx index a8cfb609087ef..5c0b99dfddf9a 100644 --- a/gui/browserv7/src/RWebBrowserImp.cxx +++ b/gui/browserv7/src/RWebBrowserImp.cxx @@ -17,7 +17,7 @@ #include -using namespace ROOT::Experimental; +using namespace ROOT; //////////////////////////////////////////////////////////////////////////////////////// /// Default constructor diff --git a/gui/canvaspainter/src/RCanvasPainter.cxx b/gui/canvaspainter/src/RCanvasPainter.cxx index 443c9ac824884..d595dfbd8d784 100644 --- a/gui/canvaspainter/src/RCanvasPainter.cxx +++ b/gui/canvaspainter/src/RCanvasPainter.cxx @@ -107,7 +107,7 @@ class RCanvasPainter : public Internal::RVirtualCanvasPainter { RCanvas &fCanvas; /// fWindow; ///!< configured display + std::shared_ptr fWindow; ///!< configured display std::list fWebConn; ///> fCmds; ///) final; + bool AddPanel(std::shared_ptr) final; + + void SetClearOnClose(const std::shared_ptr &) final; /** \class CanvasPainterGenerator Creates RCanvasPainter objects. @@ -455,13 +457,19 @@ void RCanvasPainter::DoWhenReady(const std::string &name, const std::string &arg bool RCanvasPainter::ProduceBatchOutput(const std::string &fname, int width, int height) { + auto len = fname.length(); + bool is_json = (len > 4) && ((fname.compare(len-4,4,".json") == 0) || (fname.compare(len-4,4,".JSON") == 0)); + + // do not try to produce image if current settings not allowing this + if (!is_json && !RWebDisplayHandle::CanProduceImages()) + return false; + RDrawable::RDisplayContext ctxt(&fCanvas, &fCanvas, 0); ctxt.SetConnection(1, true); auto snapshot = CreateSnapshot(ctxt); - auto len = fname.length(); - if ((len > 4) && ((fname.compare(len-4,4,".json") == 0) || (fname.compare(len-4,4,".JSON") == 0))) { + if (is_json) { std::ofstream f(fname); if (!f) { R__LOG_ERROR(CanvasPainerLog()) << "Fail to open file " << fname << " to store canvas snapshot"; @@ -517,6 +525,9 @@ void RCanvasPainter::ProcessData(unsigned connid, const std::string &arg) // use window manager to correctly terminate http server and ROOT session fWindow->TerminateROOT(); return; + } else if (arg == "START_BROWSER") { + gROOT->ProcessLine("auto br = std::make_shared();br->ClearOnClose(br);"); + } else if (arg == "RELOAD") { conn->fSend = 0; // reset send version, causes new data sending } else if (arg == "INTERRUPT") { @@ -544,6 +555,10 @@ void RCanvasPainter::ProcessData(unsigned connid, const std::string &arg) TFile *f = TFile::Open(cdata.c_str(), "RECREATE"); f->WriteObject(&fCanvas, "Canvas"); delete f; + } else if (ROOT::RWebWindow::IsFileDialogMessage(arg)) { + + ROOT::RWebWindow::EmbedFileDialog(fWindow, connid, arg); + } else if (check_header("REQ:")) { auto req = TBufferJSON::FromJSON(cdata); if (req) { @@ -580,8 +595,13 @@ void RCanvasPainter::ProcessData(unsigned connid, const std::string &arg) } else { R__LOG_ERROR(CanvasPainerLog()) << "Fail to parse RDrawableRequest"; } + } else if (check_header("RESIZED:")) { + auto sz = TBufferJSON::FromJSON>(cdata); + if (sz && sz->size() == 2) { + fCanvas.SetWidth(sz->at(0)); + fCanvas.SetHeight(sz->at(1)); + } } else if (check_header("CLEAR")) { - fCanvas.Wipe(); fCanvas.Modified(); } else { @@ -598,7 +618,7 @@ void RCanvasPainter::CreateWindow() { if (fWindow) return; - fWindow = RWebWindow::Create(); + fWindow = ROOT::RWebWindow::Create(); fWindow->SetConnLimit(0); // allow any number of connections fWindow->SetDefaultPage("file:rootui5sys/canv/canvas.html"); fWindow->SetCallBacks( @@ -624,7 +644,7 @@ void RCanvasPainter::CreateWindow() //////////////////////////////////////////////////////////////////////////////// /// Create new display for the canvas -/// See RWebWindowsManager::Show() docu for more info +/// See ROOT::RWebWindowsManager::Show() docu for more info void RCanvasPainter::NewDisplay(const std::string &where) { @@ -669,7 +689,7 @@ std::string RCanvasPainter::GetWindowAddr() const //////////////////////////////////////////////////////////////////////////////// /// Add window as panel inside canvas window -bool RCanvasPainter::AddPanel(std::shared_ptr win) +bool RCanvasPainter::AddPanel(std::shared_ptr win) { if (gROOT->IsWebDisplayBatch()) return false; @@ -703,6 +723,15 @@ bool RCanvasPainter::AddPanel(std::shared_ptr win) return true; } +//////////////////////////////////////////////////////////////////////////////// +/// Set handle to window which will be cleared when connection is closed + +void RCanvasPainter::SetClearOnClose(const std::shared_ptr &handle) +{ + if (fWindow) + fWindow->SetClearOnClose(handle); +} + //////////////////////////////////////////////////////////////////////////////// /// Create JSON representation of data, which should be send to the clients /// Here server-side painting is performed - each drawable adds own elements in diff --git a/gui/cefdisplay/Readme.md b/gui/cefdisplay/Readme.md index 93ef2df59db05..1b5d3fd67ac89 100644 --- a/gui/cefdisplay/Readme.md +++ b/gui/cefdisplay/Readme.md @@ -4,16 +4,17 @@ See details about [Chromium Embedded Framework](https://bitbucket.org/chromiumembedded/cef) -1. Current code tested with CEF3 branch 5304, Chromium 107 (November 2022) - Some older CEF versions (like 4638 or 4692) may also be supported. +1. Current code tested with CEF3 branch 5845, Chromium 116 (August 2023) + Some older CEF versions (like 95 or 107) may also be supported. -2. Download binary code from [https://cef-builds.spotifycdn.com/index.html](https://cef-builds.spotifycdn.com/index.html) and unpack it in directory without spaces and special symbols: +2. Download binary code from [https://cef-builds.spotifycdn.com/index.html](https://cef-builds.spotifycdn.com/index.html) + and unpack it in directory without spaces and special symbols: ~~~ $ mkdir /d/cef $ cd /d/cef/ $ wget https://cef-builds.spotifycdn.com/cef_binary_107.1.11%2Bg26c0b5e%2Bchromium-107.0.5304.110_linux64_minimal.tar.bz2 - $ tar cef_binary_107.1.11+g26c0b5e+chromium-107.0.5304.110_linux64_minimal.tar.bz2 + $ tar xjf cef_binary_107.1.11+g26c0b5e+chromium-107.0.5304.110_linux64_minimal.tar.bz2 ~~~ diff --git a/gui/cefdisplay/inc/RCefWebDisplayHandle.hxx b/gui/cefdisplay/inc/RCefWebDisplayHandle.hxx index 1b12b00b830dc..548d858b48140 100644 --- a/gui/cefdisplay/inc/RCefWebDisplayHandle.hxx +++ b/gui/cefdisplay/inc/RCefWebDisplayHandle.hxx @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -21,16 +21,16 @@ \ingroup cefwebdisplay */ -class RCefWebDisplayHandle : public ROOT::Experimental::RWebDisplayHandle { +class RCefWebDisplayHandle : public ROOT::RWebDisplayHandle { protected: class CefCreator : public Creator { CefRefPtr fCefApp; public: CefCreator() = default; - virtual ~CefCreator() = default; + ~CefCreator() override = default; - std::unique_ptr Display(const ROOT::Experimental::RWebDisplayArgs &args) override; + std::unique_ptr Display(const ROOT::RWebDisplayArgs &args) override; }; enum EValidValues { kValid = 0x3C3C3C3C, kInvalid = 0x92929292 }; @@ -40,9 +40,9 @@ protected: CefRefPtr fBrowser; ///< associated browser public: - RCefWebDisplayHandle(const std::string &url) : ROOT::Experimental::RWebDisplayHandle(url) {} + RCefWebDisplayHandle(const std::string &url) : ROOT::RWebDisplayHandle(url) {} - virtual ~RCefWebDisplayHandle(); + ~RCefWebDisplayHandle() override; bool IsValid() const { return fValid == kValid; } @@ -52,6 +52,8 @@ public: bool WaitForContent(int tmout_sec, const std::string &extra_args); + bool Resize(int, int) override; + static void AddCreator(); }; diff --git a/gui/cefdisplay/inc/gui_handler.h b/gui/cefdisplay/inc/gui_handler.h index 1ba8dba91dbff..5305d17db3395 100644 --- a/gui/cefdisplay/inc/gui_handler.h +++ b/gui/cefdisplay/inc/gui_handler.h @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -28,14 +28,6 @@ class RLogChannel; ROOT::Experimental::RLogChannel &CefWebDisplayLog(); - -#if CEF_VERSION_MAJOR < 95 -typedef CefRequestCallback CefResourceLoadCallBack ; -#else -typedef CefCallback CefResourceLoadCallBack; -#endif - - class THttpServer; /** \class GuiHandler @@ -57,7 +49,7 @@ class GuiHandler : public CefClient, std::vector fServers; - bool is_closing_; + bool is_closing_{false}; public: explicit GuiHandler(bool use_views = false); @@ -66,27 +58,27 @@ class GuiHandler : public CefClient, // static BaseHandler *GetInstance(); // CefClient methods: - virtual CefRefPtr GetLifeSpanHandler() override { return this; } - virtual CefRefPtr GetLoadHandler() override { return this; } - virtual CefRefPtr GetDisplayHandler() override { return this; } - virtual CefRefPtr GetRequestHandler() override { return this; } + CefRefPtr GetLifeSpanHandler() override { return this; } + CefRefPtr GetLoadHandler() override { return this; } + CefRefPtr GetDisplayHandler() override { return this; } + CefRefPtr GetRequestHandler() override { return this; } // CefLifeSpanHandler methods: - virtual void OnAfterCreated(CefRefPtr browser) override; - virtual bool DoClose(CefRefPtr browser) override; - virtual void OnBeforeClose(CefRefPtr browser) override; + void OnAfterCreated(CefRefPtr browser) override; + bool DoClose(CefRefPtr browser) override; + void OnBeforeClose(CefRefPtr browser) override; // CefLoadHandler methods: - virtual void OnLoadError(CefRefPtr browser, CefRefPtr frame, ErrorCode errorCode, - const CefString &errorText, const CefString &failedUrl) override; + void OnLoadError(CefRefPtr browser, CefRefPtr frame, ErrorCode errorCode, + const CefString &errorText, const CefString &failedUrl) override; // CefDisplayHandler methods: - virtual void OnTitleChange(CefRefPtr browser, const CefString &title) override; + void OnTitleChange(CefRefPtr browser, const CefString &title) override; - virtual bool OnConsoleMessage(CefRefPtr browser, - cef_log_severity_t level, - const CefString &message, const CefString &source, - int line) override; + bool OnConsoleMessage(CefRefPtr browser, + cef_log_severity_t level, + const CefString &message, const CefString &source, + int line) override; // Request that all existing browser windows close. void CloseAllBrowsers(bool force_close); @@ -94,7 +86,7 @@ class GuiHandler : public CefClient, bool IsClosing() const { return is_closing_; } // CefRequestHandler methods: - virtual CefRefPtr GetResourceRequestHandler( + CefRefPtr GetResourceRequestHandler( CefRefPtr browser, CefRefPtr frame, CefRefPtr request, @@ -104,13 +96,13 @@ class GuiHandler : public CefClient, bool& disable_default_handling) override { return this; } // CefResourceRequestHandler methods: - virtual cef_return_value_t OnBeforeResourceLoad( + cef_return_value_t OnBeforeResourceLoad( CefRefPtr browser, CefRefPtr frame, CefRefPtr request, - CefRefPtr callback) override; + CefRefPtr callback) override; - virtual CefRefPtr GetResourceHandler( + CefRefPtr GetResourceHandler( CefRefPtr browser, CefRefPtr frame, CefRefPtr request) override; @@ -123,6 +115,8 @@ class GuiHandler : public CefClient, static std::string GetDataURI(const std::string& data, const std::string& mime_type); + static bool PlatformResize(CefRefPtr browser, int width, int height); + private: // Platform-specific implementation. diff --git a/gui/cefdisplay/inc/simple_app.h b/gui/cefdisplay/inc/simple_app.h index d4bfc7659c7bd..c7f47697e6206 100644 --- a/gui/cefdisplay/inc/simple_app.h +++ b/gui/cefdisplay/inc/simple_app.h @@ -7,7 +7,7 @@ // can be found in the LICENSE file. /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -53,45 +53,36 @@ class SimpleApp : public CefApp, void SetNextHandle(RCefWebDisplayHandle *handle); // CefApp methods: - virtual CefRefPtr GetBrowserProcessHandler() override { return this; } + CefRefPtr GetBrowserProcessHandler() override { return this; } -#if defined(OS_LINUX) -#if CEF_VERSION_MAJOR < 95 // only on Linux special print handler is required to return PDF size - virtual CefRefPtr GetPrintHandler() override { return this; } -#endif -#endif + // CefRefPtr GetPrintHandler() override { return this; } // virtual CefRefPtr GetRenderProcessHandler() override { return this; } - virtual void OnRegisterCustomSchemes(CefRawPtr registrar) override; + void OnRegisterCustomSchemes(CefRawPtr registrar) override; // CefBrowserProcessHandler methods: - virtual void OnContextInitialized() override; + void OnContextInitialized() override; - virtual void - OnBeforeCommandLineProcessing(const CefString &process_type, CefRefPtr command_line) override; + void OnBeforeCommandLineProcessing(const CefString &process_type, CefRefPtr command_line) override; - virtual void OnBeforeChildProcessLaunch(CefRefPtr command_line) override; + void OnBeforeChildProcessLaunch(CefRefPtr command_line) override; #if defined(OS_LINUX) // CefPrintHandler methods -#if CEF_VERSION_MAJOR < 95 - virtual CefSize GetPdfPaperSize(int device_units_per_inch) override { return CefSize(device_units_per_inch*8.25, device_units_per_inch*11.75); } -#else - virtual CefSize GetPdfPaperSize(CefRefPtr, int device_units_per_inch) override { return CefSize(device_units_per_inch*8.25, device_units_per_inch*11.75); } -#endif - virtual bool OnPrintDialog( CefRefPtr< CefBrowser > browser, bool has_selection, CefRefPtr< CefPrintDialogCallback > callback ) override { return false; } - virtual bool OnPrintJob( CefRefPtr< CefBrowser > browser, const CefString& document_name, const CefString& pdf_file_path, CefRefPtr< CefPrintJobCallback > callback ) override { return false; } - virtual void OnPrintReset( CefRefPtr< CefBrowser > browser ) override {} - virtual void OnPrintSettings( CefRefPtr< CefBrowser > browser, CefRefPtr< CefPrintSettings > settings, bool get_defaults ) override {} - virtual void OnPrintStart( CefRefPtr< CefBrowser > browser ) override {} + CefSize GetPdfPaperSize(CefRefPtr, int device_units_per_inch) override { return CefSize(device_units_per_inch*8.25, device_units_per_inch*11.75); } + bool OnPrintDialog( CefRefPtr< CefBrowser > browser, bool has_selection, CefRefPtr< CefPrintDialogCallback > callback ) override { return false; } + bool OnPrintJob( CefRefPtr< CefBrowser > browser, const CefString& document_name, const CefString& pdf_file_path, CefRefPtr< CefPrintJobCallback > callback ) override { return false; } + void OnPrintReset( CefRefPtr< CefBrowser > browser ) override {} + void OnPrintSettings( CefRefPtr< CefBrowser > browser, CefRefPtr< CefPrintSettings > settings, bool get_defaults ) override {} + void OnPrintStart( CefRefPtr< CefBrowser > browser ) override {} #endif void StartWindow(THttpServer *serv, const std::string &url, const std::string &cont, CefRect &rect); // CefRenderProcessHandler methods - // virtual void OnContextCreated(CefRefPtr browser, CefRefPtr frame, + // void OnContextCreated(CefRefPtr browser, CefRefPtr frame, // CefRefPtr context) override; private: diff --git a/gui/cefdisplay/src/RCefWebDisplayHandle.cxx b/gui/cefdisplay/src/RCefWebDisplayHandle.cxx index ee02499fdf5ed..d2ef5462092d5 100644 --- a/gui/cefdisplay/src/RCefWebDisplayHandle.cxx +++ b/gui/cefdisplay/src/RCefWebDisplayHandle.cxx @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -37,7 +37,6 @@ class TCefTimer : public TTimer { { // just let run loop CefDoMessageLoopWork(); - } }; @@ -50,7 +49,7 @@ class FrameSourceVisitor : public CefStringVisitor { FrameSourceVisitor(RCefWebDisplayHandle *handle) : CefStringVisitor(), fHandle(handle) {} - virtual ~FrameSourceVisitor() = default; + ~FrameSourceVisitor() override = default; void Visit(const CefString &str) override { @@ -69,9 +68,9 @@ class HeadlessPrintCallback : public CefPdfPrintCallback { bool *fFlag{nullptr}; public: HeadlessPrintCallback(bool *flag) : CefPdfPrintCallback(), fFlag(flag) {} - virtual ~HeadlessPrintCallback() = default; + ~HeadlessPrintCallback() override = default; - void OnPdfPrintFinished(const CefString&, bool ok ) override + void OnPdfPrintFinished(const CefString&, bool ok) override { if (fFlag) *fFlag = true; } @@ -81,7 +80,7 @@ class HeadlessPrintCallback : public CefPdfPrintCallback { DISALLOW_COPY_AND_ASSIGN(HeadlessPrintCallback); }; -std::unique_ptr RCefWebDisplayHandle::CefCreator::Display(const ROOT::Experimental::RWebDisplayArgs &args) +std::unique_ptr RCefWebDisplayHandle::CefCreator::Display(const ROOT::RWebDisplayArgs &args) { auto handle = std::make_unique(args.GetFullUrl()); @@ -226,7 +225,6 @@ RCefWebDisplayHandle::~RCefWebDisplayHandle() /////////////////////////////////////////////////////////////////////////////////////////////////// /// Closes associated browser window - void RCefWebDisplayHandle::CloseBrowser() { if (fBrowser) { @@ -236,8 +234,6 @@ void RCefWebDisplayHandle::CloseBrowser() } } - - /////////////////////////////////////////////////////////////////////////////////////////////////// /// Process system events until browser content is available /// Used in headless mode for batch production like chrome --dump-dom is doing @@ -277,6 +273,18 @@ bool RCefWebDisplayHandle::WaitForContent(int tmout_sec, const std::string &extr return !GetContent().empty(); } +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Resize browser window + +bool RCefWebDisplayHandle::Resize(int width, int height) +{ + if (!fBrowser) + return false; + return GuiHandler::PlatformResize(fBrowser, width, height); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Add CEF creator void RCefWebDisplayHandle::AddCreator() { @@ -285,6 +293,8 @@ void RCefWebDisplayHandle::AddCreator() GetMap().emplace("cef", std::make_unique()); } +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Helper struct to add creator struct RCefCreatorReg { RCefCreatorReg() { RCefWebDisplayHandle::AddCreator(); } diff --git a/gui/cefdisplay/src/cef_main.cxx b/gui/cefdisplay/src/cef_main.cxx index a37ec030ef431..dcc921da41ee5 100644 --- a/gui/cefdisplay/src/cef_main.cxx +++ b/gui/cefdisplay/src/cef_main.cxx @@ -7,7 +7,7 @@ // can be found in the LICENSE file. /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -34,9 +34,9 @@ class MyRendererProcessApp : public CefApp /*, public CefRenderProcessHandler */ public: MyRendererProcessApp() : CefApp() /*, CefRenderProcessHandler() */ {} - virtual ~MyRendererProcessApp() {} + ~MyRendererProcessApp() override {} -// virtual CefRefPtr< CefRenderProcessHandler > GetRenderProcessHandler() { return this; } +// CefRefPtr< CefRenderProcessHandler > GetRenderProcessHandler() override { return this; } // void OnRegisterCustomSchemes(CefRawPtr registrar) override // { @@ -53,8 +53,6 @@ class MyRendererProcessApp : public CefApp /*, public CefRenderProcessHandler */ // Entry point function for all processes. int main(int argc, char *argv[]) { - // printf("Starting CEF_MAIN ARGC %d\n", argc); - // for (int n = 1; n < argc; n++) printf("ARGV[%d] = %s\n", n, argv[n]); #if defined(OS_WIN) CefMainArgs main_args(::GetModuleHandle(NULL)); diff --git a/gui/cefdisplay/src/gui_handler.cxx b/gui/cefdisplay/src/gui_handler.cxx index 86fa6b22d7bc7..05e0635099775 100644 --- a/gui/cefdisplay/src/gui_handler.cxx +++ b/gui/cefdisplay/src/gui_handler.cxx @@ -123,9 +123,8 @@ void GuiHandler::OnBeforeClose(CefRefPtr browser) // Returns a data: URI with the specified contents. std::string GuiHandler::GetDataURI(const std::string& data, const std::string& mime_type) { - return "data:" + mime_type + ";base64," + - CefURIEncode(CefBase64Encode(data.data(), data.size()), false) - .ToString(); + return std::string("data:") + mime_type + ";base64," + + CefURIEncode(CefBase64Encode(data.data(), data.size()), false).ToString(); } @@ -139,12 +138,14 @@ void GuiHandler::OnLoadError(CefRefPtr browser, CefRefPtr return; // Display a load error message. + /* std::stringstream ss; ss << "" "

Failed to load URL " << failedUrl.ToString().substr(0,100) << " with error " << errorText.ToString() << " (" << errorCode << ").

"; - // frame->LoadURL(GetDataURI(ss.str(), "text/html")); + frame->LoadURL(GetDataURI(ss.str(), "text/html")); + */ printf("Fail to load URL %s\n", failedUrl.ToString().substr(0,100).c_str()); } @@ -153,11 +154,7 @@ void GuiHandler::CloseAllBrowsers(bool force_close) { if (!CefCurrentlyOn(TID_UI)) { // Execute on the UI thread. -#if CEF_VERSION_MAJOR < 95 - CefPostTask(TID_UI, base::Bind(&GuiHandler::CloseAllBrowsers, this, force_close)); -#else CefPostTask(TID_UI, base::BindOnce(&GuiHandler::CloseAllBrowsers, this, force_close)); -#endif return; } @@ -197,18 +194,14 @@ cef_return_value_t GuiHandler::OnBeforeResourceLoad( CefRefPtr browser, CefRefPtr frame, CefRefPtr request, - CefRefPtr callback) { + CefRefPtr callback) { CEF_REQUIRE_IO_THREAD(); - // std::string url = request->GetURL().ToString(); - // printf("OnBeforeResourceLoad url %s\n", url.c_str()); - return fResourceManager->OnBeforeResourceLoad(browser, frame, request, callback); } - class TCefHttpCallArg : public THttpCallArg { protected: @@ -256,7 +249,7 @@ class TGuiResourceHandler : public CefResourceHandler { fArg = std::make_shared(); } - virtual ~TGuiResourceHandler() {} + ~TGuiResourceHandler() override {} void Cancel() override { CEF_REQUIRE_IO_THREAD(); } @@ -273,8 +266,11 @@ class TGuiResourceHandler : public CefResourceHandler { return true; } - +#if CEF_VERSION_MAJOR > 114 + void GetResponseHeaders(CefRefPtr response, int64_t &response_length, CefString &redirectUrl) override +#else void GetResponseHeaders(CefRefPtr response, int64 &response_length, CefString &redirectUrl) override +#endif { CEF_REQUIRE_IO_THREAD(); @@ -288,19 +284,14 @@ class TGuiResourceHandler : public CefResourceHandler { response_length = fArg->GetContentLength(); if (fArg->NumHeader() > 0) { - // printf("******* Response with extra headers\n"); CefResponse::HeaderMap headers; for (Int_t n = 0; n < fArg->NumHeader(); ++n) { TString name = fArg->GetHeaderName(n); TString value = fArg->GetHeader(name.Data()); headers.emplace(CefString(name.Data()), CefString(value.Data())); - // printf(" header %s %s\n", name.Data(), value.Data()); } response->SetHeaderMap(headers); } -// if (strstr(fArg->GetQuery(),"connection=")) -// printf("Reply %s %s %s len: %d %s\n", fArg->GetPathName(), fArg->GetFileName(), fArg->GetQuery(), -// fArg->GetContentLength(), (const char *) fArg->GetContent() ); } // DCHECK(!fArg->Is404()); } @@ -389,8 +380,6 @@ CefRefPtr GuiHandler::GetResourceHandler( std::string inp_method = request->GetMethod().ToString(); - // printf("REQUEST METHOD %s\n", inp_method.c_str()); - TGuiResourceHandler *handler = new TGuiResourceHandler(serv); handler->fArg->SetMethod(inp_method.c_str()); handler->fArg->SetPathAndFileName(inp_path); diff --git a/gui/cefdisplay/src/gui_handler_linux.cxx b/gui/cefdisplay/src/gui_handler_linux.cxx index 936dbc7cf128f..2d06207826d1a 100644 --- a/gui/cefdisplay/src/gui_handler_linux.cxx +++ b/gui/cefdisplay/src/gui_handler_linux.cxx @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -88,6 +88,30 @@ void GuiHandler::PlatformTitleChange(CefRefPtr browser, const CefStr XStoreName(display, browser->GetHost()->GetWindowHandle(), titleStr.c_str()); } +bool GuiHandler::PlatformResize(CefRefPtr browser, int width, int height) +{ + ::Display *display = cef_get_xdisplay(); + if (!display) return false; + + // Retrieve the X11 window handle for the browser. + ::Window window = browser->GetHost()->GetWindowHandle(); + if (window == kNullWindowHandle) + return false; + + int result = XResizeWindow(display, window, width, height); + if (result == BadWindow) { + printf(" bad window in XResizeWindow\n"); + return false; + } + + if (result == BadValue) { + printf(" bad values in XResizeWindow %d %d\n", width, height); + return false; + } + XFlush(display); + return true; +} + #else bool GuiHandler::PlatformInit() @@ -100,6 +124,11 @@ void GuiHandler::PlatformTitleChange(CefRefPtr, const CefString &) // do nothing } +bool GuiHandler::PlatformResize(CefRefPtr, int, int) +{ + return false; +} + #endif diff --git a/gui/cefdisplay/src/gui_handler_mac.mm b/gui/cefdisplay/src/gui_handler_mac.mm index 2bb8ef0be1bc8..579b79945dfe6 100644 --- a/gui/cefdisplay/src/gui_handler_mac.mm +++ b/gui/cefdisplay/src/gui_handler_mac.mm @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -22,7 +22,6 @@ return false; // MAC not yet support ozone and headless mode } - void GuiHandler::PlatformTitleChange(CefRefPtr browser, const CefString &title) { NSView *view = (NSView *)browser->GetHost()->GetWindowHandle(); @@ -31,3 +30,8 @@ NSString *str = [NSString stringWithUTF8String:titleStr.c_str()]; [window setTitle:str]; } + +bool GuiHandler::PlatformResize(CefRefPtr, int, int) +{ + return false; +} diff --git a/gui/cefdisplay/src/gui_handler_win.cc b/gui/cefdisplay/src/gui_handler_win.cc index 7cba417999ebc..a6eade413d23c 100644 --- a/gui/cefdisplay/src/gui_handler_win.cc +++ b/gui/cefdisplay/src/gui_handler_win.cc @@ -7,7 +7,7 @@ // can be found in the LICENSE file. /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -36,3 +36,8 @@ void GuiHandler::PlatformTitleChange(CefRefPtr browser, const CefStr CefWindowHandle hwnd = browser->GetHost()->GetWindowHandle(); SetWindowText(hwnd, std::string(title).c_str()); } + +bool GuiHandler::PlatformResize(CefRefPtr, int, int) +{ + return false; +} diff --git a/gui/cefdisplay/src/simple_app.cxx b/gui/cefdisplay/src/simple_app.cxx index 3c17e17664d9e..9dc77b44a0167 100644 --- a/gui/cefdisplay/src/simple_app.cxx +++ b/gui/cefdisplay/src/simple_app.cxx @@ -7,7 +7,7 @@ // can be found in the LICENSE file. /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * diff --git a/gui/fitpanel/inc/TAdvancedGraphicsDialog.h b/gui/fitpanel/inc/TAdvancedGraphicsDialog.h index fa02141dbe169..00212a4613fa2 100644 --- a/gui/fitpanel/inc/TAdvancedGraphicsDialog.h +++ b/gui/fitpanel/inc/TAdvancedGraphicsDialog.h @@ -80,12 +80,12 @@ class TAdvancedGraphicsDialog : public TGTransientFrame { public: TAdvancedGraphicsDialog(const TGWindow *p, const TGWindow *main); - ~TAdvancedGraphicsDialog(); + ~TAdvancedGraphicsDialog() override; void DoDraw(); void DoChangedScanPar(Int_t selected); - ClassDef(TAdvancedGraphicsDialog, 0) // Simple input dialog + ClassDefOverride(TAdvancedGraphicsDialog, 0) // Simple input dialog }; #endif diff --git a/gui/fitpanel/inc/TFitEditor.h b/gui/fitpanel/inc/TFitEditor.h index 48b0ece15258d..c6106a73ad462 100644 --- a/gui/fitpanel/inc/TFitEditor.h +++ b/gui/fitpanel/inc/TFitEditor.h @@ -163,7 +163,7 @@ class TFitEditor : public TGMainFrame { void CreateMinimizationTab(); void MakeTitle(TGCompositeFrame *parent, const char *title); TF1* HasFitFunction(); - void SetEditable(Bool_t); + void SetEditable(Bool_t) override; private: TFitEditor(const TFitEditor&); // not implemented @@ -173,12 +173,12 @@ class TFitEditor : public TGMainFrame { public: TFitEditor(TVirtualPad* pad, TObject *obj); - virtual ~TFitEditor(); + ~TFitEditor() override; TList* GetListOfFittingFunctions(TObject *obj = nullptr); static TFitEditor *GetInstance(TVirtualPad* pad = nullptr, TObject *obj = nullptr); - virtual Option_t *GetDrawOption() const; + Option_t *GetDrawOption() const override; virtual void Hide(); virtual void Show(TVirtualPad* pad, TObject *obj); @@ -187,10 +187,10 @@ class TFitEditor : public TGMainFrame { virtual void Terminate(); void UpdateGUI(); - virtual void CloseWindow(); + void CloseWindow() override; virtual void ConnectSlots(); virtual void DisconnectSlots(); - virtual void RecursiveRemove(TObject* obj); + void RecursiveRemove(TObject* obj) override; protected: virtual void SetCanvas(TCanvas *c); @@ -239,7 +239,7 @@ class TFitEditor : public TGMainFrame { typedef std::vector FuncParams_t; friend class FitEditorUnitTesting; - ClassDef(TFitEditor,0) //Fit Panel interface + ClassDefOverride(TFitEditor,0) //Fit Panel interface }; #endif diff --git a/gui/fitpanel/inc/TFitParametersDialog.h b/gui/fitpanel/inc/TFitParametersDialog.h index 5bae41246797b..48724c4435be1 100644 --- a/gui/fitpanel/inc/TFitParametersDialog.h +++ b/gui/fitpanel/inc/TFitParametersDialog.h @@ -83,9 +83,9 @@ class TFitParametersDialog : public TGTransientFrame { public: TFitParametersDialog(const TGWindow *p, const TGWindow *main, TF1 *func, TVirtualPad *pad, Int_t *ret_code = nullptr); - virtual ~TFitParametersDialog(); + ~TFitParametersDialog() override; - virtual void CloseWindow(); + void CloseWindow() override; virtual void DoApply(); virtual void DoCancel(); virtual void DoOK(); @@ -106,7 +106,7 @@ class TFitParametersDialog : public TGTransientFrame { protected: void SetParameters(); - ClassDef(TFitParametersDialog, 0) // Fit function parameters dialog + ClassDefOverride(TFitParametersDialog, 0) // Fit function parameters dialog }; #endif diff --git a/gui/fitpanel/inc/TTreeInput.h b/gui/fitpanel/inc/TTreeInput.h index 6af339ee4c470..4d707daa884f0 100644 --- a/gui/fitpanel/inc/TTreeInput.h +++ b/gui/fitpanel/inc/TTreeInput.h @@ -35,10 +35,10 @@ class TTreeInput : public TGTransientFrame { public: TTreeInput(const TGWindow *p, const TGWindow *main, char *strvars, char* strcuts); - ~TTreeInput(); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t); + ~TTreeInput() override; + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t) override; - ClassDef(TTreeInput, 0) // Simple input dialog + ClassDefOverride(TTreeInput, 0) // Simple input dialog }; diff --git a/gui/fitpanelv7/CMakeLists.txt b/gui/fitpanelv7/CMakeLists.txt index 4ac84983cf24c..f7003b4cc0086 100644 --- a/gui/fitpanelv7/CMakeLists.txt +++ b/gui/fitpanelv7/CMakeLists.txt @@ -8,6 +8,11 @@ # CMakeLists.txt file for building ROOT gui/fitpanelv7 ############################################################################ +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(ROOTFitPanelv7 HEADERS ROOT/RFitPanel.hxx @@ -20,7 +25,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTFitPanelv7 DEPENDENCIES Hist Gpad + ROOTWebDisplay ROOTGpadv7 ROOTHistDraw - ROOTWebDisplay + ${EXTRA_DICT_OPTS} ) diff --git a/gui/fitpanelv7/inc/ROOT/RFitPanel.hxx b/gui/fitpanelv7/inc/ROOT/RFitPanel.hxx index 519e540592e6f..32f5e2322f078 100644 --- a/gui/fitpanelv7/inc/ROOT/RFitPanel.hxx +++ b/gui/fitpanelv7/inc/ROOT/RFitPanel.hxx @@ -45,7 +45,7 @@ class RFitPanel { std::shared_ptr fCanvas; /// fFitHist; /// fWindow; /// fWindow; ///> fSystemFuncs; /// GetWindow(); + std::shared_ptr GetWindow(); void AssignHistogram(TH1 *hist); @@ -115,6 +117,8 @@ public: /// hide FitPanel void Hide(); + + void ClearOnClose(const std::shared_ptr &handle); }; } // namespace Experimental diff --git a/gui/fitpanelv7/src/RFitPanel.cxx b/gui/fitpanelv7/src/RFitPanel.cxx index 8268dc5d8c89f..9e02d757b0fdd 100644 --- a/gui/fitpanelv7/src/RFitPanel.cxx +++ b/gui/fitpanelv7/src/RFitPanel.cxx @@ -98,10 +98,10 @@ RFitPanel::~RFitPanel() //////////////////////////////////////////////////////////////////////////////// /// Returns RWebWindow instance, used to display FitPanel -std::shared_ptr RFitPanel::GetWindow() +std::shared_ptr RFitPanel::GetWindow() { if (!fWindow) { - fWindow = RWebWindow::Create(); + fWindow = ROOT::RWebWindow::Create(); fWindow->SetPanelName("rootui5.fitpanel.view.FitPanel"); @@ -767,10 +767,7 @@ bool RFitPanel::DoFit() copy->Draw("same"); } - if (pad) { - pad->Modified(); - pad->Update(); - } + DoPadUpdate(pad); std::string funcname = f1->GetName(); if ((funcname.compare(0,4,"prev") == 0) && (funcname.find("-") > 4)) @@ -968,8 +965,29 @@ bool RFitPanel::DoDraw() drawobj->Draw(drawopt.c_str()); - pad->Modified(); - pad->Update(); + DoPadUpdate(pad); return true; } + + +////////////////////////////////////////////////////////////////////////////////////////////// +/// Mark pad modified and do update +/// For web canvas set async mode first to avoid blocking here + +void RFitPanel::DoPadUpdate(TPad *pad) +{ + if (!pad) return; + + pad->Modified(); + pad->UpdateAsync(); +} + + +////////////////////////////////////////////////////////////////////////////////////////////// +/// Set handle which will be cleared when connection is closed + +void RFitPanel::ClearOnClose(const std::shared_ptr &handle) +{ + GetWindow()->SetClearOnClose(handle); +} diff --git a/gui/fitpanelv7/src/RFitPanelModel.cxx b/gui/fitpanelv7/src/RFitPanelModel.cxx index 33a6a697d0836..3b3d53c2d6755 100644 --- a/gui/fitpanelv7/src/RFitPanelModel.cxx +++ b/gui/fitpanelv7/src/RFitPanelModel.cxx @@ -19,7 +19,8 @@ #include "TFitResult.h" #include "TF1.h" -ROOT::Experimental::RLogChannel &ROOT::Experimental::FitPanelLog() { +ROOT::Experimental::RLogChannel &ROOT::Experimental::FitPanelLog() +{ static RLogChannel sLog("ROOT.FitPanel"); return sLog; } diff --git a/gui/ged/CMakeLists.txt b/gui/ged/CMakeLists.txt index f19a2cd925f2a..99c2e08b74303 100644 --- a/gui/ged/CMakeLists.txt +++ b/gui/ged/CMakeLists.txt @@ -8,6 +8,11 @@ # CMakeLists.txt file for building ROOT gui/ged package ############################################################################ +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(Ged HEADERS HelpSMText.h @@ -74,4 +79,5 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Ged Gui Tree TreePlayer + ${EXTRA_DICT_OPTS} ) diff --git a/gui/ged/inc/TArrowEditor.h b/gui/ged/inc/TArrowEditor.h index 8a173f755ce62..1e83ac11e29b2 100644 --- a/gui/ged/inc/TArrowEditor.h +++ b/gui/ged/inc/TArrowEditor.h @@ -38,14 +38,14 @@ class TArrowEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TArrowEditor(); + ~TArrowEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoAngle(); virtual void DoOption(Int_t id); virtual void DoSize(); - ClassDef(TArrowEditor,0) // GUI for editing arrow attributes + ClassDefOverride(TArrowEditor,0) // GUI for editing arrow attributes }; #endif diff --git a/gui/ged/inc/TAttFillEditor.h b/gui/ged/inc/TAttFillEditor.h index 6284cc4097cc6..37d82672ac369 100644 --- a/gui/ged/inc/TAttFillEditor.h +++ b/gui/ged/inc/TAttFillEditor.h @@ -36,9 +36,9 @@ class TAttFillEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TAttFillEditor(); + ~TAttFillEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoFillColor(Pixel_t color); virtual void DoFillAlphaColor(ULongptr_t p); virtual void DoFillPattern(Style_t color); @@ -47,7 +47,7 @@ class TAttFillEditor : public TGedFrame { virtual void DoLiveAlpha(Int_t a); virtual void GetCurAlpha(); - ClassDef(TAttFillEditor,0) //GUI for editing fill attributes + ClassDefOverride(TAttFillEditor,0) //GUI for editing fill attributes }; #endif diff --git a/gui/ged/inc/TAttLineEditor.h b/gui/ged/inc/TAttLineEditor.h index a8fe7e1540b0b..f405512dbb8e9 100644 --- a/gui/ged/inc/TAttLineEditor.h +++ b/gui/ged/inc/TAttLineEditor.h @@ -38,9 +38,9 @@ class TAttLineEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TAttLineEditor(); + ~TAttLineEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoLineColor(Pixel_t color); virtual void DoLineAlphaColor(ULongptr_t p); virtual void DoLineStyle(Int_t style); @@ -50,7 +50,7 @@ class TAttLineEditor : public TGedFrame { virtual void DoLiveAlpha(Int_t a); virtual void GetCurAlpha(); - ClassDef(TAttLineEditor,0) // GUI for editing line attributes + ClassDefOverride(TAttLineEditor,0) // GUI for editing line attributes }; #endif diff --git a/gui/ged/inc/TAttMarkerEditor.h b/gui/ged/inc/TAttMarkerEditor.h index 1445a0d8e3685..08765c46543bd 100644 --- a/gui/ged/inc/TAttMarkerEditor.h +++ b/gui/ged/inc/TAttMarkerEditor.h @@ -39,9 +39,9 @@ class TAttMarkerEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TAttMarkerEditor(); + ~TAttMarkerEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoMarkerColor(Pixel_t color); virtual void DoMarkerAlphaColor(ULongptr_t p); virtual void DoMarkerSize(); @@ -51,7 +51,7 @@ class TAttMarkerEditor : public TGedFrame { virtual void DoLiveAlpha(Int_t a); virtual void GetCurAlpha(); - ClassDef(TAttMarkerEditor,0) // GUI for editing marker attributes + ClassDefOverride(TAttMarkerEditor,0) // GUI for editing marker attributes }; #endif diff --git a/gui/ged/inc/TAttTextEditor.h b/gui/ged/inc/TAttTextEditor.h index 0e3946289c4cb..3608deae23b1b 100644 --- a/gui/ged/inc/TAttTextEditor.h +++ b/gui/ged/inc/TAttTextEditor.h @@ -42,10 +42,10 @@ class TAttTextEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TAttTextEditor(); + ~TAttTextEditor() override; - virtual void SetModel(TObject* obj); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + void SetModel(TObject* obj) override; + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; virtual void DoTextAlphaColor(ULongptr_t p); virtual void DoAlpha(); virtual void DoAlphaField(); @@ -53,7 +53,7 @@ class TAttTextEditor : public TGedFrame { virtual void GetCurAlpha(); virtual void DoTextColor(Pixel_t color); - ClassDef(TAttTextEditor,0) //GUI for editing text attributes + ClassDefOverride(TAttTextEditor,0) //GUI for editing text attributes }; #endif diff --git a/gui/ged/inc/TAxisEditor.h b/gui/ged/inc/TAxisEditor.h index 95b639abb6a1b..5e8d0bc6f6321 100644 --- a/gui/ged/inc/TAxisEditor.h +++ b/gui/ged/inc/TAxisEditor.h @@ -62,8 +62,8 @@ class TAxisEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TAxisEditor(); - virtual void SetModel(TObject* obj); + ~TAxisEditor() override; + void SetModel(TObject* obj) override; // slots related to axis attributes virtual void DoTickLength(); virtual void DoAxisColor(Pixel_t color); @@ -87,7 +87,7 @@ class TAxisEditor : public TGedFrame { virtual void DoNoExponent(); virtual void DoDecimal(Bool_t on); - ClassDef(TAxisEditor,0) // axis editor + ClassDefOverride(TAxisEditor,0) // axis editor }; #endif diff --git a/gui/ged/inc/TCurlyArcEditor.h b/gui/ged/inc/TCurlyArcEditor.h index 188bdea186f17..3c807890cd9a0 100644 --- a/gui/ged/inc/TCurlyArcEditor.h +++ b/gui/ged/inc/TCurlyArcEditor.h @@ -35,15 +35,15 @@ class TCurlyArcEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TCurlyArcEditor(); + ~TCurlyArcEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoRadius(); virtual void DoPhimin(); virtual void DoPhimax(); virtual void DoCenterXY(); - ClassDef(TCurlyArcEditor,0) // GUI for editing arrow attributes + ClassDefOverride(TCurlyArcEditor,0) // GUI for editing arrow attributes }; #endif diff --git a/gui/ged/inc/TCurlyLineEditor.h b/gui/ged/inc/TCurlyLineEditor.h index 7038a48ffa59f..b199653c9d9b9 100644 --- a/gui/ged/inc/TCurlyLineEditor.h +++ b/gui/ged/inc/TCurlyLineEditor.h @@ -39,17 +39,17 @@ class TCurlyLineEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TCurlyLineEditor(); + ~TCurlyLineEditor() override; - virtual void SetModel(TObject* obj); - virtual void ActivateBaseClassEditors(TClass* cl); + void SetModel(TObject* obj) override; + void ActivateBaseClassEditors(TClass* cl) override; virtual void DoStartXY(); virtual void DoEndXY(); virtual void DoAmplitude(); virtual void DoWaveLength(); virtual void DoWavy(); - ClassDef(TCurlyLineEditor,0) // GUI for editing arrow attributes + ClassDefOverride(TCurlyLineEditor,0) // GUI for editing arrow attributes }; #endif diff --git a/gui/ged/inc/TF1Editor.h b/gui/ged/inc/TF1Editor.h index b15a2f994003c..98e9859d1832a 100644 --- a/gui/ged/inc/TF1Editor.h +++ b/gui/ged/inc/TF1Editor.h @@ -43,10 +43,10 @@ class TF1Editor : public TGedFrame { public: TF1Editor(const TGWindow *p = nullptr, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TF1Editor(); + ~TF1Editor() override; - virtual void SetModel(TObject* obj); - virtual void ActivateBaseClassEditors(TClass* cl); + void SetModel(TObject* obj) override; + void ActivateBaseClassEditors(TClass* cl) override; virtual void DoParameterSettings(); virtual void DoXPoints(); @@ -55,7 +55,7 @@ class TF1Editor : public TGedFrame { virtual void DoSliderXReleased(); virtual void DoXRange(); - ClassDef(TF1Editor,0) // user interface for TF1 objects + ClassDefOverride(TF1Editor,0) // user interface for TF1 objects }; #endif diff --git a/gui/ged/inc/TFrameEditor.h b/gui/ged/inc/TFrameEditor.h index 5aea8fd39a9cc..d3e6a18cd0f29 100644 --- a/gui/ged/inc/TFrameEditor.h +++ b/gui/ged/inc/TFrameEditor.h @@ -37,13 +37,13 @@ class TFrameEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TFrameEditor(); + ~TFrameEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoBorderMode(); virtual void DoBorderSize(Int_t size); - ClassDef(TFrameEditor,0) //editor of TFrame objects + ClassDefOverride(TFrameEditor,0) //editor of TFrame objects }; #endif diff --git a/gui/ged/inc/TFunctionParametersDialog.h b/gui/ged/inc/TFunctionParametersDialog.h index 7f5a73a2f5b3b..6a560b83aa70f 100644 --- a/gui/ged/inc/TFunctionParametersDialog.h +++ b/gui/ged/inc/TFunctionParametersDialog.h @@ -64,9 +64,9 @@ class TFunctionParametersDialog : public TGTransientFrame { TFunctionParametersDialog(const TGWindow *p, const TGWindow *main, TF1 *func, TVirtualPad *pad, Double_t rmin, Double_t rmax); - virtual ~TFunctionParametersDialog(); + ~TFunctionParametersDialog() override; - virtual void CloseWindow(); + void CloseWindow() override; virtual void DoApply(); virtual void DoCancel(); virtual void DoFix(Bool_t on); @@ -79,7 +79,7 @@ class TFunctionParametersDialog : public TGTransientFrame { virtual void HandleButtons(Bool_t update); virtual void RedrawFunction(); - ClassDef(TFunctionParametersDialog, 0) // Function parameters dialog + ClassDefOverride(TFunctionParametersDialog, 0) // Function parameters dialog }; #endif diff --git a/gui/ged/inc/TGedEditor.h b/gui/ged/inc/TGedEditor.h index 4b6c5cfd745fc..c7d597934426f 100644 --- a/gui/ged/inc/TGedEditor.h +++ b/gui/ged/inc/TGedEditor.h @@ -59,7 +59,7 @@ class TGedEditor : public TVirtualPadEditor, public TGMainFrame public: TGedEditor(TCanvas* canvas = nullptr, UInt_t width = 175, UInt_t height = 20); - virtual ~TGedEditor(); + ~TGedEditor() override; void PrintFrameStat(); virtual void Update(TGedFrame* frame = nullptr); diff --git a/gui/ged/inc/TGedFrame.h b/gui/ged/inc/TGedFrame.h index 712e2ef39e5d2..4523e5c724bea 100644 --- a/gui/ged/inc/TGedFrame.h +++ b/gui/ged/inc/TGedFrame.h @@ -59,11 +59,11 @@ class TGedFrame : public TGCompositeFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGedFrame(); + ~TGedFrame() override; virtual void Update(); - virtual Option_t *GetDrawOption() const; + Option_t *GetDrawOption() const override; TClass* GetModelClass() { return fModelClass; } Int_t GetPriority() { return fPriority; } @@ -73,14 +73,14 @@ class TGedFrame : public TGCompositeFrame { virtual TGVerticalFrame* CreateEditorTabSubFrame(const char* name); virtual void Refresh(TObject *model); - virtual void SetDrawOption(Option_t *option=""); + void SetDrawOption(Option_t *option="") override; virtual Bool_t AcceptModel(TObject*) { return kTRUE; } void SetModelClass(TClass* mcl) { fModelClass = mcl; } virtual void SetModel(TObject* obj) = 0; virtual void SetGedEditor(TGedEditor* ed) { fGedEditor = ed; } virtual void ActivateBaseClassEditors(TClass* cl); - ClassDef(TGedFrame, 0); //base editor's frame + ClassDefOverride(TGedFrame, 0); //base editor's frame }; class TGedNameFrame : public TGedFrame { @@ -98,14 +98,14 @@ class TGedNameFrame : public TGedFrame { Int_t width = 170, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGedNameFrame(); + ~TGedNameFrame() override; - virtual Bool_t HandleButton(Event_t *event); - virtual Bool_t HandleCrossing(Event_t *event); + Bool_t HandleButton(Event_t *event) override; + Bool_t HandleCrossing(Event_t *event) override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; - ClassDef(TGedNameFrame,0) //frame showing the selected object name + ClassDefOverride(TGedNameFrame,0) //frame showing the selected object name }; #endif diff --git a/gui/ged/inc/TGedMarkerSelect.h b/gui/ged/inc/TGedMarkerSelect.h index 0c135ddf5c3d7..38e747711a352 100644 --- a/gui/ged/inc/TGedMarkerSelect.h +++ b/gui/ged/inc/TGedMarkerSelect.h @@ -26,11 +26,11 @@ class TGedMarkerPopup : public TGedPopup { public: TGedMarkerPopup(const TGWindow *p, const TGWindow *m, Style_t markerStyle); - virtual ~TGedMarkerPopup(); + ~TGedMarkerPopup() override; - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; - ClassDef(TGedMarkerPopup,0) //marker select popup + ClassDefOverride(TGedMarkerPopup,0) //marker select popup }; @@ -40,20 +40,20 @@ class TGedMarkerSelect : public TGedSelect { Style_t fMarkerStyle; ///< marker style const TGPicture *fPicture; ///< image used for popup window - virtual void DoRedraw(); + void DoRedraw() override; public: TGedMarkerSelect(const TGWindow *p, Style_t markerStyle, Int_t id); - virtual ~TGedMarkerSelect() { if(fPicture) gClient->FreePicture(fPicture);} + ~TGedMarkerSelect() override { if(fPicture) gClient->FreePicture(fPicture);} - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; Style_t GetMarkerStyle() const { return fMarkerStyle; } void SetMarkerStyle(Style_t pattern); virtual void MarkerSelected(Style_t marker = 0) { Emit("MarkerSelected(Style_t)", marker ? marker : GetMarkerStyle()); } // *SIGNAL* - virtual void SavePrimitive(std::ostream &out, Option_t * = ""); - virtual TGDimension GetDefaultSize() const { return TGDimension(38, 21); } + void SavePrimitive(std::ostream &out, Option_t * = "") override; + TGDimension GetDefaultSize() const override { return TGDimension(38, 21); } - ClassDef(TGedMarkerSelect,0) // Marker selection button + ClassDefOverride(TGedMarkerSelect,0) // Marker selection button }; #endif diff --git a/gui/ged/inc/TGedPatternSelect.h b/gui/ged/inc/TGedPatternSelect.h index cc934d9859777..ce2b06294de1b 100644 --- a/gui/ged/inc/TGedPatternSelect.h +++ b/gui/ged/inc/TGedPatternSelect.h @@ -25,14 +25,14 @@ class TGedPopup : public TGCompositeFrame { public: TGedPopup(const TGWindow* p, const TGWindow *m, UInt_t w, UInt_t h, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGedPopup() { } + ~TGedPopup() override { } - virtual Bool_t HandleButton(Event_t *event); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t HandleButton(Event_t *event) override; + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; void PlacePopup(Int_t x, Int_t y, UInt_t w, UInt_t h); void EndPopup(); - ClassDef(TGedPopup,0) //popup window + ClassDefOverride(TGedPopup,0) //popup window }; class TGedPatternFrame : public TGFrame { @@ -45,22 +45,22 @@ class TGedPatternFrame : public TGFrame { TGToolTip *fTip; ///< tool tip associated with a button char fTipText[7]; - virtual void DoRedraw(); + void DoRedraw() override; public: TGedPatternFrame(const TGWindow *p, Style_t pattern, Int_t width = 40, Int_t height = 20); - virtual ~TGedPatternFrame() { delete fTip; } + ~TGedPatternFrame() override { delete fTip; } - virtual Bool_t HandleButton(Event_t *event); - virtual Bool_t HandleCrossing(Event_t *event); - virtual void DrawBorder(); + Bool_t HandleButton(Event_t *event) override; + Bool_t HandleCrossing(Event_t *event) override; + void DrawBorder() override; void SetActive(Bool_t in) { fActive = in; gClient->NeedRedraw(this); } Style_t GetPattern() const { return fPattern; } static void SetFillStyle(TGGC* gc, Style_t fstyle); //set fill style for given GC - ClassDef(TGedPatternFrame,0) //pattern frame + ClassDefOverride(TGedPatternFrame,0) //pattern frame }; class TGedPatternSelector : public TGCompositeFrame { @@ -72,13 +72,13 @@ class TGedPatternSelector : public TGCompositeFrame { public: TGedPatternSelector(const TGWindow *p); - virtual ~TGedPatternSelector(); + ~TGedPatternSelector() override; - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; void SetActive(Int_t newat); Int_t GetActive() const { return fActive; } - ClassDef(TGedPatternSelector,0) //select pattern frame + ClassDefOverride(TGedPatternSelector,0) //select pattern frame }; class TGedPatternPopup : public TGedPopup { @@ -88,11 +88,11 @@ class TGedPatternPopup : public TGedPopup { public: TGedPatternPopup(const TGWindow *p, const TGWindow *m, Style_t pattern); - virtual ~TGedPatternPopup(); + ~TGedPatternPopup() override; - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; - ClassDef(TGedPatternPopup,0) // Color selector popup + ClassDefOverride(TGedPatternPopup,0) // Color selector popup }; class TGedSelect : public TGCheckButton { @@ -101,20 +101,20 @@ class TGedSelect : public TGCheckButton { TGGC *fDrawGC; TGedPopup *fPopup; - virtual void DoRedraw(); + void DoRedraw() override; void DrawTriangle(GContext_t gc, Int_t x, Int_t y); public: TGedSelect(const TGWindow *p, Int_t id); - virtual ~TGedSelect(); + ~TGedSelect() override; - virtual Bool_t HandleButton(Event_t *event); + Bool_t HandleButton(Event_t *event) override; virtual void Enable(); virtual void Disable(); virtual void SetPopup(TGedPopup* p) { fPopup = p; } // popup will be deleted in destructor. - ClassDef(TGedSelect,0) //selection check-button + ClassDefOverride(TGedSelect,0) //selection check-button }; class TGedPatternSelect : public TGedSelect { @@ -122,21 +122,21 @@ class TGedPatternSelect : public TGedSelect { protected: Style_t fPattern; - virtual void DoRedraw(); + void DoRedraw() override; public: TGedPatternSelect(const TGWindow *p, Style_t pattern, Int_t id); - virtual ~TGedPatternSelect() {} + ~TGedPatternSelect() override {} void SetPattern(Style_t pattern, Bool_t emit=kTRUE); Style_t GetPattern() const { return fPattern; } - virtual TGDimension GetDefaultSize() const { return TGDimension(55, 21); } + TGDimension GetDefaultSize() const override { return TGDimension(55, 21); } virtual void PatternSelected(Style_t pattern = 0) { Emit("PatternSelected(Style_t)", pattern ? pattern : GetPattern()); } // *SIGNAL* - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); - virtual void SavePrimitive(std::ostream &out, Option_t * = ""); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; + void SavePrimitive(std::ostream &out, Option_t * = "") override; - ClassDef(TGedPatternSelect,0) //pattern selection check-button + ClassDefOverride(TGedPatternSelect,0) //pattern selection check-button }; #endif diff --git a/gui/ged/inc/TGraphEditor.h b/gui/ged/inc/TGraphEditor.h index a1195c6e17b11..259c4c9584bc0 100644 --- a/gui/ged/inc/TGraphEditor.h +++ b/gui/ged/inc/TGraphEditor.h @@ -47,8 +47,8 @@ class TGraphEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGraphEditor(); - virtual void SetModel(TObject* obj); + ~TGraphEditor() override; + void SetModel(TObject* obj) override; // slots related to graph attributes virtual void DoShape(); @@ -56,7 +56,7 @@ class TGraphEditor : public TGedFrame { virtual void DoTitle(const char *text); virtual void DoGraphLineWidth(); - ClassDef(TGraphEditor,0) // graph editor + ClassDefOverride(TGraphEditor,0) // graph editor }; #endif diff --git a/gui/ged/inc/TH1Editor.h b/gui/ged/inc/TH1Editor.h index 1ecfb283063e3..0c135389ca24e 100644 --- a/gui/ged/inc/TH1Editor.h +++ b/gui/ged/inc/TH1Editor.h @@ -125,10 +125,10 @@ class TH1Editor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TH1Editor(); + ~TH1Editor() override; - virtual Bool_t AcceptModel(TObject* model); - virtual void SetModel(TObject* obj); + Bool_t AcceptModel(TObject* model) override; + void SetModel(TObject* obj) override; virtual void DoTitle(const char *text); virtual void DoAddMarker(Bool_t on); @@ -162,10 +162,10 @@ class TH1Editor : public TGedFrame { virtual void DoCancel(); virtual void PaintBox3D(Float_t *p1, Float_t *p2,Float_t *p3, Float_t *p4); Int_t* Dividers(Int_t n); - virtual void RecursiveRemove(TObject* obj); + void RecursiveRemove(TObject* obj) override; - ClassDef(TH1Editor,0) // TH1 editor + ClassDefOverride(TH1Editor,0) // TH1 editor }; #endif diff --git a/gui/ged/inc/TH2Editor.h b/gui/ged/inc/TH2Editor.h index a886f65cec290..14f9dc08f5593 100644 --- a/gui/ged/inc/TH2Editor.h +++ b/gui/ged/inc/TH2Editor.h @@ -141,11 +141,11 @@ class TH2Editor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TH2Editor(); + ~TH2Editor() override; - virtual Bool_t AcceptModel(TObject* model); - virtual void SetModel(TObject* obj); - virtual void ActivateBaseClassEditors(TClass* cl); + Bool_t AcceptModel(TObject* model) override; + void SetModel(TObject* obj) override; + void ActivateBaseClassEditors(TClass* cl) override; virtual void DoTitle(const char *text); virtual void DoHistView(); @@ -191,9 +191,9 @@ class TH2Editor : public TGedFrame { Int_t* Dividers(Int_t n); - virtual void RecursiveRemove(TObject* obj); + void RecursiveRemove(TObject* obj) override; - ClassDef(TH2Editor,0) // TH2 editor + ClassDefOverride(TH2Editor,0) // TH2 editor }; #endif diff --git a/gui/ged/inc/TLineEditor.h b/gui/ged/inc/TLineEditor.h index 6712d3595e178..bbdd5f1cb6c8a 100644 --- a/gui/ged/inc/TLineEditor.h +++ b/gui/ged/inc/TLineEditor.h @@ -37,15 +37,15 @@ class TLineEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TLineEditor(); + ~TLineEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoStartPoint(); virtual void DoEndPoint(); virtual void DoLineVertical(); virtual void DoLineHorizontal(); - ClassDef(TLineEditor,0) // GUI for editing Line attributes + ClassDefOverride(TLineEditor,0) // GUI for editing Line attributes }; #endif diff --git a/gui/ged/inc/TPadEditor.h b/gui/ged/inc/TPadEditor.h index 0382c7d3b8a85..0749bb46be6f1 100644 --- a/gui/ged/inc/TPadEditor.h +++ b/gui/ged/inc/TPadEditor.h @@ -50,10 +50,10 @@ class TPadEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TPadEditor(); + ~TPadEditor() override; - virtual void SetModel(TObject* obj); - virtual void ActivateBaseClassEditors(TClass* cl); + void SetModel(TObject* obj) override; + void ActivateBaseClassEditors(TClass* cl) override; virtual void DoEditable(Bool_t on); virtual void DoCrosshair(Bool_t on); @@ -68,7 +68,7 @@ class TPadEditor : public TGedFrame { virtual void DoBorderMode(); virtual void DoBorderSize(Int_t size); - ClassDef(TPadEditor,0) //editor of TPad objects + ClassDefOverride(TPadEditor,0) //editor of TPad objects }; #endif diff --git a/gui/ged/inc/TPaveStatsEditor.h b/gui/ged/inc/TPaveStatsEditor.h index 5c999f4cd9b31..75bc00ce8d99a 100644 --- a/gui/ged/inc/TPaveStatsEditor.h +++ b/gui/ged/inc/TPaveStatsEditor.h @@ -46,14 +46,14 @@ class TPaveStatsEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TPaveStatsEditor(); + ~TPaveStatsEditor() override; - virtual void SetModel(TObject* obj); + void SetModel(TObject* obj) override; virtual void DoStatOptions(); virtual void DoFitOptions(); virtual void SetValuesON(Bool_t on); - ClassDef(TPaveStatsEditor,0) // GUI for editing TPaveStats + ClassDefOverride(TPaveStatsEditor,0) // GUI for editing TPaveStats }; #endif diff --git a/gui/ged/inc/TPieEditor.h b/gui/ged/inc/TPieEditor.h index 99602975b4585..6551a2d252b2a 100644 --- a/gui/ged/inc/TPieEditor.h +++ b/gui/ged/inc/TPieEditor.h @@ -54,9 +54,9 @@ class TPieEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TPieEditor(); - virtual void SetModel(TObject* ); - virtual void ActivateBaseClassEditors(TClass*); + ~TPieEditor() override; + void SetModel(TObject* ) override; + void ActivateBaseClassEditors(TClass*) override; // slots related to graph attributes virtual void DoShape(); @@ -66,6 +66,6 @@ class TPieEditor : public TGedFrame { virtual void DoChange3DAngle(); virtual void DoTextChange(); - ClassDef(TPieEditor,0) // piechart editor + ClassDefOverride(TPieEditor,0) // piechart editor }; #endif diff --git a/gui/ged/inc/TPieSliceEditor.h b/gui/ged/inc/TPieSliceEditor.h index 04626508f3516..d836a80dd5aa5 100644 --- a/gui/ged/inc/TPieSliceEditor.h +++ b/gui/ged/inc/TPieSliceEditor.h @@ -34,15 +34,15 @@ class TPieSliceEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - ~TPieSliceEditor(); + ~TPieSliceEditor() override; - void SetModel(TObject *); + void SetModel(TObject *) override; void DoTitle(const char*); void DoValue(); void DoOffset(); - ClassDef(TPieSliceEditor,0) // piechart' slice editor + ClassDefOverride(TPieSliceEditor,0) // piechart' slice editor }; #endif // ROOT_TPieSliceEditor diff --git a/gui/ged/inc/TStyleDialog.h b/gui/ged/inc/TStyleDialog.h index 76f74785f2af1..d85239379f77c 100644 --- a/gui/ged/inc/TStyleDialog.h +++ b/gui/ged/inc/TStyleDialog.h @@ -44,14 +44,14 @@ class TStyleDialog : public TGTransientFrame { public: TStyleDialog(TStyleManager *sm, TStyle *cur, Int_t mode, TVirtualPad *currentPad = nullptr); - virtual ~TStyleDialog(); + ~TStyleDialog() override; void DoCloseWindow(); // SLOT void DoCancel(); // SLOT void DoOK(); // SLOT void DoUpdate(); // SLOT - ClassDef(TStyleDialog, 0) // Dialog box used by the TStyleManager class + ClassDefOverride(TStyleDialog, 0) // Dialog box used by the TStyleManager class }; #endif diff --git a/gui/ged/inc/TStyleManager.h b/gui/ged/inc/TStyleManager.h index d7bcd5c22d36c..5b9320470f69e 100644 --- a/gui/ged/inc/TStyleManager.h +++ b/gui/ged/inc/TStyleManager.h @@ -440,7 +440,7 @@ class TStyleManager : public TGMainFrame { public: TStyleManager(const TGWindow *); - virtual ~TStyleManager(); + ~TStyleManager() override; static void Show(); static void Terminate(); @@ -469,7 +469,7 @@ class TStyleManager : public TGMainFrame { void DoSelectNoCanvas(); // SLOT void DoSelectCanvas(TVirtualPad *pad, TObject *obj, Int_t mouseButton); // SLOT - void CloseWindow(); // SLOT + void CloseWindow() override; // SLOT // GENERAL void ModFillColor(); // SLOT @@ -651,7 +651,7 @@ class TStyleManager : public TGMainFrame { void ModPaperSizePredef(); // SLOT void ModPaperSizeXY(); // SLOT - ClassDef(TStyleManager, 0) // Graphical User Interface for managing styles + ClassDefOverride(TStyleManager, 0) // Graphical User Interface for managing styles }; #endif diff --git a/gui/ged/inc/TStylePreview.h b/gui/ged/inc/TStylePreview.h index c8850dad9856d..11a7c09b321ce 100644 --- a/gui/ged/inc/TStylePreview.h +++ b/gui/ged/inc/TStylePreview.h @@ -29,12 +29,12 @@ class TStylePreview : public TGTransientFrame { public: TStylePreview(const TGWindow *p, TStyle *style, TVirtualPad *currentPad); - virtual ~TStylePreview(); + ~TStylePreview() override; void Update(TStyle *style, TVirtualPad *pad); void MapTheWindow(); TCanvas *GetMainCanvas(); - ClassDef(TStylePreview, 0) // Preview window used by the TStyleManager class + ClassDefOverride(TStylePreview, 0) // Preview window used by the TStyleManager class }; #endif diff --git a/gui/ged/inc/TTextEditor.h b/gui/ged/inc/TTextEditor.h index 8bc4faab33dd2..615c4204eb85e 100644 --- a/gui/ged/inc/TTextEditor.h +++ b/gui/ged/inc/TTextEditor.h @@ -37,9 +37,9 @@ class TTextEditor : public TGedFrame { Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - ~TTextEditor(); + ~TTextEditor() override; - void SetModel(TObject *); + void SetModel(TObject *) override; void DoAngle(); void DoSize(); @@ -47,7 +47,7 @@ class TTextEditor : public TGedFrame { void DoXpos(); void DoYpos(); - ClassDef(TTextEditor,0) // text editor + ClassDefOverride(TTextEditor,0) // text editor }; #endif // ROOT_TTextEditor diff --git a/gui/ged/src/TH1Editor.cxx b/gui/ged/src/TH1Editor.cxx index 9873b599e7b20..3b6e721d00d99 100644 --- a/gui/ged/src/TH1Editor.cxx +++ b/gui/ged/src/TH1Editor.cxx @@ -166,7 +166,7 @@ TH1Editor::TH1Editor(const TGWindow *p, Int_t width, // Histogram draw options TGCompositeFrame *fHistLbl = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); fHistLbl->AddFrame(new TGLabel(fHistLbl,"Histogram"), @@ -277,7 +277,7 @@ TH1Editor::TH1Editor(const TGWindow *p, Int_t width, // Bar Menu => appears when the BAR checkbox is set f10 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); f10->AddFrame(new TGLabel(f10,"Bar"), @@ -343,7 +343,7 @@ void TH1Editor::CreateBinTab() TGCompositeFrame *title1 = new TGCompositeFrame(fBin, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title1->AddFrame(new TGLabel(title1, "Rebin"), @@ -450,7 +450,7 @@ void TH1Editor::CreateBinTab() kVerticalFrame); TGCompositeFrame *title2 = new TGCompositeFrame(sldCont, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title2->AddFrame(new TGLabel(title2, "Axis Range"), diff --git a/gui/ged/src/TH2Editor.cxx b/gui/ged/src/TH2Editor.cxx index ec3b93d9cef47..6862adfba4631 100644 --- a/gui/ged/src/TH2Editor.cxx +++ b/gui/ged/src/TH2Editor.cxx @@ -288,7 +288,7 @@ TH2Editor::TH2Editor(const TGWindow *p, Int_t width, // Bin bar settings f12 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); f12->AddFrame(new TGLabel(f12,"Bar"), @@ -323,7 +323,7 @@ TH2Editor::TH2Editor(const TGWindow *p, Int_t width, // Set the color and pattern of the Frame (only for Cartesian 3D plot). f38 = new TGCompositeFrame(this, 80, 20, kVerticalFrame); TGCompositeFrame *f39 = new TGCompositeFrame(f38, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); f39->AddFrame(new TGLabel(f39,"Frame Fill"), @@ -361,7 +361,7 @@ void TH2Editor::CreateBinTab() fBinXCont = new TGCompositeFrame(fBin, 80, 20, kVerticalFrame); TGCompositeFrame *title1 = new TGCompositeFrame(fBinXCont, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title1->AddFrame(new TGLabel(title1, "Rebin"), @@ -430,7 +430,7 @@ void TH2Editor::CreateBinTab() fBinXCont1 = new TGCompositeFrame(fBin, 80, 20, kVerticalFrame); TGCompositeFrame *title2 = new TGCompositeFrame(fBinXCont1, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title2->AddFrame(new TGLabel(title2, "X-Axis"), @@ -504,7 +504,7 @@ void TH2Editor::CreateBinTab() fBinYCont1 = new TGCompositeFrame(fBin, 80, 20, kVerticalFrame); TGCompositeFrame *title3 = new TGCompositeFrame(fBinYCont1, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title3->AddFrame(new TGLabel(title3, "Y-Axis"), @@ -576,7 +576,7 @@ void TH2Editor::CreateBinTab() // Axis ranges TGCompositeFrame *title4 = new TGCompositeFrame(fBin, 145, 10, kHorizontalFrame | - kLHintsExpandX | + kFitWidth | kFixedWidth | kOwnBackground); title4->AddFrame(new TGLabel(title4, "Axis Range"), diff --git a/gui/gui/inc/TGApplication.h b/gui/gui/inc/TGApplication.h index 2e4f06afceade..eded2db59beb5 100644 --- a/gui/gui/inc/TGApplication.h +++ b/gui/gui/inc/TGApplication.h @@ -32,7 +32,7 @@ class TGApplication : public TApplication { TGApplication(const char *appClassName, Int_t *argc, char **argv, void *options = nullptr, Int_t numOptions = 0); - virtual ~TGApplication(); + ~TGApplication() override; void GetOptions(Int_t *argc, char **argv) override; diff --git a/gui/gui/inc/TGButton.h b/gui/gui/inc/TGButton.h index 9a2d0092f64e0..a71554bbe7472 100644 --- a/gui/gui/inc/TGButton.h +++ b/gui/gui/inc/TGButton.h @@ -100,7 +100,7 @@ friend class TGButtonGroup; TGButton(const TGWindow *p = nullptr, Int_t id = -1, GContext_t norm = GetDefaultGC()(), UInt_t option = kRaisedFrame | kDoubleBorder); - virtual ~TGButton(); + ~TGButton() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleCrossing(Event_t *event) override; @@ -181,7 +181,7 @@ class TGTextButton : public TGButton { FontStruct_t font = GetDefaultFontStruct(), UInt_t option = kRaisedFrame | kDoubleBorder); - virtual ~TGTextButton(); + ~TGTextButton() override; TGDimension GetDefaultSize() const override; @@ -249,7 +249,7 @@ class TGPictureButton : public TGButton { TGPictureButton(const TGWindow *p = nullptr, const char* pic = nullptr, Int_t id = -1, GContext_t norm = GetDefaultGC()(), UInt_t option = kRaisedFrame | kDoubleBorder); - virtual ~TGPictureButton(); + ~TGPictureButton() override; virtual void SetPicture(const TGPicture *new_pic); virtual void SetDisabledPicture(const TGPicture *pic); @@ -299,7 +299,7 @@ class TGCheckButton : public TGTextButton { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t option = 0); - virtual ~TGCheckButton(); + ~TGCheckButton() override; TGDimension GetDefaultSize() const override; @@ -355,7 +355,7 @@ class TGRadioButton : public TGTextButton { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t option = 0); - virtual ~TGRadioButton(); + ~TGRadioButton() override; TGDimension GetDefaultSize() const override; @@ -418,7 +418,7 @@ friend class TGPopupMenu; FontStruct_t fontstruct = GetDefaultFontStruct(), UInt_t option = kRaisedFrame | kDoubleBorder); - virtual ~TGSplitButton(); + ~TGSplitButton() override; TGDimension GetDefaultSize() const override; diff --git a/gui/gui/inc/TGButtonGroup.h b/gui/gui/inc/TGButtonGroup.h index 14cf2947c9bef..4d6e52a7490eb 100644 --- a/gui/gui/inc/TGButtonGroup.h +++ b/gui/gui/inc/TGButtonGroup.h @@ -51,7 +51,7 @@ friend class TGButton; FontStruct_t font = GetDefaultFontStruct(), Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGButtonGroup(); + ~TGButtonGroup() override; virtual void Pressed(Int_t id) { Emit("Pressed(Int_t)",id); } //*SIGNAL* virtual void Released(Int_t id) { Emit("Released(Int_t)",id);} //*SIGNAL* @@ -102,7 +102,7 @@ class TGVButtonGroup : public TGButtonGroup { TGButtonGroup(parent, title, kChildFrame | kVerticalFrame, norm, font, back) {} - virtual ~TGVButtonGroup() {} + ~TGVButtonGroup() override {} void SavePrimitive(std::ostream &out, Option_t *option = "") override; ClassDefOverride(TGVButtonGroup,0) // A button group with one vertical column @@ -120,7 +120,7 @@ class TGHButtonGroup : public TGButtonGroup { TGButtonGroup(parent, title, kChildFrame | kHorizontalFrame, norm, font, back) { } - virtual ~TGHButtonGroup() {} + ~TGHButtonGroup() override {} void SavePrimitive(std::ostream &out, Option_t *option = "") override; ClassDefOverride(TGHButtonGroup,0) // A button group with one horizontal row diff --git a/gui/gui/inc/TGCanvas.h b/gui/gui/inc/TGCanvas.h index 9c6420e58c6cc..b5c5e042b3a4f 100644 --- a/gui/gui/inc/TGCanvas.h +++ b/gui/gui/inc/TGCanvas.h @@ -82,7 +82,7 @@ friend class TGListView; TGContainer(TGCanvas *p,UInt_t options = kSunkenFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGContainer(); + ~TGContainer() override; virtual void DrawRegion(Int_t x, Int_t y, UInt_t w, UInt_t h); virtual void ClearViewPort(); @@ -211,7 +211,7 @@ class TGCanvas : public TGFrame { TGCanvas(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = kSunkenFrame | kDoubleBorder, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGCanvas(); + ~TGCanvas() override; TGFrame *GetContainer() const { return fVport->GetContainer(); } TGViewPort *GetViewPort() const { return fVport; } diff --git a/gui/gui/inc/TGClient.h b/gui/gui/inc/TGClient.h index 19b0e5b82ab47..c13ea3e9aee4c 100644 --- a/gui/gui/inc/TGClient.h +++ b/gui/gui/inc/TGClient.h @@ -75,7 +75,7 @@ friend class TGCocoa; public: TGClient(const char *dpyName = nullptr); - virtual ~TGClient(); + ~TGClient() override; const TGWindow *GetRoot() const; const TGWindow *GetDefaultRoot() const; diff --git a/gui/gui/inc/TGColorDialog.h b/gui/gui/inc/TGColorDialog.h index 84e4e5b1f1576..7549c02e4396f 100644 --- a/gui/gui/inc/TGColorDialog.h +++ b/gui/gui/inc/TGColorDialog.h @@ -54,7 +54,7 @@ class TGColorPalette : public TGFrame, public TGWidget { public: TGColorPalette(const TGWindow *p = nullptr, Int_t cols = 8, Int_t rows = 8, Int_t id = -1); - virtual ~TGColorPalette(); + ~TGColorPalette() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; @@ -117,7 +117,7 @@ class TGColorPick : public TGFrame, public TGWidget { public: TGColorPick(const TGWindow *p = nullptr, Int_t w = 1, Int_t h = 1, Int_t id = -1); - virtual ~TGColorPick(); + ~TGColorPick() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; @@ -171,7 +171,7 @@ class TGColorDialog : public TGTransientFrame { public: TGColorDialog(const TGWindow *p = nullptr, const TGWindow *m = nullptr, Int_t *retc = nullptr, Pixel_t *color = nullptr, Bool_t wait = kTRUE); - virtual ~TGColorDialog(); + ~TGColorDialog() override; TGColorPalette *GetPalette() const { return fPalette; } TGColorPalette *GetCustomPalette() const { return fCpalette; } diff --git a/gui/gui/inc/TGColorSelect.h b/gui/gui/inc/TGColorSelect.h index 6b580e2b2ce55..7aa8f8278fdc4 100644 --- a/gui/gui/inc/TGColorSelect.h +++ b/gui/gui/inc/TGColorSelect.h @@ -34,7 +34,7 @@ class TGColorFrame : public TGFrame { public: TGColorFrame(const TGWindow *p = nullptr, Pixel_t c = 0, Int_t n = 1); - virtual ~TGColorFrame() { } + ~TGColorFrame() override { } Bool_t HandleButton(Event_t *event) override; void DrawBorder() override; @@ -60,7 +60,7 @@ class TG16ColorSelector : public TGCompositeFrame { public: TG16ColorSelector(const TGWindow *p = nullptr); - virtual ~TG16ColorSelector(); + ~TG16ColorSelector() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; @@ -86,7 +86,7 @@ class TGColorPopup : public TGCompositeFrame { public: TGColorPopup(const TGWindow *p = nullptr, const TGWindow *m = nullptr, Pixel_t color = 0); - virtual ~TGColorPopup(); + ~TGColorPopup() override; Bool_t HandleButton(Event_t *event) override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; @@ -120,7 +120,7 @@ class TGColorSelect : public TGCheckButton { public: TGColorSelect(const TGWindow *p = nullptr, Pixel_t color = 0, Int_t id = -1); - virtual ~TGColorSelect(); + ~TGColorSelect() override; Bool_t HandleButton(Event_t *event) override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; diff --git a/gui/gui/inc/TGComboBox.h b/gui/gui/inc/TGComboBox.h index 08497223b9fc1..1fe56a84a590d 100644 --- a/gui/gui/inc/TGComboBox.h +++ b/gui/gui/inc/TGComboBox.h @@ -71,7 +71,7 @@ class TGComboBox : public TGCompositeFrame, public TGWidget { UInt_t options = kHorizontalFrame | kSunkenFrame | kDoubleBorder, Pixel_t back = GetWhitePixel()); - virtual ~TGComboBox(); + ~TGComboBox() override; void DrawBorder() override; TGDimension GetDefaultSize() const override { return TGDimension(fWidth, fHeight); } @@ -184,7 +184,7 @@ class TGFontTypeComboBox : public TGComboBox { TGFontTypeComboBox(const TGWindow *p = nullptr, Int_t id = -1, UInt_t options = kHorizontalFrame | kSunkenFrame | kDoubleBorder, Pixel_t bask = GetWhitePixel()); - virtual ~TGFontTypeComboBox(); + ~TGFontTypeComboBox() override; ClassDefOverride(TGFontTypeComboBox, 0) // Font type combobox widget }; diff --git a/gui/gui/inc/TGCommandPlugin.h b/gui/gui/inc/TGCommandPlugin.h index 09c8c1974877b..106b12bb702b3 100644 --- a/gui/gui/inc/TGCommandPlugin.h +++ b/gui/gui/inc/TGCommandPlugin.h @@ -40,7 +40,7 @@ class TGCommandPlugin : public TGMainFrame { public: TGCommandPlugin(const TGWindow *p, UInt_t w, UInt_t h); - virtual ~TGCommandPlugin(); + ~TGCommandPlugin() override; void CheckRemote(const char * /*str*/); void HandleArrows(Int_t keysym); diff --git a/gui/gui/inc/TGDNDManager.h b/gui/gui/inc/TGDNDManager.h index 3defad495553b..00b3f4f870068 100644 --- a/gui/gui/inc/TGDNDManager.h +++ b/gui/gui/inc/TGDNDManager.h @@ -34,7 +34,7 @@ class TGDragWindow : public TGFrame { public: TGDragWindow(const TGWindow *p, Pixmap_t pic, Pixmap_t mask, UInt_t options = kChildFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGDragWindow(); + ~TGDragWindow() override; TGDimension GetDefaultSize() const override { return TGDimension(fPw, fPh); } @@ -69,7 +69,7 @@ class TDNDData : public TObject { public: TDNDData(Atom_t dt = kNone, void *d = nullptr, Int_t len = 0, Atom_t act = kNone) : fDataType(dt), fAction(act), fData(d), fDataLength(len) {} - ~TDNDData() {} + ~TDNDData() override {} Atom_t fDataType; ///< Data type description Atom_t fAction; ///< Action description @@ -148,7 +148,7 @@ class TGDNDManager : public TObject { public: TGDNDManager(TGFrame *toplevel, Atom_t *typelist); - virtual ~TGDNDManager(); + ~TGDNDManager() override; Bool_t HandleClientMessage(Event_t *event); Bool_t HandleSelectionRequest(Event_t *event); diff --git a/gui/gui/inc/TGDockableFrame.h b/gui/gui/inc/TGDockableFrame.h index 67158163e8752..c228e2dda722e 100644 --- a/gui/gui/inc/TGDockableFrame.h +++ b/gui/gui/inc/TGDockableFrame.h @@ -36,7 +36,7 @@ class TGDockButton : public TGButton { public: TGDockButton(const TGCompositeFrame *p = nullptr, Int_t id = 1); - virtual ~TGDockButton(); + ~TGDockButton() override; Bool_t HandleCrossing(Event_t *event) override; @@ -70,7 +70,7 @@ class TGUndockedFrame : public TGTransientFrame { public: TGUndockedFrame(const TGWindow *p = nullptr, TGDockableFrame *dockable = nullptr); - virtual ~TGUndockedFrame(); + ~TGUndockedFrame() override; void FixSize(); void CloseWindow() override; @@ -104,7 +104,7 @@ friend class TGUndockedFrame; public: TGDockableFrame(const TGWindow *p = nullptr, Int_t id = -1, UInt_t options = kHorizontalFrame); - virtual ~TGDockableFrame(); + ~TGDockableFrame() override; void AddFrame(TGFrame *f, TGLayoutHints *hints) override; diff --git a/gui/gui/inc/TGDoubleSlider.h b/gui/gui/inc/TGDoubleSlider.h index 6ca6c6493602e..f52b7baf6fc15 100644 --- a/gui/gui/inc/TGDoubleSlider.h +++ b/gui/gui/inc/TGDoubleSlider.h @@ -71,7 +71,7 @@ class TGDoubleSlider : public TGFrame, public TGWidget { Bool_t reversed = kFALSE, Bool_t mark_ends = kFALSE); - virtual ~TGDoubleSlider() { } + ~TGDoubleSlider() override { } Bool_t HandleButton(Event_t *event) override = 0; Bool_t HandleMotion(Event_t *event) override = 0; @@ -181,7 +181,7 @@ class TGDoubleVSlider : public TGDoubleSlider { Bool_t reversed = kFALSE, Bool_t mark_ends = kFALSE); - virtual ~TGDoubleVSlider(); + ~TGDoubleVSlider() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; @@ -207,7 +207,7 @@ class TGDoubleHSlider : public TGDoubleSlider { Bool_t reversed = kFALSE, Bool_t mark_ends = kFALSE); - virtual ~TGDoubleHSlider(); + ~TGDoubleHSlider() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; diff --git a/gui/gui/inc/TGEventHandler.h b/gui/gui/inc/TGEventHandler.h index 9f7083e6a0d96..881cbc12c5338 100644 --- a/gui/gui/inc/TGEventHandler.h +++ b/gui/gui/inc/TGEventHandler.h @@ -35,7 +35,7 @@ class TGEventHandler : public TNamed, public TQObject { public: TGEventHandler(const char *name, TGWindow *w, TObject *obj, const char *title="") : TNamed(name, title), fIsActive(kTRUE), fWindow(w), fObject(obj) { } - virtual ~TGEventHandler() { } + ~TGEventHandler() override { } void Activate() { fIsActive = kTRUE; } void DeActivate() { fIsActive = kFALSE; } diff --git a/gui/gui/inc/TGFSComboBox.h b/gui/gui/inc/TGFSComboBox.h index 6a4715a3c5353..33bd9ac4d0804 100644 --- a/gui/gui/inc/TGFSComboBox.h +++ b/gui/gui/inc/TGFSComboBox.h @@ -48,7 +48,7 @@ class TGTreeLBEntry : public TGLBEntry { Int_t id = -1, TGString *path = nullptr, GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kHorizontalFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGTreeLBEntry(); + ~TGTreeLBEntry() override; const TGString *GetText() const { return fText; } const TGPicture *GetPicture() const { return fPic; } diff --git a/gui/gui/inc/TGFSContainer.h b/gui/gui/inc/TGFSContainer.h index d1e379f2296a2..65cf1ad8dec34 100644 --- a/gui/gui/inc/TGFSContainer.h +++ b/gui/gui/inc/TGFSContainer.h @@ -73,7 +73,7 @@ class TGFileItem : public TGLVEntry { EListViewMode viewMode = kLVList, UInt_t options = kVerticalFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGFileItem(); + ~TGFileItem() override; void SetViewMode(EListViewMode viewMode) override; @@ -144,7 +144,7 @@ friend class TGFSFrameElement; TGFileContainer(TGCanvas *p, UInt_t options = kSunkenFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGFileContainer(); + ~TGFileContainer() override; Bool_t HandleTimer(TTimer *t) override; void StopRefreshTimer(); diff --git a/gui/gui/inc/TGFileBrowser.h b/gui/gui/inc/TGFileBrowser.h index d1ff7af888351..aa5808ee0526e 100644 --- a/gui/gui/inc/TGFileBrowser.h +++ b/gui/gui/inc/TGFileBrowser.h @@ -77,7 +77,7 @@ class TGFileBrowser : public TGMainFrame, public TBrowserImp { public: TGFileBrowser(const TGWindow *p, TBrowser *b = nullptr, UInt_t w = 200, UInt_t h = 400); - virtual ~TGFileBrowser(); + ~TGFileBrowser() override; void Add(TObject *obj, const char *name = nullptr, Int_t check = -1) override; void BrowseObj(TObject *obj) override; @@ -113,6 +113,9 @@ class TGFileBrowser : public TGMainFrame, public TBrowserImp { void ToggleSort(); void Update(); + TGListTree *GetListTree() const { return fListTree; } + TGListTreeItem *GetRootDir() const { return fRootDir; } + ClassDefOverride(TGFileBrowser, 0) // File browser. }; diff --git a/gui/gui/inc/TGFileDialog.h b/gui/gui/inc/TGFileDialog.h index 11cc397a47f55..92ad12713297d 100644 --- a/gui/gui/inc/TGFileDialog.h +++ b/gui/gui/inc/TGFileDialog.h @@ -93,7 +93,7 @@ class TGFileDialog : public TGTransientFrame { public: TGFileDialog(const TGWindow *p = nullptr, const TGWindow *main = nullptr, EFileDialogMode dlg_type = kFDOpen, TGFileInfo *file_info = nullptr); - virtual ~TGFileDialog(); + ~TGFileDialog() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; void CloseWindow() override; diff --git a/gui/gui/inc/TGFont.h b/gui/gui/inc/TGFont.h index 9a7556c75ca2b..a5fda22353af6 100644 --- a/gui/gui/inc/TGFont.h +++ b/gui/gui/inc/TGFont.h @@ -119,7 +119,7 @@ friend class TGFont; public: TGTextLayout(): fFont(nullptr), fString(""), fWidth(0), fNumChunks(0), fChunks(nullptr) {} - virtual ~TGTextLayout(); + ~TGTextLayout() override; void DrawText(Drawable_t dst, GContext_t gc, Int_t x, Int_t y, Int_t firstChar, Int_t lastChar) const; @@ -178,7 +178,7 @@ friend class TGTextLayout; const char *start, int numChars, int curX, int newX, int y) const; public: - virtual ~TGFont(); + ~TGFont() override; FontH_t GetFontHandle() const { return fFontH; } FontStruct_t GetFontStruct() const { return fFontStruct; } @@ -236,7 +236,7 @@ class TGFontPool : public TGObject { public: TGFontPool(TGClient *client); - virtual ~TGFontPool(); + ~TGFontPool() override; TGFont *GetFont(const char *font, Bool_t fixedDefault = kTRUE); TGFont *GetFont(const TGFont *font); diff --git a/gui/gui/inc/TGFontDialog.h b/gui/gui/inc/TGFontDialog.h index 8b23e3f272a70..95b4520f7949e 100644 --- a/gui/gui/inc/TGFontDialog.h +++ b/gui/gui/inc/TGFontDialog.h @@ -67,7 +67,7 @@ class TGFontDialog : public TGTransientFrame { TGFontDialog(const TGWindow *parent = nullptr, const TGWindow *t = nullptr, FontProp_t *fontProp = nullptr, const TString &sample = "", char **fontList = nullptr, Bool_t wait = kTRUE); - virtual ~TGFontDialog(); + ~TGFontDialog() override; virtual void SetFont(TGFont *font); virtual void SetColor(Pixel_t color); diff --git a/gui/gui/inc/TGFrame.h b/gui/gui/inc/TGFrame.h index 9e1d062a2dba5..65c34ada82c6d 100644 --- a/gui/gui/inc/TGFrame.h +++ b/gui/gui/inc/TGFrame.h @@ -147,7 +147,7 @@ class TGFrame : public TGWindow, public TQObject { TGFrame(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); TGFrame(TGClient *c, Window_t id, const TGWindow *parent = nullptr); - virtual ~TGFrame(); + ~TGFrame() override; virtual void DeleteWindow(); virtual void ReallyDelete() { delete this; } @@ -305,7 +305,7 @@ class TGCompositeFrame : public TGFrame { UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); TGCompositeFrame(TGClient *c, Window_t id, const TGWindow *parent = nullptr); - virtual ~TGCompositeFrame(); + ~TGCompositeFrame() override; virtual TList *GetList() const { return fList; } @@ -443,7 +443,7 @@ class TGMainFrame : public TGCompositeFrame { public: TGMainFrame(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = kVerticalFrame); - virtual ~TGMainFrame(); + ~TGMainFrame() override; Bool_t HandleKey(Event_t *event) override; Bool_t HandleClientMessage(Event_t *event) override; @@ -553,7 +553,7 @@ class TGGroupFrame : public TGCompositeFrame { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGGroupFrame(); + ~TGGroupFrame() override; TGDimension GetDefaultSize() const override; void DrawBorder() override; diff --git a/gui/gui/inc/TGGC.h b/gui/gui/inc/TGGC.h index d4cab6ba61612..f74a54939e8cb 100644 --- a/gui/gui/inc/TGGC.h +++ b/gui/gui/inc/TGGC.h @@ -35,7 +35,7 @@ friend class TGGCPool; public: TGGC(GCValues_t *values = nullptr); TGGC(const TGGC &g); - virtual ~TGGC(); + ~TGGC() override; TGGC &operator=(const TGGC &rhs); GContext_t GetGC() const { return fContext; } @@ -124,7 +124,7 @@ friend class TGGC; public: TGGCPool(TGClient *client); - virtual ~TGGCPool(); + ~TGGCPool() override; TGGC *GetGC(GCValues_t *values, Bool_t rw = kFALSE); TGGC *GetGC(GContext_t gct); diff --git a/gui/gui/inc/TGIcon.h b/gui/gui/inc/TGIcon.h index f28449e7644ce..7a43083c1d35e 100644 --- a/gui/gui/inc/TGIcon.h +++ b/gui/gui/inc/TGIcon.h @@ -39,7 +39,7 @@ class TGIcon : public TGFrame { TGIcon(const TGWindow *p = nullptr, const char *image = nullptr); - virtual ~TGIcon(); + ~TGIcon() override; virtual void Reset(); //*MENU* const TGPicture *GetPicture() const { return fPic; } diff --git a/gui/gui/inc/TGIdleHandler.h b/gui/gui/inc/TGIdleHandler.h index e1c9c90f4e471..4f87af988a5a5 100644 --- a/gui/gui/inc/TGIdleHandler.h +++ b/gui/gui/inc/TGIdleHandler.h @@ -23,7 +23,7 @@ class TGIdleHandler : public TObject { public: TGIdleHandler(TGWindow *w); - virtual ~TGIdleHandler(); + ~TGIdleHandler() override; virtual Bool_t HandleEvent(); diff --git a/gui/gui/inc/TGImageMap.h b/gui/gui/inc/TGImageMap.h index b6878e7dd9aba..bd6cd5716642f 100644 --- a/gui/gui/inc/TGImageMap.h +++ b/gui/gui/inc/TGImageMap.h @@ -41,7 +41,7 @@ class TGRegion : public TObject { TGRegion(Int_t n, Int_t *x, Int_t *y, Bool_t winding = kFALSE); TGRegion(const TArrayS &x, const TArrayS &y, Bool_t winding = kFALSE); TGRegion(const TGRegion ®); - virtual ~TGRegion(); + ~TGRegion() override; Bool_t Contains(const TPoint &p) const; Bool_t Contains(Int_t x, Int_t y) const; @@ -90,7 +90,7 @@ class TGRegionWithId : public TGRegion { TGRegionWithId(Int_t id, Int_t n, TPoint *points, Bool_t winding = kFALSE); TGRegionWithId(const TGRegionWithId ®); TGRegionWithId(const TGRegion ®, Int_t id); - virtual ~TGRegionWithId(); + ~TGRegionWithId() override; Int_t GetId() const { return fId; } TGToolTip *GetToolTipText() const { return fTip; } @@ -126,7 +126,7 @@ class TGImageMap : public TGPictureButton { public: TGImageMap(const TGWindow *p = nullptr, const TGPicture *pic = nullptr); TGImageMap(const TGWindow *p, const TString &pic); - virtual ~TGImageMap(); + ~TGImageMap() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleDoubleClick(Event_t *event) override; diff --git a/gui/gui/inc/TGInputDialog.h b/gui/gui/inc/TGInputDialog.h index 56aba89a06d76..e5d0c4ee9ffee 100644 --- a/gui/gui/inc/TGInputDialog.h +++ b/gui/gui/inc/TGInputDialog.h @@ -36,7 +36,7 @@ class TGInputDialog : public TGTransientFrame { TGInputDialog(const TGWindow *p = nullptr, const TGWindow *main = nullptr, const char *prompt = nullptr, const char *defval = nullptr, char *retstr = nullptr, UInt_t options = kVerticalFrame); - ~TGInputDialog(); + ~TGInputDialog() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t) override; diff --git a/gui/gui/inc/TGLabel.h b/gui/gui/inc/TGLabel.h index df46d4f3965a4..c58db60888c7b 100644 --- a/gui/gui/inc/TGLabel.h +++ b/gui/gui/inc/TGLabel.h @@ -67,7 +67,7 @@ class TGLabel : public TGFrame { UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGLabel(); + ~TGLabel() override; TGDimension GetDefaultSize() const override; diff --git a/gui/gui/inc/TGLayout.h b/gui/gui/inc/TGLayout.h index 31abf10709465..57fa3b61cc61d 100644 --- a/gui/gui/inc/TGLayout.h +++ b/gui/gui/inc/TGLayout.h @@ -77,7 +77,7 @@ friend class TGCompositeFrame; TGLayoutHints(const TGLayoutHints &lh); - virtual ~TGLayoutHints(); + ~TGLayoutHints() override; ULong_t GetLayoutHints() const { return fLayoutHints; } Int_t GetPadTop() const { return fPadtop; } @@ -115,7 +115,7 @@ class TGFrameElement : public TObject { TGFrameElement() : fFrame(nullptr), fState(0), fLayout(nullptr) { } TGFrameElement(TGFrame *f, TGLayoutHints *l); - ~TGFrameElement(); + ~TGFrameElement() override; void Print(Option_t* option = "") const override; void ls(Option_t* option = "") const override { Print(option); } diff --git a/gui/gui/inc/TGListBox.h b/gui/gui/inc/TGListBox.h index 0a610b6311586..8899d92a0ac27 100644 --- a/gui/gui/inc/TGListBox.h +++ b/gui/gui/inc/TGListBox.h @@ -73,7 +73,7 @@ class TGTextLBEntry : public TGLBEntry { FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kHorizontalFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGTextLBEntry(); + ~TGTextLBEntry() override; TGDimension GetDefaultSize() const override { return TGDimension(fTWidth, fTHeight+1); } const TGString *GetText() const { return fText; } @@ -113,7 +113,7 @@ class TGLineLBEntry : public TGTextLBEntry { UInt_t w = 0, Style_t s = 0, UInt_t options = kHorizontalFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGLineLBEntry(); + ~TGLineLBEntry() override; TGDimension GetDefaultSize() const override { return TGDimension(fTWidth, fTHeight+1); } @@ -146,7 +146,7 @@ class TGIconLBEntry : public TGTextLBEntry { UInt_t w = 0, Style_t s = 0, UInt_t options = kHorizontalFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGIconLBEntry(); + ~TGIconLBEntry() override; TGDimension GetDefaultSize() const override { return TGDimension(fTWidth, fTHeight+1); } @@ -182,7 +182,7 @@ friend class TGListBox; TGLBContainer(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = kSunkenFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGLBContainer(); + ~TGLBContainer() override; virtual void AddEntry(TGLBEntry *lbe, TGLayoutHints *lhints); virtual void AddEntrySort(TGLBEntry *lbe, TGLayoutHints *lhints); @@ -239,7 +239,7 @@ class TGListBox : public TGCompositeFrame, public TGWidget { TGListBox(const TGWindow *p = nullptr, Int_t id = -1, UInt_t options = kSunkenFrame | kDoubleBorder, Pixel_t back = GetWhitePixel()); - virtual ~TGListBox(); + ~TGListBox() override; virtual void AddEntry(TGString *s, Int_t id); virtual void AddEntry(const char *s, Int_t id); diff --git a/gui/gui/inc/TGListTree.h b/gui/gui/inc/TGListTree.h index eca365f61d619..fbb9d4fbd27a1 100644 --- a/gui/gui/inc/TGListTree.h +++ b/gui/gui/inc/TGListTree.h @@ -148,7 +148,7 @@ class TGListTreeItemStd : public TGListTreeItem TGListTreeItemStd(TGClient *fClient = gClient, const char *name = nullptr, const TGPicture *opened = nullptr, const TGPicture *closed = nullptr, Bool_t checkbox = kFALSE); - virtual ~TGListTreeItemStd(); + ~TGListTreeItemStd() override; Pixel_t GetActiveColor() const override; Bool_t IsActive() const override { return fActive; } @@ -308,7 +308,7 @@ class TGListTree : public TGContainer { UInt_t options = 0, Pixel_t back = GetWhitePixel()); TGListTree(TGCanvas *p, UInt_t options, Pixel_t back = GetWhitePixel()); - virtual ~TGListTree(); + ~TGListTree() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleDoubleClick(Event_t *event) override; diff --git a/gui/gui/inc/TGListView.h b/gui/gui/inc/TGListView.h index b8f76ec0bacd6..b10074af0edcb 100644 --- a/gui/gui/inc/TGListView.h +++ b/gui/gui/inc/TGListView.h @@ -79,7 +79,7 @@ class TGLVEntry : public TGFrame { const TString& name, const TString& cname, TGString **subnames = nullptr, UInt_t options = kChildFrame, Pixel_t back = GetWhitePixel()); - virtual ~TGLVEntry(); + ~TGLVEntry() override; virtual void SetViewMode(EListViewMode viewMode); @@ -143,7 +143,7 @@ class TGListView : public TGCanvas { TGListView(const TGWindow *p, UInt_t w, UInt_t h, UInt_t options = kSunkenFrame | kDoubleBorder, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGListView(); + ~TGListView() override; virtual void ResizeColumns(); void Layout() override; @@ -200,7 +200,7 @@ class TGLVContainer : public TGContainer { TGLVContainer(TGCanvas *p, UInt_t options = kSunkenFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGLVContainer(); + ~TGLVContainer() override; TGListView *GetListView() const { return fListView; } diff --git a/gui/gui/inc/TGMdiDecorFrame.h b/gui/gui/inc/TGMdiDecorFrame.h index d3e0801c980e5..d98b60913ed3b 100644 --- a/gui/gui/inc/TGMdiDecorFrame.h +++ b/gui/gui/inc/TGMdiDecorFrame.h @@ -137,7 +137,7 @@ friend class TGMdiTitleBar; public: TGMdiButtons(const TGWindow *p, const TGWindow *titlebar); - virtual ~TGMdiButtons(); + ~TGMdiButtons() override; TGPictureButton *GetButton(Int_t no) const { return fButton[no]; } @@ -161,7 +161,7 @@ friend class TGMdiTitleBar; public: TGMdiTitleIcon(const TGWindow *p, const TGWindow *titlebar, const TGPicture *pic, Int_t w, Int_t h); - virtual ~TGMdiTitleIcon(); + ~TGMdiTitleIcon() override; Bool_t HandleDoubleClick(Event_t *event) override; Bool_t HandleButton(Event_t *event) override; @@ -197,7 +197,7 @@ friend class TGMdiMainFrame; void RemoveFrames(TGMdiTitleIcon *icon, TGMdiButtons *buttons); public: - virtual ~TGMdiTitleBar(); + ~TGMdiTitleBar() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleDoubleClick(Event_t *event) override; @@ -259,7 +259,7 @@ friend class TGMdiMainFrame; TGMdiDecorFrame(TGMdiMainFrame *main, TGMdiFrame *frame, Int_t w, Int_t h, const TGGC *boxGC, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGMdiDecorFrame(); + ~TGMdiDecorFrame() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleConfigureNotify(Event_t *event) override; diff --git a/gui/gui/inc/TGMdiFrame.h b/gui/gui/inc/TGMdiFrame.h index 17a0034814f96..15e255a51bc81 100644 --- a/gui/gui/inc/TGMdiFrame.h +++ b/gui/gui/inc/TGMdiFrame.h @@ -56,7 +56,7 @@ friend class TGMdiDecorFrame; TGMdiFrame(TGMdiMainFrame *main, Int_t w, Int_t h, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGMdiFrame(); + ~TGMdiFrame() override; void Move(Int_t x, Int_t y) override; virtual Bool_t CloseWindow(); //*SIGNAL* diff --git a/gui/gui/inc/TGMdiMainFrame.h b/gui/gui/inc/TGMdiMainFrame.h index 2680fa9feeae5..6dc0114bbcfb8 100644 --- a/gui/gui/inc/TGMdiMainFrame.h +++ b/gui/gui/inc/TGMdiMainFrame.h @@ -166,7 +166,7 @@ friend class TGMdiFrame; TGMdiMainFrame(const TGWindow *p, TGMdiMenuBar *menu, Int_t w, Int_t h, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGMdiMainFrame(); + ~TGMdiMainFrame() override; Bool_t HandleKey(Event_t *event) override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; diff --git a/gui/gui/inc/TGMdiMenu.h b/gui/gui/inc/TGMdiMenu.h index 35abeb73765b7..9dc818f096769 100644 --- a/gui/gui/inc/TGMdiMenu.h +++ b/gui/gui/inc/TGMdiMenu.h @@ -60,7 +60,7 @@ friend class TGMdiMainFrame; public: TGMdiMenuBar(const TGWindow *p, Int_t w = 1, Int_t h = 20); - virtual ~TGMdiMenuBar(); + ~TGMdiMenuBar() override; void AddPopup(TGHotString *s, TGPopupMenu *menu, TGLayoutHints *l); TGMenuBar *GetMenuBar() const { return fBar;} diff --git a/gui/gui/inc/TGMenu.h b/gui/gui/inc/TGMenu.h index d8c2630286b18..bdc7a96f1522d 100644 --- a/gui/gui/inc/TGMenu.h +++ b/gui/gui/inc/TGMenu.h @@ -78,7 +78,7 @@ friend class TGMenuBar; public: TGMenuEntry(): fEntryId(0), fUserData(nullptr), fType(), fStatus(0), fEx(0), fEy(0), fEw(0), fEh(0), fLabel(nullptr), fShortcut(nullptr), fPic(nullptr), fPopup(nullptr) { } - virtual ~TGMenuEntry() { if (fLabel) delete fLabel; if (fShortcut) delete fShortcut; } + ~TGMenuEntry() override { if (fLabel) delete fLabel; if (fShortcut) delete fShortcut; } Int_t GetEntryId() const { return fEntryId; } const char *GetName() const override { return fLabel ? fLabel->GetString() : nullptr; } @@ -160,7 +160,7 @@ friend class TGSplitButton; public: TGPopupMenu(const TGWindow *p = nullptr, UInt_t w = 10, UInt_t h = 10, UInt_t options = 0); - virtual ~TGPopupMenu(); + ~TGPopupMenu() override; virtual void AddEntry(TGHotString *s, Int_t id, void *ud = nullptr, const TGPicture *p = nullptr, TGMenuEntry *before = nullptr); @@ -263,7 +263,7 @@ class TGMenuTitle : public TGFrame { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t options = 0); - virtual ~TGMenuTitle() { if (fLabel) delete fLabel; } + ~TGMenuTitle() override { if (fLabel) delete fLabel; } Pixel_t GetTextColor() const { return fTextColor; } void SetTextColor(Pixel_t col) { fTextColor = col; } @@ -310,7 +310,7 @@ friend class TGPopupMenu; public: TGMenuBar(const TGWindow *p = nullptr, UInt_t w = 60, UInt_t h = 20, UInt_t options = kHorizontalFrame | kRaisedFrame); - virtual ~TGMenuBar(); + ~TGMenuBar() override; virtual void AddPopup(TGHotString *s, TGPopupMenu *menu, TGLayoutHints *l, TGPopupMenu *before = nullptr); diff --git a/gui/gui/inc/TGMimeTypes.h b/gui/gui/inc/TGMimeTypes.h index a3881db0960db..492f3803bffed 100644 --- a/gui/gui/inc/TGMimeTypes.h +++ b/gui/gui/inc/TGMimeTypes.h @@ -40,7 +40,7 @@ friend class TGMimeTypes; public: TGMime() : fReg(nullptr) {} - ~TGMime(); + ~TGMime() override; }; @@ -58,7 +58,7 @@ class TGMimeTypes : public TObject { public: TGMimeTypes(TGClient *client, const char *file); - virtual ~TGMimeTypes(); + ~TGMimeTypes() override; void SaveMimes(); Bool_t HasChanged() const { return fChanged; } diff --git a/gui/gui/inc/TGMsgBox.h b/gui/gui/inc/TGMsgBox.h index a267ed4cbf03f..5ea65a5395fc7 100644 --- a/gui/gui/inc/TGMsgBox.h +++ b/gui/gui/inc/TGMsgBox.h @@ -82,7 +82,7 @@ class TGMsgBox : public TGTransientFrame { Int_t buttons = kMBDismiss, Int_t *ret_code = nullptr, UInt_t options = kVerticalFrame, Int_t text_align = kTextCenterX | kTextCenterY); - virtual ~TGMsgBox(); + ~TGMsgBox() override; void CloseWindow() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; diff --git a/gui/gui/inc/TGNumberEntry.h b/gui/gui/inc/TGNumberEntry.h index e8230c441499a..471fbd7addd70 100644 --- a/gui/gui/inc/TGNumberEntry.h +++ b/gui/gui/inc/TGNumberEntry.h @@ -171,7 +171,7 @@ class TGNumberEntry : public TGCompositeFrame, public TGWidget, EAttribute attr = kNEAAnyNumber, ELimit limits = kNELNoLimits, Double_t min = 0, Double_t max = 1); - virtual ~TGNumberEntry(); + ~TGNumberEntry() override; virtual void SetNumber(Double_t val, Bool_t emit = kTRUE) { // Set the numeric value (floating point representation) diff --git a/gui/gui/inc/TGObject.h b/gui/gui/inc/TGObject.h index 3ac45c7b5a888..872a5866ab601 100644 --- a/gui/gui/inc/TGObject.h +++ b/gui/gui/inc/TGObject.h @@ -37,7 +37,7 @@ class TGObject : public TObject { public: TGObject(): fId(0), fClient(nullptr) { } TGObject(const TGObject& tgo): TObject(tgo), fId(tgo.fId), fClient(tgo.fClient) { } - virtual ~TGObject(); + ~TGObject() override; Handle_t GetId() const { return fId; } TGClient *GetClient() const { return fClient; } ULong_t Hash() const override { return (ULong_t) fId >> 0; } diff --git a/gui/gui/inc/TGPack.h b/gui/gui/inc/TGPack.h index ee0b2e1dc5848..8a234904c33d1 100644 --- a/gui/gui/inc/TGPack.h +++ b/gui/gui/inc/TGPack.h @@ -72,7 +72,7 @@ class TGPack : public TGCompositeFrame TGPack(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = 0, Pixel_t back = GetDefaultFrameBackground()); TGPack(TGClient *c, Window_t id, const TGWindow *parent = nullptr); - virtual ~TGPack(); + ~TGPack() override; virtual void AddFrameWithWeight(TGFrame *f, TGLayoutHints* l, Float_t w); void AddFrame(TGFrame *f, TGLayoutHints* l = nullptr) override; diff --git a/gui/gui/inc/TGPicture.h b/gui/gui/inc/TGPicture.h index 504c68a6da550..3ba261cddd621 100644 --- a/gui/gui/inc/TGPicture.h +++ b/gui/gui/inc/TGPicture.h @@ -46,7 +46,7 @@ friend class TGPicturePool; void Draw(Option_t * = "") override { MayNotUse("Draw(Option_t*)"); } public: - virtual ~TGPicture(); + ~TGPicture() override; const char *GetName() const override { return fName.Data(); } UInt_t GetWidth() const { return fAttributes.fWidth; } @@ -80,7 +80,7 @@ class TGSelectedPicture : public TGPicture { public: TGSelectedPicture(const TGClient *client, const TGPicture *p); - virtual ~TGSelectedPicture(); + ~TGSelectedPicture() override; ClassDefOverride(TGSelectedPicture,0) // Selected looking picture }; @@ -99,7 +99,7 @@ class TGPicturePool : public TObject { public: TGPicturePool(const TGClient *client, const char *path): fClient(client), fPath(path), fPicList(nullptr) { } - virtual ~TGPicturePool(); + ~TGPicturePool() override; const char *GetPath() const { return fPath; } const TGPicture *GetPicture(const char *name); diff --git a/gui/gui/inc/TGProgressBar.h b/gui/gui/inc/TGProgressBar.h index 190fc1127f532..036db4d5d54ef 100644 --- a/gui/gui/inc/TGProgressBar.h +++ b/gui/gui/inc/TGProgressBar.h @@ -40,7 +40,7 @@ class TGProgressBar : public TGFrame { GContext_t fNormGC; ///< text drawing graphics context FontStruct_t fFontStruct; ///< font used to draw position text - virtual void DoRedraw() override = 0; + void DoRedraw() override = 0; static const TGFont *fgDefaultFont; static TGGC *fgDefaultGC; @@ -55,7 +55,7 @@ class TGProgressBar : public TGFrame { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kDoubleBorder | kSunkenFrame); - virtual ~TGProgressBar() { } + ~TGProgressBar() override { } Float_t GetMin() const { return fMin; } Float_t GetMax() const { return fMax; } @@ -105,7 +105,7 @@ class TGHProgressBar : public TGProgressBar { FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kDoubleBorder | kSunkenFrame); TGHProgressBar(const TGWindow *p, EBarType type, UInt_t w); - virtual ~TGHProgressBar() { } + ~TGHProgressBar() override { } TGDimension GetDefaultSize() const override { return TGDimension(fWidth, fBarWidth); } @@ -133,7 +133,7 @@ class TGVProgressBar : public TGProgressBar { FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kDoubleBorder | kSunkenFrame); TGVProgressBar(const TGWindow *p, EBarType type, UInt_t h); - virtual ~TGVProgressBar() { } + ~TGVProgressBar() override { } TGDimension GetDefaultSize() const override { return TGDimension(fBarWidth, fHeight); } diff --git a/gui/gui/inc/TGResourcePool.h b/gui/gui/inc/TGResourcePool.h index 1a4991af38bcd..c60525c2d03cb 100644 --- a/gui/gui/inc/TGResourcePool.h +++ b/gui/gui/inc/TGResourcePool.h @@ -88,7 +88,7 @@ class TGResourcePool : public TGObject { public: TGResourcePool(TGClient *client); - virtual ~TGResourcePool(); + ~TGResourcePool() override; TGGCPool *GetGCPool() const { return fGCPool; } TGFontPool *GetFontPool() const { return fFontPool; } diff --git a/gui/gui/inc/TGScrollBar.h b/gui/gui/inc/TGScrollBar.h index 48a9557e04ae8..ca824601f60c3 100644 --- a/gui/gui/inc/TGScrollBar.h +++ b/gui/gui/inc/TGScrollBar.h @@ -46,7 +46,7 @@ class TGScrollBarElement : public TGFrame { UInt_t w = 1, UInt_t h = 1, UInt_t options = kRaisedFrame | kDoubleBorder, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGScrollBarElement(); + ~TGScrollBarElement() override; virtual void SetState(Int_t state); void DrawBorder() override; @@ -96,7 +96,7 @@ class TGScrollBar : public TGFrame, public TGWidget { TGScrollBar(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGScrollBar(); + ~TGScrollBar() override; void GrabPointer(Bool_t grab) { fGrabPointer = grab; } @@ -145,7 +145,7 @@ class TGHScrollBar : public TGScrollBar { TGHScrollBar(const TGWindow *p = nullptr, UInt_t w = 4, UInt_t h = 2, UInt_t options = kHorizontalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGHScrollBar() { } + ~TGHScrollBar() override { } Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; @@ -168,7 +168,7 @@ class TGVScrollBar : public TGScrollBar { TGVScrollBar(const TGWindow *p = nullptr, UInt_t w = 2, UInt_t h = 4, UInt_t options = kVerticalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGVScrollBar() { } + ~TGVScrollBar() override { } Bool_t HandleButton(Event_t *event) override; Bool_t HandleMotion(Event_t *event) override; diff --git a/gui/gui/inc/TGShapedFrame.h b/gui/gui/inc/TGShapedFrame.h index 69c09b269c88b..7e189d2e29e3e 100644 --- a/gui/gui/inc/TGShapedFrame.h +++ b/gui/gui/inc/TGShapedFrame.h @@ -32,7 +32,7 @@ class TGShapedFrame : public TGCompositeFrame { public: TGShapedFrame(const char *fname = nullptr, const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = 0); - virtual ~TGShapedFrame(); + ~TGShapedFrame() override; const TGPicture GetPicture() const { return *fBgnd; } TImage GetImage() const { return *fImage; } diff --git a/gui/gui/inc/TGShutter.h b/gui/gui/inc/TGShutter.h index f04bc1f0090fa..b22581bf55960 100644 --- a/gui/gui/inc/TGShutter.h +++ b/gui/gui/inc/TGShutter.h @@ -39,7 +39,7 @@ friend class TGShutter; public: TGShutterItem(const TGWindow *p = nullptr, TGHotString *s = nullptr, Int_t id = -1, UInt_t options = 0); - virtual ~TGShutterItem(); + ~TGShutterItem() override; TGButton *GetButton() const { return fButton; } TGFrame *GetContainer() const { return fCanvas->GetContainer(); } @@ -71,7 +71,7 @@ class TGShutter : public TGCompositeFrame { public: TGShutter(const TGWindow *p = nullptr, UInt_t options = kSunkenFrame); - virtual ~TGShutter(); + ~TGShutter() override; virtual void AddItem(TGShutterItem *item); virtual void RemoveItem(const char *name); diff --git a/gui/gui/inc/TGSimpleTable.h b/gui/gui/inc/TGSimpleTable.h index 680c65729f250..2e4747ffc07fd 100644 --- a/gui/gui/inc/TGSimpleTable.h +++ b/gui/gui/inc/TGSimpleTable.h @@ -18,7 +18,7 @@ class TGSimpleTable : public TGTable { public: TGSimpleTable(TGWindow *p, Int_t id, Double_t **data, UInt_t nrows, UInt_t ncolumns); - virtual ~TGSimpleTable(); + ~TGSimpleTable() override; ClassDefOverride(TGSimpleTable, 0) // A simple table that owns it's interface. }; diff --git a/gui/gui/inc/TGSimpleTableInterface.h b/gui/gui/inc/TGSimpleTableInterface.h index dacbdb4c232ce..b25c291d14931 100644 --- a/gui/gui/inc/TGSimpleTableInterface.h +++ b/gui/gui/inc/TGSimpleTableInterface.h @@ -28,7 +28,7 @@ class TGSimpleTableInterface : public TVirtualTableInterface { public: TGSimpleTableInterface(Double_t **data, UInt_t nrows = 2, UInt_t ncolumns = 2); - virtual ~TGSimpleTableInterface(); + ~TGSimpleTableInterface() override; Double_t GetValue(UInt_t row, UInt_t column) override; const char *GetValueAsString(UInt_t row, UInt_t column) override; diff --git a/gui/gui/inc/TGSlider.h b/gui/gui/inc/TGSlider.h index 68d276c8b9d7f..568f46d363452 100644 --- a/gui/gui/inc/TGSlider.h +++ b/gui/gui/inc/TGSlider.h @@ -63,7 +63,7 @@ class TGSlider : public TGFrame, public TGWidget { UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGSlider() {} + ~TGSlider() override {} Bool_t HandleButton(Event_t *event) override = 0; Bool_t HandleConfigureNotify(Event_t* event) override = 0; @@ -101,7 +101,7 @@ class TGVSlider : public TGSlider { UInt_t type = kSlider1 | kScaleBoth, Int_t id = -1, UInt_t options = kVerticalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGVSlider(); + ~TGVSlider() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleConfigureNotify(Event_t* event) override; @@ -128,7 +128,7 @@ class TGHSlider : public TGSlider { UInt_t type = kSlider1 | kScaleBoth, Int_t id = -1, UInt_t options = kHorizontalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGHSlider(); + ~TGHSlider() override; Bool_t HandleButton(Event_t *event) override; Bool_t HandleConfigureNotify(Event_t* event) override; diff --git a/gui/gui/inc/TGSpeedo.h b/gui/gui/inc/TGSpeedo.h index 0233c629554aa..f407be182f3f3 100644 --- a/gui/gui/inc/TGSpeedo.h +++ b/gui/gui/inc/TGSpeedo.h @@ -59,7 +59,7 @@ class TGSpeedo : public TGFrame, public TGWidget { TGSpeedo(const TGWindow *p, Float_t smin, Float_t smax, const char *lbl1 = "", const char *lbl2 = "", const char *dsp1 = "", const char *dsp2 = "", int id = -1); - virtual ~TGSpeedo(); + ~TGSpeedo() override; TGDimension GetDefaultSize() const override; Bool_t HandleButton(Event_t *event) override; diff --git a/gui/gui/inc/TGSplitFrame.h b/gui/gui/inc/TGSplitFrame.h index 3b33a02beb05e..d387487b9f9e8 100644 --- a/gui/gui/inc/TGSplitFrame.h +++ b/gui/gui/inc/TGSplitFrame.h @@ -34,7 +34,7 @@ class TGRectMap : public TObject { // constructors TGRectMap(Int_t rx, Int_t ry, UInt_t rw, UInt_t rh): fX(rx), fY(ry), fW(rw), fH(rh) {} - virtual ~TGRectMap() {} + ~TGRectMap() override {} // methods Bool_t Contains(Int_t px, Int_t py) const @@ -59,7 +59,7 @@ class TGSplitTool : public TGCompositeFrame { public: TGSplitTool(const TGWindow *p = nullptr, const TGFrame *f = nullptr); - virtual ~TGSplitTool(); + ~TGSplitTool() override; void AddRectangle(TGFrame *frm, Int_t x, Int_t y, Int_t w, Int_t h); void DoRedraw() override; @@ -93,7 +93,7 @@ class TGSplitFrame : public TGCompositeFrame { public: TGSplitFrame(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = 0); - virtual ~TGSplitFrame(); + ~TGSplitFrame() override; void AddFrame(TGFrame *f, TGLayoutHints *l = nullptr) override; void Cleanup() override; diff --git a/gui/gui/inc/TGSplitter.h b/gui/gui/inc/TGSplitter.h index f7d6c804d2cea..d41357dac6c99 100644 --- a/gui/gui/inc/TGSplitter.h +++ b/gui/gui/inc/TGSplitter.h @@ -32,13 +32,13 @@ class TGSplitter : public TGFrame { TGSplitter(const TGWindow *p = nullptr, UInt_t w = 2, UInt_t h = 4, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGSplitter() { } + ~TGSplitter() override { } virtual void SetFrame(TGFrame *frame, Bool_t prev) = 0; - virtual Bool_t HandleButton(Event_t *event) override = 0; - virtual Bool_t HandleMotion(Event_t *event) override = 0; - virtual Bool_t HandleCrossing(Event_t *event) override = 0; + Bool_t HandleButton(Event_t *event) override = 0; + Bool_t HandleMotion(Event_t *event) override = 0; + Bool_t HandleCrossing(Event_t *event) override = 0; void DragStarted(); // *SIGNAL* void Moved(Int_t delta); // *SIGNAL* @@ -70,7 +70,7 @@ class TGVSplitter : public TGSplitter { UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); TGVSplitter(const TGWindow *p, UInt_t w, UInt_t h, Bool_t external); - virtual ~TGVSplitter(); + ~TGVSplitter() override; void DrawBorder() override; void SetFrame(TGFrame *frame, Bool_t left) override; @@ -107,7 +107,7 @@ class TGHSplitter : public TGSplitter { UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); TGHSplitter(const TGWindow *p, UInt_t w, UInt_t h, Bool_t external); - virtual ~TGHSplitter(); + ~TGHSplitter() override; void DrawBorder() override; void SetFrame(TGFrame *frame, Bool_t above) override; @@ -133,7 +133,7 @@ class TGVFileSplitter : public TGVSplitter { TGVFileSplitter(const TGWindow *p = nullptr, UInt_t w = 4, UInt_t h = 4, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGVFileSplitter(); + ~TGVFileSplitter() override; Bool_t HandleDoubleClick(Event_t *) override; Bool_t HandleButton(Event_t *event) override; diff --git a/gui/gui/inc/TGStatusBar.h b/gui/gui/inc/TGStatusBar.h index 684085c23a8cb..2a174177aa745 100644 --- a/gui/gui/inc/TGStatusBar.h +++ b/gui/gui/inc/TGStatusBar.h @@ -46,7 +46,7 @@ friend class TGStatusBarPart; TGStatusBar(const TGWindow *p = nullptr, UInt_t w = 4, UInt_t h = 2, UInt_t options = kSunkenFrame | kHorizontalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGStatusBar(); + ~TGStatusBar() override; void DrawBorder() override; virtual void SetText(TGString *text, Int_t partidx = 0); diff --git a/gui/gui/inc/TGString.h b/gui/gui/inc/TGString.h index d5db46433c99c..2c3de38b60bb8 100644 --- a/gui/gui/inc/TGString.h +++ b/gui/gui/inc/TGString.h @@ -24,7 +24,7 @@ class TGString : public TString { TGString(const char *s) : TString(s) { } TGString(Int_t number) : TString() { *this += number; } TGString(const TGString *s); - virtual ~TGString() {} + ~TGString() override {} Int_t GetLength() const { return Length(); } const char *GetString() const { return Data(); } diff --git a/gui/gui/inc/TGTab.h b/gui/gui/inc/TGTab.h index 9a7c1aa6fcb89..ab9063a5bd3dd 100644 --- a/gui/gui/inc/TGTab.h +++ b/gui/gui/inc/TGTab.h @@ -72,7 +72,7 @@ class TGTab : public TGCompositeFrame, public TGWidget { FontStruct_t font = GetDefaultFontStruct(), UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGTab(); + ~TGTab() override; virtual TGCompositeFrame *AddTab(TGString *text); virtual TGCompositeFrame *AddTab(const char *text); @@ -138,7 +138,7 @@ class TGTabElement : public TGFrame { FontStruct_t font = TGTab::GetDefaultFontStruct(), UInt_t options = kRaisedFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGTabElement(); + ~TGTabElement() override; void DrawBorder() override; TGDimension GetDefaultSize() const override; diff --git a/gui/gui/inc/TGTable.h b/gui/gui/inc/TGTable.h index 0c73aa317c9a8..0e45fae5af9a0 100644 --- a/gui/gui/inc/TGTable.h +++ b/gui/gui/inc/TGTable.h @@ -126,7 +126,7 @@ class TGTable : public TGCompositeFrame, public TGWidget { TGTable(const TGWindow *p = nullptr, Int_t id = 0, TVirtualTableInterface *interface = nullptr, UInt_t nrows = 50, UInt_t ncolumns = 20); - virtual ~TGTable(); + ~TGTable() override; virtual TObjArray *GetRow(UInt_t row); virtual TObjArray *GetColumn(UInt_t columns); diff --git a/gui/gui/inc/TGTableCell.h b/gui/gui/inc/TGTableCell.h index 6e914019956d4..2dfd9f6e043a2 100644 --- a/gui/gui/inc/TGTableCell.h +++ b/gui/gui/inc/TGTableCell.h @@ -69,7 +69,7 @@ friend class TGTable; FontStruct_t font = GetDefaultFontStruct(), UInt_t option = 0, Bool_t resize = kTRUE); - virtual ~TGTableCell(); + ~TGTableCell() override; void DrawCopy(Handle_t id, Int_t x, Int_t y) override; diff --git a/gui/gui/inc/TGTableContainer.h b/gui/gui/inc/TGTableContainer.h index 3c1c4438ed5b9..e5b5036831b9c 100644 --- a/gui/gui/inc/TGTableContainer.h +++ b/gui/gui/inc/TGTableContainer.h @@ -22,7 +22,7 @@ class TGTableFrame : public TQObject { public: TGTableFrame(const TGWindow *p, UInt_t nrows, UInt_t ncolumns); - virtual ~TGTableFrame() { delete fFrame; } + ~TGTableFrame() override { delete fFrame; } TGFrame *GetFrame() const { return fFrame; } @@ -44,7 +44,7 @@ class TGTableHeaderFrame: public TGCompositeFrame { TGTableHeaderFrame(const TGWindow *p, TGTable *table = nullptr, UInt_t w = 1, UInt_t h = 1, EHeaderType type = kColumnHeader, UInt_t option = 0); - ~TGTableHeaderFrame() {} + ~TGTableHeaderFrame() override {} virtual void DrawRegion(Int_t x, Int_t y, UInt_t w, UInt_t h); diff --git a/gui/gui/inc/TGTableHeader.h b/gui/gui/inc/TGTableHeader.h index 1d5514c7c5419..3c5b1d5ff59f0 100644 --- a/gui/gui/inc/TGTableHeader.h +++ b/gui/gui/inc/TGTableHeader.h @@ -46,7 +46,7 @@ class TGTableHeader : public TGTableCell { GContext_t norm = GetDefaultGC()(), FontStruct_t font = GetDefaultFontStruct(), UInt_t option = 0); - virtual ~TGTableHeader(); + ~TGTableHeader() override; void SetWidth(UInt_t width) override; void SetHeight(UInt_t height) override; diff --git a/gui/gui/inc/TGTableLayout.h b/gui/gui/inc/TGTableLayout.h index 40ef6752d4480..2fbd504883b49 100644 --- a/gui/gui/inc/TGTableLayout.h +++ b/gui/gui/inc/TGTableLayout.h @@ -46,7 +46,7 @@ class TGTableLayoutHints : public TGLayoutHints { fAttachRight(attach_right), fAttachTop(attach_top), fAttachBottom(attach_bottom) { } - virtual ~TGTableLayoutHints() { } + ~TGTableLayoutHints() override { } UInt_t GetAttachLeft() const { return fAttachLeft; } UInt_t GetAttachRight() const { return fAttachRight; } @@ -103,7 +103,7 @@ class TGTableLayout : public TGLayoutManager { TGTableLayout(TGCompositeFrame *main, UInt_t nrows, UInt_t ncols, Bool_t homogeneous = kFALSE, Int_t sep = 0, Int_t hints = 0); - virtual ~TGTableLayout(); + ~TGTableLayout() override; void Layout() override; TGDimension GetDefaultSize() const override; // return sum of all child sizes diff --git a/gui/gui/inc/TGTextEdit.h b/gui/gui/inc/TGTextEdit.h index 46c3c7428ac0a..8e3726513f6a2 100644 --- a/gui/gui/inc/TGTextEdit.h +++ b/gui/gui/inc/TGTextEdit.h @@ -70,7 +70,7 @@ class TGTextEdit : public TGTextView { TGTextEdit(const TGWindow *parent, UInt_t w, UInt_t h, const char *string, Int_t id = -1, UInt_t sboptions = 0, Pixel_t back = GetWhitePixel()); - virtual ~TGTextEdit(); + ~TGTextEdit() override; virtual Bool_t SaveFile(const char *fname, Bool_t saveas = kFALSE); void Clear(Option_t * = "") override; diff --git a/gui/gui/inc/TGTextEditDialogs.h b/gui/gui/inc/TGTextEditDialogs.h index 86c52020f6e4e..34a11c43275a6 100644 --- a/gui/gui/inc/TGTextEditDialogs.h +++ b/gui/gui/inc/TGTextEditDialogs.h @@ -60,7 +60,7 @@ class TGSearchDialog : public TGTransientFrame { TGSearchDialog(const TGWindow *p = nullptr, const TGWindow *main = nullptr, UInt_t w = 1, UInt_t h = 1, TGSearchType *sstruct = nullptr, Int_t *ret_code = nullptr, UInt_t options = kVerticalFrame); - virtual ~TGSearchDialog(); + ~TGSearchDialog() override; void CloseWindow() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; @@ -96,7 +96,7 @@ class TGPrintDialog : public TGTransientFrame { TGPrintDialog(const TGWindow *p = nullptr, const TGWindow *main = nullptr, UInt_t w = 1, UInt_t h = 1, char **printerName = nullptr, char **printProg = nullptr, Int_t *ret_code = nullptr, UInt_t options = kVerticalFrame); - virtual ~TGPrintDialog(); + ~TGPrintDialog() override; void CloseWindow() override; virtual void GetPrinters(); @@ -121,7 +121,7 @@ class TGGotoDialog : public TGTransientFrame { public: TGGotoDialog(const TGWindow *p = nullptr, const TGWindow *main = nullptr, UInt_t w = 1, UInt_t h = 1, Long_t *ret_code = nullptr, UInt_t options = kVerticalFrame); - virtual ~TGGotoDialog(); + ~TGGotoDialog() override; void CloseWindow() override; Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; diff --git a/gui/gui/inc/TGTextEditor.h b/gui/gui/inc/TGTextEditor.h index 57a7ac44807e3..a320648643948 100644 --- a/gui/gui/inc/TGTextEditor.h +++ b/gui/gui/inc/TGTextEditor.h @@ -61,7 +61,7 @@ class TGTextEditor : public TGMainFrame { UInt_t w = 900, UInt_t h = 600); TGTextEditor(TMacro *macro, const TGWindow *p = nullptr, UInt_t w = 0, UInt_t h = 0); - virtual ~TGTextEditor(); + ~TGTextEditor() override; void ClearText(); Bool_t LoadBuffer(const char *buf) { return fTextEdit->LoadBuffer(buf); } diff --git a/gui/gui/inc/TGTextEntry.h b/gui/gui/inc/TGTextEntry.h index 9db9bd9c63f07..34c97381819cf 100644 --- a/gui/gui/inc/TGTextEntry.h +++ b/gui/gui/inc/TGTextEntry.h @@ -91,7 +91,7 @@ class TGTextEntry : public TGFrame, public TGWidget { TGTextEntry(const TGWindow *parent = nullptr, const char *text = nullptr, Int_t id = -1); TGTextEntry(const TString &contents, const TGWindow *parent, Int_t id = -1); - virtual ~TGTextEntry(); + ~TGTextEntry() override; TGDimension GetDefaultSize() const override; virtual void SetDefaultSize(UInt_t w, UInt_t h); diff --git a/gui/gui/inc/TGTextView.h b/gui/gui/inc/TGTextView.h index cdfa15a73d807..811916998b2aa 100644 --- a/gui/gui/inc/TGTextView.h +++ b/gui/gui/inc/TGTextView.h @@ -72,7 +72,7 @@ class TGTextView : public TGView { TGTextView(const TGWindow *parent, UInt_t w, UInt_t h, const char *string, Int_t id = -1, UInt_t sboptions = 0, Pixel_t back = GetWhitePixel()); - virtual ~TGTextView(); + ~TGTextView() override; virtual Bool_t IsSaved() { fIsSaved = fText->IsSaved(); return fIsSaved;} virtual Long_t ToObjXCoord(Long_t xCoord, Long_t line); diff --git a/gui/gui/inc/TGTextViewStream.h b/gui/gui/inc/TGTextViewStream.h index 67a0dc0372c20..a8573947be1b2 100644 --- a/gui/gui/inc/TGTextViewStream.h +++ b/gui/gui/inc/TGTextViewStream.h @@ -34,7 +34,7 @@ class TGTextViewStreamBuf : public std::streambuf public: TGTextViewStreamBuf(TGTextView *textview); - virtual ~TGTextViewStreamBuf() {} + ~TGTextViewStreamBuf() override {} ClassDef(TGTextViewStreamBuf, 0) // Specialization of std::streambuf }; @@ -54,7 +54,7 @@ class TGTextViewostream : public TGTextView, public std::ostream TGTextViewostream(const TGWindow *parent, UInt_t w, UInt_t h, const char *string, Int_t id, UInt_t sboptions, ULong_t back); - virtual ~TGTextViewostream() {} + ~TGTextViewostream() override {} ClassDefOverride(TGTextViewostream, 0) // Specialization of TGTextView and std::ostream }; diff --git a/gui/gui/inc/TGToolBar.h b/gui/gui/inc/TGToolBar.h index 86bc22da72e0d..b5cb58dddf000 100644 --- a/gui/gui/inc/TGToolBar.h +++ b/gui/gui/inc/TGToolBar.h @@ -45,7 +45,7 @@ class TGToolBar : public TGCompositeFrame { TGToolBar(const TGWindow *p = nullptr, UInt_t w = 1, UInt_t h = 1, UInt_t options = kHorizontalFrame, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TGToolBar(); + ~TGToolBar() override; virtual TGButton *AddButton(const TGWindow *w, ToolBarData_t *button, Int_t spacing = 0); virtual TGButton *AddButton(const TGWindow *w, TGPictureButton *button, Int_t spacing = 0); diff --git a/gui/gui/inc/TGToolTip.h b/gui/gui/inc/TGToolTip.h index 648a6efb07bf4..0261dad528c17 100644 --- a/gui/gui/inc/TGToolTip.h +++ b/gui/gui/inc/TGToolTip.h @@ -41,7 +41,7 @@ class TGToolTip : public TGCompositeFrame { TGToolTip(const TGWindow *p, const TBox *b, const char *text, Long_t delayms); TGToolTip(const TBox *b, const char *text, Long_t delayms); TGToolTip(Int_t x, Int_t y, const char *text, Long_t delayms); - virtual ~TGToolTip(); + ~TGToolTip() override; void DrawBorder() override; diff --git a/gui/gui/inc/TGTripleSlider.h b/gui/gui/inc/TGTripleSlider.h index 9ac1fbcad7c91..ecc8e3f8a2913 100644 --- a/gui/gui/inc/TGTripleSlider.h +++ b/gui/gui/inc/TGTripleSlider.h @@ -38,7 +38,7 @@ class TGTripleVSlider : public TGDoubleVSlider { Bool_t constrained = kTRUE, Bool_t relative = kFALSE); - virtual ~TGTripleVSlider(); + ~TGTripleVSlider() override; virtual void PointerPositionChanged() { Emit("PointerPositionChanged()"); } //*SIGNAL* virtual void DrawPointer(); @@ -91,7 +91,7 @@ class TGTripleHSlider : public TGDoubleHSlider { Bool_t constrained = kTRUE, Bool_t relative = kFALSE); - virtual ~TGTripleHSlider(); + ~TGTripleHSlider() override; virtual void PointerPositionChanged() { Emit("PointerPositionChanged()"); } //*SIGNAL* virtual void DrawPointer(); diff --git a/gui/gui/inc/TGView.h b/gui/gui/inc/TGView.h index e4c695f3a2cc6..1b81e841ce757 100644 --- a/gui/gui/inc/TGView.h +++ b/gui/gui/inc/TGView.h @@ -61,7 +61,7 @@ friend class TGViewFrame; UInt_t sboptions = 0, Pixel_t back = GetWhitePixel()); - virtual ~TGView(); + ~TGView() override; TGViewFrame *GetCanvas() const { return fCanvas; } diff --git a/gui/gui/inc/TGWindow.h b/gui/gui/inc/TGWindow.h index 4abc921553f61..cc1105bd29329 100644 --- a/gui/gui/inc/TGWindow.h +++ b/gui/gui/inc/TGWindow.h @@ -78,7 +78,7 @@ friend class TGClient; UInt_t wtype = 0); TGWindow(TGClient *c, Window_t id, const TGWindow *parent = nullptr); - virtual ~TGWindow(); + ~TGWindow() override; const TGWindow *GetParent() const { return fParent; } virtual const TGWindow *GetMainFrame() const; @@ -142,7 +142,7 @@ class TGUnknownWindowHandler : public TObject { public: TGUnknownWindowHandler() {} - virtual ~TGUnknownWindowHandler() {} + ~TGUnknownWindowHandler() override {} virtual Bool_t HandleEvent(Event_t *) = 0; diff --git a/gui/gui/inc/TGuiBuilder.h b/gui/gui/inc/TGuiBuilder.h index c9691b11ca1d2..9d30540d4a77e 100644 --- a/gui/gui/inc/TGuiBuilder.h +++ b/gui/gui/inc/TGuiBuilder.h @@ -33,7 +33,7 @@ class TGuiBldAction : public TNamed { TGuiBldAction(const char *name = nullptr, const char *title = nullptr, Int_t type = kGuiBldCtor, TGLayoutHints *hints = nullptr); - virtual ~TGuiBldAction(); + ~TGuiBldAction() override; ClassDefOverride(TGuiBldAction,0) // gui builder action }; diff --git a/gui/gui/inc/TRootApplication.h b/gui/gui/inc/TRootApplication.h index 379b6a3693c2d..07af76d9d3323 100644 --- a/gui/gui/inc/TRootApplication.h +++ b/gui/gui/inc/TRootApplication.h @@ -31,7 +31,7 @@ class TRootApplication : public TApplicationImp { public: TRootApplication(const char *appClassName, Int_t *argc, char **argv); - virtual ~TRootApplication(); + ~TRootApplication() override; TGClient *Client() const { return fClient; } diff --git a/gui/gui/inc/TRootBrowser.h b/gui/gui/inc/TRootBrowser.h index a42175b07b30e..580e504b03743 100644 --- a/gui/gui/inc/TRootBrowser.h +++ b/gui/gui/inc/TRootBrowser.h @@ -42,7 +42,7 @@ class TBrowserPlugin : public TNamed TBrowserPlugin(const char *name, const char *cmd = "", Int_t tab = 1, Int_t sub = -1) : TNamed(name, cmd), fTab(tab), fSubTab(sub), fCommand(cmd) { } - virtual ~TBrowserPlugin() {} + ~TBrowserPlugin() override {} void SetTab(Int_t tab) { fTab = tab; } void SetSubTab(Int_t sub) { fSubTab = sub; } @@ -123,7 +123,7 @@ class TRootBrowser : public TGMainFrame, public TBrowserImp { TRootBrowser(TBrowser *b = nullptr, const char *name = "ROOT Browser", UInt_t width = 800, UInt_t height = 500, Option_t *opt = "", Bool_t initshow = kTRUE); TRootBrowser(TBrowser *b, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height, Option_t *opt = "", Bool_t initshow = kTRUE); - virtual ~TRootBrowser(); + ~TRootBrowser() override; void InitPlugins(Option_t *opt=""); @@ -146,6 +146,7 @@ class TRootBrowser : public TGMainFrame, public TBrowserImp { void HandleMenu(Int_t id); void RecursiveReparent(TGPopupMenu *popup); void RemoveTab(Int_t pos, Int_t subpos); + TBrowserImp *GetActBrowser() const { return fActBrowser; } void SetActBrowser(TBrowserImp *b) { fActBrowser = b; } void ShowMenu(TGCompositeFrame *menu); void StartEmbedding(Int_t pos = kRight, Int_t subpos = -1) override; diff --git a/gui/gui/inc/TRootBrowserLite.h b/gui/gui/inc/TRootBrowserLite.h index f76622b1a527f..ba80c145c83ca 100644 --- a/gui/gui/inc/TRootBrowserLite.h +++ b/gui/gui/inc/TRootBrowserLite.h @@ -114,7 +114,7 @@ friend class TRootIconBox; public: TRootBrowserLite(TBrowser *b = nullptr, const char *title = "ROOT Browser", UInt_t width = 800, UInt_t height = 500); TRootBrowserLite(TBrowser *b, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height); - virtual ~TRootBrowserLite(); + ~TRootBrowserLite() override; void Add(TObject *obj, const char *name = nullptr, Int_t check = -1) override; virtual void AddToBox(TObject *obj, const char *name); diff --git a/gui/gui/inc/TRootCanvas.h b/gui/gui/inc/TRootCanvas.h index 883b1eeb235de..60f70d9663593 100644 --- a/gui/gui/inc/TRootCanvas.h +++ b/gui/gui/inc/TRootCanvas.h @@ -102,7 +102,7 @@ friend class TRootContainer; public: TRootCanvas(TCanvas *c = nullptr, const char *name = "ROOT Canvas", UInt_t width = 500, UInt_t height = 300); TRootCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height); - virtual ~TRootCanvas(); + ~TRootCanvas() override; void AdjustSize(); void Close() override; diff --git a/gui/gui/inc/TRootContextMenu.h b/gui/gui/inc/TRootContextMenu.h index 4f2bc811bbdd4..c7056b85a1c81 100644 --- a/gui/gui/inc/TRootContextMenu.h +++ b/gui/gui/inc/TRootContextMenu.h @@ -31,7 +31,7 @@ class TRootContextMenu : public TGPopupMenu, public TContextMenuImp { public: TRootContextMenu(TContextMenu *c = nullptr, const char *name = "ROOT Context Menu"); - virtual ~TRootContextMenu(); + ~TRootContextMenu() override; void DisplayPopup(Int_t x, Int_t y) override; void Dialog(TObject *object, TMethod *method) override; diff --git a/gui/gui/inc/TRootControlBar.h b/gui/gui/inc/TRootControlBar.h index 2f8050b3681cd..5d147ded50266 100644 --- a/gui/gui/inc/TRootControlBar.h +++ b/gui/gui/inc/TRootControlBar.h @@ -30,7 +30,7 @@ class TRootControlBar : public TGMainFrame, public TControlBarImp { public: TRootControlBar(TControlBar *c = nullptr, const char *title = "ROOT Control Bar", Int_t x = -999, Int_t y = -999); - virtual ~TRootControlBar(); + ~TRootControlBar() override; void Create() override; void Hide() override; diff --git a/gui/gui/inc/TRootDialog.h b/gui/gui/inc/TRootDialog.h index 8556a547ed477..95678b7ec76f6 100644 --- a/gui/gui/inc/TRootDialog.h +++ b/gui/gui/inc/TRootDialog.h @@ -35,7 +35,7 @@ class TRootDialog : public TGTransientFrame { const char *title = "ROOT Dialog", Bool_t okB = kTRUE, Bool_t cancelB = kTRUE, Bool_t applyB = kFALSE, Bool_t helpB = kTRUE); - virtual ~TRootDialog(); + ~TRootDialog() override; virtual void Add(const char *argname, const char *value, const char *type); //virtual void Add(TGComboBox *optionSel); diff --git a/gui/gui/inc/TRootEmbeddedCanvas.h b/gui/gui/inc/TRootEmbeddedCanvas.h index 0110971ac4c54..eb9b36a426025 100644 --- a/gui/gui/inc/TRootEmbeddedCanvas.h +++ b/gui/gui/inc/TRootEmbeddedCanvas.h @@ -49,7 +49,7 @@ friend class TRootEmbeddedContainer; TRootEmbeddedCanvas(const char *name = nullptr, const TGWindow *p = nullptr, UInt_t w = 10, UInt_t h = 10, UInt_t options = kSunkenFrame | kDoubleBorder, Pixel_t back = GetDefaultFrameBackground()); - virtual ~TRootEmbeddedCanvas(); + ~TRootEmbeddedCanvas() override; void AdoptCanvas(TCanvas *c); TCanvas *GetCanvas() const { return fCanvas; } diff --git a/gui/gui/inc/TRootGuiFactory.h b/gui/gui/inc/TRootGuiFactory.h index 6433cd237ebee..6f15a41a0c8ab 100644 --- a/gui/gui/inc/TRootGuiFactory.h +++ b/gui/gui/inc/TRootGuiFactory.h @@ -26,9 +26,12 @@ class TControlBar; class TRootGuiFactory : public TGuiFactory { +protected: + void ShowWebCanvasWarning(); + public: TRootGuiFactory(const char *name = "Root", const char *title = "ROOT GUI Factory"); - virtual ~TRootGuiFactory() {} + ~TRootGuiFactory() override {} TApplicationImp *CreateApplicationImp(const char *classname, int *argc, char **argv) override; diff --git a/gui/gui/inc/TRootHelpDialog.h b/gui/gui/inc/TRootHelpDialog.h index fd6c8f09c3bd1..08b1bdaa56a75 100644 --- a/gui/gui/inc/TRootHelpDialog.h +++ b/gui/gui/inc/TRootHelpDialog.h @@ -34,7 +34,7 @@ class TRootHelpDialog : public TGTransientFrame { public: TRootHelpDialog(const TGWindow *main = nullptr, const char *title = "ROOT Help Dialog", UInt_t w = 1, UInt_t h = 1); - virtual ~TRootHelpDialog(); + ~TRootHelpDialog() override; void SetText(const char *helpText); void AddText(const char *helpText); diff --git a/gui/gui/src/TGFileBrowser.cxx b/gui/gui/src/TGFileBrowser.cxx index 225863f118be4..63e9aea24e282 100644 --- a/gui/gui/src/TGFileBrowser.cxx +++ b/gui/gui/src/TGFileBrowser.cxx @@ -1320,9 +1320,7 @@ void TGFileBrowser::DoubleClicked(TGListTreeItem *item, Int_t /*btn*/) // avoid potential crash when drawing a canvas with the same name // than a canvas already embedded in one of the browser's tab obj->DrawClone(); - } - else if (fBrowser && !obj->InheritsFrom("TFormula") && - !obj->InheritsFrom("TMethodBrowsable")) + } else if (fBrowser && !obj->InheritsFrom("TFormula")) obj->Browse(fBrowser); fDblClick = kFALSE; fNKeys = 0; diff --git a/gui/gui/src/TGImageMap.cxx b/gui/gui/src/TGImageMap.cxx index 86044001bea23..73436171ba834 100644 --- a/gui/gui/src/TGImageMap.cxx +++ b/gui/gui/src/TGImageMap.cxx @@ -53,7 +53,7 @@ friend class TGRegion; public: TGRegionData() { fRgn = 0; fIsNull = kTRUE; AddReference(); } - ~TGRegionData() { } + ~TGRegionData() override { } TGRegionData &operator=(const TGRegionData &r); }; diff --git a/gui/gui/src/TGListBox.cxx b/gui/gui/src/TGListBox.cxx index 340ac40e701b5..93071e2241e68 100644 --- a/gui/gui/src/TGListBox.cxx +++ b/gui/gui/src/TGListBox.cxx @@ -455,7 +455,7 @@ void TGIconLBEntry::SetPicture(const TGPicture *pic) class TGLBFrameElement : public TGFrameElement { public: TGLBFrameElement(TGFrame *f, TGLayoutHints *l) : TGFrameElement(f, l) {} - virtual ~TGLBFrameElement() {} + ~TGLBFrameElement() override {} Bool_t IsSortable() const override { return kTRUE; } Int_t Compare(const TObject *obj) const override diff --git a/gui/gui/src/TGNumberEntry.cxx b/gui/gui/src/TGNumberEntry.cxx index 43d099efce7e9..ec2330dd7504b 100644 --- a/gui/gui/src/TGNumberEntry.cxx +++ b/gui/gui/src/TGNumberEntry.cxx @@ -1842,7 +1842,7 @@ class TGRepeatFireButton : public TGPictureButton { : TGPictureButton(p, pic, id), fTimer(0), fIgnoreNextFire(0), fStep(TGNumberFormat::kNSSSmall), fStepLog(logstep), fDoLogStep(logstep) { fEditDisabled = kEditDisable | kEditDisableGrab; } - virtual ~TGRepeatFireButton() { delete fTimer; } + ~TGRepeatFireButton() override { delete fTimer; } Bool_t HandleButton(Event_t *event) override; void FireButton(); diff --git a/gui/gui/src/TGStatusBar.cxx b/gui/gui/src/TGStatusBar.cxx index 72e602694ea60..3fa43ffd64266 100644 --- a/gui/gui/src/TGStatusBar.cxx +++ b/gui/gui/src/TGStatusBar.cxx @@ -49,7 +49,7 @@ friend class TGStatusBar; public: TGStatusBarPart(const TGWindow *p, Int_t h, Int_t y, ULong_t back = GetDefaultFrameBackground()); - ~TGStatusBarPart() { delete fStatusInfo; DestroyWindow(); } + ~TGStatusBarPart() override { delete fStatusInfo; DestroyWindow(); } void SetText(TGString *text); const TGString *GetText() const { return fStatusInfo; } }; diff --git a/gui/gui/src/TGTextEdit.cxx b/gui/gui/src/TGTextEdit.cxx index d48a78de72ab2..515da110cd3ad 100644 --- a/gui/gui/src/TGTextEdit.cxx +++ b/gui/gui/src/TGTextEdit.cxx @@ -63,7 +63,7 @@ class TGTextEditHist : public TList { public: TGTextEditHist() {} - virtual ~TGTextEditHist() { Delete(); } + ~TGTextEditHist() override { Delete(); } Bool_t Notify() override { // @@ -197,7 +197,7 @@ class TDelTextCom : public TGTextEditCommand { fText = new TGText(dtc.fText); fBreakLine = dtc.fBreakLine; } - virtual ~TDelTextCom() { delete fText; } + ~TDelTextCom() override { delete fText; } TDelTextCom &operator=(const TDelTextCom &dtc) { if (this != &dtc) { diff --git a/gui/gui/src/TRootBrowserLite.cxx b/gui/gui/src/TRootBrowserLite.cxx index 5abc2e0776861..53a75da7eadd5 100644 --- a/gui/gui/src/TRootBrowserLite.cxx +++ b/gui/gui/src/TRootBrowserLite.cxx @@ -339,7 +339,7 @@ class TRootIconList : public TList { public: TRootIconList(TRootIconBox* box = nullptr); - virtual ~TRootIconList(); + ~TRootIconList() override; void UpdateName(); const char *GetTitle() const override{ return "ListView Container"; } Bool_t IsFolder() const override { return kFALSE; } @@ -418,7 +418,7 @@ friend class TRootBrowserLite; UInt_t options = kSunkenFrame, ULong_t back = GetDefaultFrameBackground()); - virtual ~TRootIconBox(); + ~TRootIconBox() override; void AddObjItem(const char *name, TObject *obj, TClass *cl); void GetObjPictures(const TGPicture **pic, const TGPicture **spic, diff --git a/gui/gui/src/TRootCanvas.cxx b/gui/gui/src/TRootCanvas.cxx index 36cf0d90599c7..7e0b4631f5652 100644 --- a/gui/gui/src/TRootCanvas.cxx +++ b/gui/gui/src/TRootCanvas.cxx @@ -503,7 +503,7 @@ void TRootCanvas::CreateCanvas(const char *name) fToolDock->EnableHide(kFALSE); AddFrame(fToolDock, fDockLayout = new TGLayoutHints(kLHintsExpandX)); - // will alocate it later + // will allocate it later fToolBar = 0; fVertical1 = 0; fVertical2 = 0; @@ -1260,14 +1260,21 @@ Int_t TRootCanvas::InitWindow() //////////////////////////////////////////////////////////////////////////////// /// Set size of canvas container. Units in pixels. +/// If w==0 and h==0, set autofit mode void TRootCanvas::SetCanvasSize(UInt_t w, UInt_t h) { // turn off autofit, we want to stay at the given size - fAutoFit = kFALSE; - fOptionMenu->UnCheckEntry(kOptionAutoResize); int opt = fCanvasContainer->GetOptions(); - opt |= kFixedSize; // turn on fixed size mode + if (!w && !h) { + fAutoFit = kTRUE; + fOptionMenu->CheckEntry(kOptionAutoResize); + opt &= ~kFixedSize; // turn off fixed size mode + } else { + fAutoFit = kFALSE; + fOptionMenu->UnCheckEntry(kOptionAutoResize); + opt |= kFixedSize; // turn on fixed size mode + } fCanvasContainer->ChangeOptions(opt); fCanvasContainer->SetWidth(w); fCanvasContainer->SetHeight(h); @@ -1473,6 +1480,35 @@ void TRootCanvas::ShowEditor(Bool_t show) UInt_t h = GetHeight(); UInt_t s = fHorizontal1->GetHeight(); + auto lambda_show = [&, this]() { + if (show) { + if (!fEditor) + CreateEditor(); + TVirtualPadEditor *gged = TVirtualPadEditor::GetPadEditor(kFALSE); + if (gged && gged->GetCanvas() == fCanvas) { + gged->Hide(); + } + if (!fViewMenu->IsEntryChecked(kViewToolbar) || fToolDock->IsUndocked()) { + ShowFrame(fHorizontal1); + h += s; + } + fMainFrame->ShowFrame(fEditorFrame); + fEditor->Show(); + fViewMenu->CheckEntry(kViewEditor); + w += e; + } else { + if (!fViewMenu->IsEntryChecked(kViewToolbar) || fToolDock->IsUndocked()) { + HideFrame(fHorizontal1); + h -= s; + } + if (fEditor) + fEditor->Hide(); + fMainFrame->HideFrame(fEditorFrame); + fViewMenu->UnCheckEntry(kViewEditor); + w -= e; + } + }; + if (fParent && fParent != fClient->GetDefaultRoot()) { TGMainFrame *main = (TGMainFrame *)fParent->GetMainFrame(); fMainFrame->HideFrame(fEditorFrame); @@ -1507,33 +1543,13 @@ void TRootCanvas::ShowEditor(Bool_t show) fEditor = TVirtualPadEditor::GetPadEditor(kFALSE); } if (show) browser->GetTabLeft()->SetTab("Pad Editor"); + } else { + lambda_show(); + main->Layout(); } } else { - if (show) { - if (!fEditor) CreateEditor(); - TVirtualPadEditor* gged = TVirtualPadEditor::GetPadEditor(kFALSE); - if(gged && gged->GetCanvas() == fCanvas){ - gged->Hide(); - } - if (!fViewMenu->IsEntryChecked(kViewToolbar) || fToolDock->IsUndocked()) { - ShowFrame(fHorizontal1); - h = h + s; - } - fMainFrame->ShowFrame(fEditorFrame); - fEditor->Show(); - fViewMenu->CheckEntry(kViewEditor); - w = w + e; - } else { - if (!fViewMenu->IsEntryChecked(kViewToolbar) || fToolDock->IsUndocked()) { - HideFrame(fHorizontal1); - h = h - s; - } - if (fEditor) fEditor->Hide(); - fMainFrame->HideFrame(fEditorFrame); - fViewMenu->UnCheckEntry(kViewEditor); - w = w - e; - } + lambda_show(); Resize(w, h); } } diff --git a/gui/gui/src/TRootGuiFactory.cxx b/gui/gui/src/TRootGuiFactory.cxx index 9db1fcf47caa7..6aae41116b7fb 100644 --- a/gui/gui/src/TRootGuiFactory.cxx +++ b/gui/gui/src/TRootGuiFactory.cxx @@ -30,6 +30,8 @@ the member functions of the ABS TGuiFactory. #include "TPluginManager.h" #include "TEnv.h" +#include + ClassImp(TRootGuiFactory); //////////////////////////////////////////////////////////////////////////////// @@ -49,17 +51,47 @@ TApplicationImp *TRootGuiFactory::CreateApplicationImp(const char *classname, TRootApplication *app = new TRootApplication(classname, argc, argv); if (!app->Client()) { delete app; - app = 0; + app = nullptr; } return app; } +//////////////////////////////////////////////////////////////////////////////////////// +/// Show warning that TWebCanvas will be started by default + +void TRootGuiFactory::ShowWebCanvasWarning() +{ + static bool show_warn = true; + if (!show_warn || gROOT->IsWebDisplay()) return; + show_warn = false; + + std::cout << "\n" + " !!! ATTENTION !!! \n" + "\n" + "ROOT comes with a web-based canvas, which is now being started. \n" + "Revert to the legacy canvas by setting \"Canvas.Name: TRootCanvas\" in rootrc file or\n" + "by starting \"root --web=off\".\n" + "Find more info on https://root.cern/for_developers/root7/#twebcanvas\n" + "\n"; +} + //////////////////////////////////////////////////////////////////////////////// /// Create a ROOT native GUI version of TCanvasImp TCanvasImp *TRootGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, UInt_t width, UInt_t height) { + TString canvName = gEnv->GetValue("Canvas.Name", "TWebCanvas"); + if (canvName == "TWebCanvas") { + auto ph = gROOT->GetPluginManager()->FindHandler("TCanvasImp", "TWebCanvas"); + + if (ph && ph->LoadPlugin() != -1) { + ShowWebCanvasWarning(); + auto imp = (TCanvasImp *) ph->ExecPlugin(6, c, title, 0, 0, width, height); + if (imp) return imp; + } + } + return new TRootCanvas(c, title, width, height); } @@ -69,6 +101,17 @@ TCanvasImp *TRootGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, TCanvasImp *TRootGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height) { + TString canvName = gEnv->GetValue("Canvas.Name", "TWebCanvas"); + if (canvName == "TWebCanvas") { + auto ph = gROOT->GetPluginManager()->FindHandler("TCanvasImp", "TWebCanvas"); + + if (ph && ph->LoadPlugin() != -1) { + ShowWebCanvasWarning(); + auto imp = (TCanvasImp *) ph->ExecPlugin(6, c, title, x, y, width, height); + if (imp) return imp; + } + } + return new TRootCanvas(c, title, x, y, width, height); } @@ -140,6 +183,9 @@ TContextMenuImp *TRootGuiFactory::CreateContextMenuImp(TContextMenu *c, TControlBarImp *TRootGuiFactory::CreateControlBarImp(TControlBar *c, const char *title) { + if (gROOT->IsWebDisplay()) + return TGuiFactory::CreateControlBarImp(c, title); + return new TRootControlBar(c, title); } @@ -149,5 +195,8 @@ TControlBarImp *TRootGuiFactory::CreateControlBarImp(TControlBar *c, const char TControlBarImp *TRootGuiFactory::CreateControlBarImp(TControlBar *c, const char *title, Int_t x, Int_t y) { + if (gROOT->IsWebDisplay()) + return TGuiFactory::CreateControlBarImp(c, title, x, y); + return new TRootControlBar(c, title, x, y); } diff --git a/gui/guibuilder/inc/TGuiBldDragManager.h b/gui/guibuilder/inc/TGuiBldDragManager.h index 2e9c035a01a15..3b617d6bb0704 100644 --- a/gui/guibuilder/inc/TGuiBldDragManager.h +++ b/gui/guibuilder/inc/TGuiBldDragManager.h @@ -159,14 +159,14 @@ friend class TGuiBldEditor; void CheckTargetUnderGrab(); void HighlightCompositeFrame(Window_t); void Compact(Bool_t global = kTRUE); - Bool_t StartDrag(TGFrame *src, Int_t x, Int_t y); - Bool_t EndDrag(); - Bool_t Drop(); - Bool_t Cancel(Bool_t delSrc); + Bool_t StartDrag(TGFrame *src, Int_t x, Int_t y) override; + Bool_t EndDrag() override; + Bool_t Drop() override; + Bool_t Cancel(Bool_t delSrc) override; void Menu4Frame(TGFrame *, Int_t x, Int_t y); void Menu4Lasso(Int_t x, Int_t y); void CreatePropertyEditor(); - void DoRedraw(); + void DoRedraw() override; void SwitchEditable(TGFrame *frame); void UnmapAllPopups(); void BreakLayout(); @@ -175,33 +175,33 @@ friend class TGuiBldEditor; Bool_t RecognizeGesture(Event_t *, TGFrame *frame = nullptr); Bool_t HandleButtonPress(Event_t *); Bool_t HandleButtonRelease(Event_t *); - Bool_t HandleButton(Event_t *); - Bool_t HandleDoubleClick(Event_t*); - Bool_t HandleMotion(Event_t *); - Bool_t HandleClientMessage(Event_t *); + Bool_t HandleButton(Event_t *) override; + Bool_t HandleDoubleClick(Event_t*) override; + Bool_t HandleMotion(Event_t *) override; + Bool_t HandleClientMessage(Event_t *) override; Bool_t HandleDestroyNotify(Event_t *); - Bool_t HandleSelection(Event_t *); - Bool_t HandleExpose(Event_t *); - Bool_t HandleConfigureNotify(Event_t *); - Bool_t HandleSelectionRequest(Event_t *); + Bool_t HandleSelection(Event_t *) override; + Bool_t HandleExpose(Event_t *) override; + Bool_t HandleConfigureNotify(Event_t *) override; + Bool_t HandleSelectionRequest(Event_t *) override; void HandleButon3Pressed(Event_t *, TGFrame *frame = nullptr); - Bool_t HandleEvent(Event_t *); - Bool_t HandleTimer(TTimer *); + Bool_t HandleEvent(Event_t *) override; + Bool_t HandleTimer(TTimer *) override; Bool_t IsMoveWaiting() const; Bool_t IsLassoDrawn() const { return fLassoDrawn; } void SetLassoDrawn(Bool_t on); void HideGrabRectangles(); - Bool_t IgnoreEvent(Event_t *e); + Bool_t IgnoreEvent(Event_t *e) override; Bool_t CheckDragResize(Event_t *event); Bool_t IsPasteFrameExist(); public: TGuiBldDragManager(); - virtual ~TGuiBldDragManager(); + ~TGuiBldDragManager() override; void HandleAction(Int_t act); - Bool_t HandleKey(Event_t *); + Bool_t HandleKey(Event_t *) override; TGFrame *GetTarget() const { return fTarget; } TGFrame *GetSelected() const; @@ -209,21 +209,21 @@ friend class TGuiBldEditor; void SetGridStep(UInt_t step); UInt_t GetGridStep(); void HandleUpdateSelected(TGFrame *); - Int_t GetStrartDragX() const; - Int_t GetStrartDragY() const; - Int_t GetEndDragX() const; - Int_t GetEndDragY() const; + Int_t GetStrartDragX() const override; + Int_t GetStrartDragY() const override; + Int_t GetEndDragX() const override; + Int_t GetEndDragY() const override; Bool_t GetDropStatus() const { return fDropStatus; } void SetBuilder(TRootGuiBuilder *b) { fBuilder = b; } Bool_t IsStopped() const { return fStop; } - void SetEditable(Bool_t on = kTRUE); + void SetEditable(Bool_t on = kTRUE) override; void SelectFrame(TGFrame *frame, Bool_t add = kFALSE); static void MapGlobalDialog(TGMainFrame *dialog, TGFrame *fr); - Bool_t HandleTimerEvent(Event_t *ev, TTimer *t); + Bool_t HandleTimerEvent(Event_t *ev, TTimer *t) override; void TimerEvent(Event_t *ev) { Emit("TimerEvent(Event_t*)", (Longptr_t)ev); } // *SIGNAL* @@ -256,7 +256,7 @@ friend class TGuiBldEditor; void ChangeBackgroundColor(TGFrame *); //*MENU* *DIALOG*icon=bld_colorselect.png* void ChangeBackgroundColor(TGCompositeFrame *); //*MENU* *DIALOG*icon=bld_colorselect.png* - ClassDef(TGuiBldDragManager,0) // drag and drop manager + ClassDefOverride(TGuiBldDragManager,0) // drag and drop manager }; diff --git a/gui/guibuilder/inc/TGuiBldEditor.h b/gui/guibuilder/inc/TGuiBldEditor.h index f85fcdb3a052a..ec7caa53d8079 100644 --- a/gui/guibuilder/inc/TGuiBldEditor.h +++ b/gui/guibuilder/inc/TGuiBldEditor.h @@ -52,7 +52,7 @@ friend class TGuiBldDragManager; public: TGuiBldEditor(const TGWindow *p = nullptr); - virtual ~TGuiBldEditor(); + ~TGuiBldEditor() override; Int_t GetXPos() const { return fXpos->GetIntNumber(); } Int_t GetYPos() const { return fYpos->GetIntNumber(); } @@ -69,13 +69,13 @@ friend class TGuiBldDragManager; void Reset(); TGuiBldHintsEditor *GetHintsEditor() const { return fHintsFrame; } - void RemoveFrame(TGFrame *); + void RemoveFrame(TGFrame *) override; void TabSelected(Int_t id); void UpdateSelected(TGFrame* = nullptr); //*SIGNAL* void ChangeSelected(TGFrame*); //*SIGNAL* void SwitchLayout(); - ClassDef(TGuiBldEditor,0) // frame property editor + ClassDefOverride(TGuiBldEditor,0) // frame property editor }; #endif diff --git a/gui/guibuilder/inc/TGuiBldGeometryFrame.h b/gui/guibuilder/inc/TGuiBldGeometryFrame.h index 92b6320ce2b74..c94cb40dfb5bf 100644 --- a/gui/guibuilder/inc/TGuiBldGeometryFrame.h +++ b/gui/guibuilder/inc/TGuiBldGeometryFrame.h @@ -38,12 +38,12 @@ friend class TGuiBldDragManager; public: TGuiBldGeometryFrame(const TGWindow *p, TGuiBldEditor *editor); - virtual ~TGuiBldGeometryFrame() { } + ~TGuiBldGeometryFrame() override { } void ResizeSelected(); void ChangeSelected(TGFrame *frame); - ClassDef(TGuiBldGeometryFrame, 0) // frame geometry editor + ClassDefOverride(TGuiBldGeometryFrame, 0) // frame geometry editor }; #endif diff --git a/gui/guibuilder/inc/TGuiBldHintsButton.h b/gui/guibuilder/inc/TGuiBldHintsButton.h index 2b6f0a90fba71..0e4cd6d554eb7 100644 --- a/gui/guibuilder/inc/TGuiBldHintsButton.h +++ b/gui/guibuilder/inc/TGuiBldHintsButton.h @@ -29,13 +29,13 @@ class TGuiBldHintsButton : public TGButton { virtual void DrawBottomLeft(); virtual void DrawBottomRight(); - virtual void DoRedraw(); + void DoRedraw() override; public: TGuiBldHintsButton(const TGWindow *p, Int_t id); - virtual ~TGuiBldHintsButton() {} + ~TGuiBldHintsButton() override {} - ClassDef(TGuiBldHintsButton,0) //Button for editing layout hints in GUI Builder + ClassDefOverride(TGuiBldHintsButton,0) //Button for editing layout hints in GUI Builder }; #endif diff --git a/gui/guibuilder/inc/TGuiBldHintsEditor.h b/gui/guibuilder/inc/TGuiBldHintsEditor.h index b7d987ea35cdf..510512909a52a 100644 --- a/gui/guibuilder/inc/TGuiBldHintsEditor.h +++ b/gui/guibuilder/inc/TGuiBldHintsEditor.h @@ -57,7 +57,7 @@ class TGuiBldHintsEditor : public TGVerticalFrame { public: TGuiBldHintsEditor(const TGWindow *p, TGuiBldEditor *e); - virtual ~TGuiBldHintsEditor() {} + ~TGuiBldHintsEditor() override {} void ChangeSelected(TGFrame *); void LayoutSubframes(Bool_t on = kTRUE); @@ -65,7 +65,7 @@ class TGuiBldHintsEditor : public TGVerticalFrame { void SetPosition(); void UpdateState(); - ClassDef(TGuiBldHintsEditor,0) // layout hints editor + ClassDefOverride(TGuiBldHintsEditor,0) // layout hints editor }; #endif diff --git a/gui/guibuilder/inc/TGuiBldNameFrame.h b/gui/guibuilder/inc/TGuiBldNameFrame.h index fd708f557cc4a..f16900b37a9cb 100644 --- a/gui/guibuilder/inc/TGuiBldNameFrame.h +++ b/gui/guibuilder/inc/TGuiBldNameFrame.h @@ -41,23 +41,23 @@ class TGuiBldNameFrame : public TGCompositeFrame { TGCanvas *fCanvas; protected: - void DoRedraw(); + void DoRedraw() override; public: TGuiBldNameFrame(const TGWindow *p, TGuiBldEditor *editor); - virtual ~TGuiBldNameFrame() { } + ~TGuiBldNameFrame() override { } void ChangeSelected(TGFrame *frame); Bool_t CheckItems(TGCompositeFrame *main); TGListTreeItem *FindItemByName(TGListTree *tree, const char* name, TGListTreeItem *item = nullptr); TGCompositeFrame *GetMdi(TGFrame *frame); void MapItems(TGCompositeFrame *main); - void RemoveFrame(TGFrame *frame); + void RemoveFrame(TGFrame *frame) override; void Reset(); void SelectFrameByItem(TGListTreeItem* item, Int_t i = 0); void UpdateName(); - ClassDef(TGuiBldNameFrame, 0) // frame name editor + ClassDefOverride(TGuiBldNameFrame, 0) // frame name editor }; diff --git a/gui/guibuilder/inc/TRootGuiBuilder.h b/gui/guibuilder/inc/TRootGuiBuilder.h index 13cede88a669c..87a62675546c6 100644 --- a/gui/guibuilder/inc/TRootGuiBuilder.h +++ b/gui/guibuilder/inc/TRootGuiBuilder.h @@ -94,15 +94,15 @@ friend class TGuiBldDragManager; public: TRootGuiBuilder(const TGWindow *p = nullptr); - virtual ~TRootGuiBuilder(); + ~TRootGuiBuilder() override; - virtual void AddAction(TGuiBldAction *act, const char *sect); + void AddAction(TGuiBldAction *act, const char *sect) override; virtual void AddMacro(const char *macro, TImage *img); - virtual void AddSection(const char *sect); - virtual TGFrame *ExecuteAction(); + void AddSection(const char *sect) override; + TGFrame *ExecuteAction() override; virtual void HandleButtons(); - virtual void Show() { MapRaised(); } - virtual void Hide(); + void Show() override { MapRaised(); } + void Hide() override; virtual void ChangeSelected(TGFrame *f); virtual void Update(); virtual Bool_t IsSelectMode() const; @@ -110,9 +110,9 @@ friend class TGuiBldDragManager; virtual Bool_t OpenProject(Event_t *event = nullptr); virtual Bool_t SaveProject(Event_t *event = nullptr); virtual Bool_t NewProject(TString type = ""); - virtual Bool_t HandleKey(Event_t *event); + Bool_t HandleKey(Event_t *event) override; virtual void HandleMenu(Int_t id); - virtual void CloseWindow(); + void CloseWindow() override; virtual void MaybeCloseWindow(); virtual void HandleWindowClosed(Int_t id); virtual void UpdateStatusBar(const char *text = nullptr); @@ -155,7 +155,7 @@ friend class TGuiBldDragManager; static TGFrame *BuildVProgressBar(); - ClassDef(TRootGuiBuilder,0) // ROOT GUI Builder + ClassDefOverride(TRootGuiBuilder,0) // ROOT GUI Builder }; diff --git a/gui/guibuilder/src/TGuiBldDragManager.cxx b/gui/guibuilder/src/TGuiBldDragManager.cxx index bd942a1c1fd24..7790b8fd618e6 100644 --- a/gui/guibuilder/src/TGuiBldDragManager.cxx +++ b/gui/guibuilder/src/TGuiBldDragManager.cxx @@ -120,11 +120,11 @@ friend class TGuiBldDragManager; TList *fWidgets; // list of widgets public: - virtual ~TGuiBldMenuDialog(); + ~TGuiBldMenuDialog() override; TGuiBldMenuDialog(const TGWindow *main, TObject *obj, TMethod *method); const char *GetParameters(); - void CloseWindow(); + void CloseWindow() override; void ConnectButtonSignals(); void Build(); void Popup(); @@ -674,7 +674,7 @@ class TGuiBldDragManagerRepeatTimer : public TTimer { public: TGuiBldDragManagerRepeatTimer(TGuiBldDragManager *m, Long_t ms) : TTimer(ms, kTRUE) { fManager = m; } - Bool_t Notify() { fManager->HandleTimer(this); Reset(); return kFALSE; } + Bool_t Notify() override { fManager->HandleTimer(this); Reset(); return kFALSE; } }; @@ -687,9 +687,9 @@ class TGGrabRect : public TGFrame { public: TGGrabRect(Int_t type); - ~TGGrabRect() {} + ~TGGrabRect() override {} - Bool_t HandleButton(Event_t *ev); + Bool_t HandleButton(Event_t *ev) override; ECursor GetType() const { return fType; } }; @@ -769,7 +769,7 @@ class TGAroundFrame : public TGFrame { public: TGAroundFrame(); - ~TGAroundFrame() {} + ~TGAroundFrame() override {} }; //////////////////////////////////////////////////////////////////////////////// diff --git a/gui/guibuilder/src/TGuiBldEditor.cxx b/gui/guibuilder/src/TGuiBldEditor.cxx index c9b2f5297d4d8..710fd5b5517e0 100644 --- a/gui/guibuilder/src/TGuiBldEditor.cxx +++ b/gui/guibuilder/src/TGuiBldEditor.cxx @@ -55,7 +55,7 @@ class TGuiBldBorderFrame : public TGVerticalFrame { public: TGuiBldBorderFrame(const TGWindow *p, TGuiBldEditor *editor); - virtual ~TGuiBldBorderFrame() { } + ~TGuiBldBorderFrame() override { } void ChangeSelected(TGFrame*); }; diff --git a/gui/guibuilder/src/TGuiBldHintsEditor.cxx b/gui/guibuilder/src/TGuiBldHintsEditor.cxx index 630df3c0da49c..140f0bbc4f1c2 100644 --- a/gui/guibuilder/src/TGuiBldHintsEditor.cxx +++ b/gui/guibuilder/src/TGuiBldHintsEditor.cxx @@ -48,7 +48,7 @@ class TGuiBldHintsManager : public TGVerticalFrame { public: TGuiBldHintsManager(const TGWindow *p, TGuiBldEditor *editor, TGuiBldHintsEditor *hints); - virtual ~TGuiBldHintsManager() { } + ~TGuiBldHintsManager() override { } void ChangeSelected(TGFrame *frame); }; diff --git a/gui/guibuilder/src/TRootGuiBuilder.cxx b/gui/guibuilder/src/TRootGuiBuilder.cxx index 4d37226bd5d18..69a7e47b4c79a 100644 --- a/gui/guibuilder/src/TRootGuiBuilder.cxx +++ b/gui/guibuilder/src/TRootGuiBuilder.cxx @@ -236,10 +236,10 @@ class TGuiBldMenuTitle : public TGMenuTitle { Pixel_t fBgndColor; protected: - void DoRedraw(); + void DoRedraw() override; public: - virtual ~TGuiBldMenuTitle() {} + ~TGuiBldMenuTitle() override {} TGuiBldMenuTitle(const TGWindow *p, TGHotString *s, TGPopupMenu *menu) : TGMenuTitle(p, s, menu) { fEditDisabled = kEditDisable; @@ -248,7 +248,7 @@ class TGuiBldMenuTitle : public TGMenuTitle { AddInput(kEnterWindowMask | kLeaveWindowMask); } - Bool_t HandleCrossing(Event_t *event); + Bool_t HandleCrossing(Event_t *event) override; }; //////////////////////////////////////////////////////////////////////////////// @@ -299,14 +299,14 @@ void TGuiBldMenuTitle::DoRedraw() class TGuiBldPopupMenu : public TGPopupMenu { public: - virtual ~TGuiBldPopupMenu() { } + ~TGuiBldPopupMenu() override { } TGuiBldPopupMenu() : TGPopupMenu(gClient->GetDefaultRoot()) { fEditDisabled = kEditDisable; SetBackgroundColor(TRootGuiBuilder::GetPopupBgnd()); fEntrySep = 8; } - void DrawEntry(TGMenuEntry *entry); + void DrawEntry(TGMenuEntry *entry) override; }; //////////////////////////////////////////////////////////////////////////////// @@ -465,20 +465,20 @@ class TGuiBldToolButton : public TGPictureButton { Pixel_t fBgndColor; protected: - void DoRedraw(); + void DoRedraw() override; public: - virtual ~TGuiBldToolButton() { } + ~TGuiBldToolButton() override { } TGuiBldToolButton(const TGWindow *p, const TGPicture *pic, Int_t id = -1) : TGPictureButton(p, pic, id) { fBgndColor = TRootGuiBuilder::GetBgnd(); ChangeOptions(GetOptions() & ~kRaisedFrame); } - Bool_t IsDown() const { return (fOptions & kSunkenFrame); } - void SetState(EButtonState state, Bool_t emit = kTRUE); - Bool_t HandleCrossing(Event_t *event); - void SetBackgroundColor(Pixel_t bgnd) { fBgndColor = bgnd; TGFrame::SetBackgroundColor(bgnd); } + Bool_t IsDown() const override { return (fOptions & kSunkenFrame); } + void SetState(EButtonState state, Bool_t emit = kTRUE) override; + Bool_t HandleCrossing(Event_t *event) override; + void SetBackgroundColor(Pixel_t bgnd) override { fBgndColor = bgnd; TGFrame::SetBackgroundColor(bgnd); } }; //////////////////////////////////////////////////////////////////////////////// diff --git a/gui/guihtml/inc/TGHtml.h b/gui/guihtml/inc/TGHtml.h index 0159a3022c4b1..e8bbb9f2b3b0d 100644 --- a/gui/guihtml/inc/TGHtml.h +++ b/gui/guihtml/inc/TGHtml.h @@ -290,7 +290,7 @@ class TGHtmlTextElement : public TGHtmlElement { public: TGHtmlTextElement(int size); - virtual ~TGHtmlTextElement(); + ~TGHtmlTextElement() override; Html_32_t fY; // y coordinate where text should be rendered Html_16_t fX; // x coordinate where text should be rendered @@ -324,13 +324,13 @@ class TGHtmlSpaceElement : public TGHtmlElement { class TGHtmlMarkupElement : public TGHtmlElement { public: TGHtmlMarkupElement(int type, int argc, int arglen[], char *argv[]); - virtual ~TGHtmlMarkupElement(); + ~TGHtmlMarkupElement() override; - virtual const char *MarkupArg(const char *tag, const char *zDefault); - virtual int GetAlignment(int dflt); - virtual int GetOrderedListType(int dflt); - virtual int GetUnorderedListType(int dflt); - virtual int GetVerticalAlignment(int dflt); + const char *MarkupArg(const char *tag, const char *zDefault) override; + int GetAlignment(int dflt) override; + int GetOrderedListType(int dflt) override; + int GetUnorderedListType(int dflt) override; + int GetVerticalAlignment(int dflt) override; public://protected: char **fArgv; @@ -354,7 +354,7 @@ class TGHtmlMarkupElement : public TGHtmlElement { class TGHtmlTable : public TGHtmlMarkupElement { public: TGHtmlTable(int type, int argc, int arglen[], char *argv[]); - ~TGHtmlTable(); + ~TGHtmlTable() override; public: Html_u8_t fBorderWidth; // Width of the border @@ -381,7 +381,7 @@ class TGHtmlTable : public TGHtmlMarkupElement { class TGHtmlCell : public TGHtmlMarkupElement { public: TGHtmlCell(int type, int argc, int arglen[], char *argv[]); - ~TGHtmlCell(); + ~TGHtmlCell() override; public: Html_16_t fRowspan; // Number of rows spanned by this cell @@ -405,7 +405,7 @@ class TGHtmlCell : public TGHtmlMarkupElement { class TGHtmlRef : public TGHtmlMarkupElement { public: TGHtmlRef(int type, int argc, int arglen[], char *argv[]); - ~TGHtmlRef(); + ~TGHtmlRef() override; public: TGHtmlElement *fPOther; // Pointer to some other Html element @@ -512,7 +512,7 @@ class TGHtmlImage : public TObject { public: TGHtmlImage(TGHtml *htm, const char *url, const char *width, const char *height); - virtual ~TGHtmlImage(); + ~TGHtmlImage() override; public: TGHtml *fHtml; // The owner of this image @@ -711,7 +711,7 @@ class TGHtmlScript : public TGHtmlMarkupElement { class TGHtmlBlock : public TGHtmlElement { public: TGHtmlBlock(); - virtual ~TGHtmlBlock(); + ~TGHtmlBlock() override; public: char *fZ; // Space to hold text when n > 0 @@ -873,19 +873,19 @@ class THashTable; class TGHtml : public TGView { public: TGHtml(const TGWindow *p, int w, int h, int id = -1); - virtual ~TGHtml(); + ~TGHtml() override; - virtual Bool_t HandleFocusChange(Event_t *event); - virtual Bool_t HandleButton(Event_t *event); - virtual Bool_t HandleMotion(Event_t *event); + Bool_t HandleFocusChange(Event_t *event) override; + Bool_t HandleButton(Event_t *event) override; + Bool_t HandleMotion(Event_t *event) override; - virtual Bool_t HandleIdleEvent(TGIdleHandler *i); - virtual Bool_t HandleTimer(TTimer *timer); + Bool_t HandleIdleEvent(TGIdleHandler *i) override; + Bool_t HandleTimer(TTimer *timer) override; - virtual Bool_t ProcessMessage(Longptr_t, Longptr_t, Longptr_t); + Bool_t ProcessMessage(Longptr_t, Longptr_t, Longptr_t) override; - virtual void DrawRegion(Int_t x, Int_t y, UInt_t w, UInt_t h); - virtual Bool_t ItemLayout(); + void DrawRegion(Int_t x, Int_t y, UInt_t w, UInt_t h) override; + Bool_t ItemLayout() override; Bool_t HandleHtmlInput(TGHtmlInput *pr, Event_t *event); Bool_t HandleRadioButton(TGHtmlInput *p); @@ -911,7 +911,7 @@ class TGHtml : public TGView { public: // reloadable methods // called when the widget is cleared - virtual void Clear(Option_t * = ""); + void Clear(Option_t * = "") override; // User function to resolve URIs virtual char *ResolveUri(const char *uri); @@ -1123,10 +1123,10 @@ class TGHtml : public TGView { virtual void CheckToggled(const char *name, Bool_t on, const char *val); // *SIGNAL* virtual void RadioChanged(const char *name, const char *val); // *SIGNAL* virtual void InputSelected(const char *name, const char *val); //*SIGNAL* - virtual void SavePrimitive(std::ostream &out, Option_t * = ""); + void SavePrimitive(std::ostream &out, Option_t * = "") override; protected: - virtual void UpdateBackgroundStart(); + void UpdateBackgroundStart() override; protected: enum { @@ -1287,7 +1287,7 @@ class TGHtml : public TGView { const char *fLastUri; // Used in HandleMotion int fExiting; // True if the widget is being destroyed - ClassDef(TGHtml, 0); // HTML widget + ClassDefOverride(TGHtml, 0); // HTML widget }; diff --git a/gui/guihtml/inc/TGHtmlBrowser.h b/gui/guihtml/inc/TGHtmlBrowser.h index 678cd4dda74f3..5d6d0580ad328 100644 --- a/gui/guihtml/inc/TGHtmlBrowser.h +++ b/gui/guihtml/inc/TGHtmlBrowser.h @@ -57,9 +57,9 @@ class TGHtmlBrowser : public TGMainFrame { public: TGHtmlBrowser(const char *filename = nullptr, const TGWindow *p = nullptr, UInt_t w = 900, UInt_t h = 600); - virtual ~TGHtmlBrowser() {} + ~TGHtmlBrowser() override {} - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t) override; void Selected(const char *txt); void URLChanged(); void Back(); @@ -71,7 +71,7 @@ class TGHtmlBrowser : public TGMainFrame { void MouseDown(const char *); void Clicked(char *uri) { Emit("Clicked(char *)",uri); } // *SIGNAL* - ClassDef(TGHtmlBrowser, 0) // very simple html browser + ClassDefOverride(TGHtmlBrowser, 0) // very simple html browser }; #endif diff --git a/gui/guihtml/inc/TGHtmlUri.h b/gui/guihtml/inc/TGHtmlUri.h index 75e7754952bb2..0881de6748275 100644 --- a/gui/guihtml/inc/TGHtmlUri.h +++ b/gui/guihtml/inc/TGHtmlUri.h @@ -60,7 +60,7 @@ class TGHtmlUri : public TObject { public: TGHtmlUri(const char *zUri = nullptr); TGHtmlUri(const TGHtmlUri *uri); - virtual ~TGHtmlUri(); + ~TGHtmlUri() override; char *BuildUri(); int EqualsUri(const TGHtmlUri *uri, int field_mask = URI_FULL_MASK); diff --git a/gui/guihtml/src/TGHtmlForm.cxx b/gui/guihtml/src/TGHtmlForm.cxx index 2da9076f66d60..e0027fe99f08b 100644 --- a/gui/guihtml/src/TGHtmlForm.cxx +++ b/gui/guihtml/src/TGHtmlForm.cxx @@ -281,7 +281,7 @@ class TGHtmlLBEntry : public TGTextLBEntry { public: TGHtmlLBEntry(const TGWindow *p, TGString *s, TGString *val, int ID) : TGTextLBEntry(p, s, ID) { fVal = val; } - virtual ~TGHtmlLBEntry() { if (fVal) delete fVal; } + ~TGHtmlLBEntry() override { if (fVal) delete fVal; } const char *GetValue() const { return fVal ? fVal->GetString() : 0; } diff --git a/gui/qt5webdisplay/CMakeLists.txt b/gui/qt5webdisplay/CMakeLists.txt index d1b8658bc1f00..d73d0e30ac8c9 100644 --- a/gui/qt5webdisplay/CMakeLists.txt +++ b/gui/qt5webdisplay/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. +# Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. # All rights reserved. # # For the licensing terms see $ROOTSYS/LICENSE. diff --git a/gui/qt5webdisplay/rootqt5.cpp b/gui/qt5webdisplay/rootqt5.cpp index 1d06a51862357..36fba8e543671 100644 --- a/gui/qt5webdisplay/rootqt5.cpp +++ b/gui/qt5webdisplay/rootqt5.cpp @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -19,10 +19,7 @@ #include #include #include - -#if QT_VERSION >= 0x050C00 #include -#endif #include "TROOT.h" #include "TApplication.h" @@ -31,6 +28,7 @@ #include "TThread.h" #include "THttpServer.h" #include "TSystem.h" +#include "TDirectory.h" #include "rootwebview.h" #include "rootwebpage.h" @@ -39,8 +37,32 @@ #include #include +#include #include +QWebEngineUrlScheme gRootScheme("rootscheme"); +QApplication *gOwnApplication = nullptr; +int gQt5HandleCounts = 0; +bool gProcEvents = false, gDoingShutdown = false; + +void TestQt5Cleanup() +{ + if (gQt5HandleCounts == 0 && gOwnApplication && !gProcEvents && gDoingShutdown) { + delete gOwnApplication; + gOwnApplication = nullptr; + } +} + +class DummyObject : public TObject { +public: + ~DummyObject() override + { + gDoingShutdown = true; + TestQt5Cleanup(); + } + +}; + /** \class TQt5Timer \ingroup qt5webdisplay */ @@ -53,13 +75,15 @@ class TQt5Timer : public TTimer { /// used to process all qt5 events in main ROOT thread void Timeout() override { + gProcEvents = true; QApplication::sendPostedEvents(); QApplication::processEvents(); + gProcEvents = false; + } }; namespace ROOT { -namespace Experimental { /** \class RQt5WebDisplayHandle \ingroup qt5webdisplay @@ -71,8 +95,6 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { RootWebView *fView{nullptr}; ///< pointer on widget, need to release when handle is destroyed class Qt5Creator : public Creator { - int fCounter{0}; ///< counter used to number handlers - QApplication *qapp{nullptr}; ///< created QApplication int qargc{1}; ///< arg counter char *qargv[2]; ///< arg values std::unique_ptr fTimer; ///< timer to process ROOT events @@ -81,7 +103,7 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { Qt5Creator() = default; - virtual ~Qt5Creator() + ~Qt5Creator() override { /** Code executed during exit and sometime crashes. * Disable it, while not clear if defaultProfile can be still used - seems to be not */ @@ -95,7 +117,7 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { std::unique_ptr Display(const RWebDisplayArgs &args) override { - if (!qapp && !QApplication::instance()) { + if (!gOwnApplication && !QApplication::instance()) { if (!gApplication) { R__LOG_ERROR(QtWebDisplayLog()) << "Not found gApplication to create QApplication"; @@ -105,22 +127,20 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { // initialize web engine only before creating QApplication QtWebEngine::initialize(); - #if QT_VERSION >= 0x050C00 - QWebEngineUrlScheme scheme("rootscheme"); - scheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort); - scheme.setDefaultPort(2345); - scheme.setFlags(QWebEngineUrlScheme::SecureScheme); - QWebEngineUrlScheme::registerScheme(scheme); - #endif - qargv[0] = gApplication->Argv(0); qargv[1] = nullptr; - qapp = new QApplication(qargc, qargv); + gOwnApplication = new QApplication(qargc, qargv); + + // this is workaround to detect ROOT shutdown + TDirectory::TContext ctxt; // preserve gDirectory + auto dir = new TDirectory("dummy_qt5web_dir", "cleanup instance for qt5web"); + dir->GetList()->Add(new DummyObject()); + gROOT->GetListOfClosedObjects()->Add(dir); } // create timer to process Qt events from inside ROOT process events - // very much improve performance, even when Qt even loop runs by QApplication normally + // very much improve performance, even when Qt event loop runs by QApplication normally if (!fTimer && !args.IsHeadless()) { Int_t interval = gEnv->GetValue("WebGui.Qt5Timer", 1); if (interval > 0) { @@ -184,8 +204,10 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { if (gSystem->ProcessEvents()) break; // interrupted, has to return + gProcEvents = true; QApplication::sendPostedEvents(); QApplication::processEvents(); + gProcEvents = false; if (load_finished && !did_try) { did_try = true; @@ -213,8 +235,10 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { delete view; for (expired=0;expired<100;++expired) { + gProcEvents = true; QApplication::sendPostedEvents(); QApplication::processEvents(); + gProcEvents = false; } } @@ -225,15 +249,27 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { }; public: - RQt5WebDisplayHandle(const std::string &url) : RWebDisplayHandle(url) {} + RQt5WebDisplayHandle(const std::string &url) : RWebDisplayHandle(url) { gQt5HandleCounts++; } - virtual ~RQt5WebDisplayHandle() + ~RQt5WebDisplayHandle() override { // now view can be safely destroyed if (fView) { delete fView; fView = nullptr; } + + gQt5HandleCounts--; + + TestQt5Cleanup(); + } + + bool Resize(int width, int height) override + { + if (!fView) + return false; + fView->resize(QSize(width, height)); + return true; } static void AddCreator() @@ -246,8 +282,15 @@ class RQt5WebDisplayHandle : public RWebDisplayHandle { }; struct RQt5CreatorReg { - RQt5CreatorReg() { RQt5WebDisplayHandle::AddCreator(); } + RQt5CreatorReg() { + RQt5WebDisplayHandle::AddCreator(); + + gRootScheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort); + gRootScheme.setDefaultPort(2345); + gRootScheme.setFlags(QWebEngineUrlScheme::SecureScheme); + QWebEngineUrlScheme::registerScheme(gRootScheme); + + } } newRQt5CreatorReg; -} -} +} // namespace ROOT diff --git a/gui/qt5webdisplay/rooturlschemehandler.cpp b/gui/qt5webdisplay/rooturlschemehandler.cpp index 0869027f4fbed..5e7e02f055b07 100644 --- a/gui/qt5webdisplay/rooturlschemehandler.cpp +++ b/gui/qt5webdisplay/rooturlschemehandler.cpp @@ -2,9 +2,8 @@ // Date: 2017-06-29 // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! - /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -98,14 +97,7 @@ class TWebGuiCallArg : public THttpCallArg { QFile file(fname); buffer->open(QIODevice::WriteOnly); if (file.open(QIODevice::ReadOnly)) { - QByteArray arr = file.readAll(); - if (strstr(fname, ".mjs") && !strcmp(mime, "text/javascript")) { - const char *mark1 = "///_begin_exclude_in_qt5web_", *mark2 = "///_end_exclude_in_qt5web_"; - auto p1 = arr.indexOf(mark1); - auto p2 = arr.indexOf(mark2); - if ((p1 > 0) && (p2 > p1)) arr.remove(p1, p2 - p1 + strlen(mark2)); - } - + auto arr = file.readAll(); buffer->write(arr); } file.close(); @@ -127,12 +119,12 @@ class TWebGuiCallArg : public THttpCallArg { QWebEngineUrlRequestJob *req = fRequest.req(); if (!req) { - R__LOG_ERROR(QtWebDisplayLog()) << "Qt5 request already processed path " << GetPathName() << " file " << GetFileName(); + R__LOG_ERROR(QtWebDisplayLog()) << "Qt " << QT_VERSION_STR << " request already processed path " << GetPathName() << " file " << GetFileName(); return; } if (Is404()) { - R__LOG_ERROR(QtWebDisplayLog()) << "Qt5 request FAIL path " << GetPathName() << " file " << GetFileName(); + R__LOG_ERROR(QtWebDisplayLog()) << "Qt " << QT_VERSION_STR << " request FAIL path " << GetPathName() << " file " << GetFileName(); req->fail(QWebEngineUrlRequestJob::UrlNotFound); // abort request diff --git a/gui/qt5webdisplay/rooturlschemehandler.h b/gui/qt5webdisplay/rooturlschemehandler.h index 221fc50f08fc3..2033152adbbda 100644 --- a/gui/qt5webdisplay/rooturlschemehandler.h +++ b/gui/qt5webdisplay/rooturlschemehandler.h @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * diff --git a/gui/qt5webdisplay/rootwebpage.cpp b/gui/qt5webdisplay/rootwebpage.cpp index bba86500d68ba..50dc8e723eb39 100644 --- a/gui/qt5webdisplay/rootwebpage.cpp +++ b/gui/qt5webdisplay/rootwebpage.cpp @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * diff --git a/gui/qt5webdisplay/rootwebpage.h b/gui/qt5webdisplay/rootwebpage.h index a7dfa93671b1f..a4d3b2dce84b9 100644 --- a/gui/qt5webdisplay/rootwebpage.h +++ b/gui/qt5webdisplay/rootwebpage.h @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -27,8 +27,8 @@ class RootWebPage : public QWebEnginePage { Q_OBJECT protected: int fConsole{0}; - virtual void javaScriptConsoleMessage(QWebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, - int lineNumber, const QString &sourceID); + void javaScriptConsoleMessage(QWebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, + int lineNumber, const QString &sourceID) override; public: RootWebPage(QObject *parent = nullptr); diff --git a/gui/qt5webdisplay/rootwebview.cpp b/gui/qt5webdisplay/rootwebview.cpp index 630b4d13688a5..53cf9ffee48f8 100644 --- a/gui/qt5webdisplay/rootwebview.cpp +++ b/gui/qt5webdisplay/rootwebview.cpp @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * diff --git a/gui/qt5webdisplay/rootwebview.h b/gui/qt5webdisplay/rootwebview.h index e9fe7dcf3da51..8774c47cf4583 100644 --- a/gui/qt5webdisplay/rootwebview.h +++ b/gui/qt5webdisplay/rootwebview.h @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -18,13 +18,13 @@ class RootWebView : public QWebEngineView { Q_OBJECT protected: - unsigned fWidth, fHeight; - int fX, fY; + unsigned fWidth{0}, fHeight{0}; + int fX{0}, fY{0}; - virtual void closeEvent(QCloseEvent *); + void closeEvent(QCloseEvent *) override; - virtual void dropEvent(QDropEvent* event); - virtual void dragEnterEvent( QDragEnterEvent *e ); + void dropEvent(QDropEvent *) override; + void dragEnterEvent(QDragEnterEvent *) override; public slots: void onLoadStarted(); @@ -39,7 +39,7 @@ public slots: RootWebView(QWidget *parent = nullptr, unsigned width = 0, unsigned height = 0, int x = -1, int y = -1); virtual ~RootWebView() = default; - virtual QSize sizeHint() const; + QSize sizeHint() const override; }; #endif diff --git a/gui/qt6webdisplay/CMakeLists.txt b/gui/qt6webdisplay/CMakeLists.txt index c43b17999df68..90feda69de095 100644 --- a/gui/qt6webdisplay/CMakeLists.txt +++ b/gui/qt6webdisplay/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. +# Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. # All rights reserved. # # For the licensing terms see $ROOTSYS/LICENSE. diff --git a/gui/qt6webdisplay/rootqt6.cpp b/gui/qt6webdisplay/rootqt6.cpp index cea3a8891bfde..da76e2b7e3085 100644 --- a/gui/qt6webdisplay/rootqt6.cpp +++ b/gui/qt6webdisplay/rootqt6.cpp @@ -3,7 +3,7 @@ // Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! /************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -14,7 +14,6 @@ #include #include #include -// #include #include #include @@ -40,6 +39,9 @@ #include #include +QWebEngineUrlScheme gRootScheme("rootscheme"); + + /** \class TQt6Timer \ingroup qt6webdisplay */ @@ -58,7 +60,6 @@ class TQt6Timer : public TTimer { }; namespace ROOT { -namespace Experimental { /** \class RQt6WebDisplayHandle \ingroup qt6webdisplay @@ -70,7 +71,6 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { RootWebView *fView{nullptr}; ///< pointer on widget, need to release when handle is destroyed class Qt6Creator : public Creator { - int fCounter{0}; ///< counter used to number handlers QApplication *qapp{nullptr}; ///< created QApplication int qargc{1}; ///< arg counter char *qargv[2]; ///< arg values @@ -80,7 +80,7 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { Qt6Creator() = default; - virtual ~Qt6Creator() + ~Qt6Creator() override { /** Code executed during exit and sometime crashes. * Disable it, while not clear if defaultProfile can be still used - seems to be not */ @@ -102,12 +102,6 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { // initialize web engine only before creating QApplication // QtWebEngineQuick::initialize(); - QWebEngineUrlScheme scheme("rootscheme"); - scheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort); - scheme.setDefaultPort(2345); - scheme.setFlags(QWebEngineUrlScheme::SecureScheme); - QWebEngineUrlScheme::registerScheme(scheme); - qargv[0] = gApplication->Argv(0); qargv[1] = nullptr; @@ -220,7 +214,7 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { public: RQt6WebDisplayHandle(const std::string &url) : RWebDisplayHandle(url) {} - virtual ~RQt6WebDisplayHandle() + ~RQt6WebDisplayHandle() override { // now view can be safely destroyed if (fView) { @@ -229,6 +223,14 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { } } + bool Resize(int width, int height) override + { + if (!fView) + return false; + fView->resize(QSize(width, height)); + return true; + } + static void AddCreator() { auto &entry = FindCreator("qt6"); @@ -239,8 +241,16 @@ class RQt6WebDisplayHandle : public RWebDisplayHandle { }; struct RQt6CreatorReg { - RQt6CreatorReg() { RQt6WebDisplayHandle::AddCreator(); } + RQt6CreatorReg() + { + RQt6WebDisplayHandle::AddCreator(); + + gRootScheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort); + gRootScheme.setDefaultPort(2345); + gRootScheme.setFlags(QWebEngineUrlScheme::SecureScheme); + QWebEngineUrlScheme::registerScheme(gRootScheme); + + } } newRQt6CreatorReg; -} -} +} // namespace ROOT diff --git a/gui/recorder/inc/TRecorder.h b/gui/recorder/inc/TRecorder.h index 4a6277b1aaee0..cfebe89b7e89b 100644 --- a/gui/recorder/inc/TRecorder.h +++ b/gui/recorder/inc/TRecorder.h @@ -74,7 +74,7 @@ class TRecEvent : public TObject fEventTime = t; } - ClassDef(TRecEvent,1) // Abstract class. Defines basic interface for storing information about ROOT events + ClassDefOverride(TRecEvent,1) // Abstract class. Defines basic interface for storing information about ROOT events }; @@ -108,18 +108,18 @@ class TRecCmdEvent : public TRecEvent return fText.Data(); } - virtual ERecEventType GetType() const { + ERecEventType GetType() const override { // Returns what kind of event it stores (commandline event) return TRecEvent::kCmdEvent; } - virtual void ReplayEvent(Bool_t) { + void ReplayEvent(Bool_t) override { // Stored command is executed again std::cout << GetText() << std::endl; gApplication->ProcessLine(GetText()); } - ClassDef(TRecCmdEvent,1) // Class stores information about 1 commandline event (= 1 command typed by user in commandline) + ClassDefOverride(TRecCmdEvent,1) // Class stores information about 1 commandline event (= 1 command typed by user in commandline) }; @@ -153,18 +153,18 @@ class TRecExtraEvent : public TRecEvent return fText; } - virtual ERecEventType GetType() const { + ERecEventType GetType() const override { // Returns what kind of event it stores (Especial event) return TRecEvent::kExtraEvent; } - virtual void ReplayEvent(Bool_t) { + void ReplayEvent(Bool_t) override { // Stored event is executed again gApplication->ProcessLine(GetText()); } - ClassDef(TRecExtraEvent,1) // Class stores information about extra events + ClassDefOverride(TRecExtraEvent,1) // Class stores information about extra events }; @@ -220,15 +220,15 @@ class TRecGuiEvent : public TRecEvent kROOT_MESSAGE = 10002 }; - virtual ERecEventType GetType() const { + ERecEventType GetType() const override { // Returns what kind of event it stores (GUI event) return TRecEvent::kGuiEvent; } - virtual void ReplayEvent(Bool_t showMouseCursor = kTRUE); + void ReplayEvent(Bool_t showMouseCursor = kTRUE) override; static Event_t *CreateEvent(TRecGuiEvent *ge); - ClassDef(TRecGuiEvent,1) // Class stores information about 1 GUI event in ROOT + ClassDefOverride(TRecGuiEvent,1) // Class stores information about 1 GUI event in ROOT }; @@ -258,7 +258,7 @@ class TRecWinPair : public TObject // Creates a new key-value mapping of window IDs TRecWinPair(Window_t key, Window_t value): fKey(key), fValue(value) {} - ClassDef(TRecWinPair,1) // Class used for storing of window IDs mapping. Needed for replaying events. + ClassDefOverride(TRecWinPair,1) // Class used for storing of window IDs mapping. Needed for replaying events. }; @@ -301,9 +301,9 @@ class TRecorder : public TObject TRecorder(const char *filename, Option_t *option = "READ"); // Deletes recorder together with its current state - virtual ~TRecorder(); + ~TRecorder() override; - void Browse(TBrowser *); + void Browse(TBrowser *) override; // Starts recording of events to the given file void Start(const char *filename, Option_t *option = "RECREATE", Window_t *w = nullptr, Int_t winCount = 0); @@ -338,7 +338,7 @@ class TRecorder : public TObject // Saves all the canvases previous to the TRecorder void PrevCanvases(const char *filename, Option_t *option); - ClassDef(TRecorder,2) // Class provides direct recorder/replayer interface for a user. + ClassDefOverride(TRecorder,2) // Class provides direct recorder/replayer interface for a user. }; /** \class TRecorderState @@ -395,7 +395,7 @@ Not intended to be used by a user directly. class TRecorderReplaying : public TRecorderState { private: - virtual ~TRecorderReplaying(); + ~TRecorderReplaying() override; Bool_t PrepareNextEvent(); Bool_t RemapWindowReferences(); Bool_t CanOverlap(); @@ -463,16 +463,16 @@ class TRecorderReplaying : public TRecorderState Bool_t Initialize(TRecorder *r, Bool_t showMouseCursor, TRecorder::EReplayModes mode); public: - virtual TRecorder::ERecorderState GetState() const { return TRecorder::kReplaying; } + TRecorder::ERecorderState GetState() const override { return TRecorder::kReplaying; } - virtual void Pause(TRecorder *r); + void Pause(TRecorder *r) override; virtual void Continue(); - virtual void ReplayStop(TRecorder *r); + void ReplayStop(TRecorder *r) override; void RegisterWindow(Window_t w); //SLOT void ReplayRealtime(); //SLOT - ClassDef(TRecorderReplaying, 0) // Represents state of TRecorder when replaying + ClassDefOverride(TRecorderReplaying, 0) // Represents state of TRecorder when replaying }; /** \class TRecorderRecording @@ -487,7 +487,7 @@ Not intended to be used by a user directly. class TRecorderRecording: public TRecorderState { private: - virtual ~TRecorderRecording(); + ~TRecorderRecording() override; Bool_t IsFiltered(Window_t id); void SetTypeOfConfigureNotify(Event_t *e); void CopyEvent(Event_t *e, Window_t wid); @@ -529,9 +529,9 @@ class TRecorderRecording: public TRecorderState Bool_t StartRecording(); public: - virtual TRecorder::ERecorderState GetState() const { return TRecorder::kRecording; } + TRecorder::ERecorderState GetState() const override { return TRecorder::kRecording; } - virtual void Stop(TRecorder *r, Bool_t guiCommand); + void Stop(TRecorder *r, Bool_t guiCommand) override; void RegisterWindow(Window_t w); //SLOT void RecordCmdEvent(const char *line); //SLOT @@ -546,7 +546,7 @@ class TRecorderRecording: public TRecorderState void RecordExtraEvent(TString line, TTime extTime); - ClassDef(TRecorderRecording, 0) // Represents state of TRecorder when recording events + ClassDefOverride(TRecorderRecording, 0) // Represents state of TRecorder when recording events }; /** \class TRecorderInactive @@ -567,23 +567,23 @@ class TRecorderInactive : public TRecorderState TSeqCollection *fCollect; public: - virtual ~TRecorderInactive() {} + ~TRecorderInactive() override {} TRecorderInactive() : fCollect(nullptr) {} - virtual void ListCmd(const char *filename); - virtual void ListGui(const char *filename); + void ListCmd(const char *filename) override; + void ListGui(const char *filename) override; - virtual void Start(TRecorder *r, const char *filename, Option_t *option, Window_t *w = nullptr, Int_t winCount = 0); - virtual Bool_t Replay(TRecorder *r, const char *filename, Bool_t showMouseCursor, TRecorder::EReplayModes mode); + void Start(TRecorder *r, const char *filename, Option_t *option, Window_t *w = nullptr, Int_t winCount = 0) override; + Bool_t Replay(TRecorder *r, const char *filename, Bool_t showMouseCursor, TRecorder::EReplayModes mode) override; - virtual TRecorder::ERecorderState GetState() const { return TRecorder::kInactive; } + TRecorder::ERecorderState GetState() const override { return TRecorder::kInactive; } static void DumpRootEvent(TRecGuiEvent *e, Int_t n); static long DisplayValid(Long_t n) { return ( n < 0 ? -1 : n); } - void PrevCanvases(const char *filename, Option_t *option); + void PrevCanvases(const char *filename, Option_t *option) override; - ClassDef(TRecorderInactive, 0) // Represents state of TRecorder after its creation + ClassDefOverride(TRecorderInactive, 0) // Represents state of TRecorder after its creation }; /** \class TRecorderPaused @@ -602,7 +602,7 @@ Not intended to be used by a user directly. class TRecorderPaused: public TRecorderState { private: - virtual ~TRecorderPaused() {} + ~TRecorderPaused() override {} TRecorderReplaying *fReplayingState; // Replaying that is paused @@ -611,12 +611,12 @@ class TRecorderPaused: public TRecorderState TRecorderPaused(TRecorderReplaying *state); public: - virtual TRecorder::ERecorderState GetState() const { return TRecorder::kPaused; } + TRecorder::ERecorderState GetState() const override { return TRecorder::kPaused; } - virtual void Resume(TRecorder *r); - virtual void ReplayStop(TRecorder *r); + void Resume(TRecorder *r) override; + void ReplayStop(TRecorder *r) override; - ClassDef(TRecorderPaused, 0) // Represents state of TRecorder when paused + ClassDefOverride(TRecorderPaused, 0) // Represents state of TRecorder when paused }; @@ -649,13 +649,13 @@ class TGRecorder : public TGMainFrame public: TGRecorder(const TGWindow *p = nullptr, UInt_t w = 230, UInt_t h = 150); - virtual ~TGRecorder(); + ~TGRecorder() override; void StartStop(); void Update(); void Replay(); - ClassDef(TGRecorder,0) // GUI class of the event recorder. + ClassDefOverride(TGRecorder,0) // GUI class of the event recorder. }; #endif // ROOT_TRecorder diff --git a/gui/recorder/src/TRecorder.cxx b/gui/recorder/src/TRecorder.cxx index d32c26058bca8..dd2baeeb6a8cc 100644 --- a/gui/recorder/src/TRecorder.cxx +++ b/gui/recorder/src/TRecorder.cxx @@ -138,7 +138,7 @@ class TGCursorWindow : public TGFrame { public: TGCursorWindow(); - virtual ~TGCursorWindow(); + ~TGCursorWindow() override; }; static TGCursorWindow *gCursorWin = 0; diff --git a/gui/sessionviewer/inc/TProofProgressLog.h b/gui/sessionviewer/inc/TProofProgressLog.h index 2b9233efb593f..43494d7cbdef1 100644 --- a/gui/sessionviewer/inc/TProofProgressLog.h +++ b/gui/sessionviewer/inc/TProofProgressLog.h @@ -67,7 +67,7 @@ class TProofProgressLog : public TGTransientFrame { public: TProofProgressLog(TProofProgressDialog *d, Int_t w = 700, Int_t h = 600); TProofProgressLog(const char *url = nullptr, Int_t sessionidx = 0, Int_t w = 700, Int_t h = 600); - virtual ~TProofProgressLog(); + ~TProofProgressLog() override; void BuildLogList(Bool_t create = kFALSE); void DoLog(Bool_t grep=kFALSE); @@ -79,7 +79,7 @@ class TProofProgressLog : public TGTransientFrame { void LoadFile(const char *file); - void Clear(Option_t * = nullptr); + void Clear(Option_t * = nullptr) override; void Popup(); void SaveToFile(); void NoLineEntry(); @@ -88,9 +88,9 @@ class TProofProgressLog : public TGTransientFrame { void SetUrl(const char *url) { fSessionUrl = url; } // slots - void CloseWindow(); + void CloseWindow() override; - ClassDef(TProofProgressLog,0) //Class implementing a log graphic box + ClassDefOverride(TProofProgressLog,0) //Class implementing a log graphic box }; #endif diff --git a/gui/sessionviewer/inc/TProofProgressMemoryPlot.h b/gui/sessionviewer/inc/TProofProgressMemoryPlot.h index 92436542b0d7f..5f5a08b442ced 100644 --- a/gui/sessionviewer/inc/TProofProgressMemoryPlot.h +++ b/gui/sessionviewer/inc/TProofProgressMemoryPlot.h @@ -50,13 +50,13 @@ class TProofProgressMemoryPlot : public TGTransientFrame { public: TProofProgressMemoryPlot(TProofProgressDialog *d, Int_t w = 700, Int_t h = 300); - virtual ~TProofProgressMemoryPlot(); + ~TProofProgressMemoryPlot() override; - void Clear(Option_t * = nullptr); + void Clear(Option_t * = nullptr) override; void DoPlot(); void Select(Int_t id); - ClassDef(TProofProgressMemoryPlot,0) //PROOF progress memory plots + ClassDefOverride(TProofProgressMemoryPlot,0) //PROOF progress memory plots }; #endif diff --git a/gui/sessionviewer/inc/TSessionDialogs.h b/gui/sessionviewer/inc/TSessionDialogs.h index 92a45b84cc750..e66ee569800be 100644 --- a/gui/sessionviewer/inc/TSessionDialogs.h +++ b/gui/sessionviewer/inc/TSessionDialogs.h @@ -47,7 +47,7 @@ class TNewChainDlg : public TGTransientFrame { public: TNewChainDlg(const TGWindow *p=nullptr, const TGWindow *main=nullptr); - virtual ~TNewChainDlg(); + ~TNewChainDlg() override; void UpdateList(); virtual void OnDoubleClick(TGLVEntry*,Int_t); @@ -55,10 +55,10 @@ class TNewChainDlg : public TGTransientFrame { void OnElementClicked(TGLVEntry* entry, Int_t btn); void OnElementSelected(TObject *obj); //*SIGNAL* - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); - virtual void CloseWindow(); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; + void CloseWindow() override; - ClassDef(TNewChainDlg, 0) // New chain dialog + ClassDefOverride(TNewChainDlg, 0) // New chain dialog }; ////////////////////////////////////////////////////////////////////////// @@ -91,7 +91,7 @@ class TNewQueryDlg : public TGTransientFrame { public: TNewQueryDlg(TSessionViewer *gui, Int_t Width, Int_t Height, TQueryDescription *query = nullptr, Bool_t editmode = kFALSE); - virtual ~TNewQueryDlg(); + ~TNewQueryDlg() override; void Build(TSessionViewer *gui); void OnNewQueryMore(); void OnBrowseChain(); @@ -101,13 +101,13 @@ class TNewQueryDlg : public TGTransientFrame { void OnBtnCloseClicked(); void OnBtnSubmitClicked(); void OnElementSelected(TObject *obj); - void CloseWindow(); + void CloseWindow() override; void Popup(); void SettingsChanged(); void UpdateFields(TQueryDescription *desc); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; - ClassDef(TNewQueryDlg, 0) // New query dialog + ClassDefOverride(TNewQueryDlg, 0) // New query dialog }; ////////////////////////////////////////////////////////////////////////// @@ -137,10 +137,10 @@ class TUploadDataSetDlg : public TGTransientFrame { public: TUploadDataSetDlg(TSessionViewer *gui, Int_t w, Int_t h); - virtual ~TUploadDataSetDlg(); + ~TUploadDataSetDlg() override; - virtual void CloseWindow(); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + void CloseWindow() override; + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; void AddFiles(const char *fileName); void AddFiles(TList *fileList); void BrowseFiles(); @@ -151,7 +151,7 @@ class TUploadDataSetDlg : public TGTransientFrame { void OnOverwriteFiles(Bool_t on); void OnAppendFiles(Bool_t on); - ClassDef(TUploadDataSetDlg, 0) // New query dialog + ClassDefOverride(TUploadDataSetDlg, 0) // New query dialog }; #endif diff --git a/gui/sessionviewer/inc/TSessionLogView.h b/gui/sessionviewer/inc/TSessionLogView.h index d09db076dffdc..d0a0ecf68b9dc 100644 --- a/gui/sessionviewer/inc/TSessionLogView.h +++ b/gui/sessionviewer/inc/TSessionLogView.h @@ -31,20 +31,20 @@ class TSessionLogView : public TGTransientFrame { public: TSessionLogView(TSessionViewer *viewer, UInt_t w, UInt_t h); - virtual ~TSessionLogView(); + ~TSessionLogView() override; void AddBuffer(const char *buffer); void LoadBuffer(const char *buffer); void LoadFile(const char *file); - Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; - void CloseWindow(); + void CloseWindow() override; void ClearLogView(); void Popup(); void SetTitle(); - ClassDef(TSessionLogView, 0) // PROOF progress dialog + ClassDefOverride(TSessionLogView, 0) // PROOF progress dialog }; #endif diff --git a/gui/sessionviewer/inc/TSessionViewer.h b/gui/sessionviewer/inc/TSessionViewer.h index 510d4498a97d1..62f21dd23ec2d 100644 --- a/gui/sessionviewer/inc/TSessionViewer.h +++ b/gui/sessionviewer/inc/TSessionViewer.h @@ -108,9 +108,9 @@ class TQueryDescription : public TObject { TObject *fChain; // dataset on which to process selector TQueryResult *fResult; // query result received back - const char *GetName() const { return fQueryName; } + const char *GetName() const override { return fQueryName; } - ClassDef(TQueryDescription, 1) // Query description + ClassDefOverride(TQueryDescription, 1) // Query description }; @@ -146,9 +146,9 @@ class TSessionDescription : public TObject { TProofMgr *fProofMgr; // Proof sessions manager Int_t fNbHistos; // number of feedback histos - const char *GetName() const { return fName; } + const char *GetName() const override { return fName; } - ClassDef(TSessionDescription, 1) // Session description + ClassDefOverride(TSessionDescription, 1) // Session description }; ////////////////////////////////////////////////////////////////////////// @@ -164,9 +164,9 @@ class TPackageDescription : public TObject { Bool_t fUploaded; // package has been uploaded Bool_t fEnabled; // package has been enabled - const char *GetName() const { return fName; } + const char *GetName() const override { return fName; } - ClassDef(TPackageDescription, 1) // Package description + ClassDefOverride(TPackageDescription, 1) // Package description }; ////////////////////////////////////////////////////////////////////////// @@ -194,11 +194,11 @@ class TSessionServerFrame : public TGCompositeFrame { public: TSessionServerFrame(TGWindow *parent, Int_t w, Int_t h); - virtual ~TSessionServerFrame(); + ~TSessionServerFrame() override; void Build(TSessionViewer *gui); - const char *GetName() const { return fTxtName->GetText(); } + const char *GetName() const override { return fTxtName->GetText(); } const char *GetAddress() const { return fTxtAddress->GetText(); } Int_t GetPortNumber() const { return fNumPort->GetIntNumber(); } Int_t GetLogLevel() const { return fLogLevel->GetIntNumber(); } @@ -210,7 +210,7 @@ class TSessionServerFrame : public TGCompositeFrame { on == kTRUE ? ShowFrame(fBtnAdd) : HideFrame(fBtnAdd); } void SetConnectEnabled(Bool_t on = kTRUE) { on == kTRUE ? ShowFrame(fBtnConnect) : HideFrame(fBtnConnect); } - void SetName(const char *str) { fTxtName->SetText(str); } + void SetName(const char *str) override { fTxtName->SetText(str); } void SetAddress(const char *str) { fTxtAddress->SetText(str); } void SetPortNumber(Int_t port) { fNumPort->SetIntNumber(port); } void SetLogLevel(Int_t log) { fLogLevel->SetIntNumber(log); } @@ -227,10 +227,10 @@ class TSessionServerFrame : public TGCompositeFrame { void OnBtnAddClicked(); void OnConfigFileClicked(); void Update(TSessionDescription* desc); - virtual Bool_t HandleExpose(Event_t *event); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2); + Bool_t HandleExpose(Event_t *event) override; + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t parm2) override; - ClassDef(TSessionServerFrame, 0) // Server frame + ClassDefOverride(TSessionServerFrame, 0) // Server frame }; @@ -289,7 +289,7 @@ class TSessionFrame : public TGCompositeFrame { public: TSessionFrame(TGWindow* parent, Int_t w, Int_t h); - virtual ~TSessionFrame(); + ~TSessionFrame() override; void Build(TSessionViewer *gui); void CheckAutoEnPack(Bool_t checked = kTRUE) { @@ -325,7 +325,7 @@ class TSessionFrame : public TGCompositeFrame { void OnBtnVerifyDSet(); void UpdateListOfDataSets(); - ClassDef(TSessionFrame, 0) // Session frame + ClassDefOverride(TSessionFrame, 0) // Session frame }; ////////////////////////////////////////////////////////////////////////// @@ -352,7 +352,7 @@ class TEditQueryFrame : public TGCompositeFrame { public: TEditQueryFrame(TGWindow* p, Int_t w, Int_t h); - virtual ~TEditQueryFrame(); + ~TEditQueryFrame() override; void Build(TSessionViewer *gui); void OnNewQueryMore(); void OnBrowseChain(); @@ -363,7 +363,7 @@ class TEditQueryFrame : public TGCompositeFrame { void SettingsChanged(); void UpdateFields(TQueryDescription *desc); - ClassDef(TEditQueryFrame, 0) // Edit query frame + ClassDefOverride(TEditQueryFrame, 0) // Edit query frame }; ////////////////////////////////////////////////////////////////////////// @@ -411,7 +411,7 @@ class TSessionQueryFrame : public TGCompositeFrame { public: TSessionQueryFrame(TGWindow* parent, Int_t w, Int_t h); - virtual ~TSessionQueryFrame(); + ~TSessionQueryFrame() override; void Build(TSessionViewer *gui); @@ -445,7 +445,7 @@ class TSessionQueryFrame : public TGCompositeFrame { void UpdateButtons(TQueryDescription *desc); void UpdateHistos(TList *objs); - ClassDef(TSessionQueryFrame, 0) // Query frame + ClassDefOverride(TSessionQueryFrame, 0) // Query frame }; ////////////////////////////////////////////////////////////////////////// @@ -465,16 +465,16 @@ class TSessionOutputFrame : public TGCompositeFrame { public: TSessionOutputFrame(TGWindow* parent, Int_t w, Int_t h); - virtual ~TSessionOutputFrame(); + ~TSessionOutputFrame() override; void AddObject(TObject *obj); void Build(TSessionViewer *gui); TGLVContainer *GetLVContainer() { return fLVContainer; } void OnElementClicked(TGLVEntry* entry, Int_t btn, Int_t x, Int_t y); void OnElementDblClicked(TGLVEntry *entry ,Int_t btn, Int_t x, Int_t y); - void RemoveAll() { fLVContainer->RemoveAll(); } + void RemoveAll() override { fLVContainer->RemoveAll(); } - ClassDef(TSessionOutputFrame, 0) // Output frame + ClassDefOverride(TSessionOutputFrame, 0) // Output frame }; ////////////////////////////////////////////////////////////////////////// @@ -493,14 +493,14 @@ class TSessionInputFrame : public TGCompositeFrame { public: TSessionInputFrame(TGWindow* parent, Int_t w, Int_t h); - virtual ~TSessionInputFrame(); + ~TSessionInputFrame() override; void AddObject(TObject *obj); void Build(TSessionViewer *gui); - void RemoveAll() { fLVContainer->RemoveAll(); } + void RemoveAll() override { fLVContainer->RemoveAll(); } TGLVContainer *GetLVContainer() { return fLVContainer; } - ClassDef(TSessionInputFrame, 0) // Input frame + ClassDefOverride(TSessionInputFrame, 0) // Input frame }; @@ -567,9 +567,9 @@ class TSessionViewer : public TGMainFrame { TSessionViewer(const char *title = "ROOT Session Viewer", UInt_t w = 550, UInt_t h = 320); TSessionViewer(const char *title, Int_t x, Int_t y, UInt_t w, UInt_t h); - virtual ~TSessionViewer(); + ~TSessionViewer() override; virtual void Build(); - virtual Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t); + Bool_t ProcessMessage(Longptr_t msg, Longptr_t parm1, Longptr_t) override; TSessionServerFrame *GetServerFrame() const { return fServerFrame; } TSessionFrame *GetSessionFrame() const { return fSessionFrame; } @@ -596,11 +596,11 @@ class TSessionViewer : public TGMainFrame { void ChangeRightLogo(const char *name); void CleanupSession(); - void CloseWindow(); + void CloseWindow() override; void DisableTimer(); void EditQuery(); void EnableTimer(); - Bool_t HandleTimer(TTimer *); + Bool_t HandleTimer(TTimer *) override; Bool_t IsBusy() const { return fBusy; } Bool_t IsAutoSave() const { return fAutoSave; } void LogMessage(const char *msg, Bool_t all); @@ -628,7 +628,7 @@ class TSessionViewer : public TGMainFrame { void StartViewer(); void Terminate(); - ClassDef(TSessionViewer, 0) // Session Viewer + ClassDefOverride(TSessionViewer, 0) // Session Viewer }; R__EXTERN TSessionViewer *gSessionViewer; diff --git a/gui/webdisplay/inc/LinkDef.h b/gui/webdisplay/inc/LinkDef.h index 1e631a9fcd533..650c37981931c 100644 --- a/gui/webdisplay/inc/LinkDef.h +++ b/gui/webdisplay/inc/LinkDef.h @@ -12,9 +12,9 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class ROOT::Experimental::RWebDisplayArgs+; -#pragma link C++ class ROOT::Experimental::RWebDisplayHandle+; -#pragma link C++ class ROOT::Experimental::RWebWindow+; -#pragma link C++ class ROOT::Experimental::RWebWindowsManager+; +#pragma link C++ class ROOT::RWebDisplayArgs+; +#pragma link C++ class ROOT::RWebDisplayHandle+; +#pragma link C++ class ROOT::RWebWindow+; +#pragma link C++ class ROOT::RWebWindowsManager+; #endif diff --git a/gui/webdisplay/inc/ROOT/RWebDisplayArgs.hxx b/gui/webdisplay/inc/ROOT/RWebDisplayArgs.hxx index 0fb8cca654882..043fbfb22c6bd 100644 --- a/gui/webdisplay/inc/ROOT/RWebDisplayArgs.hxx +++ b/gui/webdisplay/inc/ROOT/RWebDisplayArgs.hxx @@ -19,11 +19,14 @@ class THttpServer; namespace ROOT { -namespace Experimental { +namespace Experimental { class RLogChannel; +} // namespace Experimental + /// Log channel for WebGUI diagnostics. -RLogChannel &WebGUILog(); +ROOT::Experimental::RLogChannel &WebGUILog(); + class RWebWindow; @@ -68,6 +71,7 @@ protected: void *fDriverData{nullptr}; /// fMaster; /// master, int channel = -1); + RWebDisplayArgs(std::shared_ptr master, unsigned conndid = 0, int channel = -1); virtual ~RWebDisplayArgs(); @@ -93,7 +97,7 @@ public: EBrowserKind GetBrowserKind() const { return fKind; } std::string GetBrowserName() const; - void SetMasterWindow(std::shared_ptr master, int channel = -1); + void SetMasterWindow(std::shared_ptr master, unsigned connid = 0, int channel = -1); /// returns true if interactive browser window supposed to be started bool IsInteractiveBrowser() const @@ -206,10 +210,9 @@ public: /// [internal] returns web-driver data, used to start window void *GetDriverData() const { return fDriverData; } - static std::string GetQt5EmbedQualifier(const void *qparent, const std::string &urlopt = ""); + static std::string GetQt5EmbedQualifier(const void *qparent, const std::string &urlopt = "", unsigned qtversion = 0x50000); }; -} -} +} // namespace ROOT #endif diff --git a/gui/webdisplay/inc/ROOT/RWebDisplayHandle.hxx b/gui/webdisplay/inc/ROOT/RWebDisplayHandle.hxx index f0aa2572ebdbb..16a03735f895c 100644 --- a/gui/webdisplay/inc/ROOT/RWebDisplayHandle.hxx +++ b/gui/webdisplay/inc/ROOT/RWebDisplayHandle.hxx @@ -18,9 +18,9 @@ #include #include #include +#include namespace ROOT { -namespace Experimental { class RWebDisplayHandle { @@ -55,7 +55,7 @@ protected: std::unique_ptr Display(const RWebDisplayArgs &args) override; - virtual ~BrowserCreator() = default; + ~BrowserCreator() override = default; }; class ChromeCreator : public BrowserCreator { @@ -63,7 +63,7 @@ protected: std::string fEnvPrefix; // rc parameters prefix public: ChromeCreator(bool is_edge = false); - virtual ~ChromeCreator() = default; + ~ChromeCreator() override = default; bool IsActive() const override { return !fProg.empty(); } void ProcessGeometry(std::string &, const RWebDisplayArgs &args) override; std::string MakeProfile(std::string &exec, bool) override; @@ -72,7 +72,7 @@ protected: class FirefoxCreator : public BrowserCreator { public: FirefoxCreator(); - virtual ~FirefoxCreator() = default; + ~FirefoxCreator() override = default; bool IsActive() const override { return !fProg.empty(); } std::string MakeProfile(std::string &exec, bool batch) override; }; @@ -81,6 +81,8 @@ protected: static std::unique_ptr &FindCreator(const std::string &name, const std::string &libname = ""); + static bool CheckIfCanProduceImages(RWebDisplayArgs &args); + public: /// constructor @@ -97,14 +99,20 @@ public: /// get content const std::string &GetContent() const { return fContent; } + /// resize web window - if possible + virtual bool Resize(int, int) { return false; } + static std::unique_ptr Display(const RWebDisplayArgs &args); static bool DisplayUrl(const std::string &url); + static bool CanProduceImages(const std::string &browser = ""); + static bool ProduceImage(const std::string &fname, const std::string &json, int width = 800, int height = 600, const char *batch_file = nullptr); + + static bool ProduceImages(const std::string &fname, const std::vector &jsons, const std::vector &widths, const std::vector &heights, const char *batch_file = nullptr); }; -} -} +} // namespace ROOT #endif diff --git a/gui/webdisplay/inc/ROOT/RWebWindow.hxx b/gui/webdisplay/inc/ROOT/RWebWindow.hxx index 1835065bdaf18..234cb8a637686 100644 --- a/gui/webdisplay/inc/ROOT/RWebWindow.hxx +++ b/gui/webdisplay/inc/ROOT/RWebWindow.hxx @@ -29,8 +29,6 @@ class THttpCallArg; class THttpServer; namespace ROOT { -namespace Experimental { - /// function signature for connect/disconnect call-backs /// argument is connection id @@ -47,6 +45,7 @@ using WebWindowDataCallback_t = std::function; +class RFileDialog; class RWebWindowsManager; class RWebWindowWSHandler; @@ -55,6 +54,7 @@ class RWebWindow { friend class RWebWindowsManager; friend class RWebWindowWSHandler; friend class RWebDisplayHandle; + friend class RFileDialog; private: using timestamp_t = std::chrono::time_point; @@ -110,6 +110,12 @@ private: } }; + struct MasterConn { + unsigned connid{0}; + int channel{-1}; + MasterConn(unsigned _connid, int _channel) : connid(_connid), channel(_channel) {} + }; + enum EQueueEntryKind { kind_None, kind_Connect, kind_Data, kind_Disconnect }; struct QueueEntry { @@ -124,12 +130,12 @@ private: std::shared_ptr fMgr; /// fMaster; /// fMasterConns; /// fWSHandler; /// fInputQueue; /// fClearOnClose; /// CreateWSHandler(std::shared_ptr mgr, unsigned id, double tmout); @@ -167,7 +174,7 @@ private: void CompleteWSSend(unsigned wsid); - ConnectionsList_t GetConnections(unsigned connid = 0, bool only_active = false) const; + ConnectionsList_t GetWindowConnections(unsigned connid = 0, bool only_active = false) const; std::shared_ptr FindOrCreateConnection(unsigned wsid, bool make_new, const char *query); @@ -200,10 +207,16 @@ private: unsigned AddDisplayHandle(bool headless_mode, const std::string &key, std::unique_ptr &handle); - unsigned AddEmbedWindow(std::shared_ptr window, int channel); + unsigned AddEmbedWindow(std::shared_ptr window, unsigned connid, int channel); void RemoveEmbedWindow(unsigned connid, int channel); + void AddMasterConnection(std::shared_ptr window, unsigned connid, int channel); + + std::vector GetMasterConnections(unsigned connid = 0) const; + + void RemoveMasterConnection(unsigned connid = 0); + bool ProcessBatchHolder(std::shared_ptr &arg); std::string GetConnToken() const; @@ -212,7 +225,9 @@ private: unsigned FindHeadlessConnection(); - void CheckThreadAssign(); + static std::function &, unsigned, const std::string &)> gStartDialogFunc; + + static void SetStartDialogFunc(std::function &, unsigned, const std::string &)>); public: @@ -241,6 +256,13 @@ public: fHeight = height; } + /// Set window position. Will be applied if supported by used web display (like CEF or Chromium) + void SetPosition(unsigned x, unsigned y) + { + fX = x; + fY = y; + } + ///////////////////////////////////////////////////////////////////////// /// returns configured window width (0 - default) /// actual window width can be different @@ -250,6 +272,14 @@ public: /// returns configured window height (0 - default) unsigned GetHeight() const { return fHeight; } + ///////////////////////////////////////////////////////////////////////// + /// returns configured window X position (-1 - default) + int GetX() const { return fX; } + + ///////////////////////////////////////////////////////////////////////// + /// returns configured window Y position (-1 - default) + int GetY() const { return fY; } + void SetConnLimit(unsigned lmt = 0); unsigned GetConnLimit() const; @@ -284,6 +314,8 @@ public: unsigned GetConnectionId(int num = 0) const; + std::vector GetConnections(unsigned excludeid = 0) const; + bool HasConnection(unsigned connid = 0, bool only_active = true) const; void CloseConnections(); @@ -337,6 +369,8 @@ public: void SetDisconnectCallBack(WebWindowConnectCallback_t func); + void SetClearOnClose(const std::shared_ptr &handle = nullptr); + void AssignThreadId(); void UseServerThreads(); @@ -357,9 +391,11 @@ public: static unsigned ShowWindow(std::shared_ptr window, const RWebDisplayArgs &args = ""); + static bool IsFileDialogMessage(const std::string &msg); + + static bool EmbedFileDialog(const std::shared_ptr &window, unsigned connid, const std::string &args); }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/webdisplay/inc/ROOT/RWebWindowsManager.hxx b/gui/webdisplay/inc/ROOT/RWebWindowsManager.hxx index 9ab1906e69edf..a580c8fba1d8c 100644 --- a/gui/webdisplay/inc/ROOT/RWebWindowsManager.hxx +++ b/gui/webdisplay/inc/ROOT/RWebWindowsManager.hxx @@ -28,7 +28,6 @@ class THttpWSHandler; class TExec; namespace ROOT { -namespace Experimental { /// function signature for catching show calls of arbitrary RWebWindow /// if returns true, normal show procedure will not be invoked @@ -70,8 +69,6 @@ private: bool CreateServer(bool with_http = false); - void AssignWindowThreadId(RWebWindow &win); - bool InformListener(const std::string &msg); public: @@ -98,7 +95,6 @@ public: static void AssignMainThrd(); }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/webdisplay/src/RWebDisplayArgs.cxx b/gui/webdisplay/src/RWebDisplayArgs.cxx index 033d6ddf06cb6..2de8f1918ee04 100644 --- a/gui/webdisplay/src/RWebDisplayArgs.cxx +++ b/gui/webdisplay/src/RWebDisplayArgs.cxx @@ -19,16 +19,16 @@ #include "TROOT.h" #include -using namespace ROOT::Experimental; +using namespace ROOT; -RLogChannel &ROOT::Experimental::WebGUILog() +ROOT::Experimental::RLogChannel &ROOT::WebGUILog() { - static RLogChannel sLog("ROOT.WebGUI"); + static ROOT::Experimental::RLogChannel sLog("ROOT.WebGUI"); return sLog; } -/** \class ROOT::Experimental::RWebDisplayArgs +/** \class ROOT::RWebDisplayArgs \ingroup webdisplay Holds different arguments for starting browser with RWebDisplayHandle::Display() method @@ -79,9 +79,9 @@ RWebDisplayArgs::RWebDisplayArgs(int width, int height, int x, int y, const std: /// Constructor. /// Let specify master window and channel (if reserved already) -RWebDisplayArgs::RWebDisplayArgs(std::shared_ptr master, int channel) +RWebDisplayArgs::RWebDisplayArgs(std::shared_ptr master, unsigned conndid, int channel) { - SetMasterWindow(master, channel); + SetMasterWindow(master, conndid, channel); } /////////////////////////////////////////////////////////////////////////////////////////// @@ -265,12 +265,13 @@ std::string RWebDisplayArgs::GetBrowserName() const } /////////////////////////////////////////////////////////////////////////////////////////// -/// Assign window and channel id where other window will be embed +/// Assign window, connection and channel id where other window will be embed -void RWebDisplayArgs::SetMasterWindow(std::shared_ptr master, int channel) +void RWebDisplayArgs::SetMasterWindow(std::shared_ptr master, unsigned connid, int channel) { SetBrowserKind(kEmbedded); fMaster = master; + fMasterConnection = connid; fMasterChannel = channel; } @@ -338,15 +339,15 @@ std::string RWebDisplayArgs::GetCustomExec() const /////////////////////////////////////////////////////////////////////////////////////////// /// Returns string which can be used as argument in RWebWindow::Show() method -/// to display web window in provided QWidget. +/// to display web window in provided Qt5 QWidget. /// /// After RWebWindow is displayed created QWebEngineView can be found with the command: /// /// auto view = qparent->findChild("RootWebView"); -std::string RWebDisplayArgs::GetQt5EmbedQualifier(const void *qparent, const std::string &urlopt) +std::string RWebDisplayArgs::GetQt5EmbedQualifier(const void *qparent, const std::string &urlopt, unsigned qtversion) { - std::string where = "qt5"; + std::string where = (qtversion >= 0x60000) ? "qt6" : "qt5"; if (qparent) { where.append(":"); where.append(std::to_string((uintptr_t) qparent)); @@ -357,4 +358,3 @@ std::string RWebDisplayArgs::GetQt5EmbedQualifier(const void *qparent, const std } return where; } - diff --git a/gui/webdisplay/src/RWebDisplayHandle.cxx b/gui/webdisplay/src/RWebDisplayHandle.cxx index 53e581156d54d..aa38250a5c0bf 100644 --- a/gui/webdisplay/src/RWebDisplayHandle.cxx +++ b/gui/webdisplay/src/RWebDisplayHandle.cxx @@ -21,8 +21,10 @@ #include "TObjArray.h" #include "THttpServer.h" #include "TEnv.h" +#include "TError.h" #include "TROOT.h" #include "TBase64.h" +#include "TBufferJSON.h" #include #include @@ -38,10 +40,10 @@ #include #endif -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; -/** \class ROOT::Experimental::RWebDisplayHandle +/** \class ROOT::RWebDisplayHandle \ingroup webdisplay Handle of created web-based display @@ -92,7 +94,6 @@ std::unique_ptr &RWebDisplayHandle::FindCreator(cons } namespace ROOT { -namespace Experimental { ////////////////////////////////////////////////////////////////////////////////////////////////// /// Specialized handle to hold information about running browser process @@ -120,7 +121,7 @@ class RWebBrowserHandle : public RWebDisplayHandle { { } - virtual ~RWebBrowserHandle() + ~RWebBrowserHandle() override { #ifdef _MSC_VER if (fHasPid) @@ -137,7 +138,6 @@ class RWebBrowserHandle : public RWebDisplayHandle { }; -} // namespace Experimental } // namespace ROOT ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -329,7 +329,7 @@ RWebDisplayHandle::BrowserCreator::Display(const RWebDisplayArgs &args) R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in " << fProg << " with:\n" << exec; - _spawnv(_P_NOWAIT, fProg.c_str(), argv.data()); + _spawnv(_P_NOWAIT, gSystem->UnixPathName(fProg.c_str()), argv.data()); return std::make_unique(url, rmdir, ""s); } @@ -395,15 +395,17 @@ RWebDisplayHandle::ChromeCreator::ChromeCreator(bool _edge) : BrowserCreator(tru TestProg("/usr/bin/chromium"); TestProg("/usr/bin/chromium-browser"); TestProg("/usr/bin/chrome-browser"); + TestProg("/usr/bin/google-chrome-stable"); + TestProg("/usr/bin/google-chrome"); #endif #ifdef _MSC_VER fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless $geometry $url"); - fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "$prog --headless --disable-gpu $geometry $url &"); + fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "$prog --headless --disable-gpu $geometry \"$url\" --dump-dom &"); fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=$url &"); // & in windows mean usage of spawn #else fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless --no-sandbox --no-zygote --disable-extensions --disable-gpu --disable-audio-output $geometry $url"); - fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork: --headless --no-sandbox --no-zygote --disable-extensions --disable-gpu --disable-audio-output $geometry $url"); + fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "$prog --headless --no-sandbox --no-zygote --disable-extensions --disable-gpu --disable-audio-output $geometry \'$url\' --dump-dom >/dev/null &"); fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=\'$url\' &"); #endif } @@ -483,6 +485,7 @@ RWebDisplayHandle::FirefoxCreator::FirefoxCreator() : BrowserCreator(true) #endif #ifdef R__LINUX TestProg("/usr/bin/firefox"); + TestProg("/usr/bin/firefox-bin"); #endif #ifdef _MSC_VER @@ -649,26 +652,120 @@ bool RWebDisplayHandle::DisplayUrl(const std::string &url) return !!handle; } +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Checks if configured browser can be used for image production + +bool RWebDisplayHandle::CheckIfCanProduceImages(RWebDisplayArgs &args) +{ + if ((args.GetBrowserKind() != RWebDisplayArgs::kFirefox) && (args.GetBrowserKind() != RWebDisplayArgs::kEdge) && + (args.GetBrowserKind() != RWebDisplayArgs::kChrome) && (args.GetBrowserKind() != RWebDisplayArgs::kCEF) && + (args.GetBrowserKind() != RWebDisplayArgs::kQt5) && (args.GetBrowserKind() != RWebDisplayArgs::kQt6)) { + bool detected = false; + + auto &h1 = FindCreator("chrome", "ChromeCreator"); + if (h1 && h1->IsActive()) { + args.SetBrowserKind(RWebDisplayArgs::kChrome); + detected = true; + } + + if (!detected) { + auto &h2 = FindCreator("firefox", "FirefoxCreator"); + if (h2 && h2->IsActive()) { + args.SetBrowserKind(RWebDisplayArgs::kFirefox); + detected = true; + } + } + +#ifdef _MSC_VER + if (!detected) { + auto &h3 = FindCreator("edge", "ChromeCreator"); + if (h3 && h3->IsActive()) { + args.SetBrowserKind(RWebDisplayArgs::kEdge); + detected = true; + } + } +#endif + return detected; + } + + if (args.GetBrowserKind() == RWebDisplayArgs::kChrome) { + auto &h1 = FindCreator("chrome", "ChromeCreator"); + return h1 && h1->IsActive(); + } + + if (args.GetBrowserKind() == RWebDisplayArgs::kFirefox) { + auto &h2 = FindCreator("firefox", "FirefoxCreator"); + return h2 && h2->IsActive(); + } + +#ifdef _MSC_VER + if (args.GetBrowserKind() == RWebDisplayArgs::kEdge) { + auto &h3 = FindCreator("edge", "ChromeCreator"); + return h3 && h3->IsActive(); + } +#endif + + return true; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Returns true if image production for specified browser kind is supported +/// If browser not specified - use currently configured browser or try to test existing web browsers + +bool RWebDisplayHandle::CanProduceImages(const std::string &browser) +{ + RWebDisplayArgs args(browser); + + return CheckIfCanProduceImages(args); +} /////////////////////////////////////////////////////////////////////////////////////////////////// /// Produce image file using JSON data as source /// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox - bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string &json, int width, int height, const char *batch_file) { - if (json.empty()) + return ProduceImages(fname, {json}, {width}, {height}, batch_file); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +/// Produce image file(s) using JSON data as source +/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox +bool RWebDisplayHandle::ProduceImages(const std::string &fname, const std::vector &jsons, const std::vector &widths, const std::vector &heights, const char *batch_file) +{ + if (jsons.empty()) return false; std::string _fname = fname; std::transform(_fname.begin(), _fname.end(), _fname.begin(), ::tolower); - - auto EndsWith = [_fname](const std::string &suffix) { - return (_fname.length() > suffix.length()) ? (0 == _fname.compare (_fname.length() - suffix.length(), suffix.length(), suffix)) : false; + auto EndsWith = [&_fname](const std::string &suffix) { + return (_fname.length() > suffix.length()) ? (0 == _fname.compare(_fname.length() - suffix.length(), suffix.length(), suffix)) : false; }; + std::vector fnames; + + if (!EndsWith(".pdf")) { + bool has_quialifier = _fname.find("%") != std::string::npos; + + if (!has_quialifier && (jsons.size() > 1)) { + _fname.insert(_fname.rfind("."), "%d"); + has_quialifier = true; + } + + for (unsigned n = 0; n < jsons.size(); n++) { + if (has_quialifier) { + auto expand_name = TString::Format(_fname.c_str(), (int) n); + fnames.emplace_back(expand_name.Data()); + } else { + fnames.emplace_back(_fname); + } + } + } + if (EndsWith(".json")) { - std::ofstream ofs(fname); - ofs << json; + for (unsigned n = 0; n < jsons.size(); ++n) { + std::ofstream ofs(fnames[n]); + ofs << jsons[n]; + } return true; } @@ -683,17 +780,21 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string jsrootsys = jsrootsysdflt.Data(); } - RWebDisplayArgs args; // set default browser kind, only Chrome or Firefox or CEF or Qt5 can be used here - if ((args.GetBrowserKind() != RWebDisplayArgs::kFirefox ) && (args.GetBrowserKind() != RWebDisplayArgs::kCEF) && - (args.GetBrowserKind() != RWebDisplayArgs::kQt5) && (args.GetBrowserKind() != RWebDisplayArgs::kQt6)) - args.SetBrowserKind(RWebDisplayArgs::kChrome); + RWebDisplayArgs args; // set default browser kind, only Chrome/Firefox/Edge or CEF/Qt5/Qt6 can be used here + if (!CheckIfCanProduceImages(args)) { + R__LOG_ERROR(WebGUILog()) << "Fail to detect supported browsers for image production"; + return false; + } + + auto isChromeBased = (args.GetBrowserKind() == RWebDisplayArgs::kChrome) || (args.GetBrowserKind() == RWebDisplayArgs::kEdge), + isFirefox = args.GetBrowserKind() == RWebDisplayArgs::kFirefox; std::string draw_kind; if (EndsWith(".pdf")) draw_kind = "draw"; // not a JSROOT drawing but Chrome capability to create PDF out of HTML page is used - else if (EndsWith("shot.png")) - draw_kind = (args.GetBrowserKind() == RWebDisplayArgs::kChrome) ? "draw" : "png"; + else if (EndsWith("shot.png") && (jsons.size() == 1)) + draw_kind = isChromeBased ? "draw" : "png"; // using screenshot else if (EndsWith(".svg")) draw_kind = "svg"; else if (EndsWith(".png")) @@ -720,25 +821,45 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string return false; } - filecont = std::regex_replace(filecont, std::regex("\\$draw_width"), std::to_string(width)); - filecont = std::regex_replace(filecont, std::regex("\\$draw_height"), std::to_string(height)); + int max_width = 0, max_height = 0, page_margin = 10; + for (auto &w : widths) + if (w > max_width) + max_width = w; + for (auto &h : heights) + if (h > max_height) + max_height = h; + + auto jsonw = TBufferJSON::ToJSON(&widths, TBufferJSON::kNoSpaces); + auto jsonh = TBufferJSON::ToJSON(&heights, TBufferJSON::kNoSpaces); + + std::string mains; + for (auto &json : jsons) { + mains.append(mains.empty() ? "[" : ", "); + mains.append(json); + } + mains.append("]"); if (strstr(jsrootsys,"http://") || strstr(jsrootsys,"https://") || strstr(jsrootsys,"file://")) filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), jsrootsys); else filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), "file://"s + jsrootsys); - filecont = std::regex_replace(filecont, std::regex("\\$draw_kind"), draw_kind); + filecont = std::regex_replace(filecont, std::regex("\\$page_margin"), std::to_string(page_margin) + "px"); + filecont = std::regex_replace(filecont, std::regex("\\$page_width"), std::to_string(max_width + 2*page_margin) + "px"); + filecont = std::regex_replace(filecont, std::regex("\\$page_height"), std::to_string(max_height + 2*page_margin) + "px"); - filecont = std::regex_replace(filecont, std::regex("\\$draw_object"), json); + filecont = std::regex_replace(filecont, std::regex("\\$draw_kind"), draw_kind); + filecont = std::regex_replace(filecont, std::regex("\\$draw_widths"), jsonw.Data()); + filecont = std::regex_replace(filecont, std::regex("\\$draw_heights"), jsonh.Data()); + filecont = std::regex_replace(filecont, std::regex("\\$draw_objects"), mains); TString dump_name; if (draw_kind == "draw") { - if (args.GetBrowserKind() != RWebDisplayArgs::kChrome) { - R__LOG_ERROR(WebGUILog()) << "Creation of PDF files supported only by Chrome browser"; + if (!isChromeBased) { + R__LOG_ERROR(WebGUILog()) << "Creation of PDF files supported only by Chrome-based browser"; return false; } - } else if ((args.GetBrowserKind() == RWebDisplayArgs::kChrome) || (args.GetBrowserKind() == RWebDisplayArgs::kFirefox)) { + } else if (isChromeBased || isFirefox) { dump_name = "canvasdump"; FILE *df = gSystem->TempFileName(dump_name); if (!df) { @@ -764,7 +885,7 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string tmp_name.Clear(); html_name.Clear(); - R__LOG_DEBUG(0, WebGUILog()) << "Using file content_len " << filecont.length() << " to produce batch image " << fname; + R__LOG_DEBUG(0, WebGUILog()) << "Using file content_len " << filecont.length() << " to produce batch images " << fname; } else { tmp_name = "canvasbody"; @@ -802,34 +923,37 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string args.SetUrl("file://"s + gSystem->UnixPathName(html_name.Data())); args.SetPageContent(""s); - R__LOG_DEBUG(0, WebGUILog()) << "Using " << html_name << " content_len " << filecont.length() << " to produce batch image " << fname; + R__LOG_DEBUG(0, WebGUILog()) << "Using " << html_name << " content_len " << filecont.length() << " to produce batch images " << fname; } - TString tgtfilename = fname.c_str(); - if (!gSystem->IsAbsoluteFileName(tgtfilename.Data())) - gSystem->PrependPathName(gSystem->WorkingDirectory(), tgtfilename); - TString wait_file_name; args.SetStandalone(true); args.SetHeadless(true); args.SetBatchMode(true); - args.SetSize(width, height); + args.SetSize(widths[0], heights[0]); if (draw_kind == "draw") { + TString tgtfilename = fname.c_str(); + if (!gSystem->IsAbsoluteFileName(tgtfilename.Data())) + gSystem->PrependPathName(gSystem->WorkingDirectory(), tgtfilename); + wait_file_name = tgtfilename; if (EndsWith(".pdf")) - args.SetExtraArgs("--print-to-pdf="s + gSystem->UnixPathName(tgtfilename.Data())); + args.SetExtraArgs("--print-to-pdf-no-header --print-to-pdf="s + gSystem->UnixPathName(tgtfilename.Data())); else args.SetExtraArgs("--screenshot="s + gSystem->UnixPathName(tgtfilename.Data())); - } else if (args.GetBrowserKind() == RWebDisplayArgs::kFirefox) { + // remove target image file - we use it as detection when chrome is ready + gSystem->Unlink(tgtfilename.Data()); + + } else if (isFirefox) { // firefox will use window.dump to output produced result args.SetRedirectOutput(dump_name.Data()); gSystem->Unlink(dump_name.Data()); - } else if (args.GetBrowserKind() == RWebDisplayArgs::kChrome) { + } else if (isChromeBased) { // require temporary output file args.SetExtraArgs("--dump-dom"); args.SetRedirectOutput(dump_name.Data()); @@ -839,9 +963,6 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string gSystem->Unlink(dump_name.Data()); } - // remove target image file - we use it as detection when chrome is ready - gSystem->Unlink(tgtfilename.Data()); - auto handle = RWebDisplayHandle::Display(args); if (!handle) { @@ -862,7 +983,7 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string auto dumpcont = handle->GetContent(); - if ((dumpcont.length() > 20) && (dumpcont.length() < 60) && !chrome_tmp_workaround && (args.GetBrowserKind() == RWebDisplayArgs::kChrome)) { + if ((dumpcont.length() > 20) && (dumpcont.length() < 60) && !chrome_tmp_workaround && isChromeBased) { // chrome creates dummy html file with mostly no content // problem running chrome from /tmp directory, lets try work from home directory chrome_tmp_workaround = true; @@ -875,38 +996,57 @@ bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string } if (draw_kind == "svg") { - auto p1 = dumpcont.find(""); - std::ofstream ofs(tgtfilename); - if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) { - ofs << dumpcont.substr(p1,p2-p1+6); - } else { - R__LOG_ERROR(WebGUILog()) << "Fail to extract SVG from HTML dump " << dump_name; - ofs << "Failure!!!\n" << dumpcont; - return false; + std::string::size_type p = 0; + + for (auto & fn : fnames) { + auto p1 = dumpcont.find("
", p1 + 4); + p = p2 + 6; + std::ofstream ofs(fn); + if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) { + ofs << dumpcont.substr(p1, p2-p1+6); + ::Info("ProduceImage", "SVG file %s size %d bytes has been created", fn.c_str(), (int) (p2-p1+6)); + } else { + R__LOG_ERROR(WebGUILog()) << "Fail to extract SVG from HTML dump " << dump_name; + ofs << "Failure!!!\n" << dumpcont; + return false; + } } } else { - auto p1 = dumpcont.rfind(";base64,"); - auto p2 = dumpcont.rfind(">
"); + std::string::size_type p = 0; - if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) { + for (auto &fn : fnames) { - auto base64 = dumpcont.substr(p1+8, p2-p1-9); - auto binary = TBase64::Decode(base64.c_str()); + auto p1 = dumpcont.find(";base64,", p); + auto p2 = dumpcont.find(">
", p1 + 4); + p = p2 + 5; - std::ofstream ofs(tgtfilename, std::ios::binary); - ofs.write(binary.Data(), binary.Length()); - } else { - R__LOG_ERROR(WebGUILog()) << "Fail to extract image from dump HTML code " << dump_name; + if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) { - return false; + auto base64 = dumpcont.substr(p1+8, p2-p1-9); + auto binary = TBase64::Decode(base64.c_str()); + + std::ofstream ofs(fn, std::ios::binary); + ofs.write(binary.Data(), binary.Length()); + + ::Info("ProduceImage", "Image file %s size %d bytes has been created", fn.c_str(), (int) binary.Length()); + } else { + R__LOG_ERROR(WebGUILog()) << "Fail to extract image from dump HTML code " << dump_name; + + return false; + } } } + } else if (EndsWith(".pdf")) { + ::Info("ProduceImage", "PDF file %s with %d pages has been created", fname.c_str(), (int) jsons.size()); } - R__LOG_DEBUG(0, WebGUILog()) << "Create file " << fname; + if (fnames.size() == 1) + R__LOG_DEBUG(0, WebGUILog()) << "Create file " << fnames[0]; + else + R__LOG_DEBUG(0, WebGUILog()) << "Create files " << TBufferJSON::ToJSON(&fnames, TBufferJSON::kNoSpaces); return true; } diff --git a/gui/webdisplay/src/RWebWindow.cxx b/gui/webdisplay/src/RWebWindow.cxx index 60b84b5e09fcb..75ca6821e6a80 100644 --- a/gui/webdisplay/src/RWebWindow.cxx +++ b/gui/webdisplay/src/RWebWindow.cxx @@ -19,6 +19,7 @@ #include "THttpCallArg.h" #include "TUrl.h" #include "TROOT.h" +#include "TSystem.h" #include "TRandom3.h" #include @@ -28,7 +29,7 @@ #include #include -using namespace ROOT::Experimental; +using namespace ROOT; using namespace std::string_literals; ////////////////////////////////////////////////////////////////////////////////////////// @@ -45,7 +46,7 @@ RWebWindow::WebConn::~WebConn() } -/** \class ROOT::Experimental::RWebWindow +/** \class ROOT::RWebWindow \ingroup webdisplay Represents web window, which can be shown in web browser or any other supported environment @@ -78,8 +79,17 @@ RWebWindow::~RWebWindow() { StopThread(); - if (fMaster) - fMaster->RemoveEmbedWindow(fMasterConnId, fMasterChannel); + if (fMaster) { + std::vector lst; + { + std::lock_guard grd(fConnMutex); + std::swap(lst, fMasterConns); + } + + for (auto &entry : lst) + fMaster->RemoveEmbedWindow(entry.connid, entry.channel); + fMaster.reset(); + } if (fWSHandler) fWSHandler->SetDisabled(); @@ -87,7 +97,7 @@ RWebWindow::~RWebWindow() if (fMgr) { // make copy of all connections - auto lst = GetConnections(); + auto lst = GetWindowConnections(); { // clear connections vector under mutex @@ -99,7 +109,8 @@ RWebWindow::~RWebWindow() for (auto &conn : lst) { conn->fActive = false; for (auto &elem: conn->fEmbed) - elem.second->fMaster.reset(); + elem.second->RemoveMasterConnection(); + conn->fEmbed.clear(); } fMgr->Unregister(*this); @@ -160,7 +171,7 @@ THttpServer *RWebWindow::GetServer() ////////////////////////////////////////////////////////////////////////////////////////// /// Show window in specified location -/// \see ROOT::Experimental::RWebWindowsManager::Show for more info +/// \see ROOT::RWebWindowsManager::Show for more info /// \return (future) connection id (or 0 when fails) unsigned RWebWindow::Show(const RWebDisplayArgs &args) @@ -171,7 +182,7 @@ unsigned RWebWindow::Show(const RWebDisplayArgs &args) ////////////////////////////////////////////////////////////////////////////////////////// /// Start headless browser for specified window /// Normally only single instance is used, but many can be created -/// See ROOT::Experimental::RWebWindowsManager::Show() docu for more info +/// See ROOT::RWebWindowsManager::Show() docu for more info /// returns (future) connection id (or 0 when fails) unsigned RWebWindow::MakeHeadless(bool create_new) @@ -300,13 +311,79 @@ std::shared_ptr RWebWindow::RemoveConnection(unsigned wsid) } } - if (res) + if (res) { for (auto &elem: res->fEmbed) - elem.second->fMaster.reset(); + elem.second->RemoveMasterConnection(res->fConnId); + res->fEmbed.clear(); + } return res; } + +////////////////////////////////////////////////////////////////////////////////////////// +/// Add new master connection +/// If there are many connections - only same master is allowed + +void RWebWindow::AddMasterConnection(std::shared_ptr window, unsigned connid, int channel) +{ + if (fMaster && fMaster != window) + R__LOG_ERROR(WebGUILog()) << "Cannot configure different masters at the same time"; + + fMaster = window; + + std::lock_guard grd(fConnMutex); + + fMasterConns.emplace_back(connid, channel); +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Get list of master connections + +std::vector RWebWindow::GetMasterConnections(unsigned connid) const +{ + std::vector lst; + if (!fMaster) + return lst; + + std::lock_guard grd(fConnMutex); + + for (auto & entry : fMasterConns) + if (!connid || entry.connid == connid) + lst.emplace_back(entry); + + return lst; +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Remove master connection - if any + +void RWebWindow::RemoveMasterConnection(unsigned connid) +{ + if (!fMaster) return; + + bool isany = false; + + { + std::lock_guard grd(fConnMutex); + + if (connid == 0) { + fMasterConns.clear(); + } else { + for (auto iter = fMasterConns.begin(); iter != fMasterConns.end(); ++iter) + if (iter->connid == connid) { + fMasterConns.erase(iter); + break; + } + } + + isany = fMasterConns.size() > 0; + } + + if (!isany) + fMaster.reset(); +} + ////////////////////////////////////////////////////////////////////////////////////////// /// Process special http request, used to hold headless browser running /// Such requests should not be replied for the long time @@ -366,7 +443,10 @@ void RWebWindow::ProvideQueueEntry(unsigned connid, EQueueEntryKind kind, std::s fInputQueue.emplace(connid, kind, std::move(arg)); } - InvokeCallbacks(); + // if special python mode is used, process events called from special thread + // there is no other way to get regular calls in main python thread, + // therefore invoke widgets callbacks directly - which potentially can be dangerous + InvokeCallbacks(fUseProcessEvents); } ////////////////////////////////////////////////////////////////////////////////////////// @@ -598,16 +678,6 @@ std::string RWebWindow::GetConnToken() const return fConnToken; } -////////////////////////////////////////////////////////////////////////////////////////// -/// Internal method to verify and thread id has to be assigned from manager again -/// Special case when ProcessMT was enabled just until thread id will be assigned - -void RWebWindow::CheckThreadAssign() -{ - if (fProcessMT && fMgr->fExternalProcessEvents) - fMgr->AssignWindowThreadId(*this); -} - ////////////////////////////////////////////////////////////////////////////////////////// /// Processing of websockets call-backs, invoked from RWebWindowWSHandler /// Method invoked from http server thread, therefore appropriate mutex must be used on all relevant data @@ -680,6 +750,7 @@ bool RWebWindow::ProcessWS(THttpCallArg &arg) if (conn) { ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s); + bool do_clear_on_close = false; if (conn->fKeyUsed < 0) { // case when same handle want to be reused by client with new key std::lock_guard grd(fConnMutex); @@ -687,7 +758,13 @@ bool RWebWindow::ProcessWS(THttpCallArg &arg) conn->fConnId = ++fConnCnt; // change connection id to avoid confusion conn->ResetData(); fPendingConn.emplace_back(conn); + } else { + std::lock_guard grd(fConnMutex); + do_clear_on_close = (fPendingConn.size() == 0) && (fConn.size() == 0); } + + if (do_clear_on_close) + fClearOnClose.reset(); } return true; @@ -770,7 +847,8 @@ bool RWebWindow::ProcessWS(THttpCallArg &arg) if (nchannel == 0) { // special system channel - if ((cdata.find("READY=") == 0) && !conn->fReady) { + if ((cdata.compare(0, 6, "READY=") == 0) && !conn->fReady) { + std::string key = cdata.substr(6); if (key.empty() && IsNativeOnlyConn()) { @@ -792,13 +870,21 @@ bool RWebWindow::ProcessWS(THttpCallArg &arg) ProvideQueueEntry(conn->fConnId, kind_Connect, ""s); conn->fReady = 10; } - } else if (cdata.compare(0,8,"CLOSECH=") == 0) { + } else if (cdata.compare(0, 8, "CLOSECH=") == 0) { int channel = std::stoi(cdata.substr(8)); auto iter = conn->fEmbed.find(channel); if (iter != conn->fEmbed.end()) { iter->second->ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s); conn->fEmbed.erase(iter); } + } else if (cdata.compare(0, 7, "RESIZE=") == 0) { + auto p = cdata.find(","); + if (p != std::string::npos) { + auto width = std::stoi(cdata.substr(7, p - 7)); + auto height = std::stoi(cdata.substr(p + 1)); + if ((width > 0) && (height > 0) && conn->fDisplayHandle) + conn->fDisplayHandle->Resize(width, height); + } } else if (cdata == "GENERATE_KEY") { if (fMaster) { @@ -958,7 +1044,7 @@ bool RWebWindow::CheckDataToSend(std::shared_ptr &conn) void RWebWindow::CheckDataToSend(bool only_once) { // make copy of all connections to be independent later, only active connections are checked - auto arr = GetConnections(0, true); + auto arr = GetWindowConnections(0, true); do { bool isany = false; @@ -1071,7 +1157,13 @@ std::string RWebWindow::GetUserArgs() const int RWebWindow::NumConnections(bool with_pending) const { + bool is_master = !!fMaster; + std::lock_guard grd(fConnMutex); + + if (is_master) + return fMasterConns.size(); + auto sz = fConn.size(); if (with_pending) sz += fPendingConn.size(); @@ -1105,10 +1197,42 @@ void RWebWindow::RecordData(const std::string &fname, const std::string &fprefix unsigned RWebWindow::GetConnectionId(int num) const { + bool is_master = !!fMaster; + std::lock_guard grd(fConnMutex); + + if (is_master) + return (num >= 0) && (num < (int)fMasterConns.size()) ? fMasterConns[num].connid : 0; + return ((num >= 0) && (num < (int)fConn.size()) && fConn[num]->fActive) ? fConn[num]->fConnId : 0; } +/////////////////////////////////////////////////////////////////////////////////// +/// returns vector with all existing connections ids +/// One also can exclude specified connection from return result, +/// which can be useful to be able reply too all but this connections + +std::vector RWebWindow::GetConnections(unsigned excludeid) const +{ + std::vector res; + + bool is_master = !!fMaster; + + std::lock_guard grd(fConnMutex); + + if (is_master) { + for (auto & entry : fMasterConns) + if (entry.connid != excludeid) + res.emplace_back(entry.connid); + } else { + for (auto & entry : fConn) + if (entry->fActive && (entry->fConnId != excludeid)) + res.emplace_back(entry->fConnId); + } + + return res; +} + /////////////////////////////////////////////////////////////////////////////////// /// returns true if specified connection id exists /// \param connid connection id (0 - any) @@ -1159,7 +1283,7 @@ void RWebWindow::CloseConnection(unsigned connid) /// \param connid connection id, when 0 - all existing connections are returned /// \param only_active when true, only active (already established) connections are returned -RWebWindow::ConnectionsList_t RWebWindow::GetConnections(unsigned connid, bool only_active) const +RWebWindow::ConnectionsList_t RWebWindow::GetWindowConnections(unsigned connid, bool only_active) const { ConnectionsList_t arr; @@ -1187,7 +1311,7 @@ RWebWindow::ConnectionsList_t RWebWindow::GetConnections(unsigned connid, bool o bool RWebWindow::CanSend(unsigned connid, bool direct) const { - auto arr = GetConnections(connid, direct); // for direct sending connection has to be active + auto arr = GetWindowConnections(connid, direct); // for direct sending connection has to be active auto maxqlen = GetMaxQueueLength(); @@ -1214,7 +1338,7 @@ int RWebWindow::GetSendQueueLength(unsigned connid) const { int maxq = -1; - for (auto &conn : GetConnections(connid)) { + for (auto &conn : GetWindowConnections(connid)) { std::lock_guard grd(conn->fMutex); int len = conn->fQueue.size(); if (len > maxq) maxq = len; @@ -1232,10 +1356,18 @@ int RWebWindow::GetSendQueueLength(unsigned connid) const void RWebWindow::SubmitData(unsigned connid, bool txt, std::string &&data, int chid) { - if (fMaster) - return fMaster->SubmitData(fMasterConnId, txt, std::move(data), fMasterChannel); + if (fMaster) { + auto lst = GetMasterConnections(connid); + auto cnt = lst.size(); + for (auto & entry : lst) + if (--cnt) + fMaster->SubmitData(entry.connid, txt, std::string(data), entry.channel); + else + fMaster->SubmitData(entry.connid, txt, std::move(data), entry.channel); + return; + } - auto arr = GetConnections(connid); + auto arr = GetWindowConnections(connid); auto cnt = arr.size(); auto maxqlen = GetMaxQueueLength(); @@ -1256,6 +1388,10 @@ void RWebWindow::SubmitData(unsigned connid, bool txt, std::string &&data, int c std::string fname = fProtocolPrefix; fname.append("msg"); fname.append(std::to_string(fProtocolCnt++)); + if (chid > 1) { + fname.append("_ch"); + fname.append(std::to_string(chid)); + } fname.append(txt ? ".txt" : ".bin"); std::ofstream ofs(fname); @@ -1337,6 +1473,7 @@ void RWebWindow::SendBinary(unsigned connid, const void *data, std::size_t len) void RWebWindow::AssignThreadId() { fUseServerThreads = false; + fUseProcessEvents = false; fProcessMT = false; fCallbacksThrdIdSet = true; fCallbacksThrdId = std::this_thread::get_id(); @@ -1358,6 +1495,7 @@ void RWebWindow::AssignThreadId() void RWebWindow::UseServerThreads() { fUseServerThreads = true; + fUseProcessEvents = false; fCallbacksThrdIdSet = false; fProcessMT = true; } @@ -1422,7 +1560,8 @@ void RWebWindow::StopThread() void RWebWindow::SetDataCallBack(WebWindowDataCallback_t func) { - if (!fUseServerThreads) AssignThreadId(); + if (!fUseServerThreads && !fUseProcessEvents) + AssignThreadId(); fDataCallback = func; } @@ -1431,7 +1570,8 @@ void RWebWindow::SetDataCallBack(WebWindowDataCallback_t func) void RWebWindow::SetConnectCallBack(WebWindowConnectCallback_t func) { - if (!fUseServerThreads) AssignThreadId(); + if (!fUseServerThreads && !fUseProcessEvents) + AssignThreadId(); fConnCallback = func; } @@ -1440,16 +1580,27 @@ void RWebWindow::SetConnectCallBack(WebWindowConnectCallback_t func) void RWebWindow::SetDisconnectCallBack(WebWindowConnectCallback_t func) { - if (!fUseServerThreads) AssignThreadId(); + if (!fUseServerThreads && !fUseProcessEvents) + AssignThreadId(); fDisconnCallback = func; } +///////////////////////////////////////////////////////////////////////////////// +/// Set handle which is cleared when last active connection is closed +/// Typically can be used to destroy web-based widget at such moment + +void RWebWindow::SetClearOnClose(const std::shared_ptr &handle) +{ + fClearOnClose = handle; +} + ///////////////////////////////////////////////////////////////////////////////// /// Set call-backs function for connect, data and disconnect events void RWebWindow::SetCallBacks(WebWindowConnectCallback_t conn, WebWindowDataCallback_t data, WebWindowConnectCallback_t disconn) { - if (!fUseServerThreads) AssignThreadId(); + if (!fUseServerThreads && !fUseProcessEvents) + AssignThreadId(); fConnCallback = conn; fDataCallback = data; fDisconnCallback = disconn; @@ -1520,12 +1671,12 @@ void RWebWindow::Run(double tm) ///////////////////////////////////////////////////////////////////////////////// /// Add embed window -unsigned RWebWindow::AddEmbedWindow(std::shared_ptr window, int channel) +unsigned RWebWindow::AddEmbedWindow(std::shared_ptr window, unsigned connid, int channel) { if (channel < 2) return 0; - auto arr = GetConnections(0, true); + auto arr = GetWindowConnections(connid, true); if (arr.size() == 0) return 0; @@ -1539,11 +1690,11 @@ unsigned RWebWindow::AddEmbedWindow(std::shared_ptr window, int chan } ///////////////////////////////////////////////////////////////////////////////// -/// Remove RWebWindow associated with the channel +/// Remove RWebWindow associated with the channelfEmbed void RWebWindow::RemoveEmbedWindow(unsigned connid, int channel) { - auto arr = GetConnections(connid); + auto arr = GetWindowConnections(connid); for (auto &conn : arr) { auto iter = conn->fEmbed.find(channel); @@ -1595,12 +1746,18 @@ unsigned RWebWindow::ShowWindow(std::shared_ptr window, const RWebDi return 0; if (args.GetBrowserKind() == RWebDisplayArgs::kEmbedded) { - unsigned connid = args.fMaster ? args.fMaster->AddEmbedWindow(window, args.fMasterChannel) : 0; + if (args.fMaster && window->fMaster && window->fMaster != args.fMaster) { + R__LOG_ERROR(WebGUILog()) << "Cannot use different master for same RWebWindow"; + return 0; + } + + unsigned connid = args.fMaster ? args.fMaster->AddEmbedWindow(window, args.fMasterConnection, args.fMasterChannel) : 0; if (connid > 0) { - window->fMaster = args.fMaster; - window->fMasterConnId = connid; - window->fMasterChannel = args.fMasterChannel; + + window->RemoveMasterConnection(connid); + + window->AddMasterConnection(args.fMaster, connid, args.fMasterChannel); // inform client that connection is established and window initialized args.fMaster->SubmitData(connid, true, "EMBED_DONE"s, args.fMasterChannel); @@ -1615,3 +1772,43 @@ unsigned RWebWindow::ShowWindow(std::shared_ptr window, const RWebDi return window->Show(args); } +std::function &, unsigned, const std::string &)> RWebWindow::gStartDialogFunc = nullptr; + +///////////////////////////////////////////////////////////////////////////////////// +/// Configure func which has to be used for starting dialog + + +void RWebWindow::SetStartDialogFunc(std::function &, unsigned, const std::string &)> func) +{ + gStartDialogFunc = func; +} + +///////////////////////////////////////////////////////////////////////////////////// +/// Check if this could be the message send by client to start new file dialog +/// If returns true, one can call RWebWindow::EmbedFileDialog() to really create file dialog +/// instance inside existing widget + +bool RWebWindow::IsFileDialogMessage(const std::string &msg) +{ + return msg.compare(0, 11, "FILEDIALOG:") == 0; +} + +///////////////////////////////////////////////////////////////////////////////////// +/// Create dialog instance to use as embedded dialog inside provided widget +/// Loads libROOTBrowserv7 and tries to call RFileDialog::Embedded() method +/// Embedded dialog started on the client side where FileDialogController.SaveAs() method called +/// Such method immediately send message with "FILEDIALOG:" prefix +/// On the server side widget should detect such message and call RFileDialog::Embedded() +/// providing received string as second argument. +/// Returned instance of shared_ptr may be used to assign callback when file is selected + +bool RWebWindow::EmbedFileDialog(const std::shared_ptr &window, unsigned connid, const std::string &args) +{ + if (!gStartDialogFunc) + gSystem->Load("libROOTBrowserv7"); + + if (!gStartDialogFunc) + return false; + + return gStartDialogFunc(window, connid, args); +} diff --git a/gui/webdisplay/src/RWebWindowWSHandler.hxx b/gui/webdisplay/src/RWebWindowWSHandler.hxx index 8d6f67b1472c2..993d72005fc43 100644 --- a/gui/webdisplay/src/RWebWindowWSHandler.hxx +++ b/gui/webdisplay/src/RWebWindowWSHandler.hxx @@ -24,7 +24,6 @@ using namespace std::string_literals; namespace ROOT { -namespace Experimental { /// just wrapper to deliver websockets call-backs to the RWebWindow class @@ -90,6 +89,10 @@ protected: int credits = gEnv->GetValue("WebGui.ConnCredits", 10); if ((credits > 0) && (credits != 10)) more_args.append("credits: "s + std::to_string(credits) + ","s); + if ((fWindow.GetWidth() > 0) && (fWindow.GetHeight() > 0)) + more_args.append("winW:"s + std::to_string(fWindow.GetWidth()) + ",winH:"s + std::to_string(fWindow.GetHeight()) + ","s); + if ((fWindow.GetX() >= 0) && (fWindow.GetY() >= 0)) + more_args.append("winX:"s + std::to_string(fWindow.GetX()) + ",winY:"s + std::to_string(fWindow.GetY()) + ","s); auto user_args = fWindow.GetUserArgs(); if (!user_args.empty()) more_args.append("user_args: "s + user_args + ","s); @@ -110,7 +113,7 @@ public: { } - virtual ~RWebWindowWSHandler() = default; + ~RWebWindowWSHandler() override = default; /// returns content of default web-page /// THttpWSHandler interface @@ -124,9 +127,7 @@ public: Bool_t ProcessWS(THttpCallArg *arg) override { if (!arg || IsDisabled()) return kFALSE; - auto res = fWindow.ProcessWS(*arg); - fWindow.CheckThreadAssign(); - return res; + return fWindow.ProcessWS(*arg); } /// Allow processing of WS actions in arbitrary thread @@ -141,7 +142,6 @@ public: static int GetBoolEnv(const std::string &name, int dfl = -1); }; -} // namespace Experimental } // namespace ROOT #endif diff --git a/gui/webdisplay/src/RWebWindowsManager.cxx b/gui/webdisplay/src/RWebWindowsManager.cxx index 8a1597eb72a72..6d8a7069bfcf1 100644 --- a/gui/webdisplay/src/RWebWindowsManager.cxx +++ b/gui/webdisplay/src/RWebWindowsManager.cxx @@ -29,12 +29,13 @@ #include "TEnv.h" #include "TExec.h" #include "TSocket.h" +#include "TThread.h" #include #include #include -using namespace ROOT::Experimental; +using namespace ROOT; /////////////////////////////////////////////////////////////// /// Parse boolean gEnv variable which should be "yes" or "no" @@ -58,7 +59,7 @@ int RWebWindowWSHandler::GetBoolEnv(const std::string &name, int dflt) } -/** \class ROOT::Experimental::RWebWindowsManager +/** \class ROOT::RWebWindowsManager \ingroup webdisplay Central instance to create and show web-based windows like Canvas or FitPanel. @@ -122,11 +123,8 @@ void RWebWindowsManager::AssignMainThrd() RWebWindowsManager::RWebWindowsManager() { fExternalProcessEvents = RWebWindowWSHandler::GetBoolEnv("WebGui.ExternalProcessEvents") == 1; - if (fExternalProcessEvents) { - gWebWinMainThrdSet = false; - fAssgnExec = std::make_unique("init_threadid", "ROOT::Experimental::RWebWindowsManager::AssignMainThrd();"); - TTimer::SingleShot(0, "TExec", fAssgnExec.get(), "Exec()"); - } + if (fExternalProcessEvents) + RWebWindowsManager::AssignMainThrd(); } ////////////////////////////////////////////////////////////////////////////////////////// @@ -141,20 +139,6 @@ RWebWindowsManager::~RWebWindowsManager() } } -////////////////////////////////////////////////////////////////////////////////////////// -/// Assign thread id for window -/// Required in case of external process events - -void RWebWindowsManager::AssignWindowThreadId(RWebWindow &win) -{ - if (fExternalProcessEvents && gWebWinMainThrdSet) { - win.fUseServerThreads = false; - win.fProcessMT = false; - win.fCallbacksThrdIdSet = true; - win.fCallbacksThrdId = gWebWinMainThrd; - } -} - ////////////////////////////////////////////////////////////////////////////////////////// /// If ROOT_LISTENER_SOCKET variable is configured, /// message will be sent to that unix socket @@ -425,7 +409,7 @@ bool RWebWindowsManager::CreateServer(bool with_http) } } - engine.Append(TString::Format("thrds=%d&websocket_timeout=%d", http_thrds, http_wstmout)); + engine.Append(TString::Format("webgui&thrds=%d&websocket_timeout=%d", http_thrds, http_wstmout)); if (http_maxage >= 0) engine.Append(TString::Format("&max_age=%d", http_maxage)); @@ -498,10 +482,12 @@ std::shared_ptr RWebWindowsManager::CreateWindow() } if (fExternalProcessEvents) { - if (gWebWinMainThrdSet) - AssignWindowThreadId(*win.get()); - else - win->UseServerThreads(); // let run window until thread is obtained + // special mode when window communication performed in THttpServer::ProcessRequests + // used only with python which create special thread - but is has to be ignored!!! + // therefore use main thread id to detect callbacks which are invoked only from that main thread + win->fUseProcessEvents = true; + win->fCallbacksThrdIdSet = gWebWinMainThrdSet; + win->fCallbacksThrdId = gWebWinMainThrd; } else if (IsUseHttpThread()) win->UseServerThreads(); @@ -636,6 +622,10 @@ unsigned RWebWindowsManager::ShowWindow(RWebWindow &win, const RWebDisplayArgs & args.SetWidth(win.GetWidth()); if (args.GetHeight() <= 0) args.SetHeight(win.GetHeight()); + if (args.GetX() < 0) + args.SetX(win.GetX()); + if (args.GetY() < 0) + args.SetY(win.GetY()); bool normal_http = !args.IsLocalDisplay(); if (!normal_http && (gEnv->GetValue("WebGui.ForceHttp", 0) == 1)) diff --git a/gui/webgui6/inc/TWebCanvas.h b/gui/webgui6/inc/TWebCanvas.h index a6fbcf806ae76..6178338b922d0 100644 --- a/gui/webgui6/inc/TWebCanvas.h +++ b/gui/webgui6/inc/TWebCanvas.h @@ -1,7 +1,7 @@ // Author: Sergey Linev, GSI 7/12/2016 /************************************************************************* - * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -30,9 +30,12 @@ class TPadWebSnapshot; class TWebPS; class TObjLink; class TExec; +class TWebCanvasTimer; class TWebCanvas : public TCanvasImp { +friend class TWebCanvasTimer; + public: /// Function type for signals, invoked when canvas drawing or update is completed using UpdatedSignal_t = std::function; @@ -57,8 +60,12 @@ class TWebCanvas : public TCanvasImp { Long64_t fSendVersion{0}; /// fCtrl; /// fSend; /// fWebConn; /// fPadsStatus; /// fWindow; ///!< configured display + std::shared_ptr fWindow; ///!< configured display - Bool_t fReadOnly{true}; /// fWindowGeometry; ///0) && (fWebConn[0].fConnId == connid) ;} + Bool_t IsFirstConn(unsigned connid) const { return (connid != 0) && (fWebConn.size() > 1) && (fWebConn[1].fConnId == connid); } + + Bool_t IsFirstDrawn() const { return (fWebConn.size() > 1) && (fWebConn[1].fDrawVersion > 0); } void ShowCmd(const std::string &arg, Bool_t show); @@ -148,13 +163,15 @@ class TWebCanvas : public TCanvasImp { void ProcessExecs(TPad *pad, TExec *extra = nullptr); + void ProcessLinesForObject(TObject *obj, const std::string &lines); + public: TWebCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height, Bool_t readonly = kTRUE); - virtual ~TWebCanvas() = default; + ~TWebCanvas() override; - void ShowWebWindow(const ROOT::Experimental::RWebDisplayArgs &user_args = ""); + void ShowWebWindow(const ROOT::RWebDisplayArgs &user_args = ""); - const std::shared_ptr &GetWebWindow() const { return fWindow; } + const std::shared_ptr &GetWebWindow() const { return fWindow; } virtual Bool_t IsReadOnly() const { return fReadOnly; } @@ -176,15 +193,15 @@ class TWebCanvas : public TCanvasImp { void ForceUpdate() override; + void SetWindowPosition(Int_t x, Int_t y) override; + void SetWindowSize(UInt_t w, UInt_t h) override; + void SetWindowTitle(const char *newTitle) override; + void SetCanvasSize(UInt_t w, UInt_t h) override; + void Iconify() override; + void RaiseWindow() override; /* - virtual void Iconify() { } virtual void SetStatusText(const char *text = 0, Int_t partidx = 0); - virtual void SetWindowPosition(Int_t x, Int_t y); - virtual void SetWindowSize(UInt_t w, UInt_t h); - virtual void SetWindowTitle(const char *newTitle); - virtual void SetCanvasSize(UInt_t w, UInt_t h); - virtual void RaiseWindow(); virtual void ReallyDelete(); */ @@ -223,15 +240,19 @@ class TWebCanvas : public TCanvasImp { void SetAsyncMode(Bool_t on = kTRUE) { fAsyncMode = on; } Bool_t IsAsyncMode() const { return fAsyncMode; } - static TString CreatePadJSON(TPad *pad, Int_t json_compression = 0); - static TString CreateCanvasJSON(TCanvas *c, Int_t json_compression = 0); + Bool_t IsFixedSize() const { return fFixedSize; } + + static TString CreatePadJSON(TPad *pad, Int_t json_compression = 0, Bool_t batchmode = kFALSE); + static TString CreateCanvasJSON(TCanvas *c, Int_t json_compression = 0, Bool_t batchmode = kFALSE); static Int_t StoreCanvasJSON(TCanvas *c, const char *filename, const char *option = ""); static bool ProduceImage(TPad *pad, const char *filename, Int_t width = 0, Int_t height = 0); + static bool ProduceImages(std::vector pads, const char *filename, Int_t width = 0, Int_t height = 0); + static TCanvasImp *NewCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height); - ClassDefOverride(TWebCanvas, 0) // Web-based implementation for TCanvasImp, read-only mode + ClassDefOverride(TWebCanvas, 0) // Web-based implementation for TCanvasImp }; #endif diff --git a/gui/webgui6/inc/TWebControlBar.h b/gui/webgui6/inc/TWebControlBar.h index e6022be38232c..8906eaf3bd814 100644 --- a/gui/webgui6/inc/TWebControlBar.h +++ b/gui/webgui6/inc/TWebControlBar.h @@ -19,14 +19,14 @@ class TWebControlBar : public TControlBarImp { protected: - std::shared_ptr fWindow; ///!< configured display + std::shared_ptr fWindow; ///!< configured display void SendInitMsg(unsigned connid); Bool_t ProcessData(unsigned connid, const std::string &arg); public: TWebControlBar(TControlBar *bar, const char *title, Int_t x, Int_t y); - virtual ~TWebControlBar() = default; + ~TWebControlBar() override = default; void Create() override { } void Hide() override; diff --git a/gui/webgui6/inc/TWebMenuItem.h b/gui/webgui6/inc/TWebMenuItem.h index 51a297a256e15..c91d28b4a03be 100644 --- a/gui/webgui6/inc/TWebMenuItem.h +++ b/gui/webgui6/inc/TWebMenuItem.h @@ -66,7 +66,7 @@ class TWebCheckedMenuItem : public TWebMenuItem { } /** virtual destructor need for vtable, used when vector of TMenuItem* is stored */ - virtual ~TWebCheckedMenuItem() = default; + ~TWebCheckedMenuItem() override = default; /** Set checked state for the item, default is none */ void SetChecked(bool on = true) { fChecked = on; } @@ -105,7 +105,7 @@ class TWebArgsMenuItem : public TWebMenuItem { TWebArgsMenuItem(const std::string &name, const std::string &title) : TWebMenuItem(name, title) {} /** virtual destructor need for vtable, used when vector of TMenuItem* is stored */ - virtual ~TWebArgsMenuItem() = default; + ~TWebArgsMenuItem() override = default; std::vector &GetArgs() { return fArgs; } diff --git a/gui/webgui6/inc/TWebPadOptions.h b/gui/webgui6/inc/TWebPadOptions.h index 914bf1840879b..1e850c2f07fbb 100644 --- a/gui/webgui6/inc/TWebPadOptions.h +++ b/gui/webgui6/inc/TWebPadOptions.h @@ -35,6 +35,7 @@ class TWebPadOptions { std::string snapid; ///< id of pad bool active{false}; ///< if pad selected as active int cw{0}, ch{0}; ///< canvas width and height in pixels + std::vector w; ///< window position and size in pixels, set only for canvas int logx{0}, logy{0}, logz{0}; ///< pad log properties int gridx{0}, gridy{0}; ///< pad grid properties int tickx{0}, ticky{0}; ///< pad ticks properties diff --git a/gui/webgui6/inc/TWebPainting.h b/gui/webgui6/inc/TWebPainting.h index 6fbd5394bfe21..cc274f9769149 100644 --- a/gui/webgui6/inc/TWebPainting.h +++ b/gui/webgui6/inc/TWebPainting.h @@ -35,7 +35,7 @@ class TWebPainting : public TObject { public: TWebPainting(); - virtual ~TWebPainting() = default; + ~TWebPainting() override = default; Bool_t IsEmpty() const { return fOper.empty() && (fBuf.GetSize() == 0); } diff --git a/gui/webgui6/inc/TWebSnapshot.h b/gui/webgui6/inc/TWebSnapshot.h index da63003fe0f54..22da32e429f06 100644 --- a/gui/webgui6/inc/TWebSnapshot.h +++ b/gui/webgui6/inc/TWebSnapshot.h @@ -39,7 +39,7 @@ class TWebSnapshot : public TObject { kStyle = 5 ///< gStyle object }; - virtual ~TWebSnapshot(); + ~TWebSnapshot() override; void SetObjectIDAsPtr(void *ptr); void SetObjectID(const std::string &id) { fObjectID = id; } @@ -61,32 +61,39 @@ class TPadWebSnapshot : public TWebSnapshot { bool fActive{false}; ///< true when pad is active bool fReadOnly{true}; ///< when canvas or pad are in readonly mode bool fSetObjectIds{true}; ///> fPrimitives; ///< list of all primitives, drawn in the pad public: - TPadWebSnapshot(bool readonly = true, bool setids = true) + TPadWebSnapshot(bool readonly = true, bool setids = true, bool batchmode = false) { SetKind(kSubPad); fReadOnly = readonly; fSetObjectIds = setids; + fBatchMode = batchmode; } void SetActive(bool on = true) { fActive = on; } void SetWithoutPrimitives(bool on = true) { fWithoutPrimitives = on; } + void SetHasExecs(bool on = true) { fHasExecs = on; } + bool IsReadOnly() const { return fReadOnly; } bool IsSetObjectIds() const { return fSetObjectIds; } + bool IsBatchMode() const { return fBatchMode; } + TWebSnapshot &NewPrimitive(TObject *obj = nullptr, const std::string &opt = ""); TPadWebSnapshot &NewSubPad(); TWebSnapshot &NewSpecials(); - ClassDefOverride(TPadWebSnapshot, 2) // Pad painting snapshot, used for JSROOT + ClassDefOverride(TPadWebSnapshot, 3) // Pad painting snapshot, used for JSROOT }; // ================================================================================= @@ -95,8 +102,9 @@ class TCanvasWebSnapshot : public TPadWebSnapshot { protected: std::string fScripts; ///< custom scripts to load bool fHighlightConnect{false}; ///< does HighlightConnect has connection + bool fFixedSize{false}; ///< if canvas draw size is fixed public: - TCanvasWebSnapshot(bool readonly = true, bool setids = true) : TPadWebSnapshot(readonly, setids) {} + TCanvasWebSnapshot(bool readonly = true, bool setids = true, bool batchmode = false) : TPadWebSnapshot(readonly, setids, batchmode) {} void SetScripts(const std::string &src) { fScripts = src; } const std::string &GetScripts() const { return fScripts; } @@ -104,7 +112,10 @@ class TCanvasWebSnapshot : public TPadWebSnapshot { void SetHighlightConnect(bool on = true) { fHighlightConnect = on; } bool GetHighlightConnect() const { return fHighlightConnect; } - ClassDefOverride(TCanvasWebSnapshot, 3) // Canvas painting snapshot, used for JSROOT + void SetFixedSize(bool on = true) { fFixedSize = on; } + bool IsFixedSize() const { return fFixedSize; } + + ClassDefOverride(TCanvasWebSnapshot, 4) // Canvas painting snapshot, used for JSROOT }; diff --git a/gui/webgui6/src/TWebCanvas.cxx b/gui/webgui6/src/TWebCanvas.cxx index 83b40b14a63d2..2ada3dd7221cb 100644 --- a/gui/webgui6/src/TWebCanvas.cxx +++ b/gui/webgui6/src/TWebCanvas.cxx @@ -1,7 +1,7 @@ // Author: Sergey Linev, GSI 7/12/2016 /************************************************************************* - * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -29,18 +29,27 @@ #include "TObjArray.h" #include "TArrayI.h" #include "TList.h" +#include "TF1.h" +#include "TF2.h" #include "TH1.h" +#include "TH1K.h" +#include "TH2.h" #include "THStack.h" #include "TMultiGraph.h" #include "TEnv.h" #include "TError.h" #include "TGraph.h" +#include "TGaxis.h" +#include "TScatter.h" +#include "TCutG.h" #include "TBufferJSON.h" #include "TBase64.h" #include "TAtt3D.h" #include "TView.h" #include "TExec.h" #include "TVirtualX.h" +#include "TMath.h" +#include "TTimer.h" #include #include @@ -49,11 +58,58 @@ #include #include +class TWebCanvasTimer : public TTimer { + TWebCanvas &fCanv; + Bool_t fProcessing{kFALSE}; + Bool_t fSlow{kFALSE}; + Int_t fSlowCnt{0}; +public: + TWebCanvasTimer(TWebCanvas &canv) : TTimer(10, kTRUE), fCanv(canv) {} + + Bool_t IsSlow() const { return fSlow; } + void SetSlow(Bool_t slow = kTRUE) + { + fSlow = slow; + fSlowCnt = 0; + SetTime(slow ? 1000 : 10); + } + + /// used to send control messages to clients + void Timeout() override + { + if (fProcessing || fCanv.fProcessingData) return; + fProcessing = kTRUE; + Bool_t res = fCanv.CheckDataToSend(); + fProcessing = kFALSE; + if (res) { + fSlowCnt = 0; + } else if (++fSlowCnt > 10 && !IsSlow()) { + SetSlow(kTRUE); + } + } +}; + + /** \class TWebCanvas \ingroup webgui6 -Basic TCanvasImp ABI implementation for Web-based GUI -Provides painting of main ROOT6 classes in web browsers +Basic TCanvasImp ABI implementation for Web-based Graphics +Provides painting of main ROOT classes in web browsers using [JSROOT](https://root.cern/js/) + +Following settings parameters can be useful for TWebCanvas: + + WebGui.FullCanvas: 1 read-only mode (0), full-functional canvas (1) (default - 1) + WebGui.StyleDelivery: 1 provide gStyle object to JSROOT client (default - 1) + WebGui.PaletteDelivery: 1 provide color palette to JSROOT client (default - 1) + WebGui.TF1UseSave: 0 used saved values for function drawing (1) or calculate function on the client side (0) (default - 0) + +TWebCanvas is used by default in interactive ROOT session. To use web-based canvas in batch mode for image +generation, one should explicitly specify `--web` option when starting ROOT: + + [shell] root -b --web tutorials/hsimple.root -e 'hpxpy->Draw("colz"); c1->SaveAs("image.png");' + +If for any reasons TWebCanvas does not provide required functionality, one always can disable it. +Either by specifying `root --web=off` when starting ROOT or by setting `Canvas.Name: TRootCanvas` in rootrc file. */ @@ -65,11 +121,29 @@ using namespace std::string_literals; TWebCanvas::TWebCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height, Bool_t readonly) : TCanvasImp(c, name, x, y, width, height) { + fTimer = new TWebCanvasTimer(*this); + fReadOnly = readonly; fStyleDelivery = gEnv->GetValue("WebGui.StyleDelivery", 1); fPaletteDelivery = gEnv->GetValue("WebGui.PaletteDelivery", 1); fPrimitivesMerge = gEnv->GetValue("WebGui.PrimitivesMerge", 100); + fTF1UseSave = gEnv->GetValue("WebGui.TF1UseSave", (Int_t) 0) > 0; fJsonComp = gEnv->GetValue("WebGui.JsonComp", TBufferJSON::kSameSuppression + TBufferJSON::kNoSpaces); + + fWebConn.emplace_back(0); // add special connection which only used to perform updates + + fTimer->TurnOn(); + + // fAsyncMode = kTRUE; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Destructor + +TWebCanvas::~TWebCanvas() +{ + delete fTimer; } //////////////////////////////////////////////////////////////////////////////// @@ -105,6 +179,7 @@ Bool_t TWebCanvas::IsJSSupportedClass(TObject *obj, Bool_t many_primitives) } supported_classes[] = {{"TH1", true}, {"TF1", true}, {"TGraph", true}, + {"TScatter"}, {"TFrame"}, {"THStack"}, {"TMultiGraph"}, @@ -116,12 +191,14 @@ Bool_t TWebCanvas::IsJSSupportedClass(TObject *obj, Bool_t many_primitives) {"TBox", false, true}, // can be handled via TWebPainter, disable for large number of primitives (like in greyscale.C) {"TWbox"}, // some extra calls which cannot be handled via TWebPainter {"TLine", false, true}, // can be handler via TWebPainter, disable for large number of primitives (like in greyscale.C) + {"TEllipse", true, true}, // can be handled via TWebPainter, disable for large number of primitives (like in greyscale.C) {"TText"}, {"TLatex"}, + {"TAnnotation"}, {"TMathText"}, {"TMarker"}, {"TPolyMarker"}, - // {"TPolyLine", false, true}, // can be handled via TWebPainter, simplify colors handling + {"TPolyLine", true, true}, // can be handled via TWebPainter, simplify colors handling {"TPolyMarker3D"}, {"TPolyLine3D"}, {"TGraphTime"}, @@ -203,9 +280,10 @@ void TWebCanvas::CreateObjectSnapshot(TPadWebSnapshot &master, TPad *pad, TObjec auto *painter = dynamic_cast(Canvas()->GetCanvasPainter()); TView *view = nullptr; - auto savepad = gPad; - pad->cd(); + TVirtualPad::TContext ctxt; + + gPad = pad; if (obj->InheritsFrom(TAtt3D::Class()) && !pad->GetView()) { pad->GetViewer3D("pad"); @@ -237,8 +315,8 @@ void TWebCanvas::CreateObjectSnapshot(TPadWebSnapshot &master, TPad *pad, TObjec painter->SetPainting(nullptr); gVirtualPS = saveps; - if (savepad) - savepad->cd(); + + fPadsStatus[pad]._has_specials = true; // if there are master PS, do not create separate entries if (!masterps && !ps.IsEmptyPainting()) @@ -320,6 +398,7 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t } paddata.SetSnapshot(TWebSnapshot::kSubPad, pad); // add ref to the pad paddata.SetWithoutPrimitives(!process_primitives); + paddata.SetHasExecs(pad->GetListOfExecs()); // if pad execs are there provide more events from client // check style changes every time when creating canvas snapshot if (resfunc && (GetStyleDelivery() > 0)) { @@ -347,7 +426,7 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t TObject *obj = nullptr; TFrame *frame = nullptr; TPaveText *title = nullptr; - bool need_frame = false, has_histo = false; + bool need_frame = false, has_histo = false, need_palette = false; std::string need_title; while (process_primitives && ((obj = iter()) != nullptr)) { @@ -369,18 +448,29 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t has_histo = true; } } else if (obj->InheritsFrom(TFrame::Class())) { - frame = static_cast(obj); + if (!frame) + frame = static_cast(obj); } else if (obj->InheritsFrom(TH1::Class())) { need_frame = true; has_histo = true; - if (!obj->TestBit(TH1::kNoTitle) && (strlen(obj->GetTitle()) > 0)) + if (!obj->TestBit(TH1::kNoTitle) && !opt.Contains("SAME") && !opt.Contains("AXIS") && !opt.Contains("AXIG") && (strlen(obj->GetTitle()) > 0)) need_title = obj->GetTitle(); + if (obj->InheritsFrom(TH2::Class()) && (opt.Contains("COLZ") || opt.Contains("LEGO2Z") || opt.Contains("LEGO4Z") || opt.Contains("SURF2Z"))) + need_palette = true; } else if (obj->InheritsFrom(TGraph::Class())) { if (opt.Contains("A")) { need_frame = true; if (!has_histo && (strlen(obj->GetTitle()) > 0)) need_title = obj->GetTitle(); } + } else if (obj->InheritsFrom(TScatter::Class())) { + need_frame = need_palette = true; + if (strlen(obj->GetTitle()) > 0) + need_title = obj->GetTitle(); + } else if (obj->InheritsFrom(TF1::Class())) { + need_frame = !obj->InheritsFrom(TF2::Class()); + if (!has_histo && (strlen(obj->GetTitle()) > 0)) + need_title = obj->GetTitle(); } else if (obj->InheritsFrom(TPaveText::Class())) { if (strcmp(obj->GetName(), "title") == 0) title = static_cast(obj); @@ -388,6 +478,9 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t } if (need_frame && !frame && primitives && CanCreateObject("TFrame")) { + if (!IsReadOnly() && need_palette && (pad->GetRightMargin() < 0.12) && (pad->GetRightMargin() == gStyle->GetPadRightMargin())) + pad->SetRightMargin(0.12); + frame = pad->GetFrame(); if(frame) primitives->AddFirst(frame); @@ -433,6 +526,30 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t CreatePadSnapshot(paddata.NewSubPad(), (TPad *)obj, version, nullptr); } else if (!process_primitives) { continue; + } else if (obj->InheritsFrom(TH1K::Class())) { + flush_master(); + TH1K *hist = (TH1K *)obj; + + Int_t nbins = hist->GetXaxis()->GetNbins(); + + TH1D *h1 = new TH1D("__dummy_name__", hist->GetTitle(), nbins, hist->GetXaxis()->GetXmin(), hist->GetXaxis()->GetXmax()); + h1->SetDirectory(nullptr); + h1->SetName(hist->GetName()); + hist->TAttLine::Copy(*h1); + hist->TAttFill::Copy(*h1); + hist->TAttMarker::Copy(*h1); + for (Int_t n = 1; n <= nbins; ++n) + h1->SetBinContent(n, hist->GetBinContent(n)); + + TIter fiter(hist->GetListOfFunctions()); + while (auto fobj = fiter()) + h1->GetListOfFunctions()->Add(fobj->Clone()); + + TString hopt = iter.GetOption(); + if (title && first_obj) hopt.Append(";;use_pad_title"); + + paddata.NewPrimitive(obj, hopt.Data()).SetSnapshot(TWebSnapshot::kObject, h1, kTRUE); + } else if (obj->InheritsFrom(TH1::Class())) { flush_master(); @@ -446,21 +563,27 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t while ((fobj = fiter()) != nullptr) { if (fobj->InheritsFrom(TPaveStats::Class())) - stats = dynamic_cast (fobj); + stats = dynamic_cast (fobj); else if (fobj->InheritsFrom("TPaletteAxis")) palette = fobj; } - if (!stats && first_obj && (gStyle->GetOptStat() > 0) && CanCreateObject("TPaveStats")) { - stats = new TPaveStats( + TString hopt = iter.GetOption(); + TString o = hopt; + o.ToUpper(); + + if (!stats && (first_obj || o.Contains("SAMES")) && (gStyle->GetOptStat() > 0) && CanCreateObject("TPaveStats")) { + stats = new TPaveStats( gStyle->GetStatX() - gStyle->GetStatW(), gStyle->GetStatY() - gStyle->GetStatH(), gStyle->GetStatX(), gStyle->GetStatY(), "brNDC"); stats->SetParent(hist); - stats->SetOptFit(gStyle->GetOptFit()); - stats->SetOptStat(gStyle->GetOptStat()); + // do not set optfit and optstat, they calling pad->Update, + // values correctly set already in TPaveStats constructor + // stats->SetOptFit(gStyle->GetOptFit()); + // stats->SetOptStat(gStyle->GetOptStat()); stats->SetFillColor(gStyle->GetStatColor()); stats->SetFillStyle(gStyle->GetStatStyle()); stats->SetBorderSize(gStyle->GetStatBorderSize()); @@ -479,10 +602,8 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t hist->GetListOfFunctions()->Add(stats); } - TString hopt = iter.GetOption(); - if (!palette && CanCreateObject("TPaletteAxis") && (hist->GetDimension() > 1) && - (hopt.Index("colz", 0, TString::kIgnoreCase) != kNPOS)) { + (o.Contains("COLZ") || o.Contains("LEGO2Z") || o.Contains("LEGO4Z") || o.Contains("SURF2Z"))) { std::stringstream exec; exec << "new TPaletteAxis(0,0,0,0, (TH1*)" << std::hex << std::showbase << (size_t)hist << ");"; palette = (TObject *)gROOT->ProcessLine(exec.str().c_str()); @@ -498,6 +619,20 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t paddata.NewPrimitive(obj, hopt.Data()).SetSnapshot(TWebSnapshot::kObject, obj); + if (hist->GetDimension() == 2) { + TString opt = iter.GetOption(); + auto p1 = opt.Index("["), p2 = opt.Index("]"); + if ((p1 != kNPOS) && (p2 != kNPOS) && p2 > p1 + 1) { + TString cutname = opt(p1 + 1, p2 - p1 - 1); + TObject *cutg = primitives->FindObject(cutname.Data()); + if (!cutg || (cutg->IsA() != TCutG::Class())) { + cutg = gROOT->GetListOfSpecials()->FindObject(cutname.Data()); + if (cutg && cutg->IsA() == TCutG::Class()) + paddata.NewPrimitive(cutg, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, cutg); + } + } + } + // do not extract objects from list of functions - stats and func need to be handled together with hist // // fiter.Reset(); @@ -522,11 +657,13 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t stats = dynamic_cast (fobj); } + TString gropt = iter.GetOption(); + // ensure histogram exists on server to draw it properly on clients side - if (!IsReadOnly() && first_obj) + if (!IsReadOnly() && (first_obj || gropt.Index("A", 0, TString::kIgnoreCase) != kNPOS || + (gropt.Index("X+", 0, TString::kIgnoreCase) != kNPOS) || (gropt.Index("X+", 0, TString::kIgnoreCase) != kNPOS))) gr->GetHistogram(); - TString gropt = iter.GetOption(); if (title && first_obj) gropt.Append(";;use_pad_title"); if (stats) gropt.Append(";;use_pad_stats"); @@ -539,12 +676,88 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t if (funcs) fPrimitivesLists.Add(funcs); first_obj = false; + } else if (obj->InheritsFrom(TScatter::Class())) { + flush_master(); + + TScatter *scatter = (TScatter *)obj; + auto funcs = scatter->GetGraph()->GetListOfFunctions(); + + TIter fiter(funcs); + TObject *fobj = nullptr, *palette = nullptr; + + while ((fobj = fiter()) != nullptr) { + if (fobj->InheritsFrom("TPaletteAxis")) + palette = fobj; + } + + // ensure histogram exists on server to draw it properly on clients side + if (!IsReadOnly() && first_obj) + scatter->GetHistogram(); + + if (!palette && CanCreateObject("TPaletteAxis")) { + std::stringstream exec; + exec << "new TPaletteAxis(0,0,0,0,0,0);"; + palette = (TObject *)gROOT->ProcessLine(exec.str().c_str()); + if (palette) + funcs->AddFirst(palette); + } + + TString scopt = iter.GetOption(); + if (title && first_obj) scopt.Append(";;use_pad_title"); + if (palette) scopt.Append(";;use_pad_palette"); + + paddata.NewPrimitive(obj, scopt.Data()).SetSnapshot(TWebSnapshot::kObject, obj); + + fiter.Reset(); + while ((fobj = fiter()) != nullptr) + CreateObjectSnapshot(paddata, pad, fobj, fiter.GetOption()); + + if (funcs) + fPrimitivesLists.Add(funcs); + + first_obj = false; + } else if (obj->InheritsFrom(TF1::Class())) { + flush_master(); + auto f1 = static_cast (obj); + + TString f1opt = iter.GetOption(); + + if (f1->IsA() == TF1::Class() || f1->IsA() == TF2::Class()) { + if (paddata.IsBatchMode() || fTF1UseSave) + f1->Save(0, 0, 0, 0, 0, 0); + if (fTF1UseSave) + f1opt.Append(";force_saved"); + } + + if (first_obj) { + auto hist = f1->GetHistogram(); + paddata.NewPrimitive(hist, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, hist); + f1opt.Append(";webcanv_hist"); + } + + paddata.NewPrimitive(f1, f1opt.Data()).SetSnapshot(TWebSnapshot::kObject, f1); + + first_obj = false; + + } else if (obj->InheritsFrom(TGaxis::Class())) { + flush_master(); + auto gaxis = static_cast (obj); + auto func = gaxis->GetFunction(); + if (func) + paddata.NewPrimitive(func, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, func); + + paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj); + } else if (obj->InheritsFrom(TFrame::Class())) { + flush_master(); + if (frame && (obj == frame)) { + paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj); + frame = nullptr; // add frame only once + } } else if (IsJSSupportedClass(obj, usemaster)) { flush_master(); paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj); } else { CreateObjectSnapshot(paddata, pad, obj, iter.GetOption(), usemaster ? &masterps : nullptr); - pad_status._has_specials = true; } } @@ -611,21 +824,38 @@ void TWebCanvas::CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t fPrimitivesLists.Clear("nodelete"); } +////////////////////////////////////////////////////////////////////////////////////////////////// +/// Add control message for specified connection +/// Same control message can be overwritten many time before it really sends to the client +/// If connid == 0, message will be add to all connections +/// After ctrl message is add to the output, short timer is activated and message send afterwards + +void TWebCanvas::AddCtrlMsg(unsigned connid, const std::string &key, const std::string &value) +{ + Bool_t new_ctrl = kFALSE; + + for (auto &conn : fWebConn) { + if (conn.match(connid)) { + conn.fCtrl[key] = value; + new_ctrl = kTRUE; + } + } + + if (new_ctrl && fTimer->IsSlow()) + fTimer->SetSlow(kFALSE); +} + + ////////////////////////////////////////////////////////////////////////////////////////////////// /// Add message to send queue for specified connection /// If connid == 0, message will be add to all connections -/// Return kFALSE if queue is full or connection is not exists -Bool_t TWebCanvas::AddToSendQueue(unsigned connid, const std::string &msg) +void TWebCanvas::AddSendQueue(unsigned connid, const std::string &msg) { - Bool_t res = false; for (auto &conn : fWebConn) { - if ((conn.fConnId == connid) || (connid == 0)) { + if (conn.match(connid)) conn.fSend.emplace(msg); - res = kTRUE; - } } - return res; } @@ -633,60 +863,86 @@ Bool_t TWebCanvas::AddToSendQueue(unsigned connid, const std::string &msg) /// Check if any data should be send to client /// If connid != 0, only selected connection will be checked -void TWebCanvas::CheckDataToSend(unsigned connid) +Bool_t TWebCanvas::CheckDataToSend(unsigned connid) { - if (!Canvas() || !fWindow) - return; + if (!Canvas()) + return kFALSE; + + bool isMoreData = false, isAnySend = false; for (auto &conn : fWebConn) { - if (connid && (conn.fConnId != connid)) - continue; - // check if direct data sending is possible - if (!fWindow->CanSend(conn.fConnId, true)) - continue; + bool isConnData = !conn.fCtrl.empty() || !conn.fSend.empty() || + ((conn.fCheckedVersion < fCanvVersion) && (conn.fSendVersion == conn.fDrawVersion)); - std::string buf; + while ((conn.is_batch() && !connid) || (conn.match(connid) && fWindow && fWindow->CanSend(conn.fConnId, true))) { + // check if any control messages still there to keep timer running - if ((conn.fCheckedVersion < fCanvVersion) && (conn.fSendVersion == conn.fDrawVersion)) { + std::string buf; - buf = "SNAP6:"s + std::to_string(fCanvVersion) + ":"s; + if (!conn.fCtrl.empty()) { + buf = "CTRL:"s + TBufferJSON::ToJSON(&conn.fCtrl, TBufferJSON::kMapAsObject + TBufferJSON::kNoSpaces); + conn.fCtrl.clear(); + } else if (!conn.fSend.empty()) { + std::swap(buf, conn.fSend.front()); + conn.fSend.pop(); + } else if ((conn.fCheckedVersion < fCanvVersion) && (conn.fSendVersion == conn.fDrawVersion)) { - TCanvasWebSnapshot holder(IsReadOnly()); + buf = "SNAP6:"s + std::to_string(fCanvVersion) + ":"s; - // scripts send only when canvas drawn for the first time - if (!conn.fSendVersion) - holder.SetScripts(fCustomScripts); + TCanvasWebSnapshot holder(IsReadOnly(), true, false); // readonly, set ids, batchmode - holder.SetHighlightConnect(Canvas()->HasConnection("Highlighted(TVirtualPad*,TObject*,Int_t,Int_t)")); + holder.SetFixedSize(fFixedSize); // set fixed size flag - CreatePadSnapshot(holder, Canvas(), conn.fSendVersion, [&buf, &conn, this](TPadWebSnapshot *snap) { - auto json = TBufferJSON::ToJSON(snap, fJsonComp); - auto hash = json.Hash(); - if (conn.fLastSendHash && (conn.fLastSendHash == hash)) { - // prevent looping when same data send many times - buf.clear(); - } else { - buf.append(json.Data()); - conn.fLastSendHash = hash; - } - }); + // scripts send only when canvas drawn for the first time + if (!conn.fSendVersion) + holder.SetScripts(fCustomScripts); - conn.fCheckedVersion = fCanvVersion; + holder.SetHighlightConnect(Canvas()->HasConnection("Highlighted(TVirtualPad*,TObject*,Int_t,Int_t)")); - if (!buf.empty()) - conn.fSendVersion = fCanvVersion; + CreatePadSnapshot(holder, Canvas(), conn.fSendVersion, [&buf, &conn, this](TPadWebSnapshot *snap) { + if (conn.is_batch()) { + // for batch connection only calling of CreatePadSnapshot is important + buf.clear(); + return; + } - } else if (!conn.fSend.empty()) { + auto json = TBufferJSON::ToJSON(snap, fJsonComp); + auto hash = json.Hash(); + if (conn.fLastSendHash && (conn.fLastSendHash == hash) && conn.fSendVersion) { + // prevent looping when same data send many times + buf.clear(); + } else { + buf.append(json.Data()); + conn.fLastSendHash = hash; + } + }); + + conn.fCheckedVersion = fCanvVersion; + + conn.fSendVersion = fCanvVersion; - std::swap(buf, conn.fSend.front()); - conn.fSend.pop(); + if (buf.empty()) + conn.fDrawVersion = fCanvVersion; + } else { + isConnData = false; + break; + } + if (!buf.empty() && !conn.is_batch()) { + fWindow->Send(conn.fConnId, buf); + isAnySend = true; + } } - if (!buf.empty()) - fWindow->Send(conn.fConnId, buf); + if (isConnData) + isMoreData = true; } + + if (fTimer->IsSlow() && isMoreData) + fTimer->SetSlow(kFALSE); + + return isAnySend; } ////////////////////////////////////////////////////////////////////////////////////////// @@ -700,10 +956,10 @@ void TWebCanvas::Close() /// Show canvas in specified place. /// If parameter args not specified, default ROOT web display will be used -void TWebCanvas::ShowWebWindow(const ROOT::Experimental::RWebDisplayArgs &args) +void TWebCanvas::ShowWebWindow(const ROOT::RWebDisplayArgs &args) { if (!fWindow) { - fWindow = ROOT::Experimental::RWebWindow::Create(); + fWindow = ROOT::RWebWindow::Create(); fWindow->SetConnLimit(0); // configure connections limit @@ -718,7 +974,7 @@ void TWebCanvas::ShowWebWindow(const ROOT::Experimental::RWebDisplayArgs &args) // data [this](unsigned connid, const std::string &arg) { ProcessData(connid, arg); - CheckDataToSend(connid); + CheckDataToSend(); }, // disconnect [this](unsigned connid) { @@ -733,14 +989,13 @@ void TWebCanvas::ShowWebWindow(const ROOT::Experimental::RWebDisplayArgs &args) }); } - auto w = Canvas()->GetWw(), h = Canvas()->GetWh(); + auto w = Canvas()->GetWindowWidth(), h = Canvas()->GetWindowHeight(); + if ((w > 0) && (w < 50000) && (h > 0) && (h < 30000)) + fWindow->SetGeometry(w, h); - if ((w > 10) && (w < 50000) && (h > 10) && (h < 30000)) - fWindow->SetGeometry(w + 6, h + 22); - - if ((args.GetBrowserKind() == ROOT::Experimental::RWebDisplayArgs::kQt5) || - (args.GetBrowserKind() == ROOT::Experimental::RWebDisplayArgs::kQt6) || - (args.GetBrowserKind() == ROOT::Experimental::RWebDisplayArgs::kCEF)) + if ((args.GetBrowserKind() == ROOT::RWebDisplayArgs::kQt5) || + (args.GetBrowserKind() == ROOT::RWebDisplayArgs::kQt6) || + (args.GetBrowserKind() == ROOT::RWebDisplayArgs::kCEF)) SetLongerPolling(kTRUE); fWindow->Show(args); @@ -754,8 +1009,11 @@ void TWebCanvas::Show() if (gROOT->IsWebDisplayBatch()) return; - ROOT::Experimental::RWebDisplayArgs args; + ROOT::RWebDisplayArgs args; args.SetWidgetKind("TCanvas"); + args.SetSize(Canvas()->GetWindowWidth(), Canvas()->GetWindowHeight()); + args.SetPos(Canvas()->GetWindowTopX(), Canvas()->GetWindowTopY()); + ShowWebWindow(args); } @@ -764,8 +1022,7 @@ void TWebCanvas::Show() void TWebCanvas::ShowCmd(const std::string &arg, Bool_t show) { - if (AddToSendQueue(0, "SHOW:"s + arg + (show ? ":1"s : ":0"s))) - CheckDataToSend(); + AddCtrlMsg(0, arg, show ? "1"s : "0"s); } ////////////////////////////////////////////////////////////////////////////////////////// @@ -777,8 +1034,7 @@ void TWebCanvas::ActivateInEditor(TPad *pad, TObject *obj) UInt_t hash = TString::Hash(&obj, sizeof(obj)); - if (AddToSendQueue(0, "EDIT:"s + std::to_string(hash))) - CheckDataToSend(); + AddCtrlMsg(0, "edit"s, std::to_string(hash)); } ////////////////////////////////////////////////////////////////////////////////////////// @@ -813,6 +1069,66 @@ Bool_t TWebCanvas::HasToolTips() const return (fClientBits & TCanvas::kShowToolTips) != 0; } +////////////////////////////////////////////////////////////////////////////////////////// +/// Set window position of web canvas + +void TWebCanvas::SetWindowPosition(Int_t x, Int_t y) +{ + AddCtrlMsg(0, "x"s, std::to_string(x)); + AddCtrlMsg(0, "y"s, std::to_string(y)); +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Set window size of web canvas + +void TWebCanvas::SetWindowSize(UInt_t w, UInt_t h) +{ + AddCtrlMsg(0, "w"s, std::to_string(w)); + AddCtrlMsg(0, "h"s, std::to_string(h)); +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Set window title of web canvas + +void TWebCanvas::SetWindowTitle(const char *newTitle) +{ + AddCtrlMsg(0, "title"s, newTitle); +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Set canvas size of web canvas + +void TWebCanvas::SetCanvasSize(UInt_t cw, UInt_t ch) +{ + fFixedSize = kTRUE; + AddCtrlMsg(0, "cw"s, std::to_string(cw)); + AddCtrlMsg(0, "ch"s, std::to_string(ch)); + if ((cw > 0) && (ch > 0)) { + Canvas()->fCw = cw; + Canvas()->fCh = ch; + } else { + // temporary value, will be reported back from client + Canvas()->fCw = Canvas()->fWindowWidth; + Canvas()->fCh = Canvas()->fWindowHeight; + } +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Iconify browser window + +void TWebCanvas::Iconify() +{ + AddCtrlMsg(0, "winstate"s, "iconify"s); +} + +////////////////////////////////////////////////////////////////////////////////////////// +/// Raise browser window + +void TWebCanvas::RaiseWindow() +{ + AddCtrlMsg(0, "winstate"s, "raise"s); +} + ////////////////////////////////////////////////////////////////////////////////////////// /// Assign clients bits @@ -854,6 +1170,13 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) AssignStatusBits(r.bits); Canvas()->fCw = r.cw; Canvas()->fCh = r.ch; + if (r.w.size() == 4) { + fWindowGeometry = r.w; + Canvas()->fWindowTopX = fWindowGeometry[0]; + Canvas()->fWindowTopY = fWindowGeometry[1]; + Canvas()->fWindowWidth = fWindowGeometry[2]; + Canvas()->fWindowHeight = fWindowGeometry[3]; + } } if (r.active && (pad != gPad)) gPad = pad; @@ -862,12 +1185,9 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) pad->SetTicks(r.tickx, r.ticky); if ((pad->GetGridx() != (r.gridx > 0)) || (pad->GetGridy() != (r.gridy > 0))) pad->SetGrid(r.gridx, r.gridy); - if (r.logx != pad->GetLogx()) - pad->SetLogx(r.logx); - if (r.logy != pad->GetLogy()) - pad->SetLogy(r.logy); - if (r.logz != pad->GetLogz()) - pad->SetLogz(r.logz); + pad->fLogx = r.logx; + pad->fLogy = r.logy; + pad->fLogz = r.logz; pad->SetLeftMargin(r.mleft); pad->SetRightMargin(r.mright); @@ -875,34 +1195,19 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) pad->SetBottomMargin(r.mbottom); if (r.ranges) { - - Double_t ux1_, ux2_, uy1_, uy2_, px1_, px2_, py1_, py2_; - - pad->GetRange(px1_, py1_, px2_, py2_); - pad->GetRangeAxis(ux1_, uy1_, ux2_, uy2_); - - bool same_range = (r.ux1 == ux1_) && (r.ux2 == ux2_) && (r.uy1 == uy1_) && (r.uy2 == uy2_) && - (r.px1 == px1_) && (r.px2 == px2_) && (r.py1 == py1_) && (r.py2 == py2_); - - if (!same_range) { - - // avoid call of original methods, set members directly - // pad->Range(r.px1, r.py1, r.px2, r.py2); - // pad->RangeAxis(r.ux1, r.uy1, r.ux2, r.uy2); - - pad->fX1 = r.px1; - pad->fY1 = r.py1; - pad->fX2 = r.px2; - pad->fY2 = r.py2; - - pad->fUxmin = r.ux1; - pad->fUymin = r.uy1; - pad->fUxmax = r.ux2; - pad->fUymax = r.uy2; - - if (gDebug > 1) - Info("DecodeAllRanges", "Change ranges for pad %s", pad->GetName()); - } + // avoid call of original methods, set members directly + // pad->Range(r.px1, r.py1, r.px2, r.py2); + // pad->RangeAxis(r.ux1, r.uy1, r.ux2, r.uy2); + + pad->fX1 = r.px1; + pad->fX2 = r.px2; + pad->fY1 = r.py1; + pad->fY2 = r.py2; + + pad->fUxmin = r.ux1; + pad->fUxmax = r.ux2; + pad->fUymin = r.uy1; + pad->fUymax = r.uy2; } // pad->SetPad(r.mleft, r.mbottom, 1-r.mright, 1-r.mtop); @@ -974,6 +1279,8 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) if (hist_holder == hist) hist_holder = nullptr; + Bool_t no_entries = hist->GetEntries(); + Double_t hmin = 0., hmax = 0.; if (r.zx1 == r.zx2) @@ -984,6 +1291,11 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) if (hist->GetDimension() == 1) { hmin = r.zy1; hmax = r.zy2; + if ((hmin == hmax) && !no_entries) { + // if there are no zooming on Y and histogram has no entries, hmin/hmax should be set to full range + hmin = pad->fLogy ? TMath::Power(pad->fLogy < 2 ? 10 : pad->fLogy, r.uy1) : r.uy1; + hmax = pad->fLogy ? TMath::Power(pad->fLogy < 2 ? 10 : pad->fLogy, r.uy2) : r.uy2; + } } else if (r.zy1 == r.zy2) { hist->GetYaxis()->SetRange(0., 0.); } else { @@ -993,6 +1305,11 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) if (hist->GetDimension() == 2) { hmin = r.zz1; hmax = r.zz2; + if ((hmin == hmax) && !no_entries) { + // z scale is not transformed + hmin = r.uz1; + hmax = r.uz2; + } } else if (hist->GetDimension() == 3) { if (r.zz1 == r.zz2) { hist->GetZaxis()->SetRange(0., 0.); @@ -1004,7 +1321,7 @@ Bool_t TWebCanvas::DecodePadOptions(const std::string &msg, bool process_execs) if (hmin == hmax) hmin = hmax = -1111; - if (!hist_holder) { + if (!hist_holder || (hist_holder->IsA() == TScatter::Class())) { hist->SetMinimum(hmin); hist->SetMaximum(hmax); } else { @@ -1091,6 +1408,36 @@ void TWebCanvas::ProcessExecs(TPad *pad, TExec *extra) gVirtualX = savex; } +////////////////////////////////////////////////////////////////////////////////////////// +/// Execute one or several methods for selected object +/// String can be separated by ";;" to let execute several methods at once +void TWebCanvas::ProcessLinesForObject(TObject *obj, const std::string &lines) +{ + std::string buf = lines; + + Int_t indx = 0; + + while (obj && !buf.empty()) { + std::string sub = buf; + auto pos = buf.find(";;"); + if (pos == std::string::npos) { + sub = buf; + buf.clear(); + } else { + sub = buf.substr(0,pos); + buf = buf.substr(pos+2); + } + if (sub.empty()) continue; + + std::stringstream exec; + exec << "((" << obj->ClassName() << " *) " << std::hex << std::showbase << (size_t)obj << ")->" << sub << ";"; + if (indx < 3 || gDebug > 0) + Info("ProcessLinesForObject", "Obj %s Execute %s", obj->GetName(), exec.str().c_str()); + gROOT->ProcessLine(exec.str().c_str()); + indx++; + } +} + ////////////////////////////////////////////////////////////////////////////////////////// /// Handle data from web browser /// Returns kFALSE if message was not processed @@ -1101,14 +1448,16 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) return kTRUE; // try to identify connection for given WS request - unsigned indx = 0; - for (auto &c : fWebConn) { - if (c.fConnId == connid) break; - indx++; + unsigned indx = 0; // first connection is batch and excluded + while(++indx < fWebConn.size()) { + if (fWebConn[indx].fConnId == connid) + break; } if (indx >= fWebConn.size()) return kTRUE; + Bool_t is_main_connection = indx == 1; // first connection allow to make changes + struct FlagGuard { Bool_t &flag; FlagGuard(Bool_t &_flag) : flag(_flag) { flag = true; } @@ -1139,11 +1488,9 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) fWebConn[indx].fDrawVersion = std::stoll(cdata); } else { fWebConn[indx].fDrawVersion = std::stoll(std::string(cdata, separ - cdata)); - if ((indx == 0) && !IsReadOnly()) - if (DecodePadOptions(separ+1, false)) { + if (is_main_connection && !IsReadOnly()) + if (DecodePadOptions(separ+1, false)) CheckCanvasModified(); - CheckDataToSend(); - } } } else if (arg == "RELOAD") { @@ -1182,21 +1529,18 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) } else if (arg.compare(0, 9, "OPTIONS6:") == 0) { - if ((indx == 0) && !IsReadOnly()) - if (DecodePadOptions(arg.substr(9), true)) { - + if (is_main_connection && !IsReadOnly()) + if (DecodePadOptions(arg.substr(9), true)) CheckCanvasModified(); - CheckDataToSend(); - } } else if (arg.compare(0, 11, "STATUSBITS:") == 0) { - if (indx == 0) { + if (is_main_connection) { AssignStatusBits(std::stoul(arg.substr(11))); if (fUpdatedSignal) fUpdatedSignal(); // invoke signal } } else if (arg.compare(0, 10, "HIGHLIGHT:") == 0) { - if (indx == 0) { + if (is_main_connection) { auto arr = TBufferJSON::FromJSON>(arg.substr(10)); if (!arr || (arr->size() != 4)) { Error("ProcessData", "Wrong arguments count %d in highlight message", (int)(arr ? arr->size() : -1)); @@ -1211,6 +1555,31 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) } } } + } else if (ROOT::RWebWindow::IsFileDialogMessage(arg)) { + + ROOT::RWebWindow::EmbedFileDialog(fWindow, connid, arg); + + } else if (arg == "FITPANEL"s) { + + TH1 *hist = nullptr; + TIter iter(Canvas()->GetListOfPrimitives()); + while (auto obj = iter()) { + hist = dynamic_cast(obj); + if (hist) break; + } + + TString cmd = TString::Format("auto panel = std::make_shared(\"FitPanel\");" + "panel->AssignCanvas(\"%s\");" + "panel->AssignHistogram((TH1 *)0x%zx);" + "panel->Show();" + "panel->ClearOnClose(panel);", Canvas()->GetName(), (size_t) hist); + + gROOT->ProcessLine(cmd.Data()); + + } else if (arg == "START_BROWSER"s) { + + gROOT->ProcessLine("new TBrowser;"); + } else if (IsReadOnly()) { // all following messages are not allowed in readonly mode @@ -1251,7 +1620,7 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) std::string buf = "MENU:"; buf.append(TBufferJSON::ToJSON(&items, 103).Data()); - AddToSendQueue(connid, buf); + AddSendQueue(connid, buf); } else if (arg.compare(0, 8, "PRIMIT6:") == 0) { @@ -1327,25 +1696,10 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) TPad *objpad = nullptr; TObject *obj = FindPrimitive(sid, 1, nullptr, &lnk, &objpad); + if (obj && !buf.empty()) { - while (!buf.empty()) { - std::string sub = buf; - pos = buf.find(";;"); - if (pos == std::string::npos) { - sub = buf; - buf.clear(); - } else { - sub = buf.substr(0,pos); - buf = buf.substr(pos+2); - } - if (sub.empty()) continue; - - std::stringstream exec; - exec << "((" << obj->ClassName() << " *) " << std::hex << std::showbase << (size_t)obj << ")->" << sub << ";"; - Info("ProcessData", "Obj %s Execute %s", obj->GetName(), exec.str().c_str()); - gROOT->ProcessLine(exec.str().c_str()); - } + ProcessLinesForObject(obj, buf); if (objpad) objpad->Modified(); @@ -1391,7 +1745,7 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) std::string send = reply; send.append(":"); send.append(TBufferJSON::ToJSON(resobj, 23).Data()); - AddToSendQueue(connid, send); + AddSendQueue(connid, send); if (reply[0] == 'D') delete resobj; // delete object if first symbol in reply is D } @@ -1405,9 +1759,9 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) if (pad) { pad->Clear(); pad->Modified(); - PerformUpdate(); + CheckCanvasModified(); } else { - printf("Not found pad with id %s\n", snapid.c_str()); + Error("ProcessData", "Not found pad with id %s to clear\n", snapid.c_str()); } } else if (arg.compare(0, 7, "DIVIDE:") == 0) { auto arr = TBufferJSON::FromJSON>(arg.substr(7)); @@ -1435,7 +1789,7 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) else pad->Divide(n1, n2); pad->cd(1); - PerformUpdate(); + CheckCanvasModified(); } } @@ -1447,7 +1801,37 @@ Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg) if (objlnk) objlnk->SetOption(arr->at(1).c_str()); } - + } else if (arg.compare(0, 8, "RESIZED:") == 0) { + auto arr = TBufferJSON::FromJSON>(arg.substr(8)); + if (arr && arr->size() == 7) { + // set members directly to avoid redrawing of the client again + Canvas()->fCw = arr->at(4); + Canvas()->fCh = arr->at(5); + fFixedSize = arr->at(6) > 0; + arr->resize(4); + fWindowGeometry = *arr; + Canvas()->fWindowTopX = fWindowGeometry[0]; + Canvas()->fWindowTopY = fWindowGeometry[1]; + Canvas()->fWindowWidth = fWindowGeometry[2]; + Canvas()->fWindowHeight = fWindowGeometry[3]; + } + } else if (arg.compare(0, 7, "POPOBJ:") == 0) { + auto arr = TBufferJSON::FromJSON>(arg.substr(7)); + if (arr && arr->size() == 2) { + TPad *pad = dynamic_cast(FindPrimitive(arr->at(0))); + TObject *obj = FindPrimitive(arr->at(1), 0, pad); + if (pad && obj && (obj != pad->GetListOfPrimitives()->Last())) { + TIter next(pad->GetListOfPrimitives()); + while (auto o = next()) + if (obj == o) { + TString opt = next.GetOption(); + pad->GetListOfPrimitives()->Remove(obj); + pad->GetListOfPrimitives()->AddLast(obj, opt.Data()); + pad->Modified(); + break; + } + } + } } else if (arg == "INTERRUPT"s) { gROOT->SetInterrupt(); } else { @@ -1484,8 +1868,9 @@ void TWebCanvas::CheckPadModified(TPad *pad) ////////////////////////////////////////////////////////////////////////////////////////// /// Check if any pad on the canvas was modified /// If yes, increment version of correspondent pad +/// Returns true when canvas really modified -void TWebCanvas::CheckCanvasModified(bool force_modified) +Bool_t TWebCanvas::CheckCanvasModified(bool force_modified) { // clear temporary flags for (auto &entry : fPadsStatus) { @@ -1514,6 +1899,8 @@ void TWebCanvas::CheckCanvasModified(bool force_modified) if (entry.second._modified) entry.second.fVersion = fCanvVersion; } + + return is_any_modified; } @@ -1522,10 +1909,17 @@ void TWebCanvas::CheckCanvasModified(bool force_modified) UInt_t TWebCanvas::GetWindowGeometry(Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) { - x = 0; - y = 0; - w = Canvas()->GetWw() + 4; - h = Canvas()->GetWh() + 28; + if (fWindowGeometry.size() == 4) { + x = fWindowGeometry[0]; + y = fWindowGeometry[1]; + w = fWindowGeometry[2]; + h = fWindowGeometry[3]; + } else { + x = Canvas()->fWindowTopX; + y = Canvas()->fWindowTopY; + w = Canvas()->fWindowWidth; + h = Canvas()->fWindowHeight; + } return 0; } @@ -1535,16 +1929,13 @@ UInt_t TWebCanvas::GetWindowGeometry(Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) /// scan all primitives in the TCanvas and subpads and convert them into /// the structure which will be delivered to JSROOT client -Bool_t TWebCanvas::PerformUpdate() +Bool_t TWebCanvas::PerformUpdate(Bool_t async) { - if (!fWindow) - return kTRUE; - CheckCanvasModified(); CheckDataToSend(); - if (!fProcessingData && !IsAsyncMode()) + if (!fProcessingData && !IsAsyncMode() && !async) WaitWhenCanvasPainted(fCanvVersion); return kTRUE; @@ -1555,12 +1946,14 @@ Bool_t TWebCanvas::PerformUpdate() void TWebCanvas::ForceUpdate() { - if (!fWindow) - return; - CheckCanvasModified(true); - CheckDataToSend(); + if (!fWindow) { + TCanvasWebSnapshot holder(IsReadOnly(), false, true); // readonly, set ids, batchmode + CreatePadSnapshot(holder, Canvas(), 0, nullptr); + } else { + CheckDataToSend(); + } } ////////////////////////////////////////////////////////////////////////////////////////// @@ -1587,7 +1980,7 @@ Bool_t TWebCanvas::WaitWhenCanvasPainted(Long64_t ver) return kFALSE; // wait ~1 min if no new connection established } - if ((fWebConn.size() > 0) && (fWebConn.front().fDrawVersion >= ver)) { + if ((fWebConn.size() > 1) && (fWebConn[1].fDrawVersion >= ver)) { if (gDebug > 2) Info("WaitWhenCanvasPainted", "ver %ld got painted", (long)ver); return kTRUE; @@ -1604,7 +1997,11 @@ Bool_t TWebCanvas::WaitWhenCanvasPainted(Long64_t ver) return kFALSE; } -TString TWebCanvas::CreatePadJSON(TPad *pad, Int_t json_compression) +////////////////////////////////////////////////////////////////////////////////////////// +/// Create JSON painting output for given pad +/// Produce JSON can be used for offline drawing with JSROOT + +TString TWebCanvas::CreatePadJSON(TPad *pad, Int_t json_compression, Bool_t batchmode) { TString res; if (!pad) @@ -1612,11 +2009,11 @@ TString TWebCanvas::CreatePadJSON(TPad *pad, Int_t json_compression) TCanvas *c = dynamic_cast(pad); if (c) { - res = CreateCanvasJSON(c, json_compression); + res = CreateCanvasJSON(c, json_compression, batchmode); } else { - auto imp = std::make_unique(pad->GetCanvas(), pad->GetName(), 0, 0, 1000, 500); + auto imp = std::make_unique(pad->GetCanvas(), pad->GetName(), 0, 0, pad->GetWw(), pad->GetWh(), kTRUE); - TPadWebSnapshot holder(true, false); // readonly, no ids + TPadWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode imp->CreatePadSnapshot(holder, pad, 0, [&res, json_compression](TPadWebSnapshot *snap) { res = TBufferJSON::ToJSON(snap, json_compression); @@ -1630,7 +2027,7 @@ TString TWebCanvas::CreatePadJSON(TPad *pad, Int_t json_compression) /// Create JSON painting output for given canvas /// Produce JSON can be used for offline drawing with JSROOT -TString TWebCanvas::CreateCanvasJSON(TCanvas *c, Int_t json_compression) +TString TWebCanvas::CreateCanvasJSON(TCanvas *c, Int_t json_compression, Bool_t batchmode) { TString res; @@ -1638,9 +2035,9 @@ TString TWebCanvas::CreateCanvasJSON(TCanvas *c, Int_t json_compression) return res; { - auto imp = std::make_unique(c, c->GetName(), 0, 0, 1000, 500); + auto imp = std::make_unique(c, c->GetName(), 0, 0, c->GetWw(), c->GetWh(), kTRUE); - TCanvasWebSnapshot holder(true, false); // readonly, no ids + TCanvasWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode imp->CreatePadSnapshot(holder, c, 0, [&res, json_compression](TPadWebSnapshot *snap) { res = TBufferJSON::ToJSON(snap, json_compression); @@ -1652,19 +2049,25 @@ TString TWebCanvas::CreateCanvasJSON(TCanvas *c, Int_t json_compression) ////////////////////////////////////////////////////////////////////////////////////////// /// Create JSON painting output for given canvas and store into the file -/// See TBufferJSON::ExportToFile() method for more details +/// See TBufferJSON::ExportToFile() method for more details about option +/// If option string starts with symbol 'b', JSON for batch mode will be generated Int_t TWebCanvas::StoreCanvasJSON(TCanvas *c, const char *filename, const char *option) { Int_t res = 0; + Bool_t batchmode = kFALSE; + if (option && *option == 'b') { + batchmode = kTRUE; + ++option; + } if (!c) return res; { - auto imp = std::make_unique(c, c->GetName(), 0, 0, 1000, 500); + auto imp = std::make_unique(c, c->GetName(), 0, 0, c->GetWw(), c->GetWh(), kTRUE); - TCanvasWebSnapshot holder(true, false); // readonly, no ids + TCanvasWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode imp->CreatePadSnapshot(holder, c, 0, [&res, filename, option](TPadWebSnapshot *snap) { res = TBufferJSON::ExportToFile(filename, snap, option); @@ -1683,13 +2086,78 @@ bool TWebCanvas::ProduceImage(TPad *pad, const char *fileName, Int_t width, Int_ if (!pad) return false; - auto json = TWebCanvas::CreatePadJSON(pad, TBufferJSON::kNoSpaces + TBufferJSON::kSameSuppression); + auto json = CreatePadJSON(pad, TBufferJSON::kNoSpaces + TBufferJSON::kSameSuppression, kTRUE); if (!json.Length()) return false; - return ROOT::Experimental::RWebDisplayHandle::ProduceImage(fileName, json.Data(), width ? width : pad->GetWw(), height ? height : pad->GetWh()); + if (!width && !height) { + if ((pad->GetCanvas() == pad) || (pad->IsA() == TCanvas::Class())) { + width = pad->GetWw(); + height = pad->GetWh(); + } else { + width = (Int_t) (pad->GetAbsWNDC() * pad->GetCanvas()->GetWw()); + height = (Int_t) (pad->GetAbsHNDC() * pad->GetCanvas()->GetWh()); + } + } + + return ROOT::RWebDisplayHandle::ProduceImage(fileName, json.Data(), width, height); } +////////////////////////////////////////////////////////////////////////////////////////// +/// Create images for several pads using batch (headless) capability of Chrome or Firefox browsers +/// Supported png, jpeg, svg, pdf, webp formats +/// One can include %d qualifier which will be replaced by image index using printf functionality. +/// If for pdf format %d qualifier not specified, all images will be stored in single PDF file. +/// For all other formats %d qualifier will be add before extension automatically + +bool TWebCanvas::ProduceImages(std::vector pads, const char *filename, Int_t width, Int_t height) +{ + if (pads.empty()) + return false; + + std::vector jsons; + std::vector widths, heights; + + bool isMultiPdf = (strstr(filename, ".pdf") || strstr(filename, ".PDF")) && strstr(filename, "%"); + bool is_multipdf_ok = true; + + for (unsigned n = 0; n < pads.size(); ++n) { + auto pad = pads[n]; + + auto json = CreatePadJSON(pad, TBufferJSON::kNoSpaces + TBufferJSON::kSameSuppression, kTRUE); + if (!json.Length()) + continue; + + Int_t w = width, h = height; + + if (!w && !h) { + if ((pad->GetCanvas() == pad) || (pad->IsA() == TCanvas::Class())) { + w = pad->GetWw(); + h = pad->GetWh(); + } else { + w = (Int_t) (pad->GetAbsWNDC() * pad->GetCanvas()->GetWw()); + h = (Int_t) (pad->GetAbsHNDC() * pad->GetCanvas()->GetWh()); + } + } + + if (isMultiPdf) { + TString pdfname = TString::Format(filename, (int)n); + if (!ROOT::RWebDisplayHandle::ProduceImage(pdfname.Data(), json.Data(), w, h)) + is_multipdf_ok = false; + } else { + jsons.emplace_back(json.Data()); + widths.emplace_back(w); + heights.emplace_back(h); + } + } + + if (isMultiPdf) + return is_multipdf_ok; + + return ROOT::RWebDisplayHandle::ProduceImages(filename, jsons, widths, heights); +} + + ////////////////////////////////////////////////////////////////////////////////////////// /// Process data for single primitive /// Returns object pad if object was modified @@ -1730,7 +2198,9 @@ TPad *TWebCanvas::ProcessObjectOptions(TWebObjectOptions &item, TPad *pad, int i modified = true; } - if (item.fcust.compare("frame") == 0) { + if (item.fcust.compare(0,10,"auto_exec:") == 0) { + ProcessLinesForObject(obj, item.fcust.substr(10)); + } else if (item.fcust.compare("frame") == 0) { if (obj && obj->InheritsFrom(TFrame::Class())) { TFrame *frame = static_cast(obj); if (item.fopt.size() >= 4) { @@ -1741,7 +2211,7 @@ TPad *TWebCanvas::ProcessObjectOptions(TWebObjectOptions &item, TPad *pad, int i modified = true; } } - } else if (item.fcust.compare("pave") == 0) { + } else if (item.fcust.compare(0,4,"pave") == 0) { if (obj && obj->InheritsFrom(TPave::Class())) { TPave *pave = static_cast(obj); if ((item.fopt.size() >= 4) && objpad) { @@ -1758,6 +2228,24 @@ TPad *TWebCanvas::ProcessObjectOptions(TWebObjectOptions &item, TPad *pad, int i pave->ConvertNDCtoPad(); } + if ((item.fcust.length() > 4) && pave->InheritsFrom(TPaveStats::Class())) { + // add text lines for statsbox + auto stats = static_cast(pave); + stats->Clear(); + size_t pos_start = 6, pos_end; + while ((pos_end = item.fcust.find(";;", pos_start)) != std::string::npos) { + stats->AddText(item.fcust.substr(pos_start, pos_end - pos_start).c_str()); + pos_start = pos_end + 2; + } + stats->AddText(item.fcust.substr(pos_start).c_str()); + } + } + } else if (item.fcust.compare(0,9,"func_fail") == 0) { + if (!fTF1UseSave) { + fTF1UseSave = kTRUE; + modified = true; + } else { + Error("ProcessObjectOptions", "Client fails to calculate function %s cl %s but it should not try!", obj ? obj->GetName() : "---", obj ? obj->ClassName() : "---"); } } @@ -1812,8 +2300,10 @@ TObject *TWebCanvas::FindPrimitive(const std::string &sid, int idcnt, TPad *pad, TH1 *h1 = obj->InheritsFrom(TH1::Class()) ? static_cast(obj) : nullptr; TGraph *gr = obj->InheritsFrom(TGraph::Class()) ? static_cast(obj) : nullptr; + TScatter *scatter = obj->InheritsFrom(TScatter::Class()) ? static_cast(obj) : nullptr; TMultiGraph *mg = obj->InheritsFrom(TMultiGraph::Class()) ? static_cast(obj) : nullptr; THStack *hs = obj->InheritsFrom(THStack::Class()) ? static_cast(obj) : nullptr; + TF1 *f1 = obj->InheritsFrom(TF1::Class()) ? static_cast(obj) : nullptr; if (search_hist) { if (objlnk) @@ -1823,10 +2313,14 @@ TObject *TWebCanvas::FindPrimitive(const std::string &sid, int idcnt, TPad *pad, return h1; if (gr) return getHistogram(gr); + if (scatter) + return getHistogram(scatter); if (mg && opt.Contains("A")) return getHistogram(mg); if (hs) return getHistogram(hs); + if (f1) + return getHistogram(f1); if (objlnk) *objlnk = nullptr; @@ -1838,13 +2332,17 @@ TObject *TWebCanvas::FindPrimitive(const std::string &sid, int idcnt, TPad *pad, if (objpad) *objpad = pad; - if (kind.find("hist") == 0) { + if (kind.compare(0, 4, "hist") == 0) { if (gr) obj = h1 = getHistogram(gr); else if (mg) obj = h1 = getHistogram(mg); else if (hs) obj = h1 = getHistogram(hs); + else if (scatter) + obj = h1 = getHistogram(scatter); + else if (f1) + obj = h1 = getHistogram(f1); kind.erase(0,4); if (!kind.empty() && (kind[0]=='#')) kind.erase(0,1); @@ -1858,12 +2356,17 @@ TObject *TWebCanvas::FindPrimitive(const std::string &sid, int idcnt, TPad *pad, if (h1 && (kind == "z")) return h1->GetZaxis(); - if ((h1 || gr) && !kind.empty() && (kind.compare(0,5,"func_") == 0)) { + if ((h1 || gr || scatter) && !kind.empty() && (kind.compare(0,5,"func_") == 0)) { auto funcname = kind.substr(5); - TCollection *col = h1 ? h1->GetListOfFunctions() : gr->GetListOfFunctions(); + TCollection *col = h1 ? h1->GetListOfFunctions() : (gr ? gr->GetListOfFunctions() : scatter->GetGraph()->GetListOfFunctions()); return col ? col->FindObject(funcname.c_str()) : nullptr; } + if ((h1 || gr) && !kind.empty() && (kind.compare(0,5,"indx_") == 0)) { + auto col = h1 ? h1->GetListOfFunctions() : gr->GetListOfFunctions(); + return col ? col->At(std::stoi(kind.substr(5))) : nullptr; + } + if (!kind.empty() && (kind.compare(0,7,"member_") == 0)) { auto member = kind.substr(7); auto offset = obj->IsA() ? obj->IsA()->GetDataMemberOffset(member.c_str()) : 0; @@ -1879,8 +2382,8 @@ TObject *TWebCanvas::FindPrimitive(const std::string &sid, int idcnt, TPad *pad, return obj; } - if (h1 || gr) { - TIter fiter(h1 ? h1->GetListOfFunctions() : gr->GetListOfFunctions()); + if (h1 || gr || scatter) { + TIter fiter(h1 ? h1->GetListOfFunctions() : (gr ? gr->GetListOfFunctions() : scatter->GetGraph()->GetListOfFunctions())); TObject *fobj = nullptr; while ((fobj = fiter()) != nullptr) if (TString::Hash(&fobj, sizeof(fobj)) == id) { @@ -1908,6 +2411,17 @@ TCanvasImp *TWebCanvas::NewCanvas(TCanvas *c, const char *name, Int_t x, Int_t y { Bool_t readonly = gEnv->GetValue("WebGui.FullCanvas", (Int_t) 1) == 0; - return new TWebCanvas(c, name, x, y, width, height, readonly); + auto imp = new TWebCanvas(c, name, x, y, width, height, readonly); + + c->fWindowTopX = x; + c->fWindowTopY = y; + c->fWindowWidth = width; + c->fWindowHeight = height; + if (!gROOT->IsBatch() && (height > 25)) + height -= 25; + c->fCw = width; + c->fCh = height; + + return imp; } diff --git a/gui/webgui6/src/TWebControlBar.cxx b/gui/webgui6/src/TWebControlBar.cxx index 3275b0fa5ccac..2bd567907f351 100644 --- a/gui/webgui6/src/TWebControlBar.cxx +++ b/gui/webgui6/src/TWebControlBar.cxx @@ -117,7 +117,7 @@ void TWebControlBar::Show() return; if (!fWindow) { - fWindow = ROOT::Experimental::RWebWindow::Create(); + fWindow = ROOT::RWebWindow::Create(); fWindow->SetConnLimit(1); // configure connections limit @@ -131,13 +131,10 @@ void TWebControlBar::Show() // data [this](unsigned connid, const std::string &arg) { ProcessData(connid, arg); - }, - // disconnect - [this](unsigned) { }); } - ROOT::Experimental::RWebDisplayArgs args; + ROOT::RWebDisplayArgs args; args.SetWidgetKind("TControlBar"); auto lst = fControlBar->GetListOfButtons(); diff --git a/gui/webgui6/src/TWebSnapshot.cxx b/gui/webgui6/src/TWebSnapshot.cxx index 8da73217c9a56..8a8ff0ab4ed3a 100644 --- a/gui/webgui6/src/TWebSnapshot.cxx +++ b/gui/webgui6/src/TWebSnapshot.cxx @@ -68,7 +68,7 @@ TWebSnapshot &TPadWebSnapshot::NewPrimitive(TObject *obj, const std::string &opt TPadWebSnapshot &TPadWebSnapshot::NewSubPad() { - auto res = new TPadWebSnapshot(IsReadOnly(), IsSetObjectIds()); + auto res = new TPadWebSnapshot(IsReadOnly(), IsSetObjectIds(), IsBatchMode()); fPrimitives.emplace_back(res); return *res; } diff --git a/hist/CMakeLists.txt b/hist/CMakeLists.txt index 54a4d5fb37851..a814cedf1f643 100644 --- a/hist/CMakeLists.txt +++ b/hist/CMakeLists.txt @@ -14,7 +14,7 @@ if (spectrum) add_subdirectory(spectrum) add_subdirectory(spectrumpainter) # special CMakeLists.txt endif() -if(xml) +if(unfold) add_subdirectory(unfold) endif() if(CMAKE_Fortran_COMPILER) diff --git a/hist/hbook/src/THbookFile.cxx b/hist/hbook/src/THbookFile.cxx index fa86b23cc900d..0ea9fb8906053 100644 --- a/hist/hbook/src/THbookFile.cxx +++ b/hist/hbook/src/THbookFile.cxx @@ -245,7 +245,7 @@ extern "C" void type_of_call hldir(DEFCHAR,DEFCHAR); #endif Bool_t THbookFile::fgPawInit = kFALSE; -Int_t *THbookFile::fgLuns = 0; +Int_t *THbookFile::fgLuns = nullptr; ClassImp(THbookFile); @@ -312,8 +312,8 @@ THbookFile::THbookFile(const char *fname, Int_t lrecl) if (ier || quest[0]) { fgLuns[fLun-10]=0; fLun = 0; - fList = 0; - fKeys = 0; + fList = nullptr; + fKeys = nullptr; MakeZombie(); return; } @@ -453,10 +453,10 @@ TObject *THbookFile::Get(Int_t idd) id = quest[20]; if (id == idd) break; } - if (id == 0) return 0; + if (id == 0) return nullptr; if (id != idd) { printf("Error cannot find ID = %d\n",idd); - return 0; + return nullptr; } int i999 = 999; @@ -473,12 +473,12 @@ TObject *THbookFile::Get(Int_t idd) hrin(id,i999,0); if (quest[0]) { printf("Error cannot read ID = %d\n",id); - return 0; + return nullptr; } hdcofl(); lcid = hcbook[10]; lcont = lq[lcid-1]; - TObject *obj = 0; + TObject *obj = nullptr; if (hcbits[3]) { if (iq[lcid-2] == 2) obj = ConvertRWN(id); else obj = ConvertCWN(id); @@ -611,7 +611,7 @@ TFile *THbookFile::Convert2root(const char *rootname, Int_t /*lrecl*/, opt.ToLower(); Int_t nch = strlen(rootname); - char *rfile=0; + char *rfile=nullptr; if (nch) { rfile = new char[nch+1]; strlcpy(rfile,rootname,nch+1); @@ -633,10 +633,10 @@ TFile *THbookFile::Convert2root(const char *rootname, Int_t /*lrecl*/, gSystem->Exec(cmd); delete [] cmd; - if (opt.Contains("no")) {delete [] rfile; return 0;} + if (opt.Contains("no")) {delete [] rfile; return nullptr;} TFile *f = new TFile(rfile); delete [] rfile; - if (f->IsZombie()) {delete f; f = 0;} + if (f->IsZombie()) {delete f; f = nullptr;} return f; } @@ -679,8 +679,8 @@ TObject *THbookFile::ConvertCWN(Int_t id) #endif Int_t bufpos = 0; - Int_t isachar = 0; - Int_t isabool = 0; + //Int_t isachar = 0; + //Int_t isabool = 0; char fullname[64]; char name[32]; char block[32]; @@ -772,9 +772,17 @@ TObject *THbookFile::ConvertCWN(Int_t id) // to be done boolflag[i] = -10; charflag[i] = 0; - if (itype == 4) {isabool++; boolflag[i] = bufpos; lenbool[i] = ielem;} + if (itype == 4) { + //isabool++; + boolflag[i] = bufpos; + lenbool[i] = ielem; + } bufpos += isize*ielem; - if (ischar) {isachar++; charflag[i] = bufpos-1; lenchar[i] = isize*ielem;} + if (ischar) { + //isachar++; + charflag[i] = bufpos - 1; + lenchar[i] = isize * ielem; + } TObjArray *ll= branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)ll->UncheckedAt(0); if (!leaf) continue; @@ -941,7 +949,7 @@ TObject *THbookFile::Convert1D(Int_t id) h1 = new TH1F(idname,chtitl,ncx,xmin,xmax); } if (hcbits[8]) h1->Sumw2(); - TGraph *gr = 0; + TGraph *gr = nullptr; if (hcbits[11]) { gr = new TGraph(ncx); h1->GetListOfFunctions()->Add(gr); diff --git a/hist/hbook/src/THbookKey.cxx b/hist/hbook/src/THbookKey.cxx index f63ab0e93e7b5..896f61d4a252b 100644 --- a/hist/hbook/src/THbookKey.cxx +++ b/hist/hbook/src/THbookKey.cxx @@ -57,7 +57,7 @@ void THbookKey::Browse(TBrowser *b) if (obj->InheritsFrom(TCollection::Class())) obj->Delete(); // delete also collection elements delete obj; - obj = 0; + obj = nullptr; } if (!obj) diff --git a/hist/hbook/src/THbookTree.cxx b/hist/hbook/src/THbookTree.cxx index ca792edffa221..fbc57552ae940 100644 --- a/hist/hbook/src/THbookTree.cxx +++ b/hist/hbook/src/THbookTree.cxx @@ -62,8 +62,8 @@ THbookTree::THbookTree(): TTree() { fID = 0; fType = 0; - fX = 0; - fFile = 0; + fX = nullptr; + fFile = nullptr; fInit = kFALSE; } @@ -75,8 +75,8 @@ THbookTree::THbookTree(const char *name,Int_t id) { fID = id; fType = 0; - fX = 0; - fFile = 0; + fX = nullptr; + fFile = nullptr; fInit = kFALSE; } diff --git a/hist/hist/CMakeLists.txt b/hist/hist/CMakeLists.txt index cac1ae14a3bb7..58a17430efe25 100644 --- a/hist/hist/CMakeLists.txt +++ b/hist/hist/CMakeLists.txt @@ -42,6 +42,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Hist TGraph.h TGraphSmooth.h TGraphTime.h + TScatter.h TH1C.h TH1D.h TH1F.h @@ -131,6 +132,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Hist TGraph2DAsymmErrors.cxx TGraphSmooth.cxx TGraphTime.cxx + TScatter.cxx TH1.cxx TH1K.cxx TH1Merger.cxx diff --git a/hist/hist/inc/HFitInterface.h b/hist/hist/inc/HFitInterface.h index ee0a8f59becd3..05fb3b8543b2f 100644 --- a/hist/hist/inc/HFitInterface.h +++ b/hist/hist/inc/HFitInterface.h @@ -45,11 +45,18 @@ namespace ROOT { class UnBinData; class SparseData; - enum EFitObjectType { + enum class EFitObjectType { kHistogram, kGraph }; + enum class EChisquareType { + kNeyman = 0, + kPLikeRatio, + kPearson + }; + + //#ifndef __CINT__ // does not link on Windows (why ??) @@ -166,7 +173,7 @@ namespace ROOT { /** compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation) */ - double Chisquare(const TH1 & h1, TF1 & f1, bool useRange, bool usePL = false); + double Chisquare(const TH1 & h1, TF1 & f1, bool useRange, EChisquareType type); /** compute the chi2 value for a graph given a function (see TGraph::Chisquare) diff --git a/hist/hist/inc/LinkDef.h b/hist/hist/inc/LinkDef.h index 236e729203a95..98102b2bb9038 100644 --- a/hist/hist/inc/LinkDef.h +++ b/hist/hist/inc/LinkDef.h @@ -48,6 +48,7 @@ #pragma link C++ class TGraphAsymmErrors-; #pragma link C++ class TGraphMultiErrors+; #pragma link C++ class TGraphBentErrors+; +#pragma link C++ class TScatter+; #pragma link C++ class TGraph2D-; #pragma link C++ class TGraph2DErrors-; #pragma link C++ class TGraph2DAsymmErrors-; diff --git a/hist/hist/inc/Math/WrappedTF1.h b/hist/hist/inc/Math/WrappedTF1.h index 96ea456ec7645..45cec4c2d6856 100644 --- a/hist/hist/inc/Math/WrappedTF1.h +++ b/hist/hist/inc/Math/WrappedTF1.h @@ -36,11 +36,11 @@ namespace ROOT { @ingroup CppFunctions */ - class WrappedTF1 : public ROOT::Math::IParamGradFunction, public ROOT::Math::IGradientOneDim { + class WrappedTF1 : public ROOT::Math::IParamGradFunction, public ROOT::Math::IGradientFunctionOneDim { public: - typedef ROOT::Math::IGradientOneDim IGrad; + typedef ROOT::Math::IGradientFunctionOneDim IGrad; typedef ROOT::Math::IParamGradFunction BaseGradFunc; typedef ROOT::Math::IParamGradFunction::BaseFunc BaseFunc; diff --git a/hist/hist/inc/TAxis.h b/hist/hist/inc/TAxis.h index 7362bfaad0c50..d057e6ae13137 100644 --- a/hist/hist/inc/TAxis.h +++ b/hist/hist/inc/TAxis.h @@ -26,6 +26,7 @@ #include "TArrayD.h" class THashList; +class TAxisModLab; class TAxis : public TNamed, public TAttAxis { @@ -52,6 +53,9 @@ class TAxis : public TNamed, public TAttAxis { Bool_t HasBinWithoutLabel() const; + + TAxisModLab *FindModLab(Int_t num, Double_t v = 0., Double_t eps = 0.) const; + public: /// TAxis status bits enum EStatusBits { @@ -127,6 +131,7 @@ class TAxis : public TNamed, public TAttAxis { virtual Bool_t GetTimeDisplay() const {return fTimeDisplay;} virtual const char *GetTimeFormat() const {return fTimeFormat.Data();} virtual const char *GetTimeFormatOnly() const; + UInt_t GetTimeOffset(); const char *GetTitle() const override {return fTitle.Data();} const TArrayD *GetXbins() const {return &fXbins;} Int_t GetFirst() const; @@ -151,7 +156,11 @@ class TAxis : public TNamed, public TAttAxis { void ChangeLabel(Int_t labNum=0, Double_t labAngle = -1., Double_t labSize = -1., Int_t labAlign = -1, Int_t labColor = -1 , Int_t labFont = -1, - TString labText = ""); // *MENU* + const TString &labText = ""); // *MENU* + void ChangeLabelByValue(Double_t labValue, Double_t labAngle = -1., + Double_t labSize = -1., Int_t labAlign = -1, + Int_t labColor = -1 , Int_t labFont = -1, + const TString &labText = ""); // *MENU* virtual void SetLimits(Double_t xmin, Double_t xmax) { /* set axis limits */ fXmin = xmin; fXmax = xmax; } // *MENU* void SetMoreLogLabels(Bool_t more=kTRUE); // *TOGGLE* *GETTER=GetMoreLogLabels void SetNoExponent(Bool_t noExponent=kTRUE); // *TOGGLE* *GETTER=GetNoExponent diff --git a/hist/hist/inc/TAxisModLab.h b/hist/hist/inc/TAxisModLab.h index cb943a779c20e..959a0b2a07913 100644 --- a/hist/hist/inc/TAxisModLab.h +++ b/hist/hist/inc/TAxisModLab.h @@ -2,7 +2,7 @@ // Author: Olivier Couet /************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * @@ -21,15 +21,16 @@ class TAxisModLab : public TObject, public TAttText { private: - - Int_t fLabNum; ///< Label number. - TString fLabText; ///< Label text + Int_t fLabNum; ///< Label number. + Double_t fLabValue; ///< Label value, used when label number is 0 + TString fLabText; ///< Alternative label text public: TAxisModLab(); void SetLabNum(Int_t n = 0); + void SetLabValue(Double_t v = 0.); void SetAngle(Double_t a = -1.); void SetSize(Double_t s = -1.); void SetAlign(Int_t a = -1); @@ -37,15 +38,16 @@ class TAxisModLab : public TObject, public TAttText { void SetFont(Int_t f = -1); void SetText(TString t = ""); - Int_t GetLabNum() {return fLabNum;} - Double_t GetAngle() {return fTextAngle;} - Double_t GetSize() {return fTextSize;} - Int_t GetAlign() {return fTextAlign;} - Int_t GetColor() {return fTextColor;} - Int_t GetFont() {return fTextFont;} - TString GetText() {return fLabText;} + Int_t GetLabNum() const { return fLabNum; } + Double_t GetLabValue() const { return fLabValue; } + Double_t GetAngle() const { return fTextAngle; } + Double_t GetSize() const { return fTextSize; } + Int_t GetAlign() const { return fTextAlign; } + Int_t GetColor() const { return fTextColor; } + Int_t GetFont() const { return fTextFont; } + const TString &GetText() const { return fLabText; } - ClassDefOverride(TAxisModLab,3) // Modified axis label + ClassDefOverride(TAxisModLab,4) // Modified axis label }; #endif diff --git a/hist/hist/inc/TEfficiency.h b/hist/hist/inc/TEfficiency.h index 570da16e67a70..686821075c80c 100644 --- a/hist/hist/inc/TEfficiency.h +++ b/hist/hist/inc/TEfficiency.h @@ -20,6 +20,7 @@ class TCollection; class TF1; class TGraphAsymmErrors; +class TGraph2DAsymmErrors; class TH1; class TH2; class TList; @@ -51,8 +52,9 @@ class TEfficiency: public TNamed, public TAttLine, public TAttFill, public TAttM Double_t fConfLevel; ///< Confidence level (default = 0.683, 1 sigma) TDirectory* fDirectory; ///Pointer to list of functions - TGraphAsymmErrors* fPaintGraph; /// - T EvalParTempl(const T *data, const Double_t *params = 0); + T EvalParTempl(const T *data, const Double_t *params = nullptr); #ifdef R__HAS_VECCORE inline double EvalParVec(const Double_t *data, const Double_t *params); diff --git a/hist/hist/inc/TFormula.h b/hist/hist/inc/TFormula.h index 34519c2c6fcc2..c0dea4f2eb302 100644 --- a/hist/hist/inc/TFormula.h +++ b/hist/hist/inc/TFormula.h @@ -243,7 +243,7 @@ class TFormula : public TNamed // template // T Eval(T x, T y = 0, T z = 0, T t = 0) const; template - T EvalPar(const T *x, const Double_t *params = 0) const { + T EvalPar(const T *x, const Double_t *params = nullptr) const { return EvalParVec(x, params); } #ifdef R__HAS_VECCORE diff --git a/hist/hist/inc/TGraph.h b/hist/hist/inc/TGraph.h index d6cb82e2586b3..9c7249a4d25bb 100644 --- a/hist/hist/inc/TGraph.h +++ b/hist/hist/inc/TGraph.h @@ -53,6 +53,7 @@ class TGraph : public TNamed, public TAttLine, public TAttFill, public TAttMarke static void SwapValues(Double_t* arr, Int_t pos1, Int_t pos2); virtual void SwapPoints(Int_t pos1, Int_t pos2); + virtual void UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low); virtual Double_t **Allocate(Int_t newsize); Double_t **AllocateArrays(Int_t Narrays, Int_t arraySize); @@ -95,31 +96,31 @@ class TGraph : public TNamed, public TAttLine, public TAttFill, public TAttMarke virtual void AddPoint(Double_t x, Double_t y) { SetPoint(fNpoints, x, y); } ///< Append a new point to the graph. virtual void Apply(TF1 *f); - void Browse(TBrowser *b) override; + void Browse(TBrowser *b) override; virtual Double_t Chisquare(TF1 *f1, Option_t *option="") const; static Bool_t CompareArg(const TGraph* gr, Int_t left, Int_t right); static Bool_t CompareX(const TGraph* gr, Int_t left, Int_t right); static Bool_t CompareY(const TGraph* gr, Int_t left, Int_t right); static Bool_t CompareRadius(const TGraph* gr, Int_t left, Int_t right); virtual void ComputeRange(Double_t &xmin, Double_t &ymin, Double_t &xmax, Double_t &ymax) const; - Int_t DistancetoPrimitive(Int_t px, Int_t py) override; - void Draw(Option_t *chopt="") override; + Int_t DistancetoPrimitive(Int_t px, Int_t py) override; + void Draw(Option_t *chopt="") override; virtual void DrawGraph(Int_t n, const Int_t *x, const Int_t *y, Option_t *option=""); virtual void DrawGraph(Int_t n, const Float_t *x, const Float_t *y, Option_t *option=""); virtual void DrawGraph(Int_t n, const Double_t *x=nullptr, const Double_t *y=nullptr, Option_t *option=""); virtual void DrawPanel(); // *MENU* virtual Double_t Eval(Double_t x, TSpline *spline=nullptr, Option_t *option="") const; - void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; + void ExecuteEvent(Int_t event, Int_t px, Int_t py) override; virtual void Expand(Int_t newsize); virtual void Expand(Int_t newsize, Int_t step); - TObject *FindObject(const char *name) const override; - TObject *FindObject(const TObject *obj) const override; + TObject *FindObject(const char *name) const override; + TObject *FindObject(const TObject *obj) const override; virtual TFitResultPtr Fit(const char *formula ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0); // *MENU* virtual TFitResultPtr Fit(TF1 *f1 ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0); virtual void FitPanel(); // *MENU* Bool_t GetEditable() const; TF1 *GetFunction(const char *name) const; - TH1F *GetHistogram() const; + virtual TH1F *GetHistogram() const; TList *GetListOfFunctions() const { return fFunctions; } virtual Double_t GetCorrelationFactor() const; virtual Double_t GetCovariance() const; @@ -149,7 +150,7 @@ class TGraph : public TNamed, public TAttLine, public TAttFill, public TAttMarke Double_t GetMinimum() const {return fMinimum;} TAxis *GetXaxis() const ; TAxis *GetYaxis() const ; - char *GetObjectInfo(Int_t px, Int_t py) const override; + char *GetObjectInfo(Int_t px, Int_t py) const override; virtual Int_t GetPoint(Int_t i, Double_t &x, Double_t &y) const; virtual Double_t GetPointX(Int_t i) const; virtual Double_t GetPointY(Int_t i) const; @@ -167,16 +168,16 @@ class TGraph : public TNamed, public TAttLine, public TAttFill, public TAttMarke virtual void LeastSquareLinearFit(Int_t n, Double_t &a0, Double_t &a1, Int_t &ifail, Double_t xmin=0, Double_t xmax=0); virtual Int_t Merge(TCollection* list); virtual void MovePoints(Double_t dx, Double_t dy, Bool_t logx = kFALSE, Bool_t logy = kFALSE); - void Paint(Option_t *chopt="") override; + void Paint(Option_t *chopt="") override; void PaintGraph(Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt); void PaintGrapHist(Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt); virtual void PaintStats(TF1 *fit); - void Print(Option_t *chopt="") const override; - void RecursiveRemove(TObject *obj) override; + void Print(Option_t *chopt="") const override; + void RecursiveRemove(TObject *obj) override; virtual Int_t RemovePoint(); // *MENU* virtual Int_t RemovePoint(Int_t ipoint); - void SavePrimitive(std::ostream &out, Option_t *option = "") override; - void SaveAs(const char *filename, Option_t *option = "") const override; + void SavePrimitive(std::ostream &out, Option_t *option = "") override; + void SaveAs(const char *filename, Option_t *option = "") const override; // *MENU* virtual void Scale(Double_t c1=1., Option_t *option="y"); // *MENU* virtual void SetEditable(Bool_t editable=kTRUE); // *TOGGLE* *GETTER=GetEditable virtual void SetHighlight(Bool_t set = kTRUE); // *TOGGLE* *GETTER=IsHighlight @@ -187,13 +188,13 @@ class TGraph : public TNamed, public TAttLine, public TAttFill, public TAttMarke virtual void SetPoint(Int_t i, Double_t x, Double_t y); virtual void SetPointX(Int_t i, Double_t x); virtual void SetPointY(Int_t i, Double_t y); - void SetName(const char *name="") override; // *MENU* - void SetNameTitle(const char *name="", const char *title="") override; + void SetName(const char *name="") override; // *MENU* + void SetNameTitle(const char *name="", const char *title="") override; virtual void SetStats(Bool_t stats=kTRUE); // *MENU* - void SetTitle(const char *title="") override; // *MENU* + void SetTitle(const char *title="") override; // *MENU* virtual void Sort(Bool_t (*greater)(const TGraph*, Int_t, Int_t)=&TGraph::CompareX, Bool_t ascending=kTRUE, Int_t low=0, Int_t high=-1111); - void UseCurrentStyle() override; + void UseCurrentStyle() override; void Zero(Int_t &k,Double_t AZ,Double_t BZ,Double_t E2,Double_t &X,Double_t &Y,Int_t maxiterations); ClassDefOverride(TGraph,4) //Graph graphics class diff --git a/hist/hist/inc/TGraphAsymmErrors.h b/hist/hist/inc/TGraphAsymmErrors.h index d8a0c98a824b8..5a1a3be3494a0 100644 --- a/hist/hist/inc/TGraphAsymmErrors.h +++ b/hist/hist/inc/TGraphAsymmErrors.h @@ -32,6 +32,7 @@ class TGraphAsymmErrors : public TGraph { Double_t *fEYhigh{nullptr}; ///<[fNpoints] array of Y high errors void SwapPoints(Int_t pos1, Int_t pos2) override; + void UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) override; Double_t** Allocate(Int_t size) override; void CopyAndRelease(Double_t **newarrays, diff --git a/hist/hist/inc/TGraphBentErrors.h b/hist/hist/inc/TGraphBentErrors.h index 7050e43272221..fce28abe17251 100644 --- a/hist/hist/inc/TGraphBentErrors.h +++ b/hist/hist/inc/TGraphBentErrors.h @@ -36,6 +36,7 @@ class TGraphBentErrors : public TGraph { Double_t *fEYhighd; ///<[fNpoints] array of Y high displacements void SwapPoints(Int_t pos1, Int_t pos2) override; + void UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) override; Double_t** Allocate(Int_t size) override; void CopyAndRelease(Double_t **newarrays, diff --git a/hist/hist/inc/TGraphErrors.h b/hist/hist/inc/TGraphErrors.h index b584467035603..6ff94e4291433 100644 --- a/hist/hist/inc/TGraphErrors.h +++ b/hist/hist/inc/TGraphErrors.h @@ -30,6 +30,7 @@ class TGraphErrors : public TGraph { Double_t *fEY{nullptr}; ///<[fNpoints] array of Y errors void SwapPoints(Int_t pos1, Int_t pos2) override; + void UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) override; Double_t** Allocate(Int_t size) override; void CopyAndRelease(Double_t **newarrays, diff --git a/hist/hist/inc/TGraphMultiErrors.h b/hist/hist/inc/TGraphMultiErrors.h index 9cda990a686de..8a6dfb4451586 100644 --- a/hist/hist/inc/TGraphMultiErrors.h +++ b/hist/hist/inc/TGraphMultiErrors.h @@ -51,6 +51,7 @@ class TGraphMultiErrors : public TGraph { void CalcYErrorsSum() const; Bool_t DoMerge(const TGraph *tg) override; void SwapPoints(Int_t pos1, Int_t pos2) override; + void UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) override; public: enum ESummationModes { diff --git a/hist/hist/inc/TGraphSmooth.h b/hist/hist/inc/TGraphSmooth.h index 97605c6b1ecd2..17a7427273bd5 100644 --- a/hist/hist/inc/TGraphSmooth.h +++ b/hist/hist/inc/TGraphSmooth.h @@ -1,22 +1,20 @@ // @(#)root/hist:$Id$ // Author: Christian Stratowa 30/09/2001 +/************************************************************************* + * Copyright (C) 2006, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + /****************************************************************************** -* Copyright(c) 2001- , Dr. Christian Stratowa, Vienna, Austria. * +* Copyright(c) 2001-2006, Dr. Christian Stratowa, Vienna, Austria. * * Author: Christian Stratowa with help from Rene Brun. * * * * Algorithms for smooth regression adapted from: * * R: A Computer Language for Statistical Data Analysis * -* Copyright (C) 1996 Robert Gentleman and Ross Ihaka * -* Copyright (C) 1999-2001 Robert Gentleman, Ross Ihaka and the * -* R Development Core Team * -* R is free software, for licensing see the GNU General Public License * -* http://www.ci.tuwien.ac.at/R-project/welcome.html * -* * -* Based on: "The ROOT System", All rights reserved. * -* Authors: Rene Brun and Fons Rademakers. * -* For the licensing terms of "The ROOT System" see $ROOTSYS/AA_LICENSE. * -* For the list of contributors to "The ROOT System" see $ROOTSYS/AA_CREDITS. * ******************************************************************************/ #ifndef ROOT_TGraphSmooth diff --git a/hist/hist/inc/TH1K.h b/hist/hist/inc/TH1K.h index 7d1e8944e72bd..ac3a79cc967bc 100644 --- a/hist/hist/inc/TH1K.h +++ b/hist/hist/inc/TH1K.h @@ -32,6 +32,9 @@ class TH1K : public TH1, public TArrayF { Int_t fNIn; Int_t fKOrd; //! Int_t fKCur; //! + + Double_t RetrieveBinContent(Int_t bin) const override { return GetBinContent(bin); } + public: TH1K(); TH1K(const char *name,const char *title,Int_t nbinsx,Double_t xlow,Double_t xup,Int_t k=0); diff --git a/hist/hist/inc/TH2.h b/hist/hist/inc/TH2.h index eb04ba292ac2f..6e2dbbba9f305 100644 --- a/hist/hist/inc/TH2.h +++ b/hist/hist/inc/TH2.h @@ -121,6 +121,7 @@ class TH2 : public TH1 { void SetBinContent(Int_t binx, Int_t biny, Int_t, Double_t content) override { SetBinContent(GetBin(binx, biny), content); } virtual void SetShowProjectionX(Int_t nbins=1); // *MENU* virtual void SetShowProjectionY(Int_t nbins=1); // *MENU* + virtual void SetShowProjectionXY(Int_t nbinsY=1, Int_t nbinsX=1); // *MENU* TH1 *ShowBackground(Int_t niter=20, Option_t *option="same") override; Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05) override; // *MENU* void Smooth(Int_t ntimes=1, Option_t *option="") override; // *MENU* diff --git a/hist/hist/inc/TH2Poly.h b/hist/hist/inc/TH2Poly.h index 21377f7fc21b3..8e88b076db92e 100644 --- a/hist/hist/inc/TH2Poly.h +++ b/hist/hist/inc/TH2Poly.h @@ -108,7 +108,7 @@ class TH2Poly : public TH2 { Double_t GetMinimum(Double_t minval) const override; Bool_t GetNewBinAdded() const{return fNewBinAdded;} Int_t GetNumberOfBins() const{return fNcells-kNOverflow;} - void Honeycomb(Double_t xstart, Double_t ystart, Double_t a, Int_t k, Int_t s); + void Honeycomb(Double_t xstart, Double_t ystart, Double_t a, Int_t k, Int_t s, Option_t* option = "v"); Double_t Integral(Option_t* option = "") const override; Long64_t Merge(TCollection *) override; void Reset(Option_t *option) override; diff --git a/hist/hist/inc/THnSparse.h b/hist/hist/inc/THnSparse.h index 0278012a5b406..8bc4dd0b2f384 100644 --- a/hist/hist/inc/THnSparse.h +++ b/hist/hist/inc/THnSparse.h @@ -207,8 +207,8 @@ class THnSparseT: public THnSparse { public: THnSparseT() {} THnSparseT(const char* name, const char* title, Int_t dim, - const Int_t* nbins, const Double_t* xmin = 0, - const Double_t* xmax = 0, Int_t chunksize = 1024 * 16): + const Int_t* nbins, const Double_t* xmin = nullptr, + const Double_t* xmax = nullptr, Int_t chunksize = 1024 * 16): THnSparse(name, title, dim, nbins, xmin, xmax, chunksize) {} TArray* GenerateArray() const override { return new CONT(GetChunkSize()); } diff --git a/hist/hist/inc/TNDArray.h b/hist/hist/inc/TNDArray.h index ae8c918ec79d7..cbad49352d3c8 100644 --- a/hist/hist/inc/TNDArray.h +++ b/hist/hist/inc/TNDArray.h @@ -96,11 +96,11 @@ class TNDArrayRef { TNDArrayRef operator[] (Int_t idx) const { if (!fData) return TNDArrayRef(0, 0); R__ASSERT(idx < fSizes[-1] / fSizes[0] && "index out of range!"); - return TNDArrayRef(fData + idx * fSizes[0], (fSizes[0] == 1) ? 0 : (fSizes + 1)); + return TNDArrayRef(fData + idx * fSizes[0], (fSizes[0] == 1) ? nullptr : (fSizes + 1)); } operator T() const { if (!fData) return T(); - R__ASSERT(fSizes == 0 && "Element operator can only be used on non-array element. Missing an operator[] level?"); + R__ASSERT(fSizes == nullptr && "Element operator can only be used on non-array element. Missing an operator[] level?"); return *fData; } diff --git a/hist/hist/inc/TScatter.h b/hist/hist/inc/TScatter.h new file mode 100644 index 0000000000000..c5dd3fd89929f --- /dev/null +++ b/hist/hist/inc/TScatter.h @@ -0,0 +1,73 @@ +// @(#)root/hist:$Id$ +// Author: Olivier Couet 18/05/2022 + +/************************************************************************* + * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#ifndef ROOT_TScatter +#define ROOT_TScatter + + +////////////////////////////////////////////////////////////////////////// +// // +// TScatter // +// // +// A scatter plot able to draw four variables on a single plot // +// // +////////////////////////////////////////////////////////////////////////// + +#include "TNamed.h" +#include "TAttLine.h" +#include "TAttFill.h" +#include "TAttMarker.h" +#include "TGraph.h" + +class TH2F; + +class TScatter : public TNamed, public TAttLine, public TAttFill, public TAttMarker { + +protected: + Int_t fMaxSize{-1}; /// - double ComputeChi2(const FitObject & h1, TF1 &f1, bool useRange, bool usePL ); + double ComputeChi2(const FitObject & h1, TF1 &f1, bool useRange, ROOT::Fit::EChisquareType type ); @@ -178,6 +178,11 @@ TFitResultPtr HFit::Fit(FitObject * h1, TF1 *f1 , Foption_t & fitOption , const if (fitOption.NoErrX) opt.fCoordErrors = false; // do not use coordinate errors when requested if (fitOption.W1 ) opt.fErrors1 = true; if (fitOption.W1 > 1) opt.fUseEmpty = true; // use empty bins with weight=1 + if (fitOption.PChi2 == 1) { + opt.fErrors1 = true; // we are not using errors in chi2, it is like setting = 1 + } else if (fitOption.PChi2 == 2) { + opt.fErrors1 = false; // we need the errors in weighted likelihood fit + } if (fitOption.BinVolume) { opt.fBinVolume = true; // scale by bin volume @@ -348,7 +353,7 @@ TFitResultPtr HFit::Fit(FitObject * h1, TF1 *f1 , Foption_t & fitOption , const // check if can use option user //typedef void (* MinuitFCN_t )(int &npar, double *gin, double &f, double *u, int flag); - TVirtualFitter::FCNFunc_t userFcn = 0; + TVirtualFitter::FCNFunc_t userFcn = nullptr; if (fitOption.User && TVirtualFitter::GetFitter() ) { userFcn = (TVirtualFitter::GetFitter())->GetFCN(); (TVirtualFitter::GetFitter())->SetUserFunc(f1); @@ -522,7 +527,7 @@ void HFit::GetDrawingRange(TMultiGraph * mg, ROOT::Fit::DataRange & range) { double xmin = std::numeric_limits::infinity(); double xmax = -std::numeric_limits::infinity(); TIter next(mg->GetListOfGraphs() ); - TGraph * g = 0; + TGraph * g = nullptr; while ( (g = (TGraph*) next() ) ) { double x1 = 0, x2 = 0, y1 = 0, y2 = 0; g->ComputeRange(x1,y1,x2,y2); @@ -588,7 +593,7 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, TF1 * f1, const ROOT::Fit::Da #endif TList * funcList = h1->GetListOfFunctions(); - if (funcList == 0){ + if (funcList == nullptr){ Error("StoreAndDrawFitFunction","Function list has not been created - cannot store the fitted function"); return; } @@ -614,9 +619,9 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, TF1 * f1, const ROOT::Fit::Da } } - TF1 *fnew1 = 0; - TF2 *fnew2 = 0; - TF3 *fnew3 = 0; + TF1 *fnew1 = nullptr; + TF2 *fnew2 = nullptr; + TF3 *fnew3 = nullptr; // copy TF1 using TClass to avoid slicing in case of derived classes if (ndim < 2) { @@ -672,7 +677,7 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, TF1 * f1, const ROOT::Fit::Da if (drawFunction && ndim < 3 && h1->InheritsFrom(TH1::Class() ) ) { // no need to re-draw the histogram if the histogram is already in the pad // in that case the function will be just drawn (if option N is not set) - if (!gPad || (gPad && gPad->GetListOfPrimitives()->FindObject(h1) == NULL ) ) + if (!gPad || (gPad && gPad->GetListOfPrimitives()->FindObject(h1) == nullptr ) ) h1->Draw(goption); } if (gPad) gPad->Modified(); // this is not in TH1 code (needed ??) @@ -688,14 +693,14 @@ void ROOT::Fit::FitOptionsMake(EFitObjectType type, const char *option, Foption_ fitOption.ExecPolicy = ROOT::EExecutionPolicy::kMultiThread; } - if (option == 0) return; + if (option == nullptr) return; if (!option[0]) return; TString opt = option; opt.ToUpper(); // parse firt the specific options - if (type == kHistogram) { + if (type == EFitObjectType::kHistogram) { if (opt.Contains("WIDTH")) { fitOption.BinVolume = 1; // scale content by the bin width @@ -729,7 +734,13 @@ void ROOT::Fit::FitOptionsMake(EFitObjectType type, const char *option, Foption_ if (opt.Contains("WW")) fitOption.W1 = 2; //all bins have weight=1, even empty bins if (opt.Contains("L")) fitOption.Like = 1; if (opt.Contains("X")) fitOption.Chi2 = 1; - if (opt.Contains("P")) fitOption.PChi2 = 1; + if (opt.Contains("P")) { + fitOption.PChi2 = 1; + if (fitOption.W1) { // option contains also w is a weighted Pearson chi2 fit + fitOption.PChi2 = 2; + fitOption.W1 = 0; // does not make sense to have errors=1 in Pearson chi2 fits + } + } // specific likelihood fit options if (fitOption.Like == 1) { @@ -741,16 +752,12 @@ void ROOT::Fit::FitOptionsMake(EFitObjectType type, const char *option, Foption_ opt.ReplaceAll("MULTI",""); } // give precedence for likelihood options - if (fitOption.Chi2 == 1 || fitOption.PChi2 == 1) + if (fitOption.Chi2 || fitOption.PChi2 ) Warning("Fit","Cannot use P or X option in combination of L. Ignore the chi2 option and perform a likelihood fit"); } - if (fitOption.PChi2 && fitOption.W1) { - Warning("FitOptionsMake", "Ignore option W or WW when used together with option P (Pearson chi2)"); - fitOption.W1 = 0; // with Pearson chi2 W option is ignored - } } // specific Graph options (need to be parsed before) - else if (type == kGraph) { + else if (type == EFitObjectType::kGraph) { opt.ReplaceAll("ROB", "H"); opt.ReplaceAll("EX0", "T"); @@ -928,7 +935,7 @@ TFitResultPtr ROOT::Fit::UnBinFit(ROOT::Fit::UnBinData * data, TF1 * fitfunc, Fo // pass ownership of Fitter and Fitdata to TBackCompFitter (fitter pointer cannot be used afterwards) TBackCompFitter * bcfitter = new TBackCompFitter(fitter, fitdata); // cannot use anymore now fitdata (given away ownership) - fitdata = 0; + fitdata = nullptr; bcfitter->SetFitOption(fitOption); //bcfitter->SetObjectFit(fTree); bcfitter->SetUserFunc(fitfunc); @@ -1016,20 +1023,24 @@ TFitResultPtr ROOT::Fit::FitObject(THnBase * s1, TF1 *f1 , Foption_t & foption , // function to compute the simple chi2 for graphs and histograms -double ROOT::Fit::Chisquare(const TH1 & h1, TF1 & f1, bool useRange, bool usePL) { - return HFit::ComputeChi2(h1,f1,useRange, usePL); + +double ROOT::Fit::Chisquare(const TH1 & h1, TF1 & f1, bool useRange, ROOT::Fit::EChisquareType type) { + return HFit::ComputeChi2(h1,f1,useRange, type); } double ROOT::Fit::Chisquare(const TGraph & g, TF1 & f1, bool useRange) { - return HFit::ComputeChi2(g,f1, useRange, false); + return HFit::ComputeChi2(g,f1, useRange, ROOT::Fit::EChisquareType::kNeyman); } template -double HFit::ComputeChi2(const FitObject & obj, TF1 & f1, bool useRange, bool usePL ) { +double HFit::ComputeChi2(const FitObject & obj, TF1 & f1, bool useRange, ROOT::Fit::EChisquareType type ) { // implement using the fitting classes ROOT::Fit::DataOptions opt; - if (usePL) opt.fUseEmpty=true; + opt.fUseEmpty = (type != ROOT::Fit::EChisquareType::kNeyman); // use empty bin when not using Neyman chisquare (observed error) + opt.fExpErrors = (type == ROOT::Fit::EChisquareType::kPearson); + opt.fErrors1 = (type == ROOT::Fit::EChisquareType::kPearson); // not using observed errors in Pearson chi2 + ROOT::Fit::DataRange range; // get range of function if (useRange) HFit::GetFunctionRange(f1,range); @@ -1041,7 +1052,7 @@ double HFit::ComputeChi2(const FitObject & obj, TF1 & f1, bool useRange, bool return -1; } ROOT::Math::WrappedMultiTF1 wf1(f1); - if (usePL) { + if (type == ROOT::Fit::EChisquareType::kPLikeRatio) { // use the poisson log-lokelihood (Baker-Cousins chi2) ROOT::Fit::PoissonLLFunction nll(data, wf1); return 2.* nll( f1.GetParameters() ) ; diff --git a/hist/hist/src/HFitInterface.cxx b/hist/hist/src/HFitInterface.cxx index e2baff81ddce9..1d6c35a1525cc 100644 --- a/hist/hist/src/HFitInterface.cxx +++ b/hist/hist/src/HFitInterface.cxx @@ -53,7 +53,7 @@ namespace HFitInterface { bool IsPointOutOfRange(const TF1 * func, const double * x) { // function to check if a point is outside range - if (func ==0) return false; + if (func ==nullptr) return false; return !func->IsInside(x); } @@ -120,7 +120,7 @@ void FillData(BinData & dv, const TH1 * hfit, TF1 * func) // store instead of bin center the bin edges bool useBinEdges = fitOpt.fIntegral || fitOpt.fBinVolume; - assert(hfit != 0); + assert(hfit != nullptr); //std::cout << "creating Fit Data from histogram " << hfit->GetName() << std::endl; @@ -173,12 +173,12 @@ void FillData(BinData & dv, const TH1 * hfit, TF1 * func) int hdim = hfit->GetDimension(); int ndim = hdim; // case of function dimension less than histogram - if (func !=0 && func->GetNdim() == hdim-1) ndim = hdim-1; + if (func !=nullptr && func->GetNdim() == hdim-1) ndim = hdim-1; assert( ndim > 0 ); //typedef BinPoint::CoordData CoordData; //CoordData x = CoordData( hfit->GetDimension() ); - dv.Initialize(n,ndim); + dv.Initialize(n,ndim, (fitOpt.fErrors1) ? ROOT::Fit::BinData::kNoError : ROOT::Fit::BinData::kValueError); double x[3]; double s[3]; @@ -218,7 +218,7 @@ void FillData(BinData & dv, const TH1 * hfit, TF1 * func) // need to evaluate function to know about rejected points // hugly but no other solutions - if (func != 0) { + if (func != nullptr) { TF1::RejectPoint(false); (*func)( &x[0] ); // evaluate using stored function parameters if (TF1::RejectedPoint() ) continue; @@ -236,7 +236,10 @@ void FillData(BinData & dv, const TH1 * hfit, TF1 * func) if (hdim == 2) dv.Add( x, x[1], yaxis->GetBinWidth(biny) / error ); if (hdim == 3) dv.Add( x, x[2], zaxis->GetBinWidth(binz) / error ); } else { - dv.Add( x, value, error ); + if (fitOpt.fErrors1) + dv.Add( x, value ); + else + dv.Add( x, value, error ); if (useBinEdges) { dv.AddBinUpEdge( s ); } @@ -481,12 +484,12 @@ BinData::ErrorType GetDataType(const TGraph * gr, DataOptions & fitOpt) { // default case for graphs (when they have errors) BinData::ErrorType type = BinData::kValueError; // if all errors are zero set option of using errors to 1 - if (fitOpt.fErrors1 || ( ey == 0 && ( eyl == 0 || eyh == 0 ) ) ) { + if (fitOpt.fErrors1 || ( ey == nullptr && ( eyl == nullptr || eyh == nullptr ) ) ) { type = BinData::kNoError; } // need to treat case when all errors are zero // note that by default fitOpt.fCoordError is true - else if ( ex != 0 && fitOpt.fCoordErrors) { + else if ( ex != nullptr && fitOpt.fCoordErrors) { // check that all errors are not zero int i = 0; while (i < gr->GetN() && type != BinData::kCoordError) { @@ -495,7 +498,7 @@ BinData::ErrorType GetDataType(const TGraph * gr, DataOptions & fitOpt) { } } // case of asymmetric errors (by default fAsymErrors is true) - else if ( ( eyl != 0 && eyh != 0) && fitOpt.fAsymErrors) { + else if ( ( eyl != nullptr && eyh != nullptr) && fitOpt.fAsymErrors) { // check also if that all errors are non zero's int i = 0; bool zeroErrorX = true; @@ -521,7 +524,7 @@ BinData::ErrorType GetDataType(const TGraph * gr, DataOptions & fitOpt) { } // need to look also a case when all errors in y are zero - if ( ey != 0 && type != BinData::kCoordError ) { + if ( ey != nullptr && type != BinData::kCoordError ) { int i = 0; bool zeroError = true; while (i < gr->GetN() && zeroError) { @@ -548,10 +551,10 @@ BinData::ErrorType GetDataType(const TGraph2D * gr, const DataOptions & fitOpt) // default case for graphs (when they have errors) BinData::ErrorType type = BinData::kValueError; // if all errors are zero set option of using errors to 1 - if (fitOpt.fErrors1 || ez == 0 ) { + if (fitOpt.fErrors1 || ez == nullptr ) { type = BinData::kNoError; } - else if ( ex != 0 && ey!=0 && fitOpt.fCoordErrors) { + else if ( ex != nullptr && ey!=nullptr && fitOpt.fCoordErrors) { // check that all errors are not zero int i = 0; while (i < gr->GetN() && type != BinData::kCoordError) { @@ -726,7 +729,7 @@ void FillData(SparseData & dv, const THnBase * h1, TF1 * /*func*/) // std::cout << "FILLDATA(SparseData): h1(" << i << ")"; - // Exclude underflows and oveflows! (defect behaviour with the TH1*) + // Exclude underflows and overflows! (defect behaviour with the TH1*) bool insertBox = true; for ( int j = 0; j < dim && insertBox; ++j ) { @@ -769,7 +772,7 @@ void FillData(BinData & dv, const THnBase * s1, TF1 * func) // Put default options, needed for the likelihood fitting of sparse // data. ROOT::Fit::DataOptions& dopt = dv.Opt(); - dopt.fUseEmpty = true; + //dopt.fUseEmpty = true; // when using sparse data need to set option to use normalized bin volume, because sparse bins are merged together //if (!dopt.fIntegral) dopt.fBinVolume = true; dopt.fBinVolume = true; @@ -789,7 +792,7 @@ void FillData(BinData & dv, const THnBase * s1, TF1 * func) void FillData ( BinData & dv, const TGraph * gr, TF1 * func ) { // fill the data vector from a TGraph. Pass also the TF1 function which is // needed in case to exclude points rejected by the function - assert(gr != 0); + assert(gr != nullptr); // get fit option DataOptions & fitOpt = dv.Opt(); @@ -821,10 +824,10 @@ void FillData ( BinData & dv, const TGraph * gr, TF1 * func ) { void FillData ( BinData & dv, const TMultiGraph * mg, TF1 * func ) { // fill the data vector from a TMultiGraph. Pass also the TF1 function which is // needed in case to exclude points rejected by the function - assert(mg != 0); + assert(mg != nullptr); TList * grList = mg->GetListOfGraphs(); - assert(grList != 0); + assert(grList != nullptr); #ifdef DEBUG // grList->Print(); @@ -844,7 +847,7 @@ void FillData ( BinData & dv, const TMultiGraph * mg, TF1 * func ) { TIter next(grList); BinData::ErrorType type = BinData::kNoError; - TGraph *gr = 0; + TGraph *gr = nullptr; while ((gr = (TGraph*) next())) { BinData::ErrorType t = GetDataType(gr,fitOpt); if (t > type ) type = t; @@ -876,7 +879,7 @@ void FillData ( BinData & dv, const TGraph2D * gr, TF1 * func ) { // fill the data vector from a TGraph2D. Pass also the TF1 function which is // needed in case to exclude points rejected by the function // in case of a pure TGraph - assert(gr != 0); + assert(gr != nullptr); // get fit option DataOptions & fitOpt = dv.Opt(); @@ -892,7 +895,7 @@ void FillData ( BinData & dv, const TGraph2D * gr, TF1 * func ) { double *gz = gr->GetZ(); // if all errors are zero set option of using errors to 1 - if ( gr->GetEZ() == 0) fitOpt.fErrors1 = true; + if ( gr->GetEZ() == nullptr) fitOpt.fErrors1 = true; double x[2]; double ex[2]; @@ -966,7 +969,7 @@ bool GetConfidenceIntervals(const TH1 * h1, const ROOT::Fit::FitResult & result } // fill fit data sets with points to estimate cl. BinData d; - FillData(d,h1,0); + FillData(d,h1,nullptr); gr->Set(d.NPoints() ); double * ci = gr->GetEY(); // make CL values error of the graph result.GetConfidenceIntervals(d,ci,cl); diff --git a/hist/hist/src/Haxis.cxx b/hist/hist/src/Haxis.cxx index ea7c10e109eba..fa4af5942c25b 100644 --- a/hist/hist/src/Haxis.cxx +++ b/hist/hist/src/Haxis.cxx @@ -201,7 +201,7 @@ void TH1::SetAxisColor(Color_t color, Option_t *axis) void TH1::SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis) { Int_t ax = AxisChoice(axis); - TAxis *theAxis = 0; + TAxis *theAxis = nullptr; if (ax == 1) theAxis = GetXaxis(); if (ax == 2) theAxis = GetYaxis(); if (ax == 3) theAxis = GetZaxis(); diff --git a/hist/hist/src/TAxis.cxx b/hist/hist/src/TAxis.cxx index fa1808923dff4..4e06a49117e99 100644 --- a/hist/hist/src/TAxis.cxx +++ b/hist/hist/src/TAxis.cxx @@ -299,13 +299,13 @@ Int_t TAxis::FindBin(Double_t x) if (IsAlphanumeric() && gDebug) Info("FindBin","Numeric query on alphanumeric axis - Sorting the bins or extending the axes / rebinning can alter the correspondence between the label and the bin interval."); if (x < fXmin) { //*-* underflow bin = 0; - if (fParent == 0) return bin; + if (fParent == nullptr) return bin; if (!CanExtend() || IsAlphanumeric() ) return bin; ((TH1*)fParent)->ExtendAxis(x,this); return FindFixBin(x); } else if ( !(x < fXmax)) { //*-* overflow (note the way to catch NaN) bin = fNbins+1; - if (fParent == 0) return bin; + if (fParent == nullptr) return bin; if (!CanExtend() || IsAlphanumeric() ) return bin; ((TH1*)fParent)->ExtendAxis(x,this); return FindFixBin(x); @@ -608,6 +608,26 @@ const char *TAxis::GetTimeFormatOnly() const return timeformat.Data(); } +//////////////////////////////////////////////////////////////////////////////// +/// Return the time offset in GMT. + +UInt_t TAxis::GetTimeOffset() { + + Int_t idF = fTimeFormat.Index("%F")+2; + if (idF<2) { + Warning("GetGMTimeOffset","Time format is not set!"); + return 0; + } + TString stime=fTimeFormat(idF,19); + if (stime.Length() != 19) { + Warning("GetGMTimeOffset","Bad time format!"); + return 0; + } + + TDatime datime(stime.Data()); + return datime.Convert(kTRUE); // Convert to unix gmt time +} + //////////////////////////////////////////////////////////////////////////////// /// Return the ticks option (see SetTicks) @@ -749,7 +769,21 @@ void TAxis::SaveAttributes(std::ostream &out, const char *name, const char *subn if (TestBit(kNoExponent)) { out<<" "<SetNoExponent();"<GetLabNum() == 0) + out<<" "<ChangeLabelByValue("<GetLabValue()<<","; + else + out<<" "<ChangeLabel("<GetLabNum()<<","; + out<GetAngle()<<"," + <GetSize()<<"," + <GetAlign()<<"," + <GetColor()<<"," + <GetFont()<<"," + <GetText()<GetLabNum() != num) + continue; + + if ((num != 0) || (TMath::Abs(v - ml->GetLabValue()) <= eps)) + return ml; + } + + return nullptr; +} + + //////////////////////////////////////////////////////////////////////////////// /// Define new text attributes for the label number "labNum". It allows to do a /// fine tuning of the labels. All the attributes can be changed, even the @@ -903,28 +958,72 @@ void TAxis::SetBinLabel(Int_t bin, const char *label) /// - To retrieve the number of axis labels use TAxis::GetNlabels. void TAxis::ChangeLabel(Int_t labNum, Double_t labAngle, Double_t labSize, - Int_t labAlign, Int_t labColor, Int_t labFont, - TString labText) + Int_t labAlign, Int_t labColor, Int_t labFont, + const TString &labText) { - if (!fModLabs) fModLabs = new TList(); - // Reset the list of modified labels. if (labNum == 0) { - delete fModLabs; - fModLabs = 0; + SafeDelete(fModLabs); return; } - TAxisModLab *ml = new TAxisModLab(); - ml->SetLabNum(labNum); + if (!fModLabs) fModLabs = new TList(); + + TAxisModLab *ml = FindModLab(labNum); + if (!ml) { + ml = new TAxisModLab(); + ml->SetLabNum(labNum); + fModLabs->Add(ml); + } + ml->SetAngle(labAngle); ml->SetSize(labSize); ml->SetAlign(labAlign); ml->SetColor(labColor); ml->SetFont(labFont); ml->SetText(labText); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Define new text attributes for the label value "labValue". It allows to do a +/// fine tuning of the labels. All the attributes can be changed, even the +/// label text itself. +/// +/// \param[in] labValue Axis value to be changed +/// \param[in] labAngle New angle value +/// \param[in] labSize New size (0 erase the label) +/// \param[in] labAlign New alignment value +/// \param[in] labColor New label color +/// \param[in] labFont New label font +/// \param[in] labText New label text +/// +/// #### Notes: +/// +/// - If an attribute should not be changed just give the value "-1". +/// - If labnum=0 the list of modified labels is reset. +/// - To erase a label set labSize to 0. +/// - If labText is not specified or is an empty string, the text label is not changed. +/// - To retrieve the number of axis labels use TAxis::GetNlabels. + +void TAxis::ChangeLabelByValue(Double_t labValue, Double_t labAngle, Double_t labSize, + Int_t labAlign, Int_t labColor, Int_t labFont, + const TString &labText) +{ + if (!fModLabs) fModLabs = new TList(); + + TAxisModLab *ml = FindModLab(0, labValue, 0.); + if (!ml) { + ml = new TAxisModLab(); + ml->SetLabValue(labValue); + fModLabs->Add(ml); + } - fModLabs->Add((TObject*)ml); + ml->SetAngle(labAngle); + ml->SetSize(labSize); + ml->SetAlign(labAlign); + ml->SetColor(labColor); + ml->SetFont(labFont); + ml->SetText(labText); } @@ -1125,7 +1224,7 @@ void TAxis::Streamer(TBuffer &R__b) Float_t xmin,xmax; R__b >> xmin; fXmin = xmin; R__b >> xmax; fXmax = xmax; - Float_t *xbins = 0; + Float_t *xbins = nullptr; Int_t n = R__b.ReadArray(xbins); fXbins.Set(n); for (Int_t i=0;i=0.) fTextAngle = a; +void TAxisModLab::SetAngle(Double_t a) +{ + if (a >= 0.) fTextAngle = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label size. -void TAxisModLab::SetSize(Double_t s) { - if (s>=0.) fTextSize = s; +void TAxisModLab::SetSize(Double_t s) +{ + if (s >= 0.) fTextSize = s; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label alignment. -void TAxisModLab::SetAlign(Int_t a) { - if (a>0) fTextAlign = a; +void TAxisModLab::SetAlign(Int_t a) +{ + if (a > 0) fTextAlign = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label color. -void TAxisModLab::SetColor(Int_t c) { - if (c>0) fTextColor = c; +void TAxisModLab::SetColor(Int_t c) +{ + if (c > 0) fTextColor = c; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label font. -void TAxisModLab::SetFont(Int_t f) { - if (f>0) fTextFont = f; +void TAxisModLab::SetFont(Int_t f) +{ + if (f > 0) fTextFont = f; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label text. -void TAxisModLab::SetText(TString s) { - fLabText = s; +void TAxisModLab::SetText(TString s) +{ + fLabText = s; } diff --git a/hist/hist/src/TBackCompFitter.cxx b/hist/hist/src/TBackCompFitter.cxx index 7a99de648612b..5b709ea1aff61 100644 --- a/hist/hist/src/TBackCompFitter.cxx +++ b/hist/hist/src/TBackCompFitter.cxx @@ -75,9 +75,9 @@ ClassImp(TBackCompFitter); /// initialize setting name and the global pointer TBackCompFitter::TBackCompFitter( ) : - fMinimizer(0), - fObjFunc(0), - fModelFunc(0) + fMinimizer(nullptr), + fObjFunc(nullptr), + fModelFunc(nullptr) { SetName("BCFitter"); } @@ -89,9 +89,9 @@ TBackCompFitter::TBackCompFitter( ) : TBackCompFitter::TBackCompFitter(const std::shared_ptr & fitter, const std::shared_ptr & data) : fFitData(data), fFitter(fitter), - fMinimizer(0), - fObjFunc(0), - fModelFunc(0) + fMinimizer(nullptr), + fObjFunc(nullptr), + fModelFunc(nullptr) { SetName("LastFitter"); } @@ -280,7 +280,7 @@ Int_t TBackCompFitter::ExecuteCommand(const char *command, Double_t *args, Int_t else if (scommand.Contains("CALL FCN")) { // call fcn function (global pointer to free function) - if (nargs < 1 || fFCN == 0 ) return -1; + if (nargs < 1 || fFCN == nullptr ) return -1; int npar = fObjFunc->NDim(); // use values in fit result if existing otherwise in ParameterSettings std::vector params(npar); @@ -288,7 +288,7 @@ Int_t TBackCompFitter::ExecuteCommand(const char *command, Double_t *args, Int_t params[i] = GetParameter(i); double fval = 0; - (*fFCN)(npar, 0, fval, ¶ms[0],int(args[0]) ) ; + (*fFCN)(npar, nullptr, fval, ¶ms[0],int(args[0]) ) ; return 0; } else { @@ -383,7 +383,7 @@ void TBackCompFitter::GetConfidenceIntervals(TObject *obj, Double_t cl) if (fitobj->InheritsFrom(TGraph2D::Class())) datadim = 2; if (fitobj->InheritsFrom(TH1::Class())) { TH1 * h1 = dynamic_cast(fitobj); - assert(h1 != 0); + assert(h1 != nullptr); datadim = h1->GetDimension(); } @@ -427,7 +427,7 @@ void TBackCompFitter::GetConfidenceIntervals(TObject *obj, Double_t cl) fFitter->Result().GetConfidenceIntervals(data,&ci[0],cl,false); const ROOT::Math::IParamMultiFunction * func = fFitter->Result().FittedFunction(); - assert(func != 0); + assert(func != nullptr); // fill now the object with cl data for (unsigned int i = 0; i < n; ++i) { @@ -436,19 +436,19 @@ void TBackCompFitter::GetConfidenceIntervals(TObject *obj, Double_t cl) if (obj->InheritsFrom(TGraphErrors::Class()) ) { TGraphErrors * gr = dynamic_cast (obj); - assert(gr != 0); + assert(gr != nullptr); gr->SetPoint(i, *x, y); gr->SetPointError(i, 0, ci[i]); } if (obj->InheritsFrom(TGraph2DErrors::Class()) ) { TGraph2DErrors * gr = dynamic_cast (obj); - assert(gr != 0); + assert(gr != nullptr); gr->SetPoint(i, x[0], x[1], y); gr->SetPointError(i, 0, 0, ci[i]); } if (obj->InheritsFrom(TH1::Class()) ) { TH1 * h1 = dynamic_cast (obj); - assert(h1 != 0); + assert(h1 != nullptr); int ibin = 0; if (datadim == 1) ibin = h1->FindBin(*x); if (datadim == 2) ibin = h1->FindBin(x[0],x[1]); @@ -473,7 +473,7 @@ Double_t* TBackCompFitter::GetCovarianceMatrix() const { if (!fFitter->Result().IsValid() ) { Warning("GetCovarianceMatrix","Invalid fit result"); - return 0; + return nullptr; } unsigned int l = 0; @@ -500,7 +500,7 @@ Double_t TBackCompFitter::GetCovarianceMatrixElement(Int_t i, Int_t j) const { unsigned int npar = GetNumberFreeParameters(); if ( np2 == 0 || np2 != npar *npar ) { double * c = GetCovarianceMatrix(); - if (c == 0) return 0; + if (c == nullptr) return 0; } return fCovar[i*npar + j]; } @@ -589,7 +589,7 @@ Int_t TBackCompFitter::GetParameter(Int_t ipar,char *name,Double_t &value,Double const char *TBackCompFitter::GetParName(Int_t ipar) const { if (!ValidParameterIndex(ipar) ) { - return 0; + return nullptr; } return fFitter->Config().ParSettings(ipar).Name().c_str(); } @@ -689,7 +689,7 @@ void TBackCompFitter::ReCreateMinimizer() { assert(fFitData.get()); // case of standard fits (not made fia Fitter::FitFCN) - if (fFitter->Result().FittedFunction() != 0) { + if (fFitter->Result().FittedFunction() != nullptr) { if (fModelFunc) delete fModelFunc; fModelFunc = dynamic_cast((fFitter->Result().FittedFunction())->Clone()); @@ -712,7 +712,7 @@ void TBackCompFitter::ReCreateMinimizer() { // recreate the minimizer fMinimizer = fFitter->Config().CreateMinimizer(); - if (fMinimizer == 0) { + if (fMinimizer == nullptr) { Error("SetMinimizerFunction","cannot create minimizer %s",fFitter->Config().MinimizerType().c_str() ); } else { @@ -754,7 +754,7 @@ void TBackCompFitter::SetObjFunction(ROOT::Math::IMultiGenFunction * fcn) { void TBackCompFitter::DoSetDimension() { if (!fObjFunc) return; ROOT::Fit::FcnAdapter * fobj = dynamic_cast(fObjFunc); - assert(fobj != 0); + assert(fobj != nullptr); int ndim = fFitter->Config().ParamsSettings().size(); if (ndim != 0) fobj->SetDimension(ndim); } @@ -785,7 +785,7 @@ ROOT::Math::Minimizer * TBackCompFitter::GetMinimizer( ) const { /// Return a new copy of the TFitResult object which needs to be deleted later by the user TFitResult * TBackCompFitter::GetTFitResult( ) const { - if (!fFitter.get() ) return 0; + if (!fFitter.get() ) return nullptr; return new TFitResult( fFitter->Result() ); } diff --git a/hist/hist/src/TBinomialEfficiencyFitter.cxx b/hist/hist/src/TBinomialEfficiencyFitter.cxx index e81c889919216..8ee35f928e8dd 100644 --- a/hist/hist/src/TBinomialEfficiencyFitter.cxx +++ b/hist/hist/src/TBinomialEfficiencyFitter.cxx @@ -99,14 +99,14 @@ ClassImp(TBinomialEfficiencyFitter); /// default constructor TBinomialEfficiencyFitter::TBinomialEfficiencyFitter() { - fNumerator = 0; - fDenominator = 0; - fFunction = 0; + fNumerator = nullptr; + fDenominator = nullptr; + fFunction = nullptr; fFitDone = kFALSE; fAverage = kFALSE; fRange = kFALSE; fEpsilon = kDefaultEpsilon; - fFitter = 0; + fFitter = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -120,8 +120,8 @@ TBinomialEfficiencyFitter::TBinomialEfficiencyFitter() { TBinomialEfficiencyFitter::TBinomialEfficiencyFitter(const TH1 *numerator, const TH1 *denominator) { fEpsilon = kDefaultEpsilon; - fFunction = 0; - fFitter = 0; + fFunction = nullptr; + fFitter = nullptr; Set(numerator,denominator); } @@ -130,7 +130,7 @@ TBinomialEfficiencyFitter::TBinomialEfficiencyFitter(const TH1 *numerator, const TBinomialEfficiencyFitter::~TBinomialEfficiencyFitter() { if (fFitter) delete fFitter; - fFitter = 0; + fFitter = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -282,28 +282,33 @@ TFitResultPtr TBinomialEfficiencyFitter::Fit(TF1 *f1, Option_t* option) // perform the actual fit - fFitDone = kTRUE; + // set the fit to be a binned likelihood fit + // so use as chi2 for goodness of fit Baker&Cousins LR + fFitter->SetFitType(3); Bool_t status = fFitter->FitFCN(); if ( !status && !quiet) Warning("Fit","Abnormal termination of minimization."); + fFitDone = kTRUE; + + // set the number of fitted points + // number of fit points is set in ComputeFCN in the TF1 object + fFitter->SetNumberOfFitPoints(f1->GetNumberFitPoints()); //Store fit results in fitFunction const ROOT::Fit::FitResult & fitResult = fFitter->Result(); if (!fitResult.IsEmpty() ) { - // set in f1 the result of the fit f1->SetNDF(fitResult.Ndf() ); - - //f1->SetNumberFitPoints(...); // this is set in ComputeFCN + f1->SetChisquare(fitResult.Chi2()); f1->SetParameters( &(fitResult.Parameters().front()) ); if ( int( fitResult.Errors().size()) >= f1->GetNpar() ) f1->SetParErrors( &(fitResult.Errors().front()) ); - f1->SetChisquare(2.*fitResult.MinFcnValue()); // store goodness of fit (Baker&Cousins) - f1->SetNDF(f1->GetNumberFitPoints()- fitResult.NFreeParameters()); - Info("result"," chi2 %f ndf %d ",2.*fitResult.MinFcnValue(), fitResult.Ndf() ); - + if (!quiet) { + Info("Fit","Successful Result from Binomial Efficiency fitter of function %s",f1->GetName()); + fitResult.Print(std::cout); + } } // create a new result class if needed if (saveResult) { diff --git a/hist/hist/src/TConfidenceLevel.cxx b/hist/hist/src/TConfidenceLevel.cxx index 8f59c4666ec56..4018310b697f1 100644 --- a/hist/hist/src/TConfidenceLevel.cxx +++ b/hist/hist/src/TConfidenceLevel.cxx @@ -42,14 +42,14 @@ TConfidenceLevel::TConfidenceLevel() fBtot = 0; fDtot = 0; fTSD = 0; - fTSB = 0; - fTSS = 0; - fLRS = 0; - fLRB = 0; + fTSB = nullptr; + fTSS = nullptr; + fLRS = nullptr; + fLRB = nullptr; fNMC = 0; fNNMC = 0; - fISS = 0; - fISB = 0; + fISS = nullptr; + fISB = nullptr; fMCL3S = fgMCL3S1S; fMCL5S = fgMCL5S1S; } @@ -66,10 +66,10 @@ TConfidenceLevel::TConfidenceLevel(Int_t mc, bool onesided) fBtot = 0; fDtot = 0; fTSD = 0; - fTSB = 0; - fTSS = 0; - fLRS = 0; - fLRB = 0; + fTSB = nullptr; + fTSS = nullptr; + fLRS = nullptr; + fLRB = nullptr; fNMC = mc; fNNMC = mc; fISS = new Int_t[mc]; diff --git a/hist/hist/src/TEfficiency.cxx b/hist/hist/src/TEfficiency.cxx index efeec36091aa7..1b7a22f164341 100644 --- a/hist/hist/src/TEfficiency.cxx +++ b/hist/hist/src/TEfficiency.cxx @@ -14,6 +14,7 @@ #include "TDirectory.h" #include "TF1.h" #include "TGraphAsymmErrors.h" +#include "TGraph2DAsymmErrors.h" #include "TH1.h" #include "TH2.h" #include "TH3.h" @@ -643,14 +644,14 @@ for a TH2::Draw object. TEfficiency::TEfficiency(): fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), -fBoundary(0), +fBoundary(nullptr), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), -fPassedHistogram(0), -fTotalHistogram(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), +fPassedHistogram(nullptr), +fTotalHistogram(nullptr), fWeight(kDefWeight) { SetStatisticOption(kDefStatOpt); @@ -683,10 +684,10 @@ TEfficiency::TEfficiency(const TH1& passed,const TH1& total): fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { //check consistency of histograms @@ -723,7 +724,7 @@ fWeight(kDefWeight) SetBit(kShortestInterval,false); SetStatisticOption(kDefStatOpt); - SetDirectory(0); + SetDirectory(nullptr); } //////////////////////////////////////////////////////////////////////////////// @@ -750,10 +751,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbins, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -791,10 +792,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbinsx, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -834,10 +835,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbinsx, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -877,10 +878,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbinsx, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -924,10 +925,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbinsx, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -971,10 +972,10 @@ TEfficiency::TEfficiency(const char* name,const char* title,Int_t nbinsx, fBeta_alpha(kDefBetaAlpha), fBeta_beta(kDefBetaBeta), fConfLevel(kDefConfLevel), -fDirectory(0), -fFunctions(0), -fPaintGraph(0), -fPaintHisto(0), +fDirectory(nullptr), +fFunctions(nullptr), +fPaintGraph(nullptr), +fPaintHisto(nullptr), fWeight(kDefWeight) { // do not add new created histograms to gDirectory @@ -1012,10 +1013,10 @@ TEfficiency::TEfficiency(const TEfficiency& rEff): fBeta_beta(rEff.fBeta_beta), fBeta_bin_params(rEff.fBeta_bin_params), fConfLevel(rEff.fConfLevel), - fDirectory(0), - fFunctions(0), - fPaintGraph(0), - fPaintHisto(0), + fDirectory(nullptr), + fFunctions(nullptr), + fPaintGraph(nullptr), + fPaintHisto(nullptr), fWeight(rEff.fWeight) { // copy TObject bits @@ -1037,7 +1038,7 @@ TEfficiency::TEfficiency(const TEfficiency& rEff): SetStatisticOption(rEff.GetStatisticOption()); - SetDirectory(0); + SetDirectory(nullptr); //copy style rEff.TAttLine::Copy(*this); @@ -1055,17 +1056,17 @@ TEfficiency::~TEfficiency() // (see TH1::~TH1 code in TH1.cxx) if(fFunctions) { fFunctions->SetBit(kInvalidObject); - TObject* obj = 0; + TObject* obj = nullptr; while ((obj = fFunctions->First())) { while(fFunctions->Remove(obj)) { } if (ROOT::Detail::HasBeenDeleted(obj)) { break; } delete obj; - obj = 0; + obj = nullptr; } delete fFunctions; - fFunctions = 0; + fFunctions = nullptr; } if(fDirectory) @@ -1479,8 +1480,8 @@ void TEfficiency::Build(const char* name,const char* title) Bool_t TEfficiency::CheckBinning(const TH1& pass,const TH1& total) { - const TAxis* ax1 = 0; - const TAxis* ax2 = 0; + const TAxis* ax1 = nullptr; + const TAxis* ax2 = nullptr; //check binning along axis for(Int_t j = 0; j < pass.GetDimension(); ++j) { @@ -1620,10 +1621,9 @@ TGraphAsymmErrors * TEfficiency::CreateGraph(Option_t * opt) const { if (GetDimension() != 1) { Error("CreatePaintingGraph","Call this function only for dimension == 1"); - return 0; + return nullptr; } - Int_t npoints = fTotalHistogram->GetNbinsX(); TGraphAsymmErrors * graph = new TGraphAsymmErrors(npoints); graph->SetName("eff_graph"); @@ -1632,11 +1632,132 @@ TGraphAsymmErrors * TEfficiency::CreateGraph(Option_t * opt) const return graph; } +/////////////////////////////////////////////////////////////////////////////// +/// Create the graph used be painted (for dim=1 TEfficiency) +/// The return object is managed by the caller + +TGraph2DAsymmErrors * TEfficiency::CreateGraph2D(Option_t * opt) const +{ + if (GetDimension() != 2) { + Error("CreatePaintingGraph","Call this function only for dimension == 2"); + return nullptr; + } + + Int_t npoints = fTotalHistogram->GetNbinsX()*fTotalHistogram->GetNbinsY(); + TGraph2DAsymmErrors * graph = new TGraph2DAsymmErrors(npoints); + graph->SetName("eff_graph"); + FillGraph2D(graph,opt); + + return graph; +} //////////////////////////////////////////////////////////////////////////////// /// Fill the graph to be painted with information from TEfficiency /// Internal method called by TEfficiency::Paint or TEfficiency::CreateGraph +void TEfficiency::FillGraph2D(TGraph2DAsymmErrors * graph, Option_t * opt) const +{ + TString option = opt; + option.ToLower(); + + Bool_t plot0Bins = false; + if (option.Contains("e0") ) plot0Bins = true; + + //point i corresponds to bin i+1 in histogram + // point j is point graph index + // LM: cannot use TGraph::SetPoint because it deletes the underlying + // histogram each time (see TGraph::SetPoint) + // so use it only when extra points are added to the graph + int ipoint = 0; + double * px = graph->GetX(); + double * py = graph->GetY(); + double * pz = graph->GetZ(); + double * exl = graph->GetEXlow(); + double * exh = graph->GetEXhigh(); + double * eyl = graph->GetEYlow(); + double * eyh = graph->GetEYhigh(); + double * ezl = graph->GetEZlow(); + double * ezh = graph->GetEZhigh(); + for (int i = 0; i < fTotalHistogram->GetNbinsX(); ++i) { + double x = fTotalHistogram->GetXaxis()->GetBinCenter(i+1); + double xlow = fTotalHistogram->GetXaxis()->GetBinCenter(i+1) - fTotalHistogram->GetXaxis()->GetBinLowEdge(i+1); + double xup = fTotalHistogram->GetXaxis()->GetBinWidth(i+1) - xlow; + for (int j = 0; j < fTotalHistogram->GetNbinsY(); ++j) { + if (!plot0Bins && fTotalHistogram->GetBinContent(i+1,j+1) == 0 ) + continue; + double y = fTotalHistogram->GetYaxis()->GetBinCenter(j+1); + double ylow = fTotalHistogram->GetYaxis()->GetBinCenter(j+1) - fTotalHistogram->GetYaxis()->GetBinLowEdge(j+1); + double yup = fTotalHistogram->GetYaxis()->GetBinWidth(j+1) - ylow; + + int ibin = GetGlobalBin(i+1,j+1); + double z = GetEfficiency(ibin); + double zlow = GetEfficiencyErrorLow(ibin); + double zup = GetEfficiencyErrorUp(ibin); + // in the case the graph already existed and extra points have been added + if (ipoint >= graph->GetN() ) { + graph->SetPoint(ipoint,x,y,z); + graph->SetPointError(ipoint,xlow,xup,ylow,yup,zlow,zup); + } + else { + px[ipoint] = x; + py[ipoint] = y; + pz[ipoint] = z; + exl[ipoint] = xlow; + exh[ipoint] = xup; + eyl[ipoint] = ylow; + eyh[ipoint] = yup; + ezl[ipoint] = zlow; + ezh[ipoint] = zup; + } + ipoint++; + } + } + + // tell the graph the effective number of points + graph->Set(ipoint); + //refresh title before painting if changed + TString oldTitle = graph->GetTitle(); + TString newTitle = GetTitle(); + if (oldTitle != newTitle ) { + graph->SetTitle(newTitle); + } + + // set the axis labels + TString xlabel = fTotalHistogram->GetXaxis()->GetTitle(); + TString ylabel = fTotalHistogram->GetYaxis()->GetTitle(); + TString zlabel = fTotalHistogram->GetZaxis()->GetTitle(); + if (xlabel) graph->GetXaxis()->SetTitle(xlabel); + if (ylabel) graph->GetYaxis()->SetTitle(ylabel); + if (zlabel) graph->GetZaxis()->SetTitle(zlabel); + + //copying style information + TAttLine::Copy(*graph); + TAttFill::Copy(*graph); + TAttMarker::Copy(*graph); + + // copy axis bin labels if existing. Assume are there in the total histogram + if (fTotalHistogram->GetXaxis()->GetLabels() != nullptr) { + for (int ibin = 1; ibin <= fTotalHistogram->GetXaxis()->GetNbins(); ++ibin) { + // we need to fnd the right bin for the Histogram representing the xaxis of the graph + int grbin = graph->GetXaxis()->FindFixBin(fTotalHistogram->GetXaxis()->GetBinCenter(ibin)); + graph->GetXaxis()->SetBinLabel(grbin, fTotalHistogram->GetXaxis()->GetBinLabel(ibin)); + } + } + if (fTotalHistogram->GetYaxis()->GetLabels() != nullptr) { + for (int ibin = 1; ibin <= fTotalHistogram->GetYaxis()->GetNbins(); ++ibin) { + // we need to fnd the right bin for the Histogram representing the xaxis of the graph + int grbin = graph->GetYaxis()->FindFixBin(fTotalHistogram->GetYaxis()->GetBinCenter(ibin)); + graph->GetYaxis()->SetBinLabel(grbin, fTotalHistogram->GetYaxis()->GetBinLabel(ibin)); + } + } + // this method forces the graph to compute correctly the axis + // according to the given points + graph->GetHistogram(); +} +//////////////////////////////////////////////////////////////////////////////// +/// Fill the graph to be painted with information from TEfficiency +/// Internal method called by TEfficiency::Paint or TEfficiency::CreateGraph + void TEfficiency::FillGraph(TGraphAsymmErrors * graph, Option_t * opt) const { TString option = opt; @@ -1725,14 +1846,14 @@ TH2 * TEfficiency::CreateHistogram(Option_t *) const { if (GetDimension() != 2) { Error("CreatePaintingistogram","Call this function only for dimension == 2"); - return 0; + return nullptr; } Int_t nbinsx = fTotalHistogram->GetNbinsX(); Int_t nbinsy = fTotalHistogram->GetNbinsY(); TAxis * xaxis = fTotalHistogram->GetXaxis(); TAxis * yaxis = fTotalHistogram->GetYaxis(); - TH2 * hist = 0; + TH2 * hist = nullptr; if (xaxis->IsVariableBinSize() && yaxis->IsVariableBinSize() ) hist = new TH2F("eff_histo",GetTitle(),nbinsx,xaxis->GetXbins()->GetArray(), @@ -1748,7 +1869,7 @@ TH2 * TEfficiency::CreateHistogram(Option_t *) const nbinsy,yaxis->GetXmin(), yaxis->GetXmax()); - hist->SetDirectory(0); + hist->SetDirectory(nullptr); FillHistogram(hist); @@ -2080,14 +2201,14 @@ TGraphAsymmErrors* TEfficiency::Combine(TCollection* pList,Option_t* option, else { gROOT->Error("TEfficiency::Combine","invalid custom weight found w = %.2lf",w[k]); gROOT->Info("TEfficiency::Combine","stop combining"); - return 0; + return nullptr; } } } TIter next(pList); - TObject* obj = 0; - TEfficiency* pEff = 0; + TObject* obj = nullptr; + TEfficiency* pEff = nullptr; while((obj = next())) { pEff = dynamic_cast(obj); //is object a TEfficiency object? @@ -2132,14 +2253,14 @@ TGraphAsymmErrors* TEfficiency::Combine(TCollection* pList,Option_t* option, if(vTotal.empty()) { gROOT->Error("TEfficiency::Combine","no TEfficiency objects in given list"); gROOT->Info("TEfficiency::Combine","stop combining"); - return 0; + return nullptr; } //invalid number of custom weights if(bWeights && (n != (Int_t)vTotal.size())) { gROOT->Error("TEfficiency::Combine","number of weights n=%i differs from number of TEfficiency objects k=%i which should be combined",n,(Int_t)vTotal.size()); gROOT->Info("TEfficiency::Combine","stop combining"); - return 0; + return nullptr; } Int_t nbins_max = vTotal.at(0)->GetNbinsX(); @@ -2197,7 +2318,7 @@ TGraphAsymmErrors* TEfficiency::Combine(TCollection* pList,Option_t* option, if(eff[i-1] == -1) { gROOT->Error("TEfficiency::Combine","error occurred during combining"); gROOT->Info("TEfficiency::Combine","stop combining"); - return 0; + return nullptr; } efflow[i-1]= eff[i-1] - low; effhigh[i-1]= up - eff[i-1]; @@ -2230,7 +2351,9 @@ Int_t TEfficiency::DistancetoPrimitive(Int_t px, Int_t py) /// \param[in] opt /// - 1-dimensional case: same options as TGraphAsymmErrors::Draw() /// but as default "AP" is used -/// - 2-dimensional case: same options as TH2::Draw() +/// - 2-dimensional case: by default use an histogram and in this case same options as TH2::Draw() +/// if using instad option "GRAPH" a TGraph2DAsymmErrors is used and +/// the same options as for TGraph2D applies /// - 3-dimensional case: not yet supported /// /// Specific TEfficiency drawing options: @@ -2371,7 +2494,7 @@ Int_t TEfficiency::FindFixBin(Double_t x,Double_t y,Double_t z) const return GetGlobalBin(nx,ny,nz); } -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// /// Fits the efficiency using the TBinomialEfficiencyFitter class /// /// The resulting fit function is added to the list of associated functions. @@ -2379,12 +2502,13 @@ Int_t TEfficiency::FindFixBin(Double_t x,Double_t y,Double_t z) const /// Options: /// - "+": previous fitted functions in the list are kept, by default /// all functions in the list are deleted +/// - "N": do not store fitted function /// - for more fitting options see TBinomialEfficiencyFitter::Fit TFitResultPtr TEfficiency::Fit(TF1* f1,Option_t* opt) { TString option = opt; - option.ToLower(); + option.ToUpper(); //replace existing functions in list with same name Bool_t bDeleteOld = true; @@ -2398,24 +2522,26 @@ TFitResultPtr TEfficiency::Fit(TF1* f1,Option_t* opt) TFitResultPtr result = Fitter.Fit(f1,option.Data()); //create copy which is appended to the list - TF1* pFunc = new TF1(*f1); + if (!option.Contains("N")) { // option "N" is not store fit function + TF1* pFunc = (TF1*)f1->IsA()->New(); + f1->Copy(*pFunc); - if(bDeleteOld) { - TIter next(fFunctions); - TObject* obj = 0; - while((obj = next())) { - if(obj->InheritsFrom(TF1::Class())) { - fFunctions->Remove(obj); - delete obj; + if(bDeleteOld) { + TIter next(fFunctions); + TObject* obj = nullptr; + while((obj = next())) { + if(obj->InheritsFrom(TF1::Class())) { + fFunctions->Remove(obj); + delete obj; + } } } - } - - // create list if necessary - if(!fFunctions) - fFunctions = new TList(); + // create list if necessary + if(!fFunctions) + fFunctions = new TList(); - fFunctions->Add(pFunc); + fFunctions->Add(pFunc); + } return result; } @@ -2743,8 +2869,8 @@ Long64_t TEfficiency::Merge(TCollection* pList) { if(!pList->IsEmpty()) { TIter next(pList); - TObject* obj = 0; - TEfficiency* pEff = 0; + TObject* obj = nullptr; + TEfficiency* pEff = nullptr; while((obj = next())) { pEff = dynamic_cast(obj); if(pEff) { @@ -2806,21 +2932,21 @@ Double_t TEfficiency::Normal(Double_t total,Double_t passed,Double_t level,Bool_ TEfficiency& TEfficiency::operator+=(const TEfficiency& rhs) { - if (fTotalHistogram == 0 && fPassedHistogram == 0) { + if (fTotalHistogram == nullptr && fPassedHistogram == nullptr) { // efficiency is empty just copy it over *this = rhs; return *this; } - else if (fTotalHistogram == 0 || fPassedHistogram == 0) { + else if (fTotalHistogram == nullptr || fPassedHistogram == nullptr) { Fatal("operator+=","Adding to a non consistent TEfficiency object which has not a total or a passed histogram "); return *this; } - if (rhs.fTotalHistogram == 0 && rhs.fPassedHistogram == 0 ) { + if (rhs.fTotalHistogram == nullptr && rhs.fPassedHistogram == nullptr ) { Warning("operator+=","no operation: adding an empty object"); return *this; } - else if (rhs.fTotalHistogram == 0 || rhs.fPassedHistogram == 0 ) { + else if (rhs.fTotalHistogram == nullptr || rhs.fPassedHistogram == nullptr ) { Fatal("operator+=","Adding a non consistent TEfficiency object which has not a total or a passed histogram "); return *this; } @@ -2873,8 +2999,10 @@ TEfficiency& TEfficiency::operator=(const TEfficiency& rhs) //delete temporary paint objects delete fPaintHisto; delete fPaintGraph; - fPaintHisto = 0; - fPaintGraph = 0; + delete fPaintGraph2D; + fPaintHisto = nullptr; + fPaintGraph = nullptr; + fPaintGraph2D = nullptr; //copy style rhs.TAttLine::Copy(*this); @@ -2910,6 +3038,9 @@ void TEfficiency::Paint(const Option_t* opt) if(!gPad) return; + TString option(opt); + option.ToUpper(); + //use TGraphAsymmErrors for painting if(GetDimension() == 1) { @@ -2921,37 +3052,51 @@ void TEfficiency::Paint(const Option_t* opt) FillGraph(fPaintGraph, opt); //paint graph - fPaintGraph->Paint(opt); - - //paint all associated functions - if(fFunctions) { - //paint box with fit parameters - //the fit statistics will be painted if gStyle->SetOptFit(1) has been - // called by the user + // paint all associated functions + if (fFunctions) { + // paint box with fit parameters + // the fit statistics will be painted if gStyle->SetOptFit(1) has been + // called by the user TIter next(fFunctions); - TObject* obj = 0; - while((obj = next())) { - if(obj->InheritsFrom(TF1::Class())) { - fPaintGraph->PaintStats((TF1*)obj); - ((TF1*)obj)->Paint("sameC"); + TObject *obj = nullptr; + while ((obj = next())) { + if (obj->InheritsFrom(TF1::Class())) { + fPaintGraph->PaintStats((TF1 *)obj); + ((TF1 *)obj)->Paint("sameC"); } } } - return; } - - //use TH2 for painting + //use TH2 or optionally a TGraph2DAsymmErrors for painting if(GetDimension() == 2) { - if(!fPaintHisto) { - fPaintHisto = CreateHistogram(); + bool drawGraph2D = false; + if (option.Contains("GRAPH")) { + option.ReplaceAll("GRAPH",""); + drawGraph2D = true; } - else - FillHistogram(fPaintHisto); - - //paint histogram - fPaintHisto->Paint(opt); + if (drawGraph2D) { + //paint a TGraph2DAsymmErrors + if(!fPaintGraph2D) + fPaintGraph2D = CreateGraph2D(option); + else + FillGraph2D(fPaintGraph2D, option); + // set some sensible marker size and type + fPaintGraph2D->SetMarkerStyle(20); + fPaintGraph2D->SetMarkerSize(0.6); + // use PCOL Z as default option + if (option.IsNull()) option += "ERR PCOL Z"; + fPaintGraph2D->Paint(option); + } else { + //paint histogram + if (!fPaintHisto) + fPaintHisto = CreateHistogram(); + else + FillHistogram(fPaintHisto); + fPaintHisto->Paint(option); + } + // should we also paint the functions?? return; } Warning("Paint","Painting 3D efficiency is not implemented"); @@ -3102,7 +3247,7 @@ void TEfficiency::SavePrimitive(std::ostream& out,Option_t* opt) //save list of functions TIter next(fFunctions); - TObject* obj = 0; + TObject* obj = nullptr; while((obj = next())) { obj->SavePrimitive(out,"nodraw"); if(obj->InheritsFrom(TF1::Class())) { diff --git a/hist/hist/src/TF1.cxx b/hist/hist/src/TF1.cxx index 01a11e41e9136..daa06a0ce45f2 100644 --- a/hist/hist/src/TF1.cxx +++ b/hist/hist/src/TF1.cxx @@ -177,7 +177,7 @@ class GInverseFuncNdim { double operator()(const double *x) const { - return - fFunction->EvalPar(x, (Double_t *)0); + return - fFunction->EvalPar(x, (Double_t *)nullptr); } }; @@ -209,7 +209,7 @@ class TF1_EvalWrapper : public ROOT::Math::IGenFunction { { // use evaluation with stored parameters (i.e. pass zero) fX[0] = x; - Double_t fval = fFunc->EvalPar(fX, 0); + Double_t fval = fFunc->EvalPar(fX, nullptr); if (fAbsVal && fval < 0) return -fval; return fval; } @@ -217,13 +217,13 @@ class TF1_EvalWrapper : public ROOT::Math::IGenFunction { Double_t EvalFirstMom(Double_t x) { fX[0] = x; - return fX[0] * TMath::Abs(fFunc->EvalPar(fX, 0)); + return fX[0] * TMath::Abs(fFunc->EvalPar(fX, nullptr)); } // evaluate (x - x0) ^n * f(x) Double_t EvalNMom(Double_t x) const { fX[0] = x; - return TMath::Power(fX[0] - fX0, fN) * TMath::Abs(fFunc->EvalPar(fX, 0)); + return TMath::Power(fX[0] - fX0, fN) * TMath::Abs(fFunc->EvalPar(fX, nullptr)); } TF1 *fFunc; @@ -479,7 +479,7 @@ See also the tutorial __math/exampleFunctor.C__ for a running example. */ //////////////////////////////////////////////////////////////////////////// -TF1 *TF1::fgCurrent = 0; +TF1 *TF1::fgCurrent = nullptr; //////////////////////////////////////////////////////////////////////////////// @@ -1028,11 +1028,11 @@ void TF1::Copy(TObject &obj) const ((TF1 &)obj).fParMax = fParMax; ((TF1 &)obj).fParent = fParent; ((TF1 &)obj).fSave = fSave; - ((TF1 &)obj).fHistogram = 0; - ((TF1 &)obj).fMethodCall = 0; + ((TF1 &)obj).fHistogram = nullptr; + ((TF1 &)obj).fMethodCall = nullptr; ((TF1 &)obj).fNormalized = fNormalized; ((TF1 &)obj).fNormIntegral = fNormIntegral; - ((TF1 &)obj).fFormula = 0; + ((TF1 &)obj).fFormula = nullptr; if (fFormula) assert(fFormula->GetNpar() == fNpar); @@ -1069,7 +1069,7 @@ TObject* TF1::Clone(const char* newname) const if (fHistogram) { obj->fHistogram = (TH1*)fHistogram->Clone(); - obj->fHistogram->SetDirectory(0); + obj->fHistogram->SetDirectory(nullptr); } return obj; @@ -1619,7 +1619,7 @@ Double_t TF1::GetMaximum(Double_t xmin, Double_t xmax, Double_t epsilon, Int_t m xmax = fXmax; } - if (!logx && gPad != 0) logx = gPad->GetLogx(); + if (!logx && gPad != nullptr) logx = gPad->GetLogx(); ROOT::Math::BrentMinimizer1D bm; GInverseFunc g(this); @@ -1660,7 +1660,7 @@ Double_t TF1::GetMaximumX(Double_t xmin, Double_t xmax, Double_t epsilon, Int_t xmax = fXmax; } - if (!logx && gPad != 0) logx = gPad->GetLogx(); + if (!logx && gPad != nullptr) logx = gPad->GetLogx(); ROOT::Math::BrentMinimizer1D bm; GInverseFunc g(this); @@ -1701,7 +1701,7 @@ Double_t TF1::GetMinimum(Double_t xmin, Double_t xmax, Double_t epsilon, Int_t m xmax = fXmax; } - if (!logx && gPad != 0) logx = gPad->GetLogx(); + if (!logx && gPad != nullptr) logx = gPad->GetLogx(); ROOT::Math::BrentMinimizer1D bm; ROOT::Math::WrappedFunction wf1(*this); @@ -1723,7 +1723,7 @@ Double_t TF1::GetMinimum(Double_t xmin, Double_t xmax, Double_t epsilon, Int_t m Double_t TF1::GetMinMaxNDim(Double_t *x , bool findmax, Double_t epsilon, Int_t maxiter) const { - R__ASSERT(x != 0); + R__ASSERT(x != nullptr); int ndim = GetNdim(); if (ndim == 0) { @@ -1736,7 +1736,7 @@ Double_t TF1::GetMinMaxNDim(Double_t *x , bool findmax, Double_t epsilon, Int_t const char *minimAlgo = ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str(); ROOT::Math::Minimizer *min = ROOT::Math::Factory::CreateMinimizer(minimName, minimAlgo); - if (min == 0) { + if (min == nullptr) { Error("GetMinimumNDim", "Error creating minimizer %s", minimName); return 0; } @@ -1759,7 +1759,7 @@ Double_t TF1::GetMinMaxNDim(Double_t *x , bool findmax, Double_t epsilon, Int_t std::vector rmax(ndim); GetRange(&rmin[0], &rmax[0]); for (int i = 0; i < ndim; ++i) { - const char *xname = 0; + const char *xname = nullptr; double stepSize = 0.1; // use range for step size or give some value depending on x if range is not defined if (rmax[i] > rmin[i]) @@ -1868,7 +1868,7 @@ Double_t TF1::GetX(Double_t fy, Double_t xmin, Double_t xmax, Double_t epsilon, xmax = fXmax; } - if (!logx && gPad != 0) logx = gPad->GetLogx(); + if (!logx && gPad != nullptr) logx = gPad->GetLogx(); GFunc g(this, fy); ROOT::Math::WrappedFunction wf1(g); @@ -2399,7 +2399,7 @@ Double_t TF1::GetSave(const Double_t *xx) TAxis *TF1::GetXaxis() const { TH1 *h = GetHistogram(); - if (!h) return 0; + if (!h) return nullptr; return h->GetXaxis(); } @@ -2410,7 +2410,7 @@ TAxis *TF1::GetXaxis() const TAxis *TF1::GetYaxis() const { TH1 *h = GetHistogram(); - if (!h) return 0; + if (!h) return nullptr; return h->GetYaxis(); } @@ -2421,7 +2421,7 @@ TAxis *TF1::GetYaxis() const TAxis *TF1::GetZaxis() const { TH1 *h = GetHistogram(); - if (!h) return 0; + if (!h) return nullptr; return h->GetZaxis(); } @@ -2509,7 +2509,8 @@ void TF1::InitStandardFunctions() f1 = new TF1("expo", "expo", -1, 1); f1->SetParameters(1, 1); for (Int_t i = 0; i < 10; i++) { - f1 = new TF1(Form("pol%d", i), Form("pol%d", i), -1, 1); + auto f1name = TString::Format("pol%d", i); + f1 = new TF1(f1name.Data(), f1name.Data(), -1, 1); f1->SetParameters(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); // create also chebyshev polynomial // (note polynomial object will not be deleted) @@ -2619,7 +2620,7 @@ Double_t TF1::Integral(Double_t a, Double_t b, Double_t epsrel) Double_t TF1::IntegralOneDim(Double_t a, Double_t b, Double_t epsrel, Double_t epsabs, Double_t &error) { //Double_t *parameters = GetParameters(); - TF1_EvalWrapper wf1(this, 0, fgAbsValue); + TF1_EvalWrapper wf1(this, nullptr, fgAbsValue); Double_t result = 0; Int_t status = 0; if (epsrel <= 0) epsrel = ROOT::Math::IntegratorOneDimOptions::DefaultRelTolerance(); @@ -2971,10 +2972,9 @@ void TF1::Paint(Option_t *choptin) pmax = gPad->PadtoX(gPad->GetUxmax()); } if (optSAME) { - if (xmax < pmin) return; // Completely outside. + // Completely outside + if (xmax < pmin) return; if (xmin > pmax) return; - if (xmin < pmin) xmin = pmin; - if (xmax > pmax) xmax = pmax; } // create an histogram using the function content (re-use it if already existing) @@ -3052,7 +3052,7 @@ TH1 *TF1::DoCreateHistogram(Double_t xmin, Double_t xmax, Bool_t recreate) Int_t i; Double_t xv[1]; - TH1 *histogram = 0; + TH1 *histogram = nullptr; // Create a temporary histogram and fill each channel with the function value @@ -3111,7 +3111,7 @@ TH1 *TF1::DoCreateHistogram(Double_t xmin, Double_t xmax, Bool_t recreate) } if (fMinimum != -1111) histogram->SetMinimum(fMinimum); if (fMaximum != -1111) histogram->SetMaximum(fMaximum); - histogram->SetDirectory(0); + histogram->SetDirectory(nullptr); } R__ASSERT(histogram); @@ -3265,7 +3265,7 @@ void TF1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) static Int_t f1Number = 0; TString f1Name(GetName()); const char *l = strstr(option, "#"); - if (l != 0) { + if (l != nullptr) { sscanf(&l[1], "%d", &f1Number); } else { ++f1Number; @@ -3357,7 +3357,7 @@ void TF1::SetFitResult(const ROOT::Fit::FitResult &result, const Int_t *indpar) Warning("SetFitResult", "Empty Fit result - nothing is set in TF1"); return; } - if (indpar == 0 && npar != (int) result.NPar()) { + if (indpar == nullptr && npar != (int) result.NPar()) { Error("SetFitResult", "Invalid Fit result passed - number of parameter is %d , different than TF1::GetNpar() = %d", npar, result.NPar()); return; } @@ -3371,7 +3371,7 @@ void TF1::SetFitResult(const ROOT::Fit::FitResult &result, const Int_t *indpar) for (Int_t i = 0; i < npar; ++i) { - Int_t ipar = (indpar != 0) ? indpar[i] : i; + Int_t ipar = (indpar != nullptr) ? indpar[i] : i; if (ipar < 0) continue; GetParameters()[i] = result.Parameter(ipar); // in case errors are not present do not set them @@ -3611,7 +3611,7 @@ void TF1::Streamer(TBuffer &b) void TF1::Update() { delete fHistogram; - fHistogram = 0; + fHistogram = nullptr; if (!fIntegral.empty()) { fIntegral.clear(); fAlpha.clear(); diff --git a/hist/hist/src/TF12.cxx b/hist/hist/src/TF12.cxx index e23c6056be3ad..e8e03a230c456 100644 --- a/hist/hist/src/TF12.cxx +++ b/hist/hist/src/TF12.cxx @@ -39,7 +39,7 @@ End_Macro TF12::TF12(): TF1() { fCase = 0; - fF2 = 0; + fF2 = nullptr; fXY = 0; } @@ -191,8 +191,8 @@ void TF12::SetXY(Double_t xy) { fXY = xy; if (!fF2) return; - if (fCase == 0) SetTitle(Form("%s (y=%g)",fF2->GetTitle(),xy)); - else SetTitle(Form("%s (x=%g)",fF2->GetTitle(),xy)); + if (fCase == 0) SetTitle(TString::Format("%s (y=%g)",fF2->GetTitle(),xy)); + else SetTitle(TString::Format("%s (x=%g)",fF2->GetTitle(),xy)); if (fHistogram) fHistogram->SetTitle(GetTitle()); if (gPad) gPad->Modified(); } diff --git a/hist/hist/src/TF1Convolution.cxx b/hist/hist/src/TF1Convolution.cxx index 747b6a67a2018..601339d61eb71 100644 --- a/hist/hist/src/TF1Convolution.cxx +++ b/hist/hist/src/TF1Convolution.cxx @@ -364,7 +364,7 @@ Double_t TF1Convolution::EvalNumConv(Double_t t) Double_t TF1Convolution::operator()(const Double_t *x, const Double_t *p) { - if (p!=0) TF1Convolution::SetParameters(p); // first refresh the parameters + if (p!=nullptr) TF1Convolution::SetParameters(p); // first refresh the parameters Double_t result = 0.; if (fFlagFFT) diff --git a/hist/hist/src/TF1Data_v5.cxx b/hist/hist/src/TF1Data_v5.cxx index 98c251e4260ad..ce34c0c7593de 100644 --- a/hist/hist/src/TF1Data_v5.cxx +++ b/hist/hist/src/TF1Data_v5.cxx @@ -33,10 +33,10 @@ TF1Data::TF1Data(): ROOT::v5::TFormula(), TAttLine(), TAttFill(), TAttMarker() fNDF = 0; fNsave = 0; fChisquare = 0; - fParErrors = 0; - fParMin = 0; - fParMax = 0; - fSave = 0; + fParErrors = nullptr; + fParMin = nullptr; + fParMax = nullptr; + fSave = nullptr; fMinimum = -1111; fMaximum = -1111; SetFillStyle(0); @@ -142,7 +142,7 @@ void TF1Data::Streamer(TBuffer &b, Int_t v, UInt_t R__s, UInt_t R__c, const TCla fSave[fNsave+1] = fSave[fNsave+2]; fSave[fNsave+2] = fSave[fNsave+3]; fNsave += 3; - } else fSave = 0; + } else fSave = nullptr; } b.CheckByteCount(R__s, R__c, TF1Data::IsA()); //====end of old versions diff --git a/hist/hist/src/TF1Helper.cxx b/hist/hist/src/TF1Helper.cxx index 2bac84f5dab83..8bd8582734ab4 100644 --- a/hist/hist/src/TF1Helper.cxx +++ b/hist/hist/src/TF1Helper.cxx @@ -63,7 +63,7 @@ namespace ROOT { TMatrixDSym covMatrix(npar); - if (covmat == 0) { + if (covmat == nullptr) { // with ROOT implicit MT there is no global TVirtualFitter if (ROOT::IsImplicitMTEnabled()) { Error("TF1Helper::IntegralError", "ROOT has enabled implicit MT. There is no existing lobal fitter, as shown in the documentation a pointer to the covariance matrix" @@ -73,7 +73,7 @@ namespace ROOT { // use matrix from last fit (needs to be a TBackCompFitter) TVirtualFitter * vfitter = TVirtualFitter::GetFitter(); TBackCompFitter * fitter = dynamic_cast (vfitter); - if (fitter == 0) { + if (fitter == nullptr) { Error("TF1Helper::IntegralError","No existing fitter can be used for computing the integral error"); return 0; } diff --git a/hist/hist/src/TF1NormSum.cxx b/hist/hist/src/TF1NormSum.cxx index e6bc02811fe9f..57802d1c4a6a5 100644 --- a/hist/hist/src/TF1NormSum.cxx +++ b/hist/hist/src/TF1NormSum.cxx @@ -272,12 +272,12 @@ TF1NormSum &TF1NormSum::operator=(const TF1NormSum &rhs) double TF1NormSum::operator()(const Double_t *x, const Double_t *p) { // first refresh the parameters - if (p != 0) + if (p != nullptr) SetParameters(p); Double_t sum = 0.; for (unsigned int n=0; n EvalPar(x,0)); + sum += fCoeffs[n]*(fFunctions[n] -> EvalPar(x,nullptr)); // normalize by a scale parameter (typically the bin width) return fScale * sum; diff --git a/hist/hist/src/TF2.cxx b/hist/hist/src/TF2.cxx index d4ef2697dc9c1..2956c3f035a11 100644 --- a/hist/hist/src/TF2.cxx +++ b/hist/hist/src/TF2.cxx @@ -339,7 +339,7 @@ Double_t TF2::GetContourLevel(Int_t level) const { if (level <0 || level >= fContour.fN) return 0; if (fContour.fArray[0] != -9999) return fContour.fArray[level]; - if (fHistogram == 0) return 0; + if (fHistogram == nullptr) return 0; return fHistogram->GetContourLevel(level); } @@ -368,7 +368,7 @@ Double_t TF2::FindMinMax(Double_t *x, Bool_t findmax) const Double_t rsign = (findmax) ? -1. : 1.; TF2 & function = const_cast(*this); // needed since EvalPar is not const Double_t xxmin = 0, yymin = 0, zzmin = 0; - if (x == NULL || ( (x!= NULL) && ( !TMath::Finite(x[0]) || !TMath::Finite(x[1]) ) ) ){ + if (x == nullptr || ( (x!= nullptr) && ( !TMath::Finite(x[0]) || !TMath::Finite(x[1]) ) ) ){ Double_t dx = (fXmax - fXmin)/fNpx; Double_t dy = (fYmax - fYmin)/fNpy; xxmin = fXmin; @@ -658,7 +658,7 @@ Double_t TF2::GetSave(const Double_t *xx) //////////////////////////////////////////////////////////////////////////////// /// Return Integral of a 2d function in range [ax,bx],[ay,by] -/// with desired relative accuracy (default value of eps is 1.e-9) +/// with desired relative accuracy (defined by eps) Double_t TF2::Integral(Double_t ax, Double_t bx, Double_t ay, Double_t by, Double_t epsrel) { @@ -705,7 +705,7 @@ TH1* TF2::CreateHistogram() Double_t *parameters = GetParameters(); TH2F* h = new TH2F("Func",(char*)GetTitle(),fNpx,fXmin,fXmax,fNpy,fYmin,fYmax); - h->SetDirectory(0); + h->SetDirectory(nullptr); InitArgs(xv,parameters); dx = (fXmax - fXmin)/Double_t(fNpx); @@ -721,7 +721,7 @@ TH1* TF2::CreateHistogram() h->Fill(fXmin-1,fYmin-1,0); //This call to force fNentries non zero Double_t *levels = fContour.GetArray(); - if (levels && levels[0] == -9999) levels = 0; + if (levels && levels[0] == -9999) levels = nullptr; h->SetMinimum(fMinimum); h->SetMaximum(fMaximum); h->SetContour(fContour.fN, levels); @@ -754,7 +754,7 @@ void TF2::Paint(Option_t *option) if (!fHistogram) { fHistogram = new TH2F("Func",(char*)GetTitle(),fNpx,fXmin,fXmax,fNpy,fYmin,fYmax); if (!fHistogram) return; - fHistogram->SetDirectory(0); + fHistogram->SetDirectory(nullptr); } InitArgs(xv,parameters); dx = (fXmax - fXmin)/Double_t(fNpx); @@ -771,7 +771,7 @@ void TF2::Paint(Option_t *option) //- Copy Function attributes to histogram attributes Double_t *levels = fContour.GetArray(); - if (levels && levels[0] == -9999) levels = 0; + if (levels && levels[0] == -9999) levels = nullptr; fHistogram->SetMinimum(fMinimum); fHistogram->SetMaximum(fMaximum); fHistogram->SetContour(fContour.fN, levels); @@ -842,6 +842,7 @@ void TF2::Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Doubl void TF2::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { char quote = '"'; + TString f2Name(GetName()); out<<" "<ClassSaved(TF2::Class())) { out<<" "; @@ -849,28 +850,35 @@ void TF2::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) out<<" TF2 *"; } if (!fMethodCall) { - out<SetNpx("<SetNpy("<SetNpx("<SetChisquare("<SetChisquare("<SetParameter("<SetParError("<SetParameter("<SetParError("<SetParLimits("<SetParLimits("<Draw("<Draw("<SaveAttributes(out, f2Name.Data(), "->GetXaxis()"); + if (GetYaxis()) GetYaxis()->SaveAttributes(out, f2Name.Data(), "->GetYaxis()"); + if (GetZaxis()) GetZaxis()->SaveAttributes(out, f2Name.Data(), "->GetZaxis()"); } @@ -969,7 +977,7 @@ void TF2::Streamer(TBuffer &R__b) R__b >> fNpy; R__b >> nlevels; if (R__v < 3) { - Float_t *contour = 0; + Float_t *contour = nullptr; Int_t n = R__b.ReadArray(contour); fContour.Set(n); for (Int_t i=0;i(*this); // needed since EvalPar is not const Double_t xxmin = 0, yymin = 0, zzmin = 0, ttmin = 0; - if (x == NULL || ( (x!= NULL) && ( !TMath::Finite(x[0]) || !TMath::Finite(x[1]) || !TMath::Finite(x[2]) ) ) ){ + if (x == nullptr || ( (x!= nullptr) && ( !TMath::Finite(x[0]) || !TMath::Finite(x[1]) || !TMath::Finite(x[2]) ) ) ){ Double_t dx = (fXmax - fXmin)/fNpx; Double_t dy = (fYmax - fYmin)/fNpy; Double_t dz = (fZmax - fZmin)/fNpz; @@ -508,7 +508,7 @@ TH1* TF3::CreateHistogram() TH1* h = new TH3F("R__TF3",(char*)GetTitle(),fNpx,fXmin,fXmax ,fNpy,fYmin,fYmax ,fNpz,fZmin,fZmax); - h->SetDirectory(0); + h->SetDirectory(nullptr); return h; } @@ -526,7 +526,7 @@ void TF3::Paint(Option_t *option) fHistogram = new TH3F("R__TF3",(char*)GetTitle(),fNpx,fXmin,fXmax ,fNpy,fYmin,fYmax ,fNpz,fZmin,fZmax); - fHistogram->SetDirectory(0); + fHistogram->SetDirectory(nullptr); } fHistogram->GetPainter(option)->ProcessMessage("SetF3",this); @@ -607,6 +607,7 @@ void TF3::Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Doubl void TF3::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { char quote = '"'; + TString f3Name(GetName()); out<<" "<ClassSaved(TF3::Class())) { out<<" "; @@ -614,37 +615,47 @@ void TF3::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) out<<" TF3 *"; } if (!fMethodCall) { - out<SetFillColor(ci);" << std::endl; + out<<" "<SetFillColor(ci);" << std::endl; else - out<<" "<SetFillColor("<SetFillColor("<SetLineColor(ci);" << std::endl; + out<<" "<SetLineColor(ci);" << std::endl; else - out<<" "<SetLineColor("<SetNpz("<SetChisquare("<SetLineColor("<SetNpx("<SetNpy("<SetNpz("<SetChisquare("<SetParameter("<SetParError("<SetParameter("<SetParError("<SetParLimits("<SetParLimits("<Draw(" + + if (GetXaxis()) GetXaxis()->SaveAttributes(out, f3Name.Data(), "->GetXaxis()"); + if (GetYaxis()) GetYaxis()->SaveAttributes(out, f3Name.Data(), "->GetYaxis()"); + if (GetZaxis()) GetZaxis()->SaveAttributes(out, f3Name.Data(), "->GetZaxis()"); + + out<<" "<Draw(" <(gROOT->GetListOfFunctions()->FindObject(name)); if (old) @@ -556,7 +556,7 @@ TFormula::TFormula(const char *name, const char *formula, int ndim, int npar, bo fReadyToExecute = true; if (addToGlobList && gROOT) { - TFormula *old = 0; + TFormula *old = nullptr; R__LOCKGUARD(gROOTMutex); old = dynamic_cast ( gROOT->GetListOfFunctions()->FindObject(name) ); if (old) @@ -1413,7 +1413,7 @@ void TFormula::HandleFunctionArguments(TString &formula) argSeparators.push_back(k - 1); // closing parenthesis // retrieve `f` (code copied from ExtractFunctors) - TObject *obj = 0; + TObject *obj = nullptr; { R__LOCKGUARD(gROOTMutex); obj = gROOT->GetListOfFunctions()->FindObject(name); @@ -1964,7 +1964,7 @@ void TFormula::ExtractFunctors(TString &formula) // function " << std::endl; // check if function is provided by gROOT - TObject *obj = 0; + TObject *obj = nullptr; // exclude case function name is x,y,z,t if (!IsReservedName(name)) { @@ -2164,7 +2164,7 @@ void TFormula::ProcessFormula(TString &formula) } #endif } else { - TFormula *old = 0; + TFormula *old = nullptr; { R__LOCKGUARD(gROOTMutex); old = (TFormula *)gROOT->GetListOfFunctions()->FindObject(gNamePrefix + fun.fName); @@ -2875,7 +2875,7 @@ Double_t* TFormula::GetParameters() const { if(!fClingParameters.empty()) return const_cast(&fClingParameters[0]); - return 0; + return nullptr; } void TFormula::GetParameters(Double_t *params) const @@ -3172,7 +3172,7 @@ Double_t TFormula::EvalPar(const Double_t *x,const Double_t *params) const bool TFormula::fIsCladRuntimeIncluded = false; static bool functionExists(const string &Name) { - return gInterpreter->GetFunction(/*cl*/0, Name.c_str()); + return gInterpreter->GetFunction(/*cl*/nullptr, Name.c_str()); } static void IncludeCladRuntime(Bool_t &IsCladRuntimeIncluded) { @@ -3224,7 +3224,7 @@ static void CallCladFunction(TInterpreter::CallFuncIFacePtr_t::Generic_t FuncPtr // } // } args[1] = &result; - (*FuncPtr)(0, 2, args, /*ret*/ nullptr); // We do not use ret in a return-void func. + (*FuncPtr)(nullptr, 2, args, /*ret*/ nullptr); // We do not use ret in a return-void func. } else { // __attribute__((used)) extern "C" void __cf_0(void* obj, int nargs, void** args, void* ret) // { @@ -3246,7 +3246,7 @@ static void CallCladFunction(TInterpreter::CallFuncIFacePtr_t::Generic_t FuncPtr array_ref_interface ari{result, static_cast(result_size)}; args[2] = &ari; - (*FuncPtr)(0, 3, args, /*ret*/nullptr); // We do not use ret in a return-void func. + (*FuncPtr)(nullptr, 3, args, /*ret*/nullptr); // We do not use ret in a return-void func. } } @@ -3498,11 +3498,11 @@ Double_t TFormula::DoEval(const double * x, const double * params) const double * vars = (x) ? const_cast(x) : const_cast(fClingVariables.data()); args[0] = &vars; if (fNpar <= 0) { - (*fFuncPtr)(0, 1, args, &result); + (*fFuncPtr)(nullptr, 1, args, &result); } else { double *pars = (params) ? const_cast(params) : const_cast(fClingParameters.data()); args[1] = &pars; - (*fFuncPtr)(0, 2, args, &result); + (*fFuncPtr)(nullptr, 2, args, &result); } return result; } diff --git a/hist/hist/src/TFormulaPrimitive_v5.cxx b/hist/hist/src/TFormulaPrimitive_v5.cxx index 120b290a9d702..a5b0cd1df30c3 100644 --- a/hist/hist/src/TFormulaPrimitive_v5.cxx +++ b/hist/hist/src/TFormulaPrimitive_v5.cxx @@ -22,7 +22,7 @@ #pragma optimize("",off) #endif -static TVirtualMutex* gTFormulaPrimativeListMutex = 0; +static TVirtualMutex* gTFormulaPrimativeListMutex = nullptr; ClassImp(ROOT::v5::TFormulaPrimitive); @@ -63,7 +63,7 @@ The following sufixes are currently used, to describe function arguments: //______________________________________________________________________________ // TFormula primitive // -TObjArray * TFormulaPrimitive::fgListOfFunction = 0; +TObjArray * TFormulaPrimitive::fgListOfFunction = nullptr; #ifdef R__COMPLETE_MEM_TERMINATION namespace { class TFormulaPrimitiveCleanup { @@ -82,7 +82,7 @@ namespace { /// Default constructor. TFormulaPrimitive::TFormulaPrimitive() : TNamed(), - fFuncG(0), + fFuncG(nullptr), fType(0),fNArguments(0),fNParameters(0),fIsStatic(kTRUE) { } @@ -194,7 +194,7 @@ TFormulaPrimitive::TFormulaPrimitive(const char *name,const char *formula, Int_t TFormulaPrimitive::AddFormula(TFormulaPrimitive * formula) { R__LOCKGUARD2(gTFormulaPrimativeListMutex); - if (fgListOfFunction == 0) BuildBasicFormulas(); + if (fgListOfFunction == nullptr) BuildBasicFormulas(); if (FindFormula(formula->GetName(),formula->fNArguments)){ delete formula; return 0; @@ -317,7 +317,7 @@ TFormulaPrimitive* TFormulaPrimitive::FindFormula(const char* name) TFormulaPrimitive *formula = (TFormulaPrimitive*)fgListOfFunction->At(i); if (formula && 0==strcmp(name, formula->GetName())) return formula; } - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -337,7 +337,7 @@ TFormulaPrimitive* TFormulaPrimitive::FindFormula(const char* name, UInt_t nargs if (match && 0==strcmp(name, prim->GetName())) return prim; } } - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -365,7 +365,7 @@ TFormulaPrimitive* TFormulaPrimitive::FindFormula(const char* name, const char * } else { return FindFormula(name); } - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -407,7 +407,7 @@ Double_t TFastFun::Gausn(Double_t x, Double_t mean, Double_t sigma) Int_t TFormulaPrimitive::BuildBasicFormulas() { R__LOCKGUARD2(gTFormulaPrimativeListMutex); - if (fgListOfFunction==0) { + if (fgListOfFunction==nullptr) { fgListOfFunction = new TObjArray(1000); fgListOfFunction->SetOwner(kTRUE); } diff --git a/hist/hist/src/TFormula_v5.cxx b/hist/hist/src/TFormula_v5.cxx index cb13188708edf..8bfc9d998cc82 100644 --- a/hist/hist/src/TFormula_v5.cxx +++ b/hist/hist/src/TFormula_v5.cxx @@ -140,20 +140,20 @@ TFormula::TFormula(): TNamed() fNoper = 0; fNconst = 0; fNumber = 0; - fExpr = 0; - fOper = 0; - fConst = 0; - fParams = 0; + fExpr = nullptr; + fOper = nullptr; + fConst = nullptr; + fParams = nullptr; fNstring= 0; - fNames = 0; + fNames = nullptr; fNval = 0; // //MI change fNOperOptimized = 0; - fExprOptimized = 0; - fOperOptimized = 0; - fOperOffset = 0; - fPredefined = 0; + fExprOptimized = nullptr; + fOperOptimized = nullptr; + fOperOffset = nullptr; + fPredefined = nullptr; fOptimal = (ROOT::v5::TFormulaPrimitive::TFuncG)&TFormula::EvalParOld; } @@ -168,20 +168,20 @@ TFormula::TFormula(const char *name,const char *expression) : fNoper = 0; fNconst = 0; fNumber = 0; - fExpr = 0; - fOper = 0; - fConst = 0; - fParams = 0; + fExpr = nullptr; + fOper = nullptr; + fConst = nullptr; + fParams = nullptr; fNstring= 0; - fNames = 0; + fNames = nullptr; fNval = 0; // //MI change fNOperOptimized = 0; - fExprOptimized = 0; - fOperOptimized = 0; - fOperOffset = 0; - fPredefined = 0; + fExprOptimized = nullptr; + fOperOptimized = nullptr; + fOperOffset = nullptr; + fPredefined = nullptr; fOptimal = (ROOT::v5::TFormulaPrimitive::TFuncG)&TFormula::EvalParOld; if (!expression || !*expression) { @@ -280,18 +280,18 @@ TFormula::TFormula(const TFormula &formula) : TNamed() fNoper = 0; fNconst = 0; fNumber = 0; - fExpr = 0; - fOper = 0; - fConst = 0; - fParams = 0; + fExpr = nullptr; + fOper = nullptr; + fConst = nullptr; + fParams = nullptr; fNstring= 0; - fNames = 0; + fNames = nullptr; fNval = 0; fNOperOptimized = 0; - fPredefined = 0; - fOperOffset = 0; - fExprOptimized = 0; - fOperOptimized = 0; + fPredefined = nullptr; + fOperOffset = nullptr; + fExprOptimized = nullptr; + fOperOptimized = nullptr; fOptimal = (ROOT::v5::TFormulaPrimitive::TFuncG)&TFormula::EvalParOld; formula.TFormula::Copy(*this); @@ -418,8 +418,8 @@ Bool_t TFormula::AnalyzeFunction(TString &chaine, Int_t &err, Int_t offset) } // Now we need to lookup the function and check its arguments. - TClass *ns = (spaceName.Length()) ? TClass::GetClass(spaceName) : 0; - ClassInfo_t *cinfo = 0; + TClass *ns = (spaceName.Length()) ? TClass::GetClass(spaceName) : nullptr; + ClassInfo_t *cinfo = nullptr; if (ns) { cinfo = ns->GetClassInfo(); } else { @@ -478,7 +478,7 @@ Bool_t TFormula::AnalyzeFunction(TString &chaine, Int_t &err, Int_t offset) cbase[args_paran]=0; } - ROOT::v5::TFormulaPrimitive *prim = ROOT::v5::TFormulaPrimitive::FindFormula(cbase, args_paran>0 ? cbase.Data() + args_paran + 1 : (const char*)0); + ROOT::v5::TFormulaPrimitive *prim = ROOT::v5::TFormulaPrimitive::FindFormula(cbase, args_paran>0 ? cbase.Data() + args_paran + 1 : (const char*)nullptr); if (prim && (!IsA()->GetBaseClass("TTreeFormula"))) { // TO BE DONE ALSO IN TTREFORMULA - temporary fix MI // Analyze the arguments @@ -780,7 +780,7 @@ void TFormula::Analyze(const char *schain, Int_t &err, Int_t offset) puiss10=puiss10bis=0; if (i>2) { t = chaine[i-3]; - isdecimal = isdecimal && (strchr("0123456789.",t)!=0); + isdecimal = isdecimal && (strchr("0123456789.",t)!=nullptr); if (isdecimal) { if ( chaine[i-2] == 'e' || chaine[i-2] == 'E' ) puiss10 = 1; } else if ( strchr("+-/[]()&|><=!*/%^\\",t) ) { @@ -793,9 +793,9 @@ void TFormula::Analyze(const char *schain, Int_t &err, Int_t offset) for(k=j-3; k>=0 && isrightdecimal; --k) { t = chaine[k]; - isrightdecimal = isrightdecimal && (strchr("0123456789.",t)!=0); + isrightdecimal = isrightdecimal && (strchr("0123456789.",t)!=nullptr); if (!isrightdecimal) { - if (strchr("+-/[]()&|><=!*/%^\\",t)!=0) { + if (strchr("+-/[]()&|><=!*/%^\\",t)!=nullptr) { puiss10bis = 1; } } @@ -805,11 +805,11 @@ void TFormula::Analyze(const char *schain, Int_t &err, Int_t offset) } if (puiss10 && (i<=lchain)) { t = chaine[i]; - puiss10 = (strchr("0123456789.",t)!=0); + puiss10 = (strchr("0123456789.",t)!=nullptr); } if (puiss10bis && (j<=lchain)) { t = chaine[j]; - puiss10bis = (strchr("0123456789.",t)!=0); + puiss10bis = (strchr("0123456789.",t)!=nullptr); } if (chaine(i-1,1) == "\"") inString = !inString; @@ -1638,7 +1638,7 @@ void TFormula::Analyze(const char *schain, Int_t &err, Int_t offset) fExpr[fNoper] = chaine1ST; for (j=0; jGetListOfFunctions()->Remove(this); // if we don't, what happens if it fails the new compilation? @@ -2370,8 +2370,8 @@ Int_t TFormula::Compile(const char *expression) // if no parameters delete arrays fParams and fNames if (!fNpar) { - delete [] fParams; fParams = 0; - delete [] fNames; fNames = 0; + delete [] fParams; fParams = nullptr; + delete [] fNames; fNames = nullptr; } // if no errors, copy local parameters to formula objects @@ -2409,7 +2409,8 @@ Int_t TFormula::Compile(const char *expression) } // if formula is a polynom, set parameter names if (GetNumber() == 300+fNpar) { - for (i=0;i0 ? cbase.Data() + paran + 1 : (const char*)0); + ROOT::v5::TFormulaPrimitive *prim = ROOT::v5::TFormulaPrimitive::FindFormula(cbase ,paran>0 ? cbase.Data() + paran + 1 : (const char*)nullptr); if (prim) { fPredefined[pos] = prim; if (prim->fType==10) { @@ -3777,7 +3778,7 @@ void TFormula::MakePrimitive(const char *expr, Int_t pos) } if (prim->fType==0){ SetActionOptimized(pos,kConstant,fNconst); - fConst[fNconst] = prim->Eval(0); + fConst[fNconst] = prim->Eval(nullptr); fNconst++; } return; @@ -3822,10 +3823,10 @@ void TFormula::Optimize() Int_t i; - if (fPredefined) { delete [] fPredefined; fPredefined = 0;} - if (fOperOffset) { delete [] fOperOffset; fOperOffset = 0;} - if (fExprOptimized) { delete [] fExprOptimized; fExprOptimized = 0;} - if (fOperOptimized) { delete [] fOperOptimized; fOperOptimized = 0;} + if (fPredefined) { delete [] fPredefined; fPredefined = nullptr;} + if (fOperOffset) { delete [] fOperOffset; fOperOffset = nullptr;} + if (fExprOptimized) { delete [] fExprOptimized; fExprOptimized = nullptr;} + if (fOperOptimized) { delete [] fOperOptimized; fOperOptimized = nullptr;} fExprOptimized = new TString[fNoper]; fOperOptimized = new Int_t[fNoper]; @@ -3834,7 +3835,7 @@ void TFormula::Optimize() for (i=0; ifType0][fOperOffset->fOffset0]; switch((fOperOptimized[0] >> kTFOperShift)) { case kData : return result; @@ -4133,7 +4134,7 @@ Double_t TFormula::EvalPrimitive(const Double_t *x, const Double_t *params) Double_t TFormula::EvalPrimitive0(const Double_t *x, const Double_t *params) { - const Double_t *pdata[3] = {x,(params!=0)?params:fParams, fConst}; + const Double_t *pdata[3] = {x,(params!=nullptr)?params:fParams, fConst}; return pdata[fOperOffset->fType0][fOperOffset->fOffset0]; } @@ -4142,7 +4143,7 @@ Double_t TFormula::EvalPrimitive0(const Double_t *x, const Double_t *params) Double_t TFormula::EvalPrimitive1(const Double_t *x, const Double_t *params) { - const Double_t *pdata[3] = {x,(params!=0)?params:fParams, fConst}; + const Double_t *pdata[3] = {x,(params!=nullptr)?params:fParams, fConst}; return (fPredefined[0]->fFunc10)(pdata[fOperOffset->fType0][fOperOffset->fOffset0]); } @@ -4151,7 +4152,7 @@ Double_t TFormula::EvalPrimitive1(const Double_t *x, const Double_t *params) Double_t TFormula::EvalPrimitive2(const Double_t *x, const Double_t *params) { - const Double_t *pdata[3] = {x,(params!=0)?params:fParams, fConst}; + const Double_t *pdata[3] = {x,(params!=nullptr)?params:fParams, fConst}; return (fPredefined[0]->fFunc110)(pdata[fOperOffset->fType0][fOperOffset->fOffset0], pdata[fOperOffset->fType1][fOperOffset->fOffset1]); } @@ -4161,7 +4162,7 @@ Double_t TFormula::EvalPrimitive2(const Double_t *x, const Double_t *params) Double_t TFormula::EvalPrimitive3(const Double_t *x, const Double_t *params) { - const Double_t *pdata[3] = {x,(params!=0)?params:fParams, fConst}; + const Double_t *pdata[3] = {x,(params!=nullptr)?params:fParams, fConst}; return (fPredefined[0]->fFunc1110)(pdata[fOperOffset->fType0][fOperOffset->fOffset0], pdata[fOperOffset->fType1][fOperOffset->fOffset1], pdata[fOperOffset->fType2][fOperOffset->fOffset2]); } @@ -4171,7 +4172,7 @@ Double_t TFormula::EvalPrimitive3(const Double_t *x, const Double_t *params) Double_t TFormula::EvalPrimitive4(const Double_t *x, const Double_t *params) { - const Double_t *par = (params!=0)?params:fParams; + const Double_t *par = (params!=nullptr)?params:fParams; return (fPredefined[0]->fFuncG)((Double_t*)&x[fOperOffset->fType0], (Double_t*)&par[fOperOffset->fOffset0]); } @@ -4187,13 +4188,13 @@ Double_t TFormula::EvalPrimitive4(const Double_t *x, const Double_t *params) Double_t TFormula::EvalParFast(const Double_t *x, const Double_t *uparams) { - const Double_t *pdata[3] = {x,(uparams!=0)?uparams:fParams, fConst}; + const Double_t *pdata[3] = {x,(uparams!=nullptr)?uparams:fParams, fConst}; // Int_t i,j; Double_t tab[kMAXFOUND] = {0}; - const char *stringStack[gMAXSTRINGFOUND] = {0}; + const char *stringStack[gMAXSTRINGFOUND] = {nullptr}; Double_t param_calc[kMAXFOUND]; - char *string_calc[gMAXSTRINGFOUND] = {0}; + char *string_calc[gMAXSTRINGFOUND] = {nullptr}; Int_t precalculated = 0; Int_t precalculated_str = 0; @@ -4491,7 +4492,7 @@ Int_t TFormula::PreCompile() FILE *hf; hf = fopen(fileName.Data(),"w"); - if (hf == 0) { + if (hf == nullptr) { Error("PreCompile","Unable to open the file %s for writing.",fileName.Data()); return 1; } diff --git a/hist/hist/src/TFractionFitter.cxx b/hist/hist/src/TFractionFitter.cxx index d78356920ffae..6a395a154deff 100644 --- a/hist/hist/src/TFractionFitter.cxx +++ b/hist/hist/src/TFractionFitter.cxx @@ -165,12 +165,12 @@ fFitDone(kFALSE), fLowLimitX(0), fHighLimitX(0), fLowLimitY(0), fHighLimitY(0), fLowLimitZ(0), fHighLimitZ(0), -fData(0), fIntegralData(0), -fPlot(0) +fData(nullptr), fIntegralData(0), +fPlot(nullptr) { - fFractionFitter = 0; - fIntegralMCs = 0; - fFractions = 0; + fFractionFitter = nullptr; + fIntegralMCs = nullptr; + fFractions = nullptr; fNpfits = 0; fNDF = 0; @@ -191,7 +191,7 @@ fPlot(0) /// - option = "" : default: print initial fraction values and result TFractionFitter::TFractionFitter(TH1* data, TObjArray *MCs, Option_t *option) : -fFitDone(kFALSE), fChisquare(0), fPlot(0) { +fFitDone(kFALSE), fChisquare(0), fPlot(nullptr) { fData = data; // Default: include all of the histogram (but without under- and overflows) fLowLimitX = 1; @@ -209,10 +209,10 @@ fFitDone(kFALSE), fChisquare(0), fPlot(0) { for (par = 0; par < fNpar; ++par) { fMCs.Add(MCs->At(par)); // Histogram containing template prediction - TString s = Form("Prediction for MC sample %i",par); + TString s = TString::Format("Prediction for MC sample %i",par); TH1* pred = (TH1*) ((TH1*)MCs->At(par))->Clone(s); // TFractionFitter manages these histograms - pred->SetDirectory(0); + pred->SetDirectory(nullptr); pred->SetTitle(s); fAji.Add(pred); } @@ -554,7 +554,7 @@ TFitResultPtr TFractionFitter::Fit() { // remove any existing output histogram if (fPlot) { - delete fPlot; fPlot = 0; + delete fPlot; fPlot = nullptr; } // Make sure the correct likelihood computation is used @@ -621,7 +621,7 @@ void TFractionFitter::GetResult(Int_t parm, Double_t& value, Double_t& error) co TH1* TFractionFitter::GetPlot() { if (! fFitDone) { Error("GetPlot","Fit not yet performed"); - return 0; + return nullptr; } if (! fPlot) { Double_t f = 0; @@ -695,7 +695,7 @@ void TFractionFitter::ComputeFCN(Double_t& f, const Double_t* xx, Int_t flag) TString ts = "Fraction fit to hist: "; ts += fData->GetName(); fPlot = (TH1*) fData->Clone(ts.Data()); // plot histogram is managed by TFractionFitter - fPlot->SetDirectory(0); + fPlot->SetDirectory(nullptr); fPlot->Reset(); } // likelihood computation @@ -963,7 +963,7 @@ TH1* TFractionFitter::GetMCPrediction(Int_t parm) const CheckParNo(parm); if ( !fFitDone ) { Error("GetMCPrediction","Fit not yet performed"); - return 0; + return nullptr; } return (TH1*) fAji.At(parm); } diff --git a/hist/hist/src/TGraph.cxx b/hist/hist/src/TGraph.cxx index d84a5d43fd454..1ce87a6e01491 100644 --- a/hist/hist/src/TGraph.cxx +++ b/hist/hist/src/TGraph.cxx @@ -39,6 +39,7 @@ #include #include #include +#include #include "HFitInterface.h" #include "Fit/DataRange.h" @@ -502,7 +503,7 @@ TGraph::TGraph(const char *filename, const char *format, Option_t *option) // Initializing loop variables Bool_t isLineToBeSkipped = kFALSE ; //empty and ill-formed lines - char * token = NULL ; + char * token = nullptr ; TString token_str = "" ; Int_t token_idx = 0 ; Double_t * value = new Double_t [2] ; //x,y buffers @@ -517,7 +518,7 @@ TGraph::TGraph(const char *filename, const char *format, Option_t *option) } //token = R__STRTOK_R(const_cast(line.c_str()), option, rest); token = R__STRTOK_R(const_cast(line.c_str()), option, &rest); - while (token != NULL && value_idx < 2) { + while (token != nullptr && value_idx < 2) { if (isTokenToBeSaved[token_idx]) { token_str = TString(token) ; token_str.ReplaceAll("\t", "") ; @@ -529,7 +530,7 @@ TGraph::TGraph(const char *filename, const char *format, Option_t *option) value_idx++ ; } } - token = R__STRTOK_R(NULL, option, &rest); // next token + token = R__STRTOK_R(nullptr, option, &rest); // next token token_idx++ ; } if (!isLineToBeSkipped && value_idx == 2) { @@ -540,7 +541,7 @@ TGraph::TGraph(const char *filename, const char *format, Option_t *option) } } isLineToBeSkipped = kFALSE ; - token = NULL ; + token = nullptr ; token_idx = 0 ; value_idx = 0 ; } @@ -1204,7 +1205,7 @@ TObject *TGraph::FindObject(const TObject *obj) const TFitResultPtr TGraph::Fit(TF1 *f1, Option_t *option, Option_t *goption, Axis_t rxmin, Axis_t rxmax) { Foption_t fitOption; - ROOT::Fit::FitOptionsMake(ROOT::Fit::kGraph, option, fitOption); + ROOT::Fit::FitOptionsMake(ROOT::Fit::EFitObjectType::kGraph, option, fitOption); // create range and minimizer options with default values ROOT::Fit::DataRange range(rxmin, rxmax); ROOT::Math::MinimizerOptions minOption; @@ -1482,29 +1483,18 @@ TH1F *TGraph::GetHistogram() const fHistogram->GetXaxis()->CenterTitle(historg->GetXaxis()->GetCenterTitle()); fHistogram->GetXaxis()->RotateTitle(historg->GetXaxis()->GetRotateTitle()); fHistogram->GetXaxis()->SetNoExponent(historg->GetXaxis()->GetNoExponent()); - fHistogram->GetXaxis()->SetNdivisions(historg->GetXaxis()->GetNdivisions()); - fHistogram->GetXaxis()->SetLabelFont(historg->GetXaxis()->GetLabelFont()); - fHistogram->GetXaxis()->SetLabelOffset(historg->GetXaxis()->GetLabelOffset()); - fHistogram->GetXaxis()->SetLabelSize(historg->GetXaxis()->GetLabelSize()); - fHistogram->GetXaxis()->SetTitleSize(historg->GetXaxis()->GetTitleSize()); - fHistogram->GetXaxis()->SetTitleOffset(historg->GetXaxis()->GetTitleOffset()); - fHistogram->GetXaxis()->SetTitleFont(historg->GetXaxis()->GetTitleFont()); fHistogram->GetXaxis()->SetTimeDisplay(historg->GetXaxis()->GetTimeDisplay()); fHistogram->GetXaxis()->SetTimeFormat(historg->GetXaxis()->GetTimeFormat()); + historg->GetXaxis()->TAttAxis::Copy(*(fHistogram->GetXaxis())); fHistogram->GetYaxis()->SetTitle(historg->GetYaxis()->GetTitle()); fHistogram->GetYaxis()->CenterTitle(historg->GetYaxis()->GetCenterTitle()); fHistogram->GetYaxis()->RotateTitle(historg->GetYaxis()->GetRotateTitle()); fHistogram->GetYaxis()->SetNoExponent(historg->GetYaxis()->GetNoExponent()); - fHistogram->GetYaxis()->SetNdivisions(historg->GetYaxis()->GetNdivisions()); - fHistogram->GetYaxis()->SetLabelFont(historg->GetYaxis()->GetLabelFont()); - fHistogram->GetYaxis()->SetLabelOffset(historg->GetYaxis()->GetLabelOffset()); - fHistogram->GetYaxis()->SetLabelSize(historg->GetYaxis()->GetLabelSize()); - fHistogram->GetYaxis()->SetTitleSize(historg->GetYaxis()->GetTitleSize()); - fHistogram->GetYaxis()->SetTitleOffset(historg->GetYaxis()->GetTitleOffset()); - fHistogram->GetYaxis()->SetTitleFont(historg->GetYaxis()->GetTitleFont()); fHistogram->GetYaxis()->SetTimeDisplay(historg->GetYaxis()->GetTimeDisplay()); fHistogram->GetYaxis()->SetTimeFormat(historg->GetYaxis()->GetTimeFormat()); + historg->GetYaxis()->TAttAxis::Copy(*(fHistogram->GetYaxis())); + delete historg; } return fHistogram; @@ -2407,7 +2397,7 @@ void TGraph::SetNameTitle(const char *name, const char *title) /// Set statistics option on/off. /// /// By default, the statistics box is drawn. -/// The paint options can be selected via gStyle->SetOptStats. +/// The paint options can be selected via gStyle->SetOptStat. /// This function sets/resets the kNoStats bit in the graph object. /// It has priority over the Style option. @@ -2466,36 +2456,31 @@ Double_t **TGraph::ShrinkAndCopy(Int_t size, Int_t oend) /// graph->Sort(&CompareErrors, kFALSE); /// ~~~ -void TGraph::Sort(Bool_t (*greaterfunc)(const TGraph*, Int_t, Int_t) /*=TGraph::CompareX()*/, - Bool_t ascending /*=kTRUE*/, Int_t low /* =0 */, Int_t high /* =-1111 */) +void TGraph::Sort(Bool_t (*greaterfunc)(const TGraph *, Int_t, Int_t) /*=TGraph::CompareX()*/, + Bool_t ascending /*=kTRUE*/, Int_t low /*=0*/, Int_t high /*=-1111*/) { - // set the bit in case of an ascending =sort in X - if (greaterfunc == TGraph::CompareX && ascending && low == 0 && high == -1111) + if (greaterfunc == TGraph::CompareX && ascending && low == 0 && high == -1111) SetBit(TGraph::kIsSortedX); - if (high == -1111) high = GetN() - 1; - // Termination condition - if (high <= low) return; + if (high == -1111) + high = fNpoints - 1; - int left, right; - left = low; // low is the pivot element - right = high; - while (left < right) { - // move left while item < pivot - while (left <= high && greaterfunc(this, left, low) != ascending) - left++; - // move right while item > pivot - while (right > low && greaterfunc(this, right, low) == ascending) - right--; - if (left < right && left < high && right > low) - SwapPoints(left, right); - } - // right is final position for the pivot - if (right > low) - SwapPoints(low, right); - Sort(greaterfunc, ascending, low, right - 1); - Sort(greaterfunc, ascending, right + 1, high); + // Create a vector to store the indices of the graph data points. + // We use std::vector instead of std::vector to match the input type + // required by the comparison operator's signature provided as `greaterfunc` + std::vector sorting_indices(fNpoints); + std::iota(sorting_indices.begin(), sorting_indices.end(), 0); + + // Sort the indices using the provided comparison function + // We use std::stable_sort here because the libc++ implementation of std::sort + // is not standard-compliant until LLVM 14 which caused errors on the mac nodes + // of our CI, related issue: https://github.com/llvm/llvm-project/issues/21211 + std::stable_sort(sorting_indices.begin() + low, sorting_indices.begin() + high + 1, + [&](const auto &left, const auto &right) { return greaterfunc(this, left, right) != ascending; }); + + Int_t numSortedPoints = high - low + 1; + UpdateArrays(sorting_indices, numSortedPoints, low); } //////////////////////////////////////////////////////////////////////////////// @@ -2574,6 +2559,25 @@ void TGraph::SwapPoints(Int_t pos1, Int_t pos2) SwapValues(fY, pos1, pos2); } +//////////////////////////////////////////////////////////////////////////////// +/// Update the fX and fY arrays with the sorted values. + +void TGraph::UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) +{ + std::vector fXSorted(numSortedPoints); + std::vector fYSorted(numSortedPoints); + + // Fill the sorted X and Y values based on the sorted indices + std::generate(fXSorted.begin(), fXSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fX[sorting_indices[begin++]]; }); + std::generate(fYSorted.begin(), fYSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fY[sorting_indices[begin++]]; }); + + // Copy the sorted X and Y values back to the original arrays + std::copy(fXSorted.begin(), fXSorted.end(), fX + low); + std::copy(fYSorted.begin(), fYSorted.end(), fY + low); +} + //////////////////////////////////////////////////////////////////////////////// /// Swap values. diff --git a/hist/hist/src/TGraph2D.cxx b/hist/hist/src/TGraph2D.cxx index 15e3f7c49943e..592ce5da1a8ac 100644 --- a/hist/hist/src/TGraph2D.cxx +++ b/hist/hist/src/TGraph2D.cxx @@ -243,17 +243,17 @@ TGraph2D::TGraph2D() fMargin = 0.; fNpx = 40; fNpy = 40; - fDirectory = 0; - fHistogram = 0; + fDirectory = nullptr; + fHistogram = nullptr; fDelaunay = nullptr; fMaximum = -1111; fMinimum = -1111; - fX = 0; - fY = 0; - fZ = 0; + fX = nullptr; + fY = nullptr; + fZ = nullptr; fZout = 0; fMaxIter = 100000; - fPainter = 0; + fPainter = nullptr; fFunctions = new TList; fUserHisto = kFALSE; } @@ -471,7 +471,7 @@ TGraph2D::TGraph2D(const char *filename, const char *format, Option_t *option) // Initializing loop variables Bool_t isLineToBeSkipped = kFALSE ; //empty and ill-formed lines - char * token = NULL ; + char * token = nullptr ; TString token_str = "" ; Int_t token_idx = 0 ; Double_t * value = new Double_t [3] ; //x,y,z buffers @@ -485,7 +485,7 @@ TGraph2D::TGraph2D(const char *filename, const char *format, Option_t *option) line.erase(line.end() - 1, line.end()) ; } token = R__STRTOK_R(const_cast(line.c_str()), option, &rest); - while (token != NULL && value_idx < 3) { + while (token != nullptr && value_idx < 3) { if (isTokenToBeSaved[token_idx]) { token_str = TString(token) ; token_str.ReplaceAll("\t", "") ; @@ -497,7 +497,7 @@ TGraph2D::TGraph2D(const char *filename, const char *format, Option_t *option) value_idx++ ; } } - token = R__STRTOK_R(NULL, option, &rest); // next token + token = R__STRTOK_R(nullptr, option, &rest); // next token token_idx++ ; } if (!isLineToBeSkipped && value_idx == 3) { @@ -509,7 +509,7 @@ TGraph2D::TGraph2D(const char *filename, const char *format, Option_t *option) } } isLineToBeSkipped = kFALSE ; - token = NULL ; + token = nullptr ; token_idx = 0 ; value_idx = 0 ; } @@ -529,8 +529,8 @@ TGraph2D::TGraph2D(const char *filename, const char *format, Option_t *option) TGraph2D::TGraph2D(const TGraph2D &g) : TNamed(g), TAttLine(g), TAttFill(g), TAttMarker(g), - fX(0), fY(0), fZ(0), - fHistogram(0), fDirectory(0), fPainter(0) + fX(nullptr), fY(nullptr), fZ(nullptr), + fHistogram(nullptr), fDirectory(nullptr), fPainter(nullptr) { fFunctions = new TList(); // do not copy the functions @@ -581,9 +581,9 @@ TGraph2D& TGraph2D::operator=(const TGraph2D &g) fNpy = g.fNpy; fMaxIter = g.fMaxIter; fSize = fNpoints; // force size to be the same of npoints - fX = (fSize > 0) ? new Double_t[fSize] : 0; - fY = (fSize > 0) ? new Double_t[fSize] : 0; - fZ = (fSize > 0) ? new Double_t[fSize] : 0; + fX = (fSize > 0) ? new Double_t[fSize] : nullptr; + fY = (fSize > 0) ? new Double_t[fSize] : nullptr; + fZ = (fSize > 0) ? new Double_t[fSize] : nullptr; fMinimum = g.fMinimum; fMaximum = g.fMaximum; fMargin = g.fMargin; @@ -618,8 +618,8 @@ void TGraph2D::Build(Int_t n) fMargin = 0.; fNpx = 40; fNpy = 40; - fDirectory = 0; - fHistogram = 0; + fDirectory = nullptr; + fHistogram = nullptr; fDelaunay = nullptr; fMaximum = -1111; fMinimum = -1111; @@ -629,7 +629,7 @@ void TGraph2D::Build(Int_t n) fZout = 0; fMaxIter = 100000; fFunctions = new TList; - fPainter = 0; + fPainter = nullptr; fUserHisto = kFALSE; if (TH1::AddDirectoryStatus()) { @@ -657,11 +657,11 @@ void TGraph2D::Browse(TBrowser *) void TGraph2D::Clear(Option_t * /*option = "" */) { if (fX) delete [] fX; - fX = 0; + fX = nullptr; if (fY) delete [] fY; - fY = 0; + fY = nullptr; if (fZ) delete [] fZ; - fZ = 0; + fZ = nullptr; fSize = fNpoints = 0; if (fHistogram && !fUserHisto) { delete fHistogram; @@ -672,11 +672,11 @@ void TGraph2D::Clear(Option_t * /*option = "" */) fFunctions->SetBit(kInvalidObject); fFunctions->Delete(); delete fFunctions; - fFunctions = 0; + fFunctions = nullptr; } if (fDirectory) { fDirectory->Remove(this); - fDirectory = 0; + fDirectory = nullptr; } } @@ -767,7 +767,7 @@ void TGraph2D::ExecuteEvent(Int_t event, Int_t px, Int_t py) TObject *TGraph2D::FindObject(const char *name) const { if (fFunctions) return fFunctions->FindObject(name); - return 0; + return nullptr; } @@ -777,7 +777,7 @@ TObject *TGraph2D::FindObject(const char *name) const TObject *TGraph2D::FindObject(const TObject *obj) const { if (fFunctions) return fFunctions->FindObject(obj); - return 0; + return nullptr; } @@ -820,7 +820,7 @@ TFitResultPtr TGraph2D::Fit(TF2 *f2, Option_t *option, Option_t *) // internal graph2D fitting methods Foption_t fitOption; Option_t *goption = ""; - ROOT::Fit::FitOptionsMake(ROOT::Fit::kGraph, option, fitOption); + ROOT::Fit::FitOptionsMake(ROOT::Fit::EFitObjectType::kGraph, option, fitOption); // create range and minimizer options with default values ROOT::Fit::DataRange range(2); @@ -861,7 +861,7 @@ void TGraph2D::FitPanel() TAxis *TGraph2D::GetXaxis() const { TH1 *h = ((TGraph2D*)this)->GetHistogram("empty"); - if (!h) return 0; + if (!h) return nullptr; return h->GetXaxis(); } @@ -872,7 +872,7 @@ TAxis *TGraph2D::GetXaxis() const TAxis *TGraph2D::GetYaxis() const { TH1 *h = ((TGraph2D*)this)->GetHistogram("empty"); - if (!h) return 0; + if (!h) return nullptr; return h->GetYaxis(); } @@ -883,7 +883,7 @@ TAxis *TGraph2D::GetYaxis() const TAxis *TGraph2D::GetZaxis() const { TH1 *h = ((TGraph2D*)this)->GetHistogram("empty"); - if (!h) return 0; + if (!h) return nullptr; return h->GetZaxis(); } @@ -897,7 +897,7 @@ TList *TGraph2D::GetContourList(Double_t contour) { if (fNpoints <= 0) { Error("GetContourList", "Empty TGraph2D"); - return 0; + return nullptr; } if (!fHistogram) GetHistogram("empty"); @@ -1065,8 +1065,8 @@ TH2D *TGraph2D::GetHistogram(Option_t *option) } // Option "empty" is selected. An empty histogram is returned. + Double_t hzmax, hzmin; if (empty) { - Double_t hzmax, hzmin; if (fMinimum != -1111) { hzmin = fMinimum; } else { @@ -1111,6 +1111,10 @@ TH2D *TGraph2D::GetHistogram(Option_t *option) } } + hzmin = GetZminE(); + hzmax = GetZmaxE(); + if (hzmin < fHistogram->GetMinimum()) fHistogram->SetMinimum(hzmin); + if (hzmax > fHistogram->GetMaximum()) fHistogram->SetMaximum(hzmax); if (fMinimum != -1111) fHistogram->SetMinimum(fMinimum); if (fMaximum != -1111) fHistogram->SetMaximum(fMaximum); @@ -1302,7 +1306,7 @@ TH1 *TGraph2D::Project(Option_t *option) const { if (fNpoints <= 0) { Error("Project", "Empty TGraph2D"); - return 0; + return nullptr; } TString opt = option; @@ -1315,8 +1319,8 @@ TH1 *TGraph2D::Project(Option_t *option) const if (opt.Contains("yx")) pcase = 4; // Create the projection histogram - TH1D *h1 = 0; - TH2D *h2 = 0; + TH1D *h1 = nullptr; + TH2D *h2 = nullptr; Int_t nch = strlen(GetName()) + opt.Length() + 2; char *name = new char[nch]; snprintf(name, nch, "%s_%s", GetName(), option); @@ -1352,7 +1356,7 @@ TH1 *TGraph2D::Project(Option_t *option) const delete [] title; TH1 *h = h1; if (h2) h = h2; - if (h == 0) return 0; + if (h == nullptr) return nullptr; // Fill the projected histogram Double_t entries = 0; @@ -1438,7 +1442,7 @@ void TGraph2D::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) << GetYaxis()->GetTitle() << ";" << GetZaxis()->GetTitle() << quote << ");" << std::endl; - if (fDirectory == 0) { + if (fDirectory == nullptr) { out << " graph2d->SetDirectory(0);" << std::endl; } diff --git a/hist/hist/src/TGraph2DAsymmErrors.cxx b/hist/hist/src/TGraph2DAsymmErrors.cxx index 09fe26a3192c4..1899af11009d8 100644 --- a/hist/hist/src/TGraph2DAsymmErrors.cxx +++ b/hist/hist/src/TGraph2DAsymmErrors.cxx @@ -172,7 +172,7 @@ TGraph2DAsymmErrors::~TGraph2DAsymmErrors() /// Copy everything except list of functions TGraph2DAsymmErrors::TGraph2DAsymmErrors(const TGraph2DAsymmErrors &g) -: TGraph2D(g), fEXlow(0), fEXhigh(0), fEYlow(0), fEYhigh(0), fEZlow(0), fEZhigh(0) +: TGraph2D(g), fEXlow(nullptr), fEXhigh(nullptr), fEYlow(nullptr), fEYhigh(nullptr), fEZlow(nullptr), fEZhigh(nullptr) { if (fSize > 0) { fEXlow = new Double_t[fSize]; diff --git a/hist/hist/src/TGraph2DErrors.cxx b/hist/hist/src/TGraph2DErrors.cxx index 37ce60c3d5f5b..63211e673b5ab 100644 --- a/hist/hist/src/TGraph2DErrors.cxx +++ b/hist/hist/src/TGraph2DErrors.cxx @@ -148,7 +148,7 @@ TGraph2DErrors::~TGraph2DErrors() /// Copy everything except list of functions TGraph2DErrors::TGraph2DErrors(const TGraph2DErrors &g) -: TGraph2D(g), fEX(0), fEY(0), fEZ(0) +: TGraph2D(g), fEX(nullptr), fEY(nullptr), fEZ(nullptr) { if (fSize > 0) { fEX = new Double_t[fSize]; diff --git a/hist/hist/src/TGraphAsymmErrors.cxx b/hist/hist/src/TGraphAsymmErrors.cxx index 8307581e03ea2..90a7b4b906c9b 100644 --- a/hist/hist/src/TGraphAsymmErrors.cxx +++ b/hist/hist/src/TGraphAsymmErrors.cxx @@ -1028,7 +1028,7 @@ void TGraphAsymmErrors::CopyAndRelease(Double_t **newarrays, Bool_t TGraphAsymmErrors::CopyPoints(Double_t **arrays, Int_t ibegin, Int_t iend, Int_t obegin) { - if (TGraph::CopyPoints(arrays ? arrays+4 : 0, ibegin, iend, obegin)) { + if (TGraph::CopyPoints(arrays ? arrays+4 : nullptr, ibegin, iend, obegin)) { Int_t n = (iend - ibegin)*sizeof(Double_t); if (arrays) { memmove(&arrays[0][obegin], &fEXlow[ibegin], n); @@ -1456,3 +1456,32 @@ void TGraphAsymmErrors::SwapPoints(Int_t pos1, Int_t pos2) SwapValues(fEYhigh, pos1, pos2); TGraph::SwapPoints(pos1, pos2); } + +//////////////////////////////////////////////////////////////////////////////// +/// Update the fX, fY, fEXlow, fEXhigh, fEYlow and fEYhigh arrays with the sorted values. + +void TGraphAsymmErrors::UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) +{ + std::vector fEXlowSorted(numSortedPoints); + std::vector fEXhighSorted(numSortedPoints); + std::vector fEYlowSorted(numSortedPoints); + std::vector fEYhighSorted(numSortedPoints); + + // Fill the sorted X and Y error values based on the sorted indices + std::generate(fEXlowSorted.begin(), fEXlowSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXlow[sorting_indices[begin++]]; }); + std::generate(fEXhighSorted.begin(), fEXhighSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXhigh[sorting_indices[begin++]]; }); + std::generate(fEYlowSorted.begin(), fEYlowSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYlow[sorting_indices[begin++]]; }); + std::generate(fEYhighSorted.begin(), fEYhighSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYhigh[sorting_indices[begin++]]; }); + + // Copy the sorted X and Y error values back to the original arrays + std::copy(fEXlowSorted.begin(), fEXlowSorted.end(), fEXlow + low); + std::copy(fEXhighSorted.begin(), fEXhighSorted.end(), fEXhigh + low); + std::copy(fEYlowSorted.begin(), fEYlowSorted.end(), fEYlow + low); + std::copy(fEYhighSorted.begin(), fEYhighSorted.end(), fEYhigh + low); + + TGraph::UpdateArrays(sorting_indices, numSortedPoints, low); +} diff --git a/hist/hist/src/TGraphBentErrors.cxx b/hist/hist/src/TGraphBentErrors.cxx index 6e40906233eeb..0836f0eb082ee 100644 --- a/hist/hist/src/TGraphBentErrors.cxx +++ b/hist/hist/src/TGraphBentErrors.cxx @@ -303,7 +303,7 @@ void TGraphBentErrors::CopyAndRelease(Double_t **newarrays, Bool_t TGraphBentErrors::CopyPoints(Double_t **arrays, Int_t ibegin, Int_t iend, Int_t obegin) { - if (TGraph::CopyPoints(arrays ? arrays+8 : 0, ibegin, iend, obegin)) { + if (TGraph::CopyPoints(arrays ? arrays+8 : nullptr, ibegin, iend, obegin)) { Int_t n = (iend - ibegin)*sizeof(Double_t); if (arrays) { memmove(&arrays[0][obegin], &fEXlow[ibegin], n); @@ -648,3 +648,52 @@ void TGraphBentErrors::SwapPoints(Int_t pos1, Int_t pos2) TGraph::SwapPoints(pos1, pos2); } + +//////////////////////////////////////////////////////////////////////////////// +/// Update the fX, fY, fEXlow, fEXhigh, fEXlowd, fEXhighd, fEYlow, fEYhigh, fEYlowd, +/// and fEYhighd arrays with the sorted values. + +void TGraphBentErrors::UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) +{ + std::vector fEXlowSorted(numSortedPoints); + std::vector fEXhighSorted(numSortedPoints); + std::vector fEXlowdSorted(numSortedPoints); + std::vector fEXhighdSorted(numSortedPoints); + + std::vector fEYlowSorted(numSortedPoints); + std::vector fEYhighSorted(numSortedPoints); + std::vector fEYlowdSorted(numSortedPoints); + std::vector fEYhighdSorted(numSortedPoints); + + // Fill the sorted X and Y error values based on the sorted indices + std::generate(fEXlowSorted.begin(), fEXlowSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXlow[sorting_indices[begin++]]; }); + std::generate(fEXhighSorted.begin(), fEXhighSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXhigh[sorting_indices[begin++]]; }); + std::generate(fEXlowdSorted.begin(), fEXlowdSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXlowd[sorting_indices[begin++]]; }); + std::generate(fEXhighdSorted.begin(), fEXhighdSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEXhighd[sorting_indices[begin++]]; }); + + std::generate(fEYlowSorted.begin(), fEYlowSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYlow[sorting_indices[begin++]]; }); + std::generate(fEYhighSorted.begin(), fEYhighSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYhigh[sorting_indices[begin++]]; }); + std::generate(fEYlowdSorted.begin(), fEYlowdSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYlowd[sorting_indices[begin++]]; }); + std::generate(fEYhighdSorted.begin(), fEYhighdSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEYhighd[sorting_indices[begin++]]; }); + + // Copy the sorted X and Y error values back to the original arrays + std::copy(fEXlowSorted.begin(), fEXlowSorted.end(), fEXlow + low); + std::copy(fEXhighSorted.begin(), fEXhighSorted.end(), fEXhigh + low); + std::copy(fEXlowdSorted.begin(), fEXlowdSorted.end(), fEXlowd + low); + std::copy(fEXhighdSorted.begin(), fEXhighdSorted.end(), fEXhighd + low); + + std::copy(fEYlowSorted.begin(), fEYlowSorted.end(), fEYlow + low); + std::copy(fEYhighSorted.begin(), fEYhighSorted.end(), fEYhigh + low); + std::copy(fEYlowdSorted.begin(), fEYlowdSorted.end(), fEYlowd + low); + std::copy(fEYhighdSorted.begin(), fEYhighdSorted.end(), fEYhighd + low); + + TGraph::UpdateArrays(sorting_indices, numSortedPoints, low); +} diff --git a/hist/hist/src/TGraphDelaunay.cxx b/hist/hist/src/TGraphDelaunay.cxx index fe7cada6e77ac..f8e5f1214cf11 100644 --- a/hist/hist/src/TGraphDelaunay.cxx +++ b/hist/hist/src/TGraphDelaunay.cxx @@ -49,23 +49,23 @@ practical view of Delaunay triangulation and Voronoi diagram. TGraphDelaunay::TGraphDelaunay() : TNamed("TGraphDelaunay","TGraphDelaunay") { - fGraph2D = 0; - fX = 0; - fY = 0; - fZ = 0; + fGraph2D = nullptr; + fX = nullptr; + fY = nullptr; + fZ = nullptr; fNpoints = 0; fTriedSize = 0; fZout = 0.; fNdt = 0; fNhull = 0; - fHullPoints = 0; - fXN = 0; - fYN = 0; - fOrder = 0; - fDist = 0; - fPTried = 0; - fNTried = 0; - fMTried = 0; + fHullPoints = nullptr; + fXN = nullptr; + fYN = nullptr; + fOrder = nullptr; + fDist = nullptr; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; fInit = kFALSE; fXNmin = 0.; fXNmax = 0.; @@ -95,14 +95,14 @@ TGraphDelaunay::TGraphDelaunay(TGraph2D *g) fZout = 0.; fNdt = 0; fNhull = 0; - fHullPoints = 0; - fXN = 0; - fYN = 0; - fOrder = 0; - fDist = 0; - fPTried = 0; - fNTried = 0; - fMTried = 0; + fHullPoints = nullptr; + fXN = nullptr; + fYN = nullptr; + fOrder = nullptr; + fDist = nullptr; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; fInit = kFALSE; fXNmin = 0.; fXNmax = 0.; @@ -131,14 +131,14 @@ TGraphDelaunay::~TGraphDelaunay() if (fXN) delete [] fXN; if (fYN) delete [] fYN; - fPTried = 0; - fNTried = 0; - fMTried = 0; - fHullPoints = 0; - fOrder = 0; - fDist = 0; - fXN = 0; - fYN = 0; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; + fHullPoints = nullptr; + fOrder = nullptr; + fDist = nullptr; + fXN = nullptr; + fYN = nullptr; } diff --git a/hist/hist/src/TGraphErrors.cxx b/hist/hist/src/TGraphErrors.cxx index 0f424c390c252..5b0d937dc9b2e 100644 --- a/hist/hist/src/TGraphErrors.cxx +++ b/hist/hist/src/TGraphErrors.cxx @@ -524,7 +524,7 @@ void TGraphErrors::CopyAndRelease(Double_t **newarrays, Bool_t TGraphErrors::CopyPoints(Double_t **arrays, Int_t ibegin, Int_t iend, Int_t obegin) { - if (TGraph::CopyPoints(arrays ? arrays + 2 : 0, ibegin, iend, obegin)) { + if (TGraph::CopyPoints(arrays ? arrays + 2 : nullptr, ibegin, iend, obegin)) { Int_t n = (iend - ibegin) * sizeof(Double_t); if (arrays) { memmove(&arrays[0][obegin], &fEX[ibegin], n); @@ -842,7 +842,6 @@ void TGraphErrors::Streamer(TBuffer &b) } } - //////////////////////////////////////////////////////////////////////////////// /// Swap points. @@ -852,3 +851,24 @@ void TGraphErrors::SwapPoints(Int_t pos1, Int_t pos2) SwapValues(fEY, pos1, pos2); TGraph::SwapPoints(pos1, pos2); } + +//////////////////////////////////////////////////////////////////////////////// +/// Update the fX, fY, fEX, and fEY arrays with the sorted values. + +void TGraphErrors::UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) +{ + std::vector fEXSorted(numSortedPoints); + std::vector fEYSorted(numSortedPoints); + + // Fill the sorted X and Y error values based on the sorted indices + std::generate(fEXSorted.begin(), fEXSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEX[sorting_indices[begin++]]; }); + std::generate(fEYSorted.begin(), fEYSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fEY[sorting_indices[begin++]]; }); + + // Copy the sorted X and Y error values back to the original arrays + std::copy(fEXSorted.begin(), fEXSorted.end(), fEX + low); + std::copy(fEYSorted.begin(), fEYSorted.end(), fEY + low); + + TGraph::UpdateArrays(sorting_indices, numSortedPoints, low); +} diff --git a/hist/hist/src/TGraphMultiErrors.cxx b/hist/hist/src/TGraphMultiErrors.cxx index e2482320176c3..3117bad5c224c 100644 --- a/hist/hist/src/TGraphMultiErrors.cxx +++ b/hist/hist/src/TGraphMultiErrors.cxx @@ -879,6 +879,38 @@ void TGraphMultiErrors::SwapPoints(Int_t pos1, Int_t pos2) TGraph::SwapPoints(pos1, pos2); } +//////////////////////////////////////////////////////////////////////////////// +/// Update the fX, fY, fExL, fExH, fEyL and fEyH arrays with the sorted values. + +void TGraphMultiErrors::UpdateArrays(const std::vector &sorting_indices, Int_t numSortedPoints, Int_t low) +{ + std::vector fExLSorted(numSortedPoints); + std::vector fExHSorted(numSortedPoints); + + std::generate(fExLSorted.begin(), fExLSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fExL[sorting_indices[begin++]]; }); + std::generate(fExHSorted.begin(), fExHSorted.end(), + [begin = low, &sorting_indices, this]() mutable { return fExH[sorting_indices[begin++]]; }); + + std::copy(fExLSorted.begin(), fExLSorted.end(), fExL + low); + std::copy(fExHSorted.begin(), fExHSorted.end(), fExH + low); + + for (Int_t j = 0; j < fNYErrors; j++) { + std::vector fEyLSorted(numSortedPoints); + std::vector fEyHSorted(numSortedPoints); + + std::generate(fEyLSorted.begin(), fEyLSorted.end(), + [begin = low, &sorting_indices, &j, this]() mutable { return fEyL[j].GetArray()[sorting_indices[begin++]]; }); + std::generate(fEyHSorted.begin(), fEyHSorted.end(), + [begin = low, &sorting_indices, &j, this]() mutable { return fEyL[j].GetArray()[sorting_indices[begin++]]; }); + + std::copy(fEyLSorted.begin(), fEyLSorted.end(), fEyL[j].GetArray() + low); + std::copy(fEyHSorted.begin(), fEyHSorted.end(), fEyL[j].GetArray() + low); + } + + TGraph::UpdateArrays(sorting_indices, numSortedPoints, low); +} + //////////////////////////////////////////////////////////////////////////////// /// Add a new y error to the graph and fill it with the values from `eyL` and `eyH` diff --git a/hist/hist/src/TGraphSmooth.cxx b/hist/hist/src/TGraphSmooth.cxx index fae3c82dbe6b9..995cf252ee3aa 100644 --- a/hist/hist/src/TGraphSmooth.cxx +++ b/hist/hist/src/TGraphSmooth.cxx @@ -10,16 +10,11 @@ *************************************************************************/ /****************************************************************************** -* Copyright(c) 2001- , Dr. Christian Stratowa, Vienna, Austria. * +* Copyright(c) 2001-2006, Dr. Christian Stratowa, Vienna, Austria. * * Author: Christian Stratowa with help from Rene Brun. * * * * Algorithms for smooth regression adapted from: * * R: A Computer Language for Statistical Data Analysis * -* Copyright (C) 1996 Robert Gentleman and Ross Ihaka * -* Copyright (C) 1999-2001 Robert Gentleman, Ross Ihaka and the * -* R Development Core Team * -* R is free software, for licensing see the GNU General Public License * -* http://www.ci.tuwien.ac.at/R-project/welcome.html * * * ******************************************************************************/ @@ -42,8 +37,8 @@ TGraphSmooth::TGraphSmooth(): TNamed() { fNin = 0; fNout = 0; - fGin = 0; - fGout = 0; + fGin = nullptr; + fGout = nullptr; fMinX = 0; fMaxX = 0; } @@ -55,8 +50,8 @@ TGraphSmooth::TGraphSmooth(const char *name): TNamed(name,"") { fNin = 0; fNout = 0; - fGin = 0; - fGout = 0; + fGin = nullptr; + fGout = nullptr; fMinX = 0; fMaxX = 0; } @@ -67,8 +62,8 @@ TGraphSmooth::TGraphSmooth(const char *name): TNamed(name,"") TGraphSmooth::~TGraphSmooth() { if (fGout) delete fGout; - fGin = 0; - fGout = 0; + fGin = nullptr; + fGout = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -76,7 +71,7 @@ TGraphSmooth::~TGraphSmooth() void TGraphSmooth::Smoothin(TGraph *grin) { - if (fGout) {delete fGout; fGout = 0;} + if (fGout) {delete fGout; fGout = nullptr;} fGin = grin; fNin = fGin->GetN(); @@ -125,8 +120,8 @@ TGraph *TGraphSmooth::SmoothKern(TGraph *grin, Option_t *option, Smoothin(grin); Double_t delta = 0; - Int_t *index = 0; - if (xout == 0) { + Int_t *index = nullptr; + if (xout == nullptr) { fNout = TMath::Max(nout, fNin); delta = (fMaxX - fMinX)/(fNout - 1); } else { @@ -137,14 +132,14 @@ TGraph *TGraphSmooth::SmoothKern(TGraph *grin, Option_t *option, fGout = new TGraph(fNout); for (Int_t i=0;iSetPoint(i,fMinX + i*delta, 0); + if (xout == nullptr) fGout->SetPoint(i,fMinX + i*delta, 0); else fGout->SetPoint(i,xout[index[i]], 0); } BDRksmooth(fGin->GetX(), fGin->GetY(), fNin, fGout->GetX(), fGout->GetY(), fNout, kernel, bandwidth); - if (index) {delete [] index; index = 0;} + if (index) {delete [] index; index = nullptr;} return fGout; } @@ -486,7 +481,7 @@ TGraph *TGraphSmooth::SmoothSuper(TGraph *grin, Option_t * option, { if (span < 0 || span > 1) { std::cout << "Error: Span must be between 0 and 1" << std::endl; - return 0; + return nullptr; } TString opt = option; opt.ToLower(); @@ -498,7 +493,7 @@ TGraph *TGraphSmooth::SmoothSuper(TGraph *grin, Option_t * option, iper = 2; if (fMinX < 0 || fMaxX > 1) { std::cout << "Error: x must be between 0 and 1 for periodic smooth" << std::endl; - return 0; + return nullptr; } } @@ -513,7 +508,7 @@ TGraph *TGraphSmooth::SmoothSuper(TGraph *grin, Option_t * option, // weights Double_t *weight = new Double_t[fNin]; for (i=0; iGetN(); @@ -1010,7 +1005,7 @@ TGraph *TGraphSmooth::Approx(TGraph *grin, Option_t *option, Int_t nout, Double_ if (f < 0 || f > 1) { std::cout << "Error: Invalid f value" << std::endl; - return 0; + return nullptr; } opt = ties; @@ -1026,7 +1021,7 @@ TGraph *TGraphSmooth::Approx(TGraph *grin, Option_t *option, Int_t nout, Double_ iTies = 3; } else { std::cout << "Error: Method not known: " << ties << std::endl; - return 0; + return nullptr; } // input X, Y @@ -1037,7 +1032,7 @@ TGraph *TGraphSmooth::Approx(TGraph *grin, Option_t *option, Int_t nout, Double_ // output X, Y Double_t delta = 0; fNout = nout; - if (xout == 0) { + if (xout == nullptr) { fNout = TMath::Max(nout, fNin); delta = (fMaxX - fMinX)/(fNout - 1); } @@ -1046,7 +1041,7 @@ TGraph *TGraphSmooth::Approx(TGraph *grin, Option_t *option, Int_t nout, Double_ Double_t x; for (Int_t i=0;iGetX(), fGin->GetY(), fNin, iKind, ylow, yhigh); fGout->SetPoint(i,x, yout); diff --git a/hist/hist/src/TGraphTime.cxx b/hist/hist/src/TGraphTime.cxx index e7f00b662573c..225132a5eaaf2 100644 --- a/hist/hist/src/TGraphTime.cxx +++ b/hist/hist/src/TGraphTime.cxx @@ -37,8 +37,8 @@ TGraphTime::TGraphTime(): TNamed() fXmax = 1; fYmin = 0; fYmax = 1; - fSteps = 0; - fFrame = 0; + fSteps = nullptr; + fFrame = nullptr; } @@ -73,7 +73,7 @@ TGraphTime::~TGraphTime() { if (!fSteps) return; fSteps->Delete(); - delete fSteps; fSteps=0; + delete fSteps; fSteps=nullptr; } @@ -145,7 +145,7 @@ void TGraphTime::Paint(Option_t *option) TString opt = option; opt.ToLower(); TObject *frame = gPad->GetPrimitive("frame"); - TList *list = 0; + TList *list = nullptr; TObjLink *lnk; for (Int_t s=0;sUpdate(); if (filename && strlen(filename) > 0) - gPad->Print(Form("%s+", filename)); + gPad->Print(TString::Format("%s+", filename)); else - gPad->Print(Form("%s+", GetName())); + gPad->Print(TString::Format("%s+", GetName())); if (fSleepTime > 0) gSystem->Sleep(fSleepTime); } diff --git a/hist/hist/src/TH1.cxx b/hist/hist/src/TH1.cxx index 27540acd50de1..4a2550bb23774 100644 --- a/hist/hist/src/TH1.cxx +++ b/hist/hist/src/TH1.cxx @@ -567,7 +567,7 @@ When using the options 2 or 3 above, the labels are automatically histogram, call TH1::ResetStats. See TH1::GetStats. */ -TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead) +TF1 *gF1=nullptr; //left for back compatibility (use TVirtualFitter::GetUserFunc instead) Int_t TH1::fgBufferSize = 1000; Bool_t TH1::fgAddDirectory = kTRUE; @@ -836,7 +836,7 @@ Bool_t TH1::Add(TF1 *f1, Double_t c1, Option_t *option) Int_t bin, binx, biny, binz; Double_t cu=0; Double_t xx[3]; - Double_t *params = 0; + Double_t *params = nullptr; f1->InitArgs(xx,params); for (binz = 0; binz < ncellsz; ++binz) { xx[2] = fZaxis.GetBinCenter(binz); @@ -1489,7 +1489,7 @@ Int_t TH1::BufferFill(Double_t x, Double_t w) fBuffer[0] = nbentries; if (fEntries > 0) { // set fBuffer to zero to avoid calling BufferEmpty in Reset - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); // do not reset list of functions fBuffer = buffer; } @@ -2477,6 +2477,7 @@ Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood /// By default the full range of the histogram is used. /// Use option "R" for restricting the chisquare calculation to the given range of the function /// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare) +/// Use option "P" for using the Pearson chisquare based on the expected bin errors Double_t TH1::Chisquare(TF1 * func, Option_t *option) const { @@ -2487,9 +2488,11 @@ Double_t TH1::Chisquare(TF1 * func, Option_t *option) const TString opt(option); opt.ToUpper(); bool useRange = opt.Contains("R"); - bool usePL = opt.Contains("L"); + ROOT::Fit::EChisquareType type = ROOT::Fit::EChisquareType::kNeyman; // default chi2 with observed error + if (opt.Contains("L")) type = ROOT::Fit::EChisquareType::kPLikeRatio; + else if (opt.Contains("P")) type = ROOT::Fit::EChisquareType::kPearson; - return ROOT::Fit::Chisquare(*this, *func, useRange, usePL); + return ROOT::Fit::Chisquare(*this, *func, useRange, type); } //////////////////////////////////////////////////////////////////////////////// @@ -2616,7 +2619,7 @@ TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const hintegrated->AddBinContent(bin, sum); if (fSumw2.fN) { esum += GetBinErrorSqUnchecked(bin); - fSumw2.fArray[bin] = esum; + hintegrated->fSumw2.fArray[bin] = esum; } } } @@ -2630,7 +2633,7 @@ TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const hintegrated->AddBinContent(bin, sum); if (fSumw2.fN) { esum += GetBinErrorSqUnchecked(bin); - fSumw2.fArray[bin] = esum; + hintegrated->fSumw2.fArray[bin] = esum; } } } @@ -2728,7 +2731,7 @@ void TH1::Copy(TObject &obj) const TObject* TH1::Clone(const char* newname) const { - TH1* obj = (TH1*)IsA()->GetNew()(0); + TH1* obj = (TH1*)IsA()->GetNew()(nullptr); Copy(*obj); // Now handle the parts that Copy doesn't do @@ -2838,7 +2841,7 @@ Bool_t TH1::Divide(TF1 *f1, Double_t c1) Int_t bin, binx, biny, binz; Double_t cu, w; Double_t xx[3]; - Double_t *params = 0; + Double_t *params = nullptr; f1->InitArgs(xx,params); for (binz = 0; binz < nz; ++binz) { xx[2] = fZaxis.GetBinCenter(binz); @@ -3310,7 +3313,7 @@ TH1* TH1::FFT(TH1* h_output, Option_t *option) delete [] kind; } - if (!fft) return 0; + if (!fft) return nullptr; Int_t in=0; for (Int_t binx = 1; binx<=ndim[0]; binx++) { for (Int_t biny=1; biny<=ndim[1]; biny++) { @@ -3855,7 +3858,7 @@ Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis, Int_t firstBin, Int_ TObject *TH1::FindObject(const char *name) const { if (fFunctions) return fFunctions->FindObject(name); - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -3864,7 +3867,7 @@ TObject *TH1::FindObject(const char *name) const TObject *TH1::FindObject(const TObject *obj) const { if (fFunctions) return fFunctions->FindObject(obj); - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -4261,7 +4264,7 @@ TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xx { // implementation of Fit method is in file hist/src/HFitImpl.cxx Foption_t fitOption; - ROOT::Fit::FitOptionsMake(ROOT::Fit::kHistogram,option,fitOption); + ROOT::Fit::FitOptionsMake(ROOT::Fit::EFitObjectType::kHistogram,option,fitOption); // create range and minimizer options with default values ROOT::Fit::DataRange range(xxmin,xxmax); @@ -4588,7 +4591,7 @@ Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum) Int_t i, ibin; Double_t *prob = (Double_t*)probSum; Int_t nq = nprobSum; - if (probSum == 0) { + if (probSum == nullptr) { nq = nbins+1; prob = new Double_t[nq]; prob[0] = 0; @@ -4617,7 +4620,7 @@ Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum) Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption) { - ROOT::Fit::FitOptionsMake(ROOT::Fit::kHistogram, choptin,fitOption); + ROOT::Fit::FitOptionsMake(ROOT::Fit::EFitObjectType::kHistogram, choptin,fitOption); return 1; } @@ -5211,7 +5214,7 @@ Bool_t TH1::IsBinUnderflow(Int_t bin, Int_t iaxis) const void TH1::LabelsDeflate(Option_t *ax) { Int_t iaxis = AxisChoice(ax); - TAxis *axis = 0; + TAxis *axis = nullptr; if (iaxis == 1) axis = GetXaxis(); if (iaxis == 2) axis = GetYaxis(); if (iaxis == 3) axis = GetZaxis(); @@ -5281,7 +5284,7 @@ void TH1::LabelsDeflate(Option_t *ax) void TH1::LabelsInflate(Option_t *ax) { Int_t iaxis = AxisChoice(ax); - TAxis *axis = 0; + TAxis *axis = nullptr; if (iaxis == 1) axis = GetXaxis(); if (iaxis == 2) axis = GetYaxis(); if (iaxis == 3) axis = GetZaxis(); @@ -5348,7 +5351,7 @@ void TH1::LabelsInflate(Option_t *ax) void TH1::LabelsOption(Option_t *option, Option_t *ax) { Int_t iaxis = AxisChoice(ax); - TAxis *axis = 0; + TAxis *axis = nullptr; if (iaxis == 1) axis = GetXaxis(); if (iaxis == 2) @@ -6034,7 +6037,7 @@ Bool_t TH1::Multiply(TF1 *f1, Double_t c1) // - Loop on bins (including underflows/overflows) Double_t xx[3]; - Double_t *params = 0; + Double_t *params = nullptr; f1->InitArgs(xx,params); for (Int_t binz = 0; binz < nz; ++binz) { @@ -6263,16 +6266,16 @@ TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins) Double_t xmax = fXaxis.GetXmax(); if ((ngroup <= 0) || (ngroup > nbins)) { Error("Rebin", "Illegal value of ngroup=%d",ngroup); - return 0; + return nullptr; } if (fDimension > 1 || InheritsFrom(TProfile::Class())) { Error("Rebin", "Operation valid on 1-D histograms only"); - return 0; + return nullptr; } if (!newname && xbins) { Error("Rebin","if xbins is specified, newname must be given"); - return 0; + return nullptr; } Int_t newbins = nbins/ngroup; @@ -6296,7 +6299,7 @@ TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins) Double_t *oldBins = new Double_t[nbins+2]; Int_t bin, i; for (bin=0;bin> fTsumwx2; if (R__v < 2) { Float_t maximum, minimum, norm; - Float_t *contour=0; + Float_t *contour=nullptr; b >> maximum; fMaximum = maximum; b >> minimum; fMinimum = minimum; b >> norm; fNormFactor = norm; @@ -8003,8 +8006,8 @@ Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const ROOT::Fit::BinData data1; ROOT::Fit::BinData data2; - ROOT::Fit::FillData(data1, this, 0); - ROOT::Fit::FillData(data2, h2, 0); + ROOT::Fit::FillData(data1, this, nullptr); + ROOT::Fit::FillData(data2, h2, nullptr); double pvalue; ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue); @@ -8092,7 +8095,7 @@ Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const Double_t prob = 0; TH1 *h1 = (TH1*)this; - if (h2 == 0) return 0; + if (h2 == nullptr) return 0; const TAxis *axis1 = h1->GetXaxis(); const TAxis *axis2 = h2->GetXaxis(); Int_t ncx1 = axis1->GetNbins(); @@ -8851,7 +8854,7 @@ void TH1::SetNameTitle(const char *name, const char *title) /// Set statistics option on/off. /// /// By default, the statistics box is drawn. -/// The paint options can be selected via gStyle->SetOptStats. +/// The paint options can be selected via gStyle->SetOptStat. /// This function sets/resets the kNoStats bit in the histogram object. /// It has priority over the Style option. @@ -9188,18 +9191,18 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option) { if (!fft || !fft->GetN() ) { ::Error("TransformHisto","Invalid FFT transform class"); - return 0; + return nullptr; } if (fft->GetNdim()>2){ ::Error("TransformHisto","Only 1d and 2D transform are supported"); - return 0; + return nullptr; } Int_t binx,biny; TString opt = option; opt.ToUpper(); Int_t *n = fft->GetN(); - TH1 *hout=0; + TH1 *hout=nullptr; if (h_output) { hout = h_output; } @@ -9210,7 +9213,7 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option) else if (fft->GetNdim()==2) hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]); } - R__ASSERT(hout != 0); + R__ASSERT(hout != nullptr); TString type=fft->GetType(); Int_t ind[2]; if (opt.Contains("RE")){ @@ -9244,7 +9247,7 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option) } } else { ::Error("TransformHisto","No complex numbers in the output"); - return 0; + return nullptr; } } if (opt.Contains("MA")) { @@ -9293,7 +9296,7 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option) } } else { printf("Pure real output, no phase"); - return 0; + return nullptr; } } diff --git a/hist/hist/src/TH1K.cxx b/hist/hist/src/TH1K.cxx index 40dcbd43061fe..014b3bddfca72 100644 --- a/hist/hist/src/TH1K.cxx +++ b/hist/hist/src/TH1K.cxx @@ -178,7 +178,7 @@ void TH1K::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) <<","<SetDirectory(0);"<GetName(),allHaveLabels,allSameLimits,initialLimitsFound ); - } while ( ( h = dynamic_cast ( next() ) ) != NULL ); + } while ( ( h = dynamic_cast ( next() ) ) != nullptr ); if (!h && (*next) ) { Error("Merge","Attempt to merge object of class: %s to a %s", @@ -493,7 +493,7 @@ void TH1Merger::DefineNewAxes() { Bool_t mustCleanup = fH0->TestBit(kMustCleanup); if (mustCleanup) fH0->ResetBit(kMustCleanup); fHClone = (TH1*)fH0->IsA()->New(); - fHClone->SetDirectory(0); + fHClone->SetDirectory(nullptr); fH0->Copy(*fHClone); if (mustCleanup) fH0->SetBit(kMustCleanup); fH0->BufferEmpty(1); // To remove buffer. @@ -556,7 +556,7 @@ void TH1Merger::CopyBuffer(TH1 *hsrc, TH1 *hdes) // Check inputs //if (!hsrc || !hsrc->fBuffer || !hdes || !hdes->fBuffer) { if (!hsrc || !hsrc->fBuffer || !hdes ) { - void *p1 = hsrc ? hsrc->fBuffer : 0; + void *p1 = hsrc ? hsrc->fBuffer : nullptr; //void *p2 = hdes ? hdes->fBuffer : 0; //Warning("TH1Merger::CopyMerge", "invalid inputs: %p, %p, %p, %p -> do nothing", hsrc, hdes, p1, p2); Warning("TH1Merger::CopyMerge", "invalid inputs: %p, %p, %p, -> do nothing", hsrc, hdes, p1); @@ -588,7 +588,7 @@ void TH1Merger::CopyBuffer(TH1 *hsrc, TH1 *hdes) Bool_t TH1Merger::AutoP2BufferMerge() { - TH1 *href = 0, *hist = 0; + TH1 *href = nullptr, *hist = nullptr; TIter nextref(&fInputList); if (TH1Merger::AxesHaveLimits(fH0)) { href = fH0; @@ -637,7 +637,7 @@ Bool_t TH1Merger::AutoP2Merge() } TIter next(&fInputList); - TH1 *hist = 0; + TH1 *hist = nullptr; // Calculate boundaries and bins Double_t xmin = 0., xmax = 0.; if (!(fH0->IsEmpty())) { @@ -660,7 +660,7 @@ Bool_t TH1Merger::AutoP2Merge() Error("TH1Merger::AutoP2Merge", "cannot create axes from %s", hist->GetName()); return kFALSE; } - TH1 *h = 0; + TH1 *h = nullptr; while ((h = (TH1 *)next())) { if (!AutoP2BuildAxes(h)) { Error("TH1Merger::AutoP2Merge", "cannot merge histogram %s: not merge compatible", h->GetName()); diff --git a/hist/hist/src/TH2.cxx b/hist/hist/src/TH2.cxx index 6d3bde0edaca3..0137b328b031c 100644 --- a/hist/hist/src/TH2.cxx +++ b/hist/hist/src/TH2.cxx @@ -245,7 +245,7 @@ Int_t TH2::BufferEmpty(Int_t action) nbentries = -nbentries; // a reset might call BufferEmpty() giving an infinite loop // Protect it by setting fBuffer = 0 - fBuffer=0; + fBuffer=nullptr; //do not reset the list of functions Reset("ICES"); fBuffer = buffer; @@ -268,7 +268,7 @@ Int_t TH2::BufferEmpty(Int_t action) if (fXaxis.GetXmax() <= fXaxis.GetXmin() || fYaxis.GetXmax() <= fYaxis.GetXmin()) { THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this,xmin,xmax,ymin,ymax); } else { - fBuffer = 0; + fBuffer = nullptr; Int_t keep = fBufferSize; fBufferSize = 0; if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis); if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis); @@ -279,13 +279,13 @@ Int_t TH2::BufferEmpty(Int_t action) } } - fBuffer = 0; + fBuffer = nullptr; for (Int_t i=0;i 0) { delete [] fBuffer; fBuffer = 0; fBufferSize = 0;} + if (action > 0) { delete [] fBuffer; fBuffer = nullptr; fBufferSize = 0;} else { if (nbentries == (Int_t)fEntries) fBuffer[0] = -nbentries; else fBuffer[0] = 0; @@ -311,7 +311,7 @@ Int_t TH2::BufferFill(Double_t x, Double_t y, Double_t w) nbentries = -nbentries; fBuffer[0] = nbentries; if (fEntries > 0) { - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); fBuffer = buffer; } @@ -612,7 +612,7 @@ void TH2::FillN(Int_t ntimes, const Double_t *x, const Double_t *y, const Double else BufferFill(x[i], y[i], 1.); } // fill the remaining entries if the buffer has been deleted - if (i < ntimes && fBuffer==0) + if (i < ntimes && fBuffer==nullptr) ifirst = i; else return; @@ -811,9 +811,9 @@ void TH2::DoFitSlices(bool onX, if (opt.Contains("s")) nstep = 1; //default is to fit with a gaussian - if (f1 == 0) { + if (f1 == nullptr) { f1 = (TF1*)gROOT->GetFunction("gaus"); - if (f1 == 0) f1 = new TF1("gaus","gaus",innerAxis.GetXmin(),innerAxis.GetXmax()); + if (f1 == nullptr) f1 = new TF1("gaus","gaus",innerAxis.GetXmin(),innerAxis.GetXmax()); else f1->SetRange(innerAxis.GetXmin(),innerAxis.GetXmax()); } Int_t npar = f1->GetNpar(); @@ -854,7 +854,7 @@ void TH2::DoFitSlices(bool onX, } snprintf(name,2000,"%s_chi2",GetName()); delete gDirectory->FindObject(name); - TH1D *hchi2 = 0; + TH1D *hchi2 = nullptr; if (bins->fN == 0) { hchi2 = new TH1D(name,"chisquare", nOutBins, outerAxis.GetBinLowEdge(firstOutBin), outerAxis.GetBinUpEdge(lastOutBin)); } else { @@ -877,7 +877,7 @@ void TH2::DoFitSlices(bool onX, hp= ProjectionX("_temp",bin,bin+ngroup-1,proj_opt); else hp= ProjectionY("_temp",bin,bin+ngroup-1,proj_opt); - if (hp == 0) continue; + if (hp == nullptr) continue; // nentries can be the effective entries and it could be a very small number but not zero! Double_t nentries = hp->GetEntries(); if ( nentries <= 0 || nentries < cut) { @@ -1427,7 +1427,7 @@ Double_t TH2::KolmogorovTest(const TH1 *h2, Option_t *option) const Double_t prb = 0; TH1 *h1 = (TH1*)this; - if (h2 == 0) return 0; + if (h2 == nullptr) return 0; const TAxis *xaxis1 = h1->GetXaxis(); const TAxis *xaxis2 = h2->GetXaxis(); const TAxis *yaxis1 = h1->GetYaxis(); @@ -1661,15 +1661,15 @@ TH2 *TH2::Rebin2D(Int_t nxgroup, Int_t nygroup, const char *newname) if (GetDimension() != 2) { Error("Rebin2D", "Histogram must be TH2. This histogram has %d dimensions.", GetDimension()); - return 0; + return nullptr; } if ((nxgroup <= 0) || (nxgroup > nxbins)) { Error("Rebin2D", "Illegal value of nxgroup=%d",nxgroup); - return 0; + return nullptr; } if ((nygroup <= 0) || (nygroup > nybins)) { Error("Rebin2D", "Illegal value of nygroup=%d",nygroup); - return 0; + return nullptr; } Int_t newxbins = nxbins / nxgroup; @@ -1681,7 +1681,7 @@ TH2 *TH2::Rebin2D(Int_t nxgroup, Int_t nygroup, const char *newname) Double_t *oldBins = new Double_t[fNcells]; for (Int_t i = 0; i < fNcells; ++i) oldBins[i] = RetrieveBinContent(i); - Double_t* oldErrors = NULL; + Double_t* oldErrors = nullptr; if (fSumw2.fN) { oldErrors = new Double_t[fNcells]; for (Int_t i = 0; i < fNcells; ++i) oldErrors[i] = GetBinErrorSqUnchecked(i); @@ -1876,14 +1876,14 @@ TProfile *TH2::DoProfile(bool onX, const char *name, Int_t firstbin, Int_t lastb pname = new char[nch]; snprintf(pname,nch,"%s%s",GetName(),name); } - TProfile *h1=0; + TProfile *h1=nullptr; //check if a profile with identical name exist // if compatible reset and re-use previous histogram TObject *h1obj = gROOT->FindObject(pname); if (h1obj && h1obj->InheritsFrom(TH1::Class())) { if (h1obj->IsA() != TProfile::Class() ) { Error("DoProfile","Histogram with name %s must be a TProfile and is a %s",name,h1obj->ClassName()); - return 0; + return nullptr; } h1 = (TProfile*)h1obj; // reset the existing histogram and set always the new binning for the axis @@ -2110,7 +2110,7 @@ TProfile *TH2::ProfileY(const char *name, Int_t firstxbin, Int_t lastxbin, Optio TH1D *TH2::DoProjection(bool onX, const char *name, Int_t firstbin, Int_t lastbin, Option_t *option) const { - const char *expectedName = 0; + const char *expectedName = nullptr; Int_t inNbin; const TAxis* outAxis; const TAxis* inAxis; @@ -2168,7 +2168,7 @@ TH1D *TH2::DoProjection(bool onX, const char *name, Int_t firstbin, Int_t lastbi pname = new char[nch]; snprintf(pname,nch,"%s%s",GetName(),name); } - TH1D *h1=0; + TH1D *h1=nullptr; //check if histogram with identical name exist // if compatible reset and re-use previous histogram // (see https://savannah.cern.ch/bugs/?54340) @@ -2176,7 +2176,7 @@ TH1D *TH2::DoProjection(bool onX, const char *name, Int_t firstbin, Int_t lastbi if (h1obj && h1obj->InheritsFrom(TH1::Class())) { if (h1obj->IsA() != TH1D::Class() ) { Error("DoProjection","Histogram with name %s must be a TH1D and is a %s",name,h1obj->ClassName()); - return 0; + return nullptr; } h1 = (TH1D*)h1obj; // reset the existing histogram and set always the new binning for the axis @@ -2464,7 +2464,7 @@ TH1D* TH2::QuantilesY( Double_t prob, const char * name) const TH1D* TH2::DoQuantiles(bool onX, const char * name, Double_t prob) const { - const TAxis *outAxis = 0; + const TAxis *outAxis = nullptr; if ( onX ) { outAxis = GetXaxis(); } else { @@ -2478,14 +2478,14 @@ TH1D* TH2::DoQuantiles(bool onX, const char * name, Double_t prob) const qname = TString::Format("%s_%s_%3.2f",GetName(),qtype, prob); } // check if the histogram is already existing - TH1D *h1=0; + TH1D *h1=nullptr; //check if histogram with identical name exist TObject *h1obj = gROOT->FindObject(qname); if (h1obj) { h1 = dynamic_cast(h1obj); if (!h1) { Error("DoQuantiles","Histogram with name %s must be a TH1D and is a %s",qname.Data(),h1obj->ClassName()); - return 0; + return nullptr; } } if (h1) { @@ -2507,7 +2507,7 @@ TH1D* TH2::DoQuantiles(bool onX, const char * name, Double_t prob) const Double_t pp[1]; pp[0] = prob; - TH1D * slice = 0; + TH1D * slice = nullptr; for (int ibin = outAxis->GetFirst() ; ibin <= outAxis->GetLast() ; ++ibin) { Double_t qq[1]; // do a projection on the opposite axis @@ -2567,6 +2567,7 @@ void TH2::SetBinContent(Int_t bin, Double_t content) /// mouse position along Y. /// To stop the generation of the projections, delete the canvas /// containing the projection. +/// \param nbins number of bins in Y to sum across for the projection void TH2::SetShowProjectionX(Int_t nbins) { @@ -2582,6 +2583,7 @@ void TH2::SetShowProjectionX(Int_t nbins) /// mouse position along X. /// To stop the generation of the projections, delete the canvas /// containing the projection. +/// \param nbins number of bins in X to sum across for the projection void TH2::SetShowProjectionY(Int_t nbins) { @@ -2591,6 +2593,22 @@ void TH2::SetShowProjectionY(Int_t nbins) } +//////////////////////////////////////////////////////////////////////////////// +/// When the mouse is moved in a pad containing a 2-d view of this histogram +/// two canvases show the projection along X and Y corresponding to the +/// mouse position along Y and X, respectively. +/// To stop the generation of the projections, delete the canvas +/// containing the projection. +/// \param nbinsY number of bins in Y to sum across for the x projection +/// \param nbinsX number of bins in X to sum across for the y projection + +void TH2::SetShowProjectionXY(Int_t nbinsY, Int_t nbinsX) +{ + GetPainter(); + if (fPainter) fPainter->SetShowProjectionXY("x",nbinsY,nbinsX); +} + + //////////////////////////////////////////////////////////////////////////////// /// This function calculates the background spectrum in this histogram. /// The background is returned as a histogram. @@ -2687,7 +2705,7 @@ void TH2::Smooth(Int_t ntimes, Option_t *option) Int_t ny = GetNbinsY(); Int_t bufSize = (nx+2)*(ny+2); Double_t *buf = new Double_t[bufSize]; - Double_t *ebuf = 0; + Double_t *ebuf = nullptr; if (fSumw2.fN) ebuf = new Double_t[bufSize]; // Copy all the data to the temporary buffers diff --git a/hist/hist/src/TH2Poly.cxx b/hist/hist/src/TH2Poly.cxx index b06a0281d7cbb..a2466ff151f90 100644 --- a/hist/hist/src/TH2Poly.cxx +++ b/hist/hist/src/TH2Poly.cxx @@ -199,9 +199,9 @@ TH2Poly::~TH2Poly() TH2PolyBin *TH2Poly::CreateBin(TObject *poly) { - if (!poly) return 0; + if (!poly) return nullptr; - if (fBins == 0) { + if (fBins == nullptr) { fBins = new TList(); fBins->SetOwner(); } @@ -934,50 +934,91 @@ Double_t TH2Poly::GetMinimum(Double_t minval) const //////////////////////////////////////////////////////////////////////////////// /// Bins the histogram using a honeycomb structure +/// If the option "v" is specified, the hexagons are drawn "vertically" (default). +/// If the option "h" is selected they are drawn "horizontally". -void TH2Poly::Honeycomb(Double_t xstart, Double_t ystart, Double_t a, - Int_t k, Int_t s) +void TH2Poly::Honeycomb(Double_t xstart, Double_t ystart, Double_t a, Int_t k, Int_t s, Option_t* option) { - // Add the bins + TString opt = option; + opt.ToLower(); Double_t numberOfHexagonsInTheRow; Double_t x[6], y[6]; - Double_t xloop, yloop, xtemp; - xloop = xstart; yloop = ystart + a/2.0; - for (int sCounter = 0; sCounter < s; sCounter++) { - - xtemp = xloop; // Resets the temp variable - - // Determine the number of hexagons in that row - if(sCounter%2 == 0){numberOfHexagonsInTheRow = k;} - else{numberOfHexagonsInTheRow = k - 1;} - - for (int kCounter = 0; kCounter < numberOfHexagonsInTheRow; kCounter++) { - - // Go around the hexagon - x[0] = xtemp; - y[0] = yloop; - x[1] = x[0]; - y[1] = y[0] + a; - x[2] = x[1] + a*TMath::Sqrt(3)/2.0; - y[2] = y[1] + a/2.0; - x[3] = x[2] + a*TMath::Sqrt(3)/2.0; - y[3] = y[1]; - x[4] = x[3]; - y[4] = y[0]; - x[5] = x[2]; - y[5] = y[4] - a/2.0; - - this->AddBin(6, x, y); - - // Go right - xtemp += a*TMath::Sqrt(3); - } + Double_t xloop = xstart, yloop, xtemp, ytemp; - // Increment the starting position - if (sCounter%2 == 0) xloop += a*TMath::Sqrt(3)/2.0; - else xloop -= a*TMath::Sqrt(3)/2.0; - yloop += 1.5*a; + // Add the bins + if (opt.Contains("v")) { + yloop = ystart + a / 2.0; + for (int sCounter = 0; sCounter < s; sCounter++) { + xtemp = xloop; + // Determine the number of hexagons in that row + if (sCounter%2 == 0) + numberOfHexagonsInTheRow = k; + else + numberOfHexagonsInTheRow = k - 1; + + for (int kCounter = 0; kCounter < numberOfHexagonsInTheRow; kCounter++) { + // Go around the hexagon + x[0] = xtemp; + y[0] = yloop; + x[1] = x[0]; + y[1] = y[0] + a; + x[2] = x[1] + a * TMath::Sqrt(3) / 2.0; + y[2] = y[1] + a / 2.0; + x[3] = x[2] + a * TMath::Sqrt(3) / 2.0; + y[3] = y[1]; + x[4] = x[3]; + y[4] = y[0]; + x[5] = x[2]; + y[5] = y[4] - a/2.0; + this->AddBin(6, x, y); + // Go right + xtemp += a * TMath::Sqrt(3); + } + // Increment the starting position + if (sCounter%2 == 0) + xloop += a * TMath::Sqrt(3) / 2.0; + else + xloop -= a * TMath::Sqrt(3) / 2.0; + yloop += 1.5 * a; + } + } else if (opt.Contains("h")) { + yloop = ystart + a*TMath::Sqrt(3)/2.0; + for (int sCounter = 0; sCounter < s; sCounter++) { + ytemp = yloop; + // Determine the number of hexagons in that row + if (sCounter%2 == 0) + numberOfHexagonsInTheRow = k; + else + numberOfHexagonsInTheRow = k - 1; + for (int kCounter = 0; kCounter < numberOfHexagonsInTheRow; kCounter++) { + // Go around the hexagon + x[0] = xloop; + y[0] = ytemp; + x[1] = x[0] + a/2.0; + y[1] = y[0] + a * TMath::Sqrt(3) / 2.0; + x[2] = x[1] + a; + y[2] = y[1]; + x[3] = x[2] + a/2.0; + y[3] = y[0]; + x[4] = x[2]; + y[4] = y[3] - a * TMath::Sqrt(3) / 2.0; + x[5] = x[1]; + y[5] = y[4]; + this->AddBin(6, x, y); + // Go up + ytemp += a * TMath::Sqrt(3); + } + // Increment the starting position + if (sCounter%2 == 0) + yloop += a * TMath::Sqrt(3) / 2.0; + else + yloop -= a * TMath::Sqrt(3) / 2.0; + xloop += 1.5 * a; + } + } else { + Error("Honeycomb", "Unknown option"); } + } //////////////////////////////////////////////////////////////////////////////// @@ -989,7 +1030,7 @@ void TH2Poly::Initialize(Double_t xlow, Double_t xup, Int_t i; fDimension = 2; //The dimension of the histogram - fBins = 0; + fBins = nullptr; fNcells = kNOverflow; // Sets the boundaries of the histogram @@ -1331,7 +1372,7 @@ Helper class to represent a bin in the TH2Poly histogram TH2PolyBin::TH2PolyBin() { - fPoly = 0; + fPoly = nullptr; fContent = 0.; fNumber = 0; fXmax = -1111; diff --git a/hist/hist/src/TH3.cxx b/hist/hist/src/TH3.cxx index a72962c9d1afd..21e6afb1e1a20 100644 --- a/hist/hist/src/TH3.cxx +++ b/hist/hist/src/TH3.cxx @@ -229,7 +229,7 @@ Int_t TH3::BufferEmpty(Int_t action) if (nbentries < 0) { if (action == 0) return 0; nbentries = -nbentries; - fBuffer=0; + fBuffer=nullptr; Reset("ICES"); fBuffer = buffer; } @@ -257,7 +257,7 @@ Int_t TH3::BufferEmpty(Int_t action) if (fXaxis.GetXmax() <= fXaxis.GetXmin() || fYaxis.GetXmax() <= fYaxis.GetXmin() || fZaxis.GetXmax() <= fZaxis.GetXmin()) { THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this,xmin,xmax,ymin,ymax,zmin,zmax); } else { - fBuffer = 0; + fBuffer = nullptr; Int_t keep = fBufferSize; fBufferSize = 0; if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis); if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis); @@ -269,14 +269,14 @@ Int_t TH3::BufferEmpty(Int_t action) fBufferSize = keep; } } - fBuffer = 0; + fBuffer = nullptr; for (Int_t i=0;i 0) { delete [] fBuffer; fBuffer = 0; fBufferSize = 0;} + if (action > 0) { delete [] fBuffer; fBuffer = nullptr; fBufferSize = 0;} else { if (nbentries == (Int_t)fEntries) fBuffer[0] = -nbentries; else fBuffer[0] = 0; @@ -302,7 +302,7 @@ Int_t TH3::BufferFill(Double_t x, Double_t y, Double_t z, Double_t w) nbentries = -nbentries; fBuffer[0] = nbentries; if (fEntries > 0) { - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); fBuffer = buffer; } @@ -980,9 +980,9 @@ void TH3::FitSlicesZ(TF1 *f1, Int_t binminx, Int_t binmaxx, Int_t binminy, Int_t Int_t firstBinYaxis = computeAxisLimits(fYaxis, binminy, binmaxy, nbinsY, yMin, yMax); //default is to fit with a gaussian - if (f1 == 0) { + if (f1 == nullptr) { f1 = (TF1*)gROOT->GetFunction("gaus"); - if (f1 == 0) f1 = new TF1("gaus","gaus",fZaxis.GetXmin(),fZaxis.GetXmax()); + if (f1 == nullptr) f1 = new TF1("gaus","gaus",fZaxis.GetXmin(),fZaxis.GetXmax()); else f1->SetRange(fZaxis.GetXmin(),fZaxis.GetXmax()); } const char *fname = f1->GetName(); @@ -1494,7 +1494,7 @@ Double_t TH3::KolmogorovTest(const TH1 *h2, Option_t *option) const Double_t prb = 0; TH1 *h1 = (TH1*)this; - if (h2 == 0) return 0; + if (h2 == nullptr) return 0; const TAxis *xaxis1 = h1->GetXaxis(); const TAxis *xaxis2 = h2->GetXaxis(); const TAxis *yaxis1 = h1->GetYaxis(); @@ -1850,7 +1850,7 @@ TH1D *TH3::DoProject1D(const char* name, const char * title, const TAxis* projX, bool useUF, bool useOF) const { // Create the projection histogram - TH1D *h1 = 0; + TH1D *h1 = nullptr; // Get range to use as well as bin limits // Projected range must be inside and not outside original one (ROOT-8781) @@ -1863,7 +1863,7 @@ TH1D *TH3::DoProject1D(const char* name, const char * title, const TAxis* projX, if (h1obj && h1obj->InheritsFrom(TH1::Class())) { if (h1obj->IsA() != TH1D::Class() ) { Error("DoProject1D","Histogram with name %s must be a TH1D and is a %s",name,h1obj->ClassName()); - return 0; + return nullptr; } h1 = (TH1D*)h1obj; // reset histogram and re-set the axis in any case @@ -1939,7 +1939,7 @@ TH1D *TH3::DoProject1D(const char* name, const char * title, const TAxis* projX, } R__ASSERT(out1 != nullptr && out2 != nullptr); - Int_t *refX = 0, *refY = 0, *refZ = 0; + Int_t *refX = nullptr, *refY = nullptr, *refZ = nullptr; Int_t ixbin, out1bin, out2bin; if (projX == GetXaxis()) { refX = &ixbin; @@ -1956,7 +1956,7 @@ TH1D *TH3::DoProject1D(const char* name, const char * title, const TAxis* projX, refY = &out2bin; refZ = &ixbin; } - R__ASSERT (refX != 0 && refY != 0 && refZ != 0); + R__ASSERT (refX != nullptr && refY != nullptr && refZ != nullptr); // Fill the projected histogram excluding underflow/overflows if considered in the option // if specified in the option (by default they considered) @@ -2058,7 +2058,7 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, bool computeErrors, bool originalRange, bool useUF, bool useOF) const { - TH2D *h2 = 0; + TH2D *h2 = nullptr; // Get range to use as well as bin limits Int_t ixmin = std::max(projX->GetFirst(),1); @@ -2076,7 +2076,7 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, if (h2obj && h2obj->InheritsFrom(TH1::Class())) { if ( h2obj->IsA() != TH2D::Class() ) { Error("DoProject2D","Histogram with name %s must be a TH2D and is a %s",name,h2obj->ClassName()); - return 0; + return nullptr; } h2 = (TH2D*)h2obj; // reset histogram and its axes @@ -2136,8 +2136,8 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, } // Copy the axis attributes and the axis labels if needed. - THashList* labels1 = 0; - THashList* labels2 = 0; + THashList* labels1 = nullptr; + THashList* labels2 = nullptr; // "xy" h2->GetXaxis()->ImportAttributes(projY); h2->GetYaxis()->ImportAttributes(projX); @@ -2170,7 +2170,7 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, if ( computeErrors && (h2->GetSumw2N() != h2->GetNcells()) ) h2->Sumw2(); // Set references to the axis, so that the bucle has no branches. - const TAxis* out = 0; + const TAxis* out = nullptr; if ( projX != GetXaxis() && projY != GetXaxis() ) { out = GetXaxis(); } else if ( projX != GetYaxis() && projY != GetYaxis() ) { @@ -2179,7 +2179,7 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, out = GetZaxis(); } - Int_t *refX = 0, *refY = 0, *refZ = 0; + Int_t *refX = nullptr, *refY = nullptr, *refZ = nullptr; Int_t ixbin, iybin, outbin; if ( projX == GetXaxis() && projY == GetYaxis() ) { refX = &ixbin; refY = &iybin; refZ = &outbin; } if ( projX == GetYaxis() && projY == GetXaxis() ) { refX = &iybin; refY = &ixbin; refZ = &outbin; } @@ -2187,7 +2187,7 @@ TH2D *TH3::DoProject2D(const char* name, const char * title, const TAxis* projX, if ( projX == GetZaxis() && projY == GetXaxis() ) { refX = &iybin; refY = &outbin; refZ = &ixbin; } if ( projX == GetYaxis() && projY == GetZaxis() ) { refX = &outbin; refY = &ixbin; refZ = &iybin; } if ( projX == GetZaxis() && projY == GetYaxis() ) { refX = &outbin; refY = &iybin; refZ = &ixbin; } - R__ASSERT (refX != 0 && refY != 0 && refZ != 0); + R__ASSERT (refX != nullptr && refY != nullptr && refZ != nullptr); // Fill the projected histogram excluding underflow/overflows if considered in the option // if specified in the option (by default they considered) @@ -2377,7 +2377,7 @@ TH1 *TH3::Project3D(Option_t *option) const if (pcase == 0) { Error("Project3D","No projection axis specified - return a NULL pointer"); - return 0; + return nullptr; } // do not remove ptype from opt to use later in the projected histo name @@ -2406,7 +2406,7 @@ TH1 *TH3::Project3D(Option_t *option) const // Create the projection histogram - TH1 *h = 0; + TH1 *h = nullptr; TString name = GetName(); TString title = GetTitle(); @@ -2528,7 +2528,7 @@ TProfile2D *TH3::DoProjectProfile2D(const char* name, const char * title, const Int_t ny = iymax-iymin+1; // Create the projected profiles - TProfile2D *p2 = 0; + TProfile2D *p2 = nullptr; // Create the histogram, either reseting a preexisting one // Does an object with the same name exists? @@ -2536,7 +2536,7 @@ TProfile2D *TH3::DoProjectProfile2D(const char* name, const char * title, const if (p2obj && p2obj->InheritsFrom(TH1::Class())) { if (p2obj->IsA() != TProfile2D::Class() ) { Error("DoProjectProfile2D","Histogram with name %s must be a TProfile2D and is a %s",name,p2obj->ClassName()); - return 0; + return nullptr; } p2 = (TProfile2D*)p2obj; // reset existing profile and re-set bins @@ -2594,7 +2594,7 @@ TProfile2D *TH3::DoProjectProfile2D(const char* name, const char * title, const } // Set references to the axis, so that the loop has no branches. - const TAxis* outAxis = 0; + const TAxis* outAxis = nullptr; if ( projX != GetXaxis() && projY != GetXaxis() ) { outAxis = GetXaxis(); } else if ( projX != GetYaxis() && projY != GetYaxis() ) { @@ -2609,7 +2609,7 @@ TProfile2D *TH3::DoProjectProfile2D(const char* name, const char * title, const if (useWeights && (p2->GetBinSumw2()->fN != p2->GetNcells() ) ) p2->Sumw2(); // Set references to the bins, so that the loop has no branches. - Int_t *refX = 0, *refY = 0, *refZ = 0; + Int_t *refX = nullptr, *refY = nullptr, *refZ = nullptr; Int_t ixbin, iybin, outbin; if ( projX == GetXaxis() && projY == GetYaxis() ) { refX = &ixbin; refY = &iybin; refZ = &outbin; } if ( projX == GetYaxis() && projY == GetXaxis() ) { refX = &iybin; refY = &ixbin; refZ = &outbin; } @@ -2617,7 +2617,7 @@ TProfile2D *TH3::DoProjectProfile2D(const char* name, const char * title, const if ( projX == GetZaxis() && projY == GetXaxis() ) { refX = &iybin; refY = &outbin; refZ = &ixbin; } if ( projX == GetYaxis() && projY == GetZaxis() ) { refX = &outbin; refY = &ixbin; refZ = &iybin; } if ( projX == GetZaxis() && projY == GetYaxis() ) { refX = &outbin; refY = &iybin; refZ = &ixbin; } - R__ASSERT (refX != 0 && refY != 0 && refZ != 0); + R__ASSERT (refX != nullptr && refY != nullptr && refZ != nullptr); Int_t outmin = outAxis->GetFirst(); Int_t outmax = outAxis->GetLast(); @@ -2735,7 +2735,7 @@ TProfile2D *TH3::Project3DProfile(Option_t *option) const if (pcase == 0) { Error("Project3D","No projection axis specified - return a NULL pointer"); - return 0; + return nullptr; } // do not remove ptype from opt to use later in the projected histo name @@ -2757,7 +2757,7 @@ TProfile2D *TH3::Project3DProfile(Option_t *option) const } // Create the projected profile - TProfile2D *p2 = 0; + TProfile2D *p2 = nullptr; TString name = GetName(); TString title = GetTitle(); name += "_p"; name += opt; // opt may include a user defined name @@ -2886,15 +2886,15 @@ TH3 *TH3::Rebin3D(Int_t nxgroup, Int_t nygroup, Int_t nzgroup, const char *newna Double_t zmax = fZaxis.GetXmax(); if ((nxgroup <= 0) || (nxgroup > nxbins)) { Error("Rebin", "Illegal value of nxgroup=%d",nxgroup); - return 0; + return nullptr; } if ((nygroup <= 0) || (nygroup > nybins)) { Error("Rebin", "Illegal value of nygroup=%d",nygroup); - return 0; + return nullptr; } if ((nzgroup <= 0) || (nzgroup > nzbins)) { Error("Rebin", "Illegal value of nzgroup=%d",nzgroup); - return 0; + return nullptr; } Int_t newxbins = nxbins/nxgroup; @@ -2907,7 +2907,7 @@ TH3 *TH3::Rebin3D(Int_t nxgroup, Int_t nygroup, Int_t nzgroup, const char *newna for (Int_t ibin = 0; ibin < fNcells; ibin++) { oldBins[ibin] = RetrieveBinContent(ibin); } - Double_t *oldSumw2 = 0; + Double_t *oldSumw2 = nullptr; if (fSumw2.fN != 0) { oldSumw2 = new Double_t[fNcells]; for (Int_t ibin = 0; ibin < fNcells; ibin++) { diff --git a/hist/hist/src/THLimitsFinder.cxx b/hist/hist/src/THLimitsFinder.cxx index 05e21b6828ede..528b08303f651 100644 --- a/hist/hist/src/THLimitsFinder.cxx +++ b/hist/hist/src/THLimitsFinder.cxx @@ -12,7 +12,7 @@ #include "TMath.h" #include "THLimitsFinder.h" -THLimitsFinder *THLimitsFinder::fgLimitsFinder = 0; +THLimitsFinder *THLimitsFinder::fgLimitsFinder = nullptr; ClassImp(THLimitsFinder); diff --git a/hist/hist/src/THStack.cxx b/hist/hist/src/THStack.cxx index 26da0c79ed374..5dabc586cc18f 100644 --- a/hist/hist/src/THStack.cxx +++ b/hist/hist/src/THStack.cxx @@ -663,7 +663,7 @@ void THStack::ls(Option_t *option) const Long64_t THStack::Merge(TCollection* li, TFileMergeInfo * /* info */) { - if (li==0 || li->GetEntries()==0) { + if (li==nullptr || li->GetEntries()==0) { return fHists->GetEntries(); } TIter next(li); diff --git a/hist/hist/src/THn.cxx b/hist/hist/src/THn.cxx index 547785f59aee8..a2cdc4758428e 100644 --- a/hist/hist/src/THn.cxx +++ b/hist/hist/src/THn.cxx @@ -36,7 +36,7 @@ namespace { Bool_t respectAxisRange); ~THnBinIter() override { delete [] fCounter; } - Long64_t Next(Int_t* coord = 0) override; + Long64_t Next(Int_t* coord = nullptr) override; Int_t GetCoord(Int_t dim) const override { return fCounter[dim].i; } private: THnBinIter(const THnBinIter&); // intentionally unimplemented diff --git a/hist/hist/src/THnBase.cxx b/hist/hist/src/THnBase.cxx index 56ef7bbb733db..5d47991bbb659 100644 --- a/hist/hist/src/THnBase.cxx +++ b/hist/hist/src/THnBase.cxx @@ -197,7 +197,7 @@ void THnBase::Init(const char* name, const char* title, SetNameTitle(name, title); TIter iAxis(axes); - const TAxis* axis = 0; + const TAxis* axis = nullptr; Int_t pos = 0; Int_t *nbins = new Int_t[axes->GetEntriesFast()]; while ((axis = (TAxis*)iAxis())) { @@ -245,7 +245,7 @@ TH1* THnBase::CreateHist(const char* name, const char* title, Bool_t keepTargetAxis ) const { const int ndim = axes->GetSize(); - TH1* hist = 0; + TH1* hist = nullptr; // create hist with dummy axes, we fix them later. if (ndim == 1) hist = new TH1D(name, title, 1, 0., 1.); @@ -255,7 +255,7 @@ TH1* THnBase::CreateHist(const char* name, const char* title, hist = new TH3D(name, title, 1, 0., 1., 1, 0., 1., 1, 0., 1.); else { Error("CreateHist", "Cannot create histogram %s with %d dimensions!", name, ndim); - return 0; + return nullptr; } TAxis* hax[3] = {hist->GetXaxis(), hist->GetYaxis(), hist->GetZaxis()}; @@ -314,7 +314,7 @@ THnBase* THnBase::CreateHnAny(const char* name, const char* title, // type of the TH1. The class name will be "TH??\0" where the first // ? is 1,2 or 3 and the second ? indicates the storage as C, S, // I, F or D. - THnBase* s = 0; + THnBase* s = nullptr; const char* cname( h->ClassName() ); if (cname[0] == 'T' && cname[1] == 'H' && cname[2] >= '1' && cname[2] <= '3' && cname[4] == 0) { @@ -340,7 +340,7 @@ break; } if (!s) { ::Warning("THnSparse::CreateHnAny", "Unknown Type of Histogram"); - return 0; + return nullptr; } for (int i = 0; i < ndim; ++i) { @@ -351,7 +351,7 @@ break; const TArray *array = dynamic_cast(h); if (!array) { ::Warning("THnSparse::CreateHnAny", "Unknown Type of Histogram"); - return 0; + return nullptr; } s->Add(h); @@ -367,7 +367,7 @@ THnBase* THnBase::CreateHnAny(const char* name, const char* title, const THnBase* hn, Bool_t sparse, Int_t chunkSize /*= 1024 * 16*/) { - TClass* type = 0; + TClass* type = nullptr; if (hn->InheritsFrom(THnSparse::Class())) { if (sparse) type = hn->IsA(); else { @@ -381,7 +381,7 @@ THnBase* THnBase::CreateHnAny(const char* name, const char* title, else { hn->Error("CreateHnAny", "Type %s not implemented; please inform the ROOT team!", hn->IsA()->GetName()); - return 0; + return nullptr; } type = TClass::GetClass(TString::Format("THn%c", bintype)); } @@ -397,7 +397,7 @@ THnBase* THnBase::CreateHnAny(const char* name, const char* title, else if (hn->InheritsFrom(THnL::Class())) bintype = 'L'; else if (hn->InheritsFrom(THnL64::Class())) { hn->Error("CreateHnAny", "Type THnSparse with Long64_t bins is not available!"); - return 0; + return nullptr; } if (bintype) { type = TClass::GetClass(TString::Format("THnSparse%c", bintype)); @@ -406,12 +406,12 @@ THnBase* THnBase::CreateHnAny(const char* name, const char* title, } else { hn->Error("CreateHnAny", "Unhandled type %s, not deriving from THn nor THnSparse!", hn->IsA()->GetName()); - return 0; + return nullptr; } if (!type) { hn->Error("CreateHnAny", "Unhandled type %s, please inform the ROOT team!", hn->IsA()->GetName()); - return 0; + return nullptr; } THnBase* ret = (THnBase*)type->New(); @@ -583,11 +583,11 @@ TObject* THnBase::ProjectionAny(Int_t ndim, const Int_t* dim, newaxes.AddAt(GetAxis(dim[d]),d); } - THnBase* hn = 0; - TH1* hist = 0; - TObject* ret = 0; + THnBase* hn = nullptr; + TH1* hist = nullptr; + TObject* ret = nullptr; - Bool_t* hadRange = 0; + Bool_t* hadRange = nullptr; Bool_t ignoreTargetRange = (option && (strchr(option, 'A') || strchr(option, 'a'))); Bool_t keepTargetAxis = ignoreTargetRange || (option && (strchr(option, 'O') || strchr(option, 'o'))); if (ignoreTargetRange) { @@ -743,7 +743,7 @@ void THnBase::AddInternal(const THnBase* h, Double_t c, Bool_t rebinned) Sumw2(); Bool_t haveErrors = GetCalculateErrors(); - Double_t* x = 0; + Double_t* x = nullptr; if (rebinned) { x = new Double_t[fNdimensions]; } @@ -837,7 +837,7 @@ Long64_t THnBase::Merge(TCollection* list) Long64_t sumNbins = GetNbins(); TIter iter(list); - const TObject* addMeObj = 0; + const TObject* addMeObj = nullptr; while ((addMeObj = iter())) { const THnBase* addMe = dynamic_cast(addMeObj); if (addMe) { @@ -936,7 +936,7 @@ void THnBase::Multiply(TF1* f, Double_t c) TF1::RejectPoint(kFALSE); // Evaluate function at points - Double_t fvalue = f->EvalPar(x, NULL); + Double_t fvalue = f->EvalPar(x, nullptr); SetBinContent(i, c * fvalue * value); if (wantErrors) { @@ -1186,7 +1186,7 @@ THnBase* THnBase::RebinBase(const Int_t* group) const Int_t ndim = GetNdimensions(); TString name(GetName()); for (Int_t d = 0; d < ndim; ++d) - name += Form("_%d", group[d]); + name += TString::Format("_%d", group[d]); TString title(GetTitle()); @@ -1194,10 +1194,10 @@ THnBase* THnBase::RebinBase(const Int_t* group) const if (posInsert == kNPOS) { title += " rebin "; for (Int_t d = 0; d < ndim; ++d) - title += Form("{%d}", group[d]); + title += TString::Format("{%d}", group[d]); } else { for (Int_t d = ndim - 1; d >= 0; --d) - title.Insert(posInsert, Form("{%d}", group[d])); + title.Insert(posInsert, TString::Format("{%d}", group[d])); title.Insert(posInsert, " rebin "); } @@ -1542,7 +1542,7 @@ ClassImp(ROOT::Internal::THnBaseBrowsable); /// Construct a THnBaseBrowsable. ROOT::Internal::THnBaseBrowsable::THnBaseBrowsable(THnBase* hist, Int_t axis): -fHist(hist), fAxis(axis), fProj(0) +fHist(hist), fAxis(axis), fProj(nullptr) { TString axisName = hist->GetAxis(axis)->GetName(); if (axisName.IsNull()) { diff --git a/hist/hist/src/THnSparse.cxx b/hist/hist/src/THnSparse.cxx index 3943dea53ef2c..187dec730b0db 100644 --- a/hist/hist/src/THnSparse.cxx +++ b/hist/hist/src/THnSparse.cxx @@ -34,7 +34,7 @@ namespace { ~THnSparseBinIter() override { delete [] fCoord; } Int_t GetCoord(Int_t dim) const override; - Long64_t Next(Int_t* coord = 0) override; + Long64_t Next(Int_t* coord = nullptr) override; private: THnSparseBinIter(const THnSparseBinIter&); // intentionally unimplemented @@ -72,7 +72,7 @@ Long64_t THnSparseBinIter::Next(Int_t* coord /*= 0*/) do { ++fIndex; if (fIndex >= fHist->GetNbins()) { - fHist = 0; + fHist = nullptr; return -1; } if (RespectsAxisRange()) { @@ -147,7 +147,7 @@ class THnSparseCoordCompression { /// stores the THnSparseCoordCompression::THnSparseCoordCompression(Int_t dim, const Int_t* nbins): - fNdimensions(dim), fCoordBufferSize(0), fBitOffsets(0) + fNdimensions(dim), fCoordBufferSize(0), fBitOffsets(nullptr) { fBitOffsets = new Int_t[dim + 1]; @@ -390,7 +390,7 @@ class THnSparseCompactBinCoord: public THnSparseCoordCompression { THnSparseCompactBinCoord::THnSparseCompactBinCoord(Int_t dim, const Int_t* nbins): THnSparseCoordCompression(dim, nbins), - fHash(0), fCoordBuffer(0), fCurrentBin(0) + fHash(0), fCoordBuffer(nullptr), fCurrentBin(nullptr) { fCurrentBin = new Int_t[dim]; size_t bufAllocSize = GetBufferSize(); @@ -426,8 +426,8 @@ ClassImp(THnSparseArrayChunk); THnSparseArrayChunk::THnSparseArrayChunk(Int_t coordsize, bool errors, TArray* cont): fCoordinateAllocationSize(-1), fSingleCoordinateSize(coordsize), fCoordinatesSize(0), - fCoordinates(0), fContent(cont), - fSumw2(0) + fCoordinates(nullptr), fContent(cont), + fSumw2(nullptr) { fCoordinateAllocationSize = fSingleCoordinateSize * cont->GetSize(); fCoordinates = new Char_t[fCoordinateAllocationSize]; @@ -587,7 +587,7 @@ ClassImp(THnSparse); /// Construct an empty THnSparse. THnSparse::THnSparse(): - fChunkSize(1024), fFilledBins(0), fCompactCoord(0) + fChunkSize(1024), fFilledBins(0), fCompactCoord(nullptr) { fBinContent.SetOwner(); } @@ -604,7 +604,7 @@ THnSparse::THnSparse(const char* name, const char* title, Int_t dim, const Int_t* nbins, const Double_t* xmin, const Double_t* xmax, Int_t chunksize): THnBase(name, title, dim, nbins, xmin, xmax), - fChunkSize(chunksize), fFilledBins(0), fCompactCoord(0) + fChunkSize(chunksize), fFilledBins(0), fCompactCoord(nullptr) { fCompactCoord = new THnSparseCompactBinCoord(dim, nbins); fBinContent.SetOwner(); @@ -655,7 +655,7 @@ void THnSparse::InitStorage(Int_t* nbins, Int_t chunkSize) void THnSparse::FillExMap() { TIter iChunk(&fBinContent); - THnSparseArrayChunk* chunk = 0; + THnSparseArrayChunk* chunk = nullptr; THnSparseCoordCompression compactCoord(*GetCompactCoord()); Long64_t idx = 0; if (2 * GetNbins() > fBins.Capacity()) @@ -866,7 +866,7 @@ Double_t THnSparse::GetSparseFractionMem() const { Int_t arrayElementSize = 0; if (fFilledBins) { TClass* clArray = GetChunk(0)->fContent->IsA(); - TDataMember* dm = clArray ? clArray->GetDataMember("fArray") : 0; + TDataMember* dm = clArray ? clArray->GetDataMember("fArray") : nullptr; arrayElementSize = dm ? dm->GetDataType()->Size() : 0; } if (!arrayElementSize) { @@ -951,7 +951,7 @@ void THnSparse::Sumw2() fTsumw2 = 0.; TIter iChunk(&fBinContent); - THnSparseArrayChunk* chunk = 0; + THnSparseArrayChunk* chunk = nullptr; while ((chunk = (THnSparseArrayChunk*) iChunk())) chunk->Sumw2(); } diff --git a/hist/hist/src/TKDE.cxx b/hist/hist/src/TKDE.cxx index 34f671925a3b3..2a988b63987d7 100644 --- a/hist/hist/src/TKDE.cxx +++ b/hist/hist/src/TKDE.cxx @@ -90,12 +90,12 @@ TKDE::~TKDE() { //// Internal function to instantiate a TKDE object void TKDE::Instantiate(KernelFunction_Ptr kernfunc, UInt_t events, const Double_t* data, const Double_t* dataWeights, Double_t xMin, Double_t xMax, const Option_t* option, Double_t rho) { - fPDF = 0; - fKernelFunction = 0; - fUpperPDF = 0; - fLowerPDF = 0; - fApproximateBias = 0; - fGraph = 0; + fPDF = nullptr; + fKernelFunction = nullptr; + fUpperPDF = nullptr; + fLowerPDF = nullptr; + fApproximateBias = nullptr; + fGraph = nullptr; fNewData = false; fUseMirroring = false; fMirrorLeft = false; fMirrorRight = false; fAsymLeft = false; fAsymRight = false; @@ -912,7 +912,7 @@ void TKDE::Draw(const Option_t* opt) { Double_t level = 0.95; const char * s = strstr(plotOpt.Data(),"interval@"); // coverity [secure_coding : FALSE] - if (s != 0) sscanf(s,"interval@%lf",&level); + if (s != nullptr) sscanf(s,"interval@%lf",&level); if((level <= 0) || (level >= 1)) { Warning("Draw","given confidence level %.3lf is invalid - use default 0.95",level); level = 0.95; @@ -991,7 +991,7 @@ const Double_t * TKDE::GetAdaptiveWeights() const { // Returns the bandwidths for the adaptive KDE if (fIteration != TKDE::kAdaptive) { this->Warning("GetFixedWeight()", "Adaptive iteration option not enabled. Returning a NULL pointer<"); - return 0; + return nullptr; } if (fNewData) (const_cast(this))->InitFromNewData(); return &(fKernel->GetAdaptiveWeights()).front(); diff --git a/hist/hist/src/TLimit.cxx b/hist/hist/src/TLimit.cxx index 06615c4313b5c..5143a84ed603d 100644 --- a/hist/hist/src/TLimit.cxx +++ b/hist/hist/src/TLimit.cxx @@ -232,11 +232,11 @@ bool TLimit::Fluctuate(TLimitDataSource * input, TLimitDataSource * output, if (init) { // create a "map" with the systematics names TIter errornames = input->GetErrorNames()->MakeIterator(); - TObjArray *listofnames = 0; + TObjArray *listofnames = nullptr; delete fgSystNames; fgSystNames = new TOrdCollection(); while ((listofnames = ((TObjArray *) errornames.Next()))) { - TObjString *name = 0; + TObjString *name = nullptr; TIter loniter = listofnames->MakeIterator(); while ((name = (TObjString *) loniter.Next())) if ((fgSystNames->IndexOf(name)) < 0) @@ -261,13 +261,13 @@ bool TLimit::Fluctuate(TLimitDataSource * input, TLimitDataSource * output, for(int i=1; i<=newsignal->GetNbinsX(); i++) { newsignal->SetBinContent(i,oldsignal->GetBinContent(i)+generator->Gaus(0,oldsignal->GetBinError(i))); } - newsignal->SetDirectory(0); + newsignal->SetDirectory(nullptr); TH1 *newbackground = (TH1*)(output->GetBackground()->At(channel)); TH1 *oldbackground = (TH1*)(input->GetBackground()->At(channel)); if(stat) for(int i=1; i<=newbackground->GetNbinsX(); i++) newbackground->SetBinContent(i,oldbackground->GetBinContent(i)+generator->Gaus(0,oldbackground->GetBinError(i))); - newbackground->SetDirectory(0); + newbackground->SetDirectory(nullptr); } return 1; } @@ -317,7 +317,7 @@ bool TLimit::Fluctuate(TLimitDataSource * input, TLimitDataSource * output, for(int i=1; i<=newsignal->GetNbinsX(); i++) newsignal->SetBinContent(i,oldsignal->GetBinContent(i)); newsignal->Scale(1 + serrf[channel]); - newsignal->SetDirectory(0); + newsignal->SetDirectory(nullptr); TH1 *newbackground = (TH1*)(output->GetBackground()->At(channel)); TH1 *oldbackground = (TH1*)(input->GetBackground()->At(channel)); if(stat) @@ -327,7 +327,7 @@ bool TLimit::Fluctuate(TLimitDataSource * input, TLimitDataSource * output, for(int i=1; i<=newbackground->GetNbinsX(); i++) newbackground->SetBinContent(i,oldbackground->GetBinContent(i)); newbackground->Scale(1 + berrf[channel]); - newbackground->SetDirectory(0); + newbackground->SetDirectory(nullptr); } delete[] serrf; delete[] berrf; diff --git a/hist/hist/src/TMultiDimFit.cxx b/hist/hist/src/TMultiDimFit.cxx index 075923e058c5d..9ff25031e9484 100644 --- a/hist/hist/src/TMultiDimFit.cxx +++ b/hist/hist/src/TMultiDimFit.cxx @@ -424,7 +424,7 @@ ClassImp(TMultiDimFit); //____________________________________________________________________ // Static instance. Used with mdfHelper and TMinuit -TMultiDimFit* TMultiDimFit::fgInstance = 0; +TMultiDimFit* TMultiDimFit::fgInstance = nullptr; //////////////////////////////////////////////////////////////////////////////// @@ -446,17 +446,17 @@ TMultiDimFit::TMultiDimFit() fMaxAngle = 0; fMaxTerms = 0; fMinRelativeError = 0; - fMaxPowers = 0; + fMaxPowers = nullptr; fPowerLimit = 0; fMaxFunctions = 0; - fFunctionCodes = 0; + fFunctionCodes = nullptr; fMaxStudy = 0; fMaxFuncNV = 0; - fMaxPowersFinal = 0; - fPowers = 0; - fPowerIndex = 0; + fMaxPowersFinal = nullptr; + fPowers = nullptr; + fPowerIndex = nullptr; fMaxResidual = 0; fMinResidual = 0; @@ -476,12 +476,12 @@ TMultiDimFit::TMultiDimFit() fCorrelationCoeff = 0; fTestCorrelationCoeff = 0; - fHistograms = 0; + fHistograms = nullptr; fHistogramMask = 0; fBinVarX = 100; fBinVarY = 100; - fFitter = 0; + fFitter = nullptr; fPolyType = kMonomials; fShowCorrelation = kFALSE; fIsUserFunction = kFALSE; @@ -536,13 +536,13 @@ fMinVariables(dimension) fPowerLimit = 1; fMaxFunctions = 0; - fFunctionCodes = 0; + fFunctionCodes = nullptr; fMaxStudy = 0; fMaxFuncNV = 0; fMaxPowersFinal = new Int_t[dimension]; - fPowers = 0; - fPowerIndex = 0; + fPowers = nullptr; + fPowerIndex = nullptr; fMaxResidual = 0; fMinResidual = 0; @@ -562,12 +562,12 @@ fMinVariables(dimension) fCorrelationCoeff = 0; fTestCorrelationCoeff = 0; - fHistograms = 0; + fHistograms = nullptr; fHistogramMask = 0; fBinVarX = 100; fBinVarY = 100; - fFitter = 0; + fFitter = nullptr; fPolyType = type; fShowCorrelation = kFALSE; fIsUserFunction = kFALSE; @@ -738,7 +738,7 @@ void TMultiDimFit::Browse(TBrowser* b) { if (fHistograms) { TIter next(fHistograms); - TH1* h = 0; + TH1* h = nullptr; while ((h = (TH1*)next())) b->Add(h,h->GetName()); } @@ -1052,7 +1052,7 @@ void TMultiDimFit::Fit(Option_t *option) return; } - fFitter = TVirtualFitter::Fitter(0,fNCoefficients); + fFitter = TVirtualFitter::Fitter(nullptr,fNCoefficients); if (!fFitter) { Error("Fit", "Cannot create Fitter"); delete [] x; @@ -1069,7 +1069,7 @@ void TMultiDimFit::Fit(Option_t *option) for (i = 0; i < fNCoefficients; i++) { Double_t startVal = fCoefficients(i); Double_t startErr = fCoefficientsRMS(i); - fFitter->SetParameter(i, Form("coeff%02d",i), + fFitter->SetParameter(i, TString::Format("coeff%02d",i).Data(), startVal, startErr, 0, 0); } @@ -1080,12 +1080,17 @@ void TMultiDimFit::Fit(Option_t *option) for (i = 0; i < fNCoefficients; i++) { Double_t val = 0, err = 0, low = 0, high = 0; - fFitter->GetParameter(i, Form("coeff%02d",i), + + // use big enough string buffer to get variable name which is not used + char namebuf[512]; + fFitter->GetParameter(i, namebuf, val, err, low, high); + (void) namebuf; fCoefficients(i) = val; fCoefficientsRMS(i) = err; } delete [] x; + delete [] arglist; } //////////////////////////////////////////////////////////////////////////////// @@ -1425,7 +1430,7 @@ void TMultiDimFit::MakeCoefficients() if (TESTBIT(fHistogramMask,HIST_RX)) for (j = 0; j < fNVariables; j++) - ((TH2D*)fHistograms->FindObject(Form("res_x_%d",j))) + ((TH2D*)fHistograms->FindObject(TString::Format("res_x_%d",j))) ->Fill(fVariables(i * fNVariables + j),fResiduals(i)); } } // If histograms @@ -1607,9 +1612,9 @@ void TMultiDimFit::MakeHistograms(Option_t *option) if (opt.Contains("x") || opt.Contains("a")) { SETBIT(fHistogramMask,HIST_XORIG); for (i = 0; i < fNVariables; i++) - if (!fHistograms->FindObject(Form("x_%d_orig",i))) - fHistograms->Add(new TH1D(Form("x_%d_orig",i), - Form("Original variable # %d",i), + if (!fHistograms->FindObject(TString::Format("x_%d_orig",i))) + fHistograms->Add(new TH1D(TString::Format("x_%d_orig",i), + TString::Format("Original variable # %d",i), fBinVarX, fMinVariables(i), fMaxVariables(i))); } @@ -1626,9 +1631,9 @@ void TMultiDimFit::MakeHistograms(Option_t *option) if (opt.Contains("n") || opt.Contains("a")) { SETBIT(fHistogramMask,HIST_XNORM); for (i = 0; i < fNVariables; i++) - if (!fHistograms->FindObject(Form("x_%d_norm",i))) - fHistograms->Add(new TH1D(Form("x_%d_norm",i), - Form("Normalized variable # %d",i), + if (!fHistograms->FindObject(TString::Format("x_%d_norm",i))) + fHistograms->Add(new TH1D(TString::Format("x_%d_norm",i), + TString::Format("Normalized variable # %d",i), fBinVarX, -1,1)); } @@ -1645,9 +1650,9 @@ void TMultiDimFit::MakeHistograms(Option_t *option) if (opt.Contains("r1") || opt.Contains("a")) { SETBIT(fHistogramMask,HIST_RX); for (i = 0; i < fNVariables; i++) - if (!fHistograms->FindObject(Form("res_x_%d",i))) - fHistograms->Add(new TH2D(Form("res_x_%d",i), - Form("Computed residual versus x_%d", i), + if (!fHistograms->FindObject(TString::Format("res_x_%d",i))) + fHistograms->Add(new TH2D(TString::Format("res_x_%d",i), + TString::Format("Computed residual versus x_%d", i), fBinVarX, -1, 1, fBinVarY, fMinQuantity - fMeanQuantity, @@ -1738,7 +1743,7 @@ void TMultiDimFit::MakeHistograms(Option_t *option) void TMultiDimFit::MakeMethod(const Char_t* classname, Option_t* option) { - MakeRealCode(Form("%sMDF.cxx", classname), classname, option); + MakeRealCode(TString::Format("%sMDF.cxx", classname), classname, option); } @@ -1770,7 +1775,7 @@ void TMultiDimFit::MakeNormalized() // Fill histograms of original independent variables if (TESTBIT(fHistogramMask,HIST_XORIG)) - ((TH1D*)fHistograms->FindObject(Form("x_%d_orig",j))) + ((TH1D*)fHistograms->FindObject(TString::Format("x_%d_orig",j))) ->Fill(fVariables(k)); // Normalise independent variables @@ -1778,7 +1783,7 @@ void TMultiDimFit::MakeNormalized() // Fill histograms of normalised independent variables if (TESTBIT(fHistogramMask,HIST_XNORM)) - ((TH1D*)fHistograms->FindObject(Form("x_%d_norm",j))) + ((TH1D*)fHistograms->FindObject(TString::Format("x_%d_norm",j))) ->Fill(fVariables(k)); } @@ -1962,8 +1967,10 @@ void TMultiDimFit::MakeRealCode(const char *filename, Int_t i, j; Bool_t isMethod = (classname[0] == '\0' ? kFALSE : kTRUE); - const char *prefix = (isMethod ? Form("%s::", classname) : ""); - const char *cv_qual = (isMethod ? "" : "static "); + TString prefix; + const char *cv_qual = isMethod ? "" : "static "; + if (isMethod) + prefix.Form("%s::", classname); std::ofstream outFile(filename,std::ios::out|std::ios::trunc); if (!outFile) { diff --git a/hist/hist/src/TMultiGraph.cxx b/hist/hist/src/TMultiGraph.cxx index e111f8fedb88a..2aa4e0136b7e7 100644 --- a/hist/hist/src/TMultiGraph.cxx +++ b/hist/hist/src/TMultiGraph.cxx @@ -702,7 +702,7 @@ TFitResultPtr TMultiGraph::Fit(TF1 *f1, Option_t *option, Option_t *goption, Axi { // internal multigraph fitting methods Foption_t fitOption; - ROOT::Fit::FitOptionsMake(ROOT::Fit::kGraph,option,fitOption); + ROOT::Fit::FitOptionsMake(ROOT::Fit::EFitObjectType::kGraph,option,fitOption); // create range and minimizer options with default values ROOT::Fit::DataRange range(rxmin,rxmax); @@ -1050,8 +1050,15 @@ TH1F *TMultiGraph::GetHistogram() if (rwymin == rwymax) rwymax += 1.; double dx = 0.05*(rwxmax-rwxmin); double dy = 0.05*(rwymax-rwymin); - rwxmin = rwxmin - dx; - rwxmax = rwxmax + dx; + if (gPad && gPad->GetLogx()) { + if (rwxmin <= 0) rwxmin = 0.001*rwxmax; + double r = rwxmax/rwxmin; + rwxmin = rwxmin/(1+0.5*TMath::Log10(r)); + rwxmax = rwxmax*(1+0.2*TMath::Log10(r)); + } else { + rwxmin = rwxmin - dx; + rwxmax = rwxmax + dx; + } if (gPad && gPad->GetLogy()) { if (rwymin <= 0) rwymin = 0.001*rwymax; double r = rwymax/rwymin; @@ -1303,7 +1310,7 @@ void TMultiGraph::Paint(Option_t *choptin) fHistogram->SetBit(TH1::kNoStats); fHistogram->SetMaximum(rwymax); fHistogram->GetYaxis()->SetLimits(rwymin,rwymax); - fHistogram->SetDirectory(0); + fHistogram->SetDirectory(nullptr); if (!xtitle.empty()) fHistogram->GetXaxis()->SetTitle(xtitle.c_str()); if (!ytitle.empty()) fHistogram->GetYaxis()->SetTitle(ytitle.c_str()); if (firstx != lastx) fHistogram->GetXaxis()->SetRange(firstx,lastx); @@ -1589,9 +1596,9 @@ void TMultiGraph::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) { char quote = '"'; out<<" "<ClassSaved(TMultiGraph::Class())) + if (gROOT->ClassSaved(TMultiGraph::Class())) out<<" "; - else + else out<<" TMultiGraph *"; out<<"multigraph = new TMultiGraph();"<SetName("<Add(h,h->GetName()); } @@ -513,10 +513,10 @@ void TPrincipal::Clear(Option_t *opt) const Double_t *TPrincipal::GetRow(Int_t row) { if (row >= fNumberOfDataPoints) - return 0; + return nullptr; if (!fStoreData) - return 0; + return nullptr; Int_t index = row * fNumberOfVariables; return &fUserData(index); @@ -622,22 +622,22 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) fHistograms = new TList; // Don't create the histograms if they are already in the TList. - if (makeX && fHistograms->FindObject(Form("%s_x000",name))) + if (makeX && fHistograms->FindObject(TString::Format("%s_x000",name))) makeX = kFALSE; - if (makeD && fHistograms->FindObject(Form("%s_d000",name))) + if (makeD && fHistograms->FindObject(TString::Format("%s_d000",name))) makeD = kFALSE; - if (makeP && fHistograms->FindObject(Form("%s_p000",name))) + if (makeP && fHistograms->FindObject(TString::Format("%s_p000",name))) makeP = kFALSE; - if (makeE && fHistograms->FindObject(Form("%s_e",name))) + if (makeE && fHistograms->FindObject(TString::Format("%s_e",name))) makeE = kFALSE; - if (makeS && fHistograms->FindObject(Form("%s_s",name))) + if (makeS && fHistograms->FindObject(TString::Format("%s_s",name))) makeS = kFALSE; - TH1F **hX = 0; - TH2F **hD = 0; - TH1F **hP = 0; - TH1F *hE = 0; - TH1F *hS = 0; + TH1F **hX = nullptr; + TH2F **hD = nullptr; + TH1F **hP = nullptr; + TH1F *hE = nullptr; + TH1F *hS = nullptr; // Initialize the arrays of histograms needed if (makeX) @@ -650,15 +650,15 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) hP = new TH1F * [fNumberOfVariables]; if (makeE){ - hE = new TH1F(Form("%s_e",name), "Eigenvalues of Covariance matrix", - fNumberOfVariables,0,fNumberOfVariables); + hE = new TH1F(TString::Format("%s_e",name), "Eigenvalues of Covariance matrix", + fNumberOfVariables,0,fNumberOfVariables); hE->SetXTitle("Eigenvalue"); fHistograms->Add(hE); } if (makeS) { - hS = new TH1F(Form("%s_s",name),"E_{N}", - fNumberOfVariables-1,1,fNumberOfVariables); + hS = new TH1F(TString::Format("%s_s",name),"E_{N}", + fNumberOfVariables-1,1,fNumberOfVariables); hS->SetXTitle("N"); hS->SetYTitle("#sum_{i=1}^{M} (x_{i} - x'_{N,i})^{2}"); fHistograms->Add(hS); @@ -671,10 +671,10 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) // histogram. Double_t xlowb = fMeanValues(i) - 4 * fSigmas(i); Double_t xhighb = fMeanValues(i) + 4 * fSigmas(i); - Int_t xbins = fNumberOfDataPoints/100; - hX[i] = new TH1F(Form("%s_x%03d", name, i), - Form("Pattern space, variable %d", i), - xbins,xlowb,xhighb); + Int_t xbins = (fNumberOfDataPoints > 0 && fNumberOfDataPoints < 100 ? 1 : fNumberOfDataPoints/100); + hX[i] = new TH1F(TString::Format("%s_x%03d", name, i), + TString::Format("Pattern space, variable %d", i), + xbins,xlowb,xhighb); hX[i]->SetXTitle(Form("x_{%d}",i)); fHistograms->Add(hX[i]); } @@ -683,15 +683,12 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) // The upper limit below is arbitrary!!! Double_t dlowb = 0; Double_t dhighb = 20; - Int_t dbins = fNumberOfDataPoints/100; - hD[i] = new TH2F(Form("%s_d%03d", name, i), - Form("Distance from pattern to " - "feature space, variable %d", i), - dbins,dlowb,dhighb, - fNumberOfVariables-1, - 1, - fNumberOfVariables); - hD[i]->SetXTitle(Form("|x_{%d} - x'_{%d,N}|/#sigma_{%d}",i,i,i)); + Int_t dbins = (fNumberOfDataPoints > 0 && fNumberOfDataPoints < 100 ? 1 : fNumberOfDataPoints/100); + hD[i] = new TH2F(TString::Format("%s_d%03d", name, i), + TString::Format("Distance from pattern to feature space, variable %d", i), + dbins,dlowb,dhighb, + fNumberOfVariables-1, 1, fNumberOfVariables); + hD[i]->SetXTitle(TString::Format("|x_{%d} - x'_{%d,N}|/#sigma_{%d}",i,i,i)); hD[i]->SetYTitle("N"); fHistograms->Add(hD[i]); } @@ -704,10 +701,10 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) Double_t plowb = -10 * TMath::Sqrt(et); Double_t phighb = -plowb; Int_t pbins = 100; - hP[i] = new TH1F(Form("%s_p%03d", name, i), - Form("Feature space, variable %d", i), - pbins,plowb,phighb); - hP[i]->SetXTitle(Form("p_{%d}",i)); + hP[i] = new TH1F(TString::Format("%s_p%03d", name, i), + TString::Format("Feature space, variable %d", i), + pbins,plowb,phighb); + hP[i]->SetXTitle(TString::Format("p_{%d}",i)); fHistograms->Add(hP[i]); } @@ -726,7 +723,7 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt) return; } - Double_t *x = 0; + Double_t *x = nullptr; Double_t *p = new Double_t[fNumberOfVariables]; Double_t *d = new Double_t[fNumberOfVariables]; for (i = 0; i < fNumberOfDataPoints; i++) { @@ -862,7 +859,7 @@ void TPrincipal::MakeNormalised() void TPrincipal::MakeMethods(const char *classname, Option_t *opt) { - MakeRealCode(Form("%sPCA.cxx", classname), classname, opt); + MakeRealCode(TString::Format("%sPCA.cxx", classname), classname, opt); } @@ -897,9 +894,11 @@ void TPrincipal::MakePrincipals() void TPrincipal::MakeRealCode(const char *filename, const char *classname, Option_t *) { - Bool_t isMethod = (classname[0] == '\0' ? kFALSE : kTRUE); - const char *prefix = (isMethod ? Form("%s::", classname) : ""); - const char *cv_qual = (isMethod ? "" : "static "); + Bool_t isMethod = classname[0] == '\0' ? kFALSE : kTRUE; + TString prefix; + const char *cv_qual = isMethod ? "" : "static "; + if (isMethod) + prefix.Form("%s::", classname); std::ofstream outFile(filename,std::ios::out|std::ios::trunc); if (!outFile) { @@ -1201,7 +1200,7 @@ void TPrincipal::Test(Option_t *) if (!fStoreData) return; - TH1 *pca_s = 0; + TH1 *pca_s = nullptr; if (fHistograms) pca_s = (TH1*)fHistograms->FindObject("pca_s"); if (!pca_s) { Warning("Test", "Couldn't get histogram of square residuals"); diff --git a/hist/hist/src/TProfile.cxx b/hist/hist/src/TProfile.cxx index e60758219d6c5..d35ef6ae3b2df 100644 --- a/hist/hist/src/TProfile.cxx +++ b/hist/hist/src/TProfile.cxx @@ -342,7 +342,7 @@ Int_t TProfile::BufferEmpty(Int_t action) if (nbentries < 0) { if (action == 0) return 0; nbentries = -nbentries; - fBuffer=0; + fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -358,7 +358,7 @@ Int_t TProfile::BufferEmpty(Int_t action) if (fXaxis.GetXmax() <= fXaxis.GetXmin()) { THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this,xmin,xmax); } else { - fBuffer = 0; + fBuffer = nullptr; Int_t keep = fBufferSize; fBufferSize = 0; if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis); if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis); @@ -367,14 +367,14 @@ Int_t TProfile::BufferEmpty(Int_t action) } } - fBuffer = 0; + fBuffer = nullptr; for (Int_t i=0;i 0) { delete [] fBuffer; fBuffer = 0; fBufferSize = 0;} + if (action > 0) { delete [] fBuffer; fBuffer = nullptr; fBufferSize = 0;} else { if (nbentries == (Int_t)fEntries) fBuffer[0] = -nbentries; else fBuffer[0] = 0; @@ -398,7 +398,7 @@ Int_t TProfile::BufferFill(Double_t x, Double_t y, Double_t w) nbentries = -nbentries; fBuffer[0] = nbentries; if (fEntries > 0) { - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -490,7 +490,7 @@ Bool_t TProfile::Divide(const TH1 *h1) //- Loop on bins (including underflows/overflows) Int_t bin; - Double_t *cu1=0, *er1=0, *en1=0; + Double_t *cu1=nullptr, *er1=nullptr, *en1=nullptr; Double_t e0,e1,c12; if (h1->InheritsFrom(TProfile::Class())) { cu1 = p1->GetW(); @@ -784,7 +784,7 @@ void TProfile::FillN(Int_t ntimes, const Double_t *x, const Double_t *y, const D else BufferFill(x[i], y[i], 1.); } // fill the remaining entries if the buffer has been deleted - if (i < ntimes && fBuffer==0) + if (i < ntimes && fBuffer==nullptr) ifirst = i; // start from i else return; @@ -1411,11 +1411,11 @@ TH1 *TProfile::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins) Double_t xmax = fXaxis.GetXmax(); if ((ngroup <= 0) || (ngroup > nbins)) { Error("Rebin", "Illegal value of ngroup=%d",ngroup); - return 0; + return nullptr; } if (!newname && xbins) { Error("Rebin","if xbins is specified, newname must be given"); - return 0; + return nullptr; } Int_t newbins = nbins/ngroup; @@ -1438,7 +1438,7 @@ TH1 *TProfile::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins) Double_t *oldBins = new Double_t[nbins+2]; Double_t *oldCount = new Double_t[nbins+2]; Double_t *oldErrors = new Double_t[nbins+2]; - Double_t *oldBinw2 = (fBinSumw2.fN ? new Double_t[nbins+2] : 0 ); + Double_t *oldBinw2 = (fBinSumw2.fN ? new Double_t[nbins+2] : nullptr ); Int_t bin, i; Double_t *cu1 = GetW(); Double_t *er1 = GetW2(); @@ -1737,7 +1737,7 @@ void TProfile::SetBuffer(Int_t buffersize, Option_t *) if (fBuffer) { BufferEmpty(); delete [] fBuffer; - fBuffer = 0; + fBuffer = nullptr; } if (buffersize <= 0) { fBufferSize = 0; diff --git a/hist/hist/src/TProfile2D.cxx b/hist/hist/src/TProfile2D.cxx index dd57cfe9ee71f..ebf9dcd174ce3 100644 --- a/hist/hist/src/TProfile2D.cxx +++ b/hist/hist/src/TProfile2D.cxx @@ -298,7 +298,7 @@ Int_t TProfile2D::BufferEmpty(Int_t action) if (nbentries < 0) { if (action == 0) return 0; nbentries = -nbentries; - fBuffer=0; + fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -319,7 +319,7 @@ Int_t TProfile2D::BufferEmpty(Int_t action) if (fXaxis.GetXmax() <= fXaxis.GetXmin() || fYaxis.GetXmax() <= fYaxis.GetXmin()) { THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this,xmin,xmax,ymin,ymax); } else { - fBuffer = 0; + fBuffer = nullptr; Int_t keep = fBufferSize; fBufferSize = 0; if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis); if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis); @@ -330,13 +330,13 @@ Int_t TProfile2D::BufferEmpty(Int_t action) } } - fBuffer = 0; + fBuffer = nullptr; for (Int_t i=0;i 0) { delete [] fBuffer; fBuffer = 0; fBufferSize = 0;} + if (action > 0) { delete [] fBuffer; fBuffer = nullptr; fBufferSize = 0;} else { if (nbentries == (Int_t)fEntries) fBuffer[0] = -nbentries; else fBuffer[0] = 0; @@ -363,7 +363,7 @@ Int_t TProfile2D::BufferFill(Double_t x, Double_t y, Double_t z, Double_t w) nbentries = -nbentries; fBuffer[0] = nbentries; if (fEntries > 0) { - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -1301,7 +1301,7 @@ TH2D *TProfile2D::ProjectionXY(const char *name, Option_t *option) const Int_t ny = fYaxis.GetNbins(); const TArrayD *xbins = fXaxis.GetXbins(); const TArrayD *ybins = fYaxis.GetXbins(); - TH2D * h1 = 0; + TH2D * h1 = nullptr; if (xbins->fN == 0 && ybins->fN == 0) { h1 = new TH2D(pname,GetTitle(),nx,fXaxis.GetXmin(),fXaxis.GetXmax(),ny,fYaxis.GetXmin(),fYaxis.GetXmax()); } else if (xbins->fN == 0) { @@ -1410,7 +1410,7 @@ TProfile * TProfile2D::DoProfile(bool onX, const char *name, Int_t firstbin, Int Int_t firstOutBin = outAxis.GetFirst(); Int_t lastOutBin = outAxis.GetLast(); - TProfile * p1 = 0; + TProfile * p1 = nullptr; // case of fixed bins if (bins->fN == 0) { if (originalRange) @@ -1433,13 +1433,13 @@ TProfile * TProfile2D::DoProfile(bool onX, const char *name, Int_t firstbin, Int TH2D * h2dW = ProjectionXY("h2temp-W","W"); TH2D * h2dN = ProjectionXY("h2temp-N","B"); - h2dW->SetDirectory(0); h2dN->SetDirectory(0); + h2dW->SetDirectory(nullptr); h2dN->SetDirectory(nullptr); TString opt1 = (originalRange) ? "o" : ""; TH1D * h1W = (onX) ? h2dW->ProjectionX("h1temp-W",firstbin,lastbin,opt1) : h2dW->ProjectionY("h1temp-W",firstbin,lastbin,opt1); TH1D * h1N = (onX) ? h2dN->ProjectionX("h1temp-N",firstbin,lastbin,opt1) : h2dN->ProjectionY("h1temp-N",firstbin,lastbin,opt1); - h1W->SetDirectory(0); h1N->SetDirectory(0); + h1W->SetDirectory(nullptr); h1N->SetDirectory(nullptr); // fill the bin content @@ -1558,11 +1558,11 @@ TProfile2D * TProfile2D::Rebin2D(Int_t nxgroup ,Int_t nygroup,const char * newna Double_t ymax = fYaxis.GetXmax(); if ((nxgroup <= 0) || (nxgroup > nxbins)) { Error("Rebin", "Illegal value of nxgroup=%d",nxgroup); - return 0; + return nullptr; } if ((nygroup <= 0) || (nygroup > nybins)) { Error("Rebin", "Illegal value of nygroup=%d",nygroup); - return 0; + return nullptr; } Int_t newxbins = nxbins/nxgroup; @@ -1580,7 +1580,7 @@ TProfile2D * TProfile2D::Rebin2D(Int_t nxgroup ,Int_t nygroup,const char * newna Double_t *oldBins = new Double_t[(nxbins+2)*(nybins+2)]; Double_t *oldCount = new Double_t[(nxbins+2)*(nybins+2)]; Double_t *oldErrors = new Double_t[(nxbins+2)*(nybins+2)]; - Double_t *oldBinw2 = (fBinSumw2.fN ? new Double_t[(nxbins+2)*(nybins+2)] : 0 ); + Double_t *oldBinw2 = (fBinSumw2.fN ? new Double_t[(nxbins+2)*(nybins+2)] : nullptr ); Double_t *cu1 = GetW(); Double_t *er1 = GetW2(); Double_t *en1 = GetB(); @@ -1956,7 +1956,7 @@ void TProfile2D::SetBuffer(Int_t buffersize, Option_t *) if (fBuffer) { BufferEmpty(); delete [] fBuffer; - fBuffer = 0; + fBuffer = nullptr; } if (buffersize <= 0) { fBufferSize = 0; diff --git a/hist/hist/src/TProfile2Poly.cxx b/hist/hist/src/TProfile2Poly.cxx index 8c12f079e381c..58f0a5f3c6fe6 100644 --- a/hist/hist/src/TProfile2Poly.cxx +++ b/hist/hist/src/TProfile2Poly.cxx @@ -153,9 +153,9 @@ TProfile2Poly::TProfile2Poly(const char *name, const char *title, Int_t nX, Doub TProfile2PolyBin *TProfile2Poly::CreateBin(TObject *poly) { - if (!poly) return 0; + if (!poly) return nullptr; - if (fBins == 0) { + if (fBins == nullptr) { fBins = new TList(); fBins->SetOwner(); } diff --git a/hist/hist/src/TProfile3D.cxx b/hist/hist/src/TProfile3D.cxx index 7ff283c7d75f7..b6123e6e65b58 100644 --- a/hist/hist/src/TProfile3D.cxx +++ b/hist/hist/src/TProfile3D.cxx @@ -253,7 +253,7 @@ Int_t TProfile3D::BufferEmpty(Int_t action) if (nbentries < 0) { if (action == 0) return 0; nbentries = -nbentries; - fBuffer=0; + fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -279,7 +279,7 @@ Int_t TProfile3D::BufferEmpty(Int_t action) if (fXaxis.GetXmax() <= fXaxis.GetXmin() || fYaxis.GetXmax() <= fYaxis.GetXmin() || fZaxis.GetXmax() <= fZaxis.GetXmin()) { THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this,xmin,xmax,ymin,ymax,zmin,zmax); } else { - fBuffer = 0; + fBuffer = nullptr; Int_t keep = fBufferSize; fBufferSize = 0; if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis); if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis); @@ -292,13 +292,13 @@ Int_t TProfile3D::BufferEmpty(Int_t action) } } - fBuffer = 0; + fBuffer = nullptr; for (Int_t i=0;i 0) { delete [] fBuffer; fBuffer = 0; fBufferSize = 0;} + if (action > 0) { delete [] fBuffer; fBuffer = nullptr; fBufferSize = 0;} else { if (nbentries == (Int_t)fEntries) fBuffer[0] = -nbentries; else fBuffer[0] = 0; @@ -326,7 +326,7 @@ Int_t TProfile3D::BufferFill(Double_t x, Double_t y, Double_t z, Double_t t, Dou nbentries = -nbentries; fBuffer[0] = nbentries; if (fEntries > 0) { - Double_t *buffer = fBuffer; fBuffer=0; + Double_t *buffer = fBuffer; fBuffer=nullptr; Reset("ICES"); // reset without deleting the functions fBuffer = buffer; } @@ -975,14 +975,14 @@ TH3D *TProfile3D::ProjectionXYZ(const char *name, Option_t *option) const if (pname == "_px") { pname = GetName(); pname.Append("_pxyz"); } - TH3D *h1 = 0 ; + TH3D *h1 = nullptr ; if (xbins->fN == 0 && ybins->fN == 0 && zbins->fN == 0) h1 = new TH3D(pname,GetTitle(),nx,fXaxis.GetXmin(),fXaxis.GetXmax(),ny,fYaxis.GetXmin(),fYaxis.GetXmax(),nz,fZaxis.GetXmin(),fZaxis.GetXmax()); else if ( xbins->fN != 0 && ybins->fN != 0 && zbins->fN != 0) h1 = new TH3D(pname,GetTitle(),nx,xbins->GetArray(),ny,ybins->GetArray(), nz,zbins->GetArray() ); else { Error("ProjectionXYZ","Histogram has an axis with variable bins and an axis with fixed bins. This case is not supported - return a null pointer"); - return 0; + return nullptr; } @@ -1080,7 +1080,7 @@ TProfile2D *TProfile3D::DoProjectProfile2D(const char* name, const char * title, Int_t ny = iymax-iymin+1; // Create the projected profiles - TProfile2D *p2 = 0; + TProfile2D *p2 = nullptr; // Create always a new TProfile2D (not as in the case of TH3 projection) const TArrayD *xbins = projX->GetXbins(); @@ -1110,7 +1110,7 @@ TProfile2D *TProfile3D::DoProjectProfile2D(const char* name, const char * title, TH3D * h3dW = ProjectionXYZ("h3temp-W","W"); TH3D * h3dN = ProjectionXYZ("h3temp-N","B"); - h3dW->SetDirectory(0); h3dN->SetDirectory(0); + h3dW->SetDirectory(nullptr); h3dN->SetDirectory(nullptr); // Since no axis range is considered when doing the projection TProfile3D->TH3D // the resulting histogram will have the same axis as the parent one @@ -1141,7 +1141,7 @@ TProfile2D *TProfile3D::DoProjectProfile2D(const char* name, const char * title, TH2D * h2W = TH3::DoProject2D(*h3dW,"htemp-W","",projX_hW, projY_hW, true, originalRange, useUF, useOF); TH2D * h2N = TH3::DoProject2D(*h3dN,"htemp-N","",projX_hN, projY_hN, useWeights, originalRange, useUF, useOF); - h2W->SetDirectory(0); h2N->SetDirectory(0); + h2W->SetDirectory(nullptr); h2N->SetDirectory(nullptr); // fill the bin content @@ -1329,7 +1329,7 @@ void TProfile3D::SetBuffer(Int_t buffersize, Option_t *) if (fBuffer) { BufferEmpty(); delete [] fBuffer; - fBuffer = 0; + fBuffer = nullptr; } if (buffersize <= 0) { fBufferSize = 0; diff --git a/hist/hist/src/TProfileHelper.h b/hist/hist/src/TProfileHelper.h index e1f1f221bc255..8375b4bc2747c 100644 --- a/hist/hist/src/TProfileHelper.h +++ b/hist/hist/src/TProfileHelper.h @@ -633,7 +633,7 @@ void TProfileHelper::LabelsInflate(T* p, Option_t *ax) if (gDebug) Info("LabelsInflate","Inflate label for axis %s of profile %s",ax,p->GetName()); Int_t iaxis = p->AxisChoice(ax); - TAxis *axis = 0; + TAxis *axis = nullptr; if (iaxis == 1) axis = p->GetXaxis(); if (iaxis == 2) axis = p->GetYaxis(); if (iaxis == 3) axis = p->GetZaxis(); diff --git a/hist/hist/src/TSVDUnfold.cxx b/hist/hist/src/TSVDUnfold.cxx index 14ff1bcd1634d..6efd6ebf11082 100644 --- a/hist/hist/src/TSVDUnfold.cxx +++ b/hist/hist/src/TSVDUnfold.cxx @@ -80,16 +80,16 @@ fNdim (0), fDdim (2), fNormalize (kFALSE), fKReg (-1), -fDHist (NULL), -fSVHist (NULL), -fXtau (NULL), -fXinv (NULL), +fDHist (nullptr), +fSVHist (nullptr), +fXtau (nullptr), +fXinv (nullptr), fBdat (bdat), fBini (bini), fXini (xini), fAdet (Adet), -fToyhisto (NULL), -fToymat (NULL), +fToyhisto (nullptr), +fToymat (nullptr), fToyMode (kFALSE), fMatToyMode (kFALSE) { @@ -133,17 +133,17 @@ fNdim (0), fDdim (2), fNormalize (kFALSE), fKReg (-1), -fDHist (NULL), -fSVHist (NULL), -fXtau (NULL), -fXinv (NULL), +fDHist (nullptr), +fSVHist (nullptr), +fXtau (nullptr), +fXinv (nullptr), fBdat (bdat), fBcov (Bcov), fBini (bini), fXini (xini), fAdet (Adet), -fToyhisto (NULL), -fToymat (NULL), +fToyhisto (nullptr), +fToymat (nullptr), fToyMode (kFALSE), fMatToyMode (kFALSE) { @@ -201,37 +201,37 @@ TSVDUnfold::~TSVDUnfold() { if(fToyhisto){ delete fToyhisto; - fToyhisto = 0; + fToyhisto = nullptr; } if(fToymat){ delete fToymat; - fToymat = 0; + fToymat = nullptr; } if(fDHist){ delete fDHist; - fDHist = 0; + fDHist = nullptr; } if(fSVHist){ delete fSVHist; - fSVHist = 0; + fSVHist = nullptr; } if(fXtau){ delete fXtau; - fXtau = 0; + fXtau = nullptr; } if(fXinv){ delete fXinv; - fXinv = 0; + fXinv = nullptr; } if(fBcov){ delete fBcov; - fBcov = 0; + fBcov = nullptr; } } @@ -409,7 +409,7 @@ TH1D* TSVDUnfold::Unfold( Int_t kreg ) TH2D* TSVDUnfold::GetUnfoldCovMatrix( const TH2D* cov, Int_t ntoys, Int_t seed ) { fToyMode = true; - TH1D* unfres = 0; + TH1D* unfres = nullptr; TH2D* unfcov = (TH2D*)fAdet->Clone("unfcovmat"); unfcov->SetTitle("Toy covariance matrix"); for(int i=1; i<=fNdim; i++) @@ -468,7 +468,7 @@ TH2D* TSVDUnfold::GetUnfoldCovMatrix( const TH2D* cov, Int_t ntoys, Int_t seed ) toymean->SetBinContent(j, toymean->GetBinContent(j) + unfres->GetBinContent(j)/ntoys); } delete unfres; - unfres = 0; + unfres = nullptr; } // Reset the random seed @@ -497,7 +497,7 @@ TH2D* TSVDUnfold::GetUnfoldCovMatrix( const TH2D* cov, Int_t ntoys, Int_t seed ) } } delete unfres; - unfres = 0; + unfres = nullptr; } delete Lt; delete toymean; @@ -515,7 +515,7 @@ TH2D* TSVDUnfold::GetUnfoldCovMatrix( const TH2D* cov, Int_t ntoys, Int_t seed ) TH2D* TSVDUnfold::GetAdetCovMatrix( Int_t ntoys, Int_t seed ) { fMatToyMode = true; - TH1D* unfres = 0; + TH1D* unfres = nullptr; TH2D* unfcov = (TH2D*)fAdet->Clone("unfcovmat"); unfcov->SetTitle("Toy covariance matrix"); for(int i=1; i<=fNdim; i++) @@ -544,7 +544,7 @@ TH2D* TSVDUnfold::GetAdetCovMatrix( Int_t ntoys, Int_t seed ) toymean->SetBinContent(j, toymean->GetBinContent(j) + unfres->GetBinContent(j)/ntoys); } delete unfres; - unfres = 0; + unfres = nullptr; } // Reset the random seed @@ -566,7 +566,7 @@ TH2D* TSVDUnfold::GetAdetCovMatrix( Int_t ntoys, Int_t seed ) } } delete unfres; - unfres = 0; + unfres = nullptr; } delete toymean; fMatToyMode = kFALSE; diff --git a/hist/hist/src/TScatter.cxx b/hist/hist/src/TScatter.cxx new file mode 100644 index 0000000000000..e80dd228ae4f4 --- /dev/null +++ b/hist/hist/src/TScatter.cxx @@ -0,0 +1,279 @@ +// @(#)root/hist:$Id$ +// Author: Olivier Couet 18/05/2022 + +/************************************************************************* + * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + + +#include "TROOT.h" +#include "TBuffer.h" +#include "TScatter.h" +#include "TStyle.h" +#include "TMath.h" +#include "TVirtualPad.h" +#include "TH2.h" +#include "TVirtualGraphPainter.h" +#include "strtok.h" + +#include +#include +#include +#include + +ClassImp(TScatter); + + +//////////////////////////////////////////////////////////////////////////////// + +/** \class TScatter + \ingroup Graphs +A TScatter is able to draw four variables scatter plot on a single plot. The two first +variables are the x and y position of the markers, the third is mapped on the current +color map and the fourth on the marker size. + +The following example demonstrates how it works: + +Begin_Macro(source) +../../../tutorials/graphs/scatter.C +End_Macro + +### TScatter's plotting options +TScatter can be drawn with the following options: + +| Option | Description | +|----------|-------------------------------------------------------------------| +| "A" | Produce a new plot with Axis around the graph | + +*/ + + +//////////////////////////////////////////////////////////////////////////////// +/// TScatter default constructor. + +TScatter::TScatter() +{ +} + +//////////////////////////////////////////////////////////////////////////////// +/// TScatter normal constructor. +/// +/// the arrays are preset to zero + +TScatter::TScatter(Int_t n) +{ + fGraph = new TGraph(n); + fNpoints = fGraph->GetN(); + fMaxSize = fGraph->GetMaxSize(); + + fColor = new Double_t[fMaxSize]; + fSize = new Double_t[fMaxSize]; + + memset(fColor, 0, fNpoints * sizeof(Double_t)); + memset(fSize, 0, fNpoints * sizeof(Double_t)); + fMaxMarkerSize = 5.; + fMinMarkerSize = 1.; + fMargin = 0.1; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// TScatter normal constructor. +/// +/// if ex or ey are null, the corresponding arrays are preset to zero + +TScatter::TScatter(Int_t n, const Double_t *x, const Double_t *y, const Double_t *col, const Double_t *size) +{ + fGraph = new TGraph(n, x, y); + fNpoints = fGraph->GetN(); + fMaxSize = fGraph->GetMaxSize(); + + Int_t bufsize = sizeof(Double_t) * fNpoints; + if (col) { + fColor = new Double_t[fMaxSize]; + memcpy(fColor, col, bufsize); + } + if (size) { + fSize = new Double_t[fMaxSize]; + memcpy(fSize, size, bufsize); + } + + fMaxMarkerSize = 5.; + fMinMarkerSize = 1.; + fMargin = 0.1; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// TScatter default destructor. + +TScatter::~TScatter() +{ + delete fGraph; + delete fHistogram; + delete [] fColor; + delete [] fSize; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Compute distance from point px,py to a scatter plot. +/// +/// Compute the closest distance of approach from point px,py to this scatter plot. +/// The distance is computed in pixels units. + +Int_t TScatter::DistancetoPrimitive(Int_t px, Int_t py) +{ + TVirtualGraphPainter *painter = TVirtualGraphPainter::GetPainter(); + if (painter) + return painter->DistancetoPrimitiveHelper(this->GetGraph(), px, py); + return 0; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Execute action corresponding to one event. +/// +/// This member function is called when a graph is clicked with the locator +/// +/// If Left button clicked on one of the line end points, this point +/// follows the cursor until button is released. +/// +/// if Middle button clicked, the line is moved parallel to itself +/// until the button is released. + +void TScatter::ExecuteEvent(Int_t event, Int_t px, Int_t py) +{ + TVirtualGraphPainter *painter = TVirtualGraphPainter::GetPainter(); + if (painter) painter->ExecuteEventHelper(this->GetGraph(), event, px, py); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Returns a pointer to the histogram used to draw the axis + +TH2F *TScatter::GetHistogram() const +{ + if (!fHistogram) { + // do not add the histogram to gDirectory + // use local TDirectory::TContect that will set temporarly gDirectory to a nullptr and + // will avoid that histogram is added in the global directory + TDirectory::TContext ctx(nullptr); + double rwxmin, rwymin, rwxmax, rwymax; + int npt = 50; + fGraph->ComputeRange(rwxmin, rwymin, rwxmax, rwymax); + double dx = (rwxmax-rwxmin)*fMargin; + double dy = (rwymax-rwymin)*fMargin; + auto h = new TH2F(TString::Format("%s_h",GetName()),GetTitle(),npt,rwxmin-dx,rwxmax+dx,npt,rwymin-dy,rwymax+dy); +// h->SetMinimum(rwymin-dy); +// h->SetMaximum(rwymax+dy); + h->SetBit(TH1::kNoStats); + h->SetDirectory(nullptr); + h->Sumw2(kFALSE); + const_cast(this)->fHistogram = h; + } + return fHistogram; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Paint this scatter plot with its current attributes. + +void TScatter::Paint(Option_t *option) +{ + TVirtualGraphPainter *painter = TVirtualGraphPainter::GetPainter(); + if (painter) painter->PaintScatter(this, option); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Print graph and errors values. + +void TScatter::Print(Option_t *) const +{ + Double_t *X = fGraph->GetX(); + Double_t *Y = fGraph->GetY(); + for (Int_t i = 0; i < fNpoints; i++) { + printf("x[%d]=%g, y[%d]=%g", i, X[i], i, Y[i]); + if (fColor) printf(", color[%d]=%g", i, fColor[i]); + if (fSize) printf(", size[%d]=%g", i, fSize[i]); + printf("\n"); + } +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Set the margin around the plot in % + +void TScatter::SetMargin(Double_t margin) +{ + if (fMargin != margin) { + delete fHistogram; + fHistogram = nullptr; + fMargin = margin; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Save primitive as a C++ statement(s) on output stream out + +void TScatter::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/) +{ + char quote = '"'; + out << " " << std::endl; + static Int_t frameNumber = 1000; + frameNumber++; + + Int_t i; + Double_t *X = fGraph->GetX(); + Double_t *Y = fGraph->GetY(); + TString fXName = TString::Format("%s_fx%d",GetName(),frameNumber); + TString fYName = TString::Format("%s_fy%d", GetName(),frameNumber); + TString fColorName = TString::Format("%s_fcolor%d",GetName(),frameNumber); + TString fSizeName = TString::Format("%s_fsize%d",GetName(),frameNumber); + out << " Double_t " << fXName << "[" << fNpoints << "] = {" << std::endl; + for (i = 0; i < fNpoints-1; i++) out << " " << X[i] << "," << std::endl; + out << " " << X[fNpoints-1] << "};" << std::endl; + out << " Double_t " << fYName << "[" << fNpoints << "] = {" << std::endl; + for (i = 0; i < fNpoints-1; i++) out << " " << Y[i] << "," << std::endl; + out << " " << Y[fNpoints-1] << "};" << std::endl; + out << " Double_t " << fColorName << "[" << fNpoints << "] = {" << std::endl; + for (i = 0; i < fNpoints-1; i++) out << " " << fColor[i] << "," << std::endl; + out << " " << fColor[fNpoints-1] << "};" << std::endl; + out << " Double_t " << fSizeName << "[" << fNpoints << "] = {" << std::endl; + for (i = 0; i < fNpoints-1; i++) out << " " << fSize[i] << "," << std::endl; + out << " " << fSize[fNpoints-1] << "};" << std::endl; + + if (gROOT->ClassSaved(TScatter::Class())) + out << " "; + else + out << " TScatter *"; + out << "scat = new TScatter(" << fNpoints << "," << fXName << "," << fYName << "," + << fColorName << "," << fSizeName << ");" << std::endl; + + out << " scat->SetName(" << quote << GetName() << quote << ");" << std::endl; + out << " scat->SetTitle(" << quote << GetTitle() << quote << ");" << std::endl; + out << " scat->SetMargin(" << GetMargin() << ");" << std::endl; + out << " scat->SetMinMarkerSize(" << GetMinMarkerSize() << ");" << std::endl; + out << " scat->SetMaxMarkerSize(" << GetMaxMarkerSize() << ");" << std::endl; + + SaveFillAttributes(out, "scat", 0, 1001); + SaveLineAttributes(out, "scat", 1, 1, 1); + SaveMarkerAttributes(out, "scat", 1, 1, 1); + + if (fHistogram) { + TString hname = fHistogram->GetName(); + fHistogram->SetName(TString::Format("Graph_%s%d", hname.Data(), frameNumber)); + fHistogram->SavePrimitive(out, "nodraw"); + out << " scat->SetHistogram(" << fHistogram->GetName() << ");" << std::endl; + out << " " << std::endl; + fHistogram->SetName(hname); + } + + out << " scat->Draw(" << quote << option << quote << ");" << std::endl; +} diff --git a/hist/hist/src/TSpline.cxx b/hist/hist/src/TSpline.cxx index 6fc5653bc25ff..57c8d169d4532 100644 --- a/hist/hist/src/TSpline.cxx +++ b/hist/hist/src/TSpline.cxx @@ -48,8 +48,8 @@ TSpline::TSpline(const TSpline &sp) : fXmax(sp.fXmax), fNp(sp.fNp), fKstep(sp.fKstep), - fHistogram(0), - fGraph(0), + fHistogram(nullptr), + fGraph(nullptr), fNpx(sp.fNpx) { } @@ -78,8 +78,8 @@ TSpline& TSpline::operator=(const TSpline &sp) fXmax=sp.fXmax; fNp=sp.fNp; fKstep=sp.fKstep; - fHistogram=0; - fGraph=0; + fHistogram=nullptr; + fGraph=nullptr; fNpx=sp.fNpx; } return *this; @@ -153,7 +153,7 @@ void TSpline::Paint(Option_t *option) if (fHistogram) if ((!gPad->GetLogx() && fHistogram->TestBit(TH1::kLogX)) || (gPad->GetLogx() && !fHistogram->TestBit(TH1::kLogX))) - { delete fHistogram; fHistogram = 0;} + { delete fHistogram; fHistogram = nullptr;} if (fHistogram) { //if (xmin != fXmin || xmax != fXmax) @@ -176,7 +176,7 @@ void TSpline::Paint(Option_t *option) fHistogram = new TH1F("Spline",GetTitle(),fNpx,xmin,xmax); } if (!fHistogram) return; - fHistogram->SetDirectory(0); + fHistogram->SetDirectory(nullptr); } for (i=1;i<=fNpx;i++) { xv = fHistogram->GetBinCenter(i); @@ -537,7 +537,7 @@ TSpline3::TSpline3(const TH1 *h, const char *opt, TSpline3::TSpline3(const TSpline3& sp3) : TSpline(sp3), - fPoly(0), + fPoly(nullptr), fValBeg(sp3.fValBeg), fValEnd(sp3.fValEnd), fBegCond(sp3.fBegCond), @@ -555,7 +555,7 @@ TSpline3& TSpline3::operator=(const TSpline3& sp3) { if(this!=&sp3) { TSpline::operator=(sp3); - fPoly= 0; + fPoly= nullptr; if (fNp > 0) fPoly = new TSplinePoly3[fNp]; for (Int_t i=0; iAccessPathName(filename,kWritePermission)) { + if (f == nullptr || gSystem->AccessPathName(filename,kWritePermission)) { Error("SaveAs","Cannot open file:%s\n",filename); return; } @@ -1415,7 +1415,7 @@ TSpline5::TSpline5(const TH1 *h, TSpline5::TSpline5(const TSpline5& sp5) : TSpline(sp5), - fPoly(0) + fPoly(nullptr) { if (fNp > 0) fPoly = new TSplinePoly5[fNp]; for (Int_t i=0; i 0) fPoly = new TSplinePoly5[fNp]; for (Int_t i=0; iAccessPathName(filename,kWritePermission)) { + if (f == nullptr || gSystem->AccessPathName(filename,kWritePermission)) { Error("SaveAs","Cannot open file:%s\n",filename); return; } diff --git a/hist/hist/src/TVirtualFitter.cxx b/hist/hist/src/TVirtualFitter.cxx index b9689f0bd10a8..2f12b7ef14530 100644 --- a/hist/hist/src/TVirtualFitter.cxx +++ b/hist/hist/src/TVirtualFitter.cxx @@ -79,11 +79,11 @@ TVirtualFitter::TVirtualFitter() : fNpoints(0), fPointSize(0), fCacheSize(0), - fCache(0), - fObjectFit(0), - fUserFunc(0), - fMethodCall(0), - fFCN(0) + fCache(nullptr), + fObjectFit(nullptr), + fUserFunc(nullptr), + fMethodCall(nullptr), + fFCN(nullptr) { } @@ -144,11 +144,11 @@ TVirtualFitter::~TVirtualFitter() delete fMethodCall; delete [] fCache; if ( GetGlobalFitter() == this ) { - GetGlobalFitter() = 0; + GetGlobalFitter() = nullptr; GetGlobalMaxPar() = 0; } - fMethodCall = 0; - fFCN = 0; + fMethodCall = nullptr; + fFCN = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -160,7 +160,7 @@ TVirtualFitter *TVirtualFitter::Fitter(TObject *obj, Int_t maxpar) { if (GetGlobalFitter() && maxpar > GetGlobalMaxPar()) { delete GetGlobalFitter(); - GetGlobalFitter() = 0; + GetGlobalFitter() = nullptr; } if (!GetGlobalFitter()) { @@ -168,7 +168,7 @@ TVirtualFitter *TVirtualFitter::Fitter(TObject *obj, Int_t maxpar) if (GetGlobalDefault().Length() == 0) GetGlobalDefault() = gEnv->GetValue("Root.Fitter","Minuit"); if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualFitter",GetGlobalDefault()))) { if (h->LoadPlugin() == -1) - return 0; + return nullptr; GetGlobalFitter() = (TVirtualFitter*) h->ExecPlugin(1, maxpar); GetGlobalMaxPar() = maxpar; } @@ -247,7 +247,7 @@ void TVirtualFitter::SetDefaultFitter(const char *name) ROOT::Math::MinimizerOptions::SetDefaultMinimizer(name,""); if (GetGlobalDefault() == name) return; delete GetGlobalFitter(); - GetGlobalFitter() = 0; + GetGlobalFitter() = nullptr; GetGlobalDefault() = name; } diff --git a/hist/hist/src/TVirtualGraphPainter.cxx b/hist/hist/src/TVirtualGraphPainter.cxx index 49526c4b77938..34f7101344e3a 100644 --- a/hist/hist/src/TVirtualGraphPainter.cxx +++ b/hist/hist/src/TVirtualGraphPainter.cxx @@ -32,7 +32,7 @@ TVirtualGraphPainter *TVirtualGraphPainter::GetPainter() if (!fgPainter) { TPluginHandler *h; if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualGraphPainter"))) { - if (h->LoadPlugin() == -1) return 0; + if (h->LoadPlugin() == -1) return nullptr; fgPainter = (TVirtualGraphPainter*)gROOT->GetClass("TGraphPainter")->New(); } } diff --git a/hist/hist/src/TVirtualHistPainter.cxx b/hist/hist/src/TVirtualHistPainter.cxx index bd880d9eea73a..599e0b08d0d1a 100644 --- a/hist/hist/src/TVirtualHistPainter.cxx +++ b/hist/hist/src/TVirtualHistPainter.cxx @@ -35,12 +35,12 @@ TVirtualHistPainter *TVirtualHistPainter::HistPainter(TH1 *obj) TPluginHandler *h; if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualHistPainter"))) { if (h->LoadPlugin() == -1) - return 0; + return nullptr; TVirtualHistPainter::SetPainter(h->GetClass()); - if (!fgPainter) return 0; + if (!fgPainter) return nullptr; } else { // fgPainter is still null - return 0; + return nullptr; } } diff --git a/hist/hist/src/WrappedTF1.cxx b/hist/hist/src/WrappedTF1.cxx index c0ae5b83f73b8..19bb321c74bc3 100644 --- a/hist/hist/src/WrappedTF1.cxx +++ b/hist/hist/src/WrappedTF1.cxx @@ -49,7 +49,7 @@ namespace ROOT { // init the pointers for CINT //if (fFunc->GetMethodCall() ) fFunc->InitArgs(fX, &fParams.front() ); - if (fFunc->GetMethodCall()) fFunc->InitArgs(fX, 0); + if (fFunc->GetMethodCall()) fFunc->InitArgs(fX, nullptr); // distinguish case of polynomial functions and linear functions if (fFunc->GetNumber() >= 300 && fFunc->GetNumber() < 310) { fLinear = true; @@ -60,7 +60,7 @@ namespace ROOT { int ip = 0; fLinear = true; while (fLinear && ip < fFunc->GetNpar()) { - fLinear &= (fFunc->GetLinearPart(ip) != 0) ; + fLinear &= (fFunc->GetLinearPart(ip) != nullptr) ; ip++; } } @@ -77,7 +77,7 @@ namespace ROOT { //fParams(rhs.fParams) { // copy constructor - fFunc->InitArgs(fX, 0); + fFunc->InitArgs(fX, nullptr); } WrappedTF1 &WrappedTF1::operator = (const WrappedTF1 &rhs) @@ -87,7 +87,7 @@ namespace ROOT { fLinear = rhs.fLinear; fPolynomial = rhs.fPolynomial; fFunc = rhs.fFunc; - fFunc->InitArgs(fX, 0); + fFunc->InitArgs(fX, nullptr); //fParams = rhs.fParams; return *this; } @@ -113,7 +113,7 @@ namespace ROOT { // parameter are passed as non-const in Derivative //double * p = (fParams.size() > 0) ? const_cast( &fParams.front()) : 0; - return fFunc->Derivative(x, (double *) 0, GetDerivPrecision()); + return fFunc->Derivative(x, (double *) nullptr, GetDerivPrecision()); } double WrappedTF1::DoParameterDerivative(double x, const double *p, unsigned int ipar) const @@ -132,7 +132,7 @@ namespace ROOT { } else { // case of general linear function (built in TFormula with ++ ) const TFormula *df = dynamic_cast(fFunc->GetLinearPart(ipar)); - assert(df != 0); + assert(df != nullptr); fX[0] = x; // hack since TFormula::EvalPar is not const return (const_cast(df))->Eval(x) ; // derivatives should not depend on parameters since func is linear diff --git a/hist/hist/test/CMakeLists.txt b/hist/hist/test/CMakeLists.txt index 0d5bac7333c10..1e32eb74c057e 100644 --- a/hist/hist/test/CMakeLists.txt +++ b/hist/hist/test/CMakeLists.txt @@ -17,6 +17,7 @@ ROOT_ADD_GTEST(TGraphMultiErrorsTests TGraphMultiErrorsTests.cxx LIBRARIES Hist ROOT_ADD_GTEST(test_TF123_Moments test_TF123_Moments.cxx LIBRARIES Hist) ROOT_ADD_GTEST(test_THBinIterator test_THBinIterator.cxx LIBRARIES Hist) ROOT_ADD_GTEST(testTMultiGraphGetHistogram test_TMultiGraph_GetHistogram.cxx LIBRARIES Hist Gpad) +ROOT_ADD_GTEST(testTGraphSorting test_TGraph_sorting.cxx LIBRARIES Hist) if(fftw3) ROOT_ADD_GTEST(testTF1 test_tf1.cxx LIBRARIES Hist) @@ -26,3 +27,12 @@ if(clad) ROOT_ADD_GTEST(TFormulaGradientTests TFormulaGradientTests.cxx LIBRARIES Core MathCore Hist) ROOT_ADD_GTEST(TFormulaHessianTests TFormulaHessianTests.cxx LIBRARIES Core MathCore Hist) endif() + +# Regression test for https://github.com/root-project/root/issues/13691 +# The test needs the following to be actually useful: +# - It must be compiled and run as a standalone executable, as it depends on +# gROOT not being initialized yet. +# - It must link to any library that is not in `core`. See the linked issue +# for details. +ROOT_EXECUTABLE(tdirectoryfile_destructor_segfault tdirectoryfile_destructor_segfault.cxx LIBRARIES RIO Hist) +ROOT_ADD_TEST(test-tdirectoryfile_destructor_segfault COMMAND tdirectoryfile_destructor_segfault) diff --git a/hist/hist/test/tdirectoryfile_destructor_segfault.cxx b/hist/hist/test/tdirectoryfile_destructor_segfault.cxx new file mode 100644 index 0000000000000..a1dfb5eb53514 --- /dev/null +++ b/hist/hist/test/tdirectoryfile_destructor_segfault.cxx @@ -0,0 +1,18 @@ +#include "TDirectoryFile.h" + +int main() +{ + // Test against https://github.com/root-project/root/issues/13691 + // At destruction time TDirectoryFile called the destructor of + // TDirectory, thus: + // - inadvertently triggered initialization of gROOT + // - called TDirectory::RecursiveRemove which didn't check for the validity + // of the `fList` data member, which had already been deleted in the + // TDirectoryFile destructor + // + // NOTE: In order for the segfault to actually be triggered, this test needs + // to link against some library that is not in the list of globally ignored + // PCMs (gIgnoredPCMNames in TCling.cxx). The loading of a PCM is what + // actually triggers the call to TDirectory::RecursiveRemove in the end. + TDirectoryFile f{"f", "f"}; +} diff --git a/hist/hist/test/test_TEfficiency.cxx b/hist/hist/test/test_TEfficiency.cxx index 22767f6224ae1..d0cba167d9946 100644 --- a/hist/hist/test/test_TEfficiency.cxx +++ b/hist/hist/test/test_TEfficiency.cxx @@ -24,8 +24,8 @@ bool testTEfficiency_vs_TGA(int nexp = 1000, TEfficiency::EStatOption statOpt = double k = int(cut * n); TH1D *h1 = new TH1D("h1", "h1", 1, 0, 1); TH1D *h2 = new TH1D("h2", "h2", 1, 0, 1); - h1->SetDirectory(0); - h2->SetDirectory(0); + h1->SetDirectory(nullptr); + h2->SetDirectory(nullptr); h1->SetBinContent(1, k); h2->SetBinContent(1, n); diff --git a/hist/hist/test/test_TGraph_sorting.cxx b/hist/hist/test/test_TGraph_sorting.cxx new file mode 100644 index 0000000000000..792b3c9ae2f6f --- /dev/null +++ b/hist/hist/test/test_TGraph_sorting.cxx @@ -0,0 +1,155 @@ +#include "gtest/gtest.h" +#include "TGraph.h" +#include "TGraphErrors.h" +#include "TGraphAsymmErrors.h" +#include "TGraphMultiErrors.h" +#include "TGraphBentErrors.h" + +#include + +TEST(TGraphSortTest, TGraphSortingTest) +{ + const int numEntries = 1000000; + std::vector x(numEntries); + std::vector y(numEntries); + + // Initialize the graph data with unsorted data + for (int i = 0; i < numEntries; i++) { + x[i] = numEntries - i; + y[i] = x[i] * x[i]; + } + + TGraph graph(numEntries, x.data(), y.data()); + + graph.Sort(); + + // Check if the graph x values are sorted + bool isSorted = std::is_sorted(graph.GetX(), graph.GetX() + numEntries); + + ASSERT_TRUE(isSorted); +} + +TEST(TGraphSortTest, TGraphErrorsSortingTest) +{ + const int numEntries = 1000000; + std::vector x(numEntries); + std::vector y(numEntries); + std::vector errors(numEntries); + + // Initialize the graph data with unsorted data + for (int i = 0; i < numEntries; i++) { + x[i] = numEntries - i; + y[i] = x[i] * x[i]; + errors[i] = 1.0 / (i + 1); + } + + TGraphErrors graphErr(numEntries, x.data(), y.data(), errors.data(), errors.data()); + + graphErr.Sort(); + + // Check if the graph x values are sorted + bool isValSorted = std::is_sorted(graphErr.GetX(), graphErr.GetX() + numEntries); + + // Check if the graph errors are sorted based on the sorted values + bool isErrSorted = std::is_sorted(graphErr.GetEX(), graphErr.GetEX() + numEntries); + + ASSERT_TRUE(isValSorted); + ASSERT_TRUE(isErrSorted); +} + +TEST(TGraphSortTest, TGraphAsymmErrorsSortingTest) +{ + const int numEntries = 1000000; + std::vector x(numEntries); + std::vector y(numEntries); + std::vector elow(numEntries); + std::vector ehigh(numEntries); + + // Initialize the graph data with unsorted data + for (int i = 0; i < numEntries; i++) { + x[i] = numEntries - i; + y[i] = x[i] * x[i]; + elow[i] = 1.0 / (i + 1); + ehigh[i] = 2.0 / (i + 1); + + } + + TGraphAsymmErrors graphAsymmErr(numEntries, x.data(), y.data(), elow.data(), ehigh.data(), elow.data(), ehigh.data()); + + graphAsymmErr.Sort(); + + // Check if the graph x values are sorted + bool isValSorted = std::is_sorted(graphAsymmErr.GetX(), graphAsymmErr.GetX() + numEntries); + + // Check if the graph errors are sorted based on the sorted values + bool isErrSorted = std::is_sorted(graphAsymmErr.GetEYlow(), graphAsymmErr.GetEYlow() + numEntries); + + ASSERT_TRUE(isValSorted); + ASSERT_TRUE(isErrSorted); +} + +TEST(TGraphSortTest, TGraphBentErrorsSortingTest) +{ + const int numEntries = 1000000; + std::vector x(numEntries); + std::vector y(numEntries); + std::vector elow(numEntries); + std::vector ehigh(numEntries); + std::vector elowd(numEntries); + std::vector ehighd(numEntries); + + // Initialize the graph data with unsorted data + for (int i = 0; i < numEntries; i++) { + x[i] = numEntries - i; + y[i] = x[i] * x[i]; + elow[i] = 1.0 / (i + 1); + ehigh[i] = 2.0 / (i + 1); + elowd[i] = 3.0 / (i + 1); + ehighd[i] = 0.5 * i; + } + + TGraphBentErrors graphBentErr(numEntries, x.data(), y.data(), elow.data(), ehigh.data(), elowd.data(), ehighd.data(), elow.data(), ehigh.data(), elowd.data(), ehighd.data()); + + graphBentErr.Sort(); + + // Check if the graph x values are sorted + bool isValSorted = std::is_sorted(graphBentErr.GetX(), graphBentErr.GetX() + numEntries); + + // Check if the graph errors are sorted based on the sorted values + bool isErrSorted = std::is_sorted(graphBentErr.GetEXlow(), graphBentErr.GetEXlow() + numEntries); + bool isErrdSorted = std::is_sorted(graphBentErr.GetEYhighd(), graphBentErr.GetEYhighd() + numEntries); + + ASSERT_TRUE(isValSorted); + ASSERT_TRUE(isErrSorted); + ASSERT_FALSE(isErrdSorted); +} + +TEST(TGraphSortTest, TGraphMultiErrorsSortingTest) +{ + const int numEntries = 1000000; + std::vector x(numEntries); + std::vector y(numEntries); + std::vector elow(numEntries); + std::vector ehigh(numEntries); + + // Initialize the graph data with unsorted data + for (int i = 0; i < numEntries; i++) { + x[i] = numEntries - i; + y[i] = x[i] * x[i]; + elow[i] = 1.0 / (i + 1); + ehigh[i] = 2.0 / (i + 1); + } + + TGraphMultiErrors graphMultiErr(numEntries, x.data(), y.data(), elow.data(), ehigh.data(), elow.data(), ehigh.data()); + + graphMultiErr.Sort(); + + // Check if the graph x values are sorted + bool isValSorted = std::is_sorted(graphMultiErr.GetX(), graphMultiErr.GetX() + numEntries); + + // Check if the graph errors are sorted based on the sorted values + bool isErrSorted = std::is_sorted(graphMultiErr.GetEXlow(), graphMultiErr.GetEXlow() + numEntries); + + ASSERT_TRUE(isValSorted); + ASSERT_TRUE(isErrSorted); +} diff --git a/hist/histdrawv7/test/CMakeLists.txt b/hist/histdrawv7/test/CMakeLists.txt index 51de15bb17d4c..76b43e3166827 100644 --- a/hist/histdrawv7/test/CMakeLists.txt +++ b/hist/histdrawv7/test/CMakeLists.txt @@ -4,4 +4,10 @@ # For the licensing terms see $ROOTSYS/LICENSE. # For the list of contributors see $ROOTSYS/README/CREDITS. -ROOT_ADD_UNITTEST_DIR(ROOTHistDraw ROOTGpadv7) +ROOT_ADD_GTEST(drawUnit draw.cxx LIBRARIES ROOTHistDraw) +# On Windows, this test receives "unexpected diagnostic of severity 2000" +# because "pointer was truncated (due a missing dictionary)" and then trying +# to allocate "an object of abstract class type 'RHistImplBase'". +if(NOT MSVC OR win_broken_tests) + ROOT_ADD_GTEST(ioUnit io.cxx LIBRARIES ROOTHistDraw) +endif() diff --git a/hist/histpainter/inc/TGraphPainter.h b/hist/histpainter/inc/TGraphPainter.h index 94dea04709c15..8d360d2116c36 100644 --- a/hist/histpainter/inc/TGraphPainter.h +++ b/hist/histpainter/inc/TGraphPainter.h @@ -26,6 +26,7 @@ class TGraph; class TF1; +class TScatter; class TGraphPainter : public TVirtualGraphPainter { @@ -36,16 +37,16 @@ class TGraphPainter : public TVirtualGraphPainter { ~TGraphPainter() override; void ComputeLogs(Int_t npoints, Int_t opt); - Int_t DistancetoPrimitiveHelper(TGraph *theGraph, Int_t px, Int_t py) override; - void DrawPanelHelper(TGraph *theGraph) override; - void ExecuteEventHelper(TGraph *theGraph, Int_t event, Int_t px, Int_t py) override; - char *GetObjectInfoHelper(TGraph *theGraph, Int_t px, Int_t py) const override; + Int_t DistancetoPrimitiveHelper(TGraph *theGraph, Int_t px, Int_t py) override; + void DrawPanelHelper(TGraph *theGraph) override; + void ExecuteEventHelper(TGraph *theGraph, Int_t event, Int_t px, Int_t py) override; + char *GetObjectInfoHelper(TGraph *theGraph, Int_t px, Int_t py) const override; virtual Int_t GetHighlightPoint(TGraph *theGraph) const; virtual void HighlightPoint(TGraph *theGraph, Int_t hpoint, Int_t distance); virtual void PaintHighlightPoint(TGraph *theGraph, Option_t *option); void PaintHelper(TGraph *theGraph, Option_t *option) override; - void PaintGraph(TGraph *theGraph, Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt) override; - void PaintGrapHist(TGraph *theGraph, Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt) override; + void PaintGraph(TGraph *theGraph, Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt) override; + void PaintGrapHist(TGraph *theGraph, Int_t npoints, const Double_t *x, const Double_t *y, Option_t *chopt) override; void PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option); void PaintGraphMultiErrors(TGraph *theGraph, Option_t *option); void PaintGraphBentErrors(TGraph *theGraph, Option_t *option); @@ -54,17 +55,18 @@ class TGraphPainter : public TVirtualGraphPainter { void PaintGraphQQ(TGraph *theGraph, Option_t *option); void PaintGraphReverse(TGraph *theGraph, Option_t *option); void PaintGraphSimple(TGraph *theGraph, Option_t *option); + void PaintScatter(TScatter *theScatter, Option_t *option) override; void PaintPolyLineHatches(TGraph *theGraph, Int_t n, const Double_t *x, const Double_t *y); void PaintStats(TGraph *theGraph, TF1 *fit) override; - void SetHighlight(TGraph *theGraph) override; + void SetHighlight(TGraph *theGraph) override; void Smooth(TGraph *theGraph, Int_t npoints, Double_t *x, Double_t *y, Int_t drawtype); static void SetMaxPointsPerLine(Int_t maxp=50); protected: - static Int_t fgMaxPointsPerLine; //Number of points per chunks' line when drawing a graph. + static Int_t fgMaxPointsPerLine; ///< Number of points per chunks' line when drawing a graph. - std::vector gxwork, gywork, gxworkl, gyworkl; // buffers for coordinates + std::vector gxwork, gywork, gxworkl, gyworkl; ///< Internal buffers for coordinates. Used for graphs painting. ClassDefOverride(TGraphPainter,0) // TGraph painter }; diff --git a/hist/histpainter/inc/THistPainter.h b/hist/histpainter/inc/THistPainter.h index 5ac6868c1586b..4b8d1107d6481 100644 --- a/hist/histpainter/inc/THistPainter.h +++ b/hist/histpainter/inc/THistPainter.h @@ -65,6 +65,7 @@ class THistPainter : public TVirtualHistPainter { TCutG *fCuts[kMaxCuts]; ///< Pointers to graphical cuts TList *fStack; ///< Pointer to stack of histograms (if any) Int_t fShowProjection; ///< True if a projection must be drawn + Int_t fShowProjection2; ///< True if a second projection must be drawn (when calling SetShowProjectionXY on a TH2) TString fShowOption; ///< Option to draw the projection Int_t fXHighlightBin; ///< X highlight bin Int_t fYHighlightBin; ///< Y highlight bin @@ -139,12 +140,14 @@ class THistPainter : public TVirtualHistPainter { static Int_t ProjectMercator2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab); static Int_t ProjectSinusoidal2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab); static Int_t ProjectParabolic2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab); + static Int_t ProjectMollweide2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab); virtual void RecalculateRange(); void RecursiveRemove(TObject *) override {} void SetHighlight() override; void SetHistogram(TH1 *h) override; void SetStack(TList *stack) override {fStack = stack;} void SetShowProjection(const char *option,Int_t nbins) override; + void SetShowProjectionXY(const char *option,Int_t nbinsY,Int_t nbinsX) override; virtual void ShowProjectionX(Int_t px, Int_t py); virtual void ShowProjectionY(Int_t px, Int_t py); virtual void ShowProjection3(Int_t px, Int_t py); diff --git a/hist/histpainter/inc/TPaletteAxis.h b/hist/histpainter/inc/TPaletteAxis.h index f133add0b7594..291ab3e00f6e3 100644 --- a/hist/histpainter/inc/TPaletteAxis.h +++ b/hist/histpainter/inc/TPaletteAxis.h @@ -37,6 +37,8 @@ class TPaletteAxis : public TPave { TPaletteAxis(); TPaletteAxis(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, TH1 *h); + TPaletteAxis(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, Double_t min, Double_t max); + TPaletteAxis(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, TAxis *ax); TPaletteAxis(const TPaletteAxis &palette); ~TPaletteAxis() override; void Copy(TObject &palette) const override; @@ -52,19 +54,19 @@ class TPaletteAxis : public TPave { void Paint(Option_t *option="") override; void SavePrimitive(std::ostream &out, Option_t *option = "") override; void SetHistogram(TH1* h) {fH = h;} - virtual void SetNdivisions(Int_t ndiv=10) {if (fH) fH->GetZaxis()->SetNdivisions(ndiv);} // *MENU* + virtual void SetNdivisions(Int_t ndiv=10) {if (fH) fH->GetZaxis()->SetNdivisions(ndiv); else fAxis.SetNdivisions(ndiv);} // *MENU* + virtual void SetLabelColor(Int_t color=1) {if (fH) fH->GetZaxis()->SetLabelColor(color); else fAxis.SetLabelColor(color);} // *MENU* + virtual void SetLabelFont(Int_t font=42) {if (fH) fH->GetZaxis()->SetLabelFont(font); else fAxis.SetLabelFont(font);} // *MENU* + virtual void SetLabelOffset(Float_t offset=0.005) {if (fH) fH->GetZaxis()->SetLabelOffset(offset); else fAxis.SetLabelOffset(offset);} // *MENU* + virtual void SetLabelSize(Float_t size=0.035) {if (fH) fH->GetZaxis()->SetLabelSize(size); else fAxis.SetLabelSize(size);} // *MENU* + virtual void SetMaxDigits(Float_t maxdigits=5) {if (fH) fH->GetZaxis()->SetMaxDigits(maxdigits); else fAxis.SetMaxDigits(maxdigits);} // *MENU* + virtual void SetTickLength(Float_t length=0.03) {if (fH) fH->GetZaxis()->SetTickLength(length); else fAxis.SetTickLength(length);} // *MENU* + virtual void SetTitleOffset(Float_t offset=1) {if (fH) fH->GetZaxis()->SetTitleOffset(offset); else fAxis.SetTitleOffset(offset);} // *MENU* + virtual void SetTitleSize(Float_t size=0.035) {if (fH) fH->GetZaxis()->SetTitleSize(size); else fAxis.SetTitleSize(size);} // *MENU* + virtual void SetTitleColor(Int_t color=1) {if (fH) fH->GetZaxis()->SetTitleColor(color); else fAxis.SetTitleColor(color);} // *MENU* + virtual void SetTitleFont(Int_t font=42) {if (fH) fH->GetZaxis()->SetTitleFont(font); else fAxis.SetTitleFont(font);} // *MENU* + virtual void SetTitle(const char *title="") {if (fH) fH->GetZaxis()->SetTitle(title); else fAxis.SetTitle(title);} // *MENU* virtual void SetAxisColor(Int_t color=1, Float_t alpha=1) {if (fH) fH->GetZaxis()->SetAxisColor(color,alpha);} // *MENU* - virtual void SetLabelColor(Int_t color=1) {if (fH) fH->GetZaxis()->SetLabelColor(color);} // *MENU* - virtual void SetLabelFont(Int_t font=42) {if (fH) fH->GetZaxis()->SetLabelFont(font);} // *MENU* - virtual void SetLabelOffset(Float_t offset=0.005) {if (fH) fH->GetZaxis()->SetLabelOffset(offset);} // *MENU* - virtual void SetLabelSize(Float_t size=0.035) {if (fH) fH->GetZaxis()->SetLabelSize(size);} // *MENU* - virtual void SetMaxDigits(Float_t maxdigits=5) {if (fH) fH->GetZaxis()->SetMaxDigits(maxdigits);} // *MENU* - virtual void SetTickLength(Float_t length=0.03) {if (fH) fH->GetZaxis()->SetTickLength(length);} // *MENU* - virtual void SetTitleOffset(Float_t offset=1) {if (fH) fH->GetZaxis()->SetTitleOffset(offset);} // *MENU* - virtual void SetTitleSize(Float_t size=0.035) {if (fH) fH->GetZaxis()->SetTitleSize(size);} // *MENU* - virtual void SetTitleColor(Int_t color=1) {if (fH) fH->GetZaxis()->SetTitleColor(color);} // *MENU* - virtual void SetTitleFont(Int_t font=42) {if (fH) fH->GetZaxis()->SetTitleFont(font);} // *MENU* - virtual void SetTitle(const char *title="") {if (fH) fH->GetZaxis()->SetTitle(title);} // *MENU* void SetLineWidth(Width_t width) override {fAxis.SetLineWidth(width);} // *MENU* virtual void UnZoom(); // *MENU* diff --git a/hist/histpainter/src/TGraph2DPainter.cxx b/hist/histpainter/src/TGraph2DPainter.cxx index 87b7b48aaf049..2cd2050726b4b 100644 --- a/hist/histpainter/src/TGraph2DPainter.cxx +++ b/hist/histpainter/src/TGraph2DPainter.cxx @@ -39,6 +39,9 @@ ClassImp(TGraph2DPainter); TGraph2DPainter paints a TGraphDelaunay using triangles or clouds of points. +See documentation of TGraph2D, TGraph2DErrors and TGraph2DAsymmErrors to get the list of +drawing options for these classes. + */ @@ -47,23 +50,23 @@ TGraph2DPainter paints a TGraphDelaunay using triangles or clouds of points. TGraph2DPainter::TGraph2DPainter() { - fX = 0; - fY = 0; - fZ = 0; - fEXlow = 0; - fEXhigh = 0; - fEYlow = 0; - fEYhigh = 0; - fEZlow = 0; - fEZhigh = 0; - fXN = 0; - fYN = 0; - fPTried = 0; - fNTried = 0; - fMTried = 0; - fGraph2D = 0; - fDelaunay = 0; - fDelaunay2D = 0; + fX = nullptr; + fY = nullptr; + fZ = nullptr; + fEXlow = nullptr; + fEXhigh = nullptr; + fEYlow = nullptr; + fEYhigh = nullptr; + fEZlow = nullptr; + fEZhigh = nullptr; + fXN = nullptr; + fYN = nullptr; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; + fGraph2D = nullptr; + fDelaunay = nullptr; + fDelaunay2D = nullptr; fXmin = 0.; fXmax = 0.; fYmin = 0.; @@ -85,7 +88,7 @@ TGraph2DPainter::TGraph2DPainter() TGraph2DPainter::TGraph2DPainter(TGraphDelaunay *gd) { fDelaunay = gd; - fDelaunay2D = 0; + fDelaunay2D = nullptr; fGraph2D = fDelaunay->GetGraph2D(); fNpoints = fGraph2D->GetN(); fX = fGraph2D->GetX(); @@ -104,15 +107,15 @@ TGraph2DPainter::TGraph2DPainter(TGraphDelaunay *gd) if (fGraph2D->GetEZhigh()) fEZhigh = fGraph2D->GetEZhigh(); else fEZhigh = fGraph2D->GetEZ(); fNdt = 0; - fXN = 0; - fYN = 0; + fXN = nullptr; + fYN = nullptr; fXNmin = 0; fXNmax = 0; fYNmin = 0; fYNmax = 0; - fPTried = 0; - fNTried = 0; - fMTried = 0; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; fXmin = 0.; fXmax = 0.; fYmin = 0.; @@ -126,7 +129,7 @@ TGraph2DPainter::TGraph2DPainter(TGraphDelaunay *gd) TGraph2DPainter::TGraph2DPainter(TGraphDelaunay2D *gd) { - fDelaunay = 0; + fDelaunay = nullptr; fDelaunay2D = gd; fGraph2D = fDelaunay2D->GetGraph2D(); fNpoints = fGraph2D->GetN(); @@ -146,15 +149,15 @@ TGraph2DPainter::TGraph2DPainter(TGraphDelaunay2D *gd) if (fGraph2D->GetEZhigh()) fEZhigh = fGraph2D->GetEZhigh(); else fEZhigh = fGraph2D->GetEZ(); fNdt = 0; - fXN = 0; - fYN = 0; + fXN = nullptr; + fYN = nullptr; fXNmin = 0; fXNmax = 0; fYNmin = 0; fYNmax = 0; - fPTried = 0; - fNTried = 0; - fMTried = 0; + fPTried = nullptr; + fNTried = nullptr; + fMTried = nullptr; fXmin = 0.; fXmax = 0.; fYmin = 0.; @@ -217,13 +220,13 @@ TList *TGraph2DPainter::GetContourList(Double_t contour) zmin = TMath::Log10(zmin); zmax = TMath::Log10(zmax); } else { - return 0; + return nullptr; } } if(contourzmax) { Error("GetContourList", "Contour level (%g) outside the Z scope [%g,%g]", contour,zmin,zmax); - return 0; + return nullptr; } if (!fNdt) FindTriangles(); @@ -1173,13 +1176,16 @@ void TGraph2DPainter::PaintTriangles_old(Option_t *option) fGraph2D->SetLineColor(fGraph2D->GetLineColor()); fGraph2D->TAttLine::Modify(); int lst = fGraph2D->GetLineStyle(); - for (it=0; itGetMinimum(); + Double_t zmax = gCurrentHist->GetMaximum(); + for (it=0; it fXmax) goto endloop; if(fY[t[k]-1] < fYmin || fY[t[k]-1] > fYmax) goto endloop; + if(fZ[t[k]-1] < zmin || fZ[t[k]-1] > zmax) goto endloop; temp1[0] = fX[t[k]-1]; temp1[1] = fY[t[k]-1]; temp1[2] = fZ[t[k]-1]; @@ -1328,6 +1334,8 @@ void TGraph2DPainter::PaintTriangles_new(Option_t *option) fGraph2D->SetLineColor(fGraph2D->GetLineColor()); fGraph2D->TAttLine::Modify(); int lst = fGraph2D->GetLineStyle(); + Double_t zmin = gCurrentHist->GetMinimum(); + Double_t zmax = gCurrentHist->GetMaximum(); for (const auto & it : dist) { p[0] = it.second->idx[0]; p[1] = it.second->idx[1]; @@ -1335,6 +1343,7 @@ void TGraph2DPainter::PaintTriangles_new(Option_t *option) for (Int_t k=0; k<3; k++) { if(fX[p[k]] < fXmin || fX[p[k]] > fXmax) goto endloop; if(fY[p[k]] < fYmin || fY[p[k]] > fYmax) goto endloop; + if(fZ[p[k]] < zmin || fZ[p[k]] > zmax) goto endloop; temp1[0] = fX[p[k]]; temp1[1] = fY[p[k]]; temp1[2] = fZ[p[k]]; diff --git a/hist/histpainter/src/TGraphPainter.cxx b/hist/histpainter/src/TGraphPainter.cxx index bc1128d0dce50..f23f0714043dd 100644 --- a/hist/histpainter/src/TGraphPainter.cxx +++ b/hist/histpainter/src/TGraphPainter.cxx @@ -18,6 +18,7 @@ #include "TCanvas.h" #include "TStyle.h" #include "TH1.h" +#include "TH2.h" #include "TF1.h" #include "TPaveStats.h" #include "TGaxis.h" @@ -27,6 +28,8 @@ #include "TGraphPolargram.h" #include "TGraphPolar.h" #include "TGraphQQ.h" +#include "TScatter.h" +#include "TPaletteAxis.h" #include "TLatex.h" #include "TArrow.h" #include "TFrame.h" @@ -107,7 +110,7 @@ Graphs can be drawn with the following options: | Option | Description | |----------|-------------------------------------------------------------------| -| "A" | Axis are drawn around the graph | +| "A" | Produce a new plot with Axis around the graph | | "I" | Combine with option 'A' it draws invisible axis | | "L" | A simple polyline is drawn | | "F" | A fill area is drawn ('CF' draw a smoothed fill area) | @@ -724,16 +727,6 @@ Int_t TGraphPainter::DistancetoPrimitiveHelper(TGraph *theGraph, Int_t px, Int_t // Somewhere on the graph points? const Int_t big = 9999; const Int_t kMaxDiff = 10; - Int_t puxmin = gPad->XtoAbsPixel(gPad->GetUxmin()); - Int_t puymin = gPad->YtoAbsPixel(gPad->GetUymin()); - Int_t puxmax = gPad->XtoAbsPixel(gPad->GetUxmax()); - Int_t puymax = gPad->YtoAbsPixel(gPad->GetUymax()); - - // return if point is not in the graph area - if (px <= puxmin) return big; - if (py >= puymin) return big; - if (px >= puxmax) return big; - if (py <= puymax) return big; // check if point is near one of the graph points Int_t i, pxp, pyp, d; @@ -785,10 +778,9 @@ Int_t TGraphPainter::DistancetoPrimitiveHelper(TGraph *theGraph, Int_t px, Int_t TList *functions = theGraph->GetListOfFunctions(); TIter next(functions); while ((f = (TObject*) next())) { - Int_t dist; - if (f->InheritsFrom(TF1::Class())) dist = f->DistancetoPrimitive(-px,py); - else dist = f->DistancetoPrimitive(px,py); - if (dist < kMaxDiff) { + if (f->InheritsFrom(TF1::Class())) distance = f->DistancetoPrimitive(-px,py); + else distance = f->DistancetoPrimitive(px,py); + if (distance < kMaxDiff) { gPad->SetSelected(f); return 0; //must be o and not dist in case of TMultiGraph } @@ -810,8 +802,8 @@ void TGraphPainter::DrawPanelHelper(TGraph *theGraph) } TVirtualPadEditor *editor = TVirtualPadEditor::GetPadEditor(); editor->Show(); - gROOT->ProcessLine(Form("((TCanvas*)0x%zx)->Selected((TVirtualPad*)0x%zx,(TObject*)0x%zx,1)", - (size_t)gPad->GetCanvas(), (size_t)gPad, (size_t)theGraph)); + gROOT->ProcessLine(TString::Format("((TCanvas*)0x%zx)->Selected((TVirtualPad*)0x%zx,(TObject*)0x%zx,1)", + (size_t)gPad->GetCanvas(), (size_t)gPad, (size_t)theGraph)); } @@ -1277,9 +1269,10 @@ void TGraphPainter::PaintHelper(TGraph *theGraph, Option_t *option) break; } } + TPaletteAxis *palette = (TPaletteAxis*)functions->FindObject("palette"); + if (palette) palette->Paint(); } if (fit && !theGraph->TestBit(TGraph::kNoStats)) PaintStats(theGraph, fit); - } } @@ -1407,14 +1400,14 @@ void TGraphPainter::PaintGraph(TGraph *theGraph, Int_t npoints, const Double_t * rwxmax = uxmax; npt = 100; if (theNpoints > npt) npt = theNpoints; - TH1F *h = new TH1F(Form("%s_h",GetName()),GetTitle(),npt,rwxmin,rwxmax); + TH1F *h = new TH1F(TString::Format("%s_h",GetName()),GetTitle(),npt,rwxmin,rwxmax); theGraph->SetHistogram(h); if (!theGraph->GetHistogram()) return; theGraph->GetHistogram()->SetMinimum(rwymin); theGraph->GetHistogram()->SetMaximum(rwymax); theGraph->GetHistogram()->GetYaxis()->SetLimits(rwymin,rwymax); theGraph->GetHistogram()->SetBit(TH1::kNoStats); - theGraph->GetHistogram()->SetDirectory(0); + theGraph->GetHistogram()->SetDirectory(nullptr); theGraph->GetHistogram()->Sumw2(kFALSE); theGraph->GetHistogram()->Paint(chopth); // Draw histogram axis, title and grid } else { @@ -1966,8 +1959,9 @@ void TGraphPainter::PaintGrapHist(TGraph *theGraph, Int_t npoints, const Double_ if ((optionHist) || !chopt[0]) { if (!optionRot) { gxwork[0] = wmin; - gywork[0] = TMath::Min(TMath::Max((Double_t)0,gPad->GetUymin()) - ,gPad->GetUymax()); + if (!optionOne) gywork[0] = TMath::Min(TMath::Max((Double_t)0,gPad->GetUymin()) + ,gPad->GetUymax()); + else gywork[0] = gPad->GetUymin(); ywmin = gywork[0]; npt = 2; for (i=first; i<=last;i++) { @@ -2033,7 +2027,8 @@ void TGraphPainter::PaintGrapHist(TGraph *theGraph, Int_t npoints, const Double_ } //endfor (i=first; i<=last;i++) } else { gywork[0] = wmin; - gxwork[0] = TMath::Max((Double_t)0,gPad->GetUxmin()); + if (!optionOne) gxwork[0] = TMath::Max((Double_t)0,gPad->GetUxmin()); + else gxwork[0] = gPad->GetUxmin(); xwmin = gxwork[0]; npt = 2; for (i=first; i<=last;i++) { @@ -2439,8 +2434,6 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) Double_t xb[4], yb[4]; const Int_t kBASEMARKER=8; - Double_t s2x, s2y, symbolsize, sbase; - Double_t x, y, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2, tx, ty; static Float_t cxx[30] = {1.0,1.0,0.5,0.5,1.0,1.0,0.5,0.6,1.0,0.5,0.5,1.0,0.5,0.6,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; static Float_t cyy[30] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.5,0.5,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; Int_t theNpoints = theGraph->GetN(); @@ -2481,6 +2474,12 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) if (strchr(option,'4')) {option3 = kTRUE; option4 = kTRUE;} if (strchr(option,'5')) {option2 = kTRUE; option5 = kTRUE;} + // special flags in case of "reverse plot" and "log scale" + Bool_t xrevlog = kFALSE; + Bool_t yrevlog = kFALSE; + if (strstr(option,"-N")) xrevlog = kTRUE; // along X + if (strstr(option,"-M")) yrevlog = kTRUE; // along Y + if (option3) { xline.resize(2*theNpoints); yline.resize(2*theNpoints); @@ -2506,8 +2505,8 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) box.SetFillColor(theGraph->GetFillColor()); box.SetFillStyle(theGraph->GetFillStyle()); - symbolsize = theGraph->GetMarkerSize(); - sbase = symbolsize*kBASEMARKER; + Double_t symbolsize = theGraph->GetMarkerSize(); + Double_t sbase = symbolsize*kBASEMARKER; Int_t mark = TAttMarker::GetMarkerStyleBase(theGraph->GetMarkerStyle()); Double_t cx = 0; Double_t cy = 0; @@ -2517,17 +2516,21 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) } // Define the offset of the error bars due to the symbol size - s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); - s2y =-gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); - Int_t dxend = Int_t(gStyle->GetEndErrorSize()); - tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); - ty =-gPad->PixeltoY(dxend) + gPad->PixeltoY(0); + Double_t s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); + Double_t s2y = -gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); + Int_t dxend = Int_t(gStyle->GetEndErrorSize()); + Double_t tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); + Double_t ty = -gPad->PixeltoY(dxend) + gPad->PixeltoY(0); Float_t asize = 0.6*symbolsize*kBASEMARKER/gPad->GetWh(); gPad->SetBit(TGraph::kClipFrame, theGraph->TestBit(TGraph::kClipFrame)); + + // loop over all the graph points + Double_t x, y, exl, exh, eyl, eyh, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2; for (Int_t i=0;iXtoPad(theX[i]); y = gPad->YtoPad(theY[i]); + if (!option0) { if (option3) { if (x < gPad->GetUxmin()) x = gPad->GetUxmin(); @@ -2541,15 +2544,52 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) if (y > gPad->GetUymax()) continue; } } - xl1 = x - s2x*cx; - xl2 = gPad->XtoPad(theX[i] - theEXlow[i]); + exl = theEXlow[i]; + exh = theEXhigh[i]; + eyl = theEYlow[i]; + eyh = theEYhigh[i]; + + if (xrevlog) { + xl1 = x + s2x*cx; + xl2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + - exh); + xr1 = x - s2x*cx; + xr2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + + exl); + tx = -tx; + } else { + xl1 = x - s2x*cx; + xl2 = gPad->XtoPad(theX[i] - exl); + xr1 = x + s2x*cx; + xr2 = gPad->XtoPad(theX[i] + exh); + } + + if (yrevlog) { + yup1 = y - s2y*cy; + yup2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + + eyl); + ylow1 = y + s2y*cy; + ylow2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + - eyh); + } else { + yup1 = y + s2y*cy; + yup2 = gPad->YtoPad(theY[i] + eyh); + ylow1 = y - s2y*cy; + ylow2 = gPad->YtoPad(theY[i] - eyl); + } + if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); + if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); // draw the error rectangles if (option2) { - x1b = gPad->XtoPad(theX[i] - theEXlow[i]); - y1b = gPad->YtoPad(theY[i] - theEYlow[i]); - x2b = gPad->XtoPad(theX[i] + theEXhigh[i]); - y2b = gPad->YtoPad(theY[i] + theEYhigh[i]); + x1b = xl2; + y1b = ylow2; + x2b = xr2; + y2b = yup2; if (x1b < gPad->GetUxmin()) x1b = gPad->GetUxmin(); if (x1b > gPad->GetUxmax()) x1b = gPad->GetUxmax(); if (y1b < gPad->GetUymin()) y1b = gPad->GetUymin(); @@ -2567,89 +2607,74 @@ void TGraphPainter::PaintGraphAsymmErrors(TGraph *theGraph, Option_t *option) if (option3) { xline[if1-1] = x; xline[if2-1] = x; - yline[if1-1] = gPad->YtoPad(theY[i] + theEYhigh[i]); - yline[if2-1] = gPad->YtoPad(theY[i] - theEYlow[i]); + yline[if1-1] = yup2; + yline[if2-1] = ylow2; if1++; if2--; continue; } - if (xl1 > xl2) { + if (exl != 0. || exh != 0.) { if (arrowOpt) { - arrow.PaintArrow(xl1,y,xl2,y,asize,arrowOpt); + if (exl != 0.) arrow.PaintArrow(xl1,y,xl2,y,asize,arrowOpt); + if (exh != 0.) arrow.PaintArrow(xr1,y,xr2,y,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(xl1,y,xl2,y); - if (endLines) { - if (braticks) { - xb[0] = xl2+tx; yb[0] = y-ty; - xb[1] = xl2; yb[1] = y-ty; - xb[2] = xl2; yb[2] = y+ty; - xb[3] = xl2+tx; yb[3] = y+ty; - gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(xl2,y-ty,xl2,y+ty); - } + if (!brackets) { + if (exl != 0.) gPad->PaintLine(xl1,y,xl2,y); + if (exh != 0.) gPad->PaintLine(xr1,y,xr2,y); } - } - } - xr1 = x + s2x*cx; - xr2 = gPad->XtoPad(theX[i] + theEXhigh[i]); - if (xr1 < xr2) { - if (arrowOpt) { - arrow.PaintArrow(xr1,y,xr2,y,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(xr1,y,xr2,y); if (endLines) { if (braticks) { - xb[0] = xr2-tx; yb[0] = y-ty; - xb[1] = xr2; yb[1] = y-ty; - xb[2] = xr2; yb[2] = y+ty; - xb[3] = xr2-tx; yb[3] = y+ty; - gPad->PaintPolyLine(4, xb, yb); + if (exl != 0.) { + xb[0] = xl2+tx; yb[0] = y-ty; + xb[1] = xl2; yb[1] = y-ty; + xb[2] = xl2; yb[2] = y+ty; + xb[3] = xl2+tx; yb[3] = y+ty; + gPad->PaintPolyLine(4, xb, yb); + } + if (exh != 0.) { + xb[0] = xr2-tx; yb[0] = y-ty; + xb[1] = xr2; yb[1] = y-ty; + xb[2] = xr2; yb[2] = y+ty; + xb[3] = xr2-tx; yb[3] = y+ty; + gPad->PaintPolyLine(4, xb, yb); + } } else { + gPad->PaintLine(xl2,y-ty,xl2,y+ty); gPad->PaintLine(xr2,y-ty,xr2,y+ty); } } } } - yup1 = y + s2y*cy; - yup2 = gPad->YtoPad(theY[i] + theEYhigh[i]); - if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); - if (yup2 > yup1) { + + if (eyl != 0. || eyh != 0.) { if (arrowOpt) { - arrow.PaintArrow(x,yup1,x,yup2,asize,arrowOpt); + if (eyh != 0.) arrow.PaintArrow(x,yup1,x,yup2,asize,arrowOpt); + if (eyl != 0.) arrow.PaintArrow(x,ylow1,x,ylow2,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(x,yup1,x,yup2); - if (endLines) { - if (braticks) { - xb[0] = x-tx; yb[0] = yup2-ty; - xb[1] = x-tx; yb[1] = yup2; - xb[2] = x+tx; yb[2] = yup2; - xb[3] = x+tx; yb[3] = yup2-ty; - gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(x-tx,yup2,x+tx,yup2); - } + if (!brackets) { + if (eyh != 0.) gPad->PaintLine(x,yup1,x,yup2); + if (eyl != 0.) gPad->PaintLine(x,ylow1,x,ylow2); } - } - } - ylow1 = y - s2y*cy; - ylow2 = gPad->YtoPad(theY[i] - theEYlow[i]); - if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); - if (ylow2 < ylow1) { - if (arrowOpt) { - arrow.PaintArrow(x,ylow1,x,ylow2,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(x,ylow1,x,ylow2); if (endLines) { if (braticks) { - xb[0] = x-tx; yb[0] = ylow2+ty; - xb[1] = x-tx; yb[1] = ylow2; - xb[2] = x+tx; yb[2] = ylow2; - xb[3] = x+tx; yb[3] = ylow2+ty; - gPad->PaintPolyLine(4, xb, yb); + if (eyh != 0.) { + xb[0] = x-tx; yb[0] = yup2-ty; + xb[1] = x-tx; yb[1] = yup2; + xb[2] = x+tx; yb[2] = yup2; + xb[3] = x+tx; yb[3] = yup2-ty; + gPad->PaintPolyLine(4, xb, yb); + } + if (eyl != 0.) { + xb[0] = x-tx; yb[0] = ylow2+ty; + xb[1] = x-tx; yb[1] = ylow2; + xb[2] = x+tx; yb[2] = ylow2; + xb[3] = x+tx; yb[3] = ylow2+ty; + gPad->PaintPolyLine(4, xb, yb); + } } else { - gPad->PaintLine(x-tx,ylow2,x+tx,ylow2); + if (eyh != 0.) gPad->PaintLine(x-tx,yup2,x+tx,yup2); + if (eyl != 0.) gPad->PaintLine(x-tx,ylow2,x+tx,ylow2); } } } @@ -2721,8 +2746,6 @@ void TGraphPainter::PaintGraphMultiErrors(TGraph *theGraph, Option_t *option) Double_t xb[4], yb[4]; const Int_t kBASEMARKER = 8; - Double_t s2x, s2y, symbolsize, sbase; - Double_t x, y, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2, tx, ty; static Float_t cxx[30] = {1.0,1.0,0.5,0.5,1.0,1.0,0.5,0.6,1.0,0.5,0.5,1.0,0.5,0.6,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; static Float_t cyy[30] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.5,0.5,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; Int_t theNpoints = tg->GetN(); @@ -2831,6 +2854,7 @@ void TGraphPainter::PaintGraphMultiErrors(TGraph *theGraph, Option_t *option) Int_t NPointsInside = AnyOption0 ? theNpoints : 0; + Double_t x,y; for (Int_t i = 0; i < theNpoints && !AnyOption0; i++) { x = gPad->XtoPad(theX[i]); y = gPad->YtoPad(theY[i]); @@ -2877,8 +2901,8 @@ void TGraphPainter::PaintGraphMultiErrors(TGraph *theGraph, Option_t *option) box.SetFillColor(tg->GetFillColor()); box.SetFillStyle(tg->GetFillStyle()); - symbolsize = tg->GetMarkerSize(); - sbase = symbolsize * kBASEMARKER; + Double_t symbolsize = tg->GetMarkerSize(); + Double_t sbase = symbolsize * kBASEMARKER; Int_t mark = TAttMarker::GetMarkerStyleBase(tg->GetMarkerStyle()); Double_t cx = 0.; Double_t cy = 0.; @@ -2889,15 +2913,17 @@ void TGraphPainter::PaintGraphMultiErrors(TGraph *theGraph, Option_t *option) } // Define the offset of the error bars due to the symbol size - s2x = gPad->PixeltoX(Int_t(0.5 * sbase)) - gPad->PixeltoX(0); - s2y = -gPad->PixeltoY(Int_t(0.5 * sbase)) + gPad->PixeltoY(0); + Double_t s2x = gPad->PixeltoX(Int_t(0.5 * sbase)) - gPad->PixeltoX(0); + Double_t s2y = -gPad->PixeltoY(Int_t(0.5 * sbase)) + gPad->PixeltoY(0); auto dxend = Int_t(gStyle->GetEndErrorSize()); - tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); - ty = -gPad->PixeltoY(dxend) + gPad->PixeltoY(0); + Double_t tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); + Double_t ty = -gPad->PixeltoY(dxend) + gPad->PixeltoY(0); Float_t asize = 0.6 * symbolsize * kBASEMARKER / gPad->GetWh(); gPad->SetBit(TGraph::kClipFrame, tg->TestBit(TGraph::kClipFrame)); + // loop over all the graph points + Double_t xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2; for (Int_t i = 0; i < theNpoints; i++) { x = gPad->XtoPad(theX[i]); y = gPad->YtoPad(theY[i]); @@ -3143,9 +3169,6 @@ void TGraphPainter::PaintGraphBentErrors(TGraph *theGraph, Option_t *option) Double_t xb[4], yb[4]; const Int_t kBASEMARKER=8; - Double_t s2x, s2y, symbolsize, sbase; - Double_t x, y, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2, tx, ty; - Double_t bxl, bxh, byl, byh; static Float_t cxx[30] = {1.0,1.0,0.5,0.5,1.0,1.0,0.5,0.6,1.0,0.5,0.5,1.0,0.5,0.6,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; static Float_t cyy[30] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.5,0.5,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; Int_t theNpoints = theGraph->GetN(); @@ -3190,6 +3213,12 @@ void TGraphPainter::PaintGraphBentErrors(TGraph *theGraph, Option_t *option) if (strchr(option,'4')) {option3 = kTRUE; option4 = kTRUE;} if (strchr(option,'5')) {option2 = kTRUE; option5 = kTRUE;} + // special flags in case of "reverse plot" and "log scale" + Bool_t xrevlog = kFALSE; + Bool_t yrevlog = kFALSE; + if (strstr(option,"-N")) xrevlog = kTRUE; // along X + if (strstr(option,"-M")) yrevlog = kTRUE; // along Y + if (option3) { xline.resize(2*theNpoints); yline.resize(2*theNpoints); @@ -3215,32 +3244,37 @@ void TGraphPainter::PaintGraphBentErrors(TGraph *theGraph, Option_t *option) box.SetFillColor(theGraph->GetFillColor()); box.SetFillStyle(theGraph->GetFillStyle()); - symbolsize = theGraph->GetMarkerSize(); - sbase = symbolsize*kBASEMARKER; - Int_t mark = TAttMarker::GetMarkerStyleBase(theGraph->GetMarkerStyle()); - Double_t cx = 0; - Double_t cy = 0; + Double_t symbolsize = theGraph->GetMarkerSize(); + Double_t sbase = symbolsize*kBASEMARKER; + Int_t mark = TAttMarker::GetMarkerStyleBase(theGraph->GetMarkerStyle()); + Double_t cx = 0; + Double_t cy = 0; if (mark >= 20 && mark <= 49) { cx = cxx[mark-20]; cy = cyy[mark-20]; } // define the offset of the error bars due to the symbol size - s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); - s2y =-gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); - Int_t dxend = Int_t(gStyle->GetEndErrorSize()); - tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); - ty =-gPad->PixeltoY(dxend) + gPad->PixeltoY(0); + Double_t s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); + Double_t s2y = -gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); + Int_t dxend = Int_t(gStyle->GetEndErrorSize()); + Double_t tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); + Double_t ty = -gPad->PixeltoY(dxend) + gPad->PixeltoY(0); Float_t asize = 0.6*symbolsize*kBASEMARKER/gPad->GetWh(); gPad->SetBit(TGraph::kClipFrame, theGraph->TestBit(TGraph::kClipFrame)); + + // loop over all the graph points + Double_t x, y, exl, exh, eyl, eyh, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2; + Double_t bxl, bxh, byl, byh, bs; for (Int_t i=0;iXtoPad(theX[i]); - y = gPad->YtoPad(theY[i]); + x = gPad->XtoPad(theX[i]); + y = gPad->YtoPad(theY[i]); bxl = gPad->YtoPad(theY[i]+theEXlowd[i]); bxh = gPad->YtoPad(theY[i]+theEXhighd[i]); byl = gPad->XtoPad(theX[i]+theEYlowd[i]); byh = gPad->XtoPad(theX[i]+theEYhighd[i]); + if (!option0) { if (option3) { if (x < gPad->GetUxmin()) x = gPad->GetUxmin(); @@ -3254,13 +3288,67 @@ void TGraphPainter::PaintGraphBentErrors(TGraph *theGraph, Option_t *option) if (y > gPad->GetUymax()) continue; } } + exl = theEXlow[i]; + exh = theEXhigh[i]; + eyl = theEYlow[i]; + eyh = theEYhigh[i]; + + if (xrevlog) { + xl1 = x + s2x*cx; + xl2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + - exh); + xr1 = x - s2x*cx; + xr2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + + exl); + tx = -tx; + byl = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + - theEYlowd[i]); + byh = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + - theEYhighd[i]); + } else { + xl1 = x - s2x*cx; + xl2 = gPad->XtoPad(theX[i] - exl); + xr1 = x + s2x*cx; + xr2 = gPad->XtoPad(theX[i] + exh); + } + + if (yrevlog) { + yup1 = y - s2y*cy; + yup2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + + eyl); + ylow1 = y + s2y*cy; + ylow2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + - eyh); + bxl = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + - theEXlowd[i]); + bxh = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + - theEXhighd[i]); + } else { + yup1 = y + s2y*cy; + yup2 = gPad->YtoPad(theY[i] + eyh); + ylow1 = y - s2y*cy; + ylow2 = gPad->YtoPad(theY[i] - eyl); + } + if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); + if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); + + if (xrevlog) {bs = bxl; bxl = bxh; bxh = bs;} + if (yrevlog) {bs = byl; byl = byh; byh = bs;} // draw the error rectangles if (option2) { - x1b = gPad->XtoPad(theX[i] - theEXlow[i]); - y1b = gPad->YtoPad(theY[i] - theEYlow[i]); - x2b = gPad->XtoPad(theX[i] + theEXhigh[i]); - y2b = gPad->YtoPad(theY[i] + theEYhigh[i]); + x1b = xl2; + y1b = ylow2; + x2b = xr2; + y2b = yup2; if (x1b < gPad->GetUxmin()) x1b = gPad->GetUxmin(); if (x1b > gPad->GetUxmax()) x1b = gPad->GetUxmax(); if (y1b < gPad->GetUymin()) y1b = gPad->GetUymin(); @@ -3278,96 +3366,80 @@ void TGraphPainter::PaintGraphBentErrors(TGraph *theGraph, Option_t *option) if (option3) { xline[if1-1] = byh; xline[if2-1] = byl; - yline[if1-1] = gPad->YtoPad(theY[i] + theEYhigh[i]); - yline[if2-1] = gPad->YtoPad(theY[i] - theEYlow[i]); + yline[if1-1] = yup2; + yline[if2-1] = ylow2; if1++; if2--; continue; } - xl1 = x - s2x*cx; - xl2 = gPad->XtoPad(theX[i] - theEXlow[i]); - if (xl1 > xl2) { + if (exl != 0. || exh != 0.) { if (arrowOpt) { - arrow.PaintArrow(xl1,y,xl2,bxl,asize,arrowOpt); + if (exl != 0.) arrow.PaintArrow(xl1,y,xl2,bxl,asize,arrowOpt); + if (exh != 0.) arrow.PaintArrow(xr1,y,xr2,bxh,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(xl1,y,xl2,bxl); - if (endLines) { - if (braticks) { - xb[0] = xl2+tx; yb[0] = bxl-ty; - xb[1] = xl2; yb[1] = bxl-ty; - xb[2] = xl2; yb[2] = bxl+ty; - xb[3] = xl2+tx; yb[3] = bxl+ty; - gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(xl2,bxl-ty,xl2,bxl+ty); - } + if (!brackets) { + if (exl != 0.) gPad->PaintLine(xl1,y,xl2,bxl); + if (exh != 0.) gPad->PaintLine(xr1,y,xr2,bxh); } - } - } - xr1 = x + s2x*cx; - xr2 = gPad->XtoPad(theX[i] + theEXhigh[i]); - if (xr1 < xr2) { - if (arrowOpt) { - arrow.PaintArrow(xr1,y,xr2,bxh,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(xr1,y,xr2,bxh); if (endLines) { if (braticks) { - xb[0] = xr2-tx; yb[0] = bxh-ty; - xb[1] = xr2; yb[1] = bxh-ty; - xb[2] = xr2; yb[2] = bxh+ty; - xb[3] = xr2-tx; yb[3] = bxh+ty; - gPad->PaintPolyLine(4, xb, yb); + if (exl != 0.) { + xb[0] = xl2+tx; yb[0] = bxl-ty; + xb[1] = xl2; yb[1] = bxl-ty; + xb[2] = xl2; yb[2] = bxl+ty; + xb[3] = xl2+tx; yb[3] = bxl+ty; + gPad->PaintPolyLine(4, xb, yb); + } + if (exh != 0.) { + xb[0] = xr2-tx; yb[0] = bxh-ty; + xb[1] = xr2; yb[1] = bxh-ty; + xb[2] = xr2; yb[2] = bxh+ty; + xb[3] = xr2-tx; yb[3] = bxh+ty; + gPad->PaintPolyLine(4, xb, yb); + } } else { + gPad->PaintLine(xl2,bxl-ty,xl2,bxl+ty); gPad->PaintLine(xr2,bxh-ty,xr2,bxh+ty); } } } } - yup1 = y + s2y*cy; - yup2 = gPad->YtoPad(theY[i] + theEYhigh[i]); - if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); - if (yup2 > yup1) { + + if (eyl != 0. || eyh != 0.) { if (arrowOpt) { - arrow.PaintArrow(x,yup1,byh,yup2,asize,arrowOpt); + if (eyh != 0.) arrow.PaintArrow(x,yup1,byh,yup2,asize,arrowOpt); + if (eyl != 0.) arrow.PaintArrow(x,ylow1,byl,ylow2,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(x,yup1,byh,yup2); - if (endLines) { - if (braticks) { - xb[0] = byh-tx; yb[0] = yup2-ty; - xb[1] = byh-tx; yb[1] = yup2; - xb[2] = byh+tx; yb[2] = yup2; - xb[3] = byh+tx; yb[3] = yup2-ty; - gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(byh-tx,yup2,byh+tx,yup2); - } + if (!brackets) { + if (eyh != 0.) gPad->PaintLine(x,yup1,byh,yup2); + if (eyl != 0.) gPad->PaintLine(x,ylow1,byl,ylow2); } - } - } - ylow1 = y - s2y*cy; - ylow2 = gPad->YtoPad(theY[i] - theEYlow[i]); - if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); - if (ylow2 < ylow1) { - if (arrowOpt) { - arrow.PaintArrow(x,ylow1,byl,ylow2,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(x,ylow1,byl,ylow2); if (endLines) { if (braticks) { - xb[0] = byl-tx; yb[0] = ylow2+ty; - xb[1] = byl-tx; yb[1] = ylow2; - xb[2] = byl+tx; yb[2] = ylow2; - xb[3] = byl+tx; yb[3] = ylow2+ty; - gPad->PaintPolyLine(4, xb, yb); + if (eyh != 0.) { + xb[0] = byh-tx; yb[0] = yup2-ty; + xb[1] = byh-tx; yb[1] = yup2; + xb[2] = byh+tx; yb[2] = yup2; + xb[3] = byh+tx; yb[3] = yup2-ty; + gPad->PaintPolyLine(4, xb, yb); + } + if (eyl != 0.) { + xb[0] = byl-tx; yb[0] = ylow2+ty; + xb[1] = byl-tx; yb[1] = ylow2; + xb[2] = byl+tx; yb[2] = ylow2; + xb[3] = byl+tx; yb[3] = ylow2+ty; + gPad->PaintPolyLine(4, xb, yb); + } } else { - gPad->PaintLine(byl-tx,ylow2,byl+tx,ylow2); + if (eyh != 0.) gPad->PaintLine(byh-tx,yup2,byh+tx,yup2); + if (eyl != 0.) gPad->PaintLine(byl-tx,ylow2,byl+tx,ylow2); } } } } } + if (!brackets && !axis) PaintGraphSimple(theGraph, option); gPad->ResetBit(TGraph::kClipFrame); @@ -3396,8 +3468,6 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) Double_t xb[4], yb[4]; const Int_t kBASEMARKER=8; - Double_t s2x, s2y, symbolsize, sbase; - Double_t x, y, ex, ey, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2, tx, ty; static Float_t cxx[30] = {1.0,1.0,0.5,0.5,1.0,1.0,0.5,0.6,1.0,0.5,0.5,1.0,0.5,0.6,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; static Float_t cyy[30] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.5,0.5,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0}; Int_t theNpoints = theGraph->GetN(); @@ -3436,11 +3506,17 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) if (strchr(option,'4')) {option3 = kTRUE; option4 = kTRUE;} if (strchr(option,'5')) {option2 = kTRUE; option5 = kTRUE;} + // special flags in case of "reverse plot" and "log scale" + Bool_t xrevlog = kFALSE; + Bool_t yrevlog = kFALSE; + if (strstr(option,"-N")) xrevlog = kTRUE; // along X + if (strstr(option,"-M")) yrevlog = kTRUE; // along Y + if (option3) { xline.resize(2*theNpoints); yline.resize(2*theNpoints); if (xline.empty() || yline.empty()) { - Error("Paint", "too many points, out of memory"); + Error("PaintGraphErrors", "too many points, out of memory"); return; } if1 = 1; @@ -3461,28 +3537,32 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) box.SetFillColor(theGraph->GetFillColor()); box.SetFillStyle(theGraph->GetFillStyle()); - symbolsize = theGraph->GetMarkerSize(); - sbase = symbolsize*kBASEMARKER; - Int_t mark = TAttMarker::GetMarkerStyleBase(theGraph->GetMarkerStyle()); - Double_t cx = 0; - Double_t cy = 0; + Double_t symbolsize = theGraph->GetMarkerSize(); + Double_t sbase = symbolsize*kBASEMARKER; + Int_t mark = TAttMarker::GetMarkerStyleBase(theGraph->GetMarkerStyle()); + Double_t cx = 0; + Double_t cy = 0; if (mark >= 20 && mark <= 49) { cx = cxx[mark-20]; cy = cyy[mark-20]; } - // define the offset of the error bars due to the symbol size - s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); - s2y =-gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); - Int_t dxend = Int_t(gStyle->GetEndErrorSize()); - tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); - ty =-gPad->PixeltoY(dxend) + gPad->PixeltoY(0); + // define the offset of the error bars due to the symbol size + Double_t s2x = gPad->PixeltoX(Int_t(0.5*sbase)) - gPad->PixeltoX(0); + Double_t s2y = -gPad->PixeltoY(Int_t(0.5*sbase)) + gPad->PixeltoY(0); + Int_t dxend = Int_t(gStyle->GetEndErrorSize()); + Double_t tx = gPad->PixeltoX(dxend) - gPad->PixeltoX(0); + Double_t ty = -gPad->PixeltoY(dxend) + gPad->PixeltoY(0); Float_t asize = 0.6*symbolsize*kBASEMARKER/gPad->GetWh(); gPad->SetBit(TGraph::kClipFrame, theGraph->TestBit(TGraph::kClipFrame)); + + // loop over all the graph points + Double_t x, y, ex, ey, xl1, xl2, xr1, xr2, yup1, yup2, ylow1, ylow2; for (Int_t i=0;iXtoPad(theX[i]); y = gPad->YtoPad(theY[i]); + if (!option0) { if (option3) { if (x < gPad->GetUxmin()) x = gPad->GetUxmin(); @@ -3499,12 +3579,47 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) ex = theEX[i]; ey = theEY[i]; + if (xrevlog) { + xl1 = x + s2x*cx; + xl2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + - ex); + xr1 = x - s2x*cx; + xr2 = gPad->GetUxmax()+gPad->GetUxmin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theX[i])-gPad->GetUxmax()-gPad->GetUxmin())) + + ex); + tx = -tx; + } else { + xl1 = x - s2x*cx; + xl2 = gPad->XtoPad(theX[i] - ex); + xr1 = x + s2x*cx; + xr2 = gPad->XtoPad(theX[i] + ex); + } + + if (yrevlog) { + yup1 = y - s2y*cy; + yup2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + + ey); + ylow1 = y + s2y*cy; + ylow2 = gPad->GetUymax()+gPad->GetUymin()-TMath::Log10( + TMath::Power(10,-(TMath::Log10(theY[i])-gPad->GetUymax()-gPad->GetUymin())) + - ey); + } else { + yup1 = y + s2y*cy; + yup2 = gPad->YtoPad(theY[i] + ey); + ylow1 = y - s2y*cy; + ylow2 = gPad->YtoPad(theY[i] - ey); + } + if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); + if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); + // draw the error rectangles if (option2) { - x1b = gPad->XtoPad(theX[i] - ex); - y1b = gPad->YtoPad(theY[i] - ey); - x2b = gPad->XtoPad(theX[i] + ex); - y2b = gPad->YtoPad(theY[i] + ey); + x1b = xl2; + x2b = xr2; + y1b = ylow2; + y2b = yup2; if (x1b < gPad->GetUxmin()) x1b = gPad->GetUxmin(); if (x1b > gPad->GetUxmax()) x1b = gPad->GetUxmax(); if (y1b < gPad->GetUymin()) y1b = gPad->GetUymin(); @@ -3522,20 +3637,22 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) if (option3) { xline[if1-1] = x; xline[if2-1] = x; - yline[if1-1] = gPad->YtoPad(theY[i] + ey); - yline[if2-1] = gPad->YtoPad(theY[i] - ey); + yline[if1-1] = yup2; + yline[if2-1] = ylow2; if1++; if2--; continue; } - xl1 = x - s2x*cx; - xl2 = gPad->XtoPad(theX[i] - ex); - if (xl1 > xl2) { + if (ex != 0.) { if (arrowOpt) { arrow.PaintArrow(xl1,y,xl2,y,asize,arrowOpt); + arrow.PaintArrow(xr1,y,xr2,y,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(xl1,y,xl2,y); + if (!brackets) { + gPad->PaintLine(xl1,y,xl2,y); + gPad->PaintLine(xr1,y,xr2,y); + } if (endLines) { if (braticks) { xb[0] = xl2+tx; yb[0] = y-ty; @@ -3543,40 +3660,28 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) xb[2] = xl2; yb[2] = y+ty; xb[3] = xl2+tx; yb[3] = y+ty; gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(xl2,y-ty,xl2,y+ty); - } - } - } - } - xr1 = x + s2x*cx; - xr2 = gPad->XtoPad(theX[i] + ex); - if (xr1 < xr2) { - if (arrowOpt) { - arrow.PaintArrow(xr1,y,xr2,y,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(xr1,y,xr2,y); - if (endLines) { - if (braticks) { xb[0] = xr2-tx; yb[0] = y-ty; xb[1] = xr2; yb[1] = y-ty; xb[2] = xr2; yb[2] = y+ty; xb[3] = xr2-tx; yb[3] = y+ty; gPad->PaintPolyLine(4, xb, yb); } else { + gPad->PaintLine(xl2,y-ty,xl2,y+ty); gPad->PaintLine(xr2,y-ty,xr2,y+ty); } } } } - yup1 = y + s2y*cy; - yup2 = gPad->YtoPad(theY[i] + ey); - if (yup2 > gPad->GetUymax()) yup2 = gPad->GetUymax(); - if (yup2 > yup1) { + + if (ey != 0.) { if (arrowOpt) { arrow.PaintArrow(x,yup1,x,yup2,asize,arrowOpt); + arrow.PaintArrow(x,ylow1,x,ylow2,asize,arrowOpt); } else { - if (!brackets) gPad->PaintLine(x,yup1,x,yup2); + if (!brackets) { + gPad->PaintLine(x,yup1,x,yup2); + gPad->PaintLine(x,ylow1,x,ylow2); + } if (endLines) { if (braticks) { xb[0] = x-tx; yb[0] = yup2-ty; @@ -3584,34 +3689,20 @@ void TGraphPainter::PaintGraphErrors(TGraph *theGraph, Option_t *option) xb[2] = x+tx; yb[2] = yup2; xb[3] = x+tx; yb[3] = yup2-ty; gPad->PaintPolyLine(4, xb, yb); - } else { - gPad->PaintLine(x-tx,yup2,x+tx,yup2); - } - } - } - } - ylow1 = y - s2y*cy; - ylow2 = gPad->YtoPad(theY[i] - ey); - if (ylow2 < gPad->GetUymin()) ylow2 = gPad->GetUymin(); - if (ylow2 < ylow1) { - if (arrowOpt) { - arrow.PaintArrow(x,ylow1,x,ylow2,asize,arrowOpt); - } else { - if (!brackets) gPad->PaintLine(x,ylow1,x,ylow2); - if (endLines) { - if (braticks) { xb[0] = x-tx; yb[0] = ylow2+ty; xb[1] = x-tx; yb[1] = ylow2; xb[2] = x+tx; yb[2] = ylow2; xb[3] = x+tx; yb[3] = ylow2+ty; gPad->PaintPolyLine(4, xb, yb); - } else { + } else { + gPad->PaintLine(x-tx,yup2,x+tx,yup2); gPad->PaintLine(x-tx,ylow2,x+tx,ylow2); } } } } } + if (!brackets && !axis) PaintGraphSimple(theGraph, option); gPad->ResetBit(TGraph::kClipFrame); @@ -3660,7 +3751,7 @@ void TGraphPainter::PaintGraphPolar(TGraph *theGraph, Option_t* options) // Check for existing TGraphPolargram in the Pad if (gPad) { // Existing polargram - if (thePolargram) if (!gPad->FindObject(thePolargram->GetName())) thePolargram=0; + if (thePolargram) if (!gPad->FindObject(thePolargram->GetName())) thePolargram=nullptr; if (!thePolargram) { // Find any other Polargram in the Pad TListIter padObjIter(gPad->GetListOfPrimitives()); @@ -4023,9 +4114,20 @@ void TGraphPainter::PaintGraphReverse(TGraph *theGraph, Option_t *option) theHist->Paint(opth.Data()); } - Int_t N = theGraph->GetN(); - Double_t *X = theGraph->GetX(); - Double_t *Y = theGraph->GetY(); + Int_t N = theGraph->GetN(); + + Double_t *X = theGraph->GetX(); + Double_t *EXhigh = theGraph->GetEXhigh(); + Double_t *EXhighd = theGraph->GetEXhighd(); + Double_t *EXlow = theGraph->GetEXlow(); + Double_t *EXlowd = theGraph->GetEXlowd(); + + Double_t *Y = theGraph->GetY(); + Double_t *EYhigh = theGraph->GetEYhigh(); + Double_t *EYhighd = theGraph->GetEYhighd(); + Double_t *EYlow = theGraph->GetEYlow(); + Double_t *EYlowd = theGraph->GetEYlowd(); + Double_t XA1, XA2, YA1, YA2; if (axis) { XA1 = theGraph->GetXaxis()->GetXmin(); @@ -4041,92 +4143,175 @@ void TGraphPainter::PaintGraphReverse(TGraph *theGraph, Option_t *option) Double_t dX = XA1+XA2; Double_t dY = YA1+YA2; - std::vector newX(N); - std::vector newY(N); + // Create the new reversed graph + TGraph *theReversedGraph = (TGraph*)theGraph->Clone(); + + Double_t *rX = theReversedGraph->GetX(); + Double_t *rEXhigh = theReversedGraph->GetEXhigh(); + Double_t *rEXhighd = theReversedGraph->GetEXhighd(); + Double_t *rEXlow = theReversedGraph->GetEXlow(); + Double_t *rEXlowd = theReversedGraph->GetEXlowd(); + + Double_t *rY = theReversedGraph->GetY(); + Double_t *rEYhigh = theReversedGraph->GetEYhigh(); + Double_t *rEYhighd = theReversedGraph->GetEYhighd(); + Double_t *rEYlow = theReversedGraph->GetEYlow(); + Double_t *rEYlowd = theReversedGraph->GetEYlowd(); + theReversedGraph->SetMarkerStyle(theGraph->GetMarkerStyle()); + theReversedGraph->SetMarkerColor(theGraph->GetMarkerColor()); + theReversedGraph->SetLineStyle(theGraph->GetLineStyle()); + theReversedGraph->SetLineColor(theGraph->GetLineColor()); + + Int_t i; // loop index + + // Reserve the TGraph along the X axis if (lrx) { opt.ReplaceAll("rx", ""); if (axis) { + // Reverse the X axis Double_t GL = 0.; theHist->GetXaxis()->SetTickLength(0.); theHist->GetXaxis()->SetLabelOffset(999.); - - // Redraw the new X axis gPad->Update(); TString optax = "-SDH"; if (gPad->GetGridx()) { - GL = (YA2 - YA1) / (gPad->GetY2() - gPad->GetY1()); + if (gPad->GetLogy()) { + GL = (TMath::Log10(YA2) - TMath::Log10(YA1)) / (gPad->GetY2() - gPad->GetY1()); + } else { + GL = (YA2 - YA1) / (gPad->GetY2() - gPad->GetY1()); + } optax.Append("W"); } Double_t ypos; if (lxp) ypos = gPad->GetUymax(); else ypos = gPad->GetUymin(); - auto *theNewAxis = new TGaxis(gPad->GetUxmax(), - ypos, - gPad->GetUxmin(), - ypos, - theGraph->GetXaxis()->GetXmin(), - theGraph->GetXaxis()->GetXmax(), - theHist->GetNdivisions("X"), - optax.Data(), -GL); - theNewAxis->SetLabelFont(theGraph->GetXaxis()->GetLabelFont()); - theNewAxis->SetLabelSize(theGraph->GetXaxis()->GetLabelSize()); - theNewAxis->SetLabelColor(theGraph->GetXaxis()->GetLabelColor()); - theNewAxis->SetTickLength(TLX); - theNewAxis->SetLabelOffset(LOX - theGraph->GetXaxis()->GetLabelSize()); - theNewAxis->Paint(); + if (gPad->GetLogy()) ypos = TMath::Power(10,ypos); + TGaxis *theReversedXaxis; + if (gPad->GetLogx()) { + optax.Append("G"); + theReversedXaxis = new TGaxis(TMath::Power(10,gPad->GetUxmax()), + ypos, + TMath::Power(10,gPad->GetUxmin()), + ypos, + theGraph->GetXaxis()->GetXmin(), + theGraph->GetXaxis()->GetXmax(), + theHist->GetNdivisions("X"), + optax.Data(), -GL); + if (theHist->GetXaxis()->GetMoreLogLabels()) theReversedXaxis->SetMoreLogLabels(); + theReversedXaxis->SetLabelOffset(LOX + theGraph->GetXaxis()->GetLabelSize()); + } else { + theReversedXaxis = new TGaxis(gPad->GetUxmax(), + ypos, + gPad->GetUxmin(), + ypos, + theGraph->GetXaxis()->GetXmin(), + theGraph->GetXaxis()->GetXmax(), + theHist->GetNdivisions("X"), + optax.Data(), -GL); + theReversedXaxis->SetLabelOffset(LOX - theGraph->GetXaxis()->GetLabelSize()); + } + theReversedXaxis->SetLabelFont(theGraph->GetXaxis()->GetLabelFont()); + theReversedXaxis->SetLabelSize(theGraph->GetXaxis()->GetLabelSize()); + theReversedXaxis->SetLabelColor(theGraph->GetXaxis()->GetLabelColor()); + theReversedXaxis->SetTickLength(TLX); + theReversedXaxis->Paint(); } + // Reverse X coordinates - for (Int_t i=0; iGetLogx()) { + for (i=0; iGetUxmax()+gPad->GetUxmin()-TMath::Log10(X[i])); + opt.Append("-N"); + } else { + for (i=0; iUpdate(); TString optax = "-SDH"; - if (gPad->GetGridy()) { - GL = (XA2 - XA1) / (gPad->GetX2() - gPad->GetX1()); + if (gPad->GetLogx()) { + GL = (TMath::Log10(XA2) - TMath::Log10(XA1)) / (gPad->GetX2() - gPad->GetX1()); + } else { + GL = (XA2 - XA1) / (gPad->GetX2() - gPad->GetX1()); + } optax.Append("W"); } Double_t xpos; if (lyp) xpos = gPad->GetUxmax(); else xpos = gPad->GetUxmin(); - auto *theNewAxis = new TGaxis(xpos, - gPad->GetUymax(), - xpos, - gPad->GetUymin(), - theGraph->GetYaxis()->GetXmin(), - theGraph->GetYaxis()->GetXmax(), - theHist->GetNdivisions("Y"), - optax.Data(), GL); - theNewAxis->SetLabelFont(theGraph->GetYaxis()->GetLabelFont()); - theNewAxis->SetLabelSize(theGraph->GetYaxis()->GetLabelSize()); - theNewAxis->SetLabelColor(theGraph->GetYaxis()->GetLabelColor()); - theNewAxis->SetTickLength(-TLY); - theNewAxis->SetLabelOffset(LOY-TLY); - theNewAxis->Paint(); + if (gPad->GetLogx()) xpos = TMath::Power(10,xpos); + TGaxis *theReversedYaxis; + if (gPad->GetLogy()) { + optax.Append("G"); + theReversedYaxis = new TGaxis(xpos, + TMath::Power(10,gPad->GetUymax()), + xpos, + TMath::Power(10,gPad->GetUymin()), + theGraph->GetYaxis()->GetXmin(), + theGraph->GetYaxis()->GetXmax(), + theHist->GetNdivisions("Y"), + optax.Data(), GL); + if (theHist->GetYaxis()->GetMoreLogLabels()) theReversedYaxis->SetMoreLogLabels(); + } else { + theReversedYaxis = new TGaxis(xpos, + gPad->GetUymax(), + xpos, + gPad->GetUymin(), + theGraph->GetYaxis()->GetXmin(), + theGraph->GetYaxis()->GetXmax(), + theHist->GetNdivisions("Y"), + optax.Data(), GL); + } + theReversedYaxis->SetLabelFont(theGraph->GetYaxis()->GetLabelFont()); + theReversedYaxis->SetLabelSize(theGraph->GetYaxis()->GetLabelSize()); + theReversedYaxis->SetLabelColor(theGraph->GetYaxis()->GetLabelColor()); + theReversedYaxis->SetTickLength(-TLY); + theReversedYaxis->SetLabelOffset(LOY-TLY); + theReversedYaxis->Paint(); } + // Reverse Y coordinates - for (Int_t i=0; iGetLogy()) { + for (i=0; iGetUymax()+gPad->GetUymin()-TMath::Log10(Y[i])); + opt.Append("-M"); + } else { + for (i=0; iClone(); - for (Int_t i=0; iSetPoint(i, newX[i], newY[i]); - theNewGraph->SetMarkerStyle(theGraph->GetMarkerStyle()); - theNewGraph->SetMarkerColor(theGraph->GetMarkerColor()); - theNewGraph->SetLineStyle(theGraph->GetLineStyle()); - theNewGraph->SetLineColor(theGraph->GetLineColor()); + if (lrx) { + if (rEYlowd) for (i=0; iGetXaxis()->SetLabelOffset(LOX); theHist->GetXaxis()->SetTickLength(TLX); @@ -4137,6 +4322,188 @@ void TGraphPainter::PaintGraphReverse(TGraph *theGraph, Option_t *option) } +//////////////////////////////////////////////////////////////////////////////// +/// Paint a scatter plot + +void TGraphPainter::PaintScatter(TScatter *theScatter, Option_t* chopt) +{ + + Int_t optionAxis; + + TString opt = chopt; + opt.ToUpper(); + + if (opt.Contains("A")) optionAxis = 1; else optionAxis = 0; + + double *theX = theScatter->GetGraph()->GetX(); + double *theY = theScatter->GetGraph()->GetY(); + int n = theScatter->GetGraph()->GetN(); + double *theColor = theScatter->GetColor(); + double *theSize = theScatter->GetSize(); + double MinMarkerSize = theScatter->GetMinMarkerSize(); + double MaxMarkerSize = theScatter->GetMaxMarkerSize(); + + double minx = DBL_MAX; + double maxx = -DBL_MAX; + double miny = DBL_MAX; + double maxy = -DBL_MAX; + double minc = DBL_MAX; + double maxc = -DBL_MAX; + double mins = DBL_MAX; + double maxs = -DBL_MAX; + for (int i=0; iGetHistogram(); + if (optionAxis) h->Paint(" "); + + // Define and paint palette + if (theColor) { + TPaletteAxis *palette; + TList *functions = theScatter->GetGraph()->GetListOfFunctions(); + palette = (TPaletteAxis*)functions->FindObject("palette"); + TView *view = gPad->GetView(); + if (palette) { + if (view) { + if (!palette->TestBit(TPaletteAxis::kHasView)) { + functions->Remove(palette); + delete palette; palette = nullptr; + } + } else { + if (palette->TestBit(TPaletteAxis::kHasView)) { + functions->Remove(palette); + delete palette; palette = nullptr; + } + } + } + if (!palette) { + Double_t xup = gPad->GetUxmax(); + Double_t x2 = gPad->PadtoX(gPad->GetX2()); + Double_t ymin = gPad->PadtoY(gPad->GetUymin()); + Double_t ymax = gPad->PadtoY(gPad->GetUymax()); + Double_t xr = 0.05*(gPad->GetX2() - gPad->GetX1()); + Double_t xmin = gPad->PadtoX(xup +0.1*xr); + Double_t xmax = gPad->PadtoX(xup + xr); + if (xmax > x2) xmax = gPad->PadtoX(gPad->GetX2()-0.01*xr); + palette = new TPaletteAxis(xmin,ymin,xmax,ymax,minc,maxc); + palette->SetLabelColor(h->GetLabelColor()); + palette->SetLabelFont(h->GetLabelFont()); + palette->SetLabelOffset(h->GetLabelOffset()); + palette->SetLabelSize(h->GetLabelSize()); + palette->SetTitleOffset(h->GetTitleOffset()); + palette->SetTitleSize(h->GetTitleSize()); + palette->SetNdivisions(h->GetNdivisions()); + functions->AddFirst(palette); + } + if (palette) palette->Paint(); + } + + // Draw markers + auto nbcol = gStyle->GetNumberOfColors(); + int logx = gPad->GetLogx(); + int logy = gPad->GetLogy(); + int logz = gPad->GetLogz(); + if (theColor && logz) { + if (minc>0) minc = log10(minc); + if (maxc>0) maxc = log10(maxc); + } + theScatter->SetMarkerColor(theScatter->GetMarkerColor()); + theScatter->TAttMarker::Modify(); + double x,y,c,ms; + int nc; + for (int i=0; i0) c = log10(theColor[i]); + else continue; + } else { + c = theColor[i]; + } + nc = TMath::Nint(((c-minc)/(maxc-minc))*(nbcol-1)); + if (nc > nbcol-1) nc = nbcol-1; + theScatter->SetMarkerColor(gStyle->GetColorPalette(nc)); + } + if (theSize) { + ms = (MaxMarkerSize-MinMarkerSize)*((theSize[i]-mins)/(maxs-mins))+MinMarkerSize; + theScatter->SetMarkerSize(ms); + } + if (theColor || theSize) theScatter->TAttMarker::Modify(); + if (logx) { + if (theX[i]>0) x = log10(theX[i]); + else break; + } else { + x = theX[i]; + } + if (logy) { + if (theY[i]>0) y = log10(theY[i]); + else break; + } else { + y = theY[i]; + } + gPad->PaintPolyMarker(1,&x,&y); + } +} + + //////////////////////////////////////////////////////////////////////////////// /// Paint a simple graph, without errors bars. @@ -4393,7 +4760,7 @@ void TGraphPainter::PaintStats(TGraph *theGraph, TF1 *fit) if (stats) dofit = stats->GetOptFit(); else dofit = gStyle->GetOptFit(); - if (!dofit) fit = 0; + if (!dofit) fit = nullptr; if (!fit) return; if (dofit == 1) dofit = 111; Int_t nlines = 0; @@ -4442,11 +4809,11 @@ void TGraphPainter::PaintStats(TGraph *theGraph, TF1 *fit) char textstats[50]; Int_t ndf = fit->GetNDF(); snprintf(textstats,50,"#chi^{2} / ndf = %s%s / %d","%",stats->GetFitFormat(),ndf); - snprintf(t,64,textstats,(Float_t)fit->GetChisquare()); + snprintf(t,64,textstats,fit->GetChisquare()); if (print_fchi2) stats->AddText(t); if (print_fprob) { snprintf(textstats,50,"Prob = %s%s","%",stats->GetFitFormat()); - snprintf(t,64,textstats,(Float_t)TMath::Prob(fit->GetChisquare(),ndf)); + snprintf(t,64,textstats,TMath::Prob(fit->GetChisquare(),ndf)); stats->AddText(t); } if (print_fval || print_ferrors) { @@ -4456,11 +4823,11 @@ void TGraphPainter::PaintStats(TGraph *theGraph, TF1 *fit) if (print_fval < 2 && parmin*parmax != 0 && parmin >= parmax) continue; if (print_ferrors) { snprintf(textstats,50,"%-8s = %s%s #pm %s%s ",fit->GetParName(ipar),"%",stats->GetFitFormat(),"%",stats->GetFitFormat()); - snprintf(t,64,textstats,(Float_t)fit->GetParameter(ipar) - ,(Float_t)fit->GetParError(ipar)); + snprintf(t,64,textstats,fit->GetParameter(ipar) + ,fit->GetParError(ipar)); } else { snprintf(textstats,50,"%-8s = %s%s ",fit->GetParName(ipar),"%",stats->GetFitFormat()); - snprintf(t,64,textstats,(Float_t)fit->GetParameter(ipar)); + snprintf(t,64,textstats,fit->GetParameter(ipar)); } t[63] = 0; stats->AddText(t); diff --git a/hist/histpainter/src/THistPainter.cxx b/hist/histpainter/src/THistPainter.cxx index 966554a9f2fc4..f13c147cf75c2 100644 --- a/hist/histpainter/src/THistPainter.cxx +++ b/hist/histpainter/src/THistPainter.cxx @@ -45,6 +45,7 @@ #include "TGaxis.h" #include "TColor.h" #include "TPainter3dAlgorithms.h" +#include "TGraph2D.h" #include "TGraph2DPainter.h" #include "TGraphDelaunay2D.h" #include "TView.h" @@ -89,10 +90,10 @@ - [The error bars options](\ref HP09) - [The bar chart option](\ref HP100) - [The "BAR" and "HBAR" options](\ref HP10) -- [The SCATter plot option (default for 2D histograms)](\ref HP11) +- [The SCATter plot option](\ref HP11) - [The ARRow option](\ref HP12) - [The BOX option](\ref HP13) -- [The COLor option](\ref HP14) +- [The COLor option (default for 2D and 3D histograms)](\ref HP14) - [The CANDLE and VIOLIN options](\ref HP140) - [The CANDLE option](\ref HP140a) - [The VIOLIN option](\ref HP140b) @@ -237,7 +238,7 @@ using `TH1::GetOption`: | "LEGO3" | Draw a lego plot with hidden surface removal, like LEGO1 but the border lines of each lego-bar are not drawn.| | "LEGO4" | Draw a lego plot with hidden surface removal, like LEGO1 but without the shadow effect on each lego-bar.| | "TEXT" | Draw bin contents as text (format set via `gStyle->SetPaintTextFormat`).| -| "TEXTnn" | Draw bin contents as text at angle nn (0 < nn < 90). | +| "TEXTnn" | Draw bin contents as text at angle nn (0 < nn <= 90). | | "X+" | The X-axis is drawn on the top side of the plot. | | "Y+" | The Y-axis is drawn on the right side of the plot. | | "MIN0" | Set minimum value for the Y axis to 0, equivalent to gStyle->SetHistMinimumZero(). | @@ -276,15 +277,15 @@ using `TH1::GetOption`: | Option | Description | |--------------|------------------------------------------------------------------| -| " " | Default (scatter plot).| +| " " | Default (color plot).| | "ARR" | Arrow mode. Shows gradient between adjacent cells.| -| "BOX" | A box is drawn for each cell with surface proportional to the content's absolute value. A negative content is marked with a X.| +| "BOX" | A box is drawn for each cell with surface proportional to the content's absolute value. A negative content is marked with a X. | | "BOX1" | A button is drawn for each cell with surface proportional to content's absolute value. A sunken button is drawn for negative values a raised one for positive.| -| "COL" | A box is drawn for each cell with a color scale varying with contents. All the none empty bins are painted. Empty bins are not painted unless some bins have a negative content because in that case the null bins might be not empty. `TProfile2D` histograms are handled differently because, for this type of 2D histograms, it is possible to know if an empty bin has been filled or not. So even if all the bins' contents are positive some empty bins might be painted. And vice versa, if some bins have a negative content some empty bins might be not painted.| +| "COL" | A box is drawn for each cell with a color scale varying with contents. All the none empty bins are painted. Empty bins are not painted unless some bins have a negative content because in that case the null bins might be not empty. `TProfile2D` histograms are handled differently because, for this type of 2D histograms, it is possible to know if an empty bin has been filled or not. So even if all the bins' contents are positive some empty bins might be painted. And vice versa, if some bins have a negative content some empty bins might be not painted (default).| | "COLZ" | Same as "COL". In addition the color palette is also drawn.| | "COL2" | Alternative rendering algorithm to "COL". Can significantly improve rendering performance for large, non-sparse 2-D histograms.| | "COLZ2" | Same as "COL2". In addition the color palette is also drawn.| -| "Z CJUST" | In combination with colored options "COL","CONT0" etc: Justify labels in the color palette at color boudaries. For more details see `TPaletteAxis`| +| "Z CJUST" | In combination with colored options "COL","CONT0" etc: Justify labels in the color palette at color boundaries. For more details see `TPaletteAxis`| | "CANDLE" | Draw a candle plot along X axis.| | "CANDLEX" | Same as "CANDLE".| | "CANDLEY" | Draw a candle plot along Y axis.| @@ -318,11 +319,12 @@ using `TH1::GetOption`: | "MERCATOR" | Draw a contour via an Mercator projection.| | "SINUSOIDAL" | Draw a contour via an Sinusoidal projection.| | "PARABOLIC" | Draw a contour via an Parabolic projection.| +| "MOLLWEIDE" | Draw a contour via an Mollweide projection.| | "LEGO9" | Draw the 3D axis only. Mainly needed for internal use | | "FB" | With LEGO or SURFACE, suppress the Front-Box.| | "BB" | With LEGO or SURFACE, suppress the Back-Box.| | "A" | With LEGO or SURFACE, suppress the axis.| -| "SCAT" | Draw a scatter-plot (default).| +| "SCAT" | Draw a scatter-plot (deprecated option).| | "[cutg]" | Draw only the sub-range selected by the TCutG named "cutg".| @@ -331,7 +333,7 @@ using `TH1::GetOption`: | Option | Description | |----------|-------------------------------------------------------------------| -| " " | Default (scatter plot).| +| " " | Default (color plot).| | "ISO" | Draw a Gouraud shaded 3d iso surface through a 3d histogram. It paints one surface at the value computed as follow: `SumOfWeights/(NbinsX*NbinsY*NbinsZ)`.| | "BOX" | Draw a for each cell with volume proportional to the content's absolute value. An hidden line removal algorithm is used| | "BOX1" | Same as BOX but an hidden surface removal algorithm is used| @@ -833,7 +835,11 @@ the option `SAME`. They allow to plot the histograms next to each other. \anchor HP11 -### The SCATter plot option (default for 2D histograms) +### The SCATter plot option + +\attention +Use of option `SCAT` has been deprecated. It was the default drawing option for 2D and +3D histograms. The new default option is `COL` (heat-map). For each cell (i,j) a number of points proportional to the cell content is @@ -1023,11 +1029,10 @@ End_Macro \anchor HP14 -### The COLor option - +### The COLor option (default for 2D histograms) -For each cell (i,j) a box is drawn with a color proportional to the cell -content. +The magnitude of individual cell (i,j) is represented as a color picked in the current color palette. +This data visualization technique is often called a heat map (or heat-map). The color table used is defined in the current style. @@ -1633,7 +1638,7 @@ By default the format `g` is used. This format can be redefined by calling `gStyle->SetPaintTextFormat()`. It is also possible to use `TEXTnn` in order to draw the text with -the angle `nn` (`0 < nn < 90`). +the angle `nn` (`0 < nn <= 90`). For 2D histograms the text is plotted in the center of each non empty cells. It is possible to plot empty cells by calling `gStyle->SetHistMinimumZero()` @@ -1688,9 +1693,8 @@ Begin_Macro(source) htext4->SetMarkerSize(1.8); htext5->SetMarkerSize(1.8); htext5->SetMarkerColor(kRed); - htext3->Draw("COL"); htext4->SetBarOffset(0.2); - htext4->Draw("TEXT SAME"); + htext4->Draw("COL TEXT SAME"); htext5->SetBarOffset(-0.2); htext5->Draw("TEXT SAME"); } @@ -2331,13 +2335,13 @@ The following options are supported: | Option | Description | |----------|-------------------------------------------------------------------| -| "SCAT" | Draw a scatter plot (default).| -| "COL" | Draw a color plot. All the bins are painted even the empty bins.| +| "SCAT" | Draw a scatter plot (deprecated).| +| "COL" | Draw a color plot. All the bins are painted even the empty bins (default).| | "COLZ" | Same as "COL". In addition the color palette is also drawn.| | "0" | When used with any COL options, the empty bins are not drawn.| | "TEXT" | Draw bin contents as text (format set via `gStyle->SetPaintTextFormat`).| | "TEXTN" | Draw bin names as text.| -| "TEXTnn" | Draw bin contents as text at angle nn (0 < nn < 90).| +| "TEXTnn" | Draw bin contents as text at angle nn (0 < nn <= 90).| | "L" | Draw the bins boundaries as lines. The lines attributes are the TGraphs ones.| | "P" | Draw the bins boundaries as markers. The markers attributes are the TGraphs ones.| | "F" | Draw the bins boundaries as filled polygons. The filled polygons attributes are the TGraphs ones.| @@ -2575,16 +2579,17 @@ End_Macro | Option | Description | |----------|-------------------------------------------------------------------| +| "SCAT" | Draw a scatter plot (deprecated).| | "ISO" | Draw a Gouraud shaded 3d iso surface through a 3d histogram. It paints one surface at the value computed as follow: `SumOfWeights/(NbinsX*NbinsY*NbinsZ)`| | "BOX" | Draw a for each cell with volume proportional to the content's absolute value. An hidden line removal algorithm is used| | "BOX1" | Same as BOX but an hidden surface removal algorithm is used| -| "BOX2" | The boxes' colors are picked in the current palette according to the bins' contents| +| "BOX2" | Same as "COL". The boxes' colors are picked in the current palette according to the bins' contents (default)| | "BOX2Z" | Same as "BOX2". In addition the color palette is also drawn.| | "BOX3" | Same as BOX1, but the border lines of each lego-bar are not drawn.| Note that instead of `BOX` one can also use `LEGO`. -By default, like 2D histograms, 3D histograms are drawn as scatter plots. +By default, 3D histograms are drawn as a colored box plots. The following example shows a 3D histogram plotted as a scatter plot. @@ -2592,7 +2597,7 @@ Begin_Macro(source) { auto c06 = new TCanvas("c06","c06",600,400); gStyle->SetOptStat(kFALSE); - auto h3scat = new TH3F("h3scat","Option SCAT (default) ",15,-2,2,15,-2,2,15,0,4); + auto h3scat = new TH3F("h3scat","Option SCAT",15,-2,2,15,-2,2,15,0,4); double x, y, z; for (Int_t i=0;i<10000;i++) { gRandom->Rannor(x, y); @@ -2644,7 +2649,7 @@ Begin_Macro(source) { auto c56 = new TCanvas("c56","c56",600,400); gStyle->SetOptStat(kFALSE); - auto h3box = new TH3F("h3box","Option BOX2",10,-2.,2.,10,-2.,2.,10,-0.5,2.); + auto h3box = new TH3F("h3box","Option BOX2 (default)",10,-2.,2.,10,-2.,2.,10,-0.5,2.); double x, y, z; for (Int_t i=0;i<10000;i++) { gRandom->Rannor(x, y); @@ -3196,8 +3201,9 @@ THistPainter::THistPainter() fZaxis = nullptr; fFunctions = nullptr; fNcuts = 0; - fStack = 0; + fStack = nullptr; fShowProjection = 0; + fShowProjection2 = 0; fShowOption = ""; for (int i=0; iGetDimension(); + Bool_t explicitColor = kFALSE; Hoption.Axis = Hoption.Bar = Hoption.Curve = Hoption.Error = 0; Hoption.Hist = Hoption.Line = Hoption.Mark = Hoption.Fill = 0; @@ -4052,7 +4059,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) MakeCuts(chopt); for (Int_t i=0;i 1) Hoption.Scat = 1; + if (hdim > 1) Hoption.Color = 1; // Default drawing option for 2D and 3D histograms if (!nch) Hoption.Hist = 1; if (fFunctions->First()) Hoption.Func = 1; if (fH->GetSumw2N() && hdim == 1) Hoption.Error = 2; @@ -4076,7 +4083,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) l = strstr(chopt,"SPEC"); if (l) { - Hoption.Scat = 0; + Hoption.Color = 0; memcpy(l," ",4); Int_t bs=0; l = strstr(chopt,"BF("); @@ -4126,6 +4133,14 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (l[4] == '0') { Hoption.Same += 10; l[4] = ' '; } } + l = strstr(chopt,"SCAT"); + if (l) { + Warning("MakeChopt","option SCAT is deprecated."); + Hoption.Scat = 1; + memcpy(l," ",4); + Hoption.Color = 0; + } + l = strstr(chopt,"PIE"); if (l) { Hoption.Pie = 1; @@ -4137,19 +4152,19 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (l) { TCandle candle; Hoption.Candle = candle.ParseOption(l); - Hoption.Scat = 0; + Hoption.Color = 0; } l = strstr(chopt,"VIOLIN"); if (l) { TCandle candle; Hoption.Candle = candle.ParseOption(l); - Hoption.Scat = 0; + Hoption.Color = 0; } l = strstr(chopt,"LEGO"); if (l) { - Hoption.Scat = 0; + Hoption.Color = 0; Hoption.Lego = 1; memcpy(l," ",4); if (l[4] == '1') { Hoption.Lego = 11; l[4] = ' '; } if (l[4] == '2') { Hoption.Lego = 12; l[4] = ' '; } @@ -4163,7 +4178,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) l = strstr(chopt,"SURF"); if (l) { - Hoption.Scat = 0; + Hoption.Color = 0; Hoption.Surf = 1; memcpy(l," ",4); if (l[4] == '1') { Hoption.Surf = 11; l[4] = ' '; } if (l[4] == '2') { Hoption.Surf = 12; l[4] = ' '; } @@ -4188,6 +4203,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) memcpy(l," ",3); l = strstr(chopt,"FB"); if (l) { Hoption.FrontBox = 0; memcpy(l," ",2); } l = strstr(chopt,"BB"); if (l) { Hoption.BackBox = 0; memcpy(l," ",2); } + Hoption.Color = 0; } l = strstr(chopt,"LIST"); if (l) { Hoption.List = 1; memcpy(l," ",4);} @@ -4196,7 +4212,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (l) { memcpy(l," ",4); if (hdim>1) { - Hoption.Scat = 0; + Hoption.Color = 0; Hoption.Contour = 1; if (l[4] == '1') { Hoption.Contour = 11; l[4] = ' '; } if (l[4] == '2') { Hoption.Contour = 12; l[4] = ' '; } @@ -4231,7 +4247,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) memcpy(l," ", 3); if (hdim>1) { Hoption.Arrow = 1; - Hoption.Scat = 0; + Hoption.Color = 0; l = strstr(chopt,"COL"); if (l) { Hoption.Arrow = 2; memcpy(l," ",3); } l = strstr(chopt,"Z"); if (l) { Hoption.Zscale = 1; memcpy(l," ",1); } } else { @@ -4242,7 +4258,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (l) { memcpy(l," ", 3); if (hdim>1) { - Hoption.Scat = 0; + Hoption.Color = 0; Hoption.Box = 1; if (l[3] == '1') { Hoption.Box = 11; l[3] = ' '; } if (l[3] == '2') { Hoption.Box = 12; l[3] = ' '; } @@ -4251,12 +4267,27 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) Hoption.Hist = 1; } } + l = strstr(chopt,"TEXT"); + if (l) { + Int_t angle; + if (sscanf(&l[4],"%d",&angle) > 0) { + if (angle < 0) angle=0; + if (angle > 90) angle=90; + Hoption.Text = 1000+angle; + } else { + Hoption.Text = 1; + } + memcpy(l," ", 4); + l = strstr(chopt,"N"); + if (l && fH->InheritsFrom(TH2Poly::Class())) Hoption.Text += 3000; + Hoption.Color = 0; + } l = strstr(chopt,"COLZ"); if (l) { memcpy(l," ",4); - if (hdim>1) { + if (hdim > 1) { + explicitColor = kTRUE; Hoption.Color = 1; - Hoption.Scat = 0; Hoption.Zscale = 1; if (l[4] == '2') { Hoption.Color = 3; l[4] = ' '; } l = strstr(chopt,"0"); if (l) { Hoption.Zero = 1; memcpy(l," ",1); } @@ -4268,9 +4299,9 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) l = strstr(chopt,"COL" ); if (l) { memcpy(l," ", 3); - if (hdim>1) { + if (hdim > 1) { + explicitColor = kTRUE; Hoption.Color = 1; - Hoption.Scat = 0; if (l[3] == '2') { Hoption.Color = 3; l[3] = ' '; } l = strstr(chopt,"0"); if (l) { Hoption.Zero = 1; memcpy(l," ",1); } l = strstr(chopt,"1"); if (l) { Hoption.Color = 2; memcpy(l," ",1); } @@ -4283,21 +4314,6 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) l = strstr(chopt,"AXIS"); if (l) { Hoption.Axis = 1; memcpy(l," ",4); } l = strstr(chopt,"AXIG"); if (l) { Hoption.Axis = 2; memcpy(l," ",4); } l = strstr(chopt,"SCAT"); if (l) { Hoption.Scat = 1; memcpy(l," ",4); } - l = strstr(chopt,"TEXT"); - if (l) { - Int_t angle; - if (sscanf(&l[4],"%d",&angle) > 0) { - if (angle < 0) angle=0; - if (angle > 90) angle=90; - Hoption.Text = 1000+angle; - } else { - Hoption.Text = 1; - } - memcpy(l," ", 4); - l = strstr(chopt,"N"); - if (l && fH->InheritsFrom(TH2Poly::Class())) Hoption.Text += 3000; - Hoption.Scat = 0; - } l = strstr(chopt,"POL"); if (l) { Hoption.System = kPOLAR; memcpy(l," ",3); } l = strstr(chopt,"CYL"); if (l) { Hoption.System = kCYLINDRICAL; memcpy(l," ",3); } l = strstr(chopt,"SPH"); if (l) { Hoption.System = kSPHERICAL; memcpy(l," ",3); } @@ -4305,8 +4321,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) l = strstr(chopt,"TRI"); if (l) { - Hoption.Scat = 0; - Hoption.Color = 0; + if (!explicitColor) Hoption.Color = 0; Hoption.Tri = 1; memcpy(l," ",3); l = strstr(chopt,"FB"); if (l) { Hoption.FrontBox = 0; memcpy(l," ",2); } l = strstr(chopt,"BB"); if (l) { Hoption.BackBox = 0; memcpy(l," ",2); } @@ -4329,8 +4344,12 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (l) { Hoption.Proj = 4; memcpy(l," ",9); //Parabolic projection } + l = strstr(chopt,"MOLLWEIDE"); + if (l) { + Hoption.Proj = 5; memcpy(l," ",9); //Mollweide projection + } if (Hoption.Proj > 0) { - Hoption.Scat = 0; + if (!explicitColor) Hoption.Color = 0; Hoption.Contour = 14; } @@ -4348,7 +4367,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) if (strstr(chopt,"P0")) Hoption.Mark =10; if (fH->InheritsFrom(TH2Poly::Class())) { - if (Hoption.Fill+Hoption.Line+Hoption.Mark != 0 ) Hoption.Scat = 0; + if ((Hoption.Fill+Hoption.Line+Hoption.Mark != 0) && !explicitColor) Hoption.Color = 0; } if (strstr(chopt,"E")) { @@ -4372,7 +4391,7 @@ Int_t THistPainter::MakeChopt(Option_t *choptin) } else { if (Hoption.Error == 0) { Hoption.Error = 100; - Hoption.Scat = 0; + if (!explicitColor) Hoption.Color = 0; } if (Hoption.Text) { Hoption.Text += 2000; @@ -4424,7 +4443,7 @@ Int_t THistPainter::MakeCuts(char *choptin) Int_t nc = strlen(cuts); while (cuts[nc-1] == ' ') {cuts[nc-1] = 0; nc--;} TIter next(gROOT->GetListOfSpecials()); - TCutG *cut=0; + TCutG *cut=nullptr; TObject *obj; while ((obj = next())) { if (!obj->InheritsFrom(TCutG::Class())) continue; @@ -4625,10 +4644,10 @@ void THistPainter::Paint(Option_t *option) paintstat: if ((Hoption.Same%10) != 1 && !fH->TestBit(TH1::kNoStats)) { // bit set via TH1::SetStats TIter next(fFunctions); - TObject *obj = 0; + TObject *obj = nullptr; while ((obj = next())) { if (obj->InheritsFrom(TF1::Class())) break; - obj = 0; + obj = nullptr; } //Stat is painted twice (first, it will be in canvas' list of primitives), @@ -6892,18 +6911,16 @@ void THistPainter::PaintHist(Option_t *) // Code option for GrapHist - if (Hoption.Line) chopth[0] = 'L'; - if (Hoption.Star) chopth[1] = '*'; - if (Hoption.Mark) chopth[2] = 'P'; + if (Hoption.Line) chopth[0] = 'L'; + if (Hoption.Star) chopth[1] = '*'; + if (Hoption.Mark) chopth[2] = 'P'; if (Hoption.Mark == 10) chopth[3] = '0'; if (Hoption.Line || Hoption.Curve || Hoption.Hist || Hoption.Bar) { if (Hoption.Curve) chopth[3] = 'C'; if (Hoption.Hist > 0) chopth[4] = 'H'; else if (Hoption.Bar) chopth[5] = 'B'; + if (Hoption.Logy) chopth[6] = '1'; if (fH->GetFillColor() && htype) { - if (Hoption.Logy) { - chopth[6] = '1'; - } if (Hoption.Hist > 0 || Hoption.Curve || Hoption.Line) { chopth[7] = 'F'; } @@ -6962,43 +6979,59 @@ void THistPainter::PaintH3(Option_t *option) TString opt = option; opt.ToLower(); Int_t irep; + Float_t NEntries = fH->GetEntries(); - if (fCurrentF3) { + if (fCurrentF3 || strstr(opt,"tf3")) { PaintTF3(); return; - } else if (Hoption.Box || Hoption.Lego) { - if (Hoption.Box == 11 || Hoption.Lego == 11) { - PaintH3Box(1); - } else if (Hoption.Box == 12 || Hoption.Lego == 12) { - PaintH3Box(2); - } else if (Hoption.Box == 13 || Hoption.Lego == 13) { - PaintH3Box(3); - } else { - PaintH3BoxRaster(); + } + + if (NEntries > 0) { + if (Hoption.Box || Hoption.Lego || Hoption.Color) { + if (Hoption.Box == 11 || Hoption.Lego == 11) { + PaintH3Box(1); + } else if (Hoption.Box == 12 || Hoption.Lego == 12 || Hoption.Color == 1) { + PaintH3Box(2); + } else if (Hoption.Box == 13 || Hoption.Lego == 13) { + PaintH3Box(3); + } else { + PaintH3BoxRaster(); + } + return; + } + + if (strstr(opt,"iso")) { + PaintH3Iso(); + return; } - return; - } else if (strstr(opt,"iso")) { - PaintH3Iso(); - return; - } else if (strstr(opt,"tf3")) { - PaintTF3(); - return; - } else { - cmd.Form("TPolyMarker3D::PaintH3((TH1 *)0x%zx,\"%s\");",(size_t)fH,option); } + TView *view = gPad ? gPad->GetView() : nullptr; + if (!view) return; + if (strstr(opt,"fb")) Hoption.FrontBox = 0; if (strstr(opt,"bb")) Hoption.BackBox = 0; - TView *view = gPad ? gPad->GetView() : nullptr; - if (!view) return; Double_t thedeg = 90 - gPad->GetTheta(); Double_t phideg = -90 - gPad->GetPhi(); Double_t psideg = view->GetPsi(); view->SetView(phideg, thedeg, psideg, irep); - // Paint the data - gROOT->ProcessLine(cmd.Data()); + if(NEntries > 0) { // Paint as 3D scatter plot + cmd.Form("TPolyMarker3D::PaintH3((TH1 *)0x%zx,\"%s\");",(size_t)fH,option); + gROOT->ProcessLine(cmd.Data()); + } else { + TAxis* xAxis = fH->GetXaxis(); + TAxis* yAxis = fH->GetYaxis(); + TAxis* zAxis = fH->GetZaxis(); + Double_t xmin = xAxis->GetXmin(); + Double_t xmax = xAxis->GetXmax(); + Double_t ymin = yAxis->GetXmin(); + Double_t ymax = yAxis->GetXmax(); + Double_t zmin = zAxis->GetXmin(); + Double_t zmax = zAxis->GetXmax(); + view->SetRange(xmin, ymin, zmin, xmax, ymax, zmax); // Set the axis limits (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) + } if (Hoption.Same) return; @@ -7079,7 +7112,23 @@ Int_t THistPainter::PaintInit() } if (Hparam.xlowedge <=0 ) { if (Hoption.Same) { - Hparam.xlowedge = TMath::Power(10, gPad->GetUxmin()); + TH1* h1 = nullptr; + TObject *obj; + TIter next(gPad->GetListOfPrimitives()); + while ((obj = (TObject *)next())) { + if (obj->InheritsFrom(TH1::Class())) { h1 = (TH1*)(obj) ; break; } + if (obj->InheritsFrom(THStack::Class())) { h1 = ((THStack*)(obj))->GetHistogram() ; break; } + if (obj->InheritsFrom(TGraph::Class())) { h1 = ((TGraph*)(obj))->GetHistogram() ; break; } + if (obj->InheritsFrom(TMultiGraph::Class())) { h1 = ((TMultiGraph*)(obj))->GetHistogram(); break; } + if (obj->InheritsFrom(TGraph2D::Class())) { h1 = ((TGraph2D*)(obj))->GetHistogram(); break; } + if (obj->InheritsFrom(TF1::Class())) { h1 = ((TF1*)(obj))->GetHistogram(); break; } + } + if (h1) { + Hparam.xlowedge = h1->GetXaxis()->GetBinLowEdge(h1->GetXaxis()->GetFirst()); + } else { + Error(where, "undefined user's coordinates. Cannot use option SAME"); + return 0; + } } else { for (i=first; i<=last; i++) { Double_t binLow = fXaxis->GetBinLowEdge(i); @@ -7390,7 +7439,7 @@ Int_t THistPainter::PaintInitH() xmax = 0; xmin *= 2; } else { - xmin = -1; + xmin = 0; xmax = 1; } } @@ -7614,6 +7663,21 @@ void THistPainter::PaintH3Box(Int_t iopt) PaintPalette(); } + //Draw stats and fit results + TF1 *fit = nullptr; + TIter next(fFunctions); + while (auto obj = next()) { + if (obj->InheritsFrom(TF1::Class())) { + fit = (TF1*)obj; + break; + } + } + if ((Hoption.Same%10) != 1) { + if (!fH->TestBit(TH1::kNoStats)) { // bit set via TH1::SetStats + PaintStat3(gStyle->GetOptStat(),fit); + } + } + fLego.reset(); fH->SetFillStyle(fillsav); @@ -7805,6 +7869,21 @@ void THistPainter::PaintH3BoxRaster() } PaintTitle(); + //Draw stats and fit results + TF1 *fit = nullptr; + TIter next(fFunctions); + while (auto obj = next()) { + if (obj->InheritsFrom(TF1::Class())) { + fit = (TF1*)obj; + break; + } + } + if ((Hoption.Same%10) != 1) { + if (!fH->TestBit(TH1::kNoStats)) { // bit set via TH1::SetStats + PaintStat3(gStyle->GetOptStat(),fit); + } + } + fLego.reset(); } @@ -7915,6 +7994,21 @@ void THistPainter::PaintH3Iso() PaintTitle(); + //Draw stats and fit results + TF1 *fit = nullptr; + TIter next(fFunctions); + while (auto obj = next()) { + if (obj->InheritsFrom(TF1::Class())) { + fit = (TF1*)obj; + break; + } + } + if ((Hoption.Same%10) != 1) { + if (!fH->TestBit(TH1::kNoStats)) { // bit set via TH1::SetStats + PaintStat3(gStyle->GetOptStat(),fit); + } + } + fLego.reset(); } @@ -7983,7 +8077,7 @@ void THistPainter::PaintLego(Option_t *) fLego = std::make_unique(fXbuf.data(), fYbuf.data(), Hoption.System); Int_t nids = -1; - TH1 * hid = NULL; + TH1 * hid = nullptr; Color_t colormain = -1, colordark = -1; Bool_t drawShadowsInLego1 = kTRUE; @@ -8531,7 +8625,7 @@ void THistPainter::PaintStat(Int_t dostat, TF1 *fit) } else { dofit = gStyle->GetOptFit(); } - if (!dofit) fit = 0; + if (!dofit) fit = nullptr; if (dofit == 1) dofit = 111; if (dostat == 1) dostat = 1111; Int_t print_name = dostat%10; @@ -8694,11 +8788,11 @@ void THistPainter::PaintStat(Int_t dostat, TF1 *fit) if (fit) { Int_t ndf = fit->GetNDF(); tf.Form("#chi^{2} / ndf = %s%s / %d","%",stats->GetFitFormat(),ndf); - tt.Form(tf.Data(),(Float_t)fit->GetChisquare()); + tt.Form(tf.Data(),fit->GetChisquare()); if (print_fchi2) stats->AddText(tt.Data()); if (print_fprob) { tf.Form("Prob = %s%s","%",stats->GetFitFormat()); - tt.Form(tf.Data(),(Float_t)TMath::Prob(fit->GetChisquare(),ndf)); + tt.Form(tf.Data(),TMath::Prob(fit->GetChisquare(),ndf)); stats->AddText(tt.Data()); } if (print_fval || print_ferrors) { @@ -8709,11 +8803,11 @@ void THistPainter::PaintStat(Int_t dostat, TF1 *fit) if (print_ferrors) { tf.Form("%-8s = %s%s #pm %s ", fit->GetParName(ipar), "%",stats->GetFitFormat(), GetBestFormat(fit->GetParameter(ipar), fit->GetParError(ipar), stats->GetFitFormat())); - tt.Form(tf.Data(),(Float_t)fit->GetParameter(ipar) - ,(Float_t)fit->GetParError(ipar)); + tt.Form(tf.Data(),fit->GetParameter(ipar) + ,fit->GetParError(ipar)); } else { tf.Form("%-8s = %s%s ",fit->GetParName(ipar), "%",stats->GetFitFormat()); - tt.Form(tf.Data(),(Float_t)fit->GetParameter(ipar)); + tt.Form(tf.Data(),fit->GetParameter(ipar)); } stats->AddText(tt.Data()); } @@ -8763,7 +8857,7 @@ void THistPainter::PaintStat2(Int_t dostat, TF1 *fit) if (print_under || print_over) nlines += 3; // Pavetext with statistics - if (!gStyle->GetOptFit()) fit = 0; + if (!gStyle->GetOptFit()) fit = nullptr; Bool_t done = kFALSE; if (!dostat && !fit) { if (stats) { fFunctions->Remove(stats); delete stats;} @@ -8923,12 +9017,12 @@ void THistPainter::PaintStat2(Int_t dostat, TF1 *fit) // Draw Fit parameters if (fit) { Int_t ndf = fit->GetNDF(); - tt.Form("#chi^{2} / ndf = %6.4g / %d",(Float_t)fit->GetChisquare(),ndf); + tt.Form("#chi^{2} / ndf = %6.4g / %d",fit->GetChisquare(),ndf); stats->AddText(tt.Data()); for (Int_t ipar=0;iparGetNpar();ipar++) { tt.Form("%-8s = %5.4g #pm %5.4g ",fit->GetParName(ipar) - ,(Float_t)fit->GetParameter(ipar) - ,(Float_t)fit->GetParError(ipar)); + ,fit->GetParameter(ipar) + ,fit->GetParError(ipar)); stats->AddText(tt.Data()); } } @@ -8976,7 +9070,7 @@ void THistPainter::PaintStat3(Int_t dostat, TF1 *fit) if (print_under || print_over) nlines += 3; // Pavetext with statistics - if (!gStyle->GetOptFit()) fit = 0; + if (!gStyle->GetOptFit()) fit = nullptr; Bool_t done = kFALSE; if (!dostat && !fit) { if (stats) { fFunctions->Remove(stats); delete stats;} @@ -9137,12 +9231,12 @@ void THistPainter::PaintStat3(Int_t dostat, TF1 *fit) // Draw Fit parameters if (fit) { Int_t ndf = fit->GetNDF(); - tt.Form("#chi^{2} / ndf = %6.4g / %d",(Float_t)fit->GetChisquare(),ndf); + tt.Form("#chi^{2} / ndf = %6.4g / %d",fit->GetChisquare(),ndf); stats->AddText(tt.Data()); for (Int_t ipar=0;iparGetNpar();ipar++) { tt.Form("%-8s = %5.4g #pm %5.4g ",fit->GetParName(ipar) - ,(Float_t)fit->GetParameter(ipar) - ,(Float_t)fit->GetParError(ipar)); + ,fit->GetParameter(ipar) + ,fit->GetParError(ipar)); stats->AddText(tt.Data()); } } @@ -10271,7 +10365,9 @@ Int_t THistPainter::ProjectMercator2xy(Double_t l, Double_t b, Double_t &Al, Dou } //////////////////////////////////////////////////////////////////////////////// -/// Static function code from Ernst-Jan Buis +/// Static function code for sinusoidal projection +/// from Ernst-Jan Buis +/// Source https://en.wikipedia.org/wiki/Sinusoidal_projection Int_t THistPainter::ProjectSinusoidal2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab) { @@ -10282,7 +10378,8 @@ Int_t THistPainter::ProjectSinusoidal2xy(Double_t l, Double_t b, Double_t &Al, D } //////////////////////////////////////////////////////////////////////////////// -/// Static function code from Ernst-Jan Buis +/// Static function code for parabolic projection +/// from Ernst-Jan Buis Int_t THistPainter::ProjectParabolic2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab) { @@ -10292,6 +10389,43 @@ Int_t THistPainter::ProjectParabolic2xy(Double_t l, Double_t b, Double_t &Al, Do return 0; } +//////////////////////////////////////////////////////////////////////////////// +/// Static function. +/// +/// Convert Right Ascension, Declination to X,Y using an MOLLWEIDE projection. +/// This procedure can be used to create an all-sky map in Galactic +/// coordinates with an equal-area Mollweide projection. Output map +/// coordinates are zero longitude centered. +/// It is also known as the Babinet projection, homalographic projection, homolographic projection, and elliptical projection. +/// Source: https://en.wikipedia.org/wiki/Mollweide_projection +/// +/// code from Marco Meyer-Conde + +Int_t THistPainter::ProjectMollweide2xy(Double_t l, Double_t b, Double_t &Al, Double_t &Ab) +{ + + Double_t theta0 = b * TMath::DegToRad(), theta = theta0; + + for (int i = 0; i < 100; i++) { + Double_t num = 2 * theta + TMath::Sin(2 * theta) - TMath::Pi() * TMath::Sin(theta0); + Double_t den = 4 * TMath::Power(TMath::Cos(theta), 2); + + if (den < 1e-20) { + theta = theta0; + break; + } + + theta -= num / den; + + if (TMath::Abs(num / den) < 1e-4) break; + } + + Al = l * TMath::Cos(theta); + Ab = 90 * TMath::Sin(theta); + + return 0; +} + //////////////////////////////////////////////////////////////////////////////// /// Recompute the histogram range following graphics operations. @@ -10301,93 +10435,64 @@ void THistPainter::RecalculateRange() if (Hoption.Same) return; // Compute x,y range - Double_t xmin = Hparam.xmin; - Double_t xmax = Hparam.xmax; - Double_t ymin = Hparam.ymin; - Double_t ymax = Hparam.ymax; - - Double_t xmin_aid, ymin_aid, xmax_aid, ymax_aid; - if (Hoption.Proj ==1) { - // TODO : check x range not lower than -180 and not higher than 180 - THistPainter::ProjectAitoff2xy(Hparam.xmin, Hparam.ymin, xmin_aid, ymin_aid); - THistPainter::ProjectAitoff2xy(Hparam.xmin, Hparam.ymax, xmin, ymax_aid); - THistPainter::ProjectAitoff2xy(Hparam.xmax, Hparam.ymax, xmax_aid, ymax); - THistPainter::ProjectAitoff2xy(Hparam.xmax, Hparam.ymin, xmax, ymin); - - if (xmin > xmin_aid) xmin = xmin_aid; - if (ymin > ymin_aid) ymin = ymin_aid; - if (xmax < xmax_aid) xmax = xmax_aid; - if (ymax < ymax_aid) ymax = ymax_aid; - if (Hparam.ymin<0 && Hparam.ymax>0) { - // there is an 'equator', check its range in the plot.. - THistPainter::ProjectAitoff2xy(Hparam.xmin*0.9999, 0, xmin_aid, ymin_aid); - THistPainter::ProjectAitoff2xy(Hparam.xmax*0.9999, 0, xmax_aid, ymin_aid); - if (xmin >xmin_aid) xmin = xmin_aid; - if (xmax 0) { - THistPainter::ProjectAitoff2xy(0, Hparam.ymin, xmin_aid, ymin_aid); - THistPainter::ProjectAitoff2xy(0, Hparam.ymax, xmax_aid, ymax_aid); - if (ymin >ymin_aid) ymin = ymin_aid; - if (ymax =90) { + Double_t xmin = Hparam.xmin, + xmax = Hparam.xmax, + ymin = Hparam.ymin, + ymax = Hparam.ymax, + xscale = 1; + + std::function func; + + if (Hoption.Proj == 1) { + func = ProjectAitoff2xy; + xscale = 0.9999; + } else if (Hoption.Proj == 2) { + if (Hparam.ymin <= -90 || Hparam.ymax >= 90) { Warning("Mercator Projection", "Latitude out of range %f or %f", Hparam.ymin, Hparam.ymax); Hoption.Proj = 0; } else { - THistPainter::ProjectMercator2xy(Hparam.xmin, Hparam.ymin, xmin, ymin); - THistPainter::ProjectMercator2xy(Hparam.xmax, Hparam.ymax, xmax, ymax); + ProjectMercator2xy(Hparam.xmin, Hparam.ymin, xmin, ymin); + ProjectMercator2xy(Hparam.xmax, Hparam.ymax, xmax, ymax); } } else if (Hoption.Proj == 3) { - THistPainter::ProjectSinusoidal2xy(Hparam.xmin, Hparam.ymin, xmin_aid, ymin_aid); - THistPainter::ProjectSinusoidal2xy(Hparam.xmin, Hparam.ymax, xmin, ymax_aid); - THistPainter::ProjectSinusoidal2xy(Hparam.xmax, Hparam.ymax, xmax_aid, ymax); - THistPainter::ProjectSinusoidal2xy(Hparam.xmax, Hparam.ymin, xmax, ymin); - - if (xmin > xmin_aid) xmin = xmin_aid; - if (ymin > ymin_aid) ymin = ymin_aid; - if (xmax < xmax_aid) xmax = xmax_aid; - if (ymax < ymax_aid) ymax = ymax_aid; - if (Hparam.ymin<0 && Hparam.ymax>0) { - THistPainter::ProjectSinusoidal2xy(Hparam.xmin, 0, xmin_aid, ymin_aid); - THistPainter::ProjectSinusoidal2xy(Hparam.xmax, 0, xmax_aid, ymin_aid); - if (xmin >xmin_aid) xmin = xmin_aid; - if (xmax 0) { - THistPainter::ProjectSinusoidal2xy(0,Hparam.ymin, xmin_aid, ymin_aid); - THistPainter::ProjectSinusoidal2xy(0, Hparam.ymax, xmax_aid, ymin_aid); - if (ymin >ymin_aid) ymin = ymin_aid; - if (ymax xmin_aid) xmin = xmin_aid; if (ymin > ymin_aid) ymin = ymin_aid; if (xmax < xmax_aid) xmax = xmax_aid; if (ymax < ymax_aid) ymax = ymax_aid; - if (Hparam.ymin<0 && Hparam.ymax>0) { - THistPainter::ProjectParabolic2xy(Hparam.xmin, 0, xmin_aid, ymin_aid); - THistPainter::ProjectParabolic2xy(Hparam.xmax, 0, xmax_aid, ymin_aid); - if (xmin >xmin_aid) xmin = xmin_aid; - if (xmax 0) { + // there is an 'equator', check its range in the plot.. + func(Hparam.xmin*xscale, 0, xmin_aid, ymin_aid); + func(Hparam.xmax*xscale, 0, xmax_aid, ymin_aid); + if (xmin > xmin_aid) xmin = xmin_aid; + if (xmax < xmax_aid) xmax = xmax_aid; } - if (Hparam.xmin<0 && Hparam.xmax>0) { - THistPainter::ProjectParabolic2xy(0, Hparam.ymin, xmin_aid, ymin_aid); - THistPainter::ProjectParabolic2xy(0, Hparam.ymax, xmax_aid, ymin_aid); - if (ymin >ymin_aid) ymin = ymin_aid; - if (ymax 0) { + func(0, Hparam.ymin, xmin_aid, ymin_aid); + func(0, Hparam.ymax, xmax_aid, ymax_aid); + if (ymin > ymin_aid) ymin = ymin_aid; + if (ymax < ymax_aid) ymax = ymax_aid; } } - Hparam.xmin= xmin; - Hparam.xmax= xmax; - Hparam.ymin= ymin; - Hparam.ymax= ymax; + + Hparam.xmin = xmin; + Hparam.xmax = xmax; + Hparam.ymin = ymin; + Hparam.ymax = ymax; Double_t dx = xmax-xmin; Double_t dy = ymax-ymin; @@ -10397,9 +10502,9 @@ void THistPainter::RecalculateRange() // Range() could change the size of the pad pixmap and therefore should // be called before the other paint routines gPad->Range(xmin - dxr*gPad->GetLeftMargin(), - ymin - dyr*gPad->GetBottomMargin(), - xmax + dxr*gPad->GetRightMargin(), - ymax + dyr*gPad->GetTopMargin()); + ymin - dyr*gPad->GetBottomMargin(), + xmax + dxr*gPad->GetRightMargin(), + ymax + dyr*gPad->GetTopMargin()); gPad->RangeAxis(xmin, ymin, xmax, ymax); } @@ -10409,7 +10514,7 @@ void THistPainter::RecalculateRange() void THistPainter::SetHistogram(TH1 *h) { - if (h == 0) return; + if (h == nullptr) return; fH = h; fXaxis = h->GetXaxis(); fYaxis = h->GetYaxis(); @@ -10652,8 +10757,21 @@ const char * THistPainter::GetBestFormat(Double_t v, Double_t e, const char *f) void THistPainter::SetShowProjection(const char *option,Int_t nbins) { + if (fShowProjection2) { + auto name2 = TString::Format("c_%zx_projection2_%d", (size_t)fH, fShowProjection2); + auto c2 = static_cast(gROOT->GetListOfCanvases()->FindObject(name2.Data())); + if (c2) c2->Close(); + fShowProjection2 = 0; + } + if (fShowProjection) { + auto name1 = TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection); + auto c1 = static_cast(gROOT->GetListOfCanvases()->FindObject(name1.Data())); + if (c1) c1->Close(); + fShowProjection = 0; + } + + if (nbins <= 0) return; - if (fShowProjection) return; TString opt = option; opt.ToLower(); Int_t projection = 0; @@ -10669,11 +10787,55 @@ void THistPainter::SetShowProjection(const char *option,Int_t nbins) if (projection < 4) fShowOption = option+1; else fShowOption = option+2; fShowProjection = projection+100*nbins; + fShowProjection2 = 0; + gROOT->MakeDefCanvas(); + gPad->SetName(TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection).Data()); + gPad->SetGrid(); +} + +void THistPainter::SetShowProjectionXY(const char *option,Int_t nbinsY,Int_t nbinsX) +{ + if (fShowProjection2) { + auto name2 = TString::Format("c_%zx_projection2_%d", (size_t)fH, fShowProjection2); + auto c2 = static_cast(gROOT->GetListOfCanvases()->FindObject(name2.Data())); + if (c2) c2->Close(); + fShowProjection2 = 0; + } + if (fShowProjection) { + auto name1 = TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection); + auto c1 = static_cast(gROOT->GetListOfCanvases()->FindObject(name1.Data())); + if (c1) c1->Close(); + fShowProjection = 0; + } + + if ((nbinsX <= 0) || (nbinsY <= 0)) return; + + + TString opt = option; + opt.ToLower(); + Int_t projection = 0; + if (opt.Contains("x")) projection = 1; + if (opt.Contains("y")) projection = 2; + if (opt.Contains("z")) projection = 3; + if (opt.Contains("xy")) projection = 4; + if (opt.Contains("yx")) projection = 5; + if (opt.Contains("xz")) projection = 6; + if (opt.Contains("zx")) projection = 7; + if (opt.Contains("yz")) projection = 8; + if (opt.Contains("zy")) projection = 9; + if (projection < 4) fShowOption = option+1; + else fShowOption = option+2; + fShowProjection = projection+100*nbinsY; + fShowProjection2 = projection+100*nbinsX; gROOT->MakeDefCanvas(); gPad->SetName(TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection).Data()); gPad->SetGrid(); + gROOT->MakeDefCanvas(); + gPad->SetName(TString::Format("c_%zx_projection2_%d", (size_t)fH, fShowProjection2).Data()); + gPad->SetGrid(); } + //////////////////////////////////////////////////////////////////////////////// /// Show projection onto X. @@ -10705,12 +10867,13 @@ void THistPainter::ShowProjectionX(Int_t /*px*/, Int_t py) // Create or set the new canvas proj x TVirtualPad::TContext ctxt(true); - TVirtualPad *c = (TVirtualPad*)gROOT->GetListOfCanvases()->FindObject(TString::Format("c_%zx_projection_%d", - (size_t)fH, fShowProjection).Data()); + auto name1 = TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection); + TVirtualPad *c = (TVirtualPad*)gROOT->GetListOfCanvases()->FindObject(name1.Data()); if (c) { c->Clear(); } else { fShowProjection = 0; + fShowProjection2 = 0; pyold1 = 0; pyold2 = 0; return; @@ -10731,7 +10894,7 @@ void THistPainter::ShowProjectionX(Int_t /*px*/, Int_t py) Double_t valueTo = fH->GetYaxis()->GetBinUpEdge(biny1); // Limit precision to 1 digit more than the difference between upper and lower bound (to also catch 121.5-120.5). Int_t valuePrecision = -TMath::Nint(TMath::Log10(valueTo-valueFrom))+1; - if (fH->GetYaxis()->GetLabels() != NULL) { + if (fH->GetYaxis()->GetLabels() != nullptr) { hp->SetTitle(TString::Format("ProjectionX of biny=%d [y=%.*lf..%.*lf] %s", biny1, valuePrecision, valueFrom, valuePrecision, valueTo, fH->GetYaxis()->GetBinLabel(biny1))); } else { hp->SetTitle(TString::Format("ProjectionX of biny=%d [y=%.*lf..%.*lf]", biny1, valuePrecision, valueFrom, valuePrecision, valueTo)); @@ -10743,14 +10906,14 @@ void THistPainter::ShowProjectionX(Int_t /*px*/, Int_t py) // biny1 is used here to get equal precision no matter how large the binrange is, // otherwise precision may change when moving the mouse to the histogram boundaries (limiting effective binrange). Int_t valuePrecision = -TMath::Nint(TMath::Log10(fH->GetYaxis()->GetBinUpEdge(biny1)-valueFrom))+1; - if (fH->GetYaxis()->GetLabels() != NULL) { + if (fH->GetYaxis()->GetLabels() != nullptr) { hp->SetTitle(TString::Format("ProjectionX of biny=[%d,%d] [y=%.*lf..%.*lf] [%s..%s]", biny1, biny2, valuePrecision, valueFrom, valuePrecision, valueTo, fH->GetYaxis()->GetBinLabel(biny1), fH->GetYaxis()->GetBinLabel(biny2))); } else { hp->SetTitle(TString::Format("ProjectionX of biny=[%d,%d] [y=%.*lf..%.*lf]", biny1, biny2, valuePrecision, valueFrom, valuePrecision, valueTo)); } } hp->SetXTitle(fH->GetXaxis()->GetTitle()); - hp->SetYTitle("Number of Entries"); + hp->SetYTitle(((TH2*)fH)->GetZaxis()->GetTitle() ? ((TH2*)fH)->GetZaxis()->GetTitle() : "Number of Entries"); hp->Draw(); c->Update(); } @@ -10763,6 +10926,8 @@ void THistPainter::ShowProjectionY(Int_t px, Int_t /*py*/) { Int_t nbins = (Int_t)fShowProjection/100; + if (fShowProjection2) + nbins = (Int_t)fShowProjection2/100; gPad->SetDoubleBuffer(0); // turn off double buffer mode gVirtualX->SetDrawMode(TVirtualX::kInvert); // set the drawing mode to XOR mode @@ -10788,12 +10953,15 @@ void THistPainter::ShowProjectionY(Int_t px, Int_t /*py*/) // Create or set the new canvas proj y TVirtualPad::TContext ctxt(true); - TVirtualPad *c = (TVirtualPad*)gROOT->GetListOfCanvases()->FindObject(TString::Format("c_%zx_projection_%d", - (size_t)fH, fShowProjection).Data()); + TString name2 = fShowProjection2 ? TString::Format("c_%zx_projection2_%d", (size_t)fH, fShowProjection2) + : TString::Format("c_%zx_projection_%d", (size_t)fH, fShowProjection); + + TVirtualPad *c = (TVirtualPad*)gROOT->GetListOfCanvases()->FindObject(name2.Data()); if (c) { c->Clear(); } else { fShowProjection = 0; + fShowProjection2 = 0; pxold1 = 0; pxold2 = 0; return; @@ -10814,7 +10982,7 @@ void THistPainter::ShowProjectionY(Int_t px, Int_t /*py*/) Double_t valueTo = fH->GetXaxis()->GetBinUpEdge(binx1); // Limit precision to 1 digit more than the difference between upper and lower bound (to also catch 121.5-120.5). Int_t valuePrecision = -TMath::Nint(TMath::Log10(valueTo-valueFrom))+1; - if (fH->GetXaxis()->GetLabels() != NULL) { + if (fH->GetXaxis()->GetLabels() != nullptr) { hp->SetTitle(TString::Format("ProjectionY of binx=%d [x=%.*lf..%.*lf] [%s]", binx1, valuePrecision, valueFrom, valuePrecision, valueTo, fH->GetXaxis()->GetBinLabel(binx1))); } else { hp->SetTitle(TString::Format("ProjectionY of binx=%d [x=%.*lf..%.*lf]", binx1, valuePrecision, valueFrom, valuePrecision, valueTo)); @@ -10826,15 +10994,15 @@ void THistPainter::ShowProjectionY(Int_t px, Int_t /*py*/) // binx1 is used here to get equal precision no matter how large the binrange is, // otherwise precision may change when moving the mouse to the histogram boundaries (limiting effective binrange). Int_t valuePrecision = -TMath::Nint(TMath::Log10(fH->GetXaxis()->GetBinUpEdge(binx1)-valueFrom))+1; - if (fH->GetXaxis()->GetLabels() != NULL) { + if (fH->GetXaxis()->GetLabels() != nullptr) { hp->SetTitle(TString::Format("ProjectionY of binx=[%d,%d] [x=%.*lf..%.*lf] [%s..%s]", binx1, binx2, valuePrecision, valueFrom, valuePrecision, valueTo, fH->GetXaxis()->GetBinLabel(binx1), fH->GetXaxis()->GetBinLabel(binx2))); } else { hp->SetTitle(TString::Format("ProjectionY of binx=[%d,%d] [x=%.*lf..%.*lf]", binx1, binx2, valuePrecision, valueFrom, valuePrecision, valueTo)); } } hp->SetXTitle(fH->GetYaxis()->GetTitle()); - hp->SetYTitle("Number of Entries"); - hp->Draw(); + hp->SetYTitle(((TH2*)fH)->GetZaxis()->GetTitle() ? ((TH2*)fH)->GetZaxis()->GetTitle() : "Number of Entries"); + hp->Draw(fShowProjection2 ? "hbar" : ""); c->Update(); } } @@ -10852,8 +11020,17 @@ void THistPainter::ShowProjection3(Int_t px, Int_t py) Int_t nbins=(Int_t)fShowProjection/100; //decode nbins if (fH->GetDimension() < 3) { - if (fShowProjection%100 == 1) {ShowProjectionX(px,py); return;} - if (fShowProjection%100 == 2) {ShowProjectionY(px,py); return;} + if (fShowProjection2 % 100 == 1) { + ShowProjectionY(px, py); + } + if (fShowProjection % 100 == 1) { + ShowProjectionX(px, py); + return; + } + if (fShowProjection % 100 == 2) { + ShowProjectionY(px, py); + return; + } } gPad->SetDoubleBuffer(0); // turn off double buffer mode diff --git a/hist/histpainter/src/TPainter3dAlgorithms.cxx b/hist/histpainter/src/TPainter3dAlgorithms.cxx index 2910722550fc0..c3ceed5fcdb76 100644 --- a/hist/histpainter/src/TPainter3dAlgorithms.cxx +++ b/hist/histpainter/src/TPainter3dAlgorithms.cxx @@ -1521,7 +1521,7 @@ void TPainter3dAlgorithms::FindVisibleDraw(Double_t *r1, Double_t *r2) Double_t x1, x2, y1, y2, z1, z2, dd, di; Double_t dt, dy; Double_t tt, uu, ww, yy, yy1, yy2, yy1d, yy2d; - Double_t *tn = 0; + Double_t *tn = nullptr; const Double_t kEpsil = 1.e-6; /* Parameter adjustments */ --r2; @@ -3420,6 +3420,10 @@ void TPainter3dAlgorithms::SurfaceCartesian(Double_t, Int_t nx, Int_t ny, const THistPainter::ProjectParabolic2xy(xyz[i*3 + 0], xyz[i*3 + 1], al, ab); xyz[i*3 + 0] = al; xyz[i*3 + 1] = ab; + } else if (Hoption.Proj == 5) { + THistPainter::ProjectMollweide2xy(xyz[i*3 + 0], xyz[i*3 + 1], al, ab); + xyz[i*3 + 0] = al; + xyz[i*3 + 1] = ab; } } icodes[0] = ix; diff --git a/hist/histpainter/src/TPaletteAxis.cxx b/hist/histpainter/src/TPaletteAxis.cxx index 32c807e258389..65e946db9fc56 100644 --- a/hist/histpainter/src/TPaletteAxis.cxx +++ b/hist/histpainter/src/TPaletteAxis.cxx @@ -138,6 +138,33 @@ TPaletteAxis::TPaletteAxis(Double_t x1, Double_t y1, Double_t x2, Double_t y2, } +//////////////////////////////////////////////////////////////////////////////// +/// Palette normal constructor. + +TPaletteAxis::TPaletteAxis(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Double_t min, Double_t max) + : TPave(x1, y1, x2, y2) +{ + fH = nullptr; + fAxis.SetWmin(min); + fAxis.SetWmax(max); + SetName("palette"); + if (gPad->GetView()) SetBit(kHasView); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Palette normal constructor. + +TPaletteAxis::TPaletteAxis(Double_t x1, Double_t y1, Double_t x2, Double_t y2, TAxis *ax) + : TPave(x1, y1, x2, y2) +{ + fH = nullptr; + SetName("palette"); + fAxis.ImportAxisAttributes(ax); + if (gPad->GetView()) SetBit(kHasView); +} + + //////////////////////////////////////////////////////////////////////////////// /// Palette destructor. @@ -405,9 +432,6 @@ Int_t TPaletteAxis::GetValueColor(Double_t zc) void TPaletteAxis::Paint(Option_t *) { - - if (!fH) return; - ConvertNDCtoPad(); SetFillStyle(1001); @@ -415,8 +439,14 @@ void TPaletteAxis::Paint(Option_t *) Double_t ymax = fY2; Double_t xmin = fX1; Double_t xmax = fX2; - Double_t wmin = fH->GetMinimum(); - Double_t wmax = fH->GetMaximum(); + Double_t wmin, wmax; + if (fH) { + wmin = fH->GetMinimum(); + wmax = fH->GetMaximum(); + } else { + wmin = fAxis.GetWmin(); + wmax = fAxis.GetWmax(); + } Double_t wlmin = wmin; Double_t wlmax = wmax; Double_t b1, b2, w1, w2, zc; @@ -440,41 +470,50 @@ void TPaletteAxis::Paint(Option_t *) } Double_t ws = wlmax - wlmin; Int_t ncolors = gStyle->GetNumberOfColors(); - Int_t ndivz = fH->GetContour(); + Int_t ndivz; + if (fH) ndivz = fH->GetContour(); + else ndivz = ncolors; if (ndivz == 0) return; ndivz = TMath::Abs(ndivz); Int_t theColor, color; // import Attributes already here since we might need them for CJUST - if (fH->GetDimension() == 2) fAxis.ImportAxisAttributes(fH->GetZaxis()); + if (fH && fH->GetDimension() == 2) fAxis.ImportAxisAttributes(fH->GetZaxis()); + // for 3D histograms there is no palette's title + if (fH && fH->GetDimension() > 2) fAxis.SetTitle(""); // case option "CJUST": put labels directly at color boundaries TLatex *label = nullptr; TLine *line = nullptr; Double_t prevlab = 0; - TString opt(fH->GetDrawOption()); - if (opt.Contains("CJUST", TString::kIgnoreCase)) { - label = new TLatex(); - label->SetTextFont(fAxis.GetLabelFont()); - label->SetTextColor(fAxis.GetLabelColor()); - if (kHorizontal) label->SetTextAlign(kHAlignCenter+kVAlignTop); - else label->SetTextAlign(kHAlignLeft+kVAlignCenter); - line = new TLine(); - line->SetLineColor(fAxis.GetLineColor()); - if (kHorizontal) line->PaintLine(xmin, ymin, xmax, ymin); - else line->PaintLine(xmax, ymin, xmax, ymax); + if (fH) { + TString opt(fH->GetDrawOption()); + if (opt.Contains("CJUST", TString::kIgnoreCase)) { + label = new TLatex(); + label->SetTextFont(fAxis.GetLabelFont()); + label->SetTextColor(fAxis.GetLabelColor()); + if (kHorizontal) label->SetTextAlign(kHAlignCenter+kVAlignTop); + else label->SetTextAlign(kHAlignLeft+kVAlignCenter); + line = new TLine(); + line->SetLineColor(fAxis.GetLineColor()); + if (kHorizontal) line->PaintLine(xmin, ymin, xmax, ymin); + else line->PaintLine(xmax, ymin, xmax, ymax); + } } Double_t scale = ndivz / (wlmax - wlmin); + Double_t dw = (wlmax - wlmin) / ndivz; for (Int_t i = 0; i < ndivz; i++) { - zc = fH->GetContourLevel(i); - if (fH->TestBit(TH1::kUserContour) && gPad->GetLogz()) + if (fH) zc = fH->GetContourLevel(i); + else zc = wlmin + i*dw; + if (fH && fH->TestBit(TH1::kUserContour) && gPad->GetLogz()) zc = TMath::Log10(zc); w1 = zc; if (w1 < wlmin) w1 = wlmin; w2 = wlmax; if (i < ndivz - 1) { - zc = fH->GetContourLevel(i + 1); - if (fH->TestBit(TH1::kUserContour) && gPad->GetLogz()) + if (fH) zc = fH->GetContourLevel(i + 1); + else zc = wlmin + (i+1)*dw; + if (fH && fH->TestBit(TH1::kUserContour) && gPad->GetLogz()) zc = TMath::Log10(zc); w2 = zc; } @@ -488,7 +527,7 @@ void TPaletteAxis::Paint(Option_t *) b2 = ymin + (w2 - wlmin) * (ymax - ymin) / ws; } - if (fH->TestBit(TH1::kUserContour)) { + if (fH && fH->TestBit(TH1::kUserContour)) { color = i; } else { color = Int_t(0.01 + (w1 - wlmin) * scale); @@ -500,7 +539,7 @@ void TPaletteAxis::Paint(Option_t *) if (kHorizontal) gPad->PaintBox(b1, ymin, b2, ymax); else gPad->PaintBox(xmin, b1, xmax, b2); // case option "CJUST": put labels directly - if (label) { + if (fH && label) { Double_t lof = fAxis.GetLabelOffset()*(gPad->GetUxmax()-gPad->GetUxmin()); // the following assumes option "S" Double_t tlength = fAxis.GetTickSize() * (gPad->GetUxmax()-gPad->GetUxmin()); @@ -512,17 +551,17 @@ void TPaletteAxis::Paint(Option_t *) } // make sure labels dont overlap if (i == 0 || (b1 - prevlab) > 1.5*lsize_user) { - if (kHorizontal) label->PaintLatex(b1, ymin - lof, 0, lsize, Form("%g", zlab)); - else label->PaintLatex(xmax + lof, b1, 0, lsize, Form("%g", zlab)); + if (kHorizontal) label->PaintLatex(b1, ymin - lof, 0, lsize, TString::Format("%g", zlab)); + else label->PaintLatex(xmax + lof, b1, 0, lsize, TString::Format("%g", zlab)); prevlab = b1; } if (kHorizontal) line->PaintLine(b2, ymin+tlength, b2, ymin); else line->PaintLine(xmax-tlength, b1, xmax, b1); if (i == ndivz-1) { // label + tick at top of axis - if ((b2 - prevlab > 1.5*lsize_user)) { - if (kHorizontal) label->PaintLatex(b2, ymin - lof, 0, lsize, Form("%g",fH->GetMaximum())); - else label->PaintLatex(xmax + lof, b2, 0, lsize, Form("%g",fH->GetMaximum())); + if (fH && (b2 - prevlab > 1.5*lsize_user)) { + if (kHorizontal) label->PaintLatex(b2, ymin - lof, 0, lsize, TString::Format("%g",fH->GetMaximum())); + else label->PaintLatex(xmax + lof, b2, 0, lsize, TString::Format("%g",fH->GetMaximum())); } if (kHorizontal) line->PaintLine(b1, ymin+tlength, b1, ymin); else line->PaintLine(xmax-tlength, b2, xmax, b2); @@ -531,7 +570,9 @@ void TPaletteAxis::Paint(Option_t *) } // Take primary divisions only - Int_t ndiv = fH->GetZaxis()->GetNdivisions(); + Int_t ndiv; + if (fH) ndiv = fH->GetZaxis()->GetNdivisions(); + else ndiv = fAxis.GetNdiv(); Bool_t isOptimized = ndiv>0; Int_t absDiv = abs(ndiv); Int_t maxD = absDiv/1000000; diff --git a/hist/histv7/inc/ROOT/RHist.hxx b/hist/histv7/inc/ROOT/RHist.hxx index cec2e7b3e32fe..6294091a017b7 100644 --- a/hist/histv7/inc/ROOT/RHist.hxx +++ b/hist/histv7/inc/ROOT/RHist.hxx @@ -147,9 +147,24 @@ public: fImpl->FillN(xN, weightN); } + /// For each coordinate in `xN`, add `weightN[i]` to the bin at coordinate + /// `xN[i]`. The sizes of `xN` and `weightN` must be the same. This is more + /// efficient than many separate calls to `Fill()`. + /// Overload for passing initializer lists. + void FillN(std::initializer_list xN, std::initializer_list weightN) noexcept + { + fImpl->FillN(std::span(xN.begin(), xN.end()), std::span(weightN.begin(), weightN.end())); + } + /// Convenience overload: `FillN()` with weight 1. void FillN(const std::span xN) noexcept { fImpl->FillN(xN); } + /// Convenience overload: `FillN()` with weight 1. + /// Overload for passing initializer lists. + void FillN(std::initializer_list xN) noexcept { + fImpl->FillN(std::span(xN.begin(), xN.end())); + } + /// Get the number of entries this histogram was filled with. int64_t GetEntries() const noexcept { return fImpl->GetStat().GetEntries(); } diff --git a/hist/histv7/inc/ROOT/RHistBufferedFill.hxx b/hist/histv7/inc/ROOT/RHistBufferedFill.hxx index b9c8e5d5a08d5..c994a6b23ccdb 100644 --- a/hist/histv7/inc/ROOT/RHistBufferedFill.hxx +++ b/hist/histv7/inc/ROOT/RHistBufferedFill.hxx @@ -17,6 +17,8 @@ #define ROOT7_RHistBufferedFill #include "ROOT/RSpan.hxx" +#include +#include namespace ROOT { namespace Experimental { diff --git a/hist/histv7/inc/ROOT/RHistImpl.hxx b/hist/histv7/inc/ROOT/RHistImpl.hxx index d53ad431bbbd3..ca640b011f555 100644 --- a/hist/histv7/inc/ROOT/RHistImpl.hxx +++ b/hist/histv7/inc/ROOT/RHistImpl.hxx @@ -931,8 +931,8 @@ public: // hyperplane (overflow and regular) and the number of regular bins per // hyperplane on the hyperplanes that have them. // - std::array bins_per_hyperplane; - std::array regular_bins_per_hyperplane; + std::array bins_per_hyperplane{}; + std::array regular_bins_per_hyperplane{}; Internal::RComputeLocalBinsInitialisation()(bins_per_hyperplane, regular_bins_per_hyperplane, fAxes); int curr_bins_per_hyperplane = Internal::RGetNBinsCount()(fAxes); diff --git a/hist/histv7/test/fill.cxx b/hist/histv7/test/fill.cxx index 2bb8b9e24f7fd..cfac57767dd15 100644 --- a/hist/histv7/test/fill.cxx +++ b/hist/histv7/test/fill.cxx @@ -179,9 +179,9 @@ TEST(HistFillTest, FillNCoordsEntries) { ROOT::Experimental::RH1F hist({100, 0., 1}); EXPECT_EQ(0, hist.GetEntries()); - hist.FillN({{0.1111}, {0.2222}, {0.3333}}); + hist.FillN({0.1111, 0.2222, 0.3333}); EXPECT_EQ(3, hist.GetEntries()); - hist.FillN({{0.1111}, {0.3333}}); + hist.FillN({0.1111, 0.3333}); EXPECT_EQ(5, hist.GetEntries()); } @@ -193,12 +193,12 @@ TEST(HistFillTest, FillNCoordsContent) EXPECT_FLOAT_EQ(.0f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(.0f, hist.GetBinContent({0.3333})); - hist.FillN({{0.1111}, {0.2222}, {0.3333}}); + hist.FillN({0.1111, 0.2222, 0.3333}); EXPECT_FLOAT_EQ(1.f, hist.GetBinContent({0.1111})); EXPECT_FLOAT_EQ(1.f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(1.f, hist.GetBinContent({0.3333})); - hist.FillN({{0.1111}, {0.3333}}); + hist.FillN({0.1111, 0.3333}); EXPECT_FLOAT_EQ(2.f, hist.GetBinContent({0.1111})); EXPECT_FLOAT_EQ(1.f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(2.f, hist.GetBinContent({0.3333})); @@ -212,12 +212,12 @@ TEST(HistFillTest, FillNCoordsUncertainty) EXPECT_FLOAT_EQ(.0f, hist.GetBinUncertainty({0.2222})); EXPECT_FLOAT_EQ(.0f, hist.GetBinUncertainty({0.3333})); - hist.FillN({{0.1111}, {0.2222}, {0.3333}}); + hist.FillN({0.1111, 0.2222, 0.3333}); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.1111})); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.2222})); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.3333})); - hist.FillN({{0.1111}, {0.3333}}); + hist.FillN({0.1111, 0.3333}); EXPECT_FLOAT_EQ(std::sqrt(2.f), hist.GetBinUncertainty({0.1111})); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.2222})); EXPECT_FLOAT_EQ(std::sqrt(2.f), hist.GetBinUncertainty({0.3333})); @@ -228,9 +228,9 @@ TEST(HistFillTest, FillNCoordsWeightsEntries) { ROOT::Experimental::RH1F hist({100, 0., 1}); EXPECT_EQ(0, hist.GetEntries()); - hist.FillN({{0.1111}, {0.2222}, {0.3333}}, {.42f, .32f, .52f}); + hist.FillN({0.1111, 0.2222, 0.3333}, {.42f, .32f, .52f}); EXPECT_EQ(3, hist.GetEntries()); - hist.FillN({{0.1111}, {0.3333}}, {.42f, .32f}); + hist.FillN({0.1111, 0.3333}, {.42f, .32f}); EXPECT_EQ(5, hist.GetEntries()); } @@ -242,12 +242,12 @@ TEST(HistFillTest, FillNCoordsWeightsContent) EXPECT_FLOAT_EQ(.0f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(.0f, hist.GetBinContent({0.3333})); - hist.FillN({{0.1111}, {0.2222}, {0.3333}}, {.42f, .32f, .52f}); + hist.FillN({0.1111, 0.2222, 0.3333}, {.42f, .32f, .52f}); EXPECT_FLOAT_EQ(.42f, hist.GetBinContent({0.1111})); EXPECT_FLOAT_EQ(.32f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(.52f, hist.GetBinContent({0.3333})); - hist.FillN({{0.1111}, {0.3333}}, {.42f, .32f}); + hist.FillN({0.1111, 0.3333}, {.42f, .32f}); EXPECT_FLOAT_EQ(.42f + .42f, hist.GetBinContent({0.1111})); EXPECT_FLOAT_EQ(.32f, hist.GetBinContent({0.2222})); EXPECT_FLOAT_EQ(.52f + .32f, hist.GetBinContent({0.3333})); @@ -265,12 +265,12 @@ TEST(HistFillTest, FillNCoordsWeightsUncertainty) float weight2 = .32f; float weight3 = .52f; - hist.FillN({{0.1111}, {0.2222}, {0.3333}}, {weight1, weight2, weight3}); + hist.FillN({0.1111, 0.2222, 0.3333}, {weight1, weight2, weight3}); EXPECT_FLOAT_EQ(std::sqrt(weight1 * weight1), hist.GetBinUncertainty({0.1111})); EXPECT_FLOAT_EQ(std::sqrt(weight2 * weight2), hist.GetBinUncertainty({0.2222})); EXPECT_FLOAT_EQ(std::sqrt(weight3 * weight3), hist.GetBinUncertainty({0.3333})); - hist.FillN({{0.1111}, {0.3333}}, {weight1, weight2}); + hist.FillN({0.1111, 0.3333}, {weight1, weight2}); EXPECT_FLOAT_EQ(std::sqrt((weight1 * weight1) + (weight1 * weight1)), hist.GetBinUncertainty({0.1111})); EXPECT_FLOAT_EQ(std::sqrt(weight2 * weight2), hist.GetBinUncertainty({0.2222})); EXPECT_FLOAT_EQ(std::sqrt((weight3 * weight3) + (weight2 * weight2)), hist.GetBinUncertainty({0.3333})); @@ -565,7 +565,7 @@ TEST(HistFillTest, FillN3DCoordsUncertainty) EXPECT_FLOAT_EQ(.0f, hist.GetBinUncertainty({0.1111, 4.22, 7.33})); EXPECT_FLOAT_EQ(.0f, hist.GetBinUncertainty({0.2222, 4.33, 7.11})); EXPECT_FLOAT_EQ(.0f, hist.GetBinUncertainty({0.3333, 4.11, 7.22})); - + hist.FillN({{0.1111, 4.22, 7.33}, {0.2222, 4.33, 7.11}, {0.3333, 4.11, 7.22}}); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.1111, 4.22, 7.33})); EXPECT_FLOAT_EQ(1.f, hist.GetBinUncertainty({0.2222, 4.33, 7.11})); diff --git a/hist/spectrum/src/TSpectrum.cxx b/hist/spectrum/src/TSpectrum.cxx index 752f3fd2eda31..ca20b405aaa25 100644 --- a/hist/spectrum/src/TSpectrum.cxx +++ b/hist/spectrum/src/TSpectrum.cxx @@ -58,7 +58,7 @@ TSpectrum::TSpectrum() :TNamed("Spectrum", "Miroslav Morhac peak finder") fPositionX = new Double_t[n]; fPositionY = new Double_t[n]; fResolution = 1; - fHistogram = 0; + fHistogram = nullptr; fNPeaks = 0; } @@ -79,7 +79,7 @@ TSpectrum::TSpectrum(Int_t maxpositions, Double_t resolution) fPosition = new Double_t[n]; fPositionX = new Double_t[n]; fPositionY = new Double_t[n]; - fHistogram = 0; + fHistogram = nullptr; fNPeaks = 0; SetResolution(resolution); } @@ -155,11 +155,11 @@ void TSpectrum::SetDeconIterations(Int_t n) TH1 *TSpectrum::Background(const TH1 * h, Int_t numberIterations, Option_t * option) { - if (h == 0) return 0; + if (h == nullptr) return nullptr; Int_t dimension = h->GetDimension(); if (dimension > 1) { Error("Search", "Only implemented for 1-d histograms"); - return 0; + return nullptr; } TString opt = option; opt.ToLower(); @@ -269,7 +269,7 @@ void TSpectrum::Print(Option_t *) const Int_t TSpectrum::Search(const TH1 * hin, Double_t sigma, Option_t * option, Double_t threshold) { - if (hin == 0) return 0; + if (hin == nullptr) return 0; Int_t dimension = hin->GetDimension(); if (dimension > 2) { Error("Search", "Only implemented for 1-d and 2-d histograms"); @@ -1154,7 +1154,7 @@ const char *TSpectrum::Background(Double_t *spectrum, Int_t ssize, for (j = 0; j < ssize; j++) spectrum[j] = working_space[ssize + j]; delete[]working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1213,7 +1213,7 @@ const char* TSpectrum::SmoothMarkov(Double_t *source, int ssize, int averWindow) } if(maxch == 0) { delete [] working_space; - return 0 ; + return nullptr ; } nom = 1; @@ -1261,7 +1261,7 @@ const char* TSpectrum::SmoothMarkov(Double_t *source, int ssize, int averWindow) for(i = 0; i < ssize; i++) source[i] = working_space[i] * area; delete[]working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1588,7 +1588,7 @@ const char *TSpectrum::Deconvolution(Double_t *source, const Double_t *response, for (i = 0; i < ssize; i++) source[i] = area * working_space[ssize + i]; delete[]working_space; - return 0; + return nullptr; } @@ -1768,7 +1768,7 @@ const char *TSpectrum::DeconvolutionRL(Double_t *source, const Double_t *respons for (i = 0; i < ssize; i++) source[i] = working_space[ssize + i]; delete[]working_space; - return 0; + return nullptr; } @@ -2036,7 +2036,7 @@ const char *TSpectrum::Unfolding(Double_t *source, source[i] = 0; } delete[]working_space; - return 0; + return nullptr; } diff --git a/hist/spectrum/src/TSpectrum2.cxx b/hist/spectrum/src/TSpectrum2.cxx index 7b352f0e698d2..35a31cf19a6fa 100644 --- a/hist/spectrum/src/TSpectrum2.cxx +++ b/hist/spectrum/src/TSpectrum2.cxx @@ -64,7 +64,7 @@ TSpectrum2::TSpectrum2() :TNamed("Spectrum", "Miroslav Morhac peak finder") fPositionX = new Double_t[n]; fPositionY = new Double_t[n]; fResolution = 1; - fHistogram = 0; + fHistogram = nullptr; fNPeaks = 0; } @@ -83,7 +83,7 @@ TSpectrum2::TSpectrum2(Int_t maxpositions, Double_t resolution) :TNamed("Spectru fPosition = new Double_t[n]; fPositionX = new Double_t[n]; fPositionY = new Double_t[n]; - fHistogram = 0; + fHistogram = nullptr; fNPeaks = 0; SetResolution(resolution); } @@ -159,7 +159,7 @@ TH1 *TSpectrum2::Background(const TH1 * h, Int_t number_of_iterations, { Error("Background","function not yet implemented: h=%s, iter=%d, option=%sn" , h->GetName(), number_of_iterations, option); - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -208,7 +208,7 @@ void TSpectrum2::Print(Option_t *) const Int_t TSpectrum2::Search(const TH1 * hin, Double_t sigma, Option_t * option, Double_t threshold) { - if (hin == 0) + if (hin == nullptr) return 0; Int_t dimension = hin->GetDimension(); if (dimension != 2) { @@ -539,7 +539,7 @@ const char *TSpectrum2::Background(Double_t **spectrum, for (i = 0; i < ssizex; i++) delete[]working_space[i]; delete[]working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -607,7 +607,7 @@ const char* TSpectrum2::SmoothMarkov(Double_t **source, Int_t ssizex, Int_t ssiz for (i = 0; i < ssizex; i++) delete[]working_space[i]; delete [] working_space; - return 0; + return nullptr; } nom = 0; @@ -762,7 +762,7 @@ const char* TSpectrum2::SmoothMarkov(Double_t **source, Int_t ssizex, Int_t ssiz for (i = 0; i < ssizex; i++) delete[]working_space[i]; delete[]working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -995,7 +995,7 @@ const char *TSpectrum2::Deconvolution(Double_t **source, Double_t **resp, for (i = 0; i < ssizex; i++) delete[]working_space[i]; delete[]working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// diff --git a/hist/spectrum/src/TSpectrum2Fit.cxx b/hist/spectrum/src/TSpectrum2Fit.cxx index 01d3de69e0904..3478ac34ee2a8 100644 --- a/hist/spectrum/src/TSpectrum2Fit.cxx +++ b/hist/spectrum/src/TSpectrum2Fit.cxx @@ -48,29 +48,29 @@ TSpectrum2Fit::TSpectrum2Fit() :TNamed("Spectrum2Fit", "Miroslav Morhac peak fit fFitTaylor = kFitTaylorOrderFirst; fAlpha = 1; fChi = 0; - fPositionInitX = 0; - fPositionCalcX = 0; - fPositionErrX = 0; - fPositionInitY = 0; - fPositionCalcY = 0; - fPositionErrY = 0; - fPositionInitX1 = 0; - fPositionCalcX1 = 0; - fPositionErrX1 = 0; - fPositionInitY1 = 0; - fPositionCalcY1 = 0; - fPositionErrY1 = 0; - fAmpInit = 0; - fAmpCalc = 0; - fAmpErr = 0; - fAmpInitX1 = 0; - fAmpCalcX1 = 0; - fAmpErrX1 = 0; - fAmpInitY1 = 0; - fAmpCalcY1 = 0; - fAmpErrY1 = 0; - fVolume = 0; - fVolumeErr = 0; + fPositionInitX = nullptr; + fPositionCalcX = nullptr; + fPositionErrX = nullptr; + fPositionInitY = nullptr; + fPositionCalcY = nullptr; + fPositionErrY = nullptr; + fPositionInitX1 = nullptr; + fPositionCalcX1 = nullptr; + fPositionErrX1 = nullptr; + fPositionInitY1 = nullptr; + fPositionCalcY1 = nullptr; + fPositionErrY1 = nullptr; + fAmpInit = nullptr; + fAmpCalc = nullptr; + fAmpErr = nullptr; + fAmpInitX1 = nullptr; + fAmpCalcX1 = nullptr; + fAmpErrX1 = nullptr; + fAmpInitY1 = nullptr; + fAmpCalcY1 = nullptr; + fAmpErrY1 = nullptr; + fVolume = nullptr; + fVolumeErr = nullptr; fSigmaInitX = 2; fSigmaCalcX = 0; fSigmaErrX = 0; @@ -113,13 +113,13 @@ TSpectrum2Fit::TSpectrum2Fit() :TNamed("Spectrum2Fit", "Miroslav Morhac peak fit fAyInit = 0; fAyCalc = 0; fAyErr = 0; - fFixPositionX = 0; - fFixPositionY = 0; - fFixPositionX1 = 0; - fFixPositionY1 = 0; - fFixAmp = 0; - fFixAmpX1 = 0; - fFixAmpY1 = 0; + fFixPositionX = nullptr; + fFixPositionY = nullptr; + fFixPositionX1 = nullptr; + fFixPositionY1 = nullptr; + fFixAmp = nullptr; + fFixAmpX1 = nullptr; + fFixAmpY1 = nullptr; fFixSigmaX = false; fFixSigmaY = false; fFixRo = true; diff --git a/hist/spectrum/src/TSpectrum2Transform.cxx b/hist/spectrum/src/TSpectrum2Transform.cxx index 475357cdf76d0..09911752d4467 100644 --- a/hist/spectrum/src/TSpectrum2Transform.cxx +++ b/hist/spectrum/src/TSpectrum2Transform.cxx @@ -1749,7 +1749,7 @@ void TSpectrum2Transform::Transform(const Double_t **fSource, Double_t **fDest) { Int_t i, j; Int_t size; - Double_t *working_vector = 0, **working_matrix = 0; + Double_t *working_vector = nullptr, **working_matrix = nullptr; size = (Int_t) TMath::Max(fSizeX, fSizeY); switch (fTransformType) { case kTransformHaar: @@ -2110,7 +2110,7 @@ void TSpectrum2Transform::FilterZonal(const Double_t **fSource, Double_t **fDest Int_t i, j; Double_t a, old_area = 0, new_area = 0; Int_t size; - Double_t *working_vector = 0, **working_matrix = 0; + Double_t *working_vector = nullptr, **working_matrix = nullptr; size = (Int_t) TMath::Max(fSizeX, fSizeY); switch (fTransformType) { case kTransformHaar: @@ -2441,7 +2441,7 @@ void TSpectrum2Transform::Enhance(const Double_t **fSource, Double_t **fDest) Int_t i, j; Double_t a, old_area = 0, new_area = 0; Int_t size; - Double_t *working_vector = 0, **working_matrix = 0; + Double_t *working_vector = nullptr, **working_matrix = nullptr; size = (Int_t) TMath::Max(fSizeX, fSizeY); switch (fTransformType) { case kTransformHaar: diff --git a/hist/spectrum/src/TSpectrum3.cxx b/hist/spectrum/src/TSpectrum3.cxx index b90237d1f3505..30dd099b48089 100644 --- a/hist/spectrum/src/TSpectrum3.cxx +++ b/hist/spectrum/src/TSpectrum3.cxx @@ -119,7 +119,7 @@ const char *TSpectrum3::Background(const TH1 * h, Int_t number_of_iterations, { Error("Background","function not yet implemented: h=%s, iter=%d, option=%sn" , h->GetName(), number_of_iterations, option); - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -162,7 +162,7 @@ void TSpectrum3::Print(Option_t *) const Int_t TSpectrum3::Search(const TH1 * hin, Double_t sigma, Option_t * option, Double_t threshold) { - if (hin == 0) + if (hin == nullptr) return 0; Int_t dimension = hin->GetDimension(); if (dimension != 3) { @@ -764,7 +764,7 @@ const char *TSpectrum3::Background(Double_t***spectrum, delete[] working_space[i]; } delete[] working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -894,7 +894,7 @@ const char* TSpectrum3::SmoothMarkov(Double_t***source, Int_t ssizex, Int_t ssiz delete[] working_space[i]; } delete [] working_space; - return 0; + return nullptr; } nom = 0; @@ -1407,7 +1407,7 @@ const char* TSpectrum3::SmoothMarkov(Double_t***source, Int_t ssizex, Int_t ssiz delete[] working_space[i]; } delete[] working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1802,7 +1802,7 @@ const char *TSpectrum3::Deconvolution(Double_t***source, const Double_t***resp, delete[] working_space[i]; } delete [] working_space; - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// diff --git a/hist/spectrum/src/TSpectrumFit.cxx b/hist/spectrum/src/TSpectrumFit.cxx index 0ad7527058530..e6f1e4220ca5c 100644 --- a/hist/spectrum/src/TSpectrumFit.cxx +++ b/hist/spectrum/src/TSpectrumFit.cxx @@ -46,16 +46,16 @@ TSpectrumFit::TSpectrumFit() :TNamed("SpectrumFit", "Miroslav Morhac peak fitter fFitTaylor = kFitTaylorOrderFirst; fAlpha =1; fChi = 0; - fPositionInit = 0; - fPositionCalc = 0; - fPositionErr = 0; - fFixPosition = 0; - fAmpInit = 0; - fAmpCalc = 0; - fAmpErr = 0; - fFixAmp = 0; - fArea = 0; - fAreaErr = 0; + fPositionInit = nullptr; + fPositionCalc = nullptr; + fPositionErr = nullptr; + fFixPosition = nullptr; + fAmpInit = nullptr; + fAmpCalc = nullptr; + fAmpErr = nullptr; + fFixAmp = nullptr; + fArea = nullptr; + fAreaErr = nullptr; fSigmaInit = 2; fSigmaCalc = 1; fSigmaErr = 0; diff --git a/hist/spectrum/src/TSpectrumTransform.cxx b/hist/spectrum/src/TSpectrumTransform.cxx index 331c28d542a9e..8444f817a506b 100644 --- a/hist/spectrum/src/TSpectrumTransform.cxx +++ b/hist/spectrum/src/TSpectrumTransform.cxx @@ -743,7 +743,7 @@ void TSpectrumTransform::Transform(const Double_t *source, Double_t *destVector) int i, j=0, k = 1, m, l; Double_t val; Double_t a, b, pi = 3.14159265358979323846; - Double_t *working_space = 0; + Double_t *working_space = nullptr; if (fTransformType >= kTransformFourierWalsh && fTransformType <= kTransformSinHaar) { if (fTransformType >= kTransformCosWalsh) fDegree += 1; @@ -1270,7 +1270,7 @@ void TSpectrumTransform::FilterZonal(const Double_t *source, Double_t *destVecto { int i, j=0, k = 1, m, l; Double_t val; - Double_t *working_space = 0; + Double_t *working_space = nullptr; Double_t a, b, pi = 3.14159265358979323846, old_area, new_area; if (fTransformType >= kTransformFourierWalsh && fTransformType <= kTransformSinHaar) { if (fTransformType >= kTransformCosWalsh) @@ -1780,7 +1780,7 @@ void TSpectrumTransform::Enhance(const Double_t *source, Double_t *destVector) { int i, j=0, k = 1, m, l; Double_t val; - Double_t *working_space = 0; + Double_t *working_space = nullptr; Double_t a, b, pi = 3.14159265358979323846, old_area, new_area; if (fTransformType >= kTransformFourierWalsh && fTransformType <= kTransformSinHaar) { if (fTransformType >= kTransformCosWalsh) diff --git a/hist/spectrumpainter/src/TSpectrum2Painter.cxx b/hist/spectrumpainter/src/TSpectrum2Painter.cxx index 17571179d52a4..a70732b7d7a9c 100644 --- a/hist/spectrumpainter/src/TSpectrum2Painter.cxx +++ b/hist/spectrumpainter/src/TSpectrum2Painter.cxx @@ -161,7 +161,7 @@ TSpectrum2Painter::TSpectrum2Painter(TH2* h2, Int_t bs) fChanlineEnDis = kChannelGridNotDrawn; // Decides whether the channel lines // (grid) are shown. fChanlineColor = kRed; // Color of channel marks. - fNewColor = 0; + fNewColor = nullptr; fEnvelope = new Short_t [fMaximumXScreenResolution]; fEnvelopeContour = new Short_t [fMaximumXScreenResolution]; for (i=0;iGetRowIndexArray(); @@ -434,7 +434,7 @@ Double_t TUnfold::DoUnfold(void) // get error matrix on x // fDXDY * Vyy * fDXDY# TMatrixDSparse *fDXDYVyy = MultiplyMSparseMSparse(fDXDY,fVyy); - fVxx = MultiplyMSparseMSparseTranspVector(fDXDYVyy,fDXDY,0); + fVxx = MultiplyMSparseMSparseTranspVector(fDXDYVyy,fDXDY,nullptr); DeleteMatrix(&fDXDYVyy); @@ -498,13 +498,13 @@ Double_t TUnfold::DoUnfold(void) fDXDAM[0]=new TMatrixDSparse(*fE); fDXDAM[1]=new TMatrixDSparse(*fDXDY); // create a copy fDXDAZ[0]=VyyinvDy; // instead of deleting VyyinvDy - VyyinvDy=0; + VyyinvDy=nullptr; fDXDAZ[1]=new TMatrixDSparse(*fX); // create a copy if(fConstraint != kEConstraintNone) { // add correction to fDXDAM[0] TMatrixDSparse *temp1=MultiplyMSparseMSparseTranspVector - (Eepsilon,Eepsilon,0); + (Eepsilon,Eepsilon,nullptr); AddMSparse(fDXDAM[0], -one_over_epsEeps,temp1); DeleteMatrix(&temp1); // add correction to fDXDAZ[0] @@ -860,8 +860,8 @@ TMatrixDSparse *TUnfold::MultiplyMSparseMSparseTranspVector if(rows_m2[j](v); - const Int_t *v_rows=0; - const Double_t *v_data=0; + const Int_t *v_rows=nullptr; + const Double_t *v_data=nullptr; if(v_sparse) { v_rows=v_sparse->GetRowIndexArray(); v_data=v_sparse->GetMatrixArray(); @@ -1039,7 +1039,7 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos Fatal("InvertMSparseSymmPos", "Matrix has %d negative elements on the diagonal", nError); delete[] isZero; - return 0; + return nullptr; } // reorder matrix such that the largest block of zeros is swapped @@ -1232,7 +1232,7 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos //==================================================== // invert D2 Int_t nD2=iBlock-iDiagonal; - TMatrixDSparse *D2inv=0; + TMatrixDSparse *D2inv=nullptr; if((rNumEl>=0)&&(nD2>0)) { Double_t *D2inv_data=new Double_t[nD2]; Int_t *D2inv_col=new Int_t[nD2]; @@ -1265,9 +1265,9 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos // invert F Int_t nF=A->GetNrows()-iBlock; - TMatrixDSparse *Finv=0; - TMatrixDSparse *B=0; - TMatrixDSparse *minusBD2inv=0; + TMatrixDSparse *Finv=nullptr; + TMatrixDSparse *B=nullptr; + TMatrixDSparse *minusBD2inv=nullptr; if((rNumEl>=0)&&(nF>0)&&((nD2==0)||D2inv)) { // construct matrices F and B Int_t nFmax=nF*nF; @@ -1303,7 +1303,7 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos } } } - TMatrixDSparse *F=0; + TMatrixDSparse *F=nullptr; if(FnumEl) { #ifndef FORCE_EIGENVALUE_DECOMPOSITION F=CreateSparseMatrix(nF,nF,FnumEl,F_row,F_col,F_data); @@ -1332,7 +1332,7 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos } if(minusBD2inv && F) { TMatrixDSparse *minusBD2invBt= - MultiplyMSparseMSparseTranspVector(minusBD2inv,B,0); + MultiplyMSparseMSparseTranspVector(minusBD2inv,B,nullptr); AddMSparse(F,1.,minusBD2invBt); DeleteMatrix(&minusBD2invBt); } @@ -1423,11 +1423,11 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos // G = (F^-1) (-B/D2) // E = 1/D2 + (-B#/D2) G) - TMatrixDSparse *G=0; + TMatrixDSparse *G=nullptr; if(Finv && minusBD2inv) { G=MultiplyMSparseMSparse(Finv,minusBD2inv); } - TMatrixDSparse *E=0; + TMatrixDSparse *E=nullptr; if(D2inv) E=new TMatrixDSparse(*D2inv); if(G && minusBD2inv) { TMatrixDSparse *minusBD2invTransG= @@ -1615,7 +1615,7 @@ TMatrixDSparse *TUnfold::InvertMSparseSymmPos TMatrixDSparse *r=(rNumEl>=0) ? CreateSparseMatrix(A->GetNrows(),A->GetNrows(),rNumEl, - rEl_row,rEl_col,rEl_data) : 0; + rEl_row,rEl_col,rEl_data) : nullptr; delete [] rEl_data; delete [] rEl_col; delete [] rEl_row; diff --git a/hist/unfold/src/TUnfoldBinning.cxx b/hist/unfold/src/TUnfoldBinning.cxx index db2a7e0c879d3..ab50e9426230c 100644 --- a/hist/unfold/src/TUnfoldBinning.cxx +++ b/hist/unfold/src/TUnfoldBinning.cxx @@ -147,10 +147,10 @@ TUnfoldBinning::~TUnfoldBinning(void) void TUnfoldBinning::Initialize(Int_t nBins) { - parentNode=0; - childNode=0; - nextNode=0; - prevNode=0; + parentNode=nullptr; + childNode=nullptr; + nextNode=nullptr; + prevNode=nullptr; fAxisList=new TObjArray(); fAxisLabelList=new TObjArray(); fAxisList->SetOwner(); @@ -158,7 +158,7 @@ void TUnfoldBinning::Initialize(Int_t nBins) fHasUnderflow=0; fHasOverflow=0; fDistributionSize=nBins; - fBinFactorFunction=0; + fBinFactorFunction=nullptr; fBinFactorConstant=1.0; } @@ -262,7 +262,7 @@ TUnfoldBinning *TUnfoldBinning::AddBinning TUnfoldBinning *TUnfoldBinning::AddBinning(TUnfoldBinning *binning) { - TUnfoldBinning *r=0; + TUnfoldBinning *r=nullptr; if(binning->GetParentNode()) { Error("AddBinning", "binning \"%s\" already has parent \"%s\", can not be added to %s", @@ -541,7 +541,7 @@ void TUnfoldBinning::SetBinFactorFunction TUnfoldBinning const *TUnfoldBinning::FindNode(char const *name) const { - TUnfoldBinning const *r=0; + TUnfoldBinning const *r=nullptr; if((!name)||(!TString(GetName()).CompareTo(name))) { r=this; } @@ -747,7 +747,7 @@ TH1 *TUnfoldBinning::CreateHistogram axisSteering); const TUnfoldBinning *neNode=GetNonemptyNode(); TString title=BuildHistogramTitle(histogramName,histogramTitle,axisList); - TH1 *r=0; + TH1 *r=nullptr; if(nDim>0) { const TVectorD *axisBinsX= neNode->GetDistributionBinning(axisList[0]); @@ -807,7 +807,7 @@ TH2D *TUnfoldBinning::CreateErrorMatrixHistogram Int_t nDim=GetTHxxBinning(originalAxisBinning ? 1 : 0,nBin,axisList, axisSteering); TString title=BuildHistogramTitle(histogramName,histogramTitle,axisList); - TH2D *r=0; + TH2D *r=nullptr; if(nDim==1) { const TVectorD *axisBinsX=(TVectorD const *) GetNonemptyNode()->fAxisList->At(axisList[0]); @@ -849,11 +849,11 @@ TH2D *TUnfoldBinning::CreateHistogramOfMigrations { Int_t nBinX[3],axisListX[3]; Int_t nDimX= - xAxis->GetTHxxBinning(originalXAxisBinning ? 1 : 0,nBinX,axisListX,0); + xAxis->GetTHxxBinning(originalXAxisBinning ? 1 : 0,nBinX,axisListX,nullptr); const TUnfoldBinning *neNodeX=xAxis->GetNonemptyNode(); Int_t nBinY[3],axisListY[3]; Int_t nDimY= - yAxis->GetTHxxBinning(originalYAxisBinning ? 1 : 0,nBinY,axisListY,0); + yAxis->GetTHxxBinning(originalYAxisBinning ? 1 : 0,nBinY,axisListY,nullptr); const TUnfoldBinning *neNodeY=yAxis->GetNonemptyNode(); TString title=xAxis->BuildHistogramTitle2D (histogramName,histogramTitle,axisListX[0],yAxis,axisListY[0]); @@ -925,7 +925,7 @@ Int_t TUnfoldBinning::GetTHxxBinning const TUnfoldBinning *TUnfoldBinning::GetNonemptyNode(void) const { - const TUnfoldBinning *r=GetDistributionNumberOfBins()>0 ? this : 0; + const TUnfoldBinning *r=GetDistributionNumberOfBins()>0 ? this : nullptr; for(TUnfoldBinning const *child=GetChildNode();child; child=child->GetNextNode()) { const TUnfoldBinning *c=child->GetNonemptyNode(); @@ -935,7 +935,7 @@ const TUnfoldBinning *TUnfoldBinning::GetNonemptyNode(void) const } else { if(c) { // multiple nodes found - r=0; + r=nullptr; break; } } @@ -1085,7 +1085,7 @@ Int_t TUnfoldBinning::FillBinMap1D Int_t axisBins[3],axisList[3]; Int_t nDim=GetTHxxBinningSingleNode(3,axisBins,axisList,axisSteering); if((nDim==1)|| !GetDistributionDimension()) { - r+=FillBinMapSingleNode(0,r,0,0,axisSteering,binMap); + r+=FillBinMapSingleNode(nullptr,r,0,nullptr,axisSteering,binMap); } else { Error("FillBinMap1D","distribution %s with steering=%s is not 1D", (char *)GetName(),axisSteering); @@ -1176,7 +1176,7 @@ Int_t TUnfoldBinning::FillBinMapRecursive (Int_t startBin,const char *axisSteering,Int_t *binMap) const { Int_t nbin=0; - nbin = FillBinMapSingleNode(0,startBin,0,0,axisSteering,binMap); + nbin = FillBinMapSingleNode(nullptr,startBin,0,nullptr,axisSteering,binMap); for(TUnfoldBinning const *child=GetChildNode();child; child=child->GetNextNode()) { nbin += child->FillBinMapRecursive(startBin+nbin,axisSteering,binMap); @@ -1376,10 +1376,10 @@ TH1 *TUnfoldBinning::ExtractHistogram const TH2 *globalBinsEmatrix,Bool_t originalAxisBinning, const char *axisSteering) const { - Int_t *binMap=0; - TH1 *r=CreateHistogram(histogramName,originalAxisBinning,&binMap,0, + Int_t *binMap=nullptr; + TH1 *r=CreateHistogram(histogramName,originalAxisBinning,&binMap,nullptr, axisSteering); - if(!r) return 0; + if(!r) return nullptr; TUnfoldBinning const *root=GetRootNode(); Int_t nMax=-1; for(Int_t iSrc=root->GetStartBin();iSrcGetEndBin();iSrc++) { @@ -1387,7 +1387,7 @@ TH1 *TUnfoldBinning::ExtractHistogram } if(nMax<0) { delete r; - r=0; + r=nullptr; } else { TVectorD eSquared(nMax+1); for(Int_t iSrc=root->GetStartBin();iSrcGetEndBin();iSrc++) { @@ -2083,7 +2083,7 @@ Int_t TUnfoldBinning::ToGlobalBin TUnfoldBinning const *TUnfoldBinning::ToAxisBins (Int_t globalBin,Int_t *axisBins) const { - TUnfoldBinning const *r=0; + TUnfoldBinning const *r=nullptr; if((globalBin>=GetStartBin())&&(globalBinGetNextNode()) { diff --git a/hist/unfold/src/TUnfoldBinningXML.cxx b/hist/unfold/src/TUnfoldBinningXML.cxx index 6e77cded51eb3..971ee1e75b0fd 100644 --- a/hist/unfold/src/TUnfoldBinningXML.cxx +++ b/hist/unfold/src/TUnfoldBinningXML.cxx @@ -189,9 +189,9 @@ void TUnfoldBinningXML::WriteDTD(const char *file) { TUnfoldBinningXML *TUnfoldBinningXML::ImportXML (const TXMLDocument *document,const char *name) { - TUnfoldBinningXML *r=0; + TUnfoldBinningXML *r=nullptr; TXMLNode *root=document->GetRootNode(); - TXMLNode *binningNode=0; + TXMLNode *binningNode=nullptr; if(root && (!TString(root->GetNodeName()).CompareTo("TUnfoldBinning")) && (root->GetNodeType()==TXMLNode::kXMLElementNode)) { // loop over all "BinningNode" entities @@ -231,11 +231,11 @@ TUnfoldBinningXML *TUnfoldBinningXML::ImportXML TUnfoldBinningXML *TUnfoldBinningXML::ImportXMLNode (TXMLNode *node) { - const char *name=0; + const char *name=nullptr; Double_t factor=1.0; - TUnfoldBinningXML *r=0; + TUnfoldBinningXML *r=nullptr; Int_t nBins=0; - const char *binNames=0; + const char *binNames=nullptr; TIter i1 = node->GetAttributes()->MakeIterator(); TXMLAttr *attr; // extract name and global factor @@ -275,7 +275,7 @@ TUnfoldBinningXML *TUnfoldBinningXML::ImportXMLNode if(binName->GetNodeType()==TXMLNode::kXMLElementNode && !TString(binName->GetNodeName()).CompareTo("BinLabel")) { TIter i3 = binName->GetAttributes()->MakeIterator(); - const char *binLabelName=0; + const char *binLabelName=nullptr; Int_t index=0; while((attr=(TXMLAttr *)i3.Next())) { TString attName(attr->GetName()); @@ -315,7 +315,7 @@ TUnfoldBinningXML *TUnfoldBinningXML::ImportXMLNode r->AddAxisXML(node); // import per-bin normalisation factors if there are any - TVectorD *perBinFactors=0; + TVectorD *perBinFactors=nullptr; for(TXMLNode *child=node->GetChildren();child; child=child->GetNextNode()) { // unconnected bins: children are of type "Bins" @@ -350,7 +350,7 @@ TUnfoldBinningXML *TUnfoldBinningXML::ImportXMLNode " TUnfoldBinning=%s expected %d found %d", r->GetName(),length,nread); delete perBinFactors; - perBinFactors=0; + perBinFactors=nullptr; } } } @@ -380,7 +380,7 @@ TUnfoldBinningXML *TUnfoldBinningXML::ImportXMLNode /// find axis if there is one void TUnfoldBinningXML::AddAxisXML(TXMLNode *node) { - TXMLNode *axis=0; + TXMLNode *axis=nullptr; for(TXMLNode *child=node->GetChildren();child; child=child->GetNextNode()) { if(child->GetNodeType()==TXMLNode::kXMLElementNode) { @@ -389,7 +389,7 @@ void TUnfoldBinningXML::AddAxisXML(TXMLNode *node) { } } if(axis) { - const char *axisName=0; + const char *axisName=nullptr; TArrayD binEdges(1); TIter i1 = axis->GetAttributes()->MakeIterator(); TXMLAttr *attr; diff --git a/hist/unfold/src/TUnfoldDensity.cxx b/hist/unfold/src/TUnfoldDensity.cxx index 612dad6630c2a..579e0a40b031d 100644 --- a/hist/unfold/src/TUnfoldDensity.cxx +++ b/hist/unfold/src/TUnfoldDensity.cxx @@ -176,11 +176,11 @@ TUnfoldDensity::~TUnfoldDensity(void) TUnfoldDensity::TUnfoldDensity(void) { - fConstOutputBins=0; - fConstInputBins=0; - fOwnedOutputBins=0; - fOwnedInputBins=0; - fRegularisationConditions=0; + fConstOutputBins=nullptr; + fConstInputBins=nullptr; + fOwnedOutputBins=nullptr; + fOwnedInputBins=nullptr; + fRegularisationConditions=nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -221,10 +221,10 @@ TUnfoldDensity::TUnfoldDensity const char *regularisationAxisSteering) : TUnfoldSys(hist_A,histmap,kRegModeNone,constraint) { - fRegularisationConditions=0; + fRegularisationConditions=nullptr; // set up binning schemes fConstOutputBins = outputBins; - fOwnedOutputBins = 0; + fOwnedOutputBins = nullptr; TAxis const *genAxis,*detAxis; if(histmap==kHistMapOutputHoriz) { genAxis=hist_A->GetXaxis(); @@ -246,7 +246,7 @@ TUnfoldDensity::TUnfoldDensity "Invalid output binning scheme (node is not the root node)"); } fConstInputBins = inputBins; - fOwnedInputBins = 0; + fOwnedInputBins = nullptr; if(!fConstInputBins) { // underflow and overflow are not included in the binning scheme // They are still used to count events which have not been reconstructed @@ -661,7 +661,7 @@ TH1 *TUnfoldDensity::GetOutput Bool_t useAxisBinning) const { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -693,7 +693,7 @@ TH1 *TUnfoldDensity::GetBias Bool_t useAxisBinning) const { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -725,13 +725,13 @@ TH1 *TUnfoldDensity::GetFoldedOutput Bool_t useAxisBinning,Bool_t addBgr) const { TUnfoldBinning const *binning=fConstInputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { TUnfoldSys::GetFoldedOutput(r,binMap); if(addBgr) { - TUnfoldSys::GetBackground(r,0,binMap,0,kFALSE); + TUnfoldSys::GetBackground(r,nullptr,binMap,0,kFALSE); } } if(binMap) delete [] binMap; @@ -761,7 +761,7 @@ TH1 *TUnfoldDensity::GetBackground Int_t includeError) const { TUnfoldBinning const *binning=fConstInputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -791,7 +791,7 @@ TH1 *TUnfoldDensity::GetInput Bool_t useAxisBinning) const { TUnfoldBinning const *binning=fConstInputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -823,16 +823,16 @@ TH1 *TUnfoldDensity::GetRhoItotal const char *distributionName,const char *axisSteering, Bool_t useAxisBinning,TH2 **ematInv) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { - TH2 *invEmat=0; + TH2 *invEmat=nullptr; if(ematInv) { if(r->GetDimension()==1) { TString ematName(histogramName); ematName += "_inverseEMAT"; - Int_t *binMap2D=0; + Int_t *binMap2D=nullptr; invEmat=binning->CreateErrorMatrixHistogram (ematName,useAxisBinning,&binMap2D,histogramTitle, axisSteering); @@ -874,16 +874,16 @@ TH1 *TUnfoldDensity::GetRhoIstatbgr const char *distributionName,const char *axisSteering, Bool_t useAxisBinning,TH2 **ematInv) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { - TH2 *invEmat=0; + TH2 *invEmat=nullptr; if(ematInv) { if(r->GetDimension()==1) { TString ematName(histogramName); ematName += "_inverseEMAT"; - Int_t *binMap2D=0; + Int_t *binMap2D=nullptr; invEmat=binning->CreateErrorMatrixHistogram (ematName,useAxisBinning,&binMap2D,histogramTitle, axisSteering); @@ -922,13 +922,13 @@ TH1 *TUnfoldDensity::GetDeltaSysSource const char *histogramTitle,const char *distributionName, const char *axisSteering,Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { if(!TUnfoldSys::GetDeltaSysSource(r,source,binMap)) { delete r; - r=0; + r=nullptr; } } if(binMap) delete [] binMap; @@ -956,13 +956,13 @@ TH1 *TUnfoldDensity::GetDeltaSysBackgroundScale const char *histogramTitle,const char *distributionName, const char *axisSteering,Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { if(!TUnfoldSys::GetDeltaSysBackgroundScale(r,bgrSource,binMap)) { delete r; - r=0; + r=nullptr; } } if(binMap) delete [] binMap; @@ -989,13 +989,13 @@ TH1 *TUnfoldDensity::GetDeltaSysTau const char *distributionName,const char *axisSteering,Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH1 *r=binning->CreateHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { if(!TUnfoldSys::GetDeltaSysTau(r,binMap)) { delete r; - r=0; + r=nullptr; } } if(binMap) delete [] binMap; @@ -1074,7 +1074,7 @@ TH2 *TUnfoldDensity::GetEmatrixSysUncorr Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH2 *r=binning->CreateErrorMatrixHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -1105,7 +1105,7 @@ TH2 *TUnfoldDensity::GetEmatrixSysBackgroundUncorr const char *axisSteering,Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH2 *r=binning->CreateErrorMatrixHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -1136,7 +1136,7 @@ TH2 *TUnfoldDensity::GetEmatrixInput Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH2 *r=binning->CreateErrorMatrixHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -1188,7 +1188,7 @@ TH2 *TUnfoldDensity::GetEmatrixTotal Bool_t useAxisBinning) { TUnfoldBinning const *binning=fConstOutputBins->FindNode(distributionName); - Int_t *binMap=0; + Int_t *binMap=nullptr; TH2 *r=binning->CreateErrorMatrixHistogram (histogramName,useAxisBinning,&binMap,histogramTitle,axisSteering); if(r) { @@ -1219,7 +1219,7 @@ TH2 *TUnfoldDensity::GetL "remove invalid scheme of regularisation conditions %d %d", fRegularisationConditions->GetEndBin(),fL->GetNrows()); delete fRegularisationConditions; - fRegularisationConditions=0; + fRegularisationConditions=nullptr; } if(!fRegularisationConditions) { fRegularisationConditions=new TUnfoldBinning("regularisation",fL->GetNrows()); @@ -1259,14 +1259,14 @@ TH1 *TUnfoldDensity::GetLxMinusBias "remove invalid scheme of regularisation conditions %d %d", fRegularisationConditions->GetEndBin(),fL->GetNrows()); delete fRegularisationConditions; - fRegularisationConditions=0; + fRegularisationConditions=nullptr; } if(!fRegularisationConditions) { fRegularisationConditions=new TUnfoldBinning("regularisation",fL->GetNrows()); Warning("GetLxMinusBias","create flat regularisation conditions scheme"); } TH1 *r=fRegularisationConditions->CreateHistogram - (histogramName,kFALSE,0,histogramTitle); + (histogramName,kFALSE,nullptr,histogramTitle); const Int_t *Ldx_rows=Ldx->GetRowIndexArray(); const Double_t *Ldx_data=Ldx->GetMatrixArray(); for(Int_t row=0;rowGetNrows();row++) { @@ -1682,13 +1682,13 @@ Double_t TUnfoldDensity::GetScanVariable name += ","; if(axisSteering) name += axisSteering; name += ")"; - TH1 *rhoi=0; + TH1 *rhoi=nullptr; if((mode==kEScanTauRhoAvg)||(mode==kEScanTauRhoMax)|| (mode==kEScanTauRhoSquareAvg)) { - rhoi=GetRhoIstatbgr(name,0,distribution,axisSteering,kFALSE); + rhoi=GetRhoIstatbgr(name,nullptr,distribution,axisSteering,kFALSE); } else if((mode==kEScanTauRhoAvgSys)||(mode==kEScanTauRhoMaxSys)|| (mode==kEScanTauRhoSquareAvgSys)) { - rhoi=GetRhoItotal(name,0,distribution,axisSteering,kFALSE); + rhoi=GetRhoItotal(name,nullptr,distribution,axisSteering,kFALSE); } if(rhoi) { Double_t sum=0.0; diff --git a/hist/unfold/src/TUnfoldSys.cxx b/hist/unfold/src/TUnfoldSys.cxx index 1e89445cdec60..1b1a9aa561060 100644 --- a/hist/unfold/src/TUnfoldSys.cxx +++ b/hist/unfold/src/TUnfoldSys.cxx @@ -408,7 +408,7 @@ void TUnfoldSys::DoBackgroundSubtraction(void) } } delete[] usedBin; - usedBin=0; + usedBin=nullptr; // convert to sparse matrix fVyy=new TMatrixDSparse(vyy); @@ -449,9 +449,9 @@ Int_t TUnfoldSys::SetInput(const TH1 *hist_y,Double_t scaleBias, Int_t r=TUnfold::SetInput(hist_y,scaleBias,oneOverZeroError,hist_vyy, hist_vyy_inv); fYData=fY; - fY=0; + fY=nullptr; fVyyData=fVyy; - fVyy=0; + fVyy=nullptr; DoBackgroundSubtraction(); return r; @@ -586,9 +586,9 @@ void TUnfoldSys::GetBackground void TUnfoldSys::InitTUnfoldSys(void) { // input - fDAinRelSq = 0; - fDAinColRelSq = 0; - fAoutside = 0; + fDAinRelSq = nullptr; + fDAinColRelSq = nullptr; + fAoutside = nullptr; fBgrIn = new TMap(); fBgrErrUncorrInSq = new TMap(); fBgrErrScaleIn = new TMap(); @@ -598,16 +598,16 @@ void TUnfoldSys::InitTUnfoldSys(void) fBgrErrScaleIn->SetOwnerKeyValue(); fSysIn->SetOwnerKeyValue(); // results - fEmatUncorrX = 0; - fEmatUncorrAx = 0; + fEmatUncorrX = nullptr; + fEmatUncorrAx = nullptr; fDeltaCorrX = new TMap(); fDeltaCorrAx = new TMap(); fDeltaCorrX->SetOwnerKeyValue(); fDeltaCorrAx->SetOwnerKeyValue(); - fDeltaSysTau = 0; + fDeltaSysTau = nullptr; fDtau=0.0; - fYData=0; - fVyyData=0; + fYData=nullptr; + fVyyData=nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -634,7 +634,7 @@ void TUnfoldSys::PrepareSysError(void) if(!fEmatUncorrX) { fEmatUncorrX=PrepareUncorrEmat(GetDXDAM(0),GetDXDAM(1)); } - TMatrixDSparse *AM0=0,*AM1=0; + TMatrixDSparse *AM0=nullptr,*AM1=nullptr; if(!fEmatUncorrAx) { if(!AM0) AM0=MultiplyMSparseMSparse(fA,GetDXDAM(0)); if(!AM1) { @@ -841,7 +841,7 @@ TMatrixDSparse *TUnfoldSys::PrepareUncorrEmat //====================================================== // calculate contributions containing matrices F and G // r0,r1,r2 - TMatrixDSparse *r=0; + TMatrixDSparse *r=nullptr; if(fDAinColRelSq && fDAinRelSq) { // calculate matrices (M1*A)_{mj} * Z1_j and (M1*Rsq)_{mj} * Z1_j TMatrixDSparse *M1A_Z1=MultiplyMSparseMSparse(m_1,fA); @@ -869,9 +869,9 @@ TMatrixDSparse *TUnfoldSys::PrepareUncorrEmat // r0 = \sum_j [ F_{mj} * F_nj * SRsq_j ] r=MultiplyMSparseMSparseTranspVector(F,F,fDAinColRelSq); // r1 = \sum_j [ G_{mj} * F_nj ] - TMatrixDSparse *r1=MultiplyMSparseMSparseTranspVector(F,G,0); + TMatrixDSparse *r1=MultiplyMSparseMSparseTranspVector(F,G,nullptr); // r2 = \sum_j [ F_{mj} * G_nj ] - TMatrixDSparse *r2=MultiplyMSparseMSparseTranspVector(G,F,0); + TMatrixDSparse *r2=MultiplyMSparseMSparseTranspVector(G,F,nullptr); // r = r0-r1-r2 AddMSparse(r,-1.0,r1); AddMSparse(r,-1.0,r2); @@ -917,9 +917,9 @@ TMatrixDSparse *TUnfoldSys::PrepareUncorrEmat // H_{mi} = Z0_i * \sum_j [ M0_{mj} * Z1_j * Rsq_{ij} ] ScaleColumnsByVector(H,GetDXDAZ(0)); // r5 = \sum_i [ M1_{mi} * H_{ni} ] - TMatrixDSparse *r5=MultiplyMSparseMSparseTranspVector(m_1,H,0); + TMatrixDSparse *r5=MultiplyMSparseMSparseTranspVector(m_1,H,nullptr); // r6 = \sum_i [ H_{mi} * M1_{ni} ] - TMatrixDSparse *r6=MultiplyMSparseMSparseTranspVector(H,m_1,0); + TMatrixDSparse *r6=MultiplyMSparseMSparseTranspVector(H,m_1,nullptr); DeleteMatrix(&H); // r = r0 -r1 -r2 +r3 +r4 -r5 -r6 if(r) { @@ -927,7 +927,7 @@ TMatrixDSparse *TUnfoldSys::PrepareUncorrEmat DeleteMatrix(&r3); } else { r=r3; - r3=0; + r3=nullptr; } AddMSparse(r,1.0,r4); AddMSparse(r,-1.0,r5); @@ -1001,12 +1001,12 @@ Bool_t TUnfoldSys::GetDeltaSysSource(TH1 *hist_delta,const char *name, { PrepareSysError(); const TPair *named_emat=(const TPair *)fDeltaCorrX->FindObject(name); - const TMatrixDSparse *delta=0; + const TMatrixDSparse *delta=nullptr; if(named_emat) { delta=(TMatrixDSparse *)named_emat->Value(); } VectorMapToHist(hist_delta,delta,binMap); - return delta !=0; + return delta !=nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1028,13 +1028,13 @@ Bool_t TUnfoldSys::GetDeltaSysBackgroundScale { PrepareSysError(); const TPair *named_err=(const TPair *)fBgrErrScaleIn->FindObject(source); - TMatrixDSparse *dx=0; + TMatrixDSparse *dx=nullptr; if(named_err) { const TMatrixD *dy=(TMatrixD *)named_err->Value(); dx=MultiplyMSparseM(GetDXDY(),dy); } VectorMapToHist(hist_delta,dx,binMap); - if(dx!=0) { + if(dx!=nullptr) { DeleteMatrix(&dx); return kTRUE; } @@ -1062,7 +1062,7 @@ Bool_t TUnfoldSys::GetDeltaSysTau(TH1 *hist_delta,const Int_t *binMap) { PrepareSysError(); VectorMapToHist(hist_delta,fDeltaSysTau,binMap); - return fDeltaSysTau !=0; + return fDeltaSysTau !=nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1087,10 +1087,10 @@ void TUnfoldSys::GetEmatrixSysSource { PrepareSysError(); const TPair *named_emat=(const TPair *)fDeltaCorrX->FindObject(name); - TMatrixDSparse *emat=0; + TMatrixDSparse *emat=nullptr; if(named_emat) { const TMatrixDSparse *delta=(TMatrixDSparse *)named_emat->Value(); - emat=MultiplyMSparseMSparseTranspVector(delta,delta,0); + emat=MultiplyMSparseMSparseTranspVector(delta,delta,nullptr); } ErrorMatrixToHist(ematrix,emat,binMap,clearEmat); DeleteMatrix(&emat); @@ -1118,11 +1118,11 @@ void TUnfoldSys::GetEmatrixSysBackgroundScale { PrepareSysError(); const TPair *named_err=(const TPair *)fBgrErrScaleIn->FindObject(name); - TMatrixDSparse *emat=0; + TMatrixDSparse *emat=nullptr; if(named_err) { const TMatrixD *dy=(TMatrixD *)named_err->Value(); TMatrixDSparse *dx=MultiplyMSparseM(GetDXDY(),dy); - emat=MultiplyMSparseMSparseTranspVector(dx,dx,0); + emat=MultiplyMSparseMSparseTranspVector(dx,dx,nullptr); DeleteMatrix(&dx); } ErrorMatrixToHist(ematrix,emat,binMap,clearEmat); @@ -1154,9 +1154,9 @@ void TUnfoldSys::GetEmatrixSysTau (TH2 *ematrix,const Int_t *binMap,Bool_t clearEmat) { PrepareSysError(); - TMatrixDSparse *emat=0; + TMatrixDSparse *emat=nullptr; if(fDeltaSysTau) { - emat=MultiplyMSparseMSparseTranspVector(fDeltaSysTau,fDeltaSysTau,0); + emat=MultiplyMSparseMSparseTranspVector(fDeltaSysTau,fDeltaSysTau,nullptr); } ErrorMatrixToHist(ematrix,emat,binMap,clearEmat); DeleteMatrix(&emat); @@ -1203,7 +1203,7 @@ void TUnfoldSys::GetEmatrixSysBackgroundUncorr (TH2 *ematrix,const char *source,const Int_t *binMap,Bool_t clearEmat) { const TPair *named_err=(const TPair *)fBgrErrUncorrInSq->FindObject(source); - TMatrixDSparse *emat=0; + TMatrixDSparse *emat=nullptr; if(named_err) { TMatrixD const *dySquared=(TMatrixD const *)named_err->Value(); emat=MultiplyMSparseMSparseTranspVector(GetDXDY(),GetDXDY(),dySquared); @@ -1231,10 +1231,10 @@ void TUnfoldSys::GetEmatrixFromVyy (const TMatrixDSparse *vyy,TH2 *ematrix,const Int_t *binMap,Bool_t clearEmat) { PrepareSysError(); - TMatrixDSparse *em=0; + TMatrixDSparse *em=nullptr; if(vyy) { TMatrixDSparse *dxdyVyy=MultiplyMSparseMSparse(GetDXDY(),vyy); - em=MultiplyMSparseMSparseTranspVector(dxdyVyy,GetDXDY(),0); + em=MultiplyMSparseMSparseTranspVector(dxdyVyy,GetDXDY(),nullptr); DeleteMatrix(&dxdyVyy); } ErrorMatrixToHist(ematrix,em,binMap,clearEmat); @@ -1288,7 +1288,7 @@ TMatrixDSparse *TUnfoldSys::GetSummedErrorMatrixYY(void) // correlated systematic errors for(key=sysErrPtr.Next();key;key=sysErrPtr.Next()) { const TMatrixDSparse *delta=(TMatrixDSparse *)((const TPair *)*sysErrPtr)->Value(); - TMatrixDSparse *emat=MultiplyMSparseMSparseTranspVector(delta,delta,0); + TMatrixDSparse *emat=MultiplyMSparseMSparseTranspVector(delta,delta,nullptr); AddMSparse(emat_sum,1.0,emat); DeleteMatrix(&emat); } @@ -1296,7 +1296,7 @@ TMatrixDSparse *TUnfoldSys::GetSummedErrorMatrixYY(void) if(fDeltaSysTau) { TMatrixDSparse *Adx_tau=MultiplyMSparseMSparse(fA,fDeltaSysTau); TMatrixDSparse *emat_tau= - MultiplyMSparseMSparseTranspVector(Adx_tau,Adx_tau,0); + MultiplyMSparseMSparseTranspVector(Adx_tau,Adx_tau,nullptr); DeleteMatrix(&Adx_tau); AddMSparse(emat_sum,1.0,emat_tau); DeleteMatrix(&emat_tau); @@ -1324,14 +1324,14 @@ TMatrixDSparse *TUnfoldSys::GetSummedErrorMatrixXX(void) // correlated systematic errors for(key=sysErrPtr.Next();key;key=sysErrPtr.Next()) { const TMatrixDSparse *delta=(TMatrixDSparse *)((const TPair *)*sysErrPtr)->Value(); - TMatrixDSparse *emat=MultiplyMSparseMSparseTranspVector(delta,delta,0); + TMatrixDSparse *emat=MultiplyMSparseMSparseTranspVector(delta,delta,nullptr); AddMSparse(emat_sum,1.0,emat); DeleteMatrix(&emat); } // error on tau if(fDeltaSysTau) { TMatrixDSparse *emat_tau= - MultiplyMSparseMSparseTranspVector(fDeltaSysTau,fDeltaSysTau,0); + MultiplyMSparseMSparseTranspVector(fDeltaSysTau,fDeltaSysTau,nullptr); AddMSparse(emat_sum,1.0,emat_tau); DeleteMatrix(&emat_tau); } diff --git a/html/inc/TClassDocOutput.h b/html/inc/TClassDocOutput.h index 44c7aaee817a8..48264012d67ef 100644 --- a/html/inc/TClassDocOutput.h +++ b/html/inc/TClassDocOutput.h @@ -54,7 +54,7 @@ class TClassDocOutput: public TDocOutput { public: TClassDocOutput(THtml& html, TClass* cl, TList* typedefs); - virtual ~TClassDocOutput(); + ~TClassDocOutput() override; void Class2Html(Bool_t force=kFALSE); Bool_t ClassDotCharts(std::ostream & out); @@ -64,7 +64,7 @@ class TClassDocOutput: public TDocOutput { friend class TDocParser; - ClassDef(TClassDocOutput, 0); // generates documentation web pages for a class + ClassDefOverride(TClassDocOutput, 0); // generates documentation web pages for a class }; #endif // ROOT_TClassDocOutput diff --git a/html/inc/TDocDirective.h b/html/inc/TDocDirective.h index e6f9a9de1e9c0..b69c42ad90049 100644 --- a/html/inc/TDocDirective.h +++ b/html/inc/TDocDirective.h @@ -44,9 +44,9 @@ class TDocDirective: public TNamed { TDocDirective() {} TDocDirective(const char* name): TNamed(name, ""), fDocParser(0), fHtml(0), fDocOutput(0), fCounter(-1) {}; - virtual ~TDocDirective() {} + ~TDocDirective() override {} - const char* GetName() const { return TNamed::GetName(); } + const char* GetName() const override { return TNamed::GetName(); } void GetName(TString& name) const; TDocParser* GetDocParser() const { return fDocParser; } TDocOutput* GetDocOutput() const { return fDocOutput; } @@ -74,7 +74,7 @@ class TDocDirective: public TNamed { friend class TDocParser; - ClassDef(TDocDirective, 0); // THtml directive handler + ClassDefOverride(TDocDirective, 0); // THtml directive handler }; class TDocHtmlDirective: public TDocDirective { @@ -83,13 +83,13 @@ class TDocHtmlDirective: public TDocDirective { Bool_t fVerbatim; // whether we are in a
 block
 public:
    TDocHtmlDirective(): TDocDirective("HTML"), fVerbatim(kFALSE) {}
-   virtual ~TDocHtmlDirective() {}
+   ~TDocHtmlDirective() override {}
 
-   virtual void AddLine(const TSubString& line);
-   virtual const char* GetEndTag() const { return "end_html"; }
-   virtual Bool_t GetResult(TString& result);
+   void AddLine(const TSubString& line) override;
+   const char* GetEndTag() const override { return "end_html"; }
+   Bool_t GetResult(TString& result) override;
 
-   ClassDef(TDocHtmlDirective, 0); // Handler for "Begin_Html"/"End_Html" for raw HTML in documentation comments
+   ClassDefOverride(TDocHtmlDirective, 0); // Handler for "Begin_Html"/"End_Html" for raw HTML in documentation comments
 };
 
 class TDocMacroDirective: public TDocDirective {
@@ -99,24 +99,24 @@ class TDocMacroDirective: public TDocDirective {
    Bool_t  fShowSource;    // whether a source tab should be created
    Bool_t  fIsFilename;    // whether the directive is a failename to be executed
 
-   virtual void AddParameter(const TString& name, const char* value = 0);
+   void AddParameter(const TString& name, const char* value = 0) override;
    TString CreateSubprocessInputFile();
 
 public:
    TDocMacroDirective():
       TDocDirective("MACRO"), fMacro(0), fNeedGraphics(kFALSE),
       fShowSource(kFALSE), fIsFilename(kTRUE) {};
-   virtual ~TDocMacroDirective();
+   ~TDocMacroDirective() override;
 
-   virtual void AddLine(const TSubString& line);
-   virtual const char* GetEndTag() const { return "end_macro"; }
-   virtual Bool_t GetResult(TString& result);
+   void AddLine(const TSubString& line) override;
+   const char* GetEndTag() const override { return "end_macro"; }
+   Bool_t GetResult(TString& result) override;
    // Delete output for the parser's current class or module.
-   virtual void DeleteOutput() const { DeleteOutputFiles(".gif"); }
+   void DeleteOutput() const override { DeleteOutputFiles(".gif"); }
 
    static void SubProcess(const TString& what, const TString& out);
 
-   ClassDef(TDocMacroDirective, 0); // Handler for "Begin_Macro"/"End_Macro" for code that is executed and that can generate an image for documentation
+   ClassDefOverride(TDocMacroDirective, 0); // Handler for "Begin_Macro"/"End_Macro" for code that is executed and that can generate an image for documentation
 };
 
 class TDocLatexDirective: public TDocDirective {
@@ -128,18 +128,18 @@ class TDocLatexDirective: public TDocDirective {
    TString      fAlignment;   // column alignment: 'l' for justify left, 'c' for center, 'r' for right
    TVirtualPad* fBBCanvas;    // canvas for bounding box determination
 
-   virtual void    CreateLatex(const char* filename);
-   virtual void    AddParameter(const TString& name, const char* value = 0);
+   virtual void CreateLatex(const char* filename);
+           void AddParameter(const TString& name, const char* value = 0) override;
    virtual void GetBoundingBox(TLatex& latex, const char* text, Float_t& width, Float_t& height);
 
 public:
    TDocLatexDirective():
       TDocDirective("LATEX"), fLatex(0), fFontSize(16),
       fSepIsRegexp(kFALSE), fBBCanvas(0) {};
-   virtual ~TDocLatexDirective();
+   ~TDocLatexDirective() override;
 
-   virtual void AddLine(const TSubString& line);
-   virtual const char* GetEndTag() const {return "end_latex";}
+   void AddLine(const TSubString& line) override;
+   const char* GetEndTag() const override {return "end_latex";}
 
    const char* GetAlignment() const {return fAlignment;}
    const char* GetSeparator() const {return fSeparator;}
@@ -147,11 +147,11 @@ class TDocLatexDirective: public TDocDirective {
    Int_t  GetFontSize() const {return fFontSize;}
    TList* GetListOfLines() const;
 
-   virtual Bool_t GetResult(TString& result);
+   Bool_t GetResult(TString& result) override;
    // Delete output for the parser's current class or module.
-   virtual void DeleteOutput() const { DeleteOutputFiles(".gif"); }
+   void DeleteOutput() const override { DeleteOutputFiles(".gif"); }
 
-   ClassDef(TDocLatexDirective, 0); // Handler for "Begin_Latex"/"End_Latex" to generate an image from latex
+   ClassDefOverride(TDocLatexDirective, 0); // Handler for "Begin_Latex"/"End_Latex" to generate an image from latex
 };
 
 #endif // ROOT_TDocDirective
diff --git a/html/inc/TDocInfo.h b/html/inc/TDocInfo.h
index 03faf6516086b..4a1b7beab7659 100644
--- a/html/inc/TDocInfo.h
+++ b/html/inc/TDocInfo.h
@@ -49,14 +49,14 @@ class TClassDocInfo: public TObject {
       fDeclFileSysName(fsdecl), fImplFileSysName(fsimpl),
       fSelected(kTRUE) { }
 
-   virtual ~TClassDocInfo()
+   ~TClassDocInfo() override
    {
       // Required since we overload TObject::Hash.
       ROOT::CallRecursiveRemoveIfNeeded(*this);
    }
 
    TDictionary *GetClass() const { return fClass; }
-   virtual const char*     GetName() const;
+           const char*     GetName() const override;
            const char*     GetHtmlFileName() const { return fHtmlFileName; }
            const char*     GetDeclFileName() const { return fDeclFileName; }
            const char*     GetImplFileName() const { return fImplFileName; }
@@ -77,12 +77,12 @@ class TClassDocInfo: public TObject {
            void            SetDeclFileSysName(const char* fsname) { fDeclFileSysName = fsname; }
            void            SetImplFileSysName(const char* fsname) { fImplFileSysName = fsname; }
 
-           ULong_t         Hash() const;
+           ULong_t         Hash() const override;
 
            TList&          GetListOfTypedefs() { return fTypedefs; }
 
-   virtual Bool_t          IsSortable() const { return kTRUE; }
-   virtual Int_t           Compare(const TObject* obj) const;
+   Bool_t          IsSortable() const override { return kTRUE; }
+   Int_t           Compare(const TObject* obj) const override;
 
 private:
    TClassDocInfo();
@@ -97,7 +97,7 @@ class TClassDocInfo: public TObject {
    TList                   fTypedefs; // typedefs to this class
    Bool_t                  fSelected; // selected for doc output
 
-   ClassDef(TClassDocInfo,0); // info cache for class documentation
+   ClassDefOverride(TClassDocInfo,0); // info cache for class documentation
 };
 
 //____________________________________________________________________
@@ -110,7 +110,7 @@ class TModuleDocInfo: public TNamed {
       TNamed(name, doc), fSuper(super), fSub(0), fSelected(kTRUE) {
          if (super) super->GetSub().Add(this);
       }
-   virtual ~TModuleDocInfo() { fSub.Clear("nodelete"); fClasses.Clear("nodelete"); }
+   ~TModuleDocInfo() override { fSub.Clear("nodelete"); fClasses.Clear("nodelete"); }
 
    void        SetDoc(const char* doc) { SetTitle(doc); }
    const char* GetDoc() const { return GetTitle(); }
@@ -130,7 +130,7 @@ class TModuleDocInfo: public TNamed {
    TList       fClasses;
    Bool_t      fSelected; // selected for doc output
 
-   ClassDef(TModuleDocInfo,0); // documentation for a group of classes
+   ClassDefOverride(TModuleDocInfo,0); // documentation for a group of classes
 };
 
 //__________________________________________________________________________
@@ -152,7 +152,7 @@ class TLibraryDocInfo: public TNamed {
    std::set fDependencies; // dependencies on other libraries
    std::set fModules; // modules in the library
 
-   ClassDef(TLibraryDocInfo,0); // documentation for a library
+   ClassDefOverride(TLibraryDocInfo,0); // documentation for a library
 };
 
 
diff --git a/html/inc/TDocOutput.h b/html/inc/TDocOutput.h
index b7e454654f105..3dccd3ef9116c 100644
--- a/html/inc/TDocOutput.h
+++ b/html/inc/TDocOutput.h
@@ -65,7 +65,7 @@ class TDocOutput: public TObject {
    enum EFileType { kSource, kInclude, kTree, kDoc };
 
    TDocOutput(THtml& html);
-   virtual ~TDocOutput();
+   ~TDocOutput() override;
 
    virtual void   AdjustSourcePath(TString& line, const char* relpath = "../");
    void           Convert(std::istream& in, const char* infilename,
@@ -107,7 +107,7 @@ class TDocOutput: public TObject {
                                   const char *author="", const char *copyright="");
    void           WriteLineNumbers(std::ostream& out, Long_t nLines, const TString& infileBase) const;
 
-   ClassDef(TDocOutput, 0); // generates documentation web pages
+   ClassDefOverride(TDocOutput, 0); // generates documentation web pages
 };
 
 #endif // ROOT_TDocOutput
diff --git a/html/inc/TDocParser.h b/html/inc/TDocParser.h
index 3cc10feaa295f..f71f726a033a3 100644
--- a/html/inc/TDocParser.h
+++ b/html/inc/TDocParser.h
@@ -158,7 +158,7 @@ class TDocParser: public TObject {
 public:
    TDocParser(TClassDocOutput& docOutput, TClass* cl);
    TDocParser(TDocOutput& docOutput);
-   virtual       ~TDocParser();
+         ~TDocParser() override;
 
    static void   AnchorFromLine(const TString& line, TString& anchor);
    void          Convert(std::ostream& out, std::istream& in, const char* relpath,
@@ -184,7 +184,7 @@ class TDocParser: public TObject {
    virtual void  Parse(std::ostream& out);
    static Bool_t Strip(TString& s);
 
-   ClassDef(TDocParser,0); // parser for reference documentation
+   ClassDefOverride(TDocParser,0); // parser for reference documentation
 };
 
 #endif // ROOT_TDocParser
diff --git a/html/inc/THtml.h b/html/inc/THtml.h
index bd8265b0faa4a..ddf0aa751b675 100644
--- a/html/inc/THtml.h
+++ b/html/inc/THtml.h
@@ -44,12 +44,12 @@ class THtml: public TObject {
    class THelperBase: public TObject {
    public:
       THelperBase(): fHtml(0) {}
-      virtual ~THelperBase();
+      ~THelperBase() override;
       void    SetOwner(THtml* html);
       THtml*  GetOwner() const { return fHtml; }
    private:
       THtml*  fHtml; // object owning the helper
-      ClassDef(THelperBase, 0); // a helper object's base class
+      ClassDefOverride(THelperBase, 0); // a helper object's base class
    };
 
    class TFileSysEntry;
@@ -61,7 +61,7 @@ class THtml: public TObject {
    class TModuleDefinition: public THelperBase {
    public:
       virtual bool GetModule(TClass* cl, TFileSysEntry* fse, TString& out_modulename) const;
-      ClassDef(TModuleDefinition, 0); // helper class to determine a class's module
+      ClassDefOverride(TModuleDefinition, 0); // helper class to determine a class's module
    };
 
    //______________________________________________________________
@@ -82,7 +82,7 @@ class THtml: public TObject {
       void SplitClassIntoDirFile(const TString& clname, TString& dir, TString& filename) const;
       void NormalizePath(TString& path) const;
       void ExpandSearchPath(TString& path) const;
-      ClassDef(TFileDefinition, 0); // helper class to determine a class's source files
+      ClassDefOverride(TFileDefinition, 0); // helper class to determine a class's source files
    };
 
    //______________________________________________________________
@@ -96,7 +96,7 @@ class THtml: public TObject {
       virtual bool GetFileNameFromInclude(const char* included, TString& out_fsname) const;
       virtual bool GetDocDir(const TString& module, TString& doc_dir) const;
    protected:
-      ClassDef(TPathDefinition, 0); // helper class to determine directory layouts
+      ClassDefOverride(TPathDefinition, 0); // helper class to determine directory layouts
    };
 
    class TFileSysDir;
@@ -107,13 +107,13 @@ class THtml: public TObject {
    public:
       TFileSysEntry(const char* name, TFileSysDir* parent):
          fName(name), fParent(parent), fLevel(parent ? parent->GetLevel() + 1 : 0) {}
-      ~TFileSysEntry()
+      ~TFileSysEntry() override
       {
          // Required since we overload TObject::Hash.
          ROOT::CallRecursiveRemoveIfNeeded(*this);
       }
-      const char* GetName() const { return fName; }
-      virtual ULong_t Hash() const { return fName.Hash(); }
+      const char* GetName() const override { return fName; }
+      ULong_t Hash() const override { return fName.Hash(); }
       virtual void GetFullName(TString& fullname, Bool_t asIncluded) const {
          if (fParent) {
             fParent->GetFullName(fullname, asIncluded);
@@ -130,7 +130,7 @@ class THtml: public TObject {
       TString      fName; // name of the element
       TFileSysDir* fParent; // parent directory
       Int_t        fLevel; // level of directory
-      ClassDef(TFileSysEntry, 0); // an entry of the local file system
+      ClassDefOverride(TFileSysEntry, 0); // an entry of the local file system
    };
 
    //______________________________________________________________
@@ -148,7 +148,7 @@ class THtml: public TObject {
    protected:
       TList fFiles;
       TList fDirs;
-      ClassDef(TFileSysDir, 0); // an directory of the local file system
+      ClassDefOverride(TFileSysDir, 0); // an directory of the local file system
    };
 
    //______________________________________________________________
@@ -158,7 +158,7 @@ class THtml: public TObject {
    public:
       TFileSysRoot(const char* name, TFileSysDB* parent):
          TFileSysDir(name, parent) {}
-      void GetFullName(TString& fullname, Bool_t asIncluded) const {
+      void GetFullName(TString& fullname, Bool_t asIncluded) const override {
          // prepend directory part of THtml::GetInputPath() only
          // if !asIncluded
          fullname = "";
@@ -166,7 +166,7 @@ class THtml: public TObject {
             fullname += fName;
       }
 
-      ClassDef(TFileSysRoot, 0); // an root directory of the local file system
+      ClassDefOverride(TFileSysRoot, 0); // an root directory of the local file system
    };
 
    //______________________________________________________________
@@ -190,7 +190,7 @@ class THtml: public TObject {
       THashTable fEntries; // hash map of all filenames without paths
       TString  fIgnorePath; // regexp of path to ignore while building entry tree
       Int_t    fMaxLevel; // maximum level of directory nesting
-      ClassDef(TFileSysDB, 0); // instance of file system data
+      ClassDefOverride(TFileSysDB, 0); // instance of file system data
    };
 
 
@@ -239,7 +239,7 @@ class THtml: public TObject {
    };
 
    THtml();
-   virtual      ~THtml();
+   ~THtml() override;
 
    static void   LoadAllLibs();
 
@@ -423,7 +423,7 @@ class THtml: public TObject {
    mutable TFileSysDB    *fLocalFiles; // files found locally for a given source path
    Bool_t  fBatch; // Whether to enable GUI output
 
-   ClassDef(THtml,0)  //Convert class(es) into HTML file(s)
+   ClassDefOverride(THtml,0)  //Convert class(es) into HTML file(s)
 };
 
 R__EXTERN THtml *gHtml;
diff --git a/html/src/TDocParser.cxx b/html/src/TDocParser.cxx
index 64b869b0e3ab2..3e4008d4f3a3c 100644
--- a/html/src/TDocParser.cxx
+++ b/html/src/TDocParser.cxx
@@ -40,15 +40,15 @@ namespace {
 
       static void SetClass(const TClass* cl) { fgClass = cl; }
 
-      const char* GetName() const { return fMeth->GetName(); }
-      ULong_t Hash() const { return fMeth->Hash();}
+      const char* GetName() const override { return fMeth->GetName(); }
+      ULong_t Hash() const override { return fMeth->Hash();}
       Int_t GetNargs() const { return fMeth->GetNargs(); }
-      virtual TMethod* GetMethod() const { return fMeth; }
-      Bool_t IsSortable() const { return kTRUE; }
+      TMethod* GetMethod() const override { return fMeth; }
+      Bool_t IsSortable() const override { return kTRUE; }
 
-      Int_t GetOverloadIdx() const { return fOverloadIdx; }
+      Int_t GetOverloadIdx() const override { return fOverloadIdx; }
 
-      Int_t Compare(const TObject *obj) const {
+      Int_t Compare(const TObject *obj) const override {
          const TMethodWrapperImpl* m = dynamic_cast(obj);
          if (!m) return 1;
 
@@ -1127,7 +1127,7 @@ Bool_t TDocParser::HandleDirective(TString& line, Ssiz_t& pos, TString& word,
          if (fParseContext.size()>1)
             fParseContext.pop_back();
          if (isInCxxComment && !InContext(kComment)) {
-            fParseContext.push_back(kComment | kCXXComment);
+            fParseContext.push_back((int)kComment | (int)kCXXComment);
             fDocOutput->DecorateEntityBegin(line, pos, kComment);
          }
       }
diff --git a/interpreter/CMakeLists.txt b/interpreter/CMakeLists.txt
index 3f7785c33c37c..6275a81000464 100644
--- a/interpreter/CMakeLists.txt
+++ b/interpreter/CMakeLists.txt
@@ -3,6 +3,9 @@ if (NOT builtin_clang)
   message(WARNING "Due to ROOT-specific patches you need a special version of clang. You cannot use vanilla clang.")
 endif()
 
+#--Set the LLVM version required for ROOT-----------------------------------------------------------
+set(ROOT_LLVM_VERSION_REQUIRED_MAJOR 13)
+
 #---Define the way we want to build and what of llvm/clang/cling------------------------------------
 set(LLVM_ENABLE_RTTI ON CACHE BOOL "")
 set(LLVM_APPEND_VC_REV OFF CACHE BOOL "")
@@ -11,11 +14,12 @@ set(LLVM_ENABLE_FFI OFF CACHE BOOL "")
 set(LLVM_ENABLE_OCAMLDOC OFF CACHE BOOL "")
 set(LLVM_ENABLE_Z3_SOLVER OFF CACHE BOOL "")
 set(LLVM_ENABLE_WARNINGS OFF CACHE BOOL "")
+set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "")
+set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "")
 set(LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_BENCHMARKS OFF CACHE BOOL "")
 set(CLANG_INCLUDE_TESTS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
-set(LLVM_CXX_STD "c++${CMAKE_CXX_STANDARD}" CACHE STRING "")
 set(CLANG_BUILD_TOOLS OFF CACHE BOOL "")
 # It looks like that turning off CLANG_BUILD_TOOLS is not enough.
 set(CLANG_TOOL_ARCMT_TEST_BUILD OFF CACHE BOOL "")
@@ -36,8 +40,6 @@ set(LLVM_BUILD_TOOLS OFF CACHE BOOL "")
 set(LLVM_TOOL_LLVM_AR_BUILD OFF CACHE BOOL "")
 set(CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD OFF CACHE BOOL "")
 set(LLVM_FORCE_USE_OLD_TOOLCHAIN ON CACHE BOOL "")
-# Support gcc 4.8 and higher.
-set(LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN ON CACHE BOOL "")
 
 # Prevent Clang from finding CUDA just to determine the architecture for OpenMP
 # offloading, which we are not interested in. If the CUDA package was already
@@ -47,7 +49,7 @@ set(LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN ON CACHE BOOL "")
 set(CMAKE_DISABLE_FIND_PACKAGE_CUDA ON)
 
 # will be set again in case NOT builtin_llvm
-set(LLVM_DIR "${CMAKE_BINARY_DIR}/interpreter/llvm/src")
+set(LLVM_DIR "${CMAKE_BINARY_DIR}/interpreter/llvm-project/llvm")
 if (clad)
   set(CLING_BUILD_PLUGINS ON)
 endif()
@@ -57,20 +59,14 @@ endif()
 # mechanism.
 set(LLVM_ENABLE_THREADS OFF CACHE BOOL "")
 
-if(CMAKE_CXX_STANDARD EQUAL 17)
-  set(LLVM_ENABLE_CXX1Z ON CACHE BOOL "" FORCE)
-elseif(CMAKE_CXX_STANDARD EQUAL 14)
-  set(LLVM_ENABLE_CXX1Y ON CACHE BOOL "" FORCE)
-endif()
-
 # The llvm::ReverseIterate::value symbol from llvm's SmallPtrSet.h
 # somehow lands in our cling libraries on OS X and doesn't get hidden
 # by visibility-inlines-hidden, so we suddenly have a global weak symbol
 # from LLVM in cling which our visiblity=hidden compiled LLVM libraries
 # reference. This is triggering some build system warnings like this:
 #   ld: warning: direct access in function '(anonymous namespace)::NewGVN::runGVN()'
-#   from file 'interpreter/llvm/src/lib/libLLVMScalarOpts.a(NewGVN.cpp.o)' to global weak symbol
-#   'llvm::ReverseIterate::value' from file 'interpreter/llvm/src/lib/libclingUtils.a(AST.cpp.o)'
+#   from file 'interpreter/llvm-project/llvm/lib/libLLVMScalarOpts.a(NewGVN.cpp.o)' to global weak symbol
+#   'llvm::ReverseIterate::value' from file 'interpreter/llvm-project/llvm/lib/libclingUtils.a(AST.cpp.o)'
 #   means the weak symbol cannot be overridden at runtime. This was likely caused by different
 #   translation units being compiled with different visibility settings.
 # There is no apparent reason why this is happening and it looks like a compiler bug,
@@ -93,6 +89,8 @@ elseif(ROOT_ARCHITECTURE MATCHES linuxppc64gcc)
   set(ROOT_CLING_TARGET "PowerPC")
 elseif(ROOT_ARCHITECTURE MATCHES linuxs390)
   set(ROOT_CLING_TARGET "SystemZ")
+elseif(ROOT_ARCHITECTURE MATCHES linuxriscv64)
+  set(ROOT_CLING_TARGET "RISCV")
 elseif(ROOT_ARCHITECTURE MATCHES linux)
   set(ROOT_CLING_TARGET "X86")
 elseif(ROOT_ARCHITECTURE MATCHES macosxarm64)
@@ -133,7 +131,7 @@ if(clingtest)
   # against external llvm. In that case, cling's testsuite cannot deduce the binary
   # of cling relatively to the llvm tools folder.
   if (NOT builtin_llvm)
-    set(CLINGTEST_EXECUTABLE CLING=${CMAKE_CURRENT_BINARY_DIR}/llvm/src/${CMAKE_CFG_INTDIR}/bin/cling)
+    set(CLINGTEST_EXECUTABLE CLING=${CMAKE_CURRENT_BINARY_DIR}/llvm-project/llvm/${CMAKE_CFG_INTDIR}/bin/cling)
   endif()
   ROOT_ADD_TEST(clingtest-check-cling COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target check-cling
                                        ENVIRONMENT ${CLINGTEST_EXECUTABLE})
@@ -172,6 +170,9 @@ endif()
 
 # We will not fix llvm or clang.
 string(REPLACE "-Werror " "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ")
+# Turn off coverage - we don't need this for llvm.
+string(REPLACE "${GCC_COVERAGE_COMPILE_FLAGS}" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
+
 
 if(LLVM_SHARED_LINKER_FLAGS)
   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LLVM_SHARED_LINKER_FLAGS}")
@@ -193,7 +194,7 @@ if(builtin_llvm)
   message(STATUS "Building LLVM in '${LLVM_BUILD_TYPE}' mode.")
 
   if(NOT DEFINED LLVM_ENABLE_ASSERTIONS)
-    if(CMAKE_BUILD_TYPE MATCHES "(Debug|RelWithDebInfo)"
+    if(CMAKE_BUILD_TYPE MATCHES "Debug"
      OR LLVM_BUILD_TYPE MATCHES "(Debug|RelWithDebInfo)")
       set(LLVM_ENABLE_ASSERTIONS TRUE)
     else()
@@ -220,42 +221,32 @@ if(builtin_llvm)
 
   set(BUILD_SHARED_LIBS FALSE)
 
-  set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "")
-  set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "")
-  set(CLANG_ENABLE_FORMAT OFF CACHE BOOL "")
-
   #---Remove the inherited include_directories()
   set_directory_properties(PROPERTIES INCLUDE_DIRECTORIES "")
 
-  #---Disable VCS writing to prevent that we always have to rebuild when someone touched the git HEAD
-  set(LLVM_APPEND_VC_REV OFF CACHE BOOL "Disabled LLVM revision dependency" FORCE)
+  set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "")
 
   #---Add the sub-directory excluding all the targets from all-----------------------------------------
   if(CMAKE_GENERATOR MATCHES "Xcode")
-    add_subdirectory(llvm/src)
+    add_subdirectory(llvm-project/llvm)
   else()
-    add_subdirectory(llvm/src EXCLUDE_FROM_ALL)
+    add_subdirectory(llvm-project/llvm EXCLUDE_FROM_ALL)
   endif()
 
-  set(LLVM_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/interpreter/llvm/src/include
-    ${CMAKE_BINARY_DIR}/interpreter/llvm/src/include
+  set(LLVM_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/interpreter/llvm-project/llvm/include
+    ${CMAKE_BINARY_DIR}/interpreter/llvm-project/llvm/include
     CACHE STRING "LLVM include directories."
     )
+  list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/llvm-project/llvm/cmake/modules")
   #---Set into parent scope LLVM_VERSION --------------------------------------------------------------
-  set(llvmconfigfile "${CMAKE_CURRENT_SOURCE_DIR}/llvm/src/CMakeLists.txt")
-  file(READ ${llvmconfigfile} _filestr)
-  foreach(versionpart LLVM_VERSION_MAJOR LLVM_VERSION_MINOR LLVM_VERSION_PATCH)
-    if("${_filestr}" MATCHES "set[(](${versionpart}[^)]+)")
-      string(REGEX REPLACE " *${versionpart} ([^)]+).*" "\\1" ${versionpart} "${CMAKE_MATCH_1}")
-    else()
-      MESSAGE(FATAL_ERROR "Cannot extract LLVM version number (${versionpart}) from ${llvmconfigfile}")
-    endif()
-  endforeach()
-  set(LLVM_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}" PARENT_SCOPE)
+  get_directory_property(_llvm_version DIRECTORY llvm-project/llvm DEFINITION LLVM_VERSION)
+  set(LLVM_VERSION "${_llvm_version}" PARENT_SCOPE)
+  #---Forward TARGET_TRIPLE for check-cling------------------------------------------------------------
+  get_directory_property(TARGET_TRIPLE DIRECTORY llvm-project/llvm DEFINITION TARGET_TRIPLE)
 else()
   # Rely on llvm-config.
   set(CONFIG_OUTPUT)
-  find_program(LLVM_CONFIG NAMES "llvm-config" "llvm-config-9")
+  find_program(LLVM_CONFIG NAMES "llvm-config-${ROOT_LLVM_VERSION_REQUIRED_MAJOR}" "llvm-config")
   if(LLVM_CONFIG)
     message(STATUS "Found LLVM_CONFIG as ${LLVM_CONFIG}")
     set(CONFIG_COMMAND ${LLVM_CONFIG}
@@ -264,7 +255,6 @@ else()
       "--libdir"
       "--includedir"
       "--prefix"
-      "--src-root"
       "--cmakedir"
       "--build-mode"
       "--version")
@@ -291,10 +281,9 @@ else()
   list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
   list(GET CONFIG_OUTPUT 3 INCLUDE_DIR)
   list(GET CONFIG_OUTPUT 4 LLVM_OBJ_ROOT)
-  list(GET CONFIG_OUTPUT 5 MAIN_SRC_DIR)
-  list(GET CONFIG_OUTPUT 6 LLVM_CONFIG_CMAKE_PATH)
-  list(GET CONFIG_OUTPUT 7 LLVM_BUILD_MODE)
-  list(GET CONFIG_OUTPUT 8 LLVM_VERSION_S)
+  list(GET CONFIG_OUTPUT 5 LLVM_CONFIG_CMAKE_PATH)
+  list(GET CONFIG_OUTPUT 6 LLVM_BUILD_MODE)
+  list(GET CONFIG_OUTPUT 7 LLVM_VERSION_S)
 
   set(LLVM_VERSION_SAVE "${LLVM_VERSION_S}")
 
@@ -311,7 +300,6 @@ else()
   set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
   set(LLVM_MAIN_INCLUDE_DIR ${INCLUDE_DIR} CACHE PATH "Path to llvm/include")
   set(LLVM_BINARY_DIR ${LLVM_OBJ_ROOT} CACHE PATH "Path to LLVM build tree")
-  set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
 
   set(LLVM_DIR "${LLVM_BINARY_DIR}")
 
@@ -334,8 +322,8 @@ else()
   # We try to keep these locations consistent with the builtin_llvm. This is important
   # for the LLVMRES target.
   # FIXME: In longer term, we do not really need this and may want to adjust LLVMRES.
-  set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_CURRENT_BINARY_DIR}/llvm/src/${CMAKE_CFG_INTDIR}/bin)
-  set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_CURRENT_BINARY_DIR}/llvm/src/${CMAKE_CFG_INTDIR}/lib)
+  set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_CURRENT_BINARY_DIR}/llvm-project/llvm/${CMAKE_CFG_INTDIR}/bin)
+  set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_CURRENT_BINARY_DIR}/llvm-project/llvm/${CMAKE_CFG_INTDIR}/lib)
 
   if(WIN32 OR CYGWIN)
     # DLL platform -- put DLLs into bin.
@@ -358,10 +346,10 @@ else()
   include(VersionFromVCS)
 
   set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}")
-  if (${PACKAGE_VERSION} MATCHES "13\\.0(|\\.[0-9]+)")
+  if (${PACKAGE_VERSION} MATCHES "${ROOT_LLVM_VERSION_REQUIRED_MAJOR}\\.0(|\\.[0-9]+)")
     message(STATUS "Using LLVM external library - ${PACKAGE_VERSION}")
   else()
-    message(FATAL_ERROR "LLVM version different from ROOT supported, please try 13.0.x")
+    message(FATAL_ERROR "LLVM version ${LLVM_PACKAGE_VERSION} different from ROOT supported, please try ${ROOT_LLVM_VERSION_REQUIRED_MAJOR}.0.x")
   endif()
 
   if (NOT DEFINED LLVM_INCLUDE_TESTS)
@@ -395,7 +383,7 @@ Please install Python or specify the PYTHON_EXECUTABLE CMake variable.")
         AND EXISTS ${LLVM_TOOLS_BINARY_DIR}/not${CMAKE_EXECUTABLE_SUFFIX})
       set(LLVM_UTILS_PROVIDED ON)
     endif()
-    set(ROOT_LLVM_MAIN_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/llvm/src/")
+    set(ROOT_LLVM_MAIN_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/llvm-project/llvm/")
     if(EXISTS ${ROOT_LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
       # Note: path not really used, except for checking if lit was found
       set(LLVM_LIT ${ROOT_LLVM_MAIN_SRC_DIR}/utils/lit/lit.py CACHE PATH "The location of the lit test runner.")
@@ -458,7 +446,10 @@ Please install Python or specify the PYTHON_EXECUTABLE CMake variable.")
     # install-clang-cpp target defined by LLVM's cmake module
     set(CLANG_LINKS_TO_CREATE clang++ clang-cl)
 
-    add_subdirectory(llvm/src/tools/clang EXCLUDE_FROM_ALL)
+    # Disable linking against shared LLVM
+    set(LLVM_LINK_LLVM_DYLIB OFF)
+
+    add_subdirectory(llvm-project/clang EXCLUDE_FROM_ALL)
   endif(builtin_clang)
 
   set( CLANG_BUILT_STANDALONE 1 )
@@ -467,15 +458,15 @@ endif(builtin_llvm)
 
 if (builtin_clang)
   if (builtin_llvm)
-    # For builtin LLVM this is set in interpreter/llvm/src/CMakeLists.txt
+    # For builtin LLVM this is set in interpreter/llvm-project/llvm/CMakeLists.txt
     set(Clang_DIR "${LLVM_BINARY_DIR}/tools/clang/")
   else()
-    set(Clang_DIR "${CMAKE_BINARY_DIR}/interpreter/llvm/src/tools/clang/")
+    set(Clang_DIR "${CMAKE_BINARY_DIR}/interpreter/llvm-project/clang/")
     set(Clang_Config_ExtraPathHints "${Clang_DIR}cmake/modules/CMakeFiles")
   endif()
   set(CLANG_INCLUDE_DIRS
-    ${CMAKE_SOURCE_DIR}/interpreter/llvm/src/tools/clang/include
-    ${CMAKE_BINARY_DIR}/interpreter/llvm/src/tools/clang/include
+    ${CMAKE_SOURCE_DIR}/interpreter/llvm-project/clang/include
+    ${CMAKE_BINARY_DIR}/interpreter/llvm-project/llvm/tools/clang/include
     CACHE STRING "Clang include directories.")
 else()
   set(Clang_DIR "${LLVM_BINARY_DIR}/lib/cmake/clang/")
@@ -492,7 +483,7 @@ if (builtin_cling)
   # so we just use the normal way of doing this and read the llvm directory
   # compilation properties.
   if (builtin_llvm)
-    get_directory_property(LLVM_DEFS DIRECTORY llvm/src COMPILE_DEFINITIONS)
+    get_directory_property(LLVM_DEFS DIRECTORY llvm-project/llvm COMPILE_DEFINITIONS)
     # Turns DEFINE1;DEFINE2 to -DDEFINE1 -DDEFINE2
     string (REPLACE ";" " -D" LLVM_DEFS ";${LLVM_DEFS}")
   endif()
@@ -518,6 +509,7 @@ if (builtin_cling)
     string(APPEND CMAKE_C_FLAGS " -fPIC")
   endif(LLVM_ENABLE_PIC AND NOT MSVC)
   # Avoid cling being installed under ROOTSYS/include.
+  set(CLING_ROOT_BUILD ON)
   add_subdirectory(cling EXCLUDE_FROM_ALL)
   add_dependencies(CLING ${CLING_LIBRARIES})
 
diff --git a/interpreter/cling/CMakeLists.txt b/interpreter/cling/CMakeLists.txt
index 57b4984edd33a..75a4a84ec6006 100644
--- a/interpreter/cling/CMakeLists.txt
+++ b/interpreter/cling/CMakeLists.txt
@@ -1,17 +1,18 @@
-cmake_minimum_required(VERSION 3.4.3)
+if(WIN32)
+  # We need cmake to support exporting of symbols not only from libraries but
+  # from executables too. This way cling can find symbols from its own
+  # executable during runtime.
+  cmake_minimum_required(VERSION 3.6.2)
+else(WIN32)
+  # support of earlier cmake versions will be removed soon
+  cmake_minimum_required(VERSION 3.5)
+endif(WIN32)
 
 # If we are not building as a part of LLVM, build Cling as an
 # standalone project, using LLVM as an external library:
 if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
   project(Cling)
 
-  if(WIN32)
-    # We need cmake to support exporting of symbols not only from libraries but
-    # from executables too. This way cling can find symbols from its own
-    # executable during runtime.
-    cmake_minimum_required(VERSION 3.6.2)
-  endif(WIN32)
-
   # Rely on llvm-config.
   set(CONFIG_OUTPUT)
   find_program(LLVM_CONFIG "llvm-config")
@@ -22,8 +23,7 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
       "--bindir"
       "--libdir"
       "--includedir"
-      "--prefix"
-      "--src-root")
+      "--prefix")
     execute_process(
       COMMAND ${CONFIG_COMMAND}
       RESULT_VARIABLE HAD_ERROR
@@ -47,7 +47,6 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
   list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
   list(GET CONFIG_OUTPUT 3 INCLUDE_DIR)
   list(GET CONFIG_OUTPUT 4 LLVM_OBJ_ROOT)
-  list(GET CONFIG_OUTPUT 5 MAIN_SRC_DIR)
 
   if(NOT MSVC_IDE)
     set(LLVM_ENABLE_ASSERTIONS ${ENABLE_ASSERTIONS}
@@ -60,7 +59,6 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
   set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
   set(LLVM_MAIN_INCLUDE_DIR ${INCLUDE_DIR} CACHE PATH "Path to llvm/include")
   set(LLVM_BINARY_DIR ${LLVM_OBJ_ROOT} CACHE PATH "Path to LLVM build tree")
-  set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
 
   find_program(LLVM_TABLEGEN_EXE "llvm-tblgen" ${LLVM_TOOLS_BINARY_DIR}
     NO_DEFAULT_PATH)
@@ -170,7 +168,11 @@ Please install Python or specify the PYTHON_EXECUTABLE CMake variable.")
 
   set( CLING_BUILT_STANDALONE 1 )
   set(BACKEND_PACKAGE_STRING "LLVM ${LLVM_PACKAGE_VERSION}")
-else() # Building as part of LLVM
+elseif(DEFINED CLING_ROOT_BUILD)
+  message(STATUS "Building Cling as part of ROOT")
+  # we do not need to include LLVMConfig again, already done
+else()
+  message(STATUS "Building Cling as part of LLVM")
   set(BACKEND_PACKAGE_STRING "${PACKAGE_STRING}")
   # Try finding the LLVMConfig.cmake if we build against prebuilt LLVM
   set(LLVM_CMAKE_PATH "${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
@@ -180,8 +182,13 @@ else() # Building as part of LLVM
     include(${LLVMCONFIG_FILE})
   endif()
   if (NOT CLANG_INCLUDE_DIRS)
-    set (CLANG_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/tools/clang/include"
-      "${CMAKE_BINARY_DIR}/tools/clang/include")
+    set (CLANG_INCLUDE_DIRS "${LLVM_MAIN_SRC_DIR}/tools/clang/include")
+    if (NOT EXISTS ${CLANG_INCLUDE_DIRS})
+      # Otherwise assume the monorepo layout.
+      set (CLANG_INCLUDE_DIRS ${LLVM_MAIN_SRC_DIR}/../clang/include )
+    endif()
+    set (CLANG_INCLUDE_DIRS "${CLANG_INCLUDE_DIRS}"
+      "${LLVM_BINARY_DIR}/tools/clang/include")
   endif()
 endif()
 
@@ -193,7 +200,7 @@ endif()
 set(CLING_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
 set(CLING_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
 set(LLVM_TOOLS_BINARY_DIR "${LLVM_BINARY_DIR}/bin")
-if(DEFINED ROOT_BINARY_DIR)
+if(DEFINED CLING_ROOT_BUILD)
   set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${LLVM_TOOLS_BINARY_DIR}")
 endif()
 
@@ -293,7 +300,7 @@ endif ()
 # The package needs to be compiler without RTTI information
 if(MSVC)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -GR-")
-  if(NOT DEFINED ROOT_BINARY_DIR)
+  if(NOT DEFINED CLING_ROOT_BUILD)
     # Add the /std:c++XX flag for Visual Studio if not building as part of ROOT
     if(MSVC_VERSION GREATER_EQUAL 1920)
       set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std:c++17")
@@ -325,7 +332,7 @@ file (STRINGS "VERSION" CLING_VERSION)
 string(REGEX REPLACE "([0-9]).[0-9]+~[a-zA-Z]+" "\\1" CLING_VERSION_MAJOR ${CLING_VERSION})
 string(REGEX REPLACE "[0-9].([0-9]+)~[a-zA-Z]+" "\\1" CLING_VERSION_MINOR ${CLING_VERSION})
 
-if(DEFINED ROOT_BINARY_DIR)
+if(DEFINED CLING_ROOT_BUILD)
   # Building as part of ROOT; visibility is "inherited" from ROOT/interpreter.
   set(CLING_VERSION ROOT_${CLING_VERSION})
 else()
@@ -415,7 +422,8 @@ macro(add_cling_library name)
     endif()
   endif()
 
-  llvm_add_library(${name} ${ARG_ENABLE_SHARED} ${ARG_UNPARSED_ARGUMENTS} ${srcs})
+  # Set DISABLE_LLVM_LINK_LLVM_DYLIB to disable linking against shared LLVM
+  llvm_add_library(${name} ${ARG_ENABLE_SHARED} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARG_UNPARSED_ARGUMENTS} ${srcs})
 
   if (MSVC AND cling_ex_file_match)
     # /EHs because cling_runtime_internal_throwIfInvalidPointer is extern “Câ€
diff --git a/interpreter/cling/cmake/modules/CMakeLists.txt b/interpreter/cling/cmake/modules/CMakeLists.txt
index 444575e5d73e9..e28220db6a06b 100644
--- a/interpreter/cling/cmake/modules/CMakeLists.txt
+++ b/interpreter/cling/cmake/modules/CMakeLists.txt
@@ -2,7 +2,7 @@
 # link against them. LLVM calls its version of this file LLVMExports.cmake, but
 # the usual CMake convention seems to be ${Project}Targets.cmake.
 set(CLING_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/cling)
-set(cling_cmake_builddir "${LLVM_BINARY_DIR}/${CLING_INSTALL_PACKAGE_DIR}")
+set(cling_cmake_builddir "${CLING_BINARY_DIR}/${CLING_INSTALL_PACKAGE_DIR}")
 
 # Keep this in sync with llvm/cmake/CMakeLists.txt!
 set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)
diff --git a/interpreter/cling/include/cling/Interpreter/ClangInternalState.h b/interpreter/cling/include/cling/Interpreter/ClangInternalState.h
index e9972ca88d31a..f3e5e21d08167 100644
--- a/interpreter/cling/include/cling/Interpreter/ClangInternalState.h
+++ b/interpreter/cling/include/cling/Interpreter/ClangInternalState.h
@@ -79,7 +79,7 @@ namespace cling {
     ///
     bool differentContent(const std::string& file1, const std::string& file2,
                           const char* type = nullptr, bool verbose = false,
-               const llvm::SmallVectorImpl* ignores = 0) const;
+               const llvm::SmallVectorImpl* ignores = nullptr) const;
 
     ///\brief Return the llvm::Module this state is bound too.
     ///
@@ -95,7 +95,7 @@ namespace cling {
                                       const clang::Preprocessor& PP);
   private:
     llvm::raw_fd_ostream* createOutputFile(llvm::StringRef OutFile,
-                                           std::string* TempPathName = 0,
+                                           std::string* TempPathName = nullptr,
                                            bool RemoveFileOnSignal = true);
   };
 } // end namespace cling
diff --git a/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h b/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h
index 406e54f2a87da..d4868971f21af 100644
--- a/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h
+++ b/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h
@@ -208,7 +208,7 @@ namespace cling {
     ///\param[out] exists - sets if the file exists. Useful to distinguish if it
     ///            is a library but of incompatible file format.
     ///
-    static bool isSharedLibrary(llvm::StringRef libFullPath, bool* exists = 0);
+    static bool isSharedLibrary(llvm::StringRef libFullPath, bool *exists = nullptr);
   };
 } // end namespace cling
 #endif // CLING_DYNAMIC_LIBRARY_MANAGER_H
diff --git a/interpreter/cling/include/cling/Interpreter/DynamicLookupRuntimeUniverse.h b/interpreter/cling/include/cling/Interpreter/DynamicLookupRuntimeUniverse.h
index 35502757540d7..8942810f200b4 100644
--- a/interpreter/cling/include/cling/Interpreter/DynamicLookupRuntimeUniverse.h
+++ b/interpreter/cling/include/cling/Interpreter/DynamicLookupRuntimeUniverse.h
@@ -55,7 +55,7 @@ namespace runtime {
         // Check whether the expected return type and the actual return type are
         // compatible with Sema::CheckAssingmentConstraints or
         // ASTContext::typesAreCompatible.
-        return result.simplisticCastAs();
+        return result.castAs();
       return T();
     }
 
diff --git a/interpreter/cling/include/cling/Interpreter/Interpreter.h b/interpreter/cling/include/cling/Interpreter/Interpreter.h
index 4cf115eba47a3..4ded5c4f7182d 100644
--- a/interpreter/cling/include/cling/Interpreter/Interpreter.h
+++ b/interpreter/cling/include/cling/Interpreter/Interpreter.h
@@ -10,6 +10,10 @@
 #ifndef CLING_INTERPRETER_H
 #define CLING_INTERPRETER_H
 
+#ifndef LLVM_PATH
+#define LLVM_PATH nullptr
+#endif
+
 #include "cling/Interpreter/InvocationOptions.h"
 #include "cling/Interpreter/RuntimeOptions.h"
 
@@ -255,7 +259,7 @@ namespace cling {
     ///
     CompilationResult DeclareInternal(const std::string& input,
                                       const CompilationOptions& CO,
-                                      Transaction** T = 0) const;
+                                      Transaction** T = nullptr) const;
 
     ///\brief Worker function, building block for interpreter's public
     /// interfaces.
@@ -272,8 +276,8 @@ namespace cling {
     ///
     CompilationResult EvaluateInternal(const std::string& input,
                                        CompilationOptions CO,
-                                       Value* V = 0,
-                                       Transaction** T = 0,
+                                       Value* V = nullptr,
+                                       Transaction** T = nullptr,
                                        size_t wrapPoint = 0);
 
     ///\brief Worker function to code complete after all the mechanism
@@ -312,7 +316,7 @@ namespace cling {
     ///\returns The result of the execution.
     ///
     ExecutionResult RunFunction(const clang::FunctionDecl* FD,
-                                Value* res = 0);
+                                Value* res = nullptr);
 
     ///\brief Compile the function definition and return its Decl.
     ///
@@ -357,7 +361,7 @@ namespace cling {
     ///\param[in] extraLibHandle - resolve symbols also from this dylib
     ///\param[in] noRuntime - flag to control the presence of runtime universe
     ///
-    Interpreter(int argc, const char* const* argv, const char* llvmdir = 0,
+    Interpreter(int argc, const char* const* argv, const char* llvmdir = LLVM_PATH,
                 const ModuleFileExtensions& moduleExtensions = {},
                 void *extraLibHandle = nullptr, bool noRuntime = false)
         : Interpreter(argc, argv, llvmdir, moduleExtensions, extraLibHandle,
@@ -374,7 +378,7 @@ namespace cling {
     ///\param[in] noRuntime - flag to control the presence of runtime universe
     ///
     Interpreter(const Interpreter& parentInterpreter, int argc,
-                const char* const* argv, const char* llvmdir = 0,
+                const char* const* argv, const char* llvmdir = LLVM_PATH,
                 const ModuleFileExtensions& moduleExtensions = {},
                 void *extraLibHandle = nullptr, bool noRuntime = true);
 
@@ -521,8 +525,8 @@ namespace cling {
     ///
     ///\returns Whether the operation was fully successful.
     ///
-    CompilationResult process(const std::string& input, Value* V = 0,
-                              Transaction** T = 0,
+    CompilationResult process(const std::string& input, Value* V = nullptr,
+                              Transaction** T = nullptr,
                               bool disableValuePrinting = false);
 
     ///\brief Parses input line, which doesn't contain statements. No code
@@ -537,7 +541,7 @@ namespace cling {
     ///\returns Whether the operation was fully successful.
     ///
     CompilationResult parse(const std::string& input,
-                            Transaction** T = 0) const;
+                            Transaction** T = nullptr) const;
     /// Loads a C++ Module with a given name by synthesizing an Import decl.
     /// This routine checks if there is a modulemap in the current directory
     /// and loads it.
@@ -594,7 +598,7 @@ namespace cling {
     ///
     ///\returns Whether the operation was fully successful.
     ///
-    CompilationResult declare(const std::string& input, Transaction** T = 0);
+    CompilationResult declare(const std::string& input, Transaction** T = nullptr);
 
     ///\brief Compiles input line, which contains only expressions.
     ///
@@ -623,7 +627,7 @@ namespace cling {
     ///
     ///\returns Whether the operation was fully successful.
     ///
-    CompilationResult echo(const std::string& input, Value* V = 0);
+    CompilationResult echo(const std::string& input, Value* V = nullptr);
 
     ///\brief Compiles input line and runs.
     ///
@@ -673,7 +677,7 @@ namespace cling {
     ///\returns result of the compilation.
     ///
     CompilationResult loadHeader(const std::string& filename,
-                                 Transaction** T = 0);
+                                 Transaction** T = nullptr);
 
     ///\brief Loads header file or shared library.
     ///
@@ -685,7 +689,7 @@ namespace cling {
     ///
     CompilationResult loadFile(const std::string& filename,
                                bool allowSharedLib = true,
-                               Transaction** T = 0);
+                               Transaction** T = nullptr);
 
     ///\brief Unloads (forgets) a transaction from AST and JITed symbols.
     ///
@@ -810,7 +814,7 @@ namespace cling {
     ///\param[in]  D       - the global's Decl to find
     ///\param[out] fromJIT - whether the symbol was JITted.
     void* getAddressOfGlobal(const clang::GlobalDecl& D,
-                             bool* fromJIT = 0) const;
+                             bool* fromJIT = nullptr) const;
 
     ///\brief Gets the address of an existing global and whether it was JITted.
     ///
@@ -820,7 +824,7 @@ namespace cling {
     ///\param[in]  SymName - the name of the global to search
     ///\param[out] fromJIT - whether the symbol was JITted.
     ///
-    void* getAddressOfGlobal(llvm::StringRef SymName, bool* fromJIT = 0) const;
+    void* getAddressOfGlobal(llvm::StringRef SymName, bool* fromJIT = nullptr) const;
 
     ///\brief Get a given macro definition by name.
     ///
@@ -860,7 +864,7 @@ namespace cling {
                         clang::ASTContext& Ctx,
                         llvm::raw_ostream& out,
                         bool enableMacros = false,
-                        llvm::raw_ostream* logs = 0,
+                        llvm::raw_ostream* logs = nullptr,
                         IgnoreFilesFunc_t ignoreFiles =
                           [](const clang::PresumedLoc&) { return false;}) const;
 
diff --git a/interpreter/cling/include/cling/Interpreter/LookupHelper.h b/interpreter/cling/include/cling/Interpreter/LookupHelper.h
index 7f25944af5784..6e6e281470e13 100644
--- a/interpreter/cling/include/cling/Interpreter/LookupHelper.h
+++ b/interpreter/cling/include/cling/Interpreter/LookupHelper.h
@@ -102,7 +102,7 @@ namespace cling {
     ///
     const clang::Decl* findScope(llvm::StringRef className,
                                  DiagSetting diagOnOff,
-                                 const clang::Type** resultType = 0,
+                                 const clang::Type** resultType = nullptr,
                                  bool instantiateTemplate = true) const;
 
 
diff --git a/interpreter/cling/include/cling/Interpreter/RuntimeUniverse.h b/interpreter/cling/include/cling/Interpreter/RuntimeUniverse.h
index 446a37e69f3a6..c6f0f2eab0972 100644
--- a/interpreter/cling/include/cling/Interpreter/RuntimeUniverse.h
+++ b/interpreter/cling/include/cling/Interpreter/RuntimeUniverse.h
@@ -171,17 +171,11 @@ namespace cling {
       ///\param[in] placement - where to copy
       ///\param[in] size - size of the array.
       ///
-      template 
+      template 
       void copyArray(T* src, void* placement, std::size_t size) {
         for (std::size_t i = 0; i < size; ++i)
           new ((void*)(((T*)placement) + i)) T(src[i]);
       }
-
-      // "size" is the number of elements even for subarrays; flatten the type:
-      template 
-      void copyArray(const T (*src)[N], void* placement, std::size_t size) {
-        copyArray(src[0], placement, size);
-      }
     } // end namespace internal
   } // end namespace runtime
 } // end namespace cling
diff --git a/interpreter/cling/include/cling/Interpreter/Transaction.h b/interpreter/cling/include/cling/Interpreter/Transaction.h
index 1ce76391174ff..d16344cf3ccf6 100644
--- a/interpreter/cling/include/cling/Interpreter/Transaction.h
+++ b/interpreter/cling/include/cling/Interpreter/Transaction.h
@@ -74,11 +74,11 @@ namespace cling {
       ConsumerCallInfo m_Call;
       DelayCallInfo(clang::DeclGroupRef DGR, ConsumerCallInfo CCI)
         : m_DGR(DGR), m_Call(CCI) {}
-      inline bool operator==(const DelayCallInfo& rhs) {
+      inline bool operator==(const DelayCallInfo& rhs) const {
         return m_DGR.getAsOpaquePtr() == rhs.m_DGR.getAsOpaquePtr()
           && m_Call == rhs.m_Call;
       }
-      inline bool operator!=(const DelayCallInfo& rhs) {
+      inline bool operator!=(const DelayCallInfo& rhs) const {
         return !operator==(rhs);
       }
       void dump() const;
@@ -100,10 +100,10 @@ namespace cling {
       MacroDirectiveInfo(clang::IdentifierInfo* II,
                          const clang::MacroDirective* MD)
                 : m_II(II), m_MD(MD) {}
-      inline bool operator==(const MacroDirectiveInfo& rhs) {
+      inline bool operator==(const MacroDirectiveInfo& rhs) const {
         return m_II == rhs.m_II && m_MD == rhs.m_MD;
       }
-      inline bool operator!=(const MacroDirectiveInfo& rhs) {
+      inline bool operator!=(const MacroDirectiveInfo& rhs) const {
         return !operator==(rhs);
       }
       void dump(const clang::Preprocessor& PP) const;
@@ -272,22 +272,22 @@ namespace cling {
     const_nested_iterator nested_begin() const {
       if (hasNestedTransactions())
         return m_NestedTransactions->begin();
-      return 0;
+      return nullptr;
     }
     const_nested_iterator nested_end() const {
       if (hasNestedTransactions())
         return m_NestedTransactions->end();
-      return 0;
+      return nullptr;
     }
     const_reverse_nested_iterator rnested_begin() const {
       if (hasNestedTransactions())
         return m_NestedTransactions->rbegin();
-      return const_reverse_nested_iterator(0);
+      return const_reverse_nested_iterator(nullptr);
     }
     const_reverse_nested_iterator rnested_end() const {
       if (hasNestedTransactions())
         return m_NestedTransactions->rend();
-      return const_reverse_nested_iterator(0);
+      return const_reverse_nested_iterator(nullptr);
     }
 
     /// Macro iteration
@@ -432,7 +432,7 @@ namespace cling {
 
     Transaction* getLastNestedTransaction() const {
       if (!hasNestedTransactions())
-        return 0;
+        return nullptr;
       return m_NestedTransactions->back();
     }
 
diff --git a/interpreter/cling/include/cling/Interpreter/Value.h b/interpreter/cling/include/cling/Interpreter/Value.h
index 829b89ddf33b9..65375856f95c4 100644
--- a/interpreter/cling/include/cling/Interpreter/Value.h
+++ b/interpreter/cling/include/cling/Interpreter/Value.h
@@ -12,9 +12,7 @@
 
 #include "cling/Interpreter/Visibility.h"
 
-#include 
-#include 
-#include 
+#include  // for uintptr_t
 
 namespace llvm {
   class raw_ostream;
@@ -23,9 +21,66 @@ namespace llvm {
 namespace clang {
   class ASTContext;
   class QualType;
-  class RecordDecl;
 }
 
+// FIXME: Merge with clang::BuiltinType::getName
+#define CLING_VALUE_BUILTIN_TYPES                                      \
+  /*  X(void, Void) */                                                 \
+  X(bool, Bool)                                                        \
+  X(char, Char_S)                                                      \
+  /*X(char, Char_U)*/                                                  \
+  X(signed char, SChar)                                                \
+  X(short, Short)                                                      \
+  X(int, Int)                                                          \
+  X(long, Long)                                                        \
+  X(long long, LongLong)                                               \
+  /*X(__int128, Int128)*/                                              \
+  X(unsigned char, UChar)                                              \
+  X(unsigned short, UShort)                                            \
+  X(unsigned int, UInt)                                                \
+  X(unsigned long, ULong)                                              \
+  X(unsigned long long, ULongLong)                                     \
+  /*X(unsigned __int128, UInt128)*/                                    \
+  /*X(half, Half)*/                                                    \
+  /*X(__bf16, BFloat16)*/                                              \
+  X(float, Float)                                                      \
+  X(double, Double)                                                    \
+  X(long double, LongDouble)                                           \
+  /*X(short _Accum, ShortAccum)                                        \
+    X(_Accum, Accum)                                                   \
+    X(long _Accum, LongAccum)                                          \
+    X(unsigned short _Accum, UShortAccum)                              \
+    X(unsigned _Accum, UAccum)                                         \
+    X(unsigned long _Accum, ULongAccum)                                \
+    X(short _Fract, ShortFract)                                        \
+    X(_Fract, Fract)                                                   \
+    X(long _Fract, LongFract)                                          \
+    X(unsigned short _Fract, UShortFract)                              \
+    X(unsigned _Fract, UFract)                                         \
+    X(unsigned long _Fract, ULongFract)                                \
+    X(_Sat short _Accum, SatShortAccum)                                \
+    X(_Sat _Accum, SatAccum)                                           \
+    X(_Sat long _Accum, SatLongAccum)                                  \
+    X(_Sat unsigned short _Accum, SatUShortAccum)                      \
+    X(_Sat unsigned _Accum, SatUAccum)                                 \
+    X(_Sat unsigned long _Accum, SatULongAccum)                        \
+    X(_Sat short _Fract, SatShortFract)                                \
+    X(_Sat _Fract, SatFract)                                           \
+    X(_Sat long _Fract, SatLongFract)                                  \
+    X(_Sat unsigned short _Fract, SatUShortFract)                      \
+    X(_Sat unsigned _Fract, SatUFract)                                 \
+    X(_Sat unsigned long _Fract, SatULongFract)                        \
+    X(_Float16, Float16)                                               \
+    X(__float128, Float128)                                            \
+    X(__ibm128, Ibm128)*/                                              \
+  X(wchar_t, WChar_S)                                                  \
+  /*X(wchar_t, WChar_U)*/                                              \
+  /*X(char8_t, Char8)*/                                                \
+  X(char16_t, Char16)                                                  \
+  X(char32_t, Char32)                                                  \
+  /*X(std::nullptr_t, NullPtr) same as kPtrOrObjTy*/
+
+
 namespace cling {
   class Interpreter;
 
@@ -40,78 +95,42 @@ namespace cling {
   /// and parameters for function calls.
   ///
   class CLING_LIB_EXPORT Value {
-  protected:
+  public:
     ///\brief Multi-purpose storage.
     ///
     union Storage {
-      long long m_LL;
-      unsigned long long m_ULL;
+#define X(type, name) type m_##name;
+      CLING_VALUE_BUILTIN_TYPES
+#undef X
       void* m_Ptr; /// Can point to allocation, see needsManagedAllocation().
-      float m_Float;
-      double m_Double;
-      long double m_LongDouble;
     };
 
+    enum TypeKind : short {
+      kInvalid = 0,
+#define X(type, name) \
+      k##name,
+      CLING_VALUE_BUILTIN_TYPES
+#undef X
+      kVoid,
+      kPtrOrObjTy
+    };
+
+  protected:
     /// \brief The actual value.
     Storage m_Storage;
 
-    enum EStorageType {
-      kSignedIntegerOrEnumerationType,
-      kUnsignedIntegerOrEnumerationType,
-      kDoubleType,
-      kFloatType,
-      kLongDoubleType,
-      kPointerType,
-      kManagedAllocation,
-      kUnsupportedType
-    };
+    /// \brief If the \c Value class needs to alloc and dealloc memory.
+    bool m_NeedsManagedAlloc = false;
 
-    /// \brief Which part in m_Storage is active.
-    EStorageType m_StorageType;
+    TypeKind m_TypeKind = Value::kInvalid;
 
     /// \brief The value's type, stored as opaque void* to reduce
     /// dependencies.
-    void* m_Type;
+    void* m_Type = nullptr;
 
     ///\brief Interpreter that produced the value.
     ///
-    Interpreter* m_Interpreter;
-
-    /// \brief Retrieve the underlying, canonical, desugared, unqualified type.
-    EStorageType getStorageType() const { return m_StorageType; }
-
-    /// \brief Determine the underlying, canonical, desugared, unqualified type:
-    /// the element of Storage to be used.
-    static EStorageType determineStorageType(clang::QualType QT);
-
-    /// \brief Determine the underlying, canonical, desugared, unqualified type:
-    /// the element of Storage to be used.
-    static constexpr EStorageType determineStorageTypeT(...) {
-      return kManagedAllocation;
-    }
-
-    template ::value>::type>
-    static constexpr EStorageType determineStorageTypeT(T*) {
-      return std::is_signed::value
-        ? kSignedIntegerOrEnumerationType
-        : kUnsignedIntegerOrEnumerationType;
-    }
-    static constexpr EStorageType determineStorageTypeT(double*) {
-      return kDoubleType;
-    }
-    static constexpr EStorageType determineStorageTypeT(float*) {
-      return kFloatType;
-    }
-    static constexpr EStorageType determineStorageTypeT(long double*) {
-      return kDoubleType;
-    }
-    template 
-    static constexpr EStorageType determineStorageTypeT(T**) {
-      return kPointerType;
-    }
-    static constexpr EStorageType determineStorageTypeT(void*) {
-      return kUnsupportedType;
-    }
+    Interpreter* m_Interpreter = nullptr;
 
     /// \brief Allocate storage as needed by the type.
     void ManagedAllocate();
@@ -120,65 +139,67 @@ namespace cling {
     ///   dependencies.
     void AssertOnUnsupportedTypeCast() const;
 
-    size_t GetNumberOfElements() const;
+    bool isPointerOrObjectType() const { return m_TypeKind == kPtrOrObjTy; }
+    bool isBuiltinType() const {
+      return m_TypeKind != kInvalid && !isPointerOrObjectType();
+    };
 
-    // Allow simplisticCastAs to be partially specialized.
+    // Allow castAs to be partially specialized.
     template
     struct CastFwd {
       static T cast(const Value& V) {
-        EStorageType storageType = V.getStorageType();
-        switch (storageType) {
-        case kSignedIntegerOrEnumerationType:
-          return (T) V.getAs();
-        case kUnsignedIntegerOrEnumerationType:
-          return (T) V.getAs();
-        case kDoubleType:
-          return (T) V.getAs();
-        case kFloatType:
-          return (T) V.getAs();
-        case kLongDoubleType:
-          return (T) V.getAs();
-        case kPointerType:
-        case kManagedAllocation:
+        if (V.isPointerOrObjectType())
           return (T) (uintptr_t) V.getAs();
-        case kUnsupportedType:
-          V.AssertOnUnsupportedTypeCast();
+        if (V.isInvalid() || V.isVoid()) {
+#ifndef NDEBUG // Removing this might break inlining
+           V.AssertOnUnsupportedTypeCast();
+#endif // NDEBUG
+           return T();
         }
-        return T();
+        return V.getAs();
       }
     };
-
     template
     struct CastFwd {
       static T* cast(const Value& V) {
-        EStorageType storageType = V.getStorageType();
-        if (storageType == kPointerType
-            || storageType == kManagedAllocation)
+        if (V.isPointerOrObjectType())
           return (T*) (uintptr_t) V.getAs();
+#ifndef NDEBUG // Removing this might break inlining
         V.AssertOnUnsupportedTypeCast();
-        return 0;
+#endif // NDEBUG
+        return nullptr;
       }
     };
 
-    Value(void* QualTypeAsOpaquePtr, Interpreter& Interp, EStorageType stType):
-      m_StorageType(stType),
-      m_Type(QualTypeAsOpaquePtr),
-      m_Interpreter(&Interp) {
+    /// \brief Get to the value with type checking casting the underlying
+    /// stored value to T.
+    template  T getAs() const {
+      switch (m_TypeKind) {
+      default:
+#ifndef NDEBUG
+        AssertOnUnsupportedTypeCast();
+#endif // NDEBUG
+        return T();
+#define X(type, name)                                           \
+        case Value::k##name: return (T) m_Storage.m_##name;
+        CLING_VALUE_BUILTIN_TYPES
+#undef X
+      }
     }
 
+    void AssertTypeMismatch(const char* Type) const;
   public:
-    /// \brief Default constructor, creates a value that IsInvalid().
-    Value():
-      m_StorageType(kUnsupportedType), m_Type(nullptr),
-      m_Interpreter(nullptr) {}
+    Value() = default;
     /// \brief Copy a value.
     Value(const Value& other);
     /// \brief Move a value.
     Value(Value&& other):
-      m_Storage(other.m_Storage), m_StorageType(other.m_StorageType),
+      m_Storage(other.m_Storage), m_NeedsManagedAlloc(other.m_NeedsManagedAlloc),
+      m_TypeKind(other.m_TypeKind),
       m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) {
       // Invalidate other so it will not release.
-      other.m_StorageType = kUnsupportedType;
+      other.m_NeedsManagedAlloc = false;
+      other.m_TypeKind = kInvalid;
     }
 
     /// \brief Construct a valid but uninitialized Value. After this call the
@@ -189,16 +210,20 @@ namespace cling {
     /// \brief Destruct the value; calls ManagedFree() if needed.
     ~Value();
 
-    /// \brief Create a valid but ininitialized Value. After this call the
-    ///   value's storage can be accessed; i.e. calls ManagedAllocate() if
-    ///   needed.
+    // Avoid including type_traits.
+    template
+    struct dependent_false {
+       static constexpr bool value = false;
+       constexpr operator bool() const noexcept { return value; }
+    };
+    /// \brief Create a valid Value holding a clang::Type deduced from the
+    /// argument. This is useful when we want to create a \c Value with a
+    /// particular value from compiled code.
     template 
-    static Value Create(void* QualTypeAsOpaquePtr, Interpreter& Interp) {
-      EStorageType stType
-        = std::is_reference::value ?
-       determineStorageTypeT((typename std::remove_reference::type**)nullptr)
-        : determineStorageTypeT((T*)nullptr);
-      return Value(QualTypeAsOpaquePtr, Interp, stType);
+    static Value Create(Interpreter& Interp, T val) {
+       static_assert(dependent_false::value,
+                     "Can not instantiate for this type.");
+       return {};
     }
 
     Value& operator =(const Value& other);
@@ -211,57 +236,54 @@ namespace cling {
     /// \brief Whether this type needs managed heap, i.e. the storage provided
     /// by the m_Storage member is insufficient, or a non-trivial destructor
     /// must be called.
-    bool needsManagedAllocation() const {
-      return getStorageType() == kManagedAllocation;
-    }
+    bool needsManagedAllocation() const { return m_NeedsManagedAlloc; }
 
     /// \brief Determine whether the Value has been set.
     //
     /// Determine whether the Value has been set by checking
     /// whether the type is valid.
-    bool isValid() const;
+    bool isValid() const { return m_TypeKind != Value::kInvalid; }
+    bool isInvalid() const { return !isValid(); }
 
     /// \brief Determine whether the Value is set but void.
-    bool isVoid() const;
+    bool isVoid() const { return m_TypeKind == Value::kVoid; }
 
     /// \brief Determine whether the Value is set and not void.
     //
     /// Determine whether the Value is set and not void.
-    /// Only in this case can getAs() or simplisticCastAs() be called.
+    /// Only in this case can we can get the represented value.
     bool hasValue() const { return isValid() && !isVoid(); }
 
-    /// \brief Get a reference to the value without type checking.
-    /// T *must* correspond to type. Else use simplisticCastAs()!
-    template 
-    T& getAs() { return getAs((T*)0); }
-
-    /// \brief Get the value without type checking.
-    /// T *must* correspond to type. Else use simplisticCastAs()!
-    template 
-    T getAs() const { return const_cast(this)->getAs(); }
-
-    template 
-    T*& getAs(T**) { return (T*&)getAs((void**)0); }
-    void*& getAs(void**) { return m_Storage.m_Ptr; }
-    double& getAs(double*) { return m_Storage.m_Double; }
-    long double& getAs(long double*) { return m_Storage.m_LongDouble; }
-    float& getAs(float*) { return m_Storage.m_Float; }
-    long long& getAs(long long*) { return m_Storage.m_LL; }
-    unsigned long long& getAs(unsigned long long*) { return m_Storage.m_ULL; }
-
-    void*& getPtr() { return m_Storage.m_Ptr; }
-    double& getDouble() { return m_Storage.m_Double; }
-    long double& getLongDouble() { return m_Storage.m_LongDouble; }
-    float& getFloat() { return m_Storage.m_Float; }
-    long long& getLL() { return m_Storage.m_LL; }
-    unsigned long long& getULL() { return m_Storage.m_ULL; }
-
+    // FIXME: If the cling::Value is destroyed and it handed out an address that
+    // might be accessing invalid memory.
+    void** getPtrAddress() { return &m_Storage.m_Ptr; }
     void* getPtr() const { return m_Storage.m_Ptr; }
-    double getDouble() const { return m_Storage.m_Double; }
-    long double getLongDouble() const { return m_Storage.m_LongDouble; }
-    float getFloat() const { return m_Storage.m_Float; }
-    long long getLL() const { return m_Storage.m_LL; }
-    unsigned long long getULL() const { return m_Storage.m_ULL; }
+    void setPtr(void* Val) { m_Storage.m_Ptr = Val; }
+
+#ifndef NDEBUG
+#define _STRINGIFY(x) #x
+#define STRINGIFY(x) _STRINGIFY(x)
+    // FIXME: Uncomment and debug the various type mismatches.
+    //#define ASSERT_TYPE_MISMATCH(name) AssertTypeMismatch(STRINGIFY(name))
+    #define ASSERT_TYPE_MISMATCH(name)
+#undef STRINGIFY
+#undef _STRINGIFY
+#else
+    #define ASSERT_TYPE_MISMATCH(name)
+#endif // NDEBUG
+#define X(type, name)                                    \
+    type get##name() const {                             \
+      ASSERT_TYPE_MISMATCH(name);                        \
+      return m_Storage.m_##name;                         \
+    }                                                    \
+    void set##name(type Val) {                           \
+      ASSERT_TYPE_MISMATCH(name);                        \
+      m_Storage.m_##name = Val;                          \
+    }                                                    \
+
+  CLING_VALUE_BUILTIN_TYPES
+
+#undef X
 
     /// \brief Get the value with cast.
     //
@@ -269,7 +291,7 @@ namespace cling {
     /// casting the value of builtins (except void), enums and pointers.
     /// Values referencing an object are treated as pointers to the object.
     template 
-    T simplisticCastAs() const {
+    T castAs() const {
       return CastFwd::cast(*this);
     }
 
@@ -284,6 +306,20 @@ namespace cling {
     void print(llvm::raw_ostream& Out, bool escape = false) const;
     void dump(bool escape = true) const;
   };
+
+  template <> inline void* Value::getAs() const {
+    if (isPointerOrObjectType())
+      return m_Storage.m_Ptr;
+    return (void*)getAs();
+  }
+
+#define X(type, name)                                                   \
+  template <> Value Value::Create(Interpreter& Interp, type val);       \
+
+  CLING_VALUE_BUILTIN_TYPES
+
+#undef X
+
 } // end namespace cling
 
 #endif // CLING_VALUE_H
diff --git a/interpreter/cling/include/cling/MetaProcessor/MetaSema.h b/interpreter/cling/include/cling/MetaProcessor/MetaSema.h
index c83a4628926f7..d4b553802e76f 100644
--- a/interpreter/cling/include/cling/MetaProcessor/MetaSema.h
+++ b/interpreter/cling/include/cling/MetaProcessor/MetaSema.h
@@ -61,7 +61,7 @@ namespace cling {
     ///\param[out] transaction - Transaction containing the loaded file.
     ///
     ActionResult actOnLCommand(llvm::StringRef file,
-                               Transaction** transaction = 0);
+                               Transaction** transaction = nullptr);
 
     ///\brief O command sets the optimization level.
     ///
diff --git a/interpreter/cling/include/cling/Utils/AST.h b/interpreter/cling/include/cling/Utils/AST.h
index 0e549e512e2c1..4e0be2ce7044c 100644
--- a/interpreter/cling/include/cling/Utils/AST.h
+++ b/interpreter/cling/include/cling/Utils/AST.h
@@ -77,9 +77,9 @@ namespace utils {
     ///\returns 0 if the operation wasn't successful.
     ///
     clang::Expr* GetOrCreateLastExpr(clang::FunctionDecl* FD,
-                                     int* FoundAt = 0,
+                                     int* FoundAt = nullptr,
                                      bool omitDeclStmts = true,
-                                     clang::Sema* S = 0);
+                                     clang::Sema* S = nullptr);
 
     ///\brief Return true if the class or template is declared directly in the
     /// std namespace (modulo inline namespace).
@@ -196,7 +196,7 @@ namespace utils {
     ///
     clang::NamespaceDecl* Namespace(clang::Sema* S,
                                     const char* Name,
-                                    const clang::DeclContext* Within = 0);
+                                    const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single named declaration in a given
     /// declaration context.
@@ -209,7 +209,7 @@ namespace utils {
     ///
     clang::NamedDecl* Named(clang::Sema* S,
                             llvm::StringRef Name,
-                            const clang::DeclContext* Within = 0);
+                            const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single named declaration in a given
     /// declaration context.
@@ -222,7 +222,7 @@ namespace utils {
     ///
     clang::NamedDecl* Named(clang::Sema* S,
                             const char* Name,
-                            const clang::DeclContext* Within = 0);
+                            const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single namespace declaration in a given
     /// declaration context.
@@ -236,7 +236,7 @@ namespace utils {
     ///
     clang::NamedDecl* Named(clang::Sema* S,
                             const clang::DeclarationName& Name,
-                            const clang::DeclContext* Within = 0);
+                            const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single named tag declaration ( enums, classes,
     /// structs, and unions) in a given declaration context.
@@ -249,7 +249,7 @@ namespace utils {
     ///
     clang::TagDecl* Tag(clang::Sema* S,
                         llvm::StringRef Name,
-                        const clang::DeclContext* Within = 0);
+                        const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single named tag declaration ( enums, classes,
     /// structs, and unions) in a given declaration context.
@@ -262,7 +262,7 @@ namespace utils {
     ///
     clang::TagDecl* Tag(clang::Sema* S,
                         const char* Name,
-                        const clang::DeclContext* Within = 0);
+                        const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a single named tag declaration ( enums, classes,
     /// structs, and unions) in a given declaration context.
@@ -275,7 +275,7 @@ namespace utils {
     ///
     clang::TagDecl* Tag(clang::Sema* S,
                         const clang::DeclarationName& Name,
-                        const clang::DeclContext* Within = 0);
+                        const clang::DeclContext* Within = nullptr);
 
     ///\brief Quick lookup for a name in possible a declaration context.
     ///
@@ -289,7 +289,7 @@ namespace utils {
     ///\returns the found result if single, -1 if multiple or 0 if not found.
     ///
     void Named(clang::Sema* S, clang::LookupResult& R,
-               const clang::DeclContext* Within = 0);
+               const clang::DeclContext* Within = nullptr);
 
   }
 
diff --git a/interpreter/cling/include/cling/libc.modulemap b/interpreter/cling/include/cling/libc.modulemap
index 87654b1ecf1fe..9137a4283a630 100644
--- a/interpreter/cling/include/cling/libc.modulemap
+++ b/interpreter/cling/include/cling/libc.modulemap
@@ -62,13 +62,4 @@ module "libc" [system] [extern_c] [no_undeclared_includes] {
     export *
     header "wchar.h"
   }
-
-  use "xlocale.h"
-}
-
-// glib specific header. In it's own module because it
-// doesn't exist on some systems with unpatched glib 2.26+
-module "xlocale.h" [system] [extern_c] {
-  export *
-  header "xlocale.h"
 }
diff --git a/interpreter/cling/include/cling/libc_msvc.modulemap b/interpreter/cling/include/cling/libc_msvc.modulemap
index b5636b943e0b4..9424a062c4fe1 100644
--- a/interpreter/cling/include/cling/libc_msvc.modulemap
+++ b/interpreter/cling/include/cling/libc_msvc.modulemap
@@ -32,6 +32,7 @@ module "libc" [system] [extern_c] [no_undeclared_includes] {
     header "stdio.h"
   }
   module "complex.h" {
+    requires missing
     export *
     header "complex.h"
   }
diff --git a/interpreter/cling/include/cling/std.modulemap b/interpreter/cling/include/cling/std.modulemap
index 6f466ddbbbfd2..09f26cfe1ed4a 100644
--- a/interpreter/cling/include/cling/std.modulemap
+++ b/interpreter/cling/include/cling/std.modulemap
@@ -63,6 +63,11 @@ module "std" [system] {
     export *
     header "cmath"
   }
+  module "compare" {
+    requires cplusplus20
+    export *
+    header "compare"
+  }
   module "complex" {
     export *
     header "complex"
@@ -71,6 +76,11 @@ module "std" [system] {
     export *
     header "complex.h"
   }
+  module "concepts" {
+    requires cplusplus20
+    export *
+    header "concepts"
+  }
   module "condition_variable" {
     export *
     header "condition_variable"
@@ -172,6 +182,7 @@ module "std" [system] {
   }
   module "future" {
     export *
+    export bits_alloc_traits_h
     header "future"
   }
 /*  module "hash_map" {
@@ -243,6 +254,11 @@ module "std" [system] {
     export *
     header "memory"
   }
+  module "memory_resource" [optional] {
+    requires cplusplus17
+    export *
+    header "memory_resource"
+  }
   module "mutex" {
     export *
     header "mutex"
@@ -255,6 +271,11 @@ module "std" [system] {
     export *
     header "numeric"
   }
+  module "optional" {
+    requires cplusplus17
+    export *
+    header "optional"
+  }
   module "ostream" {
     export *
     header "ostream"
@@ -288,6 +309,11 @@ module "std" [system] {
 //    export *
 //    header "setjmp.h"
 //  }
+  module "span" {
+    requires cplusplus20
+    export *
+    header "span"
+  }
   module "sstream" {
     export *
     header "sstream"
@@ -362,6 +388,11 @@ module "std" [system] {
     export *
     header "valarray"
   }
+  module "variant" {
+    requires cplusplus17
+    export *
+    header "variant"
+  }
   module "vector" {
     export *
     header "vector"
@@ -375,10 +406,10 @@ module "std" [system] {
     export *
     header "cuchar"
   }
-  //module "experimental/algorithm" {
-  //  export *
-  //  header "experimental/algorithm"
-  //}
+  module "experimental/string_view" {
+    export *
+    header "experimental/string_view"
+  }
   module "ext/functional" {
     export *
     header "ext/functional"
@@ -396,6 +427,15 @@ module "std" [system] {
     export *
     header "ext/numeric"
   }
+  module "ext/type_traits.h" {
+    export *
+    header "ext/type_traits.h"
+  }
+
+  module "bits_alloc_traits_h" {
+    export *
+    header "bits/alloc_traits.h"
+  }
   module "bits/allocator.h" {
     export *
     header "bits/allocator.h"
@@ -404,6 +444,10 @@ module "std" [system] {
     export *
     header "bits/basic_ios.h"
   }
+  module "bits/chrono.h" [optional] {
+    export *
+    header "bits/chrono.h"
+  }
   module "bits/cpp_type_traits.h" {
     export *
     header "bits/cpp_type_traits.h"
@@ -412,18 +456,47 @@ module "std" [system] {
     export *
     header "bits/exception_defines.h"
   }
+  module "bits_invoke_h" {
+    export *
+    export bits_move_h
+    header "bits/invoke.h"
+  }
   module "bits/ios_base.h" {
     export *
     header "bits/ios_base.h"
   }
+  module "bits/iterator_concepts.h" {
+    requires cplusplus20
+    export *
+    header "bits/iterator_concepts.h"
+  }
   module "bits/locale_facets.h" {
     export *
     header "bits/locale_facets.h"
   }
-  module "bits/stl_algobase.h" {
+  module "bits_move_h" {
+    export *
+    header "bits/move.h"
+  }
+  module "bits_stl_algobase_h" {
     export *
     header "bits/stl_algobase.h"
   }
+  module "bits_stl_iterator_h" {
+    export bits_stl_algobase_h
+    export *
+    header "bits/stl_iterator.h"
+  }
+  module "bits/stl_iterator_base_funcs.h" {
+    export *
+    export bits_stl_iterator_base_types_h
+    header "bits/stl_iterator_base_funcs.h"
+  }
+  module "bits_stl_iterator_base_types_h" {
+    export *
+    export bits_stl_algobase_h
+    header "bits/stl_iterator_base_types.h"
+  }
   module "bits/stl_map.h" {
     export *
     export bits_stl_tree_h
@@ -437,4 +510,59 @@ module "std" [system] {
     export *
     header "bits/stl_tree.h"
   }
+  module "bits/range_access.h" {
+    export *
+    export bits_stl_iterator_h
+    header "bits/range_access.h"
+  }
+  module "bits/ranges_algo.h" {
+    requires cplusplus20
+    export *
+    export utility
+    export bits_stl_algo_h
+    header "bits/ranges_algo.h"
+  }
+   module "bits/ranges_algobase.h" {
+    requires cplusplus20
+    export *
+    export initializer_list
+    header "bits/ranges_algobase.h"
+  }
+  explicit module "bits_ranges_base_h" [optional] {
+    requires cplusplus20
+    export *
+    export bits_stl_iterator_h
+    export initializer_list
+    header "bits/ranges_base.h"
+  }
+  module "bits/ranges_util.h" [optional] {
+    requires cplusplus20
+    export *
+    export bits_invoke_h
+    export utility
+    header "bits/ranges_util.h"
+  }
+  module "bits_stl_algo_h" {
+    export *
+    header "bits/stl_algo.h"
+  }
+  module "bits/stl_construct.h" {
+    export *
+    export bits_stl_iterator_base_types_h
+    header "bits/stl_construct.h"
+  }
+  module "bits/uniform_int_dist.h" {
+    export *
+    export bits_stl_algobase_h
+    header "bits/uniform_int_dist.h"
+  }
+  module "bits/utility.h" [optional] {
+    export *
+    header "bits/utility.h"
+  }
+  module "bits/uses_allocator_args.h" [optional] {
+    requires cplusplus17
+    export *
+    header "bits/uses_allocator_args.h"
+  }
 }
diff --git a/interpreter/cling/include/cling/std_msvc.modulemap b/interpreter/cling/include/cling/std_msvc.modulemap
index cef3b5e5b623f..2dff2bc04d657 100644
--- a/interpreter/cling/include/cling/std_msvc.modulemap
+++ b/interpreter/cling/include/cling/std_msvc.modulemap
@@ -61,6 +61,12 @@ module "std" [system] {
     export *
     header "chrono"
   }
+  module "__msvc_chrono.hpp" {
+    requires msvc1934
+    export xtimec_h
+    export *
+    header "__msvc_chrono.hpp"
+  }
   module "cinttypes" {
     export *
     header "cinttypes"
@@ -439,14 +445,6 @@ module "std" [system] {
     export *
     header "xlocbuf"
   }
-  module "xlocinfo" {
-    export *
-    header "xlocinfo"
-  }
-  module "xlocinfo.h" {
-    export *
-    header "xlocinfo.h"
-  }
   module "xlocmes" {
     export *
     header "xlocmes"
@@ -484,12 +482,14 @@ module "std" [system] {
     header "xstring"
   }
   module "xthreads.h" {
+    export thread
     export *
-    textual header "xthreads.h"
+    header "xthreads.h"
   }
-  module "xtimec.h" {
+  module "xtimec_h" {
+    export chrono
     export *
-    textual header "xtimec.h"
+    header "xtimec.h"
   }
   module "xtr1common" {
     export *
@@ -515,4 +515,14 @@ module "std" [system] {
     export *
     header "yvals_core.h"
   }
+  module "xnode_handle.h" {
+    requires cplusplus17
+    export *
+    header "xnode_handle.h"
+  }
+  module "__msvc_iter_core.hpp" {
+    requires msvc1934
+    export *
+    header "__msvc_iter_core.hpp"
+  }
 }
diff --git a/interpreter/cling/lib/Interpreter/ASTTransformer.h b/interpreter/cling/lib/Interpreter/ASTTransformer.h
index 0f0ee2d0d07b3..ef63257376926 100644
--- a/interpreter/cling/lib/Interpreter/ASTTransformer.h
+++ b/interpreter/cling/lib/Interpreter/ASTTransformer.h
@@ -46,7 +46,7 @@ namespace cling {
     ///\param[in] S - The semantic analysis object.
     ///
     ASTTransformer(clang::Sema* S):
-      m_Sema(S), m_Consumer(0), m_Transaction(nullptr) {}
+      m_Sema(S), m_Consumer(nullptr), m_Transaction(nullptr) {}
     virtual ~ASTTransformer();
 
     ///\brief Retrieves the semantic analysis object used for this transaction
diff --git a/interpreter/cling/lib/Interpreter/AutoSynthesizer.cpp b/interpreter/cling/lib/Interpreter/AutoSynthesizer.cpp
index f49c77de1c054..b1d4448fdeff1 100644
--- a/interpreter/cling/lib/Interpreter/AutoSynthesizer.cpp
+++ b/interpreter/cling/lib/Interpreter/AutoSynthesizer.cpp
@@ -23,7 +23,7 @@ namespace cling {
     llvm::DenseSet m_HandledDecls;
   private:
   public:
-    AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(0) {}
+    AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(nullptr) {}
 
     CompoundStmt* Fix(CompoundStmt* CS) {
       if (!CS->size())
diff --git a/interpreter/cling/lib/Interpreter/BackendPasses.cpp b/interpreter/cling/lib/Interpreter/BackendPasses.cpp
index 5311ba274c7dd..0ef3b5f4fcddc 100644
--- a/interpreter/cling/lib/Interpreter/BackendPasses.cpp
+++ b/interpreter/cling/lib/Interpreter/BackendPasses.cpp
@@ -59,8 +59,7 @@ namespace {
       if (!GV.isDiscardableIfUnused(LT))
         return false;
 
-      if (LT == llvm::GlobalValue::InternalLinkage
-          || LT == llvm::GlobalValue::PrivateLinkage) {
+      if (LT == llvm::GlobalValue::InternalLinkage) {
         // We want to keep this GlobalValue around, but have to tell the JIT
         // linker that it should not error on duplicate symbols.
         // FIXME: Ideally the frontend would never emit duplicate symbols and
@@ -259,51 +258,72 @@ namespace {
   // declarations. This reduces the amount of emitted symbols.
   class ReuseExistingWeakSymbols : public ModulePass {
     static char ID;
+    cling::IncrementalJIT &m_JIT;
 
-    bool runOnGlobal(GlobalValue& GV) {
-      if (GV.isDeclaration())
-        return false; // no change.
-
-      // GV is a definition.
-
+    bool shouldRemoveGlobalDefinition(GlobalValue& GV) {
+      // Existing *weak* symbols can be re-used thanks to ODR.
       llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();
       if (!GV.isDiscardableIfUnused(LT) || !GV.isWeakForLinker(LT))
         return false;
 
-      // Find the symbol in JIT or shared libraries (without auto-loading).
-      std::string Name =  GV.getName().str();
-      if (
+      // Find the symbol as existing, previously compiled symbol in the JIT...
+      if (m_JIT.doesSymbolAlreadyExist(GV.getName()))
+        return true;
+
+      // ...or in shared libraries (without auto-loading).
+      std::string Name = GV.getName().str();
 #if !defined(_WIN32)
-        llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name)
+        return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name);
 #else
-        platform::DLSym(Name)
+        return platform::DLSym(Name);
 #endif
-      ) {
+    }
+
+    bool runOnVar(GlobalVariable& GV) {
 #if !defined(_WIN32)
-        // Heuristically, Windows cannot handle cross-library variables; they
-        // must be library-local.
-        if (auto *Var = dyn_cast(&GV)) {
-          Var->setInitializer(nullptr); // make this a declaration
-        } else
+      // Heuristically, Windows cannot handle cross-library variables; they
+      // must be library-local.
+
+      if (GV.isDeclaration())
+        return false; // no change.
+      if (shouldRemoveGlobalDefinition(GV)) {
+        GV.setInitializer(nullptr); // make this a declaration
+        return true; // a change!
+      }
+#endif
+      return false; // no change.
+    }
+
+    bool runOnFunc(Function& Func) {
+      if (Func.isDeclaration())
+        return false; // no change.
+#ifndef _WIN32
+      // MSVC's stdlib gets symbol issues; i.e. apparently: JIT all or none.
+      if (Func.getInstructionCount() < 50) {
+        // This is a small function. Keep its definition to retain it for
+        // inlining: the cost for JITting it is small, and the likelihood
+        // that the call will be inlined is high.
+        return false;
+      }
 #endif
-        if (auto *Func = dyn_cast(&GV)) {
-          Func->deleteBody(); // make this a declaration
-        }
+      if (shouldRemoveGlobalDefinition(Func)) {
+        Func.deleteBody(); // make this a declaration
         return true; // a change!
       }
-      return false;
+      return false; // no change.
     }
 
   public:
-    ReuseExistingWeakSymbols() :
-      ModulePass(ID) {}
+    ReuseExistingWeakSymbols(IncrementalJIT &JIT) :
+      ModulePass(ID), m_JIT(JIT) {}
 
     bool runOnModule(Module &M) override {
       bool ret = false;
+      // FIXME: use SymbolLookupSet, rather than looking up symbol by symbol.
       for (auto &&F: M)
-        ret |= runOnGlobal(F);
+        ret |= runOnFunc(F);
       for (auto &&G: M.globals())
-        ret |= runOnGlobal(G);
+        ret |= runOnVar(G);
       return ret;
     }
   };
@@ -313,8 +333,9 @@ char ReuseExistingWeakSymbols::ID = 0;
 
 
 BackendPasses::BackendPasses(const clang::CodeGenOptions &CGOpts,
-                             llvm::TargetMachine& TM):
+                             IncrementalJIT &JIT, llvm::TargetMachine& TM):
    m_TM(TM),
+   m_JIT(JIT),
    m_CGOpts(CGOpts)
 {}
 
@@ -392,7 +413,7 @@ void BackendPasses::CreatePasses(llvm::Module& M, int OptLevel)
   m_MPM[OptLevel]->add(new KeepLocalGVPass());
   m_MPM[OptLevel]->add(new PreventLocalOptPass());
   m_MPM[OptLevel]->add(new WeakTypeinfoVTablePass());
-  m_MPM[OptLevel]->add(new ReuseExistingWeakSymbols());
+  m_MPM[OptLevel]->add(new ReuseExistingWeakSymbols(m_JIT));
 
   // The function __cuda_module_ctor and __cuda_module_dtor will just generated,
   // if a CUDA fatbinary file exist. Without file path there is no need for the
diff --git a/interpreter/cling/lib/Interpreter/BackendPasses.h b/interpreter/cling/lib/Interpreter/BackendPasses.h
index 87d633c982812..11f753fad68da 100644
--- a/interpreter/cling/lib/Interpreter/BackendPasses.h
+++ b/interpreter/cling/lib/Interpreter/BackendPasses.h
@@ -44,12 +44,13 @@ namespace cling {
     std::array, 4> m_FPM;
 
     llvm::TargetMachine& m_TM;
+    IncrementalJIT &m_JIT;
     const clang::CodeGenOptions &m_CGOpts;
 
     void CreatePasses(llvm::Module& M, int OptLevel);
 
   public:
-    BackendPasses(const clang::CodeGenOptions &CGOpts,
+    BackendPasses(const clang::CodeGenOptions &CGOpts, IncrementalJIT &JIT,
                   llvm::TargetMachine& TM);
     ~BackendPasses();
 
diff --git a/interpreter/cling/lib/Interpreter/CIFactory.cpp b/interpreter/cling/lib/Interpreter/CIFactory.cpp
index 698f7eb63438a..aec153242b9d4 100644
--- a/interpreter/cling/lib/Interpreter/CIFactory.cpp
+++ b/interpreter/cling/lib/Interpreter/CIFactory.cpp
@@ -414,7 +414,7 @@ namespace {
     Opts.MathErrno = 0;
 #endif
 
-#ifdef _REENTRANT
+#ifndef _WIN32
     Opts.POSIXThreads = 1;
 #endif
 #ifdef __FAST_MATH__
@@ -742,8 +742,11 @@ namespace {
       if (!FS.get())
         llvm::errs() << "Error in modulemap.overlay!\n";
 
-      // Load virtual modulemap overlay file
-      CI.getInvocation().addOverlay(FS);
+      // Load virtual modulemap overlay file - we set up an OverlayFileSystem
+      // when calling createFileManager.
+      auto& OverlayVFS =
+          static_cast(CI.getVirtualFileSystem());
+      OverlayVFS.pushOverlay(FS);
     }
   }
 
@@ -1254,6 +1257,13 @@ namespace {
 #if __APPLE__ && __arm64__
     argvCompile.push_back("--target=arm64-apple-darwin20.3.0");
 #endif
+#if __aarch64__
+    // Disable outline-atomics on AArch64; the routines __aarch64_* are defined
+    // in the static library libgcc.a and not necessarily included in libCling
+    // or otherwise present in the process, so the interpreter has a hard time
+    // finding them.
+    argvCompile.push_back("-mno-outline-atomics");
+#endif
 
     // Variables for storing the memory of the C-string arguments.
     // FIXME: We shouldn't use C-strings in the first place, but just use
@@ -1389,10 +1399,6 @@ namespace {
     }
 
     llvm::Triple TheTriple(llvm::sys::getProcessTriple());
-#ifdef _WIN32
-    // COFF format currently needs a few changes in LLVM to function properly.
-    TheTriple.setObjectFormat(llvm::Triple::COFF);
-#endif
     clang::driver::Driver Drvr(argv[0], TheTriple.getTriple(), *Diags);
     //Drvr.setWarnMissingInput(false);
     Drvr.setCheckInputsExist(false); // think foo.C(12)
@@ -1447,7 +1453,9 @@ namespace {
       return CI.release();
     }
 
-    CI->createFileManager();
+    IntrusiveRefCntPtr Overlay =
+        new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem());
+    CI->createFileManager(Overlay);
     clang::CompilerInvocation& Invocation = CI->getInvocation();
     std::string& PCHFile = Invocation.getPreprocessorOpts().ImplicitPCHInclude;
     bool InitLang = true, InitTarget = true;
diff --git a/interpreter/cling/lib/Interpreter/CMakeLists.txt b/interpreter/cling/lib/Interpreter/CMakeLists.txt
index 1f15fa122ef3a..87e83535309c5 100644
--- a/interpreter/cling/lib/Interpreter/CMakeLists.txt
+++ b/interpreter/cling/lib/Interpreter/CMakeLists.txt
@@ -30,6 +30,7 @@ set(LLVM_LINK_COMPONENTS
   coverage
   executionengine
   ipo
+  jitlink
   lto
   mc
   object
@@ -235,6 +236,8 @@ if (UNIX)
           set(CLING_CXX_RLTV "${CLING_CXX_RLTV} --gcc-toolchain=${gcctoolchain}")
         endif()
       endif()
+    elseif (APPLE)
+      set(CLING_CXX_PATH_ARGS "-isysroot;${CMAKE_OSX_SYSROOT}")
     endif()
   endif()
 
@@ -349,7 +352,7 @@ add_file_dependencies(${CMAKE_CURRENT_SOURCE_DIR}/CIFactory.cpp
 # If LLVM is external, but Clang is builtin, we must use some files
 # from patched (builtin) version of LLVM
 if ((NOT builtin_llvm) AND builtin_clang)
-  set(FixInclude "${CMAKE_SOURCE_DIR}/interpreter/llvm/src/include")
+  set(FixInclude "${CMAKE_SOURCE_DIR}/interpreter/llvm-project/llvm/include")
 
   get_property(P SOURCE IncrementalJIT.cpp PROPERTY INCLUDE_DIRECTORIES)
   list(INSERT P 0 ${FixInclude})
@@ -370,4 +373,10 @@ if ((NOT builtin_llvm) AND builtin_clang)
   get_property(P SOURCE TransactionUnloader.cpp PROPERTY INCLUDE_DIRECTORIES)
   list(INSERT P 0 ${FixInclude})
   set_property(SOURCE TransactionUnloader.cpp PROPERTY INCLUDE_DIRECTORIES "${P}")
-endif()
\ No newline at end of file
+endif()
+
+# If both LLVM and Clang are external, we need to define LLVM_PATH in order for
+# cling to use the correct (external) LLVM/Clang directories.
+if ((NOT builtin_llvm) AND (NOT builtin_clang))
+  target_compile_definitions(clingInterpreter PUBLIC "LLVM_PATH=\"${LLVM_BINARY_DIR}\"")
+endif()
diff --git a/interpreter/cling/lib/Interpreter/ClangInternalState.cpp b/interpreter/cling/lib/Interpreter/ClangInternalState.cpp
index 25b5a801cb926..255ef4e3db79f 100644
--- a/interpreter/cling/lib/Interpreter/ClangInternalState.cpp
+++ b/interpreter/cling/lib/Interpreter/ClangInternalState.cpp
@@ -308,7 +308,7 @@ namespace cling {
   void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
                                            const llvm::Module& M,
                                            CodeGenerator& CG) {
-    M.print(Out, /*AssemblyAnnotationWriter*/ 0);
+    M.print(Out, /*AssemblyAnnotationWriter*/ nullptr);
     CG.print(Out);
   }
 
diff --git a/interpreter/cling/lib/Interpreter/DeclExtractor.cpp b/interpreter/cling/lib/Interpreter/DeclExtractor.cpp
index 45b2892f0a3e6..8fbbaa6b05b88 100644
--- a/interpreter/cling/lib/Interpreter/DeclExtractor.cpp
+++ b/interpreter/cling/lib/Interpreter/DeclExtractor.cpp
@@ -220,7 +220,7 @@ namespace cling {
       WrapperDC->addDecl(FD);
     }
 
-    return hasNoErrors ? FD : 0;
+    return hasNoErrors ? FD != nullptr : false;
   }
 
   void DeclExtractor::createUniqueName(std::string& out) {
@@ -239,58 +239,59 @@ namespace cling {
 
     std::string FunctionName = "__fd";
     createUniqueName(FunctionName);
-    IdentifierInfo& IIFD = m_Context->Idents.get(FunctionName);
+    clang::DeclarationName DeclName = &m_Context->Idents.get(FunctionName);
     SourceLocation Loc;
-    NamedDecl* ND = m_Sema->ImplicitlyDefineFunction(Loc, IIFD, TUScope);
-    if (FunctionDecl* FD = dyn_cast_or_null(ND)) {
-      Sema::SynthesizedFunctionScope Scope(*m_Sema, FD);
-      FD->setImplicit(false); // Better for debugging
-
-      // Add a return statement if it doesn't exist
-      if (!isa(Stmts.back())) {
-        Sema::ContextRAII pushedDC(*m_Sema, FD);
-        // Generate the return statement:
-        // First a literal 0, then the return taking that literal.
-        // One bit is enough:
-        llvm::APInt ZeroInt(m_Context->getIntWidth(m_Context->IntTy), 0,
-                            /*isSigned=*/true);
-        IntegerLiteral* ZeroLit
-          = IntegerLiteral::Create(*m_Context, ZeroInt, m_Context->IntTy,
-                                   SourceLocation());
-        Stmts.push_back(m_Sema->ActOnReturnStmt(ZeroLit->getExprLoc(),
-                                                ZeroLit,
-                                                m_Sema->getCurScope()).get());
-      }
-
-      // Wrap Stmts into a function body.
-      llvm::ArrayRef StmtsRef(Stmts.data(), Stmts.size());
-      CompoundStmt* CS = CompoundStmt::Create(*m_Context, StmtsRef, Loc, Loc);
-      FD->setBody(CS);
-      Emit(FD);
-
-      // Create the VarDecl with the init
-      std::string VarName = "__vd";
-      createUniqueName(VarName);
-      IdentifierInfo& IIVD = m_Context->Idents.get(VarName);
-      VarDecl* VD = VarDecl::Create(*m_Context, TUDC, Loc, Loc, &IIVD,
-                                    FD->getReturnType(), (TypeSourceInfo*)0,
-                                    SC_None);
-      LookupResult R(*m_Sema, FD->getDeclName(), Loc, Sema::LookupMemberName);
-      R.addDecl(FD);
-      CXXScopeSpec CSS;
-      Expr* UnresolvedLookup
-        = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).get();
-      Expr* TheCall = m_Sema->ActOnCallExpr(TUScope, UnresolvedLookup, Loc,
-                                            MultiExprArg(), Loc).get();
-      assert(VD && TheCall && "Missing VD or its init!");
-      VD->setInit(TheCall);
-
-      Emit(VD); // Add it to the transaction for codegenning
-      TUDC->addHiddenDecl(VD);
-      Stmts.clear();
-      return;
+    clang::QualType FnTy =
+        m_Context->getFunctionType(m_Context->IntTy, {},
+                                   clang::FunctionProtoType::ExtProtoInfo());
+    clang::FunctionDecl* FD = clang::FunctionDecl::Create(
+        *m_Context, m_Context->getTranslationUnitDecl(), Loc, Loc, DeclName,
+        FnTy, m_Context->getTrivialTypeSourceInfo(FnTy), clang::SC_None);
+
+    Sema::SynthesizedFunctionScope Scope(*m_Sema, FD);
+    FD->setImplicit(false); // Better for debugging
+
+    // Add a return statement if it doesn't exist
+    if (!isa(Stmts.back())) {
+      Sema::ContextRAII pushedDC(*m_Sema, FD);
+      // Generate the return statement:
+      // First a literal 0, then the return taking that literal.
+      // One bit is enough:
+      llvm::APInt ZeroInt(m_Context->getIntWidth(m_Context->IntTy), 0,
+                          /*isSigned=*/true);
+      IntegerLiteral* ZeroLit
+        = IntegerLiteral::Create(*m_Context, ZeroInt, m_Context->IntTy,
+                                 SourceLocation());
+      Stmts.push_back(
+          m_Sema->BuildReturnStmt(ZeroLit->getExprLoc(), ZeroLit).get());
     }
-    llvm_unreachable("Must be able to enforce init order.");
+
+    // Wrap Stmts into a function body.
+    llvm::ArrayRef StmtsRef(Stmts.data(), Stmts.size());
+    CompoundStmt* CS = CompoundStmt::Create(*m_Context, StmtsRef, Loc, Loc);
+    FD->setBody(CS);
+    Emit(FD);
+
+    // Create the VarDecl with the init
+    std::string VarName = "__vd";
+    createUniqueName(VarName);
+    IdentifierInfo& IIVD = m_Context->Idents.get(VarName);
+    VarDecl* VD = VarDecl::Create(*m_Context, TUDC, Loc, Loc, &IIVD,
+                                  FD->getReturnType(), (TypeSourceInfo*)0,
+                                  SC_None);
+    LookupResult R(*m_Sema, FD->getDeclName(), Loc, Sema::LookupMemberName);
+    R.addDecl(FD);
+    CXXScopeSpec CSS;
+    Expr* UnresolvedLookup
+      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).get();
+    Expr* TheCall = m_Sema->ActOnCallExpr(TUScope, UnresolvedLookup, Loc,
+                                          MultiExprArg(), Loc).get();
+    assert(VD && TheCall && "Missing VD or its init!");
+    VD->setInit(TheCall);
+
+    Emit(VD); // Add it to the transaction for codegenning
+    TUDC->addHiddenDecl(VD);
+    Stmts.clear();
   }
 
   ///\brief Checks for clashing names when trying to extract a declaration.
@@ -340,7 +341,7 @@ namespace cling {
 
     IdentifierInfo* Name = NewTD->getIdentifier();
     // If this is not a definition, it must have a name.
-    assert((Name != 0 || NewTD->isThisDeclarationADefinition()) &&
+    assert((Name != nullptr || NewTD->isThisDeclarationADefinition()) &&
            "Nameless record must be a definition!");
 
     // Figure out the underlying type if this a enum declaration. We need to do
@@ -367,7 +368,7 @@ namespace cling {
         // integral type; any cv-qualification is ignored.
 
         SourceLocation UnderlyingLoc;
-        TypeSourceInfo* TI = 0;
+        TypeSourceInfo* TI = nullptr;
         if ((TI = ED->getIntegerTypeSourceInfo()))
           UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
 
@@ -560,7 +561,7 @@ namespace cling {
               Kind = PrevTagDecl->getTagKind();
             else {
               // Recover by making this an anonymous redefinition.
-              Name = 0;
+              Name = nullptr;
               Previous.clear();
               Invalid = true;
             }
@@ -622,7 +623,7 @@ namespace cling {
                   // If this is a redefinition, recover by making this
                   // struct be anonymous, which will make any later
                   // references get the previous definition.
-                  Name = 0;
+                  Name = nullptr;
                   Previous.clear();
                   Invalid = true;
                 }
@@ -635,7 +636,7 @@ namespace cling {
                   m_Sema->Diag(NameLoc, diag::err_nested_redefinition) << Name;
                   m_Sema->Diag(PrevTagDecl->getLocation(),
                                diag::note_previous_definition);
-                  Name = 0;
+                  Name = nullptr;
                   Previous.clear();
                   Invalid = true;
                 }
@@ -689,7 +690,7 @@ namespace cling {
           // issue an error and recover by making this tag be anonymous.
           m_Sema->Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
           m_Sema->Diag(PrevDecl->getLocation(), diag::note_previous_definition);
-          Name = 0;
+          Name = nullptr;
           Invalid = true;
         }
 
diff --git a/interpreter/cling/lib/Interpreter/DeclUnloader.cpp b/interpreter/cling/lib/Interpreter/DeclUnloader.cpp
index 5d13259cd4bf7..25c01b1ef3c0b 100644
--- a/interpreter/cling/lib/Interpreter/DeclUnloader.cpp
+++ b/interpreter/cling/lib/Interpreter/DeclUnloader.cpp
@@ -26,45 +26,19 @@
 
 #include "llvm/IR/Constants.h"
 
-namespace cling {
-using namespace clang;
-
-///\brief Return whether `D' is a template that was first instantiated non-
-/// locally, i.e. in a PCH/module. If `D' is not an instantiation, return false.
-bool DeclUnloader::isInstantiatedInPCH(const Decl *D) {
-  SourceManager &SM = D->getASTContext().getSourceManager();
-  if (const auto FD = dyn_cast(D))
-    return FD->isTemplateInstantiation() &&
-           !SM.isLocalSourceLocation(FD->getPointOfInstantiation());
-  else if (const auto CTSD = dyn_cast(D))
-    return !SM.isLocalSourceLocation(CTSD->getPointOfInstantiation());
-  else if (const auto VTSD = dyn_cast(D))
-    return !SM.isLocalSourceLocation(VTSD->getPointOfInstantiation());
-  return false;
-}
-
-void DeclUnloader::resetDefinitionData(TagDecl *decl) {
-  auto canon = dyn_cast(decl->getCanonicalDecl());
-  assert(canon && "Only CXXRecordDecl have DefinitionData");
-  for (auto iter = canon->getMostRecentDecl(); iter;
-       iter = iter->getPreviousDecl()) {
-    auto declcxx = dyn_cast(iter);
-    assert(declcxx && "Only CXXRecordDecl have DefinitionData");
-    declcxx->DefinitionData = nullptr;
+namespace {
+  using namespace clang;
+
+  constexpr bool isDefinition(void*) { return false; }
+  bool isDefinition(TagDecl* R) {
+    return R->isCompleteDefinition() && isa(R);
   }
-}
-
-constexpr static bool isDefinition(void*) { return false; }
-static bool isDefinition(TagDecl* R) {
-  return R->isCompleteDefinition() && isa(R);
-}
-
-// Copied and adapted from: ASTReaderDecl.cpp
-template
-static void removeRedeclFromChain(DeclT* R) {
-  //RedeclLink is a protected member.
-  struct RedeclDerived : public Redeclarable {
-     // FIXME: Report this false positive diagnostic to clang.
+
+  // Copied and adapted from: ASTReaderDecl.cpp
+  template  void removeRedeclFromChain(DeclT* R) {
+    // RedeclLink is a protected member.
+    struct RedeclDerived : public Redeclarable {
+      // FIXME: Report this false positive diagnostic to clang.
 #ifdef __clang__
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
@@ -91,131 +65,95 @@ static void removeRedeclFromChain(DeclT* R) {
       getLink(First).setLatest(Latest);
     }
 #ifdef __clang__
-#pragma clang diagnostic push
+#pragma clang diagnostic pop
 #endif // __clang__
-  };
+    };
 
-  assert(R != R->getFirstDecl() && "Cannot remove only redecl from chain");
-
-  const bool isdef = isDefinition(R);
-
-  // In the following cases, A marks the first, Z the most recent and
-  // R the decl to be removed from the chain.
-  DeclT* Prev = R->getPreviousDecl();
-  if (R == R->getMostRecentDecl()) {
-    // A -> .. -> R
-    RedeclDerived::setLatest(Prev);
-  } else {
-    // Find the next redecl, starting at the end
-    DeclT* Next = R->getMostRecentDecl();
-    while (Next && Next->getPreviousDecl() != R)
-      Next = Next->getPreviousDecl();
-    if (!Next) {
-      // R is not (yet?) wired up.
-      return;
-    }
+    assert(R != R->getFirstDecl() && "Cannot remove only redecl from chain");
 
-    if (R->getPreviousDecl()) {
-      // A -> .. -> R -> .. -> Z
-      RedeclDerived::skipPrev(Next);
+    const bool isdef = isDefinition(R);
+
+    // In the following cases, A marks the first, Z the most recent and
+    // R the decl to be removed from the chain.
+    DeclT* Prev = R->getPreviousDecl();
+    if (R == R->getMostRecentDecl()) {
+      // A -> .. -> R
+      RedeclDerived::setLatest(Prev);
     } else {
-      assert(R->getFirstDecl() == R && "Logic error");
-      // R -> .. -> Z
-      RedeclDerived::setFirst(Next);
-    }
-  }
-  // If the decl was the definition, the other decl might have their
-  // DefinitionData pointing to it.
-  // This is really need only if DeclT is a TagDecl or derived.
-  if (isdef) {
-     DeclUnloader::resetDefinitionData(Prev);
-  }
-}
-
-///\brief Adds the previous declaration into the lookup map on DC.
-/// @param[in] D - The decl that is being removed.
-/// @param[in] DC - The DeclContext to add the previous declaration of D.
-///\returns the previous declaration.
-///
-static Decl* handleRedelaration(Decl* D, DeclContext* DC) {
-  NamedDecl* ND = dyn_cast(D);
-  if (!ND)
-    return nullptr;
-
-  DeclarationName Name = ND->getDeclName();
-  if (Name.isEmpty())
-    return nullptr;
-
-  NamedDecl* MostRecent = ND->getMostRecentDecl();
-  NamedDecl* MostRecentNotThis = MostRecent;
-  if (MostRecentNotThis == ND) {
-    MostRecentNotThis = dyn_cast_or_null(ND->getPreviousDecl());
-    if (!MostRecentNotThis || MostRecentNotThis == ND)
-      return MostRecentNotThis;
-  }
+      // Find the next redecl, starting at the end
+      DeclT* Next = R->getMostRecentDecl();
+      while (Next && Next->getPreviousDecl() != R)
+        Next = Next->getPreviousDecl();
+      if (!Next) {
+        // R is not (yet?) wired up.
+	return;
+      }
 
-  if (StoredDeclsMap* Map = DC->getPrimaryContext()->getLookupPtr()) {
-    StoredDeclsMap::iterator Pos = Map->find(Name);
-    if (Pos != Map->end() && !Pos->second.isNull()) {
-      DeclContext::lookup_result decls = Pos->second.getLookupResult();
-      // FIXME: A decl meant to be added in the lookup already exists
-      // in the lookup table. My assumption is that the DeclUnloader
-      // adds it here. This needs to be investigated mode. For now
-      // std::find gets promoted from assert to condition :)
-      // DeclContext::lookup_result::iterator is not an InputIterator
-      // (const member, thus no op=(const iterator&)), thus we cannot use
-      // std::find. MSVC actually cares!
-      auto hasDecl = [](const DeclContext::lookup_result& Result,
-                        const NamedDecl* Needle) -> bool {
-        for (auto IDecl: Result) {
-          if (IDecl == Needle)
-            return true;
-        }
-        return false;
-      };
-      if (!hasDecl(decls, MostRecentNotThis) && hasDecl(decls, ND)) {
-        // The decl was registered in the lookup, update it.
-        Pos->second.addOrReplaceDecl(MostRecentNotThis);
+      if (R->getPreviousDecl()) {
+        // A -> .. -> R -> .. -> Z
+        RedeclDerived::skipPrev(Next);
+      } else {
+        assert(R->getFirstDecl() == R && "Logic error");
+        // R -> .. -> Z
+        RedeclDerived::setFirst(Next);
       }
     }
+    // If the decl was the definition, the other decl might have their
+    // DefinitionData pointing to it.
+    // This is really need only if DeclT is a TagDecl or derived.
+    if (isdef)
+      cling::DeclUnloader::resetDefinitionData(Prev);
   }
-  return MostRecentNotThis;
-}
-
-///\brief Removes given declaration from the chain of redeclarations.
-/// Rebuilds the chain and sets properly first and last redeclaration.
-/// @param[in] R - The redeclarable, its chain to be rebuilt.
-/// @param[in] DC - Remove the redecl's lookup entry from this DeclContext.
-///
-///\returns the most recent redeclaration in the new chain.
-///
-template 
-bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC) {
-  if (R->getFirstDecl() == R) {
-    // This is the only element in the chain.
-    return true;
-  }
-
-  // Make sure we update the lookup maps, because the removed decl might
-  // be registered in the lookup and still findable.
-  T* MostRecentNotThis = (T*)handleRedelaration((T*)R, DC);
 
-  // Set a new latest redecl.
-  removeRedeclFromChain((T*)R);
+  ///\brief Adds the previous declaration into the lookup map on DC.
+  /// @param[in] D - The decl that is being removed.
+  /// @param[in] DC - The DeclContext to add the previous declaration of D.
+  ///\returns the previous declaration.
+  ///
+  Decl* handleRedelaration(Decl* D, DeclContext* DC) {
+    NamedDecl* ND = dyn_cast(D);
+    if (!ND)
+      return nullptr;
+
+    DeclarationName Name = ND->getDeclName();
+    if (Name.isEmpty())
+      return nullptr;
+
+    NamedDecl* MostRecent = ND->getMostRecentDecl();
+    NamedDecl* MostRecentNotThis = MostRecent;
+    if (MostRecentNotThis == ND) {
+      MostRecentNotThis = dyn_cast_or_null(ND->getPreviousDecl());
+      if (!MostRecentNotThis || MostRecentNotThis == ND)
+        return MostRecentNotThis;
+    }
 
-#ifndef NDEBUG
-  // Validate redecl chain by iterating through it.
-  std::set*> CheckUnique;
-  (void)CheckUnique;
-  for (auto RD: MostRecentNotThis->redecls()) {
-    assert(CheckUnique.insert(RD).second && "Dupe redecl chain element");
-    (void)RD;
+    if (StoredDeclsMap* Map = DC->getPrimaryContext()->getLookupPtr()) {
+      StoredDeclsMap::iterator Pos = Map->find(Name);
+      if (Pos != Map->end() && !Pos->second.isNull()) {
+        DeclContext::lookup_result decls = Pos->second.getLookupResult();
+        // FIXME: A decl meant to be added in the lookup already exists
+        // in the lookup table. My assumption is that the DeclUnloader
+        // adds it here. This needs to be investigated mode. For now
+        // std::find gets promoted from assert to condition :)
+        // DeclContext::lookup_result::iterator is not an InputIterator
+        // (const member, thus no op=(const iterator&)), thus we cannot use
+        // std::find. MSVC actually cares!
+        auto hasDecl = [](const DeclContext::lookup_result& Result,
+                          const NamedDecl* Needle) -> bool {
+          for (auto IDecl: Result) {
+            if (IDecl == Needle)
+              return true;
+          }
+          return false;
+        };
+        if (!hasDecl(decls, MostRecentNotThis) && hasDecl(decls, ND)) {
+          // The decl was registered in the lookup, update it.
+          Pos->second.addOrReplaceDecl(MostRecentNotThis);
+        }
+      }
+    }
+    return MostRecentNotThis;
   }
-#else
-  (void)MostRecentNotThis; // templated function issues a lot -Wunused-variable
-#endif
-  return true;
-}
 
   // Copied and adapted from GlobalDCE.cpp
   class GlobalValueEraser {
@@ -247,10 +185,10 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
       for (Globals::iterator I = VisitedGlobals.begin(),
              E = VisitedGlobals.end(); I != E; ++I)
         if (GlobalVariable* GVar = dyn_cast(*I)) {
-          GVar->setInitializer(0);
+          GVar->setInitializer(nullptr);
         }
         else if (GlobalAlias* GA = dyn_cast(*I)) {
-          GA->setAliasee(0);
+          GA->setAliasee(nullptr);
         }
         else {
           Function* F = cast(*I);
@@ -285,7 +223,6 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     }
 
   private:
-
     /// Find values that are marked as llvm.used.
     void FindUsedValues(const llvm::Module& m) {
       for (const llvm::GlobalVariable& GV : m.globals()) {
@@ -371,6 +308,252 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     }
   };
 
+  // Remove a decl and possibly it's parent entry in lookup tables.
+  static void eraseDeclFromMap(StoredDeclsMap* Map, NamedDecl* ND) {
+    assert(Map && ND && "eraseDeclFromMap recieved NULL value(s)");
+    // Make sure we the decl doesn't exist in the lookup tables.
+    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
+    if (Pos != Map->end()) {
+      StoredDeclsList& List = Pos->second;
+      // In some cases clang puts an entry in the list without a decl pointer.
+      // Clean it up.
+      if (List.isNull()) {
+        Map->erase(Pos);
+        return;
+      }
+      List.remove(ND);
+      if (List.isNull())
+        Map->erase(Pos);
+    }
+  }
+
+  typedef llvm::SmallVector Vars;
+  class StaticVarCollector : public RecursiveASTVisitor {
+    Vars& m_V;
+
+  public:
+    StaticVarCollector(FunctionDecl* FD, Vars& V) : m_V(V) {
+      TraverseStmt(FD->getBody());
+    }
+    bool VisitDeclStmt(DeclStmt* DS) {
+      for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
+           I != E; ++I)
+        if (VarDecl* VD = dyn_cast(*I))
+          if (VD->isStaticLocal())
+            m_V.push_back(VD);
+      return true;
+    }
+  };
+
+  // Template instantiation of templated function first creates a canonical
+  // declaration and after the actual template specialization. For example:
+  // template T TemplatedF(T t);
+  // template<> int TemplatedF(int i) { return i + 1; } creates:
+  // 1. Canonical decl: int TemplatedF(int i);
+  // 2. int TemplatedF(int i){ return i + 1; }
+  //
+  // The template specialization is attached to the list of specialization of
+  // the templated function.
+  // When TemplatedF is looked up it finds the templated function and the
+  // lookup is extended by the templated function with its specializations.
+  // In the end we don't need to remove the canonical decl because, it
+  // doesn't end up in the lookup table.
+  //
+  class FunctionTemplateDeclExt : public FunctionTemplateDecl {
+  public:
+    static void removeSpecialization(FunctionTemplateDecl* self,
+                                     const FunctionDecl* specialization) {
+      assert(self && specialization && "Cannot be null!");
+      assert(specialization == specialization->getCanonicalDecl() &&
+             "Not the canonical specialization!?");
+      typedef llvm::SmallVector Specializations;
+      typedef llvm::FoldingSetVector Set;
+
+      FunctionTemplateDeclExt* This = (FunctionTemplateDeclExt*)self;
+      Specializations specializations;
+      const Set& specs = This->getCommonPtr()->Specializations;
+
+      if (!specs.size()) // nothing to remove
+        return;
+
+      // Collect all the specializations without the one to remove.
+      for (Set::const_iterator I = specs.begin(), E = specs.end(); I != E;
+           ++I) {
+        assert(I->getFunction() && "Must have a specialization.");
+        if (I->getFunction() != specialization)
+          specializations.push_back(I->getFunction());
+      }
+
+      This->getCommonPtr()->Specializations.clear();
+
+      // Readd the collected specializations.
+      void* InsertPos = nullptr;
+      FunctionTemplateSpecializationInfo* FTSI = nullptr;
+      for (size_t i = 0, e = specializations.size(); i < e; ++i) {
+        FTSI = specializations[i]->getTemplateSpecializationInfo();
+        assert(FTSI && "Must not be null.");
+        // Avoid assertion on add.
+        FTSI->SetNextInBucket(nullptr);
+        This->addSpecialization(FTSI, InsertPos);
+      }
+#ifndef NDEBUG
+      const TemplateArgumentList* args =
+          specialization->getTemplateSpecializationArgs();
+      assert(!self->findSpecialization(args->asArray(), InsertPos) &&
+             "Finds the removed decl again!");
+#endif
+    }
+  };
+
+  // A template specialization is attached to the list of specialization of
+  // the templated class.
+  //
+  class ClassTemplateDeclExt : public ClassTemplateDecl {
+  public:
+    static void removeSpecialization(ClassTemplateDecl* self,
+                                     ClassTemplateSpecializationDecl* spec) {
+      assert(!isa(spec) &&
+             "Use removePartialSpecialization");
+      assert(self && spec && "Cannot be null!");
+      assert(spec == spec->getCanonicalDecl() &&
+             "Not the canonical specialization!?");
+      typedef llvm::SmallVector
+          Specializations;
+      typedef llvm::FoldingSetVector Set;
+
+      ClassTemplateDeclExt* This = (ClassTemplateDeclExt*)self;
+      Specializations specializations;
+      Set& specs = This->getCommonPtr()->Specializations;
+
+      if (!specs.size()) // nothing to remove
+        return;
+
+      // Collect all the specializations without the one to remove.
+      for (Set::iterator I = specs.begin(), E = specs.end(); I != E; ++I) {
+        if (&*I != spec)
+          specializations.push_back(&*I);
+      }
+
+      This->getCommonPtr()->Specializations.clear();
+
+      // Readd the collected specializations.
+      void* InsertPos = nullptr;
+      ClassTemplateSpecializationDecl* CTSD = nullptr;
+      for (size_t i = 0, e = specializations.size(); i < e; ++i) {
+        CTSD = specializations[i];
+        assert(CTSD && "Must not be null.");
+        // Avoid assertion on add.
+        CTSD->SetNextInBucket(nullptr);
+        This->AddSpecialization(CTSD, InsertPos);
+      }
+    }
+
+    static void
+    removePartialSpecialization(ClassTemplateDecl* self,
+                                ClassTemplatePartialSpecializationDecl* spec) {
+      assert(self && spec && "Cannot be null!");
+      assert(spec == spec->getCanonicalDecl() &&
+             "Not the canonical specialization!?");
+      typedef llvm::SmallVector
+          Specializations;
+      typedef llvm::FoldingSetVector
+          Set;
+
+      ClassTemplateDeclExt* This = (ClassTemplateDeclExt*)self;
+      Specializations specializations;
+      Set& specs = This->getPartialSpecializations();
+
+      if (!specs.size()) // nothing to remove
+        return;
+
+      // Collect all the specializations without the one to remove.
+      for (Set::iterator I = specs.begin(), E = specs.end(); I != E; ++I) {
+        if (&*I != spec)
+          specializations.push_back(&*I);
+      }
+
+      This->getPartialSpecializations().clear();
+
+      // Readd the collected specializations.
+      void* InsertPos = nullptr;
+      ClassTemplatePartialSpecializationDecl* CTPSD = nullptr;
+      for (size_t i = 0, e = specializations.size(); i < e; ++i) {
+        CTPSD = specializations[i];
+        assert(CTPSD && "Must not be null.");
+        // Avoid assertion on add.
+        CTPSD->SetNextInBucket(nullptr);
+        This->AddPartialSpecialization(CTPSD, InsertPos);
+      }
+    }
+  };
+} // end anonymous namespace
+
+namespace cling {
+  using namespace clang;
+
+  ///\brief Return whether `D' is a template that was first instantiated non-
+  /// locally, i.e. in a PCH/module. If `D' is not an instantiation, return
+  /// false.
+  bool DeclUnloader::isInstantiatedInPCH(const Decl* D) {
+    SourceManager& SM = D->getASTContext().getSourceManager();
+    if (const auto FD = dyn_cast(D))
+      return FD->isTemplateInstantiation() &&
+             !SM.isLocalSourceLocation(FD->getPointOfInstantiation());
+    else if (const auto CTSD = dyn_cast(D))
+      return !SM.isLocalSourceLocation(CTSD->getPointOfInstantiation());
+    else if (const auto VTSD = dyn_cast(D))
+      return !SM.isLocalSourceLocation(VTSD->getPointOfInstantiation());
+    return false;
+  }
+
+  void DeclUnloader::resetDefinitionData(TagDecl* decl) {
+    auto canon = dyn_cast(decl->getCanonicalDecl());
+    assert(canon && "Only CXXRecordDecl have DefinitionData");
+    for (auto iter = canon->getMostRecentDecl(); iter;
+         iter = iter->getPreviousDecl()) {
+      auto declcxx = dyn_cast(iter);
+      assert(declcxx && "Only CXXRecordDecl have DefinitionData");
+      declcxx->DefinitionData = nullptr;
+    }
+  }
+
+  ///\brief Removes given declaration from the chain of redeclarations.
+  /// Rebuilds the chain and sets properly first and last redeclaration.
+  /// @param[in] R - The redeclarable, its chain to be rebuilt.
+  /// @param[in] DC - Remove the redecl's lookup entry from this DeclContext.
+  ///
+  ///\returns the most recent redeclaration in the new chain.
+  ///
+  template 
+  bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R,
+                                       DeclContext* DC) {
+    if (R->getFirstDecl() == R) {
+      // This is the only element in the chain.
+      return true;
+    }
+
+    // Make sure we update the lookup maps, because the removed decl might
+    // be registered in the lookup and still findable.
+    T* MostRecentNotThis = (T*)handleRedelaration((T*)R, DC);
+
+    // Set a new latest redecl.
+    removeRedeclFromChain((T*)R);
+
+#ifndef NDEBUG
+    // Validate redecl chain by iterating through it.
+    std::set*> CheckUnique;
+    (void)CheckUnique;
+    for (auto RD : MostRecentNotThis->redecls()) {
+      assert(CheckUnique.insert(RD).second && "Dupe redecl chain element");
+      (void)RD;
+    }
+#else
+    (void)
+        MostRecentNotThis; // templated function issues a lot -Wunused-variable
+#endif
+    return true;
+  }
+
   DeclUnloader::~DeclUnloader() {
     SourceManager& SM = m_Sema->getSourceManager();
     for (FileIDs::iterator I = m_FilesToUncache.begin(),
@@ -404,25 +587,6 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     return true;
   }
 
-  // Remove a decl and possibly it's parent entry in lookup tables.
-  static void eraseDeclFromMap(StoredDeclsMap* Map, NamedDecl* ND) {
-    assert(Map && ND && "eraseDeclFromMap recieved NULL value(s)");
-    // Make sure we the decl doesn't exist in the lookup tables.
-    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
-    if (Pos != Map->end()) {
-      StoredDeclsList &List = Pos->second;
-      // In some cases clang puts an entry in the list without a decl pointer.
-      // Clean it up.
-      if (List.isNull()) {
-        Map->erase(Pos);
-        return;
-      }
-      List.remove(ND);
-      if (List.isNull())
-        Map->erase(Pos);
-    }
-  }
-
   bool DeclUnloader::VisitNamedDecl(NamedDecl* ND) {
     bool Successful = VisitDecl(ND);
 
@@ -454,7 +618,7 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
 
   bool DeclUnloader::VisitDeclaratorDecl(DeclaratorDecl* DD) {
     // VisitDeclaratorDecl: ValueDecl
-    auto found = std::find(m_Sema->UnusedFileScopedDecls.begin(/*ExtSource*/0,
+    auto found = std::find(m_Sema->UnusedFileScopedDecls.begin(/*ExtSource*/nullptr,
                                                                /*Local*/true),
                            m_Sema->UnusedFileScopedDecls.end(), DD);
     if (found != m_Sema->UnusedFileScopedDecls.end())
@@ -505,24 +669,6 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     return Successful;
   }
 
-  namespace {
-    typedef llvm::SmallVector Vars;
-    class StaticVarCollector : public RecursiveASTVisitor {
-      Vars& m_V;
-    public:
-      StaticVarCollector(FunctionDecl* FD, Vars& V) : m_V(V) {
-        TraverseStmt(FD->getBody());
-      }
-      bool VisitDeclStmt(DeclStmt* DS) {
-        for(DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
-            I != E; ++I)
-          if (VarDecl* VD = dyn_cast(*I))
-            if (VD->isStaticLocal())
-              m_V.push_back(VD);
-        return true;
-      }
-    };
-  }
   bool DeclUnloader::VisitFunctionDecl(FunctionDecl* FD) {
     // The Structors need to be handled differently.
     if (!isa(FD) && !isa(FD)) {
@@ -550,65 +696,6 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     Successful &= VisitRedeclarable(FD, FD->getDeclContext());
     Successful &= VisitDeclaratorDecl(FD);
 
-    // Template instantiation of templated function first creates a canonical
-    // declaration and after the actual template specialization. For example:
-    // template T TemplatedF(T t);
-    // template<> int TemplatedF(int i) { return i + 1; } creates:
-    // 1. Canonical decl: int TemplatedF(int i);
-    // 2. int TemplatedF(int i){ return i + 1; }
-    //
-    // The template specialization is attached to the list of specialization of
-    // the templated function.
-    // When TemplatedF is looked up it finds the templated function and the
-    // lookup is extended by the templated function with its specializations.
-    // In the end we don't need to remove the canonical decl because, it
-    // doesn't end up in the lookup table.
-    //
-    class FunctionTemplateDeclExt : public FunctionTemplateDecl {
-    public:
-      static void removeSpecialization(FunctionTemplateDecl* self,
-                                       const FunctionDecl* specialization) {
-        assert(self && specialization && "Cannot be null!");
-        assert(specialization == specialization->getCanonicalDecl()
-               && "Not the canonical specialization!?");
-        typedef llvm::SmallVector Specializations;
-        typedef llvm::FoldingSetVector< FunctionTemplateSpecializationInfo> Set;
-
-        FunctionTemplateDeclExt* This = (FunctionTemplateDeclExt*) self;
-        Specializations specializations;
-        const Set& specs = This->getCommonPtr()->Specializations;
-
-        if (!specs.size()) // nothing to remove
-          return;
-
-        // Collect all the specializations without the one to remove.
-        for(Set::const_iterator I = specs.begin(),E = specs.end(); I != E; ++I){
-          assert(I->getFunction() && "Must have a specialization.");
-          if (I->getFunction() != specialization)
-            specializations.push_back(I->getFunction());
-        }
-
-        This->getCommonPtr()->Specializations.clear();
-
-        //Readd the collected specializations.
-        void* InsertPos = 0;
-        FunctionTemplateSpecializationInfo* FTSI = 0;
-        for (size_t i = 0, e = specializations.size(); i < e; ++i) {
-          FTSI = specializations[i]->getTemplateSpecializationInfo();
-          assert(FTSI && "Must not be null.");
-          // Avoid assertion on add.
-          FTSI->SetNextInBucket(0);
-          This->addSpecialization(FTSI, InsertPos);
-        }
-#ifndef NDEBUG
-        const TemplateArgumentList* args
-          = specialization->getTemplateSpecializationArgs();
-        assert(!self->findSpecialization(args->asArray(),  InsertPos)
-               && "Finds the removed decl again!");
-#endif
-      }
-    };
-
     if (FD->isFunctionTemplateSpecialization() && wasCanonical) {
       // Only the canonical declarations are registered in the list of the
       // specializations.
@@ -682,16 +769,29 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
 
   bool DeclUnloader::VisitDeclContext(DeclContext* DC) {
     bool Successful = true;
-    typedef llvm::SmallVector Decls;
-    Decls declsToErase;
-    // Removing from single-linked list invalidates the iterators.
+    llvm::SmallVector tagDecls, otherDecls;
+
+    // The order in which declarations are removed makes a difference, e.g.
+    // `MaybeRemoveDeclFromModule()` may require access to type information to
+    // make up the mangled name.
+    // Thus, we segregate declarations to be removed in `TagDecl`s (i.e., struct
+    // / union / class / enum) and other declarations.  Removal of `TagDecl`s
+    // is deferred until all the other declarations have been processed.
+    // Declarations in each group are iterated in reverse order.
+    // Note that removing from single-linked list invalidates the iterators.
     for (DeclContext::decl_iterator I = DC->noload_decls_begin();
          I != DC->noload_decls_end(); ++I) {
-      declsToErase.push_back(*I);
+      if (isa(*I))
+        tagDecls.push_back(*I);
+      else
+        otherDecls.push_back(*I);
     }
 
-    for(Decls::reverse_iterator I = declsToErase.rbegin(),
-          E = declsToErase.rend(); I != E; ++I) {
+    for (auto I = otherDecls.rbegin(), E = otherDecls.rend(); I != E; ++I) {
+      Successful = Visit(*I) && Successful;
+      assert(Successful);
+    }
+    for (auto I = tagDecls.rbegin(), E = tagDecls.rend(); I != E; ++I) {
       Successful = Visit(*I) && Successful;
       assert(Successful);
     }
@@ -735,7 +835,7 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
       // Hopefully LSD->isExternCContext() means that it already does exist
       ExternCContextDecl* ECD = m_Sema->Context.getExternCContextDecl();
       StoredDeclsMap* Map = ECD ? ECD->getLookupPtr() : nullptr;
-      
+
       for (Decl* D : LSD->noload_decls()) {
         if (NamedDecl* ND = dyn_cast(D)) {
 
@@ -908,7 +1008,7 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     const MacroInfo* MI = MD->getMacroInfo();
 
     // If the macro is not defined, this is a noop undef, just return.
-    if (MI == 0)
+    if (!MI)
       return false;
 
     // Remove the pair from the macros
@@ -928,8 +1028,8 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     bool Successful = true;
 
     // Remove specializations:
-    for (FunctionTemplateDecl::spec_iterator I = FTD->spec_begin(),
-           E = FTD->spec_end(); I != E; ++I)
+    for (FunctionTemplateDecl::spec_iterator I = FTD->loaded_spec_begin(),
+           E = FTD->loaded_spec_end(); I != E; ++I)
       Successful &= Visit(*I);
 
     Successful &= VisitRedeclarableTemplateDecl(FTD);
@@ -941,8 +1041,8 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     // ClassTemplateDecl: TemplateDecl, Redeclarable
     bool Successful = true;
     // Remove specializations:
-    for (ClassTemplateDecl::spec_iterator I = CTD->spec_begin(),
-           E = CTD->spec_end(); I != E; ++I)
+    for (ClassTemplateDecl::spec_iterator I = CTD->loaded_spec_begin(),
+           E = CTD->loaded_spec_end(); I != E; ++I)
       Successful &= Visit(*I);
 
     Successful &= VisitRedeclarableTemplateDecl(CTD);
@@ -950,88 +1050,6 @@ bool DeclUnloader::VisitRedeclarable(clang::Redeclarable* R, DeclContext* DC)
     return Successful;
   }
 
-  namespace {
-  // A template specialization is attached to the list of specialization of
-  // the templated class.
-  //
-  class ClassTemplateDeclExt : public ClassTemplateDecl {
-  public:
-    static void removeSpecialization(ClassTemplateDecl* self,
-                                     ClassTemplateSpecializationDecl* spec) {
-      assert(!isa(spec) &&
-             "Use removePartialSpecialization");
-      assert(self && spec && "Cannot be null!");
-      assert(spec == spec->getCanonicalDecl()
-             && "Not the canonical specialization!?");
-      typedef llvm::SmallVector Specializations;
-      typedef llvm::FoldingSetVector Set;
-
-      ClassTemplateDeclExt* This = (ClassTemplateDeclExt*) self;
-      Specializations specializations;
-      Set& specs = This->getCommonPtr()->Specializations;
-
-      if (!specs.size()) // nothing to remove
-        return;
-
-      // Collect all the specializations without the one to remove.
-      for(Set::iterator I = specs.begin(),E = specs.end(); I != E; ++I){
-        if (&*I != spec)
-          specializations.push_back(&*I);
-      }
-
-      This->getCommonPtr()->Specializations.clear();
-
-      //Readd the collected specializations.
-      void* InsertPos = 0;
-      ClassTemplateSpecializationDecl* CTSD = 0;
-      for (size_t i = 0, e = specializations.size(); i < e; ++i) {
-        CTSD = specializations[i];
-        assert(CTSD && "Must not be null.");
-        // Avoid assertion on add.
-        CTSD->SetNextInBucket(0);
-        This->AddSpecialization(CTSD, InsertPos);
-      }
-    }
-
-    static void removePartialSpecialization(ClassTemplateDecl* self,
-                                 ClassTemplatePartialSpecializationDecl* spec) {
-      assert(self && spec && "Cannot be null!");
-      assert(spec == spec->getCanonicalDecl()
-             && "Not the canonical specialization!?");
-      typedef llvm::SmallVector
-        Specializations;
-      typedef llvm::FoldingSetVector Set;
-
-      ClassTemplateDeclExt* This = (ClassTemplateDeclExt*) self;
-      Specializations specializations;
-      Set& specs = This->getPartialSpecializations();
-
-      if (!specs.size()) // nothing to remove
-        return;
-
-      // Collect all the specializations without the one to remove.
-      for(Set::iterator I = specs.begin(),E = specs.end(); I != E; ++I){
-        if (&*I != spec)
-          specializations.push_back(&*I);
-      }
-
-      This->getPartialSpecializations().clear();
-
-      //Readd the collected specializations.
-      void* InsertPos = 0;
-      ClassTemplatePartialSpecializationDecl* CTPSD = 0;
-      for (size_t i = 0, e = specializations.size(); i < e; ++i) {
-        CTPSD = specializations[i];
-        assert(CTPSD && "Must not be null.");
-        // Avoid assertion on add.
-        CTPSD->SetNextInBucket(0);
-        This->AddPartialSpecialization(CTPSD, InsertPos);
-      }
-    }
-  };
-  } // end anonymous namespace
-
-
   bool DeclUnloader::VisitClassTemplateSpecializationDecl(
                                         ClassTemplateSpecializationDecl* CTSD) {
     // ClassTemplateSpecializationDecl: CXXRecordDecl, FoldingSet
diff --git a/interpreter/cling/lib/Interpreter/DefinitionShadower.cpp b/interpreter/cling/lib/Interpreter/DefinitionShadower.cpp
index 0f2ba28cc9401..5f9685be66de6 100644
--- a/interpreter/cling/lib/Interpreter/DefinitionShadower.cpp
+++ b/interpreter/cling/lib/Interpreter/DefinitionShadower.cpp
@@ -35,7 +35,9 @@ namespace cling {
            && (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID());
   }
 
-  /// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition.
+  /// \brief Returns whether a declaration is a definition.  A `TemplateDecl` is
+  /// a definition if the templated decl is itself a definition; a concept is
+  /// always considered a definition.
   static bool isDefinition(const Decl *D) {
     if (auto FD = dyn_cast(D))
       return FD->isThisDeclarationADefinition();
@@ -44,7 +46,7 @@ namespace cling {
     if (auto VD = dyn_cast(D))
       return VD->isThisDeclarationADefinition();
     if (auto TD = dyn_cast(D))
-      return isDefinition(TD->getTemplatedDecl());
+      return isa(TD) || isDefinition(TD->getTemplatedDecl());
     return true;
   }
 
diff --git a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp
index 73c6fed44d8df..09babd0b33bce 100644
--- a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp
+++ b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp
@@ -401,7 +401,7 @@ namespace cling {
     if (!isLibraryLoaded(canonicalLoadedLib))
       return;
 
-    DyLibHandle dyLibHandle = 0;
+    DyLibHandle dyLibHandle = nullptr;
     for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
          I != E; ++I) {
       if (I->second == canonicalLoadedLib) {
diff --git a/interpreter/cling/lib/Interpreter/DynamicLibraryManagerSymbol.cpp b/interpreter/cling/lib/Interpreter/DynamicLibraryManagerSymbol.cpp
index dda5897a3cd46..3e7fbd6dc7aab 100644
--- a/interpreter/cling/lib/Interpreter/DynamicLibraryManagerSymbol.cpp
+++ b/interpreter/cling/lib/Interpreter/DynamicLibraryManagerSymbol.cpp
@@ -37,6 +37,26 @@
 #include 
 #include 
 
+#if defined (__FreeBSD__)
+#include 
+#include 
+#include 
+#include 
+
+// libprocstat pulls in sys/elf.h which seems to clash with llvm/BinaryFormat/ELF.h
+// similar collision happens with ZFS. Defining ZFS disables this include.
+# ifndef ZFS
+#   define ZFS
+#   define defined_ZFS_for_libprocstat
+# endif
+#include 
+# ifdef defined_ZFS_for_libprocstat
+#   undef ZFS
+#   undef defined_ZFS_for_libprocstat
+# endif
+
+#include 
+#endif
 
 #ifdef LLVM_ON_UNIX
 #include 
@@ -1363,6 +1383,17 @@ namespace cling {
       if (_NSGetExecutablePath(buf, &bufsize) >= 0)
         return cached_realpath(buf);
       return cached_realpath(info.dli_fname);
+# elif defined (__FreeBSD__)
+      procstat* ps = procstat_open_sysctl();
+      kinfo_proc* kp = kinfo_getproc(getpid());
+
+      char buf[PATH_MAX] = "";
+      if (kp!=NULL) {
+        procstat_getpathname(ps, kp, buf, sizeof(buf));
+      };
+      free(kp);
+      procstat_close(ps);
+      return cached_realpath(buf);
 # elif defined(LLVM_ON_UNIX)
       char buf[PATH_MAX] = { 0 };
       // Cross our fingers that /proc/self/exe exists.
diff --git a/interpreter/cling/lib/Interpreter/DynamicLookup.cpp b/interpreter/cling/lib/Interpreter/DynamicLookup.cpp
index e426a2e2728ac..2d6bcb224c813 100644
--- a/interpreter/cling/lib/Interpreter/DynamicLookup.cpp
+++ b/interpreter/cling/lib/Interpreter/DynamicLookup.cpp
@@ -153,9 +153,9 @@ namespace cling {
 
   // Constructors
   EvaluateTSynthesizer::EvaluateTSynthesizer(Sema* S)
-    : ASTTransformer(S), m_EvalDecl(0), m_LifetimeHandlerDecl(0),
-      m_LHgetMemoryDecl(0), m_DynamicExprInfoDecl(0), m_DeclContextDecl(0),
-      m_gCling(0), m_CurDeclContext(0), m_Context(&S->getASTContext()),
+    : ASTTransformer(S), m_EvalDecl(nullptr), m_LifetimeHandlerDecl(nullptr),
+      m_LHgetMemoryDecl(nullptr), m_DynamicExprInfoDecl(nullptr), m_DeclContextDecl(nullptr),
+      m_gCling(nullptr), m_CurDeclContext(nullptr), m_Context(&S->getASTContext()),
       m_UniqueNameCounter(0), m_NestedCompoundStmts(0)
   { }
 
@@ -266,7 +266,7 @@ namespace cling {
           D->dump();
           if (NewBody.hasSingleNode())
             NewBody.getAs()->dump();
-          return Result(0, false); // Signal a fatal error.
+          return Result(nullptr, false); // Signal a fatal error.
         }
         FD->setBody(NewBody.getAsSingleNode());
       }
@@ -527,9 +527,9 @@ namespace cling {
                                               /*IsArrow=*/false,
                                               SS,
                                               m_NoSLoc,
-                                              /*FirstQualifierInScope=*/0,
+                                              /*FirstQualifierInScope=*/nullptr,
                                               MemberLookup,
-                                              /*TemplateArgs=*/0,
+                                              /*TemplateArgs=*/nullptr,
                                               /*Scope*/nullptr).get();
         // 3.3 Build the actual call
         Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
@@ -719,7 +719,7 @@ namespace cling {
     // 3. Build the array of addresses
     QualType VarAddrTy = m_Sema->BuildArrayType(m_Context->VoidPtrTy,
                                                 ArrayType::Normal,
-                                                /*ArraySize*/0,
+                                                /*ArraySize*/nullptr,
                                                 /*IndexTypeQuals*/0,
                                                 m_NoRange,
                                                 DeclarationName() );
@@ -734,7 +734,7 @@ namespace cling {
       if (!UnOp) {
         // Not good, return what we had.
         cling::errs() << "Error while creating dynamic expression for:\n  ";
-        SubTree->printPretty(cling::errs(), 0 /*PrinterHelper*/,
+        SubTree->printPretty(cling::errs(), nullptr /*PrinterHelper*/,
                              m_Context->getPrintingPolicy(), 2);
         cling::errs() << "\n";
 #ifndef NDEBUG
@@ -768,7 +768,7 @@ namespace cling {
                               CK_ArrayToPointerDecay);
 
     // Is the result of the expression to be printed or not
-    Expr* VPReq = 0;
+    Expr* VPReq = nullptr;
     if (ValuePrinterReq)
       VPReq = m_Sema->ActOnCXXBoolLiteral(m_NoSLoc, tok::kw_true).get();
     else
@@ -958,7 +958,7 @@ namespace cling {
       Value res = Interp->Evaluate(ctor.c_str(), DC,
                                    ExprInfo->isValuePrinterRequested()
                                    );
-      m_Memory = (void*)res.getAs();
+      m_Memory = res.getPtr();
     }
 
     LifetimeHandler::~LifetimeHandler() {
diff --git a/interpreter/cling/lib/Interpreter/ExternalInterpreterSource.cpp b/interpreter/cling/lib/Interpreter/ExternalInterpreterSource.cpp
index 42d2a2dcf1422..1c83a4e0ecb3f 100644
--- a/interpreter/cling/lib/Interpreter/ExternalInterpreterSource.cpp
+++ b/interpreter/cling/lib/Interpreter/ExternalInterpreterSource.cpp
@@ -111,7 +111,7 @@ namespace cling {
       const Decl* To = llvm::cantFail(m_Importer->Import(declToImport));
       assert(To && "Import did not work!");
       assert((DS.empty() ||
-              DS[0].getID() == clang::diag::err_unsupported_ast_node) &&
+              DS[0].getID() != clang::diag::err_unsupported_ast_node) &&
              "Import not supported!");
 #endif
       return;
diff --git a/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.cpp b/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.cpp
index 075f235c3b61d..f78357d956055 100644
--- a/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.cpp
+++ b/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.cpp
@@ -217,9 +217,9 @@ namespace cling {
 
        auto FE = PP.LookupFile(fileNameLoc, FileName, isAngled, FromDir,
                                FromFile,
-                               CurDir, /*SearchPath*/ 0,
-                               /*RelativePath*/ 0, /*suggestedModule*/ 0,
-                               /*IsMapped*/ 0, /*IsFramework*/ nullptr,
+                               CurDir, /*SearchPath*/ nullptr,
+                               /*RelativePath*/ nullptr, /*suggestedModule*/ nullptr,
+                               /*IsMapped*/ nullptr, /*IsFramework*/ nullptr,
                                /*SkipCache*/ false,
                                /*OpenFile*/ false, /*CacheFail*/ true);
        // Return true if we can '#include' the given filename
@@ -456,7 +456,7 @@ namespace cling {
     }
 
     if (const FunctionType *AFT = Ty->getAs()) {
-      const FunctionProtoType *FT = 0;
+      const FunctionProtoType *FT = nullptr;
       if (D->hasWrittenPrototype())
         FT = dyn_cast(AFT);
 
@@ -525,7 +525,7 @@ namespace cling {
         if (isComputedNoexcept(FT->getExceptionSpecType())) {
           Proto += "(";
           llvm::raw_string_ostream EOut(Proto);
-          FT->getNoexceptExpr()->printPretty(EOut, 0, SubPolicy,
+          FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
                                              m_Indentation);
           EOut.flush();
           //Proto += EOut.str()
@@ -570,8 +570,8 @@ namespace cling {
 
             Init = Init->IgnoreParens();
 
-            Expr *SimpleInit = 0;
-            Expr **Args = 0;
+            Expr *SimpleInit = nullptr;
+            Expr **Args = nullptr;
             unsigned NumArgs = 0;
             if (ParenListExpr *ParenList = dyn_cast(Init)) {
               Args = ParenList->getExprs();
@@ -584,7 +584,7 @@ namespace cling {
               SimpleInit = Init;
 
             if (SimpleInit)
-              SimpleInit->printPretty(Out(), 0, m_Policy, m_Indentation);
+              SimpleInit->printPretty(Out(), nullptr, m_Policy, m_Indentation);
             else {
               for (unsigned I = 0; I != NumArgs; ++I) {
                 if (isa(Args[I]))
@@ -592,7 +592,7 @@ namespace cling {
 
                 if (I)
                   Out() << ", ";
-                Args[I]->printPretty(Out(), 0, m_Policy, m_Indentation);
+                Args[I]->printPretty(Out(), nullptr, m_Policy, m_Indentation);
               }
             }
           }
@@ -662,7 +662,7 @@ namespace cling {
 
     if (D->isBitField()) {
       Out() << " : ";
-      D->getBitWidth()->printPretty(Out(), 0, m_Policy, m_Indentation);
+      D->getBitWidth()->printPretty(Out(), nullptr, m_Policy, m_Indentation);
     }
 
     Expr *Init = D->getInClassInitializer();
@@ -671,7 +671,7 @@ namespace cling {
         Out() << " ";
       else
         Out() << " = ";
-      Init->printPretty(Out(), 0, m_Policy, m_Indentation);
+      Init->printPretty(Out(), nullptr, m_Policy, m_Indentation);
     }
     prettyPrintAttributes(D);
     Out() << ';' << closeBraces << '\n';
@@ -772,7 +772,7 @@ namespace cling {
             }
           }
           if (! isEnumConst)
-            Init->printPretty(Out(), 0, m_Policy, m_Indentation);
+            Init->printPretty(Out(), nullptr, m_Policy, m_Indentation);
 
         }
       if ((D->getInitStyle() == VarDecl::CallInit) && !isa(Init))
@@ -791,7 +791,7 @@ namespace cling {
     std::string closeBraces = PrintEnclosingDeclContexts(Out(),
                                                          D->getDeclContext());
     Out() << "__asm (";
-    D->getAsmString()->printPretty(Out(), 0, m_Policy, m_Indentation);
+    D->getAsmString()->printPretty(Out(), nullptr, m_Policy, m_Indentation);
     Out() << ");" << closeBraces << '\n';
   }
 
@@ -804,9 +804,9 @@ namespace cling {
     std::string closeBraces = PrintEnclosingDeclContexts(Out(),
                                                          D->getDeclContext());
     Out() << "static_assert(";
-    D->getAssertExpr()->printPretty(Out(), 0, m_Policy, m_Indentation);
+    D->getAssertExpr()->printPretty(Out(), nullptr, m_Policy, m_Indentation);
     Out() << ", ";
-    D->getMessage()->printPretty(Out(), 0, m_Policy, m_Indentation);
+    D->getMessage()->printPretty(Out(), nullptr, m_Policy, m_Indentation);
     Out() << ");" << closeBraces << '\n';
   }
 
@@ -941,7 +941,7 @@ namespace cling {
             = utils::TypeName::GetFullyQualifiedType(ArgQT, m_Ctx);
           Visit(ArgFQQT);
           if (m_SkipFlag) {
-            skipDecl(0, "type template param default failed");
+            skipDecl(nullptr, "type template param default failed");
             return;
           }
           Stream << " = ";
@@ -964,7 +964,7 @@ namespace cling {
           if (DeclRefExpr* DRE = dyn_cast(DefArg)) {
             Visit(DRE->getFoundDecl());
             if (m_SkipFlag) {
-              skipDecl(0, "expression template param default failed");
+              skipDecl(nullptr, "expression template param default failed");
               return;
             }
           } else if (isa(DefArg)
@@ -974,9 +974,9 @@ namespace cling {
                      || isa(DefArg)
                      || isa(DefArg)) {
             Stream << " = ";
-            DefArg->printPretty(Stream, 0, m_Policy, m_Indentation);
+            DefArg->printPretty(Stream, nullptr, m_Policy, m_Indentation);
           } else {
-            skipDecl(0, "expression template param default not a literal");
+            skipDecl(nullptr, "expression template param default not a literal");
             return;
           }
         }
@@ -1013,7 +1013,7 @@ namespace cling {
 
     PrintTemplateParameters(Stream, D->getTemplateParameters());
     if (m_SkipFlag) {
-      skipDecl(0, "Template parameters failed");
+      skipDecl(nullptr, "Template parameters failed");
       return;
     }
 
@@ -1184,7 +1184,7 @@ namespace cling {
       {
         const TemplateSpecializationType* TST
           = static_cast(typ);
-        for (const TemplateArgument& TA: *TST) {
+        for (const TemplateArgument& TA : TST->template_arguments()) {
           VisitTemplateArgument(TA);
           if (m_SkipFlag) {
             skipDecl(nullptr, "template argument failed");
@@ -1302,12 +1302,12 @@ namespace cling {
     case clang::NestedNameSpecifier::TypeSpec: // fall-through:
     case clang::NestedNameSpecifier::TypeSpecWithTemplate:
       // We cannot fwd declare nested types.
-      skipDecl(0, "NestedNameSpec TypeSpec/TypeSpecWithTemplate");
+      skipDecl(nullptr, "NestedNameSpec TypeSpec/TypeSpecWithTemplate");
       break;
     default:
       Log() << "VisitNestedNameSpecifier: Unexpected kind "
             << NNS->getKind() << '\n';
-      skipDecl(0, 0);
+      skipDecl(nullptr, nullptr);
       break;
    };
   }
@@ -1332,7 +1332,7 @@ namespace cling {
         //Implement that if important functions are marked so.
         //Not important, as users do not need hints
         //about using Deleted functions
-    if (D->getIdentifier() == 0
+    if (D->getIdentifier() == nullptr
         || D->getNameAsString()[0] == '_'
         || D->getStorageClass() == SC_Static
         || D->isCXXClassMember()
@@ -1438,7 +1438,7 @@ namespace cling {
     for(; DC && !DC->isTranslationUnit(); DC = DC->getParent()) {
       if (!isa(DC) && !isa(DC)) {
         Log() << "Skipping unhandled " << DC->getDeclKindName() << '\n';
-        skipDecl(0, 0);
+        skipDecl(nullptr, nullptr);
         return "";
       }
       DeclCtxs.push_back(DC);
diff --git a/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.h b/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.h
index a4b0c68c932ff..8e3f784589689 100644
--- a/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.h
+++ b/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.h
@@ -166,7 +166,7 @@ namespace cling {
 
     void PrintTemplateParameters(llvm::raw_ostream& Stream,
                                  clang::TemplateParameterList *Params,
-                                 const clang::TemplateArgumentList *Args = 0);
+                                 const clang::TemplateArgumentList *Args = nullptr);
     void prettyPrintAttributes(clang::Decl *D);
 
     bool isOperator(clang::FunctionDecl* D);
@@ -270,7 +270,7 @@ namespace cling {
       largestream m_Stream;
       bool m_HavePopped;
     public:
-      StreamRAII(ForwardDeclPrinter& pr, clang::PrintingPolicy* pol = 0):
+      StreamRAII(ForwardDeclPrinter& pr, clang::PrintingPolicy* pol = nullptr):
         m_pr(pr), m_oldPol(pr.m_Policy), m_HavePopped(false) {
         m_pr.m_StreamStack.push(&static_cast(m_Stream));
         if (pol)
diff --git a/interpreter/cling/lib/Interpreter/IncrementalExecutor.cpp b/interpreter/cling/lib/Interpreter/IncrementalExecutor.cpp
index 99ed4963229ed..5da617a3c2796 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalExecutor.cpp
+++ b/interpreter/cling/lib/Interpreter/IncrementalExecutor.cpp
@@ -20,19 +20,12 @@
 #include "cling/Utils/Platform.h"
 
 #include "clang/Basic/Diagnostic.h"
-#include "clang/Basic/TargetOptions.h"
 #include "clang/Frontend/CompilerInstance.h"
 
 #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h"
-#include "llvm/IR/Constants.h"
 #include "llvm/IR/Instructions.h"
-#include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/ADT/SmallPtrSet.h"
-#include "llvm/ADT/Triple.h"
-#include "llvm/Support/Host.h"
-#include "llvm/Support/TargetRegistry.h"
-#include "llvm/Target/TargetMachine.h"
 
 #include 
 
@@ -40,77 +33,10 @@ using namespace llvm;
 
 namespace cling {
 
-namespace {
-
-static std::unique_ptr
-CreateHostTargetMachine(const clang::CompilerInstance& CI) {
-  const clang::TargetOptions& TargetOpts = CI.getTargetOpts();
-  const clang::CodeGenOptions& CGOpt = CI.getCodeGenOpts();
-  const std::string& Triple = TargetOpts.Triple;
-
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
-  if (!TheTarget) {
-    cling::errs() << "cling::IncrementalExecutor: unable to find target:\n"
-                  << Error;
-    return std::unique_ptr();
-  }
-
-  CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
-  switch (CGOpt.OptimizationLevel) {
-    case 0: OptLevel = CodeGenOpt::None; break;
-    case 1: OptLevel = CodeGenOpt::Less; break;
-    case 2: OptLevel = CodeGenOpt::Default; break;
-    case 3: OptLevel = CodeGenOpt::Aggressive; break;
-    default: OptLevel = CodeGenOpt::Default;
-  }
-  using namespace llvm::orc;
-  auto JTMB = JITTargetMachineBuilder::detectHost();
-  if (!JTMB)
-    logAllUnhandledErrors(JTMB.takeError(), llvm::errs(),
-                          "Error detecting host");
-
-  JTMB->setCodeGenOptLevel(OptLevel);
-#ifdef _WIN32
-  JTMB->getOptions().EmulatedTLS = false;
-#endif // _WIN32
-
-#if defined(__powerpc64__) || defined(__PPC64__)
-  // We have to use large code model for PowerPC64 because TOC and text sections
-  // can be more than 2GB apart.
-  JTMB->setCodeModel(CodeModel::Large);
-#endif
-
-  std::unique_ptr TM = cantFail(JTMB->createTargetMachine());
-
-  // Forcefully disable GlobalISel, it might be enabled on AArch64 without
-  // optimizations. In tests on an Apple M1 after the upgrade to LLVM 9, this
-  // new instruction selection framework emits branches / calls that expect all
-  // code to be reachable in +/- 128 MB. This cannot be guaranteed during JIT,
-  // which generates code into allocated pages on the heap and could span the
-  // entire address space of the process.
-  //
-  // TODO:
-  // 1. Try to reproduce the problem with vanilla lli of LLVM 9 to check that
-  //    this is not related to the way Cling incrementally JITs and executes.
-  // 2. Figure out exactly why GlobalISel emits different branch instructions,
-  //    and whether this is a problem in the framework or of the generated IR.
-  // 3. Verify if the same happens with LLVM 11/12 (whatever Cling will move to
-  //    next), and possibly fix the underlying issue in LLVM upstream's `main`.
-  //
-  // FIXME: Lift this restriction and allow the target to enable GlobalISel,
-  // if deemed ready by upstream developers.
-  TM->setGlobalISel(false);
-
-  return TM;
-}
-
-} // anonymous namespace
-
 IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& /*diags*/,
                                          const clang::CompilerInstance& CI,
                                          void *ExtraLibHandle, bool Verbose):
-  m_Callbacks(nullptr), m_externalIncrementalExecutor(nullptr)
+  m_Callbacks(nullptr)
 #if 0
   : m_Diags(diags)
 #endif
@@ -120,22 +46,25 @@ IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& /*diags*/,
   // MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition
   std::atomic_flag_clear( &m_AtExitFuncsSpinLock );
 
-  std::unique_ptr TM(CreateHostTargetMachine(CI));
-  auto &TMRef = *TM;
   llvm::Error Err = llvm::Error::success();
   auto EPC = llvm::cantFail(llvm::orc::SelfExecutorProcessControl::Create());
-  m_JIT.reset(new IncrementalJIT(*this, std::move(TM), std::move(EPC), Err,
+  m_JIT.reset(new IncrementalJIT(*this, CI, std::move(EPC), Err,
     ExtraLibHandle, Verbose));
   if (Err) {
     llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "Fatal: ");
     llvm_unreachable("Propagate this error and exit gracefully");
   }
 
-  m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(), TMRef));
+  m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(), *m_JIT, m_JIT->getTargetMachine()));
 }
 
 IncrementalExecutor::~IncrementalExecutor() {}
 
+void IncrementalExecutor::registerExternalIncrementalExecutor(
+    IncrementalExecutor& IE) {
+  m_JIT->addGenerator(IE.m_JIT->getGenerator());
+}
+
 void IncrementalExecutor::runAtExitFuncs() {
   // It is legal to register an atexit handler from within another atexit
   // handler and furthor-more the standard says they need to run in reverse
@@ -353,7 +282,7 @@ IncrementalExecutor::getPointerToGlobalFromJIT(llvm::StringRef name) const {
   void* addr = m_JIT->getSymbolAddress(name, false /*no dlsym*/);
 
   if (diagnoseUnresolvedSymbols(name, "symbol"))
-    return 0;
+    return nullptr;
   return addr;
 }
 
diff --git a/interpreter/cling/lib/Interpreter/IncrementalExecutor.h b/interpreter/cling/lib/Interpreter/IncrementalExecutor.h
index 535172831ec51..428331c4a5f4a 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalExecutor.h
+++ b/interpreter/cling/lib/Interpreter/IncrementalExecutor.h
@@ -64,10 +64,6 @@ namespace cling {
     ///\brief Whom to call upon invocation of user code.
     InterpreterCallbacks* m_Callbacks;
 
-    ///\brief A pointer to the IncrementalExecutor of the parent Interpreter.
-    ///
-    IncrementalExecutor* m_externalIncrementalExecutor;
-
     ///\brief Helper that manages when the destructor of an object to be called.
     ///
     /// The object is registered first as an CXAAtExitElement and then cling
@@ -151,9 +147,11 @@ namespace cling {
 
     ~IncrementalExecutor();
 
-    void setExternalIncrementalExecutor(IncrementalExecutor *extIncrExec) {
-      m_externalIncrementalExecutor = extIncrExec;
-    }
+    /// Register a different `IncrementalExecutor` object that can provide
+    /// addresses for external symbols.  This is used by child interpreters to
+    /// lookup symbols defined in the parent.
+    void registerExternalIncrementalExecutor(IncrementalExecutor& IE);
+
     void setCallbacks(InterpreterCallbacks* callbacks);
 
     const DynamicLibraryManager& getDynamicLibraryManager() const {
@@ -183,7 +181,7 @@ namespace cling {
 
     ///\brief Runs a wrapper function.
     ExecutionResult executeWrapper(llvm::StringRef function,
-                                   Value* returnValue = 0) const;
+                                   Value* returnValue = nullptr) const;
     ///\brief Replaces a symbol (function) to the execution engine.
     ///
     /// Allows runtime declaration of a function passing its pointer for being
@@ -216,7 +214,7 @@ namespace cling {
     ///\param[out] fromJIT - whether the symbol was JITted.
     ///
     void*
-    getAddressOfGlobal(llvm::StringRef mangledName, bool* fromJIT = 0) const;
+    getAddressOfGlobal(llvm::StringRef mangledName, bool *fromJIT = nullptr) const;
 
     ///\brief Return the address of a global from the JIT (as
     /// opposed to dynamic libraries). Forces the emission of the symbol if
diff --git a/interpreter/cling/lib/Interpreter/IncrementalJIT.cpp b/interpreter/cling/lib/Interpreter/IncrementalJIT.cpp
index 9f2accf568abc..09ad059a547a8 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalJIT.cpp
+++ b/interpreter/cling/lib/Interpreter/IncrementalJIT.cpp
@@ -15,13 +15,28 @@
 #include "cling/Utils/Output.h"
 #include "cling/Utils/Utils.h"
 
+#include 
+#include 
+#include 
+
+#include 
+#include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
+#include 
+
+#ifdef __linux__
+#include 
+#endif
 
 using namespace llvm;
+using namespace llvm::jitlink;
 using namespace llvm::orc;
 
 namespace {
@@ -178,6 +193,117 @@ namespace {
     bool needsToReserveAllocationSpace() override { return true; }
   };
 
+  /// A JITLinkMemoryManager for Cling that never frees its allocations.
+  class ClingJITLinkMemoryManager : public JITLinkMemoryManager {
+  public:
+    Expected>
+    allocate(const JITLinkDylib* JD,
+             const SegmentsRequestMap& Request) override {
+      // A copy of InProcessMemoryManager::allocate with an empty implementation
+      // of IPMMAlloc::deallocate.
+
+      using AllocationMap = DenseMap;
+
+      // Local class for allocation.
+      class IPMMAlloc : public Allocation {
+      public:
+        IPMMAlloc(AllocationMap SegBlocks) : SegBlocks(std::move(SegBlocks)) {}
+        MutableArrayRef getWorkingMemory(ProtectionFlags Seg) override {
+          assert(SegBlocks.count(Seg) && "No allocation for segment");
+          return {static_cast(SegBlocks[Seg].base()),
+                  SegBlocks[Seg].allocatedSize()};
+        }
+        JITTargetAddress getTargetMemory(ProtectionFlags Seg) override {
+          assert(SegBlocks.count(Seg) && "No allocation for segment");
+          return pointerToJITTargetAddress(SegBlocks[Seg].base());
+        }
+        void finalizeAsync(FinalizeContinuation OnFinalize) override {
+          OnFinalize(applyProtections());
+        }
+        Error deallocate() override {
+          // Disabled until CallFunc is informed about unloading, and can
+          // re-generate the wrapper (if the decl is still available). See
+          // https://github.com/root-project/root/issues/10898
+          return Error::success();
+        }
+
+      private:
+        Error applyProtections() {
+          for (auto& KV : SegBlocks) {
+            auto& Prot = KV.first;
+            auto& Block = KV.second;
+            if (auto EC = sys::Memory::protectMappedMemory(Block, Prot))
+              return errorCodeToError(EC);
+            if (Prot & sys::Memory::MF_EXEC)
+              sys::Memory::InvalidateInstructionCache(Block.base(),
+                                                      Block.allocatedSize());
+          }
+          return Error::success();
+        }
+
+        AllocationMap SegBlocks;
+      };
+
+      if (!isPowerOf2_64((uint64_t)sys::Process::getPageSizeEstimate()))
+        return make_error("Page size is not a power of 2",
+                                       inconvertibleErrorCode());
+
+      AllocationMap Blocks;
+      const sys::Memory::ProtectionFlags ReadWrite =
+          static_cast(sys::Memory::MF_READ |
+                                                    sys::Memory::MF_WRITE);
+
+      // Compute the total number of pages to allocate.
+      size_t TotalSize = 0;
+      for (auto& KV : Request) {
+        const auto& Seg = KV.second;
+
+        if (Seg.getAlignment() > sys::Process::getPageSizeEstimate())
+          return make_error("Cannot request higher than page "
+                                         "alignment",
+                                         inconvertibleErrorCode());
+
+        TotalSize = alignTo(TotalSize, sys::Process::getPageSizeEstimate());
+        TotalSize += Seg.getContentSize();
+        TotalSize += Seg.getZeroFillSize();
+      }
+
+      // Allocate one slab to cover all the segments.
+      std::error_code EC;
+      auto SlabRemaining =
+          sys::Memory::allocateMappedMemory(TotalSize, nullptr, ReadWrite, EC);
+
+      if (EC)
+        return errorCodeToError(EC);
+
+      // Allocate segment memory from the slab.
+      for (auto& KV : Request) {
+
+        const auto& Seg = KV.second;
+
+        uint64_t SegmentSize =
+            alignTo(Seg.getContentSize() + Seg.getZeroFillSize(),
+                    sys::Process::getPageSizeEstimate());
+        assert(SlabRemaining.allocatedSize() >= SegmentSize &&
+               "Mapping exceeds allocation");
+
+        sys::MemoryBlock SegMem(SlabRemaining.base(), SegmentSize);
+        SlabRemaining =
+            sys::MemoryBlock((char*)SlabRemaining.base() + SegmentSize,
+                             SlabRemaining.allocatedSize() - SegmentSize);
+
+        // Zero out the zero-fill memory.
+        memset(static_cast(SegMem.base()) + Seg.getContentSize(), 0,
+               Seg.getZeroFillSize());
+
+        // Record the block for this segment.
+        Blocks[KV.first] = std::move(SegMem);
+      }
+
+      return std::unique_ptr(
+          new IPMMAlloc(std::move(Blocks)));
+    }
+  };
 
   /// A DynamicLibrarySearchGenerator that uses ResourceTracker to remember
   /// which symbols were resolved through dlsym during a transaction's reign.
@@ -255,8 +381,6 @@ Error RTDynamicLibrarySearchGenerator::tryToGenerate(
     JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
   orc::SymbolMap NewSymbols;
 
-  bool HasGlobalPrefix = (GlobalPrefix != '\0');
-
   for (auto &KV : Symbols) {
     auto &Name = KV.first;
 
@@ -266,11 +390,10 @@ Error RTDynamicLibrarySearchGenerator::tryToGenerate(
     if (Allow && !Allow(Name))
       continue;
 
-    if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
-      continue;
+    bool StripGlobalPrefix = (GlobalPrefix != '\0' && (*Name).front() == GlobalPrefix);
 
-    std::string Tmp((*Name).data() + HasGlobalPrefix,
-                    (*Name).size() - HasGlobalPrefix);
+    std::string Tmp((*Name).data() + StripGlobalPrefix,
+                    (*Name).size() - StripGlobalPrefix);
     if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
       NewSymbols[Name] = JITEvaluatedSymbol(
           static_cast(reinterpret_cast(Addr)),
@@ -283,6 +406,119 @@ Error RTDynamicLibrarySearchGenerator::tryToGenerate(
 
   return JD.define(absoluteSymbols(std::move(NewSymbols)), CurrentRT());
 }
+
+/// A definition generator that calls a user-provided function that is
+/// responsible for providing symbol addresses.
+/// This is used by `IncrementalJIT::getGenerator()` to yield a generator that
+/// resolves symbols defined in the IncrementalJIT object on which the function
+/// is called, which in turn may be used to provide lookup across different
+/// IncrementalJIT instances.
+class DelegateGenerator : public DefinitionGenerator {
+  using LookupFunc = std::function(StringRef)>;
+  LookupFunc lookup;
+
+public:
+  DelegateGenerator(LookupFunc lookup) : lookup(lookup) {}
+
+  Error tryToGenerate(LookupState& LS, LookupKind K, JITDylib& JD,
+                      JITDylibLookupFlags JDLookupFlags,
+                      const SymbolLookupSet& LookupSet) override {
+    SymbolMap Symbols;
+    for (auto& KV : LookupSet) {
+      if (auto Addr = lookup(*KV.first))
+        Symbols[KV.first] = Addr.get();
+    }
+    if (Symbols.empty())
+      return Error::success();
+    return JD.define(absoluteSymbols(std::move(Symbols)));
+  }
+};
+
+static bool UseJITLink(const Triple& TT) {
+  bool jitLink = false;
+  // Default to JITLink on macOS and RISC-V, as done in (recent) LLVM by
+  // LLJITBuilderState::prepareForConstruction.
+  if (TT.getArch() == Triple::riscv64 ||
+      (TT.isOSBinFormatMachO() &&
+       (TT.getArch() == Triple::aarch64 || TT.getArch() == Triple::x86_64))) {
+    jitLink = true;
+  }
+  // Finally, honor the user's choice by setting an environment variable.
+  if (const char* clingJitLink = std::getenv("CLING_JITLINK")) {
+    jitLink = cling::utils::ConvertEnvValueToBool(clingJitLink);
+  }
+  return jitLink;
+}
+
+static std::unique_ptr
+CreateTargetMachine(const clang::CompilerInstance& CI, bool JITLink) {
+  CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
+  switch (CI.getCodeGenOpts().OptimizationLevel) {
+    case 0: OptLevel = CodeGenOpt::None; break;
+    case 1: OptLevel = CodeGenOpt::Less; break;
+    case 2: OptLevel = CodeGenOpt::Default; break;
+    case 3: OptLevel = CodeGenOpt::Aggressive; break;
+    default: OptLevel = CodeGenOpt::Default;
+  }
+
+  const Triple &TT = CI.getTarget().getTriple();
+
+  using namespace llvm::orc;
+  auto JTMB = JITTargetMachineBuilder(TT);
+  JTMB.addFeatures(CI.getTargetOpts().Features);
+  JTMB.getOptions().MCOptions.ABIName = CI.getTarget().getABI().str();
+
+  JTMB.setCodeGenOptLevel(OptLevel);
+#ifdef _WIN32
+  JTMB.getOptions().EmulatedTLS = false;
+#endif // _WIN32
+
+#if defined(__powerpc64__) || defined(__PPC64__)
+  // We have to use large code model for PowerPC64 because TOC and text sections
+  // can be more than 2GB apart.
+  JTMB.setCodeModel(CodeModel::Large);
+#endif
+
+  if (JITLink) {
+    // Set up the TargetMachine as otherwise done by
+    // LLJITBuilderState::prepareForConstruction.
+    JTMB.setRelocationModel(Reloc::PIC_);
+    // Set the small code except for macOS on AArch64 - it results in relocation
+    // targets that are out-of-range.
+    // TODO: Investigate / report upstream and re-evaluate after a future LLVM
+    // upgrade.
+    if (!(TT.isOSBinFormatMachO() && TT.getArch() == Triple::aarch64))
+      JTMB.setCodeModel(CodeModel::Small);
+  }
+
+  return cantFail(JTMB.createTargetMachine());
+}
+
+#if defined(__linux__) && defined(__GLIBC__)
+static SymbolMap GetListOfLibcNonsharedSymbols(const LLJIT& Jit) {
+  // Inject a number of symbols that may be in libc_nonshared.a where they are
+  // not found automatically. Before DefinitionGenerators in ORCv2, this used
+  // to be done by RTDyldMemoryManager::getSymbolAddressInProcess See also the
+  // upstream issue https://github.com/llvm/llvm-project/issues/61289.
+
+  static const std::pair NamePtrList[] = {
+      {"stat", (void*)&stat},       {"fstat", (void*)&fstat},
+      {"lstat", (void*)&lstat},     {"stat64", (void*)&stat64},
+      {"fstat64", (void*)&fstat64}, {"lstat64", (void*)&lstat64},
+      {"fstatat", (void*)&fstatat}, {"fstatat64", (void*)&fstatat64},
+      {"mknod", (void*)&mknod},     {"mknodat", (void*)&mknodat},
+  };
+
+  SymbolMap LibcNonsharedSymbols;
+  for (const auto& NamePtr : NamePtrList) {
+    auto Addr = static_cast(
+        reinterpret_cast(NamePtr.second));
+    LibcNonsharedSymbols[Jit.mangleAndIntern(NamePtr.first)] =
+        JITEvaluatedSymbol(Addr, JITSymbolFlags::Exported);
+  }
+  return LibcNonsharedSymbols;
+}
+#endif
 } // unnamed namespace
 
 namespace cling {
@@ -291,29 +527,35 @@ namespace cling {
 llvm::JITEventListener* createPerfJITEventListener();
 
 IncrementalJIT::IncrementalJIT(
-    IncrementalExecutor& Executor, std::unique_ptr TM,
+    IncrementalExecutor& Executor, const clang::CompilerInstance &CI,
     std::unique_ptr EPC, Error& Err,
     void *ExtraLibHandle, bool Verbose)
     : SkipHostProcessLookup(false),
-      TM(std::move(TM)),
+      m_JITLink(UseJITLink(CI.getTarget().getTriple())),
+      m_TM(CreateTargetMachine(CI, m_JITLink)),
       SingleThreadedContext(std::make_unique()) {
   ErrorAsOutParameter _(&Err);
 
-  // FIXME: We should probably take codegen settings from the CompilerInvocation
-  // and not from the target machine
-  JITTargetMachineBuilder JTMB(this->TM->getTargetTriple());
-  JTMB.setCodeModel(this->TM->getCodeModel());
-  JTMB.setCodeGenOptLevel(this->TM->getOptLevel());
-  JTMB.setFeatures(this->TM->getTargetFeatureString());
-  JTMB.setRelocationModel(this->TM->getRelocationModel());
-
   LLJITBuilder Builder;
-  Builder.setJITTargetMachineBuilder(std::move(JTMB));
+  Builder.setDataLayout(m_TM->createDataLayout());
   Builder.setExecutorProcessControl(std::move(EPC));
 
   // Create ObjectLinkingLayer with our own MemoryManager.
   Builder.setObjectLinkingLayerCreator([&](ExecutionSession& ES,
-                                           const Triple& TT) {
+                                           const Triple& TT)
+                                           -> std::unique_ptr {
+    if (m_JITLink) {
+      // For JITLink, we only need a custom memory manager to avoid freeing the
+      // memory segments; the default InProcessMemoryManager (which is mostly
+      // copied above) already does slab allocation to keep all segments
+      // together which is needed for exception handling support.
+      auto ObjLinkingLayer = std::make_unique(
+          ES, std::make_unique());
+      ObjLinkingLayer->addPlugin(std::make_unique(
+          ES, std::make_unique()));
+      return ObjLinkingLayer;
+    }
+
     auto GetMemMgr = []() { return std::make_unique(); };
     auto Layer =
         std::make_unique(ES, std::move(GetMemMgr));
@@ -341,6 +583,11 @@ IncrementalJIT::IncrementalJIT(
     return Layer;
   });
 
+  Builder.setCompileFunctionCreator([&](llvm::orc::JITTargetMachineBuilder)
+  -> llvm::Expected> {
+    return std::make_unique(*m_TM);
+  });
+
   if (Expected> JitInstance = Builder.create()) {
     Jit = std::move(*JitInstance);
   } else {
@@ -358,7 +605,7 @@ IncrementalJIT::IncrementalJIT(
       m_CompiledModules[Unsafe] = std::move(TSM);
     });
 
-  char LinkerPrefix = this->TM->createDataLayout().getGlobalPrefix();
+  char LinkerPrefix = this->m_TM->createDataLayout().getGlobalPrefix();
 
   // Process symbol resolution
   auto HostProcessLookup
@@ -381,6 +628,12 @@ IncrementalJIT::IncrementalJIT(
                                   return !m_ForbidDlSymbols.contains(*Sym); });
   Jit->getMainJITDylib().addGenerator(std::move(LibLookup));
 
+#if defined(__linux__) && defined(__GLIBC__)
+  // See comment in ListOfLibcNonsharedSymbols.
+  cantFail(Jit->getMainJITDylib().define(
+      absoluteSymbols(GetListOfLibcNonsharedSymbols(*Jit))));
+#endif
+
   // This replaces llvm::orc::ExecutionSession::logErrorsToStdErr:
   auto&& ErrorReporter = [&Executor, LinkerPrefix, Verbose](Error Err) {
     Err = handleErrors(std::move(Err),
@@ -413,11 +666,33 @@ IncrementalJIT::IncrementalJIT(
   Jit->getExecutionSession().setErrorReporter(ErrorReporter);
 }
 
+std::unique_ptr IncrementalJIT::getGenerator() {
+  return std::make_unique(
+      [&](StringRef UnmangledName) { return Jit->lookup(UnmangledName); });
+}
+
 void IncrementalJIT::addModule(Transaction& T) {
   ResourceTrackerSP RT = Jit->getMainJITDylib().createResourceTracker();
   m_ResourceTrackers[&T] = RT;
 
-  ThreadSafeModule TSM(T.takeModule(), SingleThreadedContext);
+  std::unique_ptr module = T.takeModule();
+
+  // Reset the sections of all functions so that they end up in the same text
+  // section. This is important for TCling on macOS to catch exceptions raised
+  // by constructors, which requires unwinding information. The addresses in
+  // the __eh_frame table are relocated against a single __text section when
+  // loading the MachO binary, which breaks if the call sites of constructors
+  // end up in a separate init section.
+  // (see clang::TargetInfo::getStaticInitSectionSpecifier())
+  for (auto &Fn : module->functions()) {
+    if (Fn.hasSection()) {
+      // dbgs() << "Resetting section '" << Fn.getSection() << "' of function "
+      //        << Fn.getName() << "\n";
+      Fn.setSection("");
+    }
+  }
+
+  ThreadSafeModule TSM(std::move(module), SingleThreadedContext);
 
   const Module *Unsafe = TSM.getModuleUnlocked();
   T.m_CompiledModule = Unsafe;
@@ -438,6 +713,10 @@ llvm::Error IncrementalJIT::removeModule(const Transaction& T) {
   m_ResourceTrackers.erase(&T);
   if (Error Err = RT->remove())
     return Err;
+  auto iMod = m_CompiledModules.find(T.m_CompiledModule);
+  if (iMod != m_CompiledModules.end())
+    m_CompiledModules.erase(iMod);
+
   return llvm::Error::success();
 }
 
@@ -452,7 +731,7 @@ IncrementalJIT::addOrReplaceDefinition(StringRef Name,
     return KnownAddr;
 
   llvm::SmallString<128> LinkerMangledName;
-  char LinkerPrefix = this->TM->createDataLayout().getGlobalPrefix();
+  char LinkerPrefix = this->m_TM->createDataLayout().getGlobalPrefix();
   bool HasLinkerPrefix = LinkerPrefix != '\0';
   if (HasLinkerPrefix && Name.front() == LinkerPrefix) {
     LinkerMangledName.assign(1, LinkerPrefix);
@@ -484,7 +763,7 @@ IncrementalJIT::addOrReplaceDefinition(StringRef Name,
   return KnownAddr;
 }
 
-void* IncrementalJIT::getSymbolAddress(StringRef Name, bool IncludeHostSymbols) {
+void* IncrementalJIT::getSymbolAddress(StringRef Name, bool IncludeHostSymbols){
   std::unique_lock G(SkipHostProcessLookup, std::defer_lock);
   if (!IncludeHostSymbols)
     G.lock();
@@ -511,4 +790,13 @@ void* IncrementalJIT::getSymbolAddress(StringRef Name, bool IncludeHostSymbols)
   return jitTargetAddressToPointer(Symbol->getAddress());
 }
 
+bool IncrementalJIT::doesSymbolAlreadyExist(StringRef UnmangledName) {
+  auto Name = Jit->mangle(UnmangledName);
+  for (auto &&M: m_CompiledModules) {
+    if (M.first->getNamedValue(Name))
+      return true;
+  }
+  return false;
+}
+
 } // namespace cling
diff --git a/interpreter/cling/lib/Interpreter/IncrementalJIT.h b/interpreter/cling/lib/Interpreter/IncrementalJIT.h
index 1ef8abdbe5435..7fd712603e5a8 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalJIT.h
+++ b/interpreter/cling/lib/Interpreter/IncrementalJIT.h
@@ -27,6 +27,10 @@
 #include 
 #include 
 
+namespace clang {
+class CompilerInstance;
+}
+
 namespace cling {
 
 class IncrementalExecutor;
@@ -52,7 +56,7 @@ class SharedAtomicFlag {
 class IncrementalJIT {
 public:
   IncrementalJIT(IncrementalExecutor& Executor,
-                 std::unique_ptr TM,
+                 const clang::CompilerInstance &CI,
                  std::unique_ptr EPC,
                  llvm::Error &Err, void *ExtraLibHandle, bool Verbose);
 
@@ -62,6 +66,12 @@ class IncrementalJIT {
     Jit->getMainJITDylib().addGenerator(std::move(G));
   }
 
+  /// Return a `DefinitionGenerator` that can provide addresses for symbols
+  /// reachable from this IncrementalJIT object.  This function can be used in
+  /// conjunction with `addGenerator()` to provide symbol resolution across
+  /// diferent IncrementalJIT instances.
+  std::unique_ptr getGenerator();
+
   // FIXME: Accept a LLVMContext as well, e.g. the one that was used for the
   // particular module in Interpreter, CIFactory or BackendPasses (would be
   // more efficient)
@@ -74,6 +84,10 @@ class IncrementalJIT {
   /// should include symbols from the host process (via dlsym) or not.
   void* getSymbolAddress(llvm::StringRef Name, bool IncludeHostSymbols);
 
+  /// @brief Check whether the JIT already has emitted or knows how to emit
+  /// a symbol based on its IR name (as coming from clang's mangler).
+  bool doesSymbolAlreadyExist(llvm::StringRef UnmangledName);
+
   /// Inject a symbol with a known address. Name is not linker mangled, i.e.
   /// as known by the IR.
   llvm::JITTargetAddress addOrReplaceDefinition(llvm::StringRef Name,
@@ -82,6 +96,11 @@ class IncrementalJIT {
   llvm::Error runCtors() const {
     return Jit->initialize(Jit->getMainJITDylib());
   }
+
+  /// @brief Get the TargetMachine used by the JIT.
+  /// Non-const because BackendPasses need to update OptLevel.
+  llvm::TargetMachine &getTargetMachine() { return *m_TM; }
+
 private:
   std::unique_ptr Jit;
   llvm::orc::SymbolMap m_InjectedSymbols;
@@ -96,8 +115,9 @@ class IncrementalJIT {
   std::map m_ResourceTrackers;
   std::map m_CompiledModules;
 
+  bool m_JITLink;
   // FIXME: Move TargetMachine ownership to BackendPasses
-  std::unique_ptr TM;
+  std::unique_ptr m_TM;
 
   // TODO: We only need the context for materialization. Instead of defining it
   // here we might want to pass one in on a per-module basis.
diff --git a/interpreter/cling/lib/Interpreter/IncrementalParser.cpp b/interpreter/cling/lib/Interpreter/IncrementalParser.cpp
index 1c6ca43cd6aab..1c84149add202 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalParser.cpp
+++ b/interpreter/cling/lib/Interpreter/IncrementalParser.cpp
@@ -162,14 +162,15 @@ namespace {
 
     void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
                           const Diagnostic &Info) override {
+      if (Info.getID() == diag::warn_falloff_nonvoid_function) {
+        DiagLevel = DiagnosticsEngine::Error;
+      }
       if (Ignoring()) {
         if (Info.getID() == diag::warn_unused_expr
+            || Info.getID() == diag::warn_unused_result
             || Info.getID() == diag::warn_unused_call
             || Info.getID() == diag::warn_unused_comparison)
           return; // ignore!
-        if (Info.getID() == diag::warn_falloff_nonvoid_function) {
-          DiagLevel = DiagnosticsEngine::Error;
-        }
         if (Info.getID() == diag::ext_return_has_expr) {
           // An error that we need to suppress.
           auto Diags = const_cast(Info.getDiags());
@@ -360,7 +361,7 @@ namespace cling {
       m_CI->createPCHExternalASTSource(PCHFileName,
                                        DisableValidationForModuleKind::All,
                                        true /*AllowPCHWithCompilerErrors*/,
-                                       0 /*DeserializationListener*/,
+                                       nullptr /*DeserializationListener*/,
                                        true /*OwnsDeserializationListener*/);
       result.push_back(endTransaction(PchT));
       if (Trap.hasErrorOccurred()) {
@@ -766,13 +767,13 @@ namespace cling {
 
     if (Transaction* Parent = T.getParent()) {
       Parent->removeNestedTransaction(&T);
-      T.setParent(0);
+      T.setParent(nullptr);
     } else {
       if (&T == m_Transactions.back()) {
         // Remove from the queue
         m_Transactions.pop_back();
         if (!m_Transactions.empty())
-          m_Transactions.back()->setNext(0);
+          m_Transactions.back()->setNext(nullptr);
       } else {
         // If T is not the last transaction it must not be a previous
         // transaction either, but a "disconnected" one, i.e. one that
@@ -865,7 +866,7 @@ namespace cling {
     Preprocessor& PP = m_CI->getPreprocessor();
     if (!PP.getCurrentLexer()) {
        PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),
-                          0, SourceLocation());
+             nullptr, SourceLocation());
     }
     assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
     PP.enableIncrementalProcessing();
@@ -910,7 +911,7 @@ namespace cling {
     m_MemoryBuffers.push_back(std::make_pair(MBNonOwn, FID));
 
     // NewLoc only used for diags.
-    PP.EnterSourceFile(FID, /*DirLookup*/0, NewLoc);
+    PP.EnterSourceFile(FID, /*DirLookup*/nullptr, NewLoc);
     m_Consumer->getTransaction()->setBufferFID(FID);
 
     DiagnosticsEngine& Diags = getCI()->getDiagnostics();
diff --git a/interpreter/cling/lib/Interpreter/IncrementalParser.h b/interpreter/cling/lib/Interpreter/IncrementalParser.h
index 8c9082088ed4d..582e2bd575bc2 100644
--- a/interpreter/cling/lib/Interpreter/IncrementalParser.h
+++ b/interpreter/cling/lib/Interpreter/IncrementalParser.h
@@ -174,7 +174,7 @@ namespace cling {
     ///
     const Transaction* getFirstTransaction() const {
       if (m_Transactions.empty())
-        return 0;
+        return nullptr;
       return m_Transactions.front();
     }
 
@@ -182,7 +182,7 @@ namespace cling {
     ///
     Transaction* getLastTransaction() {
       if (m_Transactions.empty())
-        return 0;
+        return nullptr;
       return m_Transactions.back();
     }
 
@@ -190,7 +190,7 @@ namespace cling {
     ///
     const Transaction* getLastTransaction() const {
       if (m_Transactions.empty())
-        return 0;
+        return nullptr;
       return m_Transactions.back();
     }
 
diff --git a/interpreter/cling/lib/Interpreter/Interpreter.cpp b/interpreter/cling/lib/Interpreter/Interpreter.cpp
index 0a3337e33f6d9..681dbffc9510a 100644
--- a/interpreter/cling/lib/Interpreter/Interpreter.cpp
+++ b/interpreter/cling/lib/Interpreter/Interpreter.cpp
@@ -257,7 +257,7 @@ namespace cling {
     if (!m_LookupHelper)
       return;
 
-    if (!isInSyntaxOnlyMode()) {
+    if (!isInSyntaxOnlyMode() && !m_Opts.CompilerOpts.CUDADevice) {
       m_Executor.reset(new IncrementalExecutor(SemaRef.Diags, *getCI(),
         extraLibHandle, m_Opts.Verbose()));
 
@@ -372,7 +372,8 @@ namespace cling {
 
       // Give my IncrementalExecutor a pointer to the Incremental executor of the
       // parent Interpreter.
-      m_Executor->setExternalIncrementalExecutor(parentInterpreter.m_Executor.get());
+      m_Executor->registerExternalIncrementalExecutor(
+          *parentInterpreter.m_Executor);
 
       if (auto C = parentInterpreter.m_IncrParser->getDiagnosticConsumer())
         m_IncrParser->setDiagnosticConsumer(C, /*Own=*/false);
@@ -399,7 +400,7 @@ namespace cling {
     // and the ASTContext. For that to happen we shut down the IncrementalParser
     // explicitly, before the implicit destruction (through the unique_ptr) of
     // the callbacks.
-    m_IncrParser.reset(0);
+    m_IncrParser.reset(nullptr);
   }
 
   Transaction* Interpreter::Initialize(bool NoRuntime, bool SyntaxOnly,
@@ -439,13 +440,13 @@ namespace cling {
     const char* Linkage = LangOpts.CPlusPlus ? "extern \"C\"" : "";
     if (!NoRuntime) {
       if (LangOpts.CPlusPlus) {
-        Strm << "#include \"cling/Interpreter/RuntimeUniverse.h\"\n";
+        Strm << "#include \n";
         if (EmitDefinitions)
           Strm << "namespace cling { class Interpreter; namespace runtime { "
                   "Interpreter* gCling=(Interpreter*)" << ThisP << ";\n"
                   "RuntimeOptions* gClingOpts=(RuntimeOptions*)" << &this->m_RuntimeOptions << ";}}\n";
       } else {
-        Strm << "#include \"cling/Interpreter/CValuePrinter.h\"\n"
+        Strm << "#include \n"
              << "void* gCling";
         if (EmitDefinitions)
           Strm << "=(void*)" << ThisP;
@@ -692,7 +693,7 @@ namespace cling {
     CodeGenerator* CG = m_IncrParser->getCodeGenerator();
     ClangInternalState* state = new ClangInternalState(
         getCI()->getASTContext(), getCI()->getPreprocessor(),
-        getLastTransaction()->getModule(), CG, name);
+        getLastTransaction()->getCompiledModule(), CG, name);
     m_StoredStates.push_back(state);
   }
 
@@ -773,7 +774,7 @@ namespace cling {
     CO.CodeGeneration = m_IncrParser->hasCodeGenerator();
     CO.DynamicScoping = isDynamicLookupEnabled();
     CO.Debug = isPrintingDebug();
-    CO.IgnorePromptDiags = !isRawInputEnabled();
+    CO.IgnorePromptDiags = 0;
     CO.CheckPointerValidity = !isRawInputEnabled();
     CO.OptLevel = getDefaultOptLevel();
     return CO;
@@ -1267,7 +1268,7 @@ namespace cling {
                      clang::diag::Severity::Warning, SourceLocation());
 
     if (CR != cling::Interpreter::kSuccess)
-      return 0;
+      return nullptr;
 
     for (cling::Transaction::const_iterator I = T->decls_begin(),
            E = T->decls_end(); I != E; ++I) {
@@ -1285,7 +1286,7 @@ namespace cling {
         }
       }
     }
-    return 0;
+    return nullptr;
   }
 
   void*
@@ -1296,7 +1297,7 @@ namespace cling {
     //
 
     if (isInSyntaxOnlyMode())
-      return 0;
+      return nullptr;
 
     if (ifUnique) {
       if (void* Addr = (void*)getAddressOfGlobal(name)) {
@@ -1307,7 +1308,7 @@ namespace cling {
     Transaction* T = nullptr;
     const FunctionDecl* FD = DeclareCFunction(name, code, withAccessControl, T);
     if (!FD || !T)
-      return 0;
+      return nullptr;
 
     //  Get the wrapper function pointer from the ExecutionEngine (the JIT).
     return m_Executor->getPointerToGlobalFromJIT(name);
@@ -1440,16 +1441,16 @@ namespace cling {
     // Clang doc says:
     // "LookupFrom is set when this is a \#include_next directive, it
     // specifies the file to start searching from."
-    const DirectoryLookup* FromDir = 0;
-    const FileEntry* FromFile = 0;
-    const DirectoryLookup* CurDir = 0;
+    const DirectoryLookup* FromDir = nullptr;
+    const FileEntry* FromFile = nullptr;
+    const DirectoryLookup* CurDir = nullptr;
     Preprocessor& PP = getCI()->getPreprocessor();
     // PP::LookupFile uses it to issue 'nice' diagnostic
     SourceLocation fileNameLoc;
     auto FE = PP.LookupFile(fileNameLoc, canonicalFile, isAngled, FromDir,
-                            FromFile, CurDir, /*SearchPath*/0,
-                            /*RelativePath*/ 0, /*suggestedModule*/0,
-                            0 /*IsMapped*/, /*IsFrameworkFound*/ nullptr,
+                            FromFile, CurDir, /*SearchPath*/nullptr,
+                            /*RelativePath*/ nullptr, /*suggestedModule*/nullptr,
+                            /*IsMapped*/ nullptr, /*IsFrameworkFound*/ nullptr,
                             /*SkipCache*/ false, /*OpenFile*/ false,
                             /*CacheFail*/ false);
     if (FE)
@@ -1500,7 +1501,7 @@ namespace cling {
     T.setUnloading();
     // Clear any stored states that reference the llvm::Module.
     // Do it first in case
-    auto Module = T.getModule();
+    const auto *Module = T.getCompiledModule();
     if (Module && !m_StoredStates.empty()) {
       const auto Predicate = [&Module](const ClangInternalState* S) {
         return S->getModule() == Module;
@@ -1692,7 +1693,7 @@ namespace cling {
     if (!m_DynamicLookupDeclared && value) {
       // No dynlookup for the dynlookup header!
       m_DynamicLookupEnabled = false;
-      declare("#include \"cling/Interpreter/DynamicLookupRuntimeUniverse.h\"");
+      declare("#include ");
     }
     m_DynamicLookupDeclared = true;
 
@@ -1748,7 +1749,7 @@ namespace cling {
                                         bool* fromJIT /*=0*/) const {
     // Return a symbol's address, and whether it was jitted.
     if (isInSyntaxOnlyMode())
-      return 0;
+      return nullptr;
     return m_Executor->getAddressOfGlobal(SymName, fromJIT);
   }
 
diff --git a/interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp b/interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp
index 974a5d1eed008..d9736e0e2f4e5 100644
--- a/interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp
+++ b/interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp
@@ -232,7 +232,7 @@ namespace cling {
 
   public:
     InterpreterExternalSemaSource(InterpreterCallbacks* C)
-      : m_Callbacks(C), m_Sema(0) {}
+      : m_Callbacks(C), m_Sema(nullptr) {}
 
     ~InterpreterExternalSemaSource() {
       // FIXME: Another gross hack due to the missing multiplexing AST external
@@ -250,7 +250,7 @@ namespace cling {
     }
 
     void ForgetSema() override {
-      m_Sema = 0;
+      m_Sema = nullptr;
     }
 
     InterpreterCallbacks* getCallbacks() const { return m_Callbacks; }
@@ -297,7 +297,7 @@ namespace cling {
                              bool enableExternalSemaSourceCallbacks/* = false*/,
                         bool enableDeserializationListenerCallbacks/* = false*/,
                                              bool enablePPCallbacks/* = false*/)
-    : m_Interpreter(interp), m_ExternalSemaSource(0), m_PPCallbacks(0),
+    : m_Interpreter(interp), m_ExternalSemaSource(nullptr), m_PPCallbacks(nullptr),
       m_IsRuntime(false) {
     Sema& SemaRef = interp->getSema();
     ASTReader* Reader = m_Interpreter->getCI()->getASTReader().get();
diff --git a/interpreter/cling/lib/Interpreter/LookupHelper.cpp b/interpreter/cling/lib/Interpreter/LookupHelper.cpp
index f87341ea49ada..4c9feb912ffe7 100644
--- a/interpreter/cling/lib/Interpreter/LookupHelper.cpp
+++ b/interpreter/cling/lib/Interpreter/LookupHelper.cpp
@@ -519,7 +519,7 @@ namespace cling {
 
   const Decl* LookupHelper::findScope(llvm::StringRef className,
                                       DiagSetting diagOnOff,
-                                      const Type** resultType /* = 0 */,
+                                      const Type** resultType /* = nullptr */,
                                       bool instantiateTemplate/*=true*/) const {
 
     //
@@ -1674,6 +1674,8 @@ namespace cling {
                                     llvm::StringRef("func.prototype.file"),
                                     diagOnOff);
 
+      // ParseTypeName might trigger deserialization.
+      Interpreter::PushTransactionRAII TforDeser(Interp);
       unsigned int nargs = 0;
       while (P.getCurToken().isNot(tok::eof)) {
         TypeResult Res(P.ParseTypeName());
diff --git a/interpreter/cling/lib/Interpreter/Value.cpp b/interpreter/cling/lib/Interpreter/Value.cpp
index 52be4a4437adc..8529ecbcbbf9f 100644
--- a/interpreter/cling/lib/Interpreter/Value.cpp
+++ b/interpreter/cling/lib/Interpreter/Value.cpp
@@ -135,16 +135,52 @@ namespace {
 namespace cling {
 
   Value::Value(const Value& other):
-    m_Storage(other.m_Storage), m_StorageType(other.m_StorageType),
+    m_Storage(other.m_Storage), m_NeedsManagedAlloc(other.m_NeedsManagedAlloc),
+    m_TypeKind(other.m_TypeKind),
     m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) {
     if (other.needsManagedAllocation())
       AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();
   }
 
+  static Value::TypeKind getCorrespondingTypeKind(clang::QualType QT) {
+    using namespace clang;
+
+    if (QT->isVoidType())
+      return Value::kVoid;
+
+    if (const auto *ET = dyn_cast(QT.getTypePtr()))
+      QT = ET->getDecl()->getIntegerType();
+
+    if (!QT->isBuiltinType() || QT->castAs()->isNullPtrType())
+      return Value::kPtrOrObjTy;
+
+    switch(QT->getAs()->getKind()) {
+    default:
+#ifndef NDEBUG
+      QT->dump();
+#endif // NDEBUG
+      assert(false && "Type not supported");
+      return Value::kInvalid;
+#define X(type, name) \
+      case BuiltinType::name: return Value::k##name;
+      CLING_VALUE_BUILTIN_TYPES
+#undef X
+    }
+  }
+
   Value::Value(clang::QualType clangTy, Interpreter& Interp):
-    m_StorageType(determineStorageType(clangTy)),
-    m_Type(clangTy.getAsOpaquePtr()),
+    m_TypeKind(getCorrespondingTypeKind(clangTy)),
+    m_Type(clangTy.getAsOpaquePtr()), // FIXME: What if clangTy is freed?
     m_Interpreter(&Interp) {
+    if (m_TypeKind == Value::kPtrOrObjTy) {
+      clang::QualType Canon = clangTy.getCanonicalType();
+      if (Canon->isPointerType() || Canon->isObjectType() ||
+          Canon->isReferenceType())
+        if (Canon->isRecordType() || Canon->isConstantArrayType() ||
+            Canon->isMemberPointerType())
+          m_NeedsManagedAlloc = true;
+    }
+
     if (needsManagedAllocation())
       ManagedAllocate();
   }
@@ -157,7 +193,8 @@ namespace cling {
     // Retain new one.
     m_Type = other.m_Type;
     m_Storage = other.m_Storage;
-    m_StorageType = other.m_StorageType;
+    m_NeedsManagedAlloc = other.m_NeedsManagedAlloc;
+    m_TypeKind = other.m_TypeKind;
     m_Interpreter = other.m_Interpreter;
     if (needsManagedAllocation())
       AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();
@@ -172,10 +209,12 @@ namespace cling {
     // Move new one.
     m_Type = other.m_Type;
     m_Storage = other.m_Storage;
-    m_StorageType = other.m_StorageType;
+    m_NeedsManagedAlloc = other.m_NeedsManagedAlloc;
+    m_TypeKind = other.m_TypeKind;
     m_Interpreter = other.m_Interpreter;
     // Invalidate other so it will not release.
-    other.m_StorageType = kUnsupportedType;
+    other.m_NeedsManagedAlloc = false;
+    other.m_TypeKind = kInvalid;
 
     return *this;
   }
@@ -193,16 +232,9 @@ namespace cling {
     return m_Interpreter->getCI()->getASTContext();
   }
 
-  bool Value::isValid() const { return !getType().isNull(); }
-
-  bool Value::isVoid() const {
-    const clang::ASTContext& Ctx = getASTContext();
-    return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy);
-  }
-
-  size_t Value::GetNumberOfElements() const {
+  static size_t GetNumberOfElements(clang::QualType QT) {
     if (const clang::ConstantArrayType* ArrTy
-        = llvm::dyn_cast(getType())) {
+        = llvm::dyn_cast(QT.getTypePtr())) {
       llvm::APInt arrSize(sizeof(size_t)*8, 1);
       do {
         arrSize *= ArrTy->getSize();
@@ -214,30 +246,6 @@ namespace cling {
     return 1;
   }
 
-  Value::EStorageType Value::determineStorageType(clang::QualType QT) {
-    const clang::Type* desugCanon = QT.getCanonicalType().getTypePtr();
-    if (desugCanon->isSignedIntegerOrEnumerationType())
-      return kSignedIntegerOrEnumerationType;
-    else if (desugCanon->isUnsignedIntegerOrEnumerationType())
-      return kUnsignedIntegerOrEnumerationType;
-    else if (desugCanon->isRealFloatingType()) {
-      const clang::BuiltinType* BT = desugCanon->getAs();
-      if (BT->getKind() == clang::BuiltinType::Double)
-        return kDoubleType;
-      else if (BT->getKind() == clang::BuiltinType::Float)
-        return kFloatType;
-      else if (BT->getKind() == clang::BuiltinType::LongDouble)
-        return kLongDoubleType;
-    } else if (desugCanon->isPointerType() || desugCanon->isObjectType()
-               || desugCanon->isReferenceType()) {
-      if (desugCanon->isRecordType() || desugCanon->isConstantArrayType()
-          || desugCanon->isMemberPointerType())
-        return kManagedAllocation;
-      return kPointerType;
-    }
-    return kUnsupportedType;
-  }
-
   void Value::ManagedAllocate() {
     assert(needsManagedAllocation() && "Does not need managed allocation");
     void* dtorFunc = 0;
@@ -255,11 +263,46 @@ namespace cling {
     const clang::ASTContext& ctx = getASTContext();
     unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity();
     m_Storage.m_Ptr = AllocatedValue::CreatePayload(payloadSize, dtorFunc,
-                                                    GetNumberOfElements());
+                                                GetNumberOfElements(getType()));
+  }
+
+  void Value::AssertTypeMismatch(const char* Type) const {
+#ifndef NDEBUG
+    assert(isBuiltinType() && "Must be a builtin!");
+    const clang::BuiltinType *BT = getType()->castAs();
+    clang::PrintingPolicy Policy = getASTContext().getPrintingPolicy();
+#endif // NDEBUG
+    assert(BT->getName(Policy).equals(Type));
   }
 
+  static clang::QualType getCorrespondingBuiltin(clang::ASTContext &C,
+                                                 clang::BuiltinType::Kind K) {
+    using namespace clang;
+    switch(K) {
+    default:
+      assert(false && "Type not supported");
+      return {};
+#define BUILTIN_TYPE(Id, SingletonId) \
+      case BuiltinType::Id: return C.SingletonId;
+#include "clang/AST/BuiltinTypes.def"
+    }
+  }
+
+#define X(type, name)                                                   \
+  template <> Value Value::Create(Interpreter& Interp, type val) {      \
+    clang::ASTContext &C = Interp.getCI()->getASTContext();             \
+    clang::BuiltinType::Kind K = clang::BuiltinType::name;              \
+    Value res = Value(getCorrespondingBuiltin(C, K), Interp);           \
+    res.set##name(val);                                                 \
+    return res;                                                         \
+  }                                                                     \
+
+  CLING_VALUE_BUILTIN_TYPES
+
+#undef X
+
   void Value::AssertOnUnsupportedTypeCast() const {
-    assert("unsupported type in Value, cannot cast simplistically!" && 0);
+    assert("unsupported type in Value, cannot cast!" && 0);
   }
 
   namespace valuePrinterInternal {
diff --git a/interpreter/cling/lib/Interpreter/ValueExtractionSynthesizer.cpp b/interpreter/cling/lib/Interpreter/ValueExtractionSynthesizer.cpp
index 5de56b41a901b..cf6d6cdf2979a 100644
--- a/interpreter/cling/lib/Interpreter/ValueExtractionSynthesizer.cpp
+++ b/interpreter/cling/lib/Interpreter/ValueExtractionSynthesizer.cpp
@@ -295,7 +295,14 @@ namespace {
       if (const ConstantArrayType* constArray
           = dyn_cast(desugaredTy.getTypePtr())) {
         CallArgs.clear();
-        CallArgs.push_back(E);
+        // Get a pointer to the base element type so the instantiated copyArray
+        // template can do placement new.
+        QualType baseElementType = m_Context->getBaseElementType(desugaredTy);
+        TypeSourceInfo* TSI = m_Context->getTrivialTypeSourceInfo(
+            m_Context->getPointerType(baseElementType), noLoc);
+        Expr* srcPointer =
+            m_Sema->BuildCStyleCastExpr(noLoc, TSI, noLoc, E).get();
+        CallArgs.push_back(srcPointer);
         CallArgs.push_back(placement);
         size_t arrSize
           = m_Context->getConstantArrayElementCount(constArray);
@@ -523,44 +530,42 @@ namespace runtime {
     CLING_LIB_EXPORT
     void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn,
                          float value) {
-      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs() = value;
+      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).setFloat(value);
       dumpIfNoStorage(vpSVR, vpOn);
     }
 
     CLING_LIB_EXPORT
     void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn,
                          double value) {
-      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs() = value;
+      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).setDouble(value);
       dumpIfNoStorage(vpSVR, vpOn);
     }
 
     CLING_LIB_EXPORT
     void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn,
                          long double value) {
-      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs()
-        = value;
+      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).setLongDouble(value);
       dumpIfNoStorage(vpSVR, vpOn);
     }
 
     CLING_LIB_EXPORT
     void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn,
                          unsigned long long value) {
-      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT)
-        .getAs() = value;
+      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).setULongLong(value);
       dumpIfNoStorage(vpSVR, vpOn);
     }
 
     CLING_LIB_EXPORT
     void setValueNoAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn,
                          const void* value){
-      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs()
-        = const_cast(value);
+      allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT)
+        .setPtr(const_cast(value));
       dumpIfNoStorage(vpSVR, vpOn);
     }
 
     CLING_LIB_EXPORT
     void* setValueWithAlloc(void* vpI, void* vpSVR, void* vpQT, char vpOn) {
-      return allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getAs();
+      return allocateStoredRefValueAndGetGV(vpI, vpSVR, vpQT).getPtr();
     }
   } // end namespace internal
 } // end namespace runtime
diff --git a/interpreter/cling/lib/Interpreter/ValuePrinter.cpp b/interpreter/cling/lib/Interpreter/ValuePrinter.cpp
index 784122677434c..f16f9406fc01c 100644
--- a/interpreter/cling/lib/Interpreter/ValuePrinter.cpp
+++ b/interpreter/cling/lib/Interpreter/ValuePrinter.cpp
@@ -762,7 +762,7 @@ static std::string printEnumValue(const Value &V) {
   const clang::EnumType *EnumTy = Ty.getNonReferenceType()->getAs();
   assert(EnumTy && "ValuePrinter.cpp: ERROR, printEnumValue invoked for a non enum type.");
   clang::EnumDecl *ED = EnumTy->getDecl();
-  uint64_t value = V.getULL();
+  uint64_t value = V.getULongLong();
   bool IsFirst = true;
   llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
   for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
@@ -906,33 +906,33 @@ static std::string printUnpackedClingValue(const Value &V) {
       = llvm::dyn_cast(Td.getCanonicalType().getTypePtr())) {
     switch (BT->getKind()) {
       case clang::BuiltinType::Bool:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
 
       case clang::BuiltinType::Char_S:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::SChar:
-        return executePrintValue(V, V.getLL());
+         return executePrintValue(V, V.castAs());
       case clang::BuiltinType::Short:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::Int:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::Long:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::LongLong:
-        return executePrintValue(V, V.getLL());
+        return executePrintValue(V, V.castAs());
 
       case clang::BuiltinType::Char_U:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::UChar:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::UShort:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::UInt:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::ULong:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
       case clang::BuiltinType::ULongLong:
-        return executePrintValue(V, V.getULL());
+        return executePrintValue(V, V.castAs());
 
       case clang::BuiltinType::Float:
         return executePrintValue(V, V.getFloat());
diff --git a/interpreter/cling/lib/MetaProcessor/Display.cpp b/interpreter/cling/lib/MetaProcessor/Display.cpp
index 7c74eecc01552..22032c7967b7e 100644
--- a/interpreter/cling/lib/MetaProcessor/Display.cpp
+++ b/interpreter/cling/lib/MetaProcessor/Display.cpp
@@ -71,7 +71,7 @@ bool HasUDT(const Decl* decl)
 //______________________________________________________________________________
 int NumberOfElements(const ArrayType* type)
 {
-  assert(type != 0 && "NumberOfElements, 'type' parameter is null");
+  assert(type != nullptr && "NumberOfElements, 'type' parameter is null");
 
   if (const ConstantArrayType* const arrayType = dyn_cast(type)) {
     //We can calculate only the size of constant size array.
@@ -98,7 +98,7 @@ static void AppendAnyDeclLocation(const CompilerInstance* compiler,
                                   const char* formatNull,
                                   const char* filenameNull)
 {
-  assert(compiler != 0 && "AppendAnyDeclLocation, 'compiler' parameter is null");
+  assert(compiler != nullptr && "AppendAnyDeclLocation, 'compiler' parameter is null");
 
   llvm::raw_string_ostream rss(textLine);
   llvm::formatted_raw_ostream frss(rss);
@@ -130,7 +130,7 @@ static void AppendAnyDeclLocation(const CompilerInstance* compiler,
 void AppendClassDeclLocation(const CompilerInstance* compiler, const CXXRecordDecl* classDecl,
                              std::string& textLine, bool verbose)
 {
-  assert(classDecl != 0 && "AppendClassDeclLocation, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "AppendClassDeclLocation, 'classDecl' parameter is null");
 
   //Location has a fixed format - from G__display_class.
   static const char* formatShort = "%-25s%5d";
@@ -148,8 +148,8 @@ void AppendMemberFunctionLocation(const CompilerInstance* compiler, const Decl*
 {
   //Location has a fixed format - from G__display_class.
 
-  assert(compiler != 0 && "AppendMemberFunctionLocation, 'compiler' parameter is null");
-  assert(decl != 0 && "AppendMemberFunctionLocation, 'decl' parameter is null");
+  assert(compiler != nullptr && "AppendMemberFunctionLocation, 'compiler' parameter is null");
+  assert(decl != nullptr && "AppendMemberFunctionLocation, 'decl' parameter is null");
 
   llvm::raw_string_ostream rss(textLine);
   llvm::formatted_raw_ostream frss(rss);
@@ -171,7 +171,7 @@ void AppendDeclLocation(const CompilerInstance* compiler, const Decl* decl,
 void AppendMacroLocation(const CompilerInstance* compiler, const MacroInfo* macroInfo,
                          std::string& textLine)
 {
-  assert(macroInfo != 0 && "AppendMacroLocation, 'macroInfo' parameter is null");
+  assert(macroInfo != nullptr && "AppendMacroLocation, 'macroInfo' parameter is null");
 
   //TODO: check what does location for macro definition really means -
   //macro can be defined many times, what do we have in a TranslationUnit in this case?
@@ -184,7 +184,7 @@ void AppendMacroLocation(const CompilerInstance* compiler, const MacroInfo* macr
 //______________________________________________________________________________
 void AppendClassKeyword(const CXXRecordDecl* classDecl, std::string& name)
 {
-  assert(classDecl != 0 && "AppendClassKeyword, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "AppendClassKeyword, 'classDecl' parameter is null");
 
   name += classDecl->getKindName();
   name += ' ';
@@ -193,7 +193,7 @@ void AppendClassKeyword(const CXXRecordDecl* classDecl, std::string& name)
 //______________________________________________________________________________
 void AppendClassName(const CXXRecordDecl* classDecl, std::string& name)
 {
-  assert(classDecl != 0 && "AppendClassName, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "AppendClassName, 'classDecl' parameter is null");
 
   const LangOptions langOpts;
   PrintingPolicy printingPolicy(langOpts);
@@ -211,7 +211,7 @@ void AppendClassName(const CXXRecordDecl* classDecl, std::string& name)
 //______________________________________________________________________________
 void AppendMemberAccessSpecifier(const Decl* memberDecl, std::string& name)
 {
-  assert(memberDecl != 0 && "AppendMemberAccessSpecifier, 'memberDecl' parameter is 0");
+  assert(memberDecl != nullptr && "AppendMemberAccessSpecifier, 'memberDecl' parameter is 0");
 
   switch (memberDecl->getAccess()) {
   case AS_private:
@@ -229,7 +229,7 @@ void AppendMemberAccessSpecifier(const Decl* memberDecl, std::string& name)
 //______________________________________________________________________________
 void AppendConstructorSignature(const CXXConstructorDecl* ctorDecl, std::string& name)
 {
-  assert(ctorDecl != 0 && "AppendConstructorSignature, 'ctorDecl' parameter is null");
+  assert(ctorDecl != nullptr && "AppendConstructorSignature, 'ctorDecl' parameter is null");
 
   const QualType type = ctorDecl->getType();
   assert(isa(type) == true && "AppendConstructorSignature, ctorDecl->getType is not a FunctionType");
@@ -272,7 +272,7 @@ void AppendConstructorSignature(const CXXConstructorDecl* ctorDecl, std::string&
 //______________________________________________________________________________
 void AppendMemberFunctionSignature(const Decl* methodDecl, std::string& name)
 {
-  assert(methodDecl != 0 && "AppendMemberFunctionSignature, 'methodDecl' parameter is null");
+  assert(methodDecl != nullptr && "AppendMemberFunctionSignature, 'methodDecl' parameter is null");
   assert(methodDecl->getKind() != Decl::CXXConstructor && "AppendMemberFunctionSignature, called for a ctor declaration");
 
   llvm::raw_string_ostream out(name);
@@ -289,7 +289,7 @@ void AppendMemberFunctionSignature(const Decl* methodDecl, std::string& name)
 void AppendObjectDeclaration(const Decl* objDecl, const PrintingPolicy& policy,
                              bool printInstantiation, std::string& name)
 {
-  assert(objDecl != 0 && "AppendObjectDeclaration, 'objDecl' parameter is null");
+  assert(objDecl != nullptr && "AppendObjectDeclaration, 'objDecl' parameter is null");
 
   llvm::raw_string_ostream out(name);
   objDecl->print(out, policy, 0, printInstantiation);
@@ -318,8 +318,8 @@ void AppendBaseClassSpecifiers(base_decl_iterator base, std::string& textLine)
 void AppendClassSize(const CompilerInstance* compiler, const RecordDecl* decl,
                      std::string& textLine)
 {
-  assert(compiler != 0 && "AppendClassSize, 'compiler' parameter is null");
-  assert(decl != 0 && "AppendClassSize, 'decl' parameter is null");
+  assert(compiler != nullptr && "AppendClassSize, 'compiler' parameter is null");
+  assert(decl != nullptr && "AppendClassSize, 'decl' parameter is null");
 
   if (dyn_cast(decl)) {
     textLine += "SIZE: (NA)";
@@ -337,8 +337,8 @@ void AppendClassSize(const CompilerInstance* compiler, const RecordDecl* decl,
 template
 void AppendUDTSize(const CompilerInstance* compiler, const Decl* decl, std::string& textLine)
 {
-  assert(compiler != 0 && "AppendUDTSize, 'compiler' parameter is null");
-  assert(decl != 0 && "AppendUDTSize, 'decl' parameter is null");
+  assert(compiler != nullptr && "AppendUDTSize, 'compiler' parameter is null");
+  assert(decl != nullptr && "AppendUDTSize, 'decl' parameter is null");
 
   std::string formatted;
 
@@ -372,9 +372,9 @@ void AppendUDTSize(const CompilerInstance* compiler, const Decl* decl, std::stri
 void AppendBaseClassOffset(const CompilerInstance* compiler, const CXXRecordDecl* completeClass,
                            const CXXRecordDecl* baseClass, bool isVirtual, std::string& textLine)
 {
-  assert(compiler != 0 && "AppendBaseClassOffset, 'compiler' parameter is null");
-  assert(completeClass != 0 && "AppendBaseClassOffset, 'completeClass' parameter is null");
-  assert(baseClass != 0 && "AppendBaseClassOffset, 'baseClass' parameter is null");
+  assert(compiler != nullptr && "AppendBaseClassOffset, 'compiler' parameter is null");
+  assert(completeClass != nullptr && "AppendBaseClassOffset, 'completeClass' parameter is null");
+  assert(baseClass != nullptr && "AppendBaseClassOffset, 'baseClass' parameter is null");
 
   const ASTRecordLayout& layout = compiler->getASTContext().getASTRecordLayout(completeClass);
 
@@ -391,9 +391,9 @@ void AppendBaseClassOffset(const CompilerInstance* compiler, const CXXRecordDecl
 void AppendDataMemberOffset(const CompilerInstance* compiler, const CXXRecordDecl* classDecl,
                             const FieldDecl* fieldDecl, std::string& textLine)
 {
-  assert(compiler != 0 && "AppendDataMemberOffset, 'compiler' parameter is null");
-  assert(classDecl != 0 && "AppendDataMemberOffset, 'classDecl' parameter is null");
-  assert(fieldDecl != 0 && "AppendDataMemberOffset, 'fieldDecl' parameter is null");
+  assert(compiler != nullptr && "AppendDataMemberOffset, 'compiler' parameter is null");
+  assert(classDecl != nullptr && "AppendDataMemberOffset, 'classDecl' parameter is null");
+  assert(fieldDecl != nullptr && "AppendDataMemberOffset, 'fieldDecl' parameter is null");
 
   const ASTRecordLayout& layout = compiler->getASTContext().getASTRecordLayout(classDecl);
 
@@ -428,7 +428,7 @@ FILEPrintHelper::FILEPrintHelper(llvm::raw_ostream& stream)
 //______________________________________________________________________________
 void FILEPrintHelper::Print(const char* msg)const
 {
-  assert(msg != 0 && "Print, 'msg' parameter is null");
+  assert(msg != nullptr && "Print, 'msg' parameter is null");
   // We want to keep stdout and fStream in sync if fStream is different.
   fflush(stdout);
   fStream << msg;
@@ -471,7 +471,7 @@ class ClassPrinter {
   void ProcessTypeOfMember(const Decl* decl, unsigned nSpaces)const
   {
     //Extract the type of declaration and process it.
-    assert(decl != 0 && "ProcessTypeOfMember, 'decl' parameter is null");
+    assert(decl != nullptr && "ProcessTypeOfMember, 'decl' parameter is null");
 
     if (const ArrayType* const arrayType = decl->getType()->getAsArrayTypeUnsafe()) {
       if (const Type* const elType = arrayType->getBaseElementTypeUnsafe()) {
@@ -510,7 +510,7 @@ ClassPrinter::ClassPrinter(llvm::raw_ostream& stream, const cling::Interpreter*
              fInterpreter(interpreter),
              fVerbose(false)
 {
-  assert(interpreter != 0 && "ClassPrinter, 'compiler' parameter is null");
+  assert(interpreter != nullptr && "ClassPrinter, 'compiler' parameter is null");
 }
 
 
@@ -518,13 +518,13 @@ ClassPrinter::ClassPrinter(llvm::raw_ostream& stream, const cling::Interpreter*
 void ClassPrinter::DisplayAllClasses()const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "DisplayAllClasses, fCompiler is null");
+  assert(fInterpreter != nullptr && "DisplayAllClasses, fCompiler is null");
 
   const CompilerInstance* const compiler = fInterpreter->getCI();
-  assert(compiler != 0 && "DisplayAllClasses, compiler instance is null");
+  assert(compiler != nullptr && "DisplayAllClasses, compiler instance is null");
 
   const TranslationUnitDecl* const tuDecl = compiler->getASTContext().getTranslationUnitDecl();
-  assert(tuDecl != 0 && "DisplayAllClasses, translation unit is empty");
+  assert(tuDecl != nullptr && "DisplayAllClasses, translation unit is empty");
 
   fOut.Print("List of classes\n");
   // Could trigger deserialization of decls.
@@ -565,8 +565,8 @@ void ClassPrinter::SetVerbose(bool verbose)
 void ClassPrinter::ProcessDecl(decl_iterator decl)const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "ProcessDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessDecl, 'decl' parameter is not a valid iterator");
 
   switch (decl->getKind()) {
   case Decl::Namespace:
@@ -605,14 +605,14 @@ void ClassPrinter::ProcessDecl(decl_iterator decl)const
 void ClassPrinter::ProcessBlockDecl(decl_iterator decl)const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "ProcessBlockDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessBlockDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessBlockDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessBlockDecl, 'decl' parameter is not a valid iterator");
   assert(decl->getKind() == Decl::Block && "ProcessBlockDecl, decl->getKind() != BlockDecl");
 
   //Block can contain nested (arbitrary deep) class declarations.
   //Though, I'm not sure if have block in our code.
   const BlockDecl* const blockDecl = dyn_cast(*decl);
-  assert(blockDecl != 0 && "ProcessBlockDecl, internal error - decl is not a BlockDecl");
+  assert(blockDecl != nullptr && "ProcessBlockDecl, internal error - decl is not a BlockDecl");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
@@ -624,12 +624,12 @@ void ClassPrinter::ProcessBlockDecl(decl_iterator decl)const
 void ClassPrinter::ProcessFunctionDecl(decl_iterator decl)const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "ProcessFunctionDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessFunctionDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessFunctionDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessFunctionDecl, 'decl' parameter is not a valid iterator");
 
   //Function can contain class declarations, we have to check this.
   const FunctionDecl* const functionDecl = dyn_cast(*decl);
-  assert(functionDecl != 0 && "ProcessFunctionDecl, internal error - decl is not a FunctionDecl");
+  assert(functionDecl != nullptr && "ProcessFunctionDecl, internal error - decl is not a FunctionDecl");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
@@ -641,13 +641,13 @@ void ClassPrinter::ProcessFunctionDecl(decl_iterator decl)const
 void ClassPrinter::ProcessNamespaceDecl(decl_iterator decl)const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "ProcessNamespaceDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessNamespaceDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessNamespaceDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessNamespaceDecl, 'decl' parameter is not a valid iterator");
   assert(decl->getKind() == Decl::Namespace && "ProcessNamespaceDecl, decl->getKind() != Namespace");
 
   //Namespace can contain nested (arbitrary deep) class declarations.
   const NamespaceDecl* const namespaceDecl = dyn_cast(*decl);
-  assert(namespaceDecl != 0 && "ProcessNamespaceDecl, 'decl' parameter is not a NamespaceDecl");
+  assert(namespaceDecl != nullptr && "ProcessNamespaceDecl, 'decl' parameter is not a NamespaceDecl");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
@@ -659,11 +659,11 @@ void ClassPrinter::ProcessNamespaceDecl(decl_iterator decl)const
 void ClassPrinter::ProcessLinkageSpecDecl(decl_iterator decl)const
 {
   //Just in case asserts were deleted from ctor:
-  assert(fInterpreter != 0 && "ProcessLinkageSpecDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessLinkageSpecDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessLinkageSpecDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessLinkageSpecDecl, 'decl' parameter is not a valid iterator");
 
   const LinkageSpecDecl* const linkageSpec = dyn_cast(*decl);
-  assert(linkageSpec != 0 && "ProcessLinkageSpecDecl, decl is not a LinkageSpecDecl");
+  assert(linkageSpec != nullptr && "ProcessLinkageSpecDecl, decl is not a LinkageSpecDecl");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
@@ -674,11 +674,11 @@ void ClassPrinter::ProcessLinkageSpecDecl(decl_iterator decl)const
 //______________________________________________________________________________
 void ClassPrinter::ProcessClassDecl(decl_iterator decl) const
 {
-  assert(fInterpreter != 0 && "ProcessClassDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessClassDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessClassDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessClassDecl, 'decl' parameter is not a valid iterator");
 
   const CXXRecordDecl* const classDecl = dyn_cast(*decl);
-  assert(classDecl != 0 && "ProcessClassDecl, internal error, declaration is not a CXXRecordDecl");
+  assert(classDecl != nullptr && "ProcessClassDecl, internal error, declaration is not a CXXRecordDecl");
 
   if (!classDecl->hasDefinition()) {
     DisplayClassFwdDecl(classDecl);
@@ -698,11 +698,11 @@ void ClassPrinter::ProcessClassDecl(decl_iterator decl) const
 //______________________________________________________________________________
 void ClassPrinter::ProcessClassTemplateDecl(decl_iterator decl)const
 {
-  assert(fInterpreter != 0 && "ProcessClassDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessClassDecl, 'decl' parameter is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessClassDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessClassDecl, 'decl' parameter is not a valid iterator");
 
   ClassTemplateDecl *templateDecl = dyn_cast(*decl);
-  assert(templateDecl != 0 && "ProcessClassTemplateDecl, internal error, declaration is not a ClassTemplateDecl");
+  assert(templateDecl != nullptr && "ProcessClassTemplateDecl, internal error, declaration is not a ClassTemplateDecl");
 
   templateDecl = templateDecl->getCanonicalDecl();
 
@@ -720,14 +720,14 @@ void ClassPrinter::ProcessClassTemplateDecl(decl_iterator decl)const
 //______________________________________________________________________________
 void ClassPrinter::DisplayClassDecl(const CXXRecordDecl* classDecl)const
 {
-  assert(classDecl != 0 && "DisplayClassDecl, 'classDecl' parameter is null");
-  assert(fInterpreter != 0 && "DisplayClassDecl, fInterpreter is null");
+  assert(classDecl != nullptr && "DisplayClassDecl, 'classDecl' parameter is null");
+  assert(fInterpreter != nullptr && "DisplayClassDecl, fInterpreter is null");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
 
   classDecl = classDecl->getDefinition();
-  assert(classDecl != 0 && "DisplayClassDecl, invalid decl - no definition");
+  assert(classDecl != nullptr && "DisplayClassDecl, invalid decl - no definition");
 
   if (fSeenDecls.find(classDecl) != fSeenDecls.end())
     return;
@@ -787,8 +787,8 @@ void ClassPrinter::DisplayClassDecl(const CXXRecordDecl* classDecl)const
 //______________________________________________________________________________
 void ClassPrinter::DisplayClassFwdDecl(const CXXRecordDecl* classDecl)const
 {
-  assert(classDecl != 0 && "DisplayClassDecl, 'classDecl' parameter is null");
-  assert(fInterpreter != 0 && "DisplayClassDecl, fInterpreter is null");
+  assert(classDecl != nullptr && "DisplayClassDecl, 'classDecl' parameter is null");
+  assert(fInterpreter != nullptr && "DisplayClassDecl, fInterpreter is null");
 
   if (classDecl->isImplicit() || fSeenDecls.find(classDecl) != fSeenDecls.end())
     return;
@@ -830,8 +830,8 @@ void ClassPrinter::DisplayClassFwdDecl(const CXXRecordDecl* classDecl)const
 //______________________________________________________________________________
 void ClassPrinter::DisplayBasesAsList(const CXXRecordDecl* classDecl)const
 {
-  assert(fInterpreter != 0 && "DisplayBasesAsList, fInterpreter is null");
-  assert(classDecl != 0 && "DisplayBasesAsList, 'classDecl' parameter is 0");
+  assert(fInterpreter != nullptr && "DisplayBasesAsList, fInterpreter is null");
+  assert(classDecl != nullptr && "DisplayBasesAsList, 'classDecl' parameter is 0");
   assert(classDecl->hasDefinition() == true && "DisplayBasesAsList, 'classDecl' is invalid");
   assert(fVerbose == false && "DisplayBasesAsList, called in a verbose output");
 
@@ -863,10 +863,10 @@ void ClassPrinter::DisplayBasesAsList(const CXXRecordDecl* classDecl)const
 //______________________________________________________________________________
 void ClassPrinter::DisplayBasesAsTree(const CXXRecordDecl* classDecl, unsigned nSpaces)const
 {
-  assert(classDecl != 0 && "DisplayBasesAsTree, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "DisplayBasesAsTree, 'classDecl' parameter is null");
   assert(classDecl->hasDefinition() == true && "DisplayBasesAsTree, 'classDecl' is invalid");
 
-  assert(fInterpreter != 0 && "DisplayBasesAsTree, fInterpreter is null");
+  assert(fInterpreter != nullptr && "DisplayBasesAsTree, fInterpreter is null");
   assert(fVerbose == true && "DisplayBasesAsTree, call in a simplified output");
 
   std::string textLine;
@@ -901,7 +901,7 @@ void ClassPrinter::DisplayBasesAsTree(const CXXRecordDecl* classDecl, unsigned n
 //______________________________________________________________________________
 void ClassPrinter::DisplayMemberFunctions(const CXXRecordDecl* classDecl)const
 {
-  assert(classDecl != 0 && "DisplayMemberFunctions, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "DisplayMemberFunctions, 'classDecl' parameter is null");
 
   typedef CXXRecordDecl::method_iterator method_iterator;
   typedef CXXRecordDecl::ctor_iterator ctor_iterator;
@@ -946,7 +946,7 @@ void ClassPrinter::DisplayMemberFunctions(const CXXRecordDecl* classDecl)const
   for (decl_iterator decl = classDecl->decls_begin(); decl != classDecl->decls_end(); ++decl) {
     if (decl->getKind() == Decl::FunctionTemplate) {
       const FunctionTemplateDecl* const ftDecl = dyn_cast(*decl);
-      assert(ftDecl != 0 && "DisplayMemberFunctions, decl is not a function template");
+      assert(ftDecl != nullptr && "DisplayMemberFunctions, decl is not a function template");
 
       textLine.clear();
       AppendMemberFunctionLocation(fInterpreter->getCI(), *decl, textLine);
@@ -975,7 +975,7 @@ void ClassPrinter::DisplayMemberFunctions(const CXXRecordDecl* classDecl)const
 //______________________________________________________________________________
 void ClassPrinter::DisplayDataMembers(const CXXRecordDecl* classDecl, unsigned nSpaces)const
 {
-  assert(classDecl != 0 && "DisplayDataMembers, 'classDecl' parameter is null");
+  assert(classDecl != nullptr && "DisplayDataMembers, 'classDecl' parameter is null");
 
   typedef RecordDecl::field_iterator field_iterator;
   typedef EnumDecl::enumerator_iterator enumerator_iterator;
@@ -1018,7 +1018,7 @@ void ClassPrinter::DisplayDataMembers(const CXXRecordDecl* classDecl, unsigned n
   for (decl_iterator decl = classDecl->decls_begin(); decl != classDecl->decls_end(); ++decl) {
     if (decl->getKind() == Decl::Enum) {
       const EnumDecl* enumDecl = dyn_cast(*decl);
-      assert(enumDecl != 0 && "DisplayDataMembers, decl->getKind() == Enum, but decl is not a EnumDecl");
+      assert(enumDecl != nullptr && "DisplayDataMembers, decl->getKind() == Enum, but decl is not a EnumDecl");
       //it's not really clear, if I should really check this.
       if (enumDecl->isComplete() && (enumDecl = enumDecl->getDefinition())) {
         //if (fSeenDecls.find(enumDecl) == fSeenDecls.end()) {
@@ -1053,7 +1053,7 @@ void ClassPrinter::DisplayDataMembers(const CXXRecordDecl* classDecl, unsigned n
       }
     } else if (decl->getKind() == Decl::Var) {
       const VarDecl* const varDecl = dyn_cast(*decl);
-      assert(varDecl != 0 && "DisplayDataMembers, decl->getKind() == Var, but decl is not a VarDecl");
+      assert(varDecl != nullptr && "DisplayDataMembers, decl->getKind() == Var, but decl is not a VarDecl");
       if (varDecl->getStorageClass() == SC_Static) {
         //I hope, this is a static data-member :)
         textLine.clear();
@@ -1106,7 +1106,7 @@ GlobalsPrinter::GlobalsPrinter(llvm::raw_ostream& stream, const cling::Interpret
            : fOut(stream),
              fInterpreter(interpreter)
 {
-  assert(interpreter != 0 && "GlobalsPrinter, 'compiler' parameter is null");
+  assert(interpreter != nullptr && "GlobalsPrinter, 'compiler' parameter is null");
 }
 
 //______________________________________________________________________________
@@ -1138,13 +1138,13 @@ void GlobalsPrinter::DisplayGlobals()const
 {
   typedef Preprocessor::macro_iterator macro_iterator;
 
-  assert(fInterpreter != 0 && "DisplayGlobals, fInterpreter is null");
+  assert(fInterpreter != nullptr && "DisplayGlobals, fInterpreter is null");
 
   const CompilerInstance* const compiler = fInterpreter->getCI();
-  assert(compiler != 0 && "DisplayGlobals, compiler instance is null");
+  assert(compiler != nullptr && "DisplayGlobals, compiler instance is null");
 
   const TranslationUnitDecl* const tuDecl = compiler->getASTContext().getTranslationUnitDecl();
-  assert(tuDecl != 0 && "DisplayGlobals, translation unit is empty");
+  assert(tuDecl != nullptr && "DisplayGlobals, translation unit is empty");
 
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
@@ -1174,13 +1174,13 @@ void GlobalsPrinter::DisplayGlobal(const std::string& name)const
 
   //TODO: is it ok to compare 'name' with decl->getNameAsString() ??
 
-  assert(fInterpreter != 0 && "DisplayGlobal, fInterpreter is null");
+  assert(fInterpreter != nullptr && "DisplayGlobal, fInterpreter is null");
 
   const CompilerInstance* const compiler = fInterpreter->getCI();
-  assert(compiler != 0 && "DisplayGlobal, compiler instance is null");
+  assert(compiler != nullptr && "DisplayGlobal, compiler instance is null");
 
   const TranslationUnitDecl* const tuDecl = compiler->getASTContext().getTranslationUnitDecl();
-  assert(tuDecl != 0 && "DisplayGlobal, translation unit is empty");
+  assert(tuDecl != nullptr && "DisplayGlobal, translation unit is empty");
 
   unsigned count = 0;
 
@@ -1209,8 +1209,8 @@ void GlobalsPrinter::DisplayGlobal(const std::string& name)const
 //______________________________________________________________________________
 void GlobalsPrinter::DisplayVarDecl(const VarDecl* varDecl) const
 {
-  assert(fInterpreter != 0 && "DisplayVarDecl, fInterpreter is null");
-  assert(varDecl != 0 && "DisplayVarDecl, 'varDecl' parameter is null");
+  assert(fInterpreter != nullptr && "DisplayVarDecl, fInterpreter is null");
+  assert(varDecl != nullptr && "DisplayVarDecl, 'varDecl' parameter is null");
 
   const LangOptions langOpts;
   PrintingPolicy printingPolicy(langOpts);
@@ -1240,8 +1240,8 @@ void GlobalsPrinter::DisplayVarDecl(const VarDecl* varDecl) const
 //______________________________________________________________________________
 void GlobalsPrinter::DisplayEnumeratorDecl(const EnumConstantDecl* enumerator)const
 {
-  assert(fInterpreter != 0 && "DisplayEnumeratorDecl, fInterpreter is null");
-  assert(enumerator != 0 && "DisplayEnumeratorDecl, 'enumerator' parameter is null");
+  assert(fInterpreter != nullptr && "DisplayEnumeratorDecl, fInterpreter is null");
+  assert(enumerator != nullptr && "DisplayEnumeratorDecl, 'enumerator' parameter is null");
 
   const LangOptions langOpts;
   PrintingPolicy printingPolicy(langOpts);
@@ -1342,9 +1342,9 @@ void NamespacePrinter::Print()const
 void NamespacePrinter::ProcessNamespaceDeclaration(decl_iterator declIt,
                                 const std::string& enclosingNamespaceName)const
 {
-  assert(fInterpreter != 0 &&
+  assert(fInterpreter != nullptr &&
          "ProcessNamespaceDeclaration, fInterpreter is null");
-  assert(*declIt != 0 &&
+  assert(*declIt != nullptr &&
          "ProcessNamespaceDeclaration, parameter 'decl' is not a valid iterator");
 
   if (const auto nsDecl = dyn_cast(*declIt)) {
@@ -1405,19 +1405,19 @@ TypedefPrinter::TypedefPrinter(llvm::raw_ostream& stream, const Interpreter* int
                   : fOut(stream),
                     fInterpreter(interpreter)
 {
-  assert(interpreter != 0 && "TypedefPrinter, parameter 'interpreter' is null");
+  assert(interpreter != nullptr && "TypedefPrinter, parameter 'interpreter' is null");
 }
 
 //______________________________________________________________________________
 void TypedefPrinter::DisplayTypedefs()const
 {
-  assert(fInterpreter != 0 && "DisplayTypedefs, fInterpreter is null");
+  assert(fInterpreter != nullptr && "DisplayTypedefs, fInterpreter is null");
 
   const CompilerInstance* const compiler = fInterpreter->getCI();
-  assert(compiler != 0 && "DisplayTypedefs, compiler instance is null");
+  assert(compiler != nullptr && "DisplayTypedefs, compiler instance is null");
 
   const TranslationUnitDecl* const tuDecl = compiler->getASTContext().getTranslationUnitDecl();
-  assert(tuDecl != 0 && "DisplayTypedefs, translation unit is empty");
+  assert(tuDecl != nullptr && "DisplayTypedefs, translation unit is empty");
 
   fOut.Print("List of typedefs\n");
   ProcessNestedDeclarations(tuDecl);
@@ -1450,7 +1450,7 @@ void TypedefPrinter::DisplayTypedef(const std::string& typedefName)const
 //______________________________________________________________________________
 void TypedefPrinter::ProcessNestedDeclarations(const DeclContext* decl)const
 {
-  assert(decl != 0 && "ProcessNestedDeclarations, parameter 'decl' is null");
+  assert(decl != nullptr && "ProcessNestedDeclarations, parameter 'decl' is null");
   // Could trigger deserialization of decls.
   Interpreter::PushTransactionRAII RAII(const_cast(fInterpreter));
   for (decl_iterator it = decl->decls_begin(), eIt = decl->decls_end(); it != eIt; ++it)
@@ -1460,8 +1460,8 @@ void TypedefPrinter::ProcessNestedDeclarations(const DeclContext* decl)const
 //______________________________________________________________________________
 void TypedefPrinter::ProcessDecl(decl_iterator decl)const
 {
-  assert(fInterpreter != 0 && "ProcessDecl, fInterpreter is null");
-  assert(*decl != 0 && "ProcessDecl, parameter 'decl' is not a valid iterator");
+  assert(fInterpreter != nullptr && "ProcessDecl, fInterpreter is null");
+  assert(*decl != nullptr && "ProcessDecl, parameter 'decl' is not a valid iterator");
 
   switch (decl->getKind()) {
   case Decl::Typedef:
@@ -1490,9 +1490,9 @@ void TypedefPrinter::ProcessDecl(decl_iterator decl)const
 //______________________________________________________________________________
 void TypedefPrinter::DisplayTypedefDecl(TypedefNameDecl* typedefDecl)const
 {
-  assert(typedefDecl != 0
+  assert(typedefDecl != nullptr
          && "DisplayTypedefDecl, parameter 'typedefDecl' is null");
-  assert(fInterpreter != 0 && "DisplayTypedefDecl, fInterpreter is null");
+  assert(fInterpreter != nullptr && "DisplayTypedefDecl, fInterpreter is null");
 
   std::string textLine;
   AppendDeclLocation(fInterpreter->getCI(), typedefDecl, textLine);
@@ -1524,7 +1524,7 @@ void TypedefPrinter::DisplayTypedefDecl(TypedefNameDecl* typedefDecl)const
 void DisplayClass(llvm::raw_ostream& stream, const Interpreter* interpreter,
                   const char* className, bool verbose)
 {
-  assert(interpreter != 0 && "DisplayClass, 'interpreter' parameter is null");
+  assert(interpreter != nullptr && "DisplayClass, 'interpreter' parameter is null");
 
   ClassPrinter printer(stream, interpreter);
   printer.SetVerbose(verbose);
@@ -1540,7 +1540,7 @@ void DisplayClass(llvm::raw_ostream& stream, const Interpreter* interpreter,
 //______________________________________________________________________________
 void DisplayNamespaces(llvm::raw_ostream &stream, const Interpreter *interpreter)
 {
-  assert(interpreter != 0 && "DisplayNamespaces, parameter 'interpreter' is null");
+  assert(interpreter != nullptr && "DisplayNamespaces, parameter 'interpreter' is null");
   Interpreter::PushTransactionRAII RAII(const_cast(interpreter));
 
   NamespacePrinter printer(stream, interpreter);
@@ -1551,7 +1551,7 @@ void DisplayNamespaces(llvm::raw_ostream &stream, const Interpreter *interpreter
 //______________________________________________________________________________
 void DisplayGlobals(llvm::raw_ostream& stream, const Interpreter* interpreter)
 {
-  assert(interpreter != 0 && "DisplayGlobals, 'interpreter' parameter is null");
+  assert(interpreter != nullptr && "DisplayGlobals, 'interpreter' parameter is null");
 
   GlobalsPrinter printer(stream, interpreter);
   // Could trigger deserialization of decls.
@@ -1563,7 +1563,7 @@ void DisplayGlobals(llvm::raw_ostream& stream, const Interpreter* interpreter)
 void DisplayGlobal(llvm::raw_ostream& stream, const Interpreter* interpreter,
                    const std::string& name)
 {
-  assert(interpreter != 0 && "DisplayGlobal, 'interpreter' parameter is null");
+  assert(interpreter != nullptr && "DisplayGlobal, 'interpreter' parameter is null");
 
   GlobalsPrinter printer(stream, interpreter);
   // Could trigger deserialization of decls.
@@ -1574,7 +1574,7 @@ void DisplayGlobal(llvm::raw_ostream& stream, const Interpreter* interpreter,
 //______________________________________________________________________________
 void DisplayTypedefs(llvm::raw_ostream &stream, const Interpreter *interpreter)
 {
-   assert(interpreter != 0 && "DisplayTypedefs, parameter 'interpreter' is null");
+   assert(interpreter != nullptr && "DisplayTypedefs, parameter 'interpreter' is null");
 
    TypedefPrinter printer(stream, interpreter);
    // Could trigger deserialization of decls.
@@ -1586,7 +1586,7 @@ void DisplayTypedefs(llvm::raw_ostream &stream, const Interpreter *interpreter)
 void DisplayTypedef(llvm::raw_ostream &stream, const Interpreter *interpreter,
                     const std::string &name)
 {
-   assert(interpreter != 0 && "DisplayTypedef, parameter 'interpreter' is null");
+   assert(interpreter != nullptr && "DisplayTypedef, parameter 'interpreter' is null");
 
    TypedefPrinter printer(stream, interpreter);
    printer.DisplayTypedef(name);
diff --git a/interpreter/cling/lib/MetaProcessor/MetaParser.cpp b/interpreter/cling/lib/MetaProcessor/MetaParser.cpp
index 970cb990da204..10569a36ab459 100644
--- a/interpreter/cling/lib/MetaProcessor/MetaParser.cpp
+++ b/interpreter/cling/lib/MetaProcessor/MetaParser.cpp
@@ -279,6 +279,11 @@ namespace cling {
       int forward = 0;
       std::string args;
       llvm::StringRef file(getCurTok().getBufStart());
+
+      if (file.empty()) {
+        return false; // FIXME: Issue proper diagnostics
+      }
+
       while (!lookAhead(forward).is(tok::eof))
 	++forward;
 
diff --git a/interpreter/cling/lib/MetaProcessor/MetaSema.cpp b/interpreter/cling/lib/MetaProcessor/MetaSema.cpp
index abad20f990441..ace4fb2f9f3a6 100644
--- a/interpreter/cling/lib/MetaProcessor/MetaSema.cpp
+++ b/interpreter/cling/lib/MetaProcessor/MetaSema.cpp
@@ -141,7 +141,7 @@ namespace cling {
       return (m_Interpreter.echo(OS.str(), ret) == Interpreter::kSuccess)
               ? CR_Success : CR_Failure;
     };
-    
+
     cling::Transaction* T = nullptr;
     if (actOnLCommand(file, &T) != AR_Success || !T)
       return AR_Failure;
@@ -193,7 +193,7 @@ namespace cling {
     auto interpreterHasTransaction = [] (const Interpreter& Interp,
                                          const Transaction* T) {
       for (const Transaction* I = Interp.getFirstTransaction();
-           I != 0; I = I->getNext())
+           I != nullptr; I = I->getNext())
         if (I == T)
           return true;
       return false;
@@ -469,7 +469,7 @@ namespace cling {
       clang::ASTContext& Ctx = m_Interpreter.getCI()->getASTContext();
       if (result) {
         *result = Value(Ctx.IntTy, m_Interpreter);
-        result->getAs() = exitStatus;
+        result->setLongLong(exitStatus); // FIXME: This should assert.
       }
       return (exitStatus == 0) ? AR_Success : AR_Failure;
     }
diff --git a/interpreter/cling/lib/UserInterface/UserInterface.cpp b/interpreter/cling/lib/UserInterface/UserInterface.cpp
index 77b254731a730..6aa015b8f5dd9 100644
--- a/interpreter/cling/lib/UserInterface/UserInterface.cpp
+++ b/interpreter/cling/lib/UserInterface/UserInterface.cpp
@@ -13,9 +13,10 @@
 #include "cling/MetaProcessor/MetaProcessor.h"
 #include "cling/Utils/Output.h"
 #include "textinput/Callbacks.h"
-#include "textinput/TextInput.h"
+#include "textinput/History.h"
 #include "textinput/StreamReader.h"
 #include "textinput/TerminalDisplay.h"
+#include "textinput/TextInput.h"
 
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -66,6 +67,45 @@ namespace {
 
     textinput::TextInput* operator -> () { return &m_Input; }
   };
+
+  llvm::SmallString<512> GetHistoryFilePath() {
+    if (getenv("CLING_NOHISTORY")) {
+      return {};
+    }
+
+    if (const char* HistFileEnvvar = std::getenv("CLING_HISTFILE")) {
+      return llvm::StringRef{HistFileEnvvar};
+    }
+
+    // History file search order according to XDG Base Directory Specification:
+    //
+    // ${XDG_STATE_HOME}/cling/history
+    // ~/.local/state/cling/history
+    // ~/.cling_history
+    const char* StateHome = std::getenv("XDG_STATE_HOME");
+
+    if (!StateHome) {
+      StateHome = "~/.local/state";
+    }
+
+    llvm::SmallString<512> FilePath;
+
+    if (!llvm::sys::fs::real_path(StateHome, FilePath, true)) {
+      // If xdg state home directory exists then create cling subdirectory if
+      // the latter does not exist.
+      if (llvm::sys::fs::is_directory(FilePath) &&
+          !llvm::sys::fs::create_directory(FilePath += "/cling")) {
+        return FilePath += "/history";
+      }
+    }
+
+    if (llvm::sys::path::home_directory(FilePath)) {
+      return FilePath += "/.cling_history";
+    }
+
+    cling::errs() << "Failed to create command history file\n";
+    return {};
+  }
 }
 
 namespace cling {
@@ -82,12 +122,7 @@ namespace cling {
       PrintLogo();
     }
 
-    llvm::SmallString<512> histfilePath;
-    if (!getenv("CLING_NOHISTORY")) {
-      // History file is $HOME/.cling_history
-      if (llvm::sys::path::home_directory(histfilePath))
-        llvm::sys::path::append(histfilePath, ".cling_history");
-    }
+    auto histfilePath{GetHistoryFilePath()};
 
     const auto Completion =
         std::make_unique(m_MetaProcessor->getInterpreter());
@@ -95,6 +130,17 @@ namespace cling {
 
     TI->SetCompletion(Completion.get());
 
+    if (const char* HistSizeEnvvar = std::getenv("CLING_HISTSIZE")) {
+      const size_t HistSize = std::strtoull(HistSizeEnvvar, nullptr, 0);
+
+      // std::strtoull() returns 0 if the parsing fails.
+      // zero HistSize will disable history logging to file.
+      // refer to textinput::History::AppendToFile()
+      TI->SetHistoryMaxDepth(HistSize);
+      TI->SetHistoryPruneLength(
+          static_cast(textinput::History::kPruneLengthDefault));
+    }
+
     bool Done = false;
     std::string Line;
     std::string Prompt("[cling]$ ");
diff --git a/interpreter/cling/lib/Utils/AST.cpp b/interpreter/cling/lib/Utils/AST.cpp
index 1126ac6382311..353cf27d07086 100644
--- a/interpreter/cling/lib/Utils/AST.cpp
+++ b/interpreter/cling/lib/Utils/AST.cpp
@@ -30,7 +30,7 @@ namespace {
   static D* LookupResult2Decl(clang::LookupResult& R)
   {
     if (R.empty())
-      return 0;
+      return nullptr;
 
     R.resolveKind();
 
@@ -112,7 +112,7 @@ namespace utils {
     if (FoundAt)
       *FoundAt = -1;
 
-    Expr* result = 0;
+    Expr* result = nullptr;
     if (CompoundStmt* CS = dyn_cast(FD->getBody())) {
       ArrayRef Stmts
         = llvm::makeArrayRef(CS->body_begin(), CS->size());
@@ -126,7 +126,7 @@ namespace utils {
         *FoundAt = indexOfLastExpr;
 
       if (indexOfLastExpr < 0)
-        return 0;
+        return nullptr;
 
       if ( (result = dyn_cast(Stmts[indexOfLastExpr])) )
         return result;
@@ -196,7 +196,7 @@ namespace utils {
   GetFullyQualifiedTemplateName(const ASTContext& Ctx, TemplateName &tname) {
 
     bool changed = false;
-    NestedNameSpecifier *NNS = 0;
+    NestedNameSpecifier *NNS = nullptr;
 
     TemplateDecl *argtdecl = tname.getAsTemplateDecl();
     QualifiedTemplateName *qtname = tname.getAsQualifiedTemplateName();
@@ -208,7 +208,7 @@ namespace utils {
         changed = true;
         NNS = qNNS;
       } else {
-        NNS = 0;
+        NNS = nullptr;
       }
     } else {
       NNS = CreateNestedNameSpecifierForScopeOf(Ctx, argtdecl, true);
@@ -274,15 +274,12 @@ namespace utils {
 
       bool mightHaveChanged = false;
       llvm::SmallVector desArgs;
-      for (TemplateSpecializationType::iterator
-             I = TST->begin(), E = TST->end();
-          I != E; ++I) {
-
+      for (const TemplateArgument& Arg : TST->template_arguments()) {
         // cheap to copy and potentially modified by
         // GetFullyQualifedTemplateArgument
-        TemplateArgument arg(*I);
-        mightHaveChanged |= GetFullyQualifiedTemplateArgument(Ctx,arg);
-        desArgs.push_back(arg);
+        TemplateArgument CopiedArg = Arg;
+        mightHaveChanged |= GetFullyQualifiedTemplateArgument(Ctx, CopiedArg);
+        desArgs.push_back(CopiedArg);
       }
 
       // If desugaring happened allocate new type in the AST.
@@ -362,7 +359,7 @@ namespace utils {
 
     if (const Type *type = scope->getAsType()) {
       // Find decl context.
-      const TagDecl* TD = 0;
+      const TagDecl* TD = nullptr;
       if (const TagType* tagdecltype = dyn_cast(type)) {
         TD = tagdecltype->getDecl();
       } else {
@@ -391,7 +388,7 @@ namespace utils {
                                     NestedNameSpecifier *original_prefix,
                              const Transform::Config& TypeConfig) {
     // We have to also desugar the prefix.
-    NestedNameSpecifier* prefix = 0;
+    NestedNameSpecifier* prefix = nullptr;
     if (declContext) {
       // We had a scope prefix as input, let see if it is still
       // the same as the scope of the result and if it is, then
@@ -402,7 +399,7 @@ namespace utils {
         const NamespaceDecl *new_ns =dyn_cast(declContext);
         if (new_ns) {
           new_ns = new_ns->getCanonicalDecl();
-          NamespaceDecl *old_ns = 0;
+          NamespaceDecl *old_ns = nullptr;
           if (original_prefix) {
             original_prefix->getAsNamespace();
             if (NamespaceAliasDecl *alias =
@@ -551,7 +548,7 @@ namespace utils {
         desugared = etype->getNamedType();
       } else {
 
-        Decl* decl = 0;
+        Decl* decl = nullptr;
         const TypedefType* typedeftype =
           dyn_cast_or_null(&(*desugared));
         if (typedeftype) {
@@ -576,7 +573,7 @@ namespace utils {
             outer_scope = SelectPrefix(Ctx,decl->getDeclContext(),
                                        outer_scope,TypeConfig);
           } else {
-            outer_scope = 0;
+            outer_scope = nullptr;
           }
         } else if (outer_scope) {
           outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypeConfig);
@@ -675,7 +672,7 @@ namespace utils {
 
     if (Analyze::IsStdClass(Template)) {
       static const char *stls[] =  //container names
-        {"vector","list","deque","map","multimap","set","multiset",0};
+        {"vector","list","deque","map","multimap","set","multiset",nullptr};
       static unsigned int values[] =       //number of default arg.
         {1,1,1,2,2,2,2};
       StringRef name = Template.getName();
@@ -1040,7 +1037,7 @@ namespace utils {
     // NOTE: however we problably want to add the std::vector typedefs
     // to the list of things to skip!
 
-    NestedNameSpecifier* original_prefix = 0;
+    NestedNameSpecifier* original_prefix = nullptr;
     Qualifiers prefix_qualifiers;
     const ElaboratedType* etype_input
       = dyn_cast(QT.getTypePtr());
@@ -1058,7 +1055,7 @@ namespace utils {
           prefix_qualifiers = QT.getLocalQualifiers();
           QT = QualType(etype_input->getNamedType().getTypePtr(),0);
         } else {
-          original_prefix = 0;
+          original_prefix = nullptr;
         }
       }
     }
@@ -1103,7 +1100,7 @@ namespace utils {
                                            fullyQualifyTmpltArg);
     }
 
-    NestedNameSpecifier* prefix = 0;
+    NestedNameSpecifier* prefix = nullptr;
     const ElaboratedType* etype
       = dyn_cast(QT.getTypePtr());
     if (etype) {
@@ -1118,7 +1115,7 @@ namespace utils {
       // in which case we want to add it ... but we can't really preserve
       // the typedef in this case ...
 
-      Decl *decl = 0;
+      Decl *decl = nullptr;
       const TypedefType* typedeftype =
         dyn_cast_or_null(QT.getTypePtr());
       if (typedeftype) {
@@ -1147,7 +1144,7 @@ namespace utils {
                 // Same type, use the original spelling
                 prefix
                   = GetPartiallyDesugaredNNS(Ctx, original_prefix, TypeConfig);
-                outer = 0; // Cancel the later creation.
+                outer = nullptr; // Cancel the later creation.
               }
             } else {
               const NamespaceDecl *old_ns = original_prefix->getAsNamespace();
@@ -1165,7 +1162,7 @@ namespace utils {
                 // This is the same namespace, use the original prefix
                 // as a starting point.
                 prefix = GetFullyQualifiedNameSpecifier(Ctx,original_prefix);
-                outer = 0; // Cancel the later creation.
+                outer = nullptr; // Cancel the later creation.
               }
             }
           } else { // if (!original_prefix)
@@ -1232,10 +1229,12 @@ namespace utils {
 
       bool mightHaveChanged = false;
       llvm::SmallVector desArgs;
+      llvm::ArrayRef template_arguments =
+          TST->template_arguments();
       unsigned int argi = 0;
-      for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
-          I != E; ++I, ++argi) {
-
+      for (const clang::TemplateArgument *I = template_arguments.begin(),
+                                         *E = template_arguments.end();
+           I != E; ++I, ++argi) {
         if (I->getKind() == TemplateArgument::Expression) {
           // If we have an expression, we need to replace it / desugar it
           // as it could contain unqualifed (or partially qualified or
@@ -1411,14 +1410,14 @@ namespace utils {
       if (const clang::TagDecl* TD = dyn_cast(Within)) {
         if (!TD->getDefinition()) {
           // No definition, no lookup result.
-          return 0;
+          return nullptr;
         }
       }
       S->LookupQualifiedName(R, const_cast(Within));
     }
 
     if (R.empty())
-      return 0;
+      return nullptr;
 
     R.resolveKind();
 
@@ -1527,7 +1526,7 @@ namespace utils {
         return TypeName::CreateNestedNameSpecifier(Ctx, TD, FullyQualified);
       }
     }
-    return 0;
+    return nullptr;
   }
 
   static NestedNameSpecifier*
@@ -1538,9 +1537,9 @@ namespace utils {
     // Create a nested name specifier for the declaring context of the type.
 
     if (!TypePtr)
-      return 0;
+      return nullptr;
 
-    Decl *decl = 0;
+    Decl *decl = nullptr;
     if (const TypedefType* typedeftype = llvm::dyn_cast(TypePtr)) {
       decl = typedeftype->getDecl();
     } else {
@@ -1552,7 +1551,7 @@ namespace utils {
     }
 
     if (!decl)
-      return 0;
+      return nullptr;
 
     return CreateNestedNameSpecifierForScopeOf(Ctx, decl, FullyQualified);
   }
@@ -1564,7 +1563,7 @@ namespace utils {
       // Ignore inline namespace;
       Namesp = dyn_cast_or_null(Namesp->getDeclContext());
     }
-    if (!Namesp) return 0;
+    if (!Namesp) return nullptr;
 
     bool FullyQualified = true; // doesn't matter, DeclContexts are namespaces
     return NestedNameSpecifier::Create(Ctx, CreateOuterNNS(Ctx, Namesp,
@@ -1649,7 +1648,7 @@ namespace utils {
       QT = Ctx.getQualifiedType(QT, quals);
     }
 
-    NestedNameSpecifier* prefix = 0;
+    NestedNameSpecifier* prefix = nullptr;
     Qualifiers prefix_qualifiers;
     if (const ElaboratedType* etype_input
         = llvm::dyn_cast(QT.getTypePtr())) {
@@ -1663,9 +1662,9 @@ namespace utils {
             && !(ns && ns->isAnonymousNamespace())) {
           prefix_qualifiers = QT.getLocalQualifiers();
           prefix = GetFullyQualifiedNameSpecifier(Ctx, prefix);
-          QT = QualType(etype_input->getNamedType().getTypePtr(),0);
+          QT = QualType(etype_input->getNamedType().getTypePtr(), 0);
         } else {
-          prefix = 0;
+          prefix = nullptr;
         }
       }
     } else {
diff --git a/interpreter/cling/lib/Utils/Diagnostics.cpp b/interpreter/cling/lib/Utils/Diagnostics.cpp
index fa2be9f728f6a..c205d930953e7 100644
--- a/interpreter/cling/lib/Utils/Diagnostics.cpp
+++ b/interpreter/cling/lib/Utils/Diagnostics.cpp
@@ -34,7 +34,7 @@ namespace {
 DiagnosticsStore::DiagnosticsStore(clang::DiagnosticsEngine& Diags, bool Own,
                                     bool Report, bool Reset) :
   DiagnosticsOverride(Diags, Own),
-  m_Flags(Report | (Reset << 1)) {
+  m_Flags((Report ? kReport : 0) | (Reset ? kReset : 0)) {
 }
 
 DiagnosticsStore::~DiagnosticsStore() {
diff --git a/interpreter/cling/lib/Utils/PlatformPosix.cpp b/interpreter/cling/lib/Utils/PlatformPosix.cpp
index a01887d673b38..68da3a67ff9be 100644
--- a/interpreter/cling/lib/Utils/PlatformPosix.cpp
+++ b/interpreter/cling/lib/Utils/PlatformPosix.cpp
@@ -169,7 +169,7 @@ bool Popen(const std::string& Cmd, llvm::SmallVectorImpl& Buf, bool RdE) {
 }
 
 bool GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {
-#if defined(__APPLE__) || defined(__CYGWIN__)
+#if defined(__APPLE__) || defined(__CYGWIN__) || defined(R__FBSD)
   Paths.push_back("/usr/local/lib/");
   Paths.push_back("/usr/X11R6/lib/");
   Paths.push_back("/usr/lib/");
diff --git a/interpreter/cling/lib/Utils/SourceNormalization.cpp b/interpreter/cling/lib/Utils/SourceNormalization.cpp
index d63f3583c558b..dc2fa148aff3c 100644
--- a/interpreter/cling/lib/Utils/SourceNormalization.cpp
+++ b/interpreter/cling/lib/Utils/SourceNormalization.cpp
@@ -21,12 +21,19 @@ namespace {
 ///\brief A Lexer that exposes preprocessor directives.
 class MinimalPPLexer: public Lexer {
 
-  ///\brief Jump to last Identifier in a scope chain A::B::C::D
+  ///\brief Jump to the next token after a scope chain A::B::C::D
   ///
   bool SkipScopes(Token& Tok) {
+    Token LastTok;
+    return SkipScopes(Tok, LastTok);
+  }
+
+  bool SkipScopes(Token& Tok, Token& LastTok) {
+    LastTok = Tok;
+
     if (getLangOpts().CPlusPlus) {
       while (Tok.is(tok::coloncolon)) {
-        if (!LexClean(Tok) || Identifier(Tok).empty())
+        if (!LexClean(LastTok) || Identifier(LastTok).empty())
           return false;
         if (!LexClean(Tok))
           return false;
@@ -38,9 +45,7 @@ class MinimalPPLexer: public Lexer {
   ///\brief Skips all contiguous '*' '&' tokens
   ///
   bool SkipPointerRefs(Token& Tok) {
-    while (Tok.isNot(tok::raw_identifier)) {
-      if (!Tok.isOneOf(tok::star, tok::amp))
-        return false;
+    while (Tok.isOneOf(tok::star, tok::amp)) {
       if (!LexClean(Tok))
         return false;
     }
@@ -71,14 +76,34 @@ class MinimalPPLexer: public Lexer {
         return false;
     }
 
-    // Function or class name should be in Tok now
-    if (Identifier(Tok).empty())
+    auto LastTok{Tok};
+    // skip scopes in function name
+    // e.g. int ::the_namespace::class_a::mem_func() { return 3; }
+    if ((Tok.is(tok::coloncolon) && !SkipScopes(Tok, LastTok)) ||
+        (!LexClean(Tok) ||
+         (Tok.is(tok::coloncolon) && !SkipScopes(Tok, LastTok))))
       return false;
 
-    // Advance to argument list or method name
-    if (!LexClean(Tok))
+    const auto Ident{Identifier(LastTok)}; // function, operator or class name
+
+    if (Ident.empty())
       return false;
 
+    if (Ident.equals("operator")) {
+      // Tok is the operator, e.g. <=, ==, +...
+      // however, for operator() and [], Tok only contains the
+      // left side so we need to parse the closing right side
+      // TODO: tok::spaceship operator<=>
+      if ((Tok.isOneOf(tok::l_paren, tok::l_square) && !CheckBalance(Tok)) ||
+          // user-defined literal, e.g. double operator "" _dd(long double t)
+          // TODO: parse without the space right after "",
+          // e.g. double operator ""_dd(long double t)
+          (Tok.is(tok::string_literal) && !LexClean(Tok)) ||
+          // Advance to argument list or method name
+          !LexClean(Tok))
+        return false;
+    }
+
     if (!SkipScopes(Tok))
       return false;
 
@@ -163,8 +188,13 @@ class MinimalPPLexer: public Lexer {
   ///
   /// \param Tok - Token, advanced to first token to test
   /// \param First - First token identifier.
+  /// \param[out] HasBody - if set to `true`, the function/class body follows;
+  ///                       thus, the caller needs to consume tokens until the
+  ///                       closing `}`
   /// \return - Typeof definition, function/method or class
-  DefinitionType IsClassOrFunction(Token& Tok, llvm::StringRef First) {
+  DefinitionType IsClassOrFunction(Token& Tok, llvm::StringRef First,
+                                   bool& HasBody) {
+    HasBody = true;
     /// ###TODO: Allow preprocessor expansion
     if (!Lexer::isIdentifierBodyChar(First.front(), getLangOpts()))
       return kNONE;
@@ -174,6 +204,8 @@ class MinimalPPLexer: public Lexer {
       return kNONE;
 
     bool Ctor = false;
+    bool Dtor = false;
+
     if (getLangOpts().CPlusPlus && Tok.is(tok::coloncolon)) {
       // CLASS::CLASS() or CLASS::~CLASS()
       // CLASS::NESTED::NESTED()
@@ -201,6 +233,8 @@ class MinimalPPLexer: public Lexer {
       } while (Tok.is(tok::coloncolon));
 
       if (Tok.is(tok::tilde)) {
+        Dtor = true;
+
         if (!LexClean(Tok))
           return kNONE;
         if (!Ident.empty())
@@ -219,7 +253,7 @@ class MinimalPPLexer: public Lexer {
           return kNONE;
 
         // Advance to argument list, or next scope
-        if (!LexClean(Tok))
+        if (!SkipIdentifier(Tok))
           return kNONE;
 
         // Function name should be last on scope chain
@@ -227,6 +261,7 @@ class MinimalPPLexer: public Lexer {
           return kNONE;
 
         Ctor = false;
+        Dtor = false;
       }
     } else {
       bool SeenSignedness = false;
@@ -301,6 +336,19 @@ class MinimalPPLexer: public Lexer {
       if (Ctor && Tok.is(tok::colon))
         return !AdvanceTo(Tok, tok::l_brace) ? kFunction : kNONE;
 
+      if (Ctor || Dtor) {
+        // e.g. CLASS::CLASS() = default;
+        //      CLASS::~CLASS();
+        if (Tok.is(tok::equal)) {
+          if ((!LexClean(Tok) && Tok.isNot(tok::raw_identifier)) ||
+              (!LexClean(Tok) && Tok.isNot(tok::semi)))
+            return kNONE;
+
+          HasBody = false;
+          return kFunction;
+        }
+      }
+
       // class const method 'CLASS::method() const {'
       if (!Ctor && Identifier(Tok).equals("const")) {
         if (LexClean(Tok) && Tok.is(tok::l_brace))
@@ -439,9 +487,10 @@ size_t cling::utils::getWrapPoint(std::string& source,
       Lex.Lex(Tok);
     }
 
-    const tok::TokenKind kind = Tok.getKind();
+    if (Tok.getKind() == tok::coloncolon)
+      Lex.LexClean(Tok);
 
-    if (kind == tok::raw_identifier && !Tok.needsCleaning()) {
+    if (Tok.getKind() == tok::raw_identifier && !Tok.needsCleaning()) {
       StringRef keyword(Tok.getRawIdentifier());
       if (keyword.equals("using")) {
         // FIXME: Using definitions and declarations should be decl extracted.
@@ -464,12 +513,18 @@ size_t cling::utils::getWrapPoint(std::string& source,
       if (keyword.equals("template"))
         return std::string::npos;
 
+      auto HasBody{false};
+
       if (const MinimalPPLexer::DefinitionType T =
-                                          Lex.IsClassOrFunction(Tok, keyword)) {
-        assert(Tok.is(tok::l_brace) && "Lexer begin location invalid");
-        if (!Lex.CheckBalance(Tok))
-          return offset;
-        assert(Tok.is(tok::r_brace) && "Lexer end location invalid");
+              Lex.IsClassOrFunction(Tok, keyword, HasBody)) {
+        if (HasBody) {
+          assert(Tok.is(tok::l_brace) && "Lexer begin location invalid");
+
+          if (!Lex.CheckBalance(Tok))
+            return offset;
+
+          assert(Tok.is(tok::r_brace) && "Lexer end location invalid");
+        }
 
         const size_t rBrace = getFileOffset(Tok);
         // Wrap everything after '}'
diff --git a/interpreter/cling/test/CodeGeneration/const.C b/interpreter/cling/test/CodeGeneration/const.C
new file mode 100644
index 0000000000000..8fe1397be30d8
--- /dev/null
+++ b/interpreter/cling/test/CodeGeneration/const.C
@@ -0,0 +1,37 @@
+//------------------------------------------------------------------------------
+// CLING - the C++ LLVM-based InterpreterG :)
+//
+// This file is dual-licensed: you can choose to license it under the University
+// of Illinois Open Source License or the GNU Lesser General Public License. See
+// LICENSE.TXT for details.
+//------------------------------------------------------------------------------
+
+// RUN: cat %s |  %cling 2>&1 | FileCheck %s
+
+extern "C" int printf(const char*, ...);
+
+struct A {
+  int val;
+  A(int v) : val(v) {
+    printf("A(%d), this = %p\n", val, this);
+  }
+  ~A() {
+    printf("~A(%d), this = %p\n", val, this);
+  }
+  int getVal() const { return val; }
+};
+
+const A a(1);
+// CHECK: A(1), this = [[PTR:.+]]
+
+a.val
+// CHECK-NEXT: (const int) 1
+a.getVal()
+// CHECK-NEXT: (int) 1
+a.val
+// CHECK-NEXT: (const int) 1
+a.getVal()
+// CHECK-NEXT: (int) 1
+
+// CHECK-NEXT: ~A(1), this = [[PTR]]
+// CHECK-NOT: ~A
diff --git a/interpreter/cling/test/CodeUnloading/DeclShadowing.C b/interpreter/cling/test/CodeUnloading/DeclShadowing.C
index 4b7b54d6f4532..01b79739ddb89 100644
--- a/interpreter/cling/test/CodeUnloading/DeclShadowing.C
+++ b/interpreter/cling/test/CodeUnloading/DeclShadowing.C
@@ -6,14 +6,17 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// RUN: cat %s | %cling 2>&1 | FileCheck %s
+// RUN: cat %s | %cling 2>&1 | FileCheck --implicit-check-not error: %s
 #include "cling/Interpreter/Interpreter.h"
 #include "cling/Utils/AST.h"
 #include "clang/AST/Decl.h"
 
-#include 
+#if __cplusplus > 202002L
+#include 
+#endif
 #include 
 #include 
+#include 
 
 unsigned _i;
 struct _X {};
@@ -98,6 +101,18 @@ f(33)
 f(3.3f)
 //CHECK-NEXT: (int) 21930
 
+#if __cplusplus > 202002L
+template 
+concept IsIntegral = false;
+
+// Replace concept definition; no error is expected in `constrained_fn(10)` below
+template 
+concept IsIntegral = std::is_integral::value;
+
+void constrained_fn(IsIntegral auto x) {}
+void g() { constrained_fn(10); }
+#endif
+
 cling::runtime::gClingOpts->AllowRedefinition = 0;
 
 // ==== Check DeclContext
diff --git a/interpreter/cling/test/CodeUnloading/Macros.C b/interpreter/cling/test/CodeUnloading/Macros.C
index 250806e1e6eb5..a2e6428a01578 100644
--- a/interpreter/cling/test/CodeUnloading/Macros.C
+++ b/interpreter/cling/test/CodeUnloading/Macros.C
@@ -13,16 +13,8 @@
 "TEST"
 // CHECK: (const char [5]) "TEST"
 
-// Make sure one Transactin can handle redefinitions
+// Make sure one transaction can handle redefinitions
 #include "Macros.h"
-// expected-warning@Macros.h:3 {{'TEST' macro redefined}}
-// expected-note@Macros.h:2 {{previous definition is here}}
-// expected-warning@Macros.h:4 {{'TEST' macro redefined}}
-// expected-note@Macros.h:3 {{previous definition is here}}
-// expected-warning@Macros.h:5 {{'TEST' macro redefined}}
-// expected-note@Macros.h:4 {{previous definition is here}}
-// expected-warning@Macros.h:6 {{'TEST' macro redefined}}
-// expected-note@Macros.h:5 {{previous definition is here}}
 
 TEST
 // CHECK: (const char [7]) "TEST 4"
@@ -31,7 +23,7 @@ TEST
 .undo //include
 .undo // FIXME: REMOVE once print unloading is merged
 
-TEST // expected-error@2 {{use of undeclared identifier 'TEST'}}
+TEST // expected-error {{use of undeclared identifier 'TEST'}}
 
 #define TEST "DEFINED"
 #undef TEST
@@ -42,13 +34,11 @@ TEST
 .undo // define
 .undo // FIXME: REMOVE once print unloading is merged
 
-TEST // expected-error@2 {{use of undeclared identifier 'TEST'}}
+TEST // expected-error {{use of undeclared identifier 'TEST'}}
 
-// Make sure one Transactin can handle undef, redef
+// Make sure one transaction can handle undef, redef
 #define TESTB
 #include "Macros.h"
-// expected-warning@Macros.h:19 {{'TEST' macro redefined}}
-// expected-note@Macros.h:18 {{previous definition is here}}
 
 TEST // CHECK: (const char [7]) "TEST G"
 .q
diff --git a/interpreter/cling/test/CodeUnloading/Macros.h b/interpreter/cling/test/CodeUnloading/Macros.h
index fba02f740d26e..d96d0b9779c8d 100644
--- a/interpreter/cling/test/CodeUnloading/Macros.h
+++ b/interpreter/cling/test/CodeUnloading/Macros.h
@@ -4,6 +4,14 @@
   #define TEST "TEST 2"
   #define TEST "TEST 3"
   #define TEST "TEST 4"
+  // expected-warning@3 {{'TEST' macro redefined}}
+  // expected-note@2 {{previous definition is here}}
+  // expected-warning@4 {{'TEST' macro redefined}}
+  // expected-note@3 {{previous definition is here}}
+  // expected-warning@5 {{'TEST' macro redefined}}
+  // expected-note@4 {{previous definition is here}}
+  // expected-warning@6 {{'TEST' macro redefined}}
+  // expected-note@5 {{previous definition is here}}
 #else
   #define TEST "TEST A"
   #undef TEST
@@ -17,4 +25,6 @@
   #undef TEST
   #define TEST "TEST F"
   #define TEST "TEST G"
-#endif
\ No newline at end of file
+  // expected-warning@27 {{'TEST' macro redefined}}
+  // expected-note@26 {{previous definition is here}}
+#endif
diff --git a/interpreter/cling/test/CodeUnloading/PCH/VTables.C b/interpreter/cling/test/CodeUnloading/PCH/VTables.C
index d15264653d8cf..5386598dfd9ee 100644
--- a/interpreter/cling/test/CodeUnloading/PCH/VTables.C
+++ b/interpreter/cling/test/CodeUnloading/PCH/VTables.C
@@ -1,7 +1,7 @@
 // RUN: %mkdir "%T/Rel/Path" || true
 // RUN: %rm "CompGen.h.pch" && %rm "%T/Rel/Path/Relative.pch"
-// RUN: clang -x c++-header -fexceptions -fcxx-exceptions -std=c++14 -pthread %S/Inputs/CompGen.h -o CompGen.h.pch
-// RUN: clang -x c++-header -fexceptions -fcxx-exceptions -std=c++14 -pthread %S/Inputs/CompGen.h -o %T/Rel/Path/Relative.pch
+// RUN: clang -x c++-header -fexceptions -fcxx-exceptions -std=%std_cxx -pthread %S/Inputs/CompGen.h -o CompGen.h.pch
+// RUN: clang -x c++-header -fexceptions -fcxx-exceptions -std=%std_cxx -pthread %S/Inputs/CompGen.h -o %T/Rel/Path/Relative.pch
 // RUN: cat %s | %cling -I%p -Xclang -include-pch -Xclang CompGen.h.pch  2>&1 | FileCheck %s
 // RUN: cat %s | %cling -I%p -I%T/Rel/Path -include-pch Relative.pch 2>&1 | FileCheck %s
 
diff --git a/interpreter/cling/test/Driver/CommandHistory.C b/interpreter/cling/test/Driver/CommandHistory.C
new file mode 100644
index 0000000000000..aefda3ce02a41
--- /dev/null
+++ b/interpreter/cling/test/Driver/CommandHistory.C
@@ -0,0 +1,36 @@
+//------------------------------------------------------------------------------
+// CLING - the C++ LLVM-based InterpreterG :)
+//
+// This file is dual-licensed: you can choose to license it under the University
+// of Illinois Open Source License or the GNU Lesser General Public License. See
+// LICENSE.TXT for details.
+//------------------------------------------------------------------------------
+
+// clang-format off
+// RUN: %rm /tmp/__testing_cling_history
+// RUN: cat %s | env --unset=CLING_NOHISTORY CLING_HISTSIZE=8 CLING_HISTFILE="/tmp/__testing_cling_history" %cling - 2>&1
+// RUN: diff /tmp/__testing_cling_history "%S/Inputs/cling_history"
+// UNSUPPORTED: system-windows
+
+#include 
+
+int i = 8;
+
+template
+struct type_a {
+	const T t;
+	double d;
+
+/*
+		comment
+ * */
+
+	static const int i = 37;
+};
+
+// another comment
+
+using std::cout;
+
+std::cout << "test\n";
+
diff --git a/interpreter/cling/test/Driver/CurrentDirRm.C b/interpreter/cling/test/Driver/CurrentDirRm.C
index f66aed006702a..d8ab6779d8ac1 100644
--- a/interpreter/cling/test/Driver/CurrentDirRm.C
+++ b/interpreter/cling/test/Driver/CurrentDirRm.C
@@ -11,7 +11,7 @@
 // RUN: cd "%T/Remove"
 // RUN: %rmdir "%T/Remove"
 // RUN: %cling %s -Xclang -verify 2>&1 | FileCheck %s
-// REQUIRES: not_system-windows
+// UNSUPPORTED: system-windows
 
 extern "C" {
   int printf(const char*, ...);
diff --git a/interpreter/cling/test/Driver/Gnu.C b/interpreter/cling/test/Driver/Gnu.C
index 47c0c084a2155..28ff19a15c15f 100644
--- a/interpreter/cling/test/Driver/Gnu.C
+++ b/interpreter/cling/test/Driver/Gnu.C
@@ -10,7 +10,7 @@
 // RUN: cat %s | %cling -D__STRICT_ANSI__ -std=gnu++11 -Xclang -verify 2>&1 | FileCheck %s
 // RUN: cat %s | %cling -D__STRICT_ANSI__ -std=gnu++14 -Xclang -verify 2>&1 | FileCheck %s
 // RUN: cat %s | %cling -D__STRICT_ANSI__ -std=gnu++1z -Xclang -verify 2>&1 | FileCheck %s
-// REQUIRES: not_system-windows
+// UNSUPPORTED: system-windows
 
 #ifdef __cplusplus
 extern "C" int printf(const char*, ...);
diff --git a/interpreter/cling/test/Driver/Inputs/.cling.d/startup0.C b/interpreter/cling/test/Driver/Inputs/.cling.d/startup0.C
new file mode 100644
index 0000000000000..742aa08f4e92e
--- /dev/null
+++ b/interpreter/cling/test/Driver/Inputs/.cling.d/startup0.C
@@ -0,0 +1,10 @@
+#include 
+
+namespace io = std;
+
+int startup_magic_num{43210};
+
+void startup0() {
+  std::cout << "Startup file ran, magic # was " << startup_magic_num << '\n';
+  startup_magic_num += 2;
+}
diff --git a/interpreter/cling/test/Driver/Inputs/.cling.d/startup1.C b/interpreter/cling/test/Driver/Inputs/.cling.d/startup1.C
new file mode 100644
index 0000000000000..957ba91ea8fe8
--- /dev/null
+++ b/interpreter/cling/test/Driver/Inputs/.cling.d/startup1.C
@@ -0,0 +1,7 @@
+
+const char* startup_magic_str = "AaBbCc__51";
+
+void startup1() {
+  std::cout << "Startup file ran, magic # was " << startup_magic_num << '\n';
+  ++startup_magic_num;
+}
diff --git a/interpreter/cling/test/Driver/Inputs/cling_history b/interpreter/cling/test/Driver/Inputs/cling_history
new file mode 100644
index 0000000000000..eed01cab128cb
--- /dev/null
+++ b/interpreter/cling/test/Driver/Inputs/cling_history
@@ -0,0 +1,8 @@
+/*
+comment
+ * */
+static const int i = 37;
+};
+// another comment
+using std::cout;
+std::cout << "test\n";
diff --git a/interpreter/cling/test/Driver/StartupFile.C b/interpreter/cling/test/Driver/StartupFile.C
new file mode 100644
index 0000000000000..04479a2d8ebe0
--- /dev/null
+++ b/interpreter/cling/test/Driver/StartupFile.C
@@ -0,0 +1,21 @@
+//------------------------------------------------------------------------------
+// CLING - the C++ LLVM-based InterpreterG :)
+//
+// This file is dual-licensed: you can choose to license it under the University
+// of Illinois Open Source License or the GNU Lesser General Public License. See
+// LICENSE.TXT for details.
+//------------------------------------------------------------------------------
+
+// RUN: cat %s | env CLING_HOME="%S/Inputs" %cling %s 2>&1 | FileCheck %s
+// UNSUPPORTED: system-windows
+
+// CHECK: Startup file ran, magic # was 43210
+
+void StartupFile() {
+  io::cout << "The magic # is " << startup_magic_num << '\n';
+  // CHECK: The magic # is 43213
+  io::cout << "The magic string is " << startup_magic_str << '\n';
+  // CHECK: The magic string is AaBbCc__51
+}
+
+// expected-no-diagnostics
diff --git a/interpreter/cling/test/DynamicLibraryManager/cached_realpath.C b/interpreter/cling/test/DynamicLibraryManager/cached_realpath.C
index 301f9f88d607c..c4a6dbff8afd1 100644
--- a/interpreter/cling/test/DynamicLibraryManager/cached_realpath.C
+++ b/interpreter/cling/test/DynamicLibraryManager/cached_realpath.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// REQUIRES: not_system-windows
+// UNSUPPORTED: system-windows
 
 // RUN: %rm -fr %t-dir
 // RUN: %mkdir %t-dir
@@ -71,19 +71,20 @@
 #include "../lib/Interpreter/DynamicLibraryManagerSymbol.cpp"
 
 .rawInput 1
-void test_realpath(std::string path) {
+void test_realpath(const std::string &path) {
+  int err_s = 0, err_c = 0;
+
   // system realpath
-  errno = 0;
-  char system_resolved_path[4096];
-  system_resolved_path[0] = '\0';
-  realpath(path.c_str(), system_resolved_path);
-  int err_s = errno;
-  if (err_s !=0 ) system_resolved_path[0] = '\0';
+  char system_resolved_path[4096]{};
+  if (!realpath(path.c_str(), system_resolved_path)) {
+    system_resolved_path[0] = '\0';
+    err_s = errno;
+  }
 
   // cached_realpath
-  errno = 0;
   std::string cached_resolved_path = cached_realpath(path);
-  int err_c = errno;
+  if (cached_resolved_path.empty())
+    err_c = errno;
 
   if (err_s != err_c || std::string(system_resolved_path) != cached_resolved_path) {
     std::cout << "realpath: " << path.c_str() << "\n";
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_order1.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_order1.C
index f6d93c3244e1b..1c232128529a3 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_order1.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_order1.C
@@ -13,7 +13,7 @@
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_B.c -o%t-dir/rlib1/libcall_lib_B%shlibext
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_AA.c -o%t-dir/rlib2/libcall_lib_A%shlibext
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_BB.c -o%t-dir/rlib2/libcall_lib_B%shlibext
-// RUN: %clang %fPIC -shared -Wl,-rpath,%t-dir/rlib1 -DCLING_EXPORT=%dllexport %S/call_lib_L_AB.c -o%t-dir/lib/libcall_lib_L_AB%shlibext -L %t-dir/rlib1 -lcall_lib_A -lcall_lib_B
+// RUN: %clang %fPIC -shared -Wl,--enable-new-dtags -Wl,-rpath,%t-dir/rlib1 -DCLING_EXPORT=%dllexport %S/call_lib_L_AB.c -o%t-dir/lib/libcall_lib_L_AB%shlibext -L %t-dir/rlib1 -lcall_lib_A -lcall_lib_B
 // RUN: cat %s | LD_LIBRARY_PATH="%t-dir/lib:%t-dir/rlib2" %cling 2>&1 | FileCheck %s
 
 // Test: Lookup and load library Lib_L_AB that depends on two libraries Lib_A
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst.C
index 0cd6aeb587cf4..7821e85062081 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// UNSUPPORTED: macos
+// UNSUPPORTED: system-darwin
 // RUN: mkdir -p %t-dir/rlib
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/rlib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst1.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst1.C
index b0250874dd3e0..598571193570c 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst1.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst1.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// UNSUPPORTED: windows, linux
+// UNSUPPORTED: system-windows, system-linux
 // RUN: mkdir -p %t-dir/rlib
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/rlib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst2.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst2.C
index f305cc7f3a5b7..641c4eda19be8 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst2.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst2.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// UNSUPPORTED: windows, linux
+// UNSUPPORTED: system-windows, system-linux
 // RUN: mkdir -p %t-dir/rlib
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/rlib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst3.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst3.C
index 8e446a95e5777..20b73a61044ed 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst3.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst3.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// UNSUPPORTED: windows
+// UNSUPPORTED: system-windows
 // RUN: mkdir -p %t-dir/rlib
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/rlib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst4.C b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst4.C
index adc51c14d54ce..5a7d6a4c00b7c 100644
--- a/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst4.C
+++ b/interpreter/cling/test/DynamicLibraryManager/callable_lib_L_AB_subst4.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// UNSUPPORTED: windows
+// UNSUPPORTED: system-windows
 // RUN: mkdir -p %t-dir/rlib
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/rlib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/DynamicLibraryManager/pie.C b/interpreter/cling/test/DynamicLibraryManager/pie.C
index 92aac5e34ac85..b1b6e3f330593 100644
--- a/interpreter/cling/test/DynamicLibraryManager/pie.C
+++ b/interpreter/cling/test/DynamicLibraryManager/pie.C
@@ -6,7 +6,7 @@
 // LICENSE.TXT for details.
 //------------------------------------------------------------------------------
 
-// REQUIRES: not_system-windows
+// UNSUPPORTED: system-windows
 
 // RUN: mkdir -p %t-dir/lib
 // RUN: %clang -shared -DCLING_EXPORT=%dllexport %S/call_lib_A.c -o%t-dir/lib/libcall_lib_A%shlibext
diff --git a/interpreter/cling/test/Interfaces/evaluate.C b/interpreter/cling/test/Interfaces/evaluate.C
index cbec8ea80b9ad..02b92540333e3 100644
--- a/interpreter/cling/test/Interfaces/evaluate.C
+++ b/interpreter/cling/test/Interfaces/evaluate.C
@@ -141,7 +141,7 @@ namespace cling {
   }
 }
 void dumpTracerSVR(cling::Value& svr) {
-  ((Tracer*)svr.getAs())->dump("dump");
+  ((Tracer*)svr.castAs())->dump("dump");
 }
 .rawInput 0
 
diff --git a/interpreter/cling/test/MultipleInterpreters/MultipleInterpreters.C b/interpreter/cling/test/MultipleInterpreters/MultipleInterpreters.C
index 56b4c5958d94c..fe11eaf532f51 100644
--- a/interpreter/cling/test/MultipleInterpreters/MultipleInterpreters.C
+++ b/interpreter/cling/test/MultipleInterpreters/MultipleInterpreters.C
@@ -32,6 +32,10 @@ const char* argV[1] = {"cling"};
   cling::Interpreter ChildInterp(*gCling, 1, argV);
   ChildInterp.declare("void foo(int i){ printf(\"foo(int) = %d\\n\", i); }\n");
   ChildInterp.echo("foo()"); //CHECK: (int) 42
-  ChildInterp.echo("foo(1)"); //CHECK: foo(int) = 1
+  ChildInterp.execute("foo(1)"); //CHECK: foo(int) = 1
+
+  // The following should not crash, even if the child interpreter has a
+  // different ASTContext.VoidTy.
+  ChildInterp.echo("(void)1");
 }
 .q
diff --git a/interpreter/cling/test/Prompt/decls.C b/interpreter/cling/test/Prompt/decls.C
index 756a8e0507fdd..d1f76208040fc 100644
--- a/interpreter/cling/test/Prompt/decls.C
+++ b/interpreter/cling/test/Prompt/decls.C
@@ -8,6 +8,7 @@
 
 // RUN: cat %s | %cling -I%p | FileCheck %s
 #include 
+#include 
 
 struct S{int i;} ss;
 S s = {12 };
@@ -16,6 +17,44 @@ struct U{void f() const {};} uu;
 
 struct V{V(): v(12) {}; int v; } vv;
 
+struct typeA {
+  typeA(int i): num{i} {};
+  typeA();
+  ~typeA();
+
+  typeA& operator()(int k);
+  const typeA& operator[](int k) const;
+
+  operator int() const;
+
+  int num;
+};
+
+typeA::typeA() = default;
+::typeA::~typeA() {};
+::typeA& ::typeA::operator()(int k) { return *this; }
+const typeA& typeA::operator[](int k) const { return *this; }
+bool operator>=(const typeA &lhs, int t) { return lhs.num >= t; }
+bool operator<=(::typeA const &lhs, int t) { return lhs.num <= t; }
+bool operator<(typeA const&lhs, int t) { return lhs.num < t; }
+bool operator>(const typeA &lhs, int t) { return lhs.num > t; }
+::typeA operator+(const typeA &lhs, const ::typeA &rhs) {
+  return typeA{lhs.num + rhs.num};
+}
+::typeA operator "" _tA(unsigned long long int t) { return typeA{static_cast(t)}; }
+std::ostream& operator<<(std::ostream& os, const typeA& a) {return (os << a.num);}
+typeA::operator int() const { return num + 7; }
+
+std::cout << 76601_tA; // CHECK:76601
+6551_tA(99)[4].num // CHECK:6551
+typeA{-675} > 0 // CHECK:false
+99_tA >= 99 // CHECK:true
+::typeA(31) < 31 // CHECK:false
+(60_tA + 3_tA).num // CHECK:63
+static_cast(18_tA)  // CHECK:25
+
+::atoi("42") // CHECK:42
+
 int i = 12;
 float f = sin(12);
 int j = i;
@@ -25,4 +64,9 @@ printf("j=%d\n",j); // CHECK:j=12
 std::string str("abc");
 printf("str=%s\n",str.c_str()); // CHECK: str=abc
 
+[[nodiscard]] int f() { return 0; }
+void g() { f(); } // expected-warning@1 {{ignoring return value of function declared with 'nodiscard' attribute}}
+// -Wunused-result is filtered for code parsed via `Interpreter::EvaluateInternal()`
+f();
+
 .q
diff --git a/interpreter/cling/test/Utils/Transform.C b/interpreter/cling/test/Utils/Transform.C
index 456769680c414..0cd8fda5e1758 100644
--- a/interpreter/cling/test/Utils/Transform.C
+++ b/interpreter/cling/test/Utils/Transform.C
@@ -429,7 +429,7 @@ std::cout << Transform::GetPartiallyDesugaredType(Ctx, QT, transConfig).getAsStr
 if (const clang::RecordDecl *rdecl = llvm::dyn_cast_or_null(decl)) {
   clang::RecordDecl::field_iterator field_iter = rdecl->field_begin();
   // For some reason we can not call field_end:
-  // cling: root/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.cpp:1839: void checkArgMatches(llvm::Value*, unsigned int&, llvm::FunctionType*): Assertion `Elt->getType() == FTy->getParamType(ArgNo)' failed.
+  // cling: root/interpreter/llvm-project/clang/lib/CodeGen/CGCall.cpp:1839: void checkArgMatches(llvm::Value*, unsigned int&, llvm::FunctionType*): Assertion `Elt->getType() == FTy->getParamType(ArgNo)' failed.
   // so just 'guess' the size
   int i = 0;
   while( i < 2 )  {
@@ -475,7 +475,7 @@ if (const clang::RecordDecl *rdecl = llvm::dyn_cast_or_null(d
   std::cout << Transform::GetPartiallyDesugaredType(Ctx, QT, transConfig).getAsString().c_str() << std::endl;
   clang::RecordDecl::field_iterator field_iter = rdecl->field_begin();
   // For some reason we can not call field_end:
-  // cling: root/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.cpp:1839: void checkArgMatches(llvm::Value*, unsigned int&, llvm::FunctionType*): Assertion `Elt->getType() == FTy->getParamType(ArgNo)' failed.
+  // cling: root/interpreter/llvm-project/clang/lib/CodeGen/CGCall.cpp:1839: void checkArgMatches(llvm::Value*, unsigned int&, llvm::FunctionType*): Assertion `Elt->getType() == FTy->getParamType(ArgNo)' failed.
   // so just 'guess' the size
   int i = 0;
   while( i < 2 )  {
diff --git a/interpreter/cling/test/lit.cfg b/interpreter/cling/test/lit.cfg
index 8eb82df4aa652..d1b480bc27a0a 100644
--- a/interpreter/cling/test/lit.cfg
+++ b/interpreter/cling/test/lit.cfg
@@ -69,18 +69,6 @@ llvm_config.with_system_environment(
 config.substitutions.append(('%PATH%', config.environment['PATH']))
 
 
-# For each occurrence of a clang tool name, replace it with the full path to
-# the build directory holding that tool.  We explicitly specify the directories
-# to search to ensure that we get the tools just built and not some random
-# tools that might happen to be in the user's PATH.
-tool_dirs = [config.llvm_tools_dir]
-
-tools = [
-    'c-index-test', 'clang-diff', 'clang-format', 'clang-tblgen', 'opt'
-]
-
-llvm_config.add_tool_substitutions(tools, tool_dirs)
-
 # We want to invoke the system clang. Or not?
 config.substitutions = [x for x in config.substitutions if x[0] != ' clang ']
 
@@ -88,6 +76,8 @@ config.substitutions.append(('%cling_obj_root', config.cling_obj_root))
 incDir = os.path.join(config.llvm_obj_root, 'tools', 'clang', 'include')
 config.substitutions.append( ('%cling', config.llvm_tools_dir + '/cling --nologo -I%s' % fixupPath(incDir)) )
 
+config.substitutions.append(('%std_cxx', 'c++' + config.cxx_standard))
+
 if platform.system() in ['Windows']:
   config.substitutions.append(('%dllexport', '"__declspec(dllexport)"'))
   config.substitutions.append(('%fPIC', ''))
@@ -119,10 +109,6 @@ config.substitutions.append(('%shlibext', config.shlibext))
 if platform.system() not in ['Windows'] or lit_config.getBashPath() != '':
     config.available_features.add('shell')
 
-# Filter-out tests not supposed to run on Windows
-if platform.system() not in ['Windows']:
-    config.available_features.add('not_system-windows')
-
 # ROOT adds features that "heal" some of cling's tests; need to detect
 # vanilla vs cling-as-part-of-ROOT. The latter has no `lib/UserInterface/textinput/`:
 if os.path.isdir(os.path.join(config.cling_src_root, 'lib', 'UserInterface', 'textinput')):
diff --git a/interpreter/cling/test/lit.site.cfg.in b/interpreter/cling/test/lit.site.cfg.in
index 2f619d96ac112..1f89db0f1f18d 100644
--- a/interpreter/cling/test/lit.site.cfg.in
+++ b/interpreter/cling/test/lit.site.cfg.in
@@ -8,6 +8,7 @@ config.cling_obj_root = "@CLING_BINARY_DIR@"
 config.target_triple = "@TARGET_TRIPLE@"
 config.host_triple = "@TARGET_TRIPLE@"
 config.shlibext = "@TARGET_SHLIBEXT@"
+config.cxx_standard = "@CMAKE_CXX_STANDARD@"
 
 # Support substitution of the tools and libs dirs with user parameters. This is
 # used when we can't determine the tool dir at configuration time.
diff --git a/interpreter/cling/tools/demo/cling-demo.cpp b/interpreter/cling/tools/demo/cling-demo.cpp
index 4ca2a865609b4..28764e3e9104e 100644
--- a/interpreter/cling/tools/demo/cling-demo.cpp
+++ b/interpreter/cling/tools/demo/cling-demo.cpp
@@ -31,13 +31,13 @@ void useHeader(cling::Interpreter& interp) {
 
   cling::Value res; // Will hold the result of the expression evaluation.
   interp.process("aGlobal;", &res);
-  std::cout << "aGlobal is " << res.getAs() << '\n';
+  std::cout << "aGlobal is " << res.castAs() << '\n';
   interp.process("getAnotherGlobal();", &res);
-  std::cout << "getAnotherGlobal() returned " << res.getAs() << '\n';
+  std::cout << "getAnotherGlobal() returned " << res.getFloat() << '\n';
 
   setAnotherGlobal(1.); // We modify the compiled value,
   interp.process("getAnotherGlobal();", &res); // does the interpreter see it?
-  std::cout << "getAnotherGlobal() returned " << res.getAs() << '\n';
+  std::cout << "getAnotherGlobal() returned " << res.getFloat() << '\n';
 
   // We modify using the interpreter, now the binary sees the new value.
   interp.process("setAnotherGlobal(7.777); getAnotherGlobal();");
diff --git a/interpreter/cling/tools/driver/CMakeLists.txt b/interpreter/cling/tools/driver/CMakeLists.txt
index 77d6a2870df0d..d107dd7d022fb 100644
--- a/interpreter/cling/tools/driver/CMakeLists.txt
+++ b/interpreter/cling/tools/driver/CMakeLists.txt
@@ -9,9 +9,9 @@
 # Keep symbols for JIT resolution
 set(LLVM_NO_DEAD_STRIP 1)
 
+set(LLVM_LINK_COMPONENTS Support)
 if(BUILD_SHARED_LIBS)
   set(LIBS
-    LLVMSupport
 
     clangFrontendTool
 
@@ -25,8 +25,6 @@ if(BUILD_SHARED_LIBS)
   )
 else()
   set(LIBS
-    LLVMSupport
-
     clangASTMatchers
     clangFrontendTool
 
diff --git a/interpreter/cling/tools/driver/cling.cpp b/interpreter/cling/tools/driver/cling.cpp
index 15089dfea0156..1c7ae3800d8f6 100644
--- a/interpreter/cling/tools/driver/cling.cpp
+++ b/interpreter/cling/tools/driver/cling.cpp
@@ -15,14 +15,17 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/FrontendTool/Utils.h"
 
-#include "llvm/Support/Signals.h"
-#include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/Signals.h"
 
-#include 
+#include 
 #include 
-#include 
+#include 
 #include 
+#include 
 
 #if defined(WIN32) && defined(_MSC_VER)
 #include 
@@ -51,6 +54,58 @@ static int checkDiagErrors(clang::CompilerInstance* CI, unsigned* OutErrs = 0) {
   return Errs ? EXIT_FAILURE : EXIT_SUCCESS;
 }
 
+static llvm::SmallString<512> getConfigDirPath() {
+  llvm::SmallString<512> DirPath{
+      std::getenv("CLING_HOME")}; // nullptr is also fine
+
+  if (!DirPath.empty()) {
+    return DirPath;
+  }
+
+  if (llvm::sys::path::user_config_directory(DirPath)) {
+    llvm::sys::path::append(DirPath, "cling");
+    return DirPath;
+  }
+
+  if (llvm::sys::path::home_directory(DirPath)) {
+    return DirPath;
+  }
+
+  return {};
+}
+
+static void runStartupFiles(cling::UserInterface& Ui) {
+  llvm::SmallString<512> StartupFilesDir{getConfigDirPath()};
+
+  if (StartupFilesDir.empty()) {
+    return;
+  }
+
+  llvm::sys::path::append(StartupFilesDir, ".cling.d");
+
+  std::vector FilePaths;
+  std::error_code EC;
+
+  for (llvm::sys::fs::directory_iterator DirIt(StartupFilesDir, EC), DirEnd;
+       DirIt != DirEnd && !EC; DirIt.increment(EC)) {
+    if (DirIt->type() == llvm::sys::fs::file_type::regular_file &&
+        llvm::sys::path::extension(DirIt->path()) == ".C") {
+      FilePaths.emplace_back(DirIt->path());
+    }
+  }
+
+  std::sort(FilePaths.begin(), FilePaths.end());
+
+  for (const auto& File : FilePaths) {
+    auto Result{cling::Interpreter::CompilationResult::kSuccess};
+
+    Ui.getMetaProcessor()->process(".x " + File, Result, nullptr);
+
+    if (Result != cling::Interpreter::CompilationResult::kSuccess) {
+      std::cerr << "Error running startup file " << File << '\n';
+    }
+  }
+}
 
 int main( int argc, char **argv ) {
 
@@ -106,6 +161,9 @@ int main( int argc, char **argv ) {
     Interp.loadFile(Lib);
 
   cling::UserInterface Ui(Interp);
+
+  runStartupFiles(Ui);
+
   // If we are not interactive we're supposed to parse files
   if (!Opts.IsInteractive()) {
     for (const std::string &Input : Opts.Inputs) {
diff --git a/interpreter/cling/tools/libcling/CMakeLists.txt b/interpreter/cling/tools/libcling/CMakeLists.txt
index 143d3bdb3e99a..2a2b15e029241 100644
--- a/interpreter/cling/tools/libcling/CMakeLists.txt
+++ b/interpreter/cling/tools/libcling/CMakeLists.txt
@@ -32,6 +32,7 @@ set( LLVM_LINK_COMPONENTS
   coverage
   executionengine
   ipo
+  jitlink
   mc
   object
   option
diff --git a/interpreter/cling/tools/packaging/cpt.py b/interpreter/cling/tools/packaging/cpt.py
index b5105e1844910..e6ee249b92c07 100755
--- a/interpreter/cling/tools/packaging/cpt.py
+++ b/interpreter/cling/tools/packaging/cpt.py
@@ -799,12 +799,10 @@ def setup_tests():
     exec_subprocess_call("cmake {0}".format(LLVM_OBJ_ROOT), CLING_SRC_DIR)
     exec_subprocess_call("cmake --build . --target FileCheck -- -j{0}".format(multiprocessing.cpu_count()), LLVM_OBJ_ROOT)
     if not os.path.exists(os.path.join(CLING_SRC_DIR, "..", "clang", "test")):
-        llvm_dir = exec_subprocess_check_output("llvm-config --src-root", ".").strip()
-        if llvm_dir == "":
-            if tar_required:
-                llvm_dir = copy.copy(srcdir)
-            else:
-                llvm_dir = os.path.join("/usr", "lib", "llvm-" + llvm_vers, "build")
+        if tar_required:
+            llvm_dir = copy.copy(srcdir)
+        else:
+            llvm_dir = os.path.join("/usr", "lib", "llvm-" + llvm_vers, "build")
         subprocess.Popen(
             ["sudo mkdir {0}/utils/".format(llvm_dir)],
             cwd=os.path.join(CLING_SRC_DIR, "tools"),
diff --git a/interpreter/cling/tools/plugins/clad/CMakeLists.txt b/interpreter/cling/tools/plugins/clad/CMakeLists.txt
index fb4a3ae28fe01..ec0402183472e 100644
--- a/interpreter/cling/tools/plugins/clad/CMakeLists.txt
+++ b/interpreter/cling/tools/plugins/clad/CMakeLists.txt
@@ -43,9 +43,9 @@ if (Clang_DIR)
   list(APPEND _clad_extra_cmake_args -DClang_DIR=${Clang_DIR} -DClang_CONFIG_EXTRA_PATH_HINTS=${Clang_Config_ExtraPathHints})
 endif(Clang_DIR)
 
-if (LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN)
-  list(APPEND _clad_extra_cmake_args -DLLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN=${LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN})
-endif(LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN)
+if (LLVM_FORCE_USE_OLD_TOOLCHAIN)
+  list(APPEND _clad_extra_cmake_args -DLLVM_FORCE_USE_OLD_TOOLCHAIN=${LLVM_FORCE_USE_OLD_TOOLCHAIN})
+endif(LLVM_FORCE_USE_OLD_TOOLCHAIN)
 
 if (CLING_INCLUDE_TESTS)
   list(APPEND _clad_extra_cmake_args -DLLVM_EXTERNAL_LIT=${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
@@ -63,11 +63,20 @@ set(_clad_cmake_logging_settings
 
 list(APPEND _clad_cmake_logging_settings LOG_OUTPUT_ON_FAILURE ON)
 
+#list(APPEND _clad_patches_list "patch1.patch" "patch2.patch")
+#set(_clad_patch_command
+#      ${CMAKE_COMMAND} -E copy_directory
+#      ${CMAKE_SOURCE_DIR}/interpreter/cling/tools/plugins/clad/patches 
+#      && git checkout 
+#      && git apply --ignore-space-change --ignore-whitespace ${_clad_patches_list}
+#      )
+
 ExternalProject_Add(
   clad
   GIT_REPOSITORY https://github.com/vgvassilev/clad.git
-  GIT_TAG v1.0
+  GIT_TAG v1.2
   UPDATE_COMMAND ""
+  PATCH_COMMAND ${_clad_patch_command}
   CMAKE_ARGS -G ${CMAKE_GENERATOR}
              -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
              -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
diff --git a/interpreter/cling/tools/plugins/example/CMakeLists.txt b/interpreter/cling/tools/plugins/example/CMakeLists.txt
index 17e487466eede..669682f9f3dd2 100644
--- a/interpreter/cling/tools/plugins/example/CMakeLists.txt
+++ b/interpreter/cling/tools/plugins/example/CMakeLists.txt
@@ -14,7 +14,7 @@ endif()
 
 set_target_properties(clingDemoPlugin PROPERTIES  LIBRARY_OUTPUT_DIRECTORY ".")
 if(APPLE)
-  target_link_libraries(clingDemoPlugin PUBLIC -Wl,-bind_at_load -Wl,-flat_namespace -Wl,-undefined -Wl,suppress)
+  target_link_libraries(clingDemoPlugin PUBLIC -Wl,-w -Wl,-bind_at_load -Wl,-undefined,dynamic_lookup)
 elseif(NOT MSVC)
   target_link_libraries(clingDemoPlugin PUBLIC -Wl,--unresolved-symbols=ignore-in-object-files)
 endif()
diff --git a/interpreter/llvm/src/tools/clang/.clang-format b/interpreter/llvm-project/.clang-format
similarity index 100%
rename from interpreter/llvm/src/tools/clang/.clang-format
rename to interpreter/llvm-project/.clang-format
diff --git a/interpreter/llvm/src/.clang-tidy b/interpreter/llvm-project/.clang-tidy
similarity index 78%
rename from interpreter/llvm/src/.clang-tidy
rename to interpreter/llvm-project/.clang-tidy
index 3f407e0160e69..3f2f2c054eb3d 100644
--- a/interpreter/llvm/src/.clang-tidy
+++ b/interpreter/llvm-project/.clang-tidy
@@ -1,4 +1,4 @@
-Checks: '-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,-misc-non-private-member-variables-in-classes,readability-identifier-naming'
+Checks: '-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,-misc-non-private-member-variables-in-classes,-misc-no-recursion,readability-identifier-naming'
 CheckOptions:
   - key:             readability-identifier-naming.ClassCase
     value:           CamelCase
@@ -14,4 +14,6 @@ CheckOptions:
     value:           CamelCase
   - key:             readability-identifier-naming.VariableCase
     value:           CamelCase
+  - key:             readability-identifier-naming.IgnoreMainLikeFunctions
+    value:           1
 
diff --git a/interpreter/llvm-project/.gitignore b/interpreter/llvm-project/.gitignore
new file mode 100644
index 0000000000000..b33fbbf932379
--- /dev/null
+++ b/interpreter/llvm-project/.gitignore
@@ -0,0 +1,70 @@
+#==============================================================================#
+# This file specifies intentionally untracked files that git should ignore.
+# See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html
+#
+# This file is intentionally different from the output of `git svn show-ignore`,
+# as most of those are useless.
+#==============================================================================#
+
+#==============================================================================#
+# File extensions to be ignored anywhere in the tree.
+#==============================================================================#
+# Temp files created by most text editors.
+*~
+# Merge files created by git.
+*.orig
+# Byte compiled python modules.
+*.pyc
+# vim swap files
+.*.sw?
+.sw?
+#OS X specific files.
+.DS_store
+
+# Ignore the user specified CMake presets in subproject directories.
+/*/CMakeUserPresets.json
+
+# Nested build directory
+/build*
+
+#==============================================================================#
+# Explicit files to ignore (only matches one).
+#==============================================================================#
+# Various tag programs
+/tags
+/TAGS
+/GPATH
+/GRTAGS
+/GSYMS
+/GTAGS
+/ID
+.gitusers
+autom4te.cache
+cscope.files
+cscope.out
+autoconf/aclocal.m4
+autoconf/autom4te.cache
+/compile_commands.json
+# Visual Studio built-in CMake configuration
+/CMakeSettings.json
+# CLion project configuration
+/.idea
+
+#==============================================================================#
+# Directories to ignore (do not add trailing '/'s, they skip symlinks).
+#==============================================================================#
+# VS2017 and VSCode config files.
+.vscode
+.vs
+# pythonenv for github Codespaces
+pythonenv*
+# clangd index. (".clangd" is a config file now, thus trailing slash)
+.clangd/
+.cache
+# static analyzer regression testing project files
+/clang/utils/analyzer/projects/*/CachedSource
+/clang/utils/analyzer/projects/*/PatchedSource
+/clang/utils/analyzer/projects/*/ScanBuildResults
+/clang/utils/analyzer/projects/*/RefScanBuildResults
+# automodapi puts generated documentation files here.
+/lldb/docs/python_api/
diff --git a/interpreter/llvm-project/clang/.clang-format b/interpreter/llvm-project/clang/.clang-format
new file mode 100644
index 0000000000000..9b3aa8b7213b2
--- /dev/null
+++ b/interpreter/llvm-project/clang/.clang-format
@@ -0,0 +1 @@
+BasedOnStyle: LLVM
diff --git a/interpreter/llvm/src/tools/clang/.clang-tidy b/interpreter/llvm-project/clang/.clang-tidy
similarity index 100%
rename from interpreter/llvm/src/tools/clang/.clang-tidy
rename to interpreter/llvm-project/clang/.clang-tidy
diff --git a/interpreter/llvm/src/tools/clang/.gitignore b/interpreter/llvm-project/clang/.gitignore
similarity index 100%
rename from interpreter/llvm/src/tools/clang/.gitignore
rename to interpreter/llvm-project/clang/.gitignore
diff --git a/interpreter/llvm/src/tools/clang/CMakeLists.txt b/interpreter/llvm-project/clang/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/CMakeLists.txt
rename to interpreter/llvm-project/clang/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/CODE_OWNERS.TXT b/interpreter/llvm-project/clang/CODE_OWNERS.TXT
similarity index 100%
rename from interpreter/llvm/src/tools/clang/CODE_OWNERS.TXT
rename to interpreter/llvm-project/clang/CODE_OWNERS.TXT
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/Cocoa_h.m b/interpreter/llvm-project/clang/INPUTS/Cocoa_h.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/Cocoa_h.m
rename to interpreter/llvm-project/clang/INPUTS/Cocoa_h.m
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/all-std-headers.cpp b/interpreter/llvm-project/clang/INPUTS/all-std-headers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/all-std-headers.cpp
rename to interpreter/llvm-project/clang/INPUTS/all-std-headers.cpp
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/c99-intconst-1.c b/interpreter/llvm-project/clang/INPUTS/c99-intconst-1.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/c99-intconst-1.c
rename to interpreter/llvm-project/clang/INPUTS/c99-intconst-1.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/carbon_h.c b/interpreter/llvm-project/clang/INPUTS/carbon_h.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/carbon_h.c
rename to interpreter/llvm-project/clang/INPUTS/carbon_h.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-big-switch.c b/interpreter/llvm-project/clang/INPUTS/cfg-big-switch.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-big-switch.c
rename to interpreter/llvm-project/clang/INPUTS/cfg-big-switch.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain1.c b/interpreter/llvm-project/clang/INPUTS/cfg-long-chain1.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain1.c
rename to interpreter/llvm-project/clang/INPUTS/cfg-long-chain1.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain2.c b/interpreter/llvm-project/clang/INPUTS/cfg-long-chain2.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain2.c
rename to interpreter/llvm-project/clang/INPUTS/cfg-long-chain2.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain3.c b/interpreter/llvm-project/clang/INPUTS/cfg-long-chain3.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-long-chain3.c
rename to interpreter/llvm-project/clang/INPUTS/cfg-long-chain3.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-nested-switches.c b/interpreter/llvm-project/clang/INPUTS/cfg-nested-switches.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-nested-switches.c
rename to interpreter/llvm-project/clang/INPUTS/cfg-nested-switches.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/cfg-nested-var-scopes.cpp b/interpreter/llvm-project/clang/INPUTS/cfg-nested-var-scopes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/cfg-nested-var-scopes.cpp
rename to interpreter/llvm-project/clang/INPUTS/cfg-nested-var-scopes.cpp
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/iostream.cc b/interpreter/llvm-project/clang/INPUTS/iostream.cc
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/iostream.cc
rename to interpreter/llvm-project/clang/INPUTS/iostream.cc
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/macro_pounder_fn.c b/interpreter/llvm-project/clang/INPUTS/macro_pounder_fn.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/macro_pounder_fn.c
rename to interpreter/llvm-project/clang/INPUTS/macro_pounder_fn.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/macro_pounder_obj.c b/interpreter/llvm-project/clang/INPUTS/macro_pounder_obj.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/macro_pounder_obj.c
rename to interpreter/llvm-project/clang/INPUTS/macro_pounder_obj.c
diff --git a/interpreter/llvm/src/tools/clang/INPUTS/stpcpy-test.c b/interpreter/llvm-project/clang/INPUTS/stpcpy-test.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INPUTS/stpcpy-test.c
rename to interpreter/llvm-project/clang/INPUTS/stpcpy-test.c
diff --git a/interpreter/llvm/src/tools/clang/INSTALL.txt b/interpreter/llvm-project/clang/INSTALL.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/INSTALL.txt
rename to interpreter/llvm-project/clang/INSTALL.txt
diff --git a/interpreter/llvm/src/tools/clang/LICENSE.TXT b/interpreter/llvm-project/clang/LICENSE.TXT
similarity index 100%
rename from interpreter/llvm/src/tools/clang/LICENSE.TXT
rename to interpreter/llvm-project/clang/LICENSE.TXT
diff --git a/interpreter/llvm/src/tools/clang/ModuleInfo.txt b/interpreter/llvm-project/clang/ModuleInfo.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/ModuleInfo.txt
rename to interpreter/llvm-project/clang/ModuleInfo.txt
diff --git a/interpreter/llvm/src/tools/clang/NOTES.txt b/interpreter/llvm-project/clang/NOTES.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/NOTES.txt
rename to interpreter/llvm-project/clang/NOTES.txt
diff --git a/interpreter/llvm/src/tools/clang/README.txt b/interpreter/llvm-project/clang/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/README.txt
rename to interpreter/llvm-project/clang/README.txt
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/3-stage-base.cmake b/interpreter/llvm-project/clang/cmake/caches/3-stage-base.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/3-stage-base.cmake
rename to interpreter/llvm-project/clang/cmake/caches/3-stage-base.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/3-stage.cmake b/interpreter/llvm-project/clang/cmake/caches/3-stage.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/3-stage.cmake
rename to interpreter/llvm-project/clang/cmake/caches/3-stage.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Android-stage2.cmake b/interpreter/llvm-project/clang/cmake/caches/Android-stage2.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Android-stage2.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Android-stage2.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Android.cmake b/interpreter/llvm-project/clang/cmake/caches/Android.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Android.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Android.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage1.cmake b/interpreter/llvm-project/clang/cmake/caches/Apple-stage1.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage1.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Apple-stage1.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage2-ThinLTO.cmake b/interpreter/llvm-project/clang/cmake/caches/Apple-stage2-ThinLTO.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage2-ThinLTO.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Apple-stage2-ThinLTO.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage2.cmake b/interpreter/llvm-project/clang/cmake/caches/Apple-stage2.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Apple-stage2.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Apple-stage2.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/BaremetalARM.cmake b/interpreter/llvm-project/clang/cmake/caches/BaremetalARM.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/BaremetalARM.cmake
rename to interpreter/llvm-project/clang/cmake/caches/BaremetalARM.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/CrossWinToARMLinux.cmake b/interpreter/llvm-project/clang/cmake/caches/CrossWinToARMLinux.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/CrossWinToARMLinux.cmake
rename to interpreter/llvm-project/clang/cmake/caches/CrossWinToARMLinux.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/DistributionExample-stage2.cmake b/interpreter/llvm-project/clang/cmake/caches/DistributionExample-stage2.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/DistributionExample-stage2.cmake
rename to interpreter/llvm-project/clang/cmake/caches/DistributionExample-stage2.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/DistributionExample.cmake b/interpreter/llvm-project/clang/cmake/caches/DistributionExample.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/DistributionExample.cmake
rename to interpreter/llvm-project/clang/cmake/caches/DistributionExample.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Fuchsia-stage2.cmake b/interpreter/llvm-project/clang/cmake/caches/Fuchsia-stage2.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Fuchsia-stage2.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Fuchsia-stage2.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/Fuchsia.cmake b/interpreter/llvm-project/clang/cmake/caches/Fuchsia.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/Fuchsia.cmake
rename to interpreter/llvm-project/clang/cmake/caches/Fuchsia.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/MultiDistributionExample.cmake b/interpreter/llvm-project/clang/cmake/caches/MultiDistributionExample.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/MultiDistributionExample.cmake
rename to interpreter/llvm-project/clang/cmake/caches/MultiDistributionExample.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/PGO-stage2-instrumented.cmake b/interpreter/llvm-project/clang/cmake/caches/PGO-stage2-instrumented.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/PGO-stage2-instrumented.cmake
rename to interpreter/llvm-project/clang/cmake/caches/PGO-stage2-instrumented.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/PGO-stage2.cmake b/interpreter/llvm-project/clang/cmake/caches/PGO-stage2.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/PGO-stage2.cmake
rename to interpreter/llvm-project/clang/cmake/caches/PGO-stage2.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/PGO.cmake b/interpreter/llvm-project/clang/cmake/caches/PGO.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/PGO.cmake
rename to interpreter/llvm-project/clang/cmake/caches/PGO.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/caches/README.txt b/interpreter/llvm-project/clang/cmake/caches/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/caches/README.txt
rename to interpreter/llvm-project/clang/cmake/caches/README.txt
diff --git a/interpreter/llvm/src/tools/clang/cmake/modules/AddClang.cmake b/interpreter/llvm-project/clang/cmake/modules/AddClang.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/modules/AddClang.cmake
rename to interpreter/llvm-project/clang/cmake/modules/AddClang.cmake
diff --git a/interpreter/llvm/src/tools/clang/cmake/modules/CMakeLists.txt b/interpreter/llvm-project/clang/cmake/modules/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/modules/CMakeLists.txt
rename to interpreter/llvm-project/clang/cmake/modules/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/cmake/modules/ClangConfig.cmake.in b/interpreter/llvm-project/clang/cmake/modules/ClangConfig.cmake.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/modules/ClangConfig.cmake.in
rename to interpreter/llvm-project/clang/cmake/modules/ClangConfig.cmake.in
diff --git a/interpreter/llvm/src/tools/clang/cmake/modules/ProtobufMutator.cmake b/interpreter/llvm-project/clang/cmake/modules/ProtobufMutator.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/cmake/modules/ProtobufMutator.cmake
rename to interpreter/llvm-project/clang/cmake/modules/ProtobufMutator.cmake
diff --git a/interpreter/llvm/src/tools/clang/docs/APINotes.rst b/interpreter/llvm-project/clang/docs/APINotes.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/APINotes.rst
rename to interpreter/llvm-project/clang/docs/APINotes.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/AddressSanitizer.rst b/interpreter/llvm-project/clang/docs/AddressSanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/AddressSanitizer.rst
rename to interpreter/llvm-project/clang/docs/AddressSanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/AutomaticReferenceCounting.rst b/interpreter/llvm-project/clang/docs/AutomaticReferenceCounting.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/AutomaticReferenceCounting.rst
rename to interpreter/llvm-project/clang/docs/AutomaticReferenceCounting.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Block-ABI-Apple.rst b/interpreter/llvm-project/clang/docs/Block-ABI-Apple.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Block-ABI-Apple.rst
rename to interpreter/llvm-project/clang/docs/Block-ABI-Apple.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Block-ABI-Apple.txt b/interpreter/llvm-project/clang/docs/Block-ABI-Apple.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Block-ABI-Apple.txt
rename to interpreter/llvm-project/clang/docs/Block-ABI-Apple.txt
diff --git a/interpreter/llvm/src/tools/clang/docs/BlockLanguageSpec.rst b/interpreter/llvm-project/clang/docs/BlockLanguageSpec.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/BlockLanguageSpec.rst
rename to interpreter/llvm-project/clang/docs/BlockLanguageSpec.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/CMakeLists.txt b/interpreter/llvm-project/clang/docs/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/CMakeLists.txt
rename to interpreter/llvm-project/clang/docs/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangCheck.rst b/interpreter/llvm-project/clang/docs/ClangCheck.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangCheck.rst
rename to interpreter/llvm-project/clang/docs/ClangCheck.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangCommandLineReference.rst b/interpreter/llvm-project/clang/docs/ClangCommandLineReference.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangCommandLineReference.rst
rename to interpreter/llvm-project/clang/docs/ClangCommandLineReference.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangFormat.rst b/interpreter/llvm-project/clang/docs/ClangFormat.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangFormat.rst
rename to interpreter/llvm-project/clang/docs/ClangFormat.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangFormatStyleOptions.rst b/interpreter/llvm-project/clang/docs/ClangFormatStyleOptions.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangFormatStyleOptions.rst
rename to interpreter/llvm-project/clang/docs/ClangFormatStyleOptions.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangFormattedStatus.rst b/interpreter/llvm-project/clang/docs/ClangFormattedStatus.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangFormattedStatus.rst
rename to interpreter/llvm-project/clang/docs/ClangFormattedStatus.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangOffloadBundler.rst b/interpreter/llvm-project/clang/docs/ClangOffloadBundler.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangOffloadBundler.rst
rename to interpreter/llvm-project/clang/docs/ClangOffloadBundler.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangPlugins.rst b/interpreter/llvm-project/clang/docs/ClangPlugins.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangPlugins.rst
rename to interpreter/llvm-project/clang/docs/ClangPlugins.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangStaticAnalyzer.rst b/interpreter/llvm-project/clang/docs/ClangStaticAnalyzer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangStaticAnalyzer.rst
rename to interpreter/llvm-project/clang/docs/ClangStaticAnalyzer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ClangTools.rst b/interpreter/llvm-project/clang/docs/ClangTools.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ClangTools.rst
rename to interpreter/llvm-project/clang/docs/ClangTools.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/CommandGuide/clang.rst b/interpreter/llvm-project/clang/docs/CommandGuide/clang.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/CommandGuide/clang.rst
rename to interpreter/llvm-project/clang/docs/CommandGuide/clang.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/CommandGuide/diagtool.rst b/interpreter/llvm-project/clang/docs/CommandGuide/diagtool.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/CommandGuide/diagtool.rst
rename to interpreter/llvm-project/clang/docs/CommandGuide/diagtool.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/CommandGuide/index.rst b/interpreter/llvm-project/clang/docs/CommandGuide/index.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/CommandGuide/index.rst
rename to interpreter/llvm-project/clang/docs/CommandGuide/index.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ConstantInterpreter.rst b/interpreter/llvm-project/clang/docs/ConstantInterpreter.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ConstantInterpreter.rst
rename to interpreter/llvm-project/clang/docs/ConstantInterpreter.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ControlFlowIntegrity.rst b/interpreter/llvm-project/clang/docs/ControlFlowIntegrity.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ControlFlowIntegrity.rst
rename to interpreter/llvm-project/clang/docs/ControlFlowIntegrity.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ControlFlowIntegrityDesign.rst b/interpreter/llvm-project/clang/docs/ControlFlowIntegrityDesign.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ControlFlowIntegrityDesign.rst
rename to interpreter/llvm-project/clang/docs/ControlFlowIntegrityDesign.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/CrossCompilation.rst b/interpreter/llvm-project/clang/docs/CrossCompilation.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/CrossCompilation.rst
rename to interpreter/llvm-project/clang/docs/CrossCompilation.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/DataFlowSanitizer.rst b/interpreter/llvm-project/clang/docs/DataFlowSanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/DataFlowSanitizer.rst
rename to interpreter/llvm-project/clang/docs/DataFlowSanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/DataFlowSanitizerDesign.rst b/interpreter/llvm-project/clang/docs/DataFlowSanitizerDesign.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/DataFlowSanitizerDesign.rst
rename to interpreter/llvm-project/clang/docs/DataFlowSanitizerDesign.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/DriverArchitecture.png b/interpreter/llvm-project/clang/docs/DriverArchitecture.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/DriverArchitecture.png
rename to interpreter/llvm-project/clang/docs/DriverArchitecture.png
diff --git a/interpreter/llvm/src/tools/clang/docs/DriverInternals.rst b/interpreter/llvm-project/clang/docs/DriverInternals.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/DriverInternals.rst
rename to interpreter/llvm-project/clang/docs/DriverInternals.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ExternalClangExamples.rst b/interpreter/llvm-project/clang/docs/ExternalClangExamples.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ExternalClangExamples.rst
rename to interpreter/llvm-project/clang/docs/ExternalClangExamples.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/FAQ.rst b/interpreter/llvm-project/clang/docs/FAQ.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/FAQ.rst
rename to interpreter/llvm-project/clang/docs/FAQ.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/HardwareAssistedAddressSanitizerDesign.rst b/interpreter/llvm-project/clang/docs/HardwareAssistedAddressSanitizerDesign.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/HardwareAssistedAddressSanitizerDesign.rst
rename to interpreter/llvm-project/clang/docs/HardwareAssistedAddressSanitizerDesign.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/HowToSetupToolingForLLVM.rst b/interpreter/llvm-project/clang/docs/HowToSetupToolingForLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/HowToSetupToolingForLLVM.rst
rename to interpreter/llvm-project/clang/docs/HowToSetupToolingForLLVM.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/InternalsManual.rst b/interpreter/llvm-project/clang/docs/InternalsManual.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/InternalsManual.rst
rename to interpreter/llvm-project/clang/docs/InternalsManual.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/IntroductionToTheClangAST.rst b/interpreter/llvm-project/clang/docs/IntroductionToTheClangAST.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/IntroductionToTheClangAST.rst
rename to interpreter/llvm-project/clang/docs/IntroductionToTheClangAST.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ItaniumMangleAbiTags.rst b/interpreter/llvm-project/clang/docs/ItaniumMangleAbiTags.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ItaniumMangleAbiTags.rst
rename to interpreter/llvm-project/clang/docs/ItaniumMangleAbiTags.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/JSONCompilationDatabase.rst b/interpreter/llvm-project/clang/docs/JSONCompilationDatabase.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/JSONCompilationDatabase.rst
rename to interpreter/llvm-project/clang/docs/JSONCompilationDatabase.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LTOVisibility.rst b/interpreter/llvm-project/clang/docs/LTOVisibility.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LTOVisibility.rst
rename to interpreter/llvm-project/clang/docs/LTOVisibility.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LanguageExtensions.rst b/interpreter/llvm-project/clang/docs/LanguageExtensions.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LanguageExtensions.rst
rename to interpreter/llvm-project/clang/docs/LanguageExtensions.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LeakSanitizer.rst b/interpreter/llvm-project/clang/docs/LeakSanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LeakSanitizer.rst
rename to interpreter/llvm-project/clang/docs/LeakSanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LibASTImporter.rst b/interpreter/llvm-project/clang/docs/LibASTImporter.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibASTImporter.rst
rename to interpreter/llvm-project/clang/docs/LibASTImporter.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LibASTMatchers.rst b/interpreter/llvm-project/clang/docs/LibASTMatchers.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibASTMatchers.rst
rename to interpreter/llvm-project/clang/docs/LibASTMatchers.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LibASTMatchersReference.html b/interpreter/llvm-project/clang/docs/LibASTMatchersReference.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibASTMatchersReference.html
rename to interpreter/llvm-project/clang/docs/LibASTMatchersReference.html
diff --git a/interpreter/llvm/src/tools/clang/docs/LibASTMatchersTutorial.rst b/interpreter/llvm-project/clang/docs/LibASTMatchersTutorial.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibASTMatchersTutorial.rst
rename to interpreter/llvm-project/clang/docs/LibASTMatchersTutorial.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LibFormat.rst b/interpreter/llvm-project/clang/docs/LibFormat.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibFormat.rst
rename to interpreter/llvm-project/clang/docs/LibFormat.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/LibTooling.rst b/interpreter/llvm-project/clang/docs/LibTooling.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/LibTooling.rst
rename to interpreter/llvm-project/clang/docs/LibTooling.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/MSVCCompatibility.rst b/interpreter/llvm-project/clang/docs/MSVCCompatibility.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/MSVCCompatibility.rst
rename to interpreter/llvm-project/clang/docs/MSVCCompatibility.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Makefile.sphinx b/interpreter/llvm-project/clang/docs/Makefile.sphinx
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Makefile.sphinx
rename to interpreter/llvm-project/clang/docs/Makefile.sphinx
diff --git a/interpreter/llvm/src/tools/clang/docs/MatrixTypes.rst b/interpreter/llvm-project/clang/docs/MatrixTypes.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/MatrixTypes.rst
rename to interpreter/llvm-project/clang/docs/MatrixTypes.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/MemorySanitizer.rst b/interpreter/llvm-project/clang/docs/MemorySanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/MemorySanitizer.rst
rename to interpreter/llvm-project/clang/docs/MemorySanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Modules.rst b/interpreter/llvm-project/clang/docs/Modules.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Modules.rst
rename to interpreter/llvm-project/clang/docs/Modules.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ObjectiveCLiterals.rst b/interpreter/llvm-project/clang/docs/ObjectiveCLiterals.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ObjectiveCLiterals.rst
rename to interpreter/llvm-project/clang/docs/ObjectiveCLiterals.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/OpenCLSupport.rst b/interpreter/llvm-project/clang/docs/OpenCLSupport.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/OpenCLSupport.rst
rename to interpreter/llvm-project/clang/docs/OpenCLSupport.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/OpenMPSupport.rst b/interpreter/llvm-project/clang/docs/OpenMPSupport.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/OpenMPSupport.rst
rename to interpreter/llvm-project/clang/docs/OpenMPSupport.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/PCHInternals.rst b/interpreter/llvm-project/clang/docs/PCHInternals.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/PCHInternals.rst
rename to interpreter/llvm-project/clang/docs/PCHInternals.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/PCHLayout.graffle b/interpreter/llvm-project/clang/docs/PCHLayout.graffle
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/PCHLayout.graffle
rename to interpreter/llvm-project/clang/docs/PCHLayout.graffle
diff --git a/interpreter/llvm/src/tools/clang/docs/PCHLayout.png b/interpreter/llvm-project/clang/docs/PCHLayout.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/PCHLayout.png
rename to interpreter/llvm-project/clang/docs/PCHLayout.png
diff --git a/interpreter/llvm/src/tools/clang/docs/RAVFrontendAction.rst b/interpreter/llvm-project/clang/docs/RAVFrontendAction.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/RAVFrontendAction.rst
rename to interpreter/llvm-project/clang/docs/RAVFrontendAction.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/README.txt b/interpreter/llvm-project/clang/docs/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/README.txt
rename to interpreter/llvm-project/clang/docs/README.txt
diff --git a/interpreter/llvm/src/tools/clang/docs/RefactoringEngine.rst b/interpreter/llvm-project/clang/docs/RefactoringEngine.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/RefactoringEngine.rst
rename to interpreter/llvm-project/clang/docs/RefactoringEngine.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ReleaseNotes.rst b/interpreter/llvm-project/clang/docs/ReleaseNotes.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ReleaseNotes.rst
rename to interpreter/llvm-project/clang/docs/ReleaseNotes.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SYCLSupport.rst b/interpreter/llvm-project/clang/docs/SYCLSupport.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SYCLSupport.rst
rename to interpreter/llvm-project/clang/docs/SYCLSupport.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SafeStack.rst b/interpreter/llvm-project/clang/docs/SafeStack.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SafeStack.rst
rename to interpreter/llvm-project/clang/docs/SafeStack.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SanitizerCoverage.rst b/interpreter/llvm-project/clang/docs/SanitizerCoverage.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SanitizerCoverage.rst
rename to interpreter/llvm-project/clang/docs/SanitizerCoverage.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SanitizerSpecialCaseList.rst b/interpreter/llvm-project/clang/docs/SanitizerSpecialCaseList.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SanitizerSpecialCaseList.rst
rename to interpreter/llvm-project/clang/docs/SanitizerSpecialCaseList.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SanitizerStats.rst b/interpreter/llvm-project/clang/docs/SanitizerStats.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SanitizerStats.rst
rename to interpreter/llvm-project/clang/docs/SanitizerStats.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ShadowCallStack.rst b/interpreter/llvm-project/clang/docs/ShadowCallStack.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ShadowCallStack.rst
rename to interpreter/llvm-project/clang/docs/ShadowCallStack.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/SourceBasedCodeCoverage.rst b/interpreter/llvm-project/clang/docs/SourceBasedCodeCoverage.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/SourceBasedCodeCoverage.rst
rename to interpreter/llvm-project/clang/docs/SourceBasedCodeCoverage.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ThinLTO.rst b/interpreter/llvm-project/clang/docs/ThinLTO.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ThinLTO.rst
rename to interpreter/llvm-project/clang/docs/ThinLTO.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ThreadSafetyAnalysis.rst b/interpreter/llvm-project/clang/docs/ThreadSafetyAnalysis.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ThreadSafetyAnalysis.rst
rename to interpreter/llvm-project/clang/docs/ThreadSafetyAnalysis.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/ThreadSanitizer.rst b/interpreter/llvm-project/clang/docs/ThreadSanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/ThreadSanitizer.rst
rename to interpreter/llvm-project/clang/docs/ThreadSanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Toolchain.rst b/interpreter/llvm-project/clang/docs/Toolchain.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Toolchain.rst
rename to interpreter/llvm-project/clang/docs/Toolchain.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/Tooling.rst b/interpreter/llvm-project/clang/docs/Tooling.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/Tooling.rst
rename to interpreter/llvm-project/clang/docs/Tooling.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/UndefinedBehaviorSanitizer.rst b/interpreter/llvm-project/clang/docs/UndefinedBehaviorSanitizer.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/UndefinedBehaviorSanitizer.rst
rename to interpreter/llvm-project/clang/docs/UndefinedBehaviorSanitizer.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/UsersManual.rst b/interpreter/llvm-project/clang/docs/UsersManual.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/UsersManual.rst
rename to interpreter/llvm-project/clang/docs/UsersManual.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers.rst b/interpreter/llvm-project/clang/docs/analyzer/checkers.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers.rst
rename to interpreter/llvm-project/clang/docs/analyzer/checkers.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/callandmessage_example.c b/interpreter/llvm-project/clang/docs/analyzer/checkers/callandmessage_example.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/callandmessage_example.c
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/callandmessage_example.c
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/dealloc_example.m b/interpreter/llvm-project/clang/docs/analyzer/checkers/dealloc_example.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/dealloc_example.m
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/dealloc_example.m
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/dividezero_example.c b/interpreter/llvm-project/clang/docs/analyzer/checkers/dividezero_example.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/dividezero_example.c
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/dividezero_example.c
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp b/interpreter/llvm-project/clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/newdelete_example.cpp b/interpreter/llvm-project/clang/docs/analyzer/checkers/newdelete_example.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/newdelete_example.cpp
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/newdelete_example.cpp
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/seckeychainapi_example.m b/interpreter/llvm-project/clang/docs/analyzer/checkers/seckeychainapi_example.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/seckeychainapi_example.m
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/seckeychainapi_example.m
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/unix_api_example.c b/interpreter/llvm-project/clang/docs/analyzer/checkers/unix_api_example.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/unix_api_example.c
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/unix_api_example.c
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/checkers/unix_malloc_example.c b/interpreter/llvm-project/clang/docs/analyzer/checkers/unix_malloc_example.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/checkers/unix_malloc_example.c
rename to interpreter/llvm-project/clang/docs/analyzer/checkers/unix_malloc_example.c
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/conf.py b/interpreter/llvm-project/clang/docs/analyzer/conf.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/conf.py
rename to interpreter/llvm-project/clang/docs/analyzer/conf.py
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/DebugChecks.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs/DebugChecks.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/DebugChecks.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs/DebugChecks.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/IPA.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs/IPA.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/IPA.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs/IPA.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/InitializerLists.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs/InitializerLists.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/InitializerLists.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs/InitializerLists.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/RegionStore.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs/RegionStore.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/RegionStore.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs/RegionStore.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/nullability.rst b/interpreter/llvm-project/clang/docs/analyzer/developer-docs/nullability.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/developer-docs/nullability.rst
rename to interpreter/llvm-project/clang/docs/analyzer/developer-docs/nullability.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/make.bat b/interpreter/llvm-project/clang/docs/analyzer/make.bat
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/make.bat
rename to interpreter/llvm-project/clang/docs/analyzer/make.bat
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/user-docs.rst b/interpreter/llvm-project/clang/docs/analyzer/user-docs.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/user-docs.rst
rename to interpreter/llvm-project/clang/docs/analyzer/user-docs.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst b/interpreter/llvm-project/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
rename to interpreter/llvm-project/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/conf.py b/interpreter/llvm-project/clang/docs/conf.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/conf.py
rename to interpreter/llvm-project/clang/docs/conf.py
diff --git a/interpreter/llvm/src/tools/clang/docs/doxygen-mainpage.dox b/interpreter/llvm-project/clang/docs/doxygen-mainpage.dox
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/doxygen-mainpage.dox
rename to interpreter/llvm-project/clang/docs/doxygen-mainpage.dox
diff --git a/interpreter/llvm/src/tools/clang/docs/doxygen.cfg.in b/interpreter/llvm-project/clang/docs/doxygen.cfg.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/doxygen.cfg.in
rename to interpreter/llvm-project/clang/docs/doxygen.cfg.in
diff --git a/interpreter/llvm/src/tools/clang/docs/index.rst b/interpreter/llvm-project/clang/docs/index.rst
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/index.rst
rename to interpreter/llvm-project/clang/docs/index.rst
diff --git a/interpreter/llvm/src/tools/clang/docs/make.bat b/interpreter/llvm-project/clang/docs/make.bat
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/make.bat
rename to interpreter/llvm-project/clang/docs/make.bat
diff --git a/interpreter/llvm/src/tools/clang/docs/tools/dump_ast_matchers.py b/interpreter/llvm-project/clang/docs/tools/dump_ast_matchers.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/tools/dump_ast_matchers.py
rename to interpreter/llvm-project/clang/docs/tools/dump_ast_matchers.py
diff --git a/interpreter/llvm/src/tools/clang/docs/tools/dump_format_style.py b/interpreter/llvm-project/clang/docs/tools/dump_format_style.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/tools/dump_format_style.py
rename to interpreter/llvm-project/clang/docs/tools/dump_format_style.py
diff --git a/interpreter/llvm/src/tools/clang/docs/tools/generate_formatted_state.py b/interpreter/llvm-project/clang/docs/tools/generate_formatted_state.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/docs/tools/generate_formatted_state.py
rename to interpreter/llvm-project/clang/docs/tools/generate_formatted_state.py
diff --git a/interpreter/llvm/src/tools/clang/examples/AnnotateFunctions/AnnotateFunctions.cpp b/interpreter/llvm-project/clang/examples/AnnotateFunctions/AnnotateFunctions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/AnnotateFunctions/AnnotateFunctions.cpp
rename to interpreter/llvm-project/clang/examples/AnnotateFunctions/AnnotateFunctions.cpp
diff --git a/interpreter/llvm/src/tools/clang/examples/AnnotateFunctions/CMakeLists.txt b/interpreter/llvm-project/clang/examples/AnnotateFunctions/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/AnnotateFunctions/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/AnnotateFunctions/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/Attribute/Attribute.cpp b/interpreter/llvm-project/clang/examples/Attribute/Attribute.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/Attribute/Attribute.cpp
rename to interpreter/llvm-project/clang/examples/Attribute/Attribute.cpp
diff --git a/interpreter/llvm/src/tools/clang/examples/Attribute/CMakeLists.txt b/interpreter/llvm-project/clang/examples/Attribute/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/Attribute/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/Attribute/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/CMakeLists.txt b/interpreter/llvm-project/clang/examples/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/CallSuperAttribute/CMakeLists.txt b/interpreter/llvm-project/clang/examples/CallSuperAttribute/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/CallSuperAttribute/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/CallSuperAttribute/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp b/interpreter/llvm-project/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
rename to interpreter/llvm-project/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/CMakeLists.txt b/interpreter/llvm-project/clang/examples/PrintFunctionNames/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/PrintFunctionNames/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp b/interpreter/llvm-project/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
rename to interpreter/llvm-project/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
diff --git a/interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports b/interpreter/llvm-project/clang/examples/PrintFunctionNames/PrintFunctionNames.exports
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports
rename to interpreter/llvm-project/clang/examples/PrintFunctionNames/PrintFunctionNames.exports
diff --git a/interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/README.txt b/interpreter/llvm-project/clang/examples/PrintFunctionNames/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/PrintFunctionNames/README.txt
rename to interpreter/llvm-project/clang/examples/PrintFunctionNames/README.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/clang-interpreter/CMakeLists.txt b/interpreter/llvm-project/clang/examples/clang-interpreter/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/clang-interpreter/CMakeLists.txt
rename to interpreter/llvm-project/clang/examples/clang-interpreter/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/clang-interpreter/README.txt b/interpreter/llvm-project/clang/examples/clang-interpreter/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/clang-interpreter/README.txt
rename to interpreter/llvm-project/clang/examples/clang-interpreter/README.txt
diff --git a/interpreter/llvm/src/tools/clang/examples/clang-interpreter/Test.cxx b/interpreter/llvm-project/clang/examples/clang-interpreter/Test.cxx
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/clang-interpreter/Test.cxx
rename to interpreter/llvm-project/clang/examples/clang-interpreter/Test.cxx
diff --git a/interpreter/llvm/src/tools/clang/examples/clang-interpreter/main.cpp b/interpreter/llvm-project/clang/examples/clang-interpreter/main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/examples/clang-interpreter/main.cpp
rename to interpreter/llvm-project/clang/examples/clang-interpreter/main.cpp
diff --git a/interpreter/llvm/src/tools/clang/include/CMakeLists.txt b/interpreter/llvm-project/clang/include/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/BuildSystem.h b/interpreter/llvm-project/clang/include/clang-c/BuildSystem.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/BuildSystem.h
rename to interpreter/llvm-project/clang/include/clang-c/BuildSystem.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/CXCompilationDatabase.h b/interpreter/llvm-project/clang/include/clang-c/CXCompilationDatabase.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/CXCompilationDatabase.h
rename to interpreter/llvm-project/clang/include/clang-c/CXCompilationDatabase.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/CXErrorCode.h b/interpreter/llvm-project/clang/include/clang-c/CXErrorCode.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/CXErrorCode.h
rename to interpreter/llvm-project/clang/include/clang-c/CXErrorCode.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/CXString.h b/interpreter/llvm-project/clang/include/clang-c/CXString.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/CXString.h
rename to interpreter/llvm-project/clang/include/clang-c/CXString.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/Documentation.h b/interpreter/llvm-project/clang/include/clang-c/Documentation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/Documentation.h
rename to interpreter/llvm-project/clang/include/clang-c/Documentation.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/ExternC.h b/interpreter/llvm-project/clang/include/clang-c/ExternC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/ExternC.h
rename to interpreter/llvm-project/clang/include/clang-c/ExternC.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/FatalErrorHandler.h b/interpreter/llvm-project/clang/include/clang-c/FatalErrorHandler.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/FatalErrorHandler.h
rename to interpreter/llvm-project/clang/include/clang-c/FatalErrorHandler.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/Index.h b/interpreter/llvm-project/clang/include/clang-c/Index.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/Index.h
rename to interpreter/llvm-project/clang/include/clang-c/Index.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/Platform.h b/interpreter/llvm-project/clang/include/clang-c/Platform.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/Platform.h
rename to interpreter/llvm-project/clang/include/clang-c/Platform.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/Rewrite.h b/interpreter/llvm-project/clang/include/clang-c/Rewrite.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/Rewrite.h
rename to interpreter/llvm-project/clang/include/clang-c/Rewrite.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang-c/module.modulemap b/interpreter/llvm-project/clang/include/clang-c/module.modulemap
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang-c/module.modulemap
rename to interpreter/llvm-project/clang/include/clang-c/module.modulemap
diff --git a/interpreter/llvm/src/tools/clang/include/clang/APINotes/APINotesYAMLCompiler.h b/interpreter/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/APINotes/APINotesYAMLCompiler.h
rename to interpreter/llvm-project/clang/include/clang/APINotes/APINotesYAMLCompiler.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/APINotes/Types.h b/interpreter/llvm-project/clang/include/clang/APINotes/Types.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/APINotes/Types.h
rename to interpreter/llvm-project/clang/include/clang/APINotes/Types.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/ARCMT.h b/interpreter/llvm-project/clang/include/clang/ARCMigrate/ARCMT.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/ARCMT.h
rename to interpreter/llvm-project/clang/include/clang/ARCMigrate/ARCMT.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/ARCMTActions.h b/interpreter/llvm-project/clang/include/clang/ARCMigrate/ARCMTActions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/ARCMTActions.h
rename to interpreter/llvm-project/clang/include/clang/ARCMigrate/ARCMTActions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/FileRemapper.h b/interpreter/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ARCMigrate/FileRemapper.h
rename to interpreter/llvm-project/clang/include/clang/ARCMigrate/FileRemapper.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/APValue.h b/interpreter/llvm-project/clang/include/clang/AST/APValue.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/APValue.h
rename to interpreter/llvm-project/clang/include/clang/AST/APValue.h
index 5f4ac02f53c9a..4e22d6c8443c5 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/AST/APValue.h
+++ b/interpreter/llvm-project/clang/include/clang/AST/APValue.h
@@ -238,7 +238,7 @@ class APValue {
     }
   };
   class LValuePathSerializationHelper {
-    const void *ElemTy;
+    const void *Ty;
 
   public:
     ArrayRef Path;
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AST.h b/interpreter/llvm-project/clang/include/clang/AST/AST.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AST.h
rename to interpreter/llvm-project/clang/include/clang/AST/AST.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTConcept.h b/interpreter/llvm-project/clang/include/clang/AST/ASTConcept.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTConcept.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTConcept.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTConsumer.h b/interpreter/llvm-project/clang/include/clang/AST/ASTConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTConsumer.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTContext.h b/interpreter/llvm-project/clang/include/clang/AST/ASTContext.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTContext.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTContext.h
index 08b79abc12dc2..425053cd8d2ba 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTContext.h
+++ b/interpreter/llvm-project/clang/include/clang/AST/ASTContext.h
@@ -1544,8 +1544,7 @@ class ASTContext : public RefCountedBase {
                              QualType equivalentType);
 
   QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
-                                        QualType Replacement,
-                                        bool AllowNonCanonical = false) const;
+                                        QualType Replacement) const;
   QualType getSubstTemplateTypeParmPackType(
                                           const TemplateTypeParmType *Replaced,
                                             const TemplateArgument &ArgPack);
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTContextAllocate.h b/interpreter/llvm-project/clang/include/clang/AST/ASTContextAllocate.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTContextAllocate.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTContextAllocate.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTDiagnostic.h b/interpreter/llvm-project/clang/include/clang/AST/ASTDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTDumper.h b/interpreter/llvm-project/clang/include/clang/AST/ASTDumper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTDumper.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTDumper.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTDumperUtils.h b/interpreter/llvm-project/clang/include/clang/AST/ASTDumperUtils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTDumperUtils.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTDumperUtils.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTFwd.h b/interpreter/llvm-project/clang/include/clang/AST/ASTFwd.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTFwd.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTFwd.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporter.h b/interpreter/llvm-project/clang/include/clang/AST/ASTImporter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporter.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTImporter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporterLookupTable.h b/interpreter/llvm-project/clang/include/clang/AST/ASTImporterLookupTable.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporterLookupTable.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTImporterLookupTable.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporterSharedState.h b/interpreter/llvm-project/clang/include/clang/AST/ASTImporterSharedState.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTImporterSharedState.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTImporterSharedState.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTLambda.h b/interpreter/llvm-project/clang/include/clang/AST/ASTLambda.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTLambda.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTLambda.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTMutationListener.h b/interpreter/llvm-project/clang/include/clang/AST/ASTMutationListener.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTMutationListener.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTMutationListener.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTNodeTraverser.h b/interpreter/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTNodeTraverser.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTNodeTraverser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTStructuralEquivalence.h b/interpreter/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTStructuralEquivalence.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTStructuralEquivalence.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTTypeTraits.h b/interpreter/llvm-project/clang/include/clang/AST/ASTTypeTraits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTTypeTraits.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTTypeTraits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTUnresolvedSet.h b/interpreter/llvm-project/clang/include/clang/AST/ASTUnresolvedSet.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTUnresolvedSet.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTUnresolvedSet.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ASTVector.h b/interpreter/llvm-project/clang/include/clang/AST/ASTVector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ASTVector.h
rename to interpreter/llvm-project/clang/include/clang/AST/ASTVector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AbstractBasicReader.h b/interpreter/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
similarity index 98%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AbstractBasicReader.h
rename to interpreter/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
index 5505d661b44e2..ea09a6d74dcb0 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/AST/AbstractBasicReader.h
+++ b/interpreter/llvm-project/clang/include/clang/AST/AbstractBasicReader.h
@@ -190,7 +190,8 @@ class DataStreamBasicReader : public BasicReaderBase {
 
   APValue::LValuePathSerializationHelper readLValuePathSerializationHelper(
       SmallVectorImpl &path) {
-    auto elemTy = asImpl().readQualType();
+    auto origTy = asImpl().readQualType();
+    auto elemTy = origTy;
     unsigned pathLength = asImpl().readUInt32();
     for (unsigned i = 0; i < pathLength; ++i) {
       if (elemTy->template getAs()) {
@@ -208,7 +209,7 @@ class DataStreamBasicReader : public BasicReaderBase {
             APValue::LValuePathEntry::ArrayIndex(asImpl().readUInt32()));
       }
     }
-    return APValue::LValuePathSerializationHelper(path, elemTy);
+    return APValue::LValuePathSerializationHelper(path, origTy);
   }
 
   Qualifiers readQualifiers() {
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AbstractBasicWriter.h b/interpreter/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AbstractBasicWriter.h
rename to interpreter/llvm-project/clang/include/clang/AST/AbstractBasicWriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AbstractTypeReader.h b/interpreter/llvm-project/clang/include/clang/AST/AbstractTypeReader.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AbstractTypeReader.h
rename to interpreter/llvm-project/clang/include/clang/AST/AbstractTypeReader.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AbstractTypeWriter.h b/interpreter/llvm-project/clang/include/clang/AST/AbstractTypeWriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AbstractTypeWriter.h
rename to interpreter/llvm-project/clang/include/clang/AST/AbstractTypeWriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Attr.h b/interpreter/llvm-project/clang/include/clang/AST/Attr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Attr.h
rename to interpreter/llvm-project/clang/include/clang/AST/Attr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AttrIterator.h b/interpreter/llvm-project/clang/include/clang/AST/AttrIterator.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AttrIterator.h
rename to interpreter/llvm-project/clang/include/clang/AST/AttrIterator.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/AttrVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/AttrVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/AttrVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/AttrVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Availability.h b/interpreter/llvm-project/clang/include/clang/AST/Availability.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Availability.h
rename to interpreter/llvm-project/clang/include/clang/AST/Availability.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/BaseSubobject.h b/interpreter/llvm-project/clang/include/clang/AST/BaseSubobject.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/BaseSubobject.h
rename to interpreter/llvm-project/clang/include/clang/AST/BaseSubobject.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/BuiltinTypes.def b/interpreter/llvm-project/clang/include/clang/AST/BuiltinTypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/BuiltinTypes.def
rename to interpreter/llvm-project/clang/include/clang/AST/BuiltinTypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/AST/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/AST/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CXXInheritance.h b/interpreter/llvm-project/clang/include/clang/AST/CXXInheritance.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CXXInheritance.h
rename to interpreter/llvm-project/clang/include/clang/AST/CXXInheritance.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def b/interpreter/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
rename to interpreter/llvm-project/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CanonicalType.h b/interpreter/llvm-project/clang/include/clang/AST/CanonicalType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CanonicalType.h
rename to interpreter/llvm-project/clang/include/clang/AST/CanonicalType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CharUnits.h b/interpreter/llvm-project/clang/include/clang/AST/CharUnits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CharUnits.h
rename to interpreter/llvm-project/clang/include/clang/AST/CharUnits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Comment.h b/interpreter/llvm-project/clang/include/clang/AST/Comment.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Comment.h
rename to interpreter/llvm-project/clang/include/clang/AST/Comment.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentBriefParser.h b/interpreter/llvm-project/clang/include/clang/AST/CommentBriefParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentBriefParser.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentBriefParser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentCommandTraits.h b/interpreter/llvm-project/clang/include/clang/AST/CommentCommandTraits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentCommandTraits.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentCommandTraits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentCommands.td b/interpreter/llvm-project/clang/include/clang/AST/CommentCommands.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentCommands.td
rename to interpreter/llvm-project/clang/include/clang/AST/CommentCommands.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentDiagnostic.h b/interpreter/llvm-project/clang/include/clang/AST/CommentDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentHTMLNamedCharacterReferences.td b/interpreter/llvm-project/clang/include/clang/AST/CommentHTMLNamedCharacterReferences.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentHTMLNamedCharacterReferences.td
rename to interpreter/llvm-project/clang/include/clang/AST/CommentHTMLNamedCharacterReferences.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentHTMLTags.td b/interpreter/llvm-project/clang/include/clang/AST/CommentHTMLTags.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentHTMLTags.td
rename to interpreter/llvm-project/clang/include/clang/AST/CommentHTMLTags.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentLexer.h b/interpreter/llvm-project/clang/include/clang/AST/CommentLexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentLexer.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentLexer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentParser.h b/interpreter/llvm-project/clang/include/clang/AST/CommentParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentParser.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentParser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentSema.h b/interpreter/llvm-project/clang/include/clang/AST/CommentSema.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentSema.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentSema.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CommentVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/CommentVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CommentVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/CommentVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ComparisonCategories.h b/interpreter/llvm-project/clang/include/clang/AST/ComparisonCategories.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ComparisonCategories.h
rename to interpreter/llvm-project/clang/include/clang/AST/ComparisonCategories.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ComputeDependence.h b/interpreter/llvm-project/clang/include/clang/AST/ComputeDependence.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ComputeDependence.h
rename to interpreter/llvm-project/clang/include/clang/AST/ComputeDependence.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/CurrentSourceLocExprScope.h b/interpreter/llvm-project/clang/include/clang/AST/CurrentSourceLocExprScope.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/CurrentSourceLocExprScope.h
rename to interpreter/llvm-project/clang/include/clang/AST/CurrentSourceLocExprScope.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DataCollection.h b/interpreter/llvm-project/clang/include/clang/AST/DataCollection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DataCollection.h
rename to interpreter/llvm-project/clang/include/clang/AST/DataCollection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Decl.h b/interpreter/llvm-project/clang/include/clang/AST/Decl.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Decl.h
rename to interpreter/llvm-project/clang/include/clang/AST/Decl.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclAccessPair.h b/interpreter/llvm-project/clang/include/clang/AST/DeclAccessPair.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclAccessPair.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclAccessPair.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclBase.h b/interpreter/llvm-project/clang/include/clang/AST/DeclBase.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclBase.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclBase.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclCXX.h b/interpreter/llvm-project/clang/include/clang/AST/DeclCXX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclCXX.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclCXX.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclContextInternals.h b/interpreter/llvm-project/clang/include/clang/AST/DeclContextInternals.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclContextInternals.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclContextInternals.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclFriend.h b/interpreter/llvm-project/clang/include/clang/AST/DeclFriend.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclFriend.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclFriend.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclGroup.h b/interpreter/llvm-project/clang/include/clang/AST/DeclGroup.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclGroup.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclGroup.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclLookups.h b/interpreter/llvm-project/clang/include/clang/AST/DeclLookups.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclLookups.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclLookups.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclObjC.h b/interpreter/llvm-project/clang/include/clang/AST/DeclObjC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclObjC.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclObjC.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclObjCCommon.h b/interpreter/llvm-project/clang/include/clang/AST/DeclObjCCommon.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclObjCCommon.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclObjCCommon.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclOpenMP.h b/interpreter/llvm-project/clang/include/clang/AST/DeclOpenMP.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclOpenMP.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclOpenMP.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclTemplate.h b/interpreter/llvm-project/clang/include/clang/AST/DeclTemplate.h
similarity index 98%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclTemplate.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclTemplate.h
index e6b261edf1bce..e7a011bdaed00 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclTemplate.h
+++ b/interpreter/llvm-project/clang/include/clang/AST/DeclTemplate.h
@@ -828,8 +828,7 @@ class RedeclarableTemplateDecl : public TemplateDecl,
 
   void loadLazySpecializationsImpl(bool OnlyPartial = false) const;
 
-  ///\returns true if any lazy specialization was loaded.
-  bool loadLazySpecializationsImpl(llvm::ArrayRef Args,
+  void loadLazySpecializationsImpl(llvm::ArrayRef Args,
                                    TemplateParameterList *TPL = nullptr) const;
 
   Decl *loadLazySpecializationImpl(LazySpecializationInfo &LazySpecInfo) const;
@@ -1119,6 +1118,20 @@ class FunctionTemplateDecl : public RedeclarableTemplateDecl {
     return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+    return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   /// Retrieve the "injected" template arguments that correspond to the
   /// template parameters of this function template.
   ///
@@ -2448,6 +2461,20 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl {
     return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+    return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == ClassTemplate; }
@@ -3251,6 +3278,20 @@ class VarTemplateDecl : public RedeclarableTemplateDecl {
     return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+    return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+    return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == VarTemplate; }
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/DeclVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DeclarationName.h b/interpreter/llvm-project/clang/include/clang/AST/DeclarationName.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DeclarationName.h
rename to interpreter/llvm-project/clang/include/clang/AST/DeclarationName.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DependenceFlags.h b/interpreter/llvm-project/clang/include/clang/AST/DependenceFlags.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DependenceFlags.h
rename to interpreter/llvm-project/clang/include/clang/AST/DependenceFlags.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/DependentDiagnostic.h b/interpreter/llvm-project/clang/include/clang/AST/DependentDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/DependentDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/AST/DependentDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/EvaluatedExprVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/EvaluatedExprVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/EvaluatedExprVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/EvaluatedExprVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Expr.h b/interpreter/llvm-project/clang/include/clang/AST/Expr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Expr.h
rename to interpreter/llvm-project/clang/include/clang/AST/Expr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExprCXX.h b/interpreter/llvm-project/clang/include/clang/AST/ExprCXX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExprCXX.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExprCXX.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExprConcepts.h b/interpreter/llvm-project/clang/include/clang/AST/ExprConcepts.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExprConcepts.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExprConcepts.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExprObjC.h b/interpreter/llvm-project/clang/include/clang/AST/ExprObjC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExprObjC.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExprObjC.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExprOpenMP.h b/interpreter/llvm-project/clang/include/clang/AST/ExprOpenMP.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExprOpenMP.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExprOpenMP.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExternalASTMerger.h b/interpreter/llvm-project/clang/include/clang/AST/ExternalASTMerger.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExternalASTMerger.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExternalASTMerger.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ExternalASTSource.h b/interpreter/llvm-project/clang/include/clang/AST/ExternalASTSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ExternalASTSource.h
rename to interpreter/llvm-project/clang/include/clang/AST/ExternalASTSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/FormatString.h b/interpreter/llvm-project/clang/include/clang/AST/FormatString.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/FormatString.h
rename to interpreter/llvm-project/clang/include/clang/AST/FormatString.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/GlobalDecl.h b/interpreter/llvm-project/clang/include/clang/AST/GlobalDecl.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/GlobalDecl.h
rename to interpreter/llvm-project/clang/include/clang/AST/GlobalDecl.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/IgnoreExpr.h b/interpreter/llvm-project/clang/include/clang/AST/IgnoreExpr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/IgnoreExpr.h
rename to interpreter/llvm-project/clang/include/clang/AST/IgnoreExpr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/JSONNodeDumper.h b/interpreter/llvm-project/clang/include/clang/AST/JSONNodeDumper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/JSONNodeDumper.h
rename to interpreter/llvm-project/clang/include/clang/AST/JSONNodeDumper.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/LambdaCapture.h b/interpreter/llvm-project/clang/include/clang/AST/LambdaCapture.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/LambdaCapture.h
rename to interpreter/llvm-project/clang/include/clang/AST/LambdaCapture.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/LocInfoType.h b/interpreter/llvm-project/clang/include/clang/AST/LocInfoType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/LocInfoType.h
rename to interpreter/llvm-project/clang/include/clang/AST/LocInfoType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Mangle.h b/interpreter/llvm-project/clang/include/clang/AST/Mangle.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Mangle.h
rename to interpreter/llvm-project/clang/include/clang/AST/Mangle.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/MangleNumberingContext.h b/interpreter/llvm-project/clang/include/clang/AST/MangleNumberingContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/MangleNumberingContext.h
rename to interpreter/llvm-project/clang/include/clang/AST/MangleNumberingContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/NSAPI.h b/interpreter/llvm-project/clang/include/clang/AST/NSAPI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/NSAPI.h
rename to interpreter/llvm-project/clang/include/clang/AST/NSAPI.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/NestedNameSpecifier.h b/interpreter/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/NestedNameSpecifier.h
rename to interpreter/llvm-project/clang/include/clang/AST/NestedNameSpecifier.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/NonTrivialTypeVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/NonTrivialTypeVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/NonTrivialTypeVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/NonTrivialTypeVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ODRHash.h b/interpreter/llvm-project/clang/include/clang/AST/ODRHash.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ODRHash.h
rename to interpreter/llvm-project/clang/include/clang/AST/ODRHash.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/OSLog.h b/interpreter/llvm-project/clang/include/clang/AST/OSLog.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/OSLog.h
rename to interpreter/llvm-project/clang/include/clang/AST/OSLog.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/OpenMPClause.h b/interpreter/llvm-project/clang/include/clang/AST/OpenMPClause.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/OpenMPClause.h
rename to interpreter/llvm-project/clang/include/clang/AST/OpenMPClause.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/OperationKinds.def b/interpreter/llvm-project/clang/include/clang/AST/OperationKinds.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/OperationKinds.def
rename to interpreter/llvm-project/clang/include/clang/AST/OperationKinds.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/OperationKinds.h b/interpreter/llvm-project/clang/include/clang/AST/OperationKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/OperationKinds.h
rename to interpreter/llvm-project/clang/include/clang/AST/OperationKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/OptionalDiagnostic.h b/interpreter/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/OptionalDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/AST/OptionalDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ParentMap.h b/interpreter/llvm-project/clang/include/clang/AST/ParentMap.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ParentMap.h
rename to interpreter/llvm-project/clang/include/clang/AST/ParentMap.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/ParentMapContext.h b/interpreter/llvm-project/clang/include/clang/AST/ParentMapContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/ParentMapContext.h
rename to interpreter/llvm-project/clang/include/clang/AST/ParentMapContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/PrettyDeclStackTrace.h b/interpreter/llvm-project/clang/include/clang/AST/PrettyDeclStackTrace.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/PrettyDeclStackTrace.h
rename to interpreter/llvm-project/clang/include/clang/AST/PrettyDeclStackTrace.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/PrettyPrinter.h b/interpreter/llvm-project/clang/include/clang/AST/PrettyPrinter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/PrettyPrinter.h
rename to interpreter/llvm-project/clang/include/clang/AST/PrettyPrinter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/PropertiesBase.td b/interpreter/llvm-project/clang/include/clang/AST/PropertiesBase.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/PropertiesBase.td
rename to interpreter/llvm-project/clang/include/clang/AST/PropertiesBase.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/QualTypeNames.h b/interpreter/llvm-project/clang/include/clang/AST/QualTypeNames.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/QualTypeNames.h
rename to interpreter/llvm-project/clang/include/clang/AST/QualTypeNames.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/RawCommentList.h b/interpreter/llvm-project/clang/include/clang/AST/RawCommentList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/RawCommentList.h
rename to interpreter/llvm-project/clang/include/clang/AST/RawCommentList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/RecordLayout.h b/interpreter/llvm-project/clang/include/clang/AST/RecordLayout.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/RecordLayout.h
rename to interpreter/llvm-project/clang/include/clang/AST/RecordLayout.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/RecursiveASTVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/RecursiveASTVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/RecursiveASTVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Redeclarable.h b/interpreter/llvm-project/clang/include/clang/AST/Redeclarable.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Redeclarable.h
rename to interpreter/llvm-project/clang/include/clang/AST/Redeclarable.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/SelectorLocationsKind.h b/interpreter/llvm-project/clang/include/clang/AST/SelectorLocationsKind.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/SelectorLocationsKind.h
rename to interpreter/llvm-project/clang/include/clang/AST/SelectorLocationsKind.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Stmt.h b/interpreter/llvm-project/clang/include/clang/AST/Stmt.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Stmt.h
rename to interpreter/llvm-project/clang/include/clang/AST/Stmt.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtCXX.h b/interpreter/llvm-project/clang/include/clang/AST/StmtCXX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtCXX.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtCXX.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtDataCollectors.td b/interpreter/llvm-project/clang/include/clang/AST/StmtDataCollectors.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtDataCollectors.td
rename to interpreter/llvm-project/clang/include/clang/AST/StmtDataCollectors.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtGraphTraits.h b/interpreter/llvm-project/clang/include/clang/AST/StmtGraphTraits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtGraphTraits.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtGraphTraits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtIterator.h b/interpreter/llvm-project/clang/include/clang/AST/StmtIterator.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtIterator.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtIterator.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtObjC.h b/interpreter/llvm-project/clang/include/clang/AST/StmtObjC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtObjC.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtObjC.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtOpenMP.h b/interpreter/llvm-project/clang/include/clang/AST/StmtOpenMP.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtOpenMP.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtOpenMP.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/StmtVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/StmtVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/StmtVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/StmtVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TemplateArgumentVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/TemplateArgumentVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TemplateArgumentVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/TemplateArgumentVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TemplateBase.h b/interpreter/llvm-project/clang/include/clang/AST/TemplateBase.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TemplateBase.h
rename to interpreter/llvm-project/clang/include/clang/AST/TemplateBase.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TemplateName.h b/interpreter/llvm-project/clang/include/clang/AST/TemplateName.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TemplateName.h
rename to interpreter/llvm-project/clang/include/clang/AST/TemplateName.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TextNodeDumper.h b/interpreter/llvm-project/clang/include/clang/AST/TextNodeDumper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TextNodeDumper.h
rename to interpreter/llvm-project/clang/include/clang/AST/TextNodeDumper.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/Type.h b/interpreter/llvm-project/clang/include/clang/AST/Type.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/Type.h
rename to interpreter/llvm-project/clang/include/clang/AST/Type.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeLoc.h b/interpreter/llvm-project/clang/include/clang/AST/TypeLoc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeLoc.h
rename to interpreter/llvm-project/clang/include/clang/AST/TypeLoc.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeLocNodes.def b/interpreter/llvm-project/clang/include/clang/AST/TypeLocNodes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeLocNodes.def
rename to interpreter/llvm-project/clang/include/clang/AST/TypeLocNodes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeLocVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/TypeLocVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeLocVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/TypeLocVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeOrdering.h b/interpreter/llvm-project/clang/include/clang/AST/TypeOrdering.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeOrdering.h
rename to interpreter/llvm-project/clang/include/clang/AST/TypeOrdering.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeProperties.td b/interpreter/llvm-project/clang/include/clang/AST/TypeProperties.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeProperties.td
rename to interpreter/llvm-project/clang/include/clang/AST/TypeProperties.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/TypeVisitor.h b/interpreter/llvm-project/clang/include/clang/AST/TypeVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/TypeVisitor.h
rename to interpreter/llvm-project/clang/include/clang/AST/TypeVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/UnresolvedSet.h b/interpreter/llvm-project/clang/include/clang/AST/UnresolvedSet.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/UnresolvedSet.h
rename to interpreter/llvm-project/clang/include/clang/AST/UnresolvedSet.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/VTTBuilder.h b/interpreter/llvm-project/clang/include/clang/AST/VTTBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/VTTBuilder.h
rename to interpreter/llvm-project/clang/include/clang/AST/VTTBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/AST/VTableBuilder.h b/interpreter/llvm-project/clang/include/clang/AST/VTableBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/AST/VTableBuilder.h
rename to interpreter/llvm-project/clang/include/clang/AST/VTableBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchFinder.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchFinder.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchFinder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchers.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchers.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchersInternal.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchersMacros.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Parser.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Parser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Parser.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Parser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Registry.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Registry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/Registry.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/Registry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/GtestMatchers.h b/interpreter/llvm-project/clang/include/clang/ASTMatchers/GtestMatchers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/ASTMatchers/GtestMatchers.h
rename to interpreter/llvm-project/clang/include/clang/ASTMatchers/GtestMatchers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/Consumed.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/Consumed.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/Consumed.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/Consumed.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/Dominators.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/Dominators.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/Dominators.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/LiveVariables.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/LiveVariables.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/LiveVariables.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/PostOrderCFGView.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/PostOrderCFGView.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/PostOrderCFGView.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/PostOrderCFGView.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ReachableCode.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ReachableCode.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ReachableCode.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ReachableCode.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafety.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafety.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafety.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyLogical.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyOps.def b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyOps.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyOps.def
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyOps.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/UninitializedValues.h b/interpreter/llvm-project/clang/include/clang/Analysis/Analyses/UninitializedValues.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Analyses/UninitializedValues.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Analyses/UninitializedValues.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/AnalysisDeclContext.h b/interpreter/llvm-project/clang/include/clang/Analysis/AnalysisDeclContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/AnalysisDeclContext.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/AnalysisDeclContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/AnalysisDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Analysis/AnalysisDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/AnalysisDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/AnalysisDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/AnyCall.h b/interpreter/llvm-project/clang/include/clang/Analysis/AnyCall.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/AnyCall.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/AnyCall.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/BodyFarm.h b/interpreter/llvm-project/clang/include/clang/Analysis/BodyFarm.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/BodyFarm.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/BodyFarm.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/CFG.h b/interpreter/llvm-project/clang/include/clang/Analysis/CFG.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/CFG.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/CFG.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/CFGStmtMap.h b/interpreter/llvm-project/clang/include/clang/Analysis/CFGStmtMap.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/CFGStmtMap.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/CFGStmtMap.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/CallGraph.h b/interpreter/llvm-project/clang/include/clang/Analysis/CallGraph.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/CallGraph.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/CallGraph.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/CloneDetection.h b/interpreter/llvm-project/clang/include/clang/Analysis/CloneDetection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/CloneDetection.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/CloneDetection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/CodeInjector.h b/interpreter/llvm-project/clang/include/clang/Analysis/CodeInjector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/CodeInjector.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/CodeInjector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/ConstructionContext.h b/interpreter/llvm-project/clang/include/clang/Analysis/ConstructionContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/ConstructionContext.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/ConstructionContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/DomainSpecific/CocoaConventions.h b/interpreter/llvm-project/clang/include/clang/Analysis/DomainSpecific/CocoaConventions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/DomainSpecific/CocoaConventions.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/DomainSpecific/CocoaConventions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h b/interpreter/llvm-project/clang/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h b/interpreter/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h b/interpreter/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/IssueHash.h b/interpreter/llvm-project/clang/include/clang/Analysis/IssueHash.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/IssueHash.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/IssueHash.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/MacroExpansionContext.h b/interpreter/llvm-project/clang/include/clang/Analysis/MacroExpansionContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/MacroExpansionContext.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/MacroExpansionContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/PathDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/PathDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/PathDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/ProgramPoint.h b/interpreter/llvm-project/clang/include/clang/Analysis/ProgramPoint.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/ProgramPoint.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/ProgramPoint.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/RetainSummaryManager.h b/interpreter/llvm-project/clang/include/clang/Analysis/RetainSummaryManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/RetainSummaryManager.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/RetainSummaryManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/SelectorExtras.h b/interpreter/llvm-project/clang/include/clang/Analysis/SelectorExtras.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/SelectorExtras.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/SelectorExtras.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Analysis/Support/BumpVector.h b/interpreter/llvm-project/clang/include/clang/Analysis/Support/BumpVector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Analysis/Support/BumpVector.h
rename to interpreter/llvm-project/clang/include/clang/Analysis/Support/BumpVector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AArch64SVEACLETypes.def b/interpreter/llvm-project/clang/include/clang/Basic/AArch64SVEACLETypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AArch64SVEACLETypes.def
rename to interpreter/llvm-project/clang/include/clang/Basic/AArch64SVEACLETypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ABI.h b/interpreter/llvm-project/clang/include/clang/Basic/ABI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ABI.h
rename to interpreter/llvm-project/clang/include/clang/Basic/ABI.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ASTNode.td b/interpreter/llvm-project/clang/include/clang/Basic/ASTNode.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ASTNode.td
rename to interpreter/llvm-project/clang/include/clang/Basic/ASTNode.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AddressSpaces.h b/interpreter/llvm-project/clang/include/clang/Basic/AddressSpaces.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AddressSpaces.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AddressSpaces.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AlignedAllocation.h b/interpreter/llvm-project/clang/include/clang/Basic/AlignedAllocation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AlignedAllocation.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AlignedAllocation.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AllDiagnostics.h b/interpreter/llvm-project/clang/include/clang/Basic/AllDiagnostics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AllDiagnostics.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AllDiagnostics.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Attr.td b/interpreter/llvm-project/clang/include/clang/Basic/Attr.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Attr.td
rename to interpreter/llvm-project/clang/include/clang/Basic/Attr.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AttrDocs.td b/interpreter/llvm-project/clang/include/clang/Basic/AttrDocs.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AttrDocs.td
rename to interpreter/llvm-project/clang/include/clang/Basic/AttrDocs.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AttrKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/AttrKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AttrKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AttrKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AttrSubjectMatchRules.h b/interpreter/llvm-project/clang/include/clang/Basic/AttrSubjectMatchRules.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AttrSubjectMatchRules.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AttrSubjectMatchRules.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/AttributeCommonInfo.h b/interpreter/llvm-project/clang/include/clang/Basic/AttributeCommonInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/AttributeCommonInfo.h
rename to interpreter/llvm-project/clang/include/clang/Basic/AttributeCommonInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Attributes.h b/interpreter/llvm-project/clang/include/clang/Basic/Attributes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Attributes.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Attributes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BitmaskEnum.h b/interpreter/llvm-project/clang/include/clang/Basic/BitmaskEnum.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BitmaskEnum.h
rename to interpreter/llvm-project/clang/include/clang/Basic/BitmaskEnum.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Builtins.def b/interpreter/llvm-project/clang/include/clang/Basic/Builtins.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Builtins.def
rename to interpreter/llvm-project/clang/include/clang/Basic/Builtins.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Builtins.h b/interpreter/llvm-project/clang/include/clang/Basic/Builtins.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Builtins.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Builtins.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsAArch64.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsAArch64.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsAArch64.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsAMDGPU.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsAMDGPU.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsAMDGPU.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsARM.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsARM.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsARM.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsARM.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsBPF.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsBPF.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsBPF.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagon.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagon.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagon.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagon.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagonDep.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagonDep.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagonDep.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagonDep.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagonMapCustomDep.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagonMapCustomDep.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsHexagonMapCustomDep.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsHexagonMapCustomDep.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsMips.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsMips.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsMips.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsMips.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsNEON.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsNEON.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsNEON.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsNEON.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsNVPTX.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsNVPTX.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsNVPTX.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsPPC.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsPPC.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsPPC.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsRISCV.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsRISCV.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsRISCV.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsRISCV.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsSVE.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsSVE.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsSVE.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsSVE.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsSystemZ.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsSystemZ.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsSystemZ.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsSystemZ.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsWebAssembly.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsWebAssembly.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsX86.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsX86.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsX86.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsX86.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsX86_64.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsX86_64.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsX86_64.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsXCore.def b/interpreter/llvm-project/clang/include/clang/Basic/BuiltinsXCore.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/BuiltinsXCore.def
rename to interpreter/llvm-project/clang/include/clang/Basic/BuiltinsXCore.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Basic/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Basic/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CapturedStmt.h b/interpreter/llvm-project/clang/include/clang/Basic/CapturedStmt.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CapturedStmt.h
rename to interpreter/llvm-project/clang/include/clang/Basic/CapturedStmt.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CharInfo.h b/interpreter/llvm-project/clang/include/clang/Basic/CharInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CharInfo.h
rename to interpreter/llvm-project/clang/include/clang/Basic/CharInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CodeGenOptions.def b/interpreter/llvm-project/clang/include/clang/Basic/CodeGenOptions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CodeGenOptions.def
rename to interpreter/llvm-project/clang/include/clang/Basic/CodeGenOptions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CodeGenOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/CodeGenOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CodeGenOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/CodeGenOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CommentNodes.td b/interpreter/llvm-project/clang/include/clang/Basic/CommentNodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CommentNodes.td
rename to interpreter/llvm-project/clang/include/clang/Basic/CommentNodes.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/CommentOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/CommentOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/CommentOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/CommentOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Cuda.h b/interpreter/llvm-project/clang/include/clang/Basic/Cuda.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Cuda.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Cuda.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DarwinSDKInfo.h b/interpreter/llvm-project/clang/include/clang/Basic/DarwinSDKInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DarwinSDKInfo.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DarwinSDKInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DebugInfoOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DebugInfoOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DebugInfoOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DeclNodes.td b/interpreter/llvm-project/clang/include/clang/Basic/DeclNodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DeclNodes.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DeclNodes.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Diagnostic.h b/interpreter/llvm-project/clang/include/clang/Basic/Diagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Diagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Diagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Diagnostic.td b/interpreter/llvm-project/clang/include/clang/Basic/Diagnostic.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Diagnostic.td
rename to interpreter/llvm-project/clang/include/clang/Basic/Diagnostic.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAST.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAST.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAST.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAST.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticASTKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticASTKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticASTKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAnalysis.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAnalysis.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAnalysis.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAnalysisKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAnalysisKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticAnalysisKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticAnalysisKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCategories.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCategories.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCategories.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCategories.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCategories.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCategories.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCategories.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCategories.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticComment.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticComment.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticComment.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticComment.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCommentKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCommentKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCommentKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCommentKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCommonKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCommonKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCommonKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCrossTU.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCrossTU.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCrossTU.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCrossTUKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDocs.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDocs.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDocs.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDocs.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDriver.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDriver.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDriver.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticError.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticError.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticError.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticError.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticFrontend.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticFrontend.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticFrontend.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticFrontendKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticFrontendKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticGroups.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticGroups.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticIDs.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticIDs.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticIDs.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticLex.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticLex.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticLex.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticLex.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticLexKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticLexKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticOptions.def b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticOptions.def
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticOptions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticParse.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticParse.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticParse.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticParse.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticParseKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticParseKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticParseKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticRefactoring.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticRefactoring.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticRefactoring.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticRefactoringKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSema.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSema.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSema.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSema.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSerialization.h b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSerialization.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSerialization.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSerializationKinds.td b/interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DiagnosticSerializationKinds.td
rename to interpreter/llvm-project/clang/include/clang/Basic/DiagnosticSerializationKinds.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/DirectoryEntry.h b/interpreter/llvm-project/clang/include/clang/Basic/DirectoryEntry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/DirectoryEntry.h
rename to interpreter/llvm-project/clang/include/clang/Basic/DirectoryEntry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ExceptionSpecificationType.h b/interpreter/llvm-project/clang/include/clang/Basic/ExceptionSpecificationType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ExceptionSpecificationType.h
rename to interpreter/llvm-project/clang/include/clang/Basic/ExceptionSpecificationType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ExpressionTraits.h b/interpreter/llvm-project/clang/include/clang/Basic/ExpressionTraits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ExpressionTraits.h
rename to interpreter/llvm-project/clang/include/clang/Basic/ExpressionTraits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/FPOptions.def b/interpreter/llvm-project/clang/include/clang/Basic/FPOptions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/FPOptions.def
rename to interpreter/llvm-project/clang/include/clang/Basic/FPOptions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Features.def b/interpreter/llvm-project/clang/include/clang/Basic/Features.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Features.def
rename to interpreter/llvm-project/clang/include/clang/Basic/Features.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/FileEntry.h b/interpreter/llvm-project/clang/include/clang/Basic/FileEntry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/FileEntry.h
rename to interpreter/llvm-project/clang/include/clang/Basic/FileEntry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/FileManager.h b/interpreter/llvm-project/clang/include/clang/Basic/FileManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/FileManager.h
rename to interpreter/llvm-project/clang/include/clang/Basic/FileManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/FileSystemOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/FileSystemOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/FileSystemOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/FileSystemOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/FileSystemStatCache.h b/interpreter/llvm-project/clang/include/clang/Basic/FileSystemStatCache.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/FileSystemStatCache.h
rename to interpreter/llvm-project/clang/include/clang/Basic/FileSystemStatCache.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/IdentifierTable.h b/interpreter/llvm-project/clang/include/clang/Basic/IdentifierTable.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/IdentifierTable.h
rename to interpreter/llvm-project/clang/include/clang/Basic/IdentifierTable.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/JsonSupport.h b/interpreter/llvm-project/clang/include/clang/Basic/JsonSupport.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/JsonSupport.h
rename to interpreter/llvm-project/clang/include/clang/Basic/JsonSupport.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/LLVM.h b/interpreter/llvm-project/clang/include/clang/Basic/LLVM.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/LLVM.h
rename to interpreter/llvm-project/clang/include/clang/Basic/LLVM.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Lambda.h b/interpreter/llvm-project/clang/include/clang/Basic/Lambda.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Lambda.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Lambda.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/LangOptions.def b/interpreter/llvm-project/clang/include/clang/Basic/LangOptions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/LangOptions.def
rename to interpreter/llvm-project/clang/include/clang/Basic/LangOptions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/LangOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/LangOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/LangOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/LangOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/LangStandard.h b/interpreter/llvm-project/clang/include/clang/Basic/LangStandard.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/LangStandard.h
rename to interpreter/llvm-project/clang/include/clang/Basic/LangStandard.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/LangStandards.def b/interpreter/llvm-project/clang/include/clang/Basic/LangStandards.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/LangStandards.def
rename to interpreter/llvm-project/clang/include/clang/Basic/LangStandards.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Linkage.h b/interpreter/llvm-project/clang/include/clang/Basic/Linkage.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Linkage.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Linkage.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/MSP430Target.def b/interpreter/llvm-project/clang/include/clang/Basic/MSP430Target.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/MSP430Target.def
rename to interpreter/llvm-project/clang/include/clang/Basic/MSP430Target.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/MacroBuilder.h b/interpreter/llvm-project/clang/include/clang/Basic/MacroBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/MacroBuilder.h
rename to interpreter/llvm-project/clang/include/clang/Basic/MacroBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Module.h b/interpreter/llvm-project/clang/include/clang/Basic/Module.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Module.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Module.h
index 3476b05d2e929..f62e657fef7e6 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/Basic/Module.h
+++ b/interpreter/llvm-project/clang/include/clang/Basic/Module.h
@@ -303,6 +303,9 @@ class Module {
   /// and headers from used modules.
   unsigned NoUndeclaredIncludes : 1;
 
+  /// Whether the submodule is allowed to have missing headers.
+  unsigned IsOptional: 1;
+
   /// Whether this module came from a "private" module map, found next
   /// to a regular (public) module map.
   unsigned ModuleMapIsPrivate : 1;
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/NoSanitizeList.h b/interpreter/llvm-project/clang/include/clang/Basic/NoSanitizeList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/NoSanitizeList.h
rename to interpreter/llvm-project/clang/include/clang/Basic/NoSanitizeList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ObjCRuntime.h b/interpreter/llvm-project/clang/include/clang/Basic/ObjCRuntime.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ObjCRuntime.h
rename to interpreter/llvm-project/clang/include/clang/Basic/ObjCRuntime.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLExtensionTypes.def b/interpreter/llvm-project/clang/include/clang/Basic/OpenCLExtensionTypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLExtensionTypes.def
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenCLExtensionTypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLExtensions.def b/interpreter/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLExtensions.def
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenCLExtensions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLImageTypes.def b/interpreter/llvm-project/clang/include/clang/Basic/OpenCLImageTypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLImageTypes.def
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenCLImageTypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/OpenCLOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenCLOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenCLOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenMPKinds.def b/interpreter/llvm-project/clang/include/clang/Basic/OpenMPKinds.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenMPKinds.def
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenMPKinds.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OpenMPKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/OpenMPKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OpenMPKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/OpenMPKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorKinds.def b/interpreter/llvm-project/clang/include/clang/Basic/OperatorKinds.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorKinds.def
rename to interpreter/llvm-project/clang/include/clang/Basic/OperatorKinds.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/OperatorKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/OperatorKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorPrecedence.h b/interpreter/llvm-project/clang/include/clang/Basic/OperatorPrecedence.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/OperatorPrecedence.h
rename to interpreter/llvm-project/clang/include/clang/Basic/OperatorPrecedence.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/PPCTypes.def b/interpreter/llvm-project/clang/include/clang/Basic/PPCTypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/PPCTypes.def
rename to interpreter/llvm-project/clang/include/clang/Basic/PPCTypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/PartialDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/PartialDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Basic/PartialDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/PlistSupport.h b/interpreter/llvm-project/clang/include/clang/Basic/PlistSupport.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/PlistSupport.h
rename to interpreter/llvm-project/clang/include/clang/Basic/PlistSupport.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/PragmaKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/PragmaKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/PragmaKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/PragmaKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/PrettyStackTrace.h b/interpreter/llvm-project/clang/include/clang/Basic/PrettyStackTrace.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/PrettyStackTrace.h
rename to interpreter/llvm-project/clang/include/clang/Basic/PrettyStackTrace.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/ProfileList.h b/interpreter/llvm-project/clang/include/clang/Basic/ProfileList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/ProfileList.h
rename to interpreter/llvm-project/clang/include/clang/Basic/ProfileList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/RISCVVTypes.def b/interpreter/llvm-project/clang/include/clang/Basic/RISCVVTypes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/RISCVVTypes.def
rename to interpreter/llvm-project/clang/include/clang/Basic/RISCVVTypes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/SanitizerSpecialCaseList.h b/interpreter/llvm-project/clang/include/clang/Basic/SanitizerSpecialCaseList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/SanitizerSpecialCaseList.h
rename to interpreter/llvm-project/clang/include/clang/Basic/SanitizerSpecialCaseList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Sanitizers.def b/interpreter/llvm-project/clang/include/clang/Basic/Sanitizers.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Sanitizers.def
rename to interpreter/llvm-project/clang/include/clang/Basic/Sanitizers.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Sanitizers.h b/interpreter/llvm-project/clang/include/clang/Basic/Sanitizers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Sanitizers.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Sanitizers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/SourceLocation.h b/interpreter/llvm-project/clang/include/clang/Basic/SourceLocation.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/SourceLocation.h
rename to interpreter/llvm-project/clang/include/clang/Basic/SourceLocation.h
index 28810d21763e2..540de23b9f55e 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/Basic/SourceLocation.h
+++ b/interpreter/llvm-project/clang/include/clang/Basic/SourceLocation.h
@@ -431,7 +431,6 @@ class FullSourceLoc : public SourceLocation {
   /// \returns true if this source location comes before 'Loc', false otherwise.
   bool isBeforeInTranslationUnitThan(FullSourceLoc Loc) const {
     assert(Loc.isValid());
-    if (!SrcMgr) return true; // assume command line is before Loc
     assert(SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!");
     return isBeforeInTranslationUnitThan((SourceLocation)Loc);
   }
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/SourceManager.h b/interpreter/llvm-project/clang/include/clang/Basic/SourceManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/SourceManager.h
rename to interpreter/llvm-project/clang/include/clang/Basic/SourceManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/SourceManagerInternals.h b/interpreter/llvm-project/clang/include/clang/Basic/SourceManagerInternals.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/SourceManagerInternals.h
rename to interpreter/llvm-project/clang/include/clang/Basic/SourceManagerInternals.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Specifiers.h b/interpreter/llvm-project/clang/include/clang/Basic/Specifiers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Specifiers.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Specifiers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Stack.h b/interpreter/llvm-project/clang/include/clang/Basic/Stack.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Stack.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Stack.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/StmtNodes.td b/interpreter/llvm-project/clang/include/clang/Basic/StmtNodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/StmtNodes.td
rename to interpreter/llvm-project/clang/include/clang/Basic/StmtNodes.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/SyncScope.h b/interpreter/llvm-project/clang/include/clang/Basic/SyncScope.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/SyncScope.h
rename to interpreter/llvm-project/clang/include/clang/Basic/SyncScope.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetBuiltins.h b/interpreter/llvm-project/clang/include/clang/Basic/TargetBuiltins.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetBuiltins.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetBuiltins.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetCXXABI.def b/interpreter/llvm-project/clang/include/clang/Basic/TargetCXXABI.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetCXXABI.def
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetCXXABI.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetCXXABI.h b/interpreter/llvm-project/clang/include/clang/Basic/TargetCXXABI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetCXXABI.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetCXXABI.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetID.h b/interpreter/llvm-project/clang/include/clang/Basic/TargetID.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetID.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetID.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetInfo.h b/interpreter/llvm-project/clang/include/clang/Basic/TargetInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetInfo.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TargetOptions.h b/interpreter/llvm-project/clang/include/clang/Basic/TargetOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TargetOptions.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TargetOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TemplateKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/TemplateKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TemplateKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TemplateKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Thunk.h b/interpreter/llvm-project/clang/include/clang/Basic/Thunk.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Thunk.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Thunk.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TokenKinds.def b/interpreter/llvm-project/clang/include/clang/Basic/TokenKinds.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TokenKinds.def
rename to interpreter/llvm-project/clang/include/clang/Basic/TokenKinds.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TokenKinds.h b/interpreter/llvm-project/clang/include/clang/Basic/TokenKinds.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TokenKinds.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TokenKinds.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TypeNodes.td b/interpreter/llvm-project/clang/include/clang/Basic/TypeNodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TypeNodes.td
rename to interpreter/llvm-project/clang/include/clang/Basic/TypeNodes.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/TypeTraits.h b/interpreter/llvm-project/clang/include/clang/Basic/TypeTraits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/TypeTraits.h
rename to interpreter/llvm-project/clang/include/clang/Basic/TypeTraits.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Version.h b/interpreter/llvm-project/clang/include/clang/Basic/Version.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Version.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Version.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Version.inc.in b/interpreter/llvm-project/clang/include/clang/Basic/Version.inc.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Version.inc.in
rename to interpreter/llvm-project/clang/include/clang/Basic/Version.inc.in
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/Visibility.h b/interpreter/llvm-project/clang/include/clang/Basic/Visibility.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/Visibility.h
rename to interpreter/llvm-project/clang/include/clang/Basic/Visibility.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/X86Target.def b/interpreter/llvm-project/clang/include/clang/Basic/X86Target.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/X86Target.def
rename to interpreter/llvm-project/clang/include/clang/Basic/X86Target.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/XRayInstr.h b/interpreter/llvm-project/clang/include/clang/Basic/XRayInstr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/XRayInstr.h
rename to interpreter/llvm-project/clang/include/clang/Basic/XRayInstr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/XRayLists.h b/interpreter/llvm-project/clang/include/clang/Basic/XRayLists.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/XRayLists.h
rename to interpreter/llvm-project/clang/include/clang/Basic/XRayLists.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_bf16.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_bf16.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_bf16.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_bf16.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_cde.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_cde.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_cde.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_cde.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_fp16.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_fp16.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_fp16.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_fp16.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_mve.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_mve.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_mve.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_mve.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_mve_defs.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_mve_defs.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_mve_defs.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_mve_defs.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_neon.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_neon.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_neon.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_neon.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_neon_incl.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_neon_incl.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_neon_incl.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_neon_incl.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/arm_sve.td b/interpreter/llvm-project/clang/include/clang/Basic/arm_sve.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/arm_sve.td
rename to interpreter/llvm-project/clang/include/clang/Basic/arm_sve.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Basic/riscv_vector.td b/interpreter/llvm-project/clang/include/clang/Basic/riscv_vector.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Basic/riscv_vector.td
rename to interpreter/llvm-project/clang/include/clang/Basic/riscv_vector.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/BackendUtil.h b/interpreter/llvm-project/clang/include/clang/CodeGen/BackendUtil.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/BackendUtil.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/BackendUtil.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/CGFunctionInfo.h b/interpreter/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/CGFunctionInfo.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/CGFunctionInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/CodeGenABITypes.h b/interpreter/llvm-project/clang/include/clang/CodeGen/CodeGenABITypes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/CodeGenABITypes.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/CodeGenABITypes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/CodeGenAction.h b/interpreter/llvm-project/clang/include/clang/CodeGen/CodeGenAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/CodeGenAction.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/CodeGenAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/ConstantInitBuilder.h b/interpreter/llvm-project/clang/include/clang/CodeGen/ConstantInitBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/ConstantInitBuilder.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/ConstantInitBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/ConstantInitFuture.h b/interpreter/llvm-project/clang/include/clang/CodeGen/ConstantInitFuture.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/ConstantInitFuture.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/ConstantInitFuture.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/ModuleBuilder.h b/interpreter/llvm-project/clang/include/clang/CodeGen/ModuleBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/ModuleBuilder.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/ModuleBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h b/interpreter/llvm-project/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CodeGen/SwiftCallingConv.h b/interpreter/llvm-project/clang/include/clang/CodeGen/SwiftCallingConv.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CodeGen/SwiftCallingConv.h
rename to interpreter/llvm-project/clang/include/clang/CodeGen/SwiftCallingConv.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Config/config.h.cmake b/interpreter/llvm-project/clang/include/clang/Config/config.h.cmake
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Config/config.h.cmake
rename to interpreter/llvm-project/clang/include/clang/Config/config.h.cmake
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CrossTU/CrossTUDiagnostic.h b/interpreter/llvm-project/clang/include/clang/CrossTU/CrossTUDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CrossTU/CrossTUDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/CrossTU/CrossTUDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/CrossTU/CrossTranslationUnit.h b/interpreter/llvm-project/clang/include/clang/CrossTU/CrossTranslationUnit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/CrossTU/CrossTranslationUnit.h
rename to interpreter/llvm-project/clang/include/clang/CrossTU/CrossTranslationUnit.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/DirectoryWatcher/DirectoryWatcher.h b/interpreter/llvm-project/clang/include/clang/DirectoryWatcher/DirectoryWatcher.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/DirectoryWatcher/DirectoryWatcher.h
rename to interpreter/llvm-project/clang/include/clang/DirectoryWatcher/DirectoryWatcher.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Action.h b/interpreter/llvm-project/clang/include/clang/Driver/Action.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Action.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Action.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Driver/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Driver/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/ClangOptionDocs.td b/interpreter/llvm-project/clang/include/clang/Driver/ClangOptionDocs.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/ClangOptionDocs.td
rename to interpreter/llvm-project/clang/include/clang/Driver/ClangOptionDocs.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Compilation.h b/interpreter/llvm-project/clang/include/clang/Driver/Compilation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Compilation.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Compilation.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Distro.h b/interpreter/llvm-project/clang/include/clang/Driver/Distro.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Distro.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Distro.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Driver.h b/interpreter/llvm-project/clang/include/clang/Driver/Driver.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Driver.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Driver.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/DriverDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Driver/DriverDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/DriverDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Driver/DriverDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/InputInfo.h b/interpreter/llvm-project/clang/include/clang/Driver/InputInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/InputInfo.h
rename to interpreter/llvm-project/clang/include/clang/Driver/InputInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Job.h b/interpreter/llvm-project/clang/include/clang/Driver/Job.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Job.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Job.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Multilib.h b/interpreter/llvm-project/clang/include/clang/Driver/Multilib.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Multilib.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Multilib.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/OptionUtils.h b/interpreter/llvm-project/clang/include/clang/Driver/OptionUtils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/OptionUtils.h
rename to interpreter/llvm-project/clang/include/clang/Driver/OptionUtils.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Options.h b/interpreter/llvm-project/clang/include/clang/Driver/Options.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Options.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Options.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Options.td b/interpreter/llvm-project/clang/include/clang/Driver/Options.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Options.td
rename to interpreter/llvm-project/clang/include/clang/Driver/Options.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Phases.h b/interpreter/llvm-project/clang/include/clang/Driver/Phases.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Phases.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Phases.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/SanitizerArgs.h b/interpreter/llvm-project/clang/include/clang/Driver/SanitizerArgs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/SanitizerArgs.h
rename to interpreter/llvm-project/clang/include/clang/Driver/SanitizerArgs.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Tool.h b/interpreter/llvm-project/clang/include/clang/Driver/Tool.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Tool.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Tool.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/ToolChain.h b/interpreter/llvm-project/clang/include/clang/Driver/ToolChain.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/ToolChain.h
rename to interpreter/llvm-project/clang/include/clang/Driver/ToolChain.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Types.def b/interpreter/llvm-project/clang/include/clang/Driver/Types.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Types.def
rename to interpreter/llvm-project/clang/include/clang/Driver/Types.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Types.h b/interpreter/llvm-project/clang/include/clang/Driver/Types.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Types.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Types.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/Util.h b/interpreter/llvm-project/clang/include/clang/Driver/Util.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/Util.h
rename to interpreter/llvm-project/clang/include/clang/Driver/Util.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Driver/XRayArgs.h b/interpreter/llvm-project/clang/include/clang/Driver/XRayArgs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Driver/XRayArgs.h
rename to interpreter/llvm-project/clang/include/clang/Driver/XRayArgs.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Edit/Commit.h b/interpreter/llvm-project/clang/include/clang/Edit/Commit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Edit/Commit.h
rename to interpreter/llvm-project/clang/include/clang/Edit/Commit.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Edit/EditedSource.h b/interpreter/llvm-project/clang/include/clang/Edit/EditedSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Edit/EditedSource.h
rename to interpreter/llvm-project/clang/include/clang/Edit/EditedSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Edit/EditsReceiver.h b/interpreter/llvm-project/clang/include/clang/Edit/EditsReceiver.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Edit/EditsReceiver.h
rename to interpreter/llvm-project/clang/include/clang/Edit/EditsReceiver.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Edit/FileOffset.h b/interpreter/llvm-project/clang/include/clang/Edit/FileOffset.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Edit/FileOffset.h
rename to interpreter/llvm-project/clang/include/clang/Edit/FileOffset.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Edit/Rewriters.h b/interpreter/llvm-project/clang/include/clang/Edit/Rewriters.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Edit/Rewriters.h
rename to interpreter/llvm-project/clang/include/clang/Edit/Rewriters.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Format/Format.h b/interpreter/llvm-project/clang/include/clang/Format/Format.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Format/Format.h
rename to interpreter/llvm-project/clang/include/clang/Format/Format.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/ASTConsumers.h b/interpreter/llvm-project/clang/include/clang/Frontend/ASTConsumers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/ASTConsumers.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/ASTConsumers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/ASTUnit.h b/interpreter/llvm-project/clang/include/clang/Frontend/ASTUnit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/ASTUnit.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/ASTUnit.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/ChainedDiagnosticConsumer.h b/interpreter/llvm-project/clang/include/clang/Frontend/ChainedDiagnosticConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/ChainedDiagnosticConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/ChainedDiagnosticConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/CommandLineSourceLoc.h b/interpreter/llvm-project/clang/include/clang/Frontend/CommandLineSourceLoc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/CommandLineSourceLoc.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/CommandLineSourceLoc.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/CompilerInstance.h b/interpreter/llvm-project/clang/include/clang/Frontend/CompilerInstance.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/CompilerInstance.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/CompilerInstance.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/CompilerInvocation.h b/interpreter/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/CompilerInvocation.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/CompilerInvocation.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/DependencyOutputOptions.h b/interpreter/llvm-project/clang/include/clang/Frontend/DependencyOutputOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/DependencyOutputOptions.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/DependencyOutputOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/DiagnosticRenderer.h b/interpreter/llvm-project/clang/include/clang/Frontend/DiagnosticRenderer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/DiagnosticRenderer.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/DiagnosticRenderer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendAction.h b/interpreter/llvm-project/clang/include/clang/Frontend/FrontendAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendAction.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/FrontendAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendActions.h b/interpreter/llvm-project/clang/include/clang/Frontend/FrontendActions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendActions.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/FrontendActions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Frontend/FrontendDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/FrontendDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendOptions.h b/interpreter/llvm-project/clang/include/clang/Frontend/FrontendOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendOptions.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/FrontendOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendPluginRegistry.h b/interpreter/llvm-project/clang/include/clang/Frontend/FrontendPluginRegistry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/FrontendPluginRegistry.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/FrontendPluginRegistry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/LayoutOverrideSource.h b/interpreter/llvm-project/clang/include/clang/Frontend/LayoutOverrideSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/LayoutOverrideSource.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/LayoutOverrideSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/LogDiagnosticPrinter.h b/interpreter/llvm-project/clang/include/clang/Frontend/LogDiagnosticPrinter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/LogDiagnosticPrinter.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/LogDiagnosticPrinter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/MigratorOptions.h b/interpreter/llvm-project/clang/include/clang/Frontend/MigratorOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/MigratorOptions.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/MigratorOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/MultiplexConsumer.h b/interpreter/llvm-project/clang/include/clang/Frontend/MultiplexConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/MultiplexConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/MultiplexConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/PCHContainerOperations.h b/interpreter/llvm-project/clang/include/clang/Frontend/PCHContainerOperations.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/PCHContainerOperations.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/PCHContainerOperations.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/PrecompiledPreamble.h b/interpreter/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/PrecompiledPreamble.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/PrecompiledPreamble.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/PreprocessorOutputOptions.h b/interpreter/llvm-project/clang/include/clang/Frontend/PreprocessorOutputOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/PreprocessorOutputOptions.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/PreprocessorOutputOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnosticPrinter.h b/interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnosticPrinter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnosticPrinter.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnosticPrinter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnosticReader.h b/interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnosticReader.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnosticReader.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnosticReader.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnostics.h b/interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnostics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/SerializedDiagnostics.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/SerializedDiagnostics.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnosticBuffer.h b/interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnosticBuffer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnosticBuffer.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnosticBuffer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnosticPrinter.h b/interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnosticPrinter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/TextDiagnosticPrinter.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/TextDiagnosticPrinter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/Utils.h b/interpreter/llvm-project/clang/include/clang/Frontend/Utils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/Utils.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/Utils.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Frontend/VerifyDiagnosticConsumer.h b/interpreter/llvm-project/clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/FrontendTool/Utils.h b/interpreter/llvm-project/clang/include/clang/FrontendTool/Utils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/FrontendTool/Utils.h
rename to interpreter/llvm-project/clang/include/clang/FrontendTool/Utils.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/CommentToXML.h b/interpreter/llvm-project/clang/include/clang/Index/CommentToXML.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/CommentToXML.h
rename to interpreter/llvm-project/clang/include/clang/Index/CommentToXML.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/DeclOccurrence.h b/interpreter/llvm-project/clang/include/clang/Index/DeclOccurrence.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/DeclOccurrence.h
rename to interpreter/llvm-project/clang/include/clang/Index/DeclOccurrence.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/IndexDataConsumer.h b/interpreter/llvm-project/clang/include/clang/Index/IndexDataConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/IndexDataConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Index/IndexDataConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/IndexSymbol.h b/interpreter/llvm-project/clang/include/clang/Index/IndexSymbol.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/IndexSymbol.h
rename to interpreter/llvm-project/clang/include/clang/Index/IndexSymbol.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/IndexingAction.h b/interpreter/llvm-project/clang/include/clang/Index/IndexingAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/IndexingAction.h
rename to interpreter/llvm-project/clang/include/clang/Index/IndexingAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/IndexingOptions.h b/interpreter/llvm-project/clang/include/clang/Index/IndexingOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/IndexingOptions.h
rename to interpreter/llvm-project/clang/include/clang/Index/IndexingOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Index/USRGeneration.h b/interpreter/llvm-project/clang/include/clang/Index/USRGeneration.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Index/USRGeneration.h
rename to interpreter/llvm-project/clang/include/clang/Index/USRGeneration.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/IndexSerialization/SerializablePathCollection.h b/interpreter/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/IndexSerialization/SerializablePathCollection.h
rename to interpreter/llvm-project/clang/include/clang/IndexSerialization/SerializablePathCollection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Interpreter/Interpreter.h b/interpreter/llvm-project/clang/include/clang/Interpreter/Interpreter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Interpreter/Interpreter.h
rename to interpreter/llvm-project/clang/include/clang/Interpreter/Interpreter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Interpreter/PartialTranslationUnit.h b/interpreter/llvm-project/clang/include/clang/Interpreter/PartialTranslationUnit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Interpreter/PartialTranslationUnit.h
rename to interpreter/llvm-project/clang/include/clang/Interpreter/PartialTranslationUnit.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/CodeCompletionHandler.h b/interpreter/llvm-project/clang/include/clang/Lex/CodeCompletionHandler.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/CodeCompletionHandler.h
rename to interpreter/llvm-project/clang/include/clang/Lex/CodeCompletionHandler.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h b/interpreter/llvm-project/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
rename to interpreter/llvm-project/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/DirectoryLookup.h b/interpreter/llvm-project/clang/include/clang/Lex/DirectoryLookup.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/DirectoryLookup.h
rename to interpreter/llvm-project/clang/include/clang/Lex/DirectoryLookup.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/ExternalPreprocessorSource.h b/interpreter/llvm-project/clang/include/clang/Lex/ExternalPreprocessorSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/ExternalPreprocessorSource.h
rename to interpreter/llvm-project/clang/include/clang/Lex/ExternalPreprocessorSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderMap.h b/interpreter/llvm-project/clang/include/clang/Lex/HeaderMap.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderMap.h
rename to interpreter/llvm-project/clang/include/clang/Lex/HeaderMap.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderMapTypes.h b/interpreter/llvm-project/clang/include/clang/Lex/HeaderMapTypes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderMapTypes.h
rename to interpreter/llvm-project/clang/include/clang/Lex/HeaderMapTypes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderSearch.h b/interpreter/llvm-project/clang/include/clang/Lex/HeaderSearch.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderSearch.h
rename to interpreter/llvm-project/clang/include/clang/Lex/HeaderSearch.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderSearchOptions.h b/interpreter/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/HeaderSearchOptions.h
rename to interpreter/llvm-project/clang/include/clang/Lex/HeaderSearchOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/LexDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Lex/LexDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/LexDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Lex/LexDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/Lexer.h b/interpreter/llvm-project/clang/include/clang/Lex/Lexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/Lexer.h
rename to interpreter/llvm-project/clang/include/clang/Lex/Lexer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/LiteralSupport.h b/interpreter/llvm-project/clang/include/clang/Lex/LiteralSupport.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/LiteralSupport.h
rename to interpreter/llvm-project/clang/include/clang/Lex/LiteralSupport.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/MacroArgs.h b/interpreter/llvm-project/clang/include/clang/Lex/MacroArgs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/MacroArgs.h
rename to interpreter/llvm-project/clang/include/clang/Lex/MacroArgs.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/MacroInfo.h b/interpreter/llvm-project/clang/include/clang/Lex/MacroInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/MacroInfo.h
rename to interpreter/llvm-project/clang/include/clang/Lex/MacroInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/ModuleLoader.h b/interpreter/llvm-project/clang/include/clang/Lex/ModuleLoader.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/ModuleLoader.h
rename to interpreter/llvm-project/clang/include/clang/Lex/ModuleLoader.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/ModuleMap.h b/interpreter/llvm-project/clang/include/clang/Lex/ModuleMap.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/ModuleMap.h
rename to interpreter/llvm-project/clang/include/clang/Lex/ModuleMap.h
index 41f85a1f572d7..26ed708c49eff 100644
--- a/interpreter/llvm/src/tools/clang/include/clang/Lex/ModuleMap.h
+++ b/interpreter/llvm-project/clang/include/clang/Lex/ModuleMap.h
@@ -241,9 +241,12 @@ class ModuleMap {
     /// and headers from used modules.
     unsigned NoUndeclaredIncludes : 1;
 
+    /// Whether we can have a submodule with missing header files.
+    unsigned IsOptional : 1;
+
     Attributes()
         : IsSystem(false), IsExternC(false), IsExhaustive(false),
-          NoUndeclaredIncludes(false) {}
+          NoUndeclaredIncludes(false), IsOptional(false) {}
   };
 
   /// A directory for which framework modules can be inferred.
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/MultipleIncludeOpt.h b/interpreter/llvm-project/clang/include/clang/Lex/MultipleIncludeOpt.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/MultipleIncludeOpt.h
rename to interpreter/llvm-project/clang/include/clang/Lex/MultipleIncludeOpt.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PPCallbacks.h b/interpreter/llvm-project/clang/include/clang/Lex/PPCallbacks.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PPCallbacks.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PPCallbacks.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PPConditionalDirectiveRecord.h b/interpreter/llvm-project/clang/include/clang/Lex/PPConditionalDirectiveRecord.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PPConditionalDirectiveRecord.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PPConditionalDirectiveRecord.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/Pragma.h b/interpreter/llvm-project/clang/include/clang/Lex/Pragma.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/Pragma.h
rename to interpreter/llvm-project/clang/include/clang/Lex/Pragma.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessingRecord.h b/interpreter/llvm-project/clang/include/clang/Lex/PreprocessingRecord.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessingRecord.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PreprocessingRecord.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/Preprocessor.h b/interpreter/llvm-project/clang/include/clang/Lex/Preprocessor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/Preprocessor.h
rename to interpreter/llvm-project/clang/include/clang/Lex/Preprocessor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h b/interpreter/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorLexer.h b/interpreter/llvm-project/clang/include/clang/Lex/PreprocessorLexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorLexer.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PreprocessorLexer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorOptions.h b/interpreter/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/PreprocessorOptions.h
rename to interpreter/llvm-project/clang/include/clang/Lex/PreprocessorOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/ScratchBuffer.h b/interpreter/llvm-project/clang/include/clang/Lex/ScratchBuffer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/ScratchBuffer.h
rename to interpreter/llvm-project/clang/include/clang/Lex/ScratchBuffer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/Token.h b/interpreter/llvm-project/clang/include/clang/Lex/Token.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/Token.h
rename to interpreter/llvm-project/clang/include/clang/Lex/Token.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/TokenConcatenation.h b/interpreter/llvm-project/clang/include/clang/Lex/TokenConcatenation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/TokenConcatenation.h
rename to interpreter/llvm-project/clang/include/clang/Lex/TokenConcatenation.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/TokenLexer.h b/interpreter/llvm-project/clang/include/clang/Lex/TokenLexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/TokenLexer.h
rename to interpreter/llvm-project/clang/include/clang/Lex/TokenLexer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Lex/VariadicMacroSupport.h b/interpreter/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Lex/VariadicMacroSupport.h
rename to interpreter/llvm-project/clang/include/clang/Lex/VariadicMacroSupport.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Parse/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Parse/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/LoopHint.h b/interpreter/llvm-project/clang/include/clang/Parse/LoopHint.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/LoopHint.h
rename to interpreter/llvm-project/clang/include/clang/Parse/LoopHint.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/ParseAST.h b/interpreter/llvm-project/clang/include/clang/Parse/ParseAST.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/ParseAST.h
rename to interpreter/llvm-project/clang/include/clang/Parse/ParseAST.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/ParseDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Parse/ParseDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/ParseDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Parse/ParseDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/Parser.h b/interpreter/llvm-project/clang/include/clang/Parse/Parser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/Parser.h
rename to interpreter/llvm-project/clang/include/clang/Parse/Parser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Parse/RAIIObjectsForParser.h b/interpreter/llvm-project/clang/include/clang/Parse/RAIIObjectsForParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Parse/RAIIObjectsForParser.h
rename to interpreter/llvm-project/clang/include/clang/Parse/RAIIObjectsForParser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/DeltaTree.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/DeltaTree.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/DeltaTree.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/DeltaTree.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/HTMLRewrite.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/HTMLRewrite.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/HTMLRewrite.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/HTMLRewrite.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/RewriteBuffer.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/RewriteBuffer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/RewriteBuffer.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/RewriteBuffer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/RewriteRope.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/RewriteRope.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/RewriteRope.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/RewriteRope.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/Rewriter.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/Rewriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/Rewriter.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/Rewriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/TokenRewriter.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Core/TokenRewriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Core/TokenRewriter.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Core/TokenRewriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/ASTConsumers.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/ASTConsumers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/ASTConsumers.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/ASTConsumers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/FixItRewriter.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/FixItRewriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/FixItRewriter.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/FixItRewriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/FrontendActions.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/FrontendActions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/FrontendActions.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/FrontendActions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/Rewriters.h b/interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/Rewriters.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Rewrite/Frontend/Rewriters.h
rename to interpreter/llvm-project/clang/include/clang/Rewrite/Frontend/Rewriters.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/AnalysisBasedWarnings.h b/interpreter/llvm-project/clang/include/clang/Sema/AnalysisBasedWarnings.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/AnalysisBasedWarnings.h
rename to interpreter/llvm-project/clang/include/clang/Sema/AnalysisBasedWarnings.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Sema/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Sema/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/CXXFieldCollector.h b/interpreter/llvm-project/clang/include/clang/Sema/CXXFieldCollector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/CXXFieldCollector.h
rename to interpreter/llvm-project/clang/include/clang/Sema/CXXFieldCollector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/CleanupInfo.h b/interpreter/llvm-project/clang/include/clang/Sema/CleanupInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/CleanupInfo.h
rename to interpreter/llvm-project/clang/include/clang/Sema/CleanupInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/CodeCompleteConsumer.h b/interpreter/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/CodeCompleteConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/CodeCompleteOptions.h b/interpreter/llvm-project/clang/include/clang/Sema/CodeCompleteOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/CodeCompleteOptions.h
rename to interpreter/llvm-project/clang/include/clang/Sema/CodeCompleteOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/DeclSpec.h b/interpreter/llvm-project/clang/include/clang/Sema/DeclSpec.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/DeclSpec.h
rename to interpreter/llvm-project/clang/include/clang/Sema/DeclSpec.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/DelayedDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/DelayedDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Sema/DelayedDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Designator.h b/interpreter/llvm-project/clang/include/clang/Sema/Designator.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Designator.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Designator.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/ExternalSemaSource.h b/interpreter/llvm-project/clang/include/clang/Sema/ExternalSemaSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/ExternalSemaSource.h
rename to interpreter/llvm-project/clang/include/clang/Sema/ExternalSemaSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/IdentifierResolver.h b/interpreter/llvm-project/clang/include/clang/Sema/IdentifierResolver.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/IdentifierResolver.h
rename to interpreter/llvm-project/clang/include/clang/Sema/IdentifierResolver.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Initialization.h b/interpreter/llvm-project/clang/include/clang/Sema/Initialization.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Initialization.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Initialization.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Lookup.h b/interpreter/llvm-project/clang/include/clang/Sema/Lookup.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Lookup.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Lookup.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/MultiplexExternalSemaSource.h b/interpreter/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/MultiplexExternalSemaSource.h
rename to interpreter/llvm-project/clang/include/clang/Sema/MultiplexExternalSemaSource.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/ObjCMethodList.h b/interpreter/llvm-project/clang/include/clang/Sema/ObjCMethodList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/ObjCMethodList.h
rename to interpreter/llvm-project/clang/include/clang/Sema/ObjCMethodList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Overload.h b/interpreter/llvm-project/clang/include/clang/Sema/Overload.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Overload.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Overload.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Ownership.h b/interpreter/llvm-project/clang/include/clang/Sema/Ownership.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Ownership.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Ownership.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/ParsedAttr.h b/interpreter/llvm-project/clang/include/clang/Sema/ParsedAttr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/ParsedAttr.h
rename to interpreter/llvm-project/clang/include/clang/Sema/ParsedAttr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/ParsedTemplate.h b/interpreter/llvm-project/clang/include/clang/Sema/ParsedTemplate.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/ParsedTemplate.h
rename to interpreter/llvm-project/clang/include/clang/Sema/ParsedTemplate.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Scope.h b/interpreter/llvm-project/clang/include/clang/Sema/Scope.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Scope.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Scope.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/ScopeInfo.h b/interpreter/llvm-project/clang/include/clang/Sema/ScopeInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/ScopeInfo.h
rename to interpreter/llvm-project/clang/include/clang/Sema/ScopeInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Sema.h b/interpreter/llvm-project/clang/include/clang/Sema/Sema.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Sema.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Sema.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaConcept.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaConcept.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaConcept.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaConcept.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaConsumer.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaFixItUtils.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaFixItUtils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaFixItUtils.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaFixItUtils.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaInternal.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaInternal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaInternal.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaInternal.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/SemaLambda.h b/interpreter/llvm-project/clang/include/clang/Sema/SemaLambda.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/SemaLambda.h
rename to interpreter/llvm-project/clang/include/clang/Sema/SemaLambda.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Template.h b/interpreter/llvm-project/clang/include/clang/Sema/Template.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Template.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Template.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/TemplateDeduction.h b/interpreter/llvm-project/clang/include/clang/Sema/TemplateDeduction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/TemplateDeduction.h
rename to interpreter/llvm-project/clang/include/clang/Sema/TemplateDeduction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/TemplateInstCallback.h b/interpreter/llvm-project/clang/include/clang/Sema/TemplateInstCallback.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/TemplateInstCallback.h
rename to interpreter/llvm-project/clang/include/clang/Sema/TemplateInstCallback.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/TypoCorrection.h b/interpreter/llvm-project/clang/include/clang/Sema/TypoCorrection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/TypoCorrection.h
rename to interpreter/llvm-project/clang/include/clang/Sema/TypoCorrection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Sema/Weak.h b/interpreter/llvm-project/clang/include/clang/Sema/Weak.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Sema/Weak.h
rename to interpreter/llvm-project/clang/include/clang/Sema/Weak.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTBitCodes.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTBitCodes.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTBitCodes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTDeserializationListener.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTDeserializationListener.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTDeserializationListener.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTDeserializationListener.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTReader.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTReader.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTReader.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTReader.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTRecordReader.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTRecordReader.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTRecordReader.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTRecordWriter.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTRecordWriter.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTRecordWriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTWriter.h b/interpreter/llvm-project/clang/include/clang/Serialization/ASTWriter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ASTWriter.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ASTWriter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Serialization/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Serialization/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ContinuousRangeMap.h b/interpreter/llvm-project/clang/include/clang/Serialization/ContinuousRangeMap.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ContinuousRangeMap.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ContinuousRangeMap.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/GlobalModuleIndex.h b/interpreter/llvm-project/clang/include/clang/Serialization/GlobalModuleIndex.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/GlobalModuleIndex.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/GlobalModuleIndex.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/InMemoryModuleCache.h b/interpreter/llvm-project/clang/include/clang/Serialization/InMemoryModuleCache.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/InMemoryModuleCache.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/InMemoryModuleCache.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleFile.h b/interpreter/llvm-project/clang/include/clang/Serialization/ModuleFile.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleFile.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ModuleFile.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleFileExtension.h b/interpreter/llvm-project/clang/include/clang/Serialization/ModuleFileExtension.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleFileExtension.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ModuleFileExtension.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleManager.h b/interpreter/llvm-project/clang/include/clang/Serialization/ModuleManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/ModuleManager.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/ModuleManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/PCHContainerOperations.h b/interpreter/llvm-project/clang/include/clang/Serialization/PCHContainerOperations.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/PCHContainerOperations.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/PCHContainerOperations.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/SerializationDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Serialization/SerializationDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/SerializationDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Serialization/SerializationDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Serialization/TypeBitCodes.def b/interpreter/llvm-project/clang/include/clang/Serialization/TypeBitCodes.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Serialization/TypeBitCodes.def
rename to interpreter/llvm-project/clang/include/clang/Serialization/TypeBitCodes.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/CheckerBase.td b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/CheckerBase.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/CheckerBase.td
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/CheckerBase.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/MPIFunctionClassifier.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/MPIFunctionClassifier.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/MPIFunctionClassifier.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/MPIFunctionClassifier.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/Analyses.def b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/Analyses.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/Analyses.def
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/Analyses.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/Checker.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/Checker.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/CheckerRegistryData.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/CheckerRegistryData.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/CheckerRegistryData.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/CheckerRegistryData.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.def b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.def
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/FrontendActions.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h b/interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
rename to interpreter/llvm-project/clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Testing/CommandLineArgs.h b/interpreter/llvm-project/clang/include/clang/Testing/CommandLineArgs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Testing/CommandLineArgs.h
rename to interpreter/llvm-project/clang/include/clang/Testing/CommandLineArgs.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Testing/TestClangConfig.h b/interpreter/llvm-project/clang/include/clang/Testing/TestClangConfig.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Testing/TestClangConfig.h
rename to interpreter/llvm-project/clang/include/clang/Testing/TestClangConfig.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/ASTDiff/ASTDiff.h b/interpreter/llvm-project/clang/include/clang/Tooling/ASTDiff/ASTDiff.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/ASTDiff/ASTDiff.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/ASTDiff/ASTDiff.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/ASTDiff/ASTDiffInternal.h b/interpreter/llvm-project/clang/include/clang/Tooling/ASTDiff/ASTDiffInternal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/ASTDiff/ASTDiffInternal.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/ASTDiff/ASTDiffInternal.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/AllTUsExecution.h b/interpreter/llvm-project/clang/include/clang/Tooling/AllTUsExecution.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/AllTUsExecution.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/AllTUsExecution.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/ArgumentsAdjusters.h b/interpreter/llvm-project/clang/include/clang/Tooling/ArgumentsAdjusters.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/ArgumentsAdjusters.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/ArgumentsAdjusters.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/CommonOptionsParser.h b/interpreter/llvm-project/clang/include/clang/Tooling/CommonOptionsParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/CommonOptionsParser.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/CommonOptionsParser.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/CompilationDatabase.h b/interpreter/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/CompilationDatabase.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/CompilationDatabase.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/CompilationDatabasePluginRegistry.h b/interpreter/llvm-project/clang/include/clang/Tooling/CompilationDatabasePluginRegistry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/CompilationDatabasePluginRegistry.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/CompilationDatabasePluginRegistry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Core/Diagnostic.h b/interpreter/llvm-project/clang/include/clang/Tooling/Core/Diagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Core/Diagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Core/Diagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Core/Replacement.h b/interpreter/llvm-project/clang/include/clang/Tooling/Core/Replacement.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Core/Replacement.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Core/Replacement.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h b/interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h b/interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h b/interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h b/interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/DiagnosticsYaml.h b/interpreter/llvm-project/clang/include/clang/Tooling/DiagnosticsYaml.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/DiagnosticsYaml.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/DiagnosticsYaml.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Execution.h b/interpreter/llvm-project/clang/include/clang/Tooling/Execution.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Execution.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Execution.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/FileMatchTrie.h b/interpreter/llvm-project/clang/include/clang/Tooling/FileMatchTrie.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/FileMatchTrie.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/FileMatchTrie.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/FixIt.h b/interpreter/llvm-project/clang/include/clang/Tooling/FixIt.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/FixIt.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/FixIt.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h b/interpreter/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Inclusions/IncludeStyle.h b/interpreter/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/JSONCompilationDatabase.h b/interpreter/llvm-project/clang/include/clang/Tooling/JSONCompilationDatabase.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/JSONCompilationDatabase.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/JSONCompilationDatabase.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/NodeIntrospection.h b/interpreter/llvm-project/clang/include/clang/Tooling/NodeIntrospection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/NodeIntrospection.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/NodeIntrospection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/ASTSelection.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/ASTSelection.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/ASTSelection.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/ASTSelection.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/AtomicChange.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/AtomicChange.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Extract/Extract.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Extract/Extract.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Extract/Extract.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Extract/Extract.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Extract/SourceExtraction.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Extract/SourceExtraction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Extract/SourceExtraction.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Extract/SourceExtraction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Lookup.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Lookup.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Lookup.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Lookup.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringAction.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringAction.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRule.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRule.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRule.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRule.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringDiagnostic.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringDiagnostic.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOption.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOption.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOption.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOption.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringOptions.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRFinder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRFindingAction.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h b/interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Refactoring/Rename/USRLocFinder.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/RefactoringCallbacks.h b/interpreter/llvm-project/clang/include/clang/Tooling/RefactoringCallbacks.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/RefactoringCallbacks.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/RefactoringCallbacks.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/ReplacementsYaml.h b/interpreter/llvm-project/clang/include/clang/Tooling/ReplacementsYaml.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/ReplacementsYaml.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/ReplacementsYaml.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/StandaloneExecution.h b/interpreter/llvm-project/clang/include/clang/Tooling/StandaloneExecution.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/StandaloneExecution.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/StandaloneExecution.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/BuildTree.h b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/BuildTree.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/BuildTree.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/CMakeLists.txt b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/CMakeLists.txt
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Mutations.h b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Mutations.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Mutations.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Mutations.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Nodes.h b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Nodes.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Nodes.td b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Nodes.td
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Nodes.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Syntax.td b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Syntax.td
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Syntax.td
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Tokens.h b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Tokens.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Tokens.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Tree.h b/interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Syntax/Tree.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Syntax/Tree.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/ToolExecutorPluginRegistry.h b/interpreter/llvm-project/clang/include/clang/Tooling/ToolExecutorPluginRegistry.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/ToolExecutorPluginRegistry.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/ToolExecutorPluginRegistry.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Tooling.h b/interpreter/llvm-project/clang/include/clang/Tooling/Tooling.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Tooling.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Tooling.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/MatchConsumer.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/MatchConsumer.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/MatchConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Parsing.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Parsing.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Parsing.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Parsing.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/RangeSelector.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/RangeSelector.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/RangeSelector.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/RewriteRule.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/RewriteRule.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/RewriteRule.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/SourceCode.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/SourceCode.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/SourceCode.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/SourceCode.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Stencil.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Stencil.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Stencil.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Transformer.h b/interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Transformer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/Tooling/Transformer/Transformer.h
rename to interpreter/llvm-project/clang/include/clang/Tooling/Transformer/Transformer.h
diff --git a/interpreter/llvm/src/tools/clang/include/clang/module.modulemap b/interpreter/llvm-project/clang/include/clang/module.modulemap
similarity index 100%
rename from interpreter/llvm/src/tools/clang/include/clang/module.modulemap
rename to interpreter/llvm-project/clang/include/clang/module.modulemap
diff --git a/interpreter/llvm/src/tools/clang/lib/APINotes/APINotesFormat.h b/interpreter/llvm-project/clang/lib/APINotes/APINotesFormat.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/APINotes/APINotesFormat.h
rename to interpreter/llvm-project/clang/lib/APINotes/APINotesFormat.h
diff --git a/interpreter/llvm/src/tools/clang/lib/APINotes/APINotesTypes.cpp b/interpreter/llvm-project/clang/lib/APINotes/APINotesTypes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/APINotes/APINotesTypes.cpp
rename to interpreter/llvm-project/clang/lib/APINotes/APINotesTypes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/APINotes/APINotesYAMLCompiler.cpp b/interpreter/llvm-project/clang/lib/APINotes/APINotesYAMLCompiler.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/APINotes/APINotesYAMLCompiler.cpp
rename to interpreter/llvm-project/clang/lib/APINotes/APINotesYAMLCompiler.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/APINotes/CMakeLists.txt b/interpreter/llvm-project/clang/lib/APINotes/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/APINotes/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/APINotes/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/ARCMT.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/ARCMT.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/ARCMT.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/ARCMT.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/ARCMTActions.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/ARCMTActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/ARCMTActions.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/ARCMTActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/CMakeLists.txt b/interpreter/llvm-project/clang/lib/ARCMigrate/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/ARCMigrate/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/FileRemapper.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/FileRemapper.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/FileRemapper.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/FileRemapper.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/Internals.h b/interpreter/llvm-project/clang/lib/ARCMigrate/Internals.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/Internals.h
rename to interpreter/llvm-project/clang/lib/ARCMigrate/Internals.h
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/ObjCMT.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/ObjCMT.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/ObjCMT.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/ObjCMT.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/PlistReporter.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/PlistReporter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/PlistReporter.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/PlistReporter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransAPIUses.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransAPIUses.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransAPIUses.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransAPIUses.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransARCAssign.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransARCAssign.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransARCAssign.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransARCAssign.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransAutoreleasePool.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransAutoreleasePool.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransAutoreleasePool.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransAutoreleasePool.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransBlockObjCVariable.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransBlockObjCVariable.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransBlockObjCVariable.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransBlockObjCVariable.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransGCAttrs.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransGCAttrs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransGCAttrs.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransGCAttrs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransGCCalls.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransGCCalls.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransGCCalls.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransGCCalls.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransProperties.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransProperties.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransProperties.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransProperties.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransProtectedScope.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransProtectedScope.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransProtectedScope.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransProtectedScope.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransRetainReleaseDealloc.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransUnusedInitDelegate.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransUnusedInitDelegate.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransUnusedInitDelegate.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransUnusedInitDelegate.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransformActions.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/TransformActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/TransformActions.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/TransformActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/Transforms.cpp b/interpreter/llvm-project/clang/lib/ARCMigrate/Transforms.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/Transforms.cpp
rename to interpreter/llvm-project/clang/lib/ARCMigrate/Transforms.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ARCMigrate/Transforms.h b/interpreter/llvm-project/clang/lib/ARCMigrate/Transforms.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ARCMigrate/Transforms.h
rename to interpreter/llvm-project/clang/lib/ARCMigrate/Transforms.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/APValue.cpp b/interpreter/llvm-project/clang/lib/AST/APValue.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/AST/APValue.cpp
rename to interpreter/llvm-project/clang/lib/AST/APValue.cpp
index 9a9233bc1ea74..b2bf04d6280d3 100644
--- a/interpreter/llvm/src/tools/clang/lib/AST/APValue.cpp
+++ b/interpreter/llvm-project/clang/lib/AST/APValue.cpp
@@ -156,10 +156,10 @@ void APValue::LValuePathEntry::Profile(llvm::FoldingSetNodeID &ID) const {
 
 APValue::LValuePathSerializationHelper::LValuePathSerializationHelper(
     ArrayRef Path, QualType ElemTy)
-    : ElemTy((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {}
+    : Ty((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {}
 
 QualType APValue::LValuePathSerializationHelper::getType() {
-  return QualType::getFromOpaquePtr(ElemTy);
+  return QualType::getFromOpaquePtr(Ty);
 }
 
 namespace {
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTConcept.cpp b/interpreter/llvm-project/clang/lib/AST/ASTConcept.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTConcept.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTConcept.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTConsumer.cpp b/interpreter/llvm-project/clang/lib/AST/ASTConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTConsumer.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTContext.cpp b/interpreter/llvm-project/clang/lib/AST/ASTContext.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTContext.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTContext.cpp
index 00ec96abae66d..50484fcf4d8dd 100644
--- a/interpreter/llvm/src/tools/clang/lib/AST/ASTContext.cpp
+++ b/interpreter/llvm-project/clang/lib/AST/ASTContext.cpp
@@ -4597,13 +4597,11 @@ QualType ASTContext::getAttributedType(attr::Kind attrKind,
 /// Retrieve a substitution-result type.
 QualType
 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
-                                         QualType Replacement,
-                                         bool AllowNonCanonical /* = false */
-                                        ) const {
-  if (!AllowNonCanonical) {
-     assert(Replacement.isCanonical()
-            && "replacement types must always be canonical");
-  }
+                                         QualType Replacement) const {
+#if 0
+  assert(Replacement.isCanonical()
+         && "replacement types must always be canonical");
+#endif
 
   llvm::FoldingSetNodeID ID;
   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
@@ -10833,6 +10831,15 @@ GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
 
 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
                                              const VarDecl *VD) {
+  // As an extension for interactive REPLs, make sure constant variables are
+  // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
+  // marking them as internal.
+  if (Context.getLangOpts().CPlusPlus &&
+      VD->getType().isConstQualified() &&
+      !VD->getType().isVolatileQualified() && !VD->isInline() &&
+      !isa(VD) && !VD->getDescribedVarTemplate())
+    return GVA_DiscardableODR;
+
   if (!VD->isExternallyVisible())
     return GVA_Internal;
 
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTDiagnostic.cpp b/interpreter/llvm-project/clang/lib/AST/ASTDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTDiagnostic.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTDumper.cpp b/interpreter/llvm-project/clang/lib/AST/ASTDumper.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTDumper.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTDumper.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTImporter.cpp b/interpreter/llvm-project/clang/lib/AST/ASTImporter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTImporter.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTImporter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTImporterLookupTable.cpp b/interpreter/llvm-project/clang/lib/AST/ASTImporterLookupTable.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTImporterLookupTable.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTImporterLookupTable.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTStructuralEquivalence.cpp b/interpreter/llvm-project/clang/lib/AST/ASTStructuralEquivalence.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTStructuralEquivalence.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTStructuralEquivalence.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ASTTypeTraits.cpp b/interpreter/llvm-project/clang/lib/AST/ASTTypeTraits.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ASTTypeTraits.cpp
rename to interpreter/llvm-project/clang/lib/AST/ASTTypeTraits.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/AttrImpl.cpp b/interpreter/llvm-project/clang/lib/AST/AttrImpl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/AttrImpl.cpp
rename to interpreter/llvm-project/clang/lib/AST/AttrImpl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CMakeLists.txt b/interpreter/llvm-project/clang/lib/AST/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/AST/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CXXABI.h b/interpreter/llvm-project/clang/lib/AST/CXXABI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CXXABI.h
rename to interpreter/llvm-project/clang/lib/AST/CXXABI.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CXXInheritance.cpp b/interpreter/llvm-project/clang/lib/AST/CXXInheritance.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CXXInheritance.cpp
rename to interpreter/llvm-project/clang/lib/AST/CXXInheritance.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Comment.cpp b/interpreter/llvm-project/clang/lib/AST/Comment.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Comment.cpp
rename to interpreter/llvm-project/clang/lib/AST/Comment.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CommentBriefParser.cpp b/interpreter/llvm-project/clang/lib/AST/CommentBriefParser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CommentBriefParser.cpp
rename to interpreter/llvm-project/clang/lib/AST/CommentBriefParser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CommentCommandTraits.cpp b/interpreter/llvm-project/clang/lib/AST/CommentCommandTraits.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CommentCommandTraits.cpp
rename to interpreter/llvm-project/clang/lib/AST/CommentCommandTraits.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CommentLexer.cpp b/interpreter/llvm-project/clang/lib/AST/CommentLexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CommentLexer.cpp
rename to interpreter/llvm-project/clang/lib/AST/CommentLexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CommentParser.cpp b/interpreter/llvm-project/clang/lib/AST/CommentParser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CommentParser.cpp
rename to interpreter/llvm-project/clang/lib/AST/CommentParser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/CommentSema.cpp b/interpreter/llvm-project/clang/lib/AST/CommentSema.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/CommentSema.cpp
rename to interpreter/llvm-project/clang/lib/AST/CommentSema.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ComparisonCategories.cpp b/interpreter/llvm-project/clang/lib/AST/ComparisonCategories.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ComparisonCategories.cpp
rename to interpreter/llvm-project/clang/lib/AST/ComparisonCategories.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ComputeDependence.cpp b/interpreter/llvm-project/clang/lib/AST/ComputeDependence.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ComputeDependence.cpp
rename to interpreter/llvm-project/clang/lib/AST/ComputeDependence.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DataCollection.cpp b/interpreter/llvm-project/clang/lib/AST/DataCollection.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DataCollection.cpp
rename to interpreter/llvm-project/clang/lib/AST/DataCollection.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Decl.cpp b/interpreter/llvm-project/clang/lib/AST/Decl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Decl.cpp
rename to interpreter/llvm-project/clang/lib/AST/Decl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclBase.cpp b/interpreter/llvm-project/clang/lib/AST/DeclBase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclBase.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclBase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclCXX.cpp b/interpreter/llvm-project/clang/lib/AST/DeclCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclCXX.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclFriend.cpp b/interpreter/llvm-project/clang/lib/AST/DeclFriend.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclFriend.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclFriend.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclGroup.cpp b/interpreter/llvm-project/clang/lib/AST/DeclGroup.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclGroup.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclGroup.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclObjC.cpp b/interpreter/llvm-project/clang/lib/AST/DeclObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclObjC.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclOpenMP.cpp b/interpreter/llvm-project/clang/lib/AST/DeclOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclPrinter.cpp b/interpreter/llvm-project/clang/lib/AST/DeclPrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclPrinter.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclPrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclTemplate.cpp b/interpreter/llvm-project/clang/lib/AST/DeclTemplate.cpp
similarity index 98%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclTemplate.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclTemplate.cpp
index 4b1ea6dac0d42..c344a16ab4ce7 100644
--- a/interpreter/llvm/src/tools/clang/lib/AST/DeclTemplate.cpp
+++ b/interpreter/llvm-project/clang/lib/AST/DeclTemplate.cpp
@@ -309,19 +309,17 @@ Decl *RedeclarableTemplateDecl::loadLazySpecializationImpl(
   return getASTContext().getExternalSource()->GetExternalDecl(ID);
 }
 
-bool
+void
 RedeclarableTemplateDecl::loadLazySpecializationsImpl(ArrayRef
                                                       Args,
                                                       TemplateParameterList *TPL) const {
-  bool LoadedSpecialization = false;
   CommonBase *CommonBasePtr = getMostRecentDecl()->getCommonPtr();
   if (auto *Specs = CommonBasePtr->LazySpecializations) {
     unsigned Hash = TemplateArgumentList::ComputeODRHash(Args);
     for (uint32_t I = 0, N = Specs[0].DeclID; I != N; ++I)
       if (Specs[I+1].ODRHash && Specs[I+1].ODRHash == Hash)
-        LoadedSpecialization |= (bool)loadLazySpecializationImpl(Specs[I+1]);
+        (void)loadLazySpecializationImpl(Specs[I+1]);
   }
-  return LoadedSpecialization;
 }
 
 template
@@ -331,7 +329,7 @@ RedeclarableTemplateDecl::findSpecializationImpl(
     ProfileArguments&&... ProfileArgs) {
   using SETraits = SpecEntryTraits;
 
-  (void)loadLazySpecializationsImpl(std::forward(ProfileArgs)...);
+  loadLazySpecializationsImpl(std::forward(ProfileArgs)...);
 
   llvm::FoldingSetNodeID ID;
   EntryType::Profile(ID, std::forward(ProfileArgs)...,
@@ -349,8 +347,11 @@ void RedeclarableTemplateDecl::addSpecializationImpl(
   if (InsertPos) {
 #ifndef NDEBUG
     auto Args = SETraits::getTemplateArgs(Entry);
-    assert(!loadLazySpecializationsImpl(Args) &&
-           "Specialization is already registered as lazy");
+    // Due to hash collisions, it can happen that we load another template
+    // specialization with the same hash. This is fine, as long as the next
+    // call to findSpecializationImpl does not find a matching Decl for the
+    // template arguments.
+    loadLazySpecializationsImpl(Args);
     void *CorrectInsertPos;
     assert(!findSpecializationImpl(Specializations, CorrectInsertPos, Args) &&
            InsertPos == CorrectInsertPos &&
@@ -518,7 +519,8 @@ ClassTemplateDecl::newCommon(ASTContext &C) const {
 ClassTemplateSpecializationDecl *
 ClassTemplateDecl::findSpecialization(ArrayRef Args,
                                       void *&InsertPos) {
-  return findSpecializationImpl(getSpecializations(), InsertPos, Args);
+  auto *Common = getCommonPtr();
+  return findSpecializationImpl(Common->Specializations, InsertPos, Args);
 }
 
 void ClassTemplateDecl::AddSpecialization(ClassTemplateSpecializationDecl *D,
@@ -1235,7 +1237,8 @@ VarTemplateDecl::newCommon(ASTContext &C) const {
 VarTemplateSpecializationDecl *
 VarTemplateDecl::findSpecialization(ArrayRef Args,
                                     void *&InsertPos) {
-  return findSpecializationImpl(getSpecializations(), InsertPos, Args);
+  auto *Common = getCommonPtr();
+  return findSpecializationImpl(Common->Specializations, InsertPos, Args);
 }
 
 void VarTemplateDecl::AddSpecialization(VarTemplateSpecializationDecl *D,
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/DeclarationName.cpp b/interpreter/llvm-project/clang/lib/AST/DeclarationName.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/DeclarationName.cpp
rename to interpreter/llvm-project/clang/lib/AST/DeclarationName.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Expr.cpp b/interpreter/llvm-project/clang/lib/AST/Expr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Expr.cpp
rename to interpreter/llvm-project/clang/lib/AST/Expr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExprCXX.cpp b/interpreter/llvm-project/clang/lib/AST/ExprCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExprCXX.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExprCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExprClassification.cpp b/interpreter/llvm-project/clang/lib/AST/ExprClassification.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExprClassification.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExprClassification.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExprConcepts.cpp b/interpreter/llvm-project/clang/lib/AST/ExprConcepts.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExprConcepts.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExprConcepts.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExprConstant.cpp b/interpreter/llvm-project/clang/lib/AST/ExprConstant.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExprConstant.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExprConstant.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExprObjC.cpp b/interpreter/llvm-project/clang/lib/AST/ExprObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExprObjC.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExprObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExternalASTMerger.cpp b/interpreter/llvm-project/clang/lib/AST/ExternalASTMerger.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExternalASTMerger.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExternalASTMerger.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ExternalASTSource.cpp b/interpreter/llvm-project/clang/lib/AST/ExternalASTSource.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ExternalASTSource.cpp
rename to interpreter/llvm-project/clang/lib/AST/ExternalASTSource.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/FormatString.cpp b/interpreter/llvm-project/clang/lib/AST/FormatString.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/FormatString.cpp
rename to interpreter/llvm-project/clang/lib/AST/FormatString.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/FormatStringParsing.h b/interpreter/llvm-project/clang/lib/AST/FormatStringParsing.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/FormatStringParsing.h
rename to interpreter/llvm-project/clang/lib/AST/FormatStringParsing.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/InheritViz.cpp b/interpreter/llvm-project/clang/lib/AST/InheritViz.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/InheritViz.cpp
rename to interpreter/llvm-project/clang/lib/AST/InheritViz.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Boolean.h b/interpreter/llvm-project/clang/lib/AST/Interp/Boolean.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Boolean.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Boolean.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeEmitter.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeEmitter.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeEmitter.h b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeEmitter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeEmitter.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeEmitter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeExprGen.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeExprGen.h b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeExprGen.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeGenError.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeGenError.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeGenError.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeGenError.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeGenError.h b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeGenError.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeGenError.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeGenError.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeStmtGen.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeStmtGen.h b/interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeStmtGen.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/ByteCodeStmtGen.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/ByteCodeStmtGen.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Context.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Context.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Context.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Context.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Context.h b/interpreter/llvm-project/clang/lib/AST/Interp/Context.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Context.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Context.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Descriptor.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Descriptor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Descriptor.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Descriptor.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Descriptor.h b/interpreter/llvm-project/clang/lib/AST/Interp/Descriptor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Descriptor.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Descriptor.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Disasm.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Disasm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Disasm.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Disasm.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/EvalEmitter.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/EvalEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/EvalEmitter.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/EvalEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/EvalEmitter.h b/interpreter/llvm-project/clang/lib/AST/Interp/EvalEmitter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/EvalEmitter.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/EvalEmitter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Frame.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Frame.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Frame.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Frame.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Frame.h b/interpreter/llvm-project/clang/lib/AST/Interp/Frame.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Frame.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Frame.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Function.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Function.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Function.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Function.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Function.h b/interpreter/llvm-project/clang/lib/AST/Interp/Function.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Function.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Function.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Integral.h b/interpreter/llvm-project/clang/lib/AST/Interp/Integral.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Integral.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Integral.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Interp.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Interp.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Interp.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Interp.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Interp.h b/interpreter/llvm-project/clang/lib/AST/Interp/Interp.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Interp.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Interp.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpBlock.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/InterpBlock.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpBlock.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpBlock.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpBlock.h b/interpreter/llvm-project/clang/lib/AST/Interp/InterpBlock.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpBlock.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpBlock.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpFrame.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/InterpFrame.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpFrame.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpFrame.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpFrame.h b/interpreter/llvm-project/clang/lib/AST/Interp/InterpFrame.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpFrame.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpFrame.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpStack.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/InterpStack.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpStack.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpStack.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpStack.h b/interpreter/llvm-project/clang/lib/AST/Interp/InterpStack.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpStack.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpStack.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpState.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/InterpState.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpState.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpState.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpState.h b/interpreter/llvm-project/clang/lib/AST/Interp/InterpState.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/InterpState.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/InterpState.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Opcode.h b/interpreter/llvm-project/clang/lib/AST/Interp/Opcode.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Opcode.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Opcode.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Opcodes.td b/interpreter/llvm-project/clang/lib/AST/Interp/Opcodes.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Opcodes.td
rename to interpreter/llvm-project/clang/lib/AST/Interp/Opcodes.td
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Pointer.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Pointer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Pointer.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Pointer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Pointer.h b/interpreter/llvm-project/clang/lib/AST/Interp/Pointer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Pointer.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Pointer.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/PrimType.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/PrimType.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/PrimType.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/PrimType.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/PrimType.h b/interpreter/llvm-project/clang/lib/AST/Interp/PrimType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/PrimType.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/PrimType.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Program.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Program.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Program.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Program.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Program.h b/interpreter/llvm-project/clang/lib/AST/Interp/Program.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Program.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Program.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Record.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Record.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Record.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Record.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Record.h b/interpreter/llvm-project/clang/lib/AST/Interp/Record.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Record.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Record.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Source.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/Source.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Source.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/Source.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/Source.h b/interpreter/llvm-project/clang/lib/AST/Interp/Source.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/Source.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/Source.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/State.cpp b/interpreter/llvm-project/clang/lib/AST/Interp/State.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/State.cpp
rename to interpreter/llvm-project/clang/lib/AST/Interp/State.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Interp/State.h b/interpreter/llvm-project/clang/lib/AST/Interp/State.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Interp/State.h
rename to interpreter/llvm-project/clang/lib/AST/Interp/State.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ItaniumCXXABI.cpp b/interpreter/llvm-project/clang/lib/AST/ItaniumCXXABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ItaniumCXXABI.cpp
rename to interpreter/llvm-project/clang/lib/AST/ItaniumCXXABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ItaniumMangle.cpp b/interpreter/llvm-project/clang/lib/AST/ItaniumMangle.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ItaniumMangle.cpp
rename to interpreter/llvm-project/clang/lib/AST/ItaniumMangle.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/JSONNodeDumper.cpp b/interpreter/llvm-project/clang/lib/AST/JSONNodeDumper.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/JSONNodeDumper.cpp
rename to interpreter/llvm-project/clang/lib/AST/JSONNodeDumper.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Linkage.h b/interpreter/llvm-project/clang/lib/AST/Linkage.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Linkage.h
rename to interpreter/llvm-project/clang/lib/AST/Linkage.h
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Mangle.cpp b/interpreter/llvm-project/clang/lib/AST/Mangle.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Mangle.cpp
rename to interpreter/llvm-project/clang/lib/AST/Mangle.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/MicrosoftCXXABI.cpp b/interpreter/llvm-project/clang/lib/AST/MicrosoftCXXABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/MicrosoftCXXABI.cpp
rename to interpreter/llvm-project/clang/lib/AST/MicrosoftCXXABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/MicrosoftMangle.cpp b/interpreter/llvm-project/clang/lib/AST/MicrosoftMangle.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/MicrosoftMangle.cpp
rename to interpreter/llvm-project/clang/lib/AST/MicrosoftMangle.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/NSAPI.cpp b/interpreter/llvm-project/clang/lib/AST/NSAPI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/NSAPI.cpp
rename to interpreter/llvm-project/clang/lib/AST/NSAPI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/NestedNameSpecifier.cpp b/interpreter/llvm-project/clang/lib/AST/NestedNameSpecifier.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/NestedNameSpecifier.cpp
rename to interpreter/llvm-project/clang/lib/AST/NestedNameSpecifier.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ODRHash.cpp b/interpreter/llvm-project/clang/lib/AST/ODRHash.cpp
similarity index 98%
rename from interpreter/llvm/src/tools/clang/lib/AST/ODRHash.cpp
rename to interpreter/llvm-project/clang/lib/AST/ODRHash.cpp
index 174ba52a90cd4..f3aea8ec1e835 100644
--- a/interpreter/llvm/src/tools/clang/lib/AST/ODRHash.cpp
+++ b/interpreter/llvm-project/clang/lib/AST/ODRHash.cpp
@@ -136,22 +136,8 @@ void ODRHash::AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {
 }
 
 void ODRHash::AddTemplateName(TemplateName Name) {
-  auto Kind = Name.getKind();
-  ID.AddInteger(Kind);
-
-  switch (Kind) {
-  case TemplateName::Template:
-    AddDecl(Name.getAsTemplateDecl());
-    break;
-  // TODO: Support these cases.
-  case TemplateName::OverloadedTemplate:
-  case TemplateName::AssumedTemplate:
-  case TemplateName::QualifiedTemplate:
-  case TemplateName::DependentTemplate:
-  case TemplateName::SubstTemplateTemplateParm:
-  case TemplateName::SubstTemplateTemplateParmPack:
-    break;
-  }
+  if (auto *TD = Name.getAsTemplateDecl())
+    AddDecl(TD);
 }
 
 void ODRHash::AddTemplateArgument(TemplateArgument TA) {
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/OSLog.cpp b/interpreter/llvm-project/clang/lib/AST/OSLog.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/OSLog.cpp
rename to interpreter/llvm-project/clang/lib/AST/OSLog.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/OpenMPClause.cpp b/interpreter/llvm-project/clang/lib/AST/OpenMPClause.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/OpenMPClause.cpp
rename to interpreter/llvm-project/clang/lib/AST/OpenMPClause.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ParentMap.cpp b/interpreter/llvm-project/clang/lib/AST/ParentMap.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ParentMap.cpp
rename to interpreter/llvm-project/clang/lib/AST/ParentMap.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ParentMapContext.cpp b/interpreter/llvm-project/clang/lib/AST/ParentMapContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ParentMapContext.cpp
rename to interpreter/llvm-project/clang/lib/AST/ParentMapContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/PrintfFormatString.cpp b/interpreter/llvm-project/clang/lib/AST/PrintfFormatString.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/PrintfFormatString.cpp
rename to interpreter/llvm-project/clang/lib/AST/PrintfFormatString.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/QualTypeNames.cpp b/interpreter/llvm-project/clang/lib/AST/QualTypeNames.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/QualTypeNames.cpp
rename to interpreter/llvm-project/clang/lib/AST/QualTypeNames.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/RawCommentList.cpp b/interpreter/llvm-project/clang/lib/AST/RawCommentList.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/RawCommentList.cpp
rename to interpreter/llvm-project/clang/lib/AST/RawCommentList.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/RecordLayout.cpp b/interpreter/llvm-project/clang/lib/AST/RecordLayout.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/RecordLayout.cpp
rename to interpreter/llvm-project/clang/lib/AST/RecordLayout.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/RecordLayoutBuilder.cpp b/interpreter/llvm-project/clang/lib/AST/RecordLayoutBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/RecordLayoutBuilder.cpp
rename to interpreter/llvm-project/clang/lib/AST/RecordLayoutBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/ScanfFormatString.cpp b/interpreter/llvm-project/clang/lib/AST/ScanfFormatString.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/ScanfFormatString.cpp
rename to interpreter/llvm-project/clang/lib/AST/ScanfFormatString.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/SelectorLocationsKind.cpp b/interpreter/llvm-project/clang/lib/AST/SelectorLocationsKind.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/SelectorLocationsKind.cpp
rename to interpreter/llvm-project/clang/lib/AST/SelectorLocationsKind.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Stmt.cpp b/interpreter/llvm-project/clang/lib/AST/Stmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Stmt.cpp
rename to interpreter/llvm-project/clang/lib/AST/Stmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtCXX.cpp b/interpreter/llvm-project/clang/lib/AST/StmtCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtCXX.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtIterator.cpp b/interpreter/llvm-project/clang/lib/AST/StmtIterator.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtIterator.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtIterator.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtObjC.cpp b/interpreter/llvm-project/clang/lib/AST/StmtObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtObjC.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtOpenMP.cpp b/interpreter/llvm-project/clang/lib/AST/StmtOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtPrinter.cpp b/interpreter/llvm-project/clang/lib/AST/StmtPrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtPrinter.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtPrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtProfile.cpp b/interpreter/llvm-project/clang/lib/AST/StmtProfile.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtProfile.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtProfile.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/StmtViz.cpp b/interpreter/llvm-project/clang/lib/AST/StmtViz.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/StmtViz.cpp
rename to interpreter/llvm-project/clang/lib/AST/StmtViz.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/TemplateBase.cpp b/interpreter/llvm-project/clang/lib/AST/TemplateBase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/TemplateBase.cpp
rename to interpreter/llvm-project/clang/lib/AST/TemplateBase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/TemplateName.cpp b/interpreter/llvm-project/clang/lib/AST/TemplateName.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/TemplateName.cpp
rename to interpreter/llvm-project/clang/lib/AST/TemplateName.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/TextNodeDumper.cpp b/interpreter/llvm-project/clang/lib/AST/TextNodeDumper.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/TextNodeDumper.cpp
rename to interpreter/llvm-project/clang/lib/AST/TextNodeDumper.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/Type.cpp b/interpreter/llvm-project/clang/lib/AST/Type.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/Type.cpp
rename to interpreter/llvm-project/clang/lib/AST/Type.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/TypeLoc.cpp b/interpreter/llvm-project/clang/lib/AST/TypeLoc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/TypeLoc.cpp
rename to interpreter/llvm-project/clang/lib/AST/TypeLoc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/TypePrinter.cpp b/interpreter/llvm-project/clang/lib/AST/TypePrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/TypePrinter.cpp
rename to interpreter/llvm-project/clang/lib/AST/TypePrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/VTTBuilder.cpp b/interpreter/llvm-project/clang/lib/AST/VTTBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/VTTBuilder.cpp
rename to interpreter/llvm-project/clang/lib/AST/VTTBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/AST/VTableBuilder.cpp b/interpreter/llvm-project/clang/lib/AST/VTableBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/AST/VTableBuilder.cpp
rename to interpreter/llvm-project/clang/lib/AST/VTableBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/ASTMatchFinder.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/ASTMatchFinder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/ASTMatchFinder.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/ASTMatchFinder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/ASTMatchersInternal.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/CMakeLists.txt b/interpreter/llvm-project/clang/lib/ASTMatchers/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/ASTMatchers/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Marshallers.h b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Marshallers.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Marshallers.h
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Marshallers.h
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Parser.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Parser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Parser.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Parser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Registry.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Registry.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/Registry.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/Registry.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/ASTMatchers/GtestMatchers.cpp b/interpreter/llvm-project/clang/lib/ASTMatchers/GtestMatchers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/ASTMatchers/GtestMatchers.cpp
rename to interpreter/llvm-project/clang/lib/ASTMatchers/GtestMatchers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/AnalysisDeclContext.cpp b/interpreter/llvm-project/clang/lib/Analysis/AnalysisDeclContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/AnalysisDeclContext.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/AnalysisDeclContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/BodyFarm.cpp b/interpreter/llvm-project/clang/lib/Analysis/BodyFarm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/BodyFarm.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/BodyFarm.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CFG.cpp b/interpreter/llvm-project/clang/lib/Analysis/CFG.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CFG.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CFG.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CFGReachabilityAnalysis.cpp b/interpreter/llvm-project/clang/lib/Analysis/CFGReachabilityAnalysis.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CFGReachabilityAnalysis.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CFGReachabilityAnalysis.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CFGStmtMap.cpp b/interpreter/llvm-project/clang/lib/Analysis/CFGStmtMap.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CFGStmtMap.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CFGStmtMap.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Analysis/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Analysis/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CallGraph.cpp b/interpreter/llvm-project/clang/lib/Analysis/CallGraph.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CallGraph.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CallGraph.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CalledOnceCheck.cpp b/interpreter/llvm-project/clang/lib/Analysis/CalledOnceCheck.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CalledOnceCheck.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CalledOnceCheck.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CloneDetection.cpp b/interpreter/llvm-project/clang/lib/Analysis/CloneDetection.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CloneDetection.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CloneDetection.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CocoaConventions.cpp b/interpreter/llvm-project/clang/lib/Analysis/CocoaConventions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CocoaConventions.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CocoaConventions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/CodeInjector.cpp b/interpreter/llvm-project/clang/lib/Analysis/CodeInjector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/CodeInjector.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/CodeInjector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ConstructionContext.cpp b/interpreter/llvm-project/clang/lib/Analysis/ConstructionContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ConstructionContext.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ConstructionContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/Consumed.cpp b/interpreter/llvm-project/clang/lib/Analysis/Consumed.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/Consumed.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/Consumed.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/Dominators.cpp b/interpreter/llvm-project/clang/lib/Analysis/Dominators.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/Dominators.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/Dominators.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ExprMutationAnalyzer.cpp b/interpreter/llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ExprMutationAnalyzer.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/IssueHash.cpp b/interpreter/llvm-project/clang/lib/Analysis/IssueHash.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/IssueHash.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/IssueHash.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/LiveVariables.cpp b/interpreter/llvm-project/clang/lib/Analysis/LiveVariables.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/LiveVariables.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/LiveVariables.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/MacroExpansionContext.cpp b/interpreter/llvm-project/clang/lib/Analysis/MacroExpansionContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/MacroExpansionContext.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/MacroExpansionContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ObjCNoReturn.cpp b/interpreter/llvm-project/clang/lib/Analysis/ObjCNoReturn.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ObjCNoReturn.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ObjCNoReturn.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/PathDiagnostic.cpp b/interpreter/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/PathDiagnostic.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/PostOrderCFGView.cpp b/interpreter/llvm-project/clang/lib/Analysis/PostOrderCFGView.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/PostOrderCFGView.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/PostOrderCFGView.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ProgramPoint.cpp b/interpreter/llvm-project/clang/lib/Analysis/ProgramPoint.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ProgramPoint.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ProgramPoint.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ReachableCode.cpp b/interpreter/llvm-project/clang/lib/Analysis/ReachableCode.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ReachableCode.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ReachableCode.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/RetainSummaryManager.cpp b/interpreter/llvm-project/clang/lib/Analysis/RetainSummaryManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/RetainSummaryManager.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/RetainSummaryManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafety.cpp b/interpreter/llvm-project/clang/lib/Analysis/ThreadSafety.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafety.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ThreadSafety.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyCommon.cpp b/interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyCommon.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyCommon.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyCommon.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyLogical.cpp b/interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyLogical.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyLogical.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyLogical.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp b/interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyTIL.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/ThreadSafetyTIL.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/UninitializedValues.cpp b/interpreter/llvm-project/clang/lib/Analysis/UninitializedValues.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/UninitializedValues.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/UninitializedValues.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Analysis/plugins/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandling.cpp b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandling.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandlingAnalyzerPlugin.exports b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandlingAnalyzerPlugin.exports
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandlingAnalyzerPlugin.exports
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerDependencyHandling/CheckerDependencyHandlingAnalyzerPlugin.exports
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandling.cpp b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandling.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandlingAnalyzerPlugin.exports b/interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandlingAnalyzerPlugin.exports
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandlingAnalyzerPlugin.exports
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/CheckerOptionHandling/CheckerOptionHandlingAnalyzerPlugin.exports
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/MainCallChecker.cpp b/interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/MainCallChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/MainCallChecker.cpp
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/MainCallChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.exports b/interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.exports
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.exports
rename to interpreter/llvm-project/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.exports
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Attributes.cpp b/interpreter/llvm-project/clang/lib/Basic/Attributes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Attributes.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Attributes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Builtins.cpp b/interpreter/llvm-project/clang/lib/Basic/Builtins.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Builtins.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Builtins.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Basic/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Basic/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/CharInfo.cpp b/interpreter/llvm-project/clang/lib/Basic/CharInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/CharInfo.cpp
rename to interpreter/llvm-project/clang/lib/Basic/CharInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/CodeGenOptions.cpp b/interpreter/llvm-project/clang/lib/Basic/CodeGenOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/CodeGenOptions.cpp
rename to interpreter/llvm-project/clang/lib/Basic/CodeGenOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Cuda.cpp b/interpreter/llvm-project/clang/lib/Basic/Cuda.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Cuda.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Cuda.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/DarwinSDKInfo.cpp b/interpreter/llvm-project/clang/lib/Basic/DarwinSDKInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/DarwinSDKInfo.cpp
rename to interpreter/llvm-project/clang/lib/Basic/DarwinSDKInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Diagnostic.cpp b/interpreter/llvm-project/clang/lib/Basic/Diagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Diagnostic.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Diagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/DiagnosticIDs.cpp b/interpreter/llvm-project/clang/lib/Basic/DiagnosticIDs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/DiagnosticIDs.cpp
rename to interpreter/llvm-project/clang/lib/Basic/DiagnosticIDs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/DiagnosticOptions.cpp b/interpreter/llvm-project/clang/lib/Basic/DiagnosticOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/DiagnosticOptions.cpp
rename to interpreter/llvm-project/clang/lib/Basic/DiagnosticOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/ExpressionTraits.cpp b/interpreter/llvm-project/clang/lib/Basic/ExpressionTraits.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/ExpressionTraits.cpp
rename to interpreter/llvm-project/clang/lib/Basic/ExpressionTraits.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/FileEntry.cpp b/interpreter/llvm-project/clang/lib/Basic/FileEntry.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/FileEntry.cpp
rename to interpreter/llvm-project/clang/lib/Basic/FileEntry.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/FileManager.cpp b/interpreter/llvm-project/clang/lib/Basic/FileManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/FileManager.cpp
rename to interpreter/llvm-project/clang/lib/Basic/FileManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/FileSystemStatCache.cpp b/interpreter/llvm-project/clang/lib/Basic/FileSystemStatCache.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/FileSystemStatCache.cpp
rename to interpreter/llvm-project/clang/lib/Basic/FileSystemStatCache.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/IdentifierTable.cpp b/interpreter/llvm-project/clang/lib/Basic/IdentifierTable.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/IdentifierTable.cpp
rename to interpreter/llvm-project/clang/lib/Basic/IdentifierTable.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/LangOptions.cpp b/interpreter/llvm-project/clang/lib/Basic/LangOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/LangOptions.cpp
rename to interpreter/llvm-project/clang/lib/Basic/LangOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/LangStandards.cpp b/interpreter/llvm-project/clang/lib/Basic/LangStandards.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/LangStandards.cpp
rename to interpreter/llvm-project/clang/lib/Basic/LangStandards.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Module.cpp b/interpreter/llvm-project/clang/lib/Basic/Module.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Module.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Module.cpp
index b6cf1624ef017..ff91ddcc880dd 100644
--- a/interpreter/llvm/src/tools/clang/lib/Basic/Module.cpp
+++ b/interpreter/llvm-project/clang/lib/Basic/Module.cpp
@@ -43,7 +43,7 @@ Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
       IsSystem(false), IsExternC(false), IsInferred(false),
       InferSubmodules(false), InferExplicitSubmodules(false),
       InferExportWildcard(false), ConfigMacrosExhaustive(false),
-      NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
+      NoUndeclaredIncludes(false), IsOptional(false), ModuleMapIsPrivate(false),
       NameVisibility(Hidden) {
   if (Parent) {
     IsAvailable = Parent->isAvailable();
@@ -51,6 +51,7 @@ Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
     IsSystem = Parent->IsSystem;
     IsExternC = Parent->IsExternC;
     NoUndeclaredIncludes = Parent->NoUndeclaredIncludes;
+    IsOptional = Parent->IsOptional;
     ModuleMapIsPrivate = Parent->ModuleMapIsPrivate;
 
     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
@@ -108,6 +109,7 @@ static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
                         .Case("cplusplus11", LangOpts.CPlusPlus11)
                         .Case("cplusplus14", LangOpts.CPlusPlus14)
                         .Case("cplusplus17", LangOpts.CPlusPlus17)
+                        .Case("cplusplus20", LangOpts.CPlusPlus20)
                         .Case("c99", LangOpts.C99)
                         .Case("c11", LangOpts.C11)
                         .Case("c17", LangOpts.C17)
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/NoSanitizeList.cpp b/interpreter/llvm-project/clang/lib/Basic/NoSanitizeList.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/NoSanitizeList.cpp
rename to interpreter/llvm-project/clang/lib/Basic/NoSanitizeList.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/ObjCRuntime.cpp b/interpreter/llvm-project/clang/lib/Basic/ObjCRuntime.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/ObjCRuntime.cpp
rename to interpreter/llvm-project/clang/lib/Basic/ObjCRuntime.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/OpenCLOptions.cpp b/interpreter/llvm-project/clang/lib/Basic/OpenCLOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/OpenCLOptions.cpp
rename to interpreter/llvm-project/clang/lib/Basic/OpenCLOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/OpenMPKinds.cpp b/interpreter/llvm-project/clang/lib/Basic/OpenMPKinds.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/OpenMPKinds.cpp
rename to interpreter/llvm-project/clang/lib/Basic/OpenMPKinds.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/OperatorPrecedence.cpp b/interpreter/llvm-project/clang/lib/Basic/OperatorPrecedence.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/OperatorPrecedence.cpp
rename to interpreter/llvm-project/clang/lib/Basic/OperatorPrecedence.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/ProfileList.cpp b/interpreter/llvm-project/clang/lib/Basic/ProfileList.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/ProfileList.cpp
rename to interpreter/llvm-project/clang/lib/Basic/ProfileList.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/SanitizerSpecialCaseList.cpp b/interpreter/llvm-project/clang/lib/Basic/SanitizerSpecialCaseList.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/SanitizerSpecialCaseList.cpp
rename to interpreter/llvm-project/clang/lib/Basic/SanitizerSpecialCaseList.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Sanitizers.cpp b/interpreter/llvm-project/clang/lib/Basic/Sanitizers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Sanitizers.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Sanitizers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/SourceLocation.cpp b/interpreter/llvm-project/clang/lib/Basic/SourceLocation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/SourceLocation.cpp
rename to interpreter/llvm-project/clang/lib/Basic/SourceLocation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/SourceManager.cpp b/interpreter/llvm-project/clang/lib/Basic/SourceManager.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Basic/SourceManager.cpp
rename to interpreter/llvm-project/clang/lib/Basic/SourceManager.cpp
index 42abc2963c2c3..a00edddfa3823 100644
--- a/interpreter/llvm/src/tools/clang/lib/Basic/SourceManager.cpp
+++ b/interpreter/llvm-project/clang/lib/Basic/SourceManager.cpp
@@ -2095,10 +2095,7 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
       return LIsScratch;
     return LOffs.second < ROffs.second;
   }
-  //AXEL: Work around diags from include chains not rooted in main file.
-  //AXEL: llvm_unreachable("Unsortable locations found");
-  assert(0 && "Unsortable locations found");
-  return LOffs.first < ROffs.first;
+  llvm_unreachable("Unsortable locations found");
 }
 
 std::pair SourceManager::isInTheSameTranslationUnit(
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Stack.cpp b/interpreter/llvm-project/clang/lib/Basic/Stack.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Stack.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Stack.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/TargetID.cpp b/interpreter/llvm-project/clang/lib/Basic/TargetID.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/TargetID.cpp
rename to interpreter/llvm-project/clang/lib/Basic/TargetID.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/TargetInfo.cpp b/interpreter/llvm-project/clang/lib/Basic/TargetInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/TargetInfo.cpp
rename to interpreter/llvm-project/clang/lib/Basic/TargetInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets.h b/interpreter/llvm-project/clang/lib/Basic/Targets.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AArch64.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/AArch64.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AArch64.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AArch64.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AArch64.h b/interpreter/llvm-project/clang/lib/Basic/Targets/AArch64.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AArch64.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AArch64.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AMDGPU.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/AMDGPU.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AMDGPU.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AMDGPU.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AMDGPU.h b/interpreter/llvm-project/clang/lib/Basic/Targets/AMDGPU.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AMDGPU.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AMDGPU.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARC.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/ARC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARC.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/ARC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARC.h b/interpreter/llvm-project/clang/lib/Basic/Targets/ARC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARC.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/ARC.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARM.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/ARM.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARM.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/ARM.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARM.h b/interpreter/llvm-project/clang/lib/Basic/Targets/ARM.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/ARM.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/ARM.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AVR.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/AVR.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AVR.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AVR.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/AVR.h b/interpreter/llvm-project/clang/lib/Basic/Targets/AVR.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/AVR.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/AVR.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/BPF.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/BPF.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/BPF.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/BPF.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/BPF.h b/interpreter/llvm-project/clang/lib/Basic/Targets/BPF.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/BPF.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/BPF.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Hexagon.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/Hexagon.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Hexagon.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Hexagon.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Hexagon.h b/interpreter/llvm-project/clang/lib/Basic/Targets/Hexagon.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Hexagon.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Hexagon.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Lanai.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/Lanai.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Lanai.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Lanai.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Lanai.h b/interpreter/llvm-project/clang/lib/Basic/Targets/Lanai.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Lanai.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Lanai.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Le64.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/Le64.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Le64.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Le64.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Le64.h b/interpreter/llvm-project/clang/lib/Basic/Targets/Le64.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Le64.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Le64.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/M68k.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/M68k.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/M68k.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/M68k.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/M68k.h b/interpreter/llvm-project/clang/lib/Basic/Targets/M68k.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/M68k.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/M68k.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/MSP430.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/MSP430.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/MSP430.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/MSP430.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/MSP430.h b/interpreter/llvm-project/clang/lib/Basic/Targets/MSP430.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/MSP430.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/MSP430.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Mips.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/Mips.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Mips.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Mips.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Mips.h b/interpreter/llvm-project/clang/lib/Basic/Targets/Mips.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Mips.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Mips.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/NVPTX.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/NVPTX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/NVPTX.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/NVPTX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/NVPTX.h b/interpreter/llvm-project/clang/lib/Basic/Targets/NVPTX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/NVPTX.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/NVPTX.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/OSTargets.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/OSTargets.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/OSTargets.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/OSTargets.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/OSTargets.h b/interpreter/llvm-project/clang/lib/Basic/Targets/OSTargets.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/OSTargets.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/OSTargets.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/PNaCl.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/PNaCl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/PNaCl.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/PNaCl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/PNaCl.h b/interpreter/llvm-project/clang/lib/Basic/Targets/PNaCl.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/PNaCl.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/PNaCl.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/PPC.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/PPC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/PPC.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/PPC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/PPC.h b/interpreter/llvm-project/clang/lib/Basic/Targets/PPC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/PPC.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/PPC.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/RISCV.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/RISCV.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/RISCV.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/RISCV.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/RISCV.h b/interpreter/llvm-project/clang/lib/Basic/Targets/RISCV.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/RISCV.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/RISCV.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/SPIR.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/SPIR.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/SPIR.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/SPIR.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/SPIR.h b/interpreter/llvm-project/clang/lib/Basic/Targets/SPIR.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/SPIR.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/SPIR.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Sparc.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/Sparc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Sparc.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Sparc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/Sparc.h b/interpreter/llvm-project/clang/lib/Basic/Targets/Sparc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/Sparc.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/Sparc.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/SystemZ.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/SystemZ.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/SystemZ.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/SystemZ.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/SystemZ.h b/interpreter/llvm-project/clang/lib/Basic/Targets/SystemZ.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/SystemZ.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/SystemZ.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/TCE.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/TCE.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/TCE.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/TCE.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/TCE.h b/interpreter/llvm-project/clang/lib/Basic/Targets/TCE.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/TCE.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/TCE.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/VE.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/VE.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/VE.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/VE.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/VE.h b/interpreter/llvm-project/clang/lib/Basic/Targets/VE.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/VE.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/VE.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/WebAssembly.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/WebAssembly.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/WebAssembly.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/WebAssembly.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/WebAssembly.h b/interpreter/llvm-project/clang/lib/Basic/Targets/WebAssembly.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/WebAssembly.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/WebAssembly.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/X86.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/X86.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/X86.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/X86.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/X86.h b/interpreter/llvm-project/clang/lib/Basic/Targets/X86.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/X86.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/X86.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/XCore.cpp b/interpreter/llvm-project/clang/lib/Basic/Targets/XCore.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/XCore.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Targets/XCore.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Targets/XCore.h b/interpreter/llvm-project/clang/lib/Basic/Targets/XCore.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Targets/XCore.h
rename to interpreter/llvm-project/clang/lib/Basic/Targets/XCore.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/TokenKinds.cpp b/interpreter/llvm-project/clang/lib/Basic/TokenKinds.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/TokenKinds.cpp
rename to interpreter/llvm-project/clang/lib/Basic/TokenKinds.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/TypeTraits.cpp b/interpreter/llvm-project/clang/lib/Basic/TypeTraits.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/TypeTraits.cpp
rename to interpreter/llvm-project/clang/lib/Basic/TypeTraits.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Version.cpp b/interpreter/llvm-project/clang/lib/Basic/Version.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Version.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Version.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/Warnings.cpp b/interpreter/llvm-project/clang/lib/Basic/Warnings.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/Warnings.cpp
rename to interpreter/llvm-project/clang/lib/Basic/Warnings.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/XRayInstr.cpp b/interpreter/llvm-project/clang/lib/Basic/XRayInstr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/XRayInstr.cpp
rename to interpreter/llvm-project/clang/lib/Basic/XRayInstr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Basic/XRayLists.cpp b/interpreter/llvm-project/clang/lib/Basic/XRayLists.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Basic/XRayLists.cpp
rename to interpreter/llvm-project/clang/lib/Basic/XRayLists.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CMakeLists.txt b/interpreter/llvm-project/clang/lib/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ABIInfo.h b/interpreter/llvm-project/clang/lib/CodeGen/ABIInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ABIInfo.h
rename to interpreter/llvm-project/clang/lib/CodeGen/ABIInfo.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/Address.h b/interpreter/llvm-project/clang/lib/CodeGen/Address.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/Address.h
rename to interpreter/llvm-project/clang/lib/CodeGen/Address.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/BackendUtil.cpp b/interpreter/llvm-project/clang/lib/CodeGen/BackendUtil.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/BackendUtil.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/BackendUtil.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGAtomic.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGAtomic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGAtomic.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGAtomic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGBlocks.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGBlocks.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGBlocks.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGBlocks.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGBlocks.h b/interpreter/llvm-project/clang/lib/CodeGen/CGBlocks.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGBlocks.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGBlocks.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGBuilder.h b/interpreter/llvm-project/clang/lib/CodeGen/CGBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGBuilder.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGBuiltin.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGBuiltin.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDANV.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDANV.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDARuntime.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCUDARuntime.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDARuntime.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCUDARuntime.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDARuntime.h b/interpreter/llvm-project/clang/lib/CodeGen/CGCUDARuntime.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCUDARuntime.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCUDARuntime.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXX.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXX.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXXABI.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCXXABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXXABI.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCXXABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXXABI.h b/interpreter/llvm-project/clang/lib/CodeGen/CGCXXABI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCXXABI.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCXXABI.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCall.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCall.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.h b/interpreter/llvm-project/clang/lib/CodeGen/CGCall.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCall.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCall.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGClass.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGClass.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGClass.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGClass.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCleanup.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCleanup.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCleanup.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCleanup.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCleanup.h b/interpreter/llvm-project/clang/lib/CodeGen/CGCleanup.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCleanup.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCleanup.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGCoroutine.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGCoroutine.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGDebugInfo.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGDebugInfo.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGDebugInfo.h b/interpreter/llvm-project/clang/lib/CodeGen/CGDebugInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGDebugInfo.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGDebugInfo.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGDecl.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGDecl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGDecl.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGDecl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGDeclCXX.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGDeclCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGDeclCXX.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGDeclCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGException.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGException.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGException.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGException.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExpr.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExpr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExpr.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExpr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprAgg.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExprAgg.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprAgg.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExprAgg.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprCXX.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprCXX.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp
index dbbf9b79300ba..f42759e9db502 100644
--- a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/interpreter/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp
@@ -97,9 +97,8 @@ RValue CodeGenFunction::EmitCXXDestructorCall(
   const CXXMethodDecl *DtorDecl = cast(Dtor.getDecl());
 
   assert(!ThisTy.isNull());
-  assert(
-      declaresSameEntity(ThisTy->getAsCXXRecordDecl(), DtorDecl->getParent()) &&
-      "Pointer/Object mixup");
+  assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
+         "Pointer/Object mixup");
 
   LangAS SrcAS = ThisTy.getAddressSpace();
   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprComplex.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExprComplex.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprComplex.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExprComplex.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprConstant.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExprConstant.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprConstant.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExprConstant.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprScalar.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGExprScalar.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGExprScalar.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGExprScalar.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGGPUBuiltin.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGGPUBuiltin.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGGPUBuiltin.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGGPUBuiltin.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGLoopInfo.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGLoopInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGLoopInfo.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGLoopInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGLoopInfo.h b/interpreter/llvm-project/clang/lib/CodeGen/CGLoopInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGLoopInfo.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGLoopInfo.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGNonTrivialStruct.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGNonTrivialStruct.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGNonTrivialStruct.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGNonTrivialStruct.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjC.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjC.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCGNU.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCGNU.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCMac.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGObjCMac.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCMac.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGObjCMac.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCRuntime.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGObjCRuntime.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCRuntime.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGObjCRuntime.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCRuntime.h b/interpreter/llvm-project/clang/lib/CodeGen/CGObjCRuntime.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGObjCRuntime.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGObjCRuntime.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenCLRuntime.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenCLRuntime.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenCLRuntime.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenCLRuntime.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenCLRuntime.h b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenCLRuntime.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenCLRuntime.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenCLRuntime.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntime.h b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntime.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.h b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeAMDGCN.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.h b/interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGRecordLayout.h b/interpreter/llvm-project/clang/lib/CodeGen/CGRecordLayout.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGRecordLayout.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGRecordLayout.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGStmt.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGStmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGStmt.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGStmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTT.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGVTT.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTT.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGVTT.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTables.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CGVTables.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTables.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CGVTables.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTables.h b/interpreter/llvm-project/clang/lib/CodeGen/CGVTables.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGVTables.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGVTables.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CGValue.h b/interpreter/llvm-project/clang/lib/CodeGen/CGValue.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CGValue.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CGValue.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CMakeLists.txt b/interpreter/llvm-project/clang/lib/CodeGen/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/CodeGen/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenABITypes.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenABITypes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenABITypes.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenABITypes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenAction.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenAction.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenFunction.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenFunction.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenFunction.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenFunction.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenFunction.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenFunction.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenModule.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenModule.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp
index 355033225c769..4255578d82087 100644
--- a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1460,7 +1460,6 @@ void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
   // Construct the constructor and destructor arrays.
   ConstantInitBuilder builder(*this);
   auto ctors = builder.beginArray(CtorStructTy);
-
   for (const auto &I : Fns) {
     auto ctor = ctors.beginStruct(CtorStructTy);
     ctor.addInt(Int32Ty, I.Priority);
@@ -2244,9 +2243,7 @@ static void emitUsed(CodeGenModule &CGM, StringRef Name,
 
 void CodeGenModule::emitLLVMUsed() {
   emitUsed(*this, "llvm.used", LLVMUsed);
-  LLVMUsed.clear();
   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
-  LLVMCompilerUsed.clear();
 }
 
 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenModule.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenModule.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenModule.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenModule.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenPGO.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenPGO.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenPGO.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenPGO.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenPGO.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenPGO.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenPGO.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenPGO.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTBAA.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTBAA.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTBAA.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenTBAA.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTBAA.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenTBAA.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypeCache.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypeCache.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypeCache.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypeCache.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypes.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypes.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypes.h b/interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenTypes.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CodeGenTypes.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ConstantEmitter.h b/interpreter/llvm-project/clang/lib/CodeGen/ConstantEmitter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ConstantEmitter.h
rename to interpreter/llvm-project/clang/lib/CodeGen/ConstantEmitter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ConstantInitBuilder.cpp b/interpreter/llvm-project/clang/lib/CodeGen/ConstantInitBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ConstantInitBuilder.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/ConstantInitBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CoverageMappingGen.cpp b/interpreter/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CoverageMappingGen.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/CoverageMappingGen.h b/interpreter/llvm-project/clang/lib/CodeGen/CoverageMappingGen.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/CoverageMappingGen.h
rename to interpreter/llvm-project/clang/lib/CodeGen/CoverageMappingGen.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/EHScopeStack.h b/interpreter/llvm-project/clang/lib/CodeGen/EHScopeStack.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/EHScopeStack.h
rename to interpreter/llvm-project/clang/lib/CodeGen/EHScopeStack.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp b/interpreter/llvm-project/clang/lib/CodeGen/ItaniumCXXABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/ItaniumCXXABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/MacroPPCallbacks.cpp b/interpreter/llvm-project/clang/lib/CodeGen/MacroPPCallbacks.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/MacroPPCallbacks.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/MacroPPCallbacks.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/MacroPPCallbacks.h b/interpreter/llvm-project/clang/lib/CodeGen/MacroPPCallbacks.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/MacroPPCallbacks.h
rename to interpreter/llvm-project/clang/lib/CodeGen/MacroPPCallbacks.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/interpreter/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ModuleBuilder.cpp b/interpreter/llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ModuleBuilder.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp
index 5c1bbf799ff4b..80f3f29d4115a 100644
--- a/interpreter/llvm/src/tools/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/interpreter/llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -531,7 +531,6 @@ void CodeGenerator::forgetDecl(const GlobalDecl& GD,
   static_cast(this)->forgetDecl(GD, MangledName);
 }
 
-
 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
                                          llvm::LLVMContext& C,
                                          const CodeGenOptions& CGO) {
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp b/interpreter/llvm-project/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/PatternInit.cpp b/interpreter/llvm-project/clang/lib/CodeGen/PatternInit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/PatternInit.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/PatternInit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/PatternInit.h b/interpreter/llvm-project/clang/lib/CodeGen/PatternInit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/PatternInit.h
rename to interpreter/llvm-project/clang/lib/CodeGen/PatternInit.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/README.txt b/interpreter/llvm-project/clang/lib/CodeGen/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/README.txt
rename to interpreter/llvm-project/clang/lib/CodeGen/README.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/SanitizerMetadata.cpp b/interpreter/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/SanitizerMetadata.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/SanitizerMetadata.h b/interpreter/llvm-project/clang/lib/CodeGen/SanitizerMetadata.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/SanitizerMetadata.h
rename to interpreter/llvm-project/clang/lib/CodeGen/SanitizerMetadata.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/SwiftCallingConv.cpp b/interpreter/llvm-project/clang/lib/CodeGen/SwiftCallingConv.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/SwiftCallingConv.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/SwiftCallingConv.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/TargetInfo.cpp b/interpreter/llvm-project/clang/lib/CodeGen/TargetInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/TargetInfo.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/TargetInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/TargetInfo.h b/interpreter/llvm-project/clang/lib/CodeGen/TargetInfo.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/TargetInfo.h
rename to interpreter/llvm-project/clang/lib/CodeGen/TargetInfo.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/VarBypassDetector.cpp b/interpreter/llvm-project/clang/lib/CodeGen/VarBypassDetector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/VarBypassDetector.cpp
rename to interpreter/llvm-project/clang/lib/CodeGen/VarBypassDetector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/CodeGen/VarBypassDetector.h b/interpreter/llvm-project/clang/lib/CodeGen/VarBypassDetector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CodeGen/VarBypassDetector.h
rename to interpreter/llvm-project/clang/lib/CodeGen/VarBypassDetector.h
diff --git a/interpreter/llvm/src/tools/clang/lib/CrossTU/CMakeLists.txt b/interpreter/llvm-project/clang/lib/CrossTU/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CrossTU/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/CrossTU/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp b/interpreter/llvm-project/clang/lib/CrossTU/CrossTranslationUnit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp
rename to interpreter/llvm-project/clang/lib/CrossTU/CrossTranslationUnit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/CMakeLists.txt b/interpreter/llvm-project/clang/lib/DirectoryWatcher/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/DirectoryScanner.cpp b/interpreter/llvm-project/clang/lib/DirectoryWatcher/DirectoryScanner.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/DirectoryScanner.cpp
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/DirectoryScanner.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/DirectoryScanner.h b/interpreter/llvm-project/clang/lib/DirectoryWatcher/DirectoryScanner.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/DirectoryScanner.h
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/DirectoryScanner.h
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/default/DirectoryWatcher-not-implemented.cpp b/interpreter/llvm-project/clang/lib/DirectoryWatcher/default/DirectoryWatcher-not-implemented.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/default/DirectoryWatcher-not-implemented.cpp
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/default/DirectoryWatcher-not-implemented.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp b/interpreter/llvm-project/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp b/interpreter/llvm-project/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/windows/DirectoryWatcher-windows.cpp b/interpreter/llvm-project/clang/lib/DirectoryWatcher/windows/DirectoryWatcher-windows.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/DirectoryWatcher/windows/DirectoryWatcher-windows.cpp
rename to interpreter/llvm-project/clang/lib/DirectoryWatcher/windows/DirectoryWatcher-windows.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Action.cpp b/interpreter/llvm-project/clang/lib/Driver/Action.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Action.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Action.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Driver/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Driver/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Compilation.cpp b/interpreter/llvm-project/clang/lib/Driver/Compilation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Compilation.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Compilation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Distro.cpp b/interpreter/llvm-project/clang/lib/Driver/Distro.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Distro.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Distro.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Driver.cpp b/interpreter/llvm-project/clang/lib/Driver/Driver.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Driver.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Driver.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/DriverOptions.cpp b/interpreter/llvm-project/clang/lib/Driver/DriverOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/DriverOptions.cpp
rename to interpreter/llvm-project/clang/lib/Driver/DriverOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Job.cpp b/interpreter/llvm-project/clang/lib/Driver/Job.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Job.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Job.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Multilib.cpp b/interpreter/llvm-project/clang/lib/Driver/Multilib.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Multilib.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Multilib.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/OptionUtils.cpp b/interpreter/llvm-project/clang/lib/Driver/OptionUtils.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/OptionUtils.cpp
rename to interpreter/llvm-project/clang/lib/Driver/OptionUtils.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Phases.cpp b/interpreter/llvm-project/clang/lib/Driver/Phases.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Phases.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Phases.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/SanitizerArgs.cpp b/interpreter/llvm-project/clang/lib/Driver/SanitizerArgs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/SanitizerArgs.cpp
rename to interpreter/llvm-project/clang/lib/Driver/SanitizerArgs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Tool.cpp b/interpreter/llvm-project/clang/lib/Driver/Tool.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Tool.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Tool.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChain.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChain.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChain.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChain.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AIX.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AIX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AIX.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AIX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AIX.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AIX.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AIX.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AIX.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPU.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPU.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPU.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPU.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPU.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPUOpenMP.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AVR.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AVR.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AVR.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/AVR.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/AVR.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/AVR.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Ananas.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Ananas.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Ananas.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Ananas.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Ananas.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Ananas.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Ananas.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Ananas.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/AArch64.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/AArch64.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/AArch64.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/AArch64.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/AArch64.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/ARM.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/ARM.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/ARM.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/ARM.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/ARM.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/ARM.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/ARM.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/M68k.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/M68k.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/M68k.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/M68k.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/M68k.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/M68k.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/M68k.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/M68k.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Mips.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Mips.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Mips.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Mips.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Mips.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Mips.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/PPC.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/PPC.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/PPC.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/PPC.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/RISCV.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/RISCV.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/RISCV.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/RISCV.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/RISCV.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Sparc.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Sparc.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Sparc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/Sparc.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/Sparc.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/SystemZ.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/SystemZ.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/SystemZ.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/SystemZ.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/VE.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/VE.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/VE.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/VE.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/VE.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/VE.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/VE.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/VE.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/X86.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/X86.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/X86.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/X86.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/X86.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/X86.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Arch/X86.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Arch/X86.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/BareMetal.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/BareMetal.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/BareMetal.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/BareMetal.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/BareMetal.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/BareMetal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/BareMetal.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/BareMetal.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Clang.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Clang.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Clang.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Clang.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Clang.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Clang.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CloudABI.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CloudABI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CloudABI.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CloudABI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CloudABI.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CloudABI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CloudABI.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CloudABI.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CommonArgs.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CommonArgs.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Contiki.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Contiki.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Contiki.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Contiki.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Contiki.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Contiki.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Contiki.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Contiki.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CrossWindows.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CrossWindows.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CrossWindows.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CrossWindows.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/CrossWindows.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/CrossWindows.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/CrossWindows.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Cuda.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Cuda.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Cuda.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Cuda.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Cuda.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Cuda.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Darwin.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Darwin.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Darwin.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Darwin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Darwin.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Darwin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/DragonFly.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/DragonFly.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/DragonFly.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/DragonFly.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/DragonFly.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/DragonFly.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/DragonFly.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/DragonFly.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Flang.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Flang.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Flang.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Flang.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Flang.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Flang.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Flang.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Flang.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/FreeBSD.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/FreeBSD.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/FreeBSD.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/FreeBSD.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Fuchsia.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Fuchsia.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Fuchsia.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Fuchsia.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Gnu.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Gnu.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Gnu.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Gnu.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Gnu.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Gnu.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/HIP.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/HIP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/HIP.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/HIP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/HIP.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/HIP.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/HIP.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/HIP.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Haiku.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Haiku.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Haiku.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Haiku.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Haiku.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Haiku.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Haiku.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Haiku.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hexagon.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hexagon.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hexagon.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Hexagon.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hexagon.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Hexagon.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hurd.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Hurd.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hurd.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Hurd.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hurd.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Hurd.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Hurd.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Hurd.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/InterfaceStubs.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/InterfaceStubs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/InterfaceStubs.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/InterfaceStubs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/InterfaceStubs.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/InterfaceStubs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/InterfaceStubs.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/InterfaceStubs.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Lanai.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Lanai.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Lanai.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Lanai.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Linux.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Linux.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Linux.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Linux.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Linux.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Linux.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSP430.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MSP430.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSP430.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MSP430.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSP430.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MSP430.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSP430.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MSP430.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVC.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVC.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVC.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVC.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVC.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVC.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVCSetupApi.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVCSetupApi.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MSVCSetupApi.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MSVCSetupApi.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MinGW.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MinGW.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MinGW.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MinGW.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MinGW.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MinGW.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Minix.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Minix.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Minix.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Minix.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Minix.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Minix.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Minix.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Minix.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MipsLinux.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MipsLinux.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MipsLinux.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MipsLinux.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/MipsLinux.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/MipsLinux.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/MipsLinux.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Myriad.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Myriad.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Myriad.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Myriad.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Myriad.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Myriad.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Myriad.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Myriad.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NaCl.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/NaCl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NaCl.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/NaCl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NaCl.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/NaCl.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NaCl.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/NaCl.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NetBSD.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/NetBSD.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NetBSD.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/NetBSD.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NetBSD.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/NetBSD.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/NetBSD.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/NetBSD.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/OpenBSD.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/OpenBSD.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/OpenBSD.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/OpenBSD.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/OpenBSD.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/OpenBSD.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/OpenBSD.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/OpenBSD.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PPCLinux.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/PPCLinux.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PPCLinux.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/PPCLinux.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PPCLinux.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/PPCLinux.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PPCLinux.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/PPCLinux.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PS4CPU.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/PS4CPU.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PS4CPU.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/PS4CPU.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PS4CPU.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/PS4CPU.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/PS4CPU.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/PS4CPU.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/RISCVToolchain.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/RISCVToolchain.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/RISCVToolchain.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ROCm.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/ROCm.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ROCm.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/ROCm.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Solaris.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Solaris.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Solaris.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Solaris.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Solaris.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/Solaris.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/Solaris.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/Solaris.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/TCE.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/TCE.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/TCE.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/TCE.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/TCE.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/TCE.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/TCE.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/TCE.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/VEToolchain.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/VEToolchain.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/VEToolchain.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/VEToolchain.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/VEToolchain.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/VEToolchain.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/VEToolchain.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/VEToolchain.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/WebAssembly.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/WebAssembly.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/WebAssembly.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/WebAssembly.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/WebAssembly.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/WebAssembly.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/XCore.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/XCore.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/XCore.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/XCore.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/XCore.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/XCore.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/XCore.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/XCore.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ZOS.cpp b/interpreter/llvm-project/clang/lib/Driver/ToolChains/ZOS.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ZOS.cpp
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/ZOS.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ZOS.h b/interpreter/llvm-project/clang/lib/Driver/ToolChains/ZOS.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/ToolChains/ZOS.h
rename to interpreter/llvm-project/clang/lib/Driver/ToolChains/ZOS.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/Types.cpp b/interpreter/llvm-project/clang/lib/Driver/Types.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/Types.cpp
rename to interpreter/llvm-project/clang/lib/Driver/Types.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Driver/XRayArgs.cpp b/interpreter/llvm-project/clang/lib/Driver/XRayArgs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Driver/XRayArgs.cpp
rename to interpreter/llvm-project/clang/lib/Driver/XRayArgs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Edit/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Edit/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Edit/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Edit/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Edit/Commit.cpp b/interpreter/llvm-project/clang/lib/Edit/Commit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Edit/Commit.cpp
rename to interpreter/llvm-project/clang/lib/Edit/Commit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Edit/EditedSource.cpp b/interpreter/llvm-project/clang/lib/Edit/EditedSource.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Edit/EditedSource.cpp
rename to interpreter/llvm-project/clang/lib/Edit/EditedSource.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/interpreter/llvm-project/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
rename to interpreter/llvm-project/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/AffectedRangeManager.cpp b/interpreter/llvm-project/clang/lib/Format/AffectedRangeManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/AffectedRangeManager.cpp
rename to interpreter/llvm-project/clang/lib/Format/AffectedRangeManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/AffectedRangeManager.h b/interpreter/llvm-project/clang/lib/Format/AffectedRangeManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/AffectedRangeManager.h
rename to interpreter/llvm-project/clang/lib/Format/AffectedRangeManager.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/BreakableToken.cpp b/interpreter/llvm-project/clang/lib/Format/BreakableToken.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/BreakableToken.cpp
rename to interpreter/llvm-project/clang/lib/Format/BreakableToken.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/BreakableToken.h b/interpreter/llvm-project/clang/lib/Format/BreakableToken.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/BreakableToken.h
rename to interpreter/llvm-project/clang/lib/Format/BreakableToken.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Format/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Format/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/ContinuationIndenter.cpp b/interpreter/llvm-project/clang/lib/Format/ContinuationIndenter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/ContinuationIndenter.cpp
rename to interpreter/llvm-project/clang/lib/Format/ContinuationIndenter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/ContinuationIndenter.h b/interpreter/llvm-project/clang/lib/Format/ContinuationIndenter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/ContinuationIndenter.h
rename to interpreter/llvm-project/clang/lib/Format/ContinuationIndenter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/Encoding.h b/interpreter/llvm-project/clang/lib/Format/Encoding.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/Encoding.h
rename to interpreter/llvm-project/clang/lib/Format/Encoding.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/Format.cpp b/interpreter/llvm-project/clang/lib/Format/Format.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/Format.cpp
rename to interpreter/llvm-project/clang/lib/Format/Format.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/FormatInternal.h b/interpreter/llvm-project/clang/lib/Format/FormatInternal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/FormatInternal.h
rename to interpreter/llvm-project/clang/lib/Format/FormatInternal.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/FormatToken.cpp b/interpreter/llvm-project/clang/lib/Format/FormatToken.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/FormatToken.cpp
rename to interpreter/llvm-project/clang/lib/Format/FormatToken.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/FormatToken.h b/interpreter/llvm-project/clang/lib/Format/FormatToken.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/FormatToken.h
rename to interpreter/llvm-project/clang/lib/Format/FormatToken.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/FormatTokenLexer.cpp b/interpreter/llvm-project/clang/lib/Format/FormatTokenLexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/FormatTokenLexer.cpp
rename to interpreter/llvm-project/clang/lib/Format/FormatTokenLexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/FormatTokenLexer.h b/interpreter/llvm-project/clang/lib/Format/FormatTokenLexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/FormatTokenLexer.h
rename to interpreter/llvm-project/clang/lib/Format/FormatTokenLexer.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/MacroExpander.cpp b/interpreter/llvm-project/clang/lib/Format/MacroExpander.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/MacroExpander.cpp
rename to interpreter/llvm-project/clang/lib/Format/MacroExpander.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/Macros.h b/interpreter/llvm-project/clang/lib/Format/Macros.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/Macros.h
rename to interpreter/llvm-project/clang/lib/Format/Macros.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp b/interpreter/llvm-project/clang/lib/Format/NamespaceEndCommentsFixer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/NamespaceEndCommentsFixer.cpp
rename to interpreter/llvm-project/clang/lib/Format/NamespaceEndCommentsFixer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/NamespaceEndCommentsFixer.h b/interpreter/llvm-project/clang/lib/Format/NamespaceEndCommentsFixer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/NamespaceEndCommentsFixer.h
rename to interpreter/llvm-project/clang/lib/Format/NamespaceEndCommentsFixer.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/SortJavaScriptImports.cpp b/interpreter/llvm-project/clang/lib/Format/SortJavaScriptImports.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/SortJavaScriptImports.cpp
rename to interpreter/llvm-project/clang/lib/Format/SortJavaScriptImports.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/SortJavaScriptImports.h b/interpreter/llvm-project/clang/lib/Format/SortJavaScriptImports.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/SortJavaScriptImports.h
rename to interpreter/llvm-project/clang/lib/Format/SortJavaScriptImports.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/TokenAnalyzer.cpp b/interpreter/llvm-project/clang/lib/Format/TokenAnalyzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/TokenAnalyzer.cpp
rename to interpreter/llvm-project/clang/lib/Format/TokenAnalyzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/TokenAnalyzer.h b/interpreter/llvm-project/clang/lib/Format/TokenAnalyzer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/TokenAnalyzer.h
rename to interpreter/llvm-project/clang/lib/Format/TokenAnalyzer.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/TokenAnnotator.cpp b/interpreter/llvm-project/clang/lib/Format/TokenAnnotator.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/TokenAnnotator.cpp
rename to interpreter/llvm-project/clang/lib/Format/TokenAnnotator.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/TokenAnnotator.h b/interpreter/llvm-project/clang/lib/Format/TokenAnnotator.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/TokenAnnotator.h
rename to interpreter/llvm-project/clang/lib/Format/TokenAnnotator.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineFormatter.cpp b/interpreter/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineFormatter.cpp
rename to interpreter/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineFormatter.h b/interpreter/llvm-project/clang/lib/Format/UnwrappedLineFormatter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineFormatter.h
rename to interpreter/llvm-project/clang/lib/Format/UnwrappedLineFormatter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineParser.cpp b/interpreter/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineParser.cpp
rename to interpreter/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineParser.h b/interpreter/llvm-project/clang/lib/Format/UnwrappedLineParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UnwrappedLineParser.h
rename to interpreter/llvm-project/clang/lib/Format/UnwrappedLineParser.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UsingDeclarationsSorter.cpp b/interpreter/llvm-project/clang/lib/Format/UsingDeclarationsSorter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UsingDeclarationsSorter.cpp
rename to interpreter/llvm-project/clang/lib/Format/UsingDeclarationsSorter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/UsingDeclarationsSorter.h b/interpreter/llvm-project/clang/lib/Format/UsingDeclarationsSorter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/UsingDeclarationsSorter.h
rename to interpreter/llvm-project/clang/lib/Format/UsingDeclarationsSorter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/WhitespaceManager.cpp b/interpreter/llvm-project/clang/lib/Format/WhitespaceManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/WhitespaceManager.cpp
rename to interpreter/llvm-project/clang/lib/Format/WhitespaceManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Format/WhitespaceManager.h b/interpreter/llvm-project/clang/lib/Format/WhitespaceManager.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Format/WhitespaceManager.h
rename to interpreter/llvm-project/clang/lib/Format/WhitespaceManager.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ASTConsumers.cpp b/interpreter/llvm-project/clang/lib/Frontend/ASTConsumers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ASTConsumers.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ASTConsumers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ASTMerge.cpp b/interpreter/llvm-project/clang/lib/Frontend/ASTMerge.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ASTMerge.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ASTMerge.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ASTUnit.cpp b/interpreter/llvm-project/clang/lib/Frontend/ASTUnit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ASTUnit.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ASTUnit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Frontend/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Frontend/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ChainedDiagnosticConsumer.cpp b/interpreter/llvm-project/clang/lib/Frontend/ChainedDiagnosticConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ChainedDiagnosticConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ChainedDiagnosticConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ChainedIncludesSource.cpp b/interpreter/llvm-project/clang/lib/Frontend/ChainedIncludesSource.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ChainedIncludesSource.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ChainedIncludesSource.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/CompilerInstance.cpp b/interpreter/llvm-project/clang/lib/Frontend/CompilerInstance.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/CompilerInstance.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/CompilerInstance.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/CompilerInvocation.cpp b/interpreter/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/CompilerInvocation.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp b/interpreter/llvm-project/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/DependencyFile.cpp b/interpreter/llvm-project/clang/lib/Frontend/DependencyFile.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/DependencyFile.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/DependencyFile.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/DependencyGraph.cpp b/interpreter/llvm-project/clang/lib/Frontend/DependencyGraph.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/DependencyGraph.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/DependencyGraph.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/DiagnosticRenderer.cpp b/interpreter/llvm-project/clang/lib/Frontend/DiagnosticRenderer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/DiagnosticRenderer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/DiagnosticRenderer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/FrontendAction.cpp b/interpreter/llvm-project/clang/lib/Frontend/FrontendAction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/FrontendAction.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/FrontendAction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/FrontendActions.cpp b/interpreter/llvm-project/clang/lib/Frontend/FrontendActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/FrontendActions.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/FrontendActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/FrontendOptions.cpp b/interpreter/llvm-project/clang/lib/Frontend/FrontendOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/FrontendOptions.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/FrontendOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/HeaderIncludeGen.cpp b/interpreter/llvm-project/clang/lib/Frontend/HeaderIncludeGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/HeaderIncludeGen.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/HeaderIncludeGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/InitHeaderSearch.cpp b/interpreter/llvm-project/clang/lib/Frontend/InitHeaderSearch.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/InitHeaderSearch.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/InitHeaderSearch.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/InitPreprocessor.cpp b/interpreter/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/InitPreprocessor.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp b/interpreter/llvm-project/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/LayoutOverrideSource.cpp b/interpreter/llvm-project/clang/lib/Frontend/LayoutOverrideSource.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/LayoutOverrideSource.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/LayoutOverrideSource.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/LogDiagnosticPrinter.cpp b/interpreter/llvm-project/clang/lib/Frontend/LogDiagnosticPrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/LogDiagnosticPrinter.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/LogDiagnosticPrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp b/interpreter/llvm-project/clang/lib/Frontend/ModuleDependencyCollector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/ModuleDependencyCollector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/MultiplexConsumer.cpp b/interpreter/llvm-project/clang/lib/Frontend/MultiplexConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/MultiplexConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/MultiplexConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/PrecompiledPreamble.cpp b/interpreter/llvm-project/clang/lib/Frontend/PrecompiledPreamble.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/PrecompiledPreamble.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/PrecompiledPreamble.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp b/interpreter/llvm-project/clang/lib/Frontend/PrintPreprocessedOutput.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/PrintPreprocessedOutput.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/FixItRewriter.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/FixItRewriter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/FixItRewriter.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/FixItRewriter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/FrontendActions.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/FrontendActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/FrontendActions.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/FrontendActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/HTMLPrint.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/HTMLPrint.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/HTMLPrint.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/HTMLPrint.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteMacros.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteMacros.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteMacros.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteMacros.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteTest.cpp b/interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteTest.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/Rewrite/RewriteTest.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/Rewrite/RewriteTest.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp b/interpreter/llvm-project/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/SerializedDiagnosticReader.cpp b/interpreter/llvm-project/clang/lib/Frontend/SerializedDiagnosticReader.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/SerializedDiagnosticReader.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/SerializedDiagnosticReader.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/TestModuleFileExtension.cpp b/interpreter/llvm-project/clang/lib/Frontend/TestModuleFileExtension.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/TestModuleFileExtension.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/TestModuleFileExtension.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/TestModuleFileExtension.h b/interpreter/llvm-project/clang/lib/Frontend/TestModuleFileExtension.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/TestModuleFileExtension.h
rename to interpreter/llvm-project/clang/lib/Frontend/TestModuleFileExtension.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnostic.cpp b/interpreter/llvm-project/clang/lib/Frontend/TextDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnostic.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/TextDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnosticBuffer.cpp b/interpreter/llvm-project/clang/lib/Frontend/TextDiagnosticBuffer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnosticBuffer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/TextDiagnosticBuffer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp b/interpreter/llvm-project/clang/lib/Frontend/TextDiagnosticPrinter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/TextDiagnosticPrinter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp b/interpreter/llvm-project/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/FrontendTool/CMakeLists.txt b/interpreter/llvm-project/clang/lib/FrontendTool/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/FrontendTool/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/FrontendTool/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/interpreter/llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
rename to interpreter/llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Headers/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Headers/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_builtin_vars.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_builtin_vars.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_builtin_vars.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_builtin_vars.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_cmath.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_cmath.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_cmath.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_cmath.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_complex_builtins.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_complex_builtins.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_complex_builtins.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_complex_builtins.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_device_functions.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_device_functions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_device_functions.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_device_functions.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_intrinsics.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_intrinsics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_intrinsics.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_intrinsics.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_libdevice_declares.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_libdevice_declares.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_libdevice_declares.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_libdevice_declares.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_math.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_math.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_math.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_math.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_math_forward_declares.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_math_forward_declares.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_math_forward_declares.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_math_forward_declares.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_runtime_wrapper.h b/interpreter/llvm-project/clang/lib/Headers/__clang_cuda_runtime_wrapper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_cuda_runtime_wrapper.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_cuda_runtime_wrapper.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_cmath.h b/interpreter/llvm-project/clang/lib/Headers/__clang_hip_cmath.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_cmath.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_hip_cmath.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_libdevice_declares.h b/interpreter/llvm-project/clang/lib/Headers/__clang_hip_libdevice_declares.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_libdevice_declares.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_hip_libdevice_declares.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_math.h b/interpreter/llvm-project/clang/lib/Headers/__clang_hip_math.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_math.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_hip_math.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_runtime_wrapper.h b/interpreter/llvm-project/clang/lib/Headers/__clang_hip_runtime_wrapper.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__clang_hip_runtime_wrapper.h
rename to interpreter/llvm-project/clang/lib/Headers/__clang_hip_runtime_wrapper.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__stddef_max_align_t.h b/interpreter/llvm-project/clang/lib/Headers/__stddef_max_align_t.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__stddef_max_align_t.h
rename to interpreter/llvm-project/clang/lib/Headers/__stddef_max_align_t.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__wmmintrin_aes.h b/interpreter/llvm-project/clang/lib/Headers/__wmmintrin_aes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__wmmintrin_aes.h
rename to interpreter/llvm-project/clang/lib/Headers/__wmmintrin_aes.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/__wmmintrin_pclmul.h b/interpreter/llvm-project/clang/lib/Headers/__wmmintrin_pclmul.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/__wmmintrin_pclmul.h
rename to interpreter/llvm-project/clang/lib/Headers/__wmmintrin_pclmul.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/adxintrin.h b/interpreter/llvm-project/clang/lib/Headers/adxintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/adxintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/adxintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/altivec.h b/interpreter/llvm-project/clang/lib/Headers/altivec.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/altivec.h
rename to interpreter/llvm-project/clang/lib/Headers/altivec.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ammintrin.h b/interpreter/llvm-project/clang/lib/Headers/ammintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ammintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ammintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/amxintrin.h b/interpreter/llvm-project/clang/lib/Headers/amxintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/amxintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/amxintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/arm64intr.h b/interpreter/llvm-project/clang/lib/Headers/arm64intr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/arm64intr.h
rename to interpreter/llvm-project/clang/lib/Headers/arm64intr.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/arm_acle.h b/interpreter/llvm-project/clang/lib/Headers/arm_acle.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/arm_acle.h
rename to interpreter/llvm-project/clang/lib/Headers/arm_acle.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/arm_cmse.h b/interpreter/llvm-project/clang/lib/Headers/arm_cmse.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/arm_cmse.h
rename to interpreter/llvm-project/clang/lib/Headers/arm_cmse.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/armintr.h b/interpreter/llvm-project/clang/lib/Headers/armintr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/armintr.h
rename to interpreter/llvm-project/clang/lib/Headers/armintr.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx2intrin.h b/interpreter/llvm-project/clang/lib/Headers/avx2intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx2intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx2intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512bf16intrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512bf16intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512bf16intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512bf16intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512bitalgintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512bitalgintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512bitalgintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512bitalgintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512bwintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512bwintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512bwintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512bwintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512cdintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512cdintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512cdintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512cdintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512dqintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512dqintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512dqintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512dqintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512erintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512erintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512erintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512erintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512fintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512fintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512fintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512fintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512ifmaintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512ifmaintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512ifmaintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512ifmaintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512ifmavlintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512ifmavlintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512ifmavlintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512ifmavlintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512pfintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512pfintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512pfintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512pfintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmi2intrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vbmi2intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmi2intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vbmi2intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmiintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vbmiintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmiintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vbmiintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmivlintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vbmivlintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vbmivlintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vbmivlintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbf16intrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlbf16intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbf16intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlbf16intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbitalgintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlbitalgintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbitalgintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlbitalgintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbwintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlbwintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlbwintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlbwintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlcdintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlcdintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlcdintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlcdintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vldqintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vldqintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vldqintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vldqintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvbmi2intrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlvbmi2intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvbmi2intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlvbmi2intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvnniintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlvnniintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvnniintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlvnniintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvp2intersectintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vlvp2intersectintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vlvp2intersectintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vlvp2intersectintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vnniintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vnniintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vnniintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vnniintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vp2intersectintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vp2intersectintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vp2intersectintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vp2intersectintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vpopcntdqintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vpopcntdqintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vpopcntdqintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vpopcntdqintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avx512vpopcntdqvlintrin.h b/interpreter/llvm-project/clang/lib/Headers/avx512vpopcntdqvlintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avx512vpopcntdqvlintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avx512vpopcntdqvlintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avxintrin.h b/interpreter/llvm-project/clang/lib/Headers/avxintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avxintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avxintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/avxvnniintrin.h b/interpreter/llvm-project/clang/lib/Headers/avxvnniintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/avxvnniintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/avxvnniintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/bmi2intrin.h b/interpreter/llvm-project/clang/lib/Headers/bmi2intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/bmi2intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/bmi2intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/bmiintrin.h b/interpreter/llvm-project/clang/lib/Headers/bmiintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/bmiintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/bmiintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/builtins.h b/interpreter/llvm-project/clang/lib/Headers/builtins.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/builtins.h
rename to interpreter/llvm-project/clang/lib/Headers/builtins.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cet.h b/interpreter/llvm-project/clang/lib/Headers/cet.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cet.h
rename to interpreter/llvm-project/clang/lib/Headers/cet.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cetintrin.h b/interpreter/llvm-project/clang/lib/Headers/cetintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cetintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/cetintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cldemoteintrin.h b/interpreter/llvm-project/clang/lib/Headers/cldemoteintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cldemoteintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/cldemoteintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/clflushoptintrin.h b/interpreter/llvm-project/clang/lib/Headers/clflushoptintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/clflushoptintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/clflushoptintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/clwbintrin.h b/interpreter/llvm-project/clang/lib/Headers/clwbintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/clwbintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/clwbintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/clzerointrin.h b/interpreter/llvm-project/clang/lib/Headers/clzerointrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/clzerointrin.h
rename to interpreter/llvm-project/clang/lib/Headers/clzerointrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cpuid.h b/interpreter/llvm-project/clang/lib/Headers/cpuid.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cpuid.h
rename to interpreter/llvm-project/clang/lib/Headers/cpuid.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/algorithm b/interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/algorithm
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/algorithm
rename to interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/algorithm
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/complex b/interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/complex
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/complex
rename to interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/complex
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/new b/interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/new
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/cuda_wrappers/new
rename to interpreter/llvm-project/clang/lib/Headers/cuda_wrappers/new
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/emmintrin.h b/interpreter/llvm-project/clang/lib/Headers/emmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/emmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/emmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/enqcmdintrin.h b/interpreter/llvm-project/clang/lib/Headers/enqcmdintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/enqcmdintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/enqcmdintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/f16cintrin.h b/interpreter/llvm-project/clang/lib/Headers/f16cintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/f16cintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/f16cintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/float.h b/interpreter/llvm-project/clang/lib/Headers/float.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/float.h
rename to interpreter/llvm-project/clang/lib/Headers/float.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/fma4intrin.h b/interpreter/llvm-project/clang/lib/Headers/fma4intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/fma4intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/fma4intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/fmaintrin.h b/interpreter/llvm-project/clang/lib/Headers/fmaintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/fmaintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/fmaintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/fxsrintrin.h b/interpreter/llvm-project/clang/lib/Headers/fxsrintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/fxsrintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/fxsrintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/gfniintrin.h b/interpreter/llvm-project/clang/lib/Headers/gfniintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/gfniintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/gfniintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/hexagon_circ_brev_intrinsics.h b/interpreter/llvm-project/clang/lib/Headers/hexagon_circ_brev_intrinsics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/hexagon_circ_brev_intrinsics.h
rename to interpreter/llvm-project/clang/lib/Headers/hexagon_circ_brev_intrinsics.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/hexagon_protos.h b/interpreter/llvm-project/clang/lib/Headers/hexagon_protos.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/hexagon_protos.h
rename to interpreter/llvm-project/clang/lib/Headers/hexagon_protos.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/hexagon_types.h b/interpreter/llvm-project/clang/lib/Headers/hexagon_types.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/hexagon_types.h
rename to interpreter/llvm-project/clang/lib/Headers/hexagon_types.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/hresetintrin.h b/interpreter/llvm-project/clang/lib/Headers/hresetintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/hresetintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/hresetintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/htmintrin.h b/interpreter/llvm-project/clang/lib/Headers/htmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/htmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/htmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/htmxlintrin.h b/interpreter/llvm-project/clang/lib/Headers/htmxlintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/htmxlintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/htmxlintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/hvx_hexagon_protos.h b/interpreter/llvm-project/clang/lib/Headers/hvx_hexagon_protos.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/hvx_hexagon_protos.h
rename to interpreter/llvm-project/clang/lib/Headers/hvx_hexagon_protos.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ia32intrin.h b/interpreter/llvm-project/clang/lib/Headers/ia32intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ia32intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ia32intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/immintrin.h b/interpreter/llvm-project/clang/lib/Headers/immintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/immintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/immintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/intrin.h b/interpreter/llvm-project/clang/lib/Headers/intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/inttypes.h b/interpreter/llvm-project/clang/lib/Headers/inttypes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/inttypes.h
rename to interpreter/llvm-project/clang/lib/Headers/inttypes.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/invpcidintrin.h b/interpreter/llvm-project/clang/lib/Headers/invpcidintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/invpcidintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/invpcidintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/iso646.h b/interpreter/llvm-project/clang/lib/Headers/iso646.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/iso646.h
rename to interpreter/llvm-project/clang/lib/Headers/iso646.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/keylockerintrin.h b/interpreter/llvm-project/clang/lib/Headers/keylockerintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/keylockerintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/keylockerintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/limits.h b/interpreter/llvm-project/clang/lib/Headers/limits.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/limits.h
rename to interpreter/llvm-project/clang/lib/Headers/limits.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/lwpintrin.h b/interpreter/llvm-project/clang/lib/Headers/lwpintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/lwpintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/lwpintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/lzcntintrin.h b/interpreter/llvm-project/clang/lib/Headers/lzcntintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/lzcntintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/lzcntintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/mm3dnow.h b/interpreter/llvm-project/clang/lib/Headers/mm3dnow.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/mm3dnow.h
rename to interpreter/llvm-project/clang/lib/Headers/mm3dnow.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/mm_malloc.h b/interpreter/llvm-project/clang/lib/Headers/mm_malloc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/mm_malloc.h
rename to interpreter/llvm-project/clang/lib/Headers/mm_malloc.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/mmintrin.h b/interpreter/llvm-project/clang/lib/Headers/mmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/mmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/mmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/module.modulemap b/interpreter/llvm-project/clang/lib/Headers/module.modulemap
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/module.modulemap
rename to interpreter/llvm-project/clang/lib/Headers/module.modulemap
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/movdirintrin.h b/interpreter/llvm-project/clang/lib/Headers/movdirintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/movdirintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/movdirintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/msa.h b/interpreter/llvm-project/clang/lib/Headers/msa.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/msa.h
rename to interpreter/llvm-project/clang/lib/Headers/msa.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/mwaitxintrin.h b/interpreter/llvm-project/clang/lib/Headers/mwaitxintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/mwaitxintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/mwaitxintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/nmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/nmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/nmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/nmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/opencl-c-base.h b/interpreter/llvm-project/clang/lib/Headers/opencl-c-base.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/opencl-c-base.h
rename to interpreter/llvm-project/clang/lib/Headers/opencl-c-base.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/opencl-c.h b/interpreter/llvm-project/clang/lib/Headers/opencl-c.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/opencl-c.h
rename to interpreter/llvm-project/clang/lib/Headers/opencl-c.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/cmath b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/cmath
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/cmath
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/cmath
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex.h b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex.h
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex_cmath.h b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex_cmath.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/complex_cmath.h
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/complex_cmath.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/math.h b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/math.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/math.h
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/math.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/new b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/new
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/new
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/new
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/time.h b/interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/time.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/openmp_wrappers/time.h
rename to interpreter/llvm-project/clang/lib/Headers/openmp_wrappers/time.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/pconfigintrin.h b/interpreter/llvm-project/clang/lib/Headers/pconfigintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/pconfigintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/pconfigintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/pkuintrin.h b/interpreter/llvm-project/clang/lib/Headers/pkuintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/pkuintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/pkuintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/pmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/pmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/pmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/pmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/popcntintrin.h b/interpreter/llvm-project/clang/lib/Headers/popcntintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/popcntintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/popcntintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/emmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/emmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/emmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/emmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/mm_malloc.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/mm_malloc.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/mm_malloc.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/mm_malloc.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/mmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/mmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/mmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/mmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/pmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/pmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/pmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/pmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/smmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/smmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/smmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/smmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/tmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/tmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/tmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/tmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/xmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/xmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ppc_wrappers/xmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ppc_wrappers/xmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/prfchwintrin.h b/interpreter/llvm-project/clang/lib/Headers/prfchwintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/prfchwintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/prfchwintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/ptwriteintrin.h b/interpreter/llvm-project/clang/lib/Headers/ptwriteintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/ptwriteintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/ptwriteintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/rdseedintrin.h b/interpreter/llvm-project/clang/lib/Headers/rdseedintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/rdseedintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/rdseedintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/rtmintrin.h b/interpreter/llvm-project/clang/lib/Headers/rtmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/rtmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/rtmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/s390intrin.h b/interpreter/llvm-project/clang/lib/Headers/s390intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/s390intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/s390intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/serializeintrin.h b/interpreter/llvm-project/clang/lib/Headers/serializeintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/serializeintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/serializeintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/sgxintrin.h b/interpreter/llvm-project/clang/lib/Headers/sgxintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/sgxintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/sgxintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/shaintrin.h b/interpreter/llvm-project/clang/lib/Headers/shaintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/shaintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/shaintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/smmintrin.h b/interpreter/llvm-project/clang/lib/Headers/smmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/smmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/smmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdalign.h b/interpreter/llvm-project/clang/lib/Headers/stdalign.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdalign.h
rename to interpreter/llvm-project/clang/lib/Headers/stdalign.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdarg.h b/interpreter/llvm-project/clang/lib/Headers/stdarg.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdarg.h
rename to interpreter/llvm-project/clang/lib/Headers/stdarg.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdatomic.h b/interpreter/llvm-project/clang/lib/Headers/stdatomic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdatomic.h
rename to interpreter/llvm-project/clang/lib/Headers/stdatomic.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdbool.h b/interpreter/llvm-project/clang/lib/Headers/stdbool.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdbool.h
rename to interpreter/llvm-project/clang/lib/Headers/stdbool.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stddef.h b/interpreter/llvm-project/clang/lib/Headers/stddef.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stddef.h
rename to interpreter/llvm-project/clang/lib/Headers/stddef.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdint.h b/interpreter/llvm-project/clang/lib/Headers/stdint.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdint.h
rename to interpreter/llvm-project/clang/lib/Headers/stdint.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/stdnoreturn.h b/interpreter/llvm-project/clang/lib/Headers/stdnoreturn.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/stdnoreturn.h
rename to interpreter/llvm-project/clang/lib/Headers/stdnoreturn.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/tbmintrin.h b/interpreter/llvm-project/clang/lib/Headers/tbmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/tbmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/tbmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/tgmath.h b/interpreter/llvm-project/clang/lib/Headers/tgmath.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/tgmath.h
rename to interpreter/llvm-project/clang/lib/Headers/tgmath.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/tmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/tmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/tmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/tmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/tsxldtrkintrin.h b/interpreter/llvm-project/clang/lib/Headers/tsxldtrkintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/tsxldtrkintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/tsxldtrkintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/uintrintrin.h b/interpreter/llvm-project/clang/lib/Headers/uintrintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/uintrintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/uintrintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/unwind.h b/interpreter/llvm-project/clang/lib/Headers/unwind.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/unwind.h
rename to interpreter/llvm-project/clang/lib/Headers/unwind.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/vadefs.h b/interpreter/llvm-project/clang/lib/Headers/vadefs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/vadefs.h
rename to interpreter/llvm-project/clang/lib/Headers/vadefs.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/vaesintrin.h b/interpreter/llvm-project/clang/lib/Headers/vaesintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/vaesintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/vaesintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/varargs.h b/interpreter/llvm-project/clang/lib/Headers/varargs.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/varargs.h
rename to interpreter/llvm-project/clang/lib/Headers/varargs.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/vecintrin.h b/interpreter/llvm-project/clang/lib/Headers/vecintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/vecintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/vecintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/vpclmulqdqintrin.h b/interpreter/llvm-project/clang/lib/Headers/vpclmulqdqintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/vpclmulqdqintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/vpclmulqdqintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/waitpkgintrin.h b/interpreter/llvm-project/clang/lib/Headers/waitpkgintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/waitpkgintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/waitpkgintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/wasm_simd128.h b/interpreter/llvm-project/clang/lib/Headers/wasm_simd128.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/wasm_simd128.h
rename to interpreter/llvm-project/clang/lib/Headers/wasm_simd128.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/wbnoinvdintrin.h b/interpreter/llvm-project/clang/lib/Headers/wbnoinvdintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/wbnoinvdintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/wbnoinvdintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/wmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/wmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/wmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/wmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/x86gprintrin.h b/interpreter/llvm-project/clang/lib/Headers/x86gprintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/x86gprintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/x86gprintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/x86intrin.h b/interpreter/llvm-project/clang/lib/Headers/x86intrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/x86intrin.h
rename to interpreter/llvm-project/clang/lib/Headers/x86intrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xmmintrin.h b/interpreter/llvm-project/clang/lib/Headers/xmmintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xmmintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xmmintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xopintrin.h b/interpreter/llvm-project/clang/lib/Headers/xopintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xopintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xopintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xsavecintrin.h b/interpreter/llvm-project/clang/lib/Headers/xsavecintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xsavecintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xsavecintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xsaveintrin.h b/interpreter/llvm-project/clang/lib/Headers/xsaveintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xsaveintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xsaveintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xsaveoptintrin.h b/interpreter/llvm-project/clang/lib/Headers/xsaveoptintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xsaveoptintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xsaveoptintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xsavesintrin.h b/interpreter/llvm-project/clang/lib/Headers/xsavesintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xsavesintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xsavesintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Headers/xtestintrin.h b/interpreter/llvm-project/clang/lib/Headers/xtestintrin.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Headers/xtestintrin.h
rename to interpreter/llvm-project/clang/lib/Headers/xtestintrin.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Index/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Index/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/CommentToXML.cpp b/interpreter/llvm-project/clang/lib/Index/CommentToXML.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/CommentToXML.cpp
rename to interpreter/llvm-project/clang/lib/Index/CommentToXML.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/FileIndexRecord.cpp b/interpreter/llvm-project/clang/lib/Index/FileIndexRecord.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/FileIndexRecord.cpp
rename to interpreter/llvm-project/clang/lib/Index/FileIndexRecord.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/FileIndexRecord.h b/interpreter/llvm-project/clang/lib/Index/FileIndexRecord.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/FileIndexRecord.h
rename to interpreter/llvm-project/clang/lib/Index/FileIndexRecord.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexBody.cpp b/interpreter/llvm-project/clang/lib/Index/IndexBody.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexBody.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexBody.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexDecl.cpp b/interpreter/llvm-project/clang/lib/Index/IndexDecl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexDecl.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexDecl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexSymbol.cpp b/interpreter/llvm-project/clang/lib/Index/IndexSymbol.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexSymbol.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexSymbol.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexTypeSourceInfo.cpp b/interpreter/llvm-project/clang/lib/Index/IndexTypeSourceInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexTypeSourceInfo.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexTypeSourceInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexingAction.cpp b/interpreter/llvm-project/clang/lib/Index/IndexingAction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexingAction.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexingAction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexingContext.cpp b/interpreter/llvm-project/clang/lib/Index/IndexingContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexingContext.cpp
rename to interpreter/llvm-project/clang/lib/Index/IndexingContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/IndexingContext.h b/interpreter/llvm-project/clang/lib/Index/IndexingContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/IndexingContext.h
rename to interpreter/llvm-project/clang/lib/Index/IndexingContext.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Index/USRGeneration.cpp b/interpreter/llvm-project/clang/lib/Index/USRGeneration.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Index/USRGeneration.cpp
rename to interpreter/llvm-project/clang/lib/Index/USRGeneration.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/IndexSerialization/CMakeLists.txt b/interpreter/llvm-project/clang/lib/IndexSerialization/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/IndexSerialization/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/IndexSerialization/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/IndexSerialization/SerializablePathCollection.cpp b/interpreter/llvm-project/clang/lib/IndexSerialization/SerializablePathCollection.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/IndexSerialization/SerializablePathCollection.cpp
rename to interpreter/llvm-project/clang/lib/IndexSerialization/SerializablePathCollection.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Interpreter/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Interpreter/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalExecutor.cpp b/interpreter/llvm-project/clang/lib/Interpreter/IncrementalExecutor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalExecutor.cpp
rename to interpreter/llvm-project/clang/lib/Interpreter/IncrementalExecutor.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalExecutor.h b/interpreter/llvm-project/clang/lib/Interpreter/IncrementalExecutor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalExecutor.h
rename to interpreter/llvm-project/clang/lib/Interpreter/IncrementalExecutor.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalParser.cpp b/interpreter/llvm-project/clang/lib/Interpreter/IncrementalParser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalParser.cpp
rename to interpreter/llvm-project/clang/lib/Interpreter/IncrementalParser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalParser.h b/interpreter/llvm-project/clang/lib/Interpreter/IncrementalParser.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/IncrementalParser.h
rename to interpreter/llvm-project/clang/lib/Interpreter/IncrementalParser.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Interpreter/Interpreter.cpp b/interpreter/llvm-project/clang/lib/Interpreter/Interpreter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Interpreter/Interpreter.cpp
rename to interpreter/llvm-project/clang/lib/Interpreter/Interpreter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Lex/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Lex/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp b/interpreter/llvm-project/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
rename to interpreter/llvm-project/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/HeaderMap.cpp b/interpreter/llvm-project/clang/lib/Lex/HeaderMap.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/HeaderMap.cpp
rename to interpreter/llvm-project/clang/lib/Lex/HeaderMap.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/HeaderSearch.cpp b/interpreter/llvm-project/clang/lib/Lex/HeaderSearch.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Lex/HeaderSearch.cpp
rename to interpreter/llvm-project/clang/lib/Lex/HeaderSearch.cpp
index 3fb5c61d33f3d..1e6393345a655 100644
--- a/interpreter/llvm/src/tools/clang/lib/Lex/HeaderSearch.cpp
+++ b/interpreter/llvm-project/clang/lib/Lex/HeaderSearch.cpp
@@ -367,7 +367,9 @@ Optional HeaderSearch::getFileAndSuggestModule(
     std::error_code EC = llvm::errorToErrorCode(File.takeError());
     if (EC != llvm::errc::no_such_file_or_directory &&
         EC != llvm::errc::invalid_argument &&
-        EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
+        EC != llvm::errc::is_a_directory &&
+        EC != llvm::errc::not_a_directory &&
+        EC != llvm::errc::permission_denied) {
       Diags.Report(IncludeLoc, diag::err_cannot_open_file)
           << FileName << EC.message();
     }
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/Lexer.cpp b/interpreter/llvm-project/clang/lib/Lex/Lexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/Lexer.cpp
rename to interpreter/llvm-project/clang/lib/Lex/Lexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/LiteralSupport.cpp b/interpreter/llvm-project/clang/lib/Lex/LiteralSupport.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/LiteralSupport.cpp
rename to interpreter/llvm-project/clang/lib/Lex/LiteralSupport.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/MacroArgs.cpp b/interpreter/llvm-project/clang/lib/Lex/MacroArgs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/MacroArgs.cpp
rename to interpreter/llvm-project/clang/lib/Lex/MacroArgs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/MacroInfo.cpp b/interpreter/llvm-project/clang/lib/Lex/MacroInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/MacroInfo.cpp
rename to interpreter/llvm-project/clang/lib/Lex/MacroInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/ModuleMap.cpp b/interpreter/llvm-project/clang/lib/Lex/ModuleMap.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Lex/ModuleMap.cpp
rename to interpreter/llvm-project/clang/lib/Lex/ModuleMap.cpp
index f9af7c2a24fb9..7feb88508b9a2 100644
--- a/interpreter/llvm/src/tools/clang/lib/Lex/ModuleMap.cpp
+++ b/interpreter/llvm-project/clang/lib/Lex/ModuleMap.cpp
@@ -274,6 +274,8 @@ void ModuleMap::resolveHeader(Module *Mod,
     // this was supposed to modularize the builtin header alone.
   } else if (Header.Kind == Module::HK_Excluded) {
     // Ignore missing excluded header files. They're optional anyway.
+  } else if (Mod->IsOptional) {
+     // Optional submodules can have missing headers.
   } else {
     // If we find a module that has a missing header, we mark this module as
     // unavailable and store the header directive for displaying diagnostics.
@@ -1037,6 +1039,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
   Result->IsExternC |= Attrs.IsExternC;
   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
+  Result->IsOptional |= Attrs.IsOptional;
   Result->Directory = FrameworkDir;
 
   // Chop off the first framework bit, as that is implied.
@@ -1749,7 +1752,10 @@ namespace {
     AT_exhaustive,
 
     /// The 'no_undeclared_includes' attribute.
-    AT_no_undeclared_includes
+    AT_no_undeclared_includes,
+
+    /// The 'optional' attribute.
+    AT_optional
   };
 
 } // namespace
@@ -2005,6 +2011,8 @@ void ModuleMapParser::parseModuleDecl() {
     ActiveModule->IsSystem = true;
   if (Attrs.IsExternC)
     ActiveModule->IsExternC = true;
+  if (Attrs.IsOptional)
+    ActiveModule->IsOptional = true;
   if (Attrs.NoUndeclaredIncludes ||
       (!ActiveModule->Parent && ModuleName == "Darwin"))
     ActiveModule->NoUndeclaredIncludes = true;
@@ -2905,6 +2913,7 @@ bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
           .Case("exhaustive", AT_exhaustive)
           .Case("extern_c", AT_extern_c)
           .Case("no_undeclared_includes", AT_no_undeclared_includes)
+          .Case("optional", AT_optional)
           .Case("system", AT_system)
           .Default(AT_unknown);
     switch (Attribute) {
@@ -2928,6 +2937,10 @@ bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
     case AT_no_undeclared_includes:
       Attrs.NoUndeclaredIncludes = true;
       break;
+
+    case AT_optional:
+      Attrs.IsOptional = true;
+      break;
     }
     consumeToken();
 
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPCaching.cpp b/interpreter/llvm-project/clang/lib/Lex/PPCaching.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPCaching.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPCaching.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPCallbacks.cpp b/interpreter/llvm-project/clang/lib/Lex/PPCallbacks.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPCallbacks.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPCallbacks.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPConditionalDirectiveRecord.cpp b/interpreter/llvm-project/clang/lib/Lex/PPConditionalDirectiveRecord.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPConditionalDirectiveRecord.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPConditionalDirectiveRecord.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPDirectives.cpp b/interpreter/llvm-project/clang/lib/Lex/PPDirectives.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPDirectives.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPDirectives.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPExpressions.cpp b/interpreter/llvm-project/clang/lib/Lex/PPExpressions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPExpressions.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPExpressions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPLexerChange.cpp b/interpreter/llvm-project/clang/lib/Lex/PPLexerChange.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPLexerChange.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPLexerChange.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PPMacroExpansion.cpp b/interpreter/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PPMacroExpansion.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/Pragma.cpp b/interpreter/llvm-project/clang/lib/Lex/Pragma.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/Pragma.cpp
rename to interpreter/llvm-project/clang/lib/Lex/Pragma.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PreprocessingRecord.cpp b/interpreter/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PreprocessingRecord.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/Preprocessor.cpp b/interpreter/llvm-project/clang/lib/Lex/Preprocessor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/Preprocessor.cpp
rename to interpreter/llvm-project/clang/lib/Lex/Preprocessor.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/PreprocessorLexer.cpp b/interpreter/llvm-project/clang/lib/Lex/PreprocessorLexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/PreprocessorLexer.cpp
rename to interpreter/llvm-project/clang/lib/Lex/PreprocessorLexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/ScratchBuffer.cpp b/interpreter/llvm-project/clang/lib/Lex/ScratchBuffer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/ScratchBuffer.cpp
rename to interpreter/llvm-project/clang/lib/Lex/ScratchBuffer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/TokenConcatenation.cpp b/interpreter/llvm-project/clang/lib/Lex/TokenConcatenation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/TokenConcatenation.cpp
rename to interpreter/llvm-project/clang/lib/Lex/TokenConcatenation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/TokenLexer.cpp b/interpreter/llvm-project/clang/lib/Lex/TokenLexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/TokenLexer.cpp
rename to interpreter/llvm-project/clang/lib/Lex/TokenLexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Lex/UnicodeCharSets.h b/interpreter/llvm-project/clang/lib/Lex/UnicodeCharSets.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Lex/UnicodeCharSets.h
rename to interpreter/llvm-project/clang/lib/Lex/UnicodeCharSets.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Parse/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Parse/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseAST.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseAST.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseAST.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseAST.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseCXXInlineMethods.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseCXXInlineMethods.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseDecl.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseDecl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseDecl.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseDecl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseDeclCXX.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseDeclCXX.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseExpr.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseExpr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseExpr.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseExpr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseExprCXX.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseExprCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseExprCXX.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseExprCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseInit.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseInit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseInit.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseInit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseObjc.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseObjc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseObjc.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseObjc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseOpenMP.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParsePragma.cpp b/interpreter/llvm-project/clang/lib/Parse/ParsePragma.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParsePragma.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParsePragma.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseStmt.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseStmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseStmt.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseStmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseStmtAsm.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseStmtAsm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseStmtAsm.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseStmtAsm.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseTemplate.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseTemplate.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseTemplate.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseTemplate.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/ParseTentative.cpp b/interpreter/llvm-project/clang/lib/Parse/ParseTentative.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/ParseTentative.cpp
rename to interpreter/llvm-project/clang/lib/Parse/ParseTentative.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Parse/Parser.cpp b/interpreter/llvm-project/clang/lib/Parse/Parser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Parse/Parser.cpp
rename to interpreter/llvm-project/clang/lib/Parse/Parser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Rewrite/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Rewrite/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/DeltaTree.cpp b/interpreter/llvm-project/clang/lib/Rewrite/DeltaTree.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/DeltaTree.cpp
rename to interpreter/llvm-project/clang/lib/Rewrite/DeltaTree.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/HTMLRewrite.cpp b/interpreter/llvm-project/clang/lib/Rewrite/HTMLRewrite.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/HTMLRewrite.cpp
rename to interpreter/llvm-project/clang/lib/Rewrite/HTMLRewrite.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/RewriteRope.cpp b/interpreter/llvm-project/clang/lib/Rewrite/RewriteRope.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/RewriteRope.cpp
rename to interpreter/llvm-project/clang/lib/Rewrite/RewriteRope.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/Rewriter.cpp b/interpreter/llvm-project/clang/lib/Rewrite/Rewriter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/Rewriter.cpp
rename to interpreter/llvm-project/clang/lib/Rewrite/Rewriter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Rewrite/TokenRewriter.cpp b/interpreter/llvm-project/clang/lib/Rewrite/TokenRewriter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Rewrite/TokenRewriter.cpp
rename to interpreter/llvm-project/clang/lib/Rewrite/TokenRewriter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp b/interpreter/llvm-project/clang/lib/Sema/AnalysisBasedWarnings.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp
rename to interpreter/llvm-project/clang/lib/Sema/AnalysisBasedWarnings.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Sema/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Sema/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/CodeCompleteConsumer.cpp b/interpreter/llvm-project/clang/lib/Sema/CodeCompleteConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/CodeCompleteConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Sema/CodeCompleteConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/CoroutineStmtBuilder.h b/interpreter/llvm-project/clang/lib/Sema/CoroutineStmtBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/CoroutineStmtBuilder.h
rename to interpreter/llvm-project/clang/lib/Sema/CoroutineStmtBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/DeclSpec.cpp b/interpreter/llvm-project/clang/lib/Sema/DeclSpec.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/DeclSpec.cpp
rename to interpreter/llvm-project/clang/lib/Sema/DeclSpec.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/DelayedDiagnostic.cpp b/interpreter/llvm-project/clang/lib/Sema/DelayedDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/DelayedDiagnostic.cpp
rename to interpreter/llvm-project/clang/lib/Sema/DelayedDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/IdentifierResolver.cpp b/interpreter/llvm-project/clang/lib/Sema/IdentifierResolver.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/IdentifierResolver.cpp
rename to interpreter/llvm-project/clang/lib/Sema/IdentifierResolver.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/JumpDiagnostics.cpp b/interpreter/llvm-project/clang/lib/Sema/JumpDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/JumpDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/Sema/JumpDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/MultiplexExternalSemaSource.cpp b/interpreter/llvm-project/clang/lib/Sema/MultiplexExternalSemaSource.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/MultiplexExternalSemaSource.cpp
rename to interpreter/llvm-project/clang/lib/Sema/MultiplexExternalSemaSource.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/OpenCLBuiltins.td b/interpreter/llvm-project/clang/lib/Sema/OpenCLBuiltins.td
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/OpenCLBuiltins.td
rename to interpreter/llvm-project/clang/lib/Sema/OpenCLBuiltins.td
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/ParsedAttr.cpp b/interpreter/llvm-project/clang/lib/Sema/ParsedAttr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/ParsedAttr.cpp
rename to interpreter/llvm-project/clang/lib/Sema/ParsedAttr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/Scope.cpp b/interpreter/llvm-project/clang/lib/Sema/Scope.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/Scope.cpp
rename to interpreter/llvm-project/clang/lib/Sema/Scope.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/ScopeInfo.cpp b/interpreter/llvm-project/clang/lib/Sema/ScopeInfo.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/ScopeInfo.cpp
rename to interpreter/llvm-project/clang/lib/Sema/ScopeInfo.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/Sema.cpp b/interpreter/llvm-project/clang/lib/Sema/Sema.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/Sema.cpp
rename to interpreter/llvm-project/clang/lib/Sema/Sema.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaAccess.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaAccess.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaAccess.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaAccess.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaAttr.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaAttr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaAttr.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaAttr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaAvailability.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaAvailability.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaAvailability.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaAvailability.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCUDA.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaCUDA.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaCUDA.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaCUDA.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
index 2f70f6ae50c56..5e0ef503c0af8 100644
--- a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp
+++ b/interpreter/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
@@ -23,8 +23,7 @@
 #include "llvm/ADT/STLExtras.h"
 using namespace clang;
 
-#include "HackForDefaultTemplateArg.h"
-
+/// Find the current instantiation that associated with the given type.
 static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
                                                 DeclContext *CurContext) {
   if (T.isNull())
@@ -108,10 +107,6 @@ DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
           // into that class template definition.
           QualType Injected
             = ClassTemplate->getInjectedClassNameSpecialization();
-
-          // Injected might not be canonical
-          Injected = Injected.getCanonicalType();
-
           if (Context.hasSameType(Injected, ContextType))
             return ClassTemplate->getTemplatedDecl();
 
@@ -155,12 +150,6 @@ DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
   case NestedNameSpecifier::TypeSpec:
   case NestedNameSpecifier::TypeSpecWithTemplate: {
     const TagType *Tag = NNS->getAsType()->getAs();
-    if (!Tag 
-	&& sema::HackForDefaultTemplateArg::AllowNonCanonicalSubst()) {
-      // In case we are in the middle of a template name creation
-      // that tries to keep some of the typedef
-      Tag = NNS->getAsType()->getCanonicalTypeInternal()->getAs();
-    }
     assert(Tag && "Non-tag type in nested-name-specifier");
     return Tag->getDecl();
   }
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCast.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaCast.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaCast.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaCast.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaChecking.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaChecking.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaChecking.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaChecking.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCodeComplete.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaCodeComplete.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaConcept.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaConcept.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaConcept.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaConcept.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaConsumer.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaConsumer.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaCoroutine.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaCoroutine.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaCoroutine.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaCoroutine.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaDecl.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaDecl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaDecl.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaDecl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclAttr.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclAttr.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclCXX.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclCXX.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclObjC.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaDeclObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaDeclObjC.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaDeclObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExceptionSpec.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaExceptionSpec.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaExceptionSpec.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaExceptionSpec.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExpr.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaExpr.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaExpr.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaExpr.cpp
index ca41bc619f3f3..f8bf12d39b144 100644
--- a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExpr.cpp
+++ b/interpreter/llvm-project/clang/lib/Sema/SemaExpr.cpp
@@ -16662,7 +16662,10 @@ ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
                                    getASTContext()),
       /*IsImmediateInvocation*/ true);
-  ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
+  /// Value-dependent constant expressions should not be immediately
+  /// evaluated until they are instantiated.
+  if (!Res->isValueDependent())
+    ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
   return Res;
 }
 
@@ -18760,7 +18763,7 @@ void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
 
   if (auto *FD = dyn_cast(E->getDecl()))
     if (!isConstantEvaluated() && FD->isConsteval() &&
-        !RebuildingImmediateInvocation)
+        !RebuildingImmediateInvocation && !FD->isDependentContext())
       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
                      RefsMinusAssignments);
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExprCXX.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaExprCXX.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExprMember.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaExprMember.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaExprMember.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaExprMember.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaExprObjC.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaExprObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaExprObjC.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaExprObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaFixItUtils.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaFixItUtils.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaFixItUtils.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaFixItUtils.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaInit.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaInit.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaInit.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaInit.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaLambda.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaLambda.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaLambda.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaLambda.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaLookup.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaLookup.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaLookup.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaLookup.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaModule.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaModule.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaModule.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaModule.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaObjCProperty.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaObjCProperty.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaObjCProperty.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaObjCProperty.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaOpenMP.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaOpenMP.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaOpenMP.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaOpenMP.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaOverload.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaOverload.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaOverload.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaOverload.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaPseudoObject.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaPseudoObject.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaPseudoObject.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaPseudoObject.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaSYCL.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaSYCL.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaSYCL.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaSYCL.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaStmt.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaStmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaStmt.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaStmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaStmtAsm.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaStmtAsm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaStmtAsm.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaStmtAsm.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaStmtAttr.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaStmtAttr.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaStmtAttr.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaStmtAttr.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplate.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaTemplate.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplate.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaTemplate.cpp
index b75f39b12da20..67a9a87b73ee9 100644
--- a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplate.cpp
+++ b/interpreter/llvm-project/clang/lib/Sema/SemaTemplate.cpp
@@ -39,31 +39,6 @@
 using namespace clang;
 using namespace sema;
 
-bool HackForDefaultTemplateArg::AllowNonCanonicalSubstEnabled = true;
-
-// Default constructor, record the current value
-// of HackForDefaultTemplateArg::AllowNonCanonicalSubst
-// and set it to true.
-HackForDefaultTemplateArg::HackForDefaultTemplateArg() :
-  OldValue(HackForDefaultTemplateArg::AllowNonCanonicalSubstEnabled)
-{
-  AllowNonCanonicalSubstEnabled = true;
-}
-
-// Destructor, restore the previous value of
-// HackForDefaultTemplateArg::AllowNonCanonicalSubst.
-HackForDefaultTemplateArg::~HackForDefaultTemplateArg()
-{
-  AllowNonCanonicalSubstEnabled = OldValue;
-}
-
-// Return the current value of
-// HackForDefaultTemplateArg::AllowNonCanonicalSubst.
-bool HackForDefaultTemplateArg::AllowNonCanonicalSubst()
-{
-  return AllowNonCanonicalSubstEnabled;
-}
-
 // Exported for use by Parser.
 SourceRange
 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
@@ -5107,11 +5082,7 @@ bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
     return true;
 
   // Add the converted template type argument.
-  if (!HackForDefaultTemplateArg::AllowNonCanonicalSubst()) {
-    ArgType = Context.getCanonicalType(ArgType);
-  } else {
-    ArgType = ArgType.getCanonicalType();
-  }
+  ArgType = Context.getCanonicalType(ArgType);
 
   // Objective-C ARC:
   //   If an explicitly-specified template argument type is a lifetime type
@@ -6280,15 +6251,8 @@ bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
 
   if (Arg->isVariablyModifiedType()) {
     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
-  } else if (!HackForDefaultTemplateArg::AllowNonCanonicalSubst()) {
-    if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
-      return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
-    }
-  } else {
-    if (Context.hasSameUnqualifiedType(Arg.getCanonicalType(),
-                                       Context.OverloadTy)) {
-      return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
-    }
+  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
+    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
   }
 
   // C++03 [temp.arg.type]p2:
@@ -6300,11 +6264,7 @@ bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
   // a warning.
   if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
     UnnamedLocalNoLinkageFinder Finder(*this, SR);
-    if (!HackForDefaultTemplateArg::AllowNonCanonicalSubst()) {
-      (void)Finder.Visit(Context.getCanonicalType(Arg));
-    } else {
-      (void)Finder.Visit(Arg.getCanonicalType());
-    }
+    (void)Finder.Visit(Context.getCanonicalType(Arg));
   }
 
   return false;
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateDeduction.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateDeduction.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 78b2b7e587e20..f6cb40138065f 100644
--- a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/interpreter/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1826,8 +1826,7 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
 
     // TODO: only do this uniquing once, at the start of instantiation.
     QualType Result
-      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement,
-                          HackForDefaultTemplateArg::AllowNonCanonicalSubst());
+      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
     SubstTemplateTypeParmTypeLoc NewTL
       = TLB.push(Result);
     NewTL.setNameLoc(TL.getNameLoc());
@@ -1869,8 +1868,7 @@ TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
 
   Result = getSema().Context.getSubstTemplateTypeParmType(
                                       TL.getTypePtr()->getReplacedParameter(),
-                                                          Result,
-                           HackForDefaultTemplateArg::AllowNonCanonicalSubst());
+                                                          Result);
   SubstTemplateTypeParmTypeLoc NewTL
     = TLB.push(Result);
   NewTL.setNameLoc(TL.getNameLoc());
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateVariadic.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaTemplateVariadic.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/SemaType.cpp b/interpreter/llvm-project/clang/lib/Sema/SemaType.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/SemaType.cpp
rename to interpreter/llvm-project/clang/lib/Sema/SemaType.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/TreeTransform.h b/interpreter/llvm-project/clang/lib/Sema/TreeTransform.h
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Sema/TreeTransform.h
rename to interpreter/llvm-project/clang/lib/Sema/TreeTransform.h
index 2b2cfbf41383f..d8a5b6ad4f948 100644
--- a/interpreter/llvm/src/tools/clang/lib/Sema/TreeTransform.h
+++ b/interpreter/llvm-project/clang/lib/Sema/TreeTransform.h
@@ -41,8 +41,6 @@
 #include "llvm/Support/ErrorHandling.h"
 #include 
 
-#include "HackForDefaultTemplateArg.h"
-
 using namespace llvm::omp;
 
 namespace clang {
@@ -4118,21 +4116,12 @@ NestedNameSpecifierLoc TreeTransform::TransformNestedNameSpecifierLoc(
       if (!TL)
         return NestedNameSpecifierLoc();
 
-      // When using ROOT the type being passed can still be sugared
-      // so that we can construct template instance name with template
-      // default added that still uses the original spelling of the 
-      // arguments. [This is part of adding support for opaque typedef
-      // and 'shorter' names]
-      QualType tlType = TL.getType();
-      if (HackForDefaultTemplateArg::AllowNonCanonicalSubst()) {
-        tlType = tlType->getCanonicalTypeInternal().getUnqualifiedType();
-      }
-      if (tlType->isDependentType() || tlType->isRecordType() ||
+      if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
           (SemaRef.getLangOpts().CPlusPlus11 &&
-           tlType->isEnumeralType())) {
-        assert(!tlType.hasLocalQualifiers() &&
+           TL.getType()->isEnumeralType())) {
+        assert(!TL.getType().hasLocalQualifiers() &&
                "Can't get cv-qualifiers here");
-        if (tlType->isEnumeralType())
+        if (TL.getType()->isEnumeralType())
           SemaRef.Diag(TL.getBeginLoc(),
                        diag::warn_cxx98_compat_enum_nested_name_spec);
         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
@@ -6335,7 +6324,7 @@ QualType TreeTransform::TransformSubstTemplateTypeParmType(
   Replacement = SemaRef.Context.getCanonicalType(Replacement);
   QualType Result
     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
-                                                   Replacement,false);
+                                                   Replacement);
 
   // Propagate type-source information.
   SubstTemplateTypeParmTypeLoc NewTL
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/TypeLocBuilder.cpp b/interpreter/llvm-project/clang/lib/Sema/TypeLocBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/TypeLocBuilder.cpp
rename to interpreter/llvm-project/clang/lib/Sema/TypeLocBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/TypeLocBuilder.h b/interpreter/llvm-project/clang/lib/Sema/TypeLocBuilder.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/TypeLocBuilder.h
rename to interpreter/llvm-project/clang/lib/Sema/TypeLocBuilder.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/UsedDeclVisitor.h b/interpreter/llvm-project/clang/lib/Sema/UsedDeclVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Sema/UsedDeclVisitor.h
rename to interpreter/llvm-project/clang/lib/Sema/UsedDeclVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTCommon.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTCommon.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTCommon.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTCommon.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTCommon.h b/interpreter/llvm-project/clang/lib/Serialization/ASTCommon.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTCommon.h
rename to interpreter/llvm-project/clang/lib/Serialization/ASTCommon.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTReader.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTReader.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTReader.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTReader.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderDecl.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTReaderDecl.cpp
similarity index 98%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderDecl.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTReaderDecl.cpp
index c47a239e741aa..c7b723ed36591 100644
--- a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/interpreter/llvm-project/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -183,6 +183,13 @@ namespace clang {
     static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
                                            unsigned Index, NamedDecl *D);
 
+    /// Commit to a primary definition of the class RD, which is known to be
+    /// a definition of the class. We might not have read the definition data
+    /// for it yet. If we haven't then allocate placeholder definition data
+    /// now too.
+    static CXXRecordDecl *getOrFakePrimaryClassDefinition(ASTReader &Reader,
+                                                          CXXRecordDecl *RD);
+
     /// Results from loading a RedeclarableDecl.
     class RedeclarableResult {
       Decl *MergeWith;
@@ -587,7 +594,13 @@ void ASTDeclReader::VisitDecl(Decl *D) {
     auto *LexicalDC = readDeclAs();
     if (!LexicalDC)
       LexicalDC = SemaDC;
-    DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
+    // If the context is a class, we might not have actually merged it yet, in
+    // the case where the definition comes from an update record.
+    DeclContext *MergedSemaDC;
+    if (auto *RD = dyn_cast(SemaDC))
+      MergedSemaDC = getOrFakePrimaryClassDefinition(Reader, RD);
+    else
+      MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
     // Avoid calling setLexicalDeclContext() directly because it uses
     // Decl::getASTContext() internally which is unsafe during derialization.
     D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
@@ -3149,8 +3162,27 @@ static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
 
     ASTContext &C = FuncX->getASTContext();
 
-    const Expr *XRC = FuncX->getTrailingRequiresClause();
-    const Expr *YRC = FuncY->getTrailingRequiresClause();
+    // The trailing require clause of instantiated function may change during
+    // the semantic analysis. Trying to get the primary template function (if
+    // exists) to compare the primary trailing require clause.
+    auto TryToGetPrimaryTemplatedFunction =
+        [](const FunctionDecl *FD) -> const FunctionDecl * {
+      switch (FD->getTemplatedKind()) {
+      case FunctionDecl::TK_FunctionTemplate:
+        return FD->getDescribedFunctionTemplate()->getTemplatedDecl();
+      case FunctionDecl::TK_MemberSpecialization:
+        return FD->getInstantiatedFromMemberFunction();
+      case FunctionDecl::TK_FunctionTemplateSpecialization:
+        return FD->getPrimaryTemplate()->getTemplatedDecl();
+      default:
+        return FD;
+      }
+    };
+    const FunctionDecl *PrimaryX = TryToGetPrimaryTemplatedFunction(FuncX);
+    const FunctionDecl *PrimaryY = TryToGetPrimaryTemplatedFunction(FuncY);
+
+    const Expr *XRC = PrimaryX->getTrailingRequiresClause();
+    const Expr *YRC = PrimaryY->getTrailingRequiresClause();
     if (!XRC != !YRC)
       return false;
     if (XRC) {
@@ -3290,6 +3322,32 @@ static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
   return false;
 }
 
+CXXRecordDecl *
+ASTDeclReader::getOrFakePrimaryClassDefinition(ASTReader &Reader,
+                                               CXXRecordDecl *RD) {
+  // Try to dig out the definition.
+  auto *DD = RD->DefinitionData;
+  if (!DD)
+    DD = RD->getCanonicalDecl()->DefinitionData;
+
+  // If there's no definition yet, then DC's definition is added by an update
+  // record, but we've not yet loaded that update record. In this case, we
+  // commit to DC being the canonical definition now, and will fix this when
+  // we load the update record.
+  if (!DD) {
+    DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
+    RD->setCompleteDefinition(true);
+    RD->DefinitionData = DD;
+    RD->getCanonicalDecl()->DefinitionData = DD;
+
+    // Track that we did this horrible thing so that we can fix it later.
+    Reader.PendingFakeDefinitionData.insert(
+        std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
+  }
+
+  return DD->Definition;
+}
+
 /// Find the context in which we should search for previous declarations when
 /// looking for declarations to merge.
 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
@@ -3297,29 +3355,8 @@ DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
   if (auto *ND = dyn_cast(DC))
     return ND->getOriginalNamespace();
 
-  if (auto *RD = dyn_cast(DC)) {
-    // Try to dig out the definition.
-    auto *DD = RD->DefinitionData;
-    if (!DD)
-      DD = RD->getCanonicalDecl()->DefinitionData;
-
-    // If there's no definition yet, then DC's definition is added by an update
-    // record, but we've not yet loaded that update record. In this case, we
-    // commit to DC being the canonical definition now, and will fix this when
-    // we load the update record.
-    if (!DD) {
-      DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
-      RD->setCompleteDefinition(true);
-      RD->DefinitionData = DD;
-      RD->getCanonicalDecl()->DefinitionData = DD;
-
-      // Track that we did this horrible thing so that we can fix it later.
-      Reader.PendingFakeDefinitionData.insert(
-          std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
-    }
-
-    return DD->Definition;
-  }
+  if (auto *RD = dyn_cast(DC))
+    return getOrFakePrimaryClassDefinition(Reader, RD);
 
   if (auto *ED = dyn_cast(DC))
     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderInternals.h b/interpreter/llvm-project/clang/lib/Serialization/ASTReaderInternals.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderInternals.h
rename to interpreter/llvm-project/clang/lib/Serialization/ASTReaderInternals.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderStmt.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTReaderStmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTReaderStmt.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTReaderStmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriter.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTWriter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriter.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTWriter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriterDecl.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp
similarity index 99%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriterDecl.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp
index 6446cd705a908..4c056ed963558 100644
--- a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/interpreter/llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2310,7 +2310,7 @@ void ASTWriter::WriteDeclAbbrevs() {
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Defaulted
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ExplicitlyDefaulted
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ImplicitReturnZero
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constexpr
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Constexpr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // UsesSEHTry
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // SkippedBody
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // MultiVersion
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriterStmt.cpp b/interpreter/llvm-project/clang/lib/Serialization/ASTWriterStmt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ASTWriterStmt.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ASTWriterStmt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Serialization/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Serialization/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/GeneratePCH.cpp b/interpreter/llvm-project/clang/lib/Serialization/GeneratePCH.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/GeneratePCH.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/GeneratePCH.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/GlobalModuleIndex.cpp b/interpreter/llvm-project/clang/lib/Serialization/GlobalModuleIndex.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/GlobalModuleIndex.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/GlobalModuleIndex.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/InMemoryModuleCache.cpp b/interpreter/llvm-project/clang/lib/Serialization/InMemoryModuleCache.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/InMemoryModuleCache.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/InMemoryModuleCache.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ModuleFile.cpp b/interpreter/llvm-project/clang/lib/Serialization/ModuleFile.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ModuleFile.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ModuleFile.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ModuleFileExtension.cpp b/interpreter/llvm-project/clang/lib/Serialization/ModuleFileExtension.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ModuleFileExtension.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ModuleFileExtension.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/ModuleManager.cpp b/interpreter/llvm-project/clang/lib/Serialization/ModuleManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/ModuleManager.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/ModuleManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/MultiOnDiskHashTable.h b/interpreter/llvm-project/clang/lib/Serialization/MultiOnDiskHashTable.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/MultiOnDiskHashTable.h
rename to interpreter/llvm-project/clang/lib/Serialization/MultiOnDiskHashTable.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Serialization/PCHContainerOperations.cpp b/interpreter/llvm-project/clang/lib/Serialization/PCHContainerOperations.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Serialization/PCHContainerOperations.cpp
rename to interpreter/llvm-project/clang/lib/Serialization/PCHContainerOperations.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/CMakeLists.txt b/interpreter/llvm-project/clang/lib/StaticAnalyzer/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AllocationState.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AllocationState.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AllocationState.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AllocationState.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CXXSelfAssignmentChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CXXSelfAssignmentChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CXXSelfAssignmentChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CXXSelfAssignmentChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CloneChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DynamicTypeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DynamicTypeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DynamicTypeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DynamicTypeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InterCheckerAPI.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InterCheckerAPI.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InterCheckerAPI.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InterCheckerAPI.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InvalidatedIteratorChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InvalidatedIteratorChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/InvalidatedIteratorChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/InvalidatedIteratorChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Iterator.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Iterator.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Iterator.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Iterator.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Iterator.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIBugReporter.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIChecker.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIFunctionClassifier.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIFunctionClassifier.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIFunctionClassifier.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPIFunctionClassifier.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPITypes.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPITypes.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPITypes.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPITypes.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Move.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Move.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Move.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Move.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/OSObjectCStyleCast.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/OSObjectCStyleCast.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/OSObjectCStyleCast.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/OSObjectCStyleCast.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCPropertyChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCPropertyChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCPropertyChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCPropertyChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnValueChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtrChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtrChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtrChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtrChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Taint.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Taint.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Taint.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Taint.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Taint.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TraversalChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TraversalChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TraversalChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TraversalChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/DiagOutputUtils.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/DiagOutputUtils.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/DiagOutputUtils.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/DiagOutputUtils.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Yaml.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Yaml.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/Yaml.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/Yaml.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/APSIntType.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/APSIntType.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/APSIntType.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/APSIntType.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BlockCounter.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BlockCounter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BlockCounter.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BlockCounter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CMakeLists.txt b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CallEvent.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Checker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Checker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistryData.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerRegistryData.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistryData.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CheckerRegistryData.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/DynamicExtent.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/DynamicExtent.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/DynamicExtent.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/DynamicExtent.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/DynamicType.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Environment.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Environment.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Environment.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Environment.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/FunctionSummary.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/FunctionSummary.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/FunctionSummary.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/FunctionSummary.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/PrettyStackTraceLocationContext.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/PrettyStackTraceLocationContext.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/PrettyStackTraceLocationContext.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/PrettyStackTraceLocationContext.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ProgramState.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SMTConstraintManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SMTConstraintManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SMTConstraintManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SMTConstraintManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SVals.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SVals.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SVals.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SVals.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Store.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Store.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/Store.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/Store.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/WorkList.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/WorkList.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Core/WorkList.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Core/WorkList.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/CreateCheckerManager.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/FrontendActions.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/FrontendActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/FrontendActions.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/FrontendActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelInjector.h b/interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelInjector.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Frontend/ModelInjector.h
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/Frontend/ModelInjector.h
diff --git a/interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/README.txt b/interpreter/llvm-project/clang/lib/StaticAnalyzer/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/README.txt
rename to interpreter/llvm-project/clang/lib/StaticAnalyzer/README.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Testing/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Testing/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Testing/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Testing/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Testing/CommandLineArgs.cpp b/interpreter/llvm-project/clang/lib/Testing/CommandLineArgs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Testing/CommandLineArgs.cpp
rename to interpreter/llvm-project/clang/lib/Testing/CommandLineArgs.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/ASTDiff/ASTDiff.cpp b/interpreter/llvm-project/clang/lib/Tooling/ASTDiff/ASTDiff.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/ASTDiff/ASTDiff.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/ASTDiff/ASTDiff.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/ASTDiff/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/ASTDiff/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/ASTDiff/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/ASTDiff/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/AllTUsExecution.cpp b/interpreter/llvm-project/clang/lib/Tooling/AllTUsExecution.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/AllTUsExecution.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/AllTUsExecution.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/ArgumentsAdjusters.cpp b/interpreter/llvm-project/clang/lib/Tooling/ArgumentsAdjusters.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/ArgumentsAdjusters.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/ArgumentsAdjusters.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/CommonOptionsParser.cpp b/interpreter/llvm-project/clang/lib/Tooling/CommonOptionsParser.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/CommonOptionsParser.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/CommonOptionsParser.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/CompilationDatabase.cpp b/interpreter/llvm-project/clang/lib/Tooling/CompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/CompilationDatabase.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/CompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Core/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/Core/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Core/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/Core/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Core/Diagnostic.cpp b/interpreter/llvm-project/clang/lib/Tooling/Core/Diagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Core/Diagnostic.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Core/Diagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Core/Replacement.cpp b/interpreter/llvm-project/clang/lib/Tooling/Core/Replacement.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Core/Replacement.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Core/Replacement.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningService.cpp b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/APIData.h b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/APIData.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/APIData.h
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/APIData.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
similarity index 97%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
index a41a5c3f6c578..8091a467d056c 100644
--- a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
+++ b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
@@ -1,159 +1,159 @@
-//===- ClangSrcLocDump.cpp ------------------------------------*- C++ -*---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "clang/Basic/Diagnostic.h"
-#include "clang/Driver/Compilation.h"
-#include "clang/Driver/Driver.h"
-#include "clang/Driver/Job.h"
-#include "clang/Driver/Options.h"
-#include "clang/Driver/Tool.h"
-#include "clang/Frontend/CompilerInstance.h"
-#include "clang/Frontend/TextDiagnosticPrinter.h"
-#include "clang/Lex/PreprocessorOptions.h"
-#include "clang/Tooling/Tooling.h"
-#include "llvm/Option/ArgList.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/Host.h"
-#include "llvm/Support/JSON.h"
-
-#include "ASTSrcLocProcessor.h"
-
-using namespace clang::tooling;
-using namespace clang;
-using namespace llvm;
-
-static cl::list IncludeDirectories(
-    "I", cl::desc("Include directories to use while compiling"),
-    cl::value_desc("directory"), cl::Required, cl::OneOrMore, cl::Prefix);
-
-static cl::opt
-    SkipProcessing("skip-processing",
-                   cl::desc("Avoid processing the AST header file"),
-                   cl::Required, cl::value_desc("bool"));
-
-static cl::opt JsonOutputPath("json-output-path",
-                                           cl::desc("json output path"),
-                                           cl::Required,
-                                           cl::value_desc("path"));
-
-class ASTSrcLocGenerationAction : public clang::ASTFrontendAction {
-public:
-  ASTSrcLocGenerationAction() : Processor(JsonOutputPath) {}
-
-  void ExecuteAction() override {
-    clang::ASTFrontendAction::ExecuteAction();
-    if (getCompilerInstance().getDiagnostics().getNumErrors() > 0)
-      Processor.generateEmpty();
-    else
-      Processor.generate();
-  }
-
-  std::unique_ptr
-  CreateASTConsumer(clang::CompilerInstance &Compiler,
-                    llvm::StringRef File) override {
-    return Processor.createASTConsumer(Compiler, File);
-  }
-
-private:
-  ASTSrcLocProcessor Processor;
-};
-
-static const char Filename[] = "ASTTU.cpp";
-
-int main(int argc, const char **argv) {
-
-  cl::ParseCommandLineOptions(argc, argv);
-
-  if (SkipProcessing) {
-    std::error_code EC;
-    llvm::raw_fd_ostream JsonOut(JsonOutputPath, EC, llvm::sys::fs::OF_Text);
-    if (EC)
-      return 1;
-    JsonOut << formatv("{0:2}", llvm::json::Value(llvm::json::Object()));
-    return 0;
-  }
-
-  std::vector Args;
-  Args.push_back("-cc1");
-
-  llvm::transform(IncludeDirectories, std::back_inserter(Args),
-                  [](const std::string &IncDir) { return "-I" + IncDir; });
-
-  Args.push_back("-fsyntax-only");
-  Args.push_back(Filename);
-
-  std::vector Argv(Args.size(), nullptr);
-  llvm::transform(Args, Argv.begin(),
-                  [](const std::string &Arg) { return Arg.c_str(); });
-
-  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
-  unsigned MissingArgIndex, MissingArgCount;
-  auto Opts = driver::getDriverOptTable();
-  auto ParsedArgs = Opts.ParseArgs(llvm::makeArrayRef(Argv).slice(1),
-                                   MissingArgIndex, MissingArgCount);
-  ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
-
-  // Don't output diagnostics, because common scenarios such as
-  // cross-compiling fail with diagnostics.  This is not fatal, but
-  // just causes attempts to use the introspection API to return no data.
-  TextDiagnosticPrinter DiagnosticPrinter(llvm::nulls(), &*DiagOpts);
-  DiagnosticsEngine Diagnostics(
-      IntrusiveRefCntPtr(new DiagnosticIDs()), &*DiagOpts,
-      &DiagnosticPrinter, false);
-
-  auto *OFS = new llvm::vfs::OverlayFileSystem(vfs::getRealFileSystem());
-
-  auto *MemFS = new llvm::vfs::InMemoryFileSystem();
-  OFS->pushOverlay(MemFS);
-  MemFS->addFile(Filename, 0,
-                 MemoryBuffer::getMemBuffer("#include \"clang/AST/AST.h\"\n"));
-
-  auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), OFS);
-
-  auto Driver = std::make_unique(
-      "clang", llvm::sys::getDefaultTargetTriple(), Diagnostics,
-      "ast-api-dump-tool", OFS);
-
-  std::unique_ptr Comp(
-      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
-  if (!Comp)
-    return 1;
-
-  const auto &Jobs = Comp->getJobs();
-  if (Jobs.size() != 1 || !isa(*Jobs.begin())) {
-    SmallString<256> error_msg;
-    llvm::raw_svector_ostream error_stream(error_msg);
-    Jobs.Print(error_stream, "; ", true);
-    return 1;
-  }
-
-  const auto &Cmd = cast(*Jobs.begin());
-  const llvm::opt::ArgStringList &CC1Args = Cmd.getArguments();
-
-  auto Invocation = std::make_unique();
-  CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, Diagnostics);
-
-  CompilerInstance Compiler(std::make_shared());
-  Compiler.setInvocation(std::move(Invocation));
-
-  Compiler.createDiagnostics(&DiagnosticPrinter, false);
-  if (!Compiler.hasDiagnostics())
-    return 1;
-
-  // Suppress "2 errors generated" or similar messages
-  Compiler.getDiagnosticOpts().ShowCarets = false;
-  Compiler.createSourceManager(*Files);
-  Compiler.setFileManager(Files.get());
-
-  ASTSrcLocGenerationAction ScopedToolAction;
-  Compiler.ExecuteAction(ScopedToolAction);
-
-  Files->clearStatCache();
-
-  return 0;
-}
+//===- ClangSrcLocDump.cpp ------------------------------------*- C++ -*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/Job.h"
+#include "clang/Driver/Options.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Host.h"
+#include "llvm/Support/JSON.h"
+
+#include "ASTSrcLocProcessor.h"
+
+using namespace clang::tooling;
+using namespace clang;
+using namespace llvm;
+
+static cl::list IncludeDirectories(
+    "I", cl::desc("Include directories to use while compiling"),
+    cl::value_desc("directory"), cl::Required, cl::OneOrMore, cl::Prefix);
+
+static cl::opt
+    SkipProcessing("skip-processing",
+                   cl::desc("Avoid processing the AST header file"),
+                   cl::Required, cl::value_desc("bool"));
+
+static cl::opt JsonOutputPath("json-output-path",
+                                           cl::desc("json output path"),
+                                           cl::Required,
+                                           cl::value_desc("path"));
+
+class ASTSrcLocGenerationAction : public clang::ASTFrontendAction {
+public:
+  ASTSrcLocGenerationAction() : Processor(JsonOutputPath) {}
+
+  void ExecuteAction() override {
+    clang::ASTFrontendAction::ExecuteAction();
+    if (getCompilerInstance().getDiagnostics().getNumErrors() > 0)
+      Processor.generateEmpty();
+    else
+      Processor.generate();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &Compiler,
+                    llvm::StringRef File) override {
+    return Processor.createASTConsumer(Compiler, File);
+  }
+
+private:
+  ASTSrcLocProcessor Processor;
+};
+
+static const char Filename[] = "ASTTU.cpp";
+
+int main(int argc, const char **argv) {
+
+  cl::ParseCommandLineOptions(argc, argv);
+
+  if (SkipProcessing) {
+    std::error_code EC;
+    llvm::raw_fd_ostream JsonOut(JsonOutputPath, EC, llvm::sys::fs::OF_Text);
+    if (EC)
+      return 1;
+    JsonOut << formatv("{0:2}", llvm::json::Value(llvm::json::Object()));
+    return 0;
+  }
+
+  std::vector Args;
+  Args.push_back("-cc1");
+
+  llvm::transform(IncludeDirectories, std::back_inserter(Args),
+                  [](const std::string &IncDir) { return "-I" + IncDir; });
+
+  Args.push_back("-fsyntax-only");
+  Args.push_back(Filename);
+
+  std::vector Argv(Args.size(), nullptr);
+  llvm::transform(Args, Argv.begin(),
+                  [](const std::string &Arg) { return Arg.c_str(); });
+
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  unsigned MissingArgIndex, MissingArgCount;
+  auto Opts = driver::getDriverOptTable();
+  auto ParsedArgs = Opts.ParseArgs(llvm::makeArrayRef(Argv).slice(1),
+                                   MissingArgIndex, MissingArgCount);
+  ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
+
+  // Don't output diagnostics, because common scenarios such as
+  // cross-compiling fail with diagnostics.  This is not fatal, but
+  // just causes attempts to use the introspection API to return no data.
+  TextDiagnosticPrinter DiagnosticPrinter(llvm::nulls(), &*DiagOpts);
+  DiagnosticsEngine Diagnostics(
+      IntrusiveRefCntPtr(new DiagnosticIDs()), &*DiagOpts,
+      &DiagnosticPrinter, false);
+
+  auto *OFS = new llvm::vfs::OverlayFileSystem(vfs::getRealFileSystem());
+
+  auto *MemFS = new llvm::vfs::InMemoryFileSystem();
+  OFS->pushOverlay(MemFS);
+  MemFS->addFile(Filename, 0,
+                 MemoryBuffer::getMemBuffer("#include \"clang/AST/AST.h\"\n"));
+
+  auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), OFS);
+
+  auto Driver = std::make_unique(
+      "clang", llvm::sys::getDefaultTargetTriple(), Diagnostics,
+      "ast-api-dump-tool", OFS);
+
+  std::unique_ptr Comp(
+      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
+  if (!Comp)
+    return 1;
+
+  const auto &Jobs = Comp->getJobs();
+  if (Jobs.size() != 1 || !isa(*Jobs.begin())) {
+    SmallString<256> error_msg;
+    llvm::raw_svector_ostream error_stream(error_msg);
+    Jobs.Print(error_stream, "; ", true);
+    return 1;
+  }
+
+  const auto &Cmd = cast(*Jobs.begin());
+  const llvm::opt::ArgStringList &CC1Args = Cmd.getArguments();
+
+  auto Invocation = std::make_unique();
+  CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, Diagnostics);
+
+  CompilerInstance Compiler(std::make_shared());
+  Compiler.setInvocation(std::move(Invocation));
+
+  Compiler.createDiagnostics(&DiagnosticPrinter, false);
+  if (!Compiler.hasDiagnostics())
+    return 1;
+
+  // Suppress "2 errors generated" or similar messages
+  Compiler.getDiagnosticOpts().ShowCarets = false;
+  Compiler.createSourceManager(*Files);
+  Compiler.setFileManager(Files.get());
+
+  ASTSrcLocGenerationAction ScopedToolAction;
+  Compiler.ExecuteAction(ScopedToolAction);
+
+  Files->clearStatCache();
+
+  return 0;
+}
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py b/interpreter/llvm-project/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
rename to interpreter/llvm-project/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/EmptyNodeIntrospection.inc.in b/interpreter/llvm-project/clang/lib/Tooling/EmptyNodeIntrospection.inc.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/EmptyNodeIntrospection.inc.in
rename to interpreter/llvm-project/clang/lib/Tooling/EmptyNodeIntrospection.inc.in
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Execution.cpp b/interpreter/llvm-project/clang/lib/Tooling/Execution.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Execution.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Execution.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp b/interpreter/llvm-project/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/FileMatchTrie.cpp b/interpreter/llvm-project/clang/lib/Tooling/FileMatchTrie.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/FileMatchTrie.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/FileMatchTrie.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/FixIt.cpp b/interpreter/llvm-project/clang/lib/Tooling/FixIt.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/FixIt.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/FixIt.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/GuessTargetAndModeCompilationDatabase.cpp b/interpreter/llvm-project/clang/lib/Tooling/GuessTargetAndModeCompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/GuessTargetAndModeCompilationDatabase.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/GuessTargetAndModeCompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/Inclusions/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/Inclusions/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp b/interpreter/llvm-project/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/IncludeStyle.cpp b/interpreter/llvm-project/clang/lib/Tooling/Inclusions/IncludeStyle.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Inclusions/IncludeStyle.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Inclusions/IncludeStyle.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp b/interpreter/llvm-project/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp b/interpreter/llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/NodeIntrospection.cpp b/interpreter/llvm-project/clang/lib/Tooling/NodeIntrospection.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/NodeIntrospection.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/NodeIntrospection.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/ASTSelection.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/ASTSelection.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/ASTSelection.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/ASTSelection.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/ASTSelectionRequirements.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/AtomicChange.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/AtomicChange.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/AtomicChange.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Extract/Extract.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Extract/Extract.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Extract/Extract.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Extract/Extract.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Lookup.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Lookup.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Lookup.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Lookup.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/RefactoringActions.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/RefactoringActions.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/RefactoringActions.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/RefactoringActions.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRFinder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp b/interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/RefactoringCallbacks.cpp b/interpreter/llvm-project/clang/lib/Tooling/RefactoringCallbacks.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/RefactoringCallbacks.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/RefactoringCallbacks.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/StandaloneExecution.cpp b/interpreter/llvm-project/clang/lib/Tooling/StandaloneExecution.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/StandaloneExecution.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/StandaloneExecution.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/BuildTree.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/BuildTree.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/BuildTree.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/BuildTree.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/Syntax/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/ComputeReplacements.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/ComputeReplacements.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/ComputeReplacements.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/ComputeReplacements.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Mutations.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/Mutations.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Mutations.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/Mutations.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Nodes.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/Nodes.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Nodes.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/Nodes.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Synthesis.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/Synthesis.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Synthesis.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/Synthesis.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Tokens.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/Tokens.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Tokens.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/Tokens.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Tree.cpp b/interpreter/llvm-project/clang/lib/Tooling/Syntax/Tree.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Syntax/Tree.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Syntax/Tree.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Tooling.cpp b/interpreter/llvm-project/clang/lib/Tooling/Tooling.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Tooling.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Tooling.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/CMakeLists.txt b/interpreter/llvm-project/clang/lib/Tooling/Transformer/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/CMakeLists.txt
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Parsing.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/Parsing.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Parsing.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/Parsing.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/RangeSelector.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/RangeSelector.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/RangeSelector.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/RangeSelector.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/RewriteRule.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/RewriteRule.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/RewriteRule.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/RewriteRule.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/SourceCode.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/SourceCode.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/SourceCode.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/SourceCode.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Stencil.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/Stencil.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Stencil.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/Stencil.cpp
diff --git a/interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Transformer.cpp b/interpreter/llvm-project/clang/lib/Tooling/Transformer/Transformer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/lib/Tooling/Transformer/Transformer.cpp
rename to interpreter/llvm-project/clang/lib/Tooling/Transformer/Transformer.cpp
diff --git a/interpreter/llvm/src/tools/clang/runtime/CMakeLists.txt b/interpreter/llvm-project/clang/runtime/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/runtime/CMakeLists.txt
rename to interpreter/llvm-project/clang/runtime/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/runtime/compiler-rt/clang_linux_test_input.c b/interpreter/llvm-project/clang/runtime/compiler-rt/clang_linux_test_input.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/runtime/compiler-rt/clang_linux_test_input.c
rename to interpreter/llvm-project/clang/runtime/compiler-rt/clang_linux_test_input.c
diff --git a/interpreter/llvm/src/tools/clang/tools/CMakeLists.txt b/interpreter/llvm-project/clang/tools/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/amdgpu-arch/AMDGPUArch.cpp b/interpreter/llvm-project/clang/tools/amdgpu-arch/AMDGPUArch.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/amdgpu-arch/AMDGPUArch.cpp
rename to interpreter/llvm-project/clang/tools/amdgpu-arch/AMDGPUArch.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/amdgpu-arch/CMakeLists.txt b/interpreter/llvm-project/clang/tools/amdgpu-arch/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/amdgpu-arch/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/amdgpu-arch/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/apinotes-test/APINotesTest.cpp b/interpreter/llvm-project/clang/tools/apinotes-test/APINotesTest.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/apinotes-test/APINotesTest.cpp
rename to interpreter/llvm-project/clang/tools/apinotes-test/APINotesTest.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/apinotes-test/CMakeLists.txt b/interpreter/llvm-project/clang/tools/apinotes-test/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/apinotes-test/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/apinotes-test/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/arcmt-test/CMakeLists.txt b/interpreter/llvm-project/clang/tools/arcmt-test/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/arcmt-test/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/arcmt-test/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/arcmt-test/arcmt-test.cpp b/interpreter/llvm-project/clang/tools/arcmt-test/arcmt-test.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/arcmt-test/arcmt-test.cpp
rename to interpreter/llvm-project/clang/tools/arcmt-test/arcmt-test.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/c-arcmt-test/CMakeLists.txt b/interpreter/llvm-project/clang/tools/c-arcmt-test/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/c-arcmt-test/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/c-arcmt-test/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/c-arcmt-test/c-arcmt-test.c b/interpreter/llvm-project/clang/tools/c-arcmt-test/c-arcmt-test.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/c-arcmt-test/c-arcmt-test.c
rename to interpreter/llvm-project/clang/tools/c-arcmt-test/c-arcmt-test.c
diff --git a/interpreter/llvm/src/tools/clang/tools/c-index-test/CMakeLists.txt b/interpreter/llvm-project/clang/tools/c-index-test/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/c-index-test/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/c-index-test/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/c-index-test/c-index-test.c b/interpreter/llvm-project/clang/tools/c-index-test/c-index-test.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/c-index-test/c-index-test.c
rename to interpreter/llvm-project/clang/tools/c-index-test/c-index-test.c
diff --git a/interpreter/llvm/src/tools/clang/tools/c-index-test/core_main.cpp b/interpreter/llvm-project/clang/tools/c-index-test/core_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/c-index-test/core_main.cpp
rename to interpreter/llvm-project/clang/tools/c-index-test/core_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-check/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-check/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-check/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-check/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-check/ClangCheck.cpp b/interpreter/llvm-project/clang/tools/clang-check/ClangCheck.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-check/ClangCheck.cpp
rename to interpreter/llvm-project/clang/tools/clang-check/ClangCheck.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-diff/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-diff/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-diff/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-diff/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-diff/ClangDiff.cpp b/interpreter/llvm-project/clang/tools/clang-diff/ClangDiff.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-diff/ClangDiff.cpp
rename to interpreter/llvm-project/clang/tools/clang-diff/ClangDiff.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-extdef-mapping/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-extdef-mapping/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-extdef-mapping/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-extdef-mapping/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp b/interpreter/llvm-project/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
rename to interpreter/llvm-project/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/.gitignore b/interpreter/llvm-project/clang/tools/clang-format-vs/.gitignore
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/.gitignore
rename to interpreter/llvm-project/clang/tools/clang-format-vs/.gitignore
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-format-vs/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-format-vs/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat.sln b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat.sln
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat.sln
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat.sln
index 15085c8f4f1fe..46d742bce3f0b 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat.sln
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat.sln
@@ -1,22 +1,22 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.26228.12
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClangFormat", "ClangFormat\ClangFormat.csproj", "{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}"
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Any CPU = Debug|Any CPU
-		Release|Any CPU = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Release|Any CPU.Build.0 = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-EndGlobal
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26228.12
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClangFormat", "ClangFormat\ClangFormat.csproj", "{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj
similarity index 98%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj
index 333c7b1b1c78e..e5b7ec008a1ac 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj
@@ -1,261 +1,261 @@
-
-
-  
-  
-    Debug
-    AnyCPU
-    2.0
-    {7FD1783E-2D31-4D05-BF23-6EBE1B42B608}
-    {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
-    Library
-    Properties
-    LLVM.ClangFormat
-    ClangFormat
-    true
-    Key.snk
-    v4.0
-    15.0
-    
-    
-    
-    
-    4.0
-    publish\
-    true
-    Disk
-    false
-    Foreground
-    7
-    Days
-    false
-    false
-    true
-    0
-    1.0.0.%2a
-    false
-    false
-    true
-    
-  
-  
-    true
-    full
-    false
-    bin\Debug\
-    DEBUG;TRACE
-    prompt
-    4
-    false
-  
-  
-    pdbonly
-    true
-    bin\Release\
-    TRACE
-    prompt
-    4
-    true
-    false
-  
-  
-    
-      True
-    
-    
-      True
-    
-    
-    
-      ..\packages\VSSDK.CoreUtility.10.0.4\lib\net40\Microsoft.VisualStudio.CoreUtility.dll
-      False
-    
-    
-      ..\packages\VSSDK.Editor.10.0.4\lib\net40\Microsoft.VisualStudio.Editor.dll
-      False
-    
-    
-      ..\packages\VSSDK.OLE.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.OLE.Interop.dll
-      True
-      False
-    
-    
-      ..\packages\VSSDK.Shell.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.10.0.dll
-      False
-    
-    
-      ..\packages\VSSDK.Shell.Immutable.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.Immutable.10.0.dll
-      True
-    
-    
-      ..\packages\VSSDK.Shell.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.Shell.Interop.dll
-      True
-      False
-    
-    
-      ..\packages\VSSDK.Shell.Interop.8.8.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.8.0.dll
-      True
-      False
-    
-    
-    
-      ..\packages\VSSDK.Shell.Interop.9.9.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.9.0.dll
-      True
-      False
-    
-    
-      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Data.dll
-      False
-    
-    
-      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Logic.dll
-      False
-    
-    
-      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.dll
-      False
-    
-    
-      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.Wpf.dll
-      False
-    
-    
-      False
-    
-    
-      ..\packages\VSSDK.TextManager.Interop.8.8.0.4\lib\net20\Microsoft.VisualStudio.TextManager.Interop.8.0.dll
-      True
-      False
-    
-    
-    
-    
-      ..\packages\VSSDK.DTE.7.0.3\lib\net20\stdole.dll
-      False
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-  
-  
-    
-      {1CBA492E-7263-47BB-87FE-639000619B15}
-      8
-      0
-      0
-      primary
-      False
-      False
-    
-    
-      {00020430-0000-0000-C000-000000000046}
-      2
-      0
-      0
-      primary
-      False
-      False
-    
-  
-  
-    
-    
-      True
-      True
-      Resources.resx
-    
-    
-    
-      Component
-    
-    
-    
-    
-    
-  
-  
-    
-      ResXFileCodeGenerator
-      Resources.Designer.cs
-      Designer
-    
-    
-      true
-      VSPackage
-    
-  
-  
-    
-    
-      Designer
-    
-    
-      Designer
-    
-  
-  
-    
-      Menus.ctmenu
-    
-  
-  
-    
-  
-  
-    
-      true
-    
-    
-      true
-    
-    
-  
-  
-    
-      False
-      Microsoft .NET Framework 4 %28x86 and x64%29
-      true
-    
-    
-      False
-      .NET Framework 3.5 SP1 Client Profile
-      false
-    
-    
-      False
-      .NET Framework 3.5 SP1
-      false
-    
-    
-      False
-      Windows Installer 4.5
-      true
-    
-  
-  
-    true
-  
-  
-    10.0
-    $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
-  
-  
-  
-  
-  
-    if not exist $(ProjectDir)Key.snk ("$(FrameworkSDKDir)Bin\NETFX 4.6 Tools\sn.exe" -k $(ProjectDir)Key.snk)
-  
-  
-
+
+
+  
+  
+    Debug
+    AnyCPU
+    2.0
+    {7FD1783E-2D31-4D05-BF23-6EBE1B42B608}
+    {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+    Library
+    Properties
+    LLVM.ClangFormat
+    ClangFormat
+    true
+    Key.snk
+    v4.0
+    15.0
+    
+    
+    
+    
+    4.0
+    publish\
+    true
+    Disk
+    false
+    Foreground
+    7
+    Days
+    false
+    false
+    true
+    0
+    1.0.0.%2a
+    false
+    false
+    true
+    
+  
+  
+    true
+    full
+    false
+    bin\Debug\
+    DEBUG;TRACE
+    prompt
+    4
+    false
+  
+  
+    pdbonly
+    true
+    bin\Release\
+    TRACE
+    prompt
+    4
+    true
+    false
+  
+  
+    
+      True
+    
+    
+      True
+    
+    
+    
+      ..\packages\VSSDK.CoreUtility.10.0.4\lib\net40\Microsoft.VisualStudio.CoreUtility.dll
+      False
+    
+    
+      ..\packages\VSSDK.Editor.10.0.4\lib\net40\Microsoft.VisualStudio.Editor.dll
+      False
+    
+    
+      ..\packages\VSSDK.OLE.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.OLE.Interop.dll
+      True
+      False
+    
+    
+      ..\packages\VSSDK.Shell.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.10.0.dll
+      False
+    
+    
+      ..\packages\VSSDK.Shell.Immutable.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.Immutable.10.0.dll
+      True
+    
+    
+      ..\packages\VSSDK.Shell.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.Shell.Interop.dll
+      True
+      False
+    
+    
+      ..\packages\VSSDK.Shell.Interop.8.8.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.8.0.dll
+      True
+      False
+    
+    
+    
+      ..\packages\VSSDK.Shell.Interop.9.9.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.9.0.dll
+      True
+      False
+    
+    
+      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Data.dll
+      False
+    
+    
+      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Logic.dll
+      False
+    
+    
+      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.dll
+      False
+    
+    
+      ..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.Wpf.dll
+      False
+    
+    
+      False
+    
+    
+      ..\packages\VSSDK.TextManager.Interop.8.8.0.4\lib\net20\Microsoft.VisualStudio.TextManager.Interop.8.0.dll
+      True
+      False
+    
+    
+    
+    
+      ..\packages\VSSDK.DTE.7.0.3\lib\net20\stdole.dll
+      False
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+  
+  
+    
+      {1CBA492E-7263-47BB-87FE-639000619B15}
+      8
+      0
+      0
+      primary
+      False
+      False
+    
+    
+      {00020430-0000-0000-C000-000000000046}
+      2
+      0
+      0
+      primary
+      False
+      False
+    
+  
+  
+    
+    
+      True
+      True
+      Resources.resx
+    
+    
+    
+      Component
+    
+    
+    
+    
+    
+  
+  
+    
+      ResXFileCodeGenerator
+      Resources.Designer.cs
+      Designer
+    
+    
+      true
+      VSPackage
+    
+  
+  
+    
+    
+      Designer
+    
+    
+      Designer
+    
+  
+  
+    
+      Menus.ctmenu
+    
+  
+  
+    
+  
+  
+    
+      true
+    
+    
+      true
+    
+    
+  
+  
+    
+      False
+      Microsoft .NET Framework 4 %28x86 and x64%29
+      true
+    
+    
+      False
+      .NET Framework 3.5 SP1 Client Profile
+      false
+    
+    
+      False
+      .NET Framework 3.5 SP1
+      false
+    
+    
+      False
+      Windows Installer 4.5
+      true
+    
+  
+  
+    true
+  
+  
+    10.0
+    $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
+  
+  
+  
+  
+  
+    if not exist $(ProjectDir)Key.snk ("$(FrameworkSDKDir)Bin\NETFX 4.6 Tools\sn.exe" -k $(ProjectDir)Key.snk)
+  
+  
+
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct
index 535dd6e026c87..798957740d548 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormat.vsct
@@ -1,127 +1,127 @@
-
-
-
-  
-
-  
-
-  
-  
-
-  
-  
-
-
-
-
-  
-  
-    
-
-    
-    
-    
-
-      
-        
-      
-      
-
-
-    
-    
-    
-    
-    
-      
-
-      
-
-      
-
-    
-   
-    
-    
-      
-      
-      
-    
- 
-  
-
-
-  
-    
-    
-  
-
-
-
-  
-    
-    
-    
-    
-    
-
-      
-      
-      
-    
-
-    
-
-
-    
-      
-      
-      
-      
-      
-    
-  
-
-
+
+
+
+  
+
+  
+
+  
+  
+
+  
+  
+
+
+
+
+  
+  
+    
+
+    
+    
+    
+
+      
+        
+      
+      
+
+
+    
+    
+    
+    
+    
+      
+
+      
+
+      
+
+    
+   
+    
+    
+      
+      
+      
+    
+ 
+  
+
+
+  
+    
+    
+  
+
+
+
+  
+    
+    
+    
+    
+    
+
+      
+      
+      
+    
+
+    
+
+
+    
+      
+      
+      
+      
+      
+    
+  
+
+
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs
similarity index 98%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs
index a893f9d250021..175a74e291df2 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/GlobalSuppressions.cs
@@ -1,11 +1,11 @@
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project. Project-level
-// suppressions either have no target or are given a specific target
-// and scoped to a namespace, type, member, etc.
-//
-// To add a suppression to this file, right-click the message in the
-// Error List, point to "Suppress Message(s)", and click "In Project
-// Suppression File". You do not need to add suppressions to this
-// file manually.
-
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
+// This file is used by Code Analysis to maintain SuppressMessage
+// attributes that are applied to this project. Project-level
+// suppressions either have no target or are given a specific target
+// and scoped to a namespace, type, member, etc.
+//
+// To add a suppression to this file, right-click the message in the
+// Error List, point to "Suppress Message(s)", and click "In Project
+// Suppression File". You do not need to add suppressions to this
+// file manually.
+
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Guids.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Guids.cs
similarity index 96%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Guids.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Guids.cs
index fb2978a1dea96..ed1c12d61e4ea 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Guids.cs
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Guids.cs
@@ -1,12 +1,12 @@
-using System;
-
-namespace LLVM.ClangFormat
-{
-    static class GuidList
-    {
-        public const string guidClangFormatPkgString = "c5286038-25d3-4f65-83a8-51fa2df4a146";
-        public const string guidClangFormatCmdSetString = "e39cbab1-0f96-4022-a2bc-da5a9db7eb78";
-
-        public static readonly Guid guidClangFormatCmdSet = new Guid(guidClangFormatCmdSetString);
-    };
-}
+using System;
+
+namespace LLVM.ClangFormat
+{
+    static class GuidList
+    {
+        public const string guidClangFormatPkgString = "c5286038-25d3-4f65-83a8-51fa2df4a146";
+        public const string guidClangFormatCmdSetString = "e39cbab1-0f96-4022-a2bc-da5a9db7eb78";
+
+        public static readonly Guid guidClangFormatCmdSet = new Guid(guidClangFormatCmdSetString);
+    };
+}
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs
similarity index 96%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs
index a3b0df20c760d..c274d1ca1b4b2 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/PkgCmdID.cs
@@ -1,8 +1,8 @@
-namespace LLVM.ClangFormat
-{
-    static class PkgCmdIDList
-    {
-        public const uint cmdidClangFormatSelection = 0x100;
-        public const uint cmdidClangFormatDocument = 0x101;
-    };
-}
+namespace LLVM.ClangFormat
+{
+    static class PkgCmdIDList
+    {
+        public const uint cmdidClangFormatSelection = 0x100;
+        public const uint cmdidClangFormatDocument = 0x101;
+    };
+}
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
index 58dad21791bbb..b1cef49414b5e 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
@@ -1,33 +1,33 @@
-using System;
-using System.Reflection;
-using System.Resources;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following 
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("ClangFormat")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("LLVM")]
-[assembly: AssemblyProduct("ClangFormat")]
-[assembly: AssemblyCopyright("")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: ComVisible(false)]
-[assembly: CLSCompliant(false)]
-[assembly: NeutralResourcesLanguage("en-US")]
-
-// Version information for an assembly consists of the following four values:
-//
-//      Major Version
-//      Minor Version 
-//      Build Number
-//      Revision
-//
-// You can specify all the values or you can default the Revision and Build Numbers 
-// by using the '*' as shown below:
-
-[assembly: AssemblyVersion("1.1.0.0")]
-[assembly: AssemblyFileVersion("1.1.0.0")]
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ClangFormat")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("LLVM")]
+[assembly: AssemblyProduct("ClangFormat")]
+[assembly: AssemblyCopyright("")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: ComVisible(false)]
+[assembly: CLSCompliant(false)]
+[assembly: NeutralResourcesLanguage("en-US")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Revision and Build Numbers 
+// by using the '*' as shown below:
+
+[assembly: AssemblyVersion("1.1.0.0")]
+[assembly: AssemblyFileVersion("1.1.0.0")]
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs
index e9c051988f68d..e3129b3db83ae 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.Designer.cs
@@ -1,63 +1,63 @@
-//------------------------------------------------------------------------------
-// 
-//     This code was generated by a tool.
-//     Runtime Version:4.0.30319.42000
-//
-//     Changes to this file may cause incorrect behavior and will be lost if
-//     the code is regenerated.
-// 
-//------------------------------------------------------------------------------
-
-namespace LLVM.ClangFormat {
-    using System;
-    
-    
-    /// 
-    ///   A strongly-typed resource class, for looking up localized strings, etc.
-    /// 
-    // This class was auto-generated by the StronglyTypedResourceBuilder
-    // class via a tool like ResGen or Visual Studio.
-    // To add or remove a member, edit your .ResX file then rerun ResGen
-    // with the /str option, or rebuild your VS project.
-    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
-    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
-    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
-    internal class Resources {
-        
-        private static global::System.Resources.ResourceManager resourceMan;
-        
-        private static global::System.Globalization.CultureInfo resourceCulture;
-        
-        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
-        internal Resources() {
-        }
-        
-        /// 
-        ///   Returns the cached ResourceManager instance used by this class.
-        /// 
-        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
-        internal static global::System.Resources.ResourceManager ResourceManager {
-            get {
-                if (object.ReferenceEquals(resourceMan, null)) {
-                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LLVM.ClangFormat.Resources", typeof(Resources).Assembly);
-                    resourceMan = temp;
-                }
-                return resourceMan;
-            }
-        }
-        
-        /// 
-        ///   Overrides the current thread's CurrentUICulture property for all
-        ///   resource lookups using this strongly typed resource class.
-        /// 
-        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
-        internal static global::System.Globalization.CultureInfo Culture {
-            get {
-                return resourceCulture;
-            }
-            set {
-                resourceCulture = value;
-            }
-        }
-    }
-}
+//------------------------------------------------------------------------------
+// 
+//     This code was generated by a tool.
+//     Runtime Version:4.0.30319.42000
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// 
+//------------------------------------------------------------------------------
+
+namespace LLVM.ClangFormat {
+    using System;
+    
+    
+    /// 
+    ///   A strongly-typed resource class, for looking up localized strings, etc.
+    /// 
+    // This class was auto-generated by the StronglyTypedResourceBuilder
+    // class via a tool like ResGen or Visual Studio.
+    // To add or remove a member, edit your .ResX file then rerun ResGen
+    // with the /str option, or rebuild your VS project.
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    internal class Resources {
+        
+        private static global::System.Resources.ResourceManager resourceMan;
+        
+        private static global::System.Globalization.CultureInfo resourceCulture;
+        
+        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+        internal Resources() {
+        }
+        
+        /// 
+        ///   Returns the cached ResourceManager instance used by this class.
+        /// 
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Resources.ResourceManager ResourceManager {
+            get {
+                if (object.ReferenceEquals(resourceMan, null)) {
+                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LLVM.ClangFormat.Resources", typeof(Resources).Assembly);
+                    resourceMan = temp;
+                }
+                return resourceMan;
+            }
+        }
+        
+        /// 
+        ///   Overrides the current thread's CurrentUICulture property for all
+        ///   resource lookups using this strongly typed resource class.
+        /// 
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Globalization.CultureInfo Culture {
+            get {
+                return resourceCulture;
+            }
+            set {
+                resourceCulture = value;
+            }
+        }
+    }
+}
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.resx b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.resx
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.resx
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.resx
index 891c592b4f31f..352987aa07bc6 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources.resx
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources.resx
@@ -1,129 +1,129 @@
-
-
-
-  
-  
-    
-    
-      
-        
-          
-            
-              
-                
-              
-              
-              
-              
-              
-            
-          
-          
-            
-              
-              
-            
-          
-          
-            
-              
-                
-                
-              
-              
-              
-              
-              
-            
-          
-          
-            
-              
-                
-              
-              
-            
-          
-        
-      
-    
-  
-  
-    text/microsoft-resx
-  
-  
-    2.0
-  
-  
-    System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-  
-  
-    System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-  
+
+
+
+  
+  
+    
+    
+      
+        
+          
+            
+              
+                
+              
+              
+              
+              
+              
+            
+          
+          
+            
+              
+              
+            
+          
+          
+            
+              
+                
+                
+              
+              
+              
+              
+              
+            
+          
+          
+            
+              
+                
+              
+              
+            
+          
+        
+      
+    
+  
+  
+    text/microsoft-resx
+  
+  
+    2.0
+  
+  
+    System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+  
+  
+    System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+  
 
\ No newline at end of file
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources/Images_32bit.bmp b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources/Images_32bit.bmp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources/Images_32bit.bmp
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources/Images_32bit.bmp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources/Package.ico b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources/Package.ico
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Resources/Package.ico
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Resources/Package.ico
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/RunningDocTableEventsDispatcher.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/RunningDocTableEventsDispatcher.cs
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/RunningDocTableEventsDispatcher.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/RunningDocTableEventsDispatcher.cs
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx
similarity index 98%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx
index 6d64e89ab8d68..81102d38a07a5 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/VSPackage.resx
@@ -1,140 +1,140 @@
-
-
-
-  
-  
-    
-    
-      
-        
-          
-            
-              
-                
-              
-              
-              
-              
-              
-            
-          
-          
-            
-              
-              
-            
-          
-          
-            
-              
-                
-                
-              
-              
-              
-              
-              
-            
-          
-          
-            
-              
-                
-              
-              
-            
-          
-        
-      
-    
-  
-  
-    text/microsoft-resx
-  
-  
-    2.0
-  
-  
-    System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-  
-  
-    System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-  
-  
-  
-    ClangFormat
-  
-  
-    Formats code by calling the clang-format executable.
-  
-  
-    Resources\Package.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
-  
+
+
+
+  
+  
+    
+    
+      
+        
+          
+            
+              
+                
+              
+              
+              
+              
+              
+            
+          
+          
+            
+              
+              
+            
+          
+          
+            
+              
+                
+                
+              
+              
+              
+              
+              
+            
+          
+          
+            
+              
+                
+              
+              
+            
+          
+        
+      
+    
+  
+  
+    text/microsoft-resx
+  
+  
+    2.0
+  
+  
+    System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+  
+  
+    System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+  
+  
+  
+    ClangFormat
+  
+  
+    Formats code by calling the clang-format executable.
+  
+  
+    Resources\Package.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
+  
 
\ No newline at end of file
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Vsix.cs b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Vsix.cs
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/Vsix.cs
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/Vsix.cs
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/license.txt b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/license.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/license.txt
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/license.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/packages.config b/interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/packages.config
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/ClangFormat/packages.config
rename to interpreter/llvm-project/clang/tools/clang-format-vs/ClangFormat/packages.config
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/README.txt b/interpreter/llvm-project/clang/tools/clang-format-vs/README.txt
similarity index 97%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/README.txt
rename to interpreter/llvm-project/clang/tools/clang-format-vs/README.txt
index 6593480080eaa..2cac5b9af9e3c 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/README.txt
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/README.txt
@@ -1,51 +1,51 @@
-This directory contains a VSPackage project to generate a Visual Studio extension
-for clang-format.
-
-Build prerequisites are:
-- Visual Studio 2015
-- Extensions SDK (you'll be prompted to install it if you open ClangFormat.sln)
-
-The extension is built using CMake to generate the usual LLVM.sln by setting
-the following CMake vars:
-
-- BUILD_CLANG_FORMAT_VS_PLUGIN=ON
-
-- NUGET_EXE_DIR=path/to/nuget_dir (unless nuget.exe is already available in PATH)
-
-example:
-  cd /d C:\code\llvm
-  mkdir build & cd build
-  cmake -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON -DNUGET_EXE_DIR=C:\nuget ..
-
-Once LLVM.sln is generated, build the clang_format_vsix target, which will build
-ClangFormat.sln, the C# extension application.
-
-The CMake build will copy clang-format.exe and LICENSE.TXT into the ClangFormat/
-directory so they can be bundled with the plug-in, as well as creating
-ClangFormat/source.extension.vsixmanifest. Once the plug-in has been built with
-CMake once, it can be built manually from the ClangFormat.sln solution in Visual
-Studio.
-
-===========
- Debugging
-===========
-
-Once you've built the clang_format_vsix project from LLVM.sln at least once,
-open ClangFormat.sln in Visual Studio, then:
-
-- Make sure the "Debug" target is selected
-- Open the ClangFormat project properties
-- Select the Debug tab
-- Set "Start external program:" to where your devenv.exe is installed. Typically
-  it's "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
-- Set "Command line arguments" to: /rootsuffix Exp
-- You can now set breakpoints if you like
-- Press F5 to build and run with debugger
-
-If all goes well, a new instance of Visual Studio will be launched in a special
-mode where it uses the experimental hive instead of the normal configuration hive.
-By default, when you build a VSIX project in Visual Studio, it auto-registers the
-extension in the experimental hive, allowing you to test it. In the new Visual Studio
-instance, open or create a C++ solution, and you should now see the Clang Format
-entries in the Tool menu. You can test it out, and any breakpoints you set will be
-hit where you can debug as usual.
+This directory contains a VSPackage project to generate a Visual Studio extension
+for clang-format.
+
+Build prerequisites are:
+- Visual Studio 2015
+- Extensions SDK (you'll be prompted to install it if you open ClangFormat.sln)
+
+The extension is built using CMake to generate the usual LLVM.sln by setting
+the following CMake vars:
+
+- BUILD_CLANG_FORMAT_VS_PLUGIN=ON
+
+- NUGET_EXE_DIR=path/to/nuget_dir (unless nuget.exe is already available in PATH)
+
+example:
+  cd /d C:\code\llvm
+  mkdir build & cd build
+  cmake -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON -DNUGET_EXE_DIR=C:\nuget ..
+
+Once LLVM.sln is generated, build the clang_format_vsix target, which will build
+ClangFormat.sln, the C# extension application.
+
+The CMake build will copy clang-format.exe and LICENSE.TXT into the ClangFormat/
+directory so they can be bundled with the plug-in, as well as creating
+ClangFormat/source.extension.vsixmanifest. Once the plug-in has been built with
+CMake once, it can be built manually from the ClangFormat.sln solution in Visual
+Studio.
+
+===========
+ Debugging
+===========
+
+Once you've built the clang_format_vsix project from LLVM.sln at least once,
+open ClangFormat.sln in Visual Studio, then:
+
+- Make sure the "Debug" target is selected
+- Open the ClangFormat project properties
+- Select the Debug tab
+- Set "Start external program:" to where your devenv.exe is installed. Typically
+  it's "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
+- Set "Command line arguments" to: /rootsuffix Exp
+- You can now set breakpoints if you like
+- Press F5 to build and run with debugger
+
+If all goes well, a new instance of Visual Studio will be launched in a special
+mode where it uses the experimental hive instead of the normal configuration hive.
+By default, when you build a VSIX project in Visual Studio, it auto-registers the
+extension in the experimental hive, allowing you to test it. In the new Visual Studio
+instance, open or create a C++ solution, and you should now see the Clang Format
+entries in the Tool menu. You can test it out, and any breakpoints you set will be
+hit where you can debug as usual.
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/source.extension.vsixmanifest.in b/interpreter/llvm-project/clang/tools/clang-format-vs/source.extension.vsixmanifest.in
similarity index 98%
rename from interpreter/llvm/src/tools/clang/tools/clang-format-vs/source.extension.vsixmanifest.in
rename to interpreter/llvm-project/clang/tools/clang-format-vs/source.extension.vsixmanifest.in
index beb2f611cc1f6..d4820c051ad72 100644
--- a/interpreter/llvm/src/tools/clang/tools/clang-format-vs/source.extension.vsixmanifest.in
+++ b/interpreter/llvm-project/clang/tools/clang-format-vs/source.extension.vsixmanifest.in
@@ -1,19 +1,19 @@
-
-
-  
-    
-    ClangFormat
-    A tool to format C/C++/Obj-C code.
-    http://clang.llvm.org/docs/ClangFormat.html
-    license.txt
-  
-  
-    
-  
-  
-    
-  
-  
-    
-  
-
+
+
+  
+    
+    ClangFormat
+    A tool to format C/C++/Obj-C code.
+    http://clang.llvm.org/docs/ClangFormat.html
+    license.txt
+  
+  
+    
+  
+  
+    
+  
+  
+    
+  
+
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-format/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-format/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/ClangFormat.cpp b/interpreter/llvm-project/clang/tools/clang-format/ClangFormat.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/ClangFormat.cpp
rename to interpreter/llvm-project/clang/tools/clang-format/ClangFormat.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-bbedit.applescript b/interpreter/llvm-project/clang/tools/clang-format/clang-format-bbedit.applescript
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-bbedit.applescript
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format-bbedit.applescript
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-diff.py b/interpreter/llvm-project/clang/tools/clang-format/clang-format-diff.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-diff.py
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format-diff.py
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-sublime.py b/interpreter/llvm-project/clang/tools/clang-format/clang-format-sublime.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-sublime.py
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format-sublime.py
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-test.el b/interpreter/llvm-project/clang/tools/clang-format/clang-format-test.el
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format-test.el
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format-test.el
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format.el b/interpreter/llvm-project/clang/tools/clang-format/clang-format.el
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format.el
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format.el
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/clang-format.py b/interpreter/llvm-project/clang/tools/clang-format/clang-format.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/clang-format.py
rename to interpreter/llvm-project/clang/tools/clang-format/clang-format.py
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/fuzzer/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-format/fuzzer/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/fuzzer/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-format/fuzzer/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-format/git-clang-format b/interpreter/llvm-project/clang/tools/clang-format/git-clang-format
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-format/git-clang-format
rename to interpreter/llvm-project/clang/tools/clang-format/git-clang-format
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ClangFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/ClangFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ClangFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/ClangFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ClangObjectiveCFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/ClangObjectiveCFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ClangObjectiveCFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/ClangObjectiveCFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/Dockerfile b/interpreter/llvm-project/clang/tools/clang-fuzzer/Dockerfile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/Dockerfile
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/Dockerfile
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/DummyClangFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/DummyClangFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/DummyClangFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/DummyClangFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangLLVMProtoFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangLLVMProtoFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangLLVMProtoFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangLLVMProtoFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangLoopProtoFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangLoopProtoFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangLoopProtoFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangLoopProtoFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangProtoFuzzer.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangProtoFuzzer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/ExampleClangProtoFuzzer.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/ExampleClangProtoFuzzer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/README.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/README.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/README.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/BasicClass.m b/interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/BasicClass.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/BasicClass.m
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/BasicClass.m
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/ClassCategory.m b/interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/ClassCategory.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/ClassCategory.m
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/ClassCategory.m
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/ClassExtension.m b/interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/ClassExtension.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/ClassExtension.m
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/ClassExtension.m
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/SharedInstance.m b/interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/SharedInstance.m
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/corpus_examples/objc/SharedInstance.m
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/corpus_examples/objc/SharedInstance.m
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/cxx_loop_proto.proto b/interpreter/llvm-project/clang/tools/clang-fuzzer/cxx_loop_proto.proto
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/cxx_loop_proto.proto
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/cxx_loop_proto.proto
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/cxx_proto.proto b/interpreter/llvm-project/clang/tools/clang-fuzzer/cxx_proto.proto
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/cxx_proto.proto
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/cxx_proto.proto
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/input_arrays.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/input_arrays.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/handle-llvm/input_arrays.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/handle-llvm/input_arrays.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx_main.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx_main.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/loop_proto_to_cxx_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm_main.cpp b/interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm_main.cpp
rename to interpreter/llvm-project/clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-import-test/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-import-test/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-import-test/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-import-test/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-import-test/clang-import-test.cpp b/interpreter/llvm-project/clang/tools/clang-import-test/clang-import-test.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-import-test/clang-import-test.cpp
rename to interpreter/llvm-project/clang/tools/clang-import-test/clang-import-test.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-offload-bundler/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-offload-bundler/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-offload-bundler/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-offload-bundler/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp b/interpreter/llvm-project/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
rename to interpreter/llvm-project/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-offload-wrapper/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-offload-wrapper/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-offload-wrapper/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-offload-wrapper/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp b/interpreter/llvm-project/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
rename to interpreter/llvm-project/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-refactor/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-refactor/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-refactor/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-refactor/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-refactor/ClangRefactor.cpp b/interpreter/llvm-project/clang/tools/clang-refactor/ClangRefactor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-refactor/ClangRefactor.cpp
rename to interpreter/llvm-project/clang/tools/clang-refactor/ClangRefactor.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-refactor/TestSupport.cpp b/interpreter/llvm-project/clang/tools/clang-refactor/TestSupport.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-refactor/TestSupport.cpp
rename to interpreter/llvm-project/clang/tools/clang-refactor/TestSupport.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-refactor/TestSupport.h b/interpreter/llvm-project/clang/tools/clang-refactor/TestSupport.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-refactor/TestSupport.h
rename to interpreter/llvm-project/clang/tools/clang-refactor/TestSupport.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-refactor/ToolRefactoringResultConsumer.h b/interpreter/llvm-project/clang/tools/clang-refactor/ToolRefactoringResultConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-refactor/ToolRefactoringResultConsumer.h
rename to interpreter/llvm-project/clang/tools/clang-refactor/ToolRefactoringResultConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-rename/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-rename/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-rename/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-rename/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-rename/ClangRename.cpp b/interpreter/llvm-project/clang/tools/clang-rename/ClangRename.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-rename/ClangRename.cpp
rename to interpreter/llvm-project/clang/tools/clang-rename/ClangRename.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-rename/clang-rename.el b/interpreter/llvm-project/clang/tools/clang-rename/clang-rename.el
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-rename/clang-rename.el
rename to interpreter/llvm-project/clang/tools/clang-rename/clang-rename.el
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-rename/clang-rename.py b/interpreter/llvm-project/clang/tools/clang-rename/clang-rename.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-rename/clang-rename.py
rename to interpreter/llvm-project/clang/tools/clang-rename/clang-rename.py
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-repl/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-repl/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-repl/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-repl/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-repl/ClangRepl.cpp b/interpreter/llvm-project/clang/tools/clang-repl/ClangRepl.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-repl/ClangRepl.cpp
rename to interpreter/llvm-project/clang/tools/clang-repl/ClangRepl.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-scan-deps/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-scan-deps/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-scan-deps/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-scan-deps/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-scan-deps/ClangScanDeps.cpp b/interpreter/llvm-project/clang/tools/clang-scan-deps/ClangScanDeps.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-scan-deps/ClangScanDeps.cpp
rename to interpreter/llvm-project/clang/tools/clang-scan-deps/ClangScanDeps.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-shlib/CMakeLists.txt b/interpreter/llvm-project/clang/tools/clang-shlib/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-shlib/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/clang-shlib/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/clang-shlib/clang-shlib.cpp b/interpreter/llvm-project/clang/tools/clang-shlib/clang-shlib.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/clang-shlib/clang-shlib.cpp
rename to interpreter/llvm-project/clang/tools/clang-shlib/clang-shlib.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diag-build/diag-build.sh b/interpreter/llvm-project/clang/tools/diag-build/diag-build.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diag-build/diag-build.sh
rename to interpreter/llvm-project/clang/tools/diag-build/diag-build.sh
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/CMakeLists.txt b/interpreter/llvm-project/clang/tools/diagtool/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/diagtool/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/DiagTool.cpp b/interpreter/llvm-project/clang/tools/diagtool/DiagTool.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/DiagTool.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/DiagTool.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/DiagTool.h b/interpreter/llvm-project/clang/tools/diagtool/DiagTool.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/DiagTool.h
rename to interpreter/llvm-project/clang/tools/diagtool/DiagTool.h
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/DiagnosticNames.cpp b/interpreter/llvm-project/clang/tools/diagtool/DiagnosticNames.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/DiagnosticNames.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/DiagnosticNames.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/DiagnosticNames.h b/interpreter/llvm-project/clang/tools/diagtool/DiagnosticNames.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/DiagnosticNames.h
rename to interpreter/llvm-project/clang/tools/diagtool/DiagnosticNames.h
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/FindDiagnosticID.cpp b/interpreter/llvm-project/clang/tools/diagtool/FindDiagnosticID.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/FindDiagnosticID.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/FindDiagnosticID.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/ListWarnings.cpp b/interpreter/llvm-project/clang/tools/diagtool/ListWarnings.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/ListWarnings.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/ListWarnings.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/ShowEnabledWarnings.cpp b/interpreter/llvm-project/clang/tools/diagtool/ShowEnabledWarnings.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/ShowEnabledWarnings.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/ShowEnabledWarnings.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/TreeView.cpp b/interpreter/llvm-project/clang/tools/diagtool/TreeView.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/TreeView.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/TreeView.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/diagtool/diagtool_main.cpp b/interpreter/llvm-project/clang/tools/diagtool/diagtool_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/diagtool/diagtool_main.cpp
rename to interpreter/llvm-project/clang/tools/diagtool/diagtool_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/CMakeLists.txt b/interpreter/llvm-project/clang/tools/driver/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/driver/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/Info.plist.in b/interpreter/llvm-project/clang/tools/driver/Info.plist.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/Info.plist.in
rename to interpreter/llvm-project/clang/tools/driver/Info.plist.in
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/cc1_main.cpp b/interpreter/llvm-project/clang/tools/driver/cc1_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/cc1_main.cpp
rename to interpreter/llvm-project/clang/tools/driver/cc1_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/cc1as_main.cpp b/interpreter/llvm-project/clang/tools/driver/cc1as_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/cc1as_main.cpp
rename to interpreter/llvm-project/clang/tools/driver/cc1as_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/cc1gen_reproducer_main.cpp b/interpreter/llvm-project/clang/tools/driver/cc1gen_reproducer_main.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/cc1gen_reproducer_main.cpp
rename to interpreter/llvm-project/clang/tools/driver/cc1gen_reproducer_main.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/driver/driver.cpp b/interpreter/llvm-project/clang/tools/driver/driver.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/driver/driver.cpp
rename to interpreter/llvm-project/clang/tools/driver/driver.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/ARCMigrate.cpp b/interpreter/llvm-project/clang/tools/libclang/ARCMigrate.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/ARCMigrate.cpp
rename to interpreter/llvm-project/clang/tools/libclang/ARCMigrate.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/BuildSystem.cpp b/interpreter/llvm-project/clang/tools/libclang/BuildSystem.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/BuildSystem.cpp
rename to interpreter/llvm-project/clang/tools/libclang/BuildSystem.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndex.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndex.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndex.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndex.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexCXX.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexCXX.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexCXX.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexCXX.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexCodeCompletion.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexCodeCompletion.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexCodeCompletion.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexCodeCompletion.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexDiagnostic.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexDiagnostic.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexDiagnostic.h b/interpreter/llvm-project/clang/tools/libclang/CIndexDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexDiagnostic.h
rename to interpreter/llvm-project/clang/tools/libclang/CIndexDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexHigh.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexHigh.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexHigh.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexHigh.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexInclusionStack.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexInclusionStack.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexInclusionStack.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexInclusionStack.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexUSRs.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexUSRs.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexUSRs.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexUSRs.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexer.cpp b/interpreter/llvm-project/clang/tools/libclang/CIndexer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexer.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CIndexer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CIndexer.h b/interpreter/llvm-project/clang/tools/libclang/CIndexer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CIndexer.h
rename to interpreter/llvm-project/clang/tools/libclang/CIndexer.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CLog.h b/interpreter/llvm-project/clang/tools/libclang/CLog.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CLog.h
rename to interpreter/llvm-project/clang/tools/libclang/CLog.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CMakeLists.txt b/interpreter/llvm-project/clang/tools/libclang/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/libclang/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXComment.cpp b/interpreter/llvm-project/clang/tools/libclang/CXComment.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXComment.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXComment.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXComment.h b/interpreter/llvm-project/clang/tools/libclang/CXComment.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXComment.h
rename to interpreter/llvm-project/clang/tools/libclang/CXComment.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXCompilationDatabase.cpp b/interpreter/llvm-project/clang/tools/libclang/CXCompilationDatabase.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXCompilationDatabase.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXCompilationDatabase.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXCursor.cpp b/interpreter/llvm-project/clang/tools/libclang/CXCursor.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXCursor.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXCursor.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXCursor.h b/interpreter/llvm-project/clang/tools/libclang/CXCursor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXCursor.h
rename to interpreter/llvm-project/clang/tools/libclang/CXCursor.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXIndexDataConsumer.cpp b/interpreter/llvm-project/clang/tools/libclang/CXIndexDataConsumer.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXIndexDataConsumer.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXIndexDataConsumer.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXIndexDataConsumer.h b/interpreter/llvm-project/clang/tools/libclang/CXIndexDataConsumer.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXIndexDataConsumer.h
rename to interpreter/llvm-project/clang/tools/libclang/CXIndexDataConsumer.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXLoadedDiagnostic.cpp b/interpreter/llvm-project/clang/tools/libclang/CXLoadedDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXLoadedDiagnostic.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXLoadedDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXLoadedDiagnostic.h b/interpreter/llvm-project/clang/tools/libclang/CXLoadedDiagnostic.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXLoadedDiagnostic.h
rename to interpreter/llvm-project/clang/tools/libclang/CXLoadedDiagnostic.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXSourceLocation.cpp b/interpreter/llvm-project/clang/tools/libclang/CXSourceLocation.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXSourceLocation.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXSourceLocation.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXSourceLocation.h b/interpreter/llvm-project/clang/tools/libclang/CXSourceLocation.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXSourceLocation.h
rename to interpreter/llvm-project/clang/tools/libclang/CXSourceLocation.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXStoredDiagnostic.cpp b/interpreter/llvm-project/clang/tools/libclang/CXStoredDiagnostic.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXStoredDiagnostic.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXStoredDiagnostic.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXString.cpp b/interpreter/llvm-project/clang/tools/libclang/CXString.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXString.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXString.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXString.h b/interpreter/llvm-project/clang/tools/libclang/CXString.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXString.h
rename to interpreter/llvm-project/clang/tools/libclang/CXString.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXTranslationUnit.h b/interpreter/llvm-project/clang/tools/libclang/CXTranslationUnit.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXTranslationUnit.h
rename to interpreter/llvm-project/clang/tools/libclang/CXTranslationUnit.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXType.cpp b/interpreter/llvm-project/clang/tools/libclang/CXType.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXType.cpp
rename to interpreter/llvm-project/clang/tools/libclang/CXType.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CXType.h b/interpreter/llvm-project/clang/tools/libclang/CXType.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CXType.h
rename to interpreter/llvm-project/clang/tools/libclang/CXType.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/CursorVisitor.h b/interpreter/llvm-project/clang/tools/libclang/CursorVisitor.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/CursorVisitor.h
rename to interpreter/llvm-project/clang/tools/libclang/CursorVisitor.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/FatalErrorHandler.cpp b/interpreter/llvm-project/clang/tools/libclang/FatalErrorHandler.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/FatalErrorHandler.cpp
rename to interpreter/llvm-project/clang/tools/libclang/FatalErrorHandler.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/Index_Internal.h b/interpreter/llvm-project/clang/tools/libclang/Index_Internal.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/Index_Internal.h
rename to interpreter/llvm-project/clang/tools/libclang/Index_Internal.h
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/Indexing.cpp b/interpreter/llvm-project/clang/tools/libclang/Indexing.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/Indexing.cpp
rename to interpreter/llvm-project/clang/tools/libclang/Indexing.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/Rewrite.cpp b/interpreter/llvm-project/clang/tools/libclang/Rewrite.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/Rewrite.cpp
rename to interpreter/llvm-project/clang/tools/libclang/Rewrite.cpp
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/libclang.map b/interpreter/llvm-project/clang/tools/libclang/libclang.map
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/libclang.map
rename to interpreter/llvm-project/clang/tools/libclang/libclang.map
diff --git a/interpreter/llvm/src/tools/clang/tools/libclang/linker-script-to-export-list.py b/interpreter/llvm-project/clang/tools/libclang/linker-script-to-export-list.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/libclang/linker-script-to-export-list.py
rename to interpreter/llvm-project/clang/tools/libclang/linker-script-to-export-list.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/CMakeLists.txt b/interpreter/llvm-project/clang/tools/scan-build-py/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/scan-build-py/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/README.md b/interpreter/llvm-project/clang/tools/scan-build-py/README.md
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/README.md
rename to interpreter/llvm-project/clang/tools/scan-build-py/README.md
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/analyze-build b/interpreter/llvm-project/clang/tools/scan-build-py/bin/analyze-build
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/analyze-build
rename to interpreter/llvm-project/clang/tools/scan-build-py/bin/analyze-build
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/intercept-build b/interpreter/llvm-project/clang/tools/scan-build-py/bin/intercept-build
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/intercept-build
rename to interpreter/llvm-project/clang/tools/scan-build-py/bin/intercept-build
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/scan-build b/interpreter/llvm-project/clang/tools/scan-build-py/bin/scan-build
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/bin/scan-build
rename to interpreter/llvm-project/clang/tools/scan-build-py/bin/scan-build
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/__init__.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/__init__.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/__init__.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/__init__.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/config.h.in b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/config.h.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/config.h.in
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/config.h.in
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/ear.c b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/ear.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libear/ear.c
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libear/ear.c
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/__init__.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/__init__.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/__init__.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/__init__.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/analyze.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/analyze.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/arguments.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/arguments.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/arguments.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/arguments.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/clang.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/clang.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/clang.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/clang.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/compilation.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/compilation.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/compilation.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/compilation.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/intercept.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/intercept.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/intercept.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/intercept.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/report.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/report.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/report.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/report.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/scanview.css b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/scanview.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/scanview.css
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/scanview.css
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/selectable.js b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/selectable.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/selectable.js
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/selectable.js
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/sorttable.js b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/sorttable.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/resources/sorttable.js
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/resources/sorttable.js
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/shell.py b/interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/shell.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/lib/libscanbuild/shell.py
rename to interpreter/llvm-project/clang/tools/scan-build-py/lib/libscanbuild/shell.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/analyze-c++ b/interpreter/llvm-project/clang/tools/scan-build-py/libexec/analyze-c++
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/analyze-c++
rename to interpreter/llvm-project/clang/tools/scan-build-py/libexec/analyze-c++
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/analyze-cc b/interpreter/llvm-project/clang/tools/scan-build-py/libexec/analyze-cc
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/analyze-cc
rename to interpreter/llvm-project/clang/tools/scan-build-py/libexec/analyze-cc
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/intercept-c++ b/interpreter/llvm-project/clang/tools/scan-build-py/libexec/intercept-c++
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/intercept-c++
rename to interpreter/llvm-project/clang/tools/scan-build-py/libexec/intercept-c++
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/intercept-cc b/interpreter/llvm-project/clang/tools/scan-build-py/libexec/intercept-cc
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/libexec/intercept-cc
rename to interpreter/llvm-project/clang/tools/scan-build-py/libexec/intercept-cc
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/resources/sorttable.js b/interpreter/llvm-project/clang/tools/scan-build-py/libscanbuild/resources/sorttable.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/resources/sorttable.js
rename to interpreter/llvm-project/clang/tools/scan-build-py/libscanbuild/resources/sorttable.js
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/CMakeLists.txt b/interpreter/llvm-project/clang/tools/scan-build/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/scan-build/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/bin/scan-build b/interpreter/llvm-project/clang/tools/scan-build/bin/scan-build
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/bin/scan-build
rename to interpreter/llvm-project/clang/tools/scan-build/bin/scan-build
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/bin/scan-build.bat b/interpreter/llvm-project/clang/tools/scan-build/bin/scan-build.bat
similarity index 95%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/bin/scan-build.bat
rename to interpreter/llvm-project/clang/tools/scan-build/bin/scan-build.bat
index f765f205b8ec5..77be6746318f1 100644
--- a/interpreter/llvm/src/tools/clang/tools/scan-build/bin/scan-build.bat
+++ b/interpreter/llvm-project/clang/tools/scan-build/bin/scan-build.bat
@@ -1 +1 @@
-perl -S scan-build %*
+perl -S scan-build %*
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/bin/set-xcode-analyzer b/interpreter/llvm-project/clang/tools/scan-build/bin/set-xcode-analyzer
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/bin/set-xcode-analyzer
rename to interpreter/llvm-project/clang/tools/scan-build/bin/set-xcode-analyzer
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/c++-analyzer b/interpreter/llvm-project/clang/tools/scan-build/libexec/c++-analyzer
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/libexec/c++-analyzer
rename to interpreter/llvm-project/clang/tools/scan-build/libexec/c++-analyzer
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/c++-analyzer.bat b/interpreter/llvm-project/clang/tools/scan-build/libexec/c++-analyzer.bat
similarity index 96%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/libexec/c++-analyzer.bat
rename to interpreter/llvm-project/clang/tools/scan-build/libexec/c++-analyzer.bat
index 83c7172456a51..69f048a91671f 100644
--- a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/c++-analyzer.bat
+++ b/interpreter/llvm-project/clang/tools/scan-build/libexec/c++-analyzer.bat
@@ -1 +1 @@
-perl -S c++-analyzer %*
+perl -S c++-analyzer %*
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/ccc-analyzer b/interpreter/llvm-project/clang/tools/scan-build/libexec/ccc-analyzer
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/libexec/ccc-analyzer
rename to interpreter/llvm-project/clang/tools/scan-build/libexec/ccc-analyzer
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/ccc-analyzer.bat b/interpreter/llvm-project/clang/tools/scan-build/libexec/ccc-analyzer.bat
similarity index 96%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/libexec/ccc-analyzer.bat
rename to interpreter/llvm-project/clang/tools/scan-build/libexec/ccc-analyzer.bat
index fdd36f3bdd043..2a85376eb82b1 100644
--- a/interpreter/llvm/src/tools/clang/tools/scan-build/libexec/ccc-analyzer.bat
+++ b/interpreter/llvm-project/clang/tools/scan-build/libexec/ccc-analyzer.bat
@@ -1 +1 @@
-perl -S ccc-analyzer %*
+perl -S ccc-analyzer %*
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/man/scan-build.1 b/interpreter/llvm-project/clang/tools/scan-build/man/scan-build.1
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/man/scan-build.1
rename to interpreter/llvm-project/clang/tools/scan-build/man/scan-build.1
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/share/scan-build/scanview.css b/interpreter/llvm-project/clang/tools/scan-build/share/scan-build/scanview.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/share/scan-build/scanview.css
rename to interpreter/llvm-project/clang/tools/scan-build/share/scan-build/scanview.css
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build/share/scan-build/sorttable.js b/interpreter/llvm-project/clang/tools/scan-build/share/scan-build/sorttable.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-build/share/scan-build/sorttable.js
rename to interpreter/llvm-project/clang/tools/scan-build/share/scan-build/sorttable.js
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/CMakeLists.txt b/interpreter/llvm-project/clang/tools/scan-view/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/CMakeLists.txt
rename to interpreter/llvm-project/clang/tools/scan-view/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/bin/scan-view b/interpreter/llvm-project/clang/tools/scan-view/bin/scan-view
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/bin/scan-view
rename to interpreter/llvm-project/clang/tools/scan-view/bin/scan-view
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/share/Reporter.py b/interpreter/llvm-project/clang/tools/scan-view/share/Reporter.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/share/Reporter.py
rename to interpreter/llvm-project/clang/tools/scan-view/share/Reporter.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/share/ScanView.py b/interpreter/llvm-project/clang/tools/scan-view/share/ScanView.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/share/ScanView.py
rename to interpreter/llvm-project/clang/tools/scan-view/share/ScanView.py
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/share/bugcatcher.ico b/interpreter/llvm-project/clang/tools/scan-view/share/bugcatcher.ico
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/share/bugcatcher.ico
rename to interpreter/llvm-project/clang/tools/scan-view/share/bugcatcher.ico
diff --git a/interpreter/llvm/src/tools/clang/tools/scan-view/share/startfile.py b/interpreter/llvm-project/clang/tools/scan-view/share/startfile.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/tools/scan-view/share/startfile.py
rename to interpreter/llvm-project/clang/tools/scan-view/share/startfile.py
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/ABITestGen.py b/interpreter/llvm-project/clang/utils/ABITest/ABITestGen.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/ABITestGen.py
rename to interpreter/llvm-project/clang/utils/ABITest/ABITestGen.py
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/Enumeration.py b/interpreter/llvm-project/clang/utils/ABITest/Enumeration.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/Enumeration.py
rename to interpreter/llvm-project/clang/utils/ABITest/Enumeration.py
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/Makefile.test.common b/interpreter/llvm-project/clang/utils/ABITest/Makefile.test.common
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/Makefile.test.common
rename to interpreter/llvm-project/clang/utils/ABITest/Makefile.test.common
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/TypeGen.py b/interpreter/llvm-project/clang/utils/ABITest/TypeGen.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/TypeGen.py
rename to interpreter/llvm-project/clang/utils/ABITest/TypeGen.py
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/build-and-summarize-all.sh b/interpreter/llvm-project/clang/utils/ABITest/build-and-summarize-all.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/build-and-summarize-all.sh
rename to interpreter/llvm-project/clang/utils/ABITest/build-and-summarize-all.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/build-and-summarize.sh b/interpreter/llvm-project/clang/utils/ABITest/build-and-summarize.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/build-and-summarize.sh
rename to interpreter/llvm-project/clang/utils/ABITest/build-and-summarize.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/build.sh b/interpreter/llvm-project/clang/utils/ABITest/build.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/build.sh
rename to interpreter/llvm-project/clang/utils/ABITest/build.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/layout/Makefile b/interpreter/llvm-project/clang/utils/ABITest/layout/Makefile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/layout/Makefile
rename to interpreter/llvm-project/clang/utils/ABITest/layout/Makefile
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/return-types-32/Makefile b/interpreter/llvm-project/clang/utils/ABITest/return-types-32/Makefile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/return-types-32/Makefile
rename to interpreter/llvm-project/clang/utils/ABITest/return-types-32/Makefile
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/return-types-64/Makefile b/interpreter/llvm-project/clang/utils/ABITest/return-types-64/Makefile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/return-types-64/Makefile
rename to interpreter/llvm-project/clang/utils/ABITest/return-types-64/Makefile
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/single-args-32/Makefile b/interpreter/llvm-project/clang/utils/ABITest/single-args-32/Makefile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/single-args-32/Makefile
rename to interpreter/llvm-project/clang/utils/ABITest/single-args-32/Makefile
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/single-args-64/Makefile b/interpreter/llvm-project/clang/utils/ABITest/single-args-64/Makefile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/single-args-64/Makefile
rename to interpreter/llvm-project/clang/utils/ABITest/single-args-64/Makefile
diff --git a/interpreter/llvm/src/tools/clang/utils/ABITest/summarize.sh b/interpreter/llvm-project/clang/utils/ABITest/summarize.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ABITest/summarize.sh
rename to interpreter/llvm-project/clang/utils/ABITest/summarize.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/CIndex/completion_logger_server.py b/interpreter/llvm-project/clang/utils/CIndex/completion_logger_server.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/CIndex/completion_logger_server.py
rename to interpreter/llvm-project/clang/utils/CIndex/completion_logger_server.py
diff --git a/interpreter/llvm/src/tools/clang/utils/CaptureCmd b/interpreter/llvm-project/clang/utils/CaptureCmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/CaptureCmd
rename to interpreter/llvm-project/clang/utils/CaptureCmd
diff --git a/interpreter/llvm/src/tools/clang/utils/ClangDataFormat.py b/interpreter/llvm-project/clang/utils/ClangDataFormat.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ClangDataFormat.py
rename to interpreter/llvm-project/clang/utils/ClangDataFormat.py
diff --git a/interpreter/llvm/src/tools/clang/utils/ClangVisualizers/CMakeLists.txt b/interpreter/llvm-project/clang/utils/ClangVisualizers/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/ClangVisualizers/CMakeLists.txt
rename to interpreter/llvm-project/clang/utils/ClangVisualizers/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/ClangVisualizers/clang.natvis b/interpreter/llvm-project/clang/utils/ClangVisualizers/clang.natvis
similarity index 98%
rename from interpreter/llvm/src/tools/clang/utils/ClangVisualizers/clang.natvis
rename to interpreter/llvm-project/clang/utils/ClangVisualizers/clang.natvis
index 2ef1c672a3fc6..36dea11b0118f 100644
--- a/interpreter/llvm/src/tools/clang/utils/ClangVisualizers/clang.natvis
+++ b/interpreter/llvm-project/clang/utils/ClangVisualizers/clang.natvis
@@ -1,1043 +1,1043 @@
-
-
-
-
-  
-    
-    LocInfoType
-    {(clang::Type::TypeClass)TypeBits.TC, en}Type
-    
-    {*(clang::BuiltinType *)this}
-    {*(clang::PointerType *)this}
-    {*(clang::LValueReferenceType *)this}
-    {*(clang::RValueReferenceType *)this}
-    {(clang::ConstantArrayType *)this,na}
-    {(clang::ConstantArrayType *)this,view(left)na}
-    {(clang::ConstantArrayType *)this,view(right)na}
-    {(clang::IncompleteArrayType *)this,na}
-    {(clang::IncompleteArrayType *)this,view(left)na}
-    {(clang::IncompleteArrayType *)this,view(right)na}
-    {(clang::TypedefType *)this,na}
-    {(clang::TypedefType *)this,view(cpp)na}
-    {*(clang::AttributedType *)this}
-    {(clang::DecayedType *)this,na}
-    {(clang::DecayedType *)this,view(left)na}
-    {(clang::DecayedType *)this,view(right)na}
-    {*(clang::TemplateTypeParmType *)this}
-    {*(clang::TemplateTypeParmType *)this,view(cpp)}
-    {*(clang::SubstTemplateTypeParmType *)this}
-    {*(clang::RecordType *)this}
-    {*(clang::RecordType *)this,view(cpp)}
-    {(clang::FunctionProtoType *)this,na}
-    {(clang::FunctionProtoType *)this,view(left)na}
-    {(clang::FunctionProtoType *)this,view(right)na}
-    {*(clang::TemplateSpecializationType *)this}
-    {*(clang::DeducedTemplateSpecializationType *)this}
-    {*(clang::DeducedTemplateSpecializationType *)this,view(cpp)}
-    {*(clang::InjectedClassNameType *)this}
-    {*(clang::DependentNameType *)this}
-    {*(clang::PackExpansionType *)this}
-    {(clang::LocInfoType *)this,na}
-    {(clang::LocInfoType *)this,view(cpp)na}
-    {this,view(poly)na}
-    {*this,view(cpp)}
-    
-    No visualizer yet for {(clang::Type::TypeClass)TypeBits.TC,en}Type 
-    Dependent{" ",sb}
-    
-    InstantiationDependent{" ",sb}
-    
-    VariablyModified{" ",sb}
-    
-    ContainsUnexpandedParameterPack{" ",sb}
-    
-    CachedLinkage: {(clang::Linkage)TypeBits.CachedLinkage,en} CachedLocalOrUnnamed
-    CachedLinkage: {(clang::Linkage)TypeBits.CachedLinkage,en}{" ",sb}
-    
-    FromAST
-    
-    
-      No TypeBits set beyond TypeClass
-    
-    
-{*this, view(Dependent)}{*this, view(InstantiationDependent)}{*this, view(VariablyModified)}
-{*this, view(ContainsUnexpandedParameterPack)}{*this, view(Cache)}{*this, view(FromAST)}
-    {*this,view(cmn)}  {{{*this,view(poly)}}}
-    
-      (clang::Type::TypeClass)TypeBits.TC
-      this,view(flags)na
-      CanonicalType
-      *(clang::BuiltinType *)this
-      *(clang::PointerType *)this
-      *(clang::LValueReferenceType *)this
-      *(clang::RValueReferenceType *)this
-      (clang::ConstantArrayType *)this
-      (clang::IncompleteArrayType *)this
-      *(clang::AttributedType *)this
-      (clang::DecayedType *)this
-      (clang::TemplateTypeParmType *)this
-      (clang::SubstTemplateTypeParmType *)this
-      (clang::RecordType *)this
-      (clang::FunctionProtoType *)this
-      (clang::TemplateSpecializationType *)this
-      (clang::DeducedTemplateSpecializationType *)this
-      (clang::InjectedClassNameType *)this
-      (clang::DependentNameType *)this
-      (clang::PackExpansionType *)this
-      (clang::LocInfoType *)this
-    
-  
-  
-    
-      ElementType
-    
-  
-  
-    {ElementType,view(cpp)}
-    [{Size}]
-    {ElementType,view(cpp)}[{Size}]
-    
-      Size
-      (clang::ArrayType *)this
-    
-  
-  
-    {ElementType,view(cpp)}
-    []
-    {ElementType,view(cpp)}[]
-    
-      (clang::ArrayType *)this
-    
-  
-  
-    {Decl,view(name)nd}
-    {Decl}
-    
-      Decl
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    {PointeeType, view(cpp)} *
-    
-      PointeeType
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-  
-    {((clang::ReferenceType *)this)->PointeeType,view(cpp)} &
-    
-      *(clang::Type *)this, view(cmn)
-      PointeeType
-    
-  
-  
-    {((clang::ReferenceType *)this)->PointeeType,view(cpp)} &&
-    
-      *(clang::Type *)this, view(cmn)
-      PointeeType
-    
-  
-  
-    {ModifiedType} Attribute={(clang::AttributedType::Kind)AttributedTypeBits.AttrKind}
-  
-  
-  
-  
-    {(clang::Decl::Kind)DeclContextBits.DeclKind,en}Decl
-    
-      (clang::Decl::Kind)DeclContextBits.DeclKind,en
-      
-        
-        
-          
-            FirstDecl
-            (clang::Decl *)(NextInContextAndBits.Value & ~3)
-            *this
-          
-        
-      
-    
-  
-  
-    Field {{{*(clang::DeclaratorDecl *)this,view(cpp)nd}}}
-  
-  
-    {*(clang::FunctionDecl *)this,nd}
-    Method {{{*this,view(cpp)}}}
-  
-  
-    Constructor {{{Name,view(cpp)}({*(clang::FunctionDecl *)this,view(parm0)nd})}}
-  
-  
-    Destructor {{~{Name,view(cpp)}()}}
-  
-  
-    typename
-    class
-    (not yet known if parameter pack) 
-    ...
-    
-    {(TypeSourceInfo *)(DefaultArgument.ValueOrInherited.Val.Value&~3LL),view(cpp)}
-    {{InheritedInitializer}}
-    = {this,view(DefaultArg)na}
-    
-    {*this,view(TorC)} {*this,view(MaybeEllipses)}{Name,view(cpp)} {this,view(Initializer)na} 
-  
-  
-    {*TemplatedDecl,view(cpp)}
-    template{TemplateParams,na} {*TemplatedDecl};
-    
-      TemplateParams,na
-      TemplatedDecl,na
-    
-  
-  
-  
-    {(clang::TypeSourceInfo *)(MaybeModedTInfo.Value & ~7LL),view(cpp)na}
-    {(clang::TypedefNameDecl::ModedTInfo *)(MaybeModedTInfo.Value & ~7LL),view(cpp)na}
-    {(TypeDecl *)this,view(cpp)nand}
-    typedef {this,view(type)na} {this,view(name)na};
-    
-      "Not yet calculated",sb
-      (bool)(MaybeModedTInfo.Value & 2)
-      (clang::TypeSourceInfo *)(MaybeModedTInfo.Value & ~7LL)
-      (clang::TypedefNameDecl::ModedTInfo *)(MaybeModedTInfo.Value & ~7LL)
-      (TypeDecl *)this,nd
-    
-  
-  
-    {(TypedefNameDecl *)this,view(name)nand}
-    using {(TypedefNameDecl *)this,view(name)nand} = {(TypedefNameDecl *)this,view(type)nand}
-  
-  
-    {Name}
-  
-  
-    Kind={(UncommonTemplateNameStorage::Kind)Kind,en}, Size={Size}
-    
-      (UncommonTemplateNameStorage::Kind)Kind
-      Size
-    
-  
-  
-    {Bits},
-    {this,view(cmn)na},{(OverloadedTemplateStorage*)this,na}
-    {this,view(cmn)na},{(AssumedTemplateStorage*)this,na}
-    {this,view(cmn)na},{(SubstTemplateTemplateParmStorage*)this,na}
-    {this,view(cmn)na},{(SubstTemplateTemplateParmPackStorage*)this,na}
-    {this,view(cmn)na}
-    
-      Bits
-      (OverloadedTemplateStorage*)this
-      (AssumedTemplateStorage*)this
-      (SubstTemplateTemplateParmStorage*)this
-      (SubstTemplateTemplateParmPackStorage*)this
-    
-  
-  
-  
-    
-    
-      {(clang::TemplateDecl *)(Val.Value & ~3LL),view(cpp)na}
-    
-    
-      {(clang::TemplateDecl *)(Val.Value & ~3LL),na}
-    
-    
-      {(clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL),view(cpp)na}
-    
-    
-      {(clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL),na}
-    
-    
-      {(clang::QualifiedTemplateName *)(Val.Value & ~3LL),view(cpp)na}
-    
-    
-      {(clang::QualifiedTemplateName *)(Val.Value & ~3LL),na}
-    
-    
-      {(clang::DependentTemplateName *)(Val.Value & ~3LL),view(cpp)na}
-    
-    
-      {(clang::DependentTemplateName *)(Val.Value & ~3LL),na}
-    
-    
-      "TemplateDecl",s8b
-      
-        (clang::TemplateDecl *)(Val.Value & ~3LL)
-      
-      "UncommonTemplateNameStorage",s8b
-      
-        (clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL)
-      
-      "QualifiedTemplateName",s8b
-      
-        (clang::QualifiedTemplateName *)(Val.Value & ~3LL)
-      
-      "DependentTemplateName",s8b
-      
-        (clang::DependentTemplateName *)(Val.Value & ~3LL)
-      
-      Val
-
-    
-  
-  
-    {Storage,view(cpp)na}
-    {Storage,na}
-    
-      Storage
-    
-  
-  
-    {Name,view(cpp)}
-    {Name}
-  
-  
-    implicit{" ",sb}
-    
-    {*this,view(implicit)nd}
-    {*this,view(modifiers)}{Name,view(cpp)}
-    {*this,view(modifiers)nd}struct {Name,view(cpp)}
-    {*this,view(modifiers)nd}interface {Name,view(cpp)}
-    {*this,view(modifiers)nd}union {Name,view(cpp)}
-    {*this,view(modifiers)nd}class {Name,view(cpp)}
-    {*this,view(modifiers)nd}enum {Name,view(cpp)}
-    
-      (clang::DeclContext *)this
-    
-  
-  
-    {decl,view(cpp)na}
-    {*decl}
-    
-      *(clang::Type *)this, view(cmn)
-      decl
-    
-  
-  
-    {(clang::TagType *)this,view(cpp)na}
-    {(clang::TagType *)this,na}
-    
-      *(clang::TagType *)this
-    
-  
-  
-    {{{*Replaced,view(cpp)} <= {CanonicalType,view(cpp)}}}
-    
-      *(clang::Type *)this, view(cmn)
-      *Replaced
-    
-  
-  
-  
-    
-    {ResultType,view(cpp)}
-    
-    {*(clang::QualType *)(this+1),view(cpp)}{*this,view(parm1)}
-    
-    , {*((clang::QualType *)(this+1)+1),view(cpp)}{*this,view(parm2)}
-    
-    , {*((clang::QualType *)(this+1)+2),view(cpp)}{*this,view(parm3)}
-    
-    , {*((clang::QualType *)(this+1)+3),view(cpp)}{*this,view(parm4)}
-    
-    , {*((clang::QualType *)(this+1)+4),view(cpp)}{*this,view(parm5)}
-    
-    , /* expand for more params */
-    ({*this,view(parm0)}) -> {ResultType,view(cpp)}
-    ({*this,view(parm0)})
-    {this,view(left)na}{this,view(right)na}
-    
-      ResultType
-      
-        {*this,view(parm0)}
-        
-          
-            FunctionTypeBits.NumParams
-            (clang::QualType *)(this+1)
-          
-        
-      
-      *(clang::Type *)this, view(cmn)
-    
-  
-
-  
-    {OriginalTy} adjusted to {AdjustedTy}
-    
-      OriginalTy
-      AdjustedTy
-    
-  
-  
-    {OriginalTy,view(left)}
-    {OriginalTy,view(right)}
-    {OriginalTy}
-    
-      (clang::AdjustedType *)this
-    
-  
-  
-    {TTPDecl->Name,view(cpp)}
-    Non-canonical: {*TTPDecl}
-    Canonical: {CanTTPTInfo}
-    
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    {Decl,view(cpp)}
-    
-      Decl
-      InjectedType
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    {NNS}{Name,view(cpp)na}
-    
-      NNS
-      Name
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    
-    {(IdentifierInfo*)Specifier,view(cpp)na}::
-    {(NamedDecl*)Specifier,view(cpp)na}::
-    {(Type*)Specifier,view(cpp)na}::
-    
-      (NestedNameSpecifier::StoredSpecifierKind)((Prefix.Value>>1)&3)
-    
-  
-  
-    {Pattern}
-    
-      Pattern
-      NumExpansions
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    
-    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(poly)}{*this,view(fastQuals)}
-    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(cpp)}{*this,view(fastQuals)}
-    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(left)}{*this,view(fastQuals)}
-    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(right)}{*this,view(fastQuals)}
-    
-    
-    {" ",sb}const
-    {" ",sb}restrict
-    {" ",sb}const restrict
-    {" ",sb}volatile
-    {" ",sb}const volatile
-    {" ",sb}volatile restrict
-    {" ",sb}const volatile restrict
-    Cannot visualize non-fast qualifiers
-    Null
-    {((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,na}{*this,view(fastQuals)}
-    
-      *this,view(fastQuals)
-      ((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType
-    
-  
-  
-    {DeclInfo,view(cpp)na}
-    {DeclInfo,na}
-    
-      DeclInfo
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    {Ty,view(cpp)}
-    {Ty}
-    
-      Ty
-    
-  
-  
-    {(QualType *)&Ty,na}
-    
-      (QualType *)&Ty
-      Data
-    
-  
-  
-    Not building anything
-    Building a {LastTy}
-  
-  
-    {Argument,view(cpp)}
-    {Argument}
-  
-  
-    {*(clang::QualType *)&TypeOrValue.V,view(cpp)}
-    {(clang::TemplateArgument::ArgKind)TypeOrValue.Kind,en} template argument: {*(clang::QualType *)&TypeOrValue.V}
-    
-    {Args.Args[0]}{*this,view(arg1)}
-    
-    , {Args.Args[1]}{*this,view(arg2)}
-    
-    , {Args.Args[2]}, ...
-    
-    {Args.Args[0],view(cpp)}{*this,view(arg1cpp)}
-    
-    , {Args.Args[1],view(cpp)}{*this,view(arg2cpp)}
-    
-    , {Args.Args[2],view(cpp)}, ...
-    {*this,view(arg0cpp)}
-    {*this,view(arg0)}
-    {(clang::Expr *)TypeOrValue.V,view(cpp)na}
-    {(clang::TemplateArgument::ArgKind)TypeOrValue.Kind,en}
-    
-      *(clang::QualType *)&TypeOrValue.V
-      (clang::Expr *)TypeOrValue.V
-      
-        Args.NumArgs
-        Args.Args
-      
-      
-    
-  
-  
-    
-    {((TemplateArgumentLoc*)Arguments.BeginX)[0],view(cpp)}{*this,view(elt1)}
-    
-    , {((TemplateArgumentLoc*)Arguments.BeginX)[1],view(cpp)}{*this,view(elt2)}
-    
-    , {((TemplateArgumentLoc*)Arguments.BeginX)[2],view(cpp)}{*this,view(elt3)}
-    
-    , {((TemplateArgumentLoc*)Arguments.BeginX)[3],view(cpp)}{*this,view(elt4)}
-    
-    , ...
-    empty
-    <{*this,view(elt0)}>
-    Uninitialized
-  
-  
-    
-    {Arguments[0],view(cpp)}{*this,view(arg1)}
-    
-    , {Arguments[1],view(cpp)}{*this,view(arg2)}
-    
-    , {Arguments[1],view(cpp)}, ...
-    <{*this,view(arg0)}>
-    
-      NumArguments
-      
-        NumArguments
-        Arguments
-      
-    
-  
-  
-    
-    {Data[0],view(cpp)}{*this,view(arg1)}
-    
-    , {Data[1],view(cpp)}{*this,view(arg2)}
-    
-    , {Data[2],view(cpp)}, ...
-    <{*this,view(arg0)}>
-    
-      Length
-      
-        
-          
-            Length
-            Data
-          
-        
-      
-    
-  
-  
-    
-    {((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[0],view(cpp)}{*this,view(level1)}
-    
-    ::{((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[1],view(cpp)}{*this,view(level2)}
-    
-    ::{((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[2],view(cpp)}, ...
-    {*this,view(level0)}
-    
-      TemplateArgumentLists
-    
-  
-  
-    {(clang::QualType *)Arg,view(cpp)na}
-    Type template argument: {*(clang::QualType *)Arg}
-    Non-type template argument: {*(clang::Expr *)Arg}
-    Template template argument: {*(clang::TemplateName *)Arg
-    
-      Kind,en
-      (clang::QualType *)Arg
-      (clang::Expr *)Arg
-      (clang::TemplateName *)Arg
-    
-  
-  
-  
-    void
-    bool
-    char
-    unsigned char
-    wchar_t
-    char16_t
-    char32_t
-    unsigned short
-    unsigned int
-    unsigned long
-    unsigned long long
-    __uint128_t
-    char
-    signed char
-    wchar_t
-    short
-    int
-    long
-    long long
-    __int128_t
-    __fp16
-    float
-    double
-    long double
-    nullptr_t
-    {(clang::BuiltinType::Kind)BuiltinTypeBits.Kind, en}
-    
-      (clang::BuiltinType::Kind)BuiltinTypeBits.Kind
-    
-  
-
-  
-    
-    {((clang::TemplateArgument *)(this+1))[0],view(cpp)}{*this,view(arg1)}
-    
-    , {((clang::TemplateArgument *)(this+1))[1],view(cpp)}{*this,view(arg2)}
-    
-    , {((clang::TemplateArgument *)(this+1))[2],view(cpp)}{*this,view(arg3)}
-    
-      {*((clang::TemplateDecl *)(Template.Storage.Val.Value))->TemplatedDecl,view(cpp)}<{*this,view(arg0)}>
-    
-    Can't visualize this TemplateSpecializationType
-    
-      Template.Storage
-      
-        TemplateSpecializationTypeBits.NumArgs
-        (clang::TemplateArgument *)(this+1)
-      
-      *(clang::Type *)this, view(cmn)
-    
-  
-  
-    
-      (CanonicalType.Value.Value != this) || TypeBits.Dependent
-      *(clang::Type *)this,view(cmn)
-    
-  
-  
-    {CanonicalType,view(cpp)}
-    {Template,view(cpp)}
-    {Template}
-    
-      Template
-      CanonicalType,view(cpp)
-      (clang::DeducedType *)this
-      Template
-    
-  
-  
-    {*(CXXRecordDecl *)this,nd}{*TemplateArgs}
-    
-      (CXXRecordDecl *)this,nd
-      TemplateArgs
-    
-  
-  
-    {((llvm::StringMapEntry<clang::IdentifierInfo *>*)Entry)+1,sb}
-    
-      ((llvm::StringMapEntry<clang::IdentifierInfo *>*)Entry)+1,s
-      (clang::tok::TokenKind)TokenID
-    
-  
-  
-    
-    Empty
-    {*(clang::IdentifierInfo *)(Ptr & ~PtrMask)}
-    {{Identifier ({*(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
-    {{ObjC Zero Arg Selector (*{(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
-    {{ObjC One Arg Selector (*{(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
-    {(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),view(cpp)na}
-    C++ Constructor {{{(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),view(cpp)na}}}
-    C++ Destructor {{*(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask)}}
-    C++ Conversion function {{*(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask)}}
-    C++ Operator {{*(clang::detail::CXXOperatorIdName *)(Ptr & ~PtrMask)}}    
-    {*(clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask),view(cpp)}
-    {{Extra ({*(clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask)})}}
-    
-      StoredNameKind(Ptr & PtrMask),en
-      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
-      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
-      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
-      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
-      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
-      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
-      *(clang::detail::CXXOperatorIdName *)(Ptr & ~PtrMask),na      
-      (clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask),na
-    
-  
-  
-    
-      {(CXXDeductionGuideNameExtra *)this,view(cpp)nand}
-    
-    
-      {(CXXDeductionGuideNameExtra *)this,nand}
-    
-    C++ Literal operator
-    C++ Using directive  
-    {(clang::detail::DeclarationNameExtra::ExtraKind)ExtraKindOrNumArgs,en}{"  ",sb}{*this,view(cpp)}
-    
-      (CXXDeductionGuideNameExtra *)this
-      ExtraKindOrNumArgs
-    
-  
-  
-    {Template->TemplatedDecl,view(cpp)}
-    C++ Deduction guide for {Template->TemplatedDecl,view(cpp)na}
-  
-  
-    {Type,view(cpp)}
-    {Type}
-  
-  
-    {Name}
-  
-  
-    
-    {(ParsedTemplateArgument *)(this+1),view(cpp)na}{this,view(arg1)na}
-    
-    , {((ParsedTemplateArgument *)(this+1))+1,view(cpp)na}{this,view(arg2)na}
-    
-    , ...
-    {Name,na}<{this,view(arg0)na}>
-    
-      Name
-      
-        {this,view(arg0)na}
-        
-          
-            NumArgs
-            (ParsedTemplateArgument *)(this+1)
-          
-        
-      
-      Operator
-    
-  
-  
-    {{annot_template_id ({(clang::TemplateIdAnnotation *)(PtrData),na})}}
-    {{Identifier ({(clang::IdentifierInfo *)(PtrData),na})}}
-    {(clang::tok::TokenKind)Kind,en}
-  
-  
-    {BufferPtr,nasb}
-  
-  
-    {TheLexer._Mypair._Myval2,na}
-    Expanding Macro: {TheTokenLexer._Mypair._Myval2,na}
-    
-  
-  
-    
-      [{(Token *)(CachedTokens.BeginX) + CachedLexPos,na}] {IncludeMacroStack._Mypair._Myval2._Mylast - 1,na}
-    
-     {IncludeMacroStack._Mypair._Myval2._Mylast - 1,na}
-    {CurLexer._Mypair._Myval2,na}
-    Expanding Macro: {CurTokenLexer._Mypair._Myval2,na}
-    
-    
-      {this,view(cached)}
-    
-    CLK_LexAfterModuleImport
-  
-  
-    [{Tok}] {PP,na}
-  
-  
-    this
-    *this
-    {Id}
-    &{Id}
-    No visualizer for {Kind}
-  
-  
-    
-    =,
-    &,
-    
-    {(LambdaCapture *)(Captures.BeginX),na}{this,view(capture1)na}
-    
-    ,{(LambdaCapture *)(Captures.BeginX)+1,na}{this,view(capture2)na}
-    
-    ,{(LambdaCapture *)(Captures.BeginX)+2,na}{this,view(capture3)na}
-    
-    ,...
-    [{this,view(default)na}{this,view(capture0)na}]
-  
-  
-    
-      , [{TypeRep}]
-    
-    
-      , [{ExprRep}]
-    
-    
-      , [{DeclRep}]
-    
-    
-    [{(clang::DeclSpec::SCS)StorageClassSpec,en}], [{(clang::TypeSpecifierType)TypeSpecType,en}]{this,view(extra)na}
-    
-      (clang::DeclSpec::SCS)StorageClassSpec
-      (clang::TypeSpecifierType)TypeSpecType
-      
-        TypeRep
-      
-      
-        ExprRep
-      
-      
-        DeclRep
-      
-
-    
-  
-  
-    {Name,s}
-  
-  
-    {Name,s}
-  
-  
-    {Name,s}
-  
-  
-    
-      (clang::StorageClass)SClass
-      (clang::ThreadStorageClassSpecifier)TSCSpec
-      (clang::VarDecl::InitializationStyle)InitStyle
-    
-  
-  
-    {DeclType,view(left)} {Name,view(cpp)}{DeclType,view(right)}
-    
-      Name
-      DeclType
-    
-  
-  
-    {(DeclaratorDecl*)this,nand}
-    
-      (DeclaratorDecl*)this,nd
-      Init
-      VarDeclBits
-    
-  
-  
-    {*(VarDecl*)this,nd}
-    
-      ParmVarDeclBits
-      *(VarDecl*)this,nd
-    
-  
-  
-    {"explicit ",sb}
-    
-    explicit({ExplicitSpec,view(ptr)na})
-    {ExplicitSpec,view(int)en}
-    {ExplicitSpec,view(int)en} : {ExplicitSpec,view(ptr)na}
-  
-  
-    {ExplicitSpec,view(cpp)}{Name,view(cpp)nd}({(FunctionDecl*)this,view(parm0)nand}) -> {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
-    
-      ExplicitSpec
-      (bool)FunctionDeclBits.IsCopyDeductionCandidate
-      (FunctionDecl*)this,nd
-    
-  
-  
-    {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
-    
-    {ParamInfo[0],na}{*this,view(parm1)nd}
-    
-    , {ParamInfo[1],na}{*this,view(parm2)nd}
-    
-    , {ParamInfo[2],na}{*this,view(parm3)nd}
-    
-    , {ParamInfo[3],na}{*this,view(parm4)nd}
-    
-    , {ParamInfo[4],na}{*this,view(parm5)nd}
-    
-    , /* expand for more params */
-    
-      auto {Name,view(cpp)nd}({*this,view(parm0)nd}) -> {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
-    
-    {this,view(retType)nand} {Name,view(cpp)nd}({*this,view(parm0)nd})
-    
-      (clang::DeclaratorDecl *)this,nd
-      ((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType
-      
-        {*this,view(parm0)nd}
-        
-          
-            ((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->FunctionTypeBits.NumParams
-            ParamInfo
-          
-        
-      
-      TemplateOrSpecialization
-    
-  
-  
-    {*($T1*)&Ptr}
-    
-      ($T1*)&Ptr
-    
-  
-  
-    {($T1 *)Ptr}
-    
-      ($T1 *)Ptr
-    
-  
-  
-    
-    {*((NamedDecl **)(this+1))[0],view(cpp)}{*this,view(parm1)}
-    
-    , {*((NamedDecl **)(this+1))[1],view(cpp)}{*this,view(parm2)}
-    
-    , {*((NamedDecl **)(this+1))[2],view(cpp)}{*this,view(parm3)}
-    
-    , {*((NamedDecl **)(this+1))[3],view(cpp)}{*this,view(parm4)}
-    
-    , {*((NamedDecl **)(this+1))[4],view(cpp)}{*this,view(parm5)}
-    
-    , /* Expand for more params */
-    <{*this,view(parm0)}>
-    
-      
-        NumParams
-      (NamedDecl **)(this+1)
-      
-    
-  
-  
-    {(clang::Stmt::StmtClass)StmtBits.sClass,en}
-    
-      (clang::Stmt::StmtClass)StmtBits.sClass,en
-    
-  
-  
-    Expression of class {(clang::Stmt::StmtClass)StmtBits.sClass,en} and type {TR,view(cpp)}
-  
-  
-    public
-    protected
-    private
-    
-    {*(clang::NamedDecl *)(Ptr&~Mask)}
-    {*this,view(access)} {*this,view(decl)}
-    
-      (clang::AccessSpecifier)(Ptr&Mask),en
-      *(clang::NamedDecl *)(Ptr&~Mask)
-    
-  
-  
-    [IK_Identifier] {*Identifier}
-    [IK_OperatorFunctionId] {OperatorFunctionId}
-    [IK_ConversionFunctionId] {ConversionFunctionId}
-    [IK_ConstructorName] {ConstructorName}
-    [IK_DestructorName] {DestructorName}
-    [IK_DeductionGuideName] {TemplateName}
-    [IK_TemplateId] {TemplateId}
-    [IK_ConstructorTemplateId] {TemplateId}
-    Kind
-    
-      Identifier
-      OperatorFunctionId
-      ConversionFunctionId
-      ConstructorName
-      DestructorName
-      TemplateName
-      TemplateId
-      TemplateId
-    
-  
-  
-    NumDecls={NumDecls}
-    
-      
-        NumDecls
-        (Decl **)(this+1)
-      
-    
-  
-  
-    {*D}
-    {*(DeclGroup *)((uintptr_t)D&~1)}
-    
-      D
-      (DeclGroup *)((uintptr_t)D&~1)
-    
-  
-  
-    {DS} {Name}
-  
-  
-    {Decls}
-    
-      Decls
-    
-  
-  
-    {Ambiguity,en}: {Decls}
-    {ResultKind,en}: {Decls}
-  
-  
-    Invalid
-    Unset
-    {Val}
-  
-  
-    Invalid
-    Unset
-    {($T1)(PtrWithInvalid&~1)}
-    
-      (bool)(PtrWithInvalid&1)
-      ($T1)(PtrWithInvalid&~1)
-    
-  
-
+
+
+
+
+  
+    
+    LocInfoType
+    {(clang::Type::TypeClass)TypeBits.TC, en}Type
+    
+    {*(clang::BuiltinType *)this}
+    {*(clang::PointerType *)this}
+    {*(clang::LValueReferenceType *)this}
+    {*(clang::RValueReferenceType *)this}
+    {(clang::ConstantArrayType *)this,na}
+    {(clang::ConstantArrayType *)this,view(left)na}
+    {(clang::ConstantArrayType *)this,view(right)na}
+    {(clang::IncompleteArrayType *)this,na}
+    {(clang::IncompleteArrayType *)this,view(left)na}
+    {(clang::IncompleteArrayType *)this,view(right)na}
+    {(clang::TypedefType *)this,na}
+    {(clang::TypedefType *)this,view(cpp)na}
+    {*(clang::AttributedType *)this}
+    {(clang::DecayedType *)this,na}
+    {(clang::DecayedType *)this,view(left)na}
+    {(clang::DecayedType *)this,view(right)na}
+    {*(clang::TemplateTypeParmType *)this}
+    {*(clang::TemplateTypeParmType *)this,view(cpp)}
+    {*(clang::SubstTemplateTypeParmType *)this}
+    {*(clang::RecordType *)this}
+    {*(clang::RecordType *)this,view(cpp)}
+    {(clang::FunctionProtoType *)this,na}
+    {(clang::FunctionProtoType *)this,view(left)na}
+    {(clang::FunctionProtoType *)this,view(right)na}
+    {*(clang::TemplateSpecializationType *)this}
+    {*(clang::DeducedTemplateSpecializationType *)this}
+    {*(clang::DeducedTemplateSpecializationType *)this,view(cpp)}
+    {*(clang::InjectedClassNameType *)this}
+    {*(clang::DependentNameType *)this}
+    {*(clang::PackExpansionType *)this}
+    {(clang::LocInfoType *)this,na}
+    {(clang::LocInfoType *)this,view(cpp)na}
+    {this,view(poly)na}
+    {*this,view(cpp)}
+    
+    No visualizer yet for {(clang::Type::TypeClass)TypeBits.TC,en}Type 
+    Dependent{" ",sb}
+    
+    InstantiationDependent{" ",sb}
+    
+    VariablyModified{" ",sb}
+    
+    ContainsUnexpandedParameterPack{" ",sb}
+    
+    CachedLinkage: {(clang::Linkage)TypeBits.CachedLinkage,en} CachedLocalOrUnnamed
+    CachedLinkage: {(clang::Linkage)TypeBits.CachedLinkage,en}{" ",sb}
+    
+    FromAST
+    
+    
+      No TypeBits set beyond TypeClass
+    
+    
+{*this, view(Dependent)}{*this, view(InstantiationDependent)}{*this, view(VariablyModified)}
+{*this, view(ContainsUnexpandedParameterPack)}{*this, view(Cache)}{*this, view(FromAST)}
+    {*this,view(cmn)}  {{{*this,view(poly)}}}
+    
+      (clang::Type::TypeClass)TypeBits.TC
+      this,view(flags)na
+      CanonicalType
+      *(clang::BuiltinType *)this
+      *(clang::PointerType *)this
+      *(clang::LValueReferenceType *)this
+      *(clang::RValueReferenceType *)this
+      (clang::ConstantArrayType *)this
+      (clang::IncompleteArrayType *)this
+      *(clang::AttributedType *)this
+      (clang::DecayedType *)this
+      (clang::TemplateTypeParmType *)this
+      (clang::SubstTemplateTypeParmType *)this
+      (clang::RecordType *)this
+      (clang::FunctionProtoType *)this
+      (clang::TemplateSpecializationType *)this
+      (clang::DeducedTemplateSpecializationType *)this
+      (clang::InjectedClassNameType *)this
+      (clang::DependentNameType *)this
+      (clang::PackExpansionType *)this
+      (clang::LocInfoType *)this
+    
+  
+  
+    
+      ElementType
+    
+  
+  
+    {ElementType,view(cpp)}
+    [{Size}]
+    {ElementType,view(cpp)}[{Size}]
+    
+      Size
+      (clang::ArrayType *)this
+    
+  
+  
+    {ElementType,view(cpp)}
+    []
+    {ElementType,view(cpp)}[]
+    
+      (clang::ArrayType *)this
+    
+  
+  
+    {Decl,view(name)nd}
+    {Decl}
+    
+      Decl
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    {PointeeType, view(cpp)} *
+    
+      PointeeType
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+  
+    {((clang::ReferenceType *)this)->PointeeType,view(cpp)} &
+    
+      *(clang::Type *)this, view(cmn)
+      PointeeType
+    
+  
+  
+    {((clang::ReferenceType *)this)->PointeeType,view(cpp)} &&
+    
+      *(clang::Type *)this, view(cmn)
+      PointeeType
+    
+  
+  
+    {ModifiedType} Attribute={(clang::AttributedType::Kind)AttributedTypeBits.AttrKind}
+  
+  
+  
+  
+    {(clang::Decl::Kind)DeclContextBits.DeclKind,en}Decl
+    
+      (clang::Decl::Kind)DeclContextBits.DeclKind,en
+      
+        
+        
+          
+            FirstDecl
+            (clang::Decl *)(NextInContextAndBits.Value & ~3)
+            *this
+          
+        
+      
+    
+  
+  
+    Field {{{*(clang::DeclaratorDecl *)this,view(cpp)nd}}}
+  
+  
+    {*(clang::FunctionDecl *)this,nd}
+    Method {{{*this,view(cpp)}}}
+  
+  
+    Constructor {{{Name,view(cpp)}({*(clang::FunctionDecl *)this,view(parm0)nd})}}
+  
+  
+    Destructor {{~{Name,view(cpp)}()}}
+  
+  
+    typename
+    class
+    (not yet known if parameter pack) 
+    ...
+    
+    {(TypeSourceInfo *)(DefaultArgument.ValueOrInherited.Val.Value&~3LL),view(cpp)}
+    {{InheritedInitializer}}
+    = {this,view(DefaultArg)na}
+    
+    {*this,view(TorC)} {*this,view(MaybeEllipses)}{Name,view(cpp)} {this,view(Initializer)na} 
+  
+  
+    {*TemplatedDecl,view(cpp)}
+    template{TemplateParams,na} {*TemplatedDecl};
+    
+      TemplateParams,na
+      TemplatedDecl,na
+    
+  
+  
+  
+    {(clang::TypeSourceInfo *)(MaybeModedTInfo.Value & ~7LL),view(cpp)na}
+    {(clang::TypedefNameDecl::ModedTInfo *)(MaybeModedTInfo.Value & ~7LL),view(cpp)na}
+    {(TypeDecl *)this,view(cpp)nand}
+    typedef {this,view(type)na} {this,view(name)na};
+    
+      "Not yet calculated",sb
+      (bool)(MaybeModedTInfo.Value & 2)
+      (clang::TypeSourceInfo *)(MaybeModedTInfo.Value & ~7LL)
+      (clang::TypedefNameDecl::ModedTInfo *)(MaybeModedTInfo.Value & ~7LL)
+      (TypeDecl *)this,nd
+    
+  
+  
+    {(TypedefNameDecl *)this,view(name)nand}
+    using {(TypedefNameDecl *)this,view(name)nand} = {(TypedefNameDecl *)this,view(type)nand}
+  
+  
+    {Name}
+  
+  
+    Kind={(UncommonTemplateNameStorage::Kind)Kind,en}, Size={Size}
+    
+      (UncommonTemplateNameStorage::Kind)Kind
+      Size
+    
+  
+  
+    {Bits},
+    {this,view(cmn)na},{(OverloadedTemplateStorage*)this,na}
+    {this,view(cmn)na},{(AssumedTemplateStorage*)this,na}
+    {this,view(cmn)na},{(SubstTemplateTemplateParmStorage*)this,na}
+    {this,view(cmn)na},{(SubstTemplateTemplateParmPackStorage*)this,na}
+    {this,view(cmn)na}
+    
+      Bits
+      (OverloadedTemplateStorage*)this
+      (AssumedTemplateStorage*)this
+      (SubstTemplateTemplateParmStorage*)this
+      (SubstTemplateTemplateParmPackStorage*)this
+    
+  
+  
+  
+    
+    
+      {(clang::TemplateDecl *)(Val.Value & ~3LL),view(cpp)na}
+    
+    
+      {(clang::TemplateDecl *)(Val.Value & ~3LL),na}
+    
+    
+      {(clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL),view(cpp)na}
+    
+    
+      {(clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL),na}
+    
+    
+      {(clang::QualifiedTemplateName *)(Val.Value & ~3LL),view(cpp)na}
+    
+    
+      {(clang::QualifiedTemplateName *)(Val.Value & ~3LL),na}
+    
+    
+      {(clang::DependentTemplateName *)(Val.Value & ~3LL),view(cpp)na}
+    
+    
+      {(clang::DependentTemplateName *)(Val.Value & ~3LL),na}
+    
+    
+      "TemplateDecl",s8b
+      
+        (clang::TemplateDecl *)(Val.Value & ~3LL)
+      
+      "UncommonTemplateNameStorage",s8b
+      
+        (clang::UncommonTemplateNameStorage *)(Val.Value & ~3LL)
+      
+      "QualifiedTemplateName",s8b
+      
+        (clang::QualifiedTemplateName *)(Val.Value & ~3LL)
+      
+      "DependentTemplateName",s8b
+      
+        (clang::DependentTemplateName *)(Val.Value & ~3LL)
+      
+      Val
+
+    
+  
+  
+    {Storage,view(cpp)na}
+    {Storage,na}
+    
+      Storage
+    
+  
+  
+    {Name,view(cpp)}
+    {Name}
+  
+  
+    implicit{" ",sb}
+    
+    {*this,view(implicit)nd}
+    {*this,view(modifiers)}{Name,view(cpp)}
+    {*this,view(modifiers)nd}struct {Name,view(cpp)}
+    {*this,view(modifiers)nd}interface {Name,view(cpp)}
+    {*this,view(modifiers)nd}union {Name,view(cpp)}
+    {*this,view(modifiers)nd}class {Name,view(cpp)}
+    {*this,view(modifiers)nd}enum {Name,view(cpp)}
+    
+      (clang::DeclContext *)this
+    
+  
+  
+    {decl,view(cpp)na}
+    {*decl}
+    
+      *(clang::Type *)this, view(cmn)
+      decl
+    
+  
+  
+    {(clang::TagType *)this,view(cpp)na}
+    {(clang::TagType *)this,na}
+    
+      *(clang::TagType *)this
+    
+  
+  
+    {{{*Replaced,view(cpp)} <= {CanonicalType,view(cpp)}}}
+    
+      *(clang::Type *)this, view(cmn)
+      *Replaced
+    
+  
+  
+  
+    
+    {ResultType,view(cpp)}
+    
+    {*(clang::QualType *)(this+1),view(cpp)}{*this,view(parm1)}
+    
+    , {*((clang::QualType *)(this+1)+1),view(cpp)}{*this,view(parm2)}
+    
+    , {*((clang::QualType *)(this+1)+2),view(cpp)}{*this,view(parm3)}
+    
+    , {*((clang::QualType *)(this+1)+3),view(cpp)}{*this,view(parm4)}
+    
+    , {*((clang::QualType *)(this+1)+4),view(cpp)}{*this,view(parm5)}
+    
+    , /* expand for more params */
+    ({*this,view(parm0)}) -> {ResultType,view(cpp)}
+    ({*this,view(parm0)})
+    {this,view(left)na}{this,view(right)na}
+    
+      ResultType
+      
+        {*this,view(parm0)}
+        
+          
+            FunctionTypeBits.NumParams
+            (clang::QualType *)(this+1)
+          
+        
+      
+      *(clang::Type *)this, view(cmn)
+    
+  
+
+  
+    {OriginalTy} adjusted to {AdjustedTy}
+    
+      OriginalTy
+      AdjustedTy
+    
+  
+  
+    {OriginalTy,view(left)}
+    {OriginalTy,view(right)}
+    {OriginalTy}
+    
+      (clang::AdjustedType *)this
+    
+  
+  
+    {TTPDecl->Name,view(cpp)}
+    Non-canonical: {*TTPDecl}
+    Canonical: {CanTTPTInfo}
+    
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    {Decl,view(cpp)}
+    
+      Decl
+      InjectedType
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    {NNS}{Name,view(cpp)na}
+    
+      NNS
+      Name
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    
+    {(IdentifierInfo*)Specifier,view(cpp)na}::
+    {(NamedDecl*)Specifier,view(cpp)na}::
+    {(Type*)Specifier,view(cpp)na}::
+    
+      (NestedNameSpecifier::StoredSpecifierKind)((Prefix.Value>>1)&3)
+    
+  
+  
+    {Pattern}
+    
+      Pattern
+      NumExpansions
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    
+    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(poly)}{*this,view(fastQuals)}
+    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(cpp)}{*this,view(fastQuals)}
+    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(left)}{*this,view(fastQuals)}
+    {*((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,view(right)}{*this,view(fastQuals)}
+    
+    
+    {" ",sb}const
+    {" ",sb}restrict
+    {" ",sb}const restrict
+    {" ",sb}volatile
+    {" ",sb}const volatile
+    {" ",sb}volatile restrict
+    {" ",sb}const volatile restrict
+    Cannot visualize non-fast qualifiers
+    Null
+    {((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType,na}{*this,view(fastQuals)}
+    
+      *this,view(fastQuals)
+      ((clang::ExtQualsTypeCommonBase *)(((uintptr_t)Value.Value) & ~(uintptr_t)((1 << 4) - 1)))->BaseType
+    
+  
+  
+    {DeclInfo,view(cpp)na}
+    {DeclInfo,na}
+    
+      DeclInfo
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    {Ty,view(cpp)}
+    {Ty}
+    
+      Ty
+    
+  
+  
+    {(QualType *)&Ty,na}
+    
+      (QualType *)&Ty
+      Data
+    
+  
+  
+    Not building anything
+    Building a {LastTy}
+  
+  
+    {Argument,view(cpp)}
+    {Argument}
+  
+  
+    {*(clang::QualType *)&TypeOrValue.V,view(cpp)}
+    {(clang::TemplateArgument::ArgKind)TypeOrValue.Kind,en} template argument: {*(clang::QualType *)&TypeOrValue.V}
+    
+    {Args.Args[0]}{*this,view(arg1)}
+    
+    , {Args.Args[1]}{*this,view(arg2)}
+    
+    , {Args.Args[2]}, ...
+    
+    {Args.Args[0],view(cpp)}{*this,view(arg1cpp)}
+    
+    , {Args.Args[1],view(cpp)}{*this,view(arg2cpp)}
+    
+    , {Args.Args[2],view(cpp)}, ...
+    {*this,view(arg0cpp)}
+    {*this,view(arg0)}
+    {(clang::Expr *)TypeOrValue.V,view(cpp)na}
+    {(clang::TemplateArgument::ArgKind)TypeOrValue.Kind,en}
+    
+      *(clang::QualType *)&TypeOrValue.V
+      (clang::Expr *)TypeOrValue.V
+      
+        Args.NumArgs
+        Args.Args
+      
+      
+    
+  
+  
+    
+    {((TemplateArgumentLoc*)Arguments.BeginX)[0],view(cpp)}{*this,view(elt1)}
+    
+    , {((TemplateArgumentLoc*)Arguments.BeginX)[1],view(cpp)}{*this,view(elt2)}
+    
+    , {((TemplateArgumentLoc*)Arguments.BeginX)[2],view(cpp)}{*this,view(elt3)}
+    
+    , {((TemplateArgumentLoc*)Arguments.BeginX)[3],view(cpp)}{*this,view(elt4)}
+    
+    , ...
+    empty
+    <{*this,view(elt0)}>
+    Uninitialized
+  
+  
+    
+    {Arguments[0],view(cpp)}{*this,view(arg1)}
+    
+    , {Arguments[1],view(cpp)}{*this,view(arg2)}
+    
+    , {Arguments[1],view(cpp)}, ...
+    <{*this,view(arg0)}>
+    
+      NumArguments
+      
+        NumArguments
+        Arguments
+      
+    
+  
+  
+    
+    {Data[0],view(cpp)}{*this,view(arg1)}
+    
+    , {Data[1],view(cpp)}{*this,view(arg2)}
+    
+    , {Data[2],view(cpp)}, ...
+    <{*this,view(arg0)}>
+    
+      Length
+      
+        
+          
+            Length
+            Data
+          
+        
+      
+    
+  
+  
+    
+    {((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[0],view(cpp)}{*this,view(level1)}
+    
+    ::{((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[1],view(cpp)}{*this,view(level2)}
+    
+    ::{((llvm::ArrayRef<clang::TemplateArgument> *)TemplateArgumentLists.BeginX)[2],view(cpp)}, ...
+    {*this,view(level0)}
+    
+      TemplateArgumentLists
+    
+  
+  
+    {(clang::QualType *)Arg,view(cpp)na}
+    Type template argument: {*(clang::QualType *)Arg}
+    Non-type template argument: {*(clang::Expr *)Arg}
+    Template template argument: {*(clang::TemplateName *)Arg
+    
+      Kind,en
+      (clang::QualType *)Arg
+      (clang::Expr *)Arg
+      (clang::TemplateName *)Arg
+    
+  
+  
+  
+    void
+    bool
+    char
+    unsigned char
+    wchar_t
+    char16_t
+    char32_t
+    unsigned short
+    unsigned int
+    unsigned long
+    unsigned long long
+    __uint128_t
+    char
+    signed char
+    wchar_t
+    short
+    int
+    long
+    long long
+    __int128_t
+    __fp16
+    float
+    double
+    long double
+    nullptr_t
+    {(clang::BuiltinType::Kind)BuiltinTypeBits.Kind, en}
+    
+      (clang::BuiltinType::Kind)BuiltinTypeBits.Kind
+    
+  
+
+  
+    
+    {((clang::TemplateArgument *)(this+1))[0],view(cpp)}{*this,view(arg1)}
+    
+    , {((clang::TemplateArgument *)(this+1))[1],view(cpp)}{*this,view(arg2)}
+    
+    , {((clang::TemplateArgument *)(this+1))[2],view(cpp)}{*this,view(arg3)}
+    
+      {*((clang::TemplateDecl *)(Template.Storage.Val.Value))->TemplatedDecl,view(cpp)}<{*this,view(arg0)}>
+    
+    Can't visualize this TemplateSpecializationType
+    
+      Template.Storage
+      
+        TemplateSpecializationTypeBits.NumArgs
+        (clang::TemplateArgument *)(this+1)
+      
+      *(clang::Type *)this, view(cmn)
+    
+  
+  
+    
+      (CanonicalType.Value.Value != this) || TypeBits.Dependent
+      *(clang::Type *)this,view(cmn)
+    
+  
+  
+    {CanonicalType,view(cpp)}
+    {Template,view(cpp)}
+    {Template}
+    
+      Template
+      CanonicalType,view(cpp)
+      (clang::DeducedType *)this
+      Template
+    
+  
+  
+    {*(CXXRecordDecl *)this,nd}{*TemplateArgs}
+    
+      (CXXRecordDecl *)this,nd
+      TemplateArgs
+    
+  
+  
+    {((llvm::StringMapEntry<clang::IdentifierInfo *>*)Entry)+1,sb}
+    
+      ((llvm::StringMapEntry<clang::IdentifierInfo *>*)Entry)+1,s
+      (clang::tok::TokenKind)TokenID
+    
+  
+  
+    
+    Empty
+    {*(clang::IdentifierInfo *)(Ptr & ~PtrMask)}
+    {{Identifier ({*(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
+    {{ObjC Zero Arg Selector (*{(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
+    {{ObjC One Arg Selector (*{(clang::IdentifierInfo *)(Ptr & ~PtrMask)})}}
+    {(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),view(cpp)na}
+    C++ Constructor {{{(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),view(cpp)na}}}
+    C++ Destructor {{*(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask)}}
+    C++ Conversion function {{*(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask)}}
+    C++ Operator {{*(clang::detail::CXXOperatorIdName *)(Ptr & ~PtrMask)}}    
+    {*(clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask),view(cpp)}
+    {{Extra ({*(clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask)})}}
+    
+      StoredNameKind(Ptr & PtrMask),en
+      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
+      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
+      *(clang::IdentifierInfo *)(Ptr & ~PtrMask),na
+      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
+      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
+      *(clang::detail::CXXSpecialNameExtra *)(Ptr & ~PtrMask),na
+      *(clang::detail::CXXOperatorIdName *)(Ptr & ~PtrMask),na      
+      (clang::detail::DeclarationNameExtra *)(Ptr & ~PtrMask),na
+    
+  
+  
+    
+      {(CXXDeductionGuideNameExtra *)this,view(cpp)nand}
+    
+    
+      {(CXXDeductionGuideNameExtra *)this,nand}
+    
+    C++ Literal operator
+    C++ Using directive  
+    {(clang::detail::DeclarationNameExtra::ExtraKind)ExtraKindOrNumArgs,en}{"  ",sb}{*this,view(cpp)}
+    
+      (CXXDeductionGuideNameExtra *)this
+      ExtraKindOrNumArgs
+    
+  
+  
+    {Template->TemplatedDecl,view(cpp)}
+    C++ Deduction guide for {Template->TemplatedDecl,view(cpp)na}
+  
+  
+    {Type,view(cpp)}
+    {Type}
+  
+  
+    {Name}
+  
+  
+    
+    {(ParsedTemplateArgument *)(this+1),view(cpp)na}{this,view(arg1)na}
+    
+    , {((ParsedTemplateArgument *)(this+1))+1,view(cpp)na}{this,view(arg2)na}
+    
+    , ...
+    {Name,na}<{this,view(arg0)na}>
+    
+      Name
+      
+        {this,view(arg0)na}
+        
+          
+            NumArgs
+            (ParsedTemplateArgument *)(this+1)
+          
+        
+      
+      Operator
+    
+  
+  
+    {{annot_template_id ({(clang::TemplateIdAnnotation *)(PtrData),na})}}
+    {{Identifier ({(clang::IdentifierInfo *)(PtrData),na})}}
+    {(clang::tok::TokenKind)Kind,en}
+  
+  
+    {BufferPtr,nasb}
+  
+  
+    {TheLexer._Mypair._Myval2,na}
+    Expanding Macro: {TheTokenLexer._Mypair._Myval2,na}
+    
+  
+  
+    
+      [{(Token *)(CachedTokens.BeginX) + CachedLexPos,na}] {IncludeMacroStack._Mypair._Myval2._Mylast - 1,na}
+    
+     {IncludeMacroStack._Mypair._Myval2._Mylast - 1,na}
+    {CurLexer._Mypair._Myval2,na}
+    Expanding Macro: {CurTokenLexer._Mypair._Myval2,na}
+    
+    
+      {this,view(cached)}
+    
+    CLK_LexAfterModuleImport
+  
+  
+    [{Tok}] {PP,na}
+  
+  
+    this
+    *this
+    {Id}
+    &{Id}
+    No visualizer for {Kind}
+  
+  
+    
+    =,
+    &,
+    
+    {(LambdaCapture *)(Captures.BeginX),na}{this,view(capture1)na}
+    
+    ,{(LambdaCapture *)(Captures.BeginX)+1,na}{this,view(capture2)na}
+    
+    ,{(LambdaCapture *)(Captures.BeginX)+2,na}{this,view(capture3)na}
+    
+    ,...
+    [{this,view(default)na}{this,view(capture0)na}]
+  
+  
+    
+      , [{TypeRep}]
+    
+    
+      , [{ExprRep}]
+    
+    
+      , [{DeclRep}]
+    
+    
+    [{(clang::DeclSpec::SCS)StorageClassSpec,en}], [{(clang::TypeSpecifierType)TypeSpecType,en}]{this,view(extra)na}
+    
+      (clang::DeclSpec::SCS)StorageClassSpec
+      (clang::TypeSpecifierType)TypeSpecType
+      
+        TypeRep
+      
+      
+        ExprRep
+      
+      
+        DeclRep
+      
+
+    
+  
+  
+    {Name,s}
+  
+  
+    {Name,s}
+  
+  
+    {Name,s}
+  
+  
+    
+      (clang::StorageClass)SClass
+      (clang::ThreadStorageClassSpecifier)TSCSpec
+      (clang::VarDecl::InitializationStyle)InitStyle
+    
+  
+  
+    {DeclType,view(left)} {Name,view(cpp)}{DeclType,view(right)}
+    
+      Name
+      DeclType
+    
+  
+  
+    {(DeclaratorDecl*)this,nand}
+    
+      (DeclaratorDecl*)this,nd
+      Init
+      VarDeclBits
+    
+  
+  
+    {*(VarDecl*)this,nd}
+    
+      ParmVarDeclBits
+      *(VarDecl*)this,nd
+    
+  
+  
+    {"explicit ",sb}
+    
+    explicit({ExplicitSpec,view(ptr)na})
+    {ExplicitSpec,view(int)en}
+    {ExplicitSpec,view(int)en} : {ExplicitSpec,view(ptr)na}
+  
+  
+    {ExplicitSpec,view(cpp)}{Name,view(cpp)nd}({(FunctionDecl*)this,view(parm0)nand}) -> {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
+    
+      ExplicitSpec
+      (bool)FunctionDeclBits.IsCopyDeductionCandidate
+      (FunctionDecl*)this,nd
+    
+  
+  
+    {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
+    
+    {ParamInfo[0],na}{*this,view(parm1)nd}
+    
+    , {ParamInfo[1],na}{*this,view(parm2)nd}
+    
+    , {ParamInfo[2],na}{*this,view(parm3)nd}
+    
+    , {ParamInfo[3],na}{*this,view(parm4)nd}
+    
+    , {ParamInfo[4],na}{*this,view(parm5)nd}
+    
+    , /* expand for more params */
+    
+      auto {Name,view(cpp)nd}({*this,view(parm0)nd}) -> {((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType,view(cpp)}
+    
+    {this,view(retType)nand} {Name,view(cpp)nd}({*this,view(parm0)nd})
+    
+      (clang::DeclaratorDecl *)this,nd
+      ((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->ResultType
+      
+        {*this,view(parm0)nd}
+        
+          
+            ((clang::FunctionProtoType *)((clang::ExtQualsTypeCommonBase *)(((uintptr_t)DeclType.Value.Value) & ~15))->BaseType)->FunctionTypeBits.NumParams
+            ParamInfo
+          
+        
+      
+      TemplateOrSpecialization
+    
+  
+  
+    {*($T1*)&Ptr}
+    
+      ($T1*)&Ptr
+    
+  
+  
+    {($T1 *)Ptr}
+    
+      ($T1 *)Ptr
+    
+  
+  
+    
+    {*((NamedDecl **)(this+1))[0],view(cpp)}{*this,view(parm1)}
+    
+    , {*((NamedDecl **)(this+1))[1],view(cpp)}{*this,view(parm2)}
+    
+    , {*((NamedDecl **)(this+1))[2],view(cpp)}{*this,view(parm3)}
+    
+    , {*((NamedDecl **)(this+1))[3],view(cpp)}{*this,view(parm4)}
+    
+    , {*((NamedDecl **)(this+1))[4],view(cpp)}{*this,view(parm5)}
+    
+    , /* Expand for more params */
+    <{*this,view(parm0)}>
+    
+      
+        NumParams
+      (NamedDecl **)(this+1)
+      
+    
+  
+  
+    {(clang::Stmt::StmtClass)StmtBits.sClass,en}
+    
+      (clang::Stmt::StmtClass)StmtBits.sClass,en
+    
+  
+  
+    Expression of class {(clang::Stmt::StmtClass)StmtBits.sClass,en} and type {TR,view(cpp)}
+  
+  
+    public
+    protected
+    private
+    
+    {*(clang::NamedDecl *)(Ptr&~Mask)}
+    {*this,view(access)} {*this,view(decl)}
+    
+      (clang::AccessSpecifier)(Ptr&Mask),en
+      *(clang::NamedDecl *)(Ptr&~Mask)
+    
+  
+  
+    [IK_Identifier] {*Identifier}
+    [IK_OperatorFunctionId] {OperatorFunctionId}
+    [IK_ConversionFunctionId] {ConversionFunctionId}
+    [IK_ConstructorName] {ConstructorName}
+    [IK_DestructorName] {DestructorName}
+    [IK_DeductionGuideName] {TemplateName}
+    [IK_TemplateId] {TemplateId}
+    [IK_ConstructorTemplateId] {TemplateId}
+    Kind
+    
+      Identifier
+      OperatorFunctionId
+      ConversionFunctionId
+      ConstructorName
+      DestructorName
+      TemplateName
+      TemplateId
+      TemplateId
+    
+  
+  
+    NumDecls={NumDecls}
+    
+      
+        NumDecls
+        (Decl **)(this+1)
+      
+    
+  
+  
+    {*D}
+    {*(DeclGroup *)((uintptr_t)D&~1)}
+    
+      D
+      (DeclGroup *)((uintptr_t)D&~1)
+    
+  
+  
+    {DS} {Name}
+  
+  
+    {Decls}
+    
+      Decls
+    
+  
+  
+    {Ambiguity,en}: {Decls}
+    {ResultKind,en}: {Decls}
+  
+  
+    Invalid
+    Unset
+    {Val}
+  
+  
+    Invalid
+    Unset
+    {($T1)(PtrWithInvalid&~1)}
+    
+      (bool)(PtrWithInvalid&1)
+      ($T1)(PtrWithInvalid&~1)
+    
+  
+
diff --git a/interpreter/llvm/src/tools/clang/utils/CmpDriver b/interpreter/llvm-project/clang/utils/CmpDriver
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/CmpDriver
rename to interpreter/llvm-project/clang/utils/CmpDriver
diff --git a/interpreter/llvm/src/tools/clang/utils/FindSpecRefs b/interpreter/llvm-project/clang/utils/FindSpecRefs
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/FindSpecRefs
rename to interpreter/llvm-project/clang/utils/FindSpecRefs
diff --git a/interpreter/llvm/src/tools/clang/utils/FuzzTest b/interpreter/llvm-project/clang/utils/FuzzTest
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/FuzzTest
rename to interpreter/llvm-project/clang/utils/FuzzTest
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ASTTableGen.cpp b/interpreter/llvm-project/clang/utils/TableGen/ASTTableGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ASTTableGen.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ASTTableGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ASTTableGen.h b/interpreter/llvm-project/clang/utils/TableGen/ASTTableGen.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ASTTableGen.h
rename to interpreter/llvm-project/clang/utils/TableGen/ASTTableGen.h
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/CMakeLists.txt b/interpreter/llvm-project/clang/utils/TableGen/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/CMakeLists.txt
rename to interpreter/llvm-project/clang/utils/TableGen/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangASTNodesEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangASTNodesEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangASTNodesEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangASTNodesEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangAttrEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangAttrEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangOpcodesEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangOpcodesEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangOpcodesEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangOpcodesEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangOptionDocEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangOptionDocEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangOptionDocEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangOptionDocEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangSACheckersEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangSACheckersEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangSACheckersEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangSACheckersEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangSyntaxEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangSyntaxEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangSyntaxEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangSyntaxEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/ClangTypeNodesEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/ClangTypeNodesEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/ClangTypeNodesEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/ClangTypeNodesEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/MveEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/MveEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/MveEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/MveEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/NeonEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/NeonEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/NeonEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/NeonEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/RISCVVEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/RISCVVEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/SveEmitter.cpp b/interpreter/llvm-project/clang/utils/TableGen/SveEmitter.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/SveEmitter.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/SveEmitter.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/TableGen.cpp b/interpreter/llvm-project/clang/utils/TableGen/TableGen.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/TableGen.cpp
rename to interpreter/llvm-project/clang/utils/TableGen/TableGen.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/TableGen/TableGenBackends.h b/interpreter/llvm-project/clang/utils/TableGen/TableGenBackends.h
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TableGen/TableGenBackends.h
rename to interpreter/llvm-project/clang/utils/TableGen/TableGenBackends.h
diff --git a/interpreter/llvm/src/tools/clang/utils/TestUtils/deep-stack.py b/interpreter/llvm-project/clang/utils/TestUtils/deep-stack.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TestUtils/deep-stack.py
rename to interpreter/llvm-project/clang/utils/TestUtils/deep-stack.py
diff --git a/interpreter/llvm/src/tools/clang/utils/TestUtils/pch-test.pl b/interpreter/llvm-project/clang/utils/TestUtils/pch-test.pl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/TestUtils/pch-test.pl
rename to interpreter/llvm-project/clang/utils/TestUtils/pch-test.pl
diff --git a/interpreter/llvm/src/tools/clang/utils/VtableTest/check-zti b/interpreter/llvm-project/clang/utils/VtableTest/check-zti
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/VtableTest/check-zti
rename to interpreter/llvm-project/clang/utils/VtableTest/check-zti
diff --git a/interpreter/llvm/src/tools/clang/utils/VtableTest/check-ztt b/interpreter/llvm-project/clang/utils/VtableTest/check-ztt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/VtableTest/check-ztt
rename to interpreter/llvm-project/clang/utils/VtableTest/check-ztt
diff --git a/interpreter/llvm/src/tools/clang/utils/VtableTest/check-zvt b/interpreter/llvm-project/clang/utils/VtableTest/check-zvt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/VtableTest/check-zvt
rename to interpreter/llvm-project/clang/utils/VtableTest/check-zvt
diff --git a/interpreter/llvm/src/tools/clang/utils/VtableTest/gen.cc b/interpreter/llvm-project/clang/utils/VtableTest/gen.cc
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/VtableTest/gen.cc
rename to interpreter/llvm-project/clang/utils/VtableTest/gen.cc
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/.dockerignore b/interpreter/llvm-project/clang/utils/analyzer/.dockerignore
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/.dockerignore
rename to interpreter/llvm-project/clang/utils/analyzer/.dockerignore
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/CmpRuns.py b/interpreter/llvm-project/clang/utils/analyzer/CmpRuns.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/CmpRuns.py
rename to interpreter/llvm-project/clang/utils/analyzer/CmpRuns.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/Dockerfile b/interpreter/llvm-project/clang/utils/analyzer/Dockerfile
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/Dockerfile
rename to interpreter/llvm-project/clang/utils/analyzer/Dockerfile
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/ProjectMap.py b/interpreter/llvm-project/clang/utils/analyzer/ProjectMap.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/ProjectMap.py
rename to interpreter/llvm-project/clang/utils/analyzer/ProjectMap.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATest.py b/interpreter/llvm-project/clang/utils/analyzer/SATest.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATest.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATest.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATestAdd.py b/interpreter/llvm-project/clang/utils/analyzer/SATestAdd.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATestAdd.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATestAdd.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATestBenchmark.py b/interpreter/llvm-project/clang/utils/analyzer/SATestBenchmark.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATestBenchmark.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATestBenchmark.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATestBuild.py b/interpreter/llvm-project/clang/utils/analyzer/SATestBuild.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATestBuild.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATestBuild.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATestUpdateDiffs.py b/interpreter/llvm-project/clang/utils/analyzer/SATestUpdateDiffs.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATestUpdateDiffs.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATestUpdateDiffs.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SATestUtils.py b/interpreter/llvm-project/clang/utils/analyzer/SATestUtils.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SATestUtils.py
rename to interpreter/llvm-project/clang/utils/analyzer/SATestUtils.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/SumTimerInfo.py b/interpreter/llvm-project/clang/utils/analyzer/SumTimerInfo.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/SumTimerInfo.py
rename to interpreter/llvm-project/clang/utils/analyzer/SumTimerInfo.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/entrypoint.py b/interpreter/llvm-project/clang/utils/analyzer/entrypoint.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/entrypoint.py
rename to interpreter/llvm-project/clang/utils/analyzer/entrypoint.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/exploded-graph-rewriter.py b/interpreter/llvm-project/clang/utils/analyzer/exploded-graph-rewriter.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/exploded-graph-rewriter.py
rename to interpreter/llvm-project/clang/utils/analyzer/exploded-graph-rewriter.py
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/box2d/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/box2d/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/box2d/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/box2d/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/box2d/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/box2d/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/box2d/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/box2d/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/cxxopts/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/cxxopts/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/cxxopts/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/cxxopts/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/cxxopts/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/cxxopts/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/cxxopts/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/cxxopts/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/drogon/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/drogon/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/drogon/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/drogon/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/drogon/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/drogon/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/drogon/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/drogon/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/duckdb/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/duckdb/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/duckdb/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/duckdb/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/duckdb/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/duckdb/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/duckdb/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/duckdb/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/fmt/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/fmt/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/fmt/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/fmt/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/fmt/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/fmt/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/fmt/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/fmt/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/libsoundio/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/libsoundio/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/libsoundio/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/libsoundio/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/libsoundio/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/libsoundio/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/libsoundio/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/libsoundio/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/oatpp/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/oatpp/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/oatpp/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/oatpp/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/oatpp/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/oatpp/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/oatpp/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/oatpp/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/projects.json b/interpreter/llvm-project/clang/utils/analyzer/projects/projects.json
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/projects.json
rename to interpreter/llvm-project/clang/utils/analyzer/projects/projects.json
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/re2/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/re2/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/re2/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/re2/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/re2/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/re2/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/re2/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/re2/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/simbody/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/simbody/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/simbody/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/simbody/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/simbody/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/simbody/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/simbody/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/simbody/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/symengine/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/symengine/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/symengine/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/symengine/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/symengine/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/symengine/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/symengine/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/symengine/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/termbox/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/termbox/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/termbox/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/termbox/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/termbox/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/termbox/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/termbox/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/termbox/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyexpr/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyexpr/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyexpr/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyexpr/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyexpr/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyexpr/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyexpr/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyexpr/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyspline/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyspline/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyspline/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyspline/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyspline/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyspline/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyspline/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyspline/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyvm/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyvm/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyvm/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyvm/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyvm/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/tinyvm/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tinyvm/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tinyvm/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/zstd/cleanup_run_static_analyzer.sh b/interpreter/llvm-project/clang/utils/analyzer/projects/zstd/cleanup_run_static_analyzer.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/zstd/cleanup_run_static_analyzer.sh
rename to interpreter/llvm-project/clang/utils/analyzer/projects/zstd/cleanup_run_static_analyzer.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/projects/zstd/run_static_analyzer.cmd b/interpreter/llvm-project/clang/utils/analyzer/projects/zstd/run_static_analyzer.cmd
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/projects/zstd/run_static_analyzer.cmd
rename to interpreter/llvm-project/clang/utils/analyzer/projects/zstd/run_static_analyzer.cmd
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/reducer.pl b/interpreter/llvm-project/clang/utils/analyzer/reducer.pl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/reducer.pl
rename to interpreter/llvm-project/clang/utils/analyzer/reducer.pl
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/requirements.txt b/interpreter/llvm-project/clang/utils/analyzer/requirements.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/requirements.txt
rename to interpreter/llvm-project/clang/utils/analyzer/requirements.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/analyzer/update_plist_test.pl b/interpreter/llvm-project/clang/utils/analyzer/update_plist_test.pl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/analyzer/update_plist_test.pl
rename to interpreter/llvm-project/clang/utils/analyzer/update_plist_test.pl
diff --git a/interpreter/llvm/src/tools/clang/utils/bash-autocomplete.sh b/interpreter/llvm-project/clang/utils/bash-autocomplete.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/bash-autocomplete.sh
rename to interpreter/llvm-project/clang/utils/bash-autocomplete.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/builtin-defines.c b/interpreter/llvm-project/clang/utils/builtin-defines.c
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/builtin-defines.c
rename to interpreter/llvm-project/clang/utils/builtin-defines.c
diff --git a/interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.cfg b/interpreter/llvm-project/clang/utils/check_cfc/check_cfc.cfg
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.cfg
rename to interpreter/llvm-project/clang/utils/check_cfc/check_cfc.cfg
diff --git a/interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.py b/interpreter/llvm-project/clang/utils/check_cfc/check_cfc.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.py
rename to interpreter/llvm-project/clang/utils/check_cfc/check_cfc.py
diff --git a/interpreter/llvm/src/tools/clang/utils/check_cfc/obj_diff.py b/interpreter/llvm-project/clang/utils/check_cfc/obj_diff.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/check_cfc/obj_diff.py
rename to interpreter/llvm-project/clang/utils/check_cfc/obj_diff.py
diff --git a/interpreter/llvm/src/tools/clang/utils/check_cfc/setup.py b/interpreter/llvm-project/clang/utils/check_cfc/setup.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/check_cfc/setup.py
rename to interpreter/llvm-project/clang/utils/check_cfc/setup.py
diff --git a/interpreter/llvm/src/tools/clang/utils/check_cfc/test_check_cfc.py b/interpreter/llvm-project/clang/utils/check_cfc/test_check_cfc.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/check_cfc/test_check_cfc.py
rename to interpreter/llvm-project/clang/utils/check_cfc/test_check_cfc.py
diff --git a/interpreter/llvm/src/tools/clang/utils/clangdiag.py b/interpreter/llvm-project/clang/utils/clangdiag.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/clangdiag.py
rename to interpreter/llvm-project/clang/utils/clangdiag.py
diff --git a/interpreter/llvm/src/tools/clang/utils/convert_arm_neon.py b/interpreter/llvm-project/clang/utils/convert_arm_neon.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/convert_arm_neon.py
rename to interpreter/llvm-project/clang/utils/convert_arm_neon.py
diff --git a/interpreter/llvm/src/tools/clang/utils/creduce-clang-crash.py b/interpreter/llvm-project/clang/utils/creduce-clang-crash.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/creduce-clang-crash.py
rename to interpreter/llvm-project/clang/utils/creduce-clang-crash.py
diff --git a/interpreter/llvm/src/tools/clang/utils/find-unused-diagnostics.sh b/interpreter/llvm-project/clang/utils/find-unused-diagnostics.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/find-unused-diagnostics.sh
rename to interpreter/llvm-project/clang/utils/find-unused-diagnostics.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/hmaptool/CMakeLists.txt b/interpreter/llvm-project/clang/utils/hmaptool/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/hmaptool/CMakeLists.txt
rename to interpreter/llvm-project/clang/utils/hmaptool/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/hmaptool/hmaptool b/interpreter/llvm-project/clang/utils/hmaptool/hmaptool
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/hmaptool/hmaptool
rename to interpreter/llvm-project/clang/utils/hmaptool/hmaptool
diff --git a/interpreter/llvm/src/tools/clang/utils/make-ast-dump-check.sh b/interpreter/llvm-project/clang/utils/make-ast-dump-check.sh
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/make-ast-dump-check.sh
rename to interpreter/llvm-project/clang/utils/make-ast-dump-check.sh
diff --git a/interpreter/llvm/src/tools/clang/utils/modfuzz.py b/interpreter/llvm-project/clang/utils/modfuzz.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/modfuzz.py
rename to interpreter/llvm-project/clang/utils/modfuzz.py
diff --git a/interpreter/llvm/src/tools/clang/utils/module-deps-to-rsp.py b/interpreter/llvm-project/clang/utils/module-deps-to-rsp.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/module-deps-to-rsp.py
rename to interpreter/llvm-project/clang/utils/module-deps-to-rsp.py
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/CMakeLists.txt b/interpreter/llvm-project/clang/utils/perf-training/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/CMakeLists.txt
rename to interpreter/llvm-project/clang/utils/perf-training/CMakeLists.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/README.txt b/interpreter/llvm-project/clang/utils/perf-training/README.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/README.txt
rename to interpreter/llvm-project/clang/utils/perf-training/README.txt
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/cxx/hello_world.cpp b/interpreter/llvm-project/clang/utils/perf-training/cxx/hello_world.cpp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/cxx/hello_world.cpp
rename to interpreter/llvm-project/clang/utils/perf-training/cxx/hello_world.cpp
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/lit.cfg b/interpreter/llvm-project/clang/utils/perf-training/lit.cfg
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/lit.cfg
rename to interpreter/llvm-project/clang/utils/perf-training/lit.cfg
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/lit.site.cfg.in b/interpreter/llvm-project/clang/utils/perf-training/lit.site.cfg.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/lit.site.cfg.in
rename to interpreter/llvm-project/clang/utils/perf-training/lit.site.cfg.in
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/order-files.lit.cfg b/interpreter/llvm-project/clang/utils/perf-training/order-files.lit.cfg
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/order-files.lit.cfg
rename to interpreter/llvm-project/clang/utils/perf-training/order-files.lit.cfg
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/order-files.lit.site.cfg.in b/interpreter/llvm-project/clang/utils/perf-training/order-files.lit.site.cfg.in
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/order-files.lit.site.cfg.in
rename to interpreter/llvm-project/clang/utils/perf-training/order-files.lit.site.cfg.in
diff --git a/interpreter/llvm/src/tools/clang/utils/perf-training/perf-helper.py b/interpreter/llvm-project/clang/utils/perf-training/perf-helper.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/perf-training/perf-helper.py
rename to interpreter/llvm-project/clang/utils/perf-training/perf-helper.py
diff --git a/interpreter/llvm/src/tools/clang/utils/token-delta.py b/interpreter/llvm-project/clang/utils/token-delta.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/token-delta.py
rename to interpreter/llvm-project/clang/utils/token-delta.py
diff --git a/interpreter/llvm/src/tools/clang/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp b/interpreter/llvm-project/clang/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp
similarity index 100%
rename from interpreter/llvm/src/tools/clang/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp
rename to interpreter/llvm-project/clang/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp
diff --git a/interpreter/llvm/src/tools/clang/www/OpenProjects.html b/interpreter/llvm-project/clang/www/OpenProjects.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/OpenProjects.html
rename to interpreter/llvm-project/clang/www/OpenProjects.html
diff --git a/interpreter/llvm/src/tools/clang/www/UniversalDriver.html b/interpreter/llvm-project/clang/www/UniversalDriver.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/UniversalDriver.html
rename to interpreter/llvm-project/clang/www/UniversalDriver.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/alpha_checks.html b/interpreter/llvm-project/clang/www/analyzer/alpha_checks.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/alpha_checks.html
rename to interpreter/llvm-project/clang/www/analyzer/alpha_checks.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/annotations.html b/interpreter/llvm-project/clang/www/analyzer/annotations.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/annotations.html
rename to interpreter/llvm-project/clang/www/analyzer/annotations.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/available_checks.html b/interpreter/llvm-project/clang/www/analyzer/available_checks.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/available_checks.html
rename to interpreter/llvm-project/clang/www/analyzer/available_checks.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/checker_dev_manual.html b/interpreter/llvm-project/clang/www/analyzer/checker_dev_manual.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/checker_dev_manual.html
rename to interpreter/llvm-project/clang/www/analyzer/checker_dev_manual.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/codechecker.html b/interpreter/llvm-project/clang/www/analyzer/codechecker.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/codechecker.html
rename to interpreter/llvm-project/clang/www/analyzer/codechecker.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/command-line.html b/interpreter/llvm-project/clang/www/analyzer/command-line.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/command-line.html
rename to interpreter/llvm-project/clang/www/analyzer/command-line.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/content.css b/interpreter/llvm-project/clang/www/analyzer/content.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/content.css
rename to interpreter/llvm-project/clang/www/analyzer/content.css
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/faq.html b/interpreter/llvm-project/clang/www/analyzer/faq.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/faq.html
rename to interpreter/llvm-project/clang/www/analyzer/faq.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/filing_bugs.html b/interpreter/llvm-project/clang/www/analyzer/filing_bugs.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/filing_bugs.html
rename to interpreter/llvm-project/clang/www/analyzer/filing_bugs.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/analyzer_html.png b/interpreter/llvm-project/clang/www/analyzer/images/analyzer_html.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/analyzer_html.png
rename to interpreter/llvm-project/clang/www/analyzer/images/analyzer_html.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/analyzer_xcode.png b/interpreter/llvm-project/clang/www/analyzer/images/analyzer_xcode.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/analyzer_xcode.png
rename to interpreter/llvm-project/clang/www/analyzer/images/analyzer_xcode.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_attribute_nonnull.png b/interpreter/llvm-project/clang/www/analyzer/images/example_attribute_nonnull.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_attribute_nonnull.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_attribute_nonnull.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_cf_returns_retained.png b/interpreter/llvm-project/clang/www/analyzer/images/example_cf_returns_retained.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_cf_returns_retained.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_cf_returns_retained.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_custom_assert.png b/interpreter/llvm-project/clang/www/analyzer/images/example_custom_assert.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_custom_assert.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_custom_assert.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_ns_returns_retained.png b/interpreter/llvm-project/clang/www/analyzer/images/example_ns_returns_retained.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_ns_returns_retained.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_ns_returns_retained.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_null_pointer.png b/interpreter/llvm-project/clang/www/analyzer/images/example_null_pointer.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_null_pointer.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_null_pointer.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/example_use_assert.png b/interpreter/llvm-project/clang/www/analyzer/images/example_use_assert.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/example_use_assert.png
rename to interpreter/llvm-project/clang/www/analyzer/images/example_use_assert.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/arrows_dark.gif b/interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/arrows_dark.gif
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/arrows_dark.gif
rename to interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/arrows_dark.gif
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/arrows_light.gif b/interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/arrows_light.gif
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/arrows_light.gif
rename to interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/arrows_light.gif
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/ellipses_dark.gif b/interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/ellipses_dark.gif
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/ellipses_dark.gif
rename to interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/ellipses_dark.gif
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/ellipses_light.gif b/interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/ellipses_light.gif
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/expandcollapse/ellipses_light.gif
rename to interpreter/llvm-project/clang/www/analyzer/images/expandcollapse/ellipses_light.gif
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/images/scan_build_cmd.png b/interpreter/llvm-project/clang/www/analyzer/images/scan_build_cmd.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/images/scan_build_cmd.png
rename to interpreter/llvm-project/clang/www/analyzer/images/scan_build_cmd.png
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/implicit_checks.html b/interpreter/llvm-project/clang/www/analyzer/implicit_checks.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/implicit_checks.html
rename to interpreter/llvm-project/clang/www/analyzer/implicit_checks.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/index.html b/interpreter/llvm-project/clang/www/analyzer/index.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/index.html
rename to interpreter/llvm-project/clang/www/analyzer/index.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/installation.html b/interpreter/llvm-project/clang/www/analyzer/installation.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/installation.html
rename to interpreter/llvm-project/clang/www/analyzer/installation.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/latest_checker.html.incl b/interpreter/llvm-project/clang/www/analyzer/latest_checker.html.incl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/latest_checker.html.incl
rename to interpreter/llvm-project/clang/www/analyzer/latest_checker.html.incl
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/menu.css b/interpreter/llvm-project/clang/www/analyzer/menu.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/menu.css
rename to interpreter/llvm-project/clang/www/analyzer/menu.css
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/menu.html.incl b/interpreter/llvm-project/clang/www/analyzer/menu.html.incl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/menu.html.incl
rename to interpreter/llvm-project/clang/www/analyzer/menu.html.incl
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/open_projects.html b/interpreter/llvm-project/clang/www/analyzer/open_projects.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/open_projects.html
rename to interpreter/llvm-project/clang/www/analyzer/open_projects.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/potential_checkers.html b/interpreter/llvm-project/clang/www/analyzer/potential_checkers.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/potential_checkers.html
rename to interpreter/llvm-project/clang/www/analyzer/potential_checkers.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/release_notes.html b/interpreter/llvm-project/clang/www/analyzer/release_notes.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/release_notes.html
rename to interpreter/llvm-project/clang/www/analyzer/release_notes.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/scan-build.html b/interpreter/llvm-project/clang/www/analyzer/scan-build.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/scan-build.html
rename to interpreter/llvm-project/clang/www/analyzer/scan-build.html
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/scripts/expandcollapse.js b/interpreter/llvm-project/clang/www/analyzer/scripts/expandcollapse.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/scripts/expandcollapse.js
rename to interpreter/llvm-project/clang/www/analyzer/scripts/expandcollapse.js
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/scripts/menu.js b/interpreter/llvm-project/clang/www/analyzer/scripts/menu.js
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/scripts/menu.js
rename to interpreter/llvm-project/clang/www/analyzer/scripts/menu.js
diff --git a/interpreter/llvm/src/tools/clang/www/analyzer/xcode.html b/interpreter/llvm-project/clang/www/analyzer/xcode.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/analyzer/xcode.html
rename to interpreter/llvm-project/clang/www/analyzer/xcode.html
diff --git a/interpreter/llvm/src/tools/clang/www/builtins.py b/interpreter/llvm-project/clang/www/builtins.py
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/builtins.py
rename to interpreter/llvm-project/clang/www/builtins.py
diff --git a/interpreter/llvm/src/tools/clang/www/c_status.html b/interpreter/llvm-project/clang/www/c_status.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/c_status.html
rename to interpreter/llvm-project/clang/www/c_status.html
diff --git a/interpreter/llvm/src/tools/clang/www/carbon-compile.png b/interpreter/llvm-project/clang/www/carbon-compile.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/carbon-compile.png
rename to interpreter/llvm-project/clang/www/carbon-compile.png
diff --git a/interpreter/llvm/src/tools/clang/www/clang_video-05-25-2007.html b/interpreter/llvm-project/clang/www/clang_video-05-25-2007.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/clang_video-05-25-2007.html
rename to interpreter/llvm-project/clang/www/clang_video-05-25-2007.html
diff --git a/interpreter/llvm/src/tools/clang/www/clang_video-07-25-2007.html b/interpreter/llvm-project/clang/www/clang_video-07-25-2007.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/clang_video-07-25-2007.html
rename to interpreter/llvm-project/clang/www/clang_video-07-25-2007.html
diff --git a/interpreter/llvm/src/tools/clang/www/compatibility.html b/interpreter/llvm-project/clang/www/compatibility.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/compatibility.html
rename to interpreter/llvm-project/clang/www/compatibility.html
diff --git a/interpreter/llvm/src/tools/clang/www/content.css b/interpreter/llvm-project/clang/www/content.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/content.css
rename to interpreter/llvm-project/clang/www/content.css
diff --git a/interpreter/llvm/src/tools/clang/www/cxx_compatibility.html b/interpreter/llvm-project/clang/www/cxx_compatibility.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/cxx_compatibility.html
rename to interpreter/llvm-project/clang/www/cxx_compatibility.html
diff --git a/interpreter/llvm/src/tools/clang/www/cxx_dr_status.html b/interpreter/llvm-project/clang/www/cxx_dr_status.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/cxx_dr_status.html
rename to interpreter/llvm-project/clang/www/cxx_dr_status.html
diff --git a/interpreter/llvm/src/tools/clang/www/cxx_status.html b/interpreter/llvm-project/clang/www/cxx_status.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/cxx_status.html
rename to interpreter/llvm-project/clang/www/cxx_status.html
diff --git a/interpreter/llvm/src/tools/clang/www/demo/DemoInfo.html b/interpreter/llvm-project/clang/www/demo/DemoInfo.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/demo/DemoInfo.html
rename to interpreter/llvm-project/clang/www/demo/DemoInfo.html
diff --git a/interpreter/llvm/src/tools/clang/www/demo/cathead.png b/interpreter/llvm-project/clang/www/demo/cathead.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/demo/cathead.png
rename to interpreter/llvm-project/clang/www/demo/cathead.png
diff --git a/interpreter/llvm/src/tools/clang/www/demo/index.cgi b/interpreter/llvm-project/clang/www/demo/index.cgi
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/demo/index.cgi
rename to interpreter/llvm-project/clang/www/demo/index.cgi
diff --git a/interpreter/llvm/src/tools/clang/www/demo/syntax.css b/interpreter/llvm-project/clang/www/demo/syntax.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/demo/syntax.css
rename to interpreter/llvm-project/clang/www/demo/syntax.css
diff --git a/interpreter/llvm/src/tools/clang/www/demo/what is this directory.txt b/interpreter/llvm-project/clang/www/demo/what is this directory.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/demo/what is this directory.txt
rename to interpreter/llvm-project/clang/www/demo/what is this directory.txt
diff --git a/interpreter/llvm/src/tools/clang/www/diagnostics.html b/interpreter/llvm-project/clang/www/diagnostics.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/diagnostics.html
rename to interpreter/llvm-project/clang/www/diagnostics.html
diff --git a/interpreter/llvm/src/tools/clang/www/favicon.ico b/interpreter/llvm-project/clang/www/favicon.ico
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/favicon.ico
rename to interpreter/llvm-project/clang/www/favicon.ico
diff --git a/interpreter/llvm/src/tools/clang/www/feature-compile1.png b/interpreter/llvm-project/clang/www/feature-compile1.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/feature-compile1.png
rename to interpreter/llvm-project/clang/www/feature-compile1.png
diff --git a/interpreter/llvm/src/tools/clang/www/feature-compile2.png b/interpreter/llvm-project/clang/www/feature-compile2.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/feature-compile2.png
rename to interpreter/llvm-project/clang/www/feature-compile2.png
diff --git a/interpreter/llvm/src/tools/clang/www/feature-memory1.png b/interpreter/llvm-project/clang/www/feature-memory1.png
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/feature-memory1.png
rename to interpreter/llvm-project/clang/www/feature-memory1.png
diff --git a/interpreter/llvm/src/tools/clang/www/features.html b/interpreter/llvm-project/clang/www/features.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/features.html
rename to interpreter/llvm-project/clang/www/features.html
diff --git a/interpreter/llvm/src/tools/clang/www/get_involved.html b/interpreter/llvm-project/clang/www/get_involved.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/get_involved.html
rename to interpreter/llvm-project/clang/www/get_involved.html
diff --git a/interpreter/llvm/src/tools/clang/www/get_started.html b/interpreter/llvm-project/clang/www/get_started.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/get_started.html
rename to interpreter/llvm-project/clang/www/get_started.html
diff --git a/interpreter/llvm/src/tools/clang/www/hacking.html b/interpreter/llvm-project/clang/www/hacking.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/hacking.html
rename to interpreter/llvm-project/clang/www/hacking.html
diff --git a/interpreter/llvm/src/tools/clang/www/index.html b/interpreter/llvm-project/clang/www/index.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/index.html
rename to interpreter/llvm-project/clang/www/index.html
diff --git a/interpreter/llvm/src/tools/clang/www/libstdc++4.4-clang0x.patch b/interpreter/llvm-project/clang/www/libstdc++4.4-clang0x.patch
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/libstdc++4.4-clang0x.patch
rename to interpreter/llvm-project/clang/www/libstdc++4.4-clang0x.patch
diff --git a/interpreter/llvm/src/tools/clang/www/libstdc++4.6-clang11.patch b/interpreter/llvm-project/clang/www/libstdc++4.6-clang11.patch
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/libstdc++4.6-clang11.patch
rename to interpreter/llvm-project/clang/www/libstdc++4.6-clang11.patch
diff --git a/interpreter/llvm/src/tools/clang/www/libstdc++4.7-clang11.patch b/interpreter/llvm-project/clang/www/libstdc++4.7-clang11.patch
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/libstdc++4.7-clang11.patch
rename to interpreter/llvm-project/clang/www/libstdc++4.7-clang11.patch
diff --git a/interpreter/llvm/src/tools/clang/www/make_cxx_dr_status b/interpreter/llvm-project/clang/www/make_cxx_dr_status
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/make_cxx_dr_status
rename to interpreter/llvm-project/clang/www/make_cxx_dr_status
diff --git a/interpreter/llvm/src/tools/clang/www/menu.css b/interpreter/llvm-project/clang/www/menu.css
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/menu.css
rename to interpreter/llvm-project/clang/www/menu.css
diff --git a/interpreter/llvm/src/tools/clang/www/menu.html.incl b/interpreter/llvm-project/clang/www/menu.html.incl
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/menu.html.incl
rename to interpreter/llvm-project/clang/www/menu.html.incl
diff --git a/interpreter/llvm/src/tools/clang/www/related.html b/interpreter/llvm-project/clang/www/related.html
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/related.html
rename to interpreter/llvm-project/clang/www/related.html
diff --git a/interpreter/llvm/src/tools/clang/www/robots.txt b/interpreter/llvm-project/clang/www/robots.txt
similarity index 100%
rename from interpreter/llvm/src/tools/clang/www/robots.txt
rename to interpreter/llvm-project/clang/www/robots.txt
diff --git a/interpreter/llvm-project/llvm-project.tag b/interpreter/llvm-project/llvm-project.tag
new file mode 100644
index 0000000000000..a9a4e39eccf2c
--- /dev/null
+++ b/interpreter/llvm-project/llvm-project.tag
@@ -0,0 +1 @@
+ROOT-llvm13-20231003-01
diff --git a/interpreter/llvm/src/.clang-format b/interpreter/llvm-project/llvm/.clang-format
similarity index 100%
rename from interpreter/llvm/src/.clang-format
rename to interpreter/llvm-project/llvm/.clang-format
diff --git a/interpreter/llvm-project/llvm/.clang-tidy b/interpreter/llvm-project/llvm/.clang-tidy
new file mode 100644
index 0000000000000..47bc73c13f192
--- /dev/null
+++ b/interpreter/llvm-project/llvm/.clang-tidy
@@ -0,0 +1 @@
+InheritParentConfig: true
diff --git a/interpreter/llvm-project/llvm/.gitattributes b/interpreter/llvm-project/llvm/.gitattributes
new file mode 100644
index 0000000000000..48ddf2f02d15b
--- /dev/null
+++ b/interpreter/llvm-project/llvm/.gitattributes
@@ -0,0 +1,19 @@
+# binary files
+test/Object/Inputs/*.a-* binary
+test/tools/dsymutil/Inputs/*.o binary
+test/tools/dsymutil/Inputs/*.a binary
+test/tools/dsymutil/Inputs/*.i386 binary
+test/tools/dsymutil/Inputs/*.x86_64 binary
+test/tools/dsymutil/Inputs/*.armv7m binary
+test/tools/dsymutil/Inputs/*.dylib binary
+test/tools/llvm-ar/Inputs/*.lib binary
+test/tools/llvm-objdump/Inputs/*.a binary
+test/tools/llvm-rc/Inputs/* binary
+test/tools/llvm-strings/Inputs/numbers binary
+test/MC/AsmParser/incbin_abcd binary
+test/YAMLParser/spec-09-02.test binary
+
+# This file must have CRLF line endings, therefore git should treat it as
+# binary and not autoconvert line endings (for example, when core.autocrlf is
+# on).
+test/MC/AsmParser/preserve-comments-crlf.s binary
diff --git a/interpreter/llvm-project/llvm/.gitignore b/interpreter/llvm-project/llvm/.gitignore
new file mode 100644
index 0000000000000..f2ed54a4f4bd7
--- /dev/null
+++ b/interpreter/llvm-project/llvm/.gitignore
@@ -0,0 +1,73 @@
+#==============================================================================#
+# This file specifies intentionally untracked files that git should ignore.
+# See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html
+#
+# This file is intentionally different from the output of `git svn show-ignore`,
+# as most of those are useless.
+#==============================================================================#
+
+#==============================================================================#
+# Nested build directory.
+#==============================================================================#
+/build
+
+#==============================================================================#
+# Explicit files to ignore (only matches one).
+#==============================================================================#
+# Various tag programs
+/tags
+/TAGS
+/GPATH
+/GRTAGS
+/GSYMS
+/GTAGS
+.gitusers
+autom4te.cache
+cscope.files
+cscope.out
+autoconf/aclocal.m4
+autoconf/autom4te.cache
+/compile_commands.json
+# Visual Studio built-in CMake configuration
+/CMakeSettings.json
+# CLion project configuration
+/.idea
+# Qt Creator project configuration
+/CMakeLists.txt.user
+
+#==============================================================================#
+# Directories to ignore (do not add trailing '/'s, they skip symlinks).
+#==============================================================================#
+# External projects that are tracked independently.
+projects/*
+!projects/*.*
+!projects/Makefile
+runtimes/*
+!runtimes/*.*
+# Sphinx build tree, if building in-source dir.
+docs/_build
+# VS2017 and VSCode config files.
+.vscode
+.vs
+
+#==============================================================================#
+# Files created in tree by the Go bindings.
+#==============================================================================#
+bindings/go/llvm/llvm_config.go
+bindings/go/llvm/workdir
+
+#==============================================================================#
+# File extensions to be ignored anywhere in the tree.
+# Placed at the end to override any previous ! patterns.
+#==============================================================================#
+# Temp files created by most text editors.
+*~
+# Merge files created by git.
+*.orig
+# Byte compiled python modules.
+*.pyc
+# vim swap files
+.*.sw?
+.sw?
+#OS X specific files.
+.DS_store
diff --git a/interpreter/llvm/src/CMakeLists.txt b/interpreter/llvm-project/llvm/CMakeLists.txt
similarity index 99%
rename from interpreter/llvm/src/CMakeLists.txt
rename to interpreter/llvm-project/llvm/CMakeLists.txt
index af53a26d2d67f..9525ad6e3b6d4 100644
--- a/interpreter/llvm/src/CMakeLists.txt
+++ b/interpreter/llvm-project/llvm/CMakeLists.txt
@@ -754,6 +754,9 @@ foreach(t ${LLVM_TARGETS_TO_BUILD})
   endif()
 endforeach(t)
 
+# Provide an LLVM_ namespaced alias for use in #cmakedefine.
+set(LLVM_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS})
+
 # Produce the target definition files, which provide a way for clients to easily
 # include various classes of targets.
 configure_file(
diff --git a/interpreter/llvm/src/CODE_OWNERS.TXT b/interpreter/llvm-project/llvm/CODE_OWNERS.TXT
similarity index 100%
rename from interpreter/llvm/src/CODE_OWNERS.TXT
rename to interpreter/llvm-project/llvm/CODE_OWNERS.TXT
diff --git a/interpreter/llvm/src/CREDITS.TXT b/interpreter/llvm-project/llvm/CREDITS.TXT
similarity index 100%
rename from interpreter/llvm/src/CREDITS.TXT
rename to interpreter/llvm-project/llvm/CREDITS.TXT
diff --git a/interpreter/llvm/src/LICENSE.TXT b/interpreter/llvm-project/llvm/LICENSE.TXT
similarity index 100%
rename from interpreter/llvm/src/LICENSE.TXT
rename to interpreter/llvm-project/llvm/LICENSE.TXT
diff --git a/interpreter/llvm/src/README.txt b/interpreter/llvm-project/llvm/README.txt
similarity index 100%
rename from interpreter/llvm/src/README.txt
rename to interpreter/llvm-project/llvm/README.txt
diff --git a/interpreter/llvm/src/RELEASE_TESTERS.TXT b/interpreter/llvm-project/llvm/RELEASE_TESTERS.TXT
similarity index 100%
rename from interpreter/llvm/src/RELEASE_TESTERS.TXT
rename to interpreter/llvm-project/llvm/RELEASE_TESTERS.TXT
diff --git a/interpreter/llvm/src/cmake/README b/interpreter/llvm-project/llvm/cmake/README
similarity index 100%
rename from interpreter/llvm/src/cmake/README
rename to interpreter/llvm-project/llvm/cmake/README
diff --git a/interpreter/llvm/src/cmake/config-ix.cmake b/interpreter/llvm-project/llvm/cmake/config-ix.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/config-ix.cmake
rename to interpreter/llvm-project/llvm/cmake/config-ix.cmake
diff --git a/interpreter/llvm/src/cmake/config.guess b/interpreter/llvm-project/llvm/cmake/config.guess
similarity index 100%
rename from interpreter/llvm/src/cmake/config.guess
rename to interpreter/llvm-project/llvm/cmake/config.guess
diff --git a/interpreter/llvm/src/cmake/dummy.cpp b/interpreter/llvm-project/llvm/cmake/dummy.cpp
similarity index 100%
rename from interpreter/llvm/src/cmake/dummy.cpp
rename to interpreter/llvm-project/llvm/cmake/dummy.cpp
diff --git a/interpreter/llvm/src/cmake/modules/AddLLVM.cmake b/interpreter/llvm-project/llvm/cmake/modules/AddLLVM.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/AddLLVM.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/AddLLVM.cmake
diff --git a/interpreter/llvm/src/cmake/modules/AddLLVMDefinitions.cmake b/interpreter/llvm-project/llvm/cmake/modules/AddLLVMDefinitions.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/AddLLVMDefinitions.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/AddLLVMDefinitions.cmake
diff --git a/interpreter/llvm/src/cmake/modules/AddOCaml.cmake b/interpreter/llvm-project/llvm/cmake/modules/AddOCaml.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/AddOCaml.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/AddOCaml.cmake
diff --git a/interpreter/llvm/src/cmake/modules/AddSphinxTarget.cmake b/interpreter/llvm-project/llvm/cmake/modules/AddSphinxTarget.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/AddSphinxTarget.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/AddSphinxTarget.cmake
diff --git a/interpreter/llvm/src/cmake/modules/CMakeLists.txt b/interpreter/llvm-project/llvm/cmake/modules/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/CMakeLists.txt
rename to interpreter/llvm-project/llvm/cmake/modules/CMakeLists.txt
diff --git a/interpreter/llvm/src/cmake/modules/CheckAtomic.cmake b/interpreter/llvm-project/llvm/cmake/modules/CheckAtomic.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/CheckAtomic.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/CheckAtomic.cmake
diff --git a/interpreter/llvm/src/cmake/modules/CheckCompilerVersion.cmake b/interpreter/llvm-project/llvm/cmake/modules/CheckCompilerVersion.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/CheckCompilerVersion.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/CheckCompilerVersion.cmake
diff --git a/interpreter/llvm/src/cmake/modules/ChooseMSVCCRT.cmake b/interpreter/llvm-project/llvm/cmake/modules/ChooseMSVCCRT.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/ChooseMSVCCRT.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/ChooseMSVCCRT.cmake
diff --git a/interpreter/llvm/src/cmake/modules/CrossCompile.cmake b/interpreter/llvm-project/llvm/cmake/modules/CrossCompile.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/CrossCompile.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/CrossCompile.cmake
diff --git a/interpreter/llvm/src/cmake/modules/DetermineGCCCompatible.cmake b/interpreter/llvm-project/llvm/cmake/modules/DetermineGCCCompatible.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/DetermineGCCCompatible.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/DetermineGCCCompatible.cmake
diff --git a/interpreter/llvm/src/cmake/modules/FindGRPC.cmake b/interpreter/llvm-project/llvm/cmake/modules/FindGRPC.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/FindGRPC.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/FindGRPC.cmake
diff --git a/interpreter/llvm/src/cmake/modules/FindLibpfm.cmake b/interpreter/llvm-project/llvm/cmake/modules/FindLibpfm.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/FindLibpfm.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/FindLibpfm.cmake
diff --git a/interpreter/llvm/src/cmake/modules/FindOCaml.cmake b/interpreter/llvm-project/llvm/cmake/modules/FindOCaml.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/FindOCaml.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/FindOCaml.cmake
diff --git a/interpreter/llvm/src/cmake/modules/FindSphinx.cmake b/interpreter/llvm-project/llvm/cmake/modules/FindSphinx.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/FindSphinx.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/FindSphinx.cmake
diff --git a/interpreter/llvm/src/cmake/modules/FindZ3.cmake b/interpreter/llvm-project/llvm/cmake/modules/FindZ3.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/FindZ3.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/FindZ3.cmake
diff --git a/interpreter/llvm/src/cmake/modules/GenerateVersionFromVCS.cmake b/interpreter/llvm-project/llvm/cmake/modules/GenerateVersionFromVCS.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/GenerateVersionFromVCS.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/GenerateVersionFromVCS.cmake
diff --git a/interpreter/llvm/src/cmake/modules/GetErrcMessages.cmake b/interpreter/llvm-project/llvm/cmake/modules/GetErrcMessages.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/GetErrcMessages.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/GetErrcMessages.cmake
diff --git a/interpreter/llvm/src/cmake/modules/GetHostTriple.cmake b/interpreter/llvm-project/llvm/cmake/modules/GetHostTriple.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/GetHostTriple.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/GetHostTriple.cmake
diff --git a/interpreter/llvm/src/cmake/modules/GetLibraryName.cmake b/interpreter/llvm-project/llvm/cmake/modules/GetLibraryName.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/GetLibraryName.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/GetLibraryName.cmake
diff --git a/interpreter/llvm/src/cmake/modules/HandleLLVMOptions.cmake b/interpreter/llvm-project/llvm/cmake/modules/HandleLLVMOptions.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/HandleLLVMOptions.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/HandleLLVMOptions.cmake
diff --git a/interpreter/llvm/src/cmake/modules/HandleLLVMStdlib.cmake b/interpreter/llvm-project/llvm/cmake/modules/HandleLLVMStdlib.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/HandleLLVMStdlib.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/HandleLLVMStdlib.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVM-Build.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVM-Build.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVM-Build.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVM-Build.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVM-Config.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVM-Config.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVM-Config.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVM-Config.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVMCheckLinkerFlag.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVMCheckLinkerFlag.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMCheckLinkerFlag.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMCheckLinkerFlag.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVMConfig.cmake.in b/interpreter/llvm-project/llvm/cmake/modules/LLVMConfig.cmake.in
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMConfig.cmake.in
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMConfig.cmake.in
diff --git a/interpreter/llvm/src/cmake/modules/LLVMConfigVersion.cmake.in b/interpreter/llvm-project/llvm/cmake/modules/LLVMConfigVersion.cmake.in
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMConfigVersion.cmake.in
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMConfigVersion.cmake.in
diff --git a/interpreter/llvm/src/cmake/modules/LLVMDistributionSupport.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVMDistributionSupport.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMDistributionSupport.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMDistributionSupport.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVMExternalProjectUtils.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVMExternalProjectUtils.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMExternalProjectUtils.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMExternalProjectUtils.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVMInstallSymlink.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVMInstallSymlink.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMInstallSymlink.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMInstallSymlink.cmake
diff --git a/interpreter/llvm/src/cmake/modules/LLVMProcessSources.cmake b/interpreter/llvm-project/llvm/cmake/modules/LLVMProcessSources.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/LLVMProcessSources.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/LLVMProcessSources.cmake
diff --git a/interpreter/llvm/src/cmake/modules/TableGen.cmake b/interpreter/llvm-project/llvm/cmake/modules/TableGen.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/TableGen.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/TableGen.cmake
diff --git a/interpreter/llvm/src/cmake/modules/TensorFlowCompile.cmake b/interpreter/llvm-project/llvm/cmake/modules/TensorFlowCompile.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/TensorFlowCompile.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/TensorFlowCompile.cmake
diff --git a/interpreter/llvm/src/cmake/modules/UseLibtool.cmake b/interpreter/llvm-project/llvm/cmake/modules/UseLibtool.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/UseLibtool.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/UseLibtool.cmake
diff --git a/interpreter/llvm/src/cmake/modules/VersionFromVCS.cmake b/interpreter/llvm-project/llvm/cmake/modules/VersionFromVCS.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/modules/VersionFromVCS.cmake
rename to interpreter/llvm-project/llvm/cmake/modules/VersionFromVCS.cmake
diff --git a/interpreter/llvm/src/cmake/nsis_icon.ico b/interpreter/llvm-project/llvm/cmake/nsis_icon.ico
similarity index 100%
rename from interpreter/llvm/src/cmake/nsis_icon.ico
rename to interpreter/llvm-project/llvm/cmake/nsis_icon.ico
diff --git a/interpreter/llvm/src/cmake/nsis_logo.bmp b/interpreter/llvm-project/llvm/cmake/nsis_logo.bmp
similarity index 100%
rename from interpreter/llvm/src/cmake/nsis_logo.bmp
rename to interpreter/llvm-project/llvm/cmake/nsis_logo.bmp
diff --git a/interpreter/llvm/src/cmake/platforms/Android.cmake b/interpreter/llvm-project/llvm/cmake/platforms/Android.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/platforms/Android.cmake
rename to interpreter/llvm-project/llvm/cmake/platforms/Android.cmake
diff --git a/interpreter/llvm/src/cmake/platforms/ClangClCMakeCompileRules.cmake b/interpreter/llvm-project/llvm/cmake/platforms/ClangClCMakeCompileRules.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/platforms/ClangClCMakeCompileRules.cmake
rename to interpreter/llvm-project/llvm/cmake/platforms/ClangClCMakeCompileRules.cmake
diff --git a/interpreter/llvm/src/cmake/platforms/WinMsvc.cmake b/interpreter/llvm-project/llvm/cmake/platforms/WinMsvc.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/platforms/WinMsvc.cmake
rename to interpreter/llvm-project/llvm/cmake/platforms/WinMsvc.cmake
diff --git a/interpreter/llvm/src/cmake/platforms/iOS.cmake b/interpreter/llvm-project/llvm/cmake/platforms/iOS.cmake
similarity index 100%
rename from interpreter/llvm/src/cmake/platforms/iOS.cmake
rename to interpreter/llvm-project/llvm/cmake/platforms/iOS.cmake
diff --git a/interpreter/llvm/src/cmake/unwind.h b/interpreter/llvm-project/llvm/cmake/unwind.h
similarity index 100%
rename from interpreter/llvm/src/cmake/unwind.h
rename to interpreter/llvm-project/llvm/cmake/unwind.h
diff --git a/interpreter/llvm/src/configure b/interpreter/llvm-project/llvm/configure
similarity index 100%
rename from interpreter/llvm/src/configure
rename to interpreter/llvm-project/llvm/configure
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX1011.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX1011.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX1011.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX1011.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX900.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX900.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX900.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX900.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX904.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX904.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX904.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX904.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX906.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX906.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX906.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX906.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX908.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX908.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX908.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX908.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX90a.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX90a.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/AMDGPUAsmGFX90a.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/AMDGPUAsmGFX90a.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx1011_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx1011_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx1011_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_addr_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_addr_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_addr_ds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_ds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_addr_ds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_ds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_addr_flat.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_flat.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_addr_flat.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_flat.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_addr_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_addr_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_addr_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_attr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_attr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_attr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_attr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_addr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_addr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_addr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_addr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_scratch.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_scratch.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_base_smem_scratch.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_base_smem_scratch.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_bimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_bimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_bimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_bimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_bimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_bimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_bimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_bimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_buf_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_buf_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_atomic_cmp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_atomic_cmp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_atomic_cmp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_atomic_cmp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_atomic_reg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_atomic_reg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_atomic_reg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_atomic_reg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_store.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_store.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_store.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_store.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_store_d16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_store_d16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_mimg_store_d16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_mimg_store_d16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_data_smem_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_data_smem_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_96.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_96.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_96.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_96.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_lds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_lds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_buf_lds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_buf_lds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_flat_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_flat_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_flat_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_flat_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_flat_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_flat_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_flat_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_flat_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_gather4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_gather4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_gather4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_gather4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_regular.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_regular.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_regular.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_regular.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_regular_d16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_regular_d16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_dst_mimg_regular_d16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_dst_mimg_regular_d16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_fimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_fimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_fimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_fimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_fimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_fimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_fimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_fimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_hwreg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_hwreg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_hwreg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_hwreg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_label.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_label.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_label.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_label.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_mad_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mad_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_mad_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mad_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_mod_dpp_sdwa_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_dpp_sdwa_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_mod_dpp_sdwa_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_dpp_sdwa_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_mod_sdwa_sext.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_sdwa_sext.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_mod_sdwa_sext.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_sdwa_sext.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_msg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_msg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_msg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_msg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_offset_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_offset_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_offset_smem_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_smem_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_offset_smem_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_smem_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_offset_smem_plain.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_smem_plain.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_offset_smem_plain.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_offset_smem_plain.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_param.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_param.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_param.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_param.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_perm_smem.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_perm_smem.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_perm_smem.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_perm_smem.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ret.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ret.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ret.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ret.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_rsrc_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_rsrc_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_rsrc_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_rsrc_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_rsrc_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_rsrc_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_rsrc_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_rsrc_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_saddr_flat_global.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_saddr_flat_global.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_saddr_flat_global.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_saddr_flat_global.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_saddr_flat_scratch.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_saddr_flat_scratch.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_saddr_flat_scratch.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_saddr_flat_scratch.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_samp_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_samp_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_samp_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_samp_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdata128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdata128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdata64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdata64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdata64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst256_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst256_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst256_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst256_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst512_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst512_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst512_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst512_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_sdst64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_sdst64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_sdst64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_simm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_simm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_simm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_simm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src32_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src32_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src32_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_src_exp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src_exp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_src_exp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_src_exp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_ssrc64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_ssrc64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_tgt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_tgt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_tgt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_tgt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_uimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_uimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_uimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_uimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vaddr_flat_global.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vaddr_flat_global.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vaddr_flat_global.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vaddr_flat_global.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vaddr_flat_scratch.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vaddr_flat_scratch.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vaddr_flat_scratch.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vaddr_flat_scratch.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vcc_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vcc_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vcc_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vcc_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdata128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdata128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdata64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdata64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdata96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdata96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdata96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vdst96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vdst96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vdst96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_vsrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_vsrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_waitcnt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_waitcnt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_waitcnt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_waitcnt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_wsdst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_wsdst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_wsdst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_wsdst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx10_wssrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_wssrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx10_wssrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx10_wssrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_addr_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_addr_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_addr_ds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_ds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_addr_ds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_ds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_addr_flat.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_flat.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_addr_flat.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_flat.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_addr_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_addr_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_addr_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_attr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_attr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_attr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_attr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_base_smem_addr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_base_smem_addr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_base_smem_addr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_base_smem_addr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_base_smem_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_base_smem_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_base_smem_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_base_smem_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_bimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_bimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_bimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_bimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_bimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_bimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_bimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_bimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_buf_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_buf_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_atomic_cmp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_atomic_cmp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_atomic_cmp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_atomic_cmp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_atomic_reg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_atomic_reg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_atomic_reg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_atomic_reg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_store.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_store.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_data_mimg_store.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_data_mimg_store.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_96.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_96.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_96.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_96.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_lds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_lds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_buf_lds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_buf_lds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_flat_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_flat_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_flat_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_flat_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_flat_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_flat_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_flat_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_flat_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_mimg_gather4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_mimg_gather4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_mimg_gather4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_mimg_gather4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_dst_mimg_regular.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_mimg_regular.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_dst_mimg_regular.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_dst_mimg_regular.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_fimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_fimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_fimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_fimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_hwreg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_hwreg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_hwreg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_hwreg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_label.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_label.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_label.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_label.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_mod.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_mod.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_mod.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_mod.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_msg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_msg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_msg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_msg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_offset_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_offset_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_offset_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_offset_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_offset_smem.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_offset_smem.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_offset_smem.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_offset_smem.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_param.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_param.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_param.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_param.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ret.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ret.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ret.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ret.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_rsrc_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_rsrc_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_rsrc_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_rsrc_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_rsrc_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_rsrc_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_rsrc_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_rsrc_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_samp_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_samp_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_samp_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_samp_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst256_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst256_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst256_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst256_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst512_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst512_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst512_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst512_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_sdst64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_sdst64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_sdst64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_simm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_simm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_simm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_simm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src32_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src32_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src32_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src64_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src64_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src64_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_src_exp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src_exp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_src_exp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_src_exp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc32_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc32_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_ssrc64_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_ssrc64_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_tgt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_tgt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_tgt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_tgt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_uimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_uimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_uimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_uimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vcc_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vcc_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vcc_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vcc_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdata128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdata128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdata64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdata64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdata96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdata96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdata96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vdst96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vdst96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vdst96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_vsrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_vsrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx7_waitcnt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_waitcnt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx7_waitcnt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx7_waitcnt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_addr_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_addr_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_addr_ds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_ds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_addr_ds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_ds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_addr_flat.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_flat.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_addr_flat.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_flat.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_addr_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_addr_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_addr_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_attr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_attr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_attr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_attr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_base_smem_addr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_base_smem_addr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_base_smem_addr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_base_smem_addr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_base_smem_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_base_smem_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_base_smem_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_base_smem_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_bimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_bimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_bimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_bimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_bimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_bimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_bimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_bimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_96.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_96.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_buf_d16_96.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_buf_d16_96.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_atomic_cmp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_atomic_cmp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_atomic_cmp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_atomic_cmp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_atomic_reg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_atomic_reg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_atomic_reg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_atomic_reg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_store.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_store.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_store.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_store.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_store_d16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_store_d16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_data_mimg_store_d16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_data_mimg_store_d16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_96.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_96.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_96.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_96.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_128.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_128.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_128.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_128.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_96.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_96.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_d16_96.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_d16_96.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_lds.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_lds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_buf_lds.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_buf_lds.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_flat_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_flat_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_flat_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_flat_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_flat_atomic64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_flat_atomic64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_flat_atomic64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_flat_atomic64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_gather4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_gather4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_gather4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_gather4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_regular.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_regular.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_regular.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_regular.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_regular_d16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_regular_d16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_dst_mimg_regular_d16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_dst_mimg_regular_d16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_fimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_fimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_fimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_fimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_fimm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_fimm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_fimm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_fimm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_hwreg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_hwreg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_hwreg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_hwreg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_imask.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_imask.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_imask.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_imask.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_label.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_label.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_label.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_label.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_mod_dpp_sdwa_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_dpp_sdwa_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_mod_dpp_sdwa_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_dpp_sdwa_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_mod_sdwa_sext.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_sdwa_sext.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_mod_sdwa_sext.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_sdwa_sext.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_msg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_msg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_msg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_msg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_offset_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_offset_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_offset_smem_load.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_smem_load.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_offset_smem_load.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_smem_load.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_offset_smem_store.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_smem_store.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_offset_smem_store.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_offset_smem_store.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_param.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_param.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_param.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_param.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_perm_smem.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_perm_smem.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_perm_smem.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_perm_smem.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ret.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ret.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ret.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ret.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_rsrc_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_rsrc_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_rsrc_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_rsrc_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_rsrc_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_rsrc_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_rsrc_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_rsrc_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_samp_mimg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_samp_mimg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_samp_mimg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_samp_mimg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdata128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdata128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdata64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdata64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdata64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst256_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst256_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst256_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst256_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst512_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst512_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst512_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst512_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_sdst64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_sdst64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_sdst64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_simm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_simm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_simm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_simm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src32_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src32_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src32_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_src_exp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src_exp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_src_exp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_src_exp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_ssrc64_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_ssrc64_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_tgt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_tgt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_tgt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_tgt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_uimm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_uimm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_uimm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_uimm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vcc_64.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vcc_64.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vcc_64.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vcc_64.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdata128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdata128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdata64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdata64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdata96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdata96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdata96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdst64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdst64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vdst96_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst96_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vdst96_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vdst96_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_vsrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_vsrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx8_waitcnt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_waitcnt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx8_waitcnt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx8_waitcnt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx900_mad_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_mad_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx900_mad_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_mad_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx900_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx900_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx900_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx900_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx900_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx900_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx900_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx900_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx900_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx904_mad_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_mad_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx904_mad_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_mad_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx904_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx904_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx904_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx904_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx904_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx904_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx904_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx904_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx904_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_mad_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mad_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_mad_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mad_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_mod_dpp_sdwa_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_dpp_sdwa_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_mod_dpp_sdwa_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_dpp_sdwa_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_mod_sdwa_sext.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_sdwa_sext.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_mod_sdwa_sext.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_sdwa_sext.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_src32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_src32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_src32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx906_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx906_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx906_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_addr_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_addr_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_addr_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_addr_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_adst1024_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst1024_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_adst1024_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst1024_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_adst128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_adst128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_adst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_adst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_adst512_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst512_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_adst512_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_adst512_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_asrc1024_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc1024_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_asrc1024_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc1024_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_asrc128_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc128_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_asrc128_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc128_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_asrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_asrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_asrc512_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc512_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_asrc512_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_asrc512_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_data_buf_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_data_buf_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_data_buf_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_data_buf_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_dst_flat_atomic32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_dst_flat_atomic32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_dst_flat_atomic32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_dst_flat_atomic32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_mad_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mad_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_mad_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mad_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_mod_dpp_sdwa_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_dpp_sdwa_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_mod_dpp_sdwa_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_dpp_sdwa_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_mod_sdwa_sext.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_sdwa_sext.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_mod_sdwa_sext.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_sdwa_sext.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_mod_vop3_abs_neg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_vop3_abs_neg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_mod_vop3_abs_neg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_mod_vop3_abs_neg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_offset_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_offset_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_offset_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_offset_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_ret.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_ret.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_ret.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_ret.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_rsrc_buf.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_rsrc_buf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_rsrc_buf.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_rsrc_buf.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_saddr_flat_global.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_saddr_flat_global.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_saddr_flat_global.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_saddr_flat_global.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_src32_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_src32_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_src32_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_type_dev.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_type_dev.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_type_dev.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_type_dev.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vaddr_flat_global.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vaddr_flat_global.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vaddr_flat_global.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vaddr_flat_global.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vasrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vasrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vasrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vasrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vasrc64_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vasrc64_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vasrc64_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vasrc64_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vdata32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vdata32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vdata32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vdata32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vdst32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vdst32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vdst32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vdst32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx908_vsrc32_0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vsrc32_0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx908_vsrc32_0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx908_vsrc32_0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_dst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_dst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_dst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_dst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_fx_operand.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_fx_operand.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_fx_operand.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_fx_operand.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_hwreg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_hwreg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_hwreg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_hwreg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_imask.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imask.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_imask.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imask.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_imm16_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_imm16_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_label.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_label.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_label.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_label.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_m.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_m.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_m.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_m.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_m_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_m_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_m_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_m_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_msg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_msg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_msg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_msg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_probe.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_probe.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_probe.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_probe.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_saddr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_saddr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_saddr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_saddr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_saddr_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_saddr_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_saddr_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_saddr_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sbase_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sbase_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdata_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdata_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_sdst_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_sdst_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_simm32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_simm32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_soffset_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_soffset_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_11.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_11.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_11.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_11.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_src_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_src_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_src_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_srsrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_srsrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_srsrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_srsrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_srsrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_srsrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_srsrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_srsrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssamp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssamp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssamp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssamp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_ssrc_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_ssrc_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_type_deviation.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_type_deviation.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_type_deviation.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_type_deviation.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vaddr_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vaddr_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vcc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vcc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vcc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vcc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata0_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata0_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata0_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata0_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata1_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata1_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata1_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata1_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdata_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdata_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_11.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_11.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_11.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_11.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_12.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_12.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_12.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_12.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_13.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_13.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_13.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_13.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_14.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_14.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_14.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_14.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_15.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_15.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_15.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_15.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_17.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_17.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_17.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_17.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_18.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_18.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_18.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_18.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_19.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_19.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_19.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_19.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vdst_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vdst_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_vsrc_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_vsrc_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx90a_waitcnt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_waitcnt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx90a_waitcnt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx90a_waitcnt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_attr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_attr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_attr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_attr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_dst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_dst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_dst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_dst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_hwreg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_hwreg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_hwreg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_hwreg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_imask.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imask.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_imask.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imask.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_imm16.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_imm16.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_imm16_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_imm16_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_imm16_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_imm16_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_imm16_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_label.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_label.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_label.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_label.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_m.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_m.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_m.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_m.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_m_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_m_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_m_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_m_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_msg.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_msg.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_msg.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_msg.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_opt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_opt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_opt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_param.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_param.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_param.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_param.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_probe.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_probe.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_probe.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_probe.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_saddr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_saddr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_saddr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_saddr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_saddr_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_saddr_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_saddr_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_saddr_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sbase.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sbase.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sbase_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sbase_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sbase_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sbase_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sbase_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdata_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdata_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_sdst_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_sdst_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_simm32.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_simm32.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_simm32_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_simm32_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_simm32_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_simm32_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_simm32_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_soffset.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_soffset.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_soffset_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_soffset_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_soffset_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_soffset_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_soffset_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_src_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_src_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_src_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_srsrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_srsrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_srsrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_srsrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_srsrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_srsrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_srsrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_srsrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssamp.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssamp.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssamp.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssamp.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_ssrc_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_ssrc_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_tgt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_tgt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_tgt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_tgt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_type_deviation.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_type_deviation.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_type_deviation.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_type_deviation.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vaddr_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vaddr_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vcc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vcc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vcc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vcc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata0.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata0.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata0.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata0.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata0_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata0_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata0_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata0_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata1_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata1_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata1_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata1_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdata_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdata_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_10.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_10.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_10.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_10.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_11.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_11.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_11.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_11.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_12.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_12.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_12.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_12.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_13.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_13.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_13.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_13.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_4.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_4.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_4.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_4.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_5.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_5.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_5.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_5.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_6.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_6.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_6.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_6.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_7.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_7.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_7.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_7.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_8.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_8.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_8.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_8.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_9.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_9.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vdst_9.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vdst_9.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_1.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_1.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_1.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_1.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_2.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_2.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_2.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_2.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_3.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_3.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_vsrc_3.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_vsrc_3.rst
diff --git a/interpreter/llvm/src/docs/AMDGPU/gfx9_waitcnt.rst b/interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_waitcnt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPU/gfx9_waitcnt.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPU/gfx9_waitcnt.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUDwarfExtensionsForHeterogeneousDebugging.rst b/interpreter/llvm-project/llvm/docs/AMDGPUDwarfExtensionsForHeterogeneousDebugging.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUDwarfExtensionsForHeterogeneousDebugging.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUDwarfExtensionsForHeterogeneousDebugging.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUInstructionNotation.rst b/interpreter/llvm-project/llvm/docs/AMDGPUInstructionNotation.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUInstructionNotation.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUInstructionNotation.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUInstructionSyntax.rst b/interpreter/llvm-project/llvm/docs/AMDGPUInstructionSyntax.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUInstructionSyntax.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUInstructionSyntax.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUModifierSyntax.rst b/interpreter/llvm-project/llvm/docs/AMDGPUModifierSyntax.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUModifierSyntax.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUModifierSyntax.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUOperandSyntax.rst b/interpreter/llvm-project/llvm/docs/AMDGPUOperandSyntax.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUOperandSyntax.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUOperandSyntax.rst
diff --git a/interpreter/llvm/src/docs/AMDGPUUsage.rst b/interpreter/llvm-project/llvm/docs/AMDGPUUsage.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AMDGPUUsage.rst
rename to interpreter/llvm-project/llvm/docs/AMDGPUUsage.rst
diff --git a/interpreter/llvm/src/docs/ARM-BE-bitcastfail.png b/interpreter/llvm-project/llvm/docs/ARM-BE-bitcastfail.png
similarity index 100%
rename from interpreter/llvm/src/docs/ARM-BE-bitcastfail.png
rename to interpreter/llvm-project/llvm/docs/ARM-BE-bitcastfail.png
diff --git a/interpreter/llvm/src/docs/ARM-BE-bitcastsuccess.png b/interpreter/llvm-project/llvm/docs/ARM-BE-bitcastsuccess.png
similarity index 100%
rename from interpreter/llvm/src/docs/ARM-BE-bitcastsuccess.png
rename to interpreter/llvm-project/llvm/docs/ARM-BE-bitcastsuccess.png
diff --git a/interpreter/llvm/src/docs/ARM-BE-ld1.png b/interpreter/llvm-project/llvm/docs/ARM-BE-ld1.png
similarity index 100%
rename from interpreter/llvm/src/docs/ARM-BE-ld1.png
rename to interpreter/llvm-project/llvm/docs/ARM-BE-ld1.png
diff --git a/interpreter/llvm/src/docs/ARM-BE-ldr.png b/interpreter/llvm-project/llvm/docs/ARM-BE-ldr.png
similarity index 100%
rename from interpreter/llvm/src/docs/ARM-BE-ldr.png
rename to interpreter/llvm-project/llvm/docs/ARM-BE-ldr.png
diff --git a/interpreter/llvm/src/docs/AddingConstrainedIntrinsics.rst b/interpreter/llvm-project/llvm/docs/AddingConstrainedIntrinsics.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AddingConstrainedIntrinsics.rst
rename to interpreter/llvm-project/llvm/docs/AddingConstrainedIntrinsics.rst
diff --git a/interpreter/llvm/src/docs/AdvancedBuilds.rst b/interpreter/llvm-project/llvm/docs/AdvancedBuilds.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AdvancedBuilds.rst
rename to interpreter/llvm-project/llvm/docs/AdvancedBuilds.rst
diff --git a/interpreter/llvm/src/docs/AliasAnalysis.rst b/interpreter/llvm-project/llvm/docs/AliasAnalysis.rst
similarity index 100%
rename from interpreter/llvm/src/docs/AliasAnalysis.rst
rename to interpreter/llvm-project/llvm/docs/AliasAnalysis.rst
diff --git a/interpreter/llvm/src/docs/Atomics.rst b/interpreter/llvm-project/llvm/docs/Atomics.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Atomics.rst
rename to interpreter/llvm-project/llvm/docs/Atomics.rst
diff --git a/interpreter/llvm/src/docs/Benchmarking.rst b/interpreter/llvm-project/llvm/docs/Benchmarking.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Benchmarking.rst
rename to interpreter/llvm-project/llvm/docs/Benchmarking.rst
diff --git a/interpreter/llvm/src/docs/BigEndianNEON.rst b/interpreter/llvm-project/llvm/docs/BigEndianNEON.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BigEndianNEON.rst
rename to interpreter/llvm-project/llvm/docs/BigEndianNEON.rst
diff --git a/interpreter/llvm/src/docs/BitCodeFormat.rst b/interpreter/llvm-project/llvm/docs/BitCodeFormat.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BitCodeFormat.rst
rename to interpreter/llvm-project/llvm/docs/BitCodeFormat.rst
diff --git a/interpreter/llvm/src/docs/BlockFrequencyTerminology.rst b/interpreter/llvm-project/llvm/docs/BlockFrequencyTerminology.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BlockFrequencyTerminology.rst
rename to interpreter/llvm-project/llvm/docs/BlockFrequencyTerminology.rst
diff --git a/interpreter/llvm/src/docs/BranchWeightMetadata.rst b/interpreter/llvm-project/llvm/docs/BranchWeightMetadata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BranchWeightMetadata.rst
rename to interpreter/llvm-project/llvm/docs/BranchWeightMetadata.rst
diff --git a/interpreter/llvm/src/docs/BugLifeCycle.rst b/interpreter/llvm-project/llvm/docs/BugLifeCycle.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BugLifeCycle.rst
rename to interpreter/llvm-project/llvm/docs/BugLifeCycle.rst
diff --git a/interpreter/llvm/src/docs/Bugpoint.rst b/interpreter/llvm-project/llvm/docs/Bugpoint.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Bugpoint.rst
rename to interpreter/llvm-project/llvm/docs/Bugpoint.rst
diff --git a/interpreter/llvm/src/docs/BugpointRedesign.md b/interpreter/llvm-project/llvm/docs/BugpointRedesign.md
similarity index 100%
rename from interpreter/llvm/src/docs/BugpointRedesign.md
rename to interpreter/llvm-project/llvm/docs/BugpointRedesign.md
diff --git a/interpreter/llvm/src/docs/BuildingADistribution.rst b/interpreter/llvm-project/llvm/docs/BuildingADistribution.rst
similarity index 100%
rename from interpreter/llvm/src/docs/BuildingADistribution.rst
rename to interpreter/llvm-project/llvm/docs/BuildingADistribution.rst
diff --git a/interpreter/llvm/src/docs/CFIVerify.rst b/interpreter/llvm-project/llvm/docs/CFIVerify.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CFIVerify.rst
rename to interpreter/llvm-project/llvm/docs/CFIVerify.rst
diff --git a/interpreter/llvm/src/docs/CMake.rst b/interpreter/llvm-project/llvm/docs/CMake.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CMake.rst
rename to interpreter/llvm-project/llvm/docs/CMake.rst
diff --git a/interpreter/llvm/src/docs/CMakeLists.txt b/interpreter/llvm-project/llvm/docs/CMakeLists.txt
similarity index 100%
rename from interpreter/llvm/src/docs/CMakeLists.txt
rename to interpreter/llvm-project/llvm/docs/CMakeLists.txt
diff --git a/interpreter/llvm/src/docs/CMakePrimer.rst b/interpreter/llvm-project/llvm/docs/CMakePrimer.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CMakePrimer.rst
rename to interpreter/llvm-project/llvm/docs/CMakePrimer.rst
diff --git a/interpreter/llvm/src/docs/CodeGenerator.rst b/interpreter/llvm-project/llvm/docs/CodeGenerator.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CodeGenerator.rst
rename to interpreter/llvm-project/llvm/docs/CodeGenerator.rst
diff --git a/interpreter/llvm/src/docs/CodeOfConduct.rst b/interpreter/llvm-project/llvm/docs/CodeOfConduct.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CodeOfConduct.rst
rename to interpreter/llvm-project/llvm/docs/CodeOfConduct.rst
diff --git a/interpreter/llvm/src/docs/CodeReview.rst b/interpreter/llvm-project/llvm/docs/CodeReview.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CodeReview.rst
rename to interpreter/llvm-project/llvm/docs/CodeReview.rst
diff --git a/interpreter/llvm/src/docs/CodingStandards.rst b/interpreter/llvm-project/llvm/docs/CodingStandards.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CodingStandards.rst
rename to interpreter/llvm-project/llvm/docs/CodingStandards.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/FileCheck.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/FileCheck.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/FileCheck.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/FileCheck.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/bugpoint.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/bugpoint.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/bugpoint.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/bugpoint.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/clang-tblgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/clang-tblgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/clang-tblgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/clang-tblgen.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/dsymutil.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/dsymutil.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/dsymutil.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/dsymutil.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/index.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/index.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/index.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/index.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/lit.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/lit.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/lit.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/lit.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llc.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llc.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llc.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llc.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/lldb-tblgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/lldb-tblgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/lldb-tblgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/lldb-tblgen.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/lli.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/lli.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/lli.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/lli.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-addr2line.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-addr2line.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-addr2line.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-addr2line.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-ar.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-ar.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-ar.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-ar.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-as.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-as.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-as.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-as.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-bcanalyzer.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-bcanalyzer.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-bcanalyzer.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-bcanalyzer.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-config.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-config.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-config.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-config.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-cov.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cov.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-cov.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cov.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-cxxfilt.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cxxfilt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-cxxfilt.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cxxfilt.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-cxxmap.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cxxmap.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-cxxmap.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-cxxmap.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-diff.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-diff.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-diff.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-diff.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-dis.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-dis.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-dis.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-dis.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-dwarfdump.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-dwarfdump.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-dwarfdump.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-dwarfdump.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-exegesis-analysis.png b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-exegesis-analysis.png
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-exegesis-analysis.png
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-exegesis-analysis.png
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-exegesis.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-exegesis.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-exegesis.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-exegesis.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-extract.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-extract.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-extract.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-extract.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-install-name-tool.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-install-name-tool.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-install-name-tool.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-install-name-tool.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-lib.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-lib.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-lib.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-lib.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-libtool-darwin.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-libtool-darwin.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-libtool-darwin.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-libtool-darwin.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-link.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-link.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-link.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-link.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-lipo.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-lipo.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-lipo.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-lipo.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-locstats.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-locstats.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-locstats.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-locstats.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-mca.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-mca.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-mca.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-mca.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-nm.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-nm.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-nm.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-nm.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-objcopy.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-objcopy.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-objcopy.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-objcopy.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-objdump.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-objdump.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-objdump.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-objdump.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-otool.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-otool.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-otool.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-otool.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-pdbutil.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-pdbutil.rst
similarity index 99%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-pdbutil.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-pdbutil.rst
index 74e1444794dff..955353187112c 100644
--- a/interpreter/llvm/src/docs/CommandGuide/llvm-pdbutil.rst
+++ b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-pdbutil.rst
@@ -27,18 +27,18 @@ Subcommands
 a different purpose.  A brief summary of each command follows, with more detail
 in the sections that follow.
 
-  * :ref:`pretty_subcommand` - Dump symbol and type information in a format that
+  * :ref:`pretty_subcommand` - Dump symbol and type information in a format that
     tries to look as much like the original source code as possible.
-  * :ref:`dump_subcommand` - Dump low level types and structures from the PDB
+  * :ref:`dump_subcommand` - Dump low level types and structures from the PDB
     file, including CodeView records, hash tables, PDB streams, etc.
-  * :ref:`bytes_subcommand` - Dump data from the PDB file's streams, records,
+  * :ref:`bytes_subcommand` - Dump data from the PDB file's streams, records,
     types, symbols, etc as raw bytes.
-  * :ref:`yaml2pdb_subcommand` - Given a yaml description of a PDB file, produce
+  * :ref:`yaml2pdb_subcommand` - Given a yaml description of a PDB file, produce
     a valid PDB file that matches that description.
-  * :ref:`pdb2yaml_subcommand` - For a given PDB file, produce a YAML
-    description of some or all of the file in a way that the PDB can be
+  * :ref:`pdb2yaml_subcommand` - For a given PDB file, produce a YAML
+    description of some or all of the file in a way that the PDB can be
     reconstructed.
-  * :ref:`merge_subcommand` - Given two PDBs, produce a third PDB that is the
+  * :ref:`merge_subcommand` - Given two PDBs, produce a third PDB that is the
     result of merging the two input PDBs.
 
 .. _pretty_subcommand:
@@ -49,7 +49,7 @@ pretty
 .. program:: llvm-pdbutil pretty
 
 .. important::
-   The **pretty** subcommand is built on the Windows DIA SDK, and as such is not
+   The **pretty** subcommand is built on the Windows DIA SDK, and as such is not
    supported on non-Windows platforms.
 
 USAGE: :program:`llvm-pdbutil` pretty [*options*] 
@@ -57,10 +57,10 @@ USAGE: :program:`llvm-pdbutil` pretty [*options*] 
 Summary
 ^^^^^^^^^^^
 
-The *pretty* subcommand displays a very high level representation of your
-program's debug info.  Since it is built on the Windows DIA SDK which is the
-standard API that Windows tools and debuggers query debug information, it
-presents a more authoritative view of how a debugger is going to interpret your
+The *pretty* subcommand displays a very high level representation of your
+program's debug info.  Since it is built on the Windows DIA SDK which is the
+standard API that Windows tools and debuggers query debug information, it
+presents a more authoritative view of how a debugger is going to interpret your
 debug information than a mode which displays low-level CodeView records.
 
 Options
@@ -70,55 +70,55 @@ Filtering and Sorting Options
 +++++++++++++++++++++++++++++
 
 .. note::
-   *exclude* filters take priority over *include* filters.  So if a filter
+   *exclude* filters take priority over *include* filters.  So if a filter
    matches both an include and an exclude rule, then it is excluded.
 
 .. option:: -exclude-compilands=
 
- When dumping compilands, compiland source-file contributions, or per-compiland
- symbols, this option instructs **llvm-pdbutil** to omit any compilands that
+ When dumping compilands, compiland source-file contributions, or per-compiland
+ symbols, this option instructs **llvm-pdbutil** to omit any compilands that
  match the specified regular expression.
 
 .. option:: -exclude-symbols=
 
- When dumping global, public, or per-compiland symbols, this option instructs
- **llvm-pdbutil** to omit any symbols that match the specified regular
+ When dumping global, public, or per-compiland symbols, this option instructs
+ **llvm-pdbutil** to omit any symbols that match the specified regular
  expression.
 
 .. option:: -exclude-types=
 
- When dumping types, this option instructs **llvm-pdbutil** to omit any types
+ When dumping types, this option instructs **llvm-pdbutil** to omit any types
  that match the specified regular expression.
 
 .. option:: -include-compilands=
 
- When dumping compilands, compiland source-file contributions, or per-compiland
- symbols, limit the initial search to only those compilands that match the
+ When dumping compilands, compiland source-file contributions, or per-compiland
+ symbols, limit the initial search to only those compilands that match the
  specified regular expression.
 
 .. option:: -include-symbols=
 
- When dumping global, public, or per-compiland symbols, limit the initial
+ When dumping global, public, or per-compiland symbols, limit the initial
  search to only those symbols that match the specified regular expression.
 
 .. option:: -include-types=
 
- When dumping types, limit the initial search to only those types that match
+ When dumping types, limit the initial search to only those types that match
  the specified regular expression.
 
 .. option:: -min-class-padding=
 
- Only display types that have at least the specified amount of alignment
+ Only display types that have at least the specified amount of alignment
  padding, accounting for padding in base classes and aggregate field members.
 
 .. option:: -min-class-padding-imm=
 
- Only display types that have at least the specified amount of alignment
+ Only display types that have at least the specified amount of alignment
  padding, ignoring padding in base classes and aggregate field members.
 
 .. option:: -min-type-size=
 
- Only display types T where sizeof(T) is greater than or equal to the specified
+ Only display types T where sizeof(T) is greater than or equal to the specified
  amount.
 
 .. option:: -no-compiler-generated
@@ -127,7 +127,7 @@ Filtering and Sorting Options
 
 .. option:: -no-enum-definitions
 
- When dumping an enum, don't show the full enum (e.g. the individual enumerator
+ When dumping an enum, don't show the full enum (e.g. the individual enumerator
  values).
 
 .. option:: -no-system-libs
@@ -233,12 +233,12 @@ Other Options
 
 .. option:: -color-output
 
- Force color output on or off.  By default, color if used if outputting to a
+ Force color output on or off.  By default, color if used if outputting to a
  terminal.
 
 .. option:: -load-address=
 
- When displaying relative virtual addresses, assume the process is loaded at the
+ When displaying relative virtual addresses, assume the process is loaded at the
  given address and display what would be the absolute address.
 
 .. _dump_subcommand:
@@ -253,14 +253,14 @@ USAGE: :program:`llvm-pdbutil` dump [*options*] 
 Summary
 ^^^^^^^^^^^
 
-The **dump** subcommand displays low level information about the structure of a
-PDB file.  It is used heavily by LLVM's testing infrastructure, but can also be
-used for PDB forensics.  It serves a role similar to that of Microsoft's
-`cvdump` tool.
-
-.. note::
-   The **dump** subcommand exposes internal details of the file format.  As
-   such, the reader should be familiar with :doc:`/PDB/index` before using this
+The **dump** subcommand displays low level information about the structure of a
+PDB file.  It is used heavily by LLVM's testing infrastructure, but can also be
+used for PDB forensics.  It serves a role similar to that of Microsoft's
+`cvdump` tool.
+
+.. note::
+   The **dump** subcommand exposes internal details of the file format.  As
+   such, the reader should be familiar with :doc:`/PDB/index` before using this
    command.
 
 Options
@@ -388,8 +388,8 @@ Type Record Options
  When used in conjunction with :option:`-type-index` or :option:`-id-index`,
  dumps the entire dependency graph for the specified index instead of just the
  single record with the specified index.  For example, if type index 0x4000 is
- a function whose return type has index 0x3000, and you specify
- `-dependents=0x4000`, then this would dump both records (as well as any other
+ a function whose return type has index 0x3000, and you specify
+ `-dependents=0x4000`, then this would dump both records (as well as any other
  dependents in the tree).
 
 Miscellaneous Options
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-profdata.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-profdata.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-profdata.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-profdata.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-profgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-profgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-profgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-profgen.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-ranlib.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-ranlib.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-ranlib.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-ranlib.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-readelf.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-readelf.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-readelf.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-readelf.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-readobj.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-readobj.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-readobj.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-readobj.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-size.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-size.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-size.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-size.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-stress.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-stress.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-stress.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-stress.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-strings.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-strings.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-strings.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-strings.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-strip.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-strip.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-strip.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-strip.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-symbolizer.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-symbolizer.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-symbolizer.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-symbolizer.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/llvm-tblgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/llvm-tblgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/llvm-tblgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/llvm-tblgen.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/locstats-compare.png b/interpreter/llvm-project/llvm/docs/CommandGuide/locstats-compare.png
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/locstats-compare.png
rename to interpreter/llvm-project/llvm/docs/CommandGuide/locstats-compare.png
diff --git a/interpreter/llvm/src/docs/CommandGuide/locstats-draw-plot.png b/interpreter/llvm-project/llvm/docs/CommandGuide/locstats-draw-plot.png
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/locstats-draw-plot.png
rename to interpreter/llvm-project/llvm/docs/CommandGuide/locstats-draw-plot.png
diff --git a/interpreter/llvm/src/docs/CommandGuide/mlir-tblgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/mlir-tblgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/mlir-tblgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/mlir-tblgen.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/opt.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/opt.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/opt.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/opt.rst
diff --git a/interpreter/llvm/src/docs/CommandGuide/tblgen.rst b/interpreter/llvm-project/llvm/docs/CommandGuide/tblgen.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandGuide/tblgen.rst
rename to interpreter/llvm-project/llvm/docs/CommandGuide/tblgen.rst
diff --git a/interpreter/llvm/src/docs/CommandLine.rst b/interpreter/llvm-project/llvm/docs/CommandLine.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CommandLine.rst
rename to interpreter/llvm-project/llvm/docs/CommandLine.rst
diff --git a/interpreter/llvm/src/docs/CompileCudaWithLLVM.rst b/interpreter/llvm-project/llvm/docs/CompileCudaWithLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CompileCudaWithLLVM.rst
rename to interpreter/llvm-project/llvm/docs/CompileCudaWithLLVM.rst
diff --git a/interpreter/llvm/src/docs/CompilerWriterInfo.rst b/interpreter/llvm-project/llvm/docs/CompilerWriterInfo.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CompilerWriterInfo.rst
rename to interpreter/llvm-project/llvm/docs/CompilerWriterInfo.rst
diff --git a/interpreter/llvm/src/docs/Contributing.rst b/interpreter/llvm-project/llvm/docs/Contributing.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Contributing.rst
rename to interpreter/llvm-project/llvm/docs/Contributing.rst
diff --git a/interpreter/llvm/src/docs/Coroutines.rst b/interpreter/llvm-project/llvm/docs/Coroutines.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Coroutines.rst
rename to interpreter/llvm-project/llvm/docs/Coroutines.rst
diff --git a/interpreter/llvm/src/docs/CoverageMappingFormat.rst b/interpreter/llvm-project/llvm/docs/CoverageMappingFormat.rst
similarity index 100%
rename from interpreter/llvm/src/docs/CoverageMappingFormat.rst
rename to interpreter/llvm-project/llvm/docs/CoverageMappingFormat.rst
diff --git a/interpreter/llvm/src/docs/DebuggingJITedCode.rst b/interpreter/llvm-project/llvm/docs/DebuggingJITedCode.rst
similarity index 100%
rename from interpreter/llvm/src/docs/DebuggingJITedCode.rst
rename to interpreter/llvm-project/llvm/docs/DebuggingJITedCode.rst
diff --git a/interpreter/llvm/src/docs/DependenceGraphs/cycle.png b/interpreter/llvm-project/llvm/docs/DependenceGraphs/cycle.png
similarity index 100%
rename from interpreter/llvm/src/docs/DependenceGraphs/cycle.png
rename to interpreter/llvm-project/llvm/docs/DependenceGraphs/cycle.png
diff --git a/interpreter/llvm/src/docs/DependenceGraphs/cycle_pi.png b/interpreter/llvm-project/llvm/docs/DependenceGraphs/cycle_pi.png
similarity index 100%
rename from interpreter/llvm/src/docs/DependenceGraphs/cycle_pi.png
rename to interpreter/llvm-project/llvm/docs/DependenceGraphs/cycle_pi.png
diff --git a/interpreter/llvm/src/docs/DependenceGraphs/index.rst b/interpreter/llvm-project/llvm/docs/DependenceGraphs/index.rst
similarity index 100%
rename from interpreter/llvm/src/docs/DependenceGraphs/index.rst
rename to interpreter/llvm-project/llvm/docs/DependenceGraphs/index.rst
diff --git a/interpreter/llvm/src/docs/DependenceGraphs/uml_builder_pattern.png b/interpreter/llvm-project/llvm/docs/DependenceGraphs/uml_builder_pattern.png
similarity index 100%
rename from interpreter/llvm/src/docs/DependenceGraphs/uml_builder_pattern.png
rename to interpreter/llvm-project/llvm/docs/DependenceGraphs/uml_builder_pattern.png
diff --git a/interpreter/llvm/src/docs/DependenceGraphs/uml_nodes_and_edges.png b/interpreter/llvm-project/llvm/docs/DependenceGraphs/uml_nodes_and_edges.png
similarity index 100%
rename from interpreter/llvm/src/docs/DependenceGraphs/uml_nodes_and_edges.png
rename to interpreter/llvm-project/llvm/docs/DependenceGraphs/uml_nodes_and_edges.png
diff --git a/interpreter/llvm/src/docs/DeveloperPolicy.rst b/interpreter/llvm-project/llvm/docs/DeveloperPolicy.rst
similarity index 100%
rename from interpreter/llvm/src/docs/DeveloperPolicy.rst
rename to interpreter/llvm-project/llvm/docs/DeveloperPolicy.rst
diff --git a/interpreter/llvm/src/docs/Docker.rst b/interpreter/llvm-project/llvm/docs/Docker.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Docker.rst
rename to interpreter/llvm-project/llvm/docs/Docker.rst
diff --git a/interpreter/llvm/src/docs/ExceptionHandling.rst b/interpreter/llvm-project/llvm/docs/ExceptionHandling.rst
similarity index 100%
rename from interpreter/llvm/src/docs/ExceptionHandling.rst
rename to interpreter/llvm-project/llvm/docs/ExceptionHandling.rst
diff --git a/interpreter/llvm/src/docs/ExtendedIntegerResults.txt b/interpreter/llvm-project/llvm/docs/ExtendedIntegerResults.txt
similarity index 100%
rename from interpreter/llvm/src/docs/ExtendedIntegerResults.txt
rename to interpreter/llvm-project/llvm/docs/ExtendedIntegerResults.txt
diff --git a/interpreter/llvm/src/docs/ExtendingLLVM.rst b/interpreter/llvm-project/llvm/docs/ExtendingLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/ExtendingLLVM.rst
rename to interpreter/llvm-project/llvm/docs/ExtendingLLVM.rst
diff --git a/interpreter/llvm/src/docs/Extensions.rst b/interpreter/llvm-project/llvm/docs/Extensions.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Extensions.rst
rename to interpreter/llvm-project/llvm/docs/Extensions.rst
diff --git a/interpreter/llvm/src/docs/FAQ.rst b/interpreter/llvm-project/llvm/docs/FAQ.rst
similarity index 100%
rename from interpreter/llvm/src/docs/FAQ.rst
rename to interpreter/llvm-project/llvm/docs/FAQ.rst
diff --git a/interpreter/llvm/src/docs/FaultMaps.rst b/interpreter/llvm-project/llvm/docs/FaultMaps.rst
similarity index 100%
rename from interpreter/llvm/src/docs/FaultMaps.rst
rename to interpreter/llvm-project/llvm/docs/FaultMaps.rst
diff --git a/interpreter/llvm/src/docs/Frontend/PerformanceTips.rst b/interpreter/llvm-project/llvm/docs/Frontend/PerformanceTips.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Frontend/PerformanceTips.rst
rename to interpreter/llvm-project/llvm/docs/Frontend/PerformanceTips.rst
diff --git a/interpreter/llvm/src/docs/FuzzingLLVM.rst b/interpreter/llvm-project/llvm/docs/FuzzingLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/FuzzingLLVM.rst
rename to interpreter/llvm-project/llvm/docs/FuzzingLLVM.rst
diff --git a/interpreter/llvm/src/docs/GarbageCollection.rst b/interpreter/llvm-project/llvm/docs/GarbageCollection.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GarbageCollection.rst
rename to interpreter/llvm-project/llvm/docs/GarbageCollection.rst
diff --git a/interpreter/llvm/src/docs/GetElementPtr.rst b/interpreter/llvm-project/llvm/docs/GetElementPtr.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GetElementPtr.rst
rename to interpreter/llvm-project/llvm/docs/GetElementPtr.rst
diff --git a/interpreter/llvm/src/docs/GettingInvolved.rst b/interpreter/llvm-project/llvm/docs/GettingInvolved.rst
similarity index 97%
rename from interpreter/llvm/src/docs/GettingInvolved.rst
rename to interpreter/llvm-project/llvm/docs/GettingInvolved.rst
index 9ee92c9dfc6fc..f57ca588f2eaa 100644
--- a/interpreter/llvm/src/docs/GettingInvolved.rst
+++ b/interpreter/llvm-project/llvm/docs/GettingInvolved.rst
@@ -1,291 +1,291 @@
-Getting Involved
-================
-
-LLVM welcomes contributions of all kinds. To get started, please review the following topics:
-
-.. contents::
-   :local:
-
-.. toctree::
-   :hidden:
-
-   Contributing
-   DeveloperPolicy
-   CodeReview
-   SupportPolicy
-   SphinxQuickstartTemplate
-   Phabricator
-   HowToSubmitABug
-   BugLifeCycle
-   CodingStandards
-   GitBisecting
-
-:doc:`Contributing`
-   An overview on how to contribute to LLVM.
-
-:doc:`DeveloperPolicy`
-   The LLVM project's policy towards developers and their contributions.
-
-:doc:`CodeReview`
-   The LLVM project's code-review process.
-
-:doc:`SupportPolicy`
-   The LLVM support policy for core and non-core components.
-
-:doc:`SphinxQuickstartTemplate`
-  A template + tutorial for writing new Sphinx documentation. It is meant
-  to be read in source form.
-
-:doc:`Phabricator`
-   Describes how to use the Phabricator code review tool hosted on
-   http://reviews.llvm.org/ and its command line interface, Arcanist.
-
-:doc:`HowToSubmitABug`
-   Instructions for properly submitting information about any bugs you run into
-   in the LLVM system.
-
-:doc:`BugLifeCycle`
-   Describes how bugs are reported, triaged and closed.
-
-:doc:`CodingStandards`
-  Details the LLVM coding standards and provides useful information on writing
-  efficient C++ code.
-
-:doc:`GitBisecting`
-  Describes how to use ``git bisect`` on LLVM's repository.
-
-.. _development-process:
-
-Development Process
--------------------
-
-Information about LLVM's development process.
-
-.. toctree::
-   :hidden:
-
-   Projects
-   HowToReleaseLLVM
-   Packaging
-   ReleaseProcess
-   HowToAddABuilder
-   ReleaseNotes
-
-:doc:`Projects`
-  How-to guide and templates for new projects that *use* the LLVM
-  infrastructure.  The templates (directory organization, Makefiles, and test
-  tree) allow the project code to be located outside (or inside) the ``llvm/``
-  tree, while using LLVM header files and libraries.
-
-:doc:`HowToReleaseLLVM`
-  This is a guide to preparing LLVM releases. Most developers can ignore it.
-
-:doc:`ReleaseProcess`
-  This is a guide to validate a new release, during the release process. Most developers can ignore it.
-
-:doc:`HowToAddABuilder`
-   Instructions for adding new builder to LLVM buildbot master.
-
-:doc:`Packaging`
-   Advice on packaging LLVM into a distribution.
-
-:doc:`Release notes for the current release `
-   This describes new features, known bugs, and other limitations.
-
-.. _mailing-lists:
-
-Mailing Lists
--------------
-
-If you can't find what you need in these docs, try consulting the mailing
-lists.
-
-`Developer's List (llvm-dev)`__
-  This list is for people who want to be included in technical discussions of
-  LLVM. People post to this list when they have questions about writing code
-  for or using the LLVM tools. It is relatively low volume.
-
-  .. __: http://lists.llvm.org/mailman/listinfo/llvm-dev
-
-`Commits Archive (llvm-commits)`__
-  This list contains all commit messages that are made when LLVM developers
-  commit code changes to the repository. It also serves as a forum for
-  patch review (i.e. send patches here). It is useful for those who want to
-  stay on the bleeding edge of LLVM development. This list is very high
-  volume.
-
-  .. __: http://lists.llvm.org/pipermail/llvm-commits/
-
-`Bugs & Patches Archive (llvm-bugs)`__
-  This list gets emailed every time a bug is opened and closed. It is
-  higher volume than the LLVM-dev list.
-
-  .. __: http://lists.llvm.org/pipermail/llvm-bugs/
-
-`Test Results Archive (llvm-testresults)`__
-  A message is automatically sent to this list by every active nightly tester
-  when it completes.  As such, this list gets email several times each day,
-  making it a high volume list.
-
-  .. __: http://lists.llvm.org/pipermail/llvm-testresults/
-
-`LLVM Announcements List (llvm-announce)`__
-  This is a low volume list that provides important announcements regarding
-  LLVM.  It gets email about once a month.
-
-  .. __: http://lists.llvm.org/mailman/listinfo/llvm-announce
-
-.. _online-sync-ups:
-
-Online Sync-Ups
----------------
-
-A number of regular calls are organized on specific topics. It should be
-expected that the range of topics will change over time. At the time of
-writing, the following sync-ups are organized:
-
-.. list-table:: LLVM regular sync-up calls
-   :widths: 25 25 25 25
-   :header-rows: 1
-
-   * - Topic
-     - Frequency
-     - Calendar link
-     - Minutes/docs link
-   * - RISC-V
-     - Every 2 weeks on Thursday
-     - `ics `__
-       `gcal `__
-     - 
-   * - Scalable Vectors and Arm SVE
-     - Monthly, every 3rd Tuesday
-     - `ics `__
-       `gcal `__
-     - `Minutes/docs `__
-   * - ML Guided Compiler Optimizations
-     - Monthly
-     -
-     - `Minutes/docs `__
-   * - `LLVM security group `__
-     - Monthly, every 3rd Tuesday
-     - `ics `__
-       `gcal `__
-     - `Minutes/docs `__
-   * - `CIRCT `__
-     - Weekly, on Wednesday
-     - 
-     - `Minutes/docs `__
-   * - `MLIR `__ design meetings
-     - Weekly, on Thursdays
-     - 
-     - `Minutes/docs `__
-   * - flang
-     - Multiple meeting series, `documented here `__
-     - 
-     - 
-   * - OpenMP
-     - Multiple meeting series, `documented here `__
-     - 
-     - 
-   * - LLVM Alias Analysis
-     - Every 4 weeks on Tuesdays
-     - `ics `__
-     - `Minutes/docs `__
-   * - Windows/COFF related developments
-     - Every 2 months on Thursday
-     - 
-     - `Minutes/docs `__
-   * - Vector Predication
-     - Every 2 weeks on Tuesdays, 3pm UTC
-     -
-     - `Minutes/docs `__
-   * - LLVM Pointer Authentication
-     - Every month on Mondays
-     - `ics `__
-     - `Minutes/docs `__
-   * - MemorySSA in LLVM
-     - Monthly, first Monday of the month; 10:30amPT, 1:30pmET, 5:30pmUTC
-     - `ics `__
-       `gcal `__
-     - `Minutes/docs `__
-
-IRC
----
-
-Users and developers of the LLVM project (including subprojects such as Clang)
-can be found in #llvm on `irc.oftc.net `_.
-
-This channel has several bots.
-
-* Buildbot reporters
-
-  * llvmbb - Bot for the main LLVM buildbot master.
-    http://lab.llvm.org:8011/console
-  * smooshlab - Apple's internal buildbot master.
-
-* robot - Bugzilla linker. %bug 
-
-* clang-bot - A `geordi `_ instance running
-  near-trunk clang instead of gcc.
-
-.. _meetups-social-events:
-
-Meetups and social events
--------------------------
-
-.. toctree::
-   :hidden:
-
-   MeetupGuidelines
-
-Besides developer `meetings and conferences `_,
-there are several user groups called
-`LLVM Socials `_. We greatly encourage you to
-join one in your city. Or start a new one if there is none:
-
-:doc:`MeetupGuidelines`
-
-.. _community-proposals:
-
-Community wide proposals
-------------------------
-
-Proposals for massive changes in how the community behaves and how the work flow
-can be better.
-
-.. toctree::
-   :hidden:
-
-   CodeOfConduct
-   Proposals/GitHubMove
-   BugpointRedesign
-   Proposals/LLVMLibC
-   Proposals/TestSuite
-   Proposals/VariableNames
-   Proposals/VectorizationPlan
-   Proposals/VectorPredication
-
-:doc:`CodeOfConduct`
-   Proposal to adopt a code of conduct on the LLVM social spaces (lists, events,
-   IRC, etc).
-
-:doc:`Proposals/GitHubMove`
-   Proposal to move from SVN/Git to GitHub.
-
-:doc:`BugpointRedesign`
-   Design doc for a redesign of the Bugpoint tool.
-
-:doc:`Proposals/LLVMLibC`
-   Proposal to add a libc implementation under the LLVM project.
-
-:doc:`Proposals/TestSuite`
-   Proposals for additional benchmarks/programs for llvm's test-suite.
-
-:doc:`Proposals/VariableNames`
-   Proposal to change the variable names coding standard.
-
-:doc:`Proposals/VectorizationPlan`
-   Proposal to model the process and upgrade the infrastructure of LLVM's Loop Vectorizer.
-
-:doc:`Proposals/VectorPredication`
-   Proposal for predicated vector instructions in LLVM.
+Getting Involved
+================
+
+LLVM welcomes contributions of all kinds. To get started, please review the following topics:
+
+.. contents::
+   :local:
+
+.. toctree::
+   :hidden:
+
+   Contributing
+   DeveloperPolicy
+   CodeReview
+   SupportPolicy
+   SphinxQuickstartTemplate
+   Phabricator
+   HowToSubmitABug
+   BugLifeCycle
+   CodingStandards
+   GitBisecting
+
+:doc:`Contributing`
+   An overview on how to contribute to LLVM.
+
+:doc:`DeveloperPolicy`
+   The LLVM project's policy towards developers and their contributions.
+
+:doc:`CodeReview`
+   The LLVM project's code-review process.
+
+:doc:`SupportPolicy`
+   The LLVM support policy for core and non-core components.
+
+:doc:`SphinxQuickstartTemplate`
+  A template + tutorial for writing new Sphinx documentation. It is meant
+  to be read in source form.
+
+:doc:`Phabricator`
+   Describes how to use the Phabricator code review tool hosted on
+   http://reviews.llvm.org/ and its command line interface, Arcanist.
+
+:doc:`HowToSubmitABug`
+   Instructions for properly submitting information about any bugs you run into
+   in the LLVM system.
+
+:doc:`BugLifeCycle`
+   Describes how bugs are reported, triaged and closed.
+
+:doc:`CodingStandards`
+  Details the LLVM coding standards and provides useful information on writing
+  efficient C++ code.
+
+:doc:`GitBisecting`
+  Describes how to use ``git bisect`` on LLVM's repository.
+
+.. _development-process:
+
+Development Process
+-------------------
+
+Information about LLVM's development process.
+
+.. toctree::
+   :hidden:
+
+   Projects
+   HowToReleaseLLVM
+   Packaging
+   ReleaseProcess
+   HowToAddABuilder
+   ReleaseNotes
+
+:doc:`Projects`
+  How-to guide and templates for new projects that *use* the LLVM
+  infrastructure.  The templates (directory organization, Makefiles, and test
+  tree) allow the project code to be located outside (or inside) the ``llvm/``
+  tree, while using LLVM header files and libraries.
+
+:doc:`HowToReleaseLLVM`
+  This is a guide to preparing LLVM releases. Most developers can ignore it.
+
+:doc:`ReleaseProcess`
+  This is a guide to validate a new release, during the release process. Most developers can ignore it.
+
+:doc:`HowToAddABuilder`
+   Instructions for adding new builder to LLVM buildbot master.
+
+:doc:`Packaging`
+   Advice on packaging LLVM into a distribution.
+
+:doc:`Release notes for the current release `
+   This describes new features, known bugs, and other limitations.
+
+.. _mailing-lists:
+
+Mailing Lists
+-------------
+
+If you can't find what you need in these docs, try consulting the mailing
+lists.
+
+`Developer's List (llvm-dev)`__
+  This list is for people who want to be included in technical discussions of
+  LLVM. People post to this list when they have questions about writing code
+  for or using the LLVM tools. It is relatively low volume.
+
+  .. __: http://lists.llvm.org/mailman/listinfo/llvm-dev
+
+`Commits Archive (llvm-commits)`__
+  This list contains all commit messages that are made when LLVM developers
+  commit code changes to the repository. It also serves as a forum for
+  patch review (i.e. send patches here). It is useful for those who want to
+  stay on the bleeding edge of LLVM development. This list is very high
+  volume.
+
+  .. __: http://lists.llvm.org/pipermail/llvm-commits/
+
+`Bugs & Patches Archive (llvm-bugs)`__
+  This list gets emailed every time a bug is opened and closed. It is
+  higher volume than the LLVM-dev list.
+
+  .. __: http://lists.llvm.org/pipermail/llvm-bugs/
+
+`Test Results Archive (llvm-testresults)`__
+  A message is automatically sent to this list by every active nightly tester
+  when it completes.  As such, this list gets email several times each day,
+  making it a high volume list.
+
+  .. __: http://lists.llvm.org/pipermail/llvm-testresults/
+
+`LLVM Announcements List (llvm-announce)`__
+  This is a low volume list that provides important announcements regarding
+  LLVM.  It gets email about once a month.
+
+  .. __: http://lists.llvm.org/mailman/listinfo/llvm-announce
+
+.. _online-sync-ups:
+
+Online Sync-Ups
+---------------
+
+A number of regular calls are organized on specific topics. It should be
+expected that the range of topics will change over time. At the time of
+writing, the following sync-ups are organized:
+
+.. list-table:: LLVM regular sync-up calls
+   :widths: 25 25 25 25
+   :header-rows: 1
+
+   * - Topic
+     - Frequency
+     - Calendar link
+     - Minutes/docs link
+   * - RISC-V
+     - Every 2 weeks on Thursday
+     - `ics `__
+       `gcal `__
+     - 
+   * - Scalable Vectors and Arm SVE
+     - Monthly, every 3rd Tuesday
+     - `ics `__
+       `gcal `__
+     - `Minutes/docs `__
+   * - ML Guided Compiler Optimizations
+     - Monthly
+     -
+     - `Minutes/docs `__
+   * - `LLVM security group `__
+     - Monthly, every 3rd Tuesday
+     - `ics `__
+       `gcal `__
+     - `Minutes/docs `__
+   * - `CIRCT `__
+     - Weekly, on Wednesday
+     - 
+     - `Minutes/docs `__
+   * - `MLIR `__ design meetings
+     - Weekly, on Thursdays
+     - 
+     - `Minutes/docs `__
+   * - flang
+     - Multiple meeting series, `documented here `__
+     - 
+     - 
+   * - OpenMP
+     - Multiple meeting series, `documented here `__
+     - 
+     - 
+   * - LLVM Alias Analysis
+     - Every 4 weeks on Tuesdays
+     - `ics `__
+     - `Minutes/docs `__
+   * - Windows/COFF related developments
+     - Every 2 months on Thursday
+     - 
+     - `Minutes/docs `__
+   * - Vector Predication
+     - Every 2 weeks on Tuesdays, 3pm UTC
+     -
+     - `Minutes/docs `__
+   * - LLVM Pointer Authentication
+     - Every month on Mondays
+     - `ics `__
+     - `Minutes/docs `__
+   * - MemorySSA in LLVM
+     - Monthly, first Monday of the month; 10:30amPT, 1:30pmET, 5:30pmUTC
+     - `ics `__
+       `gcal `__
+     - `Minutes/docs `__
+
+IRC
+---
+
+Users and developers of the LLVM project (including subprojects such as Clang)
+can be found in #llvm on `irc.oftc.net `_.
+
+This channel has several bots.
+
+* Buildbot reporters
+
+  * llvmbb - Bot for the main LLVM buildbot master.
+    http://lab.llvm.org:8011/console
+  * smooshlab - Apple's internal buildbot master.
+
+* robot - Bugzilla linker. %bug 
+
+* clang-bot - A `geordi `_ instance running
+  near-trunk clang instead of gcc.
+
+.. _meetups-social-events:
+
+Meetups and social events
+-------------------------
+
+.. toctree::
+   :hidden:
+
+   MeetupGuidelines
+
+Besides developer `meetings and conferences `_,
+there are several user groups called
+`LLVM Socials `_. We greatly encourage you to
+join one in your city. Or start a new one if there is none:
+
+:doc:`MeetupGuidelines`
+
+.. _community-proposals:
+
+Community wide proposals
+------------------------
+
+Proposals for massive changes in how the community behaves and how the work flow
+can be better.
+
+.. toctree::
+   :hidden:
+
+   CodeOfConduct
+   Proposals/GitHubMove
+   BugpointRedesign
+   Proposals/LLVMLibC
+   Proposals/TestSuite
+   Proposals/VariableNames
+   Proposals/VectorizationPlan
+   Proposals/VectorPredication
+
+:doc:`CodeOfConduct`
+   Proposal to adopt a code of conduct on the LLVM social spaces (lists, events,
+   IRC, etc).
+
+:doc:`Proposals/GitHubMove`
+   Proposal to move from SVN/Git to GitHub.
+
+:doc:`BugpointRedesign`
+   Design doc for a redesign of the Bugpoint tool.
+
+:doc:`Proposals/LLVMLibC`
+   Proposal to add a libc implementation under the LLVM project.
+
+:doc:`Proposals/TestSuite`
+   Proposals for additional benchmarks/programs for llvm's test-suite.
+
+:doc:`Proposals/VariableNames`
+   Proposal to change the variable names coding standard.
+
+:doc:`Proposals/VectorizationPlan`
+   Proposal to model the process and upgrade the infrastructure of LLVM's Loop Vectorizer.
+
+:doc:`Proposals/VectorPredication`
+   Proposal for predicated vector instructions in LLVM.
diff --git a/interpreter/llvm/src/docs/GettingStarted.rst b/interpreter/llvm-project/llvm/docs/GettingStarted.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GettingStarted.rst
rename to interpreter/llvm-project/llvm/docs/GettingStarted.rst
diff --git a/interpreter/llvm/src/docs/GettingStartedTutorials.rst b/interpreter/llvm-project/llvm/docs/GettingStartedTutorials.rst
similarity index 96%
rename from interpreter/llvm/src/docs/GettingStartedTutorials.rst
rename to interpreter/llvm-project/llvm/docs/GettingStartedTutorials.rst
index c094b26e66730..712463952b84e 100644
--- a/interpreter/llvm/src/docs/GettingStartedTutorials.rst
+++ b/interpreter/llvm-project/llvm/docs/GettingStartedTutorials.rst
@@ -1,38 +1,38 @@
-Getting Started/Tutorials
-=========================
-
-For those new to the LLVM system.
-
-.. toctree::
-   :hidden:
-
-   CompilerWriterInfo
-   Frontend/PerformanceTips
-   GettingStarted
-   GettingStartedVS
-   ProgrammersManual
-   tutorial/index
-
-:doc:`GettingStarted`
-   Discusses how to get up and running quickly with the LLVM infrastructure.
-   Everything from unpacking and compilation of the distribution to execution
-   of some tools.
-
-:doc:`tutorial/index`
-   Tutorials about using LLVM. Includes a tutorial about making a custom
-   language with LLVM.
-
-:doc:`ProgrammersManual`
-  Introduction to the general layout of the LLVM sourcebase, important classes
-  and APIs, and some tips & tricks.
-
-:doc:`Frontend/PerformanceTips`
-   A collection of tips for frontend authors on how to generate IR
-   which LLVM is able to effectively optimize.
-
-:doc:`GettingStartedVS`
-   An addendum to the main Getting Started guide for those using Visual Studio
-   on Windows.
-
-:doc:`CompilerWriterInfo`
+Getting Started/Tutorials
+=========================
+
+For those new to the LLVM system.
+
+.. toctree::
+   :hidden:
+
+   CompilerWriterInfo
+   Frontend/PerformanceTips
+   GettingStarted
+   GettingStartedVS
+   ProgrammersManual
+   tutorial/index
+
+:doc:`GettingStarted`
+   Discusses how to get up and running quickly with the LLVM infrastructure.
+   Everything from unpacking and compilation of the distribution to execution
+   of some tools.
+
+:doc:`tutorial/index`
+   Tutorials about using LLVM. Includes a tutorial about making a custom
+   language with LLVM.
+
+:doc:`ProgrammersManual`
+  Introduction to the general layout of the LLVM sourcebase, important classes
+  and APIs, and some tips & tricks.
+
+:doc:`Frontend/PerformanceTips`
+   A collection of tips for frontend authors on how to generate IR
+   which LLVM is able to effectively optimize.
+
+:doc:`GettingStartedVS`
+   An addendum to the main Getting Started guide for those using Visual Studio
+   on Windows.
+
+:doc:`CompilerWriterInfo`
   A list of helpful links for compiler writers.
\ No newline at end of file
diff --git a/interpreter/llvm/src/docs/GettingStartedVS.rst b/interpreter/llvm-project/llvm/docs/GettingStartedVS.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GettingStartedVS.rst
rename to interpreter/llvm-project/llvm/docs/GettingStartedVS.rst
diff --git a/interpreter/llvm/src/docs/GitBisecting.rst b/interpreter/llvm-project/llvm/docs/GitBisecting.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GitBisecting.rst
rename to interpreter/llvm-project/llvm/docs/GitBisecting.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/GMIR.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/GMIR.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/GMIR.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/GMIR.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/GenericOpcode.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/GenericOpcode.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/GenericOpcode.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/GenericOpcode.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/IRTranslator.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/IRTranslator.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/IRTranslator.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/IRTranslator.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/InstructionSelect.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/InstructionSelect.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/InstructionSelect.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/InstructionSelect.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/KnownBits.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/KnownBits.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/KnownBits.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/KnownBits.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/Legalizer.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/Legalizer.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/Legalizer.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/Legalizer.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/Pipeline.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/Pipeline.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/Pipeline.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/Pipeline.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/Porting.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/Porting.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/Porting.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/Porting.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/RegBankSelect.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/RegBankSelect.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/RegBankSelect.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/RegBankSelect.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/Resources.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/Resources.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/Resources.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/Resources.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/block-extract.png b/interpreter/llvm-project/llvm/docs/GlobalISel/block-extract.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/block-extract.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/block-extract.png
diff --git a/interpreter/llvm/src/docs/GlobalISel/index.rst b/interpreter/llvm-project/llvm/docs/GlobalISel/index.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/index.rst
rename to interpreter/llvm-project/llvm/docs/GlobalISel/index.rst
diff --git a/interpreter/llvm/src/docs/GlobalISel/pipeline-overview-customized.png b/interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview-customized.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/pipeline-overview-customized.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview-customized.png
diff --git a/interpreter/llvm/src/docs/GlobalISel/pipeline-overview-with-combiners.png b/interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview-with-combiners.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/pipeline-overview-with-combiners.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview-with-combiners.png
diff --git a/interpreter/llvm/src/docs/GlobalISel/pipeline-overview.png b/interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/pipeline-overview.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/pipeline-overview.png
diff --git a/interpreter/llvm/src/docs/GlobalISel/testing-pass-level.png b/interpreter/llvm-project/llvm/docs/GlobalISel/testing-pass-level.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/testing-pass-level.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/testing-pass-level.png
diff --git a/interpreter/llvm/src/docs/GlobalISel/testing-unit-level.png b/interpreter/llvm-project/llvm/docs/GlobalISel/testing-unit-level.png
similarity index 100%
rename from interpreter/llvm/src/docs/GlobalISel/testing-unit-level.png
rename to interpreter/llvm-project/llvm/docs/GlobalISel/testing-unit-level.png
diff --git a/interpreter/llvm/src/docs/GoldPlugin.rst b/interpreter/llvm-project/llvm/docs/GoldPlugin.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GoldPlugin.rst
rename to interpreter/llvm-project/llvm/docs/GoldPlugin.rst
diff --git a/interpreter/llvm/src/docs/GwpAsan.rst b/interpreter/llvm-project/llvm/docs/GwpAsan.rst
similarity index 100%
rename from interpreter/llvm/src/docs/GwpAsan.rst
rename to interpreter/llvm-project/llvm/docs/GwpAsan.rst
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-09-AdveComments.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-09-AdveComments.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-09-AdveComments.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-09-AdveComments.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2002-05-12-InstListChange.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2002-05-12-InstListChange.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2002-05-12-InstListChange.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2002-05-12-InstListChange.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt
diff --git a/interpreter/llvm/src/docs/HistoricalNotes/2007-OriginalClangReadme.txt b/interpreter/llvm-project/llvm/docs/HistoricalNotes/2007-OriginalClangReadme.txt
similarity index 100%
rename from interpreter/llvm/src/docs/HistoricalNotes/2007-OriginalClangReadme.txt
rename to interpreter/llvm-project/llvm/docs/HistoricalNotes/2007-OriginalClangReadme.txt
diff --git a/interpreter/llvm/src/docs/HowToAddABuilder.rst b/interpreter/llvm-project/llvm/docs/HowToAddABuilder.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToAddABuilder.rst
rename to interpreter/llvm-project/llvm/docs/HowToAddABuilder.rst
diff --git a/interpreter/llvm/src/docs/HowToBuildOnARM.rst b/interpreter/llvm-project/llvm/docs/HowToBuildOnARM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToBuildOnARM.rst
rename to interpreter/llvm-project/llvm/docs/HowToBuildOnARM.rst
diff --git a/interpreter/llvm/src/docs/HowToBuildWindowsItaniumPrograms.rst b/interpreter/llvm-project/llvm/docs/HowToBuildWindowsItaniumPrograms.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToBuildWindowsItaniumPrograms.rst
rename to interpreter/llvm-project/llvm/docs/HowToBuildWindowsItaniumPrograms.rst
diff --git a/interpreter/llvm/src/docs/HowToBuildWithPGO.rst b/interpreter/llvm-project/llvm/docs/HowToBuildWithPGO.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToBuildWithPGO.rst
rename to interpreter/llvm-project/llvm/docs/HowToBuildWithPGO.rst
diff --git a/interpreter/llvm/src/docs/HowToCrossCompileBuiltinsOnArm.rst b/interpreter/llvm-project/llvm/docs/HowToCrossCompileBuiltinsOnArm.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToCrossCompileBuiltinsOnArm.rst
rename to interpreter/llvm-project/llvm/docs/HowToCrossCompileBuiltinsOnArm.rst
diff --git a/interpreter/llvm/src/docs/HowToCrossCompileLLVM.rst b/interpreter/llvm-project/llvm/docs/HowToCrossCompileLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToCrossCompileLLVM.rst
rename to interpreter/llvm-project/llvm/docs/HowToCrossCompileLLVM.rst
diff --git a/interpreter/llvm/src/docs/HowToReleaseLLVM.rst b/interpreter/llvm-project/llvm/docs/HowToReleaseLLVM.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToReleaseLLVM.rst
rename to interpreter/llvm-project/llvm/docs/HowToReleaseLLVM.rst
diff --git a/interpreter/llvm/src/docs/HowToSetUpLLVMStyleRTTI.rst b/interpreter/llvm-project/llvm/docs/HowToSetUpLLVMStyleRTTI.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToSetUpLLVMStyleRTTI.rst
rename to interpreter/llvm-project/llvm/docs/HowToSetUpLLVMStyleRTTI.rst
diff --git a/interpreter/llvm/src/docs/HowToSubmitABug.rst b/interpreter/llvm-project/llvm/docs/HowToSubmitABug.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToSubmitABug.rst
rename to interpreter/llvm-project/llvm/docs/HowToSubmitABug.rst
diff --git a/interpreter/llvm/src/docs/HowToUpdateDebugInfo.rst b/interpreter/llvm-project/llvm/docs/HowToUpdateDebugInfo.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToUpdateDebugInfo.rst
rename to interpreter/llvm-project/llvm/docs/HowToUpdateDebugInfo.rst
diff --git a/interpreter/llvm/src/docs/HowToUseAttributes.rst b/interpreter/llvm-project/llvm/docs/HowToUseAttributes.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToUseAttributes.rst
rename to interpreter/llvm-project/llvm/docs/HowToUseAttributes.rst
diff --git a/interpreter/llvm/src/docs/HowToUseInstrMappings.rst b/interpreter/llvm-project/llvm/docs/HowToUseInstrMappings.rst
similarity index 100%
rename from interpreter/llvm/src/docs/HowToUseInstrMappings.rst
rename to interpreter/llvm-project/llvm/docs/HowToUseInstrMappings.rst
diff --git a/interpreter/llvm/src/docs/InAlloca.rst b/interpreter/llvm-project/llvm/docs/InAlloca.rst
similarity index 100%
rename from interpreter/llvm/src/docs/InAlloca.rst
rename to interpreter/llvm-project/llvm/docs/InAlloca.rst
diff --git a/interpreter/llvm/src/docs/JITLink.rst b/interpreter/llvm-project/llvm/docs/JITLink.rst
similarity index 100%
rename from interpreter/llvm/src/docs/JITLink.rst
rename to interpreter/llvm-project/llvm/docs/JITLink.rst
diff --git a/interpreter/llvm/src/docs/LangRef.rst b/interpreter/llvm-project/llvm/docs/LangRef.rst
similarity index 100%
rename from interpreter/llvm/src/docs/LangRef.rst
rename to interpreter/llvm-project/llvm/docs/LangRef.rst
diff --git a/interpreter/llvm/src/docs/Lexicon.rst b/interpreter/llvm-project/llvm/docs/Lexicon.rst
similarity index 100%
rename from interpreter/llvm/src/docs/Lexicon.rst
rename to interpreter/llvm-project/llvm/docs/Lexicon.rst
diff --git a/interpreter/llvm/src/docs/LibFuzzer.rst b/interpreter/llvm-project/llvm/docs/LibFuzzer.rst
similarity index 100%
rename from interpreter/llvm/src/docs/LibFuzzer.rst
rename to interpreter/llvm-project/llvm/docs/LibFuzzer.rst
diff --git a/interpreter/llvm/src/docs/LinkTimeOptimization.rst b/interpreter/llvm-project/llvm/docs/LinkTimeOptimization.rst
similarity index 100%
rename from interpreter/llvm/src/docs/LinkTimeOptimization.rst
rename to interpreter/llvm-project/llvm/docs/LinkTimeOptimization.rst
diff --git a/interpreter/llvm/src/docs/LoopTerminology.rst b/interpreter/llvm-project/llvm/docs/LoopTerminology.rst
similarity index 99%
rename from interpreter/llvm/src/docs/LoopTerminology.rst
rename to interpreter/llvm-project/llvm/docs/LoopTerminology.rst
index 510a718fa469d..8ef77f9acaead 100644
--- a/interpreter/llvm/src/docs/LoopTerminology.rst
+++ b/interpreter/llvm-project/llvm/docs/LoopTerminology.rst
@@ -17,16 +17,16 @@ on the following definition.
 A loop is a subset of nodes from the control-flow graph (CFG; where
 nodes represent basic blocks) with the following properties:
 
-1. The induced subgraph (which is the subgraph that contains all the
+1. The induced subgraph (which is the subgraph that contains all the
    edges from the CFG within the loop) is strongly connected
    (every node is reachable from all others).
 
-2. All edges from outside the subset into the subset point to the same
+2. All edges from outside the subset into the subset point to the same
    node, called the **header**. As a consequence, the header dominates
    all nodes in the loop (i.e. every execution path to any of the loop's
    node will have to pass through the header).
 
-3. The loop is the maximum subset with these properties. That is, no
+3. The loop is the maximum subset with these properties. That is, no
    additional nodes from the CFG can be added such that the induced
    subgraph would still be strongly connected and the header would
    remain the same.
@@ -40,7 +40,7 @@ Terminology
 
 The definition of a loop comes with some additional terminology:
 
-* An **entering block** (or **loop predecessor**) is a non-loop node
+* An **entering block** (or **loop predecessor**) is a non-loop node
   that has an edge into the loop (necessarily the header). If there is
   only one entering block entering block, and its only edge is to the
   header, it is also called the loop's **preheader**. The preheader
@@ -50,7 +50,7 @@ The definition of a loop comes with some additional terminology:
 
 * A **backedge** is an edge from a latch to the header.
 
-* An **exiting edge** is an edge from inside the loop to a node outside
+* An **exiting edge** is an edge from inside the loop to a node outside
   of the loop. The source of such an edge is called an **exiting block**, its
   target is an **exit block**.
 
@@ -63,17 +63,17 @@ Important Notes
 
 This loop definition has some noteworthy consequences:
 
-* A node can be the header of at most one loop. As such, a loop can be
+* A node can be the header of at most one loop. As such, a loop can be
   identified by its header. Due to the header being the only entry into
   a loop, it can be called a Single-Entry-Multiple-Exits (SEME) region.
 
 
-* For basic blocks that are not reachable from the function's entry, the
+* For basic blocks that are not reachable from the function's entry, the
   concept of loops is undefined. This follows from the concept of
   dominance being undefined as well.
 
 
-* The smallest loop consists of a single basic block that branches to
+* The smallest loop consists of a single basic block that branches to
   itself. In this case that block is the header, latch (and exiting
   block if it has another edge to a different block) at the same time.
   A single block that has no branch to itself is not considered a loop,
@@ -91,7 +91,7 @@ same node. :ref:`loopinfo` reports this as:
   Loop at depth 1 containing: %for.body
-* Loops can be nested inside each other. That is, a loop's node set can +* Loops can be nested inside each other. That is, a loop's node set can be a subset of another loop with a different loop header. The loop hierarchy in a function forms a forest: Each top-level loop is the root of the tree of the loops nested inside it. @@ -100,7 +100,7 @@ same node. :ref:`loopinfo` reports this as: :width: 350 px -* It is not possible that two loops share only a few of their nodes. +* It is not possible that two loops share only a few of their nodes. Two loops are either disjoint or one is nested inside the other. In the example below the left and right subsets both violate the maximality condition. Only the merge of both sets is considered a loop. @@ -109,7 +109,7 @@ same node. :ref:`loopinfo` reports this as: :width: 250 px -* It is also possible that two logical loops share a header, but are +* It is also possible that two logical loops share a header, but are considered a single loop by LLVM: .. code-block:: C @@ -130,7 +130,7 @@ detect the loop and ensure separate headers for the outer and inner loop. .. image:: ./loop-separate.svg :width: 400 px -* A cycle in the CFG does not imply there is a loop. The example below +* A cycle in the CFG does not imply there is a loop. The example below shows such a CFG, where there is no header node that dominates all other nodes in the cycle. This is called **irreducible control-flow**. @@ -146,19 +146,19 @@ has a more formal definition, which basically says that every cycle has a dominating header. -* Irreducible control-flow can occur at any level of the loop nesting. +* Irreducible control-flow can occur at any level of the loop nesting. That is, a loop that itself does not contain any loops can still have cyclic control flow in its body; a loop that is not nested inside another loop can still be part of an outer cycle; and there can be additional cycles between any two loops where one is contained in the other. -* Exiting edges are not the only way to break out of a loop. Other +* Exiting edges are not the only way to break out of a loop. Other possibilities are unreachable terminators, [[noreturn]] functions, exceptions, signals, and your computer's power button. -* A basic block "inside" the loop that does not have a path back to the +* A basic block "inside" the loop that does not have a path back to the loop (i.e. to a latch or header) is not considered part of the loop. This is illustrated by the following code. @@ -188,7 +188,7 @@ a dominating header. } -* There is no requirement for the control flow to eventually leave the +* There is no requirement for the control flow to eventually leave the loop, i.e. a loop can be infinite. A **statically infinite loop** is a loop that has no exiting edges. A **dynamically infinite loop** has exiting edges, but it is possible to be never taken. This may happen @@ -215,7 +215,7 @@ into the loop to ensure that the optimizer does not make this assumption without proof. -* The number of executions of the loop header before leaving the loop is +* The number of executions of the loop header before leaving the loop is the **loop trip count** (or **iteration count**). If the loop should not be executed at all, a **loop guard** must skip the entire loop: diff --git a/interpreter/llvm/src/docs/MCJIT-creation.png b/interpreter/llvm-project/llvm/docs/MCJIT-creation.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-creation.png rename to interpreter/llvm-project/llvm/docs/MCJIT-creation.png diff --git a/interpreter/llvm/src/docs/MCJIT-dyld-load.png b/interpreter/llvm-project/llvm/docs/MCJIT-dyld-load.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-dyld-load.png rename to interpreter/llvm-project/llvm/docs/MCJIT-dyld-load.png diff --git a/interpreter/llvm/src/docs/MCJIT-engine-builder.png b/interpreter/llvm-project/llvm/docs/MCJIT-engine-builder.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-engine-builder.png rename to interpreter/llvm-project/llvm/docs/MCJIT-engine-builder.png diff --git a/interpreter/llvm/src/docs/MCJIT-load-object.png b/interpreter/llvm-project/llvm/docs/MCJIT-load-object.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-load-object.png rename to interpreter/llvm-project/llvm/docs/MCJIT-load-object.png diff --git a/interpreter/llvm/src/docs/MCJIT-load.png b/interpreter/llvm-project/llvm/docs/MCJIT-load.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-load.png rename to interpreter/llvm-project/llvm/docs/MCJIT-load.png diff --git a/interpreter/llvm/src/docs/MCJIT-resolve-relocations.png b/interpreter/llvm-project/llvm/docs/MCJIT-resolve-relocations.png similarity index 100% rename from interpreter/llvm/src/docs/MCJIT-resolve-relocations.png rename to interpreter/llvm-project/llvm/docs/MCJIT-resolve-relocations.png diff --git a/interpreter/llvm/src/docs/MCJITDesignAndImplementation.rst b/interpreter/llvm-project/llvm/docs/MCJITDesignAndImplementation.rst similarity index 100% rename from interpreter/llvm/src/docs/MCJITDesignAndImplementation.rst rename to interpreter/llvm-project/llvm/docs/MCJITDesignAndImplementation.rst diff --git a/interpreter/llvm/src/docs/MIRLangRef.rst b/interpreter/llvm-project/llvm/docs/MIRLangRef.rst similarity index 100% rename from interpreter/llvm/src/docs/MIRLangRef.rst rename to interpreter/llvm-project/llvm/docs/MIRLangRef.rst diff --git a/interpreter/llvm/src/docs/Makefile.sphinx b/interpreter/llvm-project/llvm/docs/Makefile.sphinx similarity index 100% rename from interpreter/llvm/src/docs/Makefile.sphinx rename to interpreter/llvm-project/llvm/docs/Makefile.sphinx diff --git a/interpreter/llvm/src/docs/MarkdownQuickstartTemplate.md b/interpreter/llvm-project/llvm/docs/MarkdownQuickstartTemplate.md similarity index 100% rename from interpreter/llvm/src/docs/MarkdownQuickstartTemplate.md rename to interpreter/llvm-project/llvm/docs/MarkdownQuickstartTemplate.md diff --git a/interpreter/llvm/src/docs/MarkedUpDisassembly.rst b/interpreter/llvm-project/llvm/docs/MarkedUpDisassembly.rst similarity index 100% rename from interpreter/llvm/src/docs/MarkedUpDisassembly.rst rename to interpreter/llvm-project/llvm/docs/MarkedUpDisassembly.rst diff --git a/interpreter/llvm/src/docs/MeetupGuidelines.rst b/interpreter/llvm-project/llvm/docs/MeetupGuidelines.rst similarity index 100% rename from interpreter/llvm/src/docs/MeetupGuidelines.rst rename to interpreter/llvm-project/llvm/docs/MeetupGuidelines.rst diff --git a/interpreter/llvm/src/docs/MemTagSanitizer.rst b/interpreter/llvm-project/llvm/docs/MemTagSanitizer.rst similarity index 100% rename from interpreter/llvm/src/docs/MemTagSanitizer.rst rename to interpreter/llvm-project/llvm/docs/MemTagSanitizer.rst diff --git a/interpreter/llvm/src/docs/MemorySSA.rst b/interpreter/llvm-project/llvm/docs/MemorySSA.rst similarity index 100% rename from interpreter/llvm/src/docs/MemorySSA.rst rename to interpreter/llvm-project/llvm/docs/MemorySSA.rst diff --git a/interpreter/llvm/src/docs/MergeFunctions.rst b/interpreter/llvm-project/llvm/docs/MergeFunctions.rst similarity index 100% rename from interpreter/llvm/src/docs/MergeFunctions.rst rename to interpreter/llvm-project/llvm/docs/MergeFunctions.rst diff --git a/interpreter/llvm/src/docs/NVPTXUsage.rst b/interpreter/llvm-project/llvm/docs/NVPTXUsage.rst similarity index 100% rename from interpreter/llvm/src/docs/NVPTXUsage.rst rename to interpreter/llvm-project/llvm/docs/NVPTXUsage.rst diff --git a/interpreter/llvm/src/docs/NewPassManager.rst b/interpreter/llvm-project/llvm/docs/NewPassManager.rst similarity index 100% rename from interpreter/llvm/src/docs/NewPassManager.rst rename to interpreter/llvm-project/llvm/docs/NewPassManager.rst diff --git a/interpreter/llvm/src/docs/ORCv2.rst b/interpreter/llvm-project/llvm/docs/ORCv2.rst similarity index 100% rename from interpreter/llvm/src/docs/ORCv2.rst rename to interpreter/llvm-project/llvm/docs/ORCv2.rst diff --git a/interpreter/llvm/src/docs/OpaquePointers.rst b/interpreter/llvm-project/llvm/docs/OpaquePointers.rst similarity index 100% rename from interpreter/llvm/src/docs/OpaquePointers.rst rename to interpreter/llvm-project/llvm/docs/OpaquePointers.rst diff --git a/interpreter/llvm/src/docs/OptBisect.rst b/interpreter/llvm-project/llvm/docs/OptBisect.rst similarity index 100% rename from interpreter/llvm/src/docs/OptBisect.rst rename to interpreter/llvm-project/llvm/docs/OptBisect.rst diff --git a/interpreter/llvm/src/docs/PDB/CodeViewSymbols.rst b/interpreter/llvm-project/llvm/docs/PDB/CodeViewSymbols.rst similarity index 99% rename from interpreter/llvm/src/docs/PDB/CodeViewSymbols.rst rename to interpreter/llvm-project/llvm/docs/PDB/CodeViewSymbols.rst index 0f218db412f33..b056b804e5ad3 100644 --- a/interpreter/llvm/src/docs/PDB/CodeViewSymbols.rst +++ b/interpreter/llvm-project/llvm/docs/PDB/CodeViewSymbols.rst @@ -93,9 +93,9 @@ the compiler decided to emit is impractical. This differs from DWARF, where eve though we don't necessarily have O(1) lookup by basename within a given scope (including O(1) scope, we at least have O(n) access within a given scope). -.. important:: - Program-wide lookup of names by anything other than an exact textually matching fully - qualified name is not possible. +.. important:: + Program-wide lookup of names by anything other than an exact textually matching fully + qualified name is not possible. S_GDATA32 diff --git a/interpreter/llvm/src/docs/PDB/CodeViewTypes.rst b/interpreter/llvm-project/llvm/docs/PDB/CodeViewTypes.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/CodeViewTypes.rst rename to interpreter/llvm-project/llvm/docs/PDB/CodeViewTypes.rst diff --git a/interpreter/llvm/src/docs/PDB/DbiStream.rst b/interpreter/llvm-project/llvm/docs/PDB/DbiStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/DbiStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/DbiStream.rst diff --git a/interpreter/llvm/src/docs/PDB/GlobalStream.rst b/interpreter/llvm-project/llvm/docs/PDB/GlobalStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/GlobalStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/GlobalStream.rst diff --git a/interpreter/llvm/src/docs/PDB/HashTable.rst b/interpreter/llvm-project/llvm/docs/PDB/HashTable.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/HashTable.rst rename to interpreter/llvm-project/llvm/docs/PDB/HashTable.rst diff --git a/interpreter/llvm/src/docs/PDB/ModiStream.rst b/interpreter/llvm-project/llvm/docs/PDB/ModiStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/ModiStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/ModiStream.rst diff --git a/interpreter/llvm/src/docs/PDB/MsfFile.rst b/interpreter/llvm-project/llvm/docs/PDB/MsfFile.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/MsfFile.rst rename to interpreter/llvm-project/llvm/docs/PDB/MsfFile.rst diff --git a/interpreter/llvm/src/docs/PDB/PdbStream.rst b/interpreter/llvm-project/llvm/docs/PDB/PdbStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/PdbStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/PdbStream.rst diff --git a/interpreter/llvm/src/docs/PDB/PublicStream.rst b/interpreter/llvm-project/llvm/docs/PDB/PublicStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/PublicStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/PublicStream.rst diff --git a/interpreter/llvm/src/docs/PDB/TpiStream.rst b/interpreter/llvm-project/llvm/docs/PDB/TpiStream.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/TpiStream.rst rename to interpreter/llvm-project/llvm/docs/PDB/TpiStream.rst diff --git a/interpreter/llvm/src/docs/PDB/index.rst b/interpreter/llvm-project/llvm/docs/PDB/index.rst similarity index 100% rename from interpreter/llvm/src/docs/PDB/index.rst rename to interpreter/llvm-project/llvm/docs/PDB/index.rst diff --git a/interpreter/llvm/src/docs/Packaging.rst b/interpreter/llvm-project/llvm/docs/Packaging.rst similarity index 100% rename from interpreter/llvm/src/docs/Packaging.rst rename to interpreter/llvm-project/llvm/docs/Packaging.rst diff --git a/interpreter/llvm/src/docs/Passes.rst b/interpreter/llvm-project/llvm/docs/Passes.rst similarity index 100% rename from interpreter/llvm/src/docs/Passes.rst rename to interpreter/llvm-project/llvm/docs/Passes.rst diff --git a/interpreter/llvm/src/docs/Phabricator.rst b/interpreter/llvm-project/llvm/docs/Phabricator.rst similarity index 100% rename from interpreter/llvm/src/docs/Phabricator.rst rename to interpreter/llvm-project/llvm/docs/Phabricator.rst diff --git a/interpreter/llvm/src/docs/Phabricator_premerge_results.png b/interpreter/llvm-project/llvm/docs/Phabricator_premerge_results.png similarity index 100% rename from interpreter/llvm/src/docs/Phabricator_premerge_results.png rename to interpreter/llvm-project/llvm/docs/Phabricator_premerge_results.png diff --git a/interpreter/llvm/src/docs/Phabricator_premerge_unit_tests.png b/interpreter/llvm-project/llvm/docs/Phabricator_premerge_unit_tests.png similarity index 100% rename from interpreter/llvm/src/docs/Phabricator_premerge_unit_tests.png rename to interpreter/llvm-project/llvm/docs/Phabricator_premerge_unit_tests.png diff --git a/interpreter/llvm/src/docs/ProgrammersManual.rst b/interpreter/llvm-project/llvm/docs/ProgrammersManual.rst similarity index 100% rename from interpreter/llvm/src/docs/ProgrammersManual.rst rename to interpreter/llvm-project/llvm/docs/ProgrammersManual.rst diff --git a/interpreter/llvm/src/docs/Projects.rst b/interpreter/llvm-project/llvm/docs/Projects.rst similarity index 100% rename from interpreter/llvm/src/docs/Projects.rst rename to interpreter/llvm-project/llvm/docs/Projects.rst diff --git a/interpreter/llvm/src/docs/Proposals/GitHubMove.rst b/interpreter/llvm-project/llvm/docs/Proposals/GitHubMove.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/GitHubMove.rst rename to interpreter/llvm-project/llvm/docs/Proposals/GitHubMove.rst diff --git a/interpreter/llvm/src/docs/Proposals/LLVMLibC.rst b/interpreter/llvm-project/llvm/docs/Proposals/LLVMLibC.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/LLVMLibC.rst rename to interpreter/llvm-project/llvm/docs/Proposals/LLVMLibC.rst diff --git a/interpreter/llvm/src/docs/Proposals/TestSuite.rst b/interpreter/llvm-project/llvm/docs/Proposals/TestSuite.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/TestSuite.rst rename to interpreter/llvm-project/llvm/docs/Proposals/TestSuite.rst diff --git a/interpreter/llvm/src/docs/Proposals/VariableNames.rst b/interpreter/llvm-project/llvm/docs/Proposals/VariableNames.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/VariableNames.rst rename to interpreter/llvm-project/llvm/docs/Proposals/VariableNames.rst diff --git a/interpreter/llvm/src/docs/Proposals/VectorPredication.rst b/interpreter/llvm-project/llvm/docs/Proposals/VectorPredication.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/VectorPredication.rst rename to interpreter/llvm-project/llvm/docs/Proposals/VectorPredication.rst diff --git a/interpreter/llvm/src/docs/Proposals/VectorizationPlan.rst b/interpreter/llvm-project/llvm/docs/Proposals/VectorizationPlan.rst similarity index 100% rename from interpreter/llvm/src/docs/Proposals/VectorizationPlan.rst rename to interpreter/llvm-project/llvm/docs/Proposals/VectorizationPlan.rst diff --git a/interpreter/llvm/src/docs/README.txt b/interpreter/llvm-project/llvm/docs/README.txt similarity index 100% rename from interpreter/llvm/src/docs/README.txt rename to interpreter/llvm-project/llvm/docs/README.txt diff --git a/interpreter/llvm/src/docs/Reference.rst b/interpreter/llvm-project/llvm/docs/Reference.rst similarity index 96% rename from interpreter/llvm/src/docs/Reference.rst rename to interpreter/llvm-project/llvm/docs/Reference.rst index 3afe43b35d518..662f1ec650fcf 100644 --- a/interpreter/llvm/src/docs/Reference.rst +++ b/interpreter/llvm-project/llvm/docs/Reference.rst @@ -1,212 +1,212 @@ -Reference -========= - -LLVM and API reference documentation. - -.. contents:: - :local: - -.. toctree:: - :hidden: - - Atomics - BitCodeFormat - BlockFrequencyTerminology - BranchWeightMetadata - Bugpoint - CommandGuide/index - Coroutines - DependenceGraphs/index - ExceptionHandling - Extensions - FaultMaps - FuzzingLLVM - GarbageCollection - GetElementPtr - GlobalISel/index - GwpAsan - HowToSetUpLLVMStyleRTTI - HowToUseAttributes - InAlloca - LangRef - LibFuzzer - MarkedUpDisassembly - MIRLangRef - OptBisect - PDB/index - ScudoHardenedAllocator - MemTagSanitizer - Security - SegmentedStacks - StackMaps - SpeculativeLoadHardening - Statepoints - SystemLibrary - TestingGuide - TransformMetadata - TypeMetadata - XRay - XRayExample - XRayFDRFormat - YamlIO - -API Reference -------------- - -`Doxygen generated documentation `_ - (`classes `_) - -:doc:`HowToUseAttributes` - Answers some questions about the new Attributes infrastructure. - -`Documentation for Go bindings `_ - -LLVM Reference --------------- - -====================== -Command Line Utilities -====================== - -:doc:`LLVM Command Guide ` - A reference manual for the LLVM command line utilities ("man" pages for LLVM - tools). - -:doc:`Bugpoint` - Automatic bug finder and test-case reducer description and usage - information. - -:doc:`OptBisect` - A command line option for debugging optimization-induced failures. - -:doc:`The Microsoft PDB File Format ` - A detailed description of the Microsoft PDB (Program Database) file format. - -================== -Garbage Collection -================== - -:doc:`GarbageCollection` - The interfaces source-language compilers should use for compiling GC'd - programs. - -:doc:`Statepoints` - This describes a set of experimental extensions for garbage - collection support. - -========= -LibFuzzer -========= - -:doc:`LibFuzzer` - A library for writing in-process guided fuzzers. - -:doc:`FuzzingLLVM` - Information on writing and using Fuzzers to find bugs in LLVM. - -======== -LLVM IR -======== - -:doc:`LLVM Language Reference Manual ` - Defines the LLVM intermediate representation and the assembly form of the - different nodes. - -:doc:`InAlloca` - Description of the ``inalloca`` argument attribute. - -:doc:`BitCodeFormat` - This describes the file format and encoding used for LLVM "bc" files. - -:doc:`Machine IR (MIR) Format Reference Manual ` - A reference manual for the MIR serialization format, which is used to test - LLVM's code generation passes. - -:doc:`GlobalISel/index` - This describes the prototype instruction selection replacement, GlobalISel. - -===================== -Testing and Debugging -===================== - -:doc:`LLVM Testing Infrastructure Guide ` - A reference manual for using the LLVM testing infrastructure. - -:doc:`TestSuiteGuide` - Describes how to compile and run the test-suite benchmarks. - - -:doc:`GwpAsan` - A sampled heap memory error detection toolkit designed for production use. - -==== -XRay -==== - -:doc:`XRay` - High-level documentation of how to use XRay in LLVM. - -:doc:`XRayExample` - An example of how to debug an application with XRay. - -================= -Additional Topics -================= - -:doc:`FaultMaps` - LLVM support for folding control flow into faulting machine instructions. - -:doc:`Atomics` - Information about LLVM's concurrency model. - -:doc:`ExceptionHandling` - This document describes the design and implementation of exception handling - in LLVM. - -:doc:`Extensions` - LLVM-specific extensions to tools and formats LLVM seeks compatibility with. - -:doc:`HowToSetUpLLVMStyleRTTI` - How to make ``isa<>``, ``dyn_cast<>``, etc. available for clients of your - class hierarchy. - -:doc:`BlockFrequencyTerminology` - Provides information about terminology used in the ``BlockFrequencyInfo`` - analysis pass. - -:doc:`BranchWeightMetadata` - Provides information about Branch Prediction Information. - -:doc:`GetElementPtr` - Answers to some very frequent questions about LLVM's most frequently - misunderstood instruction. - -:doc:`ScudoHardenedAllocator` - A library that implements a security-hardened `malloc()`. - -:doc:`MemTagSanitizer` - Security hardening for production code aiming to mitigate memory - related vulnerabilities. Based on the Armv8.5-A Memory Tagging Extension. - -:doc:`Dependence Graphs ` - A description of the design of the various dependence graphs such as - the DDG (Data Dependence Graph). - -:doc:`SpeculativeLoadHardening` - A description of the Speculative Load Hardening mitigation for Spectre v1. - -:doc:`SegmentedStacks` - This document describes segmented stacks and how they are used in LLVM. - -:doc:`MarkedUpDisassembly` - This document describes the optional rich disassembly output syntax. - -:doc:`StackMaps` - LLVM support for mapping instruction addresses to the location of - values and allowing code to be patched. - -:doc:`Coroutines` - LLVM support for coroutines. - -:doc:`YamlIO` - A reference guide for using LLVM's YAML I/O library. +Reference +========= + +LLVM and API reference documentation. + +.. contents:: + :local: + +.. toctree:: + :hidden: + + Atomics + BitCodeFormat + BlockFrequencyTerminology + BranchWeightMetadata + Bugpoint + CommandGuide/index + Coroutines + DependenceGraphs/index + ExceptionHandling + Extensions + FaultMaps + FuzzingLLVM + GarbageCollection + GetElementPtr + GlobalISel/index + GwpAsan + HowToSetUpLLVMStyleRTTI + HowToUseAttributes + InAlloca + LangRef + LibFuzzer + MarkedUpDisassembly + MIRLangRef + OptBisect + PDB/index + ScudoHardenedAllocator + MemTagSanitizer + Security + SegmentedStacks + StackMaps + SpeculativeLoadHardening + Statepoints + SystemLibrary + TestingGuide + TransformMetadata + TypeMetadata + XRay + XRayExample + XRayFDRFormat + YamlIO + +API Reference +------------- + +`Doxygen generated documentation `_ + (`classes `_) + +:doc:`HowToUseAttributes` + Answers some questions about the new Attributes infrastructure. + +`Documentation for Go bindings `_ + +LLVM Reference +-------------- + +====================== +Command Line Utilities +====================== + +:doc:`LLVM Command Guide ` + A reference manual for the LLVM command line utilities ("man" pages for LLVM + tools). + +:doc:`Bugpoint` + Automatic bug finder and test-case reducer description and usage + information. + +:doc:`OptBisect` + A command line option for debugging optimization-induced failures. + +:doc:`The Microsoft PDB File Format ` + A detailed description of the Microsoft PDB (Program Database) file format. + +================== +Garbage Collection +================== + +:doc:`GarbageCollection` + The interfaces source-language compilers should use for compiling GC'd + programs. + +:doc:`Statepoints` + This describes a set of experimental extensions for garbage + collection support. + +========= +LibFuzzer +========= + +:doc:`LibFuzzer` + A library for writing in-process guided fuzzers. + +:doc:`FuzzingLLVM` + Information on writing and using Fuzzers to find bugs in LLVM. + +======== +LLVM IR +======== + +:doc:`LLVM Language Reference Manual ` + Defines the LLVM intermediate representation and the assembly form of the + different nodes. + +:doc:`InAlloca` + Description of the ``inalloca`` argument attribute. + +:doc:`BitCodeFormat` + This describes the file format and encoding used for LLVM "bc" files. + +:doc:`Machine IR (MIR) Format Reference Manual ` + A reference manual for the MIR serialization format, which is used to test + LLVM's code generation passes. + +:doc:`GlobalISel/index` + This describes the prototype instruction selection replacement, GlobalISel. + +===================== +Testing and Debugging +===================== + +:doc:`LLVM Testing Infrastructure Guide ` + A reference manual for using the LLVM testing infrastructure. + +:doc:`TestSuiteGuide` + Describes how to compile and run the test-suite benchmarks. + + +:doc:`GwpAsan` + A sampled heap memory error detection toolkit designed for production use. + +==== +XRay +==== + +:doc:`XRay` + High-level documentation of how to use XRay in LLVM. + +:doc:`XRayExample` + An example of how to debug an application with XRay. + +================= +Additional Topics +================= + +:doc:`FaultMaps` + LLVM support for folding control flow into faulting machine instructions. + +:doc:`Atomics` + Information about LLVM's concurrency model. + +:doc:`ExceptionHandling` + This document describes the design and implementation of exception handling + in LLVM. + +:doc:`Extensions` + LLVM-specific extensions to tools and formats LLVM seeks compatibility with. + +:doc:`HowToSetUpLLVMStyleRTTI` + How to make ``isa<>``, ``dyn_cast<>``, etc. available for clients of your + class hierarchy. + +:doc:`BlockFrequencyTerminology` + Provides information about terminology used in the ``BlockFrequencyInfo`` + analysis pass. + +:doc:`BranchWeightMetadata` + Provides information about Branch Prediction Information. + +:doc:`GetElementPtr` + Answers to some very frequent questions about LLVM's most frequently + misunderstood instruction. + +:doc:`ScudoHardenedAllocator` + A library that implements a security-hardened `malloc()`. + +:doc:`MemTagSanitizer` + Security hardening for production code aiming to mitigate memory + related vulnerabilities. Based on the Armv8.5-A Memory Tagging Extension. + +:doc:`Dependence Graphs ` + A description of the design of the various dependence graphs such as + the DDG (Data Dependence Graph). + +:doc:`SpeculativeLoadHardening` + A description of the Speculative Load Hardening mitigation for Spectre v1. + +:doc:`SegmentedStacks` + This document describes segmented stacks and how they are used in LLVM. + +:doc:`MarkedUpDisassembly` + This document describes the optional rich disassembly output syntax. + +:doc:`StackMaps` + LLVM support for mapping instruction addresses to the location of + values and allowing code to be patched. + +:doc:`Coroutines` + LLVM support for coroutines. + +:doc:`YamlIO` + A reference guide for using LLVM's YAML I/O library. diff --git a/interpreter/llvm/src/docs/ReleaseNotes.rst b/interpreter/llvm-project/llvm/docs/ReleaseNotes.rst similarity index 100% rename from interpreter/llvm/src/docs/ReleaseNotes.rst rename to interpreter/llvm-project/llvm/docs/ReleaseNotes.rst diff --git a/interpreter/llvm/src/docs/ReleaseProcess.rst b/interpreter/llvm-project/llvm/docs/ReleaseProcess.rst similarity index 100% rename from interpreter/llvm/src/docs/ReleaseProcess.rst rename to interpreter/llvm-project/llvm/docs/ReleaseProcess.rst diff --git a/interpreter/llvm/src/docs/Remarks.rst b/interpreter/llvm-project/llvm/docs/Remarks.rst similarity index 100% rename from interpreter/llvm/src/docs/Remarks.rst rename to interpreter/llvm-project/llvm/docs/Remarks.rst diff --git a/interpreter/llvm/src/docs/ReportingGuide.rst b/interpreter/llvm-project/llvm/docs/ReportingGuide.rst similarity index 100% rename from interpreter/llvm/src/docs/ReportingGuide.rst rename to interpreter/llvm-project/llvm/docs/ReportingGuide.rst diff --git a/interpreter/llvm/src/docs/ScudoHardenedAllocator.rst b/interpreter/llvm-project/llvm/docs/ScudoHardenedAllocator.rst similarity index 100% rename from interpreter/llvm/src/docs/ScudoHardenedAllocator.rst rename to interpreter/llvm-project/llvm/docs/ScudoHardenedAllocator.rst diff --git a/interpreter/llvm/src/docs/Security.rst b/interpreter/llvm-project/llvm/docs/Security.rst similarity index 100% rename from interpreter/llvm/src/docs/Security.rst rename to interpreter/llvm-project/llvm/docs/Security.rst diff --git a/interpreter/llvm/src/docs/SegmentedStacks.rst b/interpreter/llvm-project/llvm/docs/SegmentedStacks.rst similarity index 100% rename from interpreter/llvm/src/docs/SegmentedStacks.rst rename to interpreter/llvm-project/llvm/docs/SegmentedStacks.rst diff --git a/interpreter/llvm/src/docs/SourceLevelDebugging.rst b/interpreter/llvm-project/llvm/docs/SourceLevelDebugging.rst similarity index 100% rename from interpreter/llvm/src/docs/SourceLevelDebugging.rst rename to interpreter/llvm-project/llvm/docs/SourceLevelDebugging.rst diff --git a/interpreter/llvm/src/docs/SpeculativeLoadHardening.md b/interpreter/llvm-project/llvm/docs/SpeculativeLoadHardening.md similarity index 100% rename from interpreter/llvm/src/docs/SpeculativeLoadHardening.md rename to interpreter/llvm-project/llvm/docs/SpeculativeLoadHardening.md diff --git a/interpreter/llvm/src/docs/SphinxQuickstartTemplate.rst b/interpreter/llvm-project/llvm/docs/SphinxQuickstartTemplate.rst similarity index 100% rename from interpreter/llvm/src/docs/SphinxQuickstartTemplate.rst rename to interpreter/llvm-project/llvm/docs/SphinxQuickstartTemplate.rst diff --git a/interpreter/llvm/src/docs/StackMaps.rst b/interpreter/llvm-project/llvm/docs/StackMaps.rst similarity index 100% rename from interpreter/llvm/src/docs/StackMaps.rst rename to interpreter/llvm-project/llvm/docs/StackMaps.rst diff --git a/interpreter/llvm/src/docs/StackSafetyAnalysis.rst b/interpreter/llvm-project/llvm/docs/StackSafetyAnalysis.rst similarity index 100% rename from interpreter/llvm/src/docs/StackSafetyAnalysis.rst rename to interpreter/llvm-project/llvm/docs/StackSafetyAnalysis.rst diff --git a/interpreter/llvm/src/docs/Statepoints.rst b/interpreter/llvm-project/llvm/docs/Statepoints.rst similarity index 100% rename from interpreter/llvm/src/docs/Statepoints.rst rename to interpreter/llvm-project/llvm/docs/Statepoints.rst diff --git a/interpreter/llvm/src/docs/SupportLibrary.rst b/interpreter/llvm-project/llvm/docs/SupportLibrary.rst similarity index 100% rename from interpreter/llvm/src/docs/SupportLibrary.rst rename to interpreter/llvm-project/llvm/docs/SupportLibrary.rst diff --git a/interpreter/llvm/src/docs/SupportPolicy.rst b/interpreter/llvm-project/llvm/docs/SupportPolicy.rst similarity index 100% rename from interpreter/llvm/src/docs/SupportPolicy.rst rename to interpreter/llvm-project/llvm/docs/SupportPolicy.rst diff --git a/interpreter/llvm/src/docs/SystemLibrary.rst b/interpreter/llvm-project/llvm/docs/SystemLibrary.rst similarity index 100% rename from interpreter/llvm/src/docs/SystemLibrary.rst rename to interpreter/llvm-project/llvm/docs/SystemLibrary.rst diff --git a/interpreter/llvm/src/docs/TableGen/BackEnds.rst b/interpreter/llvm-project/llvm/docs/TableGen/BackEnds.rst similarity index 100% rename from interpreter/llvm/src/docs/TableGen/BackEnds.rst rename to interpreter/llvm-project/llvm/docs/TableGen/BackEnds.rst diff --git a/interpreter/llvm/src/docs/TableGen/BackGuide.rst b/interpreter/llvm-project/llvm/docs/TableGen/BackGuide.rst similarity index 100% rename from interpreter/llvm/src/docs/TableGen/BackGuide.rst rename to interpreter/llvm-project/llvm/docs/TableGen/BackGuide.rst diff --git a/interpreter/llvm/src/docs/TableGen/ProgRef.rst b/interpreter/llvm-project/llvm/docs/TableGen/ProgRef.rst similarity index 100% rename from interpreter/llvm/src/docs/TableGen/ProgRef.rst rename to interpreter/llvm-project/llvm/docs/TableGen/ProgRef.rst diff --git a/interpreter/llvm/src/docs/TableGen/index.rst b/interpreter/llvm-project/llvm/docs/TableGen/index.rst similarity index 100% rename from interpreter/llvm/src/docs/TableGen/index.rst rename to interpreter/llvm-project/llvm/docs/TableGen/index.rst diff --git a/interpreter/llvm/src/docs/TableGenFundamentals.rst b/interpreter/llvm-project/llvm/docs/TableGenFundamentals.rst similarity index 100% rename from interpreter/llvm/src/docs/TableGenFundamentals.rst rename to interpreter/llvm-project/llvm/docs/TableGenFundamentals.rst diff --git a/interpreter/llvm/src/docs/TestSuiteGuide.md b/interpreter/llvm-project/llvm/docs/TestSuiteGuide.md similarity index 100% rename from interpreter/llvm/src/docs/TestSuiteGuide.md rename to interpreter/llvm-project/llvm/docs/TestSuiteGuide.md diff --git a/interpreter/llvm/src/docs/TestSuiteMakefileGuide.rst b/interpreter/llvm-project/llvm/docs/TestSuiteMakefileGuide.rst similarity index 100% rename from interpreter/llvm/src/docs/TestSuiteMakefileGuide.rst rename to interpreter/llvm-project/llvm/docs/TestSuiteMakefileGuide.rst diff --git a/interpreter/llvm/src/docs/TestingGuide.rst b/interpreter/llvm-project/llvm/docs/TestingGuide.rst similarity index 100% rename from interpreter/llvm/src/docs/TestingGuide.rst rename to interpreter/llvm-project/llvm/docs/TestingGuide.rst diff --git a/interpreter/llvm/src/docs/TransformMetadata.rst b/interpreter/llvm-project/llvm/docs/TransformMetadata.rst similarity index 100% rename from interpreter/llvm/src/docs/TransformMetadata.rst rename to interpreter/llvm-project/llvm/docs/TransformMetadata.rst diff --git a/interpreter/llvm/src/docs/TypeMetadata.rst b/interpreter/llvm-project/llvm/docs/TypeMetadata.rst similarity index 100% rename from interpreter/llvm/src/docs/TypeMetadata.rst rename to interpreter/llvm-project/llvm/docs/TypeMetadata.rst diff --git a/interpreter/llvm/src/docs/UserGuides.rst b/interpreter/llvm-project/llvm/docs/UserGuides.rst similarity index 96% rename from interpreter/llvm/src/docs/UserGuides.rst rename to interpreter/llvm-project/llvm/docs/UserGuides.rst index eb6e17c7bf9bd..43f52c3ce758f 100644 --- a/interpreter/llvm/src/docs/UserGuides.rst +++ b/interpreter/llvm-project/llvm/docs/UserGuides.rst @@ -1,224 +1,224 @@ -User Guides -=========== - -NOTE: If you are a user who is only interested in using an LLVM-based compiler, -you should look into `Clang `_ instead. The -documentation here is intended for users who have a need to work with the -intermediate LLVM representation. - -.. contents:: - :local: - -.. toctree:: - :hidden: - - AddingConstrainedIntrinsics - AdvancedBuilds - AliasAnalysis - AMDGPUUsage - Benchmarking - BigEndianNEON - BuildingADistribution - CFIVerify - CMake - CMakePrimer - CodeGenerator - CodeOfConduct - CommandLine - CompileCudaWithLLVM - CoverageMappingFormat - DebuggingJITedCode - Docker - ExtendingLLVM - GoldPlugin - HowToBuildOnARM - HowToBuildWithPGO - HowToBuildWindowsItaniumPrograms - HowToCrossCompileBuiltinsOnArm - HowToCrossCompileLLVM - HowToUpdateDebugInfo - LinkTimeOptimization - LoopTerminology - MarkdownQuickstartTemplate - MemorySSA - MergeFunctions - MCJITDesignAndImplementation - ORCv2 - OpaquePointers - JITLink - NewPassManager - NVPTXUsage - Phabricator - Passes - ReportingGuide - Remarks - SourceLevelDebugging - StackSafetyAnalysis - SupportLibrary - TableGen/index - TableGenFundamentals - Vectorizers - WritingAnLLVMPass - WritingAnLLVMNewPMPass - WritingAnLLVMBackend - yaml2obj - -Clang ------ - -:doc:`HowToBuildOnARM` - Notes on building and testing LLVM/Clang on ARM. - -:doc:`HowToBuildWithPGO` - Notes on building LLVM/Clang with PGO. - -:doc:`HowToCrossCompileLLVM` - Notes on cross-building and testing LLVM/Clang. - -`How to build the C, C++, ObjC, and ObjC++ front end`__ - Instructions for building the clang front-end from source. - - .. __: https://clang.llvm.org/get_started.html - -:doc:`CoverageMappingFormat` - This describes the format and encoding used for LLVM’s code coverage mapping. - -:doc:`CFIVerify` - A description of the verification tool for Control Flow Integrity. - -LLVM Builds and Distributions ------------------------------ - -:doc:`BuildingADistribution` - A best-practices guide for using LLVM's CMake build system to package and - distribute LLVM-based tools. - -:doc:`CMake` - An addendum to the main Getting Started guide for those using the `CMake - build system `_. - -:doc:`Docker` - A reference for using Dockerfiles provided with LLVM. - -:doc:`Support Library ` - This document describes the LLVM Support Library (``lib/Support``) and - how to keep LLVM source code portable. - -:doc:`AdvancedBuilds` - This document describes more advanced build configurations. - -Optimizations -------------- - -:doc:`WritingAnLLVMPass` - Information on how to write LLVM transformations and analyses. - -:doc:`WritingAnLLVMNewPMPass` - Information on how to write LLVM transformations under the new pass - manager. - -:doc:`Passes` - A list of optimizations and analyses implemented in LLVM. - -:doc:`StackSafetyAnalysis` - This document describes the design of the stack safety analysis of local - variables. - -:doc:`MergeFunctions` - Describes functions merging optimization. - -:doc:`AliasAnalysis` - Information on how to write a new alias analysis implementation or how to - use existing analyses. - -:doc:`MemorySSA` - Information about the MemorySSA utility in LLVM, as well as how to use it. - -:doc:`LoopTerminology` - A document describing Loops and associated terms as used in LLVM. - -:doc:`Vectorizers` - This document describes the current status of vectorization in LLVM. - -:doc:`LinkTimeOptimization` - This document describes the interface between LLVM intermodular optimizer - and the linker and its design - -:doc:`GoldPlugin` - How to build your programs with link-time optimization on Linux. - -:doc:`Remarks` - A reference on the implementation of remarks in LLVM. - -:doc:`Source Level Debugging with LLVM ` - This document describes the design and philosophy behind the LLVM - source-level debugger. - -Code Generation ---------------- - -:doc:`WritingAnLLVMBackend` - Information on how to write LLVM backends for machine targets. - -:doc:`CodeGenerator` - The design and implementation of the LLVM code generator. Useful if you are - working on retargetting LLVM to a new architecture, designing a new codegen - pass, or enhancing existing components. - -:doc:`TableGen ` - Describes the TableGen tool, which is used heavily by the LLVM code - generator. - -=== -JIT -=== - -:doc:`MCJITDesignAndImplementation` - Describes the inner workings of MCJIT execution engine. - -:doc:`ORCv2` - Describes the design and implementation of the ORC APIs, including some - usage examples, and a guide for users transitioning from ORCv1 to ORCv2. - -:doc:`JITLink` - Describes the design and APIs for the JITLink library, ORC's new JIT - linker. - -:doc:`DebuggingJITedCode` - How to debug JITed code with GDB. - -Additional Topics ------------------ - -:doc:`CommandLine` - Provides information on using the command line parsing library. - -:doc:`ExtendingLLVM` - Look here to see how to add instructions and intrinsics to LLVM. - -:doc:`AddingConstrainedIntrinsics` - Gives the steps necessary when adding a new constrained math intrinsic - to LLVM. - -:doc:`HowToBuildWindowsItaniumPrograms` - Notes on assembling a Windows Itanium enviroment. - -:doc:`HowToCrossCompileBuiltinsOnArm` - Notes on cross-building and testing the compiler-rt builtins for Arm. - -:doc:`BigEndianNEON` - LLVM's support for generating NEON instructions on big endian ARM targets is - somewhat nonintuitive. This document explains the implementation and rationale. - -:doc:`CompileCudaWithLLVM` - LLVM support for CUDA. - -:doc:`NVPTXUsage` - This document describes using the NVPTX backend to compile GPU kernels. - -:doc:`AMDGPUUsage` - This document describes using the AMDGPU backend to compile GPU kernels. - -:doc:`AMDGPUDwarfExtensionsForHeterogeneousDebugging` - This document describes DWARF extensions to support heterogeneous debugging - for targets such as the AMDGPU backend. +User Guides +=========== + +NOTE: If you are a user who is only interested in using an LLVM-based compiler, +you should look into `Clang `_ instead. The +documentation here is intended for users who have a need to work with the +intermediate LLVM representation. + +.. contents:: + :local: + +.. toctree:: + :hidden: + + AddingConstrainedIntrinsics + AdvancedBuilds + AliasAnalysis + AMDGPUUsage + Benchmarking + BigEndianNEON + BuildingADistribution + CFIVerify + CMake + CMakePrimer + CodeGenerator + CodeOfConduct + CommandLine + CompileCudaWithLLVM + CoverageMappingFormat + DebuggingJITedCode + Docker + ExtendingLLVM + GoldPlugin + HowToBuildOnARM + HowToBuildWithPGO + HowToBuildWindowsItaniumPrograms + HowToCrossCompileBuiltinsOnArm + HowToCrossCompileLLVM + HowToUpdateDebugInfo + LinkTimeOptimization + LoopTerminology + MarkdownQuickstartTemplate + MemorySSA + MergeFunctions + MCJITDesignAndImplementation + ORCv2 + OpaquePointers + JITLink + NewPassManager + NVPTXUsage + Phabricator + Passes + ReportingGuide + Remarks + SourceLevelDebugging + StackSafetyAnalysis + SupportLibrary + TableGen/index + TableGenFundamentals + Vectorizers + WritingAnLLVMPass + WritingAnLLVMNewPMPass + WritingAnLLVMBackend + yaml2obj + +Clang +----- + +:doc:`HowToBuildOnARM` + Notes on building and testing LLVM/Clang on ARM. + +:doc:`HowToBuildWithPGO` + Notes on building LLVM/Clang with PGO. + +:doc:`HowToCrossCompileLLVM` + Notes on cross-building and testing LLVM/Clang. + +`How to build the C, C++, ObjC, and ObjC++ front end`__ + Instructions for building the clang front-end from source. + + .. __: https://clang.llvm.org/get_started.html + +:doc:`CoverageMappingFormat` + This describes the format and encoding used for LLVM’s code coverage mapping. + +:doc:`CFIVerify` + A description of the verification tool for Control Flow Integrity. + +LLVM Builds and Distributions +----------------------------- + +:doc:`BuildingADistribution` + A best-practices guide for using LLVM's CMake build system to package and + distribute LLVM-based tools. + +:doc:`CMake` + An addendum to the main Getting Started guide for those using the `CMake + build system `_. + +:doc:`Docker` + A reference for using Dockerfiles provided with LLVM. + +:doc:`Support Library ` + This document describes the LLVM Support Library (``lib/Support``) and + how to keep LLVM source code portable. + +:doc:`AdvancedBuilds` + This document describes more advanced build configurations. + +Optimizations +------------- + +:doc:`WritingAnLLVMPass` + Information on how to write LLVM transformations and analyses. + +:doc:`WritingAnLLVMNewPMPass` + Information on how to write LLVM transformations under the new pass + manager. + +:doc:`Passes` + A list of optimizations and analyses implemented in LLVM. + +:doc:`StackSafetyAnalysis` + This document describes the design of the stack safety analysis of local + variables. + +:doc:`MergeFunctions` + Describes functions merging optimization. + +:doc:`AliasAnalysis` + Information on how to write a new alias analysis implementation or how to + use existing analyses. + +:doc:`MemorySSA` + Information about the MemorySSA utility in LLVM, as well as how to use it. + +:doc:`LoopTerminology` + A document describing Loops and associated terms as used in LLVM. + +:doc:`Vectorizers` + This document describes the current status of vectorization in LLVM. + +:doc:`LinkTimeOptimization` + This document describes the interface between LLVM intermodular optimizer + and the linker and its design + +:doc:`GoldPlugin` + How to build your programs with link-time optimization on Linux. + +:doc:`Remarks` + A reference on the implementation of remarks in LLVM. + +:doc:`Source Level Debugging with LLVM ` + This document describes the design and philosophy behind the LLVM + source-level debugger. + +Code Generation +--------------- + +:doc:`WritingAnLLVMBackend` + Information on how to write LLVM backends for machine targets. + +:doc:`CodeGenerator` + The design and implementation of the LLVM code generator. Useful if you are + working on retargetting LLVM to a new architecture, designing a new codegen + pass, or enhancing existing components. + +:doc:`TableGen ` + Describes the TableGen tool, which is used heavily by the LLVM code + generator. + +=== +JIT +=== + +:doc:`MCJITDesignAndImplementation` + Describes the inner workings of MCJIT execution engine. + +:doc:`ORCv2` + Describes the design and implementation of the ORC APIs, including some + usage examples, and a guide for users transitioning from ORCv1 to ORCv2. + +:doc:`JITLink` + Describes the design and APIs for the JITLink library, ORC's new JIT + linker. + +:doc:`DebuggingJITedCode` + How to debug JITed code with GDB. + +Additional Topics +----------------- + +:doc:`CommandLine` + Provides information on using the command line parsing library. + +:doc:`ExtendingLLVM` + Look here to see how to add instructions and intrinsics to LLVM. + +:doc:`AddingConstrainedIntrinsics` + Gives the steps necessary when adding a new constrained math intrinsic + to LLVM. + +:doc:`HowToBuildWindowsItaniumPrograms` + Notes on assembling a Windows Itanium enviroment. + +:doc:`HowToCrossCompileBuiltinsOnArm` + Notes on cross-building and testing the compiler-rt builtins for Arm. + +:doc:`BigEndianNEON` + LLVM's support for generating NEON instructions on big endian ARM targets is + somewhat nonintuitive. This document explains the implementation and rationale. + +:doc:`CompileCudaWithLLVM` + LLVM support for CUDA. + +:doc:`NVPTXUsage` + This document describes using the NVPTX backend to compile GPU kernels. + +:doc:`AMDGPUUsage` + This document describes using the AMDGPU backend to compile GPU kernels. + +:doc:`AMDGPUDwarfExtensionsForHeterogeneousDebugging` + This document describes DWARF extensions to support heterogeneous debugging + for targets such as the AMDGPU backend. diff --git a/interpreter/llvm/src/docs/Vectorizers.rst b/interpreter/llvm-project/llvm/docs/Vectorizers.rst similarity index 100% rename from interpreter/llvm/src/docs/Vectorizers.rst rename to interpreter/llvm-project/llvm/docs/Vectorizers.rst diff --git a/interpreter/llvm/src/docs/WritingAnLLVMBackend.rst b/interpreter/llvm-project/llvm/docs/WritingAnLLVMBackend.rst similarity index 100% rename from interpreter/llvm/src/docs/WritingAnLLVMBackend.rst rename to interpreter/llvm-project/llvm/docs/WritingAnLLVMBackend.rst diff --git a/interpreter/llvm/src/docs/WritingAnLLVMNewPMPass.rst b/interpreter/llvm-project/llvm/docs/WritingAnLLVMNewPMPass.rst similarity index 100% rename from interpreter/llvm/src/docs/WritingAnLLVMNewPMPass.rst rename to interpreter/llvm-project/llvm/docs/WritingAnLLVMNewPMPass.rst diff --git a/interpreter/llvm/src/docs/WritingAnLLVMPass.rst b/interpreter/llvm-project/llvm/docs/WritingAnLLVMPass.rst similarity index 100% rename from interpreter/llvm/src/docs/WritingAnLLVMPass.rst rename to interpreter/llvm-project/llvm/docs/WritingAnLLVMPass.rst diff --git a/interpreter/llvm/src/docs/XRay.rst b/interpreter/llvm-project/llvm/docs/XRay.rst similarity index 100% rename from interpreter/llvm/src/docs/XRay.rst rename to interpreter/llvm-project/llvm/docs/XRay.rst diff --git a/interpreter/llvm/src/docs/XRayExample.rst b/interpreter/llvm-project/llvm/docs/XRayExample.rst similarity index 100% rename from interpreter/llvm/src/docs/XRayExample.rst rename to interpreter/llvm-project/llvm/docs/XRayExample.rst diff --git a/interpreter/llvm/src/docs/XRayFDRFormat.rst b/interpreter/llvm-project/llvm/docs/XRayFDRFormat.rst similarity index 100% rename from interpreter/llvm/src/docs/XRayFDRFormat.rst rename to interpreter/llvm-project/llvm/docs/XRayFDRFormat.rst diff --git a/interpreter/llvm/src/docs/YamlIO.rst b/interpreter/llvm-project/llvm/docs/YamlIO.rst similarity index 100% rename from interpreter/llvm/src/docs/YamlIO.rst rename to interpreter/llvm-project/llvm/docs/YamlIO.rst diff --git a/interpreter/llvm/src/docs/_ocamldoc/style.css b/interpreter/llvm-project/llvm/docs/_ocamldoc/style.css similarity index 100% rename from interpreter/llvm/src/docs/_ocamldoc/style.css rename to interpreter/llvm-project/llvm/docs/_ocamldoc/style.css diff --git a/interpreter/llvm/src/docs/_static/lines.gif b/interpreter/llvm-project/llvm/docs/_static/lines.gif similarity index 100% rename from interpreter/llvm/src/docs/_static/lines.gif rename to interpreter/llvm-project/llvm/docs/_static/lines.gif diff --git a/interpreter/llvm/src/docs/_static/llvm.css b/interpreter/llvm-project/llvm/docs/_static/llvm.css similarity index 100% rename from interpreter/llvm/src/docs/_static/llvm.css rename to interpreter/llvm-project/llvm/docs/_static/llvm.css diff --git a/interpreter/llvm/src/docs/_templates/indexsidebar.html b/interpreter/llvm-project/llvm/docs/_templates/indexsidebar.html similarity index 100% rename from interpreter/llvm/src/docs/_templates/indexsidebar.html rename to interpreter/llvm-project/llvm/docs/_templates/indexsidebar.html diff --git a/interpreter/llvm/src/docs/_templates/layout.html b/interpreter/llvm-project/llvm/docs/_templates/layout.html similarity index 100% rename from interpreter/llvm/src/docs/_templates/layout.html rename to interpreter/llvm-project/llvm/docs/_templates/layout.html diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/layout.html b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/layout.html similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/layout.html rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/layout.html diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/static/contents.png b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/contents.png similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/static/contents.png rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/contents.png diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/static/llvm-theme.css b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/llvm-theme.css similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/static/llvm-theme.css rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/llvm-theme.css diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/static/logo.png b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/logo.png similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/static/logo.png rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/logo.png diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/static/navigation.png b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/navigation.png similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/static/navigation.png rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/static/navigation.png diff --git a/interpreter/llvm/src/docs/_themes/llvm-theme/theme.conf b/interpreter/llvm-project/llvm/docs/_themes/llvm-theme/theme.conf similarity index 100% rename from interpreter/llvm/src/docs/_themes/llvm-theme/theme.conf rename to interpreter/llvm-project/llvm/docs/_themes/llvm-theme/theme.conf diff --git a/interpreter/llvm/src/docs/buildbot_worker_contact.png b/interpreter/llvm-project/llvm/docs/buildbot_worker_contact.png similarity index 100% rename from interpreter/llvm/src/docs/buildbot_worker_contact.png rename to interpreter/llvm-project/llvm/docs/buildbot_worker_contact.png diff --git a/interpreter/llvm/src/docs/conf.py b/interpreter/llvm-project/llvm/docs/conf.py similarity index 100% rename from interpreter/llvm/src/docs/conf.py rename to interpreter/llvm-project/llvm/docs/conf.py diff --git a/interpreter/llvm/src/docs/doxygen-mainpage.dox b/interpreter/llvm-project/llvm/docs/doxygen-mainpage.dox similarity index 100% rename from interpreter/llvm/src/docs/doxygen-mainpage.dox rename to interpreter/llvm-project/llvm/docs/doxygen-mainpage.dox diff --git a/interpreter/llvm/src/docs/doxygen.cfg.in b/interpreter/llvm-project/llvm/docs/doxygen.cfg.in similarity index 100% rename from interpreter/llvm/src/docs/doxygen.cfg.in rename to interpreter/llvm-project/llvm/docs/doxygen.cfg.in diff --git a/interpreter/llvm/src/docs/epilogue-vectorization-cfg.png b/interpreter/llvm-project/llvm/docs/epilogue-vectorization-cfg.png similarity index 100% rename from interpreter/llvm/src/docs/epilogue-vectorization-cfg.png rename to interpreter/llvm-project/llvm/docs/epilogue-vectorization-cfg.png diff --git a/interpreter/llvm/src/docs/gcc-loops.png b/interpreter/llvm-project/llvm/docs/gcc-loops.png similarity index 100% rename from interpreter/llvm/src/docs/gcc-loops.png rename to interpreter/llvm-project/llvm/docs/gcc-loops.png diff --git a/interpreter/llvm/src/docs/index.rst b/interpreter/llvm-project/llvm/docs/index.rst similarity index 100% rename from interpreter/llvm/src/docs/index.rst rename to interpreter/llvm-project/llvm/docs/index.rst diff --git a/interpreter/llvm/src/docs/linpack-pc.png b/interpreter/llvm-project/llvm/docs/linpack-pc.png similarity index 100% rename from interpreter/llvm/src/docs/linpack-pc.png rename to interpreter/llvm-project/llvm/docs/linpack-pc.png diff --git a/interpreter/llvm/src/docs/llvm-objdump.1 b/interpreter/llvm-project/llvm/docs/llvm-objdump.1 similarity index 100% rename from interpreter/llvm/src/docs/llvm-objdump.1 rename to interpreter/llvm-project/llvm/docs/llvm-objdump.1 diff --git a/interpreter/llvm/src/docs/loop-guard.svg b/interpreter/llvm-project/llvm/docs/loop-guard.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-guard.svg rename to interpreter/llvm-project/llvm/docs/loop-guard.svg diff --git a/interpreter/llvm/src/docs/loop-irreducible.svg b/interpreter/llvm-project/llvm/docs/loop-irreducible.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-irreducible.svg rename to interpreter/llvm-project/llvm/docs/loop-irreducible.svg diff --git a/interpreter/llvm/src/docs/loop-merge.svg b/interpreter/llvm-project/llvm/docs/loop-merge.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-merge.svg rename to interpreter/llvm-project/llvm/docs/loop-merge.svg diff --git a/interpreter/llvm/src/docs/loop-nested.svg b/interpreter/llvm-project/llvm/docs/loop-nested.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-nested.svg rename to interpreter/llvm-project/llvm/docs/loop-nested.svg diff --git a/interpreter/llvm/src/docs/loop-nonmaximal.svg b/interpreter/llvm-project/llvm/docs/loop-nonmaximal.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-nonmaximal.svg rename to interpreter/llvm-project/llvm/docs/loop-nonmaximal.svg diff --git a/interpreter/llvm/src/docs/loop-separate.svg b/interpreter/llvm-project/llvm/docs/loop-separate.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-separate.svg rename to interpreter/llvm-project/llvm/docs/loop-separate.svg diff --git a/interpreter/llvm/src/docs/loop-single.svg b/interpreter/llvm-project/llvm/docs/loop-single.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-single.svg rename to interpreter/llvm-project/llvm/docs/loop-single.svg diff --git a/interpreter/llvm/src/docs/loop-terminology-guarded-loop.png b/interpreter/llvm-project/llvm/docs/loop-terminology-guarded-loop.png similarity index 100% rename from interpreter/llvm/src/docs/loop-terminology-guarded-loop.png rename to interpreter/llvm-project/llvm/docs/loop-terminology-guarded-loop.png diff --git a/interpreter/llvm/src/docs/loop-terminology-initial-loop.png b/interpreter/llvm-project/llvm/docs/loop-terminology-initial-loop.png similarity index 100% rename from interpreter/llvm/src/docs/loop-terminology-initial-loop.png rename to interpreter/llvm-project/llvm/docs/loop-terminology-initial-loop.png diff --git a/interpreter/llvm/src/docs/loop-terminology-rotated-loop.png b/interpreter/llvm-project/llvm/docs/loop-terminology-rotated-loop.png similarity index 100% rename from interpreter/llvm/src/docs/loop-terminology-rotated-loop.png rename to interpreter/llvm-project/llvm/docs/loop-terminology-rotated-loop.png diff --git a/interpreter/llvm/src/docs/loop-terminology.svg b/interpreter/llvm-project/llvm/docs/loop-terminology.svg similarity index 100% rename from interpreter/llvm/src/docs/loop-terminology.svg rename to interpreter/llvm-project/llvm/docs/loop-terminology.svg diff --git a/interpreter/llvm/src/docs/make.bat b/interpreter/llvm-project/llvm/docs/make.bat similarity index 100% rename from interpreter/llvm/src/docs/make.bat rename to interpreter/llvm-project/llvm/docs/make.bat diff --git a/interpreter/llvm/src/docs/re_format.7 b/interpreter/llvm-project/llvm/docs/re_format.7 similarity index 100% rename from interpreter/llvm/src/docs/re_format.7 rename to interpreter/llvm-project/llvm/docs/re_format.7 diff --git a/interpreter/llvm/src/docs/speculative_load_hardening_microbenchmarks.png b/interpreter/llvm-project/llvm/docs/speculative_load_hardening_microbenchmarks.png similarity index 100% rename from interpreter/llvm/src/docs/speculative_load_hardening_microbenchmarks.png rename to interpreter/llvm-project/llvm/docs/speculative_load_hardening_microbenchmarks.png diff --git a/interpreter/llvm/src/docs/tutorial/BuildingAJIT1.rst b/interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT1.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/BuildingAJIT1.rst rename to interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT1.rst diff --git a/interpreter/llvm/src/docs/tutorial/BuildingAJIT2.rst b/interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT2.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/BuildingAJIT2.rst rename to interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT2.rst diff --git a/interpreter/llvm/src/docs/tutorial/BuildingAJIT3.rst b/interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT3.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/BuildingAJIT3.rst rename to interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT3.rst diff --git a/interpreter/llvm/src/docs/tutorial/BuildingAJIT4.rst b/interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT4.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/BuildingAJIT4.rst rename to interpreter/llvm-project/llvm/docs/tutorial/BuildingAJIT4.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl01.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl01.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl01.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl01.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl02.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl02.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl02.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl02.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl03.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl03.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl03.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl03.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl04.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl04.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl04.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl04.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl05.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl05.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl05.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl05.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl06.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl06.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl06.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl06.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl07.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl07.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl07.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl07.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl08.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl08.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl08.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl08.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl09.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl09.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl09.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl09.rst diff --git a/interpreter/llvm/src/docs/tutorial/LangImpl10.rst b/interpreter/llvm-project/llvm/docs/tutorial/LangImpl10.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/LangImpl10.rst rename to interpreter/llvm-project/llvm/docs/tutorial/LangImpl10.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl01.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl01.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl01.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl01.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl05-cfg.png b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl05-cfg.png similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl05-cfg.png rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl05-cfg.png diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl05.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl05.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl05.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl05.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl06.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl06.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl06.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl06.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl07.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl07.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl07.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl07.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl09.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl09.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl09.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl09.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl10.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl10.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/LangImpl10.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl10.rst diff --git a/interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/index.rst b/interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/index.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/MyFirstLanguageFrontend/index.rst rename to interpreter/llvm-project/llvm/docs/tutorial/MyFirstLanguageFrontend/index.rst diff --git a/interpreter/llvm/src/docs/tutorial/index.rst b/interpreter/llvm-project/llvm/docs/tutorial/index.rst similarity index 100% rename from interpreter/llvm/src/docs/tutorial/index.rst rename to interpreter/llvm-project/llvm/docs/tutorial/index.rst diff --git a/interpreter/llvm/src/docs/yaml2obj.rst b/interpreter/llvm-project/llvm/docs/yaml2obj.rst similarity index 100% rename from interpreter/llvm/src/docs/yaml2obj.rst rename to interpreter/llvm-project/llvm/docs/yaml2obj.rst diff --git a/interpreter/llvm/src/examples/BrainF/BrainF.cpp b/interpreter/llvm-project/llvm/examples/BrainF/BrainF.cpp similarity index 100% rename from interpreter/llvm/src/examples/BrainF/BrainF.cpp rename to interpreter/llvm-project/llvm/examples/BrainF/BrainF.cpp diff --git a/interpreter/llvm/src/examples/BrainF/BrainF.h b/interpreter/llvm-project/llvm/examples/BrainF/BrainF.h similarity index 100% rename from interpreter/llvm/src/examples/BrainF/BrainF.h rename to interpreter/llvm-project/llvm/examples/BrainF/BrainF.h diff --git a/interpreter/llvm/src/examples/BrainF/BrainFDriver.cpp b/interpreter/llvm-project/llvm/examples/BrainF/BrainFDriver.cpp similarity index 100% rename from interpreter/llvm/src/examples/BrainF/BrainFDriver.cpp rename to interpreter/llvm-project/llvm/examples/BrainF/BrainFDriver.cpp diff --git a/interpreter/llvm/src/examples/BrainF/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/BrainF/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/BrainF/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/BrainF/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Bye/Bye.cpp b/interpreter/llvm-project/llvm/examples/Bye/Bye.cpp similarity index 100% rename from interpreter/llvm/src/examples/Bye/Bye.cpp rename to interpreter/llvm-project/llvm/examples/Bye/Bye.cpp diff --git a/interpreter/llvm/src/examples/Bye/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Bye/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Bye/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Bye/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/ExceptionDemo/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/ExceptionDemo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/ExceptionDemo/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/ExceptionDemo/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/ExceptionDemo/ExceptionDemo.cpp b/interpreter/llvm-project/llvm/examples/ExceptionDemo/ExceptionDemo.cpp similarity index 100% rename from interpreter/llvm/src/examples/ExceptionDemo/ExceptionDemo.cpp rename to interpreter/llvm-project/llvm/examples/ExceptionDemo/ExceptionDemo.cpp diff --git a/interpreter/llvm/src/examples/Fibonacci/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Fibonacci/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Fibonacci/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Fibonacci/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Fibonacci/fibonacci.cpp b/interpreter/llvm-project/llvm/examples/Fibonacci/fibonacci.cpp similarity index 100% rename from interpreter/llvm/src/examples/Fibonacci/fibonacci.cpp rename to interpreter/llvm-project/llvm/examples/Fibonacci/fibonacci.cpp diff --git a/interpreter/llvm/src/examples/HowToUseJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/HowToUseJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/HowToUseJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/HowToUseJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/HowToUseJIT/HowToUseJIT.cpp b/interpreter/llvm-project/llvm/examples/HowToUseJIT/HowToUseJIT.cpp similarity index 100% rename from interpreter/llvm/src/examples/HowToUseJIT/HowToUseJIT.cpp rename to interpreter/llvm-project/llvm/examples/HowToUseJIT/HowToUseJIT.cpp diff --git a/interpreter/llvm/src/examples/HowToUseLLJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/HowToUseLLJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/HowToUseLLJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/HowToUseLLJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/HowToUseLLJIT/HowToUseLLJIT.cpp b/interpreter/llvm-project/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp similarity index 100% rename from interpreter/llvm/src/examples/HowToUseLLJIT/HowToUseLLJIT.cpp rename to interpreter/llvm-project/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp diff --git a/interpreter/llvm/src/examples/IRTransforms/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/IRTransforms/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/IRTransforms/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/IRTransforms/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/IRTransforms/InitializePasses.cpp b/interpreter/llvm-project/llvm/examples/IRTransforms/InitializePasses.cpp similarity index 100% rename from interpreter/llvm/src/examples/IRTransforms/InitializePasses.cpp rename to interpreter/llvm-project/llvm/examples/IRTransforms/InitializePasses.cpp diff --git a/interpreter/llvm/src/examples/IRTransforms/InitializePasses.h b/interpreter/llvm-project/llvm/examples/IRTransforms/InitializePasses.h similarity index 100% rename from interpreter/llvm/src/examples/IRTransforms/InitializePasses.h rename to interpreter/llvm-project/llvm/examples/IRTransforms/InitializePasses.h diff --git a/interpreter/llvm/src/examples/IRTransforms/SimplifyCFG.cpp b/interpreter/llvm-project/llvm/examples/IRTransforms/SimplifyCFG.cpp similarity index 100% rename from interpreter/llvm/src/examples/IRTransforms/SimplifyCFG.cpp rename to interpreter/llvm-project/llvm/examples/IRTransforms/SimplifyCFG.cpp diff --git a/interpreter/llvm/src/examples/IRTransforms/SimplifyCFG.h b/interpreter/llvm-project/llvm/examples/IRTransforms/SimplifyCFG.h similarity index 100% rename from interpreter/llvm/src/examples/IRTransforms/SimplifyCFG.h rename to interpreter/llvm-project/llvm/examples/IRTransforms/SimplifyCFG.h diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/KaleidoscopeJIT.h b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/KaleidoscopeJIT.h similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/KaleidoscopeJIT.h rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/KaleidoscopeJIT.h diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/KaleidoscopeJIT.h b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/KaleidoscopeJIT.h similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/KaleidoscopeJIT.h rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/KaleidoscopeJIT.h diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/KaleidoscopeJIT.h b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/KaleidoscopeJIT.h similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/KaleidoscopeJIT.h rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/KaleidoscopeJIT.h diff --git a/interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter2/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter2/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter2/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter2/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter2/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter2/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter2/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter2/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter3/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter3/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter3/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter3/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter3/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter3/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter3/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter3/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter4/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter4/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter4/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter4/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter4/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter4/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter4/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter4/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter5/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter5/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter5/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter5/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter5/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter5/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter5/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter5/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter6/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter6/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter6/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter6/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter6/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter6/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter6/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter6/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter7/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter7/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter7/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter7/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter7/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter7/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter7/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter7/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter8/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter8/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter8/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter8/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter8/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter8/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter8/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter8/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter9/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter9/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter9/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter9/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/Chapter9/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter9/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/Chapter9/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/Chapter9/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/README.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/README.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/README.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/README.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/README.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/README.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/README.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/README.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/genk-timing.py b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/genk-timing.py rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/split-lib.py b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/split-lib.py similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/split-lib.py rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/split-lib.py diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/cached/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/README.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/README.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/README.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/README.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/genk-timing.py b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/genk-timing.py rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/split-lib.py b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/split-lib.py similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/split-lib.py rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/split-lib.py diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/complete/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/complete/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/initial/README.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/initial/README.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/initial/README.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/initial/README.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/initial/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/initial/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/initial/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/initial/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/README.txt b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/README.txt similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/README.txt rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/README.txt diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/toy.cpp b/interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/toy.cpp similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/toy.cpp rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/MCJIT/lazy/toy.cpp diff --git a/interpreter/llvm/src/examples/Kaleidoscope/include/KaleidoscopeJIT.h b/interpreter/llvm-project/llvm/examples/Kaleidoscope/include/KaleidoscopeJIT.h similarity index 100% rename from interpreter/llvm/src/examples/Kaleidoscope/include/KaleidoscopeJIT.h rename to interpreter/llvm-project/llvm/examples/Kaleidoscope/include/KaleidoscopeJIT.h diff --git a/interpreter/llvm/src/examples/ModuleMaker/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/ModuleMaker/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/ModuleMaker/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/ModuleMaker/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/ModuleMaker/ModuleMaker.cpp b/interpreter/llvm-project/llvm/examples/ModuleMaker/ModuleMaker.cpp similarity index 100% rename from interpreter/llvm/src/examples/ModuleMaker/ModuleMaker.cpp rename to interpreter/llvm-project/llvm/examples/ModuleMaker/ModuleMaker.cpp diff --git a/interpreter/llvm/src/examples/ModuleMaker/README.txt b/interpreter/llvm-project/llvm/examples/ModuleMaker/README.txt similarity index 100% rename from interpreter/llvm/src/examples/ModuleMaker/README.txt rename to interpreter/llvm-project/llvm/examples/ModuleMaker/README.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/ExampleModules.h b/interpreter/llvm-project/llvm/examples/OrcV2Examples/ExampleModules.h similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/ExampleModules.h rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/ExampleModules.h diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITDumpObjects/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITDumpObjects/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITDumpObjects/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITDumpObjects/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/LLJITWithGDBRegistrationListener.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/LLJITWithGDBRegistrationListener.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/LLJITWithGDBRegistrationListener.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/LLJITWithGDBRegistrationListener.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithInitializers/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithInitializers/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithInitializers/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithInitializers/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithInitializers/LLJITWithInitializers.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithInitializers/LLJITWithInitializers.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithInitializers/LLJITWithInitializers.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithInitializers/LLJITWithInitializers.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithLazyReexports/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithLazyReexports/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithLazyReexports/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithLazyReexports/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithLazyReexports/LLJITWithLazyReexports.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithLazyReexports/LLJITWithLazyReexports.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithLazyReexports/LLJITWithLazyReexports.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithLazyReexports/LLJITWithLazyReexports.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectCache/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectCache/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectCache/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectCache/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectCache/LLJITWithObjectCache.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectCache/LLJITWithObjectCache.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectCache/LLJITWithObjectCache.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectCache/LLJITWithObjectCache.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/LLJITWithObjectLinkingLayerPlugin.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/LLJITWithObjectLinkingLayerPlugin.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/LLJITWithObjectLinkingLayerPlugin.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/LLJITWithObjectLinkingLayerPlugin.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/LLJITWithOptimizingIRTransform.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/LLJITWithOptimizingIRTransform.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/LLJITWithOptimizingIRTransform.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/LLJITWithOptimizingIRTransform.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/LLJITWithRemoteDebugging.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/LLJITWithRemoteDebugging.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/LLJITWithRemoteDebugging.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/LLJITWithRemoteDebugging.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.h b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.h similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.h rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/RemoteJITUtils.h diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithTargetProcessControl/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithTargetProcessControl/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithTargetProcessControl/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithTargetProcessControl/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithTargetProcessControl/LLJITWithTargetProcessControl.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithTargetProcessControl/LLJITWithTargetProcessControl.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithTargetProcessControl/LLJITWithTargetProcessControl.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithTargetProcessControl/LLJITWithTargetProcessControl.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithThinLTOSummaries/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithThinLTOSummaries/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp b/interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/OrcV2CBindingsAddObjectFile.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/OrcV2CBindingsAddObjectFile.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/OrcV2CBindingsAddObjectFile.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsAddObjectFile/OrcV2CBindingsAddObjectFile.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/OrcV2CBindingsBasicUsage.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/OrcV2CBindingsBasicUsage.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/OrcV2CBindingsBasicUsage.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsBasicUsage/OrcV2CBindingsBasicUsage.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/OrcV2CBindingsDumpObjects.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/OrcV2CBindingsDumpObjects.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/OrcV2CBindingsDumpObjects.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsDumpObjects/OrcV2CBindingsDumpObjects.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsLazy/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsLazy/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsLazy/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsLazy/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsLazy/OrcV2CBindingsLazy.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsLazy/OrcV2CBindingsLazy.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsLazy/OrcV2CBindingsLazy.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsLazy/OrcV2CBindingsLazy.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/OrcV2CBindingsReflectProcessSymbols.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/OrcV2CBindingsReflectProcessSymbols.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/OrcV2CBindingsReflectProcessSymbols.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsReflectProcessSymbols/OrcV2CBindingsReflectProcessSymbols.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/OrcV2CBindingsRemovableCode.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/OrcV2CBindingsRemovableCode.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/OrcV2CBindingsRemovableCode.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsRemovableCode/OrcV2CBindingsRemovableCode.c diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/OrcV2CBindingsVeryLazy.c b/interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/OrcV2CBindingsVeryLazy.c similarity index 100% rename from interpreter/llvm/src/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/OrcV2CBindingsVeryLazy.c rename to interpreter/llvm-project/llvm/examples/OrcV2Examples/OrcV2CBindingsVeryLazy/OrcV2CBindingsVeryLazy.c diff --git a/interpreter/llvm/src/examples/ParallelJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/ParallelJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/ParallelJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/ParallelJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/ParallelJIT/ParallelJIT.cpp b/interpreter/llvm-project/llvm/examples/ParallelJIT/ParallelJIT.cpp similarity index 100% rename from interpreter/llvm/src/examples/ParallelJIT/ParallelJIT.cpp rename to interpreter/llvm-project/llvm/examples/ParallelJIT/ParallelJIT.cpp diff --git a/interpreter/llvm/src/examples/SpeculativeJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/examples/SpeculativeJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/examples/SpeculativeJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/examples/SpeculativeJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/examples/SpeculativeJIT/SpeculativeJIT.cpp b/interpreter/llvm-project/llvm/examples/SpeculativeJIT/SpeculativeJIT.cpp similarity index 100% rename from interpreter/llvm/src/examples/SpeculativeJIT/SpeculativeJIT.cpp rename to interpreter/llvm-project/llvm/examples/SpeculativeJIT/SpeculativeJIT.cpp diff --git a/interpreter/llvm/src/include/llvm-c/Analysis.h b/interpreter/llvm-project/llvm/include/llvm-c/Analysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Analysis.h rename to interpreter/llvm-project/llvm/include/llvm-c/Analysis.h diff --git a/interpreter/llvm/src/include/llvm-c/BitReader.h b/interpreter/llvm-project/llvm/include/llvm-c/BitReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/BitReader.h rename to interpreter/llvm-project/llvm/include/llvm-c/BitReader.h diff --git a/interpreter/llvm/src/include/llvm-c/BitWriter.h b/interpreter/llvm-project/llvm/include/llvm-c/BitWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/BitWriter.h rename to interpreter/llvm-project/llvm/include/llvm-c/BitWriter.h diff --git a/interpreter/llvm/src/include/llvm-c/Comdat.h b/interpreter/llvm-project/llvm/include/llvm-c/Comdat.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Comdat.h rename to interpreter/llvm-project/llvm/include/llvm-c/Comdat.h diff --git a/interpreter/llvm/src/include/llvm-c/Core.h b/interpreter/llvm-project/llvm/include/llvm-c/Core.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Core.h rename to interpreter/llvm-project/llvm/include/llvm-c/Core.h diff --git a/interpreter/llvm/src/include/llvm-c/DataTypes.h b/interpreter/llvm-project/llvm/include/llvm-c/DataTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/DataTypes.h rename to interpreter/llvm-project/llvm/include/llvm-c/DataTypes.h diff --git a/interpreter/llvm/src/include/llvm-c/DebugInfo.h b/interpreter/llvm-project/llvm/include/llvm-c/DebugInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/DebugInfo.h rename to interpreter/llvm-project/llvm/include/llvm-c/DebugInfo.h diff --git a/interpreter/llvm/src/include/llvm-c/Disassembler.h b/interpreter/llvm-project/llvm/include/llvm-c/Disassembler.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Disassembler.h rename to interpreter/llvm-project/llvm/include/llvm-c/Disassembler.h diff --git a/interpreter/llvm/src/include/llvm-c/DisassemblerTypes.h b/interpreter/llvm-project/llvm/include/llvm-c/DisassemblerTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/DisassemblerTypes.h rename to interpreter/llvm-project/llvm/include/llvm-c/DisassemblerTypes.h diff --git a/interpreter/llvm/src/include/llvm-c/Error.h b/interpreter/llvm-project/llvm/include/llvm-c/Error.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Error.h rename to interpreter/llvm-project/llvm/include/llvm-c/Error.h diff --git a/interpreter/llvm/src/include/llvm-c/ErrorHandling.h b/interpreter/llvm-project/llvm/include/llvm-c/ErrorHandling.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/ErrorHandling.h rename to interpreter/llvm-project/llvm/include/llvm-c/ErrorHandling.h diff --git a/interpreter/llvm/src/include/llvm-c/ExecutionEngine.h b/interpreter/llvm-project/llvm/include/llvm-c/ExecutionEngine.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/ExecutionEngine.h rename to interpreter/llvm-project/llvm/include/llvm-c/ExecutionEngine.h diff --git a/interpreter/llvm/src/include/llvm-c/ExternC.h b/interpreter/llvm-project/llvm/include/llvm-c/ExternC.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/ExternC.h rename to interpreter/llvm-project/llvm/include/llvm-c/ExternC.h diff --git a/interpreter/llvm/src/include/llvm-c/IRReader.h b/interpreter/llvm-project/llvm/include/llvm-c/IRReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/IRReader.h rename to interpreter/llvm-project/llvm/include/llvm-c/IRReader.h diff --git a/interpreter/llvm/src/include/llvm-c/Initialization.h b/interpreter/llvm-project/llvm/include/llvm-c/Initialization.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Initialization.h rename to interpreter/llvm-project/llvm/include/llvm-c/Initialization.h diff --git a/interpreter/llvm/src/include/llvm-c/LLJIT.h b/interpreter/llvm-project/llvm/include/llvm-c/LLJIT.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/LLJIT.h rename to interpreter/llvm-project/llvm/include/llvm-c/LLJIT.h diff --git a/interpreter/llvm/src/include/llvm-c/Linker.h b/interpreter/llvm-project/llvm/include/llvm-c/Linker.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Linker.h rename to interpreter/llvm-project/llvm/include/llvm-c/Linker.h diff --git a/interpreter/llvm/src/include/llvm-c/Object.h b/interpreter/llvm-project/llvm/include/llvm-c/Object.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Object.h rename to interpreter/llvm-project/llvm/include/llvm-c/Object.h diff --git a/interpreter/llvm/src/include/llvm-c/Orc.h b/interpreter/llvm-project/llvm/include/llvm-c/Orc.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Orc.h rename to interpreter/llvm-project/llvm/include/llvm-c/Orc.h diff --git a/interpreter/llvm/src/include/llvm-c/OrcEE.h b/interpreter/llvm-project/llvm/include/llvm-c/OrcEE.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/OrcEE.h rename to interpreter/llvm-project/llvm/include/llvm-c/OrcEE.h diff --git a/interpreter/llvm/src/include/llvm-c/Remarks.h b/interpreter/llvm-project/llvm/include/llvm-c/Remarks.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Remarks.h rename to interpreter/llvm-project/llvm/include/llvm-c/Remarks.h diff --git a/interpreter/llvm/src/include/llvm-c/Support.h b/interpreter/llvm-project/llvm/include/llvm-c/Support.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Support.h rename to interpreter/llvm-project/llvm/include/llvm-c/Support.h diff --git a/interpreter/llvm/src/include/llvm-c/Target.h b/interpreter/llvm-project/llvm/include/llvm-c/Target.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Target.h rename to interpreter/llvm-project/llvm/include/llvm-c/Target.h diff --git a/interpreter/llvm/src/include/llvm-c/TargetMachine.h b/interpreter/llvm-project/llvm/include/llvm-c/TargetMachine.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/TargetMachine.h rename to interpreter/llvm-project/llvm/include/llvm-c/TargetMachine.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/AggressiveInstCombine.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/AggressiveInstCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/AggressiveInstCombine.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/AggressiveInstCombine.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/Coroutines.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/Coroutines.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/Coroutines.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/Coroutines.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/IPO.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/IPO.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/IPO.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/IPO.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/InstCombine.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/InstCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/InstCombine.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/InstCombine.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/PassBuilder.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/PassBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/PassBuilder.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/PassBuilder.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/PassManagerBuilder.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/PassManagerBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/PassManagerBuilder.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/PassManagerBuilder.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/Scalar.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/Scalar.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/Scalar.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/Scalar.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/Utils.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/Utils.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/Utils.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/Utils.h diff --git a/interpreter/llvm/src/include/llvm-c/Transforms/Vectorize.h b/interpreter/llvm-project/llvm/include/llvm-c/Transforms/Vectorize.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Transforms/Vectorize.h rename to interpreter/llvm-project/llvm/include/llvm-c/Transforms/Vectorize.h diff --git a/interpreter/llvm/src/include/llvm-c/Types.h b/interpreter/llvm-project/llvm/include/llvm-c/Types.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/Types.h rename to interpreter/llvm-project/llvm/include/llvm-c/Types.h diff --git a/interpreter/llvm/src/include/llvm-c/lto.h b/interpreter/llvm-project/llvm/include/llvm-c/lto.h similarity index 100% rename from interpreter/llvm/src/include/llvm-c/lto.h rename to interpreter/llvm-project/llvm/include/llvm-c/lto.h diff --git a/interpreter/llvm/src/include/llvm-c/module.modulemap b/interpreter/llvm-project/llvm/include/llvm-c/module.modulemap similarity index 100% rename from interpreter/llvm/src/include/llvm-c/module.modulemap rename to interpreter/llvm-project/llvm/include/llvm-c/module.modulemap diff --git a/interpreter/llvm/src/include/llvm/ADT/APFixedPoint.h b/interpreter/llvm-project/llvm/include/llvm/ADT/APFixedPoint.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/APFixedPoint.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/APFixedPoint.h diff --git a/interpreter/llvm/src/include/llvm/ADT/APFloat.h b/interpreter/llvm-project/llvm/include/llvm/ADT/APFloat.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/APFloat.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/APFloat.h diff --git a/interpreter/llvm/src/include/llvm/ADT/APInt.h b/interpreter/llvm-project/llvm/include/llvm/ADT/APInt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/APInt.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/APInt.h diff --git a/interpreter/llvm/src/include/llvm/ADT/APSInt.h b/interpreter/llvm-project/llvm/include/llvm/ADT/APSInt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/APSInt.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/APSInt.h diff --git a/interpreter/llvm/src/include/llvm/ADT/AllocatorList.h b/interpreter/llvm-project/llvm/include/llvm/ADT/AllocatorList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/AllocatorList.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/AllocatorList.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Any.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Any.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Any.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Any.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ArrayRef.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ArrayRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ArrayRef.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ArrayRef.h diff --git a/interpreter/llvm/src/include/llvm/ADT/BitVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/BitVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/BitVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/BitVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Bitfields.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Bitfields.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Bitfields.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Bitfields.h diff --git a/interpreter/llvm/src/include/llvm/ADT/BitmaskEnum.h b/interpreter/llvm-project/llvm/include/llvm/ADT/BitmaskEnum.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/BitmaskEnum.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/BitmaskEnum.h diff --git a/interpreter/llvm/src/include/llvm/ADT/BreadthFirstIterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/BreadthFirstIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/BreadthFirstIterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/BreadthFirstIterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/CachedHashString.h b/interpreter/llvm-project/llvm/include/llvm/ADT/CachedHashString.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/CachedHashString.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/CachedHashString.h diff --git a/interpreter/llvm/src/include/llvm/ADT/CoalescingBitVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/CoalescingBitVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/CoalescingBitVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/CoalescingBitVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DAGDeltaAlgorithm.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DAGDeltaAlgorithm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DAGDeltaAlgorithm.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DAGDeltaAlgorithm.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DeltaAlgorithm.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DeltaAlgorithm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DeltaAlgorithm.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DeltaAlgorithm.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DenseMap.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DenseMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DenseMap.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DenseMap.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DenseMapInfo.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DenseMapInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DenseMapInfo.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DenseMapInfo.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DenseSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DenseSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DenseSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DenseSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DepthFirstIterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DepthFirstIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DepthFirstIterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DepthFirstIterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/DirectedGraph.h b/interpreter/llvm-project/llvm/include/llvm/ADT/DirectedGraph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/DirectedGraph.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/DirectedGraph.h diff --git a/interpreter/llvm/src/include/llvm/ADT/EnumeratedArray.h b/interpreter/llvm-project/llvm/include/llvm/ADT/EnumeratedArray.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/EnumeratedArray.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/EnumeratedArray.h diff --git a/interpreter/llvm/src/include/llvm/ADT/EpochTracker.h b/interpreter/llvm-project/llvm/include/llvm/ADT/EpochTracker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/EpochTracker.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/EpochTracker.h diff --git a/interpreter/llvm/src/include/llvm/ADT/EquivalenceClasses.h b/interpreter/llvm-project/llvm/include/llvm/ADT/EquivalenceClasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/EquivalenceClasses.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/EquivalenceClasses.h diff --git a/interpreter/llvm/src/include/llvm/ADT/FloatingPointMode.h b/interpreter/llvm-project/llvm/include/llvm/ADT/FloatingPointMode.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/FloatingPointMode.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/FloatingPointMode.h diff --git a/interpreter/llvm/src/include/llvm/ADT/FoldingSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/FoldingSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/FoldingSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/FoldingSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/FunctionExtras.h b/interpreter/llvm-project/llvm/include/llvm/ADT/FunctionExtras.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/FunctionExtras.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/FunctionExtras.h diff --git a/interpreter/llvm/src/include/llvm/ADT/GraphTraits.h b/interpreter/llvm-project/llvm/include/llvm/ADT/GraphTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/GraphTraits.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/GraphTraits.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Hashing.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Hashing.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Hashing.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Hashing.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ImmutableList.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ImmutableList.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableList.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ImmutableMap.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ImmutableMap.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableMap.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ImmutableSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ImmutableSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ImmutableSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/IndexedMap.h b/interpreter/llvm-project/llvm/include/llvm/ADT/IndexedMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/IndexedMap.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/IndexedMap.h diff --git a/interpreter/llvm/src/include/llvm/ADT/IntEqClasses.h b/interpreter/llvm-project/llvm/include/llvm/ADT/IntEqClasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/IntEqClasses.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/IntEqClasses.h diff --git a/interpreter/llvm/src/include/llvm/ADT/IntervalMap.h b/interpreter/llvm-project/llvm/include/llvm/ADT/IntervalMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/IntervalMap.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/IntervalMap.h diff --git a/interpreter/llvm/src/include/llvm/ADT/IntrusiveRefCntPtr.h b/interpreter/llvm-project/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/IntrusiveRefCntPtr.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h diff --git a/interpreter/llvm/src/include/llvm/ADT/MapVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/MapVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/MapVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/MapVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/None.h b/interpreter/llvm-project/llvm/include/llvm/ADT/None.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/None.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/None.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Optional.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Optional.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Optional.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Optional.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PackedVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PackedVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PackedVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PackedVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PointerEmbeddedInt.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PointerEmbeddedInt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PointerEmbeddedInt.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PointerEmbeddedInt.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PointerIntPair.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PointerIntPair.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PointerIntPair.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PointerIntPair.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PointerSumType.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PointerSumType.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PointerSumType.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PointerSumType.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PointerUnion.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PointerUnion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PointerUnion.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PointerUnion.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PostOrderIterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PostOrderIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PostOrderIterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PostOrderIterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PriorityQueue.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PriorityQueue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PriorityQueue.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PriorityQueue.h diff --git a/interpreter/llvm/src/include/llvm/ADT/PriorityWorklist.h b/interpreter/llvm-project/llvm/include/llvm/ADT/PriorityWorklist.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/PriorityWorklist.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/PriorityWorklist.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SCCIterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SCCIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SCCIterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SCCIterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/STLExtras.h b/interpreter/llvm-project/llvm/include/llvm/ADT/STLExtras.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/STLExtras.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/STLExtras.h diff --git a/interpreter/llvm/src/include/llvm/ADT/STLForwardCompat.h b/interpreter/llvm-project/llvm/include/llvm/ADT/STLForwardCompat.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/STLForwardCompat.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/STLForwardCompat.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ScopeExit.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ScopeExit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ScopeExit.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ScopeExit.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ScopedHashTable.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ScopedHashTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ScopedHashTable.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ScopedHashTable.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Sequence.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Sequence.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Sequence.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Sequence.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SetOperations.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SetOperations.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SetOperations.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SetOperations.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SetVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SetVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SetVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SetVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SmallBitVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SmallBitVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SmallBitVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SmallBitVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SmallPtrSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SmallPtrSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SmallPtrSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SmallPtrSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SmallSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SmallSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SmallSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SmallSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SmallString.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SmallString.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SmallString.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SmallString.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SmallVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SmallVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SmallVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SmallVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SparseBitVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SparseBitVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SparseBitVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SparseBitVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SparseMultiSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SparseMultiSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SparseMultiSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SparseMultiSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/SparseSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/SparseSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/SparseSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/SparseSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Statistic.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Statistic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Statistic.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Statistic.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringExtras.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringExtras.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringExtras.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringExtras.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringMap.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringMap.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringMap.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringMapEntry.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringMapEntry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringMapEntry.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringMapEntry.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringRef.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringRef.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringRef.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringSet.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringSet.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringSet.h diff --git a/interpreter/llvm/src/include/llvm/ADT/StringSwitch.h b/interpreter/llvm-project/llvm/include/llvm/ADT/StringSwitch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/StringSwitch.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/StringSwitch.h diff --git a/interpreter/llvm/src/include/llvm/ADT/TinyPtrVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/TinyPtrVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/TinyPtrVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/TinyPtrVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Triple.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Triple.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Triple.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Triple.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Twine.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Twine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Twine.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Twine.h diff --git a/interpreter/llvm/src/include/llvm/ADT/TypeSwitch.h b/interpreter/llvm-project/llvm/include/llvm/ADT/TypeSwitch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/TypeSwitch.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/TypeSwitch.h diff --git a/interpreter/llvm/src/include/llvm/ADT/UniqueVector.h b/interpreter/llvm-project/llvm/include/llvm/ADT/UniqueVector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/UniqueVector.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/UniqueVector.h diff --git a/interpreter/llvm/src/include/llvm/ADT/Waymarking.h b/interpreter/llvm-project/llvm/include/llvm/ADT/Waymarking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/Waymarking.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/Waymarking.h diff --git a/interpreter/llvm/src/include/llvm/ADT/bit.h b/interpreter/llvm-project/llvm/include/llvm/ADT/bit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/bit.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/bit.h diff --git a/interpreter/llvm/src/include/llvm/ADT/edit_distance.h b/interpreter/llvm-project/llvm/include/llvm/ADT/edit_distance.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/edit_distance.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/edit_distance.h diff --git a/interpreter/llvm/src/include/llvm/ADT/fallible_iterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/fallible_iterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/fallible_iterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/fallible_iterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist_base.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist_base.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist_base.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist_base.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist_iterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist_iterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist_iterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist_iterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist_node.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist_node.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist_node_base.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node_base.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist_node_base.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node_base.h diff --git a/interpreter/llvm/src/include/llvm/ADT/ilist_node_options.h b/interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node_options.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/ilist_node_options.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/ilist_node_options.h diff --git a/interpreter/llvm/src/include/llvm/ADT/iterator.h b/interpreter/llvm-project/llvm/include/llvm/ADT/iterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/iterator.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/iterator.h diff --git a/interpreter/llvm/src/include/llvm/ADT/iterator_range.h b/interpreter/llvm-project/llvm/include/llvm/ADT/iterator_range.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/iterator_range.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/iterator_range.h diff --git a/interpreter/llvm/src/include/llvm/ADT/simple_ilist.h b/interpreter/llvm-project/llvm/include/llvm/ADT/simple_ilist.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ADT/simple_ilist.h rename to interpreter/llvm-project/llvm/include/llvm/ADT/simple_ilist.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/AliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/AliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/AliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/AliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/AliasAnalysisEvaluator.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/AliasAnalysisEvaluator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/AliasAnalysisEvaluator.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/AliasAnalysisEvaluator.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/AliasSetTracker.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/AliasSetTracker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/AliasSetTracker.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/AliasSetTracker.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/AssumeBundleQueries.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/AssumeBundleQueries.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/AssumeBundleQueries.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/AssumeBundleQueries.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/AssumptionCache.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/AssumptionCache.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/AssumptionCache.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/AssumptionCache.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/BasicAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/BasicAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/BasicAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/BasicAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/BlockFrequencyInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/BlockFrequencyInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/BlockFrequencyInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/BlockFrequencyInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/BlockFrequencyInfoImpl.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/BlockFrequencyInfoImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/BranchProbabilityInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/BranchProbabilityInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/BranchProbabilityInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/BranchProbabilityInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CFG.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CFG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CFG.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CFG.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CFGPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CFGPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CFGPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CFGPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CFLAliasAnalysisUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CFLAliasAnalysisUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CFLAliasAnalysisUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CFLAliasAnalysisUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CFLAndersAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CFLAndersAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CFLAndersAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CFLAndersAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CFLSteensAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CFLSteensAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CFLSteensAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CFLSteensAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CGSCCPassManager.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CGSCCPassManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CGSCCPassManager.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CGSCCPassManager.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CallGraph.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CallGraph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CallGraph.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CallGraph.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CallGraphSCCPass.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CallGraphSCCPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CallGraphSCCPass.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CallGraphSCCPass.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CallPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CallPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CallPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CallPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CaptureTracking.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CaptureTracking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CaptureTracking.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CaptureTracking.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CmpInstAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CmpInstAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CmpInstAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CmpInstAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/CodeMetrics.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/CodeMetrics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/CodeMetrics.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/CodeMetrics.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ConstantFolding.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ConstantFolding.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ConstantFolding.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ConstantFolding.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ConstraintSystem.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ConstraintSystem.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ConstraintSystem.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ConstraintSystem.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DDG.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DDG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DDG.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DDG.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DDGPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DDGPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DDGPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DDGPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DOTGraphTraitsPass.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DOTGraphTraitsPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DOTGraphTraitsPass.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DOTGraphTraitsPass.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Delinearization.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Delinearization.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Delinearization.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Delinearization.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DemandedBits.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DemandedBits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DemandedBits.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DemandedBits.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DependenceAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DependenceAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DependenceAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DependenceAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DependenceGraphBuilder.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DependenceGraphBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DependenceGraphBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DependenceGraphBuilder.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DivergenceAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DivergenceAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DivergenceAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DivergenceAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DomPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DomPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DomPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DomPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DomTreeUpdater.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DomTreeUpdater.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DomTreeUpdater.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DomTreeUpdater.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DominanceFrontier.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DominanceFrontier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DominanceFrontier.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DominanceFrontier.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/DominanceFrontierImpl.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/DominanceFrontierImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/DominanceFrontierImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/DominanceFrontierImpl.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/EHPersonalities.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/EHPersonalities.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/EHPersonalities.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/EHPersonalities.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/FunctionPropertiesAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/FunctionPropertiesAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/FunctionPropertiesAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/FunctionPropertiesAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/GlobalsModRef.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/GlobalsModRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/GlobalsModRef.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/GlobalsModRef.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/GuardUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/GuardUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/GuardUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/GuardUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/HeatUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/HeatUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/HeatUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/HeatUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IRSimilarityIdentifier.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IRSimilarityIdentifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IRSimilarityIdentifier.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IRSimilarityIdentifier.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IVDescriptors.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IVDescriptors.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IVDescriptors.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IVDescriptors.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IVUsers.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IVUsers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IVUsers.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IVUsers.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IndirectCallPromotionAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IndirectCallPromotionAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IndirectCallPromotionAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IndirectCallPromotionAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IndirectCallVisitor.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IndirectCallVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IndirectCallVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IndirectCallVisitor.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InlineAdvisor.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InlineAdvisor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InlineAdvisor.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InlineAdvisor.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InlineCost.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InlineCost.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InlineCost.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InlineCost.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InlineModelFeatureMaps.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InlineModelFeatureMaps.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InlineModelFeatureMaps.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InlineModelFeatureMaps.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InstCount.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InstCount.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InstCount.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InstCount.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InstructionPrecedenceTracking.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InstructionPrecedenceTracking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InstructionPrecedenceTracking.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InstructionPrecedenceTracking.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/InstructionSimplify.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/InstructionSimplify.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/InstructionSimplify.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/InstructionSimplify.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Interval.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Interval.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Interval.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Interval.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IntervalIterator.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IntervalIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IntervalIterator.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IntervalIterator.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IntervalPartition.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IntervalPartition.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IntervalPartition.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IntervalPartition.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/IteratedDominanceFrontier.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/IteratedDominanceFrontier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/IteratedDominanceFrontier.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/IteratedDominanceFrontier.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LazyBlockFrequencyInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LazyBlockFrequencyInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LazyBlockFrequencyInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LazyBlockFrequencyInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LazyBranchProbabilityInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LazyBranchProbabilityInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LazyBranchProbabilityInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LazyBranchProbabilityInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LazyCallGraph.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LazyCallGraph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LazyCallGraph.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LazyCallGraph.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LazyValueInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LazyValueInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LazyValueInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LazyValueInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LegacyDivergenceAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LegacyDivergenceAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LegacyDivergenceAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LegacyDivergenceAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Lint.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Lint.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Lint.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Lint.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Loads.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Loads.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Loads.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Loads.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopAccessAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopAccessAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopAccessAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopAccessAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopAnalysisManager.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopAnalysisManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopAnalysisManager.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopAnalysisManager.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopCacheAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopCacheAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopCacheAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopCacheAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopInfoImpl.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopInfoImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopInfoImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopInfoImpl.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopIterator.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopIterator.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopIterator.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopNestAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopNestAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopNestAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopNestAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopPass.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopPass.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopPass.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/LoopUnrollAnalyzer.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/LoopUnrollAnalyzer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/LoopUnrollAnalyzer.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/LoopUnrollAnalyzer.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MLInlineAdvisor.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MLInlineAdvisor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MLInlineAdvisor.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MLInlineAdvisor.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MLModelRunner.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MLModelRunner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MLModelRunner.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MLModelRunner.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemDerefPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemDerefPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemDerefPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemDerefPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemoryBuiltins.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryBuiltins.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemoryBuiltins.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryBuiltins.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemoryDependenceAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemoryDependenceAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemoryLocation.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryLocation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemoryLocation.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemoryLocation.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemorySSA.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemorySSA.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemorySSA.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemorySSA.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MemorySSAUpdater.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MemorySSAUpdater.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MemorySSAUpdater.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MemorySSAUpdater.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ModuleDebugInfoPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ModuleDebugInfoPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ModuleDebugInfoPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ModuleDebugInfoPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ModuleSummaryAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ModuleSummaryAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ModuleSummaryAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/MustExecute.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/MustExecute.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/MustExecute.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/MustExecute.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ObjCARCAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ObjCARCAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ObjCARCAnalysisUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCAnalysisUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ObjCARCAnalysisUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCAnalysisUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ObjCARCInstKind.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCInstKind.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ObjCARCInstKind.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCInstKind.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ObjCARCUtil.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCUtil.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ObjCARCUtil.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ObjCARCUtil.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/OptimizationRemarkEmitter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/OptimizationRemarkEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/OptimizationRemarkEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/OptimizationRemarkEmitter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/OverflowInstAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/OverflowInstAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/OverflowInstAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/OverflowInstAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/PHITransAddr.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/PHITransAddr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/PHITransAddr.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/PHITransAddr.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Passes.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Passes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Passes.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Passes.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/PhiValues.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/PhiValues.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/PhiValues.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/PhiValues.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/PostDominators.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/PostDominators.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/PostDominators.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/PostDominators.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ProfileSummaryInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ProfileSummaryInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ProfileSummaryInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ProfileSummaryInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/PtrUseVisitor.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/PtrUseVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/PtrUseVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/PtrUseVisitor.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/RegionInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/RegionInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/RegionInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/RegionInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/RegionInfoImpl.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/RegionInfoImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/RegionInfoImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/RegionInfoImpl.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/RegionIterator.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/RegionIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/RegionIterator.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/RegionIterator.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/RegionPass.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/RegionPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/RegionPass.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/RegionPass.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/RegionPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/RegionPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/RegionPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/RegionPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ReplayInlineAdvisor.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ReplayInlineAdvisor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ReplayInlineAdvisor.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ReplayInlineAdvisor.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScalarEvolution.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolution.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScalarEvolution.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolution.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionDivision.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionDivision.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionDivision.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionDivision.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionExpressions.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionExpressions.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionNormalization.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionNormalization.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScalarEvolutionNormalization.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScalarEvolutionNormalization.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ScopedNoAliasAA.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ScopedNoAliasAA.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ScopedNoAliasAA.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ScopedNoAliasAA.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/SparsePropagation.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/SparsePropagation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/SparsePropagation.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/SparsePropagation.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/StackLifetime.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/StackLifetime.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/StackLifetime.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/StackLifetime.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/StackSafetyAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/StackSafetyAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/StackSafetyAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/StackSafetyAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/SyncDependenceAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/SyncDependenceAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/SyncDependenceAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/SyncDependenceAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/SyntheticCountsUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/SyntheticCountsUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/SyntheticCountsUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/SyntheticCountsUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TargetFolder.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TargetFolder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TargetFolder.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TargetFolder.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TargetLibraryInfo.def b/interpreter/llvm-project/llvm/include/llvm/Analysis/TargetLibraryInfo.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TargetLibraryInfo.def rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TargetLibraryInfo.def diff --git a/interpreter/llvm/src/include/llvm/Analysis/TargetLibraryInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TargetLibraryInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TargetLibraryInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TargetLibraryInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TargetTransformInfo.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TargetTransformInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TargetTransformInfo.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TargetTransformInfoImpl.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TargetTransformInfoImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Trace.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Trace.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Trace.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Trace.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TypeBasedAliasAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TypeBasedAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TypeBasedAliasAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TypeBasedAliasAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/TypeMetadataUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/TypeMetadataUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/TypeMetadataUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/TypeMetadataUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Utils/Local.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/Local.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Utils/Local.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/Local.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/Utils/TFUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/TFUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/Utils/TFUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/Utils/TFUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ValueLattice.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ValueLattice.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ValueLattice.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ValueLattice.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ValueLatticeUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ValueLatticeUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ValueLatticeUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ValueLatticeUtils.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/ValueTracking.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/ValueTracking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/ValueTracking.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/ValueTracking.h diff --git a/interpreter/llvm/src/include/llvm/Analysis/VecFuncs.def b/interpreter/llvm-project/llvm/include/llvm/Analysis/VecFuncs.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/VecFuncs.def rename to interpreter/llvm-project/llvm/include/llvm/Analysis/VecFuncs.def diff --git a/interpreter/llvm/src/include/llvm/Analysis/VectorUtils.h b/interpreter/llvm-project/llvm/include/llvm/Analysis/VectorUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Analysis/VectorUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Analysis/VectorUtils.h diff --git a/interpreter/llvm/src/include/llvm/AsmParser/LLLexer.h b/interpreter/llvm-project/llvm/include/llvm/AsmParser/LLLexer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/AsmParser/LLLexer.h rename to interpreter/llvm-project/llvm/include/llvm/AsmParser/LLLexer.h diff --git a/interpreter/llvm/src/include/llvm/AsmParser/LLParser.h b/interpreter/llvm-project/llvm/include/llvm/AsmParser/LLParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/AsmParser/LLParser.h rename to interpreter/llvm-project/llvm/include/llvm/AsmParser/LLParser.h diff --git a/interpreter/llvm/src/include/llvm/AsmParser/LLToken.h b/interpreter/llvm-project/llvm/include/llvm/AsmParser/LLToken.h similarity index 100% rename from interpreter/llvm/src/include/llvm/AsmParser/LLToken.h rename to interpreter/llvm-project/llvm/include/llvm/AsmParser/LLToken.h diff --git a/interpreter/llvm/src/include/llvm/AsmParser/Parser.h b/interpreter/llvm-project/llvm/include/llvm/AsmParser/Parser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/AsmParser/Parser.h rename to interpreter/llvm-project/llvm/include/llvm/AsmParser/Parser.h diff --git a/interpreter/llvm/src/include/llvm/AsmParser/SlotMapping.h b/interpreter/llvm-project/llvm/include/llvm/AsmParser/SlotMapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/AsmParser/SlotMapping.h rename to interpreter/llvm-project/llvm/include/llvm/AsmParser/SlotMapping.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/AMDGPUMetadataVerifier.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/AMDGPUMetadataVerifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/AMDGPUMetadataVerifier.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/AMDGPUMetadataVerifier.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/COFF.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/COFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/COFF.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/COFF.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/Dwarf.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Dwarf.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/Dwarf.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Dwarf.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/Dwarf.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Dwarf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/Dwarf.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Dwarf.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/DynamicTags.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/DynamicTags.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/DynamicTags.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/DynamicTags.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELF.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELF.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELF.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AArch64.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AArch64.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AArch64.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AArch64.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AMDGPU.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AMDGPU.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AMDGPU.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AMDGPU.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/ARC.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/ARC.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/ARC.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/ARC.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/ARM.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/ARM.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/ARM.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/ARM.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AVR.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AVR.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/AVR.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/AVR.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/BPF.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/BPF.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/BPF.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/BPF.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/CSKY.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/CSKY.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/CSKY.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/CSKY.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Hexagon.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Hexagon.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Hexagon.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Hexagon.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Lanai.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Lanai.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Lanai.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Lanai.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/M68k.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/M68k.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/M68k.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/M68k.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/MSP430.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/MSP430.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/MSP430.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/MSP430.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Mips.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Mips.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Mips.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Mips.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/PowerPC.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/PowerPC.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/PowerPC.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/PowerPC.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/PowerPC64.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/PowerPC64.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/PowerPC64.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/PowerPC64.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/RISCV.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/RISCV.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/RISCV.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/RISCV.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Sparc.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Sparc.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/Sparc.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/Sparc.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/SystemZ.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/SystemZ.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/SystemZ.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/SystemZ.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/VE.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/VE.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/VE.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/VE.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/i386.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/i386.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/i386.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/i386.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/x86_64.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/x86_64.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/ELFRelocs/x86_64.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/ELFRelocs/x86_64.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MachO.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MachO.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MachO.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MachO.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MachO.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MachO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MachO.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MachO.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/Magic.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Magic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/Magic.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Magic.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/Minidump.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Minidump.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/Minidump.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Minidump.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MinidumpConstants.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MinidumpConstants.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MinidumpConstants.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MinidumpConstants.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MsgPack.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPack.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MsgPack.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPack.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MsgPack.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPack.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MsgPack.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPack.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackDocument.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackDocument.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackDocument.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackDocument.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackReader.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackReader.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackReader.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackWriter.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/MsgPackWriter.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/MsgPackWriter.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/Wasm.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Wasm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/Wasm.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/Wasm.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/WasmRelocs.def b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/WasmRelocs.def similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/WasmRelocs.def rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/WasmRelocs.def diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/WasmTraits.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/WasmTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/WasmTraits.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/WasmTraits.h diff --git a/interpreter/llvm/src/include/llvm/BinaryFormat/XCOFF.h b/interpreter/llvm-project/llvm/include/llvm/BinaryFormat/XCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/BinaryFormat/XCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/BinaryFormat/XCOFF.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeAnalyzer.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeAnalyzer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeAnalyzer.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeAnalyzer.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeCommon.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeCommon.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeCommon.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeConvenience.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeConvenience.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeConvenience.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeConvenience.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeReader.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeReader.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeReader.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeWriter.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeWriter.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/BitcodeWriterPass.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeWriterPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/BitcodeWriterPass.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/BitcodeWriterPass.h diff --git a/interpreter/llvm/src/include/llvm/Bitcode/LLVMBitCodes.h b/interpreter/llvm-project/llvm/include/llvm/Bitcode/LLVMBitCodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitcode/LLVMBitCodes.h rename to interpreter/llvm-project/llvm/include/llvm/Bitcode/LLVMBitCodes.h diff --git a/interpreter/llvm/src/include/llvm/Bitstream/BitCodes.h b/interpreter/llvm-project/llvm/include/llvm/Bitstream/BitCodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitstream/BitCodes.h rename to interpreter/llvm-project/llvm/include/llvm/Bitstream/BitCodes.h diff --git a/interpreter/llvm/src/include/llvm/Bitstream/BitstreamReader.h b/interpreter/llvm-project/llvm/include/llvm/Bitstream/BitstreamReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitstream/BitstreamReader.h rename to interpreter/llvm-project/llvm/include/llvm/Bitstream/BitstreamReader.h diff --git a/interpreter/llvm/src/include/llvm/Bitstream/BitstreamWriter.h b/interpreter/llvm-project/llvm/include/llvm/Bitstream/BitstreamWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Bitstream/BitstreamWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Bitstream/BitstreamWriter.h diff --git a/interpreter/llvm/src/include/llvm/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/CodeGen/AccelTable.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/AccelTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/AccelTable.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/AccelTable.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/Analysis.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/Analysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/Analysis.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/Analysis.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/AntiDepBreaker.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/AntiDepBreaker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/AntiDepBreaker.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/AntiDepBreaker.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/AsmPrinter.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/AsmPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/AsmPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/AsmPrinter.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/AsmPrinterHandler.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/AsmPrinterHandler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/AsmPrinterHandler.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/AsmPrinterHandler.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/AtomicExpandUtils.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/AtomicExpandUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/AtomicExpandUtils.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/AtomicExpandUtils.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/BasicBlockSectionUtils.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/BasicBlockSectionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/BasicBlockSectionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/BasicBlockSectionUtils.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/BasicTTIImpl.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/BasicTTIImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/BasicTTIImpl.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/BasicTTIImpl.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CSEConfigBase.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CSEConfigBase.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CSEConfigBase.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CSEConfigBase.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CalcSpillWeights.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CalcSpillWeights.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CalcSpillWeights.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CalcSpillWeights.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CallingConvLower.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CallingConvLower.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CallingConvLower.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CallingConvLower.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CodeGenPassBuilder.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CodeGenPassBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CommandFlags.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CommandFlags.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CommandFlags.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CommandFlags.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/CostTable.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/CostTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/CostTable.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/CostTable.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DAGCombine.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DAGCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DAGCombine.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DAGCombine.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DFAPacketizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DFAPacketizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DFAPacketizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DFAPacketizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DIE.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DIE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DIE.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DIE.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DIEValue.def b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DIEValue.def similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DIEValue.def rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DIEValue.def diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DbgEntityHistoryCalculator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DbgEntityHistoryCalculator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DbgEntityHistoryCalculator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DbgEntityHistoryCalculator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DebugHandlerBase.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DebugHandlerBase.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DebugHandlerBase.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DebugHandlerBase.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/DwarfStringPoolEntry.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/DwarfStringPoolEntry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/DwarfStringPoolEntry.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/DwarfStringPoolEntry.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/EdgeBundles.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/EdgeBundles.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/EdgeBundles.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/EdgeBundles.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ExecutionDomainFix.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ExecutionDomainFix.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ExecutionDomainFix.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ExecutionDomainFix.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ExpandReductions.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ExpandReductions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ExpandReductions.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ExpandReductions.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ExpandVectorPredication.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ExpandVectorPredication.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ExpandVectorPredication.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ExpandVectorPredication.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/FastISel.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/FastISel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/FastISel.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/FastISel.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/FaultMaps.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/FaultMaps.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/FaultMaps.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/FaultMaps.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/FunctionLoweringInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/FunctionLoweringInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/FunctionLoweringInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/FunctionLoweringInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GCMetadata.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GCMetadata.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GCMetadata.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GCMetadata.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GCMetadataPrinter.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GCMetadataPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GCMetadataPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GCMetadataPrinter.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CSEInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CSEInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CSEInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CSEInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CSEMIRBuilder.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CSEMIRBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CSEMIRBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CSEMIRBuilder.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CallLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CallLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CallLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CallLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Combiner.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Combiner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Combiner.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Combiner.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CombinerHelper.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CombinerHelper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CombinerHelper.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CombinerHelper.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CombinerInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CombinerInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/CombinerInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/CombinerInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelChangeObserver.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelChangeObserver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelChangeObserver.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelChangeObserver.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelKnownBits.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelKnownBits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelKnownBits.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelKnownBits.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelWorkList.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GISelWorkList.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GenericMachineInstrs.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GenericMachineInstrs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/GenericMachineInstrs.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/GenericMachineInstrs.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/IRTranslator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/IRTranslator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/IRTranslator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/IRTranslator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InlineAsmLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InlineAsmLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InlineAsmLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InlineAsmLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelect.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelect.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelect.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelect.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelector.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelector.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelector.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegacyLegalizerInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegacyLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegacyLegalizerInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegacyLegalizerInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizationArtifactCombiner.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizationArtifactCombiner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizationArtifactCombiner.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizationArtifactCombiner.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Legalizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Legalizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Legalizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Legalizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizerHelper.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizerHelper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizerHelper.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizerHelper.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Localizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Localizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Localizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Localizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LostDebugLocObserver.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LostDebugLocObserver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/LostDebugLocObserver.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/LostDebugLocObserver.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/MIPatternMatch.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/MIPatternMatch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/MIPatternMatch.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/MIPatternMatch.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegBankSelect.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegBankSelect.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegBankSelect.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegBankSelect.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegisterBank.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegisterBank.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegisterBank.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegisterBank.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegisterBankInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/RegisterBankInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegisterBankInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Utils.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Utils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/GlobalISel/Utils.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/Utils.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ISDOpcodes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ISDOpcodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ISDOpcodes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ISDOpcodes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/IndirectThunks.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/IndirectThunks.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/IndirectThunks.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/IndirectThunks.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/IntrinsicLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/IntrinsicLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/IntrinsicLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/IntrinsicLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LatencyPriorityQueue.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LatencyPriorityQueue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LatencyPriorityQueue.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LatencyPriorityQueue.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LazyMachineBlockFrequencyInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LazyMachineBlockFrequencyInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LazyMachineBlockFrequencyInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LazyMachineBlockFrequencyInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LexicalScopes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LexicalScopes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LexicalScopes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LexicalScopes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LinkAllAsmWriterComponents.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LinkAllAsmWriterComponents.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LinkAllAsmWriterComponents.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LinkAllAsmWriterComponents.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LinkAllCodegenComponents.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LinkAllCodegenComponents.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveInterval.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveInterval.h similarity index 99% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveInterval.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveInterval.h index c2b158ac1b7fa..2165f1f7d761f 100644 --- a/interpreter/llvm/src/include/llvm/CodeGen/LiveInterval.h +++ b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveInterval.h @@ -724,7 +724,7 @@ namespace llvm { T *P; public: - SingleLinkedListIterator(T *P) : P(P) {} + SingleLinkedListIterator(T *P) : P(P) {} SingleLinkedListIterator &operator++() { P = P->Next; diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveIntervalCalc.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervalCalc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveIntervalCalc.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervalCalc.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveIntervalUnion.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervalUnion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveIntervalUnion.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervalUnion.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveIntervals.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervals.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveIntervals.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveIntervals.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LivePhysRegs.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LivePhysRegs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LivePhysRegs.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LivePhysRegs.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveRangeCalc.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRangeCalc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveRangeCalc.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRangeCalc.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveRangeEdit.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRangeEdit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveRangeEdit.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRangeEdit.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveRegMatrix.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRegMatrix.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveRegMatrix.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRegMatrix.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveRegUnits.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRegUnits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveRegUnits.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveRegUnits.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveStacks.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveStacks.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveStacks.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveStacks.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LiveVariables.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveVariables.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LiveVariables.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LiveVariables.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LoopTraversal.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LoopTraversal.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LoopTraversal.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LoopTraversal.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/LowLevelType.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/LowLevelType.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/LowLevelType.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/LowLevelType.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MBFIWrapper.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MBFIWrapper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MBFIWrapper.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MBFIWrapper.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRFSDiscriminator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRFSDiscriminator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRFSDiscriminator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRFSDiscriminator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRFormatter.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRFormatter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRFormatter.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRFormatter.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRParser/MIParser.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRParser/MIParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRParser/MIParser.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRParser/MIParser.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRParser/MIRParser.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRParser/MIRParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRParser/MIRParser.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRParser/MIRParser.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRPrinter.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRPrinter.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MIRYamlMapping.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRYamlMapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MIRYamlMapping.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MIRYamlMapping.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachORelocation.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachORelocation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachORelocation.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachORelocation.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineBasicBlock.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBasicBlock.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineBasicBlock.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBasicBlock.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineBlockFrequencyInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBlockFrequencyInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineBlockFrequencyInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBlockFrequencyInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineBranchProbabilityInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBranchProbabilityInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineBranchProbabilityInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineBranchProbabilityInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineCombinerPattern.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineCombinerPattern.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineCombinerPattern.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineCombinerPattern.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineConstantPool.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineConstantPool.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineConstantPool.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineConstantPool.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineDominanceFrontier.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineDominanceFrontier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineDominanceFrontier.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineDominanceFrontier.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineDominators.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineDominators.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineDominators.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineDominators.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineFrameInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFrameInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineFrameInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFrameInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineFunction.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFunction.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineFunction.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFunction.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineFunctionPass.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFunctionPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineFunctionPass.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineFunctionPass.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineInstr.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineInstr.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstr.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBuilder.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBuilder.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBundle.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBundle.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBundle.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBundle.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBundleIterator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBundleIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineInstrBundleIterator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBundleIterator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineJumpTableInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineJumpTableInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineJumpTableInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineJumpTableInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineLoopInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineLoopInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineLoopInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineLoopInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineLoopUtils.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineLoopUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineLoopUtils.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineLoopUtils.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineMemOperand.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineMemOperand.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineMemOperand.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineMemOperand.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineModuleInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineModuleInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineModuleInfoImpls.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleInfoImpls.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineModuleInfoImpls.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleInfoImpls.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineModuleSlotTracker.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleSlotTracker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineModuleSlotTracker.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineModuleSlotTracker.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineOperand.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOperand.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineOperand.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOperand.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineOptimizationRemarkEmitter.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOptimizationRemarkEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineOptimizationRemarkEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOptimizationRemarkEmitter.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineOutliner.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOutliner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineOutliner.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineOutliner.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachinePassManager.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachinePassManager.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassManager.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachinePassRegistry.def b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassRegistry.def similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachinePassRegistry.def rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassRegistry.def diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachinePassRegistry.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassRegistry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachinePassRegistry.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePassRegistry.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachinePipeliner.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePipeliner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachinePipeliner.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePipeliner.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachinePostDominators.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePostDominators.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachinePostDominators.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachinePostDominators.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineRegionInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineRegionInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineRegionInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineRegionInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineRegisterInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineRegisterInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineRegisterInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineSSAUpdater.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineSSAUpdater.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineSSAUpdater.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineSSAUpdater.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineScheduler.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineScheduler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineScheduler.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineScheduler.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineSizeOpts.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineSizeOpts.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineSizeOpts.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineSizeOpts.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineStableHash.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineStableHash.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineStableHash.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineStableHash.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MachineTraceMetrics.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineTraceMetrics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MachineTraceMetrics.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MachineTraceMetrics.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MacroFusion.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MacroFusion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MacroFusion.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MacroFusion.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ModuloSchedule.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ModuloSchedule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ModuloSchedule.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ModuloSchedule.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/MultiHazardRecognizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/MultiHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/MultiHazardRecognizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/MultiHazardRecognizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/NonRelocatableStringpool.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/NonRelocatableStringpool.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/NonRelocatableStringpool.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/NonRelocatableStringpool.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQP/CostAllocator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/CostAllocator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQP/CostAllocator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/CostAllocator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQP/Graph.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Graph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQP/Graph.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Graph.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQP/Math.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Math.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQP/Math.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Math.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQP/ReductionRules.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/ReductionRules.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQP/ReductionRules.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/ReductionRules.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQP/Solution.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Solution.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQP/Solution.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQP/Solution.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PBQPRAConstraint.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQPRAConstraint.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PBQPRAConstraint.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PBQPRAConstraint.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ParallelCG.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ParallelCG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ParallelCG.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ParallelCG.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/Passes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/Passes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/Passes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/Passes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PreISelIntrinsicLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PreISelIntrinsicLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PreISelIntrinsicLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PreISelIntrinsicLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/PseudoSourceValue.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/PseudoSourceValue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/PseudoSourceValue.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/PseudoSourceValue.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RDFGraph.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFGraph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RDFGraph.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFGraph.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RDFLiveness.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFLiveness.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RDFLiveness.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFLiveness.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RDFRegisters.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFRegisters.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RDFRegisters.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RDFRegisters.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ReachingDefAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ReachingDefAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ReachingDefAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ReachingDefAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegAllocCommon.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegAllocCommon.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocCommon.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegAllocPBQP.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocPBQP.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegAllocPBQP.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocPBQP.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegAllocRegistry.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocRegistry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegAllocRegistry.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegAllocRegistry.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/Register.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/Register.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/Register.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/Register.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegisterClassInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterClassInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegisterClassInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterClassInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegisterPressure.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterPressure.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegisterPressure.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterPressure.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegisterScavenging.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterScavenging.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegisterScavenging.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterScavenging.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RegisterUsageInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterUsageInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RegisterUsageInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RegisterUsageInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ReplaceWithVeclib.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ReplaceWithVeclib.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ReplaceWithVeclib.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ReplaceWithVeclib.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ResourcePriorityQueue.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ResourcePriorityQueue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ResourcePriorityQueue.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ResourcePriorityQueue.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/RuntimeLibcalls.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/RuntimeLibcalls.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/RuntimeLibcalls.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/RuntimeLibcalls.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SDNodeProperties.td b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SDNodeProperties.td similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SDNodeProperties.td rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SDNodeProperties.td diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAG.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAG.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAG.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAGInstrs.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAGInstrs.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAGMutation.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAGMutation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScheduleDAGMutation.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDAGMutation.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScheduleDFS.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDFS.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScheduleDFS.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleDFS.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScheduleHazardRecognizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScheduleHazardRecognizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScheduleHazardRecognizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SchedulerRegistry.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SchedulerRegistry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SchedulerRegistry.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SchedulerRegistry.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ScoreboardHazardRecognizer.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ScoreboardHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ScoreboardHazardRecognizer.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ScoreboardHazardRecognizer.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SelectionDAG.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SelectionDAG.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAG.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGAddressAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGAddressAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGAddressAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGAddressAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGISel.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGISel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGISel.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGISel.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGNodes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGNodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGNodes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGNodes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGTargetInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGTargetInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SelectionDAGTargetInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SelectionDAGTargetInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SlotIndexes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SlotIndexes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SlotIndexes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SlotIndexes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/Spiller.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/Spiller.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/Spiller.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/Spiller.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/StableHashing.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/StableHashing.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/StableHashing.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/StableHashing.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/StackMaps.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/StackMaps.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/StackMaps.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/StackMaps.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/StackProtector.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/StackProtector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/StackProtector.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/StackProtector.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SwiftErrorValueTracking.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SwiftErrorValueTracking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SwiftErrorValueTracking.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SwiftErrorValueTracking.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/SwitchLoweringUtils.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/SwitchLoweringUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/SwitchLoweringUtils.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/SwitchLoweringUtils.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TailDuplicator.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TailDuplicator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TailDuplicator.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TailDuplicator.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetCallingConv.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetCallingConv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetCallingConv.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetCallingConv.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetFrameLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetFrameLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetFrameLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetFrameLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetInstrInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetInstrInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetInstrInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetInstrInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetLowering.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetLowering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetLowering.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetLowering.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetOpcodes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetOpcodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetOpcodes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetOpcodes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetPassConfig.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetPassConfig.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetPassConfig.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetPassConfig.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetRegisterInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetRegisterInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetRegisterInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetSchedule.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetSchedule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetSchedule.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetSchedule.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TargetSubtargetInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetSubtargetInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TargetSubtargetInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TargetSubtargetInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/TileShapeInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/TileShapeInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/TileShapeInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/TileShapeInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/UnreachableBlockElim.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/UnreachableBlockElim.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/UnreachableBlockElim.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/UnreachableBlockElim.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ValueTypes.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ValueTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ValueTypes.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ValueTypes.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/ValueTypes.td b/interpreter/llvm-project/llvm/include/llvm/CodeGen/ValueTypes.td similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/ValueTypes.td rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/ValueTypes.td diff --git a/interpreter/llvm/src/include/llvm/CodeGen/VirtRegMap.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/VirtRegMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/VirtRegMap.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/VirtRegMap.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/WasmEHFuncInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/WasmEHFuncInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/WasmEHFuncInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/WasmEHFuncInfo.h diff --git a/interpreter/llvm/src/include/llvm/CodeGen/WinEHFuncInfo.h b/interpreter/llvm-project/llvm/include/llvm/CodeGen/WinEHFuncInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/CodeGen/WinEHFuncInfo.h rename to interpreter/llvm-project/llvm/include/llvm/CodeGen/WinEHFuncInfo.h diff --git a/interpreter/llvm/src/include/llvm/Config/AsmParsers.def.in b/interpreter/llvm-project/llvm/include/llvm/Config/AsmParsers.def.in similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/AsmParsers.def.in rename to interpreter/llvm-project/llvm/include/llvm/Config/AsmParsers.def.in diff --git a/interpreter/llvm/src/include/llvm/Config/AsmPrinters.def.in b/interpreter/llvm-project/llvm/include/llvm/Config/AsmPrinters.def.in similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/AsmPrinters.def.in rename to interpreter/llvm-project/llvm/include/llvm/Config/AsmPrinters.def.in diff --git a/interpreter/llvm/src/include/llvm/Config/Disassemblers.def.in b/interpreter/llvm-project/llvm/include/llvm/Config/Disassemblers.def.in similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/Disassemblers.def.in rename to interpreter/llvm-project/llvm/include/llvm/Config/Disassemblers.def.in diff --git a/interpreter/llvm/src/include/llvm/Config/Targets.def.in b/interpreter/llvm-project/llvm/include/llvm/Config/Targets.def.in similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/Targets.def.in rename to interpreter/llvm-project/llvm/include/llvm/Config/Targets.def.in diff --git a/interpreter/llvm/src/include/llvm/Config/abi-breaking.h.cmake b/interpreter/llvm-project/llvm/include/llvm/Config/abi-breaking.h.cmake similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/abi-breaking.h.cmake rename to interpreter/llvm-project/llvm/include/llvm/Config/abi-breaking.h.cmake diff --git a/interpreter/llvm/src/include/llvm/Config/config.h.cmake b/interpreter/llvm-project/llvm/include/llvm/Config/config.h.cmake similarity index 100% rename from interpreter/llvm/src/include/llvm/Config/config.h.cmake rename to interpreter/llvm-project/llvm/include/llvm/Config/config.h.cmake diff --git a/interpreter/llvm/src/include/llvm/Config/llvm-config.h.cmake b/interpreter/llvm-project/llvm/include/llvm/Config/llvm-config.h.cmake similarity index 95% rename from interpreter/llvm/src/include/llvm/Config/llvm-config.h.cmake rename to interpreter/llvm-project/llvm/include/llvm/Config/llvm-config.h.cmake index 4e7e2e9e39d9f..b2f92ca7cb74f 100644 --- a/interpreter/llvm/src/include/llvm/Config/llvm-config.h.cmake +++ b/interpreter/llvm-project/llvm/include/llvm/Config/llvm-config.h.cmake @@ -100,5 +100,10 @@ /* Whether Timers signpost passes in Xcode Instruments */ #cmakedefine01 LLVM_SUPPORT_XCODE_SIGNPOSTS +/* Define if building libLLVM shared library */ +#cmakedefine LLVM_BUILD_LLVM_DYLIB + +/* Define if building LLVM with BUILD_SHARED_LIBS */ +#cmakedefine LLVM_BUILD_SHARED_LIBS #endif diff --git a/interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinker.h b/interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinker.h rename to interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinker.h diff --git a/interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinkerCompileUnit.h b/interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinkerCompileUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinkerCompileUnit.h rename to interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinkerCompileUnit.h diff --git a/interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinkerDeclContext.h b/interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinkerDeclContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWARFLinker/DWARFLinkerDeclContext.h rename to interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFLinkerDeclContext.h diff --git a/interpreter/llvm/src/include/llvm/DWARFLinker/DWARFStreamer.h b/interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWARFLinker/DWARFStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/DWARFLinker/DWARFStreamer.h diff --git a/interpreter/llvm/src/include/llvm/DWP/DWP.h b/interpreter/llvm-project/llvm/include/llvm/DWP/DWP.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWP/DWP.h rename to interpreter/llvm-project/llvm/include/llvm/DWP/DWP.h diff --git a/interpreter/llvm/src/include/llvm/DWP/DWPError.h b/interpreter/llvm-project/llvm/include/llvm/DWP/DWPError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWP/DWPError.h rename to interpreter/llvm-project/llvm/include/llvm/DWP/DWPError.h diff --git a/interpreter/llvm/src/include/llvm/DWP/DWPStringPool.h b/interpreter/llvm-project/llvm/include/llvm/DWP/DWPStringPool.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DWP/DWPStringPool.h rename to interpreter/llvm-project/llvm/include/llvm/DWP/DWPStringPool.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/AppendingTypeTableBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/AppendingTypeTableBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/AppendingTypeTableBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/AppendingTypeTableBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVRecord.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVRecord.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVRecord.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVSymbolVisitor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVSymbolVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVSymbolVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVSymbolVisitor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeView.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeView.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeView.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeView.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewError.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewError.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewError.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewRecordIO.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewRecordIO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewRecordIO.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewRecordIO.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewRegisters.def b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewRegisters.def similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewRegisters.def rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewRegisters.def diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewSymbols.def b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewSymbols.def similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewSymbols.def rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewSymbols.def diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewTypes.def b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewTypes.def similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/CodeViewTypes.def rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/CodeViewTypes.def diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugCrossExSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugCrossExSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugCrossExSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugCrossExSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugLinesSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugLinesSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugLinesSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugLinesSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugStringTableSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugStringTableSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugStringTableSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugStringTableSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsectionRecord.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsectionRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsectionRecord.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsectionRecord.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSymbolRVASubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSymbolRVASubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSymbolRVASubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSymbolRVASubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugUnknownSubsection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugUnknownSubsection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/DebugUnknownSubsection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/DebugUnknownSubsection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/EnumTables.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/EnumTables.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/EnumTables.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/EnumTables.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/Formatters.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/Formatters.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/Formatters.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/Formatters.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/FunctionId.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/FunctionId.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/FunctionId.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/FunctionId.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/GUID.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/GUID.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/GUID.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/GUID.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/Line.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/Line.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/Line.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/Line.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/RecordName.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/RecordName.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/RecordName.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/RecordName.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/RecordSerialization.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/RecordSerialization.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/RecordSerialization.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/RecordSerialization.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SimpleTypeSerializer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SimpleTypeSerializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SimpleTypeSerializer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SimpleTypeSerializer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/StringsAndChecksums.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/StringsAndChecksums.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/StringsAndChecksums.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/StringsAndChecksums.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDeserializer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDeserializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDeserializer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDeserializer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDumpDelegate.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDumpDelegate.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDumpDelegate.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDumpDelegate.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDumper.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDumper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolDumper.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolDumper.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecord.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecord.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecord.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecordHelpers.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecordHelpers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecordHelpers.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecordHelpers.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecordMapping.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecordMapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolRecordMapping.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolRecordMapping.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolSerializer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolSerializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolSerializer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolSerializer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorDelegate.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorDelegate.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/SymbolVisitorDelegate.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/SymbolVisitorDelegate.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeCollection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeCollection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeCollection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeCollection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeDeserializer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeDeserializer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeHashing.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeHashing.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeHashing.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeHashing.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeIndex.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeIndex.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeIndexDiscovery.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeIndexDiscovery.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeIndexDiscovery.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeIndexDiscovery.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecord.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecord.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecord.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecordHelpers.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecordHelpers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecordHelpers.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecordHelpers.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecordMapping.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecordMapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeRecordMapping.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeRecordMapping.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeStreamMerger.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeStreamMerger.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeStreamMerger.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeStreamMerger.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeSymbolEmitter.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeSymbolEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeSymbolEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeSymbolEmitter.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeTableCollection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeTableCollection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeTableCollection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeTableCollection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DIContext.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DIContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DIContext.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DIContext.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAddressRange.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAddressRange.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAddressRange.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAddressRange.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAttribute.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAttribute.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFAttribute.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFAttribute.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFContext.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFContext.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDataExtractor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDataExtractor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDataExtractor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDataExtractor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAddr.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAddr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAddr.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAddr.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAranges.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAranges.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugAranges.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAranges.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugFrame.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugFrame.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugFrame.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugFrame.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugLoc.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLoc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugLoc.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLoc.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugMacro.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugMacro.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugMacro.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugMacro.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugPubTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugPubTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugPubTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugPubTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugRnglists.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRnglists.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDebugRnglists.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRnglists.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDie.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDie.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFDie.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFDie.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFExpression.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFExpression.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFExpression.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFExpression.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFFormValue.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFFormValue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFFormValue.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFFormValue.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFGdbIndex.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFGdbIndex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFGdbIndex.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFGdbIndex.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFListTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFListTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFListTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFListTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFLocationExpression.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFLocationExpression.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFLocationExpression.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFLocationExpression.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFObject.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFObject.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFObject.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFObject.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFSection.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFSection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFSection.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFSection.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFTypeUnit.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFTypeUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFTypeUnit.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFTypeUnit.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFUnit.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFUnit.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFUnitIndex.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFUnitIndex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFUnitIndex.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFUnitIndex.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFVerifier.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/DWARF/DWARFVerifier.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/DwarfTransformer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/DwarfTransformer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/DwarfTransformer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/DwarfTransformer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FileEntry.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FileEntry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FileEntry.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FileEntry.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FileWriter.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FileWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FileWriter.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FileWriter.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FunctionInfo.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/FunctionInfo.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/GsymCreator.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/GsymCreator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/GsymCreator.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/GsymCreator.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/GsymReader.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/GsymReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/GsymReader.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/GsymReader.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/Header.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/Header.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/Header.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/Header.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/InlineInfo.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/InlineInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/InlineInfo.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/InlineInfo.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LineEntry.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LineEntry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LineEntry.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LineEntry.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LineTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LineTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LineTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LineTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LookupResult.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LookupResult.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/LookupResult.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/LookupResult.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/ObjectFileTransformer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/ObjectFileTransformer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/ObjectFileTransformer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/ObjectFileTransformer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/Range.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/Range.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/Range.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/Range.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/GSYM/StringTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/StringTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/GSYM/StringTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/GSYM/StringTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/MSF/IMSFFile.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/IMSFFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/MSF/IMSFFile.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/IMSFFile.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFCommon.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFCommon.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFCommon.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFError.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/MSF/MSFError.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MSFError.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/MSF/MappedBlockStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MappedBlockStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/MSF/MappedBlockStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/MSF/MappedBlockStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIADataStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIADataStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIADataStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIADataStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumFrameData.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumFrameData.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumFrameData.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumFrameData.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumInjectedSources.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumInjectedSources.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumInjectedSources.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumInjectedSources.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSectionContribs.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSectionContribs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSectionContribs.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSectionContribs.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumTables.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumTables.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAEnumTables.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumTables.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAError.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAError.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAError.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAFrameData.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAFrameData.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAFrameData.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAFrameData.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAInjectedSource.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAInjectedSource.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAInjectedSource.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAInjectedSource.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIALineNumber.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIALineNumber.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIALineNumber.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIALineNumber.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIARawSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIARawSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIARawSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIARawSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASectionContrib.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASectionContrib.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASectionContrib.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASectionContrib.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASession.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASession.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASession.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASession.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASourceFile.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASourceFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASourceFile.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASourceFile.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASupport.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIASupport.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIASupport.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIATable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIATable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIATable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIATable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAUtils.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/DIA/DIAUtils.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/DIA/DIAUtils.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/GenericError.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/GenericError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/GenericError.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/GenericError.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBDataStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBDataStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBDataStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBDataStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBEnumChildren.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBEnumChildren.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBEnumChildren.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBEnumChildren.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBFrameData.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBFrameData.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBFrameData.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBFrameData.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBInjectedSource.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBInjectedSource.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBInjectedSource.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBInjectedSource.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBLineNumber.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBLineNumber.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBLineNumber.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBLineNumber.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBRawSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBRawSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBRawSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBRawSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSectionContrib.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSectionContrib.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSectionContrib.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSectionContrib.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSession.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSession.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSession.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSession.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSourceFile.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSourceFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBSourceFile.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBSourceFile.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/IPDBTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/IPDBTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleList.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiModuleList.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiModuleList.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/EnumTables.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/EnumTables.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/EnumTables.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/EnumTables.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/Formatters.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/Formatters.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/Formatters.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/Formatters.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/Hash.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/Hash.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/Hash.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/Hash.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/HashTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/HashTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/HashTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/HashTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InfoStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InfoStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InfoStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InfoStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InjectedSourceStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InjectedSourceStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/InjectedSourceStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/InjectedSourceStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/ModuleDebugStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/ModuleDebugStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/ModuleDebugStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/ModuleDebugStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NamedStreamMap.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NamedStreamMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NamedStreamMap.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NamedStreamMap.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeCompilandSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeCompilandSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeCompilandSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeCompilandSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumGlobals.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumGlobals.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumGlobals.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumGlobals.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumInjectedSources.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumInjectedSources.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumInjectedSources.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumInjectedSources.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumLineNumbers.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumLineNumbers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumLineNumbers.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumLineNumbers.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumModules.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumModules.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumModules.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumModules.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumSymbols.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumSymbols.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumSymbols.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumSymbols.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumTypes.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeEnumTypes.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeEnumTypes.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeExeSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeExeSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeExeSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeExeSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeFunctionSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeFunctionSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeFunctionSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeFunctionSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeInlineSiteSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeInlineSiteSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeInlineSiteSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeInlineSiteSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeLineNumber.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeLineNumber.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeLineNumber.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeLineNumber.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativePublicSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativePublicSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativePublicSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativePublicSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeRawSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeRawSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeRawSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeRawSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSession.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSession.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSession.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSession.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSourceFile.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSourceFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSourceFile.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSourceFile.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSymbolEnumerator.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSymbolEnumerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeSymbolEnumerator.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeSymbolEnumerator.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeArray.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeArray.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeArray.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeArray.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeBuiltin.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeBuiltin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeBuiltin.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeBuiltin.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeEnum.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeEnum.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeEnum.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeEnum.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeFunctionSig.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeFunctionSig.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeFunctionSig.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeFunctionSig.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypePointer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypePointer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypePointer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypePointer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeTypedef.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeTypedef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeTypedef.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeTypedef.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeUDT.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeUDT.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeUDT.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeUDT.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeVTShape.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeVTShape.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/NativeTypeVTShape.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/NativeTypeVTShape.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBFile.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBFile.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBFile.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBFileBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBFileBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBFileBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBFileBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBStringTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBStringTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBStringTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBStringTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PublicsStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PublicsStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/PublicsStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/PublicsStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawConstants.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawConstants.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawConstants.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawConstants.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawError.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawError.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawError.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawTypes.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/RawTypes.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/SymbolCache.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/SymbolCache.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/SymbolCache.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/SymbolCache.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/SymbolStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/SymbolStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/SymbolStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/SymbolStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiHashing.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiHashing.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiHashing.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiHashing.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiStream.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiStream.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDB.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDB.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDB.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDB.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBContext.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBContext.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBContext.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBExtras.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBExtras.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBExtras.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBExtras.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymDumper.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymDumper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymDumper.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymDumper.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolAnnotation.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolAnnotation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolAnnotation.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolAnnotation.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolBlock.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolBlock.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolBlock.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolBlock.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompiland.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompiland.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompiland.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompiland.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCustom.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCustom.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolCustom.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolCustom.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolData.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolData.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolData.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolData.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolExe.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolExe.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolExe.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolExe.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFunc.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFunc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFunc.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFunc.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolLabel.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolLabel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolLabel.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolLabel.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolThunk.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolThunk.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolThunk.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolThunk.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeArray.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeArray.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeArray.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeArray.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypePointer.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypePointer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypePointer.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypePointer.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolUnknown.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolUnknown.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolUnknown.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolUnknown.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBTypes.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/PDBTypes.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/PDBTypes.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/PDB/UDTLayout.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/UDTLayout.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/PDB/UDTLayout.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/PDB/UDTLayout.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/DIPrinter.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/DIPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/DIPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/DIPrinter.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/SymbolizableModule.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/SymbolizableModule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/SymbolizableModule.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/SymbolizableModule.h diff --git a/interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/Symbolize.h b/interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/Symbolize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/DebugInfo/Symbolize/Symbolize.h rename to interpreter/llvm-project/llvm/include/llvm/DebugInfo/Symbolize/Symbolize.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/Demangle.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/Demangle.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/Demangle.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/Demangle.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/DemangleConfig.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/DemangleConfig.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/DemangleConfig.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/DemangleConfig.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/ItaniumDemangle.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/ItaniumDemangle.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/ItaniumDemangle.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/ItaniumDemangle.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/MicrosoftDemangle.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/MicrosoftDemangle.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/MicrosoftDemangle.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/MicrosoftDemangle.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/MicrosoftDemangleNodes.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/MicrosoftDemangleNodes.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/README.txt b/interpreter/llvm-project/llvm/include/llvm/Demangle/README.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/README.txt rename to interpreter/llvm-project/llvm/include/llvm/Demangle/README.txt diff --git a/interpreter/llvm/src/include/llvm/Demangle/StringView.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/StringView.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/StringView.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/StringView.h diff --git a/interpreter/llvm/src/include/llvm/Demangle/Utility.h b/interpreter/llvm-project/llvm/include/llvm/Demangle/Utility.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Demangle/Utility.h rename to interpreter/llvm-project/llvm/include/llvm/Demangle/Utility.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/ExecutionEngine.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/ExecutionEngine.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/GenericValue.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/GenericValue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/GenericValue.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/GenericValue.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Interpreter.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Interpreter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Interpreter.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Interpreter.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITEventListener.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITEventListener.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITEventListener.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITEventListener.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/EHFrameSupport.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/EHFrameSupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/EHFrameSupport.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/EHFrameSupport.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF_riscv.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF_riscv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF_riscv.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF_riscv.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF_x86_64.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF_x86_64.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/ELF_x86_64.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/ELF_x86_64.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLink.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLink.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLink.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLink.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLinkDylib.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLinkDylib.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLinkDylib.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLinkDylib.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO_arm64.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO_arm64.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO_arm64.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO_arm64.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO_x86_64.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO_x86_64.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/MachO_x86_64.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/MachO_x86_64.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/riscv.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/riscv.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/x86_64.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/x86_64.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITLink/x86_64.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/x86_64.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/JITSymbol.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/JITSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/JITSymbol.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/MCJIT.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/MCJIT.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/MCJIT.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/MCJIT.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/OProfileWrapper.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OProfileWrapper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/OProfileWrapper.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OProfileWrapper.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/ObjectCache.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/ObjectCache.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/ObjectCache.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/ObjectCache.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/CompileUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/CompileUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/CompileUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/CompileUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Core.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Core.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Core.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Core.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/DebugUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/DebugUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/DebugUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/DebugUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCIndirectionUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCIndirectionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/EPCIndirectionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/EPCIndirectionUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ExecutorProcessControl.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ExecutorProcessControl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ExecutorProcessControl.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ExecutorProcessControl.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IRCompileLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IRCompileLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IRCompileLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IRCompileLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IndirectionUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IndirectionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/IndirectionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/IndirectionUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LLJIT.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LLJIT.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LLVMSPSSerializers.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LLVMSPSSerializers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LLVMSPSSerializers.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LLVMSPSSerializers.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Layer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Layer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Layer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Layer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LazyReexports.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LazyReexports.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/LazyReexports.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/LazyReexports.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/MachOPlatform.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/MachOPlatform.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/MachOPlatform.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/MachOPlatform.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Mangling.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Mangling.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Mangling.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Mangling.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ObjectTransformLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ObjectTransformLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ObjectTransformLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ObjectTransformLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcABISupport.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcABISupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcABISupport.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcABISupport.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRPCExecutorProcessControl.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRPCExecutorProcessControl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRPCExecutorProcessControl.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRPCExecutorProcessControl.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetRPCAPI.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetRPCAPI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetRPCAPI.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetRPCAPI.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetServer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetServer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetServer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetServer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/FDRawByteChannel.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/FDRawByteChannel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/FDRawByteChannel.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/FDRawByteChannel.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/OrcError.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/OrcError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/OrcError.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/OrcError.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/RPCUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/RPCUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/RPCUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/RPCUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/RawByteChannel.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/RawByteChannel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/RawByteChannel.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/RawByteChannel.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/Serialization.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/Serialization.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/Serialization.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/Serialization.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/SimplePackedSerialization.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/SimplePackedSerialization.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/SimplePackedSerialization.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/SimplePackedSerialization.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/SpeculateAnalyses.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/SpeculateAnalyses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/SpeculateAnalyses.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/SpeculateAnalyses.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Speculation.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Speculation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/Speculation.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/Speculation.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/SymbolStringPool.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/SymbolStringPool.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/SymbolStringPool.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/SymbolStringPool.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/OrcRPCTPCServer.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/OrcRPCTPCServer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/OrcRPCTPCServer.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/OrcRPCTPCServer.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ThreadSafeModule.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ThreadSafeModule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/Orc/ThreadSafeModule.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/Orc/ThreadSafeModule.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/OrcMCJITReplacement.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OrcMCJITReplacement.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/OrcMCJITReplacement.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OrcMCJITReplacement.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/OrcV1Deprecation.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OrcV1Deprecation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/OrcV1Deprecation.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/OrcV1Deprecation.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/RTDyldMemoryManager.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/RTDyldMemoryManager.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/RuntimeDyld.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/RuntimeDyld.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/RuntimeDyldChecker.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RuntimeDyldChecker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/RuntimeDyldChecker.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/RuntimeDyldChecker.h diff --git a/interpreter/llvm/src/include/llvm/ExecutionEngine/SectionMemoryManager.h b/interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/SectionMemoryManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ExecutionEngine/SectionMemoryManager.h rename to interpreter/llvm-project/llvm/include/llvm/ExecutionEngine/SectionMemoryManager.h diff --git a/interpreter/llvm/src/include/llvm/FileCheck/FileCheck.h b/interpreter/llvm-project/llvm/include/llvm/FileCheck/FileCheck.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FileCheck/FileCheck.h rename to interpreter/llvm-project/llvm/include/llvm/FileCheck/FileCheck.h diff --git a/interpreter/llvm/src/include/llvm/Frontend/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/Frontend/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/Frontend/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/Frontend/Directive/DirectiveBase.td b/interpreter/llvm-project/llvm/include/llvm/Frontend/Directive/DirectiveBase.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/Directive/DirectiveBase.td rename to interpreter/llvm-project/llvm/include/llvm/Frontend/Directive/DirectiveBase.td diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenACC/ACC.td b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenACC/ACC.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenACC/ACC.td rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenACC/ACC.td diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenACC/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenACC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenACC/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenACC/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMP.td b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMP.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMP.td rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMP.td diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPConstants.h b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPConstants.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPConstants.h rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPConstants.h diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPContext.h b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPContext.h rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPContext.h diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPGridValues.h b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPGridValues.h rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPIRBuilder.h b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPIRBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h diff --git a/interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPKinds.def b/interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Frontend/OpenMP/OMPKinds.def rename to interpreter/llvm-project/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/FuzzerCLI.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/FuzzerCLI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/FuzzerCLI.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/FuzzerCLI.h diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/IRMutator.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/IRMutator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/IRMutator.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/IRMutator.h diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/OpDescriptor.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/OpDescriptor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/OpDescriptor.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/OpDescriptor.h diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/Operations.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/Operations.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/Operations.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/Operations.h diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/Random.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/Random.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/Random.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/Random.h diff --git a/interpreter/llvm/src/include/llvm/FuzzMutate/RandomIRBuilder.h b/interpreter/llvm-project/llvm/include/llvm/FuzzMutate/RandomIRBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/FuzzMutate/RandomIRBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/FuzzMutate/RandomIRBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/AbstractCallSite.h b/interpreter/llvm-project/llvm/include/llvm/IR/AbstractCallSite.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/AbstractCallSite.h rename to interpreter/llvm-project/llvm/include/llvm/IR/AbstractCallSite.h diff --git a/interpreter/llvm/src/include/llvm/IR/Argument.h b/interpreter/llvm-project/llvm/include/llvm/IR/Argument.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Argument.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Argument.h diff --git a/interpreter/llvm/src/include/llvm/IR/AssemblyAnnotationWriter.h b/interpreter/llvm-project/llvm/include/llvm/IR/AssemblyAnnotationWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/AssemblyAnnotationWriter.h rename to interpreter/llvm-project/llvm/include/llvm/IR/AssemblyAnnotationWriter.h diff --git a/interpreter/llvm/src/include/llvm/IR/Assumptions.h b/interpreter/llvm-project/llvm/include/llvm/IR/Assumptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Assumptions.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Assumptions.h diff --git a/interpreter/llvm/src/include/llvm/IR/Attributes.h b/interpreter/llvm-project/llvm/include/llvm/IR/Attributes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Attributes.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Attributes.h diff --git a/interpreter/llvm/src/include/llvm/IR/Attributes.td b/interpreter/llvm-project/llvm/include/llvm/IR/Attributes.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Attributes.td rename to interpreter/llvm-project/llvm/include/llvm/IR/Attributes.td diff --git a/interpreter/llvm/src/include/llvm/IR/AutoUpgrade.h b/interpreter/llvm-project/llvm/include/llvm/IR/AutoUpgrade.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/AutoUpgrade.h rename to interpreter/llvm-project/llvm/include/llvm/IR/AutoUpgrade.h diff --git a/interpreter/llvm/src/include/llvm/IR/BasicBlock.h b/interpreter/llvm-project/llvm/include/llvm/IR/BasicBlock.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/BasicBlock.h rename to interpreter/llvm-project/llvm/include/llvm/IR/BasicBlock.h diff --git a/interpreter/llvm/src/include/llvm/IR/BuiltinGCs.h b/interpreter/llvm-project/llvm/include/llvm/IR/BuiltinGCs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/BuiltinGCs.h rename to interpreter/llvm-project/llvm/include/llvm/IR/BuiltinGCs.h diff --git a/interpreter/llvm/src/include/llvm/IR/CFG.h b/interpreter/llvm-project/llvm/include/llvm/IR/CFG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/CFG.h rename to interpreter/llvm-project/llvm/include/llvm/IR/CFG.h diff --git a/interpreter/llvm/src/include/llvm/IR/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/IR/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/IR/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/IR/CallingConv.h b/interpreter/llvm-project/llvm/include/llvm/IR/CallingConv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/CallingConv.h rename to interpreter/llvm-project/llvm/include/llvm/IR/CallingConv.h diff --git a/interpreter/llvm/src/include/llvm/IR/Comdat.h b/interpreter/llvm-project/llvm/include/llvm/IR/Comdat.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Comdat.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Comdat.h diff --git a/interpreter/llvm/src/include/llvm/IR/Constant.h b/interpreter/llvm-project/llvm/include/llvm/IR/Constant.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Constant.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Constant.h diff --git a/interpreter/llvm/src/include/llvm/IR/ConstantFolder.h b/interpreter/llvm-project/llvm/include/llvm/IR/ConstantFolder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ConstantFolder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ConstantFolder.h diff --git a/interpreter/llvm/src/include/llvm/IR/ConstantRange.h b/interpreter/llvm-project/llvm/include/llvm/IR/ConstantRange.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ConstantRange.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ConstantRange.h diff --git a/interpreter/llvm/src/include/llvm/IR/Constants.h b/interpreter/llvm-project/llvm/include/llvm/IR/Constants.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Constants.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Constants.h diff --git a/interpreter/llvm/src/include/llvm/IR/ConstrainedOps.def b/interpreter/llvm-project/llvm/include/llvm/IR/ConstrainedOps.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ConstrainedOps.def rename to interpreter/llvm-project/llvm/include/llvm/IR/ConstrainedOps.def diff --git a/interpreter/llvm/src/include/llvm/IR/DIBuilder.h b/interpreter/llvm-project/llvm/include/llvm/IR/DIBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DIBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DIBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/DataLayout.h b/interpreter/llvm-project/llvm/include/llvm/IR/DataLayout.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DataLayout.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DataLayout.h index 84f66642d95c3..300f73c12df0d 100644 --- a/interpreter/llvm/src/include/llvm/IR/DataLayout.h +++ b/interpreter/llvm-project/llvm/include/llvm/IR/DataLayout.h @@ -319,9 +319,9 @@ class DataLayout { case MM_Mips: case MM_WinCOFF: case MM_XCOFF: - case MM_WinCOFFX86: return '\0'; case MM_MachO: + case MM_WinCOFFX86: return '_'; } llvm_unreachable("invalid mangling mode"); diff --git a/interpreter/llvm/src/include/llvm/IR/DebugInfo.h b/interpreter/llvm-project/llvm/include/llvm/IR/DebugInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DebugInfo.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DebugInfo.h diff --git a/interpreter/llvm/src/include/llvm/IR/DebugInfoFlags.def b/interpreter/llvm-project/llvm/include/llvm/IR/DebugInfoFlags.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DebugInfoFlags.def rename to interpreter/llvm-project/llvm/include/llvm/IR/DebugInfoFlags.def diff --git a/interpreter/llvm/src/include/llvm/IR/DebugInfoMetadata.h b/interpreter/llvm-project/llvm/include/llvm/IR/DebugInfoMetadata.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DebugInfoMetadata.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DebugInfoMetadata.h diff --git a/interpreter/llvm/src/include/llvm/IR/DebugLoc.h b/interpreter/llvm-project/llvm/include/llvm/IR/DebugLoc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DebugLoc.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DebugLoc.h diff --git a/interpreter/llvm/src/include/llvm/IR/DerivedTypes.h b/interpreter/llvm-project/llvm/include/llvm/IR/DerivedTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DerivedTypes.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DerivedTypes.h diff --git a/interpreter/llvm/src/include/llvm/IR/DerivedUser.h b/interpreter/llvm-project/llvm/include/llvm/IR/DerivedUser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DerivedUser.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DerivedUser.h diff --git a/interpreter/llvm/src/include/llvm/IR/DiagnosticHandler.h b/interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticHandler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DiagnosticHandler.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticHandler.h diff --git a/interpreter/llvm/src/include/llvm/IR/DiagnosticInfo.h b/interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DiagnosticInfo.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticInfo.h diff --git a/interpreter/llvm/src/include/llvm/IR/DiagnosticPrinter.h b/interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/DiagnosticPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/IR/DiagnosticPrinter.h diff --git a/interpreter/llvm/src/include/llvm/IR/Dominators.h b/interpreter/llvm-project/llvm/include/llvm/IR/Dominators.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Dominators.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Dominators.h diff --git a/interpreter/llvm/src/include/llvm/IR/FPEnv.h b/interpreter/llvm-project/llvm/include/llvm/IR/FPEnv.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/FPEnv.h rename to interpreter/llvm-project/llvm/include/llvm/IR/FPEnv.h diff --git a/interpreter/llvm/src/include/llvm/IR/FixedMetadataKinds.def b/interpreter/llvm-project/llvm/include/llvm/IR/FixedMetadataKinds.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/FixedMetadataKinds.def rename to interpreter/llvm-project/llvm/include/llvm/IR/FixedMetadataKinds.def diff --git a/interpreter/llvm/src/include/llvm/IR/FixedPointBuilder.h b/interpreter/llvm-project/llvm/include/llvm/IR/FixedPointBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/FixedPointBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/FixedPointBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/Function.h b/interpreter/llvm-project/llvm/include/llvm/IR/Function.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Function.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Function.h diff --git a/interpreter/llvm/src/include/llvm/IR/GCStrategy.h b/interpreter/llvm-project/llvm/include/llvm/IR/GCStrategy.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GCStrategy.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GCStrategy.h diff --git a/interpreter/llvm/src/include/llvm/IR/GVMaterializer.h b/interpreter/llvm-project/llvm/include/llvm/IR/GVMaterializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GVMaterializer.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GVMaterializer.h diff --git a/interpreter/llvm/src/include/llvm/IR/GetElementPtrTypeIterator.h b/interpreter/llvm-project/llvm/include/llvm/IR/GetElementPtrTypeIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GetElementPtrTypeIterator.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GetElementPtrTypeIterator.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalAlias.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalAlias.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalAlias.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalAlias.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalIFunc.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalIFunc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalIFunc.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalIFunc.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalIndirectSymbol.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalIndirectSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalIndirectSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalIndirectSymbol.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalObject.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalObject.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalObject.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalObject.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalValue.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalValue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalValue.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalValue.h diff --git a/interpreter/llvm/src/include/llvm/IR/GlobalVariable.h b/interpreter/llvm-project/llvm/include/llvm/IR/GlobalVariable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/GlobalVariable.h rename to interpreter/llvm-project/llvm/include/llvm/IR/GlobalVariable.h diff --git a/interpreter/llvm/src/include/llvm/IR/IRBuilder.h b/interpreter/llvm-project/llvm/include/llvm/IR/IRBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IRBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/IRBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/IRBuilderFolder.h b/interpreter/llvm-project/llvm/include/llvm/IR/IRBuilderFolder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IRBuilderFolder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/IRBuilderFolder.h diff --git a/interpreter/llvm/src/include/llvm/IR/IRPrintingPasses.h b/interpreter/llvm-project/llvm/include/llvm/IR/IRPrintingPasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IRPrintingPasses.h rename to interpreter/llvm-project/llvm/include/llvm/IR/IRPrintingPasses.h diff --git a/interpreter/llvm/src/include/llvm/IR/InlineAsm.h b/interpreter/llvm-project/llvm/include/llvm/IR/InlineAsm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/InlineAsm.h rename to interpreter/llvm-project/llvm/include/llvm/IR/InlineAsm.h diff --git a/interpreter/llvm/src/include/llvm/IR/InstIterator.h b/interpreter/llvm-project/llvm/include/llvm/IR/InstIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/InstIterator.h rename to interpreter/llvm-project/llvm/include/llvm/IR/InstIterator.h diff --git a/interpreter/llvm/src/include/llvm/IR/InstVisitor.h b/interpreter/llvm-project/llvm/include/llvm/IR/InstVisitor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/InstVisitor.h rename to interpreter/llvm-project/llvm/include/llvm/IR/InstVisitor.h diff --git a/interpreter/llvm/src/include/llvm/IR/InstrTypes.h b/interpreter/llvm-project/llvm/include/llvm/IR/InstrTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/InstrTypes.h rename to interpreter/llvm-project/llvm/include/llvm/IR/InstrTypes.h diff --git a/interpreter/llvm/src/include/llvm/IR/Instruction.def b/interpreter/llvm-project/llvm/include/llvm/IR/Instruction.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Instruction.def rename to interpreter/llvm-project/llvm/include/llvm/IR/Instruction.def diff --git a/interpreter/llvm/src/include/llvm/IR/Instruction.h b/interpreter/llvm-project/llvm/include/llvm/IR/Instruction.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Instruction.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Instruction.h diff --git a/interpreter/llvm/src/include/llvm/IR/Instructions.h b/interpreter/llvm-project/llvm/include/llvm/IR/Instructions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Instructions.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Instructions.h diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicInst.h b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicInst.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicInst.h rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicInst.h diff --git a/interpreter/llvm/src/include/llvm/IR/Intrinsics.h b/interpreter/llvm-project/llvm/include/llvm/IR/Intrinsics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Intrinsics.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Intrinsics.h diff --git a/interpreter/llvm/src/include/llvm/IR/Intrinsics.td b/interpreter/llvm-project/llvm/include/llvm/IR/Intrinsics.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Intrinsics.td rename to interpreter/llvm-project/llvm/include/llvm/IR/Intrinsics.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsAArch64.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsAArch64.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsAArch64.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsAArch64.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsAMDGPU.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsAMDGPU.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsAMDGPU.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsAMDGPU.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsARM.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsARM.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsARM.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsARM.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsBPF.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsBPF.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsBPF.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsBPF.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsHexagon.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsHexagon.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsHexagon.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsHexagon.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsHexagonDep.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsHexagonDep.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsHexagonDep.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsHexagonDep.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsMips.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsMips.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsMips.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsMips.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsNVVM.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsNVVM.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsNVVM.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsNVVM.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsPowerPC.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsPowerPC.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsPowerPC.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsPowerPC.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsRISCV.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsRISCV.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsRISCV.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsRISCV.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsSystemZ.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsSystemZ.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsSystemZ.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsSystemZ.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsVE.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsVE.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsVE.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsVE.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsVEVL.gen.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsVEVL.gen.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsVEVL.gen.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsVEVL.gen.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsWebAssembly.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsWebAssembly.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsWebAssembly.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsWebAssembly.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsX86.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsX86.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsX86.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsX86.td diff --git a/interpreter/llvm/src/include/llvm/IR/IntrinsicsXCore.td b/interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsXCore.td similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/IntrinsicsXCore.td rename to interpreter/llvm-project/llvm/include/llvm/IR/IntrinsicsXCore.td diff --git a/interpreter/llvm/src/include/llvm/IR/LLVMContext.h b/interpreter/llvm-project/llvm/include/llvm/IR/LLVMContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/LLVMContext.h rename to interpreter/llvm-project/llvm/include/llvm/IR/LLVMContext.h diff --git a/interpreter/llvm/src/include/llvm/IR/LLVMRemarkStreamer.h b/interpreter/llvm-project/llvm/include/llvm/IR/LLVMRemarkStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/LLVMRemarkStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/IR/LLVMRemarkStreamer.h diff --git a/interpreter/llvm/src/include/llvm/IR/LegacyPassManager.h b/interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/LegacyPassManager.h rename to interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassManager.h diff --git a/interpreter/llvm/src/include/llvm/IR/LegacyPassManagers.h b/interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassManagers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/LegacyPassManagers.h rename to interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassManagers.h diff --git a/interpreter/llvm/src/include/llvm/IR/LegacyPassNameParser.h b/interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassNameParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/LegacyPassNameParser.h rename to interpreter/llvm-project/llvm/include/llvm/IR/LegacyPassNameParser.h diff --git a/interpreter/llvm/src/include/llvm/IR/MDBuilder.h b/interpreter/llvm-project/llvm/include/llvm/IR/MDBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/MDBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/MDBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/Mangler.h b/interpreter/llvm-project/llvm/include/llvm/IR/Mangler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Mangler.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Mangler.h diff --git a/interpreter/llvm/src/include/llvm/IR/MatrixBuilder.h b/interpreter/llvm-project/llvm/include/llvm/IR/MatrixBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/MatrixBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/MatrixBuilder.h diff --git a/interpreter/llvm/src/include/llvm/IR/Metadata.def b/interpreter/llvm-project/llvm/include/llvm/IR/Metadata.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Metadata.def rename to interpreter/llvm-project/llvm/include/llvm/IR/Metadata.def diff --git a/interpreter/llvm/src/include/llvm/IR/Metadata.h b/interpreter/llvm-project/llvm/include/llvm/IR/Metadata.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Metadata.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Metadata.h diff --git a/interpreter/llvm/src/include/llvm/IR/Module.h b/interpreter/llvm-project/llvm/include/llvm/IR/Module.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Module.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Module.h diff --git a/interpreter/llvm/src/include/llvm/IR/ModuleSlotTracker.h b/interpreter/llvm-project/llvm/include/llvm/IR/ModuleSlotTracker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ModuleSlotTracker.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ModuleSlotTracker.h diff --git a/interpreter/llvm/src/include/llvm/IR/ModuleSummaryIndex.h b/interpreter/llvm-project/llvm/include/llvm/IR/ModuleSummaryIndex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ModuleSummaryIndex.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ModuleSummaryIndex.h diff --git a/interpreter/llvm/src/include/llvm/IR/ModuleSummaryIndexYAML.h b/interpreter/llvm-project/llvm/include/llvm/IR/ModuleSummaryIndexYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ModuleSummaryIndexYAML.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ModuleSummaryIndexYAML.h diff --git a/interpreter/llvm/src/include/llvm/IR/NoFolder.h b/interpreter/llvm-project/llvm/include/llvm/IR/NoFolder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/NoFolder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/NoFolder.h diff --git a/interpreter/llvm/src/include/llvm/IR/OperandTraits.h b/interpreter/llvm-project/llvm/include/llvm/IR/OperandTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/OperandTraits.h rename to interpreter/llvm-project/llvm/include/llvm/IR/OperandTraits.h diff --git a/interpreter/llvm/src/include/llvm/IR/Operator.h b/interpreter/llvm-project/llvm/include/llvm/IR/Operator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Operator.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Operator.h diff --git a/interpreter/llvm/src/include/llvm/IR/OptBisect.h b/interpreter/llvm-project/llvm/include/llvm/IR/OptBisect.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/OptBisect.h rename to interpreter/llvm-project/llvm/include/llvm/IR/OptBisect.h diff --git a/interpreter/llvm/src/include/llvm/IR/PassInstrumentation.h b/interpreter/llvm-project/llvm/include/llvm/IR/PassInstrumentation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PassInstrumentation.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PassInstrumentation.h diff --git a/interpreter/llvm/src/include/llvm/IR/PassManager.h b/interpreter/llvm-project/llvm/include/llvm/IR/PassManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PassManager.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PassManager.h diff --git a/interpreter/llvm/src/include/llvm/IR/PassManagerImpl.h b/interpreter/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PassManagerImpl.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h diff --git a/interpreter/llvm/src/include/llvm/IR/PassManagerInternal.h b/interpreter/llvm-project/llvm/include/llvm/IR/PassManagerInternal.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PassManagerInternal.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PassManagerInternal.h diff --git a/interpreter/llvm/src/include/llvm/IR/PassTimingInfo.h b/interpreter/llvm-project/llvm/include/llvm/IR/PassTimingInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PassTimingInfo.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PassTimingInfo.h diff --git a/interpreter/llvm/src/include/llvm/IR/PatternMatch.h b/interpreter/llvm-project/llvm/include/llvm/IR/PatternMatch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PatternMatch.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PatternMatch.h diff --git a/interpreter/llvm/src/include/llvm/IR/PredIteratorCache.h b/interpreter/llvm-project/llvm/include/llvm/IR/PredIteratorCache.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PredIteratorCache.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PredIteratorCache.h diff --git a/interpreter/llvm/src/include/llvm/IR/PrintPasses.h b/interpreter/llvm-project/llvm/include/llvm/IR/PrintPasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PrintPasses.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PrintPasses.h diff --git a/interpreter/llvm/src/include/llvm/IR/ProfileSummary.h b/interpreter/llvm-project/llvm/include/llvm/IR/ProfileSummary.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ProfileSummary.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ProfileSummary.h diff --git a/interpreter/llvm/src/include/llvm/IR/PseudoProbe.h b/interpreter/llvm-project/llvm/include/llvm/IR/PseudoProbe.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/PseudoProbe.h rename to interpreter/llvm-project/llvm/include/llvm/IR/PseudoProbe.h diff --git a/interpreter/llvm/src/include/llvm/IR/ReplaceConstant.h b/interpreter/llvm-project/llvm/include/llvm/IR/ReplaceConstant.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ReplaceConstant.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ReplaceConstant.h diff --git a/interpreter/llvm/src/include/llvm/IR/RuntimeLibcalls.def b/interpreter/llvm-project/llvm/include/llvm/IR/RuntimeLibcalls.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/RuntimeLibcalls.def rename to interpreter/llvm-project/llvm/include/llvm/IR/RuntimeLibcalls.def diff --git a/interpreter/llvm/src/include/llvm/IR/SafepointIRVerifier.h b/interpreter/llvm-project/llvm/include/llvm/IR/SafepointIRVerifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/SafepointIRVerifier.h rename to interpreter/llvm-project/llvm/include/llvm/IR/SafepointIRVerifier.h diff --git a/interpreter/llvm/src/include/llvm/IR/Statepoint.h b/interpreter/llvm-project/llvm/include/llvm/IR/Statepoint.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Statepoint.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Statepoint.h diff --git a/interpreter/llvm/src/include/llvm/IR/StructuralHash.h b/interpreter/llvm-project/llvm/include/llvm/IR/StructuralHash.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/StructuralHash.h rename to interpreter/llvm-project/llvm/include/llvm/IR/StructuralHash.h diff --git a/interpreter/llvm/src/include/llvm/IR/SymbolTableListTraits.h b/interpreter/llvm-project/llvm/include/llvm/IR/SymbolTableListTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/SymbolTableListTraits.h rename to interpreter/llvm-project/llvm/include/llvm/IR/SymbolTableListTraits.h diff --git a/interpreter/llvm/src/include/llvm/IR/TrackingMDRef.h b/interpreter/llvm-project/llvm/include/llvm/IR/TrackingMDRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/TrackingMDRef.h rename to interpreter/llvm-project/llvm/include/llvm/IR/TrackingMDRef.h diff --git a/interpreter/llvm/src/include/llvm/IR/Type.h b/interpreter/llvm-project/llvm/include/llvm/IR/Type.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Type.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Type.h diff --git a/interpreter/llvm/src/include/llvm/IR/TypeFinder.h b/interpreter/llvm-project/llvm/include/llvm/IR/TypeFinder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/TypeFinder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/TypeFinder.h diff --git a/interpreter/llvm/src/include/llvm/IR/Use.h b/interpreter/llvm-project/llvm/include/llvm/IR/Use.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Use.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Use.h diff --git a/interpreter/llvm/src/include/llvm/IR/UseListOrder.h b/interpreter/llvm-project/llvm/include/llvm/IR/UseListOrder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/UseListOrder.h rename to interpreter/llvm-project/llvm/include/llvm/IR/UseListOrder.h diff --git a/interpreter/llvm/src/include/llvm/IR/User.h b/interpreter/llvm-project/llvm/include/llvm/IR/User.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/User.h rename to interpreter/llvm-project/llvm/include/llvm/IR/User.h diff --git a/interpreter/llvm/src/include/llvm/IR/VPIntrinsics.def b/interpreter/llvm-project/llvm/include/llvm/IR/VPIntrinsics.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/VPIntrinsics.def rename to interpreter/llvm-project/llvm/include/llvm/IR/VPIntrinsics.def diff --git a/interpreter/llvm/src/include/llvm/IR/Value.def b/interpreter/llvm-project/llvm/include/llvm/IR/Value.def similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Value.def rename to interpreter/llvm-project/llvm/include/llvm/IR/Value.def diff --git a/interpreter/llvm/src/include/llvm/IR/Value.h b/interpreter/llvm-project/llvm/include/llvm/IR/Value.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Value.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Value.h diff --git a/interpreter/llvm/src/include/llvm/IR/ValueHandle.h b/interpreter/llvm-project/llvm/include/llvm/IR/ValueHandle.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ValueHandle.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ValueHandle.h diff --git a/interpreter/llvm/src/include/llvm/IR/ValueMap.h b/interpreter/llvm-project/llvm/include/llvm/IR/ValueMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ValueMap.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ValueMap.h diff --git a/interpreter/llvm/src/include/llvm/IR/ValueSymbolTable.h b/interpreter/llvm-project/llvm/include/llvm/IR/ValueSymbolTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/ValueSymbolTable.h rename to interpreter/llvm-project/llvm/include/llvm/IR/ValueSymbolTable.h diff --git a/interpreter/llvm/src/include/llvm/IR/Verifier.h b/interpreter/llvm-project/llvm/include/llvm/IR/Verifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IR/Verifier.h rename to interpreter/llvm-project/llvm/include/llvm/IR/Verifier.h diff --git a/interpreter/llvm/src/include/llvm/IRReader/IRReader.h b/interpreter/llvm-project/llvm/include/llvm/IRReader/IRReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/IRReader/IRReader.h rename to interpreter/llvm-project/llvm/include/llvm/IRReader/IRReader.h diff --git a/interpreter/llvm/src/include/llvm/InitializePasses.h b/interpreter/llvm-project/llvm/include/llvm/InitializePasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/InitializePasses.h rename to interpreter/llvm-project/llvm/include/llvm/InitializePasses.h diff --git a/interpreter/llvm/src/include/llvm/InterfaceStub/ELFObjHandler.h b/interpreter/llvm-project/llvm/include/llvm/InterfaceStub/ELFObjHandler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/InterfaceStub/ELFObjHandler.h rename to interpreter/llvm-project/llvm/include/llvm/InterfaceStub/ELFObjHandler.h diff --git a/interpreter/llvm/src/include/llvm/InterfaceStub/IFSHandler.h b/interpreter/llvm-project/llvm/include/llvm/InterfaceStub/IFSHandler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/InterfaceStub/IFSHandler.h rename to interpreter/llvm-project/llvm/include/llvm/InterfaceStub/IFSHandler.h diff --git a/interpreter/llvm/src/include/llvm/InterfaceStub/IFSStub.h b/interpreter/llvm-project/llvm/include/llvm/InterfaceStub/IFSStub.h similarity index 100% rename from interpreter/llvm/src/include/llvm/InterfaceStub/IFSStub.h rename to interpreter/llvm-project/llvm/include/llvm/InterfaceStub/IFSStub.h diff --git a/interpreter/llvm/src/include/llvm/LTO/Caching.h b/interpreter/llvm-project/llvm/include/llvm/LTO/Caching.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/Caching.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/Caching.h diff --git a/interpreter/llvm/src/include/llvm/LTO/Config.h b/interpreter/llvm-project/llvm/include/llvm/LTO/Config.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/Config.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/Config.h diff --git a/interpreter/llvm/src/include/llvm/LTO/LTO.h b/interpreter/llvm-project/llvm/include/llvm/LTO/LTO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/LTO.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/LTO.h diff --git a/interpreter/llvm/src/include/llvm/LTO/LTOBackend.h b/interpreter/llvm-project/llvm/include/llvm/LTO/LTOBackend.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/LTOBackend.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/LTOBackend.h diff --git a/interpreter/llvm/src/include/llvm/LTO/SummaryBasedOptimizations.h b/interpreter/llvm-project/llvm/include/llvm/LTO/SummaryBasedOptimizations.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/SummaryBasedOptimizations.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/SummaryBasedOptimizations.h diff --git a/interpreter/llvm/src/include/llvm/LTO/legacy/LTOCodeGenerator.h b/interpreter/llvm-project/llvm/include/llvm/LTO/legacy/LTOCodeGenerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/legacy/LTOCodeGenerator.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/legacy/LTOCodeGenerator.h diff --git a/interpreter/llvm/src/include/llvm/LTO/legacy/LTOModule.h b/interpreter/llvm-project/llvm/include/llvm/LTO/legacy/LTOModule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/legacy/LTOModule.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/legacy/LTOModule.h diff --git a/interpreter/llvm/src/include/llvm/LTO/legacy/ThinLTOCodeGenerator.h b/interpreter/llvm-project/llvm/include/llvm/LTO/legacy/ThinLTOCodeGenerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/legacy/ThinLTOCodeGenerator.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/legacy/ThinLTOCodeGenerator.h diff --git a/interpreter/llvm/src/include/llvm/LTO/legacy/UpdateCompilerUsed.h b/interpreter/llvm-project/llvm/include/llvm/LTO/legacy/UpdateCompilerUsed.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LTO/legacy/UpdateCompilerUsed.h rename to interpreter/llvm-project/llvm/include/llvm/LTO/legacy/UpdateCompilerUsed.h diff --git a/interpreter/llvm/src/include/llvm/LineEditor/LineEditor.h b/interpreter/llvm-project/llvm/include/llvm/LineEditor/LineEditor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LineEditor/LineEditor.h rename to interpreter/llvm-project/llvm/include/llvm/LineEditor/LineEditor.h diff --git a/interpreter/llvm/src/include/llvm/LinkAllIR.h b/interpreter/llvm-project/llvm/include/llvm/LinkAllIR.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LinkAllIR.h rename to interpreter/llvm-project/llvm/include/llvm/LinkAllIR.h diff --git a/interpreter/llvm/src/include/llvm/LinkAllPasses.h b/interpreter/llvm-project/llvm/include/llvm/LinkAllPasses.h similarity index 100% rename from interpreter/llvm/src/include/llvm/LinkAllPasses.h rename to interpreter/llvm-project/llvm/include/llvm/LinkAllPasses.h diff --git a/interpreter/llvm/src/include/llvm/Linker/IRMover.h b/interpreter/llvm-project/llvm/include/llvm/Linker/IRMover.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Linker/IRMover.h rename to interpreter/llvm-project/llvm/include/llvm/Linker/IRMover.h diff --git a/interpreter/llvm/src/include/llvm/Linker/Linker.h b/interpreter/llvm-project/llvm/include/llvm/Linker/Linker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Linker/Linker.h rename to interpreter/llvm-project/llvm/include/llvm/Linker/Linker.h diff --git a/interpreter/llvm/src/include/llvm/MC/ConstantPools.h b/interpreter/llvm-project/llvm/include/llvm/MC/ConstantPools.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/ConstantPools.h rename to interpreter/llvm-project/llvm/include/llvm/MC/ConstantPools.h diff --git a/interpreter/llvm/src/include/llvm/MC/LaneBitmask.h b/interpreter/llvm-project/llvm/include/llvm/MC/LaneBitmask.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/LaneBitmask.h rename to interpreter/llvm-project/llvm/include/llvm/MC/LaneBitmask.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmBackend.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmBackend.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmBackend.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmBackend.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfoCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfoCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfoDarwin.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoDarwin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfoDarwin.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoDarwin.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfoELF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfoELF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoELF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfoWasm.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoWasm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfoWasm.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoWasm.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmInfoXCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoXCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmInfoXCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmInfoXCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmLayout.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmLayout.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmLayout.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmLayout.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAsmMacro.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAsmMacro.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAsmMacro.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAsmMacro.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCAssembler.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCAssembler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCAssembler.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCAssembler.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCCodeEmitter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCCodeEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCCodeEmitter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCCodeView.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCCodeView.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCCodeView.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCCodeView.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCContext.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCContext.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCContext.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDirectives.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDirectives.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDirectives.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDirectives.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCDisassembler.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCDisassembler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCDisassembler.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCDisassembler.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCExternalSymbolizer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCExternalSymbolizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCExternalSymbolizer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCExternalSymbolizer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCRelocationInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCRelocationInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCRelocationInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCRelocationInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCSymbolizer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCSymbolizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDisassembler/MCSymbolizer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDisassembler/MCSymbolizer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCDwarf.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCDwarf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCDwarf.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCDwarf.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCELFObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCELFObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCELFObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCELFObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCELFStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCELFStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCELFStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCELFStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCExpr.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCExpr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCExpr.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCExpr.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCFixedLenDisassembler.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCFixedLenDisassembler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCFixedLenDisassembler.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCFixedLenDisassembler.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCFixup.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCFixup.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCFixup.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCFixup.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCFixupKindInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCFixupKindInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCFixupKindInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCFixupKindInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCFragment.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCFragment.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCFragment.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCFragment.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInst.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInst.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInst.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInst.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstBuilder.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstBuilder.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstPrinter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstPrinter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstrAnalysis.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstrAnalysis.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstrAnalysis.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstrAnalysis.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstrDesc.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstrDesc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstrDesc.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstrDesc.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstrInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstrInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstrInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstrInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCInstrItineraries.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCInstrItineraries.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCInstrItineraries.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCInstrItineraries.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCLabel.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCLabel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCLabel.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCLabel.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCLinkerOptimizationHint.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCLinkerOptimizationHint.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCLinkerOptimizationHint.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCLinkerOptimizationHint.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCMachObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCMachObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCMachObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCMachObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCObjectFileInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCObjectFileInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCObjectFileInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCObjectFileInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCObjectStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCObjectStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCObjectStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCObjectStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/AsmCond.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/AsmCond.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/AsmCond.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/AsmCond.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/AsmLexer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/AsmLexer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/AsmLexer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/AsmLexer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmLexer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmLexer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmLexer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmLexer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParser.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParser.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParser.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParserExtension.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParserExtension.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParserExtension.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParserExtension.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParserUtils.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParserUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCAsmParserUtils.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCAsmParserUtils.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCParsedAsmOperand.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCParsedAsmOperand.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCParsedAsmOperand.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCParsedAsmOperand.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCParser/MCTargetAsmParser.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCTargetAsmParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCParser/MCTargetAsmParser.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCParser/MCTargetAsmParser.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCPseudoProbe.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCPseudoProbe.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCPseudoProbe.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCPseudoProbe.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCRegister.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCRegister.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCRegister.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCRegister.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCRegisterInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCRegisterInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCRegisterInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSchedule.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSchedule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSchedule.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSchedule.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSection.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSection.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSection.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSection.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionELF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionELF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionELF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionGOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionGOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionGOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionGOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionMachO.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionMachO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionMachO.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionMachO.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionWasm.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionWasm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionWasm.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionWasm.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSectionXCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSectionXCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSectionXCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSectionXCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSubtargetInfo.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSubtargetInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSubtargetInfo.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSubtargetInfo.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbol.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbol.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbol.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolELF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolELF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolELF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolGOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolGOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolGOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolGOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolMachO.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolMachO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolMachO.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolMachO.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolWasm.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolWasm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolWasm.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolWasm.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCSymbolXCOFF.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolXCOFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCSymbolXCOFF.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCSymbolXCOFF.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCTargetOptions.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCTargetOptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCTargetOptions.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCTargetOptions.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCTargetOptionsCommandFlags.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCTargetOptionsCommandFlags.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCValue.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCValue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCValue.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCValue.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWasmObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWasmObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWasmObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWasmObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWasmStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWasmStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWasmStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWasmStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWin64EH.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWin64EH.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWin64EH.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWin64EH.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWinCOFFObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWinCOFFObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWinCOFFObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWinCOFFObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWinCOFFStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWinCOFFStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWinCOFFStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWinCOFFStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCWinEH.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCWinEH.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCWinEH.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCWinEH.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCXCOFFObjectWriter.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCXCOFFObjectWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCXCOFFObjectWriter.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCXCOFFObjectWriter.h diff --git a/interpreter/llvm/src/include/llvm/MC/MCXCOFFStreamer.h b/interpreter/llvm-project/llvm/include/llvm/MC/MCXCOFFStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MCXCOFFStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MCXCOFFStreamer.h diff --git a/interpreter/llvm/src/include/llvm/MC/MachineLocation.h b/interpreter/llvm-project/llvm/include/llvm/MC/MachineLocation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/MachineLocation.h rename to interpreter/llvm-project/llvm/include/llvm/MC/MachineLocation.h diff --git a/interpreter/llvm/src/include/llvm/MC/SectionKind.h b/interpreter/llvm-project/llvm/include/llvm/MC/SectionKind.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/SectionKind.h rename to interpreter/llvm-project/llvm/include/llvm/MC/SectionKind.h diff --git a/interpreter/llvm/src/include/llvm/MC/StringTableBuilder.h b/interpreter/llvm-project/llvm/include/llvm/MC/StringTableBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/StringTableBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/MC/StringTableBuilder.h diff --git a/interpreter/llvm/src/include/llvm/MC/SubtargetFeature.h b/interpreter/llvm-project/llvm/include/llvm/MC/SubtargetFeature.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MC/SubtargetFeature.h rename to interpreter/llvm-project/llvm/include/llvm/MC/SubtargetFeature.h diff --git a/interpreter/llvm/src/include/llvm/MCA/CodeEmitter.h b/interpreter/llvm-project/llvm/include/llvm/MCA/CodeEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/CodeEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/CodeEmitter.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Context.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Context.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Context.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Context.h diff --git a/interpreter/llvm/src/include/llvm/MCA/CustomBehaviour.h b/interpreter/llvm-project/llvm/include/llvm/MCA/CustomBehaviour.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/CustomBehaviour.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/CustomBehaviour.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HWEventListener.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HWEventListener.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HWEventListener.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HWEventListener.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/HardwareUnit.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/HardwareUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/HardwareUnit.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/HardwareUnit.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/LSUnit.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/LSUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/LSUnit.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/LSUnit.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/RegisterFile.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/RegisterFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/RegisterFile.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/RegisterFile.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/ResourceManager.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/ResourceManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/ResourceManager.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/ResourceManager.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/RetireControlUnit.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/RetireControlUnit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/RetireControlUnit.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/RetireControlUnit.h diff --git a/interpreter/llvm/src/include/llvm/MCA/HardwareUnits/Scheduler.h b/interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/Scheduler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/HardwareUnits/Scheduler.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/HardwareUnits/Scheduler.h diff --git a/interpreter/llvm/src/include/llvm/MCA/InstrBuilder.h b/interpreter/llvm-project/llvm/include/llvm/MCA/InstrBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/InstrBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/InstrBuilder.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Instruction.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Instruction.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Instruction.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Instruction.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Pipeline.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Pipeline.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Pipeline.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Pipeline.h diff --git a/interpreter/llvm/src/include/llvm/MCA/SourceMgr.h b/interpreter/llvm-project/llvm/include/llvm/MCA/SourceMgr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/SourceMgr.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/SourceMgr.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/DispatchStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/DispatchStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/DispatchStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/DispatchStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/EntryStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/EntryStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/EntryStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/EntryStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/ExecuteStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/ExecuteStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/ExecuteStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/ExecuteStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/InOrderIssueStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/InOrderIssueStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/InOrderIssueStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/InOrderIssueStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/InstructionTables.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/InstructionTables.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/InstructionTables.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/InstructionTables.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/MicroOpQueueStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/MicroOpQueueStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/MicroOpQueueStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/MicroOpQueueStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/RetireStage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/RetireStage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/RetireStage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/RetireStage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Stages/Stage.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Stages/Stage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Stages/Stage.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Stages/Stage.h diff --git a/interpreter/llvm/src/include/llvm/MCA/Support.h b/interpreter/llvm-project/llvm/include/llvm/MCA/Support.h similarity index 100% rename from interpreter/llvm/src/include/llvm/MCA/Support.h rename to interpreter/llvm-project/llvm/include/llvm/MCA/Support.h diff --git a/interpreter/llvm/src/include/llvm/Object/Archive.h b/interpreter/llvm-project/llvm/include/llvm/Object/Archive.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Archive.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Archive.h diff --git a/interpreter/llvm/src/include/llvm/Object/ArchiveWriter.h b/interpreter/llvm-project/llvm/include/llvm/Object/ArchiveWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ArchiveWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ArchiveWriter.h diff --git a/interpreter/llvm/src/include/llvm/Object/Binary.h b/interpreter/llvm-project/llvm/include/llvm/Object/Binary.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Binary.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Binary.h diff --git a/interpreter/llvm/src/include/llvm/Object/COFF.h b/interpreter/llvm-project/llvm/include/llvm/Object/COFF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/COFF.h rename to interpreter/llvm-project/llvm/include/llvm/Object/COFF.h diff --git a/interpreter/llvm/src/include/llvm/Object/COFFImportFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/COFFImportFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/COFFImportFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/COFFImportFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/COFFModuleDefinition.h b/interpreter/llvm-project/llvm/include/llvm/Object/COFFModuleDefinition.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/COFFModuleDefinition.h rename to interpreter/llvm-project/llvm/include/llvm/Object/COFFModuleDefinition.h diff --git a/interpreter/llvm/src/include/llvm/Object/CVDebugRecord.h b/interpreter/llvm-project/llvm/include/llvm/Object/CVDebugRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/CVDebugRecord.h rename to interpreter/llvm-project/llvm/include/llvm/Object/CVDebugRecord.h diff --git a/interpreter/llvm/src/include/llvm/Object/Decompressor.h b/interpreter/llvm-project/llvm/include/llvm/Object/Decompressor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Decompressor.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Decompressor.h diff --git a/interpreter/llvm/src/include/llvm/Object/ELF.h b/interpreter/llvm-project/llvm/include/llvm/Object/ELF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ELF.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ELF.h diff --git a/interpreter/llvm/src/include/llvm/Object/ELFObjectFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/ELFObjectFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ELFObjectFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ELFObjectFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/ELFTypes.h b/interpreter/llvm-project/llvm/include/llvm/Object/ELFTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ELFTypes.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ELFTypes.h diff --git a/interpreter/llvm/src/include/llvm/Object/Error.h b/interpreter/llvm-project/llvm/include/llvm/Object/Error.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Error.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Error.h diff --git a/interpreter/llvm/src/include/llvm/Object/FaultMapParser.h b/interpreter/llvm-project/llvm/include/llvm/Object/FaultMapParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/FaultMapParser.h rename to interpreter/llvm-project/llvm/include/llvm/Object/FaultMapParser.h diff --git a/interpreter/llvm/src/include/llvm/Object/IRObjectFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/IRObjectFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/IRObjectFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/IRObjectFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/IRSymtab.h b/interpreter/llvm-project/llvm/include/llvm/Object/IRSymtab.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/IRSymtab.h rename to interpreter/llvm-project/llvm/include/llvm/Object/IRSymtab.h diff --git a/interpreter/llvm/src/include/llvm/Object/MachO.h b/interpreter/llvm-project/llvm/include/llvm/Object/MachO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/MachO.h rename to interpreter/llvm-project/llvm/include/llvm/Object/MachO.h diff --git a/interpreter/llvm/src/include/llvm/Object/MachOUniversal.h b/interpreter/llvm-project/llvm/include/llvm/Object/MachOUniversal.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/MachOUniversal.h rename to interpreter/llvm-project/llvm/include/llvm/Object/MachOUniversal.h diff --git a/interpreter/llvm/src/include/llvm/Object/MachOUniversalWriter.h b/interpreter/llvm-project/llvm/include/llvm/Object/MachOUniversalWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/MachOUniversalWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Object/MachOUniversalWriter.h diff --git a/interpreter/llvm/src/include/llvm/Object/Minidump.h b/interpreter/llvm-project/llvm/include/llvm/Object/Minidump.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Minidump.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Minidump.h diff --git a/interpreter/llvm/src/include/llvm/Object/ModuleSymbolTable.h b/interpreter/llvm-project/llvm/include/llvm/Object/ModuleSymbolTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ModuleSymbolTable.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ModuleSymbolTable.h diff --git a/interpreter/llvm/src/include/llvm/Object/ObjectFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/ObjectFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/ObjectFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/ObjectFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/RelocationResolver.h b/interpreter/llvm-project/llvm/include/llvm/Object/RelocationResolver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/RelocationResolver.h rename to interpreter/llvm-project/llvm/include/llvm/Object/RelocationResolver.h diff --git a/interpreter/llvm/src/include/llvm/Object/StackMapParser.h b/interpreter/llvm-project/llvm/include/llvm/Object/StackMapParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/StackMapParser.h rename to interpreter/llvm-project/llvm/include/llvm/Object/StackMapParser.h diff --git a/interpreter/llvm/src/include/llvm/Object/SymbolSize.h b/interpreter/llvm-project/llvm/include/llvm/Object/SymbolSize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/SymbolSize.h rename to interpreter/llvm-project/llvm/include/llvm/Object/SymbolSize.h diff --git a/interpreter/llvm/src/include/llvm/Object/SymbolicFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/SymbolicFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/SymbolicFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/SymbolicFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/TapiFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/TapiFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/TapiFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/TapiFile.h diff --git a/interpreter/llvm/src/include/llvm/Object/TapiUniversal.h b/interpreter/llvm-project/llvm/include/llvm/Object/TapiUniversal.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/TapiUniversal.h rename to interpreter/llvm-project/llvm/include/llvm/Object/TapiUniversal.h diff --git a/interpreter/llvm/src/include/llvm/Object/Wasm.h b/interpreter/llvm-project/llvm/include/llvm/Object/Wasm.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/Wasm.h rename to interpreter/llvm-project/llvm/include/llvm/Object/Wasm.h diff --git a/interpreter/llvm/src/include/llvm/Object/WindowsMachineFlag.h b/interpreter/llvm-project/llvm/include/llvm/Object/WindowsMachineFlag.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/WindowsMachineFlag.h rename to interpreter/llvm-project/llvm/include/llvm/Object/WindowsMachineFlag.h diff --git a/interpreter/llvm/src/include/llvm/Object/WindowsResource.h b/interpreter/llvm-project/llvm/include/llvm/Object/WindowsResource.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/WindowsResource.h rename to interpreter/llvm-project/llvm/include/llvm/Object/WindowsResource.h diff --git a/interpreter/llvm/src/include/llvm/Object/XCOFFObjectFile.h b/interpreter/llvm-project/llvm/include/llvm/Object/XCOFFObjectFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Object/XCOFFObjectFile.h rename to interpreter/llvm-project/llvm/include/llvm/Object/XCOFFObjectFile.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/ArchiveYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ArchiveYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/ArchiveYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ArchiveYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/COFFYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/COFFYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/COFFYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/COFFYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLDebugSections.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLDebugSections.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLDebugSections.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLDebugSections.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLSymbols.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLSymbols.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLSymbols.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLSymbols.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLTypeHashing.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLTypeHashing.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLTypeHashing.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLTypeHashing.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLTypes.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/CodeViewYAMLTypes.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/CodeViewYAMLTypes.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/DWARFEmitter.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/DWARFEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/DWARFEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/DWARFEmitter.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/DWARFYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/DWARFYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/DWARFYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/DWARFYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/ELFYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ELFYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/ELFYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ELFYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/MachOYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/MachOYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/MachOYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/MachOYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/MinidumpYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/MinidumpYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/MinidumpYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/MinidumpYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/ObjectYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ObjectYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/ObjectYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/ObjectYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/WasmYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/WasmYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/WasmYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/WasmYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/XCOFFYAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/XCOFFYAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/XCOFFYAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/XCOFFYAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/YAML.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/YAML.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/YAML.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/YAML.h diff --git a/interpreter/llvm/src/include/llvm/ObjectYAML/yaml2obj.h b/interpreter/llvm-project/llvm/include/llvm/ObjectYAML/yaml2obj.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ObjectYAML/yaml2obj.h rename to interpreter/llvm-project/llvm/include/llvm/ObjectYAML/yaml2obj.h diff --git a/interpreter/llvm/src/include/llvm/Option/Arg.h b/interpreter/llvm-project/llvm/include/llvm/Option/Arg.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/Arg.h rename to interpreter/llvm-project/llvm/include/llvm/Option/Arg.h diff --git a/interpreter/llvm/src/include/llvm/Option/ArgList.h b/interpreter/llvm-project/llvm/include/llvm/Option/ArgList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/ArgList.h rename to interpreter/llvm-project/llvm/include/llvm/Option/ArgList.h diff --git a/interpreter/llvm/src/include/llvm/Option/OptParser.td b/interpreter/llvm-project/llvm/include/llvm/Option/OptParser.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/OptParser.td rename to interpreter/llvm-project/llvm/include/llvm/Option/OptParser.td diff --git a/interpreter/llvm/src/include/llvm/Option/OptSpecifier.h b/interpreter/llvm-project/llvm/include/llvm/Option/OptSpecifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/OptSpecifier.h rename to interpreter/llvm-project/llvm/include/llvm/Option/OptSpecifier.h diff --git a/interpreter/llvm/src/include/llvm/Option/OptTable.h b/interpreter/llvm-project/llvm/include/llvm/Option/OptTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/OptTable.h rename to interpreter/llvm-project/llvm/include/llvm/Option/OptTable.h diff --git a/interpreter/llvm/src/include/llvm/Option/Option.h b/interpreter/llvm-project/llvm/include/llvm/Option/Option.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Option/Option.h rename to interpreter/llvm-project/llvm/include/llvm/Option/Option.h diff --git a/interpreter/llvm/src/include/llvm/Pass.h b/interpreter/llvm-project/llvm/include/llvm/Pass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Pass.h rename to interpreter/llvm-project/llvm/include/llvm/Pass.h diff --git a/interpreter/llvm/src/include/llvm/PassAnalysisSupport.h b/interpreter/llvm-project/llvm/include/llvm/PassAnalysisSupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/PassAnalysisSupport.h rename to interpreter/llvm-project/llvm/include/llvm/PassAnalysisSupport.h diff --git a/interpreter/llvm/src/include/llvm/PassInfo.h b/interpreter/llvm-project/llvm/include/llvm/PassInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/PassInfo.h rename to interpreter/llvm-project/llvm/include/llvm/PassInfo.h diff --git a/interpreter/llvm/src/include/llvm/PassRegistry.h b/interpreter/llvm-project/llvm/include/llvm/PassRegistry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/PassRegistry.h rename to interpreter/llvm-project/llvm/include/llvm/PassRegistry.h diff --git a/interpreter/llvm/src/include/llvm/PassSupport.h b/interpreter/llvm-project/llvm/include/llvm/PassSupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/PassSupport.h rename to interpreter/llvm-project/llvm/include/llvm/PassSupport.h diff --git a/interpreter/llvm/src/include/llvm/Passes/PassBuilder.h b/interpreter/llvm-project/llvm/include/llvm/Passes/PassBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Passes/PassBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/Passes/PassBuilder.h diff --git a/interpreter/llvm/src/include/llvm/Passes/PassPlugin.h b/interpreter/llvm-project/llvm/include/llvm/Passes/PassPlugin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Passes/PassPlugin.h rename to interpreter/llvm-project/llvm/include/llvm/Passes/PassPlugin.h diff --git a/interpreter/llvm/src/include/llvm/Passes/StandardInstrumentations.h b/interpreter/llvm-project/llvm/include/llvm/Passes/StandardInstrumentations.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Passes/StandardInstrumentations.h rename to interpreter/llvm-project/llvm/include/llvm/Passes/StandardInstrumentations.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMapping.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMapping.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMappingReader.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMappingReader.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/GCOV.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/GCOV.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/GCOV.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/GCOV.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/InstrProf.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/InstrProf.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProf.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/InstrProfData.inc b/interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfData.inc similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/InstrProfData.inc rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfData.inc diff --git a/interpreter/llvm/src/include/llvm/ProfileData/InstrProfReader.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/InstrProfReader.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfReader.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/InstrProfWriter.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/InstrProfWriter.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/InstrProfWriter.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/ProfileCommon.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/ProfileCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/ProfileCommon.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/ProfileCommon.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/SampleProf.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/SampleProf.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProf.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/SampleProfReader.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProfReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/SampleProfReader.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProfReader.h diff --git a/interpreter/llvm/src/include/llvm/ProfileData/SampleProfWriter.h b/interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProfWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ProfileData/SampleProfWriter.h rename to interpreter/llvm-project/llvm/include/llvm/ProfileData/SampleProfWriter.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkContainer.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkContainer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkContainer.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkContainer.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkParser.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkParser.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkParser.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkSerializer.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkSerializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/BitstreamRemarkSerializer.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/BitstreamRemarkSerializer.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/HotnessThresholdParser.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/HotnessThresholdParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/HotnessThresholdParser.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/HotnessThresholdParser.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/Remark.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/Remark.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/Remark.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/Remark.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkFormat.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkFormat.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkFormat.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkFormat.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkLinker.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkLinker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkLinker.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkLinker.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkParser.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkParser.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkParser.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkSerializer.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkSerializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkSerializer.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkSerializer.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkStreamer.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkStreamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkStreamer.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkStreamer.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/RemarkStringTable.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkStringTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/RemarkStringTable.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/RemarkStringTable.h diff --git a/interpreter/llvm/src/include/llvm/Remarks/YAMLRemarkSerializer.h b/interpreter/llvm-project/llvm/include/llvm/Remarks/YAMLRemarkSerializer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Remarks/YAMLRemarkSerializer.h rename to interpreter/llvm-project/llvm/include/llvm/Remarks/YAMLRemarkSerializer.h diff --git a/interpreter/llvm/src/include/llvm/Support/AArch64TargetParser.def b/interpreter/llvm-project/llvm/include/llvm/Support/AArch64TargetParser.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AArch64TargetParser.def rename to interpreter/llvm-project/llvm/include/llvm/Support/AArch64TargetParser.def diff --git a/interpreter/llvm/src/include/llvm/Support/AArch64TargetParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/AArch64TargetParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AArch64TargetParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AArch64TargetParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/AMDGPUMetadata.h b/interpreter/llvm-project/llvm/include/llvm/Support/AMDGPUMetadata.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AMDGPUMetadata.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AMDGPUMetadata.h diff --git a/interpreter/llvm/src/include/llvm/Support/AMDHSAKernelDescriptor.h b/interpreter/llvm-project/llvm/include/llvm/Support/AMDHSAKernelDescriptor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AMDHSAKernelDescriptor.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AMDHSAKernelDescriptor.h diff --git a/interpreter/llvm/src/include/llvm/Support/ARMAttributeParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/ARMAttributeParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMAttributeParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMAttributeParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/ARMBuildAttributes.h b/interpreter/llvm-project/llvm/include/llvm/Support/ARMBuildAttributes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMBuildAttributes.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMBuildAttributes.h diff --git a/interpreter/llvm/src/include/llvm/Support/ARMEHABI.h b/interpreter/llvm-project/llvm/include/llvm/Support/ARMEHABI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMEHABI.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMEHABI.h diff --git a/interpreter/llvm/src/include/llvm/Support/ARMTargetParser.def b/interpreter/llvm-project/llvm/include/llvm/Support/ARMTargetParser.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMTargetParser.def rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMTargetParser.def diff --git a/interpreter/llvm/src/include/llvm/Support/ARMTargetParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/ARMTargetParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMTargetParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMTargetParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/ARMWinEH.h b/interpreter/llvm-project/llvm/include/llvm/Support/ARMWinEH.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ARMWinEH.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ARMWinEH.h diff --git a/interpreter/llvm/src/include/llvm/Support/AlignOf.h b/interpreter/llvm-project/llvm/include/llvm/Support/AlignOf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AlignOf.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AlignOf.h diff --git a/interpreter/llvm/src/include/llvm/Support/Alignment.h b/interpreter/llvm-project/llvm/include/llvm/Support/Alignment.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Alignment.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Alignment.h diff --git a/interpreter/llvm/src/include/llvm/Support/Allocator.h b/interpreter/llvm-project/llvm/include/llvm/Support/Allocator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Allocator.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Allocator.h diff --git a/interpreter/llvm/src/include/llvm/Support/AllocatorBase.h b/interpreter/llvm-project/llvm/include/llvm/Support/AllocatorBase.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AllocatorBase.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AllocatorBase.h diff --git a/interpreter/llvm/src/include/llvm/Support/ArrayRecycler.h b/interpreter/llvm-project/llvm/include/llvm/Support/ArrayRecycler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ArrayRecycler.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ArrayRecycler.h diff --git a/interpreter/llvm/src/include/llvm/Support/Atomic.h b/interpreter/llvm-project/llvm/include/llvm/Support/Atomic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Atomic.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Atomic.h diff --git a/interpreter/llvm/src/include/llvm/Support/AtomicOrdering.h b/interpreter/llvm-project/llvm/include/llvm/Support/AtomicOrdering.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AtomicOrdering.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AtomicOrdering.h diff --git a/interpreter/llvm/src/include/llvm/Support/AutoConvert.h b/interpreter/llvm-project/llvm/include/llvm/Support/AutoConvert.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/AutoConvert.h rename to interpreter/llvm-project/llvm/include/llvm/Support/AutoConvert.h diff --git a/interpreter/llvm/src/include/llvm/Support/Automaton.h b/interpreter/llvm-project/llvm/include/llvm/Support/Automaton.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Automaton.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Automaton.h diff --git a/interpreter/llvm/src/include/llvm/Support/BCD.h b/interpreter/llvm-project/llvm/include/llvm/Support/BCD.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BCD.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BCD.h diff --git a/interpreter/llvm/src/include/llvm/Support/Base64.h b/interpreter/llvm-project/llvm/include/llvm/Support/Base64.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Base64.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Base64.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryByteStream.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryByteStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryByteStream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryByteStream.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryItemStream.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryItemStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryItemStream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryItemStream.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStream.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryStream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStream.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStreamArray.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamArray.h similarity index 99% rename from interpreter/llvm/src/include/llvm/Support/BinaryStreamArray.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamArray.h index 148ab85169f28..3d4ee46b9e7b5 100644 --- a/interpreter/llvm/src/include/llvm/Support/BinaryStreamArray.h +++ b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamArray.h @@ -328,7 +328,7 @@ class FixedStreamArrayIterator FixedStreamArrayIterator(const FixedStreamArray &Array, uint32_t Index) : Array(Array), Index(Index) {} - FixedStreamArrayIterator(const FixedStreamArrayIterator &Other) + FixedStreamArrayIterator(const FixedStreamArrayIterator &Other) : Array(Other.Array), Index(Other.Index) {} FixedStreamArrayIterator & operator=(const FixedStreamArrayIterator &Other) { diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStreamError.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryStreamError.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamError.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStreamReader.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryStreamReader.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamReader.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStreamRef.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryStreamRef.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamRef.h diff --git a/interpreter/llvm/src/include/llvm/Support/BinaryStreamWriter.h b/interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BinaryStreamWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BinaryStreamWriter.h diff --git a/interpreter/llvm/src/include/llvm/Support/BlockFrequency.h b/interpreter/llvm-project/llvm/include/llvm/Support/BlockFrequency.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BlockFrequency.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BlockFrequency.h diff --git a/interpreter/llvm/src/include/llvm/Support/BranchProbability.h b/interpreter/llvm-project/llvm/include/llvm/Support/BranchProbability.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BranchProbability.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BranchProbability.h diff --git a/interpreter/llvm/src/include/llvm/Support/BuryPointer.h b/interpreter/llvm-project/llvm/include/llvm/Support/BuryPointer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/BuryPointer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/BuryPointer.h diff --git a/interpreter/llvm/src/include/llvm/Support/CBindingWrapping.h b/interpreter/llvm-project/llvm/include/llvm/Support/CBindingWrapping.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CBindingWrapping.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CBindingWrapping.h diff --git a/interpreter/llvm/src/include/llvm/Support/CFGDiff.h b/interpreter/llvm-project/llvm/include/llvm/Support/CFGDiff.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CFGDiff.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CFGDiff.h diff --git a/interpreter/llvm/src/include/llvm/Support/CFGUpdate.h b/interpreter/llvm-project/llvm/include/llvm/Support/CFGUpdate.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CFGUpdate.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CFGUpdate.h diff --git a/interpreter/llvm/src/include/llvm/Support/CMakeLists.txt b/interpreter/llvm-project/llvm/include/llvm/Support/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CMakeLists.txt rename to interpreter/llvm-project/llvm/include/llvm/Support/CMakeLists.txt diff --git a/interpreter/llvm/src/include/llvm/Support/COM.h b/interpreter/llvm-project/llvm/include/llvm/Support/COM.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/COM.h rename to interpreter/llvm-project/llvm/include/llvm/Support/COM.h diff --git a/interpreter/llvm/src/include/llvm/Support/CRC.h b/interpreter/llvm-project/llvm/include/llvm/Support/CRC.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CRC.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CRC.h diff --git a/interpreter/llvm/src/include/llvm/Support/CachePruning.h b/interpreter/llvm-project/llvm/include/llvm/Support/CachePruning.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CachePruning.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CachePruning.h diff --git a/interpreter/llvm/src/include/llvm/Support/Capacity.h b/interpreter/llvm-project/llvm/include/llvm/Support/Capacity.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Capacity.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Capacity.h diff --git a/interpreter/llvm/src/include/llvm/Support/Casting.h b/interpreter/llvm-project/llvm/include/llvm/Support/Casting.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Casting.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Casting.h diff --git a/interpreter/llvm/src/include/llvm/Support/CheckedArithmetic.h b/interpreter/llvm-project/llvm/include/llvm/Support/CheckedArithmetic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CheckedArithmetic.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CheckedArithmetic.h diff --git a/interpreter/llvm/src/include/llvm/Support/Chrono.h b/interpreter/llvm-project/llvm/include/llvm/Support/Chrono.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Chrono.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Chrono.h diff --git a/interpreter/llvm/src/include/llvm/Support/CodeGen.h b/interpreter/llvm-project/llvm/include/llvm/Support/CodeGen.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CodeGen.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CodeGen.h diff --git a/interpreter/llvm/src/include/llvm/Support/CodeGenCoverage.h b/interpreter/llvm-project/llvm/include/llvm/Support/CodeGenCoverage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CodeGenCoverage.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CodeGenCoverage.h diff --git a/interpreter/llvm/src/include/llvm/Support/CommandLine.h b/interpreter/llvm-project/llvm/include/llvm/Support/CommandLine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CommandLine.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CommandLine.h diff --git a/interpreter/llvm/src/include/llvm/Support/Compiler.h b/interpreter/llvm-project/llvm/include/llvm/Support/Compiler.h similarity index 99% rename from interpreter/llvm/src/include/llvm/Support/Compiler.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Compiler.h index 57052b596edbe..8a6dbe4c7afc0 100644 --- a/interpreter/llvm/src/include/llvm/Support/Compiler.h +++ b/interpreter/llvm-project/llvm/include/llvm/Support/Compiler.h @@ -126,7 +126,11 @@ #if (__has_attribute(visibility) || LLVM_GNUC_PREREQ(4, 0, 0)) && \ !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(_WIN32) #define LLVM_LIBRARY_VISIBILITY __attribute__ ((visibility("hidden"))) -#define LLVM_EXTERNAL_VISIBILITY __attribute__ ((visibility("default"))) +#if defined(LLVM_BUILD_LLVM_DYLIB) || defined(LLVM_BUILD_SHARED_LIBS) +#define LLVM_EXTERNAL_VISIBILITY __attribute__((visibility("default"))) +#else +#define LLVM_EXTERNAL_VISIBILITY +#endif #else #define LLVM_LIBRARY_VISIBILITY #define LLVM_EXTERNAL_VISIBILITY diff --git a/interpreter/llvm/src/include/llvm/Support/Compression.h b/interpreter/llvm-project/llvm/include/llvm/Support/Compression.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Compression.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Compression.h diff --git a/interpreter/llvm/src/include/llvm/Support/ConvertUTF.h b/interpreter/llvm-project/llvm/include/llvm/Support/ConvertUTF.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ConvertUTF.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ConvertUTF.h diff --git a/interpreter/llvm/src/include/llvm/Support/CrashRecoveryContext.h b/interpreter/llvm-project/llvm/include/llvm/Support/CrashRecoveryContext.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/CrashRecoveryContext.h rename to interpreter/llvm-project/llvm/include/llvm/Support/CrashRecoveryContext.h diff --git a/interpreter/llvm/src/include/llvm/Support/DJB.h b/interpreter/llvm-project/llvm/include/llvm/Support/DJB.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DJB.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DJB.h diff --git a/interpreter/llvm/src/include/llvm/Support/DOTGraphTraits.h b/interpreter/llvm-project/llvm/include/llvm/Support/DOTGraphTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DOTGraphTraits.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DOTGraphTraits.h diff --git a/interpreter/llvm/src/include/llvm/Support/DataExtractor.h b/interpreter/llvm-project/llvm/include/llvm/Support/DataExtractor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DataExtractor.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DataExtractor.h diff --git a/interpreter/llvm/src/include/llvm/Support/DataTypes.h b/interpreter/llvm-project/llvm/include/llvm/Support/DataTypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DataTypes.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DataTypes.h diff --git a/interpreter/llvm/src/include/llvm/Support/Debug.h b/interpreter/llvm-project/llvm/include/llvm/Support/Debug.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Debug.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Debug.h diff --git a/interpreter/llvm/src/include/llvm/Support/DebugCounter.h b/interpreter/llvm-project/llvm/include/llvm/Support/DebugCounter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DebugCounter.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DebugCounter.h diff --git a/interpreter/llvm/src/include/llvm/Support/Discriminator.h b/interpreter/llvm-project/llvm/include/llvm/Support/Discriminator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Discriminator.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Discriminator.h diff --git a/interpreter/llvm/src/include/llvm/Support/DynamicLibrary.h b/interpreter/llvm-project/llvm/include/llvm/Support/DynamicLibrary.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/DynamicLibrary.h rename to interpreter/llvm-project/llvm/include/llvm/Support/DynamicLibrary.h diff --git a/interpreter/llvm/src/include/llvm/Support/ELFAttributeParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/ELFAttributeParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ELFAttributeParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ELFAttributeParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/ELFAttributes.h b/interpreter/llvm-project/llvm/include/llvm/Support/ELFAttributes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ELFAttributes.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ELFAttributes.h diff --git a/interpreter/llvm/src/include/llvm/Support/Endian.h b/interpreter/llvm-project/llvm/include/llvm/Support/Endian.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Endian.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Endian.h diff --git a/interpreter/llvm/src/include/llvm/Support/EndianStream.h b/interpreter/llvm-project/llvm/include/llvm/Support/EndianStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/EndianStream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/EndianStream.h diff --git a/interpreter/llvm/src/include/llvm/Support/Errc.h b/interpreter/llvm-project/llvm/include/llvm/Support/Errc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Errc.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Errc.h diff --git a/interpreter/llvm/src/include/llvm/Support/Errno.h b/interpreter/llvm-project/llvm/include/llvm/Support/Errno.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Errno.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Errno.h diff --git a/interpreter/llvm/src/include/llvm/Support/Error.h b/interpreter/llvm-project/llvm/include/llvm/Support/Error.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Error.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Error.h diff --git a/interpreter/llvm/src/include/llvm/Support/ErrorHandling.h b/interpreter/llvm-project/llvm/include/llvm/Support/ErrorHandling.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ErrorHandling.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ErrorHandling.h diff --git a/interpreter/llvm/src/include/llvm/Support/ErrorOr.h b/interpreter/llvm-project/llvm/include/llvm/Support/ErrorOr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ErrorOr.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ErrorOr.h diff --git a/interpreter/llvm/src/include/llvm/Support/ExitCodes.h b/interpreter/llvm-project/llvm/include/llvm/Support/ExitCodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ExitCodes.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ExitCodes.h diff --git a/interpreter/llvm/src/include/llvm/Support/ExtensibleRTTI.h b/interpreter/llvm-project/llvm/include/llvm/Support/ExtensibleRTTI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ExtensibleRTTI.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ExtensibleRTTI.h diff --git a/interpreter/llvm/src/include/llvm/Support/FileCollector.h b/interpreter/llvm-project/llvm/include/llvm/Support/FileCollector.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FileCollector.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FileCollector.h diff --git a/interpreter/llvm/src/include/llvm/Support/FileOutputBuffer.h b/interpreter/llvm-project/llvm/include/llvm/Support/FileOutputBuffer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FileOutputBuffer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FileOutputBuffer.h diff --git a/interpreter/llvm/src/include/llvm/Support/FileSystem.h b/interpreter/llvm-project/llvm/include/llvm/Support/FileSystem.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FileSystem.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FileSystem.h diff --git a/interpreter/llvm/src/include/llvm/Support/FileSystem/UniqueID.h b/interpreter/llvm-project/llvm/include/llvm/Support/FileSystem/UniqueID.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FileSystem/UniqueID.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FileSystem/UniqueID.h diff --git a/interpreter/llvm/src/include/llvm/Support/FileUtilities.h b/interpreter/llvm-project/llvm/include/llvm/Support/FileUtilities.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FileUtilities.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FileUtilities.h diff --git a/interpreter/llvm/src/include/llvm/Support/Format.h b/interpreter/llvm-project/llvm/include/llvm/Support/Format.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Format.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Format.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormatAdapters.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormatAdapters.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormatAdapters.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormatAdapters.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormatCommon.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormatCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormatCommon.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormatCommon.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormatProviders.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormatProviders.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormatProviders.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormatProviders.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormatVariadic.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormatVariadic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormatVariadic.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormatVariadic.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormatVariadicDetails.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormatVariadicDetails.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormatVariadicDetails.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormatVariadicDetails.h diff --git a/interpreter/llvm/src/include/llvm/Support/FormattedStream.h b/interpreter/llvm-project/llvm/include/llvm/Support/FormattedStream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/FormattedStream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/FormattedStream.h diff --git a/interpreter/llvm/src/include/llvm/Support/GenericDomTree.h b/interpreter/llvm-project/llvm/include/llvm/Support/GenericDomTree.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/GenericDomTree.h rename to interpreter/llvm-project/llvm/include/llvm/Support/GenericDomTree.h diff --git a/interpreter/llvm/src/include/llvm/Support/GenericDomTreeConstruction.h b/interpreter/llvm-project/llvm/include/llvm/Support/GenericDomTreeConstruction.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/GenericDomTreeConstruction.h rename to interpreter/llvm-project/llvm/include/llvm/Support/GenericDomTreeConstruction.h diff --git a/interpreter/llvm/src/include/llvm/Support/GenericIteratedDominanceFrontier.h b/interpreter/llvm-project/llvm/include/llvm/Support/GenericIteratedDominanceFrontier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/GenericIteratedDominanceFrontier.h rename to interpreter/llvm-project/llvm/include/llvm/Support/GenericIteratedDominanceFrontier.h diff --git a/interpreter/llvm/src/include/llvm/Support/GlobPattern.h b/interpreter/llvm-project/llvm/include/llvm/Support/GlobPattern.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/GlobPattern.h rename to interpreter/llvm-project/llvm/include/llvm/Support/GlobPattern.h diff --git a/interpreter/llvm/src/include/llvm/Support/GraphWriter.h b/interpreter/llvm-project/llvm/include/llvm/Support/GraphWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/GraphWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Support/GraphWriter.h diff --git a/interpreter/llvm/src/include/llvm/Support/Host.h b/interpreter/llvm-project/llvm/include/llvm/Support/Host.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Host.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Host.h diff --git a/interpreter/llvm/src/include/llvm/Support/InitLLVM.h b/interpreter/llvm-project/llvm/include/llvm/Support/InitLLVM.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/InitLLVM.h rename to interpreter/llvm-project/llvm/include/llvm/Support/InitLLVM.h diff --git a/interpreter/llvm/src/include/llvm/Support/InstructionCost.h b/interpreter/llvm-project/llvm/include/llvm/Support/InstructionCost.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/InstructionCost.h rename to interpreter/llvm-project/llvm/include/llvm/Support/InstructionCost.h diff --git a/interpreter/llvm/src/include/llvm/Support/ItaniumManglingCanonicalizer.h b/interpreter/llvm-project/llvm/include/llvm/Support/ItaniumManglingCanonicalizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ItaniumManglingCanonicalizer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ItaniumManglingCanonicalizer.h diff --git a/interpreter/llvm/src/include/llvm/Support/JSON.h b/interpreter/llvm-project/llvm/include/llvm/Support/JSON.h similarity index 92% rename from interpreter/llvm/src/include/llvm/Support/JSON.h rename to interpreter/llvm-project/llvm/include/llvm/Support/JSON.h index c753cee60ec12..f752788472458 100644 --- a/interpreter/llvm/src/include/llvm/Support/JSON.h +++ b/interpreter/llvm-project/llvm/include/llvm/Support/JSON.h @@ -168,44 +168,36 @@ class Array { emplace_back(V); } - Value &operator[](size_t I) { return V[I]; } - const Value &operator[](size_t I) const { return V[I]; } - Value &front() { return V.front(); } - const Value &front() const { return V.front(); } - Value &back() { return V.back(); } - const Value &back() const { return V.back(); } - Value *data() { return V.data(); } - const Value *data() const { return V.data(); } - - iterator begin() { return V.begin(); } - const_iterator begin() const { return V.begin(); } - iterator end() { return V.end(); } - const_iterator end() const { return V.end(); } - - bool empty() const { return V.empty(); } - size_t size() const { return V.size(); } - void reserve(size_t S) { V.reserve(S); } - - void clear() { V.clear(); } - void push_back(const Value &E) { V.push_back(E); } - void push_back(Value &&E) { V.push_back(std::move(E)); } - template void emplace_back(Args &&... A) { - V.emplace_back(std::forward(A)...); - } - void pop_back() { V.pop_back(); } + Value &operator[](size_t I); + const Value &operator[](size_t I) const; + Value &front(); + const Value &front() const; + Value &back(); + const Value &back() const; + Value *data(); + const Value *data() const; + + iterator begin(); + const_iterator begin() const; + iterator end(); + const_iterator end() const; + + bool empty() const; + size_t size() const; + void reserve(size_t S); + + void clear(); + void push_back(const Value &E); + void push_back(Value &&E); + template void emplace_back(Args &&...A); + void pop_back(); // FIXME: insert() takes const_iterator since C++11, old libstdc++ disagrees. - iterator insert(iterator P, const Value &E) { return V.insert(P, E); } - iterator insert(iterator P, Value &&E) { - return V.insert(P, std::move(E)); - } - template iterator insert(iterator P, It A, It Z) { - return V.insert(P, A, Z); - } - template iterator emplace(const_iterator P, Args &&... A) { - return V.emplace(P, std::forward(A)...); - } + iterator insert(iterator P, const Value &E); + iterator insert(iterator P, Value &&E); + template iterator insert(iterator P, It A, It Z); + template iterator emplace(const_iterator P, Args &&...A); - friend bool operator==(const Array &L, const Array &R) { return L.V == R.V; } + friend bool operator==(const Array &L, const Array &R); }; inline bool operator!=(const Array &L, const Array &R) { return !(L == R); } @@ -488,6 +480,48 @@ class Value { bool operator==(const Value &, const Value &); inline bool operator!=(const Value &L, const Value &R) { return !(L == R); } +// Array Methods +inline Value &Array::operator[](size_t I) { return V[I]; } +inline const Value &Array::operator[](size_t I) const { return V[I]; } +inline Value &Array::front() { return V.front(); } +inline const Value &Array::front() const { return V.front(); } +inline Value &Array::back() { return V.back(); } +inline const Value &Array::back() const { return V.back(); } +inline Value *Array::data() { return V.data(); } +inline const Value *Array::data() const { return V.data(); } + +inline typename Array::iterator Array::begin() { return V.begin(); } +inline typename Array::const_iterator Array::begin() const { return V.begin(); } +inline typename Array::iterator Array::end() { return V.end(); } +inline typename Array::const_iterator Array::end() const { return V.end(); } + +inline bool Array::empty() const { return V.empty(); } +inline size_t Array::size() const { return V.size(); } +inline void Array::reserve(size_t S) { V.reserve(S); } + +inline void Array::clear() { V.clear(); } +inline void Array::push_back(const Value &E) { V.push_back(E); } +inline void Array::push_back(Value &&E) { V.push_back(std::move(E)); } +template inline void Array::emplace_back(Args &&...A) { + V.emplace_back(std::forward(A)...); +} +inline void Array::pop_back() { V.pop_back(); } +inline typename Array::iterator Array::insert(iterator P, const Value &E) { + return V.insert(P, E); +} +inline typename Array::iterator Array::insert(iterator P, Value &&E) { + return V.insert(P, std::move(E)); +} +template +inline typename Array::iterator Array::insert(iterator P, It A, It Z) { + return V.insert(P, A, Z); +} +template +inline typename Array::iterator Array::emplace(const_iterator P, Args &&...A) { + return V.emplace(P, std::forward(A)...); +} +inline bool operator==(const Array &L, const Array &R) { return L.V == R.V; } + /// ObjectKey is a used to capture keys in Object. Like Value but: /// - only strings are allowed /// - it's optimized for the string literal case (Owned == nullptr) diff --git a/interpreter/llvm/src/include/llvm/Support/KnownBits.h b/interpreter/llvm-project/llvm/include/llvm/Support/KnownBits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/KnownBits.h rename to interpreter/llvm-project/llvm/include/llvm/Support/KnownBits.h diff --git a/interpreter/llvm/src/include/llvm/Support/LEB128.h b/interpreter/llvm-project/llvm/include/llvm/Support/LEB128.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/LEB128.h rename to interpreter/llvm-project/llvm/include/llvm/Support/LEB128.h diff --git a/interpreter/llvm/src/include/llvm/Support/LICENSE.TXT b/interpreter/llvm-project/llvm/include/llvm/Support/LICENSE.TXT similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/LICENSE.TXT rename to interpreter/llvm-project/llvm/include/llvm/Support/LICENSE.TXT diff --git a/interpreter/llvm/src/include/llvm/Support/LineIterator.h b/interpreter/llvm-project/llvm/include/llvm/Support/LineIterator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/LineIterator.h rename to interpreter/llvm-project/llvm/include/llvm/Support/LineIterator.h diff --git a/interpreter/llvm/src/include/llvm/Support/Locale.h b/interpreter/llvm-project/llvm/include/llvm/Support/Locale.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Locale.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Locale.h diff --git a/interpreter/llvm/src/include/llvm/Support/LockFileManager.h b/interpreter/llvm-project/llvm/include/llvm/Support/LockFileManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/LockFileManager.h rename to interpreter/llvm-project/llvm/include/llvm/Support/LockFileManager.h diff --git a/interpreter/llvm/src/include/llvm/Support/LowLevelTypeImpl.h b/interpreter/llvm-project/llvm/include/llvm/Support/LowLevelTypeImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/LowLevelTypeImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Support/LowLevelTypeImpl.h diff --git a/interpreter/llvm/src/include/llvm/Support/MD5.h b/interpreter/llvm-project/llvm/include/llvm/Support/MD5.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MD5.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MD5.h diff --git a/interpreter/llvm/src/include/llvm/Support/MSVCErrorWorkarounds.h b/interpreter/llvm-project/llvm/include/llvm/Support/MSVCErrorWorkarounds.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MSVCErrorWorkarounds.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MSVCErrorWorkarounds.h diff --git a/interpreter/llvm/src/include/llvm/Support/MachineValueType.h b/interpreter/llvm-project/llvm/include/llvm/Support/MachineValueType.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MachineValueType.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MachineValueType.h diff --git a/interpreter/llvm/src/include/llvm/Support/ManagedStatic.h b/interpreter/llvm-project/llvm/include/llvm/Support/ManagedStatic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ManagedStatic.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ManagedStatic.h diff --git a/interpreter/llvm/src/include/llvm/Support/MathExtras.h b/interpreter/llvm-project/llvm/include/llvm/Support/MathExtras.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MathExtras.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MathExtras.h diff --git a/interpreter/llvm/src/include/llvm/Support/MemAlloc.h b/interpreter/llvm-project/llvm/include/llvm/Support/MemAlloc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MemAlloc.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MemAlloc.h diff --git a/interpreter/llvm/src/include/llvm/Support/Memory.h b/interpreter/llvm-project/llvm/include/llvm/Support/Memory.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Memory.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Memory.h diff --git a/interpreter/llvm/src/include/llvm/Support/MemoryBuffer.h b/interpreter/llvm-project/llvm/include/llvm/Support/MemoryBuffer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MemoryBuffer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MemoryBuffer.h diff --git a/interpreter/llvm/src/include/llvm/Support/MemoryBufferRef.h b/interpreter/llvm-project/llvm/include/llvm/Support/MemoryBufferRef.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MemoryBufferRef.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MemoryBufferRef.h diff --git a/interpreter/llvm/src/include/llvm/Support/MipsABIFlags.h b/interpreter/llvm-project/llvm/include/llvm/Support/MipsABIFlags.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/MipsABIFlags.h rename to interpreter/llvm-project/llvm/include/llvm/Support/MipsABIFlags.h diff --git a/interpreter/llvm/src/include/llvm/Support/Mutex.h b/interpreter/llvm-project/llvm/include/llvm/Support/Mutex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Mutex.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Mutex.h diff --git a/interpreter/llvm/src/include/llvm/Support/NativeFormatting.h b/interpreter/llvm-project/llvm/include/llvm/Support/NativeFormatting.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/NativeFormatting.h rename to interpreter/llvm-project/llvm/include/llvm/Support/NativeFormatting.h diff --git a/interpreter/llvm/src/include/llvm/Support/OnDiskHashTable.h b/interpreter/llvm-project/llvm/include/llvm/Support/OnDiskHashTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/OnDiskHashTable.h rename to interpreter/llvm-project/llvm/include/llvm/Support/OnDiskHashTable.h diff --git a/interpreter/llvm/src/include/llvm/Support/OptimizedStructLayout.h b/interpreter/llvm-project/llvm/include/llvm/Support/OptimizedStructLayout.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/OptimizedStructLayout.h rename to interpreter/llvm-project/llvm/include/llvm/Support/OptimizedStructLayout.h diff --git a/interpreter/llvm/src/include/llvm/Support/Parallel.h b/interpreter/llvm-project/llvm/include/llvm/Support/Parallel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Parallel.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Parallel.h diff --git a/interpreter/llvm/src/include/llvm/Support/Path.h b/interpreter/llvm-project/llvm/include/llvm/Support/Path.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Path.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Path.h diff --git a/interpreter/llvm/src/include/llvm/Support/PluginLoader.h b/interpreter/llvm-project/llvm/include/llvm/Support/PluginLoader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/PluginLoader.h rename to interpreter/llvm-project/llvm/include/llvm/Support/PluginLoader.h diff --git a/interpreter/llvm/src/include/llvm/Support/PointerLikeTypeTraits.h b/interpreter/llvm-project/llvm/include/llvm/Support/PointerLikeTypeTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/PointerLikeTypeTraits.h rename to interpreter/llvm-project/llvm/include/llvm/Support/PointerLikeTypeTraits.h diff --git a/interpreter/llvm/src/include/llvm/Support/PrettyStackTrace.h b/interpreter/llvm-project/llvm/include/llvm/Support/PrettyStackTrace.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/PrettyStackTrace.h rename to interpreter/llvm-project/llvm/include/llvm/Support/PrettyStackTrace.h diff --git a/interpreter/llvm/src/include/llvm/Support/Printable.h b/interpreter/llvm-project/llvm/include/llvm/Support/Printable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Printable.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Printable.h diff --git a/interpreter/llvm/src/include/llvm/Support/Process.h b/interpreter/llvm-project/llvm/include/llvm/Support/Process.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Process.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Process.h diff --git a/interpreter/llvm/src/include/llvm/Support/Program.h b/interpreter/llvm-project/llvm/include/llvm/Support/Program.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Program.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Program.h diff --git a/interpreter/llvm/src/include/llvm/Support/RISCVAttributeParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/RISCVAttributeParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RISCVAttributeParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/RISCVAttributeParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/RISCVAttributes.h b/interpreter/llvm-project/llvm/include/llvm/Support/RISCVAttributes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RISCVAttributes.h rename to interpreter/llvm-project/llvm/include/llvm/Support/RISCVAttributes.h diff --git a/interpreter/llvm/src/include/llvm/Support/RISCVTargetParser.def b/interpreter/llvm-project/llvm/include/llvm/Support/RISCVTargetParser.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RISCVTargetParser.def rename to interpreter/llvm-project/llvm/include/llvm/Support/RISCVTargetParser.def diff --git a/interpreter/llvm/src/include/llvm/Support/RWMutex.h b/interpreter/llvm-project/llvm/include/llvm/Support/RWMutex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RWMutex.h rename to interpreter/llvm-project/llvm/include/llvm/Support/RWMutex.h diff --git a/interpreter/llvm/src/include/llvm/Support/RandomNumberGenerator.h b/interpreter/llvm-project/llvm/include/llvm/Support/RandomNumberGenerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RandomNumberGenerator.h rename to interpreter/llvm-project/llvm/include/llvm/Support/RandomNumberGenerator.h diff --git a/interpreter/llvm/src/include/llvm/Support/Recycler.h b/interpreter/llvm-project/llvm/include/llvm/Support/Recycler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Recycler.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Recycler.h diff --git a/interpreter/llvm/src/include/llvm/Support/RecyclingAllocator.h b/interpreter/llvm-project/llvm/include/llvm/Support/RecyclingAllocator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/RecyclingAllocator.h rename to interpreter/llvm-project/llvm/include/llvm/Support/RecyclingAllocator.h diff --git a/interpreter/llvm/src/include/llvm/Support/Regex.h b/interpreter/llvm-project/llvm/include/llvm/Support/Regex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Regex.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Regex.h diff --git a/interpreter/llvm/src/include/llvm/Support/Registry.h b/interpreter/llvm-project/llvm/include/llvm/Support/Registry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Registry.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Registry.h diff --git a/interpreter/llvm/src/include/llvm/Support/ReverseIteration.h b/interpreter/llvm-project/llvm/include/llvm/Support/ReverseIteration.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ReverseIteration.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ReverseIteration.h diff --git a/interpreter/llvm/src/include/llvm/Support/SHA1.h b/interpreter/llvm-project/llvm/include/llvm/Support/SHA1.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SHA1.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SHA1.h diff --git a/interpreter/llvm/src/include/llvm/Support/SHA256.h b/interpreter/llvm-project/llvm/include/llvm/Support/SHA256.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SHA256.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SHA256.h diff --git a/interpreter/llvm/src/include/llvm/Support/SMLoc.h b/interpreter/llvm-project/llvm/include/llvm/Support/SMLoc.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SMLoc.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SMLoc.h diff --git a/interpreter/llvm/src/include/llvm/Support/SMTAPI.h b/interpreter/llvm-project/llvm/include/llvm/Support/SMTAPI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SMTAPI.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SMTAPI.h diff --git a/interpreter/llvm/src/include/llvm/Support/SaveAndRestore.h b/interpreter/llvm-project/llvm/include/llvm/Support/SaveAndRestore.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SaveAndRestore.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SaveAndRestore.h diff --git a/interpreter/llvm/src/include/llvm/Support/ScaledNumber.h b/interpreter/llvm-project/llvm/include/llvm/Support/ScaledNumber.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ScaledNumber.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ScaledNumber.h diff --git a/interpreter/llvm/src/include/llvm/Support/ScopedPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Support/ScopedPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ScopedPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ScopedPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Support/Signals.h b/interpreter/llvm-project/llvm/include/llvm/Support/Signals.h similarity index 99% rename from interpreter/llvm/src/include/llvm/Support/Signals.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Signals.h index 44f5a750ff5cb..937e0572d4a72 100644 --- a/interpreter/llvm/src/include/llvm/Support/Signals.h +++ b/interpreter/llvm-project/llvm/include/llvm/Support/Signals.h @@ -14,6 +14,7 @@ #ifndef LLVM_SUPPORT_SIGNALS_H #define LLVM_SUPPORT_SIGNALS_H +#include #include namespace llvm { diff --git a/interpreter/llvm/src/include/llvm/Support/Signposts.h b/interpreter/llvm-project/llvm/include/llvm/Support/Signposts.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Signposts.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Signposts.h diff --git a/interpreter/llvm/src/include/llvm/Support/SmallVectorMemoryBuffer.h b/interpreter/llvm-project/llvm/include/llvm/Support/SmallVectorMemoryBuffer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SmallVectorMemoryBuffer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SmallVectorMemoryBuffer.h diff --git a/interpreter/llvm/src/include/llvm/Support/Solaris/sys/regset.h b/interpreter/llvm-project/llvm/include/llvm/Support/Solaris/sys/regset.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Solaris/sys/regset.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Solaris/sys/regset.h diff --git a/interpreter/llvm/src/include/llvm/Support/SourceMgr.h b/interpreter/llvm-project/llvm/include/llvm/Support/SourceMgr.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SourceMgr.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SourceMgr.h diff --git a/interpreter/llvm/src/include/llvm/Support/SpecialCaseList.h b/interpreter/llvm-project/llvm/include/llvm/Support/SpecialCaseList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SpecialCaseList.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SpecialCaseList.h diff --git a/interpreter/llvm/src/include/llvm/Support/StringSaver.h b/interpreter/llvm-project/llvm/include/llvm/Support/StringSaver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/StringSaver.h rename to interpreter/llvm-project/llvm/include/llvm/Support/StringSaver.h diff --git a/interpreter/llvm/src/include/llvm/Support/SuffixTree.h b/interpreter/llvm-project/llvm/include/llvm/Support/SuffixTree.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SuffixTree.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SuffixTree.h diff --git a/interpreter/llvm/src/include/llvm/Support/SwapByteOrder.h b/interpreter/llvm-project/llvm/include/llvm/Support/SwapByteOrder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SwapByteOrder.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SwapByteOrder.h diff --git a/interpreter/llvm/src/include/llvm/Support/SymbolRemappingReader.h b/interpreter/llvm-project/llvm/include/llvm/Support/SymbolRemappingReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SymbolRemappingReader.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SymbolRemappingReader.h diff --git a/interpreter/llvm/src/include/llvm/Support/SystemUtils.h b/interpreter/llvm-project/llvm/include/llvm/Support/SystemUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/SystemUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Support/SystemUtils.h diff --git a/interpreter/llvm/src/include/llvm/Support/TarWriter.h b/interpreter/llvm-project/llvm/include/llvm/Support/TarWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TarWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TarWriter.h diff --git a/interpreter/llvm/src/include/llvm/Support/TargetOpcodes.def b/interpreter/llvm-project/llvm/include/llvm/Support/TargetOpcodes.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TargetOpcodes.def rename to interpreter/llvm-project/llvm/include/llvm/Support/TargetOpcodes.def diff --git a/interpreter/llvm/src/include/llvm/Support/TargetParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/TargetParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TargetParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TargetParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/TargetRegistry.h b/interpreter/llvm-project/llvm/include/llvm/Support/TargetRegistry.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TargetRegistry.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TargetRegistry.h diff --git a/interpreter/llvm/src/include/llvm/Support/TargetSelect.h b/interpreter/llvm-project/llvm/include/llvm/Support/TargetSelect.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TargetSelect.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TargetSelect.h diff --git a/interpreter/llvm/src/include/llvm/Support/TaskQueue.h b/interpreter/llvm-project/llvm/include/llvm/Support/TaskQueue.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TaskQueue.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TaskQueue.h diff --git a/interpreter/llvm/src/include/llvm/Support/ThreadLocal.h b/interpreter/llvm-project/llvm/include/llvm/Support/ThreadLocal.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ThreadLocal.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ThreadLocal.h diff --git a/interpreter/llvm/src/include/llvm/Support/ThreadPool.h b/interpreter/llvm-project/llvm/include/llvm/Support/ThreadPool.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ThreadPool.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ThreadPool.h diff --git a/interpreter/llvm/src/include/llvm/Support/Threading.h b/interpreter/llvm-project/llvm/include/llvm/Support/Threading.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Threading.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Threading.h diff --git a/interpreter/llvm/src/include/llvm/Support/TimeProfiler.h b/interpreter/llvm-project/llvm/include/llvm/Support/TimeProfiler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TimeProfiler.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TimeProfiler.h diff --git a/interpreter/llvm/src/include/llvm/Support/Timer.h b/interpreter/llvm-project/llvm/include/llvm/Support/Timer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Timer.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Timer.h diff --git a/interpreter/llvm/src/include/llvm/Support/ToolOutputFile.h b/interpreter/llvm-project/llvm/include/llvm/Support/ToolOutputFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/ToolOutputFile.h rename to interpreter/llvm-project/llvm/include/llvm/Support/ToolOutputFile.h diff --git a/interpreter/llvm/src/include/llvm/Support/TrailingObjects.h b/interpreter/llvm-project/llvm/include/llvm/Support/TrailingObjects.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TrailingObjects.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TrailingObjects.h diff --git a/interpreter/llvm/src/include/llvm/Support/TrigramIndex.h b/interpreter/llvm-project/llvm/include/llvm/Support/TrigramIndex.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TrigramIndex.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TrigramIndex.h diff --git a/interpreter/llvm/src/include/llvm/Support/TypeName.h b/interpreter/llvm-project/llvm/include/llvm/Support/TypeName.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TypeName.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TypeName.h diff --git a/interpreter/llvm/src/include/llvm/Support/TypeSize.h b/interpreter/llvm-project/llvm/include/llvm/Support/TypeSize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/TypeSize.h rename to interpreter/llvm-project/llvm/include/llvm/Support/TypeSize.h diff --git a/interpreter/llvm/src/include/llvm/Support/Unicode.h b/interpreter/llvm-project/llvm/include/llvm/Support/Unicode.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Unicode.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Unicode.h diff --git a/interpreter/llvm/src/include/llvm/Support/UnicodeCharRanges.h b/interpreter/llvm-project/llvm/include/llvm/Support/UnicodeCharRanges.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/UnicodeCharRanges.h rename to interpreter/llvm-project/llvm/include/llvm/Support/UnicodeCharRanges.h diff --git a/interpreter/llvm/src/include/llvm/Support/Valgrind.h b/interpreter/llvm-project/llvm/include/llvm/Support/Valgrind.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Valgrind.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Valgrind.h diff --git a/interpreter/llvm/src/include/llvm/Support/VersionTuple.h b/interpreter/llvm-project/llvm/include/llvm/Support/VersionTuple.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/VersionTuple.h rename to interpreter/llvm-project/llvm/include/llvm/Support/VersionTuple.h diff --git a/interpreter/llvm/src/include/llvm/Support/VirtualFileSystem.h b/interpreter/llvm-project/llvm/include/llvm/Support/VirtualFileSystem.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/VirtualFileSystem.h rename to interpreter/llvm-project/llvm/include/llvm/Support/VirtualFileSystem.h diff --git a/interpreter/llvm/src/include/llvm/Support/Watchdog.h b/interpreter/llvm-project/llvm/include/llvm/Support/Watchdog.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Watchdog.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Watchdog.h diff --git a/interpreter/llvm/src/include/llvm/Support/Win64EH.h b/interpreter/llvm-project/llvm/include/llvm/Support/Win64EH.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Win64EH.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Win64EH.h diff --git a/interpreter/llvm/src/include/llvm/Support/Windows/WindowsSupport.h b/interpreter/llvm-project/llvm/include/llvm/Support/Windows/WindowsSupport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/Windows/WindowsSupport.h rename to interpreter/llvm-project/llvm/include/llvm/Support/Windows/WindowsSupport.h diff --git a/interpreter/llvm/src/include/llvm/Support/WindowsError.h b/interpreter/llvm-project/llvm/include/llvm/Support/WindowsError.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/WindowsError.h rename to interpreter/llvm-project/llvm/include/llvm/Support/WindowsError.h diff --git a/interpreter/llvm/src/include/llvm/Support/WithColor.h b/interpreter/llvm-project/llvm/include/llvm/Support/WithColor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/WithColor.h rename to interpreter/llvm-project/llvm/include/llvm/Support/WithColor.h diff --git a/interpreter/llvm/src/include/llvm/Support/X86DisassemblerDecoderCommon.h b/interpreter/llvm-project/llvm/include/llvm/Support/X86DisassemblerDecoderCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/X86DisassemblerDecoderCommon.h rename to interpreter/llvm-project/llvm/include/llvm/Support/X86DisassemblerDecoderCommon.h diff --git a/interpreter/llvm/src/include/llvm/Support/X86TargetParser.def b/interpreter/llvm-project/llvm/include/llvm/Support/X86TargetParser.def similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/X86TargetParser.def rename to interpreter/llvm-project/llvm/include/llvm/Support/X86TargetParser.def diff --git a/interpreter/llvm/src/include/llvm/Support/X86TargetParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/X86TargetParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/X86TargetParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/X86TargetParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/YAMLParser.h b/interpreter/llvm-project/llvm/include/llvm/Support/YAMLParser.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/YAMLParser.h rename to interpreter/llvm-project/llvm/include/llvm/Support/YAMLParser.h diff --git a/interpreter/llvm/src/include/llvm/Support/YAMLTraits.h b/interpreter/llvm-project/llvm/include/llvm/Support/YAMLTraits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/YAMLTraits.h rename to interpreter/llvm-project/llvm/include/llvm/Support/YAMLTraits.h diff --git a/interpreter/llvm/src/include/llvm/Support/circular_raw_ostream.h b/interpreter/llvm-project/llvm/include/llvm/Support/circular_raw_ostream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/circular_raw_ostream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/circular_raw_ostream.h diff --git a/interpreter/llvm/src/include/llvm/Support/raw_os_ostream.h b/interpreter/llvm-project/llvm/include/llvm/Support/raw_os_ostream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/raw_os_ostream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/raw_os_ostream.h diff --git a/interpreter/llvm/src/include/llvm/Support/raw_ostream.h b/interpreter/llvm-project/llvm/include/llvm/Support/raw_ostream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/raw_ostream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/raw_ostream.h diff --git a/interpreter/llvm/src/include/llvm/Support/raw_sha1_ostream.h b/interpreter/llvm-project/llvm/include/llvm/Support/raw_sha1_ostream.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/raw_sha1_ostream.h rename to interpreter/llvm-project/llvm/include/llvm/Support/raw_sha1_ostream.h diff --git a/interpreter/llvm/src/include/llvm/Support/thread.h b/interpreter/llvm-project/llvm/include/llvm/Support/thread.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/thread.h rename to interpreter/llvm-project/llvm/include/llvm/Support/thread.h diff --git a/interpreter/llvm/src/include/llvm/Support/type_traits.h b/interpreter/llvm-project/llvm/include/llvm/Support/type_traits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/type_traits.h rename to interpreter/llvm-project/llvm/include/llvm/Support/type_traits.h diff --git a/interpreter/llvm/src/include/llvm/Support/xxhash.h b/interpreter/llvm-project/llvm/include/llvm/Support/xxhash.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Support/xxhash.h rename to interpreter/llvm-project/llvm/include/llvm/Support/xxhash.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/Automaton.td b/interpreter/llvm-project/llvm/include/llvm/TableGen/Automaton.td similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/Automaton.td rename to interpreter/llvm-project/llvm/include/llvm/TableGen/Automaton.td diff --git a/interpreter/llvm/src/include/llvm/TableGen/DirectiveEmitter.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/DirectiveEmitter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/DirectiveEmitter.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/DirectiveEmitter.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/Error.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/Error.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/Error.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/Error.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/Main.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/Main.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/Main.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/Main.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/Record.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/Record.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/Record.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/Record.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/SearchableTable.td b/interpreter/llvm-project/llvm/include/llvm/TableGen/SearchableTable.td similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/SearchableTable.td rename to interpreter/llvm-project/llvm/include/llvm/TableGen/SearchableTable.td diff --git a/interpreter/llvm/src/include/llvm/TableGen/SetTheory.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/SetTheory.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/SetTheory.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/SetTheory.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/StringMatcher.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/StringMatcher.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/StringMatcher.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/StringMatcher.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/StringToOffsetTable.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/StringToOffsetTable.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/StringToOffsetTable.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/StringToOffsetTable.h diff --git a/interpreter/llvm/src/include/llvm/TableGen/TableGenBackend.h b/interpreter/llvm-project/llvm/include/llvm/TableGen/TableGenBackend.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TableGen/TableGenBackend.h rename to interpreter/llvm-project/llvm/include/llvm/TableGen/TableGenBackend.h diff --git a/interpreter/llvm/src/include/llvm/Target/CGPassBuilderOption.h b/interpreter/llvm-project/llvm/include/llvm/Target/CGPassBuilderOption.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/CGPassBuilderOption.h rename to interpreter/llvm-project/llvm/include/llvm/Target/CGPassBuilderOption.h diff --git a/interpreter/llvm/src/include/llvm/Target/CodeGenCWrappers.h b/interpreter/llvm-project/llvm/include/llvm/Target/CodeGenCWrappers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/CodeGenCWrappers.h rename to interpreter/llvm-project/llvm/include/llvm/Target/CodeGenCWrappers.h diff --git a/interpreter/llvm/src/include/llvm/Target/GenericOpcodes.td b/interpreter/llvm-project/llvm/include/llvm/Target/GenericOpcodes.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/GenericOpcodes.td rename to interpreter/llvm-project/llvm/include/llvm/Target/GenericOpcodes.td diff --git a/interpreter/llvm/src/include/llvm/Target/GlobalISel/Combine.td b/interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/Combine.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/GlobalISel/Combine.td rename to interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/Combine.td diff --git a/interpreter/llvm/src/include/llvm/Target/GlobalISel/RegisterBank.td b/interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/RegisterBank.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/GlobalISel/RegisterBank.td rename to interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/RegisterBank.td diff --git a/interpreter/llvm/src/include/llvm/Target/GlobalISel/SelectionDAGCompat.td b/interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/SelectionDAGCompat.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/GlobalISel/SelectionDAGCompat.td rename to interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/SelectionDAGCompat.td diff --git a/interpreter/llvm/src/include/llvm/Target/GlobalISel/Target.td b/interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/Target.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/GlobalISel/Target.td rename to interpreter/llvm-project/llvm/include/llvm/Target/GlobalISel/Target.td diff --git a/interpreter/llvm/src/include/llvm/Target/Target.td b/interpreter/llvm-project/llvm/include/llvm/Target/Target.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/Target.td rename to interpreter/llvm-project/llvm/include/llvm/Target/Target.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetCallingConv.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetCallingConv.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetCallingConv.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetCallingConv.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetInstrPredicate.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetInstrPredicate.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetInstrPredicate.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetInstrPredicate.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetIntrinsicInfo.h b/interpreter/llvm-project/llvm/include/llvm/Target/TargetIntrinsicInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetIntrinsicInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetIntrinsicInfo.h diff --git a/interpreter/llvm/src/include/llvm/Target/TargetItinerary.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetItinerary.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetItinerary.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetItinerary.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetLoweringObjectFile.h b/interpreter/llvm-project/llvm/include/llvm/Target/TargetLoweringObjectFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetLoweringObjectFile.h rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetLoweringObjectFile.h diff --git a/interpreter/llvm/src/include/llvm/Target/TargetMachine.h b/interpreter/llvm-project/llvm/include/llvm/Target/TargetMachine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetMachine.h rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetMachine.h diff --git a/interpreter/llvm/src/include/llvm/Target/TargetOptions.h b/interpreter/llvm-project/llvm/include/llvm/Target/TargetOptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetOptions.h rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetOptions.h diff --git a/interpreter/llvm/src/include/llvm/Target/TargetPfmCounters.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetPfmCounters.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetPfmCounters.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetPfmCounters.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetSchedule.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetSchedule.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetSchedule.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetSchedule.td diff --git a/interpreter/llvm/src/include/llvm/Target/TargetSelectionDAG.td b/interpreter/llvm-project/llvm/include/llvm/Target/TargetSelectionDAG.td similarity index 100% rename from interpreter/llvm/src/include/llvm/Target/TargetSelectionDAG.td rename to interpreter/llvm-project/llvm/include/llvm/Target/TargetSelectionDAG.td diff --git a/interpreter/llvm/src/include/llvm/Testing/Support/Annotations.h b/interpreter/llvm-project/llvm/include/llvm/Testing/Support/Annotations.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Testing/Support/Annotations.h rename to interpreter/llvm-project/llvm/include/llvm/Testing/Support/Annotations.h diff --git a/interpreter/llvm/src/include/llvm/Testing/Support/Error.h b/interpreter/llvm-project/llvm/include/llvm/Testing/Support/Error.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Testing/Support/Error.h rename to interpreter/llvm-project/llvm/include/llvm/Testing/Support/Error.h diff --git a/interpreter/llvm/src/include/llvm/Testing/Support/SupportHelpers.h b/interpreter/llvm-project/llvm/include/llvm/Testing/Support/SupportHelpers.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Testing/Support/SupportHelpers.h rename to interpreter/llvm-project/llvm/include/llvm/Testing/Support/SupportHelpers.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/Architecture.def b/interpreter/llvm-project/llvm/include/llvm/TextAPI/Architecture.def similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/Architecture.def rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/Architecture.def diff --git a/interpreter/llvm/src/include/llvm/TextAPI/Architecture.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/Architecture.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/Architecture.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/Architecture.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/ArchitectureSet.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/ArchitectureSet.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/ArchitectureSet.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/ArchitectureSet.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/InterfaceFile.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/InterfaceFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/InterfaceFile.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/InterfaceFile.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/PackedVersion.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/PackedVersion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/PackedVersion.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/PackedVersion.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/Platform.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/Platform.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/Platform.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/Platform.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/Symbol.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/Symbol.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/Symbol.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/Symbol.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/Target.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/Target.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/Target.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/Target.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/TextAPIReader.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/TextAPIReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/TextAPIReader.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/TextAPIReader.h diff --git a/interpreter/llvm/src/include/llvm/TextAPI/TextAPIWriter.h b/interpreter/llvm-project/llvm/include/llvm/TextAPI/TextAPIWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/TextAPI/TextAPIWriter.h rename to interpreter/llvm-project/llvm/include/llvm/TextAPI/TextAPIWriter.h diff --git a/interpreter/llvm/src/include/llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h b/interpreter/llvm-project/llvm/include/llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h rename to interpreter/llvm-project/llvm/include/llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h diff --git a/interpreter/llvm/src/include/llvm/ToolDrivers/llvm-lib/LibDriver.h b/interpreter/llvm-project/llvm/include/llvm/ToolDrivers/llvm-lib/LibDriver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/ToolDrivers/llvm-lib/LibDriver.h rename to interpreter/llvm-project/llvm/include/llvm/ToolDrivers/llvm-lib/LibDriver.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/CFGuard.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/CFGuard.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/CFGuard.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/CFGuard.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Coroutines.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Coroutines.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroCleanup.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroCleanup.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroCleanup.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroCleanup.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroEarly.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroEarly.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroEarly.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroEarly.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroElide.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroElide.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroElide.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroElide.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroSplit.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroSplit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Coroutines/CoroSplit.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Coroutines/CoroSplit.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/AlwaysInliner.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/AlwaysInliner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/AlwaysInliner.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/AlwaysInliner.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/Annotation2Metadata.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Annotation2Metadata.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/Annotation2Metadata.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Annotation2Metadata.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ArgumentPromotion.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ArgumentPromotion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ArgumentPromotion.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ArgumentPromotion.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/Attributor.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Attributor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/Attributor.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Attributor.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/BlockExtractor.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/BlockExtractor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/BlockExtractor.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/BlockExtractor.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/CalledValuePropagation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/CalledValuePropagation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/CalledValuePropagation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/CalledValuePropagation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ConstantMerge.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ConstantMerge.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ConstantMerge.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ConstantMerge.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/CrossDSOCFI.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/CrossDSOCFI.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/CrossDSOCFI.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/CrossDSOCFI.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/DeadArgumentElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/DeadArgumentElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ElimAvailExtern.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ElimAvailExtern.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ElimAvailExtern.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ElimAvailExtern.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ForceFunctionAttrs.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ForceFunctionAttrs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ForceFunctionAttrs.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ForceFunctionAttrs.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/FunctionAttrs.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/FunctionAttrs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/FunctionAttrs.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/FunctionAttrs.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/FunctionImport.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/FunctionImport.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/FunctionImport.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/FunctionImport.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalDCE.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalDCE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalDCE.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalDCE.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalOpt.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalOpt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalOpt.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalOpt.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalSplit.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalSplit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/GlobalSplit.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/GlobalSplit.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/HotColdSplitting.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/HotColdSplitting.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/HotColdSplitting.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/HotColdSplitting.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/IROutliner.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/IROutliner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/IROutliner.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/IROutliner.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/InferFunctionAttrs.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/InferFunctionAttrs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/InferFunctionAttrs.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/InferFunctionAttrs.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/Inliner.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Inliner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/Inliner.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Inliner.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/Internalize.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Internalize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/Internalize.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/Internalize.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/LoopExtractor.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/LoopExtractor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/LoopExtractor.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/LoopExtractor.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/LowerTypeTests.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/LowerTypeTests.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/MergeFunctions.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/MergeFunctions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/MergeFunctions.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/MergeFunctions.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/OpenMPOpt.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/OpenMPOpt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/OpenMPOpt.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/OpenMPOpt.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/PartialInlining.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/PartialInlining.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/PartialInlining.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/PartialInlining.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/PassManagerBuilder.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/PassManagerBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ProfiledCallGraph.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ProfiledCallGraph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ProfiledCallGraph.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ProfiledCallGraph.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/SCCP.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SCCP.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/SCCP.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SCCP.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/SampleContextTracker.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleContextTracker.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/SampleContextTracker.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleContextTracker.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/SampleProfile.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleProfile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/SampleProfile.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleProfile.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/SampleProfileProbe.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/SampleProfileProbe.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/StripDeadPrototypes.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/StripDeadPrototypes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/StripDeadPrototypes.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/StripDeadPrototypes.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/StripSymbols.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/StripSymbols.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/StripSymbols.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/StripSymbols.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/SyntheticCountsPropagation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SyntheticCountsPropagation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/SyntheticCountsPropagation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/SyntheticCountsPropagation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/ThinLTOBitcodeWriter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/IPO/WholeProgramDevirt.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/WholeProgramDevirt.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/IPO/WholeProgramDevirt.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/IPO/WholeProgramDevirt.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombine.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombine.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombine.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombineWorklist.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombineWorklist.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombineWorklist.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombineWorklist.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombiner.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/InstCombine/InstCombiner.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/BoundsChecking.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/BoundsChecking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/BoundsChecking.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/BoundsChecking.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/CGProfile.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/CGProfile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/CGProfile.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/CGProfile.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/ControlHeightReduction.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/ControlHeightReduction.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/ControlHeightReduction.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/ControlHeightReduction.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/GCOVProfiler.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/GCOVProfiler.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/InstrOrderFile.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/InstrOrderFile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/InstrOrderFile.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/InstrOrderFile.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/InstrProfiling.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/InstrProfiling.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/MemProfiler.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/MemProfiler.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/MemProfiler.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/MemProfiler.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/MemorySanitizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/MemorySanitizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/PGOInstrumentation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/PGOInstrumentation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/PGOInstrumentation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/PGOInstrumentation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/PoisonChecking.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/PoisonChecking.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/PoisonChecking.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/PoisonChecking.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/SanitizerCoverage.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/SanitizerCoverage.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/SanitizerCoverage.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/SanitizerCoverage.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Instrumentation/ThreadSanitizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/ThreadSanitizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Instrumentation/ThreadSanitizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Instrumentation/ThreadSanitizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/ObjCARC.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/ObjCARC.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/ObjCARC.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/ObjCARC.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/ADCE.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ADCE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/ADCE.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ADCE.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/AlignmentFromAssumptions.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/AlignmentFromAssumptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/AlignmentFromAssumptions.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/AlignmentFromAssumptions.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/AnnotationRemarks.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/AnnotationRemarks.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/AnnotationRemarks.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/AnnotationRemarks.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/BDCE.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/BDCE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/BDCE.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/BDCE.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/CallSiteSplitting.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/CallSiteSplitting.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/CallSiteSplitting.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/CallSiteSplitting.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/ConstantHoisting.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ConstantHoisting.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/ConstantHoisting.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ConstantHoisting.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/ConstraintElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ConstraintElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/ConstraintElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ConstraintElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/CorrelatedValuePropagation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/CorrelatedValuePropagation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/CorrelatedValuePropagation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/CorrelatedValuePropagation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/DCE.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DCE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/DCE.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DCE.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/DFAJumpThreading.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DFAJumpThreading.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/DFAJumpThreading.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DFAJumpThreading.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/DeadStoreElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DeadStoreElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/DeadStoreElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DeadStoreElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/DivRemPairs.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DivRemPairs.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/DivRemPairs.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/DivRemPairs.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/EarlyCSE.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/EarlyCSE.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/EarlyCSE.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/EarlyCSE.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/Float2Int.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Float2Int.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/Float2Int.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Float2Int.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/GVN.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GVN.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/GVN.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GVN.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/GVNExpression.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GVNExpression.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/GVNExpression.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GVNExpression.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/GuardWidening.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GuardWidening.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/GuardWidening.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/GuardWidening.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/IVUsersPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/IVUsersPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/IVUsersPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/IVUsersPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/IndVarSimplify.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/IndVarSimplify.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/IndVarSimplify.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/IndVarSimplify.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/InductiveRangeCheckElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InductiveRangeCheckElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/InductiveRangeCheckElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InductiveRangeCheckElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/InferAddressSpaces.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InferAddressSpaces.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/InferAddressSpaces.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InferAddressSpaces.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/InstSimplifyPass.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InstSimplifyPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/InstSimplifyPass.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/InstSimplifyPass.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/JumpThreading.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/JumpThreading.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/JumpThreading.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/JumpThreading.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LICM.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LICM.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LICM.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LICM.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopBoundSplit.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopBoundSplit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopBoundSplit.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopBoundSplit.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDataPrefetch.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDataPrefetch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDataPrefetch.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDataPrefetch.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDeletion.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDeletion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDeletion.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDeletion.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDistribute.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDistribute.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopDistribute.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopDistribute.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopFlatten.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopFlatten.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopFlatten.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopFlatten.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopFuse.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopFuse.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopFuse.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopFuse.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopIdiomRecognize.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopIdiomRecognize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopIdiomRecognize.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopIdiomRecognize.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopInstSimplify.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopInstSimplify.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopInstSimplify.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopInstSimplify.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopInterchange.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopInterchange.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopInterchange.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopInterchange.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopLoadElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopLoadElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopLoadElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopLoadElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopPassManager.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopPassManager.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopPassManager.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopPassManager.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopPredication.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopPredication.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopPredication.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopPredication.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopReroll.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopReroll.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopReroll.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopReroll.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopRotation.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopRotation.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopRotation.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopRotation.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopSimplifyCFG.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopSimplifyCFG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopSimplifyCFG.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopSimplifyCFG.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopSink.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopSink.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopSink.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopSink.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopStrengthReduce.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopStrengthReduce.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopStrengthReduce.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopStrengthReduce.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopUnrollAndJamPass.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopUnrollAndJamPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopUnrollAndJamPass.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopUnrollAndJamPass.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopUnrollPass.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopUnrollPass.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopUnrollPass.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopUnrollPass.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopVersioningLICM.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopVersioningLICM.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LoopVersioningLICM.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LoopVersioningLICM.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerAtomic.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerAtomic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerAtomic.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerAtomic.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerConstantIntrinsics.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerConstantIntrinsics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerConstantIntrinsics.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerConstantIntrinsics.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerGuardIntrinsic.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerGuardIntrinsic.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerGuardIntrinsic.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerGuardIntrinsic.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerMatrixIntrinsics.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerMatrixIntrinsics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerMatrixIntrinsics.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerMatrixIntrinsics.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerWidenableCondition.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerWidenableCondition.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/LowerWidenableCondition.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/LowerWidenableCondition.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/MakeGuardsExplicit.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MakeGuardsExplicit.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/MakeGuardsExplicit.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MakeGuardsExplicit.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/MemCpyOptimizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/MemCpyOptimizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/MergeICmps.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MergeICmps.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/MergeICmps.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MergeICmps.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/MergedLoadStoreMotion.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MergedLoadStoreMotion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/MergedLoadStoreMotion.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/MergedLoadStoreMotion.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/NaryReassociate.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/NaryReassociate.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/NaryReassociate.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/NaryReassociate.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/NewGVN.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/NewGVN.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/NewGVN.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/NewGVN.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/PartiallyInlineLibCalls.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/PartiallyInlineLibCalls.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/PartiallyInlineLibCalls.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/PartiallyInlineLibCalls.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/Reassociate.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Reassociate.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/Reassociate.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Reassociate.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/Reg2Mem.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Reg2Mem.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/Reg2Mem.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Reg2Mem.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/RewriteStatepointsForGC.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/RewriteStatepointsForGC.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/RewriteStatepointsForGC.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/RewriteStatepointsForGC.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SCCP.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SCCP.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SCCP.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SCCP.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SROA.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SROA.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SROA.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SROA.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/Scalarizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Scalarizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/Scalarizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Scalarizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SimpleLoopUnswitch.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SimpleLoopUnswitch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SimpleLoopUnswitch.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SimpleLoopUnswitch.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SimplifyCFG.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SimplifyCFG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SimplifyCFG.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SimplifyCFG.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/Sink.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Sink.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/Sink.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/Sink.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/SpeculativeExecution.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SpeculativeExecution.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/SpeculativeExecution.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/SpeculativeExecution.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/StraightLineStrengthReduce.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/StraightLineStrengthReduce.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/StraightLineStrengthReduce.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/StraightLineStrengthReduce.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/StructurizeCFG.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/StructurizeCFG.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/StructurizeCFG.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/StructurizeCFG.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/TailRecursionElimination.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/TailRecursionElimination.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/TailRecursionElimination.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/TailRecursionElimination.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Scalar/WarnMissedTransforms.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/WarnMissedTransforms.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Scalar/WarnMissedTransforms.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Scalar/WarnMissedTransforms.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/ASanStackFrameLayout.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ASanStackFrameLayout.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/ASanStackFrameLayout.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ASanStackFrameLayout.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/AddDiscriminators.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AddDiscriminators.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/AddDiscriminators.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AddDiscriminators.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/AssumeBundleBuilder.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AssumeBundleBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/AssumeBundleBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/AssumeBundleBuilder.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/BasicBlockUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/BasicBlockUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/BreakCriticalEdges.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BreakCriticalEdges.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/BreakCriticalEdges.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BreakCriticalEdges.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/BuildLibCalls.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BuildLibCalls.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/BuildLibCalls.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BuildLibCalls.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/BypassSlowDivision.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/BypassSlowDivision.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/BypassSlowDivision.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CallGraphUpdater.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CallGraphUpdater.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CallGraphUpdater.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CallGraphUpdater.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CallPromotionUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CallPromotionUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CallPromotionUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CallPromotionUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CanonicalizeAliases.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CanonicalizeAliases.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CanonicalizeAliases.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CanonicalizeAliases.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/Cloning.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Cloning.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/Cloning.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Cloning.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CodeExtractor.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CodeExtractor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CodeExtractor.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CodeExtractor.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CodeMoverUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CodeMoverUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CodeMoverUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CodeMoverUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/CtorUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CtorUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/CtorUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/CtorUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/Debugify.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Debugify.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/Debugify.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Debugify.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/EntryExitInstrumenter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/EntryExitInstrumenter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/EntryExitInstrumenter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/EntryExitInstrumenter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/EscapeEnumerator.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/EscapeEnumerator.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/Evaluator.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Evaluator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/Evaluator.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Evaluator.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/FixIrreducible.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FixIrreducible.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/FixIrreducible.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FixIrreducible.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/FunctionComparator.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FunctionComparator.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/FunctionComparator.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FunctionComparator.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/FunctionImportUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FunctionImportUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/FunctionImportUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/FunctionImportUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/GlobalStatus.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/GlobalStatus.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/GlobalStatus.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/GlobalStatus.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/GuardUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/GuardUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/GuardUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/GuardUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/HelloWorld.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/HelloWorld.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/HelloWorld.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/HelloWorld.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/InjectTLIMappings.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/InjectTLIMappings.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/InjectTLIMappings.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/InjectTLIMappings.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/InstructionNamer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/InstructionNamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/InstructionNamer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/InstructionNamer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/IntegerDivision.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/IntegerDivision.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/IntegerDivision.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/IntegerDivision.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LCSSA.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LCSSA.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LCSSA.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LCSSA.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LibCallsShrinkWrap.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LibCallsShrinkWrap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LibCallsShrinkWrap.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LibCallsShrinkWrap.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/Local.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Local.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/Local.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Local.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LoopPeel.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopPeel.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LoopPeel.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopPeel.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LoopRotationUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopRotationUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LoopRotationUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopRotationUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LoopSimplify.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopSimplify.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LoopSimplify.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopSimplify.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LoopUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LoopUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LoopVersioning.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopVersioning.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LoopVersioning.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LoopVersioning.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LowerInvoke.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerInvoke.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LowerInvoke.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerInvoke.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LowerMemIntrinsics.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerMemIntrinsics.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LowerMemIntrinsics.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerMemIntrinsics.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/LowerSwitch.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerSwitch.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/LowerSwitch.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/LowerSwitch.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/MatrixUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MatrixUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/MatrixUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MatrixUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/Mem2Reg.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Mem2Reg.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/Mem2Reg.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/Mem2Reg.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/MemoryOpRemark.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MemoryOpRemark.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/MemoryOpRemark.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MemoryOpRemark.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/MetaRenamer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MetaRenamer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/MetaRenamer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/MetaRenamer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/ModuleUtils.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ModuleUtils.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/ModuleUtils.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ModuleUtils.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/NameAnonGlobals.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/NameAnonGlobals.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/NameAnonGlobals.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/NameAnonGlobals.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/PredicateInfo.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/PredicateInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/PredicateInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/PredicateInfo.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/PromoteMemToReg.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/PromoteMemToReg.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/PromoteMemToReg.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/PromoteMemToReg.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/RelLookupTableConverter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/RelLookupTableConverter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/RelLookupTableConverter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/RelLookupTableConverter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SCCPSolver.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SCCPSolver.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SCCPSolver.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SCCPSolver.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdater.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdater.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdater.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdater.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdaterBulk.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdaterBulk.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdaterBulk.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdaterBulk.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdaterImpl.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SSAUpdaterImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SanitizerStats.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SanitizerStats.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SanitizerStats.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SanitizerStats.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyCFGOptions.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyCFGOptions.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyCFGOptions.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyCFGOptions.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyIndVar.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyIndVar.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyIndVar.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyIndVar.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyLibCalls.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyLibCalls.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SimplifyLibCalls.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SimplifyLibCalls.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SizeOpts.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SizeOpts.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SizeOpts.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SizeOpts.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SplitModule.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SplitModule.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SplitModule.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SplitModule.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/StripGCRelocates.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/StripGCRelocates.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/StripGCRelocates.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/StripGCRelocates.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/StripNonLineTableDebugInfo.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/StripNonLineTableDebugInfo.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/StripNonLineTableDebugInfo.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/StripNonLineTableDebugInfo.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/SymbolRewriter.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SymbolRewriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/SymbolRewriter.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/SymbolRewriter.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/UnifyLoopExits.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnifyLoopExits.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/UnifyLoopExits.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnifyLoopExits.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/UnrollLoop.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnrollLoop.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/UnrollLoop.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/UnrollLoop.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/VNCoercion.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/VNCoercion.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/VNCoercion.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/VNCoercion.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Utils/ValueMapper.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ValueMapper.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Utils/ValueMapper.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Utils/ValueMapper.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoadStoreVectorizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoadStoreVectorizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoadStoreVectorizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoadStoreVectorizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoopVectorize.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoopVectorize.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize/LoopVectorize.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/LoopVectorize.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize/SLPVectorizer.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize/SLPVectorizer.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h diff --git a/interpreter/llvm/src/include/llvm/Transforms/Vectorize/VectorCombine.h b/interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/VectorCombine.h similarity index 100% rename from interpreter/llvm/src/include/llvm/Transforms/Vectorize/VectorCombine.h rename to interpreter/llvm-project/llvm/include/llvm/Transforms/Vectorize/VectorCombine.h diff --git a/interpreter/llvm/src/include/llvm/WindowsManifest/WindowsManifestMerger.h b/interpreter/llvm-project/llvm/include/llvm/WindowsManifest/WindowsManifestMerger.h similarity index 100% rename from interpreter/llvm/src/include/llvm/WindowsManifest/WindowsManifestMerger.h rename to interpreter/llvm-project/llvm/include/llvm/WindowsManifest/WindowsManifestMerger.h diff --git a/interpreter/llvm/src/include/llvm/WindowsResource/ResourceProcessor.h b/interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceProcessor.h similarity index 100% rename from interpreter/llvm/src/include/llvm/WindowsResource/ResourceProcessor.h rename to interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceProcessor.h diff --git a/interpreter/llvm/src/include/llvm/WindowsResource/ResourceScriptToken.h b/interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceScriptToken.h similarity index 100% rename from interpreter/llvm/src/include/llvm/WindowsResource/ResourceScriptToken.h rename to interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceScriptToken.h diff --git a/interpreter/llvm/src/include/llvm/WindowsResource/ResourceScriptTokenList.h b/interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceScriptTokenList.h similarity index 100% rename from interpreter/llvm/src/include/llvm/WindowsResource/ResourceScriptTokenList.h rename to interpreter/llvm-project/llvm/include/llvm/WindowsResource/ResourceScriptTokenList.h diff --git a/interpreter/llvm/src/include/llvm/XRay/BlockIndexer.h b/interpreter/llvm-project/llvm/include/llvm/XRay/BlockIndexer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/BlockIndexer.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/BlockIndexer.h diff --git a/interpreter/llvm/src/include/llvm/XRay/BlockPrinter.h b/interpreter/llvm-project/llvm/include/llvm/XRay/BlockPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/BlockPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/BlockPrinter.h diff --git a/interpreter/llvm/src/include/llvm/XRay/BlockVerifier.h b/interpreter/llvm-project/llvm/include/llvm/XRay/BlockVerifier.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/BlockVerifier.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/BlockVerifier.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRLogBuilder.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRLogBuilder.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRLogBuilder.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRLogBuilder.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRRecordConsumer.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecordConsumer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRRecordConsumer.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecordConsumer.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRRecordProducer.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecordProducer.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRRecordProducer.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecordProducer.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRRecords.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecords.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRRecords.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRRecords.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRTraceExpander.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRTraceExpander.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRTraceExpander.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRTraceExpander.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FDRTraceWriter.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FDRTraceWriter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FDRTraceWriter.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FDRTraceWriter.h diff --git a/interpreter/llvm/src/include/llvm/XRay/FileHeaderReader.h b/interpreter/llvm-project/llvm/include/llvm/XRay/FileHeaderReader.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/FileHeaderReader.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/FileHeaderReader.h diff --git a/interpreter/llvm/src/include/llvm/XRay/Graph.h b/interpreter/llvm-project/llvm/include/llvm/XRay/Graph.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/Graph.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/Graph.h diff --git a/interpreter/llvm/src/include/llvm/XRay/InstrumentationMap.h b/interpreter/llvm-project/llvm/include/llvm/XRay/InstrumentationMap.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/InstrumentationMap.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/InstrumentationMap.h diff --git a/interpreter/llvm/src/include/llvm/XRay/Profile.h b/interpreter/llvm-project/llvm/include/llvm/XRay/Profile.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/Profile.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/Profile.h diff --git a/interpreter/llvm/src/include/llvm/XRay/RecordPrinter.h b/interpreter/llvm-project/llvm/include/llvm/XRay/RecordPrinter.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/RecordPrinter.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/RecordPrinter.h diff --git a/interpreter/llvm/src/include/llvm/XRay/Trace.h b/interpreter/llvm-project/llvm/include/llvm/XRay/Trace.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/Trace.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/Trace.h diff --git a/interpreter/llvm/src/include/llvm/XRay/XRayRecord.h b/interpreter/llvm-project/llvm/include/llvm/XRay/XRayRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/XRayRecord.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/XRayRecord.h diff --git a/interpreter/llvm/src/include/llvm/XRay/YAMLXRayRecord.h b/interpreter/llvm-project/llvm/include/llvm/XRay/YAMLXRayRecord.h similarity index 100% rename from interpreter/llvm/src/include/llvm/XRay/YAMLXRayRecord.h rename to interpreter/llvm-project/llvm/include/llvm/XRay/YAMLXRayRecord.h diff --git a/interpreter/llvm/src/include/llvm/module.extern.modulemap b/interpreter/llvm-project/llvm/include/llvm/module.extern.modulemap similarity index 100% rename from interpreter/llvm/src/include/llvm/module.extern.modulemap rename to interpreter/llvm-project/llvm/include/llvm/module.extern.modulemap diff --git a/interpreter/llvm/src/include/llvm/module.install.modulemap b/interpreter/llvm-project/llvm/include/llvm/module.install.modulemap similarity index 100% rename from interpreter/llvm/src/include/llvm/module.install.modulemap rename to interpreter/llvm-project/llvm/include/llvm/module.install.modulemap diff --git a/interpreter/llvm/src/include/llvm/module.modulemap b/interpreter/llvm-project/llvm/include/llvm/module.modulemap similarity index 100% rename from interpreter/llvm/src/include/llvm/module.modulemap rename to interpreter/llvm-project/llvm/include/llvm/module.modulemap diff --git a/interpreter/llvm/src/include/llvm/module.modulemap.build b/interpreter/llvm-project/llvm/include/llvm/module.modulemap.build similarity index 100% rename from interpreter/llvm/src/include/llvm/module.modulemap.build rename to interpreter/llvm-project/llvm/include/llvm/module.modulemap.build diff --git a/interpreter/llvm/src/lib/Analysis/AliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/AliasAnalysisEvaluator.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisEvaluator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AliasAnalysisEvaluator.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisEvaluator.cpp diff --git a/interpreter/llvm/src/lib/Analysis/AliasAnalysisSummary.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisSummary.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AliasAnalysisSummary.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisSummary.cpp diff --git a/interpreter/llvm/src/lib/Analysis/AliasAnalysisSummary.h b/interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisSummary.h similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AliasAnalysisSummary.h rename to interpreter/llvm-project/llvm/lib/Analysis/AliasAnalysisSummary.h diff --git a/interpreter/llvm/src/lib/Analysis/AliasSetTracker.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AliasSetTracker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AliasSetTracker.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AliasSetTracker.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Analysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Analysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Analysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Analysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/AssumeBundleQueries.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AssumeBundleQueries.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AssumeBundleQueries.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AssumeBundleQueries.cpp diff --git a/interpreter/llvm/src/lib/Analysis/AssumptionCache.cpp b/interpreter/llvm-project/llvm/lib/Analysis/AssumptionCache.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/AssumptionCache.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/AssumptionCache.cpp diff --git a/interpreter/llvm/src/lib/Analysis/BasicAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/BasicAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/BasicAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/BasicAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/BlockFrequencyInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/BlockFrequencyInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/BlockFrequencyInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/BlockFrequencyInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/BlockFrequencyInfoImpl.cpp b/interpreter/llvm-project/llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/BlockFrequencyInfoImpl.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp diff --git a/interpreter/llvm/src/lib/Analysis/BranchProbabilityInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/BranchProbabilityInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/BranchProbabilityInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/BranchProbabilityInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CFG.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CFG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CFG.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CFG.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CFGPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CFGPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CFGPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CFGPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CFLAndersAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CFLAndersAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CFLGraph.h b/interpreter/llvm-project/llvm/lib/Analysis/CFLGraph.h similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CFLGraph.h rename to interpreter/llvm-project/llvm/lib/Analysis/CFLGraph.h diff --git a/interpreter/llvm/src/lib/Analysis/CFLSteensAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CFLSteensAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CGSCCPassManager.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CGSCCPassManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CGSCCPassManager.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CGSCCPassManager.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Analysis/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Analysis/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Analysis/CallGraph.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CallGraph.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CallGraph.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CallGraph.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CallGraphSCCPass.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CallGraphSCCPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CallGraphSCCPass.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CallGraphSCCPass.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CallPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CallPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CallPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CallPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CaptureTracking.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CaptureTracking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CaptureTracking.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CaptureTracking.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CmpInstAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CmpInstAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CmpInstAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CmpInstAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CodeMetrics.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CodeMetrics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CodeMetrics.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CodeMetrics.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ConstantFolding.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ConstantFolding.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ConstantFolding.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ConstantFolding.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ConstraintSystem.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ConstraintSystem.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ConstraintSystem.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ConstraintSystem.cpp diff --git a/interpreter/llvm/src/lib/Analysis/CostModel.cpp b/interpreter/llvm-project/llvm/lib/Analysis/CostModel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/CostModel.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/CostModel.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DDG.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DDG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DDG.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DDG.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DDGPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DDGPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DDGPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DDGPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Delinearization.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Delinearization.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Delinearization.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Delinearization.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DemandedBits.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DemandedBits.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DemandedBits.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DemandedBits.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DependenceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DependenceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DependenceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DependenceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DependenceGraphBuilder.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DependenceGraphBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DependenceGraphBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DependenceGraphBuilder.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DevelopmentModeInlineAdvisor.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DevelopmentModeInlineAdvisor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DevelopmentModeInlineAdvisor.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DevelopmentModeInlineAdvisor.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DivergenceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DivergenceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DivergenceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DivergenceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DomPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DomPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DomPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DomPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DomTreeUpdater.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DomTreeUpdater.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DomTreeUpdater.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DomTreeUpdater.cpp diff --git a/interpreter/llvm/src/lib/Analysis/DominanceFrontier.cpp b/interpreter/llvm-project/llvm/lib/Analysis/DominanceFrontier.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/DominanceFrontier.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/DominanceFrontier.cpp diff --git a/interpreter/llvm/src/lib/Analysis/EHPersonalities.cpp b/interpreter/llvm-project/llvm/lib/Analysis/EHPersonalities.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/EHPersonalities.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/EHPersonalities.cpp diff --git a/interpreter/llvm/src/lib/Analysis/FunctionPropertiesAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/FunctionPropertiesAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/GlobalsModRef.cpp b/interpreter/llvm-project/llvm/lib/Analysis/GlobalsModRef.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/GlobalsModRef.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/GlobalsModRef.cpp diff --git a/interpreter/llvm/src/lib/Analysis/GuardUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/GuardUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/GuardUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/GuardUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/HeatUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/HeatUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/HeatUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/HeatUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/IRSimilarityIdentifier.cpp b/interpreter/llvm-project/llvm/lib/Analysis/IRSimilarityIdentifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/IRSimilarityIdentifier.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/IRSimilarityIdentifier.cpp diff --git a/interpreter/llvm/src/lib/Analysis/IVDescriptors.cpp b/interpreter/llvm-project/llvm/lib/Analysis/IVDescriptors.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/IVDescriptors.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/IVDescriptors.cpp diff --git a/interpreter/llvm/src/lib/Analysis/IVUsers.cpp b/interpreter/llvm-project/llvm/lib/Analysis/IVUsers.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/IVUsers.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/IVUsers.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ImportedFunctionsInliningStatistics.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ImportedFunctionsInliningStatistics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ImportedFunctionsInliningStatistics.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ImportedFunctionsInliningStatistics.cpp diff --git a/interpreter/llvm/src/lib/Analysis/IndirectCallPromotionAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/IndirectCallPromotionAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/IndirectCallPromotionAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/IndirectCallPromotionAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InlineAdvisor.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InlineAdvisor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InlineAdvisor.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InlineAdvisor.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InlineCost.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InlineCost.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InlineCost.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InlineCost.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InlineSizeEstimatorAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InlineSizeEstimatorAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InlineSizeEstimatorAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InlineSizeEstimatorAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InstCount.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InstCount.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InstCount.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InstCount.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InstructionPrecedenceTracking.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InstructionPrecedenceTracking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InstructionPrecedenceTracking.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InstructionPrecedenceTracking.cpp diff --git a/interpreter/llvm/src/lib/Analysis/InstructionSimplify.cpp b/interpreter/llvm-project/llvm/lib/Analysis/InstructionSimplify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/InstructionSimplify.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/InstructionSimplify.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Interval.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Interval.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Interval.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Interval.cpp diff --git a/interpreter/llvm/src/lib/Analysis/IntervalPartition.cpp b/interpreter/llvm-project/llvm/lib/Analysis/IntervalPartition.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/IntervalPartition.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/IntervalPartition.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LazyBlockFrequencyInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LazyBlockFrequencyInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LazyBlockFrequencyInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LazyBlockFrequencyInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LazyBranchProbabilityInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LazyBranchProbabilityInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LazyBranchProbabilityInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LazyBranchProbabilityInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LazyCallGraph.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LazyCallGraph.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LazyCallGraph.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LazyCallGraph.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LazyValueInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LazyValueInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LazyValueInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LazyValueInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LegacyDivergenceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LegacyDivergenceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LegacyDivergenceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LegacyDivergenceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Lint.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Lint.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Lint.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Lint.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Loads.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Loads.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Loads.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Loads.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopAccessAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopAccessAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopAnalysisManager.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopAnalysisManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopAnalysisManager.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopAnalysisManager.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopCacheAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopCacheAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopCacheAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopCacheAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopNestAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopNestAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopNestAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopNestAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopPass.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopPass.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopPass.cpp diff --git a/interpreter/llvm/src/lib/Analysis/LoopUnrollAnalyzer.cpp b/interpreter/llvm-project/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/LoopUnrollAnalyzer.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MLInlineAdvisor.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MLInlineAdvisor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MLInlineAdvisor.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MLInlineAdvisor.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemDepPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemDepPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemDepPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemDepPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemDerefPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemDerefPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemDerefPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemDerefPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemoryBuiltins.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemoryBuiltins.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemoryBuiltins.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemoryBuiltins.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemoryDependenceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemoryDependenceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemoryLocation.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemoryLocation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemoryLocation.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemoryLocation.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemorySSA.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemorySSA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemorySSA.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemorySSA.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MemorySSAUpdater.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MemorySSAUpdater.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MemorySSAUpdater.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MemorySSAUpdater.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ModuleDebugInfoPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ModuleDebugInfoPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ModuleDebugInfoPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ModuleDebugInfoPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ModuleSummaryAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ModuleSummaryAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/MustExecute.cpp b/interpreter/llvm-project/llvm/lib/Analysis/MustExecute.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/MustExecute.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/MustExecute.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ObjCARCAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ObjCARCAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ObjCARCAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ObjCARCAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ObjCARCAnalysisUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ObjCARCAnalysisUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ObjCARCAnalysisUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ObjCARCAnalysisUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ObjCARCInstKind.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ObjCARCInstKind.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ObjCARCInstKind.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ObjCARCInstKind.cpp diff --git a/interpreter/llvm/src/lib/Analysis/OptimizationRemarkEmitter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/OptimizationRemarkEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/OptimizationRemarkEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/OptimizationRemarkEmitter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/OverflowInstAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/OverflowInstAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/OverflowInstAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/OverflowInstAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/PHITransAddr.cpp b/interpreter/llvm-project/llvm/lib/Analysis/PHITransAddr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/PHITransAddr.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/PHITransAddr.cpp diff --git a/interpreter/llvm/src/lib/Analysis/PhiValues.cpp b/interpreter/llvm-project/llvm/lib/Analysis/PhiValues.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/PhiValues.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/PhiValues.cpp diff --git a/interpreter/llvm/src/lib/Analysis/PostDominators.cpp b/interpreter/llvm-project/llvm/lib/Analysis/PostDominators.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/PostDominators.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/PostDominators.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ProfileSummaryInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ProfileSummaryInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ProfileSummaryInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ProfileSummaryInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/PtrUseVisitor.cpp b/interpreter/llvm-project/llvm/lib/Analysis/PtrUseVisitor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/PtrUseVisitor.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/PtrUseVisitor.cpp diff --git a/interpreter/llvm/src/lib/Analysis/README.txt b/interpreter/llvm-project/llvm/lib/Analysis/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Analysis/README.txt rename to interpreter/llvm-project/llvm/lib/Analysis/README.txt diff --git a/interpreter/llvm/src/lib/Analysis/RegionInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/RegionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/RegionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/RegionInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/RegionPass.cpp b/interpreter/llvm-project/llvm/lib/Analysis/RegionPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/RegionPass.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/RegionPass.cpp diff --git a/interpreter/llvm/src/lib/Analysis/RegionPrinter.cpp b/interpreter/llvm-project/llvm/lib/Analysis/RegionPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/RegionPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/RegionPrinter.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ReleaseModeModelRunner.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ReleaseModeModelRunner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ReleaseModeModelRunner.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ReleaseModeModelRunner.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ReplayInlineAdvisor.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ReplayInlineAdvisor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ReplayInlineAdvisor.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ReplayInlineAdvisor.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ScalarEvolution.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ScalarEvolution.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ScalarEvolutionAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ScalarEvolutionAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ScalarEvolutionDivision.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionDivision.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ScalarEvolutionDivision.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionDivision.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ScalarEvolutionNormalization.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ScalarEvolutionNormalization.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ScopedNoAliasAA.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ScopedNoAliasAA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ScopedNoAliasAA.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ScopedNoAliasAA.cpp diff --git a/interpreter/llvm/src/lib/Analysis/StackLifetime.cpp b/interpreter/llvm-project/llvm/lib/Analysis/StackLifetime.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/StackLifetime.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/StackLifetime.cpp diff --git a/interpreter/llvm/src/lib/Analysis/StackSafetyAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/StackSafetyAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/StackSafetyAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/StackSafetyAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/StratifiedSets.h b/interpreter/llvm-project/llvm/lib/Analysis/StratifiedSets.h similarity index 100% rename from interpreter/llvm/src/lib/Analysis/StratifiedSets.h rename to interpreter/llvm-project/llvm/lib/Analysis/StratifiedSets.h diff --git a/interpreter/llvm/src/lib/Analysis/SyncDependenceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/SyncDependenceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/SyncDependenceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/SyncDependenceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/SyntheticCountsUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/SyntheticCountsUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/SyntheticCountsUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/SyntheticCountsUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/TFUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/TFUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/TFUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/TFUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/TargetLibraryInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/TargetLibraryInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/TargetLibraryInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/TargetLibraryInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/TargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Analysis/TargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/TargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/TargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Analysis/Trace.cpp b/interpreter/llvm-project/llvm/lib/Analysis/Trace.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/Trace.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/Trace.cpp diff --git a/interpreter/llvm/src/lib/Analysis/TypeBasedAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/TypeBasedAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Analysis/TypeMetadataUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/TypeMetadataUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/TypeMetadataUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/TypeMetadataUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/VFABIDemangling.cpp b/interpreter/llvm-project/llvm/lib/Analysis/VFABIDemangling.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/VFABIDemangling.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/VFABIDemangling.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ValueLattice.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ValueLattice.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ValueLattice.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ValueLattice.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ValueLatticeUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ValueLatticeUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ValueLatticeUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ValueLatticeUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/ValueTracking.cpp b/interpreter/llvm-project/llvm/lib/Analysis/ValueTracking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/ValueTracking.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/ValueTracking.cpp diff --git a/interpreter/llvm/src/lib/Analysis/VectorUtils.cpp b/interpreter/llvm-project/llvm/lib/Analysis/VectorUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Analysis/VectorUtils.cpp rename to interpreter/llvm-project/llvm/lib/Analysis/VectorUtils.cpp diff --git a/interpreter/llvm/src/lib/Analysis/models/generate_mock_model.py b/interpreter/llvm-project/llvm/lib/Analysis/models/generate_mock_model.py similarity index 100% rename from interpreter/llvm/src/lib/Analysis/models/generate_mock_model.py rename to interpreter/llvm-project/llvm/lib/Analysis/models/generate_mock_model.py diff --git a/interpreter/llvm/src/lib/Analysis/models/inlining/config.py b/interpreter/llvm-project/llvm/lib/Analysis/models/inlining/config.py similarity index 100% rename from interpreter/llvm/src/lib/Analysis/models/inlining/config.py rename to interpreter/llvm-project/llvm/lib/Analysis/models/inlining/config.py diff --git a/interpreter/llvm/src/lib/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/AsmParser/LLLexer.cpp b/interpreter/llvm-project/llvm/lib/AsmParser/LLLexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/AsmParser/LLLexer.cpp rename to interpreter/llvm-project/llvm/lib/AsmParser/LLLexer.cpp diff --git a/interpreter/llvm/src/lib/AsmParser/LLParser.cpp b/interpreter/llvm-project/llvm/lib/AsmParser/LLParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/AsmParser/LLParser.cpp rename to interpreter/llvm-project/llvm/lib/AsmParser/LLParser.cpp diff --git a/interpreter/llvm/src/lib/AsmParser/Parser.cpp b/interpreter/llvm-project/llvm/lib/AsmParser/Parser.cpp similarity index 100% rename from interpreter/llvm/src/lib/AsmParser/Parser.cpp rename to interpreter/llvm-project/llvm/lib/AsmParser/Parser.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/AMDGPUMetadataVerifier.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/AMDGPUMetadataVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/AMDGPUMetadataVerifier.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/AMDGPUMetadataVerifier.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/BinaryFormat/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/BinaryFormat/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/BinaryFormat/Dwarf.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/Dwarf.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/Dwarf.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/Dwarf.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/ELF.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/ELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/ELF.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/ELF.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/MachO.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/MachO.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/MachO.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/MachO.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/Magic.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/Magic.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/Magic.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/Magic.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/Minidump.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/Minidump.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/Minidump.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/Minidump.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/MsgPackDocument.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackDocument.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/MsgPackDocument.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackDocument.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/MsgPackDocumentYAML.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackDocumentYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/MsgPackDocumentYAML.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackDocumentYAML.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/MsgPackReader.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/MsgPackReader.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackReader.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/MsgPackWriter.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/MsgPackWriter.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/MsgPackWriter.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/Wasm.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/Wasm.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/Wasm.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/Wasm.cpp diff --git a/interpreter/llvm/src/lib/BinaryFormat/XCOFF.cpp b/interpreter/llvm-project/llvm/lib/BinaryFormat/XCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/BinaryFormat/XCOFF.cpp rename to interpreter/llvm-project/llvm/lib/BinaryFormat/XCOFF.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Bitcode/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Bitcode/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/BitReader.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/BitReader.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitReader.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/BitcodeAnalyzer.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/BitcodeAnalyzer.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/BitcodeReader.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/BitcodeReader.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/MetadataLoader.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/MetadataLoader.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/MetadataLoader.h b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.h similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/MetadataLoader.h rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.h diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/ValueList.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/ValueList.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/ValueList.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/ValueList.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Reader/ValueList.h b/interpreter/llvm-project/llvm/lib/Bitcode/Reader/ValueList.h similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Reader/ValueList.h rename to interpreter/llvm-project/llvm/lib/Bitcode/Reader/ValueList.h diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/BitWriter.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/BitWriter.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitWriter.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/BitcodeWriter.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/BitcodeWriter.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/BitcodeWriterPass.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/BitcodeWriterPass.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriterPass.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/ValueEnumerator.cpp b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/ValueEnumerator.cpp rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp diff --git a/interpreter/llvm/src/lib/Bitcode/Writer/ValueEnumerator.h b/interpreter/llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.h similarity index 100% rename from interpreter/llvm/src/lib/Bitcode/Writer/ValueEnumerator.h rename to interpreter/llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.h diff --git a/interpreter/llvm/src/lib/Bitstream/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Bitstream/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Bitstream/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Bitstream/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Bitstream/Reader/BitstreamReader.cpp b/interpreter/llvm-project/llvm/lib/Bitstream/Reader/BitstreamReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Bitstream/Reader/BitstreamReader.cpp rename to interpreter/llvm-project/llvm/lib/Bitstream/Reader/BitstreamReader.cpp diff --git a/interpreter/llvm/src/lib/Bitstream/Reader/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Bitstream/Reader/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Bitstream/Reader/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Bitstream/Reader/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/AggressiveAntiDepBreaker.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AggressiveAntiDepBreaker.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AggressiveAntiDepBreaker.h b/interpreter/llvm-project/llvm/lib/CodeGen/AggressiveAntiDepBreaker.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AggressiveAntiDepBreaker.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AggressiveAntiDepBreaker.h diff --git a/interpreter/llvm/src/lib/CodeGen/AllocationOrder.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AllocationOrder.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AllocationOrder.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AllocationOrder.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AllocationOrder.h b/interpreter/llvm-project/llvm/lib/CodeGen/AllocationOrder.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AllocationOrder.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AllocationOrder.h diff --git a/interpreter/llvm/src/lib/CodeGen/Analysis.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/Analysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/Analysis.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/Analysis.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AIXException.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AIXException.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AIXException.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AIXException.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/ARMException.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ARMException.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/ARMException.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ARMException.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AccelTable.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AccelTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AccelTable.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AccelTable.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AddressPool.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AddressPool.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AddressPool.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AddressPool.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AddressPool.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AddressPool.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AddressPool.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AddressPool.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp similarity index 99% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp index d53d5ec9bdc1c..d194fc683f075 100644 --- a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinter.cpp +++ b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp @@ -1643,8 +1643,8 @@ void AsmPrinter::emitGlobalIndirectSymbol(Module &M, OutStreamer->emitSymbolAttribute(Name, MCSA_Global); else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference); - // else - // assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); + else + assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); // Set the symbol type to function if the alias has a function type. // This affects codegen when the aliasee is not a function. @@ -1850,6 +1850,8 @@ bool AsmPrinter::doFinalization(Module &M) { SmallVector AliasStack; SmallPtrSet AliasVisited; for (const auto &Alias : M.aliases()) { + if (Alias.hasAvailableExternallyLinkage()) + continue; for (const GlobalAlias *Cur = &Alias; Cur; Cur = dyn_cast(Cur->getAliasee())) { if (!AliasVisited.insert(Cur).second) diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/ByteStreamer.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ByteStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/ByteStreamer.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ByteStreamer.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/CodeViewDebug.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/CodeViewDebug.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIE.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIE.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIE.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIE.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHash.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHash.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHash.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHash.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHashAttributes.def b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHashAttributes.def similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DIEHashAttributes.def rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHashAttributes.def diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocEntry.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocEntry.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocEntry.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocEntry.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocStream.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocStream.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocStream.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocStream.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocStream.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DebugLocStream.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugLocStream.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfDebug.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfDebug.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfDebug.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfDebug.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfException.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfException.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfException.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfException.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfExpression.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfExpression.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfExpression.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfExpression.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfFile.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfFile.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfFile.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfFile.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfFile.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfStringPool.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfStringPool.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfUnit.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfUnit.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfUnit.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/DwarfUnit.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/EHStreamer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/EHStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/EHStreamer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/EHStreamer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/EHStreamer.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/EHStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/EHStreamer.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/EHStreamer.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/ErlangGCPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ErlangGCPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/ErlangGCPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/ErlangGCPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/PseudoProbePrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/PseudoProbePrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/PseudoProbePrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/PseudoProbePrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/PseudoProbePrinter.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/PseudoProbePrinter.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/PseudoProbePrinter.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/PseudoProbePrinter.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WasmException.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WasmException.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WasmException.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WasmException.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WasmException.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WasmException.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WasmException.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WasmException.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinCFGuard.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinCFGuard.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinCFGuard.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinCFGuard.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinCFGuard.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinCFGuard.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinCFGuard.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinCFGuard.h diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinException.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinException.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinException.h b/interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AsmPrinter/WinException.h rename to interpreter/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.h diff --git a/interpreter/llvm/src/lib/CodeGen/AtomicExpandPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/AtomicExpandPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/AtomicExpandPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/AtomicExpandPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/BasicBlockSections.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BasicBlockSections.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/BasicTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/BasicTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BasicTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/BasicTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/BranchFolding.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/BranchFolding.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BranchFolding.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/BranchFolding.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/BranchFolding.h b/interpreter/llvm-project/llvm/lib/CodeGen/BranchFolding.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BranchFolding.h rename to interpreter/llvm-project/llvm/lib/CodeGen/BranchFolding.h diff --git a/interpreter/llvm/src/lib/CodeGen/BranchRelaxation.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/BranchRelaxation.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BranchRelaxation.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/BranchRelaxation.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/BreakFalseDeps.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/BreakFalseDeps.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/BreakFalseDeps.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/BreakFalseDeps.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CFGuardLongjmp.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CFGuardLongjmp.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CFGuardLongjmp.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CFGuardLongjmp.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CFIInstrInserter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CFIInstrInserter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CFIInstrInserter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CFIInstrInserter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CodeGen/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/CalcSpillWeights.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CalcSpillWeights.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CalcSpillWeights.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CalcSpillWeights.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CallingConvLower.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CallingConvLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CallingConvLower.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CallingConvLower.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CodeGen.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CodeGen.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CodeGen.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CodeGen.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CodeGenPassBuilder.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CodeGenPassBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CodeGenPassBuilder.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CodeGenPassBuilder.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CodeGenPrepare.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CodeGenPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CodeGenPrepare.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CodeGenPrepare.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CommandFlags.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CommandFlags.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CommandFlags.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CommandFlags.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CriticalAntiDepBreaker.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CriticalAntiDepBreaker.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/CriticalAntiDepBreaker.h b/interpreter/llvm-project/llvm/lib/CodeGen/CriticalAntiDepBreaker.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/CriticalAntiDepBreaker.h rename to interpreter/llvm-project/llvm/lib/CodeGen/CriticalAntiDepBreaker.h diff --git a/interpreter/llvm/src/lib/CodeGen/DFAPacketizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/DFAPacketizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/DFAPacketizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/DFAPacketizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/DeadMachineInstructionElim.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/DeadMachineInstructionElim.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/DeadMachineInstructionElim.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/DeadMachineInstructionElim.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/DetectDeadLanes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/DetectDeadLanes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/DetectDeadLanes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/DetectDeadLanes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/DwarfEHPrepare.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/DwarfEHPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/DwarfEHPrepare.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/DwarfEHPrepare.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/EHContGuardCatchret.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/EHContGuardCatchret.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/EHContGuardCatchret.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/EHContGuardCatchret.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/EarlyIfConversion.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/EarlyIfConversion.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/EarlyIfConversion.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/EarlyIfConversion.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/EdgeBundles.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/EdgeBundles.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/EdgeBundles.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/EdgeBundles.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ExecutionDomainFix.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ExecutionDomainFix.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ExecutionDomainFix.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ExecutionDomainFix.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ExpandMemCmp.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ExpandMemCmp.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ExpandMemCmp.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ExpandMemCmp.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ExpandPostRAPseudos.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ExpandPostRAPseudos.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ExpandReductions.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ExpandReductions.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ExpandReductions.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ExpandReductions.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ExpandVectorPredication.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ExpandVectorPredication.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ExpandVectorPredication.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ExpandVectorPredication.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/FEntryInserter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/FEntryInserter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/FEntryInserter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/FEntryInserter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/FaultMaps.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/FaultMaps.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/FaultMaps.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/FaultMaps.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/FinalizeISel.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/FinalizeISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/FinalizeISel.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/FinalizeISel.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/FixupStatepointCallerSaved.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/FixupStatepointCallerSaved.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/FixupStatepointCallerSaved.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/FixupStatepointCallerSaved.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/FuncletLayout.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/FuncletLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/FuncletLayout.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/FuncletLayout.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GCMetadata.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GCMetadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GCMetadata.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GCMetadata.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GCMetadataPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GCMetadataPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GCMetadataPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GCMetadataPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GCRootLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GCRootLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GCRootLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GCRootLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/CSEInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CSEInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/CSEInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CSEInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/CSEMIRBuilder.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CSEMIRBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/CSEMIRBuilder.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CSEMIRBuilder.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/CallLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/CallLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CallLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/Combiner.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Combiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/Combiner.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Combiner.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/CombinerHelper.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/CombinerHelper.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/GISelChangeObserver.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GISelChangeObserver.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/GISelChangeObserver.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GISelChangeObserver.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/GISelKnownBits.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GISelKnownBits.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/GISelKnownBits.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GISelKnownBits.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/GlobalISel.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GlobalISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/GlobalISel.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/GlobalISel.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/IRTranslator.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/IRTranslator.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/InstructionSelect.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InstructionSelect.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/InstructionSelect.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InstructionSelect.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/InstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/InstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/InstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalityPredicates.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalityPredicates.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizeMutations.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizeMutations.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizeMutations.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizeMutations.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/Legalizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Legalizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/Legalizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Legalizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizerHelper.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizerHelper.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/Localizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Localizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/Localizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Localizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/LostDebugLocObserver.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LostDebugLocObserver.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/LostDebugLocObserver.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/LostDebugLocObserver.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/MachineIRBuilder.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/MachineIRBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/MachineIRBuilder.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/MachineIRBuilder.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/RegBankSelect.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/RegBankSelect.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/RegisterBank.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegisterBank.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/RegisterBank.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegisterBank.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/RegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/RegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/RegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalISel/Utils.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Utils.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalISel/Utils.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalISel/Utils.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/GlobalMerge.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/GlobalMerge.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/GlobalMerge.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/GlobalMerge.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/HardwareLoops.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/HardwareLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/HardwareLoops.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/HardwareLoops.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/IfConversion.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/IfConversion.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/IfConversion.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/IfConversion.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ImplicitNullChecks.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ImplicitNullChecks.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ImplicitNullChecks.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ImplicitNullChecks.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/IndirectBrExpandPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/IndirectBrExpandPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/IndirectBrExpandPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/IndirectBrExpandPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/InlineSpiller.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/InlineSpiller.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/InlineSpiller.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/InlineSpiller.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/InterferenceCache.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/InterferenceCache.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/InterferenceCache.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/InterferenceCache.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/InterferenceCache.h b/interpreter/llvm-project/llvm/lib/CodeGen/InterferenceCache.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/InterferenceCache.h rename to interpreter/llvm-project/llvm/lib/CodeGen/InterferenceCache.h diff --git a/interpreter/llvm/src/lib/CodeGen/InterleavedAccessPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/InterleavedAccessPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/InterleavedAccessPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/InterleavedAccessPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/InterleavedLoadCombinePass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/InterleavedLoadCombinePass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/InterleavedLoadCombinePass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/InterleavedLoadCombinePass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/IntrinsicLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/IntrinsicLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/IntrinsicLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/IntrinsicLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LLVMTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LLVMTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LLVMTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LLVMTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LatencyPriorityQueue.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LatencyPriorityQueue.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LatencyPriorityQueue.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LatencyPriorityQueue.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LazyMachineBlockFrequencyInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LazyMachineBlockFrequencyInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LazyMachineBlockFrequencyInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LazyMachineBlockFrequencyInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LexicalScopes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LexicalScopes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LexicalScopes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LexicalScopes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugValues/LiveDebugValues.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/LiveDebugValues.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugValues/LiveDebugValues.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/LiveDebugValues.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugValues/LiveDebugValues.h b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/LiveDebugValues.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugValues/LiveDebugValues.h rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/LiveDebugValues.h diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp similarity index 99% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp index 1e6d65c189535..17b1651d064fb 100644 --- a/interpreter/llvm/src/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp +++ b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp @@ -626,7 +626,7 @@ class VarLocBasedLDV : public LDVImpl { unsigned getRegIdx(Register Reg) const { for (unsigned Idx = 0; Idx < Locs.size(); ++Idx) if (Locs[Idx].Kind == MachineLocKind::RegisterKind && - Locs[Idx].Value.RegNo == Reg) + Register{static_cast(Locs[Idx].Value.RegNo)} == Reg) return Idx; llvm_unreachable("Could not find given Reg in Locs"); } diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugVariables.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugVariables.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveDebugVariables.h b/interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugVariables.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveDebugVariables.h rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveDebugVariables.h diff --git a/interpreter/llvm/src/lib/CodeGen/LiveInterval.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveInterval.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveInterval.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveInterval.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveIntervalCalc.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervalCalc.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveIntervalCalc.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervalCalc.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveIntervalUnion.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervalUnion.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveIntervalUnion.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervalUnion.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveIntervals.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervals.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveIntervals.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveIntervals.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LivePhysRegs.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LivePhysRegs.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LivePhysRegs.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LivePhysRegs.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRangeCalc.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeCalc.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRangeCalc.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeCalc.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRangeEdit.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeEdit.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRangeEdit.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeEdit.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRangeShrink.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeShrink.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRangeShrink.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeShrink.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRangeUtils.h b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeUtils.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRangeUtils.h rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRangeUtils.h diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRegMatrix.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRegMatrix.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRegMatrix.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRegMatrix.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveRegUnits.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveRegUnits.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveRegUnits.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveRegUnits.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveStacks.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveStacks.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveStacks.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveStacks.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LiveVariables.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LiveVariables.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LiveVariables.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LiveVariables.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LocalStackSlotAllocation.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LocalStackSlotAllocation.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LoopTraversal.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LoopTraversal.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LoopTraversal.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LoopTraversal.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LowLevelType.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LowLevelType.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LowLevelType.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LowLevelType.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/LowerEmuTLS.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/LowerEmuTLS.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/LowerEmuTLS.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/LowerEmuTLS.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MBFIWrapper.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MBFIWrapper.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MBFIWrapper.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MBFIWrapper.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRCanonicalizerPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRCanonicalizerPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRCanonicalizerPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRCanonicalizerPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRFSDiscriminator.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRFSDiscriminator.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRFSDiscriminator.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRFSDiscriminator.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRNamerPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRNamerPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRNamerPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRNamerPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/MIRParser/MILexer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MILexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRParser/MILexer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MILexer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRParser/MILexer.h b/interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MILexer.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRParser/MILexer.h rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MILexer.h diff --git a/interpreter/llvm/src/lib/CodeGen/MIRParser/MIParser.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MIParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRParser/MIParser.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MIParser.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRParser/MIRParser.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MIRParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRParser/MIRParser.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRParser/MIRParser.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRPrintingPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRPrintingPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRPrintingPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRPrintingPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRVRegNamerUtils.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRVRegNamerUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRVRegNamerUtils.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRVRegNamerUtils.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MIRVRegNamerUtils.h b/interpreter/llvm-project/llvm/lib/CodeGen/MIRVRegNamerUtils.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRVRegNamerUtils.h rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRVRegNamerUtils.h diff --git a/interpreter/llvm/src/lib/CodeGen/MIRYamlMapping.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MIRYamlMapping.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MIRYamlMapping.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MIRYamlMapping.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineBasicBlock.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineBasicBlock.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineBlockFrequencyInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineBlockFrequencyInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineBlockFrequencyInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineBlockFrequencyInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineBlockPlacement.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineBlockPlacement.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineBranchProbabilityInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineBranchProbabilityInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineBranchProbabilityInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineBranchProbabilityInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineCSE.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineCSE.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineCSE.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineCSE.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineCheckDebugify.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineCheckDebugify.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineCheckDebugify.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineCheckDebugify.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineCombiner.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineCombiner.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineCombiner.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineCopyPropagation.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineCopyPropagation.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineDebugify.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineDebugify.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineDebugify.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineDebugify.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineDominanceFrontier.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineDominanceFrontier.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineDominanceFrontier.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineDominanceFrontier.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineDominators.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineDominators.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineDominators.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineDominators.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineFrameInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineFrameInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineFrameInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineFrameInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineFunction.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineFunction.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineFunction.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineFunctionPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineFunctionPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineFunctionPrinterPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionPrinterPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineFunctionPrinterPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionPrinterPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineFunctionSplitter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionSplitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineFunctionSplitter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineFunctionSplitter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineInstr.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineInstr.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineInstr.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineInstr.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineInstrBundle.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineInstrBundle.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineInstrBundle.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineInstrBundle.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineLICM.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineLICM.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineLICM.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineLICM.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineLoopInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineLoopInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineLoopInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineLoopInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineLoopUtils.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineLoopUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineLoopUtils.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineLoopUtils.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineModuleInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineModuleInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineModuleInfoImpls.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleInfoImpls.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineModuleInfoImpls.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleInfoImpls.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineModuleSlotTracker.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleSlotTracker.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineModuleSlotTracker.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineModuleSlotTracker.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineOperand.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineOperand.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineOperand.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineOperand.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineOptimizationRemarkEmitter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineOptimizationRemarkEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineOptimizationRemarkEmitter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineOptimizationRemarkEmitter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineOutliner.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineOutliner.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineOutliner.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineOutliner.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachinePassManager.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachinePassManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachinePassManager.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachinePassManager.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachinePipeliner.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachinePipeliner.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachinePipeliner.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachinePipeliner.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachinePostDominators.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachinePostDominators.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachinePostDominators.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachinePostDominators.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineRegionInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineRegionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineRegionInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineRegionInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineSSAUpdater.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineSSAUpdater.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineSSAUpdater.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineSSAUpdater.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineSink.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineSink.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineSink.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineSink.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineSizeOpts.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineSizeOpts.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineSizeOpts.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineSizeOpts.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineStableHash.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineStableHash.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineStableHash.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineStableHash.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineStripDebug.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineStripDebug.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineStripDebug.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineStripDebug.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineTraceMetrics.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineTraceMetrics.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineTraceMetrics.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineTraceMetrics.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MachineVerifier.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MachineVerifier.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MacroFusion.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MacroFusion.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ModuloSchedule.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ModuloSchedule.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ModuloSchedule.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ModuloSchedule.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/MultiHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/MultiHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/MultiHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/MultiHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/NonRelocatableStringpool.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/NonRelocatableStringpool.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/NonRelocatableStringpool.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/NonRelocatableStringpool.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/OptimizePHIs.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/OptimizePHIs.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/OptimizePHIs.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/OptimizePHIs.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PHIElimination.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PHIElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PHIElimination.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PHIElimination.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PHIEliminationUtils.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PHIEliminationUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PHIEliminationUtils.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PHIEliminationUtils.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PHIEliminationUtils.h b/interpreter/llvm-project/llvm/lib/CodeGen/PHIEliminationUtils.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PHIEliminationUtils.h rename to interpreter/llvm-project/llvm/lib/CodeGen/PHIEliminationUtils.h diff --git a/interpreter/llvm/src/lib/CodeGen/ParallelCG.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ParallelCG.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ParallelCG.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ParallelCG.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PatchableFunction.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PatchableFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PatchableFunction.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PatchableFunction.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PeepholeOptimizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PeepholeOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PeepholeOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PeepholeOptimizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PostRAHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PostRAHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PostRAHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PostRAHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PostRASchedulerList.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PostRASchedulerList.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PostRASchedulerList.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PostRASchedulerList.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PreISelIntrinsicLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PreISelIntrinsicLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ProcessImplicitDefs.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ProcessImplicitDefs.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ProcessImplicitDefs.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ProcessImplicitDefs.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PrologEpilogInserter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PrologEpilogInserter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PseudoProbeInserter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PseudoProbeInserter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PseudoProbeInserter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PseudoProbeInserter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/PseudoSourceValue.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/PseudoSourceValue.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/PseudoSourceValue.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/PseudoSourceValue.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RDFGraph.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RDFGraph.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RDFGraph.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RDFGraph.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RDFLiveness.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RDFLiveness.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RDFLiveness.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RDFLiveness.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RDFRegisters.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RDFRegisters.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RDFRegisters.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RDFRegisters.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/README.txt b/interpreter/llvm-project/llvm/lib/CodeGen/README.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/README.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/README.txt diff --git a/interpreter/llvm/src/lib/CodeGen/ReachingDefAnalysis.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ReachingDefAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocBase.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBase.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocBase.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBase.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocBase.h b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBase.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocBase.h rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBase.h diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocBasic.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBasic.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocBasic.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocBasic.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocFast.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocFast.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocFast.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocFast.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocGreedy.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocGreedy.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocGreedy.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocGreedy.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegAllocPBQP.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegAllocPBQP.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegAllocPBQP.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegAllocPBQP.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegUsageInfoCollector.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegUsageInfoCollector.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegUsageInfoCollector.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegUsageInfoCollector.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegUsageInfoPropagate.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegUsageInfoPropagate.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegUsageInfoPropagate.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegUsageInfoPropagate.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterClassInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterClassInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterClassInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterClassInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterCoalescer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterCoalescer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterCoalescer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterCoalescer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterCoalescer.h b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterCoalescer.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterCoalescer.h rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterCoalescer.h diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterPressure.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterPressure.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterPressure.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterPressure.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterScavenging.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterScavenging.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterScavenging.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterScavenging.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RegisterUsageInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RegisterUsageInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RegisterUsageInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RegisterUsageInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RemoveRedundantDebugValues.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RemoveRedundantDebugValues.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RemoveRedundantDebugValues.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RemoveRedundantDebugValues.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/RenameIndependentSubregs.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/RenameIndependentSubregs.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/RenameIndependentSubregs.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/RenameIndependentSubregs.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ReplaceWithVeclib.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ReplaceWithVeclib.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ReplaceWithVeclib.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ReplaceWithVeclib.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ResetMachineFunctionPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ResetMachineFunctionPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ResetMachineFunctionPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ResetMachineFunctionPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SafeStack.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SafeStack.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SafeStack.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SafeStack.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SafeStackLayout.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SafeStackLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SafeStackLayout.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SafeStackLayout.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SafeStackLayout.h b/interpreter/llvm-project/llvm/lib/CodeGen/SafeStackLayout.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SafeStackLayout.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SafeStackLayout.h diff --git a/interpreter/llvm/src/lib/CodeGen/ScheduleDAG.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ScheduleDAG.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAG.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ScheduleDAGInstrs.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ScheduleDAGInstrs.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ScheduleDAGPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAGPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ScheduleDAGPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ScheduleDAGPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ScoreboardHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ScoreboardHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/DAGCombiner.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/FastISel.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/FastISel.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/InstrEmitter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/InstrEmitter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/InstrEmitter.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/InstrEmitter.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypes.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypes.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ResourcePriorityQueue.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ResourcePriorityQueue.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ResourcePriorityQueue.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ResourcePriorityQueue.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SDNodeDbgValue.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SDNodeDbgValue.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SDNodeDbgValue.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SDNodeDbgValue.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGVLIW.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGVLIW.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/ScheduleDAGVLIW.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGVLIW.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAG.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGAddressAnalysis.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGAddressAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGAddressAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGAddressAnalysis.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/SelectionDAGTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/StatepointLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/StatepointLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/StatepointLowering.h b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/StatepointLowering.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.h diff --git a/interpreter/llvm/src/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SelectionDAG/TargetLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ShadowStackGCLowering.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ShadowStackGCLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ShadowStackGCLowering.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ShadowStackGCLowering.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ShrinkWrap.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ShrinkWrap.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ShrinkWrap.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ShrinkWrap.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SjLjEHPrepare.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SjLjEHPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SjLjEHPrepare.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SjLjEHPrepare.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SlotIndexes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SlotIndexes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SlotIndexes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SlotIndexes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SpillPlacement.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SpillPlacement.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SpillPlacement.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SpillPlacement.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SpillPlacement.h b/interpreter/llvm-project/llvm/lib/CodeGen/SpillPlacement.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SpillPlacement.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SpillPlacement.h diff --git a/interpreter/llvm/src/lib/CodeGen/SplitKit.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SplitKit.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SplitKit.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SplitKit.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SplitKit.h b/interpreter/llvm-project/llvm/lib/CodeGen/SplitKit.h similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SplitKit.h rename to interpreter/llvm-project/llvm/lib/CodeGen/SplitKit.h diff --git a/interpreter/llvm/src/lib/CodeGen/StackColoring.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/StackColoring.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/StackColoring.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/StackColoring.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/StackMapLivenessAnalysis.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/StackMapLivenessAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/StackMapLivenessAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/StackMapLivenessAnalysis.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/StackMaps.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/StackMaps.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/StackMaps.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/StackMaps.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/StackProtector.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/StackProtector.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/StackProtector.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/StackProtector.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/StackSlotColoring.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/StackSlotColoring.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/StackSlotColoring.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/StackSlotColoring.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SwiftErrorValueTracking.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SwiftErrorValueTracking.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SwiftErrorValueTracking.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SwiftErrorValueTracking.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/SwitchLoweringUtils.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/SwitchLoweringUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/SwitchLoweringUtils.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/SwitchLoweringUtils.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TailDuplication.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TailDuplication.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TailDuplication.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TailDuplication.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TailDuplicator.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TailDuplicator.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TailDuplicator.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TailDuplicator.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetFrameLoweringImpl.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetFrameLoweringImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetFrameLoweringImpl.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetFrameLoweringImpl.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetLoweringBase.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetLoweringBase.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetLoweringBase.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetLoweringBase.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetLoweringObjectFileImpl.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetLoweringObjectFileImpl.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetOptionsImpl.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetOptionsImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetOptionsImpl.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetOptionsImpl.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetPassConfig.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetPassConfig.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetPassConfig.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetPassConfig.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetSchedule.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetSchedule.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetSchedule.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetSchedule.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TargetSubtargetInfo.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TargetSubtargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TargetSubtargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TargetSubtargetInfo.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TwoAddressInstructionPass.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TwoAddressInstructionPass.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/TypePromotion.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/TypePromotion.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/TypePromotion.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/TypePromotion.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/UnreachableBlockElim.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/UnreachableBlockElim.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/UnreachableBlockElim.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/UnreachableBlockElim.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/ValueTypes.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/ValueTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/ValueTypes.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/ValueTypes.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/VirtRegMap.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/VirtRegMap.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/VirtRegMap.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/VirtRegMap.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/WasmEHPrepare.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/WasmEHPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/WasmEHPrepare.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/WasmEHPrepare.cpp diff --git a/interpreter/llvm/src/lib/CodeGen/WinEHPrepare.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/WinEHPrepare.cpp similarity index 99% rename from interpreter/llvm/src/lib/CodeGen/WinEHPrepare.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/WinEHPrepare.cpp index 388060230ffc8..4564aa1c1278d 100644 --- a/interpreter/llvm/src/lib/CodeGen/WinEHPrepare.cpp +++ b/interpreter/llvm-project/llvm/lib/CodeGen/WinEHPrepare.cpp @@ -1065,10 +1065,10 @@ bool WinEHPrepare::prepareExplicitEH(Function &F) { DemoteCatchSwitchPHIOnlyOpt); if (!DisableCleanups) { - //assert(!verifyFunction(F, &dbgs())); + assert(!verifyFunction(F, &dbgs())); removeImplausibleInstructions(F); - //assert(!verifyFunction(F, &dbgs())); + assert(!verifyFunction(F, &dbgs())); cleanupPreparedFunclets(F); } diff --git a/interpreter/llvm/src/lib/CodeGen/XRayInstrumentation.cpp b/interpreter/llvm-project/llvm/lib/CodeGen/XRayInstrumentation.cpp similarity index 100% rename from interpreter/llvm/src/lib/CodeGen/XRayInstrumentation.cpp rename to interpreter/llvm-project/llvm/lib/CodeGen/XRayInstrumentation.cpp diff --git a/interpreter/llvm/src/lib/DWARFLinker/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DWARFLinker/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DWARFLinker/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DWARFLinker/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DWARFLinker/DWARFLinker.cpp b/interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinker.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWARFLinker/DWARFLinker.cpp rename to interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinker.cpp diff --git a/interpreter/llvm/src/lib/DWARFLinker/DWARFLinkerCompileUnit.cpp b/interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinkerCompileUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWARFLinker/DWARFLinkerCompileUnit.cpp rename to interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinkerCompileUnit.cpp diff --git a/interpreter/llvm/src/lib/DWARFLinker/DWARFLinkerDeclContext.cpp b/interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinkerDeclContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWARFLinker/DWARFLinkerDeclContext.cpp rename to interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFLinkerDeclContext.cpp diff --git a/interpreter/llvm/src/lib/DWARFLinker/DWARFStreamer.cpp b/interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWARFLinker/DWARFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/DWARFLinker/DWARFStreamer.cpp diff --git a/interpreter/llvm/src/lib/DWP/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DWP/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DWP/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DWP/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DWP/DWP.cpp b/interpreter/llvm-project/llvm/lib/DWP/DWP.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWP/DWP.cpp rename to interpreter/llvm-project/llvm/lib/DWP/DWP.cpp diff --git a/interpreter/llvm/src/lib/DWP/DWPError.cpp b/interpreter/llvm-project/llvm/lib/DWP/DWPError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DWP/DWPError.cpp rename to interpreter/llvm-project/llvm/lib/DWP/DWPError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/AppendingTypeTableBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/AppendingTypeTableBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/AppendingTypeTableBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/AppendingTypeTableBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/CVTypeVisitor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/CVTypeVisitor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/CodeViewError.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CodeViewError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/CodeViewError.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CodeViewError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/ContinuationRecordBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/ContinuationRecordBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/ContinuationRecordBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/ContinuationRecordBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugChecksumsSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugChecksumsSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugChecksumsSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugChecksumsSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugCrossExSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugCrossExSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugCrossExSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugCrossExSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugCrossImpSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugCrossImpSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugCrossImpSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugCrossImpSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugFrameDataSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugFrameDataSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugFrameDataSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugFrameDataSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugInlineeLinesSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugInlineeLinesSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugInlineeLinesSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugInlineeLinesSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugLinesSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugLinesSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugLinesSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugLinesSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugStringTableSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugStringTableSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugStringTableSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugStringTableSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsectionRecord.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsectionRecord.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsectionRecord.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsectionRecord.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsectionVisitor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsectionVisitor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSubsectionVisitor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSubsectionVisitor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSymbolRVASubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSymbolRVASubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSymbolRVASubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSymbolRVASubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSymbolsSubsection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSymbolsSubsection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/DebugSymbolsSubsection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/DebugSymbolsSubsection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/EnumTables.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/EnumTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/EnumTables.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/EnumTables.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/Formatters.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/Formatters.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/Formatters.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/Formatters.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/GlobalTypeTableBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/GlobalTypeTableBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/GlobalTypeTableBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/GlobalTypeTableBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/LazyRandomTypeCollection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/LazyRandomTypeCollection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/LazyRandomTypeCollection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/LazyRandomTypeCollection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/Line.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/Line.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/Line.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/Line.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/MergingTypeTableBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/MergingTypeTableBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/MergingTypeTableBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/MergingTypeTableBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/RecordName.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/RecordName.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/RecordName.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/RecordName.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/RecordSerialization.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/RecordSerialization.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/RecordSerialization.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/RecordSerialization.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/SimpleTypeSerializer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SimpleTypeSerializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/SimpleTypeSerializer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SimpleTypeSerializer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/StringsAndChecksums.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/StringsAndChecksums.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/StringsAndChecksums.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/StringsAndChecksums.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolDumper.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolDumper.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolDumper.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolDumper.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolRecordHelpers.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolRecordHelpers.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolRecordHelpers.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolRecordHelpers.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolRecordMapping.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolRecordMapping.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolRecordMapping.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolRecordMapping.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolSerializer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolSerializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/SymbolSerializer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/SymbolSerializer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeHashing.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeHashing.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeHashing.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeHashing.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeIndex.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeIndex.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeIndex.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeIndex.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeIndexDiscovery.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeIndexDiscovery.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeIndexDiscovery.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeIndexDiscovery.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeRecordHelpers.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeRecordHelpers.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeRecordHelpers.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeRecordHelpers.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeRecordMapping.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeRecordMapping.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeStreamMerger.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeStreamMerger.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeStreamMerger.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeStreamMerger.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/CodeView/TypeTableCollection.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeTableCollection.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/CodeView/TypeTableCollection.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/CodeView/TypeTableCollection.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAcceleratorTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAcceleratorTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAcceleratorTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAcceleratorTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAddressRange.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAddressRange.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFAddressRange.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFAddressRange.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFCompileUnit.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFCompileUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFCompileUnit.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFCompileUnit.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFContext.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFContext.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDataExtractor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDataExtractor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDataExtractor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDataExtractor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAddr.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAddr.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAddr.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAddr.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugArangeSet.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugArangeSet.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugArangeSet.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugArangeSet.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugInfoEntry.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugInfoEntry.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugInfoEntry.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugInfoEntry.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugLine.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugLine.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugMacro.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugMacro.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugMacro.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugMacro.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugPubTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugPubTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugPubTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugPubTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugRnglists.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugRnglists.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDebugRnglists.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugRnglists.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDie.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFDie.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFExpression.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFExpression.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFExpression.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFExpression.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFFormValue.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFFormValue.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFGdbIndex.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFGdbIndex.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFGdbIndex.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFGdbIndex.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFListTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFListTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFListTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFListTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFLocationExpression.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFLocationExpression.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFLocationExpression.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFLocationExpression.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFUnit.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFUnit.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFUnitIndex.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFUnitIndex.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFUnitIndex.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFUnitIndex.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFVerifier.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/DWARF/DWARFVerifier.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/DwarfTransformer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/DwarfTransformer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/FileWriter.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/FileWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/FileWriter.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/FileWriter.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/FunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/FunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/FunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/FunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/GsymCreator.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/GsymCreator.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/GsymCreator.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/GsymCreator.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/GsymReader.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/GsymReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/GsymReader.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/GsymReader.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/Header.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/Header.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/Header.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/Header.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/InlineInfo.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/InlineInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/InlineInfo.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/InlineInfo.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/LineTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/LineTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/LineTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/LineTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/LookupResult.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/LookupResult.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/LookupResult.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/LookupResult.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/ObjectFileTransformer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/ObjectFileTransformer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/ObjectFileTransformer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/ObjectFileTransformer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/GSYM/Range.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/Range.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/GSYM/Range.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/GSYM/Range.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/MSF/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/MSF/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/MSF/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/MSF/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/MSF/MSFBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/MSF/MSFBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/MSF/MSFCommon.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFCommon.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/MSF/MSFCommon.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFCommon.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/MSF/MSFError.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/MSF/MSFError.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MSFError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/MSF/MappedBlockStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MappedBlockStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/MSF/MappedBlockStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/MSF/MappedBlockStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIADataStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIADataStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIADataStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIADataStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumDebugStreams.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumDebugStreams.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumDebugStreams.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumDebugStreams.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumFrameData.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumFrameData.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumFrameData.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumFrameData.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumInjectedSources.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumInjectedSources.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumInjectedSources.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumInjectedSources.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumLineNumbers.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumLineNumbers.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumLineNumbers.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumLineNumbers.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSectionContribs.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSectionContribs.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSectionContribs.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSectionContribs.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSourceFiles.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSourceFiles.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSourceFiles.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSourceFiles.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSymbols.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSymbols.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumSymbols.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumSymbols.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumTables.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAEnumTables.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAEnumTables.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAError.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAError.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAFrameData.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAFrameData.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAFrameData.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAFrameData.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAInjectedSource.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAInjectedSource.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIAInjectedSource.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIAInjectedSource.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIALineNumber.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIALineNumber.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIALineNumber.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIALineNumber.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIARawSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIARawSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIARawSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIARawSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASectionContrib.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASectionContrib.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASectionContrib.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASectionContrib.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASession.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASession.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASession.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASession.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASourceFile.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASourceFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIASourceFile.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIASourceFile.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIATable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIATable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/DIA/DIATable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/DIA/DIATable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/GenericError.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/GenericError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/GenericError.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/GenericError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/IPDBSourceFile.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/IPDBSourceFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/IPDBSourceFile.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/IPDBSourceFile.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleDescriptor.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleDescriptor.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleDescriptor.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleDescriptor.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleList.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleList.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiModuleList.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiModuleList.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/EnumTables.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/EnumTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/EnumTables.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/EnumTables.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/GSIStreamBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/GSIStreamBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/GSIStreamBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/GSIStreamBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/GlobalsStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/GlobalsStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/GlobalsStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/GlobalsStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/Hash.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/Hash.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/Hash.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/Hash.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/HashTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/HashTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/HashTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/HashTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/InfoStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InfoStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/InfoStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InfoStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/InfoStreamBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InfoStreamBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/InfoStreamBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InfoStreamBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/InjectedSourceStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InjectedSourceStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/InjectedSourceStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/InjectedSourceStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/ModuleDebugStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/ModuleDebugStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/ModuleDebugStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/ModuleDebugStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NamedStreamMap.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NamedStreamMap.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NamedStreamMap.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NamedStreamMap.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeCompilandSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeCompilandSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeCompilandSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeCompilandSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumGlobals.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumGlobals.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumGlobals.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumGlobals.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumInjectedSources.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumInjectedSources.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumInjectedSources.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumInjectedSources.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumLineNumbers.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumLineNumbers.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumLineNumbers.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumLineNumbers.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumModules.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumModules.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumModules.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumModules.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumSymbols.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumSymbols.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumSymbols.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumSymbols.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumTypes.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeEnumTypes.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeEnumTypes.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeExeSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeExeSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeExeSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeExeSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeFunctionSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeFunctionSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeFunctionSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeFunctionSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeInlineSiteSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeInlineSiteSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeInlineSiteSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeInlineSiteSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeLineNumber.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeLineNumber.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeLineNumber.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeLineNumber.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativePublicSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativePublicSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativePublicSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativePublicSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeRawSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeRawSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeRawSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeRawSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSession.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSession.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSourceFile.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSourceFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSourceFile.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSourceFile.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSymbolEnumerator.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSymbolEnumerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeSymbolEnumerator.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeSymbolEnumerator.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeArray.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeArray.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeArray.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeArray.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeBuiltin.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeBuiltin.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeBuiltin.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeBuiltin.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeEnum.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeEnum.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeEnum.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeEnum.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeFunctionSig.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeFunctionSig.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeFunctionSig.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeFunctionSig.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypePointer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypePointer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypePointer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypePointer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeTypedef.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeTypedef.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeTypedef.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeTypedef.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeUDT.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeUDT.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeUDT.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeUDT.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeVTShape.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeVTShape.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/NativeTypeVTShape.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/NativeTypeVTShape.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBFile.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBFile.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBFile.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBFileBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBFileBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBFileBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBFileBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBStringTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBStringTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBStringTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBStringTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBStringTableBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBStringTableBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/PDBStringTableBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBStringTableBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/PublicsStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PublicsStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/PublicsStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/PublicsStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/RawError.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/RawError.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/RawError.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/RawError.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/SymbolCache.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/SymbolCache.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/SymbolCache.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/SymbolCache.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/SymbolStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/SymbolStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/SymbolStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/SymbolStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiHashing.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiHashing.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiHashing.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiHashing.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiStream.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiStream.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiStream.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDB.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDB.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDB.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDB.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBContext.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBContext.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBContext.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBExtras.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBExtras.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBExtras.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBExtras.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBInterfaceAnchors.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBInterfaceAnchors.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBInterfaceAnchors.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBInterfaceAnchors.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymDumper.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymDumper.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymDumper.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymDumper.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolAnnotation.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolAnnotation.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolAnnotation.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolAnnotation.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolBlock.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolBlock.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolBlock.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolBlock.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompiland.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompiland.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompiland.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompiland.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompilandDetails.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompilandDetails.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompilandDetails.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompilandDetails.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompilandEnv.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompilandEnv.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCompilandEnv.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCompilandEnv.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCustom.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCustom.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolCustom.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolCustom.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolData.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolData.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolData.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolData.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolExe.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolExe.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolExe.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolExe.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFunc.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFunc.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFunc.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFunc.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFuncDebugEnd.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFuncDebugEnd.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFuncDebugEnd.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFuncDebugEnd.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFuncDebugStart.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFuncDebugStart.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolFuncDebugStart.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolFuncDebugStart.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolLabel.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolLabel.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolLabel.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolLabel.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolPublicSymbol.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolPublicSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolPublicSymbol.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolPublicSymbol.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolThunk.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolThunk.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolThunk.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolThunk.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeArray.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeArray.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeArray.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeArray.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeBaseClass.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeBaseClass.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeBaseClass.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeBaseClass.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeBuiltin.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeBuiltin.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeBuiltin.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeBuiltin.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeDimension.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeDimension.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeDimension.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeDimension.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFriend.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFriend.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFriend.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFriend.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFunctionArg.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionArg.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFunctionArg.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionArg.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeManaged.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeManaged.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeManaged.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeManaged.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypePointer.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypePointer.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypePointer.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypePointer.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeTypedef.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeTypedef.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeTypedef.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeTypedef.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeUDT.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeUDT.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeUDT.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeUDT.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeVTable.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeVTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeVTable.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeVTable.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeVTableShape.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeVTableShape.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolTypeVTableShape.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolTypeVTableShape.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolUnknown.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolUnknown.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolUnknown.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolUnknown.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolUsingNamespace.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolUsingNamespace.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/PDBSymbolUsingNamespace.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/PDBSymbolUsingNamespace.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/PDB/UDTLayout.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/PDB/UDTLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/PDB/UDTLayout.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/PDB/UDTLayout.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/Symbolize/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/Symbolize/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/DebugInfo/Symbolize/DIPrinter.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/Symbolize/DIPrinter.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/Symbolize/SymbolizableObjectFile.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/SymbolizableObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/Symbolize/SymbolizableObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/SymbolizableObjectFile.cpp diff --git a/interpreter/llvm/src/lib/DebugInfo/Symbolize/SymbolizableObjectFile.h b/interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/SymbolizableObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/Symbolize/SymbolizableObjectFile.h rename to interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/SymbolizableObjectFile.h diff --git a/interpreter/llvm/src/lib/DebugInfo/Symbolize/Symbolize.cpp b/interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp similarity index 100% rename from interpreter/llvm/src/lib/DebugInfo/Symbolize/Symbolize.cpp rename to interpreter/llvm-project/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp diff --git a/interpreter/llvm/src/lib/Demangle/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Demangle/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Demangle/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Demangle/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Demangle/Demangle.cpp b/interpreter/llvm-project/llvm/lib/Demangle/Demangle.cpp similarity index 100% rename from interpreter/llvm/src/lib/Demangle/Demangle.cpp rename to interpreter/llvm-project/llvm/lib/Demangle/Demangle.cpp diff --git a/interpreter/llvm/src/lib/Demangle/ItaniumDemangle.cpp b/interpreter/llvm-project/llvm/lib/Demangle/ItaniumDemangle.cpp similarity index 100% rename from interpreter/llvm/src/lib/Demangle/ItaniumDemangle.cpp rename to interpreter/llvm-project/llvm/lib/Demangle/ItaniumDemangle.cpp diff --git a/interpreter/llvm/src/lib/Demangle/MicrosoftDemangle.cpp b/interpreter/llvm-project/llvm/lib/Demangle/MicrosoftDemangle.cpp similarity index 100% rename from interpreter/llvm/src/lib/Demangle/MicrosoftDemangle.cpp rename to interpreter/llvm-project/llvm/lib/Demangle/MicrosoftDemangle.cpp diff --git a/interpreter/llvm/src/lib/Demangle/MicrosoftDemangleNodes.cpp b/interpreter/llvm-project/llvm/lib/Demangle/MicrosoftDemangleNodes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Demangle/MicrosoftDemangleNodes.cpp rename to interpreter/llvm-project/llvm/lib/Demangle/MicrosoftDemangleNodes.cpp diff --git a/interpreter/llvm/src/lib/Demangle/RustDemangle.cpp b/interpreter/llvm-project/llvm/lib/Demangle/RustDemangle.cpp similarity index 100% rename from interpreter/llvm/src/lib/Demangle/RustDemangle.cpp rename to interpreter/llvm-project/llvm/lib/Demangle/RustDemangle.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/ExecutionEngine.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/ExecutionEngine.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/ExecutionEngineBindings.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/ExecutionEngineBindings.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/GDBRegistrationListener.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/GDBRegistrationListener.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/GDBRegistrationListener.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/GDBRegistrationListener.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/IntelJITEventListener.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/IntelJITEventListener.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/IntelJITEventListener.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/IntelJITEventListener.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/IntelJITEventsWrapper.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/IntelJITEventsWrapper.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/IntelJITEventsWrapper.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/IntelJITEventsWrapper.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/ittnotify_config.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/ittnotify_config.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/ittnotify_config.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/ittnotify_config.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/ittnotify_types.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/ittnotify_types.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/ittnotify_types.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/ittnotify_types.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/jitprofiling.c b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/jitprofiling.c similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/jitprofiling.c rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/jitprofiling.c diff --git a/interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/jitprofiling.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/jitprofiling.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/IntelJITEvents/jitprofiling.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/IntelJITEvents/jitprofiling.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Interpreter/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Interpreter/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Execution.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Execution.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Execution.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Execution.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Interpreter.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Interpreter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Interpreter.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Interpreter.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Interpreter.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Interpreter.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Interpreter/Interpreter.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Interpreter/Interpreter.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/DefineExternalSectionStartAndEndSymbols.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/DefineExternalSectionStartAndEndSymbols.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/DefineExternalSectionStartAndEndSymbols.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/DefineExternalSectionStartAndEndSymbols.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupportImpl.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/EHFrameSupportImpl.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupportImpl.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/EHFrameSupportImpl.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELFLinkGraphBuilder.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF_riscv.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF_riscv.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF_x86_64.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_x86_64.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/ELF_x86_64.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_x86_64.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLink.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLink.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLink.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLink.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkGeneric.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkGeneric.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkGeneric.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkGeneric.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkGeneric.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkGeneric.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkGeneric.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkGeneric.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkMemoryManager.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkMemoryManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/JITLinkMemoryManager.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkMemoryManager.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO_arm64.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO_arm64.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO_arm64.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO_arm64.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO_x86_64.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO_x86_64.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/MachO_x86_64.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO_x86_64.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/PerGraphGOTAndPLTStubsBuilder.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/PerGraphGOTAndPLTStubsBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/PerGraphGOTAndPLTStubsBuilder.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/PerGraphGOTAndPLTStubsBuilder.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/riscv.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/riscv.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/riscv.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/riscv.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/x86_64.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/x86_64.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/JITLink/x86_64.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/JITLink/x86_64.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/MCJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/MCJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/MCJIT/MCJIT.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/MCJIT/MCJIT.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/MCJIT/MCJIT.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/MCJIT/MCJIT.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/OProfileJITEventListener.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/OProfileJITEventListener.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/OProfileJITEventListener.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/OProfileJITEventListener.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/OProfileWrapper.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/OProfileWrapper.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/OProfileJIT/OProfileWrapper.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/OProfileJIT/OProfileWrapper.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/CompileUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/CompileUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Core.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Core.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Core.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Core.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/DebugObjectManagerPlugin.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/DebugObjectManagerPlugin.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/DebugObjectManagerPlugin.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/DebugObjectManagerPlugin.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/DebugUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/DebugUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/DebugUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/DebugUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCDebugObjectRegistrar.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCDebugObjectRegistrar.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCDebugObjectRegistrar.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCDebugObjectRegistrar.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCEHFrameRegistrar.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCEHFrameRegistrar.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCEHFrameRegistrar.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCEHFrameRegistrar.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCIndirectionUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCIndirectionUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/EPCIndirectionUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/EPCIndirectionUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/ExecutionUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/ExecutionUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/IRCompileLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IRCompileLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/IRCompileLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IRCompileLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/IRTransformLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IRTransformLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/IRTransformLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IRTransformLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/IndirectionUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IndirectionUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/IndirectionUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/IndirectionUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/LLJIT.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/LLJIT.cpp similarity index 99% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/LLJIT.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/LLJIT.cpp index 6c52998dc633b..4d304f7bca7b8 100644 --- a/interpreter/llvm/src/lib/ExecutionEngine/Orc/LLJIT.cpp +++ b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/LLJIT.cpp @@ -483,7 +483,7 @@ GlobalCtorDtorScraper::operator()(ThreadSafeModule TSM, Inits.push_back(std::make_pair(E.Func, E.Priority)); llvm::sort(Inits, [](const std::pair &LHS, const std::pair &RHS) { - return LHS.first < RHS.first; + return LHS.second < RHS.second; }); auto *EntryBlock = BasicBlock::Create(Ctx, "entry", InitFunc); IRBuilder<> IB(EntryBlock); diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Layer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Layer.cpp similarity index 97% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Layer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Layer.cpp index a8973f5ed9dfa..55ab29504df99 100644 --- a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Layer.cpp +++ b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Layer.cpp @@ -126,6 +126,10 @@ void IRMaterializationUnit::discard(const JITDylib &JD, assert(!I->second->isDeclaration() && "Discard should only apply to definitions"); I->second->setLinkage(GlobalValue::AvailableExternallyLinkage); + // According to the IR verifier, "Declaration[s] may not be in a Comdat!" + // Remove it, if this is a GlobalObject. + if (auto *GO = dyn_cast(I->second)) + GO->setComdat(nullptr); SymbolToDefinition.erase(I); } diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/LazyReexports.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/LazyReexports.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/LazyReexports.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/LazyReexports.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/MachOPlatform.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/MachOPlatform.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/MachOPlatform.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/MachOPlatform.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Mangling.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Mangling.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Mangling.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Mangling.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/ObjectTransformLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectTransformLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/ObjectTransformLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectTransformLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/OrcABISupport.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/OrcABISupport.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/OrcABISupport.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/OrcABISupport.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/OrcV2CBindings.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/OrcV2CBindings.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/OrcV2CBindings.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/OrcV2CBindings.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/OrcError.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/OrcError.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/OrcError.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/OrcError.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/RPCError.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/RPCError.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Shared/RPCError.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Shared/RPCError.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/SpeculateAnalyses.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/SpeculateAnalyses.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/SpeculateAnalyses.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/SpeculateAnalyses.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/Speculation.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Speculation.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/Speculation.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/Speculation.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/Orc/ThreadSafeModule.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ThreadSafeModule.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/Orc/ThreadSafeModule.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/Orc/ThreadSafeModule.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/PerfJITEvents/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/PerfJITEvents/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/PerfJITEvents/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/PerfJITEvents/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/PerfJITEvents/PerfJITEventListener.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/PerfJITEvents/PerfJITEventListener.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/PerfJITEvents/PerfJITEventListener.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/PerfJITEvents/PerfJITEventListener.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/JITSymbol.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/JITSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/JITSymbol.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/JITSymbol.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCheckerImpl.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCheckerImpl.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCheckerImpl.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCheckerImpl.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldELFMips.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h b/interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h diff --git a/interpreter/llvm/src/lib/ExecutionEngine/SectionMemoryManager.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/SectionMemoryManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/SectionMemoryManager.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/SectionMemoryManager.cpp diff --git a/interpreter/llvm/src/lib/ExecutionEngine/TargetSelect.cpp b/interpreter/llvm-project/llvm/lib/ExecutionEngine/TargetSelect.cpp similarity index 100% rename from interpreter/llvm/src/lib/ExecutionEngine/TargetSelect.cpp rename to interpreter/llvm-project/llvm/lib/ExecutionEngine/TargetSelect.cpp diff --git a/interpreter/llvm/src/lib/Extensions/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Extensions/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Extensions/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Extensions/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Extensions/Extensions.cpp b/interpreter/llvm-project/llvm/lib/Extensions/Extensions.cpp similarity index 100% rename from interpreter/llvm/src/lib/Extensions/Extensions.cpp rename to interpreter/llvm-project/llvm/lib/Extensions/Extensions.cpp diff --git a/interpreter/llvm/src/lib/FileCheck/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/FileCheck/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/FileCheck/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/FileCheck/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/FileCheck/FileCheck.cpp b/interpreter/llvm-project/llvm/lib/FileCheck/FileCheck.cpp similarity index 100% rename from interpreter/llvm/src/lib/FileCheck/FileCheck.cpp rename to interpreter/llvm-project/llvm/lib/FileCheck/FileCheck.cpp diff --git a/interpreter/llvm/src/lib/FileCheck/FileCheckImpl.h b/interpreter/llvm-project/llvm/lib/FileCheck/FileCheckImpl.h similarity index 100% rename from interpreter/llvm/src/lib/FileCheck/FileCheckImpl.h rename to interpreter/llvm-project/llvm/lib/FileCheck/FileCheckImpl.h diff --git a/interpreter/llvm/src/lib/Frontend/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Frontend/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Frontend/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Frontend/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Frontend/OpenACC/ACC.cpp b/interpreter/llvm-project/llvm/lib/Frontend/OpenACC/ACC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenACC/ACC.cpp rename to interpreter/llvm-project/llvm/lib/Frontend/OpenACC/ACC.cpp diff --git a/interpreter/llvm/src/lib/Frontend/OpenACC/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Frontend/OpenACC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenACC/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Frontend/OpenACC/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Frontend/OpenMP/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Frontend/OpenMP/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenMP/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Frontend/OpenMP/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Frontend/OpenMP/OMP.cpp b/interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenMP/OMP.cpp rename to interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMP.cpp diff --git a/interpreter/llvm/src/lib/Frontend/OpenMP/OMPContext.cpp b/interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMPContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenMP/OMPContext.cpp rename to interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMPContext.cpp diff --git a/interpreter/llvm/src/lib/Frontend/OpenMP/OMPIRBuilder.cpp b/interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Frontend/OpenMP/OMPIRBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp diff --git a/interpreter/llvm/src/lib/FuzzMutate/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/FuzzMutate/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/FuzzMutate/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/FuzzMutate/FuzzerCLI.cpp b/interpreter/llvm-project/llvm/lib/FuzzMutate/FuzzerCLI.cpp similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/FuzzerCLI.cpp rename to interpreter/llvm-project/llvm/lib/FuzzMutate/FuzzerCLI.cpp diff --git a/interpreter/llvm/src/lib/FuzzMutate/IRMutator.cpp b/interpreter/llvm-project/llvm/lib/FuzzMutate/IRMutator.cpp similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/IRMutator.cpp rename to interpreter/llvm-project/llvm/lib/FuzzMutate/IRMutator.cpp diff --git a/interpreter/llvm/src/lib/FuzzMutate/OpDescriptor.cpp b/interpreter/llvm-project/llvm/lib/FuzzMutate/OpDescriptor.cpp similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/OpDescriptor.cpp rename to interpreter/llvm-project/llvm/lib/FuzzMutate/OpDescriptor.cpp diff --git a/interpreter/llvm/src/lib/FuzzMutate/Operations.cpp b/interpreter/llvm-project/llvm/lib/FuzzMutate/Operations.cpp similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/Operations.cpp rename to interpreter/llvm-project/llvm/lib/FuzzMutate/Operations.cpp diff --git a/interpreter/llvm/src/lib/FuzzMutate/RandomIRBuilder.cpp b/interpreter/llvm-project/llvm/lib/FuzzMutate/RandomIRBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/FuzzMutate/RandomIRBuilder.cpp rename to interpreter/llvm-project/llvm/lib/FuzzMutate/RandomIRBuilder.cpp diff --git a/interpreter/llvm/src/lib/Fuzzer/README.txt b/interpreter/llvm-project/llvm/lib/Fuzzer/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Fuzzer/README.txt rename to interpreter/llvm-project/llvm/lib/Fuzzer/README.txt diff --git a/interpreter/llvm/src/lib/IR/AbstractCallSite.cpp b/interpreter/llvm-project/llvm/lib/IR/AbstractCallSite.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/AbstractCallSite.cpp rename to interpreter/llvm-project/llvm/lib/IR/AbstractCallSite.cpp diff --git a/interpreter/llvm/src/lib/IR/AsmWriter.cpp b/interpreter/llvm-project/llvm/lib/IR/AsmWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/AsmWriter.cpp rename to interpreter/llvm-project/llvm/lib/IR/AsmWriter.cpp diff --git a/interpreter/llvm/src/lib/IR/Assumptions.cpp b/interpreter/llvm-project/llvm/lib/IR/Assumptions.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Assumptions.cpp rename to interpreter/llvm-project/llvm/lib/IR/Assumptions.cpp diff --git a/interpreter/llvm/src/lib/IR/AttributeImpl.h b/interpreter/llvm-project/llvm/lib/IR/AttributeImpl.h similarity index 100% rename from interpreter/llvm/src/lib/IR/AttributeImpl.h rename to interpreter/llvm-project/llvm/lib/IR/AttributeImpl.h diff --git a/interpreter/llvm/src/lib/IR/Attributes.cpp b/interpreter/llvm-project/llvm/lib/IR/Attributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Attributes.cpp rename to interpreter/llvm-project/llvm/lib/IR/Attributes.cpp diff --git a/interpreter/llvm/src/lib/IR/AutoUpgrade.cpp b/interpreter/llvm-project/llvm/lib/IR/AutoUpgrade.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/AutoUpgrade.cpp rename to interpreter/llvm-project/llvm/lib/IR/AutoUpgrade.cpp diff --git a/interpreter/llvm/src/lib/IR/BasicBlock.cpp b/interpreter/llvm-project/llvm/lib/IR/BasicBlock.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/BasicBlock.cpp rename to interpreter/llvm-project/llvm/lib/IR/BasicBlock.cpp diff --git a/interpreter/llvm/src/lib/IR/BuiltinGCs.cpp b/interpreter/llvm-project/llvm/lib/IR/BuiltinGCs.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/BuiltinGCs.cpp rename to interpreter/llvm-project/llvm/lib/IR/BuiltinGCs.cpp diff --git a/interpreter/llvm/src/lib/IR/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/IR/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/IR/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/IR/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/IR/Comdat.cpp b/interpreter/llvm-project/llvm/lib/IR/Comdat.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Comdat.cpp rename to interpreter/llvm-project/llvm/lib/IR/Comdat.cpp diff --git a/interpreter/llvm/src/lib/IR/ConstantFold.cpp b/interpreter/llvm-project/llvm/lib/IR/ConstantFold.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ConstantFold.cpp rename to interpreter/llvm-project/llvm/lib/IR/ConstantFold.cpp diff --git a/interpreter/llvm/src/lib/IR/ConstantFold.h b/interpreter/llvm-project/llvm/lib/IR/ConstantFold.h similarity index 100% rename from interpreter/llvm/src/lib/IR/ConstantFold.h rename to interpreter/llvm-project/llvm/lib/IR/ConstantFold.h diff --git a/interpreter/llvm/src/lib/IR/ConstantRange.cpp b/interpreter/llvm-project/llvm/lib/IR/ConstantRange.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ConstantRange.cpp rename to interpreter/llvm-project/llvm/lib/IR/ConstantRange.cpp diff --git a/interpreter/llvm/src/lib/IR/Constants.cpp b/interpreter/llvm-project/llvm/lib/IR/Constants.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Constants.cpp rename to interpreter/llvm-project/llvm/lib/IR/Constants.cpp diff --git a/interpreter/llvm/src/lib/IR/ConstantsContext.h b/interpreter/llvm-project/llvm/lib/IR/ConstantsContext.h similarity index 100% rename from interpreter/llvm/src/lib/IR/ConstantsContext.h rename to interpreter/llvm-project/llvm/lib/IR/ConstantsContext.h diff --git a/interpreter/llvm/src/lib/IR/Core.cpp b/interpreter/llvm-project/llvm/lib/IR/Core.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Core.cpp rename to interpreter/llvm-project/llvm/lib/IR/Core.cpp diff --git a/interpreter/llvm/src/lib/IR/DIBuilder.cpp b/interpreter/llvm-project/llvm/lib/IR/DIBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DIBuilder.cpp rename to interpreter/llvm-project/llvm/lib/IR/DIBuilder.cpp diff --git a/interpreter/llvm/src/lib/IR/DataLayout.cpp b/interpreter/llvm-project/llvm/lib/IR/DataLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DataLayout.cpp rename to interpreter/llvm-project/llvm/lib/IR/DataLayout.cpp diff --git a/interpreter/llvm/src/lib/IR/DebugInfo.cpp b/interpreter/llvm-project/llvm/lib/IR/DebugInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DebugInfo.cpp rename to interpreter/llvm-project/llvm/lib/IR/DebugInfo.cpp diff --git a/interpreter/llvm/src/lib/IR/DebugInfoMetadata.cpp b/interpreter/llvm-project/llvm/lib/IR/DebugInfoMetadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DebugInfoMetadata.cpp rename to interpreter/llvm-project/llvm/lib/IR/DebugInfoMetadata.cpp diff --git a/interpreter/llvm/src/lib/IR/DebugLoc.cpp b/interpreter/llvm-project/llvm/lib/IR/DebugLoc.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DebugLoc.cpp rename to interpreter/llvm-project/llvm/lib/IR/DebugLoc.cpp diff --git a/interpreter/llvm/src/lib/IR/DiagnosticHandler.cpp b/interpreter/llvm-project/llvm/lib/IR/DiagnosticHandler.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DiagnosticHandler.cpp rename to interpreter/llvm-project/llvm/lib/IR/DiagnosticHandler.cpp diff --git a/interpreter/llvm/src/lib/IR/DiagnosticInfo.cpp b/interpreter/llvm-project/llvm/lib/IR/DiagnosticInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DiagnosticInfo.cpp rename to interpreter/llvm-project/llvm/lib/IR/DiagnosticInfo.cpp diff --git a/interpreter/llvm/src/lib/IR/DiagnosticPrinter.cpp b/interpreter/llvm-project/llvm/lib/IR/DiagnosticPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/DiagnosticPrinter.cpp rename to interpreter/llvm-project/llvm/lib/IR/DiagnosticPrinter.cpp diff --git a/interpreter/llvm/src/lib/IR/Dominators.cpp b/interpreter/llvm-project/llvm/lib/IR/Dominators.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Dominators.cpp rename to interpreter/llvm-project/llvm/lib/IR/Dominators.cpp diff --git a/interpreter/llvm/src/lib/IR/FPEnv.cpp b/interpreter/llvm-project/llvm/lib/IR/FPEnv.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/FPEnv.cpp rename to interpreter/llvm-project/llvm/lib/IR/FPEnv.cpp diff --git a/interpreter/llvm/src/lib/IR/Function.cpp b/interpreter/llvm-project/llvm/lib/IR/Function.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Function.cpp rename to interpreter/llvm-project/llvm/lib/IR/Function.cpp diff --git a/interpreter/llvm/src/lib/IR/GCStrategy.cpp b/interpreter/llvm-project/llvm/lib/IR/GCStrategy.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/GCStrategy.cpp rename to interpreter/llvm-project/llvm/lib/IR/GCStrategy.cpp diff --git a/interpreter/llvm/src/lib/IR/GVMaterializer.cpp b/interpreter/llvm-project/llvm/lib/IR/GVMaterializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/GVMaterializer.cpp rename to interpreter/llvm-project/llvm/lib/IR/GVMaterializer.cpp diff --git a/interpreter/llvm/src/lib/IR/Globals.cpp b/interpreter/llvm-project/llvm/lib/IR/Globals.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Globals.cpp rename to interpreter/llvm-project/llvm/lib/IR/Globals.cpp diff --git a/interpreter/llvm/src/lib/IR/IRBuilder.cpp b/interpreter/llvm-project/llvm/lib/IR/IRBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/IRBuilder.cpp rename to interpreter/llvm-project/llvm/lib/IR/IRBuilder.cpp diff --git a/interpreter/llvm/src/lib/IR/IRPrintingPasses.cpp b/interpreter/llvm-project/llvm/lib/IR/IRPrintingPasses.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/IRPrintingPasses.cpp rename to interpreter/llvm-project/llvm/lib/IR/IRPrintingPasses.cpp diff --git a/interpreter/llvm/src/lib/IR/InlineAsm.cpp b/interpreter/llvm-project/llvm/lib/IR/InlineAsm.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/InlineAsm.cpp rename to interpreter/llvm-project/llvm/lib/IR/InlineAsm.cpp diff --git a/interpreter/llvm/src/lib/IR/Instruction.cpp b/interpreter/llvm-project/llvm/lib/IR/Instruction.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Instruction.cpp rename to interpreter/llvm-project/llvm/lib/IR/Instruction.cpp diff --git a/interpreter/llvm/src/lib/IR/Instructions.cpp b/interpreter/llvm-project/llvm/lib/IR/Instructions.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Instructions.cpp rename to interpreter/llvm-project/llvm/lib/IR/Instructions.cpp diff --git a/interpreter/llvm/src/lib/IR/IntrinsicInst.cpp b/interpreter/llvm-project/llvm/lib/IR/IntrinsicInst.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/IntrinsicInst.cpp rename to interpreter/llvm-project/llvm/lib/IR/IntrinsicInst.cpp diff --git a/interpreter/llvm/src/lib/IR/LLVMContext.cpp b/interpreter/llvm-project/llvm/lib/IR/LLVMContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/LLVMContext.cpp rename to interpreter/llvm-project/llvm/lib/IR/LLVMContext.cpp diff --git a/interpreter/llvm/src/lib/IR/LLVMContextImpl.cpp b/interpreter/llvm-project/llvm/lib/IR/LLVMContextImpl.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/LLVMContextImpl.cpp rename to interpreter/llvm-project/llvm/lib/IR/LLVMContextImpl.cpp diff --git a/interpreter/llvm/src/lib/IR/LLVMContextImpl.h b/interpreter/llvm-project/llvm/lib/IR/LLVMContextImpl.h similarity index 100% rename from interpreter/llvm/src/lib/IR/LLVMContextImpl.h rename to interpreter/llvm-project/llvm/lib/IR/LLVMContextImpl.h diff --git a/interpreter/llvm/src/lib/IR/LLVMRemarkStreamer.cpp b/interpreter/llvm-project/llvm/lib/IR/LLVMRemarkStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/LLVMRemarkStreamer.cpp rename to interpreter/llvm-project/llvm/lib/IR/LLVMRemarkStreamer.cpp diff --git a/interpreter/llvm/src/lib/IR/LegacyPassManager.cpp b/interpreter/llvm-project/llvm/lib/IR/LegacyPassManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/LegacyPassManager.cpp rename to interpreter/llvm-project/llvm/lib/IR/LegacyPassManager.cpp diff --git a/interpreter/llvm/src/lib/IR/MDBuilder.cpp b/interpreter/llvm-project/llvm/lib/IR/MDBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/MDBuilder.cpp rename to interpreter/llvm-project/llvm/lib/IR/MDBuilder.cpp diff --git a/interpreter/llvm/src/lib/IR/Mangler.cpp b/interpreter/llvm-project/llvm/lib/IR/Mangler.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Mangler.cpp rename to interpreter/llvm-project/llvm/lib/IR/Mangler.cpp diff --git a/interpreter/llvm/src/lib/IR/Metadata.cpp b/interpreter/llvm-project/llvm/lib/IR/Metadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Metadata.cpp rename to interpreter/llvm-project/llvm/lib/IR/Metadata.cpp diff --git a/interpreter/llvm/src/lib/IR/MetadataImpl.h b/interpreter/llvm-project/llvm/lib/IR/MetadataImpl.h similarity index 100% rename from interpreter/llvm/src/lib/IR/MetadataImpl.h rename to interpreter/llvm-project/llvm/lib/IR/MetadataImpl.h diff --git a/interpreter/llvm/src/lib/IR/Module.cpp b/interpreter/llvm-project/llvm/lib/IR/Module.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Module.cpp rename to interpreter/llvm-project/llvm/lib/IR/Module.cpp diff --git a/interpreter/llvm/src/lib/IR/ModuleSummaryIndex.cpp b/interpreter/llvm-project/llvm/lib/IR/ModuleSummaryIndex.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ModuleSummaryIndex.cpp rename to interpreter/llvm-project/llvm/lib/IR/ModuleSummaryIndex.cpp diff --git a/interpreter/llvm/src/lib/IR/Operator.cpp b/interpreter/llvm-project/llvm/lib/IR/Operator.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Operator.cpp rename to interpreter/llvm-project/llvm/lib/IR/Operator.cpp diff --git a/interpreter/llvm/src/lib/IR/OptBisect.cpp b/interpreter/llvm-project/llvm/lib/IR/OptBisect.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/OptBisect.cpp rename to interpreter/llvm-project/llvm/lib/IR/OptBisect.cpp diff --git a/interpreter/llvm/src/lib/IR/Pass.cpp b/interpreter/llvm-project/llvm/lib/IR/Pass.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Pass.cpp rename to interpreter/llvm-project/llvm/lib/IR/Pass.cpp diff --git a/interpreter/llvm/src/lib/IR/PassInstrumentation.cpp b/interpreter/llvm-project/llvm/lib/IR/PassInstrumentation.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PassInstrumentation.cpp rename to interpreter/llvm-project/llvm/lib/IR/PassInstrumentation.cpp diff --git a/interpreter/llvm/src/lib/IR/PassManager.cpp b/interpreter/llvm-project/llvm/lib/IR/PassManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PassManager.cpp rename to interpreter/llvm-project/llvm/lib/IR/PassManager.cpp diff --git a/interpreter/llvm/src/lib/IR/PassRegistry.cpp b/interpreter/llvm-project/llvm/lib/IR/PassRegistry.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PassRegistry.cpp rename to interpreter/llvm-project/llvm/lib/IR/PassRegistry.cpp diff --git a/interpreter/llvm/src/lib/IR/PassTimingInfo.cpp b/interpreter/llvm-project/llvm/lib/IR/PassTimingInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PassTimingInfo.cpp rename to interpreter/llvm-project/llvm/lib/IR/PassTimingInfo.cpp diff --git a/interpreter/llvm/src/lib/IR/PrintPasses.cpp b/interpreter/llvm-project/llvm/lib/IR/PrintPasses.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PrintPasses.cpp rename to interpreter/llvm-project/llvm/lib/IR/PrintPasses.cpp diff --git a/interpreter/llvm/src/lib/IR/ProfileSummary.cpp b/interpreter/llvm-project/llvm/lib/IR/ProfileSummary.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ProfileSummary.cpp rename to interpreter/llvm-project/llvm/lib/IR/ProfileSummary.cpp diff --git a/interpreter/llvm/src/lib/IR/PseudoProbe.cpp b/interpreter/llvm-project/llvm/lib/IR/PseudoProbe.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/PseudoProbe.cpp rename to interpreter/llvm-project/llvm/lib/IR/PseudoProbe.cpp diff --git a/interpreter/llvm/src/lib/IR/ReplaceConstant.cpp b/interpreter/llvm-project/llvm/lib/IR/ReplaceConstant.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ReplaceConstant.cpp rename to interpreter/llvm-project/llvm/lib/IR/ReplaceConstant.cpp diff --git a/interpreter/llvm/src/lib/IR/SafepointIRVerifier.cpp b/interpreter/llvm-project/llvm/lib/IR/SafepointIRVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/SafepointIRVerifier.cpp rename to interpreter/llvm-project/llvm/lib/IR/SafepointIRVerifier.cpp diff --git a/interpreter/llvm/src/lib/IR/Statepoint.cpp b/interpreter/llvm-project/llvm/lib/IR/Statepoint.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Statepoint.cpp rename to interpreter/llvm-project/llvm/lib/IR/Statepoint.cpp diff --git a/interpreter/llvm/src/lib/IR/StructuralHash.cpp b/interpreter/llvm-project/llvm/lib/IR/StructuralHash.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/StructuralHash.cpp rename to interpreter/llvm-project/llvm/lib/IR/StructuralHash.cpp diff --git a/interpreter/llvm/src/lib/IR/SymbolTableListTraitsImpl.h b/interpreter/llvm-project/llvm/lib/IR/SymbolTableListTraitsImpl.h similarity index 100% rename from interpreter/llvm/src/lib/IR/SymbolTableListTraitsImpl.h rename to interpreter/llvm-project/llvm/lib/IR/SymbolTableListTraitsImpl.h diff --git a/interpreter/llvm/src/lib/IR/Type.cpp b/interpreter/llvm-project/llvm/lib/IR/Type.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Type.cpp rename to interpreter/llvm-project/llvm/lib/IR/Type.cpp diff --git a/interpreter/llvm/src/lib/IR/TypeFinder.cpp b/interpreter/llvm-project/llvm/lib/IR/TypeFinder.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/TypeFinder.cpp rename to interpreter/llvm-project/llvm/lib/IR/TypeFinder.cpp diff --git a/interpreter/llvm/src/lib/IR/Use.cpp b/interpreter/llvm-project/llvm/lib/IR/Use.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Use.cpp rename to interpreter/llvm-project/llvm/lib/IR/Use.cpp diff --git a/interpreter/llvm/src/lib/IR/User.cpp b/interpreter/llvm-project/llvm/lib/IR/User.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/User.cpp rename to interpreter/llvm-project/llvm/lib/IR/User.cpp diff --git a/interpreter/llvm/src/lib/IR/Value.cpp b/interpreter/llvm-project/llvm/lib/IR/Value.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Value.cpp rename to interpreter/llvm-project/llvm/lib/IR/Value.cpp diff --git a/interpreter/llvm/src/lib/IR/ValueSymbolTable.cpp b/interpreter/llvm-project/llvm/lib/IR/ValueSymbolTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/ValueSymbolTable.cpp rename to interpreter/llvm-project/llvm/lib/IR/ValueSymbolTable.cpp diff --git a/interpreter/llvm/src/lib/IR/Verifier.cpp b/interpreter/llvm-project/llvm/lib/IR/Verifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/IR/Verifier.cpp rename to interpreter/llvm-project/llvm/lib/IR/Verifier.cpp diff --git a/interpreter/llvm/src/lib/IRReader/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/IRReader/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/IRReader/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/IRReader/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/IRReader/IRReader.cpp b/interpreter/llvm-project/llvm/lib/IRReader/IRReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/IRReader/IRReader.cpp rename to interpreter/llvm-project/llvm/lib/IRReader/IRReader.cpp diff --git a/interpreter/llvm/src/lib/InterfaceStub/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/InterfaceStub/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/InterfaceStub/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/InterfaceStub/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/InterfaceStub/ELFObjHandler.cpp b/interpreter/llvm-project/llvm/lib/InterfaceStub/ELFObjHandler.cpp similarity index 100% rename from interpreter/llvm/src/lib/InterfaceStub/ELFObjHandler.cpp rename to interpreter/llvm-project/llvm/lib/InterfaceStub/ELFObjHandler.cpp diff --git a/interpreter/llvm/src/lib/InterfaceStub/IFSHandler.cpp b/interpreter/llvm-project/llvm/lib/InterfaceStub/IFSHandler.cpp similarity index 100% rename from interpreter/llvm/src/lib/InterfaceStub/IFSHandler.cpp rename to interpreter/llvm-project/llvm/lib/InterfaceStub/IFSHandler.cpp diff --git a/interpreter/llvm/src/lib/InterfaceStub/IFSStub.cpp b/interpreter/llvm-project/llvm/lib/InterfaceStub/IFSStub.cpp similarity index 100% rename from interpreter/llvm/src/lib/InterfaceStub/IFSStub.cpp rename to interpreter/llvm-project/llvm/lib/InterfaceStub/IFSStub.cpp diff --git a/interpreter/llvm/src/lib/LTO/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/LTO/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/LTO/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/LTO/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/LTO/Caching.cpp b/interpreter/llvm-project/llvm/lib/LTO/Caching.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/Caching.cpp rename to interpreter/llvm-project/llvm/lib/LTO/Caching.cpp diff --git a/interpreter/llvm/src/lib/LTO/LTO.cpp b/interpreter/llvm-project/llvm/lib/LTO/LTO.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/LTO.cpp rename to interpreter/llvm-project/llvm/lib/LTO/LTO.cpp diff --git a/interpreter/llvm/src/lib/LTO/LTOBackend.cpp b/interpreter/llvm-project/llvm/lib/LTO/LTOBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/LTOBackend.cpp rename to interpreter/llvm-project/llvm/lib/LTO/LTOBackend.cpp diff --git a/interpreter/llvm/src/lib/LTO/LTOCodeGenerator.cpp b/interpreter/llvm-project/llvm/lib/LTO/LTOCodeGenerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/LTOCodeGenerator.cpp rename to interpreter/llvm-project/llvm/lib/LTO/LTOCodeGenerator.cpp diff --git a/interpreter/llvm/src/lib/LTO/LTOModule.cpp b/interpreter/llvm-project/llvm/lib/LTO/LTOModule.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/LTOModule.cpp rename to interpreter/llvm-project/llvm/lib/LTO/LTOModule.cpp diff --git a/interpreter/llvm/src/lib/LTO/SummaryBasedOptimizations.cpp b/interpreter/llvm-project/llvm/lib/LTO/SummaryBasedOptimizations.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/SummaryBasedOptimizations.cpp rename to interpreter/llvm-project/llvm/lib/LTO/SummaryBasedOptimizations.cpp diff --git a/interpreter/llvm/src/lib/LTO/ThinLTOCodeGenerator.cpp b/interpreter/llvm-project/llvm/lib/LTO/ThinLTOCodeGenerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/ThinLTOCodeGenerator.cpp rename to interpreter/llvm-project/llvm/lib/LTO/ThinLTOCodeGenerator.cpp diff --git a/interpreter/llvm/src/lib/LTO/UpdateCompilerUsed.cpp b/interpreter/llvm-project/llvm/lib/LTO/UpdateCompilerUsed.cpp similarity index 100% rename from interpreter/llvm/src/lib/LTO/UpdateCompilerUsed.cpp rename to interpreter/llvm-project/llvm/lib/LTO/UpdateCompilerUsed.cpp diff --git a/interpreter/llvm/src/lib/LineEditor/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/LineEditor/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/LineEditor/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/LineEditor/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/LineEditor/LineEditor.cpp b/interpreter/llvm-project/llvm/lib/LineEditor/LineEditor.cpp similarity index 100% rename from interpreter/llvm/src/lib/LineEditor/LineEditor.cpp rename to interpreter/llvm-project/llvm/lib/LineEditor/LineEditor.cpp diff --git a/interpreter/llvm/src/lib/Linker/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Linker/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Linker/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Linker/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Linker/IRMover.cpp b/interpreter/llvm-project/llvm/lib/Linker/IRMover.cpp similarity index 100% rename from interpreter/llvm/src/lib/Linker/IRMover.cpp rename to interpreter/llvm-project/llvm/lib/Linker/IRMover.cpp diff --git a/interpreter/llvm/src/lib/Linker/LinkDiagnosticInfo.h b/interpreter/llvm-project/llvm/lib/Linker/LinkDiagnosticInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Linker/LinkDiagnosticInfo.h rename to interpreter/llvm-project/llvm/lib/Linker/LinkDiagnosticInfo.h diff --git a/interpreter/llvm/src/lib/Linker/LinkModules.cpp b/interpreter/llvm-project/llvm/lib/Linker/LinkModules.cpp similarity index 100% rename from interpreter/llvm/src/lib/Linker/LinkModules.cpp rename to interpreter/llvm-project/llvm/lib/Linker/LinkModules.cpp diff --git a/interpreter/llvm/src/lib/MC/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/MC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/MC/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/MC/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/MC/ConstantPools.cpp b/interpreter/llvm-project/llvm/lib/MC/ConstantPools.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/ConstantPools.cpp rename to interpreter/llvm-project/llvm/lib/MC/ConstantPools.cpp diff --git a/interpreter/llvm/src/lib/MC/ELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/ELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/ELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/ELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfoCOFF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfoCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfoCOFF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfoCOFF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfoDarwin.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfoDarwin.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfoDarwin.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfoDarwin.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfoELF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfoELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfoELF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfoELF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfoWasm.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfoWasm.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfoWasm.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfoWasm.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmInfoXCOFF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmInfoXCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmInfoXCOFF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmInfoXCOFF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmMacro.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmMacro.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmMacro.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmMacro.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAsmStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAsmStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAsmStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAsmStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCAssembler.cpp b/interpreter/llvm-project/llvm/lib/MC/MCAssembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCAssembler.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCAssembler.cpp diff --git a/interpreter/llvm/src/lib/MC/MCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCCodeView.cpp b/interpreter/llvm-project/llvm/lib/MC/MCCodeView.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCCodeView.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCCodeView.cpp diff --git a/interpreter/llvm/src/lib/MC/MCContext.cpp b/interpreter/llvm-project/llvm/lib/MC/MCContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCContext.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCContext.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/Disassembler.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/Disassembler.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/Disassembler.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/Disassembler.h b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/Disassembler.h similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/Disassembler.h rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/Disassembler.h diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/MCDisassembler.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/MCDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/MCRelocationInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCRelocationInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/MCRelocationInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCRelocationInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDisassembler/MCSymbolizer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCSymbolizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDisassembler/MCSymbolizer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDisassembler/MCSymbolizer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCDwarf.cpp b/interpreter/llvm-project/llvm/lib/MC/MCDwarf.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCDwarf.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCDwarf.cpp diff --git a/interpreter/llvm/src/lib/MC/MCELFObjectTargetWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCELFObjectTargetWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCELFObjectTargetWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCELFObjectTargetWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCExpr.cpp b/interpreter/llvm-project/llvm/lib/MC/MCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCExpr.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCExpr.cpp diff --git a/interpreter/llvm/src/lib/MC/MCFragment.cpp b/interpreter/llvm-project/llvm/lib/MC/MCFragment.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCFragment.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCFragment.cpp diff --git a/interpreter/llvm/src/lib/MC/MCInst.cpp b/interpreter/llvm-project/llvm/lib/MC/MCInst.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCInst.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCInst.cpp diff --git a/interpreter/llvm/src/lib/MC/MCInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCInstrAnalysis.cpp b/interpreter/llvm-project/llvm/lib/MC/MCInstrAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCInstrAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCInstrAnalysis.cpp diff --git a/interpreter/llvm/src/lib/MC/MCInstrDesc.cpp b/interpreter/llvm-project/llvm/lib/MC/MCInstrDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCInstrDesc.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCInstrDesc.cpp diff --git a/interpreter/llvm/src/lib/MC/MCInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCLabel.cpp b/interpreter/llvm-project/llvm/lib/MC/MCLabel.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCLabel.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCLabel.cpp diff --git a/interpreter/llvm/src/lib/MC/MCLinkerOptimizationHint.cpp b/interpreter/llvm-project/llvm/lib/MC/MCLinkerOptimizationHint.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCLinkerOptimizationHint.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCLinkerOptimizationHint.cpp diff --git a/interpreter/llvm/src/lib/MC/MCMachOStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCMachOStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCMachOStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCMachOStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCMachObjectTargetWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCMachObjectTargetWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCMachObjectTargetWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCMachObjectTargetWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCNullStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCNullStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCNullStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCNullStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCObjectFileInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCObjectFileInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCObjectFileInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCObjectFileInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCObjectStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCObjectStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCObjectStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCObjectStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/AsmLexer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/AsmLexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/AsmLexer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/AsmLexer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/AsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/AsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/AsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/AsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/MC/MCParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/MC/MCParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/MC/MCParser/COFFAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/COFFAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/COFFAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/COFFAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/COFFMasmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/COFFMasmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/COFFMasmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/COFFMasmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/DarwinAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/DarwinAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/DarwinAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/DarwinAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/ELFAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/ELFAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/ELFAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/ELFAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/MCAsmLexer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmLexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/MCAsmLexer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmLexer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/MCAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/MCAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/MCAsmParserExtension.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmParserExtension.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/MCAsmParserExtension.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/MCAsmParserExtension.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/MCTargetAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/MCTargetAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/MCTargetAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/MCTargetAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/MasmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/MasmParser.cpp similarity index 98% rename from interpreter/llvm/src/lib/MC/MCParser/MasmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/MasmParser.cpp index 7b4d6e529cc2c..4f83b592b0598 100644 --- a/interpreter/llvm/src/lib/MC/MCParser/MasmParser.cpp +++ b/interpreter/llvm-project/llvm/lib/MC/MCParser/MasmParser.cpp @@ -143,9 +143,7 @@ struct StructInfo { unsigned FieldAlignmentSize); StructInfo() = default; - - StructInfo(StringRef StructName, bool Union, unsigned AlignmentValue) - : Name(StructName), IsUnion(Union), Alignment(AlignmentValue) {} + StructInfo(StringRef StructName, bool Union, unsigned AlignmentValue); }; // FIXME: This should probably use a class hierarchy, raw pointers between the @@ -173,14 +171,8 @@ struct StructFieldInfo { StructInfo Structure; StructFieldInfo() = default; - StructFieldInfo(const std::vector &V, StructInfo S) { - Initializers = V; - Structure = S; - } - StructFieldInfo(std::vector &&V, StructInfo S) { - Initializers = V; - Structure = S; - } + StructFieldInfo(const std::vector &V, StructInfo S); + StructFieldInfo(std::vector &&V, StructInfo S); }; class FieldInitializer { @@ -192,133 +184,19 @@ class FieldInitializer { StructFieldInfo StructInfo; }; - ~FieldInitializer() { - switch (FT) { - case FT_INTEGRAL: - IntInfo.~IntFieldInfo(); - break; - case FT_REAL: - RealInfo.~RealFieldInfo(); - break; - case FT_STRUCT: - StructInfo.~StructFieldInfo(); - break; - } - } - - FieldInitializer(FieldType FT) : FT(FT) { - switch (FT) { - case FT_INTEGRAL: - new (&IntInfo) IntFieldInfo(); - break; - case FT_REAL: - new (&RealInfo) RealFieldInfo(); - break; - case FT_STRUCT: - new (&StructInfo) StructFieldInfo(); - break; - } - } - - FieldInitializer(SmallVector &&Values) : FT(FT_INTEGRAL) { - new (&IntInfo) IntFieldInfo(Values); - } - - FieldInitializer(SmallVector &&AsIntValues) : FT(FT_REAL) { - new (&RealInfo) RealFieldInfo(AsIntValues); - } + ~FieldInitializer(); + FieldInitializer(FieldType FT); + FieldInitializer(SmallVector &&Values); + FieldInitializer(SmallVector &&AsIntValues); FieldInitializer(std::vector &&Initializers, - struct StructInfo Structure) - : FT(FT_STRUCT) { - new (&StructInfo) StructFieldInfo(Initializers, Structure); - } - - FieldInitializer(const FieldInitializer &Initializer) : FT(Initializer.FT) { - switch (FT) { - case FT_INTEGRAL: - new (&IntInfo) IntFieldInfo(Initializer.IntInfo); - break; - case FT_REAL: - new (&RealInfo) RealFieldInfo(Initializer.RealInfo); - break; - case FT_STRUCT: - new (&StructInfo) StructFieldInfo(Initializer.StructInfo); - break; - } - } - - FieldInitializer(FieldInitializer &&Initializer) : FT(Initializer.FT) { - switch (FT) { - case FT_INTEGRAL: - new (&IntInfo) IntFieldInfo(Initializer.IntInfo); - break; - case FT_REAL: - new (&RealInfo) RealFieldInfo(Initializer.RealInfo); - break; - case FT_STRUCT: - new (&StructInfo) StructFieldInfo(Initializer.StructInfo); - break; - } - } + struct StructInfo Structure); - FieldInitializer &operator=(const FieldInitializer &Initializer) { - if (FT != Initializer.FT) { - switch (FT) { - case FT_INTEGRAL: - IntInfo.~IntFieldInfo(); - break; - case FT_REAL: - RealInfo.~RealFieldInfo(); - break; - case FT_STRUCT: - StructInfo.~StructFieldInfo(); - break; - } - } - FT = Initializer.FT; - switch (FT) { - case FT_INTEGRAL: - IntInfo = Initializer.IntInfo; - break; - case FT_REAL: - RealInfo = Initializer.RealInfo; - break; - case FT_STRUCT: - StructInfo = Initializer.StructInfo; - break; - } - return *this; - } + FieldInitializer(const FieldInitializer &Initializer); + FieldInitializer(FieldInitializer &&Initializer); - FieldInitializer &operator=(FieldInitializer &&Initializer) { - if (FT != Initializer.FT) { - switch (FT) { - case FT_INTEGRAL: - IntInfo.~IntFieldInfo(); - break; - case FT_REAL: - RealInfo.~RealFieldInfo(); - break; - case FT_STRUCT: - StructInfo.~StructFieldInfo(); - break; - } - } - FT = Initializer.FT; - switch (FT) { - case FT_INTEGRAL: - IntInfo = Initializer.IntInfo; - break; - case FT_REAL: - RealInfo = Initializer.RealInfo; - break; - case FT_STRUCT: - StructInfo = Initializer.StructInfo; - break; - } - return *this; - } + FieldInitializer &operator=(const FieldInitializer &Initializer); + FieldInitializer &operator=(FieldInitializer &&Initializer); }; struct StructInitializer { @@ -343,6 +221,22 @@ struct FieldInfo { FieldInfo(FieldType FT) : Contents(FT) {} }; +StructFieldInfo::StructFieldInfo(const std::vector &V, + StructInfo S) { + Initializers = V; + Structure = S; +} + +StructFieldInfo::StructFieldInfo(std::vector &&V, + StructInfo S) { + Initializers = V; + Structure = S; +} + +StructInfo::StructInfo(StringRef StructName, bool Union, + unsigned AlignmentValue) + : Name(StructName), IsUnion(Union), Alignment(AlignmentValue) {} + FieldInfo &StructInfo::addField(StringRef FieldName, FieldType FT, unsigned FieldAlignmentSize) { if (!FieldName.empty()) @@ -358,6 +252,139 @@ FieldInfo &StructInfo::addField(StringRef FieldName, FieldType FT, return Field; } +FieldInitializer::~FieldInitializer() { + switch (FT) { + case FT_INTEGRAL: + IntInfo.~IntFieldInfo(); + break; + case FT_REAL: + RealInfo.~RealFieldInfo(); + break; + case FT_STRUCT: + StructInfo.~StructFieldInfo(); + break; + } +} + +FieldInitializer::FieldInitializer(FieldType FT) : FT(FT) { + switch (FT) { + case FT_INTEGRAL: + new (&IntInfo) IntFieldInfo(); + break; + case FT_REAL: + new (&RealInfo) RealFieldInfo(); + break; + case FT_STRUCT: + new (&StructInfo) StructFieldInfo(); + break; + } +} + +FieldInitializer::FieldInitializer(SmallVector &&Values) + : FT(FT_INTEGRAL) { + new (&IntInfo) IntFieldInfo(Values); +} + +FieldInitializer::FieldInitializer(SmallVector &&AsIntValues) + : FT(FT_REAL) { + new (&RealInfo) RealFieldInfo(AsIntValues); +} + +FieldInitializer::FieldInitializer( + std::vector &&Initializers, struct StructInfo Structure) + : FT(FT_STRUCT) { + new (&StructInfo) StructFieldInfo(Initializers, Structure); +} + +FieldInitializer::FieldInitializer(const FieldInitializer &Initializer) + : FT(Initializer.FT) { + switch (FT) { + case FT_INTEGRAL: + new (&IntInfo) IntFieldInfo(Initializer.IntInfo); + break; + case FT_REAL: + new (&RealInfo) RealFieldInfo(Initializer.RealInfo); + break; + case FT_STRUCT: + new (&StructInfo) StructFieldInfo(Initializer.StructInfo); + break; + } +} + +FieldInitializer::FieldInitializer(FieldInitializer &&Initializer) + : FT(Initializer.FT) { + switch (FT) { + case FT_INTEGRAL: + new (&IntInfo) IntFieldInfo(Initializer.IntInfo); + break; + case FT_REAL: + new (&RealInfo) RealFieldInfo(Initializer.RealInfo); + break; + case FT_STRUCT: + new (&StructInfo) StructFieldInfo(Initializer.StructInfo); + break; + } +} + +FieldInitializer & +FieldInitializer::operator=(const FieldInitializer &Initializer) { + if (FT != Initializer.FT) { + switch (FT) { + case FT_INTEGRAL: + IntInfo.~IntFieldInfo(); + break; + case FT_REAL: + RealInfo.~RealFieldInfo(); + break; + case FT_STRUCT: + StructInfo.~StructFieldInfo(); + break; + } + } + FT = Initializer.FT; + switch (FT) { + case FT_INTEGRAL: + IntInfo = Initializer.IntInfo; + break; + case FT_REAL: + RealInfo = Initializer.RealInfo; + break; + case FT_STRUCT: + StructInfo = Initializer.StructInfo; + break; + } + return *this; +} + +FieldInitializer &FieldInitializer::operator=(FieldInitializer &&Initializer) { + if (FT != Initializer.FT) { + switch (FT) { + case FT_INTEGRAL: + IntInfo.~IntFieldInfo(); + break; + case FT_REAL: + RealInfo.~RealFieldInfo(); + break; + case FT_STRUCT: + StructInfo.~StructFieldInfo(); + break; + } + } + FT = Initializer.FT; + switch (FT) { + case FT_INTEGRAL: + IntInfo = Initializer.IntInfo; + break; + case FT_REAL: + RealInfo = Initializer.RealInfo; + break; + case FT_STRUCT: + StructInfo = Initializer.StructInfo; + break; + } + return *this; +} + /// The concrete assembly parser instance. // Note that this is a full MCAsmParser, not an MCAsmParserExtension! // It's a peer of AsmParser, not of COFFAsmParser, WasmAsmParser, etc. diff --git a/interpreter/llvm/src/lib/MC/MCParser/WasmAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/WasmAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/WasmAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/WasmAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCParser/XCOFFAsmParser.cpp b/interpreter/llvm-project/llvm/lib/MC/MCParser/XCOFFAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCParser/XCOFFAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCParser/XCOFFAsmParser.cpp diff --git a/interpreter/llvm/src/lib/MC/MCPseudoProbe.cpp b/interpreter/llvm-project/llvm/lib/MC/MCPseudoProbe.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCPseudoProbe.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCPseudoProbe.cpp diff --git a/interpreter/llvm/src/lib/MC/MCRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSchedule.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSchedule.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSchedule.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSchedule.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSection.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSection.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSection.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSection.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSectionCOFF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSectionCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSectionCOFF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSectionCOFF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSectionELF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSectionELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSectionELF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSectionELF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSectionMachO.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSectionMachO.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSectionMachO.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSectionMachO.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSectionWasm.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSectionWasm.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSectionWasm.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSectionWasm.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSectionXCOFF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSectionXCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSectionXCOFF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSectionXCOFF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSubtargetInfo.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSubtargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSubtargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSubtargetInfo.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSymbol.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSymbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSymbol.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSymbol.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSymbolELF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSymbolELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSymbolELF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSymbolELF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCSymbolXCOFF.cpp b/interpreter/llvm-project/llvm/lib/MC/MCSymbolXCOFF.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCSymbolXCOFF.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCSymbolXCOFF.cpp diff --git a/interpreter/llvm/src/lib/MC/MCTargetOptions.cpp b/interpreter/llvm-project/llvm/lib/MC/MCTargetOptions.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCTargetOptions.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCTargetOptions.cpp diff --git a/interpreter/llvm/src/lib/MC/MCTargetOptionsCommandFlags.cpp b/interpreter/llvm-project/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCTargetOptionsCommandFlags.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp diff --git a/interpreter/llvm/src/lib/MC/MCValue.cpp b/interpreter/llvm-project/llvm/lib/MC/MCValue.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCValue.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCValue.cpp diff --git a/interpreter/llvm/src/lib/MC/MCWasmObjectTargetWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCWasmObjectTargetWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCWasmObjectTargetWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCWasmObjectTargetWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCWasmStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCWasmStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCWasmStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCWasmStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCWin64EH.cpp b/interpreter/llvm-project/llvm/lib/MC/MCWin64EH.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCWin64EH.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCWin64EH.cpp diff --git a/interpreter/llvm/src/lib/MC/MCWinCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCWinCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCWinCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCWinCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MCWinEH.cpp b/interpreter/llvm-project/llvm/lib/MC/MCWinEH.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCWinEH.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCWinEH.cpp diff --git a/interpreter/llvm/src/lib/MC/MCXCOFFObjectTargetWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MCXCOFFObjectTargetWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCXCOFFObjectTargetWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCXCOFFObjectTargetWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/MCXCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/MC/MCXCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MCXCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/MC/MCXCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/MC/MachObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/MachObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/MachObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/MachObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/StringTableBuilder.cpp b/interpreter/llvm-project/llvm/lib/MC/StringTableBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/StringTableBuilder.cpp rename to interpreter/llvm-project/llvm/lib/MC/StringTableBuilder.cpp diff --git a/interpreter/llvm/src/lib/MC/SubtargetFeature.cpp b/interpreter/llvm-project/llvm/lib/MC/SubtargetFeature.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/SubtargetFeature.cpp rename to interpreter/llvm-project/llvm/lib/MC/SubtargetFeature.cpp diff --git a/interpreter/llvm/src/lib/MC/WasmObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/WasmObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/WasmObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/WasmObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/WinCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/WinCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/WinCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/WinCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MC/XCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/MC/XCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MC/XCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/MC/XCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/MCA/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/MCA/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/MCA/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/MCA/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/MCA/CodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/MCA/CodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/CodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/MCA/CodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/MCA/Context.cpp b/interpreter/llvm-project/llvm/lib/MCA/Context.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Context.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Context.cpp diff --git a/interpreter/llvm/src/lib/MCA/CustomBehaviour.cpp b/interpreter/llvm-project/llvm/lib/MCA/CustomBehaviour.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/CustomBehaviour.cpp rename to interpreter/llvm-project/llvm/lib/MCA/CustomBehaviour.cpp diff --git a/interpreter/llvm/src/lib/MCA/HWEventListener.cpp b/interpreter/llvm-project/llvm/lib/MCA/HWEventListener.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HWEventListener.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HWEventListener.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/HardwareUnit.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/HardwareUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/HardwareUnit.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/HardwareUnit.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/LSUnit.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/LSUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/LSUnit.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/LSUnit.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/RegisterFile.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/RegisterFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/RegisterFile.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/RegisterFile.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/ResourceManager.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/ResourceManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/ResourceManager.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/ResourceManager.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/RetireControlUnit.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/RetireControlUnit.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/RetireControlUnit.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/RetireControlUnit.cpp diff --git a/interpreter/llvm/src/lib/MCA/HardwareUnits/Scheduler.cpp b/interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/Scheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/HardwareUnits/Scheduler.cpp rename to interpreter/llvm-project/llvm/lib/MCA/HardwareUnits/Scheduler.cpp diff --git a/interpreter/llvm/src/lib/MCA/InstrBuilder.cpp b/interpreter/llvm-project/llvm/lib/MCA/InstrBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/InstrBuilder.cpp rename to interpreter/llvm-project/llvm/lib/MCA/InstrBuilder.cpp diff --git a/interpreter/llvm/src/lib/MCA/Instruction.cpp b/interpreter/llvm-project/llvm/lib/MCA/Instruction.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Instruction.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Instruction.cpp diff --git a/interpreter/llvm/src/lib/MCA/Pipeline.cpp b/interpreter/llvm-project/llvm/lib/MCA/Pipeline.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Pipeline.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Pipeline.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/DispatchStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/DispatchStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/DispatchStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/DispatchStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/EntryStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/EntryStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/EntryStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/EntryStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/ExecuteStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/ExecuteStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/ExecuteStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/ExecuteStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/InOrderIssueStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/InOrderIssueStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/InOrderIssueStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/InOrderIssueStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/InstructionTables.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/InstructionTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/InstructionTables.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/InstructionTables.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/MicroOpQueueStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/MicroOpQueueStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/MicroOpQueueStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/MicroOpQueueStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/RetireStage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/RetireStage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/RetireStage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/RetireStage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Stages/Stage.cpp b/interpreter/llvm-project/llvm/lib/MCA/Stages/Stage.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Stages/Stage.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Stages/Stage.cpp diff --git a/interpreter/llvm/src/lib/MCA/Support.cpp b/interpreter/llvm-project/llvm/lib/MCA/Support.cpp similarity index 100% rename from interpreter/llvm/src/lib/MCA/Support.cpp rename to interpreter/llvm-project/llvm/lib/MCA/Support.cpp diff --git a/interpreter/llvm/src/lib/Object/Archive.cpp b/interpreter/llvm-project/llvm/lib/Object/Archive.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Archive.cpp rename to interpreter/llvm-project/llvm/lib/Object/Archive.cpp diff --git a/interpreter/llvm/src/lib/Object/ArchiveWriter.cpp b/interpreter/llvm-project/llvm/lib/Object/ArchiveWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/ArchiveWriter.cpp rename to interpreter/llvm-project/llvm/lib/Object/ArchiveWriter.cpp diff --git a/interpreter/llvm/src/lib/Object/Binary.cpp b/interpreter/llvm-project/llvm/lib/Object/Binary.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Binary.cpp rename to interpreter/llvm-project/llvm/lib/Object/Binary.cpp diff --git a/interpreter/llvm/src/lib/Object/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Object/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Object/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Object/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Object/COFFImportFile.cpp b/interpreter/llvm-project/llvm/lib/Object/COFFImportFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/COFFImportFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/COFFImportFile.cpp diff --git a/interpreter/llvm/src/lib/Object/COFFModuleDefinition.cpp b/interpreter/llvm-project/llvm/lib/Object/COFFModuleDefinition.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/COFFModuleDefinition.cpp rename to interpreter/llvm-project/llvm/lib/Object/COFFModuleDefinition.cpp diff --git a/interpreter/llvm/src/lib/Object/COFFObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/COFFObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/COFFObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/COFFObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/Decompressor.cpp b/interpreter/llvm-project/llvm/lib/Object/Decompressor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Decompressor.cpp rename to interpreter/llvm-project/llvm/lib/Object/Decompressor.cpp diff --git a/interpreter/llvm/src/lib/Object/ELF.cpp b/interpreter/llvm-project/llvm/lib/Object/ELF.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/ELF.cpp rename to interpreter/llvm-project/llvm/lib/Object/ELF.cpp diff --git a/interpreter/llvm/src/lib/Object/ELFObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/ELFObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/ELFObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/ELFObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/Error.cpp b/interpreter/llvm-project/llvm/lib/Object/Error.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Error.cpp rename to interpreter/llvm-project/llvm/lib/Object/Error.cpp diff --git a/interpreter/llvm/src/lib/Object/FaultMapParser.cpp b/interpreter/llvm-project/llvm/lib/Object/FaultMapParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/FaultMapParser.cpp rename to interpreter/llvm-project/llvm/lib/Object/FaultMapParser.cpp diff --git a/interpreter/llvm/src/lib/Object/IRObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/IRObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/IRObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/IRObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/IRSymtab.cpp b/interpreter/llvm-project/llvm/lib/Object/IRSymtab.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/IRSymtab.cpp rename to interpreter/llvm-project/llvm/lib/Object/IRSymtab.cpp diff --git a/interpreter/llvm/src/lib/Object/MachOObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/MachOObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/MachOObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/MachOObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/MachOUniversal.cpp b/interpreter/llvm-project/llvm/lib/Object/MachOUniversal.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/MachOUniversal.cpp rename to interpreter/llvm-project/llvm/lib/Object/MachOUniversal.cpp diff --git a/interpreter/llvm/src/lib/Object/MachOUniversalWriter.cpp b/interpreter/llvm-project/llvm/lib/Object/MachOUniversalWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/MachOUniversalWriter.cpp rename to interpreter/llvm-project/llvm/lib/Object/MachOUniversalWriter.cpp diff --git a/interpreter/llvm/src/lib/Object/Minidump.cpp b/interpreter/llvm-project/llvm/lib/Object/Minidump.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Minidump.cpp rename to interpreter/llvm-project/llvm/lib/Object/Minidump.cpp diff --git a/interpreter/llvm/src/lib/Object/ModuleSymbolTable.cpp b/interpreter/llvm-project/llvm/lib/Object/ModuleSymbolTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/ModuleSymbolTable.cpp rename to interpreter/llvm-project/llvm/lib/Object/ModuleSymbolTable.cpp diff --git a/interpreter/llvm/src/lib/Object/Object.cpp b/interpreter/llvm-project/llvm/lib/Object/Object.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/Object.cpp rename to interpreter/llvm-project/llvm/lib/Object/Object.cpp diff --git a/interpreter/llvm/src/lib/Object/ObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/ObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/ObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/ObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/RecordStreamer.cpp b/interpreter/llvm-project/llvm/lib/Object/RecordStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/RecordStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Object/RecordStreamer.cpp diff --git a/interpreter/llvm/src/lib/Object/RecordStreamer.h b/interpreter/llvm-project/llvm/lib/Object/RecordStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Object/RecordStreamer.h rename to interpreter/llvm-project/llvm/lib/Object/RecordStreamer.h diff --git a/interpreter/llvm/src/lib/Object/RelocationResolver.cpp b/interpreter/llvm-project/llvm/lib/Object/RelocationResolver.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/RelocationResolver.cpp rename to interpreter/llvm-project/llvm/lib/Object/RelocationResolver.cpp diff --git a/interpreter/llvm/src/lib/Object/SymbolSize.cpp b/interpreter/llvm-project/llvm/lib/Object/SymbolSize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/SymbolSize.cpp rename to interpreter/llvm-project/llvm/lib/Object/SymbolSize.cpp diff --git a/interpreter/llvm/src/lib/Object/SymbolicFile.cpp b/interpreter/llvm-project/llvm/lib/Object/SymbolicFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/SymbolicFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/SymbolicFile.cpp diff --git a/interpreter/llvm/src/lib/Object/TapiFile.cpp b/interpreter/llvm-project/llvm/lib/Object/TapiFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/TapiFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/TapiFile.cpp diff --git a/interpreter/llvm/src/lib/Object/TapiUniversal.cpp b/interpreter/llvm-project/llvm/lib/Object/TapiUniversal.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/TapiUniversal.cpp rename to interpreter/llvm-project/llvm/lib/Object/TapiUniversal.cpp diff --git a/interpreter/llvm/src/lib/Object/WasmObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/WasmObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/WasmObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/WasmObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Object/WindowsMachineFlag.cpp b/interpreter/llvm-project/llvm/lib/Object/WindowsMachineFlag.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/WindowsMachineFlag.cpp rename to interpreter/llvm-project/llvm/lib/Object/WindowsMachineFlag.cpp diff --git a/interpreter/llvm/src/lib/Object/WindowsResource.cpp b/interpreter/llvm-project/llvm/lib/Object/WindowsResource.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/WindowsResource.cpp rename to interpreter/llvm-project/llvm/lib/Object/WindowsResource.cpp diff --git a/interpreter/llvm/src/lib/Object/XCOFFObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Object/XCOFFObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Object/XCOFFObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Object/XCOFFObjectFile.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/ArchiveEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/ArchiveEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/ArchiveEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/ArchiveEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/ArchiveYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/ArchiveYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/ArchiveYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/ArchiveYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ObjectYAML/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ObjectYAML/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ObjectYAML/COFFEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/COFFEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/COFFEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/COFFEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/COFFYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/COFFYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/COFFYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/COFFYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLDebugSections.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLDebugSections.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLDebugSections.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLDebugSections.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLSymbols.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLSymbols.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLSymbols.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLSymbols.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLTypeHashing.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLTypeHashing.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLTypeHashing.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLTypeHashing.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLTypes.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLTypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/CodeViewYAMLTypes.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/CodeViewYAMLTypes.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/DWARFEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/DWARFEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/DWARFEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/DWARFEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/DWARFYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/DWARFYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/DWARFYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/DWARFYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/ELFEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/ELFEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/ELFEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/ELFEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/ELFYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/ELFYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/ELFYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/ELFYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/MachOEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/MachOEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/MachOEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/MachOEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/MachOYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/MachOYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/MachOYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/MachOYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/MinidumpEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/MinidumpEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/MinidumpEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/MinidumpEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/MinidumpYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/MinidumpYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/MinidumpYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/MinidumpYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/ObjectYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/ObjectYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/ObjectYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/ObjectYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/WasmEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/WasmEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/WasmEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/WasmEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/WasmYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/WasmYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/WasmYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/WasmYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/XCOFFEmitter.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/XCOFFEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/XCOFFEmitter.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/XCOFFEmitter.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/XCOFFYAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/XCOFFYAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/XCOFFYAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/XCOFFYAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/YAML.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/YAML.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/YAML.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/YAML.cpp diff --git a/interpreter/llvm/src/lib/ObjectYAML/yaml2obj.cpp b/interpreter/llvm-project/llvm/lib/ObjectYAML/yaml2obj.cpp similarity index 100% rename from interpreter/llvm/src/lib/ObjectYAML/yaml2obj.cpp rename to interpreter/llvm-project/llvm/lib/ObjectYAML/yaml2obj.cpp diff --git a/interpreter/llvm/src/lib/Option/Arg.cpp b/interpreter/llvm-project/llvm/lib/Option/Arg.cpp similarity index 100% rename from interpreter/llvm/src/lib/Option/Arg.cpp rename to interpreter/llvm-project/llvm/lib/Option/Arg.cpp diff --git a/interpreter/llvm/src/lib/Option/ArgList.cpp b/interpreter/llvm-project/llvm/lib/Option/ArgList.cpp similarity index 100% rename from interpreter/llvm/src/lib/Option/ArgList.cpp rename to interpreter/llvm-project/llvm/lib/Option/ArgList.cpp diff --git a/interpreter/llvm/src/lib/Option/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Option/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Option/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Option/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Option/OptTable.cpp b/interpreter/llvm-project/llvm/lib/Option/OptTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/Option/OptTable.cpp rename to interpreter/llvm-project/llvm/lib/Option/OptTable.cpp diff --git a/interpreter/llvm/src/lib/Option/Option.cpp b/interpreter/llvm-project/llvm/lib/Option/Option.cpp similarity index 100% rename from interpreter/llvm/src/lib/Option/Option.cpp rename to interpreter/llvm-project/llvm/lib/Option/Option.cpp diff --git a/interpreter/llvm/src/lib/Passes/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Passes/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Passes/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Passes/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Passes/PassBuilder.cpp b/interpreter/llvm-project/llvm/lib/Passes/PassBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Passes/PassBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Passes/PassBuilder.cpp diff --git a/interpreter/llvm/src/lib/Passes/PassBuilderBindings.cpp b/interpreter/llvm-project/llvm/lib/Passes/PassBuilderBindings.cpp similarity index 100% rename from interpreter/llvm/src/lib/Passes/PassBuilderBindings.cpp rename to interpreter/llvm-project/llvm/lib/Passes/PassBuilderBindings.cpp diff --git a/interpreter/llvm/src/lib/Passes/PassPlugin.cpp b/interpreter/llvm-project/llvm/lib/Passes/PassPlugin.cpp similarity index 100% rename from interpreter/llvm/src/lib/Passes/PassPlugin.cpp rename to interpreter/llvm-project/llvm/lib/Passes/PassPlugin.cpp diff --git a/interpreter/llvm/src/lib/Passes/PassRegistry.def b/interpreter/llvm-project/llvm/lib/Passes/PassRegistry.def similarity index 100% rename from interpreter/llvm/src/lib/Passes/PassRegistry.def rename to interpreter/llvm-project/llvm/lib/Passes/PassRegistry.def diff --git a/interpreter/llvm/src/lib/Passes/StandardInstrumentations.cpp b/interpreter/llvm-project/llvm/lib/Passes/StandardInstrumentations.cpp similarity index 99% rename from interpreter/llvm/src/lib/Passes/StandardInstrumentations.cpp rename to interpreter/llvm-project/llvm/lib/Passes/StandardInstrumentations.cpp index 5a48923bce8ab..1cdcea27576e3 100644 --- a/interpreter/llvm/src/lib/Passes/StandardInstrumentations.cpp +++ b/interpreter/llvm-project/llvm/lib/Passes/StandardInstrumentations.cpp @@ -370,8 +370,7 @@ bool isIgnored(StringRef PassID) { } // namespace -template -ChangeReporter::~ChangeReporter() { +template ChangeReporter::~ChangeReporter() { assert(BeforeStack.empty() && "Problem with Change Printer stack."); } diff --git a/interpreter/llvm/src/lib/ProfileData/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ProfileData/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ProfileData/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ProfileData/Coverage/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/Coverage/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMapping.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMapping.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMappingReader.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMappingReader.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMappingWriter.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/Coverage/CoverageMappingWriter.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/GCOV.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/GCOV.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/GCOV.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/GCOV.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/InstrProf.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/InstrProf.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/InstrProf.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/InstrProf.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/InstrProfReader.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/InstrProfReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/InstrProfReader.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/InstrProfReader.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/InstrProfWriter.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/InstrProfWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/InstrProfWriter.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/InstrProfWriter.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/ProfileSummaryBuilder.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/ProfileSummaryBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/ProfileSummaryBuilder.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/ProfileSummaryBuilder.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/SampleProf.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/SampleProf.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/SampleProf.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/SampleProf.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/SampleProfReader.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/SampleProfReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/SampleProfReader.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/SampleProfReader.cpp diff --git a/interpreter/llvm/src/lib/ProfileData/SampleProfWriter.cpp b/interpreter/llvm-project/llvm/lib/ProfileData/SampleProfWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/ProfileData/SampleProfWriter.cpp rename to interpreter/llvm-project/llvm/lib/ProfileData/SampleProfWriter.cpp diff --git a/interpreter/llvm/src/lib/Remarks/BitstreamRemarkParser.cpp b/interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/BitstreamRemarkParser.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkParser.cpp diff --git a/interpreter/llvm/src/lib/Remarks/BitstreamRemarkParser.h b/interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkParser.h similarity index 100% rename from interpreter/llvm/src/lib/Remarks/BitstreamRemarkParser.h rename to interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkParser.h diff --git a/interpreter/llvm/src/lib/Remarks/BitstreamRemarkSerializer.cpp b/interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkSerializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/BitstreamRemarkSerializer.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/BitstreamRemarkSerializer.cpp diff --git a/interpreter/llvm/src/lib/Remarks/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Remarks/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Remarks/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Remarks/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Remarks/Remark.cpp b/interpreter/llvm-project/llvm/lib/Remarks/Remark.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/Remark.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/Remark.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkFormat.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkFormat.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkFormat.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkFormat.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkLinker.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkLinker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkLinker.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkLinker.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkParser.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkParser.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkParser.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkSerializer.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkSerializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkSerializer.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkSerializer.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkStreamer.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkStreamer.cpp diff --git a/interpreter/llvm/src/lib/Remarks/RemarkStringTable.cpp b/interpreter/llvm-project/llvm/lib/Remarks/RemarkStringTable.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/RemarkStringTable.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/RemarkStringTable.cpp diff --git a/interpreter/llvm/src/lib/Remarks/YAMLRemarkParser.cpp b/interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/YAMLRemarkParser.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkParser.cpp diff --git a/interpreter/llvm/src/lib/Remarks/YAMLRemarkParser.h b/interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkParser.h similarity index 100% rename from interpreter/llvm/src/lib/Remarks/YAMLRemarkParser.h rename to interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkParser.h diff --git a/interpreter/llvm/src/lib/Remarks/YAMLRemarkSerializer.cpp b/interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkSerializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Remarks/YAMLRemarkSerializer.cpp rename to interpreter/llvm-project/llvm/lib/Remarks/YAMLRemarkSerializer.cpp diff --git a/interpreter/llvm/src/lib/Support/AArch64TargetParser.cpp b/interpreter/llvm-project/llvm/lib/Support/AArch64TargetParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/AArch64TargetParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/AArch64TargetParser.cpp diff --git a/interpreter/llvm/src/lib/Support/ABIBreak.cpp b/interpreter/llvm-project/llvm/lib/Support/ABIBreak.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ABIBreak.cpp rename to interpreter/llvm-project/llvm/lib/Support/ABIBreak.cpp diff --git a/interpreter/llvm/src/lib/Support/AMDGPUMetadata.cpp b/interpreter/llvm-project/llvm/lib/Support/AMDGPUMetadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/AMDGPUMetadata.cpp rename to interpreter/llvm-project/llvm/lib/Support/AMDGPUMetadata.cpp diff --git a/interpreter/llvm/src/lib/Support/APFixedPoint.cpp b/interpreter/llvm-project/llvm/lib/Support/APFixedPoint.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/APFixedPoint.cpp rename to interpreter/llvm-project/llvm/lib/Support/APFixedPoint.cpp diff --git a/interpreter/llvm/src/lib/Support/APFloat.cpp b/interpreter/llvm-project/llvm/lib/Support/APFloat.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/APFloat.cpp rename to interpreter/llvm-project/llvm/lib/Support/APFloat.cpp diff --git a/interpreter/llvm/src/lib/Support/APInt.cpp b/interpreter/llvm-project/llvm/lib/Support/APInt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/APInt.cpp rename to interpreter/llvm-project/llvm/lib/Support/APInt.cpp diff --git a/interpreter/llvm/src/lib/Support/APSInt.cpp b/interpreter/llvm-project/llvm/lib/Support/APSInt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/APSInt.cpp rename to interpreter/llvm-project/llvm/lib/Support/APSInt.cpp diff --git a/interpreter/llvm/src/lib/Support/ARMAttributeParser.cpp b/interpreter/llvm-project/llvm/lib/Support/ARMAttributeParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ARMAttributeParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/ARMAttributeParser.cpp diff --git a/interpreter/llvm/src/lib/Support/ARMBuildAttrs.cpp b/interpreter/llvm-project/llvm/lib/Support/ARMBuildAttrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ARMBuildAttrs.cpp rename to interpreter/llvm-project/llvm/lib/Support/ARMBuildAttrs.cpp diff --git a/interpreter/llvm/src/lib/Support/ARMTargetParser.cpp b/interpreter/llvm-project/llvm/lib/Support/ARMTargetParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ARMTargetParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/ARMTargetParser.cpp diff --git a/interpreter/llvm/src/lib/Support/ARMWinEH.cpp b/interpreter/llvm-project/llvm/lib/Support/ARMWinEH.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ARMWinEH.cpp rename to interpreter/llvm-project/llvm/lib/Support/ARMWinEH.cpp diff --git a/interpreter/llvm/src/lib/Support/Allocator.cpp b/interpreter/llvm-project/llvm/lib/Support/Allocator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Allocator.cpp rename to interpreter/llvm-project/llvm/lib/Support/Allocator.cpp diff --git a/interpreter/llvm/src/lib/Support/Atomic.cpp b/interpreter/llvm-project/llvm/lib/Support/Atomic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Atomic.cpp rename to interpreter/llvm-project/llvm/lib/Support/Atomic.cpp diff --git a/interpreter/llvm/src/lib/Support/AutoConvert.cpp b/interpreter/llvm-project/llvm/lib/Support/AutoConvert.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/AutoConvert.cpp rename to interpreter/llvm-project/llvm/lib/Support/AutoConvert.cpp diff --git a/interpreter/llvm/src/lib/Support/BinaryStreamError.cpp b/interpreter/llvm-project/llvm/lib/Support/BinaryStreamError.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BinaryStreamError.cpp rename to interpreter/llvm-project/llvm/lib/Support/BinaryStreamError.cpp diff --git a/interpreter/llvm/src/lib/Support/BinaryStreamReader.cpp b/interpreter/llvm-project/llvm/lib/Support/BinaryStreamReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BinaryStreamReader.cpp rename to interpreter/llvm-project/llvm/lib/Support/BinaryStreamReader.cpp diff --git a/interpreter/llvm/src/lib/Support/BinaryStreamRef.cpp b/interpreter/llvm-project/llvm/lib/Support/BinaryStreamRef.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BinaryStreamRef.cpp rename to interpreter/llvm-project/llvm/lib/Support/BinaryStreamRef.cpp diff --git a/interpreter/llvm/src/lib/Support/BinaryStreamWriter.cpp b/interpreter/llvm-project/llvm/lib/Support/BinaryStreamWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BinaryStreamWriter.cpp rename to interpreter/llvm-project/llvm/lib/Support/BinaryStreamWriter.cpp diff --git a/interpreter/llvm/src/lib/Support/BlockFrequency.cpp b/interpreter/llvm-project/llvm/lib/Support/BlockFrequency.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BlockFrequency.cpp rename to interpreter/llvm-project/llvm/lib/Support/BlockFrequency.cpp diff --git a/interpreter/llvm/src/lib/Support/BranchProbability.cpp b/interpreter/llvm-project/llvm/lib/Support/BranchProbability.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BranchProbability.cpp rename to interpreter/llvm-project/llvm/lib/Support/BranchProbability.cpp diff --git a/interpreter/llvm/src/lib/Support/BuryPointer.cpp b/interpreter/llvm-project/llvm/lib/Support/BuryPointer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/BuryPointer.cpp rename to interpreter/llvm-project/llvm/lib/Support/BuryPointer.cpp diff --git a/interpreter/llvm/src/lib/Support/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Support/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Support/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Support/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Support/COM.cpp b/interpreter/llvm-project/llvm/lib/Support/COM.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/COM.cpp rename to interpreter/llvm-project/llvm/lib/Support/COM.cpp diff --git a/interpreter/llvm/src/lib/Support/COPYRIGHT.regex b/interpreter/llvm-project/llvm/lib/Support/COPYRIGHT.regex similarity index 100% rename from interpreter/llvm/src/lib/Support/COPYRIGHT.regex rename to interpreter/llvm-project/llvm/lib/Support/COPYRIGHT.regex diff --git a/interpreter/llvm/src/lib/Support/CRC.cpp b/interpreter/llvm-project/llvm/lib/Support/CRC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/CRC.cpp rename to interpreter/llvm-project/llvm/lib/Support/CRC.cpp diff --git a/interpreter/llvm/src/lib/Support/CachePruning.cpp b/interpreter/llvm-project/llvm/lib/Support/CachePruning.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/CachePruning.cpp rename to interpreter/llvm-project/llvm/lib/Support/CachePruning.cpp diff --git a/interpreter/llvm/src/lib/Support/Chrono.cpp b/interpreter/llvm-project/llvm/lib/Support/Chrono.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Chrono.cpp rename to interpreter/llvm-project/llvm/lib/Support/Chrono.cpp diff --git a/interpreter/llvm/src/lib/Support/CodeGenCoverage.cpp b/interpreter/llvm-project/llvm/lib/Support/CodeGenCoverage.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/CodeGenCoverage.cpp rename to interpreter/llvm-project/llvm/lib/Support/CodeGenCoverage.cpp diff --git a/interpreter/llvm/src/lib/Support/CommandLine.cpp b/interpreter/llvm-project/llvm/lib/Support/CommandLine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/CommandLine.cpp rename to interpreter/llvm-project/llvm/lib/Support/CommandLine.cpp diff --git a/interpreter/llvm/src/lib/Support/Compression.cpp b/interpreter/llvm-project/llvm/lib/Support/Compression.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Compression.cpp rename to interpreter/llvm-project/llvm/lib/Support/Compression.cpp diff --git a/interpreter/llvm/src/lib/Support/ConvertUTF.cpp b/interpreter/llvm-project/llvm/lib/Support/ConvertUTF.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ConvertUTF.cpp rename to interpreter/llvm-project/llvm/lib/Support/ConvertUTF.cpp diff --git a/interpreter/llvm/src/lib/Support/ConvertUTFWrapper.cpp b/interpreter/llvm-project/llvm/lib/Support/ConvertUTFWrapper.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ConvertUTFWrapper.cpp rename to interpreter/llvm-project/llvm/lib/Support/ConvertUTFWrapper.cpp diff --git a/interpreter/llvm/src/lib/Support/CrashRecoveryContext.cpp b/interpreter/llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/CrashRecoveryContext.cpp rename to interpreter/llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp diff --git a/interpreter/llvm/src/lib/Support/DAGDeltaAlgorithm.cpp b/interpreter/llvm-project/llvm/lib/Support/DAGDeltaAlgorithm.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DAGDeltaAlgorithm.cpp rename to interpreter/llvm-project/llvm/lib/Support/DAGDeltaAlgorithm.cpp diff --git a/interpreter/llvm/src/lib/Support/DJB.cpp b/interpreter/llvm-project/llvm/lib/Support/DJB.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DJB.cpp rename to interpreter/llvm-project/llvm/lib/Support/DJB.cpp diff --git a/interpreter/llvm/src/lib/Support/DataExtractor.cpp b/interpreter/llvm-project/llvm/lib/Support/DataExtractor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DataExtractor.cpp rename to interpreter/llvm-project/llvm/lib/Support/DataExtractor.cpp diff --git a/interpreter/llvm/src/lib/Support/Debug.cpp b/interpreter/llvm-project/llvm/lib/Support/Debug.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Debug.cpp rename to interpreter/llvm-project/llvm/lib/Support/Debug.cpp diff --git a/interpreter/llvm/src/lib/Support/DebugCounter.cpp b/interpreter/llvm-project/llvm/lib/Support/DebugCounter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DebugCounter.cpp rename to interpreter/llvm-project/llvm/lib/Support/DebugCounter.cpp diff --git a/interpreter/llvm/src/lib/Support/DebugOptions.h b/interpreter/llvm-project/llvm/lib/Support/DebugOptions.h similarity index 100% rename from interpreter/llvm/src/lib/Support/DebugOptions.h rename to interpreter/llvm-project/llvm/lib/Support/DebugOptions.h diff --git a/interpreter/llvm/src/lib/Support/DeltaAlgorithm.cpp b/interpreter/llvm-project/llvm/lib/Support/DeltaAlgorithm.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DeltaAlgorithm.cpp rename to interpreter/llvm-project/llvm/lib/Support/DeltaAlgorithm.cpp diff --git a/interpreter/llvm/src/lib/Support/DynamicLibrary.cpp b/interpreter/llvm-project/llvm/lib/Support/DynamicLibrary.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/DynamicLibrary.cpp rename to interpreter/llvm-project/llvm/lib/Support/DynamicLibrary.cpp diff --git a/interpreter/llvm/src/lib/Support/ELFAttributeParser.cpp b/interpreter/llvm-project/llvm/lib/Support/ELFAttributeParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ELFAttributeParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/ELFAttributeParser.cpp diff --git a/interpreter/llvm/src/lib/Support/ELFAttributes.cpp b/interpreter/llvm-project/llvm/lib/Support/ELFAttributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ELFAttributes.cpp rename to interpreter/llvm-project/llvm/lib/Support/ELFAttributes.cpp diff --git a/interpreter/llvm/src/lib/Support/Errno.cpp b/interpreter/llvm-project/llvm/lib/Support/Errno.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Errno.cpp rename to interpreter/llvm-project/llvm/lib/Support/Errno.cpp diff --git a/interpreter/llvm/src/lib/Support/Error.cpp b/interpreter/llvm-project/llvm/lib/Support/Error.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Error.cpp rename to interpreter/llvm-project/llvm/lib/Support/Error.cpp diff --git a/interpreter/llvm/src/lib/Support/ErrorHandling.cpp b/interpreter/llvm-project/llvm/lib/Support/ErrorHandling.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ErrorHandling.cpp rename to interpreter/llvm-project/llvm/lib/Support/ErrorHandling.cpp diff --git a/interpreter/llvm/src/lib/Support/ExtensibleRTTI.cpp b/interpreter/llvm-project/llvm/lib/Support/ExtensibleRTTI.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ExtensibleRTTI.cpp rename to interpreter/llvm-project/llvm/lib/Support/ExtensibleRTTI.cpp diff --git a/interpreter/llvm/src/lib/Support/FileCollector.cpp b/interpreter/llvm-project/llvm/lib/Support/FileCollector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FileCollector.cpp rename to interpreter/llvm-project/llvm/lib/Support/FileCollector.cpp diff --git a/interpreter/llvm/src/lib/Support/FileOutputBuffer.cpp b/interpreter/llvm-project/llvm/lib/Support/FileOutputBuffer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FileOutputBuffer.cpp rename to interpreter/llvm-project/llvm/lib/Support/FileOutputBuffer.cpp diff --git a/interpreter/llvm/src/lib/Support/FileUtilities.cpp b/interpreter/llvm-project/llvm/lib/Support/FileUtilities.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FileUtilities.cpp rename to interpreter/llvm-project/llvm/lib/Support/FileUtilities.cpp diff --git a/interpreter/llvm/src/lib/Support/FoldingSet.cpp b/interpreter/llvm-project/llvm/lib/Support/FoldingSet.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FoldingSet.cpp rename to interpreter/llvm-project/llvm/lib/Support/FoldingSet.cpp diff --git a/interpreter/llvm/src/lib/Support/FormatVariadic.cpp b/interpreter/llvm-project/llvm/lib/Support/FormatVariadic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FormatVariadic.cpp rename to interpreter/llvm-project/llvm/lib/Support/FormatVariadic.cpp diff --git a/interpreter/llvm/src/lib/Support/FormattedStream.cpp b/interpreter/llvm-project/llvm/lib/Support/FormattedStream.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/FormattedStream.cpp rename to interpreter/llvm-project/llvm/lib/Support/FormattedStream.cpp diff --git a/interpreter/llvm/src/lib/Support/GlobPattern.cpp b/interpreter/llvm-project/llvm/lib/Support/GlobPattern.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/GlobPattern.cpp rename to interpreter/llvm-project/llvm/lib/Support/GlobPattern.cpp diff --git a/interpreter/llvm/src/lib/Support/GraphWriter.cpp b/interpreter/llvm-project/llvm/lib/Support/GraphWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/GraphWriter.cpp rename to interpreter/llvm-project/llvm/lib/Support/GraphWriter.cpp diff --git a/interpreter/llvm/src/lib/Support/Hashing.cpp b/interpreter/llvm-project/llvm/lib/Support/Hashing.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Hashing.cpp rename to interpreter/llvm-project/llvm/lib/Support/Hashing.cpp diff --git a/interpreter/llvm/src/lib/Support/Host.cpp b/interpreter/llvm-project/llvm/lib/Support/Host.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Host.cpp rename to interpreter/llvm-project/llvm/lib/Support/Host.cpp diff --git a/interpreter/llvm/src/lib/Support/InitLLVM.cpp b/interpreter/llvm-project/llvm/lib/Support/InitLLVM.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/InitLLVM.cpp rename to interpreter/llvm-project/llvm/lib/Support/InitLLVM.cpp diff --git a/interpreter/llvm/src/lib/Support/InstructionCost.cpp b/interpreter/llvm-project/llvm/lib/Support/InstructionCost.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/InstructionCost.cpp rename to interpreter/llvm-project/llvm/lib/Support/InstructionCost.cpp diff --git a/interpreter/llvm/src/lib/Support/IntEqClasses.cpp b/interpreter/llvm-project/llvm/lib/Support/IntEqClasses.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/IntEqClasses.cpp rename to interpreter/llvm-project/llvm/lib/Support/IntEqClasses.cpp diff --git a/interpreter/llvm/src/lib/Support/IntervalMap.cpp b/interpreter/llvm-project/llvm/lib/Support/IntervalMap.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/IntervalMap.cpp rename to interpreter/llvm-project/llvm/lib/Support/IntervalMap.cpp diff --git a/interpreter/llvm/src/lib/Support/ItaniumManglingCanonicalizer.cpp b/interpreter/llvm-project/llvm/lib/Support/ItaniumManglingCanonicalizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ItaniumManglingCanonicalizer.cpp rename to interpreter/llvm-project/llvm/lib/Support/ItaniumManglingCanonicalizer.cpp diff --git a/interpreter/llvm/src/lib/Support/JSON.cpp b/interpreter/llvm-project/llvm/lib/Support/JSON.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/JSON.cpp rename to interpreter/llvm-project/llvm/lib/Support/JSON.cpp diff --git a/interpreter/llvm/src/lib/Support/KnownBits.cpp b/interpreter/llvm-project/llvm/lib/Support/KnownBits.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/KnownBits.cpp rename to interpreter/llvm-project/llvm/lib/Support/KnownBits.cpp diff --git a/interpreter/llvm/src/lib/Support/LEB128.cpp b/interpreter/llvm-project/llvm/lib/Support/LEB128.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/LEB128.cpp rename to interpreter/llvm-project/llvm/lib/Support/LEB128.cpp diff --git a/interpreter/llvm/src/lib/Support/LineIterator.cpp b/interpreter/llvm-project/llvm/lib/Support/LineIterator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/LineIterator.cpp rename to interpreter/llvm-project/llvm/lib/Support/LineIterator.cpp diff --git a/interpreter/llvm/src/lib/Support/Locale.cpp b/interpreter/llvm-project/llvm/lib/Support/Locale.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Locale.cpp rename to interpreter/llvm-project/llvm/lib/Support/Locale.cpp diff --git a/interpreter/llvm/src/lib/Support/LockFileManager.cpp b/interpreter/llvm-project/llvm/lib/Support/LockFileManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/LockFileManager.cpp rename to interpreter/llvm-project/llvm/lib/Support/LockFileManager.cpp diff --git a/interpreter/llvm/src/lib/Support/LowLevelType.cpp b/interpreter/llvm-project/llvm/lib/Support/LowLevelType.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/LowLevelType.cpp rename to interpreter/llvm-project/llvm/lib/Support/LowLevelType.cpp diff --git a/interpreter/llvm/src/lib/Support/MD5.cpp b/interpreter/llvm-project/llvm/lib/Support/MD5.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/MD5.cpp rename to interpreter/llvm-project/llvm/lib/Support/MD5.cpp diff --git a/interpreter/llvm/src/lib/Support/ManagedStatic.cpp b/interpreter/llvm-project/llvm/lib/Support/ManagedStatic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ManagedStatic.cpp rename to interpreter/llvm-project/llvm/lib/Support/ManagedStatic.cpp diff --git a/interpreter/llvm/src/lib/Support/MathExtras.cpp b/interpreter/llvm-project/llvm/lib/Support/MathExtras.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/MathExtras.cpp rename to interpreter/llvm-project/llvm/lib/Support/MathExtras.cpp diff --git a/interpreter/llvm/src/lib/Support/MemAlloc.cpp b/interpreter/llvm-project/llvm/lib/Support/MemAlloc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/MemAlloc.cpp rename to interpreter/llvm-project/llvm/lib/Support/MemAlloc.cpp diff --git a/interpreter/llvm/src/lib/Support/Memory.cpp b/interpreter/llvm-project/llvm/lib/Support/Memory.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Memory.cpp rename to interpreter/llvm-project/llvm/lib/Support/Memory.cpp diff --git a/interpreter/llvm/src/lib/Support/MemoryBuffer.cpp b/interpreter/llvm-project/llvm/lib/Support/MemoryBuffer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/MemoryBuffer.cpp rename to interpreter/llvm-project/llvm/lib/Support/MemoryBuffer.cpp diff --git a/interpreter/llvm/src/lib/Support/MemoryBufferRef.cpp b/interpreter/llvm-project/llvm/lib/Support/MemoryBufferRef.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/MemoryBufferRef.cpp rename to interpreter/llvm-project/llvm/lib/Support/MemoryBufferRef.cpp diff --git a/interpreter/llvm/src/lib/Support/NativeFormatting.cpp b/interpreter/llvm-project/llvm/lib/Support/NativeFormatting.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/NativeFormatting.cpp rename to interpreter/llvm-project/llvm/lib/Support/NativeFormatting.cpp diff --git a/interpreter/llvm/src/lib/Support/OptimizedStructLayout.cpp b/interpreter/llvm-project/llvm/lib/Support/OptimizedStructLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/OptimizedStructLayout.cpp rename to interpreter/llvm-project/llvm/lib/Support/OptimizedStructLayout.cpp diff --git a/interpreter/llvm/src/lib/Support/Optional.cpp b/interpreter/llvm-project/llvm/lib/Support/Optional.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Optional.cpp rename to interpreter/llvm-project/llvm/lib/Support/Optional.cpp diff --git a/interpreter/llvm/src/lib/Support/Parallel.cpp b/interpreter/llvm-project/llvm/lib/Support/Parallel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Parallel.cpp rename to interpreter/llvm-project/llvm/lib/Support/Parallel.cpp diff --git a/interpreter/llvm/src/lib/Support/Path.cpp b/interpreter/llvm-project/llvm/lib/Support/Path.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Path.cpp rename to interpreter/llvm-project/llvm/lib/Support/Path.cpp diff --git a/interpreter/llvm/src/lib/Support/PluginLoader.cpp b/interpreter/llvm-project/llvm/lib/Support/PluginLoader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/PluginLoader.cpp rename to interpreter/llvm-project/llvm/lib/Support/PluginLoader.cpp diff --git a/interpreter/llvm/src/lib/Support/PrettyStackTrace.cpp b/interpreter/llvm-project/llvm/lib/Support/PrettyStackTrace.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/PrettyStackTrace.cpp rename to interpreter/llvm-project/llvm/lib/Support/PrettyStackTrace.cpp diff --git a/interpreter/llvm/src/lib/Support/Process.cpp b/interpreter/llvm-project/llvm/lib/Support/Process.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Process.cpp rename to interpreter/llvm-project/llvm/lib/Support/Process.cpp diff --git a/interpreter/llvm/src/lib/Support/Program.cpp b/interpreter/llvm-project/llvm/lib/Support/Program.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Program.cpp rename to interpreter/llvm-project/llvm/lib/Support/Program.cpp diff --git a/interpreter/llvm/src/lib/Support/RISCVAttributeParser.cpp b/interpreter/llvm-project/llvm/lib/Support/RISCVAttributeParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/RISCVAttributeParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/RISCVAttributeParser.cpp diff --git a/interpreter/llvm/src/lib/Support/RISCVAttributes.cpp b/interpreter/llvm-project/llvm/lib/Support/RISCVAttributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/RISCVAttributes.cpp rename to interpreter/llvm-project/llvm/lib/Support/RISCVAttributes.cpp diff --git a/interpreter/llvm/src/lib/Support/RWMutex.cpp b/interpreter/llvm-project/llvm/lib/Support/RWMutex.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/RWMutex.cpp rename to interpreter/llvm-project/llvm/lib/Support/RWMutex.cpp diff --git a/interpreter/llvm/src/lib/Support/RandomNumberGenerator.cpp b/interpreter/llvm-project/llvm/lib/Support/RandomNumberGenerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/RandomNumberGenerator.cpp rename to interpreter/llvm-project/llvm/lib/Support/RandomNumberGenerator.cpp diff --git a/interpreter/llvm/src/lib/Support/Regex.cpp b/interpreter/llvm-project/llvm/lib/Support/Regex.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Regex.cpp rename to interpreter/llvm-project/llvm/lib/Support/Regex.cpp diff --git a/interpreter/llvm/src/lib/Support/SHA1.cpp b/interpreter/llvm-project/llvm/lib/Support/SHA1.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SHA1.cpp rename to interpreter/llvm-project/llvm/lib/Support/SHA1.cpp diff --git a/interpreter/llvm/src/lib/Support/SHA256.cpp b/interpreter/llvm-project/llvm/lib/Support/SHA256.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SHA256.cpp rename to interpreter/llvm-project/llvm/lib/Support/SHA256.cpp diff --git a/interpreter/llvm/src/lib/Support/ScaledNumber.cpp b/interpreter/llvm-project/llvm/lib/Support/ScaledNumber.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ScaledNumber.cpp rename to interpreter/llvm-project/llvm/lib/Support/ScaledNumber.cpp diff --git a/interpreter/llvm/src/lib/Support/ScopedPrinter.cpp b/interpreter/llvm-project/llvm/lib/Support/ScopedPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ScopedPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Support/ScopedPrinter.cpp diff --git a/interpreter/llvm/src/lib/Support/Signals.cpp b/interpreter/llvm-project/llvm/lib/Support/Signals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Signals.cpp rename to interpreter/llvm-project/llvm/lib/Support/Signals.cpp diff --git a/interpreter/llvm/src/lib/Support/Signposts.cpp b/interpreter/llvm-project/llvm/lib/Support/Signposts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Signposts.cpp rename to interpreter/llvm-project/llvm/lib/Support/Signposts.cpp diff --git a/interpreter/llvm/src/lib/Support/SmallPtrSet.cpp b/interpreter/llvm-project/llvm/lib/Support/SmallPtrSet.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SmallPtrSet.cpp rename to interpreter/llvm-project/llvm/lib/Support/SmallPtrSet.cpp diff --git a/interpreter/llvm/src/lib/Support/SmallVector.cpp b/interpreter/llvm-project/llvm/lib/Support/SmallVector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SmallVector.cpp rename to interpreter/llvm-project/llvm/lib/Support/SmallVector.cpp diff --git a/interpreter/llvm/src/lib/Support/SourceMgr.cpp b/interpreter/llvm-project/llvm/lib/Support/SourceMgr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SourceMgr.cpp rename to interpreter/llvm-project/llvm/lib/Support/SourceMgr.cpp diff --git a/interpreter/llvm/src/lib/Support/SpecialCaseList.cpp b/interpreter/llvm-project/llvm/lib/Support/SpecialCaseList.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SpecialCaseList.cpp rename to interpreter/llvm-project/llvm/lib/Support/SpecialCaseList.cpp diff --git a/interpreter/llvm/src/lib/Support/Statistic.cpp b/interpreter/llvm-project/llvm/lib/Support/Statistic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Statistic.cpp rename to interpreter/llvm-project/llvm/lib/Support/Statistic.cpp diff --git a/interpreter/llvm/src/lib/Support/StringExtras.cpp b/interpreter/llvm-project/llvm/lib/Support/StringExtras.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/StringExtras.cpp rename to interpreter/llvm-project/llvm/lib/Support/StringExtras.cpp diff --git a/interpreter/llvm/src/lib/Support/StringMap.cpp b/interpreter/llvm-project/llvm/lib/Support/StringMap.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/StringMap.cpp rename to interpreter/llvm-project/llvm/lib/Support/StringMap.cpp diff --git a/interpreter/llvm/src/lib/Support/StringRef.cpp b/interpreter/llvm-project/llvm/lib/Support/StringRef.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/StringRef.cpp rename to interpreter/llvm-project/llvm/lib/Support/StringRef.cpp diff --git a/interpreter/llvm/src/lib/Support/StringSaver.cpp b/interpreter/llvm-project/llvm/lib/Support/StringSaver.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/StringSaver.cpp rename to interpreter/llvm-project/llvm/lib/Support/StringSaver.cpp diff --git a/interpreter/llvm/src/lib/Support/SuffixTree.cpp b/interpreter/llvm-project/llvm/lib/Support/SuffixTree.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SuffixTree.cpp rename to interpreter/llvm-project/llvm/lib/Support/SuffixTree.cpp diff --git a/interpreter/llvm/src/lib/Support/SymbolRemappingReader.cpp b/interpreter/llvm-project/llvm/lib/Support/SymbolRemappingReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SymbolRemappingReader.cpp rename to interpreter/llvm-project/llvm/lib/Support/SymbolRemappingReader.cpp diff --git a/interpreter/llvm/src/lib/Support/SystemUtils.cpp b/interpreter/llvm-project/llvm/lib/Support/SystemUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/SystemUtils.cpp rename to interpreter/llvm-project/llvm/lib/Support/SystemUtils.cpp diff --git a/interpreter/llvm/src/lib/Support/TarWriter.cpp b/interpreter/llvm-project/llvm/lib/Support/TarWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TarWriter.cpp rename to interpreter/llvm-project/llvm/lib/Support/TarWriter.cpp diff --git a/interpreter/llvm/src/lib/Support/TargetParser.cpp b/interpreter/llvm-project/llvm/lib/Support/TargetParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TargetParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/TargetParser.cpp diff --git a/interpreter/llvm/src/lib/Support/TargetRegistry.cpp b/interpreter/llvm-project/llvm/lib/Support/TargetRegistry.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TargetRegistry.cpp rename to interpreter/llvm-project/llvm/lib/Support/TargetRegistry.cpp diff --git a/interpreter/llvm/src/lib/Support/ThreadLocal.cpp b/interpreter/llvm-project/llvm/lib/Support/ThreadLocal.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ThreadLocal.cpp rename to interpreter/llvm-project/llvm/lib/Support/ThreadLocal.cpp diff --git a/interpreter/llvm/src/lib/Support/ThreadPool.cpp b/interpreter/llvm-project/llvm/lib/Support/ThreadPool.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ThreadPool.cpp rename to interpreter/llvm-project/llvm/lib/Support/ThreadPool.cpp diff --git a/interpreter/llvm/src/lib/Support/Threading.cpp b/interpreter/llvm-project/llvm/lib/Support/Threading.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Threading.cpp rename to interpreter/llvm-project/llvm/lib/Support/Threading.cpp diff --git a/interpreter/llvm/src/lib/Support/TimeProfiler.cpp b/interpreter/llvm-project/llvm/lib/Support/TimeProfiler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TimeProfiler.cpp rename to interpreter/llvm-project/llvm/lib/Support/TimeProfiler.cpp diff --git a/interpreter/llvm/src/lib/Support/Timer.cpp b/interpreter/llvm-project/llvm/lib/Support/Timer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Timer.cpp rename to interpreter/llvm-project/llvm/lib/Support/Timer.cpp diff --git a/interpreter/llvm/src/lib/Support/ToolOutputFile.cpp b/interpreter/llvm-project/llvm/lib/Support/ToolOutputFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/ToolOutputFile.cpp rename to interpreter/llvm-project/llvm/lib/Support/ToolOutputFile.cpp diff --git a/interpreter/llvm/src/lib/Support/TrigramIndex.cpp b/interpreter/llvm-project/llvm/lib/Support/TrigramIndex.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TrigramIndex.cpp rename to interpreter/llvm-project/llvm/lib/Support/TrigramIndex.cpp diff --git a/interpreter/llvm/src/lib/Support/Triple.cpp b/interpreter/llvm-project/llvm/lib/Support/Triple.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Triple.cpp rename to interpreter/llvm-project/llvm/lib/Support/Triple.cpp diff --git a/interpreter/llvm/src/lib/Support/Twine.cpp b/interpreter/llvm-project/llvm/lib/Support/Twine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Twine.cpp rename to interpreter/llvm-project/llvm/lib/Support/Twine.cpp diff --git a/interpreter/llvm/src/lib/Support/TypeSize.cpp b/interpreter/llvm-project/llvm/lib/Support/TypeSize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/TypeSize.cpp rename to interpreter/llvm-project/llvm/lib/Support/TypeSize.cpp diff --git a/interpreter/llvm/src/lib/Support/Unicode.cpp b/interpreter/llvm-project/llvm/lib/Support/Unicode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Unicode.cpp rename to interpreter/llvm-project/llvm/lib/Support/Unicode.cpp diff --git a/interpreter/llvm/src/lib/Support/UnicodeCaseFold.cpp b/interpreter/llvm-project/llvm/lib/Support/UnicodeCaseFold.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/UnicodeCaseFold.cpp rename to interpreter/llvm-project/llvm/lib/Support/UnicodeCaseFold.cpp diff --git a/interpreter/llvm/src/lib/Support/Unix/COM.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/COM.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/COM.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/COM.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/DynamicLibrary.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/DynamicLibrary.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/DynamicLibrary.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/DynamicLibrary.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Host.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Host.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Host.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Host.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Memory.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Memory.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Memory.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Memory.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Path.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Path.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Path.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Path.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Process.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Process.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Process.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Process.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Program.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Program.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Program.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Program.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/README.txt b/interpreter/llvm-project/llvm/lib/Support/Unix/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/README.txt rename to interpreter/llvm-project/llvm/lib/Support/Unix/README.txt diff --git a/interpreter/llvm/src/lib/Support/Unix/Signals.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Signals.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Signals.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Signals.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/ThreadLocal.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/ThreadLocal.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/ThreadLocal.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/ThreadLocal.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Threading.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Threading.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Threading.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Threading.inc diff --git a/interpreter/llvm/src/lib/Support/Unix/Unix.h b/interpreter/llvm-project/llvm/lib/Support/Unix/Unix.h similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Unix.h rename to interpreter/llvm-project/llvm/lib/Support/Unix/Unix.h diff --git a/interpreter/llvm/src/lib/Support/Unix/Watchdog.inc b/interpreter/llvm-project/llvm/lib/Support/Unix/Watchdog.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Unix/Watchdog.inc rename to interpreter/llvm-project/llvm/lib/Support/Unix/Watchdog.inc diff --git a/interpreter/llvm/src/lib/Support/Valgrind.cpp b/interpreter/llvm-project/llvm/lib/Support/Valgrind.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Valgrind.cpp rename to interpreter/llvm-project/llvm/lib/Support/Valgrind.cpp diff --git a/interpreter/llvm/src/lib/Support/VersionTuple.cpp b/interpreter/llvm-project/llvm/lib/Support/VersionTuple.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/VersionTuple.cpp rename to interpreter/llvm-project/llvm/lib/Support/VersionTuple.cpp diff --git a/interpreter/llvm/src/lib/Support/VirtualFileSystem.cpp b/interpreter/llvm-project/llvm/lib/Support/VirtualFileSystem.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/VirtualFileSystem.cpp rename to interpreter/llvm-project/llvm/lib/Support/VirtualFileSystem.cpp diff --git a/interpreter/llvm/src/lib/Support/Watchdog.cpp b/interpreter/llvm-project/llvm/lib/Support/Watchdog.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Watchdog.cpp rename to interpreter/llvm-project/llvm/lib/Support/Watchdog.cpp diff --git a/interpreter/llvm/src/lib/Support/Windows/COM.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/COM.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/COM.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/COM.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/DynamicLibrary.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/DynamicLibrary.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/DynamicLibrary.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/DynamicLibrary.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Host.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Host.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Host.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Host.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Memory.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Memory.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Memory.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Memory.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Path.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Path.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Path.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Path.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Process.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Process.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Process.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Process.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Program.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Program.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Program.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Program.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Signals.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Signals.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Signals.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Signals.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/ThreadLocal.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/ThreadLocal.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/ThreadLocal.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/ThreadLocal.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Threading.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Threading.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Threading.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Threading.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/Watchdog.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/Watchdog.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/Watchdog.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/Watchdog.inc diff --git a/interpreter/llvm/src/lib/Support/Windows/explicit_symbols.inc b/interpreter/llvm-project/llvm/lib/Support/Windows/explicit_symbols.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/Windows/explicit_symbols.inc rename to interpreter/llvm-project/llvm/lib/Support/Windows/explicit_symbols.inc diff --git a/interpreter/llvm/src/lib/Support/WithColor.cpp b/interpreter/llvm-project/llvm/lib/Support/WithColor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/WithColor.cpp rename to interpreter/llvm-project/llvm/lib/Support/WithColor.cpp diff --git a/interpreter/llvm/src/lib/Support/X86TargetParser.cpp b/interpreter/llvm-project/llvm/lib/Support/X86TargetParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/X86TargetParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/X86TargetParser.cpp diff --git a/interpreter/llvm/src/lib/Support/YAMLParser.cpp b/interpreter/llvm-project/llvm/lib/Support/YAMLParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/YAMLParser.cpp rename to interpreter/llvm-project/llvm/lib/Support/YAMLParser.cpp diff --git a/interpreter/llvm/src/lib/Support/YAMLTraits.cpp b/interpreter/llvm-project/llvm/lib/Support/YAMLTraits.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/YAMLTraits.cpp rename to interpreter/llvm-project/llvm/lib/Support/YAMLTraits.cpp diff --git a/interpreter/llvm/src/lib/Support/Z3Solver.cpp b/interpreter/llvm-project/llvm/lib/Support/Z3Solver.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/Z3Solver.cpp rename to interpreter/llvm-project/llvm/lib/Support/Z3Solver.cpp diff --git a/interpreter/llvm/src/lib/Support/circular_raw_ostream.cpp b/interpreter/llvm-project/llvm/lib/Support/circular_raw_ostream.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/circular_raw_ostream.cpp rename to interpreter/llvm-project/llvm/lib/Support/circular_raw_ostream.cpp diff --git a/interpreter/llvm/src/lib/Support/raw_os_ostream.cpp b/interpreter/llvm-project/llvm/lib/Support/raw_os_ostream.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/raw_os_ostream.cpp rename to interpreter/llvm-project/llvm/lib/Support/raw_os_ostream.cpp diff --git a/interpreter/llvm/src/lib/Support/raw_ostream.cpp b/interpreter/llvm-project/llvm/lib/Support/raw_ostream.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/raw_ostream.cpp rename to interpreter/llvm-project/llvm/lib/Support/raw_ostream.cpp diff --git a/interpreter/llvm/src/lib/Support/regcomp.c b/interpreter/llvm-project/llvm/lib/Support/regcomp.c similarity index 100% rename from interpreter/llvm/src/lib/Support/regcomp.c rename to interpreter/llvm-project/llvm/lib/Support/regcomp.c diff --git a/interpreter/llvm/src/lib/Support/regengine.inc b/interpreter/llvm-project/llvm/lib/Support/regengine.inc similarity index 100% rename from interpreter/llvm/src/lib/Support/regengine.inc rename to interpreter/llvm-project/llvm/lib/Support/regengine.inc diff --git a/interpreter/llvm/src/lib/Support/regerror.c b/interpreter/llvm-project/llvm/lib/Support/regerror.c similarity index 100% rename from interpreter/llvm/src/lib/Support/regerror.c rename to interpreter/llvm-project/llvm/lib/Support/regerror.c diff --git a/interpreter/llvm/src/lib/Support/regex2.h b/interpreter/llvm-project/llvm/lib/Support/regex2.h similarity index 100% rename from interpreter/llvm/src/lib/Support/regex2.h rename to interpreter/llvm-project/llvm/lib/Support/regex2.h diff --git a/interpreter/llvm/src/lib/Support/regex_impl.h b/interpreter/llvm-project/llvm/lib/Support/regex_impl.h similarity index 100% rename from interpreter/llvm/src/lib/Support/regex_impl.h rename to interpreter/llvm-project/llvm/lib/Support/regex_impl.h diff --git a/interpreter/llvm/src/lib/Support/regexec.c b/interpreter/llvm-project/llvm/lib/Support/regexec.c similarity index 100% rename from interpreter/llvm/src/lib/Support/regexec.c rename to interpreter/llvm-project/llvm/lib/Support/regexec.c diff --git a/interpreter/llvm/src/lib/Support/regfree.c b/interpreter/llvm-project/llvm/lib/Support/regfree.c similarity index 100% rename from interpreter/llvm/src/lib/Support/regfree.c rename to interpreter/llvm-project/llvm/lib/Support/regfree.c diff --git a/interpreter/llvm/src/lib/Support/regstrlcpy.c b/interpreter/llvm-project/llvm/lib/Support/regstrlcpy.c similarity index 100% rename from interpreter/llvm/src/lib/Support/regstrlcpy.c rename to interpreter/llvm-project/llvm/lib/Support/regstrlcpy.c diff --git a/interpreter/llvm/src/lib/Support/regutils.h b/interpreter/llvm-project/llvm/lib/Support/regutils.h similarity index 100% rename from interpreter/llvm/src/lib/Support/regutils.h rename to interpreter/llvm-project/llvm/lib/Support/regutils.h diff --git a/interpreter/llvm/src/lib/Support/xxhash.cpp b/interpreter/llvm-project/llvm/lib/Support/xxhash.cpp similarity index 100% rename from interpreter/llvm/src/lib/Support/xxhash.cpp rename to interpreter/llvm-project/llvm/lib/Support/xxhash.cpp diff --git a/interpreter/llvm/src/lib/TableGen/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/TableGen/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/TableGen/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/TableGen/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/TableGen/DetailedRecordsBackend.cpp b/interpreter/llvm-project/llvm/lib/TableGen/DetailedRecordsBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/DetailedRecordsBackend.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/DetailedRecordsBackend.cpp diff --git a/interpreter/llvm/src/lib/TableGen/Error.cpp b/interpreter/llvm-project/llvm/lib/TableGen/Error.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/Error.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/Error.cpp diff --git a/interpreter/llvm/src/lib/TableGen/JSONBackend.cpp b/interpreter/llvm-project/llvm/lib/TableGen/JSONBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/JSONBackend.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/JSONBackend.cpp diff --git a/interpreter/llvm/src/lib/TableGen/Main.cpp b/interpreter/llvm-project/llvm/lib/TableGen/Main.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/Main.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/Main.cpp diff --git a/interpreter/llvm/src/lib/TableGen/Record.cpp b/interpreter/llvm-project/llvm/lib/TableGen/Record.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/Record.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/Record.cpp diff --git a/interpreter/llvm/src/lib/TableGen/SetTheory.cpp b/interpreter/llvm-project/llvm/lib/TableGen/SetTheory.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/SetTheory.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/SetTheory.cpp diff --git a/interpreter/llvm/src/lib/TableGen/StringMatcher.cpp b/interpreter/llvm-project/llvm/lib/TableGen/StringMatcher.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/StringMatcher.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/StringMatcher.cpp diff --git a/interpreter/llvm/src/lib/TableGen/TGLexer.cpp b/interpreter/llvm-project/llvm/lib/TableGen/TGLexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TGLexer.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/TGLexer.cpp diff --git a/interpreter/llvm/src/lib/TableGen/TGLexer.h b/interpreter/llvm-project/llvm/lib/TableGen/TGLexer.h similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TGLexer.h rename to interpreter/llvm-project/llvm/lib/TableGen/TGLexer.h diff --git a/interpreter/llvm/src/lib/TableGen/TGParser.cpp b/interpreter/llvm-project/llvm/lib/TableGen/TGParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TGParser.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/TGParser.cpp diff --git a/interpreter/llvm/src/lib/TableGen/TGParser.h b/interpreter/llvm-project/llvm/lib/TableGen/TGParser.h similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TGParser.h rename to interpreter/llvm-project/llvm/lib/TableGen/TGParser.h diff --git a/interpreter/llvm/src/lib/TableGen/TableGenBackend.cpp b/interpreter/llvm-project/llvm/lib/TableGen/TableGenBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TableGenBackend.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/TableGenBackend.cpp diff --git a/interpreter/llvm/src/lib/TableGen/TableGenBackendSkeleton.cpp b/interpreter/llvm-project/llvm/lib/TableGen/TableGenBackendSkeleton.cpp similarity index 100% rename from interpreter/llvm/src/lib/TableGen/TableGenBackendSkeleton.cpp rename to interpreter/llvm-project/llvm/lib/TableGen/TableGenBackendSkeleton.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64A53Fix835769.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64A53Fix835769.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64A53Fix835769.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64A53Fix835769.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64A57FPLoadBalancing.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64A57FPLoadBalancing.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64A57FPLoadBalancing.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64A57FPLoadBalancing.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64AdvSIMDScalarPass.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64AdvSIMDScalarPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64AdvSIMDScalarPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64AdvSIMDScalarPass.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64AsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64AsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64BranchTargets.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64BranchTargets.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64BranchTargets.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64BranchTargets.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CallingConvention.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CallingConvention.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CleanupLocalDynamicTLSPass.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CleanupLocalDynamicTLSPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CleanupLocalDynamicTLSPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CleanupLocalDynamicTLSPass.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CollectLOH.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CollectLOH.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CollectLOH.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CollectLOH.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64Combine.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Combine.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64Combine.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Combine.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CompressJumpTables.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CompressJumpTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CompressJumpTables.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CompressJumpTables.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64CondBrTuning.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CondBrTuning.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64CondBrTuning.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64CondBrTuning.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ConditionOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ConditionOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ConditionalCompares.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ConditionalCompares.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ConditionalCompares.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ConditionalCompares.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64DeadRegisterDefinitionsPass.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64DeadRegisterDefinitionsPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64DeadRegisterDefinitionsPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64DeadRegisterDefinitionsPass.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandImm.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandImm.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandImm.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandImm.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandImm.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandImm.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandImm.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandImm.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ExpandPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ExpandPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64FalkorHWPFFix.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FalkorHWPFFix.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64FalkorHWPFFix.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FalkorHWPFFix.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64FastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64FastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64GenRegisterBankInfo.def b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64GenRegisterBankInfo.def similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64GenRegisterBankInfo.def rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64GenRegisterBankInfo.def diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64ISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64ISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64ISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrAtomics.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrAtomics.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrAtomics.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrAtomics.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrGISel.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrGISel.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrGISel.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrGISel.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64LowerHomogeneousPrologEpilog.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64LowerHomogeneousPrologEpilog.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64LowerHomogeneousPrologEpilog.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64LowerHomogeneousPrologEpilog.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MacroFusion.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MacroFusion.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64MacroFusion.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MacroFusion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64MacroFusion.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64MacroFusion.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64PBQPRegAlloc.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PBQPRegAlloc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64PBQPRegAlloc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PBQPRegAlloc.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64PBQPRegAlloc.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PBQPRegAlloc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64PBQPRegAlloc.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PBQPRegAlloc.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64PerfectShuffle.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PerfectShuffle.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64PerfectShuffle.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PerfectShuffle.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64PfmCounters.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PfmCounters.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64PfmCounters.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PfmCounters.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64PromoteConstant.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PromoteConstant.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64PromoteConstant.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64PromoteConstant.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64RedundantCopyElimination.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RedundantCopyElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64RedundantCopyElimination.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RedundantCopyElimination.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64RegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64RegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SIMDInstrOpt.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SIMDInstrOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SIMDInstrOpt.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SIMDInstrOpt.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SLSHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SLSHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SLSHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SLSHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SMEInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SMEInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SVEInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SVEInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA53.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA53.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA53.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA53.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA55.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA55.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA55.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA55.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA57.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA57.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA57.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA57.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA57WriteRes.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA57WriteRes.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA57WriteRes.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA57WriteRes.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA64FX.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA64FX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedA64FX.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedA64FX.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedCyclone.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedCyclone.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedCyclone.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedCyclone.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM3.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM3.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM3.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM3.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM4.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM4.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM4.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM4.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM5.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM5.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedExynosM5.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedExynosM5.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedFalkor.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedFalkor.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedFalkor.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedFalkor.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedFalkorDetails.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedFalkorDetails.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedKryo.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedKryo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedKryo.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedKryo.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedKryoDetails.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedKryoDetails.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedKryoDetails.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedKryoDetails.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedPredExynos.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedPredExynos.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedPredExynos.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedPredExynos.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedPredicates.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedPredicates.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedPredicates.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedPredicates.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedTSV110.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedTSV110.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedTSV110.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedTSV110.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX2T99.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX2T99.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX2T99.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX2T99.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX3T110.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX3T110.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SchedThunderX3T110.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SchedThunderX3T110.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64Schedule.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Schedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64Schedule.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Schedule.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SpeculationHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SpeculationHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SpeculationHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SpeculationHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64StackTagging.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StackTagging.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64StackTagging.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StackTagging.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64StackTaggingPreRA.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StackTaggingPreRA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64StackTaggingPreRA.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StackTaggingPreRA.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64StorePairSuppress.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StorePairSuppress.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64StorePairSuppress.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64StorePairSuppress.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64Subtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Subtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64Subtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Subtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64Subtarget.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Subtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64Subtarget.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64Subtarget.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64SystemOperands.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SystemOperands.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64SystemOperands.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64SystemOperands.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AArch64TargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AArch64TargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AArch64/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64Disassembler.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64Disassembler.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64Disassembler.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64CallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64CallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64CallLowering.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64CallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64CallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64CallLowering.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64GlobalISelUtils.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64InstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64InstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64InstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64InstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64LegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64LegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64O0PreLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64O0PreLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64O0PreLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64O0PreLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostLegalizerLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostLegalizerLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostLegalizerLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostLegalizerLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostSelectOptimize.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostSelectOptimize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PostSelectOptimize.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PostSelectOptimize.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PreLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PreLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64PreLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64PreLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/AArch64RegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/select-saddo.mir b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/select-saddo.mir similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/select-saddo.mir rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/select-saddo.mir diff --git a/interpreter/llvm/src/lib/Target/AArch64/GISel/select-ssubo.mir b/interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/select-ssubo.mir similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/GISel/select-ssubo.mir rename to interpreter/llvm-project/llvm/lib/Target/AArch64/GISel/select-ssubo.mir diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64AddressingModes.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AddressingModes.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64AddressingModes.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AddressingModes.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64AsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64FixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64FixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64FixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64FixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MachObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MachObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64MachObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MachObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64TargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/AArch64WinCOFFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AArch64/SMEInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/SMEInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/SMEInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/SMEInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/SVEInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AArch64/SVEInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/SVEInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AArch64/SVEInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AArch64/SVEIntrinsicOpts.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/SVEIntrinsicOpts.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/AArch64TargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AArch64/Utils/AArch64BaseInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Utils/AArch64BaseInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AArch64/Utils/AArch64BaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Utils/AArch64BaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/AArch64/Utils/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AArch64/Utils/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AArch64/Utils/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPU.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPU.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPU.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPU.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPU.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPU.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPU.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPU.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAliasAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAliasAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAliasAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAliasAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAliasAnalysis.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAliasAnalysis.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAliasAnalysis.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAliasAnalysis.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAlwaysInlinePass.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAlwaysInlinePass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAlwaysInlinePass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAlwaysInlinePass.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAnnotateKernelFeatures.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAnnotateKernelFeatures.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAnnotateKernelFeatures.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAnnotateKernelFeatures.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAnnotateUniformValues.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAnnotateUniformValues.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAnnotateUniformValues.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAnnotateUniformValues.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAtomicOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAtomicOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAtomicOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAtomicOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAttributor.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAttributor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUAttributor.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAttributor.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCombine.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCombine.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUCombine.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCombine.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUExportClustering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUExportClustering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUExportClustering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUExportClustering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUExportClustering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUExportClustering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUExportClustering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUExportClustering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFeatures.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFeatures.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFeatures.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFeatures.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFixFunctionBitcasts.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFixFunctionBitcasts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFixFunctionBitcasts.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFixFunctionBitcasts.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGISel.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGISel.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGISel.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGISel.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGenRegisterBankInfo.def b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGenRegisterBankInfo.def similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGenRegisterBankInfo.def rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGenRegisterBankInfo.def diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUHSAMetadataStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructionSelector.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructionSelector.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULateCodeGenPrepare.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULateCodeGenPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULateCodeGenPrepare.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULateCodeGenPrepare.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibCalls.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibCalls.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibFunc.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibFunc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibFunc.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibFunc.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibFunc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULibFunc.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibFunc.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerIntrinsics.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerIntrinsics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerIntrinsics.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerIntrinsics.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerKernelArguments.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerKernelArguments.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerKernelArguments.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerKernelArguments.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerKernelAttributes.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerKernelAttributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerKernelAttributes.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerKernelAttributes.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMIRFormatter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMIRFormatter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMIRFormatter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMIRFormatter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMIRFormatter.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMIRFormatter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMIRFormatter.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMIRFormatter.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineFunction.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineFunction.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineFunction.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineFunction.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineFunction.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineFunction.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineFunction.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMacroFusion.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMacroFusion.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMacroFusion.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMacroFusion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUMacroFusion.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMacroFusion.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUOpenCLEnqueuedBlockLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUOpenCLEnqueuedBlockLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUOpenCLEnqueuedBlockLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUOpenCLEnqueuedBlockLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPTNote.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPTNote.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPTNote.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPTNote.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPerfHintAnalysis.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPostLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPostLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPostLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPostLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPreLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPreLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPreLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPreLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPropagateAttributes.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPropagateAttributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPropagateAttributes.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPropagateAttributes.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegBankCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegBankCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegBankCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegBankCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUReplaceLDSUseWithPointer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUReplaceLDSUseWithPointer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUReplaceLDSUseWithPointer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUReplaceLDSUseWithPointer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUResourceUsageAnalysis.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSearchableTables.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSearchableTables.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSearchableTables.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSearchableTables.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUUnifyDivergentExitNodes.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUUnifyDivergentExitNodes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUUnifyDivergentExitNodes.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUUnifyDivergentExitNodes.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUUnifyMetadata.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUUnifyMetadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUUnifyMetadata.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUUnifyMetadata.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDILCFGStructurizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDILCFGStructurizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDILCFGStructurizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDILCFGStructurizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AMDKernelCodeT.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDKernelCodeT.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AMDKernelCodeT.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AMDKernelCodeT.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/BUFInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/BUFInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/BUFInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/BUFInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/CaymanInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/CaymanInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/CaymanInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/CaymanInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/DSInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/DSInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/DSInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/DSInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/EXPInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/EXPInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/EXPInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/EXPInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/EvergreenInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/EvergreenInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/EvergreenInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/EvergreenInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/FLATInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/FLATInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/FLATInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/FLATInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNDPPCombine.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNDPPCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNDPPCombine.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNDPPCombine.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNHazardRecognizer.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNHazardRecognizer.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNILPSched.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNILPSched.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNILPSched.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNILPSched.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNIterativeScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNIterativeScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNIterativeScheduler.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNIterativeScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNMinRegStrategy.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNMinRegStrategy.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNMinRegStrategy.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNMinRegStrategy.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNNSAReassign.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNNSAReassign.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNNSAReassign.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNNSAReassign.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNPreRAOptimizations.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNPreRAOptimizations.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNPreRAOptimizations.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNPreRAOptimizations.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNProcessors.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNProcessors.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNProcessors.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNProcessors.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNRegPressure.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNRegPressure.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNRegPressure.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNRegPressure.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNRegPressure.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNRegPressure.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNSchedStrategy.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNSchedStrategy.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNSchedStrategy.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNSchedStrategy.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/GCNSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/GCNSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/GCNSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/InstCombineTables.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/InstCombineTables.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/InstCombineTables.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/InstCombineTables.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/R600MCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/R600MCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/R600MCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/R600MCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/R600MCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/R600MCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/R600MCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/R600MCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/SIMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/SIMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MCTargetDesc/SIMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MCTargetDesc/SIMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/MIMGInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/MIMGInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/MIMGInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/MIMGInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600AsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600AsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600AsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600AsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600AsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600AsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600AsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600AsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600ClauseMergePass.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ClauseMergePass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600ClauseMergePass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ClauseMergePass.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Defines.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Defines.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Defines.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Defines.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600EmitClauseMarkers.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600EmitClauseMarkers.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600EmitClauseMarkers.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600EmitClauseMarkers.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600ExpandSpecialInstrs.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ExpandSpecialInstrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600ExpandSpecialInstrs.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ExpandSpecialInstrs.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600ISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600ISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600ISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600ISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600ISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Instructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Instructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Instructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Instructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600MachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600MachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600MachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600MachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600MachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600MachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600MachineScheduler.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600MachineScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600MachineScheduler.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600OpenCLImageTypeLoweringPass.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600OptimizeVectorRegisters.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600OptimizeVectorRegisters.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600OptimizeVectorRegisters.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600OptimizeVectorRegisters.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Packetizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Packetizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Packetizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Packetizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Processors.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Processors.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Processors.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Processors.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600RegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600RegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Schedule.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Schedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Schedule.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Schedule.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R600Subtarget.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Subtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R600Subtarget.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R600Subtarget.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/R700Instructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/R700Instructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/R700Instructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/R700Instructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIDefines.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIDefines.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIDefines.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIDefines.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFixSGPRCopies.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFixSGPRCopies.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFixSGPRCopies.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFixSGPRCopies.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFixVGPRCopies.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFixVGPRCopies.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFixVGPRCopies.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFixVGPRCopies.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFoldOperands.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFoldOperands.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFormMemoryClauses.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFormMemoryClauses.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFormMemoryClauses.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFormMemoryClauses.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInsertHardClauses.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInsertHardClauses.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInsertHardClauses.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInsertHardClauses.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInsertWaitcnts.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInsertWaitcnts.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SILateBranchLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILateBranchLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SILateBranchLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILateBranchLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SILoadStoreOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILoadStoreOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SILoadStoreOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILoadStoreOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SILowerControlFlow.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SILowerControlFlow.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SILowerI1Copies.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerI1Copies.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SILowerI1Copies.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerI1Copies.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SILowerSGPRSpills.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerSGPRSpills.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SILowerSGPRSpills.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SILowerSGPRSpills.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIMachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIMachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIMachineScheduler.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIMachineScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMachineScheduler.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIMemoryLegalizer.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIMemoryLegalizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIModeRegister.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIModeRegister.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIModeRegister.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIModeRegister.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeVGPRLiveRange.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeVGPRLiveRange.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIOptimizeVGPRLiveRange.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeVGPRLiveRange.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIPeepholeSDWA.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPeepholeSDWA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIPeepholeSDWA.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPeepholeSDWA.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIPostRABundler.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPostRABundler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIPostRABundler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPostRABundler.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIPreAllocateWWMRegs.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPreAllocateWWMRegs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIPreAllocateWWMRegs.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPreAllocateWWMRegs.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIPreEmitPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPreEmitPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIPreEmitPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIPreEmitPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIProgramInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIProgramInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIProgramInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIProgramInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIProgramInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIProgramInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIProgramInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SISchedule.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SISchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SISchedule.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SISchedule.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIShrinkInstructions.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIShrinkInstructions.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIShrinkInstructions.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIShrinkInstructions.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SIWholeQuadMode.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIWholeQuadMode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SIWholeQuadMode.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SIWholeQuadMode.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SMInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SMInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SMInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SMInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/SOPInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/SOPInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/SOPInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/SOPInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/AMDGPUTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUAsmUtils.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPULDSUtils.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDGPUPALMetadata.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTInfo.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTInfo.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.cpp b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.cpp rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.cpp diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.h b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.h rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/AMDKernelCodeTUtils.h diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/Utils/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/Utils/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/Utils/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VIInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VIInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VIInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VIInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOP1Instructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP1Instructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOP1Instructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP1Instructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOP2Instructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP2Instructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOP2Instructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP2Instructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOP3Instructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP3Instructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOP3Instructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP3Instructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOP3PInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP3PInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOP3PInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOP3PInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOPCInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOPCInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOPCInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOPCInstructions.td diff --git a/interpreter/llvm/src/lib/Target/AMDGPU/VOPInstructions.td b/interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOPInstructions.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AMDGPU/VOPInstructions.td rename to interpreter/llvm-project/llvm/lib/Target/AMDGPU/VOPInstructions.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARC.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARC.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARC.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARC.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARC.td b/interpreter/llvm-project/llvm/lib/Target/ARC/ARC.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARC.td rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARC.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCBranchFinalize.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCBranchFinalize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCBranchFinalize.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCBranchFinalize.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCExpandPseudos.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCExpandPseudos.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCExpandPseudos.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCExpandPseudos.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCOptAddrMode.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCOptAddrMode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCOptAddrMode.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCOptAddrMode.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/ARC/ARCTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/ARCTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/ARCTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARC/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARC/Disassembler/ARCDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/Disassembler/ARCDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/Disassembler/ARCDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/Disassembler/ARCDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARC/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARC/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARC/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARC/TargetInfo/ARCTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/ARCTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/TargetInfo/ARCTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/ARCTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARC/TargetInfo/ARCTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/ARCTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/TargetInfo/ARCTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/ARCTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARC/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARC/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARC/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/A15SDOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/A15SDOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/A15SDOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/A15SDOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARM.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARM.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARM.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARM.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARM.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARM.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARM.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARM.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBaseInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBaseInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBaseInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBaseInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBaseRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBaseRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBaseRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBaseRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBaseRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBasicBlockInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBasicBlockInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBasicBlockInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBasicBlockInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBasicBlockInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBasicBlockInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBasicBlockInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBasicBlockInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMBlockPlacement.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMBlockPlacement.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMBlockPlacement.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMBlockPlacement.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMConstantIslandPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMConstantIslandPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMConstantPoolValue.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMConstantPoolValue.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMConstantPoolValue.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantPoolValue.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMConstantPoolValue.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMConstantPoolValue.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMExpandPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMExpandPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMFastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMFastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMFastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMFastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMFeatures.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMFeatures.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMFeatures.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMFeatures.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMHazardRecognizer.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMHazardRecognizer.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMHazardRecognizer.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrCDE.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrCDE.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrCDE.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrCDE.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrMVE.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrMVE.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrMVE.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrMVE.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrNEON.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrNEON.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrNEON.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrNEON.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrThumb.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrThumb.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrThumb.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrThumb.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrThumb2.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrThumb2.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrThumb2.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrThumb2.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstrVFP.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrVFP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstrVFP.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstrVFP.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMLegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMLegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMLegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMLoadStoreOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMLoadStoreOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMLowOverheadLoops.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMLowOverheadLoops.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMMacroFusion.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMMacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMMacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMMacroFusion.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMMacroFusion.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMMacroFusion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMMacroFusion.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMMacroFusion.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMOptimizeBarriersPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMOptimizeBarriersPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMParallelDSP.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMParallelDSP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMParallelDSP.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMParallelDSP.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMPerfectShuffle.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMPerfectShuffle.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMPerfectShuffle.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMPerfectShuffle.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMPredicates.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMPredicates.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMPredicates.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMPredicates.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSLSHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSLSHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSLSHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSLSHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSchedule.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSchedule.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleA57.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA57.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleA57.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA57.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleA57WriteRes.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA57WriteRes.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleA57WriteRes.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA57WriteRes.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleA8.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA8.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleA8.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA8.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleA9.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA9.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleA9.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleA9.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleM4.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleM4.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleM4.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleM4.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleM7.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleM7.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleM7.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleM7.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleR52.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleR52.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleR52.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleR52.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleSwift.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleSwift.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleSwift.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleSwift.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMScheduleV6.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleV6.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMScheduleV6.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMScheduleV6.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMSystemRegister.td b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMSystemRegister.td similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMSystemRegister.td rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMSystemRegister.td diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ARMTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ARMTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ARMTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/AsmParser/ARMAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/AsmParser/ARMAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/Disassembler/ARMDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Disassembler/ARMDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendDarwin.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendDarwin.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendDarwin.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendDarwin.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendELF.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendELF.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendELF.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendELF.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendWinCOFF.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendWinCOFF.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMAsmBackendWinCOFF.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackendWinCOFF.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMachORelocationInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMachORelocationInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMachORelocationInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMachORelocationInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMUnwindOpAsm.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMWinCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMWinCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMWinCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMWinCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMWinCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMWinCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/ARMWinCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/ARMWinCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/MLxExpansionPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MLxExpansionPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MLxExpansionPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MLxExpansionPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MVEGatherScatterLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVEGatherScatterLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MVELaneInterleavingPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVELaneInterleavingPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MVETPAndVPTOptimisationsPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MVETPAndVPTOptimisationsPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVETPAndVPTOptimisationsPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVETPAndVPTOptimisationsPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MVETailPredUtils.h b/interpreter/llvm-project/llvm/lib/Target/ARM/MVETailPredUtils.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVETailPredUtils.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVETailPredUtils.h diff --git a/interpreter/llvm/src/lib/Target/ARM/MVETailPredication.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MVETailPredication.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVETailPredication.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVETailPredication.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/MVEVPTBlockPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/MVEVPTBlockPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/MVEVPTBlockPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/MVEVPTBlockPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/README-Thumb.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/README-Thumb.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/README-Thumb.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/README-Thumb.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/README-Thumb2.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/README-Thumb2.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/README-Thumb2.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/README-Thumb2.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/README.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/README.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/README.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/TargetInfo/ARMTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/ARMTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/TargetInfo/ARMTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/ARMTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/TargetInfo/ARMTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/ARMTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/TargetInfo/ARMTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/ARMTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb1FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb1FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb1FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb1FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb1InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb1InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb1InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb1InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb1InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb2ITBlockPass.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2ITBlockPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb2ITBlockPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2ITBlockPass.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb2InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb2InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb2InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb2InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/Thumb2SizeReduction.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Thumb2SizeReduction.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ThumbRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/ThumbRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ThumbRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/ThumbRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/ThumbRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/ThumbRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/ThumbRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/ThumbRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/Utils/ARMBaseInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/ARM/Utils/ARMBaseInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Utils/ARMBaseInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/ARM/Utils/ARMBaseInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/ARM/Utils/ARMBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/ARM/Utils/ARMBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Utils/ARMBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/ARM/Utils/ARMBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/ARM/Utils/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/ARM/Utils/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/ARM/Utils/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/ARM/Utils/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AVR/AVR.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVR.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVR.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVR.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVR.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVR.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVR.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVR.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRDevices.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRDevices.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRDevices.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRDevices.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRExpandPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRExpandPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRExpandPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRExpandPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRRelaxMemOperations.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRRelaxMemOperations.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRRelaxMemOperations.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRRelaxMemOperations.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRShiftExpand.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRShiftExpand.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRShiftExpand.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRShiftExpand.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AVRTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AVRTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/AVRTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/AVR/AsmParser/AVRAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/AsmParser/AVRAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AsmParser/AVRAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/AsmParser/AVRAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AVR/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AVR/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AVR/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AVR/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AVR/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AVR/Disassembler/AVRDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/Disassembler/AVRDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/Disassembler/AVRDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/Disassembler/AVRDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AVR/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AVR/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AVR/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/AVR/README.md b/interpreter/llvm-project/llvm/lib/Target/AVR/README.md similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/README.md rename to interpreter/llvm-project/llvm/lib/Target/AVR/README.md diff --git a/interpreter/llvm/src/lib/Target/AVR/TODO.md b/interpreter/llvm-project/llvm/lib/Target/AVR/TODO.md similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/TODO.md rename to interpreter/llvm-project/llvm/lib/Target/AVR/TODO.md diff --git a/interpreter/llvm/src/lib/Target/AVR/TargetInfo/AVRTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/AVRTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/TargetInfo/AVRTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/AVRTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/AVR/TargetInfo/AVRTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/AVRTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/TargetInfo/AVRTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/AVRTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/AVR/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/AVR/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/AVR/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/BPF/AsmParser/BPFAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/AsmParser/BPFAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/AsmParser/BPFAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/AsmParser/BPFAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/BPF/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/BPF/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/BPF/BPF.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPF.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPF.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPF.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPF.td b/interpreter/llvm-project/llvm/lib/Target/BPF/BPF.td similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPF.td rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPF.td diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFAbstractMemberAccess.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFAbstractMemberAccess.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFAdjustOpt.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFAdjustOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFAdjustOpt.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFAdjustOpt.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFCORE.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFCORE.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFCORE.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFCORE.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFCheckAndAdjustIR.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFCheckAndAdjustIR.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFMIChecking.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFMIChecking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFMIChecking.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFMIChecking.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFMIPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFMIPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFMIPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFMIPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFMISimplifyPatchable.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFMISimplifyPatchable.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFPreserveDIType.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFPreserveDIType.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFPreserveDIType.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFPreserveDIType.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BPFTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BPFTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BPFTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BTF.def b/interpreter/llvm-project/llvm/lib/Target/BPF/BTF.def similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BTF.def rename to interpreter/llvm-project/llvm/lib/Target/BPF/BTF.def diff --git a/interpreter/llvm/src/lib/Target/BPF/BTF.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BTF.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BTF.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BTF.h diff --git a/interpreter/llvm/src/lib/Target/BPF/BTFDebug.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/BTFDebug.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BTFDebug.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/BTFDebug.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/BTFDebug.h b/interpreter/llvm-project/llvm/lib/Target/BPF/BTFDebug.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/BTFDebug.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/BTFDebug.h diff --git a/interpreter/llvm/src/lib/Target/BPF/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/BPF/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/BPF/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/BPF/Disassembler/BPFDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/Disassembler/BPFDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/Disassembler/BPFDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/Disassembler/BPFDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/BPF/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/BPF/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/BPF/TargetInfo/BPFTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/BPFTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/TargetInfo/BPFTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/BPFTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/BPF/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/BPF/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/BPF/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CSKY/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/CSKY/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/CSKY/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/CSKY/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKY.td b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKY.td similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKY.td rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKY.td diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKYInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKYInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKYInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKYInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKYRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKYRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKYTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKYTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/CSKYTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/CSKYTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/CSKYTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYAsmBackend.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/CSKY/TargetInfo/CSKYTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Hexagon/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/BitTracker.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/BitTracker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/BitTracker.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/BitTracker.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/BitTracker.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/BitTracker.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/BitTracker.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/BitTracker.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Hexagon/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Hexagon/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Hexagon/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Hexagon/Disassembler/HexagonDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/Disassembler/HexagonDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/Disassembler/HexagonDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/Disassembler/HexagonDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/Hexagon.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/Hexagon.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/Hexagon.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/Hexagon.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/Hexagon.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/Hexagon.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/Hexagon.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/Hexagon.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonArch.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonArch.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonArch.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonArch.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBitSimplify.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitSimplify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBitSimplify.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitSimplify.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBitTracker.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitTracker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBitTracker.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitTracker.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBitTracker.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitTracker.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBitTracker.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBitTracker.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBlockRanges.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBlockRanges.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBlockRanges.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBlockRanges.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBlockRanges.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBlockRanges.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBlockRanges.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBlockRanges.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonBranchRelaxation.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBranchRelaxation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonBranchRelaxation.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonBranchRelaxation.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonCFGOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCFGOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonCFGOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCFGOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonCommonGEP.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonCommonGEP.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonConstExtenders.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonConstExtenders.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonConstExtenders.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonConstExtenders.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonConstPropagation.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonConstPropagation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonConstPropagation.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonConstPropagation.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonCopyToCombine.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCopyToCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonCopyToCombine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonCopyToCombine.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepArch.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepArch.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepArch.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepArch.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepArch.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepArch.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepArch.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepArch.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepDecoders.inc b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepDecoders.inc similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepDecoders.inc rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepDecoders.inc diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepIICHVX.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepIICHVX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepIICHVX.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepIICHVX.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepIICScalar.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepIICScalar.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepIICScalar.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepIICScalar.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepITypes.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepITypes.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepITypes.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepITypes.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepITypes.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepITypes.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepITypes.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepITypes.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMapAsm2Intrin.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMapAsm2Intrin.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMapAsm2Intrin.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMapAsm2Intrin.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMappings.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMappings.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMappings.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMappings.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMask.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMask.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepMask.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepMask.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepOperands.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepOperands.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepOperands.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepOperands.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonDepTimingClasses.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepTimingClasses.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonDepTimingClasses.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonDepTimingClasses.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonEarlyIfConv.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonEarlyIfConv.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonEarlyIfConv.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonEarlyIfConv.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonExpandCondsets.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonExpandCondsets.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonExpandCondsets.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonExpandCondsets.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonFixupHwLoops.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFixupHwLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonFixupHwLoops.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFixupHwLoops.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonGenExtract.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenExtract.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonGenExtract.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenExtract.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonGenInsert.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenInsert.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonGenInsert.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenInsert.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonGenMux.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenMux.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonGenMux.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenMux.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonGenPredicate.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenPredicate.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonGenPredicate.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonGenPredicate.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonHardwareLoops.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHardwareLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonHardwareLoops.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHardwareLoops.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonHazardRecognizer.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonHazardRecognizer.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonHazardRecognizer.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonIICHVX.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIICHVX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonIICHVX.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIICHVX.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonIICScalar.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIICScalar.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonIICScalar.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIICScalar.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAGHVX.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAGHVX.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelDAGToDAGHVX.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelDAGToDAGHVX.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLoweringHVX.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLoweringHVX.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonISelLoweringHVX.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLoweringHVX.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormatsV60.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormatsV60.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormatsV60.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormatsV60.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormatsV65.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormatsV65.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrFormatsV65.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrFormatsV65.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsics.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsics.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsics.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsics.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsicsV5.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsicsV5.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsicsV5.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsicsV5.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsicsV60.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsicsV60.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonIntrinsicsV60.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonIntrinsicsV60.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonLoopIdiomRecognition.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonLoopIdiomRecognition.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineScheduler.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMachineScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMachineScheduler.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonMapAsm2IntrinV62.gen.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMapAsm2IntrinV62.gen.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonMapAsm2IntrinV62.gen.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonMapAsm2IntrinV62.gen.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonNewValueJump.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonNewValueJump.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonNewValueJump.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonNewValueJump.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonOperands.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOperands.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonOperands.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOperands.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonOptAddrMode.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOptAddrMode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonOptAddrMode.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOptAddrMode.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonOptimizeSZextends.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOptimizeSZextends.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonOptimizeSZextends.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonOptimizeSZextends.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonPatterns.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatterns.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonPatterns.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatterns.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonPatternsHVX.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatternsHVX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonPatternsHVX.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatternsHVX.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonPatternsV65.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatternsV65.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonPatternsV65.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPatternsV65.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonPseudo.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPseudo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonPseudo.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonPseudo.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonRDFOpt.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRDFOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonRDFOpt.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRDFOpt.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSchedule.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSchedule.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV5.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV5.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV5.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV5.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV55.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV55.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV55.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV55.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV60.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV60.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV60.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV60.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV62.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV62.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV62.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV62.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV65.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV65.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV65.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV65.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV66.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV66.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV66.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV66.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV67.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV67.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV67.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV67.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV67T.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV67T.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV67T.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV67T.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV68.td b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV68.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonScheduleV68.td rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonScheduleV68.td diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSplitConst32AndConst64.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSplitConst32AndConst64.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSplitConst32AndConst64.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSplitConst32AndConst64.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSplitDouble.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSplitDouble.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSplitDouble.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSplitDouble.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonStoreWidening.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonStoreWidening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonStoreWidening.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonStoreWidening.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVExtract.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVExtract.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVExtract.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVExtract.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVLIWPacketizer.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVLIWPacketizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVLIWPacketizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVLIWPacketizer.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVLIWPacketizer.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVLIWPacketizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVLIWPacketizer.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVLIWPacketizer.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorCombine.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorCombine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorLoopCarriedReuse.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorPrint.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorPrint.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/HexagonVectorPrint.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/HexagonVectorPrint.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCompound.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCompound.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCCompound.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCCompound.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCDuplexInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCDuplexInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCDuplexInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCDuplexInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCShuffler.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonShuffler.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/RDFCopy.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFCopy.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/RDFCopy.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFCopy.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/RDFCopy.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFCopy.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/RDFCopy.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFCopy.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/RDFDeadCode.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFDeadCode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/RDFDeadCode.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFDeadCode.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/RDFDeadCode.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFDeadCode.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/RDFDeadCode.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/RDFDeadCode.h diff --git a/interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Lanai/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Lanai/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Lanai/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Lanai/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Lanai/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Lanai/Disassembler/LanaiDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/LanaiDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/Disassembler/LanaiDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/LanaiDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/Disassembler/LanaiDisassembler.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/LanaiDisassembler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/Disassembler/LanaiDisassembler.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/Disassembler/LanaiDisassembler.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/Lanai.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/Lanai.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/Lanai.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/Lanai.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/Lanai.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/Lanai.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/Lanai.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/Lanai.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiAluCode.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiAluCode.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiAluCode.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiAluCode.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiCondCode.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiCondCode.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiCondCode.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiCondCode.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiDelaySlotFiller.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiDelaySlotFiller.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiDelaySlotFiller.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiDelaySlotFiller.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiMemAluCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMemAluCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiMemAluCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiMemAluCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiSchedule.td b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSchedule.td diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/LanaiTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/LanaiTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/LanaiTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/Lanai/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Lanai/TargetInfo/LanaiTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/M68k/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/M68k/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/M68k/AsmParser/M68kAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/AsmParser/M68kAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/AsmParser/M68kAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/AsmParser/M68kAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/M68k/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/M68k/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/M68k/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/M68k/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/M68k/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/M68k/Disassembler/M68kDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/Disassembler/M68kDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/Disassembler/M68kDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/Disassembler/M68kDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kLegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kLegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kLegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/GlSel/M68kRegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/GlSel/M68kRegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68k.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68k.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68k.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68k.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68k.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68k.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68k.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68k.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kCallingConv.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kCallingConv.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kCallingConv.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kCallingConv.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kCollapseMOVEMPass.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kCollapseMOVEMPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kCollapseMOVEMPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kCollapseMOVEMPass.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kExpandPseudo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kExpandPseudo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kExpandPseudo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kExpandPseudo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrArithmetic.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrArithmetic.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrArithmetic.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrArithmetic.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrBits.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrBits.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrBits.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrBits.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrBuilder.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrBuilder.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrBuilder.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrCompiler.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrCompiler.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrCompiler.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrCompiler.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrControl.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrControl.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrControl.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrControl.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrData.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrData.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrData.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrData.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kInstrShiftRotate.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrShiftRotate.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kInstrShiftRotate.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kInstrShiftRotate.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kMachineFunction.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kMachineFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kMachineFunction.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kMachineFunction.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kMachineFunction.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kMachineFunction.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kMachineFunction.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kMachineFunction.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kSchedule.td b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kSchedule.td diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/M68kTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/M68kTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/M68kTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/MCTargetDesc/M68kMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/M68k/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/M68k/TargetInfo/M68kTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/M68kTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/TargetInfo/M68kTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/M68kTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/M68k/TargetInfo/M68kTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/M68kTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/M68k/TargetInfo/M68kTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/M68k/TargetInfo/M68kTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/AsmParser/MSP430AsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/AsmParser/MSP430AsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/AsmParser/MSP430AsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/AsmParser/MSP430AsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/Disassembler/MSP430Disassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/Disassembler/MSP430Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/Disassembler/MSP430Disassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/Disassembler/MSP430Disassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430AsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430AsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430AsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430AsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430ELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430ELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430ELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430ELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430ELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430ELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430ELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430ELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430FixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430FixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430FixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430FixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430InstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430.td b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430.td similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430.td rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430.td diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430AsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430AsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430BranchSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430BranchSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430BranchSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430BranchSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430CallingConv.td b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430CallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430CallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430CallingConv.td diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430ISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430ISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430ISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430ISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430ISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430MCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430MCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430MCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430MCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430MachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430MachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430MachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430MachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430RegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430RegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430Subtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430Subtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430Subtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430Subtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430Subtarget.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430Subtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430Subtarget.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430Subtarget.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430TargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430TargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430TargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430TargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/MSP430TargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430TargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/MSP430TargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/MSP430TargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/MSP430/README.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/README.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/README.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/MSP430/TargetInfo/MSP430TargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/AsmParser/MipsAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/AsmParser/MipsAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/Disassembler/MipsDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Disassembler/MipsDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Disassembler/MipsDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Disassembler/MipsDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIFlagsSection.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsABIInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCNaCl.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCNaCl.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCNaCl.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCNaCl.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsNaClELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsNaClELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsNaClELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsNaClELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsOptionRecord.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsOptionRecord.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsOptionRecord.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsOptionRecord.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MSA.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/MSA.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MSA.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/MSA.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMips32r6InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMips32r6InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMips32r6InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMips32r6InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMips32r6InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMips32r6InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMips32r6InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMips32r6InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsDSPInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsDSPInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsDSPInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsDSPInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsDSPInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsDSPInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsDSPInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsDSPInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrFPU.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrFPU.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrFPU.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrFPU.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MicroMipsSizeReduction.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MicroMipsSizeReduction.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16HardFloat.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloat.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16HardFloat.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloat.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16HardFloatInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloatInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16HardFloatInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloatInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16HardFloatInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloatInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16HardFloatInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16HardFloatInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16ISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16ISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16ISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16ISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16ISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16ISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16ISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16ISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16ISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16RegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16RegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16RegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16RegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips16RegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips16RegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips16RegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips16RegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips32r6InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips32r6InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips32r6InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips32r6InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips32r6InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips32r6InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips32r6InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips32r6InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips64InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips64InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips64InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips64InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/Mips64r6InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/Mips64r6InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Mips64r6InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/Mips64r6InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsAnalyzeImmediate.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsAnalyzeImmediate.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsAnalyzeImmediate.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsAnalyzeImmediate.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsAnalyzeImmediate.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsAnalyzeImmediate.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsAnalyzeImmediate.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsAnalyzeImmediate.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsBranchExpansion.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsBranchExpansion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsBranchExpansion.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsBranchExpansion.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCCState.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCCState.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCCState.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCCState.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCCState.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCCState.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCCState.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCCState.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsCondMov.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsCondMov.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsCondMov.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsCondMov.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsConstantIslandPass.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsConstantIslandPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsDSPInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsDSPInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsDSPInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsDSPInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsDSPInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsDSPInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsDSPInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsDSPInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsDelaySlotFiller.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsDelaySlotFiller.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsEVAInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsEVAInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsEVAInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsEVAInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsEVAInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsEVAInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsEVAInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsEVAInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsExpandPseudo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsExpandPseudo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsExpandPseudo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsExpandPseudo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsFastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsFastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsFastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsFastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstrFPU.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrFPU.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstrFPU.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrFPU.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsLegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsLegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsLegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMSAInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMSAInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMSAInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMSAInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMSAInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMSAInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMSAInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMSAInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMTInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMTInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMTInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMTInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMTInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMTInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMTInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMTInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMachineFunction.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMachineFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMachineFunction.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMachineFunction.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsMachineFunction.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsMachineFunction.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsMachineFunction.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsMachineFunction.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsModuleISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsModuleISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsModuleISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsModuleISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsOptimizePICCall.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsOptimizePICCall.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsOptionRecord.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsOptionRecord.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsOptionRecord.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsOptionRecord.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsOs16.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsOs16.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsOs16.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsOs16.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsPfmCounters.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsPfmCounters.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsPfmCounters.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsPfmCounters.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsPreLegalizerCombiner.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsPreLegalizerCombiner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsPreLegalizerCombiner.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsPreLegalizerCombiner.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSEInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSEInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSEInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSERegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSERegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSERegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSERegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSERegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSERegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSERegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSERegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSchedule.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSchedule.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsScheduleGeneric.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsScheduleGeneric.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsScheduleGeneric.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsScheduleGeneric.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsScheduleP5600.td b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsScheduleP5600.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsScheduleP5600.td rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsScheduleP5600.td diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/Mips/MipsTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/MipsTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/MipsTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/Mips/Relocation.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/Relocation.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/Relocation.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/Relocation.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Mips/TargetInfo/MipsTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/MipsTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/TargetInfo/MipsTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/MipsTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Mips/TargetInfo/MipsTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/MipsTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Mips/TargetInfo/MipsTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Mips/TargetInfo/MipsTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/NVPTX/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/MCTargetDesc/NVPTXTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/ManagedStringPool.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/ManagedStringPool.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/ManagedStringPool.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/ManagedStringPool.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTX.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTX.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTX.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTX.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTX.td b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTX.td rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTX.td diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAllocaHoisting.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAllocaHoisting.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAllocaHoisting.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAllocaHoisting.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAllocaHoisting.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAllocaHoisting.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAllocaHoisting.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAllocaHoisting.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAssignValidGlobalNames.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAssignValidGlobalNames.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAssignValidGlobalNames.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAssignValidGlobalNames.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAtomicLower.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAtomicLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAtomicLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAtomicLower.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXAtomicLower.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAtomicLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXAtomicLower.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXAtomicLower.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXGenericToNVVM.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXGenericToNVVM.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXGenericToNVVM.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXGenericToNVVM.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXImageOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXImageOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXImageOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXImageOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXIntrinsics.td b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXIntrinsics.td similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXIntrinsics.td rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXIntrinsics.td diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAggrCopies.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAggrCopies.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAggrCopies.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAggrCopies.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAggrCopies.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAggrCopies.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAggrCopies.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAggrCopies.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAlloca.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAlloca.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerAlloca.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerAlloca.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerArgs.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerArgs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXLowerArgs.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXLowerArgs.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXProxyRegErasure.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXProxyRegErasure.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXProxyRegErasure.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXProxyRegErasure.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXUtilities.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXUtilities.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXUtilities.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXUtilities.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVPTXUtilities.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXUtilities.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVPTXUtilities.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVPTXUtilities.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVVMIntrRange.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVVMIntrRange.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVVMIntrRange.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVVMIntrRange.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/NVVMReflect.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/NVVMReflect.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/NVVMReflect.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/NVVMReflect.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/NVPTX/cl_common_defines.h b/interpreter/llvm-project/llvm/lib/Target/NVPTX/cl_common_defines.h similarity index 100% rename from interpreter/llvm/src/lib/Target/NVPTX/cl_common_defines.h rename to interpreter/llvm-project/llvm/lib/Target/NVPTX/cl_common_defines.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCLegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCLegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCLegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/GISel/PPCRegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/GISel/PPCRegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCPredicates.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/MCTargetDesc/PPCXCOFFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/P9InstrResources.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/P9InstrResources.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/P9InstrResources.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/P9InstrResources.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPC.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPC.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPC.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPC.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPC.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPC.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPC.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPC.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCBoolRetToInt.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCBoolRetToInt.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCBranchCoalescing.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBranchCoalescing.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCBranchCoalescing.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBranchCoalescing.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCBranchSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBranchSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCBranchSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCBranchSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCCState.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCCState.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCCState.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCCState.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCCState.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCCState.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCCState.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCCState.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCTRLoops.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCTRLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCTRLoops.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCTRLoops.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCEarlyReturn.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCEarlyReturn.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCEarlyReturn.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCEarlyReturn.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCExpandAtomicPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCExpandAtomicPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCExpandAtomicPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCExpandAtomicPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCExpandISEL.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCExpandISEL.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCExpandISEL.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCExpandISEL.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCFastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCFastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCHazardRecognizers.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCHazardRecognizers.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCHazardRecognizers.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCHazardRecognizers.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCHazardRecognizers.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCHazardRecognizers.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstr64Bit.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstr64Bit.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstr64Bit.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstr64Bit.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrAltivec.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrAltivec.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrAltivec.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrAltivec.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrBuilder.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrBuilder.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrBuilder.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrHTM.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrHTM.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrHTM.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrHTM.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrPrefix.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrPrefix.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrPrefix.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrPrefix.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrSPE.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrSPE.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrSPE.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrSPE.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCInstrVSX.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrVSX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCInstrVSX.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCInstrVSX.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCLowerMASSVEntries.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMIPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMIPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMachineScheduler.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMachineScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMachineScheduler.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.def b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.def similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.def rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.def diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCMacroFusion.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCMacroFusion.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCPerfectShuffle.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPerfectShuffle.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCPerfectShuffle.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPerfectShuffle.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCPfmCounters.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPfmCounters.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCPfmCounters.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPfmCounters.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCPreEmitPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPreEmitPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCPreEmitPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCPreEmitPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCReduceCRLogicals.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCReduceCRLogicals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCReduceCRLogicals.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCReduceCRLogicals.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCSchedule.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSchedule.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCSchedule440.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSchedule440.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCSchedule440.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSchedule440.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleA2.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleA2.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleA2.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleA2.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE500.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE500.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE500.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE500.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE500mc.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE500mc.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE500mc.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE500mc.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE5500.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE5500.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleE5500.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleE5500.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG3.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG3.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG3.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG3.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG4.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG4.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG4.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG4.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG4Plus.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG4Plus.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG4Plus.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG4Plus.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG5.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG5.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleG5.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleG5.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP7.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP7.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP7.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP7.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP8.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP8.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP8.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP8.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP9.td b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP9.td similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCScheduleP9.td rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCScheduleP9.td diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTLSDynamicCall.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTLSDynamicCall.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTOCRegDeps.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTOCRegDeps.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTOCRegDeps.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTOCRegDeps.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCVSXCopy.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXCopy.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCVSXCopy.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXCopy.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCVSXFMAMutate.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXFMAMutate.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCVSXFMAMutate.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXFMAMutate.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/PPCVSXSwapRemoval.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXSwapRemoval.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/PPCVSXSwapRemoval.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/PPCVSXSwapRemoval.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/README.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/README.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/README.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/README_ALTIVEC.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/README_ALTIVEC.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/README_ALTIVEC.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/README_ALTIVEC.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/README_P9.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/README_P9.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/README_P9.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/README_P9.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/README.txt b/interpreter/llvm-project/llvm/lib/Target/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/README.txt rename to interpreter/llvm-project/llvm/lib/Target/README.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/RISCV/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/RISCV/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/RISCV/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/RISCV/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/RISCV/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/RISCV/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCV.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCV.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCV.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCV.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCV.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCV.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCV.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCV.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVCallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVCallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVCallLowering.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVCallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallLowering.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVExpandAtomicPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVExpandAtomicPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVExpandAtomicPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVExpandAtomicPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVExpandPseudoInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVExpandPseudoInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVExpandPseudoInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVExpandPseudoInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVISelDAGToDAG.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVISelDAGToDAG.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInsertVSETVLI.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInsertVSETVLI.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInsertVSETVLI.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInsertVSETVLI.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormatsC.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormatsC.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormatsC.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormatsC.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormatsV.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormatsV.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrFormatsV.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrFormatsV.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoA.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoA.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoA.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoA.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoB.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoB.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoB.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoB.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoC.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoC.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoC.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoC.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoD.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoD.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoD.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoD.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoF.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoF.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoF.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoF.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoM.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoM.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoM.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoM.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoV.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoV.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoV.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoV.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVPseudos.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVPseudos.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoZfh.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoZfh.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstrInfoZfh.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstrInfoZfh.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVInstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVInstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVInstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVLegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVLegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVLegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVLegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVLegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVLegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVLegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVLegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVMergeBaseOffset.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMergeBaseOffset.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVMergeBaseOffset.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVMergeBaseOffset.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSchedRocket.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedRocket.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSchedRocket.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedRocket.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSchedSiFive7.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedSiFive7.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSchedSiFive7.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedSiFive7.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSchedule.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSchedule.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVScheduleB.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVScheduleB.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVScheduleB.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVScheduleB.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVScheduleV.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVScheduleV.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVScheduleV.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVScheduleV.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVSystemOperands.td b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSystemOperands.td similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVSystemOperands.td rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVSystemOperands.td diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/RISCVTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/RISCVTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/RISCV/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/RISCV/TargetInfo/RISCVTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/DelaySlotFiller.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/DelaySlotFiller.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/DelaySlotFiller.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/DelaySlotFiller.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/Disassembler/SparcDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/Disassembler/SparcDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/Disassembler/SparcDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/Disassembler/SparcDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/LeonFeatures.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/LeonFeatures.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/LeonFeatures.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/LeonFeatures.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/LeonPasses.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/LeonPasses.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/LeonPasses.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/LeonPasses.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/LeonPasses.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/LeonPasses.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/LeonPasses.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/LeonPasses.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/MCTargetDesc/SparcTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/README.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/README.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/README.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/Sparc.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/Sparc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/Sparc.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/Sparc.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/Sparc.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/Sparc.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/Sparc.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/Sparc.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstr64Bit.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstr64Bit.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstr64Bit.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstr64Bit.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrAliases.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrAliases.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrAliases.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrAliases.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcInstrVIS.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrVIS.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcInstrVIS.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcInstrVIS.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcSchedule.td b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSchedule.td diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/SparcTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/SparcTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/SparcTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/Sparc/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/Sparc/TargetInfo/SparcTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/SparcTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/TargetInfo/SparcTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/SparcTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/Sparc/TargetInfo/SparcTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/SparcTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/Sparc/TargetInfo/SparcTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/Sparc/TargetInfo/SparcTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCFixups.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCFixups.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCFixups.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCFixups.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/README.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/README.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/README.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZ.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZ.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZ.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZ.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZ.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZ.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZ.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZ.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZConstantPoolValue.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZConstantPoolValue.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZConstantPoolValue.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZConstantPoolValue.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZConstantPoolValue.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZConstantPoolValue.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZConstantPoolValue.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZConstantPoolValue.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZCopyPhysRegs.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCopyPhysRegs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZCopyPhysRegs.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZCopyPhysRegs.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZElimCompare.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZElimCompare.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZElimCompare.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZElimCompare.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZFeatures.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFeatures.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZFeatures.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFeatures.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZHazardRecognizer.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZHazardRecognizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZHazardRecognizer.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZHazardRecognizer.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZHazardRecognizer.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZHazardRecognizer.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrBuilder.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrBuilder.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrBuilder.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrDFP.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrDFP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrDFP.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrDFP.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrFP.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrFP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrFP.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrFP.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrHFP.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrHFP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrHFP.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrHFP.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrSystem.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrSystem.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrSystem.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrSystem.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrVector.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrVector.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZInstrVector.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZInstrVector.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZLDCleanup.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZLDCleanup.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZLDCleanup.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZLDCleanup.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZLongBranch.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZLongBranch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZLongBranch.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZLongBranch.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineScheduler.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineScheduler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineScheduler.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineScheduler.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineScheduler.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineScheduler.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZMachineScheduler.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZMachineScheduler.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZOperands.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZOperands.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZOperands.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZOperands.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZOperators.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZOperators.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZOperators.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZOperators.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZPatterns.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZPatterns.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZPatterns.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZPatterns.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZPostRewrite.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZPostRewrite.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZPostRewrite.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZPostRewrite.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZProcessors.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZProcessors.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZProcessors.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZProcessors.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZSchedule.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSchedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZSchedule.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSchedule.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ13.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ13.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ14.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ14.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ14.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ14.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ15.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ15.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ15.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ15.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ196.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZ196.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZEC12.td b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZScheduleZEC12.td rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZShortenInst.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZShortenInst.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZShortenInst.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZShortenInst.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZTDC.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTDC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZTDC.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTDC.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/SystemZTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/SystemZ/TargetInfo/SystemZTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/Target.cpp b/interpreter/llvm-project/llvm/lib/Target/Target.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/Target.cpp rename to interpreter/llvm-project/llvm/lib/Target/Target.cpp diff --git a/interpreter/llvm/src/lib/Target/TargetIntrinsicInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/TargetIntrinsicInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/TargetIntrinsicInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/TargetIntrinsicInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/TargetLoweringObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/TargetLoweringObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/TargetLoweringObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/TargetLoweringObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/TargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/TargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/TargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/TargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/TargetMachineC.cpp b/interpreter/llvm-project/llvm/lib/Target/TargetMachineC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/TargetMachineC.cpp rename to interpreter/llvm-project/llvm/lib/Target/TargetMachineC.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/VE/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/VE/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/VE/AsmParser/VEAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/AsmParser/VEAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/AsmParser/VEAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/AsmParser/VEAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/VE/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/VE/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/VE/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/VE/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/VE/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/VE/Disassembler/VEDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/Disassembler/VEDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/Disassembler/VEDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/Disassembler/VEDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/LVLGen.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/LVLGen.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/LVLGen.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/LVLGen.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCExpr.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCExpr.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCExpr.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCExpr.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCExpr.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCExpr.h diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VEMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VETargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VETargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VETargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VETargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VETargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VETargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/MCTargetDesc/VETargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/VE/MCTargetDesc/VETargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/VE/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/VE/TargetInfo/VETargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/VETargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/TargetInfo/VETargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/VETargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/TargetInfo/VETargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/VETargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/TargetInfo/VETargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/TargetInfo/VETargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/VE.h b/interpreter/llvm-project/llvm/lib/Target/VE/VE.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VE.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VE.h diff --git a/interpreter/llvm/src/lib/Target/VE/VE.td b/interpreter/llvm-project/llvm/lib/Target/VE/VE.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VE.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VE.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VECallingConv.td b/interpreter/llvm-project/llvm/lib/Target/VE/VECallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VECallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VECallingConv.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/VE/VEFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VEFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/VE/VEISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/VE/VEISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VEISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrBuilder.h b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrBuilder.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrBuilder.h diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrIntrinsicVL.gen.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrIntrinsicVL.gen.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrIntrinsicVL.gen.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrIntrinsicVL.gen.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrIntrinsicVL.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrIntrinsicVL.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrIntrinsicVL.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrIntrinsicVL.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrPatternsVec.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrPatternsVec.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrPatternsVec.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrPatternsVec.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEInstrVec.td b/interpreter/llvm-project/llvm/lib/Target/VE/VEInstrVec.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEInstrVec.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VEInstrVec.td diff --git a/interpreter/llvm/src/lib/Target/VE/VEMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VEMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VEMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VEMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/VEMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VEMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VEMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/VERegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VERegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VERegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VERegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/VERegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VERegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VERegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/VE/VESubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VESubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VESubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VESubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VESubtarget.h b/interpreter/llvm-project/llvm/lib/Target/VE/VESubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VESubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VESubtarget.h diff --git a/interpreter/llvm/src/lib/Target/VE/VETargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/VE/VETargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VETargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/VE/VETargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/VE/VETargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/VE/VETargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VETargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VETargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/VE/VETargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/VE/VETargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VETargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/VE/VETargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/VE/VVPInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/VE/VVPInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VVPInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VVPInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/VE/VVPInstrPatternsVec.td b/interpreter/llvm-project/llvm/lib/Target/VE/VVPInstrPatternsVec.td similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VVPInstrPatternsVec.td rename to interpreter/llvm-project/llvm/lib/Target/VE/VVPInstrPatternsVec.td diff --git a/interpreter/llvm/src/lib/Target/VE/VVPNodes.def b/interpreter/llvm-project/llvm/lib/Target/VE/VVPNodes.def similarity index 100% rename from interpreter/llvm/src/lib/Target/VE/VVPNodes.def rename to interpreter/llvm-project/llvm/lib/Target/VE/VVPNodes.def diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Disassembler/WebAssemblyDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Disassembler/WebAssemblyDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Disassembler/WebAssemblyDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Disassembler/WebAssemblyDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyFixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyFixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyFixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyFixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/README.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/README.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/README.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/TargetInfo/WebAssemblyTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Utils/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Utils/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssembly.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssembly.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssembly.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssembly.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssembly.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssembly.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssembly.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssembly.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAddMissingPrototypes.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAddMissingPrototypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAddMissingPrototypes.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAddMissingPrototypes.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyArgumentMove.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyArgumentMove.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyArgumentMove.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyArgumentMove.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyCFGSort.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGSort.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyCFGSort.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGSort.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyCFGStackify.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugValueManager.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugValueManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugValueManager.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugValueManager.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugValueManager.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugValueManager.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyDebugValueManager.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyDebugValueManager.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExceptionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExceptionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExceptionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExceptionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExceptionInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExceptionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExceptionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExceptionInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExplicitLocals.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExplicitLocals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyExplicitLocals.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyExplicitLocals.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISD.def b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISD.def similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISD.def rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISD.def diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrAtomics.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrAtomics.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrAtomics.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrAtomics.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrBulkMemory.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrBulkMemory.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrBulkMemory.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrBulkMemory.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrCall.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrCall.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrControl.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrControl.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrControl.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrControl.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrConv.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrConv.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrConv.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrFloat.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrFloat.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrFloat.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrFloat.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInteger.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInteger.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrInteger.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrInteger.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrMemory.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrMemory.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrMemory.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrMemory.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrRef.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrRef.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrRef.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrRef.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrTable.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyInstrTable.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLateEHPrepare.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLateEHPrepare.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLateEHPrepare.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLateEHPrepare.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerBrUnless.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerBrUnless.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerBrUnless.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerBrUnless.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerGlobalDtors.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerGlobalDtors.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyLowerGlobalDtors.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyLowerGlobalDtors.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCLowerPrePass.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCLowerPrePass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMCLowerPrePass.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMCLowerPrePass.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMemIntrinsicResults.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMemIntrinsicResults.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyMemIntrinsicResults.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyMemIntrinsicResults.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyNullifyDebugValueLists.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyNullifyDebugValueLists.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyNullifyDebugValueLists.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyNullifyDebugValueLists.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyOptimizeLiveIntervals.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyOptimizeLiveIntervals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyOptimizeLiveIntervals.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyOptimizeLiveIntervals.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyOptimizeReturned.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyOptimizeReturned.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyOptimizeReturned.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyOptimizeReturned.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyPeephole.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyPeephole.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyPeephole.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyPeephole.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyPrepareForLiveIntervals.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyPrepareForLiveIntervals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyPrepareForLiveIntervals.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyPrepareForLiveIntervals.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegColoring.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegColoring.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegColoring.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegColoring.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegNumbering.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegNumbering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegNumbering.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegNumbering.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyReplacePhysRegs.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyReplacePhysRegs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyReplacePhysRegs.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyReplacePhysRegs.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRuntimeLibcallSignatures.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySetP2AlignOperands.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySetP2AlignOperands.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySetP2AlignOperands.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySetP2AlignOperands.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySortRegion.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySortRegion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySortRegion.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySortRegion.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySortRegion.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySortRegion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySortRegion.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySortRegion.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySubtarget.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblySubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/AsmParser/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/AsmParser/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/X86/AsmParser/X86AsmParser.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/AsmParser/X86AsmParser.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/AsmParser/X86AsmParserCommon.h b/interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86AsmParserCommon.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/AsmParser/X86AsmParserCommon.h rename to interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86AsmParserCommon.h diff --git a/interpreter/llvm/src/lib/Target/X86/AsmParser/X86Operand.h b/interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86Operand.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/AsmParser/X86Operand.h rename to interpreter/llvm-project/llvm/lib/Target/X86/AsmParser/X86Operand.h diff --git a/interpreter/llvm/src/lib/Target/X86/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/X86/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/X86/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/X86/Disassembler/X86Disassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/Disassembler/X86Disassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/Disassembler/X86DisassemblerDecoder.h b/interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/Disassembler/X86DisassemblerDecoder.h rename to interpreter/llvm-project/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.h diff --git a/interpreter/llvm/src/lib/Target/X86/ImmutableGraph.h b/interpreter/llvm-project/llvm/lib/Target/X86/ImmutableGraph.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/ImmutableGraph.h rename to interpreter/llvm-project/llvm/lib/Target/X86/ImmutableGraph.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ATTInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86BaseInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86BaseInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86FixupKinds.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86FixupKinds.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86FixupKinds.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86FixupKinds.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstComments.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstComments.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstComments.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstComments.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstComments.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstComments.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstComments.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstComments.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86InstPrinterCommon.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86IntelInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp similarity index 99% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp index 714d2d839054d..c66ae29c7ae11 100644 --- a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp +++ b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp @@ -703,6 +703,13 @@ bool X86MCCodeEmitter::emitPrefixImpl(unsigned &CurOp, const MCInst &MI, HasREX = emitOpcodePrefix(MemoryOperand, MI, STI, OS); uint64_t Form = TSFlags & X86II::FormMask; + // FIXME (bellenot): Visual Studio v17.6.0 makes root.exe crash + // at the switch statement with Form being 0x002 or 0x001, values + // normally going to the 'default' switch branch, so the behavior + // doesn't change. + // To be reviewed and removed as soon as VS works again + if (Form <= 0x002) + return HasREX; switch (Form) { default: break; diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCExpr.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCExpr.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCExpr.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCExpr.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86ShuffleDecode.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86TargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86TargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86TargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86TargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFObjectWriter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFObjectWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFObjectWriter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFObjectWriter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFTargetStreamer.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFTargetStreamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/MCTargetDesc/X86WinCOFFTargetStreamer.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86WinCOFFTargetStreamer.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/README-FPStack.txt b/interpreter/llvm-project/llvm/lib/Target/X86/README-FPStack.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/README-FPStack.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/README-FPStack.txt diff --git a/interpreter/llvm/src/lib/Target/X86/README-SSE.txt b/interpreter/llvm-project/llvm/lib/Target/X86/README-SSE.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/README-SSE.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/README-SSE.txt diff --git a/interpreter/llvm/src/lib/Target/X86/README-X86-64.txt b/interpreter/llvm-project/llvm/lib/Target/X86/README-X86-64.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/README-X86-64.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/README-X86-64.txt diff --git a/interpreter/llvm/src/lib/Target/X86/README.txt b/interpreter/llvm-project/llvm/lib/Target/X86/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/README.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/README.txt diff --git a/interpreter/llvm/src/lib/Target/X86/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/X86/TargetInfo/X86TargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/X86TargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/TargetInfo/X86TargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/X86TargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/TargetInfo/X86TargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/X86TargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/TargetInfo/X86TargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/TargetInfo/X86TargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86AsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86AsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86AsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86AsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86AsmPrinter.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86AsmPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86AsmPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86AsmPrinter.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86AvoidStoreForwardingBlocks.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86AvoidStoreForwardingBlocks.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86AvoidStoreForwardingBlocks.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86AvoidStoreForwardingBlocks.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86AvoidTrailingCall.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86AvoidTrailingCall.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86AvoidTrailingCall.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86AvoidTrailingCall.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallFrameOptimization.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallFrameOptimization.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallFrameOptimization.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallFrameOptimization.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallLowering.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallLowering.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallLowering.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallingConv.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallingConv.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallingConv.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallingConv.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86CallingConv.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CallingConv.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86CmovConversion.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86CmovConversion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86CmovConversion.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86CmovConversion.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86DiscriminateMemOps.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86DiscriminateMemOps.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86DiscriminateMemOps.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86DiscriminateMemOps.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86DomainReassignment.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86DomainReassignment.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86DomainReassignment.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86DomainReassignment.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86EvexToVex.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86EvexToVex.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86EvexToVex.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86EvexToVex.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86ExpandPseudo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86ExpandPseudo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ExpandPseudo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ExpandPseudo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FastISel.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FastISel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FastISel.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FastISel.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FastTileConfig.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FastTileConfig.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FastTileConfig.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FastTileConfig.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FixupBWInsts.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FixupBWInsts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FixupBWInsts.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FixupBWInsts.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FixupLEAs.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FixupLEAs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FixupLEAs.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FixupLEAs.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FixupSetCC.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FixupSetCC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FixupSetCC.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FixupSetCC.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FlagsCopyLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FlagsCopyLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FloatingPoint.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FloatingPoint.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FloatingPoint.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FloatingPoint.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86FrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86FrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86FrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86FrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86GenRegisterBankInfo.def b/interpreter/llvm-project/llvm/lib/Target/X86/X86GenRegisterBankInfo.def similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86GenRegisterBankInfo.def rename to interpreter/llvm-project/llvm/lib/Target/X86/X86GenRegisterBankInfo.def diff --git a/interpreter/llvm/src/lib/Target/X86/X86ISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86ISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86ISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86ISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86ISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86IndirectBranchTracking.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86IndirectBranchTracking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86IndirectBranchTracking.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86IndirectBranchTracking.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86IndirectThunks.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86IndirectThunks.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86IndirectThunks.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86IndirectThunks.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InsertPrefetch.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InsertPrefetch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InsertPrefetch.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InsertPrefetch.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InsertWait.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InsertWait.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InsertWait.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InsertWait.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstCombineIntrinsic.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstCombineIntrinsic.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86Instr3DNow.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86Instr3DNow.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86Instr3DNow.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86Instr3DNow.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrAMX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrAMX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrAMX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrAMX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrAVX512.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrAVX512.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrAVX512.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrAVX512.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrArithmetic.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrArithmetic.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrArithmetic.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrArithmetic.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrBuilder.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrBuilder.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrBuilder.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrCMovSetCC.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrCMovSetCC.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrCMovSetCC.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrCMovSetCC.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrCompiler.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrCompiler.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrCompiler.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrCompiler.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrControl.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrControl.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrControl.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrControl.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrExtension.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrExtension.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrExtension.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrExtension.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFMA.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFMA.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFMA3Info.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA3Info.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFMA3Info.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA3Info.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFMA3Info.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA3Info.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFMA3Info.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFMA3Info.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFPStack.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFPStack.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFPStack.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFPStack.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFoldTables.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFoldTables.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFoldTables.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFoldTables.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFoldTables.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFoldTables.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFoldTables.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFoldTables.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrFragmentsSIMD.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFragmentsSIMD.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrFragmentsSIMD.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrFragmentsSIMD.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrKL.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrKL.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrKL.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrKL.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrMMX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrMMX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrMMX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrMMX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrMPX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrMPX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrMPX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrMPX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrSGX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSGX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrSGX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSGX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrSNP.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSNP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrSNP.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSNP.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrSSE.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSSE.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrSSE.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSSE.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrSVM.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSVM.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrSVM.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSVM.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrShiftRotate.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrShiftRotate.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrShiftRotate.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrShiftRotate.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrSystem.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSystem.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrSystem.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrSystem.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrTDX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrTDX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrTDX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrTDX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrTSX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrTSX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrTSX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrTSX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrVMX.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrVMX.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrVMX.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrVMX.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrVecCompiler.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrVecCompiler.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrVecCompiler.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrVecCompiler.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstrXOP.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstrXOP.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstrXOP.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstrXOP.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86InstructionSelector.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InstructionSelector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InstructionSelector.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InstructionSelector.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86InterleavedAccess.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86InterleavedAccess.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86InterleavedAccess.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86InterleavedAccess.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86IntrinsicsInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86IntrinsicsInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86IntrinsicsInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86IntrinsicsInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86LegalizerInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LegalizerInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LegalizerInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LegalizerInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86LegalizerInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86LegalizerInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LegalizerInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LegalizerInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86LoadValueInjectionLoadHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LoadValueInjectionLoadHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LoadValueInjectionLoadHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LoadValueInjectionLoadHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86LoadValueInjectionRetHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LoadValueInjectionRetHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LoadValueInjectionRetHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LoadValueInjectionRetHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86LowerAMXIntrinsics.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LowerAMXIntrinsics.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86LowerAMXType.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LowerAMXType.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LowerAMXType.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LowerAMXType.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86LowerTileCopy.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86LowerTileCopy.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86LowerTileCopy.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86LowerTileCopy.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86MCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86MCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86MCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86MCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86MachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86MachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86MachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86MachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86MachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86MachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86MachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86MachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86MacroFusion.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86MacroFusion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86MacroFusion.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86MacroFusion.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86MacroFusion.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86MacroFusion.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86MacroFusion.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86MacroFusion.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86OptimizeLEAs.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86OptimizeLEAs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86OptimizeLEAs.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86OptimizeLEAs.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86PadShortFunction.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86PadShortFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86PadShortFunction.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86PadShortFunction.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86PartialReduction.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86PartialReduction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86PartialReduction.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86PartialReduction.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86PfmCounters.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86PfmCounters.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86PfmCounters.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86PfmCounters.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86PreAMXConfig.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86PreAMXConfig.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86PreAMXConfig.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86PreAMXConfig.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86PreTileConfig.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86PreTileConfig.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86PreTileConfig.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86PreTileConfig.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterBankInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBankInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterBankInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBankInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterBankInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBankInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterBankInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBankInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterBanks.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBanks.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterBanks.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterBanks.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86RegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86RegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedBroadwell.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedBroadwell.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedBroadwell.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedBroadwell.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedHaswell.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedHaswell.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedHaswell.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedHaswell.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedPredicates.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedPredicates.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedPredicates.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedPredicates.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedSandyBridge.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSandyBridge.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedSandyBridge.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSandyBridge.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedSkylakeClient.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSkylakeClient.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedSkylakeClient.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSkylakeClient.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SchedSkylakeServer.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSkylakeServer.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SchedSkylakeServer.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SchedSkylakeServer.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86Schedule.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86Schedule.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86Schedule.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86Schedule.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleAtom.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleAtom.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleAtom.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleAtom.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleBdVer2.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleBdVer2.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleBdVer2.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleBdVer2.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleBtVer2.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleBtVer2.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleBtVer2.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleBtVer2.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleSLM.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleSLM.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleSLM.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleSLM.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver1.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver1.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver1.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver1.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver2.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver2.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver2.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver2.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver3.td b/interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver3.td similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ScheduleZnver3.td rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ScheduleZnver3.td diff --git a/interpreter/llvm/src/lib/Target/X86/X86SelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86SelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86SelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86SelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86ShuffleDecodeConstantPool.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86ShuffleDecodeConstantPool.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ShuffleDecodeConstantPool.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ShuffleDecodeConstantPool.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86ShuffleDecodeConstantPool.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86ShuffleDecodeConstantPool.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86ShuffleDecodeConstantPool.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86ShuffleDecodeConstantPool.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86SpeculativeExecutionSideEffectSuppression.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86SpeculativeExecutionSideEffectSuppression.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SpeculativeExecutionSideEffectSuppression.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SpeculativeExecutionSideEffectSuppression.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86SpeculativeLoadHardening.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86SpeculativeLoadHardening.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86Subtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86Subtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86Subtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86Subtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86Subtarget.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86Subtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86Subtarget.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86Subtarget.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetTransformInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetTransformInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetTransformInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetTransformInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86TargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/X86/X86TargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Target/X86/X86TileConfig.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86TileConfig.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86TileConfig.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86TileConfig.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86VZeroUpper.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86VZeroUpper.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86VZeroUpper.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86VZeroUpper.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86WinAllocaExpander.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86WinAllocaExpander.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86WinAllocaExpander.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86WinAllocaExpander.cpp diff --git a/interpreter/llvm/src/lib/Target/X86/X86WinEHState.cpp b/interpreter/llvm-project/llvm/lib/Target/X86/X86WinEHState.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/X86/X86WinEHState.cpp rename to interpreter/llvm-project/llvm/lib/Target/X86/X86WinEHState.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/XCore/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/XCore/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/XCore/Disassembler/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/XCore/Disassembler/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/Disassembler/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/XCore/Disassembler/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/XCore/Disassembler/XCoreDisassembler.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/Disassembler/XCoreDisassembler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/Disassembler/XCoreDisassembler.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/Disassembler/XCoreDisassembler.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.h b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreInstPrinter.h diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h b/interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h diff --git a/interpreter/llvm/src/lib/Target/XCore/README.txt b/interpreter/llvm-project/llvm/lib/Target/XCore/README.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/README.txt rename to interpreter/llvm-project/llvm/lib/Target/XCore/README.txt diff --git a/interpreter/llvm/src/lib/Target/XCore/TargetInfo/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/TargetInfo/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Target/XCore/TargetInfo/XCoreTargetInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/XCoreTargetInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/TargetInfo/XCoreTargetInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/XCoreTargetInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/TargetInfo/XCoreTargetInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/XCoreTargetInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/TargetInfo/XCoreTargetInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/TargetInfo/XCoreTargetInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCore.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCore.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCore.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCore.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCore.td b/interpreter/llvm-project/llvm/lib/Target/XCore/XCore.td similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCore.td rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCore.td diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreAsmPrinter.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreAsmPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreAsmPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreAsmPrinter.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreCallingConv.td b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreCallingConv.td similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreCallingConv.td rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreCallingConv.td diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreFrameLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreFrameLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreFrameLowering.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreFrameLowering.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameLowering.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreFrameToArgsOffsetElim.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameToArgsOffsetElim.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreFrameToArgsOffsetElim.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreFrameToArgsOffsetElim.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreISelDAGToDAG.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelDAGToDAG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreISelDAGToDAG.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelDAGToDAG.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreISelLowering.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelLowering.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreISelLowering.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelLowering.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreISelLowering.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelLowering.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreISelLowering.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreISelLowering.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreInstrFormats.td b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrFormats.td similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreInstrFormats.td rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrFormats.td diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.td b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreInstrInfo.td rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreInstrInfo.td diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreLowerThreadLocal.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreLowerThreadLocal.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreMCInstLower.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMCInstLower.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreMCInstLower.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMCInstLower.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreMCInstLower.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMCInstLower.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreMCInstLower.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMCInstLower.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreMachineFunctionInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreMachineFunctionInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreMachineFunctionInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreMachineFunctionInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.td b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.td similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreRegisterInfo.td rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreRegisterInfo.td diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreSelectionDAGInfo.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSelectionDAGInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreSelectionDAGInfo.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSelectionDAGInfo.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreSelectionDAGInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSelectionDAGInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreSelectionDAGInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSelectionDAGInfo.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreSubtarget.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSubtarget.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreSubtarget.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSubtarget.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreSubtarget.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSubtarget.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreSubtarget.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreSubtarget.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetMachine.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetMachine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetMachine.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetMachine.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetMachine.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetMachine.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetMachine.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetMachine.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetObjectFile.cpp b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetObjectFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetObjectFile.cpp rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetObjectFile.cpp diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetObjectFile.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetObjectFile.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetObjectFile.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetObjectFile.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetStreamer.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetStreamer.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetStreamer.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetStreamer.h diff --git a/interpreter/llvm/src/lib/Target/XCore/XCoreTargetTransformInfo.h b/interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetTransformInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Target/XCore/XCoreTargetTransformInfo.h rename to interpreter/llvm-project/llvm/lib/Target/XCore/XCoreTargetTransformInfo.h diff --git a/interpreter/llvm/src/lib/Testing/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Testing/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Testing/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Testing/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Testing/Support/Annotations.cpp b/interpreter/llvm-project/llvm/lib/Testing/Support/Annotations.cpp similarity index 100% rename from interpreter/llvm/src/lib/Testing/Support/Annotations.cpp rename to interpreter/llvm-project/llvm/lib/Testing/Support/Annotations.cpp diff --git a/interpreter/llvm/src/lib/Testing/Support/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Testing/Support/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Testing/Support/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Testing/Support/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Testing/Support/Error.cpp b/interpreter/llvm-project/llvm/lib/Testing/Support/Error.cpp similarity index 100% rename from interpreter/llvm/src/lib/Testing/Support/Error.cpp rename to interpreter/llvm-project/llvm/lib/Testing/Support/Error.cpp diff --git a/interpreter/llvm/src/lib/Testing/Support/SupportHelpers.cpp b/interpreter/llvm-project/llvm/lib/Testing/Support/SupportHelpers.cpp similarity index 100% rename from interpreter/llvm/src/lib/Testing/Support/SupportHelpers.cpp rename to interpreter/llvm-project/llvm/lib/Testing/Support/SupportHelpers.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/Architecture.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/Architecture.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/Architecture.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/Architecture.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/ArchitectureSet.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/ArchitectureSet.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/ArchitectureSet.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/ArchitectureSet.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/TextAPI/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/TextAPI/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/TextAPI/InterfaceFile.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/InterfaceFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/InterfaceFile.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/InterfaceFile.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/PackedVersion.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/PackedVersion.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/PackedVersion.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/PackedVersion.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/Platform.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/Platform.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/Platform.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/Platform.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/Symbol.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/Symbol.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/Symbol.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/Symbol.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/Target.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/Target.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/Target.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/Target.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/TextAPIContext.h b/interpreter/llvm-project/llvm/lib/TextAPI/TextAPIContext.h similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/TextAPIContext.h rename to interpreter/llvm-project/llvm/lib/TextAPI/TextAPIContext.h diff --git a/interpreter/llvm/src/lib/TextAPI/TextStub.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/TextStub.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/TextStub.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/TextStub.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/TextStubCommon.cpp b/interpreter/llvm-project/llvm/lib/TextAPI/TextStubCommon.cpp similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/TextStubCommon.cpp rename to interpreter/llvm-project/llvm/lib/TextAPI/TextStubCommon.cpp diff --git a/interpreter/llvm/src/lib/TextAPI/TextStubCommon.h b/interpreter/llvm-project/llvm/lib/TextAPI/TextStubCommon.h similarity index 100% rename from interpreter/llvm/src/lib/TextAPI/TextStubCommon.h rename to interpreter/llvm-project/llvm/lib/TextAPI/TextStubCommon.h diff --git a/interpreter/llvm/src/lib/ToolDrivers/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ToolDrivers/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ToolDrivers/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/Options.td b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/Options.td similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-dlltool/Options.td rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-dlltool/Options.td diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-lib/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-lib/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-lib/LibDriver.cpp b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-lib/LibDriver.cpp rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp diff --git a/interpreter/llvm/src/lib/ToolDrivers/llvm-lib/Options.td b/interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/Options.td similarity index 100% rename from interpreter/llvm/src/lib/ToolDrivers/llvm-lib/Options.td rename to interpreter/llvm-project/llvm/lib/ToolDrivers/llvm-lib/Options.td diff --git a/interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp b/interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp diff --git a/interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/AggressiveInstCombineInternal.h b/interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombineInternal.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/AggressiveInstCombineInternal.h rename to interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombineInternal.h diff --git a/interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/TruncInstCombine.cpp b/interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/TruncInstCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/AggressiveInstCombine/TruncInstCombine.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/AggressiveInstCombine/TruncInstCombine.cpp diff --git a/interpreter/llvm/src/lib/Transforms/CFGuard/CFGuard.cpp b/interpreter/llvm-project/llvm/lib/Transforms/CFGuard/CFGuard.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/CFGuard/CFGuard.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/CFGuard/CFGuard.cpp diff --git a/interpreter/llvm/src/lib/Transforms/CFGuard/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/CFGuard/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/CFGuard/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/CFGuard/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroCleanup.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroCleanup.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroEarly.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroEarly.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroEarly.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroEarly.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroElide.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroElide.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroElide.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroElide.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroFrame.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroFrame.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroFrame.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroFrame.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroInstr.h b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroInstr.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroInstr.h rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroInstr.h diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroInternal.h b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroInternal.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroInternal.h rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroInternal.h diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/CoroSplit.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroSplit.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/CoroSplit.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/CoroSplit.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Coroutines/Coroutines.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Coroutines/Coroutines.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Coroutines/Coroutines.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Coroutines/Coroutines.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Hello/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Hello/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Hello/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Hello/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Hello/Hello.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Hello/Hello.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Hello/Hello.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Hello/Hello.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Hello/Hello.exports b/interpreter/llvm-project/llvm/lib/Transforms/Hello/Hello.exports similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Hello/Hello.exports rename to interpreter/llvm-project/llvm/lib/Transforms/Hello/Hello.exports diff --git a/interpreter/llvm/src/lib/Transforms/IPO/AlwaysInliner.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/AlwaysInliner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/AlwaysInliner.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/AlwaysInliner.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/Annotation2Metadata.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/Annotation2Metadata.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/Annotation2Metadata.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ArgumentPromotion.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ArgumentPromotion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ArgumentPromotion.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ArgumentPromotion.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/Attributor.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/Attributor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/Attributor.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/Attributor.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/AttributorAttributes.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/AttributorAttributes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/AttributorAttributes.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/AttributorAttributes.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/BarrierNoopPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/BarrierNoopPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/BarrierNoopPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/BarrierNoopPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/BlockExtractor.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/BlockExtractor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/BlockExtractor.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/BlockExtractor.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/IPO/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/IPO/CalledValuePropagation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/CalledValuePropagation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/CalledValuePropagation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/CalledValuePropagation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ConstantMerge.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ConstantMerge.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ConstantMerge.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ConstantMerge.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/CrossDSOCFI.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/CrossDSOCFI.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/CrossDSOCFI.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/DeadArgumentElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/DeadArgumentElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ElimAvailExtern.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ElimAvailExtern.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ElimAvailExtern.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ElimAvailExtern.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ExtractGV.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ExtractGV.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ExtractGV.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ExtractGV.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ForceFunctionAttrs.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ForceFunctionAttrs.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/FunctionAttrs.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionAttrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/FunctionAttrs.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionAttrs.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/FunctionImport.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionImport.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/FunctionImport.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionImport.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/FunctionSpecialization.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/FunctionSpecialization.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/GlobalDCE.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalDCE.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/GlobalDCE.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalDCE.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/GlobalOpt.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/GlobalOpt.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalOpt.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/GlobalSplit.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalSplit.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/GlobalSplit.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/GlobalSplit.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/HotColdSplitting.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/HotColdSplitting.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/HotColdSplitting.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/HotColdSplitting.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/IPO.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/IPO.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/IPO.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/IPO.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/IROutliner.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/IROutliner.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/InferFunctionAttrs.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/InferFunctionAttrs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/InferFunctionAttrs.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/InferFunctionAttrs.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/InlineSimple.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/InlineSimple.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/InlineSimple.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/InlineSimple.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/Inliner.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/Inliner.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/Inliner.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/Inliner.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/Internalize.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/Internalize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/Internalize.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/Internalize.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/LoopExtractor.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/LoopExtractor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/LoopExtractor.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/LoopExtractor.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/LowerTypeTests.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/LowerTypeTests.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/LowerTypeTests.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/LowerTypeTests.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/MergeFunctions.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/MergeFunctions.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/MergeFunctions.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/MergeFunctions.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/OpenMPOpt.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/OpenMPOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/OpenMPOpt.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/OpenMPOpt.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/PartialInlining.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/PartialInlining.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/PartialInlining.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/PartialInlining.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/PassManagerBuilder.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/PassManagerBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/PassManagerBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/PassManagerBuilder.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/PruneEH.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/PruneEH.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/PruneEH.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/PruneEH.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/SCCP.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/SCCP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/SCCP.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/SCCP.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/SampleContextTracker.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleContextTracker.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/SampleContextTracker.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleContextTracker.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/SampleProfile.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleProfile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/SampleProfile.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleProfile.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/SampleProfileProbe.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/SampleProfileProbe.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/StripDeadPrototypes.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/StripDeadPrototypes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/StripDeadPrototypes.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/StripDeadPrototypes.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/StripSymbols.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/StripSymbols.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/StripSymbols.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/StripSymbols.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/SyntheticCountsPropagation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/SyntheticCountsPropagation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/SyntheticCountsPropagation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/SyntheticCountsPropagation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/IPO/WholeProgramDevirt.cpp b/interpreter/llvm-project/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/IPO/WholeProgramDevirt.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAddSub.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAtomicRMW.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAtomicRMW.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineAtomicRMW.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAtomicRMW.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCalls.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCalls.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCasts.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCasts.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCompares.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineCompares.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineInternal.h b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineInternal.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineInternal.h rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineInternal.h diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineNegator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineNegator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombinePHI.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombinePHI.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineSelect.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineSelect.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineShifts.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineShifts.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineVectorOps.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstCombineVectorOps.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp diff --git a/interpreter/llvm/src/lib/Transforms/InstCombine/InstructionCombining.cpp b/interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/InstCombine/InstructionCombining.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/AddressSanitizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/BoundsChecking.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/BoundsChecking.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/CFGMST.h b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CFGMST.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/CFGMST.h rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CFGMST.h diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/CGProfile.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CGProfile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/CGProfile.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CGProfile.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/ControlHeightReduction.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/ControlHeightReduction.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/GCOVProfiling.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/GCOVProfiling.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/InstrOrderFile.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/InstrOrderFile.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/InstrProfiling.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/InstrProfiling.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/Instrumentation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/Instrumentation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/Instrumentation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/Instrumentation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/MaximumSpanningTree.h b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MaximumSpanningTree.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/MaximumSpanningTree.h rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MaximumSpanningTree.h diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/MemProfiler.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/MemProfiler.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/MemorySanitizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/PGOInstrumentation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/PGOInstrumentation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/PGOMemOPSizeOpt.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PGOMemOPSizeOpt.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/PGOMemOPSizeOpt.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PGOMemOPSizeOpt.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/PoisonChecking.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PoisonChecking.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/PoisonChecking.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/PoisonChecking.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/SanitizerCoverage.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/SanitizerCoverage.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/ThreadSanitizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfileCollector.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfileCollector.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfileCollector.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfileCollector.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfileCollector.h b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfileCollector.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfileCollector.h rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfileCollector.h diff --git a/interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfilePlugins.inc b/interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfilePlugins.inc similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Instrumentation/ValueProfilePlugins.inc rename to interpreter/llvm-project/llvm/lib/Transforms/Instrumentation/ValueProfilePlugins.inc diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/BlotMapVector.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/BlotMapVector.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/BlotMapVector.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/BlotMapVector.h diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/DependencyAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/DependencyAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/DependencyAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/DependencyAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/DependencyAnalysis.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/DependencyAnalysis.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/DependencyAnalysis.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/DependencyAnalysis.h diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARC.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARC.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARC.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARC.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARC.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARC.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARC.h diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCAPElim.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCAPElim.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCAPElim.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCAPElim.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCContract.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCContract.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCExpand.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCExpand.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCExpand.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCExpand.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCOpts.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ObjCARCOpts.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysis.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysis.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysis.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysis.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysis.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysis.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysis.h diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysisEvaluator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysisEvaluator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/ProvenanceAnalysisEvaluator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/ProvenanceAnalysisEvaluator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/PtrState.cpp b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/PtrState.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/PtrState.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/PtrState.cpp diff --git a/interpreter/llvm/src/lib/Transforms/ObjCARC/PtrState.h b/interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/PtrState.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/ObjCARC/PtrState.h rename to interpreter/llvm-project/llvm/lib/Transforms/ObjCARC/PtrState.h diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/ADCE.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/ADCE.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/ADCE.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/ADCE.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/AnnotationRemarks.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/AnnotationRemarks.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/AnnotationRemarks.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/AnnotationRemarks.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/BDCE.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/BDCE.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/BDCE.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/BDCE.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/CallSiteSplitting.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/CallSiteSplitting.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/ConstantHoisting.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/ConstantHoisting.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/ConstraintElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/ConstraintElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/DCE.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/DCE.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/DCE.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/DCE.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/DFAJumpThreading.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/DFAJumpThreading.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/DeadStoreElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/DeadStoreElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/DivRemPairs.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/DivRemPairs.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/DivRemPairs.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/DivRemPairs.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/EarlyCSE.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/EarlyCSE.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/EarlyCSE.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/EarlyCSE.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/FlattenCFGPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/FlattenCFGPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/FlattenCFGPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/FlattenCFGPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Float2Int.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Float2Int.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Float2Int.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Float2Int.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/GVN.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVN.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/GVN.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVN.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/GVNHoist.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVNHoist.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/GVNHoist.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVNHoist.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/GVNSink.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVNSink.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/GVNSink.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/GVNSink.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/GuardWidening.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/GuardWidening.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/GuardWidening.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/GuardWidening.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/IVUsersPrinter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/IVUsersPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/IVUsersPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/IVUsersPrinter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/IndVarSimplify.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/IndVarSimplify.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/InferAddressSpaces.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/InferAddressSpaces.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/InstSimplifyPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/InstSimplifyPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/InstSimplifyPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/InstSimplifyPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/JumpThreading.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/JumpThreading.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/JumpThreading.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/JumpThreading.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LICM.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LICM.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LICM.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LICM.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopAccessAnalysisPrinter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopAccessAnalysisPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopAccessAnalysisPrinter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopAccessAnalysisPrinter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopBoundSplit.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopBoundSplit.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopDataPrefetch.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopDataPrefetch.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopDeletion.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDeletion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopDeletion.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDeletion.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopDistribute.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDistribute.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopDistribute.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopDistribute.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopFlatten.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopFlatten.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopFuse.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopFuse.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopFuse.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopFuse.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopIdiomRecognize.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopIdiomRecognize.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopInstSimplify.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopInstSimplify.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopInterchange.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopInterchange.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopInterchange.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopInterchange.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopLoadElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopLoadElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopPassManager.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopPassManager.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopPassManager.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopPassManager.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopPredication.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopPredication.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopPredication.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopPredication.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopRerollPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopRerollPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopRerollPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopRerollPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopRotation.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopRotation.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopRotation.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopRotation.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopSimplifyCFG.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopSimplifyCFG.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopSink.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopSink.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopSink.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopSink.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopStrengthReduce.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopUnswitch.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopUnswitch.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LoopVersioningLICM.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopVersioningLICM.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LoopVersioningLICM.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LoopVersioningLICM.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerAtomic.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerAtomic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerAtomic.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerAtomic.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerGuardIntrinsic.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerGuardIntrinsic.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerGuardIntrinsic.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerGuardIntrinsic.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/LowerWidenableCondition.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerWidenableCondition.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/LowerWidenableCondition.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/LowerWidenableCondition.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/MakeGuardsExplicit.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/MakeGuardsExplicit.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/MakeGuardsExplicit.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/MakeGuardsExplicit.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/MemCpyOptimizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/MemCpyOptimizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/MergeICmps.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/MergeICmps.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/MergeICmps.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/MergeICmps.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/NaryReassociate.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/NaryReassociate.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/NaryReassociate.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/NaryReassociate.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/NewGVN.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/NewGVN.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/NewGVN.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/NewGVN.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/PlaceSafepoints.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/PlaceSafepoints.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Reassociate.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Reassociate.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Reassociate.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Reassociate.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Reg2Mem.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Reg2Mem.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Reg2Mem.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Reg2Mem.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SCCP.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SCCP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SCCP.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SCCP.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SROA.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SROA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SROA.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SROA.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Scalar.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Scalar.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Scalar.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Scalar.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/ScalarizeMaskedMemIntrin.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/ScalarizeMaskedMemIntrin.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/ScalarizeMaskedMemIntrin.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/ScalarizeMaskedMemIntrin.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Scalarizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Scalarizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Scalarizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Scalarizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SimplifyCFGPass.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SimplifyCFGPass.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/Sink.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/Sink.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/Sink.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/Sink.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/SpeculativeExecution.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/SpeculativeExecution.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/StructurizeCFG.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/StructurizeCFG.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/TailRecursionElimination.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/TailRecursionElimination.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Scalar/WarnMissedTransforms.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Scalar/WarnMissedTransforms.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Scalar/WarnMissedTransforms.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Scalar/WarnMissedTransforms.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/ASanStackFrameLayout.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/ASanStackFrameLayout.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/ASanStackFrameLayout.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/ASanStackFrameLayout.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/AddDiscriminators.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/AddDiscriminators.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/AddDiscriminators.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/AddDiscriminators.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/AssumeBundleBuilder.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/AssumeBundleBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/BasicBlockUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/BasicBlockUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/BreakCriticalEdges.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/BreakCriticalEdges.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/BuildLibCalls.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/BuildLibCalls.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/BuildLibCalls.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/BuildLibCalls.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/BypassSlowDivision.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/BypassSlowDivision.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CallGraphUpdater.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CallGraphUpdater.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CallGraphUpdater.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CallGraphUpdater.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CallPromotionUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CallPromotionUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CanonicalizeAliases.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CanonicalizeAliases.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CanonicalizeAliases.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CanonicalizeAliases.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CanonicalizeFreezeInLoops.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CanonicalizeFreezeInLoops.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CanonicalizeFreezeInLoops.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CanonicalizeFreezeInLoops.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CloneFunction.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CloneFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CloneFunction.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CloneFunction.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CloneModule.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CloneModule.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CloneModule.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CloneModule.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CodeExtractor.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CodeExtractor.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CodeExtractor.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CodeExtractor.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CodeMoverUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CodeMoverUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CodeMoverUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CodeMoverUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/CtorUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/CtorUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/CtorUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/CtorUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/Debugify.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/Debugify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/Debugify.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/Debugify.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/DemoteRegToStack.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/DemoteRegToStack.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/EntryExitInstrumenter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/EntryExitInstrumenter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/EscapeEnumerator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/EscapeEnumerator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/Evaluator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/Evaluator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/Evaluator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/Evaluator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/FixIrreducible.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/FixIrreducible.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/FixIrreducible.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/FixIrreducible.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/FlattenCFG.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/FlattenCFG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/FlattenCFG.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/FlattenCFG.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/FunctionComparator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/FunctionComparator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/FunctionComparator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/FunctionComparator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/FunctionImportUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/FunctionImportUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/GlobalStatus.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/GlobalStatus.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/GlobalStatus.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/GlobalStatus.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/GuardUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/GuardUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/GuardUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/GuardUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/HelloWorld.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/HelloWorld.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/HelloWorld.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/HelloWorld.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/InjectTLIMappings.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/InjectTLIMappings.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/InjectTLIMappings.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/InjectTLIMappings.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/InlineFunction.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/InlineFunction.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/InlineFunction.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/InlineFunction.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/InstructionNamer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/InstructionNamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/InstructionNamer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/InstructionNamer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/IntegerDivision.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/IntegerDivision.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/IntegerDivision.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/IntegerDivision.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LCSSA.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LCSSA.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LibCallsShrinkWrap.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LibCallsShrinkWrap.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LibCallsShrinkWrap.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LibCallsShrinkWrap.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/Local.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/Local.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/Local.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/Local.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopPeel.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopPeel.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopPeel.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopPeel.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopRotationUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopRotationUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopSimplify.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopSimplify.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopSimplify.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopSimplify.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopUnroll.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnroll.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopUnroll.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnroll.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopUnrollAndJam.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopUnrollAndJam.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopUnrollRuntime.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopUnrollRuntime.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LoopVersioning.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopVersioning.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LoopVersioning.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LoopVersioning.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LowerInvoke.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerInvoke.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LowerInvoke.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerInvoke.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LowerMemIntrinsics.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LowerMemIntrinsics.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/LowerSwitch.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerSwitch.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/LowerSwitch.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/LowerSwitch.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/MatrixUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/MatrixUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/MatrixUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/MatrixUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/Mem2Reg.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/Mem2Reg.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/Mem2Reg.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/Mem2Reg.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/MemoryOpRemark.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/MemoryOpRemark.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/MemoryOpRemark.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/MemoryOpRemark.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/MetaRenamer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/MetaRenamer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/MetaRenamer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/MetaRenamer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/ModuleUtils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/ModuleUtils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/ModuleUtils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/ModuleUtils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/NameAnonGlobals.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/NameAnonGlobals.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/NameAnonGlobals.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/NameAnonGlobals.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/PredicateInfo.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/PredicateInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/PredicateInfo.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/PredicateInfo.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/PromoteMemoryToRegister.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/PromoteMemoryToRegister.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/RelLookupTableConverter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/RelLookupTableConverter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/RelLookupTableConverter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/RelLookupTableConverter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SCCPSolver.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SCCPSolver.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SCCPSolver.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SCCPSolver.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SSAUpdater.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SSAUpdater.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SSAUpdater.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SSAUpdater.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SSAUpdaterBulk.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SSAUpdaterBulk.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SampleProfileLoaderBaseUtil.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SampleProfileLoaderBaseUtil.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SampleProfileLoaderBaseUtil.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SampleProfileLoaderBaseUtil.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SanitizerStats.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SanitizerStats.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SanitizerStats.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SanitizerStats.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/ScalarEvolutionExpander.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/ScalarEvolutionExpander.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SimplifyCFG.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyCFG.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SimplifyCFG.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyCFG.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SimplifyIndVar.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SimplifyIndVar.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SimplifyLibCalls.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SimplifyLibCalls.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SizeOpts.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SizeOpts.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SizeOpts.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SizeOpts.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SplitModule.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SplitModule.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SplitModule.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SplitModule.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/StripGCRelocates.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/StripGCRelocates.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/StripGCRelocates.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/StripGCRelocates.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/StripNonLineTableDebugInfo.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/StripNonLineTableDebugInfo.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/StripNonLineTableDebugInfo.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/StripNonLineTableDebugInfo.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/SymbolRewriter.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/SymbolRewriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/SymbolRewriter.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/SymbolRewriter.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/UnifyLoopExits.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/UnifyLoopExits.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/Utils.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/Utils.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/Utils.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/Utils.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/VNCoercion.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/VNCoercion.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/VNCoercion.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/VNCoercion.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Utils/ValueMapper.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Utils/ValueMapper.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Utils/ValueMapper.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Utils/ValueMapper.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorizationPlanner.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorizationPlanner.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorize.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/LoopVectorize.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/SLPVectorizer.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/SLPVectorizer.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPRecipeBuilder.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPRecipeBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPRecipeBuilder.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPRecipeBuilder.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlan.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlan.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlan.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlan.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanDominatorTree.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanDominatorTree.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanDominatorTree.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanDominatorTree.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanHCFGBuilder.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanHCFGBuilder.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanLoopInfo.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanLoopInfo.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanLoopInfo.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanLoopInfo.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanPredicator.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanPredicator.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanPredicator.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanPredicator.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanPredicator.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanPredicator.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanPredicator.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanPredicator.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanSLP.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanSLP.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanSLP.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanSLP.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanTransforms.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanTransforms.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanTransforms.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanTransforms.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanValue.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanValue.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanValue.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanValue.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanVerifier.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanVerifier.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanVerifier.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VPlanVerifier.h b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanVerifier.h similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VPlanVerifier.h rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VPlanVerifier.h diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/VectorCombine.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VectorCombine.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/VectorCombine.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/VectorCombine.cpp diff --git a/interpreter/llvm/src/lib/Transforms/Vectorize/Vectorize.cpp b/interpreter/llvm-project/llvm/lib/Transforms/Vectorize/Vectorize.cpp similarity index 100% rename from interpreter/llvm/src/lib/Transforms/Vectorize/Vectorize.cpp rename to interpreter/llvm-project/llvm/lib/Transforms/Vectorize/Vectorize.cpp diff --git a/interpreter/llvm/src/lib/WindowsManifest/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/WindowsManifest/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/WindowsManifest/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/WindowsManifest/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/WindowsManifest/WindowsManifestMerger.cpp b/interpreter/llvm-project/llvm/lib/WindowsManifest/WindowsManifestMerger.cpp similarity index 100% rename from interpreter/llvm/src/lib/WindowsManifest/WindowsManifestMerger.cpp rename to interpreter/llvm-project/llvm/lib/WindowsManifest/WindowsManifestMerger.cpp diff --git a/interpreter/llvm/src/lib/XRay/BlockIndexer.cpp b/interpreter/llvm-project/llvm/lib/XRay/BlockIndexer.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/BlockIndexer.cpp rename to interpreter/llvm-project/llvm/lib/XRay/BlockIndexer.cpp diff --git a/interpreter/llvm/src/lib/XRay/BlockPrinter.cpp b/interpreter/llvm-project/llvm/lib/XRay/BlockPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/BlockPrinter.cpp rename to interpreter/llvm-project/llvm/lib/XRay/BlockPrinter.cpp diff --git a/interpreter/llvm/src/lib/XRay/BlockVerifier.cpp b/interpreter/llvm-project/llvm/lib/XRay/BlockVerifier.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/BlockVerifier.cpp rename to interpreter/llvm-project/llvm/lib/XRay/BlockVerifier.cpp diff --git a/interpreter/llvm/src/lib/XRay/CMakeLists.txt b/interpreter/llvm-project/llvm/lib/XRay/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/lib/XRay/CMakeLists.txt rename to interpreter/llvm-project/llvm/lib/XRay/CMakeLists.txt diff --git a/interpreter/llvm/src/lib/XRay/FDRRecordProducer.cpp b/interpreter/llvm-project/llvm/lib/XRay/FDRRecordProducer.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/FDRRecordProducer.cpp rename to interpreter/llvm-project/llvm/lib/XRay/FDRRecordProducer.cpp diff --git a/interpreter/llvm/src/lib/XRay/FDRRecords.cpp b/interpreter/llvm-project/llvm/lib/XRay/FDRRecords.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/FDRRecords.cpp rename to interpreter/llvm-project/llvm/lib/XRay/FDRRecords.cpp diff --git a/interpreter/llvm/src/lib/XRay/FDRTraceExpander.cpp b/interpreter/llvm-project/llvm/lib/XRay/FDRTraceExpander.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/FDRTraceExpander.cpp rename to interpreter/llvm-project/llvm/lib/XRay/FDRTraceExpander.cpp diff --git a/interpreter/llvm/src/lib/XRay/FDRTraceWriter.cpp b/interpreter/llvm-project/llvm/lib/XRay/FDRTraceWriter.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/FDRTraceWriter.cpp rename to interpreter/llvm-project/llvm/lib/XRay/FDRTraceWriter.cpp diff --git a/interpreter/llvm/src/lib/XRay/FileHeaderReader.cpp b/interpreter/llvm-project/llvm/lib/XRay/FileHeaderReader.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/FileHeaderReader.cpp rename to interpreter/llvm-project/llvm/lib/XRay/FileHeaderReader.cpp diff --git a/interpreter/llvm/src/lib/XRay/InstrumentationMap.cpp b/interpreter/llvm-project/llvm/lib/XRay/InstrumentationMap.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/InstrumentationMap.cpp rename to interpreter/llvm-project/llvm/lib/XRay/InstrumentationMap.cpp diff --git a/interpreter/llvm/src/lib/XRay/LogBuilderConsumer.cpp b/interpreter/llvm-project/llvm/lib/XRay/LogBuilderConsumer.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/LogBuilderConsumer.cpp rename to interpreter/llvm-project/llvm/lib/XRay/LogBuilderConsumer.cpp diff --git a/interpreter/llvm/src/lib/XRay/Profile.cpp b/interpreter/llvm-project/llvm/lib/XRay/Profile.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/Profile.cpp rename to interpreter/llvm-project/llvm/lib/XRay/Profile.cpp diff --git a/interpreter/llvm/src/lib/XRay/RecordInitializer.cpp b/interpreter/llvm-project/llvm/lib/XRay/RecordInitializer.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/RecordInitializer.cpp rename to interpreter/llvm-project/llvm/lib/XRay/RecordInitializer.cpp diff --git a/interpreter/llvm/src/lib/XRay/RecordPrinter.cpp b/interpreter/llvm-project/llvm/lib/XRay/RecordPrinter.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/RecordPrinter.cpp rename to interpreter/llvm-project/llvm/lib/XRay/RecordPrinter.cpp diff --git a/interpreter/llvm/src/lib/XRay/Trace.cpp b/interpreter/llvm-project/llvm/lib/XRay/Trace.cpp similarity index 100% rename from interpreter/llvm/src/lib/XRay/Trace.cpp rename to interpreter/llvm-project/llvm/lib/XRay/Trace.cpp diff --git a/interpreter/llvm/src/llvm.spec.in b/interpreter/llvm-project/llvm/llvm.spec.in similarity index 100% rename from interpreter/llvm/src/llvm.spec.in rename to interpreter/llvm-project/llvm/llvm.spec.in diff --git a/interpreter/llvm/src/projects/CMakeLists.txt b/interpreter/llvm-project/llvm/projects/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/projects/CMakeLists.txt rename to interpreter/llvm-project/llvm/projects/CMakeLists.txt diff --git a/interpreter/llvm/src/resources/windows_version_resource.rc b/interpreter/llvm-project/llvm/resources/windows_version_resource.rc similarity index 100% rename from interpreter/llvm/src/resources/windows_version_resource.rc rename to interpreter/llvm-project/llvm/resources/windows_version_resource.rc diff --git a/interpreter/llvm/src/runtimes/CMakeLists.txt b/interpreter/llvm-project/llvm/runtimes/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/runtimes/CMakeLists.txt rename to interpreter/llvm-project/llvm/runtimes/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/bugpoint-passes/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/bugpoint-passes/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/bugpoint-passes/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/bugpoint-passes/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/bugpoint-passes/TestPasses.cpp b/interpreter/llvm-project/llvm/tools/bugpoint-passes/TestPasses.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint-passes/TestPasses.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint-passes/TestPasses.cpp diff --git a/interpreter/llvm/src/tools/bugpoint-passes/bugpoint.exports b/interpreter/llvm-project/llvm/tools/bugpoint-passes/bugpoint.exports similarity index 100% rename from interpreter/llvm/src/tools/bugpoint-passes/bugpoint.exports rename to interpreter/llvm-project/llvm/tools/bugpoint-passes/bugpoint.exports diff --git a/interpreter/llvm/src/tools/bugpoint/BugDriver.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/BugDriver.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/BugDriver.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/BugDriver.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/BugDriver.h b/interpreter/llvm-project/llvm/tools/bugpoint/BugDriver.h similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/BugDriver.h rename to interpreter/llvm-project/llvm/tools/bugpoint/BugDriver.h diff --git a/interpreter/llvm/src/tools/bugpoint/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/bugpoint/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/bugpoint/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/bugpoint/CrashDebugger.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/CrashDebugger.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/CrashDebugger.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/CrashDebugger.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/ExecutionDriver.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/ExecutionDriver.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/ExecutionDriver.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/ExecutionDriver.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/ExtractFunction.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/ExtractFunction.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/ExtractFunction.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/ExtractFunction.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/FindBugs.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/FindBugs.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/FindBugs.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/FindBugs.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/ListReducer.h b/interpreter/llvm-project/llvm/tools/bugpoint/ListReducer.h similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/ListReducer.h rename to interpreter/llvm-project/llvm/tools/bugpoint/ListReducer.h diff --git a/interpreter/llvm/src/tools/bugpoint/Miscompilation.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/Miscompilation.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/Miscompilation.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/Miscompilation.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/OptimizerDriver.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/OptimizerDriver.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/OptimizerDriver.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/OptimizerDriver.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/ToolRunner.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/ToolRunner.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/ToolRunner.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/ToolRunner.cpp diff --git a/interpreter/llvm/src/tools/bugpoint/ToolRunner.h b/interpreter/llvm-project/llvm/tools/bugpoint/ToolRunner.h similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/ToolRunner.h rename to interpreter/llvm-project/llvm/tools/bugpoint/ToolRunner.h diff --git a/interpreter/llvm/src/tools/bugpoint/bugpoint.cpp b/interpreter/llvm-project/llvm/tools/bugpoint/bugpoint.cpp similarity index 100% rename from interpreter/llvm/src/tools/bugpoint/bugpoint.cpp rename to interpreter/llvm-project/llvm/tools/bugpoint/bugpoint.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/BinaryHolder.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/BinaryHolder.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/BinaryHolder.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/BinaryHolder.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/BinaryHolder.h b/interpreter/llvm-project/llvm/tools/dsymutil/BinaryHolder.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/BinaryHolder.h rename to interpreter/llvm-project/llvm/tools/dsymutil/BinaryHolder.h diff --git a/interpreter/llvm/src/tools/dsymutil/CFBundle.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/CFBundle.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/CFBundle.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/CFBundle.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/CFBundle.h b/interpreter/llvm-project/llvm/tools/dsymutil/CFBundle.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/CFBundle.h rename to interpreter/llvm-project/llvm/tools/dsymutil/CFBundle.h diff --git a/interpreter/llvm/src/tools/dsymutil/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/dsymutil/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/dsymutil/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/dsymutil/DebugMap.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/DebugMap.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/DebugMap.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/DebugMap.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/DebugMap.h b/interpreter/llvm-project/llvm/tools/dsymutil/DebugMap.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/DebugMap.h rename to interpreter/llvm-project/llvm/tools/dsymutil/DebugMap.h diff --git a/interpreter/llvm/src/tools/dsymutil/DwarfLinkerForBinary.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/DwarfLinkerForBinary.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/DwarfLinkerForBinary.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/DwarfLinkerForBinary.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/DwarfLinkerForBinary.h b/interpreter/llvm-project/llvm/tools/dsymutil/DwarfLinkerForBinary.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/DwarfLinkerForBinary.h rename to interpreter/llvm-project/llvm/tools/dsymutil/DwarfLinkerForBinary.h diff --git a/interpreter/llvm/src/tools/dsymutil/LinkUtils.h b/interpreter/llvm-project/llvm/tools/dsymutil/LinkUtils.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/LinkUtils.h rename to interpreter/llvm-project/llvm/tools/dsymutil/LinkUtils.h diff --git a/interpreter/llvm/src/tools/dsymutil/MachODebugMapParser.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/MachODebugMapParser.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/MachODebugMapParser.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/MachODebugMapParser.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/MachOUtils.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/MachOUtils.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/MachOUtils.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/MachOUtils.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/MachOUtils.h b/interpreter/llvm-project/llvm/tools/dsymutil/MachOUtils.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/MachOUtils.h rename to interpreter/llvm-project/llvm/tools/dsymutil/MachOUtils.h diff --git a/interpreter/llvm/src/tools/dsymutil/Options.td b/interpreter/llvm-project/llvm/tools/dsymutil/Options.td similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/Options.td rename to interpreter/llvm-project/llvm/tools/dsymutil/Options.td diff --git a/interpreter/llvm/src/tools/dsymutil/Reproducer.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/Reproducer.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/Reproducer.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/Reproducer.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/Reproducer.h b/interpreter/llvm-project/llvm/tools/dsymutil/Reproducer.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/Reproducer.h rename to interpreter/llvm-project/llvm/tools/dsymutil/Reproducer.h diff --git a/interpreter/llvm/src/tools/dsymutil/SymbolMap.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/SymbolMap.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/SymbolMap.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/SymbolMap.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/SymbolMap.h b/interpreter/llvm-project/llvm/tools/dsymutil/SymbolMap.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/SymbolMap.h rename to interpreter/llvm-project/llvm/tools/dsymutil/SymbolMap.h diff --git a/interpreter/llvm/src/tools/dsymutil/dsymutil.cpp b/interpreter/llvm-project/llvm/tools/dsymutil/dsymutil.cpp similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/dsymutil.cpp rename to interpreter/llvm-project/llvm/tools/dsymutil/dsymutil.cpp diff --git a/interpreter/llvm/src/tools/dsymutil/dsymutil.h b/interpreter/llvm-project/llvm/tools/dsymutil/dsymutil.h similarity index 100% rename from interpreter/llvm/src/tools/dsymutil/dsymutil.h rename to interpreter/llvm-project/llvm/tools/dsymutil/dsymutil.h diff --git a/interpreter/llvm/src/tools/gold/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/gold/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/gold/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/gold/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/gold/README.txt b/interpreter/llvm-project/llvm/tools/gold/README.txt similarity index 100% rename from interpreter/llvm/src/tools/gold/README.txt rename to interpreter/llvm-project/llvm/tools/gold/README.txt diff --git a/interpreter/llvm/src/tools/gold/gold-plugin.cpp b/interpreter/llvm-project/llvm/tools/gold/gold-plugin.cpp similarity index 100% rename from interpreter/llvm/src/tools/gold/gold-plugin.cpp rename to interpreter/llvm-project/llvm/tools/gold/gold-plugin.cpp diff --git a/interpreter/llvm/src/tools/gold/gold.exports b/interpreter/llvm-project/llvm/tools/gold/gold.exports similarity index 100% rename from interpreter/llvm/src/tools/gold/gold.exports rename to interpreter/llvm-project/llvm/tools/gold/gold.exports diff --git a/interpreter/llvm/src/tools/llc/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llc/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llc/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llc/llc.cpp b/interpreter/llvm-project/llvm/tools/llc/llc.cpp similarity index 100% rename from interpreter/llvm/src/tools/llc/llc.cpp rename to interpreter/llvm-project/llvm/tools/llc/llc.cpp diff --git a/interpreter/llvm/src/tools/lli/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/lli/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/lli/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/lli/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/lli/ChildTarget/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/lli/ChildTarget/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/lli/ChildTarget/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/lli/ChildTarget/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/lli/ChildTarget/ChildTarget.cpp b/interpreter/llvm-project/llvm/tools/lli/ChildTarget/ChildTarget.cpp similarity index 100% rename from interpreter/llvm/src/tools/lli/ChildTarget/ChildTarget.cpp rename to interpreter/llvm-project/llvm/tools/lli/ChildTarget/ChildTarget.cpp diff --git a/interpreter/llvm/src/tools/lli/ExecutionUtils.cpp b/interpreter/llvm-project/llvm/tools/lli/ExecutionUtils.cpp similarity index 100% rename from interpreter/llvm/src/tools/lli/ExecutionUtils.cpp rename to interpreter/llvm-project/llvm/tools/lli/ExecutionUtils.cpp diff --git a/interpreter/llvm/src/tools/lli/ExecutionUtils.h b/interpreter/llvm-project/llvm/tools/lli/ExecutionUtils.h similarity index 100% rename from interpreter/llvm/src/tools/lli/ExecutionUtils.h rename to interpreter/llvm-project/llvm/tools/lli/ExecutionUtils.h diff --git a/interpreter/llvm/src/tools/lli/RemoteJITUtils.h b/interpreter/llvm-project/llvm/tools/lli/RemoteJITUtils.h similarity index 100% rename from interpreter/llvm/src/tools/lli/RemoteJITUtils.h rename to interpreter/llvm-project/llvm/tools/lli/RemoteJITUtils.h diff --git a/interpreter/llvm/src/tools/lli/lli.cpp b/interpreter/llvm-project/llvm/tools/lli/lli.cpp similarity index 100% rename from interpreter/llvm/src/tools/lli/lli.cpp rename to interpreter/llvm-project/llvm/tools/lli/lli.cpp diff --git a/interpreter/llvm/src/tools/llvm-ar/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-ar/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-ar/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-ar/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-ar/llvm-ar.cpp b/interpreter/llvm-project/llvm/tools/llvm-ar/llvm-ar.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-ar/llvm-ar.cpp rename to interpreter/llvm-project/llvm/tools/llvm-ar/llvm-ar.cpp diff --git a/interpreter/llvm/src/tools/llvm-as-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-as-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-as-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-as-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-as/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-as/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-as/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-as/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-as/llvm-as.cpp b/interpreter/llvm-project/llvm/tools/llvm-as/llvm-as.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-as/llvm-as.cpp rename to interpreter/llvm-project/llvm/tools/llvm-as/llvm-as.cpp diff --git a/interpreter/llvm/src/tools/llvm-bcanalyzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-bcanalyzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-bcanalyzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-bcanalyzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-c-test/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-c-test/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-c-test/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-c-test/attributes.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/attributes.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/attributes.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/attributes.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/calc.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/calc.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/calc.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/calc.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/debuginfo.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/debuginfo.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/debuginfo.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/debuginfo.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/diagnostic.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/diagnostic.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/diagnostic.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/diagnostic.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/disassemble.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/disassemble.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/disassemble.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/disassemble.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/echo.cpp b/interpreter/llvm-project/llvm/tools/llvm-c-test/echo.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/echo.cpp rename to interpreter/llvm-project/llvm/tools/llvm-c-test/echo.cpp diff --git a/interpreter/llvm/src/tools/llvm-c-test/helpers.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/helpers.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/helpers.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/helpers.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/include-all.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/include-all.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/include-all.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/include-all.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/llvm-c-test.h b/interpreter/llvm-project/llvm/tools/llvm-c-test/llvm-c-test.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/llvm-c-test.h rename to interpreter/llvm-project/llvm/tools/llvm-c-test/llvm-c-test.h diff --git a/interpreter/llvm/src/tools/llvm-c-test/main.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/main.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/main.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/main.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/metadata.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/metadata.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/metadata.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/metadata.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/module.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/module.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/module.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/module.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/object.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/object.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/object.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/object.c diff --git a/interpreter/llvm/src/tools/llvm-c-test/targets.c b/interpreter/llvm-project/llvm/tools/llvm-c-test/targets.c similarity index 100% rename from interpreter/llvm/src/tools/llvm-c-test/targets.c rename to interpreter/llvm-project/llvm/tools/llvm-c-test/targets.c diff --git a/interpreter/llvm/src/tools/llvm-cat/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cat/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cat/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cat/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cat/llvm-cat.cpp b/interpreter/llvm-project/llvm/tools/llvm-cat/llvm-cat.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cat/llvm-cat.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cat/llvm-cat.cpp diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/lib/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/lib/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/lib/FileAnalysis.cpp b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/FileAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/lib/FileAnalysis.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/FileAnalysis.cpp diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/lib/FileAnalysis.h b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/FileAnalysis.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/lib/FileAnalysis.h rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/FileAnalysis.h diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/lib/GraphBuilder.cpp b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/GraphBuilder.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/lib/GraphBuilder.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/GraphBuilder.cpp diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/lib/GraphBuilder.h b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/GraphBuilder.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/lib/GraphBuilder.h rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/lib/GraphBuilder.h diff --git a/interpreter/llvm/src/tools/llvm-cfi-verify/llvm-cfi-verify.cpp b/interpreter/llvm-project/llvm/tools/llvm-cfi-verify/llvm-cfi-verify.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cfi-verify/llvm-cfi-verify.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cfi-verify/llvm-cfi-verify.cpp diff --git a/interpreter/llvm/src/tools/llvm-config/BuildVariables.inc.in b/interpreter/llvm-project/llvm/tools/llvm-config/BuildVariables.inc.in similarity index 100% rename from interpreter/llvm/src/tools/llvm-config/BuildVariables.inc.in rename to interpreter/llvm-project/llvm/tools/llvm-config/BuildVariables.inc.in diff --git a/interpreter/llvm/src/tools/llvm-config/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-config/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-config/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-config/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-config/llvm-config.cpp b/interpreter/llvm-project/llvm/tools/llvm-config/llvm-config.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-config/llvm-config.cpp rename to interpreter/llvm-project/llvm/tools/llvm-config/llvm-config.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cov/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cov/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cov/CodeCoverage.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CodeCoverage.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CodeCoverage.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CodeCoverage.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageExporter.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageExporter.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporter.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageExporterJson.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterJson.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageExporterJson.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterJson.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageExporterJson.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterJson.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageExporterJson.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterJson.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageExporterLcov.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterLcov.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageExporterLcov.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterLcov.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageExporterLcov.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterLcov.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageExporterLcov.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageExporterLcov.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageFilters.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageFilters.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageFilters.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageFilters.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageFilters.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageFilters.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageFilters.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageFilters.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageReport.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageReport.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageReport.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageReport.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageReport.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageReport.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageReport.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageReport.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageSummaryInfo.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageSummaryInfo.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageSummaryInfo.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageSummaryInfo.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageSummaryInfo.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageSummaryInfo.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageSummaryInfo.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageSummaryInfo.h diff --git a/interpreter/llvm/src/tools/llvm-cov/CoverageViewOptions.h b/interpreter/llvm-project/llvm/tools/llvm-cov/CoverageViewOptions.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/CoverageViewOptions.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/CoverageViewOptions.h diff --git a/interpreter/llvm/src/tools/llvm-cov/RenderingSupport.h b/interpreter/llvm-project/llvm/tools/llvm-cov/RenderingSupport.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/RenderingSupport.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/RenderingSupport.h diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageView.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageView.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageView.h b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageView.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageView.h diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewHTML.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewHTML.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewHTML.h b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewHTML.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.h diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewText.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewText.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewText.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewText.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewText.h b/interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewText.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/SourceCoverageViewText.h rename to interpreter/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewText.h diff --git a/interpreter/llvm/src/tools/llvm-cov/TestingSupport.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/TestingSupport.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/TestingSupport.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/TestingSupport.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/gcov.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/gcov.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/gcov.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/gcov.cpp diff --git a/interpreter/llvm/src/tools/llvm-cov/llvm-cov.cpp b/interpreter/llvm-project/llvm/tools/llvm-cov/llvm-cov.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cov/llvm-cov.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cov/llvm-cov.cpp diff --git a/interpreter/llvm/src/tools/llvm-cvtres/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cvtres/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cvtres/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cvtres/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cvtres/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-cvtres/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-cvtres/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-cvtres/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-cvtres/llvm-cvtres.cpp b/interpreter/llvm-project/llvm/tools/llvm-cvtres/llvm-cvtres.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cvtres/llvm-cvtres.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cvtres/llvm-cvtres.cpp diff --git a/interpreter/llvm/src/tools/llvm-cxxdump/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cxxdump/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxdump/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cxxdump/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cxxdump/Error.cpp b/interpreter/llvm-project/llvm/tools/llvm-cxxdump/Error.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxdump/Error.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cxxdump/Error.cpp diff --git a/interpreter/llvm/src/tools/llvm-cxxdump/Error.h b/interpreter/llvm-project/llvm/tools/llvm-cxxdump/Error.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxdump/Error.h rename to interpreter/llvm-project/llvm/tools/llvm-cxxdump/Error.h diff --git a/interpreter/llvm/src/tools/llvm-cxxdump/llvm-cxxdump.cpp b/interpreter/llvm-project/llvm/tools/llvm-cxxdump/llvm-cxxdump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxdump/llvm-cxxdump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cxxdump/llvm-cxxdump.cpp diff --git a/interpreter/llvm/src/tools/llvm-cxxdump/llvm-cxxdump.h b/interpreter/llvm-project/llvm/tools/llvm-cxxdump/llvm-cxxdump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxdump/llvm-cxxdump.h rename to interpreter/llvm-project/llvm/tools/llvm-cxxdump/llvm-cxxdump.h diff --git a/interpreter/llvm/src/tools/llvm-cxxfilt/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cxxfilt/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxfilt/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cxxfilt/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cxxfilt/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-cxxfilt/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxfilt/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-cxxfilt/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-cxxfilt/llvm-cxxfilt.cpp b/interpreter/llvm-project/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxfilt/llvm-cxxfilt.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp diff --git a/interpreter/llvm/src/tools/llvm-cxxmap/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-cxxmap/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxmap/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-cxxmap/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-cxxmap/llvm-cxxmap.cpp b/interpreter/llvm-project/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-cxxmap/llvm-cxxmap.cpp rename to interpreter/llvm-project/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp diff --git a/interpreter/llvm/src/tools/llvm-diff/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-diff/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-diff/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-diff/DiffConsumer.cpp b/interpreter/llvm-project/llvm/tools/llvm-diff/DiffConsumer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DiffConsumer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-diff/DiffConsumer.cpp diff --git a/interpreter/llvm/src/tools/llvm-diff/DiffConsumer.h b/interpreter/llvm-project/llvm/tools/llvm-diff/DiffConsumer.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DiffConsumer.h rename to interpreter/llvm-project/llvm/tools/llvm-diff/DiffConsumer.h diff --git a/interpreter/llvm/src/tools/llvm-diff/DiffLog.cpp b/interpreter/llvm-project/llvm/tools/llvm-diff/DiffLog.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DiffLog.cpp rename to interpreter/llvm-project/llvm/tools/llvm-diff/DiffLog.cpp diff --git a/interpreter/llvm/src/tools/llvm-diff/DiffLog.h b/interpreter/llvm-project/llvm/tools/llvm-diff/DiffLog.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DiffLog.h rename to interpreter/llvm-project/llvm/tools/llvm-diff/DiffLog.h diff --git a/interpreter/llvm/src/tools/llvm-diff/DifferenceEngine.cpp b/interpreter/llvm-project/llvm/tools/llvm-diff/DifferenceEngine.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DifferenceEngine.cpp rename to interpreter/llvm-project/llvm/tools/llvm-diff/DifferenceEngine.cpp diff --git a/interpreter/llvm/src/tools/llvm-diff/DifferenceEngine.h b/interpreter/llvm-project/llvm/tools/llvm-diff/DifferenceEngine.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/DifferenceEngine.h rename to interpreter/llvm-project/llvm/tools/llvm-diff/DifferenceEngine.h diff --git a/interpreter/llvm/src/tools/llvm-diff/llvm-diff.cpp b/interpreter/llvm-project/llvm/tools/llvm-diff/llvm-diff.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-diff/llvm-diff.cpp rename to interpreter/llvm-project/llvm/tools/llvm-diff/llvm-diff.cpp diff --git a/interpreter/llvm/src/tools/llvm-dis/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-dis/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-dis/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-dis/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-dis/llvm-dis.cpp b/interpreter/llvm-project/llvm/tools/llvm-dis/llvm-dis.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dis/llvm-dis.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dis/llvm-dis.cpp diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/SectionSizes.cpp b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/SectionSizes.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/SectionSizes.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/SectionSizes.cpp diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/Statistics.cpp b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/Statistics.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/Statistics.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/Statistics.cpp diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/fuzzer/llvm-dwarfdump-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/fuzzer/llvm-dwarfdump-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/fuzzer/llvm-dwarfdump-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/fuzzer/llvm-dwarfdump-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/llvm-dwarfdump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp diff --git a/interpreter/llvm/src/tools/llvm-dwarfdump/llvm-dwarfdump.h b/interpreter/llvm-project/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwarfdump/llvm-dwarfdump.h rename to interpreter/llvm-project/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.h diff --git a/interpreter/llvm/src/tools/llvm-dwp/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-dwp/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwp/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-dwp/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-dwp/llvm-dwp.cpp b/interpreter/llvm-project/llvm/tools/llvm-dwp/llvm-dwp.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-dwp/llvm-dwp.cpp rename to interpreter/llvm-project/llvm/tools/llvm-dwp/llvm-dwp.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/AArch64/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/AArch64/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/AArch64/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/AArch64/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/AArch64/Target.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/AArch64/Target.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/AArch64/Target.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/AArch64/Target.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Analysis.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Analysis.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Analysis.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Analysis.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Analysis.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Analysis.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Analysis.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Analysis.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Assembler.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Assembler.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Assembler.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Assembler.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Assembler.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Assembler.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Assembler.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Assembler.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkCode.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkCode.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkCode.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkCode.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkResult.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkResult.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkResult.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkResult.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkResult.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkResult.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkRunner.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkRunner.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkRunner.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkRunner.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkRunner.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkRunner.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/BenchmarkRunner.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/BenchmarkRunner.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Clustering.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Clustering.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Clustering.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Clustering.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Clustering.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Clustering.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Clustering.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Clustering.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/CodeTemplate.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/CodeTemplate.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/CodeTemplate.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CodeTemplate.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/CodeTemplate.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/CodeTemplate.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Error.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Error.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Error.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Error.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Error.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Error.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Error.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Error.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/LlvmState.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LlvmState.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/LlvmState.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LlvmState.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/LlvmState.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LlvmState.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/LlvmState.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/LlvmState.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/MCInstrDescView.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/MCInstrDescView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/MCInstrDescView.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/MCInstrDescView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/MCInstrDescView.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/MCInstrDescView.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Mips/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Mips/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Mips/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Mips/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Mips/Target.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Mips/Target.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Mips/Target.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Mips/Target.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/ParallelSnippetGenerator.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/ParallelSnippetGenerator.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/ParallelSnippetGenerator.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/ParallelSnippetGenerator.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/ParallelSnippetGenerator.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/ParallelSnippetGenerator.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/ParallelSnippetGenerator.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/ParallelSnippetGenerator.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/PerfHelper.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PerfHelper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/PerfHelper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PerfHelper.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/PerfHelper.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PerfHelper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/PerfHelper.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PerfHelper.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/PowerPC/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PowerPC/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/PowerPC/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PowerPC/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/PowerPC/Target.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PowerPC/Target.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/PowerPC/Target.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/PowerPC/Target.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterAliasing.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterAliasing.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterAliasing.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterAliasing.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterAliasing.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterAliasing.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterAliasing.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterAliasing.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterValue.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterValue.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterValue.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterValue.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterValue.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterValue.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/RegisterValue.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/RegisterValue.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SchedClassResolution.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SchedClassResolution.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SchedClassResolution.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SchedClassResolution.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SchedClassResolution.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SchedClassResolution.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SchedClassResolution.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SchedClassResolution.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SerialSnippetGenerator.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SerialSnippetGenerator.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SerialSnippetGenerator.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SerialSnippetGenerator.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SerialSnippetGenerator.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SerialSnippetGenerator.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SerialSnippetGenerator.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SerialSnippetGenerator.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetFile.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetFile.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetFile.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetFile.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetFile.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetFile.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetGenerator.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetGenerator.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetGenerator.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetGenerator.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetGenerator.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetGenerator.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetGenerator.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetGenerator.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetRepetitor.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetRepetitor.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetRepetitor.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetRepetitor.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetRepetitor.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetRepetitor.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/SnippetRepetitor.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/SnippetRepetitor.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Target.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Target.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Target.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Target.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/Target.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Target.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/Target.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/Target.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/TargetSelect.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/TargetSelect.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/TargetSelect.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/TargetSelect.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/UopsBenchmarkRunner.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/UopsBenchmarkRunner.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/UopsBenchmarkRunner.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/UopsBenchmarkRunner.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/UopsBenchmarkRunner.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/UopsBenchmarkRunner.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/UopsBenchmarkRunner.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/UopsBenchmarkRunner.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/X86/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/X86/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/X86/Target.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/Target.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/X86/Target.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/Target.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/X86/X86Counter.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/X86Counter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/X86/X86Counter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/X86Counter.cpp diff --git a/interpreter/llvm/src/tools/llvm-exegesis/lib/X86/X86Counter.h b/interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/X86Counter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/lib/X86/X86Counter.h rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/lib/X86/X86Counter.h diff --git a/interpreter/llvm/src/tools/llvm-exegesis/llvm-exegesis.cpp b/interpreter/llvm-project/llvm/tools/llvm-exegesis/llvm-exegesis.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-exegesis/llvm-exegesis.cpp rename to interpreter/llvm-project/llvm/tools/llvm-exegesis/llvm-exegesis.cpp diff --git a/interpreter/llvm/src/tools/llvm-extract/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-extract/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-extract/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-extract/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-extract/llvm-extract.cpp b/interpreter/llvm-project/llvm/tools/llvm-extract/llvm-extract.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-extract/llvm-extract.cpp rename to interpreter/llvm-project/llvm/tools/llvm-extract/llvm-extract.cpp diff --git a/interpreter/llvm/src/tools/llvm-go/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-go/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-go/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-go/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-go/llvm-go.go b/interpreter/llvm-project/llvm/tools/llvm-go/llvm-go.go similarity index 100% rename from interpreter/llvm/src/tools/llvm-go/llvm-go.go rename to interpreter/llvm-project/llvm/tools/llvm-go/llvm-go.go diff --git a/interpreter/llvm/src/tools/llvm-gsymutil/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-gsymutil/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-gsymutil/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-gsymutil/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-gsymutil/llvm-gsymutil.cpp b/interpreter/llvm-project/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-gsymutil/llvm-gsymutil.cpp rename to interpreter/llvm-project/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp diff --git a/interpreter/llvm/src/tools/llvm-ifs/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-ifs/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-ifs/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-ifs/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-ifs/ErrorCollector.cpp b/interpreter/llvm-project/llvm/tools/llvm-ifs/ErrorCollector.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-ifs/ErrorCollector.cpp rename to interpreter/llvm-project/llvm/tools/llvm-ifs/ErrorCollector.cpp diff --git a/interpreter/llvm/src/tools/llvm-ifs/ErrorCollector.h b/interpreter/llvm-project/llvm/tools/llvm-ifs/ErrorCollector.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-ifs/ErrorCollector.h rename to interpreter/llvm-project/llvm/tools/llvm-ifs/ErrorCollector.h diff --git a/interpreter/llvm/src/tools/llvm-ifs/llvm-ifs.cpp b/interpreter/llvm-project/llvm/tools/llvm-ifs/llvm-ifs.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-ifs/llvm-ifs.cpp rename to interpreter/llvm-project/llvm/tools/llvm-ifs/llvm-ifs.cpp diff --git a/interpreter/llvm/src/tools/llvm-isel-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-isel-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-isel-fuzzer/DummyISelFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/DummyISelFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-isel-fuzzer/DummyISelFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/DummyISelFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/DummyDemanglerFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/DummyDemanglerFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/DummyDemanglerFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/DummyDemanglerFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/llvm-itanium-demangle-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/llvm-itanium-demangle-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-itanium-demangle-fuzzer/llvm-itanium-demangle-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-itanium-demangle-fuzzer/llvm-itanium-demangle-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-jitlink/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-jitlink/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-elf.cpp b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-elf.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-elf.cpp rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-elf.cpp diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-executor/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-executor/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-executor/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-executor/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-executor/llvm-jitlink-executor.cpp b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-executor/llvm-jitlink-executor.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-executor/llvm-jitlink-executor.cpp rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-executor/llvm-jitlink-executor.cpp diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-macho.cpp b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-macho.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink-macho.cpp rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink-macho.cpp diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink.cpp b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink.cpp rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink.cpp diff --git a/interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink.h b/interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlink/llvm-jitlink.h rename to interpreter/llvm-project/llvm/tools/llvm-jitlink/llvm-jitlink.h diff --git a/interpreter/llvm/src/tools/llvm-jitlistener/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-jitlistener/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlistener/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-jitlistener/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-jitlistener/llvm-jitlistener.cpp b/interpreter/llvm-project/llvm/tools/llvm-jitlistener/llvm-jitlistener.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-jitlistener/llvm-jitlistener.cpp rename to interpreter/llvm-project/llvm/tools/llvm-jitlistener/llvm-jitlistener.cpp diff --git a/interpreter/llvm/src/tools/llvm-libtool-darwin/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-libtool-darwin/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-libtool-darwin/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-libtool-darwin/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp b/interpreter/llvm-project/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp rename to interpreter/llvm-project/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp diff --git a/interpreter/llvm/src/tools/llvm-link/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-link/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-link/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-link/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-link/llvm-link.cpp b/interpreter/llvm-project/llvm/tools/llvm-link/llvm-link.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-link/llvm-link.cpp rename to interpreter/llvm-project/llvm/tools/llvm-link/llvm-link.cpp diff --git a/interpreter/llvm/src/tools/llvm-lipo/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-lipo/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-lipo/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-lipo/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-lipo/LipoOpts.td b/interpreter/llvm-project/llvm/tools/llvm-lipo/LipoOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-lipo/LipoOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-lipo/LipoOpts.td diff --git a/interpreter/llvm/src/tools/llvm-lipo/llvm-lipo.cpp b/interpreter/llvm-project/llvm/tools/llvm-lipo/llvm-lipo.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-lipo/llvm-lipo.cpp rename to interpreter/llvm-project/llvm/tools/llvm-lipo/llvm-lipo.cpp diff --git a/interpreter/llvm/src/tools/llvm-lto/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-lto/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-lto/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-lto/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-lto/llvm-lto.cpp b/interpreter/llvm-project/llvm/tools/llvm-lto/llvm-lto.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-lto/llvm-lto.cpp rename to interpreter/llvm-project/llvm/tools/llvm-lto/llvm-lto.cpp diff --git a/interpreter/llvm/src/tools/llvm-lto2/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-lto2/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-lto2/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-lto2/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-lto2/llvm-lto2.cpp b/interpreter/llvm-project/llvm/tools/llvm-lto2/llvm-lto2.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-lto2/llvm-lto2.cpp rename to interpreter/llvm-project/llvm/tools/llvm-lto2/llvm-lto2.cpp diff --git a/interpreter/llvm/src/tools/llvm-mc-assemble-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mc-assemble-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc-assemble-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mc-assemble-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-mc-disassemble-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mc-disassemble-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc-disassemble-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mc-disassemble-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mc-disassemble-fuzzer/llvm-mc-disassemble-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-mc-disassemble-fuzzer/llvm-mc-disassemble-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc-disassemble-fuzzer/llvm-mc-disassemble-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mc-disassemble-fuzzer/llvm-mc-disassemble-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-mc/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mc/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mc/Disassembler.cpp b/interpreter/llvm-project/llvm/tools/llvm-mc/Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc/Disassembler.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mc/Disassembler.cpp diff --git a/interpreter/llvm/src/tools/llvm-mc/Disassembler.h b/interpreter/llvm-project/llvm/tools/llvm-mc/Disassembler.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc/Disassembler.h rename to interpreter/llvm-project/llvm/tools/llvm-mc/Disassembler.h diff --git a/interpreter/llvm/src/tools/llvm-mc/llvm-mc.cpp b/interpreter/llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mc/llvm-mc.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mca/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mca/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mca/CodeRegion.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegion.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/CodeRegion.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegion.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/CodeRegion.h b/interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegion.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/CodeRegion.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegion.h diff --git a/interpreter/llvm/src/tools/llvm-mca/CodeRegionGenerator.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegionGenerator.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/CodeRegionGenerator.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegionGenerator.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/CodeRegionGenerator.h b/interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegionGenerator.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/CodeRegionGenerator.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/CodeRegionGenerator.h diff --git a/interpreter/llvm/src/tools/llvm-mca/PipelinePrinter.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/PipelinePrinter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/PipelinePrinter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/PipelinePrinter.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/PipelinePrinter.h b/interpreter/llvm-project/llvm/tools/llvm-mca/PipelinePrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/PipelinePrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/PipelinePrinter.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/BottleneckAnalysis.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/BottleneckAnalysis.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/BottleneckAnalysis.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/BottleneckAnalysis.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/BottleneckAnalysis.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/BottleneckAnalysis.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/BottleneckAnalysis.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/BottleneckAnalysis.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/DispatchStatistics.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/DispatchStatistics.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/DispatchStatistics.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/DispatchStatistics.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/DispatchStatistics.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/DispatchStatistics.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/DispatchStatistics.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/DispatchStatistics.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/InstructionInfoView.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/InstructionInfoView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/InstructionInfoView.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionInfoView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/InstructionInfoView.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionInfoView.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/InstructionView.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/InstructionView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionView.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/InstructionView.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/InstructionView.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/InstructionView.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/RegisterFileStatistics.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/RegisterFileStatistics.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/RegisterFileStatistics.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/RegisterFileStatistics.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/RegisterFileStatistics.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/RegisterFileStatistics.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/RegisterFileStatistics.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/RegisterFileStatistics.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/ResourcePressureView.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/ResourcePressureView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/ResourcePressureView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/ResourcePressureView.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/ResourcePressureView.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/ResourcePressureView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/ResourcePressureView.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/ResourcePressureView.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/RetireControlUnitStatistics.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/RetireControlUnitStatistics.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/RetireControlUnitStatistics.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/RetireControlUnitStatistics.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/RetireControlUnitStatistics.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/RetireControlUnitStatistics.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/RetireControlUnitStatistics.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/RetireControlUnitStatistics.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/SchedulerStatistics.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/SchedulerStatistics.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/SchedulerStatistics.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/SchedulerStatistics.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/SchedulerStatistics.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/SchedulerStatistics.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/SchedulerStatistics.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/SchedulerStatistics.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/SummaryView.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/SummaryView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/SummaryView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/SummaryView.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/SummaryView.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/SummaryView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/SummaryView.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/SummaryView.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/TimelineView.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/TimelineView.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/TimelineView.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/TimelineView.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/TimelineView.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/TimelineView.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/TimelineView.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/TimelineView.h diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/View.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/View.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/View.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/View.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/Views/View.h b/interpreter/llvm-project/llvm/tools/llvm-mca/Views/View.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/Views/View.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/Views/View.h diff --git a/interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.cpp diff --git a/interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.h b/interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.h rename to interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/AMDGPUCustomBehaviour.h diff --git a/interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/lib/AMDGPU/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mca/lib/AMDGPU/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mca/lib/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mca/lib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/lib/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mca/lib/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mca/llvm-mca.cpp b/interpreter/llvm-project/llvm/tools/llvm-mca/llvm-mca.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mca/llvm-mca.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mca/llvm-mca.cpp diff --git a/interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/DummyDemanglerFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/DummyDemanglerFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/DummyDemanglerFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/DummyDemanglerFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/llvm-microsoft-demangle-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/llvm-microsoft-demangle-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-microsoft-demangle-fuzzer/llvm-microsoft-demangle-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-microsoft-demangle-fuzzer/llvm-microsoft-demangle-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-ml/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-ml/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-ml/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-ml/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-ml/Disassembler.cpp b/interpreter/llvm-project/llvm/tools/llvm-ml/Disassembler.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-ml/Disassembler.cpp rename to interpreter/llvm-project/llvm/tools/llvm-ml/Disassembler.cpp diff --git a/interpreter/llvm/src/tools/llvm-ml/Disassembler.h b/interpreter/llvm-project/llvm/tools/llvm-ml/Disassembler.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-ml/Disassembler.h rename to interpreter/llvm-project/llvm/tools/llvm-ml/Disassembler.h diff --git a/interpreter/llvm/src/tools/llvm-ml/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-ml/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-ml/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-ml/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-ml/llvm-ml.cpp b/interpreter/llvm-project/llvm/tools/llvm-ml/llvm-ml.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-ml/llvm-ml.cpp rename to interpreter/llvm-project/llvm/tools/llvm-ml/llvm-ml.cpp diff --git a/interpreter/llvm/src/tools/llvm-modextract/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-modextract/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-modextract/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-modextract/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-modextract/llvm-modextract.cpp b/interpreter/llvm-project/llvm/tools/llvm-modextract/llvm-modextract.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-modextract/llvm-modextract.cpp rename to interpreter/llvm-project/llvm/tools/llvm-modextract/llvm-modextract.cpp diff --git a/interpreter/llvm/src/tools/llvm-mt/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-mt/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-mt/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-mt/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-mt/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-mt/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-mt/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-mt/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-mt/llvm-mt.cpp b/interpreter/llvm-project/llvm/tools/llvm-mt/llvm-mt.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-mt/llvm-mt.cpp rename to interpreter/llvm-project/llvm/tools/llvm-mt/llvm-mt.cpp diff --git a/interpreter/llvm/src/tools/llvm-nm/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-nm/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-nm/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-nm/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-nm/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-nm/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-nm/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-nm/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-nm/llvm-nm.cpp b/interpreter/llvm-project/llvm/tools/llvm-nm/llvm-nm.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-nm/llvm-nm.cpp rename to interpreter/llvm-project/llvm/tools/llvm-nm/llvm-nm.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/BitcodeStripOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objcopy/BitcodeStripOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/BitcodeStripOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/BitcodeStripOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objcopy/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-objcopy/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFObjcopy.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFObjcopy.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFObjcopy.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/COFFObjcopy.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Object.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Object.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Object.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Object.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Object.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Object.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Object.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Object.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Reader.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Reader.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Reader.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Reader.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Reader.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Reader.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Reader.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Reader.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Writer.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Writer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Writer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Writer.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/COFF/Writer.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Writer.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/COFF/Writer.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/COFF/Writer.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/CommonConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/CommonConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/CommonConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/CommonConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/CommonOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objcopy/CommonOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/CommonOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/CommonOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ConfigManager.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ConfigManager.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ConfigManager.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ConfigManager.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ConfigManager.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ConfigManager.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ConfigManager.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ConfigManager.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFObjcopy.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFObjcopy.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFObjcopy.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ELF/ELFObjcopy.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ELF/Object.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/Object.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ELF/Object.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/Object.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ELF/Object.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/Object.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ELF/Object.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ELF/Object.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/InstallNameToolOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objcopy/InstallNameToolOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/InstallNameToolOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/InstallNameToolOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOLayoutBuilder.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOLayoutBuilder.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOLayoutBuilder.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOLayoutBuilder.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOLayoutBuilder.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOLayoutBuilder.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOLayoutBuilder.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOLayoutBuilder.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOObjcopy.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOObjcopy.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOObjcopy.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOObjcopy.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOReader.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOReader.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOReader.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOReader.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOReader.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOReader.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOWriter.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOWriter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOWriter.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOWriter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/MachOWriter.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/MachOWriter.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/Object.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/Object.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/Object.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/Object.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MachO/Object.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/Object.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MachO/Object.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MachO/Object.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/MultiFormatConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/MultiFormatConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/MultiFormatConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/MultiFormatConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/ObjcopyOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objcopy/ObjcopyOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/ObjcopyOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/ObjcopyOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objcopy/StripOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objcopy/StripOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/StripOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/StripOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objcopy/llvm-objcopy.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/llvm-objcopy.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/llvm-objcopy.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/llvm-objcopy.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Object.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Object.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Object.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Object.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Object.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Object.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Object.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Object.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Reader.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Reader.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Reader.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Reader.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Reader.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Reader.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Reader.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Reader.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmConfig.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmConfig.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmConfig.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmConfig.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmObjcopy.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmObjcopy.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmObjcopy.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/WasmObjcopy.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.h diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Writer.cpp b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Writer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Writer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Writer.cpp diff --git a/interpreter/llvm/src/tools/llvm-objcopy/wasm/Writer.h b/interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Writer.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objcopy/wasm/Writer.h rename to interpreter/llvm-project/llvm/tools/llvm-objcopy/wasm/Writer.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-objdump/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-objdump/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-objdump/COFFDump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/COFFDump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/COFFDump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/COFFDump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/COFFDump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/COFFDump.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/ELFDump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/ELFDump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/ELFDump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/ELFDump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/ELFDump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/ELFDump.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/MachODump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/MachODump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/MachODump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/MachODump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/MachODump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/MachODump.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/ObjdumpOptID.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/ObjdumpOptID.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/ObjdumpOptID.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/ObjdumpOptID.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/ObjdumpOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objdump/ObjdumpOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/ObjdumpOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objdump/ObjdumpOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objdump/OtoolOpts.td b/interpreter/llvm-project/llvm/tools/llvm-objdump/OtoolOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/OtoolOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-objdump/OtoolOpts.td diff --git a/interpreter/llvm/src/tools/llvm-objdump/SourcePrinter.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/SourcePrinter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/SourcePrinter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/SourcePrinter.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/SourcePrinter.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/SourcePrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/SourcePrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/SourcePrinter.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/WasmDump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/WasmDump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/WasmDump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/WasmDump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/WasmDump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/WasmDump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/WasmDump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/WasmDump.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/XCOFFDump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/XCOFFDump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/XCOFFDump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/XCOFFDump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/XCOFFDump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/XCOFFDump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/XCOFFDump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/XCOFFDump.h diff --git a/interpreter/llvm/src/tools/llvm-objdump/llvm-objdump.cpp b/interpreter/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/llvm-objdump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp diff --git a/interpreter/llvm/src/tools/llvm-objdump/llvm-objdump.h b/interpreter/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-objdump/llvm-objdump.h rename to interpreter/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h diff --git a/interpreter/llvm/src/tools/llvm-opt-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-opt-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-opt-fuzzer/DummyOptFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/DummyOptFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-opt-fuzzer/DummyOptFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/DummyOptFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-opt-report/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-opt-report/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-opt-report/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-opt-report/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-opt-report/OptReport.cpp b/interpreter/llvm-project/llvm/tools/llvm-opt-report/OptReport.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-opt-report/OptReport.cpp rename to interpreter/llvm-project/llvm/tools/llvm-opt-report/OptReport.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/BytesOutputStyle.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/BytesOutputStyle.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/BytesOutputStyle.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/BytesOutputStyle.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/BytesOutputStyle.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/BytesOutputStyle.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/BytesOutputStyle.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/BytesOutputStyle.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/DumpOutputStyle.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/DumpOutputStyle.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/DumpOutputStyle.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/DumpOutputStyle.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/DumpOutputStyle.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/DumpOutputStyle.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/ExplainOutputStyle.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/ExplainOutputStyle.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/ExplainOutputStyle.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/ExplainOutputStyle.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/ExplainOutputStyle.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/ExplainOutputStyle.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/ExplainOutputStyle.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/ExplainOutputStyle.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/FormatUtil.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/FormatUtil.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/FormatUtil.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/FormatUtil.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/FormatUtil.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/FormatUtil.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/FormatUtil.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/FormatUtil.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/InputFile.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/InputFile.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/InputFile.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/InputFile.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/InputFile.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/InputFile.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/InputFile.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/InputFile.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/LinePrinter.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/LinePrinter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/LinePrinter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/LinePrinter.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/LinePrinter.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/LinePrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/LinePrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/LinePrinter.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/MinimalSymbolDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/MinimalSymbolDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/MinimalSymbolDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/MinimalSymbolDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalSymbolDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/MinimalTypeDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/MinimalTypeDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/MinimalTypeDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalTypeDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/MinimalTypeDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/MinimalTypeDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/OutputStyle.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/OutputStyle.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/OutputStyle.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/OutputStyle.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PdbYaml.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PdbYaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PdbYaml.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PdbYaml.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PdbYaml.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PdbYaml.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PdbYaml.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PdbYaml.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyBuiltinDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyBuiltinDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyBuiltinDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyBuiltinDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyBuiltinDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyBuiltinDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyBuiltinDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyBuiltinDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassDefinitionDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassDefinitionDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassDefinitionDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassDefinitionDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassDefinitionDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassDefinitionDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassDefinitionDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassDefinitionDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyCompilandDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyCompilandDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyCompilandDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyCompilandDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyCompilandDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyCompilandDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyCompilandDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyCompilandDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyEnumDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyEnumDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyEnumDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyEnumDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyEnumDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyEnumDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyEnumDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyEnumDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyExternalSymbolDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyExternalSymbolDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyExternalSymbolDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyExternalSymbolDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyExternalSymbolDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyExternalSymbolDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyExternalSymbolDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyExternalSymbolDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyFunctionDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyFunctionDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyFunctionDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyFunctionDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyFunctionDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyFunctionDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyFunctionDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyFunctionDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypeDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypeDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypeDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypeDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypeDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypeDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypeDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypeDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypedefDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypedefDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypedefDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypedefDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypedefDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypedefDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyTypedefDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyTypedefDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyVariableDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyVariableDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyVariableDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyVariableDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/PrettyVariableDumper.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyVariableDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/PrettyVariableDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/PrettyVariableDumper.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/StreamUtil.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/StreamUtil.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/StreamUtil.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/StreamUtil.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/StreamUtil.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/StreamUtil.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/StreamUtil.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/StreamUtil.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/TypeReferenceTracker.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/TypeReferenceTracker.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/TypeReferenceTracker.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/TypeReferenceTracker.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/TypeReferenceTracker.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/TypeReferenceTracker.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/TypeReferenceTracker.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/TypeReferenceTracker.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/YAMLOutputStyle.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/YAMLOutputStyle.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/YAMLOutputStyle.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/YAMLOutputStyle.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/YAMLOutputStyle.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/YAMLOutputStyle.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/YAMLOutputStyle.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/YAMLOutputStyle.h diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/llvm-pdbutil.cpp b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/llvm-pdbutil.cpp rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp diff --git a/interpreter/llvm/src/tools/llvm-pdbutil/llvm-pdbutil.h b/interpreter/llvm-project/llvm/tools/llvm-pdbutil/llvm-pdbutil.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-pdbutil/llvm-pdbutil.h rename to interpreter/llvm-project/llvm/tools/llvm-pdbutil/llvm-pdbutil.h diff --git a/interpreter/llvm/src/tools/llvm-profdata/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-profdata/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-profdata/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-profdata/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-profdata/llvm-profdata.cpp b/interpreter/llvm-project/llvm/tools/llvm-profdata/llvm-profdata.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profdata/llvm-profdata.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profdata/llvm-profdata.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-profgen/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-profgen/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-profgen/CSPreInliner.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/CSPreInliner.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/CSPreInliner.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/CSPreInliner.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/CSPreInliner.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/CSPreInliner.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/CSPreInliner.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/CSPreInliner.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/CallContext.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/CallContext.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/CallContext.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/CallContext.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/ErrorHandling.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/ErrorHandling.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/ErrorHandling.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/ErrorHandling.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/PerfReader.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/PerfReader.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/PerfReader.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/PerfReader.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/PerfReader.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/PerfReader.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/PerfReader.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/PerfReader.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/ProfileGenerator.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/ProfileGenerator.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/ProfileGenerator.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/ProfileGenerator.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/ProfileGenerator.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/ProfileGenerator.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/ProfileGenerator.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/ProfileGenerator.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/ProfiledBinary.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/ProfiledBinary.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/ProfiledBinary.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/ProfiledBinary.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/ProfiledBinary.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/ProfiledBinary.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/ProfiledBinary.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/ProfiledBinary.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/PseudoProbe.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/PseudoProbe.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/PseudoProbe.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/PseudoProbe.cpp diff --git a/interpreter/llvm/src/tools/llvm-profgen/PseudoProbe.h b/interpreter/llvm-project/llvm/tools/llvm-profgen/PseudoProbe.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/PseudoProbe.h rename to interpreter/llvm-project/llvm/tools/llvm-profgen/PseudoProbe.h diff --git a/interpreter/llvm/src/tools/llvm-profgen/llvm-profgen.cpp b/interpreter/llvm-project/llvm/tools/llvm-profgen/llvm-profgen.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-profgen/llvm-profgen.cpp rename to interpreter/llvm-project/llvm/tools/llvm-profgen/llvm-profgen.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-rc/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-rc/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-rc/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-rc/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-rc/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceFileWriter.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceFileWriter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceFileWriter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceFileWriter.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceFileWriter.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceFileWriter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceFileWriter.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceFileWriter.h diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptCppFilter.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptCppFilter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptCppFilter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptCppFilter.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptCppFilter.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptCppFilter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptCppFilter.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptCppFilter.h diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptParser.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptParser.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptParser.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptParser.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.h diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptStmt.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptStmt.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptStmt.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptStmt.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptStmt.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptStmt.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptStmt.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptStmt.h diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptToken.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptToken.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptToken.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptToken.cpp diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptToken.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptToken.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptToken.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptToken.h diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceScriptTokenList.def b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptTokenList.def similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceScriptTokenList.def rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceScriptTokenList.def diff --git a/interpreter/llvm/src/tools/llvm-rc/ResourceVisitor.h b/interpreter/llvm-project/llvm/tools/llvm-rc/ResourceVisitor.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/ResourceVisitor.h rename to interpreter/llvm-project/llvm/tools/llvm-rc/ResourceVisitor.h diff --git a/interpreter/llvm/src/tools/llvm-rc/WindresOpts.td b/interpreter/llvm-project/llvm/tools/llvm-rc/WindresOpts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/WindresOpts.td rename to interpreter/llvm-project/llvm/tools/llvm-rc/WindresOpts.td diff --git a/interpreter/llvm/src/tools/llvm-rc/llvm-rc.cpp b/interpreter/llvm-project/llvm/tools/llvm-rc/llvm-rc.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rc/llvm-rc.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rc/llvm-rc.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/ARMEHABIPrinter.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/ARMEHABIPrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ARMEHABIPrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ARMEHABIPrinter.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/ARMWinEHPrinter.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ARMWinEHPrinter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/ARMWinEHPrinter.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/ARMWinEHPrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ARMWinEHPrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ARMWinEHPrinter.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-readobj/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-readobj/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-readobj/COFFDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/COFFDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/COFFDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/COFFDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/COFFImportDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/COFFImportDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/COFFImportDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/COFFImportDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/DwarfCFIEHPrinter.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/DwarfCFIEHPrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/DwarfCFIEHPrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/DwarfCFIEHPrinter.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/ELFDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/ELFDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ELFDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ELFDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/MachODumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/MachODumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/MachODumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/MachODumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/ObjDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/ObjDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ObjDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ObjDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/ObjDumper.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/ObjDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/ObjDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/ObjDumper.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-readobj/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-readobj/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-readobj/StackMapPrinter.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/StackMapPrinter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/StackMapPrinter.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/StackMapPrinter.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/WasmDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/WasmDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/WasmDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/WasmDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/Win64EHDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/Win64EHDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/Win64EHDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/Win64EHDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/Win64EHDumper.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/Win64EHDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/Win64EHDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/Win64EHDumper.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/WindowsResourceDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/WindowsResourceDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/WindowsResourceDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/WindowsResourceDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/WindowsResourceDumper.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/WindowsResourceDumper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/WindowsResourceDumper.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/WindowsResourceDumper.h diff --git a/interpreter/llvm/src/tools/llvm-readobj/XCOFFDumper.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/XCOFFDumper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/XCOFFDumper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/XCOFFDumper.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/llvm-readobj.cpp b/interpreter/llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/llvm-readobj.cpp rename to interpreter/llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp diff --git a/interpreter/llvm/src/tools/llvm-readobj/llvm-readobj.h b/interpreter/llvm-project/llvm/tools/llvm-readobj/llvm-readobj.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-readobj/llvm-readobj.h rename to interpreter/llvm-project/llvm/tools/llvm-readobj/llvm-readobj.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-reduce/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-reduce/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-reduce/DeltaManager.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/DeltaManager.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/DeltaManager.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/DeltaManager.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/DeltaManager.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/DeltaManager.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/DeltaManager.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/DeltaManager.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/TestRunner.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/TestRunner.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/TestRunner.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/TestRunner.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/TestRunner.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/TestRunner.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/TestRunner.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/TestRunner.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/Delta.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/Delta.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/Delta.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/Delta.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/Delta.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/Delta.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/Delta.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/Delta.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAliases.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAliases.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAliases.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAliases.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAliases.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAliases.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAliases.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAliases.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceArguments.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceArguments.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceArguments.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceArguments.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceArguments.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceArguments.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceArguments.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceArguments.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAttributes.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAttributes.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAttributes.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAttributes.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceAttributes.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceAttributes.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceBasicBlocks.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceBasicBlocks.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctionBodies.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctionBodies.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctionBodies.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctionBodies.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctionBodies.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctionBodies.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctionBodies.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctionBodies.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctions.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctions.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctions.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctions.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctions.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctions.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceFunctions.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceFunctions.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalValues.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalValues.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalValues.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalValues.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalValues.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalValues.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalValues.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalValues.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVarInitializers.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVars.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceGlobalVars.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceInstructions.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceInstructions.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceInstructions.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceInstructions.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceInstructions.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceInstructions.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceMetadata.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceMetadata.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceMetadata.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceMetadata.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceMetadata.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceMetadata.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceMetadata.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceMetadata.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceModuleInlineAsm.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceOperandBundles.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceOperandBundles.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceOperandBundles.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceOperandBundles.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceOperandBundles.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceOperandBundles.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceOperandBundles.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceOperandBundles.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceSpecialGlobals.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceSpecialGlobals.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceSpecialGlobals.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceSpecialGlobals.cpp diff --git a/interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceSpecialGlobals.h b/interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceSpecialGlobals.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/deltas/ReduceSpecialGlobals.h rename to interpreter/llvm-project/llvm/tools/llvm-reduce/deltas/ReduceSpecialGlobals.h diff --git a/interpreter/llvm/src/tools/llvm-reduce/llvm-reduce.cpp b/interpreter/llvm-project/llvm/tools/llvm-reduce/llvm-reduce.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-reduce/llvm-reduce.cpp rename to interpreter/llvm-project/llvm/tools/llvm-reduce/llvm-reduce.cpp diff --git a/interpreter/llvm/src/tools/llvm-rtdyld/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-rtdyld/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-rtdyld/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-rtdyld/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-rtdyld/llvm-rtdyld.cpp b/interpreter/llvm-project/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rtdyld/llvm-rtdyld.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp diff --git a/interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/DummyDemanglerFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/DummyDemanglerFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/DummyDemanglerFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/DummyDemanglerFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/llvm-rust-demangle-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/llvm-rust-demangle-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-rust-demangle-fuzzer/llvm-rust-demangle-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-rust-demangle-fuzzer/llvm-rust-demangle-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-shlib/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-shlib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-shlib/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-shlib/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-shlib/gen-msvc-exports.py b/interpreter/llvm-project/llvm/tools/llvm-shlib/gen-msvc-exports.py similarity index 100% rename from interpreter/llvm/src/tools/llvm-shlib/gen-msvc-exports.py rename to interpreter/llvm-project/llvm/tools/llvm-shlib/gen-msvc-exports.py diff --git a/interpreter/llvm/src/tools/llvm-shlib/libllvm.cpp b/interpreter/llvm-project/llvm/tools/llvm-shlib/libllvm.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-shlib/libllvm.cpp rename to interpreter/llvm-project/llvm/tools/llvm-shlib/libllvm.cpp diff --git a/interpreter/llvm/src/tools/llvm-shlib/simple_version_script.map.in b/interpreter/llvm-project/llvm/tools/llvm-shlib/simple_version_script.map.in similarity index 100% rename from interpreter/llvm/src/tools/llvm-shlib/simple_version_script.map.in rename to interpreter/llvm-project/llvm/tools/llvm-shlib/simple_version_script.map.in diff --git a/interpreter/llvm/src/tools/llvm-sim/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-sim/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-sim/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-sim/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-sim/llvm-sim.cpp b/interpreter/llvm-project/llvm/tools/llvm-sim/llvm-sim.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-sim/llvm-sim.cpp rename to interpreter/llvm-project/llvm/tools/llvm-sim/llvm-sim.cpp diff --git a/interpreter/llvm/src/tools/llvm-size/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-size/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-size/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-size/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-size/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-size/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-size/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-size/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-size/llvm-size.cpp b/interpreter/llvm-project/llvm/tools/llvm-size/llvm-size.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-size/llvm-size.cpp rename to interpreter/llvm-project/llvm/tools/llvm-size/llvm-size.cpp diff --git a/interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/DummySpecialCaseListFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/DummySpecialCaseListFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/DummySpecialCaseListFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/DummySpecialCaseListFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/special-case-list-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/special-case-list-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-special-case-list-fuzzer/special-case-list-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-special-case-list-fuzzer/special-case-list-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-split/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-split/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-split/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-split/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-split/llvm-split.cpp b/interpreter/llvm-project/llvm/tools/llvm-split/llvm-split.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-split/llvm-split.cpp rename to interpreter/llvm-project/llvm/tools/llvm-split/llvm-split.cpp diff --git a/interpreter/llvm/src/tools/llvm-stress/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-stress/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-stress/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-stress/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-stress/llvm-stress.cpp b/interpreter/llvm-project/llvm/tools/llvm-stress/llvm-stress.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-stress/llvm-stress.cpp rename to interpreter/llvm-project/llvm/tools/llvm-stress/llvm-stress.cpp diff --git a/interpreter/llvm/src/tools/llvm-strings/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-strings/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-strings/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-strings/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-strings/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-strings/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-strings/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-strings/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-strings/llvm-strings.cpp b/interpreter/llvm-project/llvm/tools/llvm-strings/llvm-strings.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-strings/llvm-strings.cpp rename to interpreter/llvm-project/llvm/tools/llvm-strings/llvm-strings.cpp diff --git a/interpreter/llvm/src/tools/llvm-symbolizer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-symbolizer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-symbolizer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-symbolizer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-symbolizer/Opts.td b/interpreter/llvm-project/llvm/tools/llvm-symbolizer/Opts.td similarity index 100% rename from interpreter/llvm/src/tools/llvm-symbolizer/Opts.td rename to interpreter/llvm-project/llvm/tools/llvm-symbolizer/Opts.td diff --git a/interpreter/llvm/src/tools/llvm-symbolizer/llvm-symbolizer.cpp b/interpreter/llvm-project/llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-symbolizer/llvm-symbolizer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp diff --git a/interpreter/llvm/src/tools/llvm-tapi-diff/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-tapi-diff/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-tapi-diff/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-tapi-diff/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-tapi-diff/DiffEngine.cpp b/interpreter/llvm-project/llvm/tools/llvm-tapi-diff/DiffEngine.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-tapi-diff/DiffEngine.cpp rename to interpreter/llvm-project/llvm/tools/llvm-tapi-diff/DiffEngine.cpp diff --git a/interpreter/llvm/src/tools/llvm-tapi-diff/DiffEngine.h b/interpreter/llvm-project/llvm/tools/llvm-tapi-diff/DiffEngine.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-tapi-diff/DiffEngine.h rename to interpreter/llvm-project/llvm/tools/llvm-tapi-diff/DiffEngine.h diff --git a/interpreter/llvm/src/tools/llvm-tapi-diff/llvm-tapi-diff.cpp b/interpreter/llvm-project/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-tapi-diff/llvm-tapi-diff.cpp rename to interpreter/llvm-project/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp diff --git a/interpreter/llvm/src/tools/llvm-undname/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-undname/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-undname/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-undname/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-undname/llvm-undname.cpp b/interpreter/llvm-project/llvm/tools/llvm-undname/llvm-undname.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-undname/llvm-undname.cpp rename to interpreter/llvm-project/llvm/tools/llvm-undname/llvm-undname.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-xray/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-xray/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-xray/func-id-helper.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/func-id-helper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/func-id-helper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/func-id-helper.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/func-id-helper.h b/interpreter/llvm-project/llvm/tools/llvm-xray/func-id-helper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/func-id-helper.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/func-id-helper.h diff --git a/interpreter/llvm/src/tools/llvm-xray/llvm-xray.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/llvm-xray.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/llvm-xray.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/llvm-xray.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/trie-node.h b/interpreter/llvm-project/llvm/tools/llvm-xray/trie-node.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/trie-node.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/trie-node.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-account.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-account.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-account.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-account.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-account.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-account.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-account.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-account.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-color-helper.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-color-helper.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-color-helper.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-color-helper.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-color-helper.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-color-helper.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-color-helper.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-color-helper.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-converter.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-converter.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-converter.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-converter.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-converter.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-converter.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-converter.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-converter.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-extract.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-extract.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-extract.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-extract.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-fdr-dump.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-fdr-dump.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-fdr-dump.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-fdr-dump.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-graph-diff.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph-diff.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-graph-diff.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph-diff.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-graph-diff.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph-diff.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-graph-diff.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph-diff.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-graph.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-graph.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-graph.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-graph.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-graph.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-registry.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-registry.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-registry.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-registry.cpp diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-registry.h b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-registry.h similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-registry.h rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-registry.h diff --git a/interpreter/llvm/src/tools/llvm-xray/xray-stacks.cpp b/interpreter/llvm-project/llvm/tools/llvm-xray/xray-stacks.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-xray/xray-stacks.cpp rename to interpreter/llvm-project/llvm/tools/llvm-xray/xray-stacks.cpp diff --git a/interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/DummyYAMLNumericParserFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/DummyYAMLNumericParserFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/DummyYAMLNumericParserFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/DummyYAMLNumericParserFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/DummyYAMLParserFuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/DummyYAMLParserFuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/DummyYAMLParserFuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/DummyYAMLParserFuzzer.cpp diff --git a/interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/lto/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/lto/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/lto/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/lto/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/lto/LTODisassembler.cpp b/interpreter/llvm-project/llvm/tools/lto/LTODisassembler.cpp similarity index 100% rename from interpreter/llvm/src/tools/lto/LTODisassembler.cpp rename to interpreter/llvm-project/llvm/tools/lto/LTODisassembler.cpp diff --git a/interpreter/llvm/src/tools/lto/lto.cpp b/interpreter/llvm-project/llvm/tools/lto/lto.cpp similarity index 100% rename from interpreter/llvm/src/tools/lto/lto.cpp rename to interpreter/llvm-project/llvm/tools/lto/lto.cpp diff --git a/interpreter/llvm/src/tools/lto/lto.exports b/interpreter/llvm-project/llvm/tools/lto/lto.exports similarity index 100% rename from interpreter/llvm/src/tools/lto/lto.exports rename to interpreter/llvm-project/llvm/tools/lto/lto.exports diff --git a/interpreter/llvm/src/tools/msbuild/.gitignore b/interpreter/llvm-project/llvm/tools/msbuild/.gitignore similarity index 88% rename from interpreter/llvm/src/tools/msbuild/.gitignore rename to interpreter/llvm-project/llvm/tools/msbuild/.gitignore index 19fd4df584396..692d171a21a0a 100644 --- a/interpreter/llvm/src/tools/msbuild/.gitignore +++ b/interpreter/llvm-project/llvm/tools/msbuild/.gitignore @@ -1,6 +1,6 @@ -obj/ -bin/ -.vs/ -Key.snk -packages/ -*.csproj.user +obj/ +bin/ +.vs/ +Key.snk +packages/ +*.csproj.user diff --git a/interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.props b/interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.props similarity index 98% rename from interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.props rename to interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.props index f497470b0aa0c..bc021b3b9e1f8 100644 --- a/interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.props +++ b/interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.props @@ -1,79 +1,79 @@ - - - - - - true - false - - $(IntermediateOutputPath) - $(Configuration)\ - $(SolutionDir)$(Configuration)\ - $(IntDir) - WindowsLocalDebugger - - - - - <_PlatformToolsetShortNameFor_llvm>LLVM - <_PlatformToolsetFriendlyNameFor_llvm>LLVM - - - - - $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\LLVM\LLVM) - $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LLVM\LLVM) - $(LLVMInstallDir)\ - $(LLVMInstallDir)bin\clang-cl.exe - $(LLVMInstallDir)bin\lld-link.exe - $(LLVMInstallDir)bin\llvm-lib.exe - true - true - true - - - - - - - - $(IncludePath);$(VC_IncludePath);$(WindowsSDK_IncludePath); - $(WindowsSDK_MetadataPath); - $(VC_SourcePath); - - - - - - - - Default - - - + + + + + + true + false + + $(IntermediateOutputPath) + $(Configuration)\ + $(SolutionDir)$(Configuration)\ + $(IntDir) + WindowsLocalDebugger + + + + + <_PlatformToolsetShortNameFor_llvm>LLVM + <_PlatformToolsetFriendlyNameFor_llvm>LLVM + + + + + $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\LLVM\LLVM) + $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LLVM\LLVM) + $(LLVMInstallDir)\ + $(LLVMInstallDir)bin\clang-cl.exe + $(LLVMInstallDir)bin\lld-link.exe + $(LLVMInstallDir)bin\llvm-lib.exe + true + true + true + + + + + + + + $(IncludePath);$(VC_IncludePath);$(WindowsSDK_IncludePath); + $(WindowsSDK_MetadataPath); + $(VC_SourcePath); + + + + + + + + Default + + + diff --git a/interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.targets b/interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.targets similarity index 98% rename from interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.targets rename to interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.targets index adf192a2a0680..74a98d6439b45 100644 --- a/interpreter/llvm/src/tools/msbuild/LLVM.Cpp.Common.targets +++ b/interpreter/llvm-project/llvm/tools/msbuild/LLVM.Cpp.Common.targets @@ -1,132 +1,132 @@ - - - - - - $(ClangClExecutable) - $(LldLinkExecutable) - $(LlvmLibExecutable) - - - - - Project - - - - - - - -m$(PlatformArchitecture) $(ClangClAdditionalOptions) %(AdditionalOptions) - - - - - - $(LldLinkAdditionalOptions) %(AdditionalOptions) - - - - - - - - - - - - - - - - - - - - - OldStyle - OldStyle - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Default - - - - - + + + + + + $(ClangClExecutable) + $(LldLinkExecutable) + $(LlvmLibExecutable) + + + + + Project + + + + + + + -m$(PlatformArchitecture) $(ClangClAdditionalOptions) %(AdditionalOptions) + + + + + + $(LldLinkAdditionalOptions) %(AdditionalOptions) + + + + + + + + + + + + + + + + + + + + + OldStyle + OldStyle + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default + + + + + diff --git a/interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.props b/interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.props similarity index 98% rename from interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.props rename to interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.props index aebbee0f8b7d7..4762f4eaa1c8d 100644 --- a/interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.props +++ b/interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.props @@ -1,11 +1,11 @@ - - - - - $(VC_ExecutablePath_x64);$(WindowsSDK_ExecutablePath);$(VS_ExecutablePath);$(MSBuild_ExecutablePath);$(FxCopDir);$(PATH); - $(VC_ReferencesPath_x64); - $(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(NETFXKitsDir)Lib\um\x64 - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x64); - $(VCToolsInstallDir)redist\Debug_NonRedist\x64 - - + + + + + $(VC_ExecutablePath_x64);$(WindowsSDK_ExecutablePath);$(VS_ExecutablePath);$(MSBuild_ExecutablePath);$(FxCopDir);$(PATH); + $(VC_ReferencesPath_x64); + $(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(NETFXKitsDir)Lib\um\x64 + $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x64); + $(VCToolsInstallDir)redist\Debug_NonRedist\x64 + + diff --git a/interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.targets b/interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.targets similarity index 97% rename from interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.targets rename to interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.targets index 6fbdc3eab2f6e..938e03b51e275 100644 --- a/interpreter/llvm/src/tools/msbuild/Platformx64/Toolset.targets +++ b/interpreter/llvm-project/llvm/tools/msbuild/Platformx64/Toolset.targets @@ -1,3 +1,3 @@ - - - + + + diff --git a/interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.props b/interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.props similarity index 98% rename from interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.props rename to interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.props index d03269642e2b0..5a5cd6c736fd9 100644 --- a/interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.props +++ b/interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.props @@ -1,11 +1,11 @@ - - - - - $(VC_ExecutablePath_x86);$(WindowsSDK_ExecutablePath);$(VS_ExecutablePath);$(MSBuild_ExecutablePath);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH); - $(VC_ReferencesPath_x86); - $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 - $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); - $(VCToolsInstallDir)redist\Debug_NonRedist\x86 - - + + + + + $(VC_ExecutablePath_x86);$(WindowsSDK_ExecutablePath);$(VS_ExecutablePath);$(MSBuild_ExecutablePath);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH); + $(VC_ReferencesPath_x86); + $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86 + $(VC_IncludePath);$(WindowsSDK_IncludePath);$(MSBuild_ExecutablePath);$(VC_LibraryPath_x86); + $(VCToolsInstallDir)redist\Debug_NonRedist\x86 + + diff --git a/interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.targets b/interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.targets similarity index 97% rename from interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.targets rename to interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.targets index 6fbdc3eab2f6e..938e03b51e275 100644 --- a/interpreter/llvm/src/tools/msbuild/Platformx86/Toolset.targets +++ b/interpreter/llvm-project/llvm/tools/msbuild/Platformx86/Toolset.targets @@ -1,3 +1,3 @@ - - - + + + diff --git a/interpreter/llvm/src/tools/msbuild/install.bat b/interpreter/llvm-project/llvm/tools/msbuild/install.bat similarity index 100% rename from interpreter/llvm/src/tools/msbuild/install.bat rename to interpreter/llvm-project/llvm/tools/msbuild/install.bat diff --git a/interpreter/llvm/src/tools/msbuild/license.txt b/interpreter/llvm-project/llvm/tools/msbuild/license.txt similarity index 100% rename from interpreter/llvm/src/tools/msbuild/license.txt rename to interpreter/llvm-project/llvm/tools/msbuild/license.txt diff --git a/interpreter/llvm/src/tools/msbuild/llvm-general.xml b/interpreter/llvm-project/llvm/tools/msbuild/llvm-general.xml similarity index 97% rename from interpreter/llvm/src/tools/msbuild/llvm-general.xml rename to interpreter/llvm-project/llvm/tools/msbuild/llvm-general.xml index ced9bd18b0fd5..66a2cfec0b4cb 100644 --- a/interpreter/llvm/src/tools/msbuild/llvm-general.xml +++ b/interpreter/llvm-project/llvm/tools/msbuild/llvm-general.xml @@ -1,76 +1,76 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interpreter/llvm/src/tools/msbuild/llvm.csproj b/interpreter/llvm-project/llvm/tools/msbuild/llvm.csproj similarity index 97% rename from interpreter/llvm/src/tools/msbuild/llvm.csproj rename to interpreter/llvm-project/llvm/tools/msbuild/llvm.csproj index 9810a01eb0cb2..39e898d736827 100644 --- a/interpreter/llvm/src/tools/msbuild/llvm.csproj +++ b/interpreter/llvm-project/llvm/tools/msbuild/llvm.csproj @@ -1,97 +1,97 @@ - - - - 15.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - Debug - AnyCPU - 2.0 - {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - {62530D9E-1B24-4C31-8DC9-AE47E9E5DC53} - Library - Properties - llvm - llvm - v4.6.1 - false - false - false - false - false - false - Program - $(DevEnvDir)devenv.exe - /rootsuffix Exp - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - true - VCTargets - 1033 - - - true - VCTargets - - - Always - true - - - true - VCTargets - - - Designer - - - - true - VCTargets - Platforms\x64\PlatformToolsets\llvm - - - true - VCTargets - Platforms\x64\PlatformToolsets\llvm - - - true - VCTargets - Platforms\Win32\PlatformToolsets\llvm - - - true - VCTargets - Platforms\Win32\PlatformToolsets\llvm - - - - - - - - - if not exist $(ProjectDir)Key.snk ("$(TargetFrameworkSDKToolsDirectory)\x64\sn.exe" -k $(ProjectDir)Key.snk) - + + + + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + Debug + AnyCPU + 2.0 + {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + {62530D9E-1B24-4C31-8DC9-AE47E9E5DC53} + Library + Properties + llvm + llvm + v4.6.1 + false + false + false + false + false + false + Program + $(DevEnvDir)devenv.exe + /rootsuffix Exp + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + true + VCTargets + 1033 + + + true + VCTargets + + + Always + true + + + true + VCTargets + + + Designer + + + + true + VCTargets + Platforms\x64\PlatformToolsets\llvm + + + true + VCTargets + Platforms\x64\PlatformToolsets\llvm + + + true + VCTargets + Platforms\Win32\PlatformToolsets\llvm + + + true + VCTargets + Platforms\Win32\PlatformToolsets\llvm + + + + + + + + + if not exist $(ProjectDir)Key.snk ("$(TargetFrameworkSDKToolsDirectory)\x64\sn.exe" -k $(ProjectDir)Key.snk) + \ No newline at end of file diff --git a/interpreter/llvm/src/tools/msbuild/llvm.sln b/interpreter/llvm-project/llvm/tools/msbuild/llvm.sln similarity index 100% rename from interpreter/llvm/src/tools/msbuild/llvm.sln rename to interpreter/llvm-project/llvm/tools/msbuild/llvm.sln diff --git a/interpreter/llvm/src/tools/msbuild/source.extension.vsixmanifest b/interpreter/llvm-project/llvm/tools/msbuild/source.extension.vsixmanifest similarity index 98% rename from interpreter/llvm/src/tools/msbuild/source.extension.vsixmanifest rename to interpreter/llvm-project/llvm/tools/msbuild/source.extension.vsixmanifest index d93e5e25286d3..ac2d3c4d49b99 100644 --- a/interpreter/llvm/src/tools/msbuild/source.extension.vsixmanifest +++ b/interpreter/llvm-project/llvm/tools/msbuild/source.extension.vsixmanifest @@ -1,22 +1,22 @@ - - - - - LLVM Compiler Toolchain - Allows the LLVM Compiler Toolchain (installed separately) to be used from within Visual Studio to build C/C++ Projects. - license.txt - - - - - - - - - - - - - - - + + + + + LLVM Compiler Toolchain + Allows the LLVM Compiler Toolchain (installed separately) to be used from within Visual Studio to build C/C++ Projects. + license.txt + + + + + + + + + + + + + + + diff --git a/interpreter/llvm/src/tools/msbuild/uninstall.bat b/interpreter/llvm-project/llvm/tools/msbuild/uninstall.bat similarity index 100% rename from interpreter/llvm/src/tools/msbuild/uninstall.bat rename to interpreter/llvm-project/llvm/tools/msbuild/uninstall.bat diff --git a/interpreter/llvm/src/tools/obj2yaml/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/obj2yaml/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/obj2yaml/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/obj2yaml/archive2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/archive2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/archive2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/archive2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/coff2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/coff2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/coff2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/coff2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/dwarf2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/dwarf2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/dwarf2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/dwarf2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/elf2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/elf2yaml.cpp similarity index 99% rename from interpreter/llvm/src/tools/obj2yaml/elf2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/elf2yaml.cpp index 028758d68d95c..9d1713c85995f 100644 --- a/interpreter/llvm/src/tools/obj2yaml/elf2yaml.cpp +++ b/interpreter/llvm-project/llvm/tools/obj2yaml/elf2yaml.cpp @@ -201,7 +201,8 @@ bool ELFDumper::shouldPrintSection(const ELFYAML::Section &S, if (const ELFYAML::RawContentSection *RawSec = dyn_cast(&S)) { if (RawSec->Type != ELF::SHT_PROGBITS || RawSec->Link || RawSec->Info || - RawSec->AddressAlign != 1 || RawSec->Address || RawSec->EntSize) + RawSec->AddressAlign != yaml::Hex64{1} || RawSec->Address || + RawSec->EntSize) return true; ELFYAML::ELF_SHF ShFlags = RawSec->Flags.getValueOr(ELFYAML::ELF_SHF(0)); @@ -209,7 +210,7 @@ bool ELFDumper::shouldPrintSection(const ELFYAML::Section &S, if (SecName == "debug_str") return ShFlags != ELFYAML::ELF_SHF(ELF::SHF_MERGE | ELF::SHF_STRINGS); - return ShFlags != 0; + return ShFlags != ELFYAML::ELF_SHF{0}; } } diff --git a/interpreter/llvm/src/tools/obj2yaml/macho2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/macho2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/macho2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/macho2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/minidump2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/minidump2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/minidump2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/minidump2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/obj2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/obj2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/obj2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/obj2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/obj2yaml.h b/interpreter/llvm-project/llvm/tools/obj2yaml/obj2yaml.h similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/obj2yaml.h rename to interpreter/llvm-project/llvm/tools/obj2yaml/obj2yaml.h diff --git a/interpreter/llvm/src/tools/obj2yaml/wasm2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/wasm2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/wasm2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/wasm2yaml.cpp diff --git a/interpreter/llvm/src/tools/obj2yaml/xcoff2yaml.cpp b/interpreter/llvm-project/llvm/tools/obj2yaml/xcoff2yaml.cpp similarity index 100% rename from interpreter/llvm/src/tools/obj2yaml/xcoff2yaml.cpp rename to interpreter/llvm-project/llvm/tools/obj2yaml/xcoff2yaml.cpp diff --git a/interpreter/llvm/src/tools/opt-viewer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/opt-viewer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/opt-viewer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/opt-viewer/opt-diff.py b/interpreter/llvm-project/llvm/tools/opt-viewer/opt-diff.py similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/opt-diff.py rename to interpreter/llvm-project/llvm/tools/opt-viewer/opt-diff.py diff --git a/interpreter/llvm/src/tools/opt-viewer/opt-stats.py b/interpreter/llvm-project/llvm/tools/opt-viewer/opt-stats.py similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/opt-stats.py rename to interpreter/llvm-project/llvm/tools/opt-viewer/opt-stats.py diff --git a/interpreter/llvm/src/tools/opt-viewer/opt-viewer.py b/interpreter/llvm-project/llvm/tools/opt-viewer/opt-viewer.py similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/opt-viewer.py rename to interpreter/llvm-project/llvm/tools/opt-viewer/opt-viewer.py diff --git a/interpreter/llvm/src/tools/opt-viewer/optpmap.py b/interpreter/llvm-project/llvm/tools/opt-viewer/optpmap.py similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/optpmap.py rename to interpreter/llvm-project/llvm/tools/opt-viewer/optpmap.py diff --git a/interpreter/llvm/src/tools/opt-viewer/optrecord.py b/interpreter/llvm-project/llvm/tools/opt-viewer/optrecord.py similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/optrecord.py rename to interpreter/llvm-project/llvm/tools/opt-viewer/optrecord.py diff --git a/interpreter/llvm/src/tools/opt-viewer/style.css b/interpreter/llvm-project/llvm/tools/opt-viewer/style.css similarity index 100% rename from interpreter/llvm/src/tools/opt-viewer/style.css rename to interpreter/llvm-project/llvm/tools/opt-viewer/style.css diff --git a/interpreter/llvm/src/tools/opt/AnalysisWrappers.cpp b/interpreter/llvm-project/llvm/tools/opt/AnalysisWrappers.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/AnalysisWrappers.cpp rename to interpreter/llvm-project/llvm/tools/opt/AnalysisWrappers.cpp diff --git a/interpreter/llvm/src/tools/opt/BreakpointPrinter.cpp b/interpreter/llvm-project/llvm/tools/opt/BreakpointPrinter.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/BreakpointPrinter.cpp rename to interpreter/llvm-project/llvm/tools/opt/BreakpointPrinter.cpp diff --git a/interpreter/llvm/src/tools/opt/BreakpointPrinter.h b/interpreter/llvm-project/llvm/tools/opt/BreakpointPrinter.h similarity index 100% rename from interpreter/llvm/src/tools/opt/BreakpointPrinter.h rename to interpreter/llvm-project/llvm/tools/opt/BreakpointPrinter.h diff --git a/interpreter/llvm/src/tools/opt/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/opt/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/opt/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/opt/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/opt/GraphPrinters.cpp b/interpreter/llvm-project/llvm/tools/opt/GraphPrinters.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/GraphPrinters.cpp rename to interpreter/llvm-project/llvm/tools/opt/GraphPrinters.cpp diff --git a/interpreter/llvm/src/tools/opt/NewPMDriver.cpp b/interpreter/llvm-project/llvm/tools/opt/NewPMDriver.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/NewPMDriver.cpp rename to interpreter/llvm-project/llvm/tools/opt/NewPMDriver.cpp diff --git a/interpreter/llvm/src/tools/opt/NewPMDriver.h b/interpreter/llvm-project/llvm/tools/opt/NewPMDriver.h similarity index 100% rename from interpreter/llvm/src/tools/opt/NewPMDriver.h rename to interpreter/llvm-project/llvm/tools/opt/NewPMDriver.h diff --git a/interpreter/llvm/src/tools/opt/PassPrinters.cpp b/interpreter/llvm-project/llvm/tools/opt/PassPrinters.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/PassPrinters.cpp rename to interpreter/llvm-project/llvm/tools/opt/PassPrinters.cpp diff --git a/interpreter/llvm/src/tools/opt/PassPrinters.h b/interpreter/llvm-project/llvm/tools/opt/PassPrinters.h similarity index 100% rename from interpreter/llvm/src/tools/opt/PassPrinters.h rename to interpreter/llvm-project/llvm/tools/opt/PassPrinters.h diff --git a/interpreter/llvm/src/tools/opt/PrintSCC.cpp b/interpreter/llvm-project/llvm/tools/opt/PrintSCC.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/PrintSCC.cpp rename to interpreter/llvm-project/llvm/tools/opt/PrintSCC.cpp diff --git a/interpreter/llvm/src/tools/opt/opt.cpp b/interpreter/llvm-project/llvm/tools/opt/opt.cpp similarity index 100% rename from interpreter/llvm/src/tools/opt/opt.cpp rename to interpreter/llvm-project/llvm/tools/opt/opt.cpp diff --git a/interpreter/llvm/src/tools/remarks-shlib/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/remarks-shlib/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/remarks-shlib/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/remarks-shlib/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/remarks-shlib/Remarks.exports b/interpreter/llvm-project/llvm/tools/remarks-shlib/Remarks.exports similarity index 100% rename from interpreter/llvm/src/tools/remarks-shlib/Remarks.exports rename to interpreter/llvm-project/llvm/tools/remarks-shlib/Remarks.exports diff --git a/interpreter/llvm/src/tools/remarks-shlib/libremarks.cpp b/interpreter/llvm-project/llvm/tools/remarks-shlib/libremarks.cpp similarity index 100% rename from interpreter/llvm/src/tools/remarks-shlib/libremarks.cpp rename to interpreter/llvm-project/llvm/tools/remarks-shlib/libremarks.cpp diff --git a/interpreter/llvm/src/tools/sancov/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/sancov/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/sancov/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/sancov/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/sancov/coverage-report-server.py b/interpreter/llvm-project/llvm/tools/sancov/coverage-report-server.py similarity index 100% rename from interpreter/llvm/src/tools/sancov/coverage-report-server.py rename to interpreter/llvm-project/llvm/tools/sancov/coverage-report-server.py diff --git a/interpreter/llvm/src/tools/sancov/sancov.cpp b/interpreter/llvm-project/llvm/tools/sancov/sancov.cpp similarity index 100% rename from interpreter/llvm/src/tools/sancov/sancov.cpp rename to interpreter/llvm-project/llvm/tools/sancov/sancov.cpp diff --git a/interpreter/llvm/src/tools/sanstats/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/sanstats/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/sanstats/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/sanstats/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/sanstats/sanstats.cpp b/interpreter/llvm-project/llvm/tools/sanstats/sanstats.cpp similarity index 100% rename from interpreter/llvm/src/tools/sanstats/sanstats.cpp rename to interpreter/llvm-project/llvm/tools/sanstats/sanstats.cpp diff --git a/interpreter/llvm/src/tools/split-file/.clang-tidy b/interpreter/llvm-project/llvm/tools/split-file/.clang-tidy similarity index 100% rename from interpreter/llvm/src/tools/split-file/.clang-tidy rename to interpreter/llvm-project/llvm/tools/split-file/.clang-tidy diff --git a/interpreter/llvm/src/tools/split-file/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/split-file/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/split-file/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/split-file/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/split-file/split-file.cpp b/interpreter/llvm-project/llvm/tools/split-file/split-file.cpp similarity index 100% rename from interpreter/llvm/src/tools/split-file/split-file.cpp rename to interpreter/llvm-project/llvm/tools/split-file/split-file.cpp diff --git a/interpreter/llvm/src/tools/verify-uselistorder/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/verify-uselistorder/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/verify-uselistorder/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/verify-uselistorder/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/verify-uselistorder/verify-uselistorder.cpp b/interpreter/llvm-project/llvm/tools/verify-uselistorder/verify-uselistorder.cpp similarity index 100% rename from interpreter/llvm/src/tools/verify-uselistorder/verify-uselistorder.cpp rename to interpreter/llvm-project/llvm/tools/verify-uselistorder/verify-uselistorder.cpp diff --git a/interpreter/llvm/src/tools/vfabi-demangle-fuzzer/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/vfabi-demangle-fuzzer/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/vfabi-demangle-fuzzer/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/vfabi-demangle-fuzzer/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp b/interpreter/llvm-project/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp similarity index 100% rename from interpreter/llvm/src/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp rename to interpreter/llvm-project/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp diff --git a/interpreter/llvm/src/tools/xcode-toolchain/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/xcode-toolchain/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/xcode-toolchain/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/xcode-toolchain/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/yaml2obj/CMakeLists.txt b/interpreter/llvm-project/llvm/tools/yaml2obj/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/tools/yaml2obj/CMakeLists.txt rename to interpreter/llvm-project/llvm/tools/yaml2obj/CMakeLists.txt diff --git a/interpreter/llvm/src/tools/yaml2obj/yaml2obj.cpp b/interpreter/llvm-project/llvm/tools/yaml2obj/yaml2obj.cpp similarity index 100% rename from interpreter/llvm/src/tools/yaml2obj/yaml2obj.cpp rename to interpreter/llvm-project/llvm/tools/yaml2obj/yaml2obj.cpp diff --git a/interpreter/llvm/src/utils/DSAclean.py b/interpreter/llvm-project/llvm/utils/DSAclean.py similarity index 100% rename from interpreter/llvm/src/utils/DSAclean.py rename to interpreter/llvm-project/llvm/utils/DSAclean.py diff --git a/interpreter/llvm/src/utils/DSAextract.py b/interpreter/llvm-project/llvm/utils/DSAextract.py similarity index 100% rename from interpreter/llvm/src/utils/DSAextract.py rename to interpreter/llvm-project/llvm/utils/DSAextract.py diff --git a/interpreter/llvm/src/utils/FileCheck/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/FileCheck/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/FileCheck/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/FileCheck/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/FileCheck/FileCheck.cpp b/interpreter/llvm-project/llvm/utils/FileCheck/FileCheck.cpp similarity index 100% rename from interpreter/llvm/src/utils/FileCheck/FileCheck.cpp rename to interpreter/llvm-project/llvm/utils/FileCheck/FileCheck.cpp diff --git a/interpreter/llvm/src/utils/GenLibDeps.pl b/interpreter/llvm-project/llvm/utils/GenLibDeps.pl similarity index 100% rename from interpreter/llvm/src/utils/GenLibDeps.pl rename to interpreter/llvm-project/llvm/utils/GenLibDeps.pl diff --git a/interpreter/llvm/src/utils/GetSourceVersion b/interpreter/llvm-project/llvm/utils/GetSourceVersion similarity index 100% rename from interpreter/llvm/src/utils/GetSourceVersion rename to interpreter/llvm-project/llvm/utils/GetSourceVersion diff --git a/interpreter/llvm/src/utils/KillTheDoctor/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/KillTheDoctor/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/KillTheDoctor/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/KillTheDoctor/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/KillTheDoctor/KillTheDoctor.cpp b/interpreter/llvm-project/llvm/utils/KillTheDoctor/KillTheDoctor.cpp similarity index 100% rename from interpreter/llvm/src/utils/KillTheDoctor/KillTheDoctor.cpp rename to interpreter/llvm-project/llvm/utils/KillTheDoctor/KillTheDoctor.cpp diff --git a/interpreter/llvm/src/utils/LLVMVisualizers/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/LLVMVisualizers/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/LLVMVisualizers/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/LLVMVisualizers/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/LLVMVisualizers/llvm.natvis b/interpreter/llvm-project/llvm/utils/LLVMVisualizers/llvm.natvis similarity index 98% rename from interpreter/llvm/src/utils/LLVMVisualizers/llvm.natvis rename to interpreter/llvm-project/llvm/utils/LLVMVisualizers/llvm.natvis index f1d11603bc3e5..6e75ebd6f4bba 100644 --- a/interpreter/llvm/src/utils/LLVMVisualizers/llvm.natvis +++ b/interpreter/llvm-project/llvm/utils/LLVMVisualizers/llvm.natvis @@ -1,307 +1,307 @@ - - - - - - {(($T1*)BeginX)[0]}{*this,view(elt1)} - - , {(($T1*)BeginX)[1]}{*this,view(elt2)} - - , {(($T1*)BeginX)[2]}{*this,view(elt3)} - - , {(($T1*)BeginX)[3]}{*this,view(elt4)} - - , /* {Size - 4} more*/ - empty - {{{*this,view(elt0)}}} - Uninitialized - - Size - Capacity - - Size - ($T1*)BeginX - - - - - - {U.VAL} - Cannot visualize APInts longer than 64 bits - - - empty - {{ size={Length} }} - - Length - - Length - Data - - - - - {(const char*)BeginX,[Size] na} - (const char*)BeginX,[Size] - - Size - Capacity - - Size - (char*)BeginX - - - - - - {First,[Last - First]s} - - - - {Data,[Length]s} - Data,[Length]s - - Length - - Length - Data - - - - - - - {($T1)(Value & $T5::PointerBitMask)} - {($T3)((Value >> $T5::IntShift) & $T5::IntMask)} - {$T5::IntMask}: {($T1)(Value & $T5::PointerBitMask)} [{($T3)((Value >> $T5::IntShift) & $T5::IntMask)}] - - ($T1)(Value & $T5::PointerBitMask) - ($T3)((Value >> $T5::IntShift) & $T5::IntMask) - - - - - - {($T4)(Val.Value & $T2::InfoTy::PointerBitMask)} - - - {($T5)(Val.Value & $T2::InfoTy::PointerBitMask)} - - - {($T6)(Val.Value & $T2::InfoTy::PointerBitMask)} - - - {($T7)(Val.Value & $T2::InfoTy::PointerBitMask)} - - Unexpected index in PointerUnion: {(Val.Value>>$T2::InfoTy::IntShift) & $T2::InfoTy::IntMask} - - "$T4",s8b - - ($T4)(Val.Value & $T2::InfoTy::PointerBitMask) - - "$T5",s8b - - ($T5)(Val.Value & $T2::InfoTy::PointerBitMask) - - "$T6",s8b - - ($T6)(Val.Value & $T2::InfoTy::PointerBitMask) - - "$T6",s8b - - ($T7)(Val.Value & $T2::InfoTy::PointerBitMask) - - - - - - {{ empty }} - {{ head={Head} }} - - - Head - Next - this - - - - - - empty - RefPtr [1 ref] {*Obj} - RefPtr [{Obj->RefCount} refs] {*Obj} - - Obj->RefCount - Obj - - - - - {{ [Small Mode] size={NumNonEmpty}, capacity={CurArraySize} }} - {{ [Big Mode] size={NumNonEmpty}, capacity={CurArraySize} }} - - NumNonEmpty - CurArraySize - - NumNonEmpty - ($T1*)CurArray - - - - - - empty - {{ size={NumEntries}, buckets={NumBuckets} }} - - NumEntries - NumBuckets - - NumBuckets - Buckets - - - - - - {{ size={NumItems}, buckets={NumBuckets} }} - - NumItems - NumBuckets - - NumBuckets - (MapEntryTy**)TheTable - - - - - - empty - ({this+1,s}, {second}) - - this+1,s - second - - - - - {Data} - - - - None - {*(($T1 *)(unsigned char *)Storage.storage.buffer)} - - *(($T1 *)(unsigned char *)Storage.storage.buffer) - - - - - Error - {*((storage_type *)TStorage.buffer)} - - *((storage_type *)TStorage.buffer) - *((error_type *)ErrorStorage.buffer) - - - - - - - {{little endian value = {*(($T1*)(unsigned char *)Value.buffer)} }} - - (unsigned char *)Value.buffer,1 - (unsigned char *)Value.buffer,2 - (unsigned char *)Value.buffer,4 - (unsigned char *)Value.buffer,8 - - - - - - {{ big endian value = {*(unsigned char *)Value.buffer} }} - {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 8) - | ($T1)(*((unsigned char *)Value.buffer+1))} }} - {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 24) - | (($T1)(*((unsigned char *)Value.buffer+1)) << 16) - | (($T1)(*((unsigned char *)Value.buffer+2)) << 8) - | ($T1)(*((unsigned char *)Value.buffer+3))} }} - {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 56) - | (($T1)(*((unsigned char *)Value.buffer+1)) << 48) - | (($T1)(*((unsigned char *)Value.buffer+2)) << 40) - | (($T1)(*((unsigned char *)Value.buffer+3)) << 32) - | (($T1)(*((unsigned char *)Value.buffer+4)) << 24) - | (($T1)(*((unsigned char *)Value.buffer+5)) << 16) - | (($T1)(*((unsigned char *)Value.buffer+6)) << 8) - | ($T1)(*((unsigned char *)Value.buffer+7))} }} - - (unsigned char *)Value.buffer,1 - (unsigned char *)Value.buffer,2 - (unsigned char *)Value.buffer,4 - (unsigned char *)Value.buffer,8 - - - - - {ID} - - ID - - SubclassData - - *ContainedTys - - {NumContainedTys - 1} - - - NumContainedTys - 1 - ContainedTys + 1 - - - - SubclassData == 1 - - (SubclassData & llvm::StructType::SCDB_HasBody) != 0 - (SubclassData & llvm::StructType::SCDB_Packed) != 0 - (SubclassData & llvm::StructType::SCDB_IsLiteral) != 0 - (SubclassData & llvm::StructType::SCDB_IsSized) != 0 - - {NumContainedTys} - - - NumContainedTys - ContainedTys - - - - - *ContainedTys - ((llvm::ArrayType*)this)->NumElements - - *ContainedTys - ((llvm::VectorType*)this)->ElementQuantity - - *ContainedTys - ((llvm::VectorType*)this)->ElementQuantity - - SubclassData - *ContainedTys - - Context - - - + + + + + + {(($T1*)BeginX)[0]}{*this,view(elt1)} + + , {(($T1*)BeginX)[1]}{*this,view(elt2)} + + , {(($T1*)BeginX)[2]}{*this,view(elt3)} + + , {(($T1*)BeginX)[3]}{*this,view(elt4)} + + , /* {Size - 4} more*/ + empty + {{{*this,view(elt0)}}} + Uninitialized + + Size + Capacity + + Size + ($T1*)BeginX + + + + + + {U.VAL} + Cannot visualize APInts longer than 64 bits + + + empty + {{ size={Length} }} + + Length + + Length + Data + + + + + {(const char*)BeginX,[Size] na} + (const char*)BeginX,[Size] + + Size + Capacity + + Size + (char*)BeginX + + + + + + {First,[Last - First]s} + + + + {Data,[Length]s} + Data,[Length]s + + Length + + Length + Data + + + + + + + {($T1)(Value & $T5::PointerBitMask)} + {($T3)((Value >> $T5::IntShift) & $T5::IntMask)} + {$T5::IntMask}: {($T1)(Value & $T5::PointerBitMask)} [{($T3)((Value >> $T5::IntShift) & $T5::IntMask)}] + + ($T1)(Value & $T5::PointerBitMask) + ($T3)((Value >> $T5::IntShift) & $T5::IntMask) + + + + + + {($T4)(Val.Value & $T2::InfoTy::PointerBitMask)} + + + {($T5)(Val.Value & $T2::InfoTy::PointerBitMask)} + + + {($T6)(Val.Value & $T2::InfoTy::PointerBitMask)} + + + {($T7)(Val.Value & $T2::InfoTy::PointerBitMask)} + + Unexpected index in PointerUnion: {(Val.Value>>$T2::InfoTy::IntShift) & $T2::InfoTy::IntMask} + + "$T4",s8b + + ($T4)(Val.Value & $T2::InfoTy::PointerBitMask) + + "$T5",s8b + + ($T5)(Val.Value & $T2::InfoTy::PointerBitMask) + + "$T6",s8b + + ($T6)(Val.Value & $T2::InfoTy::PointerBitMask) + + "$T6",s8b + + ($T7)(Val.Value & $T2::InfoTy::PointerBitMask) + + + + + + {{ empty }} + {{ head={Head} }} + + + Head + Next + this + + + + + + empty + RefPtr [1 ref] {*Obj} + RefPtr [{Obj->RefCount} refs] {*Obj} + + Obj->RefCount + Obj + + + + + {{ [Small Mode] size={NumNonEmpty}, capacity={CurArraySize} }} + {{ [Big Mode] size={NumNonEmpty}, capacity={CurArraySize} }} + + NumNonEmpty + CurArraySize + + NumNonEmpty + ($T1*)CurArray + + + + + + empty + {{ size={NumEntries}, buckets={NumBuckets} }} + + NumEntries + NumBuckets + + NumBuckets + Buckets + + + + + + {{ size={NumItems}, buckets={NumBuckets} }} + + NumItems + NumBuckets + + NumBuckets + (MapEntryTy**)TheTable + + + + + + empty + ({this+1,s}, {second}) + + this+1,s + second + + + + + {Data} + + + + None + {*(($T1 *)(unsigned char *)Storage.storage.buffer)} + + *(($T1 *)(unsigned char *)Storage.storage.buffer) + + + + + Error + {*((storage_type *)TStorage.buffer)} + + *((storage_type *)TStorage.buffer) + *((error_type *)ErrorStorage.buffer) + + + + + + + {{little endian value = {*(($T1*)(unsigned char *)Value.buffer)} }} + + (unsigned char *)Value.buffer,1 + (unsigned char *)Value.buffer,2 + (unsigned char *)Value.buffer,4 + (unsigned char *)Value.buffer,8 + + + + + + {{ big endian value = {*(unsigned char *)Value.buffer} }} + {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 8) + | ($T1)(*((unsigned char *)Value.buffer+1))} }} + {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 24) + | (($T1)(*((unsigned char *)Value.buffer+1)) << 16) + | (($T1)(*((unsigned char *)Value.buffer+2)) << 8) + | ($T1)(*((unsigned char *)Value.buffer+3))} }} + {{ big endian value = {(($T1)(*(unsigned char *)Value.buffer) << 56) + | (($T1)(*((unsigned char *)Value.buffer+1)) << 48) + | (($T1)(*((unsigned char *)Value.buffer+2)) << 40) + | (($T1)(*((unsigned char *)Value.buffer+3)) << 32) + | (($T1)(*((unsigned char *)Value.buffer+4)) << 24) + | (($T1)(*((unsigned char *)Value.buffer+5)) << 16) + | (($T1)(*((unsigned char *)Value.buffer+6)) << 8) + | ($T1)(*((unsigned char *)Value.buffer+7))} }} + + (unsigned char *)Value.buffer,1 + (unsigned char *)Value.buffer,2 + (unsigned char *)Value.buffer,4 + (unsigned char *)Value.buffer,8 + + + + + {ID} + + ID + + SubclassData + + *ContainedTys + + {NumContainedTys - 1} + + + NumContainedTys - 1 + ContainedTys + 1 + + + + SubclassData == 1 + + (SubclassData & llvm::StructType::SCDB_HasBody) != 0 + (SubclassData & llvm::StructType::SCDB_Packed) != 0 + (SubclassData & llvm::StructType::SCDB_IsLiteral) != 0 + (SubclassData & llvm::StructType::SCDB_IsSized) != 0 + + {NumContainedTys} + + + NumContainedTys + ContainedTys + + + + + *ContainedTys + ((llvm::ArrayType*)this)->NumElements + + *ContainedTys + ((llvm::VectorType*)this)->ElementQuantity + + *ContainedTys + ((llvm::VectorType*)this)->ElementQuantity + + SubclassData + *ContainedTys + + Context + + + diff --git a/interpreter/llvm/src/utils/Misc/zkill b/interpreter/llvm-project/llvm/utils/Misc/zkill similarity index 100% rename from interpreter/llvm/src/utils/Misc/zkill rename to interpreter/llvm-project/llvm/utils/Misc/zkill diff --git a/interpreter/llvm/src/utils/PerfectShuffle/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/PerfectShuffle/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/PerfectShuffle/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/PerfectShuffle/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/PerfectShuffle/PerfectShuffle.cpp b/interpreter/llvm-project/llvm/utils/PerfectShuffle/PerfectShuffle.cpp similarity index 100% rename from interpreter/llvm/src/utils/PerfectShuffle/PerfectShuffle.cpp rename to interpreter/llvm-project/llvm/utils/PerfectShuffle/PerfectShuffle.cpp diff --git a/interpreter/llvm/src/utils/Reviewing/find_interesting_reviews.py b/interpreter/llvm-project/llvm/utils/Reviewing/find_interesting_reviews.py similarity index 100% rename from interpreter/llvm/src/utils/Reviewing/find_interesting_reviews.py rename to interpreter/llvm-project/llvm/utils/Reviewing/find_interesting_reviews.py diff --git a/interpreter/llvm/src/utils/TableGen/AsmMatcherEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/AsmMatcherEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/AsmMatcherEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/AsmMatcherEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/AsmWriterEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/AsmWriterEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/AsmWriterEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/AsmWriterEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/AsmWriterInst.cpp b/interpreter/llvm-project/llvm/utils/TableGen/AsmWriterInst.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/AsmWriterInst.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/AsmWriterInst.cpp diff --git a/interpreter/llvm/src/utils/TableGen/AsmWriterInst.h b/interpreter/llvm-project/llvm/utils/TableGen/AsmWriterInst.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/AsmWriterInst.h rename to interpreter/llvm-project/llvm/utils/TableGen/AsmWriterInst.h diff --git a/interpreter/llvm/src/utils/TableGen/Attributes.cpp b/interpreter/llvm-project/llvm/utils/TableGen/Attributes.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/Attributes.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/Attributes.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/TableGen/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/TableGen/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/TableGen/CTagsEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CTagsEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CTagsEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CTagsEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CallingConvEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CallingConvEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CallingConvEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CallingConvEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeBeadsGen.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeBeadsGen.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeBeadsGen.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeBeadsGen.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeEmitterGen.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeEmitterGen.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeEmitterGen.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeEmitterGen.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenDAGPatterns.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenDAGPatterns.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenDAGPatterns.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenDAGPatterns.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenDAGPatterns.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenDAGPatterns.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenDAGPatterns.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenDAGPatterns.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenHwModes.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenHwModes.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenHwModes.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenHwModes.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenHwModes.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenHwModes.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenHwModes.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenHwModes.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenInstruction.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenInstruction.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenInstruction.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenInstruction.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenInstruction.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenInstruction.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenInstruction.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenInstruction.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenIntrinsics.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenIntrinsics.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenIntrinsics.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenIntrinsics.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenMapTable.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenMapTable.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenMapTable.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenMapTable.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenRegisters.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenRegisters.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenRegisters.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenRegisters.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenRegisters.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenRegisters.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenRegisters.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenRegisters.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenSchedule.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenSchedule.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenSchedule.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenSchedule.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenSchedule.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenSchedule.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenSchedule.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenSchedule.h diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenTarget.cpp b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenTarget.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenTarget.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenTarget.cpp diff --git a/interpreter/llvm/src/utils/TableGen/CodeGenTarget.h b/interpreter/llvm-project/llvm/utils/TableGen/CodeGenTarget.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/CodeGenTarget.h rename to interpreter/llvm-project/llvm/utils/TableGen/CodeGenTarget.h diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelMatcher.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcher.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelMatcher.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcher.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelMatcher.h b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcher.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelMatcher.h rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcher.h diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelMatcherEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelMatcherEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelMatcherGen.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherGen.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelMatcherGen.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherGen.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DAGISelMatcherOpt.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherOpt.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DAGISelMatcherOpt.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DAGISelMatcherOpt.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DFAEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DFAEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DFAEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DFAEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DFAEmitter.h b/interpreter/llvm-project/llvm/utils/TableGen/DFAEmitter.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DFAEmitter.h rename to interpreter/llvm-project/llvm/utils/TableGen/DFAEmitter.h diff --git a/interpreter/llvm/src/utils/TableGen/DFAPacketizerEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DFAPacketizerEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DFAPacketizerEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DFAPacketizerEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DirectiveEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DirectiveEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DirectiveEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DirectiveEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/DisassemblerEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/DisassemblerEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/DisassemblerEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/DisassemblerEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/ExegesisEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/ExegesisEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/ExegesisEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/ExegesisEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/FastISelEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/FastISelEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/FastISelEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/FastISelEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/FixedLenDecoderEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/FixedLenDecoderEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GICombinerEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GICombinerEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GICombinerEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GICombinerEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpander.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpander.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpander.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpander.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpander.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpander.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpander.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpander.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpansions.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpansions.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/CodeExpansions.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/CodeExpansions.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDag.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDag.cpp similarity index 98% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDag.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDag.cpp index 7e037dd03b601..8be32d2effa6e 100644 --- a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDag.cpp +++ b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDag.cpp @@ -48,7 +48,7 @@ void GIMatchDag::writeDOTGraph(raw_ostream &OS, StringRef ID) const { << Assignment.first << ")"; Separator = ", "; } - OS << format("|%p|", &N); + OS << llvm::format("|%p|", &N); writePorts("d", N->getOperandInfo()); OS << "}\""; if (N->isMatchRoot()) @@ -82,7 +82,7 @@ void GIMatchDag::writeDOTGraph(raw_ostream &OS, StringRef ID) const { writePorts("s", N->getOperandInfo()); OS << "|" << N->getName() << "|"; N->printDescription(OS); - OS << format("|%p|", &N); + OS << llvm::format("|%p|", &N); writePorts("d", N->getOperandInfo()); OS << "}\",style=dotted]\n"; } diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDag.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDag.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDag.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDag.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagEdge.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagEdge.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagEdge.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagEdge.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagEdge.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagEdge.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagEdge.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagEdge.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagInstr.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagInstr.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagInstr.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagInstr.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagInstr.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagInstr.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagInstr.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagInstr.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagOperands.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagOperands.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagOperands.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagOperands.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagOperands.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagOperands.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagOperands.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagOperands.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicate.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicate.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicate.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicate.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicate.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicate.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicate.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicate.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchDagPredicateDependencyEdge.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchTree.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchTree.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchTree.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchTree.cpp diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchTree.h b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchTree.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISel/GIMatchTree.h rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISel/GIMatchTree.h diff --git a/interpreter/llvm/src/utils/TableGen/GlobalISelEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/GlobalISelEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/InfoByHwMode.cpp b/interpreter/llvm-project/llvm/utils/TableGen/InfoByHwMode.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/InfoByHwMode.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/InfoByHwMode.cpp diff --git a/interpreter/llvm/src/utils/TableGen/InfoByHwMode.h b/interpreter/llvm-project/llvm/utils/TableGen/InfoByHwMode.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/InfoByHwMode.h rename to interpreter/llvm-project/llvm/utils/TableGen/InfoByHwMode.h diff --git a/interpreter/llvm/src/utils/TableGen/InstrDocsEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/InstrDocsEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/InstrDocsEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/InstrDocsEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/InstrInfoEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/InstrInfoEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/InstrInfoEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/InstrInfoEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/IntrinsicEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/IntrinsicEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/IntrinsicEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/IntrinsicEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/OptEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/OptEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/OptEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/OptEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/OptEmitter.h b/interpreter/llvm-project/llvm/utils/TableGen/OptEmitter.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/OptEmitter.h rename to interpreter/llvm-project/llvm/utils/TableGen/OptEmitter.h diff --git a/interpreter/llvm/src/utils/TableGen/OptParserEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/OptParserEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/OptParserEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/OptParserEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/OptRSTEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/OptRSTEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/OptRSTEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/OptRSTEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/PredicateExpander.cpp b/interpreter/llvm-project/llvm/utils/TableGen/PredicateExpander.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/PredicateExpander.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/PredicateExpander.cpp diff --git a/interpreter/llvm/src/utils/TableGen/PredicateExpander.h b/interpreter/llvm-project/llvm/utils/TableGen/PredicateExpander.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/PredicateExpander.h rename to interpreter/llvm-project/llvm/utils/TableGen/PredicateExpander.h diff --git a/interpreter/llvm/src/utils/TableGen/PseudoLoweringEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/PseudoLoweringEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/PseudoLoweringEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/PseudoLoweringEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/RISCVCompressInstEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/RISCVCompressInstEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/RISCVCompressInstEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/RISCVCompressInstEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/RegisterBankEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/RegisterBankEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/RegisterBankEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/RegisterBankEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/RegisterInfoEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/RegisterInfoEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/RegisterInfoEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/RegisterInfoEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/SDNodeProperties.cpp b/interpreter/llvm-project/llvm/utils/TableGen/SDNodeProperties.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SDNodeProperties.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/SDNodeProperties.cpp diff --git a/interpreter/llvm/src/utils/TableGen/SDNodeProperties.h b/interpreter/llvm-project/llvm/utils/TableGen/SDNodeProperties.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SDNodeProperties.h rename to interpreter/llvm-project/llvm/utils/TableGen/SDNodeProperties.h diff --git a/interpreter/llvm/src/utils/TableGen/SearchableTableEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/SearchableTableEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SearchableTableEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/SearchableTableEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/SequenceToOffsetTable.h b/interpreter/llvm-project/llvm/utils/TableGen/SequenceToOffsetTable.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SequenceToOffsetTable.h rename to interpreter/llvm-project/llvm/utils/TableGen/SequenceToOffsetTable.h diff --git a/interpreter/llvm/src/utils/TableGen/SubtargetEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/SubtargetEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SubtargetEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/SubtargetEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/SubtargetFeatureInfo.cpp b/interpreter/llvm-project/llvm/utils/TableGen/SubtargetFeatureInfo.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SubtargetFeatureInfo.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/SubtargetFeatureInfo.cpp diff --git a/interpreter/llvm/src/utils/TableGen/SubtargetFeatureInfo.h b/interpreter/llvm-project/llvm/utils/TableGen/SubtargetFeatureInfo.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/SubtargetFeatureInfo.h rename to interpreter/llvm-project/llvm/utils/TableGen/SubtargetFeatureInfo.h diff --git a/interpreter/llvm/src/utils/TableGen/TableGen.cpp b/interpreter/llvm-project/llvm/utils/TableGen/TableGen.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/TableGen.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/TableGen.cpp diff --git a/interpreter/llvm/src/utils/TableGen/TableGenBackends.h b/interpreter/llvm-project/llvm/utils/TableGen/TableGenBackends.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/TableGenBackends.h rename to interpreter/llvm-project/llvm/utils/TableGen/TableGenBackends.h diff --git a/interpreter/llvm/src/utils/TableGen/Types.cpp b/interpreter/llvm-project/llvm/utils/TableGen/Types.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/Types.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/Types.cpp diff --git a/interpreter/llvm/src/utils/TableGen/Types.h b/interpreter/llvm-project/llvm/utils/TableGen/Types.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/Types.h rename to interpreter/llvm-project/llvm/utils/TableGen/Types.h diff --git a/interpreter/llvm/src/utils/TableGen/WebAssemblyDisassemblerEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/WebAssemblyDisassemblerEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/WebAssemblyDisassemblerEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/WebAssemblyDisassemblerEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/WebAssemblyDisassemblerEmitter.h b/interpreter/llvm-project/llvm/utils/TableGen/WebAssemblyDisassemblerEmitter.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/WebAssemblyDisassemblerEmitter.h rename to interpreter/llvm-project/llvm/utils/TableGen/WebAssemblyDisassemblerEmitter.h diff --git a/interpreter/llvm/src/utils/TableGen/X86DisassemblerShared.h b/interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerShared.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86DisassemblerShared.h rename to interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerShared.h diff --git a/interpreter/llvm/src/utils/TableGen/X86DisassemblerTables.cpp b/interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerTables.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86DisassemblerTables.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerTables.cpp diff --git a/interpreter/llvm/src/utils/TableGen/X86DisassemblerTables.h b/interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerTables.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86DisassemblerTables.h rename to interpreter/llvm-project/llvm/utils/TableGen/X86DisassemblerTables.h diff --git a/interpreter/llvm/src/utils/TableGen/X86EVEX2VEXTablesEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/X86EVEX2VEXTablesEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86EVEX2VEXTablesEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/X86EVEX2VEXTablesEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/X86FoldTablesEmitter.cpp b/interpreter/llvm-project/llvm/utils/TableGen/X86FoldTablesEmitter.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86FoldTablesEmitter.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/X86FoldTablesEmitter.cpp diff --git a/interpreter/llvm/src/utils/TableGen/X86ModRMFilters.cpp b/interpreter/llvm-project/llvm/utils/TableGen/X86ModRMFilters.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86ModRMFilters.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/X86ModRMFilters.cpp diff --git a/interpreter/llvm/src/utils/TableGen/X86ModRMFilters.h b/interpreter/llvm-project/llvm/utils/TableGen/X86ModRMFilters.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86ModRMFilters.h rename to interpreter/llvm-project/llvm/utils/TableGen/X86ModRMFilters.h diff --git a/interpreter/llvm/src/utils/TableGen/X86RecognizableInstr.cpp b/interpreter/llvm-project/llvm/utils/TableGen/X86RecognizableInstr.cpp similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86RecognizableInstr.cpp rename to interpreter/llvm-project/llvm/utils/TableGen/X86RecognizableInstr.cpp diff --git a/interpreter/llvm/src/utils/TableGen/X86RecognizableInstr.h b/interpreter/llvm-project/llvm/utils/TableGen/X86RecognizableInstr.h similarity index 100% rename from interpreter/llvm/src/utils/TableGen/X86RecognizableInstr.h rename to interpreter/llvm-project/llvm/utils/TableGen/X86RecognizableInstr.h diff --git a/interpreter/llvm/src/utils/TableGen/tdtags b/interpreter/llvm-project/llvm/utils/TableGen/tdtags similarity index 100% rename from interpreter/llvm/src/utils/TableGen/tdtags rename to interpreter/llvm-project/llvm/utils/TableGen/tdtags diff --git a/interpreter/llvm/src/utils/Target/ARM/analyze-match-table.py b/interpreter/llvm-project/llvm/utils/Target/ARM/analyze-match-table.py similarity index 100% rename from interpreter/llvm/src/utils/Target/ARM/analyze-match-table.py rename to interpreter/llvm-project/llvm/utils/Target/ARM/analyze-match-table.py diff --git a/interpreter/llvm/src/utils/UpdateCMakeLists.pl b/interpreter/llvm-project/llvm/utils/UpdateCMakeLists.pl similarity index 100% rename from interpreter/llvm/src/utils/UpdateCMakeLists.pl rename to interpreter/llvm-project/llvm/utils/UpdateCMakeLists.pl diff --git a/interpreter/llvm/src/bindings/python/llvm/__init__.py b/interpreter/llvm-project/llvm/utils/UpdateTestChecks/__init__.py similarity index 100% rename from interpreter/llvm/src/bindings/python/llvm/__init__.py rename to interpreter/llvm-project/llvm/utils/UpdateTestChecks/__init__.py diff --git a/interpreter/llvm/src/utils/UpdateTestChecks/asm.py b/interpreter/llvm-project/llvm/utils/UpdateTestChecks/asm.py similarity index 100% rename from interpreter/llvm/src/utils/UpdateTestChecks/asm.py rename to interpreter/llvm-project/llvm/utils/UpdateTestChecks/asm.py diff --git a/interpreter/llvm/src/utils/UpdateTestChecks/common.py b/interpreter/llvm-project/llvm/utils/UpdateTestChecks/common.py similarity index 100% rename from interpreter/llvm/src/utils/UpdateTestChecks/common.py rename to interpreter/llvm-project/llvm/utils/UpdateTestChecks/common.py diff --git a/interpreter/llvm/src/utils/abtest.py b/interpreter/llvm-project/llvm/utils/abtest.py similarity index 100% rename from interpreter/llvm/src/utils/abtest.py rename to interpreter/llvm-project/llvm/utils/abtest.py diff --git a/interpreter/llvm/src/utils/add_argument_names.py b/interpreter/llvm-project/llvm/utils/add_argument_names.py similarity index 100% rename from interpreter/llvm/src/utils/add_argument_names.py rename to interpreter/llvm-project/llvm/utils/add_argument_names.py diff --git a/interpreter/llvm/src/utils/bisect b/interpreter/llvm-project/llvm/utils/bisect similarity index 100% rename from interpreter/llvm/src/utils/bisect rename to interpreter/llvm-project/llvm/utils/bisect diff --git a/interpreter/llvm/src/utils/bisect-skip-count b/interpreter/llvm-project/llvm/utils/bisect-skip-count similarity index 100% rename from interpreter/llvm/src/utils/bisect-skip-count rename to interpreter/llvm-project/llvm/utils/bisect-skip-count diff --git a/interpreter/llvm/src/utils/bugpoint/RemoteRunSafely.sh b/interpreter/llvm-project/llvm/utils/bugpoint/RemoteRunSafely.sh similarity index 100% rename from interpreter/llvm/src/utils/bugpoint/RemoteRunSafely.sh rename to interpreter/llvm-project/llvm/utils/bugpoint/RemoteRunSafely.sh diff --git a/interpreter/llvm/src/utils/bugpoint_gisel_reducer.py b/interpreter/llvm-project/llvm/utils/bugpoint_gisel_reducer.py similarity index 100% rename from interpreter/llvm/src/utils/bugpoint_gisel_reducer.py rename to interpreter/llvm-project/llvm/utils/bugpoint_gisel_reducer.py diff --git a/interpreter/llvm/src/utils/check-each-file b/interpreter/llvm-project/llvm/utils/check-each-file similarity index 100% rename from interpreter/llvm/src/utils/check-each-file rename to interpreter/llvm-project/llvm/utils/check-each-file diff --git a/interpreter/llvm/src/utils/check_ninja_deps.py b/interpreter/llvm-project/llvm/utils/check_ninja_deps.py similarity index 100% rename from interpreter/llvm/src/utils/check_ninja_deps.py rename to interpreter/llvm-project/llvm/utils/check_ninja_deps.py diff --git a/interpreter/llvm/src/utils/chunk-print-before-all.py b/interpreter/llvm-project/llvm/utils/chunk-print-before-all.py similarity index 100% rename from interpreter/llvm/src/utils/chunk-print-before-all.py rename to interpreter/llvm-project/llvm/utils/chunk-print-before-all.py diff --git a/interpreter/llvm/src/utils/clang-parse-diagnostics-file b/interpreter/llvm-project/llvm/utils/clang-parse-diagnostics-file similarity index 100% rename from interpreter/llvm/src/utils/clang-parse-diagnostics-file rename to interpreter/llvm-project/llvm/utils/clang-parse-diagnostics-file diff --git a/interpreter/llvm/src/utils/codegen-diff b/interpreter/llvm-project/llvm/utils/codegen-diff similarity index 100% rename from interpreter/llvm/src/utils/codegen-diff rename to interpreter/llvm-project/llvm/utils/codegen-diff diff --git a/interpreter/llvm/src/utils/collect_and_build_with_pgo.py b/interpreter/llvm-project/llvm/utils/collect_and_build_with_pgo.py similarity index 100% rename from interpreter/llvm/src/utils/collect_and_build_with_pgo.py rename to interpreter/llvm-project/llvm/utils/collect_and_build_with_pgo.py diff --git a/interpreter/llvm/src/utils/convert-constraint-log-to-z3.py b/interpreter/llvm-project/llvm/utils/convert-constraint-log-to-z3.py similarity index 100% rename from interpreter/llvm/src/utils/convert-constraint-log-to-z3.py rename to interpreter/llvm-project/llvm/utils/convert-constraint-log-to-z3.py diff --git a/interpreter/llvm/src/utils/count/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/count/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/count/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/count/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/count/count.c b/interpreter/llvm-project/llvm/utils/count/count.c similarity index 100% rename from interpreter/llvm/src/utils/count/count.c rename to interpreter/llvm-project/llvm/utils/count/count.c diff --git a/interpreter/llvm/src/utils/countloc.sh b/interpreter/llvm-project/llvm/utils/countloc.sh similarity index 100% rename from interpreter/llvm/src/utils/countloc.sh rename to interpreter/llvm-project/llvm/utils/countloc.sh diff --git a/interpreter/llvm/src/utils/create_ladder_graph.py b/interpreter/llvm-project/llvm/utils/create_ladder_graph.py similarity index 100% rename from interpreter/llvm/src/utils/create_ladder_graph.py rename to interpreter/llvm-project/llvm/utils/create_ladder_graph.py diff --git a/interpreter/llvm/src/utils/crosstool/ARM/README b/interpreter/llvm-project/llvm/utils/crosstool/ARM/README similarity index 100% rename from interpreter/llvm/src/utils/crosstool/ARM/README rename to interpreter/llvm-project/llvm/utils/crosstool/ARM/README diff --git a/interpreter/llvm/src/utils/crosstool/ARM/build-install-linux.sh b/interpreter/llvm-project/llvm/utils/crosstool/ARM/build-install-linux.sh similarity index 100% rename from interpreter/llvm/src/utils/crosstool/ARM/build-install-linux.sh rename to interpreter/llvm-project/llvm/utils/crosstool/ARM/build-install-linux.sh diff --git a/interpreter/llvm/src/utils/crosstool/create-snapshots.sh b/interpreter/llvm-project/llvm/utils/crosstool/create-snapshots.sh similarity index 100% rename from interpreter/llvm/src/utils/crosstool/create-snapshots.sh rename to interpreter/llvm-project/llvm/utils/crosstool/create-snapshots.sh diff --git a/interpreter/llvm/src/utils/demangle_tree.py b/interpreter/llvm-project/llvm/utils/demangle_tree.py similarity index 100% rename from interpreter/llvm/src/utils/demangle_tree.py rename to interpreter/llvm-project/llvm/utils/demangle_tree.py diff --git a/interpreter/llvm/src/utils/docker/README b/interpreter/llvm-project/llvm/utils/docker/README similarity index 100% rename from interpreter/llvm/src/utils/docker/README rename to interpreter/llvm-project/llvm/utils/docker/README diff --git a/interpreter/llvm/src/utils/docker/build_docker_image.sh b/interpreter/llvm-project/llvm/utils/docker/build_docker_image.sh similarity index 100% rename from interpreter/llvm/src/utils/docker/build_docker_image.sh rename to interpreter/llvm-project/llvm/utils/docker/build_docker_image.sh diff --git a/interpreter/llvm/src/utils/docker/debian8/Dockerfile b/interpreter/llvm-project/llvm/utils/docker/debian8/Dockerfile similarity index 100% rename from interpreter/llvm/src/utils/docker/debian8/Dockerfile rename to interpreter/llvm-project/llvm/utils/docker/debian8/Dockerfile diff --git a/interpreter/llvm/src/utils/docker/example/Dockerfile b/interpreter/llvm-project/llvm/utils/docker/example/Dockerfile similarity index 100% rename from interpreter/llvm/src/utils/docker/example/Dockerfile rename to interpreter/llvm-project/llvm/utils/docker/example/Dockerfile diff --git a/interpreter/llvm/src/utils/docker/nvidia-cuda/Dockerfile b/interpreter/llvm-project/llvm/utils/docker/nvidia-cuda/Dockerfile similarity index 100% rename from interpreter/llvm/src/utils/docker/nvidia-cuda/Dockerfile rename to interpreter/llvm-project/llvm/utils/docker/nvidia-cuda/Dockerfile diff --git a/interpreter/llvm/src/utils/docker/scripts/build_install_llvm.sh b/interpreter/llvm-project/llvm/utils/docker/scripts/build_install_llvm.sh similarity index 100% rename from interpreter/llvm/src/utils/docker/scripts/build_install_llvm.sh rename to interpreter/llvm-project/llvm/utils/docker/scripts/build_install_llvm.sh diff --git a/interpreter/llvm/src/utils/docker/scripts/checkout.sh b/interpreter/llvm-project/llvm/utils/docker/scripts/checkout.sh similarity index 100% rename from interpreter/llvm/src/utils/docker/scripts/checkout.sh rename to interpreter/llvm-project/llvm/utils/docker/scripts/checkout.sh diff --git a/interpreter/llvm/src/utils/docker/scripts/llvm_checksum/llvm_checksum.py b/interpreter/llvm-project/llvm/utils/docker/scripts/llvm_checksum/llvm_checksum.py similarity index 100% rename from interpreter/llvm/src/utils/docker/scripts/llvm_checksum/llvm_checksum.py rename to interpreter/llvm-project/llvm/utils/docker/scripts/llvm_checksum/llvm_checksum.py diff --git a/interpreter/llvm/src/utils/docker/scripts/llvm_checksum/project_tree.py b/interpreter/llvm-project/llvm/utils/docker/scripts/llvm_checksum/project_tree.py similarity index 100% rename from interpreter/llvm/src/utils/docker/scripts/llvm_checksum/project_tree.py rename to interpreter/llvm-project/llvm/utils/docker/scripts/llvm_checksum/project_tree.py diff --git a/interpreter/llvm/src/utils/emacs/README b/interpreter/llvm-project/llvm/utils/emacs/README similarity index 100% rename from interpreter/llvm/src/utils/emacs/README rename to interpreter/llvm-project/llvm/utils/emacs/README diff --git a/interpreter/llvm/src/utils/emacs/emacs.el b/interpreter/llvm-project/llvm/utils/emacs/emacs.el similarity index 100% rename from interpreter/llvm/src/utils/emacs/emacs.el rename to interpreter/llvm-project/llvm/utils/emacs/emacs.el diff --git a/interpreter/llvm/src/utils/emacs/llvm-mode.el b/interpreter/llvm-project/llvm/utils/emacs/llvm-mode.el similarity index 100% rename from interpreter/llvm/src/utils/emacs/llvm-mode.el rename to interpreter/llvm-project/llvm/utils/emacs/llvm-mode.el diff --git a/interpreter/llvm/src/utils/emacs/tablegen-mode.el b/interpreter/llvm-project/llvm/utils/emacs/tablegen-mode.el similarity index 100% rename from interpreter/llvm/src/utils/emacs/tablegen-mode.el rename to interpreter/llvm-project/llvm/utils/emacs/tablegen-mode.el diff --git a/interpreter/llvm/src/utils/extract-section.py b/interpreter/llvm-project/llvm/utils/extract-section.py similarity index 100% rename from interpreter/llvm/src/utils/extract-section.py rename to interpreter/llvm-project/llvm/utils/extract-section.py diff --git a/interpreter/llvm/src/utils/extract_symbols.py b/interpreter/llvm-project/llvm/utils/extract_symbols.py similarity index 100% rename from interpreter/llvm/src/utils/extract_symbols.py rename to interpreter/llvm-project/llvm/utils/extract_symbols.py diff --git a/interpreter/llvm/src/utils/extract_vplan.py b/interpreter/llvm-project/llvm/utils/extract_vplan.py similarity index 100% rename from interpreter/llvm/src/utils/extract_vplan.py rename to interpreter/llvm-project/llvm/utils/extract_vplan.py diff --git a/interpreter/llvm/src/utils/findmisopt b/interpreter/llvm-project/llvm/utils/findmisopt similarity index 100% rename from interpreter/llvm/src/utils/findmisopt rename to interpreter/llvm-project/llvm/utils/findmisopt diff --git a/interpreter/llvm/src/utils/findoptdiff b/interpreter/llvm-project/llvm/utils/findoptdiff similarity index 100% rename from interpreter/llvm/src/utils/findoptdiff rename to interpreter/llvm-project/llvm/utils/findoptdiff diff --git a/interpreter/llvm/src/utils/findsym.pl b/interpreter/llvm-project/llvm/utils/findsym.pl similarity index 100% rename from interpreter/llvm/src/utils/findsym.pl rename to interpreter/llvm-project/llvm/utils/findsym.pl diff --git a/interpreter/llvm/src/utils/fpcmp/fpcmp.cpp b/interpreter/llvm-project/llvm/utils/fpcmp/fpcmp.cpp similarity index 100% rename from interpreter/llvm/src/utils/fpcmp/fpcmp.cpp rename to interpreter/llvm-project/llvm/utils/fpcmp/fpcmp.cpp diff --git a/interpreter/llvm/src/utils/gdb-scripts/prettyprinters.py b/interpreter/llvm-project/llvm/utils/gdb-scripts/prettyprinters.py similarity index 100% rename from interpreter/llvm/src/utils/gdb-scripts/prettyprinters.py rename to interpreter/llvm-project/llvm/utils/gdb-scripts/prettyprinters.py diff --git a/interpreter/llvm/src/utils/getsrcs.sh b/interpreter/llvm-project/llvm/utils/getsrcs.sh similarity index 100% rename from interpreter/llvm/src/utils/getsrcs.sh rename to interpreter/llvm-project/llvm/utils/getsrcs.sh diff --git a/interpreter/llvm/src/utils/git/arcfilter.sh b/interpreter/llvm-project/llvm/utils/git/arcfilter.sh similarity index 100% rename from interpreter/llvm/src/utils/git/arcfilter.sh rename to interpreter/llvm-project/llvm/utils/git/arcfilter.sh diff --git a/interpreter/llvm/src/utils/git/pre-push.py b/interpreter/llvm-project/llvm/utils/git/pre-push.py similarity index 100% rename from interpreter/llvm/src/utils/git/pre-push.py rename to interpreter/llvm-project/llvm/utils/git/pre-push.py diff --git a/interpreter/llvm/src/utils/indirect_calls.py b/interpreter/llvm-project/llvm/utils/indirect_calls.py similarity index 100% rename from interpreter/llvm/src/utils/indirect_calls.py rename to interpreter/llvm-project/llvm/utils/indirect_calls.py diff --git a/interpreter/llvm/src/utils/jedit/README b/interpreter/llvm-project/llvm/utils/jedit/README similarity index 100% rename from interpreter/llvm/src/utils/jedit/README rename to interpreter/llvm-project/llvm/utils/jedit/README diff --git a/interpreter/llvm/src/utils/jedit/tablegen.xml b/interpreter/llvm-project/llvm/utils/jedit/tablegen.xml similarity index 100% rename from interpreter/llvm/src/utils/jedit/tablegen.xml rename to interpreter/llvm-project/llvm/utils/jedit/tablegen.xml diff --git a/interpreter/llvm/src/utils/kate/README b/interpreter/llvm-project/llvm/utils/kate/README similarity index 100% rename from interpreter/llvm/src/utils/kate/README rename to interpreter/llvm-project/llvm/utils/kate/README diff --git a/interpreter/llvm/src/utils/kate/llvm-tablegen.xml b/interpreter/llvm-project/llvm/utils/kate/llvm-tablegen.xml similarity index 100% rename from interpreter/llvm/src/utils/kate/llvm-tablegen.xml rename to interpreter/llvm-project/llvm/utils/kate/llvm-tablegen.xml diff --git a/interpreter/llvm/src/utils/kate/llvm.xml b/interpreter/llvm-project/llvm/utils/kate/llvm.xml similarity index 100% rename from interpreter/llvm/src/utils/kate/llvm.xml rename to interpreter/llvm-project/llvm/utils/kate/llvm.xml diff --git a/interpreter/llvm/src/utils/lint/common_lint.py b/interpreter/llvm-project/llvm/utils/lint/common_lint.py similarity index 100% rename from interpreter/llvm/src/utils/lint/common_lint.py rename to interpreter/llvm-project/llvm/utils/lint/common_lint.py diff --git a/interpreter/llvm/src/utils/lint/cpp_lint.py b/interpreter/llvm-project/llvm/utils/lint/cpp_lint.py similarity index 100% rename from interpreter/llvm/src/utils/lint/cpp_lint.py rename to interpreter/llvm-project/llvm/utils/lint/cpp_lint.py diff --git a/interpreter/llvm/src/utils/lint/generic_lint.py b/interpreter/llvm-project/llvm/utils/lint/generic_lint.py similarity index 100% rename from interpreter/llvm/src/utils/lint/generic_lint.py rename to interpreter/llvm-project/llvm/utils/lint/generic_lint.py diff --git a/interpreter/llvm/src/utils/lint/remove_trailing_whitespace.sh b/interpreter/llvm-project/llvm/utils/lint/remove_trailing_whitespace.sh similarity index 100% rename from interpreter/llvm/src/utils/lint/remove_trailing_whitespace.sh rename to interpreter/llvm-project/llvm/utils/lint/remove_trailing_whitespace.sh diff --git a/interpreter/llvm/src/utils/lit/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/lit/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/lit/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/lit/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/lit/LICENSE.TXT b/interpreter/llvm-project/llvm/utils/lit/LICENSE.TXT similarity index 100% rename from interpreter/llvm/src/utils/lit/LICENSE.TXT rename to interpreter/llvm-project/llvm/utils/lit/LICENSE.TXT diff --git a/interpreter/llvm/src/utils/lit/MANIFEST.in b/interpreter/llvm-project/llvm/utils/lit/MANIFEST.in similarity index 100% rename from interpreter/llvm/src/utils/lit/MANIFEST.in rename to interpreter/llvm-project/llvm/utils/lit/MANIFEST.in diff --git a/interpreter/llvm/src/utils/lit/README.txt b/interpreter/llvm-project/llvm/utils/lit/README.txt similarity index 100% rename from interpreter/llvm/src/utils/lit/README.txt rename to interpreter/llvm-project/llvm/utils/lit/README.txt diff --git a/interpreter/llvm/src/utils/lit/examples/README.txt b/interpreter/llvm-project/llvm/utils/lit/examples/README.txt similarity index 100% rename from interpreter/llvm/src/utils/lit/examples/README.txt rename to interpreter/llvm-project/llvm/utils/lit/examples/README.txt diff --git a/interpreter/llvm/src/utils/lit/examples/many-tests/ManyTests.py b/interpreter/llvm-project/llvm/utils/lit/examples/many-tests/ManyTests.py similarity index 100% rename from interpreter/llvm/src/utils/lit/examples/many-tests/ManyTests.py rename to interpreter/llvm-project/llvm/utils/lit/examples/many-tests/ManyTests.py diff --git a/interpreter/llvm/src/utils/lit/examples/many-tests/README.txt b/interpreter/llvm-project/llvm/utils/lit/examples/many-tests/README.txt similarity index 100% rename from interpreter/llvm/src/utils/lit/examples/many-tests/README.txt rename to interpreter/llvm-project/llvm/utils/lit/examples/many-tests/README.txt diff --git a/interpreter/llvm/src/utils/lit/examples/many-tests/lit.cfg b/interpreter/llvm-project/llvm/utils/lit/examples/many-tests/lit.cfg similarity index 100% rename from interpreter/llvm/src/utils/lit/examples/many-tests/lit.cfg rename to interpreter/llvm-project/llvm/utils/lit/examples/many-tests/lit.cfg diff --git a/interpreter/llvm/src/utils/lit/lit.py b/interpreter/llvm-project/llvm/utils/lit/lit.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit.py rename to interpreter/llvm-project/llvm/utils/lit/lit.py diff --git a/interpreter/llvm/src/utils/lit/lit/BooleanExpression.py b/interpreter/llvm-project/llvm/utils/lit/lit/BooleanExpression.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/BooleanExpression.py rename to interpreter/llvm-project/llvm/utils/lit/lit/BooleanExpression.py diff --git a/interpreter/llvm/src/utils/lit/lit/ExampleTests.ObjDir/lit.site.cfg b/interpreter/llvm-project/llvm/utils/lit/lit/ExampleTests.ObjDir/lit.site.cfg similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/ExampleTests.ObjDir/lit.site.cfg rename to interpreter/llvm-project/llvm/utils/lit/lit/ExampleTests.ObjDir/lit.site.cfg diff --git a/interpreter/llvm/src/utils/lit/lit/LitConfig.py b/interpreter/llvm-project/llvm/utils/lit/lit/LitConfig.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/LitConfig.py rename to interpreter/llvm-project/llvm/utils/lit/lit/LitConfig.py diff --git a/interpreter/llvm/src/utils/lit/lit/LitTestCase.py b/interpreter/llvm-project/llvm/utils/lit/lit/LitTestCase.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/LitTestCase.py rename to interpreter/llvm-project/llvm/utils/lit/lit/LitTestCase.py diff --git a/interpreter/llvm/src/utils/lit/lit/ProgressBar.py b/interpreter/llvm-project/llvm/utils/lit/lit/ProgressBar.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/ProgressBar.py rename to interpreter/llvm-project/llvm/utils/lit/lit/ProgressBar.py diff --git a/interpreter/llvm/src/utils/lit/lit/ShCommands.py b/interpreter/llvm-project/llvm/utils/lit/lit/ShCommands.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/ShCommands.py rename to interpreter/llvm-project/llvm/utils/lit/lit/ShCommands.py diff --git a/interpreter/llvm/src/utils/lit/lit/ShUtil.py b/interpreter/llvm-project/llvm/utils/lit/lit/ShUtil.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/ShUtil.py rename to interpreter/llvm-project/llvm/utils/lit/lit/ShUtil.py diff --git a/interpreter/llvm/src/utils/lit/lit/Test.py b/interpreter/llvm-project/llvm/utils/lit/lit/Test.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/Test.py rename to interpreter/llvm-project/llvm/utils/lit/lit/Test.py diff --git a/interpreter/llvm/src/utils/lit/lit/TestRunner.py b/interpreter/llvm-project/llvm/utils/lit/lit/TestRunner.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/TestRunner.py rename to interpreter/llvm-project/llvm/utils/lit/lit/TestRunner.py diff --git a/interpreter/llvm/src/utils/lit/lit/TestTimes.py b/interpreter/llvm-project/llvm/utils/lit/lit/TestTimes.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/TestTimes.py rename to interpreter/llvm-project/llvm/utils/lit/lit/TestTimes.py diff --git a/interpreter/llvm/src/utils/lit/lit/TestingConfig.py b/interpreter/llvm-project/llvm/utils/lit/lit/TestingConfig.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/TestingConfig.py rename to interpreter/llvm-project/llvm/utils/lit/lit/TestingConfig.py diff --git a/interpreter/llvm/src/utils/lit/lit/__init__.py b/interpreter/llvm-project/llvm/utils/lit/lit/__init__.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/__init__.py rename to interpreter/llvm-project/llvm/utils/lit/lit/__init__.py diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/__init__.py b/interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/__init__.py similarity index 100% rename from interpreter/llvm/src/bindings/python/llvm/tests/__init__.py rename to interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/__init__.py diff --git a/interpreter/llvm/src/utils/lit/lit/builtin_commands/cat.py b/interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/cat.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/builtin_commands/cat.py rename to interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/cat.py diff --git a/interpreter/llvm/src/utils/lit/lit/builtin_commands/diff.py b/interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/diff.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/builtin_commands/diff.py rename to interpreter/llvm-project/llvm/utils/lit/lit/builtin_commands/diff.py diff --git a/interpreter/llvm/src/utils/lit/lit/cl_arguments.py b/interpreter/llvm-project/llvm/utils/lit/lit/cl_arguments.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/cl_arguments.py rename to interpreter/llvm-project/llvm/utils/lit/lit/cl_arguments.py diff --git a/interpreter/llvm/src/utils/lit/lit/discovery.py b/interpreter/llvm-project/llvm/utils/lit/lit/discovery.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/discovery.py rename to interpreter/llvm-project/llvm/utils/lit/lit/discovery.py diff --git a/interpreter/llvm/src/utils/lit/lit/display.py b/interpreter/llvm-project/llvm/utils/lit/lit/display.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/display.py rename to interpreter/llvm-project/llvm/utils/lit/lit/display.py diff --git a/interpreter/llvm/src/utils/lit/lit/formats/__init__.py b/interpreter/llvm-project/llvm/utils/lit/lit/formats/__init__.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/formats/__init__.py rename to interpreter/llvm-project/llvm/utils/lit/lit/formats/__init__.py diff --git a/interpreter/llvm/src/utils/lit/lit/formats/base.py b/interpreter/llvm-project/llvm/utils/lit/lit/formats/base.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/formats/base.py rename to interpreter/llvm-project/llvm/utils/lit/lit/formats/base.py diff --git a/interpreter/llvm/src/utils/lit/lit/formats/googletest.py b/interpreter/llvm-project/llvm/utils/lit/lit/formats/googletest.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/formats/googletest.py rename to interpreter/llvm-project/llvm/utils/lit/lit/formats/googletest.py diff --git a/interpreter/llvm/src/utils/lit/lit/formats/shtest.py b/interpreter/llvm-project/llvm/utils/lit/lit/formats/shtest.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/formats/shtest.py rename to interpreter/llvm-project/llvm/utils/lit/lit/formats/shtest.py diff --git a/interpreter/llvm/src/utils/lit/lit/llvm/__init__.py b/interpreter/llvm-project/llvm/utils/lit/lit/llvm/__init__.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/llvm/__init__.py rename to interpreter/llvm-project/llvm/utils/lit/lit/llvm/__init__.py diff --git a/interpreter/llvm/src/utils/lit/lit/llvm/config.py b/interpreter/llvm-project/llvm/utils/lit/lit/llvm/config.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/llvm/config.py rename to interpreter/llvm-project/llvm/utils/lit/lit/llvm/config.py diff --git a/interpreter/llvm/src/utils/lit/lit/llvm/subst.py b/interpreter/llvm-project/llvm/utils/lit/lit/llvm/subst.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/llvm/subst.py rename to interpreter/llvm-project/llvm/utils/lit/lit/llvm/subst.py diff --git a/interpreter/llvm/src/utils/lit/lit/main.py b/interpreter/llvm-project/llvm/utils/lit/lit/main.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/main.py rename to interpreter/llvm-project/llvm/utils/lit/lit/main.py diff --git a/interpreter/llvm/src/utils/lit/lit/reports.py b/interpreter/llvm-project/llvm/utils/lit/lit/reports.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/reports.py rename to interpreter/llvm-project/llvm/utils/lit/lit/reports.py diff --git a/interpreter/llvm/src/utils/lit/lit/run.py b/interpreter/llvm-project/llvm/utils/lit/lit/run.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/run.py rename to interpreter/llvm-project/llvm/utils/lit/lit/run.py diff --git a/interpreter/llvm/src/utils/lit/lit/util.py b/interpreter/llvm-project/llvm/utils/lit/lit/util.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/util.py rename to interpreter/llvm-project/llvm/utils/lit/lit/util.py diff --git a/interpreter/llvm/src/utils/lit/lit/worker.py b/interpreter/llvm-project/llvm/utils/lit/lit/worker.py similarity index 100% rename from interpreter/llvm/src/utils/lit/lit/worker.py rename to interpreter/llvm-project/llvm/utils/lit/lit/worker.py diff --git a/interpreter/llvm/src/utils/lit/setup.py b/interpreter/llvm-project/llvm/utils/lit/setup.py similarity index 100% rename from interpreter/llvm/src/utils/lit/setup.py rename to interpreter/llvm-project/llvm/utils/lit/setup.py diff --git a/interpreter/llvm/src/utils/lit/utils/README.txt b/interpreter/llvm-project/llvm/utils/lit/utils/README.txt similarity index 100% rename from interpreter/llvm/src/utils/lit/utils/README.txt rename to interpreter/llvm-project/llvm/utils/lit/utils/README.txt diff --git a/interpreter/llvm/src/utils/lit/utils/check-coverage b/interpreter/llvm-project/llvm/utils/lit/utils/check-coverage similarity index 100% rename from interpreter/llvm/src/utils/lit/utils/check-coverage rename to interpreter/llvm-project/llvm/utils/lit/utils/check-coverage diff --git a/interpreter/llvm/src/utils/lit/utils/check-sdist b/interpreter/llvm-project/llvm/utils/lit/utils/check-sdist similarity index 100% rename from interpreter/llvm/src/utils/lit/utils/check-sdist rename to interpreter/llvm-project/llvm/utils/lit/utils/check-sdist diff --git a/interpreter/llvm/src/utils/lldbDataFormatters.py b/interpreter/llvm-project/llvm/utils/lldbDataFormatters.py similarity index 100% rename from interpreter/llvm/src/utils/lldbDataFormatters.py rename to interpreter/llvm-project/llvm/utils/lldbDataFormatters.py diff --git a/interpreter/llvm/src/utils/llvm-compilers-check b/interpreter/llvm-project/llvm/utils/llvm-compilers-check similarity index 100% rename from interpreter/llvm/src/utils/llvm-compilers-check rename to interpreter/llvm-project/llvm/utils/llvm-compilers-check diff --git a/interpreter/llvm/src/utils/llvm-gisel-cov.py b/interpreter/llvm-project/llvm/utils/llvm-gisel-cov.py similarity index 100% rename from interpreter/llvm/src/utils/llvm-gisel-cov.py rename to interpreter/llvm-project/llvm/utils/llvm-gisel-cov.py diff --git a/interpreter/llvm/src/utils/llvm-lit/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/llvm-lit/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/llvm-lit/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/llvm-lit/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/llvm-lit/llvm-lit.in b/interpreter/llvm-project/llvm/utils/llvm-lit/llvm-lit.in similarity index 100% rename from interpreter/llvm/src/utils/llvm-lit/llvm-lit.in rename to interpreter/llvm-project/llvm/utils/llvm-lit/llvm-lit.in diff --git a/interpreter/llvm/src/utils/llvm-locstats/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/llvm-locstats/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/llvm-locstats/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/llvm-locstats/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/llvm-locstats/llvm-locstats.py b/interpreter/llvm-project/llvm/utils/llvm-locstats/llvm-locstats.py similarity index 100% rename from interpreter/llvm/src/utils/llvm-locstats/llvm-locstats.py rename to interpreter/llvm-project/llvm/utils/llvm-locstats/llvm-locstats.py diff --git a/interpreter/llvm/src/utils/llvm-native-gxx b/interpreter/llvm-project/llvm/utils/llvm-native-gxx similarity index 100% rename from interpreter/llvm/src/utils/llvm-native-gxx rename to interpreter/llvm-project/llvm/utils/llvm-native-gxx diff --git a/interpreter/llvm/src/utils/llvm-original-di-preservation.py b/interpreter/llvm-project/llvm/utils/llvm-original-di-preservation.py similarity index 100% rename from interpreter/llvm/src/utils/llvm-original-di-preservation.py rename to interpreter/llvm-project/llvm/utils/llvm-original-di-preservation.py diff --git a/interpreter/llvm/src/utils/llvm.grm b/interpreter/llvm-project/llvm/utils/llvm.grm similarity index 100% rename from interpreter/llvm/src/utils/llvm.grm rename to interpreter/llvm-project/llvm/utils/llvm.grm diff --git a/interpreter/llvm/src/utils/llvmdo b/interpreter/llvm-project/llvm/utils/llvmdo similarity index 100% rename from interpreter/llvm/src/utils/llvmdo rename to interpreter/llvm-project/llvm/utils/llvmdo diff --git a/interpreter/llvm/src/utils/llvmgrep b/interpreter/llvm-project/llvm/utils/llvmgrep similarity index 100% rename from interpreter/llvm/src/utils/llvmgrep rename to interpreter/llvm-project/llvm/utils/llvmgrep diff --git a/interpreter/llvm/src/utils/merge-stats.py b/interpreter/llvm-project/llvm/utils/merge-stats.py similarity index 100% rename from interpreter/llvm/src/utils/merge-stats.py rename to interpreter/llvm-project/llvm/utils/merge-stats.py diff --git a/interpreter/llvm/src/utils/not/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/not/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/not/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/not/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/not/not.cpp b/interpreter/llvm-project/llvm/utils/not/not.cpp similarity index 100% rename from interpreter/llvm/src/utils/not/not.cpp rename to interpreter/llvm-project/llvm/utils/not/not.cpp diff --git a/interpreter/llvm/src/utils/prepare-code-coverage-artifact.py b/interpreter/llvm-project/llvm/utils/prepare-code-coverage-artifact.py similarity index 100% rename from interpreter/llvm/src/utils/prepare-code-coverage-artifact.py rename to interpreter/llvm-project/llvm/utils/prepare-code-coverage-artifact.py diff --git a/interpreter/llvm/src/utils/release/build_llvm_package.bat b/interpreter/llvm-project/llvm/utils/release/build_llvm_package.bat similarity index 97% rename from interpreter/llvm/src/utils/release/build_llvm_package.bat rename to interpreter/llvm-project/llvm/utils/release/build_llvm_package.bat index e2eb3751af0ea..be207244c69bd 100755 --- a/interpreter/llvm/src/utils/release/build_llvm_package.bat +++ b/interpreter/llvm-project/llvm/utils/release/build_llvm_package.bat @@ -1,149 +1,149 @@ -@echo off -setlocal - -REM Script for building the LLVM installer on Windows, -REM used for the the weekly snapshots at http://www.llvm.org/builds. -REM -REM Usage: build_llvm_package.bat - -REM Prerequisites: -REM -REM Visual Studio 2019, CMake, Ninja, GNUWin32, SWIG, Python 3, -REM NSIS with the strlen_8192 patch, -REM Visual Studio 2019 SDK and Nuget (for the clang-format plugin), -REM Perl (for the OpenMP run-time), 7Zip. -REM -REM -REM For LLDB, SWIG version <= 3.0.8 needs to be used to work around -REM https://github.com/swig/swig/issues/769 - - -REM You need to modify the paths below: -set vsdevcmd=C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat - -set python32_dir=C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32 -set python64_dir=C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36 - -for /f "usebackq" %%i in (`PowerShell ^(Get-Date^).ToString^('yyyyMMdd'^)`) do set datestamp=%%i - -set revision=%1 -set package_version=13.0.0-%revision:~0,8% -set clang_format_vs_version=13.0.0.%datestamp% -set build_dir=llvm_package_%revision:~0,8% - -echo Revision: %revision% -echo Package version: %package_version% -echo Clang format plugin version: %clang_format_vs_version% -echo Build dir: %build_dir% -echo. -pause - -mkdir %build_dir% -cd %build_dir% - -echo Checking out %revision% -curl -L https://github.com/llvm/llvm-project/archive/%revision%.zip -o src.zip || exit /b -7z x src.zip || exit /b -mv llvm-project-* llvm-project || exit /b - -REM Setting CMAKE_CL_SHOWINCLUDES_PREFIX to work around PR27226. -set cmake_flags=^ - -DCMAKE_BUILD_TYPE=Release ^ - -DLLVM_ENABLE_ASSERTIONS=ON ^ - -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON ^ - -DLLVM_BUILD_LLVM_C_DYLIB=ON ^ - -DCMAKE_INSTALL_UCRT_LIBRARIES=ON ^ - -DCLANG_FORMAT_VS_VERSION=%clang_format_vs_version% ^ - -DPACKAGE_VERSION=%package_version% ^ - -DLLDB_RELOCATABLE_PYTHON=1 ^ - -DLLDB_TEST_COMPILER=%cd%\build32_stage0\bin\clang.exe ^ - -DCMAKE_CL_SHOWINCLUDES_PREFIX="Note: including file: " ^ - -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra;lld;compiler-rt;openmp;lldb" - -REM TODO: Run the "check-all" tests. - -set "VSCMD_START_DIR=%CD%" -call "%vsdevcmd%" -arch=x86 -set CC= -set CXX= -mkdir build32_stage0 -cd build32_stage0 -cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b -ninja all || ninja all || ninja all || exit /b -ninja check || ninja check || ninja check || exit /b -ninja check-clang || ninja check-clang || ninja check-clang || exit /b -ninja check-lld || ninja check-lld || ninja check-lld || exit /b -ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b -ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b -ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b -cd.. - -mkdir build32 -cd build32 -set CC=..\build32_stage0\bin\clang-cl -set CXX=..\build32_stage0\bin\clang-cl -cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b -ninja all || ninja all || ninja all || exit /b -ninja check || ninja check || ninja check || exit /b -ninja check-clang || ninja check-clang || ninja check-clang || exit /b -ninja check-lld || ninja check-lld || ninja check-lld || exit /b -ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b -ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b -ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b -ninja package || exit /b - -7z x LLVM-%package_version%-win32.exe -orepack -rmdir /s /q repack\$PLUGINSDIR -del repack\Uninstall.exe -7z a LLVM-%package_version%-win32.zip .\repack\* -mx9 -cd .. - - -REM The plug-in is built separately as it uses a statically linked clang-format.exe. -mkdir build_vsix -cd build_vsix -REM Having VSSDKINSTALL set makes devenv *not* find the SDK for some reason. -set VSSDKINSTALL= -set CC=..\build32_stage0\bin\clang-cl -set CXX=..\build32_stage0\bin\clang-cl -cmake -GNinja %cmake_flags% -DLLVM_USE_CRT_RELEASE=MT -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b -ninja clang_format_vsix || exit /b -copy ..\llvm-project\llvm\tools\clang\tools\clang-format-vs\ClangFormat\bin\Release\ClangFormat.vsix ClangFormat-r%revision%.vsix -cd .. - - -set "VSCMD_START_DIR=%CD%" -call "%vsdevcmd%" -arch=amd64 -set CC= -set CXX= -mkdir build64_stage0 -cd build64_stage0 -cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% -DPYTHON_EXECUTABLE=%python64_dir%\python.exe ..\llvm-project\llvm || exit /b -ninja all || ninja all || ninja all || exit /b -ninja check || ninja check || ninja check || exit /b -ninja check-clang || ninja check-clang || ninja check-clang || exit /b -ninja check-lld || ninja check-lld || ninja check-lld || exit /b -ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b -ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b -ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b -cd.. - -mkdir build64 -cd build64 -set CC=..\build64_stage0\bin\clang-cl -set CXX=..\build64_stage0\bin\clang-cl -cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% -DPYTHON_EXECUTABLE=%python64_dir%\python.exe ..\llvm-project\llvm || exit /b -ninja all || ninja all || ninja all || exit /b -ninja check || ninja check || ninja check || exit /b -ninja check-clang || ninja check-clang || ninja check-clang || exit /b -ninja check-lld || ninja check-lld || ninja check-lld || exit /b -ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b -ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b -ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b -ninja package || exit /b - -7z x LLVM-%package_version%-win64.exe -orepack -rmdir /s /q repack\$PLUGINSDIR -del repack\Uninstall.exe -7z a LLVM-%package_version%-win64.zip .\repack\* -mx9 -cd .. +@echo off +setlocal + +REM Script for building the LLVM installer on Windows, +REM used for the the weekly snapshots at http://www.llvm.org/builds. +REM +REM Usage: build_llvm_package.bat + +REM Prerequisites: +REM +REM Visual Studio 2019, CMake, Ninja, GNUWin32, SWIG, Python 3, +REM NSIS with the strlen_8192 patch, +REM Visual Studio 2019 SDK and Nuget (for the clang-format plugin), +REM Perl (for the OpenMP run-time), 7Zip. +REM +REM +REM For LLDB, SWIG version <= 3.0.8 needs to be used to work around +REM https://github.com/swig/swig/issues/769 + + +REM You need to modify the paths below: +set vsdevcmd=C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat + +set python32_dir=C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32 +set python64_dir=C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36 + +for /f "usebackq" %%i in (`PowerShell ^(Get-Date^).ToString^('yyyyMMdd'^)`) do set datestamp=%%i + +set revision=%1 +set package_version=13.0.0-%revision:~0,8% +set clang_format_vs_version=13.0.0.%datestamp% +set build_dir=llvm_package_%revision:~0,8% + +echo Revision: %revision% +echo Package version: %package_version% +echo Clang format plugin version: %clang_format_vs_version% +echo Build dir: %build_dir% +echo. +pause + +mkdir %build_dir% +cd %build_dir% + +echo Checking out %revision% +curl -L https://github.com/llvm/llvm-project/archive/%revision%.zip -o src.zip || exit /b +7z x src.zip || exit /b +mv llvm-project-* llvm-project || exit /b + +REM Setting CMAKE_CL_SHOWINCLUDES_PREFIX to work around PR27226. +set cmake_flags=^ + -DCMAKE_BUILD_TYPE=Release ^ + -DLLVM_ENABLE_ASSERTIONS=ON ^ + -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON ^ + -DLLVM_BUILD_LLVM_C_DYLIB=ON ^ + -DCMAKE_INSTALL_UCRT_LIBRARIES=ON ^ + -DCLANG_FORMAT_VS_VERSION=%clang_format_vs_version% ^ + -DPACKAGE_VERSION=%package_version% ^ + -DLLDB_RELOCATABLE_PYTHON=1 ^ + -DLLDB_TEST_COMPILER=%cd%\build32_stage0\bin\clang.exe ^ + -DCMAKE_CL_SHOWINCLUDES_PREFIX="Note: including file: " ^ + -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra;lld;compiler-rt;openmp;lldb" + +REM TODO: Run the "check-all" tests. + +set "VSCMD_START_DIR=%CD%" +call "%vsdevcmd%" -arch=x86 +set CC= +set CXX= +mkdir build32_stage0 +cd build32_stage0 +cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b +ninja all || ninja all || ninja all || exit /b +ninja check || ninja check || ninja check || exit /b +ninja check-clang || ninja check-clang || ninja check-clang || exit /b +ninja check-lld || ninja check-lld || ninja check-lld || exit /b +ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b +ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b +ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b +cd.. + +mkdir build32 +cd build32 +set CC=..\build32_stage0\bin\clang-cl +set CXX=..\build32_stage0\bin\clang-cl +cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b +ninja all || ninja all || ninja all || exit /b +ninja check || ninja check || ninja check || exit /b +ninja check-clang || ninja check-clang || ninja check-clang || exit /b +ninja check-lld || ninja check-lld || ninja check-lld || exit /b +ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b +ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b +ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b +ninja package || exit /b + +7z x LLVM-%package_version%-win32.exe -orepack +rmdir /s /q repack\$PLUGINSDIR +del repack\Uninstall.exe +7z a LLVM-%package_version%-win32.zip .\repack\* -mx9 +cd .. + + +REM The plug-in is built separately as it uses a statically linked clang-format.exe. +mkdir build_vsix +cd build_vsix +REM Having VSSDKINSTALL set makes devenv *not* find the SDK for some reason. +set VSSDKINSTALL= +set CC=..\build32_stage0\bin\clang-cl +set CXX=..\build32_stage0\bin\clang-cl +cmake -GNinja %cmake_flags% -DLLVM_USE_CRT_RELEASE=MT -DBUILD_CLANG_FORMAT_VS_PLUGIN=ON -DPYTHON_HOME=%python32_dir% -DPYTHON_EXECUTABLE=%python32_dir%\python.exe ..\llvm-project\llvm || exit /b +ninja clang_format_vsix || exit /b +copy ..\llvm-project\llvm\tools\clang\tools\clang-format-vs\ClangFormat\bin\Release\ClangFormat.vsix ClangFormat-r%revision%.vsix +cd .. + + +set "VSCMD_START_DIR=%CD%" +call "%vsdevcmd%" -arch=amd64 +set CC= +set CXX= +mkdir build64_stage0 +cd build64_stage0 +cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% -DPYTHON_EXECUTABLE=%python64_dir%\python.exe ..\llvm-project\llvm || exit /b +ninja all || ninja all || ninja all || exit /b +ninja check || ninja check || ninja check || exit /b +ninja check-clang || ninja check-clang || ninja check-clang || exit /b +ninja check-lld || ninja check-lld || ninja check-lld || exit /b +ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b +ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b +ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b +cd.. + +mkdir build64 +cd build64 +set CC=..\build64_stage0\bin\clang-cl +set CXX=..\build64_stage0\bin\clang-cl +cmake -GNinja %cmake_flags% -DPYTHON_HOME=%python64_dir% -DPYTHON_EXECUTABLE=%python64_dir%\python.exe ..\llvm-project\llvm || exit /b +ninja all || ninja all || ninja all || exit /b +ninja check || ninja check || ninja check || exit /b +ninja check-clang || ninja check-clang || ninja check-clang || exit /b +ninja check-lld || ninja check-lld || ninja check-lld || exit /b +ninja check-sanitizer || ninja check-sanitizer || ninja check-sanitizer || exit /b +ninja check-clang-tools || ninja check-clang-tools || ninja check-clang-tools || exit /b +ninja check-clangd || ninja check-clangd || ninja check-clangd || exit /b +ninja package || exit /b + +7z x LLVM-%package_version%-win64.exe -orepack +rmdir /s /q repack\$PLUGINSDIR +del repack\Uninstall.exe +7z a LLVM-%package_version%-win64.zip .\repack\* -mx9 +cd .. diff --git a/interpreter/llvm/src/utils/release/export.sh b/interpreter/llvm-project/llvm/utils/release/export.sh similarity index 100% rename from interpreter/llvm/src/utils/release/export.sh rename to interpreter/llvm-project/llvm/utils/release/export.sh diff --git a/interpreter/llvm/src/utils/release/findRegressions-nightly.py b/interpreter/llvm-project/llvm/utils/release/findRegressions-nightly.py similarity index 100% rename from interpreter/llvm/src/utils/release/findRegressions-nightly.py rename to interpreter/llvm-project/llvm/utils/release/findRegressions-nightly.py diff --git a/interpreter/llvm/src/utils/release/findRegressions-simple.py b/interpreter/llvm-project/llvm/utils/release/findRegressions-simple.py similarity index 100% rename from interpreter/llvm/src/utils/release/findRegressions-simple.py rename to interpreter/llvm-project/llvm/utils/release/findRegressions-simple.py diff --git a/interpreter/llvm/src/utils/release/github-upload-release.py b/interpreter/llvm-project/llvm/utils/release/github-upload-release.py similarity index 100% rename from interpreter/llvm/src/utils/release/github-upload-release.py rename to interpreter/llvm-project/llvm/utils/release/github-upload-release.py diff --git a/interpreter/llvm/src/utils/release/merge-request.sh b/interpreter/llvm-project/llvm/utils/release/merge-request.sh similarity index 100% rename from interpreter/llvm/src/utils/release/merge-request.sh rename to interpreter/llvm-project/llvm/utils/release/merge-request.sh diff --git a/interpreter/llvm/src/utils/release/test-release.sh b/interpreter/llvm-project/llvm/utils/release/test-release.sh similarity index 100% rename from interpreter/llvm/src/utils/release/test-release.sh rename to interpreter/llvm-project/llvm/utils/release/test-release.sh diff --git a/interpreter/llvm/src/utils/remote-exec.py b/interpreter/llvm-project/llvm/utils/remote-exec.py similarity index 100% rename from interpreter/llvm/src/utils/remote-exec.py rename to interpreter/llvm-project/llvm/utils/remote-exec.py diff --git a/interpreter/llvm/src/utils/revert_checker.py b/interpreter/llvm-project/llvm/utils/revert_checker.py similarity index 100% rename from interpreter/llvm/src/utils/revert_checker.py rename to interpreter/llvm-project/llvm/utils/revert_checker.py diff --git a/interpreter/llvm/src/utils/revert_checker_test.py b/interpreter/llvm-project/llvm/utils/revert_checker_test.py similarity index 100% rename from interpreter/llvm/src/utils/revert_checker_test.py rename to interpreter/llvm-project/llvm/utils/revert_checker_test.py diff --git a/interpreter/llvm/src/utils/sanitizers/ubsan_blacklist.txt b/interpreter/llvm-project/llvm/utils/sanitizers/ubsan_blacklist.txt similarity index 100% rename from interpreter/llvm/src/utils/sanitizers/ubsan_blacklist.txt rename to interpreter/llvm-project/llvm/utils/sanitizers/ubsan_blacklist.txt diff --git a/interpreter/llvm/src/utils/schedcover.py b/interpreter/llvm-project/llvm/utils/schedcover.py similarity index 100% rename from interpreter/llvm/src/utils/schedcover.py rename to interpreter/llvm-project/llvm/utils/schedcover.py diff --git a/interpreter/llvm/src/utils/shuffle_fuzz.py b/interpreter/llvm-project/llvm/utils/shuffle_fuzz.py similarity index 100% rename from interpreter/llvm/src/utils/shuffle_fuzz.py rename to interpreter/llvm-project/llvm/utils/shuffle_fuzz.py diff --git a/interpreter/llvm/src/utils/shuffle_select_fuzz_tester.py b/interpreter/llvm-project/llvm/utils/shuffle_select_fuzz_tester.py similarity index 100% rename from interpreter/llvm/src/utils/shuffle_select_fuzz_tester.py rename to interpreter/llvm-project/llvm/utils/shuffle_select_fuzz_tester.py diff --git a/interpreter/llvm/src/utils/sort_includes.py b/interpreter/llvm-project/llvm/utils/sort_includes.py similarity index 100% rename from interpreter/llvm/src/utils/sort_includes.py rename to interpreter/llvm-project/llvm/utils/sort_includes.py diff --git a/interpreter/llvm/src/utils/sysroot.py b/interpreter/llvm-project/llvm/utils/sysroot.py similarity index 100% rename from interpreter/llvm/src/utils/sysroot.py rename to interpreter/llvm-project/llvm/utils/sysroot.py diff --git a/interpreter/llvm/src/utils/testgen/mc-bundling-x86-gen.py b/interpreter/llvm-project/llvm/utils/testgen/mc-bundling-x86-gen.py similarity index 100% rename from interpreter/llvm/src/utils/testgen/mc-bundling-x86-gen.py rename to interpreter/llvm-project/llvm/utils/testgen/mc-bundling-x86-gen.py diff --git a/interpreter/llvm/src/utils/textmate/README b/interpreter/llvm-project/llvm/utils/textmate/README similarity index 100% rename from interpreter/llvm/src/utils/textmate/README rename to interpreter/llvm-project/llvm/utils/textmate/README diff --git a/interpreter/llvm/src/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage b/interpreter/llvm-project/llvm/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage similarity index 100% rename from interpreter/llvm/src/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage rename to interpreter/llvm-project/llvm/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage diff --git a/interpreter/llvm/src/utils/textmate/TableGen.tmbundle/info.plist b/interpreter/llvm-project/llvm/utils/textmate/TableGen.tmbundle/info.plist similarity index 100% rename from interpreter/llvm/src/utils/textmate/TableGen.tmbundle/info.plist rename to interpreter/llvm-project/llvm/utils/textmate/TableGen.tmbundle/info.plist diff --git a/interpreter/llvm/src/utils/unicode-case-fold.py b/interpreter/llvm-project/llvm/utils/unicode-case-fold.py similarity index 100% rename from interpreter/llvm/src/utils/unicode-case-fold.py rename to interpreter/llvm-project/llvm/utils/unicode-case-fold.py diff --git a/interpreter/llvm/src/utils/update_analyze_test_checks.py b/interpreter/llvm-project/llvm/utils/update_analyze_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_analyze_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_analyze_test_checks.py diff --git a/interpreter/llvm/src/utils/update_cc_test_checks.py b/interpreter/llvm-project/llvm/utils/update_cc_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_cc_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_cc_test_checks.py diff --git a/interpreter/llvm/src/utils/update_llc_test_checks.py b/interpreter/llvm-project/llvm/utils/update_llc_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_llc_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_llc_test_checks.py diff --git a/interpreter/llvm/src/utils/update_mca_test_checks.py b/interpreter/llvm-project/llvm/utils/update_mca_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_mca_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_mca_test_checks.py diff --git a/interpreter/llvm/src/utils/update_mir_test_checks.py b/interpreter/llvm-project/llvm/utils/update_mir_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_mir_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_mir_test_checks.py diff --git a/interpreter/llvm/src/utils/update_test_checks.py b/interpreter/llvm-project/llvm/utils/update_test_checks.py similarity index 100% rename from interpreter/llvm/src/utils/update_test_checks.py rename to interpreter/llvm-project/llvm/utils/update_test_checks.py diff --git a/interpreter/llvm/src/utils/update_test_prefix.py b/interpreter/llvm-project/llvm/utils/update_test_prefix.py similarity index 100% rename from interpreter/llvm/src/utils/update_test_prefix.py rename to interpreter/llvm-project/llvm/utils/update_test_prefix.py diff --git a/interpreter/llvm/src/utils/valgrind/i386-pc-linux-gnu.supp b/interpreter/llvm-project/llvm/utils/valgrind/i386-pc-linux-gnu.supp similarity index 100% rename from interpreter/llvm/src/utils/valgrind/i386-pc-linux-gnu.supp rename to interpreter/llvm-project/llvm/utils/valgrind/i386-pc-linux-gnu.supp diff --git a/interpreter/llvm/src/utils/valgrind/x86_64-pc-linux-gnu.supp b/interpreter/llvm-project/llvm/utils/valgrind/x86_64-pc-linux-gnu.supp similarity index 100% rename from interpreter/llvm/src/utils/valgrind/x86_64-pc-linux-gnu.supp rename to interpreter/llvm-project/llvm/utils/valgrind/x86_64-pc-linux-gnu.supp diff --git a/interpreter/llvm/src/utils/vim/README b/interpreter/llvm-project/llvm/utils/vim/README similarity index 100% rename from interpreter/llvm/src/utils/vim/README rename to interpreter/llvm-project/llvm/utils/vim/README diff --git a/interpreter/llvm/src/utils/vim/ftdetect/llvm-lit.vim b/interpreter/llvm-project/llvm/utils/vim/ftdetect/llvm-lit.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftdetect/llvm-lit.vim rename to interpreter/llvm-project/llvm/utils/vim/ftdetect/llvm-lit.vim diff --git a/interpreter/llvm/src/utils/vim/ftdetect/llvm.vim b/interpreter/llvm-project/llvm/utils/vim/ftdetect/llvm.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftdetect/llvm.vim rename to interpreter/llvm-project/llvm/utils/vim/ftdetect/llvm.vim diff --git a/interpreter/llvm/src/utils/vim/ftdetect/mir.vim b/interpreter/llvm-project/llvm/utils/vim/ftdetect/mir.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftdetect/mir.vim rename to interpreter/llvm-project/llvm/utils/vim/ftdetect/mir.vim diff --git a/interpreter/llvm/src/utils/vim/ftdetect/tablegen.vim b/interpreter/llvm-project/llvm/utils/vim/ftdetect/tablegen.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftdetect/tablegen.vim rename to interpreter/llvm-project/llvm/utils/vim/ftdetect/tablegen.vim diff --git a/interpreter/llvm/src/utils/vim/ftplugin/llvm.vim b/interpreter/llvm-project/llvm/utils/vim/ftplugin/llvm.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftplugin/llvm.vim rename to interpreter/llvm-project/llvm/utils/vim/ftplugin/llvm.vim diff --git a/interpreter/llvm/src/utils/vim/ftplugin/mir.vim b/interpreter/llvm-project/llvm/utils/vim/ftplugin/mir.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftplugin/mir.vim rename to interpreter/llvm-project/llvm/utils/vim/ftplugin/mir.vim diff --git a/interpreter/llvm/src/utils/vim/ftplugin/tablegen.vim b/interpreter/llvm-project/llvm/utils/vim/ftplugin/tablegen.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/ftplugin/tablegen.vim rename to interpreter/llvm-project/llvm/utils/vim/ftplugin/tablegen.vim diff --git a/interpreter/llvm/src/utils/vim/indent/llvm.vim b/interpreter/llvm-project/llvm/utils/vim/indent/llvm.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/indent/llvm.vim rename to interpreter/llvm-project/llvm/utils/vim/indent/llvm.vim diff --git a/interpreter/llvm/src/utils/vim/syntax/llvm.vim b/interpreter/llvm-project/llvm/utils/vim/syntax/llvm.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/syntax/llvm.vim rename to interpreter/llvm-project/llvm/utils/vim/syntax/llvm.vim diff --git a/interpreter/llvm/src/utils/vim/syntax/machine-ir.vim b/interpreter/llvm-project/llvm/utils/vim/syntax/machine-ir.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/syntax/machine-ir.vim rename to interpreter/llvm-project/llvm/utils/vim/syntax/machine-ir.vim diff --git a/interpreter/llvm/src/utils/vim/syntax/mir.vim b/interpreter/llvm-project/llvm/utils/vim/syntax/mir.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/syntax/mir.vim rename to interpreter/llvm-project/llvm/utils/vim/syntax/mir.vim diff --git a/interpreter/llvm/src/utils/vim/syntax/tablegen.vim b/interpreter/llvm-project/llvm/utils/vim/syntax/tablegen.vim similarity index 100% rename from interpreter/llvm/src/utils/vim/syntax/tablegen.vim rename to interpreter/llvm-project/llvm/utils/vim/syntax/tablegen.vim diff --git a/interpreter/llvm/src/utils/vim/vimrc b/interpreter/llvm-project/llvm/utils/vim/vimrc similarity index 100% rename from interpreter/llvm/src/utils/vim/vimrc rename to interpreter/llvm-project/llvm/utils/vim/vimrc diff --git a/interpreter/llvm/src/utils/wciia.py b/interpreter/llvm-project/llvm/utils/wciia.py similarity index 100% rename from interpreter/llvm/src/utils/wciia.py rename to interpreter/llvm-project/llvm/utils/wciia.py diff --git a/interpreter/llvm/src/utils/yaml-bench/CMakeLists.txt b/interpreter/llvm-project/llvm/utils/yaml-bench/CMakeLists.txt similarity index 100% rename from interpreter/llvm/src/utils/yaml-bench/CMakeLists.txt rename to interpreter/llvm-project/llvm/utils/yaml-bench/CMakeLists.txt diff --git a/interpreter/llvm/src/utils/yaml-bench/YAMLBench.cpp b/interpreter/llvm-project/llvm/utils/yaml-bench/YAMLBench.cpp similarity index 100% rename from interpreter/llvm/src/utils/yaml-bench/YAMLBench.cpp rename to interpreter/llvm-project/llvm/utils/yaml-bench/YAMLBench.cpp diff --git a/interpreter/llvm/ROOT/assert.h b/interpreter/llvm/ROOT/assert.h deleted file mode 100644 index 0d2c205d10476..0000000000000 --- a/interpreter/llvm/ROOT/assert.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef ROOT_INCLUDE_ASSERT_H -#define ROOT_INCLUDE_ASSERT_H -/* axel@cern.ch, 2014-12-16 - NOT part of clang but injected by ROOT. - Adds include guards for assert.h to avoid re-parse from disk. -*/ - -#include_next - -#endif /*ROOT_INCLUDE_ASSERT_H*/ diff --git a/interpreter/llvm/ROOT/stdlib.h b/interpreter/llvm/ROOT/stdlib.h deleted file mode 100644 index da12b45c2b545..0000000000000 --- a/interpreter/llvm/ROOT/stdlib.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef ROOT_INCLUDE_STDLIB_H -#define ROOT_INCLUDE_STDLIB_H -/* axel@cern.ch, 2015-06-02 - NOT part of clang but injected by ROOT. - Adds include guards for stdlib.h to avoid re-parse from disk. -*/ - -#include_next - -#endif /*ROOT_INCLUDE_STDLIB_H*/ diff --git a/interpreter/llvm/ROOT/unistd.h b/interpreter/llvm/ROOT/unistd.h deleted file mode 100644 index b865415239ee0..0000000000000 --- a/interpreter/llvm/ROOT/unistd.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef ROOT_INCLUDE_UNISTD_H -#define ROOT_INCLUDE_UNISTD_H -/* axel@cern.ch, 2015-06-12 - NOT part of clang but injected by ROOT. - Adds include guards to avoid re-parse from disk. -*/ - -#include_next - -#endif /*ROOT_INCLUDE_UNISTD_H*/ diff --git a/interpreter/llvm/src/.arcconfig b/interpreter/llvm/src/.arcconfig deleted file mode 100644 index a8e665bd920a0..0000000000000 --- a/interpreter/llvm/src/.arcconfig +++ /dev/null @@ -1,4 +0,0 @@ -{ - "repository.callsign" : "L", - "conduit_uri" : "https://reviews.llvm.org/" -} diff --git a/interpreter/llvm/src/bindings/README.txt b/interpreter/llvm/src/bindings/README.txt deleted file mode 100644 index 7693cb2cead04..0000000000000 --- a/interpreter/llvm/src/bindings/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains bindings for the LLVM compiler infrastructure to allow -programs written in languages other than C or C++ to take advantage of the LLVM -infrastructure--for instance, a self-hosted compiler front-end. diff --git a/interpreter/llvm/src/bindings/go/README.txt b/interpreter/llvm/src/bindings/go/README.txt deleted file mode 100644 index 75cca5a82b4fd..0000000000000 --- a/interpreter/llvm/src/bindings/go/README.txt +++ /dev/null @@ -1,61 +0,0 @@ -This directory contains LLVM bindings for the Go programming language -(http://golang.org). - -Prerequisites -------------- - -* Go 1.2+. -* CMake (to build LLVM). - -Using the bindings ------------------- - -The package path "llvm.org/llvm/bindings/go/llvm" can be used to -import the latest development version of LLVM from SVN. Paths such as -"llvm.org/llvm.v36/bindings/go/llvm" refer to released versions of LLVM. - -It is recommended to use the "-d" flag with "go get" to download the -package or a dependency, as an additional step is required to build LLVM -(see "Building LLVM" below). - -Building LLVM -------------- - -The script "build.sh" in this directory can be used to build LLVM and prepare -it to be used by the bindings. If you receive an error message from "go build" -like this: - - ./analysis.go:4:84: fatal error: llvm-c/Analysis.h: No such file or directory - #include // If you are getting an error here read bindings/go/README.txt - -or like this: - - ./llvm_dep.go:5: undefined: run_build_sh - -it means that LLVM needs to be built or updated by running the script. - - $ $GOPATH/src/llvm.org/llvm/bindings/go/build.sh - -Any command line arguments supplied to the script are passed to LLVM's CMake -build system. A good set of arguments to use during development are: - - $ $GOPATH/src/llvm.org/llvm/bindings/go/build.sh -DCMAKE_BUILD_TYPE=Debug -DLLVM_TARGETS_TO_BUILD=host -DBUILD_SHARED_LIBS=ON - -Note that CMake keeps a cache of build settings so once you have built -LLVM there is no need to pass these arguments again after updating. - -Alternatively, you can build LLVM yourself, but you must then set the -CGO_CPPFLAGS, CGO_CXXFLAGS and CGO_LDFLAGS environment variables: - - $ export CGO_CPPFLAGS="`/path/to/llvm-build/bin/llvm-config --cppflags`" - $ export CGO_CXXFLAGS=-std=c++14 - $ export CGO_LDFLAGS="`/path/to/llvm-build/bin/llvm-config --ldflags --libs --system-libs all`" - $ go build -tags byollvm - -If you see a compilation error while compiling your code with Go 1.9.4 or later as follows, - - go build llvm.org/llvm/bindings/go/llvm: invalid flag in #cgo LDFLAGS: -Wl,-headerpad_max_install_names - -you need to setup $CGO_LDFLAGS_ALLOW to allow a compiler to specify some linker options: - - $ export CGO_LDFLAGS_ALLOW='-Wl,(-search_paths_first|-headerpad_max_install_names)' diff --git a/interpreter/llvm/src/bindings/go/build.sh b/interpreter/llvm/src/bindings/go/build.sh deleted file mode 100755 index 3177852aebad6..0000000000000 --- a/interpreter/llvm/src/bindings/go/build.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/sh -xe - -gollvmdir=$(dirname "$0")/llvm - -workdir=$gollvmdir/workdir -llvmdir=$gollvmdir/../../.. -llvm_builddir=$workdir/llvm_build - -mkdir -p $llvm_builddir - -cmake_flags="../../../../.. $@" -llvm_config="$llvm_builddir/bin/llvm-config" -llvm_go="$llvm_builddir/bin/llvm-go" - -if test -n "`which ninja`" ; then - # If Ninja is available, we can speed up the build by building only the - # required subset of LLVM. - (cd $llvm_builddir && cmake -G Ninja $cmake_flags) - ninja -C $llvm_builddir llvm-config llvm-go - llvm_components="$($llvm_go print-components)" - llvm_buildtargets="$($llvm_config --libs $llvm_components | sed -e 's/-l//g')" - ninja -C $llvm_builddir $llvm_buildtargets FileCheck -else - (cd $llvm_builddir && cmake $cmake_flags) - make -C $llvm_builddir -j4 -fi - -$llvm_go print-config > $gollvmdir/llvm_config.go diff --git a/interpreter/llvm/src/bindings/go/conftest.go b/interpreter/llvm/src/bindings/go/conftest.go deleted file mode 100644 index d97fb89f7c2b6..0000000000000 --- a/interpreter/llvm/src/bindings/go/conftest.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "go/build" - "os" -) - -// Tests that the Go compiler is at least version 1.2. -func main() { - for _, tag := range build.Default.ReleaseTags { - if tag == "go1.2" { - os.Exit(0) - } - } - os.Exit(1) -} diff --git a/interpreter/llvm/src/bindings/go/llvm/IRBindings.cpp b/interpreter/llvm/src/bindings/go/llvm/IRBindings.cpp deleted file mode 100644 index 1831d33540ca2..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/IRBindings.cpp +++ /dev/null @@ -1,75 +0,0 @@ -//===- IRBindings.cpp - Additional bindings for ir ------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines additional C bindings for the ir component. -// -//===----------------------------------------------------------------------===// - -#include "IRBindings.h" -#include "llvm/IR/Attributes.h" -#include "llvm/IR/DebugLoc.h" -#include "llvm/IR/DebugInfoMetadata.h" -#include "llvm/IR/Function.h" -#include "llvm/IR/IRBuilder.h" -#include "llvm/IR/LLVMContext.h" -#include "llvm/IR/Module.h" - -using namespace llvm; - -LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef C) { - return wrap(ConstantAsMetadata::get(unwrap(C))); -} - -LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen) { - return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen))); -} - -LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs, - unsigned Count) { - return wrap( - MDNode::get(*unwrap(C), ArrayRef(unwrap(MDs), Count))); -} - -void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, - LLVMMetadataRef Val) { - NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name); - if (!N) - return; - if (!Val) - return; - N->addOperand(unwrap(Val)); -} - -void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD) { - MDNode *N = MD ? unwrap(MD) : nullptr; - unwrap(Inst)->setMetadata(KindID, N); -} - -void LLVMGoSetCurrentDebugLocation(LLVMBuilderRef Bref, unsigned Line, - unsigned Col, LLVMMetadataRef Scope, - LLVMMetadataRef InlinedAt) { - if (!Scope) - unwrap(Bref)->SetCurrentDebugLocation(DebugLoc()); - else - unwrap(Bref)->SetCurrentDebugLocation(DILocation::get( - unwrap(Scope)->getContext(), Line, Col, unwrap(Scope), - InlinedAt ? unwrap(InlinedAt) : nullptr)); -} - -LLVMDebugLocMetadata LLVMGoGetCurrentDebugLocation(LLVMBuilderRef Bref) { - const auto& Loc = unwrap(Bref)->getCurrentDebugLocation(); - const auto* InlinedAt = Loc.getInlinedAt(); - const LLVMDebugLocMetadata md{ - Loc.getLine(), - Loc.getCol(), - wrap(Loc.getScope()), - InlinedAt == nullptr ? nullptr : wrap(InlinedAt->getRawInlinedAt()), - }; - return md; -} - diff --git a/interpreter/llvm/src/bindings/go/llvm/IRBindings.h b/interpreter/llvm/src/bindings/go/llvm/IRBindings.h deleted file mode 100644 index 778b0d21bb260..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/IRBindings.h +++ /dev/null @@ -1,57 +0,0 @@ -//===- IRBindings.h - Additional bindings for IR ----------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines additional C bindings for the IR component. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BINDINGS_GO_LLVM_IRBINDINGS_H -#define LLVM_BINDINGS_GO_LLVM_IRBINDINGS_H - -#include "llvm-c/Core.h" -#include "llvm-c/DebugInfo.h" -#ifdef __cplusplus -#include "llvm/IR/Metadata.h" -#include "llvm/Support/CBindingWrapping.h" -#endif - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -struct LLVMDebugLocMetadata{ - unsigned Line; - unsigned Col; - LLVMMetadataRef Scope; - LLVMMetadataRef InlinedAt; -}; - -LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef Val); - -LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen); -LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs, - unsigned Count); - -void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, - LLVMMetadataRef Val); -void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD); - -void LLVMGoSetCurrentDebugLocation(LLVMBuilderRef Bref, unsigned Line, - unsigned Col, LLVMMetadataRef Scope, - LLVMMetadataRef InlinedAt); - -struct LLVMDebugLocMetadata LLVMGoGetCurrentDebugLocation(LLVMBuilderRef Bref); - -#ifdef __cplusplus -} - -#endif - -#endif diff --git a/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.cpp b/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.cpp deleted file mode 100644 index 71d43de254a37..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.cpp +++ /dev/null @@ -1,48 +0,0 @@ -//===- InstrumentationBindings.cpp - instrumentation bindings -------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines C bindings for the instrumentation component. -// -//===----------------------------------------------------------------------===// - -#include "InstrumentationBindings.h" -#include "llvm-c/Core.h" -#include "llvm/IR/LegacyPassManager.h" -#include "llvm/IR/Module.h" -#include "llvm/Transforms/Instrumentation.h" -#include "llvm/Transforms/Instrumentation/AddressSanitizer.h" -#include "llvm/Transforms/Instrumentation/MemorySanitizer.h" -#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" - -using namespace llvm; - -void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM) { - unwrap(PM)->add(createAddressSanitizerFunctionPass()); -} - -void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM) { - unwrap(PM)->add(createModuleAddressSanitizerLegacyPassPass()); -} - -void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM) { - unwrap(PM)->add(createThreadSanitizerLegacyPassPass()); -} - -void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM) { - unwrap(PM)->add(createMemorySanitizerLegacyPassPass()); -} - -void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM, - int ABIListFilesNum, - const char **ABIListFiles) { - std::vector ABIListFilesVec; - for (int i = 0; i != ABIListFilesNum; ++i) { - ABIListFilesVec.push_back(ABIListFiles[i]); - } - unwrap(PM)->add(createDataFlowSanitizerLegacyPassPass(ABIListFilesVec)); -} diff --git a/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.h b/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.h deleted file mode 100644 index 143086c062743..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/InstrumentationBindings.h +++ /dev/null @@ -1,37 +0,0 @@ -//===- InstrumentationBindings.h - instrumentation bindings -----*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines C bindings for the Transforms/Instrumentation component. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BINDINGS_GO_LLVM_INSTRUMENTATIONBINDINGS_H -#define LLVM_BINDINGS_GO_LLVM_INSTRUMENTATIONBINDINGS_H - -#include "llvm-c/Core.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// FIXME: These bindings shouldn't be Go-specific and should eventually move to -// a (somewhat) less stable collection of C APIs for use in creating bindings of -// LLVM in other languages. - -void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM); -void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM); -void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM); -void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM); -void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM, int ABIListFilesNum, - const char **ABIListFiles); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/interpreter/llvm/src/bindings/go/llvm/SupportBindings.cpp b/interpreter/llvm/src/bindings/go/llvm/SupportBindings.cpp deleted file mode 100644 index aac69a7c788d1..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/SupportBindings.cpp +++ /dev/null @@ -1,25 +0,0 @@ -//===- SupportBindings.cpp - Additional bindings for support --------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines additional C bindings for the support component. -// -//===----------------------------------------------------------------------===// - -#include "SupportBindings.h" -#include "llvm/Support/DynamicLibrary.h" -#include -#include - -void LLVMLoadLibraryPermanently2(const char *Filename, char **ErrMsg) { - std::string ErrMsgStr; - if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Filename, &ErrMsgStr)) { - *ErrMsg = static_cast(malloc(ErrMsgStr.size() + 1)); - memcpy(static_cast(*ErrMsg), - static_cast(ErrMsgStr.c_str()), ErrMsgStr.size() + 1); - } -} diff --git a/interpreter/llvm/src/bindings/go/llvm/SupportBindings.h b/interpreter/llvm/src/bindings/go/llvm/SupportBindings.h deleted file mode 100644 index db83e91ee5ab3..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/SupportBindings.h +++ /dev/null @@ -1,29 +0,0 @@ -//===- SupportBindings.h - Additional bindings for Support ------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines additional C bindings for the Support component. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BINDINGS_GO_LLVM_SUPPORTBINDINGS_H -#define LLVM_BINDINGS_GO_LLVM_SUPPORTBINDINGS_H - -#ifdef __cplusplus -extern "C" { -#endif - -// This function duplicates the LLVMLoadLibraryPermanently function in the -// stable C API and adds an extra ErrMsg parameter to retrieve the error -// message. -void LLVMLoadLibraryPermanently2(const char *Filename, char **ErrMsg); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/interpreter/llvm/src/bindings/go/llvm/analysis.go b/interpreter/llvm/src/bindings/go/llvm/analysis.go deleted file mode 100644 index 3a1c9d34b4dc3..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/analysis.go +++ /dev/null @@ -1,68 +0,0 @@ -//===- analysis.go - Bindings for analysis --------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the analysis component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Analysis.h" // If you are getting an error here read bindings/go/README.txt -#include "llvm-c/Core.h" -#include -*/ -import "C" -import "errors" - -type VerifierFailureAction C.LLVMVerifierFailureAction - -const ( - // verifier will print to stderr and abort() - AbortProcessAction VerifierFailureAction = C.LLVMAbortProcessAction - // verifier will print to stderr and return 1 - PrintMessageAction VerifierFailureAction = C.LLVMPrintMessageAction - // verifier will just return 1 - ReturnStatusAction VerifierFailureAction = C.LLVMReturnStatusAction -) - -// Verifies that a module is valid, taking the specified action if not. -// Optionally returns a human-readable description of any invalid constructs. -func VerifyModule(m Module, a VerifierFailureAction) error { - var cmsg *C.char - broken := C.LLVMVerifyModule(m.C, C.LLVMVerifierFailureAction(a), &cmsg) - - // C++'s verifyModule means isModuleBroken, so it returns false if - // there are no errors - if broken != 0 { - err := errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - return err - } - return nil -} - -var verifyFunctionError = errors.New("Function is broken") - -// Verifies that a single function is valid, taking the specified action. -// Useful for debugging. -func VerifyFunction(f Value, a VerifierFailureAction) error { - broken := C.LLVMVerifyFunction(f.C, C.LLVMVerifierFailureAction(a)) - - // C++'s verifyFunction means isFunctionBroken, so it returns false if - // there are no errors - if broken != 0 { - return verifyFunctionError - } - return nil -} - -// Open up a ghostview window that displays the CFG of the current function. -// Useful for debugging. -func ViewFunctionCFG(f Value) { C.LLVMViewFunctionCFG(f.C) } -func ViewFunctionCFGOnly(f Value) { C.LLVMViewFunctionCFGOnly(f.C) } diff --git a/interpreter/llvm/src/bindings/go/llvm/bitreader.go b/interpreter/llvm/src/bindings/go/llvm/bitreader.go deleted file mode 100644 index 1954916e717da..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/bitreader.go +++ /dev/null @@ -1,50 +0,0 @@ -//===- bitreader.go - Bindings for bitreader ------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the bitreader component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/BitReader.h" -#include "llvm-c/Core.h" -#include -*/ -import "C" - -import ( - "errors" - "unsafe" -) - -// ParseBitcodeFile parses the LLVM IR (bitcode) in the file with the -// specified name, and returns a new LLVM module. -func ParseBitcodeFile(name string) (Module, error) { - var buf C.LLVMMemoryBufferRef - var errmsg *C.char - var cfilename *C.char = C.CString(name) - defer C.free(unsafe.Pointer(cfilename)) - result := C.LLVMCreateMemoryBufferWithContentsOfFile(cfilename, &buf, &errmsg) - if result != 0 { - err := errors.New(C.GoString(errmsg)) - C.free(unsafe.Pointer(errmsg)) - return Module{}, err - } - defer C.LLVMDisposeMemoryBuffer(buf) - - var m Module - if C.LLVMParseBitcode2(buf, &m.C) == 0 { - return m, nil - } - - err := errors.New(C.GoString(errmsg)) - C.free(unsafe.Pointer(errmsg)) - return Module{}, err -} diff --git a/interpreter/llvm/src/bindings/go/llvm/bitwriter.go b/interpreter/llvm/src/bindings/go/llvm/bitwriter.go deleted file mode 100644 index 83780fc69713e..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/bitwriter.go +++ /dev/null @@ -1,38 +0,0 @@ -//===- bitwriter.go - Bindings for bitwriter ------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the bitwriter component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/BitWriter.h" -#include -*/ -import "C" -import "os" -import "errors" - -var writeBitcodeToFileErr = errors.New("Failed to write bitcode to file") - -func WriteBitcodeToFile(m Module, file *os.File) error { - fail := C.LLVMWriteBitcodeToFD(m.C, C.int(file.Fd()), C.int(0), C.int(0)) - if fail != 0 { - return writeBitcodeToFileErr - } - return nil -} - -func WriteBitcodeToMemoryBuffer(m Module) MemoryBuffer { - mb := C.LLVMWriteBitcodeToMemoryBuffer(m.C) - return MemoryBuffer{mb} -} - -// TODO(nsf): Figure out way how to make it work with io.Writer diff --git a/interpreter/llvm/src/bindings/go/llvm/dibuilder.go b/interpreter/llvm/src/bindings/go/llvm/dibuilder.go deleted file mode 100644 index aeaf49e539b37..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/dibuilder.go +++ /dev/null @@ -1,711 +0,0 @@ -//===- dibuilder.go - Bindings for DIBuilder ------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the DIBuilder class. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "IRBindings.h" -#include -*/ -import "C" - -import ( - "debug/dwarf" - "unsafe" -) - -type DwarfTag uint32 - -const ( - DW_TAG_lexical_block DwarfTag = 0x0b - DW_TAG_compile_unit DwarfTag = 0x11 - DW_TAG_variable DwarfTag = 0x34 - DW_TAG_base_type DwarfTag = 0x24 - DW_TAG_pointer_type DwarfTag = 0x0F - DW_TAG_structure_type DwarfTag = 0x13 - DW_TAG_subroutine_type DwarfTag = 0x15 - DW_TAG_file_type DwarfTag = 0x29 - DW_TAG_subprogram DwarfTag = 0x2E - DW_TAG_auto_variable DwarfTag = 0x100 - DW_TAG_arg_variable DwarfTag = 0x101 -) - -const ( - FlagPrivate = 1 << iota - FlagProtected - FlagFwdDecl - FlagAppleBlock - FlagReserved - FlagVirtual - FlagArtificial - FlagExplicit - FlagPrototyped - FlagObjcClassComplete - FlagObjectPointer - FlagVector - FlagStaticMember - FlagIndirectVariable -) - -type DwarfLang uint32 - -const ( - // http://dwarfstd.org/ShowIssue.php?issue=101014.1&type=open - DW_LANG_Go DwarfLang = 0x0016 -) - -type DwarfTypeEncoding uint32 - -const ( - DW_ATE_address DwarfTypeEncoding = 0x01 - DW_ATE_boolean DwarfTypeEncoding = 0x02 - DW_ATE_complex_float DwarfTypeEncoding = 0x03 - DW_ATE_float DwarfTypeEncoding = 0x04 - DW_ATE_signed DwarfTypeEncoding = 0x05 - DW_ATE_signed_char DwarfTypeEncoding = 0x06 - DW_ATE_unsigned DwarfTypeEncoding = 0x07 - DW_ATE_unsigned_char DwarfTypeEncoding = 0x08 - DW_ATE_imaginary_float DwarfTypeEncoding = 0x09 - DW_ATE_packed_decimal DwarfTypeEncoding = 0x0a - DW_ATE_numeric_string DwarfTypeEncoding = 0x0b - DW_ATE_edited DwarfTypeEncoding = 0x0c - DW_ATE_signed_fixed DwarfTypeEncoding = 0x0d - DW_ATE_unsigned_fixed DwarfTypeEncoding = 0x0e - DW_ATE_decimal_float DwarfTypeEncoding = 0x0f - DW_ATE_UTF DwarfTypeEncoding = 0x10 - DW_ATE_lo_user DwarfTypeEncoding = 0x80 - DW_ATE_hi_user DwarfTypeEncoding = 0xff -) - -// DIBuilder is a wrapper for the LLVM DIBuilder class. -type DIBuilder struct { - ref C.LLVMDIBuilderRef - m Module -} - -// NewDIBuilder creates a new DIBuilder, associated with the given module. -func NewDIBuilder(m Module) *DIBuilder { - d := C.LLVMCreateDIBuilder(m.C) - return &DIBuilder{ref: d, m: m} -} - -// Destroy destroys the DIBuilder. -func (d *DIBuilder) Destroy() { - C.LLVMDisposeDIBuilder(d.ref) -} - -// FInalize finalizes the debug information generated by the DIBuilder. -func (d *DIBuilder) Finalize() { - C.LLVMDIBuilderFinalize(d.ref) -} - -// DICompileUnit holds the values for creating compile unit debug metadata. -type DICompileUnit struct { - Language DwarfLang - File string - Dir string - Producer string - Optimized bool - Flags string - RuntimeVersion int - SysRoot string - SDK string -} - -// CreateCompileUnit creates compile unit debug metadata. -func (d *DIBuilder) CreateCompileUnit(cu DICompileUnit) Metadata { - file := C.CString(cu.File) - defer C.free(unsafe.Pointer(file)) - dir := C.CString(cu.Dir) - defer C.free(unsafe.Pointer(dir)) - producer := C.CString(cu.Producer) - defer C.free(unsafe.Pointer(producer)) - flags := C.CString(cu.Flags) - defer C.free(unsafe.Pointer(flags)) - sysroot := C.CString(cu.SysRoot) - defer C.free(unsafe.Pointer(sysroot)) - sdk := C.CString(cu.SDK) - defer C.free(unsafe.Pointer(sdk)) - result := C.LLVMDIBuilderCreateCompileUnit( - d.ref, - C.LLVMDWARFSourceLanguage(cu.Language), - C.LLVMDIBuilderCreateFile(d.ref, file, C.size_t(len(cu.File)), dir, C.size_t(len(cu.Dir))), - producer, C.size_t(len(cu.Producer)), - C.LLVMBool(boolToCInt(cu.Optimized)), - flags, C.size_t(len(cu.Flags)), - C.unsigned(cu.RuntimeVersion), - /*SplitName=*/ nil, 0, - C.LLVMDWARFEmissionFull, - /*DWOId=*/ 0, - /*SplitDebugInlining*/ C.LLVMBool(boolToCInt(true)), - /*DebugInfoForProfiling*/ C.LLVMBool(boolToCInt(false)), - sysroot, C.size_t(len(cu.SysRoot)), - sdk, C.size_t(len(cu.SDK)), - ) - return Metadata{C: result} -} - -// CreateFile creates file debug metadata. -func (d *DIBuilder) CreateFile(filename, dir string) Metadata { - cfilename := C.CString(filename) - defer C.free(unsafe.Pointer(cfilename)) - cdir := C.CString(dir) - defer C.free(unsafe.Pointer(cdir)) - result := C.LLVMDIBuilderCreateFile(d.ref, - cfilename, C.size_t(len(filename)), - cdir, C.size_t(len(dir))) - return Metadata{C: result} -} - -// DILexicalBlock holds the values for creating lexical block debug metadata. -type DILexicalBlock struct { - File Metadata - Line int - Column int -} - -// CreateLexicalBlock creates lexical block debug metadata. -func (d *DIBuilder) CreateLexicalBlock(diScope Metadata, b DILexicalBlock) Metadata { - result := C.LLVMDIBuilderCreateLexicalBlock( - d.ref, - diScope.C, - b.File.C, - C.unsigned(b.Line), - C.unsigned(b.Column), - ) - return Metadata{C: result} -} - -func (d *DIBuilder) CreateLexicalBlockFile(diScope Metadata, diFile Metadata, discriminator int) Metadata { - result := C.LLVMDIBuilderCreateLexicalBlockFile(d.ref, diScope.C, diFile.C, - C.unsigned(discriminator)) - return Metadata{C: result} -} - -// DIFunction holds the values for creating function debug metadata. -type DIFunction struct { - Name string - LinkageName string - File Metadata - Line int - Type Metadata - LocalToUnit bool - IsDefinition bool - ScopeLine int - Flags int - Optimized bool -} - -// CreateFunction creates function debug metadata. -func (d *DIBuilder) CreateFunction(diScope Metadata, f DIFunction) Metadata { - name := C.CString(f.Name) - defer C.free(unsafe.Pointer(name)) - linkageName := C.CString(f.LinkageName) - defer C.free(unsafe.Pointer(linkageName)) - result := C.LLVMDIBuilderCreateFunction( - d.ref, - diScope.C, - name, C.size_t(len(f.Name)), - linkageName, C.size_t(len(f.LinkageName)), - f.File.C, - C.unsigned(f.Line), - f.Type.C, - C.LLVMBool(boolToCInt(f.LocalToUnit)), - C.LLVMBool(boolToCInt(f.IsDefinition)), - C.unsigned(f.ScopeLine), - C.LLVMDIFlags(f.Flags), - C.LLVMBool(boolToCInt(f.Optimized)), - ) - return Metadata{C: result} -} - -// DIAutoVariable holds the values for creating auto variable debug metadata. -type DIAutoVariable struct { - Name string - File Metadata - Line int - Type Metadata - AlwaysPreserve bool - Flags int - AlignInBits uint32 -} - -// CreateAutoVariable creates local variable debug metadata. -func (d *DIBuilder) CreateAutoVariable(scope Metadata, v DIAutoVariable) Metadata { - name := C.CString(v.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreateAutoVariable( - d.ref, - scope.C, - name, C.size_t(len(v.Name)), - v.File.C, - C.unsigned(v.Line), - v.Type.C, - C.LLVMBool(boolToCInt(v.AlwaysPreserve)), - C.LLVMDIFlags(v.Flags), - C.uint32_t(v.AlignInBits), - ) - return Metadata{C: result} -} - -// DIParameterVariable holds the values for creating parameter variable debug metadata. -type DIParameterVariable struct { - Name string - File Metadata - Line int - Type Metadata - AlwaysPreserve bool - Flags int - - // ArgNo is the 1-based index of the argument in the function's - // parameter list. - ArgNo int -} - -// CreateParameterVariable creates parameter variable debug metadata. -func (d *DIBuilder) CreateParameterVariable(scope Metadata, v DIParameterVariable) Metadata { - name := C.CString(v.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreateParameterVariable( - d.ref, - scope.C, - name, C.size_t(len(v.Name)), - C.unsigned(v.ArgNo), - v.File.C, - C.unsigned(v.Line), - v.Type.C, - C.LLVMBool(boolToCInt(v.AlwaysPreserve)), - C.LLVMDIFlags(v.Flags), - ) - return Metadata{C: result} -} - -// DIBasicType holds the values for creating basic type debug metadata. -type DIBasicType struct { - Name string - SizeInBits uint64 - Encoding DwarfTypeEncoding -} - -// CreateBasicType creates basic type debug metadata. -func (d *DIBuilder) CreateBasicType(t DIBasicType) Metadata { - name := C.CString(t.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreateBasicType( - d.ref, - name, - C.size_t(len(t.Name)), - C.uint64_t(t.SizeInBits), - C.LLVMDWARFTypeEncoding(t.Encoding), - C.LLVMDIFlags(0), - ) - return Metadata{C: result} -} - -// DIPointerType holds the values for creating pointer type debug metadata. -type DIPointerType struct { - Pointee Metadata - SizeInBits uint64 - AlignInBits uint32 // optional - AddressSpace uint32 - Name string // optional -} - -// CreatePointerType creates a type that represents a pointer to another type. -func (d *DIBuilder) CreatePointerType(t DIPointerType) Metadata { - name := C.CString(t.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreatePointerType( - d.ref, - t.Pointee.C, - C.uint64_t(t.SizeInBits), - C.uint32_t(t.AlignInBits), - C.unsigned(t.AddressSpace), - name, - C.size_t(len(t.Name)), - ) - return Metadata{C: result} -} - -// DISubroutineType holds the values for creating subroutine type debug metadata. -type DISubroutineType struct { - // File is the file in which the subroutine type is defined. - File Metadata - - // Parameters contains the subroutine parameter types, - // including the return type at the 0th index. - Parameters []Metadata - - Flags int -} - -// CreateSubroutineType creates subroutine type debug metadata. -func (d *DIBuilder) CreateSubroutineType(t DISubroutineType) Metadata { - params, length := llvmMetadataRefs(t.Parameters) - result := C.LLVMDIBuilderCreateSubroutineType( - d.ref, - t.File.C, - params, - length, - C.LLVMDIFlags(t.Flags), - ) - return Metadata{C: result} -} - -// DIStructType holds the values for creating struct type debug metadata. -type DIStructType struct { - Name string - File Metadata - Line int - SizeInBits uint64 - AlignInBits uint32 - Flags int - DerivedFrom Metadata - Elements []Metadata - VTableHolder Metadata // optional - UniqueID string -} - -// CreateStructType creates struct type debug metadata. -func (d *DIBuilder) CreateStructType(scope Metadata, t DIStructType) Metadata { - elements, length := llvmMetadataRefs(t.Elements) - name := C.CString(t.Name) - uniqueID := C.CString(t.UniqueID) - defer C.free(unsafe.Pointer(name)) - defer C.free(unsafe.Pointer(uniqueID)) - result := C.LLVMDIBuilderCreateStructType( - d.ref, - scope.C, - name, - C.size_t(len(t.Name)), - t.File.C, - C.unsigned(t.Line), - C.uint64_t(t.SizeInBits), - C.uint32_t(t.AlignInBits), - C.LLVMDIFlags(t.Flags), - t.DerivedFrom.C, - elements, - length, - C.unsigned(0), // Optional Objective-C runtime version. - t.VTableHolder.C, - uniqueID, - C.size_t(len(t.UniqueID)), - ) - return Metadata{C: result} -} - -// DIReplaceableCompositeType holds the values for creating replaceable -// composite type debug metadata. -type DIReplaceableCompositeType struct { - Tag dwarf.Tag - Name string - File Metadata - Line int - RuntimeLang int - SizeInBits uint64 - AlignInBits uint32 - Flags int - UniqueID string -} - -// CreateReplaceableCompositeType creates replaceable composite type debug metadata. -func (d *DIBuilder) CreateReplaceableCompositeType(scope Metadata, t DIReplaceableCompositeType) Metadata { - name := C.CString(t.Name) - uniqueID := C.CString(t.UniqueID) - defer C.free(unsafe.Pointer(name)) - defer C.free(unsafe.Pointer(uniqueID)) - result := C.LLVMDIBuilderCreateReplaceableCompositeType( - d.ref, - C.unsigned(t.Tag), - name, - C.size_t(len(t.Name)), - scope.C, - t.File.C, - C.unsigned(t.Line), - C.unsigned(t.RuntimeLang), - C.uint64_t(t.SizeInBits), - C.uint32_t(t.AlignInBits), - C.LLVMDIFlags(t.Flags), - uniqueID, - C.size_t(len(t.UniqueID)), - ) - return Metadata{C: result} -} - -// DIMemberType holds the values for creating member type debug metadata. -type DIMemberType struct { - Name string - File Metadata - Line int - SizeInBits uint64 - AlignInBits uint32 - OffsetInBits uint64 - Flags int - Type Metadata -} - -// CreateMemberType creates struct type debug metadata. -func (d *DIBuilder) CreateMemberType(scope Metadata, t DIMemberType) Metadata { - name := C.CString(t.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreateMemberType( - d.ref, - scope.C, - name, - C.size_t(len(t.Name)), - t.File.C, - C.unsigned(t.Line), - C.uint64_t(t.SizeInBits), - C.uint32_t(t.AlignInBits), - C.uint64_t(t.OffsetInBits), - C.LLVMDIFlags(t.Flags), - t.Type.C, - ) - return Metadata{C: result} -} - -// DISubrange describes an integer value range. -type DISubrange struct { - Lo int64 - Count int64 -} - -// DIArrayType holds the values for creating array type debug metadata. -type DIArrayType struct { - SizeInBits uint64 - AlignInBits uint32 - ElementType Metadata - Subscripts []DISubrange -} - -// CreateArrayType creates struct type debug metadata. -func (d *DIBuilder) CreateArrayType(t DIArrayType) Metadata { - subscriptsSlice := make([]Metadata, len(t.Subscripts)) - for i, s := range t.Subscripts { - subscriptsSlice[i] = d.getOrCreateSubrange(s.Lo, s.Count) - } - subscripts, length := llvmMetadataRefs(subscriptsSlice) - result := C.LLVMDIBuilderCreateArrayType( - d.ref, - C.uint64_t(t.SizeInBits), - C.uint32_t(t.AlignInBits), - t.ElementType.C, - subscripts, - length, - ) - return Metadata{C: result} -} - -// DITypedef holds the values for creating typedef type debug metadata. -type DITypedef struct { - Type Metadata - Name string - File Metadata - Line int - Context Metadata - AlignInBits uint32 -} - -// CreateTypedef creates typedef type debug metadata. -func (d *DIBuilder) CreateTypedef(t DITypedef) Metadata { - name := C.CString(t.Name) - defer C.free(unsafe.Pointer(name)) - result := C.LLVMDIBuilderCreateTypedef( - d.ref, - t.Type.C, - name, - C.size_t(len(t.Name)), - t.File.C, - C.unsigned(t.Line), - t.Context.C, - C.uint32_t(t.AlignInBits), - ) - return Metadata{C: result} -} - -// getOrCreateSubrange gets a metadata node for the specified subrange, -// creating if required. -func (d *DIBuilder) getOrCreateSubrange(lo, count int64) Metadata { - result := C.LLVMDIBuilderGetOrCreateSubrange(d.ref, C.int64_t(lo), C.int64_t(count)) - return Metadata{C: result} -} - -// getOrCreateArray gets a metadata node containing the specified values, -// creating if required. -func (d *DIBuilder) getOrCreateArray(values []Metadata) Metadata { - if len(values) == 0 { - return Metadata{} - } - data, length := llvmMetadataRefs(values) - result := C.LLVMDIBuilderGetOrCreateArray(d.ref, data, C.size_t(length)) - return Metadata{C: result} -} - -// getOrCreateTypeArray gets a metadata node for a type array containing the -// specified values, creating if required. -func (d *DIBuilder) getOrCreateTypeArray(values []Metadata) Metadata { - if len(values) == 0 { - return Metadata{} - } - data, length := llvmMetadataRefs(values) - result := C.LLVMDIBuilderGetOrCreateTypeArray(d.ref, data, C.size_t(length)) - return Metadata{C: result} -} - -// CreateExpression creates a new descriptor for the specified -// variable which has a complex address expression for its address. -func (d *DIBuilder) CreateExpression(addr []int64) Metadata { - var data *C.int64_t - if len(addr) > 0 { - data = (*C.int64_t)(unsafe.Pointer(&addr[0])) - } - result := C.LLVMDIBuilderCreateExpression(d.ref, data, C.size_t(len(addr))) - return Metadata{C: result} -} - -// InsertDeclareAtEnd inserts a call to llvm.dbg.declare at the end of the -// specified basic block for the given value and associated debug metadata. -func (d *DIBuilder) InsertDeclareAtEnd(v Value, diVarInfo, expr Metadata, l DebugLoc, bb BasicBlock) Value { - loc := C.LLVMDIBuilderCreateDebugLocation( - d.m.Context().C, C.uint(l.Line), C.uint(l.Col), l.Scope.C, l.InlinedAt.C) - result := C.LLVMDIBuilderInsertDeclareAtEnd(d.ref, v.C, diVarInfo.C, expr.C, loc, bb.C) - return Value{C: result} -} - -// InsertValueAtEnd inserts a call to llvm.dbg.value at the end of the -// specified basic block for the given value and associated debug metadata. -func (d *DIBuilder) InsertValueAtEnd(v Value, diVarInfo, expr Metadata, l DebugLoc, bb BasicBlock) Value { - loc := C.LLVMDIBuilderCreateDebugLocation( - d.m.Context().C, C.uint(l.Line), C.uint(l.Col), l.Scope.C, l.InlinedAt.C) - result := C.LLVMDIBuilderInsertDbgValueAtEnd(d.ref, v.C, diVarInfo.C, expr.C, loc, bb.C) - return Value{C: result} -} - -func (v Value) SetSubprogram(sp Metadata) { - C.LLVMSetSubprogram(v.C, sp.C) -} - -func (v Value) Subprogram() (md Metadata) { - md.C = C.LLVMGetSubprogram(v.C) - return -} - -func boolToCInt(v bool) C.int { - if v { - return 1 - } - return 0 -} - -//------------------------------------------------------------------------- -// llvm.Metadata -//------------------------------------------------------------------------- - -func (c Context) TemporaryMDNode(mds []Metadata) (md Metadata) { - ptr, nvals := llvmMetadataRefs(mds) - md.C = C.LLVMTemporaryMDNode(c.C, ptr, C.size_t(nvals)) - return -} - -func (md Metadata) ReplaceAllUsesWith(new Metadata) { - C.LLVMMetadataReplaceAllUsesWith(md.C, new.C) -} - -type MetadataKind C.LLVMMetadataKind - -const ( - MDStringMetadataKind = C.LLVMMDStringMetadataKind - ConstantAsMetadataMetadataKind = C.LLVMConstantAsMetadataMetadataKind - LocalAsMetadataMetadataKind = C.LLVMLocalAsMetadataMetadataKind - DistinctMDOperandPlaceholderMetadataKind = C.LLVMDistinctMDOperandPlaceholderMetadataKind - MDTupleMetadataKind = C.LLVMMDTupleMetadataKind - DILocationMetadataKind = C.LLVMDILocationMetadataKind - DIExpressionMetadataKind = C.LLVMDIExpressionMetadataKind - DIGlobalVariableExpressionMetadataKind = C.LLVMDIGlobalVariableExpressionMetadataKind - GenericDINodeMetadataKind = C.LLVMGenericDINodeMetadataKind - DISubrangeMetadataKind = C.LLVMDISubrangeMetadataKind - DIEnumeratorMetadataKind = C.LLVMDIEnumeratorMetadataKind - DIBasicTypeMetadataKind = C.LLVMDIBasicTypeMetadataKind - DIDerivedTypeMetadataKind = C.LLVMDIDerivedTypeMetadataKind - DICompositeTypeMetadataKind = C.LLVMDICompositeTypeMetadataKind - DISubroutineTypeMetadataKind = C.LLVMDISubroutineTypeMetadataKind - DIFileMetadataKind = C.LLVMDIFileMetadataKind - DICompileUnitMetadataKind = C.LLVMDICompileUnitMetadataKind - DISubprogramMetadataKind = C.LLVMDISubprogramMetadataKind - DILexicalBlockMetadataKind = C.LLVMDILexicalBlockMetadataKind - DILexicalBlockFileMetadataKind = C.LLVMDILexicalBlockFileMetadataKind - DINamespaceMetadataKind = C.LLVMDINamespaceMetadataKind - DIModuleMetadataKind = C.LLVMDIModuleMetadataKind - DITemplateTypeParameterMetadataKind = C.LLVMDITemplateTypeParameterMetadataKind - DITemplateValueParameterMetadataKind = C.LLVMDITemplateValueParameterMetadataKind - DIGlobalVariableMetadataKind = C.LLVMDIGlobalVariableMetadataKind - DILocalVariableMetadataKind = C.LLVMDILocalVariableMetadataKind - DILabelMetadataKind = C.LLVMDILabelMetadataKind - DIObjCPropertyMetadataKind = C.LLVMDIObjCPropertyMetadataKind - DIImportedEntityMetadataKind = C.LLVMDIImportedEntityMetadataKind - DIMacroMetadataKind = C.LLVMDIMacroMetadataKind - DIMacroFileMetadataKind = C.LLVMDIMacroFileMetadataKind - DICommonBlockMetadataKind = C.LLVMDICommonBlockMetadataKind -) - -// Kind returns the metadata kind. -func (md Metadata) Kind() MetadataKind { - return MetadataKind(C.LLVMGetMetadataKind(md.C)) -} - -// FileDirectory returns the directory of a DIFile metadata node. -func (md Metadata) FileDirectory() string { - var length C.unsigned - ptr := C.LLVMDIFileGetDirectory(md.C, &length) - return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length]) -} - -// FileFilename returns the filename of a DIFile metadata node. -func (md Metadata) FileFilename() string { - var length C.unsigned - ptr := C.LLVMDIFileGetFilename(md.C, &length) - return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length]) -} - -// FileSource returns the source of a DIFile metadata node. -func (md Metadata) FileSource() string { - var length C.unsigned - ptr := C.LLVMDIFileGetSource(md.C, &length) - return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length]) -} - -// LocationLine returns the line number of a DILocation. -func (md Metadata) LocationLine() uint { - return uint(C.LLVMDILocationGetLine(md.C)) -} - -// LocationColumn returns the column (offset from the start of the line) of a -// DILocation. -func (md Metadata) LocationColumn() uint { - return uint(C.LLVMDILocationGetColumn(md.C)) -} - -// LocationScope returns the local scope associated with this debug location. -func (md Metadata) LocationScope() Metadata { - return Metadata{C.LLVMDILocationGetScope(md.C)} -} - -// LocationInlinedAt return the "inline at" location associated with this debug -// location. -func (md Metadata) LocationInlinedAt() Metadata { - return Metadata{C.LLVMDILocationGetInlinedAt(md.C)} -} - -// ScopeFile returns the file (DIFile) of a given scope. -func (md Metadata) ScopeFile() Metadata { - return Metadata{C.LLVMDIScopeGetFile(md.C)} -} diff --git a/interpreter/llvm/src/bindings/go/llvm/executionengine.go b/interpreter/llvm/src/bindings/go/llvm/executionengine.go deleted file mode 100644 index 5fa82047c1798..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/executionengine.go +++ /dev/null @@ -1,177 +0,0 @@ -//===- executionengine.go - Bindings for executionengine ------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the executionengine component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Core.h" -#include "llvm-c/ExecutionEngine.h" -#include -*/ -import "C" -import "unsafe" -import "errors" - -func LinkInMCJIT() { C.LLVMLinkInMCJIT() } -func LinkInInterpreter() { C.LLVMLinkInInterpreter() } - -type GenericValue struct { - C C.LLVMGenericValueRef -} -type ExecutionEngine struct { - C C.LLVMExecutionEngineRef -} - -type MCJITCompilerOptions struct { - C C.struct_LLVMMCJITCompilerOptions -} - -func (options *MCJITCompilerOptions) SetMCJITOptimizationLevel(level uint) { - options.C.OptLevel = C.uint(level) -} - -func (options *MCJITCompilerOptions) SetMCJITNoFramePointerElim(nfp bool) { - options.C.NoFramePointerElim = boolToLLVMBool(nfp) -} - -func (options *MCJITCompilerOptions) SetMCJITEnableFastISel(fastisel bool) { - options.C.EnableFastISel = boolToLLVMBool(fastisel) -} - -func (options *MCJITCompilerOptions) SetMCJITCodeModel(CodeModel CodeModel) { - options.C.CodeModel = C.LLVMCodeModel(CodeModel) -} - -// helpers -func llvmGenericValueRefPtr(t *GenericValue) *C.LLVMGenericValueRef { - return (*C.LLVMGenericValueRef)(unsafe.Pointer(t)) -} - -//------------------------------------------------------------------------- -// llvm.GenericValue -//------------------------------------------------------------------------- - -func NewGenericValueFromInt(t Type, n uint64, signed bool) (g GenericValue) { - g.C = C.LLVMCreateGenericValueOfInt(t.C, C.ulonglong(n), boolToLLVMBool(signed)) - return -} -func NewGenericValueFromPointer(p unsafe.Pointer) (g GenericValue) { - g.C = C.LLVMCreateGenericValueOfPointer(p) - return -} -func NewGenericValueFromFloat(t Type, n float64) (g GenericValue) { - g.C = C.LLVMCreateGenericValueOfFloat(t.C, C.double(n)) - return -} -func (g GenericValue) IntWidth() int { return int(C.LLVMGenericValueIntWidth(g.C)) } -func (g GenericValue) Int(signed bool) uint64 { - return uint64(C.LLVMGenericValueToInt(g.C, boolToLLVMBool(signed))) -} -func (g GenericValue) Float(t Type) float64 { - return float64(C.LLVMGenericValueToFloat(t.C, g.C)) -} -func (g GenericValue) Pointer() unsafe.Pointer { - return C.LLVMGenericValueToPointer(g.C) -} -func (g GenericValue) Dispose() { C.LLVMDisposeGenericValue(g.C) } - -//------------------------------------------------------------------------- -// llvm.ExecutionEngine -//------------------------------------------------------------------------- - -func NewExecutionEngine(m Module) (ee ExecutionEngine, err error) { - var cmsg *C.char - fail := C.LLVMCreateExecutionEngineForModule(&ee.C, m.C, &cmsg) - if fail != 0 { - ee.C = nil - err = errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - } - return -} - -func NewInterpreter(m Module) (ee ExecutionEngine, err error) { - var cmsg *C.char - fail := C.LLVMCreateInterpreterForModule(&ee.C, m.C, &cmsg) - if fail != 0 { - ee.C = nil - err = errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - } - return -} - -func NewMCJITCompilerOptions() MCJITCompilerOptions { - var options C.struct_LLVMMCJITCompilerOptions - C.LLVMInitializeMCJITCompilerOptions(&options, C.size_t(unsafe.Sizeof(C.struct_LLVMMCJITCompilerOptions{}))) - return MCJITCompilerOptions{options} -} - -func NewMCJITCompiler(m Module, options MCJITCompilerOptions) (ee ExecutionEngine, err error) { - var cmsg *C.char - fail := C.LLVMCreateMCJITCompilerForModule(&ee.C, m.C, &options.C, C.size_t(unsafe.Sizeof(C.struct_LLVMMCJITCompilerOptions{})), &cmsg) - if fail != 0 { - ee.C = nil - err = errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - } - return -} - -func (ee ExecutionEngine) Dispose() { C.LLVMDisposeExecutionEngine(ee.C) } -func (ee ExecutionEngine) RunStaticConstructors() { C.LLVMRunStaticConstructors(ee.C) } -func (ee ExecutionEngine) RunStaticDestructors() { C.LLVMRunStaticDestructors(ee.C) } - -func (ee ExecutionEngine) RunFunction(f Value, args []GenericValue) (g GenericValue) { - nargs := len(args) - var argptr *GenericValue - if nargs > 0 { - argptr = &args[0] - } - g.C = C.LLVMRunFunction(ee.C, f.C, - C.unsigned(nargs), llvmGenericValueRefPtr(argptr)) - return -} - -func (ee ExecutionEngine) FreeMachineCodeForFunction(f Value) { - C.LLVMFreeMachineCodeForFunction(ee.C, f.C) -} -func (ee ExecutionEngine) AddModule(m Module) { C.LLVMAddModule(ee.C, m.C) } - -func (ee ExecutionEngine) RemoveModule(m Module) { - var modtmp C.LLVMModuleRef - C.LLVMRemoveModule(ee.C, m.C, &modtmp, nil) -} - -func (ee ExecutionEngine) FindFunction(name string) (f Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.LLVMFindFunction(ee.C, cname, &f.C) - return -} - -func (ee ExecutionEngine) RecompileAndRelinkFunction(f Value) unsafe.Pointer { - return C.LLVMRecompileAndRelinkFunction(ee.C, f.C) -} - -func (ee ExecutionEngine) TargetData() (td TargetData) { - td.C = C.LLVMGetExecutionEngineTargetData(ee.C) - return -} - -func (ee ExecutionEngine) AddGlobalMapping(global Value, addr unsafe.Pointer) { - C.LLVMAddGlobalMapping(ee.C, global.C, addr) -} - -func (ee ExecutionEngine) PointerToGlobal(global Value) unsafe.Pointer { - return C.LLVMGetPointerToGlobal(ee.C, global.C) -} diff --git a/interpreter/llvm/src/bindings/go/llvm/executionengine_test.go b/interpreter/llvm/src/bindings/go/llvm/executionengine_test.go deleted file mode 100644 index 2369826db9147..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/executionengine_test.go +++ /dev/null @@ -1,95 +0,0 @@ -//===- executionengine_test.go - Tests for executionengine ----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file tests bindings for the executionengine component. -// -//===----------------------------------------------------------------------===// - -package llvm - -import ( - "testing" -) - -func TestFactorial(t *testing.T) { - LinkInMCJIT() - InitializeNativeTarget() - InitializeNativeAsmPrinter() - - mod := NewModule("fac_module") - - fac_args := []Type{Int32Type()} - fac_type := FunctionType(Int32Type(), fac_args, false) - fac := AddFunction(mod, "fac", fac_type) - fac.SetFunctionCallConv(CCallConv) - n := fac.Param(0) - - entry := AddBasicBlock(fac, "entry") - iftrue := AddBasicBlock(fac, "iftrue") - iffalse := AddBasicBlock(fac, "iffalse") - end := AddBasicBlock(fac, "end") - - builder := NewBuilder() - defer builder.Dispose() - - builder.SetInsertPointAtEnd(entry) - If := builder.CreateICmp(IntEQ, n, ConstInt(Int32Type(), 0, false), "cmptmp") - builder.CreateCondBr(If, iftrue, iffalse) - - builder.SetInsertPointAtEnd(iftrue) - res_iftrue := ConstInt(Int32Type(), 1, false) - builder.CreateBr(end) - - builder.SetInsertPointAtEnd(iffalse) - n_minus := builder.CreateSub(n, ConstInt(Int32Type(), 1, false), "subtmp") - call_fac_args := []Value{n_minus} - call_fac := builder.CreateCall(fac, call_fac_args, "calltmp") - res_iffalse := builder.CreateMul(n, call_fac, "multmp") - builder.CreateBr(end) - - builder.SetInsertPointAtEnd(end) - res := builder.CreatePHI(Int32Type(), "result") - phi_vals := []Value{res_iftrue, res_iffalse} - phi_blocks := []BasicBlock{iftrue, iffalse} - res.AddIncoming(phi_vals, phi_blocks) - builder.CreateRet(res) - - err := VerifyModule(mod, ReturnStatusAction) - if err != nil { - t.Errorf("Error verifying module: %s", err) - return - } - - options := NewMCJITCompilerOptions() - options.SetMCJITOptimizationLevel(2) - options.SetMCJITEnableFastISel(true) - options.SetMCJITNoFramePointerElim(true) - options.SetMCJITCodeModel(CodeModelJITDefault) - engine, err := NewMCJITCompiler(mod, options) - if err != nil { - t.Errorf("Error creating JIT: %s", err) - return - } - defer engine.Dispose() - - pass := NewPassManager() - defer pass.Dispose() - - pass.AddInstructionCombiningPass() - pass.AddPromoteMemoryToRegisterPass() - pass.AddGVNPass() - pass.AddCFGSimplificationPass() - pass.Run(mod) - - exec_args := []GenericValue{NewGenericValueFromInt(Int32Type(), 10, false)} - exec_res := engine.RunFunction(fac, exec_args) - var fac10 uint64 = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 - if exec_res.Int(false) != fac10 { - t.Errorf("Expected %d, got %d", fac10, exec_res.Int(false)) - } -} diff --git a/interpreter/llvm/src/bindings/go/llvm/ir.go b/interpreter/llvm/src/bindings/go/llvm/ir.go deleted file mode 100644 index c5060811dd479..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/ir.go +++ /dev/null @@ -1,2016 +0,0 @@ -//===- ir.go - Bindings for ir --------------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the ir component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Core.h" -#include "llvm-c/Comdat.h" -#include "IRBindings.h" -#include -*/ -import "C" -import "unsafe" -import "errors" - -type ( - // We use these weird structs here because *Ref types are pointers and - // Go's spec says that a pointer cannot be used as a receiver base type. - Context struct { - C C.LLVMContextRef - } - Module struct { - C C.LLVMModuleRef - } - Type struct { - C C.LLVMTypeRef - } - Value struct { - C C.LLVMValueRef - } - Comdat struct { - C C.LLVMComdatRef - } - BasicBlock struct { - C C.LLVMBasicBlockRef - } - Builder struct { - C C.LLVMBuilderRef - } - ModuleProvider struct { - C C.LLVMModuleProviderRef - } - MemoryBuffer struct { - C C.LLVMMemoryBufferRef - } - PassManager struct { - C C.LLVMPassManagerRef - } - Use struct { - C C.LLVMUseRef - } - Metadata struct { - C C.LLVMMetadataRef - } - Attribute struct { - C C.LLVMAttributeRef - } - Opcode C.LLVMOpcode - AtomicRMWBinOp C.LLVMAtomicRMWBinOp - AtomicOrdering C.LLVMAtomicOrdering - TypeKind C.LLVMTypeKind - Linkage C.LLVMLinkage - Visibility C.LLVMVisibility - CallConv C.LLVMCallConv - ComdatSelectionKind C.LLVMComdatSelectionKind - IntPredicate C.LLVMIntPredicate - FloatPredicate C.LLVMRealPredicate - LandingPadClause C.LLVMLandingPadClauseTy - InlineAsmDialect C.LLVMInlineAsmDialect -) - -func (c Context) IsNil() bool { return c.C == nil } -func (c Module) IsNil() bool { return c.C == nil } -func (c Type) IsNil() bool { return c.C == nil } -func (c Value) IsNil() bool { return c.C == nil } -func (c BasicBlock) IsNil() bool { return c.C == nil } -func (c Builder) IsNil() bool { return c.C == nil } -func (c ModuleProvider) IsNil() bool { return c.C == nil } -func (c MemoryBuffer) IsNil() bool { return c.C == nil } -func (c PassManager) IsNil() bool { return c.C == nil } -func (c Use) IsNil() bool { return c.C == nil } -func (c Attribute) IsNil() bool { return c.C == nil } -func (c Metadata) IsNil() bool { return c.C == nil } - -// helpers -func llvmTypeRefPtr(t *Type) *C.LLVMTypeRef { return (*C.LLVMTypeRef)(unsafe.Pointer(t)) } -func llvmValueRefPtr(t *Value) *C.LLVMValueRef { return (*C.LLVMValueRef)(unsafe.Pointer(t)) } -func llvmMetadataRefPtr(t *Metadata) *C.LLVMMetadataRef { - return (*C.LLVMMetadataRef)(unsafe.Pointer(t)) -} -func llvmBasicBlockRefPtr(t *BasicBlock) *C.LLVMBasicBlockRef { - return (*C.LLVMBasicBlockRef)(unsafe.Pointer(t)) -} -func boolToLLVMBool(b bool) C.LLVMBool { - if b { - return C.LLVMBool(1) - } - return C.LLVMBool(0) -} - -func llvmValueRefs(values []Value) (*C.LLVMValueRef, C.unsigned) { - var pt *C.LLVMValueRef - ptlen := C.unsigned(len(values)) - if ptlen > 0 { - pt = llvmValueRefPtr(&values[0]) - } - return pt, ptlen -} - -func llvmMetadataRefs(mds []Metadata) (*C.LLVMMetadataRef, C.unsigned) { - var pt *C.LLVMMetadataRef - ptlen := C.unsigned(len(mds)) - if ptlen > 0 { - pt = llvmMetadataRefPtr(&mds[0]) - } - return pt, ptlen -} - -//------------------------------------------------------------------------- -// llvm.Opcode -//------------------------------------------------------------------------- - -const ( - Ret Opcode = C.LLVMRet - Br Opcode = C.LLVMBr - Switch Opcode = C.LLVMSwitch - IndirectBr Opcode = C.LLVMIndirectBr - Invoke Opcode = C.LLVMInvoke - Unreachable Opcode = C.LLVMUnreachable - - // Standard Binary Operators - Add Opcode = C.LLVMAdd - FAdd Opcode = C.LLVMFAdd - Sub Opcode = C.LLVMSub - FSub Opcode = C.LLVMFSub - Mul Opcode = C.LLVMMul - FMul Opcode = C.LLVMFMul - UDiv Opcode = C.LLVMUDiv - SDiv Opcode = C.LLVMSDiv - FDiv Opcode = C.LLVMFDiv - URem Opcode = C.LLVMURem - SRem Opcode = C.LLVMSRem - FRem Opcode = C.LLVMFRem - - // Logical Operators - Shl Opcode = C.LLVMShl - LShr Opcode = C.LLVMLShr - AShr Opcode = C.LLVMAShr - And Opcode = C.LLVMAnd - Or Opcode = C.LLVMOr - Xor Opcode = C.LLVMXor - - // Memory Operators - Alloca Opcode = C.LLVMAlloca - Load Opcode = C.LLVMLoad - Store Opcode = C.LLVMStore - GetElementPtr Opcode = C.LLVMGetElementPtr - - // Cast Operators - Trunc Opcode = C.LLVMTrunc - ZExt Opcode = C.LLVMZExt - SExt Opcode = C.LLVMSExt - FPToUI Opcode = C.LLVMFPToUI - FPToSI Opcode = C.LLVMFPToSI - UIToFP Opcode = C.LLVMUIToFP - SIToFP Opcode = C.LLVMSIToFP - FPTrunc Opcode = C.LLVMFPTrunc - FPExt Opcode = C.LLVMFPExt - PtrToInt Opcode = C.LLVMPtrToInt - IntToPtr Opcode = C.LLVMIntToPtr - BitCast Opcode = C.LLVMBitCast - - // Other Operators - ICmp Opcode = C.LLVMICmp - FCmp Opcode = C.LLVMFCmp - PHI Opcode = C.LLVMPHI - Call Opcode = C.LLVMCall - Select Opcode = C.LLVMSelect - // UserOp1 - // UserOp2 - VAArg Opcode = C.LLVMVAArg - ExtractElement Opcode = C.LLVMExtractElement - InsertElement Opcode = C.LLVMInsertElement - ShuffleVector Opcode = C.LLVMShuffleVector - ExtractValue Opcode = C.LLVMExtractValue - InsertValue Opcode = C.LLVMInsertValue -) - -const ( - AtomicRMWBinOpXchg AtomicRMWBinOp = C.LLVMAtomicRMWBinOpXchg - AtomicRMWBinOpAdd AtomicRMWBinOp = C.LLVMAtomicRMWBinOpAdd - AtomicRMWBinOpSub AtomicRMWBinOp = C.LLVMAtomicRMWBinOpSub - AtomicRMWBinOpAnd AtomicRMWBinOp = C.LLVMAtomicRMWBinOpAnd - AtomicRMWBinOpNand AtomicRMWBinOp = C.LLVMAtomicRMWBinOpNand - AtomicRMWBinOpOr AtomicRMWBinOp = C.LLVMAtomicRMWBinOpOr - AtomicRMWBinOpXor AtomicRMWBinOp = C.LLVMAtomicRMWBinOpXor - AtomicRMWBinOpMax AtomicRMWBinOp = C.LLVMAtomicRMWBinOpMax - AtomicRMWBinOpMin AtomicRMWBinOp = C.LLVMAtomicRMWBinOpMin - AtomicRMWBinOpUMax AtomicRMWBinOp = C.LLVMAtomicRMWBinOpUMax - AtomicRMWBinOpUMin AtomicRMWBinOp = C.LLVMAtomicRMWBinOpUMin -) - -const ( - AtomicOrderingNotAtomic AtomicOrdering = C.LLVMAtomicOrderingNotAtomic - AtomicOrderingUnordered AtomicOrdering = C.LLVMAtomicOrderingUnordered - AtomicOrderingMonotonic AtomicOrdering = C.LLVMAtomicOrderingMonotonic - AtomicOrderingAcquire AtomicOrdering = C.LLVMAtomicOrderingAcquire - AtomicOrderingRelease AtomicOrdering = C.LLVMAtomicOrderingRelease - AtomicOrderingAcquireRelease AtomicOrdering = C.LLVMAtomicOrderingAcquireRelease - AtomicOrderingSequentiallyConsistent AtomicOrdering = C.LLVMAtomicOrderingSequentiallyConsistent -) - -//------------------------------------------------------------------------- -// llvm.TypeKind -//------------------------------------------------------------------------- - -const ( - VoidTypeKind TypeKind = C.LLVMVoidTypeKind - FloatTypeKind TypeKind = C.LLVMFloatTypeKind - DoubleTypeKind TypeKind = C.LLVMDoubleTypeKind - X86_FP80TypeKind TypeKind = C.LLVMX86_FP80TypeKind - FP128TypeKind TypeKind = C.LLVMFP128TypeKind - PPC_FP128TypeKind TypeKind = C.LLVMPPC_FP128TypeKind - LabelTypeKind TypeKind = C.LLVMLabelTypeKind - IntegerTypeKind TypeKind = C.LLVMIntegerTypeKind - FunctionTypeKind TypeKind = C.LLVMFunctionTypeKind - StructTypeKind TypeKind = C.LLVMStructTypeKind - ArrayTypeKind TypeKind = C.LLVMArrayTypeKind - PointerTypeKind TypeKind = C.LLVMPointerTypeKind - MetadataTypeKind TypeKind = C.LLVMMetadataTypeKind - TokenTypeKind TypeKind = C.LLVMTokenTypeKind - VectorTypeKind TypeKind = C.LLVMVectorTypeKind - ScalableVectorTypeKind TypeKind = C.LLVMScalableVectorTypeKind -) - -//------------------------------------------------------------------------- -// llvm.Linkage -//------------------------------------------------------------------------- - -const ( - ExternalLinkage Linkage = C.LLVMExternalLinkage - AvailableExternallyLinkage Linkage = C.LLVMAvailableExternallyLinkage - LinkOnceAnyLinkage Linkage = C.LLVMLinkOnceAnyLinkage - LinkOnceODRLinkage Linkage = C.LLVMLinkOnceODRLinkage - WeakAnyLinkage Linkage = C.LLVMWeakAnyLinkage - WeakODRLinkage Linkage = C.LLVMWeakODRLinkage - AppendingLinkage Linkage = C.LLVMAppendingLinkage - InternalLinkage Linkage = C.LLVMInternalLinkage - PrivateLinkage Linkage = C.LLVMPrivateLinkage - ExternalWeakLinkage Linkage = C.LLVMExternalWeakLinkage - CommonLinkage Linkage = C.LLVMCommonLinkage -) - -//------------------------------------------------------------------------- -// llvm.Visibility -//------------------------------------------------------------------------- - -const ( - DefaultVisibility Visibility = C.LLVMDefaultVisibility - HiddenVisibility Visibility = C.LLVMHiddenVisibility - ProtectedVisibility Visibility = C.LLVMProtectedVisibility -) - -//------------------------------------------------------------------------- -// llvm.CallConv -//------------------------------------------------------------------------- - -const ( - CCallConv CallConv = C.LLVMCCallConv - FastCallConv CallConv = C.LLVMFastCallConv - ColdCallConv CallConv = C.LLVMColdCallConv - X86StdcallCallConv CallConv = C.LLVMX86StdcallCallConv - X86FastcallCallConv CallConv = C.LLVMX86FastcallCallConv -) - -//------------------------------------------------------------------------- -// llvm.ComdatSelectionKind -//------------------------------------------------------------------------- - -const ( - AnyComdatSelectionKind ComdatSelectionKind = C.LLVMAnyComdatSelectionKind - ExactMatchComdatSelectionKind ComdatSelectionKind = C.LLVMExactMatchComdatSelectionKind - LargestComdatSelectionKind ComdatSelectionKind = C.LLVMLargestComdatSelectionKind - NoDeduplicateComdatSelectionKind ComdatSelectionKind = C.LLVMNoDeduplicateComdatSelectionKind - SameSizeComdatSelectionKind ComdatSelectionKind = C.LLVMSameSizeComdatSelectionKind -) - -//------------------------------------------------------------------------- -// llvm.IntPredicate -//------------------------------------------------------------------------- - -const ( - IntEQ IntPredicate = C.LLVMIntEQ - IntNE IntPredicate = C.LLVMIntNE - IntUGT IntPredicate = C.LLVMIntUGT - IntUGE IntPredicate = C.LLVMIntUGE - IntULT IntPredicate = C.LLVMIntULT - IntULE IntPredicate = C.LLVMIntULE - IntSGT IntPredicate = C.LLVMIntSGT - IntSGE IntPredicate = C.LLVMIntSGE - IntSLT IntPredicate = C.LLVMIntSLT - IntSLE IntPredicate = C.LLVMIntSLE -) - -//------------------------------------------------------------------------- -// llvm.FloatPredicate -//------------------------------------------------------------------------- - -const ( - FloatPredicateFalse FloatPredicate = C.LLVMRealPredicateFalse - FloatOEQ FloatPredicate = C.LLVMRealOEQ - FloatOGT FloatPredicate = C.LLVMRealOGT - FloatOGE FloatPredicate = C.LLVMRealOGE - FloatOLT FloatPredicate = C.LLVMRealOLT - FloatOLE FloatPredicate = C.LLVMRealOLE - FloatONE FloatPredicate = C.LLVMRealONE - FloatORD FloatPredicate = C.LLVMRealORD - FloatUNO FloatPredicate = C.LLVMRealUNO - FloatUEQ FloatPredicate = C.LLVMRealUEQ - FloatUGT FloatPredicate = C.LLVMRealUGT - FloatUGE FloatPredicate = C.LLVMRealUGE - FloatULT FloatPredicate = C.LLVMRealULT - FloatULE FloatPredicate = C.LLVMRealULE - FloatUNE FloatPredicate = C.LLVMRealUNE - FloatPredicateTrue FloatPredicate = C.LLVMRealPredicateTrue -) - -//------------------------------------------------------------------------- -// llvm.LandingPadClause -//------------------------------------------------------------------------- - -const ( - LandingPadCatch LandingPadClause = C.LLVMLandingPadCatch - LandingPadFilter LandingPadClause = C.LLVMLandingPadFilter -) - -//------------------------------------------------------------------------- -// llvm.InlineAsmDialect -//------------------------------------------------------------------------- - -const ( - InlineAsmDialectATT InlineAsmDialect = C.LLVMInlineAsmDialectATT - InlineAsmDialectIntel InlineAsmDialect = C.LLVMInlineAsmDialectIntel -) - -//------------------------------------------------------------------------- -// llvm.Context -//------------------------------------------------------------------------- - -func NewContext() Context { return Context{C.LLVMContextCreate()} } -func GlobalContext() Context { return Context{C.LLVMGetGlobalContext()} } -func (c Context) Dispose() { C.LLVMContextDispose(c.C) } - -func (c Context) MDKindID(name string) (id int) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - id = int(C.LLVMGetMDKindIDInContext(c.C, cname, C.unsigned(len(name)))) - return -} - -func MDKindID(name string) (id int) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - id = int(C.LLVMGetMDKindID(cname, C.unsigned(len(name)))) - return -} - -//------------------------------------------------------------------------- -// llvm.Attribute -//------------------------------------------------------------------------- - -func AttributeKindID(name string) (id uint) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - id = uint(C.LLVMGetEnumAttributeKindForName(cname, C.size_t(len(name)))) - return -} - -func (c Context) CreateEnumAttribute(kind uint, val uint64) (a Attribute) { - a.C = C.LLVMCreateEnumAttribute(c.C, C.unsigned(kind), C.uint64_t(val)) - return -} - -func (a Attribute) GetEnumKind() (id int) { - id = int(C.LLVMGetEnumAttributeKind(a.C)) - return -} - -func (a Attribute) GetEnumValue() (val uint64) { - val = uint64(C.LLVMGetEnumAttributeValue(a.C)) - return -} - -func (c Context) CreateStringAttribute(kind string, val string) (a Attribute) { - ckind := C.CString(kind) - defer C.free(unsafe.Pointer(ckind)) - cval := C.CString(val) - defer C.free(unsafe.Pointer(cval)) - a.C = C.LLVMCreateStringAttribute(c.C, - ckind, C.unsigned(len(kind)), - cval, C.unsigned(len(val))) - return -} - -func (a Attribute) GetStringKind() string { - length := C.unsigned(0) - ckind := C.LLVMGetStringAttributeKind(a.C, &length) - return C.GoStringN(ckind, C.int(length)) -} - -func (a Attribute) GetStringValue() string { - length := C.unsigned(0) - ckind := C.LLVMGetStringAttributeValue(a.C, &length) - return C.GoStringN(ckind, C.int(length)) -} - -func (a Attribute) IsEnum() bool { - return C.LLVMIsEnumAttribute(a.C) != 0 -} - -func (a Attribute) IsString() bool { - return C.LLVMIsStringAttribute(a.C) != 0 -} - -//------------------------------------------------------------------------- -// llvm.Module -//------------------------------------------------------------------------- - -// Create and destroy modules. -// See llvm::Module::Module. -func NewModule(name string) (m Module) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - m.C = C.LLVMModuleCreateWithName(cname) - return -} - -func (c Context) NewModule(name string) (m Module) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - m.C = C.LLVMModuleCreateWithNameInContext(cname, c.C) - return -} - -// See llvm::Module::~Module -func (m Module) Dispose() { C.LLVMDisposeModule(m.C) } - -// Data layout. See Module::getDataLayout. -func (m Module) DataLayout() string { - clayout := C.LLVMGetDataLayout(m.C) - return C.GoString(clayout) -} - -func (m Module) SetDataLayout(layout string) { - clayout := C.CString(layout) - defer C.free(unsafe.Pointer(clayout)) - C.LLVMSetDataLayout(m.C, clayout) -} - -// Target triple. See Module::getTargetTriple. -func (m Module) Target() string { - ctarget := C.LLVMGetTarget(m.C) - return C.GoString(ctarget) -} -func (m Module) SetTarget(target string) { - ctarget := C.CString(target) - defer C.free(unsafe.Pointer(ctarget)) - C.LLVMSetTarget(m.C, ctarget) -} - -func (m Module) GetTypeByName(name string) (t Type) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - t.C = C.LLVMGetTypeByName(m.C, cname) - return -} - -// See Module::dump. -func (m Module) Dump() { - C.LLVMDumpModule(m.C) -} - -func (m Module) String() string { - cir := C.LLVMPrintModuleToString(m.C) - defer C.free(unsafe.Pointer(cir)) - ir := C.GoString(cir) - return ir -} - -// See Module::setModuleInlineAsm. -func (m Module) SetInlineAsm(asm string) { - casm := C.CString(asm) - defer C.free(unsafe.Pointer(casm)) - C.LLVMSetModuleInlineAsm(m.C, casm) -} - -func (m Module) AddNamedMetadataOperand(name string, operand Metadata) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.LLVMAddNamedMetadataOperand2(m.C, cname, operand.C) -} - -func (m Module) Context() (c Context) { - c.C = C.LLVMGetModuleContext(m.C) - return -} - -//------------------------------------------------------------------------- -// llvm.Type -//------------------------------------------------------------------------- - -// LLVM types conform to the following hierarchy: -// -// types: -// integer type -// real type -// function type -// sequence types: -// array type -// pointer type -// vector type -// void type -// label type -// opaque type - -// See llvm::LLVMTypeKind::getTypeID. -func (t Type) TypeKind() TypeKind { return TypeKind(C.LLVMGetTypeKind(t.C)) } - -// See llvm::LLVMType::getContext. -func (t Type) Context() (c Context) { - c.C = C.LLVMGetTypeContext(t.C) - return -} - -// Operations on integer types -func (c Context) Int1Type() (t Type) { t.C = C.LLVMInt1TypeInContext(c.C); return } -func (c Context) Int8Type() (t Type) { t.C = C.LLVMInt8TypeInContext(c.C); return } -func (c Context) Int16Type() (t Type) { t.C = C.LLVMInt16TypeInContext(c.C); return } -func (c Context) Int32Type() (t Type) { t.C = C.LLVMInt32TypeInContext(c.C); return } -func (c Context) Int64Type() (t Type) { t.C = C.LLVMInt64TypeInContext(c.C); return } -func (c Context) IntType(numbits int) (t Type) { - t.C = C.LLVMIntTypeInContext(c.C, C.unsigned(numbits)) - return -} - -func Int1Type() (t Type) { t.C = C.LLVMInt1Type(); return } -func Int8Type() (t Type) { t.C = C.LLVMInt8Type(); return } -func Int16Type() (t Type) { t.C = C.LLVMInt16Type(); return } -func Int32Type() (t Type) { t.C = C.LLVMInt32Type(); return } -func Int64Type() (t Type) { t.C = C.LLVMInt64Type(); return } - -func IntType(numbits int) (t Type) { - t.C = C.LLVMIntType(C.unsigned(numbits)) - return -} - -func (t Type) IntTypeWidth() int { - return int(C.LLVMGetIntTypeWidth(t.C)) -} - -// Operations on real types -func (c Context) FloatType() (t Type) { t.C = C.LLVMFloatTypeInContext(c.C); return } -func (c Context) DoubleType() (t Type) { t.C = C.LLVMDoubleTypeInContext(c.C); return } -func (c Context) X86FP80Type() (t Type) { t.C = C.LLVMX86FP80TypeInContext(c.C); return } -func (c Context) FP128Type() (t Type) { t.C = C.LLVMFP128TypeInContext(c.C); return } -func (c Context) PPCFP128Type() (t Type) { t.C = C.LLVMPPCFP128TypeInContext(c.C); return } - -func FloatType() (t Type) { t.C = C.LLVMFloatType(); return } -func DoubleType() (t Type) { t.C = C.LLVMDoubleType(); return } -func X86FP80Type() (t Type) { t.C = C.LLVMX86FP80Type(); return } -func FP128Type() (t Type) { t.C = C.LLVMFP128Type(); return } -func PPCFP128Type() (t Type) { t.C = C.LLVMPPCFP128Type(); return } - -// Operations on function types -func FunctionType(returnType Type, paramTypes []Type, isVarArg bool) (t Type) { - var pt *C.LLVMTypeRef - var ptlen C.unsigned - if len(paramTypes) > 0 { - pt = llvmTypeRefPtr(¶mTypes[0]) - ptlen = C.unsigned(len(paramTypes)) - } - t.C = C.LLVMFunctionType(returnType.C, - pt, - ptlen, - boolToLLVMBool(isVarArg)) - return -} - -func (t Type) IsFunctionVarArg() bool { return C.LLVMIsFunctionVarArg(t.C) != 0 } -func (t Type) ReturnType() (rt Type) { rt.C = C.LLVMGetReturnType(t.C); return } -func (t Type) ParamTypesCount() int { return int(C.LLVMCountParamTypes(t.C)) } -func (t Type) ParamTypes() []Type { - count := t.ParamTypesCount() - if count > 0 { - out := make([]Type, count) - C.LLVMGetParamTypes(t.C, llvmTypeRefPtr(&out[0])) - return out - } - return nil -} - -// Operations on struct types -func (c Context) StructType(elementTypes []Type, packed bool) (t Type) { - var pt *C.LLVMTypeRef - var ptlen C.unsigned - if len(elementTypes) > 0 { - pt = llvmTypeRefPtr(&elementTypes[0]) - ptlen = C.unsigned(len(elementTypes)) - } - t.C = C.LLVMStructTypeInContext(c.C, - pt, - ptlen, - boolToLLVMBool(packed)) - return -} - -func StructType(elementTypes []Type, packed bool) (t Type) { - var pt *C.LLVMTypeRef - var ptlen C.unsigned - if len(elementTypes) > 0 { - pt = llvmTypeRefPtr(&elementTypes[0]) - ptlen = C.unsigned(len(elementTypes)) - } - t.C = C.LLVMStructType(pt, ptlen, boolToLLVMBool(packed)) - return -} - -func (c Context) StructCreateNamed(name string) (t Type) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - t.C = C.LLVMStructCreateNamed(c.C, cname) - return -} - -func (t Type) StructName() string { - return C.GoString(C.LLVMGetStructName(t.C)) -} - -func (t Type) StructSetBody(elementTypes []Type, packed bool) { - var pt *C.LLVMTypeRef - var ptlen C.unsigned - if len(elementTypes) > 0 { - pt = llvmTypeRefPtr(&elementTypes[0]) - ptlen = C.unsigned(len(elementTypes)) - } - C.LLVMStructSetBody(t.C, pt, ptlen, boolToLLVMBool(packed)) -} - -func (t Type) IsStructPacked() bool { return C.LLVMIsPackedStruct(t.C) != 0 } -func (t Type) StructElementTypesCount() int { return int(C.LLVMCountStructElementTypes(t.C)) } -func (t Type) StructElementTypes() []Type { - out := make([]Type, t.StructElementTypesCount()) - if len(out) > 0 { - C.LLVMGetStructElementTypes(t.C, llvmTypeRefPtr(&out[0])) - } - return out -} - -// Operations on array, pointer, and vector types (sequence types) -func (t Type) Subtypes() (ret []Type) { - ret = make([]Type, C.LLVMGetNumContainedTypes(t.C)) - C.LLVMGetSubtypes(t.C, llvmTypeRefPtr(&ret[0])) - return -} - -func ArrayType(elementType Type, elementCount int) (t Type) { - t.C = C.LLVMArrayType(elementType.C, C.unsigned(elementCount)) - return -} -func PointerType(elementType Type, addressSpace int) (t Type) { - t.C = C.LLVMPointerType(elementType.C, C.unsigned(addressSpace)) - return -} -func VectorType(elementType Type, elementCount int) (t Type) { - t.C = C.LLVMVectorType(elementType.C, C.unsigned(elementCount)) - return -} - -func (t Type) ElementType() (rt Type) { rt.C = C.LLVMGetElementType(t.C); return } -func (t Type) ArrayLength() int { return int(C.LLVMGetArrayLength(t.C)) } -func (t Type) PointerAddressSpace() int { return int(C.LLVMGetPointerAddressSpace(t.C)) } -func (t Type) VectorSize() int { return int(C.LLVMGetVectorSize(t.C)) } - -// Operations on other types -func (c Context) VoidType() (t Type) { t.C = C.LLVMVoidTypeInContext(c.C); return } -func (c Context) LabelType() (t Type) { t.C = C.LLVMLabelTypeInContext(c.C); return } -func (c Context) TokenType() (t Type) { t.C = C.LLVMTokenTypeInContext(c.C); return } - -func VoidType() (t Type) { t.C = C.LLVMVoidType(); return } -func LabelType() (t Type) { t.C = C.LLVMLabelType(); return } - -//------------------------------------------------------------------------- -// llvm.Value -//------------------------------------------------------------------------- - -// Operations on all values -func (v Value) Type() (t Type) { t.C = C.LLVMTypeOf(v.C); return } -func (v Value) Name() string { return C.GoString(C.LLVMGetValueName(v.C)) } -func (v Value) SetName(name string) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.LLVMSetValueName(v.C, cname) -} -func (v Value) Dump() { C.LLVMDumpValue(v.C) } -func (v Value) ReplaceAllUsesWith(nv Value) { C.LLVMReplaceAllUsesWith(v.C, nv.C) } -func (v Value) HasMetadata() bool { return C.LLVMHasMetadata(v.C) != 0 } -func (v Value) Metadata(kind int) (rv Value) { - rv.C = C.LLVMGetMetadata(v.C, C.unsigned(kind)) - return -} -func (v Value) SetMetadata(kind int, node Metadata) { - C.LLVMSetMetadata2(v.C, C.unsigned(kind), node.C) -} - -// Conversion functions. -// Return the input value if it is an instance of the specified class, otherwise NULL. -// See llvm::dyn_cast_or_null<>. -func (v Value) IsAArgument() (rv Value) { rv.C = C.LLVMIsAArgument(v.C); return } -func (v Value) IsABasicBlock() (rv Value) { rv.C = C.LLVMIsABasicBlock(v.C); return } -func (v Value) IsAInlineAsm() (rv Value) { rv.C = C.LLVMIsAInlineAsm(v.C); return } -func (v Value) IsAUser() (rv Value) { rv.C = C.LLVMIsAUser(v.C); return } -func (v Value) IsAConstant() (rv Value) { rv.C = C.LLVMIsAConstant(v.C); return } -func (v Value) IsAConstantAggregateZero() (rv Value) { - rv.C = C.LLVMIsAConstantAggregateZero(v.C) - return -} -func (v Value) IsAConstantArray() (rv Value) { rv.C = C.LLVMIsAConstantArray(v.C); return } -func (v Value) IsAConstantExpr() (rv Value) { rv.C = C.LLVMIsAConstantExpr(v.C); return } -func (v Value) IsAConstantFP() (rv Value) { rv.C = C.LLVMIsAConstantFP(v.C); return } -func (v Value) IsAConstantInt() (rv Value) { rv.C = C.LLVMIsAConstantInt(v.C); return } -func (v Value) IsAConstantPointerNull() (rv Value) { rv.C = C.LLVMIsAConstantPointerNull(v.C); return } -func (v Value) IsAConstantStruct() (rv Value) { rv.C = C.LLVMIsAConstantStruct(v.C); return } -func (v Value) IsAConstantVector() (rv Value) { rv.C = C.LLVMIsAConstantVector(v.C); return } -func (v Value) IsAGlobalValue() (rv Value) { rv.C = C.LLVMIsAGlobalValue(v.C); return } -func (v Value) IsAFunction() (rv Value) { rv.C = C.LLVMIsAFunction(v.C); return } -func (v Value) IsAGlobalAlias() (rv Value) { rv.C = C.LLVMIsAGlobalAlias(v.C); return } -func (v Value) IsAGlobalVariable() (rv Value) { rv.C = C.LLVMIsAGlobalVariable(v.C); return } -func (v Value) IsAUndefValue() (rv Value) { rv.C = C.LLVMIsAUndefValue(v.C); return } -func (v Value) IsAInstruction() (rv Value) { rv.C = C.LLVMIsAInstruction(v.C); return } -func (v Value) IsABinaryOperator() (rv Value) { rv.C = C.LLVMIsABinaryOperator(v.C); return } -func (v Value) IsACallInst() (rv Value) { rv.C = C.LLVMIsACallInst(v.C); return } -func (v Value) IsAIntrinsicInst() (rv Value) { rv.C = C.LLVMIsAIntrinsicInst(v.C); return } -func (v Value) IsADbgInfoIntrinsic() (rv Value) { rv.C = C.LLVMIsADbgInfoIntrinsic(v.C); return } -func (v Value) IsADbgDeclareInst() (rv Value) { rv.C = C.LLVMIsADbgDeclareInst(v.C); return } -func (v Value) IsAMemIntrinsic() (rv Value) { rv.C = C.LLVMIsAMemIntrinsic(v.C); return } -func (v Value) IsAMemCpyInst() (rv Value) { rv.C = C.LLVMIsAMemCpyInst(v.C); return } -func (v Value) IsAMemMoveInst() (rv Value) { rv.C = C.LLVMIsAMemMoveInst(v.C); return } -func (v Value) IsAMemSetInst() (rv Value) { rv.C = C.LLVMIsAMemSetInst(v.C); return } -func (v Value) IsACmpInst() (rv Value) { rv.C = C.LLVMIsACmpInst(v.C); return } -func (v Value) IsAFCmpInst() (rv Value) { rv.C = C.LLVMIsAFCmpInst(v.C); return } -func (v Value) IsAICmpInst() (rv Value) { rv.C = C.LLVMIsAICmpInst(v.C); return } -func (v Value) IsAExtractElementInst() (rv Value) { rv.C = C.LLVMIsAExtractElementInst(v.C); return } -func (v Value) IsAGetElementPtrInst() (rv Value) { rv.C = C.LLVMIsAGetElementPtrInst(v.C); return } -func (v Value) IsAInsertElementInst() (rv Value) { rv.C = C.LLVMIsAInsertElementInst(v.C); return } -func (v Value) IsAInsertValueInst() (rv Value) { rv.C = C.LLVMIsAInsertValueInst(v.C); return } -func (v Value) IsAPHINode() (rv Value) { rv.C = C.LLVMIsAPHINode(v.C); return } -func (v Value) IsASelectInst() (rv Value) { rv.C = C.LLVMIsASelectInst(v.C); return } -func (v Value) IsAShuffleVectorInst() (rv Value) { rv.C = C.LLVMIsAShuffleVectorInst(v.C); return } -func (v Value) IsAStoreInst() (rv Value) { rv.C = C.LLVMIsAStoreInst(v.C); return } -func (v Value) IsABranchInst() (rv Value) { rv.C = C.LLVMIsABranchInst(v.C); return } -func (v Value) IsAInvokeInst() (rv Value) { rv.C = C.LLVMIsAInvokeInst(v.C); return } -func (v Value) IsAReturnInst() (rv Value) { rv.C = C.LLVMIsAReturnInst(v.C); return } -func (v Value) IsASwitchInst() (rv Value) { rv.C = C.LLVMIsASwitchInst(v.C); return } -func (v Value) IsAUnreachableInst() (rv Value) { rv.C = C.LLVMIsAUnreachableInst(v.C); return } -func (v Value) IsAUnaryInstruction() (rv Value) { rv.C = C.LLVMIsAUnaryInstruction(v.C); return } -func (v Value) IsAAllocaInst() (rv Value) { rv.C = C.LLVMIsAAllocaInst(v.C); return } -func (v Value) IsACastInst() (rv Value) { rv.C = C.LLVMIsACastInst(v.C); return } -func (v Value) IsABitCastInst() (rv Value) { rv.C = C.LLVMIsABitCastInst(v.C); return } -func (v Value) IsAFPExtInst() (rv Value) { rv.C = C.LLVMIsAFPExtInst(v.C); return } -func (v Value) IsAFPToSIInst() (rv Value) { rv.C = C.LLVMIsAFPToSIInst(v.C); return } -func (v Value) IsAFPToUIInst() (rv Value) { rv.C = C.LLVMIsAFPToUIInst(v.C); return } -func (v Value) IsAFPTruncInst() (rv Value) { rv.C = C.LLVMIsAFPTruncInst(v.C); return } -func (v Value) IsAIntToPtrInst() (rv Value) { rv.C = C.LLVMIsAIntToPtrInst(v.C); return } -func (v Value) IsAPtrToIntInst() (rv Value) { rv.C = C.LLVMIsAPtrToIntInst(v.C); return } -func (v Value) IsASExtInst() (rv Value) { rv.C = C.LLVMIsASExtInst(v.C); return } -func (v Value) IsASIToFPInst() (rv Value) { rv.C = C.LLVMIsASIToFPInst(v.C); return } -func (v Value) IsATruncInst() (rv Value) { rv.C = C.LLVMIsATruncInst(v.C); return } -func (v Value) IsAUIToFPInst() (rv Value) { rv.C = C.LLVMIsAUIToFPInst(v.C); return } -func (v Value) IsAZExtInst() (rv Value) { rv.C = C.LLVMIsAZExtInst(v.C); return } -func (v Value) IsAExtractValueInst() (rv Value) { rv.C = C.LLVMIsAExtractValueInst(v.C); return } -func (v Value) IsALoadInst() (rv Value) { rv.C = C.LLVMIsALoadInst(v.C); return } -func (v Value) IsAVAArgInst() (rv Value) { rv.C = C.LLVMIsAVAArgInst(v.C); return } - -// Operations on Uses -func (v Value) FirstUse() (u Use) { u.C = C.LLVMGetFirstUse(v.C); return } -func (u Use) NextUse() (ru Use) { ru.C = C.LLVMGetNextUse(u.C); return } -func (u Use) User() (v Value) { v.C = C.LLVMGetUser(u.C); return } -func (u Use) UsedValue() (v Value) { v.C = C.LLVMGetUsedValue(u.C); return } - -// Operations on Users -func (v Value) Operand(i int) (rv Value) { rv.C = C.LLVMGetOperand(v.C, C.unsigned(i)); return } -func (v Value) SetOperand(i int, op Value) { C.LLVMSetOperand(v.C, C.unsigned(i), op.C) } -func (v Value) OperandsCount() int { return int(C.LLVMGetNumOperands(v.C)) } - -// Operations on constants of any type -func ConstNull(t Type) (v Value) { v.C = C.LLVMConstNull(t.C); return } -func ConstAllOnes(t Type) (v Value) { v.C = C.LLVMConstAllOnes(t.C); return } -func Undef(t Type) (v Value) { v.C = C.LLVMGetUndef(t.C); return } -func (v Value) IsConstant() bool { return C.LLVMIsConstant(v.C) != 0 } -func (v Value) IsNull() bool { return C.LLVMIsNull(v.C) != 0 } -func (v Value) IsUndef() bool { return C.LLVMIsUndef(v.C) != 0 } -func ConstPointerNull(t Type) (v Value) { v.C = C.LLVMConstPointerNull(t.C); return } - -// Operations on metadata -func (c Context) MDString(str string) (md Metadata) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - md.C = C.LLVMMDString2(c.C, cstr, C.unsigned(len(str))) - return -} -func (c Context) MDNode(mds []Metadata) (md Metadata) { - ptr, nvals := llvmMetadataRefs(mds) - md.C = C.LLVMMDNode2(c.C, ptr, nvals) - return -} -func (v Value) ConstantAsMetadata() (md Metadata) { - md.C = C.LLVMConstantAsMetadata(v.C) - return -} - -// Operations on scalar constants -func ConstInt(t Type, n uint64, signExtend bool) (v Value) { - v.C = C.LLVMConstInt(t.C, - C.ulonglong(n), - boolToLLVMBool(signExtend)) - return -} -func ConstIntFromString(t Type, str string, radix int) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - v.C = C.LLVMConstIntOfString(t.C, cstr, C.uint8_t(radix)) - return -} -func ConstFloat(t Type, n float64) (v Value) { - v.C = C.LLVMConstReal(t.C, C.double(n)) - return -} -func ConstFloatFromString(t Type, str string) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - v.C = C.LLVMConstRealOfString(t.C, cstr) - return -} - -func (v Value) ZExtValue() uint64 { return uint64(C.LLVMConstIntGetZExtValue(v.C)) } -func (v Value) SExtValue() int64 { return int64(C.LLVMConstIntGetSExtValue(v.C)) } - -// Operations on composite constants -func (c Context) ConstString(str string, addnull bool) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - v.C = C.LLVMConstStringInContext(c.C, cstr, - C.unsigned(len(str)), boolToLLVMBool(!addnull)) - return -} -func (c Context) ConstStruct(constVals []Value, packed bool) (v Value) { - ptr, nvals := llvmValueRefs(constVals) - v.C = C.LLVMConstStructInContext(c.C, ptr, nvals, - boolToLLVMBool(packed)) - return -} -func ConstNamedStruct(t Type, constVals []Value) (v Value) { - ptr, nvals := llvmValueRefs(constVals) - v.C = C.LLVMConstNamedStruct(t.C, ptr, nvals) - return -} -func ConstString(str string, addnull bool) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - v.C = C.LLVMConstString(cstr, - C.unsigned(len(str)), boolToLLVMBool(!addnull)) - return -} -func ConstArray(t Type, constVals []Value) (v Value) { - ptr, nvals := llvmValueRefs(constVals) - v.C = C.LLVMConstArray(t.C, ptr, nvals) - return -} -func ConstStruct(constVals []Value, packed bool) (v Value) { - ptr, nvals := llvmValueRefs(constVals) - v.C = C.LLVMConstStruct(ptr, nvals, boolToLLVMBool(packed)) - return -} -func ConstVector(scalarConstVals []Value, packed bool) (v Value) { - ptr, nvals := llvmValueRefs(scalarConstVals) - v.C = C.LLVMConstVector(ptr, nvals) - return -} - -// Constant expressions -func (v Value) Opcode() Opcode { return Opcode(C.LLVMGetConstOpcode(v.C)) } -func (v Value) InstructionOpcode() Opcode { return Opcode(C.LLVMGetInstructionOpcode(v.C)) } -func AlignOf(t Type) (v Value) { v.C = C.LLVMAlignOf(t.C); return } -func SizeOf(t Type) (v Value) { v.C = C.LLVMSizeOf(t.C); return } -func ConstNeg(v Value) (rv Value) { rv.C = C.LLVMConstNeg(v.C); return } -func ConstNSWNeg(v Value) (rv Value) { rv.C = C.LLVMConstNSWNeg(v.C); return } -func ConstNUWNeg(v Value) (rv Value) { rv.C = C.LLVMConstNUWNeg(v.C); return } -func ConstFNeg(v Value) (rv Value) { rv.C = C.LLVMConstFNeg(v.C); return } -func ConstNot(v Value) (rv Value) { rv.C = C.LLVMConstNot(v.C); return } -func ConstAdd(lhs, rhs Value) (v Value) { v.C = C.LLVMConstAdd(lhs.C, rhs.C); return } -func ConstNSWAdd(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNSWAdd(lhs.C, rhs.C); return } -func ConstNUWAdd(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNUWAdd(lhs.C, rhs.C); return } -func ConstFAdd(lhs, rhs Value) (v Value) { v.C = C.LLVMConstFAdd(lhs.C, rhs.C); return } -func ConstSub(lhs, rhs Value) (v Value) { v.C = C.LLVMConstSub(lhs.C, rhs.C); return } -func ConstNSWSub(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNSWSub(lhs.C, rhs.C); return } -func ConstNUWSub(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNUWSub(lhs.C, rhs.C); return } -func ConstFSub(lhs, rhs Value) (v Value) { v.C = C.LLVMConstFSub(lhs.C, rhs.C); return } -func ConstMul(lhs, rhs Value) (v Value) { v.C = C.LLVMConstMul(lhs.C, rhs.C); return } -func ConstNSWMul(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNSWMul(lhs.C, rhs.C); return } -func ConstNUWMul(lhs, rhs Value) (v Value) { v.C = C.LLVMConstNUWMul(lhs.C, rhs.C); return } -func ConstFMul(lhs, rhs Value) (v Value) { v.C = C.LLVMConstFMul(lhs.C, rhs.C); return } -func ConstUDiv(lhs, rhs Value) (v Value) { v.C = C.LLVMConstUDiv(lhs.C, rhs.C); return } -func ConstSDiv(lhs, rhs Value) (v Value) { v.C = C.LLVMConstSDiv(lhs.C, rhs.C); return } -func ConstExactSDiv(lhs, rhs Value) (v Value) { v.C = C.LLVMConstExactSDiv(lhs.C, rhs.C); return } -func ConstFDiv(lhs, rhs Value) (v Value) { v.C = C.LLVMConstFDiv(lhs.C, rhs.C); return } -func ConstURem(lhs, rhs Value) (v Value) { v.C = C.LLVMConstURem(lhs.C, rhs.C); return } -func ConstSRem(lhs, rhs Value) (v Value) { v.C = C.LLVMConstSRem(lhs.C, rhs.C); return } -func ConstFRem(lhs, rhs Value) (v Value) { v.C = C.LLVMConstFRem(lhs.C, rhs.C); return } -func ConstAnd(lhs, rhs Value) (v Value) { v.C = C.LLVMConstAnd(lhs.C, rhs.C); return } -func ConstOr(lhs, rhs Value) (v Value) { v.C = C.LLVMConstOr(lhs.C, rhs.C); return } -func ConstXor(lhs, rhs Value) (v Value) { v.C = C.LLVMConstXor(lhs.C, rhs.C); return } - -func ConstICmp(pred IntPredicate, lhs, rhs Value) (v Value) { - v.C = C.LLVMConstICmp(C.LLVMIntPredicate(pred), lhs.C, rhs.C) - return -} -func ConstFCmp(pred FloatPredicate, lhs, rhs Value) (v Value) { - v.C = C.LLVMConstFCmp(C.LLVMRealPredicate(pred), lhs.C, rhs.C) - return -} - -func ConstShl(lhs, rhs Value) (v Value) { v.C = C.LLVMConstShl(lhs.C, rhs.C); return } -func ConstLShr(lhs, rhs Value) (v Value) { v.C = C.LLVMConstLShr(lhs.C, rhs.C); return } -func ConstAShr(lhs, rhs Value) (v Value) { v.C = C.LLVMConstAShr(lhs.C, rhs.C); return } - -func ConstGEP(v Value, indices []Value) (rv Value) { - ptr, nvals := llvmValueRefs(indices) - rv.C = C.LLVMConstGEP(v.C, ptr, nvals) - return -} -func ConstInBoundsGEP(v Value, indices []Value) (rv Value) { - ptr, nvals := llvmValueRefs(indices) - rv.C = C.LLVMConstInBoundsGEP(v.C, ptr, nvals) - return -} -func ConstTrunc(v Value, t Type) (rv Value) { rv.C = C.LLVMConstTrunc(v.C, t.C); return } -func ConstSExt(v Value, t Type) (rv Value) { rv.C = C.LLVMConstSExt(v.C, t.C); return } -func ConstZExt(v Value, t Type) (rv Value) { rv.C = C.LLVMConstZExt(v.C, t.C); return } -func ConstFPTrunc(v Value, t Type) (rv Value) { rv.C = C.LLVMConstFPTrunc(v.C, t.C); return } -func ConstFPExt(v Value, t Type) (rv Value) { rv.C = C.LLVMConstFPExt(v.C, t.C); return } -func ConstUIToFP(v Value, t Type) (rv Value) { rv.C = C.LLVMConstUIToFP(v.C, t.C); return } -func ConstSIToFP(v Value, t Type) (rv Value) { rv.C = C.LLVMConstSIToFP(v.C, t.C); return } -func ConstFPToUI(v Value, t Type) (rv Value) { rv.C = C.LLVMConstFPToUI(v.C, t.C); return } -func ConstFPToSI(v Value, t Type) (rv Value) { rv.C = C.LLVMConstFPToSI(v.C, t.C); return } -func ConstPtrToInt(v Value, t Type) (rv Value) { rv.C = C.LLVMConstPtrToInt(v.C, t.C); return } -func ConstIntToPtr(v Value, t Type) (rv Value) { rv.C = C.LLVMConstIntToPtr(v.C, t.C); return } -func ConstBitCast(v Value, t Type) (rv Value) { rv.C = C.LLVMConstBitCast(v.C, t.C); return } -func ConstZExtOrBitCast(v Value, t Type) (rv Value) { rv.C = C.LLVMConstZExtOrBitCast(v.C, t.C); return } -func ConstSExtOrBitCast(v Value, t Type) (rv Value) { rv.C = C.LLVMConstSExtOrBitCast(v.C, t.C); return } -func ConstTruncOrBitCast(v Value, t Type) (rv Value) { - rv.C = C.LLVMConstTruncOrBitCast(v.C, t.C) - return -} -func ConstPointerCast(v Value, t Type) (rv Value) { rv.C = C.LLVMConstPointerCast(v.C, t.C); return } -func ConstIntCast(v Value, t Type, signed bool) (rv Value) { - rv.C = C.LLVMConstIntCast(v.C, t.C, boolToLLVMBool(signed)) - return -} -func ConstFPCast(v Value, t Type) (rv Value) { rv.C = C.LLVMConstFPCast(v.C, t.C); return } -func ConstSelect(cond, iftrue, iffalse Value) (rv Value) { - rv.C = C.LLVMConstSelect(cond.C, iftrue.C, iffalse.C) - return -} -func ConstExtractElement(vec, i Value) (rv Value) { - rv.C = C.LLVMConstExtractElement(vec.C, i.C) - return -} -func ConstInsertElement(vec, elem, i Value) (rv Value) { - rv.C = C.LLVMConstInsertElement(vec.C, elem.C, i.C) - return -} -func ConstShuffleVector(veca, vecb, mask Value) (rv Value) { - rv.C = C.LLVMConstShuffleVector(veca.C, vecb.C, mask.C) - return -} - -//TODO -//LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList, -// unsigned NumIdx); - -func ConstExtractValue(agg Value, indices []uint32) (rv Value) { - n := len(indices) - if n == 0 { - panic("one or more indices are required") - } - ptr := (*C.unsigned)(&indices[0]) - rv.C = C.LLVMConstExtractValue(agg.C, ptr, C.unsigned(n)) - return -} - -func ConstInsertValue(agg, val Value, indices []uint32) (rv Value) { - n := len(indices) - if n == 0 { - panic("one or more indices are required") - } - ptr := (*C.unsigned)(&indices[0]) - rv.C = C.LLVMConstInsertValue(agg.C, val.C, ptr, C.unsigned(n)) - return -} - -func BlockAddress(f Value, bb BasicBlock) (v Value) { - v.C = C.LLVMBlockAddress(f.C, bb.C) - return -} - -// Operations on global variables, functions, and aliases (globals) -func (v Value) GlobalParent() (m Module) { m.C = C.LLVMGetGlobalParent(v.C); return } -func (v Value) IsDeclaration() bool { return C.LLVMIsDeclaration(v.C) != 0 } -func (v Value) Linkage() Linkage { return Linkage(C.LLVMGetLinkage(v.C)) } -func (v Value) SetLinkage(l Linkage) { C.LLVMSetLinkage(v.C, C.LLVMLinkage(l)) } -func (v Value) Section() string { return C.GoString(C.LLVMGetSection(v.C)) } -func (v Value) SetSection(str string) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - C.LLVMSetSection(v.C, cstr) -} -func (v Value) Visibility() Visibility { return Visibility(C.LLVMGetVisibility(v.C)) } -func (v Value) SetVisibility(vi Visibility) { C.LLVMSetVisibility(v.C, C.LLVMVisibility(vi)) } -func (v Value) Alignment() int { return int(C.LLVMGetAlignment(v.C)) } -func (v Value) SetAlignment(a int) { C.LLVMSetAlignment(v.C, C.unsigned(a)) } -func (v Value) SetUnnamedAddr(ua bool) { C.LLVMSetUnnamedAddr(v.C, boolToLLVMBool(ua)) } - -// Operations on global variables -func AddGlobal(m Module, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMAddGlobal(m.C, t.C, cname) - return -} -func AddGlobalInAddressSpace(m Module, t Type, name string, addressSpace int) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMAddGlobalInAddressSpace(m.C, t.C, cname, C.unsigned(addressSpace)) - return -} -func (m Module) NamedGlobal(name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMGetNamedGlobal(m.C, cname) - return -} - -func (m Module) FirstGlobal() (v Value) { v.C = C.LLVMGetFirstGlobal(m.C); return } -func (m Module) LastGlobal() (v Value) { v.C = C.LLVMGetLastGlobal(m.C); return } -func NextGlobal(v Value) (rv Value) { rv.C = C.LLVMGetNextGlobal(v.C); return } -func PrevGlobal(v Value) (rv Value) { rv.C = C.LLVMGetPreviousGlobal(v.C); return } -func (v Value) EraseFromParentAsGlobal() { C.LLVMDeleteGlobal(v.C) } -func (v Value) Initializer() (rv Value) { rv.C = C.LLVMGetInitializer(v.C); return } -func (v Value) SetInitializer(cv Value) { C.LLVMSetInitializer(v.C, cv.C) } -func (v Value) IsThreadLocal() bool { return C.LLVMIsThreadLocal(v.C) != 0 } -func (v Value) SetThreadLocal(tl bool) { C.LLVMSetThreadLocal(v.C, boolToLLVMBool(tl)) } -func (v Value) IsGlobalConstant() bool { return C.LLVMIsGlobalConstant(v.C) != 0 } -func (v Value) SetGlobalConstant(gc bool) { C.LLVMSetGlobalConstant(v.C, boolToLLVMBool(gc)) } -func (v Value) IsVolatile() bool { return C.LLVMGetVolatile(v.C) != 0 } -func (v Value) SetVolatile(volatile bool) { C.LLVMSetVolatile(v.C, boolToLLVMBool(volatile)) } -func (v Value) Ordering() AtomicOrdering { return AtomicOrdering(C.LLVMGetOrdering(v.C)) } -func (v Value) SetOrdering(ordering AtomicOrdering) { - C.LLVMSetOrdering(v.C, C.LLVMAtomicOrdering(ordering)) -} -func (v Value) IsAtomicSingleThread() bool { return C.LLVMIsAtomicSingleThread(v.C) != 0 } -func (v Value) SetAtomicSingleThread(singleThread bool) { - C.LLVMSetAtomicSingleThread(v.C, boolToLLVMBool(singleThread)) -} -func (v Value) CmpXchgSuccessOrdering() AtomicOrdering { - return AtomicOrdering(C.LLVMGetCmpXchgSuccessOrdering(v.C)) -} -func (v Value) SetCmpXchgSuccessOrdering(ordering AtomicOrdering) { - C.LLVMSetCmpXchgSuccessOrdering(v.C, C.LLVMAtomicOrdering(ordering)) -} -func (v Value) CmpXchgFailureOrdering() AtomicOrdering { - return AtomicOrdering(C.LLVMGetCmpXchgFailureOrdering(v.C)) -} -func (v Value) SetCmpXchgFailureOrdering(ordering AtomicOrdering) { - C.LLVMSetCmpXchgFailureOrdering(v.C, C.LLVMAtomicOrdering(ordering)) -} - -// Operations on aliases -func AddAlias(m Module, t Type, aliasee Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMAddAlias(m.C, t.C, aliasee.C, cname) - return -} - -// Operations on comdat -func (m Module) Comdat(name string) (c Comdat) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - c.C = C.LLVMGetOrInsertComdat(m.C, cname) - return -} - -func (v Value) Comdat() (c Comdat) { c.C = C.LLVMGetComdat(v.C); return } -func (v Value) SetComdat(c Comdat) { C.LLVMSetComdat(v.C, c.C) } - -func (c Comdat) SelectionKind() ComdatSelectionKind { - return ComdatSelectionKind(C.LLVMGetComdatSelectionKind(c.C)) -} - -func (c Comdat) SetSelectionKind(k ComdatSelectionKind) { - C.LLVMSetComdatSelectionKind(c.C, (C.LLVMComdatSelectionKind)(k)) -} - -// Operations on functions -func AddFunction(m Module, name string, ft Type) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMAddFunction(m.C, cname, ft.C) - return -} - -func (m Module) NamedFunction(name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMGetNamedFunction(m.C, cname) - return -} - -func (m Module) FirstFunction() (v Value) { v.C = C.LLVMGetFirstFunction(m.C); return } -func (m Module) LastFunction() (v Value) { v.C = C.LLVMGetLastFunction(m.C); return } -func NextFunction(v Value) (rv Value) { rv.C = C.LLVMGetNextFunction(v.C); return } -func PrevFunction(v Value) (rv Value) { rv.C = C.LLVMGetPreviousFunction(v.C); return } -func (v Value) EraseFromParentAsFunction() { C.LLVMDeleteFunction(v.C) } -func (v Value) IntrinsicID() int { return int(C.LLVMGetIntrinsicID(v.C)) } -func (v Value) FunctionCallConv() CallConv { - return CallConv(C.LLVMCallConv(C.LLVMGetFunctionCallConv(v.C))) -} -func (v Value) SetFunctionCallConv(cc CallConv) { C.LLVMSetFunctionCallConv(v.C, C.unsigned(cc)) } -func (v Value) GC() string { return C.GoString(C.LLVMGetGC(v.C)) } -func (v Value) SetGC(name string) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.LLVMSetGC(v.C, cname) -} -func (v Value) AddAttributeAtIndex(i int, a Attribute) { - C.LLVMAddAttributeAtIndex(v.C, C.LLVMAttributeIndex(i), a.C) -} -func (v Value) AddFunctionAttr(a Attribute) { - v.AddAttributeAtIndex(C.LLVMAttributeFunctionIndex, a) -} -func (v Value) GetEnumAttributeAtIndex(i int, kind uint) (a Attribute) { - a.C = C.LLVMGetEnumAttributeAtIndex(v.C, C.LLVMAttributeIndex(i), C.unsigned(kind)) - return -} -func (v Value) GetEnumFunctionAttribute(kind uint) Attribute { - return v.GetEnumAttributeAtIndex(C.LLVMAttributeFunctionIndex, kind) -} -func (v Value) GetStringAttributeAtIndex(i int, kind string) (a Attribute) { - ckind := C.CString(kind) - defer C.free(unsafe.Pointer(ckind)) - a.C = C.LLVMGetStringAttributeAtIndex(v.C, C.LLVMAttributeIndex(i), - ckind, C.unsigned(len(kind))) - return -} -func (v Value) RemoveEnumAttributeAtIndex(i int, kind uint) { - C.LLVMRemoveEnumAttributeAtIndex(v.C, C.LLVMAttributeIndex(i), C.unsigned(kind)) -} -func (v Value) RemoveEnumFunctionAttribute(kind uint) { - v.RemoveEnumAttributeAtIndex(C.LLVMAttributeFunctionIndex, kind) -} -func (v Value) RemoveStringAttributeAtIndex(i int, kind string) { - ckind := C.CString(kind) - defer C.free(unsafe.Pointer(ckind)) - C.LLVMRemoveStringAttributeAtIndex(v.C, C.LLVMAttributeIndex(i), - ckind, C.unsigned(len(kind))) -} -func (v Value) AddTargetDependentFunctionAttr(attr, value string) { - cattr := C.CString(attr) - defer C.free(unsafe.Pointer(cattr)) - cvalue := C.CString(value) - defer C.free(unsafe.Pointer(cvalue)) - C.LLVMAddTargetDependentFunctionAttr(v.C, cattr, cvalue) -} -func (v Value) SetPersonality(p Value) { - C.LLVMSetPersonalityFn(v.C, p.C) -} - -// Operations on parameters -func (v Value) ParamsCount() int { return int(C.LLVMCountParams(v.C)) } -func (v Value) Params() []Value { - out := make([]Value, v.ParamsCount()) - if len(out) > 0 { - C.LLVMGetParams(v.C, llvmValueRefPtr(&out[0])) - } - return out -} -func (v Value) Param(i int) (rv Value) { rv.C = C.LLVMGetParam(v.C, C.unsigned(i)); return } -func (v Value) ParamParent() (rv Value) { rv.C = C.LLVMGetParamParent(v.C); return } -func (v Value) FirstParam() (rv Value) { rv.C = C.LLVMGetFirstParam(v.C); return } -func (v Value) LastParam() (rv Value) { rv.C = C.LLVMGetLastParam(v.C); return } -func NextParam(v Value) (rv Value) { rv.C = C.LLVMGetNextParam(v.C); return } -func PrevParam(v Value) (rv Value) { rv.C = C.LLVMGetPreviousParam(v.C); return } -func (v Value) SetParamAlignment(align int) { C.LLVMSetParamAlignment(v.C, C.unsigned(align)) } - -// Operations on basic blocks -func (bb BasicBlock) AsValue() (v Value) { v.C = C.LLVMBasicBlockAsValue(bb.C); return } -func (v Value) IsBasicBlock() bool { return C.LLVMValueIsBasicBlock(v.C) != 0 } -func (v Value) AsBasicBlock() (bb BasicBlock) { bb.C = C.LLVMValueAsBasicBlock(v.C); return } -func (bb BasicBlock) Parent() (v Value) { v.C = C.LLVMGetBasicBlockParent(bb.C); return } -func (v Value) BasicBlocksCount() int { return int(C.LLVMCountBasicBlocks(v.C)) } -func (v Value) BasicBlocks() []BasicBlock { - out := make([]BasicBlock, v.BasicBlocksCount()) - C.LLVMGetBasicBlocks(v.C, llvmBasicBlockRefPtr(&out[0])) - return out -} -func (v Value) FirstBasicBlock() (bb BasicBlock) { bb.C = C.LLVMGetFirstBasicBlock(v.C); return } -func (v Value) LastBasicBlock() (bb BasicBlock) { bb.C = C.LLVMGetLastBasicBlock(v.C); return } -func NextBasicBlock(bb BasicBlock) (rbb BasicBlock) { rbb.C = C.LLVMGetNextBasicBlock(bb.C); return } -func PrevBasicBlock(bb BasicBlock) (rbb BasicBlock) { rbb.C = C.LLVMGetPreviousBasicBlock(bb.C); return } -func (v Value) EntryBasicBlock() (bb BasicBlock) { bb.C = C.LLVMGetEntryBasicBlock(v.C); return } -func (c Context) AddBasicBlock(f Value, name string) (bb BasicBlock) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - bb.C = C.LLVMAppendBasicBlockInContext(c.C, f.C, cname) - return -} -func (c Context) InsertBasicBlock(ref BasicBlock, name string) (bb BasicBlock) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - bb.C = C.LLVMInsertBasicBlockInContext(c.C, ref.C, cname) - return -} -func AddBasicBlock(f Value, name string) (bb BasicBlock) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - bb.C = C.LLVMAppendBasicBlock(f.C, cname) - return -} -func InsertBasicBlock(ref BasicBlock, name string) (bb BasicBlock) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - bb.C = C.LLVMInsertBasicBlock(ref.C, cname) - return -} -func (bb BasicBlock) EraseFromParent() { C.LLVMDeleteBasicBlock(bb.C) } -func (bb BasicBlock) MoveBefore(pos BasicBlock) { C.LLVMMoveBasicBlockBefore(bb.C, pos.C) } -func (bb BasicBlock) MoveAfter(pos BasicBlock) { C.LLVMMoveBasicBlockAfter(bb.C, pos.C) } - -// Operations on instructions -func (v Value) EraseFromParentAsInstruction() { C.LLVMInstructionEraseFromParent(v.C) } -func (v Value) RemoveFromParentAsInstruction() { C.LLVMInstructionRemoveFromParent(v.C) } -func (v Value) InstructionParent() (bb BasicBlock) { bb.C = C.LLVMGetInstructionParent(v.C); return } -func (v Value) InstructionDebugLoc() (md Metadata) { md.C = C.LLVMInstructionGetDebugLoc(v.C); return } -func (v Value) InstructionSetDebugLoc(md Metadata) { C.LLVMInstructionSetDebugLoc(v.C, md.C) } -func (bb BasicBlock) FirstInstruction() (v Value) { v.C = C.LLVMGetFirstInstruction(bb.C); return } -func (bb BasicBlock) LastInstruction() (v Value) { v.C = C.LLVMGetLastInstruction(bb.C); return } -func NextInstruction(v Value) (rv Value) { rv.C = C.LLVMGetNextInstruction(v.C); return } -func PrevInstruction(v Value) (rv Value) { rv.C = C.LLVMGetPreviousInstruction(v.C); return } - -// Operations on call sites -func (v Value) SetInstructionCallConv(cc CallConv) { - C.LLVMSetInstructionCallConv(v.C, C.unsigned(cc)) -} -func (v Value) InstructionCallConv() CallConv { - return CallConv(C.LLVMCallConv(C.LLVMGetInstructionCallConv(v.C))) -} -func (v Value) AddCallSiteAttribute(i int, a Attribute) { - C.LLVMAddCallSiteAttribute(v.C, C.LLVMAttributeIndex(i), a.C) -} -func (v Value) SetInstrParamAlignment(i int, align int) { - C.LLVMSetInstrParamAlignment(v.C, C.unsigned(i), C.unsigned(align)) -} -func (v Value) CalledValue() (rv Value) { - rv.C = C.LLVMGetCalledValue(v.C) - return -} - -// Operations on call instructions (only) -func (v Value) IsTailCall() bool { return C.LLVMIsTailCall(v.C) != 0 } -func (v Value) SetTailCall(is bool) { C.LLVMSetTailCall(v.C, boolToLLVMBool(is)) } - -// Operations on phi nodes -func (v Value) AddIncoming(vals []Value, blocks []BasicBlock) { - ptr, nvals := llvmValueRefs(vals) - C.LLVMAddIncoming(v.C, ptr, llvmBasicBlockRefPtr(&blocks[0]), nvals) -} -func (v Value) IncomingCount() int { return int(C.LLVMCountIncoming(v.C)) } -func (v Value) IncomingValue(i int) (rv Value) { - rv.C = C.LLVMGetIncomingValue(v.C, C.unsigned(i)) - return -} -func (v Value) IncomingBlock(i int) (bb BasicBlock) { - bb.C = C.LLVMGetIncomingBlock(v.C, C.unsigned(i)) - return -} - -// Operations on inline assembly -func InlineAsm(t Type, asmString, constraints string, hasSideEffects, isAlignStack bool, dialect InlineAsmDialect, canThrow bool) (rv Value) { - casm := C.CString(asmString) - defer C.free(unsafe.Pointer(casm)) - cconstraints := C.CString(constraints) - defer C.free(unsafe.Pointer(cconstraints)) - rv.C = C.LLVMGetInlineAsm(t.C, casm, C.size_t(len(asmString)), cconstraints, C.size_t(len(constraints)), boolToLLVMBool(hasSideEffects), boolToLLVMBool(isAlignStack), C.LLVMInlineAsmDialect(dialect), boolToLLVMBool(canThrow)) - return -} - -// Operations on aggregates -func (v Value) Indices() []uint32 { - num := C.LLVMGetNumIndices(v.C) - indicesPtr := C.LLVMGetIndices(v.C) - // https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices - rawIndices := (*[1 << 20]C.uint)(unsafe.Pointer(indicesPtr))[:num:num] - indices := make([]uint32, num) - for i := range indices { - indices[i] = uint32(rawIndices[i]) - } - return indices -} - -// Operations on comparisons -func (v Value) IntPredicate() IntPredicate { return IntPredicate(C.LLVMGetICmpPredicate(v.C)) } -func (v Value) FloatPredicate() FloatPredicate { return FloatPredicate(C.LLVMGetFCmpPredicate(v.C)) } - -//------------------------------------------------------------------------- -// llvm.Builder -//------------------------------------------------------------------------- - -// An instruction builder represents a point within a basic block, and is the -// exclusive means of building instructions using the C interface. - -func (c Context) NewBuilder() (b Builder) { b.C = C.LLVMCreateBuilderInContext(c.C); return } -func NewBuilder() (b Builder) { b.C = C.LLVMCreateBuilder(); return } -func (b Builder) SetInsertPoint(block BasicBlock, instr Value) { - C.LLVMPositionBuilder(b.C, block.C, instr.C) -} -func (b Builder) SetInsertPointBefore(instr Value) { C.LLVMPositionBuilderBefore(b.C, instr.C) } -func (b Builder) SetInsertPointAtEnd(block BasicBlock) { C.LLVMPositionBuilderAtEnd(b.C, block.C) } -func (b Builder) GetInsertBlock() (bb BasicBlock) { bb.C = C.LLVMGetInsertBlock(b.C); return } -func (b Builder) ClearInsertionPoint() { C.LLVMClearInsertionPosition(b.C) } -func (b Builder) Insert(instr Value) { C.LLVMInsertIntoBuilder(b.C, instr.C) } -func (b Builder) InsertWithName(instr Value, name string) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.LLVMInsertIntoBuilderWithName(b.C, instr.C, cname) -} -func (b Builder) Dispose() { C.LLVMDisposeBuilder(b.C) } - -// Metadata -type DebugLoc struct { - Line, Col uint - Scope Metadata - InlinedAt Metadata -} - -func (b Builder) SetCurrentDebugLocation(line, col uint, scope, inlinedAt Metadata) { - C.LLVMGoSetCurrentDebugLocation(b.C, C.unsigned(line), C.unsigned(col), scope.C, inlinedAt.C) -} - -// Get current debug location. Please do not call this function until setting debug location with SetCurrentDebugLocation() -func (b Builder) GetCurrentDebugLocation() (loc DebugLoc) { - md := C.LLVMGoGetCurrentDebugLocation(b.C) - loc.Line = uint(md.Line) - loc.Col = uint(md.Col) - loc.Scope = Metadata{C: md.Scope} - loc.InlinedAt = Metadata{C: md.InlinedAt} - return -} -func (b Builder) SetInstDebugLocation(v Value) { C.LLVMSetInstDebugLocation(b.C, v.C) } -func (b Builder) InsertDeclare(module Module, storage Value, md Value) Value { - f := module.NamedFunction("llvm.dbg.declare") - if f.IsNil() { - ftyp := FunctionType(VoidType(), []Type{storage.Type(), md.Type()}, false) - f = AddFunction(module, "llvm.dbg.declare", ftyp) - } - return b.CreateCall(f, []Value{storage, md}, "") -} - -// Terminators -func (b Builder) CreateRetVoid() (rv Value) { rv.C = C.LLVMBuildRetVoid(b.C); return } -func (b Builder) CreateRet(v Value) (rv Value) { rv.C = C.LLVMBuildRet(b.C, v.C); return } -func (b Builder) CreateAggregateRet(vs []Value) (rv Value) { - ptr, nvals := llvmValueRefs(vs) - rv.C = C.LLVMBuildAggregateRet(b.C, ptr, nvals) - return -} -func (b Builder) CreateBr(bb BasicBlock) (rv Value) { rv.C = C.LLVMBuildBr(b.C, bb.C); return } -func (b Builder) CreateCondBr(ifv Value, thenb, elseb BasicBlock) (rv Value) { - rv.C = C.LLVMBuildCondBr(b.C, ifv.C, thenb.C, elseb.C) - return -} -func (b Builder) CreateSwitch(v Value, elseb BasicBlock, numCases int) (rv Value) { - rv.C = C.LLVMBuildSwitch(b.C, v.C, elseb.C, C.unsigned(numCases)) - return -} -func (b Builder) CreateIndirectBr(addr Value, numDests int) (rv Value) { - rv.C = C.LLVMBuildIndirectBr(b.C, addr.C, C.unsigned(numDests)) - return -} -func (b Builder) CreateInvoke(fn Value, args []Value, then, catch BasicBlock, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - ptr, nvals := llvmValueRefs(args) - rv.C = C.LLVMBuildInvoke(b.C, fn.C, ptr, nvals, then.C, catch.C, cname) - return -} -func (b Builder) CreateUnreachable() (rv Value) { rv.C = C.LLVMBuildUnreachable(b.C); return } - -// Add a case to the switch instruction -func (v Value) AddCase(on Value, dest BasicBlock) { C.LLVMAddCase(v.C, on.C, dest.C) } - -// Add a destination to the indirectbr instruction -func (v Value) AddDest(dest BasicBlock) { C.LLVMAddDestination(v.C, dest.C) } - -// Arithmetic -func (b Builder) CreateAdd(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildAdd(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNSWAdd(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNSWAdd(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNUWAdd(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNUWAdd(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFAdd(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFAdd(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateSub(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSub(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNSWSub(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNSWSub(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNUWSub(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNUWSub(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFSub(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - v.C = C.LLVMBuildFSub(b.C, lhs.C, rhs.C, cname) - C.free(unsafe.Pointer(cname)) - return -} -func (b Builder) CreateMul(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildMul(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNSWMul(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNSWMul(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNUWMul(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildNUWMul(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFMul(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFMul(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateUDiv(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildUDiv(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateSDiv(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSDiv(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateExactSDiv(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildExactSDiv(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFDiv(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFDiv(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateURem(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildURem(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateSRem(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSRem(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFRem(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFRem(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateShl(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildShl(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateLShr(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildLShr(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateAShr(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildAShr(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateAnd(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildAnd(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateOr(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildOr(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateXor(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildXor(b.C, lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateBinOp(op Opcode, lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildBinOp(b.C, C.LLVMOpcode(op), lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateNeg(v Value, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - rv.C = C.LLVMBuildNeg(b.C, v.C, cname) - return -} -func (b Builder) CreateNSWNeg(v Value, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - rv.C = C.LLVMBuildNSWNeg(b.C, v.C, cname) - return -} -func (b Builder) CreateNUWNeg(v Value, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - rv.C = C.LLVMBuildNUWNeg(b.C, v.C, cname) - return -} -func (b Builder) CreateFNeg(v Value, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - rv.C = C.LLVMBuildFNeg(b.C, v.C, cname) - return -} -func (b Builder) CreateNot(v Value, name string) (rv Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - rv.C = C.LLVMBuildNot(b.C, v.C, cname) - return -} - -// Memory - -func (b Builder) CreateMalloc(t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildMalloc(b.C, t.C, cname) - return -} -func (b Builder) CreateArrayMalloc(t Type, val Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildArrayMalloc(b.C, t.C, val.C, cname) - return -} -func (b Builder) CreateAlloca(t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildAlloca(b.C, t.C, cname) - return -} -func (b Builder) CreateArrayAlloca(t Type, val Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildArrayAlloca(b.C, t.C, val.C, cname) - return -} -func (b Builder) CreateFree(p Value) (v Value) { - v.C = C.LLVMBuildFree(b.C, p.C) - return -} -func (b Builder) CreateLoad(p Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildLoad(b.C, p.C, cname) - return -} -func (b Builder) CreateStore(val Value, p Value) (v Value) { - v.C = C.LLVMBuildStore(b.C, val.C, p.C) - return -} -func (b Builder) CreateGEP(p Value, indices []Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - ptr, nvals := llvmValueRefs(indices) - v.C = C.LLVMBuildGEP(b.C, p.C, ptr, nvals, cname) - return -} -func (b Builder) CreateInBoundsGEP(p Value, indices []Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - ptr, nvals := llvmValueRefs(indices) - v.C = C.LLVMBuildInBoundsGEP(b.C, p.C, ptr, nvals, cname) - return -} -func (b Builder) CreateStructGEP(p Value, i int, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildStructGEP(b.C, p.C, C.unsigned(i), cname) - return -} -func (b Builder) CreateGlobalString(str, name string) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildGlobalString(b.C, cstr, cname) - return -} -func (b Builder) CreateGlobalStringPtr(str, name string) (v Value) { - cstr := C.CString(str) - defer C.free(unsafe.Pointer(cstr)) - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildGlobalStringPtr(b.C, cstr, cname) - return -} -func (b Builder) CreateAtomicRMW(op AtomicRMWBinOp, ptr, val Value, ordering AtomicOrdering, singleThread bool) (v Value) { - v.C = C.LLVMBuildAtomicRMW(b.C, C.LLVMAtomicRMWBinOp(op), ptr.C, val.C, C.LLVMAtomicOrdering(ordering), boolToLLVMBool(singleThread)) - return -} -func (b Builder) CreateAtomicCmpXchg(ptr, cmp, newVal Value, successOrdering, failureOrdering AtomicOrdering, singleThread bool) (v Value) { - v.C = C.LLVMBuildAtomicCmpXchg(b.C, ptr.C, cmp.C, newVal.C, C.LLVMAtomicOrdering(successOrdering), C.LLVMAtomicOrdering(failureOrdering), boolToLLVMBool(singleThread)) - return -} - -// Casts -func (b Builder) CreateTrunc(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildTrunc(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateZExt(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildZExt(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateSExt(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSExt(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateFPToUI(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFPToUI(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateFPToSI(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFPToSI(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateUIToFP(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildUIToFP(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateSIToFP(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSIToFP(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateFPTrunc(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFPTrunc(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateFPExt(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFPExt(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreatePtrToInt(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildPtrToInt(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateIntToPtr(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildIntToPtr(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateBitCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildBitCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateZExtOrBitCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildZExtOrBitCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateSExtOrBitCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSExtOrBitCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateTruncOrBitCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildTruncOrBitCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateCast(val Value, op Opcode, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildCast(b.C, C.LLVMOpcode(op), val.C, t.C, cname) - return -} // -func (b Builder) CreatePointerCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildPointerCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateIntCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildIntCast(b.C, val.C, t.C, cname) - return -} -func (b Builder) CreateFPCast(val Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFPCast(b.C, val.C, t.C, cname) - return -} - -// Comparisons -func (b Builder) CreateICmp(pred IntPredicate, lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildICmp(b.C, C.LLVMIntPredicate(pred), lhs.C, rhs.C, cname) - return -} -func (b Builder) CreateFCmp(pred FloatPredicate, lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildFCmp(b.C, C.LLVMRealPredicate(pred), lhs.C, rhs.C, cname) - return -} - -// Miscellaneous instructions -func (b Builder) CreatePHI(t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildPhi(b.C, t.C, cname) - return -} -func (b Builder) CreateCall(fn Value, args []Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - ptr, nvals := llvmValueRefs(args) - v.C = C.LLVMBuildCall(b.C, fn.C, ptr, nvals, cname) - return -} - -func (b Builder) CreateSelect(ifv, thenv, elsev Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildSelect(b.C, ifv.C, thenv.C, elsev.C, cname) - return -} - -func (b Builder) CreateVAArg(list Value, t Type, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildVAArg(b.C, list.C, t.C, cname) - return -} -func (b Builder) CreateExtractElement(vec, i Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildExtractElement(b.C, vec.C, i.C, cname) - return -} -func (b Builder) CreateInsertElement(vec, elt, i Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildInsertElement(b.C, vec.C, elt.C, i.C, cname) - return -} -func (b Builder) CreateShuffleVector(v1, v2, mask Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildShuffleVector(b.C, v1.C, v2.C, mask.C, cname) - return -} -func (b Builder) CreateExtractValue(agg Value, i int, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildExtractValue(b.C, agg.C, C.unsigned(i), cname) - return -} -func (b Builder) CreateInsertValue(agg, elt Value, i int, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildInsertValue(b.C, agg.C, elt.C, C.unsigned(i), cname) - return -} - -func (b Builder) CreateIsNull(val Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildIsNull(b.C, val.C, cname) - return -} -func (b Builder) CreateIsNotNull(val Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildIsNotNull(b.C, val.C, cname) - return -} -func (b Builder) CreatePtrDiff(lhs, rhs Value, name string) (v Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - v.C = C.LLVMBuildPtrDiff(b.C, lhs.C, rhs.C, cname) - return -} - -func (b Builder) CreateLandingPad(t Type, nclauses int, name string) (l Value) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - l.C = C.LLVMBuildLandingPad(b.C, t.C, nil, C.unsigned(nclauses), cname) - return l -} - -func (l Value) AddClause(v Value) { - C.LLVMAddClause(l.C, v.C) -} - -func (l Value) SetCleanup(cleanup bool) { - C.LLVMSetCleanup(l.C, boolToLLVMBool(cleanup)) -} - -func (b Builder) CreateResume(ex Value) (v Value) { - v.C = C.LLVMBuildResume(b.C, ex.C) - return -} - -//------------------------------------------------------------------------- -// llvm.ModuleProvider -//------------------------------------------------------------------------- - -// Changes the type of M so it can be passed to FunctionPassManagers and the -// JIT. They take ModuleProviders for historical reasons. -func NewModuleProviderForModule(m Module) (mp ModuleProvider) { - mp.C = C.LLVMCreateModuleProviderForExistingModule(m.C) - return -} - -// Destroys the module M. -func (mp ModuleProvider) Dispose() { C.LLVMDisposeModuleProvider(mp.C) } - -//------------------------------------------------------------------------- -// llvm.MemoryBuffer -//------------------------------------------------------------------------- - -func NewMemoryBufferFromFile(path string) (b MemoryBuffer, err error) { - var cmsg *C.char - cpath := C.CString(path) - defer C.free(unsafe.Pointer(cpath)) - fail := C.LLVMCreateMemoryBufferWithContentsOfFile(cpath, &b.C, &cmsg) - if fail != 0 { - b.C = nil - err = errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - } - return -} - -func NewMemoryBufferFromStdin() (b MemoryBuffer, err error) { - var cmsg *C.char - fail := C.LLVMCreateMemoryBufferWithSTDIN(&b.C, &cmsg) - if fail != 0 { - b.C = nil - err = errors.New(C.GoString(cmsg)) - C.LLVMDisposeMessage(cmsg) - } - return -} - -func (b MemoryBuffer) Bytes() []byte { - cstart := C.LLVMGetBufferStart(b.C) - csize := C.LLVMGetBufferSize(b.C) - return C.GoBytes(unsafe.Pointer(cstart), C.int(csize)) -} - -func (b MemoryBuffer) Dispose() { C.LLVMDisposeMemoryBuffer(b.C) } - -//------------------------------------------------------------------------- -// llvm.PassManager -//------------------------------------------------------------------------- - -// Constructs a new whole-module pass pipeline. This type of pipeline is -// suitable for link-time optimization and whole-module transformations. -// See llvm::PassManager::PassManager. -func NewPassManager() (pm PassManager) { pm.C = C.LLVMCreatePassManager(); return } - -// Constructs a new function-by-function pass pipeline over the module -// provider. It does not take ownership of the module provider. This type of -// pipeline is suitable for code generation and JIT compilation tasks. -// See llvm::FunctionPassManager::FunctionPassManager. -func NewFunctionPassManagerForModule(m Module) (pm PassManager) { - pm.C = C.LLVMCreateFunctionPassManagerForModule(m.C) - return -} - -// Initializes, executes on the provided module, and finalizes all of the -// passes scheduled in the pass manager. Returns 1 if any of the passes -// modified the module, 0 otherwise. See llvm::PassManager::run(Module&). -func (pm PassManager) Run(m Module) bool { return C.LLVMRunPassManager(pm.C, m.C) != 0 } - -// Initializes all of the function passes scheduled in the function pass -// manager. Returns 1 if any of the passes modified the module, 0 otherwise. -// See llvm::FunctionPassManager::doInitialization. -func (pm PassManager) InitializeFunc() bool { return C.LLVMInitializeFunctionPassManager(pm.C) != 0 } - -// Executes all of the function passes scheduled in the function pass manager -// on the provided function. Returns 1 if any of the passes modified the -// function, false otherwise. -// See llvm::FunctionPassManager::run(Function&). -func (pm PassManager) RunFunc(f Value) bool { return C.LLVMRunFunctionPassManager(pm.C, f.C) != 0 } - -// Finalizes all of the function passes scheduled in the function pass -// manager. Returns 1 if any of the passes modified the module, 0 otherwise. -// See llvm::FunctionPassManager::doFinalization. -func (pm PassManager) FinalizeFunc() bool { return C.LLVMFinalizeFunctionPassManager(pm.C) != 0 } - -// Frees the memory of a pass pipeline. For function pipelines, does not free -// the module provider. -// See llvm::PassManagerBase::~PassManagerBase. -func (pm PassManager) Dispose() { C.LLVMDisposePassManager(pm.C) } diff --git a/interpreter/llvm/src/bindings/go/llvm/ir_test.go b/interpreter/llvm/src/bindings/go/llvm/ir_test.go deleted file mode 100644 index 71c47d94a0ecf..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/ir_test.go +++ /dev/null @@ -1,164 +0,0 @@ -//===- ir_test.go - Tests for ir ------------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file tests bindings for the ir component. -// -//===----------------------------------------------------------------------===// - -package llvm - -import ( - "strings" - "testing" -) - -func testAttribute(t *testing.T, name string) { - mod := NewModule("") - defer mod.Dispose() - - ftyp := FunctionType(VoidType(), nil, false) - fn := AddFunction(mod, "foo", ftyp) - - kind := AttributeKindID(name) - attr := mod.Context().CreateEnumAttribute(kind, 0) - - fn.AddFunctionAttr(attr) - newattr := fn.GetEnumFunctionAttribute(kind) - if attr != newattr { - t.Errorf("got attribute %p, want %p", newattr.C, attr.C) - } - - text := mod.String() - if !strings.Contains(text, " "+name+" ") { - t.Errorf("expected attribute '%s', got:\n%s", name, text) - } - - fn.RemoveEnumFunctionAttribute(kind) - newattr = fn.GetEnumFunctionAttribute(kind) - if !newattr.IsNil() { - t.Errorf("got attribute %p, want 0", newattr.C) - } -} - -func TestAttributes(t *testing.T) { - // Tests that our attribute constants haven't drifted from LLVM's. - attrTests := []string{ - "sanitize_address", - "alwaysinline", - "builtin", - "convergent", - "inlinehint", - "inreg", - "jumptable", - "minsize", - "naked", - "nest", - "noalias", - "nobuiltin", - "nocapture", - "noduplicate", - "noimplicitfloat", - "noinline", - "nonlazybind", - "nonnull", - "noredzone", - "noreturn", - "nounwind", - "nosanitize_coverage", - "optnone", - "optsize", - "readnone", - "readonly", - "returned", - "returns_twice", - "signext", - "safestack", - "ssp", - "sspreq", - "sspstrong", - "sanitize_thread", - "sanitize_memory", - "uwtable", - "zeroext", - "cold", - "nocf_check", - } - - for _, name := range attrTests { - testAttribute(t, name) - } -} - -func TestDebugLoc(t *testing.T) { - mod := NewModule("") - defer mod.Dispose() - - ctx := mod.Context() - - b := ctx.NewBuilder() - defer b.Dispose() - - d := NewDIBuilder(mod) - defer func() { - d.Destroy() - }() - file := d.CreateFile("dummy_file", "dummy_dir") - voidInfo := d.CreateBasicType(DIBasicType{Name: "void"}) - typeInfo := d.CreateSubroutineType(DISubroutineType{ - File: file, - Parameters: []Metadata{voidInfo}, - Flags: 0, - }) - scope := d.CreateFunction(file, DIFunction{ - Name: "foo", - LinkageName: "foo", - Line: 10, - ScopeLine: 10, - Type: typeInfo, - File: file, - IsDefinition: true, - }) - - b.SetCurrentDebugLocation(10, 20, scope, Metadata{}) - loc := b.GetCurrentDebugLocation() - if loc.Line != 10 { - t.Errorf("Got line %d, though wanted 10", loc.Line) - } - if loc.Col != 20 { - t.Errorf("Got column %d, though wanted 20", loc.Col) - } - if loc.Scope.C != scope.C { - t.Errorf("Got metadata %v as scope, though wanted %v", loc.Scope.C, scope.C) - } -} - -func TestSubtypes(t *testing.T) { - cont := NewContext() - defer cont.Dispose() - - int_pointer := PointerType(cont.Int32Type(), 0) - int_inner := int_pointer.Subtypes() - if len(int_inner) != 1 { - t.Errorf("Got size %d, though wanted 1", len(int_inner)) - } - if int_inner[0] != cont.Int32Type() { - t.Errorf("Expected int32 type") - } - - st_pointer := cont.StructType([]Type{cont.Int32Type(), cont.Int8Type()}, false) - st_inner := st_pointer.Subtypes() - if len(st_inner) != 2 { - t.Errorf("Got size %d, though wanted 2", len(int_inner)) - } - if st_inner[0] != cont.Int32Type() { - t.Errorf("Expected first struct field to be int32") - } - if st_inner[1] != cont.Int8Type() { - t.Errorf("Expected second struct field to be int8") - } -} diff --git a/interpreter/llvm/src/bindings/go/llvm/linker.go b/interpreter/llvm/src/bindings/go/llvm/linker.go deleted file mode 100644 index 8e2e953fd4651..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/linker.go +++ /dev/null @@ -1,30 +0,0 @@ -//===- linker.go - Bindings for linker ------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the linker component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Core.h" -#include "llvm-c/Linker.h" -#include -*/ -import "C" -import "errors" - -func LinkModules(Dest, Src Module) error { - failed := C.LLVMLinkModules2(Dest.C, Src.C) - if failed != 0 { - err := errors.New("Linking failed") - return err - } - return nil -} diff --git a/interpreter/llvm/src/bindings/go/llvm/llvm_config.go.in b/interpreter/llvm/src/bindings/go/llvm/llvm_config.go.in deleted file mode 100644 index 4c63ed10cfb77..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/llvm_config.go.in +++ /dev/null @@ -1,12 +0,0 @@ -// +build !byollvm - -package llvm - -/* -#cgo CXXFLAGS: -std=c++14 -#cgo CPPFLAGS: @LLVM_CFLAGS@ -#cgo LDFLAGS: @LLVM_LDFLAGS@ -*/ -import "C" - -type (run_build_sh int) diff --git a/interpreter/llvm/src/bindings/go/llvm/llvm_dep.go b/interpreter/llvm/src/bindings/go/llvm/llvm_dep.go deleted file mode 100644 index 9484e6ddf879e..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/llvm_dep.go +++ /dev/null @@ -1,18 +0,0 @@ -//===- llvm_dep.go - creates LLVM dependency ------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file ensures that the LLVM libraries are built before using the -// bindings. -// -//===----------------------------------------------------------------------===// - -// +build !byollvm - -package llvm - -var _ run_build_sh diff --git a/interpreter/llvm/src/bindings/go/llvm/string.go b/interpreter/llvm/src/bindings/go/llvm/string.go deleted file mode 100644 index 7c8bf8da5b36c..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/string.go +++ /dev/null @@ -1,106 +0,0 @@ -//===- string.go - Stringer implementation for Type -----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements the Stringer interface for the Type type. -// -//===----------------------------------------------------------------------===// - -package llvm - -import "fmt" - -func (t TypeKind) String() string { - switch t { - case VoidTypeKind: - return "VoidTypeKind" - case FloatTypeKind: - return "FloatTypeKind" - case DoubleTypeKind: - return "DoubleTypeKind" - case X86_FP80TypeKind: - return "X86_FP80TypeKind" - case FP128TypeKind: - return "FP128TypeKind" - case PPC_FP128TypeKind: - return "PPC_FP128TypeKind" - case LabelTypeKind: - return "LabelTypeKind" - case IntegerTypeKind: - return "IntegerTypeKind" - case FunctionTypeKind: - return "FunctionTypeKind" - case StructTypeKind: - return "StructTypeKind" - case ArrayTypeKind: - return "ArrayTypeKind" - case PointerTypeKind: - return "PointerTypeKind" - case MetadataTypeKind: - return "MetadataTypeKind" - case VectorTypeKind: - return "VectorTypeKind" - case ScalableVectorTypeKind: - return "ScalableVectorTypeKind" - } - panic("unreachable") -} - -func (t Type) String() string { - ts := typeStringer{s: make(map[Type]string)} - return ts.typeString(t) -} - -type typeStringer struct { - s map[Type]string -} - -func (ts *typeStringer) typeString(t Type) string { - if s, ok := ts.s[t]; ok { - return s - } - - k := t.TypeKind() - s := k.String() - s = s[:len(s)-len("Kind")] - - switch k { - case ArrayTypeKind: - s += fmt.Sprintf("(%v[%v])", ts.typeString(t.ElementType()), t.ArrayLength()) - case PointerTypeKind: - s += fmt.Sprintf("(%v)", ts.typeString(t.ElementType())) - case FunctionTypeKind: - params := t.ParamTypes() - s += "(" - if len(params) > 0 { - s += fmt.Sprintf("%v", ts.typeString(params[0])) - for i := 1; i < len(params); i++ { - s += fmt.Sprintf(", %v", ts.typeString(params[i])) - } - } - s += fmt.Sprintf("):%v", ts.typeString(t.ReturnType())) - case StructTypeKind: - if name := t.StructName(); name != "" { - ts.s[t] = "%" + name - s = fmt.Sprintf("%%%s: %s", name, s) - } - etypes := t.StructElementTypes() - s += "(" - if n := len(etypes); n > 0 { - s += ts.typeString(etypes[0]) - for i := 1; i < n; i++ { - s += fmt.Sprintf(", %v", ts.typeString(etypes[i])) - } - } - s += ")" - case IntegerTypeKind: - s += fmt.Sprintf("(%d bits)", t.IntTypeWidth()) - } - - ts.s[t] = s - return s -} diff --git a/interpreter/llvm/src/bindings/go/llvm/string_test.go b/interpreter/llvm/src/bindings/go/llvm/string_test.go deleted file mode 100644 index 56cbc9f3e7fd0..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/string_test.go +++ /dev/null @@ -1,27 +0,0 @@ -//===- string_test.go - test Stringer implementation for Type -------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file tests the Stringer interface for the Type type. -// -//===----------------------------------------------------------------------===// - -package llvm - -import ( - "testing" -) - -func TestStringRecursiveType(t *testing.T) { - ctx := NewContext() - defer ctx.Dispose() - s := ctx.StructCreateNamed("recursive") - s.StructSetBody([]Type{s, s}, false) - if str := s.String(); str != "%recursive: StructType(%recursive, %recursive)" { - t.Errorf("incorrect string result %q", str) - } -} diff --git a/interpreter/llvm/src/bindings/go/llvm/support.go b/interpreter/llvm/src/bindings/go/llvm/support.go deleted file mode 100644 index 8a663fee502a5..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/support.go +++ /dev/null @@ -1,53 +0,0 @@ -//===- support.go - Bindings for support ----------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the support component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Support.h" -#include "SupportBindings.h" -#include -*/ -import "C" - -import ( - "errors" - "unsafe" -) - -// Loads a dynamic library such that it may be used as an LLVM plugin. -// See llvm::sys::DynamicLibrary::LoadLibraryPermanently. -func LoadLibraryPermanently(lib string) error { - var errstr *C.char - libstr := C.CString(lib) - defer C.free(unsafe.Pointer(libstr)) - C.LLVMLoadLibraryPermanently2(libstr, &errstr) - if errstr != nil { - err := errors.New(C.GoString(errstr)) - C.free(unsafe.Pointer(errstr)) - return err - } - return nil -} - -// Parse the given arguments using the LLVM command line parser. -// See llvm::cl::ParseCommandLineOptions. -func ParseCommandLineOptions(args []string, overview string) { - argstrs := make([]*C.char, len(args)) - for i, arg := range args { - argstrs[i] = C.CString(arg) - defer C.free(unsafe.Pointer(argstrs[i])) - } - overviewstr := C.CString(overview) - defer C.free(unsafe.Pointer(overviewstr)) - C.LLVMParseCommandLineOptions(C.int(len(args)), &argstrs[0], overviewstr) -} diff --git a/interpreter/llvm/src/bindings/go/llvm/target.go b/interpreter/llvm/src/bindings/go/llvm/target.go deleted file mode 100644 index cdd0fa30c3f5f..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/target.go +++ /dev/null @@ -1,296 +0,0 @@ -//===- target.go - Bindings for target ------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the target component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Core.h" -#include "llvm-c/Target.h" -#include "llvm-c/TargetMachine.h" -#include -*/ -import "C" -import "unsafe" -import "errors" - -type ( - TargetData struct { - C C.LLVMTargetDataRef - } - Target struct { - C C.LLVMTargetRef - } - TargetMachine struct { - C C.LLVMTargetMachineRef - } - ByteOrdering C.enum_LLVMByteOrdering - RelocMode C.LLVMRelocMode - CodeGenOptLevel C.LLVMCodeGenOptLevel - CodeGenFileType C.LLVMCodeGenFileType - CodeModel C.LLVMCodeModel -) - -const ( - BigEndian ByteOrdering = C.LLVMBigEndian - LittleEndian ByteOrdering = C.LLVMLittleEndian -) - -const ( - RelocDefault RelocMode = C.LLVMRelocDefault - RelocStatic RelocMode = C.LLVMRelocStatic - RelocPIC RelocMode = C.LLVMRelocPIC - RelocDynamicNoPic RelocMode = C.LLVMRelocDynamicNoPic -) - -const ( - CodeGenLevelNone CodeGenOptLevel = C.LLVMCodeGenLevelNone - CodeGenLevelLess CodeGenOptLevel = C.LLVMCodeGenLevelLess - CodeGenLevelDefault CodeGenOptLevel = C.LLVMCodeGenLevelDefault - CodeGenLevelAggressive CodeGenOptLevel = C.LLVMCodeGenLevelAggressive -) - -const ( - CodeModelDefault CodeModel = C.LLVMCodeModelDefault - CodeModelJITDefault CodeModel = C.LLVMCodeModelJITDefault - CodeModelTiny CodeModel = C.LLVMCodeModelTiny - CodeModelSmall CodeModel = C.LLVMCodeModelSmall - CodeModelKernel CodeModel = C.LLVMCodeModelKernel - CodeModelMedium CodeModel = C.LLVMCodeModelMedium - CodeModelLarge CodeModel = C.LLVMCodeModelLarge -) - -const ( - AssemblyFile CodeGenFileType = C.LLVMAssemblyFile - ObjectFile CodeGenFileType = C.LLVMObjectFile -) - -// InitializeAllTargetInfos - The main program should call this function if it -// wants access to all available targets that LLVM is configured to support. -func InitializeAllTargetInfos() { C.LLVMInitializeAllTargetInfos() } - -// InitializeAllTargets - The main program should call this function if it wants -// to link in all available targets that LLVM is configured to support. -func InitializeAllTargets() { C.LLVMInitializeAllTargets() } - -func InitializeAllTargetMCs() { C.LLVMInitializeAllTargetMCs() } - -func InitializeAllAsmParsers() { C.LLVMInitializeAllAsmParsers() } - -func InitializeAllAsmPrinters() { C.LLVMInitializeAllAsmPrinters() } - -var initializeNativeTargetError = errors.New("Failed to initialize native target") - -// InitializeNativeTarget - The main program should call this function to -// initialize the native target corresponding to the host. This is useful -// for JIT applications to ensure that the target gets linked in correctly. -func InitializeNativeTarget() error { - fail := C.LLVMInitializeNativeTarget() - if fail != 0 { - return initializeNativeTargetError - } - return nil -} - -func InitializeNativeAsmPrinter() error { - fail := C.LLVMInitializeNativeAsmPrinter() - if fail != 0 { - return initializeNativeTargetError - } - return nil -} - -//------------------------------------------------------------------------- -// llvm.TargetData -//------------------------------------------------------------------------- - -// Creates target data from a target layout string. -// See the constructor llvm::TargetData::TargetData. -func NewTargetData(rep string) (td TargetData) { - crep := C.CString(rep) - defer C.free(unsafe.Pointer(crep)) - td.C = C.LLVMCreateTargetData(crep) - return -} - -// Converts target data to a target layout string. The string must be disposed -// with LLVMDisposeMessage. -// See the constructor llvm::TargetData::TargetData. -func (td TargetData) String() (s string) { - cmsg := C.LLVMCopyStringRepOfTargetData(td.C) - s = C.GoString(cmsg) - C.LLVMDisposeMessage(cmsg) - return -} - -// Returns the byte order of a target, either BigEndian or LittleEndian. -// See the method llvm::TargetData::isLittleEndian. -func (td TargetData) ByteOrder() ByteOrdering { return ByteOrdering(C.LLVMByteOrder(td.C)) } - -// Returns the pointer size in bytes for a target. -// See the method llvm::TargetData::getPointerSize. -func (td TargetData) PointerSize() int { return int(C.LLVMPointerSize(td.C)) } - -// Returns the integer type that is the same size as a pointer on a target. -// See the method llvm::TargetData::getIntPtrType. -func (td TargetData) IntPtrType() (t Type) { t.C = C.LLVMIntPtrType(td.C); return } - -// Computes the size of a type in bytes for a target. -// See the method llvm::TargetData::getTypeSizeInBits. -func (td TargetData) TypeSizeInBits(t Type) uint64 { - return uint64(C.LLVMSizeOfTypeInBits(td.C, t.C)) -} - -// Computes the storage size of a type in bytes for a target. -// See the method llvm::TargetData::getTypeStoreSize. -func (td TargetData) TypeStoreSize(t Type) uint64 { - return uint64(C.LLVMStoreSizeOfType(td.C, t.C)) -} - -// Computes the ABI size of a type in bytes for a target. -// See the method llvm::TargetData::getTypeAllocSize. -func (td TargetData) TypeAllocSize(t Type) uint64 { - return uint64(C.LLVMABISizeOfType(td.C, t.C)) -} - -// Computes the ABI alignment of a type in bytes for a target. -// See the method llvm::TargetData::getABITypeAlignment. -func (td TargetData) ABITypeAlignment(t Type) int { - return int(C.LLVMABIAlignmentOfType(td.C, t.C)) -} - -// Computes the call frame alignment of a type in bytes for a target. -// See the method llvm::TargetData::getCallFrameTypeAlignment. -func (td TargetData) CallFrameTypeAlignment(t Type) int { - return int(C.LLVMCallFrameAlignmentOfType(td.C, t.C)) -} - -// Computes the preferred alignment of a type in bytes for a target. -// See the method llvm::TargetData::getPrefTypeAlignment. -func (td TargetData) PrefTypeAlignment(t Type) int { - return int(C.LLVMPreferredAlignmentOfType(td.C, t.C)) -} - -// Computes the preferred alignment of a global variable in bytes for a target. -// See the method llvm::TargetData::getPreferredAlignment. -func (td TargetData) PreferredAlignment(g Value) int { - return int(C.LLVMPreferredAlignmentOfGlobal(td.C, g.C)) -} - -// Computes the structure element that contains the byte offset for a target. -// See the method llvm::StructLayout::getElementContainingOffset. -func (td TargetData) ElementContainingOffset(t Type, offset uint64) int { - return int(C.LLVMElementAtOffset(td.C, t.C, C.ulonglong(offset))) -} - -// Computes the byte offset of the indexed struct element for a target. -// See the method llvm::StructLayout::getElementOffset. -func (td TargetData) ElementOffset(t Type, element int) uint64 { - return uint64(C.LLVMOffsetOfElement(td.C, t.C, C.unsigned(element))) -} - -// Deallocates a TargetData. -// See the destructor llvm::TargetData::~TargetData. -func (td TargetData) Dispose() { C.LLVMDisposeTargetData(td.C) } - -//------------------------------------------------------------------------- -// llvm.Target -//------------------------------------------------------------------------- - -func FirstTarget() Target { - return Target{C.LLVMGetFirstTarget()} -} - -func (t Target) NextTarget() Target { - return Target{C.LLVMGetNextTarget(t.C)} -} - -func GetTargetFromTriple(triple string) (t Target, err error) { - var errstr *C.char - ctriple := C.CString(triple) - defer C.free(unsafe.Pointer(ctriple)) - fail := C.LLVMGetTargetFromTriple(ctriple, &t.C, &errstr) - if fail != 0 { - err = errors.New(C.GoString(errstr)) - C.free(unsafe.Pointer(errstr)) - } - return -} - -func (t Target) Name() string { - return C.GoString(C.LLVMGetTargetName(t.C)) -} - -func (t Target) Description() string { - return C.GoString(C.LLVMGetTargetDescription(t.C)) -} - -//------------------------------------------------------------------------- -// llvm.TargetMachine -//------------------------------------------------------------------------- - -// CreateTargetMachine creates a new TargetMachine. -func (t Target) CreateTargetMachine(Triple string, CPU string, Features string, - Level CodeGenOptLevel, Reloc RelocMode, - CodeModel CodeModel) (tm TargetMachine) { - cTriple := C.CString(Triple) - defer C.free(unsafe.Pointer(cTriple)) - cCPU := C.CString(CPU) - defer C.free(unsafe.Pointer(cCPU)) - cFeatures := C.CString(Features) - defer C.free(unsafe.Pointer(cFeatures)) - tm.C = C.LLVMCreateTargetMachine(t.C, cTriple, cCPU, cFeatures, - C.LLVMCodeGenOptLevel(Level), - C.LLVMRelocMode(Reloc), - C.LLVMCodeModel(CodeModel)) - return -} - -// CreateTargetData returns a new TargetData describing the TargetMachine's -// data layout. The returned TargetData is owned by the caller, who is -// responsible for disposing of it by calling the TargetData.Dispose method. -func (tm TargetMachine) CreateTargetData() TargetData { - return TargetData{C.LLVMCreateTargetDataLayout(tm.C)} -} - -// Triple returns the triple describing the machine (arch-vendor-os). -func (tm TargetMachine) Triple() string { - cstr := C.LLVMGetTargetMachineTriple(tm.C) - return C.GoString(cstr) -} - -func (tm TargetMachine) EmitToMemoryBuffer(m Module, ft CodeGenFileType) (MemoryBuffer, error) { - var errstr *C.char - var mb MemoryBuffer - fail := C.LLVMTargetMachineEmitToMemoryBuffer(tm.C, m.C, C.LLVMCodeGenFileType(ft), &errstr, &mb.C) - if fail != 0 { - err := errors.New(C.GoString(errstr)) - C.free(unsafe.Pointer(errstr)) - return MemoryBuffer{}, err - } - return mb, nil -} - -func (tm TargetMachine) AddAnalysisPasses(pm PassManager) { - C.LLVMAddAnalysisPasses(tm.C, pm.C) -} - -// Dispose releases resources related to the TargetMachine. -func (tm TargetMachine) Dispose() { - C.LLVMDisposeTargetMachine(tm.C) -} - -func DefaultTargetTriple() (triple string) { - cTriple := C.LLVMGetDefaultTargetTriple() - defer C.free(unsafe.Pointer(cTriple)) - triple = C.GoString(cTriple) - return -} diff --git a/interpreter/llvm/src/bindings/go/llvm/transforms_coroutines.go b/interpreter/llvm/src/bindings/go/llvm/transforms_coroutines.go deleted file mode 100644 index c18c3fe936c1e..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/transforms_coroutines.go +++ /dev/null @@ -1,23 +0,0 @@ -//===- transforms_coroutines.go - Bindings for coroutines -----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the coroutines component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Transforms/Coroutines.h" -*/ -import "C" - -func (pm PassManager) AddCoroEarlyPass() { C.LLVMAddCoroEarlyPass(pm.C) } -func (pm PassManager) AddCoroSplitPass() { C.LLVMAddCoroSplitPass(pm.C) } -func (pm PassManager) AddCoroElidePass() { C.LLVMAddCoroElidePass(pm.C) } -func (pm PassManager) AddCoroCleanupPass() { C.LLVMAddCoroCleanupPass(pm.C) } diff --git a/interpreter/llvm/src/bindings/go/llvm/transforms_instrumentation.go b/interpreter/llvm/src/bindings/go/llvm/transforms_instrumentation.go deleted file mode 100644 index 68e0ed6967979..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/transforms_instrumentation.go +++ /dev/null @@ -1,45 +0,0 @@ -//===- transforms_instrumentation.go - Bindings for instrumentation -------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the instrumentation component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "InstrumentationBindings.h" -#include -*/ -import "C" -import "unsafe" - -func (pm PassManager) AddAddressSanitizerFunctionPass() { - C.LLVMAddAddressSanitizerFunctionPass(pm.C) -} - -func (pm PassManager) AddAddressSanitizerModulePass() { - C.LLVMAddAddressSanitizerModulePass(pm.C) -} - -func (pm PassManager) AddThreadSanitizerPass() { - C.LLVMAddThreadSanitizerPass(pm.C) -} - -func (pm PassManager) AddMemorySanitizerLegacyPassPass() { - C.LLVMAddMemorySanitizerLegacyPassPass(pm.C) -} - -func (pm PassManager) AddDataFlowSanitizerPass(abilist []string) { - abiliststrs := make([]*C.char, len(abilist)) - for i, arg := range abilist { - abiliststrs[i] = C.CString(arg) - defer C.free(unsafe.Pointer(abiliststrs[i])) - } - C.LLVMAddDataFlowSanitizerPass(pm.C, C.int(len(abilist)), &abiliststrs[0]) -} diff --git a/interpreter/llvm/src/bindings/go/llvm/transforms_ipo.go b/interpreter/llvm/src/bindings/go/llvm/transforms_ipo.go deleted file mode 100644 index 8a158f208bef4..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/transforms_ipo.go +++ /dev/null @@ -1,40 +0,0 @@ -//===- transforms_ipo.go - Bindings for ipo -------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the ipo component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Transforms/IPO.h" -*/ -import "C" - -// helpers -func boolToUnsigned(b bool) C.unsigned { - if b { - return 1 - } - return 0 -} - -func (pm PassManager) AddArgumentPromotionPass() { C.LLVMAddArgumentPromotionPass(pm.C) } -func (pm PassManager) AddConstantMergePass() { C.LLVMAddConstantMergePass(pm.C) } -func (pm PassManager) AddDeadArgEliminationPass() { C.LLVMAddDeadArgEliminationPass(pm.C) } -func (pm PassManager) AddFunctionAttrsPass() { C.LLVMAddFunctionAttrsPass(pm.C) } -func (pm PassManager) AddFunctionInliningPass() { C.LLVMAddFunctionInliningPass(pm.C) } -func (pm PassManager) AddGlobalDCEPass() { C.LLVMAddGlobalDCEPass(pm.C) } -func (pm PassManager) AddGlobalOptimizerPass() { C.LLVMAddGlobalOptimizerPass(pm.C) } -func (pm PassManager) AddPruneEHPass() { C.LLVMAddPruneEHPass(pm.C) } -func (pm PassManager) AddIPSCCPPass() { C.LLVMAddIPSCCPPass(pm.C) } -func (pm PassManager) AddInternalizePass(allButMain bool) { - C.LLVMAddInternalizePass(pm.C, boolToUnsigned(allButMain)) -} -func (pm PassManager) AddStripDeadPrototypesPass() { C.LLVMAddStripDeadPrototypesPass(pm.C) } diff --git a/interpreter/llvm/src/bindings/go/llvm/transforms_pmbuilder.go b/interpreter/llvm/src/bindings/go/llvm/transforms_pmbuilder.go deleted file mode 100644 index badd148c195da..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/transforms_pmbuilder.go +++ /dev/null @@ -1,72 +0,0 @@ -//===- transforms_pmbuilder.go - Bindings for PassManagerBuilder ----------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the PassManagerBuilder class. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Transforms/PassManagerBuilder.h" -#include "llvm-c/Transforms/Coroutines.h" -*/ -import "C" - -type PassManagerBuilder struct { - C C.LLVMPassManagerBuilderRef -} - -func NewPassManagerBuilder() (pmb PassManagerBuilder) { - pmb.C = C.LLVMPassManagerBuilderCreate() - return -} - -func (pmb PassManagerBuilder) SetOptLevel(level int) { - C.LLVMPassManagerBuilderSetOptLevel(pmb.C, C.uint(level)) -} - -func (pmb PassManagerBuilder) SetSizeLevel(level int) { - C.LLVMPassManagerBuilderSetSizeLevel(pmb.C, C.uint(level)) -} - -func (pmb PassManagerBuilder) Populate(pm PassManager) { - C.LLVMPassManagerBuilderPopulateModulePassManager(pmb.C, pm.C) -} - -func (pmb PassManagerBuilder) PopulateFunc(pm PassManager) { - C.LLVMPassManagerBuilderPopulateFunctionPassManager(pmb.C, pm.C) -} - -func (pmb PassManagerBuilder) PopulateLTOPassManager(pm PassManager, internalize bool, runInliner bool) { - C.LLVMPassManagerBuilderPopulateLTOPassManager(pmb.C, pm.C, boolToLLVMBool(internalize), boolToLLVMBool(runInliner)) -} - -func (pmb PassManagerBuilder) Dispose() { - C.LLVMPassManagerBuilderDispose(pmb.C) -} - -func (pmb PassManagerBuilder) SetDisableUnitAtATime(val bool) { - C.LLVMPassManagerBuilderSetDisableUnitAtATime(pmb.C, boolToLLVMBool(val)) -} - -func (pmb PassManagerBuilder) SetDisableUnrollLoops(val bool) { - C.LLVMPassManagerBuilderSetDisableUnrollLoops(pmb.C, boolToLLVMBool(val)) -} - -func (pmb PassManagerBuilder) SetDisableSimplifyLibCalls(val bool) { - C.LLVMPassManagerBuilderSetDisableSimplifyLibCalls(pmb.C, boolToLLVMBool(val)) -} - -func (pmb PassManagerBuilder) UseInlinerWithThreshold(threshold uint) { - C.LLVMPassManagerBuilderUseInlinerWithThreshold(pmb.C, C.uint(threshold)) -} - -func (pmb PassManagerBuilder) AddCoroutinePassesToExtensionPoints() { - C.LLVMPassManagerBuilderAddCoroutinePassesToExtensionPoints(pmb.C); -} diff --git a/interpreter/llvm/src/bindings/go/llvm/transforms_scalar.go b/interpreter/llvm/src/bindings/go/llvm/transforms_scalar.go deleted file mode 100644 index d1b54bd2a1913..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/transforms_scalar.go +++ /dev/null @@ -1,44 +0,0 @@ -//===- transforms_scalar.go - Bindings for scalaropts ---------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines bindings for the scalaropts component. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm-c/Transforms/Scalar.h" -#include "llvm-c/Transforms/Utils.h" -*/ -import "C" - -func (pm PassManager) AddAggressiveDCEPass() { C.LLVMAddAggressiveDCEPass(pm.C) } -func (pm PassManager) AddCFGSimplificationPass() { C.LLVMAddCFGSimplificationPass(pm.C) } -func (pm PassManager) AddDeadStoreEliminationPass() { C.LLVMAddDeadStoreEliminationPass(pm.C) } -func (pm PassManager) AddGVNPass() { C.LLVMAddGVNPass(pm.C) } -func (pm PassManager) AddIndVarSimplifyPass() { C.LLVMAddIndVarSimplifyPass(pm.C) } -func (pm PassManager) AddInstructionCombiningPass() { C.LLVMAddInstructionCombiningPass(pm.C) } -func (pm PassManager) AddJumpThreadingPass() { C.LLVMAddJumpThreadingPass(pm.C) } -func (pm PassManager) AddLICMPass() { C.LLVMAddLICMPass(pm.C) } -func (pm PassManager) AddLoopDeletionPass() { C.LLVMAddLoopDeletionPass(pm.C) } -func (pm PassManager) AddLoopRotatePass() { C.LLVMAddLoopRotatePass(pm.C) } -func (pm PassManager) AddLoopUnrollPass() { C.LLVMAddLoopUnrollPass(pm.C) } -func (pm PassManager) AddLoopUnswitchPass() { C.LLVMAddLoopUnswitchPass(pm.C) } -func (pm PassManager) AddMemCpyOptPass() { C.LLVMAddMemCpyOptPass(pm.C) } -func (pm PassManager) AddPromoteMemoryToRegisterPass() { C.LLVMAddPromoteMemoryToRegisterPass(pm.C) } -func (pm PassManager) AddReassociatePass() { C.LLVMAddReassociatePass(pm.C) } -func (pm PassManager) AddSCCPPass() { C.LLVMAddSCCPPass(pm.C) } -func (pm PassManager) AddScalarReplAggregatesPass() { C.LLVMAddScalarReplAggregatesPass(pm.C) } -func (pm PassManager) AddScalarReplAggregatesPassWithThreshold(threshold int) { - C.LLVMAddScalarReplAggregatesPassWithThreshold(pm.C, C.int(threshold)) -} -func (pm PassManager) AddSimplifyLibCallsPass() { C.LLVMAddSimplifyLibCallsPass(pm.C) } -func (pm PassManager) AddTailCallEliminationPass() { C.LLVMAddTailCallEliminationPass(pm.C) } -func (pm PassManager) AddDemoteMemoryToRegisterPass() { C.LLVMAddDemoteMemoryToRegisterPass(pm.C) } -func (pm PassManager) AddVerifierPass() { C.LLVMAddVerifierPass(pm.C) } diff --git a/interpreter/llvm/src/bindings/go/llvm/version.go b/interpreter/llvm/src/bindings/go/llvm/version.go deleted file mode 100644 index 1183fe431b97e..0000000000000 --- a/interpreter/llvm/src/bindings/go/llvm/version.go +++ /dev/null @@ -1,20 +0,0 @@ -//===- version.go - LLVM version info -------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines LLVM version information. -// -//===----------------------------------------------------------------------===// - -package llvm - -/* -#include "llvm/Config/llvm-config.h" -*/ -import "C" - -const Version = C.LLVM_VERSION_STRING diff --git a/interpreter/llvm/src/bindings/ocaml/.ocamlformat b/interpreter/llvm/src/bindings/ocaml/.ocamlformat deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/bindings/ocaml/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/CMakeLists.txt deleted file mode 100644 index 7fe960b67f272..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -add_subdirectory(llvm) -add_subdirectory(all_backends) -add_subdirectory(analysis) -add_subdirectory(backends) -add_subdirectory(bitreader) -add_subdirectory(bitwriter) -add_subdirectory(debuginfo) -add_subdirectory(irreader) -add_subdirectory(linker) -add_subdirectory(target) -add_subdirectory(transforms) -add_subdirectory(executionengine) diff --git a/interpreter/llvm/src/bindings/ocaml/README.txt b/interpreter/llvm/src/bindings/ocaml/README.txt deleted file mode 100644 index a6a595e75bb5f..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/README.txt +++ /dev/null @@ -1,30 +0,0 @@ -This directory contains LLVM bindings for the OCaml programming language -(http://ocaml.org). - -Prerequisites -------------- - -* OCaml 4.00.0+. -* ctypes 0.4+. -* oUnit 2+ (only required for tests). -* CMake (to build LLVM). - -Building the bindings ---------------------- - -If all dependencies are present, the bindings will be built and installed -as a part of the default CMake configuration, with no further action. -They will only work with the specific OCaml compiler detected during the build. - -The bindings can also be built out-of-tree, i.e. targeting a preinstalled -LLVM. To do this, configure the LLVM build tree as follows: - - $ cmake -DLLVM_OCAML_OUT_OF_TREE=TRUE \ - -DCMAKE_INSTALL_PREFIX=[Preinstalled LLVM path] \ - -DLLVM_OCAML_INSTALL_PATH=[OCaml install prefix] \ - [... any other options] - -then build and install it as: - - $ make ocaml_all - $ cmake -P bindings/ocaml/cmake_install.cmake diff --git a/interpreter/llvm/src/bindings/ocaml/all_backends/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/all_backends/CMakeLists.txt deleted file mode 100644 index 716a49cc3281b..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/all_backends/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_all_backends - OCAML llvm_all_backends - OCAMLDEP llvm - C all_backends_ocaml - LLVM ${LLVM_TARGETS_TO_BUILD}) diff --git a/interpreter/llvm/src/bindings/ocaml/all_backends/all_backends_ocaml.c b/interpreter/llvm/src/bindings/ocaml/all_backends/all_backends_ocaml.c deleted file mode 100644 index fdc73efa3f039..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/all_backends/all_backends_ocaml.c +++ /dev/null @@ -1,32 +0,0 @@ -/*===-- all_backends_ocaml.c - LLVM OCaml Glue ------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Target.h" -#include "caml/alloc.h" -#include "caml/fail.h" -#include "caml/memory.h" -#include "caml/custom.h" - -/* unit -> unit */ -value llvm_initialize_all(value Unit) { - LLVMInitializeAllTargetInfos(); - LLVMInitializeAllTargets(); - LLVMInitializeAllTargetMCs(); - LLVMInitializeAllAsmPrinters(); - LLVMInitializeAllAsmParsers(); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.ml b/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.ml deleted file mode 100644 index b4df7cde23d9a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.ml +++ /dev/null @@ -1,9 +0,0 @@ -(*===-- llvm_all_backends.ml - LLVM OCaml Interface -----------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external initialize : unit -> unit = "llvm_initialize_all" diff --git a/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.mli b/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.mli deleted file mode 100644 index 62a515b932a98..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/all_backends/llvm_all_backends.mli +++ /dev/null @@ -1,10 +0,0 @@ -(*===-- llvm_all_backends.mli - LLVM OCaml Interface ----------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Initialize all the backends targets *) -val initialize : unit -> unit diff --git a/interpreter/llvm/src/bindings/ocaml/analysis/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/analysis/CMakeLists.txt deleted file mode 100644 index 622ecdfca615e..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/analysis/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_ocaml_library(llvm_analysis - OCAML llvm_analysis - OCAMLDEP llvm - C analysis_ocaml - CFLAGS "-I${CMAKE_CURRENT_SOURCE_DIR}/../llvm" - LLVM Analysis) diff --git a/interpreter/llvm/src/bindings/ocaml/analysis/analysis_ocaml.c b/interpreter/llvm/src/bindings/ocaml/analysis/analysis_ocaml.c deleted file mode 100644 index 8fb81ee485258..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/analysis/analysis_ocaml.c +++ /dev/null @@ -1,72 +0,0 @@ -/*===-- analysis_ocaml.c - LLVM OCaml Glue ----------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Analysis.h" -#include "llvm-c/Core.h" -#include "caml/alloc.h" -#include "caml/mlvalues.h" -#include "caml/memory.h" -#include "llvm_ocaml.h" - -/* Llvm.llmodule -> string option */ -value llvm_verify_module(LLVMModuleRef M) { - CAMLparam0(); - CAMLlocal2(String, Option); - - char *Message; - int Result = LLVMVerifyModule(M, LLVMReturnStatusAction, &Message); - - if (0 == Result) { - Option = Val_none; - } else { - String = copy_string(Message); - Option = caml_alloc_some(String); - } - - LLVMDisposeMessage(Message); - - CAMLreturn(Option); -} - -/* Llvm.llvalue -> bool */ -value llvm_verify_function(LLVMValueRef Fn) { - return Val_bool(LLVMVerifyFunction(Fn, LLVMReturnStatusAction) == 0); -} - -/* Llvm.llmodule -> unit */ -value llvm_assert_valid_module(LLVMModuleRef M) { - LLVMVerifyModule(M, LLVMAbortProcessAction, 0); - return Val_unit; -} - -/* Llvm.llvalue -> unit */ -value llvm_assert_valid_function(LLVMValueRef Fn) { - LLVMVerifyFunction(Fn, LLVMAbortProcessAction); - return Val_unit; -} - -/* Llvm.llvalue -> unit */ -value llvm_view_function_cfg(LLVMValueRef Fn) { - LLVMViewFunctionCFG(Fn); - return Val_unit; -} - -/* Llvm.llvalue -> unit */ -value llvm_view_function_cfg_only(LLVMValueRef Fn) { - LLVMViewFunctionCFGOnly(Fn); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.ml b/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.ml deleted file mode 100644 index a8e5f4ef06ecf..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.ml +++ /dev/null @@ -1,21 +0,0 @@ -(*===-- llvm_analysis.ml - LLVM OCaml Interface ---------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - - -external verify_module : Llvm.llmodule -> string option = "llvm_verify_module" - -external verify_function : Llvm.llvalue -> bool = "llvm_verify_function" - -external assert_valid_module : Llvm.llmodule -> unit - = "llvm_assert_valid_module" - -external assert_valid_function : Llvm.llvalue -> unit - = "llvm_assert_valid_function" -external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg" -external view_function_cfg_only : Llvm.llvalue -> unit - = "llvm_view_function_cfg_only" diff --git a/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.mli b/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.mli deleted file mode 100644 index 3dd397425a78c..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/analysis/llvm_analysis.mli +++ /dev/null @@ -1,44 +0,0 @@ -(*===-- llvm_analysis.mli - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Intermediate representation analysis. - - This interface provides an OCaml API for LLVM IR analyses, the classes in - the Analysis library. *) - -(** [verify_module m] returns [None] if the module [m] is valid, and - [Some reason] if it is invalid. [reason] is a string containing a - human-readable validation report. See [llvm::verifyModule]. *) -external verify_module : Llvm.llmodule -> string option = "llvm_verify_module" - -(** [verify_function f] returns [true] if the function [f] is valid, and - [false] if it is invalid. See [llvm::verifyFunction]. *) -external verify_function : Llvm.llvalue -> bool = "llvm_verify_function" - -(** [verify_module m] returns if the module [m] is valid, but prints a - validation report to [stderr] and aborts the program if it is invalid. See - [llvm::verifyModule]. *) -external assert_valid_module : Llvm.llmodule -> unit - = "llvm_assert_valid_module" - -(** [verify_function f] returns if the function [f] is valid, but prints a - validation report to [stderr] and aborts the program if it is invalid. See - [llvm::verifyFunction]. *) -external assert_valid_function : Llvm.llvalue -> unit - = "llvm_assert_valid_function" - -(** [view_function_cfg f] opens up a ghostscript window displaying the CFG of - the current function with the code for each basic block inside. - See [llvm::Function::viewCFG]. *) -external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg" - -(** [view_function_cfg_only f] works just like [view_function_cfg], but does not - include the contents of basic blocks into the nodes. - See [llvm::Function::viewCFGOnly]. *) -external view_function_cfg_only : Llvm.llvalue -> unit - = "llvm_view_function_cfg_only" diff --git a/interpreter/llvm/src/bindings/ocaml/backends/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/backends/CMakeLists.txt deleted file mode 100644 index 18d62a8573814..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/backends/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -foreach(TARGET ${LLVM_TARGETS_TO_BUILD}) - set(OCAML_LLVM_TARGET ${TARGET}) - - foreach( ext ml mli ) - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/llvm_backend.${ext}.in" - "${CMAKE_CURRENT_BINARY_DIR}/llvm_${TARGET}.${ext}") - endforeach() - - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/backend_ocaml.c" - "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_ocaml.c") - - add_ocaml_library(llvm_${TARGET} - OCAML llvm_${TARGET} - C ${TARGET}_ocaml - CFLAGS -DTARGET=${TARGET} - LLVM ${TARGET} - NOCOPY) - - configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/META.llvm_backend.in" - "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}") - - install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}" - DESTINATION "${LLVM_OCAML_INSTALL_PATH}") -endforeach() diff --git a/interpreter/llvm/src/bindings/ocaml/backends/META.llvm_backend.in b/interpreter/llvm/src/bindings/ocaml/backends/META.llvm_backend.in deleted file mode 100644 index bd23abe0ca4bb..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/backends/META.llvm_backend.in +++ /dev/null @@ -1,7 +0,0 @@ -name = "llvm_@TARGET@" -version = "@PACKAGE_VERSION@" -description = "@TARGET@ Backend for LLVM" -requires = "llvm" -archive(byte) = "llvm_@TARGET@.cma" -archive(native) = "llvm_@TARGET@.cmxa" -directory = "llvm" diff --git a/interpreter/llvm/src/bindings/ocaml/backends/backend_ocaml.c b/interpreter/llvm/src/bindings/ocaml/backends/backend_ocaml.c deleted file mode 100644 index 2b3983f1b12ec..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/backends/backend_ocaml.c +++ /dev/null @@ -1,38 +0,0 @@ -/*===-- backend_ocaml.c - LLVM OCaml Glue -----------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Target.h" -#include "caml/alloc.h" -#include "caml/memory.h" - -/* TODO: Figure out how to call these only for targets which support them. - * LLVMInitialize ## target ## AsmPrinter(); - * LLVMInitialize ## target ## AsmParser(); - * LLVMInitialize ## target ## Disassembler(); - */ - -#define INITIALIZER1(target) \ - value llvm_initialize_ ## target(value Unit) { \ - LLVMInitialize ## target ## TargetInfo(); \ - LLVMInitialize ## target ## Target(); \ - LLVMInitialize ## target ## TargetMC(); \ - return Val_unit; \ - } - -#define INITIALIZER(target) INITIALIZER1(target) - -INITIALIZER(TARGET) diff --git a/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.ml.in b/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.ml.in deleted file mode 100644 index b80cc75c7d0ee..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.ml.in +++ /dev/null @@ -1,9 +0,0 @@ -(*===-- llvm_backend.ml.in - LLVM OCaml Interface -------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external initialize : unit -> unit = "llvm_initialize_@TARGET@" diff --git a/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.mli.in b/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.mli.in deleted file mode 100644 index 25b0f89823f26..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/backends/llvm_backend.mli.in +++ /dev/null @@ -1,18 +0,0 @@ -(*===-- llvm_backend.mli.in - LLVM OCaml Interface ------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** @TARGET@ Initialization. - - This interface provides an OCaml API for initialization of - the @TARGET@ LLVM target. By referencing this module, you will cause - OCaml to load or link in the LLVM libraries corresponding to the target. - By calling [initialize], you will register components of this target - in the target registry, which is necessary in order to emit assembly, - object files, and so on. *) - -external initialize : unit -> unit = "llvm_initialize_@TARGET@" \ No newline at end of file diff --git a/interpreter/llvm/src/bindings/ocaml/bitreader/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/bitreader/CMakeLists.txt deleted file mode 100644 index d71f51c28b453..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitreader/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_bitreader - OCAML llvm_bitreader - OCAMLDEP llvm - C bitreader_ocaml - LLVM BitReader) diff --git a/interpreter/llvm/src/bindings/ocaml/bitreader/bitreader_ocaml.c b/interpreter/llvm/src/bindings/ocaml/bitreader/bitreader_ocaml.c deleted file mode 100644 index 518103e6b606a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitreader/bitreader_ocaml.c +++ /dev/null @@ -1,44 +0,0 @@ -/*===-- bitwriter_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/BitReader.h" -#include "llvm-c/Core.h" -#include "caml/alloc.h" -#include "caml/fail.h" -#include "caml/memory.h" -#include "caml/callback.h" - -void llvm_raise(value Prototype, char *Message); - -/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */ -LLVMModuleRef llvm_get_module(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) { - LLVMModuleRef M; - - if (LLVMGetBitcodeModuleInContext2(C, MemBuf, &M)) - llvm_raise(*caml_named_value("Llvm_bitreader.Error"), - LLVMCreateMessage("")); - - return M; -} - -/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */ -LLVMModuleRef llvm_parse_bitcode(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) { - LLVMModuleRef M; - - if (LLVMParseBitcodeInContext2(C, MemBuf, &M)) - llvm_raise(*caml_named_value("Llvm_bitreader.Error"), - LLVMCreateMessage("")); - - return M; -} diff --git a/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.ml b/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.ml deleted file mode 100644 index 601089fa5da85..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.ml +++ /dev/null @@ -1,18 +0,0 @@ -(*===-- llvm_bitreader.ml - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -exception Error of string - -let () = Callback.register_exception "Llvm_bitreader.Error" (Error "") - -external get_module - : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule - = "llvm_get_module" -external parse_bitcode - : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule - = "llvm_parse_bitcode" diff --git a/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.mli b/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.mli deleted file mode 100644 index def8b84fe9e62..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitreader/llvm_bitreader.mli +++ /dev/null @@ -1,26 +0,0 @@ -(*===-- llvm_bitreader.mli - LLVM OCaml Interface -------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Bitcode reader. - - This interface provides an OCaml API for the LLVM bitcode reader, the - classes in the Bitreader library. *) - -exception Error of string - -(** [get_module context mb] reads the bitcode for a new module [m] from the - memory buffer [mb] in the context [context]. Returns [m] if successful, or - raises [Error msg] otherwise, where [msg] is a description of the error - encountered. See the function [llvm::getBitcodeModule]. *) -val get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule - -(** [parse_bitcode context mb] parses the bitcode for a new module [m] from the - memory buffer [mb] in the context [context]. Returns [m] if successful, or - raises [Error msg] otherwise, where [msg] is a description of the error - encountered. See the function [llvm::ParseBitcodeFile]. *) -val parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule diff --git a/interpreter/llvm/src/bindings/ocaml/bitwriter/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/bitwriter/CMakeLists.txt deleted file mode 100644 index 6462d65c8669a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitwriter/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_bitwriter - OCAML llvm_bitwriter - OCAMLDEP llvm - C bitwriter_ocaml - LLVM BitWriter) diff --git a/interpreter/llvm/src/bindings/ocaml/bitwriter/bitwriter_ocaml.c b/interpreter/llvm/src/bindings/ocaml/bitwriter/bitwriter_ocaml.c deleted file mode 100644 index 8ced8dd76eaf1..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitwriter/bitwriter_ocaml.c +++ /dev/null @@ -1,48 +0,0 @@ -/*===-- bitwriter_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/BitWriter.h" -#include "llvm-c/Core.h" -#include "caml/alloc.h" -#include "caml/mlvalues.h" -#include "caml/memory.h" - -/* Llvm.llmodule -> string -> bool */ -value llvm_write_bitcode_file(LLVMModuleRef M, value Path) { - int Result = LLVMWriteBitcodeToFile(M, String_val(Path)); - return Val_bool(Result == 0); -} - -/* ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool */ -value llvm_write_bitcode_to_fd(value U, LLVMModuleRef M, value FD) { - int Unbuffered; - int Result; - - if (U == Val_int(0)) { - Unbuffered = 0; - } else { - Unbuffered = Bool_val(Field(U, 0)); - } - - Result = LLVMWriteBitcodeToFD(M, Int_val(FD), 0, Unbuffered); - return Val_bool(Result == 0); -} - -/* Llvm.llmodule -> Llvm.llmemorybuffer */ -LLVMMemoryBufferRef llvm_write_bitcode_to_memory_buffer(LLVMModuleRef M) { - return LLVMWriteBitcodeToMemoryBuffer(M); -} diff --git a/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.ml b/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.ml deleted file mode 100644 index 3750a02dcd0e9..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.ml +++ /dev/null @@ -1,27 +0,0 @@ -(*===-- llvm_bitwriter.ml - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------=== - * - * This interface provides an OCaml API for the LLVM intermediate - * representation, the classes in the VMCore library. - * - *===----------------------------------------------------------------------===*) - -external write_bitcode_file - : Llvm.llmodule -> string -> bool - = "llvm_write_bitcode_file" - -external write_bitcode_to_fd - : ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool - = "llvm_write_bitcode_to_fd" - -external write_bitcode_to_memory_buffer - : Llvm.llmodule -> Llvm.llmemorybuffer - = "llvm_write_bitcode_to_memory_buffer" - -let output_bitcode ?unbuffered channel m = - write_bitcode_to_fd ?unbuffered m (Unix.descr_of_out_channel channel) diff --git a/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.mli b/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.mli deleted file mode 100644 index b8cc59c0f6713..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/bitwriter/llvm_bitwriter.mli +++ /dev/null @@ -1,36 +0,0 @@ -(*===-- llvm_bitwriter.mli - LLVM OCaml Interface -------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Bitcode writer. - - This interface provides an OCaml API for the LLVM bitcode writer, the - classes in the Bitwriter library. *) - -(** [write_bitcode_file m path] writes the bitcode for module [m] to the file at - [path]. Returns [true] if successful, [false] otherwise. *) -external write_bitcode_file - : Llvm.llmodule -> string -> bool - = "llvm_write_bitcode_file" - -(** [write_bitcode_to_fd ~unbuffered fd m] writes the bitcode for module - [m] to the channel [c]. If [unbuffered] is [true], after every write the fd - will be flushed. Returns [true] if successful, [false] otherwise. *) -external write_bitcode_to_fd - : ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool - = "llvm_write_bitcode_to_fd" - -(** [write_bitcode_to_memory_buffer m] returns a memory buffer containing - the bitcode for module [m]. *) -external write_bitcode_to_memory_buffer - : Llvm.llmodule -> Llvm.llmemorybuffer - = "llvm_write_bitcode_to_memory_buffer" - -(** [output_bitcode ~unbuffered c m] writes the bitcode for module [m] - to the channel [c]. If [unbuffered] is [true], after every write the fd - will be flushed. Returns [true] if successful, [false] otherwise. *) -val output_bitcode : ?unbuffered:bool -> out_channel -> Llvm.llmodule -> bool diff --git a/interpreter/llvm/src/bindings/ocaml/debuginfo/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/debuginfo/CMakeLists.txt deleted file mode 100644 index 07f4956cccf2f..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/debuginfo/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_ocaml_library(llvm_debuginfo - OCAML llvm_debuginfo - OCAMLDEP llvm - C debuginfo_ocaml - CFLAGS "-I${CMAKE_CURRENT_SOURCE_DIR}/../llvm" - LLVM Core) diff --git a/interpreter/llvm/src/bindings/ocaml/debuginfo/debuginfo_ocaml.c b/interpreter/llvm/src/bindings/ocaml/debuginfo/debuginfo_ocaml.c deleted file mode 100644 index 794fa6b06ab69..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/debuginfo/debuginfo_ocaml.c +++ /dev/null @@ -1,913 +0,0 @@ -/*===-- debuginfo_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include - -#include "caml/memory.h" -#include "caml/mlvalues.h" -#include "llvm-c/Core.h" -#include "llvm-c/DebugInfo.h" -#include "llvm-c/Support.h" - -#include "llvm_ocaml.h" - -// This is identical to the definition in llvm_debuginfo.ml:DIFlag.t -typedef enum { - i_DIFlagZero, - i_DIFlagPrivate, - i_DIFlagProtected, - i_DIFlagPublic, - i_DIFlagFwdDecl, - i_DIFlagAppleBlock, - i_DIFlagReservedBit4, - i_DIFlagVirtual, - i_DIFlagArtificial, - i_DIFlagExplicit, - i_DIFlagPrototyped, - i_DIFlagObjcClassComplete, - i_DIFlagObjectPointer, - i_DIFlagVector, - i_DIFlagStaticMember, - i_DIFlagLValueReference, - i_DIFlagRValueReference, - i_DIFlagReserved, - i_DIFlagSingleInheritance, - i_DIFlagMultipleInheritance, - i_DIFlagVirtualInheritance, - i_DIFlagIntroducedVirtual, - i_DIFlagBitField, - i_DIFlagNoReturn, - i_DIFlagTypePassByValue, - i_DIFlagTypePassByReference, - i_DIFlagEnumClass, - i_DIFlagFixedEnum, - i_DIFlagThunk, - i_DIFlagNonTrivial, - i_DIFlagBigEndian, - i_DIFlagLittleEndian, - i_DIFlagIndirectVirtualBase, - i_DIFlagAccessibility, - i_DIFlagPtrToMemberRep -} LLVMDIFlag_i; - -static LLVMDIFlags map_DIFlag(LLVMDIFlag_i DIF) { - switch (DIF) { - case i_DIFlagZero: - return LLVMDIFlagZero; - case i_DIFlagPrivate: - return LLVMDIFlagPrivate; - case i_DIFlagProtected: - return LLVMDIFlagProtected; - case i_DIFlagPublic: - return LLVMDIFlagPublic; - case i_DIFlagFwdDecl: - return LLVMDIFlagFwdDecl; - case i_DIFlagAppleBlock: - return LLVMDIFlagAppleBlock; - case i_DIFlagReservedBit4: - return LLVMDIFlagReservedBit4; - case i_DIFlagVirtual: - return LLVMDIFlagVirtual; - case i_DIFlagArtificial: - return LLVMDIFlagArtificial; - case i_DIFlagExplicit: - return LLVMDIFlagExplicit; - case i_DIFlagPrototyped: - return LLVMDIFlagPrototyped; - case i_DIFlagObjcClassComplete: - return LLVMDIFlagObjcClassComplete; - case i_DIFlagObjectPointer: - return LLVMDIFlagObjectPointer; - case i_DIFlagVector: - return LLVMDIFlagVector; - case i_DIFlagStaticMember: - return LLVMDIFlagStaticMember; - case i_DIFlagLValueReference: - return LLVMDIFlagLValueReference; - case i_DIFlagRValueReference: - return LLVMDIFlagRValueReference; - case i_DIFlagReserved: - return LLVMDIFlagReserved; - case i_DIFlagSingleInheritance: - return LLVMDIFlagSingleInheritance; - case i_DIFlagMultipleInheritance: - return LLVMDIFlagMultipleInheritance; - case i_DIFlagVirtualInheritance: - return LLVMDIFlagVirtualInheritance; - case i_DIFlagIntroducedVirtual: - return LLVMDIFlagIntroducedVirtual; - case i_DIFlagBitField: - return LLVMDIFlagBitField; - case i_DIFlagNoReturn: - return LLVMDIFlagNoReturn; - case i_DIFlagTypePassByValue: - return LLVMDIFlagTypePassByValue; - case i_DIFlagTypePassByReference: - return LLVMDIFlagTypePassByReference; - case i_DIFlagEnumClass: - return LLVMDIFlagEnumClass; - case i_DIFlagFixedEnum: - return LLVMDIFlagFixedEnum; - case i_DIFlagThunk: - return LLVMDIFlagThunk; - case i_DIFlagNonTrivial: - return LLVMDIFlagNonTrivial; - case i_DIFlagBigEndian: - return LLVMDIFlagBigEndian; - case i_DIFlagLittleEndian: - return LLVMDIFlagLittleEndian; - case i_DIFlagIndirectVirtualBase: - return LLVMDIFlagIndirectVirtualBase; - case i_DIFlagAccessibility: - return LLVMDIFlagAccessibility; - case i_DIFlagPtrToMemberRep: - return LLVMDIFlagPtrToMemberRep; - } -} - -value llvm_debug_metadata_version(value Unit) { - return Val_int(LLVMDebugMetadataVersion()); -} - -value llvm_get_module_debug_metadata_version(LLVMModuleRef Module) { - return Val_int(LLVMGetModuleDebugMetadataVersion(Module)); -} - -#define DIFlags_val(v) (*(LLVMDIFlags *)(Data_custom_val(v))) - -static struct custom_operations diflags_ops = { - (char *)"DebugInfo.lldiflags", custom_finalize_default, - custom_compare_default, custom_hash_default, - custom_serialize_default, custom_deserialize_default, - custom_compare_ext_default}; - -static value alloc_diflags(LLVMDIFlags Flags) { - value V = alloc_custom(&diflags_ops, sizeof(LLVMDIFlags), 0, 1); - DIFlags_val(V) = Flags; - return V; -} - -LLVMDIFlags llvm_diflags_get(value i_Flag) { - LLVMDIFlags Flags = map_DIFlag(Int_val(i_Flag)); - return alloc_diflags(Flags); -} - -LLVMDIFlags llvm_diflags_set(value Flags, value i_Flag) { - LLVMDIFlags FlagsNew = DIFlags_val(Flags) | map_DIFlag(Int_val(i_Flag)); - return alloc_diflags(FlagsNew); -} - -value llvm_diflags_test(value Flags, value i_Flag) { - LLVMDIFlags Flag = map_DIFlag(Int_val(i_Flag)); - return Val_bool((DIFlags_val(Flags) & Flag) == Flag); -} - -#define DIBuilder_val(v) (*(LLVMDIBuilderRef *)(Data_custom_val(v))) - -static void llvm_finalize_dibuilder(value B) { - LLVMDIBuilderFinalize(DIBuilder_val(B)); - LLVMDisposeDIBuilder(DIBuilder_val(B)); -} - -static struct custom_operations dibuilder_ops = { - (char *)"DebugInfo.lldibuilder", llvm_finalize_dibuilder, - custom_compare_default, custom_hash_default, - custom_serialize_default, custom_deserialize_default, - custom_compare_ext_default}; - -static value alloc_dibuilder(LLVMDIBuilderRef B) { - value V = alloc_custom(&dibuilder_ops, sizeof(LLVMDIBuilderRef), 0, 1); - DIBuilder_val(V) = B; - return V; -} - -/* llmodule -> lldibuilder */ -value llvm_dibuilder(LLVMModuleRef M) { - return alloc_dibuilder(LLVMCreateDIBuilder(M)); -} - -value llvm_dibuild_finalize(value Builder) { - LLVMDIBuilderFinalize(DIBuilder_val(Builder)); - return Val_unit; -} - -LLVMMetadataRef llvm_dibuild_create_compile_unit_native( - value Builder, value Lang, LLVMMetadataRef FileRef, value Producer, - value IsOptimized, value Flags, value RuntimeVer, value SplitName, - value Kind, value DWOId, value SplitDebugInline, - value DebugInfoForProfiling, value SysRoot, value SDK) { - return LLVMDIBuilderCreateCompileUnit( - DIBuilder_val(Builder), Int_val(Lang), FileRef, String_val(Producer), - caml_string_length(Producer), Bool_val(IsOptimized), String_val(Flags), - caml_string_length(Flags), Int_val(RuntimeVer), String_val(SplitName), - caml_string_length(SplitName), Int_val(Kind), Int_val(DWOId), - Bool_val(SplitDebugInline), Bool_val(DebugInfoForProfiling), - String_val(SysRoot), caml_string_length(SysRoot), String_val(SDK), - caml_string_length(SDK)); -} - -LLVMMetadataRef llvm_dibuild_create_compile_unit_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_compile_unit_native( - argv[0], // Builder - argv[1], // Lang - (LLVMMetadataRef)argv[2], // FileRef - argv[3], // Producer - argv[4], // IsOptimized - argv[5], // Flags - argv[6], // RuntimeVer - argv[7], // SplitName - argv[8], // Kind - argv[9], // DWOId - argv[10], // SplitDebugInline - argv[11], // DebugInfoForProfiling - argv[12], // SysRoot - argv[13] // SDK - ); -} - -LLVMMetadataRef llvm_dibuild_create_file(value Builder, value Filename, - value Directory) { - return LLVMDIBuilderCreateFile(DIBuilder_val(Builder), String_val(Filename), - caml_string_length(Filename), - String_val(Directory), - caml_string_length(Directory)); -} - -LLVMMetadataRef -llvm_dibuild_create_module_native(value Builder, LLVMMetadataRef ParentScope, - value Name, value ConfigMacros, - value IncludePath, value SysRoot) { - return LLVMDIBuilderCreateModule( - DIBuilder_val(Builder), ParentScope, String_val(Name), - caml_string_length(Name), String_val(ConfigMacros), - caml_string_length(ConfigMacros), String_val(IncludePath), - caml_string_length(IncludePath), String_val(SysRoot), - caml_string_length(SysRoot)); -} - -LLVMMetadataRef llvm_dibuild_create_module_bytecode(value *argv, int argn) { - return llvm_dibuild_create_module_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // ParentScope - argv[2], // Name - argv[3], // ConfigMacros - argv[4], // IncludePath - argv[5] // SysRoot - ); -} - -LLVMMetadataRef llvm_dibuild_create_namespace(value Builder, - LLVMMetadataRef ParentScope, - value Name, value ExportSymbols) { - return LLVMDIBuilderCreateNameSpace( - DIBuilder_val(Builder), ParentScope, String_val(Name), - caml_string_length(Name), Bool_val(ExportSymbols)); -} - -LLVMMetadataRef llvm_dibuild_create_function_native( - value Builder, LLVMMetadataRef Scope, value Name, value LinkageName, - LLVMMetadataRef File, value LineNo, LLVMMetadataRef Ty, value IsLocalToUnit, - value IsDefinition, value ScopeLine, value Flags, value IsOptimized) { - return LLVMDIBuilderCreateFunction( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - String_val(LinkageName), caml_string_length(LinkageName), File, - Int_val(LineNo), Ty, Bool_val(IsLocalToUnit), Bool_val(IsDefinition), - Int_val(ScopeLine), DIFlags_val(Flags), Bool_val(IsOptimized)); -} - -LLVMMetadataRef llvm_dibuild_create_function_bytecode(value *argv, int argn) { - return llvm_dibuild_create_function_native(argv[0], // Builder, - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - argv[3], // LinkageName - (LLVMMetadataRef)argv[4], // File - argv[5], // LineNo - (LLVMMetadataRef)argv[6], // Ty - argv[7], // IsLocalUnit - argv[8], // IsDefinition - argv[9], // ScopeLine - argv[10], // Flags - argv[11] // IsOptimized - ); -} - -LLVMMetadataRef llvm_dibuild_create_lexical_block(value Builder, - LLVMMetadataRef Scope, - LLVMMetadataRef File, - value Line, value Column) { - return LLVMDIBuilderCreateLexicalBlock(DIBuilder_val(Builder), Scope, File, - Int_val(Line), Int_val(Column)); -} - -LLVMMetadataRef llvm_metadata_null() { return (LLVMMetadataRef)NULL; } - -LLVMMetadataRef llvm_dibuild_create_debug_location(LLVMContextRef Ctx, - value Line, value Column, - LLVMMetadataRef Scope, - LLVMMetadataRef InlinedAt) { - return LLVMDIBuilderCreateDebugLocation(Ctx, Int_val(Line), Int_val(Column), - Scope, InlinedAt); -} - -value llvm_di_location_get_line(LLVMMetadataRef Location) { - return Val_int(LLVMDILocationGetLine(Location)); -} - -value llvm_di_location_get_column(LLVMMetadataRef Location) { - return Val_int(LLVMDILocationGetColumn(Location)); -} - -LLVMMetadataRef llvm_di_location_get_scope(LLVMMetadataRef Location) { - return LLVMDILocationGetScope(Location); -} - -value llvm_di_location_get_inlined_at(LLVMMetadataRef Location) { - return (ptr_to_option(LLVMDILocationGetInlinedAt(Location))); -} - -value llvm_di_scope_get_file(LLVMMetadataRef Scope) { - return (ptr_to_option(LLVMDIScopeGetFile(Scope))); -} - -value llvm_di_file_get_directory(LLVMMetadataRef File) { - unsigned Len; - const char *Directory = LLVMDIFileGetDirectory(File, &Len); - return cstr_to_string(Directory, Len); -} - -value llvm_di_file_get_filename(LLVMMetadataRef File) { - unsigned Len; - const char *Filename = LLVMDIFileGetFilename(File, &Len); - return cstr_to_string(Filename, Len); -} - -value llvm_di_file_get_source(LLVMMetadataRef File) { - unsigned Len; - const char *Source = LLVMDIFileGetSource(File, &Len); - return cstr_to_string(Source, Len); -} - -LLVMMetadataRef llvm_dibuild_get_or_create_type_array(value Builder, - value Data) { - - return LLVMDIBuilderGetOrCreateTypeArray(DIBuilder_val(Builder), - (LLVMMetadataRef *)Op_val(Data), - Wosize_val(Data)); -} - -LLVMMetadataRef llvm_dibuild_get_or_create_array(value Builder, value Data) { - - return LLVMDIBuilderGetOrCreateArray(DIBuilder_val(Builder), - (LLVMMetadataRef *)Op_val(Data), - Wosize_val(Data)); -} - -LLVMMetadataRef llvm_dibuild_create_subroutine_type(value Builder, - LLVMMetadataRef File, - value ParameterTypes, - value Flags) { - - return LLVMDIBuilderCreateSubroutineType( - DIBuilder_val(Builder), File, (LLVMMetadataRef *)Op_val(ParameterTypes), - Wosize_val(ParameterTypes), DIFlags_val(Flags)); -} - -LLVMMetadataRef llvm_dibuild_create_enumerator(value Builder, value Name, - value Value, value IsUnsigned) { - return LLVMDIBuilderCreateEnumerator( - DIBuilder_val(Builder), String_val(Name), caml_string_length(Name), - (int64_t)Int_val(Value), Bool_val(IsUnsigned)); -} - -LLVMMetadataRef llvm_dibuild_create_enumeration_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, value SizeInBits, value AlignInBits, value Elements, - LLVMMetadataRef ClassTy) { - return LLVMDIBuilderCreateEnumerationType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), (LLVMMetadataRef *)Op_val(Elements), - Wosize_val(Elements), ClassTy); -} - -LLVMMetadataRef llvm_dibuild_create_enumeration_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_enumeration_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - argv[5], // SizeInBits - argv[6], // AlignInBits - argv[7], // Elements - (LLVMMetadataRef)argv[8] // ClassTy - ); -} - -LLVMMetadataRef llvm_dibuild_create_union_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, value SizeInBits, value AlignInBits, value Flags, - value Elements, value RunTimeLanguage, value UniqueId) { - - return LLVMDIBuilderCreateUnionType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), DIFlags_val(Flags), - (LLVMMetadataRef *)Op_val(Elements), Wosize_val(Elements), - Int_val(RunTimeLanguage), String_val(UniqueId), - caml_string_length(UniqueId)); -} - -LLVMMetadataRef llvm_dibuild_create_union_type_bytecode(value *argv, int argn) { - return llvm_dibuild_create_union_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - argv[5], // SizeInBits - argv[6], // AlignInBits - argv[7], // Flags - argv[8], // Elements - argv[9], // RunTimeLanguage - argv[10] // UniqueId - ); -} - -LLVMMetadataRef llvm_dibuild_create_array_type(value Builder, value Size, - value AlignInBits, - LLVMMetadataRef Ty, - value Subscripts) { - return LLVMDIBuilderCreateArrayType( - DIBuilder_val(Builder), (uint64_t)Int_val(Size), Int_val(AlignInBits), Ty, - (LLVMMetadataRef *)Op_val(Subscripts), Wosize_val(Subscripts)); -} - -LLVMMetadataRef llvm_dibuild_create_vector_type(value Builder, value Size, - value AlignInBits, - LLVMMetadataRef Ty, - value Subscripts) { - return LLVMDIBuilderCreateVectorType( - DIBuilder_val(Builder), (uint64_t)Int_val(Size), Int_val(AlignInBits), Ty, - (LLVMMetadataRef *)Op_val(Subscripts), Wosize_val(Subscripts)); -} - -LLVMMetadataRef llvm_dibuild_create_unspecified_type(value Builder, - value Name) { - return LLVMDIBuilderCreateUnspecifiedType( - DIBuilder_val(Builder), String_val(Name), caml_string_length(Name)); -} - -LLVMMetadataRef llvm_dibuild_create_basic_type(value Builder, value Name, - value SizeInBits, value Encoding, - value Flags) { - - return LLVMDIBuilderCreateBasicType( - DIBuilder_val(Builder), String_val(Name), caml_string_length(Name), - (uint64_t)Int_val(SizeInBits), Int_val(Encoding), DIFlags_val(Flags)); -} - -LLVMMetadataRef llvm_dibuild_create_pointer_type_native( - value Builder, LLVMMetadataRef PointeeTy, value SizeInBits, - value AlignInBits, value AddressSpace, value Name) { - return LLVMDIBuilderCreatePointerType( - DIBuilder_val(Builder), PointeeTy, (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), Int_val(AddressSpace), String_val(Name), - caml_string_length(Name)); -} - -LLVMMetadataRef llvm_dibuild_create_pointer_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_pointer_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // PointeeTy - argv[2], // SizeInBits - argv[3], // AlignInBits - argv[4], // AddressSpace - argv[5] // Name - ); -} - -LLVMMetadataRef llvm_dibuild_create_struct_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, value SizeInBits, value AlignInBits, value Flags, - LLVMMetadataRef DerivedFrom, value Elements, value RunTimeLanguage, - LLVMMetadataRef VTableHolder, value UniqueId) { - - return LLVMDIBuilderCreateStructType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), DIFlags_val(Flags), DerivedFrom, - (LLVMMetadataRef *)Op_val(Elements), Wosize_val(Elements), - Int_val(RunTimeLanguage), VTableHolder, String_val(UniqueId), - caml_string_length(UniqueId)); -} - -LLVMMetadataRef llvm_dibuild_create_struct_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_struct_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - argv[5], // SizeInBits - argv[6], // AlignInBits - argv[7], // Flags - (LLVMMetadataRef)argv[8], // DeriviedFrom - argv[9], // Elements - argv[10], // RunTimeLanguage - (LLVMMetadataRef)argv[11], // VTableHolder - argv[12] // UniqueId - ); -} - -LLVMMetadataRef llvm_dibuild_create_member_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, value SizeInBits, value AlignInBits, value OffsetInBits, - value Flags, LLVMMetadataRef Ty) { - - return LLVMDIBuilderCreateMemberType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), (uint64_t)Int_val(OffsetInBits), DIFlags_val(Flags), - Ty); -} - -LLVMMetadataRef llvm_dibuild_create_member_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_member_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - argv[5], // SizeInBits - argv[6], // AlignInBits - argv[7], // OffsetInBits - argv[8], // Flags - (LLVMMetadataRef)argv[9] // Ty - ); -} - -LLVMMetadataRef llvm_dibuild_create_static_member_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, LLVMMetadataRef Type, value Flags, - LLVMValueRef ConstantVal, value AlignInBits) { - - return LLVMDIBuilderCreateStaticMemberType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), Type, DIFlags_val(Flags), ConstantVal, - Int_val(AlignInBits)); -} - -LLVMMetadataRef llvm_dibuild_create_static_member_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_static_member_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - (LLVMMetadataRef)argv[5], // Type - argv[6], // Flags, - (LLVMValueRef)argv[7], // ConstantVal - argv[8] // AlignInBits - ); -} - -LLVMMetadataRef llvm_dibuild_create_member_pointer_type_native( - value Builder, LLVMMetadataRef PointeeType, LLVMMetadataRef ClassType, - uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags) { - - return LLVMDIBuilderCreateMemberPointerType( - DIBuilder_val(Builder), PointeeType, ClassType, - (uint64_t)Int_val(SizeInBits), Int_val(AlignInBits), Flags); -} - -LLVMMetadataRef llvm_dibuild_create_member_pointer_type_bytecode(value *argv, - int argn) { - return llvm_dibuild_create_member_pointer_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // PointeeType - (LLVMMetadataRef)argv[2], // ClassType - argv[3], // SizeInBits - argv[4], // AlignInBits - argv[5] // Flags - ); -} - -LLVMMetadataRef llvm_dibuild_create_object_pointer_type(value Builder, - LLVMMetadataRef Type) { - return LLVMDIBuilderCreateObjectPointerType(DIBuilder_val(Builder), Type); -} - -LLVMMetadataRef llvm_dibuild_create_qualified_type(value Builder, value Tag, - LLVMMetadataRef Type) { - - return LLVMDIBuilderCreateQualifiedType(DIBuilder_val(Builder), Int_val(Tag), - Type); -} - -LLVMMetadataRef llvm_dibuild_create_reference_type(value Builder, value Tag, - LLVMMetadataRef Type) { - - return LLVMDIBuilderCreateReferenceType(DIBuilder_val(Builder), Int_val(Tag), - Type); -} - -LLVMMetadataRef llvm_dibuild_create_null_ptr_type(value Builder) { - - return LLVMDIBuilderCreateNullPtrType(DIBuilder_val(Builder)); -} - -LLVMMetadataRef llvm_dibuild_create_typedef_native( - value Builder, LLVMMetadataRef Type, value Name, LLVMMetadataRef File, - value LineNo, LLVMMetadataRef Scope, value AlignInBits) { - - return LLVMDIBuilderCreateTypedef( - DIBuilder_val(Builder), Type, String_val(Name), caml_string_length(Name), - File, Int_val(LineNo), Scope, Int_val(AlignInBits)); -} - -LLVMMetadataRef llvm_dibuild_create_typedef_bytecode(value *argv, int argn) { - - return llvm_dibuild_create_typedef_native(argv[0], // Builder - (LLVMMetadataRef)argv[1], // Type - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNo - (LLVMMetadataRef)argv[5], // Scope - argv[6] // AlignInBits - ); -} - -LLVMMetadataRef -llvm_dibuild_create_inheritance_native(value Builder, LLVMMetadataRef Ty, - LLVMMetadataRef BaseTy, value BaseOffset, - value VBPtrOffset, value Flags) { - - return LLVMDIBuilderCreateInheritance(DIBuilder_val(Builder), Ty, BaseTy, - (uint64_t)Int_val(BaseOffset), - Int_val(VBPtrOffset), Flags); -} - -LLVMMetadataRef llvm_dibuild_create_inheritance_bytecode(value *argv, int arg) { - - return llvm_dibuild_create_inheritance_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Ty - (LLVMMetadataRef)argv[2], // BaseTy - argv[3], // BaseOffset - argv[4], // VBPtrOffset - argv[5] // Flags - ); -} - -LLVMMetadataRef llvm_dibuild_create_forward_decl_native( - value Builder, value Tag, value Name, LLVMMetadataRef Scope, - LLVMMetadataRef File, value Line, value RuntimeLang, value SizeInBits, - value AlignInBits, value UniqueIdentifier) { - return LLVMDIBuilderCreateForwardDecl( - DIBuilder_val(Builder), Int_val(Tag), String_val(Name), - caml_string_length(Name), Scope, File, Int_val(Line), - Int_val(RuntimeLang), (uint64_t)Int_val(SizeInBits), Int_val(AlignInBits), - String_val(UniqueIdentifier), caml_string_length(UniqueIdentifier)); -} - -LLVMMetadataRef llvm_dibuild_create_forward_decl_bytecode(value *argv, - int arg) { - - return llvm_dibuild_create_forward_decl_native( - argv[0], // Builder - argv[1], // Tag - argv[2], // Name - (LLVMMetadataRef)argv[3], // Scope - (LLVMMetadataRef)argv[4], // File - argv[5], // Line - argv[6], // RuntimeLang - argv[7], // SizeInBits - argv[8], // AlignInBits - argv[9] // UniqueIdentifier - ); -} - -LLVMMetadataRef llvm_dibuild_create_replaceable_composite_type_native( - value Builder, value Tag, value Name, LLVMMetadataRef Scope, - LLVMMetadataRef File, value Line, value RuntimeLang, value SizeInBits, - value AlignInBits, value Flags, value UniqueIdentifier) { - - return LLVMDIBuilderCreateReplaceableCompositeType( - DIBuilder_val(Builder), Int_val(Tag), String_val(Name), - caml_string_length(Name), Scope, File, Int_val(Line), - Int_val(RuntimeLang), (uint64_t)Int_val(SizeInBits), Int_val(AlignInBits), - DIFlags_val(Flags), String_val(UniqueIdentifier), - caml_string_length(UniqueIdentifier)); -} - -LLVMMetadataRef -llvm_dibuild_create_replaceable_composite_type_bytecode(value *argv, int arg) { - - return llvm_dibuild_create_replaceable_composite_type_native( - argv[0], // Builder - argv[1], // Tag - argv[2], // Name - (LLVMMetadataRef)argv[3], // Scope - (LLVMMetadataRef)argv[4], // File - argv[5], // Line - argv[6], // RuntimeLang - argv[7], // SizeInBits - argv[8], // AlignInBits - argv[9], // Flags - argv[10] // UniqueIdentifier - ); -} - -LLVMMetadataRef llvm_dibuild_create_bit_field_member_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNum, value SizeInBits, value OffsetInBits, - value StorageOffsetInBits, value Flags, LLVMMetadataRef Ty) { - - return LLVMDIBuilderCreateBitFieldMemberType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNum), (uint64_t)Int_val(SizeInBits), - (uint64_t)Int_val(OffsetInBits), (uint64_t)Int_val(StorageOffsetInBits), - DIFlags_val(Flags), Ty); -} - -LLVMMetadataRef llvm_dibuild_create_bit_field_member_type_bytecode(value *argv, - int arg) { - - return llvm_dibuild_create_bit_field_member_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNum - argv[5], // SizeInBits - argv[6], // OffsetInBits - argv[7], // StorageOffsetInBits - argv[8], // Flags - (LLVMMetadataRef)argv[9] // Ty - ); -} - -LLVMMetadataRef llvm_dibuild_create_class_type_native( - value Builder, LLVMMetadataRef Scope, value Name, LLVMMetadataRef File, - value LineNumber, value SizeInBits, value AlignInBits, value OffsetInBits, - value Flags, LLVMMetadataRef DerivedFrom, value Elements, - LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode, - value UniqueIdentifier) { - - return LLVMDIBuilderCreateClassType( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - File, Int_val(LineNumber), (uint64_t)Int_val(SizeInBits), - Int_val(AlignInBits), (uint64_t)Int_val(OffsetInBits), DIFlags_val(Flags), - DerivedFrom, (LLVMMetadataRef *)Op_val(Elements), Wosize_val(Elements), - VTableHolder, TemplateParamsNode, String_val(UniqueIdentifier), - caml_string_length(UniqueIdentifier)); -} - -LLVMMetadataRef llvm_dibuild_create_class_type_bytecode(value *argv, int arg) { - - return llvm_dibuild_create_class_type_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - (LLVMMetadataRef)argv[3], // File - argv[4], // LineNumber - argv[5], // SizeInBits - argv[6], // AlignInBits - argv[7], // OffsetInBits - argv[8], // Flags - (LLVMMetadataRef)argv[9], // DerivedFrom - argv[10], // Elements - (LLVMMetadataRef)argv[11], // VTableHolder - (LLVMMetadataRef)argv[12], // TemplateParamsNode - argv[13] // UniqueIdentifier - ); -} - -LLVMMetadataRef llvm_dibuild_create_artificial_type(value Builder, - LLVMMetadataRef Type) { - return LLVMDIBuilderCreateArtificialType(DIBuilder_val(Builder), Type); -} - -value llvm_di_type_get_name(LLVMMetadataRef DType) { - size_t Len; - const char *Name = LLVMDITypeGetName(DType, &Len); - return cstr_to_string(Name, Len); -} - -value llvm_di_type_get_size_in_bits(LLVMMetadataRef DType) { - uint64_t Size = LLVMDITypeGetSizeInBits(DType); - return Val_int((int)Size); -} - -value llvm_di_type_get_offset_in_bits(LLVMMetadataRef DType) { - uint64_t Size = LLVMDITypeGetOffsetInBits(DType); - return Val_int((int)Size); -} - -value llvm_di_type_get_align_in_bits(LLVMMetadataRef DType) { - uint32_t Size = LLVMDITypeGetAlignInBits(DType); - return Val_int(Size); -} - -value llvm_di_type_get_line(LLVMMetadataRef DType) { - unsigned Line = LLVMDITypeGetLine(DType); - return Val_int(Line); -} - -value llvm_di_type_get_flags(LLVMMetadataRef DType) { - LLVMDIFlags Flags = LLVMDITypeGetLine(DType); - return alloc_diflags(Flags); -} - -value llvm_get_subprogram(LLVMValueRef Func) { - return (ptr_to_option(LLVMGetSubprogram(Func))); -} - -value llvm_set_subprogram(LLVMValueRef Func, LLVMMetadataRef SP) { - LLVMSetSubprogram(Func, SP); - return Val_unit; -} - -value llvm_di_subprogram_get_line(LLVMMetadataRef Subprogram) { - return Val_int(LLVMDISubprogramGetLine(Subprogram)); -} - -value llvm_instr_get_debug_loc(LLVMValueRef Inst) { - return (ptr_to_option(LLVMInstructionGetDebugLoc(Inst))); -} - -value llvm_instr_set_debug_loc(LLVMValueRef Inst, LLVMMetadataRef Loc) { - LLVMInstructionSetDebugLoc(Inst, Loc); - return Val_unit; -} - -LLVMMetadataRef llvm_dibuild_create_constant_value_expression(value Builder, - value Value) { - return LLVMDIBuilderCreateConstantValueExpression(DIBuilder_val(Builder), - (int64_t)Int_val(Value)); -} - -LLVMMetadataRef llvm_dibuild_create_global_variable_expression_native( - value Builder, LLVMMetadataRef Scope, value Name, value Linkage, - LLVMMetadataRef File, value Line, LLVMMetadataRef Ty, value LocalToUnit, - LLVMMetadataRef Expr, LLVMMetadataRef Decl, value AlignInBits) { - return LLVMDIBuilderCreateGlobalVariableExpression( - DIBuilder_val(Builder), Scope, String_val(Name), caml_string_length(Name), - String_val(Linkage), caml_string_length(Linkage), File, Int_val(Line), Ty, - Bool_val(LocalToUnit), Expr, Decl, Int_val(AlignInBits)); -} - -LLVMMetadataRef -llvm_dibuild_create_global_variable_expression_bytecode(value *argv, int arg) { - - return llvm_dibuild_create_global_variable_expression_native( - argv[0], // Builder - (LLVMMetadataRef)argv[1], // Scope - argv[2], // Name - argv[3], // Linkage - (LLVMMetadataRef)argv[4], // File - argv[5], // Line - (LLVMMetadataRef)argv[6], // Ty - argv[7], // LocalToUnit - (LLVMMetadataRef)argv[8], // Expr - (LLVMMetadataRef)argv[9], // Decl - argv[10] // AlignInBits - ); -} - -value llvm_di_global_variable_expression_get_variable(LLVMMetadataRef GVE) { - return (ptr_to_option(LLVMDIGlobalVariableExpressionGetVariable(GVE))); -} - -value llvm_di_variable_get_line(LLVMMetadataRef Variable) { - return Val_int(LLVMDIVariableGetLine(Variable)); -} - -value llvm_di_variable_get_file(LLVMMetadataRef Variable) { - return (ptr_to_option(LLVMDIVariableGetFile(Variable))); -} - -value llvm_get_metadata_kind(LLVMMetadataRef Metadata) { - return Val_int(LLVMGetMetadataKind(Metadata)); -} diff --git a/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.ml b/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.ml deleted file mode 100644 index 232efd4cdd387..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.ml +++ /dev/null @@ -1,567 +0,0 @@ -(*===-- llvm_debuginfo.ml - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -type lldibuilder - -(** Source languages known by DWARF. *) -module DWARFSourceLanguageKind = struct - type t = - | C89 - | C - | Ada83 - | C_plus_plus - | Cobol74 - | Cobol85 - | Fortran77 - | Fortran90 - | Pascal83 - | Modula2 - (* New in DWARF v3: *) - | LLVMJava - | C99 - | Ada95 - | Fortran95 - | PLI - | ObjC - | ObjC_plus_plus - | UPC - | D - (* New in DWARF v4: *) - | LLVMPython - (* New in DWARF v5: *) - | LLVMOpenCL - | Go - | Modula3 - | Haskell - | C_plus_plus_03 - | C_plus_plus_11 - | OCaml - | Rust - | C11 - | Swift - | Julia - | Dylan - | C_plus_plus_14 - | Fortran03 - | Fortran08 - | RenderScript - | BLISS - (* Vendor extensions: *) - | LLVMMips_Assembler - | GOOGLE_RenderScript - | BORLAND_Delphi -end - -module DIFlag = struct - type t = - | Zero - | Private - | Protected - | Public - | FwdDecl - | AppleBlock - | ReservedBit4 - | Virtual - | Artificial - | Explicit - | Prototyped - | ObjcClassComplete - | ObjectPointer - | Vector - | StaticMember - | LValueReference - | RValueReference - | Reserved - | SingleInheritance - | MultipleInheritance - | VirtualInheritance - | IntroducedVirtual - | BitField - | NoReturn - | TypePassByValue - | TypePassByReference - | EnumClass - | FixedEnum - | Thunk - | NonTrivial - | BigEndian - | LittleEndian - | IndirectVirtualBase - | Accessibility - | PtrToMemberRep -end - -type lldiflags - -external diflags_get : DIFlag.t -> lldiflags = "llvm_diflags_get" - -external diflags_set : lldiflags -> DIFlag.t -> lldiflags = "llvm_diflags_set" - -external diflags_test : lldiflags -> DIFlag.t -> bool = "llvm_diflags_test" - -(** The kind of metadata nodes. *) -module MetadataKind = struct - type t = - | MDStringMetadataKind - | ConstantAsMetadataMetadataKind - | LocalAsMetadataMetadataKind - | DistinctMDOperandPlaceholderMetadataKind - | MDTupleMetadataKind - | DILocationMetadataKind - | DIExpressionMetadataKind - | DIGlobalVariableExpressionMetadataKind - | GenericDINodeMetadataKind - | DISubrangeMetadataKind - | DIEnumeratorMetadataKind - | DIBasicTypeMetadataKind - | DIDerivedTypeMetadataKind - | DICompositeTypeMetadataKind - | DISubroutineTypeMetadataKind - | DIFileMetadataKind - | DICompileUnitMetadataKind - | DISubprogramMetadataKind - | DILexicalBlockMetadataKind - | DILexicalBlockFileMetadataKind - | DINamespaceMetadataKind - | DIModuleMetadataKind - | DITemplateTypeParameterMetadataKind - | DITemplateValueParameterMetadataKind - | DIGlobalVariableMetadataKind - | DILocalVariableMetadataKind - | DILabelMetadataKind - | DIObjCPropertyMetadataKind - | DIImportedEntityMetadataKind - | DIMacroMetadataKind - | DIMacroFileMetadataKind - | DICommonBlockMetadataKind -end - -(** The amount of debug information to emit. *) -module DWARFEmissionKind = struct - type t = None | Full | LineTablesOnly -end - -external debug_metadata_version : unit -> int = "llvm_debug_metadata_version" - -external get_module_debug_metadata_version : Llvm.llmodule -> int - = "llvm_get_module_debug_metadata_version" - -external dibuilder : Llvm.llmodule -> lldibuilder = "llvm_dibuilder" - -external dibuild_finalize : lldibuilder -> unit = "llvm_dibuild_finalize" - -(* See LLVMDIBuilderCreateCompileUnit for argument details. *) -external dibuild_create_compile_unit : - lldibuilder -> - DWARFSourceLanguageKind.t -> - file_ref:Llvm.llmetadata -> - producer:string -> - is_optimized:bool -> - flags:string -> - runtime_ver:int -> - split_name:string -> - DWARFEmissionKind.t -> - dwoid:int -> - di_inlining:bool -> - di_profiling:bool -> - sys_root:string -> - sdk:string -> - Llvm.llmetadata - = "llvm_dibuild_create_compile_unit_bytecode" "llvm_dibuild_create_compile_unit_native" - -external dibuild_create_file : - lldibuilder -> filename:string -> directory:string -> Llvm.llmetadata - = "llvm_dibuild_create_file" - -external dibuild_create_module : - lldibuilder -> - parent_ref:Llvm.llmetadata -> - name:string -> - config_macros:string -> - include_path:string -> - sys_root:string -> - Llvm.llmetadata - = "llvm_dibuild_create_module_bytecode" "llvm_dibuild_create_module_native" - -external dibuild_create_namespace : - lldibuilder -> - parent_ref:Llvm.llmetadata -> - name:string -> - export_symbols:bool -> - Llvm.llmetadata = "llvm_dibuild_create_namespace" - -external dibuild_create_function : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - linkage_name:string -> - file:Llvm.llmetadata -> - line_no:int -> - ty:Llvm.llmetadata -> - is_local_to_unit:bool -> - is_definition:bool -> - scope_line:int -> - flags:lldiflags -> - is_optimized:bool -> - Llvm.llmetadata - = "llvm_dibuild_create_function_bytecode" "llvm_dibuild_create_function_native" - -external dibuild_create_lexical_block : - lldibuilder -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - column:int -> - Llvm.llmetadata = "llvm_dibuild_create_lexical_block" - -external dibuild_create_debug_location_helper : - Llvm.llcontext -> - line:int -> - column:int -> - scope:Llvm.llmetadata -> - inlined_at:Llvm.llmetadata -> - Llvm.llmetadata = "llvm_dibuild_create_debug_location" - -external llmetadata_null : unit -> Llvm.llmetadata = "llvm_metadata_null" - -let dibuild_create_debug_location ?(inlined_at = llmetadata_null ()) llctx ~line - ~column ~scope = - dibuild_create_debug_location_helper llctx line column scope inlined_at - -external di_location_get_line : location:Llvm.llmetadata -> int - = "llvm_di_location_get_line" - -external di_location_get_column : location:Llvm.llmetadata -> int - = "llvm_di_location_get_column" - -external di_location_get_scope : location:Llvm.llmetadata -> Llvm.llmetadata - = "llvm_di_location_get_scope" - -external di_location_get_inlined_at : - location:Llvm.llmetadata -> Llvm.llmetadata option - = "llvm_di_location_get_inlined_at" - -external di_scope_get_file : scope:Llvm.llmetadata -> Llvm.llmetadata option - = "llvm_di_scope_get_file" - -external di_file_get_directory : file:Llvm.llmetadata -> string - = "llvm_di_file_get_directory" - -external di_file_get_filename : file:Llvm.llmetadata -> string - = "llvm_di_file_get_filename" - -external di_file_get_source : file:Llvm.llmetadata -> string - = "llvm_di_file_get_source" - -external dibuild_get_or_create_type_array : - lldibuilder -> data:Llvm.llmetadata array -> Llvm.llmetadata - = "llvm_dibuild_get_or_create_type_array" - -external dibuild_get_or_create_array : - lldibuilder -> data:Llvm.llmetadata array -> Llvm.llmetadata - = "llvm_dibuild_get_or_create_array" - -external dibuild_create_subroutine_type : - lldibuilder -> - file:Llvm.llmetadata -> - param_types:Llvm.llmetadata array -> - lldiflags -> - Llvm.llmetadata = "llvm_dibuild_create_subroutine_type" - -external dibuild_create_enumerator : - lldibuilder -> name:string -> value:int -> is_unsigned:bool -> Llvm.llmetadata - = "llvm_dibuild_create_enumerator" - -external dibuild_create_enumeration_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - elements:Llvm.llmetadata array -> - class_ty:Llvm.llmetadata -> - Llvm.llmetadata - = "llvm_dibuild_create_enumeration_type_bytecode" "llvm_dibuild_create_enumeration_type_native" - -external dibuild_create_union_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - elements:Llvm.llmetadata array -> - run_time_language:int -> - unique_id:string -> - Llvm.llmetadata - = "llvm_dibuild_create_union_type_bytecode" "llvm_dibuild_create_union_type_native" - -external dibuild_create_array_type : - lldibuilder -> - size:int -> - align_in_bits:int -> - ty:Llvm.llmetadata -> - subscripts:Llvm.llmetadata array -> - Llvm.llmetadata = "llvm_dibuild_create_array_type" - -external dibuild_create_vector_type : - lldibuilder -> - size:int -> - align_in_bits:int -> - ty:Llvm.llmetadata -> - subscripts:Llvm.llmetadata array -> - Llvm.llmetadata = "llvm_dibuild_create_array_type" - -external dibuild_create_unspecified_type : - lldibuilder -> name:string -> Llvm.llmetadata - = "llvm_dibuild_create_unspecified_type" - -external dibuild_create_basic_type : - lldibuilder -> - name:string -> - size_in_bits:int -> - encoding:int -> - lldiflags -> - Llvm.llmetadata = "llvm_dibuild_create_basic_type" - -external dibuild_create_pointer_type : - lldibuilder -> - pointee_ty:Llvm.llmetadata -> - size_in_bits:int -> - align_in_bits:int -> - address_space:int -> - name:string -> - Llvm.llmetadata - = "llvm_dibuild_create_pointer_type_bytecode" "llvm_dibuild_create_pointer_type_native" - -external dibuild_create_struct_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - derived_from:Llvm.llmetadata -> - elements:Llvm.llmetadata array -> - DWARFSourceLanguageKind.t -> - vtable_holder:Llvm.llmetadata -> - unique_id:string -> - Llvm.llmetadata - = "llvm_dibuild_create_struct_type_bytecode" "llvm_dibuild_create_struct_type_native" - -external dibuild_create_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - offset_in_bits:int -> - lldiflags -> - ty:Llvm.llmetadata -> - Llvm.llmetadata - = "llvm_dibuild_create_member_type_bytecode" "llvm_dibuild_create_member_type_native" - -external dibuild_create_static_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - ty:Llvm.llmetadata -> - lldiflags -> - const_val:Llvm.llvalue -> - align_in_bits:int -> - Llvm.llmetadata - = "llvm_dibuild_create_static_member_type_bytecode" "llvm_dibuild_create_static_member_type_native" - -external dibuild_create_member_pointer_type : - lldibuilder -> - pointee_type:Llvm.llmetadata -> - class_type:Llvm.llmetadata -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - Llvm.llmetadata - = "llvm_dibuild_create_member_pointer_type_bytecode" "llvm_dibuild_create_member_pointer_type_native" - -external dibuild_create_object_pointer_type : - lldibuilder -> Llvm.llmetadata -> Llvm.llmetadata - = "llvm_dibuild_create_object_pointer_type" - -external dibuild_create_qualified_type : - lldibuilder -> tag:int -> Llvm.llmetadata -> Llvm.llmetadata - = "llvm_dibuild_create_qualified_type" - -external dibuild_create_reference_type : - lldibuilder -> tag:int -> Llvm.llmetadata -> Llvm.llmetadata - = "llvm_dibuild_create_reference_type" - -external dibuild_create_null_ptr_type : lldibuilder -> Llvm.llmetadata - = "llvm_dibuild_create_null_ptr_type" - -external dibuild_create_typedef : - lldibuilder -> - ty:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_no:int -> - scope:Llvm.llmetadata -> - align_in_bits:int -> - Llvm.llmetadata - = "llvm_dibuild_create_typedef_bytecode" "llvm_dibuild_create_typedef_native" - -external dibuild_create_inheritance : - lldibuilder -> - ty:Llvm.llmetadata -> - base_ty:Llvm.llmetadata -> - base_offset:int -> - vb_ptr_offset:int -> - lldiflags -> - Llvm.llmetadata - = "llvm_dibuild_create_inheritance_bytecode" "llvm_dibuild_create_inheritance_native" - -external dibuild_create_forward_decl : - lldibuilder -> - tag:int -> - name:string -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - runtime_lang:int -> - size_in_bits:int -> - align_in_bits:int -> - unique_identifier:string -> - Llvm.llmetadata - = "llvm_dibuild_create_forward_decl_bytecode" "llvm_dibuild_create_forward_decl_native" - -external dibuild_create_replaceable_composite_type : - lldibuilder -> - tag:int -> - name:string -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - runtime_lang:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - unique_identifier:string -> - Llvm.llmetadata - = "llvm_dibuild_create_replaceable_composite_type_bytecode" "llvm_dibuild_create_replaceable_composite_type_native" - -external dibuild_create_bit_field_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_num:int -> - size_in_bits:int -> - offset_in_bits:int -> - storage_offset_in_bits:int -> - lldiflags -> - ty:Llvm.llmetadata -> - Llvm.llmetadata - = "llvm_dibuild_create_bit_field_member_type_bytecode" "llvm_dibuild_create_bit_field_member_type_native" - -external dibuild_create_class_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - offset_in_bits:int -> - lldiflags -> - derived_from:Llvm.llmetadata -> - elements:Llvm.llmetadata array -> - vtable_holder:Llvm.llmetadata -> - template_params_node:Llvm.llmetadata -> - unique_identifier:string -> - Llvm.llmetadata - = "llvm_dibuild_create_class_type_bytecode" "llvm_dibuild_create_class_type_native" - -external dibuild_create_artificial_type : - lldibuilder -> ty:Llvm.llmetadata -> Llvm.llmetadata - = "llvm_dibuild_create_artificial_type" - -external di_type_get_name : Llvm.llmetadata -> string = "llvm_di_type_get_name" - -external di_type_get_size_in_bits : Llvm.llmetadata -> int - = "llvm_di_type_get_size_in_bits" - -external di_type_get_offset_in_bits : Llvm.llmetadata -> int - = "llvm_di_type_get_offset_in_bits" - -external di_type_get_align_in_bits : Llvm.llmetadata -> int - = "llvm_di_type_get_align_in_bits" - -external di_type_get_line : Llvm.llmetadata -> int = "llvm_di_type_get_line" - -external di_type_get_flags : Llvm.llmetadata -> lldiflags - = "llvm_di_type_get_flags" - -external get_subprogram : Llvm.llvalue -> Llvm.llmetadata option - = "llvm_get_subprogram" - -external set_subprogram : Llvm.llvalue -> Llvm.llmetadata -> unit - = "llvm_set_subprogram" - -external di_subprogram_get_line : Llvm.llmetadata -> int - = "llvm_di_subprogram_get_line" - -external instr_get_debug_loc : Llvm.llvalue -> Llvm.llmetadata option - = "llvm_instr_get_debug_loc" - -external instr_set_debug_loc_helper : Llvm.llvalue -> Llvm.llmetadata -> unit - = "llvm_instr_set_debug_loc" - -let instr_set_debug_loc i mopt = - match mopt with - | None -> instr_set_debug_loc_helper i (llmetadata_null ()) - | Some m -> instr_set_debug_loc_helper i m - -external dibuild_create_constant_value_expression : - lldibuilder -> int -> Llvm.llmetadata - = "llvm_dibuild_create_constant_value_expression" - -external dibuild_create_global_variable_expression : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - linkage:string -> - file:Llvm.llmetadata -> - line:int -> - ty:Llvm.llmetadata -> - is_local_to_unit:bool -> - expr:Llvm.llmetadata -> - decl:Llvm.llmetadata -> - align_in_bits:int -> - Llvm.llmetadata - = "llvm_dibuild_create_global_variable_expression_bytecode" "llvm_dibuild_create_global_variable_expression_native" - -external di_global_variable_expression_get_variable : - Llvm.llmetadata -> Llvm.llmetadata option - = "llvm_di_global_variable_expression_get_variable" - -external di_variable_get_line : Llvm.llmetadata -> int - = "llvm_di_variable_get_line" - -external di_variable_get_file : Llvm.llmetadata -> Llvm.llmetadata option - = "llvm_di_variable_get_file" - -external get_metadata_kind : Llvm.llmetadata -> MetadataKind.t - = "llvm_get_metadata_kind" diff --git a/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.mli b/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.mli deleted file mode 100644 index 7f2bb6dd53bf9..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/debuginfo/llvm_debuginfo.mli +++ /dev/null @@ -1,625 +0,0 @@ -(*===-- llvm_debuginfo.mli - LLVM OCaml Interface -------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -type lldibuilder - -(** Source languages known by DWARF. *) -module DWARFSourceLanguageKind : sig - type t = - | C89 - | C - | Ada83 - | C_plus_plus - | Cobol74 - | Cobol85 - | Fortran77 - | Fortran90 - | Pascal83 - | Modula2 - (* New in DWARF v3: *) - | LLVMJava - | C99 - | Ada95 - | Fortran95 - | PLI - | ObjC - | ObjC_plus_plus - | UPC - | D - (* New in DWARF v4: *) - | LLVMPython - (* New in DWARF v5: *) - | LLVMOpenCL - | Go - | Modula3 - | Haskell - | C_plus_plus_03 - | C_plus_plus_11 - | OCaml - | Rust - | C11 - | Swift - | Julia - | Dylan - | C_plus_plus_14 - | Fortran03 - | Fortran08 - | RenderScript - | BLISS - (* Vendor extensions: *) - | LLVMMips_Assembler - | GOOGLE_RenderScript - | BORLAND_Delphi -end - -module DIFlag : sig - type t = - | Zero - | Private - | Protected - | Public - | FwdDecl - | AppleBlock - | ReservedBit4 - | Virtual - | Artificial - | Explicit - | Prototyped - | ObjcClassComplete - | ObjectPointer - | Vector - | StaticMember - | LValueReference - | RValueReference - | Reserved - | SingleInheritance - | MultipleInheritance - | VirtualInheritance - | IntroducedVirtual - | BitField - | NoReturn - | TypePassByValue - | TypePassByReference - | EnumClass - | FixedEnum - | Thunk - | NonTrivial - | BigEndian - | LittleEndian - | IndirectVirtualBase - | Accessibility - | PtrToMemberRep -end - -type lldiflags -(** An opaque type to represent OR of multiple DIFlag.t. *) - -val diflags_get : DIFlag.t -> lldiflags -(** [diflags_set f] Construct an lldiflags value with a single flag [f]. *) - -val diflags_set : lldiflags -> DIFlag.t -> lldiflags -(** [diflags_set fs f] Include flag [f] in [fs] and return the new value. *) - -val diflags_test : lldiflags -> DIFlag.t -> bool -(** [diflags_test fs f] Does [fs] contain flag [f]? *) - -(** The kind of metadata nodes. *) -module MetadataKind : sig - type t = - | MDStringMetadataKind - | ConstantAsMetadataMetadataKind - | LocalAsMetadataMetadataKind - | DistinctMDOperandPlaceholderMetadataKind - | MDTupleMetadataKind - | DILocationMetadataKind - | DIExpressionMetadataKind - | DIGlobalVariableExpressionMetadataKind - | GenericDINodeMetadataKind - | DISubrangeMetadataKind - | DIEnumeratorMetadataKind - | DIBasicTypeMetadataKind - | DIDerivedTypeMetadataKind - | DICompositeTypeMetadataKind - | DISubroutineTypeMetadataKind - | DIFileMetadataKind - | DICompileUnitMetadataKind - | DISubprogramMetadataKind - | DILexicalBlockMetadataKind - | DILexicalBlockFileMetadataKind - | DINamespaceMetadataKind - | DIModuleMetadataKind - | DITemplateTypeParameterMetadataKind - | DITemplateValueParameterMetadataKind - | DIGlobalVariableMetadataKind - | DILocalVariableMetadataKind - | DILabelMetadataKind - | DIObjCPropertyMetadataKind - | DIImportedEntityMetadataKind - | DIMacroMetadataKind - | DIMacroFileMetadataKind - | DICommonBlockMetadataKind -end - -(** The amount of debug information to emit. *) -module DWARFEmissionKind : sig - type t = None | Full | LineTablesOnly -end - -val debug_metadata_version : unit -> int -(** [debug_metadata_version ()] The current debug metadata version number *) - -val get_module_debug_metadata_version : Llvm.llmodule -> int -(** [get_module_debug_metadata_version m] Version of metadata present in [m]. *) - -val dibuilder : Llvm.llmodule -> lldibuilder -(** [dibuilder m] Create a debug info builder for [m]. *) - -val dibuild_finalize : lldibuilder -> unit -(** [dibuild_finalize dib] Construct any deferred debug info descriptors. *) - -val dibuild_create_compile_unit : - lldibuilder -> - DWARFSourceLanguageKind.t -> - file_ref:Llvm.llmetadata -> - producer:string -> - is_optimized:bool -> - flags:string -> - runtime_ver:int -> - split_name:string -> - DWARFEmissionKind.t -> - dwoid:int -> - di_inlining:bool -> - di_profiling:bool -> - sys_root:string -> - sdk:string -> - Llvm.llmetadata -(** [dibuild_create_compile_unit] A CompileUnit provides an anchor for all - debugging information generated during this instance of compilation. - See LLVMDIBuilderCreateCompileUnit. *) - -val dibuild_create_file : - lldibuilder -> filename:string -> directory:string -> Llvm.llmetadata -(** [dibuild_create_file] Create a file descriptor to hold debugging information - for a file. See LLVMDIBuilderCreateFile. *) - -val dibuild_create_module : - lldibuilder -> - parent_ref:Llvm.llmetadata -> - name:string -> - config_macros:string -> - include_path:string -> - sys_root:string -> - Llvm.llmetadata -(** [dibuild_create_module] Create a new descriptor for a module with the - specified parent scope. See LLVMDIBuilderCreateModule. *) - -val dibuild_create_namespace : - lldibuilder -> - parent_ref:Llvm.llmetadata -> - name:string -> - export_symbols:bool -> - Llvm.llmetadata -(** [dibuild_create_namespace] Create a new descriptor for a namespace with - the specified parent scope. See LLVMDIBuilderCreateNameSpace *) - -val dibuild_create_function : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - linkage_name:string -> - file:Llvm.llmetadata -> - line_no:int -> - ty:Llvm.llmetadata -> - is_local_to_unit:bool -> - is_definition:bool -> - scope_line:int -> - flags:lldiflags -> - is_optimized:bool -> - Llvm.llmetadata -(** [dibuild_create_function] Create a new descriptor for the specified - subprogram. See LLVMDIBuilderCreateFunction. *) - -val dibuild_create_lexical_block : - lldibuilder -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - column:int -> - Llvm.llmetadata -(** [dibuild_create_lexical_block] Create a descriptor for a lexical block with - the specified parent context. See LLVMDIBuilderCreateLexicalBlock *) - -val llmetadata_null : unit -> Llvm.llmetadata -(** [llmetadata_null ()] llmetadata is a wrapper around "llvm::Metadata *". - This function returns a nullptr valued llmetadata. For example, it - can be used to convey an llmetadata for "void" type. *) - -val dibuild_create_debug_location : - ?inlined_at:Llvm.llmetadata -> - Llvm.llcontext -> - line:int -> - column:int -> - scope:Llvm.llmetadata -> - Llvm.llmetadata -(** [dibuild_create] Create a new DebugLocation that describes a source - location. See LLVMDIBuilderCreateDebugLocation *) - -val di_location_get_line : location:Llvm.llmetadata -> int -(** [di_location_get_line l] Get the line number of debug location [l]. *) - -val di_location_get_column : location:Llvm.llmetadata -> int -(** [di_location_get_column l] Get the column number of debug location [l]. *) - -val di_location_get_scope : location:Llvm.llmetadata -> Llvm.llmetadata -(** [di_location_get_scope l] Get the local scope associated with - debug location [l]. *) - -val di_location_get_inlined_at : - location:Llvm.llmetadata -> Llvm.llmetadata option -(** [di_location_get_inlined_at l] Get the "inlined at" location associated with - debug location [l], if it exists. *) - -val di_scope_get_file : scope:Llvm.llmetadata -> Llvm.llmetadata option -(** [di_scope_get_file l] Get the metadata of the file associated with scope [s] - if it exists. *) - -val di_file_get_directory : file:Llvm.llmetadata -> string -(** [di_file_get_directory f] Get the directory of file [f]. *) - -val di_file_get_filename : file:Llvm.llmetadata -> string -(** [di_file_get_filename f] Get the name of file [f]. *) - -val di_file_get_source : file:Llvm.llmetadata -> string -(** [di_file_get_source f] Get the source of file [f]. *) - -val dibuild_get_or_create_type_array : - lldibuilder -> data:Llvm.llmetadata array -> Llvm.llmetadata -(** [dibuild_get_or_create_type_array] Create a type array. - See LLVMDIBuilderGetOrCreateTypeArray. *) - -val dibuild_get_or_create_array : - lldibuilder -> data:Llvm.llmetadata array -> Llvm.llmetadata -(** [dibuild_get_or_create_array] Create an array of DI Nodes. - See LLVMDIBuilderGetOrCreateArray. *) - -val dibuild_create_constant_value_expression : - lldibuilder -> int -> Llvm.llmetadata -(** [dibuild_create_constant_value_expression] Create a new descriptor for - the specified variable that does not have an address, but does have - a constant value. See LLVMDIBuilderCreateConstantValueExpression. *) - -val dibuild_create_global_variable_expression : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - linkage:string -> - file:Llvm.llmetadata -> - line:int -> - ty:Llvm.llmetadata -> - is_local_to_unit:bool -> - expr:Llvm.llmetadata -> - decl:Llvm.llmetadata -> - align_in_bits:int -> - Llvm.llmetadata -(** [dibuild_create_global_variable_expression] Create a new descriptor for - the specified variable. See LLVMDIBuilderCreateGlobalVariableExpression. *) - -val di_global_variable_expression_get_variable : - Llvm.llmetadata -> Llvm.llmetadata option -(** [di_global_variable_expression_get_variable gve] returns the debug variable - of [gve], which must be a [DIGlobalVariableExpression]. - See LLVMDIGlobalVariableExpressionGetVariable. *) - -val di_variable_get_line : Llvm.llmetadata -> int -(** [di_variable_get_line v] returns the line number of the variable [v]. - See LLVMDIVariableGetLine. *) - -val di_variable_get_file : Llvm.llmetadata -> Llvm.llmetadata option -(** [di_variable_get_file v] returns the file of the variable [v]. - See LLVMDIVariableGetFile. *) - -val dibuild_create_subroutine_type : - lldibuilder -> - file:Llvm.llmetadata -> - param_types:Llvm.llmetadata array -> - lldiflags -> - Llvm.llmetadata -(** [dibuild_create_subroutine_type] Create subroutine type. - See LLVMDIBuilderCreateSubroutineType *) - -val dibuild_create_enumerator : - lldibuilder -> name:string -> value:int -> is_unsigned:bool -> Llvm.llmetadata -(** [dibuild_create_enumerator] Create debugging information entry for an - enumerator. See LLVMDIBuilderCreateEnumerator *) - -val dibuild_create_enumeration_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - elements:Llvm.llmetadata array -> - class_ty:Llvm.llmetadata -> - Llvm.llmetadata -(** [dibuild_create_enumeration_type] Create debugging information entry for - an enumeration. See LLVMDIBuilderCreateEnumerationType. *) - -val dibuild_create_union_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - elements:Llvm.llmetadata array -> - run_time_language:int -> - unique_id:string -> - Llvm.llmetadata -(** [dibuild_create_union_type] Create debugging information entry for a union. - See LLVMDIBuilderCreateUnionType. *) - -val dibuild_create_array_type : - lldibuilder -> - size:int -> - align_in_bits:int -> - ty:Llvm.llmetadata -> - subscripts:Llvm.llmetadata array -> - Llvm.llmetadata -(** [dibuild_create_array_type] Create debugging information entry for an array. - See LLVMDIBuilderCreateArrayType. *) - -val dibuild_create_vector_type : - lldibuilder -> - size:int -> - align_in_bits:int -> - ty:Llvm.llmetadata -> - subscripts:Llvm.llmetadata array -> - Llvm.llmetadata -(** [dibuild_create_vector_type] Create debugging information entry for a - vector type. See LLVMDIBuilderCreateVectorType. *) - -val dibuild_create_unspecified_type : - lldibuilder -> name:string -> Llvm.llmetadata -(** [dibuild_create_unspecified_type] Create a DWARF unspecified type. *) - -val dibuild_create_basic_type : - lldibuilder -> - name:string -> - size_in_bits:int -> - encoding:int -> - lldiflags -> - Llvm.llmetadata -(** [dibuild_create_basic_type] Create debugging information entry for a basic - type. See LLVMDIBuilderCreateBasicType. *) - -val dibuild_create_pointer_type : - lldibuilder -> - pointee_ty:Llvm.llmetadata -> - size_in_bits:int -> - align_in_bits:int -> - address_space:int -> - name:string -> - Llvm.llmetadata -(** [dibuild_create_pointer_type] Create debugging information entry for a - pointer. See LLVMDIBuilderCreatePointerType. *) - -val dibuild_create_struct_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - derived_from:Llvm.llmetadata -> - elements:Llvm.llmetadata array -> - DWARFSourceLanguageKind.t -> - vtable_holder:Llvm.llmetadata -> - unique_id:string -> - Llvm.llmetadata -(** [dibuild_create_struct_type] Create debugging information entry for a - struct. See LLVMDIBuilderCreateStructType *) - -val dibuild_create_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - offset_in_bits:int -> - lldiflags -> - ty:Llvm.llmetadata -> - Llvm.llmetadata -(** [dibuild_create_member_type] Create debugging information entry for a - member. See LLVMDIBuilderCreateMemberType. *) - -val dibuild_create_static_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - ty:Llvm.llmetadata -> - lldiflags -> - const_val:Llvm.llvalue -> - align_in_bits:int -> - Llvm.llmetadata -(** [dibuild_create_static_member_type] Create debugging information entry for - a C++ static data member. See LLVMDIBuilderCreateStaticMemberType *) - -val dibuild_create_member_pointer_type : - lldibuilder -> - pointee_type:Llvm.llmetadata -> - class_type:Llvm.llmetadata -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - Llvm.llmetadata -(** [dibuild_create_member_pointer_type] Create debugging information entry for - a pointer to member. See LLVMDIBuilderCreateMemberPointerType *) - -val dibuild_create_object_pointer_type : - lldibuilder -> Llvm.llmetadata -> Llvm.llmetadata -(** [dibuild_create_object_pointer_type dib ty] Create a uniqued DIType* clone - with FlagObjectPointer and FlagArtificial set. [dib] is the dibuilder - value and [ty] the underlying type to which this pointer points. *) - -val dibuild_create_qualified_type : - lldibuilder -> tag:int -> Llvm.llmetadata -> Llvm.llmetadata -(** [dibuild_create_qualified_type dib tag ty] Create debugging information - entry for a qualified type, e.g. 'const int'. [dib] is the dibuilder value, - [tag] identifyies the type and [ty] is the base type. *) - -val dibuild_create_reference_type : - lldibuilder -> tag:int -> Llvm.llmetadata -> Llvm.llmetadata -(** [dibuild_create_reference_type dib tag ty] Create debugging information - entry for a reference type. [dib] is the dibuilder value, [tag] identifyies - the type and [ty] is the base type. *) - -val dibuild_create_null_ptr_type : lldibuilder -> Llvm.llmetadata -(** [dibuild_create_null_ptr_type dib] Create C++11 nullptr type. *) - -val dibuild_create_typedef : - lldibuilder -> - ty:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_no:int -> - scope:Llvm.llmetadata -> - align_in_bits:int -> - Llvm.llmetadata -(** [dibuild_create_typedef] Create debugging information entry for a typedef. - See LLVMDIBuilderCreateTypedef. *) - -val dibuild_create_inheritance : - lldibuilder -> - ty:Llvm.llmetadata -> - base_ty:Llvm.llmetadata -> - base_offset:int -> - vb_ptr_offset:int -> - lldiflags -> - Llvm.llmetadata -(** [dibuild_create_inheritance] Create debugging information entry - to establish inheritance relationship between two types. - See LLVMDIBuilderCreateInheritance. *) - -val dibuild_create_forward_decl : - lldibuilder -> - tag:int -> - name:string -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - runtime_lang:int -> - size_in_bits:int -> - align_in_bits:int -> - unique_identifier:string -> - Llvm.llmetadata -(** [dibuild_create_forward_decl] Create a permanent forward-declared type. - See LLVMDIBuilderCreateForwardDecl. *) - -val dibuild_create_replaceable_composite_type : - lldibuilder -> - tag:int -> - name:string -> - scope:Llvm.llmetadata -> - file:Llvm.llmetadata -> - line:int -> - runtime_lang:int -> - size_in_bits:int -> - align_in_bits:int -> - lldiflags -> - unique_identifier:string -> - Llvm.llmetadata -(** [dibuild_create_replaceable_composite_type] Create a temporary - forward-declared type. See LLVMDIBuilderCreateReplaceableCompositeType. *) - -val dibuild_create_bit_field_member_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_num:int -> - size_in_bits:int -> - offset_in_bits:int -> - storage_offset_in_bits:int -> - lldiflags -> - ty:Llvm.llmetadata -> - Llvm.llmetadata -(** [dibuild_create_bit_field_member_type] Create debugging information entry - for a bit field member. See LLVMDIBuilderCreateBitFieldMemberType. *) - -val dibuild_create_class_type : - lldibuilder -> - scope:Llvm.llmetadata -> - name:string -> - file:Llvm.llmetadata -> - line_number:int -> - size_in_bits:int -> - align_in_bits:int -> - offset_in_bits:int -> - lldiflags -> - derived_from:Llvm.llmetadata -> - elements:Llvm.llmetadata array -> - vtable_holder:Llvm.llmetadata -> - template_params_node:Llvm.llmetadata -> - unique_identifier:string -> - Llvm.llmetadata -(** [dibuild_create_class_type] Create debugging information entry for a class. - See LLVMDIBuilderCreateClassType. *) - -val dibuild_create_artificial_type : - lldibuilder -> ty:Llvm.llmetadata -> Llvm.llmetadata -(** [dibuild_create_artificial_type dib ty] Create a uniqued DIType* clone with - FlagArtificial set. - [dib] is the dibuilder value and [ty] the underlying type. *) - -val di_type_get_name : Llvm.llmetadata -> string -(** [di_type_get_name m] Get the name of DIType [m]. *) - -val di_type_get_size_in_bits : Llvm.llmetadata -> int -(** [di_type_get_size_in_bits m] Get size in bits of DIType [m]. *) - -val di_type_get_offset_in_bits : Llvm.llmetadata -> int -(** [di_type_get_offset_in_bits m] Get offset in bits of DIType [m]. *) - -val di_type_get_align_in_bits : Llvm.llmetadata -> int -(** [di_type_get_align_in_bits m] Get alignment in bits of DIType [m]. *) - -val di_type_get_line : Llvm.llmetadata -> int -(** [di_type_get_line m] Get source line where DIType [m] is declared. *) - -val di_type_get_flags : Llvm.llmetadata -> lldiflags -(** [di_type_get_flags m] Get the flags associated with DIType [m]. *) - -val get_subprogram : Llvm.llvalue -> Llvm.llmetadata option -(** [get_subprogram f] Get the metadata of the subprogram attached to - function [f]. *) - -val set_subprogram : Llvm.llvalue -> Llvm.llmetadata -> unit -(** [set_subprogram f m] Set the subprogram [m] attached to function [f]. *) - -val di_subprogram_get_line : Llvm.llmetadata -> int -(** [di_subprogram_get_line m] Get the line associated with subprogram [m]. *) - -val instr_get_debug_loc : Llvm.llvalue -> Llvm.llmetadata option -(** [instr_get_debug_loc i] Get the debug location for instruction [i]. *) - -val instr_set_debug_loc : Llvm.llvalue -> Llvm.llmetadata option -> unit -(** [instr_set_debug_loc i mopt] If [mopt] is None location metadata of [i] - is cleared, Otherwise location of [i] is set to the value in [mopt]. *) - -val get_metadata_kind : Llvm.llmetadata -> MetadataKind.t -(** [get_metadata_kind] Obtain the enumerated type of a Metadata instance. *) diff --git a/interpreter/llvm/src/bindings/ocaml/executionengine/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/executionengine/CMakeLists.txt deleted file mode 100644 index 0b1428aac1b80..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/executionengine/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_ocaml_library(llvm_executionengine - OCAML llvm_executionengine - OCAMLDEP llvm llvm_target - C executionengine_ocaml - LLVM ExecutionEngine MCJIT native - PKG ctypes) diff --git a/interpreter/llvm/src/bindings/ocaml/executionengine/executionengine_ocaml.c b/interpreter/llvm/src/bindings/ocaml/executionengine/executionengine_ocaml.c deleted file mode 100644 index 85990b0c9f555..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/executionengine/executionengine_ocaml.c +++ /dev/null @@ -1,126 +0,0 @@ -/*===-- executionengine_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include -#include -#include "llvm-c/Core.h" -#include "llvm-c/ExecutionEngine.h" -#include "llvm-c/Target.h" -#include "caml/alloc.h" -#include "caml/custom.h" -#include "caml/fail.h" -#include "caml/memory.h" -#include "caml/callback.h" - -void llvm_raise(value Prototype, char *Message); - -/* unit -> bool */ -value llvm_ee_initialize(value Unit) { - LLVMLinkInMCJIT(); - - return Val_bool(!LLVMInitializeNativeTarget() && - !LLVMInitializeNativeAsmParser() && - !LLVMInitializeNativeAsmPrinter()); -} - -/* llmodule -> llcompileroption -> ExecutionEngine.t */ -LLVMExecutionEngineRef llvm_ee_create(value OptRecordOpt, LLVMModuleRef M) { - value OptRecord; - LLVMExecutionEngineRef MCJIT; - char *Error; - struct LLVMMCJITCompilerOptions Options; - - LLVMInitializeMCJITCompilerOptions(&Options, sizeof(Options)); - if (OptRecordOpt != Val_int(0)) { - OptRecord = Field(OptRecordOpt, 0); - Options.OptLevel = Int_val(Field(OptRecord, 0)); - Options.CodeModel = Int_val(Field(OptRecord, 1)); - Options.NoFramePointerElim = Int_val(Field(OptRecord, 2)); - Options.EnableFastISel = Int_val(Field(OptRecord, 3)); - Options.MCJMM = NULL; - } - - if (LLVMCreateMCJITCompilerForModule(&MCJIT, M, &Options, sizeof(Options), - &Error)) - llvm_raise(*caml_named_value("Llvm_executionengine.Error"), Error); - return MCJIT; -} - -/* ExecutionEngine.t -> unit */ -value llvm_ee_dispose(LLVMExecutionEngineRef EE) { - LLVMDisposeExecutionEngine(EE); - return Val_unit; -} - -/* llmodule -> ExecutionEngine.t -> unit */ -value llvm_ee_add_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) { - LLVMAddModule(EE, M); - return Val_unit; -} - -/* llmodule -> ExecutionEngine.t -> llmodule */ -value llvm_ee_remove_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) { - LLVMModuleRef RemovedModule; - char *Error; - if (LLVMRemoveModule(EE, M, &RemovedModule, &Error)) - llvm_raise(*caml_named_value("Llvm_executionengine.Error"), Error); - return Val_unit; -} - -/* ExecutionEngine.t -> unit */ -value llvm_ee_run_static_ctors(LLVMExecutionEngineRef EE) { - LLVMRunStaticConstructors(EE); - return Val_unit; -} - -/* ExecutionEngine.t -> unit */ -value llvm_ee_run_static_dtors(LLVMExecutionEngineRef EE) { - LLVMRunStaticDestructors(EE); - return Val_unit; -} - -extern value llvm_alloc_data_layout(LLVMTargetDataRef TargetData); - -/* ExecutionEngine.t -> Llvm_target.DataLayout.t */ -value llvm_ee_get_data_layout(LLVMExecutionEngineRef EE) { - value DataLayout; - LLVMTargetDataRef OrigDataLayout; - char *TargetDataCStr; - - OrigDataLayout = LLVMGetExecutionEngineTargetData(EE); - TargetDataCStr = LLVMCopyStringRepOfTargetData(OrigDataLayout); - DataLayout = llvm_alloc_data_layout(LLVMCreateTargetData(TargetDataCStr)); - LLVMDisposeMessage(TargetDataCStr); - - return DataLayout; -} - -/* Llvm.llvalue -> int64 -> llexecutionengine -> unit */ -value llvm_ee_add_global_mapping(LLVMValueRef Global, value Ptr, - LLVMExecutionEngineRef EE) { - LLVMAddGlobalMapping(EE, Global, (void *)(Int64_val(Ptr))); - return Val_unit; -} - -value llvm_ee_get_global_value_address(value Name, LLVMExecutionEngineRef EE) { - return caml_copy_int64( - (int64_t)LLVMGetGlobalValueAddress(EE, String_val(Name))); -} - -value llvm_ee_get_function_address(value Name, LLVMExecutionEngineRef EE) { - return caml_copy_int64((int64_t)LLVMGetFunctionAddress(EE, String_val(Name))); -} diff --git a/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.ml b/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.ml deleted file mode 100644 index 5b202e2ead196..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.ml +++ /dev/null @@ -1,71 +0,0 @@ -(*===-- llvm_executionengine.ml - LLVM OCaml Interface --------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -exception Error of string - -let () = Callback.register_exception "Llvm_executionengine.Error" (Error "") - -external initialize : unit -> bool - = "llvm_ee_initialize" - -type llexecutionengine - -type llcompileroptions = { - opt_level: int; - code_model: Llvm_target.CodeModel.t; - no_framepointer_elim: bool; - enable_fast_isel: bool; -} - -let default_compiler_options = { - opt_level = 0; - code_model = Llvm_target.CodeModel.JITDefault; - no_framepointer_elim = false; - enable_fast_isel = false } - -external create : ?options:llcompileroptions -> Llvm.llmodule -> llexecutionengine - = "llvm_ee_create" -external dispose : llexecutionengine -> unit - = "llvm_ee_dispose" -external add_module : Llvm.llmodule -> llexecutionengine -> unit - = "llvm_ee_add_module" -external remove_module : Llvm.llmodule -> llexecutionengine -> unit - = "llvm_ee_remove_module" -external run_static_ctors : llexecutionengine -> unit - = "llvm_ee_run_static_ctors" -external run_static_dtors : llexecutionengine -> unit - = "llvm_ee_run_static_dtors" -external data_layout : llexecutionengine -> Llvm_target.DataLayout.t - = "llvm_ee_get_data_layout" -external add_global_mapping_ : Llvm.llvalue -> nativeint -> llexecutionengine -> unit - = "llvm_ee_add_global_mapping" -external get_global_value_address_ : string -> llexecutionengine -> nativeint - = "llvm_ee_get_global_value_address" -external get_function_address_ : string -> llexecutionengine -> nativeint - = "llvm_ee_get_function_address" - -let add_global_mapping llval ptr ee = - add_global_mapping_ llval (Ctypes.raw_address_of_ptr (Ctypes.to_voidp ptr)) ee - -let get_global_value_address name typ ee = - let vptr = get_global_value_address_ name ee in - if Nativeint.to_int vptr <> 0 then - let open Ctypes in !@ (coerce (ptr void) (ptr typ) (ptr_of_raw_address vptr)) - else - raise (Error ("Value " ^ name ^ " not found")) - -let get_function_address name typ ee = - let fptr = get_function_address_ name ee in - if Nativeint.to_int fptr <> 0 then - let open Ctypes in coerce (ptr void) typ (ptr_of_raw_address fptr) - else - raise (Error ("Function " ^ name ^ " not found")) - -(* The following are not bound. Patches are welcome. -target_machine : llexecutionengine -> Llvm_target.TargetMachine.t - *) diff --git a/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.mli b/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.mli deleted file mode 100644 index 3c5a1c06a4e03..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/executionengine/llvm_executionengine.mli +++ /dev/null @@ -1,92 +0,0 @@ -(*===-- llvm_executionengine.mli - LLVM OCaml Interface -------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** JIT Interpreter. - - This interface provides an OCaml API for LLVM execution engine (JIT/ - interpreter), the classes in the [ExecutionEngine] library. *) - -exception Error of string - -(** [initialize ()] initializes the backend corresponding to the host. - Returns [true] if initialization is successful; [false] indicates - that there is no such backend or it is unable to emit object code - via MCJIT. *) -val initialize : unit -> bool - -(** An execution engine is either a JIT compiler or an interpreter, capable of - directly loading an LLVM module and executing its functions without first - invoking a static compiler and generating a native executable. *) -type llexecutionengine - -(** MCJIT compiler options. See [llvm::TargetOptions]. *) -type llcompileroptions = { - opt_level: int; - code_model: Llvm_target.CodeModel.t; - no_framepointer_elim: bool; - enable_fast_isel: bool; -} - -(** Default MCJIT compiler options: - [{ opt_level = 0; code_model = CodeModel.JIT_default; - no_framepointer_elim = false; enable_fast_isel = false }] *) -val default_compiler_options : llcompileroptions - -(** [create m optlevel] creates a new MCJIT just-in-time compiler, taking - ownership of the module [m] if successful with the desired optimization - level [optlevel]. Raises [Error msg] if an error occurrs. The execution - engine is not garbage collected and must be destroyed with [dispose ee]. - - Run {!initialize} before using this function. - - See the function [llvm::EngineBuilder::create]. *) -val create : ?options:llcompileroptions -> Llvm.llmodule -> llexecutionengine - -(** [dispose ee] releases the memory used by the execution engine and must be - invoked to avoid memory leaks. *) -val dispose : llexecutionengine -> unit - -(** [add_module m ee] adds the module [m] to the execution engine [ee]. *) -val add_module : Llvm.llmodule -> llexecutionengine -> unit - -(** [remove_module m ee] removes the module [m] from the execution engine - [ee]. Raises [Error msg] if an error occurs. *) -val remove_module : Llvm.llmodule -> llexecutionengine -> unit - -(** [run_static_ctors ee] executes the static constructors of each module in - the execution engine [ee]. *) -val run_static_ctors : llexecutionengine -> unit - -(** [run_static_dtors ee] executes the static destructors of each module in - the execution engine [ee]. *) -val run_static_dtors : llexecutionengine -> unit - -(** [data_layout ee] is the data layout of the execution engine [ee]. *) -val data_layout : llexecutionengine -> Llvm_target.DataLayout.t - -(** [add_global_mapping gv ptr ee] tells the execution engine [ee] that - the global [gv] is at the specified location [ptr], which must outlive - [gv] and [ee]. - All uses of [gv] in the compiled code will refer to [ptr]. *) -val add_global_mapping : Llvm.llvalue -> 'a Ctypes.ptr -> llexecutionengine -> unit - -(** [get_global_value_address id typ ee] returns a pointer to the - identifier [id] as type [typ], which will be a pointer type for a - value, and which will be live as long as [id] and [ee] - are. Caution: this function finalizes, i.e. forces code - generation, all loaded modules. Further modifications to the - modules will not have any effect. *) -val get_global_value_address : string -> 'a Ctypes.typ -> llexecutionengine -> 'a - -(** [get_function_address fn typ ee] returns a pointer to the function - [fn] as type [typ], which will be a pointer type for a function - (e.g. [(int -> int) typ]), and which will be live as long as [fn] - and [ee] are. Caution: this function finalizes, i.e. forces code - generation, all loaded modules. Further modifications to the - modules will not have any effect. *) -val get_function_address : string -> 'a Ctypes.typ -> llexecutionengine -> 'a diff --git a/interpreter/llvm/src/bindings/ocaml/irreader/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/irreader/CMakeLists.txt deleted file mode 100644 index 5654b1803409c..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/irreader/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_irreader - OCAML llvm_irreader - OCAMLDEP llvm - C irreader_ocaml - LLVM IRReader) diff --git a/interpreter/llvm/src/bindings/ocaml/irreader/irreader_ocaml.c b/interpreter/llvm/src/bindings/ocaml/irreader/irreader_ocaml.c deleted file mode 100644 index a0ccf629decc1..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/irreader/irreader_ocaml.c +++ /dev/null @@ -1,34 +0,0 @@ -/*===-- irreader_ocaml.c - LLVM OCaml Glue ----------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/IRReader.h" -#include "caml/alloc.h" -#include "caml/fail.h" -#include "caml/memory.h" -#include "caml/callback.h" - -void llvm_raise(value Prototype, char *Message); - -/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */ -value llvm_parse_ir(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) { - CAMLparam0(); - CAMLlocal2(Variant, MessageVal); - LLVMModuleRef M; - char *Message; - - if (LLVMParseIRInContext(C, MemBuf, &M, &Message)) - llvm_raise(*caml_named_value("Llvm_irreader.Error"), Message); - - CAMLreturn((value)M); -} diff --git a/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.ml b/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.ml deleted file mode 100644 index a8ece43318155..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.ml +++ /dev/null @@ -1,15 +0,0 @@ -(*===-- llvm_irreader.ml - LLVM OCaml Interface ---------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - - -exception Error of string - -let _ = Callback.register_exception "Llvm_irreader.Error" (Error "") - -external parse_ir : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule - = "llvm_parse_ir" diff --git a/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.mli b/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.mli deleted file mode 100644 index bdb7d040845ab..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/irreader/llvm_irreader.mli +++ /dev/null @@ -1,20 +0,0 @@ -(*===-- llvm_irreader.mli - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** IR reader. - - This interface provides an OCaml API for the LLVM assembly reader, the - classes in the IRReader library. *) - -exception Error of string - -(** [parse_ir context mb] parses the IR for a new module [m] from the - memory buffer [mb] in the context [context]. Returns [m] if successful, or - raises [Error msg] otherwise, where [msg] is a description of the error - encountered. See the function [llvm::ParseIR]. *) -val parse_ir : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule diff --git a/interpreter/llvm/src/bindings/ocaml/linker/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/linker/CMakeLists.txt deleted file mode 100644 index 3bb367225784e..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/linker/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_linker - OCAML llvm_linker - OCAMLDEP llvm - C linker_ocaml - LLVM Linker) diff --git a/interpreter/llvm/src/bindings/ocaml/linker/linker_ocaml.c b/interpreter/llvm/src/bindings/ocaml/linker/linker_ocaml.c deleted file mode 100644 index 145de3b1bfbdd..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/linker/linker_ocaml.c +++ /dev/null @@ -1,34 +0,0 @@ -/*===-- linker_ocaml.c - LLVM OCaml Glue ------------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Core.h" -#include "llvm-c/Linker.h" -#include "caml/alloc.h" -#include "caml/memory.h" -#include "caml/fail.h" -#include "caml/callback.h" - -void llvm_raise(value Prototype, char *Message); - -/* llmodule -> llmodule -> unit */ -value llvm_link_modules(LLVMModuleRef Dst, LLVMModuleRef Src) { - if (LLVMLinkModules2(Dst, Src)) - llvm_raise(*caml_named_value("Llvm_linker.Error"), - LLVMCreateMessage("Linking failed")); - - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.ml b/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.ml deleted file mode 100644 index e61e8fcb5fc53..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.ml +++ /dev/null @@ -1,14 +0,0 @@ -(*===-- llvm_linker.ml - LLVM OCaml Interface ------------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -exception Error of string - -let () = Callback.register_exception "Llvm_linker.Error" (Error "") - -external link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit - = "llvm_link_modules" diff --git a/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.mli b/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.mli deleted file mode 100644 index ed8f0b38c4eb6..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/linker/llvm_linker.mli +++ /dev/null @@ -1,18 +0,0 @@ -(*===-- llvm_linker.mli - LLVM OCaml Interface -----------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Linker. - - This interface provides an OCaml API for LLVM bitcode linker, - the classes in the Linker library. *) - -exception Error of string - -(** [link_modules' dst src] links [src] into [dst], raising [Error] - if the linking fails. The src module is destroyed. *) -val link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit \ No newline at end of file diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/llvm/CMakeLists.txt deleted file mode 100644 index 5e6f74ec9c594..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -add_ocaml_library(llvm - OCAML llvm - C llvm_ocaml - CFLAGS "-I${CMAKE_CURRENT_SOURCE_DIR}/" - LLVM Core Support) - -configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/META.llvm.in" - "${LLVM_LIBRARY_DIR}/ocaml/META.llvm") - -install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm" - DESTINATION "${LLVM_OCAML_INSTALL_PATH}") diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/META.llvm.in b/interpreter/llvm/src/bindings/ocaml/llvm/META.llvm.in deleted file mode 100644 index 991bbc0600980..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/META.llvm.in +++ /dev/null @@ -1,118 +0,0 @@ -name = "llvm" -version = "@PACKAGE_VERSION@" -description = "LLVM OCaml bindings" -archive(byte) = "llvm.cma" -archive(native) = "llvm.cmxa" -directory = "llvm" - -package "analysis" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Intermediate representation analysis for LLVM" - archive(byte) = "llvm_analysis.cma" - archive(native) = "llvm_analysis.cmxa" -) - -package "bitreader" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Bitcode reader for LLVM" - archive(byte) = "llvm_bitreader.cma" - archive(native) = "llvm_bitreader.cmxa" -) - -package "bitwriter" ( - requires = "llvm,unix" - version = "@PACKAGE_VERSION@" - description = "Bitcode writer for LLVM" - archive(byte) = "llvm_bitwriter.cma" - archive(native) = "llvm_bitwriter.cmxa" -) - -package "executionengine" ( - requires = "llvm,llvm.target,ctypes.foreign" - version = "@PACKAGE_VERSION@" - description = "JIT and Interpreter for LLVM" - archive(byte) = "llvm_executionengine.cma" - archive(native) = "llvm_executionengine.cmxa" -) - -package "ipo" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "IPO Transforms for LLVM" - archive(byte) = "llvm_ipo.cma" - archive(native) = "llvm_ipo.cmxa" -) - -package "debuginfo" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "DebugInfo support for LLVM" - archive(byte) = "llvm_debuginfo.cma" - archive(native) = "llvm_debuginfo.cmxa" -) - -package "irreader" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "IR assembly reader for LLVM" - archive(byte) = "llvm_irreader.cma" - archive(native) = "llvm_irreader.cmxa" -) - -package "scalar_opts" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Scalar Transforms for LLVM" - archive(byte) = "llvm_scalar_opts.cma" - archive(native) = "llvm_scalar_opts.cmxa" -) - -package "transform_utils" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Transform utilities for LLVM" - archive(byte) = "llvm_transform_utils.cma" - archive(native) = "llvm_transform_utils.cmxa" -) - -package "vectorize" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Vector Transforms for LLVM" - archive(byte) = "llvm_vectorize.cma" - archive(native) = "llvm_vectorize.cmxa" -) - -package "passmgr_builder" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Pass Manager Builder for LLVM" - archive(byte) = "llvm_passmgr_builder.cma" - archive(native) = "llvm_passmgr_builder.cmxa" -) - -package "target" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Target Information for LLVM" - archive(byte) = "llvm_target.cma" - archive(native) = "llvm_target.cmxa" -) - -package "linker" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "Intermediate Representation Linker for LLVM" - archive(byte) = "llvm_linker.cma" - archive(native) = "llvm_linker.cmxa" -) - -package "all_backends" ( - requires = "llvm" - version = "@PACKAGE_VERSION@" - description = "All backends for LLVM" - archive(byte) = "llvm_all_backends.cma" - archive(native) = "llvm_all_backends.cmxa" -) diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/llvm.ml b/interpreter/llvm/src/bindings/ocaml/llvm/llvm.ml deleted file mode 100644 index 9e55ea8c43643..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/llvm.ml +++ /dev/null @@ -1,1425 +0,0 @@ -(*===-- llvm/llvm.ml - LLVM OCaml Interface -------------------------------===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - - -type llcontext -type llmodule -type llmetadata -type lltype -type llvalue -type lluse -type llbasicblock -type llbuilder -type llattrkind -type llattribute -type llmemorybuffer -type llmdkind - -exception FeatureDisabled of string - -let () = Callback.register_exception "Llvm.FeatureDisabled" (FeatureDisabled "") - -module TypeKind = struct - type t = - | Void - | Half - | Float - | Double - | X86fp80 - | Fp128 - | Ppc_fp128 - | Label - | Integer - | Function - | Struct - | Array - | Pointer - | Vector - | Metadata - | X86_mmx - | Token - | ScalableVector - | BFloat - | X86_amx -end - -module Linkage = struct - type t = - | External - | Available_externally - | Link_once - | Link_once_odr - | Link_once_odr_auto_hide - | Weak - | Weak_odr - | Appending - | Internal - | Private - | Dllimport - | Dllexport - | External_weak - | Ghost - | Common - | Linker_private - | Linker_private_weak -end - -module Visibility = struct - type t = - | Default - | Hidden - | Protected -end - -module DLLStorageClass = struct - type t = - | Default - | DLLImport - | DLLExport -end - -module CallConv = struct - let c = 0 - let fast = 8 - let cold = 9 - let x86_stdcall = 64 - let x86_fastcall = 65 -end - -module AttrRepr = struct - type t = - | Enum of llattrkind * int64 - | String of string * string -end - -module AttrIndex = struct - type t = - | Function - | Return - | Param of int - - let to_int index = - match index with - | Function -> -1 - | Return -> 0 - | Param(n) -> 1 + n -end - -module Attribute = struct - type t = - | Zext - | Sext - | Noreturn - | Inreg - | Structret - | Nounwind - | Noalias - | Byval - | Nest - | Readnone - | Readonly - | Noinline - | Alwaysinline - | Optsize - | Ssp - | Sspreq - | Alignment of int - | Nocapture - | Noredzone - | Noimplicitfloat - | Naked - | Inlinehint - | Stackalignment of int - | ReturnsTwice - | UWTable - | NonLazyBind -end - -module Icmp = struct - type t = - | Eq - | Ne - | Ugt - | Uge - | Ult - | Ule - | Sgt - | Sge - | Slt - | Sle -end - -module Fcmp = struct - type t = - | False - | Oeq - | Ogt - | Oge - | Olt - | Ole - | One - | Ord - | Uno - | Ueq - | Ugt - | Uge - | Ult - | Ule - | Une - | True -end - -module Opcode = struct - type t = - | Invalid (* not an instruction *) - (* Terminator Instructions *) - | Ret - | Br - | Switch - | IndirectBr - | Invoke - | Invalid2 - | Unreachable - (* Standard Binary Operators *) - | Add - | FAdd - | Sub - | FSub - | Mul - | FMul - | UDiv - | SDiv - | FDiv - | URem - | SRem - | FRem - (* Logical Operators *) - | Shl - | LShr - | AShr - | And - | Or - | Xor - (* Memory Operators *) - | Alloca - | Load - | Store - | GetElementPtr - (* Cast Operators *) - | Trunc - | ZExt - | SExt - | FPToUI - | FPToSI - | UIToFP - | SIToFP - | FPTrunc - | FPExt - | PtrToInt - | IntToPtr - | BitCast - (* Other Operators *) - | ICmp - | FCmp - | PHI - | Call - | Select - | UserOp1 - | UserOp2 - | VAArg - | ExtractElement - | InsertElement - | ShuffleVector - | ExtractValue - | InsertValue - | Fence - | AtomicCmpXchg - | AtomicRMW - | Resume - | LandingPad - | AddrSpaceCast - | CleanupRet - | CatchRet - | CatchPad - | CleanupPad - | CatchSwitch - | FNeg - | CallBr - | Freeze -end - -module LandingPadClauseTy = struct - type t = - | Catch - | Filter -end - -module ThreadLocalMode = struct - type t = - | None - | GeneralDynamic - | LocalDynamic - | InitialExec - | LocalExec -end - -module AtomicOrdering = struct - type t = - | NotAtomic - | Unordered - | Monotonic - | Invalid - | Acquire - | Release - | AcqiureRelease - | SequentiallyConsistent -end - -module AtomicRMWBinOp = struct - type t = - | Xchg - | Add - | Sub - | And - | Nand - | Or - | Xor - | Max - | Min - | UMax - | UMin - | FAdd - | FSub -end - -module ValueKind = struct - type t = - | NullValue - | Argument - | BasicBlock - | InlineAsm - | MDNode - | MDString - | BlockAddress - | ConstantAggregateZero - | ConstantArray - | ConstantDataArray - | ConstantDataVector - | ConstantExpr - | ConstantFP - | ConstantInt - | ConstantPointerNull - | ConstantStruct - | ConstantVector - | Function - | GlobalAlias - | GlobalIFunc - | GlobalVariable - | UndefValue - | PoisonValue - | Instruction of Opcode.t -end - -module DiagnosticSeverity = struct - type t = - | Error - | Warning - | Remark - | Note -end - -module ModuleFlagBehavior = struct - type t = - | Error - | Warning - | Require - | Override - | Append - | AppendUnique -end - -exception IoError of string - -let () = Callback.register_exception "Llvm.IoError" (IoError "") - -external install_fatal_error_handler : (string -> unit) -> unit - = "llvm_install_fatal_error_handler" -external reset_fatal_error_handler : unit -> unit - = "llvm_reset_fatal_error_handler" -external enable_pretty_stacktrace : unit -> unit - = "llvm_enable_pretty_stacktrace" -external parse_command_line_options : ?overview:string -> string array -> unit - = "llvm_parse_command_line_options" - -type ('a, 'b) llpos = -| At_end of 'a -| Before of 'b - -type ('a, 'b) llrev_pos = -| At_start of 'a -| After of 'b - - -(*===-- Context error handling --------------------------------------------===*) -module Diagnostic = struct - type t - - external description : t -> string = "llvm_get_diagnostic_description" - external severity : t -> DiagnosticSeverity.t - = "llvm_get_diagnostic_severity" -end - -external set_diagnostic_handler - : llcontext -> (Diagnostic.t -> unit) option -> unit - = "llvm_set_diagnostic_handler" - -(*===-- Contexts ----------------------------------------------------------===*) -external create_context : unit -> llcontext = "llvm_create_context" -external dispose_context : llcontext -> unit = "llvm_dispose_context" -external global_context : unit -> llcontext = "llvm_global_context" -external mdkind_id : llcontext -> string -> llmdkind = "llvm_mdkind_id" - -(*===-- Attributes --------------------------------------------------------===*) -exception UnknownAttribute of string - -let () = Callback.register_exception "Llvm.UnknownAttribute" - (UnknownAttribute "") - -external enum_attr_kind : string -> llattrkind = "llvm_enum_attr_kind" -external llvm_create_enum_attr : llcontext -> llattrkind -> int64 -> - llattribute - = "llvm_create_enum_attr_by_kind" -external is_enum_attr : llattribute -> bool = "llvm_is_enum_attr" -external get_enum_attr_kind : llattribute -> llattrkind - = "llvm_get_enum_attr_kind" -external get_enum_attr_value : llattribute -> int64 - = "llvm_get_enum_attr_value" -external llvm_create_string_attr : llcontext -> string -> string -> - llattribute - = "llvm_create_string_attr" -external is_string_attr : llattribute -> bool = "llvm_is_string_attr" -external get_string_attr_kind : llattribute -> string - = "llvm_get_string_attr_kind" -external get_string_attr_value : llattribute -> string - = "llvm_get_string_attr_value" - -let create_enum_attr context name value = - llvm_create_enum_attr context (enum_attr_kind name) value -let create_string_attr context kind value = - llvm_create_string_attr context kind value - -let attr_of_repr context repr = - match repr with - | AttrRepr.Enum(kind, value) -> llvm_create_enum_attr context kind value - | AttrRepr.String(key, value) -> llvm_create_string_attr context key value - -let repr_of_attr attr = - if is_enum_attr attr then - AttrRepr.Enum(get_enum_attr_kind attr, get_enum_attr_value attr) - else if is_string_attr attr then - AttrRepr.String(get_string_attr_kind attr, get_string_attr_value attr) - else assert false - -(*===-- Modules -----------------------------------------------------------===*) -external create_module : llcontext -> string -> llmodule = "llvm_create_module" -external dispose_module : llmodule -> unit = "llvm_dispose_module" -external target_triple: llmodule -> string - = "llvm_target_triple" -external set_target_triple: string -> llmodule -> unit - = "llvm_set_target_triple" -external data_layout: llmodule -> string - = "llvm_data_layout" -external set_data_layout: string -> llmodule -> unit - = "llvm_set_data_layout" -external dump_module : llmodule -> unit = "llvm_dump_module" -external print_module : string -> llmodule -> unit = "llvm_print_module" -external string_of_llmodule : llmodule -> string = "llvm_string_of_llmodule" -external set_module_inline_asm : llmodule -> string -> unit - = "llvm_set_module_inline_asm" -external module_context : llmodule -> llcontext = "LLVMGetModuleContext" - -external get_module_identifier : llmodule -> string - = "llvm_get_module_identifier" - -external set_module_identifer : llmodule -> string -> unit - = "llvm_set_module_identifier" - -external get_module_flag : llmodule -> string -> llmetadata option - = "llvm_get_module_flag" -external add_module_flag : llmodule -> ModuleFlagBehavior.t -> - string -> llmetadata -> unit = "llvm_add_module_flag" - -(*===-- Types -------------------------------------------------------------===*) -external classify_type : lltype -> TypeKind.t = "llvm_classify_type" -external type_context : lltype -> llcontext = "llvm_type_context" -external type_is_sized : lltype -> bool = "llvm_type_is_sized" -external dump_type : lltype -> unit = "llvm_dump_type" -external string_of_lltype : lltype -> string = "llvm_string_of_lltype" - -(*--... Operations on integer types ........................................--*) -external i1_type : llcontext -> lltype = "llvm_i1_type" -external i8_type : llcontext -> lltype = "llvm_i8_type" -external i16_type : llcontext -> lltype = "llvm_i16_type" -external i32_type : llcontext -> lltype = "llvm_i32_type" -external i64_type : llcontext -> lltype = "llvm_i64_type" - -external integer_type : llcontext -> int -> lltype = "llvm_integer_type" -external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth" - -(*--... Operations on real types ...........................................--*) -external float_type : llcontext -> lltype = "llvm_float_type" -external double_type : llcontext -> lltype = "llvm_double_type" -external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type" -external fp128_type : llcontext -> lltype = "llvm_fp128_type" -external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type" - -(*--... Operations on function types .......................................--*) -external function_type : lltype -> lltype array -> lltype = "llvm_function_type" -external var_arg_function_type : lltype -> lltype array -> lltype - = "llvm_var_arg_function_type" -external is_var_arg : lltype -> bool = "llvm_is_var_arg" -external return_type : lltype -> lltype = "LLVMGetReturnType" -external param_types : lltype -> lltype array = "llvm_param_types" - -(*--... Operations on struct types .........................................--*) -external struct_type : llcontext -> lltype array -> lltype = "llvm_struct_type" -external packed_struct_type : llcontext -> lltype array -> lltype - = "llvm_packed_struct_type" -external struct_name : lltype -> string option = "llvm_struct_name" -external named_struct_type : llcontext -> string -> lltype = - "llvm_named_struct_type" -external struct_set_body : lltype -> lltype array -> bool -> unit = - "llvm_struct_set_body" -external struct_element_types : lltype -> lltype array - = "llvm_struct_element_types" -external is_packed : lltype -> bool = "llvm_is_packed" -external is_opaque : lltype -> bool = "llvm_is_opaque" -external is_literal : lltype -> bool = "llvm_is_literal" - -(*--... Operations on pointer, vector, and array types .....................--*) - -external subtypes : lltype -> lltype array = "llvm_subtypes" -external array_type : lltype -> int -> lltype = "llvm_array_type" -external pointer_type : lltype -> lltype = "llvm_pointer_type" -external qualified_pointer_type : lltype -> int -> lltype - = "llvm_qualified_pointer_type" -external vector_type : lltype -> int -> lltype = "llvm_vector_type" - -external element_type : lltype -> lltype = "LLVMGetElementType" -external array_length : lltype -> int = "llvm_array_length" -external address_space : lltype -> int = "llvm_address_space" -external vector_size : lltype -> int = "llvm_vector_size" - -(*--... Operations on other types ..........................................--*) -external void_type : llcontext -> lltype = "llvm_void_type" -external label_type : llcontext -> lltype = "llvm_label_type" -external x86_mmx_type : llcontext -> lltype = "llvm_x86_mmx_type" -external type_by_name : llmodule -> string -> lltype option = "llvm_type_by_name" - -external classify_value : llvalue -> ValueKind.t = "llvm_classify_value" -(*===-- Values ------------------------------------------------------------===*) -external type_of : llvalue -> lltype = "llvm_type_of" -external value_name : llvalue -> string = "llvm_value_name" -external set_value_name : string -> llvalue -> unit = "llvm_set_value_name" -external dump_value : llvalue -> unit = "llvm_dump_value" -external string_of_llvalue : llvalue -> string = "llvm_string_of_llvalue" -external replace_all_uses_with : llvalue -> llvalue -> unit - = "llvm_replace_all_uses_with" - -(*--... Operations on uses .................................................--*) -external use_begin : llvalue -> lluse option = "llvm_use_begin" -external use_succ : lluse -> lluse option = "llvm_use_succ" -external user : lluse -> llvalue = "llvm_user" -external used_value : lluse -> llvalue = "llvm_used_value" - -let iter_uses f v = - let rec aux = function - | None -> () - | Some u -> - f u; - aux (use_succ u) - in - aux (use_begin v) - -let fold_left_uses f init v = - let rec aux init u = - match u with - | None -> init - | Some u -> aux (f init u) (use_succ u) - in - aux init (use_begin v) - -let fold_right_uses f v init = - let rec aux u init = - match u with - | None -> init - | Some u -> f u (aux (use_succ u) init) - in - aux (use_begin v) init - - -(*--... Operations on users ................................................--*) -external operand : llvalue -> int -> llvalue = "llvm_operand" -external operand_use : llvalue -> int -> lluse = "llvm_operand_use" -external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand" -external num_operands : llvalue -> int = "llvm_num_operands" -external indices : llvalue -> int array = "llvm_indices" - -(*--... Operations on constants of (mostly) any type .......................--*) -external is_constant : llvalue -> bool = "llvm_is_constant" -external const_null : lltype -> llvalue = "LLVMConstNull" -external const_all_ones : (*int|vec*)lltype -> llvalue = "LLVMConstAllOnes" -external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull" -external undef : lltype -> llvalue = "LLVMGetUndef" -external poison : lltype -> llvalue = "LLVMGetPoison" -external is_null : llvalue -> bool = "llvm_is_null" -external is_undef : llvalue -> bool = "llvm_is_undef" -external is_poison : llvalue -> bool = "llvm_is_poison" -external constexpr_opcode : llvalue -> Opcode.t = "llvm_constexpr_get_opcode" - -(*--... Operations on instructions .........................................--*) -external has_metadata : llvalue -> bool = "llvm_has_metadata" -external metadata : llvalue -> llmdkind -> llvalue option = "llvm_metadata" -external set_metadata : llvalue -> llmdkind -> llvalue -> unit = "llvm_set_metadata" -external clear_metadata : llvalue -> llmdkind -> unit = "llvm_clear_metadata" - -(*--... Operations on metadata .......,.....................................--*) -external mdstring : llcontext -> string -> llvalue = "llvm_mdstring" -external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode" -external mdnull : llcontext -> llvalue = "llvm_mdnull" -external get_mdstring : llvalue -> string option = "llvm_get_mdstring" -external get_mdnode_operands : llvalue -> llvalue array - = "llvm_get_mdnode_operands" -external get_named_metadata : llmodule -> string -> llvalue array - = "llvm_get_namedmd" -external add_named_metadata_operand : llmodule -> string -> llvalue -> unit - = "llvm_append_namedmd" -external value_as_metadata : llvalue -> llmetadata = "llvm_value_as_metadata" -external metadata_as_value : llcontext -> llmetadata -> llvalue - = "llvm_metadata_as_value" - -(*--... Operations on scalar constants .....................................--*) -external const_int : lltype -> int -> llvalue = "llvm_const_int" -external const_of_int64 : lltype -> Int64.t -> bool -> llvalue - = "llvm_const_of_int64" -external int64_of_const : llvalue -> Int64.t option - = "llvm_int64_of_const" -external const_int_of_string : lltype -> string -> int -> llvalue - = "llvm_const_int_of_string" -external const_float : lltype -> float -> llvalue = "llvm_const_float" -external float_of_const : llvalue -> float option - = "llvm_float_of_const" -external const_float_of_string : lltype -> string -> llvalue - = "llvm_const_float_of_string" - -(*--... Operations on composite constants ..................................--*) -external const_string : llcontext -> string -> llvalue = "llvm_const_string" -external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz" -external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array" -external const_struct : llcontext -> llvalue array -> llvalue - = "llvm_const_struct" -external const_named_struct : lltype -> llvalue array -> llvalue - = "llvm_const_named_struct" -external const_packed_struct : llcontext -> llvalue array -> llvalue - = "llvm_const_packed_struct" -external const_vector : llvalue array -> llvalue = "llvm_const_vector" -external string_of_const : llvalue -> string option = "llvm_string_of_const" -external const_element : llvalue -> int -> llvalue = "llvm_const_element" - -(*--... Constant expressions ...............................................--*) -external align_of : lltype -> llvalue = "LLVMAlignOf" -external size_of : lltype -> llvalue = "LLVMSizeOf" -external const_neg : llvalue -> llvalue = "LLVMConstNeg" -external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg" -external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg" -external const_fneg : llvalue -> llvalue = "LLVMConstFNeg" -external const_not : llvalue -> llvalue = "LLVMConstNot" -external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd" -external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd" -external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd" -external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd" -external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub" -external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub" -external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub" -external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub" -external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul" -external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul" -external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul" -external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul" -external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv" -external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv" -external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv" -external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv" -external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem" -external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem" -external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem" -external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd" -external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr" -external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor" -external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue - = "llvm_const_icmp" -external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue - = "llvm_const_fcmp" -external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl" -external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr" -external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr" -external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep" -external const_in_bounds_gep : llvalue -> llvalue array -> llvalue - = "llvm_const_in_bounds_gep" -external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc" -external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt" -external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt" -external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc" -external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt" -external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP" -external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP" -external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI" -external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI" -external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt" -external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr" -external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast" -external const_zext_or_bitcast : llvalue -> lltype -> llvalue - = "LLVMConstZExtOrBitCast" -external const_sext_or_bitcast : llvalue -> lltype -> llvalue - = "LLVMConstSExtOrBitCast" -external const_trunc_or_bitcast : llvalue -> lltype -> llvalue - = "LLVMConstTruncOrBitCast" -external const_pointercast : llvalue -> lltype -> llvalue - = "LLVMConstPointerCast" -external const_intcast : llvalue -> lltype -> is_signed:bool -> llvalue - = "llvm_const_intcast" -external const_fpcast : llvalue -> lltype -> llvalue = "LLVMConstFPCast" -external const_select : llvalue -> llvalue -> llvalue -> llvalue - = "LLVMConstSelect" -external const_extractelement : llvalue -> llvalue -> llvalue - = "LLVMConstExtractElement" -external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue - = "LLVMConstInsertElement" -external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue - = "LLVMConstShuffleVector" -external const_extractvalue : llvalue -> int array -> llvalue - = "llvm_const_extractvalue" -external const_insertvalue : llvalue -> llvalue -> int array -> llvalue - = "llvm_const_insertvalue" -external const_inline_asm : lltype -> string -> string -> bool -> bool -> - llvalue - = "llvm_const_inline_asm" -external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress" - -(*--... Operations on global variables, functions, and aliases (globals) ...--*) -external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent" -external is_declaration : llvalue -> bool = "llvm_is_declaration" -external linkage : llvalue -> Linkage.t = "llvm_linkage" -external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage" -external unnamed_addr : llvalue -> bool = "llvm_unnamed_addr" -external set_unnamed_addr : bool -> llvalue -> unit = "llvm_set_unnamed_addr" -external section : llvalue -> string = "llvm_section" -external set_section : string -> llvalue -> unit = "llvm_set_section" -external visibility : llvalue -> Visibility.t = "llvm_visibility" -external set_visibility : Visibility.t -> llvalue -> unit = "llvm_set_visibility" -external dll_storage_class : llvalue -> DLLStorageClass.t = "llvm_dll_storage_class" -external set_dll_storage_class : DLLStorageClass.t -> llvalue -> unit = "llvm_set_dll_storage_class" -external alignment : llvalue -> int = "llvm_alignment" -external set_alignment : int -> llvalue -> unit = "llvm_set_alignment" -external global_copy_all_metadata : llvalue -> (llmdkind * llmetadata) array - = "llvm_global_copy_all_metadata" -external is_global_constant : llvalue -> bool = "llvm_is_global_constant" -external set_global_constant : bool -> llvalue -> unit - = "llvm_set_global_constant" - -(*--... Operations on global variables .....................................--*) -external declare_global : lltype -> string -> llmodule -> llvalue - = "llvm_declare_global" -external declare_qualified_global : lltype -> string -> int -> llmodule -> - llvalue - = "llvm_declare_qualified_global" -external define_global : string -> llvalue -> llmodule -> llvalue - = "llvm_define_global" -external define_qualified_global : string -> llvalue -> int -> llmodule -> - llvalue - = "llvm_define_qualified_global" -external lookup_global : string -> llmodule -> llvalue option - = "llvm_lookup_global" -external delete_global : llvalue -> unit = "llvm_delete_global" -external global_initializer : llvalue -> llvalue option = "llvm_global_initializer" -external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer" -external remove_initializer : llvalue -> unit = "llvm_remove_initializer" -external is_thread_local : llvalue -> bool = "llvm_is_thread_local" -external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local" -external thread_local_mode : llvalue -> ThreadLocalMode.t - = "llvm_thread_local_mode" -external set_thread_local_mode : ThreadLocalMode.t -> llvalue -> unit - = "llvm_set_thread_local_mode" -external is_externally_initialized : llvalue -> bool - = "llvm_is_externally_initialized" -external set_externally_initialized : bool -> llvalue -> unit - = "llvm_set_externally_initialized" -external global_begin : llmodule -> (llmodule, llvalue) llpos - = "llvm_global_begin" -external global_succ : llvalue -> (llmodule, llvalue) llpos - = "llvm_global_succ" -external global_end : llmodule -> (llmodule, llvalue) llrev_pos - = "llvm_global_end" -external global_pred : llvalue -> (llmodule, llvalue) llrev_pos - = "llvm_global_pred" - -let rec iter_global_range f i e = - if i = e then () else - match i with - | At_end _ -> raise (Invalid_argument "Invalid global variable range.") - | Before bb -> - f bb; - iter_global_range f (global_succ bb) e - -let iter_globals f m = - iter_global_range f (global_begin m) (At_end m) - -let rec fold_left_global_range f init i e = - if i = e then init else - match i with - | At_end _ -> raise (Invalid_argument "Invalid global variable range.") - | Before bb -> fold_left_global_range f (f init bb) (global_succ bb) e - -let fold_left_globals f init m = - fold_left_global_range f init (global_begin m) (At_end m) - -let rec rev_iter_global_range f i e = - if i = e then () else - match i with - | At_start _ -> raise (Invalid_argument "Invalid global variable range.") - | After bb -> - f bb; - rev_iter_global_range f (global_pred bb) e - -let rev_iter_globals f m = - rev_iter_global_range f (global_end m) (At_start m) - -let rec fold_right_global_range f i e init = - if i = e then init else - match i with - | At_start _ -> raise (Invalid_argument "Invalid global variable range.") - | After bb -> fold_right_global_range f (global_pred bb) e (f bb init) - -let fold_right_globals f m init = - fold_right_global_range f (global_end m) (At_start m) init - -(*--... Operations on aliases ..............................................--*) -external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue - = "llvm_add_alias" - -(*--... Operations on functions ............................................--*) -external declare_function : string -> lltype -> llmodule -> llvalue - = "llvm_declare_function" -external define_function : string -> lltype -> llmodule -> llvalue - = "llvm_define_function" -external lookup_function : string -> llmodule -> llvalue option - = "llvm_lookup_function" -external delete_function : llvalue -> unit = "llvm_delete_function" -external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic" -external function_call_conv : llvalue -> int = "llvm_function_call_conv" -external set_function_call_conv : int -> llvalue -> unit - = "llvm_set_function_call_conv" -external gc : llvalue -> string option = "llvm_gc" -external set_gc : string option -> llvalue -> unit = "llvm_set_gc" -external function_begin : llmodule -> (llmodule, llvalue) llpos - = "llvm_function_begin" -external function_succ : llvalue -> (llmodule, llvalue) llpos - = "llvm_function_succ" -external function_end : llmodule -> (llmodule, llvalue) llrev_pos - = "llvm_function_end" -external function_pred : llvalue -> (llmodule, llvalue) llrev_pos - = "llvm_function_pred" - -let rec iter_function_range f i e = - if i = e then () else - match i with - | At_end _ -> raise (Invalid_argument "Invalid function range.") - | Before fn -> - f fn; - iter_function_range f (function_succ fn) e - -let iter_functions f m = - iter_function_range f (function_begin m) (At_end m) - -let rec fold_left_function_range f init i e = - if i = e then init else - match i with - | At_end _ -> raise (Invalid_argument "Invalid function range.") - | Before fn -> fold_left_function_range f (f init fn) (function_succ fn) e - -let fold_left_functions f init m = - fold_left_function_range f init (function_begin m) (At_end m) - -let rec rev_iter_function_range f i e = - if i = e then () else - match i with - | At_start _ -> raise (Invalid_argument "Invalid function range.") - | After fn -> - f fn; - rev_iter_function_range f (function_pred fn) e - -let rev_iter_functions f m = - rev_iter_function_range f (function_end m) (At_start m) - -let rec fold_right_function_range f i e init = - if i = e then init else - match i with - | At_start _ -> raise (Invalid_argument "Invalid function range.") - | After fn -> fold_right_function_range f (function_pred fn) e (f fn init) - -let fold_right_functions f m init = - fold_right_function_range f (function_end m) (At_start m) init - -external llvm_add_function_attr : llvalue -> llattribute -> int -> unit - = "llvm_add_function_attr" -external llvm_function_attrs : llvalue -> int -> llattribute array - = "llvm_function_attrs" -external llvm_remove_enum_function_attr : llvalue -> llattrkind -> int -> unit - = "llvm_remove_enum_function_attr" -external llvm_remove_string_function_attr : llvalue -> string -> int -> unit - = "llvm_remove_string_function_attr" - -let add_function_attr f a i = - llvm_add_function_attr f a (AttrIndex.to_int i) -let function_attrs f i = - llvm_function_attrs f (AttrIndex.to_int i) -let remove_enum_function_attr f k i = - llvm_remove_enum_function_attr f k (AttrIndex.to_int i) -let remove_string_function_attr f k i = - llvm_remove_string_function_attr f k (AttrIndex.to_int i) - -(*--... Operations on params ...............................................--*) -external params : llvalue -> llvalue array = "llvm_params" -external param : llvalue -> int -> llvalue = "llvm_param" -external param_parent : llvalue -> llvalue = "LLVMGetParamParent" -external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin" -external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ" -external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end" -external param_pred : llvalue -> (llvalue, llvalue) llrev_pos ="llvm_param_pred" - -let rec iter_param_range f i e = - if i = e then () else - match i with - | At_end _ -> raise (Invalid_argument "Invalid parameter range.") - | Before p -> - f p; - iter_param_range f (param_succ p) e - -let iter_params f fn = - iter_param_range f (param_begin fn) (At_end fn) - -let rec fold_left_param_range f init i e = - if i = e then init else - match i with - | At_end _ -> raise (Invalid_argument "Invalid parameter range.") - | Before p -> fold_left_param_range f (f init p) (param_succ p) e - -let fold_left_params f init fn = - fold_left_param_range f init (param_begin fn) (At_end fn) - -let rec rev_iter_param_range f i e = - if i = e then () else - match i with - | At_start _ -> raise (Invalid_argument "Invalid parameter range.") - | After p -> - f p; - rev_iter_param_range f (param_pred p) e - -let rev_iter_params f fn = - rev_iter_param_range f (param_end fn) (At_start fn) - -let rec fold_right_param_range f init i e = - if i = e then init else - match i with - | At_start _ -> raise (Invalid_argument "Invalid parameter range.") - | After p -> fold_right_param_range f (f p init) (param_pred p) e - -let fold_right_params f fn init = - fold_right_param_range f init (param_end fn) (At_start fn) - -(*--... Operations on basic blocks .........................................--*) -external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue" -external value_is_block : llvalue -> bool = "llvm_value_is_block" -external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock" -external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent" -external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks" -external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock" -external delete_block : llbasicblock -> unit = "llvm_delete_block" -external remove_block : llbasicblock -> unit = "llvm_remove_block" -external move_block_before : llbasicblock -> llbasicblock -> unit - = "llvm_move_block_before" -external move_block_after : llbasicblock -> llbasicblock -> unit - = "llvm_move_block_after" -external append_block : llcontext -> string -> llvalue -> llbasicblock - = "llvm_append_block" -external insert_block : llcontext -> string -> llbasicblock -> llbasicblock - = "llvm_insert_block" -external block_begin : llvalue -> (llvalue, llbasicblock) llpos - = "llvm_block_begin" -external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos - = "llvm_block_succ" -external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos - = "llvm_block_end" -external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos - = "llvm_block_pred" -external block_terminator : llbasicblock -> llvalue option = - "llvm_block_terminator" - -let rec iter_block_range f i e = - if i = e then () else - match i with - | At_end _ -> raise (Invalid_argument "Invalid block range.") - | Before bb -> - f bb; - iter_block_range f (block_succ bb) e - -let iter_blocks f fn = - iter_block_range f (block_begin fn) (At_end fn) - -let rec fold_left_block_range f init i e = - if i = e then init else - match i with - | At_end _ -> raise (Invalid_argument "Invalid block range.") - | Before bb -> fold_left_block_range f (f init bb) (block_succ bb) e - -let fold_left_blocks f init fn = - fold_left_block_range f init (block_begin fn) (At_end fn) - -let rec rev_iter_block_range f i e = - if i = e then () else - match i with - | At_start _ -> raise (Invalid_argument "Invalid block range.") - | After bb -> - f bb; - rev_iter_block_range f (block_pred bb) e - -let rev_iter_blocks f fn = - rev_iter_block_range f (block_end fn) (At_start fn) - -let rec fold_right_block_range f init i e = - if i = e then init else - match i with - | At_start _ -> raise (Invalid_argument "Invalid block range.") - | After bb -> fold_right_block_range f (f bb init) (block_pred bb) e - -let fold_right_blocks f fn init = - fold_right_block_range f init (block_end fn) (At_start fn) - -(*--... Operations on instructions .........................................--*) -external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent" -external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos - = "llvm_instr_begin" -external instr_succ : llvalue -> (llbasicblock, llvalue) llpos - = "llvm_instr_succ" -external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos - = "llvm_instr_end" -external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos - = "llvm_instr_pred" - -external instr_opcode : llvalue -> Opcode.t = "llvm_instr_get_opcode" -external icmp_predicate : llvalue -> Icmp.t option = "llvm_instr_icmp_predicate" -external fcmp_predicate : llvalue -> Fcmp.t option = "llvm_instr_fcmp_predicate" -external instr_clone : llvalue -> llvalue = "llvm_instr_clone" - -let rec iter_instrs_range f i e = - if i = e then () else - match i with - | At_end _ -> raise (Invalid_argument "Invalid instruction range.") - | Before i -> - f i; - iter_instrs_range f (instr_succ i) e - -let iter_instrs f bb = - iter_instrs_range f (instr_begin bb) (At_end bb) - -let rec fold_left_instrs_range f init i e = - if i = e then init else - match i with - | At_end _ -> raise (Invalid_argument "Invalid instruction range.") - | Before i -> fold_left_instrs_range f (f init i) (instr_succ i) e - -let fold_left_instrs f init bb = - fold_left_instrs_range f init (instr_begin bb) (At_end bb) - -let rec rev_iter_instrs_range f i e = - if i = e then () else - match i with - | At_start _ -> raise (Invalid_argument "Invalid instruction range.") - | After i -> - f i; - rev_iter_instrs_range f (instr_pred i) e - -let rev_iter_instrs f bb = - rev_iter_instrs_range f (instr_end bb) (At_start bb) - -let rec fold_right_instr_range f i e init = - if i = e then init else - match i with - | At_start _ -> raise (Invalid_argument "Invalid instruction range.") - | After i -> fold_right_instr_range f (instr_pred i) e (f i init) - -let fold_right_instrs f bb init = - fold_right_instr_range f (instr_end bb) (At_start bb) init - - -(*--... Operations on call sites ...........................................--*) -external instruction_call_conv: llvalue -> int - = "llvm_instruction_call_conv" -external set_instruction_call_conv: int -> llvalue -> unit - = "llvm_set_instruction_call_conv" - -external llvm_add_call_site_attr : llvalue -> llattribute -> int -> unit - = "llvm_add_call_site_attr" -external llvm_call_site_attrs : llvalue -> int -> llattribute array - = "llvm_call_site_attrs" -external llvm_remove_enum_call_site_attr : llvalue -> llattrkind -> int -> unit - = "llvm_remove_enum_call_site_attr" -external llvm_remove_string_call_site_attr : llvalue -> string -> int -> unit - = "llvm_remove_string_call_site_attr" - -let add_call_site_attr f a i = - llvm_add_call_site_attr f a (AttrIndex.to_int i) -let call_site_attrs f i = - llvm_call_site_attrs f (AttrIndex.to_int i) -let remove_enum_call_site_attr f k i = - llvm_remove_enum_call_site_attr f k (AttrIndex.to_int i) -let remove_string_call_site_attr f k i = - llvm_remove_string_call_site_attr f k (AttrIndex.to_int i) - -(*--... Operations on call and invoke instructions (only) ..................--*) -external num_arg_operands : llvalue -> int = "llvm_num_arg_operands" -external is_tail_call : llvalue -> bool = "llvm_is_tail_call" -external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call" -external get_normal_dest : llvalue -> llbasicblock = "LLVMGetNormalDest" -external get_unwind_dest : llvalue -> llbasicblock = "LLVMGetUnwindDest" - -(*--... Operations on load/store instructions (only) .......................--*) -external is_volatile : llvalue -> bool = "llvm_is_volatile" -external set_volatile : bool -> llvalue -> unit = "llvm_set_volatile" - -(*--... Operations on terminators ..........................................--*) - -let is_terminator llv = - let open ValueKind in - let open Opcode in - match classify_value llv with - | Instruction (Br | IndirectBr | Invoke | Resume | Ret | Switch | Unreachable) - -> true - | _ -> false - -external successor : llvalue -> int -> llbasicblock = "llvm_successor" -external set_successor : llvalue -> int -> llbasicblock -> unit - = "llvm_set_successor" -external num_successors : llvalue -> int = "llvm_num_successors" - -let successors llv = - if not (is_terminator llv) then - raise (Invalid_argument "Llvm.successors can only be used on terminators") - else - Array.init (num_successors llv) (successor llv) - -let iter_successors f llv = - if not (is_terminator llv) then - raise (Invalid_argument "Llvm.iter_successors can only be used on terminators") - else - for i = 0 to num_successors llv - 1 do - f (successor llv i) - done - -let fold_successors f llv z = - if not (is_terminator llv) then - raise (Invalid_argument "Llvm.fold_successors can only be used on terminators") - else - let n = num_successors llv in - let rec aux i acc = - if i >= n then acc - else begin - let llb = successor llv i in - aux (i+1) (f llb acc) - end - in aux 0 z - - -(*--... Operations on branches .............................................--*) -external condition : llvalue -> llvalue = "llvm_condition" -external set_condition : llvalue -> llvalue -> unit - = "llvm_set_condition" -external is_conditional : llvalue -> bool = "llvm_is_conditional" - -let get_branch llv = - if classify_value llv <> ValueKind.Instruction Opcode.Br then - None - else if is_conditional llv then - Some (`Conditional (condition llv, successor llv 0, successor llv 1)) - else - Some (`Unconditional (successor llv 0)) - -(*--... Operations on phi nodes ............................................--*) -external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit - = "llvm_add_incoming" -external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming" - -external delete_instruction : llvalue -> unit = "llvm_delete_instruction" - -(*===-- Instruction builders ----------------------------------------------===*) -external builder : llcontext -> llbuilder = "llvm_builder" -external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit - = "llvm_position_builder" -external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block" -external insert_into_builder : llvalue -> string -> llbuilder -> unit - = "llvm_insert_into_builder" - -let builder_at context ip = - let b = builder context in - position_builder ip b; - b - -let builder_before context i = builder_at context (Before i) -let builder_at_end context bb = builder_at context (At_end bb) - -let position_before i = position_builder (Before i) -let position_at_end bb = position_builder (At_end bb) - - -(*--... Metadata ...........................................................--*) -external set_current_debug_location : llbuilder -> llvalue -> unit - = "llvm_set_current_debug_location" -external clear_current_debug_location : llbuilder -> unit - = "llvm_clear_current_debug_location" -external current_debug_location : llbuilder -> llvalue option - = "llvm_current_debug_location" -external set_inst_debug_location : llbuilder -> llvalue -> unit - = "llvm_set_inst_debug_location" - - -(*--... Terminators ........................................................--*) -external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void" -external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret" -external build_aggregate_ret : llvalue array -> llbuilder -> llvalue - = "llvm_build_aggregate_ret" -external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br" -external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder -> - llvalue = "llvm_build_cond_br" -external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue - = "llvm_build_switch" -external build_malloc : lltype -> string -> llbuilder -> llvalue = - "llvm_build_malloc" -external build_array_malloc : lltype -> llvalue -> string -> llbuilder -> - llvalue = "llvm_build_array_malloc" -external build_free : llvalue -> llbuilder -> llvalue = "llvm_build_free" -external add_case : llvalue -> llvalue -> llbasicblock -> unit - = "llvm_add_case" -external switch_default_dest : llvalue -> llbasicblock = - "LLVMGetSwitchDefaultDest" -external build_indirect_br : llvalue -> int -> llbuilder -> llvalue - = "llvm_build_indirect_br" -external add_destination : llvalue -> llbasicblock -> unit - = "llvm_add_destination" -external build_invoke : llvalue -> llvalue array -> llbasicblock -> - llbasicblock -> string -> llbuilder -> llvalue - = "llvm_build_invoke_bc" "llvm_build_invoke_nat" -external build_landingpad : lltype -> llvalue -> int -> string -> llbuilder -> - llvalue = "llvm_build_landingpad" -external is_cleanup : llvalue -> bool = "llvm_is_cleanup" -external set_cleanup : llvalue -> bool -> unit = "llvm_set_cleanup" -external add_clause : llvalue -> llvalue -> unit = "llvm_add_clause" -external build_resume : llvalue -> llbuilder -> llvalue = "llvm_build_resume" -external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable" - -(*--... Arithmetic .........................................................--*) -external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_add" -external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nsw_add" -external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nuw_add" -external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_fadd" -external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_sub" -external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nsw_sub" -external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nuw_sub" -external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_fsub" -external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_mul" -external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nsw_mul" -external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nuw_mul" -external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_fmul" -external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_udiv" -external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_sdiv" -external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_exact_sdiv" -external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_fdiv" -external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_urem" -external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_srem" -external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_frem" -external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_shl" -external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_lshr" -external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_ashr" -external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_and" -external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_or" -external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_xor" -external build_neg : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_neg" -external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nsw_neg" -external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_nuw_neg" -external build_fneg : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_fneg" -external build_not : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_not" - -(*--... Memory .............................................................--*) -external build_alloca : lltype -> string -> llbuilder -> llvalue - = "llvm_build_alloca" -external build_array_alloca : lltype -> llvalue -> string -> llbuilder -> - llvalue = "llvm_build_array_alloca" -external build_load : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_load" -external build_store : llvalue -> llvalue -> llbuilder -> llvalue - = "llvm_build_store" -external build_atomicrmw : AtomicRMWBinOp.t -> llvalue -> llvalue -> - AtomicOrdering.t -> bool -> string -> llbuilder -> - llvalue - = "llvm_build_atomicrmw_bytecode" - "llvm_build_atomicrmw_native" -external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue - = "llvm_build_gep" -external build_in_bounds_gep : llvalue -> llvalue array -> string -> - llbuilder -> llvalue = "llvm_build_in_bounds_gep" -external build_struct_gep : llvalue -> int -> string -> llbuilder -> llvalue - = "llvm_build_struct_gep" - -external build_global_string : string -> string -> llbuilder -> llvalue - = "llvm_build_global_string" -external build_global_stringptr : string -> string -> llbuilder -> llvalue - = "llvm_build_global_stringptr" - -(*--... Casts ..............................................................--*) -external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_trunc" -external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_zext" -external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_sext" -external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_fptoui" -external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_fptosi" -external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_uitofp" -external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_sitofp" -external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_fptrunc" -external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_fpext" -external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_prttoint" -external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_inttoptr" -external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_bitcast" -external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue = "llvm_build_zext_or_bitcast" -external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue = "llvm_build_sext_or_bitcast" -external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue = "llvm_build_trunc_or_bitcast" -external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_pointercast" -external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_intcast" -external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_fpcast" - -(*--... Comparisons ........................................................--*) -external build_icmp : Icmp.t -> llvalue -> llvalue -> string -> - llbuilder -> llvalue = "llvm_build_icmp" -external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string -> - llbuilder -> llvalue = "llvm_build_fcmp" - -(*--... Miscellaneous instructions .........................................--*) -external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder -> - llvalue = "llvm_build_phi" -external build_empty_phi : lltype -> string -> llbuilder -> llvalue - = "llvm_build_empty_phi" -external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue - = "llvm_build_call" -external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder -> - llvalue = "llvm_build_select" -external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue - = "llvm_build_va_arg" -external build_extractelement : llvalue -> llvalue -> string -> llbuilder -> - llvalue = "llvm_build_extractelement" -external build_insertelement : llvalue -> llvalue -> llvalue -> string -> - llbuilder -> llvalue = "llvm_build_insertelement" -external build_shufflevector : llvalue -> llvalue -> llvalue -> string -> - llbuilder -> llvalue = "llvm_build_shufflevector" -external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue - = "llvm_build_extractvalue" -external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder -> - llvalue = "llvm_build_insertvalue" - -external build_is_null : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_is_null" -external build_is_not_null : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_is_not_null" -external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue - = "llvm_build_ptrdiff" -external build_freeze : llvalue -> string -> llbuilder -> llvalue - = "llvm_build_freeze" - - -(*===-- Memory buffers ----------------------------------------------------===*) - -module MemoryBuffer = struct - external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file" - external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin" - external of_string : ?name:string -> string -> llmemorybuffer - = "llvm_memorybuffer_of_string" - external as_string : llmemorybuffer -> string = "llvm_memorybuffer_as_string" - external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose" -end - - -(*===-- Pass Manager ------------------------------------------------------===*) - -module PassManager = struct - type 'a t - type any = [ `Module | `Function ] - external create : unit -> [ `Module ] t = "llvm_passmanager_create" - external create_function : llmodule -> [ `Function ] t - = "LLVMCreateFunctionPassManager" - external run_module : llmodule -> [ `Module ] t -> bool - = "llvm_passmanager_run_module" - external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize" - external run_function : llvalue -> [ `Function ] t -> bool - = "llvm_passmanager_run_function" - external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize" - external dispose : [< any ] t -> unit = "llvm_passmanager_dispose" -end diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/llvm.mli b/interpreter/llvm/src/bindings/ocaml/llvm/llvm.mli deleted file mode 100644 index c191382aee227..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/llvm.mli +++ /dev/null @@ -1,2731 +0,0 @@ -(*===-- llvm/llvm.mli - LLVM OCaml Interface ------------------------------===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Core API. - - This interface provides an OCaml API for the LLVM intermediate - representation, the classes in the VMCore library. *) - - -(** {6 Abstract types} - - These abstract types correlate directly to the LLVMCore classes. *) - -(** The top-level container for all LLVM global data. See the - [llvm::LLVMContext] class. *) -type llcontext - -(** The top-level container for all other LLVM Intermediate Representation (IR) - objects. See the [llvm::Module] class. *) -type llmodule - -(** Opaque representation of Metadata nodes. See the [llvm::Metadata] class. *) -type llmetadata - -(** Each value in the LLVM IR has a type, an instance of [lltype]. See the - [llvm::Type] class. *) -type lltype - -(** Any value in the LLVM IR. Functions, instructions, global variables, - constants, and much more are all [llvalues]. See the [llvm::Value] class. - This type covers a wide range of subclasses. *) -type llvalue - -(** Used to store users and usees of values. See the [llvm::Use] class. *) -type lluse - -(** A basic block in LLVM IR. See the [llvm::BasicBlock] class. *) -type llbasicblock - -(** Used to generate instructions in the LLVM IR. See the [llvm::LLVMBuilder] - class. *) -type llbuilder - -(** Used to represent attribute kinds. *) -type llattrkind - -(** An attribute in LLVM IR. See the [llvm::Attribute] class. *) -type llattribute - -(** Used to efficiently handle large buffers of read-only binary data. - See the [llvm::MemoryBuffer] class. *) -type llmemorybuffer - -(** The kind id of metadata attached to an instruction. *) -type llmdkind - -(** The kind of an [lltype], the result of [classify_type ty]. See the - [llvm::Type::TypeID] enumeration. *) -module TypeKind : sig - type t = - Void - | Half - | Float - | Double - | X86fp80 - | Fp128 - | Ppc_fp128 - | Label - | Integer - | Function - | Struct - | Array - | Pointer - | Vector - | Metadata - | X86_mmx - | Token - | ScalableVector - | BFloat - | X86_amx -end - -(** The linkage of a global value, accessed with {!linkage} and - {!set_linkage}. See [llvm::GlobalValue::LinkageTypes]. *) -module Linkage : sig - type t = - External - | Available_externally - | Link_once - | Link_once_odr - | Link_once_odr_auto_hide - | Weak - | Weak_odr - | Appending - | Internal - | Private - | Dllimport - | Dllexport - | External_weak - | Ghost - | Common - | Linker_private - | Linker_private_weak -end - -(** The linker visibility of a global value, accessed with {!visibility} and - {!set_visibility}. See [llvm::GlobalValue::VisibilityTypes]. *) -module Visibility : sig - type t = - Default - | Hidden - | Protected -end - -(** The DLL storage class of a global value, accessed with {!dll_storage_class} and - {!set_dll_storage_class}. See [llvm::GlobalValue::DLLStorageClassTypes]. *) -module DLLStorageClass : sig - type t = - | Default - | DLLImport - | DLLExport -end - -(** The following calling convention values may be accessed with - {!function_call_conv} and {!set_function_call_conv}. Calling - conventions are open-ended. *) -module CallConv : sig - val c : int (** [c] is the C calling convention. *) - val fast : int (** [fast] is the calling convention to allow LLVM - maximum optimization opportunities. Use only with - internal linkage. *) - val cold : int (** [cold] is the calling convention for - callee-save. *) - val x86_stdcall : int (** [x86_stdcall] is the familiar stdcall calling - convention from C. *) - val x86_fastcall : int (** [x86_fastcall] is the familiar fastcall calling - convention from C. *) -end - -(** The logical representation of an attribute. *) -module AttrRepr : sig - type t = - | Enum of llattrkind * int64 - | String of string * string -end - -(** The position of an attribute. See [LLVMAttributeIndex]. *) -module AttrIndex : sig - type t = - | Function - | Return - | Param of int -end - -(** The predicate for an integer comparison ([icmp]) instruction. - See the [llvm::ICmpInst::Predicate] enumeration. *) -module Icmp : sig - type t = - | Eq (** Equal *) - | Ne (** Not equal *) - | Ugt (** Unsigned greater than *) - | Uge (** Unsigned greater or equal *) - | Ult (** Unsigned less than *) - | Ule (** Unsigned less or equal *) - | Sgt (** Signed greater than *) - | Sge (** Signed greater or equal *) - | Slt (** Signed less than *) - | Sle (** Signed less or equal *) -end - -(** The predicate for a floating-point comparison ([fcmp]) instruction. - Ordered means that neither operand is a QNAN while unordered means - that either operand may be a QNAN. - See the [llvm::FCmpInst::Predicate] enumeration. *) -module Fcmp : sig - type t = - | False (** Always false *) - | Oeq (** Ordered and equal *) - | Ogt (** Ordered and greater than *) - | Oge (** Ordered and greater or equal *) - | Olt (** Ordered and less than *) - | Ole (** Ordered and less or equal *) - | One (** Ordered and not equal *) - | Ord (** Ordered (no operand is NaN) *) - | Uno (** Unordered (one operand at least is NaN) *) - | Ueq (** Unordered and equal *) - | Ugt (** Unordered and greater than *) - | Uge (** Unordered and greater or equal *) - | Ult (** Unordered and less than *) - | Ule (** Unordered and less or equal *) - | Une (** Unordered and not equal *) - | True (** Always true *) -end - -(** The opcodes for LLVM instructions and constant expressions. *) -module Opcode : sig - type t = - | Invalid (** Not an instruction *) - - | Ret (** Terminator Instructions *) - | Br - | Switch - | IndirectBr - | Invoke - | Invalid2 - | Unreachable - - | Add (** Standard Binary Operators *) - | FAdd - | Sub - | FSub - | Mul - | FMul - | UDiv - | SDiv - | FDiv - | URem - | SRem - | FRem - - | Shl (** Logical Operators *) - | LShr - | AShr - | And - | Or - | Xor - - | Alloca (** Memory Operators *) - | Load - | Store - | GetElementPtr - - | Trunc (** Cast Operators *) - | ZExt - | SExt - | FPToUI - | FPToSI - | UIToFP - | SIToFP - | FPTrunc - | FPExt - | PtrToInt - | IntToPtr - | BitCast - - | ICmp (** Other Operators *) - | FCmp - | PHI - | Call - | Select - | UserOp1 - | UserOp2 - | VAArg - | ExtractElement - | InsertElement - | ShuffleVector - | ExtractValue - | InsertValue - | Fence - | AtomicCmpXchg - | AtomicRMW - | Resume - | LandingPad - | AddrSpaceCast - | CleanupRet - | CatchRet - | CatchPad - | CleanupPad - | CatchSwitch - | FNeg - | CallBr - | Freeze -end - -(** The type of a clause of a [landingpad] instruction. - See [llvm::LandingPadInst::ClauseType]. *) -module LandingPadClauseTy : sig - type t = - | Catch - | Filter -end - -(** The thread local mode of a global value, accessed with {!thread_local_mode} - and {!set_thread_local_mode}. - See [llvm::GlobalVariable::ThreadLocalMode]. *) -module ThreadLocalMode : sig - type t = - | None - | GeneralDynamic - | LocalDynamic - | InitialExec - | LocalExec -end - -(** The ordering of an atomic [load], [store], [cmpxchg], [atomicrmw] or - [fence] instruction. See [llvm::AtomicOrdering]. *) -module AtomicOrdering : sig - type t = - | NotAtomic - | Unordered - | Monotonic - | Invalid (** removed due to API changes *) - | Acquire - | Release - | AcqiureRelease - | SequentiallyConsistent -end - -(** The opcode of an [atomicrmw] instruction. - See [llvm::AtomicRMWInst::BinOp]. *) -module AtomicRMWBinOp : sig - type t = - | Xchg - | Add - | Sub - | And - | Nand - | Or - | Xor - | Max - | Min - | UMax - | UMin - | FAdd - | FSub -end - -(** The kind of an [llvalue], the result of [classify_value v]. - See the various [LLVMIsA*] functions. *) -module ValueKind : sig - type t = - | NullValue - | Argument - | BasicBlock - | InlineAsm - | MDNode - | MDString - | BlockAddress - | ConstantAggregateZero - | ConstantArray - | ConstantDataArray - | ConstantDataVector - | ConstantExpr - | ConstantFP - | ConstantInt - | ConstantPointerNull - | ConstantStruct - | ConstantVector - | Function - | GlobalAlias - | GlobalIFunc - | GlobalVariable - | UndefValue - | PoisonValue - | Instruction of Opcode.t -end - -(** The kind of [Diagnostic], the result of [Diagnostic.severity d]. - See [llvm::DiagnosticSeverity]. *) -module DiagnosticSeverity : sig - type t = - | Error - | Warning - | Remark - | Note -end - -module ModuleFlagBehavior :sig - type t = - | Error - | Warning - | Require - | Override - | Append - | AppendUnique -end - -(** {6 Iteration} *) - -(** [Before b] and [At_end a] specify positions from the start of the ['b] list - of [a]. [llpos] is used to specify positions in and for forward iteration - through the various value lists maintained by the LLVM IR. *) -type ('a, 'b) llpos = -| At_end of 'a -| Before of 'b - -(** [After b] and [At_start a] specify positions from the end of the ['b] list - of [a]. [llrev_pos] is used for reverse iteration through the various value - lists maintained by the LLVM IR. *) -type ('a, 'b) llrev_pos = -| At_start of 'a -| After of 'b - - -(** {6 Exceptions} *) - -exception FeatureDisabled of string - -exception IoError of string - - -(** {6 Global configuration} *) - -(** [enable_pretty_stacktraces ()] enables LLVM's built-in stack trace code. - This intercepts the OS's crash signals and prints which component of LLVM - you were in at the time of the crash. *) -val enable_pretty_stacktrace : unit -> unit - -(** [install_fatal_error_handler f] installs [f] as LLVM's fatal error handler. - The handler will receive the reason for termination as a string. After - the handler has been executed, LLVM calls [exit(1)]. *) -val install_fatal_error_handler : (string -> unit) -> unit - -(** [reset_fatal_error_handler ()] resets LLVM's fatal error handler. *) -val reset_fatal_error_handler : unit -> unit - -(** [parse_command_line_options ?overview args] parses [args] using - the LLVM command line parser. Note that the only stable thing about this - function is its signature; you cannot rely on any particular set of command - line arguments being interpreted the same way across LLVM versions. - - See the function [llvm::cl::ParseCommandLineOptions()]. *) -val parse_command_line_options : ?overview:string -> string array -> unit - -(** {6 Context error handling} *) - -module Diagnostic : sig - type t - - (** [description d] returns a textual description of [d]. *) - val description : t -> string - - (** [severity d] returns the severity of [d]. *) - val severity : t -> DiagnosticSeverity.t -end - -(** [set_diagnostic_handler c h] set the diagnostic handler of [c] to [h]. - See the method [llvm::LLVMContext::setDiagnosticHandler]. *) -val set_diagnostic_handler : llcontext -> (Diagnostic.t -> unit) option -> unit - -(** {6 Contexts} *) - -(** [create_context ()] creates a context for storing the "global" state in - LLVM. See the constructor [llvm::LLVMContext]. *) -val create_context : unit -> llcontext - -(** [destroy_context ()] destroys a context. See the destructor - [llvm::LLVMContext::~LLVMContext]. *) -val dispose_context : llcontext -> unit - -(** See the function [LLVMGetGlobalContext]. *) -val global_context : unit -> llcontext - -(** [mdkind_id context name] returns the MDKind ID that corresponds to the - name [name] in the context [context]. See the function - [llvm::LLVMContext::getMDKindID]. *) -val mdkind_id : llcontext -> string -> llmdkind - - -(** {6 Attributes} *) - -(** [UnknownAttribute attr] is raised when a enum attribute name [name] - is not recognized by LLVM. *) -exception UnknownAttribute of string - -(** [enum_attr_kind name] returns the kind of enum attributes named [name]. - May raise [UnknownAttribute]. *) -val enum_attr_kind : string -> llattrkind - -(** [create_enum_attr context value kind] creates an enum attribute - with the supplied [kind] and [value] in [context]; if the value - is not required (as for the majority of attributes), use [0L]. - May raise [UnknownAttribute]. - See the constructor [llvm::Attribute::get]. *) -val create_enum_attr : llcontext -> string -> int64 -> llattribute - -(** [create_string_attr context kind value] creates a string attribute - with the supplied [kind] and [value] in [context]. - See the constructor [llvm::Attribute::get]. *) -val create_string_attr : llcontext -> string -> string -> llattribute - -(** [attr_of_repr context repr] creates an attribute with the supplied - representation [repr] in [context]. *) -val attr_of_repr : llcontext -> AttrRepr.t -> llattribute - -(** [repr_of_attr attr] describes the representation of attribute [attr]. *) -val repr_of_attr : llattribute -> AttrRepr.t - - -(** {6 Modules} *) - -(** [create_module context id] creates a module with the supplied module ID in - the context [context]. Modules are not garbage collected; it is mandatory - to call {!dispose_module} to free memory. See the constructor - [llvm::Module::Module]. *) -val create_module : llcontext -> string -> llmodule - -(** [dispose_module m] destroys a module [m] and all of the IR objects it - contained. All references to subordinate objects are invalidated; - referencing them will invoke undefined behavior. See the destructor - [llvm::Module::~Module]. *) -val dispose_module : llmodule -> unit - -(** [target_triple m] is the target specifier for the module [m], something like - [i686-apple-darwin8]. See the method [llvm::Module::getTargetTriple]. *) -val target_triple: llmodule -> string - -(** [target_triple triple m] changes the target specifier for the module [m] to - the string [triple]. See the method [llvm::Module::setTargetTriple]. *) -val set_target_triple: string -> llmodule -> unit - -(** [data_layout m] is the data layout specifier for the module [m], something - like [e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-...-a0:0:64-f80:128:128]. See the - method [llvm::Module::getDataLayout]. *) -val data_layout: llmodule -> string - -(** [set_data_layout s m] changes the data layout specifier for the module [m] - to the string [s]. See the method [llvm::Module::setDataLayout]. *) -val set_data_layout: string -> llmodule -> unit - -(** [dump_module m] prints the .ll representation of the module [m] to standard - error. See the method [llvm::Module::dump]. *) -val dump_module : llmodule -> unit - -(** [print_module f m] prints the .ll representation of the module [m] - to file [f]. See the method [llvm::Module::print]. *) -val print_module : string -> llmodule -> unit - -(** [string_of_llmodule m] returns the .ll representation of the module [m] - as a string. See the method [llvm::Module::print]. *) -val string_of_llmodule : llmodule -> string - -(** [set_module_inline_asm m asm] sets the inline assembler for the module. See - the method [llvm::Module::setModuleInlineAsm]. *) -val set_module_inline_asm : llmodule -> string -> unit - -(** [module_context m] returns the context of the specified module. - See the method [llvm::Module::getContext] *) -val module_context : llmodule -> llcontext - -(** [get_module_identifier m] returns the module identifier of the - specified module. See the method [llvm::Module::getModuleIdentifier] *) -val get_module_identifier : llmodule -> string - -(** [set_module_identifier m id] sets the module identifier of [m] - to [id]. See the method [llvm::Module::setModuleIdentifier] *) -val set_module_identifer : llmodule -> string -> unit - -(** [get_module_flag m k] Return the corresponding value if key [k] appears in - the module flags of [m], otherwise return None - See the method [llvm::Module::getModuleFlag] *) -val get_module_flag : llmodule -> string -> llmetadata option - -(** [add_module_flag m b k v] Add a module-level flag b, with key [k] and - value [v] to the flags metadata of module [m]. It will create the - module-level flags named metadata if it doesn't already exist. *) -val add_module_flag : llmodule -> ModuleFlagBehavior.t -> - string -> llmetadata -> unit -(** {6 Types} *) - -(** [classify_type ty] returns the {!TypeKind.t} corresponding to the type [ty]. - See the method [llvm::Type::getTypeID]. *) -val classify_type : lltype -> TypeKind.t - -(** [type_is_sized ty] returns whether the type has a size or not. - If it doesn't then it is not safe to call the [DataLayout::] methods on it. - *) -val type_is_sized : lltype -> bool - -(** [type_context ty] returns the {!llcontext} corresponding to the type [ty]. - See the method [llvm::Type::getContext]. *) -val type_context : lltype -> llcontext - -(** [dump_type ty] prints the .ll representation of the type [ty] to standard - error. See the method [llvm::Type::dump]. *) -val dump_type : lltype -> unit - -(** [string_of_lltype ty] returns a string describing the type [ty]. *) -val string_of_lltype : lltype -> string - - -(** {7 Operations on integer types} *) - -(** [i1_type c] returns an integer type of bitwidth 1 in the context [c]. See - [llvm::Type::Int1Ty]. *) -val i1_type : llcontext -> lltype - -(** [i8_type c] returns an integer type of bitwidth 8 in the context [c]. See - [llvm::Type::Int8Ty]. *) -val i8_type : llcontext -> lltype - -(** [i16_type c] returns an integer type of bitwidth 16 in the context [c]. See - [llvm::Type::Int16Ty]. *) -val i16_type : llcontext -> lltype - -(** [i32_type c] returns an integer type of bitwidth 32 in the context [c]. See - [llvm::Type::Int32Ty]. *) -val i32_type : llcontext -> lltype - -(** [i64_type c] returns an integer type of bitwidth 64 in the context [c]. See - [llvm::Type::Int64Ty]. *) -val i64_type : llcontext -> lltype - -(** [integer_type c n] returns an integer type of bitwidth [n] in the context - [c]. See the method [llvm::IntegerType::get]. *) -val integer_type : llcontext -> int -> lltype - -(** [integer_bitwidth c ty] returns the number of bits in the integer type [ty] - in the context [c]. See the method [llvm::IntegerType::getBitWidth]. *) -val integer_bitwidth : lltype -> int - - -(** {7 Operations on real types} *) - -(** [float_type c] returns the IEEE 32-bit floating point type in the context - [c]. See [llvm::Type::FloatTy]. *) -val float_type : llcontext -> lltype - -(** [double_type c] returns the IEEE 64-bit floating point type in the context - [c]. See [llvm::Type::DoubleTy]. *) -val double_type : llcontext -> lltype - -(** [x86fp80_type c] returns the x87 80-bit floating point type in the context - [c]. See [llvm::Type::X86_FP80Ty]. *) -val x86fp80_type : llcontext -> lltype - -(** [fp128_type c] returns the IEEE 128-bit floating point type in the context - [c]. See [llvm::Type::FP128Ty]. *) -val fp128_type : llcontext -> lltype - -(** [ppc_fp128_type c] returns the PowerPC 128-bit floating point type in the - context [c]. See [llvm::Type::PPC_FP128Ty]. *) -val ppc_fp128_type : llcontext -> lltype - - -(** {7 Operations on function types} *) - -(** [function_type ret_ty param_tys] returns the function type returning - [ret_ty] and taking [param_tys] as parameters. - See the method [llvm::FunctionType::get]. *) -val function_type : lltype -> lltype array -> lltype - -(** [var_arg_function_type ret_ty param_tys] is just like - [function_type ret_ty param_tys] except that it returns the function type - which also takes a variable number of arguments. - See the method [llvm::FunctionType::get]. *) -val var_arg_function_type : lltype -> lltype array -> lltype - -(** [is_var_arg fty] returns [true] if [fty] is a varargs function type, [false] - otherwise. See the method [llvm::FunctionType::isVarArg]. *) -val is_var_arg : lltype -> bool - -(** [return_type fty] gets the return type of the function type [fty]. - See the method [llvm::FunctionType::getReturnType]. *) -val return_type : lltype -> lltype - -(** [param_types fty] gets the parameter types of the function type [fty]. - See the method [llvm::FunctionType::getParamType]. *) -val param_types : lltype -> lltype array - - -(** {7 Operations on struct types} *) - -(** [struct_type context tys] returns the structure type in the context - [context] containing in the types in the array [tys]. See the method - [llvm::StructType::get]. *) -val struct_type : llcontext -> lltype array -> lltype - -(** [packed_struct_type context ys] returns the packed structure type in the - context [context] containing in the types in the array [tys]. See the method - [llvm::StructType::get]. *) -val packed_struct_type : llcontext -> lltype array -> lltype - -(** [struct_name ty] returns the name of the named structure type [ty], - or None if the structure type is not named *) -val struct_name : lltype -> string option - -(** [named_struct_type context name] returns the named structure type [name] - in the context [context]. - See the method [llvm::StructType::get]. *) -val named_struct_type : llcontext -> string -> lltype - -(** [struct_set_body ty elts ispacked] sets the body of the named struct [ty] - to the [elts] elements. - See the moethd [llvm::StructType::setBody]. *) -val struct_set_body : lltype -> lltype array -> bool -> unit - -(** [struct_element_types sty] returns the constituent types of the struct type - [sty]. See the method [llvm::StructType::getElementType]. *) -val struct_element_types : lltype -> lltype array - -(** [is_packed sty] returns [true] if the structure type [sty] is packed, - [false] otherwise. See the method [llvm::StructType::isPacked]. *) -val is_packed : lltype -> bool - -(** [is_opaque sty] returns [true] if the structure type [sty] is opaque. - [false] otherwise. See the method [llvm::StructType::isOpaque]. *) -val is_opaque : lltype -> bool - -(** [is_literal sty] returns [true] if the structure type [sty] is literal. - [false] otherwise. See the method [llvm::StructType::isLiteral]. *) -val is_literal : lltype -> bool - - -(** {7 Operations on pointer, vector, and array types} *) - -(** [subtypes ty] returns [ty]'s subtypes *) -val subtypes : lltype -> lltype array - -(** [array_type ty n] returns the array type containing [n] elements of type - [ty]. See the method [llvm::ArrayType::get]. *) -val array_type : lltype -> int -> lltype - -(** [pointer_type ty] returns the pointer type referencing objects of type - [ty] in the default address space (0). - See the method [llvm::PointerType::getUnqual]. *) -val pointer_type : lltype -> lltype - -(** [qualified_pointer_type ty as] returns the pointer type referencing objects - of type [ty] in address space [as]. - See the method [llvm::PointerType::get]. *) -val qualified_pointer_type : lltype -> int -> lltype - -(** [vector_type ty n] returns the array type containing [n] elements of the - primitive type [ty]. See the method [llvm::ArrayType::get]. *) -val vector_type : lltype -> int -> lltype - -(** [element_type ty] returns the element type of the pointer, vector, or array - type [ty]. See the method [llvm::SequentialType::get]. *) -val element_type : lltype -> lltype - -(** [element_type aty] returns the element count of the array type [aty]. - See the method [llvm::ArrayType::getNumElements]. *) -val array_length : lltype -> int - -(** [address_space pty] returns the address space qualifier of the pointer type - [pty]. See the method [llvm::PointerType::getAddressSpace]. *) -val address_space : lltype -> int - -(** [element_type ty] returns the element count of the vector type [ty]. - See the method [llvm::VectorType::getNumElements]. *) -val vector_size : lltype -> int - - -(** {7 Operations on other types} *) - -(** [void_type c] creates a type of a function which does not return any - value in the context [c]. See [llvm::Type::VoidTy]. *) -val void_type : llcontext -> lltype - -(** [label_type c] creates a type of a basic block in the context [c]. See - [llvm::Type::LabelTy]. *) -val label_type : llcontext -> lltype - -(** [x86_mmx_type c] returns the x86 64-bit MMX register type in the - context [c]. See [llvm::Type::X86_MMXTy]. *) -val x86_mmx_type : llcontext -> lltype - -(** [type_by_name m name] returns the specified type from the current module - if it exists. - See the method [llvm::Module::getTypeByName] *) -val type_by_name : llmodule -> string -> lltype option - - -(** {6 Values} *) - -(** [type_of v] returns the type of the value [v]. - See the method [llvm::Value::getType]. *) -val type_of : llvalue -> lltype - -(** [classify_value v] returns the kind of the value [v]. *) -val classify_value : llvalue -> ValueKind.t - -(** [value_name v] returns the name of the value [v]. For global values, this is - the symbol name. For instructions and basic blocks, it is the SSA register - name. It is meaningless for constants. - See the method [llvm::Value::getName]. *) -val value_name : llvalue -> string - -(** [set_value_name n v] sets the name of the value [v] to [n]. See the method - [llvm::Value::setName]. *) -val set_value_name : string -> llvalue -> unit - -(** [dump_value v] prints the .ll representation of the value [v] to standard - error. See the method [llvm::Value::dump]. *) -val dump_value : llvalue -> unit - -(** [string_of_llvalue v] returns a string describing the value [v]. *) -val string_of_llvalue : llvalue -> string - -(** [replace_all_uses_with old new] replaces all uses of the value [old] - with the value [new]. See the method [llvm::Value::replaceAllUsesWith]. *) -val replace_all_uses_with : llvalue -> llvalue -> unit - - -(** {6 Uses} *) - -(** [use_begin v] returns the first position in the use list for the value [v]. - [use_begin] and [use_succ] can e used to iterate over the use list in order. - See the method [llvm::Value::use_begin]. *) -val use_begin : llvalue -> lluse option - -(** [use_succ u] returns the use list position succeeding [u]. - See the method [llvm::use_value_iterator::operator++]. *) -val use_succ : lluse -> lluse option - -(** [user u] returns the user of the use [u]. - See the method [llvm::Use::getUser]. *) -val user : lluse -> llvalue - -(** [used_value u] returns the usee of the use [u]. - See the method [llvm::Use::getUsedValue]. *) -val used_value : lluse -> llvalue - -(** [iter_uses f v] applies function [f] to each of the users of the value [v] - in order. Tail recursive. *) -val iter_uses : (lluse -> unit) -> llvalue -> unit - -(** [fold_left_uses f init v] is [f (... (f init u1) ...) uN] where - [u1,...,uN] are the users of the value [v]. Tail recursive. *) -val fold_left_uses : ('a -> lluse -> 'a) -> 'a -> llvalue -> 'a - -(** [fold_right_uses f v init] is [f u1 (... (f uN init) ...)] where - [u1,...,uN] are the users of the value [v]. Not tail recursive. *) -val fold_right_uses : (lluse -> 'a -> 'a) -> llvalue -> 'a -> 'a - - -(** {6 Users} *) - -(** [operand v i] returns the operand at index [i] for the value [v]. See the - method [llvm::User::getOperand]. *) -val operand : llvalue -> int -> llvalue - -(** [operand_use v i] returns the use of the operand at index [i] for the value [v]. See the - method [llvm::User::getOperandUse]. *) -val operand_use : llvalue -> int -> lluse - - -(** [set_operand v i o] sets the operand of the value [v] at the index [i] to - the value [o]. - See the method [llvm::User::setOperand]. *) -val set_operand : llvalue -> int -> llvalue -> unit - -(** [num_operands v] returns the number of operands for the value [v]. - See the method [llvm::User::getNumOperands]. *) -val num_operands : llvalue -> int - - -(** [indices i] returns the indices for the ExtractValue or InsertValue - instruction [i]. - See the [llvm::getIndices] methods. *) -val indices : llvalue -> int array - -(** {7 Operations on constants of (mostly) any type} *) - -(** [is_constant v] returns [true] if the value [v] is a constant, [false] - otherwise. Similar to [llvm::isa]. *) -val is_constant : llvalue -> bool - -(** [const_null ty] returns the constant null (zero) of the type [ty]. - See the method [llvm::Constant::getNullValue]. *) -val const_null : lltype -> llvalue - -(** [const_all_ones ty] returns the constant '-1' of the integer or vector type - [ty]. See the method [llvm::Constant::getAllOnesValue]. *) -val const_all_ones : (*int|vec*)lltype -> llvalue - -(** [const_pointer_null ty] returns the constant null (zero) pointer of the type - [ty]. See the method [llvm::ConstantPointerNull::get]. *) -val const_pointer_null : lltype -> llvalue - -(** [undef ty] returns the undefined value of the type [ty]. - See the method [llvm::UndefValue::get]. *) -val undef : lltype -> llvalue - -(** [poison ty] returns the poison value of the type [ty]. - See the method [llvm::PoisonValue::get]. *) -val poison : lltype -> llvalue - -(** [is_null v] returns [true] if the value [v] is the null (zero) value. - See the method [llvm::Constant::isNullValue]. *) -val is_null : llvalue -> bool - -(** [is_undef v] returns [true] if the value [v] is an undefined value, [false] - otherwise. Similar to [llvm::isa]. *) -val is_undef : llvalue -> bool - -(** [is_poison v] returns [true] if the value [v] is a poison value, [false] - otherwise. Similar to [llvm::isa]. *) -val is_poison : llvalue -> bool - -(** [constexpr_opcode v] returns an [Opcode.t] corresponding to constexpr - value [v], or [Opcode.Invalid] if [v] is not a constexpr. *) -val constexpr_opcode : llvalue -> Opcode.t - - -(** {7 Operations on instructions} *) - -(** [has_metadata i] returns whether or not the instruction [i] has any - metadata attached to it. See the function - [llvm::Instruction::hasMetadata]. *) -val has_metadata : llvalue -> bool - -(** [metadata i kind] optionally returns the metadata associated with the - kind [kind] in the instruction [i] See the function - [llvm::Instruction::getMetadata]. *) -val metadata : llvalue -> llmdkind -> llvalue option - -(** [set_metadata i kind md] sets the metadata [md] of kind [kind] in the - instruction [i]. See the function [llvm::Instruction::setMetadata]. *) -val set_metadata : llvalue -> llmdkind -> llvalue -> unit - -(** [clear_metadata i kind] clears the metadata of kind [kind] in the - instruction [i]. See the function [llvm::Instruction::setMetadata]. *) -val clear_metadata : llvalue -> llmdkind -> unit - - -(** {7 Operations on metadata} *) - -(** [mdstring c s] returns the MDString of the string [s] in the context [c]. - See the method [llvm::MDNode::get]. *) -val mdstring : llcontext -> string -> llvalue - -(** [mdnode c elts] returns the MDNode containing the values [elts] in the - context [c]. - See the method [llvm::MDNode::get]. *) -val mdnode : llcontext -> llvalue array -> llvalue - -(** [mdnull c ] returns a null MDNode in context [c]. *) -val mdnull : llcontext -> llvalue - -(** [get_mdstring v] returns the MDString. - See the method [llvm::MDString::getString] *) -val get_mdstring : llvalue -> string option - -(** [get_mdnode_operands v] returns the operands in the MDNode. *) -(* See the method [llvm::MDNode::getOperand] *) -val get_mdnode_operands : llvalue -> llvalue array - -(** [get_named_metadata m name] returns all the MDNodes belonging to the named - metadata (if any). - See the method [llvm::NamedMDNode::getOperand]. *) -val get_named_metadata : llmodule -> string -> llvalue array - -(** [add_named_metadata_operand m name v] adds [v] as the last operand of - metadata named [name] in module [m]. If the metadata does not exist, - it is created. - See the methods [llvm::Module::getNamedMetadata()] and - [llvm::MDNode::addOperand()]. *) -val add_named_metadata_operand : llmodule -> string -> llvalue -> unit - -(** Obtain a Metadata as a Value. - See the method [llvm::ValueAsMetadata::get()]. *) -val value_as_metadata : llvalue -> llmetadata - -(** Obtain a Value as a Metadata. - See the method [llvm::MetadataAsValue::get()]. *) -val metadata_as_value : llcontext -> llmetadata -> llvalue - -(** {7 Operations on scalar constants} *) - -(** [const_int ty i] returns the integer constant of type [ty] and value [i]. - See the method [llvm::ConstantInt::get]. *) -val const_int : lltype -> int -> llvalue - -(** [const_of_int64 ty i s] returns the integer constant of type [ty] and value - [i]. [s] indicates whether the integer is signed or not. - See the method [llvm::ConstantInt::get]. *) -val const_of_int64 : lltype -> Int64.t -> bool -> llvalue - -(** [int64_of_const c] returns the int64 value of the [c] constant integer. - None is returned if this is not an integer constant, or bitwidth exceeds 64. - See the method [llvm::ConstantInt::getSExtValue].*) -val int64_of_const : llvalue -> Int64.t option - -(** [const_int_of_string ty s r] returns the integer constant of type [ty] and - value [s], with the radix [r]. See the method [llvm::ConstantInt::get]. *) -val const_int_of_string : lltype -> string -> int -> llvalue - -(** [const_float ty n] returns the floating point constant of type [ty] and - value [n]. See the method [llvm::ConstantFP::get]. *) -val const_float : lltype -> float -> llvalue - -(** [float_of_const c] returns the float value of the [c] constant float. - None is returned if this is not an float constant. - See the method [llvm::ConstantFP::getDoubleValue].*) -val float_of_const : llvalue -> float option - -(** [const_float_of_string ty s] returns the floating point constant of type - [ty] and value [n]. See the method [llvm::ConstantFP::get]. *) -val const_float_of_string : lltype -> string -> llvalue - -(** {7 Operations on composite constants} *) - -(** [const_string c s] returns the constant [i8] array with the values of the - characters in the string [s] in the context [c]. The array is not - null-terminated (but see {!const_stringz}). This value can in turn be used - as the initializer for a global variable. See the method - [llvm::ConstantArray::get]. *) -val const_string : llcontext -> string -> llvalue - -(** [const_stringz c s] returns the constant [i8] array with the values of the - characters in the string [s] and a null terminator in the context [c]. This - value can in turn be used as the initializer for a global variable. - See the method [llvm::ConstantArray::get]. *) -val const_stringz : llcontext -> string -> llvalue - -(** [const_array ty elts] returns the constant array of type - [array_type ty (Array.length elts)] and containing the values [elts]. - This value can in turn be used as the initializer for a global variable. - See the method [llvm::ConstantArray::get]. *) -val const_array : lltype -> llvalue array -> llvalue - -(** [const_struct context elts] returns the structured constant of type - [struct_type (Array.map type_of elts)] and containing the values [elts] - in the context [context]. This value can in turn be used as the initializer - for a global variable. See the method [llvm::ConstantStruct::getAnon]. *) -val const_struct : llcontext -> llvalue array -> llvalue - -(** [const_named_struct namedty elts] returns the structured constant of type - [namedty] (which must be a named structure type) and containing the values [elts]. - This value can in turn be used as the initializer - for a global variable. See the method [llvm::ConstantStruct::get]. *) -val const_named_struct : lltype -> llvalue array -> llvalue - -(** [const_packed_struct context elts] returns the structured constant of - type {!packed_struct_type} [(Array.map type_of elts)] and containing the - values [elts] in the context [context]. This value can in turn be used as - the initializer for a global variable. See the method - [llvm::ConstantStruct::get]. *) -val const_packed_struct : llcontext -> llvalue array -> llvalue - -(** [const_vector elts] returns the vector constant of type - [vector_type (type_of elts.(0)) (Array.length elts)] and containing the - values [elts]. See the method [llvm::ConstantVector::get]. *) -val const_vector : llvalue array -> llvalue - -(** [string_of_const c] returns [Some str] if [c] is a string constant, - or [None] if this is not a string constant. *) -val string_of_const : llvalue -> string option - -(** [const_element c] returns a constant for a specified index's element. - See the method ConstantDataSequential::getElementAsConstant. *) -val const_element : llvalue -> int -> llvalue - - -(** {7 Constant expressions} *) - -(** [align_of ty] returns the alignof constant for the type [ty]. This is - equivalent to [const_ptrtoint (const_gep (const_null (pointer_type {i8,ty})) - (const_int i32_type 0) (const_int i32_type 1)) i32_type], but considerably - more readable. See the method [llvm::ConstantExpr::getAlignOf]. *) -val align_of : lltype -> llvalue - -(** [size_of ty] returns the sizeof constant for the type [ty]. This is - equivalent to [const_ptrtoint (const_gep (const_null (pointer_type ty)) - (const_int i32_type 1)) i64_type], but considerably more readable. - See the method [llvm::ConstantExpr::getSizeOf]. *) -val size_of : lltype -> llvalue - -(** [const_neg c] returns the arithmetic negation of the constant [c]. - See the method [llvm::ConstantExpr::getNeg]. *) -val const_neg : llvalue -> llvalue - -(** [const_nsw_neg c] returns the arithmetic negation of the constant [c] with - no signed wrapping. The result is undefined if the negation overflows. - See the method [llvm::ConstantExpr::getNSWNeg]. *) -val const_nsw_neg : llvalue -> llvalue - -(** [const_nuw_neg c] returns the arithmetic negation of the constant [c] with - no unsigned wrapping. The result is undefined if the negation overflows. - See the method [llvm::ConstantExpr::getNUWNeg]. *) -val const_nuw_neg : llvalue -> llvalue - -(** [const_fneg c] returns the arithmetic negation of the constant float [c]. - See the method [llvm::ConstantExpr::getFNeg]. *) -val const_fneg : llvalue -> llvalue - -(** [const_not c] returns the bitwise inverse of the constant [c]. - See the method [llvm::ConstantExpr::getNot]. *) -val const_not : llvalue -> llvalue - -(** [const_add c1 c2] returns the constant sum of two constants. - See the method [llvm::ConstantExpr::getAdd]. *) -val const_add : llvalue -> llvalue -> llvalue - -(** [const_nsw_add c1 c2] returns the constant sum of two constants with no - signed wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWAdd]. *) -val const_nsw_add : llvalue -> llvalue -> llvalue - -(** [const_nuw_add c1 c2] returns the constant sum of two constants with no - unsigned wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWAdd]. *) -val const_nuw_add : llvalue -> llvalue -> llvalue - -(** [const_fadd c1 c2] returns the constant sum of two constant floats. - See the method [llvm::ConstantExpr::getFAdd]. *) -val const_fadd : llvalue -> llvalue -> llvalue - -(** [const_sub c1 c2] returns the constant difference, [c1 - c2], of two - constants. See the method [llvm::ConstantExpr::getSub]. *) -val const_sub : llvalue -> llvalue -> llvalue - -(** [const_nsw_sub c1 c2] returns the constant difference of two constants with - no signed wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWSub]. *) -val const_nsw_sub : llvalue -> llvalue -> llvalue - -(** [const_nuw_sub c1 c2] returns the constant difference of two constants with - no unsigned wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWSub]. *) -val const_nuw_sub : llvalue -> llvalue -> llvalue - -(** [const_fsub c1 c2] returns the constant difference, [c1 - c2], of two - constant floats. See the method [llvm::ConstantExpr::getFSub]. *) -val const_fsub : llvalue -> llvalue -> llvalue - -(** [const_mul c1 c2] returns the constant product of two constants. - See the method [llvm::ConstantExpr::getMul]. *) -val const_mul : llvalue -> llvalue -> llvalue - -(** [const_nsw_mul c1 c2] returns the constant product of two constants with - no signed wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWMul]. *) -val const_nsw_mul : llvalue -> llvalue -> llvalue - -(** [const_nuw_mul c1 c2] returns the constant product of two constants with - no unsigned wrapping. The result is undefined if the sum overflows. - See the method [llvm::ConstantExpr::getNSWMul]. *) -val const_nuw_mul : llvalue -> llvalue -> llvalue - -(** [const_fmul c1 c2] returns the constant product of two constants floats. - See the method [llvm::ConstantExpr::getFMul]. *) -val const_fmul : llvalue -> llvalue -> llvalue - -(** [const_udiv c1 c2] returns the constant quotient [c1 / c2] of two unsigned - integer constants. - See the method [llvm::ConstantExpr::getUDiv]. *) -val const_udiv : llvalue -> llvalue -> llvalue - -(** [const_sdiv c1 c2] returns the constant quotient [c1 / c2] of two signed - integer constants. - See the method [llvm::ConstantExpr::getSDiv]. *) -val const_sdiv : llvalue -> llvalue -> llvalue - -(** [const_exact_sdiv c1 c2] returns the constant quotient [c1 / c2] of two - signed integer constants. The result is undefined if the result is rounded - or overflows. See the method [llvm::ConstantExpr::getExactSDiv]. *) -val const_exact_sdiv : llvalue -> llvalue -> llvalue - -(** [const_fdiv c1 c2] returns the constant quotient [c1 / c2] of two floating - point constants. - See the method [llvm::ConstantExpr::getFDiv]. *) -val const_fdiv : llvalue -> llvalue -> llvalue - -(** [const_urem c1 c2] returns the constant remainder [c1 MOD c2] of two - unsigned integer constants. - See the method [llvm::ConstantExpr::getURem]. *) -val const_urem : llvalue -> llvalue -> llvalue - -(** [const_srem c1 c2] returns the constant remainder [c1 MOD c2] of two - signed integer constants. - See the method [llvm::ConstantExpr::getSRem]. *) -val const_srem : llvalue -> llvalue -> llvalue - -(** [const_frem c1 c2] returns the constant remainder [c1 MOD c2] of two - signed floating point constants. - See the method [llvm::ConstantExpr::getFRem]. *) -val const_frem : llvalue -> llvalue -> llvalue - -(** [const_and c1 c2] returns the constant bitwise [AND] of two integer - constants. - See the method [llvm::ConstantExpr::getAnd]. *) -val const_and : llvalue -> llvalue -> llvalue - -(** [const_or c1 c2] returns the constant bitwise [OR] of two integer - constants. - See the method [llvm::ConstantExpr::getOr]. *) -val const_or : llvalue -> llvalue -> llvalue - -(** [const_xor c1 c2] returns the constant bitwise [XOR] of two integer - constants. - See the method [llvm::ConstantExpr::getXor]. *) -val const_xor : llvalue -> llvalue -> llvalue - -(** [const_icmp pred c1 c2] returns the constant comparison of two integer - constants, [c1 pred c2]. - See the method [llvm::ConstantExpr::getICmp]. *) -val const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue - -(** [const_fcmp pred c1 c2] returns the constant comparison of two floating - point constants, [c1 pred c2]. - See the method [llvm::ConstantExpr::getFCmp]. *) -val const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue - -(** [const_shl c1 c2] returns the constant integer [c1] left-shifted by the - constant integer [c2]. - See the method [llvm::ConstantExpr::getShl]. *) -val const_shl : llvalue -> llvalue -> llvalue - -(** [const_lshr c1 c2] returns the constant integer [c1] right-shifted by the - constant integer [c2] with zero extension. - See the method [llvm::ConstantExpr::getLShr]. *) -val const_lshr : llvalue -> llvalue -> llvalue - -(** [const_ashr c1 c2] returns the constant integer [c1] right-shifted by the - constant integer [c2] with sign extension. - See the method [llvm::ConstantExpr::getAShr]. *) -val const_ashr : llvalue -> llvalue -> llvalue - -(** [const_gep pc indices] returns the constant [getElementPtr] of [pc] with the - constant integers indices from the array [indices]. - See the method [llvm::ConstantExpr::getGetElementPtr]. *) -val const_gep : llvalue -> llvalue array -> llvalue - -(** [const_in_bounds_gep pc indices] returns the constant [getElementPtr] of [pc] - with the constant integers indices from the array [indices]. - See the method [llvm::ConstantExpr::getInBoundsGetElementPtr]. *) -val const_in_bounds_gep : llvalue -> llvalue array -> llvalue - -(** [const_trunc c ty] returns the constant truncation of integer constant [c] - to the smaller integer type [ty]. - See the method [llvm::ConstantExpr::getTrunc]. *) -val const_trunc : llvalue -> lltype -> llvalue - -(** [const_sext c ty] returns the constant sign extension of integer constant - [c] to the larger integer type [ty]. - See the method [llvm::ConstantExpr::getSExt]. *) -val const_sext : llvalue -> lltype -> llvalue - -(** [const_zext c ty] returns the constant zero extension of integer constant - [c] to the larger integer type [ty]. - See the method [llvm::ConstantExpr::getZExt]. *) -val const_zext : llvalue -> lltype -> llvalue - -(** [const_fptrunc c ty] returns the constant truncation of floating point - constant [c] to the smaller floating point type [ty]. - See the method [llvm::ConstantExpr::getFPTrunc]. *) -val const_fptrunc : llvalue -> lltype -> llvalue - -(** [const_fpext c ty] returns the constant extension of floating point constant - [c] to the larger floating point type [ty]. - See the method [llvm::ConstantExpr::getFPExt]. *) -val const_fpext : llvalue -> lltype -> llvalue - -(** [const_uitofp c ty] returns the constant floating point conversion of - unsigned integer constant [c] to the floating point type [ty]. - See the method [llvm::ConstantExpr::getUIToFP]. *) -val const_uitofp : llvalue -> lltype -> llvalue - -(** [const_sitofp c ty] returns the constant floating point conversion of - signed integer constant [c] to the floating point type [ty]. - See the method [llvm::ConstantExpr::getSIToFP]. *) -val const_sitofp : llvalue -> lltype -> llvalue - -(** [const_fptoui c ty] returns the constant unsigned integer conversion of - floating point constant [c] to integer type [ty]. - See the method [llvm::ConstantExpr::getFPToUI]. *) -val const_fptoui : llvalue -> lltype -> llvalue - -(** [const_fptoui c ty] returns the constant unsigned integer conversion of - floating point constant [c] to integer type [ty]. - See the method [llvm::ConstantExpr::getFPToSI]. *) -val const_fptosi : llvalue -> lltype -> llvalue - -(** [const_ptrtoint c ty] returns the constant integer conversion of - pointer constant [c] to integer type [ty]. - See the method [llvm::ConstantExpr::getPtrToInt]. *) -val const_ptrtoint : llvalue -> lltype -> llvalue - -(** [const_inttoptr c ty] returns the constant pointer conversion of - integer constant [c] to pointer type [ty]. - See the method [llvm::ConstantExpr::getIntToPtr]. *) -val const_inttoptr : llvalue -> lltype -> llvalue - -(** [const_bitcast c ty] returns the constant bitwise conversion of constant [c] - to type [ty] of equal size. - See the method [llvm::ConstantExpr::getBitCast]. *) -val const_bitcast : llvalue -> lltype -> llvalue - -(** [const_zext_or_bitcast c ty] returns a constant zext or bitwise cast - conversion of constant [c] to type [ty]. - See the method [llvm::ConstantExpr::getZExtOrBitCast]. *) -val const_zext_or_bitcast : llvalue -> lltype -> llvalue - -(** [const_sext_or_bitcast c ty] returns a constant sext or bitwise cast - conversion of constant [c] to type [ty]. - See the method [llvm::ConstantExpr::getSExtOrBitCast]. *) -val const_sext_or_bitcast : llvalue -> lltype -> llvalue - -(** [const_trunc_or_bitcast c ty] returns a constant trunc or bitwise cast - conversion of constant [c] to type [ty]. - See the method [llvm::ConstantExpr::getTruncOrBitCast]. *) -val const_trunc_or_bitcast : llvalue -> lltype -> llvalue - -(** [const_pointercast c ty] returns a constant bitcast or a pointer-to-int - cast conversion of constant [c] to type [ty] of equal size. - See the method [llvm::ConstantExpr::getPointerCast]. *) -val const_pointercast : llvalue -> lltype -> llvalue - -(** [const_intcast c ty ~is_signed] returns a constant sext/zext, bitcast, - or trunc for integer -> integer casts of constant [c] to type [ty]. - When converting a narrower value to a wider one, whether sext or zext - will be used is controlled by [is_signed]. - See the method [llvm::ConstantExpr::getIntegerCast]. *) -val const_intcast : llvalue -> lltype -> is_signed:bool -> llvalue - -(** [const_fpcast c ty] returns a constant fpext, bitcast, or fptrunc for fp -> - fp casts of constant [c] to type [ty]. - See the method [llvm::ConstantExpr::getFPCast]. *) -val const_fpcast : llvalue -> lltype -> llvalue - -(** [const_select cond t f] returns the constant conditional which returns value - [t] if the boolean constant [cond] is true and the value [f] otherwise. - See the method [llvm::ConstantExpr::getSelect]. *) -val const_select : llvalue -> llvalue -> llvalue -> llvalue - -(** [const_extractelement vec i] returns the constant [i]th element of - constant vector [vec]. [i] must be a constant [i32] value unsigned less than - the size of the vector. - See the method [llvm::ConstantExpr::getExtractElement]. *) -val const_extractelement : llvalue -> llvalue -> llvalue - -(** [const_insertelement vec v i] returns the constant vector with the same - elements as constant vector [v] but the [i]th element replaced by the - constant [v]. [v] must be a constant value with the type of the vector - elements. [i] must be a constant [i32] value unsigned less than the size - of the vector. - See the method [llvm::ConstantExpr::getInsertElement]. *) -val const_insertelement : llvalue -> llvalue -> llvalue -> llvalue - -(** [const_shufflevector a b mask] returns a constant [shufflevector]. - See the LLVM Language Reference for details on the [shufflevector] - instruction. - See the method [llvm::ConstantExpr::getShuffleVector]. *) -val const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue - -(** [const_extractvalue agg idxs] returns the constant [idxs]th value of - constant aggregate [agg]. Each [idxs] must be less than the size of the - aggregate. See the method [llvm::ConstantExpr::getExtractValue]. *) -val const_extractvalue : llvalue -> int array -> llvalue - -(** [const_insertvalue agg val idxs] inserts the value [val] in the specified - indexs [idxs] in the aggregate [agg]. Each [idxs] must be less than the size - of the aggregate. See the method [llvm::ConstantExpr::getInsertValue]. *) -val const_insertvalue : llvalue -> llvalue -> int array -> llvalue - -(** [const_inline_asm ty asm con side align] inserts a inline assembly string. - See the method [llvm::InlineAsm::get]. *) -val const_inline_asm : lltype -> string -> string -> bool -> bool -> llvalue - -(** [block_address f bb] returns the address of the basic block [bb] in the - function [f]. See the method [llvm::BasicBlock::get]. *) -val block_address : llvalue -> llbasicblock -> llvalue - - -(** {7 Operations on global variables, functions, and aliases (globals)} *) - -(** [global_parent g] is the enclosing module of the global value [g]. - See the method [llvm::GlobalValue::getParent]. *) -val global_parent : llvalue -> llmodule - -(** [is_declaration g] returns [true] if the global value [g] is a declaration - only. Returns [false] otherwise. - See the method [llvm::GlobalValue::isDeclaration]. *) -val is_declaration : llvalue -> bool - -(** [linkage g] returns the linkage of the global value [g]. - See the method [llvm::GlobalValue::getLinkage]. *) -val linkage : llvalue -> Linkage.t - -(** [set_linkage l g] sets the linkage of the global value [g] to [l]. - See the method [llvm::GlobalValue::setLinkage]. *) -val set_linkage : Linkage.t -> llvalue -> unit - -(** [unnamed_addr g] returns [true] if the global value [g] has the unnamed_addr - attribute. Returns [false] otherwise. - See the method [llvm::GlobalValue::getUnnamedAddr]. *) -val unnamed_addr : llvalue -> bool - -(** [set_unnamed_addr b g] if [b] is [true], sets the unnamed_addr attribute of - the global value [g]. Unset it otherwise. - See the method [llvm::GlobalValue::setUnnamedAddr]. *) -val set_unnamed_addr : bool -> llvalue -> unit - -(** [section g] returns the linker section of the global value [g]. - See the method [llvm::GlobalValue::getSection]. *) -val section : llvalue -> string - -(** [set_section s g] sets the linker section of the global value [g] to [s]. - See the method [llvm::GlobalValue::setSection]. *) -val set_section : string -> llvalue -> unit - -(** [visibility g] returns the linker visibility of the global value [g]. - See the method [llvm::GlobalValue::getVisibility]. *) -val visibility : llvalue -> Visibility.t - -(** [set_visibility v g] sets the linker visibility of the global value [g] to - [v]. See the method [llvm::GlobalValue::setVisibility]. *) -val set_visibility : Visibility.t -> llvalue -> unit - -(** [dll_storage_class g] returns the DLL storage class of the global value [g]. - See the method [llvm::GlobalValue::getDLLStorageClass]. *) -val dll_storage_class : llvalue -> DLLStorageClass.t - -(** [set_dll_storage_class v g] sets the DLL storage class of the global value [g] to - [v]. See the method [llvm::GlobalValue::setDLLStorageClass]. *) -val set_dll_storage_class : DLLStorageClass.t -> llvalue -> unit - -(** [alignment g] returns the required alignment of the global value [g]. - See the method [llvm::GlobalValue::getAlignment]. *) -val alignment : llvalue -> int - -(** [set_alignment n g] sets the required alignment of the global value [g] to - [n] bytes. See the method [llvm::GlobalValue::setAlignment]. *) -val set_alignment : int -> llvalue -> unit - -(** [global_copy_all_metadata g] returns all the metadata associated with [g], - which must be an [Instruction] or [GlobalObject]. - See the [llvm::Instruction::getAllMetadata()] and - [llvm::GlobalObject::getAllMetadata()] methods. *) -val global_copy_all_metadata : llvalue -> (llmdkind * llmetadata) array - - -(** {7 Operations on global variables} *) - -(** [declare_global ty name m] returns a new global variable of type [ty] and - with name [name] in module [m] in the default address space (0). If such a - global variable already exists, it is returned. If the type of the existing - global differs, then a bitcast to [ty] is returned. *) -val declare_global : lltype -> string -> llmodule -> llvalue - -(** [declare_qualified_global ty name addrspace m] returns a new global variable - of type [ty] and with name [name] in module [m] in the address space - [addrspace]. If such a global variable already exists, it is returned. If - the type of the existing global differs, then a bitcast to [ty] is - returned. *) -val declare_qualified_global : lltype -> string -> int -> llmodule -> llvalue - -(** [define_global name init m] returns a new global with name [name] and - initializer [init] in module [m] in the default address space (0). If the - named global already exists, it is renamed. - See the constructor of [llvm::GlobalVariable]. *) -val define_global : string -> llvalue -> llmodule -> llvalue - -(** [define_qualified_global name init addrspace m] returns a new global with - name [name] and initializer [init] in module [m] in the address space - [addrspace]. If the named global already exists, it is renamed. - See the constructor of [llvm::GlobalVariable]. *) -val define_qualified_global : string -> llvalue -> int -> llmodule -> llvalue - -(** [lookup_global name m] returns [Some g] if a global variable with name - [name] exists in module [m]. If no such global exists, returns [None]. - See the [llvm::GlobalVariable] constructor. *) -val lookup_global : string -> llmodule -> llvalue option - -(** [delete_global gv] destroys the global variable [gv]. - See the method [llvm::GlobalVariable::eraseFromParent]. *) -val delete_global : llvalue -> unit - -(** [global_begin m] returns the first position in the global variable list of - the module [m]. [global_begin] and [global_succ] can be used to iterate - over the global list in order. - See the method [llvm::Module::global_begin]. *) -val global_begin : llmodule -> (llmodule, llvalue) llpos - -(** [global_succ gv] returns the global variable list position succeeding - [Before gv]. - See the method [llvm::Module::global_iterator::operator++]. *) -val global_succ : llvalue -> (llmodule, llvalue) llpos - -(** [iter_globals f m] applies function [f] to each of the global variables of - module [m] in order. Tail recursive. *) -val iter_globals : (llvalue -> unit) -> llmodule -> unit - -(** [fold_left_globals f init m] is [f (... (f init g1) ...) gN] where - [g1,...,gN] are the global variables of module [m]. Tail recursive. *) -val fold_left_globals : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a - -(** [global_end m] returns the last position in the global variable list of the - module [m]. [global_end] and [global_pred] can be used to iterate over the - global list in reverse. - See the method [llvm::Module::global_end]. *) -val global_end : llmodule -> (llmodule, llvalue) llrev_pos - -(** [global_pred gv] returns the global variable list position preceding - [After gv]. - See the method [llvm::Module::global_iterator::operator--]. *) -val global_pred : llvalue -> (llmodule, llvalue) llrev_pos - -(** [rev_iter_globals f m] applies function [f] to each of the global variables - of module [m] in reverse order. Tail recursive. *) -val rev_iter_globals : (llvalue -> unit) -> llmodule -> unit - -(** [fold_right_globals f m init] is [f g1 (... (f gN init) ...)] where - [g1,...,gN] are the global variables of module [m]. Tail recursive. *) -val fold_right_globals : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a - -(** [is_global_constant gv] returns [true] if the global variabile [gv] is a - constant. Returns [false] otherwise. - See the method [llvm::GlobalVariable::isConstant]. *) -val is_global_constant : llvalue -> bool - -(** [set_global_constant c gv] sets the global variable [gv] to be a constant if - [c] is [true] and not if [c] is [false]. - See the method [llvm::GlobalVariable::setConstant]. *) -val set_global_constant : bool -> llvalue -> unit - -(** [global_initializer gv] If global variable [gv] has an initializer it is returned, - otherwise returns [None]. See the method [llvm::GlobalVariable::getInitializer]. *) -val global_initializer : llvalue -> llvalue option - -(** [set_initializer c gv] sets the initializer for the global variable - [gv] to the constant [c]. - See the method [llvm::GlobalVariable::setInitializer]. *) -val set_initializer : llvalue -> llvalue -> unit - -(** [remove_initializer gv] unsets the initializer for the global variable - [gv]. - See the method [llvm::GlobalVariable::setInitializer]. *) -val remove_initializer : llvalue -> unit - -(** [is_thread_local gv] returns [true] if the global variable [gv] is - thread-local and [false] otherwise. - See the method [llvm::GlobalVariable::isThreadLocal]. *) -val is_thread_local : llvalue -> bool - -(** [set_thread_local c gv] sets the global variable [gv] to be thread local if - [c] is [true] and not otherwise. - See the method [llvm::GlobalVariable::setThreadLocal]. *) -val set_thread_local : bool -> llvalue -> unit - -(** [is_thread_local gv] returns the thread local mode of the global - variable [gv]. - See the method [llvm::GlobalVariable::getThreadLocalMode]. *) -val thread_local_mode : llvalue -> ThreadLocalMode.t - -(** [set_thread_local c gv] sets the thread local mode of the global - variable [gv]. - See the method [llvm::GlobalVariable::setThreadLocalMode]. *) -val set_thread_local_mode : ThreadLocalMode.t -> llvalue -> unit - -(** [is_externally_initialized gv] returns [true] if the global - variable [gv] is externally initialized and [false] otherwise. - See the method [llvm::GlobalVariable::isExternallyInitialized]. *) -val is_externally_initialized : llvalue -> bool - -(** [set_externally_initialized c gv] sets the global variable [gv] to be - externally initialized if [c] is [true] and not otherwise. - See the method [llvm::GlobalVariable::setExternallyInitialized]. *) -val set_externally_initialized : bool -> llvalue -> unit - - -(** {7 Operations on aliases} *) - -(** [add_alias m t a n] inserts an alias in the module [m] with the type [t] and - the aliasee [a] with the name [n]. - See the constructor for [llvm::GlobalAlias]. *) -val add_alias : llmodule -> lltype -> llvalue -> string -> llvalue - - -(** {7 Operations on functions} *) - -(** [declare_function name ty m] returns a new function of type [ty] and - with name [name] in module [m]. If such a function already exists, - it is returned. If the type of the existing function differs, then a bitcast - to [ty] is returned. *) -val declare_function : string -> lltype -> llmodule -> llvalue - -(** [define_function name ty m] creates a new function with name [name] and - type [ty] in module [m]. If the named function already exists, it is - renamed. An entry basic block is created in the function. - See the constructor of [llvm::GlobalVariable]. *) -val define_function : string -> lltype -> llmodule -> llvalue - -(** [lookup_function name m] returns [Some f] if a function with name - [name] exists in module [m]. If no such function exists, returns [None]. - See the method [llvm::Module] constructor. *) -val lookup_function : string -> llmodule -> llvalue option - -(** [delete_function f] destroys the function [f]. - See the method [llvm::Function::eraseFromParent]. *) -val delete_function : llvalue -> unit - -(** [function_begin m] returns the first position in the function list of the - module [m]. [function_begin] and [function_succ] can be used to iterate over - the function list in order. - See the method [llvm::Module::begin]. *) -val function_begin : llmodule -> (llmodule, llvalue) llpos - -(** [function_succ gv] returns the function list position succeeding - [Before gv]. - See the method [llvm::Module::iterator::operator++]. *) -val function_succ : llvalue -> (llmodule, llvalue) llpos - -(** [iter_functions f m] applies function [f] to each of the functions of module - [m] in order. Tail recursive. *) -val iter_functions : (llvalue -> unit) -> llmodule -> unit - -(** [fold_left_function f init m] is [f (... (f init f1) ...) fN] where - [f1,...,fN] are the functions of module [m]. Tail recursive. *) -val fold_left_functions : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a - -(** [function_end m] returns the last position in the function list of - the module [m]. [function_end] and [function_pred] can be used to iterate - over the function list in reverse. - See the method [llvm::Module::end]. *) -val function_end : llmodule -> (llmodule, llvalue) llrev_pos - -(** [function_pred gv] returns the function list position preceding [After gv]. - See the method [llvm::Module::iterator::operator--]. *) -val function_pred : llvalue -> (llmodule, llvalue) llrev_pos - -(** [rev_iter_functions f fn] applies function [f] to each of the functions of - module [m] in reverse order. Tail recursive. *) -val rev_iter_functions : (llvalue -> unit) -> llmodule -> unit - -(** [fold_right_functions f m init] is [f (... (f init fN) ...) f1] where - [f1,...,fN] are the functions of module [m]. Tail recursive. *) -val fold_right_functions : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a - -(** [is_intrinsic f] returns true if the function [f] is an intrinsic. - See the method [llvm::Function::isIntrinsic]. *) -val is_intrinsic : llvalue -> bool - -(** [function_call_conv f] returns the calling convention of the function [f]. - See the method [llvm::Function::getCallingConv]. *) -val function_call_conv : llvalue -> int - -(** [set_function_call_conv cc f] sets the calling convention of the function - [f] to the calling convention numbered [cc]. - See the method [llvm::Function::setCallingConv]. *) -val set_function_call_conv : int -> llvalue -> unit - -(** [gc f] returns [Some name] if the function [f] has a garbage - collection algorithm specified and [None] otherwise. - See the method [llvm::Function::getGC]. *) -val gc : llvalue -> string option - -(** [set_gc gc f] sets the collection algorithm for the function [f] to - [gc]. See the method [llvm::Function::setGC]. *) -val set_gc : string option -> llvalue -> unit - -(** [add_function_attr f a i] adds attribute [a] to the function [f] - at position [i]. *) -val add_function_attr : llvalue -> llattribute -> AttrIndex.t -> unit - -(** [function_attrs f i] returns the attributes for the function [f] - at position [i]. *) -val function_attrs : llvalue -> AttrIndex.t -> llattribute array - -(** [remove_enum_function_attr f k i] removes enum attribute with kind [k] - from the function [f] at position [i]. *) -val remove_enum_function_attr : llvalue -> llattrkind -> AttrIndex.t -> unit - -(** [remove_string_function_attr f k i] removes string attribute with kind [k] - from the function [f] at position [i]. *) -val remove_string_function_attr : llvalue -> string -> AttrIndex.t -> unit - - -(** {7 Operations on params} *) - -(** [params f] returns the parameters of function [f]. - See the method [llvm::Function::getArgumentList]. *) -val params : llvalue -> llvalue array - -(** [param f n] returns the [n]th parameter of function [f]. - See the method [llvm::Function::getArgumentList]. *) -val param : llvalue -> int -> llvalue - -(** [param_parent p] returns the parent function that owns the parameter. - See the method [llvm::Argument::getParent]. *) -val param_parent : llvalue -> llvalue - -(** [param_begin f] returns the first position in the parameter list of the - function [f]. [param_begin] and [param_succ] can be used to iterate over - the parameter list in order. - See the method [llvm::Function::arg_begin]. *) -val param_begin : llvalue -> (llvalue, llvalue) llpos - -(** [param_succ bb] returns the parameter list position succeeding - [Before bb]. - See the method [llvm::Function::arg_iterator::operator++]. *) -val param_succ : llvalue -> (llvalue, llvalue) llpos - -(** [iter_params f fn] applies function [f] to each of the parameters - of function [fn] in order. Tail recursive. *) -val iter_params : (llvalue -> unit) -> llvalue -> unit - -(** [fold_left_params f init fn] is [f (... (f init b1) ...) bN] where - [b1,...,bN] are the parameters of function [fn]. Tail recursive. *) -val fold_left_params : ('a -> llvalue -> 'a) -> 'a -> llvalue -> 'a - -(** [param_end f] returns the last position in the parameter list of - the function [f]. [param_end] and [param_pred] can be used to iterate - over the parameter list in reverse. - See the method [llvm::Function::arg_end]. *) -val param_end : llvalue -> (llvalue, llvalue) llrev_pos - -(** [param_pred gv] returns the function list position preceding [After gv]. - See the method [llvm::Function::arg_iterator::operator--]. *) -val param_pred : llvalue -> (llvalue, llvalue) llrev_pos - -(** [rev_iter_params f fn] applies function [f] to each of the parameters - of function [fn] in reverse order. Tail recursive. *) -val rev_iter_params : (llvalue -> unit) -> llvalue -> unit - -(** [fold_right_params f fn init] is [f (... (f init bN) ...) b1] where - [b1,...,bN] are the parameters of function [fn]. Tail recursive. *) -val fold_right_params : (llvalue -> 'a -> 'a) -> llvalue -> 'a -> 'a - - -(** {7 Operations on basic blocks} *) - -(** [basic_blocks fn] returns the basic blocks of the function [f]. - See the method [llvm::Function::getBasicBlockList]. *) -val basic_blocks : llvalue -> llbasicblock array - -(** [entry_block fn] returns the entry basic block of the function [f]. - See the method [llvm::Function::getEntryBlock]. *) -val entry_block : llvalue -> llbasicblock - -(** [delete_block bb] deletes the basic block [bb]. - See the method [llvm::BasicBlock::eraseFromParent]. *) -val delete_block : llbasicblock -> unit - -(** [remove_block bb] removes the basic block [bb] from its parent function. - See the method [llvm::BasicBlock::removeFromParent]. *) -val remove_block : llbasicblock -> unit - -(** [move_block_before pos bb] moves the basic block [bb] before [pos]. - See the method [llvm::BasicBlock::moveBefore]. *) -val move_block_before : llbasicblock -> llbasicblock -> unit - -(** [move_block_after pos bb] moves the basic block [bb] after [pos]. - See the method [llvm::BasicBlock::moveAfter]. *) -val move_block_after : llbasicblock -> llbasicblock -> unit - -(** [append_block c name f] creates a new basic block named [name] at the end of - function [f] in the context [c]. - See the constructor of [llvm::BasicBlock]. *) -val append_block : llcontext -> string -> llvalue -> llbasicblock - -(** [insert_block c name bb] creates a new basic block named [name] before the - basic block [bb] in the context [c]. - See the constructor of [llvm::BasicBlock]. *) -val insert_block : llcontext -> string -> llbasicblock -> llbasicblock - -(** [block_parent bb] returns the parent function that owns the basic block. - See the method [llvm::BasicBlock::getParent]. *) -val block_parent : llbasicblock -> llvalue - -(** [block_begin f] returns the first position in the basic block list of the - function [f]. [block_begin] and [block_succ] can be used to iterate over - the basic block list in order. - See the method [llvm::Function::begin]. *) -val block_begin : llvalue -> (llvalue, llbasicblock) llpos - -(** [block_succ bb] returns the basic block list position succeeding - [Before bb]. - See the method [llvm::Function::iterator::operator++]. *) -val block_succ : llbasicblock -> (llvalue, llbasicblock) llpos - -(** [iter_blocks f fn] applies function [f] to each of the basic blocks - of function [fn] in order. Tail recursive. *) -val iter_blocks : (llbasicblock -> unit) -> llvalue -> unit - -(** [fold_left_blocks f init fn] is [f (... (f init b1) ...) bN] where - [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *) -val fold_left_blocks : ('a -> llbasicblock -> 'a) -> 'a -> llvalue -> 'a - -(** [block_end f] returns the last position in the basic block list of - the function [f]. [block_end] and [block_pred] can be used to iterate - over the basic block list in reverse. - See the method [llvm::Function::end]. *) -val block_end : llvalue -> (llvalue, llbasicblock) llrev_pos - -(** [block_pred bb] returns the basic block list position preceding [After bb]. - See the method [llvm::Function::iterator::operator--]. *) -val block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos - -(** [block_terminator bb] returns the terminator of the basic block [bb]. *) -val block_terminator : llbasicblock -> llvalue option - -(** [rev_iter_blocks f fn] applies function [f] to each of the basic blocks - of function [fn] in reverse order. Tail recursive. *) -val rev_iter_blocks : (llbasicblock -> unit) -> llvalue -> unit - -(** [fold_right_blocks f fn init] is [f (... (f init bN) ...) b1] where - [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *) -val fold_right_blocks : (llbasicblock -> 'a -> 'a) -> llvalue -> 'a -> 'a - -(** [value_of_block bb] losslessly casts [bb] to an [llvalue]. *) -val value_of_block : llbasicblock -> llvalue - -(** [value_is_block v] returns [true] if the value [v] is a basic block and - [false] otherwise. - Similar to [llvm::isa]. *) -val value_is_block : llvalue -> bool - -(** [block_of_value v] losslessly casts [v] to an [llbasicblock]. *) -val block_of_value : llvalue -> llbasicblock - - -(** {7 Operations on instructions} *) - -(** [instr_parent i] is the enclosing basic block of the instruction [i]. - See the method [llvm::Instruction::getParent]. *) -val instr_parent : llvalue -> llbasicblock - -(** [delete_instruction i] deletes the instruction [i]. - * See the method [llvm::Instruction::eraseFromParent]. *) -val delete_instruction : llvalue -> unit - -(** [instr_begin bb] returns the first position in the instruction list of the - basic block [bb]. [instr_begin] and [instr_succ] can be used to iterate over - the instruction list in order. - See the method [llvm::BasicBlock::begin]. *) -val instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos - -(** [instr_succ i] returns the instruction list position succeeding [Before i]. - See the method [llvm::BasicBlock::iterator::operator++]. *) -val instr_succ : llvalue -> (llbasicblock, llvalue) llpos - -(** [iter_instrs f bb] applies function [f] to each of the instructions of basic - block [bb] in order. Tail recursive. *) -val iter_instrs: (llvalue -> unit) -> llbasicblock -> unit - -(** [fold_left_instrs f init bb] is [f (... (f init g1) ...) gN] where - [g1,...,gN] are the instructions of basic block [bb]. Tail recursive. *) -val fold_left_instrs: ('a -> llvalue -> 'a) -> 'a -> llbasicblock -> 'a - -(** [instr_end bb] returns the last position in the instruction list of the - basic block [bb]. [instr_end] and [instr_pred] can be used to iterate over - the instruction list in reverse. - See the method [llvm::BasicBlock::end]. *) -val instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos - -(** [instr_pred i] returns the instruction list position preceding [After i]. - See the method [llvm::BasicBlock::iterator::operator--]. *) -val instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos - -(** [fold_right_instrs f bb init] is [f (... (f init fN) ...) f1] where - [f1,...,fN] are the instructions of basic block [bb]. Tail recursive. *) -val fold_right_instrs: (llvalue -> 'a -> 'a) -> llbasicblock -> 'a -> 'a - -(** [inst_opcode i] returns the [Opcode.t] corresponding to instruction [i], - or [Opcode.Invalid] if [i] is not an instruction. *) -val instr_opcode : llvalue -> Opcode.t - -(** [icmp_predicate i] returns the [Icmp.t] corresponding to an [icmp] - instruction [i]. *) -val icmp_predicate : llvalue -> Icmp.t option - -(** [fcmp_predicate i] returns the [fcmp.t] corresponding to an [fcmp] - instruction [i]. *) -val fcmp_predicate : llvalue -> Fcmp.t option - -(** [inst_clone i] returns a copy of instruction [i], - The instruction has no parent, and no name. - See the method [llvm::Instruction::clone]. *) -val instr_clone : llvalue -> llvalue - - -(** {7 Operations on call sites} *) - -(** [instruction_call_conv ci] is the calling convention for the call or invoke - instruction [ci], which may be one of the values from the module - {!CallConv}. See the method [llvm::CallInst::getCallingConv] and - [llvm::InvokeInst::getCallingConv]. *) -val instruction_call_conv: llvalue -> int - -(** [set_instruction_call_conv cc ci] sets the calling convention for the call - or invoke instruction [ci] to the integer [cc], which can be one of the - values from the module {!CallConv}. - See the method [llvm::CallInst::setCallingConv] - and [llvm::InvokeInst::setCallingConv]. *) -val set_instruction_call_conv: int -> llvalue -> unit - -(** [add_call_site_attr f a i] adds attribute [a] to the call instruction [ci] - at position [i]. *) -val add_call_site_attr : llvalue -> llattribute -> AttrIndex.t -> unit - -(** [call_site_attr f i] returns the attributes for the call instruction [ci] - at position [i]. *) -val call_site_attrs : llvalue -> AttrIndex.t -> llattribute array - -(** [remove_enum_call_site_attr f k i] removes enum attribute with kind [k] - from the call instruction [ci] at position [i]. *) -val remove_enum_call_site_attr : llvalue -> llattrkind -> AttrIndex.t -> unit - -(** [remove_string_call_site_attr f k i] removes string attribute with kind [k] - from the call instruction [ci] at position [i]. *) -val remove_string_call_site_attr : llvalue -> string -> AttrIndex.t -> unit - - -(** {7 Operations on call and invoke instructions (only)} *) - -(** [num_arg_operands ci] returns the number of arguments for the call or - invoke instruction [ci]. See the method - [llvm::CallInst::getNumArgOperands]. *) -val num_arg_operands : llvalue -> int - -(** [is_tail_call ci] is [true] if the call instruction [ci] is flagged as - eligible for tail call optimization, [false] otherwise. - See the method [llvm::CallInst::isTailCall]. *) -val is_tail_call : llvalue -> bool - -(** [set_tail_call tc ci] flags the call instruction [ci] as eligible for tail - call optimization if [tc] is [true], clears otherwise. - See the method [llvm::CallInst::setTailCall]. *) -val set_tail_call : bool -> llvalue -> unit - -(** [get_normal_dest ii] is the normal destination basic block of an invoke - instruction. See the method [llvm::InvokeInst::getNormalDest()]. *) -val get_normal_dest : llvalue -> llbasicblock - -(** [get_unwind_dest ii] is the unwind destination basic block of an invoke - instruction. See the method [llvm::InvokeInst::getUnwindDest()]. *) -val get_unwind_dest : llvalue -> llbasicblock - - -(** {7 Operations on load/store instructions (only)} *) - -(** [is_volatile i] is [true] if the load or store instruction [i] is marked - as volatile. - See the methods [llvm::LoadInst::isVolatile] and - [llvm::StoreInst::isVolatile]. *) -val is_volatile : llvalue -> bool - -(** [set_volatile v i] marks the load or store instruction [i] as volatile - if [v] is [true], unmarks otherwise. - See the methods [llvm::LoadInst::setVolatile] and - [llvm::StoreInst::setVolatile]. *) -val set_volatile : bool -> llvalue -> unit - -(** {7 Operations on terminators} *) - -(** [is_terminator v] returns true if the instruction [v] is a terminator. *) -val is_terminator : llvalue -> bool - -(** [successor v i] returns the successor at index [i] for the value [v]. - See the method [llvm::Instruction::getSuccessor]. *) -val successor : llvalue -> int -> llbasicblock - -(** [set_successor v i o] sets the successor of the value [v] at the index [i] to - the value [o]. - See the method [llvm::Instruction::setSuccessor]. *) -val set_successor : llvalue -> int -> llbasicblock -> unit - -(** [num_successors v] returns the number of successors for the value [v]. - See the method [llvm::Instruction::getNumSuccessors]. *) -val num_successors : llvalue -> int - -(** [successors v] returns the successors of [v]. *) -val successors : llvalue -> llbasicblock array - -(** [iter_successors f v] applies function f to each successor [v] in order. Tail recursive. *) -val iter_successors : (llbasicblock -> unit) -> llvalue -> unit - -(** [fold_successors f v init] is [f (... (f init vN) ...) v1] where [v1,...,vN] are the successors of [v]. Tail recursive. *) -val fold_successors : (llbasicblock -> 'a -> 'a) -> llvalue -> 'a -> 'a - -(** {7 Operations on branches} *) - -(** [is_conditional v] returns true if the branch instruction [v] is conditional. - See the method [llvm::BranchInst::isConditional]. *) -val is_conditional : llvalue -> bool - -(** [condition v] return the condition of the branch instruction [v]. - See the method [llvm::BranchInst::getCondition]. *) -val condition : llvalue -> llvalue - -(** [set_condition v c] sets the condition of the branch instruction [v] to the value [c]. - See the method [llvm::BranchInst::setCondition]. *) -val set_condition : llvalue -> llvalue -> unit - -(** [get_branch c] returns a description of the branch instruction [c]. *) -val get_branch : llvalue -> - [ `Conditional of llvalue * llbasicblock * llbasicblock - | `Unconditional of llbasicblock ] - option - -(** {7 Operations on phi nodes} *) - -(** [add_incoming (v, bb) pn] adds the value [v] to the phi node [pn] for use - with branches from [bb]. See the method [llvm::PHINode::addIncoming]. *) -val add_incoming : (llvalue * llbasicblock) -> llvalue -> unit - -(** [incoming pn] returns the list of value-block pairs for phi node [pn]. - See the method [llvm::PHINode::getIncomingValue]. *) -val incoming : llvalue -> (llvalue * llbasicblock) list - - - -(** {6 Instruction builders} *) - -(** [builder context] creates an instruction builder with no position in - the context [context]. It is invalid to use this builder until its position - is set with {!position_before} or {!position_at_end}. See the constructor - for [llvm::LLVMBuilder]. *) -val builder : llcontext -> llbuilder - -(** [builder_at ip] creates an instruction builder positioned at [ip]. - See the constructor for [llvm::LLVMBuilder]. *) -val builder_at : llcontext -> (llbasicblock, llvalue) llpos -> llbuilder - -(** [builder_before ins] creates an instruction builder positioned before the - instruction [isn]. See the constructor for [llvm::LLVMBuilder]. *) -val builder_before : llcontext -> llvalue -> llbuilder - -(** [builder_at_end bb] creates an instruction builder positioned at the end of - the basic block [bb]. See the constructor for [llvm::LLVMBuilder]. *) -val builder_at_end : llcontext -> llbasicblock -> llbuilder - -(** [position_builder ip bb] moves the instruction builder [bb] to the position - [ip]. - See the constructor for [llvm::LLVMBuilder]. *) -val position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit - -(** [position_before ins b] moves the instruction builder [b] to before the - instruction [isn]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *) -val position_before : llvalue -> llbuilder -> unit - -(** [position_at_end bb b] moves the instruction builder [b] to the end of the - basic block [bb]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *) -val position_at_end : llbasicblock -> llbuilder -> unit - -(** [insertion_block b] returns the basic block that the builder [b] is - positioned to insert into. Raises [Not_Found] if the instruction builder is - uninitialized. - See the method [llvm::LLVMBuilder::GetInsertBlock]. *) -val insertion_block : llbuilder -> llbasicblock - -(** [insert_into_builder i name b] inserts the specified instruction [i] at the - position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::Insert]. *) -val insert_into_builder : llvalue -> string -> llbuilder -> unit - - -(** {7 Metadata} *) - -(** [set_current_debug_location b md] sets the current debug location [md] in - the builder [b]. - See the method [llvm::IRBuilder::SetDebugLocation]. *) -val set_current_debug_location : llbuilder -> llvalue -> unit - -(** [clear_current_debug_location b] clears the current debug location in the - builder [b]. *) -val clear_current_debug_location : llbuilder -> unit - -(** [current_debug_location b] returns the current debug location, or None - if none is currently set. - See the method [llvm::IRBuilder::GetDebugLocation]. *) -val current_debug_location : llbuilder -> llvalue option - -(** [set_inst_debug_location b i] sets the current debug location of the builder - [b] to the instruction [i]. - See the method [llvm::IRBuilder::SetInstDebugLocation]. *) -val set_inst_debug_location : llbuilder -> llvalue -> unit - - -(** {7 Terminators} *) - -(** [build_ret_void b] creates a - [ret void] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateRetVoid]. *) -val build_ret_void : llbuilder -> llvalue - -(** [build_ret v b] creates a - [ret %v] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateRet]. *) -val build_ret : llvalue -> llbuilder -> llvalue - -(** [build_aggregate_ret vs b] creates a - [ret {...} { %v1, %v2, ... } ] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAggregateRet]. *) -val build_aggregate_ret : llvalue array -> llbuilder -> llvalue - -(** [build_br bb b] creates a - [br %bb] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateBr]. *) -val build_br : llbasicblock -> llbuilder -> llvalue - -(** [build_cond_br cond tbb fbb b] creates a - [br %cond, %tbb, %fbb] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateCondBr]. *) -val build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder -> - llvalue - -(** [build_switch case elsebb count b] creates an empty - [switch %case, %elsebb] - instruction at the position specified by the instruction builder [b] with - space reserved for [count] cases. - See the method [llvm::LLVMBuilder::CreateSwitch]. *) -val build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue - -(** [build_malloc ty name b] creates an [malloc] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::CallInst::CreateMalloc]. *) -val build_malloc : lltype -> string -> llbuilder -> llvalue - -(** [build_array_malloc ty val name b] creates an [array malloc] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::CallInst::CreateArrayMalloc]. *) -val build_array_malloc : lltype -> llvalue -> string -> llbuilder -> llvalue - -(** [build_free p b] creates a [free] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFree]. *) -val build_free : llvalue -> llbuilder -> llvalue - -(** [add_case sw onval bb] causes switch instruction [sw] to branch to [bb] - when its input matches the constant [onval]. - See the method [llvm::SwitchInst::addCase]. **) -val add_case : llvalue -> llvalue -> llbasicblock -> unit - -(** [switch_default_dest sw] returns the default destination of the [switch] - instruction. - See the method [llvm:;SwitchInst::getDefaultDest]. **) -val switch_default_dest : llvalue -> llbasicblock - -(** [build_indirect_br addr count b] creates a - [indirectbr %addr] - instruction at the position specified by the instruction builder [b] with - space reserved for [count] destinations. - See the method [llvm::LLVMBuilder::CreateIndirectBr]. *) -val build_indirect_br : llvalue -> int -> llbuilder -> llvalue - -(** [add_destination br bb] adds the basic block [bb] as a possible branch - location for the indirectbr instruction [br]. - See the method [llvm::IndirectBrInst::addDestination]. **) -val add_destination : llvalue -> llbasicblock -> unit - -(** [build_invoke fn args tobb unwindbb name b] creates an - [%name = invoke %fn(args) to %tobb unwind %unwindbb] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateInvoke]. *) -val build_invoke : llvalue -> llvalue array -> llbasicblock -> - llbasicblock -> string -> llbuilder -> llvalue - -(** [build_landingpad ty persfn numclauses name b] creates an - [landingpad] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateLandingPad]. *) -val build_landingpad : lltype -> llvalue -> int -> string -> llbuilder -> - llvalue - -(** [is_cleanup lp] returns [true] if [landingpad] instruction lp is a cleanup. - See the method [llvm::LandingPadInst::isCleanup]. *) -val is_cleanup : llvalue -> bool - -(** [set_cleanup lp] sets the cleanup flag in the [landingpad]instruction. - See the method [llvm::LandingPadInst::setCleanup]. *) -val set_cleanup : llvalue -> bool -> unit - -(** [add_clause lp clause] adds the clause to the [landingpad]instruction. - See the method [llvm::LandingPadInst::addClause]. *) -val add_clause : llvalue -> llvalue -> unit - -(** [build_resume exn b] builds a [resume exn] instruction - at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateResume] *) -val build_resume : llvalue -> llbuilder -> llvalue - -(** [build_unreachable b] creates an - [unreachable] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateUnwind]. *) -val build_unreachable : llbuilder -> llvalue - - -(** {7 Arithmetic} *) - -(** [build_add x y name b] creates a - [%name = add %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAdd]. *) -val build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nsw_add x y name b] creates a - [%name = nsw add %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNSWAdd]. *) -val build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nuw_add x y name b] creates a - [%name = nuw add %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNUWAdd]. *) -val build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_fadd x y name b] creates a - [%name = fadd %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFAdd]. *) -val build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_sub x y name b] creates a - [%name = sub %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSub]. *) -val build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nsw_sub x y name b] creates a - [%name = nsw sub %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNSWSub]. *) -val build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nuw_sub x y name b] creates a - [%name = nuw sub %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNUWSub]. *) -val build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_fsub x y name b] creates a - [%name = fsub %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFSub]. *) -val build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_mul x y name b] creates a - [%name = mul %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateMul]. *) -val build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nsw_mul x y name b] creates a - [%name = nsw mul %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNSWMul]. *) -val build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_nuw_mul x y name b] creates a - [%name = nuw mul %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateNUWMul]. *) -val build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_fmul x y name b] creates a - [%name = fmul %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFMul]. *) -val build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_udiv x y name b] creates a - [%name = udiv %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateUDiv]. *) -val build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_sdiv x y name b] creates a - [%name = sdiv %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSDiv]. *) -val build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_exact_sdiv x y name b] creates a - [%name = exact sdiv %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateExactSDiv]. *) -val build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_fdiv x y name b] creates a - [%name = fdiv %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFDiv]. *) -val build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_urem x y name b] creates a - [%name = urem %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateURem]. *) -val build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_SRem x y name b] creates a - [%name = srem %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSRem]. *) -val build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_frem x y name b] creates a - [%name = frem %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFRem]. *) -val build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_shl x y name b] creates a - [%name = shl %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateShl]. *) -val build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_lshr x y name b] creates a - [%name = lshr %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateLShr]. *) -val build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_ashr x y name b] creates a - [%name = ashr %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAShr]. *) -val build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_and x y name b] creates a - [%name = and %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAnd]. *) -val build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_or x y name b] creates a - [%name = or %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateOr]. *) -val build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_xor x y name b] creates a - [%name = xor %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateXor]. *) -val build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_neg x name b] creates a - [%name = sub 0, %x] - instruction at the position specified by the instruction builder [b]. - [-0.0] is used for floating point types to compute the correct sign. - See the method [llvm::LLVMBuilder::CreateNeg]. *) -val build_neg : llvalue -> string -> llbuilder -> llvalue - -(** [build_nsw_neg x name b] creates a - [%name = nsw sub 0, %x] - instruction at the position specified by the instruction builder [b]. - [-0.0] is used for floating point types to compute the correct sign. - See the method [llvm::LLVMBuilder::CreateNeg]. *) -val build_nsw_neg : llvalue -> string -> llbuilder -> llvalue - -(** [build_nuw_neg x name b] creates a - [%name = nuw sub 0, %x] - instruction at the position specified by the instruction builder [b]. - [-0.0] is used for floating point types to compute the correct sign. - See the method [llvm::LLVMBuilder::CreateNeg]. *) -val build_nuw_neg : llvalue -> string -> llbuilder -> llvalue - -(** [build_fneg x name b] creates a - [%name = fsub 0, %x] - instruction at the position specified by the instruction builder [b]. - [-0.0] is used for floating point types to compute the correct sign. - See the method [llvm::LLVMBuilder::CreateFNeg]. *) -val build_fneg : llvalue -> string -> llbuilder -> llvalue - -(** [build_xor x name b] creates a - [%name = xor %x, -1] - instruction at the position specified by the instruction builder [b]. - [-1] is the correct "all ones" value for the type of [x]. - See the method [llvm::LLVMBuilder::CreateXor]. *) -val build_not : llvalue -> string -> llbuilder -> llvalue - - -(** {7 Memory} *) - -(** [build_alloca ty name b] creates a - [%name = alloca %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAlloca]. *) -val build_alloca : lltype -> string -> llbuilder -> llvalue - -(** [build_array_alloca ty n name b] creates a - [%name = alloca %ty, %n] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateAlloca]. *) -val build_array_alloca : lltype -> llvalue -> string -> llbuilder -> - llvalue - -(** [build_load v name b] creates a - [%name = load %v] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateLoad]. *) -val build_load : llvalue -> string -> llbuilder -> llvalue - -(** [build_store v p b] creates a - [store %v, %p] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateStore]. *) -val build_store : llvalue -> llvalue -> llbuilder -> llvalue - -(** [build_atomicrmw op ptr val o st b] creates an [atomicrmw] instruction with - operation [op] performed on pointer [ptr] and value [val] with ordering [o] - and singlethread flag set to [st] at the position specified by - the instruction builder [b]. - See the method [llvm::IRBuilder::CreateAtomicRMW]. *) -val build_atomicrmw : AtomicRMWBinOp.t -> llvalue -> llvalue -> - AtomicOrdering.t -> bool -> string -> llbuilder -> llvalue - -(** [build_gep p indices name b] creates a - [%name = getelementptr %p, indices...] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateGetElementPtr]. *) -val build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue - -(** [build_in_bounds_gep p indices name b] creates a - [%name = gelementptr inbounds %p, indices...] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateInBoundsGetElementPtr]. *) -val build_in_bounds_gep : llvalue -> llvalue array -> string -> llbuilder -> - llvalue - -(** [build_struct_gep p idx name b] creates a - [%name = getelementptr %p, 0, idx] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateStructGetElementPtr]. *) -val build_struct_gep : llvalue -> int -> string -> llbuilder -> - llvalue - -(** [build_global_string str name b] creates a series of instructions that adds - a global string at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateGlobalString]. *) -val build_global_string : string -> string -> llbuilder -> llvalue - -(** [build_global_stringptr str name b] creates a series of instructions that - adds a global string pointer at the position specified by the instruction - builder [b]. - See the method [llvm::LLVMBuilder::CreateGlobalStringPtr]. *) -val build_global_stringptr : string -> string -> llbuilder -> llvalue - - -(** {7 Casts} *) - -(** [build_trunc v ty name b] creates a - [%name = trunc %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateTrunc]. *) -val build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_zext v ty name b] creates a - [%name = zext %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateZExt]. *) -val build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_sext v ty name b] creates a - [%name = sext %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSExt]. *) -val build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_fptoui v ty name b] creates a - [%name = fptoui %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFPToUI]. *) -val build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_fptosi v ty name b] creates a - [%name = fptosi %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFPToSI]. *) -val build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_uitofp v ty name b] creates a - [%name = uitofp %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateUIToFP]. *) -val build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_sitofp v ty name b] creates a - [%name = sitofp %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSIToFP]. *) -val build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_fptrunc v ty name b] creates a - [%name = fptrunc %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFPTrunc]. *) -val build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_fpext v ty name b] creates a - [%name = fpext %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFPExt]. *) -val build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_ptrtoint v ty name b] creates a - [%name = prtotint %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreatePtrToInt]. *) -val build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_inttoptr v ty name b] creates a - [%name = inttoptr %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateIntToPtr]. *) -val build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_bitcast v ty name b] creates a - [%name = bitcast %p to %ty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateBitCast]. *) -val build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_zext_or_bitcast v ty name b] creates a zext or bitcast - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *) -val build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue - -(** [build_sext_or_bitcast v ty name b] creates a sext or bitcast - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSExtOrBitCast]. *) -val build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue - -(** [build_trunc_or_bitcast v ty name b] creates a trunc or bitcast - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *) -val build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder -> - llvalue - -(** [build_pointercast v ty name b] creates a bitcast or pointer-to-int - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreatePointerCast]. *) -val build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_intcast v ty name b] creates a zext, bitcast, or trunc - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateIntCast]. *) -val build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_fpcast v ty name b] creates a fpext, bitcast, or fptrunc - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFPCast]. *) -val build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue - - -(** {7 Comparisons} *) - -(** [build_icmp pred x y name b] creates a - [%name = icmp %pred %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateICmp]. *) -val build_icmp : Icmp.t -> llvalue -> llvalue -> string -> - llbuilder -> llvalue - -(** [build_fcmp pred x y name b] creates a - [%name = fcmp %pred %x, %y] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFCmp]. *) -val build_fcmp : Fcmp.t -> llvalue -> llvalue -> string -> - llbuilder -> llvalue - - -(** {7 Miscellaneous instructions} *) - -(** [build_phi incoming name b] creates a - [%name = phi %incoming] - instruction at the position specified by the instruction builder [b]. - [incoming] is a list of [(llvalue, llbasicblock)] tuples. - See the method [llvm::LLVMBuilder::CreatePHI]. *) -val build_phi : (llvalue * llbasicblock) list -> string -> llbuilder -> - llvalue - -(** [build_empty_phi ty name b] creates a - [%name = phi %ty] instruction at the position specified by - the instruction builder [b]. [ty] is the type of the instruction. - See the method [llvm::LLVMBuilder::CreatePHI]. *) -val build_empty_phi : lltype -> string -> llbuilder -> llvalue - -(** [build_call fn args name b] creates a - [%name = call %fn(args...)] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateCall]. *) -val build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue - -(** [build_select cond thenv elsev name b] creates a - [%name = select %cond, %thenv, %elsev] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateSelect]. *) -val build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder -> - llvalue - -(** [build_va_arg valist argty name b] creates a - [%name = va_arg %valist, %argty] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateVAArg]. *) -val build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue - -(** [build_extractelement vec i name b] creates a - [%name = extractelement %vec, %i] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateExtractElement]. *) -val build_extractelement : llvalue -> llvalue -> string -> llbuilder -> - llvalue - -(** [build_insertelement vec elt i name b] creates a - [%name = insertelement %vec, %elt, %i] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateInsertElement]. *) -val build_insertelement : llvalue -> llvalue -> llvalue -> string -> - llbuilder -> llvalue - -(** [build_shufflevector veca vecb mask name b] creates a - [%name = shufflevector %veca, %vecb, %mask] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateShuffleVector]. *) -val build_shufflevector : llvalue -> llvalue -> llvalue -> string -> - llbuilder -> llvalue - -(** [build_extractvalue agg idx name b] creates a - [%name = extractvalue %agg, %idx] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateExtractValue]. *) -val build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue - - -(** [build_insertvalue agg val idx name b] creates a - [%name = insertvalue %agg, %val, %idx] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateInsertValue]. *) -val build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder -> - llvalue - -(** [build_is_null val name b] creates a - [%name = icmp eq %val, null] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateIsNull]. *) -val build_is_null : llvalue -> string -> llbuilder -> llvalue - -(** [build_is_not_null val name b] creates a - [%name = icmp ne %val, null] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateIsNotNull]. *) -val build_is_not_null : llvalue -> string -> llbuilder -> llvalue - -(** [build_ptrdiff lhs rhs name b] creates a series of instructions that measure - the difference between two pointer values at the position specified by the - instruction builder [b]. - See the method [llvm::LLVMBuilder::CreatePtrDiff]. *) -val build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue - -(** [build_freeze x name b] creates a - [%name = freeze %x] - instruction at the position specified by the instruction builder [b]. - See the method [llvm::LLVMBuilder::CreateFreeze]. *) -val build_freeze : llvalue -> string -> llbuilder -> llvalue - - -(** {6 Memory buffers} *) - -module MemoryBuffer : sig - (** [of_file p] is the memory buffer containing the contents of the file at - path [p]. If the file could not be read, then [IoError msg] is - raised. *) - val of_file : string -> llmemorybuffer - - (** [of_stdin ()] is the memory buffer containing the contents of standard input. - If standard input is empty, then [IoError msg] is raised. *) - val of_stdin : unit -> llmemorybuffer - - (** [of_string ~name s] is the memory buffer containing the contents of string [s]. - The name of memory buffer is set to [name] if it is provided. *) - val of_string : ?name:string -> string -> llmemorybuffer - - (** [as_string mb] is the string containing the contents of memory buffer [mb]. *) - val as_string : llmemorybuffer -> string - - (** Disposes of a memory buffer. *) - val dispose : llmemorybuffer -> unit -end - - -(** {6 Pass Managers} *) - -module PassManager : sig - (** *) - type 'a t - type any = [ `Module | `Function ] - - (** [PassManager.create ()] constructs a new whole-module pass pipeline. This - type of pipeline is suitable for link-time optimization and whole-module - transformations. - See the constructor of [llvm::PassManager]. *) - val create : unit -> [ `Module ] t - - (** [PassManager.create_function m] constructs a new function-by-function - pass pipeline over the module [m]. It does not take ownership of [m]. - This type of pipeline is suitable for code generation and JIT compilation - tasks. - See the constructor of [llvm::FunctionPassManager]. *) - val create_function : llmodule -> [ `Function ] t - - (** [run_module m pm] initializes, executes on the module [m], and finalizes - all of the passes scheduled in the pass manager [pm]. Returns [true] if - any of the passes modified the module, [false] otherwise. - See the [llvm::PassManager::run] method. *) - val run_module : llmodule -> [ `Module ] t -> bool - - (** [initialize fpm] initializes all of the function passes scheduled in the - function pass manager [fpm]. Returns [true] if any of the passes modified - the module, [false] otherwise. - See the [llvm::FunctionPassManager::doInitialization] method. *) - val initialize : [ `Function ] t -> bool - - (** [run_function f fpm] executes all of the function passes scheduled in the - function pass manager [fpm] over the function [f]. Returns [true] if any - of the passes modified [f], [false] otherwise. - See the [llvm::FunctionPassManager::run] method. *) - val run_function : llvalue -> [ `Function ] t -> bool - - (** [finalize fpm] finalizes all of the function passes scheduled in the - function pass manager [fpm]. Returns [true] if any of the passes - modified the module, [false] otherwise. - See the [llvm::FunctionPassManager::doFinalization] method. *) - val finalize : [ `Function ] t -> bool - - (** Frees the memory of a pass pipeline. For function pipelines, does not free - the module. - See the destructor of [llvm::BasePassManager]. *) - val dispose : [< any ] t -> unit -end diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.c b/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.c deleted file mode 100644 index 0087fc8813ec6..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.c +++ /dev/null @@ -1,2401 +0,0 @@ -/*===-- llvm_ocaml.c - LLVM OCaml Glue --------------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include -#include -#include -#include "llvm-c/Core.h" -#include "llvm-c/Support.h" -#include "llvm/Config/llvm-config.h" -#include "caml/memory.h" -#include "caml/fail.h" -#include "caml/callback.h" -#include "llvm_ocaml.h" - -#if OCAML_VERSION < 41200 -value caml_alloc_some(value v) { - CAMLparam1(v); - value Some = caml_alloc_small(1, 0); - Field(Some, 0) = v; - CAMLreturn(Some); -} -#endif - -value caml_alloc_tuple_uninit(mlsize_t wosize) { - if (wosize <= Max_young_wosize) { - return caml_alloc_small(wosize, 0); - } else { - return caml_alloc_shr(wosize, 0); - } -} - -value llvm_string_of_message(char *Message) { - value String = caml_copy_string(Message); - LLVMDisposeMessage(Message); - - return String; -} - -value ptr_to_option(void *Ptr) { - if (!Ptr) - return Val_none; - return caml_alloc_some((value)Ptr); -} - -value cstr_to_string(const char *Str, mlsize_t Len) { - if (!Str) - return caml_alloc_string(0); - value String = caml_alloc_string(Len); - memcpy((char *)String_val(String), Str, Len); - return String; -} - -value cstr_to_string_option(const char *CStr, mlsize_t Len) { - if (!CStr) - return Val_none; - value String = caml_alloc_string(Len); - memcpy((char *)String_val(String), CStr, Len); - return caml_alloc_some(String); -} - -void llvm_raise(value Prototype, char *Message) { - caml_raise_with_arg(Prototype, llvm_string_of_message(Message)); -} - -static value llvm_fatal_error_handler; - -static void llvm_fatal_error_trampoline(const char *Reason) { - callback(llvm_fatal_error_handler, caml_copy_string(Reason)); -} - -value llvm_install_fatal_error_handler(value Handler) { - LLVMInstallFatalErrorHandler(llvm_fatal_error_trampoline); - llvm_fatal_error_handler = Handler; - caml_register_global_root(&llvm_fatal_error_handler); - return Val_unit; -} - -value llvm_reset_fatal_error_handler(value Unit) { - caml_remove_global_root(&llvm_fatal_error_handler); - LLVMResetFatalErrorHandler(); - return Val_unit; -} - -value llvm_enable_pretty_stacktrace(value Unit) { - LLVMEnablePrettyStackTrace(); - return Val_unit; -} - -value llvm_parse_command_line_options(value Overview, value Args) { - const char *COverview; - if (Overview == Val_int(0)) { - COverview = NULL; - } else { - COverview = String_val(Field(Overview, 0)); - } - LLVMParseCommandLineOptions(Wosize_val(Args), - (const char *const *)Op_val(Args), COverview); - return Val_unit; -} - -static value alloc_variant(int tag, void *Value) { - value Iter = caml_alloc_small(1, tag); - Field(Iter, 0) = Val_op(Value); - return Iter; -} - -/* Macro to convert the C first/next/last/prev idiom to the Ocaml llpos/ - llrev_pos idiom. */ -#define DEFINE_ITERATORS(camlname, cname, pty, cty, pfun) \ - /* llmodule -> ('a, 'b) llpos */ \ - value llvm_##camlname##_begin(pty Mom) { \ - cty First = LLVMGetFirst##cname(Mom); \ - if (First) \ - return alloc_variant(1, First); \ - return alloc_variant(0, Mom); \ - } \ - \ - /* llvalue -> ('a, 'b) llpos */ \ - value llvm_##camlname##_succ(cty Kid) { \ - cty Next = LLVMGetNext##cname(Kid); \ - if (Next) \ - return alloc_variant(1, Next); \ - return alloc_variant(0, pfun(Kid)); \ - } \ - \ - /* llmodule -> ('a, 'b) llrev_pos */ \ - value llvm_##camlname##_end(pty Mom) { \ - cty Last = LLVMGetLast##cname(Mom); \ - if (Last) \ - return alloc_variant(1, Last); \ - return alloc_variant(0, Mom); \ - } \ - \ - /* llvalue -> ('a, 'b) llrev_pos */ \ - value llvm_##camlname##_pred(cty Kid) { \ - cty Prev = LLVMGetPrevious##cname(Kid); \ - if (Prev) \ - return alloc_variant(1, Prev); \ - return alloc_variant(0, pfun(Kid)); \ - } - -/*===-- Context error handling --------------------------------------------===*/ - -void llvm_diagnostic_handler_trampoline(LLVMDiagnosticInfoRef DI, - void *DiagnosticContext) { - caml_callback(*((value *)DiagnosticContext), (value)DI); -} - -/* Diagnostic.t -> string */ -value llvm_get_diagnostic_description(value Diagnostic) { - return llvm_string_of_message( - LLVMGetDiagInfoDescription((LLVMDiagnosticInfoRef)Diagnostic)); -} - -/* Diagnostic.t -> DiagnosticSeverity.t */ -value llvm_get_diagnostic_severity(value Diagnostic) { - return Val_int(LLVMGetDiagInfoSeverity((LLVMDiagnosticInfoRef)Diagnostic)); -} - -static void llvm_remove_diagnostic_handler(LLVMContextRef C) { - if (LLVMContextGetDiagnosticHandler(C) == - llvm_diagnostic_handler_trampoline) { - value *Handler = (value *)LLVMContextGetDiagnosticContext(C); - remove_global_root(Handler); - free(Handler); - } -} - -/* llcontext -> (Diagnostic.t -> unit) option -> unit */ -value llvm_set_diagnostic_handler(LLVMContextRef C, value Handler) { - llvm_remove_diagnostic_handler(C); - if (Handler == Val_none) { - LLVMContextSetDiagnosticHandler(C, NULL, NULL); - } else { - value *DiagnosticContext = malloc(sizeof(value)); - if (DiagnosticContext == NULL) - caml_raise_out_of_memory(); - caml_register_global_root(DiagnosticContext); - *DiagnosticContext = Field(Handler, 0); - LLVMContextSetDiagnosticHandler(C, llvm_diagnostic_handler_trampoline, - DiagnosticContext); - } - return Val_unit; -} - -/*===-- Contexts ----------------------------------------------------------===*/ - -/* unit -> llcontext */ -LLVMContextRef llvm_create_context(value Unit) { return LLVMContextCreate(); } - -/* llcontext -> unit */ -value llvm_dispose_context(LLVMContextRef C) { - llvm_remove_diagnostic_handler(C); - LLVMContextDispose(C); - return Val_unit; -} - -/* unit -> llcontext */ -LLVMContextRef llvm_global_context(value Unit) { - return LLVMGetGlobalContext(); -} - -/* llcontext -> string -> int */ -value llvm_mdkind_id(LLVMContextRef C, value Name) { - unsigned MDKindID = - LLVMGetMDKindIDInContext(C, String_val(Name), caml_string_length(Name)); - return Val_int(MDKindID); -} - -/*===-- Attributes --------------------------------------------------------===*/ - -/* string -> llattrkind */ -value llvm_enum_attr_kind(value Name) { - unsigned Kind = LLVMGetEnumAttributeKindForName(String_val(Name), - caml_string_length(Name)); - if (Kind == 0) - caml_raise_with_arg(*caml_named_value("Llvm.UnknownAttribute"), Name); - return Val_int(Kind); -} - -/* llcontext -> int -> int64 -> llattribute */ -LLVMAttributeRef llvm_create_enum_attr_by_kind(LLVMContextRef C, value Kind, - value Value) { - return LLVMCreateEnumAttribute(C, Int_val(Kind), Int64_val(Value)); -} - -/* llattribute -> bool */ -value llvm_is_enum_attr(LLVMAttributeRef A) { - return Val_int(LLVMIsEnumAttribute(A)); -} - -/* llattribute -> llattrkind */ -value llvm_get_enum_attr_kind(LLVMAttributeRef A) { - return Val_int(LLVMGetEnumAttributeKind(A)); -} - -/* llattribute -> int64 */ -value llvm_get_enum_attr_value(LLVMAttributeRef A) { - return caml_copy_int64(LLVMGetEnumAttributeValue(A)); -} - -/* llcontext -> kind:string -> name:string -> llattribute */ -LLVMAttributeRef llvm_create_string_attr(LLVMContextRef C, value Kind, - value Value) { - return LLVMCreateStringAttribute(C, String_val(Kind), - caml_string_length(Kind), String_val(Value), - caml_string_length(Value)); -} - -/* llattribute -> bool */ -value llvm_is_string_attr(LLVMAttributeRef A) { - return Val_int(LLVMIsStringAttribute(A)); -} - -/* llattribute -> string */ -value llvm_get_string_attr_kind(LLVMAttributeRef A) { - unsigned Length; - const char *String = LLVMGetStringAttributeKind(A, &Length); - return cstr_to_string(String, Length); -} - -/* llattribute -> string */ -value llvm_get_string_attr_value(LLVMAttributeRef A) { - unsigned Length; - const char *String = LLVMGetStringAttributeValue(A, &Length); - return cstr_to_string(String, Length); -} - -/*===-- Modules -----------------------------------------------------------===*/ - -/* llcontext -> string -> llmodule */ -LLVMModuleRef llvm_create_module(LLVMContextRef C, value ModuleID) { - return LLVMModuleCreateWithNameInContext(String_val(ModuleID), C); -} - -/* llmodule -> unit */ -value llvm_dispose_module(LLVMModuleRef M) { - LLVMDisposeModule(M); - return Val_unit; -} - -/* llmodule -> string */ -value llvm_target_triple(LLVMModuleRef M) { - return caml_copy_string(LLVMGetTarget(M)); -} - -/* string -> llmodule -> unit */ -value llvm_set_target_triple(value Trip, LLVMModuleRef M) { - LLVMSetTarget(M, String_val(Trip)); - return Val_unit; -} - -/* llmodule -> string */ -value llvm_data_layout(LLVMModuleRef M) { - return caml_copy_string(LLVMGetDataLayout(M)); -} - -/* string -> llmodule -> unit */ -value llvm_set_data_layout(value Layout, LLVMModuleRef M) { - LLVMSetDataLayout(M, String_val(Layout)); - return Val_unit; -} - -/* llmodule -> unit */ -value llvm_dump_module(LLVMModuleRef M) { - LLVMDumpModule(M); - return Val_unit; -} - -/* string -> llmodule -> unit */ -value llvm_print_module(value Filename, LLVMModuleRef M) { - char *Message; - - if (LLVMPrintModuleToFile(M, String_val(Filename), &Message)) - llvm_raise(*caml_named_value("Llvm.IoError"), Message); - - return Val_unit; -} - -/* llmodule -> string */ -value llvm_string_of_llmodule(LLVMModuleRef M) { - char *ModuleCStr = LLVMPrintModuleToString(M); - value ModuleStr = caml_copy_string(ModuleCStr); - LLVMDisposeMessage(ModuleCStr); - - return ModuleStr; -} - -/* llmodule -> string */ -value llvm_get_module_identifier(LLVMModuleRef M) { - size_t Len; - const char *Name = LLVMGetModuleIdentifier(M, &Len); - return cstr_to_string(Name, (mlsize_t)Len); -} - -/* llmodule -> string -> unit */ -value llvm_set_module_identifier(LLVMModuleRef M, value Id) { - LLVMSetModuleIdentifier(M, String_val(Id), caml_string_length(Id)); - return Val_unit; -} - -/* llmodule -> string -> unit */ -value llvm_set_module_inline_asm(LLVMModuleRef M, value Asm) { - LLVMSetModuleInlineAsm(M, String_val(Asm)); - return Val_unit; -} - -/* llmodule -> string -> llmetadata option */ -value llvm_get_module_flag(LLVMModuleRef M, value Key) { - return ptr_to_option( - LLVMGetModuleFlag(M, String_val(Key), caml_string_length(Key))); -} - -value llvm_add_module_flag(LLVMModuleRef M, LLVMModuleFlagBehavior Behaviour, - value Key, LLVMMetadataRef Val) { - LLVMAddModuleFlag(M, Int_val(Behaviour), String_val(Key), - caml_string_length(Key), Val); - return Val_unit; -} - -/*===-- Types -------------------------------------------------------------===*/ - -/* lltype -> TypeKind.t */ -value llvm_classify_type(LLVMTypeRef Ty) { - return Val_int(LLVMGetTypeKind(Ty)); -} - -value llvm_type_is_sized(LLVMTypeRef Ty) { - return Val_bool(LLVMTypeIsSized(Ty)); -} - -/* lltype -> llcontext */ -LLVMContextRef llvm_type_context(LLVMTypeRef Ty) { - return LLVMGetTypeContext(Ty); -} - -/* lltype -> unit */ -value llvm_dump_type(LLVMTypeRef Val) { -#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) - LLVMDumpType(Val); -#else - caml_raise_with_arg(*caml_named_value("Llvm.FeatureDisabled"), - caml_copy_string("dump")); -#endif - return Val_unit; -} - -/* lltype -> string */ -value llvm_string_of_lltype(LLVMTypeRef M) { - char *TypeCStr = LLVMPrintTypeToString(M); - value TypeStr = caml_copy_string(TypeCStr); - LLVMDisposeMessage(TypeCStr); - - return TypeStr; -} - -/*--... Operations on integer types ........................................--*/ - -/* llcontext -> lltype */ -LLVMTypeRef llvm_i1_type(LLVMContextRef Context) { - return LLVMInt1TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_i8_type(LLVMContextRef Context) { - return LLVMInt8TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_i16_type(LLVMContextRef Context) { - return LLVMInt16TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_i32_type(LLVMContextRef Context) { - return LLVMInt32TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_i64_type(LLVMContextRef Context) { - return LLVMInt64TypeInContext(Context); -} - -/* llcontext -> int -> lltype */ -LLVMTypeRef llvm_integer_type(LLVMContextRef Context, value Width) { - return LLVMIntTypeInContext(Context, Int_val(Width)); -} - -/* lltype -> int */ -value llvm_integer_bitwidth(LLVMTypeRef IntegerTy) { - return Val_int(LLVMGetIntTypeWidth(IntegerTy)); -} - -/*--... Operations on real types ...........................................--*/ - -/* llcontext -> lltype */ -LLVMTypeRef llvm_float_type(LLVMContextRef Context) { - return LLVMFloatTypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_double_type(LLVMContextRef Context) { - return LLVMDoubleTypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_x86fp80_type(LLVMContextRef Context) { - return LLVMX86FP80TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_fp128_type(LLVMContextRef Context) { - return LLVMFP128TypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_ppc_fp128_type(LLVMContextRef Context) { - return LLVMPPCFP128TypeInContext(Context); -} - -/*--... Operations on function types .......................................--*/ - -/* lltype -> lltype array -> lltype */ -LLVMTypeRef llvm_function_type(LLVMTypeRef RetTy, value ParamTys) { - return LLVMFunctionType(RetTy, (LLVMTypeRef *)ParamTys, Wosize_val(ParamTys), - 0); -} - -/* lltype -> lltype array -> lltype */ -LLVMTypeRef llvm_var_arg_function_type(LLVMTypeRef RetTy, value ParamTys) { - return LLVMFunctionType(RetTy, (LLVMTypeRef *)ParamTys, Wosize_val(ParamTys), - 1); -} - -/* lltype -> bool */ -value llvm_is_var_arg(LLVMTypeRef FunTy) { - return Val_bool(LLVMIsFunctionVarArg(FunTy)); -} - -/* lltype -> lltype array */ -value llvm_param_types(LLVMTypeRef FunTy) { - value Tys = caml_alloc_tuple_uninit(LLVMCountParamTypes(FunTy)); - LLVMGetParamTypes(FunTy, (LLVMTypeRef *)Op_val(Tys)); - return Tys; -} - -/*--... Operations on struct types .........................................--*/ - -/* llcontext -> lltype array -> lltype */ -LLVMTypeRef llvm_struct_type(LLVMContextRef C, value ElementTypes) { - return LLVMStructTypeInContext(C, (LLVMTypeRef *)ElementTypes, - Wosize_val(ElementTypes), 0); -} - -/* llcontext -> lltype array -> lltype */ -LLVMTypeRef llvm_packed_struct_type(LLVMContextRef C, value ElementTypes) { - return LLVMStructTypeInContext(C, (LLVMTypeRef *)ElementTypes, - Wosize_val(ElementTypes), 1); -} - -/* llcontext -> string -> lltype */ -LLVMTypeRef llvm_named_struct_type(LLVMContextRef C, value Name) { - return LLVMStructCreateNamed(C, String_val(Name)); -} - -value llvm_struct_set_body(LLVMTypeRef Ty, value ElementTypes, value Packed) { - LLVMStructSetBody(Ty, (LLVMTypeRef *)ElementTypes, Wosize_val(ElementTypes), - Bool_val(Packed)); - return Val_unit; -} - -/* lltype -> string option */ -value llvm_struct_name(LLVMTypeRef Ty) { - const char *CStr = LLVMGetStructName(Ty); - size_t Len; - if (!CStr) - return Val_none; - Len = strlen(CStr); - return cstr_to_string_option(CStr, Len); -} - -/* lltype -> lltype array */ -value llvm_struct_element_types(LLVMTypeRef StructTy) { - value Tys = caml_alloc_tuple_uninit(LLVMCountStructElementTypes(StructTy)); - LLVMGetStructElementTypes(StructTy, (LLVMTypeRef *)Op_val(Tys)); - return Tys; -} - -/* lltype -> bool */ -value llvm_is_packed(LLVMTypeRef StructTy) { - return Val_bool(LLVMIsPackedStruct(StructTy)); -} - -/* lltype -> bool */ -value llvm_is_opaque(LLVMTypeRef StructTy) { - return Val_bool(LLVMIsOpaqueStruct(StructTy)); -} - -/* lltype -> bool */ -value llvm_is_literal(LLVMTypeRef StructTy) { - return Val_bool(LLVMIsLiteralStruct(StructTy)); -} - -/*--... Operations on array, pointer, and vector types .....................--*/ - -/* lltype -> lltype array */ -value llvm_subtypes(LLVMTypeRef Ty) { - unsigned Size = LLVMGetNumContainedTypes(Ty); - value Arr = caml_alloc_tuple_uninit(Size); - LLVMGetSubtypes(Ty, (LLVMTypeRef *)Op_val(Arr)); - return Arr; -} - -/* lltype -> int -> lltype */ -LLVMTypeRef llvm_array_type(LLVMTypeRef ElementTy, value Count) { - return LLVMArrayType(ElementTy, Int_val(Count)); -} - -/* lltype -> lltype */ -LLVMTypeRef llvm_pointer_type(LLVMTypeRef ElementTy) { - return LLVMPointerType(ElementTy, 0); -} - -/* lltype -> int -> lltype */ -LLVMTypeRef llvm_qualified_pointer_type(LLVMTypeRef ElementTy, - value AddressSpace) { - return LLVMPointerType(ElementTy, Int_val(AddressSpace)); -} - -/* lltype -> int -> lltype */ -LLVMTypeRef llvm_vector_type(LLVMTypeRef ElementTy, value Count) { - return LLVMVectorType(ElementTy, Int_val(Count)); -} - -/* lltype -> int */ -value llvm_array_length(LLVMTypeRef ArrayTy) { - return Val_int(LLVMGetArrayLength(ArrayTy)); -} - -/* lltype -> int */ -value llvm_address_space(LLVMTypeRef PtrTy) { - return Val_int(LLVMGetPointerAddressSpace(PtrTy)); -} - -/* lltype -> int */ -value llvm_vector_size(LLVMTypeRef VectorTy) { - return Val_int(LLVMGetVectorSize(VectorTy)); -} - -/*--... Operations on other types ..........................................--*/ - -/* llcontext -> lltype */ -LLVMTypeRef llvm_void_type(LLVMContextRef Context) { - return LLVMVoidTypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_label_type(LLVMContextRef Context) { - return LLVMLabelTypeInContext(Context); -} - -/* llcontext -> lltype */ -LLVMTypeRef llvm_x86_mmx_type(LLVMContextRef Context) { - return LLVMX86MMXTypeInContext(Context); -} - -value llvm_type_by_name(LLVMModuleRef M, value Name) { - return ptr_to_option(LLVMGetTypeByName(M, String_val(Name))); -} - -/*===-- VALUES ------------------------------------------------------------===*/ - -/* llvalue -> lltype */ -LLVMTypeRef llvm_type_of(LLVMValueRef Val) { return LLVMTypeOf(Val); } - -/* keep in sync with ValueKind.t */ -enum ValueKind { - NullValue = 0, - Argument, - BasicBlock, - InlineAsm, - MDNode, - MDString, - BlockAddress, - ConstantAggregateZero, - ConstantArray, - ConstantDataArray, - ConstantDataVector, - ConstantExpr, - ConstantFP, - ConstantInt, - ConstantPointerNull, - ConstantStruct, - ConstantVector, - Function, - GlobalAlias, - GlobalIFunc, - GlobalVariable, - UndefValue, - PoisonValue, - Instruction -}; - -/* llvalue -> ValueKind.t */ -#define DEFINE_CASE(Val, Kind) \ - do {if (LLVMIsA##Kind(Val)) return Val_int(Kind);} while(0) - -value llvm_classify_value(LLVMValueRef Val) { - if (!Val) - return Val_int(NullValue); - if (LLVMIsAConstant(Val)) { - DEFINE_CASE(Val, BlockAddress); - DEFINE_CASE(Val, ConstantAggregateZero); - DEFINE_CASE(Val, ConstantArray); - DEFINE_CASE(Val, ConstantDataArray); - DEFINE_CASE(Val, ConstantDataVector); - DEFINE_CASE(Val, ConstantExpr); - DEFINE_CASE(Val, ConstantFP); - DEFINE_CASE(Val, ConstantInt); - DEFINE_CASE(Val, ConstantPointerNull); - DEFINE_CASE(Val, ConstantStruct); - DEFINE_CASE(Val, ConstantVector); - } - if (LLVMIsAInstruction(Val)) { - value result = caml_alloc_small(1, 0); - Field(result, 0) = Val_int(LLVMGetInstructionOpcode(Val)); - return result; - } - if (LLVMIsAGlobalValue(Val)) { - DEFINE_CASE(Val, Function); - DEFINE_CASE(Val, GlobalAlias); - DEFINE_CASE(Val, GlobalIFunc); - DEFINE_CASE(Val, GlobalVariable); - } - DEFINE_CASE(Val, Argument); - DEFINE_CASE(Val, BasicBlock); - DEFINE_CASE(Val, InlineAsm); - DEFINE_CASE(Val, MDNode); - DEFINE_CASE(Val, MDString); - DEFINE_CASE(Val, UndefValue); - DEFINE_CASE(Val, PoisonValue); - failwith("Unknown Value class"); -} - -/* llvalue -> string */ -value llvm_value_name(LLVMValueRef Val) { - return caml_copy_string(LLVMGetValueName(Val)); -} - -/* string -> llvalue -> unit */ -value llvm_set_value_name(value Name, LLVMValueRef Val) { - LLVMSetValueName(Val, String_val(Name)); - return Val_unit; -} - -/* llvalue -> unit */ -value llvm_dump_value(LLVMValueRef Val) { - LLVMDumpValue(Val); - return Val_unit; -} - -/* llvalue -> string */ -value llvm_string_of_llvalue(LLVMValueRef M) { - char *ValueCStr = LLVMPrintValueToString(M); - value ValueStr = caml_copy_string(ValueCStr); - LLVMDisposeMessage(ValueCStr); - - return ValueStr; -} - -/* llvalue -> llvalue -> unit */ -value llvm_replace_all_uses_with(LLVMValueRef OldVal, LLVMValueRef NewVal) { - LLVMReplaceAllUsesWith(OldVal, NewVal); - return Val_unit; -} - -/*--... Operations on users ................................................--*/ - -/* llvalue -> int -> llvalue */ -LLVMValueRef llvm_operand(LLVMValueRef V, value I) { - return LLVMGetOperand(V, Int_val(I)); -} - -/* llvalue -> int -> lluse */ -LLVMUseRef llvm_operand_use(LLVMValueRef V, value I) { - return LLVMGetOperandUse(V, Int_val(I)); -} - -/* llvalue -> int -> llvalue -> unit */ -value llvm_set_operand(LLVMValueRef U, value I, LLVMValueRef V) { - LLVMSetOperand(U, Int_val(I), V); - return Val_unit; -} - -/* llvalue -> int */ -value llvm_num_operands(LLVMValueRef V) { - return Val_int(LLVMGetNumOperands(V)); -} - -/* llvalue -> int array */ -value llvm_indices(LLVMValueRef Instr) { - unsigned n = LLVMGetNumIndices(Instr); - const unsigned *Indices = LLVMGetIndices(Instr); - value indices = caml_alloc_tuple_uninit(n); - for (unsigned i = 0; i < n; i++) { - Op_val(indices)[i] = Val_int(Indices[i]); - } - return indices; -} - -/*--... Operations on constants of (mostly) any type .......................--*/ - -/* llvalue -> bool */ -value llvm_is_constant(LLVMValueRef Val) { - return Val_bool(LLVMIsConstant(Val)); -} - -/* llvalue -> bool */ -value llvm_is_null(LLVMValueRef Val) { return Val_bool(LLVMIsNull(Val)); } - -/* llvalue -> bool */ -value llvm_is_undef(LLVMValueRef Val) { return Val_bool(LLVMIsUndef(Val)); } - -/* llvalue -> bool */ -value llvm_is_poison(LLVMValueRef Val) { return Val_bool(LLVMIsPoison(Val)); } - -/* llvalue -> Opcode.t */ -value llvm_constexpr_get_opcode(LLVMValueRef Val) { - return LLVMIsAConstantExpr(Val) ? Val_int(LLVMGetConstOpcode(Val)) - : Val_int(0); -} - -/*--... Operations on instructions .........................................--*/ - -/* llvalue -> bool */ -value llvm_has_metadata(LLVMValueRef Val) { - return Val_bool(LLVMHasMetadata(Val)); -} - -/* llvalue -> int -> llvalue option */ -value llvm_metadata(LLVMValueRef Val, value MDKindID) { - return ptr_to_option(LLVMGetMetadata(Val, Int_val(MDKindID))); -} - -/* llvalue -> int -> llvalue -> unit */ -value llvm_set_metadata(LLVMValueRef Val, value MDKindID, LLVMValueRef MD) { - LLVMSetMetadata(Val, Int_val(MDKindID), MD); - return Val_unit; -} - -/* llvalue -> int -> unit */ -value llvm_clear_metadata(LLVMValueRef Val, value MDKindID) { - LLVMSetMetadata(Val, Int_val(MDKindID), NULL); - return Val_unit; -} - -/*--... Operations on metadata .............................................--*/ - -/* llcontext -> string -> llvalue */ -LLVMValueRef llvm_mdstring(LLVMContextRef C, value S) { - return LLVMMDStringInContext(C, String_val(S), caml_string_length(S)); -} - -/* llcontext -> llvalue array -> llvalue */ -LLVMValueRef llvm_mdnode(LLVMContextRef C, value ElementVals) { - return LLVMMDNodeInContext(C, (LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals)); -} - -/* llcontext -> llvalue */ -LLVMValueRef llvm_mdnull(LLVMContextRef C) { return NULL; } - -/* llvalue -> string option */ -value llvm_get_mdstring(LLVMValueRef V) { - unsigned Len; - const char *CStr = LLVMGetMDString(V, &Len); - return cstr_to_string_option(CStr, Len); -} - -value llvm_get_mdnode_operands(LLVMValueRef V) { - unsigned int n = LLVMGetMDNodeNumOperands(V); - value Operands = caml_alloc_tuple_uninit(n); - LLVMGetMDNodeOperands(V, (LLVMValueRef *)Op_val(Operands)); - return Operands; -} - -/* llmodule -> string -> llvalue array */ -value llvm_get_namedmd(LLVMModuleRef M, value Name) { - CAMLparam1(Name); - value Nodes = caml_alloc_tuple_uninit( - LLVMGetNamedMetadataNumOperands(M, String_val(Name))); - LLVMGetNamedMetadataOperands(M, String_val(Name), - (LLVMValueRef *)Op_val(Nodes)); - CAMLreturn(Nodes); -} - -/* llmodule -> string -> llvalue -> unit */ -value llvm_append_namedmd(LLVMModuleRef M, value Name, LLVMValueRef Val) { - LLVMAddNamedMetadataOperand(M, String_val(Name), Val); - return Val_unit; -} - -/* llvalue -> llmetadata */ -LLVMMetadataRef llvm_value_as_metadata(LLVMValueRef Val) { - return LLVMValueAsMetadata(Val); -} - -/* llcontext -> llmetadata -> llvalue */ -LLVMValueRef llvm_metadata_as_value(LLVMContextRef C, LLVMMetadataRef MD) { - return LLVMMetadataAsValue(C, MD); -} - -/*--... Operations on scalar constants .....................................--*/ - -/* lltype -> int -> llvalue */ -LLVMValueRef llvm_const_int(LLVMTypeRef IntTy, value N) { - return LLVMConstInt(IntTy, (long long)Long_val(N), 1); -} - -/* lltype -> Int64.t -> bool -> llvalue */ -LLVMValueRef llvm_const_of_int64(LLVMTypeRef IntTy, value N, value SExt) { - return LLVMConstInt(IntTy, Int64_val(N), Bool_val(SExt)); -} - -/* llvalue -> Int64.t */ -value llvm_int64_of_const(LLVMValueRef Const) { - if (!(LLVMIsAConstantInt(Const)) || - !(LLVMGetIntTypeWidth(LLVMTypeOf(Const)) <= 64)) - return Val_none; - return caml_alloc_some(caml_copy_int64(LLVMConstIntGetSExtValue(Const))); -} - -/* lltype -> string -> int -> llvalue */ -LLVMValueRef llvm_const_int_of_string(LLVMTypeRef IntTy, value S, value Radix) { - return LLVMConstIntOfStringAndSize(IntTy, String_val(S), - caml_string_length(S), Int_val(Radix)); -} - -/* lltype -> float -> llvalue */ -LLVMValueRef llvm_const_float(LLVMTypeRef RealTy, value N) { - return LLVMConstReal(RealTy, Double_val(N)); -} - -/* llvalue -> float */ -value llvm_float_of_const(LLVMValueRef Const) { - LLVMBool LosesInfo; - double Result; - if (!LLVMIsAConstantFP(Const)) - return Val_none; - Result = LLVMConstRealGetDouble(Const, &LosesInfo); - if (LosesInfo) - return Val_none; - return caml_alloc_some(caml_copy_double(Result)); -} - -/* lltype -> string -> llvalue */ -LLVMValueRef llvm_const_float_of_string(LLVMTypeRef RealTy, value S) { - return LLVMConstRealOfStringAndSize(RealTy, String_val(S), - caml_string_length(S)); -} - -/*--... Operations on composite constants ..................................--*/ - -/* llcontext -> string -> llvalue */ -LLVMValueRef llvm_const_string(LLVMContextRef Context, value Str, - value NullTerminate) { - return LLVMConstStringInContext(Context, String_val(Str), string_length(Str), - 1); -} - -/* llcontext -> string -> llvalue */ -LLVMValueRef llvm_const_stringz(LLVMContextRef Context, value Str, - value NullTerminate) { - return LLVMConstStringInContext(Context, String_val(Str), string_length(Str), - 0); -} - -/* lltype -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_array(LLVMTypeRef ElementTy, value ElementVals) { - return LLVMConstArray(ElementTy, (LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals)); -} - -/* llcontext -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_struct(LLVMContextRef C, value ElementVals) { - return LLVMConstStructInContext(C, (LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals), 0); -} - -/* lltype -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_named_struct(LLVMTypeRef Ty, value ElementVals) { - return LLVMConstNamedStruct(Ty, (LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals)); -} - -/* llcontext -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_packed_struct(LLVMContextRef C, value ElementVals) { - return LLVMConstStructInContext(C, (LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals), 1); -} - -/* llvalue array -> llvalue */ -LLVMValueRef llvm_const_vector(value ElementVals) { - return LLVMConstVector((LLVMValueRef *)Op_val(ElementVals), - Wosize_val(ElementVals)); -} - -/* llvalue -> string option */ -value llvm_string_of_const(LLVMValueRef Const) { - size_t Len; - const char *CStr; - if (!LLVMIsAConstantDataSequential(Const) || !LLVMIsConstantString(Const)) - return Val_none; - CStr = LLVMGetAsString(Const, &Len); - return cstr_to_string_option(CStr, Len); -} - -/* llvalue -> int -> llvalue */ -LLVMValueRef llvm_const_element(LLVMValueRef Const, value N) { - return LLVMGetElementAsConstant(Const, Int_val(N)); -} - -/*--... Constant expressions ...............................................--*/ - -/* Icmp.t -> llvalue -> llvalue -> llvalue */ -LLVMValueRef llvm_const_icmp(value Pred, LLVMValueRef LHSConstant, - LLVMValueRef RHSConstant) { - return LLVMConstICmp(Int_val(Pred) + LLVMIntEQ, LHSConstant, RHSConstant); -} - -/* Fcmp.t -> llvalue -> llvalue -> llvalue */ -LLVMValueRef llvm_const_fcmp(value Pred, LLVMValueRef LHSConstant, - LLVMValueRef RHSConstant) { - return LLVMConstFCmp(Int_val(Pred), LHSConstant, RHSConstant); -} - -/* llvalue -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_gep(LLVMValueRef ConstantVal, value Indices) { - return LLVMConstGEP(ConstantVal, (LLVMValueRef *)Op_val(Indices), - Wosize_val(Indices)); -} - -/* llvalue -> llvalue array -> llvalue */ -LLVMValueRef llvm_const_in_bounds_gep(LLVMValueRef ConstantVal, value Indices) { - return LLVMConstInBoundsGEP(ConstantVal, (LLVMValueRef *)Op_val(Indices), - Wosize_val(Indices)); -} - -/* llvalue -> lltype -> is_signed:bool -> llvalue */ -LLVMValueRef llvm_const_intcast(LLVMValueRef CV, LLVMTypeRef T, - value IsSigned) { - return LLVMConstIntCast(CV, T, Bool_val(IsSigned)); -} - -/* llvalue -> int array -> llvalue */ -LLVMValueRef llvm_const_extractvalue(LLVMValueRef Aggregate, value Indices) { - int size = Wosize_val(Indices); - int i; - LLVMValueRef result; - - unsigned *idxs = (unsigned *)malloc(size * sizeof(unsigned)); - for (i = 0; i < size; i++) { - idxs[i] = Int_val(Field(Indices, i)); - } - - result = LLVMConstExtractValue(Aggregate, idxs, size); - free(idxs); - return result; -} - -/* llvalue -> llvalue -> int array -> llvalue */ -LLVMValueRef llvm_const_insertvalue(LLVMValueRef Aggregate, LLVMValueRef Val, - value Indices) { - int size = Wosize_val(Indices); - int i; - LLVMValueRef result; - - unsigned *idxs = (unsigned *)malloc(size * sizeof(unsigned)); - for (i = 0; i < size; i++) { - idxs[i] = Int_val(Field(Indices, i)); - } - - result = LLVMConstInsertValue(Aggregate, Val, idxs, size); - free(idxs); - return result; -} - -/* lltype -> string -> string -> bool -> bool -> llvalue */ -LLVMValueRef llvm_const_inline_asm(LLVMTypeRef Ty, value Asm, value Constraints, - value HasSideEffects, value IsAlignStack) { - return LLVMConstInlineAsm(Ty, String_val(Asm), String_val(Constraints), - Bool_val(HasSideEffects), Bool_val(IsAlignStack)); -} - -/*--... Operations on global variables, functions, and aliases (globals) ...--*/ - -/* llvalue -> bool */ -value llvm_is_declaration(LLVMValueRef Global) { - return Val_bool(LLVMIsDeclaration(Global)); -} - -/* llvalue -> Linkage.t */ -value llvm_linkage(LLVMValueRef Global) { - return Val_int(LLVMGetLinkage(Global)); -} - -/* Linkage.t -> llvalue -> unit */ -value llvm_set_linkage(value Linkage, LLVMValueRef Global) { - LLVMSetLinkage(Global, Int_val(Linkage)); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_unnamed_addr(LLVMValueRef Global) { - return Val_bool(LLVMHasUnnamedAddr(Global)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_unnamed_addr(value UseUnnamedAddr, LLVMValueRef Global) { - LLVMSetUnnamedAddr(Global, Bool_val(UseUnnamedAddr)); - return Val_unit; -} - -/* llvalue -> string */ -value llvm_section(LLVMValueRef Global) { - return caml_copy_string(LLVMGetSection(Global)); -} - -/* string -> llvalue -> unit */ -value llvm_set_section(value Section, LLVMValueRef Global) { - LLVMSetSection(Global, String_val(Section)); - return Val_unit; -} - -/* llvalue -> Visibility.t */ -value llvm_visibility(LLVMValueRef Global) { - return Val_int(LLVMGetVisibility(Global)); -} - -/* Visibility.t -> llvalue -> unit */ -value llvm_set_visibility(value Viz, LLVMValueRef Global) { - LLVMSetVisibility(Global, Int_val(Viz)); - return Val_unit; -} - -/* llvalue -> DLLStorageClass.t */ -value llvm_dll_storage_class(LLVMValueRef Global) { - return Val_int(LLVMGetDLLStorageClass(Global)); -} - -/* DLLStorageClass.t -> llvalue -> unit */ -value llvm_set_dll_storage_class(value Viz, LLVMValueRef Global) { - LLVMSetDLLStorageClass(Global, Int_val(Viz)); - return Val_unit; -} - -/* llvalue -> int */ -value llvm_alignment(LLVMValueRef Global) { - return Val_int(LLVMGetAlignment(Global)); -} - -/* int -> llvalue -> unit */ -value llvm_set_alignment(value Bytes, LLVMValueRef Global) { - LLVMSetAlignment(Global, Int_val(Bytes)); - return Val_unit; -} - -/* llvalue -> (llmdkind * llmetadata) array */ -value llvm_global_copy_all_metadata(LLVMValueRef Global) { - CAMLparam0(); - CAMLlocal1(Array); - size_t NumEntries; - LLVMValueMetadataEntry *Entries = - LLVMGlobalCopyAllMetadata(Global, &NumEntries); - Array = caml_alloc_tuple(NumEntries); - for (int i = 0; i < NumEntries; i++) { - value Pair = caml_alloc_small(2, 0); - Field(Pair, 0) = Val_int(LLVMValueMetadataEntriesGetKind(Entries, i)); - Field(Pair, 1) = (value)LLVMValueMetadataEntriesGetMetadata(Entries, i); - Store_field(Array, i, Pair); - } - LLVMDisposeValueMetadataEntries(Entries); - CAMLreturn(Array); -} - -/*--... Operations on uses .................................................--*/ - -/* llvalue -> lluse option */ -value llvm_use_begin(LLVMValueRef Val) { - return ptr_to_option(LLVMGetFirstUse(Val)); -} - -/* lluse -> lluse option */ -value llvm_use_succ(LLVMUseRef U) { return ptr_to_option(LLVMGetNextUse(U)); } - -/* lluse -> llvalue */ -LLVMValueRef llvm_user(LLVMUseRef UR) { return LLVMGetUser(UR); } - -/* lluse -> llvalue */ -LLVMValueRef llvm_used_value(LLVMUseRef UR) { return LLVMGetUsedValue(UR); } - -/*--... Operations on global variables .....................................--*/ - -DEFINE_ITERATORS(global, Global, LLVMModuleRef, LLVMValueRef, - LLVMGetGlobalParent) - -/* lltype -> string -> llmodule -> llvalue */ -LLVMValueRef llvm_declare_global(LLVMTypeRef Ty, value Name, LLVMModuleRef M) { - LLVMValueRef GlobalVar; - if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) { - if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty) - return LLVMConstBitCast(GlobalVar, LLVMPointerType(Ty, 0)); - return GlobalVar; - } - return LLVMAddGlobal(M, Ty, String_val(Name)); -} - -/* lltype -> string -> int -> llmodule -> llvalue */ -LLVMValueRef llvm_declare_qualified_global(LLVMTypeRef Ty, value Name, - value AddressSpace, - LLVMModuleRef M) { - LLVMValueRef GlobalVar; - if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) { - if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty) - return LLVMConstBitCast(GlobalVar, - LLVMPointerType(Ty, Int_val(AddressSpace))); - return GlobalVar; - } - return LLVMAddGlobalInAddressSpace(M, Ty, String_val(Name), - Int_val(AddressSpace)); -} - -/* string -> llmodule -> llvalue option */ -value llvm_lookup_global(value Name, LLVMModuleRef M) { - return ptr_to_option(LLVMGetNamedGlobal(M, String_val(Name))); -} - -/* string -> llvalue -> llmodule -> llvalue */ -LLVMValueRef llvm_define_global(value Name, LLVMValueRef Initializer, - LLVMModuleRef M) { - LLVMValueRef GlobalVar = - LLVMAddGlobal(M, LLVMTypeOf(Initializer), String_val(Name)); - LLVMSetInitializer(GlobalVar, Initializer); - return GlobalVar; -} - -/* string -> llvalue -> int -> llmodule -> llvalue */ -LLVMValueRef llvm_define_qualified_global(value Name, LLVMValueRef Initializer, - value AddressSpace, LLVMModuleRef M) { - LLVMValueRef GlobalVar = LLVMAddGlobalInAddressSpace( - M, LLVMTypeOf(Initializer), String_val(Name), Int_val(AddressSpace)); - LLVMSetInitializer(GlobalVar, Initializer); - return GlobalVar; -} - -/* llvalue -> unit */ -value llvm_delete_global(LLVMValueRef GlobalVar) { - LLVMDeleteGlobal(GlobalVar); - return Val_unit; -} - -/* llvalue -> llvalue option */ -value llvm_global_initializer(LLVMValueRef GlobalVar) { - return ptr_to_option(LLVMGetInitializer(GlobalVar)); -} - -/* llvalue -> llvalue -> unit */ -value llvm_set_initializer(LLVMValueRef ConstantVal, LLVMValueRef GlobalVar) { - LLVMSetInitializer(GlobalVar, ConstantVal); - return Val_unit; -} - -/* llvalue -> unit */ -value llvm_remove_initializer(LLVMValueRef GlobalVar) { - LLVMSetInitializer(GlobalVar, NULL); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_thread_local(LLVMValueRef GlobalVar) { - return Val_bool(LLVMIsThreadLocal(GlobalVar)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_thread_local(value IsThreadLocal, LLVMValueRef GlobalVar) { - LLVMSetThreadLocal(GlobalVar, Bool_val(IsThreadLocal)); - return Val_unit; -} - -/* llvalue -> ThreadLocalMode.t */ -value llvm_thread_local_mode(LLVMValueRef GlobalVar) { - return Val_int(LLVMGetThreadLocalMode(GlobalVar)); -} - -/* ThreadLocalMode.t -> llvalue -> unit */ -value llvm_set_thread_local_mode(value ThreadLocalMode, - LLVMValueRef GlobalVar) { - LLVMSetThreadLocalMode(GlobalVar, Int_val(ThreadLocalMode)); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_externally_initialized(LLVMValueRef GlobalVar) { - return Val_bool(LLVMIsExternallyInitialized(GlobalVar)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_externally_initialized(value IsExternallyInitialized, - LLVMValueRef GlobalVar) { - LLVMSetExternallyInitialized(GlobalVar, Bool_val(IsExternallyInitialized)); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_global_constant(LLVMValueRef GlobalVar) { - return Val_bool(LLVMIsGlobalConstant(GlobalVar)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_global_constant(value Flag, LLVMValueRef GlobalVar) { - LLVMSetGlobalConstant(GlobalVar, Bool_val(Flag)); - return Val_unit; -} - -/*--... Operations on aliases ..............................................--*/ - -LLVMValueRef llvm_add_alias(LLVMModuleRef M, LLVMTypeRef Ty, - LLVMValueRef Aliasee, value Name) { - return LLVMAddAlias(M, Ty, Aliasee, String_val(Name)); -} - -/*--... Operations on functions ............................................--*/ - -DEFINE_ITERATORS(function, Function, LLVMModuleRef, LLVMValueRef, - LLVMGetGlobalParent) - -/* string -> lltype -> llmodule -> llvalue */ -LLVMValueRef llvm_declare_function(value Name, LLVMTypeRef Ty, - LLVMModuleRef M) { - LLVMValueRef Fn; - if ((Fn = LLVMGetNamedFunction(M, String_val(Name)))) { - if (LLVMGetElementType(LLVMTypeOf(Fn)) != Ty) - return LLVMConstBitCast(Fn, LLVMPointerType(Ty, 0)); - return Fn; - } - return LLVMAddFunction(M, String_val(Name), Ty); -} - -/* string -> llmodule -> llvalue option */ -value llvm_lookup_function(value Name, LLVMModuleRef M) { - return ptr_to_option(LLVMGetNamedFunction(M, String_val(Name))); -} - -/* string -> lltype -> llmodule -> llvalue */ -LLVMValueRef llvm_define_function(value Name, LLVMTypeRef Ty, LLVMModuleRef M) { - LLVMValueRef Fn = LLVMAddFunction(M, String_val(Name), Ty); - LLVMAppendBasicBlockInContext(LLVMGetTypeContext(Ty), Fn, "entry"); - return Fn; -} - -/* llvalue -> unit */ -value llvm_delete_function(LLVMValueRef Fn) { - LLVMDeleteFunction(Fn); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_intrinsic(LLVMValueRef Fn) { - return Val_bool(LLVMGetIntrinsicID(Fn)); -} - -/* llvalue -> int */ -value llvm_function_call_conv(LLVMValueRef Fn) { - return Val_int(LLVMGetFunctionCallConv(Fn)); -} - -/* int -> llvalue -> unit */ -value llvm_set_function_call_conv(value Id, LLVMValueRef Fn) { - LLVMSetFunctionCallConv(Fn, Int_val(Id)); - return Val_unit; -} - -/* llvalue -> string option */ -value llvm_gc(LLVMValueRef Fn) { - const char *GC = LLVMGetGC(Fn); - if (!GC) - return Val_none; - return caml_alloc_some(caml_copy_string(GC)); -} - -/* string option -> llvalue -> unit */ -value llvm_set_gc(value GC, LLVMValueRef Fn) { - LLVMSetGC(Fn, GC == Val_none ? 0 : String_val(Field(GC, 0))); - return Val_unit; -} - -/* llvalue -> llattribute -> int -> unit */ -value llvm_add_function_attr(LLVMValueRef F, LLVMAttributeRef A, value Index) { - LLVMAddAttributeAtIndex(F, Int_val(Index), A); - return Val_unit; -} - -/* llvalue -> int -> llattribute array */ -value llvm_function_attrs(LLVMValueRef F, value Index) { - unsigned Length = LLVMGetAttributeCountAtIndex(F, Int_val(Index)); - value Array = caml_alloc_tuple_uninit(Length); - LLVMGetAttributesAtIndex(F, Int_val(Index), - (LLVMAttributeRef *)Op_val(Array)); - return Array; -} - -/* llvalue -> llattrkind -> int -> unit */ -value llvm_remove_enum_function_attr(LLVMValueRef F, value Kind, value Index) { - LLVMRemoveEnumAttributeAtIndex(F, Int_val(Index), Int_val(Kind)); - return Val_unit; -} - -/* llvalue -> string -> int -> unit */ -value llvm_remove_string_function_attr(LLVMValueRef F, value Kind, - value Index) { - LLVMRemoveStringAttributeAtIndex(F, Int_val(Index), String_val(Kind), - caml_string_length(Kind)); - return Val_unit; -} - -/*--... Operations on parameters ...........................................--*/ - -DEFINE_ITERATORS(param, Param, LLVMValueRef, LLVMValueRef, LLVMGetParamParent) - -/* llvalue -> int -> llvalue */ -LLVMValueRef llvm_param(LLVMValueRef Fn, value Index) { - return LLVMGetParam(Fn, Int_val(Index)); -} - -/* llvalue -> llvalue */ -value llvm_params(LLVMValueRef Fn) { - value Params = caml_alloc_tuple_uninit(LLVMCountParams(Fn)); - LLVMGetParams(Fn, (LLVMValueRef *)Op_val(Params)); - return Params; -} - -/*--... Operations on basic blocks .........................................--*/ - -DEFINE_ITERATORS(block, BasicBlock, LLVMValueRef, LLVMBasicBlockRef, - LLVMGetBasicBlockParent) - -/* llbasicblock -> llvalue option */ -value llvm_block_terminator(LLVMBasicBlockRef Block) { - return ptr_to_option(LLVMGetBasicBlockTerminator(Block)); -} - -/* llvalue -> llbasicblock array */ -value llvm_basic_blocks(LLVMValueRef Fn) { - value MLArray = caml_alloc_tuple_uninit(LLVMCountBasicBlocks(Fn)); - LLVMGetBasicBlocks(Fn, (LLVMBasicBlockRef *)Op_val(MLArray)); - return MLArray; -} - -/* llbasicblock -> unit */ -value llvm_delete_block(LLVMBasicBlockRef BB) { - LLVMDeleteBasicBlock(BB); - return Val_unit; -} - -/* llbasicblock -> unit */ -value llvm_remove_block(LLVMBasicBlockRef BB) { - LLVMRemoveBasicBlockFromParent(BB); - return Val_unit; -} - -/* llbasicblock -> llbasicblock -> unit */ -value llvm_move_block_before(LLVMBasicBlockRef Pos, LLVMBasicBlockRef BB) { - LLVMMoveBasicBlockBefore(BB, Pos); - return Val_unit; -} - -/* llbasicblock -> llbasicblock -> unit */ -value llvm_move_block_after(LLVMBasicBlockRef Pos, LLVMBasicBlockRef BB) { - LLVMMoveBasicBlockAfter(BB, Pos); - return Val_unit; -} - -/* string -> llvalue -> llbasicblock */ -LLVMBasicBlockRef llvm_append_block(LLVMContextRef Context, value Name, - LLVMValueRef Fn) { - return LLVMAppendBasicBlockInContext(Context, Fn, String_val(Name)); -} - -/* string -> llbasicblock -> llbasicblock */ -LLVMBasicBlockRef llvm_insert_block(LLVMContextRef Context, value Name, - LLVMBasicBlockRef BB) { - return LLVMInsertBasicBlockInContext(Context, BB, String_val(Name)); -} - -/* llvalue -> bool */ -value llvm_value_is_block(LLVMValueRef Val) { - return Val_bool(LLVMValueIsBasicBlock(Val)); -} - -/*--... Operations on instructions .........................................--*/ - -DEFINE_ITERATORS(instr, Instruction, LLVMBasicBlockRef, LLVMValueRef, - LLVMGetInstructionParent) - -/* llvalue -> Opcode.t */ -value llvm_instr_get_opcode(LLVMValueRef Inst) { - LLVMOpcode o; - if (!LLVMIsAInstruction(Inst)) - failwith("Not an instruction"); - o = LLVMGetInstructionOpcode(Inst); - assert(o <= LLVMFreeze); - return Val_int(o); -} - -/* llvalue -> ICmp.t option */ -value llvm_instr_icmp_predicate(LLVMValueRef Val) { - int x = LLVMGetICmpPredicate(Val); - if (!x) - return Val_none; - return caml_alloc_some(Val_int(x - LLVMIntEQ)); -} - -/* llvalue -> FCmp.t option */ -value llvm_instr_fcmp_predicate(LLVMValueRef Val) { - int x = LLVMGetFCmpPredicate(Val); - if (!x) - return Val_none; - return caml_alloc_some(Val_int(x - LLVMRealPredicateFalse)); -} - -/* llvalue -> llvalue */ -LLVMValueRef llvm_instr_clone(LLVMValueRef Inst) { - if (!LLVMIsAInstruction(Inst)) - failwith("Not an instruction"); - return LLVMInstructionClone(Inst); -} - -/*--... Operations on call sites ...........................................--*/ - -/* llvalue -> int */ -value llvm_instruction_call_conv(LLVMValueRef Inst) { - return Val_int(LLVMGetInstructionCallConv(Inst)); -} - -/* int -> llvalue -> unit */ -value llvm_set_instruction_call_conv(value CC, LLVMValueRef Inst) { - LLVMSetInstructionCallConv(Inst, Int_val(CC)); - return Val_unit; -} - -/* llvalue -> llattribute -> int -> unit */ -value llvm_add_call_site_attr(LLVMValueRef F, LLVMAttributeRef A, value Index) { - LLVMAddCallSiteAttribute(F, Int_val(Index), A); - return Val_unit; -} - -/* llvalue -> int -> llattribute array */ -value llvm_call_site_attrs(LLVMValueRef F, value Index) { - unsigned Count = LLVMGetCallSiteAttributeCount(F, Int_val(Index)); - value Array = caml_alloc_tuple_uninit(Count); - LLVMGetCallSiteAttributes(F, Int_val(Index), - (LLVMAttributeRef *)Op_val(Array)); - return Array; -} - -/* llvalue -> llattrkind -> int -> unit */ -value llvm_remove_enum_call_site_attr(LLVMValueRef F, value Kind, value Index) { - LLVMRemoveCallSiteEnumAttribute(F, Int_val(Index), Int_val(Kind)); - return Val_unit; -} - -/* llvalue -> string -> int -> unit */ -value llvm_remove_string_call_site_attr(LLVMValueRef F, value Kind, - value Index) { - LLVMRemoveCallSiteStringAttribute(F, Int_val(Index), String_val(Kind), - caml_string_length(Kind)); - return Val_unit; -} - -/*--... Operations on call instructions (only) .............................--*/ - -/* llvalue -> int */ -value llvm_num_arg_operands(LLVMValueRef V) { - return Val_int(LLVMGetNumArgOperands(V)); -} - -/* llvalue -> bool */ -value llvm_is_tail_call(LLVMValueRef CallInst) { - return Val_bool(LLVMIsTailCall(CallInst)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_tail_call(value IsTailCall, LLVMValueRef CallInst) { - LLVMSetTailCall(CallInst, Bool_val(IsTailCall)); - return Val_unit; -} - -/*--... Operations on load/store instructions (only)........................--*/ - -/* llvalue -> bool */ -value llvm_is_volatile(LLVMValueRef MemoryInst) { - return Val_bool(LLVMGetVolatile(MemoryInst)); -} - -/* bool -> llvalue -> unit */ -value llvm_set_volatile(value IsVolatile, LLVMValueRef MemoryInst) { - LLVMSetVolatile(MemoryInst, Bool_val(IsVolatile)); - return Val_unit; -} - -/*--.. Operations on terminators ...........................................--*/ - -/* llvalue -> int -> llbasicblock */ -LLVMBasicBlockRef llvm_successor(LLVMValueRef V, value I) { - return LLVMGetSuccessor(V, Int_val(I)); -} - -/* llvalue -> int -> llvalue -> unit */ -value llvm_set_successor(LLVMValueRef U, value I, LLVMBasicBlockRef B) { - LLVMSetSuccessor(U, Int_val(I), B); - return Val_unit; -} - -/* llvalue -> int */ -value llvm_num_successors(LLVMValueRef V) { - return Val_int(LLVMGetNumSuccessors(V)); -} - -/*--.. Operations on branch ................................................--*/ - -/* llvalue -> llvalue */ -LLVMValueRef llvm_condition(LLVMValueRef V) { return LLVMGetCondition(V); } - -/* llvalue -> llvalue -> unit */ -value llvm_set_condition(LLVMValueRef B, LLVMValueRef C) { - LLVMSetCondition(B, C); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_conditional(LLVMValueRef V) { - return Val_bool(LLVMIsConditional(V)); -} - -/*--... Operations on phi nodes ............................................--*/ - -/* (llvalue * llbasicblock) -> llvalue -> unit */ -value llvm_add_incoming(value Incoming, LLVMValueRef PhiNode) { - LLVMAddIncoming(PhiNode, (LLVMValueRef *)&Field(Incoming, 0), - (LLVMBasicBlockRef *)&Field(Incoming, 1), 1); - return Val_unit; -} - -/* llvalue -> (llvalue * llbasicblock) list */ -value llvm_incoming(LLVMValueRef PhiNode) { - unsigned I; - CAMLparam0(); - CAMLlocal2(Hd, Tl); - - /* Build a tuple list of them. */ - Tl = Val_int(0); - for (I = LLVMCountIncoming(PhiNode); I != 0;) { - Hd = caml_alloc_small(2, 0); - Field(Hd, 0) = (value)LLVMGetIncomingValue(PhiNode, --I); - Field(Hd, 1) = (value)LLVMGetIncomingBlock(PhiNode, I); - - value Tmp = caml_alloc_small(2, 0); - Field(Tmp, 0) = Hd; - Field(Tmp, 1) = Tl; - Tl = Tmp; - } - - CAMLreturn(Tl); -} - -/* llvalue -> unit */ -value llvm_delete_instruction(LLVMValueRef Instruction) { - LLVMInstructionEraseFromParent(Instruction); - return Val_unit; -} - -/*===-- Instruction builders ----------------------------------------------===*/ - -#define Builder_val(v) (*(LLVMBuilderRef *)(Data_custom_val(v))) - -static void llvm_finalize_builder(value B) { - LLVMDisposeBuilder(Builder_val(B)); -} - -static struct custom_operations builder_ops = { - (char *)"Llvm.llbuilder", llvm_finalize_builder, - custom_compare_default, custom_hash_default, - custom_serialize_default, custom_deserialize_default, - custom_compare_ext_default}; - -static value alloc_builder(LLVMBuilderRef B) { - value V = alloc_custom(&builder_ops, sizeof(LLVMBuilderRef), 0, 1); - Builder_val(V) = B; - return V; -} - -/* llcontext -> llbuilder */ -value llvm_builder(LLVMContextRef C) { - return alloc_builder(LLVMCreateBuilderInContext(C)); -} - -/* (llbasicblock, llvalue) llpos -> llbuilder -> unit */ -value llvm_position_builder(value Pos, value B) { - if (Tag_val(Pos) == 0) { - LLVMBasicBlockRef BB = (LLVMBasicBlockRef)Op_val(Field(Pos, 0)); - LLVMPositionBuilderAtEnd(Builder_val(B), BB); - } else { - LLVMValueRef I = (LLVMValueRef)Op_val(Field(Pos, 0)); - LLVMPositionBuilderBefore(Builder_val(B), I); - } - return Val_unit; -} - -/* llbuilder -> llbasicblock */ -LLVMBasicBlockRef llvm_insertion_block(value B) { - LLVMBasicBlockRef InsertBlock = LLVMGetInsertBlock(Builder_val(B)); - if (!InsertBlock) - caml_raise_not_found(); - return InsertBlock; -} - -/* llvalue -> string -> llbuilder -> unit */ -value llvm_insert_into_builder(LLVMValueRef I, value Name, value B) { - LLVMInsertIntoBuilderWithName(Builder_val(B), I, String_val(Name)); - return Val_unit; -} - -/*--... Metadata ...........................................................--*/ - -/* llbuilder -> llvalue -> unit */ -value llvm_set_current_debug_location(value B, LLVMValueRef V) { - LLVMSetCurrentDebugLocation(Builder_val(B), V); - return Val_unit; -} - -/* llbuilder -> unit */ -value llvm_clear_current_debug_location(value B) { - LLVMSetCurrentDebugLocation(Builder_val(B), NULL); - return Val_unit; -} - -/* llbuilder -> llvalue option */ -value llvm_current_debug_location(value B) { - return ptr_to_option(LLVMGetCurrentDebugLocation(Builder_val(B))); -} - -/* llbuilder -> llvalue -> unit */ -value llvm_set_inst_debug_location(value B, LLVMValueRef V) { - LLVMSetInstDebugLocation(Builder_val(B), V); - return Val_unit; -} - -/*--... Terminators ........................................................--*/ - -/* llbuilder -> llvalue */ -LLVMValueRef llvm_build_ret_void(value B) { - return LLVMBuildRetVoid(Builder_val(B)); -} - -/* llvalue -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_ret(LLVMValueRef Val, value B) { - return LLVMBuildRet(Builder_val(B), Val); -} - -/* llvalue array -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_aggregate_ret(value RetVals, value B) { - return LLVMBuildAggregateRet(Builder_val(B), (LLVMValueRef *)Op_val(RetVals), - Wosize_val(RetVals)); -} - -/* llbasicblock -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_br(LLVMBasicBlockRef BB, value B) { - return LLVMBuildBr(Builder_val(B), BB); -} - -/* llvalue -> llbasicblock -> llbasicblock -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_cond_br(LLVMValueRef If, LLVMBasicBlockRef Then, - LLVMBasicBlockRef Else, value B) { - return LLVMBuildCondBr(Builder_val(B), If, Then, Else); -} - -/* llvalue -> llbasicblock -> int -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_switch(LLVMValueRef Of, LLVMBasicBlockRef Else, - value EstimatedCount, value B) { - return LLVMBuildSwitch(Builder_val(B), Of, Else, Int_val(EstimatedCount)); -} - -/* lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_malloc(LLVMTypeRef Ty, value Name, value B) { - return LLVMBuildMalloc(Builder_val(B), Ty, String_val(Name)); -} - -/* lltype -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_array_malloc(LLVMTypeRef Ty, LLVMValueRef Val, - value Name, value B) { - return LLVMBuildArrayMalloc(Builder_val(B), Ty, Val, String_val(Name)); -} - -/* llvalue -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_free(LLVMValueRef P, value B) { - return LLVMBuildFree(Builder_val(B), P); -} - -/* llvalue -> llvalue -> llbasicblock -> unit */ -value llvm_add_case(LLVMValueRef Switch, LLVMValueRef OnVal, - LLVMBasicBlockRef Dest) { - LLVMAddCase(Switch, OnVal, Dest); - return Val_unit; -} - -/* llvalue -> llbasicblock -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_indirect_br(LLVMValueRef Addr, value EstimatedDests, - value B) { - return LLVMBuildIndirectBr(Builder_val(B), Addr, EstimatedDests); -} - -/* llvalue -> llvalue -> llbasicblock -> unit */ -value llvm_add_destination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) { - LLVMAddDestination(IndirectBr, Dest); - return Val_unit; -} - -/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string -> - llbuilder -> llvalue */ -LLVMValueRef llvm_build_invoke_nat(LLVMValueRef Fn, value Args, - LLVMBasicBlockRef Then, - LLVMBasicBlockRef Catch, value Name, - value B) { - return LLVMBuildInvoke(Builder_val(B), Fn, (LLVMValueRef *)Op_val(Args), - Wosize_val(Args), Then, Catch, String_val(Name)); -} - -/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string -> - llbuilder -> llvalue */ -LLVMValueRef llvm_build_invoke_bc(value Args[], int NumArgs) { - return llvm_build_invoke_nat((LLVMValueRef)Args[0], Args[1], - (LLVMBasicBlockRef)Args[2], - (LLVMBasicBlockRef)Args[3], Args[4], Args[5]); -} - -/* lltype -> llvalue -> int -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_landingpad(LLVMTypeRef Ty, LLVMValueRef PersFn, - value NumClauses, value Name, value B) { - return LLVMBuildLandingPad(Builder_val(B), Ty, PersFn, Int_val(NumClauses), - String_val(Name)); -} - -/* llvalue -> llvalue -> unit */ -value llvm_add_clause(LLVMValueRef LandingPadInst, LLVMValueRef ClauseVal) { - LLVMAddClause(LandingPadInst, ClauseVal); - return Val_unit; -} - -/* llvalue -> bool */ -value llvm_is_cleanup(LLVMValueRef LandingPadInst) { - return Val_bool(LLVMIsCleanup(LandingPadInst)); -} - -/* llvalue -> bool -> unit */ -value llvm_set_cleanup(LLVMValueRef LandingPadInst, value flag) { - LLVMSetCleanup(LandingPadInst, Bool_val(flag)); - return Val_unit; -} - -/* llvalue -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_resume(LLVMValueRef Exn, value B) { - return LLVMBuildResume(Builder_val(B), Exn); -} - -/* llbuilder -> llvalue */ -LLVMValueRef llvm_build_unreachable(value B) { - return LLVMBuildUnreachable(Builder_val(B)); -} - -/*--... Arithmetic .........................................................--*/ - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_add(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildAdd(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nsw_add(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNSWAdd(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nuw_add(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNUWAdd(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fadd(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildFAdd(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_sub(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildSub(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nsw_sub(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNSWSub(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nuw_sub(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNUWSub(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fsub(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildFSub(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_mul(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildMul(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nsw_mul(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNSWMul(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nuw_mul(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildNUWMul(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fmul(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildFMul(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_udiv(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildUDiv(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_sdiv(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildSDiv(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_exact_sdiv(LLVMValueRef LHS, LLVMValueRef RHS, - value Name, value B) { - return LLVMBuildExactSDiv(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fdiv(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildFDiv(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_urem(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildURem(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_srem(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildSRem(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_frem(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildFRem(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_shl(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildShl(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_lshr(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildLShr(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_ashr(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildAShr(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_and(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildAnd(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_or(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildOr(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_xor(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildXor(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_neg(LLVMValueRef X, value Name, value B) { - return LLVMBuildNeg(Builder_val(B), X, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nsw_neg(LLVMValueRef X, value Name, value B) { - return LLVMBuildNSWNeg(Builder_val(B), X, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_nuw_neg(LLVMValueRef X, value Name, value B) { - return LLVMBuildNUWNeg(Builder_val(B), X, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fneg(LLVMValueRef X, value Name, value B) { - return LLVMBuildFNeg(Builder_val(B), X, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_not(LLVMValueRef X, value Name, value B) { - return LLVMBuildNot(Builder_val(B), X, String_val(Name)); -} - -/*--... Memory .............................................................--*/ - -/* lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_alloca(LLVMTypeRef Ty, value Name, value B) { - return LLVMBuildAlloca(Builder_val(B), Ty, String_val(Name)); -} - -/* lltype -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_array_alloca(LLVMTypeRef Ty, LLVMValueRef Size, - value Name, value B) { - return LLVMBuildArrayAlloca(Builder_val(B), Ty, Size, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_load(LLVMValueRef Pointer, value Name, value B) { - return LLVMBuildLoad(Builder_val(B), Pointer, String_val(Name)); -} - -/* llvalue -> llvalue -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_store(LLVMValueRef Value, LLVMValueRef Pointer, - value B) { - return LLVMBuildStore(Builder_val(B), Value, Pointer); -} - -/* AtomicRMWBinOp.t -> llvalue -> llvalue -> AtomicOrdering.t -> - bool -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_atomicrmw_native(value BinOp, LLVMValueRef Ptr, - LLVMValueRef Val, value Ord, value ST, - value Name, value B) { - LLVMValueRef Instr; - Instr = LLVMBuildAtomicRMW(Builder_val(B), Int_val(BinOp), Ptr, Val, - Int_val(Ord), Bool_val(ST)); - LLVMSetValueName(Instr, String_val(Name)); - return Instr; -} - -LLVMValueRef llvm_build_atomicrmw_bytecode(value *argv, int argn) { - return llvm_build_atomicrmw_native(argv[0], (LLVMValueRef)argv[1], - (LLVMValueRef)argv[2], argv[3], argv[4], - argv[5], argv[6]); -} - -/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_gep(LLVMValueRef Pointer, value Indices, value Name, - value B) { - return LLVMBuildGEP(Builder_val(B), Pointer, (LLVMValueRef *)Op_val(Indices), - Wosize_val(Indices), String_val(Name)); -} - -/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_in_bounds_gep(LLVMValueRef Pointer, value Indices, - value Name, value B) { - return LLVMBuildInBoundsGEP(Builder_val(B), Pointer, - (LLVMValueRef *)Op_val(Indices), - Wosize_val(Indices), String_val(Name)); -} - -/* llvalue -> int -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_struct_gep(LLVMValueRef Pointer, value Index, - value Name, value B) { - return LLVMBuildStructGEP(Builder_val(B), Pointer, Int_val(Index), - String_val(Name)); -} - -/* string -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_global_string(value Str, value Name, value B) { - return LLVMBuildGlobalString(Builder_val(B), String_val(Str), - String_val(Name)); -} - -/* string -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_global_stringptr(value Str, value Name, value B) { - return LLVMBuildGlobalStringPtr(Builder_val(B), String_val(Str), - String_val(Name)); -} - -/*--... Casts ..............................................................--*/ - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_trunc(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildTrunc(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_zext(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildZExt(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_sext(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildSExt(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fptoui(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildFPToUI(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fptosi(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildFPToSI(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_uitofp(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildUIToFP(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_sitofp(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildSIToFP(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fptrunc(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildFPTrunc(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fpext(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildFPExt(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_prttoint(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildPtrToInt(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_inttoptr(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildIntToPtr(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_bitcast(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildBitCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_zext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty, - value Name, value B) { - return LLVMBuildZExtOrBitCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_sext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty, - value Name, value B) { - return LLVMBuildSExtOrBitCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_trunc_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty, - value Name, value B) { - return LLVMBuildTruncOrBitCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_pointercast(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildPointerCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_intcast(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildIntCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fpcast(LLVMValueRef X, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildFPCast(Builder_val(B), X, Ty, String_val(Name)); -} - -/*--... Comparisons ........................................................--*/ - -/* Icmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_icmp(value Pred, LLVMValueRef LHS, LLVMValueRef RHS, - value Name, value B) { - return LLVMBuildICmp(Builder_val(B), Int_val(Pred) + LLVMIntEQ, LHS, RHS, - String_val(Name)); -} - -/* Fcmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_fcmp(value Pred, LLVMValueRef LHS, LLVMValueRef RHS, - value Name, value B) { - return LLVMBuildFCmp(Builder_val(B), Int_val(Pred), LHS, RHS, - String_val(Name)); -} - -/*--... Miscellaneous instructions .........................................--*/ - -/* (llvalue * llbasicblock) list -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_phi(value Incoming, value Name, value B) { - value Hd, Tl; - LLVMValueRef FirstValue, PhiNode; - - assert(Incoming != Val_int(0) && "Empty list passed to Llvm.build_phi!"); - - Hd = Field(Incoming, 0); - FirstValue = (LLVMValueRef)Field(Hd, 0); - PhiNode = - LLVMBuildPhi(Builder_val(B), LLVMTypeOf(FirstValue), String_val(Name)); - - for (Tl = Incoming; Tl != Val_int(0); Tl = Field(Tl, 1)) { - value Hd = Field(Tl, 0); - LLVMAddIncoming(PhiNode, (LLVMValueRef *)&Field(Hd, 0), - (LLVMBasicBlockRef *)&Field(Hd, 1), 1); - } - - return PhiNode; -} - -/* lltype -> string -> llbuilder -> value */ -LLVMValueRef llvm_build_empty_phi(LLVMTypeRef Type, value Name, value B) { - return LLVMBuildPhi(Builder_val(B), Type, String_val(Name)); -} - -/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_call(LLVMValueRef Fn, value Params, value Name, - value B) { - return LLVMBuildCall(Builder_val(B), Fn, (LLVMValueRef *)Op_val(Params), - Wosize_val(Params), String_val(Name)); -} - -/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_select(LLVMValueRef If, LLVMValueRef Then, - LLVMValueRef Else, value Name, value B) { - return LLVMBuildSelect(Builder_val(B), If, Then, Else, String_val(Name)); -} - -/* llvalue -> lltype -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_va_arg(LLVMValueRef List, LLVMTypeRef Ty, value Name, - value B) { - return LLVMBuildVAArg(Builder_val(B), List, Ty, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_extractelement(LLVMValueRef Vec, LLVMValueRef Idx, - value Name, value B) { - return LLVMBuildExtractElement(Builder_val(B), Vec, Idx, String_val(Name)); -} - -/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_insertelement(LLVMValueRef Vec, LLVMValueRef Element, - LLVMValueRef Idx, value Name, value B) { - return LLVMBuildInsertElement(Builder_val(B), Vec, Element, Idx, - String_val(Name)); -} - -/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_shufflevector(LLVMValueRef V1, LLVMValueRef V2, - LLVMValueRef Mask, value Name, value B) { - return LLVMBuildShuffleVector(Builder_val(B), V1, V2, Mask, String_val(Name)); -} - -/* llvalue -> int -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_extractvalue(LLVMValueRef Aggregate, value Idx, - value Name, value B) { - return LLVMBuildExtractValue(Builder_val(B), Aggregate, Int_val(Idx), - String_val(Name)); -} - -/* llvalue -> llvalue -> int -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_insertvalue(LLVMValueRef Aggregate, LLVMValueRef Val, - value Idx, value Name, value B) { - return LLVMBuildInsertValue(Builder_val(B), Aggregate, Val, Int_val(Idx), - String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_is_null(LLVMValueRef Val, value Name, value B) { - return LLVMBuildIsNull(Builder_val(B), Val, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_is_not_null(LLVMValueRef Val, value Name, value B) { - return LLVMBuildIsNotNull(Builder_val(B), Val, String_val(Name)); -} - -/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_ptrdiff(LLVMValueRef LHS, LLVMValueRef RHS, value Name, - value B) { - return LLVMBuildPtrDiff(Builder_val(B), LHS, RHS, String_val(Name)); -} - -/* llvalue -> string -> llbuilder -> llvalue */ -LLVMValueRef llvm_build_freeze(LLVMValueRef X, value Name, value B) { - return LLVMBuildFreeze(Builder_val(B), X, String_val(Name)); -} - -/*===-- Memory buffers ----------------------------------------------------===*/ - -/* string -> llmemorybuffer - raises IoError msg on error */ -LLVMMemoryBufferRef llvm_memorybuffer_of_file(value Path) { - char *Message; - LLVMMemoryBufferRef MemBuf; - - if (LLVMCreateMemoryBufferWithContentsOfFile(String_val(Path), &MemBuf, - &Message)) - llvm_raise(*caml_named_value("Llvm.IoError"), Message); - - return MemBuf; -} - -/* unit -> llmemorybuffer - raises IoError msg on error */ -LLVMMemoryBufferRef llvm_memorybuffer_of_stdin(value Unit) { - char *Message; - LLVMMemoryBufferRef MemBuf; - - if (LLVMCreateMemoryBufferWithSTDIN(&MemBuf, &Message)) - llvm_raise(*caml_named_value("Llvm.IoError"), Message); - - return MemBuf; -} - -/* ?name:string -> string -> llmemorybuffer */ -LLVMMemoryBufferRef llvm_memorybuffer_of_string(value Name, value String) { - LLVMMemoryBufferRef MemBuf; - const char *NameCStr; - - if (Name == Val_int(0)) - NameCStr = ""; - else - NameCStr = String_val(Field(Name, 0)); - - MemBuf = LLVMCreateMemoryBufferWithMemoryRangeCopy( - String_val(String), caml_string_length(String), NameCStr); - - return MemBuf; -} - -/* llmemorybuffer -> string */ -value llvm_memorybuffer_as_string(LLVMMemoryBufferRef MemBuf) { - size_t BufferSize = LLVMGetBufferSize(MemBuf); - const char *BufferStart = LLVMGetBufferStart(MemBuf); - return cstr_to_string(BufferStart, BufferSize); -} - -/* llmemorybuffer -> unit */ -value llvm_memorybuffer_dispose(LLVMMemoryBufferRef MemBuf) { - LLVMDisposeMemoryBuffer(MemBuf); - return Val_unit; -} - -/*===-- Pass Managers -----------------------------------------------------===*/ - -/* unit -> [ `Module ] PassManager.t */ -LLVMPassManagerRef llvm_passmanager_create(value Unit) { - return LLVMCreatePassManager(); -} - -/* llmodule -> [ `Function ] PassManager.t -> bool */ -value llvm_passmanager_run_module(LLVMModuleRef M, LLVMPassManagerRef PM) { - return Val_bool(LLVMRunPassManager(PM, M)); -} - -/* [ `Function ] PassManager.t -> bool */ -value llvm_passmanager_initialize(LLVMPassManagerRef FPM) { - return Val_bool(LLVMInitializeFunctionPassManager(FPM)); -} - -/* llvalue -> [ `Function ] PassManager.t -> bool */ -value llvm_passmanager_run_function(LLVMValueRef F, LLVMPassManagerRef FPM) { - return Val_bool(LLVMRunFunctionPassManager(FPM, F)); -} - -/* [ `Function ] PassManager.t -> bool */ -value llvm_passmanager_finalize(LLVMPassManagerRef FPM) { - return Val_bool(LLVMFinalizeFunctionPassManager(FPM)); -} - -/* PassManager.any PassManager.t -> unit */ -value llvm_passmanager_dispose(LLVMPassManagerRef PM) { - LLVMDisposePassManager(PM); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.h b/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.h deleted file mode 100644 index 09e3c6cfb30d7..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/llvm/llvm_ocaml.h +++ /dev/null @@ -1,41 +0,0 @@ -/*===-- llvm_ocaml.h - LLVM OCaml Glue --------------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#ifndef LLVM_LLVM_OCAML_H -#define LLVM_LLVM_OCAML_H - -#include "caml/alloc.h" -#include "caml/custom.h" -#include "caml/version.h" - -#if OCAML_VERSION < 41200 -/* operations on OCaml option values, defined by OCaml 4.12 */ -#define Val_none Val_int(0) -#define Some_val(v) Field(v, 0) -#define Tag_some 0 -#define Is_none(v) ((v) == Val_none) -#define Is_some(v) Is_block(v) -value caml_alloc_some(value); -#endif - -/* Convert a C pointer to an OCaml option */ -value ptr_to_option(void *Ptr); - -/* Convert a C string into an OCaml string */ -value cstr_to_string(const char *Str, mlsize_t Len); - -#endif // LLVM_LLVM_OCAML_H diff --git a/interpreter/llvm/src/bindings/ocaml/target/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/target/CMakeLists.txt deleted file mode 100644 index 03fd231f7bea3..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/target/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_ocaml_library(llvm_target - OCAML llvm_target - OCAMLDEP llvm - C target_ocaml - CFLAGS "-I${CMAKE_CURRENT_SOURCE_DIR}/../llvm" - LLVM Target) diff --git a/interpreter/llvm/src/bindings/ocaml/target/llvm_target.ml b/interpreter/llvm/src/bindings/ocaml/target/llvm_target.ml deleted file mode 100644 index 0922ebe55345a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/target/llvm_target.ml +++ /dev/null @@ -1,135 +0,0 @@ -(*===-- llvm_target.ml - LLVM OCaml Interface ------------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -module Endian = struct - type t = - | Big - | Little -end - -module CodeGenOptLevel = struct - type t = - | None - | Less - | Default - | Aggressive -end - -module RelocMode = struct - type t = - | Default - | Static - | PIC - | DynamicNoPIC -end - -module CodeModel = struct - type t = - | Default - | JITDefault - | Small - | Kernel - | Medium - | Large -end - -module CodeGenFileType = struct - type t = - | AssemblyFile - | ObjectFile -end - -exception Error of string - -let () = Callback.register_exception "Llvm_target.Error" (Error "") - -module DataLayout = struct - type t - - external of_string : string -> t = "llvm_datalayout_of_string" - external as_string : t -> string = "llvm_datalayout_as_string" - external byte_order : t -> Endian.t = "llvm_datalayout_byte_order" - external pointer_size : t -> int = "llvm_datalayout_pointer_size" - external intptr_type : Llvm.llcontext -> t -> Llvm.lltype - = "llvm_datalayout_intptr_type" - external qualified_pointer_size : int -> t -> int - = "llvm_datalayout_qualified_pointer_size" - external qualified_intptr_type : Llvm.llcontext -> int -> t -> Llvm.lltype - = "llvm_datalayout_qualified_intptr_type" - external size_in_bits : Llvm.lltype -> t -> Int64.t - = "llvm_datalayout_size_in_bits" - external store_size : Llvm.lltype -> t -> Int64.t - = "llvm_datalayout_store_size" - external abi_size : Llvm.lltype -> t -> Int64.t - = "llvm_datalayout_abi_size" - external abi_align : Llvm.lltype -> t -> int - = "llvm_datalayout_abi_align" - external stack_align : Llvm.lltype -> t -> int - = "llvm_datalayout_stack_align" - external preferred_align : Llvm.lltype -> t -> int - = "llvm_datalayout_preferred_align" - external preferred_align_of_global : Llvm.llvalue -> t -> int - = "llvm_datalayout_preferred_align_of_global" - external element_at_offset : Llvm.lltype -> Int64.t -> t -> int - = "llvm_datalayout_element_at_offset" - external offset_of_element : Llvm.lltype -> int -> t -> Int64.t - = "llvm_datalayout_offset_of_element" -end - -module Target = struct - type t - - external default_triple : unit -> string = "llvm_target_default_triple" - external first : unit -> t option = "llvm_target_first" - external succ : t -> t option = "llvm_target_succ" - external by_name : string -> t option = "llvm_target_by_name" - external by_triple : string -> t = "llvm_target_by_triple" - external name : t -> string = "llvm_target_name" - external description : t -> string = "llvm_target_description" - external has_jit : t -> bool = "llvm_target_has_jit" - external has_target_machine : t -> bool = "llvm_target_has_target_machine" - external has_asm_backend : t -> bool = "llvm_target_has_asm_backend" - - let all () = - let rec step elem lst = - match elem with - | Some target -> step (succ target) (target :: lst) - | None -> lst - in - step (first ()) [] -end - -module TargetMachine = struct - type t - - external create : triple:string -> ?cpu:string -> ?features:string -> - ?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t -> - ?code_model:CodeModel.t -> Target.t -> t - = "llvm_create_targetmachine_bytecode" - "llvm_create_targetmachine_native" - external target : t -> Target.t - = "llvm_targetmachine_target" - external triple : t -> string - = "llvm_targetmachine_triple" - external cpu : t -> string - = "llvm_targetmachine_cpu" - external features : t -> string - = "llvm_targetmachine_features" - external data_layout : t -> DataLayout.t - = "llvm_targetmachine_data_layout" - external add_analysis_passes : [< Llvm.PassManager.any ] Llvm.PassManager.t -> t -> unit - = "llvm_targetmachine_add_analysis_passes" - external set_verbose_asm : bool -> t -> unit - = "llvm_targetmachine_set_verbose_asm" - external emit_to_file : Llvm.llmodule -> CodeGenFileType.t -> string -> - t -> unit - = "llvm_targetmachine_emit_to_file" - external emit_to_memory_buffer : Llvm.llmodule -> CodeGenFileType.t -> - t -> Llvm.llmemorybuffer - = "llvm_targetmachine_emit_to_memory_buffer" -end diff --git a/interpreter/llvm/src/bindings/ocaml/target/llvm_target.mli b/interpreter/llvm/src/bindings/ocaml/target/llvm_target.mli deleted file mode 100644 index 8d310793bea21..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/target/llvm_target.mli +++ /dev/null @@ -1,219 +0,0 @@ -(*===-- llvm_target.mli - LLVM OCaml Interface -----------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Target Information. - - This interface provides an OCaml API for LLVM target information, - the classes in the Target library. *) - -module Endian : sig - type t = - | Big - | Little -end - -module CodeGenOptLevel : sig - type t = - | None - | Less - | Default - | Aggressive -end - -module RelocMode : sig - type t = - | Default - | Static - | PIC - | DynamicNoPIC -end - -module CodeModel : sig - type t = - | Default - | JITDefault - | Small - | Kernel - | Medium - | Large -end - -module CodeGenFileType : sig - type t = - | AssemblyFile - | ObjectFile -end - -(** {6 Exceptions} *) - -exception Error of string - -(** {6 Data Layout} *) - -module DataLayout : sig - type t - - (** [of_string rep] parses the data layout string representation [rep]. - See the constructor [llvm::DataLayout::DataLayout]. *) - val of_string : string -> t - - (** [as_string dl] is the string representation of the data layout [dl]. - See the method [llvm::DataLayout::getStringRepresentation]. *) - val as_string : t -> string - - (** Returns the byte order of a target, either [Endian.Big] or - [Endian.Little]. - See the method [llvm::DataLayout::isLittleEndian]. *) - val byte_order : t -> Endian.t - - (** Returns the pointer size in bytes for a target. - See the method [llvm::DataLayout::getPointerSize]. *) - val pointer_size : t -> int - - (** Returns the integer type that is the same size as a pointer on a target. - See the method [llvm::DataLayout::getIntPtrType]. *) - val intptr_type : Llvm.llcontext -> t -> Llvm.lltype - - (** Returns the pointer size in bytes for a target in a given address space. - See the method [llvm::DataLayout::getPointerSize]. *) - val qualified_pointer_size : int -> t -> int - - (** Returns the integer type that is the same size as a pointer on a target - in a given address space. - See the method [llvm::DataLayout::getIntPtrType]. *) - val qualified_intptr_type : Llvm.llcontext -> int -> t -> Llvm.lltype - - (** Computes the size of a type in bits for a target. - See the method [llvm::DataLayout::getTypeSizeInBits]. *) - val size_in_bits : Llvm.lltype -> t -> Int64.t - - (** Computes the storage size of a type in bytes for a target. - See the method [llvm::DataLayout::getTypeStoreSize]. *) - val store_size : Llvm.lltype -> t -> Int64.t - - (** Computes the ABI size of a type in bytes for a target. - See the method [llvm::DataLayout::getTypeAllocSize]. *) - val abi_size : Llvm.lltype -> t -> Int64.t - - (** Computes the ABI alignment of a type in bytes for a target. - See the method [llvm::DataLayout::getTypeABISize]. *) - val abi_align : Llvm.lltype -> t -> int - - (** Computes the call frame alignment of a type in bytes for a target. - See the method [llvm::DataLayout::getTypeABISize]. *) - val stack_align : Llvm.lltype -> t -> int - - (** Computes the preferred alignment of a type in bytes for a target. - See the method [llvm::DataLayout::getTypeABISize]. *) - val preferred_align : Llvm.lltype -> t -> int - - (** Computes the preferred alignment of a global variable in bytes for - a target. See the method [llvm::DataLayout::getPreferredAlignment]. *) - val preferred_align_of_global : Llvm.llvalue -> t -> int - - (** Computes the structure element that contains the byte offset for a target. - See the method [llvm::StructLayout::getElementContainingOffset]. *) - val element_at_offset : Llvm.lltype -> Int64.t -> t -> int - - (** Computes the byte offset of the indexed struct element for a target. - See the method [llvm::StructLayout::getElementContainingOffset]. *) - val offset_of_element : Llvm.lltype -> int -> t -> Int64.t -end - -(** {6 Target} *) - -module Target : sig - type t - - (** [default_triple ()] returns the default target triple for current - platform. *) - val default_triple : unit -> string - - (** [first ()] returns the first target in the registered targets - list, or [None]. *) - val first : unit -> t option - - (** [succ t] returns the next target after [t], or [None] - if [t] was the last target. *) - val succ : t -> t option - - (** [all ()] returns a list of known targets. *) - val all : unit -> t list - - (** [by_name name] returns [Some t] if a target [t] named [name] is - registered, or [None] otherwise. *) - val by_name : string -> t option - - (** [by_triple triple] returns a target for a triple [triple], or raises - [Error] if [triple] does not correspond to a registered target. *) - val by_triple : string -> t - - (** Returns the name of a target. See [llvm::Target::getName]. *) - val name : t -> string - - (** Returns the description of a target. - See [llvm::Target::getDescription]. *) - val description : t -> string - - (** Returns [true] if the target has a JIT. *) - val has_jit : t -> bool - - (** Returns [true] if the target has a target machine associated. *) - val has_target_machine : t -> bool - - (** Returns [true] if the target has an ASM backend (required for - emitting output). *) - val has_asm_backend : t -> bool -end - -(** {6 Target Machine} *) - -module TargetMachine : sig - type t - - (** Creates a new target machine. - See [llvm::Target::createTargetMachine]. *) - val create : triple:string -> ?cpu:string -> ?features:string -> - ?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t -> - ?code_model:CodeModel.t -> Target.t -> t - - (** Returns the Target used in a TargetMachine *) - val target : t -> Target.t - - (** Returns the triple used while creating this target machine. See - [llvm::TargetMachine::getTriple]. *) - val triple : t -> string - - (** Returns the CPU used while creating this target machine. See - [llvm::TargetMachine::getCPU]. *) - val cpu : t -> string - - (** Returns the data layout of this target machine. *) - val data_layout : t -> DataLayout.t - - (** Returns the feature string used while creating this target machine. See - [llvm::TargetMachine::getFeatureString]. *) - val features : t -> string - - (** Adds the target-specific analysis passes to the pass manager. - See [llvm::TargetMachine::addAnalysisPasses]. *) - val add_analysis_passes : [< Llvm.PassManager.any ] Llvm.PassManager.t -> t -> unit - - (** Sets the assembly verbosity of this target machine. - See [llvm::TargetMachine::setAsmVerbosity]. *) - val set_verbose_asm : bool -> t -> unit - - (** Emits assembly or object data for the given module to the given - file or raise [Error]. *) - val emit_to_file : Llvm.llmodule -> CodeGenFileType.t -> string -> t -> unit - - (** Emits assembly or object data for the given module to a fresh memory - buffer or raise [Error]. *) - val emit_to_memory_buffer : Llvm.llmodule -> CodeGenFileType.t -> t -> - Llvm.llmemorybuffer -end diff --git a/interpreter/llvm/src/bindings/ocaml/target/target_ocaml.c b/interpreter/llvm/src/bindings/ocaml/target/target_ocaml.c deleted file mode 100644 index 2b7259bf2bc5f..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/target/target_ocaml.c +++ /dev/null @@ -1,336 +0,0 @@ -/*===-- target_ocaml.c - LLVM OCaml Glue ------------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Core.h" -#include "llvm-c/Target.h" -#include "llvm-c/TargetMachine.h" -#include "caml/alloc.h" -#include "caml/fail.h" -#include "caml/memory.h" -#include "caml/custom.h" -#include "caml/callback.h" -#include "llvm_ocaml.h" - -void llvm_raise(value Prototype, char *Message); -value llvm_string_of_message(char *Message); - -/*===---- Data Layout -----------------------------------------------------===*/ - -#define DataLayout_val(v) (*(LLVMTargetDataRef *)(Data_custom_val(v))) - -static void llvm_finalize_data_layout(value DataLayout) { - LLVMDisposeTargetData(DataLayout_val(DataLayout)); -} - -static struct custom_operations llvm_data_layout_ops = { - (char *)"Llvm_target.DataLayout.t", - llvm_finalize_data_layout, - custom_compare_default, - custom_hash_default, - custom_serialize_default, - custom_deserialize_default, - custom_compare_ext_default}; - -value llvm_alloc_data_layout(LLVMTargetDataRef DataLayout) { - value V = - alloc_custom(&llvm_data_layout_ops, sizeof(LLVMTargetDataRef), 0, 1); - DataLayout_val(V) = DataLayout; - return V; -} - -/* string -> DataLayout.t */ -value llvm_datalayout_of_string(value StringRep) { - return llvm_alloc_data_layout(LLVMCreateTargetData(String_val(StringRep))); -} - -/* DataLayout.t -> string */ -value llvm_datalayout_as_string(value TD) { - char *StringRep = LLVMCopyStringRepOfTargetData(DataLayout_val(TD)); - value Copy = copy_string(StringRep); - LLVMDisposeMessage(StringRep); - return Copy; -} - -/* DataLayout.t -> Endian.t */ -value llvm_datalayout_byte_order(value DL) { - return Val_int(LLVMByteOrder(DataLayout_val(DL))); -} - -/* DataLayout.t -> int */ -value llvm_datalayout_pointer_size(value DL) { - return Val_int(LLVMPointerSize(DataLayout_val(DL))); -} - -/* Llvm.llcontext -> DataLayout.t -> Llvm.lltype */ -LLVMTypeRef llvm_datalayout_intptr_type(LLVMContextRef C, value DL) { - return LLVMIntPtrTypeInContext(C, DataLayout_val(DL)); -} - -/* int -> DataLayout.t -> int */ -value llvm_datalayout_qualified_pointer_size(value AS, value DL) { - return Val_int(LLVMPointerSizeForAS(DataLayout_val(DL), Int_val(AS))); -} - -/* Llvm.llcontext -> int -> DataLayout.t -> Llvm.lltype */ -LLVMTypeRef llvm_datalayout_qualified_intptr_type(LLVMContextRef C, value AS, - value DL) { - return LLVMIntPtrTypeForASInContext(C, DataLayout_val(DL), Int_val(AS)); -} - -/* Llvm.lltype -> DataLayout.t -> Int64.t */ -value llvm_datalayout_size_in_bits(LLVMTypeRef Ty, value DL) { - return caml_copy_int64(LLVMSizeOfTypeInBits(DataLayout_val(DL), Ty)); -} - -/* Llvm.lltype -> DataLayout.t -> Int64.t */ -value llvm_datalayout_store_size(LLVMTypeRef Ty, value DL) { - return caml_copy_int64(LLVMStoreSizeOfType(DataLayout_val(DL), Ty)); -} - -/* Llvm.lltype -> DataLayout.t -> Int64.t */ -value llvm_datalayout_abi_size(LLVMTypeRef Ty, value DL) { - return caml_copy_int64(LLVMABISizeOfType(DataLayout_val(DL), Ty)); -} - -/* Llvm.lltype -> DataLayout.t -> int */ -value llvm_datalayout_abi_align(LLVMTypeRef Ty, value DL) { - return Val_int(LLVMABIAlignmentOfType(DataLayout_val(DL), Ty)); -} - -/* Llvm.lltype -> DataLayout.t -> int */ -value llvm_datalayout_stack_align(LLVMTypeRef Ty, value DL) { - return Val_int(LLVMCallFrameAlignmentOfType(DataLayout_val(DL), Ty)); -} - -/* Llvm.lltype -> DataLayout.t -> int */ -value llvm_datalayout_preferred_align(LLVMTypeRef Ty, value DL) { - return Val_int(LLVMPreferredAlignmentOfType(DataLayout_val(DL), Ty)); -} - -/* Llvm.llvalue -> DataLayout.t -> int */ -value llvm_datalayout_preferred_align_of_global(LLVMValueRef GlobalVar, - value DL) { - return Val_int(LLVMPreferredAlignmentOfGlobal(DataLayout_val(DL), GlobalVar)); -} - -/* Llvm.lltype -> Int64.t -> DataLayout.t -> int */ -value llvm_datalayout_element_at_offset(LLVMTypeRef Ty, value Offset, - value DL) { - return Val_int( - LLVMElementAtOffset(DataLayout_val(DL), Ty, Int64_val(Offset))); -} - -/* Llvm.lltype -> int -> DataLayout.t -> Int64.t */ -value llvm_datalayout_offset_of_element(LLVMTypeRef Ty, value Index, value DL) { - return caml_copy_int64( - LLVMOffsetOfElement(DataLayout_val(DL), Ty, Int_val(Index))); -} - -/*===---- Target ----------------------------------------------------------===*/ - -/* unit -> string */ -value llvm_target_default_triple(value Unit) { - char *TripleCStr = LLVMGetDefaultTargetTriple(); - value TripleStr = caml_copy_string(TripleCStr); - LLVMDisposeMessage(TripleCStr); - - return TripleStr; -} - -/* unit -> Target.t option */ -value llvm_target_first(value Unit) { - return ptr_to_option(LLVMGetFirstTarget()); -} - -/* Target.t -> Target.t option */ -value llvm_target_succ(LLVMTargetRef Target) { - return ptr_to_option(LLVMGetNextTarget(Target)); -} - -/* string -> Target.t option */ -value llvm_target_by_name(value Name) { - return ptr_to_option(LLVMGetTargetFromName(String_val(Name))); -} - -/* string -> Target.t */ -LLVMTargetRef llvm_target_by_triple(value Triple) { - LLVMTargetRef T; - char *Error; - - if (LLVMGetTargetFromTriple(String_val(Triple), &T, &Error)) - llvm_raise(*caml_named_value("Llvm_target.Error"), Error); - - return T; -} - -/* Target.t -> string */ -value llvm_target_name(LLVMTargetRef Target) { - return caml_copy_string(LLVMGetTargetName(Target)); -} - -/* Target.t -> string */ -value llvm_target_description(LLVMTargetRef Target) { - return caml_copy_string(LLVMGetTargetDescription(Target)); -} - -/* Target.t -> bool */ -value llvm_target_has_jit(LLVMTargetRef Target) { - return Val_bool(LLVMTargetHasJIT(Target)); -} - -/* Target.t -> bool */ -value llvm_target_has_target_machine(LLVMTargetRef Target) { - return Val_bool(LLVMTargetHasTargetMachine(Target)); -} - -/* Target.t -> bool */ -value llvm_target_has_asm_backend(LLVMTargetRef Target) { - return Val_bool(LLVMTargetHasAsmBackend(Target)); -} - -/*===---- Target Machine --------------------------------------------------===*/ - -#define TargetMachine_val(v) (*(LLVMTargetMachineRef *)(Data_custom_val(v))) - -static void llvm_finalize_target_machine(value Machine) { - LLVMDisposeTargetMachine(TargetMachine_val(Machine)); -} - -static struct custom_operations llvm_target_machine_ops = { - (char *)"Llvm_target.TargetMachine.t", - llvm_finalize_target_machine, - custom_compare_default, - custom_hash_default, - custom_serialize_default, - custom_deserialize_default, - custom_compare_ext_default}; - -static value llvm_alloc_targetmachine(LLVMTargetMachineRef Machine) { - value V = alloc_custom(&llvm_target_machine_ops, sizeof(LLVMTargetMachineRef), - 0, 1); - TargetMachine_val(V) = Machine; - return V; -} - -/* triple:string -> ?cpu:string -> ?features:string - ?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t - ?code_model:CodeModel.t -> Target.t -> TargetMachine.t */ -value llvm_create_targetmachine_native(value Triple, value CPU, value Features, - value OptLevel, value RelocMode, - value CodeModel, LLVMTargetRef Target) { - LLVMTargetMachineRef Machine; - const char *CPUStr = "", *FeaturesStr = ""; - LLVMCodeGenOptLevel OptLevelEnum = LLVMCodeGenLevelDefault; - LLVMRelocMode RelocModeEnum = LLVMRelocDefault; - LLVMCodeModel CodeModelEnum = LLVMCodeModelDefault; - - if (CPU != Val_int(0)) - CPUStr = String_val(Field(CPU, 0)); - if (Features != Val_int(0)) - FeaturesStr = String_val(Field(Features, 0)); - if (OptLevel != Val_int(0)) - OptLevelEnum = Int_val(Field(OptLevel, 0)); - if (RelocMode != Val_int(0)) - RelocModeEnum = Int_val(Field(RelocMode, 0)); - if (CodeModel != Val_int(0)) - CodeModelEnum = Int_val(Field(CodeModel, 0)); - - Machine = - LLVMCreateTargetMachine(Target, String_val(Triple), CPUStr, FeaturesStr, - OptLevelEnum, RelocModeEnum, CodeModelEnum); - - return llvm_alloc_targetmachine(Machine); -} - -value llvm_create_targetmachine_bytecode(value *argv, int argn) { - return llvm_create_targetmachine_native(argv[0], argv[1], argv[2], argv[3], - argv[4], argv[5], - (LLVMTargetRef)argv[6]); -} - -/* TargetMachine.t -> Target.t */ -LLVMTargetRef llvm_targetmachine_target(value Machine) { - return LLVMGetTargetMachineTarget(TargetMachine_val(Machine)); -} - -/* TargetMachine.t -> string */ -value llvm_targetmachine_triple(value Machine) { - return llvm_string_of_message( - LLVMGetTargetMachineTriple(TargetMachine_val(Machine))); -} - -/* TargetMachine.t -> string */ -value llvm_targetmachine_cpu(value Machine) { - return llvm_string_of_message( - LLVMGetTargetMachineCPU(TargetMachine_val(Machine))); -} - -/* TargetMachine.t -> string */ -value llvm_targetmachine_features(value Machine) { - return llvm_string_of_message( - LLVMGetTargetMachineFeatureString(TargetMachine_val(Machine))); -} - -/* TargetMachine.t -> DataLayout.t */ -value llvm_targetmachine_data_layout(value Machine) { - return llvm_alloc_data_layout( - LLVMCreateTargetDataLayout(TargetMachine_val(Machine))); -} - -/* bool -> TargetMachine.t -> unit */ -value llvm_targetmachine_set_verbose_asm(value Verb, value Machine) { - LLVMSetTargetMachineAsmVerbosity(TargetMachine_val(Machine), Bool_val(Verb)); - return Val_unit; -} - -/* Llvm.llmodule -> CodeGenFileType.t -> string -> TargetMachine.t -> unit */ -value llvm_targetmachine_emit_to_file(LLVMModuleRef Module, value FileType, - value FileName, value Machine) { - char *ErrorMessage; - - if (LLVMTargetMachineEmitToFile(TargetMachine_val(Machine), Module, - (char *)String_val(FileName), - Int_val(FileType), &ErrorMessage)) { - llvm_raise(*caml_named_value("Llvm_target.Error"), ErrorMessage); - } - - return Val_unit; -} - -/* Llvm.llmodule -> CodeGenFileType.t -> TargetMachine.t -> - Llvm.llmemorybuffer */ -LLVMMemoryBufferRef -llvm_targetmachine_emit_to_memory_buffer(LLVMModuleRef Module, value FileType, - value Machine) { - char *ErrorMessage; - LLVMMemoryBufferRef Buffer; - - if (LLVMTargetMachineEmitToMemoryBuffer(TargetMachine_val(Machine), Module, - Int_val(FileType), &ErrorMessage, - &Buffer)) { - llvm_raise(*caml_named_value("Llvm_target.Error"), ErrorMessage); - } - - return Buffer; -} - -/* TargetMachine.t -> Llvm.PassManager.t -> unit */ -value llvm_targetmachine_add_analysis_passes(LLVMPassManagerRef PM, - value Machine) { - LLVMAddAnalysisPasses(TargetMachine_val(Machine), PM); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/CMakeLists.txt deleted file mode 100644 index beb8694019b7a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_subdirectory(ipo) -add_subdirectory(passmgr_builder) -add_subdirectory(scalar_opts) -add_subdirectory(utils) -add_subdirectory(vectorize) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/ipo/CMakeLists.txt deleted file mode 100644 index 4b8784fad67bb..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_ipo - OCAML llvm_ipo - OCAMLDEP llvm - C ipo_ocaml - LLVM ipo) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/ipo_ocaml.c b/interpreter/llvm/src/bindings/ocaml/transforms/ipo/ipo_ocaml.c deleted file mode 100644 index e18b97a1509b0..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/ipo_ocaml.c +++ /dev/null @@ -1,104 +0,0 @@ -/*===-- ipo_ocaml.c - LLVM OCaml Glue ---------------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Transforms/IPO.h" -#include "caml/mlvalues.h" -#include "caml/misc.h" - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_argument_promotion(LLVMPassManagerRef PM) { - LLVMAddArgumentPromotionPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_constant_merge(LLVMPassManagerRef PM) { - LLVMAddConstantMergePass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_merge_functions(LLVMPassManagerRef PM) { - LLVMAddMergeFunctionsPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_dead_arg_elimination(LLVMPassManagerRef PM) { - LLVMAddDeadArgEliminationPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_function_attrs(LLVMPassManagerRef PM) { - LLVMAddFunctionAttrsPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_function_inlining(LLVMPassManagerRef PM) { - LLVMAddFunctionInliningPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_always_inliner(LLVMPassManagerRef PM) { - LLVMAddAlwaysInlinerPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_global_dce(LLVMPassManagerRef PM) { - LLVMAddGlobalDCEPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_global_optimizer(LLVMPassManagerRef PM) { - LLVMAddGlobalOptimizerPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_prune_eh(LLVMPassManagerRef PM) { - LLVMAddPruneEHPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_ipsccp(LLVMPassManagerRef PM) { - LLVMAddIPSCCPPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> all_but_main:bool -> unit */ -value llvm_add_internalize(LLVMPassManagerRef PM, value AllButMain) { - LLVMAddInternalizePass(PM, Bool_val(AllButMain)); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_strip_dead_prototypes(LLVMPassManagerRef PM) { - LLVMAddStripDeadPrototypesPass(PM); - return Val_unit; -} - -/* [`Module] Llvm.PassManager.t -> unit */ -value llvm_add_strip_symbols(LLVMPassManagerRef PM) { - LLVMAddStripSymbolsPass(PM); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.ml b/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.ml deleted file mode 100644 index d5d959288d332..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.ml +++ /dev/null @@ -1,50 +0,0 @@ -(*===-- llvm_ipo.ml - LLVM OCaml Interface --------------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external add_argument_promotion - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_argument_promotion" -external add_constant_merge - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_constant_merge" -external add_merge_functions - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_merge_functions" -external add_dead_arg_elimination - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_dead_arg_elimination" -external add_function_attrs - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_function_attrs" -external add_function_inlining - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_function_inlining" -external add_always_inliner - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_always_inliner" -external add_global_dce - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_global_dce" -external add_global_optimizer - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_global_optimizer" -external add_prune_eh - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_prune_eh" -external add_ipsccp - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_ipsccp" -external add_internalize - : [ `Module ] Llvm.PassManager.t -> all_but_main:bool -> unit - = "llvm_add_internalize" -external add_strip_dead_prototypes - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_strip_dead_prototypes" -external add_strip_symbols - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_strip_symbols" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.mli b/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.mli deleted file mode 100644 index a581924c6d549..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/ipo/llvm_ipo.mli +++ /dev/null @@ -1,82 +0,0 @@ -(*===-- llvm_ipo.mli - LLVM OCaml Interface -------------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** IPO Transforms. - - This interface provides an OCaml API for LLVM interprocedural optimizations, the - classes in the [LLVMIPO] library. *) - -(** See the [llvm::createAddArgumentPromotionPass] function. *) -external add_argument_promotion - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_argument_promotion" - -(** See the [llvm::createConstantMergePass] function. *) -external add_constant_merge - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_constant_merge" - -(** See the [llvm::createMergeFunctionsPass] function. *) -external add_merge_functions - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_merge_functions" - -(** See the [llvm::createDeadArgEliminationPass] function. *) -external add_dead_arg_elimination - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_dead_arg_elimination" - -(** See the [llvm::createFunctionAttrsPass] function. *) -external add_function_attrs - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_function_attrs" - -(** See the [llvm::createFunctionInliningPass] function. *) -external add_function_inlining - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_function_inlining" - -(** See the [llvm::createAlwaysInlinerPass] function. *) -external add_always_inliner - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_always_inliner" - -(** See the [llvm::createGlobalDCEPass] function. *) -external add_global_dce - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_global_dce" - -(** See the [llvm::createGlobalOptimizerPass] function. *) -external add_global_optimizer - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_global_optimizer" - -(** See the [llvm::createPruneEHPass] function. *) -external add_prune_eh - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_prune_eh" - -(** See the [llvm::createIPSCCPPass] function. *) -external add_ipsccp - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_ipsccp" - -(** See the [llvm::createInternalizePass] function. *) -external add_internalize - : [ `Module ] Llvm.PassManager.t -> all_but_main:bool -> unit - = "llvm_add_internalize" - -(** See the [llvm::createStripDeadPrototypesPass] function. *) -external add_strip_dead_prototypes - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_strip_dead_prototypes" - -(** See the [llvm::createStripSymbolsPass] function. *) -external add_strip_symbols - : [ `Module ] Llvm.PassManager.t -> unit - = "llvm_add_strip_symbols" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/CMakeLists.txt deleted file mode 100644 index b012863d8ec7e..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_passmgr_builder - OCAML llvm_passmgr_builder - OCAMLDEP llvm - C passmgr_builder_ocaml - LLVM ipo) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.ml b/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.ml deleted file mode 100644 index f143eaf26eb02..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.ml +++ /dev/null @@ -1,31 +0,0 @@ -(*===-- llvm_passmgr_builder.ml - LLVM OCaml Interface --------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -type t - -external create : unit -> t - = "llvm_pmbuilder_create" -external set_opt_level : int -> t -> unit - = "llvm_pmbuilder_set_opt_level" -external set_size_level : int -> t -> unit - = "llvm_pmbuilder_set_size_level" -external set_disable_unit_at_a_time : bool -> t -> unit - = "llvm_pmbuilder_set_disable_unit_at_a_time" -external set_disable_unroll_loops : bool -> t -> unit - = "llvm_pmbuilder_set_disable_unroll_loops" -external use_inliner_with_threshold : int -> t -> unit - = "llvm_pmbuilder_use_inliner_with_threshold" -external populate_function_pass_manager - : [ `Function ] Llvm.PassManager.t -> t -> unit - = "llvm_pmbuilder_populate_function_pass_manager" -external populate_module_pass_manager - : [ `Module ] Llvm.PassManager.t -> t -> unit - = "llvm_pmbuilder_populate_module_pass_manager" -external populate_lto_pass_manager - : [ `Module ] Llvm.PassManager.t -> internalize:bool -> run_inliner:bool -> t -> unit - = "llvm_pmbuilder_populate_lto_pass_manager" \ No newline at end of file diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.mli b/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.mli deleted file mode 100644 index 8bb1005e6d461..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/llvm_passmgr_builder.mli +++ /dev/null @@ -1,53 +0,0 @@ -(*===-- llvm_passmgr_builder.mli - LLVM OCaml Interface -------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Pass Manager Builder. - - This interface provides an OCaml API for LLVM pass manager builder - from the [LLVMCore] library. *) - -type t - -(** See the [llvm::PassManagerBuilder] function. *) -external create : unit -> t - = "llvm_pmbuilder_create" - -(** See the [llvm::PassManagerBuilder::OptLevel] function. *) -external set_opt_level : int -> t -> unit - = "llvm_pmbuilder_set_opt_level" - -(** See the [llvm::PassManagerBuilder::SizeLevel] function. *) -external set_size_level : int -> t -> unit - = "llvm_pmbuilder_set_size_level" - -(** See the [llvm::PassManagerBuilder::DisableUnitAtATime] function. *) -external set_disable_unit_at_a_time : bool -> t -> unit - = "llvm_pmbuilder_set_disable_unit_at_a_time" - -(** See the [llvm::PassManagerBuilder::DisableUnrollLoops] function. *) -external set_disable_unroll_loops : bool -> t -> unit - = "llvm_pmbuilder_set_disable_unroll_loops" - -(** See the [llvm::PassManagerBuilder::Inliner] function. *) -external use_inliner_with_threshold : int -> t -> unit - = "llvm_pmbuilder_use_inliner_with_threshold" - -(** See the [llvm::PassManagerBuilder::populateFunctionPassManager] function. *) -external populate_function_pass_manager - : [ `Function ] Llvm.PassManager.t -> t -> unit - = "llvm_pmbuilder_populate_function_pass_manager" - -(** See the [llvm::PassManagerBuilder::populateModulePassManager] function. *) -external populate_module_pass_manager - : [ `Module ] Llvm.PassManager.t -> t -> unit - = "llvm_pmbuilder_populate_module_pass_manager" - -(** See the [llvm::PassManagerBuilder::populateLTOPassManager] function. *) -external populate_lto_pass_manager - : [ `Module ] Llvm.PassManager.t -> internalize:bool -> run_inliner:bool -> t -> unit - = "llvm_pmbuilder_populate_lto_pass_manager" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/passmgr_builder_ocaml.c b/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/passmgr_builder_ocaml.c deleted file mode 100644 index 678967a5ede69..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/passmgr_builder/passmgr_builder_ocaml.c +++ /dev/null @@ -1,102 +0,0 @@ -/*===-- passmgr_builder_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Transforms/PassManagerBuilder.h" -#include "caml/mlvalues.h" -#include "caml/custom.h" -#include "caml/misc.h" - -#define PMBuilder_val(v) (*(LLVMPassManagerBuilderRef *)(Data_custom_val(v))) - -static void llvm_finalize_pmbuilder(value PMB) { - LLVMPassManagerBuilderDispose(PMBuilder_val(PMB)); -} - -static struct custom_operations pmbuilder_ops = { - (char *)"Llvm_passmgr_builder.t", llvm_finalize_pmbuilder, - custom_compare_default, custom_hash_default, - custom_serialize_default, custom_deserialize_default, - custom_compare_ext_default}; - -static value alloc_pmbuilder(LLVMPassManagerBuilderRef Ref) { - value Val = - alloc_custom(&pmbuilder_ops, sizeof(LLVMPassManagerBuilderRef), 0, 1); - PMBuilder_val(Val) = Ref; - return Val; -} - -/* t -> unit */ -value llvm_pmbuilder_create(value Unit) { - return alloc_pmbuilder(LLVMPassManagerBuilderCreate()); -} - -/* int -> t -> unit */ -value llvm_pmbuilder_set_opt_level(value OptLevel, value PMB) { - LLVMPassManagerBuilderSetOptLevel(PMBuilder_val(PMB), Int_val(OptLevel)); - return Val_unit; -} - -/* int -> t -> unit */ -value llvm_pmbuilder_set_size_level(value SizeLevel, value PMB) { - LLVMPassManagerBuilderSetSizeLevel(PMBuilder_val(PMB), Int_val(SizeLevel)); - return Val_unit; -} - -/* int -> t -> unit */ -value llvm_pmbuilder_use_inliner_with_threshold(value Threshold, value PMB) { - LLVMPassManagerBuilderSetOptLevel(PMBuilder_val(PMB), Int_val(Threshold)); - return Val_unit; -} - -/* bool -> t -> unit */ -value llvm_pmbuilder_set_disable_unit_at_a_time(value DisableUnitAtATime, - value PMB) { - LLVMPassManagerBuilderSetDisableUnitAtATime(PMBuilder_val(PMB), - Bool_val(DisableUnitAtATime)); - return Val_unit; -} - -/* bool -> t -> unit */ -value llvm_pmbuilder_set_disable_unroll_loops(value DisableUnroll, value PMB) { - LLVMPassManagerBuilderSetDisableUnrollLoops(PMBuilder_val(PMB), - Bool_val(DisableUnroll)); - return Val_unit; -} - -/* [ `Function ] Llvm.PassManager.t -> t -> unit */ -value llvm_pmbuilder_populate_function_pass_manager(LLVMPassManagerRef PM, - value PMB) { - LLVMPassManagerBuilderPopulateFunctionPassManager(PMBuilder_val(PMB), PM); - return Val_unit; -} - -/* [ `Module ] Llvm.PassManager.t -> t -> unit */ -value llvm_pmbuilder_populate_module_pass_manager(LLVMPassManagerRef PM, - value PMB) { - LLVMPassManagerBuilderPopulateModulePassManager(PMBuilder_val(PMB), PM); - return Val_unit; -} - -/* [ `Module ] Llvm.PassManager.t -> - internalize:bool -> run_inliner:bool -> t -> unit */ -value llvm_pmbuilder_populate_lto_pass_manager(LLVMPassManagerRef PM, - value Internalize, - value RunInliner, value PMB) { - LLVMPassManagerBuilderPopulateLTOPassManager( - PMBuilder_val(PMB), PM, Bool_val(Internalize), Bool_val(RunInliner)); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/CMakeLists.txt deleted file mode 100644 index d680b02046c6b..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_scalar_opts - OCAML llvm_scalar_opts - OCAMLDEP llvm - C scalar_opts_ocaml - LLVM Scalar) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.ml b/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.ml deleted file mode 100644 index b1b0db39a91fe..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.ml +++ /dev/null @@ -1,128 +0,0 @@ -(*===-- llvm_scalar_opts.ml - LLVM OCaml Interface ------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external add_aggressive_dce - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_aggressive_dce" -external add_dce - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_dce" -external add_alignment_from_assumptions - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_alignment_from_assumptions" -external add_cfg_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_cfg_simplification" -external add_dead_store_elimination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_dead_store_elimination" -external add_scalarizer - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalarizer" -external add_merged_load_store_motion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_merged_load_store_motion" -external add_gvn - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_gvn" -external add_ind_var_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_ind_var_simplify" -external add_instruction_combination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_instruction_combining" -external add_jump_threading - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_jump_threading" -external add_licm - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_licm" -external add_loop_deletion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_deletion" -external add_loop_idiom - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_idiom" -external add_loop_rotation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_rotate" -external add_loop_reroll - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_reroll" -external add_loop_unroll - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_unroll" -external add_loop_unswitch - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_unswitch" -external add_memcpy_opt - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_memcpy_opt" -external add_partially_inline_lib_calls - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_partially_inline_lib_calls" -external add_lower_atomic - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_atomic" -external add_lower_switch - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_switch" -external add_memory_to_register_promotion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_promote_memory_to_register" -external add_reassociation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_reassociation" -external add_sccp - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_sccp" -external add_scalar_repl_aggregation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates" -external add_scalar_repl_aggregation_ssa - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates_ssa" -external add_scalar_repl_aggregation_with_threshold - : int -> [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates_with_threshold" -external add_lib_call_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_simplify_lib_calls" -external add_tail_call_elimination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_tail_call_elimination" -external add_memory_to_register_demotion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_demote_memory_to_register" -external add_verifier - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_verifier" -external add_correlated_value_propagation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_correlated_value_propagation" -external add_early_cse - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_early_cse" -external add_lower_expect_intrinsic - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_expect_intrinsic" -external add_lower_constant_intrinsics - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_constant_intrinsics" -external add_type_based_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_type_based_alias_analysis" -external add_scoped_no_alias_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scoped_no_alias_aa" -external add_basic_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_basic_alias_analysis" -external add_unify_function_exit_nodes - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_unify_function_exit_nodes" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.mli b/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.mli deleted file mode 100644 index bd57ba1136bb5..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/llvm_scalar_opts.mli +++ /dev/null @@ -1,212 +0,0 @@ -(*===-- llvm_scalar_opts.mli - LLVM OCaml Interface -----------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Scalar Transforms. - - This interface provides an OCaml API for LLVM scalar transforms, the - classes in the [LLVMScalarOpts] library. *) - -(** See the [llvm::createAggressiveDCEPass] function. *) -external add_aggressive_dce - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_aggressive_dce" - -(** See the [llvm::createDCEPass] function. *) -external add_dce - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_dce" - -(** See the [llvm::createAlignmentFromAssumptionsPass] function. *) -external add_alignment_from_assumptions - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_alignment_from_assumptions" - -(** See the [llvm::createCFGSimplificationPass] function. *) -external add_cfg_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_cfg_simplification" - -(** See [llvm::createDeadStoreEliminationPass] function. *) -external add_dead_store_elimination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_dead_store_elimination" - -(** See [llvm::createScalarizerPass] function. *) -external add_scalarizer - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalarizer" - -(** See [llvm::createMergedLoadStoreMotionPass] function. *) -external add_merged_load_store_motion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_merged_load_store_motion" - -(** See the [llvm::createGVNPass] function. *) -external add_gvn - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_gvn" - -(** See the [llvm::createIndVarSimplifyPass] function. *) -external add_ind_var_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_ind_var_simplify" - -(** See the [llvm::createInstructionCombiningPass] function. *) -external add_instruction_combination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_instruction_combining" - -(** See the [llvm::createJumpThreadingPass] function. *) -external add_jump_threading - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_jump_threading" - -(** See the [llvm::createLICMPass] function. *) -external add_licm - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_licm" - -(** See the [llvm::createLoopDeletionPass] function. *) -external add_loop_deletion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_deletion" - -(** See the [llvm::createLoopIdiomPass] function. *) -external add_loop_idiom - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_idiom" - -(** See the [llvm::createLoopRotatePass] function. *) -external add_loop_rotation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_rotate" - -(** See the [llvm::createLoopRerollPass] function. *) -external add_loop_reroll - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_reroll" - -(** See the [llvm::createLoopUnrollPass] function. *) -external add_loop_unroll - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_unroll" - -(** See the [llvm::createLoopUnswitchPass] function. *) -external add_loop_unswitch - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_loop_unswitch" - -(** See the [llvm::createMemCpyOptPass] function. *) -external add_memcpy_opt - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_memcpy_opt" - -(** See the [llvm::createPartiallyInlineLibCallsPass] function. *) -external add_partially_inline_lib_calls - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_partially_inline_lib_calls" - -(** See the [llvm::createLowerAtomicPass] function. *) -external add_lower_atomic - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_atomic" - -(** See the [llvm::createLowerSwitchPass] function. *) -external add_lower_switch - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_switch" - -(** See the [llvm::createPromoteMemoryToRegisterPass] function. *) -external add_memory_to_register_promotion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_promote_memory_to_register" - -(** See the [llvm::createReassociatePass] function. *) -external add_reassociation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_reassociation" - -(** See the [llvm::createSCCPPass] function. *) -external add_sccp - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_sccp" - -(** See the [llvm::createSROAPass] function. *) -external add_scalar_repl_aggregation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates" - -(** See the [llvm::createSROAPass] function. *) -external add_scalar_repl_aggregation_ssa - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates_ssa" - -(** See the [llvm::createSROAPass] function. *) -external add_scalar_repl_aggregation_with_threshold - : int -> [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scalar_repl_aggregates_with_threshold" - -(** See the [llvm::createSimplifyLibCallsPass] function. *) -external add_lib_call_simplification - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_simplify_lib_calls" - -(** See the [llvm::createTailCallEliminationPass] function. *) -external add_tail_call_elimination - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_tail_call_elimination" - -(** See the [llvm::createDemoteMemoryToRegisterPass] function. *) -external add_memory_to_register_demotion - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_demote_memory_to_register" - -(** See the [llvm::createVerifierPass] function. *) -external add_verifier - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_verifier" - -(** See the [llvm::createCorrelatedValuePropagationPass] function. *) -external add_correlated_value_propagation - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_correlated_value_propagation" - -(** See the [llvm::createEarlyCSE] function. *) -external add_early_cse - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_early_cse" - -(** See the [llvm::createLowerExpectIntrinsicPass] function. *) -external add_lower_expect_intrinsic - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_expect_intrinsic" - -(** See the [llvm::createLowerConstantIntrinsicsPass] function. *) -external add_lower_constant_intrinsics - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_lower_constant_intrinsics" - -(** See the [llvm::createTypeBasedAliasAnalysisPass] function. *) -external add_type_based_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_type_based_alias_analysis" - -(** See the [llvm::createScopedNoAliasAAPass] function. *) -external add_scoped_no_alias_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_scoped_no_alias_aa" - -(** See the [llvm::createBasicAliasAnalysisPass] function. *) -external add_basic_alias_analysis - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_basic_alias_analysis" - -(** See the [llvm::createUnifyFunctionExitNodesPass] function. *) -external add_unify_function_exit_nodes - : [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit - = "llvm_add_unify_function_exit_nodes" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/scalar_opts_ocaml.c b/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/scalar_opts_ocaml.c deleted file mode 100644 index 113bd0d4c7c8a..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/scalar_opts/scalar_opts_ocaml.c +++ /dev/null @@ -1,261 +0,0 @@ -/*===-- scalar_opts_ocaml.c - LLVM OCaml Glue -------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Transforms/Scalar.h" -#include "llvm-c/Transforms/Utils.h" -#include "caml/mlvalues.h" -#include "caml/misc.h" - -/* [ unit */ -value llvm_add_aggressive_dce(LLVMPassManagerRef PM) { - LLVMAddAggressiveDCEPass(PM); - return Val_unit; -} - -value llvm_add_dce(LLVMPassManagerRef PM) { - LLVMAddDCEPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_alignment_from_assumptions(LLVMPassManagerRef PM) { - LLVMAddAlignmentFromAssumptionsPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_cfg_simplification(LLVMPassManagerRef PM) { - LLVMAddCFGSimplificationPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_dead_store_elimination(LLVMPassManagerRef PM) { - LLVMAddDeadStoreEliminationPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_scalarizer(LLVMPassManagerRef PM) { - LLVMAddScalarizerPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_merged_load_store_motion(LLVMPassManagerRef PM) { - LLVMAddMergedLoadStoreMotionPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_gvn(LLVMPassManagerRef PM) { - LLVMAddGVNPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_ind_var_simplify(LLVMPassManagerRef PM) { - LLVMAddIndVarSimplifyPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_instruction_combining(LLVMPassManagerRef PM) { - LLVMAddInstructionCombiningPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_jump_threading(LLVMPassManagerRef PM) { - LLVMAddJumpThreadingPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_licm(LLVMPassManagerRef PM) { - LLVMAddLICMPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_deletion(LLVMPassManagerRef PM) { - LLVMAddLoopDeletionPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_idiom(LLVMPassManagerRef PM) { - LLVMAddLoopIdiomPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_rotate(LLVMPassManagerRef PM) { - LLVMAddLoopRotatePass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_reroll(LLVMPassManagerRef PM) { - LLVMAddLoopRerollPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_unroll(LLVMPassManagerRef PM) { - LLVMAddLoopUnrollPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_loop_unswitch(LLVMPassManagerRef PM) { - LLVMAddLoopUnswitchPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_memcpy_opt(LLVMPassManagerRef PM) { - LLVMAddMemCpyOptPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_partially_inline_lib_calls(LLVMPassManagerRef PM) { - LLVMAddPartiallyInlineLibCallsPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_lower_atomic(LLVMPassManagerRef PM) { - LLVMAddLowerAtomicPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_lower_switch(LLVMPassManagerRef PM) { - LLVMAddLowerSwitchPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_promote_memory_to_register(LLVMPassManagerRef PM) { - LLVMAddPromoteMemoryToRegisterPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_reassociation(LLVMPassManagerRef PM) { - LLVMAddReassociatePass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_sccp(LLVMPassManagerRef PM) { - LLVMAddSCCPPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_scalar_repl_aggregates(LLVMPassManagerRef PM) { - LLVMAddScalarReplAggregatesPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_scalar_repl_aggregates_ssa(LLVMPassManagerRef PM) { - LLVMAddScalarReplAggregatesPassSSA(PM); - return Val_unit; -} - -/* int -> [ unit */ -value llvm_add_scalar_repl_aggregates_with_threshold(value threshold, - LLVMPassManagerRef PM) { - LLVMAddScalarReplAggregatesPassWithThreshold(PM, Int_val(threshold)); - return Val_unit; -} - -/* [ unit */ -value llvm_add_simplify_lib_calls(LLVMPassManagerRef PM) { - LLVMAddSimplifyLibCallsPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_tail_call_elimination(LLVMPassManagerRef PM) { - LLVMAddTailCallEliminationPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_demote_memory_to_register(LLVMPassManagerRef PM) { - LLVMAddDemoteMemoryToRegisterPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_verifier(LLVMPassManagerRef PM) { - LLVMAddVerifierPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_correlated_value_propagation(LLVMPassManagerRef PM) { - LLVMAddCorrelatedValuePropagationPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_early_cse(LLVMPassManagerRef PM) { - LLVMAddEarlyCSEPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_lower_expect_intrinsic(LLVMPassManagerRef PM) { - LLVMAddLowerExpectIntrinsicPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_lower_constant_intrinsics(LLVMPassManagerRef PM) { - LLVMAddLowerConstantIntrinsicsPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_type_based_alias_analysis(LLVMPassManagerRef PM) { - LLVMAddTypeBasedAliasAnalysisPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_scoped_no_alias_aa(LLVMPassManagerRef PM) { - LLVMAddScopedNoAliasAAPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_basic_alias_analysis(LLVMPassManagerRef PM) { - LLVMAddBasicAliasAnalysisPass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_unify_function_exit_nodes(LLVMPassManagerRef PM) { - LLVMAddUnifyFunctionExitNodesPass(PM); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/utils/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/utils/CMakeLists.txt deleted file mode 100644 index 920ed793bcedc..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/utils/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_transform_utils - OCAML llvm_transform_utils - OCAMLDEP llvm - C transform_utils_ocaml - LLVM TransformUtils) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.ml b/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.ml deleted file mode 100644 index 20a50b107b3f9..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.ml +++ /dev/null @@ -1,9 +0,0 @@ -(*===-- llvm_transform_utils.ml - LLVM OCaml Interface --------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external clone_module : Llvm.llmodule -> Llvm.llmodule = "llvm_clone_module" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.mli b/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.mli deleted file mode 100644 index 536f41dc43535..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/utils/llvm_transform_utils.mli +++ /dev/null @@ -1,16 +0,0 @@ -(*===-- llvm_transform_utils.mli - LLVM OCaml Interface -------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Transform Utilities. - - This interface provides an OCaml API for LLVM transform utilities, the - classes in the [LLVMTransformUtils] library. *) - -(** [clone_module m] returns an exact copy of module [m]. - See the [llvm::CloneModule] function. *) -external clone_module : Llvm.llmodule -> Llvm.llmodule = "llvm_clone_module" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/utils/transform_utils_ocaml.c b/interpreter/llvm/src/bindings/ocaml/transforms/utils/transform_utils_ocaml.c deleted file mode 100644 index 3e0f52e940caf..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/utils/transform_utils_ocaml.c +++ /dev/null @@ -1,29 +0,0 @@ -/*===-- transform_utils_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Core.h" -#include "caml/mlvalues.h" -#include "caml/misc.h" - -/* - * Do not move directly into external. This function is here to pull in - * -lLLVMTransformUtils, which would otherwise be not linked on static builds, - * as ld can't see the reference from OCaml code. - */ - -/* llmodule -> llmodule */ -LLVMModuleRef llvm_clone_module(LLVMModuleRef M) { return LLVMCloneModule(M); } diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/CMakeLists.txt b/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/CMakeLists.txt deleted file mode 100644 index 47af23928ccbb..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_ocaml_library(llvm_vectorize - OCAML llvm_vectorize - OCAMLDEP llvm - C vectorize_ocaml - LLVM Vectorize) diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.ml b/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.ml deleted file mode 100644 index a2e280e158489..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.ml +++ /dev/null @@ -1,14 +0,0 @@ -(*===-- llvm_vectorize.ml - LLVM OCaml Interface --------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -external add_loop_vectorize - : [ unit - = "llvm_add_loop_vectorize" -external add_slp_vectorize - : [ unit - = "llvm_add_slp_vectorize" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.mli b/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.mli deleted file mode 100644 index 7376d9e6d8146..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/llvm_vectorize.mli +++ /dev/null @@ -1,22 +0,0 @@ -(*===-- llvm_vectorize.mli - LLVM OCaml Interface -------------*- OCaml -*-===* - * - * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. - * See https://llvm.org/LICENSE.txt for license information. - * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - * - *===----------------------------------------------------------------------===*) - -(** Vectorize Transforms. - - This interface provides an OCaml API for LLVM vectorize transforms, the - classes in the [LLVMVectorize] library. *) - -(** See the [llvm::createLoopVectorizePass] function. *) -external add_loop_vectorize - : [ unit - = "llvm_add_loop_vectorize" - -(** See the [llvm::createSLPVectorizerPass] function. *) -external add_slp_vectorize - : [ unit - = "llvm_add_slp_vectorize" diff --git a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/vectorize_ocaml.c b/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/vectorize_ocaml.c deleted file mode 100644 index d9b15bf4588ed..0000000000000 --- a/interpreter/llvm/src/bindings/ocaml/transforms/vectorize/vectorize_ocaml.c +++ /dev/null @@ -1,32 +0,0 @@ -/*===-- vectorize_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\ -|* *| -|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| -|* Exceptions. *| -|* See https://llvm.org/LICENSE.txt for license information. *| -|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file glues LLVM's OCaml interface to its C interface. These functions *| -|* are by and large transparent wrappers to the corresponding C functions. *| -|* *| -|* Note that these functions intentionally take liberties with the CAMLparamX *| -|* macros, since most of the parameters are not GC heap objects. *| -|* *| -\*===----------------------------------------------------------------------===*/ - -#include "llvm-c/Transforms/Vectorize.h" -#include "caml/mlvalues.h" -#include "caml/misc.h" - -/* [ unit */ -value llvm_add_loop_vectorize(LLVMPassManagerRef PM) { - LLVMAddLoopVectorizePass(PM); - return Val_unit; -} - -/* [ unit */ -value llvm_add_slp_vectorize(LLVMPassManagerRef PM) { - LLVMAddSLPVectorizePass(PM); - return Val_unit; -} diff --git a/interpreter/llvm/src/bindings/python/README.txt b/interpreter/llvm/src/bindings/python/README.txt deleted file mode 100644 index 96e334319bde3..0000000000000 --- a/interpreter/llvm/src/bindings/python/README.txt +++ /dev/null @@ -1,67 +0,0 @@ -This directory contains Python bindings for LLVM's C library. - -The bindings are currently a work in progress and are far from complete. -Use at your own risk. - -Developer Info -============== - -The single Python package is "llvm." Modules inside this package roughly -follow the names of the modules/headers defined by LLVM's C API. - -Testing -------- - -All test code is location in llvm/tests. Tests are written as classes -which inherit from llvm.tests.base.TestBase, which is a convenience base -class that provides common functionality. - -Tests can be executed by installing nose: - - pip install nosetests - -Then by running nosetests: - - nosetests - -To see more output: - - nosetests -v - -To step into the Python debugger while running a test, add the following -to your test at the point you wish to enter the debugger: - - import pdb; pdb.set_trace() - -Then run nosetests: - - nosetests -s -v - -You should strive for high code coverage. To see current coverage: - - pip install coverage - nosetests --with-coverage --cover-html - -Then open cover/index.html in your browser of choice to see the code coverage. - -Style Convention ----------------- - -All code should pass PyFlakes. First, install PyFlakes: - - pip install pyflakes - -Then at any time run it to see a report: - - pyflakes . - -Eventually we'll provide a Pylint config file. In the meantime, install -Pylint: - - pip install pylint - -And run: - - pylint llvm - -And try to keep the number of violations to a minimum. diff --git a/interpreter/llvm/src/bindings/python/llvm/bit_reader.py b/interpreter/llvm/src/bindings/python/llvm/bit_reader.py deleted file mode 100644 index 33b8211076b80..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/bit_reader.py +++ /dev/null @@ -1,30 +0,0 @@ - -from .common import LLVMObject -from .common import c_object_p -from .common import get_library -from . import enumerations -from .core import MemoryBuffer -from .core import Module -from .core import OpCode -from ctypes import POINTER -from ctypes import byref -from ctypes import c_char_p -from ctypes import cast -__all__ = ['parse_bitcode'] -lib = get_library() - -def parse_bitcode(mem_buffer): - """Input is .core.MemoryBuffer""" - module = c_object_p() - result = lib.LLVMParseBitcode2(mem_buffer, byref(module)) - if result: - raise RuntimeError('LLVM Error') - m = Module(module) - m.take_ownership(mem_buffer) - return m - -def register_library(library): - library.LLVMParseBitcode2.argtypes = [MemoryBuffer, POINTER(c_object_p)] - library.LLVMParseBitcode2.restype = bool - -register_library(lib) diff --git a/interpreter/llvm/src/bindings/python/llvm/common.py b/interpreter/llvm/src/bindings/python/llvm/common.py deleted file mode 100644 index 9c6c6d433458c..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/common.py +++ /dev/null @@ -1,125 +0,0 @@ -#===- common.py - Python LLVM Bindings -----------------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -from ctypes import POINTER -from ctypes import c_void_p -from ctypes import cdll - -import ctypes.util -import platform - -# LLVM_VERSION: sync with PACKAGE_VERSION in CMakeLists.txt -# but leave out the 'svn' suffix. -LLVM_VERSION = '10.0.0' - -__all__ = [ - 'c_object_p', - 'get_library', -] - -c_object_p = POINTER(c_void_p) - -class LLVMObject(object): - """Base class for objects that are backed by an LLVM data structure. - - This class should never be instantiated outside of this package. - """ - def __init__(self, ptr, ownable=True, disposer=None): - assert isinstance(ptr, c_object_p) - - self._ptr = self._as_parameter_ = ptr - - self._self_owned = True - self._ownable = ownable - self._disposer = disposer - - self._owned_objects = [] - - def take_ownership(self, obj): - """Take ownership of another object. - - When you take ownership of another object, you are responsible for - destroying that object. In addition, a reference to that object is - placed inside this object so the Python garbage collector will not - collect the object while it is still alive in libLLVM. - - This method should likely only be called from within modules inside - this package. - """ - assert isinstance(obj, LLVMObject) - - self._owned_objects.append(obj) - obj._self_owned = False - - def from_param(self): - """ctypes function that converts this object to a function parameter.""" - return self._as_parameter_ - - def __del__(self): - if not hasattr(self, '_self_owned') or not hasattr(self, '_disposer'): - return - - if self._self_owned and self._disposer: - self._disposer(self) - -class CachedProperty(object): - """Decorator that caches the result of a property lookup. - - This is a useful replacement for @property. It is recommended to use this - decorator on properties that invoke C API calls for which the result of the - call will be idempotent. - """ - def __init__(self, wrapped): - self.wrapped = wrapped - try: - self.__doc__ = wrapped.__doc__ - except: # pragma: no cover - pass - - def __get__(self, instance, instance_type=None): - if instance is None: - return self - - value = self.wrapped(instance) - setattr(instance, self.wrapped.__name__, value) - - return value - -def get_library(): - """Obtain a reference to the llvm library.""" - - # On Linux, ctypes.cdll.LoadLibrary() respects LD_LIBRARY_PATH - # while ctypes.util.find_library() doesn't. - # See http://docs.python.org/2/library/ctypes.html#finding-shared-libraries - # - # To make it possible to run the unit tests without installing the LLVM shared - # library into a default linker search path. Always Try ctypes.cdll.LoadLibrary() - # with all possible library names first, then try ctypes.util.find_library(). - - names = ['LLVM-' + LLVM_VERSION, 'LLVM-' + LLVM_VERSION + 'svn'] - t = platform.system() - if t == 'Darwin': - pfx, ext = 'lib', '.dylib' - elif t == 'Windows': - pfx, ext = '', '.dll' - else: - pfx, ext = 'lib', '.so' - - for i in names: - try: - lib = cdll.LoadLibrary(pfx + i + ext) - except OSError: - pass - else: - return lib - - for i in names: - t = ctypes.util.find_library(i) - if t: - return cdll.LoadLibrary(t) - raise Exception('LLVM shared library not found!') diff --git a/interpreter/llvm/src/bindings/python/llvm/core.py b/interpreter/llvm/src/bindings/python/llvm/core.py deleted file mode 100644 index 4d90f8652de13..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/core.py +++ /dev/null @@ -1,640 +0,0 @@ -#===- core.py - Python LLVM Bindings -------------------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# -from __future__ import print_function - -from .common import LLVMObject -from .common import c_object_p -from .common import get_library - -from . import enumerations - -from ctypes import POINTER -from ctypes import byref -from ctypes import c_char_p -from ctypes import c_uint - -import sys - -__all__ = [ - "lib", - "Enums", - "OpCode", - "MemoryBuffer", - "Module", - "Value", - "Function", - "BasicBlock", - "Instruction", - "Context", - "PassRegistry" -] - -lib = get_library() -Enums = [] - -class LLVMEnumeration(object): - """Represents an individual LLVM enumeration.""" - - def __init__(self, name, value): - self.name = name - self.value = value - - def __repr__(self): - return '%s.%s' % (self.__class__.__name__, - self.name) - - @classmethod - def from_value(cls, value): - """Obtain an enumeration instance from a numeric value.""" - result = cls._value_map.get(value, None) - - if result is None: - raise ValueError('Unknown %s: %d' % (cls.__name__, - value)) - - return result - - @classmethod - def register(cls, name, value): - """Registers a new enumeration. - - This is called by this module for each enumeration defined in - enumerations. You should not need to call this outside this module. - """ - if value in cls._value_map: - raise ValueError('%s value already registered: %d' % (cls.__name__, - value)) - enum = cls(name, value) - cls._value_map[value] = enum - setattr(cls, name, enum) - -class Attribute(LLVMEnumeration): - """Represents an individual Attribute enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(Attribute, self).__init__(name, value) - -class OpCode(LLVMEnumeration): - """Represents an individual OpCode enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(OpCode, self).__init__(name, value) - -class TypeKind(LLVMEnumeration): - """Represents an individual TypeKind enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(TypeKind, self).__init__(name, value) - -class Linkage(LLVMEnumeration): - """Represents an individual Linkage enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(Linkage, self).__init__(name, value) - -class Visibility(LLVMEnumeration): - """Represents an individual visibility enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(Visibility, self).__init__(name, value) - -class CallConv(LLVMEnumeration): - """Represents an individual calling convention enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(CallConv, self).__init__(name, value) - -class IntPredicate(LLVMEnumeration): - """Represents an individual IntPredicate enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(IntPredicate, self).__init__(name, value) - -class RealPredicate(LLVMEnumeration): - """Represents an individual RealPredicate enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(RealPredicate, self).__init__(name, value) - -class LandingPadClauseTy(LLVMEnumeration): - """Represents an individual LandingPadClauseTy enumeration.""" - - _value_map = {} - - def __init__(self, name, value): - super(LandingPadClauseTy, self).__init__(name, value) - -class MemoryBuffer(LLVMObject): - """Represents an opaque memory buffer.""" - - def __init__(self, filename=None): - """Create a new memory buffer. - - Currently, we support creating from the contents of a file at the - specified filename. - """ - if filename is None: - raise Exception("filename argument must be defined") - - memory = c_object_p() - out = c_char_p(None) - - result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename, - byref(memory), byref(out)) - - if result: - raise Exception("Could not create memory buffer: %s" % out.value) - - LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer) - - def __len__(self): - return lib.LLVMGetBufferSize(self) - -class Value(LLVMObject): - - def __init__(self, value): - LLVMObject.__init__(self, value) - - @property - def name(self): - return lib.LLVMGetValueName(self) - - def dump(self): - lib.LLVMDumpValue(self) - - def get_operand(self, i): - return Value(lib.LLVMGetOperand(self, i)) - - def set_operand(self, i, v): - return lib.LLVMSetOperand(self, i, v) - - def __len__(self): - return lib.LLVMGetNumOperands(self) - -class Module(LLVMObject): - """Represents the top-level structure of an llvm program in an opaque object.""" - - def __init__(self, module, name=None, context=None): - LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule) - - @classmethod - def CreateWithName(cls, module_id): - m = Module(lib.LLVMModuleCreateWithName(module_id)) - Context.GetGlobalContext().take_ownership(m) - return m - - @property - def datalayout(self): - return lib.LLVMGetDataLayout(self) - - @datalayout.setter - def datalayout(self, new_data_layout): - """new_data_layout is a string.""" - lib.LLVMSetDataLayout(self, new_data_layout) - - @property - def target(self): - return lib.LLVMGetTarget(self) - - @target.setter - def target(self, new_target): - """new_target is a string.""" - lib.LLVMSetTarget(self, new_target) - - def dump(self): - lib.LLVMDumpModule(self) - - class __function_iterator(object): - def __init__(self, module, reverse=False): - self.module = module - self.reverse = reverse - if self.reverse: - self.function = self.module.last - else: - self.function = self.module.first - - def __iter__(self): - return self - - def __next__(self): - if not isinstance(self.function, Function): - raise StopIteration("") - result = self.function - if self.reverse: - self.function = self.function.prev - else: - self.function = self.function.next - return result - - if sys.version_info.major == 2: - next = __next__ - - def __iter__(self): - return Module.__function_iterator(self) - - def __reversed__(self): - return Module.__function_iterator(self, reverse=True) - - @property - def first(self): - return Function(lib.LLVMGetFirstFunction(self)) - - @property - def last(self): - return Function(lib.LLVMGetLastFunction(self)) - - def print_module_to_file(self, filename): - out = c_char_p(None) - # Result is inverted so 0 means everything was ok. - result = lib.LLVMPrintModuleToFile(self, filename, byref(out)) - if result: - raise RuntimeError("LLVM Error: %s" % out.value) - -class Function(Value): - - def __init__(self, value): - Value.__init__(self, value) - - @property - def next(self): - f = lib.LLVMGetNextFunction(self) - return f and Function(f) - - @property - def prev(self): - f = lib.LLVMGetPreviousFunction(self) - return f and Function(f) - - @property - def first(self): - b = lib.LLVMGetFirstBasicBlock(self) - return b and BasicBlock(b) - - @property - def last(self): - b = lib.LLVMGetLastBasicBlock(self) - return b and BasicBlock(b) - - class __bb_iterator(object): - def __init__(self, function, reverse=False): - self.function = function - self.reverse = reverse - if self.reverse: - self.bb = function.last - else: - self.bb = function.first - - def __iter__(self): - return self - - def __next__(self): - if not isinstance(self.bb, BasicBlock): - raise StopIteration("") - result = self.bb - if self.reverse: - self.bb = self.bb.prev - else: - self.bb = self.bb.next - return result - - if sys.version_info.major == 2: - next = __next__ - - def __iter__(self): - return Function.__bb_iterator(self) - - def __reversed__(self): - return Function.__bb_iterator(self, reverse=True) - - def __len__(self): - return lib.LLVMCountBasicBlocks(self) - -class BasicBlock(LLVMObject): - - def __init__(self, value): - LLVMObject.__init__(self, value) - - @property - def next(self): - b = lib.LLVMGetNextBasicBlock(self) - return b and BasicBlock(b) - - @property - def prev(self): - b = lib.LLVMGetPreviousBasicBlock(self) - return b and BasicBlock(b) - - @property - def first(self): - i = lib.LLVMGetFirstInstruction(self) - return i and Instruction(i) - - @property - def last(self): - i = lib.LLVMGetLastInstruction(self) - return i and Instruction(i) - - def __as_value(self): - return Value(lib.LLVMBasicBlockAsValue(self)) - - @property - def name(self): - return lib.LLVMGetValueName(self.__as_value()) - - def dump(self): - lib.LLVMDumpValue(self.__as_value()) - - def get_operand(self, i): - return Value(lib.LLVMGetOperand(self.__as_value(), - i)) - - def set_operand(self, i, v): - return lib.LLVMSetOperand(self.__as_value(), - i, v) - - def __len__(self): - return lib.LLVMGetNumOperands(self.__as_value()) - - class __inst_iterator(object): - def __init__(self, bb, reverse=False): - self.bb = bb - self.reverse = reverse - if self.reverse: - self.inst = self.bb.last - else: - self.inst = self.bb.first - - def __iter__(self): - return self - - def __next__(self): - if not isinstance(self.inst, Instruction): - raise StopIteration("") - result = self.inst - if self.reverse: - self.inst = self.inst.prev - else: - self.inst = self.inst.next - return result - - if sys.version_info.major == 2: - next = __next__ - - def __iter__(self): - return BasicBlock.__inst_iterator(self) - - def __reversed__(self): - return BasicBlock.__inst_iterator(self, reverse=True) - - -class Instruction(Value): - - def __init__(self, value): - Value.__init__(self, value) - - @property - def next(self): - i = lib.LLVMGetNextInstruction(self) - return i and Instruction(i) - - @property - def prev(self): - i = lib.LLVMGetPreviousInstruction(self) - return i and Instruction(i) - - @property - def opcode(self): - return OpCode.from_value(lib.LLVMGetInstructionOpcode(self)) - -class Context(LLVMObject): - - def __init__(self, context=None): - if context is None: - context = lib.LLVMContextCreate() - LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose) - else: - LLVMObject.__init__(self, context) - - @classmethod - def GetGlobalContext(cls): - return Context(lib.LLVMGetGlobalContext()) - -class PassRegistry(LLVMObject): - """Represents an opaque pass registry object.""" - - def __init__(self): - LLVMObject.__init__(self, - lib.LLVMGetGlobalPassRegistry()) - -def register_library(library): - # Initialization/Shutdown declarations. - library.LLVMInitializeCore.argtypes = [PassRegistry] - library.LLVMInitializeCore.restype = None - - library.LLVMInitializeTransformUtils.argtypes = [PassRegistry] - library.LLVMInitializeTransformUtils.restype = None - - library.LLVMInitializeScalarOpts.argtypes = [PassRegistry] - library.LLVMInitializeScalarOpts.restype = None - - library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry] - library.LLVMInitializeObjCARCOpts.restype = None - - library.LLVMInitializeVectorization.argtypes = [PassRegistry] - library.LLVMInitializeVectorization.restype = None - - library.LLVMInitializeInstCombine.argtypes = [PassRegistry] - library.LLVMInitializeInstCombine.restype = None - - library.LLVMInitializeAggressiveInstCombiner.argtypes = [PassRegistry] - library.LLVMInitializeAggressiveInstCombiner.restype = None - - library.LLVMInitializeIPO.argtypes = [PassRegistry] - library.LLVMInitializeIPO.restype = None - - library.LLVMInitializeInstrumentation.argtypes = [PassRegistry] - library.LLVMInitializeInstrumentation.restype = None - - library.LLVMInitializeAnalysis.argtypes = [PassRegistry] - library.LLVMInitializeAnalysis.restype = None - - library.LLVMInitializeCodeGen.argtypes = [PassRegistry] - library.LLVMInitializeCodeGen.restype = None - - library.LLVMInitializeTarget.argtypes = [PassRegistry] - library.LLVMInitializeTarget.restype = None - - library.LLVMShutdown.argtypes = [] - library.LLVMShutdown.restype = None - - # Pass Registry declarations. - library.LLVMGetGlobalPassRegistry.argtypes = [] - library.LLVMGetGlobalPassRegistry.restype = c_object_p - - # Context declarations. - library.LLVMContextCreate.argtypes = [] - library.LLVMContextCreate.restype = c_object_p - - library.LLVMContextDispose.argtypes = [Context] - library.LLVMContextDispose.restype = None - - library.LLVMGetGlobalContext.argtypes = [] - library.LLVMGetGlobalContext.restype = c_object_p - - # Memory buffer declarations - library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p, - POINTER(c_object_p), POINTER(c_char_p)] - library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool - - library.LLVMGetBufferSize.argtypes = [MemoryBuffer] - - library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer] - - # Module declarations - library.LLVMModuleCreateWithName.argtypes = [c_char_p] - library.LLVMModuleCreateWithName.restype = c_object_p - - library.LLVMDisposeModule.argtypes = [Module] - library.LLVMDisposeModule.restype = None - - library.LLVMGetDataLayout.argtypes = [Module] - library.LLVMGetDataLayout.restype = c_char_p - - library.LLVMSetDataLayout.argtypes = [Module, c_char_p] - library.LLVMSetDataLayout.restype = None - - library.LLVMGetTarget.argtypes = [Module] - library.LLVMGetTarget.restype = c_char_p - - library.LLVMSetTarget.argtypes = [Module, c_char_p] - library.LLVMSetTarget.restype = None - - library.LLVMDumpModule.argtypes = [Module] - library.LLVMDumpModule.restype = None - - library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p, - POINTER(c_char_p)] - library.LLVMPrintModuleToFile.restype = bool - - library.LLVMGetFirstFunction.argtypes = [Module] - library.LLVMGetFirstFunction.restype = c_object_p - - library.LLVMGetLastFunction.argtypes = [Module] - library.LLVMGetLastFunction.restype = c_object_p - - library.LLVMGetNextFunction.argtypes = [Function] - library.LLVMGetNextFunction.restype = c_object_p - - library.LLVMGetPreviousFunction.argtypes = [Function] - library.LLVMGetPreviousFunction.restype = c_object_p - - # Value declarations. - library.LLVMGetValueName.argtypes = [Value] - library.LLVMGetValueName.restype = c_char_p - - library.LLVMDumpValue.argtypes = [Value] - library.LLVMDumpValue.restype = None - - library.LLVMGetOperand.argtypes = [Value, c_uint] - library.LLVMGetOperand.restype = c_object_p - - library.LLVMSetOperand.argtypes = [Value, Value, c_uint] - library.LLVMSetOperand.restype = None - - library.LLVMGetNumOperands.argtypes = [Value] - library.LLVMGetNumOperands.restype = c_uint - - # Basic Block Declarations. - library.LLVMGetFirstBasicBlock.argtypes = [Function] - library.LLVMGetFirstBasicBlock.restype = c_object_p - - library.LLVMGetLastBasicBlock.argtypes = [Function] - library.LLVMGetLastBasicBlock.restype = c_object_p - - library.LLVMGetNextBasicBlock.argtypes = [BasicBlock] - library.LLVMGetNextBasicBlock.restype = c_object_p - - library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock] - library.LLVMGetPreviousBasicBlock.restype = c_object_p - - library.LLVMGetFirstInstruction.argtypes = [BasicBlock] - library.LLVMGetFirstInstruction.restype = c_object_p - - library.LLVMGetLastInstruction.argtypes = [BasicBlock] - library.LLVMGetLastInstruction.restype = c_object_p - - library.LLVMBasicBlockAsValue.argtypes = [BasicBlock] - library.LLVMBasicBlockAsValue.restype = c_object_p - - library.LLVMCountBasicBlocks.argtypes = [Function] - library.LLVMCountBasicBlocks.restype = c_uint - - # Instruction Declarations. - library.LLVMGetNextInstruction.argtypes = [Instruction] - library.LLVMGetNextInstruction.restype = c_object_p - - library.LLVMGetPreviousInstruction.argtypes = [Instruction] - library.LLVMGetPreviousInstruction.restype = c_object_p - - library.LLVMGetInstructionOpcode.argtypes = [Instruction] - library.LLVMGetInstructionOpcode.restype = c_uint - -def register_enumerations(): - if Enums: - return None - enums = [ - (Attribute, enumerations.Attributes), - (OpCode, enumerations.OpCodes), - (TypeKind, enumerations.TypeKinds), - (Linkage, enumerations.Linkages), - (Visibility, enumerations.Visibility), - (CallConv, enumerations.CallConv), - (IntPredicate, enumerations.IntPredicate), - (RealPredicate, enumerations.RealPredicate), - (LandingPadClauseTy, enumerations.LandingPadClauseTy), - ] - for enum_class, enum_spec in enums: - for name, value in enum_spec: - print(name, value) - enum_class.register(name, value) - return enums - -def initialize_llvm(): - Context.GetGlobalContext() - p = PassRegistry() - lib.LLVMInitializeCore(p) - lib.LLVMInitializeTransformUtils(p) - lib.LLVMInitializeScalarOpts(p) - lib.LLVMInitializeObjCARCOpts(p) - lib.LLVMInitializeVectorization(p) - lib.LLVMInitializeInstCombine(p) - lib.LLVMInitializeIPO(p) - lib.LLVMInitializeInstrumentation(p) - lib.LLVMInitializeAnalysis(p) - lib.LLVMInitializeCodeGen(p) - lib.LLVMInitializeTarget(p) - -register_library(lib) -Enums = register_enumerations() -initialize_llvm() diff --git a/interpreter/llvm/src/bindings/python/llvm/disassembler.py b/interpreter/llvm/src/bindings/python/llvm/disassembler.py deleted file mode 100644 index 75625588911ca..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/disassembler.py +++ /dev/null @@ -1,169 +0,0 @@ -#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -from ctypes import CFUNCTYPE -from ctypes import POINTER -from ctypes import addressof -from ctypes import c_byte -from ctypes import c_char_p -from ctypes import c_int -from ctypes import c_size_t -from ctypes import c_ubyte -from ctypes import c_uint64 -from ctypes import c_void_p -from ctypes import cast - -from .common import LLVMObject -from .common import c_object_p -from .common import get_library - -__all__ = [ - 'Disassembler', -] - -lib = get_library() -callbacks = {} - -# Constants for set_options -Option_UseMarkup = 1 - - - -_initialized = False -_targets = ['AArch64', 'ARM', 'Hexagon', 'MSP430', 'Mips', 'NVPTX', 'PowerPC', 'R600', 'Sparc', 'SystemZ', 'X86', 'XCore'] -def _ensure_initialized(): - global _initialized - if not _initialized: - # Here one would want to call the functions - # LLVMInitializeAll{TargetInfo,TargetMC,Disassembler}s, but - # unfortunately they are only defined as static inline - # functions in the header files of llvm-c, so they don't exist - # as symbols in the shared library. - # So until that is fixed use this hack to initialize them all - for tgt in _targets: - for initializer in ("TargetInfo", "TargetMC", "Disassembler"): - try: - f = getattr(lib, "LLVMInitialize" + tgt + initializer) - except AttributeError: - continue - f() - _initialized = True - - -class Disassembler(LLVMObject): - """Represents a disassembler instance. - - Disassembler instances are tied to specific "triple," which must be defined - at creation time. - - Disassembler instances can disassemble instructions from multiple sources. - """ - def __init__(self, triple): - """Create a new disassembler instance. - - The triple argument is the triple to create the disassembler for. This - is something like 'i386-apple-darwin9'. - """ - - _ensure_initialized() - - ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0), - callbacks['op_info'](0), callbacks['symbol_lookup'](0)) - if not ptr: - raise Exception('Could not obtain disassembler for triple: %s' % - triple) - - LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisasmDispose) - - def get_instruction(self, source, pc=0): - """Obtain the next instruction from an input source. - - The input source should be a str or bytearray or something that - represents a sequence of bytes. - - This function will start reading bytes from the beginning of the - source. - - The pc argument specifies the address that the first byte is at. - - This returns a 2-tuple of: - - long number of bytes read. 0 if no instruction was read. - str representation of instruction. This will be the assembly that - represents the instruction. - """ - buf = cast(c_char_p(source), POINTER(c_ubyte)) - out_str = cast((c_byte * 255)(), c_char_p) - - result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)), - c_uint64(pc), out_str, 255) - - return (result, out_str.value) - - def get_instructions(self, source, pc=0): - """Obtain multiple instructions from an input source. - - This is like get_instruction() except it is a generator for all - instructions within the source. It starts at the beginning of the - source and reads instructions until no more can be read. - - This generator returns 3-tuple of: - - long address of instruction. - long size of instruction, in bytes. - str representation of instruction. - """ - source_bytes = c_char_p(source) - out_str = cast((c_byte * 255)(), c_char_p) - - # This could probably be written cleaner. But, it does work. - buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents - offset = 0 - address = pc - end_address = pc + len(source) - while address < end_address: - b = cast(addressof(buf) + offset, POINTER(c_ubyte)) - result = lib.LLVMDisasmInstruction(self, b, - c_uint64(len(source) - offset), c_uint64(address), - out_str, 255) - - if result == 0: - break - - yield (address, result, out_str.value) - - address += result - offset += result - - def set_options(self, options): - if not lib.LLVMSetDisasmOptions(self, options): - raise Exception('Unable to set all disassembler options in %i' % options) - - -def register_library(library): - library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int, - callbacks['op_info'], callbacks['symbol_lookup']] - library.LLVMCreateDisasm.restype = c_object_p - - library.LLVMDisasmDispose.argtypes = [Disassembler] - - library.LLVMDisasmInstruction.argtypes = [Disassembler, POINTER(c_ubyte), - c_uint64, c_uint64, c_char_p, c_size_t] - library.LLVMDisasmInstruction.restype = c_size_t - - library.LLVMSetDisasmOptions.argtypes = [Disassembler, c_uint64] - library.LLVMSetDisasmOptions.restype = c_int - - -callbacks['op_info'] = CFUNCTYPE(c_int, c_void_p, c_uint64, c_uint64, c_uint64, - c_int, c_void_p) -callbacks['symbol_lookup'] = CFUNCTYPE(c_char_p, c_void_p, c_uint64, - POINTER(c_uint64), c_uint64, - POINTER(c_char_p)) - -register_library(lib) diff --git a/interpreter/llvm/src/bindings/python/llvm/enumerations.py b/interpreter/llvm/src/bindings/python/llvm/enumerations.py deleted file mode 100644 index ebb39a4ded831..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/enumerations.py +++ /dev/null @@ -1,210 +0,0 @@ -#===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -r""" -LLVM Enumerations -================= - -This file defines enumerations from LLVM. - -Each enumeration is exposed as a list of 2-tuples. These lists are consumed by -dedicated types elsewhere in the package. The enumerations are centrally -defined in this file so they are easier to locate and maintain. -""" - -__all__ = [ - 'Attributes', - 'OpCodes', - 'TypeKinds', - 'Linkages', - 'Visibility', - 'CallConv', - 'IntPredicate', - 'RealPredicate', - 'LandingPadClauseTy', -] - -Attributes = [ - ('ZExt', 1 << 0), - ('MSExt', 1 << 1), - ('NoReturn', 1 << 2), - ('InReg', 1 << 3), - ('StructRet', 1 << 4), - ('NoUnwind', 1 << 5), - ('NoAlias', 1 << 6), - ('ByVal', 1 << 7), - ('Nest', 1 << 8), - ('ReadNone', 1 << 9), - ('ReadOnly', 1 << 10), - ('NoInline', 1 << 11), - ('AlwaysInline', 1 << 12), - ('OptimizeForSize', 1 << 13), - ('StackProtect', 1 << 14), - ('StackProtectReq', 1 << 15), - ('Alignment', 31 << 16), - ('NoCapture', 1 << 21), - ('NoRedZone', 1 << 22), - ('ImplicitFloat', 1 << 23), - ('Naked', 1 << 24), - ('InlineHint', 1 << 25), - ('StackAlignment', 7 << 26), - ('ReturnsTwice', 1 << 29), - ('UWTable', 1 << 30), - ('NonLazyBind', 1 << 31), -] - -OpCodes = [ - ('Ret', 1), - ('Br', 2), - ('Switch', 3), - ('IndirectBr', 4), - ('Invoke', 5), - ('Unreachable', 7), - ('Add', 8), - ('FAdd', 9), - ('Sub', 10), - ('FSub', 11), - ('Mul', 12), - ('FMul', 13), - ('UDiv', 14), - ('SDiv', 15), - ('FDiv', 16), - ('URem', 17), - ('SRem', 18), - ('FRem', 19), - ('Shl', 20), - ('LShr', 21), - ('AShr', 22), - ('And', 23), - ('Or', 24), - ('Xor', 25), - ('Alloca', 26), - ('Load', 27), - ('Store', 28), - ('GetElementPtr', 29), - ('Trunc', 30), - ('ZExt', 31), - ('SExt', 32), - ('FPToUI', 33), - ('FPToSI', 34), - ('UIToFP', 35), - ('SIToFP', 36), - ('FPTrunc', 37), - ('FPExt', 38), - ('PtrToInt', 39), - ('IntToPtr', 40), - ('BitCast', 41), - ('ICmp', 42), - ('FCmpl', 43), - ('PHI', 44), - ('Call', 45), - ('Select', 46), - ('UserOp1', 47), - ('UserOp2', 48), - ('AArg', 49), - ('ExtractElement', 50), - ('InsertElement', 51), - ('ShuffleVector', 52), - ('ExtractValue', 53), - ('InsertValue', 54), - ('Fence', 55), - ('AtomicCmpXchg', 56), - ('AtomicRMW', 57), - ('Resume', 58), - ('LandingPad', 59), -] - -TypeKinds = [ - ('Void', 0), - ('Half', 1), - ('Float', 2), - ('Double', 3), - ('X86_FP80', 4), - ('FP128', 5), - ('PPC_FP128', 6), - ('Label', 7), - ('Integer', 8), - ('Function', 9), - ('Struct', 10), - ('Array', 11), - ('Pointer', 12), - ('Vector', 13), - ('Metadata', 14), - ('X86_MMX', 15), -] - -Linkages = [ - ('External', 0), - ('AvailableExternally', 1), - ('LinkOnceAny', 2), - ('LinkOnceODR', 3), - ('WeakAny', 4), - ('WeakODR', 5), - ('Appending', 6), - ('Internal', 7), - ('Private', 8), - ('DLLImport', 9), - ('DLLExport', 10), - ('ExternalWeak', 11), - ('Ghost', 12), - ('Common', 13), - ('LinkerPrivate', 14), - ('LinkerPrivateWeak', 15), - ('LinkerPrivateWeakDefAuto', 16), -] - -Visibility = [ - ('Default', 0), - ('Hidden', 1), - ('Protected', 2), -] - -CallConv = [ - ('CCall', 0), - ('FastCall', 8), - ('ColdCall', 9), - ('X86StdcallCall', 64), - ('X86FastcallCall', 65), -] - -IntPredicate = [ - ('EQ', 32), - ('NE', 33), - ('UGT', 34), - ('UGE', 35), - ('ULT', 36), - ('ULE', 37), - ('SGT', 38), - ('SGE', 39), - ('SLT', 40), - ('SLE', 41), -] - -RealPredicate = [ - ('PredicateFalse', 0), - ('OEQ', 1), - ('OGT', 2), - ('OGE', 3), - ('OLT', 4), - ('OLE', 5), - ('ONE', 6), - ('ORD', 7), - ('UNO', 8), - ('UEQ', 9), - ('UGT', 10), - ('UGE', 11), - ('ULT', 12), - ('ULE', 13), - ('UNE', 14), - ('PredicateTrue', 15), -] - -LandingPadClauseTy = [ - ('Catch', 0), - ('Filter', 1), -] diff --git a/interpreter/llvm/src/bindings/python/llvm/object.py b/interpreter/llvm/src/bindings/python/llvm/object.py deleted file mode 100644 index e8841b6045f62..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/object.py +++ /dev/null @@ -1,508 +0,0 @@ -#===- object.py - Python Object Bindings --------------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -r""" -Object File Interface -===================== - -This module provides an interface for reading information from object files -(e.g. binary executables and libraries). - -Using this module, you can obtain information about an object file's sections, -symbols, and relocations. These are represented by the classes ObjectFile, -Section, Symbol, and Relocation, respectively. - -Usage ------ - -The only way to use this module is to start by creating an ObjectFile. You can -create an ObjectFile by loading a file (specified by its path) or by creating a -llvm.core.MemoryBuffer and loading that. - -Once you have an object file, you can inspect its sections and symbols directly -by calling get_sections() and get_symbols() respectively. To inspect -relocations, call get_relocations() on a Section instance. - -Iterator Interface ------------------- - -The LLVM bindings expose iteration over sections, symbols, and relocations in a -way that only allows one instance to be operated on at a single time. This is -slightly annoying from a Python perspective, as it isn't very Pythonic to have -objects that "expire" but are still active from a dynamic language. - -To aid working around this limitation, each Section, Symbol, and Relocation -instance caches its properties after first access. So, if the underlying -iterator is advanced, the properties can still be obtained provided they have -already been retrieved. - -In addition, we also provide a "cache" method on each class to cache all -available data. You can call this on each obtained instance. Or, you can pass -cache=True to the appropriate get_XXX() method to have this done for you. - -Here are some examples on how to perform iteration: - - obj = ObjectFile(filename='/bin/ls') - - # This is OK. Each Section is only accessed inside its own iteration slot. - section_names = [] - for section in obj.get_sections(): - section_names.append(section.name) - - # This is NOT OK. You perform a lookup after the object has expired. - symbols = list(obj.get_symbols()) - for symbol in symbols: - print symbol.name # This raises because the object has expired. - - # In this example, we mix a working and failing scenario. - symbols = [] - for symbol in obj.get_symbols(): - symbols.append(symbol) - print symbol.name - - for symbol in symbols: - print symbol.name # OK - print symbol.address # NOT OK. We didn't look up this property before. - - # Cache everything up front. - symbols = list(obj.get_symbols(cache=True)) - for symbol in symbols: - print symbol.name # OK - -""" - -from ctypes import c_char_p -from ctypes import c_char -from ctypes import POINTER -from ctypes import c_uint64 -from ctypes import string_at - -from .common import CachedProperty -from .common import LLVMObject -from .common import c_object_p -from .common import get_library -from .core import MemoryBuffer - -__all__ = [ - "lib", - "ObjectFile", - "Relocation", - "Section", - "Symbol", -] - -class ObjectFile(LLVMObject): - """Represents an object/binary file.""" - - def __init__(self, filename=None, contents=None): - """Construct an instance from a filename or binary data. - - filename must be a path to a file that can be opened with open(). - contents can be either a native Python buffer type (like str) or a - llvm.core.MemoryBuffer instance. - """ - if contents: - assert isinstance(contents, MemoryBuffer) - - if filename is not None: - contents = MemoryBuffer(filename=filename) - - if contents is None: - raise Exception('No input found.') - - ptr = lib.LLVMCreateObjectFile(contents) - LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile) - self.take_ownership(contents) - - def get_sections(self, cache=False): - """Obtain the sections in this object file. - - This is a generator for llvm.object.Section instances. - - Sections are exposed as limited-use objects. See the module's - documentation on iterators for more. - """ - sections = lib.LLVMGetSections(self) - last = None - while True: - if lib.LLVMIsSectionIteratorAtEnd(self, sections): - break - - last = Section(sections) - if cache: - last.cache() - - yield last - - lib.LLVMMoveToNextSection(sections) - last.expire() - - if last is not None: - last.expire() - - lib.LLVMDisposeSectionIterator(sections) - - def get_symbols(self, cache=False): - """Obtain the symbols in this object file. - - This is a generator for llvm.object.Symbol instances. - - Each Symbol instance is a limited-use object. See this module's - documentation on iterators for more. - """ - symbols = lib.LLVMGetSymbols(self) - last = None - while True: - if lib.LLVMIsSymbolIteratorAtEnd(self, symbols): - break - - last = Symbol(symbols, self) - if cache: - last.cache() - - yield last - - lib.LLVMMoveToNextSymbol(symbols) - last.expire() - - if last is not None: - last.expire() - - lib.LLVMDisposeSymbolIterator(symbols) - -class Section(LLVMObject): - """Represents a section in an object file.""" - - def __init__(self, ptr): - """Construct a new section instance. - - Section instances can currently only be created from an ObjectFile - instance. Therefore, this constructor should not be used outside of - this module. - """ - LLVMObject.__init__(self, ptr) - - self.expired = False - - @CachedProperty - def name(self): - """Obtain the string name of the section. - - This is typically something like '.dynsym' or '.rodata'. - """ - if self.expired: - raise Exception('Section instance has expired.') - - return lib.LLVMGetSectionName(self) - - @CachedProperty - def size(self): - """The size of the section, in long bytes.""" - if self.expired: - raise Exception('Section instance has expired.') - - return lib.LLVMGetSectionSize(self) - - @CachedProperty - def contents(self): - if self.expired: - raise Exception('Section instance has expired.') - - siz = self.size - - r = lib.LLVMGetSectionContents(self) - if r: - return string_at(r, siz) - return None - - @CachedProperty - def address(self): - """The address of this section, in long bytes.""" - if self.expired: - raise Exception('Section instance has expired.') - - return lib.LLVMGetSectionAddress(self) - - def has_symbol(self, symbol): - """Returns whether a Symbol instance is present in this Section.""" - if self.expired: - raise Exception('Section instance has expired.') - - assert isinstance(symbol, Symbol) - return lib.LLVMGetSectionContainsSymbol(self, symbol) - - def get_relocations(self, cache=False): - """Obtain the relocations in this Section. - - This is a generator for llvm.object.Relocation instances. - - Each instance is a limited used object. See this module's documentation - on iterators for more. - """ - if self.expired: - raise Exception('Section instance has expired.') - - relocations = lib.LLVMGetRelocations(self) - last = None - while True: - if lib.LLVMIsRelocationIteratorAtEnd(self, relocations): - break - - last = Relocation(relocations) - if cache: - last.cache() - - yield last - - lib.LLVMMoveToNextRelocation(relocations) - last.expire() - - if last is not None: - last.expire() - - lib.LLVMDisposeRelocationIterator(relocations) - - def cache(self): - """Cache properties of this Section. - - This can be called as a workaround to the single active Section - limitation. When called, the properties of the Section are fetched so - they are still available after the Section has been marked inactive. - """ - getattr(self, 'name') - getattr(self, 'size') - getattr(self, 'contents') - getattr(self, 'address') - - def expire(self): - """Expire the section. - - This is called internally by the section iterator. - """ - self.expired = True - -class Symbol(LLVMObject): - """Represents a symbol in an object file.""" - def __init__(self, ptr, object_file): - assert isinstance(ptr, c_object_p) - assert isinstance(object_file, ObjectFile) - - LLVMObject.__init__(self, ptr) - - self.expired = False - self._object_file = object_file - - @CachedProperty - def name(self): - """The str name of the symbol. - - This is often a function or variable name. Keep in mind that name - mangling could be in effect. - """ - if self.expired: - raise Exception('Symbol instance has expired.') - - return lib.LLVMGetSymbolName(self) - - @CachedProperty - def address(self): - """The address of this symbol, in long bytes.""" - if self.expired: - raise Exception('Symbol instance has expired.') - - return lib.LLVMGetSymbolAddress(self) - - @CachedProperty - def size(self): - """The size of the symbol, in long bytes.""" - if self.expired: - raise Exception('Symbol instance has expired.') - - return lib.LLVMGetSymbolSize(self) - - @CachedProperty - def section(self): - """The Section to which this Symbol belongs. - - The returned Section instance does not expire, unlike Sections that are - commonly obtained through iteration. - - Because this obtains a new section iterator each time it is accessed, - calling this on a number of Symbol instances could be expensive. - """ - sections = lib.LLVMGetSections(self._object_file) - lib.LLVMMoveToContainingSection(sections, self) - - return Section(sections) - - def cache(self): - """Cache all cacheable properties.""" - getattr(self, 'name') - getattr(self, 'address') - getattr(self, 'size') - - def expire(self): - """Mark the object as expired to prevent future API accesses. - - This is called internally by this module and it is unlikely that - external callers have a legitimate reason for using it. - """ - self.expired = True - -class Relocation(LLVMObject): - """Represents a relocation definition.""" - def __init__(self, ptr): - """Create a new relocation instance. - - Relocations are created from objects derived from Section instances. - Therefore, this constructor should not be called outside of this - module. See Section.get_relocations() for the proper method to obtain - a Relocation instance. - """ - assert isinstance(ptr, c_object_p) - - LLVMObject.__init__(self, ptr) - - self.expired = False - - @CachedProperty - def offset(self): - """The offset of this relocation, in long bytes.""" - if self.expired: - raise Exception('Relocation instance has expired.') - - return lib.LLVMGetRelocationOffset(self) - - @CachedProperty - def symbol(self): - """The Symbol corresponding to this Relocation.""" - if self.expired: - raise Exception('Relocation instance has expired.') - - ptr = lib.LLVMGetRelocationSymbol(self) - return Symbol(ptr) - - @CachedProperty - def type_number(self): - """The relocation type, as a long.""" - if self.expired: - raise Exception('Relocation instance has expired.') - - return lib.LLVMGetRelocationType(self) - - @CachedProperty - def type_name(self): - """The relocation type's name, as a str.""" - if self.expired: - raise Exception('Relocation instance has expired.') - - return lib.LLVMGetRelocationTypeName(self) - - @CachedProperty - def value_string(self): - if self.expired: - raise Exception('Relocation instance has expired.') - - return lib.LLVMGetRelocationValueString(self) - - def expire(self): - """Expire this instance, making future API accesses fail.""" - self.expired = True - - def cache(self): - """Cache all cacheable properties on this instance.""" - getattr(self, 'address') - getattr(self, 'offset') - getattr(self, 'symbol') - getattr(self, 'type') - getattr(self, 'type_name') - getattr(self, 'value_string') - -def register_library(library): - """Register function prototypes with LLVM library instance.""" - - # Object.h functions - library.LLVMCreateObjectFile.argtypes = [MemoryBuffer] - library.LLVMCreateObjectFile.restype = c_object_p - - library.LLVMDisposeObjectFile.argtypes = [ObjectFile] - - library.LLVMGetSections.argtypes = [ObjectFile] - library.LLVMGetSections.restype = c_object_p - - library.LLVMDisposeSectionIterator.argtypes = [c_object_p] - - library.LLVMIsSectionIteratorAtEnd.argtypes = [ObjectFile, c_object_p] - library.LLVMIsSectionIteratorAtEnd.restype = bool - - library.LLVMMoveToNextSection.argtypes = [c_object_p] - - library.LLVMMoveToContainingSection.argtypes = [c_object_p, c_object_p] - - library.LLVMGetSymbols.argtypes = [ObjectFile] - library.LLVMGetSymbols.restype = c_object_p - - library.LLVMDisposeSymbolIterator.argtypes = [c_object_p] - - library.LLVMIsSymbolIteratorAtEnd.argtypes = [ObjectFile, c_object_p] - library.LLVMIsSymbolIteratorAtEnd.restype = bool - - library.LLVMMoveToNextSymbol.argtypes = [c_object_p] - - library.LLVMGetSectionName.argtypes = [c_object_p] - library.LLVMGetSectionName.restype = c_char_p - - library.LLVMGetSectionSize.argtypes = [c_object_p] - library.LLVMGetSectionSize.restype = c_uint64 - - library.LLVMGetSectionContents.argtypes = [c_object_p] - # Can't use c_char_p here as it isn't a NUL-terminated string. - library.LLVMGetSectionContents.restype = POINTER(c_char) - - library.LLVMGetSectionAddress.argtypes = [c_object_p] - library.LLVMGetSectionAddress.restype = c_uint64 - - library.LLVMGetSectionContainsSymbol.argtypes = [c_object_p, c_object_p] - library.LLVMGetSectionContainsSymbol.restype = bool - - library.LLVMGetRelocations.argtypes = [c_object_p] - library.LLVMGetRelocations.restype = c_object_p - - library.LLVMDisposeRelocationIterator.argtypes = [c_object_p] - - library.LLVMIsRelocationIteratorAtEnd.argtypes = [c_object_p, c_object_p] - library.LLVMIsRelocationIteratorAtEnd.restype = bool - - library.LLVMMoveToNextRelocation.argtypes = [c_object_p] - - library.LLVMGetSymbolName.argtypes = [Symbol] - library.LLVMGetSymbolName.restype = c_char_p - - library.LLVMGetSymbolAddress.argtypes = [Symbol] - library.LLVMGetSymbolAddress.restype = c_uint64 - - library.LLVMGetSymbolSize.argtypes = [Symbol] - library.LLVMGetSymbolSize.restype = c_uint64 - - library.LLVMGetRelocationOffset.argtypes = [c_object_p] - library.LLVMGetRelocationOffset.restype = c_uint64 - - library.LLVMGetRelocationSymbol.argtypes = [c_object_p] - library.LLVMGetRelocationSymbol.restype = c_object_p - - library.LLVMGetRelocationType.argtypes = [c_object_p] - library.LLVMGetRelocationType.restype = c_uint64 - - library.LLVMGetRelocationTypeName.argtypes = [c_object_p] - library.LLVMGetRelocationTypeName.restype = c_char_p - - library.LLVMGetRelocationValueString.argtypes = [c_object_p] - library.LLVMGetRelocationValueString.restype = c_char_p - -lib = get_library() -register_library(lib) diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/base.py b/interpreter/llvm/src/bindings/python/llvm/tests/base.py deleted file mode 100644 index aa435bc1f35f5..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/base.py +++ /dev/null @@ -1,43 +0,0 @@ -import os.path -import sys -import unittest - - -POSSIBLE_TEST_BINARIES = [ - 'libreadline.so.5', - 'libreadline.so.6', -] - -POSSIBLE_TEST_BINARY_PATHS = [ - '/usr/lib/debug', - '/lib', - '/usr/lib', - '/usr/local/lib', - '/lib/i386-linux-gnu', -] - -class TestBase(unittest.TestCase): - if sys.version_info.major == 2: - assertRaisesRegex = unittest.TestCase.assertRaisesRegexp - - def get_test_binary(self): - """Helper to obtain a test binary for object file testing. - - FIXME Support additional, highly-likely targets or create one - ourselves. - """ - for d in POSSIBLE_TEST_BINARY_PATHS: - for lib in POSSIBLE_TEST_BINARIES: - path = os.path.join(d, lib) - - if os.path.exists(path): - return path - - raise Exception('No suitable test binaries available!') - get_test_binary.__test__ = False - - def get_test_file(self): - return os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_file") - - def get_test_bc(self): - return os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.bc") diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test.bc b/interpreter/llvm/src/bindings/python/llvm/tests/test.bc deleted file mode 100644 index 8d3d28fbc0db7..0000000000000 Binary files a/interpreter/llvm/src/bindings/python/llvm/tests/test.bc and /dev/null differ diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test_bitreader.py b/interpreter/llvm/src/bindings/python/llvm/tests/test_bitreader.py deleted file mode 100644 index 460005a2b87ab..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/test_bitreader.py +++ /dev/null @@ -1,17 +0,0 @@ -from __future__ import print_function - -from .base import TestBase -from ..core import OpCode -from ..core import MemoryBuffer -from ..core import PassRegistry -from ..core import Context -from ..core import Module -from ..bit_reader import parse_bitcode - -class TestBitReader(TestBase): - - def test_parse_bitcode(self): - source = self.get_test_bc() - m = parse_bitcode(MemoryBuffer(filename=source)) - print(m.target) - print(m.datalayout) diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test_core.py b/interpreter/llvm/src/bindings/python/llvm/tests/test_core.py deleted file mode 100644 index 68572b50b3d66..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/test_core.py +++ /dev/null @@ -1,142 +0,0 @@ -from __future__ import print_function - -from .base import TestBase -from ..core import MemoryBuffer -from ..core import PassRegistry -from ..core import Context -from ..core import Module -from ..core import Enums -from ..core import OpCode -from ..bit_reader import parse_bitcode - -class TestCore(TestBase): - def test_enumerations(self): - for enum_cls, enum_spec in Enums: - for enum_name, enum_value in enum_spec: - # First make sure that enum_cls has the name of the enum as an - # attribute. People will access these values as - # EnumCls.EnumName. - self.assertTrue(hasattr(enum_cls, enum_name)) - v_attr = getattr(enum_cls, enum_name) - self.assertTrue(isinstance(v_attr, enum_cls)) - - # Then make sure that the value returned for this attribute is - # correct in both ways. - self.assertEqual(v_attr.value, enum_value) - - e = enum_cls.from_value(enum_value) - self.assertTrue(isinstance(e, enum_cls)) - self.assertEqual(e, v_attr) - - def test_memory_buffer_create_from_file(self): - source = self.get_test_file() - - MemoryBuffer(filename=source) - - def test_memory_buffer_failing(self): - with self.assertRaises(Exception): - MemoryBuffer(filename="/hopefully/this/path/doesnt/exist") - - def test_memory_buffer_len(self): - source = self.get_test_file() - m = MemoryBuffer(filename=source) - self.assertEqual(len(m), 50) - - def test_create_passregistry(self): - PassRegistry() - - def test_create_context(self): - Context.GetGlobalContext() - - def test_create_module_with_name(self): - # Make sure we can not create a module without a LLVMModuleRef. - with self.assertRaises(TypeError): - m = Module() - m = Module.CreateWithName("test-module") - - def test_module_getset_datalayout(self): - m = Module.CreateWithName("test-module") - dl = "e-p:32:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:32:64-v128:32:128-a0:0:32-n32-S32" - m.datalayout = dl - self.assertEqual(m.datalayout, dl) - - def test_module_getset_target(self): - m = Module.CreateWithName("test-module") - target = "thumbv7-apple-ios5.0.0" - m.target = target - self.assertEqual(m.target, target) - - def test_module_print_module_to_file(self): - m = Module.CreateWithName("test") - dl = "e-p:32:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:32:64-v128:32:128-a0:0:32-n32-S32" - m.datalayout = dl - target = "thumbv7-apple-ios5.0.0" - m.target = target - m.print_module_to_file("test2.ll") - - def test_module_function_iteration(self): - m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) - i = 0 - functions = ["f", "f2", "f3", "f4", "f5", "f6", "g1", "g2", "h1", "h2", - "h3"] - # Forward - for f in m: - self.assertEqual(f.name, functions[i]) - f.dump() - i += 1 - # Backwards - for f in reversed(m): - i -= 1 - self.assertEqual(f.name, functions[i]) - f.dump() - - def test_function_basicblock_iteration(self): - m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) - i = 0 - - bb_list = ['b1', 'b2', 'end'] - - f = m.first - while f.name != "f6": - f = f.next - - # Forward - for bb in f: - self.assertEqual(bb.name, bb_list[i]) - bb.dump() - i += 1 - - # Backwards - for bb in reversed(f): - i -= 1 - self.assertEqual(bb.name, bb_list[i]) - bb.dump() - - def test_basicblock_instruction_iteration(self): - m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) - i = 0 - - inst_list = [('arg1', OpCode.ExtractValue), - ('arg2', OpCode.ExtractValue), - ('', OpCode.Call), - ('', OpCode.Ret)] - - bb = m.first.first - - # Forward - for inst in bb: - self.assertEqual(inst.name, inst_list[i][0]) - self.assertEqual(inst.opcode, inst_list[i][1]) - for op in range(len(inst)): - o = inst.get_operand(op) - print(o.name) - o.dump() - inst.dump() - i += 1 - - # Backwards - for inst in reversed(bb): - i -= 1 - self.assertEqual(inst.name, inst_list[i][0]) - self.assertEqual(inst.opcode, inst_list[i][1]) - inst.dump() diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test_disassembler.py b/interpreter/llvm/src/bindings/python/llvm/tests/test_disassembler.py deleted file mode 100644 index 29f2f7060bac5..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/test_disassembler.py +++ /dev/null @@ -1,45 +0,0 @@ -from __future__ import print_function - -from .base import TestBase - -from ..disassembler import Disassembler, Option_UseMarkup - -class TestDisassembler(TestBase): - def test_instantiate(self): - Disassembler('i686-apple-darwin9') - - def test_basic(self): - sequence = '\x67\xe3\x81' # jcxz -127 - triple = 'i686-apple-darwin9' - - disassembler = Disassembler(triple) - - count, s = disassembler.get_instruction(sequence) - self.assertEqual(count, 3) - self.assertEqual(s, '\tjcxz\t-127') - - def test_nonexistent_triple(self): - with self.assertRaisesRegex(Exception, "Could not obtain disassembler for triple"): - Disassembler("nonexistent-triple-raises") - - def test_get_instructions(self): - sequence = '\x67\xe3\x81\x01\xc7' # jcxz -127; addl %eax, %edi - - disassembler = Disassembler('i686-apple-darwin9') - - instructions = list(disassembler.get_instructions(sequence)) - self.assertEqual(len(instructions), 2) - - self.assertEqual(instructions[0], (0, 3, '\tjcxz\t-127')) - self.assertEqual(instructions[1], (3, 2, '\taddl\t%eax, %edi')) - - def test_set_options(self): - sequence = '\x10\x40\x2d\xe9' - triple = 'arm-linux-android' - - disassembler = Disassembler(triple) - disassembler.set_options(Option_UseMarkup) - count, s = disassembler.get_instruction(sequence) - print(s) - self.assertEqual(count, 4) - self.assertEqual(s, '\tpush\t{, }') diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test_file b/interpreter/llvm/src/bindings/python/llvm/tests/test_file deleted file mode 100644 index 6c9b0385bd976..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/test_file +++ /dev/null @@ -1 +0,0 @@ -I,"ìcAGðxq‘ÑÔ¹d«±ùà§vl¥À\»L>šg>`ö©ÿ©`‡wÉ© \ No newline at end of file diff --git a/interpreter/llvm/src/bindings/python/llvm/tests/test_object.py b/interpreter/llvm/src/bindings/python/llvm/tests/test_object.py deleted file mode 100644 index a45b7beec3353..0000000000000 --- a/interpreter/llvm/src/bindings/python/llvm/tests/test_object.py +++ /dev/null @@ -1,69 +0,0 @@ -from numbers import Integral - -from .base import TestBase -from ..object import ObjectFile -from ..object import Relocation -from ..object import Section -from ..object import Symbol - -class TestObjectFile(TestBase): - def get_object_file(self): - source = self.get_test_binary() - return ObjectFile(filename=source) - - def test_create_from_file(self): - self.get_object_file() - - def test_get_sections(self): - o = self.get_object_file() - - count = 0 - for section in o.get_sections(): - count += 1 - assert isinstance(section, Section) - assert isinstance(section.name, str) - assert isinstance(section.size, Integral) - assert isinstance(section.contents, str) - assert isinstance(section.address, Integral) - assert len(section.contents) == section.size - - self.assertGreater(count, 0) - - for section in o.get_sections(): - section.cache() - - def test_get_symbols(self): - o = self.get_object_file() - - count = 0 - for symbol in o.get_symbols(): - count += 1 - assert isinstance(symbol, Symbol) - assert isinstance(symbol.name, str) - assert isinstance(symbol.address, Integral) - assert isinstance(symbol.size, Integral) - - self.assertGreater(count, 0) - - for symbol in o.get_symbols(): - symbol.cache() - - def test_symbol_section_accessor(self): - o = self.get_object_file() - - for symbol in o.get_symbols(): - section = symbol.section - assert isinstance(section, Section) - - break - - def test_get_relocations(self): - o = self.get_object_file() - for section in o.get_sections(): - for relocation in section.get_relocations(): - assert isinstance(relocation, Relocation) - assert isinstance(relocation.address, Integral) - assert isinstance(relocation.offset, Integral) - assert isinstance(relocation.type_number, Integral) - assert isinstance(relocation.type_name, str) - assert isinstance(relocation.value_string, str) diff --git a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp.orig b/interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp.orig deleted file mode 100644 index c85e80b52e5ae..0000000000000 --- a/interpreter/llvm/src/lib/ExecutionEngine/JITLink/EHFrameSupport.cpp.orig +++ /dev/null @@ -1,812 +0,0 @@ -//===-------- JITLink_EHFrameSupport.cpp - JITLink eh-frame utils ---------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "EHFrameSupportImpl.h" - -#include "llvm/BinaryFormat/Dwarf.h" -#include "llvm/Config/config.h" -#include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h" -#include "llvm/Support/DynamicLibrary.h" - -#define DEBUG_TYPE "jitlink" - -namespace llvm { -namespace jitlink { - -EHFrameSplitter::EHFrameSplitter(StringRef EHFrameSectionName) - : EHFrameSectionName(EHFrameSectionName) {} - -Error EHFrameSplitter::operator()(LinkGraph &G) { - auto *EHFrame = G.findSectionByName(EHFrameSectionName); - - if (!EHFrame) { - LLVM_DEBUG({ - dbgs() << "EHFrameSplitter: No " << EHFrameSectionName - << " section. Nothing to do\n"; - }); - return Error::success(); - } - - LLVM_DEBUG({ - dbgs() << "EHFrameSplitter: Processing " << EHFrameSectionName << "...\n"; - }); - - DenseMap Caches; - - { - // Pre-build the split caches. - for (auto *B : EHFrame->blocks()) - Caches[B] = LinkGraph::SplitBlockCache::value_type(); - for (auto *Sym : EHFrame->symbols()) - Caches[&Sym->getBlock()]->push_back(Sym); - for (auto *B : EHFrame->blocks()) - llvm::sort(*Caches[B], [](const Symbol *LHS, const Symbol *RHS) { - return LHS->getOffset() > RHS->getOffset(); - }); - } - - // Iterate over blocks (we do this by iterating over Caches entries rather - // than EHFrame->blocks() as we will be inserting new blocks along the way, - // which would invalidate iterators in the latter sequence. - for (auto &KV : Caches) { - auto &B = *KV.first; - auto &BCache = KV.second; - if (auto Err = processBlock(G, B, BCache)) - return Err; - } - - return Error::success(); -} - -Error EHFrameSplitter::processBlock(LinkGraph &G, Block &B, - LinkGraph::SplitBlockCache &Cache) { - LLVM_DEBUG({ - dbgs() << " Processing block at " << formatv("{0:x16}", B.getAddress()) - << "\n"; - }); - - // eh-frame should not contain zero-fill blocks. - if (B.isZeroFill()) - return make_error("Unexpected zero-fill block in " + - EHFrameSectionName + " section"); - - if (B.getSize() == 0) { - LLVM_DEBUG(dbgs() << " Block is empty. Skipping.\n"); - return Error::success(); - } - - BinaryStreamReader BlockReader( - StringRef(B.getContent().data(), B.getContent().size()), - G.getEndianness()); - - while (true) { - uint64_t RecordStartOffset = BlockReader.getOffset(); - - LLVM_DEBUG({ - dbgs() << " Processing CFI record at " - << formatv("{0:x16}", B.getAddress()) << "\n"; - }); - - uint32_t Length; - if (auto Err = BlockReader.readInteger(Length)) - return Err; - if (Length != 0xffffffff) { - if (auto Err = BlockReader.skip(Length)) - return Err; - } else { - uint64_t ExtendedLength; - if (auto Err = BlockReader.readInteger(ExtendedLength)) - return Err; - if (auto Err = BlockReader.skip(ExtendedLength)) - return Err; - } - - // If this was the last block then there's nothing to split - if (BlockReader.empty()) { - LLVM_DEBUG(dbgs() << " Extracted " << B << "\n"); - return Error::success(); - } - - uint64_t BlockSize = BlockReader.getOffset() - RecordStartOffset; - auto &NewBlock = G.splitBlock(B, BlockSize); - (void)NewBlock; - LLVM_DEBUG(dbgs() << " Extracted " << NewBlock << "\n"); - } -} - -EHFrameEdgeFixer::EHFrameEdgeFixer(StringRef EHFrameSectionName, - unsigned PointerSize, Edge::Kind Delta64, - Edge::Kind Delta32, Edge::Kind NegDelta32) - : EHFrameSectionName(EHFrameSectionName), PointerSize(PointerSize), - Delta64(Delta64), Delta32(Delta32), NegDelta32(NegDelta32) {} - -Error EHFrameEdgeFixer::operator()(LinkGraph &G) { - auto *EHFrame = G.findSectionByName(EHFrameSectionName); - - if (!EHFrame) { - LLVM_DEBUG({ - dbgs() << "EHFrameEdgeFixer: No " << EHFrameSectionName - << " section. Nothing to do\n"; - }); - return Error::success(); - } - - // Check that we support the graph's pointer size. - if (G.getPointerSize() != 4 && G.getPointerSize() != 8) - return make_error( - "EHFrameEdgeFixer only supports 32 and 64 bit targets"); - - LLVM_DEBUG({ - dbgs() << "EHFrameEdgeFixer: Processing " << EHFrameSectionName << "...\n"; - }); - - ParseContext PC(G); - - // Build a map of all blocks and symbols in the text sections. We will use - // these for finding / building edge targets when processing FDEs. - for (auto &Sec : G.sections()) { - PC.AddrToSyms.addSymbols(Sec.symbols()); - if (auto Err = PC.AddrToBlock.addBlocks(Sec.blocks(), - BlockAddressMap::includeNonNull)) - return Err; - } - - // Sort eh-frame blocks into address order to ensure we visit CIEs before - // their child FDEs. - std::vector EHFrameBlocks; - for (auto *B : EHFrame->blocks()) - EHFrameBlocks.push_back(B); - llvm::sort(EHFrameBlocks, [](const Block *LHS, const Block *RHS) { - return LHS->getAddress() < RHS->getAddress(); - }); - - // Loop over the blocks in address order. - for (auto *B : EHFrameBlocks) - if (auto Err = processBlock(PC, *B)) - return Err; - - return Error::success(); -} - -Error EHFrameEdgeFixer::processBlock(ParseContext &PC, Block &B) { - - LLVM_DEBUG({ - dbgs() << " Processing block at " << formatv("{0:x16}", B.getAddress()) - << "\n"; - }); - - // eh-frame should not contain zero-fill blocks. - if (B.isZeroFill()) - return make_error("Unexpected zero-fill block in " + - EHFrameSectionName + " section"); - - if (B.getSize() == 0) { - LLVM_DEBUG(dbgs() << " Block is empty. Skipping.\n"); - return Error::success(); - } - - // Find the offsets of any existing edges from this block. - BlockEdgeMap BlockEdges; - for (auto &E : B.edges()) - if (E.isRelocation()) { - if (BlockEdges.count(E.getOffset())) - return make_error( - "Multiple relocations at offset " + - formatv("{0:x16}", E.getOffset()) + " in " + EHFrameSectionName + - " block at address " + formatv("{0:x16}", B.getAddress())); - - BlockEdges[E.getOffset()] = EdgeTarget(E); - } - - CIEInfosMap CIEInfos; - BinaryStreamReader BlockReader( - StringRef(B.getContent().data(), B.getContent().size()), - PC.G.getEndianness()); - while (!BlockReader.empty()) { - size_t RecordStartOffset = BlockReader.getOffset(); - - LLVM_DEBUG({ - dbgs() << " Processing CFI record at " - << formatv("{0:x16}", B.getAddress() + RecordStartOffset) << "\n"; - }); - - // Get the record length. - size_t RecordRemaining; - { - uint32_t Length; - if (auto Err = BlockReader.readInteger(Length)) - return Err; - // If Length < 0xffffffff then use the regular length field, otherwise - // read the extended length field. - if (Length != 0xffffffff) - RecordRemaining = Length; - else { - uint64_t ExtendedLength; - if (auto Err = BlockReader.readInteger(ExtendedLength)) - return Err; - RecordRemaining = ExtendedLength; - } - } - - if (BlockReader.bytesRemaining() < RecordRemaining) - return make_error( - "Incomplete CFI record at " + - formatv("{0:x16}", B.getAddress() + RecordStartOffset)); - - // Read the CIE delta for this record. - uint64_t CIEDeltaFieldOffset = BlockReader.getOffset() - RecordStartOffset; - uint32_t CIEDelta; - if (auto Err = BlockReader.readInteger(CIEDelta)) - return Err; - - if (CIEDelta == 0) { - if (auto Err = processCIE(PC, B, RecordStartOffset, - CIEDeltaFieldOffset + RecordRemaining, - CIEDeltaFieldOffset)) - return Err; - } else { - if (auto Err = processFDE(PC, B, RecordStartOffset, - CIEDeltaFieldOffset + RecordRemaining, - CIEDeltaFieldOffset, CIEDelta, BlockEdges)) - return Err; - } - - // Move to the next record. - BlockReader.setOffset(RecordStartOffset + CIEDeltaFieldOffset + - RecordRemaining); - } - - return Error::success(); -} - -Error EHFrameEdgeFixer::processCIE(ParseContext &PC, Block &B, - size_t RecordOffset, size_t RecordLength, - size_t CIEDeltaFieldOffset) { - - LLVM_DEBUG(dbgs() << " Record is CIE\n"); - - auto RecordContent = B.getContent().slice(RecordOffset, RecordLength); - BinaryStreamReader RecordReader( - StringRef(RecordContent.data(), RecordContent.size()), - PC.G.getEndianness()); - - // Skip past the CIE delta field: we've already processed this far. - RecordReader.setOffset(CIEDeltaFieldOffset + 4); - - auto &CIESymbol = - PC.G.addAnonymousSymbol(B, RecordOffset, RecordLength, false, false); - CIEInformation CIEInfo(CIESymbol); - - uint8_t Version = 0; - if (auto Err = RecordReader.readInteger(Version)) - return Err; - - if (Version != 0x01) - return make_error("Bad CIE version " + Twine(Version) + - " (should be 0x01) in eh-frame"); - - auto AugInfo = parseAugmentationString(RecordReader); - if (!AugInfo) - return AugInfo.takeError(); - - // Skip the EH Data field if present. - if (AugInfo->EHDataFieldPresent) - if (auto Err = RecordReader.skip(PC.G.getPointerSize())) - return Err; - - // Read and sanity check the code alignment factor. - { - uint64_t CodeAlignmentFactor = 0; - if (auto Err = RecordReader.readULEB128(CodeAlignmentFactor)) - return Err; - if (CodeAlignmentFactor != 1) - return make_error("Unsupported CIE code alignment factor " + - Twine(CodeAlignmentFactor) + - " (expected 1)"); - } - - // Read and sanity check the data alignment factor. - { - int64_t DataAlignmentFactor = 0; - if (auto Err = RecordReader.readSLEB128(DataAlignmentFactor)) - return Err; - if (DataAlignmentFactor != -8) - return make_error("Unsupported CIE data alignment factor " + - Twine(DataAlignmentFactor) + - " (expected -8)"); - } - - // Skip the return address register field. - if (auto Err = RecordReader.skip(1)) - return Err; - - uint64_t AugmentationDataLength = 0; - if (auto Err = RecordReader.readULEB128(AugmentationDataLength)) - return Err; - - uint32_t AugmentationDataStartOffset = RecordReader.getOffset(); - - uint8_t *NextField = &AugInfo->Fields[0]; - while (uint8_t Field = *NextField++) { - switch (Field) { - case 'L': { - CIEInfo.FDEsHaveLSDAField = true; - uint8_t LSDAPointerEncoding; - if (auto Err = RecordReader.readInteger(LSDAPointerEncoding)) - return Err; - if (!isSupportedPointerEncoding(LSDAPointerEncoding)) - return make_error( - "Unsupported LSDA pointer encoding " + - formatv("{0:x2}", LSDAPointerEncoding) + " in CIE at " + - formatv("{0:x16}", CIESymbol.getAddress())); - CIEInfo.LSDAPointerEncoding = LSDAPointerEncoding; - break; - } - case 'P': { - uint8_t PersonalityPointerEncoding = 0; - if (auto Err = RecordReader.readInteger(PersonalityPointerEncoding)) - return Err; - if (PersonalityPointerEncoding != - (dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | - dwarf::DW_EH_PE_sdata4)) - return make_error( - "Unspported personality pointer " - "encoding " + - formatv("{0:x2}", PersonalityPointerEncoding) + " in CIE at " + - formatv("{0:x16}", CIESymbol.getAddress())); - uint32_t PersonalityPointerAddress; - if (auto Err = RecordReader.readInteger(PersonalityPointerAddress)) - return Err; - break; - } - case 'R': { - uint8_t FDEPointerEncoding; - if (auto Err = RecordReader.readInteger(FDEPointerEncoding)) - return Err; - if (!isSupportedPointerEncoding(FDEPointerEncoding)) - return make_error( - "Unsupported FDE pointer encoding " + - formatv("{0:x2}", FDEPointerEncoding) + " in CIE at " + - formatv("{0:x16}", CIESymbol.getAddress())); - CIEInfo.FDEPointerEncoding = FDEPointerEncoding; - break; - } - default: - llvm_unreachable("Invalid augmentation string field"); - } - } - - if (RecordReader.getOffset() - AugmentationDataStartOffset > - AugmentationDataLength) - return make_error("Read past the end of the augmentation " - "data while parsing fields"); - - assert(!PC.CIEInfos.count(CIESymbol.getAddress()) && - "Multiple CIEs recorded at the same address?"); - PC.CIEInfos[CIESymbol.getAddress()] = std::move(CIEInfo); - - return Error::success(); -} - -Error EHFrameEdgeFixer::processFDE(ParseContext &PC, Block &B, - size_t RecordOffset, size_t RecordLength, - size_t CIEDeltaFieldOffset, - uint32_t CIEDelta, - BlockEdgeMap &BlockEdges) { - LLVM_DEBUG(dbgs() << " Record is FDE\n"); - - JITTargetAddress RecordAddress = B.getAddress() + RecordOffset; - - auto RecordContent = B.getContent().slice(RecordOffset, RecordLength); - BinaryStreamReader RecordReader( - StringRef(RecordContent.data(), RecordContent.size()), - PC.G.getEndianness()); - - // Skip past the CIE delta field: we've already read this far. - RecordReader.setOffset(CIEDeltaFieldOffset + 4); - - auto &FDESymbol = - PC.G.addAnonymousSymbol(B, RecordOffset, RecordLength, false, false); - - CIEInformation *CIEInfo = nullptr; - - { - // Process the CIE pointer field. - auto CIEEdgeItr = BlockEdges.find(RecordOffset + CIEDeltaFieldOffset); - JITTargetAddress CIEAddress = - RecordAddress + CIEDeltaFieldOffset - CIEDelta; - if (CIEEdgeItr == BlockEdges.end()) { - - LLVM_DEBUG({ - dbgs() << " Adding edge at " - << formatv("{0:x16}", RecordAddress + CIEDeltaFieldOffset) - << " to CIE at: " << formatv("{0:x16}", CIEAddress) << "\n"; - }); - if (auto CIEInfoOrErr = PC.findCIEInfo(CIEAddress)) - CIEInfo = *CIEInfoOrErr; - else - return CIEInfoOrErr.takeError(); - assert(CIEInfo->CIESymbol && "CIEInfo has no CIE symbol set"); - B.addEdge(NegDelta32, RecordOffset + CIEDeltaFieldOffset, - *CIEInfo->CIESymbol, 0); - } else { - LLVM_DEBUG({ - dbgs() << " Already has edge at " - << formatv("{0:x16}", RecordAddress + CIEDeltaFieldOffset) - << " to CIE at " << formatv("{0:x16}", CIEAddress) << "\n"; - }); - auto &EI = CIEEdgeItr->second; - if (EI.Addend) - return make_error( - "CIE edge at " + - formatv("{0:x16}", RecordAddress + CIEDeltaFieldOffset) + - " has non-zero addend"); - if (auto CIEInfoOrErr = PC.findCIEInfo(EI.Target->getAddress())) - CIEInfo = *CIEInfoOrErr; - else - return CIEInfoOrErr.takeError(); - } - } - - { - // Process the PC-Begin field. - Block *PCBeginBlock = nullptr; - JITTargetAddress PCBeginFieldOffset = RecordReader.getOffset(); - auto PCEdgeItr = BlockEdges.find(RecordOffset + PCBeginFieldOffset); - if (PCEdgeItr == BlockEdges.end()) { - auto PCBeginPtrInfo = - readEncodedPointer(CIEInfo->FDEPointerEncoding, - RecordAddress + PCBeginFieldOffset, RecordReader); - if (!PCBeginPtrInfo) - return PCBeginPtrInfo.takeError(); - JITTargetAddress PCBegin = PCBeginPtrInfo->first; - Edge::Kind PCBeginEdgeKind = PCBeginPtrInfo->second; - LLVM_DEBUG({ - dbgs() << " Adding edge at " - << formatv("{0:x16}", RecordAddress + PCBeginFieldOffset) - << " to PC at " << formatv("{0:x16}", PCBegin) << "\n"; - }); - auto PCBeginSym = getOrCreateSymbol(PC, PCBegin); - if (!PCBeginSym) - return PCBeginSym.takeError(); - B.addEdge(PCBeginEdgeKind, RecordOffset + PCBeginFieldOffset, *PCBeginSym, - 0); - PCBeginBlock = &PCBeginSym->getBlock(); - } else { - auto &EI = PCEdgeItr->second; - LLVM_DEBUG({ - dbgs() << " Already has edge at " - << formatv("{0:x16}", RecordAddress + PCBeginFieldOffset) - << " to PC at " << formatv("{0:x16}", EI.Target->getAddress()); - if (EI.Addend) - dbgs() << " + " << formatv("{0:x16}", EI.Addend); - dbgs() << "\n"; - }); - - // Make sure the existing edge points at a defined block. - if (!EI.Target->isDefined()) { - auto EdgeAddr = RecordAddress + PCBeginFieldOffset; - return make_error("FDE edge at " + - formatv("{0:x16}", EdgeAddr) + - " points at external block"); - } - PCBeginBlock = &EI.Target->getBlock(); - if (auto Err = RecordReader.skip( - getPointerEncodingDataSize(CIEInfo->FDEPointerEncoding))) - return Err; - } - - // Add a keep-alive edge from the FDE target to the FDE to ensure that the - // FDE is kept alive if its target is. - assert(PCBeginBlock && "PC-begin block not recorded"); - LLVM_DEBUG({ - dbgs() << " Adding keep-alive edge from target at " - << formatv("{0:x16}", PCBeginBlock->getAddress()) << " to FDE at " - << formatv("{0:x16}", RecordAddress) << "\n"; - }); - PCBeginBlock->addEdge(Edge::KeepAlive, 0, FDESymbol, 0); - } - - // Skip over the PC range size field. - if (auto Err = RecordReader.skip( - getPointerEncodingDataSize(CIEInfo->FDEPointerEncoding))) - return Err; - - if (CIEInfo->FDEsHaveLSDAField) { - uint64_t AugmentationDataSize; - if (auto Err = RecordReader.readULEB128(AugmentationDataSize)) - return Err; - - JITTargetAddress LSDAFieldOffset = RecordReader.getOffset(); - auto LSDAEdgeItr = BlockEdges.find(RecordOffset + LSDAFieldOffset); - if (LSDAEdgeItr == BlockEdges.end()) { - auto LSDAPointerInfo = - readEncodedPointer(CIEInfo->LSDAPointerEncoding, - RecordAddress + LSDAFieldOffset, RecordReader); - if (!LSDAPointerInfo) - return LSDAPointerInfo.takeError(); - JITTargetAddress LSDA = LSDAPointerInfo->first; - Edge::Kind LSDAEdgeKind = LSDAPointerInfo->second; - auto LSDASym = getOrCreateSymbol(PC, LSDA); - if (!LSDASym) - return LSDASym.takeError(); - LLVM_DEBUG({ - dbgs() << " Adding edge at " - << formatv("{0:x16}", RecordAddress + LSDAFieldOffset) - << " to LSDA at " << formatv("{0:x16}", LSDA) << "\n"; - }); - B.addEdge(LSDAEdgeKind, RecordOffset + LSDAFieldOffset, *LSDASym, 0); - } else { - LLVM_DEBUG({ - auto &EI = LSDAEdgeItr->second; - dbgs() << " Already has edge at " - << formatv("{0:x16}", RecordAddress + LSDAFieldOffset) - << " to LSDA at " << formatv("{0:x16}", EI.Target->getAddress()); - if (EI.Addend) - dbgs() << " + " << formatv("{0:x16}", EI.Addend); - dbgs() << "\n"; - }); - if (auto Err = RecordReader.skip(AugmentationDataSize)) - return Err; - } - } else { - LLVM_DEBUG(dbgs() << " Record does not have LSDA field.\n"); - } - - return Error::success(); -} - -Expected -EHFrameEdgeFixer::parseAugmentationString(BinaryStreamReader &RecordReader) { - AugmentationInfo AugInfo; - uint8_t NextChar; - uint8_t *NextField = &AugInfo.Fields[0]; - - if (auto Err = RecordReader.readInteger(NextChar)) - return std::move(Err); - - while (NextChar != 0) { - switch (NextChar) { - case 'z': - AugInfo.AugmentationDataPresent = true; - break; - case 'e': - if (auto Err = RecordReader.readInteger(NextChar)) - return std::move(Err); - if (NextChar != 'h') - return make_error("Unrecognized substring e" + - Twine(NextChar) + - " in augmentation string"); - AugInfo.EHDataFieldPresent = true; - break; - case 'L': - case 'P': - case 'R': - *NextField++ = NextChar; - break; - default: - return make_error("Unrecognized character " + - Twine(NextChar) + - " in augmentation string"); - } - - if (auto Err = RecordReader.readInteger(NextChar)) - return std::move(Err); - } - - return std::move(AugInfo); -} - -bool EHFrameEdgeFixer::isSupportedPointerEncoding(uint8_t PointerEncoding) { - using namespace dwarf; - - // We only support PC-rel for now. - if ((PointerEncoding & 0x70) != DW_EH_PE_pcrel) - return false; - - // readEncodedPointer does not handle indirect. - if (PointerEncoding & DW_EH_PE_indirect) - return false; - - // Supported datatypes. - switch (PointerEncoding & 0xf) { - case DW_EH_PE_absptr: - case DW_EH_PE_udata4: - case DW_EH_PE_udata8: - case DW_EH_PE_sdata4: - case DW_EH_PE_sdata8: - return true; - } - - return false; -} - -unsigned EHFrameEdgeFixer::getPointerEncodingDataSize(uint8_t PointerEncoding) { - using namespace dwarf; - - assert(isSupportedPointerEncoding(PointerEncoding) && - "Unsupported pointer encoding"); - switch (PointerEncoding & 0xf) { - case DW_EH_PE_absptr: - return PointerSize; - case DW_EH_PE_udata4: - case DW_EH_PE_sdata4: - return 4; - case DW_EH_PE_udata8: - case DW_EH_PE_sdata8: - return 8; - default: - llvm_unreachable("Unsupported encoding"); - } -} - -Expected> -EHFrameEdgeFixer::readEncodedPointer(uint8_t PointerEncoding, - JITTargetAddress PointerFieldAddress, - BinaryStreamReader &RecordReader) { - static_assert(sizeof(JITTargetAddress) == sizeof(uint64_t), - "Result must be able to hold a uint64_t"); - assert(isSupportedPointerEncoding(PointerEncoding) && - "Unsupported pointer encoding"); - - using namespace dwarf; - - // Isolate data type, remap absptr to udata4 or udata8. This relies on us - // having verified that the graph uses 32-bit or 64-bit pointers only at the - // start of this pass. - uint8_t EffectiveType = PointerEncoding & 0xf; - if (EffectiveType == DW_EH_PE_absptr) - EffectiveType = (PointerSize == 8) ? DW_EH_PE_udata8 : DW_EH_PE_udata4; - - JITTargetAddress Addr; - Edge::Kind PointerEdgeKind; - switch (EffectiveType) { - case DW_EH_PE_udata4: { - uint32_t Val; - if (auto Err = RecordReader.readInteger(Val)) - return std::move(Err); - Addr = PointerFieldAddress + Val; - PointerEdgeKind = Delta32; - break; - } - case DW_EH_PE_udata8: { - uint64_t Val; - if (auto Err = RecordReader.readInteger(Val)) - return std::move(Err); - Addr = PointerFieldAddress + Val; - PointerEdgeKind = Delta64; - break; - } - case DW_EH_PE_sdata4: { - int32_t Val; - if (auto Err = RecordReader.readInteger(Val)) - return std::move(Err); - Addr = PointerFieldAddress + Val; - PointerEdgeKind = Delta32; - break; - } - case DW_EH_PE_sdata8: { - int64_t Val; - if (auto Err = RecordReader.readInteger(Val)) - return std::move(Err); - Addr = PointerFieldAddress + Val; - PointerEdgeKind = Delta64; - break; - } - } - - if (PointerEdgeKind == Edge::Invalid) - return make_error( - "Unspported edge kind for encoded pointer at " + - formatv("{0:x}", PointerFieldAddress)); - - return std::make_pair(Addr, Delta64); -} - -Expected EHFrameEdgeFixer::getOrCreateSymbol(ParseContext &PC, - JITTargetAddress Addr) { - Symbol *CanonicalSym = nullptr; - - auto UpdateCanonicalSym = [&](Symbol *Sym) { - if (!CanonicalSym || Sym->getLinkage() < CanonicalSym->getLinkage() || - Sym->getScope() < CanonicalSym->getScope() || - (Sym->hasName() && !CanonicalSym->hasName()) || - Sym->getName() < CanonicalSym->getName()) - CanonicalSym = Sym; - }; - - if (auto *SymbolsAtAddr = PC.AddrToSyms.getSymbolsAt(Addr)) - for (auto *Sym : *SymbolsAtAddr) - UpdateCanonicalSym(Sym); - - // If we found an existing symbol at the given address then use it. - if (CanonicalSym) - return *CanonicalSym; - - // Otherwise search for a block covering the address and create a new symbol. - auto *B = PC.AddrToBlock.getBlockCovering(Addr); - if (!B) - return make_error("No symbol or block covering address " + - formatv("{0:x16}", Addr)); - - return PC.G.addAnonymousSymbol(*B, Addr - B->getAddress(), 0, false, false); -} - -char EHFrameNullTerminator::NullTerminatorBlockContent[4] = {0, 0, 0, 0}; - -EHFrameNullTerminator::EHFrameNullTerminator(StringRef EHFrameSectionName) - : EHFrameSectionName(EHFrameSectionName) {} - -Error EHFrameNullTerminator::operator()(LinkGraph &G) { - auto *EHFrame = G.findSectionByName(EHFrameSectionName); - - if (!EHFrame) - return Error::success(); - - LLVM_DEBUG({ - dbgs() << "EHFrameNullTerminator adding null terminator to " - << EHFrameSectionName << "\n"; - }); - - auto &NullTerminatorBlock = G.createContentBlock( - *EHFrame, NullTerminatorBlockContent, 0xfffffffffffffffc, 1, 0); - G.addAnonymousSymbol(NullTerminatorBlock, 0, 4, false, true); - return Error::success(); -} - -EHFrameRegistrar::~EHFrameRegistrar() {} - -Error InProcessEHFrameRegistrar::registerEHFrames( - JITTargetAddress EHFrameSectionAddr, size_t EHFrameSectionSize) { - return orc::registerEHFrameSection( - jitTargetAddressToPointer(EHFrameSectionAddr), - EHFrameSectionSize); -} - -Error InProcessEHFrameRegistrar::deregisterEHFrames( - JITTargetAddress EHFrameSectionAddr, size_t EHFrameSectionSize) { - return orc::deregisterEHFrameSection( - jitTargetAddressToPointer(EHFrameSectionAddr), - EHFrameSectionSize); -} - -LinkGraphPassFunction -createEHFrameRecorderPass(const Triple &TT, - StoreFrameRangeFunction StoreRangeAddress) { - const char *EHFrameSectionName = nullptr; - if (TT.getObjectFormat() == Triple::MachO) - EHFrameSectionName = "__TEXT,__eh_frame"; - else - EHFrameSectionName = ".eh_frame"; - - auto RecordEHFrame = - [EHFrameSectionName, - StoreFrameRange = std::move(StoreRangeAddress)](LinkGraph &G) -> Error { - // Search for a non-empty eh-frame and record the address of the first - // symbol in it. - JITTargetAddress Addr = 0; - size_t Size = 0; - if (auto *S = G.findSectionByName(EHFrameSectionName)) { - auto R = SectionRange(*S); - Addr = R.getStart(); - Size = R.getSize(); - } - if (Addr == 0 && Size != 0) - return make_error( - StringRef(EHFrameSectionName) + - " section can not have zero address with non-zero size"); - StoreFrameRange(Addr, Size); - return Error::success(); - }; - - return RecordEHFrame; -} - -} // end namespace jitlink -} // end namespace llvm diff --git a/interpreter/llvm/src/tools/clang/bindings/python/README.txt b/interpreter/llvm/src/tools/clang/bindings/python/README.txt deleted file mode 100644 index b0f0142a56f11..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/README.txt +++ /dev/null @@ -1,18 +0,0 @@ -//===----------------------------------------------------------------------===// -// Clang Python Bindings -//===----------------------------------------------------------------------===// - -This directory implements Python bindings for Clang. - -You may need to set CLANG_LIBRARY_PATH so that the Clang library can be -found. The unit tests are designed to be run with any standard test -runner. For example: --- -$ env PYTHONPATH=$(echo ~/llvm/tools/clang/bindings/python/) \ - CLANG_LIBRARY_PATH=$(llvm-config --libdir) \ - python -m unittest discover -v -tests.cindex.test_index.test_create ... ok -... - -OK --- diff --git a/interpreter/llvm/src/tools/clang/bindings/python/clang/__init__.py b/interpreter/llvm/src/tools/clang/bindings/python/clang/__init__.py deleted file mode 100644 index 14944b63e6dac..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/clang/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -#===- __init__.py - Clang Python Bindings --------------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -r""" -Clang Library Bindings -====================== - -This package provides access to the Clang compiler and libraries. - -The available modules are: - - cindex - - Bindings for the Clang indexing library. -""" - -__all__ = ['cindex'] - diff --git a/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py b/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py deleted file mode 100644 index aceaa131f1555..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py +++ /dev/null @@ -1,4220 +0,0 @@ -#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -r""" -Clang Indexing Library Bindings -=============================== - -This module provides an interface to the Clang indexing library. It is a -low-level interface to the indexing library which attempts to match the Clang -API directly while also being "pythonic". Notable differences from the C API -are: - - * string results are returned as Python strings, not CXString objects. - - * null cursors are translated to None. - - * access to child cursors is done via iteration, not visitation. - -The major indexing objects are: - - Index - - The top-level object which manages some global library state. - - TranslationUnit - - High-level object encapsulating the AST for a single translation unit. These - can be loaded from .ast files or parsed on the fly. - - Cursor - - Generic object for representing a node in the AST. - - SourceRange, SourceLocation, and File - - Objects representing information about the input source. - -Most object information is exposed using properties, when the underlying API -call is efficient. -""" -from __future__ import absolute_import, division, print_function - -# TODO -# ==== -# -# o API support for invalid translation units. Currently we can't even get the -# diagnostics on failure because they refer to locations in an object that -# will have been invalidated. -# -# o fix memory management issues (currently client must hold on to index and -# translation unit, or risk crashes). -# -# o expose code completion APIs. -# -# o cleanup ctypes wrapping, would be nice to separate the ctypes details more -# clearly, and hide from the external interface (i.e., help(cindex)). -# -# o implement additional SourceLocation, SourceRange, and File methods. - -from ctypes import * - -import clang.enumerations - -import os -import sys -if sys.version_info[0] == 3: - # Python 3 strings are unicode, translate them to/from utf8 for C-interop. - class c_interop_string(c_char_p): - - def __init__(self, p=None): - if p is None: - p = "" - if isinstance(p, str): - p = p.encode("utf8") - super(c_char_p, self).__init__(p) - - def __str__(self): - return self.value - - @property - def value(self): - if super(c_char_p, self).value is None: - return None - return super(c_char_p, self).value.decode("utf8") - - @classmethod - def from_param(cls, param): - if isinstance(param, str): - return cls(param) - if isinstance(param, bytes): - return cls(param) - if param is None: - # Support passing null to C functions expecting char arrays - return None - raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__)) - - @staticmethod - def to_python_string(x, *args): - return x.value - - def b(x): - if isinstance(x, bytes): - return x - return x.encode('utf8') - -elif sys.version_info[0] == 2: - # Python 2 strings are utf8 byte strings, no translation is needed for - # C-interop. - c_interop_string = c_char_p - - def _to_python_string(x, *args): - return x - - c_interop_string.to_python_string = staticmethod(_to_python_string) - - def b(x): - return x - -# Importing ABC-s directly from collections is deprecated since Python 3.7, -# will stop working in Python 3.8. -# See: https://docs.python.org/dev/whatsnew/3.7.html#id3 -if sys.version_info[:2] >= (3, 7): - from collections import abc as collections_abc -else: - import collections as collections_abc - -# We only support PathLike objects on Python version with os.fspath present -# to be consistent with the Python standard library. On older Python versions -# we only support strings and we have dummy fspath to just pass them through. -try: - fspath = os.fspath -except AttributeError: - def fspath(x): - return x - -# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper -# object. This is a problem, because it means that from_parameter will see an -# integer and pass the wrong value on platforms where int != void*. Work around -# this by marshalling object arguments as void**. -c_object_p = POINTER(c_void_p) - -callbacks = {} - -### Exception Classes ### - -class TranslationUnitLoadError(Exception): - """Represents an error that occurred when loading a TranslationUnit. - - This is raised in the case where a TranslationUnit could not be - instantiated due to failure in the libclang library. - - FIXME: Make libclang expose additional error information in this scenario. - """ - pass - -class TranslationUnitSaveError(Exception): - """Represents an error that occurred when saving a TranslationUnit. - - Each error has associated with it an enumerated value, accessible under - e.save_error. Consumers can compare the value with one of the ERROR_ - constants in this class. - """ - - # Indicates that an unknown error occurred. This typically indicates that - # I/O failed during save. - ERROR_UNKNOWN = 1 - - # Indicates that errors during translation prevented saving. The errors - # should be available via the TranslationUnit's diagnostics. - ERROR_TRANSLATION_ERRORS = 2 - - # Indicates that the translation unit was somehow invalid. - ERROR_INVALID_TU = 3 - - def __init__(self, enumeration, message): - assert isinstance(enumeration, int) - - if enumeration < 1 or enumeration > 3: - raise Exception("Encountered undefined TranslationUnit save error " - "constant: %d. Please file a bug to have this " - "value supported." % enumeration) - - self.save_error = enumeration - Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) - -### Structures and Utility Classes ### - -class CachedProperty(object): - """Decorator that lazy-loads the value of a property. - - The first time the property is accessed, the original property function is - executed. The value it returns is set as the new value of that instance's - property, replacing the original method. - """ - - def __init__(self, wrapped): - self.wrapped = wrapped - try: - self.__doc__ = wrapped.__doc__ - except: - pass - - def __get__(self, instance, instance_type=None): - if instance is None: - return self - - value = self.wrapped(instance) - setattr(instance, self.wrapped.__name__, value) - - return value - - -class _CXString(Structure): - """Helper for transforming CXString results.""" - - _fields_ = [("spelling", c_char_p), ("free", c_int)] - - def __del__(self): - conf.lib.clang_disposeString(self) - - @staticmethod - def from_result(res, fn=None, args=None): - assert isinstance(res, _CXString) - return conf.lib.clang_getCString(res) - - -class SourceLocation(Structure): - """ - A SourceLocation represents a particular location within a source file. - """ - _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] - _data = None - - def _get_instantiation(self): - if self._data is None: - f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() - conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l), - byref(c), byref(o)) - if f: - f = File(f) - else: - f = None - self._data = (f, int(l.value), int(c.value), int(o.value)) - return self._data - - @staticmethod - def from_position(tu, file, line, column): - """ - Retrieve the source location associated with a given file/line/column in - a particular translation unit. - """ - return conf.lib.clang_getLocation(tu, file, line, column) - - @staticmethod - def from_offset(tu, file, offset): - """Retrieve a SourceLocation from a given character offset. - - tu -- TranslationUnit file belongs to - file -- File instance to obtain offset from - offset -- Integer character offset within file - """ - return conf.lib.clang_getLocationForOffset(tu, file, offset) - - @property - def file(self): - """Get the file represented by this source location.""" - return self._get_instantiation()[0] - - @property - def line(self): - """Get the line represented by this source location.""" - return self._get_instantiation()[1] - - @property - def column(self): - """Get the column represented by this source location.""" - return self._get_instantiation()[2] - - @property - def offset(self): - """Get the file offset represented by this source location.""" - return self._get_instantiation()[3] - - def __eq__(self, other): - return conf.lib.clang_equalLocations(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def __repr__(self): - if self.file: - filename = self.file.name - else: - filename = None - return "" % ( - filename, self.line, self.column) - -class SourceRange(Structure): - """ - A SourceRange describes a range of source locations within the source - code. - """ - _fields_ = [ - ("ptr_data", c_void_p * 2), - ("begin_int_data", c_uint), - ("end_int_data", c_uint)] - - # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes - # object. - @staticmethod - def from_locations(start, end): - return conf.lib.clang_getRange(start, end) - - @property - def start(self): - """ - Return a SourceLocation representing the first character within a - source range. - """ - return conf.lib.clang_getRangeStart(self) - - @property - def end(self): - """ - Return a SourceLocation representing the last character within a - source range. - """ - return conf.lib.clang_getRangeEnd(self) - - def __eq__(self, other): - return conf.lib.clang_equalRanges(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def __contains__(self, other): - """Useful to detect the Token/Lexer bug""" - if not isinstance(other, SourceLocation): - return False - if other.file is None and self.start.file is None: - pass - elif ( self.start.file.name != other.file.name or - other.file.name != self.end.file.name): - # same file name - return False - # same file, in between lines - if self.start.line < other.line < self.end.line: - return True - elif self.start.line == other.line: - # same file first line - if self.start.column <= other.column: - return True - elif other.line == self.end.line: - # same file last line - if other.column <= self.end.column: - return True - return False - - def __repr__(self): - return "" % (self.start, self.end) - -class Diagnostic(object): - """ - A Diagnostic is a single instance of a Clang diagnostic. It includes the - diagnostic severity, the message, the location the diagnostic occurred, as - well as additional source ranges and associated fix-it hints. - """ - - Ignored = 0 - Note = 1 - Warning = 2 - Error = 3 - Fatal = 4 - - DisplaySourceLocation = 0x01 - DisplayColumn = 0x02 - DisplaySourceRanges = 0x04 - DisplayOption = 0x08 - DisplayCategoryId = 0x10 - DisplayCategoryName = 0x20 - _FormatOptionsMask = 0x3f - - def __init__(self, ptr): - self.ptr = ptr - - def __del__(self): - conf.lib.clang_disposeDiagnostic(self) - - @property - def severity(self): - return conf.lib.clang_getDiagnosticSeverity(self) - - @property - def location(self): - return conf.lib.clang_getDiagnosticLocation(self) - - @property - def spelling(self): - return conf.lib.clang_getDiagnosticSpelling(self) - - @property - def ranges(self): - class RangeIterator(object): - def __init__(self, diag): - self.diag = diag - - def __len__(self): - return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) - - def __getitem__(self, key): - if (key >= len(self)): - raise IndexError - return conf.lib.clang_getDiagnosticRange(self.diag, key) - - return RangeIterator(self) - - @property - def fixits(self): - class FixItIterator(object): - def __init__(self, diag): - self.diag = diag - - def __len__(self): - return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) - - def __getitem__(self, key): - range = SourceRange() - value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, - byref(range)) - if len(value) == 0: - raise IndexError - - return FixIt(range, value) - - return FixItIterator(self) - - @property - def children(self): - class ChildDiagnosticsIterator(object): - def __init__(self, diag): - self.diag_set = conf.lib.clang_getChildDiagnostics(diag) - - def __len__(self): - return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set)) - - def __getitem__(self, key): - diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key) - if not diag: - raise IndexError - return Diagnostic(diag) - - return ChildDiagnosticsIterator(self) - - @property - def category_number(self): - """The category number for this diagnostic or 0 if unavailable.""" - return conf.lib.clang_getDiagnosticCategory(self) - - @property - def category_name(self): - """The string name of the category for this diagnostic.""" - return conf.lib.clang_getDiagnosticCategoryText(self) - - @property - def option(self): - """The command-line option that enables this diagnostic.""" - return conf.lib.clang_getDiagnosticOption(self, None) - - @property - def disable_option(self): - """The command-line option that disables this diagnostic.""" - disable = _CXString() - conf.lib.clang_getDiagnosticOption(self, byref(disable)) - return _CXString.from_result(disable) - - def format(self, options=None): - """ - Format this diagnostic for display. The options argument takes - Diagnostic.Display* flags, which can be combined using bitwise OR. If - the options argument is not provided, the default display options will - be used. - """ - if options is None: - options = conf.lib.clang_defaultDiagnosticDisplayOptions() - if options & ~Diagnostic._FormatOptionsMask: - raise ValueError('Invalid format options') - return conf.lib.clang_formatDiagnostic(self, options) - - def __repr__(self): - return "" % ( - self.severity, self.location, self.spelling) - - def __str__(self): - return self.format() - - def from_param(self): - return self.ptr - -class FixIt(object): - """ - A FixIt represents a transformation to be applied to the source to - "fix-it". The fix-it shouldbe applied by replacing the given source range - with the given value. - """ - - def __init__(self, range, value): - self.range = range - self.value = value - - def __repr__(self): - return "" % (self.range, self.value) - -class TokenGroup(object): - """Helper class to facilitate token management. - - Tokens are allocated from libclang in chunks. They must be disposed of as a - collective group. - - One purpose of this class is for instances to represent groups of allocated - tokens. Each token in a group contains a reference back to an instance of - this class. When all tokens from a group are garbage collected, it allows - this class to be garbage collected. When this class is garbage collected, - it calls the libclang destructor which invalidates all tokens in the group. - - You should not instantiate this class outside of this module. - """ - def __init__(self, tu, memory, count): - self._tu = tu - self._memory = memory - self._count = count - - def __del__(self): - conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) - - @staticmethod - def get_tokens(tu, extent): - """Helper method to return all tokens in an extent. - - This functionality is needed multiple places in this module. We define - it here because it seems like a logical place. - """ - tokens_memory = POINTER(Token)() - tokens_count = c_uint() - - conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), - byref(tokens_count)) - - count = int(tokens_count.value) - - # If we get no tokens, no memory was allocated. Be sure not to return - # anything and potentially call a destructor on nothing. - if count < 1: - return - - tokens_array = cast(tokens_memory, POINTER(Token * count)).contents - - token_group = TokenGroup(tu, tokens_memory, tokens_count) - - for i in range(0, count): - token = Token() - token.int_data = tokens_array[i].int_data - token.ptr_data = tokens_array[i].ptr_data - token._tu = tu - token._group = token_group - - yield token - -class TokenKind(object): - """Describes a specific type of a Token.""" - - _value_map = {} # int -> TokenKind - - def __init__(self, value, name): - """Create a new TokenKind instance from a numeric value and a name.""" - self.value = value - self.name = name - - def __repr__(self): - return 'TokenKind.%s' % (self.name,) - - @staticmethod - def from_value(value): - """Obtain a registered TokenKind instance from its value.""" - result = TokenKind._value_map.get(value, None) - - if result is None: - raise ValueError('Unknown TokenKind: %d' % value) - - return result - - @staticmethod - def register(value, name): - """Register a new TokenKind enumeration. - - This should only be called at module load time by code within this - package. - """ - if value in TokenKind._value_map: - raise ValueError('TokenKind already registered: %d' % value) - - kind = TokenKind(value, name) - TokenKind._value_map[value] = kind - setattr(TokenKind, name, kind) - -### Cursor Kinds ### -class BaseEnumeration(object): - """ - Common base class for named enumerations held in sync with Index.h values. - - Subclasses must define their own _kinds and _name_map members, as: - _kinds = [] - _name_map = None - These values hold the per-subclass instances and value-to-name mappings, - respectively. - - """ - - def __init__(self, value): - if value >= len(self.__class__._kinds): - self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1) - if self.__class__._kinds[value] is not None: - raise ValueError('{0} value {1} already loaded'.format( - str(self.__class__), value)) - self.value = value - self.__class__._kinds[value] = self - self.__class__._name_map = None - - - def from_param(self): - return self.value - - @property - def name(self): - """Get the enumeration name of this cursor kind.""" - if self._name_map is None: - self._name_map = {} - for key, value in self.__class__.__dict__.items(): - if isinstance(value, self.__class__): - self._name_map[value] = key - return self._name_map[self] - - @classmethod - def from_id(cls, id): - if id >= len(cls._kinds) or cls._kinds[id] is None: - raise ValueError('Unknown template argument kind %d' % id) - return cls._kinds[id] - - def __repr__(self): - return '%s.%s' % (self.__class__, self.name,) - - -class CursorKind(BaseEnumeration): - """ - A CursorKind describes the kind of entity that a cursor points to. - """ - - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None - - @staticmethod - def get_all_kinds(): - """Return all CursorKind enumeration instances.""" - return [x for x in CursorKind._kinds if not x is None] - - def is_declaration(self): - """Test if this is a declaration kind.""" - return conf.lib.clang_isDeclaration(self) - - def is_reference(self): - """Test if this is a reference kind.""" - return conf.lib.clang_isReference(self) - - def is_expression(self): - """Test if this is an expression kind.""" - return conf.lib.clang_isExpression(self) - - def is_statement(self): - """Test if this is a statement kind.""" - return conf.lib.clang_isStatement(self) - - def is_attribute(self): - """Test if this is an attribute kind.""" - return conf.lib.clang_isAttribute(self) - - def is_invalid(self): - """Test if this is an invalid kind.""" - return conf.lib.clang_isInvalid(self) - - def is_translation_unit(self): - """Test if this is a translation unit kind.""" - return conf.lib.clang_isTranslationUnit(self) - - def is_preprocessing(self): - """Test if this is a preprocessing kind.""" - return conf.lib.clang_isPreprocessing(self) - - def is_unexposed(self): - """Test if this is an unexposed kind.""" - return conf.lib.clang_isUnexposed(self) - - def __repr__(self): - return 'CursorKind.%s' % (self.name,) - -### -# Declaration Kinds - -# A declaration whose specific kind is not exposed via this interface. -# -# Unexposed declarations have the same operations as any other kind of -# declaration; one can extract their location information, spelling, find their -# definitions, etc. However, the specific kind of the declaration is not -# reported. -CursorKind.UNEXPOSED_DECL = CursorKind(1) - -# A C or C++ struct. -CursorKind.STRUCT_DECL = CursorKind(2) - -# A C or C++ union. -CursorKind.UNION_DECL = CursorKind(3) - -# A C++ class. -CursorKind.CLASS_DECL = CursorKind(4) - -# An enumeration. -CursorKind.ENUM_DECL = CursorKind(5) - -# A field (in C) or non-static data member (in C++) in a struct, union, or C++ -# class. -CursorKind.FIELD_DECL = CursorKind(6) - -# An enumerator constant. -CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) - -# A function. -CursorKind.FUNCTION_DECL = CursorKind(8) - -# A variable. -CursorKind.VAR_DECL = CursorKind(9) - -# A function or method parameter. -CursorKind.PARM_DECL = CursorKind(10) - -# An Objective-C @interface. -CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) - -# An Objective-C @interface for a category. -CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) - -# An Objective-C @protocol declaration. -CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) - -# An Objective-C @property declaration. -CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) - -# An Objective-C instance variable. -CursorKind.OBJC_IVAR_DECL = CursorKind(15) - -# An Objective-C instance method. -CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) - -# An Objective-C class method. -CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) - -# An Objective-C @implementation. -CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) - -# An Objective-C @implementation for a category. -CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) - -# A typedef. -CursorKind.TYPEDEF_DECL = CursorKind(20) - -# A C++ class method. -CursorKind.CXX_METHOD = CursorKind(21) - -# A C++ namespace. -CursorKind.NAMESPACE = CursorKind(22) - -# A linkage specification, e.g. 'extern "C"'. -CursorKind.LINKAGE_SPEC = CursorKind(23) - -# A C++ constructor. -CursorKind.CONSTRUCTOR = CursorKind(24) - -# A C++ destructor. -CursorKind.DESTRUCTOR = CursorKind(25) - -# A C++ conversion function. -CursorKind.CONVERSION_FUNCTION = CursorKind(26) - -# A C++ template type parameter -CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) - -# A C++ non-type template parameter. -CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) - -# A C++ template template parameter. -CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29) - -# A C++ function template. -CursorKind.FUNCTION_TEMPLATE = CursorKind(30) - -# A C++ class template. -CursorKind.CLASS_TEMPLATE = CursorKind(31) - -# A C++ class template partial specialization. -CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) - -# A C++ namespace alias declaration. -CursorKind.NAMESPACE_ALIAS = CursorKind(33) - -# A C++ using directive -CursorKind.USING_DIRECTIVE = CursorKind(34) - -# A C++ using declaration -CursorKind.USING_DECLARATION = CursorKind(35) - -# A Type alias decl. -CursorKind.TYPE_ALIAS_DECL = CursorKind(36) - -# A Objective-C synthesize decl -CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) - -# A Objective-C dynamic decl -CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) - -# A C++ access specifier decl. -CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) - - -### -# Reference Kinds - -CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) -CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) -CursorKind.OBJC_CLASS_REF = CursorKind(42) - -# A reference to a type declaration. -# -# A type reference occurs anywhere where a type is named but not -# declared. For example, given: -# typedef unsigned size_type; -# size_type size; -# -# The typedef is a declaration of size_type (CXCursor_TypedefDecl), -# while the type of the variable "size" is referenced. The cursor -# referenced by the type of size is the typedef for size_type. -CursorKind.TYPE_REF = CursorKind(43) -CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) - -# A reference to a class template, function template, template -# template parameter, or class template partial specialization. -CursorKind.TEMPLATE_REF = CursorKind(45) - -# A reference to a namespace or namepsace alias. -CursorKind.NAMESPACE_REF = CursorKind(46) - -# A reference to a member of a struct, union, or class that occurs in -# some non-expression context, e.g., a designated initializer. -CursorKind.MEMBER_REF = CursorKind(47) - -# A reference to a labeled statement. -CursorKind.LABEL_REF = CursorKind(48) - -# A reference to a set of overloaded functions or function templates -# that has not yet been resolved to a specific function or function template. -CursorKind.OVERLOADED_DECL_REF = CursorKind(49) - -# A reference to a variable that occurs in some non-expression -# context, e.g., a C++ lambda capture list. -CursorKind.VARIABLE_REF = CursorKind(50) - -### -# Invalid/Error Kinds - -CursorKind.INVALID_FILE = CursorKind(70) -CursorKind.NO_DECL_FOUND = CursorKind(71) -CursorKind.NOT_IMPLEMENTED = CursorKind(72) -CursorKind.INVALID_CODE = CursorKind(73) - -### -# Expression Kinds - -# An expression whose specific kind is not exposed via this interface. -# -# Unexposed expressions have the same operations as any other kind of -# expression; one can extract their location information, spelling, children, -# etc. However, the specific kind of the expression is not reported. -CursorKind.UNEXPOSED_EXPR = CursorKind(100) - -# An expression that refers to some value declaration, such as a function, -# variable, or enumerator. -CursorKind.DECL_REF_EXPR = CursorKind(101) - -# An expression that refers to a member of a struct, union, class, Objective-C -# class, etc. -CursorKind.MEMBER_REF_EXPR = CursorKind(102) - -# An expression that calls a function. -CursorKind.CALL_EXPR = CursorKind(103) - -# An expression that sends a message to an Objective-C object or class. -CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) - -# An expression that represents a block literal. -CursorKind.BLOCK_EXPR = CursorKind(105) - -# An integer literal. -CursorKind.INTEGER_LITERAL = CursorKind(106) - -# A floating point number literal. -CursorKind.FLOATING_LITERAL = CursorKind(107) - -# An imaginary number literal. -CursorKind.IMAGINARY_LITERAL = CursorKind(108) - -# A string literal. -CursorKind.STRING_LITERAL = CursorKind(109) - -# A character literal. -CursorKind.CHARACTER_LITERAL = CursorKind(110) - -# A parenthesized expression, e.g. "(1)". -# -# This AST node is only formed if full location information is requested. -CursorKind.PAREN_EXPR = CursorKind(111) - -# This represents the unary-expression's (except sizeof and -# alignof). -CursorKind.UNARY_OPERATOR = CursorKind(112) - -# [C99 6.5.2.1] Array Subscripting. -CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) - -# A builtin binary operation expression such as "x + y" or -# "x <= y". -CursorKind.BINARY_OPERATOR = CursorKind(114) - -# Compound assignment such as "+=". -CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) - -# The ?: ternary operator. -CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) - -# An explicit cast in C (C99 6.5.4) or a C-style cast in C++ -# (C++ [expr.cast]), which uses the syntax (Type)expr. -# -# For example: (int)f. -CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) - -# [C99 6.5.2.5] -CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) - -# Describes an C or C++ initializer list. -CursorKind.INIT_LIST_EXPR = CursorKind(119) - -# The GNU address of label extension, representing &&label. -CursorKind.ADDR_LABEL_EXPR = CursorKind(120) - -# This is the GNU Statement Expression extension: ({int X=4; X;}) -CursorKind.StmtExpr = CursorKind(121) - -# Represents a C11 generic selection. -CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) - -# Implements the GNU __null extension, which is a name for a null -# pointer constant that has integral type (e.g., int or long) and is the same -# size and alignment as a pointer. -# -# The __null extension is typically only used by system headers, which define -# NULL as __null in C++ rather than using 0 (which is an integer that may not -# match the size of a pointer). -CursorKind.GNU_NULL_EXPR = CursorKind(123) - -# C++'s static_cast<> expression. -CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) - -# C++'s dynamic_cast<> expression. -CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) - -# C++'s reinterpret_cast<> expression. -CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) - -# C++'s const_cast<> expression. -CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) - -# Represents an explicit C++ type conversion that uses "functional" -# notion (C++ [expr.type.conv]). -# -# Example: -# \code -# x = int(0.5); -# \endcode -CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) - -# A C++ typeid expression (C++ [expr.typeid]). -CursorKind.CXX_TYPEID_EXPR = CursorKind(129) - -# [C++ 2.13.5] C++ Boolean Literal. -CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) - -# [C++0x 2.14.7] C++ Pointer Literal. -CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) - -# Represents the "this" expression in C++ -CursorKind.CXX_THIS_EXPR = CursorKind(132) - -# [C++ 15] C++ Throw Expression. -# -# This handles 'throw' and 'throw' assignment-expression. When -# assignment-expression isn't present, Op will be null. -CursorKind.CXX_THROW_EXPR = CursorKind(133) - -# A new expression for memory allocation and constructor calls, e.g: -# "new CXXNewExpr(foo)". -CursorKind.CXX_NEW_EXPR = CursorKind(134) - -# A delete expression for memory deallocation and destructor calls, -# e.g. "delete[] pArray". -CursorKind.CXX_DELETE_EXPR = CursorKind(135) - -# Represents a unary expression. -CursorKind.CXX_UNARY_EXPR = CursorKind(136) - -# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". -CursorKind.OBJC_STRING_LITERAL = CursorKind(137) - -# ObjCEncodeExpr, used for in Objective-C. -CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) - -# ObjCSelectorExpr used for in Objective-C. -CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) - -# Objective-C's protocol expression. -CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) - -# An Objective-C "bridged" cast expression, which casts between -# Objective-C pointers and C pointers, transferring ownership in the process. -# -# \code -# NSString *str = (__bridge_transfer NSString *)CFCreateString(); -# \endcode -CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) - -# Represents a C++0x pack expansion that produces a sequence of -# expressions. -# -# A pack expansion expression contains a pattern (which itself is an -# expression) followed by an ellipsis. For example: -CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) - -# Represents an expression that computes the length of a parameter -# pack. -CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) - -# Represents a C++ lambda expression that produces a local function -# object. -# -# \code -# void abssort(float *x, unsigned N) { -# std::sort(x, x + N, -# [](float a, float b) { -# return std::abs(a) < std::abs(b); -# }); -# } -# \endcode -CursorKind.LAMBDA_EXPR = CursorKind(144) - -# Objective-c Boolean Literal. -CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145) - -# Represents the "self" expression in a ObjC method. -CursorKind.OBJ_SELF_EXPR = CursorKind(146) - -# OpenMP 4.0 [2.4, Array Section]. -CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) - -# Represents an @available(...) check. -CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148) - - -# A statement whose specific kind is not exposed via this interface. -# -# Unexposed statements have the same operations as any other kind of statement; -# one can extract their location information, spelling, children, etc. However, -# the specific kind of the statement is not reported. -CursorKind.UNEXPOSED_STMT = CursorKind(200) - -# A labelled statement in a function. -CursorKind.LABEL_STMT = CursorKind(201) - -# A compound statement -CursorKind.COMPOUND_STMT = CursorKind(202) - -# A case statement. -CursorKind.CASE_STMT = CursorKind(203) - -# A default statement. -CursorKind.DEFAULT_STMT = CursorKind(204) - -# An if statement. -CursorKind.IF_STMT = CursorKind(205) - -# A switch statement. -CursorKind.SWITCH_STMT = CursorKind(206) - -# A while statement. -CursorKind.WHILE_STMT = CursorKind(207) - -# A do statement. -CursorKind.DO_STMT = CursorKind(208) - -# A for statement. -CursorKind.FOR_STMT = CursorKind(209) - -# A goto statement. -CursorKind.GOTO_STMT = CursorKind(210) - -# An indirect goto statement. -CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) - -# A continue statement. -CursorKind.CONTINUE_STMT = CursorKind(212) - -# A break statement. -CursorKind.BREAK_STMT = CursorKind(213) - -# A return statement. -CursorKind.RETURN_STMT = CursorKind(214) - -# A GNU-style inline assembler statement. -CursorKind.ASM_STMT = CursorKind(215) - -# Objective-C's overall @try-@catch-@finally statement. -CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) - -# Objective-C's @catch statement. -CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) - -# Objective-C's @finally statement. -CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) - -# Objective-C's @throw statement. -CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) - -# Objective-C's @synchronized statement. -CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) - -# Objective-C's autorealease pool statement. -CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) - -# Objective-C's for collection statement. -CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) - -# C++'s catch statement. -CursorKind.CXX_CATCH_STMT = CursorKind(223) - -# C++'s try statement. -CursorKind.CXX_TRY_STMT = CursorKind(224) - -# C++'s for (* : *) statement. -CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) - -# Windows Structured Exception Handling's try statement. -CursorKind.SEH_TRY_STMT = CursorKind(226) - -# Windows Structured Exception Handling's except statement. -CursorKind.SEH_EXCEPT_STMT = CursorKind(227) - -# Windows Structured Exception Handling's finally statement. -CursorKind.SEH_FINALLY_STMT = CursorKind(228) - -# A MS inline assembly statement extension. -CursorKind.MS_ASM_STMT = CursorKind(229) - -# The null statement. -CursorKind.NULL_STMT = CursorKind(230) - -# Adaptor class for mixing declarations with statements and expressions. -CursorKind.DECL_STMT = CursorKind(231) - -# OpenMP parallel directive. -CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232) - -# OpenMP SIMD directive. -CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233) - -# OpenMP for directive. -CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234) - -# OpenMP sections directive. -CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235) - -# OpenMP section directive. -CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236) - -# OpenMP single directive. -CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237) - -# OpenMP parallel for directive. -CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238) - -# OpenMP parallel sections directive. -CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239) - -# OpenMP task directive. -CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240) - -# OpenMP master directive. -CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241) - -# OpenMP critical directive. -CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242) - -# OpenMP taskyield directive. -CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243) - -# OpenMP barrier directive. -CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244) - -# OpenMP taskwait directive. -CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245) - -# OpenMP flush directive. -CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246) - -# Windows Structured Exception Handling's leave statement. -CursorKind.SEH_LEAVE_STMT = CursorKind(247) - -# OpenMP ordered directive. -CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248) - -# OpenMP atomic directive. -CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249) - -# OpenMP for SIMD directive. -CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250) - -# OpenMP parallel for SIMD directive. -CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251) - -# OpenMP target directive. -CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252) - -# OpenMP teams directive. -CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253) - -# OpenMP taskgroup directive. -CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254) - -# OpenMP cancellation point directive. -CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255) - -# OpenMP cancel directive. -CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256) - -# OpenMP target data directive. -CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257) - -# OpenMP taskloop directive. -CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258) - -# OpenMP taskloop simd directive. -CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259) - -# OpenMP distribute directive. -CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260) - -# OpenMP target enter data directive. -CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261) - -# OpenMP target exit data directive. -CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262) - -# OpenMP target parallel directive. -CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263) - -# OpenMP target parallel for directive. -CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264) - -# OpenMP target update directive. -CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265) - -# OpenMP distribute parallel for directive. -CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266) - -# OpenMP distribute parallel for simd directive. -CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267) - -# OpenMP distribute simd directive. -CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268) - -# OpenMP target parallel for simd directive. -CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269) - -# OpenMP target simd directive. -CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270) - -# OpenMP teams distribute directive. -CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271) - -### -# Other Kinds - -# Cursor that represents the translation unit itself. -# -# The translation unit cursor exists primarily to act as the root cursor for -# traversing the contents of a translation unit. -CursorKind.TRANSLATION_UNIT = CursorKind(300) - -### -# Attributes - -# An attribute whoe specific kind is note exposed via this interface -CursorKind.UNEXPOSED_ATTR = CursorKind(400) - -CursorKind.IB_ACTION_ATTR = CursorKind(401) -CursorKind.IB_OUTLET_ATTR = CursorKind(402) -CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) - -CursorKind.CXX_FINAL_ATTR = CursorKind(404) -CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) -CursorKind.ANNOTATE_ATTR = CursorKind(406) -CursorKind.ASM_LABEL_ATTR = CursorKind(407) -CursorKind.PACKED_ATTR = CursorKind(408) -CursorKind.PURE_ATTR = CursorKind(409) -CursorKind.CONST_ATTR = CursorKind(410) -CursorKind.NODUPLICATE_ATTR = CursorKind(411) -CursorKind.CUDACONSTANT_ATTR = CursorKind(412) -CursorKind.CUDADEVICE_ATTR = CursorKind(413) -CursorKind.CUDAGLOBAL_ATTR = CursorKind(414) -CursorKind.CUDAHOST_ATTR = CursorKind(415) -CursorKind.CUDASHARED_ATTR = CursorKind(416) - -CursorKind.VISIBILITY_ATTR = CursorKind(417) - -CursorKind.DLLEXPORT_ATTR = CursorKind(418) -CursorKind.DLLIMPORT_ATTR = CursorKind(419) -CursorKind.CONVERGENT_ATTR = CursorKind(438) -CursorKind.WARN_UNUSED_ATTR = CursorKind(439) -CursorKind.WARN_UNUSED_RESULT_ATTR = CursorKind(440) -CursorKind.ALIGNED_ATTR = CursorKind(441) - -### -# Preprocessing -CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) -CursorKind.MACRO_DEFINITION = CursorKind(501) -CursorKind.MACRO_INSTANTIATION = CursorKind(502) -CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) - -### -# Extra declaration - -# A module import declaration. -CursorKind.MODULE_IMPORT_DECL = CursorKind(600) -# A type alias template declaration -CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601) -# A static_assert or _Static_assert node -CursorKind.STATIC_ASSERT = CursorKind(602) -# A friend declaration -CursorKind.FRIEND_DECL = CursorKind(603) - -# A code completion overload candidate. -CursorKind.OVERLOAD_CANDIDATE = CursorKind(700) - -### Template Argument Kinds ### -class TemplateArgumentKind(BaseEnumeration): - """ - A TemplateArgumentKind describes the kind of entity that a template argument - represents. - """ - - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None - -TemplateArgumentKind.NULL = TemplateArgumentKind(0) -TemplateArgumentKind.TYPE = TemplateArgumentKind(1) -TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2) -TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3) -TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4) - -### Exception Specification Kinds ### -class ExceptionSpecificationKind(BaseEnumeration): - """ - An ExceptionSpecificationKind describes the kind of exception specification - that a function has. - """ - - # The required BaseEnumeration declarations. - _kinds = [] - _name_map = None - - def __repr__(self): - return 'ExceptionSpecificationKind.{}'.format(self.name) - -ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0) -ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1) -ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2) -ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3) -ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4) -ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5) -ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6) -ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7) -ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8) - -### Cursors ### - -class Cursor(Structure): - """ - The Cursor class represents a reference to an element within the AST. It - acts as a kind of iterator. - """ - _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] - - @staticmethod - def from_location(tu, location): - # We store a reference to the TU in the instance so the TU won't get - # collected before the cursor. - cursor = conf.lib.clang_getCursor(tu, location) - cursor._tu = tu - - return cursor - - def __eq__(self, other): - return conf.lib.clang_equalCursors(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - - def is_definition(self): - """ - Returns true if the declaration pointed at by the cursor is also a - definition of that entity. - """ - return conf.lib.clang_isCursorDefinition(self) - - def is_const_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'const'. - """ - return conf.lib.clang_CXXMethod_isConst(self) - - def is_converting_constructor(self): - """Returns True if the cursor refers to a C++ converting constructor. - """ - return conf.lib.clang_CXXConstructor_isConvertingConstructor(self) - - def is_copy_constructor(self): - """Returns True if the cursor refers to a C++ copy constructor. - """ - return conf.lib.clang_CXXConstructor_isCopyConstructor(self) - - def is_default_constructor(self): - """Returns True if the cursor refers to a C++ default constructor. - """ - return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) - - def is_move_constructor(self): - """Returns True if the cursor refers to a C++ move constructor. - """ - return conf.lib.clang_CXXConstructor_isMoveConstructor(self) - - def is_default_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared '= default'. - """ - return conf.lib.clang_CXXMethod_isDefaulted(self) - - def is_mutable_field(self): - """Returns True if the cursor refers to a C++ field that is declared - 'mutable'. - """ - return conf.lib.clang_CXXField_isMutable(self) - - def is_pure_virtual_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared pure virtual. - """ - return conf.lib.clang_CXXMethod_isPureVirtual(self) - - def is_static_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'static'. - """ - return conf.lib.clang_CXXMethod_isStatic(self) - - def is_virtual_method(self): - """Returns True if the cursor refers to a C++ member function or member - function template that is declared 'virtual'. - """ - return conf.lib.clang_CXXMethod_isVirtual(self) - - def is_abstract_record(self): - """Returns True if the cursor refers to a C++ record declaration - that has pure virtual member functions. - """ - return conf.lib.clang_CXXRecord_isAbstract(self) - - def is_scoped_enum(self): - """Returns True if the cursor refers to a scoped enum declaration. - """ - return conf.lib.clang_EnumDecl_isScoped(self) - - def get_definition(self): - """ - If the cursor is a reference to a declaration or a declaration of - some entity, return a cursor that points to the definition of that - entity. - """ - # TODO: Should probably check that this is either a reference or - # declaration prior to issuing the lookup. - return conf.lib.clang_getCursorDefinition(self) - - def get_usr(self): - """Return the Unified Symbol Resolution (USR) for the entity referenced - by the given cursor (or None). - - A Unified Symbol Resolution (USR) is a string that identifies a - particular entity (function, class, variable, etc.) within a - program. USRs can be compared across translation units to determine, - e.g., when references in one translation refer to an entity defined in - another translation unit.""" - return conf.lib.clang_getCursorUSR(self) - - def get_included_file(self): - """Returns the File that is included by the current inclusion cursor.""" - assert self.kind == CursorKind.INCLUSION_DIRECTIVE - - return conf.lib.clang_getIncludedFile(self) - - @property - def kind(self): - """Return the kind of this cursor.""" - return CursorKind.from_id(self._kind_id) - - @property - def spelling(self): - """Return the spelling of the entity pointed at by the cursor.""" - if not hasattr(self, '_spelling'): - self._spelling = conf.lib.clang_getCursorSpelling(self) - - return self._spelling - - @property - def displayname(self): - """ - Return the display name for the entity referenced by this cursor. - - The display name contains extra information that helps identify the - cursor, such as the parameters of a function or template or the - arguments of a class template specialization. - """ - if not hasattr(self, '_displayname'): - self._displayname = conf.lib.clang_getCursorDisplayName(self) - - return self._displayname - - @property - def mangled_name(self): - """Return the mangled name for the entity referenced by this cursor.""" - if not hasattr(self, '_mangled_name'): - self._mangled_name = conf.lib.clang_Cursor_getMangling(self) - - return self._mangled_name - - @property - def location(self): - """ - Return the source location (the starting character) of the entity - pointed at by the cursor. - """ - if not hasattr(self, '_loc'): - self._loc = conf.lib.clang_getCursorLocation(self) - - return self._loc - - @property - def linkage(self): - """Return the linkage of this cursor.""" - if not hasattr(self, '_linkage'): - self._linkage = conf.lib.clang_getCursorLinkage(self) - - return LinkageKind.from_id(self._linkage) - - @property - def tls_kind(self): - """Return the thread-local storage (TLS) kind of this cursor.""" - if not hasattr(self, '_tls_kind'): - self._tls_kind = conf.lib.clang_getCursorTLSKind(self) - - return TLSKind.from_id(self._tls_kind) - - @property - def extent(self): - """ - Return the source range (the range of text) occupied by the entity - pointed at by the cursor. - """ - if not hasattr(self, '_extent'): - self._extent = conf.lib.clang_getCursorExtent(self) - - return self._extent - - @property - def storage_class(self): - """ - Retrieves the storage class (if any) of the entity pointed at by the - cursor. - """ - if not hasattr(self, '_storage_class'): - self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) - - return StorageClass.from_id(self._storage_class) - - @property - def availability(self): - """ - Retrieves the availability of the entity pointed at by the cursor. - """ - if not hasattr(self, '_availability'): - self._availability = conf.lib.clang_getCursorAvailability(self) - - return AvailabilityKind.from_id(self._availability) - - @property - def access_specifier(self): - """ - Retrieves the access specifier (if any) of the entity pointed at by the - cursor. - """ - if not hasattr(self, '_access_specifier'): - self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) - - return AccessSpecifier.from_id(self._access_specifier) - - @property - def type(self): - """ - Retrieve the Type (if any) of the entity pointed at by the cursor. - """ - if not hasattr(self, '_type'): - self._type = conf.lib.clang_getCursorType(self) - - return self._type - - @property - def canonical(self): - """Return the canonical Cursor corresponding to this Cursor. - - The canonical cursor is the cursor which is representative for the - underlying entity. For example, if you have multiple forward - declarations for the same class, the canonical cursor for the forward - declarations will be identical. - """ - if not hasattr(self, '_canonical'): - self._canonical = conf.lib.clang_getCanonicalCursor(self) - - return self._canonical - - @property - def result_type(self): - """Retrieve the Type of the result for this Cursor.""" - if not hasattr(self, '_result_type'): - self._result_type = conf.lib.clang_getCursorResultType(self) - - return self._result_type - - @property - def exception_specification_kind(self): - ''' - Retrieve the exception specification kind, which is one of the values - from the ExceptionSpecificationKind enumeration. - ''' - if not hasattr(self, '_exception_specification_kind'): - exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self) - self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind) - - return self._exception_specification_kind - - @property - def underlying_typedef_type(self): - """Return the underlying type of a typedef declaration. - - Returns a Type for the typedef this cursor is a declaration for. If - the current cursor is not a typedef, this raises. - """ - if not hasattr(self, '_underlying_type'): - assert self.kind.is_declaration() - self._underlying_type = \ - conf.lib.clang_getTypedefDeclUnderlyingType(self) - - return self._underlying_type - - @property - def enum_type(self): - """Return the integer type of an enum declaration. - - Returns a Type corresponding to an integer. If the cursor is not for an - enum, this raises. - """ - if not hasattr(self, '_enum_type'): - assert self.kind == CursorKind.ENUM_DECL - self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) - - return self._enum_type - - @property - def enum_value(self): - """Return the value of an enum constant.""" - if not hasattr(self, '_enum_value'): - assert self.kind == CursorKind.ENUM_CONSTANT_DECL - # Figure out the underlying type of the enum to know if it - # is a signed or unsigned quantity. - underlying_type = self.type - if underlying_type.kind == TypeKind.ENUM: - underlying_type = underlying_type.get_declaration().enum_type - if underlying_type.kind in (TypeKind.CHAR_U, - TypeKind.UCHAR, - TypeKind.CHAR16, - TypeKind.CHAR32, - TypeKind.USHORT, - TypeKind.UINT, - TypeKind.ULONG, - TypeKind.ULONGLONG, - TypeKind.UINT128): - self._enum_value = \ - conf.lib.clang_getEnumConstantDeclUnsignedValue(self) - else: - self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) - return self._enum_value - - @property - def objc_type_encoding(self): - """Return the Objective-C type encoding as a str.""" - if not hasattr(self, '_objc_type_encoding'): - self._objc_type_encoding = \ - conf.lib.clang_getDeclObjCTypeEncoding(self) - - return self._objc_type_encoding - - @property - def hash(self): - """Returns a hash of the cursor as an int.""" - if not hasattr(self, '_hash'): - self._hash = conf.lib.clang_hashCursor(self) - - return self._hash - - @property - def semantic_parent(self): - """Return the semantic parent for this cursor.""" - if not hasattr(self, '_semantic_parent'): - self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) - - return self._semantic_parent - - @property - def lexical_parent(self): - """Return the lexical parent for this cursor.""" - if not hasattr(self, '_lexical_parent'): - self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) - - return self._lexical_parent - - @property - def translation_unit(self): - """Returns the TranslationUnit to which this Cursor belongs.""" - # If this triggers an AttributeError, the instance was not properly - # created. - return self._tu - - @property - def referenced(self): - """ - For a cursor that is a reference, returns a cursor - representing the entity that it references. - """ - if not hasattr(self, '_referenced'): - self._referenced = conf.lib.clang_getCursorReferenced(self) - - return self._referenced - - @property - def brief_comment(self): - """Returns the brief comment text associated with that Cursor""" - return conf.lib.clang_Cursor_getBriefCommentText(self) - - @property - def raw_comment(self): - """Returns the raw comment text associated with that Cursor""" - return conf.lib.clang_Cursor_getRawCommentText(self) - - def get_arguments(self): - """Return an iterator for accessing the arguments of this cursor.""" - num_args = conf.lib.clang_Cursor_getNumArguments(self) - for i in range(0, num_args): - yield conf.lib.clang_Cursor_getArgument(self, i) - - def get_num_template_arguments(self): - """Returns the number of template args associated with this cursor.""" - return conf.lib.clang_Cursor_getNumTemplateArguments(self) - - def get_template_argument_kind(self, num): - """Returns the TemplateArgumentKind for the indicated template - argument.""" - return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) - - def get_template_argument_type(self, num): - """Returns the CXType for the indicated template argument.""" - return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) - - def get_template_argument_value(self, num): - """Returns the value of the indicated arg as a signed 64b integer.""" - return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) - - def get_template_argument_unsigned_value(self, num): - """Returns the value of the indicated arg as an unsigned 64b integer.""" - return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num) - - def get_children(self): - """Return an iterator for accessing the children of this cursor.""" - - # FIXME: Expose iteration from CIndex, PR6125. - def visitor(child, parent, children): - # FIXME: Document this assertion in API. - # FIXME: There should just be an isNull method. - assert child != conf.lib.clang_getNullCursor() - - # Create reference to TU so it isn't GC'd before Cursor. - child._tu = self._tu - children.append(child) - return 1 # continue - children = [] - conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), - children) - return iter(children) - - def walk_preorder(self): - """Depth-first preorder walk over the cursor and its descendants. - - Yields cursors. - """ - yield self - for child in self.get_children(): - for descendant in child.walk_preorder(): - yield descendant - - def get_tokens(self): - """Obtain Token instances formulating that compose this Cursor. - - This is a generator for Token instances. It returns all tokens which - occupy the extent this cursor occupies. - """ - return TokenGroup.get_tokens(self._tu, self.extent) - - def get_field_offsetof(self): - """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" - return conf.lib.clang_Cursor_getOffsetOfField(self) - - def is_anonymous(self): - """ - Check if the record is anonymous. - """ - if self.kind == CursorKind.FIELD_DECL: - return self.type.get_declaration().is_anonymous() - return conf.lib.clang_Cursor_isAnonymous(self) - - def is_bitfield(self): - """ - Check if the field is a bitfield. - """ - return conf.lib.clang_Cursor_isBitField(self) - - def get_bitfield_width(self): - """ - Retrieve the width of a bitfield. - """ - return conf.lib.clang_getFieldDeclBitWidth(self) - - @staticmethod - def from_result(res, fn, args): - assert isinstance(res, Cursor) - # FIXME: There should just be an isNull method. - if res == conf.lib.clang_getNullCursor(): - return None - - # Store a reference to the TU in the Python object so it won't get GC'd - # before the Cursor. - tu = None - for arg in args: - if isinstance(arg, TranslationUnit): - tu = arg - break - - if hasattr(arg, 'translation_unit'): - tu = arg.translation_unit - break - - assert tu is not None - - res._tu = tu - return res - - @staticmethod - def from_cursor_result(res, fn, args): - assert isinstance(res, Cursor) - if res == conf.lib.clang_getNullCursor(): - return None - - res._tu = args[0]._tu - return res - -class StorageClass(object): - """ - Describes the storage class of a declaration - """ - - # The unique kind objects, index by id. - _kinds = [] - _name_map = None - - def __init__(self, value): - if value >= len(StorageClass._kinds): - StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1) - if StorageClass._kinds[value] is not None: - raise ValueError('StorageClass already loaded') - self.value = value - StorageClass._kinds[value] = self - StorageClass._name_map = None - - def from_param(self): - return self.value - - @property - def name(self): - """Get the enumeration name of this storage class.""" - if self._name_map is None: - self._name_map = {} - for key,value in StorageClass.__dict__.items(): - if isinstance(value,StorageClass): - self._name_map[value] = key - return self._name_map[self] - - @staticmethod - def from_id(id): - if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]: - raise ValueError('Unknown storage class %d' % id) - return StorageClass._kinds[id] - - def __repr__(self): - return 'StorageClass.%s' % (self.name,) - -StorageClass.INVALID = StorageClass(0) -StorageClass.NONE = StorageClass(1) -StorageClass.EXTERN = StorageClass(2) -StorageClass.STATIC = StorageClass(3) -StorageClass.PRIVATEEXTERN = StorageClass(4) -StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5) -StorageClass.AUTO = StorageClass(6) -StorageClass.REGISTER = StorageClass(7) - -### Availability Kinds ### - -class AvailabilityKind(BaseEnumeration): - """ - Describes the availability of an entity. - """ - - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None - - def __repr__(self): - return 'AvailabilityKind.%s' % (self.name,) - -AvailabilityKind.AVAILABLE = AvailabilityKind(0) -AvailabilityKind.DEPRECATED = AvailabilityKind(1) -AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2) -AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3) - -### C++ access specifiers ### - -class AccessSpecifier(BaseEnumeration): - """ - Describes the access of a C++ class member - """ - - # The unique kind objects, index by id. - _kinds = [] - _name_map = None - - def from_param(self): - return self.value - - def __repr__(self): - return 'AccessSpecifier.%s' % (self.name,) - -AccessSpecifier.INVALID = AccessSpecifier(0) -AccessSpecifier.PUBLIC = AccessSpecifier(1) -AccessSpecifier.PROTECTED = AccessSpecifier(2) -AccessSpecifier.PRIVATE = AccessSpecifier(3) -AccessSpecifier.NONE = AccessSpecifier(4) - -### Type Kinds ### - -class TypeKind(BaseEnumeration): - """ - Describes the kind of type. - """ - - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None - - @property - def spelling(self): - """Retrieve the spelling of this TypeKind.""" - return conf.lib.clang_getTypeKindSpelling(self.value) - - def __repr__(self): - return 'TypeKind.%s' % (self.name,) - -TypeKind.INVALID = TypeKind(0) -TypeKind.UNEXPOSED = TypeKind(1) -TypeKind.VOID = TypeKind(2) -TypeKind.BOOL = TypeKind(3) -TypeKind.CHAR_U = TypeKind(4) -TypeKind.UCHAR = TypeKind(5) -TypeKind.CHAR16 = TypeKind(6) -TypeKind.CHAR32 = TypeKind(7) -TypeKind.USHORT = TypeKind(8) -TypeKind.UINT = TypeKind(9) -TypeKind.ULONG = TypeKind(10) -TypeKind.ULONGLONG = TypeKind(11) -TypeKind.UINT128 = TypeKind(12) -TypeKind.CHAR_S = TypeKind(13) -TypeKind.SCHAR = TypeKind(14) -TypeKind.WCHAR = TypeKind(15) -TypeKind.SHORT = TypeKind(16) -TypeKind.INT = TypeKind(17) -TypeKind.LONG = TypeKind(18) -TypeKind.LONGLONG = TypeKind(19) -TypeKind.INT128 = TypeKind(20) -TypeKind.FLOAT = TypeKind(21) -TypeKind.DOUBLE = TypeKind(22) -TypeKind.LONGDOUBLE = TypeKind(23) -TypeKind.NULLPTR = TypeKind(24) -TypeKind.OVERLOAD = TypeKind(25) -TypeKind.DEPENDENT = TypeKind(26) -TypeKind.OBJCID = TypeKind(27) -TypeKind.OBJCCLASS = TypeKind(28) -TypeKind.OBJCSEL = TypeKind(29) -TypeKind.FLOAT128 = TypeKind(30) -TypeKind.HALF = TypeKind(31) -TypeKind.COMPLEX = TypeKind(100) -TypeKind.POINTER = TypeKind(101) -TypeKind.BLOCKPOINTER = TypeKind(102) -TypeKind.LVALUEREFERENCE = TypeKind(103) -TypeKind.RVALUEREFERENCE = TypeKind(104) -TypeKind.RECORD = TypeKind(105) -TypeKind.ENUM = TypeKind(106) -TypeKind.TYPEDEF = TypeKind(107) -TypeKind.OBJCINTERFACE = TypeKind(108) -TypeKind.OBJCOBJECTPOINTER = TypeKind(109) -TypeKind.FUNCTIONNOPROTO = TypeKind(110) -TypeKind.FUNCTIONPROTO = TypeKind(111) -TypeKind.CONSTANTARRAY = TypeKind(112) -TypeKind.VECTOR = TypeKind(113) -TypeKind.INCOMPLETEARRAY = TypeKind(114) -TypeKind.VARIABLEARRAY = TypeKind(115) -TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116) -TypeKind.MEMBERPOINTER = TypeKind(117) -TypeKind.AUTO = TypeKind(118) -TypeKind.ELABORATED = TypeKind(119) -TypeKind.PIPE = TypeKind(120) -TypeKind.OCLIMAGE1DRO = TypeKind(121) -TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122) -TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123) -TypeKind.OCLIMAGE2DRO = TypeKind(124) -TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125) -TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126) -TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127) -TypeKind.OCLIMAGE2DMSAARO = TypeKind(128) -TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129) -TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130) -TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131) -TypeKind.OCLIMAGE3DRO = TypeKind(132) -TypeKind.OCLIMAGE1DWO = TypeKind(133) -TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134) -TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135) -TypeKind.OCLIMAGE2DWO = TypeKind(136) -TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137) -TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138) -TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139) -TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140) -TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141) -TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142) -TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143) -TypeKind.OCLIMAGE3DWO = TypeKind(144) -TypeKind.OCLIMAGE1DRW = TypeKind(145) -TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146) -TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147) -TypeKind.OCLIMAGE2DRW = TypeKind(148) -TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149) -TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150) -TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151) -TypeKind.OCLIMAGE2DMSAARW = TypeKind(152) -TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153) -TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154) -TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155) -TypeKind.OCLIMAGE3DRW = TypeKind(156) -TypeKind.OCLSAMPLER = TypeKind(157) -TypeKind.OCLEVENT = TypeKind(158) -TypeKind.OCLQUEUE = TypeKind(159) -TypeKind.OCLRESERVEID = TypeKind(160) - -TypeKind.EXTVECTOR = TypeKind(176) -TypeKind.ATOMIC = TypeKind(177) - -class RefQualifierKind(BaseEnumeration): - """Describes a specific ref-qualifier of a type.""" - - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None - - def from_param(self): - return self.value - - def __repr__(self): - return 'RefQualifierKind.%s' % (self.name,) - -RefQualifierKind.NONE = RefQualifierKind(0) -RefQualifierKind.LVALUE = RefQualifierKind(1) -RefQualifierKind.RVALUE = RefQualifierKind(2) - -class LinkageKind(BaseEnumeration): - """Describes the kind of linkage of a cursor.""" - - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None - - def from_param(self): - return self.value - - def __repr__(self): - return 'LinkageKind.%s' % (self.name,) - -LinkageKind.INVALID = LinkageKind(0) -LinkageKind.NO_LINKAGE = LinkageKind(1) -LinkageKind.INTERNAL = LinkageKind(2) -LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3) -LinkageKind.EXTERNAL = LinkageKind(4) - -class TLSKind(BaseEnumeration): - """Describes the kind of thread-local storage (TLS) of a cursor.""" - - # The unique kind objects, indexed by id. - _kinds = [] - _name_map = None - - def from_param(self): - return self.value - - def __repr__(self): - return 'TLSKind.%s' % (self.name,) - -TLSKind.NONE = TLSKind(0) -TLSKind.DYNAMIC = TLSKind(1) -TLSKind.STATIC = TLSKind(2) - -class Type(Structure): - """ - The type of an element in the abstract syntax tree. - """ - _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] - - @property - def kind(self): - """Return the kind of this type.""" - return TypeKind.from_id(self._kind_id) - - def argument_types(self): - """Retrieve a container for the non-variadic arguments for this type. - - The returned object is iterable and indexable. Each item in the - container is a Type instance. - """ - class ArgumentsIterator(collections_abc.Sequence): - def __init__(self, parent): - self.parent = parent - self.length = None - - def __len__(self): - if self.length is None: - self.length = conf.lib.clang_getNumArgTypes(self.parent) - - return self.length - - def __getitem__(self, key): - # FIXME Support slice objects. - if not isinstance(key, int): - raise TypeError("Must supply a non-negative int.") - - if key < 0: - raise IndexError("Only non-negative indexes are accepted.") - - if key >= len(self): - raise IndexError("Index greater than container length: " - "%d > %d" % ( key, len(self) )) - - result = conf.lib.clang_getArgType(self.parent, key) - if result.kind == TypeKind.INVALID: - raise IndexError("Argument could not be retrieved.") - - return result - - assert self.kind == TypeKind.FUNCTIONPROTO - return ArgumentsIterator(self) - - @property - def element_type(self): - """Retrieve the Type of elements within this Type. - - If accessed on a type that is not an array, complex, or vector type, an - exception will be raised. - """ - result = conf.lib.clang_getElementType(self) - if result.kind == TypeKind.INVALID: - raise Exception('Element type not available on this type.') - - return result - - @property - def element_count(self): - """Retrieve the number of elements in this type. - - Returns an int. - - If the Type is not an array or vector, this raises. - """ - result = conf.lib.clang_getNumElements(self) - if result < 0: - raise Exception('Type does not have elements.') - - return result - - @property - def translation_unit(self): - """The TranslationUnit to which this Type is associated.""" - # If this triggers an AttributeError, the instance was not properly - # instantiated. - return self._tu - - @staticmethod - def from_result(res, fn, args): - assert isinstance(res, Type) - - tu = None - for arg in args: - if hasattr(arg, 'translation_unit'): - tu = arg.translation_unit - break - - assert tu is not None - res._tu = tu - - return res - - def get_num_template_arguments(self): - return conf.lib.clang_Type_getNumTemplateArguments(self) - - def get_template_argument_type(self, num): - return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) - - def get_canonical(self): - """ - Return the canonical type for a Type. - - Clang's type system explicitly models typedefs and all the - ways a specific type can be represented. The canonical type - is the underlying type with all the "sugar" removed. For - example, if 'T' is a typedef for 'int', the canonical type for - 'T' would be 'int'. - """ - return conf.lib.clang_getCanonicalType(self) - - def is_const_qualified(self): - """Determine whether a Type has the "const" qualifier set. - - This does not look through typedefs that may have added "const" - at a different level. - """ - return conf.lib.clang_isConstQualifiedType(self) - - def is_volatile_qualified(self): - """Determine whether a Type has the "volatile" qualifier set. - - This does not look through typedefs that may have added "volatile" - at a different level. - """ - return conf.lib.clang_isVolatileQualifiedType(self) - - def is_restrict_qualified(self): - """Determine whether a Type has the "restrict" qualifier set. - - This does not look through typedefs that may have added "restrict" at - a different level. - """ - return conf.lib.clang_isRestrictQualifiedType(self) - - def is_function_variadic(self): - """Determine whether this function Type is a variadic function type.""" - assert self.kind == TypeKind.FUNCTIONPROTO - - return conf.lib.clang_isFunctionTypeVariadic(self) - - def get_address_space(self): - return conf.lib.clang_getAddressSpace(self) - - def get_typedef_name(self): - return conf.lib.clang_getTypedefName(self) - - def is_pod(self): - """Determine whether this Type represents plain old data (POD).""" - return conf.lib.clang_isPODType(self) - - def get_pointee(self): - """ - For pointer types, returns the type of the pointee. - """ - return conf.lib.clang_getPointeeType(self) - - def get_declaration(self): - """ - Return the cursor for the declaration of the given type. - """ - return conf.lib.clang_getTypeDeclaration(self) - - def get_result(self): - """ - Retrieve the result type associated with a function type. - """ - return conf.lib.clang_getResultType(self) - - def get_array_element_type(self): - """ - Retrieve the type of the elements of the array type. - """ - return conf.lib.clang_getArrayElementType(self) - - def get_array_size(self): - """ - Retrieve the size of the constant array. - """ - return conf.lib.clang_getArraySize(self) - - def get_class_type(self): - """ - Retrieve the class type of the member pointer type. - """ - return conf.lib.clang_Type_getClassType(self) - - def get_named_type(self): - """ - Retrieve the type named by the qualified-id. - """ - return conf.lib.clang_Type_getNamedType(self) - - def get_align(self): - """ - Retrieve the alignment of the record. - """ - return conf.lib.clang_Type_getAlignOf(self) - - def get_size(self): - """ - Retrieve the size of the record. - """ - return conf.lib.clang_Type_getSizeOf(self) - - def get_offset(self, fieldname): - """ - Retrieve the offset of a field in the record. - """ - return conf.lib.clang_Type_getOffsetOf(self, fieldname) - - def get_ref_qualifier(self): - """ - Retrieve the ref-qualifier of the type. - """ - return RefQualifierKind.from_id( - conf.lib.clang_Type_getCXXRefQualifier(self)) - - def get_fields(self): - """Return an iterator for accessing the fields of this type.""" - - def visitor(field, children): - assert field != conf.lib.clang_getNullCursor() - - # Create reference to TU so it isn't GC'd before Cursor. - field._tu = self._tu - fields.append(field) - return 1 # continue - fields = [] - conf.lib.clang_Type_visitFields(self, - callbacks['fields_visit'](visitor), fields) - return iter(fields) - - def get_exception_specification_kind(self): - """ - Return the kind of the exception specification; a value from - the ExceptionSpecificationKind enumeration. - """ - return ExceptionSpecificationKind.from_id( - conf.lib.clang.getExceptionSpecificationType(self)) - - @property - def spelling(self): - """Retrieve the spelling of this Type.""" - return conf.lib.clang_getTypeSpelling(self) - - def __eq__(self, other): - if type(other) != type(self): - return False - - return conf.lib.clang_equalTypes(self, other) - - def __ne__(self, other): - return not self.__eq__(other) - -## CIndex Objects ## - -# CIndex objects (derived from ClangObject) are essentially lightweight -# wrappers attached to some underlying object, which is exposed via CIndex as -# a void*. - -class ClangObject(object): - """ - A helper for Clang objects. This class helps act as an intermediary for - the ctypes library and the Clang CIndex library. - """ - def __init__(self, obj): - assert isinstance(obj, c_object_p) and obj - self.obj = self._as_parameter_ = obj - - def from_param(self): - return self._as_parameter_ - - -class _CXUnsavedFile(Structure): - """Helper for passing unsaved file arguments.""" - _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] - -# Functions calls through the python interface are rather slow. Fortunately, -# for most symboles, we do not need to perform a function call. Their spelling -# never changes and is consequently provided by this spelling cache. -SpellingCache = { - # 0: CompletionChunk.Kind("Optional"), - # 1: CompletionChunk.Kind("TypedText"), - # 2: CompletionChunk.Kind("Text"), - # 3: CompletionChunk.Kind("Placeholder"), - # 4: CompletionChunk.Kind("Informative"), - # 5 : CompletionChunk.Kind("CurrentParameter"), - 6: '(', # CompletionChunk.Kind("LeftParen"), - 7: ')', # CompletionChunk.Kind("RightParen"), - 8: '[', # CompletionChunk.Kind("LeftBracket"), - 9: ']', # CompletionChunk.Kind("RightBracket"), - 10: '{', # CompletionChunk.Kind("LeftBrace"), - 11: '}', # CompletionChunk.Kind("RightBrace"), - 12: '<', # CompletionChunk.Kind("LeftAngle"), - 13: '>', # CompletionChunk.Kind("RightAngle"), - 14: ', ', # CompletionChunk.Kind("Comma"), - # 15: CompletionChunk.Kind("ResultType"), - 16: ':', # CompletionChunk.Kind("Colon"), - 17: ';', # CompletionChunk.Kind("SemiColon"), - 18: '=', # CompletionChunk.Kind("Equal"), - 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), - # 20: CompletionChunk.Kind("VerticalSpace") -} - -class CompletionChunk(object): - class Kind(object): - def __init__(self, name): - self.name = name - - def __str__(self): - return self.name - - def __repr__(self): - return "" % self - - def __init__(self, completionString, key): - self.cs = completionString - self.key = key - self.__kindNumberCache = -1 - - def __repr__(self): - return "{'" + self.spelling + "', " + str(self.kind) + "}" - - @CachedProperty - def spelling(self): - if self.__kindNumber in SpellingCache: - return SpellingCache[self.__kindNumber] - return conf.lib.clang_getCompletionChunkText(self.cs, self.key) - - # We do not use @CachedProperty here, as the manual implementation is - # apparently still significantly faster. Please profile carefully if you - # would like to add CachedProperty back. - @property - def __kindNumber(self): - if self.__kindNumberCache == -1: - self.__kindNumberCache = \ - conf.lib.clang_getCompletionChunkKind(self.cs, self.key) - return self.__kindNumberCache - - @CachedProperty - def kind(self): - return completionChunkKindMap[self.__kindNumber] - - @CachedProperty - def string(self): - res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, - self.key) - - if (res): - return CompletionString(res) - else: - None - - def isKindOptional(self): - return self.__kindNumber == 0 - - def isKindTypedText(self): - return self.__kindNumber == 1 - - def isKindPlaceHolder(self): - return self.__kindNumber == 3 - - def isKindInformative(self): - return self.__kindNumber == 4 - - def isKindResultType(self): - return self.__kindNumber == 15 - -completionChunkKindMap = { - 0: CompletionChunk.Kind("Optional"), - 1: CompletionChunk.Kind("TypedText"), - 2: CompletionChunk.Kind("Text"), - 3: CompletionChunk.Kind("Placeholder"), - 4: CompletionChunk.Kind("Informative"), - 5: CompletionChunk.Kind("CurrentParameter"), - 6: CompletionChunk.Kind("LeftParen"), - 7: CompletionChunk.Kind("RightParen"), - 8: CompletionChunk.Kind("LeftBracket"), - 9: CompletionChunk.Kind("RightBracket"), - 10: CompletionChunk.Kind("LeftBrace"), - 11: CompletionChunk.Kind("RightBrace"), - 12: CompletionChunk.Kind("LeftAngle"), - 13: CompletionChunk.Kind("RightAngle"), - 14: CompletionChunk.Kind("Comma"), - 15: CompletionChunk.Kind("ResultType"), - 16: CompletionChunk.Kind("Colon"), - 17: CompletionChunk.Kind("SemiColon"), - 18: CompletionChunk.Kind("Equal"), - 19: CompletionChunk.Kind("HorizontalSpace"), - 20: CompletionChunk.Kind("VerticalSpace")} - -class CompletionString(ClangObject): - class Availability(object): - def __init__(self, name): - self.name = name - - def __str__(self): - return self.name - - def __repr__(self): - return "" % self - - def __len__(self): - return self.num_chunks - - @CachedProperty - def num_chunks(self): - return conf.lib.clang_getNumCompletionChunks(self.obj) - - def __getitem__(self, key): - if self.num_chunks <= key: - raise IndexError - return CompletionChunk(self.obj, key) - - @property - def priority(self): - return conf.lib.clang_getCompletionPriority(self.obj) - - @property - def availability(self): - res = conf.lib.clang_getCompletionAvailability(self.obj) - return availabilityKinds[res] - - @property - def briefComment(self): - if conf.function_exists("clang_getCompletionBriefComment"): - return conf.lib.clang_getCompletionBriefComment(self.obj) - return _CXString() - - def __repr__(self): - return " | ".join([str(a) for a in self]) \ - + " || Priority: " + str(self.priority) \ - + " || Availability: " + str(self.availability) \ - + " || Brief comment: " + str(self.briefComment) - -availabilityKinds = { - 0: CompletionChunk.Kind("Available"), - 1: CompletionChunk.Kind("Deprecated"), - 2: CompletionChunk.Kind("NotAvailable"), - 3: CompletionChunk.Kind("NotAccessible")} - -class CodeCompletionResult(Structure): - _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] - - def __repr__(self): - return str(CompletionString(self.completionString)) - - @property - def kind(self): - return CursorKind.from_id(self.cursorKind) - - @property - def string(self): - return CompletionString(self.completionString) - -class CCRStructure(Structure): - _fields_ = [('results', POINTER(CodeCompletionResult)), - ('numResults', c_int)] - - def __len__(self): - return self.numResults - - def __getitem__(self, key): - if len(self) <= key: - raise IndexError - - return self.results[key] - -class CodeCompletionResults(ClangObject): - def __init__(self, ptr): - assert isinstance(ptr, POINTER(CCRStructure)) and ptr - self.ptr = self._as_parameter_ = ptr - - def from_param(self): - return self._as_parameter_ - - def __del__(self): - conf.lib.clang_disposeCodeCompleteResults(self) - - @property - def results(self): - return self.ptr.contents - - @property - def diagnostics(self): - class DiagnosticsItr(object): - def __init__(self, ccr): - self.ccr= ccr - - def __len__(self): - return int(\ - conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) - - def __getitem__(self, key): - return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) - - return DiagnosticsItr(self) - - -class Index(ClangObject): - """ - The Index type provides the primary interface to the Clang CIndex library, - primarily by providing an interface for reading and parsing translation - units. - """ - - @staticmethod - def create(excludeDecls=False): - """ - Create a new Index. - Parameters: - excludeDecls -- Exclude local declarations from translation units. - """ - return Index(conf.lib.clang_createIndex(excludeDecls, 0)) - - def __del__(self): - conf.lib.clang_disposeIndex(self) - - def read(self, path): - """Load a TranslationUnit from the given AST file.""" - return TranslationUnit.from_ast_file(path, self) - - def parse(self, path, args=None, unsaved_files=None, options = 0): - """Load the translation unit from the given source code file by running - clang and generating the AST before loading. Additional command line - parameters can be passed to clang via the args parameter. - - In-memory contents for files can be provided by passing a list of pairs - to as unsaved_files, the first item should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - - If an error was encountered during parsing, a TranslationUnitLoadError - will be raised. - """ - return TranslationUnit.from_source(path, args, unsaved_files, options, - self) - -class TranslationUnit(ClangObject): - """Represents a source code translation unit. - - This is one of the main types in the API. Any time you wish to interact - with Clang's representation of a source file, you typically start with a - translation unit. - """ - - # Default parsing mode. - PARSE_NONE = 0 - - # Instruct the parser to create a detailed processing record containing - # metadata not normally retained. - PARSE_DETAILED_PROCESSING_RECORD = 1 - - # Indicates that the translation unit is incomplete. This is typically used - # when parsing headers. - PARSE_INCOMPLETE = 2 - - # Instruct the parser to create a pre-compiled preamble for the translation - # unit. This caches the preamble (included files at top of source file). - # This is useful if the translation unit will be reparsed and you don't - # want to incur the overhead of reparsing the preamble. - PARSE_PRECOMPILED_PREAMBLE = 4 - - # Cache code completion information on parse. This adds time to parsing but - # speeds up code completion. - PARSE_CACHE_COMPLETION_RESULTS = 8 - - # Flags with values 16 and 32 are deprecated and intentionally omitted. - - # Do not parse function bodies. This is useful if you only care about - # searching for declarations/definitions. - PARSE_SKIP_FUNCTION_BODIES = 64 - - # Used to indicate that brief documentation comments should be included - # into the set of code completions returned from this translation unit. - PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 - - @classmethod - def from_source(cls, filename, args=None, unsaved_files=None, options=0, - index=None): - """Create a TranslationUnit by parsing source. - - This is capable of processing source code both from files on the - filesystem as well as in-memory contents. - - Command-line arguments that would be passed to clang are specified as - a list via args. These can be used to specify include paths, warnings, - etc. e.g. ["-Wall", "-I/path/to/include"]. - - In-memory file content can be provided via unsaved_files. This is an - iterable of 2-tuples. The first element is the filename (str or - PathLike). The second element defines the content. Content can be - provided as str source code or as file objects (anything with a read() - method). If a file object is being used, content will be read until EOF - and the read cursor will not be reset to its original position. - - options is a bitwise or of TranslationUnit.PARSE_XXX flags which will - control parsing behavior. - - index is an Index instance to utilize. If not provided, a new Index - will be created for this TranslationUnit. - - To parse source from the filesystem, the filename of the file to parse - is specified by the filename argument. Or, filename could be None and - the args list would contain the filename(s) to parse. - - To parse source from an in-memory buffer, set filename to the virtual - filename you wish to associate with this source (e.g. "test.c"). The - contents of that file are then provided in unsaved_files. - - If an error occurs, a TranslationUnitLoadError is raised. - - Please note that a TranslationUnit with parser errors may be returned. - It is the caller's responsibility to check tu.diagnostics for errors. - - Also note that Clang infers the source language from the extension of - the input filename. If you pass in source code containing a C++ class - declaration with the filename "test.c" parsing will fail. - """ - if args is None: - args = [] - - if unsaved_files is None: - unsaved_files = [] - - if index is None: - index = Index.create() - - args_array = None - if len(args) > 0: - args_array = (c_char_p * len(args))(*[b(x) for x in args]) - - unsaved_array = None - if len(unsaved_files) > 0: - unsaved_array = (_CXUnsavedFile * len(unsaved_files))() - for i, (name, contents) in enumerate(unsaved_files): - if hasattr(contents, "read"): - contents = contents.read() - contents = b(contents) - unsaved_array[i].name = b(fspath(name)) - unsaved_array[i].contents = contents - unsaved_array[i].length = len(contents) - - ptr = conf.lib.clang_parseTranslationUnit(index, - fspath(filename) if filename is not None else None, - args_array, - len(args), unsaved_array, - len(unsaved_files), options) - - if not ptr: - raise TranslationUnitLoadError("Error parsing translation unit.") - - return cls(ptr, index=index) - - @classmethod - def from_ast_file(cls, filename, index=None): - """Create a TranslationUnit instance from a saved AST file. - - A previously-saved AST file (provided with -emit-ast or - TranslationUnit.save()) is loaded from the filename specified. - - If the file cannot be loaded, a TranslationUnitLoadError will be - raised. - - index is optional and is the Index instance to use. If not provided, - a default Index will be created. - - filename can be str or PathLike. - """ - if index is None: - index = Index.create() - - ptr = conf.lib.clang_createTranslationUnit(index, fspath(filename)) - if not ptr: - raise TranslationUnitLoadError(filename) - - return cls(ptr=ptr, index=index) - - def __init__(self, ptr, index): - """Create a TranslationUnit instance. - - TranslationUnits should be created using one of the from_* @classmethod - functions above. __init__ is only called internally. - """ - assert isinstance(index, Index) - self.index = index - ClangObject.__init__(self, ptr) - - def __del__(self): - conf.lib.clang_disposeTranslationUnit(self) - - @property - def cursor(self): - """Retrieve the cursor that represents the given translation unit.""" - return conf.lib.clang_getTranslationUnitCursor(self) - - @property - def spelling(self): - """Get the original translation unit source file name.""" - return conf.lib.clang_getTranslationUnitSpelling(self) - - def get_includes(self): - """ - Return an iterable sequence of FileInclusion objects that describe the - sequence of inclusions in a translation unit. The first object in - this sequence is always the input file. Note that this method will not - recursively iterate over header files included through precompiled - headers. - """ - def visitor(fobj, lptr, depth, includes): - if depth > 0: - loc = lptr.contents - includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) - - # Automatically adapt CIndex/ctype pointers to python objects - includes = [] - conf.lib.clang_getInclusions(self, - callbacks['translation_unit_includes'](visitor), includes) - - return iter(includes) - - def get_file(self, filename): - """Obtain a File from this translation unit.""" - - return File.from_name(self, filename) - - def get_location(self, filename, position): - """Obtain a SourceLocation for a file in this translation unit. - - The position can be specified by passing: - - - Integer file offset. Initial file offset is 0. - - 2-tuple of (line number, column number). Initial file position is - (0, 0) - """ - f = self.get_file(filename) - - if isinstance(position, int): - return SourceLocation.from_offset(self, f, position) - - return SourceLocation.from_position(self, f, position[0], position[1]) - - def get_extent(self, filename, locations): - """Obtain a SourceRange from this translation unit. - - The bounds of the SourceRange must ultimately be defined by a start and - end SourceLocation. For the locations argument, you can pass: - - - 2 SourceLocation instances in a 2-tuple or list. - - 2 int file offsets via a 2-tuple or list. - - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. - - e.g. - - get_extent('foo.c', (5, 10)) - get_extent('foo.c', ((1, 1), (1, 15))) - """ - f = self.get_file(filename) - - if len(locations) < 2: - raise Exception('Must pass object with at least 2 elements') - - start_location, end_location = locations - - if hasattr(start_location, '__len__'): - start_location = SourceLocation.from_position(self, f, - start_location[0], start_location[1]) - elif isinstance(start_location, int): - start_location = SourceLocation.from_offset(self, f, - start_location) - - if hasattr(end_location, '__len__'): - end_location = SourceLocation.from_position(self, f, - end_location[0], end_location[1]) - elif isinstance(end_location, int): - end_location = SourceLocation.from_offset(self, f, end_location) - - assert isinstance(start_location, SourceLocation) - assert isinstance(end_location, SourceLocation) - - return SourceRange.from_locations(start_location, end_location) - - @property - def diagnostics(self): - """ - Return an iterable (and indexable) object containing the diagnostics. - """ - class DiagIterator(object): - def __init__(self, tu): - self.tu = tu - - def __len__(self): - return int(conf.lib.clang_getNumDiagnostics(self.tu)) - - def __getitem__(self, key): - diag = conf.lib.clang_getDiagnostic(self.tu, key) - if not diag: - raise IndexError - return Diagnostic(diag) - - return DiagIterator(self) - - def reparse(self, unsaved_files=None, options=0): - """ - Reparse an already parsed translation unit. - - In-memory contents for files can be provided by passing a list of pairs - as unsaved_files, the first items should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - """ - if unsaved_files is None: - unsaved_files = [] - - unsaved_files_array = 0 - if len(unsaved_files): - unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() - for i,(name,contents) in enumerate(unsaved_files): - if hasattr(contents, "read"): - contents = contents.read() - contents = b(contents) - unsaved_files_array[i].name = b(fspath(name)) - unsaved_files_array[i].contents = contents - unsaved_files_array[i].length = len(contents) - ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), - unsaved_files_array, options) - - def save(self, filename): - """Saves the TranslationUnit to a file. - - This is equivalent to passing -emit-ast to the clang frontend. The - saved file can be loaded back into a TranslationUnit. Or, if it - corresponds to a header, it can be used as a pre-compiled header file. - - If an error occurs while saving, a TranslationUnitSaveError is raised. - If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means - the constructed TranslationUnit was not valid at time of save. In this - case, the reason(s) why should be available via - TranslationUnit.diagnostics(). - - filename -- The path to save the translation unit to (str or PathLike). - """ - options = conf.lib.clang_defaultSaveOptions(self) - result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename), - options)) - if result != 0: - raise TranslationUnitSaveError(result, - 'Error saving TranslationUnit.') - - def codeComplete(self, path, line, column, unsaved_files=None, - include_macros=False, include_code_patterns=False, - include_brief_comments=False): - """ - Code complete in this translation unit. - - In-memory contents for files can be provided by passing a list of pairs - as unsaved_files, the first items should be the filenames to be mapped - and the second should be the contents to be substituted for the - file. The contents may be passed as strings or file objects. - """ - options = 0 - - if include_macros: - options += 1 - - if include_code_patterns: - options += 2 - - if include_brief_comments: - options += 4 - - if unsaved_files is None: - unsaved_files = [] - - unsaved_files_array = 0 - if len(unsaved_files): - unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() - for i,(name,contents) in enumerate(unsaved_files): - if hasattr(contents, "read"): - contents = contents.read() - contents = b(contents) - unsaved_files_array[i].name = b(fspath(name)) - unsaved_files_array[i].contents = contents - unsaved_files_array[i].length = len(contents) - ptr = conf.lib.clang_codeCompleteAt(self, fspath(path), line, column, - unsaved_files_array, len(unsaved_files), options) - if ptr: - return CodeCompletionResults(ptr) - return None - - def get_tokens(self, locations=None, extent=None): - """Obtain tokens in this translation unit. - - This is a generator for Token instances. The caller specifies a range - of source code to obtain tokens for. The range can be specified as a - 2-tuple of SourceLocation or as a SourceRange. If both are defined, - behavior is undefined. - """ - if locations is not None: - extent = SourceRange(start=locations[0], end=locations[1]) - - return TokenGroup.get_tokens(self, extent) - -class File(ClangObject): - """ - The File class represents a particular source file that is part of a - translation unit. - """ - - @staticmethod - def from_name(translation_unit, file_name): - """Retrieve a file handle within the given translation unit.""" - return File(conf.lib.clang_getFile(translation_unit, fspath(file_name))) - - @property - def name(self): - """Return the complete file and path name of the file.""" - return conf.lib.clang_getFileName(self) - - @property - def time(self): - """Return the last modification time of the file.""" - return conf.lib.clang_getFileTime(self) - - def __str__(self): - return self.name - - def __repr__(self): - return "" % (self.name) - - @staticmethod - def from_result(res, fn, args): - assert isinstance(res, c_object_p) - res = File(res) - - # Copy a reference to the TranslationUnit to prevent premature GC. - res._tu = args[0]._tu - return res - -class FileInclusion(object): - """ - The FileInclusion class represents the inclusion of one source file by - another via a '#include' directive or as the input file for the translation - unit. This class provides information about the included file, the including - file, the location of the '#include' directive and the depth of the included - file in the stack. Note that the input file has depth 0. - """ - - def __init__(self, src, tgt, loc, depth): - self.source = src - self.include = tgt - self.location = loc - self.depth = depth - - @property - def is_input_file(self): - """True if the included file is the input file.""" - return self.depth == 0 - -class CompilationDatabaseError(Exception): - """Represents an error that occurred when working with a CompilationDatabase - - Each error is associated to an enumerated value, accessible under - e.cdb_error. Consumers can compare the value with one of the ERROR_ - constants in this class. - """ - - # An unknown error occurred - ERROR_UNKNOWN = 0 - - # The database could not be loaded - ERROR_CANNOTLOADDATABASE = 1 - - def __init__(self, enumeration, message): - assert isinstance(enumeration, int) - - if enumeration > 1: - raise Exception("Encountered undefined CompilationDatabase error " - "constant: %d. Please file a bug to have this " - "value supported." % enumeration) - - self.cdb_error = enumeration - Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) - -class CompileCommand(object): - """Represents the compile command used to build a file""" - def __init__(self, cmd, ccmds): - self.cmd = cmd - # Keep a reference to the originating CompileCommands - # to prevent garbage collection - self.ccmds = ccmds - - @property - def directory(self): - """Get the working directory for this CompileCommand""" - return conf.lib.clang_CompileCommand_getDirectory(self.cmd) - - @property - def filename(self): - """Get the working filename for this CompileCommand""" - return conf.lib.clang_CompileCommand_getFilename(self.cmd) - - @property - def arguments(self): - """ - Get an iterable object providing each argument in the - command line for the compiler invocation as a _CXString. - - Invariant : the first argument is the compiler executable - """ - length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) - for i in range(length): - yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) - -class CompileCommands(object): - """ - CompileCommands is an iterable object containing all CompileCommand - that can be used for building a specific file. - """ - def __init__(self, ccmds): - self.ccmds = ccmds - - def __del__(self): - conf.lib.clang_CompileCommands_dispose(self.ccmds) - - def __len__(self): - return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) - - def __getitem__(self, i): - cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) - if not cc: - raise IndexError - return CompileCommand(cc, self) - - @staticmethod - def from_result(res, fn, args): - if not res: - return None - return CompileCommands(res) - -class CompilationDatabase(ClangObject): - """ - The CompilationDatabase is a wrapper class around - clang::tooling::CompilationDatabase - - It enables querying how a specific source file can be built. - """ - - def __del__(self): - conf.lib.clang_CompilationDatabase_dispose(self) - - @staticmethod - def from_result(res, fn, args): - if not res: - raise CompilationDatabaseError(0, - "CompilationDatabase loading failed") - return CompilationDatabase(res) - - @staticmethod - def fromDirectory(buildDir): - """Builds a CompilationDatabase from the database found in buildDir""" - errorCode = c_uint() - try: - cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir), - byref(errorCode)) - except CompilationDatabaseError as e: - raise CompilationDatabaseError(int(errorCode.value), - "CompilationDatabase loading failed") - return cdb - - def getCompileCommands(self, filename): - """ - Get an iterable object providing all the CompileCommands available to - build filename. Returns None if filename is not found in the database. - """ - return conf.lib.clang_CompilationDatabase_getCompileCommands(self, - fspath(filename)) - - def getAllCompileCommands(self): - """ - Get an iterable object providing all the CompileCommands available from - the database. - """ - return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) - - -class Token(Structure): - """Represents a single token from the preprocessor. - - Tokens are effectively segments of source code. Source code is first parsed - into tokens before being converted into the AST and Cursors. - - Tokens are obtained from parsed TranslationUnit instances. You currently - can't create tokens manually. - """ - _fields_ = [ - ('int_data', c_uint * 4), - ('ptr_data', c_void_p) - ] - - @property - def spelling(self): - """The spelling of this token. - - This is the textual representation of the token in source. - """ - return conf.lib.clang_getTokenSpelling(self._tu, self) - - @property - def kind(self): - """Obtain the TokenKind of the current token.""" - return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) - - @property - def location(self): - """The SourceLocation this Token occurs at.""" - return conf.lib.clang_getTokenLocation(self._tu, self) - - @property - def extent(self): - """The SourceRange this Token occupies.""" - return conf.lib.clang_getTokenExtent(self._tu, self) - - @property - def cursor(self): - """The Cursor this Token corresponds to.""" - cursor = Cursor() - cursor._tu = self._tu - - conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) - - return cursor - -# Now comes the plumbing to hook up the C library. - -# Register callback types in common container. -callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, - POINTER(SourceLocation), c_uint, py_object) -callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) -callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object) - -# Functions strictly alphabetical order. -functionList = [ - ("clang_annotateTokens", - [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), - - ("clang_CompilationDatabase_dispose", - [c_object_p]), - - ("clang_CompilationDatabase_fromDirectory", - [c_interop_string, POINTER(c_uint)], - c_object_p, - CompilationDatabase.from_result), - - ("clang_CompilationDatabase_getAllCompileCommands", - [c_object_p], - c_object_p, - CompileCommands.from_result), - - ("clang_CompilationDatabase_getCompileCommands", - [c_object_p, c_interop_string], - c_object_p, - CompileCommands.from_result), - - ("clang_CompileCommands_dispose", - [c_object_p]), - - ("clang_CompileCommands_getCommand", - [c_object_p, c_uint], - c_object_p), - - ("clang_CompileCommands_getSize", - [c_object_p], - c_uint), - - ("clang_CompileCommand_getArg", - [c_object_p, c_uint], - _CXString, - _CXString.from_result), - - ("clang_CompileCommand_getDirectory", - [c_object_p], - _CXString, - _CXString.from_result), - - ("clang_CompileCommand_getFilename", - [c_object_p], - _CXString, - _CXString.from_result), - - ("clang_CompileCommand_getNumArgs", - [c_object_p], - c_uint), - - ("clang_codeCompleteAt", - [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int], - POINTER(CCRStructure)), - - ("clang_codeCompleteGetDiagnostic", - [CodeCompletionResults, c_int], - Diagnostic), - - ("clang_codeCompleteGetNumDiagnostics", - [CodeCompletionResults], - c_int), - - ("clang_createIndex", - [c_int, c_int], - c_object_p), - - ("clang_createTranslationUnit", - [Index, c_interop_string], - c_object_p), - - ("clang_CXXConstructor_isConvertingConstructor", - [Cursor], - bool), - - ("clang_CXXConstructor_isCopyConstructor", - [Cursor], - bool), - - ("clang_CXXConstructor_isDefaultConstructor", - [Cursor], - bool), - - ("clang_CXXConstructor_isMoveConstructor", - [Cursor], - bool), - - ("clang_CXXField_isMutable", - [Cursor], - bool), - - ("clang_CXXMethod_isConst", - [Cursor], - bool), - - ("clang_CXXMethod_isDefaulted", - [Cursor], - bool), - - ("clang_CXXMethod_isPureVirtual", - [Cursor], - bool), - - ("clang_CXXMethod_isStatic", - [Cursor], - bool), - - ("clang_CXXMethod_isVirtual", - [Cursor], - bool), - - ("clang_CXXRecord_isAbstract", - [Cursor], - bool), - - ("clang_EnumDecl_isScoped", - [Cursor], - bool), - - ("clang_defaultDiagnosticDisplayOptions", - [], - c_uint), - - ("clang_defaultSaveOptions", - [TranslationUnit], - c_uint), - - ("clang_disposeCodeCompleteResults", - [CodeCompletionResults]), - -# ("clang_disposeCXTUResourceUsage", -# [CXTUResourceUsage]), - - ("clang_disposeDiagnostic", - [Diagnostic]), - - ("clang_disposeIndex", - [Index]), - - ("clang_disposeString", - [_CXString]), - - ("clang_disposeTokens", - [TranslationUnit, POINTER(Token), c_uint]), - - ("clang_disposeTranslationUnit", - [TranslationUnit]), - - ("clang_equalCursors", - [Cursor, Cursor], - bool), - - ("clang_equalLocations", - [SourceLocation, SourceLocation], - bool), - - ("clang_equalRanges", - [SourceRange, SourceRange], - bool), - - ("clang_equalTypes", - [Type, Type], - bool), - - ("clang_formatDiagnostic", - [Diagnostic, c_uint], - _CXString, - _CXString.from_result), - - ("clang_getArgType", - [Type, c_uint], - Type, - Type.from_result), - - ("clang_getArrayElementType", - [Type], - Type, - Type.from_result), - - ("clang_getArraySize", - [Type], - c_longlong), - - ("clang_getFieldDeclBitWidth", - [Cursor], - c_int), - - ("clang_getCanonicalCursor", - [Cursor], - Cursor, - Cursor.from_cursor_result), - - ("clang_getCanonicalType", - [Type], - Type, - Type.from_result), - - ("clang_getChildDiagnostics", - [Diagnostic], - c_object_p), - - ("clang_getCompletionAvailability", - [c_void_p], - c_int), - - ("clang_getCompletionBriefComment", - [c_void_p], - _CXString, - _CXString.from_result), - - ("clang_getCompletionChunkCompletionString", - [c_void_p, c_int], - c_object_p), - - ("clang_getCompletionChunkKind", - [c_void_p, c_int], - c_int), - - ("clang_getCompletionChunkText", - [c_void_p, c_int], - _CXString, - _CXString.from_result), - - ("clang_getCompletionPriority", - [c_void_p], - c_int), - - ("clang_getCString", - [_CXString], - c_interop_string, - c_interop_string.to_python_string), - - ("clang_getCursor", - [TranslationUnit, SourceLocation], - Cursor), - - ("clang_getCursorAvailability", - [Cursor], - c_int), - - ("clang_getCursorDefinition", - [Cursor], - Cursor, - Cursor.from_result), - - ("clang_getCursorDisplayName", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_getCursorExtent", - [Cursor], - SourceRange), - - ("clang_getCursorLexicalParent", - [Cursor], - Cursor, - Cursor.from_cursor_result), - - ("clang_getCursorLocation", - [Cursor], - SourceLocation), - - ("clang_getCursorReferenced", - [Cursor], - Cursor, - Cursor.from_result), - - ("clang_getCursorReferenceNameRange", - [Cursor, c_uint, c_uint], - SourceRange), - - ("clang_getCursorResultType", - [Cursor], - Type, - Type.from_result), - - ("clang_getCursorSemanticParent", - [Cursor], - Cursor, - Cursor.from_cursor_result), - - ("clang_getCursorSpelling", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_getCursorType", - [Cursor], - Type, - Type.from_result), - - ("clang_getCursorUSR", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_Cursor_getMangling", - [Cursor], - _CXString, - _CXString.from_result), - -# ("clang_getCXTUResourceUsage", -# [TranslationUnit], -# CXTUResourceUsage), - - ("clang_getCXXAccessSpecifier", - [Cursor], - c_uint), - - ("clang_getDeclObjCTypeEncoding", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_getDiagnostic", - [c_object_p, c_uint], - c_object_p), - - ("clang_getDiagnosticCategory", - [Diagnostic], - c_uint), - - ("clang_getDiagnosticCategoryText", - [Diagnostic], - _CXString, - _CXString.from_result), - - ("clang_getDiagnosticFixIt", - [Diagnostic, c_uint, POINTER(SourceRange)], - _CXString, - _CXString.from_result), - - ("clang_getDiagnosticInSet", - [c_object_p, c_uint], - c_object_p), - - ("clang_getDiagnosticLocation", - [Diagnostic], - SourceLocation), - - ("clang_getDiagnosticNumFixIts", - [Diagnostic], - c_uint), - - ("clang_getDiagnosticNumRanges", - [Diagnostic], - c_uint), - - ("clang_getDiagnosticOption", - [Diagnostic, POINTER(_CXString)], - _CXString, - _CXString.from_result), - - ("clang_getDiagnosticRange", - [Diagnostic, c_uint], - SourceRange), - - ("clang_getDiagnosticSeverity", - [Diagnostic], - c_int), - - ("clang_getDiagnosticSpelling", - [Diagnostic], - _CXString, - _CXString.from_result), - - ("clang_getElementType", - [Type], - Type, - Type.from_result), - - ("clang_getEnumConstantDeclUnsignedValue", - [Cursor], - c_ulonglong), - - ("clang_getEnumConstantDeclValue", - [Cursor], - c_longlong), - - ("clang_getEnumDeclIntegerType", - [Cursor], - Type, - Type.from_result), - - ("clang_getFile", - [TranslationUnit, c_interop_string], - c_object_p), - - ("clang_getFileName", - [File], - _CXString, - _CXString.from_result), - - ("clang_getFileTime", - [File], - c_uint), - - ("clang_getIBOutletCollectionType", - [Cursor], - Type, - Type.from_result), - - ("clang_getIncludedFile", - [Cursor], - c_object_p, - File.from_result), - - ("clang_getInclusions", - [TranslationUnit, callbacks['translation_unit_includes'], py_object]), - - ("clang_getInstantiationLocation", - [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), - POINTER(c_uint)]), - - ("clang_getLocation", - [TranslationUnit, File, c_uint, c_uint], - SourceLocation), - - ("clang_getLocationForOffset", - [TranslationUnit, File, c_uint], - SourceLocation), - - ("clang_getNullCursor", - None, - Cursor), - - ("clang_getNumArgTypes", - [Type], - c_uint), - - ("clang_getNumCompletionChunks", - [c_void_p], - c_int), - - ("clang_getNumDiagnostics", - [c_object_p], - c_uint), - - ("clang_getNumDiagnosticsInSet", - [c_object_p], - c_uint), - - ("clang_getNumElements", - [Type], - c_longlong), - - ("clang_getNumOverloadedDecls", - [Cursor], - c_uint), - - ("clang_getOverloadedDecl", - [Cursor, c_uint], - Cursor, - Cursor.from_cursor_result), - - ("clang_getPointeeType", - [Type], - Type, - Type.from_result), - - ("clang_getRange", - [SourceLocation, SourceLocation], - SourceRange), - - ("clang_getRangeEnd", - [SourceRange], - SourceLocation), - - ("clang_getRangeStart", - [SourceRange], - SourceLocation), - - ("clang_getResultType", - [Type], - Type, - Type.from_result), - - ("clang_getSpecializedCursorTemplate", - [Cursor], - Cursor, - Cursor.from_cursor_result), - - ("clang_getTemplateCursorKind", - [Cursor], - c_uint), - - ("clang_getTokenExtent", - [TranslationUnit, Token], - SourceRange), - - ("clang_getTokenKind", - [Token], - c_uint), - - ("clang_getTokenLocation", - [TranslationUnit, Token], - SourceLocation), - - ("clang_getTokenSpelling", - [TranslationUnit, Token], - _CXString, - _CXString.from_result), - - ("clang_getTranslationUnitCursor", - [TranslationUnit], - Cursor, - Cursor.from_result), - - ("clang_getTranslationUnitSpelling", - [TranslationUnit], - _CXString, - _CXString.from_result), - - ("clang_getTUResourceUsageName", - [c_uint], - c_interop_string, - c_interop_string.to_python_string), - - ("clang_getTypeDeclaration", - [Type], - Cursor, - Cursor.from_result), - - ("clang_getTypedefDeclUnderlyingType", - [Cursor], - Type, - Type.from_result), - - ("clang_getTypedefName", - [Type], - _CXString, - _CXString.from_result), - - ("clang_getTypeKindSpelling", - [c_uint], - _CXString, - _CXString.from_result), - - ("clang_getTypeSpelling", - [Type], - _CXString, - _CXString.from_result), - - ("clang_hashCursor", - [Cursor], - c_uint), - - ("clang_isAttribute", - [CursorKind], - bool), - - ("clang_isConstQualifiedType", - [Type], - bool), - - ("clang_isCursorDefinition", - [Cursor], - bool), - - ("clang_isDeclaration", - [CursorKind], - bool), - - ("clang_isExpression", - [CursorKind], - bool), - - ("clang_isFileMultipleIncludeGuarded", - [TranslationUnit, File], - bool), - - ("clang_isFunctionTypeVariadic", - [Type], - bool), - - ("clang_isInvalid", - [CursorKind], - bool), - - ("clang_isPODType", - [Type], - bool), - - ("clang_isPreprocessing", - [CursorKind], - bool), - - ("clang_isReference", - [CursorKind], - bool), - - ("clang_isRestrictQualifiedType", - [Type], - bool), - - ("clang_isStatement", - [CursorKind], - bool), - - ("clang_isTranslationUnit", - [CursorKind], - bool), - - ("clang_isUnexposed", - [CursorKind], - bool), - - ("clang_isVirtualBase", - [Cursor], - bool), - - ("clang_isVolatileQualifiedType", - [Type], - bool), - - ("clang_parseTranslationUnit", - [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int], - c_object_p), - - ("clang_reparseTranslationUnit", - [TranslationUnit, c_int, c_void_p, c_int], - c_int), - - ("clang_saveTranslationUnit", - [TranslationUnit, c_interop_string, c_uint], - c_int), - - ("clang_tokenize", - [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), - - ("clang_visitChildren", - [Cursor, callbacks['cursor_visit'], py_object], - c_uint), - - ("clang_Cursor_getNumArguments", - [Cursor], - c_int), - - ("clang_Cursor_getArgument", - [Cursor, c_uint], - Cursor, - Cursor.from_result), - - ("clang_Cursor_getNumTemplateArguments", - [Cursor], - c_int), - - ("clang_Cursor_getTemplateArgumentKind", - [Cursor, c_uint], - TemplateArgumentKind.from_id), - - ("clang_Cursor_getTemplateArgumentType", - [Cursor, c_uint], - Type, - Type.from_result), - - ("clang_Cursor_getTemplateArgumentValue", - [Cursor, c_uint], - c_longlong), - - ("clang_Cursor_getTemplateArgumentUnsignedValue", - [Cursor, c_uint], - c_ulonglong), - - ("clang_Cursor_isAnonymous", - [Cursor], - bool), - - ("clang_Cursor_isBitField", - [Cursor], - bool), - - ("clang_Cursor_getBriefCommentText", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_Cursor_getRawCommentText", - [Cursor], - _CXString, - _CXString.from_result), - - ("clang_Cursor_getOffsetOfField", - [Cursor], - c_longlong), - - ("clang_Type_getAlignOf", - [Type], - c_longlong), - - ("clang_Type_getClassType", - [Type], - Type, - Type.from_result), - - ("clang_Type_getNumTemplateArguments", - [Type], - c_int), - - ("clang_Type_getTemplateArgumentAsType", - [Type, c_uint], - Type, - Type.from_result), - - ("clang_Type_getOffsetOf", - [Type, c_interop_string], - c_longlong), - - ("clang_Type_getSizeOf", - [Type], - c_longlong), - - ("clang_Type_getCXXRefQualifier", - [Type], - c_uint), - - ("clang_Type_getNamedType", - [Type], - Type, - Type.from_result), - - ("clang_Type_visitFields", - [Type, callbacks['fields_visit'], py_object], - c_uint), -] - -class LibclangError(Exception): - def __init__(self, message): - self.m = message - - def __str__(self): - return self.m - -def register_function(lib, item, ignore_errors): - # A function may not exist, if these bindings are used with an older or - # incompatible version of libclang.so. - try: - func = getattr(lib, item[0]) - except AttributeError as e: - msg = str(e) + ". Please ensure that your python bindings are "\ - "compatible with your libclang.so version." - if ignore_errors: - return - raise LibclangError(msg) - - if len(item) >= 2: - func.argtypes = item[1] - - if len(item) >= 3: - func.restype = item[2] - - if len(item) == 4: - func.errcheck = item[3] - -def register_functions(lib, ignore_errors): - """Register function prototypes with a libclang library instance. - - This must be called as part of library instantiation so Python knows how - to call out to the shared library. - """ - - def register(item): - return register_function(lib, item, ignore_errors) - - for f in functionList: - register(f) - -class Config(object): - library_path = None - library_file = None - compatibility_check = True - loaded = False - - @staticmethod - def set_library_path(path): - """Set the path in which to search for libclang""" - if Config.loaded: - raise Exception("library path must be set before before using " \ - "any other functionalities in libclang.") - - Config.library_path = fspath(path) - - @staticmethod - def set_library_file(filename): - """Set the exact location of libclang""" - if Config.loaded: - raise Exception("library file must be set before before using " \ - "any other functionalities in libclang.") - - Config.library_file = fspath(filename) - - @staticmethod - def set_compatibility_check(check_status): - """ Perform compatibility check when loading libclang - - The python bindings are only tested and evaluated with the version of - libclang they are provided with. To ensure correct behavior a (limited) - compatibility check is performed when loading the bindings. This check - will throw an exception, as soon as it fails. - - In case these bindings are used with an older version of libclang, parts - that have been stable between releases may still work. Users of the - python bindings can disable the compatibility check. This will cause - the python bindings to load, even though they are written for a newer - version of libclang. Failures now arise if unsupported or incompatible - features are accessed. The user is required to test themselves if the - features they are using are available and compatible between different - libclang versions. - """ - if Config.loaded: - raise Exception("compatibility_check must be set before before " \ - "using any other functionalities in libclang.") - - Config.compatibility_check = check_status - - @CachedProperty - def lib(self): - lib = self.get_cindex_library() - register_functions(lib, not Config.compatibility_check) - Config.loaded = True - return lib - - def get_filename(self): - if Config.library_file: - return Config.library_file - - import platform - name = platform.system() - - if name == 'Darwin': - file = 'libclang.dylib' - elif name == 'Windows': - file = 'libclang.dll' - else: - file = 'libclang.so' - - if Config.library_path: - file = Config.library_path + '/' + file - - return file - - def get_cindex_library(self): - try: - library = cdll.LoadLibrary(self.get_filename()) - except OSError as e: - msg = str(e) + ". To provide a path to libclang use " \ - "Config.set_library_path() or " \ - "Config.set_library_file()." - raise LibclangError(msg) - - return library - - def function_exists(self, name): - try: - getattr(self.lib, name) - except AttributeError: - return False - - return True - -def register_enumerations(): - for name, value in clang.enumerations.TokenKinds: - TokenKind.register(value, name) - -conf = Config() -register_enumerations() - -__all__ = [ - 'AvailabilityKind', - 'Config', - 'CodeCompletionResults', - 'CompilationDatabase', - 'CompileCommands', - 'CompileCommand', - 'CursorKind', - 'Cursor', - 'Diagnostic', - 'File', - 'FixIt', - 'Index', - 'LinkageKind', - 'SourceLocation', - 'SourceRange', - 'TLSKind', - 'TokenKind', - 'Token', - 'TranslationUnitLoadError', - 'TranslationUnit', - 'TypeKind', - 'Type', -] diff --git a/interpreter/llvm/src/tools/clang/bindings/python/clang/enumerations.py b/interpreter/llvm/src/tools/clang/bindings/python/clang/enumerations.py deleted file mode 100644 index 520e1346d3ebe..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/clang/enumerations.py +++ /dev/null @@ -1,33 +0,0 @@ -#===- enumerations.py - Python Enumerations ------------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -""" -Clang Enumerations -================== - -This module provides static definitions of enumerations that exist in libclang. - -Enumerations are typically defined as a list of tuples. The exported values are -typically munged into other types or classes at module load time. - -All enumerations are centrally defined in this file so they are all grouped -together and easier to audit. And, maybe even one day this file will be -automatically generated by scanning the libclang headers! -""" - -# Maps to CXTokenKind. Note that libclang maintains a separate set of token -# enumerations from the C++ API. -TokenKinds = [ - ('PUNCTUATION', 0), - ('KEYWORD', 1), - ('IDENTIFIER', 2), - ('LITERAL', 3), - ('COMMENT', 4), -] - -__all__ = ['TokenKinds'] diff --git a/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-dump.py b/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-dump.py deleted file mode 100644 index 46073b285cb36..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-dump.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env python - -#===- cindex-dump.py - cindex/Python Source Dump -------------*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -""" -A simple command line tool for dumping a source file using the Clang Index -Library. -""" - -def get_diag_info(diag): - return { 'severity' : diag.severity, - 'location' : diag.location, - 'spelling' : diag.spelling, - 'ranges' : diag.ranges, - 'fixits' : diag.fixits } - -def get_cursor_id(cursor, cursor_list = []): - if not opts.showIDs: - return None - - if cursor is None: - return None - - # FIXME: This is really slow. It would be nice if the index API exposed - # something that let us hash cursors. - for i,c in enumerate(cursor_list): - if cursor == c: - return i - cursor_list.append(cursor) - return len(cursor_list) - 1 - -def get_info(node, depth=0): - if opts.maxDepth is not None and depth >= opts.maxDepth: - children = None - else: - children = [get_info(c, depth+1) - for c in node.get_children()] - return { 'id' : get_cursor_id(node), - 'kind' : node.kind, - 'usr' : node.get_usr(), - 'spelling' : node.spelling, - 'location' : node.location, - 'extent.start' : node.extent.start, - 'extent.end' : node.extent.end, - 'is_definition' : node.is_definition(), - 'definition id' : get_cursor_id(node.get_definition()), - 'children' : children } - -def main(): - from clang.cindex import Index - from pprint import pprint - - from optparse import OptionParser, OptionGroup - - global opts - - parser = OptionParser("usage: %prog [options] {filename} [clang-args*]") - parser.add_option("", "--show-ids", dest="showIDs", - help="Compute cursor IDs (very slow)", - action="store_true", default=False) - parser.add_option("", "--max-depth", dest="maxDepth", - help="Limit cursor expansion to depth N", - metavar="N", type=int, default=None) - parser.disable_interspersed_args() - (opts, args) = parser.parse_args() - - if len(args) == 0: - parser.error('invalid number arguments') - - index = Index.create() - tu = index.parse(None, args) - if not tu: - parser.error("unable to load input") - - pprint(('diags', [get_diag_info(d) for d in tu.diagnostics])) - pprint(('nodes', get_info(tu.cursor))) - -if __name__ == '__main__': - main() - diff --git a/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-includes.py b/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-includes.py deleted file mode 100644 index ec1fbc0c3edb4..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/examples/cindex/cindex-includes.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python - -#===- cindex-includes.py - cindex/Python Inclusion Graph -----*- python -*--===# -# -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -#===------------------------------------------------------------------------===# - -""" -A simple command line tool for dumping a Graphviz description (dot) that -describes include dependencies. -""" - -def main(): - import sys - from clang.cindex import Index - - from optparse import OptionParser, OptionGroup - - parser = OptionParser("usage: %prog [options] {filename} [clang-args*]") - parser.disable_interspersed_args() - (opts, args) = parser.parse_args() - if len(args) == 0: - parser.error('invalid number arguments') - - # FIXME: Add an output file option - out = sys.stdout - - index = Index.create() - tu = index.parse(None, args) - if not tu: - parser.error("unable to load input") - - # A helper function for generating the node name. - def name(f): - if f: - return "\"" + f.name + "\"" - - # Generate the include graph - out.write("digraph G {\n") - for i in tu.get_includes(): - line = " "; - if i.is_input_file: - # Always write the input file as a node just in case it doesn't - # actually include anything. This would generate a 1 node graph. - line += name(i.include) - else: - line += '%s->%s' % (name(i.source), name(i.include)) - line += "\n"; - out.write(line) - out.write("}\n") - -if __name__ == '__main__': - main() - diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/CMakeLists.txt b/interpreter/llvm/src/tools/clang/bindings/python/tests/CMakeLists.txt deleted file mode 100644 index 280da9d006862..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -# Test target to run Python test suite from main build. - -add_custom_target(check-clang-python - COMMAND ${CMAKE_COMMAND} -E env - CLANG_LIBRARY_PATH=$ - "${Python3_EXECUTABLE}" -m unittest discover - DEPENDS libclang - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..) - -set(RUN_PYTHON_TESTS TRUE) -set_target_properties(check-clang-python PROPERTIES FOLDER "Clang tests") - -# Tests require libclang.so which is only built with LLVM_ENABLE_PIC=ON -if(NOT LLVM_ENABLE_PIC) - set(RUN_PYTHON_TESTS FALSE) -endif() - -# Do not try to run if libclang was built with sanitizers because -# the sanitizer library will likely be loaded too late to perform -# interception and will then fail. -# We could use LD_PRELOAD/DYLD_INSERT_LIBRARIES but this isn't -# portable so its easier just to not run the tests when building -# with ASan. -if(NOT LLVM_USE_SANITIZER STREQUAL "") - set(RUN_PYTHON_TESTS FALSE) -endif() - -# Tests fail on Windows, and need someone knowledgeable to fix. -# It's not clear whether it's a test or a valid binding problem. -if(WIN32) - set(RUN_PYTHON_TESTS FALSE) -endif() - -# The Python FFI interface is broken on AIX: https://bugs.python.org/issue38628. -if(${CMAKE_SYSTEM_NAME} MATCHES "AIX") - set(RUN_PYTHON_TESTS FALSE) -endif() - -# AArch64, Hexagon, and Sparc have known test failures that need to be -# addressed. -# SystemZ has broken Python/FFI interface: -# https://reviews.llvm.org/D52840#1265716 -if(${LLVM_NATIVE_ARCH} MATCHES "^(AArch64|Hexagon|Sparc|SystemZ)$") - set(RUN_PYTHON_TESTS FALSE) -endif() - -if(RUN_PYTHON_TESTS) - set_property(GLOBAL APPEND PROPERTY - LLVM_ADDITIONAL_TEST_TARGETS check-clang-python) -endif() diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/__init__.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h deleted file mode 100644 index b4eacbee37548..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef HEADER1 -#define HEADER1 - -#include "header3.h" - -#endif diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h deleted file mode 100644 index c4eddc0c5620c..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef HEADER2 -#define HEADER2 - -#include "header3.h" - -#endif diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h deleted file mode 100644 index 6dca764860e1e..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h +++ /dev/null @@ -1,3 +0,0 @@ -// Not a guarded header! - -void f(); diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp deleted file mode 100644 index 7ef086e56b2cb..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "stdio.h" - -int main(int argc, char* argv[]) { - printf("hello world\n"); - return 0; -} diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp deleted file mode 100644 index 60cfdaae4d092..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#include "header1.h" -#include "header2.h" -#include "header1.h" - -int main() { } diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c deleted file mode 100644 index 7196486c78a1f..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c +++ /dev/null @@ -1,2 +0,0 @@ -int DECL_ONE = 1; -int DECL_TWO = 2; diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/__init__.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_access_specifiers.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_access_specifiers.py deleted file mode 100644 index e36424f240aa0..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_access_specifiers.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import AccessSpecifier -from clang.cindex import Cursor -from clang.cindex import TranslationUnit - -from .util import get_cursor -from .util import get_tu - -import unittest - - -class TestAccessSpecifiers(unittest.TestCase): - def test_access_specifiers(self): - """Ensure that C++ access specifiers are available on cursors""" - - tu = get_tu(""" -class test_class { -public: - void public_member_function(); -protected: - void protected_member_function(); -private: - void private_member_function(); -}; -""", lang = 'cpp') - - test_class = get_cursor(tu, "test_class") - self.assertEqual(test_class.access_specifier, AccessSpecifier.INVALID) - - public = get_cursor(tu.cursor, "public_member_function") - self.assertEqual(public.access_specifier, AccessSpecifier.PUBLIC) - - protected = get_cursor(tu.cursor, "protected_member_function") - self.assertEqual(protected.access_specifier, AccessSpecifier.PROTECTED) - - private = get_cursor(tu.cursor, "private_member_function") - self.assertEqual(private.access_specifier, AccessSpecifier.PRIVATE) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cdb.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cdb.py deleted file mode 100644 index 99bc72143beff..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cdb.py +++ /dev/null @@ -1,141 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import CompilationDatabase -from clang.cindex import CompilationDatabaseError -from clang.cindex import CompileCommands -from clang.cindex import CompileCommand -import os -import gc -import unittest -import sys -from .util import skip_if_no_fspath -from .util import str_to_path - - -kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') - - -@unittest.skipIf(sys.platform == 'win32', "TODO: Fix these tests on Windows") -class TestCDB(unittest.TestCase): - def test_create_fail(self): - """Check we fail loading a database with an assertion""" - path = os.path.dirname(__file__) - - # clang_CompilationDatabase_fromDirectory calls fprintf(stderr, ...) - # Suppress its output. - stderr = os.dup(2) - with open(os.devnull, 'wb') as null: - os.dup2(null.fileno(), 2) - with self.assertRaises(CompilationDatabaseError) as cm: - cdb = CompilationDatabase.fromDirectory(path) - os.dup2(stderr, 2) - os.close(stderr) - - e = cm.exception - self.assertEqual(e.cdb_error, - CompilationDatabaseError.ERROR_CANNOTLOADDATABASE) - - def test_create(self): - """Check we can load a compilation database""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - - def test_lookup_succeed(self): - """Check we get some results if the file exists in the db""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') - self.assertNotEqual(len(cmds), 0) - - @skip_if_no_fspath - def test_lookup_succeed_pathlike(self): - """Same as test_lookup_succeed, but with PathLikes""" - cdb = CompilationDatabase.fromDirectory(str_to_path(kInputsDir)) - cmds = cdb.getCompileCommands(str_to_path('/home/john.doe/MyProject/project.cpp')) - self.assertNotEqual(len(cmds), 0) - - def test_all_compilecommand(self): - """Check we get all results from the db""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - cmds = cdb.getAllCompileCommands() - self.assertEqual(len(cmds), 3) - expected = [ - { 'wd': '/home/john.doe/MyProject', - 'file': '/home/john.doe/MyProject/project.cpp', - 'line': ['clang++', '--driver-mode=g++', '-o', 'project.o', '-c', - '/home/john.doe/MyProject/project.cpp']}, - { 'wd': '/home/john.doe/MyProjectA', - 'file': '/home/john.doe/MyProject/project2.cpp', - 'line': ['clang++', '--driver-mode=g++', '-o', 'project2.o', '-c', - '/home/john.doe/MyProject/project2.cpp']}, - { 'wd': '/home/john.doe/MyProjectB', - 'file': '/home/john.doe/MyProject/project2.cpp', - 'line': ['clang++', '--driver-mode=g++', '-DFEATURE=1', '-o', - 'project2-feature.o', '-c', - '/home/john.doe/MyProject/project2.cpp']}, - - ] - for i in range(len(cmds)): - self.assertEqual(cmds[i].directory, expected[i]['wd']) - self.assertEqual(cmds[i].filename, expected[i]['file']) - for arg, exp in zip(cmds[i].arguments, expected[i]['line']): - self.assertEqual(arg, exp) - - def test_1_compilecommand(self): - """Check file with single compile command""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - file = '/home/john.doe/MyProject/project.cpp' - cmds = cdb.getCompileCommands(file) - self.assertEqual(len(cmds), 1) - self.assertEqual(cmds[0].directory, os.path.dirname(file)) - self.assertEqual(cmds[0].filename, file) - expected = [ 'clang++', '--driver-mode=g++', '-o', 'project.o', '-c', - '/home/john.doe/MyProject/project.cpp'] - for arg, exp in zip(cmds[0].arguments, expected): - self.assertEqual(arg, exp) - - def test_2_compilecommand(self): - """Check file with 2 compile commands""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp') - self.assertEqual(len(cmds), 2) - expected = [ - { 'wd': '/home/john.doe/MyProjectA', - 'line': ['clang++', '--driver-mode=g++', '-o', 'project2.o', '-c', - '/home/john.doe/MyProject/project2.cpp']}, - { 'wd': '/home/john.doe/MyProjectB', - 'line': ['clang++', '--driver-mode=g++', '-DFEATURE=1', '-o', - 'project2-feature.o', '-c', - '/home/john.doe/MyProject/project2.cpp']} - ] - for i in range(len(cmds)): - self.assertEqual(cmds[i].directory, expected[i]['wd']) - for arg, exp in zip(cmds[i].arguments, expected[i]['line']): - self.assertEqual(arg, exp) - - def test_compilecommand_iterator_stops(self): - """Check that iterator stops after the correct number of elements""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - count = 0 - for cmd in cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp'): - count += 1 - self.assertLessEqual(count, 2) - - def test_compilationDB_references(self): - """Ensure CompilationsCommands are independent of the database""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') - del cdb - gc.collect() - workingdir = cmds[0].directory - - def test_compilationCommands_references(self): - """Ensure CompilationsCommand keeps a reference to CompilationCommands""" - cdb = CompilationDatabase.fromDirectory(kInputsDir) - cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') - del cdb - cmd0 = cmds[0] - del cmds - gc.collect() - workingdir = cmd0.directory diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_code_completion.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_code_completion.py deleted file mode 100644 index 1603d3dfc17a8..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_code_completion.py +++ /dev/null @@ -1,112 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import TranslationUnit - -import unittest -from .util import skip_if_no_fspath -from .util import str_to_path - - -class TestCodeCompletion(unittest.TestCase): - def check_completion_results(self, cr, expected): - self.assertIsNotNone(cr) - self.assertEqual(len(cr.diagnostics), 0) - - completions = [str(c) for c in cr.results] - - for c in expected: - self.assertIn(c, completions) - - def test_code_complete(self): - files = [('fake.c', """ -/// Aaa. -int test1; - -/// Bbb. -void test2(void); - -void f() { - -} -""")] - - tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files, - options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION) - - cr = tu.codeComplete('fake.c', 9, 1, unsaved_files=files, include_brief_comments=True) - - expected = [ - "{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.", - "{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.", - "{'return', TypedText} | {';', SemiColon} || Priority: 40 || Availability: Available || Brief comment: None" - ] - self.check_completion_results(cr, expected) - - @skip_if_no_fspath - def test_code_complete_pathlike(self): - files = [(str_to_path('fake.c'), """ -/// Aaa. -int test1; - -/// Bbb. -void test2(void); - -void f() { - -} -""")] - - tu = TranslationUnit.from_source(str_to_path('fake.c'), ['-std=c99'], unsaved_files=files, - options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION) - - cr = tu.codeComplete(str_to_path('fake.c'), 9, 1, unsaved_files=files, include_brief_comments=True) - - expected = [ - "{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.", - "{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.", - "{'return', TypedText} | {';', SemiColon} || Priority: 40 || Availability: Available || Brief comment: None" - ] - self.check_completion_results(cr, expected) - - def test_code_complete_availability(self): - files = [('fake.cpp', """ -class P { -protected: - int member; -}; - -class Q : public P { -public: - using P::member; -}; - -void f(P x, Q y) { - x.; // member is inaccessible - y.; // member is accessible -} -""")] - - tu = TranslationUnit.from_source('fake.cpp', ['-std=c++98'], unsaved_files=files) - - cr = tu.codeComplete('fake.cpp', 12, 5, unsaved_files=files) - - expected = [ - "{'const', TypedText} || Priority: 50 || Availability: Available || Brief comment: None", - "{'volatile', TypedText} || Priority: 50 || Availability: Available || Brief comment: None", - "{'operator', TypedText} || Priority: 40 || Availability: Available || Brief comment: None", - "{'P', TypedText} || Priority: 50 || Availability: Available || Brief comment: None", - "{'Q', TypedText} || Priority: 50 || Availability: Available || Brief comment: None" - ] - self.check_completion_results(cr, expected) - - cr = tu.codeComplete('fake.cpp', 13, 5, unsaved_files=files) - expected = [ - "{'P', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None", - "{'P &', ResultType} | {'operator=', TypedText} | {'(', LeftParen} | {'const P &', Placeholder} | {')', RightParen} || Priority: 79 || Availability: Available || Brief comment: None", - "{'int', ResultType} | {'member', TypedText} || Priority: 35 || Availability: NotAccessible || Brief comment: None", - "{'void', ResultType} | {'~P', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 79 || Availability: Available || Brief comment: None" - ] - self.check_completion_results(cr, expected) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_comment.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_comment.py deleted file mode 100644 index 73fb617ae1681..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_comment.py +++ /dev/null @@ -1,47 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import TranslationUnit -from tests.cindex.util import get_cursor - -import unittest - - -class TestComment(unittest.TestCase): - def test_comment(self): - files = [('fake.c', """ -/// Aaa. -int test1; - -/// Bbb. -/// x -void test2(void); - -void f() { - -} -""")] - # make a comment-aware TU - tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files, - options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION) - test1 = get_cursor(tu, 'test1') - self.assertIsNotNone(test1, "Could not find test1.") - self.assertTrue(test1.type.is_pod()) - raw = test1.raw_comment - brief = test1.brief_comment - self.assertEqual(raw, """/// Aaa.""") - self.assertEqual(brief, """Aaa.""") - - test2 = get_cursor(tu, 'test2') - raw = test2.raw_comment - brief = test2.brief_comment - self.assertEqual(raw, """/// Bbb.\n/// x""") - self.assertEqual(brief, """Bbb. x""") - - f = get_cursor(tu, 'f') - raw = f.raw_comment - brief = f.brief_comment - self.assertIsNone(raw) - self.assertIsNone(brief) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor.py deleted file mode 100644 index ef875e9724748..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor.py +++ /dev/null @@ -1,569 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -import ctypes -import gc -import unittest - -from clang.cindex import AvailabilityKind -from clang.cindex import CursorKind -from clang.cindex import TemplateArgumentKind -from clang.cindex import TranslationUnit -from clang.cindex import TypeKind -from .util import get_cursor -from .util import get_cursors -from .util import get_tu - - -kInput = """\ -struct s0 { - int a; - int b; -}; - -struct s1; - -void f0(int a0, int a1) { - int l0, l1; - - if (a0) - return; - - for (;;) { - break; - } -} -""" - -kParentTest = """\ - class C { - void f(); - } - - void C::f() { } - """ - -kTemplateArgTest = """\ - template - void foo(); - - template<> - void foo<-7, float, true>(); - """ - -class TestCursor(unittest.TestCase): - def test_get_children(self): - tu = get_tu(kInput) - - it = tu.cursor.get_children() - tu_nodes = list(it) - - self.assertEqual(len(tu_nodes), 3) - for cursor in tu_nodes: - self.assertIsNotNone(cursor.translation_unit) - - self.assertNotEqual(tu_nodes[0], tu_nodes[1]) - self.assertEqual(tu_nodes[0].kind, CursorKind.STRUCT_DECL) - self.assertEqual(tu_nodes[0].spelling, 's0') - self.assertEqual(tu_nodes[0].is_definition(), True) - self.assertEqual(tu_nodes[0].location.file.name, 't.c') - self.assertEqual(tu_nodes[0].location.line, 1) - self.assertEqual(tu_nodes[0].location.column, 8) - self.assertGreater(tu_nodes[0].hash, 0) - self.assertIsNotNone(tu_nodes[0].translation_unit) - - s0_nodes = list(tu_nodes[0].get_children()) - self.assertEqual(len(s0_nodes), 2) - self.assertEqual(s0_nodes[0].kind, CursorKind.FIELD_DECL) - self.assertEqual(s0_nodes[0].spelling, 'a') - self.assertEqual(s0_nodes[0].type.kind, TypeKind.INT) - self.assertEqual(s0_nodes[1].kind, CursorKind.FIELD_DECL) - self.assertEqual(s0_nodes[1].spelling, 'b') - self.assertEqual(s0_nodes[1].type.kind, TypeKind.INT) - - self.assertEqual(tu_nodes[1].kind, CursorKind.STRUCT_DECL) - self.assertEqual(tu_nodes[1].spelling, 's1') - self.assertEqual(tu_nodes[1].displayname, 's1') - self.assertEqual(tu_nodes[1].is_definition(), False) - - self.assertEqual(tu_nodes[2].kind, CursorKind.FUNCTION_DECL) - self.assertEqual(tu_nodes[2].spelling, 'f0') - self.assertEqual(tu_nodes[2].displayname, 'f0(int, int)') - self.assertEqual(tu_nodes[2].is_definition(), True) - - def test_references(self): - """Ensure that references to TranslationUnit are kept.""" - tu = get_tu('int x;') - cursors = list(tu.cursor.get_children()) - self.assertGreater(len(cursors), 0) - - cursor = cursors[0] - self.assertIsInstance(cursor.translation_unit, TranslationUnit) - - # Delete reference to TU and perform a full GC. - del tu - gc.collect() - self.assertIsInstance(cursor.translation_unit, TranslationUnit) - - # If the TU was destroyed, this should cause a segfault. - parent = cursor.semantic_parent - - def test_canonical(self): - source = 'struct X; struct X; struct X { int member; };' - tu = get_tu(source) - - cursors = [] - for cursor in tu.cursor.get_children(): - if cursor.spelling == 'X': - cursors.append(cursor) - - self.assertEqual(len(cursors), 3) - self.assertEqual(cursors[1].canonical, cursors[2].canonical) - - def test_is_const_method(self): - """Ensure Cursor.is_const_method works.""" - source = 'class X { void foo() const; void bar(); };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - self.assertIsNotNone(cls) - self.assertIsNotNone(foo) - self.assertIsNotNone(bar) - - self.assertTrue(foo.is_const_method()) - self.assertFalse(bar.is_const_method()) - - def test_is_converting_constructor(self): - """Ensure Cursor.is_converting_constructor works.""" - source = 'class X { explicit X(int); X(double); X(); };' - tu = get_tu(source, lang='cpp') - - xs = get_cursors(tu, 'X') - - self.assertEqual(len(xs), 4) - self.assertEqual(xs[0].kind, CursorKind.CLASS_DECL) - cs = xs[1:] - self.assertEqual(cs[0].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[1].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[2].kind, CursorKind.CONSTRUCTOR) - - self.assertFalse(cs[0].is_converting_constructor()) - self.assertTrue(cs[1].is_converting_constructor()) - self.assertFalse(cs[2].is_converting_constructor()) - - - def test_is_copy_constructor(self): - """Ensure Cursor.is_copy_constructor works.""" - source = 'class X { X(); X(const X&); X(X&&); };' - tu = get_tu(source, lang='cpp') - - xs = get_cursors(tu, 'X') - self.assertEqual(xs[0].kind, CursorKind.CLASS_DECL) - cs = xs[1:] - self.assertEqual(cs[0].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[1].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[2].kind, CursorKind.CONSTRUCTOR) - - self.assertFalse(cs[0].is_copy_constructor()) - self.assertTrue(cs[1].is_copy_constructor()) - self.assertFalse(cs[2].is_copy_constructor()) - - def test_is_default_constructor(self): - """Ensure Cursor.is_default_constructor works.""" - source = 'class X { X(); X(int); };' - tu = get_tu(source, lang='cpp') - - xs = get_cursors(tu, 'X') - self.assertEqual(xs[0].kind, CursorKind.CLASS_DECL) - cs = xs[1:] - self.assertEqual(cs[0].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[1].kind, CursorKind.CONSTRUCTOR) - - self.assertTrue(cs[0].is_default_constructor()) - self.assertFalse(cs[1].is_default_constructor()) - - def test_is_move_constructor(self): - """Ensure Cursor.is_move_constructor works.""" - source = 'class X { X(); X(const X&); X(X&&); };' - tu = get_tu(source, lang='cpp') - - xs = get_cursors(tu, 'X') - self.assertEqual(xs[0].kind, CursorKind.CLASS_DECL) - cs = xs[1:] - self.assertEqual(cs[0].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[1].kind, CursorKind.CONSTRUCTOR) - self.assertEqual(cs[2].kind, CursorKind.CONSTRUCTOR) - - self.assertFalse(cs[0].is_move_constructor()) - self.assertFalse(cs[1].is_move_constructor()) - self.assertTrue(cs[2].is_move_constructor()) - - def test_is_default_method(self): - """Ensure Cursor.is_default_method works.""" - source = 'class X { X() = default; }; class Y { Y(); };' - tu = get_tu(source, lang='cpp') - - xs = get_cursors(tu, 'X') - ys = get_cursors(tu, 'Y') - - self.assertEqual(len(xs), 2) - self.assertEqual(len(ys), 2) - - xc = xs[1] - yc = ys[1] - - self.assertTrue(xc.is_default_method()) - self.assertFalse(yc.is_default_method()) - - def test_is_mutable_field(self): - """Ensure Cursor.is_mutable_field works.""" - source = 'class X { int x_; mutable int y_; };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - x_ = get_cursor(tu, 'x_') - y_ = get_cursor(tu, 'y_') - self.assertIsNotNone(cls) - self.assertIsNotNone(x_) - self.assertIsNotNone(y_) - - self.assertFalse(x_.is_mutable_field()) - self.assertTrue(y_.is_mutable_field()) - - def test_is_static_method(self): - """Ensure Cursor.is_static_method works.""" - - source = 'class X { static void foo(); void bar(); };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - self.assertIsNotNone(cls) - self.assertIsNotNone(foo) - self.assertIsNotNone(bar) - - self.assertTrue(foo.is_static_method()) - self.assertFalse(bar.is_static_method()) - - def test_is_pure_virtual_method(self): - """Ensure Cursor.is_pure_virtual_method works.""" - source = 'class X { virtual void foo() = 0; virtual void bar(); };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - self.assertIsNotNone(cls) - self.assertIsNotNone(foo) - self.assertIsNotNone(bar) - - self.assertTrue(foo.is_pure_virtual_method()) - self.assertFalse(bar.is_pure_virtual_method()) - - def test_is_virtual_method(self): - """Ensure Cursor.is_virtual_method works.""" - source = 'class X { virtual void foo(); void bar(); };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - self.assertIsNotNone(cls) - self.assertIsNotNone(foo) - self.assertIsNotNone(bar) - - self.assertTrue(foo.is_virtual_method()) - self.assertFalse(bar.is_virtual_method()) - - def test_is_abstract_record(self): - """Ensure Cursor.is_abstract_record works.""" - source = 'struct X { virtual void x() = 0; }; struct Y : X { void x(); };' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - self.assertTrue(cls.is_abstract_record()) - - cls = get_cursor(tu, 'Y') - self.assertFalse(cls.is_abstract_record()) - - def test_is_scoped_enum(self): - """Ensure Cursor.is_scoped_enum works.""" - source = 'class X {}; enum RegularEnum {}; enum class ScopedEnum {};' - tu = get_tu(source, lang='cpp') - - cls = get_cursor(tu, 'X') - regular_enum = get_cursor(tu, 'RegularEnum') - scoped_enum = get_cursor(tu, 'ScopedEnum') - self.assertIsNotNone(cls) - self.assertIsNotNone(regular_enum) - self.assertIsNotNone(scoped_enum) - - self.assertFalse(cls.is_scoped_enum()) - self.assertFalse(regular_enum.is_scoped_enum()) - self.assertTrue(scoped_enum.is_scoped_enum()) - - def test_underlying_type(self): - tu = get_tu('typedef int foo;') - typedef = get_cursor(tu, 'foo') - self.assertIsNotNone(typedef) - - self.assertTrue(typedef.kind.is_declaration()) - underlying = typedef.underlying_typedef_type - self.assertEqual(underlying.kind, TypeKind.INT) - - def test_semantic_parent(self): - tu = get_tu(kParentTest, 'cpp') - curs = get_cursors(tu, 'f') - decl = get_cursor(tu, 'C') - self.assertEqual(len(curs), 2) - self.assertEqual(curs[0].semantic_parent, curs[1].semantic_parent) - self.assertEqual(curs[0].semantic_parent, decl) - - def test_lexical_parent(self): - tu = get_tu(kParentTest, 'cpp') - curs = get_cursors(tu, 'f') - decl = get_cursor(tu, 'C') - self.assertEqual(len(curs), 2) - self.assertNotEqual(curs[0].lexical_parent, curs[1].lexical_parent) - self.assertEqual(curs[0].lexical_parent, decl) - self.assertEqual(curs[1].lexical_parent, tu.cursor) - - def test_enum_type(self): - tu = get_tu('enum TEST { FOO=1, BAR=2 };') - enum = get_cursor(tu, 'TEST') - self.assertIsNotNone(enum) - - self.assertEqual(enum.kind, CursorKind.ENUM_DECL) - enum_type = enum.enum_type - self.assertIn(enum_type.kind, (TypeKind.UINT, TypeKind.INT)) - - def test_enum_type_cpp(self): - tu = get_tu('enum TEST : long long { FOO=1, BAR=2 };', lang="cpp") - enum = get_cursor(tu, 'TEST') - self.assertIsNotNone(enum) - - self.assertEqual(enum.kind, CursorKind.ENUM_DECL) - self.assertEqual(enum.enum_type.kind, TypeKind.LONGLONG) - - def test_objc_type_encoding(self): - tu = get_tu('int i;', lang='objc') - i = get_cursor(tu, 'i') - - self.assertIsNotNone(i) - self.assertEqual(i.objc_type_encoding, 'i') - - def test_enum_values(self): - tu = get_tu('enum TEST { SPAM=1, EGG, HAM = EGG * 20};') - enum = get_cursor(tu, 'TEST') - self.assertIsNotNone(enum) - - self.assertEqual(enum.kind, CursorKind.ENUM_DECL) - - enum_constants = list(enum.get_children()) - self.assertEqual(len(enum_constants), 3) - - spam, egg, ham = enum_constants - - self.assertEqual(spam.kind, CursorKind.ENUM_CONSTANT_DECL) - self.assertEqual(spam.enum_value, 1) - self.assertEqual(egg.kind, CursorKind.ENUM_CONSTANT_DECL) - self.assertEqual(egg.enum_value, 2) - self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) - self.assertEqual(ham.enum_value, 40) - - def test_enum_values_cpp(self): - tu = get_tu('enum TEST : long long { SPAM = -1, HAM = 0x10000000000};', lang="cpp") - enum = get_cursor(tu, 'TEST') - self.assertIsNotNone(enum) - - self.assertEqual(enum.kind, CursorKind.ENUM_DECL) - - enum_constants = list(enum.get_children()) - self.assertEqual(len(enum_constants), 2) - - spam, ham = enum_constants - - self.assertEqual(spam.kind, CursorKind.ENUM_CONSTANT_DECL) - self.assertEqual(spam.enum_value, -1) - self.assertEqual(ham.kind, CursorKind.ENUM_CONSTANT_DECL) - self.assertEqual(ham.enum_value, 0x10000000000) - - def test_annotation_attribute(self): - tu = get_tu('int foo (void) __attribute__ ((annotate("here be annotation attribute")));') - - foo = get_cursor(tu, 'foo') - self.assertIsNotNone(foo) - - for c in foo.get_children(): - if c.kind == CursorKind.ANNOTATE_ATTR: - self.assertEqual(c.displayname, "here be annotation attribute") - break - else: - self.fail("Couldn't find annotation") - - def test_annotation_template(self): - annotation = '__attribute__ ((annotate("annotation")))' - for source, kind in [ - ('int foo (T value) %s;', CursorKind.FUNCTION_TEMPLATE), - ('class %s foo {};', CursorKind.CLASS_TEMPLATE), - ]: - source = 'template ' + (source % annotation) - tu = get_tu(source, lang="cpp") - - foo = get_cursor(tu, 'foo') - self.assertIsNotNone(foo) - self.assertEqual(foo.kind, kind) - - for c in foo.get_children(): - if c.kind == CursorKind.ANNOTATE_ATTR: - self.assertEqual(c.displayname, "annotation") - break - else: - self.fail("Couldn't find annotation for {}".format(kind)) - - def test_result_type(self): - tu = get_tu('int foo();') - foo = get_cursor(tu, 'foo') - - self.assertIsNotNone(foo) - t = foo.result_type - self.assertEqual(t.kind, TypeKind.INT) - - def test_result_type_objc_method_decl(self): - code = """\ - @interface Interface : NSObject - -(void)voidMethod; - @end - """ - tu = get_tu(code, lang='objc') - cursor = get_cursor(tu, 'voidMethod') - result_type = cursor.result_type - self.assertEqual(cursor.kind, CursorKind.OBJC_INSTANCE_METHOD_DECL) - self.assertEqual(result_type.kind, TypeKind.VOID) - - def test_availability(self): - tu = get_tu('class A { A(A const&) = delete; };', lang='cpp') - - # AvailabilityKind.AVAILABLE - cursor = get_cursor(tu, 'A') - self.assertEqual(cursor.kind, CursorKind.CLASS_DECL) - self.assertEqual(cursor.availability, AvailabilityKind.AVAILABLE) - - # AvailabilityKind.NOT_AVAILABLE - cursors = get_cursors(tu, 'A') - for c in cursors: - if c.kind == CursorKind.CONSTRUCTOR: - self.assertEqual(c.availability, AvailabilityKind.NOT_AVAILABLE) - break - else: - self.fail("Could not find cursor for deleted constructor") - - # AvailabilityKind.DEPRECATED - tu = get_tu('void test() __attribute__((deprecated));', lang='cpp') - cursor = get_cursor(tu, 'test') - self.assertEqual(cursor.availability, AvailabilityKind.DEPRECATED) - - # AvailabilityKind.NOT_ACCESSIBLE is only used in the code completion results - - def test_get_tokens(self): - """Ensure we can map cursors back to tokens.""" - tu = get_tu('int foo(int i);') - foo = get_cursor(tu, 'foo') - - tokens = list(foo.get_tokens()) - self.assertEqual(len(tokens), 6) - self.assertEqual(tokens[0].spelling, 'int') - self.assertEqual(tokens[1].spelling, 'foo') - - def test_get_token_cursor(self): - """Ensure we can map tokens to cursors.""" - tu = get_tu('class A {}; int foo(A var = A());', lang='cpp') - foo = get_cursor(tu, 'foo') - - for cursor in foo.walk_preorder(): - if cursor.kind.is_expression() and not cursor.kind.is_statement(): - break - else: - self.fail("Could not find default value expression") - - tokens = list(cursor.get_tokens()) - self.assertEqual(len(tokens), 4, [t.spelling for t in tokens]) - self.assertEqual(tokens[0].spelling, '=') - self.assertEqual(tokens[1].spelling, 'A') - self.assertEqual(tokens[2].spelling, '(') - self.assertEqual(tokens[3].spelling, ')') - t_cursor = tokens[1].cursor - self.assertEqual(t_cursor.kind, CursorKind.TYPE_REF) - r_cursor = t_cursor.referenced # should not raise an exception - self.assertEqual(r_cursor.kind, CursorKind.CLASS_DECL) - - def test_get_arguments(self): - tu = get_tu('void foo(int i, int j);') - foo = get_cursor(tu, 'foo') - arguments = list(foo.get_arguments()) - - self.assertEqual(len(arguments), 2) - self.assertEqual(arguments[0].spelling, "i") - self.assertEqual(arguments[1].spelling, "j") - - def test_get_num_template_arguments(self): - tu = get_tu(kTemplateArgTest, lang='cpp') - foos = get_cursors(tu, 'foo') - - self.assertEqual(foos[1].get_num_template_arguments(), 3) - - def test_get_template_argument_kind(self): - tu = get_tu(kTemplateArgTest, lang='cpp') - foos = get_cursors(tu, 'foo') - - self.assertEqual(foos[1].get_template_argument_kind(0), TemplateArgumentKind.INTEGRAL) - self.assertEqual(foos[1].get_template_argument_kind(1), TemplateArgumentKind.TYPE) - self.assertEqual(foos[1].get_template_argument_kind(2), TemplateArgumentKind.INTEGRAL) - - def test_get_template_argument_type(self): - tu = get_tu(kTemplateArgTest, lang='cpp') - foos = get_cursors(tu, 'foo') - - self.assertEqual(foos[1].get_template_argument_type(1).kind, TypeKind.FLOAT) - - def test_get_template_argument_value(self): - tu = get_tu(kTemplateArgTest, lang='cpp') - foos = get_cursors(tu, 'foo') - - self.assertEqual(foos[1].get_template_argument_value(0), -7) - self.assertEqual(foos[1].get_template_argument_value(2), True) - - def test_get_template_argument_unsigned_value(self): - tu = get_tu(kTemplateArgTest, lang='cpp') - foos = get_cursors(tu, 'foo') - - self.assertEqual(foos[1].get_template_argument_unsigned_value(0), 2 ** 32 - 7) - self.assertEqual(foos[1].get_template_argument_unsigned_value(2), True) - - def test_referenced(self): - tu = get_tu('void foo(); void bar() { foo(); }') - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - for c in bar.get_children(): - if c.kind == CursorKind.CALL_EXPR: - self.assertEqual(c.referenced.spelling, foo.spelling) - break - - def test_mangled_name(self): - kInputForMangling = """\ - int foo(int, int); - """ - tu = get_tu(kInputForMangling, lang='cpp') - foo = get_cursor(tu, 'foo') - - # Since libclang does not link in targets, we cannot pass a triple to it - # and force the target. To enable this test to pass on all platforms, accept - # all valid manglings. - # [c-index-test handles this by running the source through clang, emitting - # an AST file and running libclang on that AST file] - self.assertIn(foo.mangled_name, ('_Z3fooii', '__Z3fooii', '?foo@@YAHHH', '?foo@@YAHHH@Z')) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py deleted file mode 100644 index ed245d593d551..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py +++ /dev/null @@ -1,58 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import CursorKind - -import unittest - - -class TestCursorKind(unittest.TestCase): - def test_name(self): - self.assertEqual(CursorKind.UNEXPOSED_DECL.name, 'UNEXPOSED_DECL') - - def test_get_all_kinds(self): - kinds = CursorKind.get_all_kinds() - self.assertIn(CursorKind.UNEXPOSED_DECL, kinds) - self.assertIn(CursorKind.TRANSLATION_UNIT, kinds) - self.assertIn(CursorKind.VARIABLE_REF, kinds) - self.assertIn(CursorKind.LAMBDA_EXPR, kinds) - self.assertIn(CursorKind.OBJ_BOOL_LITERAL_EXPR, kinds) - self.assertIn(CursorKind.OBJ_SELF_EXPR, kinds) - self.assertIn(CursorKind.MS_ASM_STMT, kinds) - self.assertIn(CursorKind.MODULE_IMPORT_DECL, kinds) - self.assertIn(CursorKind.TYPE_ALIAS_TEMPLATE_DECL, kinds) - - def test_kind_groups(self): - """Check that every kind classifies to exactly one group.""" - - self.assertTrue(CursorKind.UNEXPOSED_DECL.is_declaration()) - self.assertTrue(CursorKind.TYPE_REF.is_reference()) - self.assertTrue(CursorKind.DECL_REF_EXPR.is_expression()) - self.assertTrue(CursorKind.UNEXPOSED_STMT.is_statement()) - self.assertTrue(CursorKind.INVALID_FILE.is_invalid()) - - self.assertTrue(CursorKind.TRANSLATION_UNIT.is_translation_unit()) - self.assertFalse(CursorKind.TYPE_REF.is_translation_unit()) - - self.assertTrue(CursorKind.PREPROCESSING_DIRECTIVE.is_preprocessing()) - self.assertFalse(CursorKind.TYPE_REF.is_preprocessing()) - - self.assertTrue(CursorKind.UNEXPOSED_DECL.is_unexposed()) - self.assertFalse(CursorKind.TYPE_REF.is_unexposed()) - - for k in CursorKind.get_all_kinds(): - group = [n for n in ('is_declaration', 'is_reference', 'is_expression', - 'is_statement', 'is_invalid', 'is_attribute') - if getattr(k, n)()] - - if k in ( CursorKind.TRANSLATION_UNIT, - CursorKind.MACRO_DEFINITION, - CursorKind.MACRO_INSTANTIATION, - CursorKind.INCLUSION_DIRECTIVE, - CursorKind.PREPROCESSING_DIRECTIVE, - CursorKind.OVERLOAD_CANDIDATE): - self.assertEqual(len(group), 0) - else: - self.assertEqual(len(group), 1) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_diagnostics.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_diagnostics.py deleted file mode 100644 index 8b0f042568833..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_diagnostics.py +++ /dev/null @@ -1,110 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import * -from .util import get_tu - -import unittest - - -# FIXME: We need support for invalid translation units to test better. - - -class TestDiagnostics(unittest.TestCase): - def test_diagnostic_warning(self): - tu = get_tu('int f0() {}\n') - self.assertEqual(len(tu.diagnostics), 1) - self.assertEqual(tu.diagnostics[0].severity, Diagnostic.Warning) - self.assertEqual(tu.diagnostics[0].location.line, 1) - self.assertEqual(tu.diagnostics[0].location.column, 11) - self.assertEqual(tu.diagnostics[0].spelling, - 'non-void function does not return a value') - - def test_diagnostic_note(self): - # FIXME: We aren't getting notes here for some reason. - tu = get_tu('#define A x\nvoid *A = 1;\n') - self.assertEqual(len(tu.diagnostics), 1) - self.assertEqual(tu.diagnostics[0].severity, Diagnostic.Warning) - self.assertEqual(tu.diagnostics[0].location.line, 2) - self.assertEqual(tu.diagnostics[0].location.column, 7) - self.assertIn('incompatible', tu.diagnostics[0].spelling) -# self.assertEqual(tu.diagnostics[1].severity, Diagnostic.Note) -# self.assertEqual(tu.diagnostics[1].location.line, 1) -# self.assertEqual(tu.diagnostics[1].location.column, 11) -# self.assertEqual(tu.diagnostics[1].spelling, 'instantiated from') - - def test_diagnostic_fixit(self): - tu = get_tu('struct { int f0; } x = { f0 : 1 };') - self.assertEqual(len(tu.diagnostics), 1) - self.assertEqual(tu.diagnostics[0].severity, Diagnostic.Warning) - self.assertEqual(tu.diagnostics[0].location.line, 1) - self.assertEqual(tu.diagnostics[0].location.column, 26) - self.assertRegex(tu.diagnostics[0].spelling, - 'use of GNU old-style.*') - self.assertEqual(len(tu.diagnostics[0].fixits), 1) - self.assertEqual(tu.diagnostics[0].fixits[0].range.start.line, 1) - self.assertEqual(tu.diagnostics[0].fixits[0].range.start.column, 26) - self.assertEqual(tu.diagnostics[0].fixits[0].range.end.line, 1) - self.assertEqual(tu.diagnostics[0].fixits[0].range.end.column, 30) - self.assertEqual(tu.diagnostics[0].fixits[0].value, '.f0 = ') - - def test_diagnostic_range(self): - tu = get_tu('void f() { int i = "a"; }') - self.assertEqual(len(tu.diagnostics), 1) - self.assertEqual(tu.diagnostics[0].severity, Diagnostic.Warning) - self.assertEqual(tu.diagnostics[0].location.line, 1) - self.assertEqual(tu.diagnostics[0].location.column, 16) - self.assertRegex(tu.diagnostics[0].spelling, - 'incompatible pointer to.*') - self.assertEqual(len(tu.diagnostics[0].fixits), 0) - self.assertEqual(len(tu.diagnostics[0].ranges), 1) - self.assertEqual(tu.diagnostics[0].ranges[0].start.line, 1) - self.assertEqual(tu.diagnostics[0].ranges[0].start.column, 20) - self.assertEqual(tu.diagnostics[0].ranges[0].end.line, 1) - self.assertEqual(tu.diagnostics[0].ranges[0].end.column, 23) - with self.assertRaises(IndexError): - tu.diagnostics[0].ranges[1].start.line - - def test_diagnostic_category(self): - """Ensure that category properties work.""" - tu = get_tu('int f(int i) { return 7; }', all_warnings=True) - self.assertEqual(len(tu.diagnostics), 1) - d = tu.diagnostics[0] - - self.assertEqual(d.severity, Diagnostic.Warning) - self.assertEqual(d.location.line, 1) - self.assertEqual(d.location.column, 11) - - self.assertEqual(d.category_number, 2) - self.assertEqual(d.category_name, 'Semantic Issue') - - def test_diagnostic_option(self): - """Ensure that category option properties work.""" - tu = get_tu('int f(int i) { return 7; }', all_warnings=True) - self.assertEqual(len(tu.diagnostics), 1) - d = tu.diagnostics[0] - - self.assertEqual(d.option, '-Wunused-parameter') - self.assertEqual(d.disable_option, '-Wno-unused-parameter') - - def test_diagnostic_children(self): - tu = get_tu('void f(int x) {} void g() { f(); }') - self.assertEqual(len(tu.diagnostics), 1) - d = tu.diagnostics[0] - - children = d.children - self.assertEqual(len(children), 1) - self.assertEqual(children[0].severity, Diagnostic.Note) - self.assertRegex(children[0].spelling, - '.*declared here') - self.assertEqual(children[0].location.line, 1) - self.assertEqual(children[0].location.column, 6) - - def test_diagnostic_string_repr(self): - tu = get_tu('struct MissingSemicolon{}') - self.assertEqual(len(tu.diagnostics), 1) - d = tu.diagnostics[0] - - self.assertEqual(repr(d), ', spelling "expected \';\' after struct">') diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_exception_specification_kind.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_exception_specification_kind.py deleted file mode 100644 index 6c13f70fb2565..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_exception_specification_kind.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -import clang.cindex -from clang.cindex import ExceptionSpecificationKind -from .util import get_tu - -import unittest - - -def find_function_declarations(node, declarations=[]): - if node.kind == clang.cindex.CursorKind.FUNCTION_DECL: - declarations.append((node.spelling, node.exception_specification_kind)) - for child in node.get_children(): - declarations = find_function_declarations(child, declarations) - return declarations - - -class TestExceptionSpecificationKind(unittest.TestCase): - def test_exception_specification_kind(self): - source = """int square1(int x); - int square2(int x) noexcept; - int square3(int x) noexcept(noexcept(x * x));""" - - tu = get_tu(source, lang='cpp', flags=['-std=c++14']) - - declarations = find_function_declarations(tu.cursor) - expected = [ - ('square1', ExceptionSpecificationKind.NONE), - ('square2', ExceptionSpecificationKind.BASIC_NOEXCEPT), - ('square3', ExceptionSpecificationKind.COMPUTED_NOEXCEPT) - ] - self.assertListEqual(declarations, expected) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_file.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_file.py deleted file mode 100644 index a146fe5c9239c..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_file.py +++ /dev/null @@ -1,18 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import Index, File - -import unittest - - -class TestFile(unittest.TestCase): - def test_file(self): - index = Index.create() - tu = index.parse('t.c', unsaved_files = [('t.c', "")]) - file = File.from_name(tu, "t.c") - self.assertEqual(str(file), "t.c") - self.assertEqual(file.name, "t.c") - self.assertEqual(repr(file), "") diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_index.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_index.py deleted file mode 100644 index 46aafcf222e73..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_index.py +++ /dev/null @@ -1,26 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import * -import os -import unittest - - -kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') - - -class TestIndex(unittest.TestCase): - def test_create(self): - index = Index.create() - - # FIXME: test Index.read - - def test_parse(self): - index = Index.create() - self.assertIsInstance(index, Index) - tu = index.parse(os.path.join(kInputsDir, 'hello.cpp')) - self.assertIsInstance(tu, TranslationUnit) - tu = index.parse(None, ['-c', os.path.join(kInputsDir, 'hello.cpp')]) - self.assertIsInstance(tu, TranslationUnit) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_linkage.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_linkage.py deleted file mode 100644 index cdd97fc2df0dc..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_linkage.py +++ /dev/null @@ -1,38 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import LinkageKind -from clang.cindex import Cursor -from clang.cindex import TranslationUnit - -from .util import get_cursor -from .util import get_tu - -import unittest - - -class TestLinkage(unittest.TestCase): - def test_linkage(self): - """Ensure that linkage specifers are available on cursors""" - - tu = get_tu(""" -void foo() { int no_linkage; } -static int internal; -namespace { struct unique_external_type {} } -unique_external_type unique_external; -extern int external; -""", lang = 'cpp') - - no_linkage = get_cursor(tu.cursor, 'no_linkage') - self.assertEqual(no_linkage.linkage, LinkageKind.NO_LINKAGE) - - internal = get_cursor(tu.cursor, 'internal') - self.assertEqual(internal.linkage, LinkageKind.INTERNAL) - - unique_external = get_cursor(tu.cursor, 'unique_external') - self.assertEqual(unique_external.linkage, LinkageKind.UNIQUE_EXTERNAL) - - external = get_cursor(tu.cursor, 'external') - self.assertEqual(external.linkage, LinkageKind.EXTERNAL) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_location.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_location.py deleted file mode 100644 index fbe9770d7ebc5..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_location.py +++ /dev/null @@ -1,105 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import Cursor -from clang.cindex import File -from clang.cindex import SourceLocation -from clang.cindex import SourceRange -from .util import get_cursor -from .util import get_tu - -import unittest - - -baseInput="int one;\nint two;\n" - - -class TestLocation(unittest.TestCase): - def assert_location(self, loc, line, column, offset): - self.assertEqual(loc.line, line) - self.assertEqual(loc.column, column) - self.assertEqual(loc.offset, offset) - - def test_location(self): - tu = get_tu(baseInput) - one = get_cursor(tu, 'one') - two = get_cursor(tu, 'two') - - self.assertIsNotNone(one) - self.assertIsNotNone(two) - - self.assert_location(one.location,line=1,column=5,offset=4) - self.assert_location(two.location,line=2,column=5,offset=13) - - # adding a linebreak at top should keep columns same - tu = get_tu('\n' + baseInput) - one = get_cursor(tu, 'one') - two = get_cursor(tu, 'two') - - self.assertIsNotNone(one) - self.assertIsNotNone(two) - - self.assert_location(one.location,line=2,column=5,offset=5) - self.assert_location(two.location,line=3,column=5,offset=14) - - # adding a space should affect column on first line only - tu = get_tu(' ' + baseInput) - one = get_cursor(tu, 'one') - two = get_cursor(tu, 'two') - - self.assert_location(one.location,line=1,column=6,offset=5) - self.assert_location(two.location,line=2,column=5,offset=14) - - # define the expected location ourselves and see if it matches - # the returned location - tu = get_tu(baseInput) - - file = File.from_name(tu, 't.c') - location = SourceLocation.from_position(tu, file, 1, 5) - cursor = Cursor.from_location(tu, location) - - one = get_cursor(tu, 'one') - self.assertIsNotNone(one) - self.assertEqual(one, cursor) - - # Ensure locations referring to the same entity are equivalent. - location2 = SourceLocation.from_position(tu, file, 1, 5) - self.assertEqual(location, location2) - location3 = SourceLocation.from_position(tu, file, 1, 4) - self.assertNotEqual(location2, location3) - - offset_location = SourceLocation.from_offset(tu, file, 5) - cursor = Cursor.from_location(tu, offset_location) - verified = False - for n in [n for n in tu.cursor.get_children() if n.spelling == 'one']: - self.assertEqual(n, cursor) - verified = True - - self.assertTrue(verified) - - def test_extent(self): - tu = get_tu(baseInput) - one = get_cursor(tu, 'one') - two = get_cursor(tu, 'two') - - self.assert_location(one.extent.start,line=1,column=1,offset=0) - self.assert_location(one.extent.end,line=1,column=8,offset=7) - self.assertEqual(baseInput[one.extent.start.offset:one.extent.end.offset], "int one") - - self.assert_location(two.extent.start,line=2,column=1,offset=9) - self.assert_location(two.extent.end,line=2,column=8,offset=16) - self.assertEqual(baseInput[two.extent.start.offset:two.extent.end.offset], "int two") - - file = File.from_name(tu, 't.c') - location1 = SourceLocation.from_position(tu, file, 1, 1) - location2 = SourceLocation.from_position(tu, file, 1, 8) - - range1 = SourceRange.from_locations(location1, location2) - range2 = SourceRange.from_locations(location1, location2) - self.assertEqual(range1, range2) - - location3 = SourceLocation.from_position(tu, file, 1, 6) - range3 = SourceRange.from_locations(location1, location3) - self.assertNotEqual(range1, range3) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tls_kind.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tls_kind.py deleted file mode 100644 index c828ac83a468d..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tls_kind.py +++ /dev/null @@ -1,54 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import TLSKind -from clang.cindex import Cursor -from clang.cindex import TranslationUnit - -from .util import get_cursor -from .util import get_tu - -import unittest - - -class TestTLSKind(unittest.TestCase): - def test_tls_kind(self): - """Ensure that thread-local storage kinds are available on cursors.""" - - tu = get_tu(""" -int tls_none; -thread_local int tls_dynamic; -_Thread_local int tls_static; -""", lang = 'cpp') - - tls_none = get_cursor(tu.cursor, 'tls_none') - self.assertEqual(tls_none.tls_kind, TLSKind.NONE) - - tls_dynamic = get_cursor(tu.cursor, 'tls_dynamic') - self.assertEqual(tls_dynamic.tls_kind, TLSKind.DYNAMIC) - - tls_static = get_cursor(tu.cursor, 'tls_static') - self.assertEqual(tls_static.tls_kind, TLSKind.STATIC) - - # The following case tests '__declspec(thread)'. Since it is a Microsoft - # specific extension, specific flags are required for the parser to pick - # these up. - flags = ['-fms-extensions', '-target', 'x86_64-unknown-windows-win32', - '-fms-compatibility-version=18'] - tu = get_tu(""" -__declspec(thread) int tls_declspec_msvc18; -""", lang = 'cpp', flags=flags) - - tls_declspec_msvc18 = get_cursor(tu.cursor, 'tls_declspec_msvc18') - self.assertEqual(tls_declspec_msvc18.tls_kind, TLSKind.STATIC) - - flags = ['-fms-extensions', '-target', 'x86_64-unknown-windows-win32', - '-fms-compatibility-version=19'] - tu = get_tu(""" -__declspec(thread) int tls_declspec_msvc19; -""", lang = 'cpp', flags=flags) - - tls_declspec_msvc19 = get_cursor(tu.cursor, 'tls_declspec_msvc19') - self.assertEqual(tls_declspec_msvc19.tls_kind, TLSKind.DYNAMIC) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_token_kind.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_token_kind.py deleted file mode 100644 index 904e007cafc50..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_token_kind.py +++ /dev/null @@ -1,49 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import TokenKind - -import unittest - - -class TestTokenKind(unittest.TestCase): - def test_constructor(self): - """Ensure TokenKind constructor works as expected.""" - - t = TokenKind(5, 'foo') - - self.assertEqual(t.value, 5) - self.assertEqual(t.name, 'foo') - - def test_bad_register(self): - """Ensure a duplicate value is rejected for registration.""" - - with self.assertRaises(ValueError): - TokenKind.register(2, 'foo') - - def test_unknown_value(self): - """Ensure trying to fetch an unknown value raises.""" - - with self.assertRaises(ValueError): - TokenKind.from_value(-1) - - def test_registration(self): - """Ensure that items registered appear as class attributes.""" - self.assertTrue(hasattr(TokenKind, 'LITERAL')) - literal = TokenKind.LITERAL - - self.assertIsInstance(literal, TokenKind) - - def test_from_value(self): - """Ensure registered values can be obtained from from_value().""" - t = TokenKind.from_value(3) - self.assertIsInstance(t, TokenKind) - self.assertEqual(t, TokenKind.LITERAL) - - def test_repr(self): - """Ensure repr() works.""" - - r = repr(TokenKind.LITERAL) - self.assertEqual(r, 'TokenKind.LITERAL') diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tokens.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tokens.py deleted file mode 100644 index dd6d3a3259edc..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_tokens.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from clang.cindex import CursorKind -from clang.cindex import Index -from clang.cindex import SourceLocation -from clang.cindex import SourceRange -from clang.cindex import TokenKind - -from .util import get_tu - -import unittest - - -class TestTokens(unittest.TestCase): - def test_token_to_cursor(self): - """Ensure we can obtain a Cursor from a Token instance.""" - tu = get_tu('int i = 5;') - r = tu.get_extent('t.c', (0, 9)) - tokens = list(tu.get_tokens(extent=r)) - - self.assertEqual(len(tokens), 4) - self.assertEqual(tokens[1].spelling, 'i') - self.assertEqual(tokens[1].kind, TokenKind.IDENTIFIER) - - cursor = tokens[1].cursor - self.assertEqual(cursor.kind, CursorKind.VAR_DECL) - self.assertEqual(tokens[1].cursor, tokens[2].cursor) - - def test_token_location(self): - """Ensure Token.location works.""" - - tu = get_tu('int foo = 10;') - r = tu.get_extent('t.c', (0, 11)) - - tokens = list(tu.get_tokens(extent=r)) - self.assertEqual(len(tokens), 4) - - loc = tokens[1].location - self.assertIsInstance(loc, SourceLocation) - self.assertEqual(loc.line, 1) - self.assertEqual(loc.column, 5) - self.assertEqual(loc.offset, 4) - - def test_token_extent(self): - """Ensure Token.extent works.""" - tu = get_tu('int foo = 10;') - r = tu.get_extent('t.c', (0, 11)) - - tokens = list(tu.get_tokens(extent=r)) - self.assertEqual(len(tokens), 4) - - extent = tokens[1].extent - self.assertIsInstance(extent, SourceRange) - - self.assertEqual(extent.start.offset, 4) - self.assertEqual(extent.end.offset, 7) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_translation_unit.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_translation_unit.py deleted file mode 100644 index f3e770a936117..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_translation_unit.py +++ /dev/null @@ -1,338 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -from contextlib import contextmanager -import gc -import os -import sys -import tempfile -import unittest - -from clang.cindex import CursorKind -from clang.cindex import Cursor -from clang.cindex import File -from clang.cindex import Index -from clang.cindex import SourceLocation -from clang.cindex import SourceRange -from clang.cindex import TranslationUnitSaveError -from clang.cindex import TranslationUnitLoadError -from clang.cindex import TranslationUnit -from .util import get_cursor -from .util import get_tu -from .util import skip_if_no_fspath -from .util import str_to_path - - -kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') - - -@contextmanager -def save_tu(tu): - """Convenience API to save a TranslationUnit to a file. - - Returns the filename it was saved to. - """ - with tempfile.NamedTemporaryFile() as t: - tu.save(t.name) - yield t.name - - -@contextmanager -def save_tu_pathlike(tu): - """Convenience API to save a TranslationUnit to a file. - - Returns the filename it was saved to. - """ - with tempfile.NamedTemporaryFile() as t: - tu.save(str_to_path(t.name)) - yield t.name - - -class TestTranslationUnit(unittest.TestCase): - def test_spelling(self): - path = os.path.join(kInputsDir, 'hello.cpp') - tu = TranslationUnit.from_source(path) - self.assertEqual(tu.spelling, path) - - def test_cursor(self): - path = os.path.join(kInputsDir, 'hello.cpp') - tu = get_tu(path) - c = tu.cursor - self.assertIsInstance(c, Cursor) - self.assertIs(c.kind, CursorKind.TRANSLATION_UNIT) - - def test_parse_arguments(self): - path = os.path.join(kInputsDir, 'parse_arguments.c') - tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) - spellings = [c.spelling for c in tu.cursor.get_children()] - self.assertEqual(spellings[-2], 'hello') - self.assertEqual(spellings[-1], 'hi') - - def test_reparse_arguments(self): - path = os.path.join(kInputsDir, 'parse_arguments.c') - tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) - tu.reparse() - spellings = [c.spelling for c in tu.cursor.get_children()] - self.assertEqual(spellings[-2], 'hello') - self.assertEqual(spellings[-1], 'hi') - - def test_unsaved_files(self): - tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files = [ - ('fake.c', """ -#include "fake.h" -int x; -int SOME_DEFINE; -"""), - ('./fake.h', """ -#define SOME_DEFINE y -""") - ]) - spellings = [c.spelling for c in tu.cursor.get_children()] - self.assertEqual(spellings[-2], 'x') - self.assertEqual(spellings[-1], 'y') - - def test_unsaved_files_2(self): - if sys.version_info.major >= 3: - from io import StringIO - else: - from io import BytesIO as StringIO - tu = TranslationUnit.from_source('fake.c', unsaved_files = [ - ('fake.c', StringIO('int x;'))]) - spellings = [c.spelling for c in tu.cursor.get_children()] - self.assertEqual(spellings[-1], 'x') - - @skip_if_no_fspath - def test_from_source_accepts_pathlike(self): - tu = TranslationUnit.from_source(str_to_path('fake.c'), ['-Iincludes'], unsaved_files = [ - (str_to_path('fake.c'), """ -#include "fake.h" - int x; - int SOME_DEFINE; - """), - (str_to_path('includes/fake.h'), """ -#define SOME_DEFINE y - """) - ]) - spellings = [c.spelling for c in tu.cursor.get_children()] - self.assertEqual(spellings[-2], 'x') - self.assertEqual(spellings[-1], 'y') - - def assert_normpaths_equal(self, path1, path2): - """ Compares two paths for equality after normalizing them with - os.path.normpath - """ - self.assertEqual(os.path.normpath(path1), - os.path.normpath(path2)) - - def test_includes(self): - def eq(expected, actual): - if not actual.is_input_file: - self.assert_normpaths_equal(expected[0], actual.source.name) - self.assert_normpaths_equal(expected[1], actual.include.name) - else: - self.assert_normpaths_equal(expected[1], actual.include.name) - - src = os.path.join(kInputsDir, 'include.cpp') - h1 = os.path.join(kInputsDir, "header1.h") - h2 = os.path.join(kInputsDir, "header2.h") - h3 = os.path.join(kInputsDir, "header3.h") - inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)] - - tu = TranslationUnit.from_source(src) - for i in zip(inc, tu.get_includes()): - eq(i[0], i[1]) - - def test_inclusion_directive(self): - src = os.path.join(kInputsDir, 'include.cpp') - h1 = os.path.join(kInputsDir, "header1.h") - h2 = os.path.join(kInputsDir, "header2.h") - h3 = os.path.join(kInputsDir, "header3.h") - inc = [h1, h3, h2, h3, h1] - - tu = TranslationUnit.from_source(src, options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD) - inclusion_directive_files = [c.get_included_file().name for c in tu.cursor.get_children() if c.kind == CursorKind.INCLUSION_DIRECTIVE] - for i in zip(inc, inclusion_directive_files): - self.assert_normpaths_equal(i[0], i[1]) - - def test_save(self): - """Ensure TranslationUnit.save() works.""" - - tu = get_tu('int foo();') - - with save_tu(tu) as path: - self.assertTrue(os.path.exists(path)) - self.assertGreater(os.path.getsize(path), 0) - - @skip_if_no_fspath - def test_save_pathlike(self): - """Ensure TranslationUnit.save() works with PathLike filename.""" - - tu = get_tu('int foo();') - - with save_tu_pathlike(tu) as path: - self.assertTrue(os.path.exists(path)) - self.assertGreater(os.path.getsize(path), 0) - - def test_save_translation_errors(self): - """Ensure that saving to an invalid directory raises.""" - - tu = get_tu('int foo();') - - path = '/does/not/exist/llvm-test.ast' - self.assertFalse(os.path.exists(os.path.dirname(path))) - - with self.assertRaises(TranslationUnitSaveError) as cm: - tu.save(path) - ex = cm.exception - expected = TranslationUnitSaveError.ERROR_UNKNOWN - self.assertEqual(ex.save_error, expected) - - def test_load(self): - """Ensure TranslationUnits can be constructed from saved files.""" - - tu = get_tu('int foo();') - self.assertEqual(len(tu.diagnostics), 0) - with save_tu(tu) as path: - self.assertTrue(os.path.exists(path)) - self.assertGreater(os.path.getsize(path), 0) - - tu2 = TranslationUnit.from_ast_file(filename=path) - self.assertEqual(len(tu2.diagnostics), 0) - - foo = get_cursor(tu2, 'foo') - self.assertIsNotNone(foo) - - # Just in case there is an open file descriptor somewhere. - del tu2 - - @skip_if_no_fspath - def test_load_pathlike(self): - """Ensure TranslationUnits can be constructed from saved files - - PathLike variant.""" - tu = get_tu('int foo();') - self.assertEqual(len(tu.diagnostics), 0) - with save_tu(tu) as path: - tu2 = TranslationUnit.from_ast_file(filename=str_to_path(path)) - self.assertEqual(len(tu2.diagnostics), 0) - - foo = get_cursor(tu2, 'foo') - self.assertIsNotNone(foo) - - # Just in case there is an open file descriptor somewhere. - del tu2 - - def test_index_parse(self): - path = os.path.join(kInputsDir, 'hello.cpp') - index = Index.create() - tu = index.parse(path) - self.assertIsInstance(tu, TranslationUnit) - - def test_get_file(self): - """Ensure tu.get_file() works appropriately.""" - - tu = get_tu('int foo();') - - f = tu.get_file('t.c') - self.assertIsInstance(f, File) - self.assertEqual(f.name, 't.c') - - with self.assertRaises(Exception): - f = tu.get_file('foobar.cpp') - - @skip_if_no_fspath - def test_get_file_pathlike(self): - """Ensure tu.get_file() works appropriately with PathLike filenames.""" - - tu = get_tu('int foo();') - - f = tu.get_file(str_to_path('t.c')) - self.assertIsInstance(f, File) - self.assertEqual(f.name, 't.c') - - with self.assertRaises(Exception): - f = tu.get_file(str_to_path('foobar.cpp')) - - def test_get_source_location(self): - """Ensure tu.get_source_location() works.""" - - tu = get_tu('int foo();') - - location = tu.get_location('t.c', 2) - self.assertIsInstance(location, SourceLocation) - self.assertEqual(location.offset, 2) - self.assertEqual(location.file.name, 't.c') - - location = tu.get_location('t.c', (1, 3)) - self.assertIsInstance(location, SourceLocation) - self.assertEqual(location.line, 1) - self.assertEqual(location.column, 3) - self.assertEqual(location.file.name, 't.c') - - def test_get_source_range(self): - """Ensure tu.get_source_range() works.""" - - tu = get_tu('int foo();') - - r = tu.get_extent('t.c', (1,4)) - self.assertIsInstance(r, SourceRange) - self.assertEqual(r.start.offset, 1) - self.assertEqual(r.end.offset, 4) - self.assertEqual(r.start.file.name, 't.c') - self.assertEqual(r.end.file.name, 't.c') - - r = tu.get_extent('t.c', ((1,2), (1,3))) - self.assertIsInstance(r, SourceRange) - self.assertEqual(r.start.line, 1) - self.assertEqual(r.start.column, 2) - self.assertEqual(r.end.line, 1) - self.assertEqual(r.end.column, 3) - self.assertEqual(r.start.file.name, 't.c') - self.assertEqual(r.end.file.name, 't.c') - - start = tu.get_location('t.c', 0) - end = tu.get_location('t.c', 5) - - r = tu.get_extent('t.c', (start, end)) - self.assertIsInstance(r, SourceRange) - self.assertEqual(r.start.offset, 0) - self.assertEqual(r.end.offset, 5) - self.assertEqual(r.start.file.name, 't.c') - self.assertEqual(r.end.file.name, 't.c') - - def test_get_tokens_gc(self): - """Ensures get_tokens() works properly with garbage collection.""" - - tu = get_tu('int foo();') - r = tu.get_extent('t.c', (0, 10)) - tokens = list(tu.get_tokens(extent=r)) - - self.assertEqual(tokens[0].spelling, 'int') - gc.collect() - self.assertEqual(tokens[0].spelling, 'int') - - del tokens[1] - gc.collect() - self.assertEqual(tokens[0].spelling, 'int') - - # May trigger segfault if we don't do our job properly. - del tokens - gc.collect() - gc.collect() # Just in case. - - def test_fail_from_source(self): - path = os.path.join(kInputsDir, 'non-existent.cpp') - try: - tu = TranslationUnit.from_source(path) - except TranslationUnitLoadError: - tu = None - self.assertEqual(tu, None) - - def test_fail_from_ast_file(self): - path = os.path.join(kInputsDir, 'non-existent.ast') - try: - tu = TranslationUnit.from_ast_file(path) - except TranslationUnitLoadError: - tu = None - self.assertEqual(tu, None) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_type.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_type.py deleted file mode 100644 index bcdbeff9d99c4..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/test_type.py +++ /dev/null @@ -1,468 +0,0 @@ -import os -from clang.cindex import Config -if 'CLANG_LIBRARY_PATH' in os.environ: - Config.set_library_path(os.environ['CLANG_LIBRARY_PATH']) - -import gc -import unittest - -from clang.cindex import CursorKind -from clang.cindex import TranslationUnit -from clang.cindex import TypeKind -from .util import get_cursor -from .util import get_tu - - -kInput = """\ - -typedef int I; - -struct teststruct { - int a; - I b; - long c; - unsigned long d; - signed long e; - const int f; - int *g; - int ***h; -}; - -""" - - -constarrayInput=""" -struct teststruct { - void *A[2]; -}; -""" - - -class TestType(unittest.TestCase): - def test_a_struct(self): - tu = get_tu(kInput) - - teststruct = get_cursor(tu, 'teststruct') - self.assertIsNotNone(teststruct, "Could not find teststruct.") - fields = list(teststruct.get_children()) - - self.assertEqual(fields[0].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[0].translation_unit) - self.assertEqual(fields[0].spelling, 'a') - self.assertFalse(fields[0].type.is_const_qualified()) - self.assertEqual(fields[0].type.kind, TypeKind.INT) - self.assertEqual(fields[0].type.get_canonical().kind, TypeKind.INT) - self.assertEqual(fields[0].type.get_typedef_name(), '') - - self.assertEqual(fields[1].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[1].translation_unit) - self.assertEqual(fields[1].spelling, 'b') - self.assertFalse(fields[1].type.is_const_qualified()) - self.assertEqual(fields[1].type.kind, TypeKind.TYPEDEF) - self.assertEqual(fields[1].type.get_canonical().kind, TypeKind.INT) - self.assertEqual(fields[1].type.get_declaration().spelling, 'I') - self.assertEqual(fields[1].type.get_typedef_name(), 'I') - - self.assertEqual(fields[2].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[2].translation_unit) - self.assertEqual(fields[2].spelling, 'c') - self.assertFalse(fields[2].type.is_const_qualified()) - self.assertEqual(fields[2].type.kind, TypeKind.LONG) - self.assertEqual(fields[2].type.get_canonical().kind, TypeKind.LONG) - self.assertEqual(fields[2].type.get_typedef_name(), '') - - self.assertEqual(fields[3].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[3].translation_unit) - self.assertEqual(fields[3].spelling, 'd') - self.assertFalse(fields[3].type.is_const_qualified()) - self.assertEqual(fields[3].type.kind, TypeKind.ULONG) - self.assertEqual(fields[3].type.get_canonical().kind, TypeKind.ULONG) - self.assertEqual(fields[3].type.get_typedef_name(), '') - - self.assertEqual(fields[4].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[4].translation_unit) - self.assertEqual(fields[4].spelling, 'e') - self.assertFalse(fields[4].type.is_const_qualified()) - self.assertEqual(fields[4].type.kind, TypeKind.LONG) - self.assertEqual(fields[4].type.get_canonical().kind, TypeKind.LONG) - self.assertEqual(fields[4].type.get_typedef_name(), '') - - self.assertEqual(fields[5].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[5].translation_unit) - self.assertEqual(fields[5].spelling, 'f') - self.assertTrue(fields[5].type.is_const_qualified()) - self.assertEqual(fields[5].type.kind, TypeKind.INT) - self.assertEqual(fields[5].type.get_canonical().kind, TypeKind.INT) - self.assertEqual(fields[5].type.get_typedef_name(), '') - - self.assertEqual(fields[6].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[6].translation_unit) - self.assertEqual(fields[6].spelling, 'g') - self.assertFalse(fields[6].type.is_const_qualified()) - self.assertEqual(fields[6].type.kind, TypeKind.POINTER) - self.assertEqual(fields[6].type.get_pointee().kind, TypeKind.INT) - self.assertEqual(fields[6].type.get_typedef_name(), '') - - self.assertEqual(fields[7].kind, CursorKind.FIELD_DECL) - self.assertIsNotNone(fields[7].translation_unit) - self.assertEqual(fields[7].spelling, 'h') - self.assertFalse(fields[7].type.is_const_qualified()) - self.assertEqual(fields[7].type.kind, TypeKind.POINTER) - self.assertEqual(fields[7].type.get_pointee().kind, TypeKind.POINTER) - self.assertEqual(fields[7].type.get_pointee().get_pointee().kind, TypeKind.POINTER) - self.assertEqual(fields[7].type.get_pointee().get_pointee().get_pointee().kind, TypeKind.INT) - self.assertEqual(fields[7].type.get_typedef_name(), '') - - def test_references(self): - """Ensure that a Type maintains a reference to a TranslationUnit.""" - - tu = get_tu('int x;') - children = list(tu.cursor.get_children()) - self.assertGreater(len(children), 0) - - cursor = children[0] - t = cursor.type - - self.assertIsInstance(t.translation_unit, TranslationUnit) - - # Delete main TranslationUnit reference and force a GC. - del tu - gc.collect() - self.assertIsInstance(t.translation_unit, TranslationUnit) - - # If the TU was destroyed, this should cause a segfault. - decl = t.get_declaration() - - def testConstantArray(self): - tu = get_tu(constarrayInput) - - teststruct = get_cursor(tu, 'teststruct') - self.assertIsNotNone(teststruct, "Didn't find teststruct??") - fields = list(teststruct.get_children()) - self.assertEqual(fields[0].spelling, 'A') - self.assertEqual(fields[0].type.kind, TypeKind.CONSTANTARRAY) - self.assertIsNotNone(fields[0].type.get_array_element_type()) - self.assertEqual(fields[0].type.get_array_element_type().kind, TypeKind.POINTER) - self.assertEqual(fields[0].type.get_array_size(), 2) - - def test_equal(self): - """Ensure equivalence operators work on Type.""" - source = 'int a; int b; void *v;' - tu = get_tu(source) - - a = get_cursor(tu, 'a') - b = get_cursor(tu, 'b') - v = get_cursor(tu, 'v') - - self.assertIsNotNone(a) - self.assertIsNotNone(b) - self.assertIsNotNone(v) - - self.assertEqual(a.type, b.type) - self.assertNotEqual(a.type, v.type) - - self.assertNotEqual(a.type, None) - self.assertNotEqual(a.type, 'foo') - - def test_type_spelling(self): - """Ensure Type.spelling works.""" - tu = get_tu('int c[5]; void f(int i[]); int x; int v[x];') - c = get_cursor(tu, 'c') - i = get_cursor(tu, 'i') - x = get_cursor(tu, 'x') - v = get_cursor(tu, 'v') - self.assertIsNotNone(c) - self.assertIsNotNone(i) - self.assertIsNotNone(x) - self.assertIsNotNone(v) - self.assertEqual(c.type.spelling, "int [5]") - self.assertEqual(i.type.spelling, "int []") - self.assertEqual(x.type.spelling, "int") - self.assertEqual(v.type.spelling, "int [x]") - - def test_typekind_spelling(self): - """Ensure TypeKind.spelling works.""" - tu = get_tu('int a;') - a = get_cursor(tu, 'a') - - self.assertIsNotNone(a) - self.assertEqual(a.type.kind.spelling, 'Int') - - def test_function_argument_types(self): - """Ensure that Type.argument_types() works as expected.""" - tu = get_tu('void f(int, int);') - f = get_cursor(tu, 'f') - self.assertIsNotNone(f) - - args = f.type.argument_types() - self.assertIsNotNone(args) - self.assertEqual(len(args), 2) - - t0 = args[0] - self.assertIsNotNone(t0) - self.assertEqual(t0.kind, TypeKind.INT) - - t1 = args[1] - self.assertIsNotNone(t1) - self.assertEqual(t1.kind, TypeKind.INT) - - args2 = list(args) - self.assertEqual(len(args2), 2) - self.assertEqual(t0, args2[0]) - self.assertEqual(t1, args2[1]) - - def test_argument_types_string_key(self): - """Ensure that non-int keys raise a TypeError.""" - tu = get_tu('void f(int, int);') - f = get_cursor(tu, 'f') - self.assertIsNotNone(f) - - args = f.type.argument_types() - self.assertEqual(len(args), 2) - - with self.assertRaises(TypeError): - args['foo'] - - def test_argument_types_negative_index(self): - """Ensure that negative indexes on argument_types Raises an IndexError.""" - tu = get_tu('void f(int, int);') - f = get_cursor(tu, 'f') - args = f.type.argument_types() - - with self.assertRaises(IndexError): - args[-1] - - def test_argument_types_overflow_index(self): - """Ensure that indexes beyond the length of Type.argument_types() raise.""" - tu = get_tu('void f(int, int);') - f = get_cursor(tu, 'f') - args = f.type.argument_types() - - with self.assertRaises(IndexError): - args[2] - - def test_argument_types_invalid_type(self): - """Ensure that obtaining argument_types on a Type without them raises.""" - tu = get_tu('int i;') - i = get_cursor(tu, 'i') - self.assertIsNotNone(i) - - with self.assertRaises(Exception): - i.type.argument_types() - - def test_is_pod(self): - """Ensure Type.is_pod() works.""" - tu = get_tu('int i; void f();') - i = get_cursor(tu, 'i') - f = get_cursor(tu, 'f') - - self.assertIsNotNone(i) - self.assertIsNotNone(f) - - self.assertTrue(i.type.is_pod()) - self.assertFalse(f.type.is_pod()) - - def test_function_variadic(self): - """Ensure Type.is_function_variadic works.""" - - source =""" -#include - - void foo(int a, ...); - void bar(int a, int b); - """ - - tu = get_tu(source) - foo = get_cursor(tu, 'foo') - bar = get_cursor(tu, 'bar') - - self.assertIsNotNone(foo) - self.assertIsNotNone(bar) - - self.assertIsInstance(foo.type.is_function_variadic(), bool) - self.assertTrue(foo.type.is_function_variadic()) - self.assertFalse(bar.type.is_function_variadic()) - - def test_element_type(self): - """Ensure Type.element_type works.""" - tu = get_tu('int c[5]; void f(int i[]); int x; int v[x];') - c = get_cursor(tu, 'c') - i = get_cursor(tu, 'i') - v = get_cursor(tu, 'v') - self.assertIsNotNone(c) - self.assertIsNotNone(i) - self.assertIsNotNone(v) - - self.assertEqual(c.type.kind, TypeKind.CONSTANTARRAY) - self.assertEqual(c.type.element_type.kind, TypeKind.INT) - self.assertEqual(i.type.kind, TypeKind.INCOMPLETEARRAY) - self.assertEqual(i.type.element_type.kind, TypeKind.INT) - self.assertEqual(v.type.kind, TypeKind.VARIABLEARRAY) - self.assertEqual(v.type.element_type.kind, TypeKind.INT) - - def test_invalid_element_type(self): - """Ensure Type.element_type raises if type doesn't have elements.""" - tu = get_tu('int i;') - i = get_cursor(tu, 'i') - self.assertIsNotNone(i) - with self.assertRaises(Exception): - i.element_type - - def test_element_count(self): - """Ensure Type.element_count works.""" - tu = get_tu('int i[5]; int j;') - i = get_cursor(tu, 'i') - j = get_cursor(tu, 'j') - - self.assertIsNotNone(i) - self.assertIsNotNone(j) - - self.assertEqual(i.type.element_count, 5) - - with self.assertRaises(Exception): - j.type.element_count - - def test_is_volatile_qualified(self): - """Ensure Type.is_volatile_qualified works.""" - - tu = get_tu('volatile int i = 4; int j = 2;') - - i = get_cursor(tu, 'i') - j = get_cursor(tu, 'j') - - self.assertIsNotNone(i) - self.assertIsNotNone(j) - - self.assertIsInstance(i.type.is_volatile_qualified(), bool) - self.assertTrue(i.type.is_volatile_qualified()) - self.assertFalse(j.type.is_volatile_qualified()) - - def test_is_restrict_qualified(self): - """Ensure Type.is_restrict_qualified works.""" - - tu = get_tu('struct s { void * restrict i; void * j; };') - - i = get_cursor(tu, 'i') - j = get_cursor(tu, 'j') - - self.assertIsNotNone(i) - self.assertIsNotNone(j) - - self.assertIsInstance(i.type.is_restrict_qualified(), bool) - self.assertTrue(i.type.is_restrict_qualified()) - self.assertFalse(j.type.is_restrict_qualified()) - - def test_record_layout(self): - """Ensure Cursor.type.get_size, Cursor.type.get_align and - Cursor.type.get_offset works.""" - - source =""" - struct a { - long a1; - long a2:3; - long a3:4; - long long a4; - }; - """ - tries=[(['-target','i386-linux-gnu'],(4,16,0,32,35,64)), - (['-target','nvptx64-unknown-unknown'],(8,24,0,64,67,128)), - (['-target','i386-pc-win32'],(8,16,0,32,35,64)), - (['-target','msp430-none-none'],(2,14,0,32,35,48))] - for flags, values in tries: - align,total,a1,a2,a3,a4 = values - - tu = get_tu(source, flags=flags) - teststruct = get_cursor(tu, 'a') - fields = list(teststruct.get_children()) - - self.assertEqual(teststruct.type.get_align(), align) - self.assertEqual(teststruct.type.get_size(), total) - self.assertEqual(teststruct.type.get_offset(fields[0].spelling), a1) - self.assertEqual(teststruct.type.get_offset(fields[1].spelling), a2) - self.assertEqual(teststruct.type.get_offset(fields[2].spelling), a3) - self.assertEqual(teststruct.type.get_offset(fields[3].spelling), a4) - self.assertEqual(fields[0].is_bitfield(), False) - self.assertEqual(fields[1].is_bitfield(), True) - self.assertEqual(fields[1].get_bitfield_width(), 3) - self.assertEqual(fields[2].is_bitfield(), True) - self.assertEqual(fields[2].get_bitfield_width(), 4) - self.assertEqual(fields[3].is_bitfield(), False) - - def test_offset(self): - """Ensure Cursor.get_record_field_offset works in anonymous records""" - source=""" - struct Test { - struct {int a;} typeanon; - struct { - int bariton; - union { - int foo; - }; - }; - int bar; - };""" - tries=[(['-target','i386-linux-gnu'],(4,16,0,32,64,96)), - (['-target','nvptx64-unknown-unknown'],(8,24,0,32,64,96)), - (['-target','i386-pc-win32'],(8,16,0,32,64,96)), - (['-target','msp430-none-none'],(2,14,0,32,64,96))] - for flags, values in tries: - align,total,f1,bariton,foo,bar = values - tu = get_tu(source) - teststruct = get_cursor(tu, 'Test') - children = list(teststruct.get_children()) - fields = list(teststruct.type.get_fields()) - self.assertEqual(children[0].kind, CursorKind.STRUCT_DECL) - self.assertNotEqual(children[0].spelling, "typeanon") - self.assertEqual(children[1].spelling, "typeanon") - self.assertEqual(fields[0].kind, CursorKind.FIELD_DECL) - self.assertEqual(fields[1].kind, CursorKind.FIELD_DECL) - self.assertTrue(fields[1].is_anonymous()) - self.assertEqual(teststruct.type.get_offset("typeanon"), f1) - self.assertEqual(teststruct.type.get_offset("bariton"), bariton) - self.assertEqual(teststruct.type.get_offset("foo"), foo) - self.assertEqual(teststruct.type.get_offset("bar"), bar) - - def test_decay(self): - """Ensure decayed types are handled as the original type""" - - tu = get_tu("void foo(int a[]);") - foo = get_cursor(tu, 'foo') - a = foo.type.argument_types()[0] - - self.assertEqual(a.kind, TypeKind.INCOMPLETEARRAY) - self.assertEqual(a.element_type.kind, TypeKind.INT) - self.assertEqual(a.get_canonical().kind, TypeKind.INCOMPLETEARRAY) - - def test_addrspace(self): - """Ensure the address space can be queried""" - tu = get_tu('__attribute__((address_space(2))) int testInteger = 3;', 'c') - - testInteger = get_cursor(tu, 'testInteger') - - self.assertIsNotNone(testInteger, "Could not find testInteger.") - self.assertEqual(testInteger.type.get_address_space(), 2) - - def test_template_arguments(self): - source = """ - class Foo { - }; - template - class Template { - }; - Template instance; - int bar; - """ - tu = get_tu(source, lang='cpp') - - # Varible with a template argument. - cursor = get_cursor(tu, 'instance') - cursor_type = cursor.type - self.assertEqual(cursor.kind, CursorKind.VAR_DECL) - self.assertEqual(cursor_type.spelling, 'Template') - self.assertEqual(cursor_type.get_num_template_arguments(), 1) - template_type = cursor_type.get_template_argument_type(0) - self.assertEqual(template_type.spelling, 'Foo') - - # Variable without a template argument. - cursor = get_cursor(tu, 'bar') - self.assertEqual(cursor.get_num_template_arguments(), -1) diff --git a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/util.py b/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/util.py deleted file mode 100644 index 57e17941c5581..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/python/tests/cindex/util.py +++ /dev/null @@ -1,90 +0,0 @@ -# This file provides common utility functions for the test suite. - -import os -HAS_FSPATH = hasattr(os, 'fspath') - -if HAS_FSPATH: - from pathlib import Path as str_to_path -else: - str_to_path = None - -import unittest - -from clang.cindex import Cursor -from clang.cindex import TranslationUnit - -def get_tu(source, lang='c', all_warnings=False, flags=[]): - """Obtain a translation unit from source and language. - - By default, the translation unit is created from source file "t." - where is the default file extension for the specified language. By - default it is C, so "t.c" is the default file name. - - Supported languages are {c, cpp, objc}. - - all_warnings is a convenience argument to enable all compiler warnings. - """ - args = list(flags) - name = 't.c' - if lang == 'cpp': - name = 't.cpp' - args.append('-std=c++11') - elif lang == 'objc': - name = 't.m' - elif lang != 'c': - raise Exception('Unknown language: %s' % lang) - - if all_warnings: - args += ['-Wall', '-Wextra'] - - return TranslationUnit.from_source(name, args, unsaved_files=[(name, - source)]) - -def get_cursor(source, spelling): - """Obtain a cursor from a source object. - - This provides a convenient search mechanism to find a cursor with specific - spelling within a source. The first argument can be either a - TranslationUnit or Cursor instance. - - If the cursor is not found, None is returned. - """ - # Convenience for calling on a TU. - root_cursor = source if isinstance(source, Cursor) else source.cursor - - for cursor in root_cursor.walk_preorder(): - if cursor.spelling == spelling: - return cursor - - return None - -def get_cursors(source, spelling): - """Obtain all cursors from a source object with a specific spelling. - - This provides a convenient search mechanism to find all cursors with - specific spelling within a source. The first argument can be either a - TranslationUnit or Cursor instance. - - If no cursors are found, an empty list is returned. - """ - # Convenience for calling on a TU. - root_cursor = source if isinstance(source, Cursor) else source.cursor - - cursors = [] - for cursor in root_cursor.walk_preorder(): - if cursor.spelling == spelling: - cursors.append(cursor) - - return cursors - - -skip_if_no_fspath = unittest.skipUnless(HAS_FSPATH, - "Requires file system path protocol / Python 3.6+") - -__all__ = [ - 'get_cursor', - 'get_cursors', - 'get_tu', - 'skip_if_no_fspath', - 'str_to_path', -] diff --git a/interpreter/llvm/src/tools/clang/bindings/xml/comment-xml-schema.rng b/interpreter/llvm/src/tools/clang/bindings/xml/comment-xml-schema.rng deleted file mode 100644 index 65ea597ed70c1..0000000000000 --- a/interpreter/llvm/src/tools/clang/bindings/xml/comment-xml-schema.rng +++ /dev/null @@ -1,608 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template - specialization - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template - specialization - partialSpecialization - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .*\S.* - - - - - - - - - - - - - - - - - - .*\S.* - - - - - - - - - .*\S.* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .*\S.* - - - - - - - - - - - - - - - - - - - - - - - - - - .*\S.* - - - - - - - - - - - - - - - - - - in - out - in,out - - - - - - - - - - - - - - - - - - - - - - - - - - - - \d+|\d+\.\d+|\d+\.\d+.\d+ - - - - - - - \d+|\d+\.\d+|\d+\.\d+.\d+ - - - - - - - \d+|\d+\.\d+|\d+\.\d+.\d+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - attention - author - authors - bug - copyright - date - invariant - note - post - pre - remark - remarks - sa - see - since - todo - version - warning - - - - - - - - - - preserve - - - - - code - verbatim - - - - - - - - - - - - - - .*\S.* - - - - - - .*\S.* - - - - - - .*\S.* - - - - - - - \S+ - - - - - - - - - - - - - - .*\S.* - - - - - - - diff --git a/interpreter/llvm/src/tools/clang/lib/Sema/HackForDefaultTemplateArg.h b/interpreter/llvm/src/tools/clang/lib/Sema/HackForDefaultTemplateArg.h deleted file mode 100644 index e6af62c414ba1..0000000000000 --- a/interpreter/llvm/src/tools/clang/lib/Sema/HackForDefaultTemplateArg.h +++ /dev/null @@ -1,52 +0,0 @@ -//===------- HackForDefaultTemplateArg.h - Make template argument substitution mroe permissive -----*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -//===----------------------------------------------------------------------===// -// -// Enabling this hack, make the template substitution more permissive and -// allows for replacement with non-canonical types. This is usefull in the -// case of client code emulating opaque typedefs and/or wanting to recover -// the template instance name as the user would have written if (s)he -// expanded the default paramater explicitly. For example the user might -// have type: vector and the client wants to see: -// std::vector > -// -// For convenience purposes the implementation is located in -// SemaTemplate.cpp -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_SEMA_HACKFORDEFAULTTEMPLATEARG_H -#define LLVM_CLANG_SEMA_HACKFORDEFAULTTEMPLATEARG_H - -namespace clang { -namespace sema { - -/// \brief Enabling this hack makes the template substitution more permissive -/// and allows for replacement with non-canonical types. This is usefull in -/// the case of client code emulating opaque typedefs and/or wanting to recover -/// the template instance name as the user would have written if (s)he -/// expanded the default paramater explicitly. For example the user might -/// have type: \c vector and the client wants to see: -/// \c std::vector > - -class HackForDefaultTemplateArg { - /// \brief Private RAII object that set and reset the hack state. - - static bool AllowNonCanonicalSubstEnabled; - bool OldValue; -public: - - HackForDefaultTemplateArg(); - ~HackForDefaultTemplateArg(); - - static bool AllowNonCanonicalSubst(); -}; - -} // sema -} // clang - -#endif // LLVM_CLANG_SEMA_HACKFORDEFAULTTEMPLATEARG_H diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/__init__.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/__init__.py deleted file mode 100644 index 45d5b8d7cc025..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import os -import sys - -this_dir = os.path.dirname(os.path.realpath(__file__)) -sys.path.append(os.path.join(os.path.dirname(this_dir), 'lib')) - -import unittest - -import tests.unit -import tests.functional.cases - - -def suite(): - loader = unittest.TestLoader() - suite = unittest.TestSuite() - suite.addTests(loader.loadTestsFromModule(tests.unit)) - suite.addTests(loader.loadTestsFromModule(tests.functional.cases)) - return suite diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/__init__.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/__init__.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/__init__.py deleted file mode 100644 index e8c490add6c61..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import re -import os.path -import subprocess - - -def load_tests(loader, suite, pattern): - from . import test_from_cdb - suite.addTests(loader.loadTestsFromModule(test_from_cdb)) - from . import test_from_cmd - suite.addTests(loader.loadTestsFromModule(test_from_cmd)) - from . import test_create_cdb - suite.addTests(loader.loadTestsFromModule(test_create_cdb)) - from . import test_exec_anatomy - suite.addTests(loader.loadTestsFromModule(test_exec_anatomy)) - return suite - - -def make_args(target): - this_dir, _ = os.path.split(__file__) - path = os.path.abspath(os.path.join(this_dir, '..', 'src')) - return ['make', 'SRCDIR={}'.format(path), 'OBJDIR={}'.format(target), '-f', - os.path.join(path, 'build', 'Makefile')] - - -def silent_call(cmd, *args, **kwargs): - kwargs.update({'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT}) - return subprocess.call(cmd, *args, **kwargs) - - -def silent_check_call(cmd, *args, **kwargs): - kwargs.update({'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT}) - return subprocess.check_call(cmd, *args, **kwargs) - - -def call_and_report(analyzer_cmd, build_cmd): - child = subprocess.Popen(analyzer_cmd + ['-v'] + build_cmd, - universal_newlines=True, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - - pattern = re.compile('Report directory created: (.+)') - directory = None - for line in child.stdout.readlines(): - match = pattern.search(line) - if match and match.lastindex == 1: - directory = match.group(1) - break - child.stdout.close() - child.wait() - - return (child.returncode, directory) - - -def check_call_and_report(analyzer_cmd, build_cmd): - exit_code, result = call_and_report(analyzer_cmd, build_cmd) - if exit_code != 0: - raise subprocess.CalledProcessError( - exit_code, analyzer_cmd + build_cmd, None) - else: - return result - - -def create_empty_file(filename): - with open(filename, 'a') as handle: - pass diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_create_cdb.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_create_cdb.py deleted file mode 100644 index 692a489b61178..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_create_cdb.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -from . import make_args, silent_check_call, silent_call, create_empty_file -import unittest - -import os.path -import json - - -class CompilationDatabaseTest(unittest.TestCase): - @staticmethod - def run_intercept(tmpdir, args): - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + args - silent_check_call( - ['intercept-build', '--cdb', result] + make) - return result - - @staticmethod - def count_entries(filename): - with open(filename, 'r') as handler: - content = json.load(handler) - return len(content) - - def test_successful_build(self): - with libear.TemporaryDirectory() as tmpdir: - result = self.run_intercept(tmpdir, ['build_regular']) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - def test_successful_build_with_wrapper(self): - with libear.TemporaryDirectory() as tmpdir: - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + ['build_regular'] - silent_check_call(['intercept-build', '--cdb', result, - '--override-compiler'] + make) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - @unittest.skipIf(os.getenv('TRAVIS'), 'ubuntu make return -11') - def test_successful_build_parallel(self): - with libear.TemporaryDirectory() as tmpdir: - result = self.run_intercept(tmpdir, ['-j', '4', 'build_regular']) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - @unittest.skipIf(os.getenv('TRAVIS'), 'ubuntu env remove clang from path') - def test_successful_build_on_empty_env(self): - with libear.TemporaryDirectory() as tmpdir: - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + ['CC=clang', 'build_regular'] - silent_check_call(['intercept-build', '--cdb', result, - 'env', '-'] + make) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - def test_successful_build_all_in_one(self): - with libear.TemporaryDirectory() as tmpdir: - result = self.run_intercept(tmpdir, ['build_all_in_one']) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - def test_not_successful_build(self): - with libear.TemporaryDirectory() as tmpdir: - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + ['build_broken'] - silent_call( - ['intercept-build', '--cdb', result] + make) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(2, self.count_entries(result)) - - -class ExitCodeTest(unittest.TestCase): - @staticmethod - def run_intercept(tmpdir, target): - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + [target] - return silent_call( - ['intercept-build', '--cdb', result] + make) - - def test_successful_build(self): - with libear.TemporaryDirectory() as tmpdir: - exitcode = self.run_intercept(tmpdir, 'build_clean') - self.assertFalse(exitcode) - - def test_not_successful_build(self): - with libear.TemporaryDirectory() as tmpdir: - exitcode = self.run_intercept(tmpdir, 'build_broken') - self.assertTrue(exitcode) - - -class ResumeFeatureTest(unittest.TestCase): - @staticmethod - def run_intercept(tmpdir, target, args): - result = os.path.join(tmpdir, 'cdb.json') - make = make_args(tmpdir) + [target] - silent_check_call( - ['intercept-build', '--cdb', result] + args + make) - return result - - @staticmethod - def count_entries(filename): - with open(filename, 'r') as handler: - content = json.load(handler) - return len(content) - - def test_overwrite_existing_cdb(self): - with libear.TemporaryDirectory() as tmpdir: - result = self.run_intercept(tmpdir, 'build_clean', []) - self.assertTrue(os.path.isfile(result)) - result = self.run_intercept(tmpdir, 'build_regular', []) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(2, self.count_entries(result)) - - def test_append_to_existing_cdb(self): - with libear.TemporaryDirectory() as tmpdir: - result = self.run_intercept(tmpdir, 'build_clean', []) - self.assertTrue(os.path.isfile(result)) - result = self.run_intercept(tmpdir, 'build_regular', ['--append']) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(5, self.count_entries(result)) - - -class ResultFormatingTest(unittest.TestCase): - @staticmethod - def run_intercept(tmpdir, command): - result = os.path.join(tmpdir, 'cdb.json') - silent_check_call( - ['intercept-build', '--cdb', result] + command, - cwd=tmpdir) - with open(result, 'r') as handler: - content = json.load(handler) - return content - - def assert_creates_number_of_entries(self, command, count): - with libear.TemporaryDirectory() as tmpdir: - filename = os.path.join(tmpdir, 'test.c') - create_empty_file(filename) - command.append(filename) - cmd = ['sh', '-c', ' '.join(command)] - cdb = self.run_intercept(tmpdir, cmd) - self.assertEqual(count, len(cdb)) - - def test_filter_preprocessor_only_calls(self): - self.assert_creates_number_of_entries(['cc', '-c'], 1) - self.assert_creates_number_of_entries(['cc', '-c', '-E'], 0) - self.assert_creates_number_of_entries(['cc', '-c', '-M'], 0) - self.assert_creates_number_of_entries(['cc', '-c', '-MM'], 0) - - def assert_command_creates_entry(self, command, expected): - with libear.TemporaryDirectory() as tmpdir: - filename = os.path.join(tmpdir, command[-1]) - create_empty_file(filename) - cmd = ['sh', '-c', ' '.join(command)] - cdb = self.run_intercept(tmpdir, cmd) - self.assertEqual(' '.join(expected), cdb[0]['command']) - - def test_filter_preprocessor_flags(self): - self.assert_command_creates_entry( - ['cc', '-c', '-MD', 'test.c'], - ['cc', '-c', 'test.c']) - self.assert_command_creates_entry( - ['cc', '-c', '-MMD', 'test.c'], - ['cc', '-c', 'test.c']) - self.assert_command_creates_entry( - ['cc', '-c', '-MD', '-MF', 'test.d', 'test.c'], - ['cc', '-c', 'test.c']) - - def test_pass_language_flag(self): - self.assert_command_creates_entry( - ['cc', '-c', '-x', 'c', 'test.c'], - ['cc', '-c', '-x', 'c', 'test.c']) - self.assert_command_creates_entry( - ['cc', '-c', 'test.c'], - ['cc', '-c', 'test.c']) - - def test_pass_arch_flags(self): - self.assert_command_creates_entry( - ['clang', '-c', 'test.c'], - ['cc', '-c', 'test.c']) - self.assert_command_creates_entry( - ['clang', '-c', '-arch', 'i386', 'test.c'], - ['cc', '-c', '-arch', 'i386', 'test.c']) - self.assert_command_creates_entry( - ['clang', '-c', '-arch', 'i386', '-arch', 'armv7l', 'test.c'], - ['cc', '-c', '-arch', 'i386', '-arch', 'armv7l', 'test.c']) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_exec_anatomy.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_exec_anatomy.py deleted file mode 100644 index d6bf572481a34..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_exec_anatomy.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -import unittest - -import os.path -import subprocess -import json - - -def run(source_dir, target_dir): - def execute(cmd): - return subprocess.check_call(cmd, - cwd=target_dir, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - - execute(['cmake', source_dir]) - execute(['make']) - - result_file = os.path.join(target_dir, 'result.json') - expected_file = os.path.join(target_dir, 'expected.json') - execute(['intercept-build', '--cdb', result_file, './exec', - expected_file]) - return (expected_file, result_file) - - -class ExecAnatomyTest(unittest.TestCase): - def assertEqualJson(self, expected, result): - def read_json(filename): - with open(filename) as handler: - return json.load(handler) - - lhs = read_json(expected) - rhs = read_json(result) - for item in lhs: - self.assertTrue(rhs.count(item)) - for item in rhs: - self.assertTrue(lhs.count(item)) - - def test_all_exec_calls(self): - this_dir, _ = os.path.split(__file__) - source_dir = os.path.abspath(os.path.join(this_dir, '..', 'exec')) - with libear.TemporaryDirectory() as tmp_dir: - expected, result = run(source_dir, tmp_dir) - self.assertEqualJson(expected, result) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cdb.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cdb.py deleted file mode 100644 index 3b52d852fbf23..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cdb.py +++ /dev/null @@ -1,212 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -from . import call_and_report -import unittest - -import os.path -import string -import glob - - -def prepare_cdb(name, target_dir): - target_file = 'build_{0}.json'.format(name) - this_dir, _ = os.path.split(__file__) - path = os.path.abspath(os.path.join(this_dir, '..', 'src')) - source_dir = os.path.join(path, 'compilation_database') - source_file = os.path.join(source_dir, target_file + '.in') - target_file = os.path.join(target_dir, 'compile_commands.json') - with open(source_file, 'r') as in_handle: - with open(target_file, 'w') as out_handle: - for line in in_handle: - temp = string.Template(line) - out_handle.write(temp.substitute(path=path)) - return target_file - - -def run_analyzer(directory, cdb, args): - cmd = ['analyze-build', '--cdb', cdb, '--output', directory] \ - + args - return call_and_report(cmd, []) - - -class OutputDirectoryTest(unittest.TestCase): - def test_regular_keeps_report_dir(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, []) - self.assertTrue(os.path.isdir(reportdir)) - - def test_clear_deletes_report_dir(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('clean', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, []) - self.assertFalse(os.path.isdir(reportdir)) - - def test_clear_keeps_report_dir_when_asked(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('clean', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, ['--keep-empty']) - self.assertTrue(os.path.isdir(reportdir)) - - -class ExitCodeTest(unittest.TestCase): - def test_regular_does_not_set_exit_code(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, __ = run_analyzer(tmpdir, cdb, []) - self.assertFalse(exit_code) - - def test_clear_does_not_set_exit_code(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('clean', tmpdir) - exit_code, __ = run_analyzer(tmpdir, cdb, []) - self.assertFalse(exit_code) - - def test_regular_sets_exit_code_if_asked(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, __ = run_analyzer(tmpdir, cdb, ['--status-bugs']) - self.assertTrue(exit_code) - - def test_clear_does_not_set_exit_code_if_asked(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('clean', tmpdir) - exit_code, __ = run_analyzer(tmpdir, cdb, ['--status-bugs']) - self.assertFalse(exit_code) - - def test_regular_sets_exit_code_if_asked_from_plist(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, __ = run_analyzer( - tmpdir, cdb, ['--status-bugs', '--plist']) - self.assertTrue(exit_code) - - def test_clear_does_not_set_exit_code_if_asked_from_plist(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('clean', tmpdir) - exit_code, __ = run_analyzer( - tmpdir, cdb, ['--status-bugs', '--plist']) - self.assertFalse(exit_code) - - -class OutputFormatTest(unittest.TestCase): - @staticmethod - def get_html_count(directory): - return len(glob.glob(os.path.join(directory, 'report-*.html'))) - - @staticmethod - def get_plist_count(directory): - return len(glob.glob(os.path.join(directory, 'report-*.plist'))) - - @staticmethod - def get_sarif_count(directory): - return len(glob.glob(os.path.join(directory, 'result-*.sarif'))) - - def test_default_only_creates_html_report(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, []) - self.assertTrue( - os.path.exists(os.path.join(reportdir, 'index.html'))) - self.assertEqual(self.get_html_count(reportdir), 2) - self.assertEqual(self.get_plist_count(reportdir), 0) - self.assertEqual(self.get_sarif_count(reportdir), 0) - - def test_plist_and_html_creates_html_and_plist_reports(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, ['--plist-html']) - self.assertTrue( - os.path.exists(os.path.join(reportdir, 'index.html'))) - self.assertEqual(self.get_html_count(reportdir), 2) - self.assertEqual(self.get_plist_count(reportdir), 5) - self.assertEqual(self.get_sarif_count(reportdir), 0) - - def test_plist_only_creates_plist_report(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, ['--plist']) - self.assertFalse( - os.path.exists(os.path.join(reportdir, 'index.html'))) - self.assertEqual(self.get_html_count(reportdir), 0) - self.assertEqual(self.get_plist_count(reportdir), 5) - self.assertEqual(self.get_sarif_count(reportdir), 0) - - def test_sarif_only_creates_sarif_result(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, ['--sarif']) - self.assertFalse( - os.path.exists(os.path.join(reportdir, 'index.html'))) - self.assertTrue( - os.path.exists(os.path.join(reportdir, 'results-merged.sarif'))) - self.assertEqual(self.get_html_count(reportdir), 0) - self.assertEqual(self.get_plist_count(reportdir), 0) - self.assertEqual(self.get_sarif_count(reportdir), 5) - - def test_sarif_and_html_creates_sarif_and_html_reports(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('regular', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, ['--sarif-html']) - self.assertTrue( - os.path.exists(os.path.join(reportdir, 'index.html'))) - self.assertTrue( - os.path.exists(os.path.join(reportdir, 'results-merged.sarif'))) - self.assertEqual(self.get_html_count(reportdir), 2) - self.assertEqual(self.get_plist_count(reportdir), 0) - self.assertEqual(self.get_sarif_count(reportdir), 5) - - -class FailureReportTest(unittest.TestCase): - def test_broken_creates_failure_reports(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('broken', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, []) - self.assertTrue( - os.path.isdir(os.path.join(reportdir, 'failures'))) - - def test_broken_does_not_creates_failure_reports(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('broken', tmpdir) - exit_code, reportdir = run_analyzer( - tmpdir, cdb, ['--no-failure-reports']) - self.assertFalse( - os.path.isdir(os.path.join(reportdir, 'failures'))) - - -class TitleTest(unittest.TestCase): - def assertTitleEqual(self, directory, expected): - import re - patterns = [ - re.compile(r'(?P<page>.*)'), - re.compile(r'

(?P.*)

') - ] - result = dict() - - index = os.path.join(directory, 'index.html') - with open(index, 'r') as handler: - for line in handler.readlines(): - for regex in patterns: - match = regex.match(line.strip()) - if match: - result.update(match.groupdict()) - break - self.assertEqual(result['page'], result['head']) - self.assertEqual(result['page'], expected) - - def test_default_title_in_report(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('broken', tmpdir) - exit_code, reportdir = run_analyzer(tmpdir, cdb, []) - self.assertTitleEqual(reportdir, 'src - analyzer results') - - def test_given_title_in_report(self): - with libear.TemporaryDirectory() as tmpdir: - cdb = prepare_cdb('broken', tmpdir) - exit_code, reportdir = run_analyzer( - tmpdir, cdb, ['--html-title', 'this is the title']) - self.assertTitleEqual(reportdir, 'this is the title') diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cmd.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cmd.py deleted file mode 100644 index aa244631bce9f..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_from_cmd.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -from . import make_args, check_call_and_report, create_empty_file -import unittest - -import os -import os.path -import glob - - -class OutputDirectoryTest(unittest.TestCase): - - @staticmethod - def run_analyzer(outdir, args, cmd): - return check_call_and_report( - ['scan-build-py', '--intercept-first', '-o', outdir] + args, - cmd) - - def test_regular_keeps_report_dir(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_regular'] - outdir = self.run_analyzer(tmpdir, [], make) - self.assertTrue(os.path.isdir(outdir)) - - def test_clear_deletes_report_dir(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_clean'] - outdir = self.run_analyzer(tmpdir, [], make) - self.assertFalse(os.path.isdir(outdir)) - - def test_clear_keeps_report_dir_when_asked(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_clean'] - outdir = self.run_analyzer(tmpdir, ['--keep-empty'], make) - self.assertTrue(os.path.isdir(outdir)) - - -class RunAnalyzerTest(unittest.TestCase): - - @staticmethod - def get_plist_count(directory): - return len(glob.glob(os.path.join(directory, 'report-*.plist'))) - - def test_interposition_works(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_regular'] - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--override-compiler'], - make) - - self.assertTrue(os.path.isdir(outdir)) - self.assertEqual(self.get_plist_count(outdir), 5) - - def test_intercept_wrapper_works(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_regular'] - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--intercept-first', - '--override-compiler'], - make) - - self.assertTrue(os.path.isdir(outdir)) - self.assertEqual(self.get_plist_count(outdir), 5) - - def test_intercept_library_works(self): - with libear.TemporaryDirectory() as tmpdir: - make = make_args(tmpdir) + ['build_regular'] - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--intercept-first'], - make) - - self.assertTrue(os.path.isdir(outdir)) - self.assertEqual(self.get_plist_count(outdir), 5) - - @staticmethod - def compile_empty_source_file(target_dir, is_cxx): - compiler = '$CXX' if is_cxx else '$CC' - src_file_name = 'test.cxx' if is_cxx else 'test.c' - src_file = os.path.join(target_dir, src_file_name) - obj_file = os.path.join(target_dir, 'test.o') - create_empty_file(src_file) - command = ' '.join([compiler, '-c', src_file, '-o', obj_file]) - return ['sh', '-c', command] - - def test_interposition_cc_works(self): - with libear.TemporaryDirectory() as tmpdir: - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--override-compiler'], - self.compile_empty_source_file(tmpdir, False)) - self.assertEqual(self.get_plist_count(outdir), 1) - - def test_interposition_cxx_works(self): - with libear.TemporaryDirectory() as tmpdir: - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--override-compiler'], - self.compile_empty_source_file(tmpdir, True)) - self.assertEqual(self.get_plist_count(outdir), 1) - - def test_intercept_cc_works(self): - with libear.TemporaryDirectory() as tmpdir: - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--override-compiler', - '--intercept-first'], - self.compile_empty_source_file(tmpdir, False)) - self.assertEqual(self.get_plist_count(outdir), 1) - - def test_intercept_cxx_works(self): - with libear.TemporaryDirectory() as tmpdir: - outdir = check_call_and_report( - ['scan-build-py', '--plist', '-o', tmpdir, '--override-compiler', - '--intercept-first'], - self.compile_empty_source_file(tmpdir, True)) - self.assertEqual(self.get_plist_count(outdir), 1) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt deleted file mode 100644 index 007ad4530d6dc..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -project(exec C) - -cmake_minimum_required(VERSION 3.13.4) - -include(CheckCCompilerFlag) -check_c_compiler_flag("-std=c99" C99_SUPPORTED) -if (C99_SUPPORTED) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") -endif() - -include(CheckFunctionExists) -include(CheckSymbolExists) - -add_definitions(-D_GNU_SOURCE) -list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE) - -check_function_exists(execve HAVE_EXECVE) -check_function_exists(execv HAVE_EXECV) -check_function_exists(execvpe HAVE_EXECVPE) -check_function_exists(execvp HAVE_EXECVP) -check_function_exists(execvP HAVE_EXECVP2) -check_function_exists(exect HAVE_EXECT) -check_function_exists(execl HAVE_EXECL) -check_function_exists(execlp HAVE_EXECLP) -check_function_exists(execle HAVE_EXECLE) -check_function_exists(posix_spawn HAVE_POSIX_SPAWN) -check_function_exists(posix_spawnp HAVE_POSIX_SPAWNP) - -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) -include_directories(${CMAKE_CURRENT_BINARY_DIR}) - -add_executable(exec main.c) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/config.h.in b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/config.h.in deleted file mode 100644 index 2f07d0cbea964..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/config.h.in +++ /dev/null @@ -1,19 +0,0 @@ -/* -*- coding: utf-8 -*- -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -#pragma once - -#cmakedefine HAVE_EXECVE -#cmakedefine HAVE_EXECV -#cmakedefine HAVE_EXECVPE -#cmakedefine HAVE_EXECVP -#cmakedefine HAVE_EXECVP2 -#cmakedefine HAVE_EXECT -#cmakedefine HAVE_EXECL -#cmakedefine HAVE_EXECLP -#cmakedefine HAVE_EXECLE -#cmakedefine HAVE_POSIX_SPAWN -#cmakedefine HAVE_POSIX_SPAWNP diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/main.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/main.c deleted file mode 100644 index 0f5e01fb35cfc..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/exec/main.c +++ /dev/null @@ -1,306 +0,0 @@ -/* -*- coding: utf-8 -*- -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -*/ - -#include "config.h" - -#include -#include -#include -#include -#include - -#if defined HAVE_POSIX_SPAWN || defined HAVE_POSIX_SPAWNP -#include -#endif - -// ..:: environment access fixer - begin ::.. -#ifdef HAVE_NSGETENVIRON -#include -#else -extern char **environ; -#endif - -char **get_environ() { -#ifdef HAVE_NSGETENVIRON - return *_NSGetEnviron(); -#else - return environ; -#endif -} -// ..:: environment access fixer - end ::.. - -// ..:: test fixtures - begin ::.. -static char const *cwd = NULL; -static FILE *fd = NULL; -static int need_comma = 0; - -void expected_out_open(const char *expected) { - cwd = getcwd(NULL, 0); - fd = fopen(expected, "w"); - if (!fd) { - perror("fopen"); - exit(EXIT_FAILURE); - } - fprintf(fd, "[\n"); - need_comma = 0; -} - -void expected_out_close() { - fprintf(fd, "]\n"); - fclose(fd); - fd = NULL; - - free((void *)cwd); - cwd = NULL; -} - -void expected_out(const char *file) { - if (need_comma) - fprintf(fd, ",\n"); - else - need_comma = 1; - - fprintf(fd, "{\n"); - fprintf(fd, " \"directory\": \"%s\",\n", cwd); - fprintf(fd, " \"command\": \"cc -c %s\",\n", file); - fprintf(fd, " \"file\": \"%s/%s\"\n", cwd, file); - fprintf(fd, "}\n"); -} - -void create_source(char *file) { - FILE *fd = fopen(file, "w"); - if (!fd) { - perror("fopen"); - exit(EXIT_FAILURE); - } - fprintf(fd, "typedef int score;\n"); - fclose(fd); -} - -typedef void (*exec_fun)(); - -void wait_for(pid_t child) { - int status; - if (-1 == waitpid(child, &status, 0)) { - perror("wait"); - exit(EXIT_FAILURE); - } - if (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE) { - fprintf(stderr, "children process has non zero exit code\n"); - exit(EXIT_FAILURE); - } -} - -#define FORK(FUNC) \ - { \ - pid_t child = fork(); \ - if (-1 == child) { \ - perror("fork"); \ - exit(EXIT_FAILURE); \ - } else if (0 == child) { \ - FUNC fprintf(stderr, "children process failed to exec\n"); \ - exit(EXIT_FAILURE); \ - } else { \ - wait_for(child); \ - } \ - } -// ..:: test fixtures - end ::.. - -#ifdef HAVE_EXECV -void call_execv() { - char *const file = "execv.c"; - char *const compiler = "/usr/bin/cc"; - char *const argv[] = {"cc", "-c", file, 0}; - - expected_out(file); - create_source(file); - - FORK(execv(compiler, argv);) -} -#endif - -#ifdef HAVE_EXECVE -void call_execve() { - char *const file = "execve.c"; - char *const compiler = "/usr/bin/cc"; - char *const argv[] = {compiler, "-c", file, 0}; - char *const envp[] = {"THIS=THAT", 0}; - - expected_out(file); - create_source(file); - - FORK(execve(compiler, argv, envp);) -} -#endif - -#ifdef HAVE_EXECVP -void call_execvp() { - char *const file = "execvp.c"; - char *const compiler = "cc"; - char *const argv[] = {compiler, "-c", file, 0}; - - expected_out(file); - create_source(file); - - FORK(execvp(compiler, argv);) -} -#endif - -#ifdef HAVE_EXECVP2 -void call_execvP() { - char *const file = "execv_p.c"; - char *const compiler = "cc"; - char *const argv[] = {compiler, "-c", file, 0}; - - expected_out(file); - create_source(file); - - FORK(execvP(compiler, _PATH_DEFPATH, argv);) -} -#endif - -#ifdef HAVE_EXECVPE -void call_execvpe() { - char *const file = "execvpe.c"; - char *const compiler = "cc"; - char *const argv[] = {"/usr/bin/cc", "-c", file, 0}; - char *const envp[] = {"THIS=THAT", 0}; - - expected_out(file); - create_source(file); - - FORK(execvpe(compiler, argv, envp);) -} -#endif - -#ifdef HAVE_EXECT -void call_exect() { - char *const file = "exect.c"; - char *const compiler = "/usr/bin/cc"; - char *const argv[] = {compiler, "-c", file, 0}; - char *const envp[] = {"THIS=THAT", 0}; - - expected_out(file); - create_source(file); - - FORK(exect(compiler, argv, envp);) -} -#endif - -#ifdef HAVE_EXECL -void call_execl() { - char *const file = "execl.c"; - char *const compiler = "/usr/bin/cc"; - - expected_out(file); - create_source(file); - - FORK(execl(compiler, "cc", "-c", file, (char *)0);) -} -#endif - -#ifdef HAVE_EXECLP -void call_execlp() { - char *const file = "execlp.c"; - char *const compiler = "cc"; - - expected_out(file); - create_source(file); - - FORK(execlp(compiler, compiler, "-c", file, (char *)0);) -} -#endif - -#ifdef HAVE_EXECLE -void call_execle() { - char *const file = "execle.c"; - char *const compiler = "/usr/bin/cc"; - char *const envp[] = {"THIS=THAT", 0}; - - expected_out(file); - create_source(file); - - FORK(execle(compiler, compiler, "-c", file, (char *)0, envp);) -} -#endif - -#ifdef HAVE_POSIX_SPAWN -void call_posix_spawn() { - char *const file = "posix_spawn.c"; - char *const compiler = "cc"; - char *const argv[] = {compiler, "-c", file, 0}; - - expected_out(file); - create_source(file); - - pid_t child; - if (0 != posix_spawn(&child, "/usr/bin/cc", 0, 0, argv, get_environ())) { - perror("posix_spawn"); - exit(EXIT_FAILURE); - } - wait_for(child); -} -#endif - -#ifdef HAVE_POSIX_SPAWNP -void call_posix_spawnp() { - char *const file = "posix_spawnp.c"; - char *const compiler = "cc"; - char *const argv[] = {compiler, "-c", file, 0}; - - expected_out(file); - create_source(file); - - pid_t child; - if (0 != posix_spawnp(&child, "cc", 0, 0, argv, get_environ())) { - perror("posix_spawnp"); - exit(EXIT_FAILURE); - } - wait_for(child); -} -#endif - -int main(int argc, char *const argv[]) { - if (argc != 2) - exit(EXIT_FAILURE); - - expected_out_open(argv[1]); -#ifdef HAVE_EXECV - call_execv(); -#endif -#ifdef HAVE_EXECVE - call_execve(); -#endif -#ifdef HAVE_EXECVP - call_execvp(); -#endif -#ifdef HAVE_EXECVP2 - call_execvP(); -#endif -#ifdef HAVE_EXECVPE - call_execvpe(); -#endif -#ifdef HAVE_EXECT - call_exect(); -#endif -#ifdef HAVE_EXECL - call_execl(); -#endif -#ifdef HAVE_EXECLP - call_execlp(); -#endif -#ifdef HAVE_EXECLE - call_execle(); -#endif -#ifdef HAVE_POSIX_SPAWN - call_posix_spawn(); -#endif -#ifdef HAVE_POSIX_SPAWNP - call_posix_spawnp(); -#endif - expected_out_close(); - return 0; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-one.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-one.c deleted file mode 100644 index f0550238132c2..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-one.c +++ /dev/null @@ -1,6 +0,0 @@ -#include - -int value(int in) -{ - return 2 * in; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-two.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-two.c deleted file mode 100644 index 7b4c12ff5c39d..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/broken-two.c +++ /dev/null @@ -1 +0,0 @@ -int test() { ; diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/build/Makefile b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/build/Makefile deleted file mode 100644 index a8c0aafd0e5e6..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/build/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -SRCDIR := .. -OBJDIR := . - -CFLAGS = -Wall -DDEBUG -Dvariable="value with space" -I $(SRCDIR)/include -LDFLAGS = -PROGRAM = $(OBJDIR)/prg - -$(OBJDIR)/main.o: $(SRCDIR)/main.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/main.c - -$(OBJDIR)/clean-one.o: $(SRCDIR)/clean-one.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/clean-one.c - -$(OBJDIR)/clean-two.o: $(SRCDIR)/clean-two.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/clean-two.c - -$(OBJDIR)/emit-one.o: $(SRCDIR)/emit-one.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/emit-one.c - -$(OBJDIR)/emit-two.o: $(SRCDIR)/emit-two.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/emit-two.c - -$(OBJDIR)/broken-one.o: $(SRCDIR)/broken-one.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/broken-one.c - -$(OBJDIR)/broken-two.o: $(SRCDIR)/broken-two.c - $(CC) $(CFLAGS) -c -o $@ $(SRCDIR)/broken-two.c - -$(PROGRAM): $(OBJDIR)/main.o $(OBJDIR)/clean-one.o $(OBJDIR)/clean-two.o $(OBJDIR)/emit-one.o $(OBJDIR)/emit-two.o - $(CC) $(LDFLAGS) -o $@ $(OBJDIR)/main.o $(OBJDIR)/clean-one.o $(OBJDIR)/clean-two.o $(OBJDIR)/emit-one.o $(OBJDIR)/emit-two.o - -build_regular: $(PROGRAM) - -build_clean: $(OBJDIR)/main.o $(OBJDIR)/clean-one.o $(OBJDIR)/clean-two.o - -build_broken: $(OBJDIR)/main.o $(OBJDIR)/broken-one.o $(OBJDIR)/broken-two.o - -build_all_in_one: $(SRCDIR)/main.c $(SRCDIR)/clean-one.c $(SRCDIR)/clean-two.c $(SRCDIR)/emit-one.c $(SRCDIR)/emit-two.c - $(CC) $(CFLAGS) $(LDFLAGS) -o $(PROGRAM) $(SRCDIR)/main.c $(SRCDIR)/clean-one.c $(SRCDIR)/clean-two.c $(SRCDIR)/emit-one.c $(SRCDIR)/emit-two.c - -clean: - rm -f $(PROGRAM) $(OBJDIR)/*.o diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-one.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-one.c deleted file mode 100644 index 08c5f33609bbf..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-one.c +++ /dev/null @@ -1,13 +0,0 @@ -#include - -int do_nothing_loop() -{ - int i = 32; - int idx = 0; - - for (idx = i; idx > 0; --idx) - { - i += idx; - } - return i; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-two.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-two.c deleted file mode 100644 index 73bc288627d0e..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/clean-two.c +++ /dev/null @@ -1,11 +0,0 @@ -#include - -#include - -unsigned int another_method() -{ - unsigned int const size = do_nothing_loop(); - unsigned int const square = size * size; - - return square; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_broken.json.in b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_broken.json.in deleted file mode 100644 index 104a4191cb1b4..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_broken.json.in +++ /dev/null @@ -1,43 +0,0 @@ -[ -{ - "directory": "${path}", - "command": "g++ -c -o main.o main.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/main.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o broken-one.o broken-one.c -Wall -DDEBUG \"-Dvariable=value with space\"", - "file": "${path}/broken-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o broken-two.o broken-two.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/broken-two.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o clean-one.o clean-one.c -Wall -DDEBUG \"-Dvariable=value with space\" -Iinclude", - "file": "${path}/clean-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o clean-two.o clean-two.c -Wall -DDEBUG -Dvariable=value -I ./include", - "file": "${path}/clean-two.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o emit-one.o emit-one.c -Wall -DDEBUG \"-Dvariable=value with space\"", - "file": "${path}/emit-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o emit-two.o emit-two.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/emit-two.c" -} -] diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_clean.json.in b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_clean.json.in deleted file mode 100644 index aa4dcde8e5e71..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_clean.json.in +++ /dev/null @@ -1,19 +0,0 @@ -[ -{ - "directory": "${path}", - "command": "g++ -c -o main.o main.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/main.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o clean-one.o clean-one.c -Wall -DDEBUG \"-Dvariable=value with space\" -Iinclude", - "file": "${path}/clean-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o clean-two.o clean-two.c -Wall -DDEBUG -Dvariable=value -I ./include", - "file": "${path}/clean-two.c" -} -] diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_regular.json.in b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_regular.json.in deleted file mode 100644 index 0200c1d8624a0..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/compilation_database/build_regular.json.in +++ /dev/null @@ -1,31 +0,0 @@ -[ -{ - "directory": "${path}", - "command": "g++ -c -o main.o main.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/main.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o clean-one.o clean-one.c -Wall -DDEBUG \"-Dvariable=value with space\" -Iinclude", - "file": "${path}/clean-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o clean-two.o clean-two.c -Wall -DDEBUG -Dvariable=value -I ./include", - "file": "${path}/clean-two.c" -} -, -{ - "directory": "${path}", - "command": "cc -c -o emit-one.o emit-one.c -Wall -DDEBUG \"-Dvariable=value with space\"", - "file": "${path}/emit-one.c" -} -, -{ - "directory": "${path}", - "command": "g++ -c -o emit-two.o emit-two.c -Wall -DDEBUG -Dvariable=value", - "file": "${path}/emit-two.c" -} -] diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-one.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-one.c deleted file mode 100644 index 6cbd9cea72b96..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-one.c +++ /dev/null @@ -1,23 +0,0 @@ -#include - -int div(int numerator, int denominator) -{ - return numerator / denominator; -} - -void div_test() -{ - int i = 0; - for (i = 0; i < 2; ++i) - assert(div(2 * i, i) == 2); -} - -int do_nothing() -{ - unsigned int i = 0; - - int k = 100; - int j = k + 1; - - return j; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-two.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-two.c deleted file mode 100644 index faea77167f4c3..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/emit-two.c +++ /dev/null @@ -1,13 +0,0 @@ - -int bad_guy(int * i) -{ - *i = 9; - return *i; -} - -void bad_guy_test() -{ - int * ptr = 0; - - bad_guy(ptr); -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/include/clean-one.h b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/include/clean-one.h deleted file mode 100644 index 695dbd04c6583..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/include/clean-one.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef CLEAN_ONE_H -#define CLEAN_ONE_H - -int do_nothing_loop(); - -#endif diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/main.c b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/main.c deleted file mode 100644 index 905869dfa380f..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/src/main.c +++ /dev/null @@ -1,4 +0,0 @@ -int main() -{ - return 0; -} diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/__init__.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/__init__.py deleted file mode 100644 index 83a04743e6a1d..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -from . import test_libear -from . import test_compilation -from . import test_clang -from . import test_report -from . import test_analyze -from . import test_intercept -from . import test_shell - - -def load_tests(loader, suite, _): - suite.addTests(loader.loadTestsFromModule(test_libear)) - suite.addTests(loader.loadTestsFromModule(test_compilation)) - suite.addTests(loader.loadTestsFromModule(test_clang)) - suite.addTests(loader.loadTestsFromModule(test_report)) - suite.addTests(loader.loadTestsFromModule(test_analyze)) - suite.addTests(loader.loadTestsFromModule(test_intercept)) - suite.addTests(loader.loadTestsFromModule(test_shell)) - return suite diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_analyze.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_analyze.py deleted file mode 100644 index 823fcab9f47e5..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_analyze.py +++ /dev/null @@ -1,429 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import unittest -import re -import os -import os.path -import libear -import libscanbuild.analyze as sut - - -class ReportDirectoryTest(unittest.TestCase): - - # Test that successive report directory names ascend in lexicographic - # order. This is required so that report directories from two runs of - # scan-build can be easily matched up to compare results. - def test_directory_name_comparison(self): - with libear.TemporaryDirectory() as tmpdir, \ - sut.report_directory(tmpdir, False, 'html') as report_dir1, \ - sut.report_directory(tmpdir, False, 'html') as report_dir2, \ - sut.report_directory(tmpdir, False, 'html') as report_dir3: - self.assertLess(report_dir1, report_dir2) - self.assertLess(report_dir2, report_dir3) - - -class FilteringFlagsTest(unittest.TestCase): - - def test_language_captured(self): - def test(flags): - cmd = ['clang', '-c', 'source.c'] + flags - opts = sut.classify_parameters(cmd) - return opts['language'] - - self.assertEqual(None, test([])) - self.assertEqual('c', test(['-x', 'c'])) - self.assertEqual('cpp', test(['-x', 'cpp'])) - - def test_arch(self): - def test(flags): - cmd = ['clang', '-c', 'source.c'] + flags - opts = sut.classify_parameters(cmd) - return opts['arch_list'] - - self.assertEqual([], test([])) - self.assertEqual(['mips'], test(['-arch', 'mips'])) - self.assertEqual(['mips', 'i386'], - test(['-arch', 'mips', '-arch', 'i386'])) - - def assertFlagsChanged(self, expected, flags): - cmd = ['clang', '-c', 'source.c'] + flags - opts = sut.classify_parameters(cmd) - self.assertEqual(expected, opts['flags']) - - def assertFlagsUnchanged(self, flags): - self.assertFlagsChanged(flags, flags) - - def assertFlagsFiltered(self, flags): - self.assertFlagsChanged([], flags) - - def test_optimalizations_pass(self): - self.assertFlagsUnchanged(['-O']) - self.assertFlagsUnchanged(['-O1']) - self.assertFlagsUnchanged(['-Os']) - self.assertFlagsUnchanged(['-O2']) - self.assertFlagsUnchanged(['-O3']) - - def test_include_pass(self): - self.assertFlagsUnchanged([]) - self.assertFlagsUnchanged(['-include', '/usr/local/include']) - self.assertFlagsUnchanged(['-I.']) - self.assertFlagsUnchanged(['-I', '.']) - self.assertFlagsUnchanged(['-I/usr/local/include']) - self.assertFlagsUnchanged(['-I', '/usr/local/include']) - self.assertFlagsUnchanged(['-I/opt', '-I', '/opt/otp/include']) - self.assertFlagsUnchanged(['-isystem', '/path']) - self.assertFlagsUnchanged(['-isystem=/path']) - - def test_define_pass(self): - self.assertFlagsUnchanged(['-DNDEBUG']) - self.assertFlagsUnchanged(['-UNDEBUG']) - self.assertFlagsUnchanged(['-Dvar1=val1', '-Dvar2=val2']) - self.assertFlagsUnchanged(['-Dvar="val ues"']) - - def test_output_filtered(self): - self.assertFlagsFiltered(['-o', 'source.o']) - - def test_some_warning_filtered(self): - self.assertFlagsFiltered(['-Wall']) - self.assertFlagsFiltered(['-Wnoexcept']) - self.assertFlagsFiltered(['-Wreorder', '-Wunused', '-Wundef']) - self.assertFlagsUnchanged(['-Wno-reorder', '-Wno-unused']) - - def test_compile_only_flags_pass(self): - self.assertFlagsUnchanged(['-std=C99']) - self.assertFlagsUnchanged(['-nostdinc']) - self.assertFlagsUnchanged(['-isystem', '/image/debian']) - self.assertFlagsUnchanged(['-iprefix', '/usr/local']) - self.assertFlagsUnchanged(['-iquote=me']) - self.assertFlagsUnchanged(['-iquote', 'me']) - - def test_compile_and_link_flags_pass(self): - self.assertFlagsUnchanged(['-fsinged-char']) - self.assertFlagsUnchanged(['-fPIC']) - self.assertFlagsUnchanged(['-stdlib=libc++']) - self.assertFlagsUnchanged(['--sysroot', '/']) - self.assertFlagsUnchanged(['-isysroot', '/']) - - def test_some_flags_filtered(self): - self.assertFlagsFiltered(['-g']) - self.assertFlagsFiltered(['-fsyntax-only']) - self.assertFlagsFiltered(['-save-temps']) - self.assertFlagsFiltered(['-init', 'my_init']) - self.assertFlagsFiltered(['-sectorder', 'a', 'b', 'c']) - - -class Spy(object): - def __init__(self): - self.arg = None - self.success = 0 - - def call(self, params): - self.arg = params - return self.success - - -class RunAnalyzerTest(unittest.TestCase): - - @staticmethod - def run_analyzer(content, failures_report, output_format='plist'): - with libear.TemporaryDirectory() as tmpdir: - filename = os.path.join(tmpdir, 'test.cpp') - with open(filename, 'w') as handle: - handle.write(content) - - opts = { - 'clang': 'clang', - 'directory': os.getcwd(), - 'flags': [], - 'direct_args': [], - 'file': filename, - 'output_dir': tmpdir, - 'output_format': output_format, - 'output_failures': failures_report - } - spy = Spy() - result = sut.run_analyzer(opts, spy.call) - output_files = [] - for entry in os.listdir(tmpdir): - output_files.append(entry) - return (result, spy.arg, output_files) - - def test_run_analyzer(self): - content = "int div(int n, int d) { return n / d; }" - (result, fwds, _) = RunAnalyzerTest.run_analyzer(content, False) - self.assertEqual(None, fwds) - self.assertEqual(0, result['exit_code']) - - def test_run_analyzer_crash(self): - content = "int div(int n, int d) { return n / d }" - (result, fwds, _) = RunAnalyzerTest.run_analyzer(content, False) - self.assertEqual(None, fwds) - self.assertEqual(1, result['exit_code']) - - def test_run_analyzer_crash_and_forwarded(self): - content = "int div(int n, int d) { return n / d }" - (_, fwds, _) = RunAnalyzerTest.run_analyzer(content, True) - self.assertEqual(1, fwds['exit_code']) - self.assertTrue(len(fwds['error_output']) > 0) - - def test_run_analyzer_with_sarif(self): - content = "int div(int n, int d) { return n / d; }" - (result, fwds, output_files) = RunAnalyzerTest.run_analyzer(content, False, output_format='sarif') - self.assertEqual(None, fwds) - self.assertEqual(0, result['exit_code']) - - pattern = re.compile(r'^result-.+\.sarif$') - for f in output_files: - if re.match(pattern, f): - return - self.fail('no result sarif files found in output') - - -class ReportFailureTest(unittest.TestCase): - - def assertUnderFailures(self, path): - self.assertEqual('failures', os.path.basename(os.path.dirname(path))) - - def test_report_failure_create_files(self): - with libear.TemporaryDirectory() as tmpdir: - # create input file - filename = os.path.join(tmpdir, 'test.c') - with open(filename, 'w') as handle: - handle.write('int main() { return 0') - uname_msg = ' '.join(os.uname()) + os.linesep - error_msg = 'this is my error output' - # execute test - opts = { - 'clang': 'clang', - 'directory': os.getcwd(), - 'flags': [], - 'file': filename, - 'output_dir': tmpdir, - 'language': 'c', - 'error_type': 'other_error', - 'error_output': error_msg, - 'exit_code': 13 - } - sut.report_failure(opts) - # verify the result - result = dict() - pp_file = None - for root, _, files in os.walk(tmpdir): - keys = [os.path.join(root, name) for name in files] - for key in keys: - with open(key, 'r') as handle: - result[key] = handle.readlines() - if re.match(r'^(.*/)+clang(.*)\.i$', key): - pp_file = key - - # prepocessor file generated - self.assertUnderFailures(pp_file) - # info file generated and content dumped - info_file = pp_file + '.info.txt' - self.assertTrue(info_file in result) - self.assertEqual('Other Error\n', result[info_file][1]) - self.assertEqual(uname_msg, result[info_file][3]) - # error file generated and content dumped - error_file = pp_file + '.stderr.txt' - self.assertTrue(error_file in result) - self.assertEqual([error_msg], result[error_file]) - - -class AnalyzerTest(unittest.TestCase): - - def test_nodebug_macros_appended(self): - def test(flags): - spy = Spy() - opts = {'flags': flags, 'force_debug': True} - self.assertEqual(spy.success, - sut.filter_debug_flags(opts, spy.call)) - return spy.arg['flags'] - - self.assertEqual(['-UNDEBUG'], test([])) - self.assertEqual(['-DNDEBUG', '-UNDEBUG'], test(['-DNDEBUG'])) - self.assertEqual(['-DSomething', '-UNDEBUG'], test(['-DSomething'])) - - def test_set_language_fall_through(self): - def language(expected, input): - spy = Spy() - input.update({'compiler': 'c', 'file': 'test.c'}) - self.assertEqual(spy.success, sut.language_check(input, spy.call)) - self.assertEqual(expected, spy.arg['language']) - - language('c', {'language': 'c', 'flags': []}) - language('c++', {'language': 'c++', 'flags': []}) - - def test_set_language_stops_on_not_supported(self): - spy = Spy() - input = { - 'compiler': 'c', - 'flags': [], - 'file': 'test.java', - 'language': 'java' - } - self.assertIsNone(sut.language_check(input, spy.call)) - self.assertIsNone(spy.arg) - - def test_set_language_sets_flags(self): - def flags(expected, input): - spy = Spy() - input.update({'compiler': 'c', 'file': 'test.c'}) - self.assertEqual(spy.success, sut.language_check(input, spy.call)) - self.assertEqual(expected, spy.arg['flags']) - - flags(['-x', 'c'], {'language': 'c', 'flags': []}) - flags(['-x', 'c++'], {'language': 'c++', 'flags': []}) - - def test_set_language_from_filename(self): - def language(expected, input): - spy = Spy() - input.update({'language': None, 'flags': []}) - self.assertEqual(spy.success, sut.language_check(input, spy.call)) - self.assertEqual(expected, spy.arg['language']) - - language('c', {'file': 'file.c', 'compiler': 'c'}) - language('c++', {'file': 'file.c', 'compiler': 'c++'}) - language('c++', {'file': 'file.cxx', 'compiler': 'c'}) - language('c++', {'file': 'file.cxx', 'compiler': 'c++'}) - language('c++', {'file': 'file.cpp', 'compiler': 'c++'}) - language('c-cpp-output', {'file': 'file.i', 'compiler': 'c'}) - language('c++-cpp-output', {'file': 'file.i', 'compiler': 'c++'}) - - def test_arch_loop_sets_flags(self): - def flags(archs): - spy = Spy() - input = {'flags': [], 'arch_list': archs} - sut.arch_check(input, spy.call) - return spy.arg['flags'] - - self.assertEqual([], flags([])) - self.assertEqual(['-arch', 'i386'], flags(['i386'])) - self.assertEqual(['-arch', 'i386'], flags(['i386', 'ppc'])) - self.assertEqual(['-arch', 'sparc'], flags(['i386', 'sparc'])) - - def test_arch_loop_stops_on_not_supported(self): - def stop(archs): - spy = Spy() - input = {'flags': [], 'arch_list': archs} - self.assertIsNone(sut.arch_check(input, spy.call)) - self.assertIsNone(spy.arg) - - stop(['ppc']) - stop(['ppc64']) - - -@sut.require([]) -def method_without_expecteds(opts): - return 0 - - -@sut.require(['this', 'that']) -def method_with_expecteds(opts): - return 0 - - -@sut.require([]) -def method_exception_from_inside(opts): - raise Exception('here is one') - - -class RequireDecoratorTest(unittest.TestCase): - - def test_method_without_expecteds(self): - self.assertEqual(method_without_expecteds(dict()), 0) - self.assertEqual(method_without_expecteds({}), 0) - self.assertEqual(method_without_expecteds({'this': 2}), 0) - self.assertEqual(method_without_expecteds({'that': 3}), 0) - - def test_method_with_expecteds(self): - self.assertRaises(KeyError, method_with_expecteds, dict()) - self.assertRaises(KeyError, method_with_expecteds, {}) - self.assertRaises(KeyError, method_with_expecteds, {'this': 2}) - self.assertRaises(KeyError, method_with_expecteds, {'that': 3}) - self.assertEqual(method_with_expecteds({'this': 0, 'that': 3}), 0) - - def test_method_exception_not_caught(self): - self.assertRaises(Exception, method_exception_from_inside, dict()) - - -class PrefixWithTest(unittest.TestCase): - - def test_gives_empty_on_empty(self): - res = sut.prefix_with(0, []) - self.assertFalse(res) - - def test_interleaves_prefix(self): - res = sut.prefix_with(0, [1, 2, 3]) - self.assertListEqual([0, 1, 0, 2, 0, 3], res) - - -class MergeCtuMapTest(unittest.TestCase): - - def test_no_map_gives_empty(self): - pairs = sut.create_global_ctu_extdef_map([]) - self.assertFalse(pairs) - - def test_multiple_maps_merged(self): - concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', - 'c:@F@fun2#I# ast/fun2.c.ast', - 'c:@F@fun3#I# ast/fun3.c.ast'] - pairs = sut.create_global_ctu_extdef_map(concat_map) - self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) - self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) - self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs) - self.assertEqual(3, len(pairs)) - - def test_not_unique_func_left_out(self): - concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', - 'c:@F@fun2#I# ast/fun2.c.ast', - 'c:@F@fun1#I# ast/fun7.c.ast'] - pairs = sut.create_global_ctu_extdef_map(concat_map) - self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) - self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs) - self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) - self.assertEqual(1, len(pairs)) - - def test_duplicates_are_kept(self): - concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', - 'c:@F@fun2#I# ast/fun2.c.ast', - 'c:@F@fun1#I# ast/fun1.c.ast'] - pairs = sut.create_global_ctu_extdef_map(concat_map) - self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) - self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) - self.assertEqual(2, len(pairs)) - - def test_space_handled_in_source(self): - concat_map = ['c:@F@fun1#I# ast/f un.c.ast'] - pairs = sut.create_global_ctu_extdef_map(concat_map) - self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs) - self.assertEqual(1, len(pairs)) - - -class ExtdefMapSrcToAstTest(unittest.TestCase): - - def test_empty_gives_empty(self): - fun_ast_lst = sut.extdef_map_list_src_to_ast([]) - self.assertFalse(fun_ast_lst) - - def test_sources_to_asts(self): - fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f1.c'), - 'c:@F@f2#I# ' + os.path.join(os.sep + 'path', 'f2.c')] - fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) - self.assertTrue('c:@F@f1#I# ' + - os.path.join('ast', 'path', 'f1.c.ast') - in fun_ast_lst) - self.assertTrue('c:@F@f2#I# ' + - os.path.join('ast', 'path', 'f2.c.ast') - in fun_ast_lst) - self.assertEqual(2, len(fun_ast_lst)) - - def test_spaces_handled(self): - fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f 1.c')] - fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) - self.assertTrue('c:@F@f1#I# ' + - os.path.join('ast', 'path', 'f 1.c.ast') - in fun_ast_lst) - self.assertEqual(1, len(fun_ast_lst)) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_clang.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_clang.py deleted file mode 100644 index 80ce61a1fab17..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_clang.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -import libscanbuild.clang as sut -import unittest -import os.path -import sys - - -class ClangGetVersion(unittest.TestCase): - def test_get_version_is_not_empty(self): - self.assertTrue(sut.get_version('clang')) - - def test_get_version_throws(self): - with self.assertRaises(OSError): - sut.get_version('notexists') - - -class ClangGetArgumentsTest(unittest.TestCase): - def test_get_clang_arguments(self): - with libear.TemporaryDirectory() as tmpdir: - filename = os.path.join(tmpdir, 'test.c') - with open(filename, 'w') as handle: - handle.write('') - - result = sut.get_arguments( - ['clang', '-c', filename, '-DNDEBUG', '-Dvar="this is it"'], - tmpdir) - - self.assertTrue('NDEBUG' in result) - self.assertTrue('var="this is it"' in result) - - def test_get_clang_arguments_fails(self): - with self.assertRaises(Exception): - sut.get_arguments(['clang', '-x', 'c', 'notexist.c'], '.') - - def test_get_clang_arguments_fails_badly(self): - with self.assertRaises(OSError): - sut.get_arguments(['notexist'], '.') - - -class ClangGetCheckersTest(unittest.TestCase): - def test_get_checkers(self): - # this test is only to see is not crashing - result = sut.get_checkers('clang', []) - self.assertTrue(len(result)) - # do check result types - string_type = unicode if sys.version_info < (3,) else str - for key, value in result.items(): - self.assertEqual(string_type, type(key)) - self.assertEqual(string_type, type(value[0])) - self.assertEqual(bool, type(value[1])) - - def test_get_active_checkers(self): - # this test is only to see is not crashing - result = sut.get_active_checkers('clang', []) - self.assertTrue(len(result)) - # do check result types - for value in result: - self.assertEqual(str, type(value)) - - def test_is_active(self): - test = sut.is_active(['a', 'b.b', 'c.c.c']) - - self.assertTrue(test('a')) - self.assertTrue(test('a.b')) - self.assertTrue(test('b.b')) - self.assertTrue(test('b.b.c')) - self.assertTrue(test('c.c.c.p')) - - self.assertFalse(test('ab')) - self.assertFalse(test('ba')) - self.assertFalse(test('bb')) - self.assertFalse(test('c.c')) - self.assertFalse(test('b')) - self.assertFalse(test('d')) - - def test_parse_checkers(self): - lines = [ - 'OVERVIEW: Clang Static Analyzer Checkers List', - '', - 'CHECKERS:', - ' checker.one Checker One description', - ' checker.two', - ' Checker Two description'] - result = dict(sut.parse_checkers(lines)) - self.assertTrue('checker.one' in result) - self.assertEqual('Checker One description', result.get('checker.one')) - self.assertTrue('checker.two' in result) - self.assertEqual('Checker Two description', result.get('checker.two')) - - -class ClangIsCtuCapableTest(unittest.TestCase): - def test_ctu_not_found(self): - is_ctu = sut.is_ctu_capable('not-found-clang-extdef-mapping') - self.assertFalse(is_ctu) - - -class ClangGetTripleArchTest(unittest.TestCase): - def test_arch_is_not_empty(self): - arch = sut.get_triple_arch(['clang', '-E', '-'], '.') - self.assertTrue(len(arch) > 0) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_compilation.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_compilation.py deleted file mode 100644 index e8ad3d8c99ffb..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_compilation.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libscanbuild.compilation as sut -import unittest - - -class CompilerTest(unittest.TestCase): - - def test_is_compiler_call(self): - self.assertIsNotNone(sut.compiler_language(['clang'])) - self.assertIsNotNone(sut.compiler_language(['clang-3.6'])) - self.assertIsNotNone(sut.compiler_language(['clang++'])) - self.assertIsNotNone(sut.compiler_language(['clang++-3.5.1'])) - self.assertIsNotNone(sut.compiler_language(['cc'])) - self.assertIsNotNone(sut.compiler_language(['c++'])) - self.assertIsNotNone(sut.compiler_language(['gcc'])) - self.assertIsNotNone(sut.compiler_language(['g++'])) - self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/gcc'])) - self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/g++'])) - self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/clang'])) - self.assertIsNotNone( - sut.compiler_language(['armv7_neno-linux-gnueabi-g++'])) - - self.assertIsNone(sut.compiler_language([])) - self.assertIsNone(sut.compiler_language([''])) - self.assertIsNone(sut.compiler_language(['ld'])) - self.assertIsNone(sut.compiler_language(['as'])) - self.assertIsNone(sut.compiler_language(['/usr/local/bin/compiler'])) - - -class SplitTest(unittest.TestCase): - - def test_detect_cxx_from_compiler_name(self): - def test(cmd): - result = sut.split_command([cmd, '-c', 'src.c']) - self.assertIsNotNone(result, "wrong input for test") - return result.compiler == 'c++' - - self.assertFalse(test('cc')) - self.assertFalse(test('gcc')) - self.assertFalse(test('clang')) - - self.assertTrue(test('c++')) - self.assertTrue(test('g++')) - self.assertTrue(test('g++-5.3.1')) - self.assertTrue(test('clang++')) - self.assertTrue(test('clang++-3.7.1')) - self.assertTrue(test('armv7_neno-linux-gnueabi-g++')) - - def test_action(self): - self.assertIsNotNone(sut.split_command(['clang', 'source.c'])) - self.assertIsNotNone(sut.split_command(['clang', '-c', 'source.c'])) - self.assertIsNotNone(sut.split_command(['clang', '-c', 'source.c', - '-MF', 'a.d'])) - - self.assertIsNone(sut.split_command(['clang', '-E', 'source.c'])) - self.assertIsNone(sut.split_command(['clang', '-c', '-E', 'source.c'])) - self.assertIsNone(sut.split_command(['clang', '-c', '-M', 'source.c'])) - self.assertIsNone( - sut.split_command(['clang', '-c', '-MM', 'source.c'])) - - def test_source_file(self): - def test(expected, cmd): - self.assertEqual(expected, sut.split_command(cmd).files) - - test(['src.c'], ['clang', 'src.c']) - test(['src.c'], ['clang', '-c', 'src.c']) - test(['src.C'], ['clang', '-x', 'c', 'src.C']) - test(['src.cpp'], ['clang++', '-c', 'src.cpp']) - test(['s1.c', 's2.c'], ['clang', '-c', 's1.c', 's2.c']) - test(['s1.c', 's2.c'], ['cc', 's1.c', 's2.c', '-ldep', '-o', 'a.out']) - test(['src.c'], ['clang', '-c', '-I', './include', 'src.c']) - test(['src.c'], ['clang', '-c', '-I', '/opt/me/include', 'src.c']) - test(['src.c'], ['clang', '-c', '-D', 'config=file.c', 'src.c']) - - self.assertIsNone( - sut.split_command(['cc', 'this.o', 'that.o', '-o', 'a.out'])) - self.assertIsNone( - sut.split_command(['cc', 'this.o', '-lthat', '-o', 'a.out'])) - - def test_filter_flags(self): - def test(expected, flags): - command = ['clang', '-c', 'src.c'] + flags - self.assertEqual(expected, sut.split_command(command).flags) - - def same(expected): - test(expected, expected) - - def filtered(flags): - test([], flags) - - same([]) - same(['-I', '/opt/me/include', '-DNDEBUG', '-ULIMITS']) - same(['-O', '-O2']) - same(['-m32', '-mmms']) - same(['-Wall', '-Wno-unused', '-g', '-funroll-loops']) - - filtered([]) - filtered(['-lclien', '-L/opt/me/lib', '-L', '/opt/you/lib']) - filtered(['-static']) - filtered(['-MD', '-MT', 'something']) - filtered(['-MMD', '-MF', 'something']) - - -class SourceClassifierTest(unittest.TestCase): - - def test_sources(self): - self.assertIsNone(sut.classify_source('file.o')) - self.assertIsNone(sut.classify_source('file.exe')) - self.assertIsNone(sut.classify_source('/path/file.o')) - self.assertIsNone(sut.classify_source('clang')) - - self.assertEqual('c', sut.classify_source('file.c')) - self.assertEqual('c', sut.classify_source('./file.c')) - self.assertEqual('c', sut.classify_source('/path/file.c')) - self.assertEqual('c++', sut.classify_source('file.c', False)) - self.assertEqual('c++', sut.classify_source('./file.c', False)) - self.assertEqual('c++', sut.classify_source('/path/file.c', False)) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_intercept.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_intercept.py deleted file mode 100644 index 5473b88d833cc..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_intercept.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear -import libscanbuild.intercept as sut -import unittest -import os.path - - -class InterceptUtilTest(unittest.TestCase): - - def test_format_entry_filters_action(self): - def test(command): - trace = {'command': command, 'directory': '/opt/src/project'} - return list(sut.format_entry(trace)) - - self.assertTrue(test(['cc', '-c', 'file.c', '-o', 'file.o'])) - self.assertFalse(test(['cc', '-E', 'file.c'])) - self.assertFalse(test(['cc', '-MM', 'file.c'])) - self.assertFalse(test(['cc', 'this.o', 'that.o', '-o', 'a.out'])) - - def test_format_entry_normalize_filename(self): - parent = os.path.join(os.sep, 'home', 'me') - current = os.path.join(parent, 'project') - - def test(filename): - trace = {'directory': current, 'command': ['cc', '-c', filename]} - return list(sut.format_entry(trace))[0]['file'] - - self.assertEqual(os.path.join(current, 'file.c'), test('file.c')) - self.assertEqual(os.path.join(current, 'file.c'), test('./file.c')) - self.assertEqual(os.path.join(parent, 'file.c'), test('../file.c')) - self.assertEqual(os.path.join(current, 'file.c'), - test(os.path.join(current, 'file.c'))) - - def test_sip(self): - def create_status_report(filename, message): - content = """#!/usr/bin/env sh - echo 'sa-la-la-la' - echo 'la-la-la' - echo '{0}' - echo 'sa-la-la-la' - echo 'la-la-la' - """.format(message) - lines = [line.strip() for line in content.split('\n')] - with open(filename, 'w') as handle: - handle.write('\n'.join(lines)) - handle.close() - os.chmod(filename, 0x1ff) - - def create_csrutil(dest_dir, status): - filename = os.path.join(dest_dir, 'csrutil') - message = 'System Integrity Protection status: {0}'.format(status) - return create_status_report(filename, message) - - def create_sestatus(dest_dir, status): - filename = os.path.join(dest_dir, 'sestatus') - message = 'SELinux status:\t{0}'.format(status) - return create_status_report(filename, message) - - ENABLED = 'enabled' - DISABLED = 'disabled' - - OSX = 'darwin' - - with libear.TemporaryDirectory() as tmpdir: - saved = os.environ['PATH'] - try: - os.environ['PATH'] = tmpdir + ':' + saved - - create_csrutil(tmpdir, ENABLED) - self.assertTrue(sut.is_preload_disabled(OSX)) - - create_csrutil(tmpdir, DISABLED) - self.assertFalse(sut.is_preload_disabled(OSX)) - finally: - os.environ['PATH'] = saved - - saved = os.environ['PATH'] - try: - os.environ['PATH'] = '' - # shall be false when it's not in the path - self.assertFalse(sut.is_preload_disabled(OSX)) - - self.assertFalse(sut.is_preload_disabled('unix')) - finally: - os.environ['PATH'] = saved diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_libear.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_libear.py deleted file mode 100644 index 933da50242ff4..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_libear.py +++ /dev/null @@ -1,29 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libear as sut -import unittest -import os.path - - -class TemporaryDirectoryTest(unittest.TestCase): - def test_creates_directory(self): - dirname = None - with sut.TemporaryDirectory() as tmpdir: - self.assertTrue(os.path.isdir(tmpdir)) - dirname = tmpdir - self.assertIsNotNone(dirname) - self.assertFalse(os.path.exists(dirname)) - - def test_removes_directory_when_exception(self): - dirname = None - try: - with sut.TemporaryDirectory() as tmpdir: - self.assertTrue(os.path.isdir(tmpdir)) - dirname = tmpdir - raise RuntimeError('message') - except: - self.assertIsNotNone(dirname) - self.assertFalse(os.path.exists(dirname)) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_report.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_report.py deleted file mode 100644 index 57f0331c46219..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_report.py +++ /dev/null @@ -1,661 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import json -import libear -import libscanbuild.report as sut -import unittest -import os -import os.path - - -def run_bug_parse(content): - with libear.TemporaryDirectory() as tmpdir: - file_name = os.path.join(tmpdir, 'test.html') - with open(file_name, 'w') as handle: - handle.writelines(content) - for bug in sut.parse_bug_html(file_name): - return bug - - -def run_crash_parse(content, preproc): - with libear.TemporaryDirectory() as tmpdir: - file_name = os.path.join(tmpdir, preproc + '.info.txt') - with open(file_name, 'w') as handle: - handle.writelines(content) - return sut.parse_crash(file_name) - - -class ParseFileTest(unittest.TestCase): - - def test_parse_bug(self): - content = [ - "some header\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "some tails\n"] - result = run_bug_parse(content) - self.assertEqual(result['bug_category'], 'Logic error') - self.assertEqual(result['bug_path_length'], 4) - self.assertEqual(result['bug_line'], 5) - self.assertEqual(result['bug_description'], 'Division by zero') - self.assertEqual(result['bug_type'], 'Division by zero') - self.assertEqual(result['bug_file'], 'xx') - - def test_parse_bug_empty(self): - content = [] - result = run_bug_parse(content) - self.assertEqual(result['bug_category'], 'Other') - self.assertEqual(result['bug_path_length'], 1) - self.assertEqual(result['bug_line'], 0) - - def test_parse_crash(self): - content = [ - "/some/path/file.c\n", - "Some very serious Error\n", - "bla\n", - "bla-bla\n"] - result = run_crash_parse(content, 'file.i') - self.assertEqual(result['source'], content[0].rstrip()) - self.assertEqual(result['problem'], content[1].rstrip()) - self.assertEqual(os.path.basename(result['file']), - 'file.i') - self.assertEqual(os.path.basename(result['info']), - 'file.i.info.txt') - self.assertEqual(os.path.basename(result['stderr']), - 'file.i.stderr.txt') - - def test_parse_real_crash(self): - import libscanbuild.analyze as sut2 - import re - with libear.TemporaryDirectory() as tmpdir: - filename = os.path.join(tmpdir, 'test.c') - with open(filename, 'w') as handle: - handle.write('int main() { return 0') - # produce failure report - opts = { - 'clang': 'clang', - 'directory': os.getcwd(), - 'flags': [], - 'file': filename, - 'output_dir': tmpdir, - 'language': 'c', - 'error_type': 'other_error', - 'error_output': 'some output', - 'exit_code': 13 - } - sut2.report_failure(opts) - # find the info file - pp_file = None - for root, _, files in os.walk(tmpdir): - keys = [os.path.join(root, name) for name in files] - for key in keys: - if re.match(r'^(.*/)+clang(.*)\.i$', key): - pp_file = key - self.assertIsNot(pp_file, None) - # read the failure report back - result = sut.parse_crash(pp_file + '.info.txt') - self.assertEqual(result['source'], filename) - self.assertEqual(result['problem'], 'Other Error') - self.assertEqual(result['file'], pp_file) - self.assertEqual(result['info'], pp_file + '.info.txt') - self.assertEqual(result['stderr'], pp_file + '.stderr.txt') - - -class ReportMethodTest(unittest.TestCase): - - def test_chop(self): - self.assertEqual('file', sut.chop('/prefix', '/prefix/file')) - self.assertEqual('file', sut.chop('/prefix/', '/prefix/file')) - self.assertEqual('lib/file', sut.chop('/prefix/', '/prefix/lib/file')) - self.assertEqual('/prefix/file', sut.chop('', '/prefix/file')) - - def test_chop_when_cwd(self): - self.assertEqual('../src/file', sut.chop('/cwd', '/src/file')) - self.assertEqual('../src/file', sut.chop('/prefix/cwd', - '/prefix/src/file')) - - -class GetPrefixFromCompilationDatabaseTest(unittest.TestCase): - - def test_with_different_filenames(self): - self.assertEqual( - sut.commonprefix(['/tmp/a.c', '/tmp/b.c']), '/tmp') - - def test_with_different_dirnames(self): - self.assertEqual( - sut.commonprefix(['/tmp/abs/a.c', '/tmp/ack/b.c']), '/tmp') - - def test_no_common_prefix(self): - self.assertEqual( - sut.commonprefix(['/tmp/abs/a.c', '/usr/ack/b.c']), '/') - - def test_with_single_file(self): - self.assertEqual( - sut.commonprefix(['/tmp/a.c']), '/tmp') - - def test_empty(self): - self.assertEqual( - sut.commonprefix([]), '') - -class MergeSarifTest(unittest.TestCase): - - def test_merging_sarif(self): - sarif1 = { - '$schema': 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json', - 'runs': [ - { - 'artifacts': [ - { - 'length': 100, - 'location': { - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'mimeType': 'text/plain', - 'roles': [ - 'resultFile' - ] - } - ], - 'columnKind': 'unicodeCodePoints', - 'results': [ - { - 'codeFlows': [ - { - 'threadFlows': [ - { - 'locations': [ - { - 'importance': 'important', - 'location': { - 'message': { - 'text': 'test message 1' - }, - 'physicalLocation': { - 'artifactLocation': { - 'index': 0, - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'region': { - 'endColumn': 5, - 'startColumn': 1, - 'startLine': 2 - } - } - } - } - ] - } - ] - } - ] - }, - { - 'codeFlows': [ - { - 'threadFlows': [ - { - 'locations': [ - { - 'importance': 'important', - 'location': { - 'message': { - 'text': 'test message 2' - }, - 'physicalLocation': { - 'artifactLocation': { - 'index': 0, - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'region': { - 'endColumn': 23, - 'startColumn': 9, - 'startLine': 10 - } - } - } - } - ] - } - ] - } - ] - } - ], - 'tool': { - 'driver': { - 'fullName': 'clang static analyzer', - 'language': 'en-US', - 'name': 'clang', - 'rules': [ - { - 'fullDescription': { - 'text': 'test rule for merge sarif test' - }, - 'helpUrl': '//clang/tools/scan-build-py/tests/unit/test_report.py', - 'id': 'testId', - 'name': 'testName' - } - ], - 'version': 'test clang' - } - } - } - ], - 'version': '2.1.0' - } - sarif2 = { - '$schema': 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json', - 'runs': [ - { - 'artifacts': [ - { - 'length': 1523, - 'location': { - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'mimeType': 'text/plain', - 'roles': [ - 'resultFile' - ] - } - ], - 'columnKind': 'unicodeCodePoints', - 'results': [ - { - 'codeFlows': [ - { - 'threadFlows': [ - { - 'locations': [ - { - 'importance': 'important', - 'location': { - 'message': { - 'text': 'test message 3' - }, - 'physicalLocation': { - 'artifactLocation': { - 'index': 0, - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'region': { - 'endColumn': 99, - 'startColumn': 99, - 'startLine': 17 - } - } - } - } - ] - } - ] - } - ] - }, - { - 'codeFlows': [ - { - 'threadFlows': [ - { - 'locations': [ - { - 'importance': 'important', - 'location': { - 'message': { - 'text': 'test message 4' - }, - 'physicalLocation': { - 'artifactLocation': { - 'index': 0, - 'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py' - }, - 'region': { - 'endColumn': 305, - 'startColumn': 304, - 'startLine': 1 - } - } - } - } - ] - } - ] - } - ] - } - ], - 'tool': { - 'driver': { - 'fullName': 'clang static analyzer', - 'language': 'en-US', - 'name': 'clang', - 'rules': [ - { - 'fullDescription': { - 'text': 'test rule for merge sarif test' - }, - 'helpUrl': '//clang/tools/scan-build-py/tests/unit/test_report.py', - 'id': 'testId', - 'name': 'testName' - } - ], - 'version': 'test clang' - } - } - } - ], - 'version': '2.1.0' - } - - contents = [sarif1, sarif2] - with libear.TemporaryDirectory() as tmpdir: - for idx, content in enumerate(contents): - file_name = os.path.join(tmpdir, 'results-{}.sarif'.format(idx)) - with open(file_name, 'w') as handle: - json.dump(content, handle) - - sut.merge_sarif_files(tmpdir, sort_files=True) - - self.assertIn('results-merged.sarif', os.listdir(tmpdir)) - with open(os.path.join(tmpdir, 'results-merged.sarif')) as f: - merged = json.load(f) - self.assertEqual(len(merged['runs']), 2) - self.assertEqual(len(merged['runs'][0]['results']), 2) - self.assertEqual(len(merged['runs'][1]['results']), 2) - - expected = sarif1 - for run in sarif2['runs']: - expected['runs'].append(run) - - self.assertEqual(merged, expected) - - def test_merge_updates_embedded_link(self): - sarif1 = { - 'runs': [ - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 1-1 [link](sarif:/runs/1/results/0) [link2](sarif:/runs/1/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 1-2 [link](sarif:/runs/1/results/0)' - } - } - ] - } - ] - } - ] - }, - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 2-1 [link](sarif:/runs/0/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 2-2 [link](sarif:/runs/0/results/0)' - } - } - ] - } - ] - } - ] - } - ] - } - sarif2 = { - 'runs': [ - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 3-1 [link](sarif:/runs/1/results/0) [link2](sarif:/runs/1/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 3-2 [link](sarif:/runs/1/results/0)' - } - } - ] - } - ] - } - ], - }, - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 4-1 [link](sarif:/runs/0/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 4-2 [link](sarif:/runs/0/results/0)' - } - } - ] - } - ] - } - ] - } - ] - } - sarif3 = { - 'runs': [ - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 5-1 [link](sarif:/runs/1/results/0) [link2](sarif:/runs/1/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 5-2 [link](sarif:/runs/1/results/0)' - } - } - ] - } - ] - } - ], - }, - { - 'results': [ - { - 'codeFlows': [ - { - 'message': { - 'text': 'test message 6-1 [link](sarif:/runs/0/results/0)' - }, - 'threadFlows': [ - { - 'message': { - 'text': 'test message 6-2 [link](sarif:/runs/0/results/0)' - } - } - ] - } - ] - } - ] - } - ] - } - - contents = [sarif1, sarif2, sarif3] - - with libear.TemporaryDirectory() as tmpdir: - for idx, content in enumerate(contents): - file_name = os.path.join(tmpdir, 'results-{}.sarif'.format(idx)) - with open(file_name, 'w') as handle: - json.dump(content, handle) - - sut.merge_sarif_files(tmpdir, sort_files=True) - - self.assertIn('results-merged.sarif', os.listdir(tmpdir)) - with open(os.path.join(tmpdir, 'results-merged.sarif')) as f: - merged = json.load(f) - self.assertEqual(len(merged['runs']), 6) - - code_flows = [merged['runs'][x]['results'][0]['codeFlows'][0]['message']['text'] for x in range(6)] - thread_flows = [merged['runs'][x]['results'][0]['codeFlows'][0]['threadFlows'][0]['message']['text'] for x in range(6)] - - # The run index should be updated for the second and third sets of runs - self.assertEqual(code_flows, - [ - 'test message 1-1 [link](sarif:/runs/1/results/0) [link2](sarif:/runs/1/results/0)', - 'test message 2-1 [link](sarif:/runs/0/results/0)', - 'test message 3-1 [link](sarif:/runs/3/results/0) [link2](sarif:/runs/3/results/0)', - 'test message 4-1 [link](sarif:/runs/2/results/0)', - 'test message 5-1 [link](sarif:/runs/5/results/0) [link2](sarif:/runs/5/results/0)', - 'test message 6-1 [link](sarif:/runs/4/results/0)' - ]) - self.assertEquals(thread_flows, - [ - 'test message 1-2 [link](sarif:/runs/1/results/0)', - 'test message 2-2 [link](sarif:/runs/0/results/0)', - 'test message 3-2 [link](sarif:/runs/3/results/0)', - 'test message 4-2 [link](sarif:/runs/2/results/0)', - 'test message 5-2 [link](sarif:/runs/5/results/0)', - 'test message 6-2 [link](sarif:/runs/4/results/0)' - ]) - - def test_overflow_run_count(self): - sarif1 = { - 'runs': [ - {'results': [{ - 'message': {'text': 'run 1-0 [link](sarif:/runs/1/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-1 [link](sarif:/runs/2/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-2 [link](sarif:/runs/3/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-3 [link](sarif:/runs/4/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-4 [link](sarif:/runs/5/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-5 [link](sarif:/runs/6/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-6 [link](sarif:/runs/7/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-7 [link](sarif:/runs/8/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-8 [link](sarif:/runs/9/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 1-9 [link](sarif:/runs/0/results/0)'} - }]} - ] - } - sarif2 = { - 'runs': [ - {'results': [{ - 'message': {'text': 'run 2-0 [link](sarif:/runs/1/results/0) [link2](sarif:/runs/2/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-1 [link](sarif:/runs/2/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-2 [link](sarif:/runs/3/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-3 [link](sarif:/runs/4/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-4 [link](sarif:/runs/5/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-5 [link](sarif:/runs/6/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-6 [link](sarif:/runs/7/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-7 [link](sarif:/runs/8/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-8 [link](sarif:/runs/9/results/0)'} - }]}, - {'results': [{ - 'message': {'text': 'run 2-9 [link](sarif:/runs/0/results/0)'} - }]} - ] - } - - contents = [sarif1, sarif2] - with libear.TemporaryDirectory() as tmpdir: - for idx, content in enumerate(contents): - file_name = os.path.join(tmpdir, 'results-{}.sarif'.format(idx)) - with open(file_name, 'w') as handle: - json.dump(content, handle) - - sut.merge_sarif_files(tmpdir, sort_files=True) - - self.assertIn('results-merged.sarif', os.listdir(tmpdir)) - with open(os.path.join(tmpdir, 'results-merged.sarif')) as f: - merged = json.load(f) - self.assertEqual(len(merged['runs']), 20) - - messages = [merged['runs'][x]['results'][0]['message']['text'] for x in range(20)] - self.assertEqual(messages, - [ - 'run 1-0 [link](sarif:/runs/1/results/0)', - 'run 1-1 [link](sarif:/runs/2/results/0)', - 'run 1-2 [link](sarif:/runs/3/results/0)', - 'run 1-3 [link](sarif:/runs/4/results/0)', - 'run 1-4 [link](sarif:/runs/5/results/0)', - 'run 1-5 [link](sarif:/runs/6/results/0)', - 'run 1-6 [link](sarif:/runs/7/results/0)', - 'run 1-7 [link](sarif:/runs/8/results/0)', - 'run 1-8 [link](sarif:/runs/9/results/0)', - 'run 1-9 [link](sarif:/runs/0/results/0)', - 'run 2-0 [link](sarif:/runs/11/results/0) [link2](sarif:/runs/12/results/0)', - 'run 2-1 [link](sarif:/runs/12/results/0)', - 'run 2-2 [link](sarif:/runs/13/results/0)', - 'run 2-3 [link](sarif:/runs/14/results/0)', - 'run 2-4 [link](sarif:/runs/15/results/0)', - 'run 2-5 [link](sarif:/runs/16/results/0)', - 'run 2-6 [link](sarif:/runs/17/results/0)', - 'run 2-7 [link](sarif:/runs/18/results/0)', - 'run 2-8 [link](sarif:/runs/19/results/0)', - 'run 2-9 [link](sarif:/runs/10/results/0)' - ]) diff --git a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_shell.py b/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_shell.py deleted file mode 100644 index 6ffbb8782a953..0000000000000 --- a/interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/unit/test_shell.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -import libscanbuild.shell as sut -import unittest - - -class ShellTest(unittest.TestCase): - - def test_encode_decode_are_same(self): - def test(value): - self.assertEqual(sut.encode(sut.decode(value)), value) - - test("") - test("clang") - test("clang this and that") - - def test_decode_encode_are_same(self): - def test(value): - self.assertEqual(sut.decode(sut.encode(value)), value) - - test([]) - test(['clang']) - test(['clang', 'this', 'and', 'that']) - test(['clang', 'this and', 'that']) - test(['clang', "it's me", 'again']) - test(['clang', 'some "words" are', 'quoted']) - - def test_encode(self): - self.assertEqual(sut.encode(['clang', "it's me", 'again']), - 'clang "it\'s me" again') - self.assertEqual(sut.encode(['clang', "it(s me", 'again)']), - 'clang "it(s me" "again)"') - self.assertEqual(sut.encode(['clang', 'redirect > it']), - 'clang "redirect > it"') - self.assertEqual(sut.encode(['clang', '-DKEY="VALUE"']), - 'clang -DKEY=\\"VALUE\\"') - self.assertEqual(sut.encode(['clang', '-DKEY="value with spaces"']), - 'clang -DKEY=\\"value with spaces\\"') diff --git a/interpreter/llvm/src/utils/UpdateTestChecks/__init__.py b/interpreter/llvm/src/utils/UpdateTestChecks/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/utils/benchmark/AUTHORS b/interpreter/llvm/src/utils/benchmark/AUTHORS deleted file mode 100644 index 052a383f77cdf..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/AUTHORS +++ /dev/null @@ -1,47 +0,0 @@ -# This is the official list of benchmark authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. -# -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. -# -# Please keep the list sorted. - -Albert Pretorius -Arne Beer -Carto -Christopher Seymour -David Coeurjolly -Deniz Evrenci -Dirac Research -Dominik Czarnota -Eric Fiselier -Eugene Zhuk -Evgeny Safronov -Felix Homann -Google Inc. -International Business Machines Corporation -Ismael Jimenez Martinez -Jern-Kuan Leong -JianXiong Zhou -Joao Paulo Magalhaes -Jussi Knuuttila -Kaito Udagawa -Kishan Kumar -Lei Xu -Matt Clarkson -Maxim Vafin -MongoDB Inc. -Nick Hutchinson -Oleksandr Sochka -Paul Redmond -Radoslav Yovchev -Roman Lebedev -Shuo Chen -Steinar H. Gunderson -Stripe, Inc. -Yixuan Qiu -Yusuke Suzuki -Zbigniew Skowron -Min-Yih Hsu diff --git a/interpreter/llvm/src/utils/benchmark/CMakeLists.txt b/interpreter/llvm/src/utils/benchmark/CMakeLists.txt deleted file mode 100644 index 3a80b906d5cc7..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/CMakeLists.txt +++ /dev/null @@ -1,266 +0,0 @@ -cmake_minimum_required(VERSION 3.13.4) - -# Tell cmake 3.0+ that it's safe to clear the PROJECT_VERSION variable in the -# call to project() below. -if(POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) -endif() - -project (benchmark) - -foreach(p - CMP0054 # CMake 3.1 - CMP0056 # export EXE_LINKER_FLAGS to try_run - CMP0057 # Support no if() IN_LIST operator - ) - if(POLICY ${p}) - cmake_policy(SET ${p} NEW) - endif() -endforeach() - -option(BENCHMARK_ENABLE_TESTING "Enable testing of the benchmark library." ON) -option(BENCHMARK_ENABLE_EXCEPTIONS "Enable the use of exceptions in the benchmark library." ON) -option(BENCHMARK_ENABLE_LTO "Enable link time optimisation of the benchmark library." OFF) -option(BENCHMARK_USE_LIBCXX "Build and test using libc++ as the standard library." OFF) -option(BENCHMARK_BUILD_32_BITS "Build a 32 bit version of the library." OFF) -option(BENCHMARK_ENABLE_INSTALL "Enable installation of benchmark. (Projects embedding benchmark may want to turn this OFF.)" ON) - -# Allow unmet dependencies to be met using CMake's ExternalProject mechanics, which -# may require downloading the source code. -option(BENCHMARK_DOWNLOAD_DEPENDENCIES "Allow the downloading and in-tree building of unmet dependencies" OFF) - -# This option can be used to disable building and running unit tests which depend on gtest -# in cases where it is not possible to build or find a valid version of gtest. -option(BENCHMARK_ENABLE_GTEST_TESTS "Enable building the unit tests which depend on gtest" OFF) - -set(ENABLE_ASSEMBLY_TESTS_DEFAULT OFF) -function(should_enable_assembly_tests) - if(CMAKE_BUILD_TYPE) - string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) - if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage") - # FIXME: The --coverage flag needs to be removed when building assembly - # tests for this to work. - return() - endif() - endif() - if (MSVC) - return() - elseif(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64") - return() - elseif(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) - # FIXME: Make these work on 32 bit builds - return() - elseif(BENCHMARK_BUILD_32_BITS) - # FIXME: Make these work on 32 bit builds - return() - endif() - find_program(LLVM_FILECHECK_EXE FileCheck) - if (LLVM_FILECHECK_EXE) - set(LLVM_FILECHECK_EXE "${LLVM_FILECHECK_EXE}" CACHE PATH "llvm filecheck" FORCE) - message(STATUS "LLVM FileCheck Found: ${LLVM_FILECHECK_EXE}") - else() - message(STATUS "Failed to find LLVM FileCheck") - return() - endif() - set(ENABLE_ASSEMBLY_TESTS_DEFAULT ON PARENT_SCOPE) -endfunction() -should_enable_assembly_tests() - -# This option disables the building and running of the assembly verification tests -option(BENCHMARK_ENABLE_ASSEMBLY_TESTS "Enable building and running the assembly tests" - ${ENABLE_ASSEMBLY_TESTS_DEFAULT}) - -# Make sure we can import out CMake functions -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") - - -# Read the git tags to determine the project version -# WARNING: This is meaningless for when the benchmark library is being built in-tree, -# so disable it and hardcode a null version. -# include(GetGitVersion) -# get_git_version(GIT_VERSION) -set(GIT_VERSION "v0.0.0") - -# Tell the user what versions we are using -string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" VERSION ${GIT_VERSION}) -message("-- Version: ${VERSION}") - -# The version of the libraries -set(GENERIC_LIB_VERSION ${VERSION}) -string(SUBSTRING ${VERSION} 0 1 GENERIC_LIB_SOVERSION) - -# Import our CMake modules -include(CheckCXXCompilerFlag) -include(AddCXXCompilerFlag) -include(CXXFeatureCheck) - -if (BENCHMARK_BUILD_32_BITS) - add_required_cxx_compiler_flag(-m32) -endif() - -if (MSVC) - # Turn compiler warnings up to 11 - string(REGEX REPLACE "[-/]W[1-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") - add_definitions(-D_CRT_SECURE_NO_WARNINGS) - - if (NOT BENCHMARK_ENABLE_EXCEPTIONS) - add_cxx_compiler_flag(-EHs-) - add_cxx_compiler_flag(-EHa-) - add_definitions(-D_HAS_EXCEPTIONS=0) - endif() - # Link time optimisation - if (BENCHMARK_ENABLE_LTO) - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /GL") - set(CMAKE_STATIC_LINKER_FLAGS_RELEASE "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG") - set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG") - set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG") - - set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /GL") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - - set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /GL") - set(CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL "${CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL} /LTCG") - set(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "${CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL} /LTCG") - set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /LTCG") - endif() -else() - # Try and enable C++11. Don't use C++14 because it doesn't work in some - # configurations. - add_cxx_compiler_flag(-std=c++11) - if (NOT HAVE_CXX_FLAG_STD_CXX11) - add_cxx_compiler_flag(-std=c++0x) - endif() - - # Turn compiler warnings up to 11 - add_cxx_compiler_flag(-Wall) - - add_cxx_compiler_flag(-Wextra) - add_cxx_compiler_flag(-Wshadow) - # FIXME(kbobyrev): Document this change. - # add_cxx_compiler_flag(-Werror RELEASE) - # add_cxx_compiler_flag(-Werror RELWITHDEBINFO) - # add_cxx_compiler_flag(-Werror MINSIZEREL) - add_cxx_compiler_flag(-pedantic) - add_cxx_compiler_flag(-pedantic-errors) - add_cxx_compiler_flag(-Wshorten-64-to-32) - add_cxx_compiler_flag(-Wfloat-equal) - add_cxx_compiler_flag(-fstrict-aliasing) - if (NOT BENCHMARK_ENABLE_EXCEPTIONS) - add_cxx_compiler_flag(-fno-exceptions) - endif() - - if (CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG) - add_cxx_compiler_flag(-Wno-suggest-override) - endif() - - if (HAVE_CXX_FLAG_FSTRICT_ALIASING) - if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel") #ICC17u2: Many false positives for Wstrict-aliasing - add_cxx_compiler_flag(-Wstrict-aliasing) - endif() - endif() - # ICC17u2: overloaded virtual function "benchmark::Fixture::SetUp" is only partially overridden - # (because of deprecated overload) - add_cxx_compiler_flag(-wd654) - add_cxx_compiler_flag(-Wthread-safety) - if (HAVE_CXX_FLAG_WTHREAD_SAFETY) - cxx_feature_check(THREAD_SAFETY_ATTRIBUTES) - endif() - - # On most UNIX like platforms g++ and clang++ define _GNU_SOURCE as a - # predefined macro, which turns on all of the wonderful libc extensions. - # However g++ doesn't do this in Cygwin so we have to define it ourselfs - # since we depend on GNU/POSIX/BSD extensions. - if (CYGWIN) - add_definitions(-D_GNU_SOURCE=1) - endif() - - # Link time optimisation - if (BENCHMARK_ENABLE_LTO) - add_cxx_compiler_flag(-flto) - if ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU") - find_program(GCC_AR gcc-ar) - if (GCC_AR) - set(CMAKE_AR ${GCC_AR}) - endif() - find_program(GCC_RANLIB gcc-ranlib) - if (GCC_RANLIB) - set(CMAKE_RANLIB ${GCC_RANLIB}) - endif() - elseif("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") - include(llvm-toolchain) - endif() - endif() - - # Coverage build type - set(BENCHMARK_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_DEBUG}" - CACHE STRING "Flags used by the C++ compiler during coverage builds." - FORCE) - set(BENCHMARK_EXE_LINKER_FLAGS_COVERAGE "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" - CACHE STRING "Flags used for linking binaries during coverage builds." - FORCE) - set(BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" - CACHE STRING "Flags used by the shared libraries linker during coverage builds." - FORCE) - mark_as_advanced( - BENCHMARK_CXX_FLAGS_COVERAGE - BENCHMARK_EXE_LINKER_FLAGS_COVERAGE - BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE) - set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING - "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage.") - add_cxx_compiler_flag(--coverage COVERAGE) -endif() - -if (BENCHMARK_USE_LIBCXX) - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - add_cxx_compiler_flag(-stdlib=libc++) - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR - "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") - add_cxx_compiler_flag(-nostdinc++) - message("libc++ header path must be manually specified using CMAKE_CXX_FLAGS") - # Adding -nodefaultlibs directly to CMAKE__LINKER_FLAGS will break - # configuration checks such as 'find_package(Threads)' - list(APPEND BENCHMARK_CXX_LINKER_FLAGS -nodefaultlibs) - # -lc++ cannot be added directly to CMAKE__LINKER_FLAGS because - # linker flags appear before all linker inputs and -lc++ must appear after. - list(APPEND BENCHMARK_CXX_LIBRARIES c++) - else() - message(FATAL_ERROR "-DBENCHMARK_USE_LIBCXX:BOOL=ON is not supported for compiler") - endif() -endif(BENCHMARK_USE_LIBCXX) - -# C++ feature checks -# Determine the correct regular expression engine to use -cxx_feature_check(STD_REGEX) -cxx_feature_check(GNU_POSIX_REGEX) -cxx_feature_check(POSIX_REGEX) -if(NOT HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) - message(FATAL_ERROR "Failed to determine the source files for the regular expression backend") -endif() -if (NOT BENCHMARK_ENABLE_EXCEPTIONS AND HAVE_STD_REGEX - AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) - message(WARNING "Using std::regex with exceptions disabled is not fully supported") -endif() -cxx_feature_check(STEADY_CLOCK) -# Ensure we have pthreads -find_package(Threads REQUIRED) - -# Set up directories -include_directories(${PROJECT_SOURCE_DIR}/include) - -# Build the targets -add_subdirectory(src) - -if (BENCHMARK_ENABLE_TESTING) - enable_testing() - if (BENCHMARK_ENABLE_GTEST_TESTS) - include(HandleGTest) - endif() - add_subdirectory(test) -endif() diff --git a/interpreter/llvm/src/utils/benchmark/CONTRIBUTING.md b/interpreter/llvm/src/utils/benchmark/CONTRIBUTING.md deleted file mode 100644 index 43de4c9d4709a..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/CONTRIBUTING.md +++ /dev/null @@ -1,58 +0,0 @@ -# How to contribute # - -We'd love to accept your patches and contributions to this project. There are -a just a few small guidelines you need to follow. - - -## Contributor License Agreement ## - -Contributions to any Google project must be accompanied by a Contributor -License Agreement. This is not a copyright **assignment**, it simply gives -Google permission to use and redistribute your contributions as part of the -project. - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual - CLA][]. - - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA][]. - -You generally only need to submit a CLA once, so if you've already submitted -one (even if it was for a different project), you probably don't need to do it -again. - -[individual CLA]: https://developers.google.com/open-source/cla/individual -[corporate CLA]: https://developers.google.com/open-source/cla/corporate - -Once your CLA is submitted (or if you already submitted one for -another Google project), make a commit adding yourself to the -[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part -of your first [pull request][]. - -[AUTHORS]: AUTHORS -[CONTRIBUTORS]: CONTRIBUTORS - - -## Submitting a patch ## - - 1. It's generally best to start by opening a new issue describing the bug or - feature you're intending to fix. Even if you think it's relatively minor, - it's helpful to know what people are working on. Mention in the initial - issue that you are planning to work on that bug or feature so that it can - be assigned to you. - - 1. Follow the normal process of [forking][] the project, and setup a new - branch to work in. It's important that each group of changes be done in - separate branches in order to ensure that a pull request only includes the - commits related to that bug or feature. - - 1. Do your best to have [well-formed commit messages][] for each change. - This provides consistency throughout the project, and ensures that commit - messages are able to be formatted properly by various git tools. - - 1. Finally, push the commits to your fork and submit a [pull request][]. - -[forking]: https://help.github.com/articles/fork-a-repo -[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/interpreter/llvm/src/utils/benchmark/CONTRIBUTORS b/interpreter/llvm/src/utils/benchmark/CONTRIBUTORS deleted file mode 100644 index 073d6767bc487..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/CONTRIBUTORS +++ /dev/null @@ -1,67 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. -# -# Names should be added to this file as: -# Name -# -# Please keep the list sorted. - -Albert Pretorius -Arne Beer -Billy Robert O'Neal III -Chris Kennelly -Christopher Seymour -David Coeurjolly -Deniz Evrenci -Dominic Hamon -Dominik Czarnota -Eric Fiselier -Eugene Zhuk -Evgeny Safronov -Felix Homann -Ismael Jimenez Martinez -Jern-Kuan Leong -JianXiong Zhou -Joao Paulo Magalhaes -John Millikin -Jussi Knuuttila -Kai Wolf -Kishan Kumar -Kaito Udagawa -Lei Xu -Matt Clarkson -Maxim Vafin -Nick Hutchinson -Oleksandr Sochka -Pascal Leroy -Paul Redmond -Pierre Phaneuf -Radoslav Yovchev -Raul Marin -Ray Glover -Robert Guo -Roman Lebedev -Shuo Chen -Steven Wan -Tobias Ulvgård -Tom Madams -Yixuan Qiu -Yusuke Suzuki -Zbigniew Skowron -Min-Yih Hsu diff --git a/interpreter/llvm/src/utils/benchmark/LICENSE b/interpreter/llvm/src/utils/benchmark/LICENSE deleted file mode 100644 index d645695673349..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/interpreter/llvm/src/utils/benchmark/README.LLVM b/interpreter/llvm/src/utils/benchmark/README.LLVM deleted file mode 100644 index d77da3b620010..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/README.LLVM +++ /dev/null @@ -1,39 +0,0 @@ -LLVM notes ----------- - -This directory contains the Google Benchmark source code. Currently, the checked -Benchmark library version is v1.4.1. - -This directory is under a different license than LLVM. - -Changes: - -* Bazel BUILD files are removed from the library -* https://github.com/google/benchmark/commit/f85304e4e3a0e4e1bf15b91720df4a19e90b589f - is applied on top of the v1.4.1 to silence compiler warnings -* https://github.com/google/benchmark/commit/505be96ab23056580a3a2315abba048f4428b04e - is applied to comply with the LLVM's required CMake version -* https://github.com/google/benchmark/commit/f0901417c89d123474e6b91365029cfe32cf89dc - is applied to fix 32-bit build failure on macOS -* https://github.com/google/benchmark/commit/52613079824ac58d06c070aa9fbbb186a5859e2c - is applied to fix cross compilation with MinGW headers -* https://github.com/google/benchmark/commit/439d6b1c2a6da5cb6adc4c4dfc555af235722396 - is applied to fix building with MinGW headers for ARM -* https://github.com/google/benchmark/commit/a9b31c51b1ee7ec7b31438c647123c2cbac5d956 - is applied to disable exceptions in Microsoft STL when exceptions are disabled -* Disabled CMake get_git_version as it is meaningless for this in-tree build, - and hardcoded a null version -* https://github.com/google/benchmark/commit/4abdfbb802d1b514703223f5f852ce4a507d32d2 - is applied on top of v1.4.1 to add RISC-V timer support. -* https://github.com/google/benchmark/commit/8e48105d465c586068dd8e248fe75a8971c6ba3a - is applied on top of v1.4.1 to fix cross-build from linux to windows via MinGW. -* https://github.com/google/benchmark/commit/a77d5f70efaebe2b7e8c10134526a23a7ce7ef35 - and - https://github.com/google/benchmark/commit/ecc1685340f58f7fe6b707036bc0bb1fccabb0c1 - are applied on top of the previous cherrypick to fix timestamp-related inline - asm issues and 32-bit RISC-V build failures. The second cherrypicked commit - fixes formatting issues introduced by the preceding change. -* https://github.com/google/benchmark/commit/ffe1342eb2faa7d2e7c35b4db2ccf99fab81ec20 - is applied to add the CycleTimer implementation for M68k -* https://github.com/google/benchmark/commit/d9abf017632be4a00b92cf4289539b353fcea5d2 - is applied to rename 'mftbl' to 'mftb'. diff --git a/interpreter/llvm/src/utils/benchmark/README.md b/interpreter/llvm/src/utils/benchmark/README.md deleted file mode 100644 index bba89afd0c002..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/README.md +++ /dev/null @@ -1,950 +0,0 @@ -# benchmark -[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark) -[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master) -[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) -[![slackin](https://slackin-iqtfqnpzxd.now.sh/badge.svg)](https://slackin-iqtfqnpzxd.now.sh/) - -A library to support the benchmarking of functions, similar to unit-tests. - -Discussion group: https://groups.google.com/d/forum/benchmark-discuss - -IRC channel: https://freenode.net #googlebenchmark - -[Known issues and common problems](#known-issues) - -[Additional Tooling Documentation](docs/tools.md) - -[Assembly Testing Documentation](docs/AssemblyTests.md) - - -## Building - -The basic steps for configuring and building the library look like this: - -```bash -$ git clone https://github.com/google/benchmark.git -# Benchmark requires Google Test as a dependency. Add the source tree as a subdirectory. -$ git clone https://github.com/google/googletest.git benchmark/googletest -$ mkdir build && cd build -$ cmake -G [options] ../benchmark -# Assuming a makefile generator was used -$ make -``` - -Note that Google Benchmark requires Google Test to build and run the tests. This -dependency can be provided two ways: - -* Checkout the Google Test sources into `benchmark/googletest` as above. -* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during - configuration, the library will automatically download and build any required - dependencies. - -If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` -to `CMAKE_ARGS`. - - -## Installation Guide - -For Ubuntu and Debian Based System - -First make sure you have git and cmake installed (If not please install it) - -``` -sudo apt-get install git -sudo apt-get install cmake -``` - -Now, let's clone the repository and build it - -``` -git clone https://github.com/google/benchmark.git -cd benchmark -git clone https://github.com/google/googletest.git -mkdir build -cd build -cmake .. -DCMAKE_BUILD_TYPE=RELEASE -make -``` - -We need to install the library globally now - -``` -sudo make install -``` - -Now you have google/benchmark installed in your machine -Note: Don't forget to link to pthread library while building - -## Stable and Experimental Library Versions - -The main branch contains the latest stable version of the benchmarking library; -the API of which can be considered largely stable, with source breaking changes -being made only upon the release of a new major version. - -Newer, experimental, features are implemented and tested on the -[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish -to use, test, and provide feedback on the new features are encouraged to try -this branch. However, this branch provides no stability guarantees and reserves -the right to change and break the API at any time. - -##Prerequisite knowledge - -Before attempting to understand this framework one should ideally have some familiarity with the structure and format of the Google Test framework, upon which it is based. Documentation for Google Test, including a "Getting Started" (primer) guide, is available here: -https://github.com/google/googletest/blob/master/googletest/docs/Documentation.md - - -## Example usage -### Basic usage -Define a function that executes the code to be measured. - -```c++ -#include - -static void BM_StringCreation(benchmark::State& state) { - for (auto _ : state) - std::string empty_string; -} -// Register the function as a benchmark -BENCHMARK(BM_StringCreation); - -// Define another benchmark -static void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - for (auto _ : state) - std::string copy(x); -} -BENCHMARK(BM_StringCopy); - -BENCHMARK_MAIN(); -``` - -Don't forget to inform your linker to add benchmark library e.g. through -`-lbenchmark` compilation flag. Alternatively, you may leave out the -`BENCHMARK_MAIN();` at the end of the source file and link against -`-lbenchmark_main` to get the same default behavior. - -The benchmark library will reporting the timing for the code within the `for(...)` loop. - -### Passing arguments -Sometimes a family of benchmarks can be implemented with just one routine that -takes an extra argument to specify which one of the family of benchmarks to -run. For example, the following code defines a family of benchmarks for -measuring the speed of `memcpy()` calls of different lengths: - -```c++ -static void BM_memcpy(benchmark::State& state) { - char* src = new char[state.range(0)]; - char* dst = new char[state.range(0)]; - memset(src, 'x', state.range(0)); - for (auto _ : state) - memcpy(dst, src, state.range(0)); - state.SetBytesProcessed(int64_t(state.iterations()) * - int64_t(state.range(0))); - delete[] src; - delete[] dst; -} -BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); -``` - -The preceding code is quite repetitive, and can be replaced with the following -short-hand. The following invocation will pick a few appropriate arguments in -the specified range and will generate a benchmark for each such argument. - -```c++ -BENCHMARK(BM_memcpy)->Range(8, 8<<10); -``` - -By default the arguments in the range are generated in multiples of eight and -the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the -range multiplier is changed to multiples of two. - -```c++ -BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10); -``` -Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ]. - -You might have a benchmark that depends on two or more inputs. For example, the -following code defines a family of benchmarks for measuring the speed of set -insertion. - -```c++ -static void BM_SetInsert(benchmark::State& state) { - std::set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) - data.insert(RandomNumber()); - } -} -BENCHMARK(BM_SetInsert) - ->Args({1<<10, 128}) - ->Args({2<<10, 128}) - ->Args({4<<10, 128}) - ->Args({8<<10, 128}) - ->Args({1<<10, 512}) - ->Args({2<<10, 512}) - ->Args({4<<10, 512}) - ->Args({8<<10, 512}); -``` - -The preceding code is quite repetitive, and can be replaced with the following -short-hand. The following macro will pick a few appropriate arguments in the -product of the two specified ranges and will generate a benchmark for each such -pair. - -```c++ -BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); -``` - -For more complex patterns of inputs, passing a custom function to `Apply` allows -programmatic specification of an arbitrary set of arguments on which to run the -benchmark. The following example enumerates a dense range on one parameter, -and a sparse range on the second. - -```c++ -static void CustomArguments(benchmark::internal::Benchmark* b) { - for (int i = 0; i <= 10; ++i) - for (int j = 32; j <= 1024*1024; j *= 8) - b->Args({i, j}); -} -BENCHMARK(BM_SetInsert)->Apply(CustomArguments); -``` - -### Calculate asymptotic complexity (Big O) -Asymptotic complexity might be calculated for a family of benchmarks. The -following code will calculate the coefficient for the high-order term in the -running time and the normalized root-mean square error of string comparison. - -```c++ -static void BM_StringCompare(benchmark::State& state) { - std::string s1(state.range(0), '-'); - std::string s2(state.range(0), '-'); - for (auto _ : state) { - benchmark::DoNotOptimize(s1.compare(s2)); - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_StringCompare) - ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN); -``` - -As shown in the following invocation, asymptotic complexity might also be -calculated automatically. - -```c++ -BENCHMARK(BM_StringCompare) - ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(); -``` - -The following code will specify asymptotic complexity with a lambda function, -that might be used to customize high-order term calculation. - -```c++ -BENCHMARK(BM_StringCompare)->RangeMultiplier(2) - ->Range(1<<10, 1<<18)->Complexity([](int n)->double{return n; }); -``` - -### Templated benchmarks -Templated benchmarks work the same way: This example produces and consumes -messages of size `sizeof(v)` `range_x` times. It also outputs throughput in the -absence of multiprogramming. - -```c++ -template int BM_Sequential(benchmark::State& state) { - Q q; - typename Q::value_type v; - for (auto _ : state) { - for (int i = state.range(0); i--; ) - q.push(v); - for (int e = state.range(0); e--; ) - q.Wait(&v); - } - // actually messages, not bytes: - state.SetBytesProcessed( - static_cast(state.iterations())*state.range(0)); -} -BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); -``` - -Three macros are provided for adding benchmark templates. - -```c++ -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters. -#else // C++ < C++11 -#define BENCHMARK_TEMPLATE(func, arg1) -#endif -#define BENCHMARK_TEMPLATE1(func, arg1) -#define BENCHMARK_TEMPLATE2(func, arg1, arg2) -``` - -### A Faster KeepRunning loop - -In C++11 mode, a ranged-based for loop should be used in preference to -the `KeepRunning` loop for running the benchmarks. For example: - -```c++ -static void BM_Fast(benchmark::State &state) { - for (auto _ : state) { - FastOperation(); - } -} -BENCHMARK(BM_Fast); -``` - -The reason the ranged-for loop is faster than using `KeepRunning`, is -because `KeepRunning` requires a memory load and store of the iteration count -ever iteration, whereas the ranged-for variant is able to keep the iteration count -in a register. - -For example, an empty inner loop of using the ranged-based for method looks like: - -```asm -# Loop Init - mov rbx, qword ptr [r14 + 104] - call benchmark::State::StartKeepRunning() - test rbx, rbx - je .LoopEnd -.LoopHeader: # =>This Inner Loop Header: Depth=1 - add rbx, -1 - jne .LoopHeader -.LoopEnd: -``` - -Compared to an empty `KeepRunning` loop, which looks like: - -```asm -.LoopHeader: # in Loop: Header=BB0_3 Depth=1 - cmp byte ptr [rbx], 1 - jne .LoopInit -.LoopBody: # =>This Inner Loop Header: Depth=1 - mov rax, qword ptr [rbx + 8] - lea rcx, [rax + 1] - mov qword ptr [rbx + 8], rcx - cmp rax, qword ptr [rbx + 104] - jb .LoopHeader - jmp .LoopEnd -.LoopInit: - mov rdi, rbx - call benchmark::State::StartKeepRunning() - jmp .LoopBody -.LoopEnd: -``` - -Unless C++03 compatibility is required, the ranged-for variant of writing -the benchmark loop should be preferred. - -## Passing arbitrary arguments to a benchmark -In C++11 it is possible to define a benchmark that takes an arbitrary number -of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)` -macro creates a benchmark that invokes `func` with the `benchmark::State` as -the first argument followed by the specified `args...`. -The `test_case_name` is appended to the name of the benchmark and -should describe the values passed. - -```c++ -template -void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { - [...] -} -// Registers a benchmark named "BM_takes_args/int_string_test" that passes -// the specified values to `extra_args`. -BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); -``` -Note that elements of `...args` may refer to global variables. Users should -avoid modifying global state inside of a benchmark. - -## Using RegisterBenchmark(name, fn, args...) - -The `RegisterBenchmark(name, func, args...)` function provides an alternative -way to create and register benchmarks. -`RegisterBenchmark(name, func, args...)` creates, registers, and returns a -pointer to a new benchmark with the specified `name` that invokes -`func(st, args...)` where `st` is a `benchmark::State` object. - -Unlike the `BENCHMARK` registration macros, which can only be used at the global -scope, the `RegisterBenchmark` can be called anywhere. This allows for -benchmark tests to be registered programmatically. - -Additionally `RegisterBenchmark` allows any callable object to be registered -as a benchmark. Including capturing lambdas and function objects. - -For Example: -```c++ -auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ }; - -int main(int argc, char** argv) { - for (auto& test_input : { /* ... */ }) - benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input); - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); -} -``` - -### Multithreaded benchmarks -In a multithreaded test (benchmark invoked by multiple threads simultaneously), -it is guaranteed that none of the threads will start until all have reached -the start of the benchmark loop, and all will have finished before any thread -exits the benchmark loop. (This behavior is also provided by the `KeepRunning()` -API) As such, any global setup or teardown can be wrapped in a check against the thread -index: - -```c++ -static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { - // Setup code here. - } - for (auto _ : state) { - // Run the test as normal. - } - if (state.thread_index == 0) { - // Teardown code here. - } -} -BENCHMARK(BM_MultiThreaded)->Threads(2); -``` - -If the benchmarked code itself uses threads and you want to compare it to -single-threaded code, you may want to use real-time ("wallclock") measurements -for latency comparisons: - -```c++ -BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime(); -``` - -Without `UseRealTime`, CPU time is used by default. - - -## Manual timing -For benchmarking something for which neither CPU time nor real-time are -correct or accurate enough, completely manual timing is supported using -the `UseManualTime` function. - -When `UseManualTime` is used, the benchmarked code must call -`SetIterationTime` once per iteration of the benchmark loop to -report the manually measured time. - -An example use case for this is benchmarking GPU execution (e.g. OpenCL -or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot -be accurately measured using CPU time or real-time. Instead, they can be -measured accurately using a dedicated API, and these measurement results -can be reported back with `SetIterationTime`. - -```c++ -static void BM_ManualTiming(benchmark::State& state) { - int microseconds = state.range(0); - std::chrono::duration sleep_duration { - static_cast(microseconds) - }; - - for (auto _ : state) { - auto start = std::chrono::high_resolution_clock::now(); - // Simulate some useful workload with a sleep - std::this_thread::sleep_for(sleep_duration); - auto end = std::chrono::high_resolution_clock::now(); - - auto elapsed_seconds = - std::chrono::duration_cast>( - end - start); - - state.SetIterationTime(elapsed_seconds.count()); - } -} -BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime(); -``` - -### Preventing optimisation -To prevent a value or expression from being optimized away by the compiler -the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()` -functions can be used. - -```c++ -static void BM_test(benchmark::State& state) { - for (auto _ : state) { - int x = 0; - for (int i=0; i < 64; ++i) { - benchmark::DoNotOptimize(x += i); - } - } -} -``` - -`DoNotOptimize()` forces the *result* of `` to be stored in either -memory or a register. For GNU based compilers it acts as read/write barrier -for global memory. More specifically it forces the compiler to flush pending -writes to memory and reload any other values as necessary. - -Note that `DoNotOptimize()` does not prevent optimizations on `` -in any way. `` may even be removed entirely when the result is already -known. For example: - -```c++ - /* Example 1: `` is removed entirely. */ - int foo(int x) { return x + 42; } - while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42); - - /* Example 2: Result of '' is only reused */ - int bar(int) __attribute__((const)); - while (...) DoNotOptimize(bar(0)); // Optimized to: - // int __result__ = bar(0); - // while (...) DoNotOptimize(__result__); -``` - -The second tool for preventing optimizations is `ClobberMemory()`. In essence -`ClobberMemory()` forces the compiler to perform all pending writes to global -memory. Memory managed by block scope objects must be "escaped" using -`DoNotOptimize(...)` before it can be clobbered. In the below example -`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized -away. - -```c++ -static void BM_vector_push_back(benchmark::State& state) { - for (auto _ : state) { - std::vector v; - v.reserve(1); - benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered. - v.push_back(42); - benchmark::ClobberMemory(); // Force 42 to be written to memory. - } -} -``` - -Note that `ClobberMemory()` is only available for GNU or MSVC based compilers. - -### Set time unit manually -If a benchmark runs a few milliseconds it may be hard to visually compare the -measured times, since the output data is given in nanoseconds per default. In -order to manually set the time unit, you can specify it manually: - -```c++ -BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); -``` - -## Controlling number of iterations -In all cases, the number of iterations for which the benchmark is run is -governed by the amount of time the benchmark takes. Concretely, the number of -iterations is at least one, not more than 1e9, until CPU time is greater than -the minimum time, or the wallclock time is 5x minimum time. The minimum time is -set as a flag `--benchmark_min_time` or per benchmark by calling `MinTime` on -the registered benchmark object. - -## Reporting the mean, median and standard deviation by repeated benchmarks -By default each benchmark is run once and that single result is reported. -However benchmarks are often noisy and a single result may not be representative -of the overall behavior. For this reason it's possible to repeatedly rerun the -benchmark. - -The number of runs of each benchmark is specified globally by the -`--benchmark_repetitions` flag or on a per benchmark basis by calling -`Repetitions` on the registered benchmark object. When a benchmark is run more -than once the mean, median and standard deviation of the runs will be reported. - -Additionally the `--benchmark_report_aggregates_only={true|false}` flag or -`ReportAggregatesOnly(bool)` function can be used to change how repeated tests -are reported. By default the result of each repeated run is reported. When this -option is `true` only the mean, median and standard deviation of the runs is reported. -Calling `ReportAggregatesOnly(bool)` on a registered benchmark object overrides -the value of the flag for that benchmark. - -## User-defined statistics for repeated benchmarks -While having mean, median and standard deviation is nice, this may not be -enough for everyone. For example you may want to know what is the largest -observation, e.g. because you have some real-time constraints. This is easy. -The following code will specify a custom statistic to be calculated, defined -by a lambda function. - -```c++ -void BM_spin_empty(benchmark::State& state) { - for (auto _ : state) { - for (int x = 0; x < state.range(0); ++x) { - benchmark::DoNotOptimize(x); - } - } -} - -BENCHMARK(BM_spin_empty) - ->ComputeStatistics("max", [](const std::vector& v) -> double { - return *(std::max_element(std::begin(v), std::end(v))); - }) - ->Arg(512); -``` - -## Fixtures -Fixture tests are created by -first defining a type that derives from `::benchmark::Fixture` and then -creating/registering the tests using the following macros: - -* `BENCHMARK_F(ClassName, Method)` -* `BENCHMARK_DEFINE_F(ClassName, Method)` -* `BENCHMARK_REGISTER_F(ClassName, Method)` - -For Example: - -```c++ -class MyFixture : public benchmark::Fixture {}; - -BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} -/* BarTest is NOT registered */ -BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2); -/* BarTest is now registered */ -``` - -### Templated fixtures -Also you can create templated fixture by using the following macros: - -* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)` -* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)` - -For example: -```c++ -template -class MyFixture : public benchmark::Fixture {}; - -BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2); -``` - -## User-defined counters - -You can add your own counters with user-defined names. The example below -will add columns "Foo", "Bar" and "Baz" in its output: - -```c++ -static void UserCountersExample1(benchmark::State& state) { - double numFoos = 0, numBars = 0, numBazs = 0; - for (auto _ : state) { - // ... count Foo,Bar,Baz events - } - state.counters["Foo"] = numFoos; - state.counters["Bar"] = numBars; - state.counters["Baz"] = numBazs; -} -``` - -The `state.counters` object is a `std::map` with `std::string` keys -and `Counter` values. The latter is a `double`-like class, via an implicit -conversion to `double&`. Thus you can use all of the standard arithmetic -assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter. - -In multithreaded benchmarks, each counter is set on the calling thread only. -When the benchmark finishes, the counters from each thread will be summed; -the resulting sum is the value which will be shown for the benchmark. - -The `Counter` constructor accepts two parameters: the value as a `double` -and a bit flag which allows you to show counters as rates and/or as -per-thread averages: - -```c++ - // sets a simple counter - state.counters["Foo"] = numFoos; - - // Set the counter as a rate. It will be presented divided - // by the duration of the benchmark. - state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate); - - // Set the counter as a thread-average quantity. It will - // be presented divided by the number of threads. - state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads); - - // There's also a combined flag: - state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate); -``` - -When you're compiling in C++11 mode or later you can use `insert()` with -`std::initializer_list`: - -```c++ - // With C++11, this can be done: - state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}}); - // ... instead of: - state.counters["Foo"] = numFoos; - state.counters["Bar"] = numBars; - state.counters["Baz"] = numBazs; -``` - -### Counter reporting - -When using the console reporter, by default, user counters are are printed at -the end after the table, the same way as ``bytes_processed`` and -``items_processed``. This is best for cases in which there are few counters, -or where there are only a couple of lines per benchmark. Here's an example of -the default output: - -``` ------------------------------------------------------------------------------- -Benchmark Time CPU Iterations UserCounters... ------------------------------------------------------------------------------- -BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8 -BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m -BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2 -BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4 -BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8 -BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16 -BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32 -BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4 -BM_Factorial 26 ns 26 ns 26608979 40320 -BM_Factorial/real_time 26 ns 26 ns 26587936 40320 -BM_CalculatePiRange/1 16 ns 16 ns 45704255 0 -BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374 -BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746 -BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355 -``` - -If this doesn't suit you, you can print each counter as a table column by -passing the flag `--benchmark_counters_tabular=true` to the benchmark -application. This is best for cases in which there are a lot of counters, or -a lot of lines per individual benchmark. Note that this will trigger a -reprinting of the table header any time the counter set changes between -individual benchmarks. Here's an example of corresponding output when -`--benchmark_counters_tabular=true` is passed: - -``` ---------------------------------------------------------------------------------------- -Benchmark Time CPU Iterations Bar Bat Baz Foo ---------------------------------------------------------------------------------------- -BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8 -BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1 -BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2 -BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4 -BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8 -BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16 -BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32 -BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4 --------------------------------------------------------------- -Benchmark Time CPU Iterations --------------------------------------------------------------- -BM_Factorial 26 ns 26 ns 26392245 40320 -BM_Factorial/real_time 26 ns 26 ns 26494107 40320 -BM_CalculatePiRange/1 15 ns 15 ns 45571597 0 -BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374 -BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746 -BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355 -BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184 -BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162 -BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416 -BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159 -BM_CalculatePi/threads:8 2255 ns 9943 ns 70936 -``` -Note above the additional header printed when the benchmark changes from -``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does -not have the same counter set as ``BM_UserCounter``. - -## Exiting Benchmarks in Error - -When errors caused by external influences, such as file I/O and network -communication, occur within a benchmark the -`State::SkipWithError(const char* msg)` function can be used to skip that run -of benchmark and report the error. Note that only future iterations of the -`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop -Users must explicitly exit the loop, otherwise all iterations will be performed. -Users may explicitly return to exit the benchmark immediately. - -The `SkipWithError(...)` function may be used at any point within the benchmark, -including before and after the benchmark loop. - -For example: - -```c++ -static void BM_test(benchmark::State& state) { - auto resource = GetResource(); - if (!resource.good()) { - state.SkipWithError("Resource is not good!"); - // KeepRunning() loop will not be entered. - } - for (state.KeepRunning()) { - auto data = resource.read_data(); - if (!resource.good()) { - state.SkipWithError("Failed to read data!"); - break; // Needed to skip the rest of the iteration. - } - do_stuff(data); - } -} - -static void BM_test_ranged_fo(benchmark::State & state) { - state.SkipWithError("test will not be entered"); - for (auto _ : state) { - state.SkipWithError("Failed!"); - break; // REQUIRED to prevent all further iterations. - } -} -``` - -## Running a subset of the benchmarks - -The `--benchmark_filter=` option can be used to only run the benchmarks -which match the specified ``. For example: - -```bash -$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32 -Run on (1 X 2300 MHz CPU ) -2016-06-25 19:34:24 -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_memcpy/32 11 ns 11 ns 79545455 -BM_memcpy/32k 2181 ns 2185 ns 324074 -BM_memcpy/32 12 ns 12 ns 54687500 -BM_memcpy/32k 1834 ns 1837 ns 357143 -``` - - -## Output Formats -The library supports multiple output formats. Use the -`--benchmark_format=` flag to set the format type. `console` -is the default format. - -The Console format is intended to be a human readable format. By default -the format generates color output. Context is output on stderr and the -tabular data on stdout. Example tabular output looks like: -``` -Benchmark Time(ns) CPU(ns) Iterations ----------------------------------------------------------------------- -BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s -BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s -BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s -``` - -The JSON format outputs human readable json split into two top level attributes. -The `context` attribute contains information about the run in general, including -information about the CPU and the date. -The `benchmarks` attribute contains a list of every benchmark run. Example json -output looks like: -```json -{ - "context": { - "date": "2015/03/17-18:40:25", - "num_cpus": 40, - "mhz_per_cpu": 2801, - "cpu_scaling_enabled": false, - "build_type": "debug" - }, - "benchmarks": [ - { - "name": "BM_SetInsert/1024/1", - "iterations": 94877, - "real_time": 29275, - "cpu_time": 29836, - "bytes_per_second": 134066, - "items_per_second": 33516 - }, - { - "name": "BM_SetInsert/1024/8", - "iterations": 21609, - "real_time": 32317, - "cpu_time": 32429, - "bytes_per_second": 986770, - "items_per_second": 246693 - }, - { - "name": "BM_SetInsert/1024/10", - "iterations": 21393, - "real_time": 32724, - "cpu_time": 33355, - "bytes_per_second": 1199226, - "items_per_second": 299807 - } - ] -} -``` - -The CSV format outputs comma-separated values. The `context` is output on stderr -and the CSV itself on stdout. Example CSV output looks like: -``` -name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label -"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942, -"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115, -"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06, -``` - -## Output Files -The library supports writing the output of the benchmark to a file specified -by `--benchmark_out=`. The format of the output can be specified -using `--benchmark_out_format={json|console|csv}`. Specifying -`--benchmark_out` does not suppress the console output. - -## Debug vs Release -By default, benchmark builds as a debug library. You will see a warning in the output when this is the case. To build it as a release library instead, use: - -``` -cmake -DCMAKE_BUILD_TYPE=Release -``` - -To enable link-time optimisation, use - -``` -cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true -``` - -If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake cache variables, if autodetection fails. -If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, `LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables. - -## Linking against the library - -When the library is built using GCC it is necessary to link with `-pthread`, -due to how GCC implements `std::thread`. - -For GCC 4.x failing to link to pthreads will lead to runtime exceptions, not linker errors. -See [issue #67](https://github.com/google/benchmark/issues/67) for more details. - -## Compiler Support - -Google Benchmark uses C++11 when building the library. As such we require -a modern C++ toolchain, both compiler and standard library. - -The following minimum versions are strongly recommended build the library: - -* GCC 4.8 -* Clang 3.4 -* Visual Studio 2013 -* Intel 2015 Update 1 - -Anything older *may* work. - -Note: Using the library and its headers in C++03 is supported. C++11 is only -required to build the library. - -## Disable CPU frequency scaling -If you see this error: -``` -***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. -``` -you might want to disable the CPU frequency scaling while running the benchmark: -```bash -sudo cpupower frequency-set --governor performance -./mybench -sudo cpupower frequency-set --governor powersave -``` - -# Known Issues - -### Windows with CMake - -* Users must manually link `shlwapi.lib`. Failure to do so may result -in unresolved symbols. - -### Solaris - -* Users must explicitly link with kstat library (-lkstat compilation flag). diff --git a/interpreter/llvm/src/utils/benchmark/WORKSPACE b/interpreter/llvm/src/utils/benchmark/WORKSPACE deleted file mode 100644 index 54734f1ea55e7..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/WORKSPACE +++ /dev/null @@ -1,7 +0,0 @@ -workspace(name = "com_github_google_benchmark") - -http_archive( - name = "com_google_googletest", - urls = ["https://github.com/google/googletest/archive/3f0cf6b62ad1eb50d8736538363d3580dd640c3e.zip"], - strip_prefix = "googletest-3f0cf6b62ad1eb50d8736538363d3580dd640c3e", -) diff --git a/interpreter/llvm/src/utils/benchmark/appveyor.yml b/interpreter/llvm/src/utils/benchmark/appveyor.yml deleted file mode 100644 index e99c6e77f006e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/appveyor.yml +++ /dev/null @@ -1,56 +0,0 @@ -version: '{build}' - -image: Visual Studio 2017 - -configuration: - - Debug - - Release - -environment: - matrix: - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017" - - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017 Win64" - - - compiler: msvc-14-seh - generator: "Visual Studio 14 2015" - - - compiler: msvc-14-seh - generator: "Visual Studio 14 2015 Win64" - - - compiler: msvc-12-seh - generator: "Visual Studio 12 2013" - - - compiler: msvc-12-seh - generator: "Visual Studio 12 2013 Win64" - - - compiler: gcc-5.3.0-posix - generator: "MinGW Makefiles" - cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin' - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - -matrix: - fast_finish: true - -install: - # git bash conflicts with MinGW makefiles - - if "%generator%"=="MinGW Makefiles" (set "PATH=%PATH:C:\Program Files\Git\usr\bin;=%") - - if not "%cxx_path%"=="" (set "PATH=%PATH%;%cxx_path%") - -build_script: - - md _build -Force - - cd _build - - echo %configuration% - - cmake -G "%generator%" "-DCMAKE_BUILD_TYPE=%configuration%" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON .. - - cmake --build . --config %configuration% - -test_script: - - ctest -c %configuration% --timeout 300 --output-on-failure - -artifacts: - - path: '_build/CMakeFiles/*.log' - name: logs - - path: '_build/Testing/**/*.xml' - name: test_results diff --git a/interpreter/llvm/src/utils/benchmark/cmake/AddCXXCompilerFlag.cmake b/interpreter/llvm/src/utils/benchmark/cmake/AddCXXCompilerFlag.cmake deleted file mode 100644 index d0d2099814402..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/AddCXXCompilerFlag.cmake +++ /dev/null @@ -1,74 +0,0 @@ -# - Adds a compiler flag if it is supported by the compiler -# -# This function checks that the supplied compiler flag is supported and then -# adds it to the corresponding compiler flags -# -# add_cxx_compiler_flag( []) -# -# - Example -# -# include(AddCXXCompilerFlag) -# add_cxx_compiler_flag(-Wall) -# add_cxx_compiler_flag(-no-strict-aliasing RELEASE) -# Requires CMake 2.6+ - -if(__add_cxx_compiler_flag) - return() -endif() -set(__add_cxx_compiler_flag INCLUDED) - -include(CheckCXXCompilerFlag) - -function(mangle_compiler_flag FLAG OUTPUT) - string(TOUPPER "HAVE_CXX_FLAG_${FLAG}" SANITIZED_FLAG) - string(REPLACE "+" "X" SANITIZED_FLAG ${SANITIZED_FLAG}) - string(REGEX REPLACE "[^A-Za-z_0-9]" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) - string(REGEX REPLACE "_+" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) - set(${OUTPUT} "${SANITIZED_FLAG}" PARENT_SCOPE) -endfunction(mangle_compiler_flag) - -function(add_cxx_compiler_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") - if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) - string(TOUPPER "_${VARIANT}" VARIANT) - endif() - set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${BENCHMARK_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) - endif() -endfunction() - -function(add_required_cxx_compiler_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") - if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) - string(TOUPPER "_${VARIANT}" VARIANT) - endif() - set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}" PARENT_SCOPE) - else() - message(FATAL_ERROR "Required flag '${FLAG}' is not supported by the compiler") - endif() -endfunction() - -function(check_cxx_warning_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - # Add -Werror to ensure the compiler generates an error if the warning flag - # doesn't exist. - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") -endfunction() diff --git a/interpreter/llvm/src/utils/benchmark/cmake/CXXFeatureCheck.cmake b/interpreter/llvm/src/utils/benchmark/cmake/CXXFeatureCheck.cmake deleted file mode 100644 index c4c4d660f1eba..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/CXXFeatureCheck.cmake +++ /dev/null @@ -1,64 +0,0 @@ -# - Compile and run code to check for C++ features -# -# This functions compiles a source file under the `cmake` folder -# and adds the corresponding `HAVE_[FILENAME]` flag to the CMake -# environment -# -# cxx_feature_check( []) -# -# - Example -# -# include(CXXFeatureCheck) -# cxx_feature_check(STD_REGEX) -# Requires CMake 2.8.12+ - -if(__cxx_feature_check) - return() -endif() -set(__cxx_feature_check INCLUDED) - -function(cxx_feature_check FILE) - string(TOLOWER ${FILE} FILE) - string(TOUPPER ${FILE} VAR) - string(TOUPPER "HAVE_${VAR}" FEATURE) - if (DEFINED HAVE_${VAR}) - set(HAVE_${VAR} 1 PARENT_SCOPE) - add_definitions(-DHAVE_${VAR}) - return() - endif() - - if (NOT DEFINED COMPILE_${FEATURE}) - message("-- Performing Test ${FEATURE}") - if(CMAKE_CROSSCOMPILING) - try_compile(COMPILE_${FEATURE} - ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) - if(COMPILE_${FEATURE}) - message(WARNING - "If you see build failures due to cross compilation, try setting HAVE_${VAR} to 0") - set(RUN_${FEATURE} 0) - else() - set(RUN_${FEATURE} 1) - endif() - else() - message("-- Performing Test ${FEATURE}") - try_run(RUN_${FEATURE} COMPILE_${FEATURE} - ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) - endif() - endif() - - if(RUN_${FEATURE} EQUAL 0) - message("-- Performing Test ${FEATURE} -- success") - set(HAVE_${VAR} 1 PARENT_SCOPE) - add_definitions(-DHAVE_${VAR}) - else() - if(NOT COMPILE_${FEATURE}) - message("-- Performing Test ${FEATURE} -- failed to compile") - else() - message("-- Performing Test ${FEATURE} -- compiled but failed to run") - endif() - endif() -endfunction() diff --git a/interpreter/llvm/src/utils/benchmark/cmake/Config.cmake.in b/interpreter/llvm/src/utils/benchmark/cmake/Config.cmake.in deleted file mode 100644 index 6e9256eea8a2d..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/Config.cmake.in +++ /dev/null @@ -1 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") diff --git a/interpreter/llvm/src/utils/benchmark/cmake/GetGitVersion.cmake b/interpreter/llvm/src/utils/benchmark/cmake/GetGitVersion.cmake deleted file mode 100644 index 88cebe3a1caac..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/GetGitVersion.cmake +++ /dev/null @@ -1,54 +0,0 @@ -# - Returns a version string from Git tags -# -# This function inspects the annotated git tags for the project and returns a string -# into a CMake variable -# -# get_git_version() -# -# - Example -# -# include(GetGitVersion) -# get_git_version(GIT_VERSION) -# -# Requires CMake 2.8.11+ -find_package(Git) - -if(__get_git_version) - return() -endif() -set(__get_git_version INCLUDED) - -function(get_git_version var) - if(GIT_EXECUTABLE) - execute_process(COMMAND ${GIT_EXECUTABLE} describe --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8 - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - RESULT_VARIABLE status - OUTPUT_VARIABLE GIT_VERSION - ERROR_QUIET) - if(${status}) - set(GIT_VERSION "v0.0.0") - else() - string(STRIP ${GIT_VERSION} GIT_VERSION) - string(REGEX REPLACE "-[0-9]+-g" "-" GIT_VERSION ${GIT_VERSION}) - endif() - - # Work out if the repository is dirty - execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - OUTPUT_QUIET - ERROR_QUIET) - execute_process(COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD -- - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_DIFF_INDEX - ERROR_QUIET) - string(COMPARE NOTEQUAL "${GIT_DIFF_INDEX}" "" GIT_DIRTY) - if (${GIT_DIRTY}) - set(GIT_VERSION "${GIT_VERSION}-dirty") - endif() - else() - set(GIT_VERSION "v0.0.0") - endif() - - message("-- git Version: ${GIT_VERSION}") - set(${var} ${GIT_VERSION} PARENT_SCOPE) -endfunction() diff --git a/interpreter/llvm/src/utils/benchmark/cmake/HandleGTest.cmake b/interpreter/llvm/src/utils/benchmark/cmake/HandleGTest.cmake deleted file mode 100644 index 7ce1a633d65a2..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/HandleGTest.cmake +++ /dev/null @@ -1,113 +0,0 @@ - -include(split_list) - -macro(build_external_gtest) - include(ExternalProject) - set(GTEST_FLAGS "") - if (BENCHMARK_USE_LIBCXX) - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - list(APPEND GTEST_FLAGS -stdlib=libc++) - else() - message(WARNING "Unsupported compiler (${CMAKE_CXX_COMPILER}) when using libc++") - endif() - endif() - if (BENCHMARK_BUILD_32_BITS) - list(APPEND GTEST_FLAGS -m32) - endif() - if (NOT "${CMAKE_CXX_FLAGS}" STREQUAL "") - list(APPEND GTEST_FLAGS ${CMAKE_CXX_FLAGS}) - endif() - string(TOUPPER "${CMAKE_BUILD_TYPE}" GTEST_BUILD_TYPE) - if ("${GTEST_BUILD_TYPE}" STREQUAL "COVERAGE") - set(GTEST_BUILD_TYPE "DEBUG") - endif() - # FIXME: Since 10/Feb/2017 the googletest trunk has had a bug where - # -Werror=unused-function fires during the build on OS X. This is a temporary - # workaround to keep our travis bots from failing. It should be removed - # once gtest is fixed. - if (NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - list(APPEND GTEST_FLAGS "-Wno-unused-function") - endif() - split_list(GTEST_FLAGS) - set(EXCLUDE_FROM_ALL_OPT "") - set(EXCLUDE_FROM_ALL_VALUE "") - if (${CMAKE_VERSION} VERSION_GREATER "3.0.99") - set(EXCLUDE_FROM_ALL_OPT "EXCLUDE_FROM_ALL") - set(EXCLUDE_FROM_ALL_VALUE "ON") - endif() - ExternalProject_Add(googletest - ${EXCLUDE_FROM_ALL_OPT} ${EXCLUDE_FROM_ALL_VALUE} - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG master - PREFIX "${CMAKE_BINARY_DIR}/googletest" - INSTALL_DIR "${CMAKE_BINARY_DIR}/googletest" - CMAKE_CACHE_ARGS - -DCMAKE_BUILD_TYPE:STRING=${GTEST_BUILD_TYPE} - -DCMAKE_C_COMPILER:STRING=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER:STRING=${CMAKE_CXX_COMPILER} - -DCMAKE_INSTALL_PREFIX:PATH= - -DCMAKE_INSTALL_LIBDIR:PATH=/lib - -DCMAKE_CXX_FLAGS:STRING=${GTEST_FLAGS} - -Dgtest_force_shared_crt:BOOL=ON - ) - - ExternalProject_Get_Property(googletest install_dir) - set(GTEST_INCLUDE_DIRS ${install_dir}/include) - file(MAKE_DIRECTORY ${GTEST_INCLUDE_DIRS}) - - set(LIB_SUFFIX "${CMAKE_STATIC_LIBRARY_SUFFIX}") - set(LIB_PREFIX "${CMAKE_STATIC_LIBRARY_PREFIX}") - if("${GTEST_BUILD_TYPE}" STREQUAL "DEBUG") - set(LIB_SUFFIX "d${CMAKE_STATIC_LIBRARY_SUFFIX}") - endif() - - # Use gmock_main instead of gtest_main because it initializes gtest as well. - # Note: The libraries are listed in reverse order of their dependancies. - foreach(LIB gtest gmock gmock_main) - add_library(${LIB} UNKNOWN IMPORTED) - set_target_properties(${LIB} PROPERTIES - IMPORTED_LOCATION ${install_dir}/lib/${LIB_PREFIX}${LIB}${LIB_SUFFIX} - INTERFACE_INCLUDE_DIRECTORIES ${GTEST_INCLUDE_DIRS} - INTERFACE_LINK_LIBRARIES "${GTEST_BOTH_LIBRARIES}" - ) - add_dependencies(${LIB} googletest) - list(APPEND GTEST_BOTH_LIBRARIES ${LIB}) - endforeach() -endmacro(build_external_gtest) - -if (BENCHMARK_ENABLE_GTEST_TESTS) - if (IS_DIRECTORY ${CMAKE_SOURCE_DIR}/googletest) - set(GTEST_ROOT "${CMAKE_SOURCE_DIR}/googletest") - set(INSTALL_GTEST OFF CACHE INTERNAL "") - set(INSTALL_GMOCK OFF CACHE INTERNAL "") - add_subdirectory(${CMAKE_SOURCE_DIR}/googletest) - set(GTEST_BOTH_LIBRARIES gtest gmock gmock_main) - foreach(HEADER test mock) - # CMake 2.8 and older don't respect INTERFACE_INCLUDE_DIRECTORIES, so we - # have to add the paths ourselves. - set(HFILE g${HEADER}/g${HEADER}.h) - set(HPATH ${GTEST_ROOT}/google${HEADER}/include) - find_path(HEADER_PATH_${HEADER} ${HFILE} - NO_DEFAULT_PATHS - HINTS ${HPATH} - ) - if (NOT HEADER_PATH_${HEADER}) - message(FATAL_ERROR "Failed to find header ${HFILE} in ${HPATH}") - endif() - list(APPEND GTEST_INCLUDE_DIRS ${HEADER_PATH_${HEADER}}) - endforeach() - elseif(BENCHMARK_DOWNLOAD_DEPENDENCIES) - build_external_gtest() - else() - find_package(GTest REQUIRED) - find_path(GMOCK_INCLUDE_DIRS gmock/gmock.h - HINTS ${GTEST_INCLUDE_DIRS}) - if (NOT GMOCK_INCLUDE_DIRS) - message(FATAL_ERROR "Failed to find header gmock/gmock.h with hint ${GTEST_INCLUDE_DIRS}") - endif() - set(GTEST_INCLUDE_DIRS ${GTEST_INCLUDE_DIRS} ${GMOCK_INCLUDE_DIRS}) - # FIXME: We don't currently require the gmock library to build the tests, - # and it's likely we won't find it, so we don't try. As long as we've - # found the gmock/gmock.h header and gtest_main that should be good enough. - endif() -endif() diff --git a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMAr.cmake b/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMAr.cmake deleted file mode 100644 index 23469813cfab5..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMAr.cmake +++ /dev/null @@ -1,16 +0,0 @@ -include(FeatureSummary) - -find_program(LLVMAR_EXECUTABLE - NAMES llvm-ar - DOC "The llvm-ar executable" - ) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(LLVMAr - DEFAULT_MSG - LLVMAR_EXECUTABLE) - -SET_PACKAGE_PROPERTIES(LLVMAr PROPERTIES - URL https://llvm.org/docs/CommandGuide/llvm-ar.html - DESCRIPTION "create, modify, and extract from archives" -) diff --git a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMNm.cmake b/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMNm.cmake deleted file mode 100644 index e56430a04f6e8..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMNm.cmake +++ /dev/null @@ -1,16 +0,0 @@ -include(FeatureSummary) - -find_program(LLVMNM_EXECUTABLE - NAMES llvm-nm - DOC "The llvm-nm executable" - ) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(LLVMNm - DEFAULT_MSG - LLVMNM_EXECUTABLE) - -SET_PACKAGE_PROPERTIES(LLVMNm PROPERTIES - URL https://llvm.org/docs/CommandGuide/llvm-nm.html - DESCRIPTION "list LLVM bitcode and object file’s symbol table" -) diff --git a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMRanLib.cmake b/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMRanLib.cmake deleted file mode 100644 index 7b53e1a790590..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/Modules/FindLLVMRanLib.cmake +++ /dev/null @@ -1,15 +0,0 @@ -include(FeatureSummary) - -find_program(LLVMRANLIB_EXECUTABLE - NAMES llvm-ranlib - DOC "The llvm-ranlib executable" - ) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(LLVMRanLib - DEFAULT_MSG - LLVMRANLIB_EXECUTABLE) - -SET_PACKAGE_PROPERTIES(LLVMRanLib PROPERTIES - DESCRIPTION "generate index for LLVM archive" -) diff --git a/interpreter/llvm/src/utils/benchmark/cmake/benchmark.pc.in b/interpreter/llvm/src/utils/benchmark/cmake/benchmark.pc.in deleted file mode 100644 index 1e84bff68d811..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/benchmark.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=${prefix} -libdir=${prefix}/lib -includedir=${prefix}/include - -Name: @PROJECT_NAME@ -Description: Google microbenchmark framework -Version: @VERSION@ - -Libs: -L${libdir} -lbenchmark -Cflags: -I${includedir} diff --git a/interpreter/llvm/src/utils/benchmark/cmake/gnu_posix_regex.cpp b/interpreter/llvm/src/utils/benchmark/cmake/gnu_posix_regex.cpp deleted file mode 100644 index 105189f02ee6f..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/gnu_posix_regex.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -int main() { - std::string str = "test0159"; - regex_t re; - int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - return ec; - } - return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; -} diff --git a/interpreter/llvm/src/utils/benchmark/cmake/llvm-toolchain.cmake b/interpreter/llvm/src/utils/benchmark/cmake/llvm-toolchain.cmake deleted file mode 100644 index fc119e52fd26a..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/llvm-toolchain.cmake +++ /dev/null @@ -1,8 +0,0 @@ -find_package(LLVMAr REQUIRED) -set(CMAKE_AR "${LLVMAR_EXECUTABLE}" CACHE FILEPATH "" FORCE) - -find_package(LLVMNm REQUIRED) -set(CMAKE_NM "${LLVMNM_EXECUTABLE}" CACHE FILEPATH "" FORCE) - -find_package(LLVMRanLib REQUIRED) -set(CMAKE_RANLIB "${LLVMRANLIB_EXECUTABLE}" CACHE FILEPATH "" FORCE) diff --git a/interpreter/llvm/src/utils/benchmark/cmake/posix_regex.cpp b/interpreter/llvm/src/utils/benchmark/cmake/posix_regex.cpp deleted file mode 100644 index 02f6dfc278a7c..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/posix_regex.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include -#include -int main() { - std::string str = "test0159"; - regex_t re; - int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - return ec; - } - int ret = regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; - regfree(&re); - return ret; -} diff --git a/interpreter/llvm/src/utils/benchmark/cmake/split_list.cmake b/interpreter/llvm/src/utils/benchmark/cmake/split_list.cmake deleted file mode 100644 index 67aed3fdc8579..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/split_list.cmake +++ /dev/null @@ -1,3 +0,0 @@ -macro(split_list listname) - string(REPLACE ";" " " ${listname} "${${listname}}") -endmacro() diff --git a/interpreter/llvm/src/utils/benchmark/cmake/std_regex.cpp b/interpreter/llvm/src/utils/benchmark/cmake/std_regex.cpp deleted file mode 100644 index 8177c482e838b..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/std_regex.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include -#include -int main() { - const std::string str = "test0159"; - std::regex re; - re = std::regex("^[a-z]+[0-9]+$", - std::regex_constants::extended | std::regex_constants::nosubs); - return std::regex_search(str, re) ? 0 : -1; -} diff --git a/interpreter/llvm/src/utils/benchmark/cmake/steady_clock.cpp b/interpreter/llvm/src/utils/benchmark/cmake/steady_clock.cpp deleted file mode 100644 index 66d50d17e9e61..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/steady_clock.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include - -int main() { - typedef std::chrono::steady_clock Clock; - Clock::time_point tp = Clock::now(); - ((void)tp); -} diff --git a/interpreter/llvm/src/utils/benchmark/cmake/thread_safety_attributes.cpp b/interpreter/llvm/src/utils/benchmark/cmake/thread_safety_attributes.cpp deleted file mode 100644 index 46161babdb100..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/cmake/thread_safety_attributes.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#define HAVE_THREAD_SAFETY_ATTRIBUTES -#include "../src/mutex.h" - -int main() {} diff --git a/interpreter/llvm/src/utils/benchmark/docs/AssemblyTests.md b/interpreter/llvm/src/utils/benchmark/docs/AssemblyTests.md deleted file mode 100644 index 0d06f50ac652d..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/docs/AssemblyTests.md +++ /dev/null @@ -1,146 +0,0 @@ -# Assembly Tests - -The Benchmark library provides a number of functions whose primary -purpose in to affect assembly generation, including `DoNotOptimize` -and `ClobberMemory`. In addition there are other functions, -such as `KeepRunning`, for which generating good assembly is paramount. - -For these functions it's important to have tests that verify the -correctness and quality of the implementation. This requires testing -the code generated by the compiler. - -This document describes how the Benchmark library tests compiler output, -as well as how to properly write new tests. - - -## Anatomy of a Test - -Writing a test has two steps: - -* Write the code you want to generate assembly for. -* Add `// CHECK` lines to match against the verified assembly. - -Example: -```c++ - -// CHECK-LABEL: test_add: -extern "C" int test_add() { - extern int ExternInt; - return ExternInt + 1; - - // CHECK: movl ExternInt(%rip), %eax - // CHECK: addl %eax - // CHECK: ret -} - -``` - -#### LLVM Filecheck - -[LLVM's Filecheck](https://llvm.org/docs/CommandGuide/FileCheck.html) -is used to test the generated assembly against the `// CHECK` lines -specified in the tests source file. Please see the documentation -linked above for information on how to write `CHECK` directives. - -#### Tips and Tricks: - -* Tests should match the minimal amount of output required to establish -correctness. `CHECK` directives don't have to match on the exact next line -after the previous match, so tests should omit checks for unimportant -bits of assembly. ([`CHECK-NEXT`](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-next-directive) -can be used to ensure a match occurs exactly after the previous match). - -* The tests are compiled with `-O3 -g0`. So we're only testing the -optimized output. - -* The assembly output is further cleaned up using `tools/strip_asm.py`. -This removes comments, assembler directives, and unused labels before -the test is run. - -* The generated and stripped assembly file for a test is output under -`/test/.s` - -* Filecheck supports using [`CHECK` prefixes](https://llvm.org/docs/CommandGuide/FileCheck.html#cmdoption-check-prefixes) -to specify lines that should only match in certain situations. -The Benchmark tests use `CHECK-CLANG` and `CHECK-GNU` for lines that -are only expected to match Clang or GCC's output respectively. Normal -`CHECK` lines match against all compilers. (Note: `CHECK-NOT` and -`CHECK-LABEL` are NOT prefixes. They are versions of non-prefixed -`CHECK` lines) - -* Use `extern "C"` to disable name mangling for specific functions. This -makes them easier to name in the `CHECK` lines. - - -## Problems Writing Portable Tests - -Writing tests which check the code generated by a compiler are -inherently non-portable. Different compilers and even different compiler -versions may generate entirely different code. The Benchmark tests -must tolerate this. - -LLVM Filecheck provides a number of mechanisms to help write -"more portable" tests; including [matching using regular expressions](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-pattern-matching-syntax), -allowing the creation of [named variables](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-variables) -for later matching, and [checking non-sequential matches](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-dag-directive). - -#### Capturing Variables - -For example, say GCC stores a variable in a register but Clang stores -it in memory. To write a test that tolerates both cases we "capture" -the destination of the store, and then use the captured expression -to write the remainder of the test. - -```c++ -// CHECK-LABEL: test_div_no_op_into_shr: -extern "C" void test_div_no_op_into_shr(int value) { - int divisor = 2; - benchmark::DoNotOptimize(divisor); // hide the value from the optimizer - return value / divisor; - - // CHECK: movl $2, [[DEST:.*]] - // CHECK: idivl [[DEST]] - // CHECK: ret -} -``` - -#### Using Regular Expressions to Match Differing Output - -Often tests require testing assembly lines which may subtly differ -between compilers or compiler versions. A common example of this -is matching stack frame addresses. In this case regular expressions -can be used to match the differing bits of output. For example: - -```c++ -int ExternInt; -struct Point { int x, y, z; }; - -// CHECK-LABEL: test_store_point: -extern "C" void test_store_point() { - Point p{ExternInt, ExternInt, ExternInt}; - benchmark::DoNotOptimize(p); - - // CHECK: movl ExternInt(%rip), %eax - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: ret -} -``` - -## Current Requirements and Limitations - -The tests require Filecheck to be installed along the `PATH` of the -build machine. Otherwise the tests will be disabled. - -Additionally, as mentioned in the previous section, codegen tests are -inherently non-portable. Currently the tests are limited to: - -* x86_64 targets. -* Compiled with GCC or Clang - -Further work could be done, at least on a limited basis, to extend the -tests to other architectures and compilers (using `CHECK` prefixes). - -Furthermore, the tests fail for builds which specify additional flags -that modify code generation, including `--coverage` or `-fsanitize=`. diff --git a/interpreter/llvm/src/utils/benchmark/docs/tools.md b/interpreter/llvm/src/utils/benchmark/docs/tools.md deleted file mode 100644 index 70500bd3223ce..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/docs/tools.md +++ /dev/null @@ -1,242 +0,0 @@ -# Benchmark Tools - -## compare_bench.py - -The `compare_bench.py` utility which can be used to compare the result of benchmarks. -The program is invoked like: - -``` bash -$ compare_bench.py [benchmark options]... -``` - -Where `` and `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -The sample output using the JSON test files under `Inputs/` gives: - -``` bash -$ ./compare_bench.py ./gbench/Inputs/test1_run1.json ./gbench/Inputs/test1_run2.json -Comparing ./gbench/Inputs/test1_run1.json to ./gbench/Inputs/test1_run2.json -Benchmark Time CPU Time Old Time New CPU Old CPU New -------------------------------------------------------------------------------------------------------------- -BM_SameTimes +0.0000 +0.0000 10 10 10 10 -BM_2xFaster -0.5000 -0.5000 50 25 50 25 -BM_2xSlower +1.0000 +1.0000 50 100 50 100 -BM_1PercentFaster -0.0100 -0.0100 100 99 100 99 -BM_1PercentSlower +0.0100 +0.0100 100 101 100 101 -BM_10PercentFaster -0.1000 -0.1000 100 90 100 90 -BM_10PercentSlower +0.1000 +0.1000 100 110 100 110 -BM_100xSlower +99.0000 +99.0000 100 10000 100 10000 -BM_100xFaster -0.9900 -0.9900 10000 100 10000 100 -BM_10PercentCPUToTime +0.1000 -0.1000 100 110 100 90 -BM_ThirdFaster -0.3333 -0.3334 100 67 100 67 -BM_BadTimeUnit -0.9000 +0.2000 0 0 0 1 -``` - -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -When a benchmark executable is run, the raw output from the benchmark is printed in real time to stdout. The sample output using `benchmark/basic_test` for both arguments looks like: - -``` -./compare_bench.py test/basic_test test/basic_test --benchmark_filter=BM_empty.* -RUNNING: test/basic_test --benchmark_filter=BM_empty.* --benchmark_out=/tmp/tmpN7LF3a -Run on (8 X 4000 MHz CPU s) -2017-11-07 23:28:36 ---------------------------------------------------------------------- -Benchmark Time CPU Iterations ---------------------------------------------------------------------- -BM_empty 4 ns 4 ns 170178757 -BM_empty/threads:8 1 ns 7 ns 103868920 -BM_empty_stop_start 0 ns 0 ns 1000000000 -BM_empty_stop_start/threads:8 0 ns 0 ns 1403031720 -RUNNING: /test/basic_test --benchmark_filter=BM_empty.* --benchmark_out=/tmp/tmplvrIp8 -Run on (8 X 4000 MHz CPU s) -2017-11-07 23:28:38 ---------------------------------------------------------------------- -Benchmark Time CPU Iterations ---------------------------------------------------------------------- -BM_empty 4 ns 4 ns 169534855 -BM_empty/threads:8 1 ns 7 ns 104188776 -BM_empty_stop_start 0 ns 0 ns 1000000000 -BM_empty_stop_start/threads:8 0 ns 0 ns 1404159424 -Comparing ../build/test/basic_test to ../build/test/basic_test -Benchmark Time CPU Time Old Time New CPU Old CPU New ---------------------------------------------------------------------------------------------------------------------- -BM_empty -0.0048 -0.0049 4 4 4 4 -BM_empty/threads:8 -0.0123 -0.0054 1 1 7 7 -BM_empty_stop_start -0.0000 -0.0000 0 0 0 0 -BM_empty_stop_start/threads:8 -0.0029 +0.0001 0 0 0 0 - -``` - -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. -Obviously this example doesn't give any useful output, but it's intended to show the output format when 'compare_bench.py' needs to run benchmarks. - -## compare.py - -The `compare.py` can be used to compare the result of benchmarks. -There are three modes of operation: - -1. Just compare two benchmarks, what `compare_bench.py` did. -The program is invoked like: - -``` bash -$ compare.py benchmarks [benchmark options]... -``` -Where `` and `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py benchmarks ./a.out ./a.out -RUNNING: ./a.out --benchmark_out=/tmp/tmprBT5nW -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:16:44 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 19101577 211.669MB/s -BM_memcpy/64 76 ns 76 ns 9412571 800.199MB/s -BM_memcpy/512 84 ns 84 ns 8249070 5.64771GB/s -BM_memcpy/1024 116 ns 116 ns 6181763 8.19505GB/s -BM_memcpy/8192 643 ns 643 ns 1062855 11.8636GB/s -BM_copy/8 222 ns 222 ns 3137987 34.3772MB/s -BM_copy/64 1608 ns 1608 ns 432758 37.9501MB/s -BM_copy/512 12589 ns 12589 ns 54806 38.7867MB/s -BM_copy/1024 25169 ns 25169 ns 27713 38.8003MB/s -BM_copy/8192 201165 ns 201112 ns 3486 38.8466MB/s -RUNNING: ./a.out --benchmark_out=/tmp/tmpt1wwG_ -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:16:53 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 19397903 211.255MB/s -BM_memcpy/64 73 ns 73 ns 9691174 839.635MB/s -BM_memcpy/512 85 ns 85 ns 8312329 5.60101GB/s -BM_memcpy/1024 118 ns 118 ns 6438774 8.11608GB/s -BM_memcpy/8192 656 ns 656 ns 1068644 11.6277GB/s -BM_copy/8 223 ns 223 ns 3146977 34.2338MB/s -BM_copy/64 1611 ns 1611 ns 435340 37.8751MB/s -BM_copy/512 12622 ns 12622 ns 54818 38.6844MB/s -BM_copy/1024 25257 ns 25239 ns 27779 38.6927MB/s -BM_copy/8192 205013 ns 205010 ns 3479 38.108MB/s -Comparing ./a.out to ./a.out -Benchmark Time CPU Time Old Time New CPU Old CPU New ------------------------------------------------------------------------------------------------------- -BM_memcpy/8 +0.0020 +0.0020 36 36 36 36 -BM_memcpy/64 -0.0468 -0.0470 76 73 76 73 -BM_memcpy/512 +0.0081 +0.0083 84 85 84 85 -BM_memcpy/1024 +0.0098 +0.0097 116 118 116 118 -BM_memcpy/8192 +0.0200 +0.0203 643 656 643 656 -BM_copy/8 +0.0046 +0.0042 222 223 222 223 -BM_copy/64 +0.0020 +0.0020 1608 1611 1608 1611 -BM_copy/512 +0.0027 +0.0026 12589 12622 12589 12622 -BM_copy/1024 +0.0035 +0.0028 25169 25257 25169 25239 -BM_copy/8192 +0.0191 +0.0194 201165 205013 201112 205010 -``` - -What it does is for the every benchmark from the first run it looks for the benchmark with exactly the same name in the second run, and then compares the results. If the names differ, the benchmark is omitted from the diff. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -2. Compare two different filters of one benchmark -The program is invoked like: - -``` bash -$ compare.py filters [benchmark options]... -``` -Where `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -Where `` and `` are the same regex filters that you would pass to the `[--benchmark_filter=]` parameter of the benchmark binary. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py filters ./a.out BM_memcpy BM_copy -RUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmpBWKk0k -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:37:28 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 17891491 211.215MB/s -BM_memcpy/64 74 ns 74 ns 9400999 825.646MB/s -BM_memcpy/512 87 ns 87 ns 8027453 5.46126GB/s -BM_memcpy/1024 111 ns 111 ns 6116853 8.5648GB/s -BM_memcpy/8192 657 ns 656 ns 1064679 11.6247GB/s -RUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpAvWcOM -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:37:33 ----------------------------------------------------- -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_copy/8 227 ns 227 ns 3038700 33.6264MB/s -BM_copy/64 1640 ns 1640 ns 426893 37.2154MB/s -BM_copy/512 12804 ns 12801 ns 55417 38.1444MB/s -BM_copy/1024 25409 ns 25407 ns 27516 38.4365MB/s -BM_copy/8192 202986 ns 202990 ns 3454 38.4871MB/s -Comparing BM_memcpy to BM_copy (from ./a.out) -Benchmark Time CPU Time Old Time New CPU Old CPU New --------------------------------------------------------------------------------------------------------------------- -[BM_memcpy vs. BM_copy]/8 +5.2829 +5.2812 36 227 36 227 -[BM_memcpy vs. BM_copy]/64 +21.1719 +21.1856 74 1640 74 1640 -[BM_memcpy vs. BM_copy]/512 +145.6487 +145.6097 87 12804 87 12801 -[BM_memcpy vs. BM_copy]/1024 +227.1860 +227.1776 111 25409 111 25407 -[BM_memcpy vs. BM_copy]/8192 +308.1664 +308.2898 657 202986 656 202990 -``` - -As you can see, it applies filter to the benchmarks, both when running the benchmark, and before doing the diff. And to make the diff work, the matches are replaced with some common string. Thus, you can compare two different benchmark families within one benchmark binary. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -3. Compare filter one from benchmark one to filter two from benchmark two: -The program is invoked like: - -``` bash -$ compare.py filters [benchmark options]... -``` - -Where `` and `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -Where `` and `` are the same regex filters that you would pass to the `[--benchmark_filter=]` parameter of the benchmark binary. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py benchmarksfiltered ./a.out BM_memcpy ./a.out BM_copy -RUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmp_FvbYg -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:38:27 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 37 ns 37 ns 18953482 204.118MB/s -BM_memcpy/64 74 ns 74 ns 9206578 828.245MB/s -BM_memcpy/512 91 ns 91 ns 8086195 5.25476GB/s -BM_memcpy/1024 120 ns 120 ns 5804513 7.95662GB/s -BM_memcpy/8192 664 ns 664 ns 1028363 11.4948GB/s -RUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpDfL5iE -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:38:32 ----------------------------------------------------- -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_copy/8 230 ns 230 ns 2985909 33.1161MB/s -BM_copy/64 1654 ns 1653 ns 419408 36.9137MB/s -BM_copy/512 13122 ns 13120 ns 53403 37.2156MB/s -BM_copy/1024 26679 ns 26666 ns 26575 36.6218MB/s -BM_copy/8192 215068 ns 215053 ns 3221 36.3283MB/s -Comparing BM_memcpy (from ./a.out) to BM_copy (from ./a.out) -Benchmark Time CPU Time Old Time New CPU Old CPU New --------------------------------------------------------------------------------------------------------------------- -[BM_memcpy vs. BM_copy]/8 +5.1649 +5.1637 37 230 37 230 -[BM_memcpy vs. BM_copy]/64 +21.4352 +21.4374 74 1654 74 1653 -[BM_memcpy vs. BM_copy]/512 +143.6022 +143.5865 91 13122 91 13120 -[BM_memcpy vs. BM_copy]/1024 +221.5903 +221.4790 120 26679 120 26666 -[BM_memcpy vs. BM_copy]/8192 +322.9059 +323.0096 664 215068 664 215053 -``` -This is a mix of the previous two modes, two (potentially different) benchmark binaries are run, and a different filter is applied to each one. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. diff --git a/interpreter/llvm/src/utils/benchmark/include/benchmark/benchmark.h b/interpreter/llvm/src/utils/benchmark/include/benchmark/benchmark.h deleted file mode 100644 index 528aa7f9c8bb8..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/include/benchmark/benchmark.h +++ /dev/null @@ -1,1467 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Support for registering benchmarks for functions. - -/* Example usage: -// Define a function that executes the code to be measured a -// specified number of times: -static void BM_StringCreation(benchmark::State& state) { - for (auto _ : state) - std::string empty_string; -} - -// Register the function as a benchmark -BENCHMARK(BM_StringCreation); - -// Define another benchmark -static void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - for (auto _ : state) - std::string copy(x); -} -BENCHMARK(BM_StringCopy); - -// Augment the main() program to invoke benchmarks if specified -// via the --benchmarks command line flag. E.g., -// my_unittest --benchmark_filter=all -// my_unittest --benchmark_filter=BM_StringCreation -// my_unittest --benchmark_filter=String -// my_unittest --benchmark_filter='Copy|Creation' -int main(int argc, char** argv) { - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); - return 0; -} - -// Sometimes a family of microbenchmarks can be implemented with -// just one routine that takes an extra argument to specify which -// one of the family of benchmarks to run. For example, the following -// code defines a family of microbenchmarks for measuring the speed -// of memcpy() calls of different lengths: - -static void BM_memcpy(benchmark::State& state) { - char* src = new char[state.range(0)]; char* dst = new char[state.range(0)]; - memset(src, 'x', state.range(0)); - for (auto _ : state) - memcpy(dst, src, state.range(0)); - state.SetBytesProcessed(int64_t(state.iterations()) * - int64_t(state.range(0))); - delete[] src; delete[] dst; -} -BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); - -// The preceding code is quite repetitive, and can be replaced with the -// following short-hand. The following invocation will pick a few -// appropriate arguments in the specified range and will generate a -// microbenchmark for each such argument. -BENCHMARK(BM_memcpy)->Range(8, 8<<10); - -// You might have a microbenchmark that depends on two inputs. For -// example, the following code defines a family of microbenchmarks for -// measuring the speed of set insertion. -static void BM_SetInsert(benchmark::State& state) { - set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) - data.insert(RandomNumber()); - } -} -BENCHMARK(BM_SetInsert) - ->Args({1<<10, 128}) - ->Args({2<<10, 128}) - ->Args({4<<10, 128}) - ->Args({8<<10, 128}) - ->Args({1<<10, 512}) - ->Args({2<<10, 512}) - ->Args({4<<10, 512}) - ->Args({8<<10, 512}); - -// The preceding code is quite repetitive, and can be replaced with -// the following short-hand. The following macro will pick a few -// appropriate arguments in the product of the two specified ranges -// and will generate a microbenchmark for each such pair. -BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); - -// For more complex patterns of inputs, passing a custom function -// to Apply allows programmatic specification of an -// arbitrary set of arguments to run the microbenchmark on. -// The following example enumerates a dense range on -// one parameter, and a sparse range on the second. -static void CustomArguments(benchmark::internal::Benchmark* b) { - for (int i = 0; i <= 10; ++i) - for (int j = 32; j <= 1024*1024; j *= 8) - b->Args({i, j}); -} -BENCHMARK(BM_SetInsert)->Apply(CustomArguments); - -// Templated microbenchmarks work the same way: -// Produce then consume 'size' messages 'iters' times -// Measures throughput in the absence of multiprogramming. -template int BM_Sequential(benchmark::State& state) { - Q q; - typename Q::value_type v; - for (auto _ : state) { - for (int i = state.range(0); i--; ) - q.push(v); - for (int e = state.range(0); e--; ) - q.Wait(&v); - } - // actually messages, not bytes: - state.SetBytesProcessed( - static_cast(state.iterations())*state.range(0)); -} -BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); - -Use `Benchmark::MinTime(double t)` to set the minimum time used to run the -benchmark. This option overrides the `benchmark_min_time` flag. - -void BM_test(benchmark::State& state) { - ... body ... -} -BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds. - -In a multithreaded test, it is guaranteed that none of the threads will start -until all have reached the loop start, and all will have finished before any -thread exits the loop body. As such, any global setup or teardown you want to -do can be wrapped in a check against the thread index: - -static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { - // Setup code here. - } - for (auto _ : state) { - // Run the test as normal. - } - if (state.thread_index == 0) { - // Teardown code here. - } -} -BENCHMARK(BM_MultiThreaded)->Threads(4); - - -If a benchmark runs a few milliseconds it may be hard to visually compare the -measured times, since the output data is given in nanoseconds per default. In -order to manually set the time unit, you can specify it manually: - -BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); -*/ - -#ifndef BENCHMARK_BENCHMARK_H_ -#define BENCHMARK_BENCHMARK_H_ - - -// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. -#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) -#define BENCHMARK_HAS_CXX11 -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(BENCHMARK_HAS_CXX11) -#include -#include -#include -#endif - -#if defined(_MSC_VER) -#include // for _ReadWriteBarrier -#endif - -#ifndef BENCHMARK_HAS_CXX11 -#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - TypeName& operator=(const TypeName&) -#else -#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName& operator=(const TypeName&) = delete -#endif - -#if defined(__GNUC__) -#define BENCHMARK_UNUSED __attribute__((unused)) -#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline)) -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) -#elif defined(_MSC_VER) && !defined(__clang__) -#define BENCHMARK_UNUSED -#define BENCHMARK_ALWAYS_INLINE __forceinline -#if _MSC_VER >= 1900 -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) -#else -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) -#endif -#define __func__ __FUNCTION__ -#else -#define BENCHMARK_UNUSED -#define BENCHMARK_ALWAYS_INLINE -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) -#endif - -#define BENCHMARK_INTERNAL_TOSTRING2(x) #x -#define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x) - -#if defined(__GNUC__) -#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) -#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) -#else -#define BENCHMARK_BUILTIN_EXPECT(x, y) x -#define BENCHMARK_DEPRECATED_MSG(msg) -#define BENCHMARK_WARNING_MSG(msg) __pragma(message(__FILE__ "(" BENCHMARK_INTERNAL_TOSTRING(__LINE__) ") : warning note: " msg)) -#endif - -#if defined(__GNUC__) && !defined(__clang__) -#define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -#endif - -#ifndef __has_builtin -#define __has_builtin(x) 0 -#endif - -#if defined(__GNUC__) || __has_builtin(__builtin_unreachable) - #define BENCHMARK_UNREACHABLE() __builtin_unreachable() -#elif defined(_MSC_VER) - #define BENCHMARK_UNREACHABLE() __assume(false) -#else - #define BENCHMARK_UNREACHABLE() ((void)0) -#endif - -namespace benchmark { -class BenchmarkReporter; - -void Initialize(int* argc, char** argv); - -// Report to stdout all arguments in 'argv' as unrecognized except the first. -// Returns true there is at least on unrecognized argument (i.e. 'argc' > 1). -bool ReportUnrecognizedArguments(int argc, char** argv); - -// Generate a list of benchmarks matching the specified --benchmark_filter flag -// and if --benchmark_list_tests is specified return after printing the name -// of each matching benchmark. Otherwise run each matching benchmark and -// report the results. -// -// The second and third overload use the specified 'console_reporter' and -// 'file_reporter' respectively. 'file_reporter' will write to the file -// specified -// by '--benchmark_output'. If '--benchmark_output' is not given the -// 'file_reporter' is ignored. -// -// RETURNS: The number of matching benchmarks. -size_t RunSpecifiedBenchmarks(); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter, - BenchmarkReporter* file_reporter); - -// If this routine is called, peak memory allocation past this point in the -// benchmark is reported at the end of the benchmark report line. (It is -// computed by running the benchmark once with a single iteration and a memory -// tracer.) -// TODO(dominic) -// void MemoryUsage(); - -namespace internal { -class Benchmark; -class BenchmarkImp; -class BenchmarkFamilies; - -void UseCharPointer(char const volatile*); - -// Take ownership of the pointer and register the benchmark. Return the -// registered benchmark. -Benchmark* RegisterBenchmarkInternal(Benchmark*); - -// Ensure that the standard streams are properly initialized in every TU. -int InitializeStreams(); -BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams(); - -} // namespace internal - - -#if (!defined(__GNUC__) && !defined(__clang__)) || defined(__pnacl__) || \ - defined(__EMSCRIPTEN__) -# define BENCHMARK_HAS_NO_INLINE_ASSEMBLY -#endif - - -// The DoNotOptimize(...) function can be used to prevent a value or -// expression from being optimized away by the compiler. This function is -// intended to add little to no overhead. -// See: https://youtu.be/nXaxk27zwlk?t=2441 -#ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY -template -inline BENCHMARK_ALWAYS_INLINE -void DoNotOptimize(Tp const& value) { - asm volatile("" : : "r,m"(value) : "memory"); -} - -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { -#if defined(__clang__) - asm volatile("" : "+r,m"(value) : : "memory"); -#else - asm volatile("" : "+m,r"(value) : : "memory"); -#endif -} - -// Force the compiler to flush pending writes to global memory. Acts as an -// effective read/write barrier -inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { - asm volatile("" : : : "memory"); -} -#elif defined(_MSC_VER) -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { - internal::UseCharPointer(&reinterpret_cast(value)); - _ReadWriteBarrier(); -} - -inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { - _ReadWriteBarrier(); -} -#else -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { - internal::UseCharPointer(&reinterpret_cast(value)); -} -// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers -#endif - - - -// This class is used for user-defined counters. -class Counter { -public: - - enum Flags { - kDefaults = 0, - // Mark the counter as a rate. It will be presented divided - // by the duration of the benchmark. - kIsRate = 1, - // Mark the counter as a thread-average quantity. It will be - // presented divided by the number of threads. - kAvgThreads = 2, - // Mark the counter as a thread-average rate. See above. - kAvgThreadsRate = kIsRate|kAvgThreads - }; - - double value; - Flags flags; - - BENCHMARK_ALWAYS_INLINE - Counter(double v = 0., Flags f = kDefaults) : value(v), flags(f) {} - - BENCHMARK_ALWAYS_INLINE operator double const& () const { return value; } - BENCHMARK_ALWAYS_INLINE operator double & () { return value; } - -}; - -// This is the container for the user-defined counters. -typedef std::map UserCounters; - - -// TimeUnit is passed to a benchmark in order to specify the order of magnitude -// for the measured time. -enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond }; - -// BigO is passed to a benchmark in order to specify the asymptotic -// computational -// complexity for the benchmark. In case oAuto is selected, complexity will be -// calculated automatically to the best fit. -enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda }; - -// BigOFunc is passed to a benchmark in order to specify the asymptotic -// computational complexity for the benchmark. -typedef double(BigOFunc)(int64_t); - -// StatisticsFunc is passed to a benchmark in order to compute some descriptive -// statistics over all the measurements of some type -typedef double(StatisticsFunc)(const std::vector&); - -struct Statistics { - std::string name_; - StatisticsFunc* compute_; - - Statistics(std::string name, StatisticsFunc* compute) - : name_(name), compute_(compute) {} -}; - -namespace internal { -class ThreadTimer; -class ThreadManager; - -enum ReportMode -#if defined(BENCHMARK_HAS_CXX11) - : unsigned -#else -#endif - { - RM_Unspecified, // The mode has not been manually specified - RM_Default, // The mode is user-specified as default. - RM_ReportAggregatesOnly -}; -} // namespace internal - -// State is passed to a running Benchmark and contains state for the -// benchmark to use. -class State { - public: - struct StateIterator; - friend struct StateIterator; - - // Returns iterators used to run each iteration of a benchmark using a - // C++11 ranged-based for loop. These functions should not be called directly. - // - // REQUIRES: The benchmark has not started running yet. Neither begin nor end - // have been called previously. - // - // NOTE: KeepRunning may not be used after calling either of these functions. - BENCHMARK_ALWAYS_INLINE StateIterator begin(); - BENCHMARK_ALWAYS_INLINE StateIterator end(); - - // Returns true if the benchmark should continue through another iteration. - // NOTE: A benchmark may not return from the test until KeepRunning() has - // returned false. - bool KeepRunning(); - - // Returns true iff the benchmark should run n more iterations. - // REQUIRES: 'n' > 0. - // NOTE: A benchmark must not return from the test until KeepRunningBatch() - // has returned false. - // NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations. - // - // Intended usage: - // while (state.KeepRunningBatch(1000)) { - // // process 1000 elements - // } - bool KeepRunningBatch(size_t n); - - // REQUIRES: timer is running and 'SkipWithError(...)' has not been called - // by the current thread. - // Stop the benchmark timer. If not called, the timer will be - // automatically stopped after the last iteration of the benchmark loop. - // - // For threaded benchmarks the PauseTiming() function only pauses the timing - // for the current thread. - // - // NOTE: The "real time" measurement is per-thread. If different threads - // report different measurements the largest one is reported. - // - // NOTE: PauseTiming()/ResumeTiming() are relatively - // heavyweight, and so their use should generally be avoided - // within each benchmark iteration, if possible. - void PauseTiming(); - - // REQUIRES: timer is not running and 'SkipWithError(...)' has not been called - // by the current thread. - // Start the benchmark timer. The timer is NOT running on entrance to the - // benchmark function. It begins running after control flow enters the - // benchmark loop. - // - // NOTE: PauseTiming()/ResumeTiming() are relatively - // heavyweight, and so their use should generally be avoided - // within each benchmark iteration, if possible. - void ResumeTiming(); - - // REQUIRES: 'SkipWithError(...)' has not been called previously by the - // current thread. - // Report the benchmark as resulting in an error with the specified 'msg'. - // After this call the user may explicitly 'return' from the benchmark. - // - // If the ranged-for style of benchmark loop is used, the user must explicitly - // break from the loop, otherwise all future iterations will be run. - // If the 'KeepRunning()' loop is used the current thread will automatically - // exit the loop at the end of the current iteration. - // - // For threaded benchmarks only the current thread stops executing and future - // calls to `KeepRunning()` will block until all threads have completed - // the `KeepRunning()` loop. If multiple threads report an error only the - // first error message is used. - // - // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit - // the current scope immediately. If the function is called from within - // the 'KeepRunning()' loop the current iteration will finish. It is the users - // responsibility to exit the scope as needed. - void SkipWithError(const char* msg); - - // REQUIRES: called exactly once per iteration of the benchmarking loop. - // Set the manually measured time for this benchmark iteration, which - // is used instead of automatically measured time if UseManualTime() was - // specified. - // - // For threaded benchmarks the final value will be set to the largest - // reported values. - void SetIterationTime(double seconds); - - // Set the number of bytes processed by the current benchmark - // execution. This routine is typically called once at the end of a - // throughput oriented benchmark. If this routine is called with a - // value > 0, the report is printed in MB/sec instead of nanoseconds - // per iteration. - // - // REQUIRES: a benchmark has exited its benchmarking loop. - BENCHMARK_ALWAYS_INLINE - void SetBytesProcessed(int64_t bytes) { bytes_processed_ = bytes; } - - BENCHMARK_ALWAYS_INLINE - int64_t bytes_processed() const { return bytes_processed_; } - - // If this routine is called with complexity_n > 0 and complexity report is - // requested for the - // family benchmark, then current benchmark will be part of the computation - // and complexity_n will - // represent the length of N. - BENCHMARK_ALWAYS_INLINE - void SetComplexityN(int64_t complexity_n) { complexity_n_ = complexity_n; } - - BENCHMARK_ALWAYS_INLINE - int64_t complexity_length_n() { return complexity_n_; } - - // If this routine is called with items > 0, then an items/s - // label is printed on the benchmark report line for the currently - // executing benchmark. It is typically called at the end of a processing - // benchmark where a processing items/second output is desired. - // - // REQUIRES: a benchmark has exited its benchmarking loop. - BENCHMARK_ALWAYS_INLINE - void SetItemsProcessed(int64_t items) { items_processed_ = items; } - - BENCHMARK_ALWAYS_INLINE - int64_t items_processed() const { return items_processed_; } - - // If this routine is called, the specified label is printed at the - // end of the benchmark report line for the currently executing - // benchmark. Example: - // static void BM_Compress(benchmark::State& state) { - // ... - // double compress = input_size / output_size; - // state.SetLabel(StrFormat("compress:%.1f%%", 100.0*compression)); - // } - // Produces output that looks like: - // BM_Compress 50 50 14115038 compress:27.3% - // - // REQUIRES: a benchmark has exited its benchmarking loop. - void SetLabel(const char* label); - - void BENCHMARK_ALWAYS_INLINE SetLabel(const std::string& str) { - this->SetLabel(str.c_str()); - } - - // Range arguments for this run. CHECKs if the argument has been set. - BENCHMARK_ALWAYS_INLINE - int64_t range(std::size_t pos = 0) const { - assert(range_.size() > pos); - return range_[pos]; - } - - BENCHMARK_DEPRECATED_MSG("use 'range(0)' instead") - int64_t range_x() const { return range(0); } - - BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead") - int64_t range_y() const { return range(1); } - - BENCHMARK_ALWAYS_INLINE - size_t iterations() const { - if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) { - return 0; - } - return max_iterations - total_iterations_ + batch_leftover_; - } - -private: // items we expect on the first cache line (ie 64 bytes of the struct) - - // When total_iterations_ is 0, KeepRunning() and friends will return false. - // May be larger than max_iterations. - size_t total_iterations_; - - // When using KeepRunningBatch(), batch_leftover_ holds the number of - // iterations beyond max_iters that were run. Used to track - // completed_iterations_ accurately. - size_t batch_leftover_; - -public: - const size_t max_iterations; - -private: - bool started_; - bool finished_; - bool error_occurred_; - -private: // items we don't need on the first cache line - std::vector range_; - - int64_t bytes_processed_; - int64_t items_processed_; - - int64_t complexity_n_; - - public: - // Container for user-defined counters. - UserCounters counters; - // Index of the executing thread. Values from [0, threads). - const int thread_index; - // Number of threads concurrently executing the benchmark. - const int threads; - - - // TODO(EricWF) make me private - State(size_t max_iters, const std::vector& ranges, int thread_i, - int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager); - - private: - void StartKeepRunning(); - // Implementation of KeepRunning() and KeepRunningBatch(). - // is_batch must be true unless n is 1. - bool KeepRunningInternal(size_t n, bool is_batch); - void FinishKeepRunning(); - internal::ThreadTimer* timer_; - internal::ThreadManager* manager_; - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(State); -}; - -inline BENCHMARK_ALWAYS_INLINE -bool State::KeepRunning() { - return KeepRunningInternal(1, /*is_batch=*/ false); -} - -inline BENCHMARK_ALWAYS_INLINE -bool State::KeepRunningBatch(size_t n) { - return KeepRunningInternal(n, /*is_batch=*/ true); -} - -inline BENCHMARK_ALWAYS_INLINE -bool State::KeepRunningInternal(size_t n, bool is_batch) { - // total_iterations_ is set to 0 by the constructor, and always set to a - // nonzero value by StartKepRunning(). - assert(n > 0); - // n must be 1 unless is_batch is true. - assert(is_batch || n == 1); - if (BENCHMARK_BUILTIN_EXPECT(total_iterations_ >= n, true)) { - total_iterations_ -= n; - return true; - } - if (!started_) { - StartKeepRunning(); - if (!error_occurred_ && total_iterations_ >= n) { - total_iterations_-= n; - return true; - } - } - // For non-batch runs, total_iterations_ must be 0 by now. - if (is_batch && total_iterations_ != 0) { - batch_leftover_ = n - total_iterations_; - total_iterations_ = 0; - return true; - } - FinishKeepRunning(); - return false; -} - -struct State::StateIterator { - struct BENCHMARK_UNUSED Value {}; - typedef std::forward_iterator_tag iterator_category; - typedef Value value_type; - typedef Value reference; - typedef Value pointer; - typedef std::ptrdiff_t difference_type; - - private: - friend class State; - BENCHMARK_ALWAYS_INLINE - StateIterator() : cached_(0), parent_() {} - - BENCHMARK_ALWAYS_INLINE - explicit StateIterator(State* st) - : cached_(st->error_occurred_ ? 0 : st->max_iterations), parent_(st) {} - - public: - BENCHMARK_ALWAYS_INLINE - Value operator*() const { return Value(); } - - BENCHMARK_ALWAYS_INLINE - StateIterator& operator++() { - assert(cached_ > 0); - --cached_; - return *this; - } - - BENCHMARK_ALWAYS_INLINE - bool operator!=(StateIterator const&) const { - if (BENCHMARK_BUILTIN_EXPECT(cached_ != 0, true)) return true; - parent_->FinishKeepRunning(); - return false; - } - - private: - size_t cached_; - State* const parent_; -}; - -inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::begin() { - return StateIterator(this); -} -inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::end() { - StartKeepRunning(); - return StateIterator(); -} - -namespace internal { - -typedef void(Function)(State&); - -// ------------------------------------------------------ -// Benchmark registration object. The BENCHMARK() macro expands -// into an internal::Benchmark* object. Various methods can -// be called on this object to change the properties of the benchmark. -// Each method returns "this" so that multiple method calls can -// chained into one expression. -class Benchmark { - public: - virtual ~Benchmark(); - - // Note: the following methods all return "this" so that multiple - // method calls can be chained together in one expression. - - // Run this benchmark once with "x" as the extra argument passed - // to the function. - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* Arg(int64_t x); - - // Run this benchmark with the given time unit for the generated output report - Benchmark* Unit(TimeUnit unit); - - // Run this benchmark once for a number of values picked from the - // range [start..limit]. (start and limit are always picked.) - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* Range(int64_t start, int64_t limit); - - // Run this benchmark once for all values in the range [start..limit] with - // specific step - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* DenseRange(int64_t start, int64_t limit, int step = 1); - - // Run this benchmark once with "args" as the extra arguments passed - // to the function. - // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... - Benchmark* Args(const std::vector& args); - - // Equivalent to Args({x, y}) - // NOTE: This is a legacy C++03 interface provided for compatibility only. - // New code should use 'Args'. - Benchmark* ArgPair(int64_t x, int64_t y) { - std::vector args; - args.push_back(x); - args.push_back(y); - return Args(args); - } - - // Run this benchmark once for a number of values picked from the - // ranges [start..limit]. (starts and limits are always picked.) - // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... - Benchmark* Ranges(const std::vector >& ranges); - - // Equivalent to ArgNames({name}) - Benchmark* ArgName(const std::string& name); - - // Set the argument names to display in the benchmark name. If not called, - // only argument values will be shown. - Benchmark* ArgNames(const std::vector& names); - - // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}). - // NOTE: This is a legacy C++03 interface provided for compatibility only. - // New code should use 'Ranges'. - Benchmark* RangePair(int64_t lo1, int64_t hi1, int64_t lo2, int64_t hi2) { - std::vector > ranges; - ranges.push_back(std::make_pair(lo1, hi1)); - ranges.push_back(std::make_pair(lo2, hi2)); - return Ranges(ranges); - } - - // Pass this benchmark object to *func, which can customize - // the benchmark by calling various methods like Arg, Args, - // Threads, etc. - Benchmark* Apply(void (*func)(Benchmark* benchmark)); - - // Set the range multiplier for non-dense range. If not called, the range - // multiplier kRangeMultiplier will be used. - Benchmark* RangeMultiplier(int multiplier); - - // Set the minimum amount of time to use when running this benchmark. This - // option overrides the `benchmark_min_time` flag. - // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark. - Benchmark* MinTime(double t); - - // Specify the amount of iterations that should be run by this benchmark. - // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark. - // - // NOTE: This function should only be used when *exact* iteration control is - // needed and never to control or limit how long a benchmark runs, where - // `--benchmark_min_time=N` or `MinTime(...)` should be used instead. - Benchmark* Iterations(size_t n); - - // Specify the amount of times to repeat this benchmark. This option overrides - // the `benchmark_repetitions` flag. - // REQUIRES: `n > 0` - Benchmark* Repetitions(int n); - - // Specify if each repetition of the benchmark should be reported separately - // or if only the final statistics should be reported. If the benchmark - // is not repeated then the single result is always reported. - Benchmark* ReportAggregatesOnly(bool value = true); - - // If a particular benchmark is I/O bound, runs multiple threads internally or - // if for some reason CPU timings are not representative, call this method. If - // called, the elapsed time will be used to control how many iterations are - // run, and in the printing of items/second or MB/seconds values. If not - // called, the cpu time used by the benchmark will be used. - Benchmark* UseRealTime(); - - // If a benchmark must measure time manually (e.g. if GPU execution time is - // being - // measured), call this method. If called, each benchmark iteration should - // call - // SetIterationTime(seconds) to report the measured time, which will be used - // to control how many iterations are run, and in the printing of items/second - // or MB/second values. - Benchmark* UseManualTime(); - - // Set the asymptotic computational complexity for the benchmark. If called - // the asymptotic computational complexity will be shown on the output. - Benchmark* Complexity(BigO complexity = benchmark::oAuto); - - // Set the asymptotic computational complexity for the benchmark. If called - // the asymptotic computational complexity will be shown on the output. - Benchmark* Complexity(BigOFunc* complexity); - - // Add this statistics to be computed over all the values of benchmark run - Benchmark* ComputeStatistics(std::string name, StatisticsFunc* statistics); - - // Support for running multiple copies of the same benchmark concurrently - // in multiple threads. This may be useful when measuring the scaling - // of some piece of code. - - // Run one instance of this benchmark concurrently in t threads. - Benchmark* Threads(int t); - - // Pick a set of values T from [min_threads,max_threads]. - // min_threads and max_threads are always included in T. Run this - // benchmark once for each value in T. The benchmark run for a - // particular value t consists of t threads running the benchmark - // function concurrently. For example, consider: - // BENCHMARK(Foo)->ThreadRange(1,16); - // This will run the following benchmarks: - // Foo in 1 thread - // Foo in 2 threads - // Foo in 4 threads - // Foo in 8 threads - // Foo in 16 threads - Benchmark* ThreadRange(int min_threads, int max_threads); - - // For each value n in the range, run this benchmark once using n threads. - // min_threads and max_threads are always included in the range. - // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts - // a benchmark with 1, 4, 7 and 8 threads. - Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1); - - // Equivalent to ThreadRange(NumCPUs(), NumCPUs()) - Benchmark* ThreadPerCpu(); - - virtual void Run(State& state) = 0; - - // Used inside the benchmark implementation - struct Instance; - - protected: - explicit Benchmark(const char* name); - Benchmark(Benchmark const&); - void SetName(const char* name); - - int ArgsCnt() const; - - private: - friend class BenchmarkFamilies; - - std::string name_; - ReportMode report_mode_; - std::vector arg_names_; // Args for all benchmark runs - std::vector > args_; // Args for all benchmark runs - TimeUnit time_unit_; - int range_multiplier_; - double min_time_; - size_t iterations_; - int repetitions_; - bool use_real_time_; - bool use_manual_time_; - BigO complexity_; - BigOFunc* complexity_lambda_; - std::vector statistics_; - std::vector thread_counts_; - - Benchmark& operator=(Benchmark const&); -}; - -} // namespace internal - -// Create and register a benchmark with the specified 'name' that invokes -// the specified functor 'fn'. -// -// RETURNS: A pointer to the registered benchmark. -internal::Benchmark* RegisterBenchmark(const char* name, - internal::Function* fn); - -#if defined(BENCHMARK_HAS_CXX11) -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn); -#endif - -// Remove all registered benchmarks. All pointers to previously registered -// benchmarks are invalidated. -void ClearRegisteredBenchmarks(); - -namespace internal { -// The class used to hold all Benchmarks created from static function. -// (ie those created using the BENCHMARK(...) macros. -class FunctionBenchmark : public Benchmark { - public: - FunctionBenchmark(const char* name, Function* func) - : Benchmark(name), func_(func) {} - - void Run(State& st) override; - - private: - Function* func_; -}; - -#ifdef BENCHMARK_HAS_CXX11 -template -class LambdaBenchmark : public Benchmark { - public: - void Run(State& st) override { lambda_(st); } - - private: - template - LambdaBenchmark(const char* name, OLambda&& lam) - : Benchmark(name), lambda_(std::forward(lam)) {} - - LambdaBenchmark(LambdaBenchmark const&) = delete; - - private: - template - friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&); - - Lambda lambda_; -}; -#endif - -} // namespace internal - -inline internal::Benchmark* RegisterBenchmark(const char* name, - internal::Function* fn) { - return internal::RegisterBenchmarkInternal( - ::new internal::FunctionBenchmark(name, fn)); -} - -#ifdef BENCHMARK_HAS_CXX11 -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) { - using BenchType = internal::LambdaBenchmark::type>; - return internal::RegisterBenchmarkInternal( - ::new BenchType(name, std::forward(fn))); -} -#endif - -#if defined(BENCHMARK_HAS_CXX11) && \ - (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409) -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn, - Args&&... args) { - return benchmark::RegisterBenchmark( - name, [=](benchmark::State& st) { fn(st, args...); }); -} -#else -#define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK -#endif - -// The base class for all fixture tests. -class Fixture : public internal::Benchmark { - public: - Fixture() : internal::Benchmark("") {} - - void Run(State& st) override { - this->SetUp(st); - this->BenchmarkCase(st); - this->TearDown(st); - } - - // These will be deprecated ... - virtual void SetUp(const State&) {} - virtual void TearDown(const State&) {} - // ... In favor of these. - virtual void SetUp(State& st) { SetUp(const_cast(st)); } - virtual void TearDown(State& st) { TearDown(const_cast(st)); } - - protected: - virtual void BenchmarkCase(State&) = 0; -}; - -} // namespace benchmark - -// ------------------------------------------------------ -// Macro to register benchmarks - -// Check that __COUNTER__ is defined and that __COUNTER__ increases by 1 -// every time it is expanded. X + 1 == X + 0 is used in case X is defined to be -// empty. If X is empty the expression becomes (+1 == +0). -#if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0) -#define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__ -#else -#define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__ -#endif - -// Helpers for generating unique variable names -#define BENCHMARK_PRIVATE_NAME(n) \ - BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n) -#define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c) -#define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c - -#define BENCHMARK_PRIVATE_DECLARE(n) \ - static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \ - BENCHMARK_UNUSED - -#define BENCHMARK(n) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n, n))) - -// Old-style macros -#define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a)) -#define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)}) -#define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t)) -#define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi)) -#define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \ - BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}}) - -#ifdef BENCHMARK_HAS_CXX11 - -// Register a benchmark which invokes the function specified by `func` -// with the additional arguments specified by `...`. -// -// For example: -// -// template ` -// void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { -// [...] -//} -// /* Registers a benchmark named "BM_takes_args/int_string_test` */ -// BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); -#define BENCHMARK_CAPTURE(func, test_case_name, ...) \ - BENCHMARK_PRIVATE_DECLARE(func) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark( \ - #func "/" #test_case_name, \ - [](::benchmark::State& st) { func(st, __VA_ARGS__); }))) - -#endif // BENCHMARK_HAS_CXX11 - -// This will register a benchmark for a templatized function. For example: -// -// template -// void BM_Foo(int iters); -// -// BENCHMARK_TEMPLATE(BM_Foo, 1); -// -// will register BM_Foo<1> as a benchmark. -#define BENCHMARK_TEMPLATE1(n, a) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n))) - -#define BENCHMARK_TEMPLATE2(n, a, b) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n "<" #a "," #b ">", \ - n))) - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE(n, ...) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark( \ - #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>))) -#else -#define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a) -#endif - -#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass "/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass"<" #a ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass"<" #a "," #b ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...) \ - class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass<__VA_ARGS__>() { \ - this->SetName(#BaseClass"<" #__VA_ARGS__ ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; -#else -#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(n, a) -#endif - -#define BENCHMARK_DEFINE_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b) \ - BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...) \ - BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase -#else -#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) -#endif - -#define BENCHMARK_REGISTER_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark) - -#define BENCHMARK_PRIVATE_REGISTER_F(TestName) \ - BENCHMARK_PRIVATE_DECLARE(TestName) = \ - (::benchmark::internal::RegisterBenchmarkInternal(new TestName())) - -// This macro will define and register a benchmark within a fixture class. -#define BENCHMARK_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b) \ - BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...) \ - BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase -#else -#define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) -#endif - -// Helper macro to create a main routine in a test that runs the benchmarks -#define BENCHMARK_MAIN() \ - int main(int argc, char** argv) { \ - ::benchmark::Initialize(&argc, argv); \ - if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \ - ::benchmark::RunSpecifiedBenchmarks(); \ - } \ - int main(int, char**) - - -// ------------------------------------------------------ -// Benchmark Reporters - -namespace benchmark { - -struct CPUInfo { - struct CacheInfo { - std::string type; - int level; - int size; - int num_sharing; - }; - - int num_cpus; - double cycles_per_second; - std::vector caches; - bool scaling_enabled; - - static const CPUInfo& Get(); - - private: - CPUInfo(); - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(CPUInfo); -}; - -// Interface for custom benchmark result printers. -// By default, benchmark reports are printed to stdout. However an application -// can control the destination of the reports by calling -// RunSpecifiedBenchmarks and passing it a custom reporter object. -// The reporter object must implement the following interface. -class BenchmarkReporter { - public: - struct Context { - CPUInfo const& cpu_info; - // The number of chars in the longest benchmark name. - size_t name_field_width; - static const char *executable_name; - Context(); - }; - - struct Run { - Run() - : error_occurred(false), - iterations(1), - time_unit(kNanosecond), - real_accumulated_time(0), - cpu_accumulated_time(0), - bytes_per_second(0), - items_per_second(0), - max_heapbytes_used(0), - complexity(oNone), - complexity_lambda(), - complexity_n(0), - report_big_o(false), - report_rms(false), - counters() {} - - std::string benchmark_name; - std::string report_label; // Empty if not set by benchmark. - bool error_occurred; - std::string error_message; - - int64_t iterations; - TimeUnit time_unit; - double real_accumulated_time; - double cpu_accumulated_time; - - // Return a value representing the real time per iteration in the unit - // specified by 'time_unit'. - // NOTE: If 'iterations' is zero the returned value represents the - // accumulated time. - double GetAdjustedRealTime() const; - - // Return a value representing the cpu time per iteration in the unit - // specified by 'time_unit'. - // NOTE: If 'iterations' is zero the returned value represents the - // accumulated time. - double GetAdjustedCPUTime() const; - - // Zero if not set by benchmark. - double bytes_per_second; - double items_per_second; - - // This is set to 0.0 if memory tracing is not enabled. - double max_heapbytes_used; - - // Keep track of arguments to compute asymptotic complexity - BigO complexity; - BigOFunc* complexity_lambda; - int64_t complexity_n; - - // what statistics to compute from the measurements - const std::vector* statistics; - - // Inform print function whether the current run is a complexity report - bool report_big_o; - bool report_rms; - - UserCounters counters; - }; - - // Construct a BenchmarkReporter with the output stream set to 'std::cout' - // and the error stream set to 'std::cerr' - BenchmarkReporter(); - - // Called once for every suite of benchmarks run. - // The parameter "context" contains information that the - // reporter may wish to use when generating its report, for example the - // platform under which the benchmarks are running. The benchmark run is - // never started if this function returns false, allowing the reporter - // to skip runs based on the context information. - virtual bool ReportContext(const Context& context) = 0; - - // Called once for each group of benchmark runs, gives information about - // cpu-time and heap memory usage during the benchmark run. If the group - // of runs contained more than two entries then 'report' contains additional - // elements representing the mean and standard deviation of those runs. - // Additionally if this group of runs was the last in a family of benchmarks - // 'reports' contains additional entries representing the asymptotic - // complexity and RMS of that benchmark family. - virtual void ReportRuns(const std::vector& report) = 0; - - // Called once and only once after ever group of benchmarks is run and - // reported. - virtual void Finalize() {} - - // REQUIRES: The object referenced by 'out' is valid for the lifetime - // of the reporter. - void SetOutputStream(std::ostream* out) { - assert(out); - output_stream_ = out; - } - - // REQUIRES: The object referenced by 'err' is valid for the lifetime - // of the reporter. - void SetErrorStream(std::ostream* err) { - assert(err); - error_stream_ = err; - } - - std::ostream& GetOutputStream() const { return *output_stream_; } - - std::ostream& GetErrorStream() const { return *error_stream_; } - - virtual ~BenchmarkReporter(); - - // Write a human readable string to 'out' representing the specified - // 'context'. - // REQUIRES: 'out' is non-null. - static void PrintBasicContext(std::ostream* out, Context const& context); - - private: - std::ostream* output_stream_; - std::ostream* error_stream_; -}; - -// Simple reporter that outputs benchmark data to the console. This is the -// default reporter used by RunSpecifiedBenchmarks(). -class ConsoleReporter : public BenchmarkReporter { -public: - enum OutputOptions { - OO_None = 0, - OO_Color = 1, - OO_Tabular = 2, - OO_ColorTabular = OO_Color|OO_Tabular, - OO_Defaults = OO_ColorTabular - }; - explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults) - : output_options_(opts_), name_field_width_(0), - prev_counters_(), printed_header_(false) {} - - bool ReportContext(const Context& context) override; - void ReportRuns(const std::vector& reports) override; - - protected: - virtual void PrintRunData(const Run& report); - virtual void PrintHeader(const Run& report); - - OutputOptions output_options_; - size_t name_field_width_; - UserCounters prev_counters_; - bool printed_header_; -}; - -class JSONReporter : public BenchmarkReporter { - public: - JSONReporter() : first_report_(true) {} - bool ReportContext(const Context& context) override; - void ReportRuns(const std::vector& reports) override; - void Finalize() override; - - private: - void PrintRunData(const Run& report); - - bool first_report_; -}; - -class CSVReporter : public BenchmarkReporter { - public: - CSVReporter() : printed_header_(false) {} - bool ReportContext(const Context& context) override; - void ReportRuns(const std::vector& reports) override; - - private: - void PrintRunData(const Run& report); - - bool printed_header_; - std::set< std::string > user_counter_names_; -}; - -inline const char* GetTimeUnitString(TimeUnit unit) { - switch (unit) { - case kMillisecond: - return "ms"; - case kMicrosecond: - return "us"; - case kNanosecond: - return "ns"; - } - BENCHMARK_UNREACHABLE(); -} - -inline double GetTimeUnitMultiplier(TimeUnit unit) { - switch (unit) { - case kMillisecond: - return 1e3; - case kMicrosecond: - return 1e6; - case kNanosecond: - return 1e9; - } - BENCHMARK_UNREACHABLE(); -} - -} // namespace benchmark - -#endif // BENCHMARK_BENCHMARK_H_ diff --git a/interpreter/llvm/src/utils/benchmark/mingw.py b/interpreter/llvm/src/utils/benchmark/mingw.py deleted file mode 100644 index 0b69692ca2a40..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/mingw.py +++ /dev/null @@ -1,320 +0,0 @@ -#!/usr/bin/env python -# encoding: utf-8 - -import argparse -import errno -import logging -import os -import platform -import re -import sys -import subprocess -import tempfile - -try: - import winreg -except ImportError: - import _winreg as winreg -try: - import urllib.request as request -except ImportError: - import urllib as request -try: - import urllib.parse as parse -except ImportError: - import urlparse as parse - -class EmptyLogger(object): - ''' - Provides an implementation that performs no logging - ''' - def debug(self, *k, **kw): - pass - def info(self, *k, **kw): - pass - def warn(self, *k, **kw): - pass - def error(self, *k, **kw): - pass - def critical(self, *k, **kw): - pass - def setLevel(self, *k, **kw): - pass - -urls = ( - 'http://downloads.sourceforge.net/project/mingw-w64/Toolchains%20' - 'targetting%20Win32/Personal%20Builds/mingw-builds/installer/' - 'repository.txt', - 'http://downloads.sourceforge.net/project/mingwbuilds/host-windows/' - 'repository.txt' -) -''' -A list of mingw-build repositories -''' - -def repository(urls = urls, log = EmptyLogger()): - ''' - Downloads and parse mingw-build repository files and parses them - ''' - log.info('getting mingw-builds repository') - versions = {} - re_sourceforge = re.compile(r'http://sourceforge.net/projects/([^/]+)/files') - re_sub = r'http://downloads.sourceforge.net/project/\1' - for url in urls: - log.debug(' - requesting: %s', url) - socket = request.urlopen(url) - repo = socket.read() - if not isinstance(repo, str): - repo = repo.decode(); - socket.close() - for entry in repo.split('\n')[:-1]: - value = entry.split('|') - version = tuple([int(n) for n in value[0].strip().split('.')]) - version = versions.setdefault(version, {}) - arch = value[1].strip() - if arch == 'x32': - arch = 'i686' - elif arch == 'x64': - arch = 'x86_64' - arch = version.setdefault(arch, {}) - threading = arch.setdefault(value[2].strip(), {}) - exceptions = threading.setdefault(value[3].strip(), {}) - revision = exceptions.setdefault(int(value[4].strip()[3:]), - re_sourceforge.sub(re_sub, value[5].strip())) - return versions - -def find_in_path(file, path=None): - ''' - Attempts to find an executable in the path - ''' - if platform.system() == 'Windows': - file += '.exe' - if path is None: - path = os.environ.get('PATH', '') - if type(path) is type(''): - path = path.split(os.pathsep) - return list(filter(os.path.exists, - map(lambda dir, file=file: os.path.join(dir, file), path))) - -def find_7zip(log = EmptyLogger()): - ''' - Attempts to find 7zip for unpacking the mingw-build archives - ''' - log.info('finding 7zip') - path = find_in_path('7z') - if not path: - key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip') - path, _ = winreg.QueryValueEx(key, 'Path') - path = [os.path.join(path, '7z.exe')] - log.debug('found \'%s\'', path[0]) - return path[0] - -find_7zip() - -def unpack(archive, location, log = EmptyLogger()): - ''' - Unpacks a mingw-builds archive - ''' - sevenzip = find_7zip(log) - log.info('unpacking %s', os.path.basename(archive)) - cmd = [sevenzip, 'x', archive, '-o' + location, '-y'] - log.debug(' - %r', cmd) - with open(os.devnull, 'w') as devnull: - subprocess.check_call(cmd, stdout = devnull) - -def download(url, location, log = EmptyLogger()): - ''' - Downloads and unpacks a mingw-builds archive - ''' - log.info('downloading MinGW') - log.debug(' - url: %s', url) - log.debug(' - location: %s', location) - - re_content = re.compile(r'attachment;[ \t]*filename=(")?([^"]*)(")?[\r\n]*') - - stream = request.urlopen(url) - try: - content = stream.getheader('Content-Disposition') or '' - except AttributeError: - content = stream.headers.getheader('Content-Disposition') or '' - matches = re_content.match(content) - if matches: - filename = matches.group(2) - else: - parsed = parse.urlparse(stream.geturl()) - filename = os.path.basename(parsed.path) - - try: - os.makedirs(location) - except OSError as e: - if e.errno == errno.EEXIST and os.path.isdir(location): - pass - else: - raise - - archive = os.path.join(location, filename) - with open(archive, 'wb') as out: - while True: - buf = stream.read(1024) - if not buf: - break - out.write(buf) - unpack(archive, location, log = log) - os.remove(archive) - - possible = os.path.join(location, 'mingw64') - if not os.path.exists(possible): - possible = os.path.join(location, 'mingw32') - if not os.path.exists(possible): - raise ValueError('Failed to find unpacked MinGW: ' + possible) - return possible - -def root(location = None, arch = None, version = None, threading = None, - exceptions = None, revision = None, log = EmptyLogger()): - ''' - Returns the root folder of a specific version of the mingw-builds variant - of gcc. Will download the compiler if needed - ''' - - # Get the repository if we don't have all the information - if not (arch and version and threading and exceptions and revision): - versions = repository(log = log) - - # Determine some defaults - version = version or max(versions.keys()) - if not arch: - arch = platform.machine().lower() - if arch == 'x86': - arch = 'i686' - elif arch == 'amd64': - arch = 'x86_64' - if not threading: - keys = versions[version][arch].keys() - if 'posix' in keys: - threading = 'posix' - elif 'win32' in keys: - threading = 'win32' - else: - threading = keys[0] - if not exceptions: - keys = versions[version][arch][threading].keys() - if 'seh' in keys: - exceptions = 'seh' - elif 'sjlj' in keys: - exceptions = 'sjlj' - else: - exceptions = keys[0] - if revision == None: - revision = max(versions[version][arch][threading][exceptions].keys()) - if not location: - location = os.path.join(tempfile.gettempdir(), 'mingw-builds') - - # Get the download url - url = versions[version][arch][threading][exceptions][revision] - - # Tell the user whatzzup - log.info('finding MinGW %s', '.'.join(str(v) for v in version)) - log.debug(' - arch: %s', arch) - log.debug(' - threading: %s', threading) - log.debug(' - exceptions: %s', exceptions) - log.debug(' - revision: %s', revision) - log.debug(' - url: %s', url) - - # Store each specific revision differently - slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}' - slug = slug.format( - version = '.'.join(str(v) for v in version), - arch = arch, - threading = threading, - exceptions = exceptions, - revision = revision - ) - if arch == 'x86_64': - root_dir = os.path.join(location, slug, 'mingw64') - elif arch == 'i686': - root_dir = os.path.join(location, slug, 'mingw32') - else: - raise ValueError('Unknown MinGW arch: ' + arch) - - # Download if needed - if not os.path.exists(root_dir): - downloaded = download(url, os.path.join(location, slug), log = log) - if downloaded != root_dir: - raise ValueError('The location of mingw did not match\n%s\n%s' - % (downloaded, root_dir)) - - return root_dir - -def str2ver(string): - ''' - Converts a version string into a tuple - ''' - try: - version = tuple(int(v) for v in string.split('.')) - if len(version) is not 3: - raise ValueError() - except ValueError: - raise argparse.ArgumentTypeError( - 'please provide a three digit version string') - return version - -def main(): - ''' - Invoked when the script is run directly by the python interpreter - ''' - parser = argparse.ArgumentParser( - description = 'Downloads a specific version of MinGW', - formatter_class = argparse.ArgumentDefaultsHelpFormatter - ) - parser.add_argument('--location', - help = 'the location to download the compiler to', - default = os.path.join(tempfile.gettempdir(), 'mingw-builds')) - parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'], - help = 'the target MinGW architecture string') - parser.add_argument('--version', type = str2ver, - help = 'the version of GCC to download') - parser.add_argument('--threading', choices = ['posix', 'win32'], - help = 'the threading type of the compiler') - parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'], - help = 'the method to throw exceptions') - parser.add_argument('--revision', type=int, - help = 'the revision of the MinGW release') - group = parser.add_mutually_exclusive_group() - group.add_argument('-v', '--verbose', action='store_true', - help='increase the script output verbosity') - group.add_argument('-q', '--quiet', action='store_true', - help='only print errors and warning') - args = parser.parse_args() - - # Create the logger - logger = logging.getLogger('mingw') - handler = logging.StreamHandler() - formatter = logging.Formatter('%(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.INFO) - if args.quiet: - logger.setLevel(logging.WARN) - if args.verbose: - logger.setLevel(logging.DEBUG) - - # Get MinGW - root_dir = root(location = args.location, arch = args.arch, - version = args.version, threading = args.threading, - exceptions = args.exceptions, revision = args.revision, - log = logger) - - sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin')) - -if __name__ == '__main__': - try: - main() - except IOError as e: - sys.stderr.write('IO error: %s\n' % e) - sys.exit(1) - except OSError as e: - sys.stderr.write('OS error: %s\n' % e) - sys.exit(1) - except KeyboardInterrupt as e: - sys.stderr.write('Killed\n') - sys.exit(1) diff --git a/interpreter/llvm/src/utils/benchmark/releasing.md b/interpreter/llvm/src/utils/benchmark/releasing.md deleted file mode 100644 index f0cd7010e3a90..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/releasing.md +++ /dev/null @@ -1,16 +0,0 @@ -# How to release - -* Make sure you're on master and synced to HEAD -* Ensure the project builds and tests run (sanity check only, obviously) - * `parallel -j0 exec ::: test/*_test` can help ensure everything at least - passes -* Prepare release notes - * `git log $(git describe --abbrev=0 --tags)..HEAD` gives you the list of - commits between the last annotated tag and HEAD - * Pick the most interesting. -* Create a release through github's interface - * Note this will create a lightweight tag. - * Update this to an annotated tag: - * `git pull --tags` - * `git tag -a -f ` - * `git push --force origin` diff --git a/interpreter/llvm/src/utils/benchmark/src/CMakeLists.txt b/interpreter/llvm/src/utils/benchmark/src/CMakeLists.txt deleted file mode 100644 index 0abfe3cfd53c2..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/CMakeLists.txt +++ /dev/null @@ -1,110 +0,0 @@ -# Allow the source files to find headers in src/ -include_directories(${PROJECT_SOURCE_DIR}/src) - -if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) - list(APPEND CMAKE_SHARED_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) - list(APPEND CMAKE_MODULE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) -endif() - -file(GLOB - SOURCE_FILES - *.cc - ${PROJECT_SOURCE_DIR}/include/benchmark/*.h - ${CMAKE_CURRENT_SOURCE_DIR}/*.h) -file(GLOB BENCHMARK_MAIN "benchmark_main.cc") -foreach(item ${BENCHMARK_MAIN}) - list(REMOVE_ITEM SOURCE_FILES "${item}") -endforeach() - -add_library(benchmark ${SOURCE_FILES}) -set_target_properties(benchmark PROPERTIES - OUTPUT_NAME "benchmark" - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} - FOLDER "Utils" -) -target_include_directories(benchmark PUBLIC - $ - ) - -# Link threads. -target_link_libraries(benchmark ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) -find_library(LIBRT rt) -if(LIBRT) - target_link_libraries(benchmark ${LIBRT}) -endif() - -# We need extra libraries on Windows -if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - target_link_libraries(benchmark shlwapi) -endif() - -# We need extra libraries on Solaris -if(${CMAKE_SYSTEM_NAME} MATCHES "SunOS") - target_link_libraries(benchmark kstat) -endif() - -# Benchmark main library -add_library(benchmark_main "benchmark_main.cc") -set_target_properties(benchmark_main PROPERTIES - OUTPUT_NAME "benchmark_main" - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} - FOLDER "Utils" -) -target_include_directories(benchmark PUBLIC - $ - ) -target_link_libraries(benchmark_main benchmark) - -set(include_install_dir "include") -set(lib_install_dir "lib/") -set(bin_install_dir "bin/") -set(config_install_dir "lib/cmake/${PROJECT_NAME}") -set(pkgconfig_install_dir "lib/pkgconfig") - -set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") - -set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") -set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") -set(pkg_config "${generated_dir}/${PROJECT_NAME}.pc") -set(targets_export_name "${PROJECT_NAME}Targets") - -set(namespace "${PROJECT_NAME}::") - -include(CMakePackageConfigHelpers) -write_basic_package_version_file( - "${version_config}" VERSION ${GIT_VERSION} COMPATIBILITY SameMajorVersion -) - -configure_file("${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in" "${project_config}" @ONLY) -configure_file("${PROJECT_SOURCE_DIR}/cmake/benchmark.pc.in" "${pkg_config}" @ONLY) - -if (BENCHMARK_ENABLE_INSTALL) - # Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable) - install( - TARGETS benchmark benchmark_main - EXPORT ${targets_export_name} - ARCHIVE DESTINATION ${lib_install_dir} - LIBRARY DESTINATION ${lib_install_dir} - RUNTIME DESTINATION ${bin_install_dir} - INCLUDES DESTINATION ${include_install_dir}) - - install( - DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark" - DESTINATION ${include_install_dir} - FILES_MATCHING PATTERN "*.*h") - - install( - FILES "${project_config}" "${version_config}" - DESTINATION "${config_install_dir}") - - install( - FILES "${pkg_config}" - DESTINATION "${pkgconfig_install_dir}") - - install( - EXPORT "${targets_export_name}" - NAMESPACE "${namespace}" - DESTINATION "${config_install_dir}") -endif() diff --git a/interpreter/llvm/src/utils/benchmark/src/arraysize.h b/interpreter/llvm/src/utils/benchmark/src/arraysize.h deleted file mode 100644 index 51a50f2dff271..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/arraysize.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef BENCHMARK_ARRAYSIZE_H_ -#define BENCHMARK_ARRAYSIZE_H_ - -#include "internal_macros.h" - -namespace benchmark { -namespace internal { -// The arraysize(arr) macro returns the # of elements in an array arr. -// The expression is a compile-time constant, and therefore can be -// used in defining new arrays, for example. If you use arraysize on -// a pointer by mistake, you will get a compile-time error. -// - -// This template function declaration is used in defining arraysize. -// Note that the function doesn't need an implementation, as we only -// use its type. -template -char (&ArraySizeHelper(T (&array)[N]))[N]; - -// That gcc wants both of these prototypes seems mysterious. VC, for -// its part, can't decide which to use (another mystery). Matching of -// template overloads: the final frontier. -#ifndef COMPILER_MSVC -template -char (&ArraySizeHelper(const T (&array)[N]))[N]; -#endif - -#define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array))) - -} // end namespace internal -} // end namespace benchmark - -#endif // BENCHMARK_ARRAYSIZE_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/benchmark.cc b/interpreter/llvm/src/utils/benchmark/src/benchmark.cc deleted file mode 100644 index 82b15ac7090cf..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/benchmark.cc +++ /dev/null @@ -1,630 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "internal_macros.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "counter.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "thread_manager.h" -#include "thread_timer.h" - -DEFINE_bool(benchmark_list_tests, false, - "Print a list of benchmarks. This option overrides all other " - "options."); - -DEFINE_string(benchmark_filter, ".", - "A regular expression that specifies the set of benchmarks " - "to execute. If this flag is empty, no benchmarks are run. " - "If this flag is the string \"all\", all benchmarks linked " - "into the process are run."); - -DEFINE_double(benchmark_min_time, 0.5, - "Minimum number of seconds we should run benchmark before " - "results are considered significant. For cpu-time based " - "tests, this is the lower bound on the total cpu time " - "used by all threads that make up the test. For real-time " - "based tests, this is the lower bound on the elapsed time " - "of the benchmark execution, regardless of number of " - "threads."); - -DEFINE_int32(benchmark_repetitions, 1, - "The number of runs of each benchmark. If greater than 1, the " - "mean and standard deviation of the runs will be reported."); - -DEFINE_bool(benchmark_report_aggregates_only, false, - "Report the result of each benchmark repetitions. When 'true' is " - "specified only the mean, standard deviation, and other statistics " - "are reported for repeated benchmarks."); - -DEFINE_string(benchmark_format, "console", - "The format to use for console output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out_format, "json", - "The format to use for file output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out, "", "The file to write additional output to"); - -DEFINE_string(benchmark_color, "auto", - "Whether to use colors in the output. Valid values: " - "'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use " - "colors if the output is being sent to a terminal and the TERM " - "environment variable is set to a terminal type that supports " - "colors."); - -DEFINE_bool(benchmark_counters_tabular, false, - "Whether to use tabular format when printing user counters to " - "the console. Valid values: 'true'/'yes'/1, 'false'/'no'/0." - "Defaults to false."); - -DEFINE_int32(v, 0, "The level of verbose logging to output"); - -namespace benchmark { - -namespace { -static const size_t kMaxIterations = 1000000000; -} // end namespace - -namespace internal { - -void UseCharPointer(char const volatile*) {} - -namespace { - -BenchmarkReporter::Run CreateRunReport( - const benchmark::internal::Benchmark::Instance& b, - const internal::ThreadManager::Result& results, - double seconds) { - // Create report about this benchmark run. - BenchmarkReporter::Run report; - - report.benchmark_name = b.name; - report.error_occurred = results.has_error_; - report.error_message = results.error_message_; - report.report_label = results.report_label_; - // This is the total iterations across all threads. - report.iterations = results.iterations; - report.time_unit = b.time_unit; - - if (!report.error_occurred) { - double bytes_per_second = 0; - if (results.bytes_processed > 0 && seconds > 0.0) { - bytes_per_second = (results.bytes_processed / seconds); - } - double items_per_second = 0; - if (results.items_processed > 0 && seconds > 0.0) { - items_per_second = (results.items_processed / seconds); - } - - if (b.use_manual_time) { - report.real_accumulated_time = results.manual_time_used; - } else { - report.real_accumulated_time = results.real_time_used; - } - report.cpu_accumulated_time = results.cpu_time_used; - report.bytes_per_second = bytes_per_second; - report.items_per_second = items_per_second; - report.complexity_n = results.complexity_n; - report.complexity = b.complexity; - report.complexity_lambda = b.complexity_lambda; - report.statistics = b.statistics; - report.counters = results.counters; - internal::Finish(&report.counters, seconds, b.threads); - } - return report; -} - -// Execute one thread of benchmark b for the specified number of iterations. -// Adds the stats collected for the thread into *total. -void RunInThread(const benchmark::internal::Benchmark::Instance* b, - size_t iters, int thread_id, - internal::ThreadManager* manager) { - internal::ThreadTimer timer; - State st(iters, b->arg, thread_id, b->threads, &timer, manager); - b->benchmark->Run(st); - CHECK(st.iterations() >= st.max_iterations) - << "Benchmark returned before State::KeepRunning() returned false!"; - { - MutexLock l(manager->GetBenchmarkMutex()); - internal::ThreadManager::Result& results = manager->results; - results.iterations += st.iterations(); - results.cpu_time_used += timer.cpu_time_used(); - results.real_time_used += timer.real_time_used(); - results.manual_time_used += timer.manual_time_used(); - results.bytes_processed += st.bytes_processed(); - results.items_processed += st.items_processed(); - results.complexity_n += st.complexity_length_n(); - internal::Increment(&results.counters, st.counters); - } - manager->NotifyThreadComplete(); -} - -std::vector RunBenchmark( - const benchmark::internal::Benchmark::Instance& b, - std::vector* complexity_reports) { - std::vector reports; // return value - - const bool has_explicit_iteration_count = b.iterations != 0; - size_t iters = has_explicit_iteration_count ? b.iterations : 1; - std::unique_ptr manager; - std::vector pool(b.threads - 1); - const int repeats = - b.repetitions != 0 ? b.repetitions : FLAGS_benchmark_repetitions; - const bool report_aggregates_only = - repeats != 1 && - (b.report_mode == internal::RM_Unspecified - ? FLAGS_benchmark_report_aggregates_only - : b.report_mode == internal::RM_ReportAggregatesOnly); - for (int repetition_num = 0; repetition_num < repeats; repetition_num++) { - for (;;) { - // Try benchmark - VLOG(2) << "Running " << b.name << " for " << iters << "\n"; - - manager.reset(new internal::ThreadManager(b.threads)); - for (std::size_t ti = 0; ti < pool.size(); ++ti) { - pool[ti] = std::thread(&RunInThread, &b, iters, - static_cast(ti + 1), manager.get()); - } - RunInThread(&b, iters, 0, manager.get()); - manager->WaitForAllThreads(); - for (std::thread& thread : pool) thread.join(); - internal::ThreadManager::Result results; - { - MutexLock l(manager->GetBenchmarkMutex()); - results = manager->results; - } - manager.reset(); - // Adjust real/manual time stats since they were reported per thread. - results.real_time_used /= b.threads; - results.manual_time_used /= b.threads; - - VLOG(2) << "Ran in " << results.cpu_time_used << "/" - << results.real_time_used << "\n"; - - // Base decisions off of real time if requested by this benchmark. - double seconds = results.cpu_time_used; - if (b.use_manual_time) { - seconds = results.manual_time_used; - } else if (b.use_real_time) { - seconds = results.real_time_used; - } - - const double min_time = - !IsZero(b.min_time) ? b.min_time : FLAGS_benchmark_min_time; - - // Determine if this run should be reported; Either it has - // run for a sufficient amount of time or because an error was reported. - const bool should_report = repetition_num > 0 - || has_explicit_iteration_count // An exact iteration count was requested - || results.has_error_ - || iters >= kMaxIterations // No chance to try again, we hit the limit. - || seconds >= min_time // the elapsed time is large enough - // CPU time is specified but the elapsed real time greatly exceeds the - // minimum time. Note that user provided timers are except from this - // sanity check. - || ((results.real_time_used >= 5 * min_time) && !b.use_manual_time); - - if (should_report) { - BenchmarkReporter::Run report = CreateRunReport(b, results, seconds); - if (!report.error_occurred && b.complexity != oNone) - complexity_reports->push_back(report); - reports.push_back(report); - break; - } - - // See how much iterations should be increased by - // Note: Avoid division by zero with max(seconds, 1ns). - double multiplier = min_time * 1.4 / std::max(seconds, 1e-9); - // If our last run was at least 10% of FLAGS_benchmark_min_time then we - // use the multiplier directly. Otherwise we use at most 10 times - // expansion. - // NOTE: When the last run was at least 10% of the min time the max - // expansion should be 14x. - bool is_significant = (seconds / min_time) > 0.1; - multiplier = is_significant ? multiplier : std::min(10.0, multiplier); - if (multiplier <= 1.0) multiplier = 2.0; - double next_iters = std::max(multiplier * iters, iters + 1.0); - if (next_iters > kMaxIterations) { - next_iters = kMaxIterations; - } - VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n"; - iters = static_cast(next_iters + 0.5); - } - } - // Calculate additional statistics - auto stat_reports = ComputeStats(reports); - if ((b.complexity != oNone) && b.last_benchmark_instance) { - auto additional_run_stats = ComputeBigO(*complexity_reports); - stat_reports.insert(stat_reports.end(), additional_run_stats.begin(), - additional_run_stats.end()); - complexity_reports->clear(); - } - - if (report_aggregates_only) reports.clear(); - reports.insert(reports.end(), stat_reports.begin(), stat_reports.end()); - return reports; -} - -} // namespace -} // namespace internal - -State::State(size_t max_iters, const std::vector& ranges, int thread_i, - int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager) - : total_iterations_(0), - batch_leftover_(0), - max_iterations(max_iters), - started_(false), - finished_(false), - error_occurred_(false), - range_(ranges), - bytes_processed_(0), - items_processed_(0), - complexity_n_(0), - counters(), - thread_index(thread_i), - threads(n_threads), - timer_(timer), - manager_(manager) { - CHECK(max_iterations != 0) << "At least one iteration must be run"; - CHECK_LT(thread_index, threads) << "thread_index must be less than threads"; - - // Note: The use of offsetof below is technically undefined until C++17 - // because State is not a standard layout type. However, all compilers - // currently provide well-defined behavior as an extension (which is - // demonstrated since constexpr evaluation must diagnose all undefined - // behavior). However, GCC and Clang also warn about this use of offsetof, - // which must be suppressed. -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Winvalid-offsetof" -#endif - // Offset tests to ensure commonly accessed data is on the first cache line. - const int cache_line_size = 64; - static_assert(offsetof(State, error_occurred_) <= - (cache_line_size - sizeof(error_occurred_)), ""); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -} - -void State::PauseTiming() { - // Add in time accumulated so far - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StopTimer(); -} - -void State::ResumeTiming() { - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StartTimer(); -} - -void State::SkipWithError(const char* msg) { - CHECK(msg); - error_occurred_ = true; - { - MutexLock l(manager_->GetBenchmarkMutex()); - if (manager_->results.has_error_ == false) { - manager_->results.error_message_ = msg; - manager_->results.has_error_ = true; - } - } - total_iterations_ = 0; - if (timer_->running()) timer_->StopTimer(); -} - -void State::SetIterationTime(double seconds) { - timer_->SetIterationTime(seconds); -} - -void State::SetLabel(const char* label) { - MutexLock l(manager_->GetBenchmarkMutex()); - manager_->results.report_label_ = label; -} - -void State::StartKeepRunning() { - CHECK(!started_ && !finished_); - started_ = true; - total_iterations_ = error_occurred_ ? 0 : max_iterations; - manager_->StartStopBarrier(); - if (!error_occurred_) ResumeTiming(); -} - -void State::FinishKeepRunning() { - CHECK(started_ && (!finished_ || error_occurred_)); - if (!error_occurred_) { - PauseTiming(); - } - // Total iterations has now wrapped around past 0. Fix this. - total_iterations_ = 0; - finished_ = true; - manager_->StartStopBarrier(); -} - -namespace internal { -namespace { - -void RunBenchmarks(const std::vector& benchmarks, - BenchmarkReporter* console_reporter, - BenchmarkReporter* file_reporter) { - // Note the file_reporter can be null. - CHECK(console_reporter != nullptr); - - // Determine the width of the name field using a minimum width of 10. - bool has_repetitions = FLAGS_benchmark_repetitions > 1; - size_t name_field_width = 10; - size_t stat_field_width = 0; - for (const Benchmark::Instance& benchmark : benchmarks) { - name_field_width = - std::max(name_field_width, benchmark.name.size()); - has_repetitions |= benchmark.repetitions > 1; - - for(const auto& Stat : *benchmark.statistics) - stat_field_width = std::max(stat_field_width, Stat.name_.size()); - } - if (has_repetitions) name_field_width += 1 + stat_field_width; - - // Print header here - BenchmarkReporter::Context context; - context.name_field_width = name_field_width; - - // Keep track of running times of all instances of current benchmark - std::vector complexity_reports; - - // We flush streams after invoking reporter methods that write to them. This - // ensures users get timely updates even when streams are not line-buffered. - auto flushStreams = [](BenchmarkReporter* reporter) { - if (!reporter) return; - std::flush(reporter->GetOutputStream()); - std::flush(reporter->GetErrorStream()); - }; - - if (console_reporter->ReportContext(context) && - (!file_reporter || file_reporter->ReportContext(context))) { - flushStreams(console_reporter); - flushStreams(file_reporter); - for (const auto& benchmark : benchmarks) { - std::vector reports = - RunBenchmark(benchmark, &complexity_reports); - console_reporter->ReportRuns(reports); - if (file_reporter) file_reporter->ReportRuns(reports); - flushStreams(console_reporter); - flushStreams(file_reporter); - } - } - console_reporter->Finalize(); - if (file_reporter) file_reporter->Finalize(); - flushStreams(console_reporter); - flushStreams(file_reporter); -} - -std::unique_ptr CreateReporter( - std::string const& name, ConsoleReporter::OutputOptions output_opts) { - typedef std::unique_ptr PtrType; - if (name == "console") { - return PtrType(new ConsoleReporter(output_opts)); - } else if (name == "json") { - return PtrType(new JSONReporter); - } else if (name == "csv") { - return PtrType(new CSVReporter); - } else { - std::cerr << "Unexpected format: '" << name << "'\n"; - std::exit(1); - } -} - -} // end namespace - -bool IsZero(double n) { - return std::abs(n) < std::numeric_limits::epsilon(); -} - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { - int output_opts = ConsoleReporter::OO_Defaults; - if ((FLAGS_benchmark_color == "auto" && IsColorTerminal()) || - IsTruthyFlagValue(FLAGS_benchmark_color)) { - output_opts |= ConsoleReporter::OO_Color; - } else { - output_opts &= ~ConsoleReporter::OO_Color; - } - if(force_no_color) { - output_opts &= ~ConsoleReporter::OO_Color; - } - if(FLAGS_benchmark_counters_tabular) { - output_opts |= ConsoleReporter::OO_Tabular; - } else { - output_opts &= ~ConsoleReporter::OO_Tabular; - } - return static_cast< ConsoleReporter::OutputOptions >(output_opts); -} - -} // end namespace internal - -size_t RunSpecifiedBenchmarks() { - return RunSpecifiedBenchmarks(nullptr, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter) { - return RunSpecifiedBenchmarks(console_reporter, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter, - BenchmarkReporter* file_reporter) { - std::string spec = FLAGS_benchmark_filter; - if (spec.empty() || spec == "all") - spec = "."; // Regexp that matches all benchmarks - - // Setup the reporters - std::ofstream output_file; - std::unique_ptr default_console_reporter; - std::unique_ptr default_file_reporter; - if (!console_reporter) { - default_console_reporter = internal::CreateReporter( - FLAGS_benchmark_format, internal::GetOutputOptions()); - console_reporter = default_console_reporter.get(); - } - auto& Out = console_reporter->GetOutputStream(); - auto& Err = console_reporter->GetErrorStream(); - - std::string const& fname = FLAGS_benchmark_out; - if (fname.empty() && file_reporter) { - Err << "A custom file reporter was provided but " - "--benchmark_out= was not specified." - << std::endl; - std::exit(1); - } - if (!fname.empty()) { - output_file.open(fname); - if (!output_file.is_open()) { - Err << "invalid file name: '" << fname << std::endl; - std::exit(1); - } - if (!file_reporter) { - default_file_reporter = internal::CreateReporter( - FLAGS_benchmark_out_format, ConsoleReporter::OO_None); - file_reporter = default_file_reporter.get(); - } - file_reporter->SetOutputStream(&output_file); - file_reporter->SetErrorStream(&output_file); - } - - std::vector benchmarks; - if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; - - if (benchmarks.empty()) { - Err << "Failed to match any benchmarks against regex: " << spec << "\n"; - return 0; - } - - if (FLAGS_benchmark_list_tests) { - for (auto const& benchmark : benchmarks) Out << benchmark.name << "\n"; - } else { - internal::RunBenchmarks(benchmarks, console_reporter, file_reporter); - } - - return benchmarks.size(); -} - -namespace internal { - -void PrintUsageAndExit() { - fprintf(stdout, - "benchmark" - " [--benchmark_list_tests={true|false}]\n" - " [--benchmark_filter=]\n" - " [--benchmark_min_time=]\n" - " [--benchmark_repetitions=]\n" - " [--benchmark_report_aggregates_only={true|false}\n" - " [--benchmark_format=]\n" - " [--benchmark_out=]\n" - " [--benchmark_out_format=]\n" - " [--benchmark_color={auto|true|false}]\n" - " [--benchmark_counters_tabular={true|false}]\n" - " [--v=]\n"); - exit(0); -} - -void ParseCommandLineFlags(int* argc, char** argv) { - using namespace benchmark; - BenchmarkReporter::Context::executable_name = argv[0]; - for (int i = 1; i < *argc; ++i) { - if (ParseBoolFlag(argv[i], "benchmark_list_tests", - &FLAGS_benchmark_list_tests) || - ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || - ParseDoubleFlag(argv[i], "benchmark_min_time", - &FLAGS_benchmark_min_time) || - ParseInt32Flag(argv[i], "benchmark_repetitions", - &FLAGS_benchmark_repetitions) || - ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", - &FLAGS_benchmark_report_aggregates_only) || - ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || - ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || - ParseStringFlag(argv[i], "benchmark_out_format", - &FLAGS_benchmark_out_format) || - ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || - // "color_print" is the deprecated name for "benchmark_color". - // TODO: Remove this. - ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) || - ParseBoolFlag(argv[i], "benchmark_counters_tabular", - &FLAGS_benchmark_counters_tabular) || - ParseInt32Flag(argv[i], "v", &FLAGS_v)) { - for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; - - --(*argc); - --i; - } else if (IsFlag(argv[i], "help")) { - PrintUsageAndExit(); - } - } - for (auto const* flag : - {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) - if (*flag != "console" && *flag != "json" && *flag != "csv") { - PrintUsageAndExit(); - } - if (FLAGS_benchmark_color.empty()) { - PrintUsageAndExit(); - } -} - -int InitializeStreams() { - static std::ios_base::Init init; - return 0; -} - -} // end namespace internal - -void Initialize(int* argc, char** argv) { - internal::ParseCommandLineFlags(argc, argv); - internal::LogLevel() = FLAGS_v; -} - -bool ReportUnrecognizedArguments(int argc, char** argv) { - for (int i = 1; i < argc; ++i) { - fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], argv[i]); - } - return argc > 1; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/benchmark_api_internal.h b/interpreter/llvm/src/utils/benchmark/src/benchmark_api_internal.h deleted file mode 100644 index dd7a3ffe8cbb2..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/benchmark_api_internal.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef BENCHMARK_API_INTERNAL_H -#define BENCHMARK_API_INTERNAL_H - -#include "benchmark/benchmark.h" - -#include -#include -#include -#include -#include - -namespace benchmark { -namespace internal { - -// Information kept per benchmark we may want to run -struct Benchmark::Instance { - std::string name; - Benchmark* benchmark; - ReportMode report_mode; - std::vector arg; - TimeUnit time_unit; - int range_multiplier; - bool use_real_time; - bool use_manual_time; - BigO complexity; - BigOFunc* complexity_lambda; - UserCounters counters; - const std::vector* statistics; - bool last_benchmark_instance; - int repetitions; - double min_time; - size_t iterations; - int threads; // Number of concurrent threads to us -}; - -bool FindBenchmarksInternal(const std::string& re, - std::vector* benchmarks, - std::ostream* Err); - -bool IsZero(double n); - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); - -} // end namespace internal -} // end namespace benchmark - -#endif // BENCHMARK_API_INTERNAL_H diff --git a/interpreter/llvm/src/utils/benchmark/src/benchmark_main.cc b/interpreter/llvm/src/utils/benchmark/src/benchmark_main.cc deleted file mode 100644 index b3b247831496f..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/benchmark_main.cc +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/src/benchmark_register.cc b/interpreter/llvm/src/utils/benchmark/src/benchmark_register.cc deleted file mode 100644 index dc6f93568539b..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/benchmark_register.cc +++ /dev/null @@ -1,461 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark_register.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "check.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -namespace { -// For non-dense Range, intermediate values are powers of kRangeMultiplier. -static const int kRangeMultiplier = 8; -// The size of a benchmark family determines is the number of inputs to repeat -// the benchmark on. If this is "large" then warn the user during configuration. -static const size_t kMaxFamilySize = 100; -} // end namespace - -namespace internal { - -//=============================================================================// -// BenchmarkFamilies -//=============================================================================// - -// Class for managing registered benchmarks. Note that each registered -// benchmark identifies a family of related benchmarks to run. -class BenchmarkFamilies { - public: - static BenchmarkFamilies* GetInstance(); - - // Registers a benchmark family and returns the index assigned to it. - size_t AddBenchmark(std::unique_ptr family); - - // Clear all registered benchmark families. - void ClearBenchmarks(); - - // Extract the list of benchmark instances that match the specified - // regular expression. - bool FindBenchmarks(std::string re, - std::vector* benchmarks, - std::ostream* Err); - - private: - BenchmarkFamilies() {} - - std::vector> families_; - Mutex mutex_; -}; - -BenchmarkFamilies* BenchmarkFamilies::GetInstance() { - static BenchmarkFamilies instance; - return &instance; -} - -size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr family) { - MutexLock l(mutex_); - size_t index = families_.size(); - families_.push_back(std::move(family)); - return index; -} - -void BenchmarkFamilies::ClearBenchmarks() { - MutexLock l(mutex_); - families_.clear(); - families_.shrink_to_fit(); -} - -bool BenchmarkFamilies::FindBenchmarks( - std::string spec, std::vector* benchmarks, - std::ostream* ErrStream) { - CHECK(ErrStream); - auto& Err = *ErrStream; - // Make regular expression out of command-line flag - std::string error_msg; - Regex re; - bool isNegativeFilter = false; - if(spec[0] == '-') { - spec.replace(0, 1, ""); - isNegativeFilter = true; - } - if (!re.Init(spec, &error_msg)) { - Err << "Could not compile benchmark re: " << error_msg << std::endl; - return false; - } - - // Special list of thread counts to use when none are specified - const std::vector one_thread = {1}; - - MutexLock l(mutex_); - for (std::unique_ptr& family : families_) { - // Family was deleted or benchmark doesn't match - if (!family) continue; - - if (family->ArgsCnt() == -1) { - family->Args({}); - } - const std::vector* thread_counts = - (family->thread_counts_.empty() - ? &one_thread - : &static_cast&>(family->thread_counts_)); - const size_t family_size = family->args_.size() * thread_counts->size(); - // The benchmark will be run at least 'family_size' different inputs. - // If 'family_size' is very large warn the user. - if (family_size > kMaxFamilySize) { - Err << "The number of inputs is very large. " << family->name_ - << " will be repeated at least " << family_size << " times.\n"; - } - // reserve in the special case the regex ".", since we know the final - // family size. - if (spec == ".") benchmarks->reserve(family_size); - - for (auto const& args : family->args_) { - for (int num_threads : *thread_counts) { - Benchmark::Instance instance; - instance.name = family->name_; - instance.benchmark = family.get(); - instance.report_mode = family->report_mode_; - instance.arg = args; - instance.time_unit = family->time_unit_; - instance.range_multiplier = family->range_multiplier_; - instance.min_time = family->min_time_; - instance.iterations = family->iterations_; - instance.repetitions = family->repetitions_; - instance.use_real_time = family->use_real_time_; - instance.use_manual_time = family->use_manual_time_; - instance.complexity = family->complexity_; - instance.complexity_lambda = family->complexity_lambda_; - instance.statistics = &family->statistics_; - instance.threads = num_threads; - - // Add arguments to instance name - size_t arg_i = 0; - for (auto const& arg : args) { - instance.name += "/"; - - if (arg_i < family->arg_names_.size()) { - const auto& arg_name = family->arg_names_[arg_i]; - if (!arg_name.empty()) { - instance.name += - StrFormat("%s:", family->arg_names_[arg_i].c_str()); - } - } - - instance.name += StrFormat("%d", arg); - ++arg_i; - } - - if (!IsZero(family->min_time_)) - instance.name += StrFormat("/min_time:%0.3f", family->min_time_); - if (family->iterations_ != 0) - instance.name += StrFormat("/iterations:%d", family->iterations_); - if (family->repetitions_ != 0) - instance.name += StrFormat("/repeats:%d", family->repetitions_); - - if (family->use_manual_time_) { - instance.name += "/manual_time"; - } else if (family->use_real_time_) { - instance.name += "/real_time"; - } - - // Add the number of threads used to the name - if (!family->thread_counts_.empty()) { - instance.name += StrFormat("/threads:%d", instance.threads); - } - - if ((re.Match(instance.name) && !isNegativeFilter) || - (!re.Match(instance.name) && isNegativeFilter)) { - instance.last_benchmark_instance = (&args == &family->args_.back()); - benchmarks->push_back(std::move(instance)); - } - } - } - } - return true; -} - -Benchmark* RegisterBenchmarkInternal(Benchmark* bench) { - std::unique_ptr bench_ptr(bench); - BenchmarkFamilies* families = BenchmarkFamilies::GetInstance(); - families->AddBenchmark(std::move(bench_ptr)); - return bench; -} - -// FIXME: This function is a hack so that benchmark.cc can access -// `BenchmarkFamilies` -bool FindBenchmarksInternal(const std::string& re, - std::vector* benchmarks, - std::ostream* Err) { - return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err); -} - -//=============================================================================// -// Benchmark -//=============================================================================// - -Benchmark::Benchmark(const char* name) - : name_(name), - report_mode_(RM_Unspecified), - time_unit_(kNanosecond), - range_multiplier_(kRangeMultiplier), - min_time_(0), - iterations_(0), - repetitions_(0), - use_real_time_(false), - use_manual_time_(false), - complexity_(oNone), - complexity_lambda_(nullptr) { - ComputeStatistics("mean", StatisticsMean); - ComputeStatistics("median", StatisticsMedian); - ComputeStatistics("stddev", StatisticsStdDev); -} - -Benchmark::~Benchmark() {} - -Benchmark* Benchmark::Arg(int64_t x) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - args_.push_back({x}); - return this; -} - -Benchmark* Benchmark::Unit(TimeUnit unit) { - time_unit_ = unit; - return this; -} - -Benchmark* Benchmark::Range(int64_t start, int64_t limit) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - std::vector arglist; - AddRange(&arglist, start, limit, range_multiplier_); - - for (int64_t i : arglist) { - args_.push_back({i}); - } - return this; -} - -Benchmark* Benchmark::Ranges( - const std::vector>& ranges) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(ranges.size())); - std::vector> arglists(ranges.size()); - std::size_t total = 1; - for (std::size_t i = 0; i < ranges.size(); i++) { - AddRange(&arglists[i], ranges[i].first, ranges[i].second, - range_multiplier_); - total *= arglists[i].size(); - } - - std::vector ctr(arglists.size(), 0); - - for (std::size_t i = 0; i < total; i++) { - std::vector tmp; - tmp.reserve(arglists.size()); - - for (std::size_t j = 0; j < arglists.size(); j++) { - tmp.push_back(arglists[j].at(ctr[j])); - } - - args_.push_back(std::move(tmp)); - - for (std::size_t j = 0; j < arglists.size(); j++) { - if (ctr[j] + 1 < arglists[j].size()) { - ++ctr[j]; - break; - } - ctr[j] = 0; - } - } - return this; -} - -Benchmark* Benchmark::ArgName(const std::string& name) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - arg_names_ = {name}; - return this; -} - -Benchmark* Benchmark::ArgNames(const std::vector& names) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(names.size())); - arg_names_ = names; - return this; -} - -Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - CHECK_GE(start, 0); - CHECK_LE(start, limit); - for (int64_t arg = start; arg <= limit; arg += step) { - args_.push_back({arg}); - } - return this; -} - -Benchmark* Benchmark::Args(const std::vector& args) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(args.size())); - args_.push_back(args); - return this; -} - -Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) { - custom_arguments(this); - return this; -} - -Benchmark* Benchmark::RangeMultiplier(int multiplier) { - CHECK(multiplier > 1); - range_multiplier_ = multiplier; - return this; -} - -Benchmark* Benchmark::MinTime(double t) { - CHECK(t > 0.0); - CHECK(iterations_ == 0); - min_time_ = t; - return this; -} - -Benchmark* Benchmark::Iterations(size_t n) { - CHECK(n > 0); - CHECK(IsZero(min_time_)); - iterations_ = n; - return this; -} - -Benchmark* Benchmark::Repetitions(int n) { - CHECK(n > 0); - repetitions_ = n; - return this; -} - -Benchmark* Benchmark::ReportAggregatesOnly(bool value) { - report_mode_ = value ? RM_ReportAggregatesOnly : RM_Default; - return this; -} - -Benchmark* Benchmark::UseRealTime() { - CHECK(!use_manual_time_) - << "Cannot set UseRealTime and UseManualTime simultaneously."; - use_real_time_ = true; - return this; -} - -Benchmark* Benchmark::UseManualTime() { - CHECK(!use_real_time_) - << "Cannot set UseRealTime and UseManualTime simultaneously."; - use_manual_time_ = true; - return this; -} - -Benchmark* Benchmark::Complexity(BigO complexity) { - complexity_ = complexity; - return this; -} - -Benchmark* Benchmark::Complexity(BigOFunc* complexity) { - complexity_lambda_ = complexity; - complexity_ = oLambda; - return this; -} - -Benchmark* Benchmark::ComputeStatistics(std::string name, - StatisticsFunc* statistics) { - statistics_.emplace_back(name, statistics); - return this; -} - -Benchmark* Benchmark::Threads(int t) { - CHECK_GT(t, 0); - thread_counts_.push_back(t); - return this; -} - -Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); - - AddRange(&thread_counts_, min_threads, max_threads, 2); - return this; -} - -Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads, - int stride) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); - CHECK_GE(stride, 1); - - for (auto i = min_threads; i < max_threads; i += stride) { - thread_counts_.push_back(i); - } - thread_counts_.push_back(max_threads); - return this; -} - -Benchmark* Benchmark::ThreadPerCpu() { - thread_counts_.push_back(CPUInfo::Get().num_cpus); - return this; -} - -void Benchmark::SetName(const char* name) { name_ = name; } - -int Benchmark::ArgsCnt() const { - if (args_.empty()) { - if (arg_names_.empty()) return -1; - return static_cast(arg_names_.size()); - } - return static_cast(args_.front().size()); -} - -//=============================================================================// -// FunctionBenchmark -//=============================================================================// - -void FunctionBenchmark::Run(State& st) { func_(st); } - -} // end namespace internal - -void ClearRegisteredBenchmarks() { - internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks(); -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/benchmark_register.h b/interpreter/llvm/src/utils/benchmark/src/benchmark_register.h deleted file mode 100644 index 4caa5ad4da079..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/benchmark_register.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef BENCHMARK_REGISTER_H -#define BENCHMARK_REGISTER_H - -#include -#include - -#include "check.h" - -template -void AddRange(std::vector* dst, T lo, T hi, int mult) { - CHECK_GE(lo, 0); - CHECK_GE(hi, lo); - CHECK_GE(mult, 2); - - // Add "lo" - dst->push_back(lo); - - static const T kmax = std::numeric_limits::max(); - - // Now space out the benchmarks in multiples of "mult" - for (T i = 1; i < kmax / mult; i *= mult) { - if (i >= hi) break; - if (i > lo) { - dst->push_back(i); - } - } - - // Add "hi" (if different from "lo") - if (hi != lo) { - dst->push_back(hi); - } -} - -#endif // BENCHMARK_REGISTER_H diff --git a/interpreter/llvm/src/utils/benchmark/src/check.h b/interpreter/llvm/src/utils/benchmark/src/check.h deleted file mode 100644 index 73bead2fb555b..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/check.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef CHECK_H_ -#define CHECK_H_ - -#include -#include -#include - -#include "internal_macros.h" -#include "log.h" - -namespace benchmark { -namespace internal { - -typedef void(AbortHandlerT)(); - -inline AbortHandlerT*& GetAbortHandler() { - static AbortHandlerT* handler = &std::abort; - return handler; -} - -BENCHMARK_NORETURN inline void CallAbortHandler() { - GetAbortHandler()(); - std::abort(); // fallback to enforce noreturn -} - -// CheckHandler is the class constructed by failing CHECK macros. CheckHandler -// will log information about the failures and abort when it is destructed. -class CheckHandler { - public: - CheckHandler(const char* check, const char* file, const char* func, int line) - : log_(GetErrorLogInstance()) { - log_ << file << ":" << line << ": " << func << ": Check `" << check - << "' failed. "; - } - - LogType& GetLog() { return log_; } - - BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { - log_ << std::endl; - CallAbortHandler(); - } - - CheckHandler& operator=(const CheckHandler&) = delete; - CheckHandler(const CheckHandler&) = delete; - CheckHandler() = delete; - - private: - LogType& log_; -}; - -} // end namespace internal -} // end namespace benchmark - -// The CHECK macro returns a std::ostream object that can have extra information -// written to it. -#ifndef NDEBUG -#define CHECK(b) \ - (b ? ::benchmark::internal::GetNullLogInstance() \ - : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ - .GetLog()) -#else -#define CHECK(b) ::benchmark::internal::GetNullLogInstance() -#endif - -#define CHECK_EQ(a, b) CHECK((a) == (b)) -#define CHECK_NE(a, b) CHECK((a) != (b)) -#define CHECK_GE(a, b) CHECK((a) >= (b)) -#define CHECK_LE(a, b) CHECK((a) <= (b)) -#define CHECK_GT(a, b) CHECK((a) > (b)) -#define CHECK_LT(a, b) CHECK((a) < (b)) - -#define CHECK_FLOAT_EQ(a, b, eps) CHECK(std::fabs((a) - (b)) < (eps)) -#define CHECK_FLOAT_NE(a, b, eps) CHECK(std::fabs((a) - (b)) >= (eps)) -#define CHECK_FLOAT_GE(a, b, eps) CHECK((a) - (b) > -(eps)) -#define CHECK_FLOAT_LE(a, b, eps) CHECK((b) - (a) > -(eps)) -#define CHECK_FLOAT_GT(a, b, eps) CHECK((a) - (b) > (eps)) -#define CHECK_FLOAT_LT(a, b, eps) CHECK((b) - (a) > (eps)) - -#endif // CHECK_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/colorprint.cc b/interpreter/llvm/src/utils/benchmark/src/colorprint.cc deleted file mode 100644 index fff6a98818b84..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/colorprint.cc +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "colorprint.h" - -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#include -#else -#include -#endif // BENCHMARK_OS_WINDOWS - -namespace benchmark { -namespace { -#ifdef BENCHMARK_OS_WINDOWS -typedef WORD PlatformColorCode; -#else -typedef const char* PlatformColorCode; -#endif - -PlatformColorCode GetPlatformColorCode(LogColor color) { -#ifdef BENCHMARK_OS_WINDOWS - switch (color) { - case COLOR_RED: - return FOREGROUND_RED; - case COLOR_GREEN: - return FOREGROUND_GREEN; - case COLOR_YELLOW: - return FOREGROUND_RED | FOREGROUND_GREEN; - case COLOR_BLUE: - return FOREGROUND_BLUE; - case COLOR_MAGENTA: - return FOREGROUND_BLUE | FOREGROUND_RED; - case COLOR_CYAN: - return FOREGROUND_BLUE | FOREGROUND_GREEN; - case COLOR_WHITE: // fall through to default - default: - return 0; - } -#else - switch (color) { - case COLOR_RED: - return "1"; - case COLOR_GREEN: - return "2"; - case COLOR_YELLOW: - return "3"; - case COLOR_BLUE: - return "4"; - case COLOR_MAGENTA: - return "5"; - case COLOR_CYAN: - return "6"; - case COLOR_WHITE: - return "7"; - default: - return nullptr; - }; -#endif -} - -} // end namespace - -std::string FormatString(const char* msg, va_list args) { - // we might need a second shot at this, so pre-emptivly make a copy - va_list args_cp; - va_copy(args_cp, args); - - std::size_t size = 256; - char local_buff[256]; - auto ret = vsnprintf(local_buff, size, msg, args_cp); - - va_end(args_cp); - - // currently there is no error handling for failure, so this is hack. - CHECK(ret >= 0); - - if (ret == 0) // handle empty expansion - return {}; - else if (static_cast(ret) < size) - return local_buff; - else { - // we did not provide a long enough buffer on our first attempt. - size = (size_t)ret + 1; // + 1 for the null byte - std::unique_ptr buff(new char[size]); - ret = vsnprintf(buff.get(), size, msg, args); - CHECK(ret > 0 && ((size_t)ret) < size); - return buff.get(); - } -} - -std::string FormatString(const char* msg, ...) { - va_list args; - va_start(args, msg); - auto tmp = FormatString(msg, args); - va_end(args); - return tmp; -} - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...) { - va_list args; - va_start(args, fmt); - ColorPrintf(out, color, fmt, args); - va_end(args); -} - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, - va_list args) { -#ifdef BENCHMARK_OS_WINDOWS - ((void)out); // suppress unused warning - - const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); - - // Gets the current text color. - CONSOLE_SCREEN_BUFFER_INFO buffer_info; - GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); - const WORD old_color_attrs = buffer_info.wAttributes; - - // We need to flush the stream buffers into the console before each - // SetConsoleTextAttribute call lest it affect the text that is already - // printed but has not yet reached the console. - fflush(stdout); - SetConsoleTextAttribute(stdout_handle, - GetPlatformColorCode(color) | FOREGROUND_INTENSITY); - vprintf(fmt, args); - - fflush(stdout); - // Restores the text color. - SetConsoleTextAttribute(stdout_handle, old_color_attrs); -#else - const char* color_code = GetPlatformColorCode(color); - if (color_code) out << FormatString("\033[0;3%sm", color_code); - out << FormatString(fmt, args) << "\033[m"; -#endif -} - -bool IsColorTerminal() { -#if BENCHMARK_OS_WINDOWS - // On Windows the TERM variable is usually not set, but the - // console there does support colors. - return 0 != _isatty(_fileno(stdout)); -#else - // On non-Windows platforms, we rely on the TERM variable. This list of - // supported TERM values is copied from Google Test: - // . - const char* const SUPPORTED_TERM_VALUES[] = { - "xterm", "xterm-color", "xterm-256color", - "screen", "screen-256color", "tmux", - "tmux-256color", "rxvt-unicode", "rxvt-unicode-256color", - "linux", "cygwin", - }; - - const char* const term = getenv("TERM"); - - bool term_supports_color = false; - for (const char* candidate : SUPPORTED_TERM_VALUES) { - if (term && 0 == strcmp(term, candidate)) { - term_supports_color = true; - break; - } - } - - return 0 != isatty(fileno(stdout)) && term_supports_color; -#endif // BENCHMARK_OS_WINDOWS -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/colorprint.h b/interpreter/llvm/src/utils/benchmark/src/colorprint.h deleted file mode 100644 index 9f6fab9b34226..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/colorprint.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef BENCHMARK_COLORPRINT_H_ -#define BENCHMARK_COLORPRINT_H_ - -#include -#include -#include - -namespace benchmark { -enum LogColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW, - COLOR_BLUE, - COLOR_MAGENTA, - COLOR_CYAN, - COLOR_WHITE -}; - -std::string FormatString(const char* msg, va_list args); -std::string FormatString(const char* msg, ...); - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, - va_list args); -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...); - -// Returns true if stdout appears to be a terminal that supports colored -// output, false otherwise. -bool IsColorTerminal(); - -} // end namespace benchmark - -#endif // BENCHMARK_COLORPRINT_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/commandlineflags.cc b/interpreter/llvm/src/utils/benchmark/src/commandlineflags.cc deleted file mode 100644 index 2fc92517a32c7..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/commandlineflags.cc +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "commandlineflags.h" - -#include -#include -#include -#include -#include - -namespace benchmark { -// Parses 'str' for a 32-bit signed integer. If successful, writes -// the result to *value and returns true; otherwise leaves *value -// unchanged and returns false. -bool ParseInt32(const std::string& src_text, const char* str, int32_t* value) { - // Parses the environment variable as a decimal integer. - char* end = nullptr; - const long long_value = strtol(str, &end, 10); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - std::cerr << src_text << " is expected to be a 32-bit integer, " - << "but actually has value \"" << str << "\".\n"; - return false; - } - - // Is the parsed value in the range of an Int32? - const int32_t result = static_cast(long_value); - if (long_value == std::numeric_limits::max() || - long_value == std::numeric_limits::min() || - // The parsed value overflows as a long. (strtol() returns - // LONG_MAX or LONG_MIN when the input overflows.) - result != long_value - // The parsed value overflows as an Int32. - ) { - std::cerr << src_text << " is expected to be a 32-bit integer, " - << "but actually has value \"" << str << "\", " - << "which overflows.\n"; - return false; - } - - *value = result; - return true; -} - -// Parses 'str' for a double. If successful, writes the result to *value and -// returns true; otherwise leaves *value unchanged and returns false. -bool ParseDouble(const std::string& src_text, const char* str, double* value) { - // Parses the environment variable as a decimal integer. - char* end = nullptr; - const double double_value = strtod(str, &end); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - std::cerr << src_text << " is expected to be a double, " - << "but actually has value \"" << str << "\".\n"; - return false; - } - - *value = double_value; - return true; -} - -// Returns the name of the environment variable corresponding to the -// given flag. For example, FlagToEnvVar("foo") will return -// "BENCHMARK_FOO" in the open-source version. -static std::string FlagToEnvVar(const char* flag) { - const std::string flag_str(flag); - - std::string env_var; - for (size_t i = 0; i != flag_str.length(); ++i) - env_var += static_cast(::toupper(flag_str.c_str()[i])); - - return "BENCHMARK_" + env_var; -} - -// Reads and returns the Boolean environment variable corresponding to -// the given flag; if it's not set, returns default_value. -// -// The value is considered true iff it's not "0". -bool BoolFromEnv(const char* flag, bool default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - return string_value == nullptr ? default_value - : strcmp(string_value, "0") != 0; -} - -// Reads and returns a 32-bit integer stored in the environment -// variable corresponding to the given flag; if it isn't set or -// doesn't represent a valid 32-bit integer, returns default_value. -int32_t Int32FromEnv(const char* flag, int32_t default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - if (string_value == nullptr) { - // The environment variable is not set. - return default_value; - } - - int32_t result = default_value; - if (!ParseInt32(std::string("Environment variable ") + env_var, string_value, - &result)) { - std::cout << "The default value " << default_value << " is used.\n"; - return default_value; - } - - return result; -} - -// Reads and returns the string environment variable corresponding to -// the given flag; if it's not set, returns default_value. -const char* StringFromEnv(const char* flag, const char* default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const value = getenv(env_var.c_str()); - return value == nullptr ? default_value : value; -} - -// Parses a string as a command line flag. The string should have -// the format "--flag=value". When def_optional is true, the "=value" -// part can be omitted. -// -// Returns the value of the flag, or nullptr if the parsing failed. -const char* ParseFlagValue(const char* str, const char* flag, - bool def_optional) { - // str and flag must not be nullptr. - if (str == nullptr || flag == nullptr) return nullptr; - - // The flag must start with "--". - const std::string flag_str = std::string("--") + std::string(flag); - const size_t flag_len = flag_str.length(); - if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; - - // Skips the flag name. - const char* flag_end = str + flag_len; - - // When def_optional is true, it's OK to not have a "=value" part. - if (def_optional && (flag_end[0] == '\0')) return flag_end; - - // If def_optional is true and there are more characters after the - // flag name, or if def_optional is false, there must be a '=' after - // the flag name. - if (flag_end[0] != '=') return nullptr; - - // Returns the string after "=". - return flag_end + 1; -} - -bool ParseBoolFlag(const char* str, const char* flag, bool* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, true); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Converts the string value to a bool. - *value = IsTruthyFlagValue(value_str); - return true; -} - -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - return ParseInt32(std::string("The value of flag --") + flag, value_str, - value); -} - -bool ParseDoubleFlag(const char* str, const char* flag, double* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - return ParseDouble(std::string("The value of flag --") + flag, value_str, - value); -} - -bool ParseStringFlag(const char* str, const char* flag, std::string* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - *value = value_str; - return true; -} - -bool IsFlag(const char* str, const char* flag) { - return (ParseFlagValue(str, flag, true) != nullptr); -} - -bool IsTruthyFlagValue(const std::string& value) { - if (value.empty()) return true; - char ch = value[0]; - return isalnum(ch) && - !(ch == '0' || ch == 'f' || ch == 'F' || ch == 'n' || ch == 'N'); -} -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/commandlineflags.h b/interpreter/llvm/src/utils/benchmark/src/commandlineflags.h deleted file mode 100644 index 945c9a9fc4af3..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/commandlineflags.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ -#define BENCHMARK_COMMANDLINEFLAGS_H_ - -#include -#include - -// Macro for referencing flags. -#define FLAG(name) FLAGS_##name - -// Macros for declaring flags. -#define DECLARE_bool(name) extern bool FLAG(name) -#define DECLARE_int32(name) extern int32_t FLAG(name) -#define DECLARE_int64(name) extern int64_t FLAG(name) -#define DECLARE_double(name) extern double FLAG(name) -#define DECLARE_string(name) extern std::string FLAG(name) - -// Macros for defining flags. -#define DEFINE_bool(name, default_val, doc) bool FLAG(name) = (default_val) -#define DEFINE_int32(name, default_val, doc) int32_t FLAG(name) = (default_val) -#define DEFINE_int64(name, default_val, doc) int64_t FLAG(name) = (default_val) -#define DEFINE_double(name, default_val, doc) double FLAG(name) = (default_val) -#define DEFINE_string(name, default_val, doc) \ - std::string FLAG(name) = (default_val) - -namespace benchmark { -// Parses 'str' for a 32-bit signed integer. If successful, writes the result -// to *value and returns true; otherwise leaves *value unchanged and returns -// false. -bool ParseInt32(const std::string& src_text, const char* str, int32_t* value); - -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromEnv(const char* flag, bool default_val); -int32_t Int32FromEnv(const char* flag, int32_t default_val); -double DoubleFromEnv(const char* flag, double default_val); -const char* StringFromEnv(const char* flag, const char* default_val); - -// Parses a string for a bool flag, in the form of either -// "--flag=value" or "--flag". -// -// In the former case, the value is taken as true if it passes IsTruthyValue(). -// -// In the latter case, the value is taken as true. -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseBoolFlag(const char* str, const char* flag, bool* value); - -// Parses a string for an Int32 flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); - -// Parses a string for a Double flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseDoubleFlag(const char* str, const char* flag, double* value); - -// Parses a string for a string flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseStringFlag(const char* str, const char* flag, std::string* value); - -// Returns true if the string matches the flag. -bool IsFlag(const char* str, const char* flag); - -// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or -// some non-alphanumeric character. As a special case, also returns true if -// value is the empty string. -bool IsTruthyFlagValue(const std::string& value); -} // end namespace benchmark - -#endif // BENCHMARK_COMMANDLINEFLAGS_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/complexity.cc b/interpreter/llvm/src/utils/benchmark/src/complexity.cc deleted file mode 100644 index 97cb0a88271d5..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/complexity.cc +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Source project : https://github.com/ismaelJimenez/cpp.leastsq -// Adapted to be used with google benchmark - -#include "benchmark/benchmark.h" - -#include -#include -#include "check.h" -#include "complexity.h" - -namespace benchmark { - -// Internal function to calculate the different scalability forms -BigOFunc* FittingCurve(BigO complexity) { - switch (complexity) { - case oN: - return [](int64_t n) -> double { return static_cast(n); }; - case oNSquared: - return [](int64_t n) -> double { return std::pow(n, 2); }; - case oNCubed: - return [](int64_t n) -> double { return std::pow(n, 3); }; - case oLogN: - return [](int64_t n) { return log2(n); }; - case oNLogN: - return [](int64_t n) { return n * log2(n); }; - case o1: - default: - return [](int64_t) { return 1.0; }; - } -} - -// Function to return an string for the calculated complexity -std::string GetBigOString(BigO complexity) { - switch (complexity) { - case oN: - return "N"; - case oNSquared: - return "N^2"; - case oNCubed: - return "N^3"; - case oLogN: - return "lgN"; - case oNLogN: - return "NlgN"; - case o1: - return "(1)"; - default: - return "f(N)"; - } -} - -// Find the coefficient for the high-order term in the running time, by -// minimizing the sum of squares of relative error, for the fitting curve -// given by the lambda expression. -// - n : Vector containing the size of the benchmark tests. -// - time : Vector containing the times for the benchmark tests. -// - fitting_curve : lambda expression (e.g. [](int64_t n) {return n; };). - -// For a deeper explanation on the algorithm logic, look the README file at -// http://github.com/ismaelJimenez/Minimal-Cpp-Least-Squared-Fit - -LeastSq MinimalLeastSq(const std::vector& n, - const std::vector& time, - BigOFunc* fitting_curve) { - double sigma_gn_squared = 0.0; - double sigma_time = 0.0; - double sigma_time_gn = 0.0; - - // Calculate least square fitting parameter - for (size_t i = 0; i < n.size(); ++i) { - double gn_i = fitting_curve(n[i]); - sigma_gn_squared += gn_i * gn_i; - sigma_time += time[i]; - sigma_time_gn += time[i] * gn_i; - } - - LeastSq result; - result.complexity = oLambda; - - // Calculate complexity. - result.coef = sigma_time_gn / sigma_gn_squared; - - // Calculate RMS - double rms = 0.0; - for (size_t i = 0; i < n.size(); ++i) { - double fit = result.coef * fitting_curve(n[i]); - rms += pow((time[i] - fit), 2); - } - - // Normalized RMS by the mean of the observed values - double mean = sigma_time / n.size(); - result.rms = sqrt(rms / n.size()) / mean; - - return result; -} - -// Find the coefficient for the high-order term in the running time, by -// minimizing the sum of squares of relative error. -// - n : Vector containing the size of the benchmark tests. -// - time : Vector containing the times for the benchmark tests. -// - complexity : If different than oAuto, the fitting curve will stick to -// this one. If it is oAuto, it will be calculated the best -// fitting curve. -LeastSq MinimalLeastSq(const std::vector& n, - const std::vector& time, const BigO complexity) { - CHECK_EQ(n.size(), time.size()); - CHECK_GE(n.size(), 2); // Do not compute fitting curve is less than two - // benchmark runs are given - CHECK_NE(complexity, oNone); - - LeastSq best_fit; - - if (complexity == oAuto) { - std::vector fit_curves = {oLogN, oN, oNLogN, oNSquared, oNCubed}; - - // Take o1 as default best fitting curve - best_fit = MinimalLeastSq(n, time, FittingCurve(o1)); - best_fit.complexity = o1; - - // Compute all possible fitting curves and stick to the best one - for (const auto& fit : fit_curves) { - LeastSq current_fit = MinimalLeastSq(n, time, FittingCurve(fit)); - if (current_fit.rms < best_fit.rms) { - best_fit = current_fit; - best_fit.complexity = fit; - } - } - } else { - best_fit = MinimalLeastSq(n, time, FittingCurve(complexity)); - best_fit.complexity = complexity; - } - - return best_fit; -} - -std::vector ComputeBigO( - const std::vector& reports) { - typedef BenchmarkReporter::Run Run; - std::vector results; - - if (reports.size() < 2) return results; - - // Accumulators. - std::vector n; - std::vector real_time; - std::vector cpu_time; - - // Populate the accumulators. - for (const Run& run : reports) { - CHECK_GT(run.complexity_n, 0) << "Did you forget to call SetComplexityN?"; - n.push_back(run.complexity_n); - real_time.push_back(run.real_accumulated_time / run.iterations); - cpu_time.push_back(run.cpu_accumulated_time / run.iterations); - } - - LeastSq result_cpu; - LeastSq result_real; - - if (reports[0].complexity == oLambda) { - result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity_lambda); - result_real = MinimalLeastSq(n, real_time, reports[0].complexity_lambda); - } else { - result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity); - result_real = MinimalLeastSq(n, real_time, result_cpu.complexity); - } - std::string benchmark_name = - reports[0].benchmark_name.substr(0, reports[0].benchmark_name.find('/')); - - // Get the data from the accumulator to BenchmarkReporter::Run's. - Run big_o; - big_o.benchmark_name = benchmark_name + "_BigO"; - big_o.iterations = 0; - big_o.real_accumulated_time = result_real.coef; - big_o.cpu_accumulated_time = result_cpu.coef; - big_o.report_big_o = true; - big_o.complexity = result_cpu.complexity; - - // All the time results are reported after being multiplied by the - // time unit multiplier. But since RMS is a relative quantity it - // should not be multiplied at all. So, here, we _divide_ it by the - // multiplier so that when it is multiplied later the result is the - // correct one. - double multiplier = GetTimeUnitMultiplier(reports[0].time_unit); - - // Only add label to mean/stddev if it is same for all runs - Run rms; - big_o.report_label = reports[0].report_label; - rms.benchmark_name = benchmark_name + "_RMS"; - rms.report_label = big_o.report_label; - rms.iterations = 0; - rms.real_accumulated_time = result_real.rms / multiplier; - rms.cpu_accumulated_time = result_cpu.rms / multiplier; - rms.report_rms = true; - rms.complexity = result_cpu.complexity; - // don't forget to keep the time unit, or we won't be able to - // recover the correct value. - rms.time_unit = reports[0].time_unit; - - results.push_back(big_o); - results.push_back(rms); - return results; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/complexity.h b/interpreter/llvm/src/utils/benchmark/src/complexity.h deleted file mode 100644 index df29b48d29b4e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/complexity.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Source project : https://github.com/ismaelJimenez/cpp.leastsq -// Adapted to be used with google benchmark - -#ifndef COMPLEXITY_H_ -#define COMPLEXITY_H_ - -#include -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// Return a vector containing the bigO and RMS information for the specified -// list of reports. If 'reports.size() < 2' an empty vector is returned. -std::vector ComputeBigO( - const std::vector& reports); - -// This data structure will contain the result returned by MinimalLeastSq -// - coef : Estimated coeficient for the high-order term as -// interpolated from data. -// - rms : Normalized Root Mean Squared Error. -// - complexity : Scalability form (e.g. oN, oNLogN). In case a scalability -// form has been provided to MinimalLeastSq this will return -// the same value. In case BigO::oAuto has been selected, this -// parameter will return the best fitting curve detected. - -struct LeastSq { - LeastSq() : coef(0.0), rms(0.0), complexity(oNone) {} - - double coef; - double rms; - BigO complexity; -}; - -// Function to return an string for the calculated complexity -std::string GetBigOString(BigO complexity); - -} // end namespace benchmark - -#endif // COMPLEXITY_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/console_reporter.cc b/interpreter/llvm/src/utils/benchmark/src/console_reporter.cc deleted file mode 100644 index 48920ca782956..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/console_reporter.cc +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" -#include "counter.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "internal_macros.h" -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -bool ConsoleReporter::ReportContext(const Context& context) { - name_field_width_ = context.name_field_width; - printed_header_ = false; - prev_counters_.clear(); - - PrintBasicContext(&GetErrorStream(), context); - -#ifdef BENCHMARK_OS_WINDOWS - if ((output_options_ & OO_Color) && &std::cout != &GetOutputStream()) { - GetErrorStream() - << "Color printing is only supported for stdout on windows." - " Disabling color printing\n"; - output_options_ = static_cast< OutputOptions >(output_options_ & ~OO_Color); - } -#endif - - return true; -} - -void ConsoleReporter::PrintHeader(const Run& run) { - std::string str = FormatString("%-*s %13s %13s %10s", static_cast(name_field_width_), - "Benchmark", "Time", "CPU", "Iterations"); - if(!run.counters.empty()) { - if(output_options_ & OO_Tabular) { - for(auto const& c : run.counters) { - str += FormatString(" %10s", c.first.c_str()); - } - } else { - str += " UserCounters..."; - } - } - str += "\n"; - std::string line = std::string(str.length(), '-'); - GetOutputStream() << line << "\n" << str << line << "\n"; -} - -void ConsoleReporter::ReportRuns(const std::vector& reports) { - for (const auto& run : reports) { - // print the header: - // --- if none was printed yet - bool print_header = !printed_header_; - // --- or if the format is tabular and this run - // has different fields from the prev header - print_header |= (output_options_ & OO_Tabular) && - (!internal::SameNames(run.counters, prev_counters_)); - if (print_header) { - printed_header_ = true; - prev_counters_ = run.counters; - PrintHeader(run); - } - // As an alternative to printing the headers like this, we could sort - // the benchmarks by header and then print. But this would require - // waiting for the full results before printing, or printing twice. - PrintRunData(run); - } -} - -static void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt, - ...) { - va_list args; - va_start(args, fmt); - out << FormatString(fmt, args); - va_end(args); -} - -void ConsoleReporter::PrintRunData(const Run& result) { - typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...); - auto& Out = GetOutputStream(); - PrinterFn* printer = (output_options_ & OO_Color) ? - (PrinterFn*)ColorPrintf : IgnoreColorPrint; - auto name_color = - (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN; - printer(Out, name_color, "%-*s ", name_field_width_, - result.benchmark_name.c_str()); - - if (result.error_occurred) { - printer(Out, COLOR_RED, "ERROR OCCURRED: \'%s\'", - result.error_message.c_str()); - printer(Out, COLOR_DEFAULT, "\n"); - return; - } - // Format bytes per second - std::string rate; - if (result.bytes_per_second > 0) { - rate = StrCat(" ", HumanReadableNumber(result.bytes_per_second), "B/s"); - } - - // Format items per second - std::string items; - if (result.items_per_second > 0) { - items = - StrCat(" ", HumanReadableNumber(result.items_per_second), " items/s"); - } - - const double real_time = result.GetAdjustedRealTime(); - const double cpu_time = result.GetAdjustedCPUTime(); - - if (result.report_big_o) { - std::string big_o = GetBigOString(result.complexity); - printer(Out, COLOR_YELLOW, "%10.2f %s %10.2f %s ", real_time, big_o.c_str(), - cpu_time, big_o.c_str()); - } else if (result.report_rms) { - printer(Out, COLOR_YELLOW, "%10.0f %% %10.0f %% ", real_time * 100, - cpu_time * 100); - } else { - const char* timeLabel = GetTimeUnitString(result.time_unit); - printer(Out, COLOR_YELLOW, "%10.0f %s %10.0f %s ", real_time, timeLabel, - cpu_time, timeLabel); - } - - if (!result.report_big_o && !result.report_rms) { - printer(Out, COLOR_CYAN, "%10lld", result.iterations); - } - - for (auto& c : result.counters) { - const std::size_t cNameLen = std::max(std::string::size_type(10), - c.first.length()); - auto const& s = HumanReadableNumber(c.second.value, 1000); - if (output_options_ & OO_Tabular) { - if (c.second.flags & Counter::kIsRate) { - printer(Out, COLOR_DEFAULT, " %*s/s", cNameLen - 2, s.c_str()); - } else { - printer(Out, COLOR_DEFAULT, " %*s", cNameLen, s.c_str()); - } - } else { - const char* unit = (c.second.flags & Counter::kIsRate) ? "/s" : ""; - printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), - unit); - } - } - - if (!rate.empty()) { - printer(Out, COLOR_DEFAULT, " %*s", 13, rate.c_str()); - } - - if (!items.empty()) { - printer(Out, COLOR_DEFAULT, " %*s", 18, items.c_str()); - } - - if (!result.report_label.empty()) { - printer(Out, COLOR_DEFAULT, " %s", result.report_label.c_str()); - } - - printer(Out, COLOR_DEFAULT, "\n"); -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/counter.cc b/interpreter/llvm/src/utils/benchmark/src/counter.cc deleted file mode 100644 index ed1aa044ee79f..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/counter.cc +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "counter.h" - -namespace benchmark { -namespace internal { - -double Finish(Counter const& c, double cpu_time, double num_threads) { - double v = c.value; - if (c.flags & Counter::kIsRate) { - v /= cpu_time; - } - if (c.flags & Counter::kAvgThreads) { - v /= num_threads; - } - return v; -} - -void Finish(UserCounters *l, double cpu_time, double num_threads) { - for (auto &c : *l) { - c.second.value = Finish(c.second, cpu_time, num_threads); - } -} - -void Increment(UserCounters *l, UserCounters const& r) { - // add counters present in both or just in *l - for (auto &c : *l) { - auto it = r.find(c.first); - if (it != r.end()) { - c.second.value = c.second + it->second; - } - } - // add counters present in r, but not in *l - for (auto const &tc : r) { - auto it = l->find(tc.first); - if (it == l->end()) { - (*l)[tc.first] = tc.second; - } - } -} - -bool SameNames(UserCounters const& l, UserCounters const& r) { - if (&l == &r) return true; - if (l.size() != r.size()) { - return false; - } - for (auto const& c : l) { - if (r.find(c.first) == r.end()) { - return false; - } - } - return true; -} - -} // end namespace internal -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/counter.h b/interpreter/llvm/src/utils/benchmark/src/counter.h deleted file mode 100644 index dd6865a31d766..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/counter.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// these counter-related functions are hidden to reduce API surface. -namespace internal { -void Finish(UserCounters *l, double time, double num_threads); -void Increment(UserCounters *l, UserCounters const& r); -bool SameNames(UserCounters const& l, UserCounters const& r); -} // end namespace internal - -} //end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/csv_reporter.cc b/interpreter/llvm/src/utils/benchmark/src/csv_reporter.cc deleted file mode 100644 index 35510645b084e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/csv_reporter.cc +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" - -#include -#include -#include -#include -#include -#include - -#include "string_util.h" -#include "timers.h" -#include "check.h" - -// File format reference: http://edoceo.com/utilitas/csv-file-format. - -namespace benchmark { - -namespace { -std::vector elements = { - "name", "iterations", "real_time", "cpu_time", - "time_unit", "bytes_per_second", "items_per_second", "label", - "error_occurred", "error_message"}; -} // namespace - -bool CSVReporter::ReportContext(const Context& context) { - PrintBasicContext(&GetErrorStream(), context); - return true; -} - -void CSVReporter::ReportRuns(const std::vector & reports) { - std::ostream& Out = GetOutputStream(); - - if (!printed_header_) { - // save the names of all the user counters - for (const auto& run : reports) { - for (const auto& cnt : run.counters) { - user_counter_names_.insert(cnt.first); - } - } - - // print the header - for (auto B = elements.begin(); B != elements.end();) { - Out << *B++; - if (B != elements.end()) Out << ","; - } - for (auto B = user_counter_names_.begin(); B != user_counter_names_.end();) { - Out << ",\"" << *B++ << "\""; - } - Out << "\n"; - - printed_header_ = true; - } else { - // check that all the current counters are saved in the name set - for (const auto& run : reports) { - for (const auto& cnt : run.counters) { - CHECK(user_counter_names_.find(cnt.first) != user_counter_names_.end()) - << "All counters must be present in each run. " - << "Counter named \"" << cnt.first - << "\" was not in a run after being added to the header"; - } - } - } - - // print results for each run - for (const auto& run : reports) { - PrintRunData(run); - } - -} - -void CSVReporter::PrintRunData(const Run & run) { - std::ostream& Out = GetOutputStream(); - - // Field with embedded double-quote characters must be doubled and the field - // delimited with double-quotes. - std::string name = run.benchmark_name; - ReplaceAll(&name, "\"", "\"\""); - Out << '"' << name << "\","; - if (run.error_occurred) { - Out << std::string(elements.size() - 3, ','); - Out << "true,"; - std::string msg = run.error_message; - ReplaceAll(&msg, "\"", "\"\""); - Out << '"' << msg << "\"\n"; - return; - } - - // Do not print iteration on bigO and RMS report - if (!run.report_big_o && !run.report_rms) { - Out << run.iterations; - } - Out << ","; - - Out << run.GetAdjustedRealTime() << ","; - Out << run.GetAdjustedCPUTime() << ","; - - // Do not print timeLabel on bigO and RMS report - if (run.report_big_o) { - Out << GetBigOString(run.complexity); - } else if (!run.report_rms) { - Out << GetTimeUnitString(run.time_unit); - } - Out << ","; - - if (run.bytes_per_second > 0.0) { - Out << run.bytes_per_second; - } - Out << ","; - if (run.items_per_second > 0.0) { - Out << run.items_per_second; - } - Out << ","; - if (!run.report_label.empty()) { - // Field with embedded double-quote characters must be doubled and the field - // delimited with double-quotes. - std::string label = run.report_label; - ReplaceAll(&label, "\"", "\"\""); - Out << "\"" << label << "\""; - } - Out << ",,"; // for error_occurred and error_message - - // Print user counters - for (const auto &ucn : user_counter_names_) { - auto it = run.counters.find(ucn); - if(it == run.counters.end()) { - Out << ","; - } else { - Out << "," << it->second; - } - } - Out << '\n'; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/cycleclock.h b/interpreter/llvm/src/utils/benchmark/src/cycleclock.h deleted file mode 100644 index 040ec22c20a96..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/cycleclock.h +++ /dev/null @@ -1,206 +0,0 @@ -// ---------------------------------------------------------------------- -// CycleClock -// A CycleClock tells you the current time in Cycles. The "time" -// is actually time since power-on. This is like time() but doesn't -// involve a system call and is much more precise. -// -// NOTE: Not all cpu/platform/kernel combinations guarantee that this -// clock increments at a constant rate or is synchronized across all logical -// cpus in a system. -// -// If you need the above guarantees, please consider using a different -// API. There are efforts to provide an interface which provides a millisecond -// granularity and implemented as a memory read. A memory read is generally -// cheaper than the CycleClock for many architectures. -// -// Also, in some out of order CPU implementations, the CycleClock is not -// serializing. So if you're trying to count at cycles granularity, your -// data might be inaccurate due to out of order instruction execution. -// ---------------------------------------------------------------------- - -#ifndef BENCHMARK_CYCLECLOCK_H_ -#define BENCHMARK_CYCLECLOCK_H_ - -#include - -#include "benchmark/benchmark.h" -#include "internal_macros.h" - -#if defined(BENCHMARK_OS_MACOSX) -#include -#endif -// For MSVC, we want to use '_asm rdtsc' when possible (since it works -// with even ancient MSVC compilers), and when not possible the -// __rdtsc intrinsic, declared in . Unfortunately, in some -// environments, and have conflicting -// declarations of some other intrinsics, breaking compilation. -// Therefore, we simply declare __rdtsc ourselves. See also -// http://connect.microsoft.com/VisualStudio/feedback/details/262047 -#if defined(COMPILER_MSVC) && !defined(_M_IX86) -extern "C" uint64_t __rdtsc(); -#pragma intrinsic(__rdtsc) -#endif - -#if !defined(BENCHMARK_OS_WINDOWS) || defined(BENCHMARK_OS_MINGW) -#include -#include -#endif - -#ifdef BENCHMARK_OS_EMSCRIPTEN -#include -#endif - -namespace benchmark { -// NOTE: only i386 and x86_64 have been well tested. -// PPC, sparc, alpha, and ia64 are based on -// http://peter.kuscsik.com/wordpress/?p=14 -// with modifications by m3b. See also -// https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h -namespace cycleclock { -// This should return the number of cycles since power-on. Thread-safe. -inline BENCHMARK_ALWAYS_INLINE int64_t Now() { -#if defined(BENCHMARK_OS_MACOSX) - // this goes at the top because we need ALL Macs, regardless of - // architecture, to return the number of "mach time units" that - // have passed since startup. See sysinfo.cc where - // InitializeSystemInfo() sets the supposed cpu clock frequency of - // macs to the number of mach time units per second, not actual - // CPU clock frequency (which can change in the face of CPU - // frequency scaling). Also note that when the Mac sleeps, this - // counter pauses; it does not continue counting, nor does it - // reset to zero. - return mach_absolute_time(); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // this goes above x86-specific code because old versions of Emscripten - // define __x86_64__, although they have nothing to do with it. - return static_cast(emscripten_get_now() * 1e+6); -#elif defined(__i386__) - int64_t ret; - __asm__ volatile("rdtsc" : "=A"(ret)); - return ret; -#elif defined(__x86_64__) || defined(__amd64__) - uint64_t low, high; - __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); - return (high << 32) | low; -#elif defined(__powerpc__) || defined(__ppc__) - // This returns a time-base, which is not always precisely a cycle-count. -#if defined(__powerpc64__) || defined(__ppc64__) - int64_t tb; - asm volatile("mfspr %0, 268" : "=r"(tb)); - return tb; -#else - uint32_t tbl, tbu0, tbu1; - asm volatile( - "mftbu %0\n" - "mftb %1\n" - "mftbu %2" - : "=r"(tbu0), "=r"(tbl), "=r"(tbu1)); - tbl &= -static_cast(tbu0 == tbu1); - // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is no longer needed) - return (static_cast(tbu1) << 32) | tbl; -#endif -#elif defined(__sparc__) - int64_t tick; - asm(".byte 0x83, 0x41, 0x00, 0x00"); - asm("mov %%g1, %0" : "=r"(tick)); - return tick; -#elif defined(__ia64__) - int64_t itc; - asm("mov %0 = ar.itc" : "=r"(itc)); - return itc; -#elif defined(COMPILER_MSVC) && defined(_M_IX86) - // Older MSVC compilers (like 7.x) don't seem to support the - // __rdtsc intrinsic properly, so I prefer to use _asm instead - // when I know it will work. Otherwise, I'll use __rdtsc and hope - // the code is being compiled with a non-ancient compiler. - _asm rdtsc -#elif defined(COMPILER_MSVC) - return __rdtsc(); -#elif defined(BENCHMARK_OS_NACL) - // Native Client validator on x86/x86-64 allows RDTSC instructions, - // and this case is handled above. Native Client validator on ARM - // rejects MRC instructions (used in the ARM-specific sequence below), - // so we handle it here. Portable Native Client compiles to - // architecture-agnostic bytecode, which doesn't provide any - // cycle counter access mnemonics. - - // Native Client does not provide any API to access cycle counter. - // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday - // because is provides nanosecond resolution (which is noticable at - // least for PNaCl modules running on x86 Mac & Linux). - // Initialize to always return 0 if clock_gettime fails. - struct timespec ts = { 0, 0 }; - clock_gettime(CLOCK_MONOTONIC, &ts); - return static_cast(ts.tv_sec) * 1000000000 + ts.tv_nsec; -#elif defined(__aarch64__) - // System timer of ARMv8 runs at a different frequency than the CPU's. - // The frequency is fixed, typically in the range 1-50MHz. It can be - // read at CNTFRQ special register. We assume the OS has set up - // the virtual timer properly. - int64_t virtual_timer_value; - asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); - return virtual_timer_value; -#elif defined(__ARM_ARCH) - // V6 is the earliest arch that has a standard cyclecount - // Native Client validator doesn't allow MRC instructions. -#if (__ARM_ARCH >= 6) - uint32_t pmccntr; - uint32_t pmuseren; - uint32_t pmcntenset; - // Read the user mode perf monitor counter access permissions. - asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); - if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. - asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); - if (pmcntenset & 0x80000000ul) { // Is it counting? - asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); - // The counter is set up to count every 64th cycle - return static_cast(pmccntr) * 64; // Should optimize to << 6 - } - } -#endif - struct timeval tv; - gettimeofday(&tv, nullptr); - return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -#elif defined(__mips__) || defined(__m68k__) - // mips apparently only allows rdtsc for superusers, so we fall - // back to gettimeofday. It's possible clock_gettime would be better. - struct timeval tv; - gettimeofday(&tv, nullptr); - return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -#elif defined(__s390__) // Covers both s390 and s390x. - // Return the CPU clock. - uint64_t tsc; - asm("stck %0" : "=Q" (tsc) : : "cc"); - return tsc; -#elif defined(__riscv) // RISC-V - // Use RDCYCLE (and RDCYCLEH on riscv32) -#if __riscv_xlen == 32 - uint32_t cycles_lo, cycles_hi0, cycles_hi1; - // This asm also includes the PowerPC overflow handling strategy, as above. - // Implemented in assembly because Clang insisted on branching. - asm volatile( - "rdcycleh %0\n" - "rdcycle %1\n" - "rdcycleh %2\n" - "sub %0, %0, %2\n" - "seqz %0, %0\n" - "sub %0, zero, %0\n" - "and %1, %1, %0\n" - : "=r"(cycles_hi0), "=r"(cycles_lo), "=r"(cycles_hi1)); - return (static_cast(cycles_hi1) << 32) | cycles_lo; -#else - uint64_t cycles; - asm volatile("rdcycle %0" : "=r"(cycles)); - return cycles; -#endif -#else -// The soft failover to a generic implementation is automatic only for ARM. -// For other platforms the developer is expected to make an attempt to create -// a fast implementation and use generic version if nothing better is available. -#error You need to define CycleTimer for your OS and CPU -#endif -} -} // end namespace cycleclock -} // end namespace benchmark - -#endif // BENCHMARK_CYCLECLOCK_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/internal_macros.h b/interpreter/llvm/src/utils/benchmark/src/internal_macros.h deleted file mode 100644 index f2d54bfcbd9dd..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/internal_macros.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef BENCHMARK_INTERNAL_MACROS_H_ -#define BENCHMARK_INTERNAL_MACROS_H_ - -#include "benchmark/benchmark.h" - -#ifndef __has_feature -#define __has_feature(x) 0 -#endif - -#if defined(__clang__) - #if !defined(COMPILER_CLANG) - #define COMPILER_CLANG - #endif -#elif defined(_MSC_VER) - #if !defined(COMPILER_MSVC) - #define COMPILER_MSVC - #endif -#elif defined(__GNUC__) - #if !defined(COMPILER_GCC) - #define COMPILER_GCC - #endif -#endif - -#if __has_feature(cxx_attributes) - #define BENCHMARK_NORETURN [[noreturn]] -#elif defined(__GNUC__) - #define BENCHMARK_NORETURN __attribute__((noreturn)) -#elif defined(COMPILER_MSVC) - #define BENCHMARK_NORETURN __declspec(noreturn) -#else - #define BENCHMARK_NORETURN -#endif - -#if defined(__CYGWIN__) - #define BENCHMARK_OS_CYGWIN 1 -#elif defined(_WIN32) - #define BENCHMARK_OS_WINDOWS 1 - #if defined(__MINGW32__) - #define BENCHMARK_OS_MINGW 1 - #endif -#elif defined(__APPLE__) - #define BENCHMARK_OS_APPLE 1 - #include "TargetConditionals.h" - #if defined(TARGET_OS_MAC) - #define BENCHMARK_OS_MACOSX 1 - #if defined(TARGET_OS_IPHONE) - #define BENCHMARK_OS_IOS 1 - #endif - #endif -#elif defined(__FreeBSD__) - #define BENCHMARK_OS_FREEBSD 1 -#elif defined(__NetBSD__) - #define BENCHMARK_OS_NETBSD 1 -#elif defined(__OpenBSD__) - #define BENCHMARK_OS_OPENBSD 1 -#elif defined(__linux__) - #define BENCHMARK_OS_LINUX 1 -#elif defined(__native_client__) - #define BENCHMARK_OS_NACL 1 -#elif defined(__EMSCRIPTEN__) - #define BENCHMARK_OS_EMSCRIPTEN 1 -#elif defined(__rtems__) - #define BENCHMARK_OS_RTEMS 1 -#elif defined(__Fuchsia__) -#define BENCHMARK_OS_FUCHSIA 1 -#elif defined (__SVR4) && defined (__sun) -#define BENCHMARK_OS_SOLARIS 1 -#endif - -#if !__has_feature(cxx_exceptions) && !defined(__cpp_exceptions) \ - && !defined(__EXCEPTIONS) - #define BENCHMARK_HAS_NO_EXCEPTIONS -#endif - -#if defined(COMPILER_CLANG) || defined(COMPILER_GCC) - #define BENCHMARK_MAYBE_UNUSED __attribute__((unused)) -#else - #define BENCHMARK_MAYBE_UNUSED -#endif - -#endif // BENCHMARK_INTERNAL_MACROS_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/json_reporter.cc b/interpreter/llvm/src/utils/benchmark/src/json_reporter.cc deleted file mode 100644 index 685d6b097dcf1..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/json_reporter.cc +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" - -#include -#include -#include -#include -#include -#include -#include // for setprecision -#include - -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -namespace { - -std::string FormatKV(std::string const& key, std::string const& value) { - return StrFormat("\"%s\": \"%s\"", key.c_str(), value.c_str()); -} - -std::string FormatKV(std::string const& key, const char* value) { - return StrFormat("\"%s\": \"%s\"", key.c_str(), value); -} - -std::string FormatKV(std::string const& key, bool value) { - return StrFormat("\"%s\": %s", key.c_str(), value ? "true" : "false"); -} - -std::string FormatKV(std::string const& key, int64_t value) { - std::stringstream ss; - ss << '"' << key << "\": " << value; - return ss.str(); -} - -std::string FormatKV(std::string const& key, double value) { - std::stringstream ss; - ss << '"' << key << "\": "; - - const auto max_digits10 = std::numeric_limits::max_digits10; - const auto max_fractional_digits10 = max_digits10 - 1; - - ss << std::scientific << std::setprecision(max_fractional_digits10) << value; - return ss.str(); -} - -int64_t RoundDouble(double v) { return static_cast(v + 0.5); } - -} // end namespace - -bool JSONReporter::ReportContext(const Context& context) { - std::ostream& out = GetOutputStream(); - - out << "{\n"; - std::string inner_indent(2, ' '); - - // Open context block and print context information. - out << inner_indent << "\"context\": {\n"; - std::string indent(4, ' '); - - std::string walltime_value = LocalDateTimeString(); - out << indent << FormatKV("date", walltime_value) << ",\n"; - - if (Context::executable_name) { - out << indent << FormatKV("executable", Context::executable_name) << ",\n"; - } - - CPUInfo const& info = context.cpu_info; - out << indent << FormatKV("num_cpus", static_cast(info.num_cpus)) - << ",\n"; - out << indent - << FormatKV("mhz_per_cpu", - RoundDouble(info.cycles_per_second / 1000000.0)) - << ",\n"; - out << indent << FormatKV("cpu_scaling_enabled", info.scaling_enabled) - << ",\n"; - - out << indent << "\"caches\": [\n"; - indent = std::string(6, ' '); - std::string cache_indent(8, ' '); - for (size_t i = 0; i < info.caches.size(); ++i) { - auto& CI = info.caches[i]; - out << indent << "{\n"; - out << cache_indent << FormatKV("type", CI.type) << ",\n"; - out << cache_indent << FormatKV("level", static_cast(CI.level)) - << ",\n"; - out << cache_indent - << FormatKV("size", static_cast(CI.size) * 1000u) << ",\n"; - out << cache_indent - << FormatKV("num_sharing", static_cast(CI.num_sharing)) - << "\n"; - out << indent << "}"; - if (i != info.caches.size() - 1) out << ","; - out << "\n"; - } - indent = std::string(4, ' '); - out << indent << "],\n"; - -#if defined(NDEBUG) - const char build_type[] = "release"; -#else - const char build_type[] = "debug"; -#endif - out << indent << FormatKV("library_build_type", build_type) << "\n"; - // Close context block and open the list of benchmarks. - out << inner_indent << "},\n"; - out << inner_indent << "\"benchmarks\": [\n"; - return true; -} - -void JSONReporter::ReportRuns(std::vector const& reports) { - if (reports.empty()) { - return; - } - std::string indent(4, ' '); - std::ostream& out = GetOutputStream(); - if (!first_report_) { - out << ",\n"; - } - first_report_ = false; - - for (auto it = reports.begin(); it != reports.end(); ++it) { - out << indent << "{\n"; - PrintRunData(*it); - out << indent << '}'; - auto it_cp = it; - if (++it_cp != reports.end()) { - out << ",\n"; - } - } -} - -void JSONReporter::Finalize() { - // Close the list of benchmarks and the top level object. - GetOutputStream() << "\n ]\n}\n"; -} - -void JSONReporter::PrintRunData(Run const& run) { - std::string indent(6, ' '); - std::ostream& out = GetOutputStream(); - out << indent << FormatKV("name", run.benchmark_name) << ",\n"; - if (run.error_occurred) { - out << indent << FormatKV("error_occurred", run.error_occurred) << ",\n"; - out << indent << FormatKV("error_message", run.error_message) << ",\n"; - } - if (!run.report_big_o && !run.report_rms) { - out << indent << FormatKV("iterations", run.iterations) << ",\n"; - out << indent - << FormatKV("real_time", run.GetAdjustedRealTime()) - << ",\n"; - out << indent - << FormatKV("cpu_time", run.GetAdjustedCPUTime()); - out << ",\n" - << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); - } else if (run.report_big_o) { - out << indent - << FormatKV("cpu_coefficient", run.GetAdjustedCPUTime()) - << ",\n"; - out << indent - << FormatKV("real_coefficient", run.GetAdjustedRealTime()) - << ",\n"; - out << indent << FormatKV("big_o", GetBigOString(run.complexity)) << ",\n"; - out << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); - } else if (run.report_rms) { - out << indent - << FormatKV("rms", run.GetAdjustedCPUTime()); - } - if (run.bytes_per_second > 0.0) { - out << ",\n" - << indent - << FormatKV("bytes_per_second", run.bytes_per_second); - } - if (run.items_per_second > 0.0) { - out << ",\n" - << indent - << FormatKV("items_per_second", run.items_per_second); - } - for(auto &c : run.counters) { - out << ",\n" - << indent - << FormatKV(c.first, c.second); - } - if (!run.report_label.empty()) { - out << ",\n" << indent << FormatKV("label", run.report_label); - } - out << '\n'; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/log.h b/interpreter/llvm/src/utils/benchmark/src/log.h deleted file mode 100644 index d06e1031db141..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/log.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef BENCHMARK_LOG_H_ -#define BENCHMARK_LOG_H_ - -#include -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { -namespace internal { - -typedef std::basic_ostream&(EndLType)(std::basic_ostream&); - -class LogType { - friend LogType& GetNullLogInstance(); - friend LogType& GetErrorLogInstance(); - - // FIXME: Add locking to output. - template - friend LogType& operator<<(LogType&, Tp const&); - friend LogType& operator<<(LogType&, EndLType*); - - private: - LogType(std::ostream* out) : out_(out) {} - std::ostream* out_; - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(LogType); -}; - -template -LogType& operator<<(LogType& log, Tp const& value) { - if (log.out_) { - *log.out_ << value; - } - return log; -} - -inline LogType& operator<<(LogType& log, EndLType* m) { - if (log.out_) { - *log.out_ << m; - } - return log; -} - -inline int& LogLevel() { - static int log_level = 0; - return log_level; -} - -inline LogType& GetNullLogInstance() { - static LogType log(nullptr); - return log; -} - -inline LogType& GetErrorLogInstance() { - static LogType log(&std::clog); - return log; -} - -inline LogType& GetLogInstanceForLevel(int level) { - if (level <= LogLevel()) { - return GetErrorLogInstance(); - } - return GetNullLogInstance(); -} - -} // end namespace internal -} // end namespace benchmark - -#define VLOG(x) \ - (::benchmark::internal::GetLogInstanceForLevel(x) << "-- LOG(" << x << "):" \ - " ") - -#endif diff --git a/interpreter/llvm/src/utils/benchmark/src/mutex.h b/interpreter/llvm/src/utils/benchmark/src/mutex.h deleted file mode 100644 index 5f461d05a0c64..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/mutex.h +++ /dev/null @@ -1,155 +0,0 @@ -#ifndef BENCHMARK_MUTEX_H_ -#define BENCHMARK_MUTEX_H_ - -#include -#include - -#include "check.h" - -// Enable thread safety attributes only with clang. -// The attributes can be safely erased when compiling with other compilers. -#if defined(HAVE_THREAD_SAFETY_ATTRIBUTES) -#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) -#else -#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op -#endif - -#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) - -#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) - -#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) - -#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) - -#define ACQUIRED_BEFORE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) - -#define ACQUIRED_AFTER(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) - -#define REQUIRES(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) - -#define REQUIRES_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) - -#define ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) - -#define ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) - -#define RELEASE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) - -#define RELEASE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) - -#define TRY_ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) - -#define TRY_ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) - -#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) - -#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) - -#define ASSERT_SHARED_CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) - -#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) - -#define NO_THREAD_SAFETY_ANALYSIS \ - THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) - -namespace benchmark { - -typedef std::condition_variable Condition; - -// NOTE: Wrappers for std::mutex and std::unique_lock are provided so that -// we can annotate them with thread safety attributes and use the -// -Wthread-safety warning with clang. The standard library types cannot be -// used directly because they do not provided the required annotations. -class CAPABILITY("mutex") Mutex { - public: - Mutex() {} - - void lock() ACQUIRE() { mut_.lock(); } - void unlock() RELEASE() { mut_.unlock(); } - std::mutex& native_handle() { return mut_; } - - private: - std::mutex mut_; -}; - -class SCOPED_CAPABILITY MutexLock { - typedef std::unique_lock MutexLockImp; - - public: - MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle()) {} - ~MutexLock() RELEASE() {} - MutexLockImp& native_handle() { return ml_; } - - private: - MutexLockImp ml_; -}; - -class Barrier { - public: - Barrier(int num_threads) : running_threads_(num_threads) {} - - // Called by each thread - bool wait() EXCLUDES(lock_) { - bool last_thread = false; - { - MutexLock ml(lock_); - last_thread = createBarrier(ml); - } - if (last_thread) phase_condition_.notify_all(); - return last_thread; - } - - void removeThread() EXCLUDES(lock_) { - MutexLock ml(lock_); - --running_threads_; - if (entered_ != 0) phase_condition_.notify_all(); - } - - private: - Mutex lock_; - Condition phase_condition_; - int running_threads_; - - // State for barrier management - int phase_number_ = 0; - int entered_ = 0; // Number of threads that have entered this barrier - - // Enter the barrier and wait until all other threads have also - // entered the barrier. Returns iff this is the last thread to - // enter the barrier. - bool createBarrier(MutexLock& ml) REQUIRES(lock_) { - CHECK_LT(entered_, running_threads_); - entered_++; - if (entered_ < running_threads_) { - // Wait for all threads to enter - int phase_number_cp = phase_number_; - auto cb = [this, phase_number_cp]() { - return this->phase_number_ > phase_number_cp || - entered_ == running_threads_; // A thread has aborted in error - }; - phase_condition_.wait(ml.native_handle(), cb); - if (phase_number_ > phase_number_cp) return false; - // else (running_threads_ == entered_) and we are the last thread. - } - // Last thread has reached the barrier - phase_number_++; - entered_ = 0; - return true; - } -}; - -} // end namespace benchmark - -#endif // BENCHMARK_MUTEX_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/re.h b/interpreter/llvm/src/utils/benchmark/src/re.h deleted file mode 100644 index 924d2f0ba7e51..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/re.h +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef BENCHMARK_RE_H_ -#define BENCHMARK_RE_H_ - -#include "internal_macros.h" - -#if !defined(HAVE_STD_REGEX) && \ - !defined(HAVE_GNU_POSIX_REGEX) && \ - !defined(HAVE_POSIX_REGEX) - // No explicit regex selection; detect based on builtin hints. - #if defined(BENCHMARK_OS_LINUX) || defined(BENCHMARK_OS_APPLE) - #define HAVE_POSIX_REGEX 1 - #elif __cplusplus >= 199711L - #define HAVE_STD_REGEX 1 - #endif -#endif - -// Prefer C regex libraries when compiling w/o exceptions so that we can -// correctly report errors. -#if defined(BENCHMARK_HAS_NO_EXCEPTIONS) && \ - defined(BENCHMARK_HAVE_STD_REGEX) && \ - (defined(HAVE_GNU_POSIX_REGEX) || defined(HAVE_POSIX_REGEX)) - #undef HAVE_STD_REGEX -#endif - -#if defined(HAVE_STD_REGEX) - #include -#elif defined(HAVE_GNU_POSIX_REGEX) - #include -#elif defined(HAVE_POSIX_REGEX) - #include -#else -#error No regular expression backend was found! -#endif -#include - -#include "check.h" - -namespace benchmark { - -// A wrapper around the POSIX regular expression API that provides automatic -// cleanup -class Regex { - public: - Regex() : init_(false) {} - - ~Regex(); - - // Compile a regular expression matcher from spec. Returns true on success. - // - // On failure (and if error is not nullptr), error is populated with a human - // readable error message if an error occurs. - bool Init(const std::string& spec, std::string* error); - - // Returns whether str matches the compiled regular expression. - bool Match(const std::string& str); - - private: - bool init_; -// Underlying regular expression object -#if defined(HAVE_STD_REGEX) - std::regex re_; -#elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX) - regex_t re_; -#else - #error No regular expression backend implementation available -#endif -}; - -#if defined(HAVE_STD_REGEX) - -inline bool Regex::Init(const std::string& spec, std::string* error) { -#ifdef BENCHMARK_HAS_NO_EXCEPTIONS - ((void)error); // suppress unused warning -#else - try { -#endif - re_ = std::regex(spec, std::regex_constants::extended); - init_ = true; -#ifndef BENCHMARK_HAS_NO_EXCEPTIONS - } catch (const std::regex_error& e) { - if (error) { - *error = e.what(); - } - } -#endif - return init_; -} - -inline Regex::~Regex() {} - -inline bool Regex::Match(const std::string& str) { - if (!init_) { - return false; - } - return std::regex_search(str, re_); -} - -#else -inline bool Regex::Init(const std::string& spec, std::string* error) { - int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - if (error) { - size_t needed = regerror(ec, &re_, nullptr, 0); - char* errbuf = new char[needed]; - regerror(ec, &re_, errbuf, needed); - - // regerror returns the number of bytes necessary to null terminate - // the string, so we move that when assigning to error. - CHECK_NE(needed, 0); - error->assign(errbuf, needed - 1); - - delete[] errbuf; - } - - return false; - } - - init_ = true; - return true; -} - -inline Regex::~Regex() { - if (init_) { - regfree(&re_); - } -} - -inline bool Regex::Match(const std::string& str) { - if (!init_) { - return false; - } - return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0; -} -#endif - -} // end namespace benchmark - -#endif // BENCHMARK_RE_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/reporter.cc b/interpreter/llvm/src/utils/benchmark/src/reporter.cc deleted file mode 100644 index 4b40aaec8b94d..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/reporter.cc +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "timers.h" - -#include - -#include -#include -#include - -#include "check.h" - -namespace benchmark { - -BenchmarkReporter::BenchmarkReporter() - : output_stream_(&std::cout), error_stream_(&std::cerr) {} - -BenchmarkReporter::~BenchmarkReporter() {} - -void BenchmarkReporter::PrintBasicContext(std::ostream *out, - Context const &context) { - CHECK(out) << "cannot be null"; - auto &Out = *out; - - Out << LocalDateTimeString() << "\n"; - - if (context.executable_name) - Out << "Running " << context.executable_name << "\n"; - - const CPUInfo &info = context.cpu_info; - Out << "Run on (" << info.num_cpus << " X " - << (info.cycles_per_second / 1000000.0) << " MHz CPU " - << ((info.num_cpus > 1) ? "s" : "") << ")\n"; - if (info.caches.size() != 0) { - Out << "CPU Caches:\n"; - for (auto &CInfo : info.caches) { - Out << " L" << CInfo.level << " " << CInfo.type << " " - << (CInfo.size / 1000) << "K"; - if (CInfo.num_sharing != 0) - Out << " (x" << (info.num_cpus / CInfo.num_sharing) << ")"; - Out << "\n"; - } - } - - if (info.scaling_enabled) { - Out << "***WARNING*** CPU scaling is enabled, the benchmark " - "real time measurements may be noisy and will incur extra " - "overhead.\n"; - } - -#ifndef NDEBUG - Out << "***WARNING*** Library was built as DEBUG. Timings may be " - "affected.\n"; -#endif -} - -// No initializer because it's already initialized to NULL. -const char* BenchmarkReporter::Context::executable_name; - -BenchmarkReporter::Context::Context() : cpu_info(CPUInfo::Get()) {} - -double BenchmarkReporter::Run::GetAdjustedRealTime() const { - double new_time = real_accumulated_time * GetTimeUnitMultiplier(time_unit); - if (iterations != 0) new_time /= static_cast(iterations); - return new_time; -} - -double BenchmarkReporter::Run::GetAdjustedCPUTime() const { - double new_time = cpu_accumulated_time * GetTimeUnitMultiplier(time_unit); - if (iterations != 0) new_time /= static_cast(iterations); - return new_time; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/sleep.cc b/interpreter/llvm/src/utils/benchmark/src/sleep.cc deleted file mode 100644 index 1512ac90f7ead..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/sleep.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "sleep.h" - -#include -#include -#include - -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#endif - -namespace benchmark { -#ifdef BENCHMARK_OS_WINDOWS -// Window's Sleep takes milliseconds argument. -void SleepForMilliseconds(int milliseconds) { Sleep(milliseconds); } -void SleepForSeconds(double seconds) { - SleepForMilliseconds(static_cast(kNumMillisPerSecond * seconds)); -} -#else // BENCHMARK_OS_WINDOWS -void SleepForMicroseconds(int microseconds) { - struct timespec sleep_time; - sleep_time.tv_sec = microseconds / kNumMicrosPerSecond; - sleep_time.tv_nsec = (microseconds % kNumMicrosPerSecond) * kNumNanosPerMicro; - while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) - ; // Ignore signals and wait for the full interval to elapse. -} - -void SleepForMilliseconds(int milliseconds) { - SleepForMicroseconds(milliseconds * kNumMicrosPerMilli); -} - -void SleepForSeconds(double seconds) { - SleepForMicroseconds(static_cast(seconds * kNumMicrosPerSecond)); -} -#endif // BENCHMARK_OS_WINDOWS -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/sleep.h b/interpreter/llvm/src/utils/benchmark/src/sleep.h deleted file mode 100644 index f98551afe2849..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/sleep.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef BENCHMARK_SLEEP_H_ -#define BENCHMARK_SLEEP_H_ - -namespace benchmark { -const int kNumMillisPerSecond = 1000; -const int kNumMicrosPerMilli = 1000; -const int kNumMicrosPerSecond = kNumMillisPerSecond * 1000; -const int kNumNanosPerMicro = 1000; -const int kNumNanosPerSecond = kNumNanosPerMicro * kNumMicrosPerSecond; - -void SleepForMilliseconds(int milliseconds); -void SleepForSeconds(double seconds); -} // end namespace benchmark - -#endif // BENCHMARK_SLEEP_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/statistics.cc b/interpreter/llvm/src/utils/benchmark/src/statistics.cc deleted file mode 100644 index 1c91e1015ab6f..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/statistics.cc +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// Copyright 2017 Roman Lebedev. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -#include -#include -#include -#include -#include -#include "check.h" -#include "statistics.h" - -namespace benchmark { - -auto StatisticsSum = [](const std::vector& v) { - return std::accumulate(v.begin(), v.end(), 0.0); -}; - -double StatisticsMean(const std::vector& v) { - if (v.empty()) return 0.0; - return StatisticsSum(v) * (1.0 / v.size()); -} - -double StatisticsMedian(const std::vector& v) { - if (v.size() < 3) return StatisticsMean(v); - std::vector copy(v); - - auto center = copy.begin() + v.size() / 2; - std::nth_element(copy.begin(), center, copy.end()); - - // did we have an odd number of samples? - // if yes, then center is the median - // it no, then we are looking for the average between center and the value before - if(v.size() % 2 == 1) - return *center; - auto center2 = copy.begin() + v.size() / 2 - 1; - std::nth_element(copy.begin(), center2, copy.end()); - return (*center + *center2) / 2.0; -} - -// Return the sum of the squares of this sample set -auto SumSquares = [](const std::vector& v) { - return std::inner_product(v.begin(), v.end(), v.begin(), 0.0); -}; - -auto Sqr = [](const double dat) { return dat * dat; }; -auto Sqrt = [](const double dat) { - // Avoid NaN due to imprecision in the calculations - if (dat < 0.0) return 0.0; - return std::sqrt(dat); -}; - -double StatisticsStdDev(const std::vector& v) { - const auto mean = StatisticsMean(v); - if (v.empty()) return mean; - - // Sample standard deviation is undefined for n = 1 - if (v.size() == 1) - return 0.0; - - const double avg_squares = SumSquares(v) * (1.0 / v.size()); - return Sqrt(v.size() / (v.size() - 1.0) * (avg_squares - Sqr(mean))); -} - -std::vector ComputeStats( - const std::vector& reports) { - typedef BenchmarkReporter::Run Run; - std::vector results; - - auto error_count = - std::count_if(reports.begin(), reports.end(), - [](Run const& run) { return run.error_occurred; }); - - if (reports.size() - error_count < 2) { - // We don't report aggregated data if there was a single run. - return results; - } - - // Accumulators. - std::vector real_accumulated_time_stat; - std::vector cpu_accumulated_time_stat; - std::vector bytes_per_second_stat; - std::vector items_per_second_stat; - - real_accumulated_time_stat.reserve(reports.size()); - cpu_accumulated_time_stat.reserve(reports.size()); - bytes_per_second_stat.reserve(reports.size()); - items_per_second_stat.reserve(reports.size()); - - // All repetitions should be run with the same number of iterations so we - // can take this information from the first benchmark. - int64_t const run_iterations = reports.front().iterations; - // create stats for user counters - struct CounterStat { - Counter c; - std::vector s; - }; - std::map< std::string, CounterStat > counter_stats; - for(Run const& r : reports) { - for(auto const& cnt : r.counters) { - auto it = counter_stats.find(cnt.first); - if(it == counter_stats.end()) { - counter_stats.insert({cnt.first, {cnt.second, std::vector{}}}); - it = counter_stats.find(cnt.first); - it->second.s.reserve(reports.size()); - } else { - CHECK_EQ(counter_stats[cnt.first].c.flags, cnt.second.flags); - } - } - } - - // Populate the accumulators. - for (Run const& run : reports) { - CHECK_EQ(reports[0].benchmark_name, run.benchmark_name); - CHECK_EQ(run_iterations, run.iterations); - if (run.error_occurred) continue; - real_accumulated_time_stat.emplace_back(run.real_accumulated_time); - cpu_accumulated_time_stat.emplace_back(run.cpu_accumulated_time); - items_per_second_stat.emplace_back(run.items_per_second); - bytes_per_second_stat.emplace_back(run.bytes_per_second); - // user counters - for(auto const& cnt : run.counters) { - auto it = counter_stats.find(cnt.first); - CHECK_NE(it, counter_stats.end()); - it->second.s.emplace_back(cnt.second); - } - } - - // Only add label if it is same for all runs - std::string report_label = reports[0].report_label; - for (std::size_t i = 1; i < reports.size(); i++) { - if (reports[i].report_label != report_label) { - report_label = ""; - break; - } - } - - for(const auto& Stat : *reports[0].statistics) { - // Get the data from the accumulator to BenchmarkReporter::Run's. - Run data; - data.benchmark_name = reports[0].benchmark_name + "_" + Stat.name_; - data.report_label = report_label; - data.iterations = run_iterations; - - data.real_accumulated_time = Stat.compute_(real_accumulated_time_stat); - data.cpu_accumulated_time = Stat.compute_(cpu_accumulated_time_stat); - data.bytes_per_second = Stat.compute_(bytes_per_second_stat); - data.items_per_second = Stat.compute_(items_per_second_stat); - - data.time_unit = reports[0].time_unit; - - // user counters - for(auto const& kv : counter_stats) { - const auto uc_stat = Stat.compute_(kv.second.s); - auto c = Counter(uc_stat, counter_stats[kv.first].c.flags); - data.counters[kv.first] = c; - } - - results.push_back(data); - } - - return results; -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/statistics.h b/interpreter/llvm/src/utils/benchmark/src/statistics.h deleted file mode 100644 index 7eccc85536a5f..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/statistics.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// Copyright 2017 Roman Lebedev. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef STATISTICS_H_ -#define STATISTICS_H_ - -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// Return a vector containing the mean, median and standard devation information -// (and any user-specified info) for the specified list of reports. If 'reports' -// contains less than two non-errored runs an empty vector is returned -std::vector ComputeStats( - const std::vector& reports); - -double StatisticsMean(const std::vector& v); -double StatisticsMedian(const std::vector& v); -double StatisticsStdDev(const std::vector& v); - -} // end namespace benchmark - -#endif // STATISTICS_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/string_util.cc b/interpreter/llvm/src/utils/benchmark/src/string_util.cc deleted file mode 100644 index ebc3acebd2a80..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/string_util.cc +++ /dev/null @@ -1,172 +0,0 @@ -#include "string_util.h" - -#include -#include -#include -#include -#include -#include - -#include "arraysize.h" - -namespace benchmark { -namespace { - -// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. -const char kBigSIUnits[] = "kMGTPEZY"; -// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. -const char kBigIECUnits[] = "KMGTPEZY"; -// milli, micro, nano, pico, femto, atto, zepto, yocto. -const char kSmallSIUnits[] = "munpfazy"; - -// We require that all three arrays have the same size. -static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), - "SI and IEC unit arrays must be the same size"); -static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), - "Small SI and Big SI unit arrays must be the same size"); - -static const int64_t kUnitsSize = arraysize(kBigSIUnits); - -void ToExponentAndMantissa(double val, double thresh, int precision, - double one_k, std::string* mantissa, - int64_t* exponent) { - std::stringstream mantissa_stream; - - if (val < 0) { - mantissa_stream << "-"; - val = -val; - } - - // Adjust threshold so that it never excludes things which can't be rendered - // in 'precision' digits. - const double adjusted_threshold = - std::max(thresh, 1.0 / std::pow(10.0, precision)); - const double big_threshold = adjusted_threshold * one_k; - const double small_threshold = adjusted_threshold; - // Values in ]simple_threshold,small_threshold[ will be printed as-is - const double simple_threshold = 0.01; - - if (val > big_threshold) { - // Positive powers - double scaled = val; - for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { - scaled /= one_k; - if (scaled <= big_threshold) { - mantissa_stream << scaled; - *exponent = i + 1; - *mantissa = mantissa_stream.str(); - return; - } - } - mantissa_stream << val; - *exponent = 0; - } else if (val < small_threshold) { - // Negative powers - if (val < simple_threshold) { - double scaled = val; - for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { - scaled *= one_k; - if (scaled >= small_threshold) { - mantissa_stream << scaled; - *exponent = -static_cast(i + 1); - *mantissa = mantissa_stream.str(); - return; - } - } - } - mantissa_stream << val; - *exponent = 0; - } else { - mantissa_stream << val; - *exponent = 0; - } - *mantissa = mantissa_stream.str(); -} - -std::string ExponentToPrefix(int64_t exponent, bool iec) { - if (exponent == 0) return ""; - - const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); - if (index >= kUnitsSize) return ""; - - const char* array = - (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); - if (iec) - return array[index] + std::string("i"); - else - return std::string(1, array[index]); -} - -std::string ToBinaryStringFullySpecified(double value, double threshold, - int precision, double one_k = 1024.0) { - std::string mantissa; - int64_t exponent; - ToExponentAndMantissa(value, threshold, precision, one_k, &mantissa, - &exponent); - return mantissa + ExponentToPrefix(exponent, false); -} - -} // end namespace - -void AppendHumanReadable(int n, std::string* str) { - std::stringstream ss; - // Round down to the nearest SI prefix. - ss << ToBinaryStringFullySpecified(n, 1.0, 0); - *str += ss.str(); -} - -std::string HumanReadableNumber(double n, double one_k) { - // 1.1 means that figures up to 1.1k should be shown with the next unit down; - // this softens edge effects. - // 1 means that we should show one decimal place of precision. - return ToBinaryStringFullySpecified(n, 1.1, 1, one_k); -} - -std::string StrFormatImp(const char* msg, va_list args) { - // we might need a second shot at this, so pre-emptivly make a copy - va_list args_cp; - va_copy(args_cp, args); - - // TODO(ericwf): use std::array for first attempt to avoid one memory - // allocation guess what the size might be - std::array local_buff; - std::size_t size = local_buff.size(); - // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation - // in the android-ndk - auto ret = vsnprintf(local_buff.data(), size, msg, args_cp); - - va_end(args_cp); - - // handle empty expansion - if (ret == 0) return std::string{}; - if (static_cast(ret) < size) - return std::string(local_buff.data()); - - // we did not provide a long enough buffer on our first attempt. - // add 1 to size to account for null-byte in size cast to prevent overflow - size = static_cast(ret) + 1; - auto buff_ptr = std::unique_ptr(new char[size]); - // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation - // in the android-ndk - ret = vsnprintf(buff_ptr.get(), size, msg, args); - return std::string(buff_ptr.get()); -} - -std::string StrFormat(const char* format, ...) { - va_list args; - va_start(args, format); - std::string tmp = StrFormatImp(format, args); - va_end(args); - return tmp; -} - -void ReplaceAll(std::string* str, const std::string& from, - const std::string& to) { - std::size_t start = 0; - while ((start = str->find(from, start)) != std::string::npos) { - str->replace(start, from.length(), to); - start += to.length(); - } -} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/string_util.h b/interpreter/llvm/src/utils/benchmark/src/string_util.h deleted file mode 100644 index e70e76987245e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/string_util.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef BENCHMARK_STRING_UTIL_H_ -#define BENCHMARK_STRING_UTIL_H_ - -#include -#include -#include -#include "internal_macros.h" - -namespace benchmark { - -void AppendHumanReadable(int n, std::string* str); - -std::string HumanReadableNumber(double n, double one_k = 1024.0); - -std::string StrFormat(const char* format, ...); - -inline std::ostream& StrCatImp(std::ostream& out) BENCHMARK_NOEXCEPT { - return out; -} - -template -inline std::ostream& StrCatImp(std::ostream& out, First&& f, - Rest&&... rest) { - out << std::forward(f); - return StrCatImp(out, std::forward(rest)...); -} - -template -inline std::string StrCat(Args&&... args) { - std::ostringstream ss; - StrCatImp(ss, std::forward(args)...); - return ss.str(); -} - -void ReplaceAll(std::string* str, const std::string& from, - const std::string& to); - -} // end namespace benchmark - -#endif // BENCHMARK_STRING_UTIL_H_ diff --git a/interpreter/llvm/src/utils/benchmark/src/sysinfo.cc b/interpreter/llvm/src/utils/benchmark/src/sysinfo.cc deleted file mode 100644 index 01dd8a0317b05..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/sysinfo.cc +++ /dev/null @@ -1,585 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA -#include -#include -#else -#include -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD -#include -#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \ - defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD -#define BENCHMARK_HAS_SYSCTL -#include -#endif -#endif -#if defined(BENCHMARK_OS_SOLARIS) -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "cycleclock.h" -#include "internal_macros.h" -#include "log.h" -#include "sleep.h" -#include "string_util.h" - -namespace benchmark { -namespace { - -void PrintImp(std::ostream& out) { out << std::endl; } - -template -void PrintImp(std::ostream& out, First&& f, Rest&&... rest) { - out << std::forward(f); - PrintImp(out, std::forward(rest)...); -} - -template -BENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) { - PrintImp(std::cerr, std::forward(args)...); - std::exit(EXIT_FAILURE); -} - -#ifdef BENCHMARK_HAS_SYSCTL - -/// ValueUnion - A type used to correctly alias the byte-for-byte output of -/// `sysctl` with the result type it's to be interpreted as. -struct ValueUnion { - union DataT { - uint32_t uint32_value; - uint64_t uint64_value; - // For correct aliasing of union members from bytes. - char bytes[8]; - }; - using DataPtr = std::unique_ptr; - - // The size of the data union member + its trailing array size. - size_t Size; - DataPtr Buff; - - public: - ValueUnion() : Size(0), Buff(nullptr, &std::free) {} - - explicit ValueUnion(size_t BuffSize) - : Size(sizeof(DataT) + BuffSize), - Buff(::new (std::malloc(Size)) DataT(), &std::free) {} - - ValueUnion(ValueUnion&& other) = default; - - explicit operator bool() const { return bool(Buff); } - - char* data() const { return Buff->bytes; } - - std::string GetAsString() const { return std::string(data()); } - - int64_t GetAsInteger() const { - if (Size == sizeof(Buff->uint32_value)) - return static_cast(Buff->uint32_value); - else if (Size == sizeof(Buff->uint64_value)) - return static_cast(Buff->uint64_value); - BENCHMARK_UNREACHABLE(); - } - - uint64_t GetAsUnsigned() const { - if (Size == sizeof(Buff->uint32_value)) - return Buff->uint32_value; - else if (Size == sizeof(Buff->uint64_value)) - return Buff->uint64_value; - BENCHMARK_UNREACHABLE(); - } - - template - std::array GetAsArray() { - const int ArrSize = sizeof(T) * N; - CHECK_LE(ArrSize, Size); - std::array Arr; - std::memcpy(Arr.data(), data(), ArrSize); - return Arr; - } -}; - -ValueUnion GetSysctlImp(std::string const& Name) { -#if defined BENCHMARK_OS_OPENBSD - int mib[2]; - - mib[0] = CTL_HW; - if ((Name == "hw.ncpu") || (Name == "hw.cpuspeed")){ - ValueUnion buff(sizeof(int)); - - if (Name == "hw.ncpu") { - mib[1] = HW_NCPU; - } else { - mib[1] = HW_CPUSPEED; - } - - if (sysctl(mib, 2, buff.data(), &buff.Size, nullptr, 0) == -1) { - return ValueUnion(); - } - return buff; - } - return ValueUnion(); -#else - size_t CurBuffSize = 0; - if (sysctlbyname(Name.c_str(), nullptr, &CurBuffSize, nullptr, 0) == -1) - return ValueUnion(); - - ValueUnion buff(CurBuffSize); - if (sysctlbyname(Name.c_str(), buff.data(), &buff.Size, nullptr, 0) == 0) - return buff; - return ValueUnion(); -#endif -} - -BENCHMARK_MAYBE_UNUSED -bool GetSysctl(std::string const& Name, std::string* Out) { - Out->clear(); - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - Out->assign(Buff.data()); - return true; -} - -template ::value>::type> -bool GetSysctl(std::string const& Name, Tp* Out) { - *Out = 0; - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = static_cast(Buff.GetAsUnsigned()); - return true; -} - -template -bool GetSysctl(std::string const& Name, std::array* Out) { - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = Buff.GetAsArray(); - return true; -} -#endif - -template -bool ReadFromFile(std::string const& fname, ArgT* arg) { - *arg = ArgT(); - std::ifstream f(fname.c_str()); - if (!f.is_open()) return false; - f >> *arg; - return f.good(); -} - -bool CpuScalingEnabled(int num_cpus) { - // We don't have a valid CPU count, so don't even bother. - if (num_cpus <= 0) return false; -#ifndef BENCHMARK_OS_WINDOWS - // On Linux, the CPUfreq subsystem exposes CPU information as files on the - // local file system. If reading the exported files fails, then we may not be - // running on Linux, so we silently ignore all the read errors. - std::string res; - for (int cpu = 0; cpu < num_cpus; ++cpu) { - std::string governor_file = - StrCat("/sys/devices/system/cpu/cpu", cpu, "/cpufreq/scaling_governor"); - if (ReadFromFile(governor_file, &res) && res != "performance") return true; - } -#endif - return false; -} - -int CountSetBitsInCPUMap(std::string Val) { - auto CountBits = [](std::string Part) { - using CPUMask = std::bitset; - Part = "0x" + Part; - CPUMask Mask(std::stoul(Part, nullptr, 16)); - return static_cast(Mask.count()); - }; - size_t Pos; - int total = 0; - while ((Pos = Val.find(',')) != std::string::npos) { - total += CountBits(Val.substr(0, Pos)); - Val = Val.substr(Pos + 1); - } - if (!Val.empty()) { - total += CountBits(Val); - } - return total; -} - -BENCHMARK_MAYBE_UNUSED -std::vector GetCacheSizesFromKVFS() { - std::vector res; - std::string dir = "/sys/devices/system/cpu/cpu0/cache/"; - int Idx = 0; - while (true) { - CPUInfo::CacheInfo info; - std::string FPath = StrCat(dir, "index", Idx++, "/"); - std::ifstream f(StrCat(FPath, "size").c_str()); - if (!f.is_open()) break; - std::string suffix; - f >> info.size; - if (f.fail()) - PrintErrorAndDie("Failed while reading file '", FPath, "size'"); - if (f.good()) { - f >> suffix; - if (f.bad()) - PrintErrorAndDie( - "Invalid cache size format: failed to read size suffix"); - else if (f && suffix != "K") - PrintErrorAndDie("Invalid cache size format: Expected bytes ", suffix); - else if (suffix == "K") - info.size *= 1000; - } - if (!ReadFromFile(StrCat(FPath, "type"), &info.type)) - PrintErrorAndDie("Failed to read from file ", FPath, "type"); - if (!ReadFromFile(StrCat(FPath, "level"), &info.level)) - PrintErrorAndDie("Failed to read from file ", FPath, "level"); - std::string map_str; - if (!ReadFromFile(StrCat(FPath, "shared_cpu_map"), &map_str)) - PrintErrorAndDie("Failed to read from file ", FPath, "shared_cpu_map"); - info.num_sharing = CountSetBitsInCPUMap(map_str); - res.push_back(info); - } - - return res; -} - -#ifdef BENCHMARK_OS_MACOSX -std::vector GetCacheSizesMacOSX() { - std::vector res; - std::array CacheCounts{{0, 0, 0, 0}}; - GetSysctl("hw.cacheconfig", &CacheCounts); - - struct { - std::string name; - std::string type; - int level; - uint64_t num_sharing; - } Cases[] = {{"hw.l1dcachesize", "Data", 1, CacheCounts[1]}, - {"hw.l1icachesize", "Instruction", 1, CacheCounts[1]}, - {"hw.l2cachesize", "Unified", 2, CacheCounts[2]}, - {"hw.l3cachesize", "Unified", 3, CacheCounts[3]}}; - for (auto& C : Cases) { - int val; - if (!GetSysctl(C.name, &val)) continue; - CPUInfo::CacheInfo info; - info.type = C.type; - info.level = C.level; - info.size = val; - info.num_sharing = static_cast(C.num_sharing); - res.push_back(std::move(info)); - } - return res; -} -#elif defined(BENCHMARK_OS_WINDOWS) -std::vector GetCacheSizesWindows() { - std::vector res; - DWORD buffer_size = 0; - using PInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION; - using CInfo = CACHE_DESCRIPTOR; - - using UPtr = std::unique_ptr; - GetLogicalProcessorInformation(nullptr, &buffer_size); - UPtr buff((PInfo*)malloc(buffer_size), &std::free); - if (!GetLogicalProcessorInformation(buff.get(), &buffer_size)) - PrintErrorAndDie("Failed during call to GetLogicalProcessorInformation: ", - GetLastError()); - - PInfo* it = buff.get(); - PInfo* end = buff.get() + (buffer_size / sizeof(PInfo)); - - for (; it != end; ++it) { - if (it->Relationship != RelationCache) continue; - using BitSet = std::bitset; - BitSet B(it->ProcessorMask); - // To prevent duplicates, only consider caches where CPU 0 is specified - if (!B.test(0)) continue; - CInfo* Cache = &it->Cache; - CPUInfo::CacheInfo C; - C.num_sharing = static_cast(B.count()); - C.level = Cache->Level; - C.size = Cache->Size; - C.type = "Unknown"; - switch (Cache->Type) { - case CacheUnified: - C.type = "Unified"; - break; - case CacheInstruction: - C.type = "Instruction"; - break; - case CacheData: - C.type = "Data"; - break; - case CacheTrace: - C.type = "Trace"; - break; - } - res.push_back(C); - } - return res; -} -#endif - -std::vector GetCacheSizes() { -#ifdef BENCHMARK_OS_MACOSX - return GetCacheSizesMacOSX(); -#elif defined(BENCHMARK_OS_WINDOWS) - return GetCacheSizesWindows(); -#else - return GetCacheSizesFromKVFS(); -#endif -} - -int GetNumCPUs() { -#ifdef BENCHMARK_HAS_SYSCTL - int NumCPU = -1; - if (GetSysctl("hw.ncpu", &NumCPU)) return NumCPU; - fprintf(stderr, "Err: %s\n", strerror(errno)); - std::exit(EXIT_FAILURE); -#elif defined(BENCHMARK_OS_WINDOWS) - SYSTEM_INFO sysinfo; - // Use memset as opposed to = {} to avoid GCC missing initializer false - // positives. - std::memset(&sysinfo, 0, sizeof(SYSTEM_INFO)); - GetSystemInfo(&sysinfo); - return sysinfo.dwNumberOfProcessors; // number of logical - // processors in the current - // group -#elif defined(BENCHMARK_OS_SOLARIS) - // Returns -1 in case of a failure. - int NumCPU = sysconf(_SC_NPROCESSORS_ONLN); - if (NumCPU < 0) { - fprintf(stderr, - "sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\n", - strerror(errno)); - } - return NumCPU; -#else - int NumCPUs = 0; - int MaxID = -1; - std::ifstream f("/proc/cpuinfo"); - if (!f.is_open()) { - std::cerr << "failed to open /proc/cpuinfo\n"; - return -1; - } - const std::string Key = "processor"; - std::string ln; - while (std::getline(f, ln)) { - if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); - std::string value; - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); - if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) { - NumCPUs++; - if (!value.empty()) { - int CurID = std::stoi(value); - MaxID = std::max(CurID, MaxID); - } - } - } - if (f.bad()) { - std::cerr << "Failure reading /proc/cpuinfo\n"; - return -1; - } - if (!f.eof()) { - std::cerr << "Failed to read to end of /proc/cpuinfo\n"; - return -1; - } - f.close(); - - if ((MaxID + 1) != NumCPUs) { - fprintf(stderr, - "CPU ID assignments in /proc/cpuinfo seem messed up." - " This is usually caused by a bad BIOS.\n"); - } - return NumCPUs; -#endif - BENCHMARK_UNREACHABLE(); -} - -double GetCPUCyclesPerSecond() { -#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN - long freq; - - // If the kernel is exporting the tsc frequency use that. There are issues - // where cpuinfo_max_freq cannot be relied on because the BIOS may be - // exporintg an invalid p-state (on x86) or p-states may be used to put the - // processor in a new mode (turbo mode). Essentially, those frequencies - // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as - // well. - if (ReadFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq) - // If CPU scaling is in effect, we want to use the *maximum* frequency, - // not whatever CPU speed some random processor happens to be using now. - || ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", - &freq)) { - // The value is in kHz (as the file name suggests). For example, on a - // 2GHz warpstation, the file contains the value "2000000". - return freq * 1000.0; - } - - const double error_value = -1; - double bogo_clock = error_value; - - std::ifstream f("/proc/cpuinfo"); - if (!f.is_open()) { - std::cerr << "failed to open /proc/cpuinfo\n"; - return error_value; - } - - auto startsWithKey = [](std::string const& Value, std::string const& Key) { - if (Key.size() > Value.size()) return false; - auto Cmp = [&](char X, char Y) { - return std::tolower(X) == std::tolower(Y); - }; - return std::equal(Key.begin(), Key.end(), Value.begin(), Cmp); - }; - - std::string ln; - while (std::getline(f, ln)) { - if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); - std::string value; - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); - // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only - // accept positive values. Some environments (virtual machines) report zero, - // which would cause infinite looping in WallTime_Init. - if (startsWithKey(ln, "cpu MHz")) { - if (!value.empty()) { - double cycles_per_second = std::stod(value) * 1000000.0; - if (cycles_per_second > 0) return cycles_per_second; - } - } else if (startsWithKey(ln, "bogomips")) { - if (!value.empty()) { - bogo_clock = std::stod(value) * 1000000.0; - if (bogo_clock < 0.0) bogo_clock = error_value; - } - } - } - if (f.bad()) { - std::cerr << "Failure reading /proc/cpuinfo\n"; - return error_value; - } - if (!f.eof()) { - std::cerr << "Failed to read to end of /proc/cpuinfo\n"; - return error_value; - } - f.close(); - // If we found the bogomips clock, but nothing better, we'll use it (but - // we're not happy about it); otherwise, fallback to the rough estimation - // below. - if (bogo_clock >= 0.0) return bogo_clock; - -#elif defined BENCHMARK_HAS_SYSCTL - constexpr auto* FreqStr = -#if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD) - "machdep.tsc_freq"; -#elif defined BENCHMARK_OS_OPENBSD - "hw.cpuspeed"; -#else - "hw.cpufrequency"; -#endif - unsigned long long hz = 0; -#if defined BENCHMARK_OS_OPENBSD - if (GetSysctl(FreqStr, &hz)) return hz * 1000000; -#else - if (GetSysctl(FreqStr, &hz)) return hz; -#endif - fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", - FreqStr, strerror(errno)); - -#elif defined BENCHMARK_OS_WINDOWS - // In NT, read MHz from the registry. If we fail to do so or we're in win9x - // then make a crude estimate. - DWORD data, data_size = sizeof(data); - if (IsWindowsXPOrGreater() && - SUCCEEDED( - SHGetValueA(HKEY_LOCAL_MACHINE, - "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - "~MHz", nullptr, &data, &data_size))) - return static_cast((int64_t)data * - (int64_t)(1000 * 1000)); // was mhz -#elif defined (BENCHMARK_OS_SOLARIS) - kstat_ctl_t *kc = kstat_open(); - if (!kc) { - std::cerr << "failed to open /dev/kstat\n"; - return -1; - } - kstat_t *ksp = kstat_lookup(kc, (char*)"cpu_info", -1, (char*)"cpu_info0"); - if (!ksp) { - std::cerr << "failed to lookup in /dev/kstat\n"; - return -1; - } - if (kstat_read(kc, ksp, NULL) < 0) { - std::cerr << "failed to read from /dev/kstat\n"; - return -1; - } - kstat_named_t *knp = - (kstat_named_t*)kstat_data_lookup(ksp, (char*)"current_clock_Hz"); - if (!knp) { - std::cerr << "failed to lookup data in /dev/kstat\n"; - return -1; - } - if (knp->data_type != KSTAT_DATA_UINT64) { - std::cerr << "current_clock_Hz is of unexpected data type: " - << knp->data_type << "\n"; - return -1; - } - double clock_hz = knp->value.ui64; - kstat_close(kc); - return clock_hz; -#endif - // If we've fallen through, attempt to roughly estimate the CPU clock rate. - const int estimate_time_ms = 1000; - const auto start_ticks = cycleclock::Now(); - SleepForMilliseconds(estimate_time_ms); - return static_cast(cycleclock::Now() - start_ticks); -} - -} // end namespace - -const CPUInfo& CPUInfo::Get() { - static const CPUInfo* info = new CPUInfo(); - return *info; -} - -CPUInfo::CPUInfo() - : num_cpus(GetNumCPUs()), - cycles_per_second(GetCPUCyclesPerSecond()), - caches(GetCacheSizes()), - scaling_enabled(CpuScalingEnabled(num_cpus)) {} - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/thread_manager.h b/interpreter/llvm/src/utils/benchmark/src/thread_manager.h deleted file mode 100644 index 82b4d72b62fbe..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/thread_manager.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef BENCHMARK_THREAD_MANAGER_H -#define BENCHMARK_THREAD_MANAGER_H - -#include - -#include "benchmark/benchmark.h" -#include "mutex.h" - -namespace benchmark { -namespace internal { - -class ThreadManager { - public: - ThreadManager(int num_threads) - : alive_threads_(num_threads), start_stop_barrier_(num_threads) {} - - Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) { - return benchmark_mutex_; - } - - bool StartStopBarrier() EXCLUDES(end_cond_mutex_) { - return start_stop_barrier_.wait(); - } - - void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) { - start_stop_barrier_.removeThread(); - if (--alive_threads_ == 0) { - MutexLock lock(end_cond_mutex_); - end_condition_.notify_all(); - } - } - - void WaitForAllThreads() EXCLUDES(end_cond_mutex_) { - MutexLock lock(end_cond_mutex_); - end_condition_.wait(lock.native_handle(), - [this]() { return alive_threads_ == 0; }); - } - - public: - struct Result { - int64_t iterations = 0; - double real_time_used = 0; - double cpu_time_used = 0; - double manual_time_used = 0; - int64_t bytes_processed = 0; - int64_t items_processed = 0; - int64_t complexity_n = 0; - std::string report_label_; - std::string error_message_; - bool has_error_ = false; - UserCounters counters; - }; - GUARDED_BY(GetBenchmarkMutex()) Result results; - - private: - mutable Mutex benchmark_mutex_; - std::atomic alive_threads_; - Barrier start_stop_barrier_; - Mutex end_cond_mutex_; - Condition end_condition_; -}; - -} // namespace internal -} // namespace benchmark - -#endif // BENCHMARK_THREAD_MANAGER_H diff --git a/interpreter/llvm/src/utils/benchmark/src/thread_timer.h b/interpreter/llvm/src/utils/benchmark/src/thread_timer.h deleted file mode 100644 index eaf108e017dc5..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/thread_timer.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef BENCHMARK_THREAD_TIMER_H -#define BENCHMARK_THREAD_TIMER_H - -#include "check.h" -#include "timers.h" - -namespace benchmark { -namespace internal { - -class ThreadTimer { - public: - ThreadTimer() = default; - - // Called by each thread - void StartTimer() { - running_ = true; - start_real_time_ = ChronoClockNow(); - start_cpu_time_ = ThreadCPUUsage(); - } - - // Called by each thread - void StopTimer() { - CHECK(running_); - running_ = false; - real_time_used_ += ChronoClockNow() - start_real_time_; - // Floating point error can result in the subtraction producing a negative - // time. Guard against that. - cpu_time_used_ += std::max(ThreadCPUUsage() - start_cpu_time_, 0); - } - - // Called by each thread - void SetIterationTime(double seconds) { manual_time_used_ += seconds; } - - bool running() const { return running_; } - - // REQUIRES: timer is not running - double real_time_used() { - CHECK(!running_); - return real_time_used_; - } - - // REQUIRES: timer is not running - double cpu_time_used() { - CHECK(!running_); - return cpu_time_used_; - } - - // REQUIRES: timer is not running - double manual_time_used() { - CHECK(!running_); - return manual_time_used_; - } - - private: - bool running_ = false; // Is the timer running - double start_real_time_ = 0; // If running_ - double start_cpu_time_ = 0; // If running_ - - // Accumulated time so far (does not contain current slice if running_) - double real_time_used_ = 0; - double cpu_time_used_ = 0; - // Manually set iteration time. User sets this with SetIterationTime(seconds). - double manual_time_used_ = 0; -}; - -} // namespace internal -} // namespace benchmark - -#endif // BENCHMARK_THREAD_TIMER_H diff --git a/interpreter/llvm/src/utils/benchmark/src/timers.cc b/interpreter/llvm/src/utils/benchmark/src/timers.cc deleted file mode 100644 index 7613ff92c6ef0..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/timers.cc +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "timers.h" -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA -#include -#include -#else -#include -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD -#include -#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX -#include -#endif -#if defined(BENCHMARK_OS_MACOSX) -#include -#include -#include -#endif -#endif - -#ifdef BENCHMARK_OS_EMSCRIPTEN -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "log.h" -#include "sleep.h" -#include "string_util.h" - -namespace benchmark { - -// Suppress unused warnings on helper functions. -#if defined(__GNUC__) -#pragma GCC diagnostic ignored "-Wunused-function" -#endif - -namespace { -#if defined(BENCHMARK_OS_WINDOWS) -double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) { - ULARGE_INTEGER kernel; - ULARGE_INTEGER user; - kernel.HighPart = kernel_time.dwHighDateTime; - kernel.LowPart = kernel_time.dwLowDateTime; - user.HighPart = user_time.dwHighDateTime; - user.LowPart = user_time.dwLowDateTime; - return (static_cast(kernel.QuadPart) + - static_cast(user.QuadPart)) * - 1e-7; -} -#elif !defined(BENCHMARK_OS_FUCHSIA) -double MakeTime(struct rusage const& ru) { - return (static_cast(ru.ru_utime.tv_sec) + - static_cast(ru.ru_utime.tv_usec) * 1e-6 + - static_cast(ru.ru_stime.tv_sec) + - static_cast(ru.ru_stime.tv_usec) * 1e-6); -} -#endif -#if defined(BENCHMARK_OS_MACOSX) -double MakeTime(thread_basic_info_data_t const& info) { - return (static_cast(info.user_time.seconds) + - static_cast(info.user_time.microseconds) * 1e-6 + - static_cast(info.system_time.seconds) + - static_cast(info.system_time.microseconds) * 1e-6); -} -#endif -#if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID) -double MakeTime(struct timespec const& ts) { - return ts.tv_sec + (static_cast(ts.tv_nsec) * 1e-9); -} -#endif - -BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) { - std::cerr << "ERROR: " << msg << std::endl; - std::exit(EXIT_FAILURE); -} - -} // end namespace - -double ProcessCPUUsage() { -#if defined(BENCHMARK_OS_WINDOWS) - HANDLE proc = GetCurrentProcess(); - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time, - &user_time)) - return MakeTime(kernel_time, user_time); - DiagnoseAndExit("GetProccessTimes() failed"); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten. - // Use Emscripten-specific API. Reported CPU time would be exactly the - // same as total time, but this is ok because there aren't long-latency - // syncronous system calls in Emscripten. - return emscripten_get_now() * 1e-3; -#elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 - struct timespec spec; - if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0) - return MakeTime(spec); - DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed"); -#else - struct rusage ru; - if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru); - DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed"); -#endif -} - -double ThreadCPUUsage() { -#if defined(BENCHMARK_OS_WINDOWS) - HANDLE this_thread = GetCurrentThread(); - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time, - &user_time); - return MakeTime(kernel_time, user_time); -#elif defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 - mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; - thread_basic_info_data_t info; - mach_port_t thread = pthread_mach_thread_np(pthread_self()); - if (thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&info, &count) == - KERN_SUCCESS) { - return MakeTime(info); - } - DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info"); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // Emscripten doesn't support traditional threads - return ProcessCPUUsage(); -#elif defined(BENCHMARK_OS_RTEMS) - // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See - // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c - return ProcessCPUUsage(); -#elif defined(BENCHMARK_OS_SOLARIS) - struct rusage ru; - if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru); - DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed"); -#elif defined(CLOCK_THREAD_CPUTIME_ID) - struct timespec ts; - if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts); - DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed"); -#else -#error Per-thread timing is not available on your system. -#endif -} - -namespace { - -std::string DateTimeString(bool local) { - typedef std::chrono::system_clock Clock; - std::time_t now = Clock::to_time_t(Clock::now()); - const std::size_t kStorageSize = 128; - char storage[kStorageSize]; - std::size_t written; - - if (local) { -#if defined(BENCHMARK_OS_WINDOWS) - written = - std::strftime(storage, sizeof(storage), "%x %X", ::localtime(&now)); -#else - std::tm timeinfo; - ::localtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); -#endif - } else { -#if defined(BENCHMARK_OS_WINDOWS) - written = std::strftime(storage, sizeof(storage), "%x %X", ::gmtime(&now)); -#else - std::tm timeinfo; - ::gmtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); -#endif - } - CHECK(written < kStorageSize); - ((void)written); // prevent unused variable in optimized mode. - return std::string(storage); -} - -} // end namespace - -std::string LocalDateTimeString() { return DateTimeString(true); } - -} // end namespace benchmark diff --git a/interpreter/llvm/src/utils/benchmark/src/timers.h b/interpreter/llvm/src/utils/benchmark/src/timers.h deleted file mode 100644 index 65606ccd93d14..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/src/timers.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef BENCHMARK_TIMERS_H -#define BENCHMARK_TIMERS_H - -#include -#include - -namespace benchmark { - -// Return the CPU usage of the current process -double ProcessCPUUsage(); - -// Return the CPU usage of the children of the current process -double ChildrenCPUUsage(); - -// Return the CPU usage of the current thread -double ThreadCPUUsage(); - -#if defined(HAVE_STEADY_CLOCK) -template -struct ChooseSteadyClock { - typedef std::chrono::high_resolution_clock type; -}; - -template <> -struct ChooseSteadyClock { - typedef std::chrono::steady_clock type; -}; -#endif - -struct ChooseClockType { -#if defined(HAVE_STEADY_CLOCK) - typedef ChooseSteadyClock<>::type type; -#else - typedef std::chrono::high_resolution_clock type; -#endif -}; - -inline double ChronoClockNow() { - typedef ChooseClockType::type ClockType; - using FpSeconds = std::chrono::duration; - return FpSeconds(ClockType::now().time_since_epoch()).count(); -} - -std::string LocalDateTimeString(); - -} // end namespace benchmark - -#endif // BENCHMARK_TIMERS_H diff --git a/interpreter/llvm/src/utils/benchmark/test/AssemblyTests.cmake b/interpreter/llvm/src/utils/benchmark/test/AssemblyTests.cmake deleted file mode 100644 index 8605221ff7107..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/AssemblyTests.cmake +++ /dev/null @@ -1,45 +0,0 @@ - -include(split_list) - -set(ASM_TEST_FLAGS "") -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -if (BENCHMARK_HAS_O3_FLAG) - list(APPEND ASM_TEST_FLAGS -O3) -endif() - -check_cxx_compiler_flag(-g0 BENCHMARK_HAS_G0_FLAG) -if (BENCHMARK_HAS_G0_FLAG) - list(APPEND ASM_TEST_FLAGS -g0) -endif() - -check_cxx_compiler_flag(-fno-stack-protector BENCHMARK_HAS_FNO_STACK_PROTECTOR_FLAG) -if (BENCHMARK_HAS_FNO_STACK_PROTECTOR_FLAG) - list(APPEND ASM_TEST_FLAGS -fno-stack-protector) -endif() - -split_list(ASM_TEST_FLAGS) -string(TOUPPER "${CMAKE_CXX_COMPILER_ID}" ASM_TEST_COMPILER) - -macro(add_filecheck_test name) - cmake_parse_arguments(ARG "" "" "CHECK_PREFIXES" ${ARGV}) - add_library(${name} OBJECT ${name}.cc) - set_target_properties(${name} PROPERTIES COMPILE_FLAGS "-S ${ASM_TEST_FLAGS}") - set(ASM_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${name}.s") - add_custom_target(copy_${name} ALL - COMMAND ${PROJECT_SOURCE_DIR}/tools/strip_asm.py - $ - ${ASM_OUTPUT_FILE} - BYPRODUCTS ${ASM_OUTPUT_FILE}) - add_dependencies(copy_${name} ${name}) - if (NOT ARG_CHECK_PREFIXES) - set(ARG_CHECK_PREFIXES "CHECK") - endif() - foreach(prefix ${ARG_CHECK_PREFIXES}) - add_test(NAME run_${name}_${prefix} - COMMAND - ${LLVM_FILECHECK_EXE} ${name}.cc - --input-file=${ASM_OUTPUT_FILE} - --check-prefixes=CHECK,CHECK-${ASM_TEST_COMPILER} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - endforeach() -endmacro() diff --git a/interpreter/llvm/src/utils/benchmark/test/CMakeLists.txt b/interpreter/llvm/src/utils/benchmark/test/CMakeLists.txt deleted file mode 100644 index 05ae804bfe3fb..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/CMakeLists.txt +++ /dev/null @@ -1,247 +0,0 @@ -# Enable the tests - -find_package(Threads REQUIRED) -include(CheckCXXCompilerFlag) - -# NOTE: Some tests use `` to perform the test. Therefore we must -# strip -DNDEBUG from the default CMake flags in DEBUG mode. -string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE) -if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" ) - add_definitions( -UNDEBUG ) - add_definitions(-DTEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) - # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines. - foreach (flags_var_to_scrub - CMAKE_CXX_FLAGS_RELEASE - CMAKE_CXX_FLAGS_RELWITHDEBINFO - CMAKE_CXX_FLAGS_MINSIZEREL - CMAKE_C_FLAGS_RELEASE - CMAKE_C_FLAGS_RELWITHDEBINFO - CMAKE_C_FLAGS_MINSIZEREL) - string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " " - "${flags_var_to_scrub}" "${${flags_var_to_scrub}}") - endforeach() -endif() - -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -set(BENCHMARK_O3_FLAG "") -if (BENCHMARK_HAS_O3_FLAG) - set(BENCHMARK_O3_FLAG "-O3") -endif() - -# NOTE: These flags must be added after find_package(Threads REQUIRED) otherwise -# they will break the configuration check. -if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) - list(APPEND CMAKE_EXE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) -endif() - -add_library(output_test_helper STATIC output_test_helper.cc output_test.h) - -macro(compile_benchmark_test name) - add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark ${CMAKE_THREAD_LIBS_INIT}) -endmacro(compile_benchmark_test) - -macro(compile_benchmark_test_with_main name) - add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark_main) -endmacro(compile_benchmark_test_with_main) - -macro(compile_output_test name) - add_executable(${name} "${name}.cc" output_test.h) - target_link_libraries(${name} output_test_helper benchmark - ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) -endmacro(compile_output_test) - -# Demonstration executable -compile_benchmark_test(benchmark_test) -add_test(benchmark benchmark_test --benchmark_min_time=0.01) - -compile_benchmark_test(filter_test) -macro(add_filter_test name filter expect) - add_test(${name} filter_test --benchmark_min_time=0.01 --benchmark_filter=${filter} ${expect}) - add_test(${name}_list_only filter_test --benchmark_list_tests --benchmark_filter=${filter} ${expect}) -endmacro(add_filter_test) - -add_filter_test(filter_simple "Foo" 3) -add_filter_test(filter_simple_negative "-Foo" 2) -add_filter_test(filter_suffix "BM_.*" 4) -add_filter_test(filter_suffix_negative "-BM_.*" 1) -add_filter_test(filter_regex_all ".*" 5) -add_filter_test(filter_regex_all_negative "-.*" 0) -add_filter_test(filter_regex_blank "" 5) -add_filter_test(filter_regex_blank_negative "-" 0) -add_filter_test(filter_regex_none "monkey" 0) -add_filter_test(filter_regex_none_negative "-monkey" 5) -add_filter_test(filter_regex_wildcard ".*Foo.*" 3) -add_filter_test(filter_regex_wildcard_negative "-.*Foo.*" 2) -add_filter_test(filter_regex_begin "^BM_.*" 4) -add_filter_test(filter_regex_begin_negative "-^BM_.*" 1) -add_filter_test(filter_regex_begin2 "^N" 1) -add_filter_test(filter_regex_begin2_negative "-^N" 4) -add_filter_test(filter_regex_end ".*Ba$" 1) -add_filter_test(filter_regex_end_negative "-.*Ba$" 4) - -compile_benchmark_test(options_test) -add_test(options_benchmarks options_test --benchmark_min_time=0.01) - -compile_benchmark_test(basic_test) -add_test(basic_benchmark basic_test --benchmark_min_time=0.01) - -compile_benchmark_test(diagnostics_test) -add_test(diagnostics_test diagnostics_test --benchmark_min_time=0.01) - -compile_benchmark_test(skip_with_error_test) -add_test(skip_with_error_test skip_with_error_test --benchmark_min_time=0.01) - -compile_benchmark_test(donotoptimize_test) -# Some of the issues with DoNotOptimize only occur when optimization is enabled -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -if (BENCHMARK_HAS_O3_FLAG) - set_target_properties(donotoptimize_test PROPERTIES COMPILE_FLAGS "-O3") -endif() -add_test(donotoptimize_test donotoptimize_test --benchmark_min_time=0.01) - -compile_benchmark_test(fixture_test) -add_test(fixture_test fixture_test --benchmark_min_time=0.01) - -compile_benchmark_test(register_benchmark_test) -add_test(register_benchmark_test register_benchmark_test --benchmark_min_time=0.01) - -compile_benchmark_test(map_test) -add_test(map_test map_test --benchmark_min_time=0.01) - -compile_benchmark_test(multiple_ranges_test) -add_test(multiple_ranges_test multiple_ranges_test --benchmark_min_time=0.01) - -compile_benchmark_test_with_main(link_main_test) -add_test(link_main_test link_main_test --benchmark_min_time=0.01) - -compile_output_test(reporter_output_test) -add_test(reporter_output_test reporter_output_test --benchmark_min_time=0.01) - -compile_output_test(templated_fixture_test) -add_test(templated_fixture_test templated_fixture_test --benchmark_min_time=0.01) - -compile_output_test(user_counters_test) -add_test(user_counters_test user_counters_test --benchmark_min_time=0.01) - -compile_output_test(user_counters_tabular_test) -add_test(user_counters_tabular_test user_counters_tabular_test --benchmark_counters_tabular=true --benchmark_min_time=0.01) - -check_cxx_compiler_flag(-std=c++03 BENCHMARK_HAS_CXX03_FLAG) -if (BENCHMARK_HAS_CXX03_FLAG) - compile_benchmark_test(cxx03_test) - set_target_properties(cxx03_test - PROPERTIES - COMPILE_FLAGS "-std=c++03") - # libstdc++ provides different definitions within between dialects. When - # LTO is enabled and -Werror is specified GCC diagnoses this ODR violation - # causing the test to fail to compile. To prevent this we explicitly disable - # the warning. - check_cxx_compiler_flag(-Wno-odr BENCHMARK_HAS_WNO_ODR) - if (BENCHMARK_ENABLE_LTO AND BENCHMARK_HAS_WNO_ODR) - set_target_properties(cxx03_test - PROPERTIES - LINK_FLAGS "-Wno-odr") - endif() - add_test(cxx03 cxx03_test --benchmark_min_time=0.01) -endif() - -# Attempt to work around flaky test failures when running on Appveyor servers. -if (DEFINED ENV{APPVEYOR}) - set(COMPLEXITY_MIN_TIME "0.5") -else() - set(COMPLEXITY_MIN_TIME "0.01") -endif() -compile_output_test(complexity_test) -add_test(complexity_benchmark complexity_test --benchmark_min_time=${COMPLEXITY_MIN_TIME}) - -############################################################################### -# GoogleTest Unit Tests -############################################################################### - -if (BENCHMARK_ENABLE_GTEST_TESTS) - macro(compile_gtest name) - add_executable(${name} "${name}.cc") - if (TARGET googletest) - add_dependencies(${name} googletest) - endif() - if (GTEST_INCLUDE_DIRS) - target_include_directories(${name} PRIVATE ${GTEST_INCLUDE_DIRS}) - endif() - target_link_libraries(${name} benchmark - ${GTEST_BOTH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) - endmacro(compile_gtest) - - macro(add_gtest name) - compile_gtest(${name}) - add_test(${name} ${name}) - endmacro() - - add_gtest(benchmark_gtest) - add_gtest(statistics_gtest) -endif(BENCHMARK_ENABLE_GTEST_TESTS) - -############################################################################### -# Assembly Unit Tests -############################################################################### - -if (BENCHMARK_ENABLE_ASSEMBLY_TESTS) - if (NOT LLVM_FILECHECK_EXE) - message(FATAL_ERROR "LLVM FileCheck is required when including this file") - endif() - include(AssemblyTests.cmake) - add_filecheck_test(donotoptimize_assembly_test) - add_filecheck_test(state_assembly_test) - add_filecheck_test(clobber_memory_assembly_test) -endif() - - - -############################################################################### -# Code Coverage Configuration -############################################################################### - -# Add the coverage command(s) -if(CMAKE_BUILD_TYPE) - string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) -endif() -if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage") - find_program(GCOV gcov) - find_program(LCOV lcov) - find_program(GENHTML genhtml) - find_program(CTEST ctest) - if (GCOV AND LCOV AND GENHTML AND CTEST AND HAVE_CXX_FLAG_COVERAGE) - add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/lcov/index.html - COMMAND ${LCOV} -q -z -d . - COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o before.lcov -i - COMMAND ${CTEST} --force-new-ctest-process - COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o after.lcov - COMMAND ${LCOV} -q -a before.lcov -a after.lcov --output-file final.lcov - COMMAND ${LCOV} -q -r final.lcov "'${CMAKE_SOURCE_DIR}/test/*'" -o final.lcov - COMMAND ${GENHTML} final.lcov -o lcov --demangle-cpp --sort -p "${CMAKE_BINARY_DIR}" -t benchmark - DEPENDS filter_test benchmark_test options_test basic_test fixture_test cxx03_test complexity_test - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} - COMMENT "Running LCOV" - ) - add_custom_target(coverage - DEPENDS ${CMAKE_BINARY_DIR}/lcov/index.html - COMMENT "LCOV report at lcov/index.html" - ) - message(STATUS "Coverage command added") - else() - if (HAVE_CXX_FLAG_COVERAGE) - set(CXX_FLAG_COVERAGE_MESSAGE supported) - else() - set(CXX_FLAG_COVERAGE_MESSAGE unavailable) - endif() - message(WARNING - "Coverage not available:\n" - " gcov: ${GCOV}\n" - " lcov: ${LCOV}\n" - " genhtml: ${GENHTML}\n" - " ctest: ${CTEST}\n" - " --coverage flag: ${CXX_FLAG_COVERAGE_MESSAGE}") - endif() -endif() diff --git a/interpreter/llvm/src/utils/benchmark/test/basic_test.cc b/interpreter/llvm/src/utils/benchmark/test/basic_test.cc deleted file mode 100644 index d07fbc00b1516..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/basic_test.cc +++ /dev/null @@ -1,136 +0,0 @@ - -#include "benchmark/benchmark.h" - -#define BASIC_BENCHMARK_TEST(x) BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192) - -void BM_empty(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } -} -BENCHMARK(BM_empty); -BENCHMARK(BM_empty)->ThreadPerCpu(); - -void BM_spin_empty(benchmark::State& state) { - for (auto _ : state) { - for (int x = 0; x < state.range(0); ++x) { - benchmark::DoNotOptimize(x); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_empty); -BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu(); - -void BM_spin_pause_before(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_before); -BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu(); - -void BM_spin_pause_during(benchmark::State& state) { - for (auto _ : state) { - state.PauseTiming(); - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - state.ResumeTiming(); - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_during); -BASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu(); - -void BM_pause_during(benchmark::State& state) { - for (auto _ : state) { - state.PauseTiming(); - state.ResumeTiming(); - } -} -BENCHMARK(BM_pause_during); -BENCHMARK(BM_pause_during)->ThreadPerCpu(); -BENCHMARK(BM_pause_during)->UseRealTime(); -BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu(); - -void BM_spin_pause_after(benchmark::State& state) { - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_after); -BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu(); - -void BM_spin_pause_before_and_after(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after); -BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu(); - -void BM_empty_stop_start(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_empty_stop_start); -BENCHMARK(BM_empty_stop_start)->ThreadPerCpu(); - - -void BM_KeepRunning(benchmark::State& state) { - size_t iter_count = 0; - assert(iter_count == state.iterations()); - while (state.KeepRunning()) { - ++iter_count; - } - assert(iter_count == state.iterations()); -} -BENCHMARK(BM_KeepRunning); - -void BM_KeepRunningBatch(benchmark::State& state) { - // Choose a prime batch size to avoid evenly dividing max_iterations. - const size_t batch_size = 101; - size_t iter_count = 0; - while (state.KeepRunningBatch(batch_size)) { - iter_count += batch_size; - } - assert(state.iterations() == iter_count); -} -BENCHMARK(BM_KeepRunningBatch); - -void BM_RangedFor(benchmark::State& state) { - size_t iter_count = 0; - for (auto _ : state) { - ++iter_count; - } - assert(iter_count == state.max_iterations); -} -BENCHMARK(BM_RangedFor); - -// Ensure that StateIterator provides all the necessary typedefs required to -// instantiate std::iterator_traits. -static_assert(std::is_same< - typename std::iterator_traits::value_type, - typename benchmark::State::StateIterator::value_type>::value, ""); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/benchmark_gtest.cc b/interpreter/llvm/src/utils/benchmark/test/benchmark_gtest.cc deleted file mode 100644 index 10683b433ab54..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/benchmark_gtest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include - -#include "../src/benchmark_register.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -namespace { - -TEST(AddRangeTest, Simple) { - std::vector dst; - AddRange(&dst, 1, 2, 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2)); -} - -TEST(AddRangeTest, Simple64) { - std::vector dst; - AddRange(&dst, static_cast(1), static_cast(2), 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2)); -} - -TEST(AddRangeTest, Advanced) { - std::vector dst; - AddRange(&dst, 5, 15, 2); - EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15)); -} - -TEST(AddRangeTest, Advanced64) { - std::vector dst; - AddRange(&dst, static_cast(5), static_cast(15), 2); - EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15)); -} - -} // end namespace diff --git a/interpreter/llvm/src/utils/benchmark/test/benchmark_test.cc b/interpreter/llvm/src/utils/benchmark/test/benchmark_test.cc deleted file mode 100644 index 3cd4f5565fa1c..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/benchmark_test.cc +++ /dev/null @@ -1,245 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__GNUC__) -#define BENCHMARK_NOINLINE __attribute__((noinline)) -#else -#define BENCHMARK_NOINLINE -#endif - -namespace { - -int BENCHMARK_NOINLINE Factorial(uint32_t n) { - return (n == 1) ? 1 : n * Factorial(n - 1); -} - -double CalculatePi(int depth) { - double pi = 0.0; - for (int i = 0; i < depth; ++i) { - double numerator = static_cast(((i % 2) * 2) - 1); - double denominator = static_cast((2 * i) - 1); - pi += numerator / denominator; - } - return (pi - 1.0) * 4; -} - -std::set ConstructRandomSet(int64_t size) { - std::set s; - for (int i = 0; i < size; ++i) s.insert(s.end(), i); - return s; -} - -std::mutex test_vector_mu; -std::vector* test_vector = nullptr; - -} // end namespace - -static void BM_Factorial(benchmark::State& state) { - int fac_42 = 0; - for (auto _ : state) fac_42 = Factorial(8); - // Prevent compiler optimizations - std::stringstream ss; - ss << fac_42; - state.SetLabel(ss.str()); -} -BENCHMARK(BM_Factorial); -BENCHMARK(BM_Factorial)->UseRealTime(); - -static void BM_CalculatePiRange(benchmark::State& state) { - double pi = 0.0; - for (auto _ : state) pi = CalculatePi(static_cast(state.range(0))); - std::stringstream ss; - ss << pi; - state.SetLabel(ss.str()); -} -BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); - -static void BM_CalculatePi(benchmark::State& state) { - static const int depth = 1024; - for (auto _ : state) { - benchmark::DoNotOptimize(CalculatePi(static_cast(depth))); - } -} -BENCHMARK(BM_CalculatePi)->Threads(8); -BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); -BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); - -static void BM_SetInsert(benchmark::State& state) { - std::set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) data.insert(rand()); - } - state.SetItemsProcessed(state.iterations() * state.range(1)); - state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int)); -} - -// Test many inserts at once to reduce the total iterations needed. Otherwise, the slower, -// non-timed part of each iteration will make the benchmark take forever. -BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}}); - -template -static void BM_Sequential(benchmark::State& state) { - ValueType v = 42; - for (auto _ : state) { - Container c; - for (int64_t i = state.range(0); --i;) c.push_back(v); - } - const int64_t items_processed = state.iterations() * state.range(0); - state.SetItemsProcessed(items_processed); - state.SetBytesProcessed(items_processed * sizeof(v)); -} -BENCHMARK_TEMPLATE2(BM_Sequential, std::vector, int) - ->Range(1 << 0, 1 << 10); -BENCHMARK_TEMPLATE(BM_Sequential, std::list)->Range(1 << 0, 1 << 10); -// Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond. -#ifdef BENCHMARK_HAS_CXX11 -BENCHMARK_TEMPLATE(BM_Sequential, std::vector, int)->Arg(512); -#endif - -static void BM_StringCompare(benchmark::State& state) { - size_t len = static_cast(state.range(0)); - std::string s1(len, '-'); - std::string s2(len, '-'); - for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2)); -} -BENCHMARK(BM_StringCompare)->Range(1, 1 << 20); - -static void BM_SetupTeardown(benchmark::State& state) { - if (state.thread_index == 0) { - // No need to lock test_vector_mu here as this is running single-threaded. - test_vector = new std::vector(); - } - int i = 0; - for (auto _ : state) { - std::lock_guard l(test_vector_mu); - if (i % 2 == 0) - test_vector->push_back(i); - else - test_vector->pop_back(); - ++i; - } - if (state.thread_index == 0) { - delete test_vector; - } -} -BENCHMARK(BM_SetupTeardown)->ThreadPerCpu(); - -static void BM_LongTest(benchmark::State& state) { - double tracker = 0.0; - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) - benchmark::DoNotOptimize(tracker += i); - } -} -BENCHMARK(BM_LongTest)->Range(1 << 16, 1 << 28); - -static void BM_ParallelMemset(benchmark::State& state) { - int64_t size = state.range(0) / static_cast(sizeof(int)); - int thread_size = static_cast(size) / state.threads; - int from = thread_size * state.thread_index; - int to = from + thread_size; - - if (state.thread_index == 0) { - test_vector = new std::vector(static_cast(size)); - } - - for (auto _ : state) { - for (int i = from; i < to; i++) { - // No need to lock test_vector_mu as ranges - // do not overlap between threads. - benchmark::DoNotOptimize(test_vector->at(i) = 1); - } - } - - if (state.thread_index == 0) { - delete test_vector; - } -} -BENCHMARK(BM_ParallelMemset)->Arg(10 << 20)->ThreadRange(1, 4); - -static void BM_ManualTiming(benchmark::State& state) { - int64_t slept_for = 0; - int64_t microseconds = state.range(0); - std::chrono::duration sleep_duration{ - static_cast(microseconds)}; - - for (auto _ : state) { - auto start = std::chrono::high_resolution_clock::now(); - // Simulate some useful workload with a sleep - std::this_thread::sleep_for( - std::chrono::duration_cast(sleep_duration)); - auto end = std::chrono::high_resolution_clock::now(); - - auto elapsed = - std::chrono::duration_cast>(end - start); - - state.SetIterationTime(elapsed.count()); - slept_for += microseconds; - } - state.SetItemsProcessed(slept_for); -} -BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseRealTime(); -BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseManualTime(); - -#ifdef BENCHMARK_HAS_CXX11 - -template -void BM_with_args(benchmark::State& state, Args&&...) { - for (auto _ : state) { - } -} -BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44); -BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"), - std::pair(42, 3.8)); - -void BM_non_template_args(benchmark::State& state, int, double) { - while(state.KeepRunning()) {} -} -BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); - -#endif // BENCHMARK_HAS_CXX11 - -static void BM_DenseThreadRanges(benchmark::State& st) { - switch (st.range(0)) { - case 1: - assert(st.threads == 1 || st.threads == 2 || st.threads == 3); - break; - case 2: - assert(st.threads == 1 || st.threads == 3 || st.threads == 4); - break; - case 3: - assert(st.threads == 5 || st.threads == 8 || st.threads == 11 || - st.threads == 14); - break; - default: - assert(false && "Invalid test case number"); - } - while (st.KeepRunning()) { - } -} -BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3); -BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2); -BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/clobber_memory_assembly_test.cc b/interpreter/llvm/src/utils/benchmark/test/clobber_memory_assembly_test.cc deleted file mode 100644 index f41911a39ce73..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/clobber_memory_assembly_test.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -extern "C" { - -extern int ExternInt; -extern int ExternInt2; -extern int ExternInt3; - -} - -// CHECK-LABEL: test_basic: -extern "C" void test_basic() { - int x; - benchmark::DoNotOptimize(&x); - x = 101; - benchmark::ClobberMemory(); - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: movl $101, [[DEST]] - // CHECK: ret -} - -// CHECK-LABEL: test_redundant_store: -extern "C" void test_redundant_store() { - ExternInt = 3; - benchmark::ClobberMemory(); - ExternInt = 51; - // CHECK-DAG: ExternInt - // CHECK-DAG: movl $3 - // CHECK: movl $51 -} - -// CHECK-LABEL: test_redundant_read: -extern "C" void test_redundant_read() { - int x; - benchmark::DoNotOptimize(&x); - x = ExternInt; - benchmark::ClobberMemory(); - x = ExternInt2; - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK-NOT: ExternInt2 - // CHECK: ret -} - -// CHECK-LABEL: test_redundant_read2: -extern "C" void test_redundant_read2() { - int x; - benchmark::DoNotOptimize(&x); - x = ExternInt; - benchmark::ClobberMemory(); - x = ExternInt2; - benchmark::ClobberMemory(); - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK: ExternInt2(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK: ret -} diff --git a/interpreter/llvm/src/utils/benchmark/test/complexity_test.cc b/interpreter/llvm/src/utils/benchmark/test/complexity_test.cc deleted file mode 100644 index ab832861ece29..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/complexity_test.cc +++ /dev/null @@ -1,167 +0,0 @@ -#undef NDEBUG -#include -#include -#include -#include -#include -#include "benchmark/benchmark.h" -#include "output_test.h" - -namespace { - -#define ADD_COMPLEXITY_CASES(...) \ - int CONCAT(dummy, __LINE__) = AddComplexityTest(__VA_ARGS__) - -int AddComplexityTest(std::string big_o_test_name, std::string rms_test_name, - std::string big_o) { - SetSubstitutions({{"%bigo_name", big_o_test_name}, - {"%rms_name", rms_test_name}, - {"%bigo_str", "[ ]* %float " + big_o}, - {"%bigo", big_o}, - {"%rms", "[ ]*[0-9]+ %"}}); - AddCases( - TC_ConsoleOut, - {{"^%bigo_name %bigo_str %bigo_str[ ]*$"}, - {"^%bigo_name", MR_Not}, // Assert we we didn't only matched a name. - {"^%rms_name %rms %rms[ ]*$", MR_Next}}); - AddCases(TC_JSONOut, {{"\"name\": \"%bigo_name\",$"}, - {"\"cpu_coefficient\": %float,$", MR_Next}, - {"\"real_coefficient\": %float,$", MR_Next}, - {"\"big_o\": \"%bigo\",$", MR_Next}, - {"\"time_unit\": \"ns\"$", MR_Next}, - {"}", MR_Next}, - {"\"name\": \"%rms_name\",$"}, - {"\"rms\": %float$", MR_Next}, - {"}", MR_Next}}); - AddCases(TC_CSVOut, {{"^\"%bigo_name\",,%float,%float,%bigo,,,,,$"}, - {"^\"%bigo_name\"", MR_Not}, - {"^\"%rms_name\",,%float,%float,,,,,,$", MR_Next}}); - return 0; -} - -} // end namespace - -// ========================================================================= // -// --------------------------- Testing BigO O(1) --------------------------- // -// ========================================================================= // - -void BM_Complexity_O1(benchmark::State& state) { - for (auto _ : state) { - for (int i = 0; i < 1024; ++i) { - benchmark::DoNotOptimize(&i); - } - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1); -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(); -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity([](int64_t) { - return 1.0; -}); - -const char *big_o_1_test_name = "BM_Complexity_O1_BigO"; -const char *rms_o_1_test_name = "BM_Complexity_O1_RMS"; -const char *enum_big_o_1 = "\\([0-9]+\\)"; -// FIXME: Tolerate both '(1)' and 'lgN' as output when the complexity is auto -// deduced. -// See https://github.com/google/benchmark/issues/272 -const char *auto_big_o_1 = "(\\([0-9]+\\))|(lgN)"; -const char *lambda_big_o_1 = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(big_o_1_test_name, rms_o_1_test_name, enum_big_o_1); - -// Add auto enum tests -ADD_COMPLEXITY_CASES(big_o_1_test_name, rms_o_1_test_name, auto_big_o_1); - -// Add lambda tests -ADD_COMPLEXITY_CASES(big_o_1_test_name, rms_o_1_test_name, lambda_big_o_1); - -// ========================================================================= // -// --------------------------- Testing BigO O(N) --------------------------- // -// ========================================================================= // - -std::vector ConstructRandomVector(int64_t size) { - std::vector v; - v.reserve(static_cast(size)); - for (int i = 0; i < size; ++i) { - v.push_back(std::rand() % size); - } - return v; -} - -void BM_Complexity_O_N(benchmark::State& state) { - auto v = ConstructRandomVector(state.range(0)); - // Test worst case scenario (item not in vector) - const int64_t item_not_in_vector = state.range(0) * 2; - for (auto _ : state) { - benchmark::DoNotOptimize(std::find(v.begin(), v.end(), item_not_in_vector)); - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(benchmark::oN); -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity([](int64_t n) -> double { return n; }); -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(); - -const char *big_o_n_test_name = "BM_Complexity_O_N_BigO"; -const char *rms_o_n_test_name = "BM_Complexity_O_N_RMS"; -const char *enum_auto_big_o_n = "N"; -const char *lambda_big_o_n = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(big_o_n_test_name, rms_o_n_test_name, enum_auto_big_o_n); - -// Add lambda tests -ADD_COMPLEXITY_CASES(big_o_n_test_name, rms_o_n_test_name, lambda_big_o_n); - -// ========================================================================= // -// ------------------------- Testing BigO O(N*lgN) ------------------------- // -// ========================================================================= // - -static void BM_Complexity_O_N_log_N(benchmark::State& state) { - auto v = ConstructRandomVector(state.range(0)); - for (auto _ : state) { - std::sort(v.begin(), v.end()); - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(benchmark::oNLogN); -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity([](int64_t n) { return n * log2(n); }); -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(); - -const char *big_o_n_lg_n_test_name = "BM_Complexity_O_N_log_N_BigO"; -const char *rms_o_n_lg_n_test_name = "BM_Complexity_O_N_log_N_RMS"; -const char *enum_auto_big_o_n_lg_n = "NlgN"; -const char *lambda_big_o_n_lg_n = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(big_o_n_lg_n_test_name, rms_o_n_lg_n_test_name, - enum_auto_big_o_n_lg_n); - -// Add lambda tests -ADD_COMPLEXITY_CASES(big_o_n_lg_n_test_name, rms_o_n_lg_n_test_name, - lambda_big_o_n_lg_n); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char *argv[]) { RunOutputTests(argc, argv); } diff --git a/interpreter/llvm/src/utils/benchmark/test/cxx03_test.cc b/interpreter/llvm/src/utils/benchmark/test/cxx03_test.cc deleted file mode 100644 index baa9ed9262baa..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/cxx03_test.cc +++ /dev/null @@ -1,63 +0,0 @@ -#undef NDEBUG -#include -#include - -#include "benchmark/benchmark.h" - -#if __cplusplus >= 201103L -#error C++11 or greater detected. Should be C++03. -#endif - -#ifdef BENCHMARK_HAS_CXX11 -#error C++11 or greater detected by the library. BENCHMARK_HAS_CXX11 is defined. -#endif - -void BM_empty(benchmark::State& state) { - while (state.KeepRunning()) { - volatile std::size_t x = state.iterations(); - ((void)x); - } -} -BENCHMARK(BM_empty); - -// The new C++11 interface for args/ranges requires initializer list support. -// Therefore we provide the old interface to support C++03. -void BM_old_arg_range_interface(benchmark::State& state) { - assert((state.range(0) == 1 && state.range(1) == 2) || - (state.range(0) == 5 && state.range(1) == 6)); - while (state.KeepRunning()) { - } -} -BENCHMARK(BM_old_arg_range_interface)->ArgPair(1, 2)->RangePair(5, 5, 6, 6); - -template -void BM_template2(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE2(BM_template2, int, long); - -template -void BM_template1(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE(BM_template1, long); -BENCHMARK_TEMPLATE1(BM_template1, int); - -template -struct BM_Fixture : public ::benchmark::Fixture { -}; - -BENCHMARK_TEMPLATE_F(BM_Fixture, BM_template1, long)(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE1_F(BM_Fixture, BM_template2, int)(benchmark::State& state) { - BM_empty(state); -} - -void BM_counters(benchmark::State& state) { - BM_empty(state); - state.counters["Foo"] = 2; -} -BENCHMARK(BM_counters); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/diagnostics_test.cc b/interpreter/llvm/src/utils/benchmark/test/diagnostics_test.cc deleted file mode 100644 index dd64a33655315..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/diagnostics_test.cc +++ /dev/null @@ -1,80 +0,0 @@ -// Testing: -// State::PauseTiming() -// State::ResumeTiming() -// Test that CHECK's within these function diagnose when they are called -// outside of the KeepRunning() loop. -// -// NOTE: Users should NOT include or use src/check.h. This is only done in -// order to test library internals. - -#include -#include - -#include "../src/check.h" -#include "benchmark/benchmark.h" - -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -#define TEST_HAS_NO_EXCEPTIONS -#endif - -void TestHandler() { -#ifndef TEST_HAS_NO_EXCEPTIONS - throw std::logic_error(""); -#else - std::abort(); -#endif -} - -void try_invalid_pause_resume(benchmark::State& state) { -#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && !defined(TEST_HAS_NO_EXCEPTIONS) - try { - state.PauseTiming(); - std::abort(); - } catch (std::logic_error const&) { - } - try { - state.ResumeTiming(); - std::abort(); - } catch (std::logic_error const&) { - } -#else - (void)state; // avoid unused warning -#endif -} - -void BM_diagnostic_test(benchmark::State& state) { - static bool called_once = false; - - if (called_once == false) try_invalid_pause_resume(state); - - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } - - if (called_once == false) try_invalid_pause_resume(state); - - called_once = true; -} -BENCHMARK(BM_diagnostic_test); - - -void BM_diagnostic_test_keep_running(benchmark::State& state) { - static bool called_once = false; - - if (called_once == false) try_invalid_pause_resume(state); - - while(state.KeepRunning()) { - benchmark::DoNotOptimize(state.iterations()); - } - - if (called_once == false) try_invalid_pause_resume(state); - - called_once = true; -} -BENCHMARK(BM_diagnostic_test_keep_running); - -int main(int argc, char* argv[]) { - benchmark::internal::GetAbortHandler() = &TestHandler; - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); -} diff --git a/interpreter/llvm/src/utils/benchmark/test/donotoptimize_assembly_test.cc b/interpreter/llvm/src/utils/benchmark/test/donotoptimize_assembly_test.cc deleted file mode 100644 index d4b0bab70e773..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/donotoptimize_assembly_test.cc +++ /dev/null @@ -1,163 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -extern "C" { - -extern int ExternInt; -extern int ExternInt2; -extern int ExternInt3; - -inline int Add42(int x) { return x + 42; } - -struct NotTriviallyCopyable { - NotTriviallyCopyable(); - explicit NotTriviallyCopyable(int x) : value(x) {} - NotTriviallyCopyable(NotTriviallyCopyable const&); - int value; -}; - -struct Large { - int value; - int data[2]; -}; - -} -// CHECK-LABEL: test_with_rvalue: -extern "C" void test_with_rvalue() { - benchmark::DoNotOptimize(Add42(0)); - // CHECK: movl $42, %eax - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_rvalue: -extern "C" void test_with_large_rvalue() { - benchmark::DoNotOptimize(Large{ExternInt, {ExternInt, ExternInt}}); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]] - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_rvalue: -extern "C" void test_with_non_trivial_rvalue() { - benchmark::DoNotOptimize(NotTriviallyCopyable(ExternInt)); - // CHECK: mov{{l|q}} ExternInt(%rip) - // CHECK: ret -} - -// CHECK-LABEL: test_with_lvalue: -extern "C" void test_with_lvalue() { - int x = 101; - benchmark::DoNotOptimize(x); - // CHECK-GNU: movl $101, %eax - // CHECK-CLANG: movl $101, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_lvalue: -extern "C" void test_with_large_lvalue() { - Large L{ExternInt, {ExternInt, ExternInt}}; - benchmark::DoNotOptimize(L); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_lvalue: -extern "C" void test_with_non_trivial_lvalue() { - NotTriviallyCopyable NTC(ExternInt); - benchmark::DoNotOptimize(NTC); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_const_lvalue: -extern "C" void test_with_const_lvalue() { - const int x = 123; - benchmark::DoNotOptimize(x); - // CHECK: movl $123, %eax - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_const_lvalue: -extern "C" void test_with_large_const_lvalue() { - const Large L{ExternInt, {ExternInt, ExternInt}}; - benchmark::DoNotOptimize(L); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_const_lvalue: -extern "C" void test_with_non_trivial_const_lvalue() { - const NotTriviallyCopyable Obj(ExternInt); - benchmark::DoNotOptimize(Obj); - // CHECK: mov{{q|l}} ExternInt(%rip) - // CHECK: ret -} - -// CHECK-LABEL: test_div_by_two: -extern "C" int test_div_by_two(int input) { - int divisor = 2; - benchmark::DoNotOptimize(divisor); - return input / divisor; - // CHECK: movl $2, [[DEST:.*]] - // CHECK: idivl [[DEST]] - // CHECK: ret -} - -// CHECK-LABEL: test_inc_integer: -extern "C" int test_inc_integer() { - int x = 0; - for (int i=0; i < 5; ++i) - benchmark::DoNotOptimize(++x); - // CHECK: movl $1, [[DEST:.*]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK-CLANG: movl [[DEST]], %eax - // CHECK: ret - return x; -} - -// CHECK-LABEL: test_pointer_rvalue -extern "C" void test_pointer_rvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret - int x = 42; - benchmark::DoNotOptimize(&x); -} - -// CHECK-LABEL: test_pointer_const_lvalue: -extern "C" void test_pointer_const_lvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret - int x = 42; - int * const xp = &x; - benchmark::DoNotOptimize(xp); -} - -// CHECK-LABEL: test_pointer_lvalue: -extern "C" void test_pointer_lvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z+]+]]) - // CHECK: ret - int x = 42; - int *xp = &x; - benchmark::DoNotOptimize(xp); -} diff --git a/interpreter/llvm/src/utils/benchmark/test/donotoptimize_test.cc b/interpreter/llvm/src/utils/benchmark/test/donotoptimize_test.cc deleted file mode 100644 index 2ce92d1c72bed..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/donotoptimize_test.cc +++ /dev/null @@ -1,52 +0,0 @@ -#include "benchmark/benchmark.h" - -#include - -namespace { -#if defined(__GNUC__) -std::uint64_t double_up(const std::uint64_t x) __attribute__((const)); -#endif -std::uint64_t double_up(const std::uint64_t x) { return x * 2; } -} - -// Using DoNotOptimize on types like BitRef seem to cause a lot of problems -// with the inline assembly on both GCC and Clang. -struct BitRef { - int index; - unsigned char &byte; - -public: - static BitRef Make() { - static unsigned char arr[2] = {}; - BitRef b(1, arr[0]); - return b; - } -private: - BitRef(int i, unsigned char& b) : index(i), byte(b) {} -}; - -int main(int, char*[]) { - // this test verifies compilation of DoNotOptimize() for some types - - char buffer8[8] = ""; - benchmark::DoNotOptimize(buffer8); - - char buffer20[20] = ""; - benchmark::DoNotOptimize(buffer20); - - char buffer1024[1024] = ""; - benchmark::DoNotOptimize(buffer1024); - benchmark::DoNotOptimize(&buffer1024[0]); - - int x = 123; - benchmark::DoNotOptimize(x); - benchmark::DoNotOptimize(&x); - benchmark::DoNotOptimize(x += 42); - - benchmark::DoNotOptimize(double_up(x)); - - // These tests are to e - benchmark::DoNotOptimize(BitRef::Make()); - BitRef lval = BitRef::Make(); - benchmark::DoNotOptimize(lval); -} diff --git a/interpreter/llvm/src/utils/benchmark/test/filter_test.cc b/interpreter/llvm/src/utils/benchmark/test/filter_test.cc deleted file mode 100644 index 0e27065c1558e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/filter_test.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual bool ReportContext(const Context& context) { - return ConsoleReporter::ReportContext(context); - }; - - virtual void ReportRuns(const std::vector& report) { - ++count_; - ConsoleReporter::ReportRuns(report); - }; - - TestReporter() : count_(0) {} - - virtual ~TestReporter() {} - - size_t GetCount() const { return count_; } - - private: - mutable size_t count_; -}; - -} // end namespace - -static void NoPrefix(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(NoPrefix); - -static void BM_Foo(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_Foo); - -static void BM_Bar(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_Bar); - -static void BM_FooBar(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_FooBar); - -static void BM_FooBa(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_FooBa); - -int main(int argc, char **argv) { - bool list_only = false; - for (int i = 0; i < argc; ++i) - list_only |= std::string(argv[i]).find("--benchmark_list_tests") != - std::string::npos; - - benchmark::Initialize(&argc, argv); - - TestReporter test_reporter; - const size_t returned_count = - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - if (argc == 2) { - // Make sure we ran all of the tests - std::stringstream ss(argv[1]); - size_t expected_return; - ss >> expected_return; - - if (returned_count != expected_return) { - std::cerr << "ERROR: Expected " << expected_return - << " tests to match the filter but returned_count = " - << returned_count << std::endl; - return -1; - } - - const size_t expected_reports = list_only ? 0 : expected_return; - const size_t reports_count = test_reporter.GetCount(); - if (reports_count != expected_reports) { - std::cerr << "ERROR: Expected " << expected_reports - << " tests to be run but reported_count = " << reports_count - << std::endl; - return -1; - } - } - - return 0; -} diff --git a/interpreter/llvm/src/utils/benchmark/test/fixture_test.cc b/interpreter/llvm/src/utils/benchmark/test/fixture_test.cc deleted file mode 100644 index 1462b10f02f96..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/fixture_test.cc +++ /dev/null @@ -1,49 +0,0 @@ - -#include "benchmark/benchmark.h" - -#include -#include - -class MyFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() == nullptr); - data.reset(new int(42)); - } - } - - void TearDown(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() != nullptr); - data.reset(); - } - } - - ~MyFixture() { assert(data == nullptr); } - - std::unique_ptr data; -}; - -BENCHMARK_F(MyFixture, Foo)(benchmark::State &st) { - assert(data.get() != nullptr); - assert(*data == 42); - for (auto _ : st) { - } -} - -BENCHMARK_DEFINE_F(MyFixture, Bar)(benchmark::State& st) { - if (st.thread_index == 0) { - assert(data.get() != nullptr); - assert(*data == 42); - } - for (auto _ : st) { - assert(data.get() != nullptr); - assert(*data == 42); - } - st.SetItemsProcessed(st.range(0)); -} -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42); -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42)->ThreadPerCpu(); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/link_main_test.cc b/interpreter/llvm/src/utils/benchmark/test/link_main_test.cc deleted file mode 100644 index 241ad5c3905e9..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/link_main_test.cc +++ /dev/null @@ -1,8 +0,0 @@ -#include "benchmark/benchmark.h" - -void BM_empty(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } -} -BENCHMARK(BM_empty); diff --git a/interpreter/llvm/src/utils/benchmark/test/map_test.cc b/interpreter/llvm/src/utils/benchmark/test/map_test.cc deleted file mode 100644 index dbf7982a3686e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/map_test.cc +++ /dev/null @@ -1,57 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include - -namespace { - -std::map ConstructRandomMap(int size) { - std::map m; - for (int i = 0; i < size; ++i) { - m.insert(std::make_pair(std::rand() % size, std::rand() % size)); - } - return m; -} - -} // namespace - -// Basic version. -static void BM_MapLookup(benchmark::State& state) { - const int size = static_cast(state.range(0)); - std::map m; - for (auto _ : state) { - state.PauseTiming(); - m = ConstructRandomMap(size); - state.ResumeTiming(); - for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); - } - } - state.SetItemsProcessed(state.iterations() * size); -} -BENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12); - -// Using fixtures. -class MapFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& st) { - m = ConstructRandomMap(static_cast(st.range(0))); - } - - void TearDown(const ::benchmark::State&) { m.clear(); } - - std::map m; -}; - -BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) { - const int size = static_cast(state.range(0)); - for (auto _ : state) { - for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); - } - } - state.SetItemsProcessed(state.iterations() * size); -} -BENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(1 << 3, 1 << 12); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/multiple_ranges_test.cc b/interpreter/llvm/src/utils/benchmark/test/multiple_ranges_test.cc deleted file mode 100644 index c64acabc25c98..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/multiple_ranges_test.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include -#include - -class MultipleRangesFixture : public ::benchmark::Fixture { - public: - MultipleRangesFixture() - : expectedValues({{1, 3, 5}, - {1, 3, 8}, - {1, 3, 15}, - {2, 3, 5}, - {2, 3, 8}, - {2, 3, 15}, - {1, 4, 5}, - {1, 4, 8}, - {1, 4, 15}, - {2, 4, 5}, - {2, 4, 8}, - {2, 4, 15}, - {1, 7, 5}, - {1, 7, 8}, - {1, 7, 15}, - {2, 7, 5}, - {2, 7, 8}, - {2, 7, 15}, - {7, 6, 3}}) {} - - void SetUp(const ::benchmark::State& state) { - std::vector ranges = {state.range(0), state.range(1), - state.range(2)}; - - assert(expectedValues.find(ranges) != expectedValues.end()); - - actualValues.insert(ranges); - } - - // NOTE: This is not TearDown as we want to check after _all_ runs are - // complete. - virtual ~MultipleRangesFixture() { - assert(actualValues.size() == expectedValues.size()); - if (actualValues.size() != expectedValues.size()) { - std::cout << "EXPECTED\n"; - for (auto v : expectedValues) { - std::cout << "{"; - for (int64_t iv : v) { - std::cout << iv << ", "; - } - std::cout << "}\n"; - } - std::cout << "ACTUAL\n"; - for (auto v : actualValues) { - std::cout << "{"; - for (int64_t iv : v) { - std::cout << iv << ", "; - } - std::cout << "}\n"; - } - } - } - - std::set> expectedValues; - std::set> actualValues; -}; - -BENCHMARK_DEFINE_F(MultipleRangesFixture, Empty)(benchmark::State& state) { - for (auto _ : state) { - int64_t product = state.range(0) * state.range(1) * state.range(2); - for (int64_t x = 0; x < product; x++) { - benchmark::DoNotOptimize(x); - } - } -} - -BENCHMARK_REGISTER_F(MultipleRangesFixture, Empty) - ->RangeMultiplier(2) - ->Ranges({{1, 2}, {3, 7}, {5, 15}}) - ->Args({7, 6, 3}); - -void BM_CheckDefaultArgument(benchmark::State& state) { - // Test that the 'range()' without an argument is the same as 'range(0)'. - assert(state.range() == state.range(0)); - assert(state.range() != state.range(1)); - for (auto _ : state) { - } -} -BENCHMARK(BM_CheckDefaultArgument)->Ranges({{1, 5}, {6, 10}}); - -static void BM_MultipleRanges(benchmark::State& st) { - for (auto _ : st) { - } -} -BENCHMARK(BM_MultipleRanges)->Ranges({{5, 5}, {6, 6}}); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/options_test.cc b/interpreter/llvm/src/utils/benchmark/test/options_test.cc deleted file mode 100644 index fdec69174eec0..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/options_test.cc +++ /dev/null @@ -1,65 +0,0 @@ -#include "benchmark/benchmark.h" -#include -#include - -#if defined(NDEBUG) -#undef NDEBUG -#endif -#include - -void BM_basic(benchmark::State& state) { - for (auto _ : state) { - } -} - -void BM_basic_slow(benchmark::State& state) { - std::chrono::milliseconds sleep_duration(state.range(0)); - for (auto _ : state) { - std::this_thread::sleep_for( - std::chrono::duration_cast(sleep_duration)); - } -} - -BENCHMARK(BM_basic); -BENCHMARK(BM_basic)->Arg(42); -BENCHMARK(BM_basic_slow)->Arg(10)->Unit(benchmark::kNanosecond); -BENCHMARK(BM_basic_slow)->Arg(100)->Unit(benchmark::kMicrosecond); -BENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kMillisecond); -BENCHMARK(BM_basic)->Range(1, 8); -BENCHMARK(BM_basic)->RangeMultiplier(2)->Range(1, 8); -BENCHMARK(BM_basic)->DenseRange(10, 15); -BENCHMARK(BM_basic)->Args({42, 42}); -BENCHMARK(BM_basic)->Ranges({{64, 512}, {64, 512}}); -BENCHMARK(BM_basic)->MinTime(0.7); -BENCHMARK(BM_basic)->UseRealTime(); -BENCHMARK(BM_basic)->ThreadRange(2, 4); -BENCHMARK(BM_basic)->ThreadPerCpu(); -BENCHMARK(BM_basic)->Repetitions(3); - -void CustomArgs(benchmark::internal::Benchmark* b) { - for (int i = 0; i < 10; ++i) { - b->Arg(i); - } -} - -BENCHMARK(BM_basic)->Apply(CustomArgs); - -void BM_explicit_iteration_count(benchmark::State& state) { - // Test that benchmarks specified with an explicit iteration count are - // only run once. - static bool invoked_before = false; - assert(!invoked_before); - invoked_before = true; - - // Test that the requested iteration count is respected. - assert(state.max_iterations == 42); - size_t actual_iterations = 0; - for (auto _ : state) - ++actual_iterations; - assert(state.iterations() == state.max_iterations); - assert(state.iterations() == 42); - -} -BENCHMARK(BM_explicit_iteration_count)->Iterations(42); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/output_test.h b/interpreter/llvm/src/utils/benchmark/test/output_test.h deleted file mode 100644 index 897a13866baec..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/output_test.h +++ /dev/null @@ -1,201 +0,0 @@ -#ifndef TEST_OUTPUT_TEST_H -#define TEST_OUTPUT_TEST_H - -#undef NDEBUG -#include -#include -#include -#include -#include -#include -#include - -#include "../src/re.h" -#include "benchmark/benchmark.h" - -#define CONCAT2(x, y) x##y -#define CONCAT(x, y) CONCAT2(x, y) - -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = ::AddCases(__VA_ARGS__) - -#define SET_SUBSTITUTIONS(...) \ - int CONCAT(dummy, __LINE__) = ::SetSubstitutions(__VA_ARGS__) - -enum MatchRules { - MR_Default, // Skip non-matching lines until a match is found. - MR_Next, // Match must occur on the next line. - MR_Not // No line between the current position and the next match matches - // the regex -}; - -struct TestCase { - TestCase(std::string re, int rule = MR_Default); - - std::string regex_str; - int match_rule; - std::string substituted_regex; - std::shared_ptr regex; -}; - -enum TestCaseID { - TC_ConsoleOut, - TC_ConsoleErr, - TC_JSONOut, - TC_JSONErr, - TC_CSVOut, - TC_CSVErr, - - TC_NumID // PRIVATE -}; - -// Add a list of test cases to be run against the output specified by -// 'ID' -int AddCases(TestCaseID ID, std::initializer_list il); - -// Add or set a list of substitutions to be performed on constructed regex's -// See 'output_test_helper.cc' for a list of default substitutions. -int SetSubstitutions( - std::initializer_list> il); - -// Run all output tests. -void RunOutputTests(int argc, char* argv[]); - -// ========================================================================= // -// ------------------------- Results checking ------------------------------ // -// ========================================================================= // - -// Call this macro to register a benchmark for checking its results. This -// should be all that's needed. It subscribes a function to check the (CSV) -// results of a benchmark. This is done only after verifying that the output -// strings are really as expected. -// bm_name_pattern: a name or a regex pattern which will be matched against -// all the benchmark names. Matching benchmarks -// will be the subject of a call to checker_function -// checker_function: should be of type ResultsCheckFn (see below) -#define CHECK_BENCHMARK_RESULTS(bm_name_pattern, checker_function) \ - size_t CONCAT(dummy, __LINE__) = AddChecker(bm_name_pattern, checker_function) - -struct Results; -typedef std::function< void(Results const&) > ResultsCheckFn; - -size_t AddChecker(const char* bm_name_pattern, ResultsCheckFn fn); - -// Class holding the results of a benchmark. -// It is passed in calls to checker functions. -struct Results { - - // the benchmark name - std::string name; - // the benchmark fields - std::map< std::string, std::string > values; - - Results(const std::string& n) : name(n) {} - - int NumThreads() const; - - typedef enum { kCpuTime, kRealTime } BenchmarkTime; - - // get cpu_time or real_time in seconds - double GetTime(BenchmarkTime which) const; - - // get the real_time duration of the benchmark in seconds. - // it is better to use fuzzy float checks for this, as the float - // ASCII formatting is lossy. - double DurationRealTime() const { - return GetAs< double >("iterations") * GetTime(kRealTime); - } - // get the cpu_time duration of the benchmark in seconds - double DurationCPUTime() const { - return GetAs< double >("iterations") * GetTime(kCpuTime); - } - - // get the string for a result by name, or nullptr if the name - // is not found - const std::string* Get(const char* entry_name) const { - auto it = values.find(entry_name); - if(it == values.end()) return nullptr; - return &it->second; - } - - // get a result by name, parsed as a specific type. - // NOTE: for counters, use GetCounterAs instead. - template - T GetAs(const char* entry_name) const; - - // counters are written as doubles, so they have to be read first - // as a double, and only then converted to the asked type. - template - T GetCounterAs(const char* entry_name) const { - double dval = GetAs< double >(entry_name); - T tval = static_cast< T >(dval); - return tval; - } -}; - -template -T Results::GetAs(const char* entry_name) const { - auto *sv = Get(entry_name); - CHECK(sv != nullptr && !sv->empty()); - std::stringstream ss; - ss << *sv; - T out; - ss >> out; - CHECK(!ss.fail()); - return out; -} - -//---------------------------------- -// Macros to help in result checking. Do not use them with arguments causing -// side-effects. - -#define _CHECK_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value) \ - CONCAT(CHECK_, relationship) \ - (entry.getfn< var_type >(var_name), (value)) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "expected (" << #var_type << ")" << (var_name) \ - << "=" << (entry).getfn< var_type >(var_name) \ - << " to be " #relationship " to " << (value) << "\n" - -// check with tolerance. eps_factor is the tolerance window, which is -// interpreted relative to value (eg, 0.1 means 10% of value). -#define _CHECK_FLOAT_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value, eps_factor) \ - CONCAT(CHECK_FLOAT_, relationship) \ - (entry.getfn< var_type >(var_name), (value), (eps_factor) * (value)) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "expected (" << #var_type << ")" << (var_name) \ - << "=" << (entry).getfn< var_type >(var_name) \ - << " to be " #relationship " to " << (value) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "with tolerance of " << (eps_factor) * (value) \ - << " (" << (eps_factor)*100. << "%), " \ - << "but delta was " << ((entry).getfn< var_type >(var_name) - (value)) \ - << " (" << (((entry).getfn< var_type >(var_name) - (value)) \ - / \ - ((value) > 1.e-5 || value < -1.e-5 ? value : 1.e-5)*100.) \ - << "%)" - -#define CHECK_RESULT_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetAs, var_type, var_name, relationship, value) - -#define CHECK_COUNTER_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetCounterAs, var_type, var_name, relationship, value) - -#define CHECK_FLOAT_RESULT_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetAs, double, var_name, relationship, value, eps_factor) - -#define CHECK_FLOAT_COUNTER_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetCounterAs, double, var_name, relationship, value, eps_factor) - -// ========================================================================= // -// --------------------------- Misc Utilities ------------------------------ // -// ========================================================================= // - -namespace { - -const char* const dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; - -} // end namespace - -#endif // TEST_OUTPUT_TEST_H diff --git a/interpreter/llvm/src/utils/benchmark/test/output_test_helper.cc b/interpreter/llvm/src/utils/benchmark/test/output_test_helper.cc deleted file mode 100644 index 6b18fe43593fc..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/output_test_helper.cc +++ /dev/null @@ -1,423 +0,0 @@ -#include -#include -#include -#include -#include - -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "../src/re.h" // NOTE: re.h is for internal use only -#include "output_test.h" -#include "../src/benchmark_api_internal.h" - -// ========================================================================= // -// ------------------------------ Internals -------------------------------- // -// ========================================================================= // -namespace internal { -namespace { - -using TestCaseList = std::vector; - -// Use a vector because the order elements are added matters during iteration. -// std::map/unordered_map don't guarantee that. -// For example: -// SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}}); -// Substitute("%HelloWorld") // Always expands to Hello. -using SubMap = std::vector>; - -TestCaseList& GetTestCaseList(TestCaseID ID) { - // Uses function-local statics to ensure initialization occurs - // before first use. - static TestCaseList lists[TC_NumID]; - return lists[ID]; -} - -SubMap& GetSubstitutions() { - // Don't use 'dec_re' from header because it may not yet be initialized. - static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; - static SubMap map = { - {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"}, - // human-readable float - {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?"}, - {"%int", "[ ]*[0-9]+"}, - {" %s ", "[ ]+"}, - {"%time", "[ ]*[0-9]{1,6} ns"}, - {"%console_report", "[ ]*[0-9]{1,6} ns [ ]*[0-9]{1,6} ns [ ]*[0-9]+"}, - {"%console_us_report", "[ ]*[0-9] us [ ]*[0-9] us [ ]*[0-9]+"}, - {"%csv_header", - "name,iterations,real_time,cpu_time,time_unit,bytes_per_second," - "items_per_second,label,error_occurred,error_message"}, - {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"}, - {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"}, - {"%csv_bytes_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"}, - {"%csv_items_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,," + safe_dec_re + ",,,"}, - {"%csv_bytes_items_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + - "," + safe_dec_re + ",,,"}, - {"%csv_label_report_begin", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,"}, - {"%csv_label_report_end", ",,"}}; - return map; -} - -std::string PerformSubstitutions(std::string source) { - SubMap const& subs = GetSubstitutions(); - using SizeT = std::string::size_type; - for (auto const& KV : subs) { - SizeT pos; - SizeT next_start = 0; - while ((pos = source.find(KV.first, next_start)) != std::string::npos) { - next_start = pos + KV.second.size(); - source.replace(pos, KV.first.size(), KV.second); - } - } - return source; -} - -void CheckCase(std::stringstream& remaining_output, TestCase const& TC, - TestCaseList const& not_checks) { - std::string first_line; - bool on_first = true; - std::string line; - while (remaining_output.eof() == false) { - CHECK(remaining_output.good()); - std::getline(remaining_output, line); - if (on_first) { - first_line = line; - on_first = false; - } - for (const auto& NC : not_checks) { - CHECK(!NC.regex->Match(line)) - << "Unexpected match for line \"" << line << "\" for MR_Not regex \"" - << NC.regex_str << "\"" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; - } - if (TC.regex->Match(line)) return; - CHECK(TC.match_rule != MR_Next) - << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str - << "\"" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; - } - CHECK(remaining_output.eof() == false) - << "End of output reached before match for regex \"" << TC.regex_str - << "\" was found" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; -} - -void CheckCases(TestCaseList const& checks, std::stringstream& output) { - std::vector not_checks; - for (size_t i = 0; i < checks.size(); ++i) { - const auto& TC = checks[i]; - if (TC.match_rule == MR_Not) { - not_checks.push_back(TC); - continue; - } - CheckCase(output, TC, not_checks); - not_checks.clear(); - } -} - -class TestReporter : public benchmark::BenchmarkReporter { - public: - TestReporter(std::vector reps) - : reporters_(reps) {} - - virtual bool ReportContext(const Context& context) { - bool last_ret = false; - bool first = true; - for (auto rep : reporters_) { - bool new_ret = rep->ReportContext(context); - CHECK(first || new_ret == last_ret) - << "Reports return different values for ReportContext"; - first = false; - last_ret = new_ret; - } - (void)first; - return last_ret; - } - - void ReportRuns(const std::vector& report) { - for (auto rep : reporters_) rep->ReportRuns(report); - } - void Finalize() { - for (auto rep : reporters_) rep->Finalize(); - } - - private: - std::vector reporters_; -}; -} - -} // end namespace internal - -// ========================================================================= // -// -------------------------- Results checking ----------------------------- // -// ========================================================================= // - -namespace internal { - -// Utility class to manage subscribers for checking benchmark results. -// It works by parsing the CSV output to read the results. -class ResultsChecker { - public: - - struct PatternAndFn : public TestCase { // reusing TestCase for its regexes - PatternAndFn(const std::string& rx, ResultsCheckFn fn_) - : TestCase(rx), fn(fn_) {} - ResultsCheckFn fn; - }; - - std::vector< PatternAndFn > check_patterns; - std::vector< Results > results; - std::vector< std::string > field_names; - - void Add(const std::string& entry_pattern, ResultsCheckFn fn); - - void CheckResults(std::stringstream& output); - - private: - - void SetHeader_(const std::string& csv_header); - void SetValues_(const std::string& entry_csv_line); - - std::vector< std::string > SplitCsv_(const std::string& line); - -}; - -// store the static ResultsChecker in a function to prevent initialization -// order problems -ResultsChecker& GetResultsChecker() { - static ResultsChecker rc; - return rc; -} - -// add a results checker for a benchmark -void ResultsChecker::Add(const std::string& entry_pattern, ResultsCheckFn fn) { - check_patterns.emplace_back(entry_pattern, fn); -} - -// check the results of all subscribed benchmarks -void ResultsChecker::CheckResults(std::stringstream& output) { - // first reset the stream to the start - { - auto start = std::ios::streampos(0); - // clear before calling tellg() - output.clear(); - // seek to zero only when needed - if(output.tellg() > start) output.seekg(start); - // and just in case - output.clear(); - } - // now go over every line and publish it to the ResultsChecker - std::string line; - bool on_first = true; - while (output.eof() == false) { - CHECK(output.good()); - std::getline(output, line); - if (on_first) { - SetHeader_(line); // this is important - on_first = false; - continue; - } - SetValues_(line); - } - // finally we can call the subscribed check functions - for(const auto& p : check_patterns) { - VLOG(2) << "--------------------------------\n"; - VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n"; - for(const auto& r : results) { - if(!p.regex->Match(r.name)) { - VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n"; - continue; - } else { - VLOG(2) << p.regex_str << " is matched by " << r.name << "\n"; - } - VLOG(1) << "Checking results of " << r.name << ": ... \n"; - p.fn(r); - VLOG(1) << "Checking results of " << r.name << ": OK.\n"; - } - } -} - -// prepare for the names in this header -void ResultsChecker::SetHeader_(const std::string& csv_header) { - field_names = SplitCsv_(csv_header); -} - -// set the values for a benchmark -void ResultsChecker::SetValues_(const std::string& entry_csv_line) { - if(entry_csv_line.empty()) return; // some lines are empty - CHECK(!field_names.empty()); - auto vals = SplitCsv_(entry_csv_line); - CHECK_EQ(vals.size(), field_names.size()); - results.emplace_back(vals[0]); // vals[0] is the benchmark name - auto &entry = results.back(); - for (size_t i = 1, e = vals.size(); i < e; ++i) { - entry.values[field_names[i]] = vals[i]; - } -} - -// a quick'n'dirty csv splitter (eliminating quotes) -std::vector< std::string > ResultsChecker::SplitCsv_(const std::string& line) { - std::vector< std::string > out; - if(line.empty()) return out; - if(!field_names.empty()) out.reserve(field_names.size()); - size_t prev = 0, pos = line.find_first_of(','), curr = pos; - while(pos != line.npos) { - CHECK(curr > 0); - if(line[prev] == '"') ++prev; - if(line[curr-1] == '"') --curr; - out.push_back(line.substr(prev, curr-prev)); - prev = pos + 1; - pos = line.find_first_of(',', pos + 1); - curr = pos; - } - curr = line.size(); - if(line[prev] == '"') ++prev; - if(line[curr-1] == '"') --curr; - out.push_back(line.substr(prev, curr-prev)); - return out; -} - -} // end namespace internal - -size_t AddChecker(const char* bm_name, ResultsCheckFn fn) -{ - auto &rc = internal::GetResultsChecker(); - rc.Add(bm_name, fn); - return rc.results.size(); -} - -int Results::NumThreads() const { - auto pos = name.find("/threads:"); - if(pos == name.npos) return 1; - auto end = name.find('/', pos + 9); - std::stringstream ss; - ss << name.substr(pos + 9, end); - int num = 1; - ss >> num; - CHECK(!ss.fail()); - return num; -} - -double Results::GetTime(BenchmarkTime which) const { - CHECK(which == kCpuTime || which == kRealTime); - const char *which_str = which == kCpuTime ? "cpu_time" : "real_time"; - double val = GetAs< double >(which_str); - auto unit = Get("time_unit"); - CHECK(unit); - if(*unit == "ns") { - return val * 1.e-9; - } else if(*unit == "us") { - return val * 1.e-6; - } else if(*unit == "ms") { - return val * 1.e-3; - } else if(*unit == "s") { - return val; - } else { - CHECK(1 == 0) << "unknown time unit: " << *unit; - return 0; - } -} - -// ========================================================================= // -// -------------------------- Public API Definitions------------------------ // -// ========================================================================= // - -TestCase::TestCase(std::string re, int rule) - : regex_str(std::move(re)), - match_rule(rule), - substituted_regex(internal::PerformSubstitutions(regex_str)), - regex(std::make_shared()) { - std::string err_str; - regex->Init(substituted_regex,& err_str); - CHECK(err_str.empty()) << "Could not construct regex \"" << substituted_regex - << "\"" - << "\n originally \"" << regex_str << "\"" - << "\n got error: " << err_str; -} - -int AddCases(TestCaseID ID, std::initializer_list il) { - auto& L = internal::GetTestCaseList(ID); - L.insert(L.end(), il); - return 0; -} - -int SetSubstitutions( - std::initializer_list> il) { - auto& subs = internal::GetSubstitutions(); - for (auto KV : il) { - bool exists = false; - KV.second = internal::PerformSubstitutions(KV.second); - for (auto& EKV : subs) { - if (EKV.first == KV.first) { - EKV.second = std::move(KV.second); - exists = true; - break; - } - } - if (!exists) subs.push_back(std::move(KV)); - } - return 0; -} - -void RunOutputTests(int argc, char* argv[]) { - using internal::GetTestCaseList; - benchmark::Initialize(&argc, argv); - auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/true); - benchmark::ConsoleReporter CR(options); - benchmark::JSONReporter JR; - benchmark::CSVReporter CSVR; - struct ReporterTest { - const char* name; - std::vector& output_cases; - std::vector& error_cases; - benchmark::BenchmarkReporter& reporter; - std::stringstream out_stream; - std::stringstream err_stream; - - ReporterTest(const char* n, std::vector& out_tc, - std::vector& err_tc, - benchmark::BenchmarkReporter& br) - : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) { - reporter.SetOutputStream(&out_stream); - reporter.SetErrorStream(&err_stream); - } - } TestCases[] = { - {"ConsoleReporter", GetTestCaseList(TC_ConsoleOut), - GetTestCaseList(TC_ConsoleErr), CR}, - {"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr), - JR}, - {"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr), - CSVR}, - }; - - // Create the test reporter and run the benchmarks. - std::cout << "Running benchmarks...\n"; - internal::TestReporter test_rep({&CR, &JR, &CSVR}); - benchmark::RunSpecifiedBenchmarks(&test_rep); - - for (auto& rep_test : TestCases) { - std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n"; - std::string banner(msg.size() - 1, '-'); - std::cout << banner << msg << banner << "\n"; - - std::cerr << rep_test.err_stream.str(); - std::cout << rep_test.out_stream.str(); - - internal::CheckCases(rep_test.error_cases, rep_test.err_stream); - internal::CheckCases(rep_test.output_cases, rep_test.out_stream); - - std::cout << "\n"; - } - - // now that we know the output is as expected, we can dispatch - // the checks to subscribees. - auto &csv = TestCases[2]; - // would use == but gcc spits a warning - CHECK(std::strcmp(csv.name, "CSVReporter") == 0); - internal::GetResultsChecker().CheckResults(csv.out_stream); -} diff --git a/interpreter/llvm/src/utils/benchmark/test/register_benchmark_test.cc b/interpreter/llvm/src/utils/benchmark/test/register_benchmark_test.cc deleted file mode 100644 index 8ab2c299393fa..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/register_benchmark_test.cc +++ /dev/null @@ -1,182 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "benchmark/benchmark.h" - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual void ReportRuns(const std::vector& report) { - all_runs_.insert(all_runs_.end(), begin(report), end(report)); - ConsoleReporter::ReportRuns(report); - } - - std::vector all_runs_; -}; - -struct TestCase { - std::string name; - const char* label; - // Note: not explicit as we rely on it being converted through ADD_CASES. - TestCase(const char* xname) : TestCase(xname, nullptr) {} - TestCase(const char* xname, const char* xlabel) - : name(xname), label(xlabel) {} - - typedef benchmark::BenchmarkReporter::Run Run; - - void CheckRun(Run const& run) const { - CHECK(name == run.benchmark_name) << "expected " << name << " got " - << run.benchmark_name; - if (label) { - CHECK(run.report_label == label) << "expected " << label << " got " - << run.report_label; - } else { - CHECK(run.report_label == ""); - } - } -}; - -std::vector ExpectedResults; - -int AddCases(std::initializer_list const& v) { - for (auto N : v) { - ExpectedResults.push_back(N); - } - return 0; -} - -#define CONCAT(x, y) CONCAT2(x, y) -#define CONCAT2(x, y) x##y -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases({__VA_ARGS__}) - -} // end namespace - -typedef benchmark::internal::Benchmark* ReturnVal; - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with no additional arguments -//----------------------------------------------------------------------------// -void BM_function(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_function); -ReturnVal dummy = benchmark::RegisterBenchmark( - "BM_function_manual_registration", BM_function); -ADD_CASES({"BM_function"}, {"BM_function_manual_registration"}); - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with additional arguments -// Note: GCC <= 4.8 do not support this form of RegisterBenchmark because they -// reject the variadic pack expansion of lambda captures. -//----------------------------------------------------------------------------// -#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - -void BM_extra_args(benchmark::State& st, const char* label) { - for (auto _ : st) { - } - st.SetLabel(label); -} -int RegisterFromFunction() { - std::pair cases[] = { - {"test1", "One"}, {"test2", "Two"}, {"test3", "Three"}}; - for (auto const& c : cases) - benchmark::RegisterBenchmark(c.first, &BM_extra_args, c.second); - return 0; -} -int dummy2 = RegisterFromFunction(); -ADD_CASES({"test1", "One"}, {"test2", "Two"}, {"test3", "Three"}); - -#endif // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with different callable types -//----------------------------------------------------------------------------// - -struct CustomFixture { - void operator()(benchmark::State& st) { - for (auto _ : st) { - } - } -}; - -void TestRegistrationAtRuntime() { -#ifdef BENCHMARK_HAS_CXX11 - { - CustomFixture fx; - benchmark::RegisterBenchmark("custom_fixture", fx); - AddCases({"custom_fixture"}); - } -#endif -#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - { - const char* x = "42"; - auto capturing_lam = [=](benchmark::State& st) { - for (auto _ : st) { - } - st.SetLabel(x); - }; - benchmark::RegisterBenchmark("lambda_benchmark", capturing_lam); - AddCases({{"lambda_benchmark", x}}); - } -#endif -} - -// Test that all benchmarks, registered at either during static init or runtime, -// are run and the results are passed to the reported. -void RunTestOne() { - TestRegistrationAtRuntime(); - - TestReporter test_reporter; - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); -} - -// Test that ClearRegisteredBenchmarks() clears all previously registered -// benchmarks. -// Also test that new benchmarks can be registered and ran afterwards. -void RunTestTwo() { - assert(ExpectedResults.size() != 0 && - "must have at least one registered benchmark"); - ExpectedResults.clear(); - benchmark::ClearRegisteredBenchmarks(); - - TestReporter test_reporter; - size_t num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter); - assert(num_ran == 0); - assert(test_reporter.all_runs_.begin() == test_reporter.all_runs_.end()); - - TestRegistrationAtRuntime(); - num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter); - assert(num_ran == ExpectedResults.size()); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); -} - -int main(int argc, char* argv[]) { - benchmark::Initialize(&argc, argv); - - RunTestOne(); - RunTestTwo(); -} diff --git a/interpreter/llvm/src/utils/benchmark/test/reporter_output_test.cc b/interpreter/llvm/src/utils/benchmark/test/reporter_output_test.cc deleted file mode 100644 index 23eb1baf63376..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/reporter_output_test.cc +++ /dev/null @@ -1,382 +0,0 @@ - -#undef NDEBUG -#include - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// ========================================================================= // -// ---------------------- Testing Prologue Output -------------------------- // -// ========================================================================= // - -ADD_CASES(TC_ConsoleOut, - {{"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations$", MR_Next}, - {"^[-]+$", MR_Next}}); -static int AddContextCases() { - AddCases(TC_ConsoleErr, - { - {"%int[-/]%int[-/]%int %int:%int:%int$", MR_Default}, - {"Running .*/reporter_output_test(\\.exe)?$", MR_Next}, - {"Run on \\(%int X %float MHz CPU s\\)", MR_Next}, - }); - AddCases(TC_JSONOut, {{"^\\{", MR_Default}, - {"\"context\":", MR_Next}, - {"\"date\": \"", MR_Next}, - {"\"executable\": \".*/reporter_output_test(\\.exe)?\",", MR_Next}, - {"\"num_cpus\": %int,$", MR_Next}, - {"\"mhz_per_cpu\": %float,$", MR_Next}, - {"\"cpu_scaling_enabled\": ", MR_Next}, - {"\"caches\": \\[$", MR_Next}}); - auto const& Caches = benchmark::CPUInfo::Get().caches; - if (!Caches.empty()) { - AddCases(TC_ConsoleErr, {{"CPU Caches:$", MR_Next}}); - } - for (size_t I = 0; I < Caches.size(); ++I) { - std::string num_caches_str = - Caches[I].num_sharing != 0 ? " \\(x%int\\)$" : "$"; - AddCases( - TC_ConsoleErr, - {{"L%int (Data|Instruction|Unified) %intK" + num_caches_str, MR_Next}}); - AddCases(TC_JSONOut, {{"\\{$", MR_Next}, - {"\"type\": \"", MR_Next}, - {"\"level\": %int,$", MR_Next}, - {"\"size\": %int,$", MR_Next}, - {"\"num_sharing\": %int$", MR_Next}, - {"}[,]{0,1}$", MR_Next}}); - } - - AddCases(TC_JSONOut, {{"],$"}}); - return 0; -} -int dummy_register = AddContextCases(); -ADD_CASES(TC_CSVOut, {{"%csv_header"}}); - -// ========================================================================= // -// ------------------------ Testing Basic Output --------------------------- // -// ========================================================================= // - -void BM_basic(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_basic); - -ADD_CASES(TC_ConsoleOut, {{"^BM_basic %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_basic\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\"$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_basic\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Bytes per Second Output ---------------- // -// ========================================================================= // - -void BM_bytes_per_second(benchmark::State& state) { - for (auto _ : state) { - } - state.SetBytesProcessed(1); -} -BENCHMARK(BM_bytes_per_second); - -ADD_CASES(TC_ConsoleOut, - {{"^BM_bytes_per_second %console_report +%float[kM]{0,1}B/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_bytes_per_second\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bytes_per_second\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_bytes_per_second\",%csv_bytes_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Items per Second Output ---------------- // -// ========================================================================= // - -void BM_items_per_second(benchmark::State& state) { - for (auto _ : state) { - } - state.SetItemsProcessed(1); -} -BENCHMARK(BM_items_per_second); - -ADD_CASES(TC_ConsoleOut, - {{"^BM_items_per_second %console_report +%float[kM]{0,1} items/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_items_per_second\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"items_per_second\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_items_per_second\",%csv_items_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Label Output --------------------------- // -// ========================================================================= // - -void BM_label(benchmark::State& state) { - for (auto _ : state) { - } - state.SetLabel("some label"); -} -BENCHMARK(BM_label); - -ADD_CASES(TC_ConsoleOut, {{"^BM_label %console_report some label$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_label\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"label\": \"some label\"$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_label\",%csv_label_report_begin\"some " - "label\"%csv_label_report_end$"}}); - -// ========================================================================= // -// ------------------------ Testing Error Output --------------------------- // -// ========================================================================= // - -void BM_error(benchmark::State& state) { - state.SkipWithError("message"); - for (auto _ : state) { - } -} -BENCHMARK(BM_error); -ADD_CASES(TC_ConsoleOut, {{"^BM_error[ ]+ERROR OCCURRED: 'message'$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_error\",$"}, - {"\"error_occurred\": true,$", MR_Next}, - {"\"error_message\": \"message\",$", MR_Next}}); - -ADD_CASES(TC_CSVOut, {{"^\"BM_error\",,,,,,,,true,\"message\"$"}}); - -// ========================================================================= // -// ------------------------ Testing No Arg Name Output ----------------------- -// // -// ========================================================================= // - -void BM_no_arg_name(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_no_arg_name)->Arg(3); -ADD_CASES(TC_ConsoleOut, {{"^BM_no_arg_name/3 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_no_arg_name/3\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_no_arg_name/3\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Arg Name Output ----------------------- // -// ========================================================================= // - -void BM_arg_name(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_arg_name)->ArgName("first")->Arg(3); -ADD_CASES(TC_ConsoleOut, {{"^BM_arg_name/first:3 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_arg_name/first:3\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_arg_name/first:3\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Arg Names Output ----------------------- // -// ========================================================================= // - -void BM_arg_names(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_arg_names)->Args({2, 5, 4})->ArgNames({"first", "", "third"}); -ADD_CASES(TC_ConsoleOut, - {{"^BM_arg_names/first:2/5/third:4 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_arg_names/first:2/5/third:4\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_arg_names/first:2/5/third:4\",%csv_report$"}}); - -// ========================================================================= // -// ----------------------- Testing Complexity Output ----------------------- // -// ========================================================================= // - -void BM_Complexity_O1(benchmark::State& state) { - for (auto _ : state) { - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1); -SET_SUBSTITUTIONS({{"%bigOStr", "[ ]* %float \\([0-9]+\\)"}, - {"%RMS", "[ ]*[0-9]+ %"}}); -ADD_CASES(TC_ConsoleOut, {{"^BM_Complexity_O1_BigO %bigOStr %bigOStr[ ]*$"}, - {"^BM_Complexity_O1_RMS %RMS %RMS[ ]*$"}}); - -// ========================================================================= // -// ----------------------- Testing Aggregate Output ------------------------ // -// ========================================================================= // - -// Test that non-aggregate data is printed by default -void BM_Repeat(benchmark::State& state) { - for (auto _ : state) { - } -} -// need two repetitions min to be able to output any aggregate output -BENCHMARK(BM_Repeat)->Repetitions(2); -ADD_CASES(TC_ConsoleOut, {{"^BM_Repeat/repeats:2 %console_report$"}, - {"^BM_Repeat/repeats:2 %console_report$"}, - {"^BM_Repeat/repeats:2_mean %console_report$"}, - {"^BM_Repeat/repeats:2_median %console_report$"}, - {"^BM_Repeat/repeats:2_stddev %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:2\",$"}, - {"\"name\": \"BM_Repeat/repeats:2\",$"}, - {"\"name\": \"BM_Repeat/repeats:2_mean\",$"}, - {"\"name\": \"BM_Repeat/repeats:2_median\",$"}, - {"\"name\": \"BM_Repeat/repeats:2_stddev\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:2\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_stddev\",%csv_report$"}}); -// but for two repetitions, mean and median is the same, so let's repeat.. -BENCHMARK(BM_Repeat)->Repetitions(3); -ADD_CASES(TC_ConsoleOut, {{"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3_mean %console_report$"}, - {"^BM_Repeat/repeats:3_median %console_report$"}, - {"^BM_Repeat/repeats:3_stddev %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"name\": \"BM_Repeat/repeats:3_mean\",$"}, - {"\"name\": \"BM_Repeat/repeats:3_median\",$"}, - {"\"name\": \"BM_Repeat/repeats:3_stddev\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_stddev\",%csv_report$"}}); -// median differs between even/odd number of repetitions, so just to be sure -BENCHMARK(BM_Repeat)->Repetitions(4); -ADD_CASES(TC_ConsoleOut, {{"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4_mean %console_report$"}, - {"^BM_Repeat/repeats:4_median %console_report$"}, - {"^BM_Repeat/repeats:4_stddev %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"name\": \"BM_Repeat/repeats:4_mean\",$"}, - {"\"name\": \"BM_Repeat/repeats:4_median\",$"}, - {"\"name\": \"BM_Repeat/repeats:4_stddev\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_stddev\",%csv_report$"}}); - -// Test that a non-repeated test still prints non-aggregate results even when -// only-aggregate reports have been requested -void BM_RepeatOnce(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_RepeatOnce)->Repetitions(1)->ReportAggregatesOnly(); -ADD_CASES(TC_ConsoleOut, {{"^BM_RepeatOnce/repeats:1 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_RepeatOnce/repeats:1\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_RepeatOnce/repeats:1\",%csv_report$"}}); - -// Test that non-aggregate data is not reported -void BM_SummaryRepeat(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly(); -ADD_CASES(TC_ConsoleOut, - {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"^BM_SummaryRepeat/repeats:3_mean %console_report$"}, - {"^BM_SummaryRepeat/repeats:3_median %console_report$"}, - {"^BM_SummaryRepeat/repeats:3_stddev %console_report$"}}); -ADD_CASES(TC_JSONOut, {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_mean\",$"}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_median\",$"}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_stddev\",$"}}); -ADD_CASES(TC_CSVOut, {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"^\"BM_SummaryRepeat/repeats:3_mean\",%csv_report$"}, - {"^\"BM_SummaryRepeat/repeats:3_median\",%csv_report$"}, - {"^\"BM_SummaryRepeat/repeats:3_stddev\",%csv_report$"}}); - -void BM_RepeatTimeUnit(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_RepeatTimeUnit) - ->Repetitions(3) - ->ReportAggregatesOnly() - ->Unit(benchmark::kMicrosecond); -ADD_CASES(TC_ConsoleOut, - {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"^BM_RepeatTimeUnit/repeats:3_mean %console_us_report$"}, - {"^BM_RepeatTimeUnit/repeats:3_median %console_us_report$"}, - {"^BM_RepeatTimeUnit/repeats:3_stddev %console_us_report$"}}); -ADD_CASES(TC_JSONOut, {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_mean\",$"}, - {"\"time_unit\": \"us\",?$"}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_median\",$"}, - {"\"time_unit\": \"us\",?$"}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_stddev\",$"}, - {"\"time_unit\": \"us\",?$"}}); -ADD_CASES(TC_CSVOut, - {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"^\"BM_RepeatTimeUnit/repeats:3_mean\",%csv_us_report$"}, - {"^\"BM_RepeatTimeUnit/repeats:3_median\",%csv_us_report$"}, - {"^\"BM_RepeatTimeUnit/repeats:3_stddev\",%csv_us_report$"}}); - -// ========================================================================= // -// -------------------- Testing user-provided statistics ------------------- // -// ========================================================================= // - -const auto UserStatistics = [](const std::vector& v) { - return v.back(); -}; -void BM_UserStats(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_UserStats) - ->Repetitions(3) - ->ComputeStatistics("", UserStatistics); -// check that user-provided stats is calculated, and is after the default-ones -// empty string as name is intentional, it would sort before anything else -ADD_CASES(TC_ConsoleOut, {{"^BM_UserStats/repeats:3 %console_report$"}, - {"^BM_UserStats/repeats:3 %console_report$"}, - {"^BM_UserStats/repeats:3 %console_report$"}, - {"^BM_UserStats/repeats:3_mean %console_report$"}, - {"^BM_UserStats/repeats:3_median %console_report$"}, - {"^BM_UserStats/repeats:3_stddev %console_report$"}, - {"^BM_UserStats/repeats:3_ %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_UserStats/repeats:3\",$"}, - {"\"name\": \"BM_UserStats/repeats:3\",$"}, - {"\"name\": \"BM_UserStats/repeats:3\",$"}, - {"\"name\": \"BM_UserStats/repeats:3_mean\",$"}, - {"\"name\": \"BM_UserStats/repeats:3_median\",$"}, - {"\"name\": \"BM_UserStats/repeats:3_stddev\",$"}, - {"\"name\": \"BM_UserStats/repeats:3_\",$"}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_UserStats/repeats:3\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3_mean\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3_median\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3_stddev\",%csv_report$"}, - {"^\"BM_UserStats/repeats:3_\",%csv_report$"}}); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/interpreter/llvm/src/utils/benchmark/test/skip_with_error_test.cc b/interpreter/llvm/src/utils/benchmark/test/skip_with_error_test.cc deleted file mode 100644 index 8d2c342a9af40..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/skip_with_error_test.cc +++ /dev/null @@ -1,192 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "benchmark/benchmark.h" - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual bool ReportContext(const Context& context) { - return ConsoleReporter::ReportContext(context); - }; - - virtual void ReportRuns(const std::vector& report) { - all_runs_.insert(all_runs_.end(), begin(report), end(report)); - ConsoleReporter::ReportRuns(report); - } - - TestReporter() {} - virtual ~TestReporter() {} - - mutable std::vector all_runs_; -}; - -struct TestCase { - std::string name; - bool error_occurred; - std::string error_message; - - typedef benchmark::BenchmarkReporter::Run Run; - - void CheckRun(Run const& run) const { - CHECK(name == run.benchmark_name) << "expected " << name << " got " - << run.benchmark_name; - CHECK(error_occurred == run.error_occurred); - CHECK(error_message == run.error_message); - if (error_occurred) { - // CHECK(run.iterations == 0); - } else { - CHECK(run.iterations != 0); - } - } -}; - -std::vector ExpectedResults; - -int AddCases(const char* base_name, std::initializer_list const& v) { - for (auto TC : v) { - TC.name = base_name + TC.name; - ExpectedResults.push_back(std::move(TC)); - } - return 0; -} - -#define CONCAT(x, y) CONCAT2(x, y) -#define CONCAT2(x, y) x##y -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases(__VA_ARGS__) - -} // end namespace - -void BM_error_before_running(benchmark::State& state) { - state.SkipWithError("error message"); - while (state.KeepRunning()) { - assert(false); - } -} -BENCHMARK(BM_error_before_running); -ADD_CASES("BM_error_before_running", {{"", true, "error message"}}); - - -void BM_error_before_running_batch(benchmark::State& state) { - state.SkipWithError("error message"); - while (state.KeepRunningBatch(17)) { - assert(false); - } -} -BENCHMARK(BM_error_before_running_batch); -ADD_CASES("BM_error_before_running_batch", {{"", true, "error message"}}); - -void BM_error_before_running_range_for(benchmark::State& state) { - state.SkipWithError("error message"); - for (auto _ : state) { - assert(false); - } -} -BENCHMARK(BM_error_before_running_range_for); -ADD_CASES("BM_error_before_running_range_for", {{"", true, "error message"}}); - -void BM_error_during_running(benchmark::State& state) { - int first_iter = true; - while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { - assert(first_iter); - first_iter = false; - state.SkipWithError("error message"); - } else { - state.PauseTiming(); - state.ResumeTiming(); - } - } -} -BENCHMARK(BM_error_during_running)->Arg(1)->Arg(2)->ThreadRange(1, 8); -ADD_CASES("BM_error_during_running", {{"/1/threads:1", true, "error message"}, - {"/1/threads:2", true, "error message"}, - {"/1/threads:4", true, "error message"}, - {"/1/threads:8", true, "error message"}, - {"/2/threads:1", false, ""}, - {"/2/threads:2", false, ""}, - {"/2/threads:4", false, ""}, - {"/2/threads:8", false, ""}}); - -void BM_error_during_running_ranged_for(benchmark::State& state) { - assert(state.max_iterations > 3 && "test requires at least a few iterations"); - int first_iter = true; - // NOTE: Users should not write the for loop explicitly. - for (auto It = state.begin(), End = state.end(); It != End; ++It) { - if (state.range(0) == 1) { - assert(first_iter); - first_iter = false; - state.SkipWithError("error message"); - // Test the unfortunate but documented behavior that the ranged-for loop - // doesn't automatically terminate when SkipWithError is set. - assert(++It != End); - break; // Required behavior - } - } -} -BENCHMARK(BM_error_during_running_ranged_for)->Arg(1)->Arg(2)->Iterations(5); -ADD_CASES("BM_error_during_running_ranged_for", - {{"/1/iterations:5", true, "error message"}, - {"/2/iterations:5", false, ""}}); - - - -void BM_error_after_running(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } - if (state.thread_index <= (state.threads / 2)) - state.SkipWithError("error message"); -} -BENCHMARK(BM_error_after_running)->ThreadRange(1, 8); -ADD_CASES("BM_error_after_running", {{"/threads:1", true, "error message"}, - {"/threads:2", true, "error message"}, - {"/threads:4", true, "error message"}, - {"/threads:8", true, "error message"}}); - -void BM_error_while_paused(benchmark::State& state) { - bool first_iter = true; - while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { - assert(first_iter); - first_iter = false; - state.PauseTiming(); - state.SkipWithError("error message"); - } else { - state.PauseTiming(); - state.ResumeTiming(); - } - } -} -BENCHMARK(BM_error_while_paused)->Arg(1)->Arg(2)->ThreadRange(1, 8); -ADD_CASES("BM_error_while_paused", {{"/1/threads:1", true, "error message"}, - {"/1/threads:2", true, "error message"}, - {"/1/threads:4", true, "error message"}, - {"/1/threads:8", true, "error message"}, - {"/2/threads:1", false, ""}, - {"/2/threads:2", false, ""}, - {"/2/threads:4", false, ""}, - {"/2/threads:8", false, ""}}); - -int main(int argc, char* argv[]) { - benchmark::Initialize(&argc, argv); - - TestReporter test_reporter; - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); - - return 0; -} diff --git a/interpreter/llvm/src/utils/benchmark/test/state_assembly_test.cc b/interpreter/llvm/src/utils/benchmark/test/state_assembly_test.cc deleted file mode 100644 index e2c5c8648d035..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/state_assembly_test.cc +++ /dev/null @@ -1,66 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -extern "C" { - extern int ExternInt; - benchmark::State& GetState(); - void Fn(); -} - -using benchmark::State; - -// CHECK-LABEL: test_for_auto_loop: -extern "C" int test_for_auto_loop() { - State& S = GetState(); - int x = 42; - // CHECK: [[CALL:call(q)*]] _ZN9benchmark5State16StartKeepRunningEv - // CHECK-NEXT: testq %rbx, %rbx - // CHECK-NEXT: je [[LOOP_END:.*]] - - for (auto _ : S) { - // CHECK: .L[[LOOP_HEAD:[a-zA-Z0-9_]+]]: - // CHECK-GNU-NEXT: subq $1, %rbx - // CHECK-CLANG-NEXT: {{(addq \$1,|incq)}} %rax - // CHECK-NEXT: jne .L[[LOOP_HEAD]] - benchmark::DoNotOptimize(x); - } - // CHECK: [[LOOP_END]]: - // CHECK: [[CALL]] _ZN9benchmark5State17FinishKeepRunningEv - - // CHECK: movl $101, %eax - // CHECK: ret - return 101; -} - -// CHECK-LABEL: test_while_loop: -extern "C" int test_while_loop() { - State& S = GetState(); - int x = 42; - - // CHECK: j{{(e|mp)}} .L[[LOOP_HEADER:[a-zA-Z0-9_]+]] - // CHECK-NEXT: .L[[LOOP_BODY:[a-zA-Z0-9_]+]]: - while (S.KeepRunning()) { - // CHECK-GNU-NEXT: subq $1, %[[IREG:[a-z]+]] - // CHECK-CLANG-NEXT: {{(addq \$-1,|decq)}} %[[IREG:[a-z]+]] - // CHECK: movq %[[IREG]], [[DEST:.*]] - benchmark::DoNotOptimize(x); - } - // CHECK-DAG: movq [[DEST]], %[[IREG]] - // CHECK-DAG: testq %[[IREG]], %[[IREG]] - // CHECK-DAG: jne .L[[LOOP_BODY]] - // CHECK-DAG: .L[[LOOP_HEADER]]: - - // CHECK: cmpb $0 - // CHECK-NEXT: jne .L[[LOOP_END:[a-zA-Z0-9_]+]] - // CHECK: [[CALL:call(q)*]] _ZN9benchmark5State16StartKeepRunningEv - - // CHECK: .L[[LOOP_END]]: - // CHECK: [[CALL]] _ZN9benchmark5State17FinishKeepRunningEv - - // CHECK: movl $101, %eax - // CHECK: ret - return 101; -} diff --git a/interpreter/llvm/src/utils/benchmark/test/statistics_gtest.cc b/interpreter/llvm/src/utils/benchmark/test/statistics_gtest.cc deleted file mode 100644 index b4d6abbb5780e..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/statistics_gtest.cc +++ /dev/null @@ -1,61 +0,0 @@ -//===---------------------------------------------------------------------===// -// statistics_test - Unit tests for src/statistics.cc -//===---------------------------------------------------------------------===// - -#include "../src/statistics.h" -#include "gtest/gtest.h" - -namespace { -TEST(StatisticsTest, Mean) { - std::vector Inputs; - { - Inputs = {42, 42, 42, 42}; - double Res = benchmark::StatisticsMean(Inputs); - EXPECT_DOUBLE_EQ(Res, 42.0); - } - { - Inputs = {1, 2, 3, 4}; - double Res = benchmark::StatisticsMean(Inputs); - EXPECT_DOUBLE_EQ(Res, 2.5); - } - { - Inputs = {1, 2, 5, 10, 10, 14}; - double Res = benchmark::StatisticsMean(Inputs); - EXPECT_DOUBLE_EQ(Res, 7.0); - } -} - -TEST(StatisticsTest, Median) { - std::vector Inputs; - { - Inputs = {42, 42, 42, 42}; - double Res = benchmark::StatisticsMedian(Inputs); - EXPECT_DOUBLE_EQ(Res, 42.0); - } - { - Inputs = {1, 2, 3, 4}; - double Res = benchmark::StatisticsMedian(Inputs); - EXPECT_DOUBLE_EQ(Res, 2.5); - } - { - Inputs = {1, 2, 5, 10, 10}; - double Res = benchmark::StatisticsMedian(Inputs); - EXPECT_DOUBLE_EQ(Res, 5.0); - } -} - -TEST(StatisticsTest, StdDev) { - std::vector Inputs; - { - Inputs = {101, 101, 101, 101}; - double Res = benchmark::StatisticsStdDev(Inputs); - EXPECT_DOUBLE_EQ(Res, 0.0); - } - { - Inputs = {1, 2, 3}; - double Res = benchmark::StatisticsStdDev(Inputs); - EXPECT_DOUBLE_EQ(Res, 1.0); - } -} - -} // end namespace diff --git a/interpreter/llvm/src/utils/benchmark/test/templated_fixture_test.cc b/interpreter/llvm/src/utils/benchmark/test/templated_fixture_test.cc deleted file mode 100644 index ec5b4c0cc0782..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/templated_fixture_test.cc +++ /dev/null @@ -1,28 +0,0 @@ - -#include "benchmark/benchmark.h" - -#include -#include - -template -class MyFixture : public ::benchmark::Fixture { -public: - MyFixture() : data(0) {} - - T data; -}; - -BENCHMARK_TEMPLATE_F(MyFixture, Foo, int)(benchmark::State &st) { - for (auto _ : st) { - data += 1; - } -} - -BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, Bar, double)(benchmark::State& st) { - for (auto _ : st) { - data += 1.0; - } -} -BENCHMARK_REGISTER_F(MyFixture, Bar); - -BENCHMARK_MAIN(); diff --git a/interpreter/llvm/src/utils/benchmark/test/user_counters_tabular_test.cc b/interpreter/llvm/src/utils/benchmark/test/user_counters_tabular_test.cc deleted file mode 100644 index 9b8a6132e6d6a..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/user_counters_tabular_test.cc +++ /dev/null @@ -1,250 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// @todo: this checks the full output at once; the rule for -// CounterSet1 was failing because it was not matching "^[-]+$". -// @todo: check that the counters are vertically aligned. -ADD_CASES(TC_ConsoleOut, { -// keeping these lines long improves readability, so: -// clang-format off - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Bat %s Baz %s Foo %s Frob %s Lob$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bat %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$"}, -// clang-format on -}); -ADD_CASES(TC_CSVOut, {{"%csv_header," - "\"Bar\",\"Bat\",\"Baz\",\"Foo\",\"Frob\",\"Lob\""}}); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -void BM_Counters_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", { 1, bm::Counter::kAvgThreads}}, - {"Bar", { 2, bm::Counter::kAvgThreads}}, - {"Baz", { 4, bm::Counter::kAvgThreads}}, - {"Bat", { 8, bm::Counter::kAvgThreads}}, - {"Frob", {16, bm::Counter::kAvgThreads}}, - {"Lob", {32, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_Counters_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Tabular/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabular(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 2); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 4); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 8); - CHECK_COUNTER_VALUE(e, int, "Frob", EQ, 16); - CHECK_COUNTER_VALUE(e, int, "Lob", EQ, 32); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Tabular/threads:%int", &CheckTabular); - -// ========================================================================= // -// -------------------- Tabular+Rate Counters Output ----------------------- // -// ========================================================================= // - -void BM_CounterRates_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", { 1, bm::Counter::kAvgThreadsRate}}, - {"Bar", { 2, bm::Counter::kAvgThreadsRate}}, - {"Baz", { 4, bm::Counter::kAvgThreadsRate}}, - {"Bat", { 8, bm::Counter::kAvgThreadsRate}}, - {"Frob", {16, bm::Counter::kAvgThreadsRate}}, - {"Lob", {32, bm::Counter::kAvgThreadsRate}}, - }); -} -BENCHMARK(BM_CounterRates_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_CounterRates_Tabular/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterRates_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabularRate(Results const& e) { - double t = e.DurationCPUTime(); - CHECK_FLOAT_COUNTER_VALUE(e, "Foo", EQ, 1./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bar", EQ, 2./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Baz", EQ, 4./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bat", EQ, 8./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Frob", EQ, 16./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Lob", EQ, 32./t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_CounterRates_Tabular/threads:%int", - &CheckTabularRate); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters -void BM_CounterSet0_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bar", {20, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet0_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_CounterSet0_Tabular/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet0_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet0(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 20); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet0_Tabular", &CheckSet0); - -// again. -void BM_CounterSet1_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {15, bm::Counter::kAvgThreads}}, - {"Bar", {25, bm::Counter::kAvgThreads}}, - {"Baz", {45, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet1_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_CounterSet1_Tabular/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet1_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet1(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 15); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 25); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 45); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet1_Tabular/threads:%int", &CheckSet1); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters, different set now. -void BM_CounterSet2_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bat", {30, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet2_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_CounterSet2_Tabular/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet2_Tabular/threads:%int\",%csv_report," - ",%float,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet2(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 30); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet2_Tabular", &CheckSet2); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/interpreter/llvm/src/utils/benchmark/test/user_counters_test.cc b/interpreter/llvm/src/utils/benchmark/test/user_counters_test.cc deleted file mode 100644 index 06aafb1fa1463..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/test/user_counters_test.cc +++ /dev/null @@ -1,217 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// ========================================================================= // -// ---------------------- Testing Prologue Output -------------------------- // -// ========================================================================= // - -ADD_CASES(TC_ConsoleOut, - {{"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations UserCounters...$", MR_Next}, - {"^[-]+$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"%csv_header,\"bar\",\"foo\""}}); - -// ========================================================================= // -// ------------------------- Simple Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_Simple(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = 2 * (double)state.iterations(); -} -BENCHMARK(BM_Counters_Simple); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Simple %console_report bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Simple\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Simple\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSimple(Results const& e) { - double its = e.GetAs< double >("iterations"); - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - // check that the value of bar is within 0.1% of the expected value - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2.*its, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Simple", &CheckSimple); - -// ========================================================================= // -// --------------------- Counters+Items+Bytes/s Output --------------------- // -// ========================================================================= // - -namespace { int num_calls1 = 0; } -void BM_Counters_WithBytesAndItemsPSec(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = ++num_calls1; - state.SetBytesProcessed(364); - state.SetItemsProcessed(150); -} -BENCHMARK(BM_Counters_WithBytesAndItemsPSec); -ADD_CASES(TC_ConsoleOut, - {{"^BM_Counters_WithBytesAndItemsPSec %console_report " - "bar=%hrfloat foo=%hrfloat +%hrfloatB/s +%hrfloat items/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_WithBytesAndItemsPSec\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bytes_per_second\": %float,$", MR_Next}, - {"\"items_per_second\": %float,$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_WithBytesAndItemsPSec\"," - "%csv_bytes_items_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckBytesAndItemsPSec(Results const& e) { - double t = e.DurationCPUTime(); // this (and not real time) is the time used - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, num_calls1); - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_RESULT_VALUE(e, "bytes_per_second", EQ, 364./t, 0.001); - CHECK_FLOAT_RESULT_VALUE(e, "items_per_second", EQ, 150./t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_WithBytesAndItemsPSec", - &CheckBytesAndItemsPSec); - -// ========================================================================= // -// ------------------------- Rate Counters Output -------------------------- // -// ========================================================================= // - -void BM_Counters_Rate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kIsRate}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kIsRate}; -} -BENCHMARK(BM_Counters_Rate); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Rate %console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Rate\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Rate\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckRate(Results const& e) { - double t = e.DurationCPUTime(); // this (and not real time) is the time used - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1./t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2./t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Rate", &CheckRate); - -// ========================================================================= // -// ------------------------- Thread Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_Threads(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = 2; -} -BENCHMARK(BM_Counters_Threads)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Threads/threads:%int %console_report bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Threads/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Threads/threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckThreads(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "foo", EQ, e.NumThreads()); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, 2 * e.NumThreads()); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Threads/threads:%int", &CheckThreads); - -// ========================================================================= // -// ---------------------- ThreadAvg Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_AvgThreads(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgThreads}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kAvgThreads}; -} -BENCHMARK(BM_Counters_AvgThreads)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreads/threads:%int %console_report bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_AvgThreads/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_AvgThreads/threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgThreads(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, 2); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_AvgThreads/threads:%int", - &CheckAvgThreads); - -// ========================================================================= // -// ---------------------- ThreadAvg Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_AvgThreadsRate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgThreadsRate}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kAvgThreadsRate}; -} -BENCHMARK(BM_Counters_AvgThreadsRate)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreadsRate/threads:%int %console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_AvgThreadsRate/threads:%int\",$"}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_AvgThreadsRate/threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgThreadsRate(Results const& e) { - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1./e.DurationCPUTime(), 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2./e.DurationCPUTime(), 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_AvgThreadsRate/threads:%int", - &CheckAvgThreadsRate); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/interpreter/llvm/src/utils/benchmark/tools/compare.py b/interpreter/llvm/src/utils/benchmark/tools/compare.py deleted file mode 100644 index f0a4455f5fb7c..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/compare.py +++ /dev/null @@ -1,316 +0,0 @@ -#!/usr/bin/env python - -""" -compare.py - versatile benchmark output compare tool -""" - -import argparse -from argparse import ArgumentParser -import sys -import gbench -from gbench import util, report -from gbench.util import * - - -def check_inputs(in1, in2, flags): - """ - Perform checking on the user provided inputs and diagnose any abnormalities - """ - in1_kind, in1_err = classify_input_file(in1) - in2_kind, in2_err = classify_input_file(in2) - output_file = find_benchmark_flag('--benchmark_out=', flags) - output_type = find_benchmark_flag('--benchmark_out_format=', flags) - if in1_kind == IT_Executable and in2_kind == IT_Executable and output_file: - print(("WARNING: '--benchmark_out=%s' will be passed to both " - "benchmarks causing it to be overwritten") % output_file) - if in1_kind == IT_JSON and in2_kind == IT_JSON and len(flags) > 0: - print("WARNING: passing optional flags has no effect since both " - "inputs are JSON") - if output_type is not None and output_type != 'json': - print(("ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" - " is not supported.") % output_type) - sys.exit(1) - - -def create_parser(): - parser = ArgumentParser( - description='versatile benchmark output compare tool') - subparsers = parser.add_subparsers( - help='This tool has multiple modes of operation:', - dest='mode') - - parser_a = subparsers.add_parser( - 'benchmarks', - help='The most simple use-case, compare all the output of these two benchmarks') - baseline = parser_a.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test_baseline', - metavar='test_baseline', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - contender = parser_a.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'test_contender', - metavar='test_contender', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - parser_a.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - parser_b = subparsers.add_parser( - 'filters', help='Compare filter one with the filter two of benchmark') - baseline = parser_b.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test', - metavar='test', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - baseline.add_argument( - 'filter_baseline', - metavar='filter_baseline', - type=str, - nargs=1, - help='The first filter, that will be used as baseline') - contender = parser_b.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'filter_contender', - metavar='filter_contender', - type=str, - nargs=1, - help='The second filter, that will be compared against the baseline') - parser_b.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - parser_c = subparsers.add_parser( - 'benchmarksfiltered', - help='Compare filter one of first benchmark with filter two of the second benchmark') - baseline = parser_c.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test_baseline', - metavar='test_baseline', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - baseline.add_argument( - 'filter_baseline', - metavar='filter_baseline', - type=str, - nargs=1, - help='The first filter, that will be used as baseline') - contender = parser_c.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'test_contender', - metavar='test_contender', - type=argparse.FileType('r'), - nargs=1, - help='The second benchmark executable or JSON output file, that will be compared against the baseline') - contender.add_argument( - 'filter_contender', - metavar='filter_contender', - type=str, - nargs=1, - help='The second filter, that will be compared against the baseline') - parser_c.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - return parser - - -def main(): - # Parse the command line flags - parser = create_parser() - args, unknown_args = parser.parse_known_args() - if args.mode is None: - parser.print_help() - exit(1) - assert not unknown_args - benchmark_options = args.benchmark_options - - if args.mode == 'benchmarks': - test_baseline = args.test_baseline[0].name - test_contender = args.test_contender[0].name - filter_baseline = '' - filter_contender = '' - - # NOTE: if test_baseline == test_contender, you are analyzing the stdev - - description = 'Comparing %s to %s' % (test_baseline, test_contender) - elif args.mode == 'filters': - test_baseline = args.test[0].name - test_contender = args.test[0].name - filter_baseline = args.filter_baseline[0] - filter_contender = args.filter_contender[0] - - # NOTE: if filter_baseline == filter_contender, you are analyzing the - # stdev - - description = 'Comparing %s to %s (from %s)' % ( - filter_baseline, filter_contender, args.test[0].name) - elif args.mode == 'benchmarksfiltered': - test_baseline = args.test_baseline[0].name - test_contender = args.test_contender[0].name - filter_baseline = args.filter_baseline[0] - filter_contender = args.filter_contender[0] - - # NOTE: if test_baseline == test_contender and - # filter_baseline == filter_contender, you are analyzing the stdev - - description = 'Comparing %s (from %s) to %s (from %s)' % ( - filter_baseline, test_baseline, filter_contender, test_contender) - else: - # should never happen - print("Unrecognized mode of operation: '%s'" % args.mode) - parser.print_help() - exit(1) - - check_inputs(test_baseline, test_contender, benchmark_options) - - options_baseline = [] - options_contender = [] - - if filter_baseline and filter_contender: - options_baseline = ['--benchmark_filter=%s' % filter_baseline] - options_contender = ['--benchmark_filter=%s' % filter_contender] - - # Run the benchmarks and report the results - json1 = json1_orig = gbench.util.run_or_load_benchmark( - test_baseline, benchmark_options + options_baseline) - json2 = json2_orig = gbench.util.run_or_load_benchmark( - test_contender, benchmark_options + options_contender) - - # Now, filter the benchmarks so that the difference report can work - if filter_baseline and filter_contender: - replacement = '[%s vs. %s]' % (filter_baseline, filter_contender) - json1 = gbench.report.filter_benchmark( - json1_orig, filter_baseline, replacement) - json2 = gbench.report.filter_benchmark( - json2_orig, filter_contender, replacement) - - # Diff and output - output_lines = gbench.report.generate_difference_report(json1, json2) - print(description) - for ln in output_lines: - print(ln) - - -import unittest - - -class TestParser(unittest.TestCase): - def setUp(self): - self.parser = create_parser() - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'gbench', - 'Inputs') - self.testInput0 = os.path.join(testInputs, 'test1_run1.json') - self.testInput1 = os.path.join(testInputs, 'test1_run2.json') - - def test_benchmarks_basic(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1]) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_with_remainder(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1, 'd']) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.benchmark_options, ['d']) - - def test_benchmarks_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1, '--', 'e']) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.benchmark_options, ['e']) - - def test_filters_basic(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd']) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertFalse(parsed.benchmark_options) - - def test_filters_with_remainder(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd', 'e']) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertEqual(parsed.benchmark_options, ['e']) - - def test_filters_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd', '--', 'f']) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertEqual(parsed.benchmark_options, ['f']) - - def test_benchmarksfiltered_basic(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e']) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertFalse(parsed.benchmark_options) - - def test_benchmarksfiltered_with_remainder(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', 'f']) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertEqual(parsed.benchmark_options[0], 'f') - - def test_benchmarksfiltered_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', '--', 'g']) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertEqual(parsed.benchmark_options[0], 'g') - - -if __name__ == '__main__': - # unittest.main() - main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run1.json b/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run1.json deleted file mode 100644 index d7ec6a9c8f61a..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run1.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_SameTimes", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_2xFaster", - "iterations": 1000, - "real_time": 50, - "cpu_time": 50, - "time_unit": "ns" - }, - { - "name": "BM_2xSlower", - "iterations": 1000, - "real_time": 50, - "cpu_time": 50, - "time_unit": "ns" - }, - { - "name": "BM_1PercentFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_1PercentSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_100xSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_100xFaster", - "iterations": 1000, - "real_time": 10000, - "cpu_time": 10000, - "time_unit": "ns" - }, - { - "name": "BM_10PercentCPUToTime", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_ThirdFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_BadTimeUnit", - "iterations": 1000, - "real_time": 0.4, - "cpu_time": 0.5, - "time_unit": "s" - }, - { - "name": "BM_DifferentTimeUnit", - "iterations": 1, - "real_time": 1, - "cpu_time": 1, - "time_unit": "s" - } - ] -} diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run2.json b/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run2.json deleted file mode 100644 index 59a5ffaca4d4d..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test1_run2.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_SameTimes", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_2xFaster", - "iterations": 1000, - "real_time": 25, - "cpu_time": 25, - "time_unit": "ns" - }, - { - "name": "BM_2xSlower", - "iterations": 20833333, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_1PercentFaster", - "iterations": 1000, - "real_time": 98.9999999, - "cpu_time": 98.9999999, - "time_unit": "ns" - }, - { - "name": "BM_1PercentSlower", - "iterations": 1000, - "real_time": 100.9999999, - "cpu_time": 100.9999999, - "time_unit": "ns" - }, - { - "name": "BM_10PercentFaster", - "iterations": 1000, - "real_time": 90, - "cpu_time": 90, - "time_unit": "ns" - }, - { - "name": "BM_10PercentSlower", - "iterations": 1000, - "real_time": 110, - "cpu_time": 110, - "time_unit": "ns" - }, - { - "name": "BM_100xSlower", - "iterations": 1000, - "real_time": 1.0000e+04, - "cpu_time": 1.0000e+04, - "time_unit": "ns" - }, - { - "name": "BM_100xFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentCPUToTime", - "iterations": 1000, - "real_time": 110, - "cpu_time": 90, - "time_unit": "ns" - }, - { - "name": "BM_ThirdFaster", - "iterations": 1000, - "real_time": 66.665, - "cpu_time": 66.664, - "time_unit": "ns" - }, - { - "name": "BM_BadTimeUnit", - "iterations": 1000, - "real_time": 0.04, - "cpu_time": 0.6, - "time_unit": "s" - }, - { - "name": "BM_DifferentTimeUnit", - "iterations": 1, - "real_time": 1, - "cpu_time": 1, - "time_unit": "ns" - } - ] -} diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test2_run.json b/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test2_run.json deleted file mode 100644 index 15bc698030493..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/Inputs/test2_run.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_Hi", - "iterations": 1234, - "real_time": 42, - "cpu_time": 24, - "time_unit": "ms" - }, - { - "name": "BM_Zero", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_Zero/4", - "iterations": 4000, - "real_time": 40, - "cpu_time": 40, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_Zero", - "iterations": 2000, - "real_time": 20, - "cpu_time": 20, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_Zero/3", - "iterations": 3000, - "real_time": 30, - "cpu_time": 30, - "time_unit": "ns" - }, - { - "name": "BM_One", - "iterations": 5000, - "real_time": 5, - "cpu_time": 5, - "time_unit": "ns" - }, - { - "name": "BM_One/4", - "iterations": 2000, - "real_time": 20, - "cpu_time": 20, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_One", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_One/3", - "iterations": 1500, - "real_time": 15, - "cpu_time": 15, - "time_unit": "ns" - }, - { - "name": "BM_Bye", - "iterations": 5321, - "real_time": 11, - "cpu_time": 63, - "time_unit": "ns" - } - ] -} diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/__init__.py b/interpreter/llvm/src/utils/benchmark/tools/gbench/__init__.py deleted file mode 100644 index fce1a1acfbb33..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Google Benchmark tooling""" - -__author__ = 'Eric Fiselier' -__email__ = 'eric@efcs.ca' -__versioninfo__ = (0, 5, 0) -__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev' - -__all__ = [] diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/report.py b/interpreter/llvm/src/utils/benchmark/tools/gbench/report.py deleted file mode 100644 index 0c090981a833a..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/report.py +++ /dev/null @@ -1,208 +0,0 @@ -"""report.py - Utilities for reporting statistics about benchmark results -""" -import os -import re -import copy - -class BenchmarkColor(object): - def __init__(self, name, code): - self.name = name - self.code = code - - def __repr__(self): - return '%s%r' % (self.__class__.__name__, - (self.name, self.code)) - - def __format__(self, format): - return self.code - -# Benchmark Colors Enumeration -BC_NONE = BenchmarkColor('NONE', '') -BC_MAGENTA = BenchmarkColor('MAGENTA', '\033[95m') -BC_CYAN = BenchmarkColor('CYAN', '\033[96m') -BC_OKBLUE = BenchmarkColor('OKBLUE', '\033[94m') -BC_HEADER = BenchmarkColor('HEADER', '\033[92m') -BC_WARNING = BenchmarkColor('WARNING', '\033[93m') -BC_WHITE = BenchmarkColor('WHITE', '\033[97m') -BC_FAIL = BenchmarkColor('FAIL', '\033[91m') -BC_ENDC = BenchmarkColor('ENDC', '\033[0m') -BC_BOLD = BenchmarkColor('BOLD', '\033[1m') -BC_UNDERLINE = BenchmarkColor('UNDERLINE', '\033[4m') - -def color_format(use_color, fmt_str, *args, **kwargs): - """ - Return the result of 'fmt_str.format(*args, **kwargs)' after transforming - 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' - is False then all color codes in 'args' and 'kwargs' are replaced with - the empty string. - """ - assert use_color is True or use_color is False - if not use_color: - args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for arg in args] - kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for key, arg in kwargs.items()} - return fmt_str.format(*args, **kwargs) - - -def find_longest_name(benchmark_list): - """ - Return the length of the longest benchmark name in a given list of - benchmark JSON objects - """ - longest_name = 1 - for bc in benchmark_list: - if len(bc['name']) > longest_name: - longest_name = len(bc['name']) - return longest_name - - -def calculate_change(old_val, new_val): - """ - Return a float representing the decimal change between old_val and new_val. - """ - if old_val == 0 and new_val == 0: - return 0.0 - if old_val == 0: - return float(new_val - old_val) / (float(old_val + new_val) / 2) - return float(new_val - old_val) / abs(old_val) - - -def filter_benchmark(json_orig, family, replacement=""): - """ - Apply a filter to the json, and only leave the 'family' of benchmarks. - """ - regex = re.compile(family) - filtered = {} - filtered['benchmarks'] = [] - for be in json_orig['benchmarks']: - if not regex.search(be['name']): - continue - filteredbench = copy.deepcopy(be) # Do NOT modify the old name! - filteredbench['name'] = regex.sub(replacement, filteredbench['name']) - filtered['benchmarks'].append(filteredbench) - return filtered - - -def generate_difference_report(json1, json2, use_color=True): - """ - Calculate and report the difference between each test of two benchmarks - runs specified as 'json1' and 'json2'. - """ - first_col_width = find_longest_name(json1['benchmarks']) - def find_test(name): - for b in json2['benchmarks']: - if b['name'] == name: - return b - return None - first_col_width = max(first_col_width, len('Benchmark')) - first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format( - 'Benchmark', 12 + first_col_width) - output_strs = [first_line, '-' * len(first_line)] - - gen = (bn for bn in json1['benchmarks'] if 'real_time' in bn and 'cpu_time' in bn) - for bn in gen: - other_bench = find_test(bn['name']) - if not other_bench: - continue - - if bn['time_unit'] != other_bench['time_unit']: - continue - - def get_color(res): - if res > 0.05: - return BC_FAIL - elif res > -0.07: - return BC_WHITE - else: - return BC_CYAN - fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}" - tres = calculate_change(bn['real_time'], other_bench['real_time']) - cpures = calculate_change(bn['cpu_time'], other_bench['cpu_time']) - output_strs += [color_format(use_color, fmt_str, - BC_HEADER, bn['name'], first_col_width, - get_color(tres), tres, get_color(cpures), cpures, - bn['real_time'], other_bench['real_time'], - bn['cpu_time'], other_bench['cpu_time'], - endc=BC_ENDC)] - return output_strs - -############################################################################### -# Unit tests - -import unittest - -class TestReportDifference(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Inputs') - testOutput1 = os.path.join(testInputs, 'test1_run1.json') - testOutput2 = os.path.join(testInputs, 'test1_run2.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_basic(self): - expect_lines = [ - ['BM_SameTimes', '+0.0000', '+0.0000', '10', '10', '10', '10'], - ['BM_2xFaster', '-0.5000', '-0.5000', '50', '25', '50', '25'], - ['BM_2xSlower', '+1.0000', '+1.0000', '50', '100', '50', '100'], - ['BM_1PercentFaster', '-0.0100', '-0.0100', '100', '99', '100', '99'], - ['BM_1PercentSlower', '+0.0100', '+0.0100', '100', '101', '100', '101'], - ['BM_10PercentFaster', '-0.1000', '-0.1000', '100', '90', '100', '90'], - ['BM_10PercentSlower', '+0.1000', '+0.1000', '100', '110', '100', '110'], - ['BM_100xSlower', '+99.0000', '+99.0000', '100', '10000', '100', '10000'], - ['BM_100xFaster', '-0.9900', '-0.9900', '10000', '100', '10000', '100'], - ['BM_10PercentCPUToTime', '+0.1000', '-0.1000', '100', '110', '100', '90'], - ['BM_ThirdFaster', '-0.3333', '-0.3334', '100', '67', '100', '67'], - ['BM_BadTimeUnit', '-0.9000', '+0.2000', '0', '0', '0', '1'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report(json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(parts, expect_lines[i]) - - -class TestReportDifferenceBetweenFamilies(unittest.TestCase): - def load_result(self): - import json - testInputs = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Inputs') - testOutput = os.path.join(testInputs, 'test2_run.json') - with open(testOutput, 'r') as f: - json = json.load(f) - return json - - def test_basic(self): - expect_lines = [ - ['.', '-0.5000', '-0.5000', '10', '5', '10', '5'], - ['./4', '-0.5000', '-0.5000', '40', '20', '40', '20'], - ['Prefix/.', '-0.5000', '-0.5000', '20', '10', '20', '10'], - ['Prefix/./3', '-0.5000', '-0.5000', '30', '15', '30', '15'], - ] - json = self.load_result() - json1 = filter_benchmark(json, "BM_Z.ro", ".") - json2 = filter_benchmark(json, "BM_O.e", ".") - output_lines_with_header = generate_difference_report(json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(parts, expect_lines[i]) - - -if __name__ == '__main__': - unittest.main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/interpreter/llvm/src/utils/benchmark/tools/gbench/util.py b/interpreter/llvm/src/utils/benchmark/tools/gbench/util.py deleted file mode 100644 index 07c2377275498..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/gbench/util.py +++ /dev/null @@ -1,159 +0,0 @@ -"""util.py - General utilities for running, loading, and processing benchmarks -""" -import json -import os -import tempfile -import subprocess -import sys - -# Input file type enumeration -IT_Invalid = 0 -IT_JSON = 1 -IT_Executable = 2 - -_num_magic_bytes = 2 if sys.platform.startswith('win') else 4 -def is_executable_file(filename): - """ - Return 'True' if 'filename' names a valid file which is likely - an executable. A file is considered an executable if it starts with the - magic bytes for a EXE, Mach O, or ELF file. - """ - if not os.path.isfile(filename): - return False - with open(filename, mode='rb') as f: - magic_bytes = f.read(_num_magic_bytes) - if sys.platform == 'darwin': - return magic_bytes in [ - b'\xfe\xed\xfa\xce', # MH_MAGIC - b'\xce\xfa\xed\xfe', # MH_CIGAM - b'\xfe\xed\xfa\xcf', # MH_MAGIC_64 - b'\xcf\xfa\xed\xfe', # MH_CIGAM_64 - b'\xca\xfe\xba\xbe', # FAT_MAGIC - b'\xbe\xba\xfe\xca' # FAT_CIGAM - ] - elif sys.platform.startswith('win'): - return magic_bytes == b'MZ' - else: - return magic_bytes == b'\x7FELF' - - -def is_json_file(filename): - """ - Returns 'True' if 'filename' names a valid JSON output file. - 'False' otherwise. - """ - try: - with open(filename, 'r') as f: - json.load(f) - return True - except: - pass - return False - - -def classify_input_file(filename): - """ - Return a tuple (type, msg) where 'type' specifies the classified type - of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable - string represeting the error. - """ - ftype = IT_Invalid - err_msg = None - if not os.path.exists(filename): - err_msg = "'%s' does not exist" % filename - elif not os.path.isfile(filename): - err_msg = "'%s' does not name a file" % filename - elif is_executable_file(filename): - ftype = IT_Executable - elif is_json_file(filename): - ftype = IT_JSON - else: - err_msg = "'%s' does not name a valid benchmark executable or JSON file" % filename - return ftype, err_msg - - -def check_input_file(filename): - """ - Classify the file named by 'filename' and return the classification. - If the file is classified as 'IT_Invalid' print an error message and exit - the program. - """ - ftype, msg = classify_input_file(filename) - if ftype == IT_Invalid: - print("Invalid input file: %s" % msg) - sys.exit(1) - return ftype - -def find_benchmark_flag(prefix, benchmark_flags): - """ - Search the specified list of flags for a flag matching `` and - if it is found return the arg it specifies. If specified more than once the - last value is returned. If the flag is not found None is returned. - """ - assert prefix.startswith('--') and prefix.endswith('=') - result = None - for f in benchmark_flags: - if f.startswith(prefix): - result = f[len(prefix):] - return result - -def remove_benchmark_flags(prefix, benchmark_flags): - """ - Return a new list containing the specified benchmark_flags except those - with the specified prefix. - """ - assert prefix.startswith('--') and prefix.endswith('=') - return [f for f in benchmark_flags if not f.startswith(prefix)] - -def load_benchmark_results(fname): - """ - Read benchmark output from a file and return the JSON object. - REQUIRES: 'fname' names a file containing JSON benchmark output. - """ - with open(fname, 'r') as f: - return json.load(f) - - -def run_benchmark(exe_name, benchmark_flags): - """ - Run a benchmark specified by 'exe_name' with the specified - 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve - real time console output. - RETURNS: A JSON object representing the benchmark output - """ - output_name = find_benchmark_flag('--benchmark_out=', - benchmark_flags) - is_temp_output = False - if output_name is None: - is_temp_output = True - thandle, output_name = tempfile.mkstemp() - os.close(thandle) - benchmark_flags = list(benchmark_flags) + \ - ['--benchmark_out=%s' % output_name] - - cmd = [exe_name] + benchmark_flags - print("RUNNING: %s" % ' '.join(cmd)) - exitCode = subprocess.call(cmd) - if exitCode != 0: - print('TEST FAILED...') - sys.exit(exitCode) - json_res = load_benchmark_results(output_name) - if is_temp_output: - os.unlink(output_name) - return json_res - - -def run_or_load_benchmark(filename, benchmark_flags): - """ - Get the results for a specified benchmark. If 'filename' specifies - an executable benchmark then the results are generated by running the - benchmark. Otherwise 'filename' must name a valid JSON output file, - which is loaded and the result returned. - """ - ftype = check_input_file(filename) - if ftype == IT_JSON: - return load_benchmark_results(filename) - elif ftype == IT_Executable: - return run_benchmark(filename, benchmark_flags) - else: - assert False # This branch is unreachable \ No newline at end of file diff --git a/interpreter/llvm/src/utils/benchmark/tools/strip_asm.py b/interpreter/llvm/src/utils/benchmark/tools/strip_asm.py deleted file mode 100644 index 9030550b43bec..0000000000000 --- a/interpreter/llvm/src/utils/benchmark/tools/strip_asm.py +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env python - -""" -strip_asm.py - Cleanup ASM output for the specified file -""" - -from argparse import ArgumentParser -import sys -import os -import re - -def find_used_labels(asm): - found = set() - label_re = re.compile("\s*j[a-z]+\s+\.L([a-zA-Z0-9][a-zA-Z0-9_]*)") - for l in asm.splitlines(): - m = label_re.match(l) - if m: - found.add('.L%s' % m.group(1)) - return found - - -def normalize_labels(asm): - decls = set() - label_decl = re.compile("^[.]{0,1}L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") - for l in asm.splitlines(): - m = label_decl.match(l) - if m: - decls.add(m.group(0)) - if len(decls) == 0: - return asm - needs_dot = next(iter(decls))[0] != '.' - if not needs_dot: - return asm - for ld in decls: - asm = re.sub("(^|\s+)" + ld + "(?=:|\s)", '\\1.' + ld, asm) - return asm - - -def transform_labels(asm): - asm = normalize_labels(asm) - used_decls = find_used_labels(asm) - new_asm = '' - label_decl = re.compile("^\.L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") - for l in asm.splitlines(): - m = label_decl.match(l) - if not m or m.group(0) in used_decls: - new_asm += l - new_asm += '\n' - return new_asm - - -def is_identifier(tk): - if len(tk) == 0: - return False - first = tk[0] - if not first.isalpha() and first != '_': - return False - for i in range(1, len(tk)): - c = tk[i] - if not c.isalnum() and c != '_': - return False - return True - -def process_identifiers(l): - """ - process_identifiers - process all identifiers and modify them to have - consistent names across all platforms; specifically across ELF and MachO. - For example, MachO inserts an additional understore at the beginning of - names. This function removes that. - """ - parts = re.split(r'([a-zA-Z0-9_]+)', l) - new_line = '' - for tk in parts: - if is_identifier(tk): - if tk.startswith('__Z'): - tk = tk[1:] - elif tk.startswith('_') and len(tk) > 1 and \ - tk[1].isalpha() and tk[1] != 'Z': - tk = tk[1:] - new_line += tk - return new_line - - -def process_asm(asm): - """ - Strip the ASM of unwanted directives and lines - """ - new_contents = '' - asm = transform_labels(asm) - - # TODO: Add more things we want to remove - discard_regexes = [ - re.compile("\s+\..*$"), # directive - re.compile("\s*#(NO_APP|APP)$"), #inline ASM - re.compile("\s*#.*$"), # comment line - re.compile("\s*\.globa?l\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)"), #global directive - re.compile("\s*\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)"), - ] - keep_regexes = [ - - ] - fn_label_def = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]*:") - for l in asm.splitlines(): - # Remove Mach-O attribute - l = l.replace('@GOTPCREL', '') - add_line = True - for reg in discard_regexes: - if reg.match(l) is not None: - add_line = False - break - for reg in keep_regexes: - if reg.match(l) is not None: - add_line = True - break - if add_line: - if fn_label_def.match(l) and len(new_contents) != 0: - new_contents += '\n' - l = process_identifiers(l) - new_contents += l - new_contents += '\n' - return new_contents - -def main(): - parser = ArgumentParser( - description='generate a stripped assembly file') - parser.add_argument( - 'input', metavar='input', type=str, nargs=1, - help='An input assembly file') - parser.add_argument( - 'out', metavar='output', type=str, nargs=1, - help='The output file') - args, unknown_args = parser.parse_known_args() - input = args.input[0] - output = args.out[0] - if not os.path.isfile(input): - print(("ERROR: input file '%s' does not exist") % input) - sys.exit(1) - contents = None - with open(input, 'r') as f: - contents = f.read() - new_contents = process_asm(contents) - with open(output, 'w') as f: - f.write(new_contents) - - -if __name__ == '__main__': - main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/interpreter/llvm/src/utils/lit/lit/builtin_commands/__init__.py b/interpreter/llvm/src/utils/lit/lit/builtin_commands/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/interpreter/llvm/src/utils/vscode/README b/interpreter/llvm/src/utils/vscode/README deleted file mode 100644 index b8c860d87d6ef..0000000000000 --- a/interpreter/llvm/src/utils/vscode/README +++ /dev/null @@ -1,2 +0,0 @@ -"llvm" directory contains a VS Code Extension for doing syntax highlighting of -TableGen files and LLVM IR files. diff --git a/interpreter/llvm/src/utils/vscode/llvm/.gitignore b/interpreter/llvm/src/utils/vscode/llvm/.gitignore deleted file mode 100644 index 2bee7f99f4753..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules -*~ -syntaxes/ll.tmLanguage.json -out/ \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/.vscodeignore b/interpreter/llvm/src/utils/vscode/llvm/.vscodeignore deleted file mode 100644 index d63f792794e25..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/.vscodeignore +++ /dev/null @@ -1,7 +0,0 @@ -.vscode/** -.vscode-test/** -.gitignore -vsc-extension-quickstart.md -syntaxes/ll.tmLanguage.yaml -**/*.ts -**/tsconfig.json \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/CHANGELOG.md b/interpreter/llvm/src/utils/vscode/llvm/CHANGELOG.md deleted file mode 100644 index d9a4ecd2ec688..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -# Change Log - -All notable changes to the "llvm" extension will be documented in this file. - -Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. - -## [Unreleased] - -- Initial release \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/README.md b/interpreter/llvm/src/utils/vscode/llvm/README.md deleted file mode 100644 index 57196947ee0d5..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# VS Code Extension For LLVM Dev - -## Features - - LLVM IR files (.ll) syntax highlighting. - (manually translated from `llvm/utils/vim/syntax/llvm.vim`) - - TableGen files (.td) syntax highlighting. - (translated from `llvm/utils/textmate`) - - PatternMatchers for LIT test output. - (`$llvm-lit`, `$llvm-filecheck`) - - Tasks to run LIT on current selected file. - (`Terminal` -> `Run Task` -> `llvm-lit`) - -## Installation - -```sh -sudo apt-get install nodejs-dev node-gyp npm -sudo npm install -g typescript npx vsce -``` - -### Install From Source -```sh -cd -cp -r llvm/utils/vscode/llvm . -cd llvm -npm install -npm run vscode:prepublish -``` -`` is OS dependent. - -Please refer to https://code.visualstudio.com/docs/editor/extension-gallery#_where-are-extensions-installed - -### Install From Package (.vsix) - -First package the extension according to -https://code.visualstudio.com/api/working-with-extensions/publishing-extension#usage. - -Then install the package according to -https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix. - -## Setup - -Set `cmake.buildDirectory` to your build directory. - -https://code.visualstudio.com/docs/getstarted/settings - -https://vector-of-bool.github.io/docs/vscode-cmake-tools/settings.html#cmake-builddirectory diff --git a/interpreter/llvm/src/utils/vscode/llvm/language-configuration-tablegen.json b/interpreter/llvm/src/utils/vscode/llvm/language-configuration-tablegen.json deleted file mode 100644 index aa2571000769a..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/language-configuration-tablegen.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "comments": { - // symbol used for single line comment. Remove this entry if your language does not support line comments - "lineComment": "//", - // symbols used for start and end a block comment. Remove this entry if your language does not support block comments - "blockComment": [ "/*", "*/" ] - }, - // symbols used as brackets - "brackets": [ - ["{", "}"], - ["[", "]"], - ["(", ")"] - ], - // symbols that are auto closed when typing - "autoClosingPairs": [ - ["{", "}"], - ["[", "]"], - ["(", ")"], - ["\"", "\""], - ["'", "'"] - ], - // symbols that that can be used to surround a selection - "surroundingPairs": [ - ["{", "}"], - ["[", "]"], - ["(", ")"], - ["\"", "\""], - ["'", "'"] - ] -} \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/language-configuration.json b/interpreter/llvm/src/utils/vscode/llvm/language-configuration.json deleted file mode 100644 index a894d4aaa26e3..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/language-configuration.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "comments": { - // symbol used for single line comment. Remove this entry if your language does not support line comments - "lineComment": ";" - }, - // symbols used as brackets - "brackets": [ - ["{", "}"], - ["[", "]"], - ["(", ")"] - ], - // symbols that are auto closed when typing - "autoClosingPairs": [ - ["{", "}"], - ["[", "]"], - ["(", ")"], - ["\"", "\""] - ], - // symbols that can be used to surround a selection - "surroundingPairs": [ - ["{", "}"], - ["[", "]"], - ["(", ")"], - ["\"", "\""] - ] -} diff --git a/interpreter/llvm/src/utils/vscode/llvm/package-lock.json b/interpreter/llvm/src/utils/vscode/llvm/package-lock.json deleted file mode 100644 index 6ecb22c2dea84..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/package-lock.json +++ /dev/null @@ -1,323 +0,0 @@ -{ - "name": "llvm", - "version": "0.0.1", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@babel/code-frame": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", - "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", - "dev": true, - "requires": { - "@babel/highlight": "^7.8.3" - } - }, - "@babel/highlight": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", - "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", - "dev": true, - "requires": { - "chalk": "^2.0.0", - "esutils": "^2.0.2", - "js-tokens": "^4.0.0" - } - }, - "@types/node": { - "version": "8.10.59", - "resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.59.tgz", - "integrity": "sha512-8RkBivJrDCyPpBXhVZcjh7cQxVBSmRk9QM7hOketZzp6Tg79c0N8kkpAIito9bnJ3HCVCHVYz+KHTEbfQNfeVQ==", - "dev": true - }, - "@types/vscode": { - "version": "1.42.0", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.42.0.tgz", - "integrity": "sha512-ds6TceMsh77Fs0Mq0Vap6Y72JbGWB8Bay4DrnJlf5d9ui2RSe1wis13oQm+XhguOeH1HUfLGzaDAoupTUtgabw==", - "dev": true - }, - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true - }, - "diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - }, - "esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true - }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "js-yaml": { - "version": "3.13.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", - "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - }, - "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, - "requires": { - "wrappy": "1" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true - }, - "path-parse": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", - "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", - "dev": true - }, - "resolve": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz", - "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==", - "dev": true, - "requires": { - "path-parse": "^1.0.6" - } - }, - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "tslib": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", - "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==", - "dev": true - }, - "tslint": { - "version": "5.20.1", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.20.1.tgz", - "integrity": "sha512-EcMxhzCFt8k+/UP5r8waCf/lzmeSyVlqxqMEDQE7rWYiQky8KpIBz1JAoYXfROHrPZ1XXd43q8yQnULOLiBRQg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "builtin-modules": "^1.1.1", - "chalk": "^2.3.0", - "commander": "^2.12.1", - "diff": "^4.0.1", - "glob": "^7.1.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", - "resolve": "^1.3.2", - "semver": "^5.3.0", - "tslib": "^1.8.0", - "tsutils": "^2.29.0" - } - }, - "tsutils": { - "version": "2.29.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", - "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", - "dev": true, - "requires": { - "tslib": "^1.8.1" - } - }, - "typescript": { - "version": "3.8.3", - "resolved": "https://artifactory.sie.sony.com/artifactory/api/npm/ce-sie-private-npm-prod-virtual/typescript/-/typescript-3.8.3.tgz", - "integrity": "sha1-QJ64VE6gM1cRIFhp7EWKsQnuEGE=", - "dev": true - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true - } - } -} diff --git a/interpreter/llvm/src/utils/vscode/llvm/package.json b/interpreter/llvm/src/utils/vscode/llvm/package.json deleted file mode 100644 index fbee74954cbb3..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/package.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "name": "llvm", - "displayName": "llvm", - "description": "VS Code Externsion for LLVM development", - "publisher": "llvm-vs-code-extensions", - "version": "0.0.1", - "repository": "somewhere", - "engines": { - "vscode": "^1.42.0" - }, - "categories": [ - "Programming Languages" - ], - "activationEvents": [ - "onCommand:workbench.action.tasks.runTask" - ], - "main": "./out/extension", - "contributes": { - "languages": [ - { - "id": "tablegen", - "aliases": [ - "TableGen", - "tablegen" - ], - "extensions": [ - ".td" - ], - "configuration": "./language-configuration-tablegen.json" - }, - { - "id": "llvm", - "aliases": [ - "LLVM IR", - "LLVM", - "llvm" - ], - "extensions": [ - ".ll" - ], - "configuration": "./language-configuration.json" - } - ], - "grammars": [ - { - "language": "tablegen", - "scopeName": "source.tablegen", - "path": "./syntaxes/TableGen.tmLanguage" - }, - { - "language": "llvm", - "scopeName": "source.llvm", - "path": "./syntaxes/ll.tmLanguage.json" - } - ], - "taskDefinitions": [ - { - "type": "llvm-lit", - "required": [ - "task" - ], - "properties": { - "task": { - "type": "string", - "description": "The Rake task to customize" - } - } - } - ], - "problemMatchers": [ - { - "name": "llvm-lit", - "fileLocation": [ - "absolute" - ], - "label": "LLVM LIT", - "source": "llvm lit", - "severity": "error", - "pattern": [ - { - "regexp": "^(.+):(\\d+)\\((\\d+)\\):\\s+(.+)$", - "kind": "location", - "file": 1, - "line": 2, - "code": 3, - "message": 4 - } - ] - }, - { - "name": "llvm-filecheck", - "fileLocation": [ - "absolute" - ], - "label": "LLVM FileCheck", - "source": "llvm filecheck", - "pattern": [ - { - "regexp": "^(.+):(\\d+):\\d+:\\s+(error|warning|note|remark):\\s+(.+)$", - "kind": "location", - "file": 1, - "line": 2, - "severity": 3, - "message": 4 - } - ] - } - ] - }, - "devDependencies": { - "@types/node": "^8.10.59", - "@types/vscode": "^1.39.0", - "js-yaml": "^3.13.1", - "tslint": "^5.16.0", - "typescript": "^3.8.3" - }, - "extensionDependencies": ["ms-vscode.cmake-tools"], - "scripts": { - "vscode:prepublish": "npx js-yaml syntaxes/ll.tmLanguage.yaml > syntaxes/ll.tmLanguage.json && tsc -b", - "watch": "tsc -b -w" - } -} \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/src/extension.ts b/interpreter/llvm/src/utils/vscode/llvm/src/extension.ts deleted file mode 100644 index ffb8d9dc04291..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/src/extension.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as vscode from 'vscode'; -import { LITTaskProvider } from './litTaskProvider'; - -let litTaskProvider: vscode.Disposable | undefined; -let customTaskProvider: vscode.Disposable | undefined; - -export function activate(_context: vscode.ExtensionContext): void { - litTaskProvider = vscode.tasks.registerTaskProvider(LITTaskProvider.LITType, new LITTaskProvider()); -} - -export function deactivate(): void { - if (litTaskProvider) { - litTaskProvider.dispose(); - } -} \ No newline at end of file diff --git a/interpreter/llvm/src/utils/vscode/llvm/src/litTaskProvider.ts b/interpreter/llvm/src/utils/vscode/llvm/src/litTaskProvider.ts deleted file mode 100644 index 45d5c2befec05..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/src/litTaskProvider.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as vscode from 'vscode'; -import * as fs from 'fs'; - -interface LITTaskDefinition extends vscode.TaskDefinition { - /** - * The task name - */ - task: string; -} - -export class LITTaskProvider implements vscode.TaskProvider { - static LITType: string = 'llvm-lit'; - private cmd: string; - private args: string[] = []; - private litPromise: Thenable | undefined = undefined; - - constructor() { - const isWindows = process.platform === 'win32'; - if (isWindows) { - this.cmd = "py" - this.args = ["-3", "${config:cmake.buildDirectory}\\bin\\llvm-lit.py", "-vv"] - } else { - this.cmd = "python3" - this.args = ["${config:cmake.buildDirectory}/bin/llvm-lit", "-vv"] - } - } - - public provideTasks(): Thenable | undefined { - if (!this.litPromise) { - this.litPromise = this.getLITTasks(); - } - return this.litPromise; - } - - public resolveTask(_task: vscode.Task): vscode.Task | undefined { - const task = _task.definition.task; - if (task) { - let args: string[] = this.args; - const definition: LITTaskDefinition = _task.definition; - if (definition.task === 'llvm-lit file') { - args.push("${file}") - } else if (definition.task === 'llvm-lit directory') { - args.push("${fileDirname}") - } - - return new vscode.Task( - definition, - definition.task, - 'llvm', - new vscode.ShellExecution(this.cmd, args), - ["$llvm-lit", "$llvm-filecheck"] - ); - } - return undefined; - } - - private async getLITTasks(): Promise { - let result: vscode.Task[] = []; - - let bld_dir: string | undefined = vscode.workspace.getConfiguration().get("cmake.buildDirectory"); - if (bld_dir == undefined || !fs.existsSync(bld_dir)) { - return result; - } - - let taskName = 'llvm-lit file'; - result.push(new vscode.Task({ type: 'llvm-lit', task: taskName }, - taskName, 'llvm', - new vscode.ShellExecution(this.cmd, this.args.concat(["${file}"])), - ["$llvm-lit", "$llvm-filecheck"])); - - taskName = 'llvm-lit directory'; - result.push(new vscode.Task({ type: 'llvm-lit', task: taskName }, - taskName, 'llvm', - new vscode.ShellExecution(this.cmd, this.args.concat(["${fileDirname}"])), - ["$llvm-lit", "$llvm-filecheck"]) - ); - return result; - } -} diff --git a/interpreter/llvm/src/utils/vscode/llvm/syntaxes/TableGen.tmLanguage b/interpreter/llvm/src/utils/vscode/llvm/syntaxes/TableGen.tmLanguage deleted file mode 100644 index 0b08ec262a1a9..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/syntaxes/TableGen.tmLanguage +++ /dev/null @@ -1,132 +0,0 @@ - - - - - fileTypes - td - foldingStartMarker - /\*\*|\{\s*$ - foldingStopMarker - \*\*/|^\s*\} - name - TableGen - patterns - - - include - #comments - - - match - \b(def|let|in|code|dag|string|list|bits|bit|field|include|defm|foreach|class|multiclass|int|defvar|defset|if|then|else)\b - name - keyword.control.tablegen - - - begin - " - end - " - name - string.quoted.double.untitled - patterns - - - match - \\. - name - constant.character.escape.tablegen - - - - - repository - - comments - - patterns - - - captures - - 1 - - name - meta.toc-list.banner.block.tablegen - - - match - ^/\* =(\s*.*?)\s*= \*/$\n? - name - comment.block.tablegen - - - begin - /\* - captures - - 0 - - name - punctuation.definition.comment.tablegen - - - end - \*/ - name - comment.block.tablegen - - - match - \*/.*\n - name - invalid.illegal.stray-comment-end.tablegen - - - captures - - 1 - - name - meta.toc-list.banner.line.tablegen - - - match - ^// =(\s*.*?)\s*=\s*$\n? - name - comment.line.banner.tablegen - - - begin - // - beginCaptures - - 0 - - name - punctuation.definition.comment.tablegen - - - end - $\n? - name - comment.line.double-slash.tablegen - patterns - - - match - (?>\\\s*\n) - name - punctuation.separator.continuation.tablegen - - - - - - - scopeName - source.tablegen - uuid - 3A090BFC-E74B-4993-8DAE-7CCF6D238A32 - - diff --git a/interpreter/llvm/src/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml b/interpreter/llvm/src/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml deleted file mode 100644 index 127f5d9867a09..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml +++ /dev/null @@ -1,365 +0,0 @@ -# https://macromates.com/manual/en/language_grammars -# https://macromates.com/manual/en/regular_expressions -# https://www.sublimetext.com/docs/3/scope_naming.html - -# Coloring -# https://code.visualstudio.com/docs/getstarted/themes -# https://code.visualstudio.com/api/extension-guides/color-theme#syntax-colors -# https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide -# https://code.visualstudio.com/docs/cpp/colorization-cpp - -$schema: https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json -name: LLVM IR -scopeName: source.llvm -patterns: - - match: "\\bvoid\\b|\ - \\bhalf\\b|\ - \\bbfloat\\b|\ - \\bfloat\\b|\ - \\bdouble\\b|\ - \\bx86_fp80\\b|\ - \\bfp128\\b|\ - \\bppc_fp128\\b|\ - \\blabel\\b|\ - \\bmetadata\\b|\ - \\bx86_mmx\\b|\ - \\bx86_amx\\b|\ - \\btype\\b|\ - \\blabel\\b|\ - \\bopaque\\b|\ - \\btoken\\b|\ - \\bi\\d+\\**" - name: storage.type.llvm - - match: "!([a-zA-Z]+)\\s*\\(" - captures: - 1: - name: storage.type.llvm - - match: "\\badd\\b|\ - \\baddrspacecast\\b|\ - \\balloca\\b|\ - \\band\\b|\ - \\barcp\\b|\ - \\bashr\\b|\ - \\batomicrmw\\b|\ - \\bbitcast\\b|\ - \\bbr\\b|\ - \\bcatchpad\\b|\ - \\bcatchswitch\\b|\ - \\bcatchret\\b|\ - \\bcall\\b|\ - \\bcallbr\\b|\ - \\bcleanuppad\\b|\ - \\bcleanupret\\b|\ - \\bcmpxchg\\b|\ - \\beq\\b|\ - \\bexact\\b|\ - \\bextractelement\\b|\ - \\bextractvalue\\b|\ - \\bfadd\\b|\ - \\bfast\\b|\ - \\bfcmp\\b|\ - \\bfdiv\\b|\ - \\bfence\\b|\ - \\bfmul\\b|\ - \\bfpext\\b|\ - \\bfptosi\\b|\ - \\bfptoui\\b|\ - \\bfptrunc\\b|\ - \\bfree\\b|\ - \\bfrem\\b|\ - \\bfreeze\\b|\ - \\bfsub\\b|\ - \\bfneg\\b|\ - \\bgetelementptr\\b|\ - \\bicmp\\b|\ - \\binbounds\\b|\ - \\bindirectbr\\b|\ - \\binsertelement\\b|\ - \\binsertvalue\\b|\ - \\binttoptr\\b|\ - \\binvoke\\b|\ - \\blandingpad\\b|\ - \\bload\\b|\ - \\blshr\\b|\ - \\bmalloc\\b|\ - \\bmax\\b|\ - \\bmin\\b|\ - \\bmul\\b|\ - \\bnand\\b|\ - \\bne\\b|\ - \\bninf\\b|\ - \\bnnan\\b|\ - \\bnsw\\b|\ - \\bnsz\\b|\ - \\bnuw\\b|\ - \\boeq\\b|\ - \\boge\\b|\ - \\bogt\\b|\ - \\bole\\b|\ - \\bolt\\b|\ - \\bone\\b|\ - \\bor\\b|\ - \\bord\\b|\ - \\bphi\\b|\ - \\bptrtoint\\b|\ - \\bresume\\b|\ - \\bret\\b|\ - \\bsdiv\\b|\ - \\bselect\\b|\ - \\bsext\\b|\ - \\bsge\\b|\ - \\bsgt\\b|\ - \\bshl\\b|\ - \\bshufflevector\\b|\ - \\bsitofp\\b|\ - \\bsle\\b|\ - \\bslt\\b|\ - \\bsrem\\b|\ - \\bstore\\b|\ - \\bsub\\b|\ - \\bswitch\\b|\ - \\btrunc\\b|\ - \\budiv\\b|\ - \\bueq\\b|\ - \\buge\\b|\ - \\bugt\\b|\ - \\buitofp\\b|\ - \\bule\\b|\ - \\bult\\b|\ - \\bumax\\b|\ - \\bumin\\b|\ - \\bune\\b|\ - \\buno\\b|\ - \\bunreachable\\b|\ - \\bunwind\\b|\ - \\burem\\b|\ - \\bva_arg\\b|\ - \\bxchg\\b|\ - \\bxor\\b|\ - \\bzext\\b" - name: keyword.instruction.llvm - - match: "\\bacq_rel\\b|\ - \\bacquire\\b|\ - \\baddrspace\\b|\ - \\balias\\b|\ - \\balign\\b|\ - \\balignstack\\b|\ - \\ballocsize\\b|\ - \\balwaysinline\\b|\ - \\bappending\\b|\ - \\bargmemonly\\b|\ - \\barm_aapcs_vfpcc\\b|\ - \\barm_aapcscc\\b|\ - \\barm_apcscc\\b|\ - \\basm\\b|\ - \\batomic\\b|\ - \\bavailable_externally\\b|\ - \\bblockaddress\\b|\ - \\bbuiltin\\b|\ - \\bbyref\\b|\ - \\bbyval\\b|\ - \\bc\\b|\ - \\bcaller\\b|\ - \\bcatch\\b|\ - \\bcc\\b|\ - \\bccc\\b|\ - \\bcleanup\\b|\ - \\bcold\\b|\ - \\bcoldcc\\b|\ - \\bcomdat\\b|\ - \\bcommon\\b|\ - \\bconstant\\b|\ - \\bconvergent\\b|\ - \\bdatalayout\\b|\ - \\bdeclare\\b|\ - \\bdefault\\b|\ - \\bdefine\\b|\ - \\bdeplibs\\b|\ - \\bdereferenceable\\b|\ - \\bdereferenceable_or_null\\b|\ - \\bdistinct\\b|\ - \\bdllexport\\b|\ - \\bdllimport\\b|\ - \\bdso_local\\b|\ - \\bdso_preemptable\\b|\ - \\bexcept\\b|\ - \\bextern_weak\\b|\ - \\bexternal\\b|\ - \\bexternally_initialized\\b|\ - \\bfastcc\\b|\ - \\bfilter\\b|\ - \\bfrom\\b|\ - \\bgc\\b|\ - \\bglobal\\b|\ - \\bhhvm_ccc\\b|\ - \\bhhvmcc\\b|\ - \\bhidden\\b|\ - \\bhot\\b|\ - \\bimmarg\\b|\ - \\binaccessiblemem_or_argmemonly\\b|\ - \\binaccessiblememonly\\b|\ - \\binalloc\\b|\ - \\binitialexec\\b|\ - \\binlinehint\\b|\ - \\binreg\\b|\ - \\bintel_ocl_bicc\\b|\ - \\binteldialect\\b|\ - \\binternal\\b|\ - \\bjumptable\\b|\ - \\blinkonce\\b|\ - \\blinkonce_odr\\b|\ - \\blocal_unnamed_addr\\b|\ - \\blocaldynamic\\b|\ - \\blocalexec\\b|\ - \\bminsize\\b|\ - \\bmodule\\b|\ - \\bmonotonic\\b|\ - \\bmsp430_intrcc\\b|\ - \\bmustprogress\\b|\ - \\bmusttail\\b|\ - \\bnaked\\b|\ - \\bnest\\b|\ - \\bnoalias\\b|\ - \\bnobuiltin\\b|\ - \\bnocallback\\b|\ - \\bnocapture\\b|\ - \\bnocf_check\\b|\ - \\bnoduplicate\\b|\ - \\bnofree\\b|\ - \\bnoimplicitfloat\\b|\ - \\bnoinline\\b|\ - \\bnomerge\\b|\ - \\bnonlazybind\\b|\ - \\bnonnull\\b|\ - \\bnoprofile\\b|\ - \\bnorecurse\\b|\ - \\bnoredzone\\b|\ - \\bnoreturn\\b|\ - \\bnosync\\b|\ - \\bnoundef\\b|\ - \\bnounwind\\b|\ - \\bnosanitize_coverage\\b|\ - \\bnull_pointer_is_valid\\b|\ - \\boptforfuzzing\\b|\ - \\boptnone\\b|\ - \\boptsize\\b|\ - \\bpersonality\\b|\ - \\bpreallocated\\b|\ - \\bprivate\\b|\ - \\bprotected\\b|\ - \\bptx_device\\b|\ - \\bptx_kernel\\b|\ - \\breadnone\\b|\ - \\breadonly\\b|\ - \\brelease\\b|\ - \\breturned\\b|\ - \\breturns_twice\\b|\ - \\bsafestack\\b|\ - \\bsanitize_address\\b|\ - \\bsanitize_hwaddress\\b|\ - \\bsanitize_memory\\b|\ - \\bsanitize_memtag\\b|\ - \\bsanitize_thread\\b|\ - \\bsection\\b|\ - \\bseq_cst\\b|\ - \\bshadowcallstack\\b|\ - \\bsideeffect\\b|\ - \\bsignext\\b|\ - \\bsource_filename\\b|\ - \\bspeculatable\\b|\ - \\bspeculative_load_hardening\\b|\ - \\bspir_func\\b|\ - \\bspir_kernel\\b|\ - \\bsret\\b|\ - \\bssp\\b|\ - \\bsspreq\\b|\ - \\bsspstrong\\b|\ - \\bstrictfp\\b|\ - \\bswiftcc\\b|\ - \\bswifterror\\b|\ - \\bswiftself\\b|\ - \\bsyncscope\\b|\ - \\btail\\b|\ - \\btailcc\\b|\ - \\btarget\\b|\ - \\bthread_local\\b|\ - \\bto\\b|\ - \\btriple\\b|\ - \\bunnamed_addr\\b|\ - \\bunordered\\b|\ - \\buselistorder\\b|\ - \\buselistorder_bb\\b|\ - \\buwtable\\b|\ - \\bvolatile\\b|\ - \\bweak\\b|\ - \\bweak_odr\\b|\ - \\bwillreturn\\b|\ - \\bwin64cc\\b|\ - \\bwithin\\b|\ - \\bwriteonly\\b|\ - \\bx86_64_sysvcc\\b|\ - \\bx86_fastcallcc\\b|\ - \\bx86_stdcallcc\\b|\ - \\bx86_thiscallcc\\b|\ - \\bzeroext\\b" - name: storage.modifier.llvm - - match: "@[-a-zA-Z$._][-a-zA-Z$._0-9]*" - name: entity.name.function.llvm - - match: "[%@!]\\d+\\b" - name: variable.llvm - - match: "%[-a-zA-Z$._][-a-zA-Z$._0-9]*" - name: variable.llvm - - match: "(![-a-zA-Z$._][-a-zA-Z$._0-9]*)\\s*$" - captures: - 1: - name: variable.llvm - - match: "(![-a-zA-Z$._][-a-zA-Z$._0-9]*)\\s*[=!]" - captures: - 1: - name: variable.llvm - - begin: "\"" - end: "\"" - patterns: - - name: "constant.character.escape.untitled" - match: "\\." - name: string.quoted.double.llvm - - match: "[-a-zA-Z$._][-a-zA-Z$._0-9]*:" - name: entity.name.label.llvm - - match: "-?\\b\\d+\\.\\d*(e[+-]\\d+)?\\b" - name: constant.numeric.float - - match: "\\b0x\\x+\\b" - name: constant.numeric.float - - match: "-?\\b\\d+\\b" - name: constant.numeric.integer - - match: "\\btrue\\b|\ - \\bfalse\\b|\ - \\bnull\\b|\ - \\bzeroinitializer\\b|\ - \\bundef\\b|\ - \\bpoison\\b|\ - \\bnull\\b|\ - \\bnone\\b" - name: constant.language - - match: "\\bDW_TAG_[a-z_]+\\b|\ - \\bDW_ATE_[a-zA-Z_]+\\b|\ - \\bDW_OP_[a-zA-Z0-9_]+\\b|\ - \\bDW_LANG_[a-zA-Z0-9_]+\\b|\ - \\bDW_VIRTUALITY_[a-z_]+\\b|\ - \\bDIFlag[A-Za-z]+\\b" - name: constant.other - - match: ";\\s*PR\\d*\\s*$" - name: string.regexp - - match: ";\\s*REQUIRES:.*$" - name: string.regexp - - match: ";\\s*RUN:.*$" - name: string.regexp - - match: ";\\s*ALLOW_RETRIES:.*$" - name: string.regexp - - match: ";\\s*CHECK:.*$" - name: string.regexp - - match: ";\\s*CHECK-(NEXT|NOT|DAG|SAME|LABEL):.*$" - name: string.regexp - - match: ";\\s*XFAIL:.*$" - name: string.regexp - - match: ;.*$ - name: comment.line.llvm diff --git a/interpreter/llvm/src/utils/vscode/llvm/tsconfig.json b/interpreter/llvm/src/utils/vscode/llvm/tsconfig.json deleted file mode 100644 index 6b4dc05c1492c..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "outDir": "out", - "lib": [ - "es6" - ], - "sourceMap": true, - "rootDir": "src", - "strict": true /* enable all strict type-checking options */ - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - }, - "exclude": [ - "node_modules" - ] -} diff --git a/interpreter/llvm/src/utils/vscode/llvm/vsc-extension-quickstart.md b/interpreter/llvm/src/utils/vscode/llvm/vsc-extension-quickstart.md deleted file mode 100644 index 2837046b058ac..0000000000000 --- a/interpreter/llvm/src/utils/vscode/llvm/vsc-extension-quickstart.md +++ /dev/null @@ -1,29 +0,0 @@ -# Welcome to your VS Code Extension - -## What's in the folder - -* This folder contains all of the files necessary for your extension. -* `package.json` - this is the manifest file in which you declare your language support and define the location of the grammar file that has been copied into your extension. -* `syntaxes/ll.tmLanguage.json` - this is the Text mate grammar file that is used for tokenization. -* `language-configuration.json` - this is the language configuration, defining the tokens that are used for comments and brackets. - -## Get up and running straight away - -* Make sure the language configuration settings in `language-configuration.json` are accurate. -* Press `F5` to open a new window with your extension loaded. -* Create a new file with a file name suffix matching your language. -* Verify that syntax highlighting works and that the language configuration settings are working. - -## Make changes - -* You can relaunch the extension from the debug toolbar after making changes to the files listed above. -* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes. - -## Add more language features - -* To add features such as intellisense, hovers and validators check out the VS Code extenders documentation at https://code.visualstudio.com/docs - -## Install your extension - -* To start using your extension with Visual Studio Code copy it into the `/.vscode/extensions` folder and restart Code. -* To share your extension with the world, read on https://code.visualstudio.com/docs about publishing an extension. diff --git a/io/dcache/inc/TDCacheFile.h b/io/dcache/inc/TDCacheFile.h index a0f6971a7f919..46eef19862016 100644 --- a/io/dcache/inc/TDCacheFile.h +++ b/io/dcache/inc/TDCacheFile.h @@ -31,27 +31,27 @@ class TDCacheFile : public TFile { TDCacheFile() : fStatCached(kFALSE) { } // Interface to basic system I/O routines - Int_t SysOpen(const char *pathname, Int_t flags, UInt_t mode); - Int_t SysClose(Int_t fd); - Int_t SysRead(Int_t fd, void *buf, Int_t len); - Int_t SysWrite(Int_t fd, const void *buf, Int_t len); - Long64_t SysSeek(Int_t fd, Long64_t offset, Int_t whence); - Int_t SysStat(Int_t fd, Long_t *id, Long64_t *size, Long_t *flags, Long_t *modtime); - Int_t SysSync(Int_t fd); + Int_t SysOpen(const char *pathname, Int_t flags, UInt_t mode) override; + Int_t SysClose(Int_t fd) override; + Int_t SysRead(Int_t fd, void *buf, Int_t len) override; + Int_t SysWrite(Int_t fd, const void *buf, Int_t len) override; + Long64_t SysSeek(Int_t fd, Long64_t offset, Int_t whence) override; + Int_t SysStat(Int_t fd, Long_t *id, Long64_t *size, Long_t *flags, Long_t *modtime) override; + Int_t SysSync(Int_t fd) override; public: TDCacheFile(const char *path, Option_t *option="", const char *ftitle="", Int_t compress = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); - ~TDCacheFile(); + ~TDCacheFile() override; - Bool_t ReadBuffer(char *buf, Int_t len); - Bool_t ReadBuffer(char *buf, Long64_t pos, Int_t len); - Bool_t WriteBuffer(const char *buf, Int_t len); + Bool_t ReadBuffer(char *buf, Int_t len) override; + Bool_t ReadBuffer(char *buf, Long64_t pos, Int_t len) override; + Bool_t WriteBuffer(const char *buf, Int_t len) override; - Bool_t ReadBuffers(char *buf, Long64_t *pos, Int_t *len, Int_t nbuf); + Bool_t ReadBuffers(char *buf, Long64_t *pos, Int_t *len, Int_t nbuf) override; - void ResetErrno() const; + void ResetErrno() const override; static Bool_t Stage(const char *path, UInt_t secs, const char *location = 0); @@ -72,7 +72,7 @@ class TDCacheFile : public TFile { static TString GetDcapPath(const char *path); - ClassDef(TDCacheFile,1) //A ROOT file that reads/writes via a dCache server + ClassDefOverride(TDCacheFile,1) //A ROOT file that reads/writes via a dCache server }; @@ -81,20 +81,20 @@ class TDCacheSystem : public TSystem { private: void *fDirp; ///< directory handler - void *GetDirPtr() const { return fDirp; } + void *GetDirPtr() const override { return fDirp; } public: TDCacheSystem(); - virtual ~TDCacheSystem() { } + ~TDCacheSystem() override { } - Int_t MakeDirectory(const char *name); - void *OpenDirectory(const char *name); - void FreeDirectory(void *dirp); - const char *GetDirEntry(void *dirp); - Int_t GetPathInfo(const char *path, FileStat_t &buf); - Bool_t AccessPathName(const char *path, EAccessMode mode); + Int_t MakeDirectory(const char *name) override; + void *OpenDirectory(const char *name) override; + void FreeDirectory(void *dirp) override; + const char *GetDirEntry(void *dirp) override; + Int_t GetPathInfo(const char *path, FileStat_t &buf) override; + Bool_t AccessPathName(const char *path, EAccessMode mode) override; - ClassDef(TDCacheSystem,0) // Directory handler for DCache + ClassDefOverride(TDCacheSystem,0) // Directory handler for DCache }; #endif diff --git a/io/gfal/inc/TGFALFile.h b/io/gfal/inc/TGFALFile.h index 6b0065622f65a..818763f358c78 100644 --- a/io/gfal/inc/TGFALFile.h +++ b/io/gfal/inc/TGFALFile.h @@ -25,24 +25,24 @@ class TGFALFile : public TFile { TGFALFile() : fStatCached(kFALSE) { } // Interface to basic system I/O routines - Int_t SysOpen(const char *pathname, Int_t flags, UInt_t mode); - Int_t SysClose(Int_t fd); - Int_t SysRead(Int_t fd, void *buf, Int_t len); - Int_t SysWrite(Int_t fd, const void *buf, Int_t len); - Long64_t SysSeek(Int_t fd, Long64_t offset, Int_t whence); - Int_t SysStat(Int_t fd, Long_t *id, Long64_t *size, Long_t *flags, Long_t *modtime); - Int_t SysSync(Int_t) { /* no fsync for GFAL */ return 0; } + Int_t SysOpen(const char *pathname, Int_t flags, UInt_t mode) override; + Int_t SysClose(Int_t fd) override; + Int_t SysRead(Int_t fd, void *buf, Int_t len) override; + Int_t SysWrite(Int_t fd, const void *buf, Int_t len) override; + Long64_t SysSeek(Int_t fd, Long64_t offset, Int_t whence) override; + Int_t SysStat(Int_t fd, Long_t *id, Long64_t *size, Long_t *flags, Long_t *modtime) override; + Int_t SysSync(Int_t) override { /* no fsync for GFAL */ return 0; } public: TGFALFile(const char *url, Option_t *option="", const char *ftitle="", Int_t compress = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); - ~TGFALFile(); + ~TGFALFile() override; - Bool_t ReadBuffer(char *buf, Int_t len); - Bool_t ReadBuffer(char *buf, Long64_t pos, Int_t len); - Bool_t WriteBuffer(const char *buf, Int_t len); + Bool_t ReadBuffer(char *buf, Int_t len) override; + Bool_t ReadBuffer(char *buf, Long64_t pos, Int_t len) override; + Bool_t WriteBuffer(const char *buf, Int_t len) override; - ClassDef(TGFALFile,1) //A ROOT file that reads/writes via a GFAL + ClassDefOverride(TGFALFile,1) //A ROOT file that reads/writes via a GFAL }; @@ -51,20 +51,20 @@ class TGFALSystem : public TSystem { private: void *fDirp; // directory handler - void *GetDirPtr() const { return fDirp; } + void *GetDirPtr() const override { return fDirp; } public: TGFALSystem(); - virtual ~TGFALSystem() { } + ~TGFALSystem() override { } - Int_t MakeDirectory(const char *name); - void *OpenDirectory(const char *name); - void FreeDirectory(void *dirp); - const char *GetDirEntry(void *dirp); - Int_t GetPathInfo(const char *path, FileStat_t &buf); - Bool_t AccessPathName(const char *path, EAccessMode mode); + Int_t MakeDirectory(const char *name) override; + void *OpenDirectory(const char *name) override; + void FreeDirectory(void *dirp) override; + const char *GetDirEntry(void *dirp) override; + Int_t GetPathInfo(const char *path, FileStat_t &buf) override; + Bool_t AccessPathName(const char *path, EAccessMode mode) override; - ClassDef(TGFALSystem,0) // Directory handler for GFAL + ClassDefOverride(TGFALSystem,0) // Directory handler for GFAL }; #endif diff --git a/io/io/inc/ROOT/RRawFileUnix.hxx b/io/io/inc/ROOT/RRawFileUnix.hxx index bf65e0e25ec97..b88e213f07c50 100644 --- a/io/io/inc/ROOT/RRawFileUnix.hxx +++ b/io/io/inc/ROOT/RRawFileUnix.hxx @@ -42,7 +42,7 @@ protected: public: RRawFileUnix(std::string_view url, RRawFile::ROptions options); - ~RRawFileUnix(); + ~RRawFileUnix() override; std::unique_ptr Clone() const final; int GetFeatures() const final; int GetFd() const { return fFileDes; } diff --git a/io/io/inc/ROOT/RRawFileWin.hxx b/io/io/inc/ROOT/RRawFileWin.hxx index 83d072fa2ac5c..c959047dc427b 100644 --- a/io/io/inc/ROOT/RRawFileWin.hxx +++ b/io/io/inc/ROOT/RRawFileWin.hxx @@ -41,7 +41,7 @@ protected: public: RRawFileWin(std::string_view url, RRawFile::ROptions options); - ~RRawFileWin(); + ~RRawFileWin() override; std::unique_ptr Clone() const final; int GetFeatures() const final { return kFeatureHasSize; } }; diff --git a/io/io/inc/ROOT/TBufferMerger.hxx b/io/io/inc/ROOT/TBufferMerger.hxx index de7b6d64b4a33..17815e7531c2e 100644 --- a/io/io/inc/ROOT/TBufferMerger.hxx +++ b/io/io/inc/ROOT/TBufferMerger.hxx @@ -197,7 +197,7 @@ private: public: /** Destructor */ - ~TBufferMergerFile(); + ~TBufferMergerFile() override; using TMemFile::Write; @@ -208,7 +208,7 @@ public: * This function must be called before the TBufferMergerFile gets destroyed, * or no data is appended to the TBufferMerger. */ - virtual Int_t Write(const char *name = nullptr, Int_t opt = 0, Int_t bufsize = 0) override; + Int_t Write(const char *name = nullptr, Int_t opt = 0, Int_t bufsize = 0) override; ClassDefOverride(TBufferMergerFile, 0); }; diff --git a/io/io/inc/TArchiveFile.h b/io/io/inc/TArchiveFile.h index c2e5d031fbb79..68df4d0a9e2d0 100644 --- a/io/io/inc/TArchiveFile.h +++ b/io/io/inc/TArchiveFile.h @@ -40,7 +40,7 @@ class TArchiveFile : public TObject { public: TArchiveFile() : fArchiveName(""), fMemberName(""), fMemberIndex(-1), fFile(nullptr), fMembers(nullptr), fCurMember(nullptr) { } TArchiveFile(const char *archive, const char *member, TFile *file); - virtual ~TArchiveFile(); + ~TArchiveFile() override; virtual Int_t OpenArchive() = 0; virtual Int_t SetCurrentMember() = 0; @@ -81,7 +81,7 @@ friend class TArchiveFile; TArchiveMember(const char *name); TArchiveMember(const TArchiveMember &member); TArchiveMember &operator=(const TArchiveMember &rhs); - virtual ~TArchiveMember() { } + ~TArchiveMember() override { } const char *GetName() const override { return fName; } const char *GetComment() const { return fComment; } diff --git a/io/io/inc/TBufferFile.h b/io/io/inc/TBufferFile.h index c739d84f94fbe..393318ce0e87c 100644 --- a/io/io/inc/TBufferFile.h +++ b/io/io/inc/TBufferFile.h @@ -71,7 +71,7 @@ class TBufferFile : public TBufferIO { TBufferFile(TBuffer::EMode mode); TBufferFile(TBuffer::EMode mode, Int_t bufsiz); TBufferFile(TBuffer::EMode mode, Int_t bufsiz, void *buf, Bool_t adopt = kTRUE, ReAllocCharFun_t reallocfunc = nullptr); - virtual ~TBufferFile(); + ~TBufferFile() override; Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const TClass *clss) override; Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const char *classname) override; diff --git a/io/io/inc/TBufferIO.h b/io/io/inc/TBufferIO.h index b3d5dd2544ae9..09265c90377b4 100644 --- a/io/io/inc/TBufferIO.h +++ b/io/io/inc/TBufferIO.h @@ -71,7 +71,7 @@ class TBufferIO : public TBuffer { kUser3 = BIT(23) // free for user }; - virtual ~TBufferIO(); + ~TBufferIO() override; Int_t GetVersionOwner() const override; diff --git a/io/io/inc/TBufferJSON.h b/io/io/inc/TBufferJSON.h index 72c571053ed0e..0e7c47f2495f8 100644 --- a/io/io/inc/TBufferJSON.h +++ b/io/io/inc/TBufferJSON.h @@ -49,7 +49,7 @@ class TBufferJSON final : public TBufferText { }; TBufferJSON(TBuffer::EMode mode = TBuffer::kWrite); - virtual ~TBufferJSON(); + ~TBufferJSON() override; void SetCompact(int level); void SetTypenameTag(const char *tag = "_typename"); diff --git a/io/io/inc/TBufferText.h b/io/io/inc/TBufferText.h index 31843d4ed6929..ff7721dac008d 100644 --- a/io/io/inc/TBufferText.h +++ b/io/io/inc/TBufferText.h @@ -24,7 +24,7 @@ class TBufferText : public TBufferIO { TBufferText(TBuffer::EMode mode, TObject *parent = nullptr); public: - virtual ~TBufferText(); + ~TBufferText() override; // virtual TBuffer methods, which are generic for all text-based streamers diff --git a/io/io/inc/TCollectionProxyFactory.h b/io/io/inc/TCollectionProxyFactory.h index ca005a532aaa3..22ebc16ba026b 100644 --- a/io/io/inc/TCollectionProxyFactory.h +++ b/io/io/inc/TCollectionProxyFactory.h @@ -165,7 +165,7 @@ class TCollectionClassStreamer : public TClassStreamer, public TCollectionStream /// Initializing constructor TCollectionClassStreamer() : TClassStreamer(nullptr) { } /// Standard destructor - virtual ~TCollectionClassStreamer() { } + ~TCollectionClassStreamer() override { } /// Streamer for I/O handling void operator()(TBuffer &buff, void *obj) override { Streamer(buff,obj,0,fOnFileClass); } @@ -212,7 +212,7 @@ class TCollectionMemberStreamer : public TMemberStreamer, public TCollectionStre TCollectionMemberStreamer(const TCollectionMemberStreamer& c) : TMemberStreamer(c), TCollectionStreamer(c) { } /// Standard destructor - virtual ~TCollectionMemberStreamer() { } + ~TCollectionMemberStreamer() override { } /// Streamer for I/O handling void operator()(TBuffer &buff,void *obj, Int_t siz = 0) override { Streamer(buff, obj, siz, nullptr); /* FIXME */ } diff --git a/io/io/inc/TContainerConverters.h b/io/io/inc/TContainerConverters.h index 1ccf903501502..d15b0b9c4ad91 100644 --- a/io/io/inc/TContainerConverters.h +++ b/io/io/inc/TContainerConverters.h @@ -24,7 +24,7 @@ class TConvertClonesArrayToProxy : public TMemberStreamer { TClass *fCollectionClass; public: TConvertClonesArrayToProxy(TVirtualCollectionProxy *proxy, Bool_t isPointer, Bool_t isPrealloc); - ~TConvertClonesArrayToProxy(); + ~TConvertClonesArrayToProxy() override; void operator()(TBuffer &b, void *pmember, Int_t size=0) override; }; diff --git a/io/io/inc/TDirectoryFile.h b/io/io/inc/TDirectoryFile.h index c573a06db37e3..16f2d2edaa4e4 100644 --- a/io/io/inc/TDirectoryFile.h +++ b/io/io/inc/TDirectoryFile.h @@ -59,7 +59,7 @@ class TDirectoryFile : public TDirectory { TDirectoryFile(); TDirectoryFile(const char *name, const char *title, Option_t *option="", TDirectory* motherDir = nullptr); - virtual ~TDirectoryFile(); + ~TDirectoryFile() override; void Append(TObject *obj, Bool_t replace = kFALSE) override; void Add(TObject *obj, Bool_t replace = kFALSE) override { Append(obj,replace); } @@ -69,7 +69,8 @@ class TDirectoryFile : public TDirectory { TObject *CloneObject(const TObject *obj, Bool_t autoadd = kTRUE) override; void Close(Option_t *option="") override; void Copy(TObject &) const override { MayNotUse("Copy(TObject &)"); } - Bool_t cd(const char *path = nullptr) override; + Bool_t cd() override; + Bool_t cd(const char *path) override; void Delete(const char *namecycle="") override; void FillBuffer(char *&buffer) override; TKey *FindKey(const char *keyname) const override; diff --git a/io/io/inc/TEmulatedCollectionProxy.h b/io/io/inc/TEmulatedCollectionProxy.h index 6caf8e9fda6f1..3f1a1cd75dff4 100644 --- a/io/io/inc/TEmulatedCollectionProxy.h +++ b/io/io/inc/TEmulatedCollectionProxy.h @@ -56,7 +56,7 @@ class TEmulatedCollectionProxy : public TGenCollectionProxy { TEmulatedCollectionProxy(const char* cl_name, Bool_t silent); // Standard destructor - virtual ~TEmulatedCollectionProxy(); + ~TEmulatedCollectionProxy() override; // Virtual constructor void* New() const override { return new Cont_t; } diff --git a/io/io/inc/TEmulatedMapProxy.h b/io/io/inc/TEmulatedMapProxy.h index a79b1585b9a7c..48e990d85e86d 100644 --- a/io/io/inc/TEmulatedMapProxy.h +++ b/io/io/inc/TEmulatedMapProxy.h @@ -35,7 +35,7 @@ class TEmulatedMapProxy : public TEmulatedCollectionProxy { TEmulatedMapProxy(const char* cl_name, Bool_t silent); // Standard destructor - virtual ~TEmulatedMapProxy(); + ~TEmulatedMapProxy() override; // Return the address of the value at index 'idx' void *At(UInt_t idx) override; diff --git a/io/io/inc/TFPBlock.h b/io/io/inc/TFPBlock.h index 4830de77b8c98..53d751e280732 100644 --- a/io/io/inc/TFPBlock.h +++ b/io/io/inc/TFPBlock.h @@ -36,7 +36,7 @@ class TFPBlock : public TObject{ public: TFPBlock(Long64_t*, Int_t*, Int_t); - virtual ~TFPBlock(); + ~TFPBlock() override; Long64_t GetPos(Int_t) const; Int_t GetLen(Int_t) const; diff --git a/io/io/inc/TFile.h b/io/io/inc/TFile.h index 1fcccd5941ec0..df36591ed9445 100644 --- a/io/io/inc/TFile.h +++ b/io/io/inc/TFile.h @@ -197,7 +197,7 @@ class TFile : public TDirectoryFile { TFile(); TFile(const char *fname, Option_t *option="", const char *ftitle="", Int_t compress = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); - virtual ~TFile(); + ~TFile() override; void Close(Option_t *option="") override; // *MENU* void Copy(TObject &) const override { MayNotUse("Copy(TObject &)"); } @@ -357,7 +357,6 @@ Class holding info about the file being opened class TFileOpenHandle : public TNamed { friend class TFile; -friend class TAlienFile; private: TString fOpt; ///< Options @@ -376,7 +375,7 @@ friend class TAlienFile; TFile *GetFile() const { return fFile; } public: - ~TFileOpenHandle() { } + ~TFileOpenHandle() override { } Bool_t Matches(const char *name); diff --git a/io/io/inc/TFileCacheRead.h b/io/io/inc/TFileCacheRead.h index 884b4c0863e23..15385ab756ae9 100644 --- a/io/io/inc/TFileCacheRead.h +++ b/io/io/inc/TFileCacheRead.h @@ -79,7 +79,7 @@ class TFileCacheRead : public TObject { public: TFileCacheRead(); TFileCacheRead(TFile *file, Int_t buffersize, TObject *tree = nullptr); - virtual ~TFileCacheRead(); + ~TFileCacheRead() override; virtual Int_t AddBranch(TBranch * /*b*/, Bool_t /*subbranches*/ = kFALSE) { return 0; } virtual Int_t AddBranch(const char * /*branch*/, Bool_t /*subbranches*/ = kFALSE) { return 0; } virtual void AddNoCacheBytesRead(Long64_t len) { fNoCacheBytesRead += len; } diff --git a/io/io/inc/TFileCacheWrite.h b/io/io/inc/TFileCacheWrite.h index c2914414faa04..10cdeba203f80 100644 --- a/io/io/inc/TFileCacheWrite.h +++ b/io/io/inc/TFileCacheWrite.h @@ -33,7 +33,7 @@ class TFileCacheWrite : public TObject { public: TFileCacheWrite(); TFileCacheWrite(TFile *file, Int_t buffersize); - virtual ~TFileCacheWrite(); + ~TFileCacheWrite() override; virtual Bool_t Flush(); virtual Int_t GetBytesInCache() const { return fNtot; } void Print(Option_t *option="") const override; diff --git a/io/io/inc/TFileMerger.h b/io/io/inc/TFileMerger.h index b4e623e92c00b..e4445b4d8bb9a 100644 --- a/io/io/inc/TFileMerger.h +++ b/io/io/inc/TFileMerger.h @@ -82,7 +82,7 @@ class TFileMerger : public TObject { }; TFileMerger(Bool_t isLocal = kTRUE, Bool_t histoOneGo = kTRUE); - virtual ~TFileMerger(); + ~TFileMerger() override; Int_t GetPrintLevel() const { return fPrintLevel; } void SetPrintLevel(Int_t level) { fPrintLevel = level; } diff --git a/io/io/inc/TFilePrefetch.h b/io/io/inc/TFilePrefetch.h index 872e29606bbaf..0fecbb3700d24 100644 --- a/io/io/inc/TFilePrefetch.h +++ b/io/io/inc/TFilePrefetch.h @@ -51,7 +51,7 @@ class TFilePrefetch : public TObject { public: TFilePrefetch(TFile*); - virtual ~TFilePrefetch(); + ~TFilePrefetch() override; void ReadAsync(TFPBlock*, Bool_t&); void ReadListOfBlocks(); diff --git a/io/io/inc/TFree.h b/io/io/inc/TFree.h index 2c30f506d0bc8..0acaad50aa1e5 100644 --- a/io/io/inc/TFree.h +++ b/io/io/inc/TFree.h @@ -33,7 +33,7 @@ class TFree : public TObject { public: TFree(); TFree(TList *lfree, Long64_t first, Long64_t last); - virtual ~TFree(); + ~TFree() override; TFree *AddFree(TList *lfree, Long64_t first, Long64_t last); virtual void FillBuffer(char *&buffer); TFree *GetBestFree(TList *lfree, Int_t nbytes); diff --git a/io/io/inc/TGenCollectionProxy.h b/io/io/inc/TGenCollectionProxy.h index fa644fec3bd15..008db88af6020 100644 --- a/io/io/inc/TGenCollectionProxy.h +++ b/io/io/inc/TGenCollectionProxy.h @@ -342,7 +342,7 @@ class TGenCollectionProxy public: // Virtual copy constructor. - virtual TVirtualCollectionProxy* Generate() const override; + TVirtualCollectionProxy* Generate() const override; // Copy constructor. TGenCollectionProxy(const TGenCollectionProxy& copy); @@ -357,7 +357,7 @@ class TGenCollectionProxy TGenCollectionProxy(const ROOT::Detail::TCollectionProxyInfo &info, TClass *cl); // Standard destructor. - virtual ~TGenCollectionProxy(); + ~TGenCollectionProxy() override; // Reset the info gathered from StreamerInfos and value's TClass. Bool_t Reset() override; @@ -482,7 +482,7 @@ struct AnyCollectionProxy : public TGenCollectionProxy { fFeed = T::feed; CheckFunctions(); } - virtual ~AnyCollectionProxy() { } + ~AnyCollectionProxy() override { } }; #endif diff --git a/io/io/inc/TGenCollectionStreamer.h b/io/io/inc/TGenCollectionStreamer.h index c3cf3dd4eac91..6b27ca8a62c8c 100644 --- a/io/io/inc/TGenCollectionStreamer.h +++ b/io/io/inc/TGenCollectionStreamer.h @@ -57,7 +57,7 @@ class TGenCollectionStreamer : public TGenCollectionProxy { TGenCollectionStreamer(const ROOT::TCollectionProxyInfo &info, TClass *cl); // Standard destructor - virtual ~TGenCollectionStreamer(); + ~TGenCollectionStreamer() override; // Streamer I/O overload void Streamer(TBuffer &refBuffer) override; @@ -94,7 +94,7 @@ struct AnyCollectionStreamer : public TGenCollectionStreamer { fFeed = T::feed; CheckFunctions(); } - virtual ~AnyCollectionStreamer() {} + ~AnyCollectionStreamer() override {} }; // Forward declaration in the event of later separation diff --git a/io/io/inc/TKey.h b/io/io/inc/TKey.h index b070887ac3d19..a94081326ada1 100644 --- a/io/io/inc/TKey.h +++ b/io/io/inc/TKey.h @@ -66,7 +66,7 @@ class TKey : public TNamed { TKey(const TObject *obj, const char *name, Int_t bufsize, TDirectory* motherDir); TKey(const void *obj, const TClass *cl, const char *name, Int_t bufsize, TDirectory* motherDir); TKey(Long64_t pointer, Int_t nbytes, TDirectory* motherDir = nullptr); - virtual ~TKey(); + ~TKey() override; void Browse(TBrowser *b) override; void Delete(Option_t *option="") override; diff --git a/io/io/inc/TKeyMapFile.h b/io/io/inc/TKeyMapFile.h index fae13a68e78b8..680d305808a0e 100644 --- a/io/io/inc/TKeyMapFile.h +++ b/io/io/inc/TKeyMapFile.h @@ -28,7 +28,7 @@ class TKeyMapFile : public TNamed { public: TKeyMapFile(); TKeyMapFile(const char *name, const char *classname, TMapFile *mapfile); - virtual ~TKeyMapFile() {} + ~TKeyMapFile() override {} void Browse(TBrowser *b) override; ClassDefOverride(TKeyMapFile,0); //Utility class for browsing TMapFile objects. diff --git a/io/io/inc/TLockFile.h b/io/io/inc/TLockFile.h index 8e56a3cf24d11..d00c82903f3d4 100644 --- a/io/io/inc/TLockFile.h +++ b/io/io/inc/TLockFile.h @@ -29,7 +29,7 @@ class TLockFile : public TObject { public: TLockFile(const char *path, Int_t timeLimit = 0); - virtual ~TLockFile(); + ~TLockFile() override; ClassDefOverride(TLockFile, 0) //Lock an object using a file }; diff --git a/io/io/inc/TMapFile.h b/io/io/inc/TMapFile.h index 4eda7a599db84..0acb3abd55abd 100644 --- a/io/io/inc/TMapFile.h +++ b/io/io/inc/TMapFile.h @@ -76,7 +76,7 @@ friend class TMapRec; enum { kDefaultMapSize = 0x80000 }; // default size of mapped heap is 500 KB // Should both be protected (waiting for cint) - virtual ~TMapFile(); + ~TMapFile() override; void *operator new(size_t sz) { return TObject::operator new(sz); } void *operator new[](size_t sz) { return TObject::operator new[](sz); } void *operator new(size_t sz, void *vp) { return TObject::operator new(sz, vp); } diff --git a/io/io/inc/TMemFile.h b/io/io/inc/TMemFile.h index 5fb07fc0d14f7..3b40651d6f167 100644 --- a/io/io/inc/TMemFile.h +++ b/io/io/inc/TMemFile.h @@ -95,7 +95,7 @@ class TMemFile : public TFile { TMemFile(const char *name, const ZeroCopyView_t &datarange); TMemFile(const char *name, std::unique_ptr buffer); TMemFile(const TMemFile &orig); - virtual ~TMemFile(); + ~TMemFile() override; virtual Long64_t CopyTo(void *to, Long64_t maxsize) const; virtual void CopyTo(TBuffer &tobuf) const; diff --git a/io/io/inc/TStreamerInfo.h b/io/io/inc/TStreamerInfo.h index 6b2c2ccfcf938..54c56ca4c040d 100644 --- a/io/io/inc/TStreamerInfo.h +++ b/io/io/inc/TStreamerInfo.h @@ -181,7 +181,7 @@ class TStreamerInfo : public TVirtualStreamerInfo { TStreamerInfo(); TStreamerInfo(TClass *cl); - virtual ~TStreamerInfo(); + ~TStreamerInfo() override; void Build(Bool_t isTransient = kFALSE) override; void BuildCheck(TFile *file = nullptr, Bool_t load = kTRUE) override; void BuildEmulated(TFile *file) override; diff --git a/io/io/inc/TStreamerInfoActions.h b/io/io/inc/TStreamerInfoActions.h index 2f28ebacfacf4..ea1cc24dfdcda 100644 --- a/io/io/inc/TStreamerInfoActions.h +++ b/io/io/inc/TStreamerInfoActions.h @@ -111,7 +111,7 @@ namespace TStreamerInfoActions { { // Usual constructor. } - ~TConfiguredAction() { + ~TConfiguredAction() override { // Usual destructor. // Idea: the configuration ownership might be moved to a single list so that // we can shared them between the optimized and non-optimized list of actions. @@ -141,11 +141,9 @@ namespace TStreamerInfoActions { // a sub-object struct TNestedIDs { TNestedIDs() = default; - TNestedIDs(TStreamerInfo *info, Int_t offset) : fInfo(info), fOffset(offset) {} - ~TNestedIDs() { - if (fOwnOnfileObject) - delete fOnfileObject; - } + TNestedIDs(TStreamerInfo *info, Int_t offset); + ~TNestedIDs(); + TStreamerInfo *fInfo = nullptr; ///< Not owned. TVirtualArray *fOnfileObject = nullptr; Bool_t fOwnOnfileObject = kFALSE; @@ -168,6 +166,13 @@ namespace TStreamerInfoActions { std::unique_ptr fNestedIDs; }; + inline TNestedIDs::TNestedIDs(TStreamerInfo *info, Int_t offset) : fInfo(info), fOffset(offset) {} + inline TNestedIDs::~TNestedIDs() { + if (fOwnOnfileObject) + delete fOnfileObject; + } + + typedef std::vector ActionContainer_t; class TActionSequence : public TObject { TActionSequence() {}; @@ -186,7 +191,7 @@ namespace TStreamerInfoActions { SetBit((UInt_t)EStatusBits::kVectorPtrLooper); fActions.reserve(maxdata); }; - ~TActionSequence() { + ~TActionSequence() override { delete fLoopConfig; } diff --git a/io/io/inc/TZIPFile.h b/io/io/inc/TZIPFile.h index ad6b6c9f6d218..99409e980893e 100644 --- a/io/io/inc/TZIPFile.h +++ b/io/io/inc/TZIPFile.h @@ -134,7 +134,7 @@ class TZIPFile : public TArchiveFile { public: TZIPFile(); TZIPFile(const char *archive, const char *member, TFile *file); - virtual ~TZIPFile() { } + ~TZIPFile() override { } Int_t OpenArchive() override; Int_t SetCurrentMember() override; @@ -173,7 +173,7 @@ friend class TZIPFile; TZIPMember(const char *name); TZIPMember(const TZIPMember &member); TZIPMember &operator=(const TZIPMember &rhs); - virtual ~TZIPMember(); + ~TZIPMember() override; void *GetLocal() const { return fLocal; } UInt_t GetLocalLen() const { return fLocalLen; } diff --git a/io/io/src/TBufferJSON.cxx b/io/io/src/TBufferJSON.cxx index b575be6a65de8..f8a5be65b9062 100644 --- a/io/io/src/TBufferJSON.cxx +++ b/io/io/src/TBufferJSON.cxx @@ -359,7 +359,7 @@ class TJSONStackObj : public TObject { TJSONStackObj() = default; - ~TJSONStackObj() + ~TJSONStackObj() override { if (fIsElemOwner) delete fElem; @@ -1196,7 +1196,7 @@ TJSONStackObj *TBufferJSON::JsonStartObjectWrite(const TClass *obj_class, TStrea AppendOutput(fTypeVersionTag.Data()); AppendOutput("\""); AppendOutput(fSemicolon.Data()); - AppendOutput(Form("%d", (int)(info ? info->GetClassVersion() : obj_class->GetClassVersion()))); + AppendOutput(TString::Format("%d", (int)(info ? info->GetClassVersion() : obj_class->GetClassVersion()))); } } else { stack->fMemberCnt = 0; // exclude typename @@ -1367,9 +1367,9 @@ void TBufferJSON::JsonWriteObject(const void *obj, const TClass *cl, Bool_t chec Long64_t refid = GetObjectTag(obj); if (refid > 0) { // old-style refs, coded into string like "$ref12" - // AppendOutput(Form("\"$ref:%u\"", iter->second)); + // AppendOutput(TString::Format("\"$ref:%u\"", iter->second)); // new-style refs, coded into extra object {"$ref":12}, auto-detected by JSROOT 4.8 and higher - AppendOutput(Form("{\"$ref\":%u}", (unsigned)(refid - 1))); + AppendOutput(TString::Format("{\"$ref\":%u}", (unsigned)(refid - 1))); goto post_process; } MapObject(obj, cl, fJsonrCnt + 1); // +1 used diff --git a/io/io/src/TDirectoryFile.cxx b/io/io/src/TDirectoryFile.cxx index 9f46588dd74e2..db0c29db53969 100644 --- a/io/io/src/TDirectoryFile.cxx +++ b/io/io/src/TDirectoryFile.cxx @@ -329,7 +329,19 @@ void TDirectoryFile::BuildDirectoryFile(TFile* motherFile, TDirectory* motherDir //////////////////////////////////////////////////////////////////////////////// /// Change current directory to "this" directory. -/// Using path one can +/// +/// Returns kTRUE in case of success. + +Bool_t TDirectoryFile::cd() +{ + Bool_t ok = TDirectory::cd(); + if (ok) + TFile::CurrentFile() = fFile; + return ok; +} + +//////////////////////////////////////////////////////////////////////////////// +/// Change current directory the directory described by the path if given one. /// change the current directory to "path". The absolute path syntax is: /// /// file.root:/dir1/dir2 @@ -341,7 +353,8 @@ void TDirectoryFile::BuildDirectoryFile(TFile* motherFile, TDirectory* motherDir Bool_t TDirectoryFile::cd(const char *path) { Bool_t ok = TDirectory::cd(path); - if (ok) TFile::CurrentFile() = fFile; + if (ok) + TFile::CurrentFile() = fFile; return ok; } @@ -1192,8 +1205,7 @@ void TDirectoryFile::ls(Option_t *option) const if (diskobj && fKeys) { //*-* Loop on all the keys - TObjLink *lnk = fKeys->FirstLink(); - while (lnk) { + for (TObjLink *lnk = fKeys->FirstLink(); lnk != nullptr; lnk = lnk->Next()) { TKey *key = (TKey*)lnk->GetObject(); TString s = key->GetName(); if (s.Index(re) == kNPOS) continue; @@ -1206,7 +1218,6 @@ void TDirectoryFile::ls(Option_t *option) const key->ls(); else key->ls(false); - lnk = lnk->Next(); } } TROOT::DecreaseDirLevel(); @@ -1557,8 +1568,10 @@ void TDirectoryFile::Save() //////////////////////////////////////////////////////////////////////////////// /// Save object in filename. /// -/// If filename is 0 or "", a file with "objectname.root" is created. +/// If filename is `nullptr` or "", a file with ".root" is created. /// The name of the key is the object name. +/// By default new file will be created. Using option "a", one can append object +/// to the existing ROOT file. /// If the operation is successful, it returns the number of bytes written to the file /// otherwise it returns 0. /// By default a message is printed. Use option "q" to not print the message. @@ -1569,27 +1582,28 @@ void TDirectoryFile::Save() Int_t TDirectoryFile::SaveObjectAs(const TObject *obj, const char *filename, Option_t *option) const { + // option can contain single letter args: "a" for append, "q" for quiet in any combinations + if (!obj) return 0; - TDirectory *dirsav = gDirectory; - TString fname = filename; - if (!filename || !filename[0]) { - fname.Form("%s.root",obj->GetName()); - } + TString fname, opt = option; + if (filename && *filename) + fname = filename; + else + fname.Form("%s.root", obj->GetName()); + opt.ToLower(); + Int_t nbytes = 0; if (fname.Index(".json") > 0) { nbytes = TBufferJSON::ExportToFile(fname, obj, option); } else { - TFile *local = TFile::Open(fname.Data(),"recreate"); + TContext ctxt; // The TFile::Open will change the current directory. + auto *local = TFile::Open(fname.Data(), opt.Contains("a") ? "update" : "recreate"); if (!local) return 0; nbytes = obj->Write(); delete local; - if (dirsav) dirsav->cd(); - } - TString opt = option; - opt.ToLower(); - if (!opt.Contains("q")) { - if (!gSystem->AccessPathName(fname.Data())) obj->Info("SaveAs", "ROOT file %s has been created", fname.Data()); } + if (!opt.Contains("q") && !gSystem->AccessPathName(fname.Data())) + obj->Info("SaveAs", "ROOT file %s has been created", fname.Data()); return nbytes; } diff --git a/io/io/src/TEmulatedCollectionProxy.cxx b/io/io/src/TEmulatedCollectionProxy.cxx index 9707ee4c072eb..9b3116d91b659 100644 --- a/io/io/src/TEmulatedCollectionProxy.cxx +++ b/io/io/src/TEmulatedCollectionProxy.cxx @@ -301,7 +301,7 @@ void TEmulatedCollectionProxy::Shrink(UInt_t nCurr, UInt_t left, Bool_t force ) h->set(0); } break; - case kIsPointer|kBIT_ISSTRING: + case 0U|kIsPointer|kBIT_ISSTRING: for( i=nCurr; iset(0); } break; - case kIsPointer|kBIT_ISTSTRING|kIsClass: + case 0U|kIsPointer|kBIT_ISTSTRING|kIsClass: for( i=nCurr; iptr(); @@ -347,14 +347,14 @@ void TEmulatedCollectionProxy::Shrink(UInt_t nCurr, UInt_t left, Bool_t force ) h->set(0); } break; - case kIsPointer|kBIT_ISSTRING: + case 0U|kIsPointer|kBIT_ISSTRING: for( i=nCurr; iptr(); h->set(0); } break; - case kIsPointer|kBIT_ISTSTRING|kIsClass: + case 0U|kIsPointer|kBIT_ISTSTRING|kIsClass: for( i=nCurr; iptr(); @@ -403,8 +403,8 @@ void TEmulatedCollectionProxy::Expand(UInt_t nCurr, UInt_t left) ::new(addr) std::string(); break; case kIsPointer|kIsClass: - case kIsPointer|kBIT_ISSTRING: - case kIsPointer|kBIT_ISTSTRING|kIsClass: + case 0U|kIsPointer|kBIT_ISSTRING: + case 0U|kIsPointer|kBIT_ISTSTRING|kIsClass: for( i=nCurr; iread_std_string(b) ); case kIsPointer|kIsClass: DOLOOP( i->read_any_object(fVal,b) ); - case kIsPointer|kBIT_ISSTRING: + case 0U|kIsPointer|kBIT_ISSTRING: DOLOOP( i->read_std_string_pointer(b) ); - case kIsPointer|kBIT_ISTSTRING|kIsClass: + case 0U|kIsPointer|kBIT_ISTSTRING|kIsClass: DOLOOP( i->read_tstring_pointer(vsn3,b) ); } @@ -590,9 +590,9 @@ void TEmulatedCollectionProxy::WriteItems(int nElements, TBuffer &b) DOLOOP( TString(i->c_str()).Streamer(b) ); case kIsPointer|kIsClass: DOLOOP( b.WriteObjectAny(i->ptr(),fVal->fType) ); - case kBIT_ISSTRING|kIsPointer: + case 0U|kBIT_ISSTRING|kIsPointer: DOLOOP( i->write_std_string_pointer(b) ); - case kBIT_ISTSTRING|kIsClass|kIsPointer: + case 0U|kBIT_ISTSTRING|kIsClass|kIsPointer: DOLOOP( i->write_tstring_pointer(b) ); } #undef DOLOOP diff --git a/io/io/src/TEmulatedMapProxy.cxx b/io/io/src/TEmulatedMapProxy.cxx index 6f3db329b1861..e79e133c065a2 100644 --- a/io/io/src/TEmulatedMapProxy.cxx +++ b/io/io/src/TEmulatedMapProxy.cxx @@ -141,10 +141,10 @@ void TEmulatedMapProxy::ReadMap(UInt_t nElements, TBuffer &b) case kIsPointer|kIsClass: helper->set(b.ReadObjectAny(v->fType)); break; - case kIsPointer|kBIT_ISSTRING: + case 0U|kIsPointer|kBIT_ISSTRING: helper->read_std_string_pointer(b); break; - case kIsPointer|kBIT_ISTSTRING|kIsClass: + case 0U|kIsPointer|kBIT_ISTSTRING|kIsClass: helper->read_tstring_pointer(vsn3,b); break; } @@ -200,10 +200,10 @@ void TEmulatedMapProxy::WriteMap(UInt_t nElements, TBuffer &b) case kIsPointer|kIsClass: b.WriteObjectAny(i->ptr(),v->fType); break; - case kBIT_ISSTRING|kIsPointer: + case 0U|kBIT_ISSTRING|kIsPointer: i->write_std_string_pointer(b); break; - case kBIT_ISTSTRING|kIsClass|kIsPointer: + case 0U|kBIT_ISTSTRING|kIsClass|kIsPointer: i->write_tstring_pointer(b); break; } diff --git a/io/io/src/TFile.cxx b/io/io/src/TFile.cxx index 032095ecdebe0..f64e5c15ca92e 100644 --- a/io/io/src/TFile.cxx +++ b/io/io/src/TFile.cxx @@ -14,29 +14,8 @@ \class TFile \ingroup IO -A ROOT file is a suite of consecutive data records (TKey instances) with -a well defined format. - -If the key is located past the 32 bit file limit (> 2 GB) then some fields will -be 8 instead of 4 bytes: - -Byte Range | Member Name | Description -----------------|-----------|-------------- -1->4 | Nbytes | Length of compressed object (in bytes) -5->6 | Version | TKey version identifier -7->10 | ObjLen | Length of uncompressed object -11->14 | Datime | Date and time when object was written to file -15->16 | KeyLen | Length of the key structure (in bytes) -17->18 | Cycle | Cycle of key -19->22 [19->26] | SeekKey | Pointer to record itself (consistency check) -23->26 [27->34] | SeekPdir | Pointer to directory header -27->27 [35->35] | lname | Number of bytes in the class name -28->.. [36->..] | ClassName | Object Class Name -..->.. | lname | Number of bytes in the object name -..->.. | Name | lName bytes with the name of the object -..->.. | lTitle | Number of bytes in the object title -..->.. | Title | Title of the object ------> | DATA | Data bytes associated to the object +A ROOT file is composed of a header, followed by consecutive data records +(`TKey` instances) with a well defined format. The first data record starts at byte fBEGIN (currently set to kBEGIN). Bytes 1->kBEGIN contain the file description, when fVersion >= 1000000 @@ -58,6 +37,35 @@ Byte Range | Record Name | Description 42->45 [54->57] | fNbytesInfo | Number of bytes in TStreamerInfo record 46->63 [58->75] | fUUID | Universal Unique ID +For the purpose of magic bytes in the context of ROOT files' MIME definition, +the following additional requirements are introduced: +- The value of `fBEGIN` is fixed at 100. +- The four bytes starting at position 96 are reserved and must be 0. +If any changes to this need to be made, `media-types@iana.org` needs to be +notified in accordance with RFC 6838. + +The key structure is as follows; if a key is located past the 32 bit file +limit (> 2 GB) then some fields will be 8 instead of 4 bytes (see parts marked +with square brackets below): + +Byte Range | Member Name | Description +----------------|-----------|-------------- +1->4 | Nbytes | Length of compressed object (in bytes) +5->6 | Version | TKey version identifier +7->10 | ObjLen | Length of uncompressed object +11->14 | Datime | Date and time when object was written to file +15->16 | KeyLen | Length of the key structure (in bytes) +17->18 | Cycle | Cycle of key +19->22 [19->26] | SeekKey | Pointer to record itself (consistency check) +23->26 [27->34] | SeekPdir | Pointer to directory header +27->27 [35->35] | lname | Number of bytes in the class name +28->.. [36->..] | ClassName | Object Class Name +..->.. | lname | Number of bytes in the object name +..->.. | Name | lName bytes with the name of the object +..->.. | lTitle | Number of bytes in the object title +..->.. | Title | Title of the object +-----> | DATA | Data bytes associated to the object + Begin_Macro ../../../tutorials/io/file.C End_Macro @@ -77,7 +85,9 @@ The structure of a directory is shown in TDirectoryFile::TDirectoryFile #include #ifndef WIN32 #include +#ifndef R__FBSD #include +#endif #else # define ssize_t int # include @@ -133,6 +143,10 @@ The structure of a directory is shown in TDirectoryFile::TDirectoryFile #include "ROOT/RConcurrentHashColl.hxx" #include +#ifdef R__FBSD +#include +#endif + using std::sqrt; std::atomic TFile::fgBytesRead{0}; @@ -155,6 +169,9 @@ ROOT::Internal::RConcurrentHashColl TFile::fgTsSIHashes; /* On macOS getxattr takes two extra arguments that should be set to 0 */ #define getxattr(path, name, value, size) getxattr(path, name, value, size, 0u, 0) #endif +#ifdef R__FBSD +#define getxattr(path, name, value, size) extattr_get_file(path, EXTATTR_NAMESPACE_USER, name, value, size) +#endif const Int_t kBEGIN = 100; @@ -4367,12 +4384,6 @@ TFileOpenHandle *TFile::AsyncOpen(const char *url, Option_t *option, notfound = kFALSE; } } - if ((h = gROOT->GetPluginManager()->FindHandler("TFile", name)) && - !strcmp(h->GetClass(),"TAlienFile") && h->LoadPlugin() == 0) { - f = (TFile*) h->ExecPlugin(5, name.Data(), option, ftitle, compress, kTRUE); - notfound = kFALSE; - } - } if (rediroutput) { diff --git a/io/io/src/TGenCollectionProxy.cxx b/io/io/src/TGenCollectionProxy.cxx index 476770046591d..c24e5ebcfd1ee 100644 --- a/io/io/src/TGenCollectionProxy.cxx +++ b/io/io/src/TGenCollectionProxy.cxx @@ -43,7 +43,7 @@ class TGenVectorProxy : public TGenCollectionProxy { { } // Standard Destructor - virtual ~TGenVectorProxy() + ~TGenVectorProxy() override { } // Return the address of the value at index 'idx' @@ -93,7 +93,7 @@ class TGenVectorBoolProxy : public TGenCollectionProxy { { // Standard Constructor. } - virtual ~TGenVectorBoolProxy() + ~TGenVectorBoolProxy() override { // Standard Destructor. } @@ -139,7 +139,7 @@ class TGenBitsetProxy : public TGenCollectionProxy { { // Standard Constructor. } - virtual ~TGenBitsetProxy() + ~TGenBitsetProxy() override { // Standard Destructor. } @@ -194,7 +194,7 @@ class TGenListProxy : public TGenVectorProxy { { } // Standard Destructor - virtual ~TGenListProxy() + ~TGenListProxy() override { } // Return the address of the value at index 'idx' @@ -236,7 +236,7 @@ class TGenSetProxy : public TGenVectorProxy { { } // Standard Destructor - virtual ~TGenSetProxy() + ~TGenSetProxy() override { } // Return the address of the value at index 'idx' @@ -281,7 +281,7 @@ class TGenMapProxy : public TGenSetProxy { { } // Standard Destructor - virtual ~TGenMapProxy() + ~TGenMapProxy() override { } // Call to delete/destruct individual item @@ -958,6 +958,12 @@ TGenCollectionProxy *TGenCollectionProxy::InitializeEx(Bool_t silent) } break; } + if (!(fProperties & kIsEmulated) && newfValue->fType && !newfValue->fType->IsSyntheticPair()) { + if (!newfValue->fType->IsLoaded() && !newfValue->fType->HasInterpreterInfo()) + Error("TGenCollectionProxy::InitializeEx", + "The TClass for %s used as the value type of the compiled collection proxy %s is not loaded.", + newfValue->fType->GetName(), cl->GetName()); + } fPointers = fPointers || (0 != (fVal->fCase&kIsPointer)); if (fPointers || (0 != (fVal->fProperties&kNeedDelete))) { diff --git a/io/io/src/TGenCollectionStreamer.cxx b/io/io/src/TGenCollectionStreamer.cxx index a2acf0b8d0ba5..0ac364f92c524 100644 --- a/io/io/src/TGenCollectionStreamer.cxx +++ b/io/io/src/TGenCollectionStreamer.cxx @@ -393,9 +393,9 @@ void TGenCollectionStreamer::ReadObjects(int nElements, TBuffer &b, const TClass DOLOOP(i->read_std_string(b)); case kIsPointer | kIsClass: DOLOOP(i->set(b.ReadObjectAny(fVal->fType))); - case kIsPointer | kBIT_ISSTRING: + case 0U | kIsPointer | kBIT_ISSTRING: DOLOOP(i->read_std_string_pointer(b)); - case kIsPointer | kBIT_ISTSTRING | kIsClass: + case 0U | kIsPointer | kBIT_ISTSTRING | kIsClass: DOLOOP(i->read_tstring_pointer(vsn3, b)); } #undef DOLOOP @@ -418,9 +418,9 @@ void TGenCollectionStreamer::ReadObjects(int nElements, TBuffer &b, const TClass DOLOOP(i->read_std_string(b)); case kIsPointer | kIsClass: DOLOOP(i->set(b.ReadObjectAny(fVal->fType))); - case kIsPointer | kBIT_ISSTRING: + case 0U | kIsPointer | kBIT_ISSTRING: DOLOOP(i->read_std_string_pointer(b)); - case kIsPointer | kBIT_ISTSTRING | kIsClass: + case 0U | kIsPointer | kBIT_ISTSTRING | kIsClass: DOLOOP(i->read_tstring_pointer(vsn3, b)); } #undef DOLOOP @@ -451,11 +451,11 @@ void TGenCollectionStreamer::ReadObjects(int nElements, TBuffer &b, const TClass DOLOOP(i->set(b.ReadObjectAny(fVal->fType))); fFeed(fEnv->fStart,fEnv->fObject,fEnv->fSize); break; - case kIsPointer | kBIT_ISSTRING: + case 0U | kIsPointer | kBIT_ISSTRING: DOLOOP(i->read_std_string_pointer(b)) fFeed(fEnv->fStart,fEnv->fObject,fEnv->fSize); break; - case kIsPointer | kBIT_ISTSTRING | kIsClass: + case 0U | kIsPointer | kBIT_ISTSTRING | kIsClass: DOLOOP(i->read_tstring_pointer(vsn3, b)); fFeed(fEnv->fStart,fEnv->fObject,fEnv->fSize); break; @@ -636,10 +636,10 @@ void TGenCollectionStreamer::ReadMapHelper(StreamHelper *i, Value *v, Bool_t vsn case kIsPointer | kIsClass: i->set(b.ReadObjectAny(v->fType)); break; - case kIsPointer | kBIT_ISSTRING: + case 0U | kIsPointer | kBIT_ISSTRING: i->read_std_string_pointer(b); break; - case kIsPointer | kBIT_ISTSTRING | kIsClass: + case 0U | kIsPointer | kBIT_ISTSTRING | kIsClass: i->read_tstring_pointer(vsn3, b); break; } @@ -870,10 +870,10 @@ void TGenCollectionStreamer::ReadMap(int nElements, TBuffer &b, const TClass *on case kIsPointer | kIsClass: i->set(b.ReadObjectAny(v->fType)); break; - case kIsPointer | kBIT_ISSTRING: + case 0U | kIsPointer | kBIT_ISSTRING: i->read_std_string_pointer(b); break; - case kIsPointer | kBIT_ISTSTRING | kIsClass: + case 0U | kIsPointer | kBIT_ISTSTRING | kIsClass: i->read_tstring_pointer(vsn3, b); break; } @@ -981,10 +981,10 @@ void TGenCollectionStreamer::WriteObjects(int nElements, TBuffer &b) case kIsPointer | kIsClass: DOLOOP(b.WriteObjectAny(i->ptr(), fVal->fType)); break; - case kBIT_ISSTRING | kIsPointer: + case 0U | kBIT_ISSTRING | kIsPointer: DOLOOP(i->write_std_string_pointer(b)); break; - case kBIT_ISTSTRING | kIsClass | kIsPointer: + case 0U | kBIT_ISTSTRING | kIsClass | kIsPointer: DOLOOP(i->write_tstring_pointer(b)); break; } @@ -1009,9 +1009,9 @@ void TGenCollectionStreamer::WriteObjects(int nElements, TBuffer &b) DOLOOP(TString(i->c_str()).Streamer(b)); case kIsPointer | kIsClass: DOLOOP(b.WriteObjectAny(i->ptr(), fVal->fType)); - case kBIT_ISSTRING | kIsPointer: + case 0U | kBIT_ISSTRING | kIsPointer: DOLOOP(i->write_std_string_pointer(b)); - case kBIT_ISTSTRING | kIsClass | kIsPointer: + case 0U | kBIT_ISTSTRING | kIsClass | kIsPointer: DOLOOP(i->write_tstring_pointer(b)); } #undef DOLOOP @@ -1096,10 +1096,10 @@ void TGenCollectionStreamer::WriteMap(int nElements, TBuffer &b) case kIsPointer | kIsClass: b.WriteObjectAny(i->ptr(), v->fType); break; - case kBIT_ISSTRING | kIsPointer: + case 0U | kBIT_ISSTRING | kIsPointer: i->write_std_string_pointer(b); break; - case kBIT_ISTSTRING | kIsClass | kIsPointer: + case 0U | kBIT_ISTSTRING | kIsClass | kIsPointer: i->write_tstring_pointer(b); break; } diff --git a/io/io/src/TKey.cxx b/io/io/src/TKey.cxx index e604af2980b88..bc94f35c1b15b 100644 --- a/io/io/src/TKey.cxx +++ b/io/io/src/TKey.cxx @@ -736,16 +736,24 @@ void TKey::Print(Option_t *) const /// one must use a dynamic_cast. /// /// #### Example1: simplified case -/// class MyClass : public TObject, public AnotherClass +/// ~~~{.cpp} +/// class MyClass : public TObject, public AnotherClass +/// ~~~ /// then on return, one get away with using: -/// MyClass *obj = (MyClass*)key->ReadObj(); +/// ~~~{.cpp} +/// MyClass *obj = (MyClass*)key->ReadObj(); +/// ~~~ /// /// #### Example2: Usual case (recommended unless performance is critical) -/// MyClass *obj = dynamic_cast(key->ReadObj()); +/// ~~~{.cpp} +/// MyClass *obj = dynamic_cast(key->ReadObj()); +/// ~~~ /// which support also the more complex inheritance like: -/// class MyClass : public AnotherClass, public TObject +/// ~~~{.cpp} +/// class MyClass : public AnotherClass, public TObject +/// ~~~ /// -/// Of course, dynamic_cast<> can also be used in the example 1. +/// Of course, `dynamic_cast<>` can also be used in the example 1. TObject *TKey::ReadObj() { diff --git a/io/io/src/TStreamerInfo.cxx b/io/io/src/TStreamerInfo.cxx index ccba410d4dc52..08e8dd25fe7de 100644 --- a/io/io/src/TStreamerInfo.cxx +++ b/io/io/src/TStreamerInfo.cxx @@ -4394,24 +4394,24 @@ T TStreamerInfo::GetTypedValueAux(Int_t type, void *ladd, Int_t k, Int_t len) } // pointer to an array of basic types array[n] - case kOffsetP + kBool_t: READ_ARRAY(Bool_t) - case kOffsetP + kChar_t: READ_ARRAY(Char_t) - case kOffsetP + kShort_t: READ_ARRAY(Short_t) - case kOffsetP + kInt_t: READ_ARRAY(Int_t) - case kOffsetP + kLong_t: READ_ARRAY(Long_t) - case kOffsetP + kLong64_t: READ_ARRAY(Long64_t) - case kOffsetP + kFloat16_t: - case kOffsetP + kFloat_t: READ_ARRAY(Float_t) - case kOffsetP + kDouble32_t: - case kOffsetP + kDouble_t: READ_ARRAY(Double_t) - case kOffsetP + kUChar_t: READ_ARRAY(UChar_t) - case kOffsetP + kUShort_t: READ_ARRAY(UShort_t) - case kOffsetP + kUInt_t: READ_ARRAY(UInt_t) - case kOffsetP + kULong_t: READ_ARRAY(ULong_t) + case (unsigned)kOffsetP + kBool_t: READ_ARRAY(Bool_t) + case (unsigned)kOffsetP + kChar_t: READ_ARRAY(Char_t) + case (unsigned)kOffsetP + kShort_t: READ_ARRAY(Short_t) + case (unsigned)kOffsetP + kInt_t: READ_ARRAY(Int_t) + case (unsigned)kOffsetP + kLong_t: READ_ARRAY(Long_t) + case (unsigned)kOffsetP + kLong64_t: READ_ARRAY(Long64_t) + case (unsigned)kOffsetP + kFloat16_t: + case (unsigned)kOffsetP + kFloat_t: READ_ARRAY(Float_t) + case (unsigned)kOffsetP + kDouble32_t: + case (unsigned)kOffsetP + kDouble_t: READ_ARRAY(Double_t) + case (unsigned)kOffsetP + kUChar_t: READ_ARRAY(UChar_t) + case (unsigned)kOffsetP + kUShort_t: READ_ARRAY(UShort_t) + case (unsigned)kOffsetP + kUInt_t: READ_ARRAY(UInt_t) + case (unsigned)kOffsetP + kULong_t: READ_ARRAY(ULong_t) #if defined(_MSC_VER) && (_MSC_VER <= 1200) - case kOffsetP + kULong64_t: READ_ARRAY(Long64_t) + case (unsigned)kOffsetP + kULong64_t: READ_ARRAY(Long64_t) #else - case kOffsetP + kULong64_t: READ_ARRAY(ULong64_t) + case (unsigned)kOffsetP + kULong64_t: READ_ARRAY(ULong64_t) #endif // array counter //[n] diff --git a/io/io/src/TStreamerInfoActions.cxx b/io/io/src/TStreamerInfoActions.cxx index 636dd7c1391be..3817ad6c96b20 100644 --- a/io/io/src/TStreamerInfoActions.cxx +++ b/io/io/src/TStreamerInfoActions.cxx @@ -237,7 +237,9 @@ namespace TStreamerInfoActions UInt_t *x = (UInt_t*)( ((char*)addr) + config->fOffset ); // Idea: Implement buf.ReadBasic/Primitive to avoid the return value // Idea: This code really belongs inside TBuffer[File] + const UInt_t isonheap = *x & TObject::kIsOnHeap; // Record how this instance was actually allocated. buf >> *x; + *x |= isonheap | TObject::kNotDeleted; // by definition de-serialized object are not yet deleted. if ((*x & kIsReferenced) != 0) { HandleReferencedTObject(buf,addr,config); @@ -1028,7 +1030,7 @@ namespace TStreamerInfoActions public: TVectorLoopConfig(TVirtualCollectionProxy *proxy, Long_t increment, Bool_t /* read */) : TLoopConfiguration(proxy), fIncrement(increment) {}; //virtual void PrintDebug(TBuffer &buffer, void *); - virtual ~TVectorLoopConfig() {}; + ~TVectorLoopConfig() override {}; void Print() const override { printf("TVectorLoopConfig: increment=%ld\n",fIncrement); @@ -1049,7 +1051,7 @@ namespace TStreamerInfoActions public: TAssocLoopConfig(TVirtualCollectionProxy *proxy, Bool_t /* read */) : TLoopConfiguration(proxy) {}; //virtual void PrintDebug(TBuffer &buffer, void *); - virtual ~TAssocLoopConfig() {}; + ~TAssocLoopConfig() override {}; void Print() const override { printf("TAssocLoopConfig: proxy=%s\n",fProxy->GetCollectionClass()->GetName()); @@ -1096,7 +1098,7 @@ namespace TStreamerInfoActions { Init(read); } - virtual ~TGenericLoopConfig() {}; + ~TGenericLoopConfig() override {}; void Print() const override { printf("TGenericLoopConfig: proxy=%s\n",fProxy->GetCollectionClass()->GetName()); @@ -1568,7 +1570,7 @@ namespace TStreamerInfoActions } } - virtual ~TConfigurationUseCache() {} + ~TConfigurationUseCache() override {} TConfiguration *Copy() override { TConfigurationUseCache *copy = new TConfigurationUseCache(*this); diff --git a/io/io/src/TStreamerInfoReadBuffer.cxx b/io/io/src/TStreamerInfoReadBuffer.cxx index e9054d8d4e26e..5b84e330f9b91 100644 --- a/io/io/src/TStreamerInfoReadBuffer.cxx +++ b/io/io/src/TStreamerInfoReadBuffer.cxx @@ -609,6 +609,7 @@ Int_t TStreamerInfo::ReadBufferConv(TBuffer &b, const T &arr, const TCompInfo * DOLOOP { UInt_t u; b >> u; + u |= kNotDeleted; // by definition de-serialized object are not yet deleted. if ((u & kIsReferenced) != 0) { UShort_t pidf; b >> pidf; @@ -1019,7 +1020,10 @@ Int_t TStreamerInfo::ReadBuffer(TBuffer &b, const T &arr, // special case for TObject::fBits in case of a referenced object case TStreamerInfo::kBits: { DOLOOP { - UInt_t *x=(UInt_t*)(arr[k]+ioffset); b >> *x; + UInt_t *x=(UInt_t*)(arr[k]+ioffset); + const UInt_t isonheap = *x & TObject::kIsOnHeap; // Record how this instance was actually allocated. + b >> *x; + *x |= isonheap | TObject::kNotDeleted; // by definition de-serialized object are not yet deleted. if ((*x & kIsReferenced) != 0) { UShort_t pidf; b >> pidf; diff --git a/io/io/src/TStreamerInfoWriteBuffer.cxx b/io/io/src/TStreamerInfoWriteBuffer.cxx index 6d3ec6f1aee7d..652a72885169b 100644 --- a/io/io/src/TStreamerInfoWriteBuffer.cxx +++ b/io/io/src/TStreamerInfoWriteBuffer.cxx @@ -404,7 +404,7 @@ Int_t TStreamerInfo::WriteBufferAux(TBuffer &b, const T &arr, // special case for TObject::fBits in case of a referenced object case TStreamerInfo::kBits: { DOLOOP { - UInt_t *x=(UInt_t*)(arr[k]+ioffset); b << *x; + UInt_t *x=(UInt_t*)(arr[k]+ioffset); b << (*x & (~kIsOnHeap & ~kNotDeleted)); if ((*x & kIsReferenced) != 0) { TObject *obj = (TObject*)(arr[k]+eoffset); TProcessID *pid = TProcessID::GetProcessWithUID(obj->GetUniqueID(),obj); diff --git a/io/mpi/inc/TMPIFile.h b/io/mpi/inc/TMPIFile.h index 10024c7fdae83..fcf68ff81006c 100644 --- a/io/mpi/inc/TMPIFile.h +++ b/io/mpi/inc/TMPIFile.h @@ -71,10 +71,10 @@ class TMPIFile : public TMemFile { public: ParallelFileMerger(const char *filename, Int_t compression_settings, Bool_t writeCache = kFALSE); - virtual ~ParallelFileMerger(); + ~ParallelFileMerger() override; - ULong_t Hash() const { return fFilename.Hash(); }; - const char *GetName() const { return fFilename; }; + ULong_t Hash() const override { return fFilename.Hash(); }; + const char *GetName() const override { return fFilename; }; static Bool_t NeedInitialMerge(TDirectory *dir); @@ -97,7 +97,7 @@ class TMPIFile : public TMemFile { const char *ftitle = "", Int_t compress = 4); TMPIFile(const char *name, Option_t *option = "", Int_t split = 1, const char *ftitle = "", Int_t compress = 4); // no complete implementation - virtual ~TMPIFile(); + ~TMPIFile() override; // some functions on MPI information Int_t GetMPIGlobalSize() const { return fMPIGlobalSize; }; @@ -122,6 +122,6 @@ class TMPIFile : public TMemFile { // Finalize work and save output in disk. void Close(Option_t *option = "") final; - ClassDef(TMPIFile, 0) + ClassDefOverride(TMPIFile, 0) }; #endif diff --git a/io/rootpcm/src/rootclingIO.cxx b/io/rootpcm/src/rootclingIO.cxx index 9e470646f4089..cd24918a66bb0 100644 --- a/io/rootpcm/src/rootclingIO.cxx +++ b/io/rootpcm/src/rootclingIO.cxx @@ -241,9 +241,9 @@ bool CloseStreamerInfoROOTFile(bool writeEmptyRootPCM) TObjArray enums(gEnumsToStore.size()); for (const auto & enumname : gEnumsToStore) { TEnum *en = nullptr; - const size_t lastSepPos = enumname.find_last_of("::"); + const size_t lastSepPos = enumname.rfind("::"); if (lastSepPos != std::string::npos) { - const std::string nsName = enumname.substr(0, lastSepPos - 1); + const std::string nsName = enumname.substr(0, lastSepPos); TClass *tclassInstance = TClass::GetClass(nsName.c_str()); if (!tclassInstance) { Error("CloseStreamerInfoROOTFile", "Cannot find TClass instance for namespace %s.", nsName.c_str()); @@ -256,7 +256,7 @@ bool CloseStreamerInfoROOTFile(bool writeEmptyRootPCM) Error("CloseStreamerInfoROOTFile", "TClass instance for namespace %s does not have any enum associated. This is an inconsistency.", nsName.c_str()); return false; } - const std::string unqualifiedEnumName = enumname.substr(lastSepPos + 1); + const std::string unqualifiedEnumName = enumname.substr(lastSepPos + 2); en = (TEnum *)enumListPtr->FindObject(unqualifiedEnumName.c_str()); if (en) en->SetTitle(nsName.c_str()); } else { diff --git a/io/sql/inc/TBufferSQL2.h b/io/sql/inc/TBufferSQL2.h index 49b59183ac7e8..ff82a0bb6a47a 100644 --- a/io/sql/inc/TBufferSQL2.h +++ b/io/sql/inc/TBufferSQL2.h @@ -123,7 +123,7 @@ class TBufferSQL2 final : public TBufferText { public: TBufferSQL2(TBuffer::EMode mode, TSQLFile *file = nullptr); - virtual ~TBufferSQL2(); + ~TBufferSQL2() override; void SetCompressionLevel(int level) { fCompressLevel = level; } diff --git a/io/sql/inc/TKeySQL.h b/io/sql/inc/TKeySQL.h index f0d3b80f070e0..93025fa108a6d 100644 --- a/io/sql/inc/TKeySQL.h +++ b/io/sql/inc/TKeySQL.h @@ -38,7 +38,7 @@ class TKeySQL final : public TKey { TKeySQL(TDirectory *mother, const void *obj, const TClass *cl, const char *name, const char *title = nullptr); TKeySQL(TDirectory *mother, Long64_t keyid, Long64_t objid, const char *name, const char *title, const char *keydatetime, Int_t cycle, const char *classname); - virtual ~TKeySQL() = default; + ~TKeySQL() override = default; Bool_t IsKeyModified(const char *keyname, const char *keytitle, const char *keydatime, Int_t cycle, const char *classname); diff --git a/io/sql/inc/TSQLClassInfo.h b/io/sql/inc/TSQLClassInfo.h index 2a79ba412a468..63be948ffb75a 100644 --- a/io/sql/inc/TSQLClassInfo.h +++ b/io/sql/inc/TSQLClassInfo.h @@ -42,7 +42,7 @@ class TSQLClassInfo final : public TObject { public: TSQLClassInfo() {} // NOLINT: not allowed to use = default because of TObject::kIsOnHeap detection, see ROOT-10300 TSQLClassInfo(Long64_t classid, const char *classname, Int_t version); - virtual ~TSQLClassInfo(); + ~TSQLClassInfo() override; Long64_t GetClassId() const { return fClassId; } diff --git a/io/sql/inc/TSQLFile.h b/io/sql/inc/TSQLFile.h index 42a25433f0a72..0ece3679ae096 100644 --- a/io/sql/inc/TSQLFile.h +++ b/io/sql/inc/TSQLFile.h @@ -178,7 +178,7 @@ class TSQLFile final : public TFile { TSQLFile(); TSQLFile(const char *dbname, Option_t *option = "read", const char *user = "user", const char *pass = "pass"); - virtual ~TSQLFile(); + ~TSQLFile() override; // configuration of SQL Bool_t GetUseSuffixes() const { return fUseSuffixes; } diff --git a/io/sql/inc/TSQLObjectData.h b/io/sql/inc/TSQLObjectData.h index cec3f7757acc3..6e9dab2f8cea7 100644 --- a/io/sql/inc/TSQLObjectData.h +++ b/io/sql/inc/TSQLObjectData.h @@ -28,7 +28,7 @@ class TSQLObjectInfo : public TObject { public: TSQLObjectInfo(); TSQLObjectInfo(Long64_t objid, const char *classname, Version_t version); - virtual ~TSQLObjectInfo(); + ~TSQLObjectInfo() override; Long64_t GetObjId() const { return fObjId; } const char *GetObjClassName() const { return fClassName.Data(); } @@ -52,7 +52,7 @@ class TSQLObjectData : public TObject { TSQLObjectData(TSQLClassInfo *sqlinfo, Long64_t objid, TSQLResult *classdata, TSQLRow *classrow, TSQLResult *blobdata, TSQLStatement *blobstmt); - virtual ~TSQLObjectData(); + ~TSQLObjectData() override; Long64_t GetObjId() const { return fObjId; } TSQLClassInfo *GetInfo() const { return fInfo; } @@ -110,7 +110,7 @@ class TSQLObjectDataPool : public TObject { public: TSQLObjectDataPool(); TSQLObjectDataPool(TSQLClassInfo *info, TSQLResult *data); - virtual ~TSQLObjectDataPool(); + ~TSQLObjectDataPool() override; TSQLClassInfo *GetSqlInfo() const { return fInfo; } TSQLResult *GetClassData() const { return fClassData; } diff --git a/io/sql/inc/TSQLStructure.h b/io/sql/inc/TSQLStructure.h index 84be669285eac..b244f1b57f171 100644 --- a/io/sql/inc/TSQLStructure.h +++ b/io/sql/inc/TSQLStructure.h @@ -69,7 +69,7 @@ class TSQLTableData : public TObject { public: TSQLTableData(TSQLFile *f = nullptr, TSQLClassInfo *info = nullptr); - virtual ~TSQLTableData(); + ~TSQLTableData() override; void AddColumn(const char *name, Long64_t value); void AddColumn(const char *name, const char *sqltype, const char *value, Bool_t numeric); @@ -111,7 +111,7 @@ class TSQLStructure : public TObject { public: TSQLStructure() {} // NOLINT: not allowed to use = default because of TObject::kIsOnHeap detection, see ROOT-10300 - virtual ~TSQLStructure(); + ~TSQLStructure() override; TSQLStructure *GetParent() const { return fParent; } void SetParent(TSQLStructure *p) { fParent = p; } diff --git a/io/sql/src/TSQLStructure.cxx b/io/sql/src/TSQLStructure.cxx index 01cd703a8cd07..64c079b0e7844 100644 --- a/io/sql/src/TSQLStructure.cxx +++ b/io/sql/src/TSQLStructure.cxx @@ -789,7 +789,7 @@ class TSqlCmdsBuffer : public TObject { public: TSqlCmdsBuffer(TSQLFile *f, TSQLClassInfo *info) : TObject(), fFile(f), fInfo(info), fBlobStmt(nullptr), fNormStmt(nullptr) {} - virtual ~TSqlCmdsBuffer() + ~TSqlCmdsBuffer() override { fNormCmds.Delete(); fBlobCmds.Delete(); @@ -844,7 +844,7 @@ class TSqlRegistry : public TObject { TSQLStatement *fRegStmt; - virtual ~TSqlRegistry() + ~TSqlRegistry() override { fPool.DeleteValues(); fLongStrValues.Delete(); @@ -1089,7 +1089,7 @@ class TSqlRawBuffer : public TObject { fMaxStrSize = reg->fFile->SQLSmallTextTypeLimit(); } - virtual ~TSqlRawBuffer() + ~TSqlRawBuffer() override { // close blob statement for Oracle TSQLStatement *stmt = fCmdBuf->fBlobStmt; diff --git a/io/xml/inc/TBufferXML.h b/io/xml/inc/TBufferXML.h index 0f7fc29020d42..be61c1332a336 100644 --- a/io/xml/inc/TBufferXML.h +++ b/io/xml/inc/TBufferXML.h @@ -37,7 +37,7 @@ class TBufferXML final : public TBufferText, public TXMLSetup { public: TBufferXML(TBuffer::EMode mode); TBufferXML(TBuffer::EMode mode, TXMLFile *file); - virtual ~TBufferXML(); + ~TBufferXML() override; static TString ConvertToXML(const TObject *obj, Bool_t GenericLayout = kFALSE, Bool_t UseNamespaces = kFALSE); static TString diff --git a/io/xml/inc/TKeyXML.h b/io/xml/inc/TKeyXML.h index 7ef1a1c02af5f..9294990dd8400 100644 --- a/io/xml/inc/TKeyXML.h +++ b/io/xml/inc/TKeyXML.h @@ -32,7 +32,7 @@ class TKeyXML final : public TKey { TKeyXML(TDirectory *mother, Long64_t keyid, const void *obj, const TClass *cl, const char *name, const char *title = nullptr); TKeyXML(TDirectory *mother, Long64_t keyid, XMLNodePointer_t keynode); - virtual ~TKeyXML(); + ~TKeyXML() override; // redefined TKey Methods void Delete(Option_t *option = "") final; diff --git a/io/xml/inc/TXMLEngine.h b/io/xml/inc/TXMLEngine.h index 257a2374ee6ff..ebc1a6d8aae9c 100644 --- a/io/xml/inc/TXMLEngine.h +++ b/io/xml/inc/TXMLEngine.h @@ -43,7 +43,7 @@ class TXMLEngine : public TObject { public: TXMLEngine(); - virtual ~TXMLEngine(); + ~TXMLEngine() override; void SetSkipComments(Bool_t on = kTRUE) { fSkipComments = on; } Bool_t GetSkipComments() const { return fSkipComments; } diff --git a/io/xml/inc/TXMLFile.h b/io/xml/inc/TXMLFile.h index b398f2d894173..12cbc41de4571 100644 --- a/io/xml/inc/TXMLFile.h +++ b/io/xml/inc/TXMLFile.h @@ -50,7 +50,7 @@ class TXMLFile final : public TFile, public TXMLSetup { public: TXMLFile() {} // NOLINT: not allowed to use = default because of TObject::kIsOnHeap detection, see ROOT-10300 TXMLFile(const char *filename, Option_t *option = "read", const char *title = "title", Int_t compression = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); - virtual ~TXMLFile(); + ~TXMLFile() override; void Close(Option_t *option = "") final; // *MENU* TKey *CreateKey(TDirectory *mother, const TObject *obj, const char *name, Int_t bufsize) final; diff --git a/io/xml/inc/TXMLPlayer.h b/io/xml/inc/TXMLPlayer.h index a219ac52b08ae..609a9921f485a 100644 --- a/io/xml/inc/TXMLPlayer.h +++ b/io/xml/inc/TXMLPlayer.h @@ -25,7 +25,7 @@ class TList; class TXMLPlayer : public TObject { public: TXMLPlayer(); - virtual ~TXMLPlayer(); + ~TXMLPlayer() override; Bool_t ProduceCode(TList *cllist, const char *filename); diff --git a/io/xmlparser/inc/TDOMParser.h b/io/xmlparser/inc/TDOMParser.h index dea739fb376de..02d219424a58c 100644 --- a/io/xmlparser/inc/TDOMParser.h +++ b/io/xmlparser/inc/TDOMParser.h @@ -28,7 +28,7 @@ class TDOMParser : public TXMLParser { public: TDOMParser(); - virtual ~TDOMParser(); + ~TDOMParser() override; Int_t ParseFile(const char *filename) override; Int_t ParseBuffer(const char *buffer, Int_t len) override; diff --git a/io/xmlparser/inc/TSAXParser.h b/io/xmlparser/inc/TSAXParser.h index 890589e2769f4..82c3d328a6329 100644 --- a/io/xmlparser/inc/TSAXParser.h +++ b/io/xmlparser/inc/TSAXParser.h @@ -34,7 +34,7 @@ friend class TSAXParserCallback; public: TSAXParser(); - virtual ~TSAXParser(); + ~TSAXParser() override; Int_t ParseFile(const char *filename) override; Int_t ParseBuffer(const char *contents, Int_t len) override; diff --git a/io/xmlparser/inc/TXMLAttr.h b/io/xmlparser/inc/TXMLAttr.h index b81af360cf872..ff76b1808b321 100644 --- a/io/xmlparser/inc/TXMLAttr.h +++ b/io/xmlparser/inc/TXMLAttr.h @@ -26,7 +26,7 @@ class TXMLAttr : public TObject { public: TXMLAttr(const char *key, const char *value) : fKey(key), fValue(value) {} - virtual ~TXMLAttr() {} + ~TXMLAttr() override {} const char *GetName() const override { return fKey; } const char *Key() const { return fKey; } diff --git a/io/xmlparser/inc/TXMLDocument.h b/io/xmlparser/inc/TXMLDocument.h index 581315248d0cc..c70777335bbf3 100644 --- a/io/xmlparser/inc/TXMLDocument.h +++ b/io/xmlparser/inc/TXMLDocument.h @@ -29,7 +29,7 @@ class TXMLDocument : public TObject { public: TXMLDocument(_xmlDoc *doc); - virtual ~TXMLDocument(); + ~TXMLDocument() override; TXMLNode *GetRootNode() const; diff --git a/io/xmlparser/inc/TXMLNode.h b/io/xmlparser/inc/TXMLNode.h index 06d4506c1632a..539c531da804a 100644 --- a/io/xmlparser/inc/TXMLNode.h +++ b/io/xmlparser/inc/TXMLNode.h @@ -42,7 +42,7 @@ class TXMLNode : public TObject { TXMLNode(_xmlNode *node, TXMLNode *parent = nullptr, TXMLNode *previous = nullptr); - virtual ~TXMLNode(); + ~TXMLNode() override; EXMLElementType GetNodeType() const; const char *GetNodeName() const; diff --git a/io/xmlparser/inc/TXMLParser.h b/io/xmlparser/inc/TXMLParser.h index 6e84e9b3a1bb4..6c2d11c907fef 100644 --- a/io/xmlparser/inc/TXMLParser.h +++ b/io/xmlparser/inc/TXMLParser.h @@ -44,7 +44,7 @@ class TXMLParser : public TObject, public TQObject { public: TXMLParser(); - virtual ~TXMLParser(); + ~TXMLParser() override; void SetValidate(Bool_t val = kTRUE); Bool_t GetValidate() const { return fValidate; } diff --git a/js/LICENSE b/js/LICENSE index 6a257e05e29d8..0c09d771444b3 100644 --- a/js/LICENSE +++ b/js/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright � 2013-2022 JavaScript ROOT authors +Copyright � 2013-2023 JavaScript ROOT authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/js/build/jsroot.js b/js/build/jsroot.js index a931797c4b473..752c1bff9b2b5 100644 --- a/js/build/jsroot.js +++ b/js/build/jsroot.js @@ -1,4 +1,4 @@ -// https://root.cern/js/ v7.3.0 +// https://root.cern/js/ v7.5.0 (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : @@ -7,35 +7,39 @@ typeof define === 'function' && define.amd ? define(['exports'], factory) : /** @summary version id * @desc For the JSROOT release the string in format 'major.minor.patch' like '7.0.0' */ -let version_id = '7.3.x'; +const version_id = '7.5.pre', /** @summary version date * @desc Release date in format day/month/year like '14/04/2022' */ -let version_date = '19/12/2022'; +version_date = '28/09/2023', /** @summary version id and date * @desc Produced by concatenation of {@link version_id} and {@link version_date} * Like '7.0.0 14/04/2022' */ -let version = version_id + ' ' + version_date; +version = version_id + ' ' + version_date, -/** @summary Location of JSROOT scripts - * @desc Automatically detected and used to load other scripts or modules */ -exports.source_dir = ''; - -let nodejs = !!((typeof process == 'object') && isObject(process.versions) && process.versions.node && process.versions.v8); +/** @summary Is node.js flag + * @private */ +nodejs = !!((typeof process === 'object') && isObject(process.versions) && process.versions.node && process.versions.v8), /** @summary internal data * @private */ -let internals = { - id_counter: 1 ///< unique id contner, starts from 1 -}; +internals = { + /** @summary unique id counter, starts from 1 */ + id_counter: 1 +}, -//openuicfg // DO NOT DELETE, used to configure openui5 usage like internals.openui5src = 'nojsroot'; +_src = (typeof document === 'undefined' && typeof location === 'undefined' ? undefined : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('jsroot.js', document.baseURI).href)); -const src = (typeof document === 'undefined' && typeof location === 'undefined' ? undefined : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('jsroot.js', document.baseURI).href));if (src && isStr(src)) { - const pos = src.indexOf('modules/core.mjs'); +/** @summary Location of JSROOT modules + * @desc Automatically detected and used to dynamically load other modules + * @private */ +exports.source_dir = ''; + +if (_src && isStr(_src)) { + const pos = _src.indexOf('modules/core.mjs'); if (pos >= 0) { - exports.source_dir = src.slice(0, pos); + exports.source_dir = _src.slice(0, pos); console.log(`Set jsroot source_dir to ${exports.source_dir}, ${version}`); } else { console.log(`jsroot bundle, ${version}`); @@ -43,49 +47,57 @@ const src = (typeof document === 'undefined' && typeof location === 'undefined' } } +/** @summary Is batch mode flag + * @private */ let batch_mode = nodejs; /** @summary Indicates if running in batch mode */ function isBatchMode() { return batch_mode; } -/** @summary Set batch mode */ +/** @summary Set batch mode + * @private */ function setBatchMode(on) { batch_mode = !!on; } /** @summary Indicates if running inside Node.js */ function isNodeJs() { return nodejs; } -/** @summary atob function in all environments */ -const atob_func = isNodeJs() ? str => Buffer.from(str,'base64').toString('latin1') : globalThis?.atob; +/** @summary atob function in all environments + * @private */ +const atob_func = isNodeJs() ? str => Buffer.from(str, 'base64').toString('latin1') : globalThis?.atob, -/** @summary btoa function in all environments */ -const btoa_func = isNodeJs() ? str => Buffer.from(str,'latin1').toString('base64') : globalThis?.btoa; +/** @summary btoa function in all environments + * @private */ +btoa_func = isNodeJs() ? str => Buffer.from(str, 'latin1').toString('base64') : globalThis?.btoa, -let browser$1 = { isFirefox: true, isSafari: false, isChrome: false, isWin: false, touches: false }; +/** @summary browser detection flags + * @private */ +browser = { isFirefox: true, isSafari: false, isChrome: false, isWin: false, touches: false, screenWidth: 1200 }; if ((typeof document !== 'undefined') && (typeof window !== 'undefined') && (typeof navigator !== 'undefined')) { - browser$1.isFirefox = (navigator.userAgent.indexOf('Firefox') >= 0) || (typeof InstallTrigger !== 'undefined'); - browser$1.isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; - browser$1.isChrome = !!window.chrome; - browser$1.isChromeHeadless = navigator.userAgent.indexOf('HeadlessChrome') >= 0; - browser$1.chromeVersion = (browser$1.isChrome || browser$1.isChromeHeadless) ? parseInt(navigator.userAgent.match(/Chrom(?:e|ium)\/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/)[1]) : 0; - browser$1.isWin = navigator.userAgent.indexOf('Windows') >= 0; - browser$1.touches = ('ontouchend' in document); // identify if touch events are supported + browser.isFirefox = navigator.userAgent.indexOf('Firefox') >= 0; + browser.isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; + browser.isChrome = !!window.chrome; + browser.isChromeHeadless = navigator.userAgent.indexOf('HeadlessChrome') >= 0; + browser.chromeVersion = (browser.isChrome || browser.isChromeHeadless) ? parseInt(navigator.userAgent.match(/Chrom(?:e|ium)\/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/)[1]) : 0; + browser.isWin = navigator.userAgent.indexOf('Windows') >= 0; + browser.touches = ('ontouchend' in document); // identify if touch events are supported + browser.screenWidth = window.screen?.width ?? 1200; } /** @summary Check if prototype string match to array (typed on untyped) * @return {Number} 0 - not array, 1 - regular array, 2 - typed array * @private */ function isArrayProto(proto) { - if ((proto.length < 14) || (proto.indexOf('[object ') != 0)) return 0; - let p = proto.indexOf('Array]'); - if ((p < 0) || (p != proto.length - 6)) return 0; + if ((proto.length < 14) || (proto.indexOf('[object ') !== 0)) return 0; + const p = proto.indexOf('Array]'); + if ((p < 0) || (p !== proto.length - 6)) return 0; // plain array has only '[object Array]', typed array type name inside - return proto.length == 14 ? 1 : 2; + return proto.length === 14 ? 1 : 2; } /** @desc Specialized JSROOT constants, used in {@link settings} * @namespace */ -let constants$1 = { +const constants$1 = { /** @summary Kind of 3D rendering, used for {@link settings.Render3D} * @namespace */ Render3D: { @@ -98,7 +110,7 @@ let constants$1 = { /** @summary Use SVG rendering, slow, inprecise and not interactive, nor recommendet */ SVG: 3, fromString(s) { - if ((s === 'webgl') || (s == 'gl')) return this.WebGL; + if ((s === 'webgl') || (s === 'gl')) return this.WebGL; if (s === 'img') return this.WebGLImage; if (s === 'svg') return this.SVG; return this.Default; @@ -141,7 +153,7 @@ let constants$1 = { fromString(s) { if (!s || !isStr(s)) return this.Normal; - switch(s){ + switch (s) { case 'off': return this.Off; case 'symbols': return this.Symbols; case 'normal': @@ -155,15 +167,15 @@ let constants$1 = { case 'alwaysmath': case 'alwaysmathjax': return this.AlwaysMathJax; } - let code = parseInt(s); + const code = parseInt(s); return (Number.isInteger(code) && (code >= this.Off) && (code <= this.AlwaysMathJax)) ? code : this.Normal; } } -}; +}, /** @desc Global JSROOT settings * @namespace */ -let settings = { +settings = { /** @summary Render of 3D drawing methods, see {@link constants.Render3D} for possible values */ Render3D: constants$1.Render3D.Default, /** @summary 3D drawing methods in batch mode, see {@link constants.Render3D} for possible values */ @@ -171,33 +183,33 @@ let settings = { /** @summary Way to embed 3D drawing in SVG, see {@link constants.Embed3D} for possible values */ Embed3D: constants$1.Embed3D.Default, /** @summary Enable or disable tooltips, default on */ - Tooltip: true, + Tooltip: !nodejs, /** @summary Time in msec for appearance of tooltips, 0 - no animation */ TooltipAnimation: 500, /** @summary Enables context menu usage */ - ContextMenu: true, + ContextMenu: !nodejs, /** @summary Global zooming flag, enable/disable any kind of interactive zooming */ - Zooming: true, + Zooming: !nodejs, /** @summary Zooming with the mouse events */ - ZoomMouse: true, + ZoomMouse: !nodejs, /** @summary Zooming with mouse wheel */ - ZoomWheel: true, + ZoomWheel: !nodejs, /** @summary Zooming on touch devices */ - ZoomTouch: true, + ZoomTouch: !nodejs, /** @summary Enables move and resize of elements like statbox, title, pave, colz */ - MoveResize: true, + MoveResize: !browser.touches && !nodejs, /** @summary Configures keybord key press handling * @desc Can be disabled to prevent keys heandling in complex HTML layouts * @default true */ - HandleKeys: true, + HandleKeys: !nodejs, /** @summary enables drag and drop functionality */ - DragAndDrop: true, + DragAndDrop: !nodejs, /** @summary Interactive dragging of TGraph points */ DragGraphs: true, /** @summary Show progress box */ - ProgressBox: true, + ProgressBox: !nodejs, /** @summary Show additional tool buttons on the canvas, false - disabled, true - enabled, 'popup' - only toggle button */ - ToolBar: 'popup', + ToolBar: nodejs ? false : 'popup', /** @summary Position of toolbar 'left' left-bottom corner on canvas, 'right' - right-bottom corner on canvas, opposite on sub-pads */ ToolBarSide: 'left', /** @summary display tool bar vertical (default false) */ @@ -212,8 +224,9 @@ let settings = { OptimizeDraw: 1, /** @summary Automatically create stats box, default on */ AutoStat: true, - /** @summary Default frame position in NFC */ - FrameNDC: { fX1NDC: 0.07, fY1NDC: 0.12, fX2NDC: 0.95, fY2NDC: 0.88 }, + /** @summary Default frame position in NFC + * @deprecated Use gStyle.fPad[Left/Right/Top/Bottom]Margin values instead */ + FrameNDC: {}, /** @summary size of pad, where many features will be deactivated like text draw or zooming */ SmallPad: { width: 150, height: 100 }, /** @summary Default color palette id */ @@ -242,12 +255,15 @@ let settings = { /** @summary Tweak browser caching with stamp URL parameter * @desc When specified, extra URL parameter like ```?stamp=unique_value``` append to each files loaded * In such case browser will be forced to load file content disregards of server cache settings + * Can be disabled by providing &usestamp=false in URL or via Settings/Files sub-menu * @default true */ UseStamp: true, /** @summary Maximal number of bytes ranges in http 'Range' header * @desc Some http server has limitations for number of bytes rannges therefore let change maximal number via setting * @default 200 */ MaxRanges: 200, + /** @summary Configure xhr.withCredentials = true when submitting http requests from JSROOT */ + WithCredentials: false, /** @summary Skip streamer infos from the GUI */ SkipStreamerInfos: false, /** @summary Show only last cycle for objects in TFile */ @@ -255,20 +271,19 @@ let settings = { /** @summary Configures dark mode for the GUI */ DarkMode: false, /** @summary Prefer to use saved points in TF1/TF2, avoids eval() and Function() when possible */ - PreferSavedPoints: false -}; - - -if (nodejs) - Object.assign(settings, { ToolBar: false, Tooltip: 0, ContextMenu: false, Zooming: false, MoveResize: false, DragAndDrop: false, ProgressBox: false }); - + PreferSavedPoints: false, + /** @summary Angle in degree for axis labels tilt when available space is not enough */ + AxisTiltAngle: 25, + /** @summary Strip axis labels trailing 0 or replace 10^0 by 1 */ + StripAxisLabels: true +}, /** @namespace * @summary Insiance of TStyle object like in ROOT * @desc Includes default draw styles, can be changed after loading of JSRoot.core.js * or can be load from the file providing style=itemname in the URL * See [TStyle docu]{@link https://root.cern/doc/master/classTStyle.html} 'Private attributes' section for more detailed info about each value */ -let gStyle = { +gStyle = { fName: 'Modern', /** @summary Default log x scale */ fOptLogx: 0, @@ -296,6 +311,10 @@ let gStyle = { fPadGridY: false, fPadTickX: 0, fPadTickY: 0, + fPadBorderSize: 2, + fPadBorderMode: 0, + fCanvasBorderSize: 2, + fCanvasBorderMode: 0, /** @summary fill color for stat box */ fStatColor: 0, /** @summary fill style for stat box */ @@ -366,7 +385,19 @@ let gStyle = { fLegendTextSize: 0, fLegendFillColor: 0, fHatchesLineWidth: 1, - fHatchesSpacing: 1 + fHatchesSpacing: 1, + fCandleWhiskerRange: 1.0, + fCandleBoxRange: 0.5, + fCandleScaled: false, + fViolinScaled: true, + fOrthoCamera: false, + fXAxisExpXOffset: 0, + fXAxisExpYOffset: 0, + fYAxisExpXOffset: 0, + fYAxisExpYOffset: 0, + fAxisMaxDigits: 5, + fStripDecimals: true, + fBarWidth: 1 }; /** @summary Method returns current document in use @@ -376,7 +407,7 @@ function getDocument() { return internals.nodejs_document; if (typeof document !== 'undefined') return document; - if (typeof window == 'object') + if (typeof window === 'object') return window.document; return undefined; } @@ -400,21 +431,20 @@ async function injectCode(code) { if (typeof document !== 'undefined') { // check if code already loaded - to avoid duplication - let scripts = document.getElementsByTagName('script'); - for (let n = 0; n < scripts.length; ++n) - if (scripts[n].innerHTML == code) + const scripts = document.getElementsByTagName('script'); + for (let n = 0; n < scripts.length; ++n) { + if (scripts[n].innerHTML === code) return true; + } - let promise = code.indexOf('JSROOT.require') >= 0 ? _ensureJSROOT() : Promise.resolve(true); + const promise = code.indexOf('JSROOT.require') >= 0 ? _ensureJSROOT() : Promise.resolve(true); return promise.then(() => { - return new Promise(resolve => { - let element = document.createElement('script'); - element.setAttribute('type', 'text/javascript'); - element.innerHTML = code; - document.head.appendChild(element); - setTimeout(() => resolve(true), 10); // while onload event not fired, just postpone resolve - }); + const element = document.createElement('script'); + element.setAttribute('type', 'text/javascript'); + element.innerHTML = code; + document.head.appendChild(element); + return postponePromise(true, 10); // while onload event not fired, just postpone resolve }); } @@ -422,7 +452,7 @@ async function injectCode(code) { } /** @summary Load script or CSS file into the browser - * @param {String} url - script or css file URL (or array, in this case they all loaded secuentially) + * @param {String} url - script or css file URL (or array, in this case they all loaded sequentially) * @return {Promise} */ async function loadScript(url) { if (!url) @@ -432,7 +462,7 @@ async function loadScript(url) { url = url.split(';'); if (!isStr(url)) { - let scripts = url, loadNext = () => { + const scripts = url, loadNext = () => { if (!scripts.length) return true; return loadScript(scripts.shift()).then(loadNext, loadNext); }; @@ -441,43 +471,48 @@ async function loadScript(url) { if (url.indexOf('$$$') === 0) { url = url.slice(3); - if ((url.indexOf('style/') == 0) && (url.indexOf('.css') < 0)) + if ((url.indexOf('style/') === 0) && (url.indexOf('.css') < 0)) url += '.css'; url = exports.source_dir + url; } - let element, isstyle = url.indexOf('.css') > 0; + const isstyle = url.indexOf('.css') > 0; if (nodejs) { if (isstyle) return null; - if ((url.indexOf('http:') == 0) || (url.indexOf('https:') == 0)) + if ((url.indexOf('http:') === 0) || (url.indexOf('https:') === 0)) return httpRequest(url, 'text').then(code => injectCode(code)); + // local files, read and use it + if (url.indexOf('./') === 0) + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(fs => injectCode(fs.readFileSync(url))); + return import(/* webpackIgnore: true */ url); } const match_url = src => { - if (src == url) return true; - let indx = src.indexOf(url); - return (indx > 0) && (indx + url.length == src.length) && (src[indx-1] == '/'); + if (src === url) return true; + const indx = src.indexOf(url); + return (indx > 0) && (indx + url.length === src.length) && (src[indx-1] === '/'); }; if (isstyle) { - let styles = document.getElementsByTagName('link'); + const styles = document.getElementsByTagName('link'); for (let n = 0; n < styles.length; ++n) { if (!styles[n].href || (styles[n].type !== 'text/css') || (styles[n].rel !== 'stylesheet')) continue; if (match_url(styles[n].href)) return true; } - } else { - let scripts = document.getElementsByTagName('script'); - for (let n = 0; n < scripts.length; ++n) + const scripts = document.getElementsByTagName('script'); + for (let n = 0; n < scripts.length; ++n) { if (match_url(scripts[n].src)) return true; + } } + let element; if (isstyle) { element = document.createElement('link'); element.setAttribute('rel', 'stylesheet'); @@ -508,32 +543,28 @@ function BIT(n) { return 1 << n; } function clone(src, map, nofunc) { if (!src) return null; - if (!map) { - map = { obj: [], clones: [], nofunc: nofunc }; - } else { + if (!map) + map = { obj: [], clones: [], nofunc }; + else { const i = map.obj.indexOf(src); if (i >= 0) return map.clones[i]; } - let arr_kind = isArrayProto(Object.prototype.toString.apply(src)); + const arr_kind = isArrayProto(Object.prototype.toString.apply(src)); // process normal array - if (arr_kind == 1) { - let tgt = []; + if (arr_kind === 1) { + const tgt = []; map.obj.push(src); map.clones.push(tgt); for (let i = 0; i < src.length; ++i) - if (isObject(src[i])) - tgt.push(clone(src[i], map)); - else - tgt.push(src[i]); - + tgt.push(isObject(src[i]) ? clone(src[i], map) : src[i]); return tgt; } // process typed array - if (arr_kind == 2) { - let tgt = []; + if (arr_kind === 2) { + const tgt = []; map.obj.push(src); map.clones.push(tgt); for (let i = 0; i < src.length; ++i) @@ -542,11 +573,11 @@ function clone(src, map, nofunc) { return tgt; } - let tgt = {}; + const tgt = {}; map.obj.push(src); map.clones.push(tgt); - for (let k in src) { + for (const k in src) { if (isObject(src[k])) tgt[k] = clone(src[k], map); else if (!map.nofunc || !isFunc(src[k])) @@ -573,18 +604,17 @@ function addMethods(obj, typename) { * @param {object|string} json object where references will be replaced * @return {object} parsed object */ function parse(json) { - if (!json) return null; - let obj = isStr(json) ? JSON.parse(json) : json, - map = [], newfmt = undefined; + const obj = isStr(json) ? JSON.parse(json) : json, map = []; + let newfmt; const unref_value = value => { if ((value === null) || (value === undefined)) return; if (isStr(value)) { if (newfmt || (value.length < 6) || (value.indexOf('$ref:') !== 0)) return; - let ref = parseInt(value.slice(5)); + const ref = parseInt(value.slice(5)); if (!Number.isInteger(ref) || (ref < 0) || (ref >= map.length)) return; newfmt = false; return map[ref]; @@ -592,21 +622,21 @@ function parse(json) { if (typeof value !== 'object') return; - let proto = Object.prototype.toString.apply(value); + const proto = Object.prototype.toString.apply(value); // scan array - it can contain other objects if (isArrayProto(proto) > 0) { for (let i = 0; i < value.length; ++i) { - let res = unref_value(value[i]); + const res = unref_value(value[i]); if (res !== undefined) value[i] = res; } return; } - let ks = Object.keys(value), len = ks.length; + const ks = Object.keys(value), len = ks.length; if ((newfmt !== false) && (len === 1) && (ks[0] === '$ref')) { - const ref = parseInt(value['$ref']); + const ref = parseInt(value.$ref); if (!Number.isInteger(ref) || (ref < 0) || (ref >= map.length)) return; newfmt = true; return map[ref]; @@ -633,29 +663,27 @@ function parse(json) { if (value.b !== undefined) { // base64 coding - - let buf = atob_func(value.b); - + const buf = atob_func(value.b); if (arr.buffer) { - let dv = new DataView(arr.buffer, value.o || 0), - len = Math.min(buf.length, dv.byteLength); + const dv = new DataView(arr.buffer, value.o || 0), + len = Math.min(buf.length, dv.byteLength); for (let k = 0; k < len; ++k) dv.setUint8(k, buf.charCodeAt(k)); - } else { + } else throw new Error('base64 coding supported only for native arrays with binary data'); - } } else { // compressed coding let nkey = 2, p = 0; while (nkey < len) { - if (ks[nkey][0] == 'p') p = value[ks[nkey++]]; // position + if (ks[nkey][0] === 'p') p = value[ks[nkey++]]; // position if (ks[nkey][0] !== 'v') throw new Error(`Unexpected member ${ks[nkey]} in array decoding`); - let v = value[ks[nkey++]]; // value + const v = value[ks[nkey++]]; // value if (typeof v === 'object') { - for (let k = 0; k < v.length; ++k) arr[p++] = v[k]; + for (let k = 0; k < v.length; ++k) + arr[p++] = v[k]; } else { arr[p++] = v; - if ((nkey < len) && (ks[nkey][0] == 'n')) { + if ((nkey < len) && (ks[nkey][0] === 'n')) { let cnt = value[ks[nkey++]]; // counter while (--cnt) arr[p++] = v; } @@ -668,12 +696,12 @@ function parse(json) { if ((newfmt !== false) && (len === 3) && (ks[0] === '$pair') && (ks[1] === 'first') && (ks[2] === 'second')) { newfmt = true; - let f1 = unref_value(value.first), - s1 = unref_value(value.second); + const f1 = unref_value(value.first), + s1 = unref_value(value.second); if (f1 !== undefined) value.first = f1; if (s1 !== undefined) value.second = s1; - value._typename = value['$pair']; - delete value['$pair']; + value._typename = value.$pair; + delete value.$pair; return; // pair object is not counted in the objects map } @@ -687,8 +715,7 @@ function parse(json) { if (value._typename) addMethods(value); for (let k = 0; k < len; ++k) { - const i = ks[k], - res = unref_value(value[i]); + const i = ks[k], res = unref_value(value[i]); if (res !== undefined) value[i] = res; } }; @@ -704,44 +731,50 @@ function parse(json) { * @return {Array} array of parsed elements */ function parseMulti(json) { if (!json) return null; - let arr = JSON.parse(json); - if (arr && arr.length) + const arr = JSON.parse(json); + if (arr?.length) { for (let i = 0; i < arr.length; ++i) arr[i] = parse(arr[i]); + } return arr; } /** @summary Method converts JavaScript object into ROOT-like JSON - * @desc Produced JSON can be used in parse() again - * When performed properly, JSON can be used in [TBufferJSON::fromJSON()]{@link https://root.cern/doc/master/classTBufferJSON.html#a2ecf0daacdad801e60b8093a404c897d} method to read data back with C++ + * @desc When performed properly, JSON can be used in [TBufferJSON::fromJSON()]{@link https://root.cern/doc/master/classTBufferJSON.html#a2ecf0daacdad801e60b8093a404c897d} method to read data back with C++ + * Or one can again parse json with {@link parse} function * @param {object} obj - JavaScript object to convert * @param {number} [spacing] - optional line spacing in JSON - * @return {string} produced JSON code */ + * @return {string} produced JSON code + * @example + * import { openFile, draw, toJSON } from 'https://root.cern/js/latest/modules/main.mjs'; + * let file = await openFile('https://root.cern/js/files/hsimple.root'); + * let obj = await file.readObject('hpxpy;1'); + * obj.fTitle = 'New histogram title'; + * let json = toJSON(obj); */ function toJSON(obj, spacing) { if (!isObject(obj)) return ''; - let map = []; // map of stored objects - - const copy_value = value => { + const map = [], // map of stored objects + copy_value = value => { if (isFunc(value)) return undefined; if ((value === undefined) || (value === null) || !isObject(value)) return value; // typed array need to be converted into normal array, otherwise looks strange if (isArrayProto(Object.prototype.toString.apply(value)) > 0) { - let arr = new Array(value.length); + const arr = new Array(value.length); for (let i = 0; i < value.length; ++i) arr[i] = copy_value(value[i]); return arr; } // this is how reference is code - let refid = map.indexOf(value); + const refid = map.indexOf(value); if (refid >= 0) return { $ref: refid }; - let ks = Object.keys(value), len = ks.length, tgt = {}; + const ks = Object.keys(value), len = ks.length, tgt = {}; - if ((len == 3) && (ks[0] === '$pair') && (ks[1] === 'first') && (ks[2] === 'second')) { + if ((len === 3) && (ks[0] === '$pair') && (ks[1] === 'first') && (ks[2] === 'second')) { // special handling of pair objects which does not included into objects map tgt.$pair = value.$pair; tgt.first = copy_value(value.first); @@ -752,15 +785,14 @@ function toJSON(obj, spacing) { map.push(value); for (let k = 0; k < len; ++k) { - let name = ks[k]; - if (name && (name[0] != '$')) + const name = ks[k]; + if (name && (name[0] !== '$')) tgt[name] = copy_value(value[name]); } return tgt; - }; - - let tgt = copy_value(obj); + }, + tgt = copy_value(obj); return JSON.stringify(tgt, null, spacing); } @@ -770,16 +802,17 @@ function toJSON(obj, spacing) { * @param {string} [url] URL string with options, document.URL will be used when not specified * @return {Object} with ```.has(opt)``` and ```.get(opt,dflt)``` methods * @example + * import { decodeUrl } from 'https://root.cern/js/latest/modules/core.mjs'; * let d = decodeUrl('any?opt1&op2=3'); * console.log(`Has opt1 ${d.has('opt1')}`); // true * console.log(`Get opt1 ${d.get('opt1')}`); // '' * console.log(`Get opt2 ${d.get('opt2')}`); // '3' * console.log(`Get opt3 ${d.get('opt3','-')}`); // '-' */ function decodeUrl(url) { - let res = { + const res = { opts: {}, has(opt) { return this.opts[opt] !== undefined; }, - get(opt,dflt) { let v = this.opts[opt]; return v !== undefined ? v : dflt; } + get(opt, dflt) { const v = this.opts[opt]; return v !== undefined ? v : dflt; } }; if (!url || !isStr(url)) { @@ -788,32 +821,31 @@ function decodeUrl(url) { } res.url = url; - let p1 = url.indexOf('?'); + const p1 = url.indexOf('?'); if (p1 < 0) return res; url = decodeURI(url.slice(p1+1)); while (url) { - // try to correctly handle quotes in the URL let pos = 0, nq = 0, eq = -1, firstq = -1; while ((pos < url.length) && ((nq !== 0) || ((url[pos] !== '&') && (url[pos] !== '#')))) { switch (url[pos]) { - case "'": if (nq >= 0) nq = (nq+1)%2; if (firstq < 0) firstq = pos; break; - case '"': if (nq <= 0) nq = (nq-1)%2; if (firstq < 0) firstq = pos; break; + case '\'': if (nq >= 0) nq = (nq+1) % 2; if (firstq < 0) firstq = pos; break; + case '"': if (nq <= 0) nq = (nq-1) % 2; if (firstq < 0) firstq = pos; break; case '=': if ((firstq < 0) && (eq < 0)) eq = pos; break; } pos++; } - if ((eq < 0) && (firstq < 0)) { - res.opts[url.slice(0,pos)] = ''; - } if (eq > 0) { - let val = url.slice(eq+1, pos); - if (((val[0] === "'") || (val[0] === '"')) && (val[0] === val[val.length-1])) val = val.slice(1, val.length-1); - res.opts[url.slice(0,eq)] = val; + if ((eq < 0) && (firstq < 0)) + res.opts[url.slice(0, pos)] = ''; + else if (eq > 0) { + let val = url.slice(eq + 1, pos); + if (((val[0] === '\'') || (val[0] === '"')) && (val[0] === val[val.length-1])) val = val.slice(1, val.length-1); + res.opts[url.slice(0, eq)] = val; } - if ((pos >= url.length) || (url[pos] == '#')) break; + if ((pos >= url.length) || (url[pos] === '#')) break; url = url.slice(pos+1); } @@ -826,7 +858,8 @@ function decodeUrl(url) { function findFunction(name) { if (isFunc(name)) return name; if (!isStr(name)) return null; - let names = name.split('.'), elem = globalThis; + const names = name.split('.'); + let elem = globalThis; for (let n = 0; elem && (n < names.length); ++n) elem = elem[names[n]]; @@ -834,118 +867,114 @@ function findFunction(name) { return isFunc(elem) ? elem : null; } - -/** @summary Assign methods to request +/** @summary Method to create http request, without promise can be used only in browser environment * @private */ -function setRequestMethods(xhr, url, kind, user_accept_callback, user_reject_callback) { - xhr.http_callback = isFunc(user_accept_callback) ? user_accept_callback.bind(xhr) : function() {}; - xhr.error_callback = isFunc(user_reject_callback) ? user_reject_callback.bind(xhr) : function(err) { console.warn(err.message); this.http_callback(null); }.bind(xhr); +function createHttpRequest(url, kind, user_accept_callback, user_reject_callback, use_promise) { + function configureXhr(xhr) { + xhr.http_callback = isFunc(user_accept_callback) ? user_accept_callback.bind(xhr) : () => {}; + xhr.error_callback = isFunc(user_reject_callback) ? user_reject_callback.bind(xhr) : function(err) { console.warn(err.message); this.http_callback(null); }.bind(xhr); - if (!kind) kind = 'buf'; + if (!kind) kind = 'buf'; - let method = 'GET', is_async = true, p = kind.indexOf(';sync'); - if (p > 0) { kind = kind.slice(0,p); is_async = false; } - switch (kind) { - case 'head': method = 'HEAD'; break; - case 'posttext': method = 'POST'; kind = 'text'; break; - case 'postbuf': method = 'POST'; kind = 'buf'; break; - case 'post': - case 'multi': method = 'POST'; break; - } + let method = 'GET', is_async = true; + const p = kind.indexOf(';sync'); + if (p > 0) { kind = kind.slice(0, p); is_async = false; } + switch (kind) { + case 'head': method = 'HEAD'; break; + case 'posttext': method = 'POST'; kind = 'text'; break; + case 'postbuf': method = 'POST'; kind = 'buf'; break; + case 'post': + case 'multi': method = 'POST'; break; + } - xhr.kind = kind; + xhr.kind = kind; - if (settings.HandleWrongHttpResponse && (method == 'GET') && isFunc(xhr.addEventListener)) - xhr.addEventListener('progress', function(oEvent) { - if (oEvent.lengthComputable && this.expected_size && (oEvent.loaded > this.expected_size)) { - this.did_abort = true; - this.abort(); - this.error_callback(Error(`Server sends more bytes ${oEvent.loaded} than expected ${this.expected_size}. Abort I/O operation`), 598); - } - }.bind(xhr)); + if (settings.WithCredentials) + xhr.withCredentials = true; - xhr.onreadystatechange = function() { + if (settings.HandleWrongHttpResponse && (method === 'GET') && isFunc(xhr.addEventListener)) { + xhr.addEventListener('progress', function(oEvent) { + if (oEvent.lengthComputable && this.expected_size && (oEvent.loaded > this.expected_size)) { + this.did_abort = true; + this.abort(); + this.error_callback(Error(`Server sends more bytes ${oEvent.loaded} than expected ${this.expected_size}. Abort I/O operation`), 598); + } + }.bind(xhr)); + } - if (this.did_abort) return; + xhr.onreadystatechange = function() { + if (this.did_abort) return; - if ((this.readyState === 2) && this.expected_size) { - let len = parseInt(this.getResponseHeader('Content-Length')); - if (Number.isInteger(len) && (len > this.expected_size) && !settings.HandleWrongHttpResponse) { - this.did_abort = true; - this.abort(); - return this.error_callback(Error(`Server response size ${len} larger than expected ${this.expected_size}. Abort I/O operation`), 599); + if ((this.readyState === 2) && this.expected_size) { + const len = parseInt(this.getResponseHeader('Content-Length')); + if (Number.isInteger(len) && (len > this.expected_size) && !settings.HandleWrongHttpResponse) { + this.did_abort = true; + this.abort(); + return this.error_callback(Error(`Server response size ${len} larger than expected ${this.expected_size}. Abort I/O operation`), 599); + } } - } - - if (this.readyState != 4) return; - if ((this.status != 200) && (this.status != 206) && !browser$1.qt5 && - // in these special cases browsers not always set status - !((this.status == 0) && ((url.indexOf('file://') == 0) || (url.indexOf('blob:') == 0)))) { - return this.error_callback(Error(`Fail to load url ${url}`), this.status); - } + if (this.readyState !== 4) return; - if (this.nodejs_checkzip && (this.getResponseHeader('content-encoding') == 'gzip')) - // special handling of gzipped JSON objects in Node.js - return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(handle => { - let res = handle.unzipSync(Buffer.from(this.response)), - obj = JSON.parse(res); // zlib returns Buffer, use JSON to parse it - return this.http_callback(parse(obj)); - }); + if ((this.status !== 200) && (this.status !== 206) && !browser.qt5 && + // in these special cases browsers not always set status + !((this.status === 0) && ((url.indexOf('file://') === 0) || (url.indexOf('blob:') === 0)))) + return this.error_callback(Error(`Fail to load url ${url}`), this.status); - switch(this.kind) { - case 'xml': return this.http_callback(this.responseXML); - case 'text': return this.http_callback(this.responseText); - case 'object': return this.http_callback(parse(this.responseText)); - case 'multi': return this.http_callback(parseMulti(this.responseText)); - case 'head': return this.http_callback(this); - } + if (this.nodejs_checkzip && (this.getResponseHeader('content-encoding') === 'gzip')) { + // special handling of gzipped JSON objects in Node.js + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(handle => { + const res = handle.unzipSync(Buffer.from(this.response)), + obj = JSON.parse(res); // zlib returns Buffer, use JSON to parse it + return this.http_callback(parse(obj)); + }); + } - // if no response type is supported, return as text (most probably, will fail) - if (this.responseType === undefined) - return this.http_callback(this.responseText); + switch (this.kind) { + case 'xml': return this.http_callback(this.responseXML); + case 'text': return this.http_callback(this.responseText); + case 'object': return this.http_callback(parse(this.responseText)); + case 'multi': return this.http_callback(parseMulti(this.responseText)); + case 'head': return this.http_callback(this); + } - if ((this.kind == 'bin') && ('byteLength' in this.response)) { - // if string representation in requested - provide it + // if no response type is supported, return as text (most probably, will fail) + if (this.responseType === undefined) + return this.http_callback(this.responseText); - let filecontent = '', u8Arr = new Uint8Array(this.response); - for (let i = 0; i < u8Arr.length; ++i) - filecontent += String.fromCharCode(u8Arr[i]); + if ((this.kind === 'bin') && ('byteLength' in this.response)) { + // if string representation in requested - provide it + const u8Arr = new Uint8Array(this.response); + let filecontent = ''; + for (let i = 0; i < u8Arr.length; ++i) + filecontent += String.fromCharCode(u8Arr[i]); + return this.http_callback(filecontent); + } - return this.http_callback(filecontent); - } + this.http_callback(this.response); + }; - this.http_callback(this.response); - }; + xhr.open(method, url, is_async); - xhr.open(method, url, is_async); + if ((kind === 'bin') || (kind === 'buf')) + xhr.responseType = 'arraybuffer'; - if ((kind == 'bin') || (kind == 'buf')) - xhr.responseType = 'arraybuffer'; + if (nodejs && (method === 'GET') && (kind === 'object') && (url.indexOf('.json.gz') > 0)) { + xhr.nodejs_checkzip = true; + xhr.responseType = 'arraybuffer'; + } - if (nodejs && (method == 'GET') && (kind === 'object') && (url.indexOf('.json.gz') > 0)) { - xhr.nodejs_checkzip = true; - xhr.responseType = 'arraybuffer'; + return xhr; } - return xhr; -} - -/** @summary Method to create http request, without promise can be used only in browser environment - * @private */ -function createHttpRequest(url, kind, user_accept_callback, user_reject_callback, use_promise) { if (isNodeJs()) { if (!use_promise) - throw Error('Not allowed to create http requests in node without promise'); - return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(h => { - let xhr = new h.default(); - setRequestMethods(xhr, url, kind, user_accept_callback, user_reject_callback); - return xhr; - }); + throw Error('Not allowed to create http requests in node.js without promise'); + // eslint-disable-next-line new-cap + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(h => configureXhr(new h.default())); } - let xhr = new XMLHttpRequest(); - setRequestMethods(xhr, url, kind, user_accept_callback, user_reject_callback); + const xhr = configureXhr(new XMLHttpRequest()); return use_promise ? Promise.resolve(xhr) : xhr; } @@ -965,43 +994,49 @@ function createHttpRequest(url, kind, user_accept_callback, user_reject_callback * @param {string} [post_data] - data submitted with post kind of request * @return {Promise} Promise for requested data, result type depends from the kind * @example + * import { httpRequest } from 'https://root.cern/js/latest/modules/core.mjs'; * httpRequest('https://root.cern/js/files/thstack.json.gz', 'object') * .then(obj => console.log(`Get object of type ${obj._typename}`)) * .catch(err => console.error(err.message)); */ async function httpRequest(url, kind, post_data) { - return new Promise((accept, reject) => { - createHttpRequest(url, kind, accept, reject, true).then(xhr => xhr.send(post_data || null)); + return new Promise((resolve, reject) => { + createHttpRequest(url, kind, resolve, reject, true).then(xhr => xhr.send(post_data || null)); }); } -const clTObject = 'TObject', clTNamed = 'TNamed', - clTString = 'TString', clTObjString = 'TObjString', +const prROOT = 'ROOT.', clTObject = 'TObject', clTNamed = 'TNamed', clTString = 'TString', clTObjString = 'TObjString', + clTKey = 'TKey', clTFile = 'TFile', clTList = 'TList', clTHashList = 'THashList', clTMap = 'TMap', clTObjArray = 'TObjArray', clTClonesArray = 'TClonesArray', clTAttLine = 'TAttLine', clTAttFill = 'TAttFill', clTAttMarker = 'TAttMarker', clTAttText = 'TAttText', clTHStack = 'THStack', clTGraph = 'TGraph', clTMultiGraph = 'TMultiGraph', clTCutG = 'TCutG', - clTGraphPolargram = 'TGraphPolargram', clTGraphTime = 'TGraphTime', - clTPave = 'TPave', clTPaveText = 'TPaveText', clTPaveStats = 'TPaveStats', - clTLegend = 'TLegend', clTLegendEntry = 'TLegendEntry', clTPaletteAxis = 'TPaletteAxis', - clTText = 'TText', clTLatex = 'TLatex', clTMathText = 'TMathText', + clTGraph2DErrors = 'TGraph2DErrors', clTGraph2DAsymmErrors = 'TGraph2DAsymmErrors', + clTGraphPolar = 'TGraphPolar', clTGraphPolargram = 'TGraphPolargram', clTGraphTime = 'TGraphTime', + clTPave = 'TPave', clTPaveText = 'TPaveText', clTPaveStats = 'TPaveStats', clTPavesText = 'TPavesText', + clTPaveLabel = 'TPaveLabel', clTPaveClass = 'TPaveClass', clTDiamond = 'TDiamond', + clTLegend = 'TLegend', clTLegendEntry = 'TLegendEntry', + clTPaletteAxis = 'TPaletteAxis', clTImagePalette = 'TImagePalette', + clTText = 'TText', clTLatex = 'TLatex', clTMathText = 'TMathText', clTAnnotation = 'TAnnotation', clTColor = 'TColor', clTLine = 'TLine', clTBox = 'TBox', clTPolyLine = 'TPolyLine', clTPolyLine3D = 'TPolyLine3D', clTPolyMarker3D = 'TPolyMarker3D', clTAttPad = 'TAttPad', clTPad = 'TPad', clTCanvas = 'TCanvas', clTAttCanvas = 'TAttCanvas', clTGaxis = 'TGaxis', clTAttAxis = 'TAttAxis', clTAxis = 'TAxis', clTStyle = 'TStyle', - clTH1 = 'TH1', clTH2 = 'TH2', clTH3 = 'TH3', clTF1 = 'TF1', clTF2 = 'TF2', clTProfile = 'TProfile', clTProfile2D = 'TProfile2D', + clTH1 = 'TH1', clTH1I = 'TH1I', clTH1D = 'TH1D', clTH2 = 'TH2', clTH2I = 'TH2I', clTH2F = 'TH2F', clTH3 = 'TH3', + clTF1 = 'TF1', clTF2 = 'TF2', clTProfile = 'TProfile', clTProfile2D = 'TProfile2D', clTProfile3D = 'TProfile3D', clTGeoVolume = 'TGeoVolume', clTGeoNode = 'TGeoNode', clTGeoNodeMatrix = 'TGeoNodeMatrix', - kNoZoom = -1111; + nsREX = 'ROOT::Experimental::', + kNoZoom = -1111, kNoStats = BIT(9), kInspect = 'inspect'; /** @summary Create some ROOT classes * @desc Supported classes: `TObject`, `TNamed`, `TList`, `TAxis`, `TLine`, `TText`, `TLatex`, `TPad`, `TCanvas` * @param {string} typename - ROOT class name * @example - * import { create } from 'path_to_jsroot/modules/core.mjs'; + * import { create } from 'https://root.cern/js/latest/modules/core.mjs'; * let obj = create('TNamed'); * obj.fName = 'name'; * obj.fTitle = 'title'; */ function create$1(typename, target) { - let obj = target || {}; + const obj = target || {}; switch (typename) { case clTObject: @@ -1022,7 +1057,7 @@ function create$1(typename, target) { case clTAxis: create$1(clTNamed, obj); create$1(clTAttAxis, obj); - extend$1(obj, { fNbins: 1, fXmin: 0, fXmax: 1, fXbins : [], fFirst: 0, fLast: 0, + extend$1(obj, { fNbins: 1, fXmin: 0, fXmax: 1, fXbins: [], fFirst: 0, fLast: 0, fBits2: 0, fTimeDisplay: false, fTimeFormat: '', fLabels: null, fModLabs: null }); break; case clTAttLine: @@ -1032,7 +1067,7 @@ function create$1(typename, target) { extend$1(obj, { fFillColor: 0, fFillStyle: 0 }); break; case clTAttMarker: - extend$1(obj, { fMarkerColor: 1, fMarkerStyle: 1, fMarkerSize: 1. }); + extend$1(obj, { fMarkerColor: 1, fMarkerStyle: 1, fMarkerSize: 1 }); break; case clTLine: create$1(clTObject, obj); @@ -1047,12 +1082,12 @@ function create$1(typename, target) { break; case clTPave: create$1(clTBox, obj); - extend$1(obj, { fX1NDC : 0., fY1NDC: 0, fX2NDC: 1, fY2NDC: 1, + extend$1(obj, { fX1NDC: 0, fY1NDC: 0, fX2NDC: 1, fY2NDC: 1, fBorderSize: 0, fInit: 1, fShadowColor: 1, fCornerRadius: 0, fOption: 'brNDC', fName: 'title' }); break; case clTAttText: - extend$1(obj, { fTextAngle: 0, fTextSize: 0, fTextAlign: 22, fTextColor: 1, fTextFont: 42}); + extend$1(obj, { fTextAngle: 0, fTextSize: 0, fTextAlign: 22, fTextColor: 1, fTextFont: 42 }); break; case clTPaveText: create$1(clTPave, obj); @@ -1082,7 +1117,7 @@ function create$1(typename, target) { create$1(clTAttLine, obj); create$1(clTAttFill, obj); create$1(clTAttMarker, obj); - extend$1(obj, { fLabel: '', fObject: null, fOption: '' }); + extend$1(obj, { fLabel: '', fObject: null, fOption: '', fTextAlign: 0, fTextColor: 0, fTextFont: 0 }); break; case clTText: create$1(clTNamed, obj); @@ -1107,16 +1142,16 @@ function create$1(typename, target) { fXaxis: create$1(clTAxis), fYaxis: create$1(clTAxis), fZaxis: create$1(clTAxis), fFillColor: gStyle.fHistFillColor, fFillStyle: gStyle.fHistFillStyle, fLineColor: gStyle.fHistLineColor, fLineStyle: gStyle.fHistLineStyle, fLineWidth: gStyle.fHistLineWidth, - fBarOffset: 0, fBarWidth: 1000, fEntries: 0., - fTsumw: 0., fTsumw2: 0., fTsumwx: 0., fTsumwx2: 0., - fMaximum: kNoZoom, fMinimum: kNoZoom, fNormFactor: 0., fContour: [], + fBarOffset: 0, fBarWidth: 1000, fEntries: 0, + fTsumw: 0, fTsumw2: 0, fTsumwx: 0, fTsumwx2: 0, + fMaximum: kNoZoom, fMinimum: kNoZoom, fNormFactor: 0, fContour: [], fSumw2: [], fOption: '', fFunctions: create$1(clTList), fBufferSize: 0, fBuffer: [], fBinStatErrOpt: 0, fStatOverflows: 2 }); break; - case 'TH1I': + case clTH1I: + case clTH1D: case 'TH1L64': case 'TH1F': - case 'TH1D': case 'TH1S': case 'TH1C': create$1(clTH1, obj); @@ -1124,11 +1159,11 @@ function create$1(typename, target) { break; case clTH2: create$1(clTH1, obj); - extend$1(obj, { fScalefactor: 1., fTsumwy: 0., fTsumwy2: 0, fTsumwxy: 0 }); + extend$1(obj, { fScalefactor: 1, fTsumwy: 0, fTsumwy2: 0, fTsumwxy: 0 }); break; - case 'TH2I': + case clTH2I: case 'TH2L64': - case 'TH2F': + case clTH2F: case 'TH2D': case 'TH2S': case 'TH2C': @@ -1137,7 +1172,7 @@ function create$1(typename, target) { break; case clTH3: create$1(clTH1, obj); - extend$1(obj, { fTsumwy: 0., fTsumwy2: 0, fTsumwz: 0., fTsumwz2: 0, fTsumwxy: 0, fTsumwxz: 0, fTsumwyz: 0 }); + extend$1(obj, { fTsumwy: 0, fTsumwy2: 0, fTsumwz: 0, fTsumwz2: 0, fTsumwxy: 0, fTsumwxz: 0, fTsumwyz: 0 }); break; case 'TH3I': case 'TH3L64': @@ -1162,7 +1197,7 @@ function create$1(typename, target) { break; case 'TGraphAsymmErrors': create$1(clTGraph, obj); - extend$1(obj, { fEXlow: [], fEXhigh: [], fEYlow: [], fEYhigh: []}); + extend$1(obj, { fEXlow: [], fEXhigh: [], fEYlow: [], fEYhigh: [] }); break; case clTMultiGraph: create$1(clTNamed, obj); @@ -1223,13 +1258,12 @@ function create$1(typename, target) { fUxmin: 0, fUymin: 0, fUxmax: 0, fUymax: 0, fTheta: 30, fPhi: 30, fAspectRatio: 0, fNumber: 0, fLogx: gStyle.fOptLogx, fLogy: gStyle.fOptLogy, fLogz: gStyle.fOptLogz, fTickx: gStyle.fPadTickX, fTicky: gStyle.fPadTickY, - fPadPaint: 0, fCrosshair: 0, fCrosshairPos: 0, fBorderSize: 2, - fBorderMode: 0, fModified: false, + fPadPaint: 0, fCrosshair: 0, fCrosshairPos: 0, fBorderSize: gStyle.fPadBorderSize, + fBorderMode: gStyle.fPadBorderMode, fModified: false, fGridx: gStyle.fPadGridX, fGridy: gStyle.fPadGridY, fAbsCoord: false, fEditable: true, fFixedAspectRatio: false, fPrimitives: create$1(clTList), fExecs: null, fName: 'pad', fTitle: 'canvas' }); - break; case clTAttCanvas: extend$1(obj, { fXBetween: 2, fYBetween: 2, fTitleFromTop: 1.2, @@ -1242,6 +1276,7 @@ function create$1(typename, target) { fDoubleBuffer: 0, fRetained: true, fXsizeUser: 0, fYsizeUser: 0, fXsizeReal: 20, fYsizeReal: 10, fWindowTopX: 0, fWindowTopY: 0, fWindowWidth: 0, fWindowHeight: 0, + fBorderSize: gStyle.fCanvasBorderSize, fBorderMode: gStyle.fCanvasBorderMode, fCw: 500, fCh: 300, fCatt: create$1(clTAttCanvas), kMoveOpaque: true, kResizeOpaque: true, fHighLightColor: 5, fBatch: true, kShowEventStatus: false, kAutoExec: true, kMenuBar: true }); @@ -1290,6 +1325,7 @@ function create$1(typename, target) { * @param {number} [nbinsz] - number of bins on Z-axis (for 3D histograms) * @return {Object} created histogram object * @example + * import { createHistogram } from 'https://root.cern/js/latest/modules/core.mjs'; * let h1 = createHistogram('TH1I', 20); * h1.fName = 'Hist1'; * h1.fTitle = 'Histogram title'; @@ -1297,7 +1333,7 @@ function create$1(typename, target) { * h1.fYaxis.fTitle = 'yaxis'; * h1.fXaxis.fLabelSize = 0.02; */ function createHistogram(typename, nbinsx, nbinsy, nbinsz) { - let histo = create$1(typename); + const histo = create$1(typename); if (!histo.fXaxis || !histo.fYaxis || !histo.fZaxis) return null; histo.fName = 'hist'; histo.fTitle = 'title'; if (nbinsx) extend$1(histo.fXaxis, { fNbins: nbinsx, fXmin: 0, fXmax: nbinsx }); @@ -1323,11 +1359,28 @@ function createHistogram(typename, nbinsx, nbinsy, nbinsz) { return histo; } +/** @summary Set histogram title + * @desc Title may include axes titles, provided with ';' symbol like "Title;x;y;z" */ + +function setHistogramTitle(histo, title) { + if (!histo) return; + if (title.indexOf(';') < 0) + histo.fTitle = title; + else { + const arr = title.split(';'); + histo.fTitle = arr[0]; + if (arr.length > 1) histo.fXaxis.fTitle = arr[1]; + if (arr.length > 2) histo.fYaxis.fTitle = arr[2]; + if (arr.length > 3) histo.fZaxis.fTitle = arr[3]; + } +} + + /** @summary Creates TPolyLine object * @param {number} npoints - number of points * @param {boolean} [use_int32] - use Int32Array type for points, default is Float32Array */ function createTPolyLine(npoints, use_int32) { - let poly = create$1(clTPolyLine); + const poly = create$1(clTPolyLine); if (npoints) { poly.fN = npoints; if (use_int32) { @@ -1346,13 +1399,13 @@ function createTPolyLine(npoints, use_int32) { * @param {array} [xpts] - array with X coordinates * @param {array} [ypts] - array with Y coordinates */ function createTGraph(npoints, xpts, ypts) { - let graph = extend$1(create$1(clTGraph), { fBits: 0x408, fName: 'graph', fTitle: 'title' }); + const graph = extend$1(create$1(clTGraph), { fBits: 0x408, fName: 'graph', fTitle: 'title' }); if (npoints > 0) { graph.fMaxSize = graph.fNpoints = npoints; - const usex = isObject(xpts) && (xpts.length === npoints); - const usey = isObject(ypts) && (ypts.length === npoints); + const usex = isObject(xpts) && (xpts.length === npoints), + usey = isObject(ypts) && (ypts.length === npoints); for (let i = 0; i < npoints; ++i) { graph.fX.push(usex ? xpts[i] : i/npoints); @@ -1366,13 +1419,14 @@ function createTGraph(npoints, xpts, ypts) { /** @summary Creates THStack object * @desc As arguments one could specify any number of histograms objects * @example + * import { createHistogram, createTHStack } from 'https://root.cern/js/latest/modules/core.mjs'; * let nbinsx = 20; * let h1 = createHistogram('TH1F', nbinsx); * let h2 = createHistogram('TH1F', nbinsx); * let h3 = createHistogram('TH1F', nbinsx); * let stack = createTHStack(h1, h2, h3); */ function createTHStack() { - let stack = create$1(clTHStack); + const stack = create$1(clTHStack); for (let i = 0; i < arguments.length; ++i) stack.fHists.Add(arguments[i], ''); return stack; @@ -1381,12 +1435,13 @@ function createTHStack() { /** @summary Creates TMultiGraph object * @desc As arguments one could specify any number of TGraph objects * @example + * import { createTGraph, createTMultiGraph } from 'https://root.cern/js/latest/modules/core.mjs'; * let gr1 = createTGraph(100); * let gr2 = createTGraph(100); * let gr3 = createTGraph(100); * let mgr = createTMultiGraph(gr1, gr2, gr3); */ function createTMultiGraph() { - let mgraph = create$1(clTMultiGraph); + const mgraph = create$1(clTMultiGraph); for (let i = 0; i < arguments.length; ++i) mgraph.fGraphs.Add(arguments[i], ''); return mgraph; @@ -1399,19 +1454,18 @@ const methodsCache = {}; /** @summary Returns methods for given typename * @private */ function getMethods(typename, obj) { - - let m = methodsCache[typename], - has_methods = (m !== undefined); - + let m = methodsCache[typename]; + const has_methods = (m !== undefined); if (!has_methods) m = {}; // Due to binary I/O such TObject methods may not be set for derived classes // Therefore when methods requested for given object, check also that basic methods are there - if ((typename == clTObject) || (typename == clTNamed) || (obj && (obj.fBits !== undefined))) + if ((typename === clTObject) || (typename === clTNamed) || (obj?.fBits !== undefined)) { if (typeof m.TestBit === 'undefined') { - m.TestBit = function (f) { return (this.fBits & f) != 0; }; - m.InvertBit = function (f) { this.fBits = this.fBits ^ (f & 0xffffff); }; + m.TestBit = function(f) { return (this.fBits & f) !== 0; }; + m.InvertBit = function(f) { this.fBits = this.fBits ^ (f & 0xffffff); }; } + } if (has_methods) return m; @@ -1420,11 +1474,11 @@ function getMethods(typename, obj) { this.arr = []; this.opt = []; }; - m.Add = function(obj,opt) { + m.Add = function(obj, opt) { this.arr.push(obj); this.opt.push(isStr(opt) ? opt : ''); }; - m.AddFirst = function(obj,opt) { + m.AddFirst = function(obj, opt) { this.arr.unshift(obj); this.opt.unshift(isStr(opt) ? opt : ''); }; @@ -1436,7 +1490,7 @@ function getMethods(typename, obj) { if ((typename === clTPaveText) || (typename === clTPaveStats)) { m.AddText = function(txt) { - let line = create$1(clTLatex); + const line = create$1(clTLatex); line.fTitle = txt; line.fTextAlign = this.fTextAlign; this.fLines.Add(line); @@ -1446,26 +1500,26 @@ function getMethods(typename, obj) { }; } - if ((typename.indexOf(clTF1) == 0) || (typename === clTF2)) { + if ((typename.indexOf(clTF1) === 0) || (typename === clTF2)) { m.addFormula = function(obj) { if (!obj) return; if (this.formulas === undefined) this.formulas = []; this.formulas.push(obj); }; - m.GetParName = function(n) { - if (this.fParams && this.fParams.fParNames) return this.fParams.fParNames[n]; - if (this.fFormula && this.fFormula.fParams) { - for (let k=0;k=yp) || (y[j]=yp)) { - if (x[i]+(yp-y[i])/(y[j]-y[i])*(x[j]-x[i])= yp) || (y[j] < yp && y[i] >= yp)) { + if (x[i] + (yp - y[i])/(y[j] - y[i])*(x[j] - x[i]) < xp) oddNodes = !oddNodes; - } } - j=i; + j = i; } return oddNodes; }; } - if (typename.indexOf(clTH1) == 0 || typename.indexOf(clTH2) == 0 || typename.indexOf(clTH3) == 0) { + if (typename.indexOf(clTH1) === 0 || typename.indexOf(clTH2) === 0 || typename.indexOf(clTH3) === 0) { m.getBinError = function(bin) { // -*-*-*-*-*Return value of error associated to bin number bin*-*-*-*-* // if the sum of squares of weights has been defined (via Sumw2), @@ -1511,71 +1565,70 @@ function getMethods(typename, obj) { // Set bin content - only trivial case, without expansion this.fEntries++; this.fTsumw = 0; - if ((bin >= 0) && (bin= 0) && (bin < this.fArray.length)) this.fArray[bin] = content; }; } - if (typename.indexOf(clTH1) == 0) { + if (typename.indexOf(clTH1) === 0) { m.getBin = function(x) { return x; }; m.getBinContent = function(bin) { return this.fArray[bin]; }; m.Fill = function(x, weight) { - let axis = this.fXaxis, - bin = 1 + Math.floor((x - axis.fXmin) / (axis.fXmax - axis.fXmin) * axis.fNbins); - if (bin < 0) bin = 0; else - if (bin > axis.fNbins + 1) bin = axis.fNbins + 1; - this.fArray[bin] += (weight === undefined) ? 1 : weight; + const a = this.fXaxis, + bin = Math.max(0, 1 + Math.min(a.fNbins, Math.floor((x - a.fXmin) / (a.fXmax - a.fXmin) * a.fNbins))); + this.fArray[bin] += weight ?? 1; this.fEntries++; }; } - if (typename.indexOf(clTH2) == 0) { + if (typename.indexOf(clTH2) === 0) { m.getBin = function(x, y) { return (x + (this.fXaxis.fNbins+2) * y); }; m.getBinContent = function(x, y) { return this.fArray[this.getBin(x, y)]; }; m.Fill = function(x, y, weight) { - let axis1 = this.fXaxis, axis2 = this.fYaxis, - bin1 = 1 + Math.floor((x - axis1.fXmin) / (axis1.fXmax - axis1.fXmin) * axis1.fNbins), - bin2 = 1 + Math.floor((y - axis2.fXmin) / (axis2.fXmax - axis2.fXmin) * axis2.fNbins); - if (bin1 < 0) bin1 = 0; else - if (bin1 > axis1.fNbins + 1) bin1 = axis1.fNbins + 1; - if (bin2 < 0) bin2 = 0; else - if (bin2 > axis2.fNbins + 1) bin2 = axis2.fNbins + 1; - this.fArray[bin1 + (axis1.fNbins+2)*bin2] += (weight === undefined) ? 1 : weight; + const a1 = this.fXaxis, a2 = this.fYaxis, + bin1 = Math.max(0, 1 + Math.min(a1.fNbins, Math.floor((x - a1.fXmin) / (a1.fXmax - a1.fXmin) * a1.fNbins))), + bin2 = Math.max(0, 1 + Math.min(a2.fNbins, Math.floor((y - a2.fXmin) / (a2.fXmax - a2.fXmin) * a2.fNbins))); + this.fArray[bin1 + (a1.fNbins + 2)*bin2] += weight ?? 1; this.fEntries++; }; } - if (typename.indexOf(clTH3) == 0) { + if (typename.indexOf(clTH3) === 0) { m.getBin = function(x, y, z) { return (x + (this.fXaxis.fNbins+2) * (y + (this.fYaxis.fNbins+2) * z)); }; m.getBinContent = function(x, y, z) { return this.fArray[this.getBin(x, y, z)]; }; m.Fill = function(x, y, z, weight) { - let axis1 = this.fXaxis, axis2 = this.fYaxis, axis3 = this.fZaxis, - bin1 = 1 + Math.floor((x - axis1.fXmin) / (axis1.fXmax - axis1.fXmin) * axis1.fNbins), - bin2 = 1 + Math.floor((y - axis2.fXmin) / (axis2.fXmax - axis2.fXmin) * axis2.fNbins), - bin3 = 1 + Math.floor((z - axis3.fXmin) / (axis3.fXmax - axis3.fXmin) * axis3.fNbins); - if (bin1 < 0) bin1 = 0; else - if (bin1 > axis1.fNbins + 1) bin1 = axis1.fNbins + 1; - if (bin2 < 0) bin2 = 0; else - if (bin2 > axis2.fNbins + 1) bin2 = axis2.fNbins + 1; - if (bin3 < 0) bin3 = 0; else - if (bin3 > axis3.fNbins + 1) bin3 = axis3.fNbins + 1; - this.fArray[bin1 + (axis1.fNbins+2)* (bin2+(axis2.fNbins+2)*bin3)] += (weight === undefined) ? 1 : weight; + const a1 = this.fXaxis, a2 = this.fYaxis, a3 = this.fZaxis, + bin1 = Math.max(0, 1 + Math.min(a1.fNbins, Math.floor((x - a1.fXmin) / (a1.fXmax - a1.fXmin) * a1.fNbins))), + bin2 = Math.max(0, 1 + Math.min(a2.fNbins, Math.floor((y - a2.fXmin) / (a2.fXmax - a2.fXmin) * a2.fNbins))), + bin3 = Math.max(0, 1 + Math.min(a3.fNbins, Math.floor((z - a3.fXmin) / (a3.fXmax - a3.fXmin) * a3.fNbins))); + this.fArray[bin1 + (a1.fNbins + 2) * (bin2 + (a2.fNbins + 2)*bin3)] += weight ?? 1; this.fEntries++; }; } - if (typename.indexOf(clTProfile) == 0) { - if (typename.indexOf(clTProfile2D) == 0) { + if (typename.indexOf(clTProfile) === 0) { + if (typename === clTProfile3D) { + m.getBin = function(x, y, z) { return (x + (this.fXaxis.fNbins+2) * (y + (this.fYaxis.fNbins+2) * z)); }; + m.getBinContent = function(x, y, z) { + const bin = this.getBin(x, y, z); + if (bin < 0 || bin >= this.fNcells || this.fBinEntries[bin] < 1e-300) return 0; + return this.fArray ? this.fArray[bin]/this.fBinEntries[bin] : 0; + }; + m.getBinEntries = function(x, y, z) { + const bin = this.getBin(x, y, z); + return (bin < 0) || (bin >= this.fNcells) ? 0 : this.fBinEntries[bin]; + }; + } else if (typename === clTProfile2D) { m.getBin = function(x, y) { return (x + (this.fXaxis.fNbins+2) * y); }; m.getBinContent = function(x, y) { - let bin = this.getBin(x, y); + const bin = this.getBin(x, y); if (bin < 0 || bin >= this.fNcells) return 0; if (this.fBinEntries[bin] < 1e-300) return 0; if (!this.fArray) return 0; return this.fArray[bin]/this.fBinEntries[bin]; }; m.getBinEntries = function(x, y) { - let bin = this.getBin(x, y); + const bin = this.getBin(x, y); if (bin < 0 || bin >= this.fNcells) return 0; return this.fBinEntries[bin]; }; @@ -1590,29 +1643,28 @@ function getMethods(typename, obj) { } m.getBinEffectiveEntries = function(bin) { if (bin < 0 || bin >= this.fNcells) return 0; - let sumOfWeights = this.fBinEntries[bin]; - if ( !this.fBinSumw2 || this.fBinSumw2.length != this.fNcells) { + const sumOfWeights = this.fBinEntries[bin]; + if (!this.fBinSumw2 || this.fBinSumw2.length !== this.fNcells) // this can happen when reading an old file return sumOfWeights; - } - let sumOfWeightsSquare = this.fBinSumw2[bin]; + const sumOfWeightsSquare = this.fBinSumw2[bin]; return (sumOfWeightsSquare > 0) ? sumOfWeights * sumOfWeights / sumOfWeightsSquare : 0; }; m.getBinError = function(bin) { if (bin < 0 || bin >= this.fNcells) return 0; - let cont = this.fArray[bin], // sum of bin w *y - sum = this.fBinEntries[bin], // sum of bin weights - err2 = this.fSumw2[bin], // sum of bin w * y^2 - neff = this.getBinEffectiveEntries(bin); // (sum of w)^2 / (sum of w^2) + const cont = this.fArray[bin], // sum of bin w *y + sum = this.fBinEntries[bin], // sum of bin weights + err2 = this.fSumw2[bin], // sum of bin w * y^2 + neff = this.getBinEffectiveEntries(bin); // (sum of w)^2 / (sum of w^2) if (sum < 1e-300) return 0; // for empty bins const EErrorType = { kERRORMEAN: 0, kERRORSPREAD: 1, kERRORSPREADI: 2, kERRORSPREADG: 3 }; // case the values y are gaussian distributed y +/- sigma and w = 1/sigma^2 if (this.fErrorMode === EErrorType.kERRORSPREADG) return 1.0/Math.sqrt(sum); // compute variance in y (eprim2) and standard deviation in y (eprim) - let contsum = cont/sum, eprim = Math.sqrt(Math.abs(err2/sum - contsum**2)); + const contsum = cont/sum, eprim = Math.sqrt(Math.abs(err2/sum - contsum**2)); if (this.fErrorMode === EErrorType.kERRORSPREADI) { - if (eprim != 0) return eprim/Math.sqrt(neff); + if (eprim !== 0) return eprim/Math.sqrt(neff); // in case content y is an integer (so each my has an error +/- 1/sqrt(12) // when the std(y) is zero return 1.0/Math.sqrt(12*neff); @@ -1627,7 +1679,7 @@ function getMethods(typename, obj) { }; } - if (typename == clTAxis) { + if (typename === clTAxis) { m.GetBinLowEdge = function(bin) { if (this.fNbins <= 0) return 0; if ((this.fXbins.length > 0) && (bin > 0) && (bin <= this.fNbins)) return this.fXbins[bin-1]; @@ -1673,6 +1725,10 @@ function getMethods(typename, obj) { return m; } +gStyle.fXaxis = create$1(clTAttAxis); +gStyle.fYaxis = create$1(clTAttAxis); +gStyle.fZaxis = create$1(clTAttAxis); + /** @summary Add methods for specified type. * @desc Will be automatically applied when decoding JSON string * @private */ @@ -1690,7 +1746,6 @@ function isRootCollection(lst, typename) { if ((lst.$kind === clTList) || (lst.$kind === clTObjArray)) return true; if (!typename) typename = lst._typename; } - if (!typename) return false; return (typename === clTList) || (typename === clTHashList) || (typename === clTMap) || (typename === clTObjArray) || (typename === clTClonesArray); } @@ -1711,6 +1766,17 @@ function isStr(arg) { return typeof arg === 'string'; } * @private */ function isPromise(obj) { return isObject(obj) && isFunc(obj.then); } +/** @summary Postpone func execution and return result in promise + * @private */ +function postponePromise(func, timeout) { + return new Promise(resolveFunc => { + setTimeout(() => { + const res = isFunc(func) ? func() : func; + resolveFunc(res); + }, timeout); + }); +} + /** @summary Provide promise in any case * @private */ function getPromise(obj) { return isPromise(obj) ? obj : Promise.resolve(obj); } @@ -1718,7 +1784,7 @@ function getPromise(obj) { return isPromise(obj) ? obj : Promise.resolve(obj); } /** @summary Ensure global JSROOT and v6 support methods * @private */ async function _ensureJSROOT() { - let pr = globalThis.JSROOT ? Promise.resolve(true) : loadScript(exports.source_dir + 'scripts/JSRoot.core.js'); + const pr = globalThis.JSROOT ? Promise.resolve(true) : loadScript(exports.source_dir + 'scripts/JSRoot.core.js'); return pr.then(() => { if (globalThis.JSROOT?._complete_loading) @@ -1728,102 +1794,125 @@ async function _ensureJSROOT() { var core = /*#__PURE__*/Object.freeze({ __proto__: null, -version_id: version_id, -version_date: version_date, -version: version, -get source_dir () { return exports.source_dir; }, -isNodeJs: isNodeJs, -isBatchMode: isBatchMode, -setBatchMode: setBatchMode, -browser: browser$1, -internals: internals, -constants: constants$1, -settings: settings, -gStyle: gStyle, +BIT: BIT, +_ensureJSROOT: _ensureJSROOT, +addMethods: addMethods, atob_func: atob_func, +browser: browser, btoa_func: btoa_func, -clTObject: clTObject, -clTNamed: clTNamed, -clTString: clTString, -clTObjString: clTObjString, -clTList: clTList, -clTHashList: clTHashList, -clTMap: clTMap, -clTObjArray: clTObjArray, -clTClonesArray: clTClonesArray, -clTAttLine: clTAttLine, +clTAnnotation: clTAnnotation, +clTAttCanvas: clTAttCanvas, clTAttFill: clTAttFill, +clTAttLine: clTAttLine, clTAttMarker: clTAttMarker, clTAttText: clTAttText, -clTPave: clTPave, -clTPaveText: clTPaveText, -clTPaveStats: clTPaveStats, -clTLegend: clTLegend, -clTLegendEntry: clTLegendEntry, -clTPaletteAxis: clTPaletteAxis, -clTText: clTText, -clTLatex: clTLatex, -clTMathText: clTMathText, -clTMultiGraph: clTMultiGraph, -clTColor: clTColor, -clTLine: clTLine, +clTAxis: clTAxis, clTBox: clTBox, -clTPolyLine: clTPolyLine, -clTPad: clTPad, clTCanvas: clTCanvas, -clTAttCanvas: clTAttCanvas, -clTGaxis: clTGaxis, -clTAxis: clTAxis, -clTStyle: clTStyle, -clTH1: clTH1, -clTH2: clTH2, -clTH3: clTH3, +clTClonesArray: clTClonesArray, +clTColor: clTColor, +clTCutG: clTCutG, +clTDiamond: clTDiamond, clTF1: clTF1, clTF2: clTF2, -clTProfile: clTProfile, -clTProfile2D: clTProfile2D, +clTFile: clTFile, +clTGaxis: clTGaxis, +clTGeoNode: clTGeoNode, +clTGeoNodeMatrix: clTGeoNodeMatrix, +clTGeoVolume: clTGeoVolume, clTGraph: clTGraph, +clTGraph2DAsymmErrors: clTGraph2DAsymmErrors, +clTGraph2DErrors: clTGraph2DErrors, +clTGraphPolar: clTGraphPolar, clTGraphPolargram: clTGraphPolargram, clTGraphTime: clTGraphTime, -clTCutG: clTCutG, +clTH1: clTH1, +clTH1D: clTH1D, +clTH1I: clTH1I, +clTH2: clTH2, +clTH2F: clTH2F, +clTH2I: clTH2I, +clTH3: clTH3, +clTHStack: clTHStack, +clTHashList: clTHashList, +clTImagePalette: clTImagePalette, +clTKey: clTKey, +clTLatex: clTLatex, +clTLegend: clTLegend, +clTLegendEntry: clTLegendEntry, +clTLine: clTLine, +clTList: clTList, +clTMap: clTMap, +clTMathText: clTMathText, +clTMultiGraph: clTMultiGraph, +clTNamed: clTNamed, +clTObjArray: clTObjArray, +clTObjString: clTObjString, +clTObject: clTObject, +clTPad: clTPad, +clTPaletteAxis: clTPaletteAxis, +clTPave: clTPave, +clTPaveClass: clTPaveClass, +clTPaveLabel: clTPaveLabel, +clTPaveStats: clTPaveStats, +clTPaveText: clTPaveText, +clTPavesText: clTPavesText, +clTPolyLine: clTPolyLine, clTPolyLine3D: clTPolyLine3D, clTPolyMarker3D: clTPolyMarker3D, -clTGeoVolume: clTGeoVolume, -clTGeoNode: clTGeoNode, -clTGeoNodeMatrix: clTGeoNodeMatrix, -kNoZoom: kNoZoom, -isArrayProto: isArrayProto, -getDocument: getDocument, -BIT: BIT, +clTProfile: clTProfile, +clTProfile2D: clTProfile2D, +clTProfile3D: clTProfile3D, +clTString: clTString, +clTStyle: clTStyle, +clTText: clTText, clone: clone, -addMethods: addMethods, -parse: parse, -parseMulti: parseMulti, -toJSON: toJSON, -decodeUrl: decodeUrl, -findFunction: findFunction, -createHttpRequest: createHttpRequest, -httpRequest: httpRequest, -loadScript: loadScript, -injectCode: injectCode, +constants: constants$1, create: create$1, createHistogram: createHistogram, -createTPolyLine: createTPolyLine, +createHttpRequest: createHttpRequest, createTGraph: createTGraph, createTHStack: createTHStack, createTMultiGraph: createTMultiGraph, +createTPolyLine: createTPolyLine, +decodeUrl: decodeUrl, +findFunction: findFunction, +gStyle: gStyle, +getDocument: getDocument, getMethods: getMethods, -registerMethods: registerMethods, -isRootCollection: isRootCollection, -isObject: isObject, +getPromise: getPromise, +httpRequest: httpRequest, +injectCode: injectCode, +internals: internals, +isArrayProto: isArrayProto, +isBatchMode: isBatchMode, isFunc: isFunc, -isStr: isStr, +isNodeJs: isNodeJs, +isObject: isObject, isPromise: isPromise, -getPromise: getPromise, -_ensureJSROOT: _ensureJSROOT +isRootCollection: isRootCollection, +isStr: isStr, +kInspect: kInspect, +kNoStats: kNoStats, +kNoZoom: kNoZoom, +loadScript: loadScript, +nsREX: nsREX, +parse: parse, +parseMulti: parseMulti, +postponePromise: postponePromise, +prROOT: prROOT, +registerMethods: registerMethods, +setBatchMode: setBatchMode, +setHistogramTitle: setHistogramTitle, +settings: settings, +get source_dir () { return exports.source_dir; }, +toJSON: toJSON, +version: version, +version_date: version_date, +version_id: version_id }); -// https://d3js.org v7.6.1 Copyright 2010-2021 Mike Bostock +// https://d3js.org v7.8.4 Copyright 2010-2021 Mike Bostock function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; @@ -1836,7 +1925,7 @@ function extend(parent, definition) { return prototype; } -function Color$2() {} +function Color$1() {} var darker = 0.7; var brighter = 1 / darker; @@ -2003,7 +2092,7 @@ var named = { yellowgreen: 0x9acd32 }; -define(Color$2, color$1, { +define(Color$1, color, { copy(channels) { return Object.assign(new this.constructor, this, channels); }, @@ -2034,7 +2123,7 @@ function color_formatRgb() { return this.rgb().formatRgb(); } -function color$1(format) { +function color(format) { var m, l; format = (format + "").trim().toLowerCase(); return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000 @@ -2063,7 +2152,7 @@ function rgba(r, g, b, a) { } function rgbConvert(o) { - if (!(o instanceof Color$2)) o = color$1(o); + if (!(o instanceof Color$1)) o = color(o); if (!o) return new Rgb; o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); @@ -2080,7 +2169,7 @@ function Rgb(r, g, b, opacity) { this.opacity = +opacity; } -define(Rgb, rgb, extend(Color$2, { +define(Rgb, rgb, extend(Color$1, { brighter(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); @@ -2143,7 +2232,7 @@ function hsla(h, s, l, a) { function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); - if (!(o instanceof Color$2)) o = color$1(o); + if (!(o instanceof Color$1)) o = color(o); if (!o) return new Hsl; if (o instanceof Hsl) return o; o = o.rgb(); @@ -2178,7 +2267,7 @@ function Hsl(h, s, l, opacity) { this.opacity = +opacity; } -define(Hsl, hsl, extend(Color$2, { +define(Hsl, hsl, extend(Color$1, { brighter(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); @@ -2270,7 +2359,7 @@ function Lab(l, a, b, opacity) { this.opacity = +opacity; } -define(Lab, lab, extend(Color$2, { +define(Lab, lab, extend(Color$1, { brighter(k) { return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity); }, @@ -2334,7 +2423,7 @@ function hcl2lab(o) { return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); } -define(Hcl, hcl, extend(Color$2, { +define(Hcl, hcl, extend(Color$1, { brighter(k) { return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity); }, @@ -2380,7 +2469,7 @@ function Cubehelix(h, s, l, opacity) { this.opacity = +opacity; } -define(Cubehelix, cubehelix, extend(Color$2, { +define(Cubehelix, cubehelix, extend(Color$1, { brighter(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); @@ -2531,39 +2620,58 @@ const pi$1 = Math.PI, epsilon$1 = 1e-6, tauEpsilon = tau$1 - epsilon$1; -function Path$1() { - this._x0 = this._y0 = // start of current subpath - this._x1 = this._y1 = null; // end of current subpath - this._ = ""; +function append(strings) { + this._ += strings[0]; + for (let i = 1, n = strings.length; i < n; ++i) { + this._ += arguments[i] + strings[i]; + } } -function path() { - return new Path$1; +function appendRound(digits) { + let d = Math.floor(digits); + if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`); + if (d > 15) return append; + const k = 10 ** d; + return function(strings) { + this._ += strings[0]; + for (let i = 1, n = strings.length; i < n; ++i) { + this._ += Math.round(arguments[i] * k) / k + strings[i]; + } + }; } -Path$1.prototype = path.prototype = { - constructor: Path$1, - moveTo: function(x, y) { - this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y); - }, - closePath: function() { +let Path$1 = class Path { + constructor(digits) { + this._x0 = this._y0 = // start of current subpath + this._x1 = this._y1 = null; // end of current subpath + this._ = ""; + this._append = digits == null ? append : appendRound(digits); + } + moveTo(x, y) { + this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`; + } + closePath() { if (this._x1 !== null) { this._x1 = this._x0, this._y1 = this._y0; - this._ += "Z"; + this._append`Z`; } - }, - lineTo: function(x, y) { - this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y); - }, - quadraticCurveTo: function(x1, y1, x, y) { - this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y); - }, - bezierCurveTo: function(x1, y1, x2, y2, x, y) { - this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y); - }, - arcTo: function(x1, y1, x2, y2, r) { + } + lineTo(x, y) { + this._append`L${this._x1 = +x},${this._y1 = +y}`; + } + quadraticCurveTo(x1, y1, x, y) { + this._append`Q${+x1},${+y1},${this._x1 = +x},${this._y1 = +y}`; + } + bezierCurveTo(x1, y1, x2, y2, x, y) { + this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x},${this._y1 = +y}`; + } + arcTo(x1, y1, x2, y2, r) { x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r; - var x0 = this._x1, + + // Is the radius negative? Error. + if (r < 0) throw new Error(`negative radius: ${r}`); + + let x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, @@ -2571,12 +2679,9 @@ Path$1.prototype = path.prototype = { y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01; - // Is the radius negative? Error. - if (r < 0) throw new Error("negative radius: " + r); - // Is this path empty? Move to (x1,y1). if (this._x1 === null) { - this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1); + this._append`M${this._x1 = x1},${this._y1 = y1}`; } // Or, is (x1,y1) coincident with (x0,y0)? Do nothing. @@ -2586,12 +2691,12 @@ Path$1.prototype = path.prototype = { // Equivalently, is (x1,y1) coincident with (x2,y2)? // Or, is the radius zero? Line to (x1,y1). else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon$1) || !r) { - this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1); + this._append`L${this._x1 = x1},${this._y1 = y1}`; } // Otherwise, draw an arc! else { - var x20 = x2 - x0, + let x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, @@ -2603,32 +2708,33 @@ Path$1.prototype = path.prototype = { // If the start tangent is not coincident with (x0,y0), line to. if (Math.abs(t01 - 1) > epsilon$1) { - this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01); + this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`; } - this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21); + this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`; } - }, - arc: function(x, y, r, a0, a1, ccw) { + } + arc(x, y, r, a0, a1, ccw) { x = +x, y = +y, r = +r, ccw = !!ccw; - var dx = r * Math.cos(a0), + + // Is the radius negative? Error. + if (r < 0) throw new Error(`negative radius: ${r}`); + + let dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0; - // Is the radius negative? Error. - if (r < 0) throw new Error("negative radius: " + r); - // Is this path empty? Move to (x0,y0). if (this._x1 === null) { - this._ += "M" + x0 + "," + y0; + this._append`M${x0},${y0}`; } // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0). else if (Math.abs(this._x1 - x0) > epsilon$1 || Math.abs(this._y1 - y0) > epsilon$1) { - this._ += "L" + x0 + "," + y0; + this._append`L${x0},${y0}`; } // Is this arc empty? We’re done. @@ -2639,22 +2745,29 @@ Path$1.prototype = path.prototype = { // Is this a complete circle? Draw two arcs to complete the circle. if (da > tauEpsilon) { - this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0); + this._append`A${r},${r},0,1,${cw},${x - dx},${y - dy}A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`; } // Is this arc non-empty? Draw an arc! else if (da > epsilon$1) { - this._ += "A" + r + "," + r + ",0," + (+(da >= pi$1)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1)); + this._append`A${r},${r},0,${+(da >= pi$1)},${cw},${this._x1 = x + r * Math.cos(a1)},${this._y1 = y + r * Math.sin(a1)}`; } - }, - rect: function(x, y, w, h) { - this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z"; - }, - toString: function() { + } + rect(x, y, w, h) { + this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${w = +w}v${+h}h${-w}Z`; + } + toString() { return this._; } }; +function path() { + return new Path$1; +} + +// Allow instanceof d3.path +path.prototype = Path$1.prototype; + var slice = Array.prototype.slice; function constant$4(x) { @@ -4184,59 +4297,60 @@ const bisectRight = ascendingBisect.right; bisector(number$2).center; var bisect = bisectRight; -var e10 = Math.sqrt(50), +const e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); -function ticks(start, stop, count) { - var reverse, - i = -1, - n, - ticks, - step; +function tickSpec(start, stop, count) { + const step = (stop - start) / Math.max(0, count), + power = Math.floor(Math.log10(step)), + error = step / Math.pow(10, power), + factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1; + let i1, i2, inc; + if (power < 0) { + inc = Math.pow(10, -power) / factor; + i1 = Math.round(start * inc); + i2 = Math.round(stop * inc); + if (i1 / inc < start) ++i1; + if (i2 / inc > stop) --i2; + inc = -inc; + } else { + inc = Math.pow(10, power) * factor; + i1 = Math.round(start / inc); + i2 = Math.round(stop / inc); + if (i1 * inc < start) ++i1; + if (i2 * inc > stop) --i2; + } + if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2); + return [i1, i2, inc]; +} +function ticks(start, stop, count) { stop = +stop, start = +start, count = +count; - if (start === stop && count > 0) return [start]; - if (reverse = stop < start) n = start, start = stop, stop = n; - if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return []; - - if (step > 0) { - let r0 = Math.round(start / step), r1 = Math.round(stop / step); - if (r0 * step < start) ++r0; - if (r1 * step > stop) --r1; - ticks = new Array(n = r1 - r0 + 1); - while (++i < n) ticks[i] = (r0 + i) * step; + if (!(count > 0)) return []; + if (start === stop) return [start]; + const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count); + if (!(i2 >= i1)) return []; + const n = i2 - i1 + 1, ticks = new Array(n); + if (reverse) { + if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc; + else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc; } else { - step = -step; - let r0 = Math.round(start * step), r1 = Math.round(stop * step); - if (r0 / step < start) ++r0; - if (r1 / step > stop) --r1; - ticks = new Array(n = r1 - r0 + 1); - while (++i < n) ticks[i] = (r0 + i) / step; + if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc; + else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc; } - - if (reverse) ticks.reverse(); - return ticks; } function tickIncrement(start, stop, count) { - var step = (stop - start) / Math.max(0, count), - power = Math.floor(Math.log(step) / Math.LN10), - error = step / Math.pow(10, power); - return power >= 0 - ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power) - : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1); + stop = +stop, start = +start, count = +count; + return tickSpec(start, stop, count)[2]; } function tickStep(start, stop, count) { - var step0 = Math.abs(stop - start) / Math.max(0, count), - step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), - error = step0 / step1; - if (error >= e10) step1 *= 10; - else if (error >= e5) step1 *= 5; - else if (error >= e2) step1 *= 2; - return stop < start ? -step1 : step1; + stop = +stop, start = +start, count = +count; + const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count); + return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc); } function initRange(domain, range) { @@ -4428,8 +4542,8 @@ function interpolate$1(a, b) { var t = typeof b, c; return b == null || t === "boolean" ? constant$1(b) : (t === "number" ? interpolateNumber - : t === "string" ? ((c = color$1(b)) ? (b = c, interpolateRgb) : interpolateString) - : b instanceof color$1 ? interpolateRgb + : t === "string" ? ((c = color(b)) ? (b = c, interpolateRgb) : interpolateString) + : b instanceof color ? interpolateRgb : b instanceof Date ? date$1 : isNumberArray(b) ? numberArray : Array.isArray(b) ? genericArray @@ -4836,17 +4950,17 @@ function identity$1(x) { return x; } -var map$1 = Array.prototype.map, - prefixes = ["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"]; +var map = Array.prototype.map, + prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"]; function formatLocale$1(locale) { - var group = locale.grouping === undefined || locale.thousands === undefined ? identity$1 : formatGroup(map$1.call(locale.grouping, Number), locale.thousands + ""), + var group = locale.grouping === undefined || locale.thousands === undefined ? identity$1 : formatGroup(map.call(locale.grouping, Number), locale.thousands + ""), currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "", currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "", decimal = locale.decimal === undefined ? "." : locale.decimal + "", - numerals = locale.numerals === undefined ? identity$1 : formatNumerals(map$1.call(locale.numerals, String)), + numerals = locale.numerals === undefined ? identity$1 : formatNumerals(map.call(locale.numerals, String)), percent = locale.percent === undefined ? "%" : locale.percent + "", - minus = locale.minus === undefined ? "\u2212" : locale.minus + "", + minus = locale.minus === undefined ? "−" : locale.minus + "", nan = locale.nan === undefined ? "NaN" : locale.nan + ""; function newFormat(specifier) { @@ -5285,47 +5399,46 @@ function symlog() { return initRange.apply(scale, arguments); } -var t0 = new Date, - t1 = new Date; +const t0 = new Date, t1 = new Date; -function newInterval(floori, offseti, count, field) { +function timeInterval(floori, offseti, count, field) { function interval(date) { return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date; } - interval.floor = function(date) { + interval.floor = (date) => { return floori(date = new Date(+date)), date; }; - interval.ceil = function(date) { + interval.ceil = (date) => { return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date; }; - interval.round = function(date) { - var d0 = interval(date), - d1 = interval.ceil(date); + interval.round = (date) => { + const d0 = interval(date), d1 = interval.ceil(date); return date - d0 < d1 - date ? d0 : d1; }; - interval.offset = function(date, step) { + interval.offset = (date, step) => { return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date; }; - interval.range = function(start, stop, step) { - var range = [], previous; + interval.range = (start, stop, step) => { + const range = []; start = interval.ceil(start); step = step == null ? 1 : Math.floor(step); if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date + let previous; do range.push(previous = new Date(+start)), offseti(start, step), floori(start); while (previous < start && start < stop); return range; }; - interval.filter = function(test) { - return newInterval(function(date) { + interval.filter = (test) => { + return timeInterval((date) => { if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1); - }, function(date, step) { + }, (date, step) => { if (date >= date) { if (step < 0) while (++step <= 0) { while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty @@ -5337,48 +5450,47 @@ function newInterval(floori, offseti, count, field) { }; if (count) { - interval.count = function(start, end) { + interval.count = (start, end) => { t0.setTime(+start), t1.setTime(+end); floori(t0), floori(t1); return Math.floor(count(t0, t1)); }; - interval.every = function(step) { + interval.every = (step) => { step = Math.floor(step); return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field - ? function(d) { return field(d) % step === 0; } - : function(d) { return interval.count(0, d) % step === 0; }); + ? (d) => field(d) % step === 0 + : (d) => interval.count(0, d) % step === 0); }; } return interval; } -var millisecond = newInterval(function() { +const millisecond = timeInterval(() => { // noop -}, function(date, step) { +}, (date, step) => { date.setTime(+date + step); -}, function(start, end) { +}, (start, end) => { return end - start; }); // An optimized implementation for this simple case. -millisecond.every = function(k) { +millisecond.every = (k) => { k = Math.floor(k); if (!isFinite(k) || !(k > 0)) return null; if (!(k > 1)) return millisecond; - return newInterval(function(date) { + return timeInterval((date) => { date.setTime(Math.floor(date / k) * k); - }, function(date, step) { + }, (date, step) => { date.setTime(+date + step * k); - }, function(start, end) { + }, (start, end) => { return (end - start) / k; }); }; -var millisecond$1 = millisecond; millisecond.range; const durationSecond = 1000; @@ -5389,174 +5501,144 @@ const durationWeek = durationDay * 7; const durationMonth = durationDay * 30; const durationYear = durationDay * 365; -var second = newInterval(function(date) { +const second = timeInterval((date) => { date.setTime(date - date.getMilliseconds()); -}, function(date, step) { +}, (date, step) => { date.setTime(+date + step * durationSecond); -}, function(start, end) { +}, (start, end) => { return (end - start) / durationSecond; -}, function(date) { +}, (date) => { return date.getUTCSeconds(); }); -var utcSecond = second; second.range; -var minute = newInterval(function(date) { +const timeMinute = timeInterval((date) => { date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond); -}, function(date, step) { +}, (date, step) => { date.setTime(+date + step * durationMinute); -}, function(start, end) { +}, (start, end) => { return (end - start) / durationMinute; -}, function(date) { +}, (date) => { return date.getMinutes(); }); -var timeMinute = minute; -minute.range; +timeMinute.range; + +const utcMinute = timeInterval((date) => { + date.setUTCSeconds(0, 0); +}, (date, step) => { + date.setTime(+date + step * durationMinute); +}, (start, end) => { + return (end - start) / durationMinute; +}, (date) => { + return date.getUTCMinutes(); +}); + +utcMinute.range; -var hour = newInterval(function(date) { +const timeHour = timeInterval((date) => { date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute); -}, function(date, step) { +}, (date, step) => { date.setTime(+date + step * durationHour); -}, function(start, end) { +}, (start, end) => { return (end - start) / durationHour; -}, function(date) { +}, (date) => { return date.getHours(); }); -var timeHour = hour; -hour.range; +timeHour.range; -var day = newInterval( +const utcHour = timeInterval((date) => { + date.setUTCMinutes(0, 0, 0); +}, (date, step) => { + date.setTime(+date + step * durationHour); +}, (start, end) => { + return (end - start) / durationHour; +}, (date) => { + return date.getUTCHours(); +}); + +utcHour.range; + +const timeDay = timeInterval( date => date.setHours(0, 0, 0, 0), (date, step) => date.setDate(date.getDate() + step), (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay, date => date.getDate() - 1 ); -var timeDay = day; -day.range; - -function weekday(i) { - return newInterval(function(date) { - date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); - date.setHours(0, 0, 0, 0); - }, function(date, step) { - date.setDate(date.getDate() + step * 7); - }, function(start, end) { - return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; - }); -} - -var sunday = weekday(0); -var monday = weekday(1); -var tuesday = weekday(2); -var wednesday = weekday(3); -var thursday = weekday(4); -var friday = weekday(5); -var saturday = weekday(6); +timeDay.range; -sunday.range; -monday.range; -tuesday.range; -wednesday.range; -thursday.range; -friday.range; -saturday.range; - -var month = newInterval(function(date) { - date.setDate(1); - date.setHours(0, 0, 0, 0); -}, function(date, step) { - date.setMonth(date.getMonth() + step); -}, function(start, end) { - return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; -}, function(date) { - return date.getMonth(); +const utcDay = timeInterval((date) => { + date.setUTCHours(0, 0, 0, 0); +}, (date, step) => { + date.setUTCDate(date.getUTCDate() + step); +}, (start, end) => { + return (end - start) / durationDay; +}, (date) => { + return date.getUTCDate() - 1; }); -var timeMonth = month; -month.range; +utcDay.range; -var year = newInterval(function(date) { - date.setMonth(0, 1); - date.setHours(0, 0, 0, 0); -}, function(date, step) { - date.setFullYear(date.getFullYear() + step); -}, function(start, end) { - return end.getFullYear() - start.getFullYear(); -}, function(date) { - return date.getFullYear(); +const unixDay = timeInterval((date) => { + date.setUTCHours(0, 0, 0, 0); +}, (date, step) => { + date.setUTCDate(date.getUTCDate() + step); +}, (start, end) => { + return (end - start) / durationDay; +}, (date) => { + return Math.floor(date / durationDay); }); -// An optimized implementation for this simple case. -year.every = function(k) { - return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) { - date.setFullYear(Math.floor(date.getFullYear() / k) * k); - date.setMonth(0, 1); +unixDay.range; + +function timeWeekday(i) { + return timeInterval((date) => { + date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); date.setHours(0, 0, 0, 0); - }, function(date, step) { - date.setFullYear(date.getFullYear() + step * k); + }, (date, step) => { + date.setDate(date.getDate() + step * 7); + }, (start, end) => { + return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; }); -}; - -var timeYear = year; -year.range; - -var utcMinute = newInterval(function(date) { - date.setUTCSeconds(0, 0); -}, function(date, step) { - date.setTime(+date + step * durationMinute); -}, function(start, end) { - return (end - start) / durationMinute; -}, function(date) { - return date.getUTCMinutes(); -}); -utcMinute.range; - -var utcHour = newInterval(function(date) { - date.setUTCMinutes(0, 0, 0); -}, function(date, step) { - date.setTime(+date + step * durationHour); -}, function(start, end) { - return (end - start) / durationHour; -}, function(date) { - return date.getUTCHours(); -}); -utcHour.range; +} -var utcDay = newInterval(function(date) { - date.setUTCHours(0, 0, 0, 0); -}, function(date, step) { - date.setUTCDate(date.getUTCDate() + step); -}, function(start, end) { - return (end - start) / durationDay; -}, function(date) { - return date.getUTCDate() - 1; -}); +const timeSunday = timeWeekday(0); +const timeMonday = timeWeekday(1); +const timeTuesday = timeWeekday(2); +const timeWednesday = timeWeekday(3); +const timeThursday = timeWeekday(4); +const timeFriday = timeWeekday(5); +const timeSaturday = timeWeekday(6); -var utcDay$1 = utcDay; -utcDay.range; +timeSunday.range; +timeMonday.range; +timeTuesday.range; +timeWednesday.range; +timeThursday.range; +timeFriday.range; +timeSaturday.range; function utcWeekday(i) { - return newInterval(function(date) { + return timeInterval((date) => { date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7); date.setUTCHours(0, 0, 0, 0); - }, function(date, step) { + }, (date, step) => { date.setUTCDate(date.getUTCDate() + step * 7); - }, function(start, end) { + }, (start, end) => { return (end - start) / durationWeek; }); } -var utcSunday = utcWeekday(0); -var utcMonday = utcWeekday(1); -var utcTuesday = utcWeekday(2); -var utcWednesday = utcWeekday(3); -var utcThursday = utcWeekday(4); -var utcFriday = utcWeekday(5); -var utcSaturday = utcWeekday(6); +const utcSunday = utcWeekday(0); +const utcMonday = utcWeekday(1); +const utcTuesday = utcWeekday(2); +const utcWednesday = utcWeekday(3); +const utcThursday = utcWeekday(4); +const utcFriday = utcWeekday(5); +const utcSaturday = utcWeekday(6); utcSunday.range; utcMonday.range; @@ -5566,50 +5648,87 @@ utcThursday.range; utcFriday.range; utcSaturday.range; -var utcMonth = newInterval(function(date) { +const timeMonth = timeInterval((date) => { + date.setDate(1); + date.setHours(0, 0, 0, 0); +}, (date, step) => { + date.setMonth(date.getMonth() + step); +}, (start, end) => { + return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; +}, (date) => { + return date.getMonth(); +}); + +timeMonth.range; + +const utcMonth = timeInterval((date) => { date.setUTCDate(1); date.setUTCHours(0, 0, 0, 0); -}, function(date, step) { +}, (date, step) => { date.setUTCMonth(date.getUTCMonth() + step); -}, function(start, end) { +}, (start, end) => { return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; -}, function(date) { +}, (date) => { return date.getUTCMonth(); }); + utcMonth.range; -var utcYear = newInterval(function(date) { +const timeYear = timeInterval((date) => { + date.setMonth(0, 1); + date.setHours(0, 0, 0, 0); +}, (date, step) => { + date.setFullYear(date.getFullYear() + step); +}, (start, end) => { + return end.getFullYear() - start.getFullYear(); +}, (date) => { + return date.getFullYear(); +}); + +// An optimized implementation for this simple case. +timeYear.every = (k) => { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => { + date.setFullYear(Math.floor(date.getFullYear() / k) * k); + date.setMonth(0, 1); + date.setHours(0, 0, 0, 0); + }, (date, step) => { + date.setFullYear(date.getFullYear() + step * k); + }); +}; + +timeYear.range; + +const utcYear = timeInterval((date) => { date.setUTCMonth(0, 1); date.setUTCHours(0, 0, 0, 0); -}, function(date, step) { +}, (date, step) => { date.setUTCFullYear(date.getUTCFullYear() + step); -}, function(start, end) { +}, (start, end) => { return end.getUTCFullYear() - start.getUTCFullYear(); -}, function(date) { +}, (date) => { return date.getUTCFullYear(); }); // An optimized implementation for this simple case. -utcYear.every = function(k) { - return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) { +utcYear.every = (k) => { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => { date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k); date.setUTCMonth(0, 1); date.setUTCHours(0, 0, 0, 0); - }, function(date, step) { + }, (date, step) => { date.setUTCFullYear(date.getUTCFullYear() + step * k); }); }; -var utcYear$1 = utcYear; utcYear.range; function ticker(year, month, week, day, hour, minute) { const tickIntervals = [ - [utcSecond, 1, durationSecond], - [utcSecond, 5, 5 * durationSecond], - [utcSecond, 15, 15 * durationSecond], - [utcSecond, 30, 30 * durationSecond], + [second, 1, durationSecond], + [second, 5, 5 * durationSecond], + [second, 15, 15 * durationSecond], + [second, 30, 30 * durationSecond], [minute, 1, durationMinute], [minute, 5, 5 * durationMinute], [minute, 15, 15 * durationMinute], @@ -5638,14 +5757,14 @@ function ticker(year, month, week, day, hour, minute) { const target = Math.abs(stop - start) / count; const i = bisector(([,, step]) => step).right(tickIntervals, target); if (i === tickIntervals.length) return year.every(tickStep(start / durationYear, stop / durationYear, count)); - if (i === 0) return millisecond$1.every(Math.max(tickStep(start, stop, count), 1)); + if (i === 0) return millisecond.every(Math.max(tickStep(start, stop, count), 1)); const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i]; return t.every(step); } return [ticks, tickInterval]; } -const [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, sunday, timeDay, timeHour, timeMinute); +const [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute); function localDate(d) { if (0 <= d.y && d.y < 100) { @@ -5858,13 +5977,13 @@ function formatLocale(locale) { if ("Z" in d) { week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay(); week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week); - week = utcDay$1.offset(week, (d.V - 1) * 7); + week = utcDay.offset(week, (d.V - 1) * 7); d.y = week.getUTCFullYear(); d.m = week.getUTCMonth(); d.d = week.getUTCDate() + (d.w + 6) % 7; } else { week = localDate(newDate(d.y, 0, 1)), day = week.getDay(); - week = day > 4 || day === 0 ? monday.ceil(week) : monday(week); + week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week); week = timeDay.offset(week, (d.V - 1) * 7); d.y = week.getFullYear(); d.m = week.getMonth(); @@ -6187,17 +6306,17 @@ function formatWeekdayNumberMonday(d) { } function formatWeekNumberSunday(d, p) { - return pad(sunday.count(timeYear(d) - 1, d), p, 2); + return pad(timeSunday.count(timeYear(d) - 1, d), p, 2); } function dISO(d) { var day = d.getDay(); - return (day >= 4 || day === 0) ? thursday(d) : thursday.ceil(d); + return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d); } function formatWeekNumberISO(d, p) { d = dISO(d); - return pad(thursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2); + return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2); } function formatWeekdayNumberSunday(d) { @@ -6205,7 +6324,7 @@ function formatWeekdayNumberSunday(d) { } function formatWeekNumberMonday(d, p) { - return pad(monday.count(timeYear(d) - 1, d), p, 2); + return pad(timeMonday.count(timeYear(d) - 1, d), p, 2); } function formatYear(d, p) { @@ -6223,7 +6342,7 @@ function formatFullYear(d, p) { function formatFullYearISO(d, p) { var day = d.getDay(); - d = (day >= 4 || day === 0) ? thursday(d) : thursday.ceil(d); + d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d); return pad(d.getFullYear() % 10000, p, 4); } @@ -6247,7 +6366,7 @@ function formatUTCHour12(d, p) { } function formatUTCDayOfYear(d, p) { - return pad(1 + utcDay$1.count(utcYear$1(d), d), p, 3); + return pad(1 + utcDay.count(utcYear(d), d), p, 3); } function formatUTCMilliseconds(d, p) { @@ -6276,7 +6395,7 @@ function formatUTCWeekdayNumberMonday(d) { } function formatUTCWeekNumberSunday(d, p) { - return pad(utcSunday.count(utcYear$1(d) - 1, d), p, 2); + return pad(utcSunday.count(utcYear(d) - 1, d), p, 2); } function UTCdISO(d) { @@ -6286,7 +6405,7 @@ function UTCdISO(d) { function formatUTCWeekNumberISO(d, p) { d = UTCdISO(d); - return pad(utcThursday.count(utcYear$1(d), d) + (utcYear$1(d).getUTCDay() === 4), p, 2); + return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2); } function formatUTCWeekdayNumberSunday(d) { @@ -6294,7 +6413,7 @@ function formatUTCWeekdayNumberSunday(d) { } function formatUTCWeekNumberMonday(d, p) { - return pad(utcMonday.count(utcYear$1(d) - 1, d), p, 2); + return pad(utcMonday.count(utcYear(d) - 1, d), p, 2); } function formatUTCYear(d, p) { @@ -6439,7 +6558,7 @@ function calendar(ticks, tickInterval, year, month, week, day, hour, minute, sec } function time() { - return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, sunday, timeDay, timeHour, timeMinute, utcSecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments); + return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute, second, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments); } function constant(x) { @@ -6469,6 +6588,24 @@ function asin(x) { return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x); } +function withPath(shape) { + let digits = 3; + + shape.digits = function(_) { + if (!arguments.length) return digits; + if (_ == null) { + digits = null; + } else { + const d = Math.floor(_); + if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`); + digits = d; + } + return shape; + }; + + return () => new Path$1(digits); +} + function arcInnerRadius(d) { return d.innerRadius; } @@ -6549,7 +6686,8 @@ function arc() { startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, - context = null; + context = null, + path = withPath(arc); function arc() { var buffer, @@ -6618,16 +6756,22 @@ function arc() { y00 = r0 * sin(a00), oc; - // Restrict the corner radius according to the sector angle. - if (da < pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) { - var ax = x01 - oc[0], - ay = y01 - oc[1], - bx = x11 - oc[0], - by = y11 - oc[1], - kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), - lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]); - rc0 = min(rc, (r0 - lc) / (kc - 1)); - rc1 = min(rc, (r1 - lc) / (kc + 1)); + // Restrict the corner radius according to the sector angle. If this + // intersection fails, it’s probably because the arc is too small, so + // disable the corner radius entirely. + if (da < pi) { + if (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10)) { + var ax = x01 - oc[0], + ay = y01 - oc[1], + bx = x11 - oc[0], + by = y11 - oc[1], + kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), + lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + rc0 = min(rc, (r0 - lc) / (kc - 1)); + rc1 = min(rc, (r1 - lc) / (kc + 1)); + } else { + rc0 = rc1 = 0; + } } } @@ -6879,18 +7023,18 @@ function schedule(node, name, id, index, group, timing) { } function init(node, id) { - var schedule = get$2(node, id); + var schedule = get(node, id); if (schedule.state > CREATED) throw new Error("too late; already scheduled"); return schedule; } function set(node, id) { - var schedule = get$2(node, id); + var schedule = get(node, id); if (schedule.state > STARTED) throw new Error("too late; already running"); return schedule; } -function get$2(node, id) { +function get(node, id) { var schedule = node.__transition; if (!schedule || !(schedule = schedule[id])) throw new Error("transition not found"); return schedule; @@ -7083,7 +7227,7 @@ function transition_tween(name, value) { name += ""; if (arguments.length < 2) { - var tween = get$2(this.node(), id).tween; + var tween = get(this.node(), id).tween; for (var i = 0, n = tween.length, t; i < n; ++i) { if ((t = tween[i]).name === name) { return t.value; @@ -7104,15 +7248,15 @@ function tweenValue(transition, name, value) { }); return function(node) { - return get$2(node, id).value[name]; + return get(node, id).value[name]; }; } function interpolate(a, b) { var c; return (typeof b === "number" ? interpolateNumber - : b instanceof color$1 ? interpolateRgb - : (c = color$1(b)) ? (b = c, interpolateRgb) + : b instanceof color ? interpolateRgb + : (c = color(b)) ? (b = c, interpolateRgb) : interpolateString)(a, b); } @@ -7252,7 +7396,7 @@ function transition_delay(value) { ? this.each((typeof value === "function" ? delayFunction : delayConstant)(id, value)) - : get$2(this.node(), id).delay; + : get(this.node(), id).delay; } function durationFunction(id, value) { @@ -7274,7 +7418,7 @@ function transition_duration(value) { ? this.each((typeof value === "function" ? durationFunction : durationConstant)(id, value)) - : get$2(this.node(), id).duration; + : get(this.node(), id).duration; } function easeConstant(id, value) { @@ -7289,7 +7433,7 @@ function transition_ease(value) { return arguments.length ? this.each(easeConstant(id, value)) - : get$2(this.node(), id).ease; + : get(this.node(), id).ease; } function easeVarying(id, value) { @@ -7364,7 +7508,7 @@ function transition_on(name, listener) { var id = this._id; return arguments.length < 2 - ? get$2(this.node(), id).on.on(name) + ? get(this.node(), id).on.on(name) : this.each(onFunction(id, name, listener)); } @@ -7391,7 +7535,7 @@ function transition_select(select) { if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) { if ("__data__" in node) subnode.__data__ = node.__data__; subgroup[i] = subnode; - schedule(subgroup[i], name, id, i, subgroup, get$2(node, id)); + schedule(subgroup[i], name, id, i, subgroup, get(node, id)); } } } @@ -7408,7 +7552,7 @@ function transition_selectAll(select) { for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) { for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) { if (node = group[i]) { - for (var children = select.call(node, node.__data__, i, group), child, inherit = get$2(node, id), k = 0, l = children.length; k < l; ++k) { + for (var children = select.call(node, node.__data__, i, group), child, inherit = get(node, id), k = 0, l = children.length; k < l; ++k) { if (child = children[k]) { schedule(child, name, id, k, children, inherit); } @@ -7580,7 +7724,7 @@ function transition_transition() { for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) { for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) { if (node = group[i]) { - var inherit = get$2(node, id0); + var inherit = get(node, id0); schedule(node, name, id1, i, group, { time: inherit.time + inherit.delay + inherit.duration, delay: 0, @@ -7724,7 +7868,10 @@ selection.prototype.transition = selection_transition; * With node.js can use 'width' and 'height' attributes when provided in element * @private */ function getElementRect(elem, sizearg) { - if (isNodeJs() && (sizearg != 'bbox')) + if (!elem || elem.empty()) + return { x: 0, y: 0, width: 0, height: 0 }; + + if ((isNodeJs() && (sizearg !== 'bbox')) || elem.property('_batch_mode')) return { x: 0, y: 0, width: parseInt(elem.attr('width')), height: parseInt(elem.attr('height')) }; const styleValue = name => { @@ -7735,10 +7882,10 @@ function getElementRect(elem, sizearg) { }; let rect = elem.node().getBoundingClientRect(); - if ((sizearg == 'bbox') && (parseFloat(rect.width) > 0)) + if ((sizearg === 'bbox') && (parseFloat(rect.width) > 0)) rect = elem.node().getBBox(); - let res = { x: 0, y: 0, width: parseInt(rect.width), height: parseInt(rect.height) }; + const res = { x: 0, y: 0, width: parseInt(rect.width), height: parseInt(rect.height) }; if (rect.left !== undefined) { res.x = parseInt(rect.left); res.y = parseInt(rect.top); @@ -7747,7 +7894,7 @@ function getElementRect(elem, sizearg) { res.y = parseInt(rect.y); } - if ((sizearg === undefined) || (sizearg == 'nopadding')) { + if ((sizearg === undefined) || (sizearg === 'nopadding')) { // this is size exclude padding area res.width -= styleValue('padding-left') + styleValue('padding-right'); res.height -= styleValue('padding-top') + styleValue('padding-bottom'); @@ -7760,8 +7907,10 @@ function getElementRect(elem, sizearg) { /** @summary Calculate absolute position of provided element in canvas * @private */ function getAbsPosInCanvas(sel, pos) { - while (pos && !sel.empty() && !sel.classed('root_canvas')) { - let cl = sel.attr('class'); + if (!pos) return pos; + + while (!sel.empty() && !sel.classed('root_canvas')) { + const cl = sel.attr('class'); if (cl && ((cl.indexOf('root_frame') >= 0) || (cl.indexOf('__root_pad_') >= 0))) { pos.x += sel.property('draw_x') || 0; pos.y += sel.property('draw_y') || 0; @@ -7782,24 +7931,23 @@ function floatToString(value, fmt, ret_fmt) { if (!fmt) fmt = '6.4g'; fmt = fmt.trim(); - let len = fmt.length; + const len = fmt.length; if (len < 2) return ret_fmt ? [value.toFixed(4), '6.4f'] : value.toFixed(4); - let last = fmt[len-1]; - fmt = fmt.slice(0,len-1); + const last = fmt[len-1]; + fmt = fmt.slice(0, len-1); let isexp, prec = fmt.indexOf('.'); prec = (prec < 0) ? 4 : parseInt(fmt.slice(prec+1)); if (!Number.isInteger(prec) || (prec <= 0)) prec = 4; let significance = false; - if ((last == 'e') || (last == 'E')) { isexp = true; } else - if (last == 'Q') { isexp = true; significance = true; } else - if ((last == 'f') || (last == 'F')) { isexp = false; } else - if (last == 'W') { isexp = false; significance = true; } else - if ((last == 'g') || (last == 'G')) { - let se = floatToString(value, fmt+'Q', true), - sg = floatToString(value, fmt+'W', true); - + if ((last === 'e') || (last === 'E')) isexp = true; else + if (last === 'Q') { isexp = true; significance = true; } else + if ((last === 'f') || (last === 'F')) isexp = false; else + if (last === 'W') { isexp = false; significance = true; } else + if ((last === 'g') || (last === 'G')) { + const se = floatToString(value, fmt+'Q', true); + let sg = floatToString(value, fmt+'W', true); if (se[0].length < sg[0].length) sg = se; return ret_fmt ? sg : sg[0]; } else { @@ -7812,27 +7960,25 @@ function floatToString(value, fmt, ret_fmt) { if (significance) prec--; if (prec < 0) prec = 0; - let se = value.toExponential(prec); - - return ret_fmt ? [se, '5.'+prec+'e'] : se; + const se = value.toExponential(prec); + return ret_fmt ? [se, `5.${prec}e`] : se; } let sg = value.toFixed(prec); if (significance) { - - // when using fixed representation, one could get 0.0 - if (value && (Number(sg) === 0.) && (prec > 0)) { + // when using fixed representation, one could get 0 + if (value && (Number(sg) === 0) && (prec > 0)) { prec = 20; sg = value.toFixed(prec); } let l = 0; - while ((ll) diff--; + if (sg.indexOf('.') > l) diff--; - if (diff != 0) { + if (diff !== 0) { prec -= diff; if (prec < 0) prec = 0; @@ -7858,7 +8004,7 @@ class DrawOptions { /** @summary Returns true if remaining options are empty or contain only seperators symbols. */ empty() { if (this.opt.length === 0) return true; - return this.opt.replace(/[ ;_,]/g, '').length == 0; + return this.opt.replace(/[ ;_,]/g, '').length === 0; } /** @summary Returns remaining part of the draw options. */ @@ -7866,7 +8012,7 @@ class DrawOptions { /** @summary Checks if given option exists */ check(name, postpart) { - let pos = this.opt.indexOf(name); + const pos = this.opt.indexOf(name); if (pos < 0) return false; this.opt = this.opt.slice(0, pos) + this.opt.slice(pos + name.length); this.part = ''; @@ -7883,9 +8029,17 @@ class DrawOptions { /** @summary Returns remaining part of found option as integer. */ partAsInt(offset, dflt) { + let mult = 1; + const last = this.part ? this.part[this.part.length - 1] : ''; + if (last === 'K') + mult = 1e3; + else if (last === 'M') + mult = 1e6; + else if (last === 'G') + mult = 1e9; let val = this.part.replace(/^\D+/g, ''); val = val ? parseInt(val, 10) : Number.NaN; - return !Number.isInteger(val) ? (dflt || 0) : val + (offset || 0); + return !Number.isInteger(val) ? (dflt || 0) : mult*val + (offset || 0); } /** @summary Returns remaining part of found option as float. */ @@ -7894,15 +8048,18 @@ class DrawOptions { val = val ? parseFloat(val) : Number.NaN; return !Number.isFinite(val) ? (dflt || 0) : val + (offset || 0); } + } // class DrawOptions /** @summary Simple random generator with controlled seed * @private */ class TRandom { + constructor(i) { if (i !== undefined) this.seed(i); } + /** @summary Seed simple random generator */ seed(i) { i = Math.abs(i); @@ -7913,6 +8070,7 @@ class TRandom { this.m_w = Math.round(i); this.m_z = 987654321; } + /** @summary Produce random value between 0 and 1 */ random() { if (this.m_z === undefined) return Math.random(); @@ -7922,103 +8080,104 @@ class TRandom { result /= 4294967296; return result + 0.5; } + } // class TRandom -/** @summary Function used to provide svg:path for the smoothed curves. - * @desc reuse code from d3.js. Used in TH1, TF1 and TGraph painters - * @param {string} kind should contain 'bezier' or 'line'. - * If first symbol 'L', then it used to continue drawing +/** @summary Build smooth SVG curve uzing Bezier + * @desc Reuse code from https://stackoverflow.com/questions/62855310 * @private */ -function buildSvgPath(kind, bins, height, ndig) { - - const smooth = kind.indexOf('bezier') >= 0; - - if (ndig === undefined) ndig = smooth ? 2 : 0; - if (height === undefined) height = 0; - - const jsroot_d3_svg_lineSlope = (p0, p1) => (p1.gry - p0.gry) / (p1.grx - p0.grx), - jsroot_d3_svg_lineFiniteDifferences = points => { - let i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = jsroot_d3_svg_lineSlope(p0, p1); - while (++i < j) { - p0 = p1; p1 = points[i + 1]; - m[i] = (d + (d = jsroot_d3_svg_lineSlope(p0, p1))) / 2; - } - m[i] = d; - return m; - }, jsroot_d3_svg_lineMonotoneTangents = points => { - let d, a, b, s, m = jsroot_d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; - while (++i < j) { - d = jsroot_d3_svg_lineSlope(points[i], points[i + 1]); - if (Math.abs(d) < 1e-6) { - m[i] = m[i + 1] = 0; - } else { - a = m[i] / d; - b = m[i + 1] / d; - s = a * a + b * b; - if (s > 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; - } - } - } - i = -1; - while (++i <= j) { - s = (points[Math.min(j, i + 1)].grx - points[Math.max(0, i - 1)].grx) / (6 * (1 + m[i] * m[i])); - points[i].dgrx = s || 0; - points[i].dgry = m[i] * s || 0; - } +function buildSvgCurve(p, args) { + if (!args) + args = {}; + if (!args.line) + args.calc = true; + else if (args.ndig === undefined) + args.ndig = 0; + + let npnts = p.length; + if (npnts < 3) args.line = true; + + args.t = args.t ?? 0.2; + + if ((args.ndig === undefined) || args.height) { + args.maxy = p[0].gry; + args.mindiff = 100; + for (let i = 1; i < npnts; i++) { + args.maxy = Math.max(args.maxy, p[i].gry); + args.mindiff = Math.min(args.mindiff, Math.abs(p[i].grx - p[i-1].grx), Math.abs(p[i].gry - p[i-1].gry)); + } + if (args.ndig === undefined) + args.ndig = args.mindiff > 20 ? 0 : (args.mindiff > 5 ? 1 : 2); + } + + const end_point = (pnt1, pnt2, sign) => { + const len = Math.sqrt((pnt2.gry - pnt1.gry)**2 + (pnt2.grx - pnt1.grx)**2) * args.t, + a2 = Math.atan2(pnt2.dgry, pnt2.dgrx), + a1 = Math.atan2(sign*(pnt2.gry - pnt1.gry), sign*(pnt2.grx - pnt1.grx)); + + pnt1.dgrx = len * Math.cos(2*a1 - a2); + pnt1.dgry = len * Math.sin(2*a1 - a2); + }, conv = val => { + if (!args.ndig || (Math.round(val) === val)) + return val.toFixed(0); + let s = val.toFixed(args.ndig), p = s.length-1; + while (s[p] === '0') p--; + if (s[p] === '.') p--; + s = s.slice(0, p+1); + return (s === '-0') ? '0' : s; }; - let res = { path: '', close: '' }, bin = bins[0], maxy = Math.max(bin.gry, height + 5), - currx = Math.round(bin.grx), curry = Math.round(bin.gry), dx, dy, npnts = bins.length; - - const conv = val => { - let vvv = Math.round(val); - if ((ndig == 0) || (vvv === val)) return vvv.toString(); - let str = val.toFixed(ndig); - while ((str[str.length - 1] == '0') && (str.lastIndexOf('.') < str.length - 1)) - str = str.slice(0, str.length - 1); - if (str[str.length - 1] == '.') - str = str.slice(0, str.length - 1); - if (str == '-0') str = '0'; - return str; - }; + if (args.calc) { + for (let i = 1; i < npnts - 1; i++) { + p[i].dgrx = (p[i+1].grx - p[i-1].grx) * args.t; + p[i].dgry = (p[i+1].gry - p[i-1].gry) * args.t; + } - res.path = ((kind[0] == 'L') ? 'L' : 'M') + conv(bin.grx) + ',' + conv(bin.gry); + if (npnts > 2) { + end_point(p[0], p[1], 1); + end_point(p[npnts - 1], p[npnts - 2], -1); + } else if (p.length === 2) { + p[0].dgrx = (p[1].grx - p[0].grx) * args.t; + p[0].dgry = (p[1].gry - p[0].gry) * args.t; + p[1].dgrx = -p[0].dgrx; + p[1].dgry = -p[0].dgry; + } + } - // just calculate all deltas, can be used to build exclusion - if (smooth || kind.indexOf('calc') >= 0) - jsroot_d3_svg_lineMonotoneTangents(bins); + let path = `${args.cmd ?? 'M'}${conv(p[0].grx)},${conv(p[0].gry)}`; - if (smooth) { - // build smoothed curve - res.path += `C${conv(bin.grx+bin.dgrx)},${conv(bin.gry+bin.dgry)},`; - for (let n = 1; n < npnts; ++n) { - let prev = bin; - bin = bins[n]; - if (n > 1) res.path += 'S'; - res.path += `${conv(bin.grx - bin.dgrx)},${conv(bin.gry - bin.dgry)},${conv(bin.grx)},${conv(bin.gry)}`; - maxy = Math.max(maxy, prev.gry); + if (!args.line) { + let i0 = 1; + if (args.qubic) { + npnts--; i0++; + path += `Q${conv(p[1].grx-p[1].dgrx)},${conv(p[1].gry-p[1].dgry)},${conv(p[1].grx)},${conv(p[1].gry)}`; } + path += `C${conv(p[i0-1].grx+p[i0-1].dgrx)},${conv(p[i0-1].gry+p[i0-1].dgry)},${conv(p[i0].grx-p[i0].dgrx)},${conv(p[i0].gry-p[i0].dgry)},${conv(p[i0].grx)},${conv(p[i0].gry)}`; + + // continue with simpler points + for (let i = i0 + 1; i < npnts; i++) + path += `S${conv(p[i].grx-p[i].dgrx)},${conv(p[i].gry-p[i].dgry)},${conv(p[i].grx)},${conv(p[i].gry)}`; + + if (args.qubic) + path += `Q${conv(p[npnts].grx-p[npnts].dgrx)},${conv(p[npnts].gry-p[npnts].dgry)},${conv(p[npnts].grx)},${conv(p[npnts].gry)}`; } else if (npnts < 10000) { // build simple curve - let acc_x = 0, acc_y = 0; + let acc_x = 0, acc_y = 0, currx = Math.round(p[0].grx), curry = Math.round(p[0].gry); const flush = () => { - if (acc_x) { res.path += 'h' + acc_x; acc_x = 0; } - if (acc_y) { res.path += 'v' + acc_y; acc_y = 0; } + if (acc_x) { path += 'h' + acc_x; acc_x = 0; } + if (acc_y) { path += 'v' + acc_y; acc_y = 0; } }; for (let n = 1; n < npnts; ++n) { - bin = bins[n]; - dx = Math.round(bin.grx) - currx; - dy = Math.round(bin.gry) - curry; + const bin = p[n], + dx = Math.round(bin.grx) - currx, + dy = Math.round(bin.gry) - curry; if (dx && dy) { flush(); - res.path += `l${dx},${dy}`; + path += `l${dx},${dy}`; } else if (!dx && dy) { if ((acc_y === 0) || ((dy < 0) !== (acc_y < 0))) flush(); acc_y += dy; @@ -8027,20 +8186,19 @@ function buildSvgPath(kind, bins, height, ndig) { acc_x += dx; } currx += dx; curry += dy; - maxy = Math.max(maxy, curry); } flush(); - } else { // build line with trying optimize many vertical moves - let lastx, lasty, cminy = curry, cmaxy = curry, prevy = curry; + let currx = Math.round(p[0].grx), curry = Math.round(p[0].gry), + cminy = curry, cmaxy = curry, prevy = curry; + for (let n = 1; n < npnts; ++n) { - bin = bins[n]; - lastx = Math.round(bin.grx); - lasty = Math.round(bin.gry); - maxy = Math.max(maxy, lasty); - dx = lastx - currx; + const bin = p[n], + lastx = Math.round(bin.grx), + lasty = Math.round(bin.gry), + dx = lastx - currx; if (dx === 0) { // if X not change, just remember amplitude and cminy = Math.min(cminy, lasty); @@ -8050,51 +8208,51 @@ function buildSvgPath(kind, bins, height, ndig) { } if (cminy !== cmaxy) { - if (cminy != curry) res.path += 'v' + (cminy - curry); - res.path += 'v' + (cmaxy - cminy); - if (cmaxy != prevy) res.path += 'v' + (prevy - cmaxy); + if (cminy !== curry) + path += `v${cminy-curry}`; + path += `v${cmaxy-cminy}`; + if (cmaxy !== prevy) + path += `v${prevy-cmaxy}`; curry = prevy; } - dy = lasty - curry; + const dy = lasty - curry; if (dy) - res.path += `l${dx},${dy}`; + path += `l${dx},${dy}`; else - res.path += 'h' + dx; + path += `h${dx}`; currx = lastx; curry = lasty; prevy = cminy = cmaxy = lasty; } - if (cminy != cmaxy) { - if (cminy != curry) res.path += 'v' + (cminy - curry); - res.path += 'v' + (cmaxy - cminy); - if (cmaxy != prevy) res.path += 'v' + (prevy - cmaxy); + if (cminy !== cmaxy) { + if (cminy !== curry) + path += `v${cminy-curry}`; + path += `v${cmaxy-cminy}`; + if (cmaxy !== prevy) + path += `v${prevy-cmaxy}`; } } - if (height > 0) - res.close = `L${conv(bin.grx)},${conv(maxy)}h${conv(bins[0].grx - bin.grx)}Z`; + if (args.height) + args.close = `L${conv(p[p.length-1].grx)},${conv(Math.max(args.maxy, args.height))}H${conv(p[0].grx)}Z`; - return res; + return path; } /** @summary Compress SVG code, produced from drawing * @desc removes extra info or empty elements * @private */ function compressSVG(svg) { - - svg = svg.replace(/url\(\"\;\#(\w+)\"\;\)/g, 'url(#$1)') // decode all URL - .replace(/ class=\"\w*\"/g, '') // remove all classes - .replace(/ pad=\"\w*\"/g, '') // remove all pad ids - .replace(/ title=\"\"/g, '') // remove all empty titles - .replace(/<\/g>/g, '') // remove all empty groups with transform - .replace(/<\/g>/g, ''); // remove all empty groups + svg = svg.replace(/url\("#(\w+)"\)/g, 'url(#$1)') // decode all URL + .replace(/ class="\w*"/g, '') // remove all classes + .replace(/ pad="\w*"/g, '') // remove all pad ids + .replace(/ title=""/g, '') // remove all empty titles + .replace(/<\/g>/g, '') // remove all empty groups with transform + .replace(/<\/g>/g, ''); // remove all empty groups // remove all empty frame svgs, typically appears in 3D drawings, maybe should be improved in frame painter itself - svg = svg.replace(/<\/svg>/g, ''); - - if (svg.indexOf('xlink:href') < 0) - svg = svg.replace(/ xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\"/g, ''); + svg = svg.replace(/<\/svg>/g, ''); return svg; } @@ -8135,32 +8293,32 @@ class BasePainter { * @param {string} [is_direct] - if 'origin' specified, returns original element even if actual drawing moved to some other place * @return {object} d3.select object for main element for drawing */ selectDom(is_direct) { - if (!this.divid) return select(null); let res = this._selected_main; if (!res) { if (isStr(this.divid)) { let id = this.divid; - if (id[0] != '#') id = '#' + id; + if (id[0] !== '#') id = '#' + id; res = select(id); if (!res.empty()) this.divid = res.node(); - } else { + } else res = select(this.divid); - } this._selected_main = res; } if (!res || res.empty() || (is_direct === 'origin')) return res; - let use_enlarge = res.property('use_enlarge'), - layout = res.property('layout') || 'simple', - layout_selector = (layout == 'simple') ? '' : res.property('layout_selector'); + const use_enlarge = res.property('use_enlarge'), + layout = res.property('layout') || 'simple', + layout_selector = (layout === 'simple') ? '' : res.property('layout_selector'); - if (layout_selector) res = res.select(layout_selector); + if (layout_selector) + res = res.select(layout_selector); // one could redirect here - if (!is_direct && !res.empty() && use_enlarge) res = select('#jsroot_enlarge_div'); + if (!is_direct && !res.empty() && use_enlarge) + res = select(getDocument().getElementById('jsroot_enlarge_div')); return res; } @@ -8168,11 +8326,11 @@ class BasePainter { /** @summary Access/change top painter * @private */ _accessTopPainter(on) { - let chld = this.selectDom().node()?.firstChild; + const chld = this.selectDom().node()?.firstChild; if (!chld) return null; - if (on === true) { + if (on === true) chld.painter = this; - } else if (on === false) + else if (on === false) delete chld.painter; return chld.painter; } @@ -8200,7 +8358,7 @@ class BasePainter { * @desc Removes all visible elements and all internal data */ cleanup(keep_origin) { this.clearTopPainter(); - let origin = this.selectDom('origin'); + const origin = this.selectDom('origin'); if (!origin.empty() && !keep_origin) origin.html(''); this.divid = null; delete this._selected_main; @@ -8224,23 +8382,21 @@ class BasePainter { * @return size of area when main div is drawn * @private */ testMainResize(check_level, new_size, height_factor) { + const enlarge = this.enlargeMain('state'), + origin = this.selectDom('origin'), + main = this.selectDom(), + lmt = 5; // minimal size - let enlarge = this.enlargeMain('state'), - main_origin = this.selectDom('origin'), - main = this.selectDom(), - lmt = 5; // minimal size - - if (enlarge !== 'on') { - if (new_size && new_size.width && new_size.height) - main_origin.style('width', new_size.width + 'px') + if ((enlarge !== 'on') && new_size?.width && new_size?.height) { + origin.style('width', new_size.width + 'px') .style('height', new_size.height + 'px'); } - let rect_origin = getElementRect(main_origin, true), - can_resize = main_origin.attr('can_resize'), - do_resize = false; + const rect_origin = getElementRect(origin, true), + can_resize = origin.attr('can_resize'); + let do_resize = false; - if (can_resize == 'height') + if (can_resize === 'height') if (height_factor && Math.abs(rect_origin.width * height_factor - rect_origin.height) > 0.1 * rect_origin.width) do_resize = true; if (((rect_origin.height <= lmt) || (rect_origin.width <= lmt)) && @@ -8251,24 +8407,30 @@ class BasePainter { if (rect_origin.width > lmt) { height_factor = height_factor || 0.66; - main_origin.style('height', Math.round(rect_origin.width * height_factor) + 'px'); - } else if (can_resize !== 'height') { - main_origin.style('width', '200px').style('height', '100px'); - } + origin.style('height', Math.round(rect_origin.width * height_factor) + 'px'); + } else if (can_resize !== 'height') + origin.style('width', '200px').style('height', '100px'); } - let rect = getElementRect(main), - old_h = main.property('draw_height'), - old_w = main.property('draw_width'); + const rect = getElementRect(main), + old_h = main.property('_jsroot_height'), + old_w = main.property('_jsroot_width'); rect.changed = false; if (old_h && old_w && (old_h > 0) && (old_w > 0)) { if ((old_h !== rect.height) || (old_w !== rect.width)) - if ((check_level > 1) || (rect.width / old_w < 0.66) || (rect.width / old_w > 1.5) || - (rect.height / old_h < 0.66) && (rect.height / old_h > 1.5)) rect.changed = true; - } else { + rect.changed = (check_level > 1) || (rect.width / old_w < 0.99) || (rect.width / old_w > 1.01) || (rect.height / old_h < 0.99) || (rect.height / old_h > 1.01); + } else + rect.changed = true; + + if (rect.changed) + main.property('_jsroot_height', rect.height).property('_jsroot_width', rect.width); + + // after change enlarge state always mark main element as resized + if (origin.property('did_enlarge')) { rect.changed = true; + origin.property('did_enlarge', false); } return rect; @@ -8285,56 +8447,57 @@ class BasePainter { * if action not specified, just return possibility to enlarge main div * @protected */ enlargeMain(action, skip_warning) { - - let main = this.selectDom(true), - origin = this.selectDom('origin'); + const main = this.selectDom(true), + origin = this.selectDom('origin'), + doc = getDocument(); if (main.empty() || !settings.CanEnlarge || (origin.property('can_enlarge') === false)) return false; if ((action === undefined) || (action === 'verify')) return true; - let state = origin.property('use_enlarge') ? 'on' : 'off'; + const state = origin.property('use_enlarge') ? 'on' : 'off'; if (action === 'state') return state; if (action === 'toggle') action = (state === 'off'); - let enlarge = select('#jsroot_enlarge_div'); + let enlarge = select(doc.getElementById('jsroot_enlarge_div')); if ((action === true) && (state !== 'on')) { if (!enlarge.empty()) return false; - enlarge = select(document.body) + enlarge = select(doc.body) .append('div') .attr('id', 'jsroot_enlarge_div') - .attr('style', 'position: fixed; margin: 0px; border: 0px; padding: 0px; left: 1px; right: 1px; top: 1px; bottom: 1px; background: white; opacity: 0.95; z-index: 100; overflow: hidden;'); + .attr('style', 'position: fixed; margin: 0px; border: 0px; padding: 0px; inset: 1px; background: white; opacity: 0.95; z-index: 100; overflow: hidden;'); - let rect1 = getElementRect(main), - rect2 = getElementRect(enlarge); + const rect1 = getElementRect(main), + rect2 = getElementRect(enlarge); // if new enlarge area not big enough, do not do it - if ((rect2.width <= rect1.width) || (rect2.height <= rect1.height)) + if ((rect2.width <= rect1.width) || (rect2.height <= rect1.height)) { if (rect2.width * rect2.height < rect1.width * rect1.height) { if (!skip_warning) console.log(`Enlarged area ${rect2.width} x ${rect2.height} smaller then original drawing ${rect1.width} x ${rect1.height}`); enlarge.remove(); return false; } + } while (main.node().childNodes.length > 0) enlarge.node().appendChild(main.node().firstChild); origin.property('use_enlarge', true); - + origin.property('did_enlarge', true); return true; } if ((action === false) && (state !== 'off')) { - while (enlarge.node() && enlarge.node().childNodes.length > 0) main.node().appendChild(enlarge.node().firstChild); enlarge.remove(); origin.property('use_enlarge', false); + origin.property('did_enlarge', true); return true; } @@ -8368,35 +8531,118 @@ class BasePainter { /** @summary Load and initialize JSDOM from nodes * @return {Promise} with d3 selection for d3_body - * @private */ + * @private */ async function _loadJSDOM() { return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(handle => { - if (!internals.nodejs_window) { internals.nodejs_window = (new handle.JSDOM('hello')).window; internals.nodejs_document = internals.nodejs_window.document; // used with three.js - internals.nodejs_body = select(internals.nodejs_document).select('body'); //get d3 handle for body + internals.nodejs_body = select(internals.nodejs_document).select('body'); // get d3 handle for body } return { JSDOM: handle.JSDOM, doc: internals.nodejs_document, body: internals.nodejs_body }; }); } +/** @summary Return translate string for transform attribute of some svg element + * @return string or null if x and y are zeros + * @private */ +function makeTranslate(g, x, y) { + if (!isObject(g)) { + y = x; x = g; g = null; + } + const res = y ? `translate(${x},${y})` : (x ? `translate(${x})` : null); + return g ? g.attr('transform', res) : res; +} + + +/** @summary Configure special style used for highlight or dragging elements + * @private */ +function addHighlightStyle(elem, drag) { + if (drag) { + elem.style('stroke', 'steelblue') + .style('fill-opacity', '0.1'); + } else { + elem.style('stroke', '#4572A7') + .style('fill', '#4572A7') + .style('opacity', '0'); + } +} + +/** @summary Create image based on SVG + * @param {string} svg - svg code of the image + * @param {string} [image_format] - image format like 'png' or 'jpeg' + * @param {boolean} [as_buffer] - return Buffer object for image + * @return {Promise} with produced image in base64 form or as Buffer (or canvas when no image_format specified) + * @private */ +async function svgToImage(svg, image_format, as_buffer) { + if (image_format === 'svg') + return svg; + + if (!isNodeJs()) { + // required with df104.py/df105.py example with RCanvas + const doctype = ''; + svg = encodeURIComponent(doctype + svg); + svg = svg.replace(/%([0-9A-F]{2})/g, (match, p1) => { + const c = String.fromCharCode('0x'+p1); + return c === '%' ? '%25' : c; + }); + svg = decodeURIComponent(svg); + } + + const img_src = 'data:image/svg+xml;base64,' + btoa_func(svg); + + if (isNodeJs()) { + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(async handle => { + return handle.default.loadImage(img_src).then(img => { + const canvas = handle.default.createCanvas(img.width, img.height); + + canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height); + + if (as_buffer) return canvas.toBuffer('image/' + image_format); + + return image_format ? canvas.toDataURL('image/' + image_format) : canvas; + }); + }); + } + + return new Promise(resolveFunc => { + const image = document.createElement('img'); + + image.onload = function() { + const canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + + canvas.getContext('2d').drawImage(image, 0, 0); + + if (as_buffer && image_format) + canvas.toBlob(blob => blob.arrayBuffer().then(resolveFunc), 'image/' + image_format); + else + resolveFunc(image_format ? canvas.toDataURL('image/' + image_format) : canvas); + }; + image.onerror = function(arg) { + console.log(`IMAGE ERROR ${arg}`); + resolveFunc(null); + }; + + image.src = img_src; + }); +} + const root_fonts = ['Arial', 'iTimes New Roman', 'bTimes New Roman', 'biTimes New Roman', 'Arial', 'oArial', 'bArial', 'boArial', 'Courier New', 'oCourier New', 'bCourier New', 'boCourier New', 'Symbol', 'Times New Roman', 'Wingdings', 'iSymbol', - 'Verdana', 'iVerdana', 'bVerdana', 'biVerdana']; - - + 'Verdana', 'iVerdana', 'bVerdana', 'biVerdana'], // taken from symbols.html, counted only for letters and digits -const root_fonts_aver_width = [0.5778,0.5314, +root_fonts_aver_width = [0.5778, 0.5314, 0.5809, 0.5540, 0.5778, - 0.5783,0.6034,0.6030,0.6003, - 0.6004,0.6003,0.6005, - 0.5521,0.5521,0.5664,0.5314, - 0.5664,0.5495,0.5748,0.5578]; + 0.5783, 0.6034, 0.6030, 0.6003, + 0.6004, 0.6003, 0.6005, + 0.5521, 0.5521, 0.5664, 0.5314, + 0.5664, 0.5495, 0.5748, 0.5578]; /** * @summary Helper class for font handling @@ -8420,9 +8666,8 @@ class FontHandler { this.scale = scale; if (fontIndex !== null) { - - let indx = Math.floor(fontIndex / 10), - fontName = root_fonts[indx] || 'Arial'; + const indx = Math.floor(fontIndex / 10); + let fontName = root_fonts[indx] || 'Arial'; while (fontName) { if (fontName[0] === 'b') @@ -8445,24 +8690,24 @@ class FontHandler { this.aver_width = this.weight ? 0.58 : 0.55; } - if ((this.name == 'Symbol') || (this.name == 'Wingdings')) { + if ((this.name === 'Symbol') || (this.name === 'Wingdings')) { this.isSymbol = this.name; - this.name = "Times New Roman"; - } else { + this.name = 'Times New Roman'; + } else this.isSymbol = ''; - } this.func = this.setFont.bind(this); } /** @summary Assigns font-related attributes */ setFont(selection, arg) { - selection.attr("font-family", this.name); - if (arg != 'without-size') - selection.attr("font-size", this.size) - .attr("xml:space", "preserve"); - selection.attr("font-weight", this.weight || null); - selection.attr("font-style", this.style || null); + selection.attr('font-family', this.name); + if (arg !== 'without-size') { + selection.attr('font-size', this.size) + .attr('xml:space', 'preserve'); + } + selection.attr('font-weight', this.weight || null); + selection.attr('font-style', this.style || null); } /** @summary Set font size (optional) */ @@ -8490,26 +8735,26 @@ class FontHandler { /** @summary Clears all font-related attributes */ clearFont(selection) { - selection.attr("font-family", null) - .attr("font-size", null) - .attr("xml:space", null) - .attr("font-weight", null) - .attr("font-style", null); + selection.attr('font-family', null) + .attr('font-size', null) + .attr('xml:space', null) + .attr('font-weight', null) + .attr('font-style', null); } /** @summary Returns true in case of monospace font * @private */ isMonospace() { - let n = this.name.toLowerCase(); - return (n.indexOf("courier") == 0) || (n == "monospace") || (n == "monaco"); + const n = this.name.toLowerCase(); + return (n.indexOf('courier') === 0) || (n === 'monospace') || (n === 'monaco'); } - /** @summary Return full font declaration which can be set as font property like "12pt Arial bold" + /** @summary Return full font declaration which can be set as font property like '12pt Arial bold' * @private */ getFontHtml() { - let res = Math.round(this.size) + "pt " + this.name; - if (this.weight) res += " " + this.weight; - if (this.style) res += " " + this.style; + let res = Math.round(this.size) + 'pt ' + this.name; + if (this.weight) res += ' ' + this.weight; + if (this.style) res += ' ' + this.style; return res; } @@ -8698,39 +8943,41 @@ const symbols_map = { '#left': '', '#right': '', '{}': '' -}; +}, /** @summary Create a single regex to detect any symbol to replace * @private */ -const symbolsRegexCache = new RegExp('(' + Object.keys(symbols_map).join('|').replace(/\\\{/g, '{').replace(/\\\}/g, '}') + ')', 'g'); +symbolsRegexCache = new RegExp('(' + Object.keys(symbols_map).join('|').replace(/\\\{/g, '{').replace(/\\\}/g, '}') + ')', 'g'), /** @summary Simple replacement of latex letters * @private */ -const translateLaTeX = (str, more) => { - while ((str.length > 2) && (str[0] == '{') && (str[str.length - 1] == '}')) +translateLaTeX = str => { + while ((str.length > 2) && (str[0] === '{') && (str[str.length - 1] === '}')) str = str.slice(1, str.length - 1); return str.replace(symbolsRegexCache, ch => symbols_map[ch]).replace(/\{\}/g, ''); -}; +}, // array with relative width of base symbols from range 32..126 -const base_symbols_width = [453,535,661,973,955,1448,1242,324,593,596,778,1011,431,570,468,492,947,885,947,947,947,947,947,947,947,947,511,495,980,1010,987,893,1624,1185,1147,1193,1216,1080,1028,1270,1274,531,910,1177,1004,1521,1252,1276,1111,1276,1164,1056,1073,1215,1159,1596,1150,1124,1065,540,591,540,837,874,572,929,972,879,973,901,569,967,973,453,458,903,453,1477,973,970,972,976,638,846,548,973,870,1285,884,864,835,656,430,656,1069]; +// eslint-disable-next-line +base_symbols_width = [453,535,661,973,955,1448,1242,324,593,596,778,1011,431,570,468,492,947,885,947,947,947,947,947,947,947,947,511,495,980,1010,987,893,1624,1185,1147,1193,1216,1080,1028,1270,1274,531,910,1177,1004,1521,1252,1276,1111,1276,1164,1056,1073,1215,1159,1596,1150,1124,1065,540,591,540,837,874,572,929,972,879,973,901,569,967,973,453,458,903,453,1477,973,970,972,976,638,846,548,973,870,1285,884,864,835,656,430,656,1069], -const extra_symbols_width = {945:1002,946:996,967:917,948:953,949:834,966:1149,947:847,951:989,953:516,954:951,955:913,956:1003,957:862,959:967,960:1070,952:954,961:973,963:1017,964:797,965:944,982:1354,969:1359,958:803,968:1232,950:825,913:1194,914:1153,935:1162,916:1178,917:1086,934:1358,915:1016,919:1275,921:539,977:995,922:1189,923:1170,924:1523,925:1253,927:1281,928:1281,920:1285,929:1102,931:1041,932:1069,933:1135,962:848,937:1279,926:1092,936:1334,918:1067,978:1154,8730:986,8804:940,8260:476,8734:1453,402:811,9827:1170,9830:931,9829:1067,9824:965,8596:1768,8592:1761,8593:895,8594:1761,8595:895,710:695,177:955,8243:680,8805:947,215:995,8733:1124,8706:916,8226:626,247:977,8800:969,8801:1031,8776:976,8230:1552,175:883,8629:1454,8501:1095,8465:1002,8476:1490,8472:1493,8855:1417,8853:1417,8709:1205,8745:1276,8746:1404,8839:1426,8835:1426,8836:1426,8838:1426,8834:1426,8747:480,8712:1426,8713:1426,8736:1608,8711:1551,174:1339,169:1339,8482:1469,8719:1364,729:522,172:1033,8743:1383,8744:1383,8660:1768,8656:1496,8657:1447,8658:1496,8659:1447,8721:1182,9115:882,9144:1000,9117:882,8970:749,9127:1322,9128:1322,8491:1150,229:929,8704:1397,8707:1170,8901:524,183:519,10003:1477,732:692,295:984,9725:1780,9744:1581,8741:737,8869:1390,8857:1421}; +// eslint-disable-next-line +extra_symbols_width = {945:1002,946:996,967:917,948:953,949:834,966:1149,947:847,951:989,953:516,954:951,955:913,956:1003,957:862,959:967,960:1070,952:954,961:973,963:1017,964:797,965:944,982:1354,969:1359,958:803,968:1232,950:825,913:1194,914:1153,935:1162,916:1178,917:1086,934:1358,915:1016,919:1275,921:539,977:995,922:1189,923:1170,924:1523,925:1253,927:1281,928:1281,920:1285,929:1102,931:1041,932:1069,933:1135,962:848,937:1279,926:1092,936:1334,918:1067,978:1154,8730:986,8804:940,8260:476,8734:1453,402:811,9827:1170,9830:931,9829:1067,9824:965,8596:1768,8592:1761,8593:895,8594:1761,8595:895,710:695,177:955,8243:680,8805:947,215:995,8733:1124,8706:916,8226:626,247:977,8800:969,8801:1031,8776:976,8230:1552,175:883,8629:1454,8501:1095,8465:1002,8476:1490,8472:1493,8855:1417,8853:1417,8709:1205,8745:1276,8746:1404,8839:1426,8835:1426,8836:1426,8838:1426,8834:1426,8747:480,8712:1426,8713:1426,8736:1608,8711:1551,174:1339,169:1339,8482:1469,8719:1364,729:522,172:1033,8743:1383,8744:1383,8660:1768,8656:1496,8657:1447,8658:1496,8659:1447,8721:1182,9115:882,9144:1000,9117:882,8970:749,9127:1322,9128:1322,8491:1150,229:929,8704:1397,8707:1170,8901:524,183:519,10003:1477,732:692,295:984,9725:1780,9744:1581,8741:737,8869:1390,8857:1421}; /** @ummary Calculate approximate labels width * @private */ function approximateLabelWidth(label, font, fsize) { - let len = label.length, - symbol_width = (fsize || font.size) * font.aver_width; + const len = label.length, + symbol_width = (fsize || font.size) * font.aver_width; if (font.isMonospace()) return len * symbol_width; let sum = 0; for (let i = 0; i < len; ++i) { - let code = label.charCodeAt(i); - if ((code >= 32) && (code<127)) - sum += base_symbols_width[code-32]; + const code = label.charCodeAt(i); + if ((code >= 32) && (code < 127)) + sum += base_symbols_width[code - 32]; else sum += extra_symbols_width[code] || 1000; } @@ -8780,16 +9027,19 @@ const latex_features = [ ]; // taken from: https://sites.math.washington.edu/~marshall/cxseminar/symbol.htm, starts from 33 +// eslint-disable-next-line const symbolsMap = [0,8704,0,8707,0,0,8717,0,0,8727,0,0,8722,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8773,913,914,935,916,917,934,915,919,921,977,922,923,924,925,927,928,920,929,931,932,933,962,937,926,936,918,0,8756,0,8869,0,0,945,946,967,948,949,966,947,951,953,981,954,955,956,957,959,960,952,961,963,964,965,982,969,958,968,950,0,402,0,8764,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,978,8242,8804,8260,8734,0,9827,9830,9829,9824,8596,8592,8593,8594,8595,0,0,8243,8805,0,8733,8706,8729,0,8800,8801,8776,8230,0,0,8629,8501,8465,8476,8472,8855,8853,8709,8745,8746,8835,8839,8836,8834,8838,8712,8713,8736,8711,0,0,8482,8719,8730,8901,0,8743,8744,8660,8656,8657,8658,8659,9674,9001,0,0,8482,8721,0,0,0,0,0,0,0,0,0,0,8364,9002,8747,8992,0,8993]; // taken from http://www.alanwood.net/demos/wingdings.html, starts from 33 +// eslint-disable-next-line const wingdingsMap = [128393,9986,9985,128083,128365,128366,128367,128383,9990,128386,128387,128234,128235,128236,128237,128193,128194,128196,128463,128464,128452,8987,128430,128432,128434,128435,128436,128427,128428,9991,9997,128398,9996,128076,128077,128078,9756,9758,9757,9759,128400,9786,128528,9785,128163,9760,127987,127985,9992,9788,128167,10052,128326,10014,128328,10016,10017,9770,9775,2384,9784,9800,9801,9802,9803,9804,9805,9806,9807,9808,9809,9810,9811,128624,128629,9679,128318,9632,9633,128912,10065,10066,11047,10731,9670,10070,11045,8999,11193,8984,127989,127990,128630,128631,0,9450,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,9471,10102,10103,10104,10105,10106,10107,10108,10109,10110,10111,128610,128608,128609,128611,128606,128604,128605,128607,183,8226,9642,9898,128902,128904,9673,9678,128319,9642,9723,128962,10022,9733,10038,10036,10041,10037,11216,8982,10209,8977,11217,10026,10032,128336,128337,128338,128339,128340,128341,128342,128343,128344,128345,128346,128347,11184,11185,11186,11187,11188,11189,11190,11191,128618,128619,128597,128596,128599,128598,128592,128593,128594,128595,9003,8998,11160,11162,11161,11163,11144,11146,11145,11147,129128,129130,129129,129131,129132,129133,129135,129134,129144,129146,129145,129147,129148,129149,129151,129150,8678,8680,8679,8681,11012,8691,11008,11009,11011,11010,129196,129197,128502,10004,128503,128505]; function replaceSymbols(s, kind) { - let res = '', m = kind == 'Wingdings' ? wingdingsMap : symbolsMap; + const m = (kind === 'Wingdings') ? wingdingsMap : symbolsMap; + let res = ''; for (let k = 0; k < s.length; ++k) { - let code = s.charCodeAt(k), - new_code = (code > 32) ? m[code-33] : 0; + const code = s.charCodeAt(k), + new_code = (code > 32) ? m[code-33] : 0; res += String.fromCodePoint(new_code || code); } return res; @@ -8817,17 +9067,16 @@ function isPlainText(txt) { * @desc use together with normal elements * @private */ function parseLatex(node, arg, label, curr) { - let nelements = 0; - const currG = () => { if (!curr.g) curr.g = node.append('svg:g'); return curr.g; }; + const currG = () => { if (!curr.g) curr.g = node.append('svg:g'); return curr.g; }, - const shiftX = dx => { curr.x += Math.round(dx); }; + shiftX = dx => { curr.x += Math.round(dx); }, - const extendPosition = (x1, y1, x2, y2) => { - if (!curr.rect) { - curr.rect = { x1: x1, y1: y1, x2: x2, y2: y2 }; - } else { + extendPosition = (x1, y1, x2, y2) => { + if (!curr.rect) + curr.rect = { x1, y1, x2, y2 }; + else { curr.rect.x1 = Math.min(curr.rect.x1, x1); curr.rect.y1 = Math.min(curr.rect.y1, y1); curr.rect.x2 = Math.max(curr.rect.x2, x2); @@ -8839,17 +9088,19 @@ function parseLatex(node, arg, label, curr) { if (!curr.parent) arg.text_rect = curr.rect; - }; + }, + + addSpaces = nspaces => { + extendPosition(curr.x, curr.y, curr.x + nspaces * curr.fsize * 0.4, curr.y); + shiftX(nspaces * curr.fsize * 0.4); + }, /** Position pos.g node which directly attached to curr.g and uses curr.g coordinates */ - const positionGNode = (pos, x, y, inside_gg) => { + positionGNode = (pos, x, y, inside_gg) => { x = Math.round(x); y = Math.round(y); - if (y) - pos.g.attr('transform',`translate(${x},${y})`); - else if (x) - pos.g.attr('transform',`translate(${x})`); + makeTranslate(pos.g, x, y); pos.rect.x1 += x; pos.rect.x2 += x; pos.rect.y1 += y; @@ -8859,48 +9110,42 @@ function parseLatex(node, arg, label, curr) { extendPosition(curr.x + pos.rect.x1, curr.y + pos.rect.y1, curr.x + pos.rect.x2, curr.y + pos.rect.y2); else extendPosition(pos.rect.x1, pos.rect.y1, pos.rect.x2, pos.rect.y2); - }; + }, /** Create special sub-container for elements like sqrt or braces */ - const createGG = () => { - let gg = currG(); + createGG = () => { + const gg = currG(); // this is indicator that gg element will be the only one, one can use directly main container - if ((nelements == 1) && !label && !curr.x && !curr.y) { + if ((nelements === 1) && !label && !curr.x && !curr.y) return gg; - } - - gg = gg.append('svg:g'); - if (curr.y) - gg.attr('transform',`translate(${curr.x},${curr.y})`); - else if (curr.x) - gg.attr('transform',`translate(${curr.x})`); - return gg; - }; + return makeTranslate(gg.append('svg:g'), curr.x, curr.y); + }, - const extractSubLabel = (check_first, lbrace, rbrace) => { - let pos = 0, n = 1, err = false, extra_braces = false; + extractSubLabel = (check_first, lbrace, rbrace) => { + let pos = 0, n = 1, extra_braces = false; if (!lbrace) lbrace = '{'; if (!rbrace) rbrace = '}'; - const match = br => (pos + br.length <= label.length) && (label.slice(pos, pos+br.length) == br); + const match = br => (pos + br.length <= label.length) && (label.slice(pos, pos+br.length) === br); if (check_first) { - if(!match(lbrace)) - err = true; - else + if (!match(lbrace)) { + console.log(`not starting with ${lbrace} in ${label}`); + return -1; + } else label = label.slice(lbrace.length); } - while (!err && (n != 0) && (pos < label.length)) { + while ((n !== 0) && (pos < label.length)) { if (match(lbrace)) { n++; pos += lbrace.length; } else if (match(rbrace)) { n--; pos += rbrace.length; - if ((n == 0) && (typeof check_first == 'string') && match(check_first+lbrace)) { + if ((n === 0) && (typeof check_first === 'string') && match(check_first + lbrace)) { // handle special case like a^{b}^{2} should mean a^{b^{2}} n++; pos += lbrace.length + check_first.length; @@ -8909,7 +9154,7 @@ function parseLatex(node, arg, label, curr) { } } else pos++; } - if ((n != 0) || err) { + if (n !== 0) { console.log(`mismatch with open ${lbrace} and closing ${rbrace} in ${label}`); return -1; } @@ -8921,39 +9166,54 @@ function parseLatex(node, arg, label, curr) { label = label.slice(pos); return sublabel; - }; + }, - const createPath = (gg, dofill) => { + createPath = (gg, d, dofill) => { return gg.append('svg:path') .style('stroke', dofill ? 'none' : (curr.color || arg.color)) .style('stroke-width', dofill ? null : Math.max(1, Math.round(curr.fsize*(curr.font.weight ? 0.1 : 0.07)))) - .style('fill', dofill ? (curr.color || arg.color) : 'none'); - }; + .style('fill', dofill ? (curr.color || arg.color) : 'none') + .attr('d', d ?? null); + }, - const createSubPos = fscale => { + createSubPos = fscale => { return { lvl: curr.lvl + 1, x: 0, y: 0, fsize: curr.fsize*(fscale || 1), color: curr.color, font: curr.font, parent: curr, painter: curr.painter }; }; while (label) { - let best = label.length, found = null; for (let n = 0; n < latex_features.length; ++n) { - let pos = label.indexOf(latex_features[n].name); + const pos = label.indexOf(latex_features[n].name); if ((pos >= 0) && (pos < best)) { best = pos; found = latex_features[n]; } } if (best > 0) { - - let alone = (best == label.length) && (nelements == 0) && !found; + const alone = (best === label.length) && (nelements === 0) && !found; nelements++; - let s = translateLaTeX(label.slice(0, best)); + let s = translateLaTeX(label.slice(0, best)), + nbeginspaces = 0, nendspaces = 0; + + while ((nbeginspaces < s.length) && (s[nbeginspaces] === ' ')) + nbeginspaces++; + + if (nbeginspaces > 0) { + addSpaces(nbeginspaces); + s = s.slice(nbeginspaces); + } + + while ((nendspaces < s.length) && (s[s.length - 1 - nendspaces] === ' ')) + nendspaces++; + + if (nendspaces > 0) + s = s.slice(0, s.length - nendspaces); + if (s || alone) { // if single text element created, place it directly in the node - let g = curr.g || (alone ? node : currG()), - elem = g.append('svg:text'); + const g = curr.g || (alone ? node : currG()), + elem = g.append('svg:text'); if (alone && !curr.g) curr.g = elem; @@ -8979,25 +9239,24 @@ function parseLatex(node, arg, label, curr) { else elem.text(s); - let rect = !isNodeJs() && !settings.ApproxTextSize && !arg.fast ? getElementRect(elem, 'nopadding') : - { height: curr.fsize * 1.2, width: approximateLabelWidth(s, curr.font, curr.fsize) }; + const rect = !isNodeJs() && !settings.ApproxTextSize && !arg.fast + ? getElementRect(elem, 'nopadding') + : { height: curr.fsize * 1.2, width: approximateLabelWidth(s, curr.font, curr.fsize) }; if (curr.x) elem.attr('x', curr.x); if (curr.y) elem.attr('y', curr.y); - // values used for superscript - curr.last_y1 = curr.y - rect.height*0.8; - curr.last_y2 = curr.y + rect.height*0.2; - - extendPosition(curr.x, curr.last_y1, curr.x + rect.width, curr.last_y2); + extendPosition(curr.x, curr.y - rect.height*0.8, curr.x + rect.width, curr.y + rect.height*0.2); if (!alone) { shiftX(rect.width); + addSpaces(nendspaces); } else if (curr.deco) { elem.attr('text-decoration', curr.deco); delete curr.deco; // inform that decoration was applied } - } + } else + addSpaces(nendspaces); } if (!found) return true; @@ -9008,19 +9267,19 @@ function parseLatex(node, arg, label, curr) { nelements++; if (found.accent) { - let sublabel = extractSubLabel(); + const sublabel = extractSubLabel(); if (sublabel === -1) return false; - let gg = createGG(), - subpos = createSubPos(); + const gg = createGG(), + subpos = createSubPos(); parseLatex(gg, arg, sublabel, subpos); - let minw = curr.fsize*0.6, xpos = 0, - w = subpos.rect.width, - y1 = Math.round(subpos.rect.y1), - dy2 = Math.round(curr.fsize*0.1), dy = dy2*2, - dot = `a${dy2},${dy2},0,0,1,${dy},0a${dy2},${dy2},0,0,1,${-dy},0z`; + const minw = curr.fsize * 0.6, + y1 = Math.round(subpos.rect.y1), + dy2 = Math.round(curr.fsize*0.1), dy = dy2*2, + dot = `a${dy2},${dy2},0,0,1,${dy},0a${dy2},${dy2},0,0,1,${-dy},0z`; + let xpos = 0, w = subpos.rect.width; // shift symbol when it is too small if (found.hasw && (w < minw)) { @@ -9028,21 +9287,21 @@ function parseLatex(node, arg, label, curr) { xpos = (minw - subpos.rect.width) / 2; } - let w5 = Math.round(w*0.5), w3 = Math.round(w*0.3), w2 = w5-w3, w8 = w5+w3; + const w5 = Math.round(w*0.5), w3 = Math.round(w*0.3), w2 = w5-w3, w8 = w5+w3; w = w5*2; positionGNode(subpos, xpos, 0, true); - switch(found.name) { - case '#check{': createPath(gg).attr('d',`M${w2},${y1-dy}L${w5},${y1}L${w8},${y1-dy}`); break; - case '#acute{': createPath(gg).attr('d',`M${w5},${y1}l${dy},${-dy}`); break; - case '#grave{': createPath(gg).attr('d',`M${w5},${y1}l${-dy},${-dy}`); break; - case '#dot{': createPath(gg, true).attr('d',`M${w5-dy2},${y1}${dot}`); break; - case '#ddot{': createPath(gg, true).attr('d',`M${w5-3*dy2},${y1}${dot} M${w5+dy2},${y1}${dot}`); break; - case '#tilde{': createPath(gg).attr('d',`M${w2},${y1} a${w3},${dy},0,0,1,${w3},0 a${w3},${dy},0,0,0,${w3},0`); break; - case '#slash{': createPath(gg).attr('d',`M${w},${y1}L0,${Math.round(subpos.rect.y2)}`); break; - case '#vec{': createPath(gg).attr('d',`M${w2},${y1}H${w8}M${w8-dy},${y1-dy}l${dy},${dy}l${-dy},${dy}`); break; - default: createPath(gg).attr('d',`M${w2},${y1}L${w5},${y1-dy}L${w8},${y1}`); // #hat{ + switch (found.name) { + case '#check{': createPath(gg, `M${w2},${y1-dy}L${w5},${y1}L${w8},${y1-dy}`); break; + case '#acute{': createPath(gg, `M${w5},${y1}l${dy},${-dy}`); break; + case '#grave{': createPath(gg, `M${w5},${y1}l${-dy},${-dy}`); break; + case '#dot{': createPath(gg, `M${w5-dy2},${y1}${dot}`, true); break; + case '#ddot{': createPath(gg, `M${w5-3*dy2},${y1}${dot} M${w5+dy2},${y1}${dot}`, true); break; + case '#tilde{': createPath(gg, `M${w2},${y1} a${w3},${dy},0,0,1,${w3},0 a${w3},${dy},0,0,0,${w3},0`); break; + case '#slash{': createPath(gg, `M${w},${y1}L0,${Math.round(subpos.rect.y2)}`); break; + case '#vec{': createPath(gg, `M${w2},${y1}H${w8}M${w8-dy},${y1-dy}l${dy},${dy}l${-dy},${dy}`); break; + default: createPath(gg, `M${w2},${y1}L${w5},${y1-dy}L${w8},${y1}`); // #hat{ } shiftX(subpos.rect.width); @@ -9051,26 +9310,25 @@ function parseLatex(node, arg, label, curr) { } if (found.twolines) { - curr.twolines = true; - let line1 = extractSubLabel(), line2 = extractSubLabel(true); + const line1 = extractSubLabel(), line2 = extractSubLabel(true); if ((line1 === -1) || (line2 === -1)) return false; - let gg = createGG(), - fscale = (curr.parent && curr.parent.twolines) ? 0.7 : 1, - subpos1 = createSubPos(fscale); + const gg = createGG(), + fscale = (curr.parent && curr.parent.twolines) ? 0.7 : 1, + subpos1 = createSubPos(fscale); parseLatex(gg, arg, line1, subpos1); - let path = (found.twolines == 'line') ? createPath(gg) : null, - subpos2 = createSubPos(fscale); + const path = (found.twolines === 'line') ? createPath(gg) : null, + subpos2 = createSubPos(fscale); parseLatex(gg, arg, line2, subpos2); - let w = Math.max(subpos1.rect.width, subpos2.rect.width), - dw = subpos1.rect.width - subpos2.rect.width, - dy = -curr.fsize*0.35; // approximate position of middle line + const w = Math.max(subpos1.rect.width, subpos2.rect.width), + dw = subpos1.rect.width - subpos2.rect.width, + dy = -curr.fsize*0.35; // approximate position of middle line positionGNode(subpos1, (dw < 0 ? -dw/2 : 0), dy - subpos1.rect.y2, true); @@ -9086,25 +9344,25 @@ function parseLatex(node, arg, label, curr) { } const extractLowUp = name => { - let res = {}; + const res = {}; if (name) { res[name] = extractSubLabel(); if (res[name] === -1) return false; } while (label) { - if (label[0] == '_') { + if (label[0] === '_') { label = label.slice(1); res.low = !res.low ? extractSubLabel('_') : -1; if (res.low === -1) { console.log(`error with ${found.name} low limit`); return false; } - } else if (label[0] == '^') { + } else if (label[0] === '^') { label = label.slice(1); res.up = !res.up ? extractSubLabel('^') : -1; if (res.up === -1) { - console.log(`error with ${found.name} upper limit ` + label); + console.log(`error with ${found.name} upper limit ${label}`); return false; } } else break; @@ -9116,8 +9374,8 @@ function parseLatex(node, arg, label, curr) { const subs = extractLowUp(found.low_up); if (!subs) return false; - let pos_up, pos_low, - x = curr.x, y1 = -curr.fsize, y2 = 0.25*curr.fsize, w1 = 0, w2 = 0; + const x = curr.x, y1 = -curr.fsize, y2 = 0.25*curr.fsize; + let pos_up, pos_low, w1 = 0, w2 = 0; if (subs.up) { pos_up = createSubPos(0.6); @@ -9129,10 +9387,6 @@ function parseLatex(node, arg, label, curr) { parseLatex(currG(), arg, subs.low, pos_low); } - if ((curr.last_y1 !== undefined) && (curr.last_y2 !== undefined)) { - y1 = curr.last_y1; y2 = curr.last_y2; - } - if (pos_up) { positionGNode(pos_up, x, y1 - pos_up.rect.y1 - curr.fsize*0.1); w1 = pos_up.rect.width; @@ -9143,7 +9397,7 @@ function parseLatex(node, arg, label, curr) { w2 = pos_low.rect.width; } - shiftX(Math.max(w1,w2)); + shiftX(Math.max(w1, w2)); continue; } @@ -9151,29 +9405,30 @@ function parseLatex(node, arg, label, curr) { if (found.special) { // this is sum and integral, now make fix height, later can adjust to right-content size - let subs = extractLowUp() || {}, - gg = createGG(), path = createPath(gg), - h = Math.round(curr.fsize*1.7), w = Math.round(curr.fsize), r = Math.round(h*0.1), x_up, x_low; + const subs = extractLowUp() || {}, + gg = createGG(), path = createPath(gg), + h = Math.round(curr.fsize*1.7), w = Math.round(curr.fsize), r = Math.round(h*0.1); + let x_up, x_low; - if (found.name == '#sum') { + if (found.name === '#sum') { x_up = x_low = w/2; - path.attr('d',`M${w},${Math.round(-0.75*h)}h${-w}l${Math.round(0.4*w)},${Math.round(0.3*h)}l${Math.round(-0.4*w)},${Math.round(0.7*h)}h${w}`); + path.attr('d', `M${w},${Math.round(-0.75*h)}h${-w}l${Math.round(0.4*w)},${Math.round(0.3*h)}l${Math.round(-0.4*w)},${Math.round(0.7*h)}h${w}`); } else { x_up = 3*r; x_low = r; - path.attr('d',`M0,${Math.round(0.25*h-r)}a${r},${r},0,0,0,${2*r},0v${2*r-h}a${r},${r},0,1,1,${2*r},0`); + path.attr('d', `M0,${Math.round(0.25*h-r)}a${r},${r},0,0,0,${2*r},0v${2*r-h}a${r},${r},0,1,1,${2*r},0`); // path.attr('transform','skewX(-3)'); could use skewX for italic-like style } extendPosition(curr.x, curr.y - 0.6*h, curr.x + w, curr.y + 0.4*h); if (subs.low) { - let subpos1 = createSubPos(0.6); + const subpos1 = createSubPos(0.6); parseLatex(gg, arg, subs.low, subpos1); positionGNode(subpos1, (x_low - subpos1.rect.width/2), 0.25*h - subpos1.rect.y1, true); } if (subs.up) { - let subpos2 = createSubPos(0.6); + const subpos2 = createSubPos(0.6); parseLatex(gg, arg, subs.up, subpos2); positionGNode(subpos2, (x_up - subpos2.rect.width/2), -0.75*h - subpos2.rect.y2, true); } @@ -9184,35 +9439,36 @@ function parseLatex(node, arg, label, curr) { } if (found.braces) { - let rbrace = found.right, lbrace = rbrace ? found.name : '{', - sublabel = extractSubLabel(false, lbrace, rbrace), - gg = createGG(), - subpos = createSubPos(), - path1 = createPath(gg); + const rbrace = found.right, + lbrace = rbrace ? found.name : '{', + sublabel = extractSubLabel(false, lbrace, rbrace), + gg = createGG(), + subpos = createSubPos(), + path1 = createPath(gg); parseLatex(gg, arg, sublabel, subpos); - let path2 = createPath(gg), - w = Math.max(2, Math.round(curr.fsize*0.2)), - r = subpos.rect, dy = Math.round(r.y2 - r.y1), - r_y1 = Math.round(r.y1), r_width = Math.round(r.width); + const path2 = createPath(gg), + w = Math.max(2, Math.round(curr.fsize*0.2)), + r = subpos.rect, dy = Math.round(r.y2 - r.y1), + r_y1 = Math.round(r.y1), r_width = Math.round(r.width); switch (found.braces) { case '||': - path1.attr('d',`M${w},${r_y1}v${dy}`); - path2.attr('d',`M${3*w+r_width},${r_y1}v${dy}`); + path1.attr('d', `M${w},${r_y1}v${dy}`); + path2.attr('d', `M${3*w+r_width},${r_y1}v${dy}`); break; case '[]': - path1.attr('d',`M${2*w},${r_y1}h${-w}v${dy}h${w}`); - path2.attr('d',`M${2*w+r_width},${r_y1}h${w}v${dy}h${-w}`); + path1.attr('d', `M${2*w},${r_y1}h${-w}v${dy}h${w}`); + path2.attr('d', `M${2*w+r_width},${r_y1}h${w}v${dy}h${-w}`); break; case '{}': - path1.attr('d',`M${2*w},${r_y1} a${w},${w},0,0,0,${-w},${w} v${dy/2-2*w} a${w},${w},0,0,1,${-w},${w} a${w},${w},0,0,1,${w},${w} v${dy/2-2*w} a${w},${w},0,0,0,${w},${w}`); - path2.attr('d',`M${2*w+r_width},${r_y1} a${w},${w},0,0,1,${w},${w} v${dy/2-2*w} a${w},${w},0,0,0,${w},${w} a${w},${w},0,0,0,${-w},${w} v${dy/2-2*w} a${w},${w},0,0,1,${-w},${w}`); + path1.attr('d', `M${2*w},${r_y1}a${w},${w},0,0,0,${-w},${w}v${dy/2-2*w}a${w},${w},0,0,1,${-w},${w}a${w},${w},0,0,1,${w},${w}v${dy/2-2*w}a${w},${w},0,0,0,${w},${w}`); + path2.attr('d', `M${2*w+r_width},${r_y1}a${w},${w},0,0,1,${w},${w}v${dy/2-2*w}a${w},${w},0,0,0,${w},${w}a${w},${w},0,0,0,${-w},${w}v${dy/2-2*w}a${w},${w},0,0,1,${-w},${w}`); break; default: // () - path1.attr('d',`M${w},${r_y1}a${4*dy},${4*dy},0,0,0,0,${dy}`); - path2.attr('d',`M${3*w+r_width},${r_y1}a${4*dy},${4*dy},0,0,1,0,${dy}`); + path1.attr('d', `M${w},${r_y1}a${4*dy},${4*dy},0,0,0,0,${dy}`); + path2.attr('d', `M${3*w+r_width},${r_y1}a${4*dy},${4*dy},0,0,1,0,${dy}`); } positionGNode(subpos, 2*w, 0, true); @@ -9221,30 +9477,25 @@ function parseLatex(node, arg, label, curr) { shiftX(4*w + r.width); - // values used for superscript - curr.last_y1 = r.y1; - curr.last_y2 = r.y2; - continue; } if (found.deco) { - let sublabel = extractSubLabel(), - gg = createGG(), - subpos = createSubPos(); + const sublabel = extractSubLabel(), + gg = createGG(), + subpos = createSubPos(); subpos.deco = found.deco; parseLatex(gg, arg, sublabel, subpos); - let r = subpos.rect; - + const r = subpos.rect; if (subpos.deco) { - let path = createPath(gg), r_width = Math.round(r.width); - switch(subpos.deco) { - case 'underline': path.attr('d',`M0,${Math.round(r.y2)}h${r_width}`); break; - case 'overline': path.attr('d',`M0,${Math.round(r.y1)}h${r_width}`); break; - case 'line-through': path.attr('d',`M0,${Math.round(0.45*r.y1+0.55*r.y2)}h${r_width}`); break; + const path = createPath(gg), r_width = Math.round(r.width); + switch (subpos.deco) { + case 'underline': path.attr('d', `M0,${Math.round(r.y2)}h${r_width}`); break; + case 'overline': path.attr('d', `M0,${Math.round(r.y1)}h${r_width}`); break; + case 'line-through': path.attr('d', `M0,${Math.round(0.45*r.y1+0.55*r.y2)}h${r_width}`); break; } } @@ -9255,13 +9506,13 @@ function parseLatex(node, arg, label, curr) { continue; } - if (found.name == '#bf{' || found.name == '#it{') { - let sublabel = extractSubLabel(); + if (found.name === '#bf{' || found.name === '#it{') { + const sublabel = extractSubLabel(); if (sublabel === -1) return false; - let subpos = createSubPos(); + const subpos = createSubPos(); - if (found.name == '#bf{') + if (found.name === '#bf{') subpos.bold = !subpos.bold; else subpos.italic = !subpos.italic; @@ -9278,29 +9529,29 @@ function parseLatex(node, arg, label, curr) { let foundarg = 0; if (found.arg) { - let pos = label.indexOf(']{'); + const pos = label.indexOf(']{'); if (pos < 0) { console.log('missing argument for ', found.name); return false; } foundarg = label.slice(0, pos); - if (found.arg == 'int') { + if (found.arg === 'int') { foundarg = parseInt(foundarg); if (!Number.isInteger(foundarg)) { console.log('wrong int argument', label.slice(0, pos)); return false; } - } else if (found.arg == 'float') { + } else if (found.arg === 'float') { foundarg = parseFloat(foundarg); if (!Number.isFinite(foundarg)) { console.log('wrong float argument', label.slice(0, pos)); return false; } } label = label.slice(pos + 2); } - if ((found.name == '#kern[') || (found.name == '#lower[')) { - let sublabel = extractSubLabel(); + if ((found.name === '#kern[') || (found.name === '#lower[')) { + const sublabel = extractSubLabel(); if (sublabel === -1) return false; - let subpos = createSubPos(); + const subpos = createSubPos(); parseLatex(currG(), arg, sublabel, subpos); let shiftx = 0, shifty = 0; - if (found.name == 'kern[') shiftx = foundarg; else shifty = foundarg; + if (found.name === 'kern[') shiftx = foundarg; else shifty = foundarg; positionGNode(subpos, curr.x + shiftx * subpos.rect.width, curr.y + shifty * subpos.rect.height); @@ -9309,16 +9560,15 @@ function parseLatex(node, arg, label, curr) { continue; } - if ((found.name == '#color[') || (found.name == '#scale[') || (found.name == '#font[')) { - - let sublabel = extractSubLabel(); + if ((found.name === '#color[') || (found.name === '#scale[') || (found.name === '#font[')) { + const sublabel = extractSubLabel(); if (sublabel === -1) return false; - let subpos = createSubPos(); + const subpos = createSubPos(); - if (found.name == '#color[') + if (found.name === '#color[') subpos.color = curr.painter.getColor(foundarg); - else if (found.name == '#font[') { + else if (found.name === '#font[') { subpos.font = new FontHandler(foundarg); subpos.ufont = true; // mark that custom font is applied } else @@ -9334,10 +9584,11 @@ function parseLatex(node, arg, label, curr) { } if (found.sqrt) { - let sublabel = extractSubLabel(); + const sublabel = extractSubLabel(); if (sublabel === -1) return false; - let gg = createGG(), subpos0, subpos = createSubPos(); + const gg = createGG(), subpos = createSubPos(); + let subpos0; if (found.arg) { subpos0 = createSubPos(0.7); @@ -9345,15 +9596,15 @@ function parseLatex(node, arg, label, curr) { } // placeholder for the sqrt sign - let path = createPath(gg); + const path = createPath(gg); parseLatex(gg, arg, sublabel, subpos); - let r = subpos.rect, - h = Math.round(r.height), - h1 = Math.round(r.height*0.1), - w = Math.round(r.width), midy = Math.round((r.y1 + r.y2)/2), - f2 = Math.round(curr.fsize*0.2), r_y2 = Math.round(r.y2); + const r = subpos.rect, + h = Math.round(r.height), + h1 = Math.round(r.height*0.1), + w = Math.round(r.width), midy = Math.round((r.y1 + r.y2)/2), + f2 = Math.round(curr.fsize*0.2), r_y2 = Math.round(r.y2); if (subpos0) positionGNode(subpos0, 0, midy - subpos0.fsize*0.3, true); @@ -9368,7 +9619,6 @@ function parseLatex(node, arg, label, curr) { continue; } - } return true; @@ -9378,9 +9628,7 @@ function parseLatex(node, arg, label, curr) { * @desc use together with normal elements * @private */ function produceLatex(painter, node, arg) { - - let pos = { lvl: 0, g: node, x: 0, y: 0, dx: 0, dy: -0.1, fsize: arg.font_size, font: arg.font, parent: null, painter }; - + const pos = { lvl: 0, g: node, x: 0, y: 0, dx: 0, dy: -0.1, fsize: arg.font_size, font: arg.font, parent: null, painter }; return parseLatex(node, arg, arg.text, pos); } @@ -9390,25 +9638,25 @@ let _mj_loading; * @desc one need not only to load script but wait for initialization * @private */ async function loadMathjax() { - let loading = (_mj_loading !== undefined); + const loading = _mj_loading !== undefined; - if (!loading && (typeof globalThis.MathJax != 'undefined')) + if (!loading && (typeof globalThis.MathJax !== 'undefined')) return globalThis.MathJax; if (!loading) _mj_loading = []; - let promise = new Promise(resolve => { _mj_loading ? _mj_loading.push(resolve) : resolve(globalThis.MathJax); }); + const promise = new Promise(resolve => { _mj_loading ? _mj_loading.push(resolve) : resolve(globalThis.MathJax); }); if (loading) return promise; - let svg_config = { + const svg = { scale: 1, // global scaling factor for all expressions - minScale: .5, // smallest scaling factor to use + minScale: 0.5, // smallest scaling factor to use mtextInheritFont: false, // true to make mtext elements use surrounding font merrorInheritFont: true, // true to make merror text use surrounding font mathmlSpacing: false, // true for MathML spacing rules, false for TeX rules skipAttributes: {}, // RFDa and other attributes NOT to copy to the output - exFactor: .5, // default size of ex in em units + exFactor: 0.5, // default size of ex in em units displayAlign: 'center', // default for indentalign when set to 'auto' displayIndent: '0', // default for indentshift when set to 'auto' fontCache: 'local', // or 'global' or 'none' @@ -9426,58 +9674,67 @@ async function loadMathjax() { load: ['[tex]/color', '[tex]/upgreek', '[tex]/mathtools', '[tex]/physics'] }, tex: { - packages: {'[+]': ['color', 'upgreek', 'mathtools', 'physics']} + packages: { '[+]': ['color', 'upgreek', 'mathtools', 'physics'] } }, - svg: svg_config, + svg, startup: { ready() { + // eslint-disable-next-line no-undef MathJax.startup.defaultReady(); - let arr = _mj_loading; + const arr = _mj_loading; _mj_loading = undefined; arr.forEach(func => func(globalThis.MathJax)); } } }; - return loadScript(exports.source_dir + '../mathjax/3.2.0/es5/tex-svg.js') + let mj_dir = '../mathjax/3.2.0'; + if (browser.webwindow && exports.source_dir.indexOf('https://root.cern/js') < 0 && exports.source_dir.indexOf('https://jsroot.gsi.de') < 0) + mj_dir = 'mathjax'; + + return loadScript(exports.source_dir + mj_dir + '/es5/tex-svg.js') .catch(() => loadScript('https://cdn.jsdelivr.net/npm/mathjax@3.2.0/es5/tex-svg.js')) .then(() => promise); } - let myJSDOM; - - return _loadJSDOM().then(handle => { myJSDOM = handle.JSDOM; return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }); }).then(mj => { + let JSDOM; + return _loadJSDOM().then(handle => { + JSDOM = handle.JSDOM; + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }); + }).then(mj => { // return Promise with mathjax loading mj.init({ loader: { load: ['input/tex', 'output/svg', '[tex]/color', '[tex]/upgreek', '[tex]/mathtools', '[tex]/physics'] }, tex: { - packages: {'[+]': ['color', 'upgreek', 'mathtools', 'physics']} + packages: { '[+]': ['color', 'upgreek', 'mathtools', 'physics'] } }, - svg: svg_config, + svg, config: { - JSDOM: myJSDOM + JSDOM }, startup: { typeset: false, ready() { - MathJax.startup.registerConstructor('jsdomAdaptor', () => { - return new MathJax._.adaptors.HTMLAdaptor.HTMLAdaptor(new MathJax.config.config.JSDOM().window); + // eslint-disable-next-line no-undef + const mj = MathJax; + + mj.startup.registerConstructor('jsdomAdaptor', () => { + return new mj._.adaptors.HTMLAdaptor.HTMLAdaptor(new mj.config.config.JSDOM().window); }); - MathJax.startup.useAdaptor('jsdomAdaptor', true); - MathJax.startup.defaultReady(); - let arr = _mj_loading; + mj.startup.useAdaptor('jsdomAdaptor', true); + mj.startup.defaultReady(); + const arr = _mj_loading; _mj_loading = undefined; - arr.forEach(func => func(MathJax)); + arr.forEach(func => func(mj)); } } }); return promise; }); - } const math_symbols_map = { @@ -9504,7 +9761,7 @@ const math_symbols_map = { '#doublequote': '"', '#plus': '+', '#minus': '-', - '#\/': '/', + '#/': '/', '#upoint': '.', '#aa': '\\mathring{a}', '#AA': '\\mathring{A}', @@ -9548,149 +9805,149 @@ const math_symbols_map = { '#{': '\\lbrace', '#}': '\\rbrace', ' ': '\\;' - }; - - const mathjax_remap = { - 'upDelta': 'Updelta', - 'upGamma': 'Upgamma', - 'upLambda': 'Uplambda', - 'upOmega': 'Upomega', - 'upPhi': 'Upphi', - 'upPi': 'Uppi', - 'upPsi': 'Uppsi', - 'upSigma': 'Upsigma', - 'upTheta': 'Uptheta', - 'upUpsilon': 'Upupsilon', - 'upXi': 'Upxi', - 'notcong': 'ncong', - 'notgeq': 'ngeq', - 'notgr': 'ngtr', - 'notless': 'nless', - 'notleq': 'nleq', - 'notsucc': 'nsucc', - 'notprec': 'nprec', - 'notsubseteq': 'nsubseteq', - 'notsupseteq': 'nsupseteq', - 'openclubsuit': 'clubsuit', - 'openspadesuit': 'spadesuit', - 'dasharrow': 'dashrightarrow', - 'comp': 'circ', - 'iiintop': 'iiint', - 'iintop': 'iint', - 'ointop': 'oint' - }; - - const mathjax_unicode = { - 'Digamma': 0x3DC, - 'upDigamma': 0x3DC, - 'digamma': 0x3DD, - 'updigamma': 0x3DD, - 'Koppa': 0x3DE, - 'koppa': 0x3DF, - 'upkoppa': 0x3DF, - 'upKoppa': 0x3DE, - 'VarKoppa': 0x3D8, - 'upVarKoppa': 0x3D8, - 'varkoppa': 0x3D9, - 'upvarkoppa': 0x3D9, - 'varkappa': 0x3BA, // not found archaic kappa - use normal - 'upvarkappa': 0x3BA, - 'varbeta': 0x3D0, // not found archaic beta - use normal - 'upvarbeta': 0x3D0, - 'Sampi': 0x3E0, - 'upSampi': 0x3E0, - 'sampi': 0x3E1, - 'upsampi': 0x3E1, - 'Stigma': 0x3DA, - 'upStigma': 0x3DA, - 'stigma': 0x3DB, - 'upstigma': 0x3DB, - 'San': 0x3FA, - 'upSan': 0x3FA, - 'san': 0x3FB, - 'upsan': 0x3FB, - 'Sho': 0x3F7, - 'upSho': 0x3F7, - 'sho': 0x3F8, - 'upsho': 0x3F8, - 'P': 0xB6, - 'aa': 0xB0, - 'bulletdashcirc': 0x22B7, - 'circdashbullet': 0x22B6, - 'downuparrows': 0x21F5, - 'updownarrows': 0x21C5, - 'dashdownarrow': 0x21E3, - 'dashuparrow': 0x21E1, - 'complement': 0x2201, - 'dbar': 0x18C, - 'ddddot': 0x22EF, - 'dddot': 0x22EF, - 'ddots': 0x22F1, - 'defineequal': 0x225D, - 'defineeq': 0x225D, - 'downdownharpoons': 0x2965, - 'downupharpoons': 0x296F, - 'updownharpoons': 0x296E, - 'upupharpoons': 0x2963, - 'hateq': 0x2259, - 'ldbrack': 0x27E6, - 'rdbrack': 0x27E7, - 'leadsfrom': 0x219C, - 'leftsquigarrow': 0x21DC, - 'lightning': 0x2607, - 'napprox': 0x2249, - 'nasymp': 0x226D, - 'nequiv': 0x2262, - 'nsimeq': 0x2244, - 'nsubseteq': 0x2288, - 'nsubset': 0x2284, - 'notapprox': 0x2249, - 'notasymp': 0x226D, - 'notequiv': 0x2262, - 'notni': 0x220C, - 'notsimeq': 0x2244, - 'notsubseteq': 0x2288, - 'notsubset': 0x2284, - 'notsupseteq': 0x2289, - 'notsupset': 0x2285, - 'nsupset': 0x2285, - 'setdif': 0x2216, - 'simarrow': 0x2972, - 't': 0x2040, - 'u': 0x2C7, - 'v': 0x2C7, - 'undercurvearrowright': 0x293B, - 'updbar': 0x18C, - 'wwbar': 0x2015, - 'awointop': 0x2232, - 'awoint': 0x2233, - 'barintop': 0x2A1C, - 'barint': 0x2A1B, - 'cwintop': 0x2231, // no opposite direction, use same - 'cwint': 0x2231, - 'cwointop': 0x2233, - 'cwoint': 0x2232, - 'oiiintop': 0x2230, - 'oiiint': 0x2230, - 'oiintop': 0x222F, - 'oiint': 0x222F, - 'slashintop': 0x2A0F, - 'slashint': 0x2A0F - }; - -const mathjax_asis = ['"', "'", '`', '=', '~']; +}, + +mathjax_remap = { + upDelta: 'Updelta', + upGamma: 'Upgamma', + upLambda: 'Uplambda', + upOmega: 'Upomega', + upPhi: 'Upphi', + upPi: 'Uppi', + upPsi: 'Uppsi', + upSigma: 'Upsigma', + upTheta: 'Uptheta', + upUpsilon: 'Upupsilon', + upXi: 'Upxi', + notcong: 'ncong', + notgeq: 'ngeq', + notgr: 'ngtr', + notless: 'nless', + notleq: 'nleq', + notsucc: 'nsucc', + notprec: 'nprec', + notsubseteq: 'nsubseteq', + notsupseteq: 'nsupseteq', + openclubsuit: 'clubsuit', + openspadesuit: 'spadesuit', + dasharrow: 'dashrightarrow', + comp: 'circ', + iiintop: 'iiint', + iintop: 'iint', + ointop: 'oint' +}, + +mathjax_unicode = { + Digamma: 0x3DC, + upDigamma: 0x3DC, + digamma: 0x3DD, + updigamma: 0x3DD, + Koppa: 0x3DE, + koppa: 0x3DF, + upkoppa: 0x3DF, + upKoppa: 0x3DE, + VarKoppa: 0x3D8, + upVarKoppa: 0x3D8, + varkoppa: 0x3D9, + upvarkoppa: 0x3D9, + varkappa: 0x3BA, // not found archaic kappa - use normal + upvarkappa: 0x3BA, + varbeta: 0x3D0, // not found archaic beta - use normal + upvarbeta: 0x3D0, + Sampi: 0x3E0, + upSampi: 0x3E0, + sampi: 0x3E1, + upsampi: 0x3E1, + Stigma: 0x3DA, + upStigma: 0x3DA, + stigma: 0x3DB, + upstigma: 0x3DB, + San: 0x3FA, + upSan: 0x3FA, + san: 0x3FB, + upsan: 0x3FB, + Sho: 0x3F7, + upSho: 0x3F7, + sho: 0x3F8, + upsho: 0x3F8, + P: 0xB6, + aa: 0xB0, + bulletdashcirc: 0x22B7, + circdashbullet: 0x22B6, + downuparrows: 0x21F5, + updownarrows: 0x21C5, + dashdownarrow: 0x21E3, + dashuparrow: 0x21E1, + complement: 0x2201, + dbar: 0x18C, + ddddot: 0x22EF, + dddot: 0x22EF, + ddots: 0x22F1, + defineequal: 0x225D, + defineeq: 0x225D, + downdownharpoons: 0x2965, + downupharpoons: 0x296F, + updownharpoons: 0x296E, + upupharpoons: 0x2963, + hateq: 0x2259, + ldbrack: 0x27E6, + rdbrack: 0x27E7, + leadsfrom: 0x219C, + leftsquigarrow: 0x21DC, + lightning: 0x2607, + napprox: 0x2249, + nasymp: 0x226D, + nequiv: 0x2262, + nsimeq: 0x2244, + nsubseteq: 0x2288, + nsubset: 0x2284, + notapprox: 0x2249, + notasymp: 0x226D, + notequiv: 0x2262, + notni: 0x220C, + notsimeq: 0x2244, + notsubseteq: 0x2288, + notsubset: 0x2284, + notsupseteq: 0x2289, + notsupset: 0x2285, + nsupset: 0x2285, + setdif: 0x2216, + simarrow: 0x2972, + t: 0x2040, + u: 0x2C7, + v: 0x2C7, + undercurvearrowright: 0x293B, + updbar: 0x18C, + wwbar: 0x2015, + awointop: 0x2232, + awoint: 0x2233, + barintop: 0x2A1C, + barint: 0x2A1B, + cwintop: 0x2231, // no opposite direction, use same + cwint: 0x2231, + cwointop: 0x2233, + cwoint: 0x2232, + oiiintop: 0x2230, + oiiint: 0x2230, + oiintop: 0x222F, + oiint: 0x222F, + slashintop: 0x2A0F, + slashint: 0x2A0F +}, + +mathjax_asis = ['"', '\'', '`', '=', '~']; /** @summary Function translates ROOT TLatex into MathJax format * @private */ function translateMath(str, kind, color, painter) { - - if (kind != 2) { - for (let x in math_symbols_map) + if (kind !== 2) { + for (const x in math_symbols_map) str = str.replace(new RegExp(x, 'g'), math_symbols_map[x]); - for (let x in symbols_map) + for (const x in symbols_map) { if (x.length > 2) str = str.replace(new RegExp(x, 'g'), '\\' + x.slice(1)); + } // replace all #color[]{} occurances let clean = '', first = true; @@ -9698,8 +9955,8 @@ function translateMath(str, kind, color, painter) { let p = str.indexOf('#color['); if ((p < 0) && first) { clean = str; break; } first = false; - if (p != 0) { - let norm = (p < 0) ? str : str.slice(0, p); + if (p !== 0) { + const norm = (p < 0) ? str : str.slice(0, p); clean += norm; if (p < 0) break; } @@ -9707,17 +9964,21 @@ function translateMath(str, kind, color, painter) { str = str.slice(p + 7); p = str.indexOf(']{'); if (p <= 0) break; - let colindx = parseInt(str.slice(0, p)); + const colindx = parseInt(str.slice(0, p)); if (!Number.isInteger(colindx)) break; - let col = painter.getColor(colindx), cnt = 1; + const col = painter.getColor(colindx); + let cnt = 1; str = str.slice(p + 2); p = -1; while (cnt && (++p < str.length)) { - if (str[p] == '{') cnt++; else if (str[p] == '}') cnt--; + if (str[p] === '{') + cnt++; + else if (str[p] === '}') + cnt--; } - if (cnt != 0) break; + if (cnt !== 0) break; - let part = str.slice(0, p); + const part = str.slice(0, p); str = str.slice(p + 1); if (part) clean += `\\color{${col}}{${part}}`; @@ -9725,33 +9986,33 @@ function translateMath(str, kind, color, painter) { str = clean; } else { - if (str == '\\^') str = '\\unicode{0x5E}'; - if (str == '\\vec') str = '\\unicode{0x2192}'; + if (str === '\\^') str = '\\unicode{0x5E}'; + if (str === '\\vec') str = '\\unicode{0x2192}'; str = str.replace(/\\\./g, '\\unicode{0x2E}').replace(/\\\^/g, '\\hat'); - for (let x in mathjax_unicode) + for (const x in mathjax_unicode) str = str.replace(new RegExp(`\\\\\\b${x}\\b`, 'g'), `\\unicode{0x${mathjax_unicode[x].toString(16)}}`); - for(let x in mathjax_asis) + for (const x in mathjax_asis) str = str.replace(new RegExp(`(\\\\${mathjax_asis[x]})`, 'g'), `\\unicode{0x${mathjax_asis[x].charCodeAt(0).toString(16)}}`); - for (let x in mathjax_remap) + for (const x in mathjax_remap) str = str.replace(new RegExp(`\\\\\\b${x}\\b`, 'g'), `\\${mathjax_remap[x]}`); } if (!isStr(color)) return str; // MathJax SVG converter use colors in normal form - //if (color.indexOf('rgb(') >= 0) - // color = color.replace(/rgb/g, '[RGB]') - // .replace(/\(/g, '{') - // .replace(/\)/g, '}'); + // if (color.indexOf('rgb(') >= 0) + // color = color.replace(/rgb/g, '[RGB]') + // .replace(/\(/g, '{') + // .replace(/\)/g, '}'); return `\\color{${color}}{${str}}`; } /** @summary Workaround to fix size attributes in MathJax SVG * @private */ function repairMathJaxSvgSize(painter, mj_node, svg, arg) { - let transform = value => { + const transform = value => { if (!value || !isStr(value) || (value.length < 3)) return null; - let p = value.indexOf('ex'); + const p = value.indexOf('ex'); if ((p < 0) || (p !== value.length - 2)) return null; value = parseFloat(value.slice(0, p)); return Number.isFinite(value) ? value * arg.font.size * 0.5 : null; @@ -9761,12 +10022,11 @@ function repairMathJaxSvgSize(painter, mj_node, svg, arg) { height = transform(svg.getAttribute('height')), valign = svg.getAttribute('style'); - if (valign && (valign.length > 18) && valign.indexOf('vertical-align:') == 0) { - let p = valign.indexOf('ex;'); - valign = ((p > 0) && (p == valign.length - 3)) ? transform(valign.slice(16, valign.length - 1)) : null; - } else { + if (valign && (valign.length > 18) && valign.indexOf('vertical-align:') === 0) { + const p = valign.indexOf('ex;'); + valign = ((p > 0) && (p === valign.length - 3)) ? transform(valign.slice(16, valign.length - 1)) : null; + } else valign = null; - } width = (!width || (width <= 0.5)) ? 1 : Math.round(width); height = (!height || (height <= 0.5)) ? 1 : Math.round(height); @@ -9776,7 +10036,7 @@ function repairMathJaxSvgSize(painter, mj_node, svg, arg) { svg.removeAttribute('style'); if (!isNodeJs()) { - let box = getElementRect(mj_node, 'bbox'); + const box = getElementRect(mj_node, 'bbox'); width = 1.05 * box.width; height = 1.05 * box.height; } @@ -9793,59 +10053,63 @@ function applyAttributesToMathJax(painter, mj_node, svg, arg, font_size, svg_fac mh = parseInt(svg.attr('height')); if (Number.isInteger(mh) && Number.isInteger(mw)) { - if (svg_factor > 0.) { + if (svg_factor > 0) { mw = mw / svg_factor; mh = mh / svg_factor; svg.attr('width', Math.round(mw)).attr('height', Math.round(mh)); } } else { - let box = getElementRect(mj_node, 'bbox'); // sizes before rotation + const box = getElementRect(mj_node, 'bbox'); // sizes before rotation mw = box.width || mw || 100; mh = box.height || mh || 10; } - if ((svg_factor > 0.) && arg.valign) arg.valign = arg.valign / svg_factor; + if ((svg_factor > 0) && arg.valign) arg.valign = arg.valign / svg_factor; if (arg.valign === null) arg.valign = (font_size - mh) / 2; - let sign = { x: 1, y: 1 }, nx = 'x', ny = 'y'; - if (arg.rotate == 180) { + const sign = { x: 1, y: 1 }; + let nx = 'x', ny = 'y'; + if (arg.rotate === 180) sign.x = sign.y = -1; - } else if ((arg.rotate == 270) || (arg.rotate == 90)) { - sign.x = (arg.rotate == 270) ? -1 : 1; + else if ((arg.rotate === 270) || (arg.rotate === 90)) { + sign.x = (arg.rotate === 270) ? -1 : 1; sign.y = -sign.x; nx = 'y'; ny = 'x'; // replace names to which align applied } - if (arg.align[0] == 'middle') + if (arg.align[0] === 'middle') arg[nx] += sign.x * (arg.width - mw) / 2; - else if (arg.align[0] == 'end') + else if (arg.align[0] === 'end') arg[nx] += sign.x * (arg.width - mw); - if (arg.align[1] == 'middle') + if (arg.align[1] === 'middle') arg[ny] += sign.y * (arg.height - mh) / 2; - else if (arg.align[1] == 'bottom') + else if (arg.align[1] === 'bottom') arg[ny] += sign.y * (arg.height - mh); - else if (arg.align[1] == 'bottom-base') + else if (arg.align[1] === 'bottom-base') arg[ny] += sign.y * (arg.height - mh - arg.valign); - let trans = `translate(${arg.x},${arg.y})`; - if (arg.rotate) trans += ` rotate(${arg.rotate})`; + let trans = makeTranslate(arg.x, arg.y) || ''; + if (arg.rotate) { + if (trans) trans += ' '; + trans += `rotate(${arg.rotate})`; + } - mj_node.attr('transform', trans).attr('visibility', null); + mj_node.attr('transform', trans || null).attr('visibility', null); } /** @summary Produce text with MathJax * @private */ async function produceMathjax(painter, mj_node, arg) { - let mtext = translateMath(arg.text, arg.latex, arg.color, painter), - options = { em: arg.font.size, ex: arg.font.size/2, family: arg.font.name, scale: 1, containerWidth: -1, lineWidth: 100000 }; + const mtext = translateMath(arg.text, arg.latex, arg.color, painter), + options = { em: arg.font.size, ex: arg.font.size/2, family: arg.font.name, scale: 1, containerWidth: -1, lineWidth: 100000 }; return loadMathjax() - .then(() => MathJax.tex2svgPromise(mtext, options)) + .then(mj => mj.tex2svgPromise(mtext, options)) .then(elem => { // when adding element to new node, it will be removed from original parent - let svg = elem.querySelector('svg'); + const svg = elem.querySelector('svg'); mj_node.append(() => svg); @@ -9859,14 +10123,14 @@ async function produceMathjax(painter, mj_node, arg) { /** @summary Just typeset HTML node with MathJax * @private */ async function typesetMathjax(node) { - return loadMathjax().then(() => MathJax.typesetPromise(node ? [node] : undefined)); + return loadMathjax().then(mj => mj.typesetPromise(node ? [node] : undefined)); } /** @summary Covert value between 0 and 1 into hex, used for colors coding * @private */ -function toHex(num,scale) { - let s = Math.round(num*(scale || 255)).toString(16); - return s.length == 1 ? '0'+s : s; +function toHex(num, scale) { + const s = Math.round(num*(scale || 255)).toString(16); + return s.length === 1 ? '0'+s : s; } /** @summary list of global root colors @@ -9876,7 +10140,7 @@ let gbl_colors_list = []; /** @summary Generates all root colors, used also in jstests to reset colors * @private */ function createRootColors() { - let colorMap = ['white', 'black', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan', '#59d454', '#5954d9', 'white']; + const colorMap = ['white', 'black', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan', '#59d454', '#5954d9', 'white']; colorMap[110] = 'white'; const moreCol = [ @@ -9892,10 +10156,10 @@ function createRootColors() { { n: 920, s: 'cdcdcd9a9a9a666666333333' }]; moreCol.forEach(entry => { - let s = entry.s; + const s = entry.s; for (let n = 0; n < s.length; n += 6) { - let num = entry.n + n / 6; - colorMap[num] = '#' + s.slice(n,n+6); + const num = entry.n + n / 6; + colorMap[num] = '#' + s.slice(n, n+6); } }); @@ -9911,10 +10175,10 @@ function getRootColors() { /** @summary Produces rgb code for TColor object * @private */ function getRGBfromTColor(col) { - if (col?._typename != clTColor) return null; + if (col?._typename !== clTColor) return null; let rgb = '#' + toHex(col.fRed) + toHex(col.fGreen) + toHex(col.fBlue); - if ((col.fAlpha !== undefined) && (col.fAlpha !== 1.)) + if ((col.fAlpha !== undefined) && (col.fAlpha !== 1)) rgb += toHex(col.fAlpha); switch (rgb) { @@ -9930,10 +10194,27 @@ function getRGBfromTColor(col) { return rgb; } +/** @ummary Return list of grey colors for the original array + * @private */ +function getGrayColors(rgb_array) { + const gray_colors = []; + + if (!rgb_array) rgb_array = getRootColors(); + + for (let n = 0; n < rgb_array.length; ++n) { + if (!rgb_array[n]) continue; + const rgb = color(rgb_array[n]), + gray = 0.299*rgb.r + 0.587*rgb.g + 0.114*rgb.b; + rgb.r = rgb.g = rgb.b = gray; + gray_colors[n] = rgb.hex(); + } + + return gray_colors; +} /** @summary Add new colors from object array * @private */ -function extendRootColors(jsarr, objarr) { +function extendRootColors(jsarr, objarr, grayscale) { if (!jsarr) { jsarr = []; for (let n = 0; n < gbl_colors_list.length; ++n) @@ -9946,19 +10227,20 @@ function extendRootColors(jsarr, objarr) { if (objarr._typename && objarr.arr) { rgb_array = []; for (let n = 0; n < objarr.arr.length; ++n) { - let col = objarr.arr[n]; - if (col?._typename != clTColor) continue; + const col = objarr.arr[n]; + if (col?._typename !== clTColor) continue; if ((col.fNumber >= 0) && (col.fNumber <= 10000)) rgb_array[col.fNumber] = getRGBfromTColor(col); } } - for (let n = 0; n < rgb_array.length; ++n) - if (rgb_array[n] && (jsarr[n] != rgb_array[n])) + for (let n = 0; n < rgb_array.length; ++n) { + if (rgb_array[n] && (jsarr[n] !== rgb_array[n])) jsarr[n] = rgb_array[n]; + } - return jsarr; + return grayscale ? getGrayColors(jsarr) : jsarr; } /** @ummary Set global list of colors. @@ -9982,9 +10264,10 @@ function getColor(indx) { * @private */ function findColor(name) { if (!name) return -1; - for (let indx = 0; indx < gbl_colors_list.length; ++indx) - if (gbl_colors_list[indx] == name) + for (let indx = 0; indx < gbl_colors_list.length; ++indx) { + if (gbl_colors_list[indx] === name) return indx; + } return -1; } @@ -9995,7 +10278,7 @@ function findColor(name) { * @private */ function addColor(rgb, lst) { if (!lst) lst = gbl_colors_list; - let indx = lst.indexOf(rgb); + const indx = lst.indexOf(rgb); if (indx >= 0) return indx; lst.push(rgb); return lst.length-1; @@ -10010,13 +10293,13 @@ function addColor(rgb, lst) { class ColorPalette { /** @summary constructor */ - constructor(arr) { - this.palette = arr; + constructor(arr, grayscale) { + this.palette = grayscale ? getGrayColors(arr) : arr; } /** @summary Returns color index which correspond to contour index of provided length */ calcColorIndex(i, len) { - let plen = this.palette.length, theColor = Math.floor((i + 0.99) * plen / (len - 1)); + const plen = this.palette.length, theColor = Math.floor((i + 0.99) * plen / (len - 1)); return (theColor > plen - 1) ? plen - 1 : theColor; } @@ -10031,6 +10314,196 @@ class ColorPalette { } // class ColorPalette +function createDefaultPalette(grayscale) { + const hue2rgb = (p, q, t) => { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2/3 - t) * 6; + return p; + }, HLStoRGB = (h, l, s) => { + const q = (l < 0.5) ? l * (1 + s) : l + s - l * s, + p = 2 * l - q, + r = hue2rgb(p, q, h + 1/3), + g = hue2rgb(p, q, h), + b = hue2rgb(p, q, h - 1/3); + return '#' + toHex(r) + toHex(g) + toHex(b); + }, minHue = 0, maxHue = 280, maxPretty = 50, palette = []; + for (let i = 0; i < maxPretty; ++i) { + const hue = (maxHue - (i + 1) * ((maxHue - minHue) / maxPretty)) / 360; + palette.push(HLStoRGB(hue, 0.5, 1)); + } + return new ColorPalette(palette, grayscale); +} + +function createGrayPalette() { + const palette = []; + for (let i = 0; i < 50; ++i) { + const code = toHex((i+2)/60); + palette.push('#'+code+code+code); + } + return new ColorPalette(palette); +} + +/* eslint-disable comma-spacing */ + + +/** @summary Create color palette + * @private */ +function getColorPalette(id, grayscale) { + id = id || settings.Palette; + if ((id > 0) && (id < 10)) return createGrayPalette(); + if (id < 51) return createDefaultPalette(grayscale); + if (id > 113) id = 57; + const stops = [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]; + let rgb; + switch (id) { + // Deep Sea + case 51: rgb = [[0,9,13,17,24,32,27,25,29],[0,0,0,2,37,74,113,160,221],[28,42,59,78,98,129,154,184,221]]; break; + // Grey Scale + case 52: rgb = [[0,32,64,96,128,160,192,224,255],[0,32,64,96,128,160,192,224,255],[0,32,64,96,128,160,192,224,255]]; break; + // Dark Body Radiator + case 53: rgb = [[0,45,99,156,212,230,237,234,242],[0,0,0,45,101,168,238,238,243],[0,1,1,3,9,8,11,95,230]]; break; + // Two-color hue (dark blue through neutral gray to bright yellow) + case 54: rgb = [[0,22,44,68,93,124,160,192,237],[0,16,41,67,93,125,162,194,241],[97,100,99,99,93,68,44,26,74]]; break; + // Rain Bow + case 55: rgb = [[0,5,15,35,102,196,208,199,110],[0,48,124,192,206,226,97,16,0],[99,142,198,201,90,22,13,8,2]]; break; + // Inverted Dark Body Radiator + case 56: rgb = [[242,234,237,230,212,156,99,45,0],[243,238,238,168,101,45,0,0,0],[230,95,11,8,9,3,1,1,0]]; break; + // Bird (default, keep float for backward compatibility) + case 57: rgb = [[53.091,15.096,19.89,5.916,45.951,135.1755,208.743,253.878,248.982],[42.432,91.7745,128.5455,163.6845,183.039,191.046,186.864,200.481,250.716],[134.9715,221.442,213.8175,201.807,163.8375,118.881,89.2245,50.184,13.7445]]; break; + // Cubehelix + case 58: rgb = [[0,24,2,54,176,236,202,194,255],[0,29,92,129,117,120,176,236,255],[0,68,80,34,57,172,252,245,255]]; break; + // Green Red Violet + case 59: rgb = [[13,23,25,63,76,104,137,161,206],[95,67,37,21,0,12,35,52,79],[4,3,2,6,11,22,49,98,208]]; break; + // Blue Red Yellow + case 60: rgb = [[0,61,89,122,143,160,185,204,231],[0,0,0,0,14,37,72,132,235],[0,140,224,144,4,5,6,9,13]]; break; + // Ocean + case 61: rgb = [[14,7,2,0,5,11,55,131,229],[105,56,26,1,42,74,131,171,229],[2,21,35,60,92,113,160,185,229]]; break; + // Color Printable On Grey + case 62: rgb = [[0,0,0,70,148,231,235,237,244],[0,0,0,0,0,69,67,216,244],[0,102,228,231,177,124,137,20,244]]; break; + // Alpine + case 63: rgb = [[50,56,63,68,93,121,165,192,241],[66,81,91,96,111,128,155,189,241],[97,91,75,65,77,103,143,167,217]]; break; + // Aquamarine + case 64: rgb = [[145,166,167,156,131,114,101,112,132],[158,178,179,181,163,154,144,152,159],[190,199,201,192,176,169,160,166,190]]; break; + // Army + case 65: rgb = [[93,91,99,108,130,125,132,155,174],[126,124,128,129,131,121,119,153,173],[103,94,87,85,80,85,107,120,146]]; break; + // Atlantic + case 66: rgb = [[24,40,69,90,104,114,120,132,103],[29,52,94,127,150,162,159,151,101],[29,52,96,132,162,181,184,186,131]]; break; + // Aurora + case 67: rgb = [[46,38,61,92,113,121,132,150,191],[46,36,40,69,110,135,131,92,34],[46,80,74,70,81,105,165,211,225]]; break; + // Avocado + case 68: rgb = [[0,4,12,30,52,101,142,190,237],[0,40,86,121,140,172,187,213,240],[0,9,14,18,21,23,27,35,101]]; break; + // Beach + case 69: rgb = [[198,206,206,211,198,181,161,171,244],[103,133,150,172,178,174,163,175,244],[49,54,55,66,91,130,184,224,244]]; break; + // Black Body + case 70: rgb = [[243,243,240,240,241,239,186,151,129],[0,46,99,149,194,220,183,166,147],[6,8,36,91,169,235,246,240,233]]; break; + // Blue Green Yellow + case 71: rgb = [[22,19,19,25,35,53,88,139,210],[0,32,69,108,135,159,183,198,215],[77,96,110,116,110,100,90,78,70]]; break; + // Brown Cyan + case 72: rgb = [[68,116,165,182,189,180,145,111,71],[37,82,135,178,204,225,221,202,147],[16,55,105,147,196,226,232,224,178]]; break; + // CMYK + case 73: rgb = [[61,99,136,181,213,225,198,136,24],[149,140,96,83,132,178,190,135,22],[214,203,168,135,110,100,111,113,22]]; break; + // Candy + case 74: rgb = [[76,120,156,183,197,180,162,154,140],[34,35,42,69,102,137,164,188,197],[64,69,78,105,142,177,205,217,198]]; break; + // Cherry + case 75: rgb = [[37,102,157,188,196,214,223,235,251],[37,29,25,37,67,91,132,185,251],[37,32,33,45,66,98,137,187,251]]; break; + // Coffee + case 76: rgb = [[79,100,119,137,153,172,192,205,250],[63,79,93,103,115,135,167,196,250],[51,59,66,61,62,70,110,160,250]]; break; + // Dark Rain Bow + case 77: rgb = [[43,44,50,66,125,172,178,155,157],[63,63,85,101,138,163,122,51,39],[121,101,58,44,47,55,57,44,43]]; break; + // Dark Terrain + case 78: rgb = [[0,41,62,79,90,87,99,140,228],[0,57,81,93,85,70,71,125,228],[95,91,91,82,60,43,44,112,228]]; break; + // Fall + case 79: rgb = [[49,59,72,88,114,141,176,205,222],[78,72,66,57,59,75,106,142,173],[78,55,46,40,39,39,40,41,47]]; break; + // Fruit Punch + case 80: rgb = [[243,222,201,185,165,158,166,187,219],[94,108,132,135,125,96,68,51,61],[7,9,12,19,45,89,118,146,118]]; break; + // Fuchsia + case 81: rgb = [[19,44,74,105,137,166,194,206,220],[19,28,40,55,82,110,159,181,220],[19,42,68,96,129,157,188,203,220]]; break; + // Grey Yellow + case 82: rgb = [[33,44,70,99,140,165,199,211,216],[38,50,76,105,140,165,191,189,167],[55,67,97,124,140,166,163,129,52]]; break; + // Green Brown Terrain + case 83: rgb = [[0,33,73,124,136,152,159,171,223],[0,43,92,124,134,126,121,144,223],[0,43,68,76,73,64,72,114,223]]; break; + // Green Pink + case 84: rgb = [[5,18,45,124,193,223,205,128,49],[48,134,207,230,193,113,28,0,7],[6,15,41,121,193,226,208,130,49]]; break; + // Island + case 85: rgb = [[180,106,104,135,164,188,189,165,144],[72,126,154,184,198,207,205,190,179],[41,120,158,188,194,181,145,100,62]]; break; + // Lake + case 86: rgb = [[57,72,94,117,136,154,174,192,215],[0,33,68,109,140,171,192,196,209],[116,137,173,201,200,201,203,190,187]]; break; + // Light Temperature + case 87: rgb = [[31,71,123,160,210,222,214,199,183],[40,117,171,211,231,220,190,132,65],[234,214,228,222,210,160,105,60,34]]; break; + // Light Terrain + case 88: rgb = [[123,108,109,126,154,172,188,196,218],[184,138,130,133,154,175,188,196,218],[208,130,109,99,110,122,150,171,218]]; break; + // Mint + case 89: rgb = [[105,106,122,143,159,172,176,181,207],[252,197,194,187,174,162,153,136,125],[146,133,144,155,163,167,166,162,174]]; break; + // Neon + case 90: rgb = [[171,141,145,152,154,159,163,158,177],[236,143,100,63,53,55,44,31,6],[59,48,46,44,42,54,82,112,179]]; break; + // Pastel + case 91: rgb = [[180,190,209,223,204,228,205,152,91],[93,125,147,172,181,224,233,198,158],[236,218,160,133,114,132,162,220,218]]; break; + // Pearl + case 92: rgb = [[225,183,162,135,115,111,119,145,211],[205,177,166,135,124,117,117,132,172],[186,165,155,135,126,130,150,178,226]]; break; + // Pigeon + case 93: rgb = [[39,43,59,63,80,116,153,177,223],[39,43,59,74,91,114,139,165,223],[39,50,59,70,85,115,151,176,223]]; break; + // Plum + case 94: rgb = [[0,38,60,76,84,89,101,128,204],[0,10,15,23,35,57,83,123,199],[0,11,22,40,63,86,97,94,85]]; break; + // Red Blue + case 95: rgb = [[94,112,141,165,167,140,91,49,27],[27,46,88,135,166,161,135,97,58],[42,52,81,106,139,158,155,137,116]]; break; + // Rose + case 96: rgb = [[30,49,79,117,135,151,146,138,147],[63,60,72,90,94,94,68,46,16],[18,28,41,56,62,63,50,36,21]]; break; + // Rust + case 97: rgb = [[0,30,63,101,143,152,169,187,230],[0,14,28,42,58,61,67,74,91],[39,26,21,18,15,14,14,13,13]]; break; + // Sandy Terrain + case 98: rgb = [[149,140,164,179,182,181,131,87,61],[62,70,107,136,144,138,117,87,74],[40,38,45,49,49,49,38,32,34]]; break; + // Sienna + case 99: rgb = [[99,112,148,165,179,182,183,183,208],[39,40,57,79,104,127,148,161,198],[15,16,18,33,51,79,103,129,177]]; break; + // Solar + case 100: rgb = [[99,116,154,174,200,196,201,201,230],[0,0,8,32,58,83,119,136,173],[5,6,7,9,9,14,17,19,24]]; break; + // South West + case 101: rgb = [[82,106,126,141,155,163,142,107,66],[62,44,69,107,135,152,149,132,119],[39,25,31,60,73,68,49,72,188]]; break; + // Starry Night + case 102: rgb = [[18,29,44,72,116,158,184,208,221],[27,46,71,105,146,177,189,190,183],[39,55,80,108,130,133,124,100,76]]; break; + // Sunset + case 103: rgb = [[0,48,119,173,212,224,228,228,245],[0,13,30,47,79,127,167,205,245],[0,68,75,43,16,22,55,128,245]]; break; + // Temperature Map + case 104: rgb = [[34,70,129,187,225,226,216,193,179],[48,91,147,194,226,229,196,110,12],[234,212,216,224,206,110,53,40,29]]; break; + // Thermometer + case 105: rgb = [[30,55,103,147,174,203,188,151,105],[0,65,138,182,187,175,121,53,9],[191,202,212,208,171,140,97,57,30]]; break; + // Valentine + case 106: rgb = [[112,97,113,125,138,159,178,188,225],[16,17,24,37,56,81,110,136,189],[38,35,46,59,78,103,130,152,201]]; break; + // Visible Spectrum + case 107: rgb = [[18,72,5,23,29,201,200,98,29],[0,0,43,167,211,117,0,0,0],[51,203,177,26,10,9,8,3,0]]; break; + // Water Melon + case 108: rgb = [[19,42,64,88,118,147,175,187,205],[19,55,89,125,154,169,161,129,70],[19,32,47,70,100,128,145,130,75]]; break; + // Cool + case 109: rgb = [[33,31,42,68,86,111,141,172,227],[255,175,145,106,88,55,15,0,0],[255,205,202,203,208,205,203,206,231]]; break; + // Copper + case 110: rgb = [[0,25,50,79,110,145,181,201,254],[0,16,30,46,63,82,101,124,179],[0,12,21,29,39,49,61,74,103]]; break; + // Gist Earth + case 111: rgb = [[0,13,30,44,72,120,156,200,247],[0,36,84,117,141,153,151,158,247],[0,94,100,82,56,66,76,131,247]]; break; + // Viridis + case 112: rgb = [[26,51,43,33,28,35,74,144,246],[9,24,55,87,118,150,180,200,222],[30,96,112,114,112,101,72,35,0]]; break; + // Cividis + case 113: rgb = [[0,5,65,97,124,156,189,224,255],[32,54,77,100,123,148,175,203,234],[77,110,107,111,120,119,111,94,70]]; break; + default: return createDefaultPalette(); + } + + const NColors = 255, Red = rgb[0], Green = rgb[1], Blue = rgb[2], palette = []; + + for (let g = 1; g < stops.length; g++) { + // create the colors... + const nColorsGradient = Math.round(Math.floor(NColors*stops[g]) - Math.floor(NColors*stops[g-1])); + for (let c = 0; c < nColorsGradient; c++) { + const col = '#' + toHex(Red[g-1] + c * (Red[g] - Red[g-1]) / nColorsGradient, 1) + + toHex(Green[g-1] + c * (Green[g] - Green[g-1]) / nColorsGradient, 1) + + toHex(Blue[g-1] + c * (Blue[g] - Blue[g-1]) / nColorsGradient, 1); + palette.push(col); + } + } + + return new ColorPalette(palette, grayscale); +} + createRootColors(); const root_markers = [ @@ -10080,7 +10553,7 @@ class TAttMarkerHandler { * @param {number} args.size - marker size * @param {number} [args.refsize] - when specified and marker size < 1, marker size will be calculated relative to that size */ setArgs(args) { - if (isObject(args) && (typeof args.fMarkerStyle == 'number')) args = { attr: args }; + if (isObject(args) && (typeof args.fMarkerStyle === 'number')) args = { attr: args }; if (args.attr) { if (args.color === undefined) @@ -10097,6 +10570,11 @@ class TAttMarkerHandler { this._configure(); } + /** @summary Set usage flag of attribute */ + setUsed(flag) { + this.used = flag; + } + /** @summary Reset position, used for optimization of drawing of multiple markers * @private */ resetPos() { this.lastx = this.lasty = null; } @@ -10111,12 +10589,13 @@ class TAttMarkerHandler { return `M${(x + this.x0).toFixed(this.ndig)},${(y + this.y0).toFixed(this.ndig)}${this.marker}`; // use optimized handling with relative position - let xx = Math.round(x), yy = Math.round(y), mv = `M${xx},${yy}`; + const xx = Math.round(x), yy = Math.round(y); + let mv = `M${xx},${yy}`; if (this.lastx !== null) { - if ((xx == this.lastx) && (yy == this.lasty)) { + if ((xx === this.lastx) && (yy === this.lasty)) mv = ''; // pathological case, but let exclude it - } else { - let m2 = `m${xx-this.lastx},${yy - this.lasty}`; + else { + const m2 = `m${xx-this.lastx},${yy - this.lasty}`; if (m2.length < mv.length) mv = m2; } } @@ -10146,8 +10625,7 @@ class TAttMarkerHandler { /** @summary Prepare object to create marker * @private */ - _configure() { - + _configure() { this.x0 = this.y0 = 0; if ((this.style === 1) || (this.style === 777)) { @@ -10161,23 +10639,23 @@ class TAttMarkerHandler { this.optimized = false; - let marker_kind = root_markers[this.style] ?? 104, - shape = marker_kind % 100; + const marker_kind = root_markers[this.style] ?? 104, + shape = marker_kind % 100; this.fill = (marker_kind >= 100); this.scale = this.refsize || 8; // v7 defines refsize as 1 or pad height - let size = this.getFullSize(); + const size = this.getFullSize(); this.ndig = (size > 7) ? 0 : ((size > 2) ? 1 : 2); - if (shape == 30) this.ndig++; // increase precision for star - let s1 = size.toFixed(this.ndig), - s2 = (size/2).toFixed(this.ndig), - s3 = (size/3).toFixed(this.ndig), - s4 = (size/4).toFixed(this.ndig), - s8 = (size/8).toFixed(this.ndig), - s38 = (size*3/8).toFixed(this.ndig); + if (shape === 30) this.ndig++; // increase precision for star + let s1 = size.toFixed(this.ndig); + const s2 = (size/2).toFixed(this.ndig), + s3 = (size/3).toFixed(this.ndig), + s4 = (size/4).toFixed(this.ndig), + s8 = (size/8).toFixed(this.ndig), + s38 = (size*3/8).toFixed(this.ndig); switch (shape) { case 1: // dot @@ -10224,11 +10702,12 @@ class TAttMarkerHandler { this.x0 = this.y0 = size / 6; this.marker = `h${s3}v-${s3}h-${s3}v-${s3}h-${s3}v${s3}h-${s3}v${s3}h${s3}v${s3}h${s3}z`; break; - case 30: // star + case 30: { // star this.y0 = -size / 2; - let s56 = (size*5/6).toFixed(this.ndig), s58 = (size*5/8).toFixed(this.ndig); + const s56 = (size*5/6).toFixed(this.ndig), s58 = (size*5/8).toFixed(this.ndig); this.marker = `l${s3},${s1}l-${s56},-${s58}h${s1}l-${s56},${s58}z`; break; + } case 32: // triangle-down this.y0 = size / 2; this.marker = `l-${s2},-${s1}h${s1}z`; @@ -10293,6 +10772,7 @@ class TAttMarkerHandler { /** @summary Apply marker styles to created element */ apply(selection) { + this.used = true; selection.style('stroke', this.stroke ? this.color : 'none') .style('fill', this.fill ? this.color : 'none'); } @@ -10353,7 +10833,7 @@ class TAttFillHandler { if ((args.color === undefined) && (args.attr.fFillColor !== undefined)) args.color = args.attr.fFillColor; } - let was_changed = this.changed; // preserve changed state + const was_changed = this.changed; // preserve changed state this.change(args.color, args.pattern, args.svg, args.color_as_svg, args.painter); this.changed = was_changed; } @@ -10378,17 +10858,22 @@ class TAttFillHandler { * @desc If empty, alternative color will be provided * @param {string} [altern] - alternative color which returned when fill color not exists * @private */ - getFillColorAlt(altern) { return this.color && (this.color != 'none') ? this.color : altern; } + getFillColorAlt(altern) { return this.color && (this.color !== 'none') ? this.color : altern; } /** @summary Returns true if color not specified or fill style not specified */ empty() { - let fill = this.getFillColor(); - return !fill || (fill == 'none'); + const fill = this.getFillColor(); + return !fill || (fill === 'none'); + } + + /** @summary Set usage flag of attribute */ + setUsed(flag) { + this.used = flag; } /** @summary Returns true if fill attributes has real color */ hasColor() { - return this.color && (this.color != 'none'); + return this.color && (this.color !== 'none'); } /** @summary Set solid fill color as fill pattern @@ -10408,7 +10893,7 @@ class TAttFillHandler { * @param {string} [solid_color] - when specified, checks if fill color matches */ isSolid(solid_color) { if (this.pattern !== 1001) return false; - return !solid_color || (solid_color == this.color); + return !solid_color || (solid_color === this.color); } /** @summary Method used when color or pattern were changed with OpenUi5 widgets @@ -10428,12 +10913,12 @@ class TAttFillHandler { * @param {selection} svg - top canvas element for pattern storages * @param {string} [color_as_svg] - when color is string, interpret as normal SVG color * @param {object} [painter] - when specified, used to extract color by index */ - change(color, pattern, svg, color_as_svg, painter) { + change(color$1, pattern, svg, color_as_svg, painter) { delete this.pattern_url; this.changed = true; - if ((color !== undefined) && Number.isInteger(parseInt(color)) && !color_as_svg) - this.colorindx = parseInt(color); + if ((color$1 !== undefined) && Number.isInteger(parseInt(color$1)) && !color_as_svg) + this.colorindx = parseInt(color$1); if ((pattern !== undefined) && Number.isInteger(parseInt(pattern))) { this.pattern = parseInt(pattern); @@ -10441,12 +10926,12 @@ class TAttFillHandler { delete this.antialias; } - if ((this.pattern == 1000) && (this.colorindx === 0)) { + if ((this.pattern === 1000) && (this.colorindx === 0)) { this.pattern_url = 'white'; return true; } - if (this.pattern == 1000) + if (this.pattern === 1000) this.pattern = 1001; if (this.pattern < 1001) { @@ -10462,11 +10947,10 @@ class TAttFillHandler { let indx = this.colorindx; if (color_as_svg) { - this.color = color; - if (color != 'none') indx = color$1(color).hex().slice(1); // fictional index produced from color code - } else { + this.color = color$1; + if (color$1 !== 'none') indx = color(color$1).hex().slice(1); // fictional index produced from color code + } else this.color = painter ? painter.getColor(indx) : getColor(indx); - } if (!isStr(this.color)) this.color = 'none'; @@ -10478,21 +10962,10 @@ class TAttFillHandler { return true; } - if (!svg || svg.empty() || (this.pattern < 3000) || (this.color == 'none')) return false; + if (!svg || svg.empty() || (this.pattern < 3000) || (this.color === 'none')) return false; let id = `pat_${this.pattern}_${indx}`, - defs = svg.select('.canvas_defs'); - - if (defs.empty()) - defs = svg.insert('svg:defs', ':first-child').attr('class', 'canvas_defs'); - - this.pattern_url = `url(#${id})`; - this.antialias = false; - - if (!defs.select('.' + id).empty()) - return true; - - let lines = '', lfill = null, fills = '', fills2 = '', w = 2, h = 2; + lines = '', lfill = null, fills = '', fills2 = '', w = 2, h = 2; switch (this.pattern) { case 3001: w = h = 2; fills = 'M0,0h1v1h-1zM1,1h1v1h-1z'; break; @@ -10528,37 +11001,45 @@ class TAttFillHandler { case 3023: w = h = 8; fills = 'M4,0h4v4zM8,4v4h-4z'; fills2 = 'M4,0L0,4L4,8L8,4Z'; break; case 3024: w = h = 16; fills = 'M0,8v8h2v-8zM8,0v8h2v-8M4,14v2h12v-2z'; fills2 = 'M0,2h8v6h4v-6h4v12h-12v-6h-4z'; break; case 3025: w = h = 18; fills = 'M5,13v-8h8ZM18,0v18h-18l5,-5h8v-8Z'; break; - default: + default: { if ((this.pattern > 3025) && (this.pattern < 3100)) { // same as 3002, see TGX11.cxx, line 2234 w = 4; h = 2; fills = 'M1,0h1v1h-1zM3,1h1v1h-1z'; break; } - let code = this.pattern % 1000, - k = code % 10, - j = ((code - k) % 100) / 10, - i = (code - j * 10 - k) / 100; + const code = this.pattern % 1000, + k = code % 10, + j = ((code - k) % 100) / 10, + i = (code - j * 10 - k) / 100; if (!i) break; - let hatches_spacing = Math.round(Math.max(0.5, gStyle.fHatchesSpacing)*2) * 6, - sz = i * hatches_spacing, pos, step, x1, x2, y1, y2, max; // axis distance between lines + // use flexible hatches only possible when single pattern is used, + // otherwise it is not possible to adjust pattern dimension that both hatches match with each other + const use_new = (j === k) || (j === 0) || (j === 5) || (j === 9) || (k === 0) || (k === 5) || (k === 9), + pp = painter?.getPadPainter(), + scale_size = pp ? Math.max(pp.getPadWidth(), pp.getPadHeight()) : 600, + spacing_original = Math.max(0.1, gStyle.fHatchesSpacing * scale_size * 0.001), + hatches_spacing = Math.max(1, Math.round(spacing_original)) * 6, + sz = i * hatches_spacing; // axis distance between lines + + id += use_new ? `_hn${Math.round(spacing_original*100)}` : `_ho${hatches_spacing}`; w = h = 6 * sz; // we use at least 6 steps - const produce = (dy, swap) => { - pos = []; step = sz; y1 = 0; max = h; + const produce_old = (dy, swap) => { + const pos = []; + let step = sz, y1 = 0, max = h, y2, x1, x2; // reduce step for smaller angles to keep normal distance approx same if (Math.abs(dy) < 3) step = Math.round(sz / 12 * 9); - if (dy == 0) { + if (dy === 0) { step = Math.round(sz / 12 * 8); y1 = step / 2; - } else if (dy > 0) { + } else if (dy > 0) max -= step; - } else { + else y1 = step; - } while (y1 <= max) { y2 = y1 + dy * step; @@ -10570,64 +11051,143 @@ class TAttFillHandler { x2 = Math.round((h - y1) / (y2 - y1) * w); pos.push(0, y1, x2, h); pos.push(w, h - y1, w - x2, 0); - } else { + } else pos.push(0, y1, w, y2); - } y1 += step; } for (let k = 0; k < pos.length; k += 4) { - if (swap) { x1 = pos[k+1]; y1 = pos[k]; x2 = pos[k+3]; y2 = pos[k+2]; } - else { x1 = pos[k]; y1 = pos[k+1]; x2 = pos[k+2]; y2 = pos[k+3]; } - lines += `M${x1},${y1}`; - if (y2 == y1) - lines += `h${x2-x1}`; - else if (x2 == x1) - lines += `v${y2-y1}`; - else - lines += `L${x2},${y2}`; + if (swap) { + x1 = pos[k+1]; + y1 = pos[k]; + x2 = pos[k+3]; + y2 = pos[k+2]; + } else { + x1 = pos[k]; + y1 = pos[k+1]; + x2 = pos[k+2]; + y2 = pos[k+3]; + } + lines += `M${x1},${y1}`; + if (y2 === y1) + lines += `h${x2-x1}`; + else if (x2 === x1) + lines += `v${y2-y1}`; + else + lines += `L${x2},${y2}`; } - }; + }, + + produce_new = (_aa, _bb, angle, swapx) => { + if ((angle === 0) || (angle === 90)) { + const dy = i*spacing_original*3, + nsteps = Math.round(h / dy), + dyreal = h / nsteps; + let yy = dyreal/2; + + while (yy < h) { + if (angle === 0) + lines += `M0,${Math.round(yy)}h${w}`; + else + lines += `M${Math.round(yy)},0v${h}`; + yy += dyreal; + } + + return; + } + + const a = angle/180*Math.PI, + dy = i*spacing_original*3/Math.cos(a), + hside = Math.tan(a) * w, + hside_steps = Math.round(hside / dy), + dyreal = hside / hside_steps, + nsteps = Math.floor(h / dyreal); + + h = Math.round(nsteps * dyreal); + + let yy = nsteps * dyreal; + + while (Math.abs(yy-h) < 0.1) yy -= dyreal; + + while (yy + hside > 0) { + let x1 = 0, y1 = yy, x2 = w, y2 = yy + hside; + + if (y1 < -0.00001) { + // cut at the begin + x1 = -y1 / hside * w; + y1 = 0; + } else if (y2 > h) { + // cut at the end + x2 = (h - y1) / hside * w; + y2 = h; + } + + if (swapx) { + x1 = w - x1; + x2 = w - x2; + } + + lines += `M${Math.round(x1)},${Math.round(y1)}L${Math.round(x2)},${Math.round(y2)}`; + yy -= dyreal; + } + }, + + func = use_new ? produce_new : produce_old; + + let horiz = false, vertical = false; switch (j) { - case 0: produce(0); break; - case 1: produce(1); break; - case 2: produce(2); break; - case 3: produce(3); break; - case 4: produce(6); break; - case 6: produce(3, true); break; - case 7: produce(2, true); break; - case 8: produce(1, true); break; - case 9: produce(0, true); break; + case 0: horiz = true; break; + case 1: func(1, false, 10); break; + case 2: func(2, false, 20); break; + case 3: func(3, false, 30); break; + case 4: func(6, false, 45); break; + case 6: func(3, true, 60); break; + case 7: func(2, true, 70); break; + case 8: func(1, true, 80); break; + case 9: vertical = true; break; } switch (k) { - case 0: if (j) produce(0); break; - case 1: produce(-1); break; - case 2: produce(-2); break; - case 3: produce(-3); break; - case 4: produce(-6); break; - case 6: produce(-3, true); break; - case 7: produce(-2, true); break; - case 8: produce(-1, true); break; - case 9: if (j != 9) produce(0, true); break; + case 0: horiz = true; break; + case 1: func(-1, false, 10, true); break; + case 2: func(-2, false, 20, true); break; + case 3: func(-3, false, 30, true); break; + case 4: func(-6, false, 45, true); break; + case 6: func(-3, true, 60, true); break; + case 7: func(-2, true, 70, true); break; + case 8: func(-1, true, 80, true); break; + case 9: vertical = true; break; } + if (horiz) func(0, false, 0); + if (vertical) func(0, true, 90); + break; + } } if (!fills && !lines) return false; - let patt = defs.append('svg:pattern') - .attr('id', id).attr('class', id).attr('patternUnits', 'userSpaceOnUse') - .attr('width', w).attr('height', h); + this.pattern_url = `url(#${id})`; + this.antialias = false; + + let defs = svg.selectChild('.canvas_defs'); + if (defs.empty()) + defs = svg.insert('svg:defs', ':first-child').attr('class', 'canvas_defs'); + + if (defs.selectChild('.' + id).empty()) { + const patt = defs.append('svg:pattern') + .attr('id', id).attr('class', id).attr('patternUnits', 'userSpaceOnUse') + .attr('width', w).attr('height', h); - if (fills2) { - let col = rgb(this.color); - col.r = Math.round((col.r + 255) / 2); col.g = Math.round((col.g + 255) / 2); col.b = Math.round((col.b + 255) / 2); - patt.append('svg:path').attr('d', fills2).style('fill', col); + if (fills2) { + const col = rgb(this.color); + col.r = Math.round((col.r + 255) / 2); col.g = Math.round((col.g + 255) / 2); col.b = Math.round((col.b + 255) / 2); + patt.append('svg:path').attr('d', fills2).style('fill', col); + } + if (fills) patt.append('svg:path').attr('d', fills).style('fill', this.color); + if (lines) patt.append('svg:path').attr('d', lines).style('stroke', this.color).style('stroke-width', gStyle.fHatchesLineWidth || 1).style('fill', lfill); } - if (fills) patt.append('svg:path').attr('d', fills).style('fill', this.color); - if (lines) patt.append('svg:path').attr('d', lines).style('stroke', this.color).style('stroke-width', gStyle.fHatchesLineWidth).style('fill', lfill); return true; } @@ -10649,7 +11209,7 @@ class TAttFillHandler { * @private */ saveToStyle(name_color, name_pattern) { if (name_color) { - let indx = this.colorindx ?? findColor(this.color); + const indx = this.colorindx ?? findColor(this.color); if (indx >= 0) gStyle[name_color] = indx; } if (name_pattern) @@ -10688,18 +11248,18 @@ class TAttLineHandler { setArgs(args) { if (args.attr) { this.color_index = args.attr.fLineColor; - args.color = args.color0 || (args.painter ? args.painter.getColor(this.color_index) : getColor(this.color_index)); + args.color = args.color0 || (args.painter?.getColor(this.color_index) ?? getColor(this.color_index)); if (args.width === undefined) args.width = args.attr.fLineWidth; if (args.style === undefined) args.style = args.attr.fLineStyle; } else if (isStr(args.color)) { if ((args.color !== 'none') && !args.width) args.width = 1; - } else if (typeof args.color == 'number') { + } else if (typeof args.color === 'number') { this.color_index = args.color; - args.color = args.painter ? args.painter.getColor(args.color) : getColor(args.color); + args.color = args.painter?.getColor(args.color) ?? getColor(args.color); } if (args.width === undefined) - args.width = (args.color && args.color != 'none') ? 1 : 0; + args.width = (args.color && args.color !== 'none') ? 1 : 0; this.color = (args.width === 0) ? 'none' : args.color; this.width = args.width; @@ -10733,7 +11293,12 @@ class TAttLineHandler { } /** @summary returns true if line attribute is empty and will not be applied. */ - empty() { return this.color == 'none'; } + empty() { return this.color === 'none'; } + + /** @summary Set usage flag of attribute */ + setUsed(flag) { + this.used = flag; + } /** @summary set border parameters, used for rect drawing */ setBorder(rx, ry) { @@ -10746,30 +11311,32 @@ class TAttLineHandler { * @param {object} selection - d3.js selection */ apply(selection) { this.used = true; - if (this.empty()) + if (this.empty()) { selection.style('stroke', null) .style('stroke-width', null) .style('stroke-dasharray', null); - else + } else { selection.style('stroke', this.color) .style('stroke-width', this.width) .style('stroke-dasharray', this.pattern); + } } /** @summary Applies line and border attribute to selection. * @param {object} selection - d3.js selection */ applyBorder(selection) { this.used = true; - if (this.empty()) + if (this.empty()) { selection.style('stroke', null) .style('stroke-width', null) .style('stroke-dasharray', null) .attr('rx', null).attr('ry', null); - else + } else { selection.style('stroke', this.color) .style('stroke-width', this.width) .style('stroke-dasharray', this.pattern) .attr('rx', this.rx || null).attr('ry', this.ry || null); + } } /** @summary Change line attributes */ @@ -10805,7 +11372,7 @@ class TAttLineHandler { /** @summary Save attributes values to gStyle */ saveToStyle(name_color, name_width, name_style) { if (name_color) { - let indx = (this.color_index !== undefined) ? this.color_index : findColor(this.color); + const indx = (this.color_index !== undefined) ? this.color_index : findColor(this.color); if (indx >= 0) gStyle[name_color] = indx; } @@ -10824,6 +11391,123 @@ function getSvgLineStyle(indx) { return root_line_styles[indx]; } +/** + * @summary Handle for text attributes + * @private + */ + +class TAttTextHandler { + + /** @summary constructor + * @param {object} attr - attributes, see {@link TAttTextHandler#setArgs} */ + constructor(args) { + this.used = true; + if (args._typename && (args.fTextFont !== undefined)) args = { attr: args }; + this.setArgs(args); + } + + /** @summary Set text attributes. + * @param {object} args - specify attributes by different ways + * @param {object} args.attr - TAttText object with appropriate data members or + * @param {object} args.attr_alt - alternative TAttText object with appropriate data members if values are 0 + * @param {string} args.color - color in html like rgb(255,0,0) or 'red' or '#ff0000' + * @param {number} args.align - text align + * @param {number} args.angle - text angle + * @param {number} args.font - font index + * @param {number} args.size - text size */ + setArgs(args) { + if (args.attr) { + args.font = args.attr.fTextFont || args.attr_alt?.fTextFont || 0; + args.size = args.attr.fTextSize || args.attr_alt?.fTextSize || 0; + this.color_index = args.attr.fTextColor || args.attr_alt?.fTextColor || 0; + args.color = args.painter?.getColor(this.color_index) ?? getColor(this.color_index); + args.align = args.attr.fTextAlign || args.attr_alt?.fTextAlign || 0; + args.angle = args.attr.fTextAngle || args.attr_alt?.fTextAngle || 0; + } else if (typeof args.color === 'number') { + this.color_index = args.color; + args.color = args.painter?.getColor(args.color) ?? getColor(args.color); + } + + this.font = args.font; + this.size = args.size; + this.color = args.color; + this.align = args.align; + this.angle = args.angle; + + this.angle_used = false; + this.align_used = false; + } + + /** @summary returns true if line attribute is empty and will not be applied. */ + empty() { return this.color === 'none'; } + + /** @summary Change text attributes */ + change(font, size, color, align, angle) { + if (font !== undefined) + this.font = font; + if (size !== undefined) + this.size = size; + if (color !== undefined) { + if (this.color !== color) + delete this.color_index; + this.color = color; + } + if (align !== undefined) + this.align = align; + if (angle !== undefined) + this.angle = angle; + this.changed = true; + } + + /** @summary Method used when color or pattern were changed with OpenUi5 widgets. + * @private */ + verifyDirectChange(/* painter */) { + this.change(parseInt(this.font), parseFloat(this.size), this.color, parseInt(this.align), parseInt(this.angle)); + } + + /** @summary Create argument for drawText method */ + createArg(arg) { + if (!arg) arg = {}; + this.align_used = !arg.noalign && !arg.align; + if (this.align_used) + arg.align = this.align; + this.angle_used = !arg.norotate; + if (this.angle_used && this.angle) + arg.rotate = -this.angle; // SVG rotation angle has different sign + arg.color = this.color || 'black'; + return arg; + } + + /** @summary Provides pixel size */ + getSize(w, h, fact, zero_size) { + if (this.size >= 1) + return Math.round(this.size); + if (!w) w = 1000; + if (!h) h = w; + if (!fact) fact = 1; + + return Math.round((this.size || zero_size || 0) * Math.min(w, h) * fact); + } + + /** @summary Returns alternating size - which defined by sz1 variable */ + getAltSize(sz1, h) { + if (!sz1) sz1 = this.size; + return Math.round(sz1 >= 1 ? sz1 : sz1 * h); + } + + /** @summary Get font index - without precision */ + getGedFont() { return Math.floor(this.font/10); } + + /** @summary Change text font from GED */ + setGedFont(value) { + const v = parseInt(value); + if ((v > 0) && (v < 17)) + this.change(v*10 + (this.font % 10)); + return this.font; + } + +} // class TAttTextHandler + /** * @summary Painter class for ROOT objects * @@ -10863,9 +11547,11 @@ class ObjectPainter extends BasePainter { } /** @summary Returns pad name where object is drawn */ - getPadName() { - return this.pad_name || ''; - } + getPadName() { return this.pad_name || ''; } + + /** @summary Indicates that drawing runs in batch mode + * @private */ + isBatchMode() { return isBatchMode() ? true : (this.getCanvPainter()?.isBatchMode() ?? false); } /** @summary Assign snapid to the painter * @desc Identifier used to communicate with server side and identifies object on the server @@ -10876,13 +11562,12 @@ class ObjectPainter extends BasePainter { * @desc Remove object drawing and (in case of main painter) also main HTML components * @protected */ cleanup() { - this.removeG(); let keep_origin = true; if (this.isMainPainter()) { - let pp = this.getPadPainter(); + const pp = this.getPadPainter(); if (!pp || (pp.normal_canvas === false)) keep_origin = false; } @@ -10912,8 +11597,11 @@ class ObjectPainter extends BasePainter { /** @summary Returns drawn object */ getObject() { return this.draw_object; } + /** @summary Returns drawn object name */ + getObjectName() { return this.getObject()?.fName ?? ''; } + /** @summary Returns drawn object class name */ - getClassName() { return this.getObject()?._typename || ''; } + getClassName() { return this.getObject()?._typename ?? ''; } /** @summary Checks if drawn object matches with provided typename * @param {string|object} arg - typename (or object with _typename member) @@ -10931,10 +11619,10 @@ class ObjectPainter extends BasePainter { setItemName(name, opt, hpainter) { super.setItemName(name, opt, hpainter); if (this.no_default_title || !name) return; - let can = this.getCanvSvg(); + const can = this.getCanvSvg(); if (!can.empty()) can.select('title').text(name); else this.selectDom().attr('title', name); - let cp = this.getCanvPainter(); + const cp = this.getCanvPainter(); if (cp && ((cp === this) || (this.isMainPainter() && (cp === this.getPadPainter())))) cp.drawItemNameOnCanvas(name); } @@ -10944,28 +11632,31 @@ class ObjectPainter extends BasePainter { storeDrawOpt(original) { if (!this.options) return; if (!original) original = ''; - let pp = original.indexOf(';;'); + const pp = original.indexOf(';;'); if (pp >= 0) original = original.slice(0, pp); this.options.original = original; this.options_store = Object.assign({}, this.options); } /** @summary Return actual draw options as string + * @param ignore_pad - do not include pad settings into histogram draw options * @desc if options are not modified - returns original string which was specified for object draw */ - getDrawOpt() { + getDrawOpt(ignore_pad) { if (!this.options) return ''; if (isFunc(this.options.asString)) { - let changed = false, pp = this.getPadPainter(); - if (!this.options_store || pp?._interactively_changed) { - changed = true; - } else { - for (let k in this.options) + let changed = false; + const pp = this.getPadPainter(); + if (!this.options_store || pp?._interactively_changed) + changed = true; + else { + for (const k in this.options) { if (this.options[k] !== this.options_store[k]) changed = true; + } } - if (changed) - return this.options.asString(this.isMainPainter(), pp?.getRootPad()); + if (changed && isFunc(this.options.asString)) + return this.options.asString(this.isMainPainter(), ignore_pad ? null : pp?.getRootPad()); } return this.options.original || ''; // nothing better, return original draw option @@ -10974,14 +11665,13 @@ class ObjectPainter extends BasePainter { /** @summary Returns array with supported draw options as configured in draw.mjs * @desc works via pad painter and only when module was loaded */ getSupportedDrawOptions() { - let pp = this.getPadPainter(), - obj = this.getObject(); + const pp = this.getPadPainter(), + cl = this.getClassName(); - if (!obj?._typename || !pp?.getObjectDrawSettings) + if (!cl || !isFunc(pp?.getObjectDrawSettings)) return []; - let sett = pp.getObjectDrawSettings('ROOT.' + obj._typename, 'nosame'); - return sett?.opts; + return pp.getObjectDrawSettings(prROOT + cl, 'nosame')?.opts; } /** @summary Central place to update objects drawing @@ -10994,11 +11684,12 @@ class ObjectPainter extends BasePainter { * only way to control how object can be update while requested from the server * @protected */ redrawObject(obj, opt) { - if (!this.updateObject(obj,opt)) return false; - let current = document.body.style.cursor; + if (!this.updateObject(obj, opt)) return false; + const doc = getDocument(), + current = doc.body.style.cursor; document.body.style.cursor = 'wait'; - let res = this.redrawPad(); - document.body.style.cursor = current; + const res = this.redrawPad(); + doc.body.style.cursor = current; return res || true; } @@ -11018,11 +11709,8 @@ class ObjectPainter extends BasePainter { * Such string typically used as object tooltip. * If result string larger than 20 symbols, it will be cutted. */ getObjectHint() { - let res = this.getItemName(), obj = this.getObject(); - if (!res) res = obj && obj.fName ? obj.fName : ''; - if (!res) res = this.getClassName(); - if (res.length > 20) res = res.slice(0, 17) + '...'; - return res; + const hint = this.getItemName() || this.getObjectName() || this.getClassName() || ''; + return (hint.length <= 20) ? hint : hint.slice(0, 17) + '...'; } /** @summary returns color from current list of colors @@ -11044,7 +11732,7 @@ class ObjectPainter extends BasePainter { addColor(color) { if (!this.root_colors) this.root_colors = this.getCanvPainter()?.root_colors || getRootColors(); - let indx = this.root_colors.indexOf(color); + const indx = this.root_colors.indexOf(color); if (indx >= 0) return indx; this.root_colors.push(color); return this.root_colors.length - 1; @@ -11054,8 +11742,8 @@ class ObjectPainter extends BasePainter { * @desc If available, checks in canvas painter * @private */ isTooltipAllowed() { - let src = this.getCanvPainter() || this; - return src.tooltip_allowed ? true : false; + const src = this.getCanvPainter() || this; + return src.tooltip_allowed; } /** @summary change tooltip allowed flag @@ -11063,29 +11751,23 @@ class ObjectPainter extends BasePainter { * @private */ setTooltipAllowed(on) { if (on === undefined) on = true; - let src = this.getCanvPainter() || this; - src.tooltip_allowed = (on == 'toggle') ? !src.tooltip_allowed : on; + const src = this.getCanvPainter() || this; + src.tooltip_allowed = (on === 'toggle') ? !src.tooltip_allowed : on; } /** @summary Checks if draw elements were resized and drawing should be updated. * @desc Redirects to {@link TPadPainter#checkCanvasResize} * @private */ checkResize(arg) { - let p = this.getCanvPainter(); - if (!p) return false; - // only canvas should be checked - p.checkCanvasResize(arg); - return true; + return this.getCanvPainter()?.checkCanvasResize(arg); } /** @summary removes element with object drawing * @desc generic method to delete all graphical elements, associated with the painter * @protected */ removeG() { - if (this.draw_g) { - this.draw_g.remove(); - delete this.draw_g; - } + this.draw_g?.remove(); + delete this.draw_g; } /** @summary Returns created element used for object drawing @@ -11099,20 +11781,18 @@ class ObjectPainter extends BasePainter { * @param {boolean|string} [frame_layer] - when specified, element will be created inside frame layer, otherwise in the pad * @protected */ createG(frame_layer) { - let layer; if (frame_layer) { - let frame = this.getFrameSvg(); + const frame = this.getFrameSvg(); if (frame.empty()) { console.error('Not found frame to create g element inside'); return frame; } if (!isStr(frame_layer)) frame_layer = 'main_layer'; - layer = frame.select('.' + frame_layer); - } else { + layer = frame.selectChild('.' + frame_layer); + } else layer = this.getLayerSvg('primitives_layer'); - } if (this.draw_g && this.draw_g.node().parentNode !== layer.node()) { console.log('g element changes its layer!!'); @@ -11140,6 +11820,19 @@ class ObjectPainter extends BasePainter { return this.draw_g; } + /** @summary Bring draw element to the front */ + bringToFront(check_online) { + if (!this.draw_g) return; + const prnt = this.draw_g.node().parentNode; + prnt?.appendChild(this.draw_g.node()); + + if (!check_online || !this.snapid) return; + const pp = this.getPadPainter(); + if (!pp?.snapid) return; + + this.getCanvPainter()?.sendWebsocket('POPOBJ:'+JSON.stringify([pp.snapid.toString(), this.snapid.toString()])); + } + /** @summary Canvas main svg element * @return {object} d3 selection with canvas svg * @protected */ @@ -11156,8 +11849,8 @@ class ObjectPainter extends BasePainter { let c = this.getCanvSvg(); if (!pad_name || c.empty()) return c; - let cp = c.property('pad_painter'); - if (cp && cp.pads_cache && cp.pads_cache[pad_name]) + const cp = c.property('pad_painter'); + if (cp?.pads_cache && cp.pads_cache[pad_name]) return select(cp.pads_cache[pad_name]); c = c.select('.primitives_layer .__root_pad_' + pad_name); @@ -11168,6 +11861,34 @@ class ObjectPainter extends BasePainter { return c; } + /** @summary Assign unique identifier for the painter + * @private */ + getUniqueId() { + if (this._unique_painter_id === undefined) + this._unique_painter_id = internals.id_counter++; // assign unique identifier + return this._unique_painter_id; + } + + /** @summary Assign secondary id + * @private */ + setSecondaryId(main) { + this._main_painter_id = main.getUniqueId(); + } + + /** @summary Check if this is secondary painter + * @private */ + isSecondaryPainter(main) { + return this._main_painter_id === main.getUniqueId(); + } + + /** @summary Provides identifier on server for requested sublement */ + getSnapId(subelem) { + if (!this.snapid) + return ''; + + return this.snapid.toString() + (subelem ? '#'+subelem : ''); + } + /** @summary Method selects immediate layer under canvas/pad main element * @param {string} name - layer name, exits 'primitives_layer', 'btns_layer', 'info_layer' * @param {string} [pad_name] - pad name; current pad name used by default @@ -11176,19 +11897,12 @@ class ObjectPainter extends BasePainter { let svg = this.getPadSvg(pad_name); if (svg.empty()) return svg; - if (name.indexOf('prim#') == 0) { - svg = svg.select('.primitives_layer'); + if (name.indexOf('prim#') === 0) { + svg = svg.selectChild('.primitives_layer'); name = name.slice(5); } - let node = svg.node().firstChild; - while (node) { - let elem = select(node); - if (elem.classed(name)) return elem; - node = node.nextSibling; - } - - return select(null); + return svg.selectChild('.' + name); } /** @summary Method selects current pad name @@ -11196,9 +11910,9 @@ class ObjectPainter extends BasePainter { * @return {string} previous selected pad or actual pad when new_name not specified * @private */ selectCurrentPad(new_name) { - let svg = this.getCanvSvg(); + const svg = this.getCanvSvg(); if (svg.empty()) return ''; - let curr = svg.property('current_pad'); + const curr = svg.property('current_pad'); if (new_name !== undefined) svg.property('current_pad', new_name); return curr; } @@ -11207,14 +11921,14 @@ class ObjectPainter extends BasePainter { * @param {string} [pad_name] pad name or use current pad by default * @protected */ getPadPainter(pad_name) { - let elem = this.getPadSvg(isStr(pad_name) ? pad_name : undefined); + const elem = this.getPadSvg(isStr(pad_name) ? pad_name : undefined); return elem.empty() ? null : elem.property('pad_painter'); } /** @summary returns canvas painter * @protected */ getCanvPainter() { - let elem = this.getCanvSvg(); + const elem = this.getCanvSvg(); return elem.empty() ? null : elem.property('pad_painter'); } @@ -11225,8 +11939,8 @@ class ObjectPainter extends BasePainter { * @param {boolean} [noround] - if set, return coordinates will not be rounded * @protected */ getAxisToSvgFunc(isndc, nornd) { - let func = { isndc, nornd }, - use_frame = this.draw_g && this.draw_g.property('in_frame'); + const func = { isndc, nornd }, + use_frame = this.draw_g?.property('in_frame'); if (use_frame) func.main = this.getFramePainter(); if (func.main?.grx && func.main?.gry) { if (nornd) { @@ -11237,7 +11951,7 @@ class ObjectPainter extends BasePainter { func.y = function(y) { return Math.round(this.main.gry(y)); }; } } else if (!use_frame) { - let pp = this.getPadPainter(); + const pp = this.getPadPainter(); if (!isndc) func.pad = pp?.getRootPad(true); // need for NDC conversion func.padw = pp?.getPadWidth() ?? 10; func.x = function(value) { @@ -11263,7 +11977,6 @@ class ObjectPainter extends BasePainter { console.error(`Problem to create functor for ${this.getClassName()}`); func.x = () => 0; func.y = () => 0; - } return func; } @@ -11277,7 +11990,7 @@ class ObjectPainter extends BasePainter { * @return {number} value of requested coordiantes * @protected */ axisToSvg(axis, value, ndc, noround) { - let func = this.getAxisToSvgFunc(ndc, noround); + const func = this.getAxisToSvgFunc(ndc, noround); return func[axis](value); } @@ -11289,19 +12002,17 @@ class ObjectPainter extends BasePainter { * @return {number} value of requested coordiantes * @protected */ svgToAxis(axis, coord, ndc) { - let use_frame = this.draw_g && this.draw_g.property('in_frame'); + const use_frame = this.draw_g?.property('in_frame'); - if (use_frame) { - let main = this.getFramePainter(); - return main?.revertAxis(axis, coord) ?? 0; - } + if (use_frame) + return this.getFramePainter()?.revertAxis(axis, coord) ?? 0; - let pp = this.getPadPainter(), - value = !pp ? 0 : ((axis == 'y') ? (1 - coord / pp.getPadHeight()) : coord / pp.getPadWidth()), - pad = (ndc || !pp) ? null : pp.getRootPad(true); + const pp = this.getPadPainter(), + pad = (ndc || !pp) ? null : pp.getRootPad(true); + let value = !pp ? 0 : ((axis === 'y') ? (1 - coord / pp.getPadHeight()) : coord / pp.getPadWidth()); if (pad) { - if (axis == 'y') { + if (axis === 'y') { value = pad.fY1 + value * (pad.fY2 - pad.fY1); if (pad.fLogy) value = Math.pow(10, value); } else { @@ -11316,11 +12027,11 @@ class ObjectPainter extends BasePainter { /** @summary Returns svg element for the frame in current pad * @protected */ getFrameSvg(pad_name) { - let layer = this.getLayerSvg('primitives_layer', pad_name); + const layer = this.getLayerSvg('primitives_layer', pad_name); if (layer.empty()) return layer; let node = layer.node().firstChild; while (node) { - let elem = select(node); + const elem = select(node); if (elem.classed('root_frame')) return elem; node = node.nextSibling; } @@ -11342,7 +12053,7 @@ class ObjectPainter extends BasePainter { getMainPainter(not_store) { let res = this._main_painter; if (!res) { - let pp = this.getPadPainter(); + const pp = this.getPadPainter(); res = pp ? pp.getMainPainter() : this.getTopPainter(); if (!res) res = null; if (!not_store) @@ -11360,10 +12071,10 @@ class ObjectPainter extends BasePainter { * Should not be used by pad/canvas painters, but rather by objects which are drawing axis * @protected */ setAsMainPainter(force) { - let pp = this.getPadPainter(); + const pp = this.getPadPainter(); if (!pp) - this.setTopPainter(); //fallback on BasePainter method - else + this.setTopPainter(); // fallback on BasePainter method + else pp.setMainPainter(this, force); } @@ -11373,7 +12084,7 @@ class ObjectPainter extends BasePainter { * @protected */ addToPadPrimitives(pad_name) { if (pad_name !== undefined) this.setPadName(pad_name); - let pp = this.getPadPainter(pad_name); // important - pad_name must be here, otherwise PadPainter class confuses itself + const pp = this.getPadPainter(pad_name); // important - pad_name must be here, otherwise PadPainter class confuses itself if (!pp || (pp === this)) return false; @@ -11389,11 +12100,10 @@ class ObjectPainter extends BasePainter { /** @summary Remove painter from pad list of painters * @protected */ removeFromPadPrimitives() { - let pp = this.getPadPainter(); - + const pp = this.getPadPainter(); if (!pp || (pp === this)) return false; - let k = pp.painters.indexOf(this); + const k = pp.painters.indexOf(this); if (k >= 0) pp.painters.splice(k, 1); return true; } @@ -11451,6 +12161,29 @@ class ObjectPainter extends BasePainter { return handler; } + /** @summary Creates text attributes object. + * @param {object} args - either TAttText or see constructor arguments of {@link TAttTextHandler} + * @protected */ + createAttText(args) { + if (!isObject(args)) + args = { std: true }; + else if (args.fTextFont !== undefined && args.fTextSize !== undefined && args.fTextSize !== undefined) + args = { attr: args, std: false }; + + if (args.std === undefined) args.std = true; + if (args.painter === undefined) args.painter = this; + + let handler = args.std ? this.textatt : null; + + if (!handler) + handler = new TAttTextHandler(args); + else if (!handler.changed || args.force) + handler.setArgs(args); + + if (args.std) this.textatt = handler; + return handler; + } + /** @summary Creates fill attributes object. * @desc Method dedicated to create fill attributes, bound to canvas SVG * otherwise newly created patters will not be usable in the canvas @@ -11492,11 +12225,11 @@ class ObjectPainter extends BasePainter { * @private */ forEachPainter(userfunc, kind) { // iterate over all painters from pad list - let pp = this.getPadPainter(); - if (pp) { + const pp = this.getPadPainter(); + if (pp) pp.forEachPainterInPad(userfunc, kind); - } else { - let painter = this.getTopPainter(); + else { + const painter = this.getTopPainter(); if (painter && (kind !== 'pads')) userfunc(painter); } } @@ -11506,19 +12239,18 @@ class ObjectPainter extends BasePainter { * @return {Promise} when completed * @private */ async interactiveRedraw(arg, info, subelem) { - let reason, res; - if (isStr(info) && (info.indexOf('exec:') != 0)) + if (isStr(info) && (info.indexOf('exec:') !== 0)) reason = info; - if (arg == 'pad') + if (arg === 'pad') res = this.redrawPad(reason); else if (arg !== false) res = this.redraw(reason); return getPromise(res).then(() => { // inform GED that something changes - let canp = this.getCanvPainter(); + const canp = this.getCanvPainter(); if (isFunc(canp?.producePadEvent)) canp.producePadEvent('redraw', this.getPadPainter(), this, null, subelem); @@ -11536,15 +12268,13 @@ class ObjectPainter extends BasePainter { * @return {Promise} when pad redraw completed * @protected */ async redrawPad(reason) { - let pp = this.getPadPainter(); - return pp ? pp.redrawPad(reason) : false; + return this.getPadPainter()?.redrawPad(reason) ?? false; } /** @summary execute selected menu command, either locally or remotely * @private */ executeMenuCommand(method) { - - if (method.fName == 'Inspect') + if (method.fName === 'Inspect') // primitve inspector, keep it here return this.showInspector(); @@ -11560,7 +12290,7 @@ class ObjectPainter extends BasePainter { submitCanvExec(exec, snapid) { if (!exec || !isStr(exec)) return; - let canp = this.getCanvPainter(); + const canp = this.getCanvPainter(); if (isFunc(canp?.submitExec)) canp.submitExec(this, exec, snapid); } @@ -11575,25 +12305,32 @@ class ObjectPainter extends BasePainter { /** @summary Show object in inspector for provided object * @protected */ - showInspector() { + showInspector(/* opt */) { return false; } /** @summary Fill context menu for the object * @private */ fillContextMenu(menu) { - let title = this.getObjectHint(); - if (this.getObject() && ('_typename' in this.getObject())) - title = this.getObject()._typename + '::' + title; + const name = this.getObjectName(); + let cl = this.getClassName(); + const p = cl.lastIndexOf('::'); + if (p > 0) cl = cl.slice(p+2); + const title = (cl && name) ? `${cl}:${name}` : (cl || name || 'object'); - menu.add('header:' + title); + menu.add(`header:${title}`); - menu.addAttributesMenu(this); + const size0 = menu.size(); - if ((menu.size() > 0) && this.showInspector('check')) + if (isFunc(this.fillContextMenuItems)) + this.fillContextMenuItems(menu); + + if ((menu.size() > size0) && this.showInspector('check')) menu.add('Inspect', this.showInspector); - return menu.size() > 0; + menu.addAttributesMenu(this); + + return menu.size() > size0; } /** @summary shows objects status @@ -11610,7 +12347,7 @@ class ObjectPainter extends BasePainter { if (this.enlargeMain('state') === 'on') return false; if ((name === undefined) && (title === undefined)) { - let obj = this.getObject(); + const obj = this.getObject(); if (!obj) return; name = this.getItemName() || obj.fName; title = obj.fTitle || obj._typename; @@ -11638,22 +12375,20 @@ class ObjectPainter extends BasePainter { * @param {number} [max_font_size] - maximal font size, used when text can be scaled * @protected */ startTextDrawing(font_face, font_size, draw_g, max_font_size) { - if (!draw_g) draw_g = this.draw_g; if (!draw_g || draw_g.empty()) return; - let font = (font_size === 'font') ? font_face : new FontHandler(font_face, font_size), - pp = this.getPadPainter(); + const font = (font_size === 'font') ? font_face : new FontHandler(font_face, font_size); draw_g.call(font.func); draw_g.property('draw_text_completed', false) // indicate that draw operations submitted - .property('all_args',[]) // array of all submitted args, makes easier to analyze them + .property('all_args', []) // array of all submitted args, makes easier to analyze them .property('text_font', font) - .property('text_factor', 0.) + .property('text_factor', 0) .property('max_text_width', 0) // keep maximal text width, use it later .property('max_font_size', max_font_size) - .property('_fast_drawing', pp?._fast_drawing || false); + .property('_fast_drawing', this.getPadPainter()?._fast_drawing ?? false); if (draw_g.property('_fast_drawing')) draw_g.property('_font_too_small', (max_font_size && (max_font_size < 5)) || (font.size < 4)); @@ -11674,7 +12409,6 @@ class ObjectPainter extends BasePainter { /** @summary Analyze if all text draw operations are completed * @private */ _checkAllTextDrawing(draw_g, resolveFunc, try_optimize) { - let all_args = draw_g.property('all_args'), missing = 0; if (!all_args) { console.log('Text drawing is finished - why calling _checkAllTextDrawing?????'); @@ -11694,10 +12428,10 @@ class ObjectPainter extends BasePainter { draw_g.property('all_args', null); // clear all_args property // adjust font size (if there are normal text) - let f = draw_g.property('text_factor'), - font = draw_g.property('text_font'), - max_sz = draw_g.property('max_font_size'), - font_size = font.size, any_text = false, only_text = true; + const f = draw_g.property('text_factor'), + font = draw_g.property('text_font'), + max_sz = draw_g.property('max_font_size'); + let font_size = font.size, any_text = false, only_text = true; if ((f > 0) && ((f < 0.9) || (f > 1))) font.size = Math.max(1, Math.floor(font.size / f)); @@ -11705,20 +12439,19 @@ class ObjectPainter extends BasePainter { if (max_sz && (font.size > max_sz)) font.size = max_sz; - if (font.size != font_size) { + if (font.size !== font_size) { draw_g.call(font.func); font_size = font.size; } all_args.forEach(arg => { if (arg.mj_node && arg.applyAttributesToMathJax) { - let svg = arg.mj_node.select('svg'); // MathJax svg + const svg = arg.mj_node.select('svg'); // MathJax svg arg.applyAttributesToMathJax(this, arg.mj_node, svg, arg, font_size, f); delete arg.mj_node; // remove reference only_text = false; - } else if (arg.txt_g) { + } else if (arg.txt_g) only_text = false; - } }); if (!resolveFunc) { @@ -11728,7 +12461,7 @@ class ObjectPainter extends BasePainter { delete draw_g.node().try_optimize; } - let optimize_arr = (try_optimize && only_text) ? [] : null; + const optimize_arr = (try_optimize && only_text) ? [] : null; // now process text and latex drawings all_args.forEach(arg => { @@ -11742,9 +12475,8 @@ class ObjectPainter extends BasePainter { txt = arg.txt_g; delete arg.txt_g; is_txt = false; - } else { + } else return; - } txt.attr('visibility', null); @@ -11752,23 +12484,22 @@ class ObjectPainter extends BasePainter { if (arg.width) { // adjust x position when scale into specified rectangle - if (arg.align[0] == 'middle') + if (arg.align[0] === 'middle') arg.x += arg.width / 2; - else if (arg.align[0] == 'end') + else if (arg.align[0] === 'end') arg.x += arg.width; } if (arg.height) { if (arg.align[1].indexOf('bottom') === 0) arg.y += arg.height; - else if (arg.align[1] == 'middle') + else if (arg.align[1] === 'middle') arg.y += arg.height / 2; } - arg.dx = arg.dy = 0; + let dx = 0, dy = 0; if (is_txt) { - // handle simple text drawing if (isNodeJs()) { @@ -11780,52 +12511,47 @@ class ObjectPainter extends BasePainter { if (arg.plain) { txt.attr('text-anchor', arg.align[0]); - if (arg.align[1] == 'top') + if (arg.align[1] === 'top') txt.attr('dy', '.8em'); - else if (arg.align[1] == 'middle') { - if (isNodeJs()) txt.attr('dy', '.4em'); else txt.attr('dominant-baseline', 'middle'); + else if (arg.align[1] === 'middle') { + if (isNodeJs()) txt.attr('dy', '.4em'); + else txt.attr('dominant-baseline', 'middle'); } } else { txt.attr('text-anchor', 'start'); - arg.dx = ((arg.align[0] == 'middle') ? -0.5 : ((arg.align[0] == 'end') ? -1 : 0)) * arg.box.width; - arg.dy = ((arg.align[1] == 'top') ? (arg.top_shift || 1) : (arg.align[1] == 'middle') ? (arg.mid_shift || 0.5) : 0) * arg.box.height; + dx = ((arg.align[0] === 'middle') ? -0.5 : ((arg.align[0] === 'end') ? -1 : 0)) * arg.box.width; + dy = ((arg.align[1] === 'top') ? (arg.top_shift || 1) : (arg.align[1] === 'middle') ? (arg.mid_shift || 0.5) : 0) * arg.box.height; } - } else if (arg.text_rect) { - // handle latext drawing - let box = arg.text_rect; + const box = arg.text_rect; scale = (f > 0) && (Math.abs(1-f) > 0.01) ? 1/f : 1; - arg.dx = ((arg.align[0] == 'middle') ? -0.5 : ((arg.align[0] == 'end') ? -1 : 0)) * box.width * scale; + dx = ((arg.align[0] === 'middle') ? -0.5 : ((arg.align[0] === 'end') ? -1 : 0)) * box.width * scale; - if (arg.align[1] == 'top') - arg.dy = -box.y1*scale; - else if (arg.align[1] == 'bottom') - arg.dy = -box.y2*scale; - else if (arg.align[1] == 'middle') - arg.dy = -0.5*(box.y1 + box.y2)*scale; - } else { + if (arg.align[1] === 'top') + dy = -box.y1*scale; + else if (arg.align[1] === 'bottom') + dy = -box.y2*scale; + else if (arg.align[1] === 'middle') + dy = -0.5*(box.y1 + box.y2)*scale; + } else console.error('text rect not calcualted - please check code'); - } - if (!arg.rotate) { arg.x += arg.dx; arg.y += arg.dy; arg.dx = arg.dy = 0; } + if (!arg.rotate) { arg.x += dx; arg.y += dy; dx = dy = 0; } // use translate and then rotate to avoid complex sign calculations - let trans = ''; - if (arg.y) - trans = `translate(${Math.round(arg.x)},${Math.round(arg.y)})`; - else if (arg.x) - trans = `translate(${Math.round(arg.x)})`; + let trans = makeTranslate(Math.round(arg.x), Math.round(arg.y)) || ''; + const dtrans = makeTranslate(Math.round(dx), Math.round(dy)), + append = arg => { if (trans) trans += ' '; trans += arg; }; + if (arg.rotate) - trans += ` rotate(${Math.round(arg.rotate)})`; + append(`rotate(${Math.round(arg.rotate)})`); if (scale !== 1) - trans += ` scale(${scale.toFixed(3)})`; - if (arg.dy) - trans += ` translate(${Math.round(arg.dx)},${Math.round(arg.dy)})`; - else if (arg.dx) - trans += ` translate(${Math.round(arg.dx)})`; + append(`scale(${scale.toFixed(3)})`); + if (dtrans) + append(dtrans); if (trans) txt.attr('transform', trans); }); @@ -11834,11 +12560,11 @@ class ObjectPainter extends BasePainter { if (!any_text) font.clearFont(draw_g); - if ((optimize_arr !== null) && (optimize_arr.length > 1)) + if ((optimize_arr !== null) && (optimize_arr.length > 1)) { ['fill', 'text-anchor'].forEach(name => { let first = optimize_arr[0].attr(name); optimize_arr.forEach(txt_node => { - let value = txt_node.attr(name); + const value = txt_node.attr(name); if (!value || (value !== first)) first = undefined; }); if (first) { @@ -11846,6 +12572,7 @@ class ObjectPainter extends BasePainter { optimize_arr.forEach(txt_node => { txt_node.attr(name, null); }); } }); + } // if specified, call resolve function if (resolveFunc) resolveFunc(this); // IMPORTANT - return painter, may use in draw methods @@ -11855,15 +12582,16 @@ class ObjectPainter extends BasePainter { * @private */ _postprocessDrawText(arg, txt_node) { // complete rectangle with very rougth size estimations - arg.box = !isNodeJs() && !settings.ApproxTextSize && !arg.fast ? getElementRect(txt_node, 'bbox') : - (arg.text_rect || { height: arg.font_size * 1.2, width: arg.text.length * arg.font_size * arg.font.aver_width }); + arg.box = !isNodeJs() && !settings.ApproxTextSize && !arg.fast + ? getElementRect(txt_node, 'bbox') + : (arg.text_rect || { height: arg.font_size * 1.2, width: arg.text.length * arg.font_size * arg.font.aver_width }); txt_node.attr('visibility', 'hidden'); // hide elements until text drawing is finished if (arg.box.width > arg.draw_g.property('max_text_width')) arg.draw_g.property('max_text_width', arg.box.width); if (arg.scale) - this.scaleTextDrawing(Math.max(1.05 * arg.box.width / arg.width, 1. * arg.box.height / arg.height), arg.draw_g); + this.scaleTextDrawing(Math.max(1.05 * arg.box.width / arg.width, arg.box.height / arg.height), arg.draw_g); arg.result_width = arg.box.width; arg.result_height = arg.box.height; @@ -11884,6 +12612,7 @@ class ObjectPainter extends BasePainter { * @param {number} [arg.y = 0] - y position * @param {number} [arg.width] - when specified, adjust font size in the specified box * @param {number} [arg.height] - when specified, adjust font size in the specified box + * @param {boolean} [arg.scale = true] - scale into draw box when width and height parameters are specified * @param {number} [arg.latex] - 0 - plain text, 1 - normal TLatex, 2 - math * @param {string} [arg.color=black] - text color * @param {number} [arg.rotate] - rotaion angle @@ -11892,14 +12621,13 @@ class ObjectPainter extends BasePainter { * @param {function} [arg.post_process] - optional function called when specified text is drawn * @protected */ drawText(arg) { - if (!arg.text) arg.text = ''; arg.draw_g = arg.draw_g || this.draw_g; if (!arg.draw_g || arg.draw_g.empty()) return; - let font = arg.draw_g.property('text_font'); + const font = arg.draw_g.property('text_font'); arg.font = font; // use in latex conversion if (font) { @@ -11912,27 +12640,27 @@ class ObjectPainter extends BasePainter { if (isStr(arg.align)) { align = arg.align.split(';'); - if (align.length == 1) align.push('middle'); - } else if (typeof arg.align == 'number') { + if (align.length === 1) align.push('middle'); + } else if (typeof arg.align === 'number') { if ((arg.align / 10) >= 3) align[0] = 'end'; else if ((arg.align / 10) >= 2) align[0] = 'middle'; - if ((arg.align % 10) == 0) + if ((arg.align % 10) === 0) align[1] = 'bottom'; - else if ((arg.align % 10) == 1) + else if ((arg.align % 10) === 1) align[1] = 'bottom-base'; - else if ((arg.align % 10) == 3) + else if ((arg.align % 10) === 3) align[1] = 'top'; - } else if (isObject(arg.align) && (arg.align.length == 2)) { + } else if (isObject(arg.align) && (arg.align.length === 2)) align = arg.align; - } if (arg.latex === undefined) arg.latex = 1; // latex 0-text, 1-latex, 2-math arg.align = align; arg.x = arg.x || 0; arg.y = arg.y || 0; - arg.scale = arg.width && arg.height && !arg.font_size; + if (arg.scale !== false) + arg.scale = arg.width && arg.height && !arg.font_size; arg.width = arg.width || 0; arg.height = arg.height || 0; @@ -11953,15 +12681,16 @@ class ObjectPainter extends BasePainter { arg.draw_g.property('all_args').push(arg); arg.ready = false; // indicates if drawing is ready for post-processing - let use_mathjax = (arg.latex == 2); + let use_mathjax = (arg.latex === 2); + const cl = constants$1.Latex; - if (arg.latex === 1) - use_mathjax = (settings.Latex == constants$1.Latex.AlwaysMathJax) || - ((settings.Latex == constants$1.Latex.MathJax) && arg.text.match(/[#{\\]/g)) || + if (arg.latex === 1) { + use_mathjax = (settings.Latex === cl.AlwaysMathJax) || + ((settings.Latex === cl.MathJax) && arg.text.match(/[#{\\]/g)) || arg.text.match(/[\\]/g); + } if (!use_mathjax || arg.nomathjax) { - arg.txt_node = arg.draw_g.append('svg:text'); if (arg.color) arg.txt_node.attr('fill', arg.color); @@ -11969,9 +12698,9 @@ class ObjectPainter extends BasePainter { if (arg.font_size) arg.txt_node.attr('font-size', arg.font_size); else arg.font_size = font.size; - arg.plain = !arg.latex || (settings.Latex == constants$1.Latex.Off) || (settings.Latex == constants$1.Latex.Symbols); + arg.plain = !arg.latex || (settings.Latex === cl.Off) || (settings.Latex === cl.Symbols); - arg.simple_latex = arg.latex && (settings.Latex == constants$1.Latex.Symbols); + arg.simple_latex = arg.latex && (settings.Latex === cl.Symbols); if (!arg.plain || arg.simple_latex || (arg.font && arg.font.isSymbol)) { if (arg.simple_latex || isPlainText(arg.text) || arg.plain) { @@ -12033,7 +12762,6 @@ class ObjectPainter extends BasePainter { * Function should return promise with menu when items are filled * @param {function} fillmenu_func - function to fill custom context menu for oabject */ configureUserContextMenu(fillmenu_func) { - if (!fillmenu_func || !isFunc(fillmenu_func)) delete this._userContextMenuFunc; else @@ -12043,89 +12771,87 @@ class ObjectPainter extends BasePainter { /** @summary Fill object menu in web canvas * @private */ async fillObjectExecMenu(menu, kind) { - - if (this._userContextMenuFunc) + if (isFunc(this._userContextMenuFunc)) return this._userContextMenuFunc(menu, kind); - let canvp = this.getCanvPainter(); + const canvp = this.getCanvPainter(); if (!this.snapid || !canvp || canvp?._readonly || !canvp?._websocket) return menu; function DoExecMenu(arg) { - let execp = this.exec_painter || this, - cp = execp.getCanvPainter(), - item = execp.args_menu_items[parseInt(arg)]; + const execp = menu.exec_painter || this, + cp = execp.getCanvPainter(), + item = menu.exec_items[parseInt(arg)]; - if (!item || !item.fName) return; + if (!item?.fName) return; // this is special entry, produced by TWebMenuItem, which recognizes editor entries itself - if (item.fExec == 'Show:Editor') { + if (item.fExec === 'Show:Editor') { if (isFunc(cp?.activateGed)) cp.activateGed(execp); return; } if (isFunc(cp?.executeObjectMethod)) - if (cp.executeObjectMethod(execp, item, execp.args_menu_id)) return; + if (cp.executeObjectMethod(execp, item, item.$execid)) return; - if (execp.executeMenuCommand(item)) return; + item.fClassName = execp.getClassName(); + if ((item.$execid.indexOf('#x') > 0) || (item.$execid.indexOf('#y') > 0) || (item.$execid.indexOf('#z') > 0)) + item.fClassName = clTAxis; - if (!execp.args_menu_id) return; + if (execp.executeMenuCommand(item)) return; - if (!item.fArgs) - if (cp?.v7canvas) - return cp.submitExec(execp, item.fExec, kind); - else - return execp.submitCanvExec(item.fExec, execp.args_menu_id); + if (!item.$execid) return; - item.fClassName = execp.getClassName(); - if ((execp.args_menu_id.indexOf('#x') > 0) || (execp.args_menu_id.indexOf('#y') > 0) || (execp.args_menu_id.indexOf('#z') > 0)) - item.fClassName = clTAxis; + if (!item.fArgs) { + if (cp?.v7canvas) + return cp.submitExec(execp, item.fExec, kind); + else + return execp.submitCanvExec(item.fExec, item.$execid); + } - menu.showMethodArgsDialog(item).then(args => { - if (!args) return; - if (execp.executeMenuCommand(item, args)) return; + menu.showMethodArgsDialog(item).then(args => { + if (!args) return; + if (execp.executeMenuCommand(item, args)) return; - let exec = item.fExec.slice(0, item.fExec.length-1) + args + ')'; - if (cp?.v7canvas) - cp.submitExec(execp, exec, kind); - else if (cp) - cp.sendWebsocket(`OBJEXEC:${execp.args_menu_id}:${exec}`); + const exec = item.fExec.slice(0, item.fExec.length-1) + args + ')'; + if (cp?.v7canvas) + cp.submitExec(execp, exec, kind); + else + cp?.sendWebsocket(`OBJEXEC:${item.$execid}:${exec}`); }); } const DoFillMenu = (_menu, _reqid, _resolveFunc, reply) => { - // avoid multiple call of the callback after timeout - if (this._got_menu) return; - this._got_menu = true; + if (menu._got_menu) return; + menu._got_menu = true; if (reply && (_reqid !== reply.fId)) console.error(`missmatch between request ${_reqid} and reply ${reply.fId} identifiers`); - let items = reply ? reply.fItems : null; + menu.exec_items = reply?.fItems; - if (items && items.length) { + if (menu.exec_items?.length) { if (_menu.size() > 0) _menu.add('separator'); - this.args_menu_items = items; - this.args_menu_id = reply.fId; - let lastclname; - for (let n = 0; n < items.length; ++n) { - let item = items[n]; + for (let n = 0; n < menu.exec_items.length; ++n) { + const item = menu.exec_items[n]; + item.$execid = reply.fId; + item.$menu = menu; - if (item.fClassName && lastclname && (lastclname != item.fClassName)) { + if (item.fClassName && lastclname && (lastclname !== item.fClassName)) { _menu.add('endsub:'); lastclname = ''; } - if (lastclname != item.fClassName) { + if (lastclname !== item.fClassName) { lastclname = item.fClassName; - let p = lastclname.lastIndexOf('::'), - shortname = (p > 0) ? lastclname.slice(p+2) : lastclname; + const p = lastclname.lastIndexOf('::'), + shortname = (p > 0) ? lastclname.slice(p+2) : lastclname; _menu.add('sub:' + shortname.replace(/[<>]/g, '_')); } @@ -12140,23 +12866,28 @@ class ObjectPainter extends BasePainter { } _resolveFunc(_menu); - }; - - let reqid = this.snapid; - if (kind) reqid += '#' + kind; // use # to separate object id from member specifier like 'x' or 'z' + }, + reqid = this.getSnapId(kind); - this._got_menu = false; + menu._got_menu = false; // if menu painter differs from this, remember it for further usage if (menu.painter) - menu.painter.exec_painter = (menu.painter !== this) ? this : undefined; + menu.exec_painter = (menu.painter !== this) ? this : undefined; return new Promise(resolveFunc => { + let did_resolve = false; + + function handleResolve(res) { + if (did_resolve) return; + did_resolve = true; + resolveFunc(res); + } // set timeout to avoid menu hanging - setTimeout(() => DoFillMenu(menu, reqid, resolveFunc), 2000); + setTimeout(() => DoFillMenu(menu, reqid, handleResolve), 2000); - canvp.submitMenuRequest(this, kind, reqid).then(lst => DoFillMenu(menu, reqid, resolveFunc, lst)); + canvp.submitMenuRequest(this, kind, reqid).then(lst => DoFillMenu(menu, reqid, handleResolve, lst)); }); } @@ -12182,7 +12913,7 @@ class ObjectPainter extends BasePainter { * If handler function returns true, default handling of click will be disabled * @param {function} handler - function called when mouse click is done */ configureUserClickHandler(handler) { - let fp = this.getFramePainter(); + const fp = this.getFramePainter(); if (isFunc(fp?.configureUserClickHandler)) fp.configureUserClickHandler(handler); } @@ -12193,7 +12924,7 @@ class ObjectPainter extends BasePainter { * If handler function returns true, default handling of dblclick (unzoom) will be disabled * @param {function} handler - function called when mouse double click is done */ configureUserDblclickHandler(handler) { - let fp = this.getFramePainter(); + const fp = this.getFramePainter(); if (isFunc(fp?.configureUserDblclickHandler)) fp.configureUserDblclickHandler(handler); } @@ -12208,7 +12939,6 @@ class ObjectPainter extends BasePainter { * @param {object} data - tooltip data * @private */ provideUserTooltip(data) { - if (!this.hasUserTooltip()) return; if (this._user_tooltip_timeout <= 0) @@ -12222,20 +12952,18 @@ class ObjectPainter extends BasePainter { if (!data) return this._user_tooltip_handler(data); - let d = data; - // only after timeout user function will be called this._user_tooltip_handle = setTimeout(() => { delete this._user_tooltip_handle; - if (this._user_tooltip_handler) this._user_tooltip_handler(d); + if (this._user_tooltip_handler) this._user_tooltip_handler(data); }, this._user_tooltip_timeout); } /** @summary Provide projection areas - * @param kind - 'X', 'Y' or '' + * @param kind - 'X', 'Y', 'XY' or '' * @private */ async provideSpecialDrawArea(kind) { - if (kind == this._special_draw_area) + if (kind === this._special_draw_area) return true; return this.getCanvPainter().toggleProjection(kind).then(() => { @@ -12244,13 +12972,15 @@ class ObjectPainter extends BasePainter { }); } - /** @summary Provide projection areas - * @param kind - 'X', 'Y' or '' + /** @summary Draw in special projection areas + * @param obj - object to draw + * @param opt - draw option + * @param kind - '', 'X', 'Y' * @private */ - async drawInSpecialArea(obj, opt) { - let canp = this.getCanvPainter(); + async drawInSpecialArea(obj, opt, kind) { + const canp = this.getCanvPainter(); if (this._special_draw_area && isFunc(canp?.drawProjection)) - return canp.drawProjection(this._special_draw_area, obj, opt); + return canp.drawProjection(kind || this._special_draw_area, obj, opt); return false; } @@ -12261,20 +12991,20 @@ class ObjectPainter extends BasePainter { getToolTip(evnt) { if ((evnt?.clientX === undefined) || (evnt?.clientY === undefined)) return null; - let frame = this.getFrameSvg(); + const frame = this.getFrameSvg(); if (frame.empty()) return null; - let layer = frame.select('.main_layer'); + const layer = frame.selectChild('.main_layer'); if (layer.empty()) return null; - let pos = pointer(evnt, layer.node()), - pnt = { touch: false, x: pos[0], y: pos[1] }; + const pos = pointer(evnt, layer.node()), + pnt = { touch: false, x: pos[0], y: pos[1] }; if (isFunc(this.extractToolTip)) return this.extractToolTip(pnt); pnt.disabled = true; - let res = isFunc(this.processTooltipEvent) ? this.processTooltipEvent(pnt) : null; + const res = isFunc(this.processTooltipEvent) ? this.processTooltipEvent(pnt) : null; return res?.user_info || res; } @@ -12284,9 +13014,8 @@ class ObjectPainter extends BasePainter { /** @summary Generic text drawing * @private */ -function drawRawText(dom, txt /*, opt*/) { - - let painter = new BasePainter(dom); +function drawRawText(dom, txt /* , opt */) { + const painter = new BasePainter(dom); painter.txt = txt; painter.redrawObject = function(obj) { @@ -12296,19 +13025,19 @@ function drawRawText(dom, txt /*, opt*/) { }; painter.drawText = async function() { - let txt = (this.txt._typename && (this.txt._typename == clTObjString)) ? this.txt.fString : this.txt.value; + let txt = (this.txt._typename === clTObjString) ? this.txt.fString : this.txt.value; if (!isStr(txt)) txt = ''; - let mathjax = this.txt.mathjax || (settings.Latex == constants$1.Latex.AlwaysMathJax); + const mathjax = this.txt.mathjax || (settings.Latex === constants$1.Latex.AlwaysMathJax); if (!mathjax && !('as_is' in this.txt)) { - let arr = txt.split('\n'); txt = ''; + const arr = txt.split('\n'); txt = ''; for (let i = 0; i < arr.length; ++i) txt += `
${arr[i]}
`; } - let frame = this.selectDom(), - main = frame.select('div'); + const frame = this.selectDom(); + let main = frame.select('div'); if (main.empty()) main = frame.append('div').attr('style', 'max-width:100%;max-height:100%;overflow:auto'); main.html(txt); @@ -12344,11 +13073,9 @@ function getElementMainPainter(dom) { * @param {string|object} dom - id of top div element or directly DOMElement * @return {string} produced JSON string */ function drawingJSON(dom) { - let canp = getElementCanvPainter(dom); - return canp ? canp.produceJSON() : ''; + return getElementCanvPainter(dom)?.produceJSON() || ''; } - let $active_pp = null; /** @summary Set active pad painter @@ -12359,16 +13086,11 @@ let $active_pp = null; * @private */ function selectActivePad(args) { if (args.active) { - let fp = $active_pp ? $active_pp.getFramePainter() : null; - if (fp) fp.setFrameActive(false); - + $active_pp?.getFramePainter()?.setFrameActive(false); $active_pp = args.pp; - - fp = $active_pp ? $active_pp.getFramePainter() : null; - if (fp) fp.setFrameActive(true); - } else if ($active_pp === args.pp) { + $active_pp?.getFramePainter()?.setFrameActive(true); + } else if ($active_pp === args.pp) $active_pp = null; - } } /** @summary Returns current active pad @@ -12386,6 +13108,7 @@ function getActivePad() { * the element even after minimal resize * Or one just supply object with exact sizes like { width:300, height:200, force:true }; * @example + * import { resize } from 'https://root.cern/js/latest/modules/base/ObjectPainter.mjs'; * resize('drawing', { width: 500, height: 200 }); * resize(document.querySelector('#drawing'), true); */ function resize(dom, arg) { @@ -12406,10 +13129,11 @@ function resize(dom, arg) { * @param {string|object} dom - id or DOM element * @public * @example + * import { cleanup } from 'https://root.cern/js/latest/modules/base/ObjectPainter.mjs'; * cleanup('drawing'); * cleanup(document.querySelector('#drawing')); */ function cleanup(dom) { - let dummy = new ObjectPainter(dom), lst = []; + const dummy = new ObjectPainter(dom), lst = []; dummy.forEachPainter(p => { if (lst.indexOf(p) < 0) lst.push(p); }); lst.forEach(p => p.cleanup()); dummy.selectDom().html(''); @@ -12437,24 +13161,13 @@ const EAxisBits = { /** * @license - * Copyright 2010-2021 Three.js Authors + * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ -const REVISION = '146'; -const MOUSE = { - LEFT: 0, - MIDDLE: 1, - RIGHT: 2, - ROTATE: 0, - DOLLY: 1, - PAN: 2 -}; -const TOUCH = { - ROTATE: 0, - PAN: 1, - DOLLY_PAN: 2, - DOLLY_ROTATE: 3 -}; +const REVISION = '155'; + +const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; const CullFaceNone = 0; const CullFaceBack = 1; const CullFaceFront = 2; @@ -12503,6 +13216,7 @@ const ReinhardToneMapping = 2; const CineonToneMapping = 3; const ACESFilmicToneMapping = 4; const CustomToneMapping = 5; + const UVMapping = 300; const CubeReflectionMapping = 301; const CubeRefractionMapping = 302; @@ -12530,7 +13244,6 @@ const UnsignedShort4444Type = 1017; const UnsignedShort5551Type = 1018; const UnsignedInt248Type = 1020; const AlphaFormat = 1021; -const RGBFormat = 1022; // @deprecated since r137 const RGBAFormat = 1023; const LuminanceFormat = 1024; const LuminanceAlphaFormat = 1025; @@ -12541,6 +13254,7 @@ const RedIntegerFormat = 1029; const RGFormat = 1030; const RGIntegerFormat = 1031; const RGBAIntegerFormat = 1033; + const RGB_S3TC_DXT1_Format = 33776; const RGBA_S3TC_DXT1_Format = 33777; const RGBA_S3TC_DXT3_Format = 33778; @@ -12567,2095 +13281,2497 @@ const RGBA_ASTC_10x10_Format = 37819; const RGBA_ASTC_12x10_Format = 37820; const RGBA_ASTC_12x12_Format = 37821; const RGBA_BPTC_Format = 36492; +const RED_RGTC1_Format = 36283; +const SIGNED_RED_RGTC1_Format = 36284; +const RED_GREEN_RGTC2_Format = 36285; +const SIGNED_RED_GREEN_RGTC2_Format = 36286; +/** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */ const LinearEncoding = 3000; +/** @deprecated Use SRGBColorSpace in three.js r152+. */ const sRGBEncoding = 3001; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; const ObjectSpaceNormalMap = 1; + +// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. +const NoColorSpace = ''; const SRGBColorSpace = 'srgb'; const LinearSRGBColorSpace = 'srgb-linear'; +const DisplayP3ColorSpace = 'display-p3'; const KeepStencilOp = 7680; const AlwaysStencilFunc = 519; + +const NeverCompare = 512; +const LessCompare = 513; +const EqualCompare = 514; +const LessEqualCompare = 515; +const GreaterCompare = 516; +const NotEqualCompare = 517; +const GreaterEqualCompare = 518; +const AlwaysCompare = 519; + const StaticDrawUsage = 35044; const GLSL3 = '300 es'; + const _SRGBAFormat = 1035; // fallback for WebGL 1 +const WebGLCoordinateSystem = 2000; +const WebGPUCoordinateSystem = 2001; + /** * https://github.com/mrdoob/eventdispatcher.js/ */ class EventDispatcher { - addEventListener(type, listener) { - if (this._listeners === undefined) this._listeners = {}; + + addEventListener( type, listener ) { + + if ( this._listeners === undefined ) this._listeners = {}; + const listeners = this._listeners; - if (listeners[type] === undefined) { - listeners[type] = []; + + if ( listeners[ type ] === undefined ) { + + listeners[ type ] = []; + } - if (listeners[type].indexOf(listener) === -1) { - listeners[type].push(listener); + + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + + listeners[ type ].push( listener ); + } + } - hasEventListener(type, listener) { - if (this._listeners === undefined) return false; + + hasEventListener( type, listener ) { + + if ( this._listeners === undefined ) return false; + const listeners = this._listeners; - return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + + return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; + } - removeEventListener(type, listener) { - if (this._listeners === undefined) return; + + removeEventListener( type, listener ) { + + if ( this._listeners === undefined ) return; + const listeners = this._listeners; - const listenerArray = listeners[type]; - if (listenerArray !== undefined) { - const index = listenerArray.indexOf(listener); - if (index !== -1) { - listenerArray.splice(index, 1); + const listenerArray = listeners[ type ]; + + if ( listenerArray !== undefined ) { + + const index = listenerArray.indexOf( listener ); + + if ( index !== - 1 ) { + + listenerArray.splice( index, 1 ); + } + } + } - dispatchEvent(event) { - if (this._listeners === undefined) return; + + dispatchEvent( event ) { + + if ( this._listeners === undefined ) return; + const listeners = this._listeners; - const listenerArray = listeners[event.type]; - if (listenerArray !== undefined) { + const listenerArray = listeners[ event.type ]; + + if ( listenerArray !== undefined ) { + event.target = this; // Make a copy, in case listeners are removed while iterating. - const array = listenerArray.slice(0); - for (let i = 0, l = array.length; i < l; i++) { - array[i].call(this, event); + const array = listenerArray.slice( 0 ); + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + array[ i ].call( this, event ); + } + event.target = null; + } + } + } -const _lut = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff']; -let _seed = 1234567; +const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + + const DEG2RAD = Math.PI / 180; const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 function generateUUID() { + const d0 = Math.random() * 0xffffffff | 0; const d1 = Math.random() * 0xffffffff | 0; const d2 = Math.random() * 0xffffffff | 0; const d3 = Math.random() * 0xffffffff | 0; - const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; // .toLowerCase() here flattens concatenated strings to save heap memory space. return uuid.toLowerCase(); + } -function clamp(value, min, max) { - return Math.max(min, Math.min(max, value)); + +function clamp( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); + } // compute euclidean modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation -function euclideanModulo(n, m) { - return (n % m + m) % m; -} +function euclideanModulo( n, m ) { -// Linear mapping from range to range -function mapLinear(x, a1, a2, b1, b2) { - return b1 + (x - a1) * (b2 - b1) / (a2 - a1); -} + return ( ( n % m ) + m ) % m; -// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ -function inverseLerp(x, y, value) { - if (x !== y) { - return (value - x) / (y - x); - } else { - return 0; - } } // https://en.wikipedia.org/wiki/Linear_interpolation -function lerp(x, y, t) { - return (1 - t) * x + t * y; -} +function lerp( x, y, t ) { -// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ -function damp(x, y, lambda, dt) { - return lerp(x, y, 1 - Math.exp(-lambda * dt)); -} - -// https://www.desmos.com/calculator/vcsjnyz7x4 -function pingpong(x, length = 1) { - return length - Math.abs(euclideanModulo(x, length * 2) - length); -} + return ( 1 - t ) * x + t * y; -// http://en.wikipedia.org/wiki/Smoothstep -function smoothstep(x, min, max) { - if (x <= min) return 0; - if (x >= max) return 1; - x = (x - min) / (max - min); - return x * x * (3 - 2 * x); -} -function smootherstep(x, min, max) { - if (x <= min) return 0; - if (x >= max) return 1; - x = (x - min) / (max - min); - return x * x * x * (x * (x * 6 - 15) + 10); } -// Random integer from interval -function randInt(low, high) { - return low + Math.floor(Math.random() * (high - low + 1)); -} +function isPowerOfTwo( value ) { -// Random float from interval -function randFloat(low, high) { - return low + Math.random() * (high - low); -} + return ( value & ( value - 1 ) ) === 0 && value !== 0; -// Random float from <-range/2, range/2> interval -function randFloatSpread(range) { - return range * (0.5 - Math.random()); } -// Deterministic pseudo-random float in the interval [ 0, 1 ] -function seededRandom(s) { - if (s !== undefined) _seed = s; +function floorPowerOfTwo( value ) { - // Mulberry32 generator + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - let t = _seed += 0x6D2B79F5; - t = Math.imul(t ^ t >>> 15, t | 1); - t ^= t + Math.imul(t ^ t >>> 7, t | 61); - return ((t ^ t >>> 14) >>> 0) / 4294967296; -} -function degToRad(degrees) { - return degrees * DEG2RAD; -} -function radToDeg(radians) { - return radians * RAD2DEG; } -function isPowerOfTwo(value) { - return (value & value - 1) === 0 && value !== 0; -} -function ceilPowerOfTwo(value) { - return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); -} -function floorPowerOfTwo(value) { - return Math.pow(2, Math.floor(Math.log(value) / Math.LN2)); -} -function setQuaternionFromProperEuler(q, a, b, c, order) { - // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - // rotations are applied to the axes in the order specified by 'order' - // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' - // angles are in radians +function denormalize( value, array ) { + + switch ( array.constructor ) { - const cos = Math.cos; - const sin = Math.sin; - const c2 = cos(b / 2); - const s2 = sin(b / 2); - const c13 = cos((a + c) / 2); - const s13 = sin((a + c) / 2); - const c1_3 = cos((a - c) / 2); - const s1_3 = sin((a - c) / 2); - const c3_1 = cos((c - a) / 2); - const s3_1 = sin((c - a) / 2); - switch (order) { - case 'XYX': - q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); - break; - case 'YZY': - q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); - break; - case 'ZXZ': - q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); - break; - case 'XZX': - q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); - break; - case 'YXY': - q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); - break; - case 'ZYZ': - q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); - break; - default: - console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order); - } -} -function denormalize(value, array) { - switch (array.constructor) { case Float32Array: + return value; + + case Uint32Array: + + return value / 4294967295.0; + case Uint16Array: + return value / 65535.0; + case Uint8Array: + return value / 255.0; + + case Int32Array: + + return Math.max( value / 2147483647.0, - 1.0 ); + case Int16Array: - return Math.max(value / 32767.0, -1.0); + + return Math.max( value / 32767.0, - 1.0 ); + case Int8Array: - return Math.max(value / 127.0, -1.0); + + return Math.max( value / 127.0, - 1.0 ); + default: - throw new Error('Invalid component type.'); + + throw new Error( 'Invalid component type.' ); + } + } -function normalize(value, array) { - switch (array.constructor) { + +function normalize( value, array ) { + + switch ( array.constructor ) { + case Float32Array: + return value; + + case Uint32Array: + + return Math.round( value * 4294967295.0 ); + case Uint16Array: - return Math.round(value * 65535.0); + + return Math.round( value * 65535.0 ); + case Uint8Array: - return Math.round(value * 255.0); + + return Math.round( value * 255.0 ); + + case Int32Array: + + return Math.round( value * 2147483647.0 ); + case Int16Array: - return Math.round(value * 32767.0); + + return Math.round( value * 32767.0 ); + case Int8Array: - return Math.round(value * 127.0); + + return Math.round( value * 127.0 ); + default: - throw new Error('Invalid component type.'); + + throw new Error( 'Invalid component type.' ); + } -} -var MathUtils = /*#__PURE__*/Object.freeze({ - __proto__: null, - DEG2RAD: DEG2RAD, - RAD2DEG: RAD2DEG, - generateUUID: generateUUID, - clamp: clamp, - euclideanModulo: euclideanModulo, - mapLinear: mapLinear, - inverseLerp: inverseLerp, - lerp: lerp, - damp: damp, - pingpong: pingpong, - smoothstep: smoothstep, - smootherstep: smootherstep, - randInt: randInt, - randFloat: randFloat, - randFloatSpread: randFloatSpread, - seededRandom: seededRandom, - degToRad: degToRad, - radToDeg: radToDeg, - isPowerOfTwo: isPowerOfTwo, - ceilPowerOfTwo: ceilPowerOfTwo, - floorPowerOfTwo: floorPowerOfTwo, - setQuaternionFromProperEuler: setQuaternionFromProperEuler, - normalize: normalize, - denormalize: denormalize -}); +} class Vector2 { - constructor(x = 0, y = 0) { + + constructor( x = 0, y = 0 ) { + Vector2.prototype.isVector2 = true; + this.x = x; this.y = y; + } + get width() { + return this.x; + } - set width(value) { + + set width( value ) { + this.x = value; + } + get height() { + return this.y; + } - set height(value) { + + set height( value ) { + this.y = value; + } - set(x, y) { + + set( x, y ) { + this.x = x; this.y = y; + return this; + } - setScalar(scalar) { + + setScalar( scalar ) { + this.x = scalar; this.y = scalar; + return this; + } - setX(x) { + + setX( x ) { + this.x = x; + return this; + } - setY(y) { + + setY( y ) { + this.y = y; + return this; + } - setComponent(index, value) { - switch (index) { - case 0: - this.x = value; - break; - case 1: - this.y = value; - break; - default: - throw new Error('index is out of range: ' + index); + + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); + } + return this; + } - getComponent(index) { - switch (index) { - case 0: - return this.x; - case 1: - return this.y; - default: - throw new Error('index is out of range: ' + index); + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); + } + } + clone() { - return new this.constructor(this.x, this.y); + + return new this.constructor( this.x, this.y ); + } - copy(v) { + + copy( v ) { + this.x = v.x; this.y = v.y; + return this; + } - add(v) { + + add( v ) { + this.x += v.x; this.y += v.y; + return this; + } - addScalar(s) { + + addScalar( s ) { + this.x += s; this.y += s; + return this; + } - addVectors(a, b) { + + addVectors( a, b ) { + this.x = a.x + b.x; this.y = a.y + b.y; + return this; + } - addScaledVector(v, s) { + + addScaledVector( v, s ) { + this.x += v.x * s; this.y += v.y * s; + return this; + } - sub(v) { + + sub( v ) { + this.x -= v.x; this.y -= v.y; + return this; + } - subScalar(s) { + + subScalar( s ) { + this.x -= s; this.y -= s; + return this; + } - subVectors(a, b) { + + subVectors( a, b ) { + this.x = a.x - b.x; this.y = a.y - b.y; + return this; + } - multiply(v) { + + multiply( v ) { + this.x *= v.x; this.y *= v.y; + return this; + } - multiplyScalar(scalar) { + + multiplyScalar( scalar ) { + this.x *= scalar; this.y *= scalar; + return this; + } - divide(v) { + + divide( v ) { + this.x /= v.x; this.y /= v.y; + return this; + } - divideScalar(scalar) { - return this.multiplyScalar(1 / scalar); + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + } - applyMatrix3(m) { - const x = this.x, - y = this.y; + + applyMatrix3( m ) { + + const x = this.x, y = this.y; const e = m.elements; - this.x = e[0] * x + e[3] * y + e[6]; - this.y = e[1] * x + e[4] * y + e[7]; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + return this; + } - min(v) { - this.x = Math.min(this.x, v.x); - this.y = Math.min(this.y, v.y); + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + return this; + } - max(v) { - this.x = Math.max(this.x, v.x); - this.y = Math.max(this.y, v.y); + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + return this; + } - clamp(min, max) { + + clamp( min, max ) { + // assumes min < max, componentwise - this.x = Math.max(min.x, Math.min(max.x, this.x)); - this.y = Math.max(min.y, Math.min(max.y, this.y)); + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + return this; + } - clampScalar(minVal, maxVal) { - this.x = Math.max(minVal, Math.min(maxVal, this.x)); - this.y = Math.max(minVal, Math.min(maxVal, this.y)); + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + return this; + } - clampLength(min, max) { + + clampLength( min, max ) { + const length = this.length(); - return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length))); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + } + floor() { - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + return this; + } + ceil() { - this.x = Math.ceil(this.x); - this.y = Math.ceil(this.y); + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + return this; + } + round() { - this.x = Math.round(this.x); - this.y = Math.round(this.y); + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + return this; + } + roundToZero() { - this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); - this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); + + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + return this; + } + negate() { - this.x = -this.x; - this.y = -this.y; + + this.x = - this.x; + this.y = - this.y; + return this; + } - dot(v) { + + dot( v ) { + return this.x * v.x + this.y * v.y; + } - cross(v) { + + cross( v ) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { - return Math.sqrt(this.x * this.x + this.y * this.y); + + return Math.sqrt( this.x * this.x + this.y * this.y ); + } + manhattanLength() { - return Math.abs(this.x) + Math.abs(this.y); + + return Math.abs( this.x ) + Math.abs( this.y ); + } + normalize() { - return this.divideScalar(this.length() || 1); + + return this.divideScalar( this.length() || 1 ); + } + angle() { + // computes the angle in radians with respect to the positive x-axis - const angle = Math.atan2(-this.y, -this.x) + Math.PI; + const angle = Math.atan2( - this.y, - this.x ) + Math.PI; + return angle; + + } + + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, - 1, 1 ) ); + } - distanceTo(v) { - return Math.sqrt(this.distanceToSquared(v)); + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + } - distanceToSquared(v) { - const dx = this.x - v.x, - dy = this.y - v.y; + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y; return dx * dx + dy * dy; + } - manhattanDistanceTo(v) { - return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + } - setLength(length) { - return this.normalize().multiplyScalar(length); + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + } - lerp(v, alpha) { - this.x += (v.x - this.x) * alpha; - this.y += (v.y - this.y) * alpha; + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + return this; + } - lerpVectors(v1, v2, alpha) { - this.x = v1.x + (v2.x - v1.x) * alpha; - this.y = v1.y + (v2.y - v1.y) * alpha; + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + return this; + } - equals(v) { - return v.x === this.x && v.y === this.y; + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) ); + } - fromArray(array, offset = 0) { - this.x = array[offset]; - this.y = array[offset + 1]; + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + return this; + } - toArray(array = [], offset = 0) { - array[offset] = this.x; - array[offset + 1] = this.y; + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + return array; + } - fromBufferAttribute(attribute, index) { - this.x = attribute.getX(index); - this.y = attribute.getY(index); + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + return this; + } - rotateAround(center, angle) { - const c = Math.cos(angle), - s = Math.sin(angle); + + rotateAround( center, angle ) { + + const c = Math.cos( angle ), s = Math.sin( angle ); + const x = this.x - center.x; const y = this.y - center.y; + this.x = x * c - y * s + center.x; this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); this.y = Math.random(); + return this; + } - *[Symbol.iterator]() { + + *[ Symbol.iterator ]() { + yield this.x; yield this.y; + } + } class Matrix3 { - constructor() { + + constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + Matrix3.prototype.isMatrix3 = true; - this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + + this.elements = [ + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ]; + + if ( n11 !== undefined ) { + + this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ); + + } + } - set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + + set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + const te = this.elements; - te[0] = n11; - te[1] = n21; - te[2] = n31; - te[3] = n12; - te[4] = n22; - te[5] = n32; - te[6] = n13; - te[7] = n23; - te[8] = n33; + + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + return this; + } + identity() { - this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + + this.set( + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ); + return this; + } - copy(m) { + + copy( m ) { + const te = this.elements; const me = m.elements; - te[0] = me[0]; - te[1] = me[1]; - te[2] = me[2]; - te[3] = me[3]; - te[4] = me[4]; - te[5] = me[5]; - te[6] = me[6]; - te[7] = me[7]; - te[8] = me[8]; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + return this; + } - extractBasis(xAxis, yAxis, zAxis) { - xAxis.setFromMatrix3Column(this, 0); - yAxis.setFromMatrix3Column(this, 1); - zAxis.setFromMatrix3Column(this, 2); + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); + return this; + } - setFromMatrix4(m) { + + setFromMatrix4( m ) { + const me = m.elements; - this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + + this.set( + + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] + + ); + return this; + } - multiply(m) { - return this.multiplyMatrices(this, m); + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + } - premultiply(m) { - return this.multiplyMatrices(m, this); + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + } - multiplyMatrices(a, b) { + + multiplyMatrices( a, b ) { + const ae = a.elements; const be = b.elements; const te = this.elements; - const a11 = ae[0], - a12 = ae[3], - a13 = ae[6]; - const a21 = ae[1], - a22 = ae[4], - a23 = ae[7]; - const a31 = ae[2], - a32 = ae[5], - a33 = ae[8]; - const b11 = be[0], - b12 = be[3], - b13 = be[6]; - const b21 = be[1], - b22 = be[4], - b23 = be[7]; - const b31 = be[2], - b32 = be[5], - b33 = be[8]; - te[0] = a11 * b11 + a12 * b21 + a13 * b31; - te[3] = a11 * b12 + a12 * b22 + a13 * b32; - te[6] = a11 * b13 + a12 * b23 + a13 * b33; - te[1] = a21 * b11 + a22 * b21 + a23 * b31; - te[4] = a21 * b12 + a22 * b22 + a23 * b32; - te[7] = a21 * b13 + a22 * b23 + a23 * b33; - te[2] = a31 * b11 + a32 * b21 + a33 * b31; - te[5] = a31 * b12 + a32 * b22 + a33 * b32; - te[8] = a31 * b13 + a32 * b23 + a33 * b33; - return this; - } - multiplyScalar(s) { - const te = this.elements; - te[0] *= s; - te[3] *= s; - te[6] *= s; - te[1] *= s; - te[4] *= s; - te[7] *= s; - te[2] *= s; - te[5] *= s; - te[8] *= s; + + const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + + const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + + return this; + + } + + multiplyScalar( s ) { + + const te = this.elements; + + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; + return this; + } + determinant() { + const te = this.elements; - const a = te[0], - b = te[1], - c = te[2], - d = te[3], - e = te[4], - f = te[5], - g = te[6], - h = te[7], - i = te[8]; + + const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te = this.elements, - n11 = te[0], - n21 = te[1], - n31 = te[2], - n12 = te[3], - n22 = te[4], - n32 = te[5], - n13 = te[6], - n23 = te[7], - n33 = te[8], + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], + n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], + n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], + t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, + det = n11 * t11 + n21 * t12 + n31 * t13; - if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + const detInv = 1 / det; - te[0] = t11 * detInv; - te[1] = (n31 * n23 - n33 * n21) * detInv; - te[2] = (n32 * n21 - n31 * n22) * detInv; - te[3] = t12 * detInv; - te[4] = (n33 * n11 - n31 * n13) * detInv; - te[5] = (n31 * n12 - n32 * n11) * detInv; - te[6] = t13 * detInv; - te[7] = (n21 * n13 - n23 * n11) * detInv; - te[8] = (n22 * n11 - n21 * n12) * detInv; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + return this; + } + transpose() { + let tmp; const m = this.elements; - tmp = m[1]; - m[1] = m[3]; - m[3] = tmp; - tmp = m[2]; - m[2] = m[6]; - m[6] = tmp; - tmp = m[5]; - m[5] = m[7]; - m[7] = tmp; + + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + return this; + } - getNormalMatrix(matrix4) { - return this.setFromMatrix4(matrix4).invert().transpose(); + + getNormalMatrix( matrix4 ) { + + return this.setFromMatrix4( matrix4 ).invert().transpose(); + } - transposeIntoArray(r) { + + transposeIntoArray( r ) { + const m = this.elements; - r[0] = m[0]; - r[1] = m[3]; - r[2] = m[6]; - r[3] = m[1]; - r[4] = m[4]; - r[5] = m[7]; - r[6] = m[2]; - r[7] = m[5]; - r[8] = m[8]; + + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; + return this; + } - setUvTransform(tx, ty, sx, sy, rotation, cx, cy) { - const c = Math.cos(rotation); - const s = Math.sin(rotation); - this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1); + + setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { + + const c = Math.cos( rotation ); + const s = Math.sin( rotation ); + + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); + return this; + } - scale(sx, sy) { - const te = this.elements; - te[0] *= sx; - te[3] *= sx; - te[6] *= sx; - te[1] *= sy; - te[4] *= sy; - te[7] *= sy; + + // + + scale( sx, sy ) { + + this.premultiply( _m3.makeScale( sx, sy ) ); + return this; + } - rotate(theta) { - const c = Math.cos(theta); - const s = Math.sin(theta); - const te = this.elements; - const a11 = te[0], - a12 = te[3], - a13 = te[6]; - const a21 = te[1], - a22 = te[4], - a23 = te[7]; - te[0] = c * a11 + s * a21; - te[3] = c * a12 + s * a22; - te[6] = c * a13 + s * a23; - te[1] = -s * a11 + c * a21; - te[4] = -s * a12 + c * a22; - te[7] = -s * a13 + c * a23; + + rotate( theta ) { + + this.premultiply( _m3.makeRotation( - theta ) ); + return this; + } - translate(tx, ty) { - const te = this.elements; - te[0] += tx * te[2]; - te[3] += tx * te[5]; - te[6] += tx * te[8]; - te[1] += ty * te[2]; - te[4] += ty * te[5]; - te[7] += ty * te[8]; + + translate( tx, ty ) { + + this.premultiply( _m3.makeTranslation( tx, ty ) ); + + return this; + + } + + // for 2D Transforms + + makeTranslation( x, y ) { + + if ( x.isVector2 ) { + + this.set( + + 1, 0, x.x, + 0, 1, x.y, + 0, 0, 1 + + ); + + } else { + + this.set( + + 1, 0, x, + 0, 1, y, + 0, 0, 1 + + ); + + } + + return this; + + } + + makeRotation( theta ) { + + // counterclockwise + + const c = Math.cos( theta ); + const s = Math.sin( theta ); + + this.set( + + c, - s, 0, + s, c, 0, + 0, 0, 1 + + ); + + return this; + + } + + makeScale( x, y ) { + + this.set( + + x, 0, 0, + 0, y, 0, + 0, 0, 1 + + ); + return this; + } - equals(matrix) { + + // + + equals( matrix ) { + const te = this.elements; const me = matrix.elements; - for (let i = 0; i < 9; i++) { - if (te[i] !== me[i]) return false; + + for ( let i = 0; i < 9; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + } + return true; + } - fromArray(array, offset = 0) { - for (let i = 0; i < 9; i++) { - this.elements[i] = array[i + offset]; + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + } + return this; + } - toArray(array = [], offset = 0) { + + toArray( array = [], offset = 0 ) { + const te = this.elements; - array[offset] = te[0]; - array[offset + 1] = te[1]; - array[offset + 2] = te[2]; - array[offset + 3] = te[3]; - array[offset + 4] = te[4]; - array[offset + 5] = te[5]; - array[offset + 6] = te[6]; - array[offset + 7] = te[7]; - array[offset + 8] = te[8]; + + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; + return array; + } + clone() { - return new this.constructor().fromArray(this.elements); + + return new this.constructor().fromArray( this.elements ); + } + } -function arrayNeedsUint32(array) { +const _m3 = /*@__PURE__*/ new Matrix3(); + +function arrayNeedsUint32( array ) { + // assumes larger values usually on last - for (let i = array.length - 1; i >= 0; --i) { - if (array[i] >= 65535) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + for ( let i = array.length - 1; i >= 0; -- i ) { + + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + } return false; + +} + +function createElementNS( name ) { + + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); + } -function createElementNS(name) { - return document.createElementNS('http://www.w3.org/1999/xhtml', name); + +const _cache = {}; + +function warnOnce( message ) { + + if ( message in _cache ) return; + + _cache[ message ] = true; + + console.warn( message ); + } -function SRGBToLinear(c) { - return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); +function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + } -function LinearToSRGB(c) { - return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; + +function LinearToSRGB( c ) { + + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + } -// JavaScript RGB-to-RGB transforms, defined as -// FN[InputColorSpace][OutputColorSpace] callback functions. -const FN = { - [SRGBColorSpace]: { - [LinearSRGBColorSpace]: SRGBToLinear - }, - [LinearSRGBColorSpace]: { - [SRGBColorSpace]: LinearToSRGB - } +/** + * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping + * or clipping. Based on W3C specifications for sRGB and Display P3, + * and ICC specifications for the D50 connection space. Values in/out + * are _linear_ sRGB and _linear_ Display P3. + * + * Note that both sRGB and Display P3 use the sRGB transfer functions. + * + * Reference: + * - http://www.russellcottrell.com/photo/matrixCalculator.htm + */ + +const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [ + 0.8224621, 0.0331941, 0.0170827, + 0.1775380, 0.9668058, 0.0723974, + - 0.0000001, 0.0000001, 0.9105199 +] ); + +const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [ + 1.2249401, - 0.0420569, - 0.0196376, + - 0.2249404, 1.0420571, - 0.0786361, + 0.0000001, 0.0000000, 1.0982735 +] ); + +function DisplayP3ToLinearSRGB( color ) { + + // Display P3 uses the sRGB transfer functions + return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ); + +} + +function LinearSRGBToDisplayP3( color ) { + + // Display P3 uses the sRGB transfer functions + return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(); + +} + +// Conversions from to Linear-sRGB reference space. +const TO_LINEAR = { + [ LinearSRGBColorSpace ]: ( color ) => color, + [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(), + [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB, +}; + +// Conversions to from Linear-sRGB reference space. +const FROM_LINEAR = { + [ LinearSRGBColorSpace ]: ( color ) => color, + [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(), + [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3, }; + const ColorManagement = { - legacyMode: true, + + enabled: true, + + get legacyMode() { + + console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' ); + + return ! this.enabled; + + }, + + set legacyMode( legacyMode ) { + + console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' ); + + this.enabled = ! legacyMode; + + }, + get workingColorSpace() { + return LinearSRGBColorSpace; + }, - set workingColorSpace(colorSpace) { - console.warn('THREE.ColorManagement: .workingColorSpace is readonly.'); + + set workingColorSpace( colorSpace ) { + + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); + }, - convert: function (color, sourceColorSpace, targetColorSpace) { - if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + + convert: function ( color, sourceColorSpace, targetColorSpace ) { + + if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { + return color; + } - if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) { - const fn = FN[sourceColorSpace][targetColorSpace]; - color.r = fn(color.r); - color.g = fn(color.g); - color.b = fn(color.b); - return color; + + const sourceToLinear = TO_LINEAR[ sourceColorSpace ]; + const targetFromLinear = FROM_LINEAR[ targetColorSpace ]; + + if ( sourceToLinear === undefined || targetFromLinear === undefined ) { + + throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` ); + } - throw new Error('Unsupported color space conversion.'); + + return targetFromLinear( sourceToLinear( color ) ); + }, - fromWorkingColorSpace: function (color, targetColorSpace) { - return this.convert(color, this.workingColorSpace, targetColorSpace); + + fromWorkingColorSpace: function ( color, targetColorSpace ) { + + return this.convert( color, this.workingColorSpace, targetColorSpace ); + }, - toWorkingColorSpace: function (color, sourceColorSpace) { - return this.convert(color, sourceColorSpace, this.workingColorSpace); - } -}; -const _colorKeywords = { - 'aliceblue': 0xF0F8FF, - 'antiquewhite': 0xFAEBD7, - 'aqua': 0x00FFFF, - 'aquamarine': 0x7FFFD4, - 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, - 'bisque': 0xFFE4C4, - 'black': 0x000000, - 'blanchedalmond': 0xFFEBCD, - 'blue': 0x0000FF, - 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, - 'burlywood': 0xDEB887, - 'cadetblue': 0x5F9EA0, - 'chartreuse': 0x7FFF00, - 'chocolate': 0xD2691E, - 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, - 'cornsilk': 0xFFF8DC, - 'crimson': 0xDC143C, - 'cyan': 0x00FFFF, - 'darkblue': 0x00008B, - 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, - 'darkgray': 0xA9A9A9, - 'darkgreen': 0x006400, - 'darkgrey': 0xA9A9A9, - 'darkkhaki': 0xBDB76B, - 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, - 'darkorange': 0xFF8C00, - 'darkorchid': 0x9932CC, - 'darkred': 0x8B0000, - 'darksalmon': 0xE9967A, - 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, - 'darkslategray': 0x2F4F4F, - 'darkslategrey': 0x2F4F4F, - 'darkturquoise': 0x00CED1, - 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, - 'deepskyblue': 0x00BFFF, - 'dimgray': 0x696969, - 'dimgrey': 0x696969, - 'dodgerblue': 0x1E90FF, - 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, - 'forestgreen': 0x228B22, - 'fuchsia': 0xFF00FF, - 'gainsboro': 0xDCDCDC, - 'ghostwhite': 0xF8F8FF, - 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, - 'gray': 0x808080, - 'green': 0x008000, - 'greenyellow': 0xADFF2F, - 'grey': 0x808080, - 'honeydew': 0xF0FFF0, - 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, - 'indigo': 0x4B0082, - 'ivory': 0xFFFFF0, - 'khaki': 0xF0E68C, - 'lavender': 0xE6E6FA, - 'lavenderblush': 0xFFF0F5, - 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, - 'lightblue': 0xADD8E6, - 'lightcoral': 0xF08080, - 'lightcyan': 0xE0FFFF, - 'lightgoldenrodyellow': 0xFAFAD2, - 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, - 'lightgrey': 0xD3D3D3, - 'lightpink': 0xFFB6C1, - 'lightsalmon': 0xFFA07A, - 'lightseagreen': 0x20B2AA, - 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, - 'lightslategrey': 0x778899, - 'lightsteelblue': 0xB0C4DE, - 'lightyellow': 0xFFFFE0, - 'lime': 0x00FF00, - 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, - 'magenta': 0xFF00FF, - 'maroon': 0x800000, - 'mediumaquamarine': 0x66CDAA, - 'mediumblue': 0x0000CD, - 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, - 'mediumseagreen': 0x3CB371, - 'mediumslateblue': 0x7B68EE, - 'mediumspringgreen': 0x00FA9A, - 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, - 'midnightblue': 0x191970, - 'mintcream': 0xF5FFFA, - 'mistyrose': 0xFFE4E1, - 'moccasin': 0xFFE4B5, - 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, - 'oldlace': 0xFDF5E6, - 'olive': 0x808000, - 'olivedrab': 0x6B8E23, - 'orange': 0xFFA500, - 'orangered': 0xFF4500, - 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, - 'palegreen': 0x98FB98, - 'paleturquoise': 0xAFEEEE, - 'palevioletred': 0xDB7093, - 'papayawhip': 0xFFEFD5, - 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, - 'pink': 0xFFC0CB, - 'plum': 0xDDA0DD, - 'powderblue': 0xB0E0E6, - 'purple': 0x800080, - 'rebeccapurple': 0x663399, - 'red': 0xFF0000, - 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, - 'saddlebrown': 0x8B4513, - 'salmon': 0xFA8072, - 'sandybrown': 0xF4A460, - 'seagreen': 0x2E8B57, - 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, - 'silver': 0xC0C0C0, - 'skyblue': 0x87CEEB, - 'slateblue': 0x6A5ACD, - 'slategray': 0x708090, - 'slategrey': 0x708090, - 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, - 'steelblue': 0x4682B4, - 'tan': 0xD2B48C, - 'teal': 0x008080, - 'thistle': 0xD8BFD8, - 'tomato': 0xFF6347, - 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, - 'wheat': 0xF5DEB3, - 'white': 0xFFFFFF, - 'whitesmoke': 0xF5F5F5, - 'yellow': 0xFFFF00, - 'yellowgreen': 0x9ACD32 -}; -const _rgb = { - r: 0, - g: 0, - b: 0 -}; -const _hslA = { - h: 0, - s: 0, - l: 0 -}; -const _hslB = { - h: 0, - s: 0, - l: 0 -}; -function hue2rgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p + (q - p) * 6 * t; - if (t < 1 / 2) return q; - if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t); - return p; -} -function toComponents(source, target) { - target.r = source.r; - target.g = source.g; - target.b = source.b; - return target; -} -class Color$1 { - constructor(r, g, b) { - this.isColor = true; - this.r = 1; - this.g = 1; - this.b = 1; - if (g === undefined && b === undefined) { - // r is THREE.Color, hex or string - return this.set(r); - } - return this.setRGB(r, g, b); - } - set(value) { - if (value && value.isColor) { - this.copy(value); - } else if (typeof value === 'number') { - this.setHex(value); - } else if (typeof value === 'string') { - this.setStyle(value); - } - return this; - } - setScalar(scalar) { - this.r = scalar; - this.g = scalar; - this.b = scalar; - return this; - } - setHex(hex, colorSpace = SRGBColorSpace) { - hex = Math.floor(hex); - this.r = (hex >> 16 & 255) / 255; - this.g = (hex >> 8 & 255) / 255; - this.b = (hex & 255) / 255; - ColorManagement.toWorkingColorSpace(this, colorSpace); - return this; - } - setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) { - this.r = r; - this.g = g; - this.b = b; - ColorManagement.toWorkingColorSpace(this, colorSpace); - return this; - } - setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) { - // h,s,l ranges are in 0.0 - 1.0 - h = euclideanModulo(h, 1); - s = clamp(s, 0, 1); - l = clamp(l, 0, 1); - if (s === 0) { - this.r = this.g = this.b = l; - } else { - const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; - const q = 2 * l - p; - this.r = hue2rgb(q, p, h + 1 / 3); - this.g = hue2rgb(q, p, h); - this.b = hue2rgb(q, p, h - 1 / 3); - } - ColorManagement.toWorkingColorSpace(this, colorSpace); - return this; - } - setStyle(style, colorSpace = SRGBColorSpace) { - function handleAlpha(string) { - if (string === undefined) return; - if (parseFloat(string) < 1) { - console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.'); - } - } - let m; - if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) { - // rgb / hsl + toWorkingColorSpace: function ( color, sourceColorSpace ) { - let color; - const name = m[1]; - const components = m[2]; - switch (name) { - case 'rgb': - case 'rgba': - if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min(255, parseInt(color[1], 10)) / 255; - this.g = Math.min(255, parseInt(color[2], 10)) / 255; - this.b = Math.min(255, parseInt(color[3], 10)) / 255; - ColorManagement.toWorkingColorSpace(this, colorSpace); - handleAlpha(color[4]); - return this; - } - if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min(100, parseInt(color[1], 10)) / 100; - this.g = Math.min(100, parseInt(color[2], 10)) / 100; - this.b = Math.min(100, parseInt(color[3], 10)) / 100; - ColorManagement.toWorkingColorSpace(this, colorSpace); - handleAlpha(color[4]); - return this; - } - break; - case 'hsl': - case 'hsla': - if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - const h = parseFloat(color[1]) / 360; - const s = parseFloat(color[2]) / 100; - const l = parseFloat(color[3]) / 100; - handleAlpha(color[4]); - return this.setHSL(h, s, l, colorSpace); - } - break; - } - } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { - // hex color + return this.convert( color, sourceColorSpace, this.workingColorSpace ); - const hex = m[1]; - const size = hex.length; - if (size === 3) { - // #ff0 - this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255; - this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255; - this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255; - ColorManagement.toWorkingColorSpace(this, colorSpace); - return this; - } else if (size === 6) { - // #ff0000 - this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255; - this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255; - this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255; - ColorManagement.toWorkingColorSpace(this, colorSpace); - return this; - } - } - if (style && style.length > 0) { - return this.setColorName(style, colorSpace); - } - return this; - } - setColorName(style, colorSpace = SRGBColorSpace) { - // color keywords - const hex = _colorKeywords[style.toLowerCase()]; - if (hex !== undefined) { - // red - this.setHex(hex, colorSpace); - } else { - // unknown color - console.warn('THREE.Color: Unknown color ' + style); - } - return this; - } - clone() { - return new this.constructor(this.r, this.g, this.b); - } - copy(color) { - this.r = color.r; - this.g = color.g; - this.b = color.b; - return this; - } - copySRGBToLinear(color) { - this.r = SRGBToLinear(color.r); - this.g = SRGBToLinear(color.g); - this.b = SRGBToLinear(color.b); - return this; - } - copyLinearToSRGB(color) { - this.r = LinearToSRGB(color.r); - this.g = LinearToSRGB(color.g); - this.b = LinearToSRGB(color.b); - return this; - } - convertSRGBToLinear() { - this.copySRGBToLinear(this); - return this; - } - convertLinearToSRGB() { - this.copyLinearToSRGB(this); - return this; - } - getHex(colorSpace = SRGBColorSpace) { - ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); - return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0; - } - getHexString(colorSpace = SRGBColorSpace) { - return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6); - } - getHSL(target, colorSpace = LinearSRGBColorSpace) { - // h,s,l ranges are in 0.0 - 1.0 + }, - ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); - const r = _rgb.r, - g = _rgb.g, - b = _rgb.b; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - let hue, saturation; - const lightness = (min + max) / 2.0; - if (min === max) { - hue = 0; - saturation = 0; - } else { - const delta = max - min; - saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); - switch (max) { - case r: - hue = (g - b) / delta + (g < b ? 6 : 0); - break; - case g: - hue = (b - r) / delta + 2; - break; - case b: - hue = (r - g) / delta + 4; - break; - } - hue /= 6; - } - target.h = hue; - target.s = saturation; - target.l = lightness; - return target; - } - getRGB(target, colorSpace = LinearSRGBColorSpace) { - ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); - target.r = _rgb.r; - target.g = _rgb.g; - target.b = _rgb.b; - return target; - } - getStyle(colorSpace = SRGBColorSpace) { - ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); - if (colorSpace !== SRGBColorSpace) { - // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). - return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`; - } - return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`; - } - offsetHSL(h, s, l) { - this.getHSL(_hslA); - _hslA.h += h; - _hslA.s += s; - _hslA.l += l; - this.setHSL(_hslA.h, _hslA.s, _hslA.l); - return this; - } - add(color) { - this.r += color.r; - this.g += color.g; - this.b += color.b; - return this; - } - addColors(color1, color2) { - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; - return this; - } - addScalar(s) { - this.r += s; - this.g += s; - this.b += s; - return this; - } - sub(color) { - this.r = Math.max(0, this.r - color.r); - this.g = Math.max(0, this.g - color.g); - this.b = Math.max(0, this.b - color.b); - return this; - } - multiply(color) { - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; - return this; - } - multiplyScalar(s) { - this.r *= s; - this.g *= s; - this.b *= s; - return this; - } - lerp(color, alpha) { - this.r += (color.r - this.r) * alpha; - this.g += (color.g - this.g) * alpha; - this.b += (color.b - this.b) * alpha; - return this; - } - lerpColors(color1, color2, alpha) { - this.r = color1.r + (color2.r - color1.r) * alpha; - this.g = color1.g + (color2.g - color1.g) * alpha; - this.b = color1.b + (color2.b - color1.b) * alpha; - return this; - } - lerpHSL(color, alpha) { - this.getHSL(_hslA); - color.getHSL(_hslB); - const h = lerp(_hslA.h, _hslB.h, alpha); - const s = lerp(_hslA.s, _hslB.s, alpha); - const l = lerp(_hslA.l, _hslB.l, alpha); - this.setHSL(h, s, l); - return this; - } - equals(c) { - return c.r === this.r && c.g === this.g && c.b === this.b; - } - fromArray(array, offset = 0) { - this.r = array[offset]; - this.g = array[offset + 1]; - this.b = array[offset + 2]; - return this; - } - toArray(array = [], offset = 0) { - array[offset] = this.r; - array[offset + 1] = this.g; - array[offset + 2] = this.b; - return array; - } - fromBufferAttribute(attribute, index) { - this.r = attribute.getX(index); - this.g = attribute.getY(index); - this.b = attribute.getZ(index); - return this; - } - toJSON() { - return this.getHex(); - } - *[Symbol.iterator]() { - yield this.r; - yield this.g; - yield this.b; - } -} -Color$1.NAMES = _colorKeywords; +}; let _canvas; + class ImageUtils { - static getDataURL(image) { - if (/^data:/i.test(image.src)) { + + static getDataURL( image ) { + + if ( /^data:/i.test( image.src ) ) { + return image.src; + } - if (typeof HTMLCanvasElement == 'undefined') { + + if ( typeof HTMLCanvasElement === 'undefined' ) { + return image.src; + } + let canvas; - if (image instanceof HTMLCanvasElement) { + + if ( image instanceof HTMLCanvasElement ) { + canvas = image; + } else { - if (_canvas === undefined) _canvas = createElementNS('canvas'); + + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); + _canvas.width = image.width; _canvas.height = image.height; - const context = _canvas.getContext('2d'); - if (image instanceof ImageData) { - context.putImageData(image, 0, 0); + + const context = _canvas.getContext( '2d' ); + + if ( image instanceof ImageData ) { + + context.putImageData( image, 0, 0 ); + } else { - context.drawImage(image, 0, 0, image.width, image.height); + + context.drawImage( image, 0, 0, image.width, image.height ); + } + canvas = _canvas; + } - if (canvas.width > 2048 || canvas.height > 2048) { - console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image); - return canvas.toDataURL('image/jpeg', 0.6); + + if ( canvas.width > 2048 || canvas.height > 2048 ) { + + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); + + return canvas.toDataURL( 'image/jpeg', 0.6 ); + } else { - return canvas.toDataURL('image/png'); + + return canvas.toDataURL( 'image/png' ); + } + } - static sRGBToLinear(image) { - if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) { - const canvas = createElementNS('canvas'); + + static sRGBToLinear( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const canvas = createElementNS( 'canvas' ); + canvas.width = image.width; canvas.height = image.height; - const context = canvas.getContext('2d'); - context.drawImage(image, 0, 0, image.width, image.height); - const imageData = context.getImageData(0, 0, image.width, image.height); + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); + + const imageData = context.getImageData( 0, 0, image.width, image.height ); const data = imageData.data; - for (let i = 0; i < data.length; i++) { - data[i] = SRGBToLinear(data[i] / 255) * 255; + + for ( let i = 0; i < data.length; i ++ ) { + + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; + } - context.putImageData(imageData, 0, 0); + + context.putImageData( imageData, 0, 0 ); + return canvas; - } else if (image.data) { - const data = image.data.slice(0); - for (let i = 0; i < data.length; i++) { - if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) { - data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255); + + } else if ( image.data ) { + + const data = image.data.slice( 0 ); + + for ( let i = 0; i < data.length; i ++ ) { + + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { + + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); + } else { + // assuming float - data[i] = SRGBToLinear(data[i]); + data[ i ] = SRGBToLinear( data[ i ] ); + } + } + return { data: data, width: image.width, height: image.height }; + } else { - console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.'); + + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); return image; + } + } + } +let sourceId = 0; + class Source { - constructor(data = null) { + + constructor( data = null ) { + this.isSource = true; + + Object.defineProperty( this, 'id', { value: sourceId ++ } ); + this.uuid = generateUUID(); + this.data = data; + this.version = 0; + } - set needsUpdate(value) { - if (value === true) this.version++; + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + } - toJSON(meta) { - const isRootObject = meta === undefined || typeof meta === 'string'; - if (!isRootObject && meta.images[this.uuid] !== undefined) { - return meta.images[this.uuid]; + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { + + return meta.images[ this.uuid ]; + } + const output = { uuid: this.uuid, url: '' }; + const data = this.data; - if (data !== null) { + + if ( data !== null ) { + let url; - if (Array.isArray(data)) { + + if ( Array.isArray( data ) ) { + // cube texture url = []; - for (let i = 0, l = data.length; i < l; i++) { - if (data[i].isDataTexture) { - url.push(serializeImage(data[i].image)); + + for ( let i = 0, l = data.length; i < l; i ++ ) { + + if ( data[ i ].isDataTexture ) { + + url.push( serializeImage( data[ i ].image ) ); + } else { - url.push(serializeImage(data[i])); + + url.push( serializeImage( data[ i ] ) ); + } + } + } else { + // texture - url = serializeImage(data); + url = serializeImage( data ); + } + output.url = url; + } - if (!isRootObject) { - meta.images[this.uuid] = output; + + if ( ! isRootObject ) { + + meta.images[ this.uuid ] = output; + } + return output; + } + } -function serializeImage(image) { - if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) { + +function serializeImage( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + // default images - return ImageUtils.getDataURL(image); + return ImageUtils.getDataURL( image ); + } else { - if (image.data) { + + if ( image.data ) { + // images of DataTexture return { - data: Array.from(image.data), + data: Array.from( image.data ), width: image.width, height: image.height, type: image.data.constructor.name }; + } else { - console.warn('THREE.Texture: Unable to serialize Texture.'); + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); return {}; + } + } + } let textureId = 0; + class Texture extends EventDispatcher { - constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) { + + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) { + super(); + this.isTexture = true; - Object.defineProperty(this, 'id', { - value: textureId++ - }); + + Object.defineProperty( this, 'id', { value: textureId ++ } ); + this.uuid = generateUUID(); + this.name = ''; - this.source = new Source(image); + + this.source = new Source( image ); this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; this.wrapT = wrapT; + this.magFilter = magFilter; this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; this.internalFormat = null; this.type = type; - this.offset = new Vector2(0, 0); - this.repeat = new Vector2(1, 1); - this.center = new Vector2(0, 0); + + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); this.rotation = 0; + this.matrixAutoUpdate = true; this.matrix = new Matrix3(); + this.generateMipmaps = true; this.premultiplyAlpha = false; this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + + if ( typeof colorSpace === 'string' ) { + + this.colorSpace = colorSpace; + + } else { // @deprecated, r152 + + warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); + this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + + } + - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding; this.userData = {}; + this.version = 0; this.onUpdate = null; + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) + } get image() { + return this.source.data; + } - set image(value) { + + set image( value = null ) { + this.source.data = value; + } + updateMatrix() { - this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + } + clone() { - return new this.constructor().copy(this); + + return new this.constructor().copy( this ); + } - copy(source) { + + copy( source ) { + this.name = source.name; + this.source = source.source; - this.mipmaps = source.mipmaps.slice(0); + this.mipmaps = source.mipmaps.slice( 0 ); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; this.wrapT = source.wrapT; + this.magFilter = source.magFilter; this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; this.internalFormat = source.internalFormat; this.type = source.type; - this.offset.copy(source.offset); - this.repeat.copy(source.repeat); - this.center.copy(source.center); + + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrix.copy(source.matrix); + this.matrix.copy( source.matrix ); + this.generateMipmaps = source.generateMipmaps; this.premultiplyAlpha = source.premultiplyAlpha; this.flipY = source.flipY; this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; - this.userData = JSON.parse(JSON.stringify(source.userData)); + this.colorSpace = source.colorSpace; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + this.needsUpdate = true; + return this; + } - toJSON(meta) { - const isRootObject = meta === undefined || typeof meta === 'string'; - if (!isRootObject && meta.textures[this.uuid] !== undefined) { - return meta.textures[this.uuid]; + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + + return meta.textures[ this.uuid ]; + } + const output = { + metadata: { - version: 4.5, + version: 4.6, type: 'Texture', generator: 'Texture.toJSON' }, + uuid: this.uuid, name: this.name, - image: this.source.toJSON(meta).uuid, + + image: this.source.toJSON( meta ).uuid, + mapping: this.mapping, - repeat: [this.repeat.x, this.repeat.y], - offset: [this.offset.x, this.offset.y], - center: [this.center.x, this.center.y], + channel: this.channel, + + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], rotation: this.rotation, - wrap: [this.wrapS, this.wrapT], + + wrap: [ this.wrapS, this.wrapT ], + format: this.format, + internalFormat: this.internalFormat, type: this.type, - encoding: this.encoding, + colorSpace: this.colorSpace, + minFilter: this.minFilter, magFilter: this.magFilter, anisotropy: this.anisotropy, + flipY: this.flipY, + + generateMipmaps: this.generateMipmaps, premultiplyAlpha: this.premultiplyAlpha, unpackAlignment: this.unpackAlignment + }; - if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData; - if (!isRootObject) { - meta.textures[this.uuid] = output; + + if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData; + + if ( ! isRootObject ) { + + meta.textures[ this.uuid ] = output; + } + return output; + } + dispose() { - this.dispatchEvent({ - type: 'dispose' - }); - } - transformUv(uv) { - if (this.mapping !== UVMapping) return uv; - uv.applyMatrix3(this.matrix); - if (uv.x < 0 || uv.x > 1) { - switch (this.wrapS) { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + transformUv( uv ) { + + if ( this.mapping !== UVMapping ) return uv; + + uv.applyMatrix3( this.matrix ); + + if ( uv.x < 0 || uv.x > 1 ) { + + switch ( this.wrapS ) { + case RepeatWrapping: - uv.x = uv.x - Math.floor(uv.x); + + uv.x = uv.x - Math.floor( uv.x ); break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; break; + case MirroredRepeatWrapping: - if (Math.abs(Math.floor(uv.x) % 2) === 1) { - uv.x = Math.ceil(uv.x) - uv.x; + + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + + uv.x = Math.ceil( uv.x ) - uv.x; + } else { - uv.x = uv.x - Math.floor(uv.x); + + uv.x = uv.x - Math.floor( uv.x ); + } + break; + } + } - if (uv.y < 0 || uv.y > 1) { - switch (this.wrapT) { + + if ( uv.y < 0 || uv.y > 1 ) { + + switch ( this.wrapT ) { + case RepeatWrapping: - uv.y = uv.y - Math.floor(uv.y); + + uv.y = uv.y - Math.floor( uv.y ); break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; break; + case MirroredRepeatWrapping: - if (Math.abs(Math.floor(uv.y) % 2) === 1) { - uv.y = Math.ceil(uv.y) - uv.y; + + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + + uv.y = Math.ceil( uv.y ) - uv.y; + } else { - uv.y = uv.y - Math.floor(uv.y); + + uv.y = uv.y - Math.floor( uv.y ); + } + break; + } + } - if (this.flipY) { + + if ( this.flipY ) { + uv.y = 1 - uv.y; + } + return uv; + } - set needsUpdate(value) { - if (value === true) { - this.version++; + + set needsUpdate( value ) { + + if ( value === true ) { + + this.version ++; this.source.needsUpdate = true; + } + + } + + get encoding() { // @deprecated, r152 + + warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); + return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; + + } + + set encoding( encoding ) { // @deprecated, r152 + + warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); + this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + } + } + Texture.DEFAULT_IMAGE = null; Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; class Vector4 { - constructor(x = 0, y = 0, z = 0, w = 1) { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + Vector4.prototype.isVector4 = true; + this.x = x; this.y = y; this.z = z; this.w = w; + } + get width() { + return this.z; + } - set width(value) { + + set width( value ) { + this.z = value; + } + get height() { + return this.w; + } - set height(value) { + + set height( value ) { + this.w = value; + } - set(x, y, z, w) { + + set( x, y, z, w ) { + this.x = x; this.y = y; this.z = z; this.w = w; + return this; + } - setScalar(scalar) { + + setScalar( scalar ) { + this.x = scalar; this.y = scalar; this.z = scalar; this.w = scalar; + return this; + } - setX(x) { + + setX( x ) { + this.x = x; + return this; + } - setY(y) { + + setY( y ) { + this.y = y; + return this; + } - setZ(z) { + + setZ( z ) { + this.z = z; + return this; + } - setW(w) { + + setW( w ) { + this.w = w; + return this; + } - setComponent(index, value) { - switch (index) { - case 0: - this.x = value; - break; - case 1: - this.y = value; - break; - case 2: - this.z = value; - break; - case 3: - this.w = value; - break; - default: - throw new Error('index is out of range: ' + index); + + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); + } + return this; + } - getComponent(index) { - switch (index) { - case 0: - return this.x; - case 1: - return this.y; - case 2: - return this.z; - case 3: - return this.w; - default: - throw new Error('index is out of range: ' + index); + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); + } + } + clone() { - return new this.constructor(this.x, this.y, this.z, this.w); + + return new this.constructor( this.x, this.y, this.z, this.w ); + } - copy(v) { + + copy( v ) { + this.x = v.x; this.y = v.y; this.z = v.z; - this.w = v.w !== undefined ? v.w : 1; + this.w = ( v.w !== undefined ) ? v.w : 1; + return this; + } - add(v) { + + add( v ) { + this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; + return this; + } - addScalar(s) { + + addScalar( s ) { + this.x += s; this.y += s; this.z += s; this.w += s; + return this; + } - addVectors(a, b) { + + addVectors( a, b ) { + this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; this.w = a.w + b.w; + return this; + } - addScaledVector(v, s) { + + addScaledVector( v, s ) { + this.x += v.x * s; this.y += v.y * s; this.z += v.z * s; this.w += v.w * s; + return this; + } - sub(v) { + + sub( v ) { + this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; + return this; + } - subScalar(s) { + + subScalar( s ) { + this.x -= s; this.y -= s; this.z -= s; this.w -= s; + return this; + } - subVectors(a, b) { + + subVectors( a, b ) { + this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; this.w = a.w - b.w; + return this; + } - multiply(v) { + + multiply( v ) { + this.x *= v.x; this.y *= v.y; this.z *= v.z; this.w *= v.w; + return this; + } - multiplyScalar(scalar) { + + multiplyScalar( scalar ) { + this.x *= scalar; this.y *= scalar; this.z *= scalar; this.w *= scalar; + return this; + } - applyMatrix4(m) { - const x = this.x, - y = this.y, - z = this.z, - w = this.w; + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z, w = this.w; const e = m.elements; - this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; - this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; - this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; - this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + return this; + } - divideScalar(scalar) { - return this.multiplyScalar(1 / scalar); + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + } - setAxisAngleFromQuaternion(q) { + + setAxisAngleFromQuaternion( q ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm // q is assumed to be normalized - this.w = 2 * Math.acos(q.w); - const s = Math.sqrt(1 - q.w * q.w); - if (s < 0.0001) { + this.w = 2 * Math.acos( q.w ); + + const s = Math.sqrt( 1 - q.w * q.w ); + + if ( s < 0.0001 ) { + this.x = 1; this.y = 0; this.z = 0; + } else { + this.x = q.x / s; this.y = q.y / s; this.z = q.z / s; + } + return this; + } - setAxisAngleFromRotationMatrix(m) { + + setAxisAngleFromRotationMatrix( m ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) let angle, x, y, z; // variables for result - const epsilon = 0.01, - // margin to allow for rounding errors - epsilon2 = 0.1, - // margin to distinguish between 0 and 180 degrees + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees te = m.elements, - m11 = te[0], - m12 = te[4], - m13 = te[8], - m21 = te[1], - m22 = te[5], - m23 = te[9], - m31 = te[2], - m32 = te[6], - m33 = te[10]; - if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { + // singularity found // first check for identity matrix which must have +1 for all terms // in leading diagonal and zero in other terms - if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + // this singularity is identity matrix so angle = 0 - this.set(1, 0, 0, 0); + this.set( 1, 0, 0, 0 ); + return this; // zero angle, arbitrary axis + } // otherwise this singularity is angle = 180 angle = Math.PI; - const xx = (m11 + 1) / 2; - const yy = (m22 + 1) / 2; - const zz = (m33 + 1) / 2; - const xy = (m12 + m21) / 4; - const xz = (m13 + m31) / 4; - const yz = (m23 + m32) / 4; - if (xx > yy && xx > zz) { + + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; + + if ( ( xx > yy ) && ( xx > zz ) ) { + // m11 is the largest diagonal term - if (xx < epsilon) { + if ( xx < epsilon ) { + x = 0; y = 0.707106781; z = 0.707106781; + } else { - x = Math.sqrt(xx); + + x = Math.sqrt( xx ); y = xy / x; z = xz / x; + } - } else if (yy > zz) { + + } else if ( yy > zz ) { + // m22 is the largest diagonal term - if (yy < epsilon) { + if ( yy < epsilon ) { + x = 0.707106781; y = 0; z = 0.707106781; + } else { - y = Math.sqrt(yy); + + y = Math.sqrt( yy ); x = xy / y; z = yz / y; + } + } else { + // m33 is the largest diagonal term so base result on this - if (zz < epsilon) { + if ( zz < epsilon ) { + x = 0.707106781; y = 0.707106781; z = 0; + } else { - z = Math.sqrt(zz); + + z = Math.sqrt( zz ); x = xz / z; y = yz / z; + } + } - this.set(x, y, z, angle); + + this.set( x, y, z, angle ); + return this; // return 180 deg rotation + } // as we have reached here there are no singularities so we can handle normally - let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize + let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - if (Math.abs(s) < 0.001) s = 1; + if ( Math.abs( s ) < 0.001 ) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be // caught by singularity test above, but I've left it in just in case - this.x = (m32 - m23) / s; - this.y = (m13 - m31) / s; - this.z = (m21 - m12) / s; - this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + return this; + } - min(v) { - this.x = Math.min(this.x, v.x); - this.y = Math.min(this.y, v.y); - this.z = Math.min(this.z, v.z); - this.w = Math.min(this.w, v.w); + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); + return this; + } - max(v) { - this.x = Math.max(this.x, v.x); - this.y = Math.max(this.y, v.y); - this.z = Math.max(this.z, v.z); - this.w = Math.max(this.w, v.w); + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); + return this; + } - clamp(min, max) { + + clamp( min, max ) { + // assumes min < max, componentwise - this.x = Math.max(min.x, Math.min(max.x, this.x)); - this.y = Math.max(min.y, Math.min(max.y, this.y)); - this.z = Math.max(min.z, Math.min(max.z, this.z)); - this.w = Math.max(min.w, Math.min(max.w, this.w)); + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + return this; + } - clampScalar(minVal, maxVal) { - this.x = Math.max(minVal, Math.min(maxVal, this.x)); - this.y = Math.max(minVal, Math.min(maxVal, this.y)); - this.z = Math.max(minVal, Math.min(maxVal, this.z)); - this.w = Math.max(minVal, Math.min(maxVal, this.w)); + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + return this; + } - clampLength(min, max) { + + clampLength( min, max ) { + const length = this.length(); - return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length))); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + } + floor() { - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); - this.z = Math.floor(this.z); - this.w = Math.floor(this.w); + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); + return this; + } + ceil() { - this.x = Math.ceil(this.x); - this.y = Math.ceil(this.y); - this.z = Math.ceil(this.z); - this.w = Math.ceil(this.w); + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); + return this; + } + round() { - this.x = Math.round(this.x); - this.y = Math.round(this.y); - this.z = Math.round(this.z); - this.w = Math.round(this.w); + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); + return this; + } + roundToZero() { - this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); - this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); - this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z); - this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w); + + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + return this; + } + negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + return this; + } - dot(v) { + + dot( v ) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + } + manhattanLength() { - return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + } + normalize() { - return this.divideScalar(this.length() || 1); + + return this.divideScalar( this.length() || 1 ); + } - setLength(length) { - return this.normalize().multiplyScalar(length); + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + } - lerp(v, alpha) { - this.x += (v.x - this.x) * alpha; - this.y += (v.y - this.y) * alpha; - this.z += (v.z - this.z) * alpha; - this.w += (v.w - this.w) * alpha; + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; + return this; + } - lerpVectors(v1, v2, alpha) { - this.x = v1.x + (v2.x - v1.x) * alpha; - this.y = v1.y + (v2.y - v1.y) * alpha; - this.z = v1.z + (v2.z - v1.z) * alpha; - this.w = v1.w + (v2.w - v1.w) * alpha; + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; + return this; + } - equals(v) { - return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + } - fromArray(array, offset = 0) { - this.x = array[offset]; - this.y = array[offset + 1]; - this.z = array[offset + 2]; - this.w = array[offset + 3]; + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; + return this; + } - toArray(array = [], offset = 0) { - array[offset] = this.x; - array[offset + 1] = this.y; - array[offset + 2] = this.z; - array[offset + 3] = this.w; + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; + return array; + } - fromBufferAttribute(attribute, index) { - this.x = attribute.getX(index); - this.y = attribute.getY(index); - this.z = attribute.getZ(index); - this.w = attribute.getW(index); + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); + return this; + } + random() { + this.x = Math.random(); this.y = Math.random(); this.z = Math.random(); this.w = Math.random(); + return this; + } - *[Symbol.iterator]() { + + *[ Symbol.iterator ]() { + yield this.x; yield this.y; yield this.z; yield this.w; + } + } /* @@ -14663,45671 +15779,62172 @@ class Vector4 { * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */ -class WebGLRenderTarget extends EventDispatcher { - constructor(width = 1, height = 1, options = {}) { +class RenderTarget extends EventDispatcher { + + constructor( width = 1, height = 1, options = {} ) { + super(); - this.isWebGLRenderTarget = true; + + this.isRenderTarget = true; + this.width = width; this.height = height; this.depth = 1; - this.scissor = new Vector4(0, 0, width, height); + + this.scissor = new Vector4( 0, 0, width, height ); this.scissorTest = false; - this.viewport = new Vector4(0, 0, width, height); - const image = { - width: width, - height: height, - depth: 1 - }; - this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); + + this.viewport = new Vector4( 0, 0, width, height ); + + const image = { width: width, height: height, depth: 1 }; + + if ( options.encoding !== undefined ) { + + // @deprecated, r152 + warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' ); + options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + + } + + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); this.texture.isRenderTargetTexture = true; + this.texture.flipY = false; this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + this.samples = options.samples !== undefined ? options.samples : 0; + } - setSize(width, height, depth = 1) { - if (this.width !== width || this.height !== height || this.depth !== depth) { + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + this.width = width; this.height = height; this.depth = depth; + this.texture.image.width = width; this.texture.image.height = height; this.texture.image.depth = depth; + this.dispose(); + } - this.viewport.set(0, 0, width, height); - this.scissor.set(0, 0, width, height); + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + } + clone() { - return new this.constructor().copy(this); + + return new this.constructor().copy( this ); + } - copy(source) { + + copy( source ) { + this.width = source.width; this.height = source.height; this.depth = source.depth; - this.viewport.copy(source.viewport); + + this.scissor.copy( source.scissor ); + this.scissorTest = source.scissorTest; + + this.viewport.copy( source.viewport ); + this.texture = source.texture.clone(); this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328 - const image = Object.assign({}, source.texture.image); - this.texture.source = new Source(image); + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); + this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; - if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { - this.dispatchEvent({ - type: 'dispose' - }); + + this.dispatchEvent( { type: 'dispose' } ); + } + } -class Quaternion { - constructor(x = 0, y = 0, z = 0, w = 1) { - this.isQuaternion = true; - this._x = x; - this._y = y; - this._z = z; - this._w = w; +class WebGLRenderTarget extends RenderTarget { + + constructor( width = 1, height = 1, options = {} ) { + + super( width, height, options ); + + this.isWebGLRenderTarget = true; + } - static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { - // fuzz-free, array-based Quaternion SLERP operation - let x0 = src0[srcOffset0 + 0], - y0 = src0[srcOffset0 + 1], - z0 = src0[srcOffset0 + 2], - w0 = src0[srcOffset0 + 3]; - const x1 = src1[srcOffset1 + 0], - y1 = src1[srcOffset1 + 1], - z1 = src1[srcOffset1 + 2], - w1 = src1[srcOffset1 + 3]; - if (t === 0) { - dst[dstOffset + 0] = x0; - dst[dstOffset + 1] = y0; - dst[dstOffset + 2] = z0; - dst[dstOffset + 3] = w0; - return; - } - if (t === 1) { - dst[dstOffset + 0] = x1; - dst[dstOffset + 1] = y1; - dst[dstOffset + 2] = z1; - dst[dstOffset + 3] = w1; - return; - } - if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = cos >= 0 ? 1 : -1, - sqrSin = 1 - cos * cos; +} - // Skip the Slerp for tiny steps to avoid numeric problems: - if (sqrSin > Number.EPSILON) { - const sin = Math.sqrt(sqrSin), - len = Math.atan2(sin, cos * dir); - s = Math.sin(s * len) / sin; - t = Math.sin(t * len) / sin; - } - const tDir = t * dir; - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; +const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; + +function hue2rgb( p, q, t ) { + + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; + +} + +class Color { + + constructor( r, g, b ) { + + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + + return this.set( r, g, b ); + + } + + set( r, g, b ) { + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + + const value = r; + + if ( value && value.isColor ) { + + this.copy( value ); + + } else if ( typeof value === 'number' ) { + + this.setHex( value ); + + } else if ( typeof value === 'string' ) { + + this.setStyle( value ); - // Normalize in case we just did a lerp: - if (s === 1 - t) { - const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; } + + } else { + + this.setRGB( r, g, b ); + } - dst[dstOffset] = x0; - dst[dstOffset + 1] = y0; - dst[dstOffset + 2] = z0; - dst[dstOffset + 3] = w0; - } - static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { - const x0 = src0[srcOffset0]; - const y0 = src0[srcOffset0 + 1]; - const z0 = src0[srcOffset0 + 2]; - const w0 = src0[srcOffset0 + 3]; - const x1 = src1[srcOffset1]; - const y1 = src1[srcOffset1 + 1]; - const z1 = src1[srcOffset1 + 2]; - const w1 = src1[srcOffset1 + 3]; - dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - return dst; - } - get x() { - return this._x; - } - set x(value) { - this._x = value; - this._onChangeCallback(); - } - get y() { - return this._y; - } - set y(value) { - this._y = value; - this._onChangeCallback(); - } - get z() { - return this._z; - } - set z(value) { - this._z = value; - this._onChangeCallback(); - } - get w() { - return this._w; - } - set w(value) { - this._w = value; - this._onChangeCallback(); + + return this; + } - set(x, y, z, w) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; - this._onChangeCallback(); + + setScalar( scalar ) { + + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } - clone() { - return new this.constructor(this._x, this._y, this._z, this._w); + + setHex( hex, colorSpace = SRGBColorSpace ) { + + hex = Math.floor( hex ); + + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + } - copy(quaternion) { - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; - this._onChangeCallback(); + + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { + + this.r = r; + this.g = g; + this.b = b; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + return this; + } - setFromEuler(euler, update) { - const x = euler._x, - y = euler._y, - z = euler._z, - order = euler._order; - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); + + if ( s === 0 ) { + + this.r = this.g = this.b = l; + + } else { + + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const q = ( 2 * l ) - p; + + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - const cos = Math.cos; - const sin = Math.sin; - const c1 = cos(x / 2); - const c2 = cos(y / 2); - const c3 = cos(z / 2); - const s1 = sin(x / 2); - const s2 = sin(y / 2); - const s3 = sin(z / 2); - switch (order) { - case 'XYZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - case 'ZYX': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; - case 'XZY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; - default: - console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order); } - if (update !== false) this._onChangeCallback(); - return this; - } - setFromAxisAngle(axis, angle) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - // assumes axis is normalized + ColorManagement.toWorkingColorSpace( this, colorSpace ); - const halfAngle = angle / 2, - s = Math.sin(halfAngle); - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos(halfAngle); - this._onChangeCallback(); return this; + } - setFromRotationMatrix(m) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + setStyle( style, colorSpace = SRGBColorSpace ) { + + function handleAlpha( string ) { + + if ( string === undefined ) return; + + if ( parseFloat( string ) < 1 ) { + + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + + } - const te = m.elements, - m11 = te[0], - m12 = te[4], - m13 = te[8], - m21 = te[1], - m22 = te[5], - m23 = te[9], - m31 = te[2], - m32 = te[6], - m33 = te[10], - trace = m11 + m22 + m33; - if (trace > 0) { - const s = 0.5 / Math.sqrt(trace + 1.0); - this._w = 0.25 / s; - this._x = (m32 - m23) * s; - this._y = (m13 - m31) * s; - this._z = (m21 - m12) * s; - } else if (m11 > m22 && m11 > m33) { - const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33); - this._w = (m32 - m23) / s; - this._x = 0.25 * s; - this._y = (m12 + m21) / s; - this._z = (m13 + m31) / s; - } else if (m22 > m33) { - const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33); - this._w = (m13 - m31) / s; - this._x = (m12 + m21) / s; - this._y = 0.25 * s; - this._z = (m23 + m32) / s; - } else { - const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22); - this._w = (m21 - m12) / s; - this._x = (m13 + m31) / s; - this._y = (m23 + m32) / s; - this._z = 0.25 * s; } - this._onChangeCallback(); - return this; - } - setFromUnitVectors(vFrom, vTo) { - // assumes direction vectors vFrom and vTo are normalized - let r = vFrom.dot(vTo) + 1; - if (r < Number.EPSILON) { - // vFrom and vTo point in opposite directions - r = 0; - if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { - this._x = -vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; + let m; + + if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) { + + // rgb / hsl + + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; + + switch ( name ) { + + case 'rgb': + case 'rgba': + + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // rgb(255,0,0) rgba(255,0,0,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setRGB( + Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255, + Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255, + Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255, + colorSpace + ); + + } + + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setRGB( + Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100, + Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100, + Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100, + colorSpace + ); + + } + + break; + + case 'hsl': + case 'hsla': + + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setHSL( + parseFloat( color[ 1 ] ) / 360, + parseFloat( color[ 2 ] ) / 100, + parseFloat( color[ 3 ] ) / 100, + colorSpace + ); + + } + + break; + + default: + + console.warn( 'THREE.Color: Unknown color model ' + style ); + + } + + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + + // hex color + + const hex = m[ 1 ]; + const size = hex.length; + + if ( size === 3 ) { + + // #ff0 + return this.setRGB( + parseInt( hex.charAt( 0 ), 16 ) / 15, + parseInt( hex.charAt( 1 ), 16 ) / 15, + parseInt( hex.charAt( 2 ), 16 ) / 15, + colorSpace + ); + + } else if ( size === 6 ) { + + // #ff0000 + return this.setHex( parseInt( hex, 16 ), colorSpace ); + } else { - this._x = 0; - this._y = -vFrom.z; - this._z = vFrom.y; - this._w = r; + + console.warn( 'THREE.Color: Invalid hex color ' + style ); + } - } else { - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; - } - return this.normalize(); - } - angleTo(q) { - return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1))); - } - rotateTowards(q, step) { - const angle = this.angleTo(q); - if (angle === 0) return this; - const t = Math.min(1, step / angle); - this.slerp(q, t); - return this; - } - identity() { - return this.set(0, 0, 0, 1); - } - invert() { - // quaternion is assumed to have unit length + } else if ( style && style.length > 0 ) { + + return this.setColorName( style, colorSpace ); - return this.conjugate(); - } - conjugate() { - this._x *= -1; - this._y *= -1; - this._z *= -1; - this._onChangeCallback(); - return this; - } - dot(v) { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - } - lengthSq() { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - } - length() { - return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); - } - normalize() { - let l = this.length(); - if (l === 0) { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; - } else { - l = 1 / l; - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; } - this._onChangeCallback(); - return this; - } - multiply(q) { - return this.multiplyQuaternions(this, q); - } - premultiply(q) { - return this.multiplyQuaternions(q, this); - } - multiplyQuaternions(a, b) { - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - const qax = a._x, - qay = a._y, - qaz = a._z, - qaw = a._w; - const qbx = b._x, - qby = b._y, - qbz = b._z, - qbw = b._w; - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - this._onChangeCallback(); return this; + } - slerp(qb, t) { - if (t === 0) return this; - if (t === 1) return this.copy(qb); - const x = this._x, - y = this._y, - z = this._z, - w = this._w; - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + setColorName( style, colorSpace = SRGBColorSpace ) { + + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; + + if ( hex !== undefined ) { + + // red + this.setHex( hex, colorSpace ); - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - if (cosHalfTheta < 0) { - this._w = -qb._w; - this._x = -qb._x; - this._y = -qb._y; - this._z = -qb._z; - cosHalfTheta = -cosHalfTheta; } else { - this.copy(qb); - } - if (cosHalfTheta >= 1.0) { - this._w = w; - this._x = x; - this._y = y; - this._z = z; - return this; - } - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - if (sqrSinHalfTheta <= Number.EPSILON) { - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; - this.normalize(); - this._onChangeCallback(); - return this; + + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); + } - const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); - const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); - const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, - ratioB = Math.sin(t * halfTheta) / sinHalfTheta; - this._w = w * ratioA + this._w * ratioB; - this._x = x * ratioA + this._x * ratioB; - this._y = y * ratioA + this._y * ratioB; - this._z = z * ratioA + this._z * ratioB; - this._onChangeCallback(); - return this; - } - slerpQuaternions(qa, qb, t) { - return this.copy(qa).slerp(qb, t); - } - random() { - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt(1 - u1); - const sqrtu1 = Math.sqrt(u1); - const u2 = 2 * Math.PI * Math.random(); - const u3 = 2 * Math.PI * Math.random(); - return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2)); - } - equals(quaternion) { - return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; - } - fromArray(array, offset = 0) { - this._x = array[offset]; - this._y = array[offset + 1]; - this._z = array[offset + 2]; - this._w = array[offset + 3]; - this._onChangeCallback(); return this; + } - toArray(array = [], offset = 0) { - array[offset] = this._x; - array[offset + 1] = this._y; - array[offset + 2] = this._z; - array[offset + 3] = this._w; - return array; + + clone() { + + return new this.constructor( this.r, this.g, this.b ); + } - fromBufferAttribute(attribute, index) { - this._x = attribute.getX(index); - this._y = attribute.getY(index); - this._z = attribute.getZ(index); - this._w = attribute.getW(index); + + copy( color ) { + + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } - _onChange(callback) { - this._onChangeCallback = callback; + + copySRGBToLinear( color ) { + + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); + return this; - } - _onChangeCallback() {} - *[Symbol.iterator]() { - yield this._x; - yield this._y; - yield this._z; - yield this._w; - } -} -class Vector3 { - constructor(x = 0, y = 0, z = 0) { - Vector3.prototype.isVector3 = true; - this.x = x; - this.y = y; - this.z = z; } - set(x, y, z) { - if (z === undefined) z = this.z; // sprite.scale.set(x,y) - this.x = x; - this.y = y; - this.z = z; + copyLinearToSRGB( color ) { + + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); + return this; + } - setScalar(scalar) { - this.x = scalar; - this.y = scalar; - this.z = scalar; + + convertSRGBToLinear() { + + this.copySRGBToLinear( this ); + return this; + } - setX(x) { - this.x = x; + + convertLinearToSRGB() { + + this.copyLinearToSRGB( this ); + return this; + } - setY(y) { - this.y = y; - return this; + + getHex( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace ); + + return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) ); + } - setZ(z) { - this.z = z; - return this; + + getHexString( colorSpace = SRGBColorSpace ) { + + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); + } - setComponent(index, value) { - switch (index) { - case 0: - this.x = value; - break; - case 1: - this.y = value; - break; - case 2: - this.z = value; - break; - default: - throw new Error('index is out of range: ' + index); + + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + + ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace ); + + const r = _color.r, g = _color.g, b = _color.b; + + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); + + let hue, saturation; + const lightness = ( min + max ) / 2.0; + + if ( min === max ) { + + hue = 0; + saturation = 0; + + } else { + + const delta = max - min; + + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; + + } + + hue /= 6; + } - return this; + + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + } - getComponent(index) { - switch (index) { - case 0: - return this.x; - case 1: - return this.y; - case 2: - return this.z; - default: - throw new Error('index is out of range: ' + index); - } + + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { + + ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace ); + + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + + return target; + } - clone() { - return new this.constructor(this.x, this.y, this.z); + + getStyle( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace ); + + const r = _color.r, g = _color.g, b = _color.b; + + if ( colorSpace !== SRGBColorSpace ) { + + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`; + + } + + return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`; + } - copy(v) { - this.x = v.x; - this.y = v.y; - this.z = v.z; + + offsetHSL( h, s, l ) { + + this.getHSL( _hslA ); + + _hslA.h += h; _hslA.s += s; _hslA.l += l; + + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + return this; + } - add(v) { - this.x += v.x; - this.y += v.y; - this.z += v.z; + + add( color ) { + + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } - addScalar(s) { - this.x += s; - this.y += s; - this.z += s; + + addColors( color1, color2 ) { + + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } - addVectors(a, b) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + + addScalar( s ) { + + this.r += s; + this.g += s; + this.b += s; + return this; + } - addScaledVector(v, s) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + + sub( color ) { + + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); + return this; + } - sub(v) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + + multiply( color ) { + + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } - subScalar(s) { - this.x -= s; - this.y -= s; - this.z -= s; + + multiplyScalar( s ) { + + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } - subVectors(a, b) { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + + lerp( color, alpha ) { + + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; + return this; + } - multiply(v) { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + + lerpColors( color1, color2, alpha ) { + + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; + return this; + } - multiplyScalar(scalar) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + + lerpHSL( color, alpha ) { + + this.getHSL( _hslA ); + color.getHSL( _hslB ); + + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); + return this; + } - multiplyVectors(a, b) { - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + + setFromVector3( v ) { + + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } - applyEuler(euler) { - return this.applyQuaternion(_quaternion$2.setFromEuler(euler)); - } - applyAxisAngle(axis, angle) { - return this.applyQuaternion(_quaternion$2.setFromAxisAngle(axis, angle)); - } - applyMatrix3(m) { - const x = this.x, - y = this.y, - z = this.z; + + applyMatrix3( m ) { + + const r = this.r, g = this.g, b = this.b; const e = m.elements; - this.x = e[0] * x + e[3] * y + e[6] * z; - this.y = e[1] * x + e[4] * y + e[7] * z; - this.z = e[2] * x + e[5] * y + e[8] * z; + + this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b; + this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b; + this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b; + return this; + } - applyNormalMatrix(m) { - return this.applyMatrix3(m).normalize(); + + equals( c ) { + + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + } - applyMatrix4(m) { - const x = this.x, - y = this.y, - z = this.z; - const e = m.elements; - const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); - this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; - this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; - this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + + fromArray( array, offset = 0 ) { + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + return this; + } - applyQuaternion(q) { - const x = this.x, - y = this.y, - z = this.z; - const qx = q.x, - qy = q.y, - qz = q.z, - qw = q.w; - // calculate quat * vector + toArray( array = [], offset = 0 ) { - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = -qx * x - qy * y - qz * z; + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - // calculate result * inverse quat + return array; - this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - return this; - } - project(camera) { - return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); } - unproject(camera) { - return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); - } - transformDirection(m) { - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction - const x = this.x, - y = this.y, - z = this.z; - const e = m.elements; - this.x = e[0] * x + e[4] * y + e[8] * z; - this.y = e[1] * x + e[5] * y + e[9] * z; - this.z = e[2] * x + e[6] * y + e[10] * z; - return this.normalize(); - } - divide(v) { - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - return this; - } - divideScalar(scalar) { - return this.multiplyScalar(1 / scalar); - } - min(v) { - this.x = Math.min(this.x, v.x); - this.y = Math.min(this.y, v.y); - this.z = Math.min(this.z, v.z); - return this; - } - max(v) { - this.x = Math.max(this.x, v.x); - this.y = Math.max(this.y, v.y); - this.z = Math.max(this.z, v.z); - return this; - } - clamp(min, max) { - // assumes min < max, componentwise + fromBufferAttribute( attribute, index ) { + + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); - this.x = Math.max(min.x, Math.min(max.x, this.x)); - this.y = Math.max(min.y, Math.min(max.y, this.y)); - this.z = Math.max(min.z, Math.min(max.z, this.z)); - return this; - } - clampScalar(minVal, maxVal) { - this.x = Math.max(minVal, Math.min(maxVal, this.x)); - this.y = Math.max(minVal, Math.min(maxVal, this.y)); - this.z = Math.max(minVal, Math.min(maxVal, this.z)); - return this; - } - clampLength(min, max) { - const length = this.length(); - return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length))); - } - floor() { - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); - this.z = Math.floor(this.z); - return this; - } - ceil() { - this.x = Math.ceil(this.x); - this.y = Math.ceil(this.y); - this.z = Math.ceil(this.z); - return this; - } - round() { - this.x = Math.round(this.x); - this.y = Math.round(this.y); - this.z = Math.round(this.z); - return this; - } - roundToZero() { - this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); - this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); - this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z); - return this; - } - negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; return this; + } - dot(v) { - return this.x * v.x + this.y * v.y + this.z * v.z; + + toJSON() { + + return this.getHex(); + } - // TODO lengthSquared? + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; - lengthSq() { - return this.x * this.x + this.y * this.y + this.z * this.z; } - length() { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - } - manhattanLength() { - return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); - } - normalize() { - return this.divideScalar(this.length() || 1); - } - setLength(length) { - return this.normalize().multiplyScalar(length); - } - lerp(v, alpha) { - this.x += (v.x - this.x) * alpha; - this.y += (v.y - this.y) * alpha; - this.z += (v.z - this.z) * alpha; - return this; - } - lerpVectors(v1, v2, alpha) { - this.x = v1.x + (v2.x - v1.x) * alpha; - this.y = v1.y + (v2.y - v1.y) * alpha; - this.z = v1.z + (v2.z - v1.z) * alpha; - return this; - } - cross(v) { - return this.crossVectors(this, v); - } - crossVectors(a, b) { - const ax = a.x, - ay = a.y, - az = a.z; - const bx = b.x, - by = b.y, - bz = b.z; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - return this; - } - projectOnVector(v) { - const denominator = v.lengthSq(); - if (denominator === 0) return this.set(0, 0, 0); - const scalar = v.dot(this) / denominator; - return this.copy(v).multiplyScalar(scalar); - } - projectOnPlane(planeNormal) { - _vector$c.copy(this).projectOnVector(planeNormal); - return this.sub(_vector$c); - } - reflect(normal) { - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length - return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); - } - angleTo(v) { - const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); - if (denominator === 0) return Math.PI / 2; - const theta = this.dot(v) / denominator; +} - // clamp, to handle numerical problems +const _color = /*@__PURE__*/ new Color(); + +Color.NAMES = _colorKeywords; + +class Quaternion { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + this.isQuaternion = true; + + this._x = x; + this._y = y; + this._z = z; + this._w = w; - return Math.acos(clamp(theta, -1, 1)); - } - distanceTo(v) { - return Math.sqrt(this.distanceToSquared(v)); - } - distanceToSquared(v) { - const dx = this.x - v.x, - dy = this.y - v.y, - dz = this.z - v.z; - return dx * dx + dy * dy + dz * dz; - } - manhattanDistanceTo(v) { - return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); - } - setFromSpherical(s) { - return this.setFromSphericalCoords(s.radius, s.phi, s.theta); - } - setFromSphericalCoords(radius, phi, theta) { - const sinPhiRadius = Math.sin(phi) * radius; - this.x = sinPhiRadius * Math.sin(theta); - this.y = Math.cos(phi) * radius; - this.z = sinPhiRadius * Math.cos(theta); - return this; - } - setFromCylindrical(c) { - return this.setFromCylindricalCoords(c.radius, c.theta, c.y); - } - setFromCylindricalCoords(radius, theta, y) { - this.x = radius * Math.sin(theta); - this.y = y; - this.z = radius * Math.cos(theta); - return this; - } - setFromMatrixPosition(m) { - const e = m.elements; - this.x = e[12]; - this.y = e[13]; - this.z = e[14]; - return this; - } - setFromMatrixScale(m) { - const sx = this.setFromMatrixColumn(m, 0).length(); - const sy = this.setFromMatrixColumn(m, 1).length(); - const sz = this.setFromMatrixColumn(m, 2).length(); - this.x = sx; - this.y = sy; - this.z = sz; - return this; - } - setFromMatrixColumn(m, index) { - return this.fromArray(m.elements, index * 4); - } - setFromMatrix3Column(m, index) { - return this.fromArray(m.elements, index * 3); - } - setFromEuler(e) { - this.x = e._x; - this.y = e._y; - this.z = e._z; - return this; - } - equals(v) { - return v.x === this.x && v.y === this.y && v.z === this.z; - } - fromArray(array, offset = 0) { - this.x = array[offset]; - this.y = array[offset + 1]; - this.z = array[offset + 2]; - return this; } - toArray(array = [], offset = 0) { - array[offset] = this.x; - array[offset + 1] = this.y; - array[offset + 2] = this.z; - return array; + + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + + // fuzz-free, array-based Quaternion SLERP operation + + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; + + if ( t === 0 ) { + + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; + + } + + if ( t === 1 ) { + + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; + + } + + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; + + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { + + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); + + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; + + } + + const tDir = t * dir; + + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { + + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + + } + + } + + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + } - fromBufferAttribute(attribute, index) { - this.x = attribute.getX(index); - this.y = attribute.getY(index); - this.z = attribute.getZ(index); - return this; + + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; + + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + + return dst; + } - random() { - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - return this; + + get x() { + + return this._x; + } - randomDirection() { - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - const u = (Math.random() - 0.5) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt(1 - u ** 2); - this.x = f * Math.cos(t); - this.y = f * Math.sin(t); - this.z = u; - return this; + set x( value ) { + + this._x = value; + this._onChangeCallback(); + } - *[Symbol.iterator]() { - yield this.x; - yield this.y; - yield this.z; + + get y() { + + return this._y; + } -} -const _vector$c = /*@__PURE__*/new Vector3(); -const _quaternion$2 = /*@__PURE__*/new Quaternion(); -class Box3 { - constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { - this.isBox3 = true; - this.min = min; - this.max = max; + set y( value ) { + + this._y = value; + this._onChangeCallback(); + } - set(min, max) { - this.min.copy(min); - this.max.copy(max); - return this; + + get z() { + + return this._z; + } - setFromArray(array) { - let minX = +Infinity; - let minY = +Infinity; - let minZ = +Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let maxZ = -Infinity; - for (let i = 0, l = array.length; i < l; i += 3) { - const x = array[i]; - const y = array[i + 1]; - const z = array[i + 2]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (z < minZ) minZ = z; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - if (z > maxZ) maxZ = z; - } - this.min.set(minX, minY, minZ); - this.max.set(maxX, maxY, maxZ); - return this; + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + } - setFromBufferAttribute(attribute) { - let minX = +Infinity; - let minY = +Infinity; - let minZ = +Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let maxZ = -Infinity; - for (let i = 0, l = attribute.count; i < l; i++) { - const x = attribute.getX(i); - const y = attribute.getY(i); - const z = attribute.getZ(i); - if (x < minX) minX = x; - if (y < minY) minY = y; - if (z < minZ) minZ = z; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - if (z > maxZ) maxZ = z; - } - this.min.set(minX, minY, minZ); - this.max.set(maxX, maxY, maxZ); - return this; + + get w() { + + return this._w; + } - setFromPoints(points) { - this.makeEmpty(); - for (let i = 0, il = points.length; i < il; i++) { - this.expandByPoint(points[i]); - } - return this; + + set w( value ) { + + this._w = value; + this._onChangeCallback(); + } - setFromCenterAndSize(center, size) { - const halfSize = _vector$b.copy(size).multiplyScalar(0.5); - this.min.copy(center).sub(halfSize); - this.max.copy(center).add(halfSize); + + set( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._onChangeCallback(); + return this; + } - setFromObject(object, precise = false) { - this.makeEmpty(); - return this.expandByObject(object, precise); - } + clone() { - return new this.constructor().copy(this); - } - copy(box) { - this.min.copy(box.min); - this.max.copy(box.max); - return this; + + return new this.constructor( this._x, this._y, this._z, this._w ); + } - makeEmpty() { - this.min.x = this.min.y = this.min.z = +Infinity; - this.max.x = this.max.y = this.max.z = -Infinity; + + copy( quaternion ) { + + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); + return this; - } - isEmpty() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; } - getCenter(target) { - return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); - } - getSize(target) { - return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); - } - expandByPoint(point) { - this.min.min(point); - this.max.max(point); + + setFromEuler( euler, update ) { + + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m + + const cos = Math.cos; + const sin = Math.sin; + + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); + + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); + + switch ( order ) { + + case 'XYZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'YXZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + case 'ZXY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'ZYX': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + case 'YZX': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'XZY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + + } + + if ( update !== false ) this._onChangeCallback(); + return this; + } - expandByVector(vector) { - this.min.sub(vector); - this.max.add(vector); + + setFromAxisAngle( axis, angle ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + + // assumes axis is normalized + + const halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._onChangeCallback(); + return this; + } - expandByScalar(scalar) { - this.min.addScalar(-scalar); - this.max.addScalar(scalar); + + setFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements, + + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + + trace = m11 + m22 + m33; + + if ( trace > 0 ) { + + const s = 0.5 / Math.sqrt( trace + 1.0 ); + + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; + + } else if ( m11 > m22 && m11 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; + + } else { + + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._onChangeCallback(); + return this; + } - expandByObject(object, precise = false) { - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms - object.updateWorldMatrix(false, false); - const geometry = object.geometry; - if (geometry !== undefined) { - if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) { - const position = geometry.attributes.position; - for (let i = 0, l = position.count; i < l; i++) { - _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld); - this.expandByPoint(_vector$b); - } + setFromUnitVectors( vFrom, vTo ) { + + // assumes direction vectors vFrom and vTo are normalized + + let r = vFrom.dot( vTo ) + 1; + + if ( r < Number.EPSILON ) { + + // vFrom and vTo point in opposite directions + + r = 0; + + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { - if (geometry.boundingBox === null) { - geometry.computeBoundingBox(); - } - _box$3.copy(geometry.boundingBox); - _box$3.applyMatrix4(object.matrixWorld); - this.union(_box$3); + + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; + } + + } else { + + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } - const children = object.children; - for (let i = 0, l = children.length; i < l; i++) { - this.expandByObject(children[i], precise); - } - return this; - } - containsPoint(point) { - return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true; - } - containsBox(box) { - return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; - } - getParameter(point, target) { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); - } - intersectsBox(box) { - // using 6 splitting planes to rule out intersections. - return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true; - } - intersectsSphere(sphere) { - // Find the point on the AABB closest to the sphere center. - this.clampPoint(sphere.center, _vector$b); + return this.normalize(); - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; } - intersectsPlane(plane) { - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. - let min, max; - if (plane.normal.x > 0) { - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; - } else { - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; - } - if (plane.normal.y > 0) { - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; - } else { - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; - } - if (plane.normal.z > 0) { - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; - } else { - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; - } - return min <= -plane.constant && max >= -plane.constant; + angleTo( q ) { + + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); + } - intersectsTriangle(triangle) { - if (this.isEmpty()) { - return false; - } - // compute box center and extents - this.getCenter(_center); - _extents.subVectors(this.max, _center); + rotateTowards( q, step ) { - // translate triangle to aabb origin - _v0$2.subVectors(triangle.a, _center); - _v1$8.subVectors(triangle.b, _center); - _v2$5.subVectors(triangle.c, _center); + const angle = this.angleTo( q ); - // compute edge vectors for triangle - _f0.subVectors(_v1$8, _v0$2); - _f1.subVectors(_v2$5, _v1$8); - _f2.subVectors(_v0$2, _v2$5); + if ( angle === 0 ) return this; - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0]; - if (!satForAxes(axes, _v0$2, _v1$8, _v2$5, _extents)) { - return false; - } + const t = Math.min( 1, step / angle ); - // test 3 face normals from the aabb - axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - if (!satForAxes(axes, _v0$2, _v1$8, _v2$5, _extents)) { - return false; - } + this.slerp( q, t ); + + return this; - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors(_f0, _f1); - axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; - return satForAxes(axes, _v0$2, _v1$8, _v2$5, _extents); - } - clampPoint(point, target) { - return target.copy(point).clamp(this.min, this.max); - } - distanceToPoint(point) { - const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max); - return clampedPoint.sub(point).length(); } - getBoundingSphere(target) { - this.getCenter(target.center); - target.radius = this.getSize(_vector$b).length() * 0.5; - return target; + + identity() { + + return this.set( 0, 0, 0, 1 ); + } - intersect(box) { - this.min.max(box.min); - this.max.min(box.max); - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if (this.isEmpty()) this.makeEmpty(); - return this; + invert() { + + // quaternion is assumed to have unit length + + return this.conjugate(); + } - union(box) { - this.min.min(box.min); - this.max.max(box.max); + + conjugate() { + + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); + return this; + } - applyMatrix4(matrix) { - // transform of empty box is an empty box. - if (this.isEmpty()) return this; - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000 - _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001 - _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010 - _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011 - _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100 - _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101 - _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110 - _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111 - - this.setFromPoints(_points); - return this; + dot( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } - translate(offset) { - this.min.add(offset); - this.max.add(offset); - return this; + + lengthSq() { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } - equals(box) { - return box.min.equals(this.min) && box.max.equals(this.max); + + length() { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + } -} -const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()]; -const _vector$b = /*@__PURE__*/new Vector3(); -const _box$3 = /*@__PURE__*/new Box3(); -// triangle centered vertices + normalize() { -const _v0$2 = /*@__PURE__*/new Vector3(); -const _v1$8 = /*@__PURE__*/new Vector3(); -const _v2$5 = /*@__PURE__*/new Vector3(); + let l = this.length(); -// triangle edge vectors + if ( l === 0 ) { -const _f0 = /*@__PURE__*/new Vector3(); -const _f1 = /*@__PURE__*/new Vector3(); -const _f2 = /*@__PURE__*/new Vector3(); -const _center = /*@__PURE__*/new Vector3(); -const _extents = /*@__PURE__*/new Vector3(); -const _triangleNormal = /*@__PURE__*/new Vector3(); -const _testAxis = /*@__PURE__*/new Vector3(); -function satForAxes(axes, v0, v1, v2, extents) { - for (let i = 0, j = axes.length - 3; i <= j; i += 3) { - _testAxis.fromArray(axes, i); - // project the aabb onto the separating axis - const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); - // project all 3 vertices of the triangle onto the separating axis - const p0 = v0.dot(_testAxis); - const p1 = v1.dot(_testAxis); - const p2 = v2.dot(_testAxis); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is separating and we can exit - return false; - } - } - return true; -} + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; -const _box$2 = /*@__PURE__*/new Box3(); -const _v1$7 = /*@__PURE__*/new Vector3(); -const _v2$4 = /*@__PURE__*/new Vector3(); -class Sphere { - constructor(center = new Vector3(), radius = -1) { - this.center = center; - this.radius = radius; - } - set(center, radius) { - this.center.copy(center); - this.radius = radius; - return this; - } - setFromPoints(points, optionalCenter) { - const center = this.center; - if (optionalCenter !== undefined) { - center.copy(optionalCenter); } else { - _box$2.setFromPoints(points).getCenter(center); - } - let maxRadiusSq = 0; - for (let i = 0, il = points.length; i < il; i++) { - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } - this.radius = Math.sqrt(maxRadiusSq); + + this._onChangeCallback(); + return this; + } - copy(sphere) { - this.center.copy(sphere.center); - this.radius = sphere.radius; - return this; + + multiply( q ) { + + return this.multiplyQuaternions( this, q ); + } - isEmpty() { - return this.radius < 0; + + premultiply( q ) { + + return this.multiplyQuaternions( q, this ); + } - makeEmpty() { - this.center.set(0, 0, 0); - this.radius = -1; + + multiplyQuaternions( a, b ) { + + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + + this._onChangeCallback(); + return this; + } - containsPoint(point) { - return point.distanceToSquared(this.center) <= this.radius * this.radius; - } - distanceToPoint(point) { - return point.distanceTo(this.center) - this.radius; - } - intersectsSphere(sphere) { - const radiusSum = this.radius + sphere.radius; - return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; - } - intersectsBox(box) { - return box.intersectsSphere(this); - } - intersectsPlane(plane) { - return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; - } - clampPoint(point, target) { - const deltaLengthSq = this.center.distanceToSquared(point); - target.copy(point); - if (deltaLengthSq > this.radius * this.radius) { - target.sub(this.center).normalize(); - target.multiplyScalar(this.radius).add(this.center); - } - return target; - } - getBoundingBox(target) { - if (this.isEmpty()) { - // Empty sphere produces empty bounding box - target.makeEmpty(); - return target; - } - target.set(this.center, this.center); - target.expandByScalar(this.radius); - return target; - } - applyMatrix4(matrix) { - this.center.applyMatrix4(matrix); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); - return this; - } - translate(offset) { - this.center.add(offset); - return this; - } - expandByPoint(point) { - if (this.isEmpty()) { - this.center.copy(point); - this.radius = 0; - return this; - } - _v1$7.subVectors(point, this.center); - const lengthSq = _v1$7.lengthSq(); - if (lengthSq > this.radius * this.radius) { - // calculate the minimal sphere - const length = Math.sqrt(lengthSq); - const delta = (length - this.radius) * 0.5; - this.center.addScaledVector(_v1$7, delta / length); - this.radius += delta; + slerp( qb, t ) { + + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); + + const x = this._x, y = this._y, z = this._z, w = this._w; + + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + + if ( cosHalfTheta < 0 ) { + + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; + + cosHalfTheta = - cosHalfTheta; + + } else { + + this.copy( qb ); + } - return this; - } - union(sphere) { - if (sphere.isEmpty()) { + + if ( cosHalfTheta >= 1.0 ) { + + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } - if (this.isEmpty()) { - this.copy(sphere); + + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); + return this; + } - if (this.center.equals(sphere.center) === true) { - this.radius = Math.max(this.radius, sphere.radius); - } else { - _v2$4.subVectors(sphere.center, this.center).setLength(sphere.radius); - this.expandByPoint(_v1$7.copy(sphere.center).add(_v2$4)); - this.expandByPoint(_v1$7.copy(sphere.center).sub(_v2$4)); - } + + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); + + this._onChangeCallback(); + return this; + } - equals(sphere) { - return sphere.center.equals(this.center) && sphere.radius === this.radius; - } - clone() { - return new this.constructor().copy(this); - } -} -const _vector1 = /*@__PURE__*/new Vector3(); -const _vector2$1 = /*@__PURE__*/new Vector3(); -const _normalMatrix = /*@__PURE__*/new Matrix3(); -class Plane { - constructor(normal = new Vector3(1, 0, 0), constant = 0) { - this.isPlane = true; + slerpQuaternions( qa, qb, t ) { - // normal is assumed to be normalized + return this.copy( qa ).slerp( qb, t ); - this.normal = normal; - this.constant = constant; } - set(normal, constant) { - this.normal.copy(normal); - this.constant = constant; - return this; + + random() { + + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. + + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); + + const u2 = 2 * Math.PI * Math.random(); + + const u3 = 2 * Math.PI * Math.random(); + + return this.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), + ); + } - setComponents(x, y, z, w) { - this.normal.set(x, y, z); - this.constant = w; - return this; + + equals( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + } - setFromNormalAndCoplanarPoint(normal, point) { - this.normal.copy(normal); - this.constant = -point.dot(this.normal); + + fromArray( array, offset = 0 ) { + + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; + + this._onChangeCallback(); + return this; + } - setFromCoplanarPoints(a, b, c) { - const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; + + return array; - this.setFromNormalAndCoplanarPoint(normal, a); - return this; } - copy(plane) { - this.normal.copy(plane.normal); - this.constant = plane.constant; + + fromBufferAttribute( attribute, index ) { + + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); + return this; + } - normalize() { - // Note: will lead to a divide by zero if the plane is invalid. - const inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar(inverseNormalLength); - this.constant *= inverseNormalLength; - return this; + toJSON() { + + return this.toArray(); + } - negate() { - this.constant *= -1; - this.normal.negate(); + + _onChange( callback ) { + + this._onChangeCallback = callback; + return this; - } - distanceToPoint(point) { - return this.normal.dot(point) + this.constant; - } - distanceToSphere(sphere) { - return this.distanceToPoint(sphere.center) - sphere.radius; - } - projectPoint(point, target) { - return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point); - } - intersectLine(line, target) { - const direction = line.delta(_vector1); - const denominator = this.normal.dot(direction); - if (denominator === 0) { - // line is coplanar, return origin - if (this.distanceToPoint(line.start) === 0) { - return target.copy(line.start); - } - // Unsure if this is the correct method to handle this case. - return null; - } - const t = -(line.start.dot(this.normal) + this.constant) / denominator; - if (t < 0 || t > 1) { - return null; - } - return target.copy(direction).multiplyScalar(t).add(line.start); } - intersectsLine(line) { - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - const startSign = this.distanceToPoint(line.start); - const endSign = this.distanceToPoint(line.end); - return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; - } - intersectsBox(box) { - return box.intersectsPlane(this); - } - intersectsSphere(sphere) { - return sphere.intersectsPlane(this); + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } - coplanarPoint(target) { - return target.copy(this.normal).multiplyScalar(-this.constant); + +} + +class Vector3 { + + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; + } - applyMatrix4(matrix, optionalNormalMatrix) { - const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); - const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); - const normal = this.normal.applyMatrix3(normalMatrix).normalize(); - this.constant = -referencePoint.dot(normal); + + set( x, y, z ) { + + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + + this.x = x; + this.y = y; + this.z = z; + return this; + } - translate(offset) { - this.constant -= offset.dot(this.normal); + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; - } - equals(plane) { - return plane.normal.equals(this.normal) && plane.constant === this.constant; - } - clone() { - return new this.constructor().copy(this); - } -} -const _sphere$3 = /*@__PURE__*/new Sphere(); -const _vector$a = /*@__PURE__*/new Vector3(); -class Frustum { - constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) { - this.planes = [p0, p1, p2, p3, p4, p5]; } - set(p0, p1, p2, p3, p4, p5) { - const planes = this.planes; - planes[0].copy(p0); - planes[1].copy(p1); - planes[2].copy(p2); - planes[3].copy(p3); - planes[4].copy(p4); - planes[5].copy(p5); + + setX( x ) { + + this.x = x; + return this; + } - copy(frustum) { - const planes = this.planes; - for (let i = 0; i < 6; i++) { - planes[i].copy(frustum.planes[i]); - } + + setY( y ) { + + this.y = y; + return this; + } - setFromProjectionMatrix(m) { - const planes = this.planes; - const me = m.elements; - const me0 = me[0], - me1 = me[1], - me2 = me[2], - me3 = me[3]; - const me4 = me[4], - me5 = me[5], - me6 = me[6], - me7 = me[7]; - const me8 = me[8], - me9 = me[9], - me10 = me[10], - me11 = me[11]; - const me12 = me[12], - me13 = me[13], - me14 = me[14], - me15 = me[15]; - planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); - planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); - planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); - planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); - planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); - planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + + setZ( z ) { + + this.z = z; + return this; + } - intersectsObject(object) { - const geometry = object.geometry; - if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); - _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); - return this.intersectsSphere(_sphere$3); - } - intersectsSprite(sprite) { - _sphere$3.center.set(0, 0, 0); - _sphere$3.radius = 0.7071067811865476; - _sphere$3.applyMatrix4(sprite.matrixWorld); - return this.intersectsSphere(_sphere$3); - } - intersectsSphere(sphere) { - const planes = this.planes; - const center = sphere.center; - const negRadius = -sphere.radius; - for (let i = 0; i < 6; i++) { - const distance = planes[i].distanceToPoint(center); - if (distance < negRadius) { - return false; - } - } - return true; - } - intersectsBox(box) { - const planes = this.planes; - for (let i = 0; i < 6; i++) { - const plane = planes[i]; - // corner at max distance + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'index is out of range: ' + index ); - _vector$a.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector$a.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector$a.z = plane.normal.z > 0 ? box.max.z : box.min.z; - if (plane.distanceToPoint(_vector$a) < 0) { - return false; - } } - return true; + + return this; + } - containsPoint(point) { - const planes = this.planes; - for (let i = 0; i < 6; i++) { - if (planes[i].distanceToPoint(point) < 0) { - return false; - } + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); + } - return true; + } + clone() { - return new this.constructor().copy(this); - } -} -class Matrix4 { - constructor() { - Matrix4.prototype.isMatrix4 = true; - this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + return new this.constructor( this.x, this.y, this.z ); + } - set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { - const te = this.elements; - te[0] = n11; - te[4] = n12; - te[8] = n13; - te[12] = n14; - te[1] = n21; - te[5] = n22; - te[9] = n23; - te[13] = n24; - te[2] = n31; - te[6] = n32; - te[10] = n33; - te[14] = n34; - te[3] = n41; - te[7] = n42; - te[11] = n43; - te[15] = n44; + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } - identity() { - this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } - clone() { - return new Matrix4().fromArray(this.elements); - } - copy(m) { - const te = this.elements; - const me = m.elements; - te[0] = me[0]; - te[1] = me[1]; - te[2] = me[2]; - te[3] = me[3]; - te[4] = me[4]; - te[5] = me[5]; - te[6] = me[6]; - te[7] = me[7]; - te[8] = me[8]; - te[9] = me[9]; - te[10] = me[10]; - te[11] = me[11]; - te[12] = me[12]; - te[13] = me[13]; - te[14] = me[14]; - te[15] = me[15]; + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + return this; + } - copyPosition(m) { - const te = this.elements, - me = m.elements; - te[12] = me[12]; - te[13] = me[13]; - te[14] = me[14]; + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } - setFromMatrix3(m) { - const me = m.elements; - this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } - extractBasis(xAxis, yAxis, zAxis) { - xAxis.setFromMatrixColumn(this, 0); - yAxis.setFromMatrixColumn(this, 1); - zAxis.setFromMatrixColumn(this, 2); + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } - makeBasis(xAxis, yAxis, zAxis) { - this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1); + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } - extractRotation(m) { - // this method does not support reflection matrices - const te = this.elements; - const me = m.elements; - const scaleX = 1 / _v1$6.setFromMatrixColumn(m, 0).length(); - const scaleY = 1 / _v1$6.setFromMatrixColumn(m, 1).length(); - const scaleZ = 1 / _v1$6.setFromMatrixColumn(m, 2).length(); - te[0] = me[0] * scaleX; - te[1] = me[1] * scaleX; - te[2] = me[2] * scaleX; - te[3] = 0; - te[4] = me[4] * scaleY; - te[5] = me[5] * scaleY; - te[6] = me[6] * scaleY; - te[7] = 0; - te[8] = me[8] * scaleZ; - te[9] = me[9] * scaleZ; - te[10] = me[10] * scaleZ; - te[11] = 0; - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } - makeRotationFromEuler(euler) { - const te = this.elements; - const x = euler.x, - y = euler.y, - z = euler.z; - const a = Math.cos(x), - b = Math.sin(x); - const c = Math.cos(y), - d = Math.sin(y); - const e = Math.cos(z), - f = Math.sin(z); - if (euler.order === 'XYZ') { - const ae = a * e, - af = a * f, - be = b * e, - bf = b * f; - te[0] = c * e; - te[4] = -c * f; - te[8] = d; - te[1] = af + be * d; - te[5] = ae - bf * d; - te[9] = -b * c; - te[2] = bf - ae * d; - te[6] = be + af * d; - te[10] = a * c; - } else if (euler.order === 'YXZ') { - const ce = c * e, - cf = c * f, - de = d * e, - df = d * f; - te[0] = ce + df * b; - te[4] = de * b - cf; - te[8] = a * d; - te[1] = a * f; - te[5] = a * e; - te[9] = -b; - te[2] = cf * b - de; - te[6] = df + ce * b; - te[10] = a * c; - } else if (euler.order === 'ZXY') { - const ce = c * e, - cf = c * f, - de = d * e, - df = d * f; - te[0] = ce - df * b; - te[4] = -a * f; - te[8] = de + cf * b; - te[1] = cf + de * b; - te[5] = a * e; - te[9] = df - ce * b; - te[2] = -a * d; - te[6] = b; - te[10] = a * c; - } else if (euler.order === 'ZYX') { - const ae = a * e, - af = a * f, - be = b * e, - bf = b * f; - te[0] = c * e; - te[4] = be * d - af; - te[8] = ae * d + bf; - te[1] = c * f; - te[5] = bf * d + ae; - te[9] = af * d - be; - te[2] = -d; - te[6] = b * c; - te[10] = a * c; - } else if (euler.order === 'YZX') { - const ac = a * c, - ad = a * d, - bc = b * c, - bd = b * d; - te[0] = c * e; - te[4] = bd - ac * f; - te[8] = bc * f + ad; - te[1] = f; - te[5] = a * e; - te[9] = -b * e; - te[2] = -d * e; - te[6] = ad * f + bc; - te[10] = ac - bd * f; - } else if (euler.order === 'XZY') { - const ac = a * c, - ad = a * d, - bc = b * c, - bd = b * d; - te[0] = c * e; - te[4] = -f; - te[8] = d * e; - te[1] = ac * f + bd; - te[5] = a * e; - te[9] = ad * f - bc; - te[2] = bc * f - ad; - te[6] = b * e; - te[10] = bd * f + ac; - } - // bottom row - te[3] = 0; - te[7] = 0; - te[11] = 0; + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - // last column - te[12] = 0; - te[13] = 0; - te[14] = 0; - te[15] = 1; return this; + } - makeRotationFromQuaternion(q) { - return this.compose(_zero, q, _one); - } - lookAt(eye, target, up) { - const te = this.elements; - _z.subVectors(eye, target); - if (_z.lengthSq() === 0) { - // eye and target are in the same position - _z.z = 1; - } - _z.normalize(); - _x.crossVectors(up, _z); - if (_x.lengthSq() === 0) { - // up and z are parallel + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - if (Math.abs(up.z) === 1) { - _z.x += 0.0001; - } else { - _z.z += 0.0001; - } - _z.normalize(); - _x.crossVectors(up, _z); - } - _x.normalize(); - _y.crossVectors(_z, _x); - te[0] = _x.x; - te[4] = _y.x; - te[8] = _z.x; - te[1] = _x.y; - te[5] = _y.y; - te[9] = _z.y; - te[2] = _x.z; - te[6] = _y.z; - te[10] = _z.z; return this; + } - multiply(m) { - return this.multiplyMatrices(this, m); + + multiplyVectors( a, b ) { + + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + + return this; + } - premultiply(m) { - return this.multiplyMatrices(m, this); + + applyEuler( euler ) { + + return this.applyQuaternion( _quaternion$2.setFromEuler( euler ) ); + } - multiplyMatrices(a, b) { - const ae = a.elements; - const be = b.elements; - const te = this.elements; - const a11 = ae[0], - a12 = ae[4], - a13 = ae[8], - a14 = ae[12]; - const a21 = ae[1], - a22 = ae[5], - a23 = ae[9], - a24 = ae[13]; - const a31 = ae[2], - a32 = ae[6], - a33 = ae[10], - a34 = ae[14]; - const a41 = ae[3], - a42 = ae[7], - a43 = ae[11], - a44 = ae[15]; - const b11 = be[0], - b12 = be[4], - b13 = be[8], - b14 = be[12]; - const b21 = be[1], - b22 = be[5], - b23 = be[9], - b24 = be[13]; - const b31 = be[2], - b32 = be[6], - b33 = be[10], - b34 = be[14]; - const b41 = be[3], - b42 = be[7], - b43 = be[11], - b44 = be[15]; - te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - return this; + + applyAxisAngle( axis, angle ) { + + return this.applyQuaternion( _quaternion$2.setFromAxisAngle( axis, angle ) ); + } - multiplyScalar(s) { - const te = this.elements; - te[0] *= s; - te[4] *= s; - te[8] *= s; - te[12] *= s; - te[1] *= s; - te[5] *= s; - te[9] *= s; - te[13] *= s; - te[2] *= s; - te[6] *= s; - te[10] *= s; - te[14] *= s; - te[3] *= s; - te[7] *= s; - te[11] *= s; - te[15] *= s; + + applyMatrix3( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + return this; + } - determinant() { - const te = this.elements; - const n11 = te[0], - n12 = te[4], - n13 = te[8], - n14 = te[12]; - const n21 = te[1], - n22 = te[5], - n23 = te[9], - n24 = te[13]; - const n31 = te[2], - n32 = te[6], - n33 = te[10], - n34 = te[14]; - const n41 = te[3], - n42 = te[7], - n43 = te[11], - n44 = te[15]; - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + applyNormalMatrix( m ) { + + return this.applyMatrix3( m ).normalize(); - return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); } - transpose() { - const te = this.elements; - let tmp; - tmp = te[1]; - te[1] = te[4]; - te[4] = tmp; - tmp = te[2]; - te[2] = te[8]; - te[8] = tmp; - tmp = te[6]; - te[6] = te[9]; - te[9] = tmp; - tmp = te[3]; - te[3] = te[12]; - te[12] = tmp; - tmp = te[7]; - te[7] = te[13]; - te[13] = tmp; - tmp = te[11]; - te[11] = te[14]; - te[14] = tmp; + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; + return this; + } - setPosition(x, y, z) { - const te = this.elements; - if (x.isVector3) { - te[12] = x.x; - te[13] = x.y; - te[14] = x.z; - } else { - te[12] = x; - te[13] = y; - te[14] = z; - } + + applyQuaternion( q ) { + + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vector + + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; + + // calculate result * inverse quat + + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + return this; + } - invert() { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, - n11 = te[0], - n21 = te[1], - n31 = te[2], - n41 = te[3], - n12 = te[4], - n22 = te[5], - n32 = te[6], - n42 = te[7], - n13 = te[8], - n23 = te[9], - n33 = te[10], - n43 = te[11], - n14 = te[12], - n24 = te[13], - n34 = te[14], - n44 = te[15], - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - const detInv = 1 / det; - te[0] = t11 * detInv; - te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; - te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; - te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; - te[4] = t12 * detInv; - te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; - te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; - te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; - te[8] = t13 * detInv; - te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; - te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; - te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; - te[12] = t14 * detInv; - te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; - te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; - te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; - return this; + + project( camera ) { + + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + } - scale(v) { - const te = this.elements; - const x = v.x, - y = v.y, - z = v.z; - te[0] *= x; - te[4] *= y; - te[8] *= z; - te[1] *= x; - te[5] *= y; - te[9] *= z; - te[2] *= x; - te[6] *= y; - te[10] *= z; - te[3] *= x; - te[7] *= y; - te[11] *= z; - return this; + + unproject( camera ) { + + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + } - getMaxScaleOnAxis() { - const te = this.elements; - const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; - const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; - const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; - return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + + transformDirection( m ) { + + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + + return this.normalize(); + } - makeTranslation(x, y, z) { - this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } - makeRotationX(theta) { - const c = Math.cos(theta), - s = Math.sin(theta); - this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); - return this; + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + } - makeRotationY(theta) { - const c = Math.cos(theta), - s = Math.sin(theta); - this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + return this; + } - makeRotationZ(theta) { - const c = Math.cos(theta), - s = Math.sin(theta); - this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + return this; + } - makeRotationAxis(axis, angle) { - // Based on http://www.gamedev.net/reference/articles/article1199.asp - const c = Math.cos(angle); - const s = Math.sin(angle); - const t = 1 - c; - const x = axis.x, - y = axis.y, - z = axis.z; - const tx = t * x, - ty = t * y; - this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); + clamp( min, max ) { + + // assumes min < max, componentwise + + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + return this; + } - makeScale(x, y, z) { - this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + return this; + } - makeShear(xy, xz, yx, yz, zx, zy) { - this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); - return this; + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + } - compose(position, quaternion, scale) { - const te = this.elements; - const x = quaternion._x, - y = quaternion._y, - z = quaternion._z, - w = quaternion._w; - const x2 = x + x, - y2 = y + y, - z2 = z + z; - const xx = x * x2, - xy = x * y2, - xz = x * z2; - const yy = y * y2, - yz = y * z2, - zz = z * z2; - const wx = w * x2, - wy = w * y2, - wz = w * z2; - const sx = scale.x, - sy = scale.y, - sz = scale.z; - te[0] = (1 - (yy + zz)) * sx; - te[1] = (xy + wz) * sx; - te[2] = (xz - wy) * sx; - te[3] = 0; - te[4] = (xy - wz) * sy; - te[5] = (1 - (xx + zz)) * sy; - te[6] = (yz + wx) * sy; - te[7] = 0; - te[8] = (xz + wy) * sz; - te[9] = (yz - wx) * sz; - te[10] = (1 - (xx + yy)) * sz; - te[11] = 0; - te[12] = position.x; - te[13] = position.y; - te[14] = position.z; - te[15] = 1; + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + return this; + } - decompose(position, quaternion, scale) { - const te = this.elements; - let sx = _v1$6.set(te[0], te[1], te[2]).length(); - const sy = _v1$6.set(te[4], te[5], te[6]).length(); - const sz = _v1$6.set(te[8], te[9], te[10]).length(); - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if (det < 0) sx = -sx; - position.x = te[12]; - position.y = te[13]; - position.z = te[14]; + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - // scale the rotation part - _m1$2.copy(this); - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; - _m1$2.elements[0] *= invSX; - _m1$2.elements[1] *= invSX; - _m1$2.elements[2] *= invSX; - _m1$2.elements[4] *= invSY; - _m1$2.elements[5] *= invSY; - _m1$2.elements[6] *= invSY; - _m1$2.elements[8] *= invSZ; - _m1$2.elements[9] *= invSZ; - _m1$2.elements[10] *= invSZ; - quaternion.setFromRotationMatrix(_m1$2); - scale.x = sx; - scale.y = sy; - scale.z = sz; return this; + } - makePerspective(left, right, top, bottom, near, far) { - const te = this.elements; - const x = 2 * near / (right - left); - const y = 2 * near / (top - bottom); - const a = (right + left) / (right - left); - const b = (top + bottom) / (top - bottom); - const c = -(far + near) / (far - near); - const d = -2 * far * near / (far - near); - te[0] = x; - te[4] = 0; - te[8] = a; - te[12] = 0; - te[1] = 0; - te[5] = y; - te[9] = b; - te[13] = 0; - te[2] = 0; - te[6] = 0; - te[10] = c; - te[14] = d; - te[3] = 0; - te[7] = 0; - te[11] = -1; - te[15] = 0; + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + return this; + } - makeOrthographic(left, right, top, bottom, near, far) { - const te = this.elements; - const w = 1.0 / (right - left); - const h = 1.0 / (top - bottom); - const p = 1.0 / (far - near); - const x = (right + left) * w; - const y = (top + bottom) * h; - const z = (far + near) * p; - te[0] = 2 * w; - te[4] = 0; - te[8] = 0; - te[12] = -x; - te[1] = 0; - te[5] = 2 * h; - te[9] = 0; - te[13] = -y; - te[2] = 0; - te[6] = 0; - te[10] = -2 * p; - te[14] = -z; - te[3] = 0; - te[7] = 0; - te[11] = 0; - te[15] = 1; + + roundToZero() { + + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + return this; + } - equals(matrix) { - const te = this.elements; - const me = matrix.elements; - for (let i = 0; i < 16; i++) { - if (te[i] !== me[i]) return false; - } - return true; - } - fromArray(array, offset = 0) { - for (let i = 0; i < 16; i++) { - this.elements[i] = array[i + offset]; - } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + return this; + } - toArray(array = [], offset = 0) { - const te = this.elements; - array[offset] = te[0]; - array[offset + 1] = te[1]; - array[offset + 2] = te[2]; - array[offset + 3] = te[3]; - array[offset + 4] = te[4]; - array[offset + 5] = te[5]; - array[offset + 6] = te[6]; - array[offset + 7] = te[7]; - array[offset + 8] = te[8]; - array[offset + 9] = te[9]; - array[offset + 10] = te[10]; - array[offset + 11] = te[11]; - array[offset + 12] = te[12]; - array[offset + 13] = te[13]; - array[offset + 14] = te[14]; - array[offset + 15] = te[15]; - return array; - } -} -const _v1$6 = /*@__PURE__*/new Vector3(); -const _m1$2 = /*@__PURE__*/new Matrix4(); -const _zero = /*@__PURE__*/new Vector3(0, 0, 0); -const _one = /*@__PURE__*/new Vector3(1, 1, 1); -const _x = /*@__PURE__*/new Vector3(); -const _y = /*@__PURE__*/new Vector3(); -const _z = /*@__PURE__*/new Vector3(); -function WebGLAnimation() { - let context = null; - let isAnimating = false; - let animationLoop = null; - let requestId = null; - function onAnimationFrame(time, frame) { - animationLoop(time, frame); - requestId = context.requestAnimationFrame(onAnimationFrame); + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z; + } - return { - start: function () { - if (isAnimating === true) return; - if (animationLoop === null) return; - requestId = context.requestAnimationFrame(onAnimationFrame); - isAnimating = true; - }, - stop: function () { - context.cancelAnimationFrame(requestId); - isAnimating = false; - }, - setAnimationLoop: function (callback) { - animationLoop = callback; - }, - setContext: function (value) { - context = value; - } - }; -} -function WebGLAttributes(gl, capabilities) { - const isWebGL2 = capabilities.isWebGL2; - const buffers = new WeakMap(); - function createBuffer(attribute, bufferType) { - const array = attribute.array; - const usage = attribute.usage; - const buffer = gl.createBuffer(); - gl.bindBuffer(bufferType, buffer); - gl.bufferData(bufferType, array, usage); - attribute.onUploadCallback(); - let type; - if (array instanceof Float32Array) { - type = gl.FLOAT; - } else if (array instanceof Uint16Array) { - if (attribute.isFloat16BufferAttribute) { - if (isWebGL2) { - type = gl.HALF_FLOAT; - } else { - throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.'); - } - } else { - type = gl.UNSIGNED_SHORT; - } - } else if (array instanceof Int16Array) { - type = gl.SHORT; - } else if (array instanceof Uint32Array) { - type = gl.UNSIGNED_INT; - } else if (array instanceof Int32Array) { - type = gl.INT; - } else if (array instanceof Int8Array) { - type = gl.BYTE; - } else if (array instanceof Uint8Array) { - type = gl.UNSIGNED_BYTE; - } else if (array instanceof Uint8ClampedArray) { - type = gl.UNSIGNED_BYTE; - } else { - throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array); - } - return { - buffer: buffer, - type: type, - bytesPerElement: array.BYTES_PER_ELEMENT, - version: attribute.version - }; - } - function updateBuffer(buffer, attribute, bufferType) { - const array = attribute.array; - const updateRange = attribute.updateRange; - gl.bindBuffer(bufferType, buffer); - if (updateRange.count === -1) { - // Not using update ranges + // TODO lengthSquared? - gl.bufferSubData(bufferType, 0, array); - } else { - if (isWebGL2) { - gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count); - } else { - gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count)); - } - updateRange.count = -1; // reset range - } - } + lengthSq() { - // + return this.x * this.x + this.y * this.y + this.z * this.z; - function get(attribute) { - if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; - return buffers.get(attribute); } - function remove(attribute) { - if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; - const data = buffers.get(attribute); - if (data) { - gl.deleteBuffer(data.buffer); - buffers.delete(attribute); - } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + } - function update(attribute, bufferType) { - if (attribute.isGLBufferAttribute) { - const cached = buffers.get(attribute); - if (!cached || cached.version < attribute.version) { - buffers.set(attribute, { - buffer: attribute.buffer, - type: attribute.type, - bytesPerElement: attribute.elementSize, - version: attribute.version - }); - } - return; - } - if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; - const data = buffers.get(attribute); - if (data === undefined) { - buffers.set(attribute, createBuffer(attribute, bufferType)); - } else if (data.version < attribute.version) { - updateBuffer(data.buffer, attribute, bufferType); - data.version = attribute.version; - } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + } - return { - get: get, - remove: remove, - update: update - }; -} -const _vector$9 = /*@__PURE__*/new Vector3(); -const _vector2 = /*@__PURE__*/new Vector2(); -class BufferAttribute { - constructor(array, itemSize, normalized) { - if (Array.isArray(array)) { - throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.'); - } - this.isBufferAttribute = true; - this.name = ''; - this.array = array; - this.itemSize = itemSize; - this.count = array !== undefined ? array.length / itemSize : 0; - this.normalized = normalized === true; - this.usage = StaticDrawUsage; - this.updateRange = { - offset: 0, - count: -1 - }; - this.version = 0; + normalize() { + + return this.divideScalar( this.length() || 1 ); + } - onUploadCallback() {} - set needsUpdate(value) { - if (value === true) this.version++; + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + } - setUsage(value) { - this.usage = value; + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + return this; + } - copy(source) { - this.name = source.name; - this.array = new source.array.constructor(source.array); - this.itemSize = source.itemSize; - this.count = source.count; - this.normalized = source.normalized; - this.usage = source.usage; + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + return this; + } - copyAt(index1, attribute, index2) { - index1 *= this.itemSize; - index2 *= attribute.itemSize; - for (let i = 0, l = this.itemSize; i < l; i++) { - this.array[index1 + i] = attribute.array[index2 + i]; - } - return this; + + cross( v ) { + + return this.crossVectors( this, v ); + } - copyArray(array) { - this.array.set(array); + + crossVectors( a, b ) { + + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } - applyMatrix3(m) { - if (this.itemSize === 2) { - for (let i = 0, l = this.count; i < l; i++) { - _vector2.fromBufferAttribute(this, i); - _vector2.applyMatrix3(m); - this.setXY(i, _vector2.x, _vector2.y); - } - } else if (this.itemSize === 3) { - for (let i = 0, l = this.count; i < l; i++) { - _vector$9.fromBufferAttribute(this, i); - _vector$9.applyMatrix3(m); - this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); - } - } - return this; + + projectOnVector( v ) { + + const denominator = v.lengthSq(); + + if ( denominator === 0 ) return this.set( 0, 0, 0 ); + + const scalar = v.dot( this ) / denominator; + + return this.copy( v ).multiplyScalar( scalar ); + } - applyMatrix4(m) { - for (let i = 0, l = this.count; i < l; i++) { - _vector$9.fromBufferAttribute(this, i); - _vector$9.applyMatrix4(m); - this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); - } - return this; + + projectOnPlane( planeNormal ) { + + _vector$7.copy( this ).projectOnVector( planeNormal ); + + return this.sub( _vector$7 ); + } - applyNormalMatrix(m) { - for (let i = 0, l = this.count; i < l; i++) { - _vector$9.fromBufferAttribute(this, i); - _vector$9.applyNormalMatrix(m); - this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); - } - return this; + + reflect( normal ) { + + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length + + return this.sub( _vector$7.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + } - transformDirection(m) { - for (let i = 0, l = this.count; i < l; i++) { - _vector$9.fromBufferAttribute(this, i); - _vector$9.transformDirection(m); - this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); - } - return this; + + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, - 1, 1 ) ); + } - set(value, offset = 0) { - // Matching BufferAttribute constructor, do not normalize the array. - this.array.set(value, offset); - return this; + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + } - getX(index) { - let x = this.array[index * this.itemSize]; - if (this.normalized) x = denormalize(x, this.array); - return x; + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + + return dx * dx + dy * dy + dz * dz; + } - setX(index, x) { - if (this.normalized) x = normalize(x, this.array); - this.array[index * this.itemSize] = x; - return this; + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + } - getY(index) { - let y = this.array[index * this.itemSize + 1]; - if (this.normalized) y = denormalize(y, this.array); - return y; + + setFromSpherical( s ) { + + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + } - setY(index, y) { - if (this.normalized) y = normalize(y, this.array); - this.array[index * this.itemSize + 1] = y; + + setFromSphericalCoords( radius, phi, theta ) { + + const sinPhiRadius = Math.sin( phi ) * radius; + + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); + return this; + } - getZ(index) { - let z = this.array[index * this.itemSize + 2]; - if (this.normalized) z = denormalize(z, this.array); - return z; + + setFromCylindrical( c ) { + + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + } - setZ(index, z) { - if (this.normalized) z = normalize(z, this.array); - this.array[index * this.itemSize + 2] = z; + + setFromCylindricalCoords( radius, theta, y ) { + + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); + return this; + } - getW(index) { - let w = this.array[index * this.itemSize + 3]; - if (this.normalized) w = denormalize(w, this.array); - return w; - } - setW(index, w) { - if (this.normalized) w = normalize(w, this.array); - this.array[index * this.itemSize + 3] = w; + + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + return this; + } - setXY(index, x, y) { - index *= this.itemSize; - if (this.normalized) { - x = normalize(x, this.array); - y = normalize(y, this.array); - } - this.array[index + 0] = x; - this.array[index + 1] = y; + + setFromMatrixScale( m ) { + + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); + + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } - setXYZ(index, x, y, z) { - index *= this.itemSize; - if (this.normalized) { - x = normalize(x, this.array); - y = normalize(y, this.array); - z = normalize(z, this.array); - } - this.array[index + 0] = x; - this.array[index + 1] = y; - this.array[index + 2] = z; - return this; + + setFromMatrixColumn( m, index ) { + + return this.fromArray( m.elements, index * 4 ); + } - setXYZW(index, x, y, z, w) { - index *= this.itemSize; - if (this.normalized) { - x = normalize(x, this.array); - y = normalize(y, this.array); - z = normalize(z, this.array); - w = normalize(w, this.array); - } - this.array[index + 0] = x; - this.array[index + 1] = y; - this.array[index + 2] = z; - this.array[index + 3] = w; - return this; + + setFromMatrix3Column( m, index ) { + + return this.fromArray( m.elements, index * 3 ); + } - onUpload(callback) { - this.onUploadCallback = callback; + + setFromEuler( e ) { + + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } - clone() { - return new this.constructor(this.array, this.itemSize).copy(this); - } - toJSON() { - const data = { - itemSize: this.itemSize, - type: this.array.constructor.name, - array: Array.from(this.array), - normalized: this.normalized - }; - if (this.name !== '') data.name = this.name; - if (this.usage !== StaticDrawUsage) data.usage = this.usage; - if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange; - return data; + + setFromColor( c ) { + + this.x = c.r; + this.y = c.g; + this.z = c.b; + + return this; + } - // @deprecated + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - copyColorsArray() { - console.error('THREE.BufferAttribute: copyColorsArray() was removed in r144.'); } - copyVector2sArray() { - console.error('THREE.BufferAttribute: copyVector2sArray() was removed in r144.'); + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + + return this; + } - copyVector3sArray() { - console.error('THREE.BufferAttribute: copyVector3sArray() was removed in r144.'); + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + + return array; + } - copyVector4sArray() { - console.error('THREE.BufferAttribute: copyVector4sArray() was removed in r144.'); + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + + return this; + } -} -class Uint16BufferAttribute extends BufferAttribute { - constructor(array, itemSize, normalized) { - super(new Uint16Array(array), itemSize, normalized); + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; + } -} -class Uint32BufferAttribute extends BufferAttribute { - constructor(array, itemSize, normalized) { - super(new Uint32Array(array), itemSize, normalized); + + randomDirection() { + + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); + + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; + + return this; + } -} -class Float32BufferAttribute extends BufferAttribute { - constructor(array, itemSize, normalized) { - super(new Float32Array(array), itemSize, normalized); + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + } + } -const _matrix$1 = /*@__PURE__*/new Matrix4(); -const _quaternion$1 = /*@__PURE__*/new Quaternion(); -class Euler { - constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) { - this.isEuler = true; - this._x = x; - this._y = y; - this._z = z; - this._order = order; - } - get x() { - return this._x; - } - set x(value) { - this._x = value; - this._onChangeCallback(); - } - get y() { - return this._y; - } - set y(value) { - this._y = value; - this._onChangeCallback(); +const _vector$7 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); + +class Box3 { + + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + + this.isBox3 = true; + + this.min = min; + this.max = max; + } - get z() { - return this._z; + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + } - set z(value) { - this._z = value; - this._onChangeCallback(); + + setFromArray( array ) { + + this.makeEmpty(); + + for ( let i = 0, il = array.length; i < il; i += 3 ) { + + this.expandByPoint( _vector$6.fromArray( array, i ) ); + + } + + return this; + } - get order() { - return this._order; + + setFromBufferAttribute( attribute ) { + + this.makeEmpty(); + + for ( let i = 0, il = attribute.count; i < il; i ++ ) { + + this.expandByPoint( _vector$6.fromBufferAttribute( attribute, i ) ); + + } + + return this; + } - set order(value) { - this._order = value; - this._onChangeCallback(); + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + } - set(x, y, z, order = this._order) { - this._x = x; - this._y = y; - this._z = z; - this._order = order; - this._onChangeCallback(); + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$6.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + return this; + + } + + setFromObject( object, precise = false ) { + + this.makeEmpty(); + + return this.expandByObject( object, precise ); + } + clone() { - return new this.constructor(this._x, this._y, this._z, this._order); + + return new this.constructor().copy( this ); + } - copy(euler) { - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; - this._onChangeCallback(); + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + return this; + } - setFromRotationMatrix(m, order = this._order, update = true) { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - const te = m.elements; - const m11 = te[0], - m12 = te[4], - m13 = te[8]; - const m21 = te[1], - m22 = te[5], - m23 = te[9]; - const m31 = te[2], - m32 = te[6], - m33 = te[10]; - switch (order) { - case 'XYZ': - this._y = Math.asin(clamp(m13, -1, 1)); - if (Math.abs(m13) < 0.9999999) { - this._x = Math.atan2(-m23, m33); - this._z = Math.atan2(-m12, m11); - } else { - this._x = Math.atan2(m32, m22); - this._z = 0; - } - break; - case 'YXZ': - this._x = Math.asin(-clamp(m23, -1, 1)); - if (Math.abs(m23) < 0.9999999) { - this._y = Math.atan2(m13, m33); - this._z = Math.atan2(m21, m22); - } else { - this._y = Math.atan2(-m31, m11); - this._z = 0; - } - break; - case 'ZXY': - this._x = Math.asin(clamp(m32, -1, 1)); - if (Math.abs(m32) < 0.9999999) { - this._y = Math.atan2(-m31, m33); - this._z = Math.atan2(-m12, m22); - } else { - this._y = 0; - this._z = Math.atan2(m21, m11); - } - break; - case 'ZYX': - this._y = Math.asin(-clamp(m31, -1, 1)); - if (Math.abs(m31) < 0.9999999) { - this._x = Math.atan2(m32, m33); - this._z = Math.atan2(m21, m11); - } else { - this._x = 0; - this._z = Math.atan2(-m12, m22); - } - break; - case 'YZX': - this._z = Math.asin(clamp(m21, -1, 1)); - if (Math.abs(m21) < 0.9999999) { - this._x = Math.atan2(-m23, m22); - this._y = Math.atan2(-m31, m11); - } else { - this._x = 0; - this._y = Math.atan2(m13, m33); - } - break; - case 'XZY': - this._z = Math.asin(-clamp(m12, -1, 1)); - if (Math.abs(m12) < 0.9999999) { - this._x = Math.atan2(m32, m22); - this._y = Math.atan2(m13, m11); - } else { - this._x = Math.atan2(-m23, m33); - this._y = 0; - } - break; - default: - console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order); - } - this._order = order; - if (update === true) this._onChangeCallback(); + makeEmpty() { + + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; + return this; + } - setFromQuaternion(q, order, update) { - _matrix$1.makeRotationFromQuaternion(q); - return this.setFromRotationMatrix(_matrix$1, order, update); - } - setFromVector3(v, order = this._order) { - return this.set(v.x, v.y, v.z, order); + + isEmpty() { + + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + } - reorder(newOrder) { - // WARNING: this discards revolution information -bhouston - _quaternion$1.setFromEuler(this); - return this.setFromQuaternion(_quaternion$1, newOrder); + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + } - equals(euler) { - return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + } - fromArray(array) { - this._x = array[0]; - this._y = array[1]; - this._z = array[2]; - if (array[3] !== undefined) this._order = array[3]; - this._onChangeCallback(); + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + return this; + } - toArray(array = [], offset = 0) { - array[offset] = this._x; - array[offset + 1] = this._y; - array[offset + 2] = this._z; - array[offset + 3] = this._order; - return array; - } - _onChange(callback) { - this._onChangeCallback = callback; + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + return this; + } - _onChangeCallback() {} - *[Symbol.iterator]() { - yield this._x; - yield this._y; - yield this._z; - yield this._order; + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + } - // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 + expandByObject( object, precise = false ) { + + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms + + object.updateWorldMatrix( false, false ); + + if ( object.boundingBox !== undefined ) { + + if ( object.boundingBox === null ) { + + object.computeBoundingBox(); + + } + + _box$2.copy( object.boundingBox ); + _box$2.applyMatrix4( object.matrixWorld ); + + this.union( _box$2 ); + + } else { + + const geometry = object.geometry; + + if ( geometry !== undefined ) { + + if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) { + + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$6 ); + + } + + } else { + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + _box$2.copy( geometry.boundingBox ); + _box$2.applyMatrix4( object.matrixWorld ); + + this.union( _box$2 ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } + + return this; - toVector3() { - console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead'); } -} -Euler.DefaultOrder = 'XYZ'; -Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX']; -class Layers { - constructor() { - this.mask = 1 | 0; + containsPoint( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ? false : true; + } - set(channel) { - this.mask = (1 << channel | 0) >>> 0; + + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y && + this.min.z <= box.min.z && box.max.z <= this.max.z; + } - enable(channel) { - this.mask |= 1 << channel | 0; - } - enableAll() { - this.mask = 0xffffffff | 0; - } - toggle(channel) { - this.mask ^= 1 << channel | 0; - } - disable(channel) { - this.mask &= ~(1 << channel | 0); - } - disableAll() { - this.mask = 0; + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); + } - test(layers) { - return (this.mask & layers.mask) !== 0; + + intersectsBox( box ) { + + // using 6 splitting planes to rule out intersections. + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ? false : true; + } - isEnabled(channel) { - return (this.mask & (1 << channel | 0)) !== 0; + + intersectsSphere( sphere ) { + + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$6 ); + + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$6.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + } -} -let _object3DId = 0; -const _v1$5 = /*@__PURE__*/new Vector3(); -const _q1 = /*@__PURE__*/new Quaternion(); -const _m1$1 = /*@__PURE__*/new Matrix4(); -const _target = /*@__PURE__*/new Vector3(); -const _position$1 = /*@__PURE__*/new Vector3(); -const _scale = /*@__PURE__*/new Vector3(); -const _quaternion = /*@__PURE__*/new Quaternion(); -const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0); -const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0); -const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1); -const _addedEvent = { - type: 'added' -}; -const _removedEvent = { - type: 'removed' -}; -class Object3D extends EventDispatcher { - constructor() { - super(); - this.isObject3D = true; - Object.defineProperty(this, 'id', { - value: _object3DId++ - }); - this.uuid = generateUUID(); - this.name = ''; - this.type = 'Object3D'; - this.parent = null; - this.children = []; - this.up = Object3D.DefaultUp.clone(); - const position = new Vector3(); - const rotation = new Euler(); - const quaternion = new Quaternion(); - const scale = new Vector3(1, 1, 1); - function onRotationChange() { - quaternion.setFromEuler(rotation, false); + intersectsPlane( plane ) { + + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. + + let min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + + } else { + + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } - function onQuaternionChange() { - rotation.setFromQuaternion(quaternion, undefined, false); + + if ( plane.normal.y > 0 ) { + + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + + } else { + + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } - rotation._onChange(onRotationChange); - quaternion._onChange(onQuaternionChange); - Object.defineProperties(this, { - position: { - configurable: true, - enumerable: true, - value: position - }, - rotation: { - configurable: true, - enumerable: true, - value: rotation - }, - quaternion: { - configurable: true, - enumerable: true, - value: quaternion - }, - scale: { - configurable: true, - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() - } - }); - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; - this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer - this.layers = new Layers(); - this.visible = true; - this.castShadow = false; - this.receiveShadow = false; - this.frustumCulled = true; - this.renderOrder = 0; - this.animations = []; - this.userData = {}; - } - onBeforeRender( /* renderer, scene, camera, geometry, material, group */) {} - onAfterRender( /* renderer, scene, camera, geometry, material, group */) {} - applyMatrix4(matrix) { - if (this.matrixAutoUpdate) this.updateMatrix(); - this.matrix.premultiply(matrix); - this.matrix.decompose(this.position, this.quaternion, this.scale); - } - applyQuaternion(q) { - this.quaternion.premultiply(q); - return this; + if ( plane.normal.z > 0 ) { + + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + + } else { + + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); + } - setRotationFromAxisAngle(axis, angle) { - // assumes axis is normalized - this.quaternion.setFromAxisAngle(axis, angle); + intersectsTriangle( triangle ) { + + if ( this.isEmpty() ) { + + return false; + + } + + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); + + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$6.subVectors( triangle.b, _center ); + _v2$3.subVectors( triangle.c, _center ); + + // compute edge vectors for triangle + _f0.subVectors( _v1$6, _v0$2 ); + _f1.subVectors( _v2$3, _v1$6 ); + _f2.subVectors( _v0$2, _v2$3 ); + + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$6, _v2$3, _extents ) ) { + + return false; + + } + + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$6, _v2$3, _extents ) ) { + + return false; + + } + + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + + return satForAxes( axes, _v0$2, _v1$6, _v2$3, _extents ); + } - setRotationFromEuler(euler) { - this.quaternion.setFromEuler(euler, true); + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + } - setRotationFromMatrix(m) { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - this.quaternion.setFromRotationMatrix(m); + distanceToPoint( point ) { + + return this.clampPoint( point, _vector$6 ).distanceTo( point ); + } - setRotationFromQuaternion(q) { - // assumes q is normalized - this.quaternion.copy(q); + getBoundingSphere( target ) { + + if ( this.isEmpty() ) { + + target.makeEmpty(); + + } else { + + this.getCenter( target.center ); + + target.radius = this.getSize( _vector$6 ).length() * 0.5; + + } + + return target; + } - rotateOnAxis(axis, angle) { - // rotate object on axis in object space - // axis is assumed to be normalized - _q1.setFromAxisAngle(axis, angle); - this.quaternion.multiply(_q1); + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if ( this.isEmpty() ) this.makeEmpty(); + return this; + } - rotateOnWorldAxis(axis, angle) { - // rotate object on axis in world space - // axis is assumed to be normalized - // method assumes no rotated parent - _q1.setFromAxisAngle(axis, angle); - this.quaternion.premultiply(_q1); + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + return this; + } - rotateX(angle) { - return this.rotateOnAxis(_xAxis, angle); - } - rotateY(angle) { - return this.rotateOnAxis(_yAxis, angle); - } - rotateZ(angle) { - return this.rotateOnAxis(_zAxis, angle); - } - translateOnAxis(axis, distance) { - // translate object by distance along axis in object space - // axis is assumed to be normalized - _v1$5.copy(axis).applyQuaternion(this.quaternion); - this.position.add(_v1$5.multiplyScalar(distance)); + applyMatrix4( matrix ) { + + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; + + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + + this.setFromPoints( _points ); + return this; + } - translateX(distance) { - return this.translateOnAxis(_xAxis, distance); - } - translateY(distance) { - return this.translateOnAxis(_yAxis, distance); - } - translateZ(distance) { - return this.translateOnAxis(_zAxis, distance); - } - localToWorld(vector) { - return vector.applyMatrix4(this.matrixWorld); + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + } - worldToLocal(vector) { - return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + } - lookAt(x, y, z) { - // This method does not support objects having non-uniformly-scaled parent(s) - if (x.isVector3) { - _target.copy(x); - } else { - _target.set(x, y, z); - } - const parent = this.parent; - this.updateWorldMatrix(true, false); - _position$1.setFromMatrixPosition(this.matrixWorld); - if (this.isCamera || this.isLight) { - _m1$1.lookAt(_position$1, _target, this.up); - } else { - _m1$1.lookAt(_target, _position$1, this.up); - } - this.quaternion.setFromRotationMatrix(_m1$1); - if (parent) { - _m1$1.extractRotation(parent.matrixWorld); - _q1.setFromRotationMatrix(_m1$1); - this.quaternion.premultiply(_q1.invert()); +} + +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; + +const _vector$6 = /*@__PURE__*/ new Vector3(); + +const _box$2 = /*@__PURE__*/ new Box3(); + +// triangle centered vertices + +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); + +// triangle edge vectors + +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); + +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); + +function satForAxes( axes, v0, v1, v2, extents ) { + + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; + } + } - add(object) { - if (arguments.length > 1) { - for (let i = 0; i < arguments.length; i++) { - this.add(arguments[i]); - } - return this; - } - if (object === this) { - console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object); - return this; - } - if (object && object.isObject3D) { - if (object.parent !== null) { - object.parent.remove(object); - } - object.parent = this; - this.children.push(object); - object.dispatchEvent(_addedEvent); - } else { - console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object); - } - return this; + + return true; + +} + +const _box$1 = /*@__PURE__*/ new Box3(); +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); + +class Sphere { + + constructor( center = new Vector3(), radius = - 1 ) { + + this.center = center; + this.radius = radius; + } - remove(object) { - if (arguments.length > 1) { - for (let i = 0; i < arguments.length; i++) { - this.remove(arguments[i]); - } - return this; - } - const index = this.children.indexOf(object); - if (index !== -1) { - object.parent = null; - this.children.splice(index, 1); - object.dispatchEvent(_removedEvent); - } + + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + return this; + } - removeFromParent() { - const parent = this.parent; - if (parent !== null) { - parent.remove(this); + + setFromPoints( points, optionalCenter ) { + + const center = this.center; + + if ( optionalCenter !== undefined ) { + + center.copy( optionalCenter ); + + } else { + + _box$1.setFromPoints( points ).getCenter( center ); + } - return this; - } - clear() { - for (let i = 0; i < this.children.length; i++) { - const object = this.children[i]; - object.parent = null; - object.dispatchEvent(_removedEvent); + + let maxRadiusSq = 0; + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + } - this.children.length = 0; + + this.radius = Math.sqrt( maxRadiusSq ); + return this; + } - attach(object) { - // adds object as a child of this, while maintaining the object's world transform - // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + copy( sphere ) { + + this.center.copy( sphere.center ); + this.radius = sphere.radius; - this.updateWorldMatrix(true, false); - _m1$1.copy(this.matrixWorld).invert(); - if (object.parent !== null) { - object.parent.updateWorldMatrix(true, false); - _m1$1.multiply(object.parent.matrixWorld); - } - object.applyMatrix4(_m1$1); - this.add(object); - object.updateWorldMatrix(false, true); return this; + } - getObjectById(id) { - return this.getObjectByProperty('id', id); - } - getObjectByName(name) { - return this.getObjectByProperty('name', name); + + isEmpty() { + + return ( this.radius < 0 ); + } - getObjectByProperty(name, value) { - if (this[name] === value) return this; - for (let i = 0, l = this.children.length; i < l; i++) { - const child = this.children[i]; - const object = child.getObjectByProperty(name, value); - if (object !== undefined) { - return object; - } - } - return undefined; + + makeEmpty() { + + this.center.set( 0, 0, 0 ); + this.radius = - 1; + + return this; + } - getWorldPosition(target) { - this.updateWorldMatrix(true, false); - return target.setFromMatrixPosition(this.matrixWorld); + + containsPoint( point ) { + + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + } - getWorldQuaternion(target) { - this.updateWorldMatrix(true, false); - this.matrixWorld.decompose(_position$1, target, _scale); - return target; + + distanceToPoint( point ) { + + return ( point.distanceTo( this.center ) - this.radius ); + } - getWorldScale(target) { - this.updateWorldMatrix(true, false); - this.matrixWorld.decompose(_position$1, _quaternion, target); - return target; + + intersectsSphere( sphere ) { + + const radiusSum = this.radius + sphere.radius; + + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + } - getWorldDirection(target) { - this.updateWorldMatrix(true, false); - const e = this.matrixWorld.elements; - return target.set(e[8], e[9], e[10]).normalize(); + + intersectsBox( box ) { + + return box.intersectsSphere( this ); + } - raycast( /* raycaster, intersects */) {} - traverse(callback) { - callback(this); - const children = this.children; - for (let i = 0, l = children.length; i < l; i++) { - children[i].traverse(callback); - } + + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + } - traverseVisible(callback) { - if (this.visible === false) return; - callback(this); - const children = this.children; - for (let i = 0, l = children.length; i < l; i++) { - children[i].traverseVisible(callback); + + clampPoint( point, target ) { + + const deltaLengthSq = this.center.distanceToSquared( point ); + + target.copy( point ); + + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); + } + + return target; + } - traverseAncestors(callback) { - const parent = this.parent; - if (parent !== null) { - callback(parent); - parent.traverseAncestors(callback); + + getBoundingBox( target ) { + + if ( this.isEmpty() ) { + + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; + } + + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); + + return target; + } - updateMatrix() { - this.matrix.compose(this.position, this.quaternion, this.scale); - this.matrixWorldNeedsUpdate = true; + + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + + return this; + } - updateMatrixWorld(force) { - if (this.matrixAutoUpdate) this.updateMatrix(); - if (this.matrixWorldNeedsUpdate || force) { - if (this.parent === null) { - this.matrixWorld.copy(this.matrix); - } else { - this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); - } - this.matrixWorldNeedsUpdate = false; - force = true; - } - // update children + translate( offset ) { + + this.center.add( offset ); + + return this; - const children = this.children; - for (let i = 0, l = children.length; i < l; i++) { - const child = children[i]; - if (child.matrixWorldAutoUpdate === true || force === true) { - child.updateMatrixWorld(force); - } - } } - updateWorldMatrix(updateParents, updateChildren) { - const parent = this.parent; - if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) { - parent.updateWorldMatrix(true, false); - } - if (this.matrixAutoUpdate) this.updateMatrix(); - if (this.parent === null) { - this.matrixWorld.copy(this.matrix); - } else { - this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + + expandByPoint( point ) { + + if ( this.isEmpty() ) { + + this.center.copy( point ); + + this.radius = 0; + + return this; + } - // update children + _v1$5.subVectors( point, this.center ); + + const lengthSq = _v1$5.lengthSq(); + + if ( lengthSq > ( this.radius * this.radius ) ) { + + // calculate the minimal sphere + + const length = Math.sqrt( lengthSq ); + + const delta = ( length - this.radius ) * 0.5; + + this.center.addScaledVector( _v1$5, delta / length ); + + this.radius += delta; - if (updateChildren === true) { - const children = this.children; - for (let i = 0, l = children.length; i < l; i++) { - const child = children[i]; - if (child.matrixWorldAutoUpdate === true) { - child.updateWorldMatrix(false, true); - } - } } + + return this; + } - toJSON(meta) { - // meta is a string when called from JSON.stringify - const isRootObject = meta === undefined || typeof meta === 'string'; - const output = {}; - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if (isRootObject) { - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {}, - shapes: {}, - skeletons: {}, - animations: {}, - nodes: {} - }; - output.metadata = { - version: 4.5, - type: 'Object', - generator: 'Object3D.toJSON' - }; + union( sphere ) { + + if ( sphere.isEmpty() ) { + + return this; + } - // standard Object3D serialization + if ( this.isEmpty() ) { - const object = {}; - object.uuid = this.uuid; - object.type = this.type; - if (this.name !== '') object.name = this.name; - if (this.castShadow === true) object.castShadow = true; - if (this.receiveShadow === true) object.receiveShadow = true; - if (this.visible === false) object.visible = false; - if (this.frustumCulled === false) object.frustumCulled = false; - if (this.renderOrder !== 0) object.renderOrder = this.renderOrder; - if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData; - object.layers = this.layers.mask; - object.matrix = this.matrix.toArray(); - if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; + this.copy( sphere ); - // object specific properties + return this; - if (this.isInstancedMesh) { - object.type = 'InstancedMesh'; - object.count = this.count; - object.instanceMatrix = this.instanceMatrix.toJSON(); - if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON(); } - // + if ( this.center.equals( sphere.center ) === true ) { - function serialize(library, element) { - if (library[element.uuid] === undefined) { - library[element.uuid] = element.toJSON(meta); - } - return element.uuid; - } - if (this.isScene) { - if (this.background) { - if (this.background.isColor) { - object.background = this.background.toJSON(); - } else if (this.background.isTexture) { - object.background = this.background.toJSON(meta).uuid; - } - } - if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { - object.environment = this.environment.toJSON(meta).uuid; - } - } else if (this.isMesh || this.isLine || this.isPoints) { - object.geometry = serialize(meta.geometries, this.geometry); - const parameters = this.geometry.parameters; - if (parameters !== undefined && parameters.shapes !== undefined) { - const shapes = parameters.shapes; - if (Array.isArray(shapes)) { - for (let i = 0, l = shapes.length; i < l; i++) { - const shape = shapes[i]; - serialize(meta.shapes, shape); - } - } else { - serialize(meta.shapes, shapes); - } - } - } - if (this.isSkinnedMesh) { - object.bindMode = this.bindMode; - object.bindMatrix = this.bindMatrix.toArray(); - if (this.skeleton !== undefined) { - serialize(meta.skeletons, this.skeleton); - object.skeleton = this.skeleton.uuid; - } - } - if (this.material !== undefined) { - if (Array.isArray(this.material)) { - const uuids = []; - for (let i = 0, l = this.material.length; i < l; i++) { - uuids.push(serialize(meta.materials, this.material[i])); - } - object.material = uuids; - } else { - object.material = serialize(meta.materials, this.material); - } - } + this.radius = Math.max( this.radius, sphere.radius ); - // + } else { - if (this.children.length > 0) { - object.children = []; - for (let i = 0; i < this.children.length; i++) { - object.children.push(this.children[i].toJSON(meta).object); - } - } + _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius ); - // + this.expandByPoint( _v1$5.copy( sphere.center ).add( _v2$2 ) ); - if (this.animations.length > 0) { - object.animations = []; - for (let i = 0; i < this.animations.length; i++) { - const animation = this.animations[i]; - object.animations.push(serialize(meta.animations, animation)); - } - } - if (isRootObject) { - const geometries = extractFromCache(meta.geometries); - const materials = extractFromCache(meta.materials); - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - const shapes = extractFromCache(meta.shapes); - const skeletons = extractFromCache(meta.skeletons); - const animations = extractFromCache(meta.animations); - const nodes = extractFromCache(meta.nodes); - if (geometries.length > 0) output.geometries = geometries; - if (materials.length > 0) output.materials = materials; - if (textures.length > 0) output.textures = textures; - if (images.length > 0) output.images = images; - if (shapes.length > 0) output.shapes = shapes; - if (skeletons.length > 0) output.skeletons = skeletons; - if (animations.length > 0) output.animations = animations; - if (nodes.length > 0) output.nodes = nodes; - } - output.object = object; - return output; + this.expandByPoint( _v1$5.copy( sphere.center ).sub( _v2$2 ) ); - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache(cache) { - const values = []; - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); - } - return values; } + + return this; + } - clone(recursive) { - return new this.constructor().copy(this, recursive); + + equals( sphere ) { + + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + } - copy(source, recursive = true) { - this.name = source.name; - this.up.copy(source.up); - this.position.copy(source.position); - this.rotation.order = source.rotation.order; - this.quaternion.copy(source.quaternion); - this.scale.copy(source.scale); - this.matrix.copy(source.matrix); - this.matrixWorld.copy(source.matrixWorld); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; - this.layers.mask = source.layers.mask; - this.visible = source.visible; - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; - this.userData = JSON.parse(JSON.stringify(source.userData)); - if (recursive === true) { - for (let i = 0; i < source.children.length; i++) { - const child = source.children[i]; - this.add(child.clone()); - } - } - return this; + + clone() { + + return new this.constructor().copy( this ); + } + } -Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0); -Object3D.DefaultMatrixAutoUpdate = true; -Object3D.DefaultMatrixWorldAutoUpdate = true; -let _id$1 = 0; -const _m1 = /*@__PURE__*/new Matrix4(); -const _obj = /*@__PURE__*/new Object3D(); -const _offset = /*@__PURE__*/new Vector3(); -const _box$1 = /*@__PURE__*/new Box3(); -const _boxMorphTargets = /*@__PURE__*/new Box3(); -const _vector$8 = /*@__PURE__*/new Vector3(); -class BufferGeometry extends EventDispatcher { - constructor() { - super(); - this.isBufferGeometry = true; - Object.defineProperty(this, 'id', { - value: _id$1++ - }); - this.uuid = generateUUID(); - this.name = ''; - this.type = 'BufferGeometry'; - this.index = null; - this.attributes = {}; - this.morphAttributes = {}; - this.morphTargetsRelative = false; - this.groups = []; - this.boundingBox = null; - this.boundingSphere = null; - this.drawRange = { - start: 0, - count: Infinity - }; - this.userData = {}; - } - getIndex() { - return this.index; - } - setIndex(index) { - if (Array.isArray(index)) { - this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1); - } else { - this.index = index; - } - return this; - } - getAttribute(name) { - return this.attributes[name]; - } - setAttribute(name, attribute) { - this.attributes[name] = attribute; - return this; - } - deleteAttribute(name) { - delete this.attributes[name]; - return this; - } - hasAttribute(name) { - return this.attributes[name] !== undefined; - } - addGroup(start, count, materialIndex = 0) { - this.groups.push({ - start: start, - count: count, - materialIndex: materialIndex - }); - } - clearGroups() { - this.groups = []; - } - setDrawRange(start, count) { - this.drawRange.start = start; - this.drawRange.count = count; - } - applyMatrix4(matrix) { - const position = this.attributes.position; - if (position !== undefined) { - position.applyMatrix4(matrix); - position.needsUpdate = true; - } - const normal = this.attributes.normal; - if (normal !== undefined) { - const normalMatrix = new Matrix3().getNormalMatrix(matrix); - normal.applyNormalMatrix(normalMatrix); - normal.needsUpdate = true; - } - const tangent = this.attributes.tangent; - if (tangent !== undefined) { - tangent.transformDirection(matrix); - tangent.needsUpdate = true; - } - if (this.boundingBox !== null) { - this.computeBoundingBox(); - } - if (this.boundingSphere !== null) { - this.computeBoundingSphere(); - } - return this; +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); + +class Plane { + + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + + this.isPlane = true; + + // normal is assumed to be normalized + + this.normal = normal; + this.constant = constant; + } - applyQuaternion(q) { - _m1.makeRotationFromQuaternion(q); - this.applyMatrix4(_m1); + + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + return this; + } - rotateX(angle) { - // rotate geometry around world x-axis - _m1.makeRotationX(angle); - this.applyMatrix4(_m1); + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; + return this; + } - rotateY(angle) { - // rotate geometry around world y-axis - _m1.makeRotationY(angle); - this.applyMatrix4(_m1); + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + return this; + } - rotateZ(angle) { - // rotate geometry around world z-axis - _m1.makeRotationZ(angle); - this.applyMatrix4(_m1); + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2$1.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + return this; + } - translate(x, y, z) { - // translate geometry - _m1.makeTranslation(x, y, z); - this.applyMatrix4(_m1); + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + return this; + } - scale(x, y, z) { - // scale geometry - _m1.makeScale(x, y, z); - this.applyMatrix4(_m1); + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + return this; + } - lookAt(vector) { - _obj.lookAt(vector); - _obj.updateMatrix(); - this.applyMatrix4(_obj.matrix); + + negate() { + + this.constant *= - 1; + this.normal.negate(); + return this; + } - center() { - this.computeBoundingBox(); - this.boundingBox.getCenter(_offset).negate(); - this.translate(_offset.x, _offset.y, _offset.z); - return this; + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + } - setFromPoints(points) { - const position = []; - for (let i = 0, l = points.length; i < l; i++) { - const point = points[i]; - position.push(point.x, point.y, point.z || 0); - } - this.setAttribute('position', new Float32BufferAttribute(position, 3)); - return this; + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + } - computeBoundingBox() { - if (this.boundingBox === null) { - this.boundingBox = new Box3(); - } - const position = this.attributes.position; - const morphAttributesPosition = this.morphAttributes.position; - if (position && position.isGLBufferAttribute) { - console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this); - this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity)); - return; - } - if (position !== undefined) { - this.boundingBox.setFromBufferAttribute(position); - // process morph attributes if present + projectPoint( point, target ) { + + return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) ); - if (morphAttributesPosition) { - for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { - const morphAttribute = morphAttributesPosition[i]; - _box$1.setFromBufferAttribute(morphAttribute); - if (this.morphTargetsRelative) { - _vector$8.addVectors(this.boundingBox.min, _box$1.min); - this.boundingBox.expandByPoint(_vector$8); - _vector$8.addVectors(this.boundingBox.max, _box$1.max); - this.boundingBox.expandByPoint(_vector$8); - } else { - this.boundingBox.expandByPoint(_box$1.min); - this.boundingBox.expandByPoint(_box$1.max); - } - } - } - } else { - this.boundingBox.makeEmpty(); - } - if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { - console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); - } } - computeBoundingSphere() { - if (this.boundingSphere === null) { - this.boundingSphere = new Sphere(); - } - const position = this.attributes.position; - const morphAttributesPosition = this.morphAttributes.position; - if (position && position.isGLBufferAttribute) { - console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this); - this.boundingSphere.set(new Vector3(), Infinity); - return; - } - if (position) { - // first, find the center of the bounding sphere - const center = this.boundingSphere.center; - _box$1.setFromBufferAttribute(position); + intersectLine( line, target ) { - // process morph attributes if present + const direction = line.delta( _vector1 ); - if (morphAttributesPosition) { - for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { - const morphAttribute = morphAttributesPosition[i]; - _boxMorphTargets.setFromBufferAttribute(morphAttribute); - if (this.morphTargetsRelative) { - _vector$8.addVectors(_box$1.min, _boxMorphTargets.min); - _box$1.expandByPoint(_vector$8); - _vector$8.addVectors(_box$1.max, _boxMorphTargets.max); - _box$1.expandByPoint(_vector$8); - } else { - _box$1.expandByPoint(_boxMorphTargets.min); - _box$1.expandByPoint(_boxMorphTargets.max); - } - } - } - _box$1.getCenter(center); + const denominator = this.normal.dot( direction ); - // second, try to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + if ( denominator === 0 ) { - let maxRadiusSq = 0; - for (let i = 0, il = position.count; i < il; i++) { - _vector$8.fromBufferAttribute(position, i); - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); - } + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - // process morph attributes if present + return target.copy( line.start ); - if (morphAttributesPosition) { - for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { - const morphAttribute = morphAttributesPosition[i]; - const morphTargetsRelative = this.morphTargetsRelative; - for (let j = 0, jl = morphAttribute.count; j < jl; j++) { - _vector$8.fromBufferAttribute(morphAttribute, j); - if (morphTargetsRelative) { - _offset.fromBufferAttribute(position, j); - _vector$8.add(_offset); - } - maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); - } - } } - this.boundingSphere.radius = Math.sqrt(maxRadiusSq); - if (isNaN(this.boundingSphere.radius)) { - console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); - } - } - } - computeTangents() { - const index = this.index; - const attributes = this.attributes; - // based on http://www.terathon.com/code/tangent.html - // (per vertex tangents) + // Unsure if this is the correct method to handle this case. + return null; - if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { - console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)'); - return; - } - const indices = index.array; - const positions = attributes.position.array; - const normals = attributes.normal.array; - const uvs = attributes.uv.array; - const nVertices = positions.length / 3; - if (this.hasAttribute('tangent') === false) { - this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4)); - } - const tangents = this.getAttribute('tangent').array; - const tan1 = [], - tan2 = []; - for (let i = 0; i < nVertices; i++) { - tan1[i] = new Vector3(); - tan2[i] = new Vector3(); } - const vA = new Vector3(), - vB = new Vector3(), - vC = new Vector3(), - uvA = new Vector2(), - uvB = new Vector2(), - uvC = new Vector2(), - sdir = new Vector3(), - tdir = new Vector3(); - function handleTriangle(a, b, c) { - vA.fromArray(positions, a * 3); - vB.fromArray(positions, b * 3); - vC.fromArray(positions, c * 3); - uvA.fromArray(uvs, a * 2); - uvB.fromArray(uvs, b * 2); - uvC.fromArray(uvs, c * 2); - vB.sub(vA); - vC.sub(vA); - uvB.sub(uvA); - uvC.sub(uvA); - const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); - // silently ignore degenerate uv triangles having coincident or colinear vertices + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - if (!isFinite(r)) return; - sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); - tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); - tan1[a].add(sdir); - tan1[b].add(sdir); - tan1[c].add(sdir); - tan2[a].add(tdir); - tan2[b].add(tdir); - tan2[c].add(tdir); - } - let groups = this.groups; - if (groups.length === 0) { - groups = [{ - start: 0, - count: indices.length - }]; - } - for (let i = 0, il = groups.length; i < il; ++i) { - const group = groups[i]; - const start = group.start; - const count = group.count; - for (let j = start, jl = start + count; j < jl; j += 3) { - handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]); - } - } - const tmp = new Vector3(), - tmp2 = new Vector3(); - const n = new Vector3(), - n2 = new Vector3(); - function handleVertex(v) { - n.fromArray(normals, v * 3); - n2.copy(n); - const t = tan1[v]; + if ( t < 0 || t > 1 ) { - // Gram-Schmidt orthogonalize + return null; - tmp.copy(t); - tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); + } - // Calculate handedness + return target.copy( line.start ).addScaledVector( direction, t ); - tmp2.crossVectors(n2, t); - const test = tmp2.dot(tan2[v]); - const w = test < 0.0 ? -1.0 : 1.0; - tangents[v * 4] = tmp.x; - tangents[v * 4 + 1] = tmp.y; - tangents[v * 4 + 2] = tmp.z; - tangents[v * 4 + 3] = w; - } - for (let i = 0, il = groups.length; i < il; ++i) { - const group = groups[i]; - const start = group.start; - const count = group.count; - for (let j = start, jl = start + count; j < jl; j += 3) { - handleVertex(indices[j + 0]); - handleVertex(indices[j + 1]); - handleVertex(indices[j + 2]); - } - } } - computeVertexNormals() { - const index = this.index; - const positionAttribute = this.getAttribute('position'); - if (positionAttribute !== undefined) { - let normalAttribute = this.getAttribute('normal'); - if (normalAttribute === undefined) { - normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); - this.setAttribute('normal', normalAttribute); - } else { - // reset existing normals to zero - for (let i = 0, il = normalAttribute.count; i < il; i++) { - normalAttribute.setXYZ(i, 0, 0, 0); - } - } - const pA = new Vector3(), - pB = new Vector3(), - pC = new Vector3(); - const nA = new Vector3(), - nB = new Vector3(), - nC = new Vector3(); - const cb = new Vector3(), - ab = new Vector3(); + intersectsLine( line ) { - // indexed elements + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - if (index) { - for (let i = 0, il = index.count; i < il; i += 3) { - const vA = index.getX(i + 0); - const vB = index.getX(i + 1); - const vC = index.getX(i + 2); - pA.fromBufferAttribute(positionAttribute, vA); - pB.fromBufferAttribute(positionAttribute, vB); - pC.fromBufferAttribute(positionAttribute, vC); - cb.subVectors(pC, pB); - ab.subVectors(pA, pB); - cb.cross(ab); - nA.fromBufferAttribute(normalAttribute, vA); - nB.fromBufferAttribute(normalAttribute, vB); - nC.fromBufferAttribute(normalAttribute, vC); - nA.add(cb); - nB.add(cb); - nC.add(cb); - normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); - normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); - normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); - } - } else { - // non-indexed elements (unconnected triangle soup) + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - for (let i = 0, il = positionAttribute.count; i < il; i += 3) { - pA.fromBufferAttribute(positionAttribute, i + 0); - pB.fromBufferAttribute(positionAttribute, i + 1); - pC.fromBufferAttribute(positionAttribute, i + 2); - cb.subVectors(pC, pB); - ab.subVectors(pA, pB); - cb.cross(ab); - normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); - normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); - normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); - } - } - this.normalizeNormals(); - normalAttribute.needsUpdate = true; - } } - // @deprecated since r144 + intersectsBox( box ) { + + return box.intersectsPlane( this ); - merge() { - console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.'); - return this; } - normalizeNormals() { - const normals = this.attributes.normal; - for (let i = 0, il = normals.count; i < il; i++) { - _vector$8.fromBufferAttribute(normals, i); - _vector$8.normalize(); - normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); - } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + } - toNonIndexed() { - function convertBufferAttribute(attribute, indices) { - const array = attribute.array; - const itemSize = attribute.itemSize; - const normalized = attribute.normalized; - const array2 = new array.constructor(indices.length * itemSize); - let index = 0, - index2 = 0; - for (let i = 0, l = indices.length; i < l; i++) { - if (attribute.isInterleavedBufferAttribute) { - index = indices[i] * attribute.data.stride + attribute.offset; - } else { - index = indices[i] * itemSize; - } - for (let j = 0; j < itemSize; j++) { - array2[index2++] = array[index++]; - } - } - return new BufferAttribute(array2, itemSize, normalized); - } - // + coplanarPoint( target ) { - if (this.index === null) { - console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.'); - return this; - } - const geometry2 = new BufferGeometry(); - const indices = this.index.array; - const attributes = this.attributes; + return target.copy( this.normal ).multiplyScalar( - this.constant ); - // attributes + } - for (const name in attributes) { - const attribute = attributes[name]; - const newAttribute = convertBufferAttribute(attribute, indices); - geometry2.setAttribute(name, newAttribute); - } + applyMatrix4( matrix, optionalNormalMatrix ) { - // morph attributes + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); - const morphAttributes = this.morphAttributes; - for (const name in morphAttributes) { - const morphArray = []; - const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); - for (let i = 0, il = morphAttribute.length; i < il; i++) { - const attribute = morphAttribute[i]; - const newAttribute = convertBufferAttribute(attribute, indices); - morphArray.push(newAttribute); - } - geometry2.morphAttributes[name] = morphArray; - } - geometry2.morphTargetsRelative = this.morphTargetsRelative; + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - // groups + this.constant = - referencePoint.dot( normal ); + + return this; - const groups = this.groups; - for (let i = 0, l = groups.length; i < l; i++) { - const group = groups[i]; - geometry2.addGroup(group.start, group.count, group.materialIndex); - } - return geometry2; } - toJSON() { - const data = { - metadata: { - version: 4.5, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; - // standard BufferGeometry serialization + translate( offset ) { - data.uuid = this.uuid; - data.type = this.type; - if (this.name !== '') data.name = this.name; - if (Object.keys(this.userData).length > 0) data.userData = this.userData; - if (this.parameters !== undefined) { - const parameters = this.parameters; - for (const key in parameters) { - if (parameters[key] !== undefined) data[key] = parameters[key]; - } - return data; - } + this.constant -= offset.dot( this.normal ); - // for simplicity the code assumes attributes are not shared across geometries, see #15811 + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - data.data = { - attributes: {} - }; - const index = this.index; - if (index !== null) { - data.data.index = { - type: index.array.constructor.name, - array: Array.prototype.slice.call(index.array) - }; - } - const attributes = this.attributes; - for (const key in attributes) { - const attribute = attributes[key]; - data.data.attributes[key] = attribute.toJSON(data.data); - } - const morphAttributes = {}; - let hasMorphAttributes = false; - for (const key in this.morphAttributes) { - const attributeArray = this.morphAttributes[key]; - const array = []; - for (let i = 0, il = attributeArray.length; i < il; i++) { - const attribute = attributeArray[i]; - array.push(attribute.toJSON(data.data)); - } - if (array.length > 0) { - morphAttributes[key] = array; - hasMorphAttributes = true; - } - } - if (hasMorphAttributes) { - data.data.morphAttributes = morphAttributes; - data.data.morphTargetsRelative = this.morphTargetsRelative; - } - const groups = this.groups; - if (groups.length > 0) { - data.data.groups = JSON.parse(JSON.stringify(groups)); - } - const boundingSphere = this.boundingSphere; - if (boundingSphere !== null) { - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; - } - return data; } + clone() { - return new this.constructor().copy(this); + + return new this.constructor().copy( this ); + } - copy(source) { - // reset - this.index = null; - this.attributes = {}; - this.morphAttributes = {}; - this.groups = []; - this.boundingBox = null; - this.boundingSphere = null; +} - // used for storing cloned, shared data +const _sphere$5 = /*@__PURE__*/ new Sphere(); +const _vector$5 = /*@__PURE__*/ new Vector3(); - const data = {}; +class Frustum { - // name + constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { - this.name = source.name; + this.planes = [ p0, p1, p2, p3, p4, p5 ]; - // index + } - const index = source.index; - if (index !== null) { - this.setIndex(index.clone(data)); - } + set( p0, p1, p2, p3, p4, p5 ) { - // attributes + const planes = this.planes; - const attributes = source.attributes; - for (const name in attributes) { - const attribute = attributes[name]; - this.setAttribute(name, attribute.clone(data)); - } + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - // morph attributes + return this; - const morphAttributes = source.morphAttributes; - for (const name in morphAttributes) { - const array = []; - const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes + } - for (let i = 0, l = morphAttribute.length; i < l; i++) { - array.push(morphAttribute[i].clone(data)); - } - this.morphAttributes[name] = array; - } - this.morphTargetsRelative = source.morphTargetsRelative; + copy( frustum ) { - // groups + const planes = this.planes; - const groups = source.groups; - for (let i = 0, l = groups.length; i < l; i++) { - const group = groups[i]; - this.addGroup(group.start, group.count, group.materialIndex); - } + for ( let i = 0; i < 6; i ++ ) { - // bounding box + planes[ i ].copy( frustum.planes[ i ] ); - const boundingBox = source.boundingBox; - if (boundingBox !== null) { - this.boundingBox = boundingBox.clone(); } - // bounding sphere + return this; - const boundingSphere = source.boundingSphere; - if (boundingSphere !== null) { - this.boundingSphere = boundingSphere.clone(); - } + } - // draw range + setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) { - this.drawRange.start = source.drawRange.start; - this.drawRange.count = source.drawRange.count; + const planes = this.planes; + const me = m.elements; + const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - // user data + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - this.userData = source.userData; + if ( coordinateSystem === WebGLCoordinateSystem ) { + + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - // geometry generator parameters + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); + + } else { + + throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem ); + + } - if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters); return this; + } - dispose() { - this.dispatchEvent({ - type: 'dispose' - }); - } -} -class BoxGeometry extends BufferGeometry { - constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { - super(); - this.type = 'BoxGeometry'; - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; - const scope = this; + intersectsObject( object ) { - // segments + if ( object.boundingSphere !== undefined ) { - widthSegments = Math.floor(widthSegments); - heightSegments = Math.floor(heightSegments); - depthSegments = Math.floor(depthSegments); + if ( object.boundingSphere === null ) object.computeBoundingSphere(); - // buffers + _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld ); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + } else { - // helper variables + const geometry = object.geometry; - let numberOfVertices = 0; - let groupStart = 0; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - // build each side of the box geometry + _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px - buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx - buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py - buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny - buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz - buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz + } - // build geometry + return this.intersectsSphere( _sphere$5 ); - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) { - const segmentWidth = width / gridX; - const segmentHeight = height / gridY; - const widthHalf = width / 2; - const heightHalf = height / 2; - const depthHalf = depth / 2; - const gridX1 = gridX + 1; - const gridY1 = gridY + 1; - let vertexCounter = 0; - let groupCount = 0; - const vector = new Vector3(); + } - // generate vertices, normals and uvs + intersectsSprite( sprite ) { - for (let iy = 0; iy < gridY1; iy++) { - const y = iy * segmentHeight - heightHalf; - for (let ix = 0; ix < gridX1; ix++) { - const x = ix * segmentWidth - widthHalf; + _sphere$5.center.set( 0, 0, 0 ); + _sphere$5.radius = 0.7071067811865476; + _sphere$5.applyMatrix4( sprite.matrixWorld ); - // set values to correct vector component + return this.intersectsSphere( _sphere$5 ); - vector[u] = x * udir; - vector[v] = y * vdir; - vector[w] = depthHalf; + } - // now apply vector to vertex buffer + intersectsSphere( sphere ) { - vertices.push(vector.x, vector.y, vector.z); + const planes = this.planes; + const center = sphere.center; + const negRadius = - sphere.radius; - // set values to correct vector component + for ( let i = 0; i < 6; i ++ ) { - vector[u] = 0; - vector[v] = 0; - vector[w] = depth > 0 ? 1 : -1; + const distance = planes[ i ].distanceToPoint( center ); - // now apply vector to normal buffer + if ( distance < negRadius ) { - normals.push(vector.x, vector.y, vector.z); + return false; - // uvs + } - uvs.push(ix / gridX); - uvs.push(1 - iy / gridY); + } - // counters + return true; - vertexCounter += 1; - } - } + } - // indices + intersectsBox( box ) { - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + const planes = this.planes; - for (let iy = 0; iy < gridY; iy++) { - for (let ix = 0; ix < gridX; ix++) { - const a = numberOfVertices + ix + gridX1 * iy; - const b = numberOfVertices + ix + gridX1 * (iy + 1); - const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); - const d = numberOfVertices + (ix + 1) + gridX1 * iy; + for ( let i = 0; i < 6; i ++ ) { - // faces + const plane = planes[ i ]; - indices.push(a, b, d); - indices.push(b, c, d); + // corner at max distance - // increase counter + _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; + + if ( plane.distanceToPoint( _vector$5 ) < 0 ) { + + return false; - groupCount += 6; - } } - // add a group to the geometry. this will ensure multi material support + } - scope.addGroup(groupStart, groupCount, materialIndex); + return true; - // calculate new start value for groups + } - groupStart += groupCount; + containsPoint( point ) { - // update total number of vertices + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; + + } - numberOfVertices += vertexCounter; } + + return true; + } - static fromJSON(data) { - return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments); + + clone() { + + return new this.constructor().copy( this ); + } + } -class PlaneGeometry extends BufferGeometry { - constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) { - super(); - this.type = 'PlaneGeometry'; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; - const width_half = width / 2; - const height_half = height / 2; - const gridX = Math.floor(widthSegments); - const gridY = Math.floor(heightSegments); - const gridX1 = gridX + 1; - const gridY1 = gridY + 1; - const segment_width = width / gridX; - const segment_height = height / gridY; +class Matrix4 { - // + constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + Matrix4.prototype.isMatrix4 = true; + + this.elements = [ + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ]; + + if ( n11 !== undefined ) { + + this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; - for (let iy = 0; iy < gridY1; iy++) { - const y = iy * segment_height - height_half; - for (let ix = 0; ix < gridX1; ix++) { - const x = ix * segment_width - width_half; - vertices.push(x, -y, 0); - normals.push(0, 0, 1); - uvs.push(ix / gridX); - uvs.push(1 - iy / gridY); - } - } - for (let iy = 0; iy < gridY; iy++) { - for (let ix = 0; ix < gridX; ix++) { - const a = ix + gridX1 * iy; - const b = ix + gridX1 * (iy + 1); - const c = ix + 1 + gridX1 * (iy + 1); - const d = ix + 1 + gridX1 * iy; - indices.push(a, b, d); - indices.push(b, c, d); - } } - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); + } - static fromJSON(data) { - return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments); + + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + const te = this.elements; + + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + + return this; + } -} -let materialId = 0; -class Material extends EventDispatcher { - constructor() { - super(); - this.isMaterial = true; - Object.defineProperty(this, 'id', { - value: materialId++ - }); - this.uuid = generateUUID(); - this.name = ''; - this.type = 'Material'; - this.blending = NormalBlending; - this.side = FrontSide; - this.vertexColors = false; - this.opacity = 1; - this.transparent = false; - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; - this.stencilWriteMask = 0xff; - this.stencilFunc = AlwaysStencilFunc; - this.stencilRef = 0; - this.stencilFuncMask = 0xff; - this.stencilFail = KeepStencilOp; - this.stencilZFail = KeepStencilOp; - this.stencilZPass = KeepStencilOp; - this.stencilWrite = false; - this.clippingPlanes = null; - this.clipIntersection = false; - this.clipShadows = false; - this.shadowSide = null; - this.colorWrite = true; - this.precision = null; // override the renderer's default precision for this material + identity() { - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; - this.dithering = false; - this.alphaToCoverage = false; - this.premultipliedAlpha = false; - this.visible = true; - this.toneMapped = true; - this.userData = {}; - this.version = 0; - this._alphaTest = 0; - } - get alphaTest() { - return this._alphaTest; - } - set alphaTest(value) { - if (this._alphaTest > 0 !== value > 0) { - this.version++; - } - this._alphaTest = value; - } - onBuild( /* shaderobject, renderer */) {} - onBeforeRender( /* renderer, scene, camera, geometry, object, group */) {} - onBeforeCompile( /* shaderobject, renderer */) {} - customProgramCacheKey() { - return this.onBeforeCompile.toString(); - } - setValues(values) { - if (values === undefined) return; - for (const key in values) { - const newValue = values[key]; - if (newValue === undefined) { - console.warn('THREE.Material: \'' + key + '\' parameter is undefined.'); - continue; - } - const currentValue = this[key]; - if (currentValue === undefined) { - console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.'); - continue; - } - if (currentValue && currentValue.isColor) { - currentValue.set(newValue); - } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) { - currentValue.copy(newValue); - } else { - this[key] = newValue; - } - } - } - toJSON(meta) { - const isRootObject = meta === undefined || typeof meta === 'string'; - if (isRootObject) { - meta = { - textures: {}, - images: {} - }; - } - const data = { - metadata: { - version: 4.5, - type: 'Material', - generator: 'Material.toJSON' - } - }; + this.set( - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; - if (this.name !== '') data.name = this.name; - if (this.color && this.color.isColor) data.color = this.color.getHex(); - if (this.roughness !== undefined) data.roughness = this.roughness; - if (this.metalness !== undefined) data.metalness = this.metalness; - if (this.sheen !== undefined) data.sheen = this.sheen; - if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex(); - if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness; - if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex(); - if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity; - if (this.specular && this.specular.isColor) data.specular = this.specular.getHex(); - if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity; - if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex(); - if (this.shininess !== undefined) data.shininess = this.shininess; - if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat; - if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness; - if (this.clearcoatMap && this.clearcoatMap.isTexture) { - data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; - } - if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { - data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; - } - if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { - data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; - data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); - } - if (this.iridescence !== undefined) data.iridescence = this.iridescence; - if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR; - if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange; - if (this.iridescenceMap && this.iridescenceMap.isTexture) { - data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; - } - if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { - data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; - } - if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid; - if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid; - if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid; - if (this.lightMap && this.lightMap.isTexture) { - data.lightMap = this.lightMap.toJSON(meta).uuid; - data.lightMapIntensity = this.lightMapIntensity; - } - if (this.aoMap && this.aoMap.isTexture) { - data.aoMap = this.aoMap.toJSON(meta).uuid; - data.aoMapIntensity = this.aoMapIntensity; - } - if (this.bumpMap && this.bumpMap.isTexture) { - data.bumpMap = this.bumpMap.toJSON(meta).uuid; - data.bumpScale = this.bumpScale; - } - if (this.normalMap && this.normalMap.isTexture) { - data.normalMap = this.normalMap.toJSON(meta).uuid; - data.normalMapType = this.normalMapType; - data.normalScale = this.normalScale.toArray(); - } - if (this.displacementMap && this.displacementMap.isTexture) { - data.displacementMap = this.displacementMap.toJSON(meta).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; - } - if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid; - if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid; - if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid; - if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid; - if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; - if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid; - if (this.envMap && this.envMap.isTexture) { - data.envMap = this.envMap.toJSON(meta).uuid; - if (this.combine !== undefined) data.combine = this.combine; - } - if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity; - if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity; - if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio; - if (this.gradientMap && this.gradientMap.isTexture) { - data.gradientMap = this.gradientMap.toJSON(meta).uuid; - } - if (this.transmission !== undefined) data.transmission = this.transmission; - if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid; - if (this.thickness !== undefined) data.thickness = this.thickness; - if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid; - if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance; - if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex(); - if (this.size !== undefined) data.size = this.size; - if (this.shadowSide !== null) data.shadowSide = this.shadowSide; - if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation; - if (this.blending !== NormalBlending) data.blending = this.blending; - if (this.side !== FrontSide) data.side = this.side; - if (this.vertexColors) data.vertexColors = true; - if (this.opacity < 1) data.opacity = this.opacity; - if (this.transparent === true) data.transparent = this.transparent; - data.depthFunc = this.depthFunc; - data.depthTest = this.depthTest; - data.depthWrite = this.depthWrite; - data.colorWrite = this.colorWrite; - data.stencilWrite = this.stencilWrite; - data.stencilWriteMask = this.stencilWriteMask; - data.stencilFunc = this.stencilFunc; - data.stencilRef = this.stencilRef; - data.stencilFuncMask = this.stencilFuncMask; - data.stencilFail = this.stencilFail; - data.stencilZFail = this.stencilZFail; - data.stencilZPass = this.stencilZPass; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - // rotation (SpriteMaterial) - if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation; - if (this.polygonOffset === true) data.polygonOffset = true; - if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor; - if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits; - if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth; - if (this.dashSize !== undefined) data.dashSize = this.dashSize; - if (this.gapSize !== undefined) data.gapSize = this.gapSize; - if (this.scale !== undefined) data.scale = this.scale; - if (this.dithering === true) data.dithering = true; - if (this.alphaTest > 0) data.alphaTest = this.alphaTest; - if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage; - if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha; - if (this.wireframe === true) data.wireframe = this.wireframe; - if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth; - if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap; - if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin; - if (this.flatShading === true) data.flatShading = this.flatShading; - if (this.visible === false) data.visible = false; - if (this.toneMapped === false) data.toneMapped = false; - if (this.fog === false) data.fog = false; - if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; + ); - // TODO: Copied from Object3D.toJSON + return this; - function extractFromCache(cache) { - const values = []; - for (const key in cache) { - const data = cache[key]; - delete data.metadata; - values.push(data); - } - return values; - } - if (isRootObject) { - const textures = extractFromCache(meta.textures); - const images = extractFromCache(meta.images); - if (textures.length > 0) data.textures = textures; - if (images.length > 0) data.images = images; - } - return data; } + clone() { - return new this.constructor().copy(this); - } - copy(source) { - this.name = source.name; - this.blending = source.blending; - this.side = source.side; - this.vertexColors = source.vertexColors; - this.opacity = source.opacity; - this.transparent = source.transparent; - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; - this.stencilWriteMask = source.stencilWriteMask; - this.stencilFunc = source.stencilFunc; - this.stencilRef = source.stencilRef; - this.stencilFuncMask = source.stencilFuncMask; - this.stencilFail = source.stencilFail; - this.stencilZFail = source.stencilZFail; - this.stencilZPass = source.stencilZPass; - this.stencilWrite = source.stencilWrite; - const srcPlanes = source.clippingPlanes; - let dstPlanes = null; - if (srcPlanes !== null) { - const n = srcPlanes.length; - dstPlanes = new Array(n); - for (let i = 0; i !== n; ++i) { - dstPlanes[i] = srcPlanes[i].clone(); - } - } - this.clippingPlanes = dstPlanes; - this.clipIntersection = source.clipIntersection; - this.clipShadows = source.clipShadows; - this.shadowSide = source.shadowSide; - this.colorWrite = source.colorWrite; - this.precision = source.precision; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; - this.dithering = source.dithering; - this.alphaTest = source.alphaTest; - this.alphaToCoverage = source.alphaToCoverage; - this.premultipliedAlpha = source.premultipliedAlpha; - this.visible = source.visible; - this.toneMapped = source.toneMapped; - this.userData = JSON.parse(JSON.stringify(source.userData)); - return this; - } - dispose() { - this.dispatchEvent({ - type: 'dispose' - }); - } - set needsUpdate(value) { - if (value === true) this.version++; - } -} -/** - * Uniform Utilities - */ + return new Matrix4().fromArray( this.elements ); -function cloneUniforms(src) { - const dst = {}; - for (const u in src) { - dst[u] = {}; - for (const p in src[u]) { - const property = src[u][p]; - if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) { - dst[u][p] = property.clone(); - } else if (Array.isArray(property)) { - dst[u][p] = property.slice(); - } else { - dst[u][p] = property; - } - } - } - return dst; -} -function mergeUniforms(uniforms) { - const merged = {}; - for (let u = 0; u < uniforms.length; u++) { - const tmp = cloneUniforms(uniforms[u]); - for (const p in tmp) { - merged[p] = tmp[p]; - } - } - return merged; -} -function cloneUniformsGroups(src) { - const dst = []; - for (let u = 0; u < src.length; u++) { - dst.push(src[u].clone()); } - return dst; -} -// Legacy + copy( m ) { -const UniformsUtils = { - clone: cloneUniforms, - merge: mergeUniforms -}; + const te = this.elements; + const me = m.elements; -var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; -var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + return this; -class ShaderMaterial extends Material { - constructor(parameters) { - super(); - this.isShaderMaterial = true; - this.type = 'ShaderMaterial'; - this.defines = {}; - this.uniforms = {}; - this.uniformsGroups = []; - this.vertexShader = default_vertex; - this.fragmentShader = default_fragment; - this.linewidth = 1; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + } - this.extensions = { - derivatives: false, - // set to use derivatives - fragDepth: false, - // set to use fragment depth values - drawBuffers: false, - // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + copyPosition( m ) { + + const te = this.elements, me = m.elements; + + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [1, 1, 1], - 'uv': [0, 0], - 'uv2': [0, 0] - }; - this.index0AttributeName = undefined; - this.uniformsNeedUpdate = false; - this.glslVersion = null; - if (parameters !== undefined) { - this.setValues(parameters); - } - } - copy(source) { - super.copy(source); - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; - this.uniforms = cloneUniforms(source.uniforms); - this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); - this.defines = Object.assign({}, source.defines); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.fog = source.fog; - this.lights = source.lights; - this.clipping = source.clipping; - this.extensions = Object.assign({}, source.extensions); - this.glslVersion = source.glslVersion; return this; + } - toJSON(meta) { - const data = super.toJSON(meta); - data.glslVersion = this.glslVersion; - data.uniforms = {}; - for (const name in this.uniforms) { - const uniform = this.uniforms[name]; - const value = uniform.value; - if (value && value.isTexture) { - data.uniforms[name] = { - type: 't', - value: value.toJSON(meta).uuid - }; - } else if (value && value.isColor) { - data.uniforms[name] = { - type: 'c', - value: value.getHex() - }; - } else if (value && value.isVector2) { - data.uniforms[name] = { - type: 'v2', - value: value.toArray() - }; - } else if (value && value.isVector3) { - data.uniforms[name] = { - type: 'v3', - value: value.toArray() - }; - } else if (value && value.isVector4) { - data.uniforms[name] = { - type: 'v4', - value: value.toArray() - }; - } else if (value && value.isMatrix3) { - data.uniforms[name] = { - type: 'm3', - value: value.toArray() - }; - } else if (value && value.isMatrix4) { - data.uniforms[name] = { - type: 'm4', - value: value.toArray() - }; - } else { - data.uniforms[name] = { - value: value - }; - // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far - } - } + setFromMatrix3( m ) { - if (Object.keys(this.defines).length > 0) data.defines = this.defines; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; - const extensions = {}; - for (const key in this.extensions) { - if (this.extensions[key] === true) extensions[key] = true; - } - if (Object.keys(extensions).length > 0) data.extensions = extensions; - return data; - } -} + const me = m.elements; + + this.set( + + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 + + ); -const _vector$7 = /*@__PURE__*/new Vector3(); -const _segCenter = /*@__PURE__*/new Vector3(); -const _segDir = /*@__PURE__*/new Vector3(); -const _diff = /*@__PURE__*/new Vector3(); -const _edge1 = /*@__PURE__*/new Vector3(); -const _edge2 = /*@__PURE__*/new Vector3(); -const _normal$1 = /*@__PURE__*/new Vector3(); -class Ray { - constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) { - this.origin = origin; - this.direction = direction; - } - set(origin, direction) { - this.origin.copy(origin); - this.direction.copy(direction); return this; + } - copy(ray) { - this.origin.copy(ray.origin); - this.direction.copy(ray.direction); + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); + return this; + } - at(t, target) { - return target.copy(this.direction).multiplyScalar(t).add(this.origin); - } - lookAt(v) { - this.direction.copy(v).sub(this.origin).normalize(); + + makeBasis( xAxis, yAxis, zAxis ) { + + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); + return this; + } - recast(t) { - this.origin.copy(this.at(t, _vector$7)); + + extractRotation( m ) { + + // this method does not support reflection matrices + + const te = this.elements; + const me = m.elements; + + const scaleX = 1 / _v1$4.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$4.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$4.setFromMatrixColumn( m, 2 ).length(); + + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; + + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; + + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; + + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + return this; + } - closestPointToPoint(point, target) { - target.subVectors(point, this.origin); - const directionDistance = target.dot(this.direction); - if (directionDistance < 0) { - return target.copy(this.origin); - } - return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin); - } - distanceToPoint(point) { - return Math.sqrt(this.distanceSqToPoint(point)); - } - distanceSqToPoint(point) { - const directionDistance = _vector$7.subVectors(point, this.origin).dot(this.direction); - // point behind the ray + makeRotationFromEuler( euler ) { - if (directionDistance < 0) { - return this.origin.distanceToSquared(point); - } - _vector$7.copy(this.direction).multiplyScalar(directionDistance).add(this.origin); - return _vector$7.distanceToSquared(point); - } - distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { - // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + const te = this.elements; - _segCenter.copy(v0).add(v1).multiplyScalar(0.5); - _segDir.copy(v1).sub(v0).normalize(); - _diff.copy(this.origin).sub(_segCenter); - const segExtent = v0.distanceTo(v1) * 0.5; - const a01 = -this.direction.dot(_segDir); - const b0 = _diff.dot(this.direction); - const b1 = -_diff.dot(_segDir); - const c = _diff.lengthSq(); - const det = Math.abs(1 - a01 * a01); - let s0, s1, sqrDist, extDet; - if (det > 0) { - // The ray and segment are not parallel. + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; - if (s0 >= 0) { - if (s1 >= -extDet) { - if (s1 <= extDet) { - // region 0 - // Minimum at interior points of ray and segment. + if ( euler.order === 'XYZ' ) { - const invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; - } else { - // region 1 + const ae = a * e, af = a * f, be = b * e, bf = b * f; - s1 = segExtent; - s0 = Math.max(0, -(a01 * s1 + b0)); - sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; - } - } else { - // region 5 + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - s1 = -segExtent; - s0 = Math.max(0, -(a01 * s1 + b0)); - sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; - } - } else { - if (s1 <= -extDet) { - // region 4 + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - s0 = Math.max(0, -(-a01 * segExtent + b0)); - s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); - sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; - } else if (s1 <= extDet) { - // region 3 + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - s0 = 0; - s1 = Math.min(Math.max(-segExtent, -b1), segExtent); - sqrDist = s1 * (s1 + 2 * b1) + c; - } else { - // region 2 + } else if ( euler.order === 'YXZ' ) { - s0 = Math.max(0, -(a01 * segExtent + b0)); - s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); - sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; - } - } - } else { - // Ray and segment are parallel. + const ce = c * e, cf = c * f, de = d * e, df = d * f; - s1 = a01 > 0 ? -segExtent : segExtent; - s0 = Math.max(0, -(a01 * s1 + b0)); - sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; - } - if (optionalPointOnRay) { - optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin); - } - if (optionalPointOnSegment) { - optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter); - } - return sqrDist; - } - intersectSphere(sphere, target) { - _vector$7.subVectors(sphere.center, this.origin); - const tca = _vector$7.dot(this.direction); - const d2 = _vector$7.dot(_vector$7) - tca * tca; - const radius2 = sphere.radius * sphere.radius; - if (d2 > radius2) return null; - const thc = Math.sqrt(radius2 - d2); + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - // t0 = first intersect point - entrance on front of sphere - const t0 = tca - thc; + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - // t1 = second intersect point - exit point on back of sphere - const t1 = tca + thc; + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - // test to see if both t0 and t1 are behind the ray - if so, return null - if (t0 < 0 && t1 < 0) return null; + } else if ( euler.order === 'ZXY' ) { - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if (t0 < 0) return this.at(t1, target); + const ce = c * e, cf = c * f, de = d * e, df = d * f; - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at(t0, target); - } - intersectsSphere(sphere) { - return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; - } - distanceToPlane(plane) { - const denominator = plane.normal.dot(this.direction); - if (denominator === 0) { - // line is coplanar, return origin - if (plane.distanceToPoint(this.origin) === 0) { - return 0; - } + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - // Null is preferable to undefined since undefined means.... it is undefined + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - return null; - } - const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - // Return if the ray never intersects the plane + } else if ( euler.order === 'ZYX' ) { - return t >= 0 ? t : null; - } - intersectPlane(plane, target) { - const t = this.distanceToPlane(plane); - if (t === null) { - return null; - } - return this.at(t, target); - } - intersectsPlane(plane) { - // check if the ray lies on the plane first + const ae = a * e, af = a * f, be = b * e, bf = b * f; - const distToPoint = plane.distanceToPoint(this.origin); - if (distToPoint === 0) { - return true; - } - const denominator = plane.normal.dot(this.direction); - if (denominator * distToPoint < 0) { - return true; - } + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - // ray origin is behind the plane (and is pointing behind it) + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - return false; - } - intersectBox(box, target) { - let tmin, tmax, tymin, tymax, tzmin, tzmax; - const invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; - const origin = this.origin; - if (invdirx >= 0) { - tmin = (box.min.x - origin.x) * invdirx; - tmax = (box.max.x - origin.x) * invdirx; - } else { - tmin = (box.max.x - origin.x) * invdirx; - tmax = (box.min.x - origin.x) * invdirx; - } - if (invdiry >= 0) { - tymin = (box.min.y - origin.y) * invdiry; - tymax = (box.max.y - origin.y) * invdiry; - } else { - tymin = (box.max.y - origin.y) * invdiry; - tymax = (box.min.y - origin.y) * invdiry; - } - if (tmin > tymax || tymin > tmax) return null; - if (tymin > tmin || isNaN(tmin)) tmin = tymin; - if (tymax < tmax || isNaN(tmax)) tmax = tymax; - if (invdirz >= 0) { - tzmin = (box.min.z - origin.z) * invdirz; - tzmax = (box.max.z - origin.z) * invdirz; - } else { - tzmin = (box.max.z - origin.z) * invdirz; - tzmax = (box.min.z - origin.z) * invdirz; - } - if (tmin > tzmax || tzmin > tmax) return null; - if (tzmin > tmin || tmin !== tmin) tmin = tzmin; - if (tzmax < tmax || tmax !== tmax) tmax = tzmax; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - //return point closest to the ray (positive side) + } else if ( euler.order === 'YZX' ) { - if (tmax < 0) return null; - return this.at(tmin >= 0 ? tmin : tmax, target); - } - intersectsBox(box) { - return this.intersectBox(box, _vector$7) !== null; - } - intersectTriangle(a, b, c, backfaceCulling, target) { - // Compute the offset origin, edges, and normal. + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - _edge1.subVectors(b, a); - _edge2.subVectors(c, a); - _normal$1.crossVectors(_edge1, _edge2); + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - let DdN = this.direction.dot(_normal$1); - let sign; - if (DdN > 0) { - if (backfaceCulling) return null; - sign = 1; - } else if (DdN < 0) { - sign = -1; - DdN = -DdN; - } else { - return null; - } - _diff.subVectors(this.origin, a); - const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - // b1 < 0, no intersection - if (DdQxE2 < 0) { - return null; - } - const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); + } else if ( euler.order === 'XZY' ) { - // b2 < 0, no intersection - if (DdE1xQ < 0) { - return null; - } + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - // b1+b2 > 1, no intersection - if (DdQxE2 + DdE1xQ > DdN) { - return null; - } + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - // Line intersects triangle, check if ray does. - const QdN = -sign * _diff.dot(_normal$1); + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; + + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - // t < 0, no intersection - if (QdN < 0) { - return null; } - // Ray intersects triangle. - return this.at(QdN / DdN, target); - } - applyMatrix4(matrix4) { - this.origin.applyMatrix4(matrix4); - this.direction.transformDirection(matrix4); + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; + + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + return this; + } - equals(ray) { - return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); - } - clone() { - return new this.constructor().copy(this); - } -} -const _v0$1 = /*@__PURE__*/new Vector3(); -const _v1$4 = /*@__PURE__*/new Vector3(); -const _v2$3 = /*@__PURE__*/new Vector3(); -const _v3$2 = /*@__PURE__*/new Vector3(); -const _vab = /*@__PURE__*/new Vector3(); -const _vac = /*@__PURE__*/new Vector3(); -const _vbc = /*@__PURE__*/new Vector3(); -const _vap = /*@__PURE__*/new Vector3(); -const _vbp = /*@__PURE__*/new Vector3(); -const _vcp = /*@__PURE__*/new Vector3(); -class Triangle { - constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) { - this.a = a; - this.b = b; - this.c = c; + makeRotationFromQuaternion( q ) { + + return this.compose( _zero, q, _one ); + } - static getNormal(a, b, c, target) { - target.subVectors(c, b); - _v0$1.subVectors(a, b); - target.cross(_v0$1); - const targetLengthSq = target.lengthSq(); - if (targetLengthSq > 0) { - return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + + lookAt( eye, target, up ) { + + const te = this.elements; + + _z.subVectors( eye, target ); + + if ( _z.lengthSq() === 0 ) { + + // eye and target are in the same position + + _z.z = 1; + } - return target.set(0, 0, 0); - } - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static getBarycoord(point, a, b, c, target) { - _v0$1.subVectors(c, a); - _v1$4.subVectors(b, a); - _v2$3.subVectors(point, a); - const dot00 = _v0$1.dot(_v0$1); - const dot01 = _v0$1.dot(_v1$4); - const dot02 = _v0$1.dot(_v2$3); - const dot11 = _v1$4.dot(_v1$4); - const dot12 = _v1$4.dot(_v2$3); - const denom = dot00 * dot11 - dot01 * dot01; + _z.normalize(); + _x.crossVectors( up, _z ); + + if ( _x.lengthSq() === 0 ) { + + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { + + _z.x += 0.0001; + + } else { + + _z.z += 0.0001; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); - // collinear or singular triangle - if (denom === 0) { - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set(-2, -1, -1); } - const invDenom = 1 / denom; - const u = (dot11 * dot02 - dot01 * dot12) * invDenom; - const v = (dot00 * dot12 - dot01 * dot02) * invDenom; - // barycentric coordinates must always sum to 1 - return target.set(1 - u - v, v, u); - } - static containsPoint(point, a, b, c) { - this.getBarycoord(point, a, b, c, _v3$2); - return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; - } - static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) { - this.getBarycoord(point, p1, p2, p3, _v3$2); - target.set(0, 0); - target.addScaledVector(uv1, _v3$2.x); - target.addScaledVector(uv2, _v3$2.y); - target.addScaledVector(uv3, _v3$2.z); - return target; + _x.normalize(); + _y.crossVectors( _z, _x ); + + te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; + te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; + te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; + + return this; + } - static isFrontFacing(a, b, c, direction) { - _v0$1.subVectors(c, b); - _v1$4.subVectors(a, b); - // strictly front facing - return _v0$1.cross(_v1$4).dot(direction) < 0 ? true : false; + multiply( m ) { + + return this.multiplyMatrices( this, m ); + } - set(a, b, c) { - this.a.copy(a); - this.b.copy(b); - this.c.copy(c); - return this; + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + } - setFromPointsAndIndices(points, i0, i1, i2) { - this.a.copy(points[i0]); - this.b.copy(points[i1]); - this.c.copy(points[i2]); + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } - setFromAttributeAndIndices(attribute, i0, i1, i2) { - this.a.fromBufferAttribute(attribute, i0); - this.b.fromBufferAttribute(attribute, i1); - this.c.fromBufferAttribute(attribute, i2); + + multiplyScalar( s ) { + + const te = this.elements; + + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + return this; + } - clone() { - return new this.constructor().copy(this); + + determinant() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) + + ); + } - copy(triangle) { - this.a.copy(triangle.a); - this.b.copy(triangle.b); - this.c.copy(triangle.c); + + transpose() { + + const te = this.elements; + let tmp; + + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + return this; + } - getArea() { - _v0$1.subVectors(this.c, this.b); - _v1$4.subVectors(this.a, this.b); - return _v0$1.cross(_v1$4).length() * 0.5; - } - getMidpoint(target) { - return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); - } - getNormal(target) { - return Triangle.getNormal(this.a, this.b, this.c, target); + + setPosition( x, y, z ) { + + const te = this.elements; + + if ( x.isVector3 ) { + + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; + + } else { + + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; + + } + + return this; + } - getPlane(target) { - return target.setFromCoplanarPoints(this.a, this.b, this.c); + + invert() { + + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], + + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + + return this; + } - getBarycoord(point, target) { - return Triangle.getBarycoord(point, this.a, this.b, this.c, target); + + scale( v ) { + + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + + return this; + } - getUV(point, uv1, uv2, uv3, target) { - return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target); + + getMaxScaleOnAxis() { + + const te = this.elements; + + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + } - containsPoint(point) { - return Triangle.containsPoint(point, this.a, this.b, this.c); + + makeTranslation( x, y, z ) { + + if ( x.isVector3 ) { + + this.set( + + 1, 0, 0, x.x, + 0, 1, 0, x.y, + 0, 0, 1, x.z, + 0, 0, 0, 1 + + ); + + } else { + + this.set( + + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); + + } + + return this; + } - isFrontFacing(direction) { - return Triangle.isFrontFacing(this.a, this.b, this.c, direction); + + makeRotationX( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 + + ); + + return this; + } - intersectsBox(box) { - return box.intersectsTriangle(this); + + makeRotationY( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 + + ); + + return this; + } - closestPointToPoint(p, target) { - const a = this.a, - b = this.b, - c = this.c; - let v, w; - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. + makeRotationZ( theta ) { - _vab.subVectors(b, a); - _vac.subVectors(c, a); - _vap.subVectors(p, a); - const d1 = _vab.dot(_vap); - const d2 = _vac.dot(_vap); - if (d1 <= 0 && d2 <= 0) { - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy(a); - } - _vbp.subVectors(p, b); - const d3 = _vab.dot(_vbp); - const d4 = _vac.dot(_vbp); - if (d3 >= 0 && d4 <= d3) { - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy(b); - } - const vc = d1 * d4 - d3 * d2; - if (vc <= 0 && d1 >= 0 && d3 <= 0) { - v = d1 / (d1 - d3); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy(a).addScaledVector(_vab, v); - } - _vcp.subVectors(p, c); - const d5 = _vab.dot(_vcp); - const d6 = _vac.dot(_vcp); - if (d6 >= 0 && d5 <= d6) { - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy(c); - } - const vb = d5 * d2 - d1 * d6; - if (vb <= 0 && d2 >= 0 && d6 <= 0) { - w = d2 / (d2 - d6); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy(a).addScaledVector(_vac, w); - } - const va = d3 * d6 - d5 * d4; - if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { - _vbc.subVectors(c, b); - w = (d4 - d3) / (d4 - d3 + (d5 - d6)); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy(b).addScaledVector(_vbc, w); // edge region of BC - } + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; - // face region - const denom = 1 / (va + vb + vc); - // u = va * denom - v = vb * denom; - w = vc * denom; - return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); } - equals(triangle) { - return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + + makeRotationAxis( axis, angle ) { + + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + + this.set( + + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 + + ); + + return this; + } -} -class MeshBasicMaterial extends Material { - constructor(parameters) { - super(); - this.isMeshBasicMaterial = true; - this.type = 'MeshBasicMaterial'; - this.color = new Color$1(0xffffff); // emissive + makeScale( x, y, z ) { + + this.set( + + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 + + ); + + return this; - this.map = null; - this.lightMap = null; - this.lightMapIntensity = 1.0; - this.aoMap = null; - this.aoMapIntensity = 1.0; - this.specularMap = null; - this.alphaMap = null; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - this.fog = true; - this.setValues(parameters); } - copy(source) { - super.copy(source); - this.color.copy(source.color); - this.map = source.map; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; - this.specularMap = source.specularMap; - this.alphaMap = source.alphaMap; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; - this.fog = source.fog; + + makeShear( xy, xz, yx, yz, zx, zy ) { + + this.set( + + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 + + ); + return this; + } -} -const _inverseMatrix$2 = /*@__PURE__*/new Matrix4(); -const _ray$2 = /*@__PURE__*/new Ray(); -const _sphere$2 = /*@__PURE__*/new Sphere(); -const _vA$1 = /*@__PURE__*/new Vector3(); -const _vB$1 = /*@__PURE__*/new Vector3(); -const _vC$1 = /*@__PURE__*/new Vector3(); -const _tempA = /*@__PURE__*/new Vector3(); -const _tempB = /*@__PURE__*/new Vector3(); -const _tempC = /*@__PURE__*/new Vector3(); -const _morphA = /*@__PURE__*/new Vector3(); -const _morphB = /*@__PURE__*/new Vector3(); -const _morphC = /*@__PURE__*/new Vector3(); -const _uvA$1 = /*@__PURE__*/new Vector2(); -const _uvB$1 = /*@__PURE__*/new Vector2(); -const _uvC$1 = /*@__PURE__*/new Vector2(); -const _intersectionPoint = /*@__PURE__*/new Vector3(); -const _intersectionPointWorld = /*@__PURE__*/new Vector3(); -class Mesh extends Object3D { - constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) { - super(); - this.isMesh = true; - this.type = 'Mesh'; - this.geometry = geometry; - this.material = material; - this.updateMorphTargets(); + compose( position, quaternion, scale ) { + + const te = this.elements; + + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + + const sx = scale.x, sy = scale.y, sz = scale.z; + + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; + + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; + + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; + + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; + + return this; + } - copy(source, recursive) { - super.copy(source, recursive); - if (source.morphTargetInfluences !== undefined) { - this.morphTargetInfluences = source.morphTargetInfluences.slice(); - } - if (source.morphTargetDictionary !== undefined) { - this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); - } - this.material = source.material; - this.geometry = source.geometry; + + decompose( position, quaternion, scale ) { + + const te = this.elements; + + let sx = _v1$4.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$4.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$4.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; + + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; + + // scale the rotation part + _m1$2.copy( this ); + + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; + + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; + + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; + + quaternion.setFromRotationMatrix( _m1$2 ); + + scale.x = sx; + scale.y = sy; + scale.z = sz; + return this; + } - updateMorphTargets() { - const geometry = this.geometry; - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys(morphAttributes); - if (keys.length > 0) { - const morphAttribute = morphAttributes[keys[0]]; - if (morphAttribute !== undefined) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; - for (let m = 0, ml = morphAttribute.length; m < ml; m++) { - const name = morphAttribute[m].name || String(m); - this.morphTargetInfluences.push(0); - this.morphTargetDictionary[name] = m; - } - } + + makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) { + + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); + + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + + let c, d; + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + c = - ( far + near ) / ( far - near ); + d = ( - 2 * far * near ) / ( far - near ); + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + c = - far / ( far - near ); + d = ( - far * near ) / ( far - near ); + + } else { + + throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem ); + } + + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + + return this; + } - raycast(raycaster, intersects) { - const geometry = this.geometry; - const material = this.material; - const matrixWorld = this.matrixWorld; - if (material === undefined) return; - // Checking boundingSphere distance to ray + makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) { - if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); - _sphere$2.copy(geometry.boundingSphere); - _sphere$2.applyMatrix4(matrixWorld); - if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); - // + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; - _inverseMatrix$2.copy(matrixWorld).invert(); - _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + let z, zInv; - // Check boundingBox before continuing + if ( coordinateSystem === WebGLCoordinateSystem ) { - if (geometry.boundingBox !== null) { - if (_ray$2.intersectsBox(geometry.boundingBox) === false) return; - } - let intersection; - const index = geometry.index; - const position = geometry.attributes.position; - const morphPosition = geometry.morphAttributes.position; - const morphTargetsRelative = geometry.morphTargetsRelative; - const uv = geometry.attributes.uv; - const uv2 = geometry.attributes.uv2; - const groups = geometry.groups; - const drawRange = geometry.drawRange; - if (index !== null) { - // indexed buffer geometry + z = ( far + near ) * p; + zInv = - 2 * p; - if (Array.isArray(material)) { - for (let i = 0, il = groups.length; i < il; i++) { - const group = groups[i]; - const groupMaterial = material[group.materialIndex]; - const start = Math.max(group.start, drawRange.start); - const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); - for (let j = start, jl = end; j < jl; j += 3) { - const a = index.getX(j); - const b = index.getX(j + 1); - const c = index.getX(j + 2); - intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); - if (intersection) { - intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push(intersection); - } - } - } - } else { - const start = Math.max(0, drawRange.start); - const end = Math.min(index.count, drawRange.start + drawRange.count); - for (let i = start, il = end; i < il; i += 3) { - const a = index.getX(i); - const b = index.getX(i + 1); - const c = index.getX(i + 2); - intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); - if (intersection) { - intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics - intersects.push(intersection); - } - } - } - } else if (position !== undefined) { - // non-indexed buffer geometry + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + z = near * p; + zInv = - 1 * p; + + } else { + + throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem ); - if (Array.isArray(material)) { - for (let i = 0, il = groups.length; i < il; i++) { - const group = groups[i]; - const groupMaterial = material[group.materialIndex]; - const start = Math.max(group.start, drawRange.start); - const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); - for (let j = start, jl = end; j < jl; j += 3) { - const a = j; - const b = j + 1; - const c = j + 2; - intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); - if (intersection) { - intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push(intersection); - } - } - } - } else { - const start = Math.max(0, drawRange.start); - const end = Math.min(position.count, drawRange.start + drawRange.count); - for (let i = start, il = end; i < il; i += 3) { - const a = i; - const b = i + 1; - const c = i + 2; - intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); - if (intersection) { - intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics - intersects.push(intersection); - } - } - } } + + te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + + return this; + } -} -function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) { - let intersect; - if (material.side === BackSide) { - intersect = ray.intersectTriangle(pC, pB, pA, true, point); - } else { - intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point); - } - if (intersect === null) return null; - _intersectionPointWorld.copy(point); - _intersectionPointWorld.applyMatrix4(object.matrixWorld); - const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); - if (distance < raycaster.near || distance > raycaster.far) return null; - return { - distance: distance, - point: _intersectionPointWorld.clone(), - object: object - }; -} -function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) { - _vA$1.fromBufferAttribute(position, a); - _vB$1.fromBufferAttribute(position, b); - _vC$1.fromBufferAttribute(position, c); - const morphInfluences = object.morphTargetInfluences; - if (morphPosition && morphInfluences) { - _morphA.set(0, 0, 0); - _morphB.set(0, 0, 0); - _morphC.set(0, 0, 0); - for (let i = 0, il = morphPosition.length; i < il; i++) { - const influence = morphInfluences[i]; - const morphAttribute = morphPosition[i]; - if (influence === 0) continue; - _tempA.fromBufferAttribute(morphAttribute, a); - _tempB.fromBufferAttribute(morphAttribute, b); - _tempC.fromBufferAttribute(morphAttribute, c); - if (morphTargetsRelative) { - _morphA.addScaledVector(_tempA, influence); - _morphB.addScaledVector(_tempB, influence); - _morphC.addScaledVector(_tempC, influence); - } else { - _morphA.addScaledVector(_tempA.sub(_vA$1), influence); - _morphB.addScaledVector(_tempB.sub(_vB$1), influence); - _morphC.addScaledVector(_tempC.sub(_vC$1), influence); - } + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 16; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + } - _vA$1.add(_morphA); - _vB$1.add(_morphB); - _vC$1.add(_morphC); - } - if (object.isSkinnedMesh) { - object.boneTransform(a, _vA$1); - object.boneTransform(b, _vB$1); - object.boneTransform(c, _vC$1); - } - const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); - if (intersection) { - if (uv) { - _uvA$1.fromBufferAttribute(uv, a); - _uvB$1.fromBufferAttribute(uv, b); - _uvC$1.fromBufferAttribute(uv, c); - intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); - } - if (uv2) { - _uvA$1.fromBufferAttribute(uv2, a); - _uvB$1.fromBufferAttribute(uv2, b); - _uvC$1.fromBufferAttribute(uv2, c); - intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 16; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + } - const face = { - a: a, - b: b, - c: c, - normal: new Vector3(), - materialIndex: 0 - }; - Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); - intersection.face = face; + + return this; + } - return intersection; + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; + + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; + + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; + + return array; + + } + } -var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); -var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; +function WebGLAnimation() { -var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; -var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + function onAnimationFrame( time, frame ) { -var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + animationLoop( time, frame ); -var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + requestId = context.requestAnimationFrame( onAnimationFrame ); -var begin_vertex = "vec3 transformed = vec3( position );"; + } -var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + return { -var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + start: function () { -var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; -var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + requestId = context.requestAnimationFrame( onAnimationFrame ); -var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + isAnimating = true; -var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + }, -var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + stop: function () { -var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + context.cancelAnimationFrame( requestId ); -var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + isAnimating = false; -var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + }, -var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + setAnimationLoop: function ( callback ) { -var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; + animationLoop = callback; -var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; + }, -var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + setContext: function ( value ) { -var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + context = value; -var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + } -var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; + }; -var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; +} -var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; +function WebGLAttributes( gl, capabilities ) { -var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + const isWebGL2 = capabilities.isWebGL2; -var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; + const buffers = new WeakMap(); -var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + function createBuffer( attribute, bufferType ) { -var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + const array = attribute.array; + const usage = attribute.usage; -var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + const buffer = gl.createBuffer(); -var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); -var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + attribute.onUploadCallback(); -var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + let type; -var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + if ( array instanceof Float32Array ) { -var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + type = gl.FLOAT; -var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + } else if ( array instanceof Uint16Array ) { -var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + if ( attribute.isFloat16BufferAttribute ) { -var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + if ( isWebGL2 ) { -var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + type = gl.HALF_FLOAT; -var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + } else { -var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)"; + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); -var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + } -var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; + } else { -var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + type = gl.UNSIGNED_SHORT; -var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; + } -var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + } else if ( array instanceof Int16Array ) { -var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; + type = gl.SHORT; -var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; + } else if ( array instanceof Uint32Array ) { -var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + type = gl.UNSIGNED_INT; -var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + } else if ( array instanceof Int32Array ) { -var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + type = gl.INT; -var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + } else if ( array instanceof Int8Array ) { -var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + type = gl.BYTE; -var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + } else if ( array instanceof Uint8Array ) { -var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + type = gl.UNSIGNED_BYTE; -var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + } else if ( array instanceof Uint8ClampedArray ) { -var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + type = gl.UNSIGNED_BYTE; -var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + } else { -var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); -var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + } -var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; -var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + } -var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + function updateBuffer( buffer, attribute, bufferType ) { -var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; + const array = attribute.array; + const updateRange = attribute.updateRange; -var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + gl.bindBuffer( bufferType, buffer ); -var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; + if ( updateRange.count === - 1 ) { -var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + // Not using update ranges -var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + gl.bufferSubData( bufferType, 0, array ); -var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + } else { -var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + if ( isWebGL2 ) { -var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array, updateRange.offset, updateRange.count ); -var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + } else { -var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); -var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; + } -var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; + updateRange.count = - 1; // reset range -var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + } -var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + attribute.onUploadCallback(); -var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; + } -var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + // -var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + function get( attribute ) { -var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; -var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + return buffers.get( attribute ); -var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + } -var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + function remove( attribute ) { -var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; -var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + const data = buffers.get( attribute ); -var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; + if ( data ) { -var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + gl.deleteBuffer( data.buffer ); -var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + buffers.delete( attribute ); -var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; + } -var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + } -var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + function update( attribute, bufferType ) { -var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + if ( attribute.isGLBufferAttribute ) { -var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + const cached = buffers.get( attribute ); -var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + if ( ! cached || cached.version < attribute.version ) { -var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); -var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; + } -var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; + return; -var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; + } -var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; -var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; + const data = buffers.get( attribute ); -var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + if ( data === undefined ) { -var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; + buffers.set( attribute, createBuffer( attribute, bufferType ) ); -var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; + } else if ( data.version < attribute.version ) { -var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + updateBuffer( data.buffer, attribute, bufferType ); -const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; -const fragment$h = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include \n\t#include \n}"; + data.version = attribute.version; -const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; -const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + } -const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; -const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + } -const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; -const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; + return { -const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; -const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + get: get, + remove: remove, + update: update -const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; -const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + }; -const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +} -const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const _vector$4 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector2(); -const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +class BufferAttribute { -const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; -const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + constructor( array, itemSize, normalized = false ) { -const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; -const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + if ( Array.isArray( array ) ) { -const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); -const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; -const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + } -const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; -const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + this.isBufferAttribute = true; -const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + this.name = ''; -const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; -const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; -const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + this.gpuType = FloatType; -const ShaderChunk = { - alphamap_fragment: alphamap_fragment, - alphamap_pars_fragment: alphamap_pars_fragment, - alphatest_fragment: alphatest_fragment, - alphatest_pars_fragment: alphatest_pars_fragment, - aomap_fragment: aomap_fragment, - aomap_pars_fragment: aomap_pars_fragment, - begin_vertex: begin_vertex, - beginnormal_vertex: beginnormal_vertex, - bsdfs: bsdfs, - iridescence_fragment: iridescence_fragment, - bumpmap_pars_fragment: bumpmap_pars_fragment, - clipping_planes_fragment: clipping_planes_fragment, - clipping_planes_pars_fragment: clipping_planes_pars_fragment, - clipping_planes_pars_vertex: clipping_planes_pars_vertex, - clipping_planes_vertex: clipping_planes_vertex, - color_fragment: color_fragment, - color_pars_fragment: color_pars_fragment, - color_pars_vertex: color_pars_vertex, - color_vertex: color_vertex, - common: common, - cube_uv_reflection_fragment: cube_uv_reflection_fragment, - defaultnormal_vertex: defaultnormal_vertex, - displacementmap_pars_vertex: displacementmap_pars_vertex, - displacementmap_vertex: displacementmap_vertex, - emissivemap_fragment: emissivemap_fragment, - emissivemap_pars_fragment: emissivemap_pars_fragment, - encodings_fragment: encodings_fragment, - encodings_pars_fragment: encodings_pars_fragment, - envmap_fragment: envmap_fragment, - envmap_common_pars_fragment: envmap_common_pars_fragment, - envmap_pars_fragment: envmap_pars_fragment, - envmap_pars_vertex: envmap_pars_vertex, - envmap_physical_pars_fragment: envmap_physical_pars_fragment, - envmap_vertex: envmap_vertex, - fog_vertex: fog_vertex, - fog_pars_vertex: fog_pars_vertex, - fog_fragment: fog_fragment, - fog_pars_fragment: fog_pars_fragment, - gradientmap_pars_fragment: gradientmap_pars_fragment, - lightmap_fragment: lightmap_fragment, - lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_fragment: lights_lambert_fragment, - lights_lambert_pars_fragment: lights_lambert_pars_fragment, - lights_pars_begin: lights_pars_begin, - lights_toon_fragment: lights_toon_fragment, - lights_toon_pars_fragment: lights_toon_pars_fragment, - lights_phong_fragment: lights_phong_fragment, - lights_phong_pars_fragment: lights_phong_pars_fragment, - lights_physical_fragment: lights_physical_fragment, - lights_physical_pars_fragment: lights_physical_pars_fragment, - lights_fragment_begin: lights_fragment_begin, - lights_fragment_maps: lights_fragment_maps, - lights_fragment_end: lights_fragment_end, - logdepthbuf_fragment: logdepthbuf_fragment, - logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, - logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, - logdepthbuf_vertex: logdepthbuf_vertex, - map_fragment: map_fragment, - map_pars_fragment: map_pars_fragment, - map_particle_fragment: map_particle_fragment, - map_particle_pars_fragment: map_particle_pars_fragment, - metalnessmap_fragment: metalnessmap_fragment, - metalnessmap_pars_fragment: metalnessmap_pars_fragment, - morphcolor_vertex: morphcolor_vertex, - morphnormal_vertex: morphnormal_vertex, - morphtarget_pars_vertex: morphtarget_pars_vertex, - morphtarget_vertex: morphtarget_vertex, - normal_fragment_begin: normal_fragment_begin, - normal_fragment_maps: normal_fragment_maps, - normal_pars_fragment: normal_pars_fragment, - normal_pars_vertex: normal_pars_vertex, - normal_vertex: normal_vertex, - normalmap_pars_fragment: normalmap_pars_fragment, - clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, - clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, - clearcoat_pars_fragment: clearcoat_pars_fragment, - iridescence_pars_fragment: iridescence_pars_fragment, - output_fragment: output_fragment, - packing: packing, - premultiplied_alpha_fragment: premultiplied_alpha_fragment, - project_vertex: project_vertex, - dithering_fragment: dithering_fragment, - dithering_pars_fragment: dithering_pars_fragment, - roughnessmap_fragment: roughnessmap_fragment, - roughnessmap_pars_fragment: roughnessmap_pars_fragment, - shadowmap_pars_fragment: shadowmap_pars_fragment, - shadowmap_pars_vertex: shadowmap_pars_vertex, - shadowmap_vertex: shadowmap_vertex, - shadowmask_pars_fragment: shadowmask_pars_fragment, - skinbase_vertex: skinbase_vertex, - skinning_pars_vertex: skinning_pars_vertex, - skinning_vertex: skinning_vertex, - skinnormal_vertex: skinnormal_vertex, - specularmap_fragment: specularmap_fragment, - specularmap_pars_fragment: specularmap_pars_fragment, - tonemapping_fragment: tonemapping_fragment, - tonemapping_pars_fragment: tonemapping_pars_fragment, - transmission_fragment: transmission_fragment, - transmission_pars_fragment: transmission_pars_fragment, - uv_pars_fragment: uv_pars_fragment, - uv_pars_vertex: uv_pars_vertex, - uv_vertex: uv_vertex, - uv2_pars_fragment: uv2_pars_fragment, - uv2_pars_vertex: uv2_pars_vertex, - uv2_vertex: uv2_vertex, - worldpos_vertex: worldpos_vertex, - background_vert: vertex$h, - background_frag: fragment$h, - backgroundCube_vert: vertex$g, - backgroundCube_frag: fragment$g, - cube_vert: vertex$f, - cube_frag: fragment$f, - depth_vert: vertex$e, - depth_frag: fragment$e, - distanceRGBA_vert: vertex$d, - distanceRGBA_frag: fragment$d, - equirect_vert: vertex$c, - equirect_frag: fragment$c, - linedashed_vert: vertex$b, - linedashed_frag: fragment$b, - meshbasic_vert: vertex$a, - meshbasic_frag: fragment$a, - meshlambert_vert: vertex$9, - meshlambert_frag: fragment$9, - meshmatcap_vert: vertex$8, - meshmatcap_frag: fragment$8, - meshnormal_vert: vertex$7, - meshnormal_frag: fragment$7, - meshphong_vert: vertex$6, - meshphong_frag: fragment$6, - meshphysical_vert: vertex$5, - meshphysical_frag: fragment$5, - meshtoon_vert: vertex$4, - meshtoon_frag: fragment$4, - points_vert: vertex$3, - points_frag: fragment$3, - shadow_vert: vertex$2, - shadow_frag: fragment$2, - sprite_vert: vertex$1, - sprite_frag: fragment$1 -}; + this.version = 0; -/** - * Uniforms library for shared webgl shaders - */ + } -const UniformsLib = { - common: { - diffuse: { - value: /*@__PURE__*/new Color$1(0xffffff) - }, - opacity: { - value: 1.0 - }, - map: { - value: null - }, - uvTransform: { - value: /*@__PURE__*/new Matrix3() - }, - uv2Transform: { - value: /*@__PURE__*/new Matrix3() - }, - alphaMap: { - value: null - }, - alphaTest: { - value: 0 - } - }, - specularmap: { - specularMap: { - value: null - } - }, - envmap: { - envMap: { - value: null - }, - flipEnvMap: { - value: -1 - }, - reflectivity: { - value: 1.0 - }, - // basic, lambert, phong - ior: { - value: 1.5 - }, - // physical - refractionRatio: { - value: 0.98 - } // basic, lambert, phong - }, + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + + this.usage = source.usage; + this.gpuType = source.gpuType; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.itemSize; + index2 *= attribute.itemSize; + + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - aomap: { - aoMap: { - value: null - }, - aoMapIntensity: { - value: 1 - } - }, - lightmap: { - lightMap: { - value: null - }, - lightMapIntensity: { - value: 1 - } - }, - emissivemap: { - emissiveMap: { - value: null - } - }, - bumpmap: { - bumpMap: { - value: null - }, - bumpScale: { - value: 1 - } - }, - normalmap: { - normalMap: { - value: null - }, - normalScale: { - value: /*@__PURE__*/new Vector2(1, 1) - } - }, - displacementmap: { - displacementMap: { - value: null - }, - displacementScale: { - value: 1 - }, - displacementBias: { - value: 0 } - }, - roughnessmap: { - roughnessMap: { - value: null + + return this; + + } + + copyArray( array ) { + + this.array.set( array ); + + return this; + + } + + applyMatrix3( m ) { + + if ( this.itemSize === 2 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector2.fromBufferAttribute( this, i ); + _vector2.applyMatrix3( m ); + + this.setXY( i, _vector2.x, _vector2.y ); + + } + + } else if ( this.itemSize === 3 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$4.fromBufferAttribute( this, i ); + _vector$4.applyMatrix3( m ); + + this.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + + } + } - }, - metalnessmap: { - metalnessMap: { - value: null + + return this; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$4.fromBufferAttribute( this, i ); + + _vector$4.applyMatrix4( m ); + + this.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + } - }, - gradientmap: { - gradientMap: { - value: null + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$4.fromBufferAttribute( this, i ); + + _vector$4.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + } - }, - fog: { - fogDensity: { - value: 0.00025 - }, - fogNear: { - value: 1 - }, - fogFar: { - value: 2000 - }, - fogColor: { - value: /*@__PURE__*/new Color$1(0xffffff) + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$4.fromBufferAttribute( this, i ); + + _vector$4.transformDirection( m ); + + this.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + } - }, - lights: { - ambientLightColor: { - value: [] - }, - lightProbe: { - value: [] - }, - directionalLights: { - value: [], - properties: { - direction: {}, - color: {} - } - }, - directionalLightShadows: { - value: [], - properties: { - shadowBias: {}, - shadowNormalBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } - }, - directionalShadowMap: { - value: [] - }, - directionalShadowMatrix: { - value: [] - }, - spotLights: { - value: [], - properties: { - color: {}, - position: {}, - direction: {}, - distance: {}, - coneCos: {}, - penumbraCos: {}, - decay: {} - } - }, - spotLightShadows: { - value: [], - properties: { - shadowBias: {}, - shadowNormalBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } - }, - spotLightMap: { - value: [] - }, - spotShadowMap: { - value: [] - }, - spotLightMatrix: { - value: [] - }, - pointLights: { - value: [], - properties: { - color: {}, - position: {}, - decay: {}, - distance: {} - } - }, - pointLightShadows: { - value: [], - properties: { - shadowBias: {}, - shadowNormalBias: {}, - shadowRadius: {}, - shadowMapSize: {}, - shadowCameraNear: {}, - shadowCameraFar: {} - } - }, - pointShadowMap: { - value: [] - }, - pointShadowMatrix: { - value: [] - }, - hemisphereLights: { - value: [], - properties: { - direction: {}, - skyColor: {}, - groundColor: {} - } - }, - // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src - rectAreaLights: { - value: [], - properties: { - color: {}, - position: {}, - width: {}, - height: {} - } - }, - ltc_1: { - value: null - }, - ltc_2: { - value: null + + return this; + + } + + set( value, offset = 0 ) { + + // Matching BufferAttribute constructor, do not normalize the array. + this.array.set( value, offset ); + + return this; + + } + + getComponent( index, component ) { + + let value = this.array[ index * this.itemSize + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize( value, this.array ); + + this.array[ index * this.itemSize + component ] = value; + + return this; + + } + + getX( index ) { + + let x = this.array[ index * this.itemSize ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = x; + + return this; + + } + + getY( index ) { + + let y = this.array[ index * this.itemSize + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = y; + + return this; + + } + + getZ( index ) { + + let z = this.array[ index * this.itemSize + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = z; + + return this; + + } + + getW( index ) { + + let w = this.array[ index * this.itemSize + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = w; + + return this; + + } + + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + } - }, - points: { - diffuse: { - value: /*@__PURE__*/new Color$1(0xffffff) - }, - opacity: { - value: 1.0 - }, - size: { - value: 1.0 - }, - scale: { - value: 1.0 - }, - map: { - value: null - }, - alphaMap: { - value: null - }, - alphaTest: { - value: 0 - }, - uvTransform: { - value: /*@__PURE__*/new Matrix3() + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + } - }, - sprite: { - diffuse: { - value: /*@__PURE__*/new Color$1(0xffffff) - }, - opacity: { - value: 1.0 - }, - center: { - value: /*@__PURE__*/new Vector2(0.5, 0.5) - }, - rotation: { - value: 0.0 - }, - map: { - value: null - }, - alphaMap: { - value: null - }, - alphaTest: { - value: 0 - }, - uvTransform: { - value: /*@__PURE__*/new Matrix3() + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; + + return this; + } -}; -const ShaderLib = { - basic: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]), - vertexShader: ShaderChunk.meshbasic_vert, - fragmentShader: ShaderChunk.meshbasic_frag - }, - lambert: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { - value: /*@__PURE__*/new Color$1(0x000000) - } - }]), - vertexShader: ShaderChunk.meshlambert_vert, - fragmentShader: ShaderChunk.meshlambert_frag - }, - phong: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { - value: /*@__PURE__*/new Color$1(0x000000) - }, - specular: { - value: /*@__PURE__*/new Color$1(0x111111) - }, - shininess: { - value: 30 - } - }]), - vertexShader: ShaderChunk.meshphong_vert, - fragmentShader: ShaderChunk.meshphong_frag - }, - standard: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { - value: /*@__PURE__*/new Color$1(0x000000) - }, - roughness: { - value: 1.0 - }, - metalness: { - value: 0.0 - }, - envMapIntensity: { - value: 1 - } // temporary - }]), + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + clone() { + + return new this.constructor( this.array, this.itemSize ).copy( this ); + + } + + toJSON() { + + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from( this.array ), + normalized: this.normalized + }; + + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; + + return data; + + } + +} + +class Uint16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + } + +} + +class Uint32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint32Array( array ), itemSize, normalized ); + + } + +} + + +class Float32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } + +} + +const _matrix = /*@__PURE__*/ new Matrix4(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); + +class Euler { + + constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) { + + this.isEuler = true; + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get order() { + + return this._order; + + } + + set order( value ) { + + this._order = value; + this._onChangeCallback(); + + } + + set( x, y, z, order = this._order ) { + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._order ); + + } + + copy( euler ) { + + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m, order = this._order, update = true ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + switch ( order ) { + + case 'XYZ': + + this._y = Math.asin( clamp( m13, - 1, 1 ) ); + + if ( Math.abs( m13 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); + + } else { + + this._x = Math.atan2( m32, m22 ); + this._z = 0; + + } + + break; + + case 'YXZ': + + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + + if ( Math.abs( m23 ) < 0.9999999 ) { + + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); + + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; + + } + + break; + + case 'ZXY': + + this._x = Math.asin( clamp( m32, - 1, 1 ) ); + + if ( Math.abs( m32 ) < 0.9999999 ) { + + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); + + } else { + + this._y = 0; + this._z = Math.atan2( m21, m11 ); + + } + + break; + + case 'ZYX': + + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + + if ( Math.abs( m31 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); + + } else { + + this._x = 0; + this._z = Math.atan2( - m12, m22 ); + + } + + break; + + case 'YZX': + + this._z = Math.asin( clamp( m21, - 1, 1 ) ); + + if ( Math.abs( m21 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); + + } else { + + this._x = 0; + this._y = Math.atan2( m13, m33 ); + + } + + break; + + case 'XZY': + + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + + if ( Math.abs( m12 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); + + } else { + + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + break; + + default: + + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + + } + + this._order = order; + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + setFromQuaternion( q, order, update ) { + + _matrix.makeRotationFromQuaternion( q ); + + return this.setFromRotationMatrix( _matrix, order, update ); + + } + + setFromVector3( v, order = this._order ) { + + return this.set( v.x, v.y, v.z, order ); + + } + + reorder( newOrder ) { + + // WARNING: this discards revolution information -bhouston + + _quaternion$1.setFromEuler( this ); + + return this.setFromQuaternion( _quaternion$1, newOrder ); + + } + + equals( euler ) { + + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + + } + + fromArray( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; + + return array; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + +} + +Euler.DEFAULT_ORDER = 'XYZ'; + +class Layers { + + constructor() { + + this.mask = 1 | 0; + + } + + set( channel ) { + + this.mask = ( 1 << channel | 0 ) >>> 0; + + } + + enable( channel ) { + + this.mask |= 1 << channel | 0; + + } + + enableAll() { + + this.mask = 0xffffffff | 0; + + } + + toggle( channel ) { + + this.mask ^= 1 << channel | 0; + + } + + disable( channel ) { + + this.mask &= ~ ( 1 << channel | 0 ); + + } + + disableAll() { + + this.mask = 0; + + } + + test( layers ) { + + return ( this.mask & layers.mask ) !== 0; + + } + + isEnabled( channel ) { + + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; + + } + +} + +let _object3DId = 0; + +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); + +const _position$1 = /*@__PURE__*/ new Vector3(); +const _scale = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); + +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); + +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; + +class Object3D extends EventDispatcher { + + constructor() { + + super(); + + this.isObject3D = true; + + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Object3D'; + + this.parent = null; + this.children = []; + + this.up = Object3D.DEFAULT_UP.clone(); + + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); + + function onRotationChange() { + + quaternion.setFromEuler( rotation, false ); + + } + + function onQuaternionChange() { + + rotation.setFromQuaternion( quaternion, undefined, false ); + + } + + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); + + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); + + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer + + this.layers = new Layers(); + this.visible = true; + + this.castShadow = false; + this.receiveShadow = false; + + this.frustumCulled = true; + this.renderOrder = 0; + + this.animations = []; + + this.userData = {}; + + } + + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + applyMatrix4( matrix ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + this.matrix.premultiply( matrix ); + + this.matrix.decompose( this.position, this.quaternion, this.scale ); + + } + + applyQuaternion( q ) { + + this.quaternion.premultiply( q ); + + return this; + + } + + setRotationFromAxisAngle( axis, angle ) { + + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); + + } + + setRotationFromEuler( euler ) { + + this.quaternion.setFromEuler( euler, true ); + + } + + setRotationFromMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + this.quaternion.setFromRotationMatrix( m ); + + } + + setRotationFromQuaternion( q ) { + + // assumes q is normalized + + this.quaternion.copy( q ); + + } + + rotateOnAxis( axis, angle ) { + + // rotate object on axis in object space + // axis is assumed to be normalized + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.multiply( _q1 ); + + return this; + + } + + rotateOnWorldAxis( axis, angle ) { + + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.premultiply( _q1 ); + + return this; + + } + + rotateX( angle ) { + + return this.rotateOnAxis( _xAxis, angle ); + + } + + rotateY( angle ) { + + return this.rotateOnAxis( _yAxis, angle ); + + } + + rotateZ( angle ) { + + return this.rotateOnAxis( _zAxis, angle ); + + } + + translateOnAxis( axis, distance ) { + + // translate object by distance along axis in object space + // axis is assumed to be normalized + + _v1$3.copy( axis ).applyQuaternion( this.quaternion ); + + this.position.add( _v1$3.multiplyScalar( distance ) ); + + return this; + + } + + translateX( distance ) { + + return this.translateOnAxis( _xAxis, distance ); + + } + + translateY( distance ) { + + return this.translateOnAxis( _yAxis, distance ); + + } + + translateZ( distance ) { + + return this.translateOnAxis( _zAxis, distance ); + + } + + localToWorld( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( this.matrixWorld ); + + } + + worldToLocal( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + + } + + lookAt( x, y, z ) { + + // This method does not support objects having non-uniformly-scaled parent(s) + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + const parent = this.parent; + + this.updateWorldMatrix( true, false ); + + _position$1.setFromMatrixPosition( this.matrixWorld ); + + if ( this.isCamera || this.isLight ) { + + _m1$1.lookAt( _position$1, _target, this.up ); + + } else { + + _m1$1.lookAt( _target, _position$1, this.up ); + + } + + this.quaternion.setFromRotationMatrix( _m1$1 ); + + if ( parent ) { + + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); + + } + + } + + add( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + } + + if ( object === this ) { + + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; + + } + + if ( object && object.isObject3D ) { + + if ( object.parent !== null ) { + + object.parent.remove( object ); + + } + + object.parent = this; + this.children.push( object ); + + object.dispatchEvent( _addedEvent ); + + } else { + + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + + } + + return this; + + } + + remove( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.remove( arguments[ i ] ); + + } + + return this; + + } + + const index = this.children.indexOf( object ); + + if ( index !== - 1 ) { + + object.parent = null; + this.children.splice( index, 1 ); + + object.dispatchEvent( _removedEvent ); + + } + + return this; + + } + + removeFromParent() { + + const parent = this.parent; + + if ( parent !== null ) { + + parent.remove( this ); + + } + + return this; + + } + + clear() { + + for ( let i = 0; i < this.children.length; i ++ ) { + + const object = this.children[ i ]; + + object.parent = null; + + object.dispatchEvent( _removedEvent ); + + } + + this.children.length = 0; + + return this; + + + } + + attach( object ) { + + // adds object as a child of this, while maintaining the object's world transform + + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + + this.updateWorldMatrix( true, false ); + + _m1$1.copy( this.matrixWorld ).invert(); + + if ( object.parent !== null ) { + + object.parent.updateWorldMatrix( true, false ); + + _m1$1.multiply( object.parent.matrixWorld ); + + } + + object.applyMatrix4( _m1$1 ); + + this.add( object ); + + object.updateWorldMatrix( false, true ); + + return this; + + } + + getObjectById( id ) { + + return this.getObjectByProperty( 'id', id ); + + } + + getObjectByName( name ) { + + return this.getObjectByProperty( 'name', name ); + + } + + getObjectByProperty( name, value ) { + + if ( this[ name ] === value ) return this; + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); + + if ( object !== undefined ) { + + return object; + + } + + } + + return undefined; + + } + + getObjectsByProperty( name, value ) { + + let result = []; + + if ( this[ name ] === value ) result.push( this ); + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const childResult = this.children[ i ].getObjectsByProperty( name, value ); + + if ( childResult.length > 0 ) { + + result = result.concat( childResult ); + + } + + } + + return result; + + } + + getWorldPosition( target ) { + + this.updateWorldMatrix( true, false ); + + return target.setFromMatrixPosition( this.matrixWorld ); + + } + + getWorldQuaternion( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$1, target, _scale ); + + return target; + + } + + getWorldScale( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$1, _quaternion, target ); + + return target; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + + } + + raycast( /* raycaster, intersects */ ) {} + + traverse( callback ) { + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverse( callback ); + + } + + } + + traverseVisible( callback ) { + + if ( this.visible === false ) return; + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverseVisible( callback ); + + } + + } + + traverseAncestors( callback ) { + + const parent = this.parent; + + if ( parent !== null ) { + + callback( parent ); + + parent.traverseAncestors( callback ); + + } + + } + + updateMatrix() { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + this.matrixWorldNeedsUpdate = true; + + } + + updateMatrixWorld( force ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // update children + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } + + } + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + const parent = this.parent; + + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { + + parent.updateWorldMatrix( true, false ); + + } + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + // update children + + if ( updateChildren === true ) { + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true ) { + + child.updateWorldMatrix( false, true ); + + } + + } + + } + + } + + toJSON( meta ) { + + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + const output = {}; + + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { + + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + + output.metadata = { + version: 4.6, + type: 'Object', + generator: 'Object3D.toJSON' + }; + + } + + // standard Object3D serialization + + const object = {}; + + object.uuid = this.uuid; + object.type = this.type; + + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData; + + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + + // object specific properties + + if ( this.isInstancedMesh ) { + + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); + + } + + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); + + } + + return element.uuid; + + } + + if ( this.isScene ) { + + if ( this.background ) { + + if ( this.background.isColor ) { + + object.background = this.background.toJSON(); + + } else if ( this.background.isTexture ) { + + object.background = this.background.toJSON( meta ).uuid; + + } + + } + + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { + + object.environment = this.environment.toJSON( meta ).uuid; + + } + + } else if ( this.isMesh || this.isLine || this.isPoints ) { + + object.geometry = serialize( meta.geometries, this.geometry ); + + const parameters = this.geometry.parameters; + + if ( parameters !== undefined && parameters.shapes !== undefined ) { + + const shapes = parameters.shapes; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + serialize( meta.shapes, shape ); + + } + + } else { + + serialize( meta.shapes, shapes ); + + } + + } + + } + + if ( this.isSkinnedMesh ) { + + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + + if ( this.skeleton !== undefined ) { + + serialize( meta.skeletons, this.skeleton ); + + object.skeleton = this.skeleton.uuid; + + } + + } + + if ( this.material !== undefined ) { + + if ( Array.isArray( this.material ) ) { + + const uuids = []; + + for ( let i = 0, l = this.material.length; i < l; i ++ ) { + + uuids.push( serialize( meta.materials, this.material[ i ] ) ); + + } + + object.material = uuids; + + } else { + + object.material = serialize( meta.materials, this.material ); + + } + + } + + // + + if ( this.children.length > 0 ) { + + object.children = []; + + for ( let i = 0; i < this.children.length; i ++ ) { + + object.children.push( this.children[ i ].toJSON( meta ).object ); + + } + + } + + // + + if ( this.animations.length > 0 ) { + + object.animations = []; + + for ( let i = 0; i < this.animations.length; i ++ ) { + + const animation = this.animations[ i ]; + + object.animations.push( serialize( meta.animations, animation ) ); + + } + + } + + if ( isRootObject ) { + + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); + + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; + + } + + output.object = object; + + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { + + const values = []; + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + } + + clone( recursive ) { + + return new this.constructor().copy( this, recursive ); + + } + + copy( source, recursive = true ) { + + this.name = source.name; + + this.up.copy( source.up ); + + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); + + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + + this.layers.mask = source.layers.mask; + this.visible = source.visible; + + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + + this.animations = source.animations.slice(); + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { + + for ( let i = 0; i < source.children.length; i ++ ) { + + const child = source.children[ i ]; + this.add( child.clone() ); + + } + + } + + return this; + + } + +} + +Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + +let _id$1 = 0; + +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$3 = /*@__PURE__*/ new Vector3(); + +class BufferGeometry extends EventDispatcher { + + constructor() { + + super(); + + this.isBufferGeometry = true; + + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'BufferGeometry'; + + this.index = null; + this.attributes = {}; + + this.morphAttributes = {}; + this.morphTargetsRelative = false; + + this.groups = []; + + this.boundingBox = null; + this.boundingSphere = null; + + this.drawRange = { start: 0, count: Infinity }; + + this.userData = {}; + + } + + getIndex() { + + return this.index; + + } + + setIndex( index ) { + + if ( Array.isArray( index ) ) { + + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; + + } + + return this; + + } + + getAttribute( name ) { + + return this.attributes[ name ]; + + } + + setAttribute( name, attribute ) { + + this.attributes[ name ] = attribute; + + return this; + + } + + deleteAttribute( name ) { + + delete this.attributes[ name ]; + + return this; + + } + + hasAttribute( name ) { + + return this.attributes[ name ] !== undefined; + + } + + addGroup( start, count, materialIndex = 0 ) { + + this.groups.push( { + + start: start, + count: count, + materialIndex: materialIndex + + } ); + + } + + clearGroups() { + + this.groups = []; + + } + + setDrawRange( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; + + } + + applyMatrix4( matrix ) { + + const position = this.attributes.position; + + if ( position !== undefined ) { + + position.applyMatrix4( matrix ); + + position.needsUpdate = true; + + } + + const normal = this.attributes.normal; + + if ( normal !== undefined ) { + + const normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + normal.applyNormalMatrix( normalMatrix ); + + normal.needsUpdate = true; + + } + + const tangent = this.attributes.tangent; + + if ( tangent !== undefined ) { + + tangent.transformDirection( matrix ); + + tangent.needsUpdate = true; + + } + + if ( this.boundingBox !== null ) { + + this.computeBoundingBox(); + + } + + if ( this.boundingSphere !== null ) { + + this.computeBoundingSphere(); + + } + + return this; + + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateX( angle ) { + + // rotate geometry around world x-axis + + _m1.makeRotationX( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateY( angle ) { + + // rotate geometry around world y-axis + + _m1.makeRotationY( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateZ( angle ) { + + // rotate geometry around world z-axis + + _m1.makeRotationZ( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + translate( x, y, z ) { + + // translate geometry + + _m1.makeTranslation( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + scale( x, y, z ) { + + // scale geometry + + _m1.makeScale( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + lookAt( vector ) { + + _obj.lookAt( vector ); + + _obj.updateMatrix(); + + this.applyMatrix4( _obj.matrix ); + + return this; + + } + + center() { + + this.computeBoundingBox(); + + this.boundingBox.getCenter( _offset ).negate(); + + this.translate( _offset.x, _offset.y, _offset.z ); + + return this; + + } + + setFromPoints( points ) { + + const position = []; + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + const point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } + + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + return this; + + } + + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingBox.set( + new Vector3( - Infinity, - Infinity, - Infinity ), + new Vector3( + Infinity, + Infinity, + Infinity ) + ); + + return; + + } + + if ( position !== undefined ) { + + this.boundingBox.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _box.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$3.addVectors( this.boundingBox.min, _box.min ); + this.boundingBox.expandByPoint( _vector$3 ); + + _vector$3.addVectors( this.boundingBox.max, _box.max ); + this.boundingBox.expandByPoint( _vector$3 ); + + } else { + + this.boundingBox.expandByPoint( _box.min ); + this.boundingBox.expandByPoint( _box.max ); + + } + + } + + } + + } else { + + this.boundingBox.makeEmpty(); + + } + + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingSphere.set( new Vector3(), Infinity ); + + return; + + } + + if ( position ) { + + // first, find the center of the bounding sphere + + const center = this.boundingSphere.center; + + _box.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$3.addVectors( _box.min, _boxMorphTargets.min ); + _box.expandByPoint( _vector$3 ); + + _vector$3.addVectors( _box.max, _boxMorphTargets.max ); + _box.expandByPoint( _vector$3 ); + + } else { + + _box.expandByPoint( _boxMorphTargets.min ); + _box.expandByPoint( _boxMorphTargets.max ); + + } + + } + + } + + _box.getCenter( center ); + + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + + let maxRadiusSq = 0; + + for ( let i = 0, il = position.count; i < il; i ++ ) { + + _vector$3.fromBufferAttribute( position, i ); + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$3 ) ); + + } + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + const morphTargetsRelative = this.morphTargetsRelative; + + for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + + _vector$3.fromBufferAttribute( morphAttribute, j ); + + if ( morphTargetsRelative ) { + + _offset.fromBufferAttribute( position, j ); + _vector$3.add( _offset ); + + } + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$3 ) ); + + } + + } + + } + + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + + if ( isNaN( this.boundingSphere.radius ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + } + + computeTangents() { + + const index = this.index; + const attributes = this.attributes; + + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) + + if ( index === null || + attributes.position === undefined || + attributes.normal === undefined || + attributes.uv === undefined ) { + + console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' ); + return; + + } + + const indices = index.array; + const positions = attributes.position.array; + const normals = attributes.normal.array; + const uvs = attributes.uv.array; + + const nVertices = positions.length / 3; + + if ( this.hasAttribute( 'tangent' ) === false ) { + + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + + } + + const tangents = this.getAttribute( 'tangent' ).array; + + const tan1 = [], tan2 = []; + + for ( let i = 0; i < nVertices; i ++ ) { + + tan1[ i ] = new Vector3(); + tan2[ i ] = new Vector3(); + + } + + const vA = new Vector3(), + vB = new Vector3(), + vC = new Vector3(), + + uvA = new Vector2(), + uvB = new Vector2(), + uvC = new Vector2(), + + sdir = new Vector3(), + tdir = new Vector3(); + + function handleTriangle( a, b, c ) { + + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); + + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); + + vB.sub( vA ); + vC.sub( vA ); + + uvB.sub( uvA ); + uvC.sub( uvA ); + + const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); + + // silently ignore degenerate uv triangles having coincident or colinear vertices + + if ( ! isFinite( r ) ) return; + + sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); + tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); + + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); + + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); + + } + + let groups = this.groups; + + if ( groups.length === 0 ) { + + groups = [ { + start: 0, + count: indices.length + } ]; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleTriangle( + indices[ j + 0 ], + indices[ j + 1 ], + indices[ j + 2 ] + ); + + } + + } + + const tmp = new Vector3(), tmp2 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + + function handleVertex( v ) { + + n.fromArray( normals, v * 3 ); + n2.copy( n ); + + const t = tan1[ v ]; + + // Gram-Schmidt orthogonalize + + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + + // Calculate handedness + + tmp2.crossVectors( n2, t ); + const test = tmp2.dot( tan2[ v ] ); + const w = ( test < 0.0 ) ? - 1.0 : 1.0; + + tangents[ v * 4 ] = tmp.x; + tangents[ v * 4 + 1 ] = tmp.y; + tangents[ v * 4 + 2 ] = tmp.z; + tangents[ v * 4 + 3 ] = w; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleVertex( indices[ j + 0 ] ); + handleVertex( indices[ j + 1 ] ); + handleVertex( indices[ j + 2 ] ); + + } + + } + + } + + computeVertexNormals() { + + const index = this.index; + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute !== undefined ) { + + let normalAttribute = this.getAttribute( 'normal' ); + + if ( normalAttribute === undefined ) { + + normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 ); + this.setAttribute( 'normal', normalAttribute ); + + } else { + + // reset existing normals to zero + + for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) { + + normalAttribute.setXYZ( i, 0, 0, 0 ); + + } + + } + + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + + // indexed elements + + if ( index ) { + + for ( let i = 0, il = index.count; i < il; i += 3 ) { + + const vA = index.getX( i + 0 ); + const vB = index.getX( i + 1 ); + const vC = index.getX( i + 2 ); + + pA.fromBufferAttribute( positionAttribute, vA ); + pB.fromBufferAttribute( positionAttribute, vB ); + pC.fromBufferAttribute( positionAttribute, vC ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + nA.fromBufferAttribute( normalAttribute, vA ); + nB.fromBufferAttribute( normalAttribute, vB ); + nC.fromBufferAttribute( normalAttribute, vC ); + + nA.add( cb ); + nB.add( cb ); + nC.add( cb ); + + normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z ); + normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z ); + normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z ); + + } + + } else { + + // non-indexed elements (unconnected triangle soup) + + for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) { + + pA.fromBufferAttribute( positionAttribute, i + 0 ); + pB.fromBufferAttribute( positionAttribute, i + 1 ); + pC.fromBufferAttribute( positionAttribute, i + 2 ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z ); + + } + + } + + this.normalizeNormals(); + + normalAttribute.needsUpdate = true; + + } + + } + + normalizeNormals() { + + const normals = this.attributes.normal; + + for ( let i = 0, il = normals.count; i < il; i ++ ) { + + _vector$3.fromBufferAttribute( normals, i ); + + _vector$3.normalize(); + + normals.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + + } + + } + + toNonIndexed() { + + function convertBufferAttribute( attribute, indices ) { + + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array2 = new array.constructor( indices.length * itemSize ); + + let index = 0, index2 = 0; + + for ( let i = 0, l = indices.length; i < l; i ++ ) { + + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } + + for ( let j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + return new BufferAttribute( array2, itemSize, normalized ); + + } + + // + + if ( this.index === null ) { + + console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' ); + return this; + + } + + const geometry2 = new BufferGeometry(); + + const indices = this.index.array; + const attributes = this.attributes; + + // attributes + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + geometry2.setAttribute( name, newAttribute ); + + } + + // morph attributes + + const morphAttributes = this.morphAttributes; + + for ( const name in morphAttributes ) { + + const morphArray = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const attribute = morphAttribute[ i ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + morphArray.push( newAttribute ); + + } + + geometry2.morphAttributes[ name ] = morphArray; + + } + + geometry2.morphTargetsRelative = this.morphTargetsRelative; + + // groups + + const groups = this.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); + + } + + return geometry2; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.6, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; + + // standard BufferGeometry serialization + + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + if ( this.parameters !== undefined ) { + + const parameters = this.parameters; + + for ( const key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + + } + + return data; + + } + + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + + data.data = { attributes: {} }; + + const index = this.index; + + if ( index !== null ) { + + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; + + } + + const attributes = this.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + + data.data.attributes[ key ] = attribute.toJSON( data.data ); + + } + + const morphAttributes = {}; + let hasMorphAttributes = false; + + for ( const key in this.morphAttributes ) { + + const attributeArray = this.morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + + array.push( attribute.toJSON( data.data ) ); + + } + + if ( array.length > 0 ) { + + morphAttributes[ key ] = array; + + hasMorphAttributes = true; + + } + + } + + if ( hasMorphAttributes ) { + + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + + } + + const groups = this.groups; + + if ( groups.length > 0 ) { + + data.data.groups = JSON.parse( JSON.stringify( groups ) ); + + } + + const boundingSphere = this.boundingSphere; + + if ( boundingSphere !== null ) { + + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + // reset + + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + + // used for storing cloned, shared data + + const data = {}; + + // name + + this.name = source.name; + + // index + + const index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone( data ) ); + + } + + // attributes + + const attributes = source.attributes; + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone( data ) ); + + } + + // morph attributes + + const morphAttributes = source.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone( data ) ); + + } + + this.morphAttributes[ name ] = array; + + } + + this.morphTargetsRelative = source.morphTargetsRelative; + + // groups + + const groups = source.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); + + } + + // bounding box + + const boundingBox = source.boundingBox; + + if ( boundingBox !== null ) { + + this.boundingBox = boundingBox.clone(); + + } + + // bounding sphere + + const boundingSphere = source.boundingSphere; + + if ( boundingSphere !== null ) { + + this.boundingSphere = boundingSphere.clone(); + + } + + // draw range + + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + + // user data + + this.userData = source.userData; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class BoxGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + this.type = 'BoxGeometry'; + + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; + + const scope = this; + + // segments + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let numberOfVertices = 0; + let groupStart = 0; + + // build each side of the box geometry + + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + let vertexCounter = 0; + let groupCount = 0; + + const vector = new Vector3(); + + // generate vertices, normals and uvs + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segmentHeight - heightHalf; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segmentWidth - widthHalf; + + // set values to correct vector component + + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; + + // now apply vector to vertex buffer + + vertices.push( vector.x, vector.y, vector.z ); + + // set values to correct vector component + + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; + + // now apply vector to normal buffer + + normals.push( vector.x, vector.y, vector.z ); + + // uvs + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + // counters + + vertexCounter += 1; + + } + + } + + // indices + + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // increase counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, materialIndex ); + + // calculate new start value for groups + + groupStart += groupCount; + + // update total number of vertices + + numberOfVertices += vertexCounter; + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + +} + +class PlaneGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { + + super(); + + this.type = 'PlaneGeometry'; + + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + + const width_half = width / 2; + const height_half = height / 2; + + const gridX = Math.floor( widthSegments ); + const gridY = Math.floor( heightSegments ); + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + const segment_width = width / gridX; + const segment_height = height / gridY; + + // + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segment_height - height_half; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segment_width - width_half; + + vertices.push( x, - y, 0 ); + + normals.push( 0, 0, 1 ); + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + } + + } + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = ix + gridX1 * iy; + const b = ix + gridX1 * ( iy + 1 ); + const c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = ( ix + 1 ) + gridX1 * iy; + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + +} + +let materialId = 0; + +class Material extends EventDispatcher { + + constructor() { + + super(); + + this.isMaterial = true; + + Object.defineProperty( this, 'id', { value: materialId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Material'; + + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + + this.shadowSide = null; + + this.colorWrite = true; + + this.precision = null; // override the renderer's default precision for this material + + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + + this.dithering = false; + + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + + this.visible = true; + + this.toneMapped = true; + + this.userData = {}; + + this.version = 0; + + this._alphaTest = 0; + + } + + get alphaTest() { + + return this._alphaTest; + + } + + set alphaTest( value ) { + + if ( this._alphaTest > 0 !== value > 0 ) { + + this.version ++; + + } + + this._alphaTest = value; + + } + + onBuild( /* shaderobject, renderer */ ) {} + + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} + + onBeforeCompile( /* shaderobject, renderer */ ) {} + + customProgramCacheKey() { + + return this.onBeforeCompile.toString(); + + } + + setValues( values ) { + + if ( values === undefined ) return; + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` ); + continue; + + } + + if ( currentValue && currentValue.isColor ) { + + currentValue.set( newValue ); + + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( isRootObject ) { + + meta = { + textures: {}, + images: {} + }; + + } + + const data = { + metadata: { + version: 4.6, + type: 'Material', + generator: 'Material.toJSON' + } + }; + + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; + + if ( this.name !== '' ) data.name = this.name; + + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); + + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; + + if ( this.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + + } + + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + + if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy; + if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation; + + if ( this.anisotropyMap && this.anisotropyMap.isTexture ) { + + data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid; + + } + + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; + if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + + if ( this.lightMap && this.lightMap.isTexture ) { + + data.lightMap = this.lightMap.toJSON( meta ).uuid; + data.lightMapIntensity = this.lightMapIntensity; + + } + + if ( this.aoMap && this.aoMap.isTexture ) { + + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; + + } + + if ( this.bumpMap && this.bumpMap.isTexture ) { + + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; + + } + + if ( this.normalMap && this.normalMap.isTexture ) { + + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + + } + + if ( this.displacementMap && this.displacementMap.isTexture ) { + + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + + } + + if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + + if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; + + if ( this.envMap && this.envMap.isTexture ) { + + data.envMap = this.envMap.toJSON( meta ).uuid; + + if ( this.combine !== undefined ) data.combine = this.combine; + + } + + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; + + if ( this.gradientMap && this.gradientMap.isTexture ) { + + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + + } + + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); + + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; + + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; + + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; + + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; + + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; + + if ( this.dithering === true ) data.dithering = true; + + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaHash === true ) data.alphaHash = this.alphaHash; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass; + + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + + if ( this.flatShading === true ) data.flatShading = this.flatShading; + + if ( this.visible === false ) data.visible = false; + + if ( this.toneMapped === false ) data.toneMapped = false; + + if ( this.fog === false ) data.fog = false; + + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + // TODO: Copied from Object3D.toJSON + + function extractFromCache( cache ) { + + const values = []; + + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + if ( isRootObject ) { + + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + + if ( srcPlanes !== null ) { + + const n = srcPlanes.length; + dstPlanes = new Array( n ); + + for ( let i = 0; i !== n; ++ i ) { + + dstPlanes[ i ] = srcPlanes[ i ].clone(); + + } + + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +/** + * Uniform Utilities + */ + +function cloneUniforms( src ) { + + const dst = {}; + + for ( const u in src ) { + + dst[ u ] = {}; + + for ( const p in src[ u ] ) { + + const property = src[ u ][ p ]; + + if ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ) { + + if ( property.isRenderTargetTexture ) { + + console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' ); + dst[ u ][ p ] = null; + + } else { + + dst[ u ][ p ] = property.clone(); + + } + + } else if ( Array.isArray( property ) ) { + + dst[ u ][ p ] = property.slice(); + + } else { + + dst[ u ][ p ] = property; + + } + + } + + } + + return dst; + +} + +function mergeUniforms( uniforms ) { + + const merged = {}; + + for ( let u = 0; u < uniforms.length; u ++ ) { + + const tmp = cloneUniforms( uniforms[ u ] ); + + for ( const p in tmp ) { + + merged[ p ] = tmp[ p ]; + + } + + } + + return merged; + +} + +function cloneUniformsGroups( src ) { + + const dst = []; + + for ( let u = 0; u < src.length; u ++ ) { + + dst.push( src[ u ].clone() ); + + } + + return dst; + +} + +function getUnlitUniformColorSpace( renderer ) { + + if ( renderer.getRenderTarget() === null ) { + + // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398 + return renderer.outputColorSpace; + + } + + return LinearSRGBColorSpace; + +} + +// Legacy + +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + +class ShaderMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShaderMaterial = true; + + this.type = 'ShaderMaterial'; + + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + + this.linewidth = 1; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes + + this.forceSinglePass = true; + + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; + + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv1': [ 0, 0 ] + }; + + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + + this.glslVersion = null; + + if ( parameters !== undefined ) { + + this.setValues( parameters ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); + + this.defines = Object.assign( {}, source.defines ); + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + + this.extensions = Object.assign( {}, source.extensions ); + + this.glslVersion = source.glslVersion; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.glslVersion = this.glslVersion; + data.uniforms = {}; + + for ( const name in this.uniforms ) { + + const uniform = this.uniforms[ name ]; + const value = uniform.value; + + if ( value && value.isTexture ) { + + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; + + } else if ( value && value.isColor ) { + + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; + + } else if ( value && value.isVector2 ) { + + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; + + } else if ( value && value.isVector3 ) { + + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; + + } else if ( value && value.isVector4 ) { + + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; + + } else if ( value && value.isMatrix3 ) { + + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; + + } else if ( value && value.isMatrix4 ) { + + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; + + } else { + + data.uniforms[ name ] = { + value: value + }; + + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + + } + + } + + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + data.lights = this.lights; + data.clipping = this.clipping; + + const extensions = {}; + + for ( const key in this.extensions ) { + + if ( this.extensions[ key ] === true ) extensions[ key ] = true; + + } + + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + + return data; + + } + +} + +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); + +const _edge1 = /*@__PURE__*/ new Vector3(); +const _edge2 = /*@__PURE__*/ new Vector3(); +const _normal$1 = /*@__PURE__*/ new Vector3(); + +class Ray { + + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + + this.origin = origin; + this.direction = direction; + + } + + set( origin, direction ) { + + this.origin.copy( origin ); + this.direction.copy( direction ); + + return this; + + } + + copy( ray ) { + + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); + + return this; + + } + + at( t, target ) { + + return target.copy( this.origin ).addScaledVector( this.direction, t ); + + } + + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); + + return this; + + } + + recast( t ) { + + this.origin.copy( this.at( t, _vector$2 ) ); + + return this; + + } + + closestPointToPoint( point, target ) { + + target.subVectors( point, this.origin ); + + const directionDistance = target.dot( this.direction ); + + if ( directionDistance < 0 ) { + + return target.copy( this.origin ); + + } + + return target.copy( this.origin ).addScaledVector( this.direction, directionDistance ); + + } + + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); + + } + + distanceSqToPoint( point ) { + + const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction ); + + // point behind the ray + + if ( directionDistance < 0 ) { + + return this.origin.distanceToSquared( point ); + + } + + _vector$2.copy( this.origin ).addScaledVector( this.direction, directionDistance ); + + return _vector$2.distanceToSquared( point ); + + } + + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment + + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); + + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; + + if ( det > 0 ) { + + // The ray and segment are not parallel. + + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { + + if ( s1 >= - extDet ) { + + if ( s1 <= extDet ) { + + // region 0 + // Minimum at interior points of ray and segment. + + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + + } else { + + // region 1 + + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + if ( s1 <= - extDet ) { + + // region 4 + + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } else if ( s1 <= extDet ) { + + // region 3 + + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; + + } else { + + // region 2 + + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } + + } else { + + // Ray and segment are parallel. + + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + if ( optionalPointOnRay ) { + + optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 ); + + } + + if ( optionalPointOnSegment ) { + + optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 ); + + } + + return sqrDist; + + } + + intersectSphere( sphere, target ) { + + _vector$2.subVectors( sphere.center, this.origin ); + const tca = _vector$2.dot( this.direction ); + const d2 = _vector$2.dot( _vector$2 ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + const thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + const t1 = tca + thc; + + // test to see if t1 is behind the ray - if so, return null + if ( t1 < 0 ) return null; + + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); + + } + + intersectsSphere( sphere ) { + + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + distanceToPlane( plane ) { + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { + + return 0; + + } + + // Null is preferable to undefined since undefined means.... it is undefined + + return null; + + } + + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + + // Return if the ray never intersects the plane + + return t >= 0 ? t : null; + + } + + intersectPlane( plane, target ) { + + const t = this.distanceToPlane( plane ); + + if ( t === null ) { + + return null; + + } + + return this.at( t, target ); + + } + + intersectsPlane( plane ) { + + // check if the ray lies on the plane first + + const distToPoint = plane.distanceToPoint( this.origin ); + + if ( distToPoint === 0 ) { + + return true; + + } + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator * distToPoint < 0 ) { + + return true; + + } + + // ray origin is behind the plane (and is pointing behind it) + + return false; + + } + + intersectBox( box, target ) { + + let tmin, tmax, tymin, tymax, tzmin, tzmax; + + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; + + const origin = this.origin; + + if ( invdirx >= 0 ) { + + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; + + } else { + + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + + } + + if ( invdiry >= 0 ) { + + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; + + } else { + + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; + + } + + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + + if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin; + + if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; + + } else { + + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + + } + + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + + //return point closest to the ray (positive side) + + if ( tmax < 0 ) return null; + + return this.at( tmin >= 0 ? tmin : tmax, target ); + + } + + intersectsBox( box ) { + + return this.intersectBox( box, _vector$2 ) !== null; + + } + + intersectTriangle( a, b, c, backfaceCulling, target ) { + + // Compute the offset origin, edges, and normal. + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.crossVectors( _edge1, _edge2 ); + + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + let DdN = this.direction.dot( _normal$1 ); + let sign; + + if ( DdN > 0 ) { + + if ( backfaceCulling ) return null; + sign = 1; + + } else if ( DdN < 0 ) { + + sign = - 1; + DdN = - DdN; + + } else { + + return null; + + } + + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { + + return null; + + } + + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { + + return null; + + } + + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { + + return null; + + } + + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); + + // t < 0, no intersection + if ( QdN < 0 ) { + + return null; + + } + + // Ray intersects triangle. + return this.at( QdN / DdN, target ); + + } + + applyMatrix4( matrix4 ) { + + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); + + return this; + + } + + equals( ray ) { + + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); + +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); + +let warnedGetUV = false; + +class Triangle { + + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + + this.a = a; + this.b = b; + this.c = c; + + } + + static getNormal( a, b, c, target ) { + + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); + + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { + + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + + } + + return target.set( 0, 0, 0 ); + + } + + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { + + _v0$1.subVectors( c, a ); + _v1$2.subVectors( b, a ); + _v2$1.subVectors( point, a ); + + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$2 ); + const dot02 = _v0$1.dot( _v2$1 ); + const dot11 = _v1$2.dot( _v1$2 ); + const dot12 = _v1$2.dot( _v2$1 ); + + const denom = ( dot00 * dot11 - dot01 * dot01 ); + + // collinear or singular triangle + if ( denom === 0 ) { + + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return target.set( - 2, - 1, - 1 ); + + } + + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); + + } + + static containsPoint( point, a, b, c ) { + + this.getBarycoord( point, a, b, c, _v3 ); + + return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); + + } + + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151 + + if ( warnedGetUV === false ) { + + console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' ); + + warnedGetUV = true; + + } + + return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target ); + + } + + static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) { + + this.getBarycoord( point, p1, p2, p3, _v3 ); + + target.setScalar( 0 ); + target.addScaledVector( v1, _v3.x ); + target.addScaledVector( v2, _v3.y ); + target.addScaledVector( v3, _v3.z ); + + return target; + + } + + static isFrontFacing( a, b, c, direction ) { + + _v0$1.subVectors( c, b ); + _v1$2.subVectors( a, b ); + + // strictly front facing + return ( _v0$1.cross( _v1$2 ).dot( direction ) < 0 ) ? true : false; + + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); + + return this; + + } + + setFromPointsAndIndices( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; + + } + + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { + + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( triangle ) { + + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; + + } + + getArea() { + + _v0$1.subVectors( this.c, this.b ); + _v1$2.subVectors( this.a, this.b ); + + return _v0$1.cross( _v1$2 ).length() * 0.5; + + } + + getMidpoint( target ) { + + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + + } + + getNormal( target ) { + + return Triangle.getNormal( this.a, this.b, this.c, target ); + + } + + getPlane( target ) { + + return target.setFromCoplanarPoints( this.a, this.b, this.c ); + + } + + getBarycoord( point, target ) { + + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + + } + + getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151 + + if ( warnedGetUV === false ) { + + console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' ); + + warnedGetUV = true; + + } + + return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + + } + + getInterpolation( point, v1, v2, v3, target ) { + + return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target ); + + } + + containsPoint( point ) { + + return Triangle.containsPoint( point, this.a, this.b, this.c ); + + } + + isFrontFacing( direction ) { + + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + + } + + intersectsBox( box ) { + + return box.intersectsTriangle( this ); + + } + + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; + + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. + + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { + + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); + + } + + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { + + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } + + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); + + } + + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { + + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } + + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); + + } + + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + + } + + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; + + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + + } + + equals( triangle ) { + + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + + } + +} + +class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4(); +const _ray$4 = /*@__PURE__*/ new Ray(); +const _sphere$4 = /*@__PURE__*/ new Sphere(); +const _sphereHitAt = /*@__PURE__*/ new Vector3(); + +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); + +const _tempA = /*@__PURE__*/ new Vector3(); +const _morphA = /*@__PURE__*/ new Vector3(); + +const _uvA$1 = /*@__PURE__*/ new Vector2(); +const _uvB$1 = /*@__PURE__*/ new Vector2(); +const _uvC$1 = /*@__PURE__*/ new Vector2(); + +const _normalA = /*@__PURE__*/ new Vector3(); +const _normalB = /*@__PURE__*/ new Vector3(); +const _normalC = /*@__PURE__*/ new Vector3(); + +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); + +class Mesh extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { + + super(); + + this.isMesh = true; + + this.type = 'Mesh'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.morphTargetInfluences !== undefined ) { + + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + + } + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + getVertexPosition( index, target ) { + + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + + target.fromBufferAttribute( position, index ); + + const morphInfluences = this.morphTargetInfluences; + + if ( morphPosition && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + + for ( let i = 0, il = morphPosition.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morphAttribute = morphPosition[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morphAttribute, index ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( target ), influence ); + + } + + } + + target.add( _morphA ); + + } + + return target; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // test with bounding sphere in world space + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$4.copy( geometry.boundingSphere ); + _sphere$4.applyMatrix4( matrixWorld ); + + // check distance from ray origin to bounding sphere + + _ray$4.copy( raycaster.ray ).recast( raycaster.near ); + + if ( _sphere$4.containsPoint( _ray$4.origin ) === false ) { + + if ( _ray$4.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return; + + if ( _ray$4.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return; + + } + + // convert ray to local space of mesh + + _inverseMatrix$3.copy( matrixWorld ).invert(); + _ray$4.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 ); + + // test with bounding box in local space + + if ( geometry.boundingBox !== null ) { + + if ( _ray$4.intersectsBox( geometry.boundingBox ) === false ) return; + + } + + // test for intersections with geometry + + this._computeIntersections( raycaster, intersects, _ray$4 ); + + } + + _computeIntersections( raycaster, intersects, rayLocalSpace ) { + + let intersection; + + const geometry = this.geometry; + const material = this.material; + + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); + + intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } else if ( position !== undefined ) { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = j; + const b = j + 1; + const c = j + 2; + + intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = i; + const b = i + 1; + const c = i + 2; + + intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } + + } + +} + +function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { + + let intersect; + + if ( material.side === BackSide ) { + + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + + } else { + + intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point ); + + } + + if ( intersect === null ) return null; + + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + + if ( distance < raycaster.near || distance > raycaster.far ) return null; + + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; + +} + +function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) { + + object.getVertexPosition( a, _vA$1 ); + object.getVertexPosition( b, _vB$1 ); + object.getVertexPosition( c, _vC$1 ); + + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); + + if ( intersection ) { + + if ( uv ) { + + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); + + intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + if ( uv1 ) { + + _uvA$1.fromBufferAttribute( uv1, a ); + _uvB$1.fromBufferAttribute( uv1, b ); + _uvC$1.fromBufferAttribute( uv1, c ); + + intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + intersection.uv2 = intersection.uv1; // @deprecated, r152 + + } + + if ( normal ) { + + _normalA.fromBufferAttribute( normal, a ); + _normalB.fromBufferAttribute( normal, b ); + _normalC.fromBufferAttribute( normal, c ); + + intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() ); + + if ( intersection.normal.dot( ray.direction ) > 0 ) { + + intersection.normal.multiplyScalar( - 1 ); + + } + + } + + const face = { + a: a, + b: b, + c: c, + normal: new Vector3(), + materialIndex: 0 + }; + + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); + + intersection.face = face; + + } + + return intersection; + +} + +var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; + +var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif"; + +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; + +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + +var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif"; + +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + +var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; + +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; + +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; + +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + +var colorspace_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; + +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + +var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif"; + +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tanisotropyV /= material.anisotropy;\n\tmaterial.anisotropy = saturate( material.anisotropy );\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x - tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x + tbn[ 0 ] * anisotropyV.y;\n#endif"; + +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometry.viewDir, geometry.normal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + +var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + +var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + +var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + +var map_fragment = "#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, vMapUv );\n#endif"; + +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + +var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; + +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; + +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + +var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; + +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif"; + +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}"; + +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + +var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; + +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + +var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; + +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif"; + +var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; + +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + +const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + +const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; + +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const ShaderChunk = { + alphahash_fragment: alphahash_fragment, + alphahash_pars_fragment: alphahash_pars_fragment, + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + colorspace_fragment: colorspace_fragment, + colorspace_pars_fragment: colorspace_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + opaque_fragment: opaque_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + worldpos_vertex: worldpos_vertex, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; + +/** + * Uniforms library for shared webgl shaders + */ + +const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + specularMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + envmap: { + + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + emissivemap: { + + emissiveMap: { value: null }, + emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + metalnessmap: { + + metalnessMap: { value: null }, + metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + roughnessmap: { + + roughnessMap: { value: null }, + roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 } + + } + +}; + +const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distanceRGBA: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + +}; + +ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + anisotropyVector: { value: /*@__PURE__*/ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + +}; + +const _rgb = { r: 0, b: 0, g: 0 }; + +function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function render( renderList, scene ) { + + let forceClear = false; + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background ); + + } + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + const xr = renderer.xr; + const environmentBlendMode = xr.getEnvironmentBlendMode(); + + switch ( environmentBlendMode ) { + + case 'opaque': + forceClear = true; + break; + + case 'additive': + state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha ); + forceClear = true; + break; + + case 'alpha-blend': + state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha ); + forceClear = true; + break; + + } + + if ( renderer.autoClear || forceClear ) { + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render + + }; + +} + +function WebGLBindingStates( gl, extensions, attributes, capabilities ) { + + const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + + const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' ); + const vaoAvailable = capabilities.isWebGL2 || extension !== null; + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + if ( vaoAvailable ) { + + const state = getBindingState( geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + } else { + + const wireframe = ( material.wireframe === true ); + + if ( currentState.geometry !== geometry.id || + currentState.program !== program.id || + currentState.wireframe !== wireframe ) { + + currentState.geometry = geometry.id; + currentState.program = program.id; + currentState.wireframe = wireframe; + + updateBuffers = true; + + } + + } + + if ( index !== null ) { + + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + if ( capabilities.isWebGL2 ) return gl.createVertexArray(); + + return extension.createVertexArrayOES(); + + } + + function bindVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao ); + + return extension.bindVertexArrayOES( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao ); + + return extension.deleteVertexArrayOES( vao ); + + } + + function getBindingState( geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let programMap = bindingStates[ geometry.id ]; + + if ( programMap === undefined ) { + + programMap = {}; + bindingStates[ geometry.id ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + + extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) { + + if ( integer === true ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { + + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return; + + } + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + // check for integer attributes (WebGL 2 only) + + const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) ); + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement, + integer + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement, + integer + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const programMap = bindingStates[ geometry.id ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + +} + +function WebGLBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawArraysInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawArraysInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLCapabilities( gl, extensions, parameters ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext'; + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + + const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + + const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + + const vertexTextures = maxVertexTextures > 0; + const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' ); + const floatVertexTextures = vertexTextures && floatFragmentTextures; + + const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0; + + return { + + isWebGL2: isWebGL2, + + drawBuffers: drawBuffers, + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures, + + maxSamples: maxSamples + + }; + +} + +function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + +} + +class Camera extends Object3D { + + constructor() { + + super(); + + this.isCamera = true; + + this.type = 'Camera'; + + this.matrixWorldInverse = new Matrix4(); + + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + + this.coordinateSystem = WebGLCoordinateSystem; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); + + this.coordinateSystem = source.coordinateSystem; + + return this; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + super.updateWorldMatrix( updateParents, updateChildren ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class PerspectiveCamera extends Camera { + + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + this.fov = fov; + this.zoom = 1; + + this.near = near; + this.far = far; + this.focus = 10; + + this.aspect = aspect; + this.view = null; + + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + return this; + + } + + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const near = this.near; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = - 0.5 * width; + const view = this.view; + + if ( this.view !== null && this.view.enabled ) { + + const fullWidth = view.fullWidth, + fullHeight = view.fullHeight; + + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + + } + + const skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.fov = this.fov; + data.object.zoom = this.zoom; + + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + + data.object.aspect = this.aspect; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + + return data; + + } + +} + +const fov = - 90; // negative fov is not an error +const aspect = 1; + +class CubeCamera extends Object3D { + + constructor( near, far, renderTarget ) { + + super(); + + this.type = 'CubeCamera'; + + this.renderTarget = renderTarget; + this.coordinateSystem = null; + + const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + this.add( cameraPX ); + + const cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + this.add( cameraNX ); + + const cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + this.add( cameraPY ); + + const cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + this.add( cameraNY ); + + const cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + this.add( cameraPZ ); + + const cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + this.add( cameraNZ ); + + } + + updateCoordinateSystem() { + + const coordinateSystem = this.coordinateSystem; + + const cameras = this.children.concat(); + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras; + + for ( const camera of cameras ) this.remove( camera ); + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + cameraPX.up.set( 0, 1, 0 ); + cameraPX.lookAt( 1, 0, 0 ); + + cameraNX.up.set( 0, 1, 0 ); + cameraNX.lookAt( - 1, 0, 0 ); + + cameraPY.up.set( 0, 0, - 1 ); + cameraPY.lookAt( 0, 1, 0 ); + + cameraNY.up.set( 0, 0, 1 ); + cameraNY.lookAt( 0, - 1, 0 ); + + cameraPZ.up.set( 0, 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + + cameraNZ.up.set( 0, 1, 0 ); + cameraNZ.lookAt( 0, 0, - 1 ); + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( - 1, 0, 0 ); + + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( 1, 0, 0 ); + + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( 0, 1, 0 ); + + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( 0, - 1, 0 ); + + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( 0, 0, - 1 ); + + } else { + + throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem ); + + } + + for ( const camera of cameras ) { + + this.add( camera ); + + camera.updateMatrixWorld(); + + } + + } + + update( renderer, scene ) { + + if ( this.parent === null ) this.updateMatrixWorld(); + + const renderTarget = this.renderTarget; + + if ( this.coordinateSystem !== renderer.coordinateSystem ) { + + this.coordinateSystem = renderer.coordinateSystem; + + this.updateCoordinateSystem(); + + } + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; + + const currentRenderTarget = renderer.getRenderTarget(); + + const currentXrEnabled = renderer.xr.enabled; + + renderer.xr.enabled = false; + + const generateMipmaps = renderTarget.texture.generateMipmaps; + + renderTarget.texture.generateMipmaps = false; + + renderer.setRenderTarget( renderTarget, 0 ); + renderer.render( scene, cameraPX ); + + renderer.setRenderTarget( renderTarget, 1 ); + renderer.render( scene, cameraNX ); + + renderer.setRenderTarget( renderTarget, 2 ); + renderer.render( scene, cameraPY ); + + renderer.setRenderTarget( renderTarget, 3 ); + renderer.render( scene, cameraNY ); + + renderer.setRenderTarget( renderTarget, 4 ); + renderer.render( scene, cameraPZ ); + + renderTarget.texture.generateMipmaps = generateMipmaps; + + renderer.setRenderTarget( renderTarget, 5 ); + renderer.render( scene, cameraNZ ); + + renderer.setRenderTarget( currentRenderTarget ); + + renderer.xr.enabled = currentXrEnabled; + + renderTarget.texture.needsPMREMUpdate = true; + + } + +} + +class CubeTexture extends Texture { + + constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) { + + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + + super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ); + + this.isCubeTexture = true; + + this.flipY = false; + + } + + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + + constructor( size = 1, options = {} ) { + + super( size, size, options ); + + this.isWebGLCubeRenderTarget = true; + + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + if ( options.encoding !== undefined ) { + + // @deprecated, r152 + warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' ); + options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + + } + + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); + + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. + + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). + + this.texture.isRenderTargetTexture = true; + + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + } + + fromEquirectangularTexture( renderer, texture ) { + + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + + const shader = { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: /* glsl */` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + + fragmentShader: /* glsl */` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + + const geometry = new BoxGeometry( 5, 5, 5 ); + + const material = new ShaderMaterial( { + + name: 'CubemapFromEquirect', + + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + + } ); + + material.uniforms.tEquirect.value = texture; + + const mesh = new Mesh( geometry, material ); + + const currentMinFilter = texture.minFilter; + + // Avoid blurred poles + if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter; + + const camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, mesh ); + + texture.minFilter = currentMinFilter; + + mesh.geometry.dispose(); + mesh.material.dispose(); + + return this; + + } + + clear( renderer, color, depth, stencil ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + for ( let i = 0; i < 6; i ++ ) { + + renderer.setRenderTarget( this, i ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( currentRenderTarget ); + + } + +} + +function WebGLCubeMaps( renderer ) { + + let cubemaps = new WeakMap(); + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function get( texture ) { + + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubemaps.has( texture ) ) { + + const cubemap = cubemaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubemaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemap = cubemaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubemaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function dispose() { + + cubemaps = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class OrthographicCamera extends Camera { + + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + + super(); + + this.isOrthographicCamera = true; + + this.type = 'OrthographicCamera'; + + this.zoom = 1; + this.view = null; + + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + + this.near = near; + this.far = far; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + return this; + + } + + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + return data; + + } + +} + +const LOD_MIN = 4; + +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; + +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; + +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; + +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ + +class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._compileMaterial( this._blurMaterial ); + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + + _oldTarget = this._renderer.getRenderTarget(); + + this._setSize( 256 ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + + this._lodPlanes[ i ].dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); + + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); + + let useSolidColor = false; + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { + + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); + + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); + + } + + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); + + } + + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; + + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; + + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + + if ( samples > MAX_SAMPLES ) { + + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + + } + + const weights = []; + let sum = 0; + + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); + + if ( i === 0 ) { + + sum += weight; + + } else if ( i < samples ) { + + sum += 2 * weight; + + } + + } + + for ( let i = 0; i < weights.length; i ++ ) { + + weights[ i ] = weights[ i ] / sum; + + } + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + + if ( poleAxis ) { + + blurUniforms[ 'poleAxis' ].value = poleAxis; + + } + + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + + + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + +} + +function WebGLCubeUVMaps( renderer ) { + + let cubeUVmaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { + + texture.needsPMREMUpdate = false; + + let renderTarget = cubeUVmaps.get( texture ); + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( cubeUVmaps.has( texture ) ) { + + return cubeUVmaps.get( texture ).texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemapUV = cubeUVmaps.get( texture ); + + if ( cubemapUV !== undefined ) { + + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); + + } + + } + + function dispose() { + + cubeUVmaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + +} + +function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + let extension; + + switch ( name ) { + + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; + + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; + + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; + + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; + + default: + extension = gl.getExtension( name ); + + } + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function ( capabilities ) { + + if ( capabilities.isWebGL2 ) { + + getExtension( 'EXT_color_buffer_float' ); + + } else { + + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); + + } + + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + +} + +function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + for ( const name in geometry.morphAttributes ) { + + const array = geometry.morphAttributes[ name ]; + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + attributes.remove( array[ i ] ); + + } + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + + } + + // morph targets + + const morphAttributes = geometry.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = morphAttributes[ name ]; + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + attributes.update( array[ i ], gl.ARRAY_BUFFER ); + + } + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else if ( geometryPosition !== undefined ) { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + return; + + } + + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + +} + +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawElementsInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; + + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; + + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; + + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + + case gl.POINTS: + render.points += instanceCount * count; + break; + + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + +} + +class DataArrayTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + super( null ); + + this.isDataArrayTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +function numericalSort( a, b ) { + + return a[ 0 ] - b[ 0 ]; + +} + +function absNumericalSort( a, b ) { + + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + +} + +function WebGLMorphtargets( gl, capabilities, textures ) { + + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + const workInfluences = []; + + for ( let i = 0; i < 8; i ++ ) { + + workInfluences[ i ] = [ i, 0 ]; + + } + + function update( object, geometry, program ) { + + const objectInfluences = object.morphTargetInfluences; + + if ( capabilities.isWebGL2 === true ) { + + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + + } else { + + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + + const length = objectInfluences === undefined ? 0 : objectInfluences.length; + + let influences = influencesList[ geometry.id ]; + + if ( influences === undefined || influences.length !== length ) { + + // initialise list + + influences = []; + + for ( let i = 0; i < length; i ++ ) { + + influences[ i ] = [ i, 0 ]; + + } + + influencesList[ geometry.id ] = influences; + + } + + // Collect influences + + for ( let i = 0; i < length; i ++ ) { + + const influence = influences[ i ]; + + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; + + } + + influences.sort( absNumericalSort ); + + for ( let i = 0; i < 8; i ++ ) { + + if ( i < length && influences[ i ][ 1 ] ) { + + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + + } else { + + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; + + } + + } + + workInfluences.sort( numericalSort ); + + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < 8; i ++ ) { + + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; + + if ( index !== Number.MAX_SAFE_INTEGER && value ) { + + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + + } + + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + + } + + morphInfluences[ i ] = value; + morphInfluencesSum += value; + + } else { + + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + + geometry.deleteAttribute( 'morphTarget' + i ); + + } + + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + + geometry.deleteAttribute( 'morphNormal' + i ); + + } + + morphInfluences[ i ] = 0; + + } + + } + + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + + } + + } + + return { + + update: update + + }; + +} + +function WebGLObjects( gl, geometries, attributes, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + if ( updateMap.get( object ) !== frame ) { + + attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, gl.ARRAY_BUFFER ); + + } + + updateMap.set( object, frame ); + + } + + } + + if ( object.isSkinnedMesh ) { + + const skeleton = object.skeleton; + + if ( updateMap.get( skeleton ) !== frame ) { + + skeleton.update(); + + updateMap.set( skeleton, frame ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + +} + +class Data3DTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + super( null ); + + this.isData3DTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +/** + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + + +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + +// --- Utilities --- + +// Array Caches (provide typed arrays for temporary by size) + +const arrayCacheF32 = []; +const arrayCacheI32 = []; + +// Float32Array caches used for uploading Matrix uniforms + +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); + +// Flattening for arrays of vectors and matrices + +function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + +} + +function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + +} + +function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + +} + +// Texture unit allocation + +function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + +} + +// --- Setters --- + +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. + +// Single scalar + +function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single float vector (from flat array or THREE.VectorN) + +function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single matrix (from flat array or THREE.MatrixN) + +function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + +} + +// Single integer / boolean + +function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single integer / boolean vector (from flat array or THREE.VectorN) + +function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single unsigned integer + +function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single unsigned integer vector (from flat array or THREE.VectorN) + +function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + + +// Single texture (2D / Cube) + +function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2D( v || emptyTexture, unit ); + +} + +function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + +} + +function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + +} + +function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + +} + +// Helper to pick the right setter for the singular case + +function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + +} + + +// Array of scalars + +function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + +} + +// Array of vectors (from flat array or array of THREE.VectorN) + +function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + +} + +function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + +} + +function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + +} + +// Array of matrices (from flat array or array of THREE.MatrixN) + +function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + +} + +function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + +} + +function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + +} + +// Array of integer / boolean + +function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + +} + +// Array of integer / boolean vectors (from flat array) + +function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + +} + +function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + +} + +function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + +} + +// Array of unsigned integer + +function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + +} + +// Array of unsigned integer vectors (from flat array) + +function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + +} + +function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + +} + +function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + +} + + +// Array of textures (2D / 3D / Cube / 2DArray) + +function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + + } + +} + +function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + +} + +function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + +} + +function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + +} + + +// Helper to pick the right setter for a pure (bottom-level) array + +function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + +} + +// --- Uniform Classes --- + +class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + +} + +// --- Top-level --- + +// Parser - builds up the property tree from the path strings + +const RePathPart = /(\w+)(\])?(\[|\.)?/g; + +// extracts +// - the identifier (member name or array index) +// - followed by an optional right bracket (found when array index) +// - followed by an optional left bracket or dot (type of subscript) +// +// Note: These portions can be read in a non-overlapping fashion and +// allow straightforward parsing of the hierarchy that WebGL encodes +// in the uniform names. + +function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + +} + +function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + +} + +// Root Container + +class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + +} + +function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + +} + +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + +} + +function getEncodingComponents( colorSpace ) { + + switch ( colorSpace ) { + + case LinearSRGBColorSpace: + return [ 'Linear', '( value )' ]; + case SRGBColorSpace: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace ); + return [ 'Linear', '( value )' ]; + + } + +} + +function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS ); + const errors = gl.getShaderInfoLog( shader ).trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + +} + +function getTexelEncodingFunction( functionName, colorSpace ) { + + const components = getEncodingComponents( colorSpace ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + +} + +function getToneMappingFunction( functionName, toneMapping ) { + + let toneMappingName; + + switch ( toneMapping ) { + + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + +} + +function generateExtensions( parameters ) { + + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + +} + +function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2; + if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3; + if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +const shaderChunkMap = new Map( [ + [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154 + [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154 + [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154 +] ); + +function includeReplacer( match, include ) { + + let string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + const newInclude = shaderChunkMap.get( include ); + + if ( newInclude !== undefined ) { + + string = ShaderChunk[ newInclude ]; + console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude ); + + } else { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + // + + parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '', + parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '', + parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '', + parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '', + parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '', + parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '', + parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '', + parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '', + + parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '', + parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '', + + parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '', + + parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '', + parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '', + parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '', + + parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '', + parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '', + + parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '', + parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '', + + parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '', + parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '', + parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '', + + parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '', + parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '', + + // + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_UV1', + + ' attribute vec2 uv1;', + + '#endif', + + '#ifdef USE_UV2', + + ' attribute vec2 uv2;', + + '#endif', + + '#ifdef USE_UV3', + + ' attribute vec2 uv3;', + + '#endif', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropy ? '#define USE_ANISOTROPY' : '', + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + + parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', + + parameters.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + + runnable = false; + + if ( typeof renderer.debug.onShaderError === 'function' ) { + + renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader ); + + } else { + + // default error reporting + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const IS_WEBGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getChannel( value ) { + + if ( value === 0 ) return 'uv'; + + return `uv${ value }`; + + } + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + + const HAS_MAP = !! material.map; + const HAS_MATCAP = !! material.matcap; + const HAS_ENVMAP = !! envMap; + const HAS_AOMAP = !! material.aoMap; + const HAS_LIGHTMAP = !! material.lightMap; + const HAS_BUMPMAP = !! material.bumpMap; + const HAS_NORMALMAP = !! material.normalMap; + const HAS_DISPLACEMENTMAP = !! material.displacementMap; + const HAS_EMISSIVEMAP = !! material.emissiveMap; + + const HAS_METALNESSMAP = !! material.metalnessMap; + const HAS_ROUGHNESSMAP = !! material.roughnessMap; + + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap; + + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap; + + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap; + + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap; + + const HAS_SPECULARMAP = !! material.specularMap; + const HAS_SPECULAR_COLORMAP = !! material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap; + + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap; + + const HAS_GRADIENTMAP = !! material.gradientMap; + + const HAS_ALPHAMAP = !! material.alphaMap; + + const HAS_ALPHATEST = material.alphaTest > 0; + + const HAS_ALPHAHASH = !! material.alphaHash; + + const HAS_EXTENSIONS = !! material.extensions; + + const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1; + const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2; + const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = renderer.toneMapping; + + } + + } + + const parameters = { + + isWebGL2: IS_WEBGL2, + + shaderID: shaderID, + shaderType: material.type, + shaderName: material.name, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ), + + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + + gradientMap: HAS_GRADIENTMAP, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + + combine: material.combine, + + // + + mapUv: HAS_MAP && getChannel( material.map.channel ), + aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ), + lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ), + bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ), + normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ), + + metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ), + + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ), + + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ), + + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ), + + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ), + + specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ), + + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ), + thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ), + + alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ), + + // + + vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUv1s: HAS_ATTRIBUTE_UV1, + vertexUv2s: HAS_ATTRIBUTE_UV2, + vertexUv3s: HAS_ATTRIBUTE_UV3, + + pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: material.flatShading === true, + + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: toneMapping, + useLegacyLights: renderer._useLegacyLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true, + extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true, + extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true, + extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true, + + rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputColorSpace ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputColorSpace ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.mapUv ); + array.push( parameters.alphaMapUv ); + array.push( parameters.lightMapUv ); + array.push( parameters.aoMapUv ); + array.push( parameters.bumpMapUv ); + array.push( parameters.normalMapUv ); + array.push( parameters.displacementMapUv ); + array.push( parameters.emissiveMapUv ); + array.push( parameters.metalnessMapUv ); + array.push( parameters.roughnessMapUv ); + array.push( parameters.anisotropyMapUv ); + array.push( parameters.clearcoatMapUv ); + array.push( parameters.clearcoatNormalMapUv ); + array.push( parameters.clearcoatRoughnessMapUv ); + array.push( parameters.iridescenceMapUv ); + array.push( parameters.iridescenceThicknessMapUv ); + array.push( parameters.sheenColorMapUv ); + array.push( parameters.sheenRoughnessMapUv ); + array.push( parameters.specularMapUv ); + array.push( parameters.specularColorMapUv ); + array.push( parameters.specularIntensityMapUv ); + array.push( parameters.transmissionMapUv ); + array.push( parameters.thicknessMapUv ); + array.push( parameters.combine ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.matcap ) + _programLayers.enable( 4 ); + if ( parameters.envMap ) + _programLayers.enable( 5 ); + if ( parameters.normalMapObjectSpace ) + _programLayers.enable( 6 ); + if ( parameters.normalMapTangentSpace ) + _programLayers.enable( 7 ); + if ( parameters.clearcoat ) + _programLayers.enable( 8 ); + if ( parameters.iridescence ) + _programLayers.enable( 9 ); + if ( parameters.alphaTest ) + _programLayers.enable( 10 ); + if ( parameters.vertexColors ) + _programLayers.enable( 11 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 12 ); + if ( parameters.vertexUv1s ) + _programLayers.enable( 13 ); + if ( parameters.vertexUv2s ) + _programLayers.enable( 14 ); + if ( parameters.vertexUv3s ) + _programLayers.enable( 15 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 16 ); + if ( parameters.anisotropy ) + _programLayers.enable( 17 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.useLegacyLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.transmission ) + _programLayers.enable( 15 ); + if ( parameters.sheen ) + _programLayers.enable( 16 ); + if ( parameters.opaque ) + _programLayers.enable( 17 ); + if ( parameters.pointsUvs ) + _programLayers.enable( 18 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + +function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + + + +let nextVersion = 0; + +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + +} + +function WebGLLights( extensions, capabilities ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + directionalLength: - 1, + pointLength: - 1, + spotLength: - 1, + rectAreaLength: - 1, + hemiLength: - 1, + + numDirectionalShadows: - 1, + numPointShadows: - 1, + numSpotShadows: - 1, + numSpotMaps: - 1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights, useLegacyLights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + + if ( light.isAmbientLight ) { + + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( capabilities.isWebGL2 ) { + + // WebGL 2 + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + // WebGL 1 + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } else { + + console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' ); + + } + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { + + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + +} + +function WebGLRenderState( extensions, capabilities ) { + + const lights = new WebGLLights( extensions, capabilities ); + + const lightsArray = []; + const shadowsArray = []; + + function init() { + + lightsArray.length = 0; + shadowsArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function setupLights( useLegacyLights ) { + + lights.setup( lightsArray, useLegacyLights ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + + lights: lights + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow + }; + +} + +function WebGLRenderStates( extensions, capabilities ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class MeshDepthMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDepthMaterial = true; + + this.type = 'MeshDepthMaterial'; + + this.depthPacking = BasicDepthPacking; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.depthPacking = source.depthPacking; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + return this; + + } + +} + +class MeshDistanceMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDistanceMaterial = true; + + this.type = 'MeshDistanceMaterial'; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + return this; + + } + +} + +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + +function WebGLShadowMap( _renderer, _objects, _capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = _capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + let _previousType = this.type; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + const currentRenderTarget = _renderer.getRenderTarget(); + const activeCubeFace = _renderer.getActiveCubeFace(); + const activeMipmapLevel = _renderer.getActiveMipmapLevel(); + + const _state = _renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // check for shadow map type changes + + const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap ); + const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap ); + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + if ( shadow.map === null || toVSM === true || fromVSM === true ) { + + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + + if ( shadow.map !== null ) { + + shadow.map.dispose(); + + } + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + '.shadowMap'; + + shadow.camera.updateProjectionMatrix(); + + } + + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + + const viewportCount = shadow.getViewportCount(); + + for ( let vp = 0; vp < viewportCount; vp ++ ) { + + const viewport = shadow.getViewport( vp ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + shadow.updateMatrices( light, vp ); + + _frustum = shadow.getFrustum(); + + renderObject( scene, camera, shadow.camera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + _previousType = this.type; + + scope.needsUpdate = false; + + _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = _objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // vertical pass + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.mapPass ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + const materialProperties = _renderer.properties.get( result ); + materialProperties.light = light; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = _objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + +} + +function WebGLState( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( gl.NEVER ); + break; + + case AlwaysDepth: + + gl.depthFunc( gl.ALWAYS ); + break; + + case LessDepth: + + gl.depthFunc( gl.LESS ); + break; + + case LessEqualDepth: + + gl.depthFunc( gl.LEQUAL ); + break; + + case EqualDepth: + + gl.depthFunc( gl.EQUAL ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( gl.GEQUAL ); + break; + + case GreaterDepth: + + gl.depthFunc( gl.GREATER ); + break; + + case NotEqualDepth: + + gl.depthFunc( gl.NOTEQUAL ); + break; + + default: + + gl.depthFunc( gl.LEQUAL ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + gl.clearDepth( depth ); + currentDepthClear = depth; + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( gl.STENCIL_TEST ); + + } else { + + disable( gl.STENCIL_TEST ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( gl.SCISSOR_BOX ); + const viewportParam = gl.getParameter( gl.VIEWPORT ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count, dimensions ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const texture = gl.createTexture(); + + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + + for ( let i = 0; i < count; i ++ ) { + + if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) { + + gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } else { + + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } + + } + + return texture; + + } + + const emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + + if ( isWebGL2 ) { + + emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 ); + emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 ); + + } + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + + if ( target === gl.DRAW_FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer; + + } + + if ( target === gl.FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; + + needsUpdate = true; + + } + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.BACK ) { + + drawBuffers[ 0 ] = gl.BACK; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + if ( capabilities.isWebGL2 ) { + + gl.drawBuffers( drawBuffers ); + + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } + + } + + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: gl.FUNC_ADD, + [ SubtractEquation ]: gl.FUNC_SUBTRACT, + [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT + }; + + if ( isWebGL2 ) { + + equationToGL[ MinEquation ] = gl.MIN; + equationToGL[ MaxEquation ] = gl.MAX; + + } else { + + const extension = extensions.get( 'EXT_blend_minmax' ); + + if ( extension !== null ) { + + equationToGL[ MinEquation ] = extension.MIN_EXT; + equationToGL[ MaxEquation ] = extension.MAX_EXT; + + } + + } + + const factorToGL = { + [ ZeroFactor ]: gl.ZERO, + [ OneFactor ]: gl.ONE, + [ SrcColorFactor ]: gl.SRC_COLOR, + [ SrcAlphaFactor ]: gl.SRC_ALPHA, + [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE, + [ DstColorFactor ]: gl.DST_COLOR, + [ DstAlphaFactor ]: gl.DST_ALPHA, + [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR, + [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA, + [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR, + [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( gl.BLEND ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( gl.BLEND ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( gl.FUNC_ADD ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( gl.CULL_FACE ) + : enable( gl.CULL_FACE ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE ) + : disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( gl.CW ); + + } else { + + gl.frontFace( gl.CCW ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( gl.CULL_FACE ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( gl.BACK ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( gl.FRONT ); + + } else { + + gl.cullFace( gl.FRONT_AND_BACK ); + + } + + } + + } else { + + disable( gl.CULL_FACE ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( gl.POLYGON_OFFSET_FILL ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + gl.polygonOffset( factor, units ); + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + } + + } else { + + disable( gl.POLYGON_OFFSET_FILL ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( gl.SCISSOR_TEST ); + + } else { + + disable( gl.SCISSOR_TEST ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = gl.TEXTURE0 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( gl.BLEND ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.POLYGON_OFFSET_FILL ); + gl.disable( gl.SCISSOR_TEST ); + gl.disable( gl.STENCIL_TEST ); + gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ONE, gl.ZERO ); + gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( gl.LESS ); + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff ); + gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP ); + gl.clearStencil( 0 ); + + gl.cullFace( gl.BACK ); + gl.frontFace( gl.CCW ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( gl.TEXTURE0 ); + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + + if ( isWebGL2 === true ) { + + gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); + + } + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + // reset internals + + enabledCapabilities = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + +} + +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _videoTextures = new WeakMap(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { + + let scale = 1; + + // handle case if texture exceeds max size + + if ( image.width > maxSize || image.height > maxSize ) { + + scale = maxSize / Math.max( image.width, image.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 || needsPowerOfTwo === true ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; + + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function isPowerOfTwo$1( image ) { + + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + + } + + function textureNeedsPowerOfTwo( texture ) { + + if ( isWebGL2 ) return false; + + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + + } + + function textureNeedsGenerateMipmaps( texture, supportsMips ) { + + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) { + + if ( isWebGL2 === false ) return glFormat; + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let internalFormat = glFormat; + + if ( glFormat === _gl.RED ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; + + } + + if ( glFormat === _gl.RED_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.R8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.R16I; + if ( glType === _gl.INT ) internalFormat = _gl.R32I; + + } + + if ( glFormat === _gl.RG ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8; + + } + + if ( glFormat === _gl.RGBA ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4; + if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1; + + } + + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || + internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getMipLevels( texture, image, supportsMips ) { + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // Fallback filters for non-power-of-2 textures + + function filterFallback( f ) { + + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + + return _gl.NEAREST; + + } + + return _gl.LINEAR; + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; + + } + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + for ( let i = 0, il = texture.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( texture[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( texture[ i ] ); + + } + + } + + properties.remove( texture ); + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= maxTextures ) { + + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.colorSpace ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } + + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: _gl.REPEAT, + [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, + [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT + }; + + const filterToGL = { + [ NearestFilter ]: _gl.NEAREST, + [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, + [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, + + [ LinearFilter ]: _gl.LINEAR, + [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, + [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR + }; + + const compareToGL = { + [ NeverCompare ]: _gl.NEVER, + [ AlwaysCompare ]: _gl.ALWAYS, + [ LessCompare ]: _gl.LESS, + [ LessEqualCompare ]: _gl.LEQUAL, + [ EqualCompare ]: _gl.EQUAL, + [ GreaterEqualCompare ]: _gl.GEQUAL, + [ GreaterCompare ]: _gl.GREATER, + [ NotEqualCompare ]: _gl.NOTEQUAL + }; + + function setTextureParameters( textureType, texture, supportsMips ) { + + if ( supportsMips ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); + + } else { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE ); + + } + + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { + + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); + + } + + } + + if ( texture.compareFunction ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE ); + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] ); + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create Source <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = _gl.TEXTURE_2D; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY; + if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.colorSpace ); + + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + + setTextureParameters( textureType, texture, supportsMips ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); + + if ( texture.isDepthTexture ) { + + // populate depth texture with dummy data + + glInternalFormat = _gl.DEPTH_COMPONENT; + + if ( isWebGL2 ) { + + if ( texture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( texture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( texture.type === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } else { + + glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D + + } + + } else { + + if ( texture.type === FloatType ) { + + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + + } + + } + + // validation checks for WebGL 1 + + if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); + + } + + } + + if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = _gl.DEPTH_STENCIL; + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); + + } + + } + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( texture.isDataTexture ) { + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } else { + + state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else { + + // regular Texture (image, video, canvas) + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.colorSpace ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); + + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) { + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + const renderTargetProperties = properties.get( renderTarget ); + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + const width = Math.max( 1, renderTarget.width >> level ); + const height = Math.max( 1, renderTarget.height >> level ); + + if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) { + + state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753 + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + + let glInternalFormat = _gl.DEPTH_COMPONENT16; + + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { + + const depthTexture = renderTarget.depthTexture; + + if ( depthTexture && depthTexture.isDepthTexture ) { + + if ( depthTexture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( depthTexture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } + + } + + const samples = getRenderTargetSamples( renderTarget ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + + } + + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else { + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { + + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + + } + + // upload an empty depth texture with framebuffer size + if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + + } + + setTexture2D( renderTarget.depthTexture, 0 ); + + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'Unknown depthTexture format' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } + + } else { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer[ i ] = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } + + } else { + + if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + } + + if ( isMultipleRenderTargets ) { + + if ( capabilities.drawBuffers ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); + + } + + } + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = isMultipleRenderTargets ? texture : [ texture ]; + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + for ( let i = 0; i < 6; i ++ ) { + + if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 ); + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 ); + + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_2D ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + if ( isWebGL2 ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } else { + + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); + + } + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + + if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 ); + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); + + } + + } + + } + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i ); + + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; + if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] ); + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); + + if ( supportsInvalidateFramebuffer ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray ); + + } + + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.format === _SRGBAFormat ) return image; + + if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) { + + // sRGB + + if ( colorSpace === SRGBColorSpace ) { + + if ( isWebGL2 === false ) { + + // in WebGL 1, try to use EXT_sRGB extension and unsized formats + + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { + + texture.format = _SRGBAFormat; + + // it's not possible to generate mips in WebGL 1 with this extension + + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; + + } else { + + // slow fallback (CPU decode) + + image = ImageUtils.sRGBToLinear( image ); + + } + + } else { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } + + } else { + + console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace ); + + } + + } + + return image; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + +} + +function WebGLUtils( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function convert( p, colorSpace = NoColorSpace ) { + + let extension; + + if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1; + + if ( p === ByteType ) return gl.BYTE; + if ( p === ShortType ) return gl.SHORT; + if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT; + if ( p === IntType ) return gl.INT; + if ( p === UnsignedIntType ) return gl.UNSIGNED_INT; + if ( p === FloatType ) return gl.FLOAT; + + if ( p === HalfFloatType ) { + + if ( isWebGL2 ) return gl.HALF_FLOAT; + + extension = extensions.get( 'OES_texture_half_float' ); + + if ( extension !== null ) { + + return extension.HALF_FLOAT_OES; + + } else { + + return null; + + } + + } + + if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === RGBAFormat ) return gl.RGBA; + if ( p === LuminanceFormat ) return gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return gl.DEPTH_COMPONENT; + if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL; + + // WebGL 1 sRGB fallback + + if ( p === _SRGBAFormat ) { + + extension = extensions.get( 'EXT_sRGB' ); + + if ( extension !== null ) { + + return extension.SRGB_ALPHA_EXT; + + } else { + + return null; + + } + + } + + // WebGL2 formats. + + if ( p === RedFormat ) return gl.RED; + if ( p === RedIntegerFormat ) return gl.RED_INTEGER; + if ( p === RGFormat ) return gl.RG; + if ( p === RGIntegerFormat ) return gl.RG_INTEGER; + if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( colorSpace === SRGBColorSpace ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + + } else { + + return null; + + } + + } + + // ETC1 + + if ( p === RGB_ETC1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + + if ( extension !== null ) { + + return extension.COMPRESSED_RGB_ETC1_WEBGL; + + } else { + + return null; + + } + + } + + // ETC2 + + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) { + + if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8; + + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { + + return extension.UNSIGNED_INT_24_8_WEBGL; + + } else { + + return null; + + } + + } + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + +} + +class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; + + } + +} + +class Group extends Object3D { + + constructor() { + + super(); + + this.isGroup = true; + + this.type = 'Group'; + + } + +} + +const _moveEvent = { type: 'move' }; + +class WebXRController { + + constructor() { + + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + + } + + return this._hand; + + } + + getTargetRaySpace() { + + if ( this._targetRay === null ) { + + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + + } + + return this._targetRay; + + } + + getGripSpace() { + + if ( this._grip === null ) { + + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + + } + + return this._grip; + + } + + dispatchEvent( event ) { + + if ( this._targetRay !== null ) { + + this._targetRay.dispatchEvent( event ); + + } + + if ( this._grip !== null ) { + + this._grip.dispatchEvent( event ); + + } + + if ( this._hand !== null ) { + + this._hand.dispatchEvent( event ); + + } + + return this; + + } + + connect( inputSource ) { + + if ( inputSource && inputSource.hand ) { + + const hand = this._hand; + + if ( hand ) { + + for ( const inputjoint of inputSource.hand.values() ) { + + // Initialize hand with joints when connected + this._getHandJoint( hand, inputjoint ); + + } + + } + + } + + this.dispatchEvent( { type: 'connected', data: inputSource } ); + + return this; + + } + + disconnect( inputSource ) { + + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + + if ( this._targetRay !== null ) { + + this._targetRay.visible = false; + + } + + if ( this._grip !== null ) { + + this._grip.visible = false; + + } + + if ( this._hand !== null ) { + + this._hand.visible = false; + + } + + return this; + + } + + update( inputSource, frame, referenceSpace ) { + + let inputPose = null; + let gripPose = null; + let handPose = null; + + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + + if ( hand && inputSource.hand ) { + + handPose = true; + + for ( const inputjoint of inputSource.hand.values() ) { + + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + + // The transform of this joint will be updated with the joint pose on each frame + const joint = this._getHandJoint( hand, inputjoint ); + + if ( jointPose !== null ) { + + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + + } + + joint.visible = jointPose !== null; + + } + + // Custom events + + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); + + const distanceToPinch = 0.02; + const threshold = 0.005; + + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); + + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); + + } + + } else { + + if ( grip !== null && inputSource.gripSpace ) { + + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + + if ( gripPose !== null ) { + + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + grip.matrixWorldNeedsUpdate = true; + + if ( gripPose.linearVelocity ) { + + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); + + } else { + + grip.hasLinearVelocity = false; + + } + + if ( gripPose.angularVelocity ) { + + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); + + } else { + + grip.hasAngularVelocity = false; + + } + + } + + } + + } + + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + targetRay.matrixWorldNeedsUpdate = true; + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + + } + + if ( targetRay !== null ) { + + targetRay.visible = ( inputPose !== null ); + + } + + if ( grip !== null ) { + + grip.visible = ( gripPose !== null ); + + } + + if ( hand !== null ) { + + hand.visible = ( handPose !== null ); + + } + + return this; + + } + + // private method + + _getHandJoint( hand, inputjoint ) { + + if ( hand.joints[ inputjoint.jointName ] === undefined ) { + + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + + hand.add( joint ); + + } + + return hand.joints[ inputjoint.jointName ]; + + } + +} + +class DepthTexture extends Texture { + + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + + format = format !== undefined ? format : DepthFormat; + + if ( format !== DepthFormat && format !== DepthStencilFormat ) { + + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + + } + + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isDepthTexture = true; + + this.image = { width: width, height: height }; + + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + + this.flipY = false; + this.generateMipmaps = false; + + this.compareFunction = null; + + } + + + copy( source ) { + + super.copy( source ); + + this.compareFunction = source.compareFunction; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction; + + return data; + + } + +} + +class WebXRManager extends EventDispatcher { + + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + // Set default foveation to maximum. + let foveation = 1.0; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + // + + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraXR = new ArrayCamera(); + cameraXR.layers.enable( 1 ); + cameraXR.layers.enable( 2 ); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + this.cameraAutoUpdate = true; + this.enabled = false; + + this.isPresenting = false; + + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace ); + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + this.getBinding = function () { + + return glBinding; + + }; + + this.getFrame = function () { + + return xrFrame; + + }; + + this.getSession = function () { + + return session; + + }; + + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { + + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = new XRWebGLBinding( session, gl ); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0 + } ); + + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + this.setFoveation( foveation ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + this.getEnvironmentBlendMode = function () { + + if ( session !== null ) { + + return session.environmentBlendMode; + + } + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + cameraXR.near = cameraR.near = cameraL.near = camera.near; + cameraXR.far = cameraR.far = cameraL.far = camera.far; + + if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraXR.near, + depthFar: cameraXR.far + } ); + + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + + } + + const parent = camera.parent; + const cameras = cameraXR.cameras; + + updateCamera( cameraXR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraXR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraXR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + // update user camera and its children + + updateUserCamera( camera, cameraXR, parent ); + + }; + + function updateUserCamera( camera, cameraXR, parent ) { + + if ( parent === null ) { + + camera.matrix.copy( cameraXR.matrixWorld ); + + } else { + + camera.matrix.copy( parent.matrixWorld ); + camera.matrix.invert(); + camera.matrix.multiply( cameraXR.matrixWorld ); + + } + + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.updateMatrixWorld( true ); + + const children = camera.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].updateMatrixWorld( true ); + + } + + camera.projectionMatrix.copy( cameraXR.projectionMatrix ); + camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse ); + + if ( camera.isPerspectiveCamera ) { + + camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] ); + camera.zoom = 1; + + } + + } + + this.getCamera = function () { + + return cameraXR; + + }; + + this.getFoveation = function () { + + if ( glProjLayer === null && glBaseLayer === null ) { + + return undefined; + + } + + return foveation; + + }; + + this.setFoveation = function ( value ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + foveation = value; + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = value; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = value; + + } + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraXRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraXR's camera list + + if ( views.length !== cameraXR.cameras.length ) { + + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraXR.matrix.copy( camera.matrix ); + cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale ); + + } + + if ( cameraXRNeedsUpdate === true ) { + + cameraXR.cameras.push( camera ); + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame } ); + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + +} + +function WebGLMaterials( renderer, properties ) { + + function refreshTransformUniform( map, uniform ) { + + if ( map.matrixAutoUpdate === true ) { + + map.updateMatrix(); + + } + + uniform.value.copy( map.matrix ); + + } + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + + refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform ); + + uniforms.bumpScale.value = material.bumpScale; + + if ( material.side === BackSide ) { + + uniforms.bumpScale.value *= - 1; + + } + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + + refreshTransformUniform( material.normalMap, uniforms.normalMapTransform ); + + uniforms.normalScale.value.copy( material.normalScale ); + + if ( material.side === BackSide ) { + + uniforms.normalScale.value.negate(); + + } + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + + refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform ); + + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform ); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + refreshTransformUniform( material.specularMap, uniforms.specularMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1; + + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; + + refreshTransformUniform( material.lightMap, uniforms.lightMapTransform ); + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + refreshTransformUniform( material.aoMap, uniforms.aoMapTransform ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.uvTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.metalness.value = material.metalness; + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform ); + + } + + uniforms.roughness.value = material.roughness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform ); + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform ); + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform ); + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform ); + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform ); + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform ); + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform ); + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform ); + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform ); + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform ); + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + if ( material.anisotropy > 0 ) { + + uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) ); + + if ( material.anisotropyMap ) { + + uniforms.anisotropyMap.value = material.anisotropyMap; + + refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform ); + + } + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform ); + + } + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform ); + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + const light = properties.get( material ).light; + + uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld ); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + +} + +function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + gl.bufferData( gl.UNIFORM_BUFFER, size, usage ); + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniform = uniforms[ i ]; + + // partly update the buffer if necessary + + if ( hasUniformChanged( uniform, i, cache ) === true ) { + + const offset = uniform.__offset; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + let arrayOffset = 0; + + for ( let i = 0; i < values.length; i ++ ) { + + const value = values[ i ]; + + const info = getUniformSize( value ); + + if ( typeof value === 'number' ) { + + uniform.__data[ 0 ] = value; + gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data ); + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + uniform.__data[ 0 ] = value.elements[ 0 ]; + uniform.__data[ 1 ] = value.elements[ 1 ]; + uniform.__data[ 2 ] = value.elements[ 2 ]; + uniform.__data[ 3 ] = value.elements[ 0 ]; + uniform.__data[ 4 ] = value.elements[ 3 ]; + uniform.__data[ 5 ] = value.elements[ 4 ]; + uniform.__data[ 6 ] = value.elements[ 5 ]; + uniform.__data[ 7 ] = value.elements[ 0 ]; + uniform.__data[ 8 ] = value.elements[ 6 ]; + uniform.__data[ 9 ] = value.elements[ 7 ]; + uniform.__data[ 10 ] = value.elements[ 8 ]; + uniform.__data[ 11 ] = value.elements[ 0 ]; + + } else { + + value.toArray( uniform.__data, arrayOffset ); + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data ); + + } + + } + + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + + } + + function hasUniformChanged( uniform, index, cache ) { + + const value = uniform.value; + + if ( cache[ index ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' ) { + + cache[ index ] = value; + + } else { + + const values = Array.isArray( value ) ? value : [ value ]; + + const tempValues = []; + + for ( let i = 0; i < values.length; i ++ ) { + + tempValues.push( values[ i ].clone() ); + + } + + cache[ index ] = tempValues; + + } + + return true; + + } else { + + // compare current value with cached entry + + if ( typeof value === 'number' ) { + + if ( cache[ index ] !== value ) { + + cache[ index ] = value; + return true; + + } + + } else { + + const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ]; + const values = Array.isArray( value ) ? value : [ value ]; + + for ( let i = 0; i < cachedObjects.length; i ++ ) { + + const cachedObject = cachedObjects[ i ]; + + if ( cachedObject.equals( values[ i ] ) === false ) { + + cachedObject.copy( values[ i ] ); + return true; + + } + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniform = uniforms[ i ]; + + const infos = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let j = 0, jl = values.length; j < jl; j ++ ) { + + const value = values[ j ]; + + const info = getUniformSize( value ); + + infos.boundary += info.boundary; + infos.storage += info.storage; + + } + + // the following two properties will be used for partial buffer updates + + uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // + + if ( i > 0 ) { + + chunkOffset = offset % chunkSize; + + const remainingSizeInChunk = chunkSize - chunkOffset; + + // check for chunk overflow + + if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) { + + // add padding and adjust offset + + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; + + } + + } + + offset += infos.storage; + + } + + // ensure correct final padding + + chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' ) { + + // float/int + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + +} + +function createCanvasElement() { + + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; + +} + +class WebGLRenderer { + + constructor( parameters = {} ) { + + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = true, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = 'default', + failIfMajorPerformanceCaveat = false, + } = parameters; + + this.isWebGLRenderer = true; + + let _alpha; + + if ( context !== null ) { + + _alpha = context.getContextAttributes().alpha; + + } else { + + _alpha = alpha; + + } + + const uintClearColor = new Uint32Array( 4 ); + const intClearColor = new Int32Array( 4 ); + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // public properties + + this.domElement = canvas; + + // Debug configuration container + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + + // clearing + + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + + // scene graph + + this.sortObjects = true; + + // user-defined clipping + + this.clippingPlanes = []; + this.localClippingEnabled = false; + + // physically based shading + + this.outputColorSpace = SRGBColorSpace; + + // physical lights + + this._useLegacyLights = false; + + // tone mapping + + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + + // internal state cache + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + const _currentClearColor = new Color( 0x000000 ); + let _currentClearAlpha = 0; + + // + + let _width = canvas.width; + let _height = canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // transmission + + let _transmissionRenderTarget = null; + + // camera matrices cache + + const _projScreenMatrix = new Matrix4(); + + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = context; + + function getContext( contextNames, contextAttributes ) { + + for ( let i = 0; i < contextNames.length; i ++ ) { + + const contextName = contextNames[ i ]; + const context = canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; + + } + + return null; + + } + + try { + + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat, + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + + if ( _this.isWebGL1Renderer === true ) { + + contextNames.shift(); + + } + + _gl = getContext( contextNames, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextNames ) ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'Error creating WebGL context.' ); + + } + + } + + } + + if ( typeof WebGLRenderingContext !== 'undefined' && _gl instanceof WebGLRenderingContext ) { // @deprecated, r153 + + console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' ); + + } + + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + + }; + + } + + } catch ( error ) { + + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + + extensions.init( capabilities ); + + utils = new WebGLUtils( _gl, extensions, capabilities ); + + state = new WebGLState( _gl, extensions, capabilities ); + + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + + info.programs = programCache.programs; + + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + + } + + initGLContext(); + + // xr + + const xr = new WebXRManager( _this, _gl ); + + this.xr = xr; + + // API + + this.getContext = function () { + + return _gl; + + }; + + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + this.setSize = function ( width, height, updateStyle = true ) { + + if ( xr.isPresenting ) { + + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + canvas.width = Math.floor( width * _pixelRatio ); + canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle === true ) { + + canvas.style.width = width + 'px'; + canvas.style.height = height + 'px'; + + } + + this.setViewport( 0, 0, width, height ); + + }; + + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + canvas.width = Math.floor( width * pixelRatio ); + canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissorTest = function () { + + return _scissorTest; + + }; + + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + this.setClearColor = function () { + + background.setClearColor.apply( background, arguments ); + + }; + + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + this.setClearAlpha = function () { + + background.setClearAlpha.apply( background, arguments ); + + }; + + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) { + + // check if we're trying to clear an integer target + let isIntegerFormat = false; + if ( _currentRenderTarget !== null ) { + + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || + targetFormat === RGIntegerFormat || + targetFormat === RedIntegerFormat; + + } + + // use the appropriate clear functions to clear the target if it's a signed + // or unsigned integer target + if ( isIntegerFormat ) { + + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || + targetType === UnsignedIntType || + targetType === UnsignedShortType || + targetType === UnsignedInt248Type || + targetType === UnsignedShort4444Type || + targetType === UnsignedShort5551Type; + + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + + if ( isUnsignedType ) { + + uintClearColor[ 0 ] = r; + uintClearColor[ 1 ] = g; + uintClearColor[ 2 ] = b; + uintClearColor[ 3 ] = a; + _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor ); + + } else { + + intClearColor[ 0 ] = r; + intClearColor[ 1 ] = g; + intClearColor[ 2 ] = b; + intClearColor[ 3 ] = a; + _gl.clearBufferiv( _gl.COLOR, 0, intClearColor ); + + } + + } else { + + bits |= _gl.COLOR_BUFFER_BIT; + + } + + } + + if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + + _gl.clear( bits ); + + }; + + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + // + + this.dispose = function () { + + canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + if ( _transmissionRenderTarget ) { + + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; + + } + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + console.log( 'THREE.WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + console.log( 'THREE.WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + + if ( index === undefined ) return; + + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); + + } else { + + renderer.setMode( _gl.TRIANGLES ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( _gl.LINES ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( _gl.LINE_LOOP ); + + } else { + + renderer.setMode( _gl.LINE_STRIP ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( _gl.POINTS ); + + } else if ( object.isSprite ) { + + renderer.setMode( _gl.TRIANGLES ); + + } + + if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + this.compile = function ( scene, camera ) { + + function prepare( material, scene, object ) { + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = DoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + currentRenderState.setupLights( _this._useLegacyLights ); + + scene.traverse( function ( object ) { + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepare( material2, scene, object ); + + } + + } else { + + prepare( material, scene, object ); + + } + + } + + } ); + + renderStateStack.pop(); + currentRenderState = null; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + // + + this.info.render.frame ++; + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + if ( this.info.autoReset === true ) this.info.reset(); + + + // + + background.render( currentRenderList, scene ); + + // render scene + + currentRenderState.setupLights( _this._useLegacyLights ); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + renderScene( currentRenderList, scene, camera ); + + } + + // + + if ( _currentRenderTarget !== null ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + + const geometry = objects.update( object ); + const material = object.material; + + if ( sortObjects ) { + + if ( object.boundingSphere !== undefined ) { + + if ( object.boundingSphere === null ) object.computeBoundingSphere(); + _vector3.copy( object.boundingSphere.center ); + + } else { + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + _vector3.copy( geometry.boundingSphere.center ); + + } + + _vector3 + .applyMatrix4( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) { + + const isWebGL2 = capabilities.isWebGL2; + + if ( _transmissionRenderTarget === null ) { + + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 ) ? 4 : 0 + } ); + + // debug + + /* + const geometry = new PlaneGeometry(); + const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } ); + + const mesh = new Mesh( geometry, material ); + scene.add( mesh ); + */ + + } + + _this.getDrawingBufferSize( _vector2 ); + + if ( isWebGL2 ) { + + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); + + } else { + + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); + + } + + // + + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + + _this.getClearColor( _currentClearColor ); + _currentClearAlpha = _this.getClearAlpha(); + if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 ); + + _this.clear(); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + renderObjects( opaqueObjects, scene, camera ); + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + let renderTargetNeedsUpdate = false; + + for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) { + + const renderItem = transmissiveObjects[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + + if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) { + + const currentSide = material.side; + + material.side = BackSide; + material.needsUpdate = true; + + renderObject( object, scene, camera, geometry, material, group ); + + material.side = currentSide; + material.needsUpdate = true; + + renderTargetNeedsUpdate = true; + + } + + } + + if ( renderTargetNeedsUpdate === true ) { + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + } + + _this.setRenderTarget( currentRenderTarget ); + + _this.setClearColor( _currentClearColor, _currentClearAlpha ); + + _this.toneMapping = currentToneMapping; + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = DoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + material.onBuild( object, parameters, _this ); + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputColorSpace = parameters.outputColorSpace; + materialProperties.instancing = parameters.instancing; + materialProperties.instancingColor = parameters.instancingColor; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 ); + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = _this.toneMapping; + + } + + } + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const useCache = + camera === _currentCamera && + material.id === _currentMaterialId; + + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + clipping.setState( material, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputColorSpace !== colorSpace ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( capabilities.floatVertexTextures ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + + } else { + + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); + + } + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { + + morphtargets.update( object, geometry, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { + + m_uniforms.envMap.value = envMap; + + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + if ( capabilities.isWebGL2 ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); + + } + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; + + if ( renderTargetProperties.__hasExternalTextures ) { + + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { + + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; + + } + + } + + } + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + useDefaultFramebuffer = false; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + + } + + isCube = true; + + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + if ( Array.isArray( __webglFramebuffer ) ) { + + framebuffer = __webglFramebuffer[ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer; + + } + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + + } + + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings + + }; + + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + try { + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + } + + } + + }; + + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + + textures.setTexture2D( dstTexture, 0 ); + + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + + } else { + + if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + + } else { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image ); + + } + + } + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + + if ( _this.isWebGL1Renderer ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; + + } + + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_3D; + + } else if ( dstTexture.isDataArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D_ARRAY; + + } else { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; + + } + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH ); + const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT ); + const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS ); + const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES ); + + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z ); + + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); + + } else { + + if ( srcTexture.isCompressedArrayTexture ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); + + } + + } + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + + state.unbindTexture(); + + }; + + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + get coordinateSystem() { + + return WebGLCoordinateSystem; + + } + + get physicallyCorrectLights() { // @deprecated, r150 + + console.warn( 'THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' ); + return ! this.useLegacyLights; + + } + + set physicallyCorrectLights( value ) { // @deprecated, r150 + + console.warn( 'THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' ); + this.useLegacyLights = ! value; + + } + + get outputEncoding() { // @deprecated, r152 + + console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); + return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; + + } + + set outputEncoding( encoding ) { // @deprecated, r152 + + console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); + this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; + + } + + get useLegacyLights() { // @deprecated, r155 + + console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' ); + return this._useLegacyLights; + + } + + set useLegacyLights( value ) { // @deprecated, r155 + + console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' ); + this._useLegacyLights = value; + + } + +} + +class Fog { + + constructor( color, near = 1, far = 1000 ) { + + this.isFog = true; + + this.name = ''; + + this.color = new Color( color ); + + this.near = near; + this.far = far; + + } + + clone() { + + return new Fog( this.color, this.near, this.far ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; + + } + +} + +class Scene extends Object3D { + + constructor() { + + super(); + + this.isScene = true; + + this.type = 'Scene'; + + this.background = null; + this.environment = null; + this.fog = null; + + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + + this.overrideMaterial = null; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; + if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + + return data; + + } + +} + +class InstancedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { + + super( array, itemSize, normalized ); + + this.isInstancedBufferAttribute = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.meshPerAttribute = this.meshPerAttribute; + + data.isInstancedBufferAttribute = true; + + return data; + + } + +} + +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _instanceIntersects = []; + +const _box3 = /*@__PURE__*/ new Box3(); +const _identity = /*@__PURE__*/ new Matrix4(); +const _mesh = /*@__PURE__*/ new Mesh(); +const _sphere$3 = /*@__PURE__*/ new Sphere(); + +class InstancedMesh extends Mesh { + + constructor( geometry, material, count ) { + + super( geometry, material ); + + this.isInstancedMesh = true; + + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; + + this.count = count; + + this.boundingBox = null; + this.boundingSphere = null; + + for ( let i = 0; i < count; i ++ ) { + + this.setMatrixAt( i, _identity ); + + } + + } + + computeBoundingBox() { + + const geometry = this.geometry; + const count = this.count; + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + this.boundingBox.makeEmpty(); + + for ( let i = 0; i < count; i ++ ) { + + this.getMatrixAt( i, _instanceLocalMatrix ); + + _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix ); + + this.boundingBox.union( _box3 ); + + } + + } + + computeBoundingSphere() { + + const geometry = this.geometry; + const count = this.count; + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + if ( geometry.boundingSphere === null ) { + + geometry.computeBoundingSphere(); + + } + + this.boundingSphere.makeEmpty(); + + for ( let i = 0; i < count; i ++ ) { + + this.getMatrixAt( i, _instanceLocalMatrix ); + + _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix ); + + this.boundingSphere.union( _sphere$3 ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.instanceMatrix.copy( source.instanceMatrix ); + + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + + this.count = source.count; + + if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone(); + if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone(); + + return this; + + } + + getColorAt( index, color ) { + + color.fromArray( this.instanceColor.array, index * 3 ); + + } + + getMatrixAt( index, matrix ) { + + matrix.fromArray( this.instanceMatrix.array, index * 16 ); + + } + + raycast( raycaster, intersects ) { + + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + + _mesh.geometry = this.geometry; + _mesh.material = this.material; + + if ( _mesh.material === undefined ) return; + + // test with bounding sphere first + + if ( this.boundingSphere === null ) this.computeBoundingSphere(); + + _sphere$3.copy( this.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + + // now test each instance + + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + + // calculate the world matrix for each instance + + this.getMatrixAt( instanceId, _instanceLocalMatrix ); + + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + + // the mesh represents this single instance + + _mesh.matrixWorld = _instanceWorldMatrix; + + _mesh.raycast( raycaster, _instanceIntersects ); + + // process the result of raycast + + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); + + } + + _instanceIntersects.length = 0; + + } + + } + + setColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); + + } + + color.toArray( this.instanceColor.array, index * 3 ); + + } + + setMatrixAt( index, matrix ) { + + matrix.toArray( this.instanceMatrix.array, index * 16 ); + + } + + updateMorphTargets() { + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class LineBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isLineBasicMaterial = true; + + this.type = 'LineBasicMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _start$1 = /*@__PURE__*/ new Vector3(); +const _end$1 = /*@__PURE__*/ new Vector3(); +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$3 = /*@__PURE__*/ new Ray(); +const _sphere$2 = /*@__PURE__*/ new Sphere(); + +class Line extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + + super(); + + this.isLine = true; + + this.type = 'Line'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; + + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$2.copy( geometry.boundingSphere ); + _sphere$2.applyMatrix4( matrixWorld ); + _sphere$2.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return; + + // + + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + + const distSq = _ray$3.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this + + } ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + + const distSq = _ray$3.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this + + } ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); + +class LineSegments extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineSegments = true; + + this.type = 'LineSegments'; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); + + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + +} + +class PointsMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isPointsMaterial = true; + + this.type = 'PointsMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.size = 1; + this.sizeAttenuation = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); +const _position = /*@__PURE__*/ new Vector3(); + +class Points extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + + super(); + + this.isPoints = true; + + this.type = 'Points'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; + + // + + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i ++ ) { + + const a = index.getX( i ); + + _position.fromBufferAttribute( positionAttribute, a ); + + testPoint( _position, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end; i < l; i ++ ) { + + _position.fromBufferAttribute( positionAttribute, i ); + + testPoint( _position, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + + const rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); + + if ( rayPointDistanceSq < localThresholdSq ) { + + const intersectPoint = new Vector3(); + + _ray$2.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object + + } ); + + } + +} + +class CanvasTexture extends Texture { + + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isCanvasTexture = true; + + this.needsUpdate = true; + + } + +} + +/** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ + +class Curve { + + constructor() { + + this.type = 'Curve'; + + this.arcLengthDivisions = 200; + + } + + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + + getPoint( /* t, optionalTarget */ ) { + + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; + + } + + // Get point at relative position in curve according to arc length + // - u [0 .. 1] + + getPointAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); + + } + + // Get sequence of points using getPoint( t ) + + getPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPoint( d / divisions ) ); + + } + + return points; + + } + + // Get sequence of points using getPointAt( u ) + + getSpacedPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); + + } + + return points; + + } + + // Get total curve arc length + + getLength() { + + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; + + } + + // Get list of cumulative segment lengths + + getLengths( divisions = this.arcLengthDivisions ) { + + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; + + } + + this.needsUpdate = false; + + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; + + cache.push( 0 ); + + for ( let p = 1; p <= divisions; p ++ ) { + + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; + + } + + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum: sum }; Sum is in the last element. + + } + + updateArcLengths() { + + this.needsUpdate = true; + this.getLengths(); + + } + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + getUtoTmapping( u, distance ) { + + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if ( distance ) { + + targetArcLength = distance; + + } else { + + targetArcLength = u * arcLengths[ il - 1 ]; + + } + + // binary search for the index with largest value smaller than target u distance + + let low = 0, high = il - 1, comparison; + + while ( low <= high ) { + + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + + comparison = arcLengths[ i ] - targetArcLength; + + if ( comparison < 0 ) { + + low = i + 1; + + } else if ( comparison > 0 ) { + + high = i - 1; + + } else { + + high = i; + break; + + // DONE + + } + + } + + i = high; + + if ( arcLengths[ i ] === targetArcLength ) { + + return i / ( il - 1 ); + + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + + // add that fractional amount to t + + const t = ( i + segmentFraction ) / ( il - 1 ); + + return t; + + } + + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation + + getTangent( t, optionalTarget ) { + + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + + // Capping in case of danger + + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); + + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); + + return tangent; + + } + + getTangentAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); + + } + + computeFrenetFrames( segments, closed ) { + + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + + const normal = new Vector3(); + + const tangents = []; + const normals = []; + const binormals = []; + + const vec = new Vector3(); + const mat = new Matrix4(); + + // compute the tangent vectors for each segment on the curve + + for ( let i = 0; i <= segments; i ++ ) { + + const u = i / segments; + + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + + } + + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component + + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); + + if ( tx <= min ) { + + min = tx; + normal.set( 1, 0, 0 ); + + } + + if ( ty <= min ) { + + min = ty; + normal.set( 0, 1, 0 ); + + } + + if ( tz <= min ) { + + normal.set( 0, 0, 1 ); + + } + + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + + + // compute the slowly-varying normal and binormal vectors for each segment on the curve + + for ( let i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( let i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + } + + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.6, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; + + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + + return data; + + } + + fromJSON( json ) { + + this.arcLengthDivisions = json.arcLengthDivisions; + + return this; + + } + +} + +class EllipseCurve extends Curve { + + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + + super(); + + this.isEllipseCurve = true; + + this.type = 'EllipseCurve'; + + this.aX = aX; + this.aY = aY; + + this.xRadius = xRadius; + this.yRadius = yRadius; + + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + + this.aClockwise = aClockwise; + + this.aRotation = aRotation; + + } + + getPoint( t, optionalTarget ) { + + const point = optionalTarget || new Vector2(); + + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + + if ( deltaAngle < Number.EPSILON ) { + + if ( samePoints ) { + + deltaAngle = 0; + + } else { + + deltaAngle = twoPi; + + } + + } + + if ( this.aClockwise === true && ! samePoints ) { + + if ( deltaAngle === twoPi ) { + + deltaAngle = - twoPi; + + } else { + + deltaAngle = deltaAngle - twoPi; + + } + + } + + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); + + if ( this.aRotation !== 0 ) { + + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); + + const tx = x - this.aX; + const ty = y - this.aY; + + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + + } + + return point.set( x, y ); + + } + + copy( source ) { + + super.copy( source ); + + this.aX = source.aX; + this.aY = source.aY; + + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + + this.aClockwise = source.aClockwise; + + this.aRotation = source.aRotation; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.aX = this.aX; + data.aY = this.aY; + + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + + data.aClockwise = this.aClockwise; + + data.aRotation = this.aRotation; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.aX = json.aX; + this.aY = json.aY; + + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + + this.aClockwise = json.aClockwise; + + this.aRotation = json.aRotation; + + return this; + + } + +} + +class ArcCurve extends EllipseCurve { + + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + this.isArcCurve = true; + + this.type = 'ArcCurve'; + + } + +} + +/** + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ + + +/* +Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM + +This CubicPoly class could be used for reusing some variables and calculations, +but for three.js curve use, it could be possible inlined and flatten into a single function call +which can be placed in CurveUtils. +*/ + +function CubicPoly() { + + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + + } + + return { + + initCatmullRom: function ( x0, x1, x2, x3, tension ) { + + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + + }, + + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; + + init( x1, x2, t1, t2 ); + + }, + + calc: function ( t ) { + + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + + } + + }; + +} + +// + +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); + +class CatmullRomCurve3 extends Curve { + + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + + super(); + + this.isCatmullRomCurve3 = true; + + this.type = 'CatmullRomCurve3'; + + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const points = this.points; + const l = points.length; + + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; + + if ( this.closed ) { + + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + + } else if ( weight === 0 && intPoint === l - 1 ) { + + intPoint = l - 2; + weight = 1; + + } + + let p0, p3; // 4 points (p1 & p2 defined below) + + if ( this.closed || intPoint > 0 ) { + + p0 = points[ ( intPoint - 1 ) % l ]; + + } else { + + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; + + } + + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; + + if ( this.closed || intPoint + 2 < l ) { + + p3 = points[ ( intPoint + 2 ) % l ]; + + } else { + + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; + + } + + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; + + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); + + } else if ( this.curveType === 'catmullrom' ) { + + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + + } + + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); + + } + + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + + return this; + + } + +} + +/** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ + +function CatmullRom( t, p0, p1, p2, p3 ) { + + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + +} + +// + +function QuadraticBezierP0( t, p ) { + + const k = 1 - t; + return k * k * p; + +} + +function QuadraticBezierP1( t, p ) { + + return 2 * ( 1 - t ) * t * p; + +} + +function QuadraticBezierP2( t, p ) { + + return t * t * p; + +} + +function QuadraticBezier( t, p0, p1, p2 ) { + + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); + +} + +// + +function CubicBezierP0( t, p ) { + + const k = 1 - t; + return k * k * k * p; + +} + +function CubicBezierP1( t, p ) { + + const k = 1 - t; + return 3 * k * k * t * p; + +} + +function CubicBezierP2( t, p ) { + + return 3 * ( 1 - t ) * t * t * p; + +} + +function CubicBezierP3( t, p ) { + + return t * t * t * p; + +} + +function CubicBezier( t, p0, p1, p2, p3 ) { + + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); + +} + +class CubicBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + + super(); + + this.isCubicBezierCurve = true; + + this.type = 'CubicBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class CubicBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + + super(); + + this.isCubicBezierCurve3 = true; + + this.type = 'CubicBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class LineCurve extends Curve { + + constructor( v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isLineCurve = true; + + this.type = 'LineCurve'; + + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget = new Vector2() ) { + + return optionalTarget.subVectors( this.v2, this.v1 ).normalize(); + + } + + getTangentAt( u, optionalTarget ) { + + return this.getTangent( u, optionalTarget ); + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class LineCurve3 extends Curve { + + constructor( v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isLineCurve3 = true; + + this.type = 'LineCurve3'; + + this.v1 = v1; + this.v2 = v2; + + } + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget = new Vector3() ) { + + return optionalTarget.subVectors( this.v2, this.v1 ).normalize(); + + } + + getTangentAt( u, optionalTarget ) { + + return this.getTangent( u, optionalTarget ); + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isQuadraticBezierCurve = true; + + this.type = 'QuadraticBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isQuadraticBezierCurve3 = true; + + this.type = 'QuadraticBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class SplineCurve extends Curve { + + constructor( points = [] ) { + + super(); + + this.isSplineCurve = true; + + this.type = 'SplineCurve'; + + this.points = points; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const points = this.points; + const p = ( points.length - 1 ) * t; + + const intPoint = Math.floor( p ); + const weight = p - intPoint; + + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); + + } + + return this; + + } + +} + +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); + +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ + +class CurvePath extends Curve { + + constructor() { + + super(); + + this.type = 'CurvePath'; + + this.curves = []; + this.autoClose = false; // Automatically closes the path + + } + + add( curve ) { + + this.curves.push( curve ); + + } + + closePath() { + + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + + if ( ! startPoint.equals( endPoint ) ) { + + this.curves.push( new LineCurve( endPoint, startPoint ) ); + + } + + } + + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: + + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') + + getPoint( t, optionalTarget ) { + + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + + // To think about boundaries points. + + while ( i < curveLengths.length ) { + + if ( curveLengths[ i ] >= d ) { + + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; + + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt( u, optionalTarget ); + + } + + i ++; + + } + + return null; + + // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { + + points.push( points[ 0 ] ); + + } + + return points; + + } + + copy( source ) { + + super.copy( source ); + + this.curves = []; + + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + + const curve = source.curves[ i ]; + + this.curves.push( curve.clone() ); + + } + + this.autoClose = source.autoClose; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.autoClose = this.autoClose; + data.curves = []; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.autoClose = json.autoClose; + this.curves = []; + + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + + } + + return this; + + } + +} + +class Path extends CurvePath { + + constructor( points ) { + + super(); + + this.type = 'Path'; + + this.currentPoint = new Vector2(); + + if ( points ) { + + this.setFromPoints( points ); + + } + + } + + setFromPoints( points ) { + + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } + + return this; + + } + + moveTo( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + return this; + + } + + lineTo( x, y ) { + + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + splineThru( pts /*Array of Vector*/ ) { + + const npts = [ this.currentPoint.clone() ].concat( pts ); + + const curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + return this; + + } + + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + return this; + + } + + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + if ( this.curves.length > 0 ) { + + // if a previous curve is present, attempt to join + const firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; + + } + + copy( source ) { + + super.copy( source ); + + this.currentPoint.copy( source.currentPoint ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; + + } + +} + +class CircleGeometry extends BufferGeometry { + + constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CircleGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + segments = Math.max( 3, segments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + const segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( let i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + static fromJSON( data ) { + + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); + + } + +} + +class Shape extends Path { + + constructor( points ) { + + super( points ); + + this.uuid = generateUUID(); + + this.type = 'Shape'; + + this.holes = []; + + } + + getPointsHoles( divisions ) { + + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + + } + + return holesPts; + + } + + // get points of shape and holes (keypoints based on segments parameter) + + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; + + } + + copy( source ) { + + super.copy( source ); + + this.holes = []; + + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + + const hole = source.holes[ i ]; + + this.holes.push( hole.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.uuid = this.uuid; + data.holes = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.uuid = json.uuid; + this.holes = []; + + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); + + } + + return this; + + } + +} + +/** + * Port from https://github.com/mapbox/earcut (v2.2.4) + */ + +const Earcut = { + + triangulate: function ( data, holeIndices, dim = 2 ) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 32767 / invSize : 0; + + } + + earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 ); + + return triangles; + + } + +}; + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { + + let i, last; + + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } else { + + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } + + if ( last && equals( last, last.next ) ) { + + removeNode( last ); + last = last.next; + + } + + return last; + +} + +// eliminate colinear or duplicate points +function filterPoints( start, end ) { + + if ( ! start ) return start; + if ( ! end ) end = start; + + let p = start, + again; + do { + + again = false; + + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; + + } else { + + p = p.next; + + } + + } while ( again || p !== end ); + + return end; + +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + + if ( ! ear ) return; + + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + + let stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { + + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim | 0 ); + triangles.push( ear.i / dim | 0 ); + triangles.push( next.i / dim | 0 ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { + + // try filtering points and slicing again + if ( ! pass ) { + + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); + + // if this didn't work, try curing all small self-intersections locally + + } else if ( pass === 1 ) { + + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); + + // as a last resort, try splitting the remaining polygon into two + + } else if ( pass === 2 ) { + + splitEarcut( ear, triangles, dim, minX, minY, invSize ); + + } + + break; + + } + + } + +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + let p = c.next; + while ( p !== a ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; + + } + + return true; + +} + +function isEarHashed( ear, minX, minY, invSize ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + // z-order range for the current triangle bbox; + const minZ = zOrder( x0, y0, minX, minY, invSize ), + maxZ = zOrder( x1, y1, minX, minY, invSize ); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + } + + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + return true; + +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { + + let p = start; + do { + + const a = p.prev, + b = p.next.next; + + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + + triangles.push( a.i / dim | 0 ); + triangles.push( p.i / dim | 0 ); + triangles.push( b.i / dim | 0 ); + + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); + + p = start = b; + + } + + p = p.next; + + } while ( p !== start ); + + return filterPoints( p ); + +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + + let b = a.next.next; + while ( b !== a.prev ) { + + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); + + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); + + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize, 0 ); + earcutLinked( c, triangles, dim, minX, minY, invSize, 0 ); + return; + + } + + b = b.next; + + } + + a = a.next; + + } while ( a !== start ); + +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { + + const queue = []; + let i, len, start, end, list; + + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); + + } + + queue.sort( compareX ); + + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { + + outerNode = eliminateHole( queue[ i ], outerNode ); + + } + + return outerNode; + +} + +function compareX( a, b ) { + + return a.x - b.x; + +} + +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole( hole, outerNode ) { + + const bridge = findHoleBridge( hole, outerNode ); + if ( ! bridge ) { + + return outerNode; + + } + + const bridgeReverse = splitPolygon( bridge, hole ); + + // filter collinear points around the cuts + filterPoints( bridgeReverse, bridgeReverse.next ); + return filterPoints( bridge, bridge.next ); + +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { + + let p = outerNode, + qx = - Infinity, + m; + + const hx = hole.x, hy = hole.y; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { + + qx = x; + m = p.x < p.next.x ? p : p.next; + if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint + + } + + } + + p = p.next; + + } while ( p !== outerNode ); + + if ( ! m ) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; + + p = m; + + do { + + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + + m = p; + tanMin = tan; + + } + + } + + p = p.next; + + } while ( p !== stop ); + + return m; + +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { + + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + +} + +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { + + let p = start; + do { + + if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + + } while ( p !== start ); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked( p ); + +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { + + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + + p = list; + list = null; + tail = null; + numMerges = 0; + + while ( p ) { + + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { + + pSize ++; + q = q.nextZ; + if ( ! q ) break; + + } + + qSize = inSize; + + while ( pSize > 0 || ( qSize > 0 && q ) ) { + + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + + e = p; + p = p.nextZ; + pSize --; + + } else { + + e = q; + q = q.nextZ; + qSize --; + + } + + if ( tail ) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + + } + + p = q; + + } + + tail.nextZ = null; + inSize *= 2; + + } while ( numMerges > 1 ); + + return list; + +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { + + // coords are transformed into non-negative 15-bit integer range + x = ( x - minX ) * invSize | 0; + y = ( y - minY ) * invSize | 0; + + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; + + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; + + return x | ( y << 1 ); + +} + +// find the leftmost node of a polygon ring +function getLeftmost( start ) { + + let p = start, + leftmost = start; + do { + + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; + + } while ( p !== start ); + + return leftmost; + +} + +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + + return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) && + ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) && + ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py ); + +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { + + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + +} + +// signed area of a triangle +function area( p, q, r ) { + + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + +} + +// check if two points are equal +function equals( p1, p2 ) { + + return p1.x === p2.x && p1.y === p2.y; + +} + +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { + + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); + + if ( o1 !== o2 && o3 !== o4 ) return true; // general case + + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { + + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + +} + +function sign( num ) { + + return num > 0 ? 1 : num < 0 ? - 1 : 0; + +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { + + let p = a; + do { + + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; + + } while ( p !== a ); + + return false; + +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { + + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { + + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { + + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; + + } while ( p !== a ); + + return inside; + +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { + + const a2 = new Node$1( a.i, a.x, a.y ), + b2 = new Node$1( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { + + const p = new Node$1( i, x, y ); + + if ( ! last ) { + + p.prev = p; + p.next = p; + + } else { + + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + + } + + return p; + +} + +function removeNode( p ) { + + p.next.prev = p.prev; + p.prev.next = p.next; + + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + +} + +function Node$1( i, x, y ) { + + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + +} + +function signedArea( data, start, end, dim ) { + + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { + + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; + + } + + return sum; + +} + +class ShapeUtils { + + // calculate area of the contour polygon + + static area( contour ) { + + const n = contour.length; + let a = 0.0; + + for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + + } + + return a * 0.5; + + } + + static isClockWise( pts ) { + + return ShapeUtils.area( pts ) < 0; + + } + + static triangulateShape( contour, holes ) { + + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + + removeDupEndPts( contour ); + addContour( vertices, contour ); + + // + + let holeIndex = contour.length; + + holes.forEach( removeDupEndPts ); + + for ( let i = 0; i < holes.length; i ++ ) { + + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); + + } + + // + + const triangles = Earcut.triangulate( vertices, holeIndices ); + + // + + for ( let i = 0; i < triangles.length; i += 3 ) { + + faces.push( triangles.slice( i, i + 3 ) ); + + } + + return faces; + + } + +} + +function removeDupEndPts( points ) { + + const l = points.length; + + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + + points.pop(); + + } + +} + +function addContour( vertices, contour ) { + + for ( let i = 0; i < contour.length; i ++ ) { + + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); + + } + +} + +/** + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ + + +class ExtrudeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { + + super(); + + this.type = 'ExtrudeGeometry'; + + this.parameters = { + shapes: shapes, + options: options + }; + + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + + const scope = this; + + const verticesArray = []; + const uvArray = []; + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + addShape( shape ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + this.computeVertexNormals(); + + // functions + + function addShape( shape ) { + + const placeholder = []; + + // options + + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + + const extrudePath = options.extrudePath; + + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + + // + + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + + if ( extrudePath ) { + + extrudePts = extrudePath.getSpacedPoints( steps ); + + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion + + // SETUP TNB variables + + // TODO1 - have a .isClosed in spline? + + splineTube = extrudePath.computeFrenetFrames( steps, false ); + + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } + + // Safeguards if bevels are not enabled + + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + + } + + // Variables initialization + + const shapePoints = shape.extractPoints( curveSegments ); + + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + + const reverse = ! ShapeUtils.isClockWise( vertices ); + + if ( reverse ) { + + vertices = vertices.reverse(); + + // Maybe we should also check if holes are in the opposite direction, just to be safe ... + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + if ( ShapeUtils.isClockWise( ahole ) ) { + + holes[ h ] = ahole.reverse(); + + } + + } + + } + + + const faces = ShapeUtils.triangulateShape( vertices, holes ); + + /* Vertices */ + + const contour = vertices; // vertices has all points but contour has only points of circumference + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + vertices = vertices.concat( ahole ); + + } + + + function scalePt2( pt, vec, size ) { + + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + + return pt.clone().addScaledVector( vec, size ); + + } + + const vlen = vertices.length, flen = faces.length; + + + // Find directions for point movement + + + function getBevelVec( inPt, inPrev, inNext ) { + + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. + + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html + + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; + + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + + // not collinear + + // length of vectors for normalizing + + const v_prev_len = Math.sqrt( v_prev_lensq ); + const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + + // shift adjacent points by unit vectors to the left + + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + // vector from inPt to intersection point + + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } + + } else { + + // handle special case of collinear edges + + let direction_eq = false; // assumes: opposite + + if ( v_prev_x > Number.EPSILON ) { + + if ( v_next_x > Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( v_prev_x < - Number.EPSILON ) { + + if ( v_next_x < - Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + + direction_eq = true; + + } + + } + + } + + if ( direction_eq ) { + + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); + + } else { + + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); + + } + + } + + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + + } + + + const contourMovements = []; + + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) + + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + + } + + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + oneHoleMovements = []; + + for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + + } + + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); + + } + + + // Loop bevelSegments, 1 for the front, 1 for the back + + for ( let b = 0; b < bevelSegments; b ++ ) { + + //for ( b = bevelSegments; b > 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + } + + } + + const bs = bevelSize + bevelOffset; + + // Back facing vertices + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, 0 ); + + } else { + + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + // Add stepped vertices... + // Including front facing vertices + + for ( let s = 1; s <= steps; s ++ ) { + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth / steps * s ); + + } else { + + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag - }, - toon: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { - value: /*@__PURE__*/new Color$1(0x000000) - } - }]), - vertexShader: ShaderChunk.meshtoon_vert, - fragmentShader: ShaderChunk.meshtoon_frag - }, - matcap: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, { - matcap: { - value: null - } - }]), - vertexShader: ShaderChunk.meshmatcap_vert, - fragmentShader: ShaderChunk.meshmatcap_frag - }, - points: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]), - vertexShader: ShaderChunk.points_vert, - fragmentShader: ShaderChunk.points_frag - }, - dashed: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, { - scale: { - value: 1 - }, - dashSize: { - value: 1 - }, - totalSize: { - value: 2 - } - }]), - vertexShader: ShaderChunk.linedashed_vert, - fragmentShader: ShaderChunk.linedashed_frag - }, - depth: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]), - vertexShader: ShaderChunk.depth_vert, - fragmentShader: ShaderChunk.depth_frag - }, - normal: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, { - opacity: { - value: 1.0 - } - }]), - vertexShader: ShaderChunk.meshnormal_vert, - fragmentShader: ShaderChunk.meshnormal_frag - }, - sprite: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]), - vertexShader: ShaderChunk.sprite_vert, - fragmentShader: ShaderChunk.sprite_frag - }, - background: { - uniforms: { - uvTransform: { - value: /*@__PURE__*/new Matrix3() - }, - t2D: { - value: null - } - }, - vertexShader: ShaderChunk.background_vert, - fragmentShader: ShaderChunk.background_frag - }, - backgroundCube: { - uniforms: { - envMap: { - value: null - }, - flipEnvMap: { - value: -1 - }, - backgroundBlurriness: { - value: 0 - } - }, - vertexShader: ShaderChunk.backgroundCube_vert, - fragmentShader: ShaderChunk.backgroundCube_frag - }, - cube: { - uniforms: { - tCube: { - value: null - }, - tFlip: { - value: -1 - }, - opacity: { - value: 1.0 - } - }, - vertexShader: ShaderChunk.cube_vert, - fragmentShader: ShaderChunk.cube_frag - }, - equirect: { - uniforms: { - tEquirect: { - value: null - } - }, - vertexShader: ShaderChunk.equirect_vert, - fragmentShader: ShaderChunk.equirect_frag - }, - distanceRGBA: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, { - referencePosition: { - value: /*@__PURE__*/new Vector3() - }, - nearDistance: { - value: 1 - }, - farDistance: { - value: 1000 } - }]), - vertexShader: ShaderChunk.distanceRGBA_vert, - fragmentShader: ShaderChunk.distanceRGBA_frag + + + // Add bevel segments planes + + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } + + } + + /* Faces */ + + // Top and bottom faces + + buildLidFaces(); + + // Sides faces + + buildSideFaces(); + + + ///// Internal functions + + function buildLidFaces() { + + const start = verticesArray.length / 3; + + if ( bevelEnabled ) { + + let layer = 0; // steps + 1 + let offset = vlen * layer; + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + + } + + layer = steps + bevelSegments * 2; + offset = vlen * layer; + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + + } + + } else { + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + + } + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + + } + + } + + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; + + } + + + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + + + } + + function sidewalls( contour, layeroffset ) { + + let i = contour.length; + + while ( -- i >= 0 ) { + + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; + + //console.log('b', i,j, i-1, k,vertices.length); + + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); + + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } + + } + + } + + function v( x, y, z ) { + + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); + + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + + } + + function f4( a, b, c, d ) { + + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + const options = this.parameters.options; + + return toJSON$1( shapes, options, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + const extrudePath = data.options.extrudePath; + + if ( extrudePath !== undefined ) { + + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + + } + + return new ExtrudeGeometry( geometryShapes, data.options ); + + } + +} + +const WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + }, - shadow: { - uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, { - color: { - value: /*@__PURE__*/new Color$1(0x00000) + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { + + return [ + new Vector2( a_x, 1 - a_z ), + new Vector2( b_x, 1 - b_z ), + new Vector2( c_x, 1 - c_z ), + new Vector2( d_x, 1 - d_z ) + ]; + + } else { + + return [ + new Vector2( a_y, 1 - a_z ), + new Vector2( b_y, 1 - b_z ), + new Vector2( c_y, 1 - c_z ), + new Vector2( d_y, 1 - d_z ) + ]; + + } + + } + +}; + +function toJSON$1( shapes, options, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + data.options = Object.assign( {}, options ); + + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + + return data; + +} + +class SphereGeometry extends BufferGeometry { + + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + + super(); + + this.type = 'SphereGeometry'; + + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + + let index = 0; + const grid = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // generate vertices, normals and uvs + + for ( let iy = 0; iy <= heightSegments; iy ++ ) { + + const verticesRow = []; + + const v = iy / heightSegments; + + // special case for the poles + + let uOffset = 0; + + if ( iy === 0 && thetaStart === 0 ) { + + uOffset = 0.5 / widthSegments; + + } else if ( iy === heightSegments && thetaEnd === Math.PI ) { + + uOffset = - 0.5 / widthSegments; + + } + + for ( let ix = 0; ix <= widthSegments; ix ++ ) { + + const u = ix / widthSegments; + + // vertex + + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, 1 - v ); + + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); + + } + + // indices + + for ( let iy = 0; iy < heightSegments; iy ++ ) { + + for ( let ix = 0; ix < widthSegments; ix ++ ) { + + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + static fromJSON( data ) { + + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); + + } + +} + +class MeshStandardMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshStandardMaterial = true; + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.roughnessMap = null; + + this.metalnessMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.envMapIntensity = 1.0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { 'STANDARD': '' }; + + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + + constructor( parameters ) { + + super(); + + this.isMeshPhysicalMaterial = true; + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.type = 'MeshPhysicalMaterial'; + + this.anisotropyRotation = 0; + this.anisotropyMap = null; + + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; + + this.ior = 1.5; + + Object.defineProperty( this, 'reflectivity', { + get: function () { + + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); + }, - opacity: { - value: 1.0 + set: function ( reflectivity ) { + + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); + } - }]), - vertexShader: ShaderChunk.shadow_vert, - fragmentShader: ShaderChunk.shadow_frag + } ); + + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; + + this.transmissionMap = null; + + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color( 1, 1, 1 ); + + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; + + this._anisotropy = 0; + this._clearcoat = 0; + this._iridescence = 0; + this._sheen = 0.0; + this._transmission = 0; + + this.setValues( parameters ); + + } + + get anisotropy() { + + return this._anisotropy; + + } + + set anisotropy( value ) { + + if ( this._anisotropy > 0 !== value > 0 ) { + + this.version ++; + + } + + this._anisotropy = value; + + } + + get clearcoat() { + + return this._clearcoat; + + } + + set clearcoat( value ) { + + if ( this._clearcoat > 0 !== value > 0 ) { + + this.version ++; + + } + + this._clearcoat = value; + + } + + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + + get sheen() { + + return this._sheen; + + } + + set sheen( value ) { + + if ( this._sheen > 0 !== value > 0 ) { + + this.version ++; + + } + + this._sheen = value; + + } + + get transmission() { + + return this._transmission; + } -}; -ShaderLib.physical = { - uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, { - clearcoat: { - value: 0 - }, - clearcoatMap: { - value: null - }, - clearcoatRoughness: { - value: 0 - }, - clearcoatRoughnessMap: { - value: null - }, - clearcoatNormalScale: { - value: /*@__PURE__*/new Vector2(1, 1) - }, - clearcoatNormalMap: { - value: null - }, - iridescence: { - value: 0 - }, - iridescenceMap: { - value: null - }, - iridescenceIOR: { - value: 1.3 - }, - iridescenceThicknessMinimum: { - value: 100 - }, - iridescenceThicknessMaximum: { - value: 400 - }, - iridescenceThicknessMap: { - value: null - }, - sheen: { - value: 0 - }, - sheenColor: { - value: /*@__PURE__*/new Color$1(0x000000) - }, - sheenColorMap: { - value: null - }, - sheenRoughness: { - value: 1 - }, - sheenRoughnessMap: { - value: null - }, - transmission: { - value: 0 - }, - transmissionMap: { - value: null - }, - transmissionSamplerSize: { - value: /*@__PURE__*/new Vector2() - }, - transmissionSamplerMap: { - value: null - }, - thickness: { - value: 0 - }, - thicknessMap: { - value: null - }, - attenuationDistance: { - value: 0 - }, - attenuationColor: { - value: /*@__PURE__*/new Color$1(0x000000) - }, - specularIntensity: { - value: 1 - }, - specularIntensityMap: { - value: null - }, - specularColor: { - value: /*@__PURE__*/new Color$1(1, 1, 1) - }, - specularColorMap: { - value: null + + set transmission( value ) { + + if ( this._transmission > 0 !== value > 0 ) { + + this.version ++; + } - }]), - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag + + this._transmission = value; + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.ior = source.ior; + + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); + + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; + + return this; + + } + +} + +class MeshPhongMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshPhongMaterial = true; + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshToonMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshToonMaterial = true; + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + this.gradientMap = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + this.gradientMap = source.gradientMap; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshNormalMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshNormalMaterial = true; + + this.type = 'MeshNormalMaterial'; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.flatShading = false; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + return this; + + } + +} + +class MeshLambertMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshLambertMaterial = true; + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshMatcapMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshMatcapMaterial = true; + + this.defines = { 'MATCAP': '' }; + + this.type = 'MeshMatcapMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.matcap = null; + + this.map = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.defines = { 'MATCAP': '' }; + + this.color.copy( source.color ); + + this.matcap = source.matcap; + + this.map = source.map; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class LineDashedMaterial extends LineBasicMaterial { + + constructor( parameters ) { + + super(); + + this.isLineDashedMaterial = true; + + this.type = 'LineDashedMaterial'; + + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + } + +} + +const Cache = { + + enabled: false, + + files: {}, + + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + get: function ( key ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + clear: function () { + + this.files = {}; + + } + }; -function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { - const clearColor = new Color$1(0x000000); - let clearAlpha = alpha === true ? 0 : 1; - let planeMesh; - let boxMesh; - let currentBackground = null; - let currentBackgroundVersion = 0; - let currentTonemapping = null; - function render(renderList, scene) { - let forceClear = false; - let background = scene.isScene === true ? scene.background : null; - if (background && background.isTexture) { - const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background - background = (usePMREM ? cubeuvmaps : cubemaps).get(background); - } +class LoadingManager { + + constructor( onLoad, onProgress, onError ) { + + const scope = this; + + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor - // Ignore background in AR - // TODO: Reconsider this. + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - const xr = renderer.xr; - const session = xr.getSession && xr.getSession(); - if (session && session.environmentBlendMode === 'additive') { - background = null; - } - if (background === null) { - setClear(clearColor, clearAlpha); - } else if (background && background.isColor) { - setClear(background, 1); - forceClear = true; - } - if (renderer.autoClear || forceClear) { - renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); - } - if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { - if (boxMesh === undefined) { - boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({ - name: 'BackgroundCubeMaterial', - uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), - vertexShader: ShaderLib.backgroundCube.vertexShader, - fragmentShader: ShaderLib.backgroundCube.fragmentShader, - side: BackSide, - depthTest: false, - depthWrite: false, - fog: false - })); - boxMesh.geometry.deleteAttribute('normal'); - boxMesh.geometry.deleteAttribute('uv'); - boxMesh.onBeforeRender = function (renderer, scene, camera) { - this.matrixWorld.copyPosition(camera.matrixWorld); - }; + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } - // add "envMap" material property so the renderer can evaluate it like for built-in materials - Object.defineProperty(boxMesh.material, 'envMap', { - get: function () { - return this.uniforms.envMap.value; - } - }); - objects.update(boxMesh); - } - boxMesh.material.uniforms.envMap.value = background; - boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; - boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; - if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { - boxMesh.material.needsUpdate = true; - currentBackground = background; - currentBackgroundVersion = background.version; - currentTonemapping = renderer.toneMapping; } - boxMesh.layers.enableAll(); - // push to the pre-sorted opaque render list - renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); - } else if (background && background.isTexture) { - if (planeMesh === undefined) { - planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({ - name: 'BackgroundMaterial', - uniforms: cloneUniforms(ShaderLib.background.uniforms), - vertexShader: ShaderLib.background.vertexShader, - fragmentShader: ShaderLib.background.fragmentShader, - side: FrontSide, - depthTest: false, - depthWrite: false, - fog: false - })); - planeMesh.geometry.deleteAttribute('normal'); + isLoading = true; + + }; + + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); - // add "map" material property so the renderer can evaluate it like for built-in materials - Object.defineProperty(planeMesh.material, 'map', { - get: function () { - return this.uniforms.t2D.value; - } - }); - objects.update(planeMesh); } - planeMesh.material.uniforms.t2D.value = background; - if (background.matrixAutoUpdate === true) { - background.updateMatrix(); + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + } - planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); - if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { - planeMesh.material.needsUpdate = true; - currentBackground = background; - currentBackgroundVersion = background.version; - currentTonemapping = renderer.toneMapping; + + }; + + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + } - planeMesh.layers.enableAll(); - // push to the pre-sorted opaque render list - renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); - } - } - function setClear(color, alpha) { - state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha); - } - return { - getClearColor: function () { - return clearColor; - }, - setClearColor: function (color, alpha = 1) { - clearColor.set(color); - clearAlpha = alpha; - setClear(clearColor, clearAlpha); - }, - getClearAlpha: function () { - return clearAlpha; - }, - setClearAlpha: function (alpha) { - clearAlpha = alpha; - setClear(clearColor, clearAlpha); - }, - render: render - }; -} + }; + + this.resolveURL = function ( url ) { + + if ( urlModifier ) { + + return urlModifier( url ); -function WebGLBindingStates(gl, extensions, attributes, capabilities) { - const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object'); - const vaoAvailable = capabilities.isWebGL2 || extension !== null; - const bindingStates = {}; - const defaultState = createBindingState(null); - let currentState = defaultState; - let forceUpdate = false; - function setup(object, material, program, geometry, index) { - let updateBuffers = false; - if (vaoAvailable) { - const state = getBindingState(geometry, program, material); - if (currentState !== state) { - currentState = state; - bindVertexArrayObject(currentState.object); } - updateBuffers = needsUpdate(object, geometry, program, index); - if (updateBuffers) saveCache(object, geometry, program, index); - } else { - const wireframe = material.wireframe === true; - if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) { - currentState.geometry = geometry.id; - currentState.program = program.id; - currentState.wireframe = wireframe; - updateBuffers = true; + + return url; + + }; + + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + + return this; + + }; + + this.addHandler = function ( regex, loader ) { + + handlers.push( regex, loader ); + + return this; + + }; + + this.removeHandler = function ( regex ) { + + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); + } - } - if (index !== null) { - attributes.update(index, gl.ELEMENT_ARRAY_BUFFER); - } - if (updateBuffers || forceUpdate) { - forceUpdate = false; - setupVertexAttributes(object, material, program, geometry); - if (index !== null) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer); + + return this; + + }; + + this.getHandler = function ( file ) { + + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; + + if ( regex.global ) regex.lastIndex = 0; // see #17920 + + if ( regex.test( file ) ) { + + return loader; + + } + } - } + + return null; + + }; + } - function createVertexArrayObject() { - if (capabilities.isWebGL2) return gl.createVertexArray(); - return extension.createVertexArrayOES(); + +} + +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +class Loader { + + constructor( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; + + } + + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.load( url, resolve, onProgress, reject ); + + } ); + } - function bindVertexArrayObject(vao) { - if (capabilities.isWebGL2) return gl.bindVertexArray(vao); - return extension.bindVertexArrayOES(vao); + + parse( /* data */ ) {} + + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + } - function deleteVertexArrayObject(vao) { - if (capabilities.isWebGL2) return gl.deleteVertexArray(vao); - return extension.deleteVertexArrayOES(vao); + + setWithCredentials( value ) { + + this.withCredentials = value; + return this; + } - function getBindingState(geometry, program, material) { - const wireframe = material.wireframe === true; - let programMap = bindingStates[geometry.id]; - if (programMap === undefined) { - programMap = {}; - bindingStates[geometry.id] = programMap; + + setPath( path ) { + + this.path = path; + return this; + + } + + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + setRequestHeader( requestHeader ) { + + this.requestHeader = requestHeader; + return this; + + } + +} + +Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT'; + +class ImageLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + } - let stateMap = programMap[program.id]; - if (stateMap === undefined) { - stateMap = {}; - programMap[program.id] = stateMap; + + const image = createElementNS( 'img' ); + + function onImageLoad() { + + removeEventListeners(); + + Cache.add( url, this ); + + if ( onLoad ) onLoad( this ); + + scope.manager.itemEnd( url ); + } - let state = stateMap[wireframe]; - if (state === undefined) { - state = createBindingState(createVertexArrayObject()); - stateMap[wireframe] = state; + + function onImageError( event ) { + + removeEventListeners(); + + if ( onError ) onError( event ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + } - return state; - } - function createBindingState(vao) { - const newAttributes = []; - const enabledAttributes = []; - const attributeDivisors = []; - for (let i = 0; i < maxVertexAttributes; i++) { - newAttributes[i] = 0; - enabledAttributes[i] = 0; - attributeDivisors[i] = 0; + + function removeEventListeners() { + + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); + } - return { - // for backward compatibility on non-VAO support browser - geometry: null, - program: null, - wireframe: false, - newAttributes: newAttributes, - enabledAttributes: enabledAttributes, - attributeDivisors: attributeDivisors, - object: vao, - attributes: {}, - index: null - }; - } - function needsUpdate(object, geometry, program, index) { - const cachedAttributes = currentState.attributes; - const geometryAttributes = geometry.attributes; - let attributesNum = 0; - const programAttributes = program.getAttributes(); - for (const name in programAttributes) { - const programAttribute = programAttributes[name]; - if (programAttribute.location >= 0) { - const cachedAttribute = cachedAttributes[name]; - let geometryAttribute = geometryAttributes[name]; - if (geometryAttribute === undefined) { - if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix; - if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor; - } - if (cachedAttribute === undefined) return true; - if (cachedAttribute.attribute !== geometryAttribute) return true; - if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true; - attributesNum++; - } + + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); + + if ( url.slice( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + } - if (currentState.attributesNum !== attributesNum) return true; - if (currentState.index !== index) return true; - return false; + + scope.manager.itemStart( url ); + + image.src = url; + + return image; + } - function saveCache(object, geometry, program, index) { - const cache = {}; - const attributes = geometry.attributes; - let attributesNum = 0; - const programAttributes = program.getAttributes(); - for (const name in programAttributes) { - const programAttribute = programAttributes[name]; - if (programAttribute.location >= 0) { - let attribute = attributes[name]; - if (attribute === undefined) { - if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix; - if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor; - } - const data = {}; - data.attribute = attribute; - if (attribute && attribute.data) { - data.data = attribute.data; - } - cache[name] = data; - attributesNum++; + +} + +class TextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const texture = new Texture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + loader.load( url, function ( image ) { + + texture.image = image; + texture.needsUpdate = true; + + if ( onLoad !== undefined ) { + + onLoad( texture ); + } - } - currentState.attributes = cache; - currentState.attributesNum = attributesNum; - currentState.index = index; + + }, onProgress, onError ); + + return texture; + } - function initAttributes() { - const newAttributes = currentState.newAttributes; - for (let i = 0, il = newAttributes.length; i < il; i++) { - newAttributes[i] = 0; - } + +} + +class Light extends Object3D { + + constructor( color, intensity = 1 ) { + + super(); + + this.isLight = true; + + this.type = 'Light'; + + this.color = new Color( color ); + this.intensity = intensity; + } - function enableAttribute(attribute) { - enableAttributeAndDivisor(attribute, 0); + + dispose() { + + // Empty here in base class; some subclasses override. + } - function enableAttributeAndDivisor(attribute, meshPerAttribute) { - const newAttributes = currentState.newAttributes; - const enabledAttributes = currentState.enabledAttributes; - const attributeDivisors = currentState.attributeDivisors; - newAttributes[attribute] = 1; - if (enabledAttributes[attribute] === 0) { - gl.enableVertexAttribArray(attribute); - enabledAttributes[attribute] = 1; - } - if (attributeDivisors[attribute] !== meshPerAttribute) { - const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays'); - extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute); - attributeDivisors[attribute] = meshPerAttribute; - } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.color.copy( source.color ); + this.intensity = source.intensity; + + return this; + } - function disableUnusedAttributes() { - const newAttributes = currentState.newAttributes; - const enabledAttributes = currentState.enabledAttributes; - for (let i = 0, il = enabledAttributes.length; i < il; i++) { - if (enabledAttributes[i] !== newAttributes[i]) { - gl.disableVertexAttribArray(i); - enabledAttributes[i] = 0; - } - } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; + + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + + return data; + } - function vertexAttribPointer(index, size, type, normalized, stride, offset) { - if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) { - gl.vertexAttribIPointer(index, size, type, stride, offset); - } else { - gl.vertexAttribPointer(index, size, type, normalized, stride, offset); - } + +} + +class HemisphereLight extends Light { + + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.groundColor = new Color( groundColor ); + } - function setupVertexAttributes(object, material, program, geometry) { - if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) { - if (extensions.get('ANGLE_instanced_arrays') === null) return; - } - initAttributes(); - const geometryAttributes = geometry.attributes; - const programAttributes = program.getAttributes(); - const materialDefaultAttributeValues = material.defaultAttributeValues; - for (const name in programAttributes) { - const programAttribute = programAttributes[name]; - if (programAttribute.location >= 0) { - let geometryAttribute = geometryAttributes[name]; - if (geometryAttribute === undefined) { - if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix; - if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor; - } - if (geometryAttribute !== undefined) { - const normalized = geometryAttribute.normalized; - const size = geometryAttribute.itemSize; - const attribute = attributes.get(geometryAttribute); - // TODO Attribute may not be available on context restore + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; - if (attribute === undefined) continue; - const buffer = attribute.buffer; - const type = attribute.type; - const bytesPerElement = attribute.bytesPerElement; - if (geometryAttribute.isInterleavedBufferAttribute) { - const data = geometryAttribute.data; - const stride = data.stride; - const offset = geometryAttribute.offset; - if (data.isInstancedInterleavedBuffer) { - for (let i = 0; i < programAttribute.locationSize; i++) { - enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute); - } - if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { - geometry._maxInstanceCount = data.meshPerAttribute * data.count; - } - } else { - for (let i = 0; i < programAttribute.locationSize; i++) { - enableAttribute(programAttribute.location + i); - } - } - gl.bindBuffer(gl.ARRAY_BUFFER, buffer); - for (let i = 0; i < programAttribute.locationSize; i++) { - vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement); - } - } else { - if (geometryAttribute.isInstancedBufferAttribute) { - for (let i = 0; i < programAttribute.locationSize; i++) { - enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); - } - if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { - geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - } - } else { - for (let i = 0; i < programAttribute.locationSize; i++) { - enableAttribute(programAttribute.location + i); - } - } - gl.bindBuffer(gl.ARRAY_BUFFER, buffer); - for (let i = 0; i < programAttribute.locationSize; i++) { - vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement); - } - } - } else if (materialDefaultAttributeValues !== undefined) { - const value = materialDefaultAttributeValues[name]; - if (value !== undefined) { - switch (value.length) { - case 2: - gl.vertexAttrib2fv(programAttribute.location, value); - break; - case 3: - gl.vertexAttrib3fv(programAttribute.location, value); - break; - case 4: - gl.vertexAttrib4fv(programAttribute.location, value); - break; - default: - gl.vertexAttrib1fv(programAttribute.location, value); - } - } - } - } - } - disableUnusedAttributes(); } - function dispose() { - reset(); - for (const geometryId in bindingStates) { - const programMap = bindingStates[geometryId]; - for (const programId in programMap) { - const stateMap = programMap[programId]; - for (const wireframe in stateMap) { - deleteVertexArrayObject(stateMap[wireframe].object); - delete stateMap[wireframe]; - } - delete programMap[programId]; - } - delete bindingStates[geometryId]; + +} + +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); +const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + +class LightShadow { + + constructor( camera ) { + + this.camera = camera; + + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + + this.mapSize = new Vector2( 512, 512 ); + + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + + this.autoUpdate = true; + this.needsUpdate = false; + + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); + + this._viewportCount = 1; + + this._viewports = [ + + new Vector4( 0, 0, 1, 1 ) + + ]; + + } + + getViewportCount() { + + return this._viewportCount; + + } + + getFrustum() { + + return this._frustum; + + } + + updateMatrices( light ) { + + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); + + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); + + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + + shadowMatrix.set( + 0.5, 0.0, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); + + shadowMatrix.multiply( _projScreenMatrix$1 ); + + } + + getViewport( viewportIndex ) { + + return this._viewports[ viewportIndex ]; + + } + + getFrameExtents() { + + return this._frameExtents; + + } + + dispose() { + + if ( this.map ) { + + this.map.dispose(); + + } + + if ( this.mapPass ) { + + this.mapPass.dispose(); + } + } - function releaseStatesOfGeometry(geometry) { - if (bindingStates[geometry.id] === undefined) return; - const programMap = bindingStates[geometry.id]; - for (const programId in programMap) { - const stateMap = programMap[programId]; - for (const wireframe in stateMap) { - deleteVertexArrayObject(stateMap[wireframe].object); - delete stateMap[wireframe]; - } - delete programMap[programId]; - } - delete bindingStates[geometry.id]; - } - function releaseStatesOfProgram(program) { - for (const geometryId in bindingStates) { - const programMap = bindingStates[geometryId]; - if (programMap[program.id] === undefined) continue; - const stateMap = programMap[program.id]; - for (const wireframe in stateMap) { - deleteVertexArrayObject(stateMap[wireframe].object); - delete stateMap[wireframe]; - } - delete programMap[program.id]; - } + + copy( source ) { + + this.camera = source.camera.clone(); + + this.bias = source.bias; + this.radius = source.radius; + + this.mapSize.copy( source.mapSize ); + + return this; + } - function reset() { - resetDefaultState(); - forceUpdate = true; - if (currentState === defaultState) return; - currentState = defaultState; - bindVertexArrayObject(currentState.object); + + clone() { + + return new this.constructor().copy( this ); + } - // for backward-compatibility + toJSON() { + + const object = {}; + + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; + + return object; - function resetDefaultState() { - defaultState.geometry = null; - defaultState.program = null; - defaultState.wireframe = false; } - return { - setup: setup, - reset: reset, - resetDefaultState: resetDefaultState, - dispose: dispose, - releaseStatesOfGeometry: releaseStatesOfGeometry, - releaseStatesOfProgram: releaseStatesOfProgram, - initAttributes: initAttributes, - enableAttribute: enableAttribute, - disableUnusedAttributes: disableUnusedAttributes - }; + } -function WebGLBufferRenderer(gl, extensions, info, capabilities) { - const isWebGL2 = capabilities.isWebGL2; - let mode; - function setMode(value) { - mode = value; - } - function render(start, count) { - gl.drawArrays(mode, start, count); - info.update(count, mode, 1); +class DirectionalLightShadow extends LightShadow { + + constructor() { + + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + + this.isDirectionalLightShadow = true; + } - function renderInstances(start, count, primcount) { - if (primcount === 0) return; - let extension, methodName; - if (isWebGL2) { - extension = gl; - methodName = 'drawArraysInstanced'; - } else { - extension = extensions.get('ANGLE_instanced_arrays'); - methodName = 'drawArraysInstancedANGLE'; - if (extension === null) { - console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.'); - return; - } - } - extension[methodName](mode, start, count, primcount); - info.update(count, mode, primcount); + +} + +class DirectionalLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isDirectionalLight = true; + + this.type = 'DirectionalLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.shadow = new DirectionalLightShadow(); + } - // + dispose() { - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; -} + this.shadow.dispose(); -function WebGLCapabilities(gl, extensions, parameters) { - let maxAnisotropy; - function getMaxAnisotropy() { - if (maxAnisotropy !== undefined) return maxAnisotropy; - if (extensions.has('EXT_texture_filter_anisotropic') === true) { - const extension = extensions.get('EXT_texture_filter_anisotropic'); - maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); - } else { - maxAnisotropy = 0; - } - return maxAnisotropy; } - function getMaxPrecision(precision) { - if (precision === 'highp') { - if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { - return 'highp'; - } - precision = 'mediump'; - } - if (precision === 'mediump') { - if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { - return 'mediump'; - } - } - return 'lowp'; + + copy( source ) { + + super.copy( source ); + + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + + return this; + } - const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext; - let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - const maxPrecision = getMaxPrecision(precision); - if (maxPrecision !== precision) { - console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.'); - precision = maxPrecision; + +} + +class AmbientLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isAmbientLight = true; + + this.type = 'AmbientLight'; + } - const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers'); - const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; - const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); - const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); - const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); - const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); - const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); - const vertexTextures = maxVertexTextures > 0; - const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float'); - const floatVertexTextures = vertexTextures && floatFragmentTextures; - const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0; - return { - isWebGL2: isWebGL2, - drawBuffers: drawBuffers, - getMaxAnisotropy: getMaxAnisotropy, - getMaxPrecision: getMaxPrecision, - precision: precision, - logarithmicDepthBuffer: logarithmicDepthBuffer, - maxTextures: maxTextures, - maxVertexTextures: maxVertexTextures, - maxTextureSize: maxTextureSize, - maxCubemapSize: maxCubemapSize, - maxAttributes: maxAttributes, - maxVertexUniforms: maxVertexUniforms, - maxVaryings: maxVaryings, - maxFragmentUniforms: maxFragmentUniforms, - vertexTextures: vertexTextures, - floatFragmentTextures: floatFragmentTextures, - floatVertexTextures: floatVertexTextures, - maxSamples: maxSamples - }; + } -function WebGLClipping(properties) { - const scope = this; - let globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false; - const plane = new Plane(), - viewNormalMatrix = new Matrix3(), - uniform = { - value: null, - needsUpdate: false +class Raycaster { + + constructor( origin, direction, near = 0, far = Infinity ) { + + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) + + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} }; - this.uniform = uniform; - this.numPlanes = 0; - this.numIntersection = 0; - this.init = function (planes, enableLocalClipping, camera) { - const enabled = planes.length !== 0 || enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || localClippingEnabled; - localClippingEnabled = enableLocalClipping; - globalState = projectPlanes(planes, camera, 0); - numGlobalPlanes = planes.length; - return enabled; - }; - this.beginShadows = function () { - renderingShadows = true; - projectPlanes(null); - }; - this.endShadows = function () { - renderingShadows = false; - resetGlobalState(); - }; - this.setState = function (material, camera, useCache) { - const planes = material.clippingPlanes, - clipIntersection = material.clipIntersection, - clipShadows = material.clipShadows; - const materialProperties = properties.get(material); - if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { - // there's no local clipping - if (renderingShadows) { - // there's no global clipping + } + + set( origin, direction ) { + + // direction is assumed to be normalized (for accurate distance calculations) + + this.ray.set( origin, direction ); + + } + + setFromCamera( coords, camera ) { + + if ( camera.isPerspectiveCamera ) { + + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; + + } else if ( camera.isOrthographicCamera ) { + + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + this.camera = camera; - projectPlanes(null); - } else { - resetGlobalState(); - } } else { - const nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4; - let dstArray = materialProperties.clippingState || null; - uniform.value = dstArray; // ensure unique state - dstArray = projectPlanes(planes, camera, lGlobal, useCache); - for (let i = 0; i !== lGlobal; ++i) { - dstArray[i] = globalState[i]; - } - materialProperties.clippingState = dstArray; - this.numIntersection = clipIntersection ? this.numPlanes : 0; - this.numPlanes += nGlobal; - } - }; - function resetGlobalState() { - if (uniform.value !== globalState) { - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + } - scope.numPlanes = numGlobalPlanes; - scope.numIntersection = 0; + } - function projectPlanes(planes, camera, dstOffset, skipTransform) { - const nPlanes = planes !== null ? planes.length : 0; - let dstArray = null; - if (nPlanes !== 0) { - dstArray = uniform.value; - if (skipTransform !== true || dstArray === null) { - const flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; - viewNormalMatrix.getNormalMatrix(viewMatrix); - if (dstArray === null || dstArray.length < flatSize) { - dstArray = new Float32Array(flatSize); - } - for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) { - plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); - plane.normal.toArray(dstArray, i4); - dstArray[i4 + 3] = plane.constant; - } - } - uniform.value = dstArray; - uniform.needsUpdate = true; + + intersectObject( object, recursive = true, intersects = [] ) { + + intersectObject( object, this, intersects, recursive ); + + intersects.sort( ascSort ); + + return intersects; + + } + + intersectObjects( objects, recursive = true, intersects = [] ) { + + for ( let i = 0, l = objects.length; i < l; i ++ ) { + + intersectObject( objects[ i ], this, intersects, recursive ); + } - scope.numPlanes = nPlanes; - scope.numIntersection = 0; - return dstArray; + + intersects.sort( ascSort ); + + return intersects; + } + } -class Camera extends Object3D { - constructor() { - super(); - this.isCamera = true; - this.type = 'Camera'; - this.matrixWorldInverse = new Matrix4(); - this.projectionMatrix = new Matrix4(); - this.projectionMatrixInverse = new Matrix4(); - } - copy(source, recursive) { - super.copy(source, recursive); - this.matrixWorldInverse.copy(source.matrixWorldInverse); - this.projectionMatrix.copy(source.projectionMatrix); - this.projectionMatrixInverse.copy(source.projectionMatrixInverse); - return this; - } - getWorldDirection(target) { - this.updateWorldMatrix(true, false); - const e = this.matrixWorld.elements; - return target.set(-e[8], -e[9], -e[10]).normalize(); - } - updateMatrixWorld(force) { - super.updateMatrixWorld(force); - this.matrixWorldInverse.copy(this.matrixWorld).invert(); - } - updateWorldMatrix(updateParents, updateChildren) { - super.updateWorldMatrix(updateParents, updateChildren); - this.matrixWorldInverse.copy(this.matrixWorld).invert(); - } - clone() { - return new this.constructor().copy(this); - } +function ascSort( a, b ) { + + return a.distance - b.distance; + } -class PerspectiveCamera extends Camera { - constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) { - super(); - this.isPerspectiveCamera = true; - this.type = 'PerspectiveCamera'; - this.fov = fov; - this.zoom = 1; - this.near = near; - this.far = far; - this.focus = 10; - this.aspect = aspect; - this.view = null; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) +function intersectObject( object, raycaster, intersects, recursive ) { + + if ( object.layers.test( raycaster.layers ) ) { + + object.raycast( raycaster, intersects ); - this.updateProjectionMatrix(); - } - copy(source, recursive) { - super.copy(source, recursive); - this.fov = source.fov; - this.zoom = source.zoom; - this.near = source.near; - this.far = source.far; - this.focus = source.focus; - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign({}, source.view); - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; - return this; } - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength(focalLength) { - /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ - const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); - this.updateProjectionMatrix(); + if ( recursive === true ) { + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + intersectObject( children[ i ], raycaster, intersects, true ); + + } + } - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength() { - const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); - return 0.5 * this.getFilmHeight() / vExtentSlope; +} + +class Clock { + + constructor( autoStart = true ) { + + this.autoStart = autoStart; + + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + + this.running = false; + } - getEffectiveFOV() { - return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom); + + start() { + + this.startTime = now(); + + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } - getFilmWidth() { - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min(this.aspect, 1); + + stop() { + + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } - getFilmHeight() { - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max(this.aspect, 1); + + getElapsedTime() { + + this.getDelta(); + return this.elapsedTime; + } - /** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * const w = 1920; - * const h = 1080; - * const fullWidth = w * 3; - * const fullHeight = h * 2; - * - * --A-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - setViewOffset(fullWidth, fullHeight, x, y, width, height) { - this.aspect = fullWidth / fullHeight; - if (this.view === null) { - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; + getDelta() { + + let diff = 0; + + if ( this.autoStart && ! this.running ) { + + this.start(); + return 0; + } - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; - this.updateProjectionMatrix(); - } - clearViewOffset() { - if (this.view !== null) { - this.view.enabled = false; + + if ( this.running ) { + + const newTime = now(); + + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; + + this.elapsedTime += diff; + } - this.updateProjectionMatrix(); + + return diff; + } - updateProjectionMatrix() { - const near = this.near; - let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; - let height = 2 * top; - let width = this.aspect * height; - let left = -0.5 * width; - const view = this.view; - if (this.view !== null && this.view.enabled) { - const fullWidth = view.fullWidth, - fullHeight = view.fullHeight; - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; - } - const skew = this.filmOffset; - if (skew !== 0) left += near * skew / this.getFilmWidth(); - this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far); - this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + +} + +function now() { + + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + +} + +/** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ + + +class Spherical { + + constructor( radius = 1, phi = 0, theta = 0 ) { + + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle + + return this; + } - toJSON(meta) { - const data = super.toJSON(meta); - data.object.fov = this.fov; - data.object.zoom = this.zoom; - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; - data.object.aspect = this.aspect; - if (this.view !== null) data.object.view = Object.assign({}, this.view); - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; - return data; + + set( radius, phi, theta ) { + + this.radius = radius; + this.phi = phi; + this.theta = theta; + + return this; + } -} -const fov = 90, - aspect = 1; -class CubeCamera extends Object3D { - constructor(near, far, renderTarget) { - super(); - this.type = 'CubeCamera'; - this.renderTarget = renderTarget; - const cameraPX = new PerspectiveCamera(fov, aspect, near, far); - cameraPX.layers = this.layers; - cameraPX.up.set(0, -1, 0); - cameraPX.lookAt(new Vector3(1, 0, 0)); - this.add(cameraPX); - const cameraNX = new PerspectiveCamera(fov, aspect, near, far); - cameraNX.layers = this.layers; - cameraNX.up.set(0, -1, 0); - cameraNX.lookAt(new Vector3(-1, 0, 0)); - this.add(cameraNX); - const cameraPY = new PerspectiveCamera(fov, aspect, near, far); - cameraPY.layers = this.layers; - cameraPY.up.set(0, 0, 1); - cameraPY.lookAt(new Vector3(0, 1, 0)); - this.add(cameraPY); - const cameraNY = new PerspectiveCamera(fov, aspect, near, far); - cameraNY.layers = this.layers; - cameraNY.up.set(0, 0, -1); - cameraNY.lookAt(new Vector3(0, -1, 0)); - this.add(cameraNY); - const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); - cameraPZ.layers = this.layers; - cameraPZ.up.set(0, -1, 0); - cameraPZ.lookAt(new Vector3(0, 0, 1)); - this.add(cameraPZ); - const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); - cameraNZ.layers = this.layers; - cameraNZ.up.set(0, -1, 0); - cameraNZ.lookAt(new Vector3(0, 0, -1)); - this.add(cameraNZ); + copy( other ) { + + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + + return this; + } - update(renderer, scene) { - if (this.parent === null) this.updateMatrixWorld(); - const renderTarget = this.renderTarget; - const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; - const currentRenderTarget = renderer.getRenderTarget(); - const currentToneMapping = renderer.toneMapping; - const currentXrEnabled = renderer.xr.enabled; - renderer.toneMapping = NoToneMapping; - renderer.xr.enabled = false; - const generateMipmaps = renderTarget.texture.generateMipmaps; - renderTarget.texture.generateMipmaps = false; - renderer.setRenderTarget(renderTarget, 0); - renderer.render(scene, cameraPX); - renderer.setRenderTarget(renderTarget, 1); - renderer.render(scene, cameraNX); - renderer.setRenderTarget(renderTarget, 2); - renderer.render(scene, cameraPY); - renderer.setRenderTarget(renderTarget, 3); - renderer.render(scene, cameraNY); - renderer.setRenderTarget(renderTarget, 4); - renderer.render(scene, cameraPZ); - renderTarget.texture.generateMipmaps = generateMipmaps; - renderer.setRenderTarget(renderTarget, 5); - renderer.render(scene, cameraNZ); - renderer.setRenderTarget(currentRenderTarget); - renderer.toneMapping = currentToneMapping; - renderer.xr.enabled = currentXrEnabled; - renderTarget.texture.needsPMREMUpdate = true; + + // restrict phi to be between EPS and PI-EPS + makeSafe() { + + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + + return this; + } -} -class CubeTexture extends Texture { - constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) { - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); - this.isCubeTexture = true; - this.flipY = false; - } - get images() { - return this.image; + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + y * y + z * z ); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); + + } + + return this; + } - set images(value) { - this.image = value; + + clone() { + + return new this.constructor().copy( this ); + } -} -class WebGLCubeRenderTarget extends WebGLRenderTarget { - constructor(size = 1, options = {}) { - super(size, size, options); - this.isWebGLCubeRenderTarget = true; - const image = { - width: size, - height: size, - depth: 1 - }; - const images = [image, image, image, image, image, image]; - this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); +} - // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) - // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, - // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. +const _vector = /*@__PURE__*/ new Vector2(); - // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped - // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture - // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). +class Box2 { - this.texture.isRenderTargetTexture = true; - this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; - this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - } - fromEquirectangularTexture(renderer, texture) { - this.texture.type = texture.type; - this.texture.encoding = texture.encoding; - this.texture.generateMipmaps = texture.generateMipmaps; - this.texture.minFilter = texture.minFilter; - this.texture.magFilter = texture.magFilter; - const shader = { - uniforms: { - tEquirect: { - value: null - } - }, - vertexShader: /* glsl */` + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { - varying vec3 vWorldDirection; + this.isBox2 = true; - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + this.min = min; + this.max = max; - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + } - } + set( min, max ) { - void main() { + this.min.copy( min ); + this.max.copy( max ); - vWorldDirection = transformDirection( position, modelMatrix ); + return this; - #include - #include + } - } - `, - fragmentShader: /* glsl */` + setFromPoints( points ) { - uniform sampler2D tEquirect; + this.makeEmpty(); - varying vec3 vWorldDirection; + for ( let i = 0, il = points.length; i < il; i ++ ) { - #include + this.expandByPoint( points[ i ] ); - void main() { + } - vec3 direction = normalize( vWorldDirection ); + return this; - vec2 sampleUV = equirectUv( direction ); + } - gl_FragColor = texture2D( tEquirect, sampleUV ); + setFromCenterAndSize( center, size ) { - } - ` - }; - const geometry = new BoxGeometry(5, 5, 5); - const material = new ShaderMaterial({ - name: 'CubemapFromEquirect', - uniforms: cloneUniforms(shader.uniforms), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - side: BackSide, - blending: NoBlending - }); - material.uniforms.tEquirect.value = texture; - const mesh = new Mesh(geometry, material); - const currentMinFilter = texture.minFilter; + const halfSize = _vector.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - // Avoid blurred poles - if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter; - const camera = new CubeCamera(1, 10, this); - camera.update(renderer, mesh); - texture.minFilter = currentMinFilter; - mesh.geometry.dispose(); - mesh.material.dispose(); return this; + } - clear(renderer, color, depth, stencil) { - const currentRenderTarget = renderer.getRenderTarget(); - for (let i = 0; i < 6; i++) { - renderer.setRenderTarget(this, i); - renderer.clear(color, depth, stencil); - } - renderer.setRenderTarget(currentRenderTarget); + + clone() { + + return new this.constructor().copy( this ); + } -} -function WebGLCubeMaps(renderer) { - let cubemaps = new WeakMap(); - function mapTextureMapping(texture, mapping) { - if (mapping === EquirectangularReflectionMapping) { - texture.mapping = CubeReflectionMapping; - } else if (mapping === EquirectangularRefractionMapping) { - texture.mapping = CubeRefractionMapping; - } - return texture; + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + } - function get(texture) { - if (texture && texture.isTexture && texture.isRenderTargetTexture === false) { - const mapping = texture.mapping; - if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { - if (cubemaps.has(texture)) { - const cubemap = cubemaps.get(texture).texture; - return mapTextureMapping(cubemap, texture.mapping); - } else { - const image = texture.image; - if (image && image.height > 0) { - const renderTarget = new WebGLCubeRenderTarget(image.height / 2); - renderTarget.fromEquirectangularTexture(renderer, texture); - cubemaps.set(texture, renderTarget); - texture.addEventListener('dispose', onTextureDispose); - return mapTextureMapping(renderTarget.texture, texture.mapping); - } else { - // image not yet ready. try the conversion next frame - return null; - } - } - } - } - return texture; + makeEmpty() { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + } - function onTextureDispose(event) { - const texture = event.target; - texture.removeEventListener('dispose', onTextureDispose); - const cubemap = cubemaps.get(texture); - if (cubemap !== undefined) { - cubemaps.delete(texture); - cubemap.dispose(); - } + + isEmpty() { + + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + } - function dispose() { - cubemaps = new WeakMap(); + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + } - return { - get: get, - dispose: dispose - }; -} -class OrthographicCamera extends Camera { - constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { - super(); - this.isOrthographicCamera = true; - this.type = 'OrthographicCamera'; - this.zoom = 1; - this.view = null; - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; - this.near = near; - this.far = far; - this.updateProjectionMatrix(); + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + } - copy(source, recursive) { - super.copy(source, recursive); - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign({}, source.view); + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + return this; + } - setViewOffset(fullWidth, fullHeight, x, y, width, height) { - if (this.view === null) { - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; - } - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; - this.updateProjectionMatrix(); + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + } - clearViewOffset() { - if (this.view !== null) { - this.view.enabled = false; - } - this.updateProjectionMatrix(); + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + } - updateProjectionMatrix() { - const dx = (this.right - this.left) / (2 * this.zoom); - const dy = (this.top - this.bottom) / (2 * this.zoom); - const cx = (this.right + this.left) / 2; - const cy = (this.top + this.bottom) / 2; - let left = cx - dx; - let right = cx + dx; - let top = cy + dy; - let bottom = cy - dy; - if (this.view !== null && this.view.enabled) { - const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; - const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; - left += scaleW * this.view.offsetX; - right = left + scaleW * this.view.width; - top -= scaleH * this.view.offsetY; - bottom = top - scaleH * this.view.height; - } - this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far); - this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + + containsPoint( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; + } - toJSON(meta) { - const data = super.toJSON(meta); - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; - if (this.view !== null) data.object.view = Object.assign({}, this.view); - return data; + + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + } -} -const LOD_MIN = 4; + getParameter( point, target ) { -// The standard deviations (radians) associated with the extra mips. These are -// chosen to approximate a Trowbridge-Reitz distribution function times the -// geometric shadowing function. These sigma values squared must match the -// variance #defines in cube_uv_reflection_fragment.glsl.js. -const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. -// The maximum length of the blur for loop. Smaller sigmas will use fewer -// samples and exit early, but not recompile the shader. -const MAX_SAMPLES = 20; -const _flatCamera = /*@__PURE__*/new OrthographicCamera(); -const _clearColor = /*@__PURE__*/new Color$1(); -let _oldTarget = null; + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); -// Golden Ratio -const PHI = (1 + Math.sqrt(5)) / 2; -const INV_PHI = 1 / PHI; + } -// Vertices of a dodecahedron (except the opposites, which represent the -// same axis), used as axis directions evenly spread on a sphere. -const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)]; + intersectsBox( box ) { -/** - * This class generates a Prefiltered, Mipmapped Radiance Environment Map - * (PMREM) from a cubeMap environment texture. This allows different levels of - * blur to be quickly accessed based on material roughness. It is packed into a - * special CubeUV format that allows us to perform custom interpolation so that - * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap - * chain, it only goes down to the LOD_MIN level (above), and then creates extra - * even more filtered 'mips' at the same LOD_MIN resolution, associated with - * higher roughness levels. In this way we maintain resolution to smoothly - * interpolate diffuse lighting while limiting sampling computation. - * - * Paper: Fast, Accurate Image-Based Lighting - * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view -*/ + // using 4 splitting planes to rule out intersections + + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; -class PMREMGenerator { - constructor(renderer) { - this._renderer = renderer; - this._pingPongRenderTarget = null; - this._lodMax = 0; - this._cubeSize = 0; - this._lodPlanes = []; - this._sizeLods = []; - this._sigmas = []; - this._blurMaterial = null; - this._cubemapMaterial = null; - this._equirectMaterial = null; - this._compileMaterial(this._blurMaterial); } - /** - * Generates a PMREM from a supplied Scene, which can be faster than using an - * image if networking bandwidth is low. Optional sigma specifies a blur radius - * in radians to be applied to the scene before PMREM generation. Optional near - * and far planes ensure the scene is rendered in its entirety (the cubeCamera - * is placed at the origin). - */ - fromScene(scene, sigma = 0, near = 0.1, far = 100) { - _oldTarget = this._renderer.getRenderTarget(); - this._setSize(256); - const cubeUVRenderTarget = this._allocateTargets(); - cubeUVRenderTarget.depthBuffer = true; - this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); - if (sigma > 0) { - this._blur(cubeUVRenderTarget, 0, 0, sigma); - } - this._applyPMREM(cubeUVRenderTarget); - this._cleanup(cubeUVRenderTarget); - return cubeUVRenderTarget; + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + } - /** - * Generates a PMREM from an equirectangular texture, which can be either LDR - * or HDR. The ideal input image size is 1k (1024 x 512), - * as this matches best with the 256 x 256 cubemap output. - */ - fromEquirectangular(equirectangular, renderTarget = null) { - return this._fromTexture(equirectangular, renderTarget); + distanceToPoint( point ) { + + return this.clampPoint( point, _vector ).distanceTo( point ); + } - /** - * Generates a PMREM from an cubemap texture, which can be either LDR - * or HDR. The ideal input cube size is 256 x 256, - * as this matches best with the 256 x 256 cubemap output. - */ - fromCubemap(cubemap, renderTarget = null) { - return this._fromTexture(cubemap, renderTarget); + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + if ( this.isEmpty() ) this.makeEmpty(); + + return this; + } - /** - * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileCubemapShader() { - if (this._cubemapMaterial === null) { - this._cubemapMaterial = _getCubemapMaterial(); - this._compileMaterial(this._cubemapMaterial); - } + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + } - /** - * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileEquirectangularShader() { - if (this._equirectMaterial === null) { - this._equirectMaterial = _getEquirectMaterial(); - this._compileMaterial(this._equirectMaterial); - } + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + } - /** - * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, - * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on - * one of them will cause any others to also become unusable. - */ - dispose() { - this._dispose(); - if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose(); - if (this._equirectMaterial !== null) this._equirectMaterial.dispose(); + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + } - // private interface +} + +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); + +class Line3 { + + constructor( start = new Vector3(), end = new Vector3() ) { + + this.start = start; + this.end = end; - _setSize(cubeSize) { - this._lodMax = Math.floor(Math.log2(cubeSize)); - this._cubeSize = Math.pow(2, this._lodMax); } - _dispose() { - if (this._blurMaterial !== null) this._blurMaterial.dispose(); - if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose(); - for (let i = 0; i < this._lodPlanes.length; i++) { - this._lodPlanes[i].dispose(); - } + + set( start, end ) { + + this.start.copy( start ); + this.end.copy( end ); + + return this; + } - _cleanup(outputTarget) { - this._renderer.setRenderTarget(_oldTarget); - outputTarget.scissorTest = false; - _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + + copy( line ) { + + this.start.copy( line.start ); + this.end.copy( line.end ); + + return this; + } - _fromTexture(texture, renderTarget) { - if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { - this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); - } else { - // Equirectangular - this._setSize(texture.image.width / 4); - } - _oldTarget = this._renderer.getRenderTarget(); - const cubeUVRenderTarget = renderTarget || this._allocateTargets(); - this._textureToCubeUV(texture, cubeUVRenderTarget); - this._applyPMREM(cubeUVRenderTarget); - this._cleanup(cubeUVRenderTarget); - return cubeUVRenderTarget; + getCenter( target ) { + + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + } - _allocateTargets() { - const width = 3 * Math.max(this._cubeSize, 16 * 7); - const height = 4 * this._cubeSize; - const params = { - magFilter: LinearFilter, - minFilter: LinearFilter, - generateMipmaps: false, - type: HalfFloatType, - format: RGBAFormat, - encoding: LinearEncoding, - depthBuffer: false - }; - const cubeUVRenderTarget = _createRenderTarget(width, height, params); - if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) { - if (this._pingPongRenderTarget !== null) { - this._dispose(); - } - this._pingPongRenderTarget = _createRenderTarget(width, height, params); - const { - _lodMax - } = this; - ({ - sizeLods: this._sizeLods, - lodPlanes: this._lodPlanes, - sigmas: this._sigmas - } = _createPlanes(_lodMax)); - this._blurMaterial = _getBlurShader(_lodMax, width, height); - } - return cubeUVRenderTarget; + + delta( target ) { + + return target.subVectors( this.end, this.start ); + } - _compileMaterial(material) { - const tmpMesh = new Mesh(this._lodPlanes[0], material); - this._renderer.compile(tmpMesh, _flatCamera); + + distanceSq() { + + return this.start.distanceToSquared( this.end ); + } - _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { - const fov = 90; - const aspect = 1; - const cubeCamera = new PerspectiveCamera(fov, aspect, near, far); - const upSign = [1, -1, 1, 1, 1, 1]; - const forwardSign = [1, 1, 1, -1, -1, -1]; - const renderer = this._renderer; - const originalAutoClear = renderer.autoClear; - const toneMapping = renderer.toneMapping; - renderer.getClearColor(_clearColor); - renderer.toneMapping = NoToneMapping; - renderer.autoClear = false; - const backgroundMaterial = new MeshBasicMaterial({ - name: 'PMREM.Background', - side: BackSide, - depthWrite: false, - depthTest: false - }); - const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial); - let useSolidColor = false; - const background = scene.background; - if (background) { - if (background.isColor) { - backgroundMaterial.color.copy(background); - scene.background = null; - useSolidColor = true; - } - } else { - backgroundMaterial.color.copy(_clearColor); - useSolidColor = true; - } - for (let i = 0; i < 6; i++) { - const col = i % 3; - if (col === 0) { - cubeCamera.up.set(0, upSign[i], 0); - cubeCamera.lookAt(forwardSign[i], 0, 0); - } else if (col === 1) { - cubeCamera.up.set(0, 0, upSign[i]); - cubeCamera.lookAt(0, forwardSign[i], 0); - } else { - cubeCamera.up.set(0, upSign[i], 0); - cubeCamera.lookAt(0, 0, forwardSign[i]); - } - const size = this._cubeSize; - _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); - renderer.setRenderTarget(cubeUVRenderTarget); - if (useSolidColor) { - renderer.render(backgroundBox, cubeCamera); - } - renderer.render(scene, cubeCamera); - } - backgroundBox.geometry.dispose(); - backgroundBox.material.dispose(); - renderer.toneMapping = toneMapping; - renderer.autoClear = originalAutoClear; - scene.background = background; + + distance() { + + return this.start.distanceTo( this.end ); + } - _textureToCubeUV(texture, cubeUVRenderTarget) { - const renderer = this._renderer; - const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; - if (isCubeTexture) { - if (this._cubemapMaterial === null) { - this._cubemapMaterial = _getCubemapMaterial(); - } - this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; - } else { - if (this._equirectMaterial === null) { - this._equirectMaterial = _getEquirectMaterial(); - } - } - const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; - const mesh = new Mesh(this._lodPlanes[0], material); - const uniforms = material.uniforms; - uniforms['envMap'].value = texture; - const size = this._cubeSize; - _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); - renderer.setRenderTarget(cubeUVRenderTarget); - renderer.render(mesh, _flatCamera); + + at( t, target ) { + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + } - _applyPMREM(cubeUVRenderTarget) { - const renderer = this._renderer; - const autoClear = renderer.autoClear; - renderer.autoClear = false; - for (let i = 1; i < this._lodPlanes.length; i++) { - const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); - const poleAxis = _axisDirections[(i - 1) % _axisDirections.length]; - this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + + closestPointToPointParameter( point, clampToLine ) { + + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); + + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); + + let t = startEnd_startP / startEnd2; + + if ( clampToLine ) { + + t = clamp( t, 0, 1 ); + } - renderer.autoClear = autoClear; + + return t; + } - /** - * This is a two-pass Gaussian blur for a cubemap. Normally this is done - * vertically and horizontally, but this breaks down on a cube. Here we apply - * the blur latitudinally (around the poles), and then longitudinally (towards - * the poles) to approximate the orthogonally-separable blur. It is least - * accurate at the poles, but still does a decent job. - */ - _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { - const pingPongRenderTarget = this._pingPongRenderTarget; - this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis); - this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis); + closestPointToPoint( point, clampToLine, target ) { + + const t = this.closestPointToPointParameter( point, clampToLine ); + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + } - _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { - const renderer = this._renderer; - const blurMaterial = this._blurMaterial; - if (direction !== 'latitudinal' && direction !== 'longitudinal') { - console.error('blur direction must be either latitudinal or longitudinal!'); - } - // Number of standard deviations at which to cut off the discrete approximation. - const STANDARD_DEVIATIONS = 3; - const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); - const blurUniforms = blurMaterial.uniforms; - const pixels = this._sizeLods[lodIn] - 1; - const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); - const sigmaPixels = sigmaRadians / radiansPerPixel; - const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; - if (samples > MAX_SAMPLES) { - console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); - } - const weights = []; - let sum = 0; - for (let i = 0; i < MAX_SAMPLES; ++i) { - const x = i / sigmaPixels; - const weight = Math.exp(-x * x / 2); - weights.push(weight); - if (i === 0) { - sum += weight; - } else if (i < samples) { - sum += 2 * weight; - } - } - for (let i = 0; i < weights.length; i++) { - weights[i] = weights[i] / sum; - } - blurUniforms['envMap'].value = targetIn.texture; - blurUniforms['samples'].value = samples; - blurUniforms['weights'].value = weights; - blurUniforms['latitudinal'].value = direction === 'latitudinal'; - if (poleAxis) { - blurUniforms['poleAxis'].value = poleAxis; - } - const { - _lodMax - } = this; - blurUniforms['dTheta'].value = radiansPerPixel; - blurUniforms['mipInt'].value = _lodMax - lodIn; - const outputSize = this._sizeLods[lodOut]; - const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); - const y = 4 * (this._cubeSize - outputSize); - _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); - renderer.setRenderTarget(targetOut); - renderer.render(blurMesh, _flatCamera); - } -} -function _createPlanes(lodMax) { - const lodPlanes = []; - const sizeLods = []; - const sigmas = []; - let lod = lodMax; - const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; - for (let i = 0; i < totalLods; i++) { - const sizeLod = Math.pow(2, lod); - sizeLods.push(sizeLod); - let sigma = 1.0 / sizeLod; - if (i > lodMax - LOD_MIN) { - sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; - } else if (i === 0) { - sigma = 0; - } - sigmas.push(sigma); - const texelSize = 1.0 / (sizeLod - 2); - const min = -texelSize; - const max = 1 + texelSize; - const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; - const cubeFaces = 6; - const vertices = 6; - const positionSize = 3; - const uvSize = 2; - const faceIndexSize = 1; - const position = new Float32Array(positionSize * vertices * cubeFaces); - const uv = new Float32Array(uvSize * vertices * cubeFaces); - const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); - for (let face = 0; face < cubeFaces; face++) { - const x = face % 3 * 2 / 3 - 1; - const y = face > 2 ? 0 : -1; - const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0]; - position.set(coordinates, positionSize * vertices * face); - uv.set(uv1, uvSize * vertices * face); - const fill = [face, face, face, face, face, face]; - faceIndex.set(fill, faceIndexSize * vertices * face); - } - const planes = new BufferGeometry(); - planes.setAttribute('position', new BufferAttribute(position, positionSize)); - planes.setAttribute('uv', new BufferAttribute(uv, uvSize)); - planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize)); - lodPlanes.push(planes); - if (lod > LOD_MIN) { - lod--; - } + applyMatrix4( matrix ) { + + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); + + return this; + } - return { - lodPlanes, - sizeLods, - sigmas - }; -} -function _createRenderTarget(width, height, params) { - const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params); - cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; - cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; - cubeUVRenderTarget.scissorTest = true; - return cubeUVRenderTarget; -} -function _setViewport(target, x, y, width, height) { - target.viewport.set(x, y, width, height); - target.scissor.set(x, y, width, height); -} -function _getBlurShader(lodMax, width, height) { - const weights = new Float32Array(MAX_SAMPLES); - const poleAxis = new Vector3(0, 1, 0); - const shaderMaterial = new ShaderMaterial({ - name: 'SphericalGaussianBlur', - defines: { - 'n': MAX_SAMPLES, - 'CUBEUV_TEXEL_WIDTH': 1.0 / width, - 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, - 'CUBEUV_MAX_MIP': `${lodMax}.0` - }, - uniforms: { - 'envMap': { - value: null - }, - 'samples': { - value: 1 - }, - 'weights': { - value: weights - }, - 'latitudinal': { - value: false - }, - 'dTheta': { - value: 0 - }, - 'mipInt': { - value: 0 - }, - 'poleAxis': { - value: poleAxis - } - }, - vertexShader: _getCommonVertexShader(), - fragmentShader: /* glsl */` - precision mediump float; - precision mediump int; + equals( line ) { + + return line.start.equals( this.start ) && line.end.equals( this.end ); - varying vec3 vOutputDirection; + } - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; + clone() { - #define ENVMAP_TYPE_CUBE_UV - #include + return new this.constructor().copy( this ); - vec3 getSample( float theta, vec3 axis ) { + } - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); +} - return bilinearCubeUV( envMap, sampleDirection, mipInt ); +class PlaneHelper extends Line { - } + constructor( plane, size = 1, hex = 0xffff00 ) { - void main() { + const color = hex; - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - } + this.type = 'PlaneHelper'; - axis = normalize( axis ); + this.plane = plane; - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + this.size = size; - for ( int i = 1; i < n; i++ ) { + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; - if ( i >= samples ) { + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); - break; + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); - } + } - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + updateMatrixWorld( force ) { - } + this.position.set( 0, 0, 0 ); - } - `, - blending: NoBlending, - depthTest: false, - depthWrite: false - }); - return shaderMaterial; -} -function _getEquirectMaterial() { - return new ShaderMaterial({ - name: 'EquirectangularToCubeUV', - uniforms: { - 'envMap': { - value: null - } - }, - vertexShader: _getCommonVertexShader(), - fragmentShader: /* glsl */` + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); - precision mediump float; - precision mediump int; + this.lookAt( this.plane.normal ); - varying vec3 vOutputDirection; + this.translateZ( - this.plane.constant ); - uniform sampler2D envMap; + super.updateMatrixWorld( force ); - #include + } - void main() { + dispose() { - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + } - } - `, - blending: NoBlending, - depthTest: false, - depthWrite: false - }); } -function _getCubemapMaterial() { - return new ShaderMaterial({ - name: 'CubemapToCubeUV', - uniforms: { - 'envMap': { - value: null - }, - 'flipEnvMap': { - value: -1 - } - }, - vertexShader: _getCommonVertexShader(), - fragmentShader: /* glsl */` - precision mediump float; - precision mediump int; +class ShapePath { - uniform float flipEnvMap; + constructor() { - varying vec3 vOutputDirection; + this.type = 'ShapePath'; - uniform samplerCube envMap; + this.color = new Color(); - void main() { + this.subPaths = []; + this.currentPath = null; - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + } - } - `, - blending: NoBlending, - depthTest: false, - depthWrite: false - }); -} -function _getCommonVertexShader() { - return (/* glsl */` + moveTo( x, y ) { - precision mediump float; - precision mediump int; + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); - attribute float faceIndex; + return this; - varying vec3 vOutputDirection; + } - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { + lineTo( x, y ) { - uv = 2.0 * uv - 1.0; + this.currentPath.lineTo( x, y ); - vec3 direction = vec3( uv, 1.0 ); + return this; - if ( face == 0.0 ) { + } - direction = direction.zyx; // ( 1, v, u ) pos x + quadraticCurveTo( aCPx, aCPy, aX, aY ) { - } else if ( face == 1.0 ) { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y + return this; - } else if ( face == 2.0 ) { + } - direction.x *= -1.0; // ( -u, v, 1 ) pos z + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - } else if ( face == 3.0 ) { + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x + return this; - } else if ( face == 4.0 ) { + } - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y + splineThru( pts ) { - } else if ( face == 5.0 ) { + this.currentPath.splineThru( pts ); - direction.z *= -1.0; // ( u, v, -1 ) neg z + return this; + + } + + toShapes( isCCW ) { + + function toShapesNoHoles( inSubpaths ) { + + const shapes = []; + + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + + const tmpPath = inSubpaths[ i ]; + + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + + shapes.push( tmpShape ); } - return direction; + return shapes; } - void main() { + function isPointInsidePolygon( inPt, inPolygon ) { - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); + const polyLen = inPolygon.length; - } - ` - ); -} + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { -function WebGLCubeUVMaps(renderer) { - let cubeUVmaps = new WeakMap(); - let pmremGenerator = null; - function get(texture) { - if (texture && texture.isTexture) { - const mapping = texture.mapping; - const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; - const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; - // equirect/cube map to cubeUV conversion + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + + if ( Math.abs( edgeDy ) > Number.EPSILON ) { + + // not parallel + if ( edgeDy < 0 ) { + + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + + } + + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + + if ( inPt.y === edgeLowPt.y ) { + + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - if (isEquirectMap || isCubeMap) { - if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) { - texture.needsPMREMUpdate = false; - let renderTarget = cubeUVmaps.get(texture); - if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); - renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); - cubeUVmaps.set(texture, renderTarget); - return renderTarget.texture; - } else { - if (cubeUVmaps.has(texture)) { - return cubeUVmaps.get(texture).texture; } else { - const image = texture.image; - if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { - if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); - const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); - cubeUVmaps.set(texture, renderTarget); - texture.addEventListener('dispose', onTextureDispose); - return renderTarget.texture; - } else { - // image not yet ready. try the conversion next frame - return null; - } + const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); + if ( perpEdge === 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt + } + + } else { + + // parallel or collinear + if ( inPt.y !== edgeLowPt.y ) continue; // parallel + // edge lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; + } - } - } - return texture; - } - function isCubeTextureComplete(image) { - let count = 0; - const length = 6; - for (let i = 0; i < length; i++) { - if (image[i] !== undefined) count++; - } - return count === length; - } - function onTextureDispose(event) { - const texture = event.target; - texture.removeEventListener('dispose', onTextureDispose); - const cubemapUV = cubeUVmaps.get(texture); - if (cubemapUV !== undefined) { - cubeUVmaps.delete(texture); - cubemapUV.dispose(); - } - } - function dispose() { - cubeUVmaps = new WeakMap(); - if (pmremGenerator !== null) { - pmremGenerator.dispose(); - pmremGenerator = null; - } - } - return { - get: get, - dispose: dispose - }; -} -function WebGLExtensions(gl) { - const extensions = {}; - function getExtension(name) { - if (extensions[name] !== undefined) { - return extensions[name]; - } - let extension; - switch (name) { - case 'WEBGL_depth_texture': - extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture'); - break; - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic'); - break; - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); - break; - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); - break; - default: - extension = gl.getExtension(name); - } - extensions[name] = extension; - return extension; - } - return { - has: function (name) { - return getExtension(name) !== null; - }, - init: function (capabilities) { - if (capabilities.isWebGL2) { - getExtension('EXT_color_buffer_float'); - } else { - getExtension('WEBGL_depth_texture'); - getExtension('OES_texture_float'); - getExtension('OES_texture_half_float'); - getExtension('OES_texture_half_float_linear'); - getExtension('OES_standard_derivatives'); - getExtension('OES_element_index_uint'); - getExtension('OES_vertex_array_object'); - getExtension('ANGLE_instanced_arrays'); } - getExtension('OES_texture_float_linear'); - getExtension('EXT_color_buffer_half_float'); - getExtension('WEBGL_multisampled_render_to_texture'); - }, - get: function (name) { - const extension = getExtension(name); - if (extension === null) { - console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.'); - } - return extension; - } - }; -} -function WebGLGeometries(gl, attributes, info, bindingStates) { - const geometries = {}; - const wireframeAttributes = new WeakMap(); - function onGeometryDispose(event) { - const geometry = event.target; - if (geometry.index !== null) { - attributes.remove(geometry.index); - } - for (const name in geometry.attributes) { - attributes.remove(geometry.attributes[name]); - } - geometry.removeEventListener('dispose', onGeometryDispose); - delete geometries[geometry.id]; - const attribute = wireframeAttributes.get(geometry); - if (attribute) { - attributes.remove(attribute); - wireframeAttributes.delete(geometry); - } - bindingStates.releaseStatesOfGeometry(geometry); - if (geometry.isInstancedBufferGeometry === true) { - delete geometry._maxInstanceCount; + return inside; + } - // + const isClockWise = ShapeUtils.isClockWise; - info.memory.geometries--; - } - function get(object, geometry) { - if (geometries[geometry.id] === true) return geometry; - geometry.addEventListener('dispose', onGeometryDispose); - geometries[geometry.id] = true; - info.memory.geometries++; - return geometry; - } - function update(geometry) { - const geometryAttributes = geometry.attributes; + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - // Updating index buffer in VAO now. See WebGLBindingStates. + let solid, tmpPath, tmpShape; + const shapes = []; - for (const name in geometryAttributes) { - attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER); - } + if ( subPaths.length === 1 ) { - // morph targets + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - const morphAttributes = geometry.morphAttributes; - for (const name in morphAttributes) { - const array = morphAttributes[name]; - for (let i = 0, l = array.length; i < l; i++) { - attributes.update(array[i], gl.ARRAY_BUFFER); - } - } - } - function updateWireframeAttribute(geometry) { - const indices = []; - const geometryIndex = geometry.index; - const geometryPosition = geometry.attributes.position; - let version = 0; - if (geometryIndex !== null) { - const array = geometryIndex.array; - version = geometryIndex.version; - for (let i = 0, l = array.length; i < l; i += 3) { - const a = array[i + 0]; - const b = array[i + 1]; - const c = array[i + 2]; - indices.push(a, b, b, c, c, a); - } - } else { - const array = geometryPosition.array; - version = geometryPosition.version; - for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) { - const a = i + 0; - const b = i + 1; - const c = i + 2; - indices.push(a, b, b, c, c, a); - } } - const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); - attribute.version = version; - // Updating index buffer in VAO now. See WebGLBindingStates + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - // + // console.log("Holes first", holesFirst); + + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; - const previousAttribute = wireframeAttributes.get(geometry); - if (previousAttribute) attributes.remove(previousAttribute); + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - // + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { - wireframeAttributes.set(geometry, attribute); - } - function getWireframeAttribute(geometry) { - const currentAttribute = wireframeAttributes.get(geometry); - if (currentAttribute) { - const geometryIndex = geometry.index; - if (geometryIndex !== null) { - // if the attribute is obsolete, create a new one + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; + + if ( solid ) { + + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; + + //console.log('cw', i); + + } else { + + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + + //console.log('ccw', i); - if (currentAttribute.version < geometryIndex.version) { - updateWireframeAttribute(geometry); - } } - } else { - updateWireframeAttribute(geometry); + } - return wireframeAttributes.get(geometry); - } - return { - get: get, - update: update, - getWireframeAttribute: getWireframeAttribute - }; -} -function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) { - const isWebGL2 = capabilities.isWebGL2; - let mode; - function setMode(value) { - mode = value; - } - let type, bytesPerElement; - function setIndex(value) { - type = value.type; - bytesPerElement = value.bytesPerElement; - } - function render(start, count) { - gl.drawElements(mode, count, type, start * bytesPerElement); - info.update(count, mode, 1); - } - function renderInstances(start, count, primcount) { - if (primcount === 0) return; - let extension, methodName; - if (isWebGL2) { - extension = gl; - methodName = 'drawElementsInstanced'; - } else { - extension = extensions.get('ANGLE_instanced_arrays'); - methodName = 'drawElementsInstancedANGLE'; - if (extension === null) { - console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.'); - return; + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + + + if ( newShapes.length > 1 ) { + + let ambiguous = false; + let toChange = 0; + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + betterShapeHoles[ sIdx ] = []; + } - } - extension[methodName](mode, count, type, start * bytesPerElement, primcount); - info.update(count, mode, primcount); - } - // + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; -} + const sho = newShapeHoles[ sIdx ]; -function WebGLInfo(gl) { - const memory = { - geometries: 0, - textures: 0 - }; - const render = { - frame: 0, - calls: 0, - triangles: 0, - points: 0, - lines: 0 - }; - function update(count, mode, instanceCount) { - render.calls++; - switch (mode) { - case gl.TRIANGLES: - render.triangles += instanceCount * (count / 3); - break; - case gl.LINES: - render.lines += instanceCount * (count / 2); - break; - case gl.LINE_STRIP: - render.lines += instanceCount * (count - 1); - break; - case gl.LINE_LOOP: - render.lines += instanceCount * count; - break; - case gl.POINTS: - render.points += instanceCount * count; - break; - default: - console.error('THREE.WebGLInfo: Unknown draw mode:', mode); - break; - } - } - function reset() { - render.frame++; - render.calls = 0; - render.triangles = 0; - render.points = 0; - render.lines = 0; - } - return { - memory: memory, - render: render, - programs: null, - autoReset: true, - reset: reset, - update: update - }; -} + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { -class DataArrayTexture extends Texture { - constructor(data = null, width = 1, height = 1, depth = 1) { - super(null); - this.isDataArrayTexture = true; - this.image = { - data, - width, - height, - depth - }; - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; - this.wrapR = ClampToEdgeWrapping; - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; - } -} + const ho = sho[ hIdx ]; + let hole_unassigned = true; -function numericalSort(a, b) { - return a[0] - b[0]; -} -function absNumericalSort(a, b) { - return Math.abs(b[1]) - Math.abs(a[1]); -} -function WebGLMorphtargets(gl, capabilities, textures) { - const influencesList = {}; - const morphInfluences = new Float32Array(8); - const morphTextures = new WeakMap(); - const morph = new Vector4(); - const workInfluences = []; - for (let i = 0; i < 8; i++) { - workInfluences[i] = [i, 0]; - } - function update(object, geometry, material, program) { - const objectInfluences = object.morphTargetInfluences; - if (capabilities.isWebGL2 === true) { - // instead of using attributes, the WebGL 2 code path encodes morph targets - // into an array of data textures. Each layer represents a single morph target. + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; - const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; - let entry = morphTextures.get(geometry); - if (entry === undefined || entry.count !== morphTargetsCount) { - if (entry !== undefined) entry.texture.dispose(); - const hasMorphPosition = geometry.morphAttributes.position !== undefined; - const hasMorphNormals = geometry.morphAttributes.normal !== undefined; - const hasMorphColors = geometry.morphAttributes.color !== undefined; - const morphTargets = geometry.morphAttributes.position || []; - const morphNormals = geometry.morphAttributes.normal || []; - const morphColors = geometry.morphAttributes.color || []; - let vertexDataCount = 0; - if (hasMorphPosition === true) vertexDataCount = 1; - if (hasMorphNormals === true) vertexDataCount = 2; - if (hasMorphColors === true) vertexDataCount = 3; - let width = geometry.attributes.position.count * vertexDataCount; - let height = 1; - if (width > capabilities.maxTextureSize) { - height = Math.ceil(width / capabilities.maxTextureSize); - width = capabilities.maxTextureSize; - } - const buffer = new Float32Array(width * height * 4 * morphTargetsCount); - const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount); - texture.type = FloatType; - texture.needsUpdate = true; + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - // fill buffer + if ( sIdx !== s2Idx ) toChange ++; - const vertexDataStride = vertexDataCount * 4; - for (let i = 0; i < morphTargetsCount; i++) { - const morphTarget = morphTargets[i]; - const morphNormal = morphNormals[i]; - const morphColor = morphColors[i]; - const offset = width * height * 4 * i; - for (let j = 0; j < morphTarget.count; j++) { - const stride = j * vertexDataStride; - if (hasMorphPosition === true) { - morph.fromBufferAttribute(morphTarget, j); - buffer[offset + stride + 0] = morph.x; - buffer[offset + stride + 1] = morph.y; - buffer[offset + stride + 2] = morph.z; - buffer[offset + stride + 3] = 0; - } - if (hasMorphNormals === true) { - morph.fromBufferAttribute(morphNormal, j); - buffer[offset + stride + 4] = morph.x; - buffer[offset + stride + 5] = morph.y; - buffer[offset + stride + 6] = morph.z; - buffer[offset + stride + 7] = 0; - } - if (hasMorphColors === true) { - morph.fromBufferAttribute(morphColor, j); - buffer[offset + stride + 8] = morph.x; - buffer[offset + stride + 9] = morph.y; - buffer[offset + stride + 10] = morph.z; - buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; - } - } - } - entry = { - count: morphTargetsCount, - texture: texture, - size: new Vector2(width, height) - }; - morphTextures.set(geometry, entry); - function disposeTexture() { - texture.dispose(); - morphTextures.delete(geometry); - geometry.removeEventListener('dispose', disposeTexture); - } - geometry.addEventListener('dispose', disposeTexture); - } + if ( hole_unassigned ) { - // + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); - let morphInfluencesSum = 0; - for (let i = 0; i < objectInfluences.length; i++) { - morphInfluencesSum += objectInfluences[i]; - } - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence); - program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences); - program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures); - program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size); - } else { - // When object doesn't have morph target influences defined, we treat it as a 0-length array - // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + } else { - const length = objectInfluences === undefined ? 0 : objectInfluences.length; - let influences = influencesList[geometry.id]; - if (influences === undefined || influences.length !== length) { - // initialise list + ambiguous = true; - influences = []; - for (let i = 0; i < length; i++) { - influences[i] = [i, 0]; - } - influencesList[geometry.id] = influences; - } + } - // Collect influences + } - for (let i = 0; i < length; i++) { - const influence = influences[i]; - influence[0] = i; - influence[1] = objectInfluences[i]; - } - influences.sort(absNumericalSort); - for (let i = 0; i < 8; i++) { - if (i < length && influences[i][1]) { - workInfluences[i][0] = influences[i][0]; - workInfluences[i][1] = influences[i][1]; - } else { - workInfluences[i][0] = Number.MAX_SAFE_INTEGER; - workInfluences[i][1] = 0; - } - } - workInfluences.sort(numericalSort); - const morphTargets = geometry.morphAttributes.position; - const morphNormals = geometry.morphAttributes.normal; - let morphInfluencesSum = 0; - for (let i = 0; i < 8; i++) { - const influence = workInfluences[i]; - const index = influence[0]; - const value = influence[1]; - if (index !== Number.MAX_SAFE_INTEGER && value) { - if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) { - geometry.setAttribute('morphTarget' + i, morphTargets[index]); - } - if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) { - geometry.setAttribute('morphNormal' + i, morphNormals[index]); } - morphInfluences[i] = value; - morphInfluencesSum += value; - } else { - if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) { - geometry.deleteAttribute('morphTarget' + i); - } - if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) { - geometry.deleteAttribute('morphNormal' + i); + + if ( hole_unassigned ) { + + betterShapeHoles[ sIdx ].push( ho ); + } - morphInfluences[i] = 0; + } - } - // GLSL shader uses formula baseinfluence * base + sum(target * influence) - // This allows us to switch between absolute morphs and relative morphs without changing shader code - // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence); - program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences); - } - } - return { - update: update - }; -} + } -function WebGLObjects(gl, geometries, attributes, info) { - let updateMap = new WeakMap(); - function update(object) { - const frame = info.render.frame; - const geometry = object.geometry; - const buffergeometry = geometries.get(object, geometry); + if ( toChange > 0 && ambiguous === false ) { - // Update once per frame + newShapeHoles = betterShapeHoles; - if (updateMap.get(buffergeometry) !== frame) { - geometries.update(buffergeometry); - updateMap.set(buffergeometry, frame); - } - if (object.isInstancedMesh) { - if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) { - object.addEventListener('dispose', onInstancedMeshDispose); - } - attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); - if (object.instanceColor !== null) { - attributes.update(object.instanceColor, gl.ARRAY_BUFFER); } + } - return buffergeometry; - } - function dispose() { - updateMap = new WeakMap(); - } - function onInstancedMeshDispose(event) { - const instancedMesh = event.target; - instancedMesh.removeEventListener('dispose', onInstancedMeshDispose); - attributes.remove(instancedMesh.instanceMatrix); - if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor); - } - return { - update: update, - dispose: dispose - }; -} -class Data3DTexture extends Texture { - constructor(data = null, width = 1, height = 1, depth = 1) { - // We're going to add .setXXX() methods for setting properties later. - // Users can still set in DataTexture3D directly. - // - // const texture = new THREE.DataTexture3D( data, width, height, depth ); - // texture.anisotropy = 16; - // - // See #14839 + let tmpHoles; + + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; + + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + + tmpShape.holes.push( tmpHoles[ j ].h ); + + } + + } + + //console.log("shape", shapes); + + return shapes; - super(null); - this.isData3DTexture = true; - this.image = { - data, - width, - height, - depth - }; - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; - this.wrapR = ClampToEdgeWrapping; - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; } + } /** - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [textures] ) - * - * uploads a uniform value(s) - * the 'textures' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (textures factorizations): - * - * .upload( gl, seq, values, textures ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * - * Methods of the top-level container (textures factorizations): - * - * .setValue( gl, name, value, textures ) - * - * sets uniform with name 'name' to 'value' + * Text = 3D Text * - * .setOptional( gl, obj, prop ) + * parameters = { + * font: , // font * - * like .set for an optional property of the object + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: , // how far from text outline (including bevelOffset) is bevel + * bevelOffset: // how far from text outline does bevel start + * } */ -const emptyTexture = /*@__PURE__*/new Texture(); -const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture(); -const empty3dTexture = /*@__PURE__*/new Data3DTexture(); -const emptyCubeTexture = /*@__PURE__*/new CubeTexture(); -// --- Utilities --- -// Array Caches (provide typed arrays for temporary by size) +class TextGeometry extends ExtrudeGeometry { -const arrayCacheF32 = []; -const arrayCacheI32 = []; + constructor( text, parameters = {} ) { -// Float32Array caches used for uploading Matrix uniforms + const font = parameters.font; -const mat4array = new Float32Array(16); -const mat3array = new Float32Array(9); -const mat2array = new Float32Array(4); + if ( font === undefined ) { -// Flattening for arrays of vectors and matrices + super(); // generate default extrude geometry -function flatten(array, nBlocks, blockSize) { - const firstElem = array[0]; - if (firstElem <= 0 || firstElem > 0) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + } else { - const n = nBlocks * blockSize; - let r = arrayCacheF32[n]; - if (r === undefined) { - r = new Float32Array(n); - arrayCacheF32[n] = r; - } - if (nBlocks !== 0) { - firstElem.toArray(r, 0); - for (let i = 1, offset = 0; i !== nBlocks; ++i) { - offset += blockSize; - array[i].toArray(r, offset); - } - } - return r; -} -function arraysEqual(a, b) { - if (a.length !== b.length) return false; - for (let i = 0, l = a.length; i < l; i++) { - if (a[i] !== b[i]) return false; - } - return true; -} -function copyArray(a, b) { - for (let i = 0, l = b.length; i < l; i++) { - a[i] = b[i]; - } -} + const shapes = font.generateShapes( text, parameters.size ); -// Texture unit allocation + // translate parameters to ExtrudeGeometry API -function allocTexUnits(textures, n) { - let r = arrayCacheI32[n]; - if (r === undefined) { - r = new Int32Array(n); - arrayCacheI32[n] = r; - } - for (let i = 0; i !== n; ++i) { - r[i] = textures.allocateTextureUnit(); - } - return r; -} + parameters.depth = parameters.height !== undefined ? parameters.height : 50; -// --- Setters --- + // defaults -// Note: Defining these methods externally, because they come in a bunch -// and this way their names minify. + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; -// Single scalar + super( shapes, parameters ); -function setValueV1f(gl, v) { - const cache = this.cache; - if (cache[0] === v) return; - gl.uniform1f(this.addr, v); - cache[0] = v; -} + } -// Single float vector (from flat array or THREE.VectorN) + this.type = 'TextGeometry'; -function setValueV2f(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y) { - gl.uniform2f(this.addr, v.x, v.y); - cache[0] = v.x; - cache[1] = v.y; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform2fv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV3f(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { - gl.uniform3f(this.addr, v.x, v.y, v.z); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - } - } else if (v.r !== undefined) { - if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { - gl.uniform3f(this.addr, v.r, v.g, v.b); - cache[0] = v.r; - cache[1] = v.g; - cache[2] = v.b; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform3fv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV4f(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { - gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - cache[3] = v.w; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform4fv(this.addr, v); - copyArray(cache, v); } + } -// Single matrix (from flat array or THREE.MatrixN) +var glyphs={"0":{x_min:73,x_max:715,ha:792,o:"m 394 -29 q 153 129 242 -29 q 73 479 73 272 q 152 829 73 687 q 394 989 241 989 q 634 829 545 989 q 715 479 715 684 q 635 129 715 270 q 394 -29 546 -29 m 394 89 q 546 211 489 89 q 598 479 598 322 q 548 748 598 640 q 394 871 491 871 q 241 748 298 871 q 190 479 190 637 q 239 211 190 319 q 394 89 296 89 "},"1":{x_min:215.671875,x_max:574,ha:792,o:"m 574 0 l 442 0 l 442 697 l 215 697 l 215 796 q 386 833 330 796 q 475 986 447 875 l 574 986 l 574 0 "},"2":{x_min:59,x_max:731,ha:792,o:"m 731 0 l 59 0 q 197 314 59 188 q 457 487 199 315 q 598 691 598 580 q 543 819 598 772 q 411 867 488 867 q 272 811 328 867 q 209 630 209 747 l 81 630 q 182 901 81 805 q 408 986 271 986 q 629 909 536 986 q 731 694 731 826 q 613 449 731 541 q 378 316 495 383 q 201 122 235 234 l 731 122 l 731 0 "},"3":{x_min:54,x_max:737,ha:792,o:"m 737 284 q 635 55 737 141 q 399 -25 541 -25 q 156 52 248 -25 q 54 308 54 140 l 185 308 q 245 147 185 202 q 395 96 302 96 q 539 140 484 96 q 602 280 602 190 q 510 429 602 390 q 324 454 451 454 l 324 565 q 487 584 441 565 q 565 719 565 617 q 515 835 565 791 q 395 879 466 879 q 255 824 307 879 q 203 661 203 769 l 78 661 q 166 909 78 822 q 387 992 250 992 q 603 921 513 992 q 701 723 701 844 q 669 607 701 656 q 578 524 637 558 q 696 434 655 499 q 737 284 737 369 "},"4":{x_min:48,x_max:742.453125,ha:792,o:"m 742 243 l 602 243 l 602 0 l 476 0 l 476 243 l 48 243 l 48 368 l 476 958 l 602 958 l 602 354 l 742 354 l 742 243 m 476 354 l 476 792 l 162 354 l 476 354 "},"5":{x_min:54.171875,x_max:738,ha:792,o:"m 738 314 q 626 60 738 153 q 382 -23 526 -23 q 155 47 248 -23 q 54 256 54 125 l 183 256 q 259 132 204 174 q 382 91 314 91 q 533 149 471 91 q 602 314 602 213 q 538 469 602 411 q 386 528 475 528 q 284 506 332 528 q 197 439 237 484 l 81 439 l 159 958 l 684 958 l 684 840 l 254 840 l 214 579 q 306 627 258 612 q 407 643 354 643 q 636 552 540 643 q 738 314 738 457 "},"6":{x_min:53,x_max:739,ha:792,o:"m 739 312 q 633 62 739 162 q 400 -31 534 -31 q 162 78 257 -31 q 53 439 53 206 q 178 859 53 712 q 441 986 284 986 q 643 912 559 986 q 732 713 732 833 l 601 713 q 544 830 594 786 q 426 875 494 875 q 268 793 331 875 q 193 517 193 697 q 301 597 240 570 q 427 624 362 624 q 643 540 552 624 q 739 312 739 451 m 603 298 q 540 461 603 400 q 404 516 484 516 q 268 461 323 516 q 207 300 207 401 q 269 137 207 198 q 405 83 325 83 q 541 137 486 83 q 603 298 603 197 "},"7":{x_min:58.71875,x_max:730.953125,ha:792,o:"m 730 839 q 469 448 560 641 q 335 0 378 255 l 192 0 q 328 441 235 252 q 593 830 421 630 l 58 830 l 58 958 l 730 958 l 730 839 "},"8":{x_min:55,x_max:736,ha:792,o:"m 571 527 q 694 424 652 491 q 736 280 736 358 q 648 71 736 158 q 395 -26 551 -26 q 142 69 238 -26 q 55 279 55 157 q 96 425 55 359 q 220 527 138 491 q 120 615 153 562 q 88 726 88 668 q 171 904 88 827 q 395 986 261 986 q 618 905 529 986 q 702 727 702 830 q 670 616 702 667 q 571 527 638 565 m 394 565 q 519 610 475 565 q 563 717 563 655 q 521 823 563 781 q 392 872 474 872 q 265 824 312 872 q 224 720 224 783 q 265 613 224 656 q 394 565 312 565 m 395 91 q 545 150 488 91 q 597 280 597 204 q 546 408 597 355 q 395 465 492 465 q 244 408 299 465 q 194 280 194 356 q 244 150 194 203 q 395 91 299 91 "},"9":{x_min:53,x_max:739,ha:792,o:"m 739 524 q 619 94 739 241 q 362 -32 516 -32 q 150 47 242 -32 q 59 244 59 126 l 191 244 q 246 129 191 176 q 373 82 301 82 q 526 161 466 82 q 597 440 597 255 q 363 334 501 334 q 130 432 216 334 q 53 650 53 521 q 134 880 53 786 q 383 986 226 986 q 659 841 566 986 q 739 524 739 719 m 388 449 q 535 514 480 449 q 585 658 585 573 q 535 805 585 744 q 388 873 480 873 q 242 809 294 873 q 191 658 191 745 q 239 514 191 572 q 388 449 292 449 "},"ο":{x_min:0,x_max:712,ha:815,o:"m 356 -25 q 96 88 192 -25 q 0 368 0 201 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 "},S:{x_min:0,x_max:788,ha:890,o:"m 788 291 q 662 54 788 144 q 397 -26 550 -26 q 116 68 226 -26 q 0 337 0 168 l 131 337 q 200 152 131 220 q 384 85 269 85 q 557 129 479 85 q 650 270 650 183 q 490 429 650 379 q 194 513 341 470 q 33 739 33 584 q 142 964 33 881 q 388 1041 242 1041 q 644 957 543 1041 q 756 716 756 867 l 625 716 q 561 874 625 816 q 395 933 497 933 q 243 891 309 933 q 164 759 164 841 q 325 609 164 656 q 625 526 475 568 q 788 291 788 454 "},"¦":{x_min:343,x_max:449,ha:792,o:"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"/":{x_min:183.25,x_max:608.328125,ha:792,o:"m 608 1041 l 266 -129 l 183 -129 l 520 1041 l 608 1041 "},"Τ":{x_min:-0.4375,x_max:777.453125,ha:839,o:"m 777 893 l 458 893 l 458 0 l 319 0 l 319 892 l 0 892 l 0 1013 l 777 1013 l 777 893 "},y:{x_min:0,x_max:684.78125,ha:771,o:"m 684 738 l 388 -83 q 311 -216 356 -167 q 173 -279 252 -279 q 97 -266 133 -279 l 97 -149 q 132 -155 109 -151 q 168 -160 155 -160 q 240 -114 213 -160 q 274 -26 248 -98 l 0 738 l 137 737 l 341 139 l 548 737 l 684 738 "},"Π":{x_min:0,x_max:803,ha:917,o:"m 803 0 l 667 0 l 667 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 803 1012 l 803 0 "},"Î":{x_min:-111,x_max:339,ha:361,o:"m 339 800 l 229 800 l 229 925 l 339 925 l 339 800 m -1 800 l -111 800 l -111 925 l -1 925 l -1 800 m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 m 302 1040 l 113 819 l 30 819 l 165 1040 l 302 1040 "},g:{x_min:0,x_max:686,ha:838,o:"m 686 34 q 586 -213 686 -121 q 331 -306 487 -306 q 131 -252 216 -306 q 31 -84 31 -190 l 155 -84 q 228 -174 166 -138 q 345 -207 284 -207 q 514 -109 454 -207 q 564 89 564 -27 q 461 6 521 36 q 335 -23 401 -23 q 88 100 184 -23 q 0 370 0 215 q 87 634 0 522 q 330 758 183 758 q 457 728 398 758 q 564 644 515 699 l 564 737 l 686 737 l 686 34 m 582 367 q 529 560 582 481 q 358 652 468 652 q 189 561 250 652 q 135 369 135 482 q 189 176 135 255 q 361 85 251 85 q 529 176 468 85 q 582 367 582 255 "},"²":{x_min:0,x_max:442,ha:539,o:"m 442 383 l 0 383 q 91 566 0 492 q 260 668 176 617 q 354 798 354 727 q 315 875 354 845 q 227 905 277 905 q 136 869 173 905 q 99 761 99 833 l 14 761 q 82 922 14 864 q 232 974 141 974 q 379 926 316 974 q 442 797 442 878 q 351 635 442 704 q 183 539 321 611 q 92 455 92 491 l 442 455 l 442 383 "},"–":{x_min:0,x_max:705.5625,ha:803,o:"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},"Κ":{x_min:0,x_max:819.5625,ha:893,o:"m 819 0 l 650 0 l 294 509 l 139 356 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},"Æ’":{x_min:-46.265625,x_max:392,ha:513,o:"m 392 651 l 259 651 l 79 -279 l -46 -278 l 134 651 l 14 651 l 14 751 l 135 751 q 151 948 135 900 q 304 1041 185 1041 q 334 1040 319 1041 q 392 1034 348 1039 l 392 922 q 337 931 360 931 q 271 883 287 931 q 260 793 260 853 l 260 751 l 392 751 l 392 651 "},e:{x_min:0,x_max:714,ha:813,o:"m 714 326 l 140 326 q 200 157 140 227 q 359 87 260 87 q 488 130 431 87 q 561 245 545 174 l 697 245 q 577 48 670 123 q 358 -26 484 -26 q 97 85 195 -26 q 0 363 0 197 q 94 642 0 529 q 358 765 195 765 q 626 627 529 765 q 714 326 714 503 m 576 429 q 507 583 564 522 q 355 650 445 650 q 206 583 266 650 q 140 429 152 522 l 576 429 "},"ÏŒ":{x_min:0,x_max:712,ha:815,o:"m 356 -25 q 94 91 194 -25 q 0 368 0 202 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 m 576 1040 l 387 819 l 303 819 l 438 1040 l 576 1040 "},J:{x_min:0,x_max:588,ha:699,o:"m 588 279 q 287 -26 588 -26 q 58 73 126 -26 q 0 327 0 158 l 133 327 q 160 172 133 227 q 288 96 198 96 q 426 171 391 96 q 449 336 449 219 l 449 1013 l 588 1013 l 588 279 "},"»":{x_min:-1,x_max:503,ha:601,o:"m 503 302 l 280 136 l 281 256 l 429 373 l 281 486 l 280 608 l 503 440 l 503 302 m 221 302 l 0 136 l 0 255 l 145 372 l 0 486 l -1 608 l 221 440 l 221 302 "},"©":{x_min:-3,x_max:1008,ha:1106,o:"m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 741 394 q 661 246 731 302 q 496 190 591 190 q 294 285 369 190 q 228 497 228 370 q 295 714 228 625 q 499 813 370 813 q 656 762 588 813 q 733 625 724 711 l 634 625 q 589 704 629 673 q 498 735 550 735 q 377 666 421 735 q 334 504 334 597 q 374 340 334 408 q 490 272 415 272 q 589 304 549 272 q 638 394 628 337 l 741 394 "},"ÏŽ":{x_min:0,x_max:922,ha:1030,o:"m 687 1040 l 498 819 l 415 819 l 549 1040 l 687 1040 m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 338 0 202 q 45 551 0 444 q 161 737 84 643 l 302 737 q 175 552 219 647 q 124 336 124 446 q 155 179 124 248 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 341 797 257 q 745 555 797 450 q 619 737 705 637 l 760 737 q 874 551 835 640 q 922 339 922 444 "},"^":{x_min:193.0625,x_max:598.609375,ha:792,o:"m 598 772 l 515 772 l 395 931 l 277 772 l 193 772 l 326 1013 l 462 1013 l 598 772 "},"«":{x_min:0,x_max:507.203125,ha:604,o:"m 506 136 l 284 302 l 284 440 l 506 608 l 507 485 l 360 371 l 506 255 l 506 136 m 222 136 l 0 302 l 0 440 l 222 608 l 221 486 l 73 373 l 222 256 l 222 136 "},D:{x_min:0,x_max:828,ha:935,o:"m 389 1013 q 714 867 593 1013 q 828 521 828 729 q 712 161 828 309 q 382 0 587 0 l 0 0 l 0 1013 l 389 1013 m 376 124 q 607 247 523 124 q 681 510 681 355 q 607 771 681 662 q 376 896 522 896 l 139 896 l 139 124 l 376 124 "},"∙":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"ÿ":{x_min:0,x_max:47,ha:125,o:"m 47 3 q 37 -7 47 -7 q 28 0 30 -7 q 39 -4 32 -4 q 45 3 45 -1 l 37 0 q 28 9 28 0 q 39 19 28 19 l 47 16 l 47 19 l 47 3 m 37 1 q 44 8 44 1 q 37 16 44 16 q 30 8 30 16 q 37 1 30 1 m 26 1 l 23 22 l 14 0 l 3 22 l 3 3 l 0 25 l 13 1 l 22 25 l 26 1 "},w:{x_min:0,x_max:1009.71875,ha:1100,o:"m 1009 738 l 783 0 l 658 0 l 501 567 l 345 0 l 222 0 l 0 738 l 130 738 l 284 174 l 432 737 l 576 738 l 721 173 l 881 737 l 1009 738 "},$:{x_min:0,x_max:700,ha:793,o:"m 664 717 l 542 717 q 490 825 531 785 q 381 872 450 865 l 381 551 q 620 446 540 522 q 700 241 700 370 q 618 45 700 116 q 381 -25 536 -25 l 381 -152 l 307 -152 l 307 -25 q 81 62 162 -25 q 0 297 0 149 l 124 297 q 169 146 124 204 q 307 81 215 89 l 307 441 q 80 536 148 469 q 13 725 13 603 q 96 910 13 839 q 307 982 180 982 l 307 1077 l 381 1077 l 381 982 q 574 917 494 982 q 664 717 664 845 m 307 565 l 307 872 q 187 831 233 872 q 142 724 142 791 q 180 618 142 656 q 307 565 218 580 m 381 76 q 562 237 562 96 q 517 361 562 313 q 381 423 472 409 l 381 76 "},"\\":{x_min:-0.015625,x_max:425.0625,ha:522,o:"m 425 -129 l 337 -129 l 0 1041 l 83 1041 l 425 -129 "},"µ":{x_min:0,x_max:697.21875,ha:747,o:"m 697 -4 q 629 -14 658 -14 q 498 97 513 -14 q 422 9 470 41 q 313 -23 374 -23 q 207 4 258 -23 q 119 81 156 32 l 119 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 173 124 246 q 308 83 216 83 q 452 178 402 83 q 493 359 493 255 l 493 738 l 617 738 l 617 214 q 623 136 617 160 q 673 92 637 92 q 697 96 684 92 l 697 -4 "},"Ι":{x_min:42,x_max:181,ha:297,o:"m 181 0 l 42 0 l 42 1013 l 181 1013 l 181 0 "},"ÎŽ":{x_min:0,x_max:1144.5,ha:1214,o:"m 1144 1012 l 807 416 l 807 0 l 667 0 l 667 416 l 325 1012 l 465 1012 l 736 533 l 1004 1012 l 1144 1012 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"’":{x_min:0,x_max:139,ha:236,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"Î":{x_min:0,x_max:801,ha:915,o:"m 801 0 l 651 0 l 131 822 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 191 l 670 1013 l 801 1013 l 801 0 "},"-":{x_min:8.71875,x_max:350.390625,ha:478,o:"m 350 317 l 8 317 l 8 428 l 350 428 l 350 317 "},Q:{x_min:0,x_max:968,ha:1072,o:"m 954 5 l 887 -79 l 744 35 q 622 -11 687 2 q 483 -26 556 -26 q 127 130 262 -26 q 0 504 0 279 q 127 880 0 728 q 484 1041 262 1041 q 841 884 708 1041 q 968 507 968 735 q 933 293 968 398 q 832 104 899 188 l 954 5 m 723 191 q 802 330 777 248 q 828 499 828 412 q 744 790 828 673 q 483 922 650 922 q 228 791 322 922 q 142 505 142 673 q 227 221 142 337 q 487 91 323 91 q 632 123 566 91 l 520 215 l 587 301 l 723 191 "},"Ï‚":{x_min:1,x_max:676.28125,ha:740,o:"m 676 460 l 551 460 q 498 595 542 546 q 365 651 448 651 q 199 578 263 651 q 136 401 136 505 q 266 178 136 241 q 508 106 387 142 q 640 -50 640 62 q 625 -158 640 -105 q 583 -278 611 -211 l 465 -278 q 498 -182 490 -211 q 515 -80 515 -126 q 381 12 515 -15 q 134 91 197 51 q 1 388 1 179 q 100 651 1 542 q 354 761 199 761 q 587 680 498 761 q 676 460 676 599 "},M:{x_min:0,x_max:954,ha:1067,o:"m 954 0 l 819 0 l 819 869 l 537 0 l 405 0 l 128 866 l 128 0 l 0 0 l 0 1013 l 200 1013 l 472 160 l 757 1013 l 954 1013 l 954 0 "},"Ψ":{x_min:0,x_max:1006,ha:1094,o:"m 1006 678 q 914 319 1006 429 q 571 200 814 200 l 571 0 l 433 0 l 433 200 q 92 319 194 200 q 0 678 0 429 l 0 1013 l 139 1013 l 139 679 q 191 417 139 492 q 433 326 255 326 l 433 1013 l 571 1013 l 571 326 l 580 326 q 813 423 747 326 q 868 679 868 502 l 868 1013 l 1006 1013 l 1006 678 "},C:{x_min:0,x_max:886,ha:944,o:"m 886 379 q 760 87 886 201 q 455 -26 634 -26 q 112 136 236 -26 q 0 509 0 283 q 118 882 0 737 q 469 1041 245 1041 q 748 955 630 1041 q 879 708 879 859 l 745 708 q 649 862 724 805 q 473 920 573 920 q 219 791 312 920 q 136 509 136 675 q 217 229 136 344 q 470 99 311 99 q 672 179 591 99 q 753 379 753 259 l 886 379 "},"!":{x_min:0,x_max:138,ha:236,o:"m 138 684 q 116 409 138 629 q 105 244 105 299 l 33 244 q 16 465 33 313 q 0 684 0 616 l 0 1013 l 138 1013 l 138 684 m 138 0 l 0 0 l 0 151 l 138 151 l 138 0 "},"{":{x_min:0,x_max:480.5625,ha:578,o:"m 480 -286 q 237 -213 303 -286 q 187 -45 187 -159 q 194 48 187 -15 q 201 141 201 112 q 164 264 201 225 q 0 314 118 314 l 0 417 q 164 471 119 417 q 201 605 201 514 q 199 665 201 644 q 193 772 193 769 q 241 941 193 887 q 480 1015 308 1015 l 480 915 q 336 866 375 915 q 306 742 306 828 q 310 662 306 717 q 314 577 314 606 q 288 452 314 500 q 176 365 256 391 q 289 275 257 337 q 314 143 314 226 q 313 84 314 107 q 310 -11 310 -5 q 339 -131 310 -94 q 480 -182 377 -182 l 480 -286 "},X:{x_min:-0.015625,x_max:854.15625,ha:940,o:"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 428 637 l 675 1013 l 836 1013 l 504 520 l 854 0 "},"#":{x_min:0,x_max:963.890625,ha:1061,o:"m 963 690 l 927 590 l 719 590 l 655 410 l 876 410 l 840 310 l 618 310 l 508 -3 l 393 -2 l 506 309 l 329 310 l 215 -2 l 102 -3 l 212 310 l 0 310 l 36 410 l 248 409 l 312 590 l 86 590 l 120 690 l 347 690 l 459 1006 l 573 1006 l 462 690 l 640 690 l 751 1006 l 865 1006 l 754 690 l 963 690 m 606 590 l 425 590 l 362 410 l 543 410 l 606 590 "},"ι":{x_min:42,x_max:284,ha:361,o:"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 738 l 167 738 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 "},"Ά":{x_min:0,x_max:906.953125,ha:982,o:"m 283 1040 l 88 799 l 5 799 l 145 1040 l 283 1040 m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1012 l 529 1012 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},")":{x_min:0,x_max:318,ha:415,o:"m 318 365 q 257 25 318 191 q 87 -290 197 -141 l 0 -290 q 140 21 93 -128 q 193 360 193 189 q 141 704 193 537 q 0 1024 97 850 l 87 1024 q 257 706 197 871 q 318 365 318 542 "},"ε":{x_min:0,x_max:634.71875,ha:714,o:"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 314 0 265 q 128 390 67 353 q 56 460 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 "},"Δ":{x_min:0,x_max:952.78125,ha:1028,o:"m 952 0 l 0 0 l 400 1013 l 551 1013 l 952 0 m 762 124 l 476 867 l 187 124 l 762 124 "},"}":{x_min:0,x_max:481,ha:578,o:"m 481 314 q 318 262 364 314 q 282 136 282 222 q 284 65 282 97 q 293 -58 293 -48 q 241 -217 293 -166 q 0 -286 174 -286 l 0 -182 q 143 -130 105 -182 q 171 -2 171 -93 q 168 81 171 22 q 165 144 165 140 q 188 275 165 229 q 306 365 220 339 q 191 455 224 391 q 165 588 165 505 q 168 681 165 624 q 171 742 171 737 q 141 865 171 827 q 0 915 102 915 l 0 1015 q 243 942 176 1015 q 293 773 293 888 q 287 675 293 741 q 282 590 282 608 q 318 466 282 505 q 481 417 364 417 l 481 314 "},"‰":{x_min:-3,x_max:1672,ha:1821,o:"m 846 0 q 664 76 732 0 q 603 244 603 145 q 662 412 603 344 q 846 489 729 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 846 0 962 0 m 845 103 q 945 143 910 103 q 981 243 981 184 q 947 340 981 301 q 845 385 910 385 q 745 342 782 385 q 709 243 709 300 q 742 147 709 186 q 845 103 781 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 m 1428 0 q 1246 76 1314 0 q 1185 244 1185 145 q 1244 412 1185 344 q 1428 489 1311 489 q 1610 412 1542 489 q 1672 244 1672 343 q 1612 76 1672 144 q 1428 0 1545 0 m 1427 103 q 1528 143 1492 103 q 1564 243 1564 184 q 1530 340 1564 301 q 1427 385 1492 385 q 1327 342 1364 385 q 1291 243 1291 300 q 1324 147 1291 186 q 1427 103 1363 103 "},a:{x_min:0,x_max:698.609375,ha:794,o:"m 698 0 q 661 -12 679 -7 q 615 -17 643 -17 q 536 12 564 -17 q 500 96 508 41 q 384 6 456 37 q 236 -25 312 -25 q 65 31 130 -25 q 0 194 0 88 q 118 390 0 334 q 328 435 180 420 q 488 483 476 451 q 495 523 495 504 q 442 619 495 584 q 325 654 389 654 q 209 617 257 654 q 152 513 161 580 l 33 513 q 123 705 33 633 q 332 772 207 772 q 528 712 448 772 q 617 531 617 645 l 617 163 q 624 108 617 126 q 664 90 632 90 l 698 94 l 698 0 m 491 262 l 491 372 q 272 329 350 347 q 128 201 128 294 q 166 113 128 144 q 264 83 205 83 q 414 130 346 83 q 491 262 491 183 "},"—":{x_min:0,x_max:941.671875,ha:1039,o:"m 941 334 l 0 334 l 0 410 l 941 410 l 941 334 "},"=":{x_min:8.71875,x_max:780.953125,ha:792,o:"m 780 510 l 8 510 l 8 606 l 780 606 l 780 510 m 780 235 l 8 235 l 8 332 l 780 332 l 780 235 "},N:{x_min:0,x_max:801,ha:914,o:"m 801 0 l 651 0 l 131 823 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 193 l 670 1013 l 801 1013 l 801 0 "},"Ï":{x_min:0,x_max:712,ha:797,o:"m 712 369 q 620 94 712 207 q 362 -26 521 -26 q 230 2 292 -26 q 119 83 167 30 l 119 -278 l 0 -278 l 0 362 q 91 643 0 531 q 355 764 190 764 q 617 647 517 764 q 712 369 712 536 m 583 366 q 530 559 583 480 q 359 651 469 651 q 190 562 252 651 q 135 370 135 483 q 189 176 135 257 q 359 85 250 85 q 528 175 466 85 q 583 366 583 254 "},"¯":{x_min:0,x_max:941.671875,ha:938,o:"m 941 1033 l 0 1033 l 0 1109 l 941 1109 l 941 1033 "},Z:{x_min:0,x_max:779,ha:849,o:"m 779 0 l 0 0 l 0 113 l 621 896 l 40 896 l 40 1013 l 779 1013 l 778 887 l 171 124 l 779 124 l 779 0 "},u:{x_min:0,x_max:617,ha:729,o:"m 617 0 l 499 0 l 499 110 q 391 10 460 45 q 246 -25 322 -25 q 61 58 127 -25 q 0 258 0 136 l 0 738 l 125 738 l 125 284 q 156 148 125 202 q 273 82 197 82 q 433 165 369 82 q 493 340 493 243 l 493 738 l 617 738 l 617 0 "},k:{x_min:0,x_max:612.484375,ha:697,o:"m 612 738 l 338 465 l 608 0 l 469 0 l 251 382 l 121 251 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 402 l 456 738 l 612 738 "},"Η":{x_min:0,x_max:803,ha:917,o:"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"Α":{x_min:0,x_max:906.953125,ha:985,o:"m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},s:{x_min:0,x_max:604,ha:697,o:"m 604 217 q 501 36 604 104 q 292 -23 411 -23 q 86 43 166 -23 q 0 238 0 114 l 121 237 q 175 122 121 164 q 300 85 223 85 q 415 112 363 85 q 479 207 479 147 q 361 309 479 276 q 140 372 141 370 q 21 544 21 426 q 111 708 21 647 q 298 761 190 761 q 492 705 413 761 q 583 531 583 643 l 462 531 q 412 625 462 594 q 298 657 363 657 q 199 636 242 657 q 143 558 143 608 q 262 454 143 486 q 484 394 479 397 q 604 217 604 341 "},B:{x_min:0,x_max:778,ha:876,o:"m 580 546 q 724 469 670 535 q 778 311 778 403 q 673 83 778 171 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 892 q 691 633 732 693 q 580 546 650 572 m 393 899 l 139 899 l 139 588 l 379 588 q 521 624 462 588 q 592 744 592 667 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 303 635 219 q 559 436 635 389 q 402 477 494 477 l 139 477 l 139 124 l 419 124 "},"…":{x_min:0,x_max:614,ha:708,o:"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 m 378 0 l 236 0 l 236 151 l 378 151 l 378 0 m 614 0 l 472 0 l 472 151 l 614 151 l 614 0 "},"?":{x_min:0,x_max:607,ha:704,o:"m 607 777 q 543 599 607 674 q 422 474 482 537 q 357 272 357 391 l 236 272 q 297 487 236 395 q 411 619 298 490 q 474 762 474 691 q 422 885 474 838 q 301 933 371 933 q 179 880 228 933 q 124 706 124 819 l 0 706 q 94 963 0 872 q 302 1044 177 1044 q 511 973 423 1044 q 607 777 607 895 m 370 0 l 230 0 l 230 151 l 370 151 l 370 0 "},H:{x_min:0,x_max:803,ha:915,o:"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"ν":{x_min:0,x_max:675,ha:761,o:"m 675 738 l 404 0 l 272 0 l 0 738 l 133 738 l 340 147 l 541 738 l 675 738 "},c:{x_min:1,x_max:701.390625,ha:775,o:"m 701 264 q 584 53 681 133 q 353 -26 487 -26 q 91 91 188 -26 q 1 370 1 201 q 92 645 1 537 q 353 761 190 761 q 572 688 479 761 q 690 493 666 615 l 556 493 q 487 606 545 562 q 356 650 428 650 q 186 563 246 650 q 134 372 134 487 q 188 179 134 258 q 359 88 250 88 q 492 136 437 88 q 566 264 548 185 l 701 264 "},"¶":{x_min:0,x_max:566.671875,ha:678,o:"m 21 892 l 52 892 l 98 761 l 145 892 l 176 892 l 178 741 l 157 741 l 157 867 l 108 741 l 88 741 l 40 871 l 40 741 l 21 741 l 21 892 m 308 854 l 308 731 q 252 691 308 691 q 227 691 240 691 q 207 696 213 695 l 207 712 l 253 706 q 288 733 288 706 l 288 763 q 244 741 279 741 q 193 797 193 741 q 261 860 193 860 q 287 860 273 860 q 308 854 302 855 m 288 842 l 263 843 q 213 796 213 843 q 248 756 213 756 q 288 796 288 756 l 288 842 m 566 988 l 502 988 l 502 -1 l 439 -1 l 439 988 l 317 988 l 317 -1 l 252 -1 l 252 602 q 81 653 155 602 q 0 805 0 711 q 101 989 0 918 q 309 1053 194 1053 l 566 1053 l 566 988 "},"β":{x_min:0,x_max:660,ha:745,o:"m 471 550 q 610 450 561 522 q 660 280 660 378 q 578 64 660 151 q 367 -22 497 -22 q 239 5 299 -22 q 126 82 178 32 l 126 -278 l 0 -278 l 0 593 q 54 903 0 801 q 318 1042 127 1042 q 519 964 436 1042 q 603 771 603 887 q 567 644 603 701 q 471 550 532 586 m 337 79 q 476 138 418 79 q 535 279 535 198 q 427 437 535 386 q 226 477 344 477 l 226 583 q 398 620 329 583 q 486 762 486 668 q 435 884 486 833 q 312 935 384 935 q 169 861 219 935 q 126 698 126 797 l 126 362 q 170 169 126 242 q 337 79 224 79 "},"Îœ":{x_min:0,x_max:954,ha:1068,o:"m 954 0 l 819 0 l 819 868 l 537 0 l 405 0 l 128 865 l 128 0 l 0 0 l 0 1013 l 199 1013 l 472 158 l 758 1013 l 954 1013 l 954 0 "},"ÎŒ":{x_min:0.109375,x_max:1120,ha:1217,o:"m 1120 505 q 994 132 1120 282 q 642 -29 861 -29 q 290 130 422 -29 q 167 505 167 280 q 294 883 167 730 q 650 1046 430 1046 q 999 882 868 1046 q 1120 505 1120 730 m 977 504 q 896 784 977 669 q 644 915 804 915 q 391 785 484 915 q 307 504 307 669 q 391 224 307 339 q 644 95 486 95 q 894 224 803 95 q 977 504 977 339 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Ή":{x_min:0,x_max:1158,ha:1275,o:"m 1158 0 l 1022 0 l 1022 475 l 496 475 l 496 0 l 356 0 l 356 1012 l 496 1012 l 496 599 l 1022 599 l 1022 1012 l 1158 1012 l 1158 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"•":{x_min:0,x_max:663.890625,ha:775,o:"m 663 529 q 566 293 663 391 q 331 196 469 196 q 97 294 194 196 q 0 529 0 393 q 96 763 0 665 q 331 861 193 861 q 566 763 469 861 q 663 529 663 665 "},"Â¥":{x_min:0.1875,x_max:819.546875,ha:886,o:"m 563 561 l 697 561 l 696 487 l 520 487 l 482 416 l 482 380 l 697 380 l 695 308 l 482 308 l 482 0 l 342 0 l 342 308 l 125 308 l 125 380 l 342 380 l 342 417 l 303 487 l 125 487 l 125 561 l 258 561 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 l 563 561 "},"(":{x_min:0,x_max:318.0625,ha:415,o:"m 318 -290 l 230 -290 q 61 23 122 -142 q 0 365 0 190 q 62 712 0 540 q 230 1024 119 869 l 318 1024 q 175 705 219 853 q 125 360 125 542 q 176 22 125 187 q 318 -290 223 -127 "},U:{x_min:0,x_max:796,ha:904,o:"m 796 393 q 681 93 796 212 q 386 -25 566 -25 q 101 95 208 -25 q 0 393 0 211 l 0 1013 l 138 1013 l 138 391 q 204 191 138 270 q 394 107 276 107 q 586 191 512 107 q 656 391 656 270 l 656 1013 l 796 1013 l 796 393 "},"γ":{x_min:0.5,x_max:744.953125,ha:822,o:"m 744 737 l 463 54 l 463 -278 l 338 -278 l 338 54 l 154 495 q 104 597 124 569 q 13 651 67 651 l 0 651 l 0 751 l 39 753 q 168 711 121 753 q 242 594 207 676 l 403 208 l 617 737 l 744 737 "},"α":{x_min:0,x_max:765.5625,ha:809,o:"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 728 407 760 q 563 637 524 696 l 563 739 l 685 739 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 96 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 "},F:{x_min:0,x_max:683.328125,ha:717,o:"m 683 888 l 140 888 l 140 583 l 613 583 l 613 458 l 140 458 l 140 0 l 0 0 l 0 1013 l 683 1013 l 683 888 "},"­":{x_min:0,x_max:705.5625,ha:803,o:"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},":":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"Χ":{x_min:0,x_max:854.171875,ha:935,o:"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 427 637 l 675 1013 l 836 1013 l 504 521 l 854 0 "},"*":{x_min:116,x_max:674,ha:792,o:"m 674 768 l 475 713 l 610 544 l 517 477 l 394 652 l 272 478 l 178 544 l 314 713 l 116 766 l 153 876 l 341 812 l 342 1013 l 446 1013 l 446 811 l 635 874 l 674 768 "},"†":{x_min:0,x_max:777,ha:835,o:"m 458 804 l 777 804 l 777 683 l 458 683 l 458 0 l 319 0 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 "},"°":{x_min:0,x_max:347,ha:444,o:"m 173 802 q 43 856 91 802 q 0 977 0 905 q 45 1101 0 1049 q 173 1153 90 1153 q 303 1098 255 1153 q 347 977 347 1049 q 303 856 347 905 q 173 802 256 802 m 173 884 q 238 910 214 884 q 262 973 262 937 q 239 1038 262 1012 q 173 1064 217 1064 q 108 1037 132 1064 q 85 973 85 1010 q 108 910 85 937 q 173 884 132 884 "},V:{x_min:0,x_max:862.71875,ha:940,o:"m 862 1013 l 505 0 l 361 0 l 0 1013 l 143 1013 l 434 165 l 718 1012 l 862 1013 "},"Ξ":{x_min:0,x_max:734.71875,ha:763,o:"m 723 889 l 9 889 l 9 1013 l 723 1013 l 723 889 m 673 463 l 61 463 l 61 589 l 673 589 l 673 463 m 734 0 l 0 0 l 0 124 l 734 124 l 734 0 "}," ":{x_min:0,x_max:0,ha:853},"Ϋ":{x_min:0.328125,x_max:819.515625,ha:889,o:"m 588 1046 l 460 1046 l 460 1189 l 588 1189 l 588 1046 m 360 1046 l 232 1046 l 232 1189 l 360 1189 l 360 1046 m 819 1012 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1012 l 140 1012 l 411 533 l 679 1012 l 819 1012 "},"â€":{x_min:0,x_max:347,ha:454,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 m 347 851 q 310 737 347 784 q 208 669 273 690 l 208 734 q 267 787 250 741 q 280 873 280 821 l 208 873 l 208 1013 l 347 1013 l 347 851 "},"@":{x_min:0,x_max:1260,ha:1357,o:"m 1098 -45 q 877 -160 1001 -117 q 633 -203 752 -203 q 155 -29 327 -203 q 0 360 0 127 q 176 802 0 616 q 687 1008 372 1008 q 1123 854 969 1008 q 1260 517 1260 718 q 1155 216 1260 341 q 868 82 1044 82 q 772 106 801 82 q 737 202 737 135 q 647 113 700 144 q 527 82 594 82 q 367 147 420 82 q 314 312 314 212 q 401 565 314 452 q 639 690 498 690 q 810 588 760 690 l 849 668 l 938 668 q 877 441 900 532 q 833 226 833 268 q 853 182 833 198 q 902 167 873 167 q 1088 272 1012 167 q 1159 512 1159 372 q 1051 793 1159 681 q 687 925 925 925 q 248 747 415 925 q 97 361 97 586 q 226 26 97 159 q 627 -122 370 -122 q 856 -87 737 -122 q 1061 8 976 -53 l 1098 -45 m 786 488 q 738 580 777 545 q 643 615 700 615 q 483 517 548 615 q 425 322 425 430 q 457 203 425 250 q 552 156 490 156 q 722 273 665 156 q 786 488 738 309 "},"Ί":{x_min:0,x_max:499,ha:613,o:"m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 m 499 0 l 360 0 l 360 1012 l 499 1012 l 499 0 "},i:{x_min:14,x_max:136,ha:275,o:"m 136 873 l 14 873 l 14 1013 l 136 1013 l 136 873 m 136 0 l 14 0 l 14 737 l 136 737 l 136 0 "},"Î’":{x_min:0,x_max:778,ha:877,o:"m 580 545 q 724 468 671 534 q 778 310 778 402 q 673 83 778 170 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 891 q 691 632 732 692 q 580 545 650 571 m 393 899 l 139 899 l 139 587 l 379 587 q 521 623 462 587 q 592 744 592 666 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 302 635 219 q 559 435 635 388 q 402 476 494 476 l 139 476 l 139 124 l 419 124 "},"Ï…":{x_min:0,x_max:617,ha:725,o:"m 617 352 q 540 94 617 199 q 308 -24 455 -24 q 76 94 161 -24 q 0 352 0 199 l 0 739 l 126 739 l 126 355 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 355 492 257 l 492 739 l 617 739 l 617 352 "},"]":{x_min:0,x_max:275,ha:372,o:"m 275 -281 l 0 -281 l 0 -187 l 151 -187 l 151 920 l 0 920 l 0 1013 l 275 1013 l 275 -281 "},m:{x_min:0,x_max:1019,ha:1128,o:"m 1019 0 l 897 0 l 897 454 q 860 591 897 536 q 739 660 816 660 q 613 586 659 660 q 573 436 573 522 l 573 0 l 447 0 l 447 455 q 412 591 447 535 q 294 657 372 657 q 165 586 213 657 q 122 437 122 521 l 122 0 l 0 0 l 0 738 l 117 738 l 117 640 q 202 730 150 697 q 316 763 254 763 q 437 730 381 763 q 525 642 494 697 q 621 731 559 700 q 753 763 682 763 q 943 694 867 763 q 1019 512 1019 625 l 1019 0 "},"χ":{x_min:8.328125,x_max:780.5625,ha:815,o:"m 780 -278 q 715 -294 747 -294 q 616 -257 663 -294 q 548 -175 576 -227 l 379 133 l 143 -277 l 9 -277 l 313 254 l 163 522 q 127 586 131 580 q 36 640 91 640 q 8 637 27 640 l 8 752 l 52 757 q 162 719 113 757 q 236 627 200 690 l 383 372 l 594 737 l 726 737 l 448 250 l 625 -69 q 670 -153 647 -110 q 743 -188 695 -188 q 780 -184 759 -188 l 780 -278 "},"ί":{x_min:42,x_max:326.71875,ha:361,o:"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 102 239 101 q 284 112 257 104 l 284 3 m 326 1040 l 137 819 l 54 819 l 189 1040 l 326 1040 "},"Ζ":{x_min:0,x_max:779.171875,ha:850,o:"m 779 0 l 0 0 l 0 113 l 620 896 l 40 896 l 40 1013 l 779 1013 l 779 887 l 170 124 l 779 124 l 779 0 "},R:{x_min:0,x_max:781.953125,ha:907,o:"m 781 0 l 623 0 q 587 242 590 52 q 407 433 585 433 l 138 433 l 138 0 l 0 0 l 0 1013 l 396 1013 q 636 946 539 1013 q 749 731 749 868 q 711 597 749 659 q 608 502 674 534 q 718 370 696 474 q 729 207 722 352 q 781 26 736 62 l 781 0 m 373 551 q 533 594 465 551 q 614 731 614 645 q 532 859 614 815 q 373 896 465 896 l 138 896 l 138 551 l 373 551 "},o:{x_min:0,x_max:713,ha:821,o:"m 357 -25 q 94 91 194 -25 q 0 368 0 202 q 93 642 0 533 q 357 761 193 761 q 618 644 518 761 q 713 368 713 533 q 619 91 713 201 q 357 -25 521 -25 m 357 85 q 528 175 465 85 q 584 369 584 255 q 529 562 584 484 q 357 651 467 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 357 85 250 85 "},K:{x_min:0,x_max:819.46875,ha:906,o:"m 819 0 l 649 0 l 294 509 l 139 355 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},",":{x_min:0,x_max:142,ha:239,o:"m 142 -12 q 105 -132 142 -82 q 0 -205 68 -182 l 0 -138 q 57 -82 40 -124 q 70 0 70 -51 l 0 0 l 0 151 l 142 151 l 142 -12 "},d:{x_min:0,x_max:683,ha:796,o:"m 683 0 l 564 0 l 564 93 q 456 6 516 38 q 327 -25 395 -25 q 87 100 181 -25 q 0 365 0 215 q 90 639 0 525 q 343 763 187 763 q 564 647 486 763 l 564 1013 l 683 1013 l 683 0 m 582 373 q 529 562 582 484 q 361 653 468 653 q 190 561 253 653 q 135 365 135 479 q 189 175 135 254 q 358 85 251 85 q 529 178 468 85 q 582 373 582 258 "},"¨":{x_min:-109,x_max:247,ha:232,o:"m 247 1046 l 119 1046 l 119 1189 l 247 1189 l 247 1046 m 19 1046 l -109 1046 l -109 1189 l 19 1189 l 19 1046 "},E:{x_min:0,x_max:736.109375,ha:789,o:"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},Y:{x_min:0,x_max:820,ha:886,o:"m 820 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 534 l 679 1012 l 820 1013 "},"\"":{x_min:0,x_max:299,ha:396,o:"m 299 606 l 203 606 l 203 988 l 299 988 l 299 606 m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"‹":{x_min:17.984375,x_max:773.609375,ha:792,o:"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"„":{x_min:0,x_max:364,ha:467,o:"m 141 -12 q 104 -132 141 -82 q 0 -205 67 -182 l 0 -138 q 56 -82 40 -124 q 69 0 69 -51 l 0 0 l 0 151 l 141 151 l 141 -12 m 364 -12 q 327 -132 364 -82 q 222 -205 290 -182 l 222 -138 q 279 -82 262 -124 q 292 0 292 -51 l 222 0 l 222 151 l 364 151 l 364 -12 "},"δ":{x_min:1,x_max:710,ha:810,o:"m 710 360 q 616 87 710 196 q 356 -28 518 -28 q 99 82 197 -28 q 1 356 1 192 q 100 606 1 509 q 355 703 199 703 q 180 829 288 754 q 70 903 124 866 l 70 1012 l 643 1012 l 643 901 l 258 901 q 462 763 422 794 q 636 592 577 677 q 710 360 710 485 m 584 365 q 552 501 584 447 q 451 602 521 555 q 372 611 411 611 q 197 541 258 611 q 136 355 136 472 q 190 171 136 245 q 358 85 252 85 q 528 173 465 85 q 584 365 584 252 "},"έ":{x_min:0,x_max:634.71875,ha:714,o:"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 313 0 265 q 128 390 67 352 q 56 459 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 m 520 1040 l 331 819 l 248 819 l 383 1040 l 520 1040 "},"ω":{x_min:0,x_max:922,ha:1031,o:"m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 339 0 203 q 45 551 0 444 q 161 738 84 643 l 302 738 q 175 553 219 647 q 124 336 124 446 q 155 179 124 249 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 342 797 257 q 745 556 797 450 q 619 738 705 638 l 760 738 q 874 551 835 640 q 922 339 922 444 "},"´":{x_min:0,x_max:96,ha:251,o:"m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"±":{x_min:11,x_max:781,ha:792,o:"m 781 490 l 446 490 l 446 255 l 349 255 l 349 490 l 11 490 l 11 586 l 349 586 l 349 819 l 446 819 l 446 586 l 781 586 l 781 490 m 781 21 l 11 21 l 11 115 l 781 115 l 781 21 "},"|":{x_min:343,x_max:449,ha:792,o:"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"Ï‹":{x_min:0,x_max:617,ha:725,o:"m 482 800 l 372 800 l 372 925 l 482 925 l 482 800 m 239 800 l 129 800 l 129 925 l 239 925 l 239 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 "},"§":{x_min:0,x_max:593,ha:690,o:"m 593 425 q 554 312 593 369 q 467 233 516 254 q 537 83 537 172 q 459 -74 537 -12 q 288 -133 387 -133 q 115 -69 184 -133 q 47 96 47 -6 l 166 96 q 199 7 166 40 q 288 -26 232 -26 q 371 -5 332 -26 q 420 60 420 21 q 311 201 420 139 q 108 309 210 255 q 0 490 0 383 q 33 602 0 551 q 124 687 66 654 q 75 743 93 712 q 58 812 58 773 q 133 984 58 920 q 300 1043 201 1043 q 458 987 394 1043 q 529 814 529 925 l 411 814 q 370 908 404 877 q 289 939 336 939 q 213 911 246 939 q 180 841 180 883 q 286 720 180 779 q 484 612 480 615 q 593 425 593 534 m 467 409 q 355 544 467 473 q 196 630 228 612 q 146 587 162 609 q 124 525 124 558 q 239 387 124 462 q 398 298 369 315 q 448 345 429 316 q 467 409 467 375 "},b:{x_min:0,x_max:685,ha:783,o:"m 685 372 q 597 99 685 213 q 347 -25 501 -25 q 219 5 277 -25 q 121 93 161 36 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 634 q 214 723 157 692 q 341 754 272 754 q 591 637 493 754 q 685 372 685 526 m 554 356 q 499 550 554 470 q 328 644 437 644 q 162 556 223 644 q 108 369 108 478 q 160 176 108 256 q 330 83 221 83 q 498 169 435 83 q 554 356 554 245 "},q:{x_min:0,x_max:683,ha:876,o:"m 683 -278 l 564 -278 l 564 97 q 474 8 533 39 q 345 -23 415 -23 q 91 93 188 -23 q 0 364 0 203 q 87 635 0 522 q 337 760 184 760 q 466 727 408 760 q 564 637 523 695 l 564 737 l 683 737 l 683 -278 m 582 375 q 527 564 582 488 q 358 652 466 652 q 190 565 253 652 q 135 377 135 488 q 189 179 135 261 q 361 84 251 84 q 530 179 469 84 q 582 375 582 260 "},"Ω":{x_min:-0.171875,x_max:969.5625,ha:1068,o:"m 969 0 l 555 0 l 555 123 q 744 308 675 194 q 814 558 814 423 q 726 812 814 709 q 484 922 633 922 q 244 820 334 922 q 154 567 154 719 q 223 316 154 433 q 412 123 292 199 l 412 0 l 0 0 l 0 124 l 217 124 q 68 327 122 210 q 15 572 15 444 q 144 911 15 781 q 484 1041 274 1041 q 822 909 691 1041 q 953 569 953 777 q 899 326 953 443 q 750 124 846 210 l 969 124 l 969 0 "},"Ï":{x_min:0,x_max:617,ha:725,o:"m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 535 1040 l 346 819 l 262 819 l 397 1040 l 535 1040 "},z:{x_min:-0.015625,x_max:613.890625,ha:697,o:"m 613 0 l 0 0 l 0 100 l 433 630 l 20 630 l 20 738 l 594 738 l 593 636 l 163 110 l 613 110 l 613 0 "},"â„¢":{x_min:0,x_max:894,ha:1000,o:"m 389 951 l 229 951 l 229 503 l 160 503 l 160 951 l 0 951 l 0 1011 l 389 1011 l 389 951 m 894 503 l 827 503 l 827 939 l 685 503 l 620 503 l 481 937 l 481 503 l 417 503 l 417 1011 l 517 1011 l 653 580 l 796 1010 l 894 1011 l 894 503 "},"ή":{x_min:0.78125,x_max:697,ha:810,o:"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 721 124 755 q 200 630 193 687 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 m 479 1040 l 290 819 l 207 819 l 341 1040 l 479 1040 "},"Θ":{x_min:0,x_max:960,ha:1056,o:"m 960 507 q 833 129 960 280 q 476 -32 698 -32 q 123 129 255 -32 q 0 507 0 280 q 123 883 0 732 q 476 1045 255 1045 q 832 883 696 1045 q 960 507 960 732 m 817 500 q 733 789 817 669 q 476 924 639 924 q 223 792 317 924 q 142 507 142 675 q 222 222 142 339 q 476 89 315 89 q 730 218 636 89 q 817 500 817 334 m 716 449 l 243 449 l 243 571 l 716 571 l 716 449 "},"®":{x_min:-3,x_max:1008,ha:1106,o:"m 503 532 q 614 562 566 532 q 672 658 672 598 q 614 747 672 716 q 503 772 569 772 l 338 772 l 338 532 l 503 532 m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 788 146 l 678 146 q 653 316 655 183 q 527 449 652 449 l 338 449 l 338 146 l 241 146 l 241 854 l 518 854 q 688 808 621 854 q 766 658 766 755 q 739 563 766 607 q 668 497 713 519 q 751 331 747 472 q 788 164 756 190 l 788 146 "},"~":{x_min:0,x_max:833,ha:931,o:"m 833 958 q 778 753 833 831 q 594 665 716 665 q 402 761 502 665 q 240 857 302 857 q 131 795 166 857 q 104 665 104 745 l 0 665 q 54 867 0 789 q 237 958 116 958 q 429 861 331 958 q 594 765 527 765 q 704 827 670 765 q 729 958 729 874 l 833 958 "},"Ε":{x_min:0,x_max:736.21875,ha:778,o:"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},"³":{x_min:0,x_max:450,ha:547,o:"m 450 552 q 379 413 450 464 q 220 366 313 366 q 69 414 130 366 q 0 567 0 470 l 85 567 q 126 470 85 504 q 225 437 168 437 q 320 467 280 437 q 360 552 360 498 q 318 632 360 608 q 213 657 276 657 q 195 657 203 657 q 176 657 181 657 l 176 722 q 279 733 249 722 q 334 815 334 752 q 300 881 334 856 q 220 907 267 907 q 133 875 169 907 q 97 781 97 844 l 15 781 q 78 926 15 875 q 220 972 135 972 q 364 930 303 972 q 426 817 426 888 q 344 697 426 733 q 421 642 392 681 q 450 552 450 603 "},"[":{x_min:0,x_max:273.609375,ha:371,o:"m 273 -281 l 0 -281 l 0 1013 l 273 1013 l 273 920 l 124 920 l 124 -187 l 273 -187 l 273 -281 "},L:{x_min:0,x_max:645.828125,ha:696,o:"m 645 0 l 0 0 l 0 1013 l 140 1013 l 140 126 l 645 126 l 645 0 "},"σ":{x_min:0,x_max:803.390625,ha:894,o:"m 803 628 l 633 628 q 713 368 713 512 q 618 93 713 204 q 357 -25 518 -25 q 94 91 194 -25 q 0 368 0 201 q 94 644 0 533 q 356 761 194 761 q 481 750 398 761 q 608 739 564 739 l 803 739 l 803 628 m 360 85 q 529 180 467 85 q 584 374 584 262 q 527 566 584 490 q 352 651 463 651 q 187 559 247 651 q 135 368 135 478 q 189 175 135 254 q 360 85 251 85 "},"ζ":{x_min:0,x_max:573,ha:642,o:"m 573 -40 q 553 -162 573 -97 q 510 -278 543 -193 l 400 -278 q 441 -187 428 -219 q 462 -90 462 -132 q 378 -14 462 -14 q 108 45 197 -14 q 0 290 0 117 q 108 631 0 462 q 353 901 194 767 l 55 901 l 55 1012 l 561 1012 l 561 924 q 261 669 382 831 q 128 301 128 489 q 243 117 128 149 q 458 98 350 108 q 573 -40 573 80 "},"θ":{x_min:0,x_max:674,ha:778,o:"m 674 496 q 601 160 674 304 q 336 -26 508 -26 q 73 153 165 -26 q 0 485 0 296 q 72 840 0 683 q 343 1045 166 1045 q 605 844 516 1045 q 674 496 674 692 m 546 579 q 498 798 546 691 q 336 935 437 935 q 178 798 237 935 q 126 579 137 701 l 546 579 m 546 475 l 126 475 q 170 233 126 348 q 338 80 230 80 q 504 233 447 80 q 546 475 546 346 "},"Ο":{x_min:0,x_max:958,ha:1054,o:"m 485 1042 q 834 883 703 1042 q 958 511 958 735 q 834 136 958 287 q 481 -26 701 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 729 q 485 1042 263 1042 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 670 q 480 913 640 913 q 226 785 321 913 q 142 504 142 671 q 226 224 142 339 q 480 98 319 98 "},"Γ":{x_min:0,x_max:705.28125,ha:749,o:"m 705 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 705 1012 l 705 886 "}," ":{x_min:0,x_max:0,ha:375},"%":{x_min:-3,x_max:1089,ha:1186,o:"m 845 0 q 663 76 731 0 q 602 244 602 145 q 661 412 602 344 q 845 489 728 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 845 0 962 0 m 844 103 q 945 143 909 103 q 981 243 981 184 q 947 340 981 301 q 844 385 909 385 q 744 342 781 385 q 708 243 708 300 q 741 147 708 186 q 844 103 780 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 "},P:{x_min:0,x_max:726,ha:806,o:"m 424 1013 q 640 931 555 1013 q 726 719 726 850 q 637 506 726 587 q 413 426 548 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 379 889 l 140 889 l 140 548 l 372 548 q 522 589 459 548 q 593 720 593 637 q 528 845 593 801 q 379 889 463 889 "},"Έ":{x_min:0,x_max:1078.21875,ha:1118,o:"m 1078 0 l 342 0 l 342 1013 l 1067 1013 l 1067 889 l 481 889 l 481 585 l 1019 585 l 1019 467 l 481 467 l 481 125 l 1078 125 l 1078 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Î":{x_min:0.125,x_max:1136.546875,ha:1235,o:"m 1136 0 l 722 0 l 722 123 q 911 309 842 194 q 981 558 981 423 q 893 813 981 710 q 651 923 800 923 q 411 821 501 923 q 321 568 321 720 q 390 316 321 433 q 579 123 459 200 l 579 0 l 166 0 l 166 124 l 384 124 q 235 327 289 210 q 182 572 182 444 q 311 912 182 782 q 651 1042 441 1042 q 989 910 858 1042 q 1120 569 1120 778 q 1066 326 1120 443 q 917 124 1013 210 l 1136 124 l 1136 0 m 277 1040 l 83 800 l 0 800 l 140 1041 l 277 1040 "},_:{x_min:0,x_max:705.5625,ha:803,o:"m 705 -334 l 0 -334 l 0 -234 l 705 -234 l 705 -334 "},"Ϊ":{x_min:-110,x_max:246,ha:275,o:"m 246 1046 l 118 1046 l 118 1189 l 246 1189 l 246 1046 m 18 1046 l -110 1046 l -110 1189 l 18 1189 l 18 1046 m 136 0 l 0 0 l 0 1012 l 136 1012 l 136 0 "},"+":{x_min:23,x_max:768,ha:792,o:"m 768 372 l 444 372 l 444 0 l 347 0 l 347 372 l 23 372 l 23 468 l 347 468 l 347 840 l 444 840 l 444 468 l 768 468 l 768 372 "},"½":{x_min:0,x_max:1050,ha:1149,o:"m 1050 0 l 625 0 q 712 178 625 108 q 878 277 722 187 q 967 385 967 328 q 932 456 967 429 q 850 484 897 484 q 759 450 798 484 q 721 352 721 416 l 640 352 q 706 502 640 448 q 851 551 766 551 q 987 509 931 551 q 1050 385 1050 462 q 976 251 1050 301 q 829 179 902 215 q 717 68 740 133 l 1050 68 l 1050 0 m 834 985 l 215 -28 l 130 -28 l 750 984 l 834 985 m 224 422 l 142 422 l 142 811 l 0 811 l 0 867 q 104 889 62 867 q 164 973 157 916 l 224 973 l 224 422 "},"Ρ":{x_min:0,x_max:720,ha:783,o:"m 424 1013 q 637 933 554 1013 q 720 723 720 853 q 633 508 720 591 q 413 426 546 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 378 889 l 140 889 l 140 548 l 371 548 q 521 589 458 548 q 592 720 592 637 q 527 845 592 801 q 378 889 463 889 "},"'":{x_min:0,x_max:139,ha:236,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"ª":{x_min:0,x_max:350,ha:397,o:"m 350 625 q 307 616 328 616 q 266 631 281 616 q 247 673 251 645 q 190 628 225 644 q 116 613 156 613 q 32 641 64 613 q 0 722 0 669 q 72 826 0 800 q 247 866 159 846 l 247 887 q 220 934 247 916 q 162 953 194 953 q 104 934 129 953 q 76 882 80 915 l 16 882 q 60 976 16 941 q 166 1011 104 1011 q 266 979 224 1011 q 308 891 308 948 l 308 706 q 311 679 308 688 q 331 670 315 670 l 350 672 l 350 625 m 247 757 l 247 811 q 136 790 175 798 q 64 726 64 773 q 83 682 64 697 q 132 667 103 667 q 207 690 174 667 q 247 757 247 718 "},"Î…":{x_min:0,x_max:450,ha:553,o:"m 450 800 l 340 800 l 340 925 l 450 925 l 450 800 m 406 1040 l 212 800 l 129 800 l 269 1040 l 406 1040 m 110 800 l 0 800 l 0 925 l 110 925 l 110 800 "},T:{x_min:0,x_max:777,ha:835,o:"m 777 894 l 458 894 l 458 0 l 319 0 l 319 894 l 0 894 l 0 1013 l 777 1013 l 777 894 "},"Φ":{x_min:0,x_max:915,ha:997,o:"m 527 0 l 389 0 l 389 122 q 110 231 220 122 q 0 509 0 340 q 110 785 0 677 q 389 893 220 893 l 389 1013 l 527 1013 l 527 893 q 804 786 693 893 q 915 509 915 679 q 805 231 915 341 q 527 122 696 122 l 527 0 m 527 226 q 712 310 641 226 q 779 507 779 389 q 712 705 779 627 q 527 787 641 787 l 527 226 m 389 226 l 389 787 q 205 698 275 775 q 136 505 136 620 q 206 308 136 391 q 389 226 276 226 "},"â‹":{x_min:0,x_max:0,ha:694},j:{x_min:-77.78125,x_max:167,ha:349,o:"m 167 871 l 42 871 l 42 1013 l 167 1013 l 167 871 m 167 -80 q 121 -231 167 -184 q -26 -278 76 -278 l -77 -278 l -77 -164 l -41 -164 q 26 -143 11 -164 q 42 -65 42 -122 l 42 737 l 167 737 l 167 -80 "},"Σ":{x_min:0,x_max:756.953125,ha:819,o:"m 756 0 l 0 0 l 0 107 l 395 523 l 22 904 l 22 1013 l 745 1013 l 745 889 l 209 889 l 566 523 l 187 125 l 756 125 l 756 0 "},"›":{x_min:18.0625,x_max:774,ha:792,o:"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},"<":{x_min:17.984375,x_max:773.609375,ha:792,o:"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"£":{x_min:0,x_max:704.484375,ha:801,o:"m 704 41 q 623 -10 664 5 q 543 -26 583 -26 q 359 15 501 -26 q 243 36 288 36 q 158 23 197 36 q 73 -21 119 10 l 6 76 q 125 195 90 150 q 175 331 175 262 q 147 443 175 383 l 0 443 l 0 512 l 108 512 q 43 734 43 623 q 120 929 43 854 q 358 1010 204 1010 q 579 936 487 1010 q 678 729 678 857 l 678 684 l 552 684 q 504 838 552 780 q 362 896 457 896 q 216 852 263 896 q 176 747 176 815 q 199 627 176 697 q 248 512 217 574 l 468 512 l 468 443 l 279 443 q 297 356 297 398 q 230 194 297 279 q 153 107 211 170 q 227 133 190 125 q 293 142 264 142 q 410 119 339 142 q 516 96 482 96 q 579 105 550 96 q 648 142 608 115 l 704 41 "},t:{x_min:0,x_max:367,ha:458,o:"m 367 0 q 312 -5 339 -2 q 262 -8 284 -8 q 145 28 183 -8 q 108 143 108 64 l 108 638 l 0 638 l 0 738 l 108 738 l 108 944 l 232 944 l 232 738 l 367 738 l 367 638 l 232 638 l 232 185 q 248 121 232 140 q 307 102 264 102 q 345 104 330 102 q 367 107 360 107 l 367 0 "},"¬":{x_min:0,x_max:706,ha:803,o:"m 706 411 l 706 158 l 630 158 l 630 335 l 0 335 l 0 411 l 706 411 "},"λ":{x_min:0,x_max:750,ha:803,o:"m 750 -7 q 679 -15 716 -15 q 538 59 591 -15 q 466 214 512 97 l 336 551 l 126 0 l 0 0 l 270 705 q 223 837 247 770 q 116 899 190 899 q 90 898 100 899 l 90 1004 q 152 1011 125 1011 q 298 938 244 1011 q 373 783 326 901 l 605 192 q 649 115 629 136 q 716 95 669 95 l 736 95 q 750 97 745 97 l 750 -7 "},W:{x_min:0,x_max:1263.890625,ha:1351,o:"m 1263 1013 l 995 0 l 859 0 l 627 837 l 405 0 l 265 0 l 0 1013 l 136 1013 l 342 202 l 556 1013 l 701 1013 l 921 207 l 1133 1012 l 1263 1013 "},">":{x_min:18.0625,x_max:774,ha:792,o:"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},v:{x_min:0,x_max:675.15625,ha:761,o:"m 675 738 l 404 0 l 272 0 l 0 738 l 133 737 l 340 147 l 541 737 l 675 738 "},"Ï„":{x_min:0.28125,x_max:644.5,ha:703,o:"m 644 628 l 382 628 l 382 179 q 388 120 382 137 q 436 91 401 91 q 474 94 447 91 q 504 97 501 97 l 504 0 q 454 -9 482 -5 q 401 -14 426 -14 q 278 67 308 -14 q 260 233 260 118 l 260 628 l 0 628 l 0 739 l 644 739 l 644 628 "},"ξ":{x_min:0,x_max:624.9375,ha:699,o:"m 624 -37 q 608 -153 624 -96 q 563 -278 593 -211 l 454 -278 q 491 -183 486 -200 q 511 -83 511 -126 q 484 -23 511 -44 q 370 1 452 1 q 323 0 354 1 q 283 -1 293 -1 q 84 76 169 -1 q 0 266 0 154 q 56 431 0 358 q 197 538 108 498 q 94 613 134 562 q 54 730 54 665 q 77 823 54 780 q 143 901 101 867 l 27 901 l 27 1012 l 576 1012 l 576 901 l 380 901 q 244 863 303 901 q 178 745 178 820 q 312 600 178 636 q 532 582 380 582 l 532 479 q 276 455 361 479 q 118 281 118 410 q 165 173 118 217 q 274 120 208 133 q 494 101 384 110 q 624 -37 624 76 "},"&":{x_min:-3,x_max:894.25,ha:992,o:"m 894 0 l 725 0 l 624 123 q 471 0 553 40 q 306 -41 390 -41 q 168 -7 231 -41 q 62 92 105 26 q 14 187 31 139 q -3 276 -3 235 q 55 433 -3 358 q 248 581 114 508 q 170 689 196 640 q 137 817 137 751 q 214 985 137 922 q 384 1041 284 1041 q 548 988 483 1041 q 622 824 622 928 q 563 666 622 739 q 431 556 516 608 l 621 326 q 649 407 639 361 q 663 493 653 426 l 781 493 q 703 229 781 352 l 894 0 m 504 818 q 468 908 504 877 q 384 940 433 940 q 293 907 331 940 q 255 818 255 875 q 289 714 255 767 q 363 628 313 678 q 477 729 446 682 q 504 818 504 771 m 556 209 l 314 499 q 179 395 223 449 q 135 283 135 341 q 146 222 135 253 q 183 158 158 192 q 333 80 241 80 q 556 209 448 80 "},"Λ":{x_min:0,x_max:862.5,ha:942,o:"m 862 0 l 719 0 l 426 847 l 143 0 l 0 0 l 356 1013 l 501 1013 l 862 0 "},I:{x_min:41,x_max:180,ha:293,o:"m 180 0 l 41 0 l 41 1013 l 180 1013 l 180 0 "},G:{x_min:0,x_max:921,ha:1011,o:"m 921 0 l 832 0 l 801 136 q 655 15 741 58 q 470 -28 568 -28 q 126 133 259 -28 q 0 499 0 284 q 125 881 0 731 q 486 1043 259 1043 q 763 957 647 1043 q 905 709 890 864 l 772 709 q 668 866 747 807 q 486 926 589 926 q 228 795 322 926 q 142 507 142 677 q 228 224 142 342 q 483 94 323 94 q 712 195 625 94 q 796 435 796 291 l 477 435 l 477 549 l 921 549 l 921 0 "},"ΰ":{x_min:0,x_max:617,ha:725,o:"m 524 800 l 414 800 l 414 925 l 524 925 l 524 800 m 183 800 l 73 800 l 73 925 l 183 925 l 183 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 489 1040 l 300 819 l 216 819 l 351 1040 l 489 1040 "},"`":{x_min:0,x_max:138.890625,ha:236,o:"m 138 699 l 0 699 l 0 861 q 36 974 0 929 q 138 1041 72 1020 l 138 977 q 82 931 95 969 q 69 839 69 893 l 138 839 l 138 699 "},"·":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"Î¥":{x_min:0.328125,x_max:819.515625,ha:889,o:"m 819 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 "},r:{x_min:0,x_max:355.5625,ha:432,o:"m 355 621 l 343 621 q 179 569 236 621 q 122 411 122 518 l 122 0 l 0 0 l 0 737 l 117 737 l 117 604 q 204 719 146 686 q 355 753 262 753 l 355 621 "},x:{x_min:0,x_max:675,ha:764,o:"m 675 0 l 525 0 l 331 286 l 144 0 l 0 0 l 256 379 l 12 738 l 157 737 l 336 473 l 516 738 l 661 738 l 412 380 l 675 0 "},"μ":{x_min:0,x_max:696.609375,ha:747,o:"m 696 -4 q 628 -14 657 -14 q 498 97 513 -14 q 422 8 470 41 q 313 -24 374 -24 q 207 3 258 -24 q 120 80 157 31 l 120 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 172 124 246 q 308 82 216 82 q 451 177 402 82 q 492 358 492 254 l 492 738 l 616 738 l 616 214 q 623 136 616 160 q 673 92 636 92 q 696 95 684 92 l 696 -4 "},h:{x_min:0,x_max:615,ha:724,o:"m 615 472 l 615 0 l 490 0 l 490 454 q 456 590 490 535 q 338 654 416 654 q 186 588 251 654 q 122 436 122 522 l 122 0 l 0 0 l 0 1013 l 122 1013 l 122 633 q 218 727 149 694 q 362 760 287 760 q 552 676 484 760 q 615 472 615 600 "},".":{x_min:0,x_max:142,ha:239,o:"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"φ":{x_min:-2,x_max:878,ha:974,o:"m 496 -279 l 378 -279 l 378 -17 q 101 88 204 -17 q -2 367 -2 194 q 68 626 -2 510 q 283 758 151 758 l 283 646 q 167 537 209 626 q 133 373 133 462 q 192 177 133 254 q 378 93 259 93 l 378 758 q 445 764 426 763 q 476 765 464 765 q 765 659 653 765 q 878 377 878 553 q 771 96 878 209 q 496 -17 665 -17 l 496 -279 m 496 93 l 514 93 q 687 183 623 93 q 746 380 746 265 q 691 569 746 491 q 522 658 629 658 l 496 656 l 496 93 "},";":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 -12 q 105 -132 142 -82 q 0 -206 68 -182 l 0 -138 q 58 -82 43 -123 q 68 0 68 -56 l 0 0 l 0 151 l 142 151 l 142 -12 "},f:{x_min:0,x_max:378,ha:472,o:"m 378 638 l 246 638 l 246 0 l 121 0 l 121 638 l 0 638 l 0 738 l 121 738 q 137 935 121 887 q 290 1028 171 1028 q 320 1027 305 1028 q 378 1021 334 1026 l 378 908 q 323 918 346 918 q 257 870 273 918 q 246 780 246 840 l 246 738 l 378 738 l 378 638 "},"“":{x_min:1,x_max:348.21875,ha:454,o:"m 140 670 l 1 670 l 1 830 q 37 943 1 897 q 140 1011 74 990 l 140 947 q 82 900 97 940 q 68 810 68 861 l 140 810 l 140 670 m 348 670 l 209 670 l 209 830 q 245 943 209 897 q 348 1011 282 990 l 348 947 q 290 900 305 940 q 276 810 276 861 l 348 810 l 348 670 "},A:{x_min:0.03125,x_max:906.953125,ha:1008,o:"m 906 0 l 756 0 l 648 303 l 251 303 l 142 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 610 421 l 452 867 l 293 421 l 610 421 "},"‘":{x_min:1,x_max:139.890625,ha:236,o:"m 139 670 l 1 670 l 1 830 q 37 943 1 897 q 139 1011 74 990 l 139 947 q 82 900 97 940 q 68 810 68 861 l 139 810 l 139 670 "},"ÏŠ":{x_min:-70,x_max:283,ha:361,o:"m 283 800 l 173 800 l 173 925 l 283 925 l 283 800 m 40 800 l -70 800 l -70 925 l 40 925 l 40 800 m 283 3 q 232 -10 257 -5 q 181 -15 206 -15 q 84 26 118 -15 q 41 200 41 79 l 41 737 l 166 737 l 167 215 q 171 141 167 157 q 225 101 182 101 q 247 103 238 101 q 283 112 256 104 l 283 3 "},"Ï€":{x_min:-0.21875,x_max:773.21875,ha:857,o:"m 773 -7 l 707 -11 q 575 40 607 -11 q 552 174 552 77 l 552 226 l 552 626 l 222 626 l 222 0 l 97 0 l 97 626 l 0 626 l 0 737 l 773 737 l 773 626 l 676 626 l 676 171 q 695 103 676 117 q 773 90 714 90 l 773 -7 "},"ά":{x_min:0,x_max:765.5625,ha:809,o:"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 727 407 760 q 563 637 524 695 l 563 738 l 685 738 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 95 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 m 604 1040 l 415 819 l 332 819 l 466 1040 l 604 1040 "},O:{x_min:0,x_max:958,ha:1057,o:"m 485 1041 q 834 882 702 1041 q 958 512 958 734 q 834 136 958 287 q 481 -26 702 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 728 q 485 1041 263 1041 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 669 q 480 912 640 912 q 226 784 321 912 q 142 504 142 670 q 226 224 142 339 q 480 98 319 98 "},n:{x_min:0,x_max:615,ha:724,o:"m 615 463 l 615 0 l 490 0 l 490 454 q 453 592 490 537 q 331 656 410 656 q 178 585 240 656 q 117 421 117 514 l 117 0 l 0 0 l 0 738 l 117 738 l 117 630 q 218 728 150 693 q 359 764 286 764 q 552 675 484 764 q 615 463 615 593 "},l:{x_min:41,x_max:166,ha:279,o:"m 166 0 l 41 0 l 41 1013 l 166 1013 l 166 0 "},"¤":{x_min:40.09375,x_max:728.796875,ha:825,o:"m 728 304 l 649 224 l 512 363 q 383 331 458 331 q 256 363 310 331 l 119 224 l 40 304 l 177 441 q 150 553 150 493 q 184 673 150 621 l 40 818 l 119 898 l 267 749 q 321 766 291 759 q 384 773 351 773 q 447 766 417 773 q 501 749 477 759 l 649 898 l 728 818 l 585 675 q 612 618 604 648 q 621 553 621 587 q 591 441 621 491 l 728 304 m 384 682 q 280 643 318 682 q 243 551 243 604 q 279 461 243 499 q 383 423 316 423 q 487 461 449 423 q 525 553 525 500 q 490 641 525 605 q 384 682 451 682 "},"κ":{x_min:0,x_max:632.328125,ha:679,o:"m 632 0 l 482 0 l 225 384 l 124 288 l 124 0 l 0 0 l 0 738 l 124 738 l 124 446 l 433 738 l 596 738 l 312 466 l 632 0 "},p:{x_min:0,x_max:685,ha:786,o:"m 685 364 q 598 96 685 205 q 350 -23 504 -23 q 121 89 205 -23 l 121 -278 l 0 -278 l 0 738 l 121 738 l 121 633 q 220 726 159 691 q 351 761 280 761 q 598 636 504 761 q 685 364 685 522 m 557 371 q 501 560 557 481 q 330 651 437 651 q 162 559 223 651 q 108 366 108 479 q 162 177 108 254 q 333 87 224 87 q 502 178 441 87 q 557 371 557 258 "},"‡":{x_min:0,x_max:777,ha:835,o:"m 458 238 l 458 0 l 319 0 l 319 238 l 0 238 l 0 360 l 319 360 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 l 777 804 l 777 683 l 458 683 l 458 360 l 777 360 l 777 238 l 458 238 "},"ψ":{x_min:0,x_max:808,ha:907,o:"m 465 -278 l 341 -278 l 341 -15 q 87 102 180 -15 q 0 378 0 210 l 0 739 l 133 739 l 133 379 q 182 195 133 275 q 341 98 242 98 l 341 922 l 465 922 l 465 98 q 623 195 563 98 q 675 382 675 278 l 675 742 l 808 742 l 808 381 q 720 104 808 213 q 466 -13 627 -13 l 465 -278 "},"η":{x_min:0.78125,x_max:697,ha:810,o:"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 720 124 755 q 200 630 193 686 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 "}};var cssFontWeight="normal";var ascender=1189;var underlinePosition=-100;var cssFontStyle="normal";var boundingBox={yMin:-334,xMin:-111,yMax:1189,xMax:1672};var resolution=1000;var original_font_information={postscript_name:"Helvetiker-Regular",version_string:"Version 1.00 2004 initial release",vendor_url:"http://www.magenta.gr/",full_font_name:"Helvetiker",font_family_name:"Helvetiker",copyright:"Copyright (c) Îœagenta ltd, 2004",description:"",trademark:"",designer:"",designer_url:"",unique_font_identifier:"Îœagenta ltd:Helvetiker:22-10-104",license_url:"http://www.ellak.gr/fonts/MgOpen/license.html",license_description:"Copyright (c) 2004 by MAGENTA Ltd. All Rights Reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license (\"Fonts\") and associated documentation files (the \"Font Software\"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: \r\n\r\nThe above copyright and this permission notice shall be included in all copies of one or more of the Font Software typefaces.\r\n\r\nThe Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing the word \"MgOpen\", or if the modifications are accepted for inclusion in the Font Software itself by the each appointed Administrator.\r\n\r\nThis License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the \"MgOpen\" name.\r\n\r\nThe Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. \r\n\r\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL MAGENTA OR PERSONS OR BODIES IN CHARGE OF ADMINISTRATION AND MAINTENANCE OF THE FONT SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.",manufacturer_name:"Îœagenta ltd",font_sub_family_name:"Regular"};var descender=-334;var familyName="Helvetiker";var lineHeight=1522;var underlineThickness=50;var helvetiker_regular_typeface = {glyphs:glyphs,cssFontWeight:cssFontWeight,ascender:ascender,underlinePosition:underlinePosition,cssFontStyle:cssFontStyle,boundingBox:boundingBox,resolution:resolution,original_font_information:original_font_information,descender:descender,familyName:familyName,lineHeight:lineHeight,underlineThickness:underlineThickness}; -function setValueM2(gl, v) { - const cache = this.cache; - const elements = v.elements; - if (elements === undefined) { - if (arraysEqual(cache, v)) return; - gl.uniformMatrix2fv(this.addr, false, v); - copyArray(cache, v); - } else { - if (arraysEqual(cache, elements)) return; - mat2array.set(elements); - gl.uniformMatrix2fv(this.addr, false, mat2array); - copyArray(cache, elements); - } -} -function setValueM3(gl, v) { - const cache = this.cache; - const elements = v.elements; - if (elements === undefined) { - if (arraysEqual(cache, v)) return; - gl.uniformMatrix3fv(this.addr, false, v); - copyArray(cache, v); - } else { - if (arraysEqual(cache, elements)) return; - mat3array.set(elements); - gl.uniformMatrix3fv(this.addr, false, mat3array); - copyArray(cache, elements); - } -} -function setValueM4(gl, v) { - const cache = this.cache; - const elements = v.elements; - if (elements === undefined) { - if (arraysEqual(cache, v)) return; - gl.uniformMatrix4fv(this.addr, false, v); - copyArray(cache, v); - } else { - if (arraysEqual(cache, elements)) return; - mat4array.set(elements); - gl.uniformMatrix4fv(this.addr, false, mat4array); - copyArray(cache, elements); - } -} +var json1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + ascender: ascender, + boundingBox: boundingBox, + cssFontStyle: cssFontStyle, + cssFontWeight: cssFontWeight, + default: helvetiker_regular_typeface, + descender: descender, + familyName: familyName, + glyphs: glyphs, + lineHeight: lineHeight, + original_font_information: original_font_information, + resolution: resolution, + underlinePosition: underlinePosition, + underlineThickness: underlineThickness +}); -// Single integer / boolean +// -function setValueV1i(gl, v) { - const cache = this.cache; - if (cache[0] === v) return; - gl.uniform1i(this.addr, v); - cache[0] = v; -} +class Font { -// Single integer / boolean vector (from flat array or THREE.VectorN) + constructor( data ) { + + this.isFont = true; + + this.type = 'Font'; + + this.data = data; -function setValueV2i(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y) { - gl.uniform2i(this.addr, v.x, v.y); - cache[0] = v.x; - cache[1] = v.y; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform2iv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV3i(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { - gl.uniform3i(this.addr, v.x, v.y, v.z); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform3iv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV4i(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { - gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - cache[3] = v.w; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform4iv(this.addr, v); - copyArray(cache, v); } -} -// Single unsigned integer + generateShapes( text, size = 100 ) { -function setValueV1ui(gl, v) { - const cache = this.cache; - if (cache[0] === v) return; - gl.uniform1ui(this.addr, v); - cache[0] = v; -} + const shapes = []; + const paths = createPaths( text, size, this.data ); -// Single unsigned integer vector (from flat array or THREE.VectorN) + for ( let p = 0, pl = paths.length; p < pl; p ++ ) { + + shapes.push( ...paths[ p ].toShapes() ); -function setValueV2ui(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y) { - gl.uniform2ui(this.addr, v.x, v.y); - cache[0] = v.x; - cache[1] = v.y; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform2uiv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV3ui(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { - gl.uniform3ui(this.addr, v.x, v.y, v.z); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform3uiv(this.addr, v); - copyArray(cache, v); - } -} -function setValueV4ui(gl, v) { - const cache = this.cache; - if (v.x !== undefined) { - if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { - gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); - cache[0] = v.x; - cache[1] = v.y; - cache[2] = v.z; - cache[3] = v.w; } - } else { - if (arraysEqual(cache, v)) return; - gl.uniform4uiv(this.addr, v); - copyArray(cache, v); - } -} -// Single texture (2D / Cube) + return shapes; -function setValueT1(gl, v, textures) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); - if (cache[0] !== unit) { - gl.uniform1i(this.addr, unit); - cache[0] = unit; - } - textures.setTexture2D(v || emptyTexture, unit); -} -function setValueT3D1(gl, v, textures) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); - if (cache[0] !== unit) { - gl.uniform1i(this.addr, unit); - cache[0] = unit; - } - textures.setTexture3D(v || empty3dTexture, unit); -} -function setValueT6(gl, v, textures) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); - if (cache[0] !== unit) { - gl.uniform1i(this.addr, unit); - cache[0] = unit; - } - textures.setTextureCube(v || emptyCubeTexture, unit); -} -function setValueT2DArray1(gl, v, textures) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); - if (cache[0] !== unit) { - gl.uniform1i(this.addr, unit); - cache[0] = unit; } - textures.setTexture2DArray(v || emptyArrayTexture, unit); + } -// Helper to pick the right setter for the singular case +function createPaths( text, size, data ) { -function getSingularSetter(type) { - switch (type) { - case 0x1406: - return setValueV1f; - // FLOAT - case 0x8b50: - return setValueV2f; - // _VEC2 - case 0x8b51: - return setValueV3f; - // _VEC3 - case 0x8b52: - return setValueV4f; - // _VEC4 - - case 0x8b5a: - return setValueM2; - // _MAT2 - case 0x8b5b: - return setValueM3; - // _MAT3 - case 0x8b5c: - return setValueM4; - // _MAT4 - - case 0x1404: - case 0x8b56: - return setValueV1i; - // INT, BOOL - case 0x8b53: - case 0x8b57: - return setValueV2i; - // _VEC2 - case 0x8b54: - case 0x8b58: - return setValueV3i; - // _VEC3 - case 0x8b55: - case 0x8b59: - return setValueV4i; - // _VEC4 - - case 0x1405: - return setValueV1ui; - // UINT - case 0x8dc6: - return setValueV2ui; - // _VEC2 - case 0x8dc7: - return setValueV3ui; - // _VEC3 - case 0x8dc8: - return setValueV4ui; - // _VEC4 + const chars = Array.from( text ); + const scale = size / data.resolution; + const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: - // SAMPLER_2D_SHADOW - return setValueT1; - case 0x8b5f: // SAMPLER_3D - case 0x8dcb: // INT_SAMPLER_3D - case 0x8dd3: - // UNSIGNED_INT_SAMPLER_3D - return setValueT3D1; - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: - // SAMPLER_CUBE_SHADOW - return setValueT6; - case 0x8dc1: // SAMPLER_2D_ARRAY - case 0x8dcf: // INT_SAMPLER_2D_ARRAY - case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY - case 0x8dc4: - // SAMPLER_2D_ARRAY_SHADOW - return setValueT2DArray1; - } -} + const paths = []; -// Array of scalars + let offsetX = 0, offsetY = 0; -function setValueV1fArray(gl, v) { - gl.uniform1fv(this.addr, v); -} + for ( let i = 0; i < chars.length; i ++ ) { -// Array of vectors (from flat array or array of THREE.VectorN) + const char = chars[ i ]; -function setValueV2fArray(gl, v) { - const data = flatten(v, this.size, 2); - gl.uniform2fv(this.addr, data); -} -function setValueV3fArray(gl, v) { - const data = flatten(v, this.size, 3); - gl.uniform3fv(this.addr, data); -} -function setValueV4fArray(gl, v) { - const data = flatten(v, this.size, 4); - gl.uniform4fv(this.addr, data); -} + if ( char === '\n' ) { -// Array of matrices (from flat array or array of THREE.MatrixN) + offsetX = 0; + offsetY -= line_height; -function setValueM2Array(gl, v) { - const data = flatten(v, this.size, 4); - gl.uniformMatrix2fv(this.addr, false, data); -} -function setValueM3Array(gl, v) { - const data = flatten(v, this.size, 9); - gl.uniformMatrix3fv(this.addr, false, data); -} -function setValueM4Array(gl, v) { - const data = flatten(v, this.size, 16); - gl.uniformMatrix4fv(this.addr, false, data); -} + } else { -// Array of integer / boolean + const ret = createPath( char, scale, offsetX, offsetY, data ); + offsetX += ret.offsetX; + paths.push( ret.path ); -function setValueV1iArray(gl, v) { - gl.uniform1iv(this.addr, v); -} + } -// Array of integer / boolean vectors (from flat array) + } + + return paths; -function setValueV2iArray(gl, v) { - gl.uniform2iv(this.addr, v); -} -function setValueV3iArray(gl, v) { - gl.uniform3iv(this.addr, v); -} -function setValueV4iArray(gl, v) { - gl.uniform4iv(this.addr, v); } -// Array of unsigned integer +function createPath( char, scale, offsetX, offsetY, data ) { -function setValueV1uiArray(gl, v) { - gl.uniform1uiv(this.addr, v); -} + const glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; -// Array of unsigned integer vectors (from flat array) + if ( ! glyph ) { -function setValueV2uiArray(gl, v) { - gl.uniform2uiv(this.addr, v); -} -function setValueV3uiArray(gl, v) { - gl.uniform3uiv(this.addr, v); -} -function setValueV4uiArray(gl, v) { - gl.uniform4uiv(this.addr, v); -} + console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); -// Array of textures (2D / 3D / Cube / 2DArray) + return; -function setValueT1Array(gl, v, textures) { - const cache = this.cache; - const n = v.length; - const units = allocTexUnits(textures, n); - if (!arraysEqual(cache, units)) { - gl.uniform1iv(this.addr, units); - copyArray(cache, units); - } - for (let i = 0; i !== n; ++i) { - textures.setTexture2D(v[i] || emptyTexture, units[i]); - } -} -function setValueT3DArray(gl, v, textures) { - const cache = this.cache; - const n = v.length; - const units = allocTexUnits(textures, n); - if (!arraysEqual(cache, units)) { - gl.uniform1iv(this.addr, units); - copyArray(cache, units); - } - for (let i = 0; i !== n; ++i) { - textures.setTexture3D(v[i] || empty3dTexture, units[i]); - } -} -function setValueT6Array(gl, v, textures) { - const cache = this.cache; - const n = v.length; - const units = allocTexUnits(textures, n); - if (!arraysEqual(cache, units)) { - gl.uniform1iv(this.addr, units); - copyArray(cache, units); - } - for (let i = 0; i !== n; ++i) { - textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); } -} -function setValueT2DArrayArray(gl, v, textures) { - const cache = this.cache; - const n = v.length; - const units = allocTexUnits(textures, n); - if (!arraysEqual(cache, units)) { - gl.uniform1iv(this.addr, units); - copyArray(cache, units); - } - for (let i = 0; i !== n; ++i) { - textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); - } -} -// Helper to pick the right setter for a pure (bottom-level) array + const path = new ShapePath(); -function getPureArraySetter(type) { - switch (type) { - case 0x1406: - return setValueV1fArray; - // FLOAT - case 0x8b50: - return setValueV2fArray; - // _VEC2 - case 0x8b51: - return setValueV3fArray; - // _VEC3 - case 0x8b52: - return setValueV4fArray; - // _VEC4 - - case 0x8b5a: - return setValueM2Array; - // _MAT2 - case 0x8b5b: - return setValueM3Array; - // _MAT3 - case 0x8b5c: - return setValueM4Array; - // _MAT4 - - case 0x1404: - case 0x8b56: - return setValueV1iArray; - // INT, BOOL - case 0x8b53: - case 0x8b57: - return setValueV2iArray; - // _VEC2 - case 0x8b54: - case 0x8b58: - return setValueV3iArray; - // _VEC3 - case 0x8b55: - case 0x8b59: - return setValueV4iArray; - // _VEC4 - - case 0x1405: - return setValueV1uiArray; - // UINT - case 0x8dc6: - return setValueV2uiArray; - // _VEC2 - case 0x8dc7: - return setValueV3uiArray; - // _VEC3 - case 0x8dc8: - return setValueV4uiArray; - // _VEC4 + let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: - // SAMPLER_2D_SHADOW - return setValueT1Array; - case 0x8b5f: // SAMPLER_3D - case 0x8dcb: // INT_SAMPLER_3D - case 0x8dd3: - // UNSIGNED_INT_SAMPLER_3D - return setValueT3DArray; - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: - // SAMPLER_CUBE_SHADOW - return setValueT6Array; - case 0x8dc1: // SAMPLER_2D_ARRAY - case 0x8dcf: // INT_SAMPLER_2D_ARRAY - case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY - case 0x8dc4: - // SAMPLER_2D_ARRAY_SHADOW - return setValueT2DArrayArray; - } -} + if ( glyph.o ) { -// --- Uniform Classes --- + const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); -class SingleUniform { - constructor(id, activeInfo, addr) { - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter(activeInfo.type); + for ( let i = 0, l = outline.length; i < l; ) { - // this.path = activeInfo.name; // DEBUG - } -} + const action = outline[ i ++ ]; -class PureArrayUniform { - constructor(id, activeInfo, addr) { - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter(activeInfo.type); + switch ( action ) { - // this.path = activeInfo.name; // DEBUG - } -} + case 'm': // moveTo -class StructuredUniform { - constructor(id) { - this.id = id; - this.seq = []; - this.map = {}; - } - setValue(gl, value, textures) { - const seq = this.seq; - for (let i = 0, n = seq.length; i !== n; ++i) { - const u = seq[i]; - u.setValue(gl, value[u.id], textures); - } - } -} + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; -// --- Top-level --- + path.moveTo( x, y ); -// Parser - builds up the property tree from the path strings + break; -const RePathPart = /(\w+)(\])?(\[|\.)?/g; + case 'l': // lineTo -// extracts -// - the identifier (member name or array index) -// - followed by an optional right bracket (found when array index) -// - followed by an optional left bracket or dot (type of subscript) -// -// Note: These portions can be read in a non-overlapping fashion and -// allow straightforward parsing of the hierarchy that WebGL encodes -// in the uniform names. + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; -function addUniform(container, uniformObject) { - container.seq.push(uniformObject); - container.map[uniformObject.id] = uniformObject; -} -function parseUniform(activeInfo, addr, container) { - const path = activeInfo.name, - pathLength = path.length; + path.lineTo( x, y ); - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; - while (true) { - const match = RePathPart.exec(path), - matchEnd = RePathPart.lastIndex; - let id = match[1]; - const idIsIndex = match[2] === ']', - subscript = match[3]; - if (idIsIndex) id = id | 0; // convert to integer + break; - if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) { - // bare name or "pure" bottom-level array "[0]" suffix + case 'q': // quadraticCurveTo - addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); - break; - } else { - // step into inner node / create it in case it doesn't exist + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; - const map = container.map; - let next = map[id]; - if (next === undefined) { - next = new StructuredUniform(id); - addUniform(container, next); - } - container = next; - } - } -} + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); -// Root Container + break; + + case 'b': // bezierCurveTo + + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; + cpx2 = outline[ i ++ ] * scale + offsetX; + cpy2 = outline[ i ++ ] * scale + offsetY; + + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + + break; -class WebGLUniforms { - constructor(gl, program) { - this.seq = []; - this.map = {}; - const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (let i = 0; i < n; ++i) { - const info = gl.getActiveUniform(program, i), - addr = gl.getUniformLocation(program, info.name); - parseUniform(info, addr, this); - } - } - setValue(gl, name, value, textures) { - const u = this.map[name]; - if (u !== undefined) u.setValue(gl, value, textures); - } - setOptional(gl, object, name) { - const v = object[name]; - if (v !== undefined) this.setValue(gl, name, v); - } - static upload(gl, seq, values, textures) { - for (let i = 0, n = seq.length; i !== n; ++i) { - const u = seq[i], - v = values[u.id]; - if (v.needsUpdate !== false) { - // note: always updating when .needsUpdate is undefined - u.setValue(gl, v.value, textures); } + } + } - static seqWithValue(seq, values) { - const r = []; - for (let i = 0, n = seq.length; i !== n; ++i) { - const u = seq[i]; - if (u.id in values) r.push(u); - } - return r; - } -} -function WebGLShader(gl, type, string) { - const shader = gl.createShader(type); - gl.shaderSource(shader, string); - gl.compileShader(shader); - return shader; -} + return { offsetX: glyph.ha * scale, path: path }; -let programIdCount = 0; -function handleSource(string, errorLine) { - const lines = string.split('\n'); - const lines2 = []; - const from = Math.max(errorLine - 6, 0); - const to = Math.min(errorLine + 6, lines.length); - for (let i = from; i < to; i++) { - const line = i + 1; - lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`); - } - return lines2.join('\n'); -} -function getEncodingComponents(encoding) { - switch (encoding) { - case LinearEncoding: - return ['Linear', '( value )']; - case sRGBEncoding: - return ['sRGB', '( value )']; - default: - console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding); - return ['Linear', '( value )']; - } } -function getShaderErrors(gl, shader, type) { - const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); - const errors = gl.getShaderInfoLog(shader).trim(); - if (status && errors === '') return ''; - const errorMatches = /ERROR: 0:(\d+)/.exec(errors); - if (errorMatches) { - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - const errorLine = parseInt(errorMatches[1]); - return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine); - } else { - return errors; - } -} -function getTexelEncodingFunction(functionName, encoding) { - const components = getEncodingComponents(encoding); - return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }'; -} -function getToneMappingFunction(functionName, toneMapping) { - let toneMappingName; - switch (toneMapping) { - case LinearToneMapping: - toneMappingName = 'Linear'; - break; - case ReinhardToneMapping: - toneMappingName = 'Reinhard'; - break; - case CineonToneMapping: - toneMappingName = 'OptimizedCineon'; - break; - case ACESFilmicToneMapping: - toneMappingName = 'ACESFilmic'; - break; - case CustomToneMapping: - toneMappingName = 'Custom'; - break; - default: - console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping); - toneMappingName = 'Linear'; - } - return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; -} -function generateExtensions(parameters) { - const chunks = [parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '']; - return chunks.filter(filterEmptyLine).join('\n'); -} -function generateDefines(defines) { - const chunks = []; - for (const name in defines) { - const value = defines[name]; - if (value === false) continue; - chunks.push('#define ' + name + ' ' + value); - } - return chunks.join('\n'); -} -function fetchAttributeLocations(gl, program) { - const attributes = {}; - const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (let i = 0; i < n; i++) { - const info = gl.getActiveAttrib(program, i); - const name = info.name; - let locationSize = 1; - if (info.type === gl.FLOAT_MAT2) locationSize = 2; - if (info.type === gl.FLOAT_MAT3) locationSize = 3; - if (info.type === gl.FLOAT_MAT4) locationSize = 4; +// OrbitControls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). +// +// Orbit - left mouse / touch: one-finger move +// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish +// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move - // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; +const _ray = new Ray(); +const _plane = new Plane(); +const TILT_LIMIT = Math.cos( 70 * DEG2RAD ); - attributes[name] = { - type: info.type, - location: gl.getAttribLocation(program, name), - locationSize: locationSize - }; - } - return attributes; -} -function filterEmptyLine(string) { - return string !== ''; -} -function replaceLightNums(string, parameters) { - const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; - return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); -} -function replaceClippingPlaneNums(string, parameters) { - return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); -} +class OrbitControls extends EventDispatcher { -// Resolve Includes + constructor( object, domElement ) { -const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; -function resolveIncludes(string) { - return string.replace(includePattern, includeReplacer); -} -function includeReplacer(match, include) { - const string = ShaderChunk[include]; - if (string === undefined) { - throw new Error('Can not resolve #include <' + include + '>'); - } - return resolveIncludes(string); -} + super(); -// Unroll Loops + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll -const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; -function unrollLoops(string) { - return string.replace(unrollLoopPattern, loopReplacer); -} -function loopReplacer(match, start, end, snippet) { - let string = ''; - for (let i = parseInt(start); i < parseInt(end); i++) { - string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i); - } - return string; -} + // Set to false to disable this control + this.enabled = true; -// + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); -function generatePrecision(parameters) { - let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; - if (parameters.precision === 'highp') { - precisionstring += '\n#define HIGH_PRECISION'; - } else if (parameters.precision === 'mediump') { - precisionstring += '\n#define MEDIUM_PRECISION'; - } else if (parameters.precision === 'lowp') { - precisionstring += '\n#define LOW_PRECISION'; - } - return precisionstring; -} -function generateShadowMapTypeDefine(parameters) { - let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - if (parameters.shadowMapType === PCFShadowMap) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - } else if (parameters.shadowMapType === PCFSoftShadowMap) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - } else if (parameters.shadowMapType === VSMShadowMap) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; - } - return shadowMapTypeDefine; -} -function generateEnvMapTypeDefine(parameters) { - let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - if (parameters.envMap) { - switch (parameters.envMapMode) { - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; - case CubeUVReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; - } - } - return envMapTypeDefine; -} -function generateEnvMapModeDefine(parameters) { - let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - if (parameters.envMap) { - switch (parameters.envMapMode) { - case CubeRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; - } - } - return envMapModeDefine; -} -function generateEnvMapBlendingDefine(parameters) { - let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; - if (parameters.envMap) { - switch (parameters.combine) { - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; - } - } - return envMapBlendingDefine; -} -function generateCubeUVSize(parameters) { - const imageHeight = parameters.envMapCubeUVHeight; - if (imageHeight === null) return null; - const maxMip = Math.log2(imageHeight) - 2; - const texelHeight = 1.0 / imageHeight; - const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); - return { - texelWidth, - texelHeight, - maxMip - }; -} -function WebGLProgram(renderer, cacheKey, parameters, bindingStates) { - // TODO Send this event to Three.js DevTools - // console.log( 'WebGLProgram', cacheKey ); + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; - const gl = renderer.getContext(); - const defines = parameters.defines; - let vertexShader = parameters.vertexShader; - let fragmentShader = parameters.fragmentShader; - const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); - const envMapTypeDefine = generateEnvMapTypeDefine(parameters); - const envMapModeDefine = generateEnvMapModeDefine(parameters); - const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); - const envMapCubeUVSize = generateCubeUVSize(parameters); - const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters); - const customDefines = generateDefines(defines); - const program = gl.createProgram(); - let prefixVertex, prefixFragment; - let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; - if (parameters.isRawShaderMaterial) { - prefixVertex = [customDefines].filter(filterEmptyLine).join('\n'); - if (prefixVertex.length > 0) { - prefixVertex += '\n'; - } - prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n'); - if (prefixFragment.length > 0) { - prefixFragment += '\n'; - } - } else { - prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphColors && parameters.isWebGL2 ? '#define USE_MORPHCOLORS' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n'); - prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescence ? '#define USE_IRIDESCENCE' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', - // this code is required here because it is used by the toneMapping() function defined below - parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], - // this code is required here because it is used by the various encoding/decoding function defined below - getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n'); - } - vertexShader = resolveIncludes(vertexShader); - vertexShader = replaceLightNums(vertexShader, parameters); - vertexShader = replaceClippingPlaneNums(vertexShader, parameters); - fragmentShader = resolveIncludes(fragmentShader); - fragmentShader = replaceLightNums(fragmentShader, parameters); - fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); - vertexShader = unrollLoops(vertexShader); - fragmentShader = unrollLoops(fragmentShader); - if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) { - // GLSL 3.0 conversion for built-in materials and ShaderMaterial + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; - versionString = '#version 300 es\n'; - prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex; - prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment; - } - const vertexGlsl = versionString + prefixVertex + vertexShader; - const fragmentGlsl = versionString + prefixFragment + fragmentShader; + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians - const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); - const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); - gl.attachShader(program, glVertexShader); - gl.attachShader(program, glFragmentShader); + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; - // Force a particular attribute to index 0. + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; - if (parameters.index0AttributeName !== undefined) { - gl.bindAttribLocation(program, 0, parameters.index0AttributeName); - } else if (parameters.morphTargets === true) { - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation(program, 0, 'position'); - } - gl.linkProgram(program); + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; - // check for link errors - if (renderer.debug.checkShaderErrors) { - const programLog = gl.getProgramInfoLog(program).trim(); - const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); - const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); - let runnable = true; - let haveDiagnostics = true; - if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { - runnable = false; - const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex'); - const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment'); - console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors); - } else if (programLog !== '') { - console.warn('THREE.WebGLProgram: Program Info Log:', programLog); - } else if (vertexLog === '' || fragmentLog === '') { - haveDiagnostics = false; - } - if (haveDiagnostics) { - this.diagnostics = { - runnable: runnable, - programLog: programLog, - vertexShader: { - log: vertexLog, - prefix: prefixVertex - }, - fragmentShader: { - log: fragmentLog, - prefix: prefixFragment - } - }; - } - } + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push + this.zoomToCursor = false; - // Clean up + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - // Crashes in iOS9 and iOS10. #18402 - // gl.detachShader( program, glVertexShader ); - // gl.detachShader( program, glFragmentShader ); + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - gl.deleteShader(glVertexShader); - gl.deleteShader(glFragmentShader); + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - // set up caching for uniform locations + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - let cachedUniforms; - this.getUniforms = function () { - if (cachedUniforms === undefined) { - cachedUniforms = new WebGLUniforms(gl, program); - } - return cachedUniforms; - }; + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; - // set up caching for attribute locations + // the target DOM element for key events + this._domElementKeyEvents = null; - let cachedAttributes; - this.getAttributes = function () { - if (cachedAttributes === undefined) { - cachedAttributes = fetchAttributeLocations(gl, program); - } - return cachedAttributes; - }; + // + // public methods + // - // free resource + this.getPolarAngle = function () { - this.destroy = function () { - bindingStates.releaseStatesOfProgram(this); - gl.deleteProgram(program); - this.program = undefined; - }; + return spherical.phi; - // + }; - this.name = parameters.shaderName; - this.id = programIdCount++; - this.cacheKey = cacheKey; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; - return this; -} + this.getAzimuthalAngle = function () { -let _id = 0; -class WebGLShaderCache { - constructor() { - this.shaderCache = new Map(); - this.materialCache = new Map(); - } - update(material) { - const vertexShader = material.vertexShader; - const fragmentShader = material.fragmentShader; - const vertexShaderStage = this._getShaderStage(vertexShader); - const fragmentShaderStage = this._getShaderStage(fragmentShader); - const materialShaders = this._getShaderCacheForMaterial(material); - if (materialShaders.has(vertexShaderStage) === false) { - materialShaders.add(vertexShaderStage); - vertexShaderStage.usedTimes++; - } - if (materialShaders.has(fragmentShaderStage) === false) { - materialShaders.add(fragmentShaderStage); - fragmentShaderStage.usedTimes++; - } - return this; - } - remove(material) { - const materialShaders = this.materialCache.get(material); - for (const shaderStage of materialShaders) { - shaderStage.usedTimes--; - if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code); - } - this.materialCache.delete(material); - return this; - } - getVertexShaderID(material) { - return this._getShaderStage(material.vertexShader).id; - } - getFragmentShaderID(material) { - return this._getShaderStage(material.fragmentShader).id; - } - dispose() { - this.shaderCache.clear(); - this.materialCache.clear(); - } - _getShaderCacheForMaterial(material) { - const cache = this.materialCache; - let set = cache.get(material); - if (set === undefined) { - set = new Set(); - cache.set(material, set); - } - return set; - } - _getShaderStage(code) { - const cache = this.shaderCache; - let stage = cache.get(code); - if (stage === undefined) { - stage = new WebGLShaderStage(code); - cache.set(code, stage); - } - return stage; - } -} -class WebGLShaderStage { - constructor(code) { - this.id = _id++; - this.code = code; - this.usedTimes = 0; - } -} + return spherical.theta; -function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { - const _programLayers = new Layers(); - const _customShaders = new WebGLShaderCache(); - const programs = []; - const isWebGL2 = capabilities.isWebGL2; - const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - const vertexTextures = capabilities.vertexTextures; - let precision = capabilities.precision; - const shaderIDs = { - MeshDepthMaterial: 'depth', - MeshDistanceMaterial: 'distanceRGBA', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshToonMaterial: 'toon', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - MeshMatcapMaterial: 'matcap', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points', - ShadowMaterial: 'shadow', - SpriteMaterial: 'sprite' - }; - function getParameters(material, lights, shadows, scene, object) { - const fog = scene.fog; - const geometry = object.geometry; - const environment = material.isMeshStandardMaterial ? scene.environment : null; - const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); - const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; - const shaderID = shaderIDs[material.type]; + }; - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + this.getDistance = function () { - if (material.precision !== null) { - precision = capabilities.getMaxPrecision(material.precision); - if (precision !== material.precision) { - console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.'); - } - } + return this.object.position.distanceTo( this.target ); - // + }; - const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; - const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; - let morphTextureStride = 0; - if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1; - if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2; - if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; + this.listenToKeyEvents = function ( domElement ) { - // + domElement.addEventListener( 'keydown', onKeyDown ); + this._domElementKeyEvents = domElement; - let vertexShader, fragmentShader; - let customVertexShaderID, customFragmentShaderID; - if (shaderID) { - const shader = ShaderLib[shaderID]; - vertexShader = shader.vertexShader; - fragmentShader = shader.fragmentShader; - } else { - vertexShader = material.vertexShader; - fragmentShader = material.fragmentShader; - _customShaders.update(material); - customVertexShaderID = _customShaders.getVertexShaderID(material); - customFragmentShaderID = _customShaders.getFragmentShaderID(material); - } - const currentRenderTarget = renderer.getRenderTarget(); - const useAlphaTest = material.alphaTest > 0; - const useClearcoat = material.clearcoat > 0; - const useIridescence = material.iridescence > 0; - const parameters = { - isWebGL2: isWebGL2, - shaderID: shaderID, - shaderName: material.type, - vertexShader: vertexShader, - fragmentShader: fragmentShader, - defines: material.defines, - customVertexShaderID: customVertexShaderID, - customFragmentShaderID: customFragmentShaderID, - isRawShaderMaterial: material.isRawShaderMaterial === true, - glslVersion: material.glslVersion, - precision: precision, - instancing: object.isInstancedMesh === true, - instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, - supportsVertexTextures: vertexTextures, - outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding, - map: !!material.map, - matcap: !!material.matcap, - envMap: !!envMap, - envMapMode: envMap && envMap.mapping, - envMapCubeUVHeight: envMapCubeUVHeight, - lightMap: !!material.lightMap, - aoMap: !!material.aoMap, - emissiveMap: !!material.emissiveMap, - bumpMap: !!material.bumpMap, - normalMap: !!material.normalMap, - objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, - tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, - decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding, - clearcoat: useClearcoat, - clearcoatMap: useClearcoat && !!material.clearcoatMap, - clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap, - clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap, - iridescence: useIridescence, - iridescenceMap: useIridescence && !!material.iridescenceMap, - iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap, - displacementMap: !!material.displacementMap, - roughnessMap: !!material.roughnessMap, - metalnessMap: !!material.metalnessMap, - specularMap: !!material.specularMap, - specularIntensityMap: !!material.specularIntensityMap, - specularColorMap: !!material.specularColorMap, - opaque: material.transparent === false && material.blending === NormalBlending, - alphaMap: !!material.alphaMap, - alphaTest: useAlphaTest, - gradientMap: !!material.gradientMap, - sheen: material.sheen > 0, - sheenColorMap: !!material.sheenColorMap, - sheenRoughnessMap: !!material.sheenRoughnessMap, - transmission: material.transmission > 0, - transmissionMap: !!material.transmissionMap, - thicknessMap: !!material.thicknessMap, - combine: material.combine, - vertexTangents: !!material.normalMap && !!geometry.attributes.tangent, - vertexColors: material.vertexColors, - vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap, - uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap, - fog: !!fog, - useFog: material.fog === true, - fogExp2: fog && fog.isFogExp2, - flatShading: !!material.flatShading, - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: logarithmicDepthBuffer, - skinning: object.isSkinnedMesh === true, - morphTargets: geometry.morphAttributes.position !== undefined, - morphNormals: geometry.morphAttributes.normal !== undefined, - morphColors: geometry.morphAttributes.color !== undefined, - morphTargetsCount: morphTargetsCount, - morphTextureStride: morphTextureStride, - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numSpotLightMaps: lights.spotLightMap.length, - numRectAreaLights: lights.rectArea.length, - numHemiLights: lights.hemi.length, - numDirLightShadows: lights.directionalShadowMap.length, - numPointLightShadows: lights.pointShadowMap.length, - numSpotLightShadows: lights.spotShadowMap.length, - numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, - numClippingPlanes: clipping.numPlanes, - numClipIntersection: clipping.numIntersection, - dithering: material.dithering, - shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, - shadowMapType: renderer.shadowMap.type, - toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, - premultipliedAlpha: material.premultipliedAlpha, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, - useDepthPacking: !!material.depthPacking, - depthPacking: material.depthPacking || 0, - index0AttributeName: material.index0AttributeName, - extensionDerivatives: material.extensions && material.extensions.derivatives, - extensionFragDepth: material.extensions && material.extensions.fragDepth, - extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, - extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, - rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'), - rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'), - rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'), - customProgramCacheKey: material.customProgramCacheKey() }; - return parameters; - } - function getProgramCacheKey(parameters) { - const array = []; - if (parameters.shaderID) { - array.push(parameters.shaderID); - } else { - array.push(parameters.customVertexShaderID); - array.push(parameters.customFragmentShaderID); - } - if (parameters.defines !== undefined) { - for (const name in parameters.defines) { - array.push(name); - array.push(parameters.defines[name]); - } - } - if (parameters.isRawShaderMaterial === false) { - getProgramCacheKeyParameters(array, parameters); - getProgramCacheKeyBooleans(array, parameters); - array.push(renderer.outputEncoding); - } - array.push(parameters.customProgramCacheKey); - return array.join(); - } - function getProgramCacheKeyParameters(array, parameters) { - array.push(parameters.precision); - array.push(parameters.outputEncoding); - array.push(parameters.envMapMode); - array.push(parameters.envMapCubeUVHeight); - array.push(parameters.combine); - array.push(parameters.vertexUvs); - array.push(parameters.fogExp2); - array.push(parameters.sizeAttenuation); - array.push(parameters.morphTargetsCount); - array.push(parameters.morphAttributeCount); - array.push(parameters.numDirLights); - array.push(parameters.numPointLights); - array.push(parameters.numSpotLights); - array.push(parameters.numSpotLightMaps); - array.push(parameters.numHemiLights); - array.push(parameters.numRectAreaLights); - array.push(parameters.numDirLightShadows); - array.push(parameters.numPointLightShadows); - array.push(parameters.numSpotLightShadows); - array.push(parameters.numSpotLightShadowsWithMaps); - array.push(parameters.shadowMapType); - array.push(parameters.toneMapping); - array.push(parameters.numClippingPlanes); - array.push(parameters.numClipIntersection); - array.push(parameters.depthPacking); - } - function getProgramCacheKeyBooleans(array, parameters) { - _programLayers.disableAll(); - if (parameters.isWebGL2) _programLayers.enable(0); - if (parameters.supportsVertexTextures) _programLayers.enable(1); - if (parameters.instancing) _programLayers.enable(2); - if (parameters.instancingColor) _programLayers.enable(3); - if (parameters.map) _programLayers.enable(4); - if (parameters.matcap) _programLayers.enable(5); - if (parameters.envMap) _programLayers.enable(6); - if (parameters.lightMap) _programLayers.enable(7); - if (parameters.aoMap) _programLayers.enable(8); - if (parameters.emissiveMap) _programLayers.enable(9); - if (parameters.bumpMap) _programLayers.enable(10); - if (parameters.normalMap) _programLayers.enable(11); - if (parameters.objectSpaceNormalMap) _programLayers.enable(12); - if (parameters.tangentSpaceNormalMap) _programLayers.enable(13); - if (parameters.clearcoat) _programLayers.enable(14); - if (parameters.clearcoatMap) _programLayers.enable(15); - if (parameters.clearcoatRoughnessMap) _programLayers.enable(16); - if (parameters.clearcoatNormalMap) _programLayers.enable(17); - if (parameters.iridescence) _programLayers.enable(18); - if (parameters.iridescenceMap) _programLayers.enable(19); - if (parameters.iridescenceThicknessMap) _programLayers.enable(20); - if (parameters.displacementMap) _programLayers.enable(21); - if (parameters.specularMap) _programLayers.enable(22); - if (parameters.roughnessMap) _programLayers.enable(23); - if (parameters.metalnessMap) _programLayers.enable(24); - if (parameters.gradientMap) _programLayers.enable(25); - if (parameters.alphaMap) _programLayers.enable(26); - if (parameters.alphaTest) _programLayers.enable(27); - if (parameters.vertexColors) _programLayers.enable(28); - if (parameters.vertexAlphas) _programLayers.enable(29); - if (parameters.vertexUvs) _programLayers.enable(30); - if (parameters.vertexTangents) _programLayers.enable(31); - if (parameters.uvsVertexOnly) _programLayers.enable(32); - array.push(_programLayers.mask); - _programLayers.disableAll(); - if (parameters.fog) _programLayers.enable(0); - if (parameters.useFog) _programLayers.enable(1); - if (parameters.flatShading) _programLayers.enable(2); - if (parameters.logarithmicDepthBuffer) _programLayers.enable(3); - if (parameters.skinning) _programLayers.enable(4); - if (parameters.morphTargets) _programLayers.enable(5); - if (parameters.morphNormals) _programLayers.enable(6); - if (parameters.morphColors) _programLayers.enable(7); - if (parameters.premultipliedAlpha) _programLayers.enable(8); - if (parameters.shadowMapEnabled) _programLayers.enable(9); - if (parameters.physicallyCorrectLights) _programLayers.enable(10); - if (parameters.doubleSided) _programLayers.enable(11); - if (parameters.flipSided) _programLayers.enable(12); - if (parameters.useDepthPacking) _programLayers.enable(13); - if (parameters.dithering) _programLayers.enable(14); - if (parameters.specularIntensityMap) _programLayers.enable(15); - if (parameters.specularColorMap) _programLayers.enable(16); - if (parameters.transmission) _programLayers.enable(17); - if (parameters.transmissionMap) _programLayers.enable(18); - if (parameters.thicknessMap) _programLayers.enable(19); - if (parameters.sheen) _programLayers.enable(20); - if (parameters.sheenColorMap) _programLayers.enable(21); - if (parameters.sheenRoughnessMap) _programLayers.enable(22); - if (parameters.decodeVideoTexture) _programLayers.enable(23); - if (parameters.opaque) _programLayers.enable(24); - array.push(_programLayers.mask); - } - function getUniforms(material) { - const shaderID = shaderIDs[material.type]; - let uniforms; - if (shaderID) { - const shader = ShaderLib[shaderID]; - uniforms = UniformsUtils.clone(shader.uniforms); - } else { - uniforms = material.uniforms; - } - return uniforms; - } - function acquireProgram(parameters, cacheKey) { - let program; - // Check if code has been already compiled - for (let p = 0, pl = programs.length; p < pl; p++) { - const preexistingProgram = programs[p]; - if (preexistingProgram.cacheKey === cacheKey) { - program = preexistingProgram; - ++program.usedTimes; - break; - } - } - if (program === undefined) { - program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates); - programs.push(program); - } - return program; - } - function releaseProgram(program) { - if (--program.usedTimes === 0) { - // Remove from unordered set - const i = programs.indexOf(program); - programs[i] = programs[programs.length - 1]; - programs.pop(); + this.stopListenToKeyEvents = function () { - // Free WebGL resources - program.destroy(); - } - } - function releaseShaderCache(material) { - _customShaders.remove(material); - } - function dispose() { - _customShaders.dispose(); - } - return { - getParameters: getParameters, - getProgramCacheKey: getProgramCacheKey, - getUniforms: getUniforms, - acquireProgram: acquireProgram, - releaseProgram: releaseProgram, - releaseShaderCache: releaseShaderCache, - // Exposed for resource monitoring & error feedback via renderer.info: - programs: programs, - dispose: dispose - }; -} + this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); + this._domElementKeyEvents = null; -function WebGLProperties() { - let properties = new WeakMap(); - function get(object) { - let map = properties.get(object); - if (map === undefined) { - map = {}; - properties.set(object, map); - } - return map; - } - function remove(object) { - properties.delete(object); - } - function update(object, key, value) { - properties.get(object)[key] = value; - } - function dispose() { - properties = new WeakMap(); - } - return { - get: get, - remove: remove, - update: update, - dispose: dispose - }; -} + }; -function painterSortStable(a, b) { - if (a.groupOrder !== b.groupOrder) { - return a.groupOrder - b.groupOrder; - } else if (a.renderOrder !== b.renderOrder) { - return a.renderOrder - b.renderOrder; - } else if (a.material.id !== b.material.id) { - return a.material.id - b.material.id; - } else if (a.z !== b.z) { - return a.z - b.z; - } else { - return a.id - b.id; - } -} -function reversePainterSortStable(a, b) { - if (a.groupOrder !== b.groupOrder) { - return a.groupOrder - b.groupOrder; - } else if (a.renderOrder !== b.renderOrder) { - return a.renderOrder - b.renderOrder; - } else if (a.z !== b.z) { - return b.z - a.z; - } else { - return a.id - b.id; - } -} -function WebGLRenderList() { - const renderItems = []; - let renderItemsIndex = 0; - const opaque = []; - const transmissive = []; - const transparent = []; - function init() { - renderItemsIndex = 0; - opaque.length = 0; - transmissive.length = 0; - transparent.length = 0; - } - function getNextRenderItem(object, geometry, material, groupOrder, z, group) { - let renderItem = renderItems[renderItemsIndex]; - if (renderItem === undefined) { - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; - renderItems[renderItemsIndex] = renderItem; - } else { - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; - } - renderItemsIndex++; - return renderItem; - } - function push(object, geometry, material, groupOrder, z, group) { - const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); - if (material.transmission > 0.0) { - transmissive.push(renderItem); - } else if (material.transparent === true) { - transparent.push(renderItem); - } else { - opaque.push(renderItem); - } - } - function unshift(object, geometry, material, groupOrder, z, group) { - const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); - if (material.transmission > 0.0) { - transmissive.unshift(renderItem); - } else if (material.transparent === true) { - transparent.unshift(renderItem); - } else { - opaque.unshift(renderItem); - } - } - function sort(customOpaqueSort, customTransparentSort) { - if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable); - if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable); - if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable); - } - function finish() { - // Clear references from inactive renderItems in the list + this.saveState = function () { - for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) { - const renderItem = renderItems[i]; - if (renderItem.id === null) break; - renderItem.id = null; - renderItem.object = null; - renderItem.geometry = null; - renderItem.material = null; - renderItem.group = null; - } - } - return { - opaque: opaque, - transmissive: transmissive, - transparent: transparent, - init: init, - push: push, - unshift: unshift, - finish: finish, - sort: sort - }; -} -function WebGLRenderLists() { - let lists = new WeakMap(); - function get(scene, renderCallDepth) { - const listArray = lists.get(scene); - let list; - if (listArray === undefined) { - list = new WebGLRenderList(); - lists.set(scene, [list]); - } else { - if (renderCallDepth >= listArray.length) { - list = new WebGLRenderList(); - listArray.push(list); - } else { - list = listArray[renderCallDepth]; - } - } - return list; - } - function dispose() { - lists = new WeakMap(); - } - return { - get: get, - dispose: dispose - }; -} + scope.target0.copy( scope.target ); + scope.position0.copy( scope.object.position ); + scope.zoom0 = scope.object.zoom; -function UniformsCache() { - const lights = {}; - return { - get: function (light) { - if (lights[light.id] !== undefined) { - return lights[light.id]; - } - let uniforms; - switch (light.type) { - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color$1() - }; - break; - case 'SpotLight': - uniforms = { - position: new Vector3(), - direction: new Vector3(), - color: new Color$1(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0 - }; - break; - case 'PointLight': - uniforms = { - position: new Vector3(), - color: new Color$1(), - distance: 0, - decay: 0 - }; - break; - case 'HemisphereLight': - uniforms = { - direction: new Vector3(), - skyColor: new Color$1(), - groundColor: new Color$1() - }; - break; - case 'RectAreaLight': - uniforms = { - color: new Color$1(), - position: new Vector3(), - halfWidth: new Vector3(), - halfHeight: new Vector3() - }; - break; - } - lights[light.id] = uniforms; - return uniforms; - } - }; -} -function ShadowUniformsCache() { - const lights = {}; - return { - get: function (light) { - if (lights[light.id] !== undefined) { - return lights[light.id]; - } - let uniforms; - switch (light.type) { - case 'DirectionalLight': - uniforms = { - shadowBias: 0, - shadowNormalBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; - case 'SpotLight': - uniforms = { - shadowBias: 0, - shadowNormalBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; - case 'PointLight': - uniforms = { - shadowBias: 0, - shadowNormalBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2(), - shadowCameraNear: 1, - shadowCameraFar: 1000 - }; - break; + }; + + this.reset = function () { + + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.zoom = scope.zoom0; + + scope.object.updateProjectionMatrix(); + scope.dispatchEvent( _changeEvent ); + + scope.update(); + + state = STATE.NONE; + + }; + + this.resetOrthoPanZoom = function () { + panOffset.set(0,0,0); + scope.object.zoom = 1; + scope.object.updateProjectionMatrix(); + }; + + // this method is exposed, but perhaps it would be better if we can make it private... + this.update = function () { + + const offset = new Vector3(); + + // so camera.up is the orbit axis + const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + const quatInverse = quat.clone().invert(); + + const lastPosition = new Vector3(); + const lastQuaternion = new Quaternion(); + const lastTargetPosition = new Vector3(); - // TODO (abelnation): set RectAreaLight shadow uniforms - } + const twoPI = 2 * Math.PI; - lights[light.id] = uniforms; - return uniforms; - } - }; -} -let nextVersion = 0; -function shadowCastingAndTexturingLightsFirst(lightA, lightB) { - return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); -} -function WebGLLights(extensions, capabilities) { - const cache = new UniformsCache(); - const shadowCache = ShadowUniformsCache(); - const state = { - version: 0, - hash: { - directionalLength: -1, - pointLength: -1, - spotLength: -1, - rectAreaLength: -1, - hemiLength: -1, - numDirectionalShadows: -1, - numPointShadows: -1, - numSpotShadows: -1, - numSpotMaps: -1 - }, - ambient: [0, 0, 0], - probe: [], - directional: [], - directionalShadow: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotLightMap: [], - spotShadow: [], - spotShadowMap: [], - spotLightMatrix: [], - rectArea: [], - rectAreaLTC1: null, - rectAreaLTC2: null, - point: [], - pointShadow: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], - numSpotLightShadowsWithMaps: 0 - }; - for (let i = 0; i < 9; i++) state.probe.push(new Vector3()); - const vector3 = new Vector3(); - const matrix4 = new Matrix4(); - const matrix42 = new Matrix4(); - function setup(lights, physicallyCorrectLights) { - let r = 0, - g = 0, - b = 0; - for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0); - let directionalLength = 0; - let pointLength = 0; - let spotLength = 0; - let rectAreaLength = 0; - let hemiLength = 0; - let numDirectionalShadows = 0; - let numPointShadows = 0; - let numSpotShadows = 0; - let numSpotMaps = 0; - let numSpotShadowsWithMaps = 0; + return function update() { - // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] - lights.sort(shadowCastingAndTexturingLightsFirst); + const position = scope.object.position; - // artist-friendly light intensity scaling factor - const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1; - for (let i = 0, l = lights.length; i < l; i++) { - const light = lights[i]; - const color = light.color; - const intensity = light.intensity; - const distance = light.distance; - const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; - if (light.isAmbientLight) { - r += color.r * intensity * scaleFactor; - g += color.g * intensity * scaleFactor; - b += color.b * intensity * scaleFactor; - } else if (light.isLightProbe) { - for (let j = 0; j < 9; j++) { - state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); - } - } else if (light.isDirectionalLight) { - const uniforms = cache.get(light); - uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); - if (light.castShadow) { - const shadow = light.shadow; - const shadowUniforms = shadowCache.get(light); - shadowUniforms.shadowBias = shadow.bias; - shadowUniforms.shadowNormalBias = shadow.normalBias; - shadowUniforms.shadowRadius = shadow.radius; - shadowUniforms.shadowMapSize = shadow.mapSize; - state.directionalShadow[directionalLength] = shadowUniforms; - state.directionalShadowMap[directionalLength] = shadowMap; - state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; - numDirectionalShadows++; - } - state.directional[directionalLength] = uniforms; - directionalLength++; - } else if (light.isSpotLight) { - const uniforms = cache.get(light); - uniforms.position.setFromMatrixPosition(light.matrixWorld); - uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor); - uniforms.distance = distance; - uniforms.coneCos = Math.cos(light.angle); - uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); - uniforms.decay = light.decay; - state.spot[spotLength] = uniforms; - const shadow = light.shadow; - if (light.map) { - state.spotLightMap[numSpotMaps] = light.map; - numSpotMaps++; + offset.copy( position ).sub( scope.target ); + + // rotate offset to "y-axis-is-up" space + offset.applyQuaternion( quat ); + + // angle from z-axis around y-axis + spherical.setFromVector3( offset ); + + if ( scope.autoRotate && state === STATE.NONE ) { + + rotateLeft( getAutoRotationAngle() ); - // make sure the lightMatrix is up to date - // TODO : do it if required only - shadow.updateMatrices(light); - if (light.castShadow) numSpotShadowsWithMaps++; - } - state.spotLightMatrix[spotLength] = shadow.matrix; - if (light.castShadow) { - const shadowUniforms = shadowCache.get(light); - shadowUniforms.shadowBias = shadow.bias; - shadowUniforms.shadowNormalBias = shadow.normalBias; - shadowUniforms.shadowRadius = shadow.radius; - shadowUniforms.shadowMapSize = shadow.mapSize; - state.spotShadow[spotLength] = shadowUniforms; - state.spotShadowMap[spotLength] = shadowMap; - numSpotShadows++; - } - spotLength++; - } else if (light.isRectAreaLight) { - const uniforms = cache.get(light); - - // (a) intensity is the total visible light emitted - //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); - - // (b) intensity is the brightness of the light - uniforms.color.copy(color).multiplyScalar(intensity); - uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0); - uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0); - state.rectArea[rectAreaLength] = uniforms; - rectAreaLength++; - } else if (light.isPointLight) { - const uniforms = cache.get(light); - uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); - uniforms.distance = light.distance; - uniforms.decay = light.decay; - if (light.castShadow) { - const shadow = light.shadow; - const shadowUniforms = shadowCache.get(light); - shadowUniforms.shadowBias = shadow.bias; - shadowUniforms.shadowNormalBias = shadow.normalBias; - shadowUniforms.shadowRadius = shadow.radius; - shadowUniforms.shadowMapSize = shadow.mapSize; - shadowUniforms.shadowCameraNear = shadow.camera.near; - shadowUniforms.shadowCameraFar = shadow.camera.far; - state.pointShadow[pointLength] = shadowUniforms; - state.pointShadowMap[pointLength] = shadowMap; - state.pointShadowMatrix[pointLength] = light.shadow.matrix; - numPointShadows++; } - state.point[pointLength] = uniforms; - pointLength++; - } else if (light.isHemisphereLight) { - const uniforms = cache.get(light); - uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor); - uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor); - state.hemi[hemiLength] = uniforms; - hemiLength++; - } - } - if (rectAreaLength > 0) { - if (capabilities.isWebGL2) { - // WebGL 2 - state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; - state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; - } else { - // WebGL 1 + if ( scope.enableDamping ) { + + spherical.theta += sphericalDelta.theta * scope.dampingFactor; + spherical.phi += sphericalDelta.phi * scope.dampingFactor; - if (extensions.has('OES_texture_float_linear') === true) { - state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; - state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; - } else if (extensions.has('OES_texture_half_float_linear') === true) { - state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; - state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; } else { - console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.'); + + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; + } - } - } - state.ambient[0] = r; - state.ambient[1] = g; - state.ambient[2] = b; - const hash = state.hash; - if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps) { - state.directional.length = directionalLength; - state.spot.length = spotLength; - state.rectArea.length = rectAreaLength; - state.point.length = pointLength; - state.hemi.length = hemiLength; - state.directionalShadow.length = numDirectionalShadows; - state.directionalShadowMap.length = numDirectionalShadows; - state.pointShadow.length = numPointShadows; - state.pointShadowMap.length = numPointShadows; - state.spotShadow.length = numSpotShadows; - state.spotShadowMap.length = numSpotShadows; - state.directionalShadowMatrix.length = numDirectionalShadows; - state.pointShadowMatrix.length = numPointShadows; - state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; - state.spotLightMap.length = numSpotMaps; - state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; - hash.directionalLength = directionalLength; - hash.pointLength = pointLength; - hash.spotLength = spotLength; - hash.rectAreaLength = rectAreaLength; - hash.hemiLength = hemiLength; - hash.numDirectionalShadows = numDirectionalShadows; - hash.numPointShadows = numPointShadows; - hash.numSpotShadows = numSpotShadows; - hash.numSpotMaps = numSpotMaps; - state.version = nextVersion++; - } - } - function setupView(lights, camera) { - let directionalLength = 0; - let pointLength = 0; - let spotLength = 0; - let rectAreaLength = 0; - let hemiLength = 0; - const viewMatrix = camera.matrixWorldInverse; - for (let i = 0, l = lights.length; i < l; i++) { - const light = lights[i]; - if (light.isDirectionalLight) { - const uniforms = state.directional[directionalLength]; - uniforms.direction.setFromMatrixPosition(light.matrixWorld); - vector3.setFromMatrixPosition(light.target.matrixWorld); - uniforms.direction.sub(vector3); - uniforms.direction.transformDirection(viewMatrix); - directionalLength++; - } else if (light.isSpotLight) { - const uniforms = state.spot[spotLength]; - uniforms.position.setFromMatrixPosition(light.matrixWorld); - uniforms.position.applyMatrix4(viewMatrix); - uniforms.direction.setFromMatrixPosition(light.matrixWorld); - vector3.setFromMatrixPosition(light.target.matrixWorld); - uniforms.direction.sub(vector3); - uniforms.direction.transformDirection(viewMatrix); - spotLength++; - } else if (light.isRectAreaLight) { - const uniforms = state.rectArea[rectAreaLength]; - uniforms.position.setFromMatrixPosition(light.matrixWorld); - uniforms.position.applyMatrix4(viewMatrix); - // extract local rotation of light to derive width/height half vectors - matrix42.identity(); - matrix4.copy(light.matrixWorld); - matrix4.premultiply(viewMatrix); - matrix42.extractRotation(matrix4); - uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0); - uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0); - uniforms.halfWidth.applyMatrix4(matrix42); - uniforms.halfHeight.applyMatrix4(matrix42); - rectAreaLength++; - } else if (light.isPointLight) { - const uniforms = state.point[pointLength]; - uniforms.position.setFromMatrixPosition(light.matrixWorld); - uniforms.position.applyMatrix4(viewMatrix); - pointLength++; - } else if (light.isHemisphereLight) { - const uniforms = state.hemi[hemiLength]; - uniforms.direction.setFromMatrixPosition(light.matrixWorld); - uniforms.direction.transformDirection(viewMatrix); - hemiLength++; - } - } - } - return { - setup: setup, - setupView: setupView, - state: state - }; -} + // restrict theta to be between desired limits -function WebGLRenderState(extensions, capabilities) { - const lights = new WebGLLights(extensions, capabilities); - const lightsArray = []; - const shadowsArray = []; - function init() { - lightsArray.length = 0; - shadowsArray.length = 0; - } - function pushLight(light) { - lightsArray.push(light); - } - function pushShadow(shadowLight) { - shadowsArray.push(shadowLight); - } - function setupLights(physicallyCorrectLights) { - lights.setup(lightsArray, physicallyCorrectLights); - } - function setupLightsView(camera) { - lights.setupView(lightsArray, camera); - } - const state = { - lightsArray: lightsArray, - shadowsArray: shadowsArray, - lights: lights - }; - return { - init: init, - state: state, - setupLights: setupLights, - setupLightsView: setupLightsView, - pushLight: pushLight, - pushShadow: pushShadow - }; -} -function WebGLRenderStates(extensions, capabilities) { - let renderStates = new WeakMap(); - function get(scene, renderCallDepth = 0) { - const renderStateArray = renderStates.get(scene); - let renderState; - if (renderStateArray === undefined) { - renderState = new WebGLRenderState(extensions, capabilities); - renderStates.set(scene, [renderState]); - } else { - if (renderCallDepth >= renderStateArray.length) { - renderState = new WebGLRenderState(extensions, capabilities); - renderStateArray.push(renderState); - } else { - renderState = renderStateArray[renderCallDepth]; - } - } - return renderState; - } - function dispose() { - renderStates = new WeakMap(); - } - return { - get: get, - dispose: dispose - }; -} + let min = scope.minAzimuthAngle; + let max = scope.maxAzimuthAngle; -class MeshDepthMaterial extends Material { - constructor(parameters) { - super(); - this.isMeshDepthMaterial = true; - this.type = 'MeshDepthMaterial'; - this.depthPacking = BasicDepthPacking; - this.map = null; - this.alphaMap = null; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.depthPacking = source.depthPacking; - this.map = source.map; - this.alphaMap = source.alphaMap; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - return this; - } -} + if ( isFinite( min ) && isFinite( max ) ) { -class MeshDistanceMaterial extends Material { - constructor(parameters) { - super(); - this.isMeshDistanceMaterial = true; - this.type = 'MeshDistanceMaterial'; - this.referencePosition = new Vector3(); - this.nearDistance = 1; - this.farDistance = 1000; - this.map = null; - this.alphaMap = null; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.referencePosition.copy(source.referencePosition); - this.nearDistance = source.nearDistance; - this.farDistance = source.farDistance; - this.map = source.map; - this.alphaMap = source.alphaMap; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; - return this; - } -} + if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; -const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; -const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; -function WebGLShadowMap(_renderer, _objects, _capabilities) { - let _frustum = new Frustum(); - const _shadowMapSize = new Vector2(), - _viewportSize = new Vector2(), - _viewport = new Vector4(), - _depthMaterial = new MeshDepthMaterial({ - depthPacking: RGBADepthPacking - }), - _distanceMaterial = new MeshDistanceMaterial(), - _materialCache = {}, - _maxTextureSize = _capabilities.maxTextureSize; - const shadowSide = { - 0: BackSide, - 1: FrontSide, - 2: DoubleSide - }; - const shadowMaterialVertical = new ShaderMaterial({ - defines: { - VSM_SAMPLES: 8 - }, - uniforms: { - shadow_pass: { - value: null - }, - resolution: { - value: new Vector2() - }, - radius: { - value: 4.0 - } - }, - vertexShader: vertex, - fragmentShader: fragment - }); - const shadowMaterialHorizontal = shadowMaterialVertical.clone(); - shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; - const fullScreenTri = new BufferGeometry(); - fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); - const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); - const scope = this; - this.enabled = false; - this.autoUpdate = true; - this.needsUpdate = false; - this.type = PCFShadowMap; - this.render = function (lights, scene, camera) { - if (scope.enabled === false) return; - if (scope.autoUpdate === false && scope.needsUpdate === false) return; - if (lights.length === 0) return; - const currentRenderTarget = _renderer.getRenderTarget(); - const activeCubeFace = _renderer.getActiveCubeFace(); - const activeMipmapLevel = _renderer.getActiveMipmapLevel(); - const _state = _renderer.state; + if ( min <= max ) { - // Set GL state for depth map. - _state.setBlending(NoBlending); - _state.buffers.color.setClear(1, 1, 1, 1); - _state.buffers.depth.setTest(true); - _state.setScissorTest(false); + spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); - // render depth map + } else { + + spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, spherical.theta ) : + Math.min( max, spherical.theta ); + + } - for (let i = 0, il = lights.length; i < il; i++) { - const light = lights[i]; - const shadow = light.shadow; - if (shadow === undefined) { - console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.'); - continue; - } - if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue; - _shadowMapSize.copy(shadow.mapSize); - const shadowFrameExtents = shadow.getFrameExtents(); - _shadowMapSize.multiply(shadowFrameExtents); - _viewportSize.copy(shadow.mapSize); - if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { - if (_shadowMapSize.x > _maxTextureSize) { - _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); - _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; - shadow.mapSize.x = _viewportSize.x; - } - if (_shadowMapSize.y > _maxTextureSize) { - _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); - _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; - shadow.mapSize.y = _viewportSize.y; } - } - if (shadow.map === null) { - const pars = this.type !== VSMShadowMap ? { - minFilter: NearestFilter, - magFilter: NearestFilter - } : {}; - shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); - shadow.map.texture.name = light.name + '.shadowMap'; - shadow.camera.updateProjectionMatrix(); - } - _renderer.setRenderTarget(shadow.map); - _renderer.clear(); - const viewportCount = shadow.getViewportCount(); - for (let vp = 0; vp < viewportCount; vp++) { - const viewport = shadow.getViewport(vp); - _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); - _state.viewport(_viewport); - shadow.updateMatrices(light, vp); - _frustum = shadow.getFrustum(); - renderObject(scene, camera, shadow.camera, light, this.type); - } - // do blur pass for VSM + // restrict phi to be between desired limits + spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { - VSMPass(shadow, camera); - } - shadow.needsUpdate = false; - } - scope.needsUpdate = false; - _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); - }; - function VSMPass(shadow, camera) { - const geometry = _objects.update(fullScreenMesh); - if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { - shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; - shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; - shadowMaterialVertical.needsUpdate = true; - shadowMaterialHorizontal.needsUpdate = true; - } - if (shadow.mapPass === null) { - shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); - } + spherical.makeSafe(); - // vertical pass - shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; - shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; - shadowMaterialVertical.uniforms.radius.value = shadow.radius; - _renderer.setRenderTarget(shadow.mapPass); - _renderer.clear(); - _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + // move target to panned location - // horizontal pass + if ( scope.enableDamping === true ) { - shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; - shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; - shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; - _renderer.setRenderTarget(shadow.map); - _renderer.clear(); - _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); - } - function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) { - let result = null; - const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; - if (customMaterial !== undefined) { - result = customMaterial; - } else { - result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; - } - if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) { - // in this case we need a unique material instance reflecting the - // appropriate state - - const keyA = result.uuid, - keyB = material.uuid; - let materialsForVariant = _materialCache[keyA]; - if (materialsForVariant === undefined) { - materialsForVariant = {}; - _materialCache[keyA] = materialsForVariant; - } - let cachedMaterial = materialsForVariant[keyB]; - if (cachedMaterial === undefined) { - cachedMaterial = result.clone(); - materialsForVariant[keyB] = cachedMaterial; - } - result = cachedMaterial; - } - result.visible = material.visible; - result.wireframe = material.wireframe; - if (type === VSMShadowMap) { - result.side = material.shadowSide !== null ? material.shadowSide : material.side; - } else { - result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; - } - result.alphaMap = material.alphaMap; - result.alphaTest = material.alphaTest; - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; - result.clipIntersection = material.clipIntersection; - result.displacementMap = material.displacementMap; - result.displacementScale = material.displacementScale; - result.displacementBias = material.displacementBias; - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; - if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { - result.referencePosition.setFromMatrixPosition(light.matrixWorld); - result.nearDistance = shadowCameraNear; - result.farDistance = shadowCameraFar; - } - return result; - } - function renderObject(object, camera, shadowCamera, light, type) { - if (object.visible === false) return; - const visible = object.layers.test(camera.layers); - if (visible && (object.isMesh || object.isLine || object.isPoints)) { - if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) { - object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); - const geometry = _objects.update(object); - const material = object.material; - if (Array.isArray(material)) { - const groups = geometry.groups; - for (let k = 0, kl = groups.length; k < kl; k++) { - const group = groups[k]; - const groupMaterial = material[group.materialIndex]; - if (groupMaterial && groupMaterial.visible) { - const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type); - _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); - } - } - } else if (material.visible) { - const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type); - _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); - } - } - } - const children = object.children; - for (let i = 0, l = children.length; i < l; i++) { - renderObject(children[i], camera, shadowCamera, light, type); - } - } -} + scope.target.addScaledVector( panOffset, scope.dampingFactor ); + + } else { + + scope.target.add( panOffset ); -function WebGLState(gl, extensions, capabilities) { - const isWebGL2 = capabilities.isWebGL2; - function ColorBuffer() { - let locked = false; - const color = new Vector4(); - let currentColorMask = null; - const currentColorClear = new Vector4(0, 0, 0, 0); - return { - setMask: function (colorMask) { - if (currentColorMask !== colorMask && !locked) { - gl.colorMask(colorMask, colorMask, colorMask, colorMask); - currentColorMask = colorMask; - } - }, - setLocked: function (lock) { - locked = lock; - }, - setClear: function (r, g, b, a, premultipliedAlpha) { - if (premultipliedAlpha === true) { - r *= a; - g *= a; - b *= a; - } - color.set(r, g, b, a); - if (currentColorClear.equals(color) === false) { - gl.clearColor(r, g, b, a); - currentColorClear.copy(color); } - }, - reset: function () { - locked = false; - currentColorMask = null; - currentColorClear.set(-1, 0, 0, 0); // set to invalid state - } - }; - } - function DepthBuffer() { - let locked = false; - let currentDepthMask = null; - let currentDepthFunc = null; - let currentDepthClear = null; - return { - setTest: function (depthTest) { - if (depthTest) { - enable(gl.DEPTH_TEST); + // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera + // we adjust zoom later in these cases + if ( scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera ) { + + spherical.radius = clampDistance( spherical.radius ); + } else { - disable(gl.DEPTH_TEST); - } - }, - setMask: function (depthMask) { - if (currentDepthMask !== depthMask && !locked) { - gl.depthMask(depthMask); - currentDepthMask = depthMask; - } - }, - setFunc: function (depthFunc) { - if (currentDepthFunc !== depthFunc) { - switch (depthFunc) { - case NeverDepth: - gl.depthFunc(gl.NEVER); - break; - case AlwaysDepth: - gl.depthFunc(gl.ALWAYS); - break; - case LessDepth: - gl.depthFunc(gl.LESS); - break; - case LessEqualDepth: - gl.depthFunc(gl.LEQUAL); - break; - case EqualDepth: - gl.depthFunc(gl.EQUAL); - break; - case GreaterEqualDepth: - gl.depthFunc(gl.GEQUAL); - break; - case GreaterDepth: - gl.depthFunc(gl.GREATER); - break; - case NotEqualDepth: - gl.depthFunc(gl.NOTEQUAL); - break; - default: - gl.depthFunc(gl.LEQUAL); - } - currentDepthFunc = depthFunc; + + spherical.radius = clampDistance( spherical.radius * scale ); + } - }, - setLocked: function (lock) { - locked = lock; - }, - setClear: function (depth) { - if (currentDepthClear !== depth) { - gl.clearDepth(depth); - currentDepthClear = depth; + + + offset.setFromSpherical( spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + offset.applyQuaternion( quatInverse ); + + position.copy( scope.target ).add( offset ); + + scope.object.lookAt( scope.target ); + + if ( scope.enableDamping === true ) { + + sphericalDelta.theta *= ( 1 - scope.dampingFactor ); + sphericalDelta.phi *= ( 1 - scope.dampingFactor ); + + panOffset.multiplyScalar( 1 - scope.dampingFactor ); + + } else { + + sphericalDelta.set( 0, 0, 0 ); + + panOffset.set( 0, 0, 0 ); + } - }, - reset: function () { - locked = false; - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; - } - }; - } - function StencilBuffer() { - let locked = false; - let currentStencilMask = null; - let currentStencilFunc = null; - let currentStencilRef = null; - let currentStencilFuncMask = null; - let currentStencilFail = null; - let currentStencilZFail = null; - let currentStencilZPass = null; - let currentStencilClear = null; - return { - setTest: function (stencilTest) { - if (!locked) { - if (stencilTest) { - enable(gl.STENCIL_TEST); + + // adjust camera position + let zoomChanged = false; + if ( scope.zoomToCursor && performCursorZoom ) { + + let newRadius = null; + if ( scope.object.isPerspectiveCamera ) { + + // move the camera down the pointer ray + // this method avoids floating point error + const prevRadius = offset.length(); + newRadius = clampDistance( prevRadius * scale ); + + const radiusDelta = prevRadius - newRadius; + scope.object.position.addScaledVector( dollyDirection, radiusDelta ); + scope.object.updateMatrixWorld(); + + } else if ( scope.object.isOrthographicCamera ) { + + // adjust the ortho camera position based on zoom changes + const mouseBefore = new Vector3( mouse.x, mouse.y, 0 ); + mouseBefore.unproject( scope.object ); + + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + + const mouseAfter = new Vector3( mouse.x, mouse.y, 0 ); + mouseAfter.unproject( scope.object ); + + scope.object.position.sub( mouseAfter ).add( mouseBefore ); + scope.object.updateMatrixWorld(); + + newRadius = offset.length(); + } else { - disable(gl.STENCIL_TEST); + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); + scope.zoomToCursor = false; + } + + // handle the placement of the target + if ( newRadius !== null ) { + + if ( this.screenSpacePanning ) { + + // position the orbit target in front of the new camera position + scope.target.set( 0, 0, - 1 ) + .transformDirection( scope.object.matrix ) + .multiplyScalar( newRadius ) + .add( scope.object.position ); + + } else { + + // get the ray and translation plane to compute target + _ray.origin.copy( scope.object.position ); + _ray.direction.set( 0, 0, - 1 ).transformDirection( scope.object.matrix ); + + // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid + // extremely large values + if ( Math.abs( scope.object.up.dot( _ray.direction ) ) < TILT_LIMIT ) { + + object.lookAt( scope.target ); + + } else { + + _plane.setFromNormalAndCoplanarPoint( scope.object.up, scope.target ); + _ray.intersectPlane( _plane, scope.target ); + + } + + } + + } + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + } - }, - setMask: function (stencilMask) { - if (currentStencilMask !== stencilMask && !locked) { - gl.stencilMask(stencilMask); - currentStencilMask = stencilMask; - } - }, - setFunc: function (stencilFunc, stencilRef, stencilMask) { - if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { - gl.stencilFunc(stencilFunc, stencilRef, stencilMask); - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; - } - }, - setOp: function (stencilFail, stencilZFail, stencilZPass) { - if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { - gl.stencilOp(stencilFail, stencilZFail, stencilZPass); - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; - } - }, - setLocked: function (lock) { - locked = lock; - }, - setClear: function (stencil) { - if (currentStencilClear !== stencil) { - gl.clearStencil(stencil); - currentStencilClear = stencil; + + scale = 1; + performCursorZoom = false; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS || + lastTargetPosition.distanceToSquared( scope.target ) > 0 ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastQuaternion.copy( scope.object.quaternion ); + lastTargetPosition.copy( scope.target ); + + zoomChanged = false; + + return true; + } - }, - reset: function () { - locked = false; - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + + return false; + + }; + + }(); + + this.dispose = function () { + + scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); + + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerUp ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + + if ( scope._domElementKeyEvents !== null ) { + + scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); + scope._domElementKeyEvents = null; + } + + //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + }; - } - // + // + // internals + // - const colorBuffer = new ColorBuffer(); - const depthBuffer = new DepthBuffer(); - const stencilBuffer = new StencilBuffer(); - const uboBindings = new WeakMap(); - const uboProgamMap = new WeakMap(); - let enabledCapabilities = {}; - let currentBoundFramebuffers = {}; - let currentDrawbuffers = new WeakMap(); - let defaultDrawbuffers = []; - let currentProgram = null; - let currentBlendingEnabled = false; - let currentBlending = null; - let currentBlendEquation = null; - let currentBlendSrc = null; - let currentBlendDst = null; - let currentBlendEquationAlpha = null; - let currentBlendSrcAlpha = null; - let currentBlendDstAlpha = null; - let currentPremultipledAlpha = false; - let currentFlipSided = null; - let currentCullFace = null; - let currentLineWidth = null; - let currentPolygonOffsetFactor = null; - let currentPolygonOffsetUnits = null; - const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); - let lineWidthAvailable = false; - let version = 0; - const glVersion = gl.getParameter(gl.VERSION); - if (glVersion.indexOf('WebGL') !== -1) { - version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); - lineWidthAvailable = version >= 1.0; - } else if (glVersion.indexOf('OpenGL ES') !== -1) { - version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); - lineWidthAvailable = version >= 2.0; - } - let currentTextureSlot = null; - let currentBoundTextures = {}; - const scissorParam = gl.getParameter(gl.SCISSOR_BOX); - const viewportParam = gl.getParameter(gl.VIEWPORT); - const currentScissor = new Vector4().fromArray(scissorParam); - const currentViewport = new Vector4().fromArray(viewportParam); - function createTexture(type, target, count) { - const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4. - const texture = gl.createTexture(); - gl.bindTexture(type, texture); - gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - for (let i = 0; i < count; i++) { - gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); - } - return texture; - } - const emptyTextures = {}; - emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); - emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + const scope = this; - // init + const STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 + }; - colorBuffer.setClear(0, 0, 0, 1); - depthBuffer.setClear(1); - stencilBuffer.setClear(0); - enable(gl.DEPTH_TEST); - depthBuffer.setFunc(LessEqualDepth); - setFlipSided(false); - setCullFace(CullFaceBack); - enable(gl.CULL_FACE); - setBlending(NoBlending); + let state = STATE.NONE; - // + const EPS = 0.000001; - function enable(id) { - if (enabledCapabilities[id] !== true) { - gl.enable(id); - enabledCapabilities[id] = true; - } - } - function disable(id) { - if (enabledCapabilities[id] !== false) { - gl.disable(id); - enabledCapabilities[id] = false; - } - } - function bindFramebuffer(target, framebuffer) { - if (currentBoundFramebuffers[target] !== framebuffer) { - gl.bindFramebuffer(target, framebuffer); - currentBoundFramebuffers[target] = framebuffer; - if (isWebGL2) { - // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + // current position in spherical coordinates + const spherical = new Spherical(); + const sphericalDelta = new Spherical(); + + let scale = 1; + const panOffset = new Vector3(); + + const rotateStart = new Vector2(); + const rotateEnd = new Vector2(); + const rotateDelta = new Vector2(); + + const panStart = new Vector2(); + const panEnd = new Vector2(); + const panDelta = new Vector2(); + + const dollyStart = new Vector2(); + const dollyEnd = new Vector2(); + const dollyDelta = new Vector2(); + + const dollyDirection = new Vector3(); + const mouse = new Vector2(); + let performCursorZoom = false; + + const pointers = []; + const pointerPositions = {}; + + function getAutoRotationAngle() { + + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - if (target === gl.DRAW_FRAMEBUFFER) { - currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; - } - if (target === gl.FRAMEBUFFER) { - currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; - } - } - return true; - } - return false; - } - function drawBuffers(renderTarget, framebuffer) { - let drawBuffers = defaultDrawbuffers; - let needsUpdate = false; - if (renderTarget) { - drawBuffers = currentDrawbuffers.get(framebuffer); - if (drawBuffers === undefined) { - drawBuffers = []; - currentDrawbuffers.set(framebuffer, drawBuffers); - } - if (renderTarget.isWebGLMultipleRenderTargets) { - const textures = renderTarget.texture; - if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) { - for (let i = 0, il = textures.length; i < il; i++) { - drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i; - } - drawBuffers.length = textures.length; - needsUpdate = true; - } - } else { - if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) { - drawBuffers[0] = gl.COLOR_ATTACHMENT0; - needsUpdate = true; - } - } - } else { - if (drawBuffers[0] !== gl.BACK) { - drawBuffers[0] = gl.BACK; - needsUpdate = true; - } - } - if (needsUpdate) { - if (capabilities.isWebGL2) { - gl.drawBuffers(drawBuffers); - } else { - extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers); - } - } - } - function useProgram(program) { - if (currentProgram !== program) { - gl.useProgram(program); - currentProgram = program; - return true; } - return false; - } - const equationToGL = { - [AddEquation]: gl.FUNC_ADD, - [SubtractEquation]: gl.FUNC_SUBTRACT, - [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT - }; - if (isWebGL2) { - equationToGL[MinEquation] = gl.MIN; - equationToGL[MaxEquation] = gl.MAX; - } else { - const extension = extensions.get('EXT_blend_minmax'); - if (extension !== null) { - equationToGL[MinEquation] = extension.MIN_EXT; - equationToGL[MaxEquation] = extension.MAX_EXT; + + function getZoomScale() { + + return Math.pow( 0.95, scope.zoomSpeed ); + } - } - const factorToGL = { - [ZeroFactor]: gl.ZERO, - [OneFactor]: gl.ONE, - [SrcColorFactor]: gl.SRC_COLOR, - [SrcAlphaFactor]: gl.SRC_ALPHA, - [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, - [DstColorFactor]: gl.DST_COLOR, - [DstAlphaFactor]: gl.DST_ALPHA, - [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, - [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, - [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, - [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA - }; - function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) { - if (blending === NoBlending) { - if (currentBlendingEnabled === true) { - disable(gl.BLEND); - currentBlendingEnabled = false; - } - return; + + function rotateLeft( angle ) { + + sphericalDelta.theta -= angle; + } - if (currentBlendingEnabled === false) { - enable(gl.BLEND); - currentBlendingEnabled = true; + + function rotateUp( angle ) { + + sphericalDelta.phi -= angle; + } - if (blending !== CustomBlending) { - if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { - if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { - gl.blendEquation(gl.FUNC_ADD); - currentBlendEquation = AddEquation; - currentBlendEquationAlpha = AddEquation; - } - if (premultipliedAlpha) { - switch (blending) { - case NormalBlending: - gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - break; - case AdditiveBlending: - gl.blendFunc(gl.ONE, gl.ONE); - break; - case SubtractiveBlending: - gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); - break; - case MultiplyBlending: - gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); - break; - default: - console.error('THREE.WebGLState: Invalid blending: ', blending); - break; - } + + const panLeft = function () { + + const v = new Vector3(); + + return function panLeft( distance, objectMatrix ) { + + v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + v.multiplyScalar( - distance ); + + panOffset.add( v ); + + }; + + }(); + + const panUp = function () { + + const v = new Vector3(); + + return function panUp( distance, objectMatrix ) { + + if ( scope.screenSpacePanning === true ) { + + v.setFromMatrixColumn( objectMatrix, 1 ); + } else { - switch (blending) { - case NormalBlending: - gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - break; - case AdditiveBlending: - gl.blendFunc(gl.SRC_ALPHA, gl.ONE); - break; - case SubtractiveBlending: - gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); - break; - case MultiplyBlending: - gl.blendFunc(gl.ZERO, gl.SRC_COLOR); - break; - default: - console.error('THREE.WebGLState: Invalid blending: ', blending); - break; - } + + v.setFromMatrixColumn( objectMatrix, 0 ); + v.crossVectors( scope.object.up, v ); + } - currentBlendSrc = null; - currentBlendDst = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; - } - return; - } - // custom blending + v.multiplyScalar( distance ); - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; - if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { - gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; - } - if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { - gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; - } - currentBlending = blending; - currentPremultipledAlpha = null; - } - function setMaterial(material, frontFaceCW) { - material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); - let flipSided = material.side === BackSide; - if (frontFaceCW) flipSided = !flipSided; - setFlipSided(flipSided); - material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha); - depthBuffer.setFunc(material.depthFunc); - depthBuffer.setTest(material.depthTest); - depthBuffer.setMask(material.depthWrite); - colorBuffer.setMask(material.colorWrite); - const stencilWrite = material.stencilWrite; - stencilBuffer.setTest(stencilWrite); - if (stencilWrite) { - stencilBuffer.setMask(material.stencilWriteMask); - stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); - stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); - } - setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); - material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); - } + panOffset.add( v ); - // + }; + + }(); + + // deltaX and deltaY are in pixels; right and down are positive + const pan = function () { + + const offset = new Vector3(); + + return function pan( deltaX, deltaY ) { + + const element = scope.domElement; + + if ( scope.object.isPerspectiveCamera ) { + + // perspective + const position = scope.object.position; + offset.copy( position ).sub( scope.target ); + let targetDistance = offset.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); + panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); + + } else if ( scope.object.isOrthographicCamera ) { + + // orthographic + panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); + panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); - function setFlipSided(flipSided) { - if (currentFlipSided !== flipSided) { - if (flipSided) { - gl.frontFace(gl.CW); - } else { - gl.frontFace(gl.CCW); - } - currentFlipSided = flipSided; - } - } - function setCullFace(cullFace) { - if (cullFace !== CullFaceNone) { - enable(gl.CULL_FACE); - if (cullFace !== currentCullFace) { - if (cullFace === CullFaceBack) { - gl.cullFace(gl.BACK); - } else if (cullFace === CullFaceFront) { - gl.cullFace(gl.FRONT); } else { - gl.cullFace(gl.FRONT_AND_BACK); + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + scope.enablePan = false; + } + + }; + + }(); + + function dollyOut( dollyScale ) { + + if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) { + + scale /= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; + } - } else { - disable(gl.CULL_FACE); - } - currentCullFace = cullFace; - } - function setLineWidth(width) { - if (width !== currentLineWidth) { - if (lineWidthAvailable) gl.lineWidth(width); - currentLineWidth = width; - } - } - function setPolygonOffset(polygonOffset, factor, units) { - if (polygonOffset) { - enable(gl.POLYGON_OFFSET_FILL); - if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { - gl.polygonOffset(factor, units); - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; - } - } else { - disable(gl.POLYGON_OFFSET_FILL); - } - } - function setScissorTest(scissorTest) { - if (scissorTest) { - enable(gl.SCISSOR_TEST); - } else { - disable(gl.SCISSOR_TEST); + } - } - // texture + function dollyIn( dollyScale ) { + + if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) { + + scale *= dollyScale; - function activeTexture(webglSlot) { - if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1; - if (currentTextureSlot !== webglSlot) { - gl.activeTexture(webglSlot); - currentTextureSlot = webglSlot; - } - } - function bindTexture(webglType, webglTexture, webglSlot) { - if (webglSlot === undefined) { - if (currentTextureSlot === null) { - webglSlot = gl.TEXTURE0 + maxTextures - 1; } else { - webglSlot = currentTextureSlot; + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; + } + } - let boundTexture = currentBoundTextures[webglSlot]; - if (boundTexture === undefined) { - boundTexture = { - type: undefined, - texture: undefined - }; - currentBoundTextures[webglSlot] = boundTexture; - } - if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { - if (currentTextureSlot !== webglSlot) { - gl.activeTexture(webglSlot); - currentTextureSlot = webglSlot; + + function updateMouseParameters( event ) { + + if ( ! scope.zoomToCursor ) { + + return; + } - gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); - boundTexture.type = webglType; - boundTexture.texture = webglTexture; - } - } - function unbindTexture() { - const boundTexture = currentBoundTextures[currentTextureSlot]; - if (boundTexture !== undefined && boundTexture.type !== undefined) { - gl.bindTexture(boundTexture.type, null); - boundTexture.type = undefined; - boundTexture.texture = undefined; - } - } - function compressedTexImage2D() { - try { - gl.compressedTexImage2D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function compressedTexImage3D() { - try { - gl.compressedTexImage3D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texSubImage2D() { - try { - gl.texSubImage2D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texSubImage3D() { - try { - gl.texSubImage3D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function compressedTexSubImage2D() { - try { - gl.compressedTexSubImage2D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function compressedTexSubImage3D() { - try { - gl.compressedTexSubImage3D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texStorage2D() { - try { - gl.texStorage2D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texStorage3D() { - try { - gl.texStorage3D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texImage2D() { - try { - gl.texImage2D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - function texImage3D() { - try { - gl.texImage3D.apply(gl, arguments); - } catch (error) { - console.error('THREE.WebGLState:', error); - } - } - // + performCursorZoom = true; - function scissor(scissor) { - if (currentScissor.equals(scissor) === false) { - gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w); - currentScissor.copy(scissor); - } - } - function viewport(viewport) { - if (currentViewport.equals(viewport) === false) { - gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w); - currentViewport.copy(viewport); - } - } - function updateUBOMapping(uniformsGroup, program) { - let mapping = uboProgamMap.get(program); - if (mapping === undefined) { - mapping = new WeakMap(); - uboProgamMap.set(program, mapping); - } - let blockIndex = mapping.get(uniformsGroup); - if (blockIndex === undefined) { - blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); - mapping.set(uniformsGroup, blockIndex); - } - } - function uniformBlockBinding(uniformsGroup, program) { - const mapping = uboProgamMap.get(program); - const blockIndex = mapping.get(uniformsGroup); - if (uboBindings.get(uniformsGroup) !== blockIndex) { - // bind shader specific block index to global block point + const rect = scope.domElement.getBoundingClientRect(); + const x = event.clientX - rect.left; + const y = event.clientY - rect.top; + const w = rect.width; + const h = rect.height; + + mouse.x = ( x / w ) * 2 - 1; + mouse.y = - ( y / h ) * 2 + 1; + + dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( object ).sub( object.position ).normalize(); - gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); - uboBindings.set(uniformsGroup, blockIndex); } - } - // + function clampDistance( dist ) { - function reset() { - // reset state + return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) ); - gl.disable(gl.BLEND); - gl.disable(gl.CULL_FACE); - gl.disable(gl.DEPTH_TEST); - gl.disable(gl.POLYGON_OFFSET_FILL); - gl.disable(gl.SCISSOR_TEST); - gl.disable(gl.STENCIL_TEST); - gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ZERO); - gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); - gl.colorMask(true, true, true, true); - gl.clearColor(0, 0, 0, 0); - gl.depthMask(true); - gl.depthFunc(gl.LESS); - gl.clearDepth(1); - gl.stencilMask(0xffffffff); - gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - gl.clearStencil(0); - gl.cullFace(gl.BACK); - gl.frontFace(gl.CCW); - gl.polygonOffset(0, 0); - gl.activeTexture(gl.TEXTURE0); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - if (isWebGL2 === true) { - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); - gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); - } - gl.useProgram(null); - gl.lineWidth(1); - gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); - gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + } - // reset internals + // + // event callbacks - update the object state + // - enabledCapabilities = {}; - currentTextureSlot = null; - currentBoundTextures = {}; - currentBoundFramebuffers = {}; - currentDrawbuffers = new WeakMap(); - defaultDrawbuffers = []; - currentProgram = null; - currentBlendingEnabled = false; - currentBlending = null; - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - currentPremultipledAlpha = false; - currentFlipSided = null; - currentCullFace = null; - currentLineWidth = null; - currentPolygonOffsetFactor = null; - currentPolygonOffsetUnits = null; - currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); - currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); - colorBuffer.reset(); - depthBuffer.reset(); - stencilBuffer.reset(); - } - return { - buffers: { - color: colorBuffer, - depth: depthBuffer, - stencil: stencilBuffer - }, - enable: enable, - disable: disable, - bindFramebuffer: bindFramebuffer, - drawBuffers: drawBuffers, - useProgram: useProgram, - setBlending: setBlending, - setMaterial: setMaterial, - setFlipSided: setFlipSided, - setCullFace: setCullFace, - setLineWidth: setLineWidth, - setPolygonOffset: setPolygonOffset, - setScissorTest: setScissorTest, - activeTexture: activeTexture, - bindTexture: bindTexture, - unbindTexture: unbindTexture, - compressedTexImage2D: compressedTexImage2D, - compressedTexImage3D: compressedTexImage3D, - texImage2D: texImage2D, - texImage3D: texImage3D, - updateUBOMapping: updateUBOMapping, - uniformBlockBinding: uniformBlockBinding, - texStorage2D: texStorage2D, - texStorage3D: texStorage3D, - texSubImage2D: texSubImage2D, - texSubImage3D: texSubImage3D, - compressedTexSubImage2D: compressedTexSubImage2D, - compressedTexSubImage3D: compressedTexSubImage3D, - scissor: scissor, - viewport: viewport, - reset: reset - }; -} + function handleMouseDownRotate( event ) { -function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { - const isWebGL2 = capabilities.isWebGL2; - const maxTextures = capabilities.maxTextures; - const maxCubemapSize = capabilities.maxCubemapSize; - const maxTextureSize = capabilities.maxTextureSize; - const maxSamples = capabilities.maxSamples; - const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null; - const supportsInvalidateFramebuffer = /OculusBrowser/g.test(typeof navigator === 'undefined' ? '' : navigator.userAgent); - const _videoTextures = new WeakMap(); - let _canvas; - const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + rotateStart.set( event.clientX, event.clientY ); - // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, - // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! - // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + } - let useOffscreenCanvas = false; - try { - useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' - // eslint-disable-next-line compat/compat - && new OffscreenCanvas(1, 1).getContext('2d') !== null; - } catch (err) { + function handleMouseDownDolly( event ) { - // Ignore any errors - } - function createCanvas(width, height) { - // Use OffscreenCanvas when available. Specially needed in web workers + updateMouseParameters( event ); + dollyStart.set( event.clientX, event.clientY ); - return useOffscreenCanvas ? - // eslint-disable-next-line compat/compat - new OffscreenCanvas(width, height) : createElementNS('canvas'); - } - function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) { - let scale = 1; + } - // handle case if texture exceeds max size + function handleMouseDownPan( event ) { + + panStart.set( event.clientX, event.clientY ); - if (image.width > maxSize || image.height > maxSize) { - scale = maxSize / Math.max(image.width, image.height); } - // only perform resize if necessary + function handleMouseMoveRotate( event ) { - if (scale < 1 || needsPowerOfTwo === true) { - // only perform resize for certain image types + rotateEnd.set( event.clientX, event.clientY ); - if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) { - const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - const width = floor(scale * image.width); - const height = floor(scale * image.height); - if (_canvas === undefined) _canvas = createCanvas(width, height); + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - // cube textures can't reuse the same canvas + const element = scope.domElement; - const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas; - canvas.width = width; - canvas.height = height; - const context = canvas.getContext('2d'); - context.drawImage(image, 0, 0, width, height); - console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').'); - return canvas; - } else { - if ('data' in image) { - console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').'); - } - return image; - } - } - return image; - } - function isPowerOfTwo$1(image) { - return isPowerOfTwo(image.width) && isPowerOfTwo(image.height); - } - function textureNeedsPowerOfTwo(texture) { - if (isWebGL2) return false; - return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - } - function textureNeedsGenerateMipmaps(texture, supportsMips) { - return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - } - function generateMipmap(target) { - _gl.generateMipmap(target); - } - function getInternalFormat(internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false) { - if (isWebGL2 === false) return glFormat; - if (internalFormatName !== null) { - if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName]; - console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\''); - } - let internalFormat = glFormat; - if (glFormat === _gl.RED) { - if (glType === _gl.FLOAT) internalFormat = _gl.R32F; - if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F; - if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8; - } - if (glFormat === _gl.RG) { - if (glType === _gl.FLOAT) internalFormat = _gl.RG32F; - if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F; - if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8; - } - if (glFormat === _gl.RGBA) { - if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F; - if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F; - if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && forceLinearEncoding === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; - if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4; - if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1; - } - if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { - extensions.get('EXT_color_buffer_float'); - } - return internalFormat; - } - function getMipLevels(texture, image, supportsMips) { - if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { - return Math.log2(Math.max(image.width, image.height)) + 1; - } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { - // user-defined mipmaps + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - return texture.mipmaps.length; - } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { - return image.mipmaps.length; - } else { - // texture without mipmaps (only base level) + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - return 1; - } - } + rotateStart.copy( rotateEnd ); - // Fallback filters for non-power-of-2 textures + scope.update(); - function filterFallback(f) { - if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) { - return _gl.NEAREST; } - return _gl.LINEAR; - } - // + function handleMouseMoveDolly( event ) { - function onTextureDispose(event) { - const texture = event.target; - texture.removeEventListener('dispose', onTextureDispose); - deallocateTexture(texture); - if (texture.isVideoTexture) { - _videoTextures.delete(texture); - } - } - function onRenderTargetDispose(event) { - const renderTarget = event.target; - renderTarget.removeEventListener('dispose', onRenderTargetDispose); - deallocateRenderTarget(renderTarget); - } + dollyEnd.set( event.clientX, event.clientY ); - // + dollyDelta.subVectors( dollyEnd, dollyStart ); - function deallocateTexture(texture) { - const textureProperties = properties.get(texture); - if (textureProperties.__webglInit === undefined) return; + if ( dollyDelta.y > 0 ) { - // check if it's necessary to remove the WebGLTexture object + dollyOut( getZoomScale() ); - const source = texture.source; - const webglTextures = _sources.get(source); - if (webglTextures) { - const webglTexture = webglTextures[textureProperties.__cacheKey]; - webglTexture.usedTimes--; + } else if ( dollyDelta.y < 0 ) { - // the WebGLTexture object is not used anymore, remove it + dollyIn( getZoomScale() ); - if (webglTexture.usedTimes === 0) { - deleteTexture(texture); } - // remove the weak map entry if no WebGLTexture uses the source anymore + dollyStart.copy( dollyEnd ); + + scope.update(); - if (Object.keys(webglTextures).length === 0) { - _sources.delete(source); - } - } - properties.remove(texture); - } - function deleteTexture(texture) { - const textureProperties = properties.get(texture); - _gl.deleteTexture(textureProperties.__webglTexture); - const source = texture.source; - const webglTextures = _sources.get(source); - delete webglTextures[textureProperties.__cacheKey]; - info.memory.textures--; - } - function deallocateRenderTarget(renderTarget) { - const texture = renderTarget.texture; - const renderTargetProperties = properties.get(renderTarget); - const textureProperties = properties.get(texture); - if (textureProperties.__webglTexture !== undefined) { - _gl.deleteTexture(textureProperties.__webglTexture); - info.memory.textures--; - } - if (renderTarget.depthTexture) { - renderTarget.depthTexture.dispose(); - } - if (renderTarget.isWebGLCubeRenderTarget) { - for (let i = 0; i < 6; i++) { - _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); - if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); - } - } else { - _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); - if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); - if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); - if (renderTargetProperties.__webglColorRenderbuffer) { - for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { - if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); - } - } - if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); - } - if (renderTarget.isWebGLMultipleRenderTargets) { - for (let i = 0, il = texture.length; i < il; i++) { - const attachmentProperties = properties.get(texture[i]); - if (attachmentProperties.__webglTexture) { - _gl.deleteTexture(attachmentProperties.__webglTexture); - info.memory.textures--; - } - properties.remove(texture[i]); - } } - properties.remove(texture); - properties.remove(renderTarget); - } - // + function handleMouseMovePan( event ) { - let textureUnits = 0; - function resetTextureUnits() { - textureUnits = 0; - } - function allocateTextureUnit() { - const textureUnit = textureUnits; - if (textureUnit >= maxTextures) { - console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures); - } - textureUnits += 1; - return textureUnit; - } - function getTextureCacheKey(texture) { - const array = []; - array.push(texture.wrapS); - array.push(texture.wrapT); - array.push(texture.wrapR || 0); - array.push(texture.magFilter); - array.push(texture.minFilter); - array.push(texture.anisotropy); - array.push(texture.internalFormat); - array.push(texture.format); - array.push(texture.type); - array.push(texture.generateMipmaps); - array.push(texture.premultiplyAlpha); - array.push(texture.flipY); - array.push(texture.unpackAlignment); - array.push(texture.encoding); - return array.join(); - } + panEnd.set( event.clientX, event.clientY ); - // + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - function setTexture2D(texture, slot) { - const textureProperties = properties.get(texture); - if (texture.isVideoTexture) updateVideoTexture(texture); - if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { - const image = texture.image; - if (image === null) { - console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.'); - } else if (image.complete === false) { - console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete'); - } else { - uploadTexture(textureProperties, texture, slot); - return; - } - } - state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - } - function setTexture2DArray(texture, slot) { - const textureProperties = properties.get(texture); - if (texture.version > 0 && textureProperties.__version !== texture.version) { - uploadTexture(textureProperties, texture, slot); - return; - } - state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - } - function setTexture3D(texture, slot) { - const textureProperties = properties.get(texture); - if (texture.version > 0 && textureProperties.__version !== texture.version) { - uploadTexture(textureProperties, texture, slot); - return; - } - state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - } - function setTextureCube(texture, slot) { - const textureProperties = properties.get(texture); - if (texture.version > 0 && textureProperties.__version !== texture.version) { - uploadCubeTexture(textureProperties, texture, slot); - return; - } - state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - } - const wrappingToGL = { - [RepeatWrapping]: _gl.REPEAT, - [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, - [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT - }; - const filterToGL = { - [NearestFilter]: _gl.NEAREST, - [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, - [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, - [LinearFilter]: _gl.LINEAR, - [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, - [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR - }; - function setTextureParameters(textureType, texture, supportsMips) { - if (supportsMips) { - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); - if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); - } - _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); - _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); - } else { - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE); - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE); - if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { - _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE); - } - if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) { - console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.'); - } - _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter)); - _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter)); - if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { - console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.'); - } - } - if (extensions.has('EXT_texture_filter_anisotropic') === true) { - const extension = extensions.get('EXT_texture_filter_anisotropic'); - if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2 - if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only + pan( panDelta.x, panDelta.y ); - if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { - _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); - properties.get(texture).__currentAnisotropy = texture.anisotropy; - } - } - } - function initTexture(textureProperties, texture) { - let forceUpload = false; - if (textureProperties.__webglInit === undefined) { - textureProperties.__webglInit = true; - texture.addEventListener('dispose', onTextureDispose); - } + panStart.copy( panEnd ); - // create Source <-> WebGLTextures mapping if necessary + scope.update(); - const source = texture.source; - let webglTextures = _sources.get(source); - if (webglTextures === undefined) { - webglTextures = {}; - _sources.set(source, webglTextures); } - // check if there is already a WebGLTexture object for the given texture parameters - - const textureCacheKey = getTextureCacheKey(texture); - if (textureCacheKey !== textureProperties.__cacheKey) { - // if not, create a new instance of WebGLTexture + function handleMouseWheel( event ) { - if (webglTextures[textureCacheKey] === undefined) { - // create new entry + updateMouseParameters( event ); - webglTextures[textureCacheKey] = { - texture: _gl.createTexture(), - usedTimes: 0 - }; - info.memory.textures++; + if ( event.deltaY < 0 ) { - // when a new instance of WebGLTexture was created, a texture upload is required - // even if the image contents are identical + dollyIn( getZoomScale() ); - forceUpload = true; - } - webglTextures[textureCacheKey].usedTimes++; + } else if ( event.deltaY > 0 ) { - // every time the texture cache key changes, it's necessary to check if an instance of - // WebGLTexture can be deleted in order to avoid a memory leak. + dollyOut( getZoomScale() ); - const webglTexture = webglTextures[textureProperties.__cacheKey]; - if (webglTexture !== undefined) { - webglTextures[textureProperties.__cacheKey].usedTimes--; - if (webglTexture.usedTimes === 0) { - deleteTexture(texture); - } } - // store references to cache key and WebGLTexture object + scope.update(); - textureProperties.__cacheKey = textureCacheKey; - textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; } - return forceUpload; - } - function uploadTexture(textureProperties, texture, slot) { - let textureType = _gl.TEXTURE_2D; - if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY; - if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D; - const forceUpload = initTexture(textureProperties, texture); - const source = texture.source; - state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - const sourceProperties = properties.get(source); - if (source.version !== sourceProperties.__version || forceUpload === true) { - state.activeTexture(_gl.TEXTURE0 + slot); - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); - _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); - _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); - _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE); - const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false; - let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize); - image = verifyColorSpace(texture, image); - const supportsMips = isPowerOfTwo$1(image) || isWebGL2, - glFormat = utils.convert(texture.format, texture.encoding); - let glType = utils.convert(texture.type), - glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture); - setTextureParameters(textureType, texture, supportsMips); - let mipmap; - const mipmaps = texture.mipmaps; - const useTexStorage = isWebGL2 && texture.isVideoTexture !== true; - const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; - const levels = getMipLevels(texture, image, supportsMips); - if (texture.isDepthTexture) { - // populate depth texture with dummy data - glInternalFormat = _gl.DEPTH_COMPONENT; - if (isWebGL2) { - if (texture.type === FloatType) { - glInternalFormat = _gl.DEPTH_COMPONENT32F; - } else if (texture.type === UnsignedIntType) { - glInternalFormat = _gl.DEPTH_COMPONENT24; - } else if (texture.type === UnsignedInt248Type) { - glInternalFormat = _gl.DEPTH24_STENCIL8; - } else { - glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D - } - } else { - if (texture.type === FloatType) { - console.error('WebGLRenderer: Floating point depth texture requires WebGL2.'); - } - } + function handleKeyDown( event ) { - // validation checks for WebGL 1 + let needsUpdate = false; - if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) { - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) { - console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.'); - texture.type = UnsignedIntType; - glType = utils.convert(texture.type); - } - } - if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) { - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - glInternalFormat = _gl.DEPTH_STENCIL; + switch ( event.code ) { - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if (texture.type !== UnsignedInt248Type) { - console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.'); - texture.type = UnsignedInt248Type; - glType = utils.convert(texture.type); - } - } + case scope.keys.UP: - // + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); - if (allocateMemory) { - if (useTexStorage) { - state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); } else { - state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); - } - } - } else if (texture.isDataTexture) { - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels - if (mipmaps.length > 0 && supportsMips) { - if (useTexStorage && allocateMemory) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); - } - for (let i = 0, il = mipmaps.length; i < il; i++) { - mipmap = mipmaps[i]; - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); - } else { - state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); - } + pan( 0, scope.keyPanSpeed ); + } - texture.generateMipmaps = false; - } else { - if (useTexStorage) { - if (allocateMemory) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); - } - state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + + needsUpdate = true; + break; + + case scope.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + } else { - state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); - } - } - } else if (texture.isCompressedTexture) { - if (texture.isCompressedArrayTexture) { - if (useTexStorage && allocateMemory) { - state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); - } - for (let i = 0, il = mipmaps.length; i < il; i++) { - mipmap = mipmaps[i]; - if (texture.format !== RGBAFormat) { - if (glFormat !== null) { - if (useTexStorage) { - state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0); - } else { - state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); - } - } else { - console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()'); - } - } else { - if (useTexStorage) { - state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); - } else { - state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); - } - } - } - } else { - if (useTexStorage && allocateMemory) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); - } - for (let i = 0, il = mipmaps.length; i < il; i++) { - mipmap = mipmaps[i]; - if (texture.format !== RGBAFormat) { - if (glFormat !== null) { - if (useTexStorage) { - state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); - } else { - state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); - } - } else { - console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()'); - } - } else { - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); - } else { - state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); - } - } - } - } - } else if (texture.isDataArrayTexture) { - if (useTexStorage) { - if (allocateMemory) { - state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); - } - state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); - } else { - state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); - } - } else if (texture.isData3DTexture) { - if (useTexStorage) { - if (allocateMemory) { - state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + + pan( 0, - scope.keyPanSpeed ); + } - state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); - } else { - state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); - } - } else if (texture.isFramebufferTexture) { - if (allocateMemory) { - if (useTexStorage) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + + needsUpdate = true; + break; + + case scope.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + } else { - let width = image.width, - height = image.height; - for (let i = 0; i < levels; i++) { - state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null); - width >>= 1; - height >>= 1; - } - } - } - } else { - // regular Texture (image, video, canvas) - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + pan( scope.keyPanSpeed, 0 ); - if (mipmaps.length > 0 && supportsMips) { - if (useTexStorage && allocateMemory) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); - } - for (let i = 0, il = mipmaps.length; i < il; i++) { - mipmap = mipmaps[i]; - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); - } else { - state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); - } } - texture.generateMipmaps = false; - } else { - if (useTexStorage) { - if (allocateMemory) { - state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); - } - state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + + needsUpdate = true; + break; + + case scope.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + } else { - state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + + pan( - scope.keyPanSpeed, 0 ); + } - } + + needsUpdate = true; + break; + } - if (textureNeedsGenerateMipmaps(texture, supportsMips)) { - generateMipmap(textureType); + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + scope.update(); + } - sourceProperties.__version = source.version; - if (texture.onUpdate) texture.onUpdate(texture); + + } - textureProperties.__version = texture.version; - } - function uploadCubeTexture(textureProperties, texture, slot) { - if (texture.image.length !== 6) return; - const forceUpload = initTexture(textureProperties, texture); - const source = texture.source; - state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); - const sourceProperties = properties.get(source); - if (source.version !== sourceProperties.__version || forceUpload === true) { - state.activeTexture(_gl.TEXTURE0 + slot); - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); - _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); - _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); - _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE); - const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; - const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; - const cubeImage = []; - for (let i = 0; i < 6; i++) { - if (!isCompressed && !isDataTexture) { - cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize); - } else { - cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; - } - cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); - } - const image = cubeImage[0], - supportsMips = isPowerOfTwo$1(image) || isWebGL2, - glFormat = utils.convert(texture.format, texture.encoding), - glType = utils.convert(texture.type), - glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); - const useTexStorage = isWebGL2 && texture.isVideoTexture !== true; - const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; - let levels = getMipLevels(texture, image, supportsMips); - setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips); - let mipmaps; - if (isCompressed) { - if (useTexStorage && allocateMemory) { - state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); - } - for (let i = 0; i < 6; i++) { - mipmaps = cubeImage[i].mipmaps; - for (let j = 0; j < mipmaps.length; j++) { - const mipmap = mipmaps[j]; - if (texture.format !== RGBAFormat) { - if (glFormat !== null) { - if (useTexStorage) { - state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); - } else { - state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); - } - } else { - console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()'); - } - } else { - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); - } else { - state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); - } - } - } - } + + function handleTouchStartRotate() { + + if ( pointers.length === 1 ) { + + rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); + } else { - mipmaps = texture.mipmaps; - if (useTexStorage && allocateMemory) { - // TODO: Uniformly handle mipmap definitions - // Normal textures and compressed cube textures define base level + mips with their mipmap array - // Uncompressed cube textures use their mipmap array only for mips (no base level) - if (mipmaps.length > 0) levels++; - state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height); - } - for (let i = 0; i < 6; i++) { - if (isDataTexture) { - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); - } else { - state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); - } - for (let j = 0; j < mipmaps.length; j++) { - const mipmap = mipmaps[j]; - const mipmapImage = mipmap.image[i].image; - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); - } else { - state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); - } - } - } else { - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); - } else { - state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); - } - for (let j = 0; j < mipmaps.length; j++) { - const mipmap = mipmaps[j]; - if (useTexStorage) { - state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); - } else { - state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); - } - } - } - } - } - if (textureNeedsGenerateMipmaps(texture, supportsMips)) { - // We assume images for cube map have the same size. - generateMipmap(_gl.TEXTURE_CUBE_MAP); + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); + + rotateStart.set( x, y ); + } - sourceProperties.__version = source.version; - if (texture.onUpdate) texture.onUpdate(texture); + } - textureProperties.__version = texture.version; - } - // Render targets + function handleTouchStartPan() { + + if ( pointers.length === 1 ) { + + panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) { - const glFormat = utils.convert(texture.format, texture.encoding); - const glType = utils.convert(texture.type); - const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); - const renderTargetProperties = properties.get(renderTarget); - if (!renderTargetProperties.__hasExternalTextures) { - if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { - state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null); } else { - state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null); + + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); + + panStart.set( x, y ); + } + } - state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget)); - } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { - // see #24753 - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0); + function handleTouchStartDolly() { + + const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; + const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + dollyStart.set( 0, distance ); + } - state.bindFramebuffer(_gl.FRAMEBUFFER, null); - } - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { - _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); - if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) { - let glInternalFormat = _gl.DEPTH_COMPONENT16; - if (isMultisample || useMultisampledRTT(renderTarget)) { - const depthTexture = renderTarget.depthTexture; - if (depthTexture && depthTexture.isDepthTexture) { - if (depthTexture.type === FloatType) { - glInternalFormat = _gl.DEPTH_COMPONENT32F; - } else if (depthTexture.type === UnsignedIntType) { - glInternalFormat = _gl.DEPTH_COMPONENT24; - } - } - const samples = getRenderTargetSamples(renderTarget); - if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); - } else { - _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); - } + function handleTouchStartDollyPan() { + + if ( scope.enableZoom ) handleTouchStartDolly(); + + if ( scope.enablePan ) handleTouchStartPan(); + + } + + function handleTouchStartDollyRotate() { + + if ( scope.enableZoom ) handleTouchStartDolly(); + + if ( scope.enableRotate ) handleTouchStartRotate(); + + } + + function handleTouchMoveRotate( event ) { + + if ( pointers.length == 1 ) { + + rotateEnd.set( event.pageX, event.pageY ); + } else { - _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + + const position = getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + rotateEnd.set( x, y ); + } - _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer); - } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) { - const samples = getRenderTargetSamples(renderTarget); - if (isMultisample && useMultisampledRTT(renderTarget) === false) { - _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height); - } else if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height); + + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + + const element = scope.domElement; + + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + + rotateStart.copy( rotateEnd ); + + } + + function handleTouchMovePan( event ) { + + if ( pointers.length === 1 ) { + + panEnd.set( event.pageX, event.pageY ); + } else { - _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height); - } - _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer); - } else { - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; - for (let i = 0; i < textures.length; i++) { - const texture = textures[i]; - const glFormat = utils.convert(texture.format, texture.encoding); - const glType = utils.convert(texture.type); - const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); - const samples = getRenderTargetSamples(renderTarget); - if (isMultisample && useMultisampledRTT(renderTarget) === false) { - _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); - } else if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); - } else { - _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); - } + + const position = getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + panEnd.set( x, y ); + } + + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + + pan( panDelta.x, panDelta.y ); + + panStart.copy( panEnd ); + } - _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); - } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture(framebuffer, renderTarget) { - const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; - if (isCube) throw new Error('Depth Texture with cube render targets is not supported'); - state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + function handleTouchMoveDolly( event ) { + + const position = getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + dollyEnd.set( 0, distance ); + + dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); + + dollyOut( dollyDelta.y ); + + dollyStart.copy( dollyEnd ); + } - // upload an empty depth texture with framebuffer size - if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; + function handleTouchMoveDollyPan( event ) { + + if ( scope.enableZoom ) handleTouchMoveDolly( event ); + + if ( scope.enablePan ) handleTouchMovePan( event ); + } - setTexture2D(renderTarget.depthTexture, 0); - const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture; - const samples = getRenderTargetSamples(renderTarget); - if (renderTarget.depthTexture.format === DepthFormat) { - if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); - } else { - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + + function handleTouchMoveDollyRotate( event ) { + + if ( scope.enableZoom ) handleTouchMoveDolly( event ); + + if ( scope.enableRotate ) handleTouchMoveRotate( event ); + + } + + // + // event handlers - FSM: listen for events and reset state + // + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + if ( pointers.length === 0 ) { + + scope.domElement.setPointerCapture( event.pointerId ); + + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); + } - } else if (renderTarget.depthTexture.format === DepthStencilFormat) { - if (useMultisampledRTT(renderTarget)) { - multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + + // + + addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + onTouchStart( event ); + } else { - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + + onMouseDown( event ); + } - } else { - throw new Error('Unknown depthTexture format'); + } - } - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer(renderTarget) { - const renderTargetProperties = properties.get(renderTarget); - const isCube = renderTarget.isWebGLCubeRenderTarget === true; - if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { - if (isCube) throw new Error('target.depthTexture not supported in Cube render targets'); - setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); - } else { - if (isCube) { - renderTargetProperties.__webglDepthbuffer = []; - for (let i = 0; i < 6; i++) { - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); - renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); - setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); - } + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchMove( event ); + } else { - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + + onMouseMove( event ); + } - } - state.bindFramebuffer(_gl.FRAMEBUFFER, null); - } - // rebind framebuffer with external textures - function rebindTextures(renderTarget, colorTexture, depthTexture) { - const renderTargetProperties = properties.get(renderTarget); - if (colorTexture !== undefined) { - setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D); - } - if (depthTexture !== undefined) { - setupDepthRenderbuffer(renderTarget); } - } - // Set up GL resources for the render target - function setupRenderTarget(renderTarget) { - const texture = renderTarget.texture; - const renderTargetProperties = properties.get(renderTarget); - const textureProperties = properties.get(texture); - renderTarget.addEventListener('dispose', onRenderTargetDispose); - if (renderTarget.isWebGLMultipleRenderTargets !== true) { - if (textureProperties.__webglTexture === undefined) { - textureProperties.__webglTexture = _gl.createTexture(); + function onPointerUp( event ) { + + removePointer( event ); + + if ( pointers.length === 0 ) { + + scope.domElement.releasePointerCapture( event.pointerId ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + } - textureProperties.__version = texture.version; - info.memory.textures++; + + scope.dispatchEvent( _endEvent ); + + state = STATE.NONE; + } - const isCube = renderTarget.isWebGLCubeRenderTarget === true; - const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; - const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; - // Setup framebuffer + function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = scope.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = scope.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = scope.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; - if (isCube) { - renderTargetProperties.__webglFramebuffer = []; - for (let i = 0; i < 6; i++) { - renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); } - } else { - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - if (isMultipleRenderTargets) { - if (capabilities.drawBuffers) { - const textures = renderTarget.texture; - for (let i = 0, il = textures.length; i < il; i++) { - const attachmentProperties = properties.get(textures[i]); - if (attachmentProperties.__webglTexture === undefined) { - attachmentProperties.__webglTexture = _gl.createTexture(); - info.memory.textures++; - } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( scope.enableZoom === false ) return; + + handleMouseDownDolly( event ); + + state = STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( scope.enablePan === false ) return; + + handleMouseDownPan( event ); + + state = STATE.PAN; + + } else { + + if ( scope.enableRotate === false ) return; + + handleMouseDownRotate( event ); + + state = STATE.ROTATE; + } - } else { - console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.'); - } - } - if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { - const textures = isMultipleRenderTargets ? texture : [texture]; - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = []; - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); - for (let i = 0; i < textures.length; i++) { - const texture = textures[i]; - renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); - _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); - const glFormat = utils.convert(texture.format, texture.encoding); - const glType = utils.convert(texture.type); - const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true); - const samples = getRenderTargetSamples(renderTarget); - _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); - _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); - } - _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); - if (renderTarget.depthBuffer) { - renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); - } - state.bindFramebuffer(_gl.FRAMEBUFFER, null); + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( scope.enableRotate === false ) return; + + handleMouseDownRotate( event ); + + state = STATE.ROTATE; + + } else { + + if ( scope.enablePan === false ) return; + + handleMouseDownPan( event ); + + state = STATE.PAN; + + } + + break; + + default: + + state = STATE.NONE; + } - } - // Setup color buffer + if ( state !== STATE.NONE ) { + + scope.dispatchEvent( _startEvent ); - if (isCube) { - state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); - setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips); - for (let i = 0; i < 6; i++) { - setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i); - } - if (textureNeedsGenerateMipmaps(texture, supportsMips)) { - generateMipmap(_gl.TEXTURE_CUBE_MAP); - } - state.unbindTexture(); - } else if (isMultipleRenderTargets) { - const textures = renderTarget.texture; - for (let i = 0, il = textures.length; i < il; i++) { - const attachment = textures[i]; - const attachmentProperties = properties.get(attachment); - state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); - setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips); - setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D); - if (textureNeedsGenerateMipmaps(attachment, supportsMips)) { - generateMipmap(_gl.TEXTURE_2D); - } - } - state.unbindTexture(); - } else { - let glTextureType = _gl.TEXTURE_2D; - if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { - if (isWebGL2) { - glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; - } else { - console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.'); - } - } - state.bindTexture(glTextureType, textureProperties.__webglTexture); - setTextureParameters(glTextureType, texture, supportsMips); - setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType); - if (textureNeedsGenerateMipmaps(texture, supportsMips)) { - generateMipmap(glTextureType); } - state.unbindTexture(); + } - // Setup depth and stencil buffers + function onMouseMove( event ) { - if (renderTarget.depthBuffer) { - setupDepthRenderbuffer(renderTarget); - } - } - function updateRenderTargetMipmap(renderTarget) { - const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; - for (let i = 0, il = textures.length; i < il; i++) { - const texture = textures[i]; - if (textureNeedsGenerateMipmaps(texture, supportsMips)) { - const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - const webglTexture = properties.get(texture).__webglTexture; - state.bindTexture(target, webglTexture); - generateMipmap(target); - state.unbindTexture(); - } - } - } - function updateMultisampleRenderTarget(renderTarget) { - if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { - const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture]; - const width = renderTarget.width; - const height = renderTarget.height; - let mask = _gl.COLOR_BUFFER_BIT; - const invalidationArray = []; - const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; - const renderTargetProperties = properties.get(renderTarget); - const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; + switch ( state ) { - // If MRT we need to remove FBO attachments - if (isMultipleRenderTargets) { - for (let i = 0; i < textures.length; i++) { - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); - _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); - _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); - } - } - state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); - state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); - for (let i = 0; i < textures.length; i++) { - invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i); - if (renderTarget.depthBuffer) { - invalidationArray.push(depthStyle); - } - const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false; - if (ignoreDepthValues === false) { - if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT; - if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT; - } - if (isMultipleRenderTargets) { - _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); - } - if (ignoreDepthValues === true) { - _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]); - _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); - } - if (isMultipleRenderTargets) { - const webglTexture = properties.get(textures[i]).__webglTexture; - _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); - } - _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST); - if (supportsInvalidateFramebuffer) { - _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray); - } - } - state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); - state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + case STATE.ROTATE: - // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments - if (isMultipleRenderTargets) { - for (let i = 0; i < textures.length; i++) { - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); - _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); - const webglTexture = properties.get(textures[i]).__webglTexture; - state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); - _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); - } - } - state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); - } - } - function getRenderTargetSamples(renderTarget) { - return Math.min(maxSamples, renderTarget.samples); - } - function useMultisampledRTT(renderTarget) { - const renderTargetProperties = properties.get(renderTarget); - return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false; - } - function updateVideoTexture(texture) { - const frame = info.render.frame; + if ( scope.enableRotate === false ) return; - // Check the last frame we updated the VideoTexture + handleMouseMoveRotate( event ); - if (_videoTextures.get(texture) !== frame) { - _videoTextures.set(texture, frame); - texture.update(); - } - } - function verifyColorSpace(texture, image) { - const encoding = texture.encoding; - const format = texture.format; - const type = texture.type; - if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image; - if (encoding !== LinearEncoding) { - // sRGB + break; - if (encoding === sRGBEncoding) { - if (isWebGL2 === false) { - // in WebGL 1, try to use EXT_sRGB extension and unsized formats + case STATE.DOLLY: - if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) { - texture.format = _SRGBAFormat; + if ( scope.enableZoom === false ) return; - // it's not possible to generate mips in WebGL 1 with this extension + handleMouseMoveDolly( event ); - texture.minFilter = LinearFilter; - texture.generateMipmaps = false; - } else { - // slow fallback (CPU decode) + break; - image = ImageUtils.sRGBToLinear(image); - } - } else { - // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + case STATE.PAN: - if (format !== RGBAFormat || type !== UnsignedByteType) { - console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.'); - } - } - } else { - console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding); - } - } - return image; - } + if ( scope.enablePan === false ) return; - // + handleMouseMovePan( event ); - this.allocateTextureUnit = allocateTextureUnit; - this.resetTextureUnits = resetTextureUnits; - this.setTexture2D = setTexture2D; - this.setTexture2DArray = setTexture2DArray; - this.setTexture3D = setTexture3D; - this.setTextureCube = setTextureCube; - this.rebindTextures = rebindTextures; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; - this.setupDepthRenderbuffer = setupDepthRenderbuffer; - this.setupFrameBufferTexture = setupFrameBufferTexture; - this.useMultisampledRTT = useMultisampledRTT; -} + break; -function WebGLUtils(gl, extensions, capabilities) { - const isWebGL2 = capabilities.isWebGL2; - function convert(p, encoding = null) { - let extension; - if (p === UnsignedByteType) return gl.UNSIGNED_BYTE; - if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4; - if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1; - if (p === ByteType) return gl.BYTE; - if (p === ShortType) return gl.SHORT; - if (p === UnsignedShortType) return gl.UNSIGNED_SHORT; - if (p === IntType) return gl.INT; - if (p === UnsignedIntType) return gl.UNSIGNED_INT; - if (p === FloatType) return gl.FLOAT; - if (p === HalfFloatType) { - if (isWebGL2) return gl.HALF_FLOAT; - extension = extensions.get('OES_texture_half_float'); - if (extension !== null) { - return extension.HALF_FLOAT_OES; - } else { - return null; } + } - if (p === AlphaFormat) return gl.ALPHA; - if (p === RGBAFormat) return gl.RGBA; - if (p === LuminanceFormat) return gl.LUMINANCE; - if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA; - if (p === DepthFormat) return gl.DEPTH_COMPONENT; - if (p === DepthStencilFormat) return gl.DEPTH_STENCIL; - if (p === RedFormat) return gl.RED; - // @deprecated since r137 + function onMouseWheel( event ) { - if (p === RGBFormat) { - console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228'); - return gl.RGBA; - } + if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - // WebGL 1 sRGB fallback + event.preventDefault(); + + scope.dispatchEvent( _startEvent ); + + handleMouseWheel( event ); + + scope.dispatchEvent( _endEvent ); - if (p === _SRGBAFormat) { - extension = extensions.get('EXT_sRGB'); - if (extension !== null) { - return extension.SRGB_ALPHA_EXT; - } else { - return null; - } } - // WebGL2 formats. + function onKeyDown( event ) { - if (p === RedIntegerFormat) return gl.RED_INTEGER; - if (p === RGFormat) return gl.RG; - if (p === RGIntegerFormat) return gl.RG_INTEGER; - if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; + if ( scope.enabled === false || scope.enablePan === false ) return; - // S3TC + handleKeyDown( event ); - if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { - if (encoding === sRGBEncoding) { - extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb'); - if (extension !== null) { - if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; - if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - } else { - return null; - } - } else { - extension = extensions.get('WEBGL_compressed_texture_s3tc'); - if (extension !== null) { - if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - } else { - return null; - } - } } - // PVRTC + function onTouchStart( event ) { - if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { - extension = extensions.get('WEBGL_compressed_texture_pvrtc'); - if (extension !== null) { - if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - } else { - return null; - } - } + trackPointer( event ); - // ETC1 + switch ( pointers.length ) { - if (p === RGB_ETC1_Format) { - extension = extensions.get('WEBGL_compressed_texture_etc1'); - if (extension !== null) { - return extension.COMPRESSED_RGB_ETC1_WEBGL; - } else { - return null; - } - } + case 1: - // ETC2 + switch ( scope.touches.ONE ) { - if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) { - extension = extensions.get('WEBGL_compressed_texture_etc'); - if (extension !== null) { - if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; - if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; - } else { - return null; - } - } + case TOUCH.ROTATE: - // ASTC + if ( scope.enableRotate === false ) return; - if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { - extension = extensions.get('WEBGL_compressed_texture_astc'); - if (extension !== null) { - if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; - if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; - if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; - if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; - if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; - if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; - if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; - if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; - if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; - if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; - if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; - if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; - if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; - if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; - } else { - return null; - } - } + handleTouchStartRotate(); - // BPTC + state = STATE.TOUCH_ROTATE; - if (p === RGBA_BPTC_Format) { - extension = extensions.get('EXT_texture_compression_bptc'); - if (extension !== null) { - if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; - } else { - return null; - } - } + break; - // + case TOUCH.PAN: - if (p === UnsignedInt248Type) { - if (isWebGL2) return gl.UNSIGNED_INT_24_8; - extension = extensions.get('WEBGL_depth_texture'); - if (extension !== null) { - return extension.UNSIGNED_INT_24_8_WEBGL; - } else { - return null; - } - } + if ( scope.enablePan === false ) return; - // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + handleTouchStartPan(); - return gl[p] !== undefined ? gl[p] : null; - } - return { - convert: convert - }; -} + state = STATE.TOUCH_PAN; -class ArrayCamera extends PerspectiveCamera { - constructor(array = []) { - super(); - this.isArrayCamera = true; - this.cameras = array; - } -} + break; -class Group extends Object3D { - constructor() { - super(); - this.isGroup = true; - this.type = 'Group'; - } -} + default: + + state = STATE.NONE; -const _moveEvent = { - type: 'move' -}; -class WebXRController { - constructor() { - this._targetRay = null; - this._grip = null; - this._hand = null; - } - getHandSpace() { - if (this._hand === null) { - this._hand = new Group(); - this._hand.matrixAutoUpdate = false; - this._hand.visible = false; - this._hand.joints = {}; - this._hand.inputState = { - pinching: false - }; - } - return this._hand; - } - getTargetRaySpace() { - if (this._targetRay === null) { - this._targetRay = new Group(); - this._targetRay.matrixAutoUpdate = false; - this._targetRay.visible = false; - this._targetRay.hasLinearVelocity = false; - this._targetRay.linearVelocity = new Vector3(); - this._targetRay.hasAngularVelocity = false; - this._targetRay.angularVelocity = new Vector3(); - } - return this._targetRay; - } - getGripSpace() { - if (this._grip === null) { - this._grip = new Group(); - this._grip.matrixAutoUpdate = false; - this._grip.visible = false; - this._grip.hasLinearVelocity = false; - this._grip.linearVelocity = new Vector3(); - this._grip.hasAngularVelocity = false; - this._grip.angularVelocity = new Vector3(); - } - return this._grip; - } - dispatchEvent(event) { - if (this._targetRay !== null) { - this._targetRay.dispatchEvent(event); - } - if (this._grip !== null) { - this._grip.dispatchEvent(event); - } - if (this._hand !== null) { - this._hand.dispatchEvent(event); - } - return this; - } - disconnect(inputSource) { - this.dispatchEvent({ - type: 'disconnected', - data: inputSource - }); - if (this._targetRay !== null) { - this._targetRay.visible = false; - } - if (this._grip !== null) { - this._grip.visible = false; - } - if (this._hand !== null) { - this._hand.visible = false; - } - return this; - } - update(inputSource, frame, referenceSpace) { - let inputPose = null; - let gripPose = null; - let handPose = null; - const targetRay = this._targetRay; - const grip = this._grip; - const hand = this._hand; - if (inputSource && frame.session.visibilityState !== 'visible-blurred') { - if (hand && inputSource.hand) { - handPose = true; - for (const inputjoint of inputSource.hand.values()) { - // Update the joints groups with the XRJoint poses - const jointPose = frame.getJointPose(inputjoint, referenceSpace); - if (hand.joints[inputjoint.jointName] === undefined) { - // The transform of this joint will be updated with the joint pose on each frame - const joint = new Group(); - joint.matrixAutoUpdate = false; - joint.visible = false; - hand.joints[inputjoint.jointName] = joint; - // ?? - hand.add(joint); - } - const joint = hand.joints[inputjoint.jointName]; - if (jointPose !== null) { - joint.matrix.fromArray(jointPose.transform.matrix); - joint.matrix.decompose(joint.position, joint.rotation, joint.scale); - joint.jointRadius = jointPose.radius; } - joint.visible = jointPose !== null; - } - // Custom events + break; + + case 2: + + switch ( scope.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( scope.enableZoom === false && scope.enablePan === false ) return; + + handleTouchStartDollyPan(); + + state = STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( scope.enableZoom === false && scope.enableRotate === false ) return; + + handleTouchStartDollyRotate(); + + state = STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + state = STATE.NONE; - // Check pinchz - const indexTip = hand.joints['index-finger-tip']; - const thumbTip = hand.joints['thumb-tip']; - const distance = indexTip.position.distanceTo(thumbTip.position); - const distanceToPinch = 0.02; - const threshold = 0.005; - if (hand.inputState.pinching && distance > distanceToPinch + threshold) { - hand.inputState.pinching = false; - this.dispatchEvent({ - type: 'pinchend', - handedness: inputSource.handedness, - target: this - }); - } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { - hand.inputState.pinching = true; - this.dispatchEvent({ - type: 'pinchstart', - handedness: inputSource.handedness, - target: this - }); - } - } else { - if (grip !== null && inputSource.gripSpace) { - gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); - if (gripPose !== null) { - grip.matrix.fromArray(gripPose.transform.matrix); - grip.matrix.decompose(grip.position, grip.rotation, grip.scale); - if (gripPose.linearVelocity) { - grip.hasLinearVelocity = true; - grip.linearVelocity.copy(gripPose.linearVelocity); - } else { - grip.hasLinearVelocity = false; - } - if (gripPose.angularVelocity) { - grip.hasAngularVelocity = true; - grip.angularVelocity.copy(gripPose.angularVelocity); - } else { - grip.hasAngularVelocity = false; - } } - } + + break; + + default: + + state = STATE.NONE; + } - if (targetRay !== null) { - inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); - // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it - if (inputPose === null && gripPose !== null) { - inputPose = gripPose; - } - if (inputPose !== null) { - targetRay.matrix.fromArray(inputPose.transform.matrix); - targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); - if (inputPose.linearVelocity) { - targetRay.hasLinearVelocity = true; - targetRay.linearVelocity.copy(inputPose.linearVelocity); - } else { - targetRay.hasLinearVelocity = false; - } - if (inputPose.angularVelocity) { - targetRay.hasAngularVelocity = true; - targetRay.angularVelocity.copy(inputPose.angularVelocity); - } else { - targetRay.hasAngularVelocity = false; - } - this.dispatchEvent(_moveEvent); - } + if ( state !== STATE.NONE ) { + + scope.dispatchEvent( _startEvent ); + } - } - if (targetRay !== null) { - targetRay.visible = inputPose !== null; - } - if (grip !== null) { - grip.visible = gripPose !== null; - } - if (hand !== null) { - hand.visible = handPose !== null; - } - return this; - } -} -class DepthTexture extends Texture { - constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) { - format = format !== undefined ? format : DepthFormat; - if (format !== DepthFormat && format !== DepthStencilFormat) { - throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat'); } - if (type === undefined && format === DepthFormat) type = UnsignedIntType; - if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type; - super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); - this.isDepthTexture = true; - this.image = { - width: width, - height: height - }; - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - this.flipY = false; - this.generateMipmaps = false; - } -} -class WebXRManager extends EventDispatcher { - constructor(renderer, gl) { - super(); - const scope = this; - let session = null; - let framebufferScaleFactor = 1.0; - let referenceSpace = null; - let referenceSpaceType = 'local-floor'; - let customReferenceSpace = null; - let pose = null; - let glBinding = null; - let glProjLayer = null; - let glBaseLayer = null; - let xrFrame = null; - const attributes = gl.getContextAttributes(); - let initialRenderTarget = null; - let newRenderTarget = null; - const controllers = []; - const controllerInputSources = []; + function onTouchMove( event ) { - // + trackPointer( event ); - const cameraL = new PerspectiveCamera(); - cameraL.layers.enable(1); - cameraL.viewport = new Vector4(); - const cameraR = new PerspectiveCamera(); - cameraR.layers.enable(2); - cameraR.viewport = new Vector4(); - const cameras = [cameraL, cameraR]; - const cameraVR = new ArrayCamera(); - cameraVR.layers.enable(1); - cameraVR.layers.enable(2); - let _currentDepthNear = null; - let _currentDepthFar = null; + switch ( state ) { - // + case STATE.TOUCH_ROTATE: - this.cameraAutoUpdate = true; - this.enabled = false; - this.isPresenting = false; - this.getController = function (index) { - let controller = controllers[index]; - if (controller === undefined) { - controller = new WebXRController(); - controllers[index] = controller; - } - return controller.getTargetRaySpace(); - }; - this.getControllerGrip = function (index) { - let controller = controllers[index]; - if (controller === undefined) { - controller = new WebXRController(); - controllers[index] = controller; - } - return controller.getGripSpace(); - }; - this.getHand = function (index) { - let controller = controllers[index]; - if (controller === undefined) { - controller = new WebXRController(); - controllers[index] = controller; - } - return controller.getHandSpace(); - }; + if ( scope.enableRotate === false ) return; - // + handleTouchMoveRotate( event ); - function onSessionEvent(event) { - const controllerIndex = controllerInputSources.indexOf(event.inputSource); - if (controllerIndex === -1) { - return; - } - const controller = controllers[controllerIndex]; - if (controller !== undefined) { - controller.dispatchEvent({ - type: event.type, - data: event.inputSource - }); - } - } - function onSessionEnd() { - session.removeEventListener('select', onSessionEvent); - session.removeEventListener('selectstart', onSessionEvent); - session.removeEventListener('selectend', onSessionEvent); - session.removeEventListener('squeeze', onSessionEvent); - session.removeEventListener('squeezestart', onSessionEvent); - session.removeEventListener('squeezeend', onSessionEvent); - session.removeEventListener('end', onSessionEnd); - session.removeEventListener('inputsourceschange', onInputSourcesChange); - for (let i = 0; i < controllers.length; i++) { - const inputSource = controllerInputSources[i]; - if (inputSource === null) continue; - controllerInputSources[i] = null; - controllers[i].disconnect(inputSource); - } - _currentDepthNear = null; - _currentDepthFar = null; + scope.update(); - // restore framebuffer/rendering state + break; - renderer.setRenderTarget(initialRenderTarget); - glBaseLayer = null; - glProjLayer = null; - glBinding = null; - session = null; - newRenderTarget = null; + case STATE.TOUCH_PAN: - // + if ( scope.enablePan === false ) return; - animation.stop(); - scope.isPresenting = false; - scope.dispatchEvent({ - type: 'sessionend' - }); - } - this.setFramebufferScaleFactor = function (value) { - framebufferScaleFactor = value; - if (scope.isPresenting === true) { - console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.'); - } - }; - this.setReferenceSpaceType = function (value) { - referenceSpaceType = value; - if (scope.isPresenting === true) { - console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.'); - } - }; - this.getReferenceSpace = function () { - return customReferenceSpace || referenceSpace; - }; - this.setReferenceSpace = function (space) { - customReferenceSpace = space; - }; - this.getBaseLayer = function () { - return glProjLayer !== null ? glProjLayer : glBaseLayer; - }; - this.getBinding = function () { - return glBinding; - }; - this.getFrame = function () { - return xrFrame; - }; - this.getSession = function () { - return session; - }; - this.setSession = async function (value) { - session = value; - if (session !== null) { - initialRenderTarget = renderer.getRenderTarget(); - session.addEventListener('select', onSessionEvent); - session.addEventListener('selectstart', onSessionEvent); - session.addEventListener('selectend', onSessionEvent); - session.addEventListener('squeeze', onSessionEvent); - session.addEventListener('squeezestart', onSessionEvent); - session.addEventListener('squeezeend', onSessionEvent); - session.addEventListener('end', onSessionEnd); - session.addEventListener('inputsourceschange', onInputSourcesChange); - if (attributes.xrCompatible !== true) { - await gl.makeXRCompatible(); - } - if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) { - const layerInit = { - antialias: session.renderState.layers === undefined ? attributes.antialias : true, - alpha: attributes.alpha, - depth: attributes.depth, - stencil: attributes.stencil, - framebufferScaleFactor: framebufferScaleFactor - }; - glBaseLayer = new XRWebGLLayer(session, gl, layerInit); - session.updateRenderState({ - baseLayer: glBaseLayer - }); - newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { - format: RGBAFormat, - type: UnsignedByteType, - encoding: renderer.outputEncoding, - stencilBuffer: attributes.stencil - }); - } else { - let depthFormat = null; - let depthType = null; - let glDepthFormat = null; - if (attributes.depth) { - glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; - depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; - depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; - } - const projectionlayerInit = { - colorFormat: gl.RGBA8, - depthFormat: glDepthFormat, - scaleFactor: framebufferScaleFactor - }; - glBinding = new XRWebGLBinding(session, gl); - glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); - session.updateRenderState({ - layers: [glProjLayer] - }); - newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, { - format: RGBAFormat, - type: UnsignedByteType, - depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), - stencilBuffer: attributes.stencil, - encoding: renderer.outputEncoding, - samples: attributes.antialias ? 4 : 0 - }); - const renderTargetProperties = renderer.properties.get(newRenderTarget); - renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; - } - newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + handleTouchMovePan( event ); - // Set foveation to maximum. - this.setFoveation(1.0); - customReferenceSpace = null; - referenceSpace = await session.requestReferenceSpace(referenceSpaceType); - animation.setContext(session); - animation.start(); - scope.isPresenting = true; - scope.dispatchEvent({ - type: 'sessionstart' - }); - } - }; - function onInputSourcesChange(event) { - // Notify disconnected + scope.update(); - for (let i = 0; i < event.removed.length; i++) { - const inputSource = event.removed[i]; - const index = controllerInputSources.indexOf(inputSource); - if (index >= 0) { - controllerInputSources[index] = null; - controllers[index].dispatchEvent({ - type: 'disconnected', - data: inputSource - }); - } - } + break; - // Notify connected + case STATE.TOUCH_DOLLY_PAN: - for (let i = 0; i < event.added.length; i++) { - const inputSource = event.added[i]; - let controllerIndex = controllerInputSources.indexOf(inputSource); - if (controllerIndex === -1) { - // Assign input source a controller that currently has no input source + if ( scope.enableZoom === false && scope.enablePan === false ) return; - for (let i = 0; i < controllers.length; i++) { - if (i >= controllerInputSources.length) { - controllerInputSources.push(inputSource); - controllerIndex = i; - break; - } else if (controllerInputSources[i] === null) { - controllerInputSources[i] = inputSource; - controllerIndex = i; - break; - } - } + handleTouchMoveDollyPan( event ); - // If all controllers do currently receive input we ignore new ones + scope.update(); - if (controllerIndex === -1) break; - } - const controller = controllers[controllerIndex]; - if (controller) { - controller.dispatchEvent({ - type: 'connected', - data: inputSource - }); - } - } - } + break; - // + case STATE.TOUCH_DOLLY_ROTATE: - const cameraLPos = new Vector3(); - const cameraRPos = new Vector3(); + if ( scope.enableZoom === false && scope.enableRotate === false ) return; - /** - * Assumes 2 cameras that are parallel and share an X-axis, and that - * the cameras' projection and world matrices have already been set. - * And that near and far planes are identical for both cameras. - * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 - */ - function setProjectionFromUnion(camera, cameraL, cameraR) { - cameraLPos.setFromMatrixPosition(cameraL.matrixWorld); - cameraRPos.setFromMatrixPosition(cameraR.matrixWorld); - const ipd = cameraLPos.distanceTo(cameraRPos); - const projL = cameraL.projectionMatrix.elements; - const projR = cameraR.projectionMatrix.elements; + handleTouchMoveDollyRotate( event ); - // VR systems will have identical far and near planes, and - // most likely identical top and bottom frustum extents. - // Use the left camera for these values. - const near = projL[14] / (projL[10] - 1); - const far = projL[14] / (projL[10] + 1); - const topFov = (projL[9] + 1) / projL[5]; - const bottomFov = (projL[9] - 1) / projL[5]; - const leftFov = (projL[8] - 1) / projL[0]; - const rightFov = (projR[8] + 1) / projR[0]; - const left = near * leftFov; - const right = near * rightFov; + scope.update(); - // Calculate the new camera's position offset from the - // left camera. xOffset should be roughly half `ipd`. - const zOffset = ipd / (-leftFov + rightFov); - const xOffset = zOffset * -leftFov; + break; - // TODO: Better way to apply this offset? - cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); - camera.translateX(xOffset); - camera.translateZ(zOffset); - camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); - camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + default: - // Find the union of the frustum values of the cameras and scale - // the values so that the near plane's position does not change in world space, - // although must now be relative to the new union camera. - const near2 = near + zOffset; - const far2 = far + zOffset; - const left2 = left - xOffset; - const right2 = right + (ipd - xOffset); - const top2 = topFov * far / far2 * near2; - const bottom2 = bottomFov * far / far2 * near2; - camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); - } - function updateCamera(camera, parent) { - if (parent === null) { - camera.matrixWorld.copy(camera.matrix); - } else { - camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix); - } - camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); - } - this.updateCamera = function (camera) { - if (session === null) return; - cameraVR.near = cameraR.near = cameraL.near = camera.near; - cameraVR.far = cameraR.far = cameraL.far = camera.far; - if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) { - // Note that the new renderState won't apply until the next frame. See #18320 + state = STATE.NONE; - session.updateRenderState({ - depthNear: cameraVR.near, - depthFar: cameraVR.far - }); - _currentDepthNear = cameraVR.near; - _currentDepthFar = cameraVR.far; } - const parent = camera.parent; - const cameras = cameraVR.cameras; - updateCamera(cameraVR, parent); - for (let i = 0; i < cameras.length; i++) { - updateCamera(cameras[i], parent); - } - cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); - // update user camera and its children + } + + function onContextMenu( event ) { - camera.matrix.copy(cameraVR.matrix); - camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); - const children = camera.children; - for (let i = 0, l = children.length; i < l; i++) { - children[i].updateMatrixWorld(true); - } + if ( scope.enabled === false ) return; - // update projection matrix for proper view frustum culling + event.preventDefault(); - if (cameras.length === 2) { - setProjectionFromUnion(cameraVR, cameraL, cameraR); - } else { - // assume single camera setup (AR) + } - cameraVR.projectionMatrix.copy(cameraL.projectionMatrix); - } - }; - this.getCamera = function () { - return cameraVR; - }; - this.getFoveation = function () { - if (glProjLayer !== null) { - return glProjLayer.fixedFoveation; - } - if (glBaseLayer !== null) { - return glBaseLayer.fixedFoveation; - } - return undefined; - }; - this.setFoveation = function (foveation) { - // 0 = no foveation = full resolution - // 1 = maximum foveation = the edges render at lower resolution + function addPointer( event ) { - if (glProjLayer !== null) { - glProjLayer.fixedFoveation = foveation; - } - if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { - glBaseLayer.fixedFoveation = foveation; - } - }; + pointers.push( event ); - // Animation Loop + } - let onAnimationFrameCallback = null; - function onAnimationFrame(time, frame) { - pose = frame.getViewerPose(customReferenceSpace || referenceSpace); - xrFrame = frame; - if (pose !== null) { - const views = pose.views; - if (glBaseLayer !== null) { - renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); - renderer.setRenderTarget(newRenderTarget); - } - let cameraVRNeedsUpdate = false; + function removePointer( event ) { - // check if it's necessary to rebuild cameraVR's camera list + delete pointerPositions[ event.pointerId ]; - if (views.length !== cameraVR.cameras.length) { - cameraVR.cameras.length = 0; - cameraVRNeedsUpdate = true; - } - for (let i = 0; i < views.length; i++) { - const view = views[i]; - let viewport = null; - if (glBaseLayer !== null) { - viewport = glBaseLayer.getViewport(view); - } else { - const glSubImage = glBinding.getViewSubImage(glProjLayer, view); - viewport = glSubImage.viewport; + for ( let i = 0; i < pointers.length; i ++ ) { - // For side-by-side projection, we only produce a single texture for both eyes. - if (i === 0) { - renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); - renderer.setRenderTarget(newRenderTarget); - } - } - let camera = cameras[i]; - if (camera === undefined) { - camera = new PerspectiveCamera(); - camera.layers.enable(i); - camera.viewport = new Vector4(); - cameras[i] = camera; - } - camera.matrix.fromArray(view.transform.matrix); - camera.projectionMatrix.fromArray(view.projectionMatrix); - camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); - if (i === 0) { - cameraVR.matrix.copy(camera.matrix); - } - if (cameraVRNeedsUpdate === true) { - cameraVR.cameras.push(camera); - } - } - } + if ( pointers[ i ].pointerId == event.pointerId ) { - // + pointers.splice( i, 1 ); + return; - for (let i = 0; i < controllers.length; i++) { - const inputSource = controllerInputSources[i]; - const controller = controllers[i]; - if (inputSource !== null && controller !== undefined) { - controller.update(inputSource, frame, customReferenceSpace || referenceSpace); } - } - if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame); - xrFrame = null; - } - const animation = new WebGLAnimation(); - animation.setAnimationLoop(onAnimationFrame); - this.setAnimationLoop = function (callback) { - onAnimationFrameCallback = callback; - }; - this.dispose = function () {}; - } -} -function WebGLMaterials(renderer, properties) { - function refreshFogUniforms(uniforms, fog) { - uniforms.fogColor.value.copy(fog.color); - if (fog.isFog) { - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; - } else if (fog.isFogExp2) { - uniforms.fogDensity.value = fog.density; - } - } - function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) { - if (material.isMeshBasicMaterial) { - refreshUniformsCommon(uniforms, material); - } else if (material.isMeshLambertMaterial) { - refreshUniformsCommon(uniforms, material); - } else if (material.isMeshToonMaterial) { - refreshUniformsCommon(uniforms, material); - refreshUniformsToon(uniforms, material); - } else if (material.isMeshPhongMaterial) { - refreshUniformsCommon(uniforms, material); - refreshUniformsPhong(uniforms, material); - } else if (material.isMeshStandardMaterial) { - refreshUniformsCommon(uniforms, material); - refreshUniformsStandard(uniforms, material); - if (material.isMeshPhysicalMaterial) { - refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); - } - } else if (material.isMeshMatcapMaterial) { - refreshUniformsCommon(uniforms, material); - refreshUniformsMatcap(uniforms, material); - } else if (material.isMeshDepthMaterial) { - refreshUniformsCommon(uniforms, material); - } else if (material.isMeshDistanceMaterial) { - refreshUniformsCommon(uniforms, material); - refreshUniformsDistance(uniforms, material); - } else if (material.isMeshNormalMaterial) { - refreshUniformsCommon(uniforms, material); - } else if (material.isLineBasicMaterial) { - refreshUniformsLine(uniforms, material); - if (material.isLineDashedMaterial) { - refreshUniformsDash(uniforms, material); } - } else if (material.isPointsMaterial) { - refreshUniformsPoints(uniforms, material, pixelRatio, height); - } else if (material.isSpriteMaterial) { - refreshUniformsSprites(uniforms, material); - } else if (material.isShadowMaterial) { - uniforms.color.value.copy(material.color); - uniforms.opacity.value = material.opacity; - } else if (material.isShaderMaterial) { - material.uniformsNeedUpdate = false; // #15581 - } - } - function refreshUniformsCommon(uniforms, material) { - uniforms.opacity.value = material.opacity; - if (material.color) { - uniforms.diffuse.value.copy(material.color); - } - if (material.emissive) { - uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); } - if (material.map) { - uniforms.map.value = material.map; - } - if (material.alphaMap) { - uniforms.alphaMap.value = material.alphaMap; - } - if (material.bumpMap) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if (material.side === BackSide) uniforms.bumpScale.value *= -1; - } - if (material.displacementMap) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; - } - if (material.emissiveMap) { - uniforms.emissiveMap.value = material.emissiveMap; - } - if (material.normalMap) { - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy(material.normalScale); - if (material.side === BackSide) uniforms.normalScale.value.negate(); - } - if (material.specularMap) { - uniforms.specularMap.value = material.specularMap; - } - if (material.alphaTest > 0) { - uniforms.alphaTest.value = material.alphaTest; - } - const envMap = properties.get(material).envMap; - if (envMap) { - uniforms.envMap.value = envMap; - uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; - uniforms.reflectivity.value = material.reflectivity; - uniforms.ior.value = material.ior; - uniforms.refractionRatio.value = material.refractionRatio; - } - if (material.lightMap) { - uniforms.lightMap.value = material.lightMap; - // artist-friendly light intensity scaling factor - const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1; - uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; - } - if (material.aoMap) { - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; - } + function trackPointer( event ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. displacementMap map - // 4. normal map - // 5. bump map - // 6. roughnessMap map - // 7. metalnessMap map - // 8. alphaMap map - // 9. emissiveMap map - // 10. clearcoat map - // 11. clearcoat normal map - // 12. clearcoat roughnessMap map - // 13. iridescence map - // 14. iridescence thickness map - // 15. specular intensity map - // 16. specular tint map - // 17. transmission map - // 18. thickness map - - let uvScaleMap; - if (material.map) { - uvScaleMap = material.map; - } else if (material.specularMap) { - uvScaleMap = material.specularMap; - } else if (material.displacementMap) { - uvScaleMap = material.displacementMap; - } else if (material.normalMap) { - uvScaleMap = material.normalMap; - } else if (material.bumpMap) { - uvScaleMap = material.bumpMap; - } else if (material.roughnessMap) { - uvScaleMap = material.roughnessMap; - } else if (material.metalnessMap) { - uvScaleMap = material.metalnessMap; - } else if (material.alphaMap) { - uvScaleMap = material.alphaMap; - } else if (material.emissiveMap) { - uvScaleMap = material.emissiveMap; - } else if (material.clearcoatMap) { - uvScaleMap = material.clearcoatMap; - } else if (material.clearcoatNormalMap) { - uvScaleMap = material.clearcoatNormalMap; - } else if (material.clearcoatRoughnessMap) { - uvScaleMap = material.clearcoatRoughnessMap; - } else if (material.iridescenceMap) { - uvScaleMap = material.iridescenceMap; - } else if (material.iridescenceThicknessMap) { - uvScaleMap = material.iridescenceThicknessMap; - } else if (material.specularIntensityMap) { - uvScaleMap = material.specularIntensityMap; - } else if (material.specularColorMap) { - uvScaleMap = material.specularColorMap; - } else if (material.transmissionMap) { - uvScaleMap = material.transmissionMap; - } else if (material.thicknessMap) { - uvScaleMap = material.thicknessMap; - } else if (material.sheenColorMap) { - uvScaleMap = material.sheenColorMap; - } else if (material.sheenRoughnessMap) { - uvScaleMap = material.sheenRoughnessMap; - } - if (uvScaleMap !== undefined) { - // backwards compatibility - if (uvScaleMap.isWebGLRenderTarget) { - uvScaleMap = uvScaleMap.texture; - } - if (uvScaleMap.matrixAutoUpdate === true) { - uvScaleMap.updateMatrix(); - } - uniforms.uvTransform.value.copy(uvScaleMap.matrix); - } + let position = pointerPositions[ event.pointerId ]; - // uv repeat and offset setting priorities for uv2 - // 1. ao map - // 2. light map + if ( position === undefined ) { + + position = new Vector2(); + pointerPositions[ event.pointerId ] = position; - let uv2ScaleMap; - if (material.aoMap) { - uv2ScaleMap = material.aoMap; - } else if (material.lightMap) { - uv2ScaleMap = material.lightMap; - } - if (uv2ScaleMap !== undefined) { - // backwards compatibility - if (uv2ScaleMap.isWebGLRenderTarget) { - uv2ScaleMap = uv2ScaleMap.texture; - } - if (uv2ScaleMap.matrixAutoUpdate === true) { - uv2ScaleMap.updateMatrix(); } - uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix); - } - } - function refreshUniformsLine(uniforms, material) { - uniforms.diffuse.value.copy(material.color); - uniforms.opacity.value = material.opacity; - } - function refreshUniformsDash(uniforms, material) { - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; - } - function refreshUniformsPoints(uniforms, material, pixelRatio, height) { - uniforms.diffuse.value.copy(material.color); - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * pixelRatio; - uniforms.scale.value = height * 0.5; - if (material.map) { - uniforms.map.value = material.map; - } - if (material.alphaMap) { - uniforms.alphaMap.value = material.alphaMap; - } - if (material.alphaTest > 0) { - uniforms.alphaTest.value = material.alphaTest; - } - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + position.set( event.pageX, event.pageY ); - let uvScaleMap; - if (material.map) { - uvScaleMap = material.map; - } else if (material.alphaMap) { - uvScaleMap = material.alphaMap; - } - if (uvScaleMap !== undefined) { - if (uvScaleMap.matrixAutoUpdate === true) { - uvScaleMap.updateMatrix(); - } - uniforms.uvTransform.value.copy(uvScaleMap.matrix); - } - } - function refreshUniformsSprites(uniforms, material) { - uniforms.diffuse.value.copy(material.color); - uniforms.opacity.value = material.opacity; - uniforms.rotation.value = material.rotation; - if (material.map) { - uniforms.map.value = material.map; - } - if (material.alphaMap) { - uniforms.alphaMap.value = material.alphaMap; - } - if (material.alphaTest > 0) { - uniforms.alphaTest.value = material.alphaTest; } - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + function getSecondPointerPosition( event ) { - let uvScaleMap; - if (material.map) { - uvScaleMap = material.map; - } else if (material.alphaMap) { - uvScaleMap = material.alphaMap; - } - if (uvScaleMap !== undefined) { - if (uvScaleMap.matrixAutoUpdate === true) { - uvScaleMap.updateMatrix(); - } - uniforms.uvTransform.value.copy(uvScaleMap.matrix); - } - } - function refreshUniformsPhong(uniforms, material) { - uniforms.specular.value.copy(material.specular); - uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 ) - } + const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - function refreshUniformsToon(uniforms, material) { - if (material.gradientMap) { - uniforms.gradientMap.value = material.gradientMap; - } - } - function refreshUniformsStandard(uniforms, material) { - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; - if (material.roughnessMap) { - uniforms.roughnessMap.value = material.roughnessMap; - } - if (material.metalnessMap) { - uniforms.metalnessMap.value = material.metalnessMap; - } - const envMap = properties.get(material).envMap; - if (envMap) { - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; - } - } - function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { - uniforms.ior.value = material.ior; // also part of uniforms common + return pointerPositions[ pointer.pointerId ]; - if (material.sheen > 0) { - uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); - uniforms.sheenRoughness.value = material.sheenRoughness; - if (material.sheenColorMap) { - uniforms.sheenColorMap.value = material.sheenColorMap; - } - if (material.sheenRoughnessMap) { - uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; - } - } - if (material.clearcoat > 0) { - uniforms.clearcoat.value = material.clearcoat; - uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if (material.clearcoatMap) { - uniforms.clearcoatMap.value = material.clearcoatMap; - } - if (material.clearcoatRoughnessMap) { - uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; - } - if (material.clearcoatNormalMap) { - uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); - uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; - if (material.side === BackSide) { - uniforms.clearcoatNormalScale.value.negate(); - } - } - } - if (material.iridescence > 0) { - uniforms.iridescence.value = material.iridescence; - uniforms.iridescenceIOR.value = material.iridescenceIOR; - uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; - uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; - if (material.iridescenceMap) { - uniforms.iridescenceMap.value = material.iridescenceMap; - } - if (material.iridescenceThicknessMap) { - uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; - } - } - if (material.transmission > 0) { - uniforms.transmission.value = material.transmission; - uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; - uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); - if (material.transmissionMap) { - uniforms.transmissionMap.value = material.transmissionMap; - } - uniforms.thickness.value = material.thickness; - if (material.thicknessMap) { - uniforms.thicknessMap.value = material.thicknessMap; - } - uniforms.attenuationDistance.value = material.attenuationDistance; - uniforms.attenuationColor.value.copy(material.attenuationColor); - } - uniforms.specularIntensity.value = material.specularIntensity; - uniforms.specularColor.value.copy(material.specularColor); - if (material.specularIntensityMap) { - uniforms.specularIntensityMap.value = material.specularIntensityMap; } - if (material.specularColorMap) { - uniforms.specularColorMap.value = material.specularColorMap; - } - } - function refreshUniformsMatcap(uniforms, material) { - if (material.matcap) { - uniforms.matcap.value = material.matcap; - } - } - function refreshUniformsDistance(uniforms, material) { - uniforms.referencePosition.value.copy(material.referencePosition); - uniforms.nearDistance.value = material.nearDistance; - uniforms.farDistance.value = material.farDistance; + + // + + scope.domElement.addEventListener( 'contextmenu', onContextMenu ); + + scope.domElement.addEventListener( 'pointerdown', onPointerDown ); + scope.domElement.addEventListener( 'pointercancel', onPointerUp ); + scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); + + // force an update at start + + this.update(); + } - return { - refreshFogUniforms: refreshFogUniforms, - refreshMaterialUniforms: refreshMaterialUniforms - }; + } -function WebGLUniformsGroups(gl, info, capabilities, state) { - let buffers = {}; - let updateList = {}; - let allocatedBindingPoints = []; - const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program +/** + * Full-screen textured quad shader + */ - function bind(uniformsGroup, program) { - const webglProgram = program.program; - state.uniformBlockBinding(uniformsGroup, webglProgram); - } - function update(uniformsGroup, program) { - let buffer = buffers[uniformsGroup.id]; - if (buffer === undefined) { - prepareUniformsGroup(uniformsGroup); - buffer = createBuffer(uniformsGroup); - buffers[uniformsGroup.id] = buffer; - uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose); - } +const CopyShader = { - // ensure to update the binding points/block indices mapping for this program + name: 'CopyShader', - const webglProgram = program.program; - state.updateUBOMapping(uniformsGroup, webglProgram); + uniforms: { - // update UBO once per frame + 'tDiffuse': { value: null }, + 'opacity': { value: 1.0 } - const frame = info.render.frame; - if (updateList[uniformsGroup.id] !== frame) { - updateBufferData(uniformsGroup); - updateList[uniformsGroup.id] = frame; - } - } - function createBuffer(uniformsGroup) { - // the setup of an UBO is independent of a particular shader program but global + }, - const bindingPointIndex = allocateBindingPointIndex(); - uniformsGroup.__bindingPointIndex = bindingPointIndex; - const buffer = gl.createBuffer(); - const size = uniformsGroup.__size; - const usage = uniformsGroup.usage; - gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); - gl.bufferData(gl.UNIFORM_BUFFER, size, usage); - gl.bindBuffer(gl.UNIFORM_BUFFER, null); - gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); - return buffer; - } - function allocateBindingPointIndex() { - for (let i = 0; i < maxBindingPoints; i++) { - if (allocatedBindingPoints.indexOf(i) === -1) { - allocatedBindingPoints.push(i); - return i; - } - } - console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.'); - return 0; - } - function updateBufferData(uniformsGroup) { - const buffer = buffers[uniformsGroup.id]; - const uniforms = uniformsGroup.uniforms; - const cache = uniformsGroup.__cache; - gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); - for (let i = 0, il = uniforms.length; i < il; i++) { - const uniform = uniforms[i]; + vertexShader: /* glsl */` - // partly update the buffer if necessary + varying vec2 vUv; - if (hasUniformChanged(uniform, i, cache) === true) { - const value = uniform.value; - const offset = uniform.__offset; - if (typeof value === 'number') { - uniform.__data[0] = value; - gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); - } else { - if (uniform.value.isMatrix3) { - // manually converting 3x3 to 3x4 + void main() { - uniform.__data[0] = uniform.value.elements[0]; - uniform.__data[1] = uniform.value.elements[1]; - uniform.__data[2] = uniform.value.elements[2]; - uniform.__data[3] = uniform.value.elements[0]; - uniform.__data[4] = uniform.value.elements[3]; - uniform.__data[5] = uniform.value.elements[4]; - uniform.__data[6] = uniform.value.elements[5]; - uniform.__data[7] = uniform.value.elements[0]; - uniform.__data[8] = uniform.value.elements[6]; - uniform.__data[9] = uniform.value.elements[7]; - uniform.__data[10] = uniform.value.elements[8]; - uniform.__data[11] = uniform.value.elements[0]; - } else { - value.toArray(uniform.__data); - } - gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); - } - } - } - gl.bindBuffer(gl.UNIFORM_BUFFER, null); - } - function hasUniformChanged(uniform, index, cache) { - const value = uniform.value; - if (cache[index] === undefined) { - // cache entry does not exist so far + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - if (typeof value === 'number') { - cache[index] = value; - } else { - cache[index] = value.clone(); - } - return true; - } else { - // compare current value with cached entry + }`, - if (typeof value === 'number') { - if (cache[index] !== value) { - cache[index] = value; - return true; - } - } else { - const cachedObject = cache[index]; - if (cachedObject.equals(value) === false) { - cachedObject.copy(value); - return true; - } - } - } - return false; - } - function prepareUniformsGroup(uniformsGroup) { - // determine total buffer size according to the STD140 layout - // Hint: STD140 is the only supported layout in WebGL 2 + fragmentShader: /* glsl */` - const uniforms = uniformsGroup.uniforms; - let offset = 0; // global buffer offset in bytes - const chunkSize = 16; // size of a chunk in bytes - let chunkOffset = 0; // offset within a single chunk in bytes + uniform float opacity; - for (let i = 0, l = uniforms.length; i < l; i++) { - const uniform = uniforms[i]; - const info = getUniformSize(uniform); + uniform sampler2D tDiffuse; - // the following two properties will be used for partial buffer updates + varying vec2 vUv; - uniform.__data = new Float32Array(info.storage / Float32Array.BYTES_PER_ELEMENT); - uniform.__offset = offset; + void main() { - // + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = opacity * texel; - if (i > 0) { - chunkOffset = offset % chunkSize; - const remainingSizeInChunk = chunkSize - chunkOffset; - // check for chunk overflow + }` - if (chunkOffset !== 0 && remainingSizeInChunk - info.boundary < 0) { - // add padding and adjust offset +}; - offset += chunkSize - chunkOffset; - uniform.__offset = offset; - } - } - offset += info.storage; - } +class Pass { - // ensure correct final padding + constructor() { - chunkOffset = offset % chunkSize; - if (chunkOffset > 0) offset += chunkSize - chunkOffset; + this.isPass = true; - // + // if set to true, the pass is processed by the composer + this.enabled = true; + + // if set to true, the pass indicates to swap read and write buffer after rendering + this.needsSwap = true; + + // if set to true, the pass clears its buffer before rendering + this.clear = false; + + // if set to true, the result of the pass is rendered to screen. This is set automatically by EffectComposer. + this.renderToScreen = false; - uniformsGroup.__size = offset; - uniformsGroup.__cache = {}; - return this; } - function getUniformSize(uniform) { - const value = uniform.value; - const info = { - boundary: 0, - // bytes - storage: 0 // bytes - }; - // determine sizes according to STD140 + setSize( /* width, height */ ) {} - if (typeof value === 'number') { - // float/int + render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) { - info.boundary = 4; - info.storage = 4; - } else if (value.isVector2) { - // vec2 + console.error( 'THREE.Pass: .render() must be implemented in derived pass.' ); - info.boundary = 8; - info.storage = 8; - } else if (value.isVector3 || value.isColor) { - // vec3 + } - info.boundary = 16; - info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes - } else if (value.isVector4) { - // vec4 + dispose() {} - info.boundary = 16; - info.storage = 16; - } else if (value.isMatrix3) { - // mat3 (in STD140 a 3x3 matrix is represented as 3x4) +} - info.boundary = 48; - info.storage = 48; - } else if (value.isMatrix4) { - // mat4 +// Helper for passes that need to fill the viewport with a single quad. + +const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + +// https://github.com/mrdoob/three.js/pull/21358 + +const _geometry = new BufferGeometry(); +_geometry.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) ); +_geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) ); + +class FullScreenQuad { + + constructor( material ) { + + this._mesh = new Mesh( _geometry, material ); - info.boundary = 64; - info.storage = 64; - } else if (value.isTexture) { - console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.'); - } else { - console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value); - } - return info; - } - function onUniformsGroupsDispose(event) { - const uniformsGroup = event.target; - uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose); - const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); - allocatedBindingPoints.splice(index, 1); - gl.deleteBuffer(buffers[uniformsGroup.id]); - delete buffers[uniformsGroup.id]; - delete updateList[uniformsGroup.id]; } - function dispose() { - for (const id in buffers) { - gl.deleteBuffer(buffers[id]); - } - allocatedBindingPoints = []; - buffers = {}; - updateList = {}; + + dispose() { + + this._mesh.geometry.dispose(); + } - return { - bind: bind, - update: update, - dispose: dispose - }; -} -function createCanvasElement() { - const canvas = createElementNS('canvas'); - canvas.style.display = 'block'; - return canvas; -} -function WebGLRenderer(parameters = {}) { - this.isWebGLRenderer = true; - const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), - _context = parameters.context !== undefined ? parameters.context : null, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, - _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', - _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; - let _alpha; - if (_context !== null) { - _alpha = _context.getContextAttributes().alpha; - } else { - _alpha = parameters.alpha !== undefined ? parameters.alpha : false; + render( renderer ) { + + renderer.render( this._mesh, _camera ); + } - let currentRenderList = null; - let currentRenderState = null; - // render() can be called from within a callback triggered by another render. - // We track this so that the nested render call gets its list and state isolated from the parent render call. + get material() { - const renderListStack = []; - const renderStateStack = []; + return this._mesh.material; - // public properties + } - this.domElement = _canvas; + set material( value ) { - // Debug configuration container - this.debug = { - /** - * Enables error checking and reporting when shader programs are being compiled - * @type {boolean} - */ - checkShaderErrors: true - }; + this._mesh.material = value; - // clearing + } - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; +} - // scene graph +class ShaderPass extends Pass { - this.sortObjects = true; + constructor( shader, textureID ) { - // user-defined clipping + super(); - this.clippingPlanes = []; - this.localClippingEnabled = false; + this.textureID = ( textureID !== undefined ) ? textureID : 'tDiffuse'; - // physically based shading + if ( shader instanceof ShaderMaterial ) { - this.outputEncoding = LinearEncoding; + this.uniforms = shader.uniforms; - // physical lights + this.material = shader; - this.physicallyCorrectLights = false; + } else if ( shader ) { - // tone mapping + this.uniforms = UniformsUtils.clone( shader.uniforms ); - this.toneMapping = NoToneMapping; - this.toneMappingExposure = 1.0; + this.material = new ShaderMaterial( { - // + name: ( shader.name !== undefined ) ? shader.name : 'unspecified', + defines: Object.assign( {}, shader.defines ), + uniforms: this.uniforms, + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader - Object.defineProperties(this, { - // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d + } ); - gammaFactor: { - get: function () { - console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.'); - return 2; - }, - set: function () { - console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.'); - } } - }); - // internal properties + this.fsQuad = new FullScreenQuad( this.material ); + + } - const _this = this; - let _isContextLost = false; + render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) { - // internal state cache + if ( this.uniforms[ this.textureID ] ) { - let _currentActiveCubeFace = 0; - let _currentActiveMipmapLevel = 0; - let _currentRenderTarget = null; - let _currentMaterialId = -1; - let _currentCamera = null; - const _currentViewport = new Vector4(); - const _currentScissor = new Vector4(); - let _currentScissorTest = null; + this.uniforms[ this.textureID ].value = readBuffer.texture; - // + } + + this.fsQuad.material = this.material; + + if ( this.renderToScreen ) { - let _width = _canvas.width; - let _height = _canvas.height; - let _pixelRatio = 1; - let _opaqueSort = null; - let _transparentSort = null; - const _viewport = new Vector4(0, 0, _width, _height); - const _scissor = new Vector4(0, 0, _width, _height); - let _scissorTest = false; + renderer.setRenderTarget( null ); + this.fsQuad.render( renderer ); - // frustum + } else { - const _frustum = new Frustum(); + renderer.setRenderTarget( writeBuffer ); + // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600 + if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + this.fsQuad.render( renderer ); - // clipping + } - let _clippingEnabled = false; - let _localClippingEnabled = false; + } - // transmission + dispose() { - let _transmissionRenderTarget = null; + this.material.dispose(); - // camera matrices cache + this.fsQuad.dispose(); - const _projScreenMatrix = new Matrix4(); - const _vector2 = new Vector2(); - const _vector3 = new Vector3(); - const _emptyScene = { - background: null, - fog: null, - environment: null, - overrideMaterial: null, - isScene: true - }; - function getTargetPixelRatio() { - return _currentRenderTarget === null ? _pixelRatio : 1; } - // initialize +} + +class MaskPass extends Pass { + + constructor( scene, camera ) { + + super(); + + this.scene = scene; + this.camera = camera; + + this.clear = true; + this.needsSwap = false; + + this.inverse = false; - let _gl = _context; - function getContext(contextNames, contextAttributes) { - for (let i = 0; i < contextNames.length; i++) { - const contextName = contextNames[i]; - const context = _canvas.getContext(contextName, contextAttributes); - if (context !== null) return context; - } - return null; } - try { - const contextAttributes = { - alpha: true, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer, - powerPreference: _powerPreference, - failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat - }; - // OffscreenCanvas does not have setAttribute, see #22811 - if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); - - // event listeners must be registered before WebGL context is created, see #12753 - _canvas.addEventListener('webglcontextlost', onContextLost, false); - _canvas.addEventListener('webglcontextrestored', onContextRestore, false); - _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false); - if (_gl === null) { - const contextNames = ['webgl2', 'webgl', 'experimental-webgl']; - if (_this.isWebGL1Renderer === true) { - contextNames.shift(); - } - _gl = getContext(contextNames, contextAttributes); - if (_gl === null) { - if (getContext(contextNames)) { - throw new Error('Error creating WebGL context with your selected attributes.'); - } else { - throw new Error('Error creating WebGL context.'); - } - } - } + render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) { - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + const context = renderer.getContext(); + const state = renderer.state; + + // don't update color or depth + + state.buffers.color.setMask( false ); + state.buffers.depth.setMask( false ); + + // lock buffers + + state.buffers.color.setLocked( true ); + state.buffers.depth.setLocked( true ); + + // set up stencil + + let writeValue, clearValue; + + if ( this.inverse ) { + + writeValue = 0; + clearValue = 1; - if (_gl.getShaderPrecisionFormat === undefined) { - _gl.getShaderPrecisionFormat = function () { - return { - 'rangeMin': 1, - 'rangeMax': 1, - 'precision': 1 - }; - }; - } - } catch (error) { - console.error('THREE.WebGLRenderer: ' + error.message); - throw error; - } - let extensions, capabilities, state, info; - let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; - let programCache, materials, renderLists, renderStates, clipping, shadowMap; - let background, morphtargets, bufferRenderer, indexedBufferRenderer; - let utils, bindingStates, uniformsGroups; - function initGLContext() { - extensions = new WebGLExtensions(_gl); - capabilities = new WebGLCapabilities(_gl, extensions, parameters); - extensions.init(capabilities); - utils = new WebGLUtils(_gl, extensions, capabilities); - state = new WebGLState(_gl, extensions, capabilities); - info = new WebGLInfo(_gl); - properties = new WebGLProperties(); - textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); - cubemaps = new WebGLCubeMaps(_this); - cubeuvmaps = new WebGLCubeUVMaps(_this); - attributes = new WebGLAttributes(_gl, capabilities); - bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities); - geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); - objects = new WebGLObjects(_gl, geometries, attributes, info); - morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); - clipping = new WebGLClipping(properties); - programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); - materials = new WebGLMaterials(_this, properties); - renderLists = new WebGLRenderLists(); - renderStates = new WebGLRenderStates(extensions, capabilities); - background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha); - shadowMap = new WebGLShadowMap(_this, objects, capabilities); - uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); - bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities); - indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities); - info.programs = programCache.programs; - _this.capabilities = capabilities; - _this.extensions = extensions; - _this.properties = properties; - _this.renderLists = renderLists; - _this.shadowMap = shadowMap; - _this.state = state; - _this.info = info; - } - initGLContext(); - - // xr - - const xr = new WebXRManager(_this, _gl); - this.xr = xr; - - // API - - this.getContext = function () { - return _gl; - }; - this.getContextAttributes = function () { - return _gl.getContextAttributes(); - }; - this.forceContextLoss = function () { - const extension = extensions.get('WEBGL_lose_context'); - if (extension) extension.loseContext(); - }; - this.forceContextRestore = function () { - const extension = extensions.get('WEBGL_lose_context'); - if (extension) extension.restoreContext(); - }; - this.getPixelRatio = function () { - return _pixelRatio; - }; - this.setPixelRatio = function (value) { - if (value === undefined) return; - _pixelRatio = value; - this.setSize(_width, _height, false); - }; - this.getSize = function (target) { - return target.set(_width, _height); - }; - this.setSize = function (width, height, updateStyle) { - if (xr.isPresenting) { - console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.'); - return; - } - _width = width; - _height = height; - _canvas.width = Math.floor(width * _pixelRatio); - _canvas.height = Math.floor(height * _pixelRatio); - if (updateStyle !== false) { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; - } - this.setViewport(0, 0, width, height); - }; - this.getDrawingBufferSize = function (target) { - return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); - }; - this.setDrawingBufferSize = function (width, height, pixelRatio) { - _width = width; - _height = height; - _pixelRatio = pixelRatio; - _canvas.width = Math.floor(width * pixelRatio); - _canvas.height = Math.floor(height * pixelRatio); - this.setViewport(0, 0, width, height); - }; - this.getCurrentViewport = function (target) { - return target.copy(_currentViewport); - }; - this.getViewport = function (target) { - return target.copy(_viewport); - }; - this.setViewport = function (x, y, width, height) { - if (x.isVector4) { - _viewport.set(x.x, x.y, x.z, x.w); - } else { - _viewport.set(x, y, width, height); - } - state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor()); - }; - this.getScissor = function (target) { - return target.copy(_scissor); - }; - this.setScissor = function (x, y, width, height) { - if (x.isVector4) { - _scissor.set(x.x, x.y, x.z, x.w); } else { - _scissor.set(x, y, width, height); + + writeValue = 1; + clearValue = 0; + } - state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor()); - }; - this.getScissorTest = function () { - return _scissorTest; - }; - this.setScissorTest = function (boolean) { - state.setScissorTest(_scissorTest = boolean); - }; - this.setOpaqueSort = function (method) { - _opaqueSort = method; - }; - this.setTransparentSort = function (method) { - _transparentSort = method; - }; - // Clearing + state.buffers.stencil.setTest( true ); + state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE ); + state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff ); + state.buffers.stencil.setClear( clearValue ); + state.buffers.stencil.setLocked( true ); - this.getClearColor = function (target) { - return target.copy(background.getClearColor()); - }; - this.setClearColor = function () { - background.setClearColor.apply(background, arguments); - }; - this.getClearAlpha = function () { - return background.getClearAlpha(); - }; - this.setClearAlpha = function () { - background.setClearAlpha.apply(background, arguments); - }; - this.clear = function (color = true, depth = true, stencil = true) { - let bits = 0; - if (color) bits |= _gl.COLOR_BUFFER_BIT; - if (depth) bits |= _gl.DEPTH_BUFFER_BIT; - if (stencil) bits |= _gl.STENCIL_BUFFER_BIT; - _gl.clear(bits); - }; - this.clearColor = function () { - this.clear(true, false, false); - }; - this.clearDepth = function () { - this.clear(false, true, false); - }; - this.clearStencil = function () { - this.clear(false, false, true); - }; + // draw into the stencil buffer - // + renderer.setRenderTarget( readBuffer ); + if ( this.clear ) renderer.clear(); + renderer.render( this.scene, this.camera ); - this.dispose = function () { - _canvas.removeEventListener('webglcontextlost', onContextLost, false); - _canvas.removeEventListener('webglcontextrestored', onContextRestore, false); - _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false); - renderLists.dispose(); - renderStates.dispose(); - properties.dispose(); - cubemaps.dispose(); - cubeuvmaps.dispose(); - objects.dispose(); - bindingStates.dispose(); - uniformsGroups.dispose(); - programCache.dispose(); - xr.dispose(); - xr.removeEventListener('sessionstart', onXRSessionStart); - xr.removeEventListener('sessionend', onXRSessionEnd); - if (_transmissionRenderTarget) { - _transmissionRenderTarget.dispose(); - _transmissionRenderTarget = null; - } - animation.stop(); - }; + renderer.setRenderTarget( writeBuffer ); + if ( this.clear ) renderer.clear(); + renderer.render( this.scene, this.camera ); + + // unlock color and depth buffer and make them writable for subsequent rendering/clearing + + state.buffers.color.setLocked( false ); + state.buffers.depth.setLocked( false ); + + state.buffers.color.setMask( true ); + state.buffers.depth.setMask( true ); + + // only render where stencil is set to 1 + + state.buffers.stencil.setLocked( false ); + state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1 + state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP ); + state.buffers.stencil.setLocked( true ); - // Events - - function onContextLost(event) { - event.preventDefault(); - console.log('THREE.WebGLRenderer: Context Lost.'); - _isContextLost = true; - } - function /* event */ - onContextRestore() { - console.log('THREE.WebGLRenderer: Context Restored.'); - _isContextLost = false; - const infoAutoReset = info.autoReset; - const shadowMapEnabled = shadowMap.enabled; - const shadowMapAutoUpdate = shadowMap.autoUpdate; - const shadowMapNeedsUpdate = shadowMap.needsUpdate; - const shadowMapType = shadowMap.type; - initGLContext(); - info.autoReset = infoAutoReset; - shadowMap.enabled = shadowMapEnabled; - shadowMap.autoUpdate = shadowMapAutoUpdate; - shadowMap.needsUpdate = shadowMapNeedsUpdate; - shadowMap.type = shadowMapType; - } - function onContextCreationError(event) { - console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage); - } - function onMaterialDispose(event) { - const material = event.target; - material.removeEventListener('dispose', onMaterialDispose); - deallocateMaterial(material); - } - - // Buffer deallocation - - function deallocateMaterial(material) { - releaseMaterialProgramReferences(material); - properties.remove(material); - } - function releaseMaterialProgramReferences(material) { - const programs = properties.get(material).programs; - if (programs !== undefined) { - programs.forEach(function (program) { - programCache.releaseProgram(program); - }); - if (material.isShaderMaterial) { - programCache.releaseShaderCache(material); - } - } } - // Buffer rendering +} + +class ClearMaskPass extends Pass { + + constructor() { + + super(); + + this.needsSwap = false; - this.renderBufferDirect = function (camera, scene, geometry, material, object, group) { - if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + } - const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; - const program = setProgram(camera, scene, geometry, material, object); - state.setMaterial(material, frontFaceCW); + render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) { - // + renderer.state.buffers.stencil.setLocked( false ); + renderer.state.buffers.stencil.setTest( false ); - let index = geometry.index; - const position = geometry.attributes.position; + } - // +} - if (index === null) { - if (position === undefined || position.count === 0) return; - } else if (index.count === 0) { - return; - } +class EffectComposer { - // + constructor( renderer, renderTarget ) { - let rangeFactor = 1; - if (material.wireframe === true) { - index = geometries.getWireframeAttribute(geometry); - rangeFactor = 2; - } - bindingStates.setup(object, material, program, geometry, index); - let attribute; - let renderer = bufferRenderer; - if (index !== null) { - attribute = attributes.get(index); - renderer = indexedBufferRenderer; - renderer.setIndex(attribute); - } + this.renderer = renderer; - // + this._pixelRatio = renderer.getPixelRatio(); - const dataCount = index !== null ? index.count : position.count; - const rangeStart = geometry.drawRange.start * rangeFactor; - const rangeCount = geometry.drawRange.count * rangeFactor; - const groupStart = group !== null ? group.start * rangeFactor : 0; - const groupCount = group !== null ? group.count * rangeFactor : Infinity; - const drawStart = Math.max(rangeStart, groupStart); - const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1; - const drawCount = Math.max(0, drawEnd - drawStart + 1); - if (drawCount === 0) return; + if ( renderTarget === undefined ) { - // + const size = renderer.getSize( new Vector2() ); + this._width = size.width; + this._height = size.height; + + renderTarget = new WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); + renderTarget.texture.name = 'EffectComposer.rt1'; - if (object.isMesh) { - if (material.wireframe === true) { - state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); - renderer.setMode(_gl.LINES); - } else { - renderer.setMode(_gl.TRIANGLES); - } - } else if (object.isLine) { - let lineWidth = material.linewidth; - if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material - - state.setLineWidth(lineWidth * getTargetPixelRatio()); - if (object.isLineSegments) { - renderer.setMode(_gl.LINES); - } else if (object.isLineLoop) { - renderer.setMode(_gl.LINE_LOOP); - } else { - renderer.setMode(_gl.LINE_STRIP); - } - } else if (object.isPoints) { - renderer.setMode(_gl.POINTS); - } else if (object.isSprite) { - renderer.setMode(_gl.TRIANGLES); - } - if (object.isInstancedMesh) { - renderer.renderInstances(drawStart, drawCount, object.count); - } else if (geometry.isInstancedBufferGeometry) { - const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount); - renderer.renderInstances(drawStart, drawCount, instanceCount); } else { - renderer.render(drawStart, drawCount); - } - }; - // Compile + this._width = renderTarget.width; + this._height = renderTarget.height; - this.compile = function (scene, camera) { - function prepare(material, scene, object) { - if (material.transparent === true && material.side === DoubleSide) { - material.side = BackSide; - material.needsUpdate = true; - getProgram(material, scene, object); - material.side = FrontSide; - material.needsUpdate = true; - getProgram(material, scene, object); - material.side = DoubleSide; - } else { - getProgram(material, scene, object); - } } - currentRenderState = renderStates.get(scene); - currentRenderState.init(); - renderStateStack.push(currentRenderState); - scene.traverseVisible(function (object) { - if (object.isLight && object.layers.test(camera.layers)) { - currentRenderState.pushLight(object); - if (object.castShadow) { - currentRenderState.pushShadow(object); - } - } - }); - currentRenderState.setupLights(_this.physicallyCorrectLights); - scene.traverse(function (object) { - const material = object.material; - if (material) { - if (Array.isArray(material)) { - for (let i = 0; i < material.length; i++) { - const material2 = material[i]; - prepare(material2, scene, object); - } - } else { - prepare(material, scene, object); - } - } - }); - renderStateStack.pop(); - currentRenderState = null; - }; - // Animation Loop - - let onAnimationFrameCallback = null; - function onAnimationFrame(time) { - if (onAnimationFrameCallback) onAnimationFrameCallback(time); - } - function onXRSessionStart() { - animation.stop(); - } - function onXRSessionEnd() { - animation.start(); - } - const animation = new WebGLAnimation(); - animation.setAnimationLoop(onAnimationFrame); - if (typeof self !== 'undefined') animation.setContext(self); - this.setAnimationLoop = function (callback) { - onAnimationFrameCallback = callback; - xr.setAnimationLoop(callback); - callback === null ? animation.stop() : animation.start(); - }; - xr.addEventListener('sessionstart', onXRSessionStart); - xr.addEventListener('sessionend', onXRSessionEnd); + this.renderTarget1 = renderTarget; + this.renderTarget2 = renderTarget.clone(); + this.renderTarget2.texture.name = 'EffectComposer.rt2'; - // Rendering + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; - this.render = function (scene, camera) { - if (camera !== undefined && camera.isCamera !== true) { - console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.'); - return; - } - if (_isContextLost === true) return; + this.renderToScreen = true; - // update scene graph + this.passes = []; - if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); + this.copyPass = new ShaderPass( CopyShader ); + this.copyPass.material.blending = NoBlending; - // update camera matrices and frustum + this.clock = new Clock(); - if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); - if (xr.enabled === true && xr.isPresenting === true) { - if (xr.cameraAutoUpdate === true) xr.updateCamera(camera); - camera = xr.getCamera(); // use XR camera for rendering - } + } - // - if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); - currentRenderState = renderStates.get(scene, renderStateStack.length); - currentRenderState.init(); - renderStateStack.push(currentRenderState); - _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); - _frustum.setFromProjectionMatrix(_projScreenMatrix); - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera); - currentRenderList = renderLists.get(scene, renderListStack.length); - currentRenderList.init(); - renderListStack.push(currentRenderList); - projectObject(scene, camera, 0, _this.sortObjects); - currentRenderList.finish(); - if (_this.sortObjects === true) { - currentRenderList.sort(_opaqueSort, _transparentSort); - } + swapBuffers() { - // + const tmp = this.readBuffer; + this.readBuffer = this.writeBuffer; + this.writeBuffer = tmp; - if (_clippingEnabled === true) clipping.beginShadows(); - const shadowsArray = currentRenderState.state.shadowsArray; - shadowMap.render(shadowsArray, scene, camera); - if (_clippingEnabled === true) clipping.endShadows(); + } - // + addPass( pass ) { - if (this.info.autoReset === true) this.info.reset(); + this.passes.push( pass ); + pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); - // + } - background.render(currentRenderList, scene); + insertPass( pass, index ) { - // render scene + this.passes.splice( index, 0, pass ); + pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); - currentRenderState.setupLights(_this.physicallyCorrectLights); - if (camera.isArrayCamera) { - const cameras = camera.cameras; - for (let i = 0, l = cameras.length; i < l; i++) { - const camera2 = cameras[i]; - renderScene(currentRenderList, scene, camera2, camera2.viewport); - } - } else { - renderScene(currentRenderList, scene, camera); - } + } - // + removePass( pass ) { - if (_currentRenderTarget !== null) { - // resolve multisample renderbuffers to a single-sample texture if necessary + const index = this.passes.indexOf( pass ); - textures.updateMultisampleRenderTarget(_currentRenderTarget); + if ( index !== - 1 ) { - // Generate mipmap if we're using any kind of mipmap filtering + this.passes.splice( index, 1 ); - textures.updateRenderTargetMipmap(_currentRenderTarget); } - // + } - if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); + isLastEnabledPass( passIndex ) { - // _gl.finish(); + for ( let i = passIndex + 1; i < this.passes.length; i ++ ) { - bindingStates.resetDefaultState(); - _currentMaterialId = -1; - _currentCamera = null; - renderStateStack.pop(); - if (renderStateStack.length > 0) { - currentRenderState = renderStateStack[renderStateStack.length - 1]; - } else { - currentRenderState = null; - } - renderListStack.pop(); - if (renderListStack.length > 0) { - currentRenderList = renderListStack[renderListStack.length - 1]; - } else { - currentRenderList = null; - } - }; - function projectObject(object, camera, groupOrder, sortObjects) { - if (object.visible === false) return; - const visible = object.layers.test(camera.layers); - if (visible) { - if (object.isGroup) { - groupOrder = object.renderOrder; - } else if (object.isLOD) { - if (object.autoUpdate === true) object.update(camera); - } else if (object.isLight) { - currentRenderState.pushLight(object); - if (object.castShadow) { - currentRenderState.pushShadow(object); - } - } else if (object.isSprite) { - if (!object.frustumCulled || _frustum.intersectsSprite(object)) { - if (sortObjects) { - _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix); - } - const geometry = objects.update(object); - const material = object.material; - if (material.visible) { - currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null); - } - } - } else if (object.isMesh || object.isLine || object.isPoints) { - if (object.isSkinnedMesh) { - // update skeleton only once in a frame + if ( this.passes[ i ].enabled ) { + + return false; - if (object.skeleton.frame !== info.render.frame) { - object.skeleton.update(); - object.skeleton.frame = info.render.frame; - } - } - if (!object.frustumCulled || _frustum.intersectsObject(object)) { - if (sortObjects) { - _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix); - } - const geometry = objects.update(object); - const material = object.material; - if (Array.isArray(material)) { - const groups = geometry.groups; - for (let i = 0, l = groups.length; i < l; i++) { - const group = groups[i]; - const groupMaterial = material[group.materialIndex]; - if (groupMaterial && groupMaterial.visible) { - currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group); - } - } - } else if (material.visible) { - currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null); - } - } } - } - const children = object.children; - for (let i = 0, l = children.length; i < l; i++) { - projectObject(children[i], camera, groupOrder, sortObjects); - } - } - function renderScene(currentRenderList, scene, camera, viewport) { - const opaqueObjects = currentRenderList.opaque; - const transmissiveObjects = currentRenderList.transmissive; - const transparentObjects = currentRenderList.transparent; - currentRenderState.setupLightsView(camera); - if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera); - if (viewport) state.viewport(_currentViewport.copy(viewport)); - if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera); - if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera); - if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); - - // Ensure depth buffer writing is enabled so it can be cleared on next render - - state.buffers.depth.setTest(true); - state.buffers.depth.setMask(true); - state.buffers.color.setMask(true); - state.setPolygonOffset(false); - } - function renderTransmissionPass(opaqueObjects, scene, camera) { - const isWebGL2 = capabilities.isWebGL2; - if (_transmissionRenderTarget === null) { - _transmissionRenderTarget = new WebGLRenderTarget(1, 1, { - generateMipmaps: true, - type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType, - minFilter: LinearMipmapLinearFilter, - samples: isWebGL2 && _antialias === true ? 4 : 0 - }); - } - _this.getDrawingBufferSize(_vector2); - if (isWebGL2) { - _transmissionRenderTarget.setSize(_vector2.x, _vector2.y); - } else { - _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y)); + } - // + return true; - const currentRenderTarget = _this.getRenderTarget(); - _this.setRenderTarget(_transmissionRenderTarget); - _this.clear(); - - // Turn off the features which can affect the frag color for opaque objects pass. - // Otherwise they are applied twice in opaque objects pass and transmission objects pass. - const currentToneMapping = _this.toneMapping; - _this.toneMapping = NoToneMapping; - renderObjects(opaqueObjects, scene, camera); - _this.toneMapping = currentToneMapping; - textures.updateMultisampleRenderTarget(_transmissionRenderTarget); - textures.updateRenderTargetMipmap(_transmissionRenderTarget); - _this.setRenderTarget(currentRenderTarget); - } - function renderObjects(renderList, scene, camera) { - const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; - for (let i = 0, l = renderList.length; i < l; i++) { - const renderItem = renderList[i]; - const object = renderItem.object; - const geometry = renderItem.geometry; - const material = overrideMaterial === null ? renderItem.material : overrideMaterial; - const group = renderItem.group; - if (object.layers.test(camera.layers)) { - renderObject(object, scene, camera, geometry, material, group); - } - } } - function renderObject(object, scene, camera, geometry, material, group) { - object.onBeforeRender(_this, scene, camera, geometry, material, group); - object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); - object.normalMatrix.getNormalMatrix(object.modelViewMatrix); - material.onBeforeRender(_this, scene, camera, geometry, object, group); - if (material.transparent === true && material.side === DoubleSide) { - material.side = BackSide; - material.needsUpdate = true; - _this.renderBufferDirect(camera, scene, geometry, material, object, group); - material.side = FrontSide; - material.needsUpdate = true; - _this.renderBufferDirect(camera, scene, geometry, material, object, group); - material.side = DoubleSide; - } else { - _this.renderBufferDirect(camera, scene, geometry, material, object, group); - } - object.onAfterRender(_this, scene, camera, geometry, material, group); - } - function getProgram(material, scene, object) { - if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - const materialProperties = properties.get(material); - const lights = currentRenderState.state.lights; - const shadowsArray = currentRenderState.state.shadowsArray; - const lightsStateVersion = lights.state.version; - const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object); - const programCacheKey = programCache.getProgramCacheKey(parameters); - let programs = materialProperties.programs; + render( deltaTime ) { - // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + // deltaTime value is in seconds - materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; - materialProperties.fog = scene.fog; - materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); - if (programs === undefined) { - // new material + if ( deltaTime === undefined ) { - material.addEventListener('dispose', onMaterialDispose); - programs = new Map(); - materialProperties.programs = programs; - } - let program = programs.get(programCacheKey); - if (program !== undefined) { - // early out if program and light state is identical + deltaTime = this.clock.getDelta(); - if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { - updateCommonMaterialProperties(material, parameters); - return program; - } - } else { - parameters.uniforms = programCache.getUniforms(material); - material.onBuild(object, parameters, _this); - material.onBeforeCompile(parameters, _this); - program = programCache.acquireProgram(parameters, programCacheKey); - programs.set(programCacheKey, program); - materialProperties.uniforms = parameters.uniforms; - } - const uniforms = materialProperties.uniforms; - if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { - uniforms.clippingPlanes = clipping.uniform; - } - updateCommonMaterialProperties(material, parameters); - - // store the light setup it was created for - - materialProperties.needsLights = materialNeedsLights(material); - materialProperties.lightsStateVersion = lightsStateVersion; - if (materialProperties.needsLights) { - // wire up the material to this renderer's lighting state - - uniforms.ambientLightColor.value = lights.state.ambient; - uniforms.lightProbe.value = lights.state.probe; - uniforms.directionalLights.value = lights.state.directional; - uniforms.directionalLightShadows.value = lights.state.directionalShadow; - uniforms.spotLights.value = lights.state.spot; - uniforms.spotLightShadows.value = lights.state.spotShadow; - uniforms.rectAreaLights.value = lights.state.rectArea; - uniforms.ltc_1.value = lights.state.rectAreaLTC1; - uniforms.ltc_2.value = lights.state.rectAreaLTC2; - uniforms.pointLights.value = lights.state.point; - uniforms.pointLightShadows.value = lights.state.pointShadow; - uniforms.hemisphereLights.value = lights.state.hemi; - uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; - uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; - uniforms.spotShadowMap.value = lights.state.spotShadowMap; - uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; - uniforms.spotLightMap.value = lights.state.spotLightMap; - uniforms.pointShadowMap.value = lights.state.pointShadowMap; - uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; - // TODO (abelnation): add area lights shadow info to uniforms - } - - const progUniforms = program.getUniforms(); - const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms); - materialProperties.currentProgram = program; - materialProperties.uniformsList = uniformsList; - return program; - } - function updateCommonMaterialProperties(material, parameters) { - const materialProperties = properties.get(material); - materialProperties.outputEncoding = parameters.outputEncoding; - materialProperties.instancing = parameters.instancing; - materialProperties.skinning = parameters.skinning; - materialProperties.morphTargets = parameters.morphTargets; - materialProperties.morphNormals = parameters.morphNormals; - materialProperties.morphColors = parameters.morphColors; - materialProperties.morphTargetsCount = parameters.morphTargetsCount; - materialProperties.numClippingPlanes = parameters.numClippingPlanes; - materialProperties.numIntersection = parameters.numClipIntersection; - materialProperties.vertexAlphas = parameters.vertexAlphas; - materialProperties.vertexTangents = parameters.vertexTangents; - materialProperties.toneMapping = parameters.toneMapping; - } - function setProgram(camera, scene, geometry, material, object) { - if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - - textures.resetTextureUnits(); - const fog = scene.fog; - const environment = material.isMeshStandardMaterial ? scene.environment : null; - const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding; - const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); - const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; - const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent; - const morphTargets = !!geometry.morphAttributes.position; - const morphNormals = !!geometry.morphAttributes.normal; - const morphColors = !!geometry.morphAttributes.color; - const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; - const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; - const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; - const materialProperties = properties.get(material); - const lights = currentRenderState.state.lights; - if (_clippingEnabled === true) { - if (_localClippingEnabled === true || camera !== _currentCamera) { - const useCache = camera === _currentCamera && material.id === _currentMaterialId; - - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - clipping.setState(material, camera, useCache); - } } - // - - let needsProgramChange = false; - if (material.version === materialProperties.__version) { - if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { - needsProgramChange = true; - } else if (materialProperties.outputEncoding !== encoding) { - needsProgramChange = true; - } else if (object.isInstancedMesh && materialProperties.instancing === false) { - needsProgramChange = true; - } else if (!object.isInstancedMesh && materialProperties.instancing === true) { - needsProgramChange = true; - } else if (object.isSkinnedMesh && materialProperties.skinning === false) { - needsProgramChange = true; - } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { - needsProgramChange = true; - } else if (materialProperties.envMap !== envMap) { - needsProgramChange = true; - } else if (material.fog === true && materialProperties.fog !== fog) { - needsProgramChange = true; - } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { - needsProgramChange = true; - } else if (materialProperties.vertexAlphas !== vertexAlphas) { - needsProgramChange = true; - } else if (materialProperties.vertexTangents !== vertexTangents) { - needsProgramChange = true; - } else if (materialProperties.morphTargets !== morphTargets) { - needsProgramChange = true; - } else if (materialProperties.morphNormals !== morphNormals) { - needsProgramChange = true; - } else if (materialProperties.morphColors !== morphColors) { - needsProgramChange = true; - } else if (materialProperties.toneMapping !== toneMapping) { - needsProgramChange = true; - } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) { - needsProgramChange = true; - } - } else { - needsProgramChange = true; - materialProperties.__version = material.version; - } + const currentRenderTarget = this.renderer.getRenderTarget(); - // + let maskActive = false; - let program = materialProperties.currentProgram; - if (needsProgramChange === true) { - program = getProgram(material, scene, object); - } - let refreshProgram = false; - let refreshMaterial = false; - let refreshLights = false; - const p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.uniforms; - if (state.useProgram(program.program)) { - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; - } - if (material.id !== _currentMaterialId) { - _currentMaterialId = material.id; - refreshMaterial = true; - } - if (refreshProgram || _currentCamera !== camera) { - p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix); - if (capabilities.logarithmicDepthBuffer) { - p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2)); - } - if (_currentCamera !== camera) { - _currentCamera = camera; + for ( let i = 0, il = this.passes.length; i < il; i ++ ) { - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + const pass = this.passes[ i ]; - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done - } + if ( pass.enabled === false ) continue; - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + pass.renderToScreen = ( this.renderToScreen && this.isLastEnabledPass( i ) ); + pass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive ); - if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) { - const uCamPos = p_uniforms.map.cameraPosition; - if (uCamPos !== undefined) { - uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld)); - } - } - if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { - p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true); - } - if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) { - p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse); - } - } + if ( pass.needsSwap ) { - // skinning and morph target uniforms must be set even if material didn't change - // auto-setting of texture unit for bone and morph texture must go before other textures - // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + if ( maskActive ) { - if (object.isSkinnedMesh) { - p_uniforms.setOptional(_gl, object, 'bindMatrix'); - p_uniforms.setOptional(_gl, object, 'bindMatrixInverse'); - const skeleton = object.skeleton; - if (skeleton) { - if (capabilities.floatVertexTextures) { - if (skeleton.boneTexture === null) skeleton.computeBoneTexture(); - p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures); - p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize); - } else { - console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.'); - } - } - } - const morphAttributes = geometry.morphAttributes; - if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) { - morphtargets.update(object, geometry, material, program); - } - if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { - materialProperties.receiveShadow = object.receiveShadow; - p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow); - } + const context = this.renderer.getContext(); + const stencil = this.renderer.state.buffers.stencil; - // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + //context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff ); + stencil.setFunc( context.NOTEQUAL, 1, 0xffffffff ); - if (material.isMeshGouraudMaterial && material.envMap !== null) { - m_uniforms.envMap.value = envMap; - m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; - } - if (refreshMaterial) { - p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure); - if (materialProperties.needsLights) { - // the current material requires lighting info + this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime ); - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + //context.stencilFunc( context.EQUAL, 1, 0xffffffff ); + stencil.setFunc( context.EQUAL, 1, 0xffffffff ); - markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); - } + } - // refresh uniforms common to several materials + this.swapBuffers(); - if (fog && material.fog === true) { - materials.refreshFogUniforms(m_uniforms, fog); } - materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget); - WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures); - } - if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { - WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures); - material.uniformsNeedUpdate = false; - } - if (material.isSpriteMaterial) { - p_uniforms.setValue(_gl, 'center', object.center); - } - // common matrices + if ( MaskPass !== undefined ) { - p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix); - p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix); - p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld); + if ( pass instanceof MaskPass ) { - // UBOs + maskActive = true; - if (material.isShaderMaterial || material.isRawShaderMaterial) { - const groups = material.uniformsGroups; - for (let i = 0, l = groups.length; i < l; i++) { - if (capabilities.isWebGL2) { - const group = groups[i]; - uniformsGroups.update(group, program); - uniformsGroups.bind(group, program); - } else { - console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.'); - } - } - } - return program; - } + } else if ( pass instanceof ClearMaskPass ) { - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + maskActive = false; - function markUniformsLightsNeedsUpdate(uniforms, value) { - uniforms.ambientLightColor.needsUpdate = value; - uniforms.lightProbe.needsUpdate = value; - uniforms.directionalLights.needsUpdate = value; - uniforms.directionalLightShadows.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.pointLightShadows.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.spotLightShadows.needsUpdate = value; - uniforms.rectAreaLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; - } - function materialNeedsLights(material) { - return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; - } - this.getActiveCubeFace = function () { - return _currentActiveCubeFace; - }; - this.getActiveMipmapLevel = function () { - return _currentActiveMipmapLevel; - }; - this.getRenderTarget = function () { - return _currentRenderTarget; - }; - this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) { - properties.get(renderTarget.texture).__webglTexture = colorTexture; - properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; - const renderTargetProperties = properties.get(renderTarget); - renderTargetProperties.__hasExternalTextures = true; - if (renderTargetProperties.__hasExternalTextures) { - renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - if (!renderTargetProperties.__autoAllocateDepthBuffer) { - // The multisample_render_to_texture extension doesn't work properly if there - // are midframe flushes and an external depth buffer. Disable use of the extension. - if (extensions.has('WEBGL_multisampled_render_to_texture') === true) { - console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided'); - renderTargetProperties.__useRenderToTexture = false; } + } - } - }; - this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) { - const renderTargetProperties = properties.get(renderTarget); - renderTargetProperties.__webglFramebuffer = defaultFramebuffer; - renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; - }; - this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { - _currentRenderTarget = renderTarget; - _currentActiveCubeFace = activeCubeFace; - _currentActiveMipmapLevel = activeMipmapLevel; - let useDefaultFramebuffer = true; - let framebuffer = null; - let isCube = false; - let isRenderTarget3D = false; - if (renderTarget) { - const renderTargetProperties = properties.get(renderTarget); - if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { - // We need to make sure to rebind the framebuffer. - state.bindFramebuffer(_gl.FRAMEBUFFER, null); - useDefaultFramebuffer = false; - } else if (renderTargetProperties.__webglFramebuffer === undefined) { - textures.setupRenderTarget(renderTarget); - } else if (renderTargetProperties.__hasExternalTextures) { - // Color and depth texture must be rebound in order for the swapchain to update. - textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); - } - const texture = renderTarget.texture; - if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { - isRenderTarget3D = true; - } - const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; - if (renderTarget.isWebGLCubeRenderTarget) { - framebuffer = __webglFramebuffer[activeCubeFace]; - isCube = true; - } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { - framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; - } else { - framebuffer = __webglFramebuffer; - } - _currentViewport.copy(renderTarget.viewport); - _currentScissor.copy(renderTarget.scissor); - _currentScissorTest = renderTarget.scissorTest; - } else { - _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); - _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); - _currentScissorTest = _scissorTest; - } - const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) { - state.drawBuffers(renderTarget, framebuffer); - } - state.viewport(_currentViewport); - state.scissor(_currentScissor); - state.setScissorTest(_currentScissorTest); - if (isCube) { - const textureProperties = properties.get(renderTarget.texture); - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); - } else if (isRenderTarget3D) { - const textureProperties = properties.get(renderTarget.texture); - const layer = activeCubeFace || 0; - _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer); - } - _currentMaterialId = -1; // reset current material to ensure correct uniform bindings - }; - this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) { - if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { - console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.'); - return; - } - let framebuffer = properties.get(renderTarget).__webglFramebuffer; - if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { - framebuffer = framebuffer[activeCubeFaceIndex]; } - if (framebuffer) { - state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - try { - const texture = renderTarget.texture; - const textureFormat = texture.format; - const textureType = texture.type; - if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { - console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.'); - return; - } - const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float')); - if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && - // Edge and Chrome Mac < 52 (#9513) - !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && - // Chrome Mac >= 52 and Firefox - !halfFloatSupportedByExt) { - console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.'); - return; - } - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + this.renderer.setRenderTarget( currentRenderTarget ); - if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) { - _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer); - } - } finally { - // restore framebuffer of current render target if necessary + } - const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; - state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - } - } - }; - this.copyFramebufferToTexture = function (position, texture, level = 0) { - const levelScale = Math.pow(2, -level); - const width = Math.floor(texture.image.width * levelScale); - const height = Math.floor(texture.image.height * levelScale); - textures.setTexture2D(texture, 0); - _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height); - state.unbindTexture(); - }; - this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) { - const width = srcTexture.image.width; - const height = srcTexture.image.height; - const glFormat = utils.convert(dstTexture.format); - const glType = utils.convert(dstTexture.type); - textures.setTexture2D(dstTexture, 0); - - // As another texture upload may have changed pixelStorei - // parameters, make sure they are correct for the dstTexture - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); - _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); - _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); - if (srcTexture.isDataTexture) { - _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data); - } else { - if (srcTexture.isCompressedTexture) { - _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data); - } else { - _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image); - } - } + reset( renderTarget ) { - // Generate mipmaps only when copying level 0 - if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D); - state.unbindTexture(); - }; - this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) { - if (_this.isWebGL1Renderer) { - console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.'); - return; - } - const width = sourceBox.max.x - sourceBox.min.x + 1; - const height = sourceBox.max.y - sourceBox.min.y + 1; - const depth = sourceBox.max.z - sourceBox.min.z + 1; - const glFormat = utils.convert(dstTexture.format); - const glType = utils.convert(dstTexture.type); - let glTarget; - if (dstTexture.isData3DTexture) { - textures.setTexture3D(dstTexture, 0); - glTarget = _gl.TEXTURE_3D; - } else if (dstTexture.isDataArrayTexture) { - textures.setTexture2DArray(dstTexture, 0); - glTarget = _gl.TEXTURE_2D_ARRAY; - } else { - console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.'); - return; - } - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); - _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); - _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); - const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); - const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); - const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); - const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); - const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); - const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image; - _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); - _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); - _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x); - _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y); - _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z); - if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { - _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data); - } else { - if (srcTexture.isCompressedArrayTexture) { - console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.'); - _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data); - } else { - _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image); - } - } - _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen); - _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight); - _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels); - _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows); - _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); + if ( renderTarget === undefined ) { - // Generate mipmaps only when copying level 0 - if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget); - state.unbindTexture(); - }; - this.initTexture = function (texture) { - if (texture.isCubeTexture) { - textures.setTextureCube(texture, 0); - } else if (texture.isData3DTexture) { - textures.setTexture3D(texture, 0); - } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { - textures.setTexture2DArray(texture, 0); - } else { - textures.setTexture2D(texture, 0); - } - state.unbindTexture(); - }; - this.resetState = function () { - _currentActiveCubeFace = 0; - _currentActiveMipmapLevel = 0; - _currentRenderTarget = null; - state.reset(); - bindingStates.reset(); - }; - if (typeof __THREE_DEVTOOLS__ !== 'undefined') { - __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', { - detail: this - })); - } -} + const size = this.renderer.getSize( new Vector2() ); + this._pixelRatio = this.renderer.getPixelRatio(); + this._width = size.width; + this._height = size.height; -class Fog { - constructor(color, near = 1, far = 1000) { - this.isFog = true; - this.name = ''; - this.color = new Color$1(color); - this.near = near; - this.far = far; - } - clone() { - return new Fog(this.color, this.near, this.far); - } - toJSON( /* meta */ - ) { - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; - } -} + renderTarget = this.renderTarget1.clone(); + renderTarget.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); -class Scene extends Object3D { - constructor() { - super(); - this.isScene = true; - this.type = 'Scene'; - this.background = null; - this.environment = null; - this.fog = null; - this.backgroundBlurriness = 0; - this.overrideMaterial = null; - if (typeof __THREE_DEVTOOLS__ !== 'undefined') { - __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', { - detail: this - })); } - } - copy(source, recursive) { - super.copy(source, recursive); - if (source.background !== null) this.background = source.background.clone(); - if (source.environment !== null) this.environment = source.environment.clone(); - if (source.fog !== null) this.fog = source.fog.clone(); - this.backgroundBlurriness = source.backgroundBlurriness; - if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone(); - this.matrixAutoUpdate = source.matrixAutoUpdate; - return this; - } - toJSON(meta) { - const data = super.toJSON(meta); - if (this.fog !== null) data.object.fog = this.fog.toJSON(); - if (this.backgroundBlurriness > 0) data.backgroundBlurriness = this.backgroundBlurriness; - return data; - } - // @deprecated + this.renderTarget1.dispose(); + this.renderTarget2.dispose(); + this.renderTarget1 = renderTarget; + this.renderTarget2 = renderTarget.clone(); - get autoUpdate() { - console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.'); - return this.matrixWorldAutoUpdate; - } - set autoUpdate(value) { - console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.'); - this.matrixWorldAutoUpdate = value; - } -} + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; -class LineBasicMaterial extends Material { - constructor(parameters) { - super(); - this.isLineBasicMaterial = true; - this.type = 'LineBasicMaterial'; - this.color = new Color$1(0xffffff); - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; - this.fog = true; - this.setValues(parameters); } - copy(source) { - super.copy(source); - this.color.copy(source.color); - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; - this.fog = source.fog; - return this; - } -} -const _start$1 = /*@__PURE__*/new Vector3(); -const _end$1 = /*@__PURE__*/new Vector3(); -const _inverseMatrix$1 = /*@__PURE__*/new Matrix4(); -const _ray$1 = /*@__PURE__*/new Ray(); -const _sphere$1 = /*@__PURE__*/new Sphere(); -class Line extends Object3D { - constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) { - super(); - this.isLine = true; - this.type = 'Line'; - this.geometry = geometry; - this.material = material; - this.updateMorphTargets(); - } - copy(source, recursive) { - super.copy(source, recursive); - this.material = source.material; - this.geometry = source.geometry; - return this; - } - computeLineDistances() { - const geometry = this.geometry; + setSize( width, height ) { - // we assume non-indexed geometry + this._width = width; + this._height = height; - if (geometry.index === null) { - const positionAttribute = geometry.attributes.position; - const lineDistances = [0]; - for (let i = 1, l = positionAttribute.count; i < l; i++) { - _start$1.fromBufferAttribute(positionAttribute, i - 1); - _end$1.fromBufferAttribute(positionAttribute, i); - lineDistances[i] = lineDistances[i - 1]; - lineDistances[i] += _start$1.distanceTo(_end$1); - } - geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1)); - } else { - console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.'); - } - return this; - } - raycast(raycaster, intersects) { - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Line.threshold; - const drawRange = geometry.drawRange; + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; - // Checking boundingSphere distance to ray + this.renderTarget1.setSize( effectiveWidth, effectiveHeight ); + this.renderTarget2.setSize( effectiveWidth, effectiveHeight ); - if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); - _sphere$1.copy(geometry.boundingSphere); - _sphere$1.applyMatrix4(matrixWorld); - _sphere$1.radius += threshold; - if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; + for ( let i = 0; i < this.passes.length; i ++ ) { - // + this.passes[ i ].setSize( effectiveWidth, effectiveHeight ); - _inverseMatrix$1.copy(matrixWorld).invert(); - _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); - const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); - const localThresholdSq = localThreshold * localThreshold; - const vStart = new Vector3(); - const vEnd = new Vector3(); - const interSegment = new Vector3(); - const interRay = new Vector3(); - const step = this.isLineSegments ? 2 : 1; - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - if (index !== null) { - const start = Math.max(0, drawRange.start); - const end = Math.min(index.count, drawRange.start + drawRange.count); - for (let i = start, l = end - 1; i < l; i += step) { - const a = index.getX(i); - const b = index.getX(i + 1); - vStart.fromBufferAttribute(positionAttribute, a); - vEnd.fromBufferAttribute(positionAttribute, b); - const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); - if (distSq > localThresholdSq) continue; - interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation - - const distance = raycaster.ray.origin.distanceTo(interRay); - if (distance < raycaster.near || distance > raycaster.far) continue; - intersects.push({ - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4(this.matrixWorld), - index: i, - face: null, - faceIndex: null, - object: this - }); - } - } else { - const start = Math.max(0, drawRange.start); - const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); - for (let i = start, l = end - 1; i < l; i += step) { - vStart.fromBufferAttribute(positionAttribute, i); - vEnd.fromBufferAttribute(positionAttribute, i + 1); - const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); - if (distSq > localThresholdSq) continue; - interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation - - const distance = raycaster.ray.origin.distanceTo(interRay); - if (distance < raycaster.near || distance > raycaster.far) continue; - intersects.push({ - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4(this.matrixWorld), - index: i, - face: null, - faceIndex: null, - object: this - }); - } - } - } - updateMorphTargets() { - const geometry = this.geometry; - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys(morphAttributes); - if (keys.length > 0) { - const morphAttribute = morphAttributes[keys[0]]; - if (morphAttribute !== undefined) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; - for (let m = 0, ml = morphAttribute.length; m < ml; m++) { - const name = morphAttribute[m].name || String(m); - this.morphTargetInfluences.push(0); - this.morphTargetDictionary[name] = m; - } - } } - } -} -const _start = /*@__PURE__*/new Vector3(); -const _end = /*@__PURE__*/new Vector3(); -class LineSegments extends Line { - constructor(geometry, material) { - super(geometry, material); - this.isLineSegments = true; - this.type = 'LineSegments'; } - computeLineDistances() { - const geometry = this.geometry; - // we assume non-indexed geometry + setPixelRatio( pixelRatio ) { - if (geometry.index === null) { - const positionAttribute = geometry.attributes.position; - const lineDistances = []; - for (let i = 0, l = positionAttribute.count; i < l; i += 2) { - _start.fromBufferAttribute(positionAttribute, i); - _end.fromBufferAttribute(positionAttribute, i + 1); - lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; - lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); - } - geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1)); - } else { - console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.'); - } - return this; - } -} + this._pixelRatio = pixelRatio; -class PointsMaterial extends Material { - constructor(parameters) { - super(); - this.isPointsMaterial = true; - this.type = 'PointsMaterial'; - this.color = new Color$1(0xffffff); - this.map = null; - this.alphaMap = null; - this.size = 1; - this.sizeAttenuation = true; - this.fog = true; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.color.copy(source.color); - this.map = source.map; - this.alphaMap = source.alphaMap; - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; - this.fog = source.fog; - return this; - } -} + this.setSize( this._width, this._height ); -const _inverseMatrix = /*@__PURE__*/new Matrix4(); -const _ray = /*@__PURE__*/new Ray(); -const _sphere = /*@__PURE__*/new Sphere(); -const _position = /*@__PURE__*/new Vector3(); -class Points extends Object3D { - constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) { - super(); - this.isPoints = true; - this.type = 'Points'; - this.geometry = geometry; - this.material = material; - this.updateMorphTargets(); - } - copy(source, recursive) { - super.copy(source, recursive); - this.material = source.material; - this.geometry = source.geometry; - return this; } - raycast(raycaster, intersects) { - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Points.threshold; - const drawRange = geometry.drawRange; - // Checking boundingSphere distance to ray + dispose() { - if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); - _sphere.copy(geometry.boundingSphere); - _sphere.applyMatrix4(matrixWorld); - _sphere.radius += threshold; - if (raycaster.ray.intersectsSphere(_sphere) === false) return; + this.renderTarget1.dispose(); + this.renderTarget2.dispose(); - // + this.copyPass.dispose(); - _inverseMatrix.copy(matrixWorld).invert(); - _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); - const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); - const localThresholdSq = localThreshold * localThreshold; - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; - if (index !== null) { - const start = Math.max(0, drawRange.start); - const end = Math.min(index.count, drawRange.start + drawRange.count); - for (let i = start, il = end; i < il; i++) { - const a = index.getX(i); - _position.fromBufferAttribute(positionAttribute, a); - testPoint(_position, a, localThresholdSq, matrixWorld, raycaster, intersects, this); - } - } else { - const start = Math.max(0, drawRange.start); - const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); - for (let i = start, l = end; i < l; i++) { - _position.fromBufferAttribute(positionAttribute, i); - testPoint(_position, i, localThresholdSq, matrixWorld, raycaster, intersects, this); - } - } - } - updateMorphTargets() { - const geometry = this.geometry; - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys(morphAttributes); - if (keys.length > 0) { - const morphAttribute = morphAttributes[keys[0]]; - if (morphAttribute !== undefined) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; - for (let m = 0, ml = morphAttribute.length; m < ml; m++) { - const name = morphAttribute[m].name || String(m); - this.morphTargetInfluences.push(0); - this.morphTargetDictionary[name] = m; - } - } - } - } -} -function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) { - const rayPointDistanceSq = _ray.distanceSqToPoint(point); - if (rayPointDistanceSq < localThresholdSq) { - const intersectPoint = new Vector3(); - _ray.closestPointToPoint(point, intersectPoint); - intersectPoint.applyMatrix4(matrixWorld); - const distance = raycaster.ray.origin.distanceTo(intersectPoint); - if (distance < raycaster.near || distance > raycaster.far) return; - intersects.push({ - distance: distance, - distanceToRay: Math.sqrt(rayPointDistanceSq), - point: intersectPoint, - index: index, - face: null, - object: object - }); } -} -class DataTexture extends Texture { - constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) { - super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); - this.isDataTexture = true; - this.image = { - data: data, - width: width, - height: height - }; - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; - } } -class CanvasTexture extends Texture { - constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { - super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); - this.isCanvasTexture = true; - this.needsUpdate = true; - } -} +class RenderPass extends Pass { -/** - * Extensible curve object. - * - * Some common of curve methods: - * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) - * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following curves inherit from THREE.Curve: - * - * -- 2D curves -- - * THREE.ArcCurve - * THREE.CubicBezierCurve - * THREE.EllipseCurve - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.SplineCurve - * - * -- 3D curves -- - * THREE.CatmullRomCurve3 - * THREE.CubicBezierCurve3 - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * - * A series of curves can be represented as a THREE.CurvePath. - * - **/ + constructor( scene, camera, overrideMaterial, clearColor, clearAlpha ) { -class Curve { - constructor() { - this.type = 'Curve'; - this.arcLengthDivisions = 200; - } + super(); - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + this.scene = scene; + this.camera = camera; - getPoint( /* t, optionalTarget */ - ) { - console.warn('THREE.Curve: .getPoint() not implemented.'); - return null; - } + this.overrideMaterial = overrideMaterial; - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + this.clearColor = clearColor; + this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0; + + this.clear = true; + this.clearDepth = false; + this.needsSwap = false; + this._oldClearColor = new Color(); - getPointAt(u, optionalTarget) { - const t = this.getUtoTmapping(u); - return this.getPoint(t, optionalTarget); } - // Get sequence of points using getPoint( t ) + render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) { - getPoints(divisions = 5) { - const points = []; - for (let d = 0; d <= divisions; d++) { - points.push(this.getPoint(d / divisions)); - } - return points; - } + const oldAutoClear = renderer.autoClear; + renderer.autoClear = false; - // Get sequence of points using getPointAt( u ) + let oldClearAlpha, oldOverrideMaterial; + + if ( this.overrideMaterial !== undefined ) { + + oldOverrideMaterial = this.scene.overrideMaterial; + + this.scene.overrideMaterial = this.overrideMaterial; - getSpacedPoints(divisions = 5) { - const points = []; - for (let d = 0; d <= divisions; d++) { - points.push(this.getPointAt(d / divisions)); } - return points; - } - // Get total curve arc length + if ( this.clearColor ) { - getLength() { - const lengths = this.getLengths(); - return lengths[lengths.length - 1]; - } + renderer.getClearColor( this._oldClearColor ); + oldClearAlpha = renderer.getClearAlpha(); - // Get list of cumulative segment lengths + renderer.setClearColor( this.clearColor, this.clearAlpha ); - getLengths(divisions = this.arcLengthDivisions) { - if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { - return this.cacheArcLengths; - } - this.needsUpdate = false; - const cache = []; - let current, - last = this.getPoint(0); - let sum = 0; - cache.push(0); - for (let p = 1; p <= divisions; p++) { - current = this.getPoint(p / divisions); - sum += current.distanceTo(last); - cache.push(sum); - last = current; } - this.cacheArcLengths = cache; - return cache; // { sums: cache, sum: sum }; Sum is in the last element. - } - - updateArcLengths() { - this.needsUpdate = true; - this.getLengths(); - } - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + if ( this.clearDepth ) { - getUtoTmapping(u, distance) { - const arcLengths = this.getLengths(); - let i = 0; - const il = arcLengths.length; - let targetArcLength; // The targeted u distance value to get + renderer.clearDepth(); - if (distance) { - targetArcLength = distance; - } else { - targetArcLength = u * arcLengths[il - 1]; } - // binary search for the index with largest value smaller than target u distance + renderer.setRenderTarget( this.renderToScreen ? null : readBuffer ); + + // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600 + if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + renderer.render( this.scene, this.camera ); - let low = 0, - high = il - 1, - comparison; - while (low <= high) { - i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + if ( this.clearColor ) { - comparison = arcLengths[i] - targetArcLength; - if (comparison < 0) { - low = i + 1; - } else if (comparison > 0) { - high = i - 1; - } else { - high = i; - break; + renderer.setClearColor( this._oldClearColor, oldClearAlpha ); - // DONE - } } - i = high; - if (arcLengths[i] === targetArcLength) { - return i / (il - 1); + if ( this.overrideMaterial !== undefined ) { + + this.scene.overrideMaterial = oldOverrideMaterial; + } - // we could get finer grain at lengths, or use simple interpolation between two points + renderer.autoClear = oldAutoClear; - const lengthBefore = arcLengths[i]; - const lengthAfter = arcLengths[i + 1]; - const segmentLength = lengthAfter - lengthBefore; + } - // determine where we are between the 'before' and 'after' points +} - const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; +/** + * Luminosity + * http://en.wikipedia.org/wiki/Luminosity + */ - // add that fractional amount to t +const LuminosityHighPassShader = { - const t = (i + segmentFraction) / (il - 1); - return t; - } + shaderID: 'luminosityHighPass', - // Returns a unit vector tangent at t - // In case any sub curve does not implement its tangent derivation, - // 2 points a small delta apart will be used to find its gradient - // which seems to give a reasonable approximation + uniforms: { - getTangent(t, optionalTarget) { - const delta = 0.0001; - let t1 = t - delta; - let t2 = t + delta; + 'tDiffuse': { value: null }, + 'luminosityThreshold': { value: 1.0 }, + 'smoothWidth': { value: 1.0 }, + 'defaultColor': { value: new Color( 0x000000 ) }, + 'defaultOpacity': { value: 0.0 } - // Capping in case of danger + }, - if (t1 < 0) t1 = 0; - if (t2 > 1) t2 = 1; - const pt1 = this.getPoint(t1); - const pt2 = this.getPoint(t2); - const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3()); - tangent.copy(pt2).sub(pt1).normalize(); - return tangent; - } - getTangentAt(u, optionalTarget) { - const t = this.getUtoTmapping(u); - return this.getTangent(t, optionalTarget); - } - computeFrenetFrames(segments, closed) { - // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + vertexShader: /* glsl */` - const normal = new Vector3(); - const tangents = []; - const normals = []; - const binormals = []; - const vec = new Vector3(); - const mat = new Matrix4(); + varying vec2 vUv; - // compute the tangent vectors for each segment on the curve + void main() { - for (let i = 0; i <= segments; i++) { - const u = i / segments; - tangents[i] = this.getTangentAt(u, new Vector3()); - } + vUv = uv; - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the minimum tangent xyz component + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - normals[0] = new Vector3(); - binormals[0] = new Vector3(); - let min = Number.MAX_VALUE; - const tx = Math.abs(tangents[0].x); - const ty = Math.abs(tangents[0].y); - const tz = Math.abs(tangents[0].z); - if (tx <= min) { - min = tx; - normal.set(1, 0, 0); - } - if (ty <= min) { - min = ty; - normal.set(0, 1, 0); - } - if (tz <= min) { - normal.set(0, 0, 1); - } - vec.crossVectors(tangents[0], normal).normalize(); - normals[0].crossVectors(tangents[0], vec); - binormals[0].crossVectors(tangents[0], normals[0]); + }`, - // compute the slowly-varying normal and binormal vectors for each segment on the curve + fragmentShader: /* glsl */` - for (let i = 1; i <= segments; i++) { - normals[i] = normals[i - 1].clone(); - binormals[i] = binormals[i - 1].clone(); - vec.crossVectors(tangents[i - 1], tangents[i]); - if (vec.length() > Number.EPSILON) { - vec.normalize(); - const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors + uniform sampler2D tDiffuse; + uniform vec3 defaultColor; + uniform float defaultOpacity; + uniform float luminosityThreshold; + uniform float smoothWidth; - normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); - } - binormals[i].crossVectors(tangents[i], normals[i]); - } + varying vec2 vUv; - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + void main() { - if (closed === true) { - let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1)); - theta /= segments; - if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { - theta = -theta; - } - for (let i = 1; i <= segments; i++) { - // twist a little... - normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); - binormals[i].crossVectors(tangents[i], normals[i]); - } - } - return { - tangents: tangents, - normals: normals, - binormals: binormals - }; - } - clone() { - return new this.constructor().copy(this); - } - copy(source) { - this.arcLengthDivisions = source.arcLengthDivisions; - return this; - } - toJSON() { - const data = { - metadata: { - version: 4.5, - type: 'Curve', - generator: 'Curve.toJSON' - } - }; - data.arcLengthDivisions = this.arcLengthDivisions; - data.type = this.type; - return data; - } - fromJSON(json) { - this.arcLengthDivisions = json.arcLengthDivisions; - return this; - } -} + vec4 texel = texture2D( tDiffuse, vUv ); -class EllipseCurve extends Curve { - constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { - super(); - this.isEllipseCurve = true; - this.type = 'EllipseCurve'; - this.aX = aX; - this.aY = aY; - this.xRadius = xRadius; - this.yRadius = yRadius; - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; - this.aClockwise = aClockwise; - this.aRotation = aRotation; - } - getPoint(t, optionalTarget) { - const point = optionalTarget || new Vector2(); - const twoPi = Math.PI * 2; - let deltaAngle = this.aEndAngle - this.aStartAngle; - const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + vec3 luma = vec3( 0.299, 0.587, 0.114 ); - // ensures that deltaAngle is 0 .. 2 PI - while (deltaAngle < 0) deltaAngle += twoPi; - while (deltaAngle > twoPi) deltaAngle -= twoPi; - if (deltaAngle < Number.EPSILON) { - if (samePoints) { - deltaAngle = 0; - } else { - deltaAngle = twoPi; - } - } - if (this.aClockwise === true && !samePoints) { - if (deltaAngle === twoPi) { - deltaAngle = -twoPi; - } else { - deltaAngle = deltaAngle - twoPi; - } - } - const angle = this.aStartAngle + t * deltaAngle; - let x = this.aX + this.xRadius * Math.cos(angle); - let y = this.aY + this.yRadius * Math.sin(angle); - if (this.aRotation !== 0) { - const cos = Math.cos(this.aRotation); - const sin = Math.sin(this.aRotation); - const tx = x - this.aX; - const ty = y - this.aY; + float v = dot( texel.xyz, luma ); - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; - } - return point.set(x, y); - } - copy(source) { - super.copy(source); - this.aX = source.aX; - this.aY = source.aY; - this.xRadius = source.xRadius; - this.yRadius = source.yRadius; - this.aStartAngle = source.aStartAngle; - this.aEndAngle = source.aEndAngle; - this.aClockwise = source.aClockwise; - this.aRotation = source.aRotation; - return this; - } - toJSON() { - const data = super.toJSON(); - data.aX = this.aX; - data.aY = this.aY; - data.xRadius = this.xRadius; - data.yRadius = this.yRadius; - data.aStartAngle = this.aStartAngle; - data.aEndAngle = this.aEndAngle; - data.aClockwise = this.aClockwise; - data.aRotation = this.aRotation; - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.aX = json.aX; - this.aY = json.aY; - this.xRadius = json.xRadius; - this.yRadius = json.yRadius; - this.aStartAngle = json.aStartAngle; - this.aEndAngle = json.aEndAngle; - this.aClockwise = json.aClockwise; - this.aRotation = json.aRotation; - return this; - } -} + vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); -class ArcCurve extends EllipseCurve { - constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { - super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); - this.isArcCurve = true; - this.type = 'ArcCurve'; - } -} + float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); + + gl_FragColor = mix( outputColor, texel, alpha ); + + }` + +}; /** - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a + * mip map chain of bloom textures and blurs them with different radii. Because + * of the weighted combination of mips, and because larger blurs are done on + * higher mips, this effect provides good quality and performance. * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 + * Reference: + * - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/ */ +class UnrealBloomPass extends Pass { -/* -Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM - -This CubicPoly class could be used for reusing some variables and calculations, -but for three.js curve use, it could be possible inlined and flatten into a single function call -which can be placed in CurveUtils. -*/ - -function CubicPoly() { - let c0 = 0, - c1 = 0, - c2 = 0, - c3 = 0; + constructor( resolution, strength, radius, threshold ) { - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - function init(x0, x1, t0, t1) { - c0 = x0; - c1 = t0; - c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; - c3 = 2 * x0 - 2 * x1 + t0 + t1; - } - return { - initCatmullRom: function (x0, x1, x2, x3, tension) { - init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); - }, - initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) { - // compute tangents when parameterized in [t1,t2] - let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; - let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + super(); - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; - init(x1, x2, t1, t2); - }, - calc: function (t) { - const t2 = t * t; - const t3 = t2 * t; - return c0 + c1 * t + c2 * t2 + c3 * t3; - } - }; -} + this.strength = ( strength !== undefined ) ? strength : 1; + this.radius = radius; + this.threshold = threshold; + this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 ); -// + // create color only once here, reuse it later inside the render function + this.clearColor = new Color( 0, 0, 0 ); -const tmp = /*@__PURE__*/new Vector3(); -const px = /*@__PURE__*/new CubicPoly(); -const py = /*@__PURE__*/new CubicPoly(); -const pz = /*@__PURE__*/new CubicPoly(); -class CatmullRomCurve3 extends Curve { - constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) { - super(); - this.isCatmullRomCurve3 = true; - this.type = 'CatmullRomCurve3'; - this.points = points; - this.closed = closed; - this.curveType = curveType; - this.tension = tension; - } - getPoint(t, optionalTarget = new Vector3()) { - const point = optionalTarget; - const points = this.points; - const l = points.length; - const p = (l - (this.closed ? 0 : 1)) * t; - let intPoint = Math.floor(p); - let weight = p - intPoint; - if (this.closed) { - intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; - } else if (weight === 0 && intPoint === l - 1) { - intPoint = l - 2; - weight = 1; - } - let p0, p3; // 4 points (p1 & p2 defined below) + // render targets + this.renderTargetsHorizontal = []; + this.renderTargetsVertical = []; + this.nMips = 5; + let resx = Math.round( this.resolution.x / 2 ); + let resy = Math.round( this.resolution.y / 2 ); - if (this.closed || intPoint > 0) { - p0 = points[(intPoint - 1) % l]; - } else { - // extrapolate first point - tmp.subVectors(points[0], points[1]).add(points[0]); - p0 = tmp; - } - const p1 = points[intPoint % l]; - const p2 = points[(intPoint + 1) % l]; - if (this.closed || intPoint + 2 < l) { - p3 = points[(intPoint + 2) % l]; - } else { - // extrapolate last point - tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); - p3 = tmp; - } - if (this.curveType === 'centripetal' || this.curveType === 'chordal') { - // init Centripetal / Chordal Catmull-Rom - const pow = this.curveType === 'chordal' ? 0.5 : 0.25; - let dt0 = Math.pow(p0.distanceToSquared(p1), pow); - let dt1 = Math.pow(p1.distanceToSquared(p2), pow); - let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + this.renderTargetBright = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } ); + this.renderTargetBright.texture.name = 'UnrealBloomPass.bright'; + this.renderTargetBright.texture.generateMipmaps = false; - // safety check for repeated points - if (dt1 < 1e-4) dt1 = 1.0; - if (dt0 < 1e-4) dt0 = dt1; - if (dt2 < 1e-4) dt2 = dt1; - px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); - py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); - pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); - } else if (this.curveType === 'catmullrom') { - px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); - py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); - pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); - } - point.set(px.calc(weight), py.calc(weight), pz.calc(weight)); - return point; - } - copy(source) { - super.copy(source); - this.points = []; - for (let i = 0, l = source.points.length; i < l; i++) { - const point = source.points[i]; - this.points.push(point.clone()); - } - this.closed = source.closed; - this.curveType = source.curveType; - this.tension = source.tension; - return this; - } - toJSON() { - const data = super.toJSON(); - data.points = []; - for (let i = 0, l = this.points.length; i < l; i++) { - const point = this.points[i]; - data.points.push(point.toArray()); - } - data.closed = this.closed; - data.curveType = this.curveType; - data.tension = this.tension; - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.points = []; - for (let i = 0, l = json.points.length; i < l; i++) { - const point = json.points[i]; - this.points.push(new Vector3().fromArray(point)); - } - this.closed = json.closed; - this.curveType = json.curveType; - this.tension = json.tension; - return this; - } -} + for ( let i = 0; i < this.nMips; i ++ ) { -/** - * Bezier Curves formulas obtained from - * https://en.wikipedia.org/wiki/B%C3%A9zier_curve - */ + const renderTargetHorizonal = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } ); -function CatmullRom(t, p0, p1, p2, p3) { - const v0 = (p2 - p0) * 0.5; - const v1 = (p3 - p1) * 0.5; - const t2 = t * t; - const t3 = t * t2; - return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; -} + renderTargetHorizonal.texture.name = 'UnrealBloomPass.h' + i; + renderTargetHorizonal.texture.generateMipmaps = false; -// + this.renderTargetsHorizontal.push( renderTargetHorizonal ); -function QuadraticBezierP0(t, p) { - const k = 1 - t; - return k * k * p; -} -function QuadraticBezierP1(t, p) { - return 2 * (1 - t) * t * p; -} -function QuadraticBezierP2(t, p) { - return t * t * p; -} -function QuadraticBezier(t, p0, p1, p2) { - return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); -} + const renderTargetVertical = new WebGLRenderTarget( resx, resy, { type: HalfFloatType } ); -// + renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i; + renderTargetVertical.texture.generateMipmaps = false; -function CubicBezierP0(t, p) { - const k = 1 - t; - return k * k * k * p; -} -function CubicBezierP1(t, p) { - const k = 1 - t; - return 3 * k * k * t * p; -} -function CubicBezierP2(t, p) { - return 3 * (1 - t) * t * t * p; -} -function CubicBezierP3(t, p) { - return t * t * t * p; -} -function CubicBezier(t, p0, p1, p2, p3) { - return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); -} + this.renderTargetsVertical.push( renderTargetVertical ); -class CubicBezierCurve extends Curve { - constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) { - super(); - this.isCubicBezierCurve = true; - this.type = 'CubicBezierCurve'; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - } - getPoint(t, optionalTarget = new Vector2()) { - const point = optionalTarget; - const v0 = this.v0, - v1 = this.v1, - v2 = this.v2, - v3 = this.v3; - point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y)); - return point; - } - copy(source) { - super.copy(source); - this.v0.copy(source.v0); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - this.v3.copy(source.v3); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v0.fromArray(json.v0); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - this.v3.fromArray(json.v3); - return this; - } -} + resx = Math.round( resx / 2 ); -class CubicBezierCurve3 extends Curve { - constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) { - super(); - this.isCubicBezierCurve3 = true; - this.type = 'CubicBezierCurve3'; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - } - getPoint(t, optionalTarget = new Vector3()) { - const point = optionalTarget; - const v0 = this.v0, - v1 = this.v1, - v2 = this.v2, - v3 = this.v3; - point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z)); - return point; - } - copy(source) { - super.copy(source); - this.v0.copy(source.v0); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - this.v3.copy(source.v3); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v0.fromArray(json.v0); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - this.v3.fromArray(json.v3); - return this; - } -} + resy = Math.round( resy / 2 ); -class LineCurve extends Curve { - constructor(v1 = new Vector2(), v2 = new Vector2()) { - super(); - this.isLineCurve = true; - this.type = 'LineCurve'; - this.v1 = v1; - this.v2 = v2; - } - getPoint(t, optionalTarget = new Vector2()) { - const point = optionalTarget; - if (t === 1) { - point.copy(this.v2); - } else { - point.copy(this.v2).sub(this.v1); - point.multiplyScalar(t).add(this.v1); } - return point; - } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt(u, optionalTarget) { - return this.getPoint(u, optionalTarget); - } - getTangent(t, optionalTarget) { - const tangent = optionalTarget || new Vector2(); - tangent.copy(this.v2).sub(this.v1).normalize(); - return tangent; - } - copy(source) { - super.copy(source); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - return this; - } -} + // luminosity high pass material -class LineCurve3 extends Curve { - constructor(v1 = new Vector3(), v2 = new Vector3()) { - super(); - this.isLineCurve3 = true; - this.type = 'LineCurve3'; - this.v1 = v1; - this.v2 = v2; - } - getPoint(t, optionalTarget = new Vector3()) { - const point = optionalTarget; - if (t === 1) { - point.copy(this.v2); - } else { - point.copy(this.v2).sub(this.v1); - point.multiplyScalar(t).add(this.v1); - } - return point; - } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt(u, optionalTarget) { - return this.getPoint(u, optionalTarget); - } - copy(source) { - super.copy(source); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - return this; - } -} + const highPassShader = LuminosityHighPassShader; + this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms ); -class QuadraticBezierCurve extends Curve { - constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) { - super(); - this.isQuadraticBezierCurve = true; - this.type = 'QuadraticBezierCurve'; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - } - getPoint(t, optionalTarget = new Vector2()) { - const point = optionalTarget; - const v0 = this.v0, - v1 = this.v1, - v2 = this.v2; - point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y)); - return point; - } - copy(source) { - super.copy(source); - this.v0.copy(source.v0); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v0.fromArray(json.v0); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - return this; - } -} + this.highPassUniforms[ 'luminosityThreshold' ].value = threshold; + this.highPassUniforms[ 'smoothWidth' ].value = 0.01; -class QuadraticBezierCurve3 extends Curve { - constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) { - super(); - this.isQuadraticBezierCurve3 = true; - this.type = 'QuadraticBezierCurve3'; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - } - getPoint(t, optionalTarget = new Vector3()) { - const point = optionalTarget; - const v0 = this.v0, - v1 = this.v1, - v2 = this.v2; - point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z)); - return point; - } - copy(source) { - super.copy(source); - this.v0.copy(source.v0); - this.v1.copy(source.v1); - this.v2.copy(source.v2); - return this; - } - toJSON() { - const data = super.toJSON(); - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.v0.fromArray(json.v0); - this.v1.fromArray(json.v1); - this.v2.fromArray(json.v2); - return this; - } -} + this.materialHighPassFilter = new ShaderMaterial( { + uniforms: this.highPassUniforms, + vertexShader: highPassShader.vertexShader, + fragmentShader: highPassShader.fragmentShader + } ); + + // gaussian blur materials + + this.separableBlurMaterials = []; + const kernelSizeArray = [ 3, 5, 7, 9, 11 ]; + resx = Math.round( this.resolution.x / 2 ); + resy = Math.round( this.resolution.y / 2 ); + + for ( let i = 0; i < this.nMips; i ++ ) { + + this.separableBlurMaterials.push( this.getSeperableBlurMaterial( kernelSizeArray[ i ] ) ); + + this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy ); + + resx = Math.round( resx / 2 ); + + resy = Math.round( resy / 2 ); -class SplineCurve extends Curve { - constructor(points = []) { - super(); - this.isSplineCurve = true; - this.type = 'SplineCurve'; - this.points = points; - } - getPoint(t, optionalTarget = new Vector2()) { - const point = optionalTarget; - const points = this.points; - const p = (points.length - 1) * t; - const intPoint = Math.floor(p); - const weight = p - intPoint; - const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; - const p1 = points[intPoint]; - const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; - const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; - point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); - return point; - } - copy(source) { - super.copy(source); - this.points = []; - for (let i = 0, l = source.points.length; i < l; i++) { - const point = source.points[i]; - this.points.push(point.clone()); } - return this; + + // composite material + + this.compositeMaterial = this.getCompositeMaterial( this.nMips ); + this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture; + this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture; + this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture; + this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture; + this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture; + this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength; + this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1; + + const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ]; + this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors; + this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ]; + this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors; + + // blend material + + const copyShader = CopyShader; + + this.copyUniforms = UniformsUtils.clone( copyShader.uniforms ); + + this.blendMaterial = new ShaderMaterial( { + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.enabled = true; + this.needsSwap = false; + + this._oldClearColor = new Color(); + this.oldClearAlpha = 1; + + this.basic = new MeshBasicMaterial(); + + this.fsQuad = new FullScreenQuad( null ); + } - toJSON() { - const data = super.toJSON(); - data.points = []; - for (let i = 0, l = this.points.length; i < l; i++) { - const point = this.points[i]; - data.points.push(point.toArray()); + + dispose() { + + for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) { + + this.renderTargetsHorizontal[ i ].dispose(); + } - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.points = []; - for (let i = 0, l = json.points.length; i < l; i++) { - const point = json.points[i]; - this.points.push(new Vector2().fromArray(point)); + + for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) { + + this.renderTargetsVertical[ i ].dispose(); + } - return this; - } -} -var Curves = /*#__PURE__*/Object.freeze({ - __proto__: null, - ArcCurve: ArcCurve, - CatmullRomCurve3: CatmullRomCurve3, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - EllipseCurve: EllipseCurve, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - SplineCurve: SplineCurve -}); + this.renderTargetBright.dispose(); -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + // -class CurvePath extends Curve { - constructor() { - super(); - this.type = 'CurvePath'; - this.curves = []; - this.autoClose = false; // Automatically closes the path - } + for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) { + + this.separableBlurMaterials[ i ].dispose(); - add(curve) { - this.curves.push(curve); - } - closePath() { - // Add a line curve if start and end of lines are not connected - const startPoint = this.curves[0].getPoint(0); - const endPoint = this.curves[this.curves.length - 1].getPoint(1); - if (!startPoint.equals(endPoint)) { - this.curves.push(new LineCurve(endPoint, startPoint)); } + + this.compositeMaterial.dispose(); + this.blendMaterial.dispose(); + this.basic.dispose(); + + // + + this.fsQuad.dispose(); + } - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + setSize( width, height ) { - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + let resx = Math.round( width / 2 ); + let resy = Math.round( height / 2 ); - getPoint(t, optionalTarget) { - const d = t * this.getLength(); - const curveLengths = this.getCurveLengths(); - let i = 0; + this.renderTargetBright.setSize( resx, resy ); - // To think about boundaries points. + for ( let i = 0; i < this.nMips; i ++ ) { + + this.renderTargetsHorizontal[ i ].setSize( resx, resy ); + this.renderTargetsVertical[ i ].setSize( resx, resy ); + + this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy ); + + resx = Math.round( resx / 2 ); + resy = Math.round( resy / 2 ); - while (i < curveLengths.length) { - if (curveLengths[i] >= d) { - const diff = curveLengths[i] - d; - const curve = this.curves[i]; - const segmentLength = curve.getLength(); - const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - return curve.getPointAt(u, optionalTarget); - } - i++; } - return null; - // loop where sum != 0, sum > d , sum+1 1 && !points[points.length - 1].equals(points[0])) { - points.push(points[0]); + + // 1. Extract Bright Areas + + this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture; + this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold; + this.fsQuad.material = this.materialHighPassFilter; + + renderer.setRenderTarget( this.renderTargetBright ); + renderer.clear(); + this.fsQuad.render( renderer ); + + // 2. Blur All the mips progressively + + let inputRenderTarget = this.renderTargetBright; + + for ( let i = 0; i < this.nMips; i ++ ) { + + this.fsQuad.material = this.separableBlurMaterials[ i ]; + + this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture; + this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX; + renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] ); + renderer.clear(); + this.fsQuad.render( renderer ); + + this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture; + this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY; + renderer.setRenderTarget( this.renderTargetsVertical[ i ] ); + renderer.clear(); + this.fsQuad.render( renderer ); + + inputRenderTarget = this.renderTargetsVertical[ i ]; + } - return points; - } - copy(source) { - super.copy(source); - this.curves = []; - for (let i = 0, l = source.curves.length; i < l; i++) { - const curve = source.curves[i]; - this.curves.push(curve.clone()); + + // Composite All the mips + + this.fsQuad.material = this.compositeMaterial; + this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength; + this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius; + this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors; + + renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] ); + renderer.clear(); + this.fsQuad.render( renderer ); + + // Blend it additively over the input texture + + this.fsQuad.material = this.blendMaterial; + this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture; + + if ( maskActive ) renderer.state.buffers.stencil.setTest( true ); + + if ( this.renderToScreen ) { + + renderer.setRenderTarget( null ); + this.fsQuad.render( renderer ); + + } else { + + renderer.setRenderTarget( readBuffer ); + this.fsQuad.render( renderer ); + } - this.autoClose = source.autoClose; - return this; + + // Restore renderer settings + + renderer.setClearColor( this._oldClearColor, this.oldClearAlpha ); + renderer.autoClear = oldAutoClear; + } - toJSON() { - const data = super.toJSON(); - data.autoClose = this.autoClose; - data.curves = []; - for (let i = 0, l = this.curves.length; i < l; i++) { - const curve = this.curves[i]; - data.curves.push(curve.toJSON()); + + getSeperableBlurMaterial( kernelRadius ) { + + const coefficients = []; + + for ( let i = 0; i < kernelRadius; i ++ ) { + + coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius ); + } - return data; + + return new ShaderMaterial( { + + defines: { + 'KERNEL_RADIUS': kernelRadius + }, + + uniforms: { + 'colorTexture': { value: null }, + 'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size + 'direction': { value: new Vector2( 0.5, 0.5 ) }, + 'gaussianCoefficients': { value: coefficients } // precomputed Gaussian coefficients + }, + + vertexShader: + `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + + fragmentShader: + `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 invSize; + uniform vec2 direction; + uniform float gaussianCoefficients[KERNEL_RADIUS]; + + void main() { + float weightSum = gaussianCoefficients[0]; + vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; + for( int i = 1; i < KERNEL_RADIUS; i ++ ) { + float x = float(i); + float w = gaussianCoefficients[i]; + vec2 uvOffset = direction * invSize * x; + vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; + vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; + diffuseSum += (sample1 + sample2) * w; + weightSum += 2.0 * w; + } + gl_FragColor = vec4(diffuseSum/weightSum, 1.0); + }` + } ); + } - fromJSON(json) { - super.fromJSON(json); - this.autoClose = json.autoClose; - this.curves = []; - for (let i = 0, l = json.curves.length; i < l; i++) { - const curve = json.curves[i]; - this.curves.push(new Curves[curve.type]().fromJSON(curve)); - } - return this; + + getCompositeMaterial( nMips ) { + + return new ShaderMaterial( { + + defines: { + 'NUM_MIPS': nMips + }, + + uniforms: { + 'blurTexture1': { value: null }, + 'blurTexture2': { value: null }, + 'blurTexture3': { value: null }, + 'blurTexture4': { value: null }, + 'blurTexture5': { value: null }, + 'bloomStrength': { value: 1.0 }, + 'bloomFactors': { value: null }, + 'bloomTintColors': { value: null }, + 'bloomRadius': { value: 0.0 } + }, + + vertexShader: + `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + + fragmentShader: + `varying vec2 vUv; + uniform sampler2D blurTexture1; + uniform sampler2D blurTexture2; + uniform sampler2D blurTexture3; + uniform sampler2D blurTexture4; + uniform sampler2D blurTexture5; + uniform float bloomStrength; + uniform float bloomRadius; + uniform float bloomFactors[NUM_MIPS]; + uniform vec3 bloomTintColors[NUM_MIPS]; + + float lerpBloomFactor(const in float factor) { + float mirrorFactor = 1.2 - factor; + return mix(factor, mirrorFactor, bloomRadius); + } + + void main() { + gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); + }` + } ); + } + } -class Path extends CurvePath { - constructor(points) { - super(); - this.type = 'Path'; - this.currentPoint = new Vector2(); - if (points) { - this.setFromPoints(points); - } - } - setFromPoints(points) { - this.moveTo(points[0].x, points[0].y); - for (let i = 1, l = points.length; i < l; i++) { - this.lineTo(points[i].x, points[i].y); - } - return this; - } - moveTo(x, y) { - this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying? +UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 ); +UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 ); + +class RenderableObject { + + constructor() { + + this.id = 0; + + this.object = null; + this.z = 0; + this.renderOrder = 0; - return this; - } - lineTo(x, y) { - const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); - this.curves.push(curve); - this.currentPoint.set(x, y); - return this; - } - quadraticCurveTo(aCPx, aCPy, aX, aY) { - const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY)); - this.curves.push(curve); - this.currentPoint.set(aX, aY); - return this; - } - bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { - const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY)); - this.curves.push(curve); - this.currentPoint.set(aX, aY); - return this; - } - splineThru(pts /*Array of Vector*/) { - const npts = [this.currentPoint.clone()].concat(pts); - const curve = new SplineCurve(npts); - this.curves.push(curve); - this.currentPoint.copy(pts[pts.length - 1]); - return this; - } - arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; - this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); - return this; - } - absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { - this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); - return this; - } - ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; - this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); - return this; - } - absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { - const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); - if (this.curves.length > 0) { - // if a previous curve is present, attempt to join - const firstPoint = curve.getPoint(0); - if (!firstPoint.equals(this.currentPoint)) { - this.lineTo(firstPoint.x, firstPoint.y); - } - } - this.curves.push(curve); - const lastPoint = curve.getPoint(1); - this.currentPoint.copy(lastPoint); - return this; } - copy(source) { - super.copy(source); - this.currentPoint.copy(source.currentPoint); - return this; + +} + +// + +class RenderableFace { + + constructor() { + + this.id = 0; + + this.v1 = new RenderableVertex(); + this.v2 = new RenderableVertex(); + this.v3 = new RenderableVertex(); + + this.normalModel = new Vector3(); + + this.vertexNormalsModel = [ new Vector3(), new Vector3(), new Vector3() ]; + this.vertexNormalsLength = 0; + + this.color = new Color(); + this.material = null; + this.uvs = [ new Vector2(), new Vector2(), new Vector2() ]; + + this.z = 0; + this.renderOrder = 0; + } - toJSON() { - const data = super.toJSON(); - data.currentPoint = this.currentPoint.toArray(); - return data; + +} + +// + +class RenderableVertex { + + constructor() { + + this.position = new Vector3(); + this.positionWorld = new Vector3(); + this.positionScreen = new Vector4(); + + this.visible = true; + } - fromJSON(json) { - super.fromJSON(json); - this.currentPoint.fromArray(json.currentPoint); - return this; + + copy( vertex ) { + + this.positionWorld.copy( vertex.positionWorld ); + this.positionScreen.copy( vertex.positionScreen ); + } + } -class CircleGeometry extends BufferGeometry { - constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) { - super(); - this.type = 'CircleGeometry'; - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; - segments = Math.max(3, segments); +// - // buffers +class RenderableLine { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + constructor() { - // helper variables + this.id = 0; - const vertex = new Vector3(); - const uv = new Vector2(); + this.v1 = new RenderableVertex(); + this.v2 = new RenderableVertex(); - // center point + this.vertexColors = [ new Color(), new Color() ]; + this.material = null; - vertices.push(0, 0, 0); - normals.push(0, 0, 1); - uvs.push(0.5, 0.5); - for (let s = 0, i = 3; s <= segments; s++, i += 3) { - const segment = thetaStart + s / segments * thetaLength; + this.z = 0; + this.renderOrder = 0; - // vertex + } - vertex.x = radius * Math.cos(segment); - vertex.y = radius * Math.sin(segment); - vertices.push(vertex.x, vertex.y, vertex.z); +} - // normal +// - normals.push(0, 0, 1); +class RenderableSprite { - // uvs + constructor() { - uv.x = (vertices[i] / radius + 1) / 2; - uv.y = (vertices[i + 1] / radius + 1) / 2; - uvs.push(uv.x, uv.y); - } + this.id = 0; - // indices + this.object = null; - for (let i = 1; i <= segments; i++) { - indices.push(i, i + 1, 0); - } + this.x = 0; + this.y = 0; + this.z = 0; - // build geometry + this.rotation = 0; + this.scale = new Vector2(); + + this.material = null; + this.renderOrder = 0; - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - } - static fromJSON(data) { - return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength); } + } -class CylinderGeometry extends BufferGeometry { - constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { - super(); - this.type = 'CylinderGeometry'; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; - const scope = this; - radialSegments = Math.floor(radialSegments); - heightSegments = Math.floor(heightSegments); +// - // buffers +class Projector { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + constructor() { - // helper variables + let _object, _objectCount, _objectPoolLength = 0, + _vertex, _vertexCount, _vertexPoolLength = 0, + _face, _faceCount, _facePoolLength = 0, + _line, _lineCount, _linePoolLength = 0, + _sprite, _spriteCount, _spritePoolLength = 0, + _modelMatrix; - let index = 0; - const indexArray = []; - const halfHeight = height / 2; - let groupStart = 0; + const - // generate geometry + _renderData = { objects: [], lights: [], elements: [] }, - generateTorso(); - if (openEnded === false) { - if (radiusTop > 0) generateCap(true); - if (radiusBottom > 0) generateCap(false); - } + _vector3 = new Vector3(), + _vector4 = new Vector4(), - // build geometry + _clipBox = new Box3( new Vector3( - 1, - 1, - 1 ), new Vector3( 1, 1, 1 ) ), + _boundingBox = new Box3(), + _points3 = new Array( 3 ), - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - function generateTorso() { - const normal = new Vector3(); - const vertex = new Vector3(); - let groupCount = 0; + _viewMatrix = new Matrix4(), + _viewProjectionMatrix = new Matrix4(), - // this will be used to calculate the normal - const slope = (radiusBottom - radiusTop) / height; + _modelViewProjectionMatrix = new Matrix4(), - // generate vertices, normals and uvs + _frustum = new Frustum(), + + _objectPool = [], _vertexPool = [], _facePool = [], _linePool = [], _spritePool = []; + + // - for (let y = 0; y <= heightSegments; y++) { - const indexRow = []; - const v = y / heightSegments; + function RenderList() { + + const normals = []; + const colors = []; + const uvs = []; - // calculate the radius of the current row + let object = null; - const radius = v * (radiusBottom - radiusTop) + radiusTop; - for (let x = 0; x <= radialSegments; x++) { - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); + const normalMatrix = new Matrix3(); - // vertex + function setObject( value ) { - vertex.x = radius * sinTheta; - vertex.y = -v * height + halfHeight; - vertex.z = radius * cosTheta; - vertices.push(vertex.x, vertex.y, vertex.z); + object = value; - // normal + normalMatrix.getNormalMatrix( object.matrixWorld ); - normal.set(sinTheta, slope, cosTheta).normalize(); - normals.push(normal.x, normal.y, normal.z); + normals.length = 0; + colors.length = 0; + uvs.length = 0; - // uv + } - uvs.push(u, 1 - v); + function projectVertex( vertex ) { - // save index of vertex in respective row + const position = vertex.position; + const positionWorld = vertex.positionWorld; + const positionScreen = vertex.positionScreen; - indexRow.push(index++); - } + positionWorld.copy( position ).applyMatrix4( _modelMatrix ); + positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix ); - // now save vertices of the row in our index array + const invW = 1 / positionScreen.w; + + positionScreen.x *= invW; + positionScreen.y *= invW; + positionScreen.z *= invW; + + vertex.visible = positionScreen.x >= - 1 && positionScreen.x <= 1 && + positionScreen.y >= - 1 && positionScreen.y <= 1 && + positionScreen.z >= - 1 && positionScreen.z <= 1; - indexArray.push(indexRow); } - // generate indices + function pushVertex( x, y, z ) { - for (let x = 0; x < radialSegments; x++) { - for (let y = 0; y < heightSegments; y++) { - // we use the index array to access the correct indices + _vertex = getNextVertexInPool(); + _vertex.position.set( x, y, z ); - const a = indexArray[y][x]; - const b = indexArray[y + 1][x]; - const c = indexArray[y + 1][x + 1]; - const d = indexArray[y][x + 1]; + projectVertex( _vertex ); - // faces + } - indices.push(a, b, d); - indices.push(b, c, d); + function pushNormal( x, y, z ) { - // update group counter + normals.push( x, y, z ); - groupCount += 6; - } } - // add a group to the geometry. this will ensure multi material support + function pushColor( r, g, b ) { - scope.addGroup(groupStart, groupCount, 0); + colors.push( r, g, b ); - // calculate new start value for groups + } - groupStart += groupCount; - } - function generateCap(top) { - // save the index of the first center vertex - const centerIndexStart = index; - const uv = new Vector2(); - const vertex = new Vector3(); - let groupCount = 0; - const radius = top === true ? radiusTop : radiusBottom; - const sign = top === true ? 1 : -1; + function pushUv( x, y ) { - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + uvs.push( x, y ); - for (let x = 1; x <= radialSegments; x++) { - // vertex + } - vertices.push(0, halfHeight * sign, 0); + function checkTriangleVisibility( v1, v2, v3 ) { - // normal + if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true; - normals.push(0, sign, 0); + _points3[ 0 ] = v1.positionScreen; + _points3[ 1 ] = v2.positionScreen; + _points3[ 2 ] = v3.positionScreen; - // uv + return _clipBox.intersectsBox( _boundingBox.setFromPoints( _points3 ) ); + + } - uvs.push(0.5, 0.5); + function checkBackfaceCulling( v1, v2, v3 ) { - // increase index + return ( ( v3.positionScreen.x - v1.positionScreen.x ) * + ( v2.positionScreen.y - v1.positionScreen.y ) - + ( v3.positionScreen.y - v1.positionScreen.y ) * + ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0; - index++; } - // save the index of the last center vertex - const centerIndexEnd = index; + function pushLine( a, b ) { + + const v1 = _vertexPool[ a ]; + const v2 = _vertexPool[ b ]; - // now we generate the surrounding vertices, normals and uvs + // Clip - for (let x = 0; x <= radialSegments; x++) { - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; - const cosTheta = Math.cos(theta); - const sinTheta = Math.sin(theta); + v1.positionScreen.copy( v1.position ).applyMatrix4( _modelViewProjectionMatrix ); + v2.positionScreen.copy( v2.position ).applyMatrix4( _modelViewProjectionMatrix ); - // vertex + if ( clipLine( v1.positionScreen, v2.positionScreen ) === true ) { + + // Perform the perspective divide + v1.positionScreen.multiplyScalar( 1 / v1.positionScreen.w ); + v2.positionScreen.multiplyScalar( 1 / v2.positionScreen.w ); + + _line = getNextLineInPool(); + _line.id = object.id; + _line.v1.copy( v1 ); + _line.v2.copy( v2 ); + _line.z = Math.max( v1.positionScreen.z, v2.positionScreen.z ); + _line.renderOrder = object.renderOrder; - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.push(vertex.x, vertex.y, vertex.z); + _line.material = object.material; - // normal + if ( object.material.vertexColors ) { - normals.push(0, sign, 0); + _line.vertexColors[ 0 ].fromArray( colors, a * 3 ); + _line.vertexColors[ 1 ].fromArray( colors, b * 3 ); - // uv + } - uv.x = cosTheta * 0.5 + 0.5; - uv.y = sinTheta * 0.5 * sign + 0.5; - uvs.push(uv.x, uv.y); + _renderData.elements.push( _line ); - // increase index + } - index++; } - // generate indices - - for (let x = 0; x < radialSegments; x++) { - const c = centerIndexStart + x; - const i = centerIndexEnd + x; - if (top === true) { - // face top + function pushTriangle( a, b, c, material ) { - indices.push(i, i + 1, c); - } else { - // face bottom + const v1 = _vertexPool[ a ]; + const v2 = _vertexPool[ b ]; + const v3 = _vertexPool[ c ]; - indices.push(i + 1, i, c); - } - groupCount += 3; - } + if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return; - // add a group to the geometry. this will ensure multi material support + if ( material.side === DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) { - scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + _face = getNextFaceInPool(); - // calculate new start value for groups + _face.id = object.id; + _face.v1.copy( v1 ); + _face.v2.copy( v2 ); + _face.v3.copy( v3 ); + _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3; + _face.renderOrder = object.renderOrder; - groupStart += groupCount; - } - } - static fromJSON(data) { - return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); - } -} + // face normal + _vector3.subVectors( v3.position, v2.position ); + _vector4.subVectors( v1.position, v2.position ); + _vector3.cross( _vector4 ); + _face.normalModel.copy( _vector3 ); + _face.normalModel.applyMatrix3( normalMatrix ).normalize(); -class PolyhedronGeometry extends BufferGeometry { - constructor(vertices = [], indices = [], radius = 1, detail = 0) { - super(); - this.type = 'PolyhedronGeometry'; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + for ( let i = 0; i < 3; i ++ ) { - // default buffer data + const normal = _face.vertexNormalsModel[ i ]; + normal.fromArray( normals, arguments[ i ] * 3 ); + normal.applyMatrix3( normalMatrix ).normalize(); - const vertexBuffer = []; - const uvBuffer = []; + const uv = _face.uvs[ i ]; + uv.fromArray( uvs, arguments[ i ] * 2 ); - // the subdivision creates the vertex buffer data + } - subdivide(detail); + _face.vertexNormalsLength = 3; - // all vertices should lie on a conceptual sphere with a given radius + _face.material = material; - applyRadius(radius); + if ( material.vertexColors ) { - // finally, create the uv data + _face.color.fromArray( colors, a * 3 ); - generateUVs(); + } - // build non-indexed geometry + _renderData.elements.push( _face ); - this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3)); - this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2)); - if (detail === 0) { - this.computeVertexNormals(); // flat normals - } else { - this.normalizeNormals(); // smooth normals - } + } - // helper functions + } - function subdivide(detail) { - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); + return { + setObject: setObject, + projectVertex: projectVertex, + checkTriangleVisibility: checkTriangleVisibility, + checkBackfaceCulling: checkBackfaceCulling, + pushVertex: pushVertex, + pushNormal: pushNormal, + pushColor: pushColor, + pushUv: pushUv, + pushLine: pushLine, + pushTriangle: pushTriangle + }; - // iterate over all faces and apply a subdivison with the given detail value + } - for (let i = 0; i < indices.length; i += 3) { - // get the vertices of the face + const renderList = new RenderList(); - getVertexByIndex(indices[i + 0], a); - getVertexByIndex(indices[i + 1], b); - getVertexByIndex(indices[i + 2], c); + function projectObject( object ) { - // perform subdivision + if ( object.visible === false ) return; - subdivideFace(a, b, c, detail); - } - } - function subdivideFace(a, b, c, detail) { - const cols = detail + 1; + if ( object.isLight ) { - // we use this multidimensional array as a data structure for creating the subdivision + _renderData.lights.push( object ); - const v = []; + } else if ( object.isMesh || object.isLine || object.isPoints ) { - // construct all of the vertices for this subdivision + if ( object.material.visible === false ) return; + if ( object.frustumCulled === true && _frustum.intersectsObject( object ) === false ) return; - for (let i = 0; i <= cols; i++) { - v[i] = []; - const aj = a.clone().lerp(c, i / cols); - const bj = b.clone().lerp(c, i / cols); - const rows = cols - i; - for (let j = 0; j <= rows; j++) { - if (j === 0 && i === cols) { - v[i][j] = aj; - } else { - v[i][j] = aj.clone().lerp(bj, j / rows); - } - } - } + addObject( object ); - // construct all of the faces + } else if ( object.isSprite ) { - for (let i = 0; i < cols; i++) { - for (let j = 0; j < 2 * (cols - i) - 1; j++) { - const k = Math.floor(j / 2); - if (j % 2 === 0) { - pushVertex(v[i][k + 1]); - pushVertex(v[i + 1][k]); - pushVertex(v[i][k]); - } else { - pushVertex(v[i][k + 1]); - pushVertex(v[i + 1][k + 1]); - pushVertex(v[i + 1][k]); - } - } - } - } - function applyRadius(radius) { - const vertex = new Vector3(); + if ( object.material.visible === false ) return; + if ( object.frustumCulled === true && _frustum.intersectsSprite( object ) === false ) return; - // iterate over the entire buffer and apply the radius to each vertex + addObject( object ); - for (let i = 0; i < vertexBuffer.length; i += 3) { - vertex.x = vertexBuffer[i + 0]; - vertex.y = vertexBuffer[i + 1]; - vertex.z = vertexBuffer[i + 2]; - vertex.normalize().multiplyScalar(radius); - vertexBuffer[i + 0] = vertex.x; - vertexBuffer[i + 1] = vertex.y; - vertexBuffer[i + 2] = vertex.z; - } - } - function generateUVs() { - const vertex = new Vector3(); - for (let i = 0; i < vertexBuffer.length; i += 3) { - vertex.x = vertexBuffer[i + 0]; - vertex.y = vertexBuffer[i + 1]; - vertex.z = vertexBuffer[i + 2]; - const u = azimuth(vertex) / 2 / Math.PI + 0.5; - const v = inclination(vertex) / Math.PI + 0.5; - uvBuffer.push(u, 1 - v); } - correctUVs(); - correctSeam(); - } - function correctSeam() { - // handle case when face straddles the seam, see #3269 - for (let i = 0; i < uvBuffer.length; i += 6) { - // uv data of a single face + const children = object.children; - const x0 = uvBuffer[i + 0]; - const x1 = uvBuffer[i + 2]; - const x2 = uvBuffer[i + 4]; - const max = Math.max(x0, x1, x2); - const min = Math.min(x0, x1, x2); + for ( let i = 0, l = children.length; i < l; i ++ ) { - // 0.9 is somewhat arbitrary + projectObject( children[ i ] ); - if (max > 0.9 && min < 0.1) { - if (x0 < 0.2) uvBuffer[i + 0] += 1; - if (x1 < 0.2) uvBuffer[i + 2] += 1; - if (x2 < 0.2) uvBuffer[i + 4] += 1; - } - } - } - function pushVertex(vertex) { - vertexBuffer.push(vertex.x, vertex.y, vertex.z); - } - function getVertexByIndex(index, vertex) { - const stride = index * 3; - vertex.x = vertices[stride + 0]; - vertex.y = vertices[stride + 1]; - vertex.z = vertices[stride + 2]; - } - function correctUVs() { - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); - const centroid = new Vector3(); - const uvA = new Vector2(); - const uvB = new Vector2(); - const uvC = new Vector2(); - for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) { - a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); - b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); - c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); - uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); - uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); - uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); - centroid.copy(a).add(b).add(c).divideScalar(3); - const azi = azimuth(centroid); - correctUV(uvA, j + 0, a, azi); - correctUV(uvB, j + 2, b, azi); - correctUV(uvC, j + 4, c, azi); } - } - function correctUV(uv, stride, vector, azimuth) { - if (azimuth < 0 && uv.x === 1) { - uvBuffer[stride] = uv.x - 1; - } - if (vector.x === 0 && vector.z === 0) { - uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5; - } - } - // Angle around the Y axis, counter-clockwise when looking from above. - - function azimuth(vector) { - return Math.atan2(vector.z, -vector.x); } - // Angle above the XZ plane. + function addObject( object ) { - function inclination(vector) { - return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); - } - } - static fromJSON(data) { - return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details); - } -} + _object = getNextObjectInPool(); + _object.id = object.id; + _object.object = object; -class Shape extends Path { - constructor(points) { - super(points); - this.uuid = generateUUID(); - this.type = 'Shape'; - this.holes = []; - } - getPointsHoles(divisions) { - const holesPts = []; - for (let i = 0, l = this.holes.length; i < l; i++) { - holesPts[i] = this.holes[i].getPoints(divisions); - } - return holesPts; - } + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyMatrix4( _viewProjectionMatrix ); + _object.z = _vector3.z; + _object.renderOrder = object.renderOrder; - // get points of shape and holes (keypoints based on segments parameter) + _renderData.objects.push( _object ); - extractPoints(divisions) { - return { - shape: this.getPoints(divisions), - holes: this.getPointsHoles(divisions) - }; - } - copy(source) { - super.copy(source); - this.holes = []; - for (let i = 0, l = source.holes.length; i < l; i++) { - const hole = source.holes[i]; - this.holes.push(hole.clone()); - } - return this; - } - toJSON() { - const data = super.toJSON(); - data.uuid = this.uuid; - data.holes = []; - for (let i = 0, l = this.holes.length; i < l; i++) { - const hole = this.holes[i]; - data.holes.push(hole.toJSON()); - } - return data; - } - fromJSON(json) { - super.fromJSON(json); - this.uuid = json.uuid; - this.holes = []; - for (let i = 0, l = json.holes.length; i < l; i++) { - const hole = json.holes[i]; - this.holes.push(new Path().fromJSON(hole)); } - return this; - } -} -/** - * Port from https://github.com/mapbox/earcut (v2.2.4) - */ + this.projectScene = function ( scene, camera, sortObjects, sortElements ) { -const Earcut = { - triangulate: function (data, holeIndices, dim = 2) { - const hasHoles = holeIndices && holeIndices.length; - const outerLen = hasHoles ? holeIndices[0] * dim : data.length; - let outerNode = linkedList(data, 0, outerLen, dim, true); - const triangles = []; - if (!outerNode || outerNode.next === outerNode.prev) return triangles; - let minX, minY, maxX, maxY, x, y, invSize; - if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + _faceCount = 0; + _lineCount = 0; + _spriteCount = 0; - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - for (let i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } + _renderData.elements.length = 0; - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max(maxX - minX, maxY - minY); - invSize = invSize !== 0 ? 32767 / invSize : 0; - } - earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); - return triangles; - } -}; + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList(data, start, end, dim, clockwise) { - let i, last; - if (clockwise === signedArea(data, start, end, dim) > 0) { - for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); - } else { - for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); - } - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - return last; -} + _viewMatrix.copy( camera.matrixWorldInverse ); + _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix ); -// eliminate colinear or duplicate points -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; - let p = start, - again; - do { - again = false; - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) break; - again = true; - } else { - p = p.next; - } - } while (again || p !== end); - return end; -} + _frustum.setFromProjectionMatrix( _viewProjectionMatrix ); -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) return; + // - // interlink polygon nodes in z-order - if (!pass && invSize) indexCurve(ear, minX, minY, invSize); - let stop = ear, - prev, - next; + _objectCount = 0; - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim | 0); - triangles.push(ear.i / dim | 0); - triangles.push(next.i / dim | 0); - removeNode(ear); + _renderData.objects.length = 0; + _renderData.lights.length = 0; - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; - continue; - } - ear = next; + projectObject( scene ); - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + if ( sortObjects === true ) { - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(filterPoints(ear), triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + _renderData.objects.sort( painterSort ); - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); } - break; - } - } -} -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar(ear) { - const a = ear.prev, - b = ear, - c = ear.next; - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + // - // now make sure we don't have other points inside the potential ear - const ax = a.x, - bx = b.x, - cx = c.x, - ay = a.y, - by = b.y, - cy = c.y; + const objects = _renderData.objects; - // triangle bbox; min & max are calculated like this for speed - const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, - y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, - x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, - y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; - let p = c.next; - while (p !== a) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.next; - } - return true; -} -function isEarHashed(ear, minX, minY, invSize) { - const a = ear.prev, - b = ear, - c = ear.next; - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + for ( let o = 0, ol = objects.length; o < ol; o ++ ) { - const ax = a.x, - bx = b.x, - cx = c.x, - ay = a.y, - by = b.y, - cy = c.y; + const object = objects[ o ].object; + const geometry = object.geometry; - // triangle bbox; min & max are calculated like this for speed - const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, - y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, - x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, - y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + renderList.setObject( object ); - // z-order range for the current triangle bbox; - const minZ = zOrder(x0, y0, minX, minY, invSize), - maxZ = zOrder(x1, y1, minX, minY, invSize); - let p = ear.prevZ, - n = ear.nextZ; + _modelMatrix = object.matrixWorld; - // look for points inside the triangle in both directions - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } + _vertexCount = 0; - // look for remaining points in decreasing z-order - while (p && p.z >= minZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - } + if ( object.isMesh ) { - // look for remaining points in increasing z-order - while (n && n.z <= maxZ) { - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - return true; -} + let material = object.material; -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections(start, triangles, dim) { - let p = start; - do { - const a = p.prev, - b = p.next.next; - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - triangles.push(a.i / dim | 0); - triangles.push(p.i / dim | 0); - triangles.push(b.i / dim | 0); + const isMultiMaterial = Array.isArray( material ); - // remove two nodes involved - removeNode(p); - removeNode(p.next); - p = start = b; - } - p = p.next; - } while (p !== start); - return filterPoints(p); -} + const attributes = geometry.attributes; + const groups = geometry.groups; -// try splitting polygon into two and triangulate them independently -function splitEarcut(start, triangles, dim, minX, minY, invSize) { - // look for a valid diagonal that divides the polygon into two - let a = start; - do { - let b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - let c = splitPolygon(a, b); + if ( attributes.position === undefined ) continue; - // filter colinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); + const positions = attributes.position.array; - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, invSize, 0); - earcutLinked(c, triangles, dim, minX, minY, invSize, 0); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); -} + for ( let i = 0, l = positions.length; i < l; i += 3 ) { -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles(data, holeIndices, outerNode, dim) { - const queue = []; - let i, len, start, end, list; - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) list.steiner = true; - queue.push(getLeftmost(list)); - } - queue.sort(compareX); + let x = positions[ i ]; + let y = positions[ i + 1 ]; + let z = positions[ i + 2 ]; - // process holes from left to right - for (i = 0; i < queue.length; i++) { - outerNode = eliminateHole(queue[i], outerNode); - } - return outerNode; -} -function compareX(a, b) { - return a.x - b.x; -} + const morphTargets = geometry.morphAttributes.position; -// find a bridge between vertices that connects hole with an outer ring and link it -function eliminateHole(hole, outerNode) { - const bridge = findHoleBridge(hole, outerNode); - if (!bridge) { - return outerNode; - } - const bridgeReverse = splitPolygon(bridge, hole); + if ( morphTargets !== undefined ) { - // filter collinear points around the cuts - filterPoints(bridgeReverse, bridgeReverse.next); - return filterPoints(bridge, bridge.next); -} + const morphTargetsRelative = geometry.morphTargetsRelative; + const morphInfluences = object.morphTargetInfluences; -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge(hole, outerNode) { - let p = outerNode, - qx = -Infinity, - m; - const hx = hole.x, - hy = hole.y; + for ( let t = 0, tl = morphTargets.length; t < tl; t ++ ) { - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - m = p.x < p.next.x ? p : p.next; - if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint - } - } + const influence = morphInfluences[ t ]; - p = p.next; - } while (p !== outerNode); - if (!m) return null; + if ( influence === 0 ) continue; - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point + const target = morphTargets[ t ]; - const stop = m, - mx = m.x, - my = m.y; - let tanMin = Infinity, - tan; - p = m; - do { - if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + if ( morphTargetsRelative ) { - if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { - m = p; - tanMin = tan; - } - } - p = p.next; - } while (p !== stop); - return m; -} + x += target.getX( i / 3 ) * influence; + y += target.getY( i / 3 ) * influence; + z += target.getZ( i / 3 ) * influence; -// whether sector in vertex m contains sector in vertex p in the same coordinates -function sectorContainsSector(m, p) { - return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; -} + } else { -// interlink polygon nodes in z-order -function indexCurve(start, minX, minY, invSize) { - let p = start; - do { - if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - p.prevZ.nextZ = null; - p.prevZ = null; - sortLinked(p); -} + x += ( target.getX( i / 3 ) - positions[ i ] ) * influence; + y += ( target.getY( i / 3 ) - positions[ i + 1 ] ) * influence; + z += ( target.getZ( i / 3 ) - positions[ i + 2 ] ) * influence; -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked(list) { - let i, - p, - q, - e, - tail, - numMerges, - pSize, - qSize, - inSize = 1; - do { - p = list; - list = null; - tail = null; - numMerges = 0; - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) break; - } - qSize = inSize; - while (pSize > 0 || qSize > 0 && q) { - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - if (tail) tail.nextZ = e;else list = e; - e.prevZ = tail; - tail = e; - } - p = q; - } - tail.nextZ = null; - inSize *= 2; - } while (numMerges > 1); - return list; -} + } -// z-order of a point given coords and inverse of the longer side of data bbox -function zOrder(x, y, minX, minY, invSize) { - // coords are transformed into non-negative 15-bit integer range - x = (x - minX) * invSize | 0; - y = (y - minY) * invSize | 0; - x = (x | x << 8) & 0x00FF00FF; - x = (x | x << 4) & 0x0F0F0F0F; - x = (x | x << 2) & 0x33333333; - x = (x | x << 1) & 0x55555555; - y = (y | y << 8) & 0x00FF00FF; - y = (y | y << 4) & 0x0F0F0F0F; - y = (y | y << 2) & 0x33333333; - y = (y | y << 1) & 0x55555555; - return x | y << 1; -} + } -// find the leftmost node of a polygon ring -function getLeftmost(start) { - let p = start, - leftmost = start; - do { - if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; - p = p.next; - } while (p !== start); - return leftmost; -} + } -// check if a point lies within a convex triangle -function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py); -} + renderList.pushVertex( x, y, z ); -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( - // dones't intersect other edges - locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( - // locally visible - area(a.prev, a, b.prev) || area(a, b.prev, b)) || - // does not create opposite-facing sectors - equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case -} + } -// signed area of a triangle -function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); -} + if ( attributes.normal !== undefined ) { -// check if two points are equal -function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; -} + const normals = attributes.normal.array; -// check if two segments intersect -function intersects(p1, q1, p2, q2) { - const o1 = sign(area(p1, q1, p2)); - const o2 = sign(area(p1, q1, q2)); - const o3 = sign(area(p2, q2, p1)); - const o4 = sign(area(p2, q2, q1)); - if (o1 !== o2 && o3 !== o4) return true; // general case - - if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 - if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 - if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 - if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + for ( let i = 0, l = normals.length; i < l; i += 3 ) { - return false; -} + renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ); -// for collinear points p, q, r, check if point q lies on segment pr -function onSegment(p, q, r) { - return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); -} -function sign(num) { - return num > 0 ? 1 : num < 0 ? -1 : 0; -} + } -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon(a, b) { - let p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; - p = p.next; - } while (p !== a); - return false; -} + } -// check if a polygon diagonal is locally inside the polygon -function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; -} + if ( attributes.color !== undefined ) { -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside(a, b) { - let p = a, - inside = false; - const px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside; - p = p.next; - } while (p !== a); - return inside; -} + const colors = attributes.color.array; -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon(a, b) { - const a2 = new Node$1(a.i, a.x, a.y), - b2 = new Node$1(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - a.next = b; - b.prev = a; - a2.next = an; - an.prev = a2; - b2.next = a2; - a2.prev = b2; - bp.next = b2; - b2.prev = bp; - return b2; -} + for ( let i = 0, l = colors.length; i < l; i += 3 ) { -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode(i, x, y, last) { - const p = new Node$1(i, x, y); - if (!last) { - p.prev = p; - p.next = p; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} -function Node$1(i, x, y) { - // vertex index in coordinates array - this.i = i; + renderList.pushColor( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ); - // vertex coordinates - this.x = x; - this.y = y; + } - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; + } - // z-order curve value - this.z = 0; + if ( attributes.uv !== undefined ) { - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; + const uvs = attributes.uv.array; - // indicates whether this is a steiner point - this.steiner = false; -} -function signedArea(data, start, end, dim) { - let sum = 0; - for (let i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; -} + for ( let i = 0, l = uvs.length; i < l; i += 2 ) { -class ShapeUtils { - // calculate area of the contour polygon + renderList.pushUv( uvs[ i ], uvs[ i + 1 ] ); - static area(contour) { - const n = contour.length; - let a = 0.0; - for (let p = n - 1, q = 0; q < n; p = q++) { - a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; - } - return a * 0.5; - } - static isClockWise(pts) { - return ShapeUtils.area(pts) < 0; - } - static triangulateShape(contour, holes) { - const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] - const holeIndices = []; // array of hole indices - const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + } - removeDupEndPts(contour); - addContour(vertices, contour); + } - // + if ( geometry.index !== null ) { - let holeIndex = contour.length; - holes.forEach(removeDupEndPts); - for (let i = 0; i < holes.length; i++) { - holeIndices.push(holeIndex); - holeIndex += holes[i].length; - addContour(vertices, holes[i]); - } + const indices = geometry.index.array; - // + if ( groups.length > 0 ) { - const triangles = Earcut.triangulate(vertices, holeIndices); + for ( let g = 0; g < groups.length; g ++ ) { - // + const group = groups[ g ]; - for (let i = 0; i < triangles.length; i += 3) { - faces.push(triangles.slice(i, i + 3)); - } - return faces; - } -} -function removeDupEndPts(points) { - const l = points.length; - if (l > 2 && points[l - 1].equals(points[0])) { - points.pop(); - } -} -function addContour(vertices, contour) { - for (let i = 0; i < contour.length; i++) { - vertices.push(contour[i].x); - vertices.push(contour[i].y); - } -} + material = isMultiMaterial === true + ? object.material[ group.materialIndex ] + : object.material; -/** - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * depth: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline (including bevelOffset) is bevel - * bevelOffset: , // how far from shape outline does bevel start - * bevelSegments: , // number of bevel layers - * - * extrudePath: // curve to extrude shape along - * - * UVGenerator: // object that provides UV generator functions - * - * } - */ -class ExtrudeGeometry extends BufferGeometry { - constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { - super(); - this.type = 'ExtrudeGeometry'; - this.parameters = { - shapes: shapes, - options: options - }; - shapes = Array.isArray(shapes) ? shapes : [shapes]; - const scope = this; - const verticesArray = []; - const uvArray = []; - for (let i = 0, l = shapes.length; i < l; i++) { - const shape = shapes[i]; - addShape(shape); - } + if ( material === undefined ) continue; - // build geometry + for ( let i = group.start, l = group.start + group.count; i < l; i += 3 ) { - this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2)); - this.computeVertexNormals(); + renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ], material ); - // functions + } - function addShape(shape) { - const placeholder = []; + } - // options + } else { - const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - const steps = options.steps !== undefined ? options.steps : 1; - const depth = options.depth !== undefined ? options.depth : 1; - let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; - let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; - let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; - let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; - let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - const extrudePath = options.extrudePath; - const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + for ( let i = 0, l = indices.length; i < l; i += 3 ) { - // + renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ], material ); - let extrudePts, - extrudeByPath = false; - let splineTube, binormal, normal, position2; - if (extrudePath) { - extrudePts = extrudePath.getSpacedPoints(steps); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + } - // SETUP TNB variables + } - // TODO1 - have a .isClosed in spline? + } else { - splineTube = extrudePath.computeFrenetFrames(steps, false); + if ( groups.length > 0 ) { - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + for ( let g = 0; g < groups.length; g ++ ) { - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); - } + const group = groups[ g ]; - // Safeguards if bevels are not enabled + material = isMultiMaterial === true + ? object.material[ group.materialIndex ] + : object.material; - if (!bevelEnabled) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; - bevelOffset = 0; - } + if ( material === undefined ) continue; + + for ( let i = group.start, l = group.start + group.count; i < l; i += 3 ) { + + renderList.pushTriangle( i, i + 1, i + 2, material ); + + } + + } - // Variables initialization + } else { - const shapePoints = shape.extractPoints(curveSegments); - let vertices = shapePoints.shape; - const holes = shapePoints.holes; - const reverse = !ShapeUtils.isClockWise(vertices); - if (reverse) { - vertices = vertices.reverse(); + for ( let i = 0, l = positions.length / 3; i < l; i += 3 ) { - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + renderList.pushTriangle( i, i + 1, i + 2, material ); - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - if (ShapeUtils.isClockWise(ahole)) { - holes[h] = ahole.reverse(); - } - } - } - const faces = ShapeUtils.triangulateShape(vertices, holes); + } - /* Vertices */ + } - const contour = vertices; // vertices has all points but contour has only points of circumference + } - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - vertices = vertices.concat(ahole); - } - function scalePt2(pt, vec, size) { - if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist'); - return vec.clone().multiplyScalar(size).add(pt); - } - const vlen = vertices.length, - flen = faces.length; + } else if ( object.isLine ) { - // Find directions for point movement + _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix ); - function getBevelVec(inPt, inPrev, inNext) { - // computes for inPt the corresponding point inPt' on a new contour - // shifted by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. + const attributes = geometry.attributes; - let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + if ( attributes.position !== undefined ) { - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + const positions = attributes.position.array; - const v_prev_x = inPt.x - inPrev.x, - v_prev_y = inPt.y - inPrev.y; - const v_next_x = inNext.x - inPt.x, - v_next_y = inNext.y - inPt.y; - const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + for ( let i = 0, l = positions.length; i < l; i += 3 ) { - // check for collinear edges - const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; - if (Math.abs(collinear0) > Number.EPSILON) { - // not collinear + renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - // length of vectors for normalizing + } - const v_prev_len = Math.sqrt(v_prev_lensq); - const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + if ( attributes.color !== undefined ) { - // shift adjacent points by unit vectors to the left + const colors = attributes.color.array; - const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; - const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; - const ptNextShift_x = inNext.x - v_next_y / v_next_len; - const ptNextShift_y = inNext.y + v_next_x / v_next_len; + for ( let i = 0, l = colors.length; i < l; i += 3 ) { - // scaling factor for v_prev to intersection point + renderList.pushColor( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ); - const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + } - // vector from inPt to intersection point + } - v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; - v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + if ( geometry.index !== null ) { - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; - if (v_trans_lensq <= 2) { - return new Vector2(v_trans_x, v_trans_y); - } else { - shrink_by = Math.sqrt(v_trans_lensq / 2); - } - } else { - // handle special case of collinear edges + const indices = geometry.index.array; - let direction_eq = false; // assumes: opposite + for ( let i = 0, l = indices.length; i < l; i += 2 ) { + + renderList.pushLine( indices[ i ], indices[ i + 1 ] ); - if (v_prev_x > Number.EPSILON) { - if (v_next_x > Number.EPSILON) { - direction_eq = true; - } - } else { - if (v_prev_x < -Number.EPSILON) { - if (v_next_x < -Number.EPSILON) { - direction_eq = true; } + } else { - if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { - direction_eq = true; + + const step = object.isLineSegments ? 2 : 1; + + for ( let i = 0, l = ( positions.length / 3 ) - 1; i < l; i += step ) { + + renderList.pushLine( i, i + 1 ); + } + } + } - if (direction_eq) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = -v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt(v_prev_lensq); - } else { - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt(v_prev_lensq / 2); - } - } - return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); - } - const contourMovements = []; - for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { - if (j === il) j = 0; - if (k === il) k = 0; - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + } else if ( object.isPoints ) { - contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); - } - const holesMovements = []; - let oneHoleMovements, - verticesMovements = contourMovements.concat(); - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - oneHoleMovements = []; - for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { - if (j === il) j = 0; - if (k === il) k = 0; + _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix ); - // (j)---(i)---(k) - oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); - } - holesMovements.push(oneHoleMovements); - verticesMovements = verticesMovements.concat(oneHoleMovements); - } + const attributes = geometry.attributes; - // Loop bevelSegments, 1 for the front, 1 for the back + if ( attributes.position !== undefined ) { - for (let b = 0; b < bevelSegments; b++) { - //for ( b = bevelSegments; b > 0; b -- ) { + const positions = attributes.position.array; - const t = b / bevelSegments; - const z = bevelThickness * Math.cos(t * Math.PI / 2); - const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for ( let i = 0, l = positions.length; i < l; i += 3 ) { - // contract shape + _vector4.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ], 1 ); + _vector4.applyMatrix4( _modelViewProjectionMatrix ); - for (let i = 0, il = contour.length; i < il; i++) { - const vert = scalePt2(contour[i], contourMovements[i], bs); - v(vert.x, vert.y, -z); - } + pushPoint( _vector4, object, camera ); - // expand holes + } - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - oneHoleMovements = holesMovements[h]; - for (let i = 0, il = ahole.length; i < il; i++) { - const vert = scalePt2(ahole[i], oneHoleMovements[i], bs); - v(vert.x, vert.y, -z); } - } - } - const bs = bevelSize + bevelOffset; - // Back facing vertices + } else if ( object.isSprite ) { - for (let i = 0; i < vlen; i++) { - const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; - if (!extrudeByPath) { - v(vert.x, vert.y, 0); - } else { - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + _vector4.set( _modelMatrix.elements[ 12 ], _modelMatrix.elements[ 13 ], _modelMatrix.elements[ 14 ], 1 ); + _vector4.applyMatrix4( _viewProjectionMatrix ); + + pushPoint( _vector4, object, camera ); - normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); - binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); - position2.copy(extrudePts[0]).add(normal).add(binormal); - v(position2.x, position2.y, position2.z); } + } - // Add stepped vertices... - // Including front facing vertices + if ( sortElements === true ) { - for (let s = 1; s <= steps; s++) { - for (let i = 0; i < vlen; i++) { - const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; - if (!extrudeByPath) { - v(vert.x, vert.y, depth / steps * s); - } else { - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + _renderData.elements.sort( painterSort ); - normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); - binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); - position2.copy(extrudePts[s]).add(normal).add(binormal); - v(position2.x, position2.y, position2.z); - } - } } - // Add bevel segments planes + return _renderData; - //for ( b = 1; b <= bevelSegments; b ++ ) { - for (let b = bevelSegments - 1; b >= 0; b--) { - const t = b / bevelSegments; - const z = bevelThickness * Math.cos(t * Math.PI / 2); - const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + }; - // contract shape + function pushPoint( _vector4, object, camera ) { - for (let i = 0, il = contour.length; i < il; i++) { - const vert = scalePt2(contour[i], contourMovements[i], bs); - v(vert.x, vert.y, depth + z); - } + const invW = 1 / _vector4.w; - // expand holes + _vector4.z *= invW; - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - oneHoleMovements = holesMovements[h]; - for (let i = 0, il = ahole.length; i < il; i++) { - const vert = scalePt2(ahole[i], oneHoleMovements[i], bs); - if (!extrudeByPath) { - v(vert.x, vert.y, depth + z); - } else { - v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); - } - } - } - } + if ( _vector4.z >= - 1 && _vector4.z <= 1 ) { - /* Faces */ + _sprite = getNextSpriteInPool(); + _sprite.id = object.id; + _sprite.x = _vector4.x * invW; + _sprite.y = _vector4.y * invW; + _sprite.z = _vector4.z; + _sprite.renderOrder = object.renderOrder; + _sprite.object = object; - // Top and bottom faces + _sprite.rotation = object.rotation; - buildLidFaces(); + _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[ 0 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 12 ] ) ); + _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[ 5 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 13 ] ) ); - // Sides faces + _sprite.material = object.material; - buildSideFaces(); + _renderData.elements.push( _sprite ); - ///// Internal functions + } - function buildLidFaces() { - const start = verticesArray.length / 3; - if (bevelEnabled) { - let layer = 0; // steps + 1 - let offset = vlen * layer; + } - // Bottom faces + // Pools - for (let i = 0; i < flen; i++) { - const face = faces[i]; - f3(face[2] + offset, face[1] + offset, face[0] + offset); - } - layer = steps + bevelSegments * 2; - offset = vlen * layer; + function getNextObjectInPool() { - // Top faces + if ( _objectCount === _objectPoolLength ) { - for (let i = 0; i < flen; i++) { - const face = faces[i]; - f3(face[0] + offset, face[1] + offset, face[2] + offset); - } - } else { - // Bottom faces + const object = new RenderableObject(); + _objectPool.push( object ); + _objectPoolLength ++; + _objectCount ++; + return object; - for (let i = 0; i < flen; i++) { - const face = faces[i]; - f3(face[2], face[1], face[0]); - } + } - // Top faces + return _objectPool[ _objectCount ++ ]; - for (let i = 0; i < flen; i++) { - const face = faces[i]; - f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); - } - } - scope.addGroup(start, verticesArray.length / 3 - start, 0); - } + } - // Create faces for the z-sides of the shape + function getNextVertexInPool() { - function buildSideFaces() { - const start = verticesArray.length / 3; - let layeroffset = 0; - sidewalls(contour, layeroffset); - layeroffset += contour.length; - for (let h = 0, hl = holes.length; h < hl; h++) { - const ahole = holes[h]; - sidewalls(ahole, layeroffset); + if ( _vertexCount === _vertexPoolLength ) { + + const vertex = new RenderableVertex(); + _vertexPool.push( vertex ); + _vertexPoolLength ++; + _vertexCount ++; + return vertex; - //, true - layeroffset += ahole.length; - } - scope.addGroup(start, verticesArray.length / 3 - start, 1); } - function sidewalls(contour, layeroffset) { - let i = contour.length; - while (--i >= 0) { - const j = i; - let k = i - 1; - if (k < 0) k = contour.length - 1; - //console.log('b', i,j, i-1, k,vertices.length); + return _vertexPool[ _vertexCount ++ ]; - for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) { - const slen1 = vlen * s; - const slen2 = vlen * (s + 1); - const a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; - f4(a, b, c, d); - } - } - } - function v(x, y, z) { - placeholder.push(x); - placeholder.push(y); - placeholder.push(z); - } - function f3(a, b, c) { - addVertex(a); - addVertex(b); - addVertex(c); - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); - addUV(uvs[0]); - addUV(uvs[1]); - addUV(uvs[2]); - } - function f4(a, b, c, d) { - addVertex(a); - addVertex(b); - addVertex(d); - addVertex(b); - addVertex(c); - addVertex(d); - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); - addUV(uvs[0]); - addUV(uvs[1]); - addUV(uvs[3]); - addUV(uvs[1]); - addUV(uvs[2]); - addUV(uvs[3]); - } - function addVertex(index) { - verticesArray.push(placeholder[index * 3 + 0]); - verticesArray.push(placeholder[index * 3 + 1]); - verticesArray.push(placeholder[index * 3 + 2]); - } - function addUV(vector2) { - uvArray.push(vector2.x); - uvArray.push(vector2.y); - } - } - } - toJSON() { - const data = super.toJSON(); - const shapes = this.parameters.shapes; - const options = this.parameters.options; - return toJSON$1(shapes, options, data); - } - static fromJSON(data, shapes) { - const geometryShapes = []; - for (let j = 0, jl = data.shapes.length; j < jl; j++) { - const shape = shapes[data.shapes[j]]; - geometryShapes.push(shape); - } - const extrudePath = data.options.extrudePath; - if (extrudePath !== undefined) { - data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); - } - return new ExtrudeGeometry(geometryShapes, data.options); - } -} -const WorldUVGenerator = { - generateTopUV: function (geometry, vertices, indexA, indexB, indexC) { - const a_x = vertices[indexA * 3]; - const a_y = vertices[indexA * 3 + 1]; - const b_x = vertices[indexB * 3]; - const b_y = vertices[indexB * 3 + 1]; - const c_x = vertices[indexC * 3]; - const c_y = vertices[indexC * 3 + 1]; - return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)]; - }, - generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) { - const a_x = vertices[indexA * 3]; - const a_y = vertices[indexA * 3 + 1]; - const a_z = vertices[indexA * 3 + 2]; - const b_x = vertices[indexB * 3]; - const b_y = vertices[indexB * 3 + 1]; - const b_z = vertices[indexB * 3 + 2]; - const c_x = vertices[indexC * 3]; - const c_y = vertices[indexC * 3 + 1]; - const c_z = vertices[indexC * 3 + 2]; - const d_x = vertices[indexD * 3]; - const d_y = vertices[indexD * 3 + 1]; - const d_z = vertices[indexD * 3 + 2]; - if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { - return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)]; - } else { - return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)]; - } - } -}; -function toJSON$1(shapes, options, data) { - data.shapes = []; - if (Array.isArray(shapes)) { - for (let i = 0, l = shapes.length; i < l; i++) { - const shape = shapes[i]; - data.shapes.push(shape.uuid); } - } else { - data.shapes.push(shapes.uuid); - } - data.options = Object.assign({}, options); - if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON(); - return data; -} -class OctahedronGeometry extends PolyhedronGeometry { - constructor(radius = 1, detail = 0) { - const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1]; - const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2]; - super(vertices, indices, radius, detail); - this.type = 'OctahedronGeometry'; - this.parameters = { - radius: radius, - detail: detail - }; - } - static fromJSON(data) { - return new OctahedronGeometry(data.radius, data.detail); - } -} + function getNextFaceInPool() { -class SphereGeometry extends BufferGeometry { - constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { - super(); - this.type = 'SphereGeometry'; - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; - widthSegments = Math.max(3, Math.floor(widthSegments)); - heightSegments = Math.max(2, Math.floor(heightSegments)); - const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); - let index = 0; - const grid = []; - const vertex = new Vector3(); - const normal = new Vector3(); + if ( _faceCount === _facePoolLength ) { - // buffers + const face = new RenderableFace(); + _facePool.push( face ); + _facePoolLength ++; + _faceCount ++; + return face; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + } - // generate vertices, normals and uvs + return _facePool[ _faceCount ++ ]; - for (let iy = 0; iy <= heightSegments; iy++) { - const verticesRow = []; - const v = iy / heightSegments; - // special case for the poles + } + + function getNextLineInPool() { + + if ( _lineCount === _linePoolLength ) { + + const line = new RenderableLine(); + _linePool.push( line ); + _linePoolLength ++; + _lineCount ++; + return line; - let uOffset = 0; - if (iy == 0 && thetaStart == 0) { - uOffset = 0.5 / widthSegments; - } else if (iy == heightSegments && thetaEnd == Math.PI) { - uOffset = -0.5 / widthSegments; } - for (let ix = 0; ix <= widthSegments; ix++) { - const u = ix / widthSegments; - // vertex + return _linePool[ _lineCount ++ ]; - vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); - vertex.y = radius * Math.cos(thetaStart + v * thetaLength); - vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); - vertices.push(vertex.x, vertex.y, vertex.z); + } - // normal + function getNextSpriteInPool() { - normal.copy(vertex).normalize(); - normals.push(normal.x, normal.y, normal.z); + if ( _spriteCount === _spritePoolLength ) { - // uv + const sprite = new RenderableSprite(); + _spritePool.push( sprite ); + _spritePoolLength ++; + _spriteCount ++; + return sprite; - uvs.push(u + uOffset, 1 - v); - verticesRow.push(index++); } - grid.push(verticesRow); - } - // indices + return _spritePool[ _spriteCount ++ ]; - for (let iy = 0; iy < heightSegments; iy++) { - for (let ix = 0; ix < widthSegments; ix++) { - const a = grid[iy][ix + 1]; - const b = grid[iy][ix]; - const c = grid[iy + 1][ix]; - const d = grid[iy + 1][ix + 1]; - if (iy !== 0 || thetaStart > 0) indices.push(a, b, d); - if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d); - } } - // build geometry + // - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - } - static fromJSON(data) { - return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength); - } -} + function painterSort( a, b ) { -class TorusGeometry extends BufferGeometry { - constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) { - super(); - this.type = 'TorusGeometry'; - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; - radialSegments = Math.floor(radialSegments); - tubularSegments = Math.floor(tubularSegments); + if ( a.renderOrder !== b.renderOrder ) { - // buffers + return a.renderOrder - b.renderOrder; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + } else if ( a.z !== b.z ) { - // helper variables + return b.z - a.z; - const center = new Vector3(); - const vertex = new Vector3(); - const normal = new Vector3(); + } else if ( a.id !== b.id ) { - // generate vertices, normals and uvs + return a.id - b.id; - for (let j = 0; j <= radialSegments; j++) { - for (let i = 0; i <= tubularSegments; i++) { - const u = i / tubularSegments * arc; - const v = j / radialSegments * Math.PI * 2; + } else { - // vertex + return 0; - vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u); - vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u); - vertex.z = tube * Math.sin(v); - vertices.push(vertex.x, vertex.y, vertex.z); + } - // normal + } - center.x = radius * Math.cos(u); - center.y = radius * Math.sin(u); - normal.subVectors(vertex, center).normalize(); - normals.push(normal.x, normal.y, normal.z); + function clipLine( s1, s2 ) { - // uv + let alpha1 = 0, alpha2 = 1; - uvs.push(i / tubularSegments); - uvs.push(j / radialSegments); - } - } + // Calculate the boundary coordinate of each vertex for the near and far clip planes, + // Z = -1 and Z = +1, respectively. - // generate indices + const bc1near = s1.z + s1.w, + bc2near = s2.z + s2.w, + bc1far = - s1.z + s1.w, + bc2far = - s2.z + s2.w; - for (let j = 1; j <= radialSegments; j++) { - for (let i = 1; i <= tubularSegments; i++) { - // indices + if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) { - const a = (tubularSegments + 1) * j + i - 1; - const b = (tubularSegments + 1) * (j - 1) + i - 1; - const c = (tubularSegments + 1) * (j - 1) + i; - const d = (tubularSegments + 1) * j + i; + // Both vertices lie entirely within all clip planes. + return true; - // faces + } else if ( ( bc1near < 0 && bc2near < 0 ) || ( bc1far < 0 && bc2far < 0 ) ) { - indices.push(a, b, d); - indices.push(b, c, d); - } - } + // Both vertices lie entirely outside one of the clip planes. + return false; - // build geometry + } else { - this.setIndex(indices); - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - this.setAttribute('normal', new Float32BufferAttribute(normals, 3)); - this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); - } - static fromJSON(data) { - return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc); - } -} + // The line segment spans at least one clip plane. + + if ( bc1near < 0 ) { + + // v1 lies outside the near plane, v2 inside + alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) ); + + } else if ( bc2near < 0 ) { + + // v2 lies outside the near plane, v1 inside + alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) ); -class WireframeGeometry extends BufferGeometry { - constructor(geometry = null) { - super(); - this.type = 'WireframeGeometry'; - this.parameters = { - geometry: geometry - }; - if (geometry !== null) { - // buffer - - const vertices = []; - const edges = new Set(); - - // helper variables - - const start = new Vector3(); - const end = new Vector3(); - if (geometry.index !== null) { - // indexed BufferGeometry - - const position = geometry.attributes.position; - const indices = geometry.index; - let groups = geometry.groups; - if (groups.length === 0) { - groups = [{ - start: 0, - count: indices.count, - materialIndex: 0 - }]; } - // create a data structure that contains all edges without duplicates - - for (let o = 0, ol = groups.length; o < ol; ++o) { - const group = groups[o]; - const groupStart = group.start; - const groupCount = group.count; - for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) { - for (let j = 0; j < 3; j++) { - const index1 = indices.getX(i + j); - const index2 = indices.getX(i + (j + 1) % 3); - start.fromBufferAttribute(position, index1); - end.fromBufferAttribute(position, index2); - if (isUniqueEdge(start, end, edges) === true) { - vertices.push(start.x, start.y, start.z); - vertices.push(end.x, end.y, end.z); - } - } - } + if ( bc1far < 0 ) { + + // v1 lies outside the far plane, v2 inside + alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) ); + + } else if ( bc2far < 0 ) { + + // v2 lies outside the far plane, v2 inside + alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) ); + } - } else { - // non-indexed BufferGeometry - - const position = geometry.attributes.position; - for (let i = 0, l = position.count / 3; i < l; i++) { - for (let j = 0; j < 3; j++) { - // three edges per triangle, an edge is represented as (index1, index2) - // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) - - const index1 = 3 * i + j; - const index2 = 3 * i + (j + 1) % 3; - start.fromBufferAttribute(position, index1); - end.fromBufferAttribute(position, index2); - if (isUniqueEdge(start, end, edges) === true) { - vertices.push(start.x, start.y, start.z); - vertices.push(end.x, end.y, end.z); - } - } + + if ( alpha2 < alpha1 ) { + + // The line segment spans two boundaries, but is outside both of them. + // (This can't happen when we're only clipping against just near/far but good + // to leave the check here for future usage if other clip planes are added.) + return false; + + } else { + + // Update the s1 and s2 vertices to match the clipped line segment. + s1.lerp( s2, alpha1 ); + s2.lerp( s1, 1 - alpha2 ); + + return true; + } - } - // build geometry + } - this.setAttribute('position', new Float32BufferAttribute(vertices, 3)); } - } -} -function isUniqueEdge(start, end, edges) { - const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; - const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge - if (edges.has(hash1) === true || edges.has(hash2) === true) { - return false; - } else { - edges.add(hash1); - edges.add(hash2); - return true; } -} -class MeshNormalMaterial extends Material { - constructor(parameters) { - super(); - this.isMeshNormalMaterial = true; - this.type = 'MeshNormalMaterial'; - this.bumpMap = null; - this.bumpScale = 1; - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2(1, 1); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.flatShading = false; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy(source.normalScale); - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.flatShading = source.flatShading; - return this; - } } -class MeshLambertMaterial extends Material { - constructor(parameters) { - super(); - this.isMeshLambertMaterial = true; - this.type = 'MeshLambertMaterial'; - this.color = new Color$1(0xffffff); // diffuse +class SVGRenderer { - this.map = null; - this.lightMap = null; - this.lightMapIntensity = 1.0; - this.aoMap = null; - this.aoMapIntensity = 1.0; - this.emissive = new Color$1(0x000000); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; - this.bumpMap = null; - this.bumpScale = 1; - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2(1, 1); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; - this.specularMap = null; - this.alphaMap = null; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - this.flatShading = false; - this.fog = true; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.color.copy(source.color); - this.map = source.map; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; - this.emissive.copy(source.emissive); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy(source.normalScale); - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; - this.specularMap = source.specularMap; - this.alphaMap = source.alphaMap; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; - this.flatShading = source.flatShading; - this.fog = source.fog; - return this; - } -} + constructor() { -class LineDashedMaterial extends LineBasicMaterial { - constructor(parameters) { - super(); - this.isLineDashedMaterial = true; - this.type = 'LineDashedMaterial'; - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; - this.setValues(parameters); - } - copy(source) { - super.copy(source); - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; - return this; - } -} + let _renderData, _elements, _lights, + _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf, -const Cache = { - enabled: false, - files: {}, - add: function (key, file) { - if (this.enabled === false) return; + _v1, _v2, _v3, - // console.log( 'THREE.Cache', 'Adding key:', key ); + _svgNode, + _pathCount = 0, - this.files[key] = file; - }, - get: function (key) { - if (this.enabled === false) return; + _precision = null, + _quality = 1, - // console.log( 'THREE.Cache', 'Checking key:', key ); + _currentPath, _currentStyle; - return this.files[key]; - }, - remove: function (key) { - delete this.files[key]; - }, - clear: function () { - this.files = {}; - } -}; + const _this = this, + _clipBox = new Box2(), + _elemBox = new Box2(), -class LoadingManager { - constructor(onLoad, onProgress, onError) { - const scope = this; - let isLoading = false; - let itemsLoaded = 0; - let itemsTotal = 0; - let urlModifier = undefined; - const handlers = []; + _color = new Color(), + _diffuseColor = new Color(), + _ambientLight = new Color(), + _directionalLights = new Color(), + _pointLights = new Color(), + _clearColor = new Color(), - // Refer to #5689 for the reason why we don't set .onStart - // in the constructor + _vector3 = new Vector3(), // Needed for PointLight + _centroid = new Vector3(), + _normal = new Vector3(), + _normalViewMatrix = new Matrix3(), + + _viewMatrix = new Matrix4(), + _viewProjectionMatrix = new Matrix4(), + + _svgPathPool = [], + + _projector = new Projector(), + _svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' ); + + this.domElement = _svg; + + this.autoClear = true; + this.sortObjects = true; + this.sortElements = true; + + this.overdraw = 0.5; + + this.info = { + + render: { + + vertices: 0, + faces: 0 - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; - this.itemStart = function (url) { - itemsTotal++; - if (isLoading === false) { - if (scope.onStart !== undefined) { - scope.onStart(url, itemsLoaded, itemsTotal); - } - } - isLoading = true; - }; - this.itemEnd = function (url) { - itemsLoaded++; - if (scope.onProgress !== undefined) { - scope.onProgress(url, itemsLoaded, itemsTotal); - } - if (itemsLoaded === itemsTotal) { - isLoading = false; - if (scope.onLoad !== undefined) { - scope.onLoad(); - } - } - }; - this.itemError = function (url) { - if (scope.onError !== undefined) { - scope.onError(url); - } - }; - this.resolveURL = function (url) { - if (urlModifier) { - return urlModifier(url); } - return url; - }; - this.setURLModifier = function (transform) { - urlModifier = transform; - return this; - }; - this.addHandler = function (regex, loader) { - handlers.push(regex, loader); - return this; + }; - this.removeHandler = function (regex) { - const index = handlers.indexOf(regex); - if (index !== -1) { - handlers.splice(index, 2); + + this.setQuality = function ( quality ) { + + switch ( quality ) { + + case 'high': _quality = 1; break; + case 'low': _quality = 0; break; + } - return this; + }; - this.getHandler = function (file) { - for (let i = 0, l = handlers.length; i < l; i += 2) { - const regex = handlers[i]; - const loader = handlers[i + 1]; - if (regex.global) regex.lastIndex = 0; // see #17920 - if (regex.test(file)) { - return loader; - } - } - return null; + this.setClearColor = function ( color ) { + + _clearColor.set( color ); + }; - } -} -const DefaultLoadingManager = /*@__PURE__*/new LoadingManager(); -class Loader { - constructor(manager) { - this.manager = manager !== undefined ? manager : DefaultLoadingManager; - this.crossOrigin = 'anonymous'; - this.withCredentials = false; - this.path = ''; - this.resourcePath = ''; - this.requestHeader = {}; - } - load( /* url, onLoad, onProgress, onError */) {} - loadAsync(url, onProgress) { - const scope = this; - return new Promise(function (resolve, reject) { - scope.load(url, resolve, onProgress, reject); - }); - } - parse( /* data */) {} - setCrossOrigin(crossOrigin) { - this.crossOrigin = crossOrigin; - return this; - } - setWithCredentials(value) { - this.withCredentials = value; - return this; - } - setPath(path) { - this.path = path; - return this; - } - setResourcePath(resourcePath) { - this.resourcePath = resourcePath; - return this; - } - setRequestHeader(requestHeader) { - this.requestHeader = requestHeader; - return this; - } -} + this.setPixelRatio = function () {}; -class ImageLoader extends Loader { - constructor(manager) { - super(manager); - } - load(url, onLoad, onProgress, onError) { - if (this.path !== undefined) url = this.path + url; - url = this.manager.resolveURL(url); - const scope = this; - const cached = Cache.get(url); - if (cached !== undefined) { - scope.manager.itemStart(url); - setTimeout(function () { - if (onLoad) onLoad(cached); - scope.manager.itemEnd(url); - }, 0); - return cached; - } - const image = createElementNS('img'); - function onImageLoad() { - removeEventListeners(); - Cache.add(url, this); - if (onLoad) onLoad(this); - scope.manager.itemEnd(url); - } - function onImageError(event) { - removeEventListeners(); - if (onError) onError(event); - scope.manager.itemError(url); - scope.manager.itemEnd(url); - } - function removeEventListeners() { - image.removeEventListener('load', onImageLoad, false); - image.removeEventListener('error', onImageError, false); - } - image.addEventListener('load', onImageLoad, false); - image.addEventListener('error', onImageError, false); - if (url.slice(0, 5) !== 'data:') { - if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin; - } - scope.manager.itemStart(url); - image.src = url; - return image; - } -} + this.setSize = function ( width, height ) { -class TextureLoader extends Loader { - constructor(manager) { - super(manager); - } - load(url, onLoad, onProgress, onError) { - const texture = new Texture(); - const loader = new ImageLoader(this.manager); - loader.setCrossOrigin(this.crossOrigin); - loader.setPath(this.path); - loader.load(url, function (image) { - texture.image = image; - texture.needsUpdate = true; - if (onLoad !== undefined) { - onLoad(texture); - } - }, onProgress, onError); - return texture; - } -} + _svgWidth = width; _svgHeight = height; + _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2; -class Light extends Object3D { - constructor(color, intensity = 1) { - super(); - this.isLight = true; - this.type = 'Light'; - this.color = new Color$1(color); - this.intensity = intensity; - } - dispose() { + _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight ); + _svg.setAttribute( 'width', _svgWidth ); + _svg.setAttribute( 'height', _svgHeight ); - // Empty here in base class; some subclasses override. - } - copy(source, recursive) { - super.copy(source, recursive); - this.color.copy(source.color); - this.intensity = source.intensity; - return this; - } - toJSON(meta) { - const data = super.toJSON(meta); - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; - if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex(); - if (this.distance !== undefined) data.object.distance = this.distance; - if (this.angle !== undefined) data.object.angle = this.angle; - if (this.decay !== undefined) data.object.decay = this.decay; - if (this.penumbra !== undefined) data.object.penumbra = this.penumbra; - if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON(); - return data; - } -} + _clipBox.min.set( - _svgWidthHalf, - _svgHeightHalf ); + _clipBox.max.set( _svgWidthHalf, _svgHeightHalf ); -class HemisphereLight extends Light { - constructor(skyColor, groundColor, intensity) { - super(skyColor, intensity); - this.isHemisphereLight = true; - this.type = 'HemisphereLight'; - this.position.copy(Object3D.DefaultUp); - this.updateMatrix(); - this.groundColor = new Color$1(groundColor); - } - copy(source, recursive) { - super.copy(source, recursive); - this.groundColor.copy(source.groundColor); - return this; - } -} + }; -const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4(); -const _lightPositionWorld$1 = /*@__PURE__*/new Vector3(); -const _lookTarget$1 = /*@__PURE__*/new Vector3(); -class LightShadow { - constructor(camera) { - this.camera = camera; - this.bias = 0; - this.normalBias = 0; - this.radius = 1; - this.blurSamples = 8; - this.mapSize = new Vector2(512, 512); - this.map = null; - this.mapPass = null; - this.matrix = new Matrix4(); - this.autoUpdate = true; - this.needsUpdate = false; - this._frustum = new Frustum(); - this._frameExtents = new Vector2(1, 1); - this._viewportCount = 1; - this._viewports = [new Vector4(0, 0, 1, 1)]; - } - getViewportCount() { - return this._viewportCount; - } - getFrustum() { - return this._frustum; - } - updateMatrices(light) { - const shadowCamera = this.camera; - const shadowMatrix = this.matrix; - _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); - shadowCamera.position.copy(_lightPositionWorld$1); - _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); - shadowCamera.lookAt(_lookTarget$1); - shadowCamera.updateMatrixWorld(); - _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); - this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); - shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0); - shadowMatrix.multiply(_projScreenMatrix$1); - } - getViewport(viewportIndex) { - return this._viewports[viewportIndex]; - } - getFrameExtents() { - return this._frameExtents; - } - dispose() { - if (this.map) { - this.map.dispose(); - } - if (this.mapPass) { - this.mapPass.dispose(); - } - } - copy(source) { - this.camera = source.camera.clone(); - this.bias = source.bias; - this.radius = source.radius; - this.mapSize.copy(source.mapSize); - return this; - } - clone() { - return new this.constructor().copy(this); - } - toJSON() { - const object = {}; - if (this.bias !== 0) object.bias = this.bias; - if (this.normalBias !== 0) object.normalBias = this.normalBias; - if (this.radius !== 1) object.radius = this.radius; - if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray(); - object.camera = this.camera.toJSON(false).object; - delete object.camera.matrix; - return object; - } -} + this.getSize = function () { -const _projScreenMatrix = /*@__PURE__*/new Matrix4(); -const _lightPositionWorld = /*@__PURE__*/new Vector3(); -const _lookTarget = /*@__PURE__*/new Vector3(); -class PointLightShadow extends LightShadow { - constructor() { - super(new PerspectiveCamera(90, 1, 0.5, 500)); - this.isPointLightShadow = true; - this._frameExtents = new Vector2(4, 2); - this._viewportCount = 6; - this._viewports = [ - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction - - // positive X - new Vector4(2, 1, 1, 1), - // negative X - new Vector4(0, 1, 1, 1), - // positive Z - new Vector4(3, 1, 1, 1), - // negative Z - new Vector4(1, 1, 1, 1), - // positive Y - new Vector4(3, 0, 1, 1), - // negative Y - new Vector4(1, 0, 1, 1)]; - this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)]; - this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)]; - } - updateMatrices(light, viewportIndex = 0) { - const camera = this.camera; - const shadowMatrix = this.matrix; - const far = light.distance || camera.far; - if (far !== camera.far) { - camera.far = far; - camera.updateProjectionMatrix(); - } - _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); - camera.position.copy(_lightPositionWorld); - _lookTarget.copy(camera.position); - _lookTarget.add(this._cubeDirections[viewportIndex]); - camera.up.copy(this._cubeUps[viewportIndex]); - camera.lookAt(_lookTarget); - camera.updateMatrixWorld(); - shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); - _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); - this._frustum.setFromProjectionMatrix(_projScreenMatrix); - } -} - -class PointLight extends Light { - constructor(color, intensity, distance = 0, decay = 1) { - super(color, intensity); - this.isPointLight = true; - this.type = 'PointLight'; - this.distance = distance; - this.decay = decay; // for physically correct lights, should be 2. - - this.shadow = new PointLightShadow(); - } - get power() { - // compute the light's luminous power (in lumens) from its intensity (in candela) - // for an isotropic light source, luminous power (lm) = 4 Ï€ luminous intensity (cd) - return this.intensity * 4 * Math.PI; - } - set power(power) { - // set the light's intensity (in candela) from the desired luminous power (in lumens) - this.intensity = power / (4 * Math.PI); - } - dispose() { - this.shadow.dispose(); - } - copy(source, recursive) { - super.copy(source, recursive); - this.distance = source.distance; - this.decay = source.decay; - this.shadow = source.shadow.clone(); - return this; - } -} + return { + width: _svgWidth, + height: _svgHeight + }; -class AmbientLight extends Light { - constructor(color, intensity) { - super(color, intensity); - this.isAmbientLight = true; - this.type = 'AmbientLight'; - } -} + }; -class Raycaster { - constructor(origin, direction, near = 0, far = Infinity) { - this.ray = new Ray(origin, direction); - // direction is assumed to be normalized (for accurate distance calculations) + this.setPrecision = function ( precision ) { + + _precision = precision; - this.near = near; - this.far = far; - this.camera = null; - this.layers = new Layers(); - this.params = { - Mesh: {}, - Line: { - threshold: 1 - }, - LOD: {}, - Points: { - threshold: 1 - }, - Sprite: {} }; - } - set(origin, direction) { - // direction is assumed to be normalized (for accurate distance calculations) - this.ray.set(origin, direction); - } - setFromCamera(coords, camera) { - if (camera.isPerspectiveCamera) { - this.ray.origin.setFromMatrixPosition(camera.matrixWorld); - this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); - this.camera = camera; - } else if (camera.isOrthographicCamera) { - this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera - this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); - this.camera = camera; - } else { - console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type); - } - } - intersectObject(object, recursive = true, intersects = []) { - intersectObject(object, this, intersects, recursive); - intersects.sort(ascSort); - return intersects; - } - intersectObjects(objects, recursive = true, intersects = []) { - for (let i = 0, l = objects.length; i < l; i++) { - intersectObject(objects[i], this, intersects, recursive); - } - intersects.sort(ascSort); - return intersects; - } -} -function ascSort(a, b) { - return a.distance - b.distance; -} -function intersectObject(object, raycaster, intersects, recursive) { - if (object.layers.test(raycaster.layers)) { - object.raycast(raycaster, intersects); - } - if (recursive === true) { - const children = object.children; - for (let i = 0, l = children.length; i < l; i++) { - intersectObject(children[i], raycaster, intersects, true); - } - } -} + function removeChildNodes() { -class Clock { - constructor(autoStart = true) { - this.autoStart = autoStart; - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; - this.running = false; - } - start() { - this.startTime = now(); - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; - } - stop() { - this.getElapsedTime(); - this.running = false; - this.autoStart = false; - } - getElapsedTime() { - this.getDelta(); - return this.elapsedTime; - } - getDelta() { - let diff = 0; - if (this.autoStart && !this.running) { - this.start(); - return 0; - } - if (this.running) { - const newTime = now(); - diff = (newTime - this.oldTime) / 1000; - this.oldTime = newTime; - this.elapsedTime += diff; - } - return diff; - } -} -function now() { - return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732 -} + _pathCount = 0; -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ -class Spherical { - constructor(radius = 1, phi = 0, theta = 0) { - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle + while ( _svg.childNodes.length > 0 ) { - return this; - } - set(radius, phi, theta) { - this.radius = radius; - this.phi = phi; - this.theta = theta; - return this; - } - copy(other) { - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; - return this; - } + _svg.removeChild( _svg.childNodes[ 0 ] ); + + } - // restrict phi to be between EPS and PI-EPS - makeSafe() { - const EPS = 0.000001; - this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi)); - return this; - } - setFromVector3(v) { - return this.setFromCartesianCoords(v.x, v.y, v.z); - } - setFromCartesianCoords(x, y, z) { - this.radius = Math.sqrt(x * x + y * y + z * z); - if (this.radius === 0) { - this.theta = 0; - this.phi = 0; - } else { - this.theta = Math.atan2(x, z); - this.phi = Math.acos(clamp(y / this.radius, -1, 1)); } - return this; - } - clone() { - return new this.constructor().copy(this); - } -} -const _vector$4 = /*@__PURE__*/new Vector2(); -class Box2 { - constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) { - this.isBox2 = true; - this.min = min; - this.max = max; - } - set(min, max) { - this.min.copy(min); - this.max.copy(max); - return this; - } - setFromPoints(points) { - this.makeEmpty(); - for (let i = 0, il = points.length; i < il; i++) { - this.expandByPoint(points[i]); + function convert( c ) { + + return _precision !== null ? c.toFixed( _precision ) : c; + } - return this; - } - setFromCenterAndSize(center, size) { - const halfSize = _vector$4.copy(size).multiplyScalar(0.5); - this.min.copy(center).sub(halfSize); - this.max.copy(center).add(halfSize); - return this; - } - clone() { - return new this.constructor().copy(this); - } - copy(box) { - this.min.copy(box.min); - this.max.copy(box.max); - return this; - } - makeEmpty() { - this.min.x = this.min.y = +Infinity; - this.max.x = this.max.y = -Infinity; - return this; - } - isEmpty() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return this.max.x < this.min.x || this.max.y < this.min.y; - } - getCenter(target) { - return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); - } - getSize(target) { - return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); - } - expandByPoint(point) { - this.min.min(point); - this.max.max(point); - return this; - } - expandByVector(vector) { - this.min.sub(vector); - this.max.add(vector); - return this; - } - expandByScalar(scalar) { - this.min.addScalar(-scalar); - this.max.addScalar(scalar); - return this; - } - containsPoint(point) { - return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true; - } - containsBox(box) { - return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; - } - getParameter(point, target) { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + this.clear = function () { - return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); - } - intersectsBox(box) { - // using 4 splitting planes to rule out intersections + removeChildNodes(); + _svg.style.backgroundColor = _clearColor.getStyle(); - return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - } - clampPoint(point, target) { - return target.copy(point).clamp(this.min, this.max); - } - distanceToPoint(point) { - const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max); - return clampedPoint.sub(point).length(); - } - intersect(box) { - this.min.max(box.min); - this.max.min(box.max); - return this; - } - union(box) { - this.min.min(box.min); - this.max.max(box.max); - return this; - } - translate(offset) { - this.min.add(offset); - this.max.add(offset); - return this; - } - equals(box) { - return box.min.equals(this.min) && box.max.equals(this.max); - } -} + }; -const _startP = /*@__PURE__*/new Vector3(); -const _startEnd = /*@__PURE__*/new Vector3(); -class Line3 { - constructor(start = new Vector3(), end = new Vector3()) { - this.start = start; - this.end = end; - } - set(start, end) { - this.start.copy(start); - this.end.copy(end); - return this; - } - copy(line) { - this.start.copy(line.start); - this.end.copy(line.end); - return this; - } - getCenter(target) { - return target.addVectors(this.start, this.end).multiplyScalar(0.5); - } - delta(target) { - return target.subVectors(this.end, this.start); - } - distanceSq() { - return this.start.distanceToSquared(this.end); - } - distance() { - return this.start.distanceTo(this.end); - } - at(t, target) { - return this.delta(target).multiplyScalar(t).add(this.start); - } - closestPointToPointParameter(point, clampToLine) { - _startP.subVectors(point, this.start); - _startEnd.subVectors(this.end, this.start); - const startEnd2 = _startEnd.dot(_startEnd); - const startEnd_startP = _startEnd.dot(_startP); - let t = startEnd_startP / startEnd2; - if (clampToLine) { - t = clamp(t, 0, 1); - } - return t; - } - closestPointToPoint(point, clampToLine, target) { - const t = this.closestPointToPointParameter(point, clampToLine); - return this.delta(target).multiplyScalar(t).add(this.start); - } - applyMatrix4(matrix) { - this.start.applyMatrix4(matrix); - this.end.applyMatrix4(matrix); - return this; - } - equals(line) { - return line.start.equals(this.start) && line.end.equals(this.end); - } - clone() { - return new this.constructor().copy(this); - } -} - -class GridHelper extends LineSegments { - constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) { - color1 = new Color$1(color1); - color2 = new Color$1(color2); - const center = divisions / 2; - const step = size / divisions; - const halfSize = size / 2; - const vertices = [], - colors = []; - for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) { - vertices.push(-halfSize, 0, k, halfSize, 0, k); - vertices.push(k, 0, -halfSize, k, 0, halfSize); - const color = i === center ? color1 : color2; - color.toArray(colors, j); - j += 3; - color.toArray(colors, j); - j += 3; - color.toArray(colors, j); - j += 3; - color.toArray(colors, j); - j += 3; - } - const geometry = new BufferGeometry(); - geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - geometry.setAttribute('color', new Float32BufferAttribute(colors, 3)); - const material = new LineBasicMaterial({ - vertexColors: true, - toneMapped: false - }); - super(geometry, material); - this.type = 'GridHelper'; - } - dispose() { - this.geometry.dispose(); - this.material.dispose(); - } -} + this.render = function ( scene, camera ) { -const _box = /*@__PURE__*/new Box3(); -class BoxHelper extends LineSegments { - constructor(object, color = 0xffff00) { - const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); - const positions = new Float32Array(8 * 3); - const geometry = new BufferGeometry(); - geometry.setIndex(new BufferAttribute(indices, 1)); - geometry.setAttribute('position', new BufferAttribute(positions, 3)); - super(geometry, new LineBasicMaterial({ - color: color, - toneMapped: false - })); - this.object = object; - this.type = 'BoxHelper'; - this.matrixAutoUpdate = false; - this.update(); - } - update(object) { - if (object !== undefined) { - console.warn('THREE.BoxHelper: .update() has no longer arguments.'); - } - if (this.object !== undefined) { - _box.setFromObject(this.object); - } - if (_box.isEmpty()) return; - const min = _box.min; - const max = _box.max; - - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ - 0: max.x, max.y, max.z - 1: min.x, max.y, max.z - 2: min.x, min.y, max.z - 3: max.x, min.y, max.z - 4: max.x, max.y, min.z - 5: min.x, max.y, min.z - 6: min.x, min.y, min.z - 7: max.x, min.y, min.z - */ - - const position = this.geometry.attributes.position; - const array = position.array; - array[0] = max.x; - array[1] = max.y; - array[2] = max.z; - array[3] = min.x; - array[4] = max.y; - array[5] = max.z; - array[6] = min.x; - array[7] = min.y; - array[8] = max.z; - array[9] = max.x; - array[10] = min.y; - array[11] = max.z; - array[12] = max.x; - array[13] = max.y; - array[14] = min.z; - array[15] = min.x; - array[16] = max.y; - array[17] = min.z; - array[18] = min.x; - array[19] = min.y; - array[20] = min.z; - array[21] = max.x; - array[22] = min.y; - array[23] = min.z; - position.needsUpdate = true; - this.geometry.computeBoundingSphere(); - } - setFromObject(object) { - this.object = object; - this.update(); - return this; - } - copy(source, recursive) { - super.copy(source, recursive); - this.object = source.object; - return this; - } - dispose() { - this.geometry.dispose(); - this.material.dispose(); - } -} + if ( camera instanceof Camera === false ) { -class AxesHelper extends LineSegments { - constructor(size = 1) { - const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size]; - const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1]; - const geometry = new BufferGeometry(); - geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3)); - geometry.setAttribute('color', new Float32BufferAttribute(colors, 3)); - const material = new LineBasicMaterial({ - vertexColors: true, - toneMapped: false - }); - super(geometry, material); - this.type = 'AxesHelper'; - } - setColors(xAxisColor, yAxisColor, zAxisColor) { - const color = new Color$1(); - const array = this.geometry.attributes.color.array; - color.set(xAxisColor); - color.toArray(array, 0); - color.toArray(array, 3); - color.set(yAxisColor); - color.toArray(array, 6); - color.toArray(array, 9); - color.set(zAxisColor); - color.toArray(array, 12); - color.toArray(array, 15); - this.geometry.attributes.color.needsUpdate = true; - return this; - } - dispose() { - this.geometry.dispose(); - this.material.dispose(); - } -} + console.error( 'THREE.SVGRenderer.render: camera is not an instance of Camera.' ); + return; -class ShapePath { - constructor() { - this.type = 'ShapePath'; - this.color = new Color$1(); - this.subPaths = []; - this.currentPath = null; - } - moveTo(x, y) { - this.currentPath = new Path(); - this.subPaths.push(this.currentPath); - this.currentPath.moveTo(x, y); - return this; - } - lineTo(x, y) { - this.currentPath.lineTo(x, y); - return this; - } - quadraticCurveTo(aCPx, aCPy, aX, aY) { - this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); - return this; - } - bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { - this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); - return this; - } - splineThru(pts) { - this.currentPath.splineThru(pts); - return this; - } - toShapes(isCCW) { - function toShapesNoHoles(inSubpaths) { - const shapes = []; - for (let i = 0, l = inSubpaths.length; i < l; i++) { - const tmpPath = inSubpaths[i]; - const tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push(tmpShape); } - return shapes; - } - function isPointInsidePolygon(inPt, inPolygon) { - const polyLen = inPolygon.length; - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - let inside = false; - for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) { - let edgeLowPt = inPolygon[p]; - let edgeHighPt = inPolygon[q]; - let edgeDx = edgeHighPt.x - edgeLowPt.x; - let edgeDy = edgeHighPt.y - edgeLowPt.y; - if (Math.abs(edgeDy) > Number.EPSILON) { - // not parallel - if (edgeDy < 0) { - edgeLowPt = inPolygon[q]; - edgeDx = -edgeDx; - edgeHighPt = inPolygon[p]; - edgeDy = -edgeDy; - } - if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue; - if (inPt.y === edgeLowPt.y) { - if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! - } else { - const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); - if (perpEdge === 0) return true; // inPt is on contour ? - if (perpEdge < 0) continue; - inside = !inside; // true intersection left of inPt - } - } else { - // parallel or collinear - if (inPt.y !== edgeLowPt.y) continue; // parallel - // edge lies on the same horizontal line as inPt - if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour ! - // continue; - } - } + const background = scene.background; - return inside; - } - const isClockWise = ShapeUtils.isClockWise; - const subPaths = this.subPaths; - if (subPaths.length === 0) return []; - let solid, tmpPath, tmpShape; - const shapes = []; - if (subPaths.length === 1) { - tmpPath = subPaths[0]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push(tmpShape); - return shapes; - } - let holesFirst = !isClockWise(subPaths[0].getPoints()); - holesFirst = isCCW ? !holesFirst : holesFirst; + if ( background && background.isColor ) { - // console.log("Holes first", holesFirst); + removeChildNodes(); + _svg.style.backgroundColor = background.getStyle(); - const betterShapeHoles = []; - const newShapes = []; - let newShapeHoles = []; - let mainIdx = 0; - let tmpPoints; - newShapes[mainIdx] = undefined; - newShapeHoles[mainIdx] = []; - for (let i = 0, l = subPaths.length; i < l; i++) { - tmpPath = subPaths[i]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise(tmpPoints); - solid = isCCW ? !solid : solid; - if (solid) { - if (!holesFirst && newShapes[mainIdx]) mainIdx++; - newShapes[mainIdx] = { - s: new Shape(), - p: tmpPoints - }; - newShapes[mainIdx].s.curves = tmpPath.curves; - if (holesFirst) mainIdx++; - newShapeHoles[mainIdx] = []; + } else if ( this.autoClear === true ) { - //console.log('cw', i); - } else { - newShapeHoles[mainIdx].push({ - h: tmpPath, - p: tmpPoints[0] - }); + this.clear(); - //console.log('ccw', i); } - } - // only Holes? -> probably all Shapes with wrong orientation - if (!newShapes[0]) return toShapesNoHoles(subPaths); - if (newShapes.length > 1) { - let ambiguous = false; - let toChange = 0; - for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { - betterShapeHoles[sIdx] = []; - } - for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { - const sho = newShapeHoles[sIdx]; - for (let hIdx = 0; hIdx < sho.length; hIdx++) { - const ho = sho[hIdx]; - let hole_unassigned = true; - for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) { - if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { - if (sIdx !== s2Idx) toChange++; - if (hole_unassigned) { - hole_unassigned = false; - betterShapeHoles[s2Idx].push(ho); - } else { - ambiguous = true; - } - } - } - if (hole_unassigned) { - betterShapeHoles[sIdx].push(ho); - } - } - } - if (toChange > 0 && ambiguous === false) { - newShapeHoles = betterShapeHoles; - } - } - let tmpHoles; - for (let i = 0, il = newShapes.length; i < il; i++) { - tmpShape = newShapes[i].s; - shapes.push(tmpShape); - tmpHoles = newShapeHoles[i]; - for (let j = 0, jl = tmpHoles.length; j < jl; j++) { - tmpShape.holes.push(tmpHoles[j].h); - } - } + _this.info.render.vertices = 0; + _this.info.render.faces = 0; + + _viewMatrix.copy( camera.matrixWorldInverse ); + _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix ); + + _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements ); + _elements = _renderData.elements; + _lights = _renderData.lights; + + _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse ); + + calculateLights( _lights ); + + // reset accumulated path + + _currentPath = ''; + _currentStyle = ''; + + for ( let e = 0, el = _elements.length; e < el; e ++ ) { + + const element = _elements[ e ]; + const material = element.material; + + if ( material === undefined || material.opacity === 0 ) continue; + + _elemBox.makeEmpty(); + + if ( element instanceof RenderableSprite ) { + + _v1 = element; + _v1.x *= _svgWidthHalf; _v1.y *= - _svgHeightHalf; + + renderSprite( _v1, element, material ); + + } else if ( element instanceof RenderableLine ) { + + _v1 = element.v1; _v2 = element.v2; + + _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf; + _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf; + + _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] ); + + if ( _clipBox.intersectsBox( _elemBox ) === true ) { - //console.log("shape", shapes); + renderLine( _v1, _v2, material ); - return shapes; - } -} + } -/** - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: , // how far from text outline (including bevelOffset) is bevel - * bevelOffset: // how far from text outline does bevel start - * } - */ -class TextGeometry extends ExtrudeGeometry { - constructor(text, parameters = {}) { - const font = parameters.font; - if (font === undefined) { - super(); // generate default extrude geometry - } else { - const shapes = font.generateShapes(text, parameters.size); + } else if ( element instanceof RenderableFace ) { - // translate parameters to ExtrudeGeometry API + _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; - parameters.depth = parameters.height !== undefined ? parameters.height : 50; + if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue; + if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue; + if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue; - // defaults + _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf; + _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf; + _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf; - if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10; - if (parameters.bevelSize === undefined) parameters.bevelSize = 8; - if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false; - super(shapes, parameters); - } - this.type = 'TextGeometry'; - } -} + if ( this.overdraw > 0 ) { -var glyphs={"0":{x_min:73,x_max:715,ha:792,o:"m 394 -29 q 153 129 242 -29 q 73 479 73 272 q 152 829 73 687 q 394 989 241 989 q 634 829 545 989 q 715 479 715 684 q 635 129 715 270 q 394 -29 546 -29 m 394 89 q 546 211 489 89 q 598 479 598 322 q 548 748 598 640 q 394 871 491 871 q 241 748 298 871 q 190 479 190 637 q 239 211 190 319 q 394 89 296 89 "},"1":{x_min:215.671875,x_max:574,ha:792,o:"m 574 0 l 442 0 l 442 697 l 215 697 l 215 796 q 386 833 330 796 q 475 986 447 875 l 574 986 l 574 0 "},"2":{x_min:59,x_max:731,ha:792,o:"m 731 0 l 59 0 q 197 314 59 188 q 457 487 199 315 q 598 691 598 580 q 543 819 598 772 q 411 867 488 867 q 272 811 328 867 q 209 630 209 747 l 81 630 q 182 901 81 805 q 408 986 271 986 q 629 909 536 986 q 731 694 731 826 q 613 449 731 541 q 378 316 495 383 q 201 122 235 234 l 731 122 l 731 0 "},"3":{x_min:54,x_max:737,ha:792,o:"m 737 284 q 635 55 737 141 q 399 -25 541 -25 q 156 52 248 -25 q 54 308 54 140 l 185 308 q 245 147 185 202 q 395 96 302 96 q 539 140 484 96 q 602 280 602 190 q 510 429 602 390 q 324 454 451 454 l 324 565 q 487 584 441 565 q 565 719 565 617 q 515 835 565 791 q 395 879 466 879 q 255 824 307 879 q 203 661 203 769 l 78 661 q 166 909 78 822 q 387 992 250 992 q 603 921 513 992 q 701 723 701 844 q 669 607 701 656 q 578 524 637 558 q 696 434 655 499 q 737 284 737 369 "},"4":{x_min:48,x_max:742.453125,ha:792,o:"m 742 243 l 602 243 l 602 0 l 476 0 l 476 243 l 48 243 l 48 368 l 476 958 l 602 958 l 602 354 l 742 354 l 742 243 m 476 354 l 476 792 l 162 354 l 476 354 "},"5":{x_min:54.171875,x_max:738,ha:792,o:"m 738 314 q 626 60 738 153 q 382 -23 526 -23 q 155 47 248 -23 q 54 256 54 125 l 183 256 q 259 132 204 174 q 382 91 314 91 q 533 149 471 91 q 602 314 602 213 q 538 469 602 411 q 386 528 475 528 q 284 506 332 528 q 197 439 237 484 l 81 439 l 159 958 l 684 958 l 684 840 l 254 840 l 214 579 q 306 627 258 612 q 407 643 354 643 q 636 552 540 643 q 738 314 738 457 "},"6":{x_min:53,x_max:739,ha:792,o:"m 739 312 q 633 62 739 162 q 400 -31 534 -31 q 162 78 257 -31 q 53 439 53 206 q 178 859 53 712 q 441 986 284 986 q 643 912 559 986 q 732 713 732 833 l 601 713 q 544 830 594 786 q 426 875 494 875 q 268 793 331 875 q 193 517 193 697 q 301 597 240 570 q 427 624 362 624 q 643 540 552 624 q 739 312 739 451 m 603 298 q 540 461 603 400 q 404 516 484 516 q 268 461 323 516 q 207 300 207 401 q 269 137 207 198 q 405 83 325 83 q 541 137 486 83 q 603 298 603 197 "},"7":{x_min:58.71875,x_max:730.953125,ha:792,o:"m 730 839 q 469 448 560 641 q 335 0 378 255 l 192 0 q 328 441 235 252 q 593 830 421 630 l 58 830 l 58 958 l 730 958 l 730 839 "},"8":{x_min:55,x_max:736,ha:792,o:"m 571 527 q 694 424 652 491 q 736 280 736 358 q 648 71 736 158 q 395 -26 551 -26 q 142 69 238 -26 q 55 279 55 157 q 96 425 55 359 q 220 527 138 491 q 120 615 153 562 q 88 726 88 668 q 171 904 88 827 q 395 986 261 986 q 618 905 529 986 q 702 727 702 830 q 670 616 702 667 q 571 527 638 565 m 394 565 q 519 610 475 565 q 563 717 563 655 q 521 823 563 781 q 392 872 474 872 q 265 824 312 872 q 224 720 224 783 q 265 613 224 656 q 394 565 312 565 m 395 91 q 545 150 488 91 q 597 280 597 204 q 546 408 597 355 q 395 465 492 465 q 244 408 299 465 q 194 280 194 356 q 244 150 194 203 q 395 91 299 91 "},"9":{x_min:53,x_max:739,ha:792,o:"m 739 524 q 619 94 739 241 q 362 -32 516 -32 q 150 47 242 -32 q 59 244 59 126 l 191 244 q 246 129 191 176 q 373 82 301 82 q 526 161 466 82 q 597 440 597 255 q 363 334 501 334 q 130 432 216 334 q 53 650 53 521 q 134 880 53 786 q 383 986 226 986 q 659 841 566 986 q 739 524 739 719 m 388 449 q 535 514 480 449 q 585 658 585 573 q 535 805 585 744 q 388 873 480 873 q 242 809 294 873 q 191 658 191 745 q 239 514 191 572 q 388 449 292 449 "},"ο":{x_min:0,x_max:712,ha:815,o:"m 356 -25 q 96 88 192 -25 q 0 368 0 201 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 "},S:{x_min:0,x_max:788,ha:890,o:"m 788 291 q 662 54 788 144 q 397 -26 550 -26 q 116 68 226 -26 q 0 337 0 168 l 131 337 q 200 152 131 220 q 384 85 269 85 q 557 129 479 85 q 650 270 650 183 q 490 429 650 379 q 194 513 341 470 q 33 739 33 584 q 142 964 33 881 q 388 1041 242 1041 q 644 957 543 1041 q 756 716 756 867 l 625 716 q 561 874 625 816 q 395 933 497 933 q 243 891 309 933 q 164 759 164 841 q 325 609 164 656 q 625 526 475 568 q 788 291 788 454 "},"¦":{x_min:343,x_max:449,ha:792,o:"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"/":{x_min:183.25,x_max:608.328125,ha:792,o:"m 608 1041 l 266 -129 l 183 -129 l 520 1041 l 608 1041 "},"Τ":{x_min:-0.4375,x_max:777.453125,ha:839,o:"m 777 893 l 458 893 l 458 0 l 319 0 l 319 892 l 0 892 l 0 1013 l 777 1013 l 777 893 "},y:{x_min:0,x_max:684.78125,ha:771,o:"m 684 738 l 388 -83 q 311 -216 356 -167 q 173 -279 252 -279 q 97 -266 133 -279 l 97 -149 q 132 -155 109 -151 q 168 -160 155 -160 q 240 -114 213 -160 q 274 -26 248 -98 l 0 738 l 137 737 l 341 139 l 548 737 l 684 738 "},"Π":{x_min:0,x_max:803,ha:917,o:"m 803 0 l 667 0 l 667 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 803 1012 l 803 0 "},"Î":{x_min:-111,x_max:339,ha:361,o:"m 339 800 l 229 800 l 229 925 l 339 925 l 339 800 m -1 800 l -111 800 l -111 925 l -1 925 l -1 800 m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 m 302 1040 l 113 819 l 30 819 l 165 1040 l 302 1040 "},g:{x_min:0,x_max:686,ha:838,o:"m 686 34 q 586 -213 686 -121 q 331 -306 487 -306 q 131 -252 216 -306 q 31 -84 31 -190 l 155 -84 q 228 -174 166 -138 q 345 -207 284 -207 q 514 -109 454 -207 q 564 89 564 -27 q 461 6 521 36 q 335 -23 401 -23 q 88 100 184 -23 q 0 370 0 215 q 87 634 0 522 q 330 758 183 758 q 457 728 398 758 q 564 644 515 699 l 564 737 l 686 737 l 686 34 m 582 367 q 529 560 582 481 q 358 652 468 652 q 189 561 250 652 q 135 369 135 482 q 189 176 135 255 q 361 85 251 85 q 529 176 468 85 q 582 367 582 255 "},"²":{x_min:0,x_max:442,ha:539,o:"m 442 383 l 0 383 q 91 566 0 492 q 260 668 176 617 q 354 798 354 727 q 315 875 354 845 q 227 905 277 905 q 136 869 173 905 q 99 761 99 833 l 14 761 q 82 922 14 864 q 232 974 141 974 q 379 926 316 974 q 442 797 442 878 q 351 635 442 704 q 183 539 321 611 q 92 455 92 491 l 442 455 l 442 383 "},"–":{x_min:0,x_max:705.5625,ha:803,o:"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},"Κ":{x_min:0,x_max:819.5625,ha:893,o:"m 819 0 l 650 0 l 294 509 l 139 356 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},"Æ’":{x_min:-46.265625,x_max:392,ha:513,o:"m 392 651 l 259 651 l 79 -279 l -46 -278 l 134 651 l 14 651 l 14 751 l 135 751 q 151 948 135 900 q 304 1041 185 1041 q 334 1040 319 1041 q 392 1034 348 1039 l 392 922 q 337 931 360 931 q 271 883 287 931 q 260 793 260 853 l 260 751 l 392 751 l 392 651 "},e:{x_min:0,x_max:714,ha:813,o:"m 714 326 l 140 326 q 200 157 140 227 q 359 87 260 87 q 488 130 431 87 q 561 245 545 174 l 697 245 q 577 48 670 123 q 358 -26 484 -26 q 97 85 195 -26 q 0 363 0 197 q 94 642 0 529 q 358 765 195 765 q 626 627 529 765 q 714 326 714 503 m 576 429 q 507 583 564 522 q 355 650 445 650 q 206 583 266 650 q 140 429 152 522 l 576 429 "},"ÏŒ":{x_min:0,x_max:712,ha:815,o:"m 356 -25 q 94 91 194 -25 q 0 368 0 202 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 m 576 1040 l 387 819 l 303 819 l 438 1040 l 576 1040 "},J:{x_min:0,x_max:588,ha:699,o:"m 588 279 q 287 -26 588 -26 q 58 73 126 -26 q 0 327 0 158 l 133 327 q 160 172 133 227 q 288 96 198 96 q 426 171 391 96 q 449 336 449 219 l 449 1013 l 588 1013 l 588 279 "},"»":{x_min:-1,x_max:503,ha:601,o:"m 503 302 l 280 136 l 281 256 l 429 373 l 281 486 l 280 608 l 503 440 l 503 302 m 221 302 l 0 136 l 0 255 l 145 372 l 0 486 l -1 608 l 221 440 l 221 302 "},"©":{x_min:-3,x_max:1008,ha:1106,o:"m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 741 394 q 661 246 731 302 q 496 190 591 190 q 294 285 369 190 q 228 497 228 370 q 295 714 228 625 q 499 813 370 813 q 656 762 588 813 q 733 625 724 711 l 634 625 q 589 704 629 673 q 498 735 550 735 q 377 666 421 735 q 334 504 334 597 q 374 340 334 408 q 490 272 415 272 q 589 304 549 272 q 638 394 628 337 l 741 394 "},"ÏŽ":{x_min:0,x_max:922,ha:1030,o:"m 687 1040 l 498 819 l 415 819 l 549 1040 l 687 1040 m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 338 0 202 q 45 551 0 444 q 161 737 84 643 l 302 737 q 175 552 219 647 q 124 336 124 446 q 155 179 124 248 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 341 797 257 q 745 555 797 450 q 619 737 705 637 l 760 737 q 874 551 835 640 q 922 339 922 444 "},"^":{x_min:193.0625,x_max:598.609375,ha:792,o:"m 598 772 l 515 772 l 395 931 l 277 772 l 193 772 l 326 1013 l 462 1013 l 598 772 "},"«":{x_min:0,x_max:507.203125,ha:604,o:"m 506 136 l 284 302 l 284 440 l 506 608 l 507 485 l 360 371 l 506 255 l 506 136 m 222 136 l 0 302 l 0 440 l 222 608 l 221 486 l 73 373 l 222 256 l 222 136 "},D:{x_min:0,x_max:828,ha:935,o:"m 389 1013 q 714 867 593 1013 q 828 521 828 729 q 712 161 828 309 q 382 0 587 0 l 0 0 l 0 1013 l 389 1013 m 376 124 q 607 247 523 124 q 681 510 681 355 q 607 771 681 662 q 376 896 522 896 l 139 896 l 139 124 l 376 124 "},"∙":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"ÿ":{x_min:0,x_max:47,ha:125,o:"m 47 3 q 37 -7 47 -7 q 28 0 30 -7 q 39 -4 32 -4 q 45 3 45 -1 l 37 0 q 28 9 28 0 q 39 19 28 19 l 47 16 l 47 19 l 47 3 m 37 1 q 44 8 44 1 q 37 16 44 16 q 30 8 30 16 q 37 1 30 1 m 26 1 l 23 22 l 14 0 l 3 22 l 3 3 l 0 25 l 13 1 l 22 25 l 26 1 "},w:{x_min:0,x_max:1009.71875,ha:1100,o:"m 1009 738 l 783 0 l 658 0 l 501 567 l 345 0 l 222 0 l 0 738 l 130 738 l 284 174 l 432 737 l 576 738 l 721 173 l 881 737 l 1009 738 "},$:{x_min:0,x_max:700,ha:793,o:"m 664 717 l 542 717 q 490 825 531 785 q 381 872 450 865 l 381 551 q 620 446 540 522 q 700 241 700 370 q 618 45 700 116 q 381 -25 536 -25 l 381 -152 l 307 -152 l 307 -25 q 81 62 162 -25 q 0 297 0 149 l 124 297 q 169 146 124 204 q 307 81 215 89 l 307 441 q 80 536 148 469 q 13 725 13 603 q 96 910 13 839 q 307 982 180 982 l 307 1077 l 381 1077 l 381 982 q 574 917 494 982 q 664 717 664 845 m 307 565 l 307 872 q 187 831 233 872 q 142 724 142 791 q 180 618 142 656 q 307 565 218 580 m 381 76 q 562 237 562 96 q 517 361 562 313 q 381 423 472 409 l 381 76 "},"\\":{x_min:-0.015625,x_max:425.0625,ha:522,o:"m 425 -129 l 337 -129 l 0 1041 l 83 1041 l 425 -129 "},"µ":{x_min:0,x_max:697.21875,ha:747,o:"m 697 -4 q 629 -14 658 -14 q 498 97 513 -14 q 422 9 470 41 q 313 -23 374 -23 q 207 4 258 -23 q 119 81 156 32 l 119 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 173 124 246 q 308 83 216 83 q 452 178 402 83 q 493 359 493 255 l 493 738 l 617 738 l 617 214 q 623 136 617 160 q 673 92 637 92 q 697 96 684 92 l 697 -4 "},"Ι":{x_min:42,x_max:181,ha:297,o:"m 181 0 l 42 0 l 42 1013 l 181 1013 l 181 0 "},"ÎŽ":{x_min:0,x_max:1144.5,ha:1214,o:"m 1144 1012 l 807 416 l 807 0 l 667 0 l 667 416 l 325 1012 l 465 1012 l 736 533 l 1004 1012 l 1144 1012 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"’":{x_min:0,x_max:139,ha:236,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"Î":{x_min:0,x_max:801,ha:915,o:"m 801 0 l 651 0 l 131 822 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 191 l 670 1013 l 801 1013 l 801 0 "},"-":{x_min:8.71875,x_max:350.390625,ha:478,o:"m 350 317 l 8 317 l 8 428 l 350 428 l 350 317 "},Q:{x_min:0,x_max:968,ha:1072,o:"m 954 5 l 887 -79 l 744 35 q 622 -11 687 2 q 483 -26 556 -26 q 127 130 262 -26 q 0 504 0 279 q 127 880 0 728 q 484 1041 262 1041 q 841 884 708 1041 q 968 507 968 735 q 933 293 968 398 q 832 104 899 188 l 954 5 m 723 191 q 802 330 777 248 q 828 499 828 412 q 744 790 828 673 q 483 922 650 922 q 228 791 322 922 q 142 505 142 673 q 227 221 142 337 q 487 91 323 91 q 632 123 566 91 l 520 215 l 587 301 l 723 191 "},"Ï‚":{x_min:1,x_max:676.28125,ha:740,o:"m 676 460 l 551 460 q 498 595 542 546 q 365 651 448 651 q 199 578 263 651 q 136 401 136 505 q 266 178 136 241 q 508 106 387 142 q 640 -50 640 62 q 625 -158 640 -105 q 583 -278 611 -211 l 465 -278 q 498 -182 490 -211 q 515 -80 515 -126 q 381 12 515 -15 q 134 91 197 51 q 1 388 1 179 q 100 651 1 542 q 354 761 199 761 q 587 680 498 761 q 676 460 676 599 "},M:{x_min:0,x_max:954,ha:1067,o:"m 954 0 l 819 0 l 819 869 l 537 0 l 405 0 l 128 866 l 128 0 l 0 0 l 0 1013 l 200 1013 l 472 160 l 757 1013 l 954 1013 l 954 0 "},"Ψ":{x_min:0,x_max:1006,ha:1094,o:"m 1006 678 q 914 319 1006 429 q 571 200 814 200 l 571 0 l 433 0 l 433 200 q 92 319 194 200 q 0 678 0 429 l 0 1013 l 139 1013 l 139 679 q 191 417 139 492 q 433 326 255 326 l 433 1013 l 571 1013 l 571 326 l 580 326 q 813 423 747 326 q 868 679 868 502 l 868 1013 l 1006 1013 l 1006 678 "},C:{x_min:0,x_max:886,ha:944,o:"m 886 379 q 760 87 886 201 q 455 -26 634 -26 q 112 136 236 -26 q 0 509 0 283 q 118 882 0 737 q 469 1041 245 1041 q 748 955 630 1041 q 879 708 879 859 l 745 708 q 649 862 724 805 q 473 920 573 920 q 219 791 312 920 q 136 509 136 675 q 217 229 136 344 q 470 99 311 99 q 672 179 591 99 q 753 379 753 259 l 886 379 "},"!":{x_min:0,x_max:138,ha:236,o:"m 138 684 q 116 409 138 629 q 105 244 105 299 l 33 244 q 16 465 33 313 q 0 684 0 616 l 0 1013 l 138 1013 l 138 684 m 138 0 l 0 0 l 0 151 l 138 151 l 138 0 "},"{":{x_min:0,x_max:480.5625,ha:578,o:"m 480 -286 q 237 -213 303 -286 q 187 -45 187 -159 q 194 48 187 -15 q 201 141 201 112 q 164 264 201 225 q 0 314 118 314 l 0 417 q 164 471 119 417 q 201 605 201 514 q 199 665 201 644 q 193 772 193 769 q 241 941 193 887 q 480 1015 308 1015 l 480 915 q 336 866 375 915 q 306 742 306 828 q 310 662 306 717 q 314 577 314 606 q 288 452 314 500 q 176 365 256 391 q 289 275 257 337 q 314 143 314 226 q 313 84 314 107 q 310 -11 310 -5 q 339 -131 310 -94 q 480 -182 377 -182 l 480 -286 "},X:{x_min:-0.015625,x_max:854.15625,ha:940,o:"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 428 637 l 675 1013 l 836 1013 l 504 520 l 854 0 "},"#":{x_min:0,x_max:963.890625,ha:1061,o:"m 963 690 l 927 590 l 719 590 l 655 410 l 876 410 l 840 310 l 618 310 l 508 -3 l 393 -2 l 506 309 l 329 310 l 215 -2 l 102 -3 l 212 310 l 0 310 l 36 410 l 248 409 l 312 590 l 86 590 l 120 690 l 347 690 l 459 1006 l 573 1006 l 462 690 l 640 690 l 751 1006 l 865 1006 l 754 690 l 963 690 m 606 590 l 425 590 l 362 410 l 543 410 l 606 590 "},"ι":{x_min:42,x_max:284,ha:361,o:"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 738 l 167 738 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 "},"Ά":{x_min:0,x_max:906.953125,ha:982,o:"m 283 1040 l 88 799 l 5 799 l 145 1040 l 283 1040 m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1012 l 529 1012 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},")":{x_min:0,x_max:318,ha:415,o:"m 318 365 q 257 25 318 191 q 87 -290 197 -141 l 0 -290 q 140 21 93 -128 q 193 360 193 189 q 141 704 193 537 q 0 1024 97 850 l 87 1024 q 257 706 197 871 q 318 365 318 542 "},"ε":{x_min:0,x_max:634.71875,ha:714,o:"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 314 0 265 q 128 390 67 353 q 56 460 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 "},"Δ":{x_min:0,x_max:952.78125,ha:1028,o:"m 952 0 l 0 0 l 400 1013 l 551 1013 l 952 0 m 762 124 l 476 867 l 187 124 l 762 124 "},"}":{x_min:0,x_max:481,ha:578,o:"m 481 314 q 318 262 364 314 q 282 136 282 222 q 284 65 282 97 q 293 -58 293 -48 q 241 -217 293 -166 q 0 -286 174 -286 l 0 -182 q 143 -130 105 -182 q 171 -2 171 -93 q 168 81 171 22 q 165 144 165 140 q 188 275 165 229 q 306 365 220 339 q 191 455 224 391 q 165 588 165 505 q 168 681 165 624 q 171 742 171 737 q 141 865 171 827 q 0 915 102 915 l 0 1015 q 243 942 176 1015 q 293 773 293 888 q 287 675 293 741 q 282 590 282 608 q 318 466 282 505 q 481 417 364 417 l 481 314 "},"‰":{x_min:-3,x_max:1672,ha:1821,o:"m 846 0 q 664 76 732 0 q 603 244 603 145 q 662 412 603 344 q 846 489 729 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 846 0 962 0 m 845 103 q 945 143 910 103 q 981 243 981 184 q 947 340 981 301 q 845 385 910 385 q 745 342 782 385 q 709 243 709 300 q 742 147 709 186 q 845 103 781 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 m 1428 0 q 1246 76 1314 0 q 1185 244 1185 145 q 1244 412 1185 344 q 1428 489 1311 489 q 1610 412 1542 489 q 1672 244 1672 343 q 1612 76 1672 144 q 1428 0 1545 0 m 1427 103 q 1528 143 1492 103 q 1564 243 1564 184 q 1530 340 1564 301 q 1427 385 1492 385 q 1327 342 1364 385 q 1291 243 1291 300 q 1324 147 1291 186 q 1427 103 1363 103 "},a:{x_min:0,x_max:698.609375,ha:794,o:"m 698 0 q 661 -12 679 -7 q 615 -17 643 -17 q 536 12 564 -17 q 500 96 508 41 q 384 6 456 37 q 236 -25 312 -25 q 65 31 130 -25 q 0 194 0 88 q 118 390 0 334 q 328 435 180 420 q 488 483 476 451 q 495 523 495 504 q 442 619 495 584 q 325 654 389 654 q 209 617 257 654 q 152 513 161 580 l 33 513 q 123 705 33 633 q 332 772 207 772 q 528 712 448 772 q 617 531 617 645 l 617 163 q 624 108 617 126 q 664 90 632 90 l 698 94 l 698 0 m 491 262 l 491 372 q 272 329 350 347 q 128 201 128 294 q 166 113 128 144 q 264 83 205 83 q 414 130 346 83 q 491 262 491 183 "},"—":{x_min:0,x_max:941.671875,ha:1039,o:"m 941 334 l 0 334 l 0 410 l 941 410 l 941 334 "},"=":{x_min:8.71875,x_max:780.953125,ha:792,o:"m 780 510 l 8 510 l 8 606 l 780 606 l 780 510 m 780 235 l 8 235 l 8 332 l 780 332 l 780 235 "},N:{x_min:0,x_max:801,ha:914,o:"m 801 0 l 651 0 l 131 823 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 193 l 670 1013 l 801 1013 l 801 0 "},"Ï":{x_min:0,x_max:712,ha:797,o:"m 712 369 q 620 94 712 207 q 362 -26 521 -26 q 230 2 292 -26 q 119 83 167 30 l 119 -278 l 0 -278 l 0 362 q 91 643 0 531 q 355 764 190 764 q 617 647 517 764 q 712 369 712 536 m 583 366 q 530 559 583 480 q 359 651 469 651 q 190 562 252 651 q 135 370 135 483 q 189 176 135 257 q 359 85 250 85 q 528 175 466 85 q 583 366 583 254 "},"¯":{x_min:0,x_max:941.671875,ha:938,o:"m 941 1033 l 0 1033 l 0 1109 l 941 1109 l 941 1033 "},Z:{x_min:0,x_max:779,ha:849,o:"m 779 0 l 0 0 l 0 113 l 621 896 l 40 896 l 40 1013 l 779 1013 l 778 887 l 171 124 l 779 124 l 779 0 "},u:{x_min:0,x_max:617,ha:729,o:"m 617 0 l 499 0 l 499 110 q 391 10 460 45 q 246 -25 322 -25 q 61 58 127 -25 q 0 258 0 136 l 0 738 l 125 738 l 125 284 q 156 148 125 202 q 273 82 197 82 q 433 165 369 82 q 493 340 493 243 l 493 738 l 617 738 l 617 0 "},k:{x_min:0,x_max:612.484375,ha:697,o:"m 612 738 l 338 465 l 608 0 l 469 0 l 251 382 l 121 251 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 402 l 456 738 l 612 738 "},"Η":{x_min:0,x_max:803,ha:917,o:"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"Α":{x_min:0,x_max:906.953125,ha:985,o:"m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},s:{x_min:0,x_max:604,ha:697,o:"m 604 217 q 501 36 604 104 q 292 -23 411 -23 q 86 43 166 -23 q 0 238 0 114 l 121 237 q 175 122 121 164 q 300 85 223 85 q 415 112 363 85 q 479 207 479 147 q 361 309 479 276 q 140 372 141 370 q 21 544 21 426 q 111 708 21 647 q 298 761 190 761 q 492 705 413 761 q 583 531 583 643 l 462 531 q 412 625 462 594 q 298 657 363 657 q 199 636 242 657 q 143 558 143 608 q 262 454 143 486 q 484 394 479 397 q 604 217 604 341 "},B:{x_min:0,x_max:778,ha:876,o:"m 580 546 q 724 469 670 535 q 778 311 778 403 q 673 83 778 171 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 892 q 691 633 732 693 q 580 546 650 572 m 393 899 l 139 899 l 139 588 l 379 588 q 521 624 462 588 q 592 744 592 667 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 303 635 219 q 559 436 635 389 q 402 477 494 477 l 139 477 l 139 124 l 419 124 "},"…":{x_min:0,x_max:614,ha:708,o:"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 m 378 0 l 236 0 l 236 151 l 378 151 l 378 0 m 614 0 l 472 0 l 472 151 l 614 151 l 614 0 "},"?":{x_min:0,x_max:607,ha:704,o:"m 607 777 q 543 599 607 674 q 422 474 482 537 q 357 272 357 391 l 236 272 q 297 487 236 395 q 411 619 298 490 q 474 762 474 691 q 422 885 474 838 q 301 933 371 933 q 179 880 228 933 q 124 706 124 819 l 0 706 q 94 963 0 872 q 302 1044 177 1044 q 511 973 423 1044 q 607 777 607 895 m 370 0 l 230 0 l 230 151 l 370 151 l 370 0 "},H:{x_min:0,x_max:803,ha:915,o:"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"ν":{x_min:0,x_max:675,ha:761,o:"m 675 738 l 404 0 l 272 0 l 0 738 l 133 738 l 340 147 l 541 738 l 675 738 "},c:{x_min:1,x_max:701.390625,ha:775,o:"m 701 264 q 584 53 681 133 q 353 -26 487 -26 q 91 91 188 -26 q 1 370 1 201 q 92 645 1 537 q 353 761 190 761 q 572 688 479 761 q 690 493 666 615 l 556 493 q 487 606 545 562 q 356 650 428 650 q 186 563 246 650 q 134 372 134 487 q 188 179 134 258 q 359 88 250 88 q 492 136 437 88 q 566 264 548 185 l 701 264 "},"¶":{x_min:0,x_max:566.671875,ha:678,o:"m 21 892 l 52 892 l 98 761 l 145 892 l 176 892 l 178 741 l 157 741 l 157 867 l 108 741 l 88 741 l 40 871 l 40 741 l 21 741 l 21 892 m 308 854 l 308 731 q 252 691 308 691 q 227 691 240 691 q 207 696 213 695 l 207 712 l 253 706 q 288 733 288 706 l 288 763 q 244 741 279 741 q 193 797 193 741 q 261 860 193 860 q 287 860 273 860 q 308 854 302 855 m 288 842 l 263 843 q 213 796 213 843 q 248 756 213 756 q 288 796 288 756 l 288 842 m 566 988 l 502 988 l 502 -1 l 439 -1 l 439 988 l 317 988 l 317 -1 l 252 -1 l 252 602 q 81 653 155 602 q 0 805 0 711 q 101 989 0 918 q 309 1053 194 1053 l 566 1053 l 566 988 "},"β":{x_min:0,x_max:660,ha:745,o:"m 471 550 q 610 450 561 522 q 660 280 660 378 q 578 64 660 151 q 367 -22 497 -22 q 239 5 299 -22 q 126 82 178 32 l 126 -278 l 0 -278 l 0 593 q 54 903 0 801 q 318 1042 127 1042 q 519 964 436 1042 q 603 771 603 887 q 567 644 603 701 q 471 550 532 586 m 337 79 q 476 138 418 79 q 535 279 535 198 q 427 437 535 386 q 226 477 344 477 l 226 583 q 398 620 329 583 q 486 762 486 668 q 435 884 486 833 q 312 935 384 935 q 169 861 219 935 q 126 698 126 797 l 126 362 q 170 169 126 242 q 337 79 224 79 "},"Îœ":{x_min:0,x_max:954,ha:1068,o:"m 954 0 l 819 0 l 819 868 l 537 0 l 405 0 l 128 865 l 128 0 l 0 0 l 0 1013 l 199 1013 l 472 158 l 758 1013 l 954 1013 l 954 0 "},"ÎŒ":{x_min:0.109375,x_max:1120,ha:1217,o:"m 1120 505 q 994 132 1120 282 q 642 -29 861 -29 q 290 130 422 -29 q 167 505 167 280 q 294 883 167 730 q 650 1046 430 1046 q 999 882 868 1046 q 1120 505 1120 730 m 977 504 q 896 784 977 669 q 644 915 804 915 q 391 785 484 915 q 307 504 307 669 q 391 224 307 339 q 644 95 486 95 q 894 224 803 95 q 977 504 977 339 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Ή":{x_min:0,x_max:1158,ha:1275,o:"m 1158 0 l 1022 0 l 1022 475 l 496 475 l 496 0 l 356 0 l 356 1012 l 496 1012 l 496 599 l 1022 599 l 1022 1012 l 1158 1012 l 1158 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"•":{x_min:0,x_max:663.890625,ha:775,o:"m 663 529 q 566 293 663 391 q 331 196 469 196 q 97 294 194 196 q 0 529 0 393 q 96 763 0 665 q 331 861 193 861 q 566 763 469 861 q 663 529 663 665 "},"Â¥":{x_min:0.1875,x_max:819.546875,ha:886,o:"m 563 561 l 697 561 l 696 487 l 520 487 l 482 416 l 482 380 l 697 380 l 695 308 l 482 308 l 482 0 l 342 0 l 342 308 l 125 308 l 125 380 l 342 380 l 342 417 l 303 487 l 125 487 l 125 561 l 258 561 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 l 563 561 "},"(":{x_min:0,x_max:318.0625,ha:415,o:"m 318 -290 l 230 -290 q 61 23 122 -142 q 0 365 0 190 q 62 712 0 540 q 230 1024 119 869 l 318 1024 q 175 705 219 853 q 125 360 125 542 q 176 22 125 187 q 318 -290 223 -127 "},U:{x_min:0,x_max:796,ha:904,o:"m 796 393 q 681 93 796 212 q 386 -25 566 -25 q 101 95 208 -25 q 0 393 0 211 l 0 1013 l 138 1013 l 138 391 q 204 191 138 270 q 394 107 276 107 q 586 191 512 107 q 656 391 656 270 l 656 1013 l 796 1013 l 796 393 "},"γ":{x_min:0.5,x_max:744.953125,ha:822,o:"m 744 737 l 463 54 l 463 -278 l 338 -278 l 338 54 l 154 495 q 104 597 124 569 q 13 651 67 651 l 0 651 l 0 751 l 39 753 q 168 711 121 753 q 242 594 207 676 l 403 208 l 617 737 l 744 737 "},"α":{x_min:0,x_max:765.5625,ha:809,o:"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 728 407 760 q 563 637 524 696 l 563 739 l 685 739 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 96 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 "},F:{x_min:0,x_max:683.328125,ha:717,o:"m 683 888 l 140 888 l 140 583 l 613 583 l 613 458 l 140 458 l 140 0 l 0 0 l 0 1013 l 683 1013 l 683 888 "},"­":{x_min:0,x_max:705.5625,ha:803,o:"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},":":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"Χ":{x_min:0,x_max:854.171875,ha:935,o:"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 427 637 l 675 1013 l 836 1013 l 504 521 l 854 0 "},"*":{x_min:116,x_max:674,ha:792,o:"m 674 768 l 475 713 l 610 544 l 517 477 l 394 652 l 272 478 l 178 544 l 314 713 l 116 766 l 153 876 l 341 812 l 342 1013 l 446 1013 l 446 811 l 635 874 l 674 768 "},"†":{x_min:0,x_max:777,ha:835,o:"m 458 804 l 777 804 l 777 683 l 458 683 l 458 0 l 319 0 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 "},"°":{x_min:0,x_max:347,ha:444,o:"m 173 802 q 43 856 91 802 q 0 977 0 905 q 45 1101 0 1049 q 173 1153 90 1153 q 303 1098 255 1153 q 347 977 347 1049 q 303 856 347 905 q 173 802 256 802 m 173 884 q 238 910 214 884 q 262 973 262 937 q 239 1038 262 1012 q 173 1064 217 1064 q 108 1037 132 1064 q 85 973 85 1010 q 108 910 85 937 q 173 884 132 884 "},V:{x_min:0,x_max:862.71875,ha:940,o:"m 862 1013 l 505 0 l 361 0 l 0 1013 l 143 1013 l 434 165 l 718 1012 l 862 1013 "},"Ξ":{x_min:0,x_max:734.71875,ha:763,o:"m 723 889 l 9 889 l 9 1013 l 723 1013 l 723 889 m 673 463 l 61 463 l 61 589 l 673 589 l 673 463 m 734 0 l 0 0 l 0 124 l 734 124 l 734 0 "}," ":{x_min:0,x_max:0,ha:853},"Ϋ":{x_min:0.328125,x_max:819.515625,ha:889,o:"m 588 1046 l 460 1046 l 460 1189 l 588 1189 l 588 1046 m 360 1046 l 232 1046 l 232 1189 l 360 1189 l 360 1046 m 819 1012 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1012 l 140 1012 l 411 533 l 679 1012 l 819 1012 "},"â€":{x_min:0,x_max:347,ha:454,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 m 347 851 q 310 737 347 784 q 208 669 273 690 l 208 734 q 267 787 250 741 q 280 873 280 821 l 208 873 l 208 1013 l 347 1013 l 347 851 "},"@":{x_min:0,x_max:1260,ha:1357,o:"m 1098 -45 q 877 -160 1001 -117 q 633 -203 752 -203 q 155 -29 327 -203 q 0 360 0 127 q 176 802 0 616 q 687 1008 372 1008 q 1123 854 969 1008 q 1260 517 1260 718 q 1155 216 1260 341 q 868 82 1044 82 q 772 106 801 82 q 737 202 737 135 q 647 113 700 144 q 527 82 594 82 q 367 147 420 82 q 314 312 314 212 q 401 565 314 452 q 639 690 498 690 q 810 588 760 690 l 849 668 l 938 668 q 877 441 900 532 q 833 226 833 268 q 853 182 833 198 q 902 167 873 167 q 1088 272 1012 167 q 1159 512 1159 372 q 1051 793 1159 681 q 687 925 925 925 q 248 747 415 925 q 97 361 97 586 q 226 26 97 159 q 627 -122 370 -122 q 856 -87 737 -122 q 1061 8 976 -53 l 1098 -45 m 786 488 q 738 580 777 545 q 643 615 700 615 q 483 517 548 615 q 425 322 425 430 q 457 203 425 250 q 552 156 490 156 q 722 273 665 156 q 786 488 738 309 "},"Ί":{x_min:0,x_max:499,ha:613,o:"m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 m 499 0 l 360 0 l 360 1012 l 499 1012 l 499 0 "},i:{x_min:14,x_max:136,ha:275,o:"m 136 873 l 14 873 l 14 1013 l 136 1013 l 136 873 m 136 0 l 14 0 l 14 737 l 136 737 l 136 0 "},"Î’":{x_min:0,x_max:778,ha:877,o:"m 580 545 q 724 468 671 534 q 778 310 778 402 q 673 83 778 170 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 891 q 691 632 732 692 q 580 545 650 571 m 393 899 l 139 899 l 139 587 l 379 587 q 521 623 462 587 q 592 744 592 666 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 302 635 219 q 559 435 635 388 q 402 476 494 476 l 139 476 l 139 124 l 419 124 "},"Ï…":{x_min:0,x_max:617,ha:725,o:"m 617 352 q 540 94 617 199 q 308 -24 455 -24 q 76 94 161 -24 q 0 352 0 199 l 0 739 l 126 739 l 126 355 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 355 492 257 l 492 739 l 617 739 l 617 352 "},"]":{x_min:0,x_max:275,ha:372,o:"m 275 -281 l 0 -281 l 0 -187 l 151 -187 l 151 920 l 0 920 l 0 1013 l 275 1013 l 275 -281 "},m:{x_min:0,x_max:1019,ha:1128,o:"m 1019 0 l 897 0 l 897 454 q 860 591 897 536 q 739 660 816 660 q 613 586 659 660 q 573 436 573 522 l 573 0 l 447 0 l 447 455 q 412 591 447 535 q 294 657 372 657 q 165 586 213 657 q 122 437 122 521 l 122 0 l 0 0 l 0 738 l 117 738 l 117 640 q 202 730 150 697 q 316 763 254 763 q 437 730 381 763 q 525 642 494 697 q 621 731 559 700 q 753 763 682 763 q 943 694 867 763 q 1019 512 1019 625 l 1019 0 "},"χ":{x_min:8.328125,x_max:780.5625,ha:815,o:"m 780 -278 q 715 -294 747 -294 q 616 -257 663 -294 q 548 -175 576 -227 l 379 133 l 143 -277 l 9 -277 l 313 254 l 163 522 q 127 586 131 580 q 36 640 91 640 q 8 637 27 640 l 8 752 l 52 757 q 162 719 113 757 q 236 627 200 690 l 383 372 l 594 737 l 726 737 l 448 250 l 625 -69 q 670 -153 647 -110 q 743 -188 695 -188 q 780 -184 759 -188 l 780 -278 "},"ί":{x_min:42,x_max:326.71875,ha:361,o:"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 102 239 101 q 284 112 257 104 l 284 3 m 326 1040 l 137 819 l 54 819 l 189 1040 l 326 1040 "},"Ζ":{x_min:0,x_max:779.171875,ha:850,o:"m 779 0 l 0 0 l 0 113 l 620 896 l 40 896 l 40 1013 l 779 1013 l 779 887 l 170 124 l 779 124 l 779 0 "},R:{x_min:0,x_max:781.953125,ha:907,o:"m 781 0 l 623 0 q 587 242 590 52 q 407 433 585 433 l 138 433 l 138 0 l 0 0 l 0 1013 l 396 1013 q 636 946 539 1013 q 749 731 749 868 q 711 597 749 659 q 608 502 674 534 q 718 370 696 474 q 729 207 722 352 q 781 26 736 62 l 781 0 m 373 551 q 533 594 465 551 q 614 731 614 645 q 532 859 614 815 q 373 896 465 896 l 138 896 l 138 551 l 373 551 "},o:{x_min:0,x_max:713,ha:821,o:"m 357 -25 q 94 91 194 -25 q 0 368 0 202 q 93 642 0 533 q 357 761 193 761 q 618 644 518 761 q 713 368 713 533 q 619 91 713 201 q 357 -25 521 -25 m 357 85 q 528 175 465 85 q 584 369 584 255 q 529 562 584 484 q 357 651 467 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 357 85 250 85 "},K:{x_min:0,x_max:819.46875,ha:906,o:"m 819 0 l 649 0 l 294 509 l 139 355 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},",":{x_min:0,x_max:142,ha:239,o:"m 142 -12 q 105 -132 142 -82 q 0 -205 68 -182 l 0 -138 q 57 -82 40 -124 q 70 0 70 -51 l 0 0 l 0 151 l 142 151 l 142 -12 "},d:{x_min:0,x_max:683,ha:796,o:"m 683 0 l 564 0 l 564 93 q 456 6 516 38 q 327 -25 395 -25 q 87 100 181 -25 q 0 365 0 215 q 90 639 0 525 q 343 763 187 763 q 564 647 486 763 l 564 1013 l 683 1013 l 683 0 m 582 373 q 529 562 582 484 q 361 653 468 653 q 190 561 253 653 q 135 365 135 479 q 189 175 135 254 q 358 85 251 85 q 529 178 468 85 q 582 373 582 258 "},"¨":{x_min:-109,x_max:247,ha:232,o:"m 247 1046 l 119 1046 l 119 1189 l 247 1189 l 247 1046 m 19 1046 l -109 1046 l -109 1189 l 19 1189 l 19 1046 "},E:{x_min:0,x_max:736.109375,ha:789,o:"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},Y:{x_min:0,x_max:820,ha:886,o:"m 820 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 534 l 679 1012 l 820 1013 "},"\"":{x_min:0,x_max:299,ha:396,o:"m 299 606 l 203 606 l 203 988 l 299 988 l 299 606 m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"‹":{x_min:17.984375,x_max:773.609375,ha:792,o:"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"„":{x_min:0,x_max:364,ha:467,o:"m 141 -12 q 104 -132 141 -82 q 0 -205 67 -182 l 0 -138 q 56 -82 40 -124 q 69 0 69 -51 l 0 0 l 0 151 l 141 151 l 141 -12 m 364 -12 q 327 -132 364 -82 q 222 -205 290 -182 l 222 -138 q 279 -82 262 -124 q 292 0 292 -51 l 222 0 l 222 151 l 364 151 l 364 -12 "},"δ":{x_min:1,x_max:710,ha:810,o:"m 710 360 q 616 87 710 196 q 356 -28 518 -28 q 99 82 197 -28 q 1 356 1 192 q 100 606 1 509 q 355 703 199 703 q 180 829 288 754 q 70 903 124 866 l 70 1012 l 643 1012 l 643 901 l 258 901 q 462 763 422 794 q 636 592 577 677 q 710 360 710 485 m 584 365 q 552 501 584 447 q 451 602 521 555 q 372 611 411 611 q 197 541 258 611 q 136 355 136 472 q 190 171 136 245 q 358 85 252 85 q 528 173 465 85 q 584 365 584 252 "},"έ":{x_min:0,x_max:634.71875,ha:714,o:"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 313 0 265 q 128 390 67 352 q 56 459 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 m 520 1040 l 331 819 l 248 819 l 383 1040 l 520 1040 "},"ω":{x_min:0,x_max:922,ha:1031,o:"m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 339 0 203 q 45 551 0 444 q 161 738 84 643 l 302 738 q 175 553 219 647 q 124 336 124 446 q 155 179 124 249 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 342 797 257 q 745 556 797 450 q 619 738 705 638 l 760 738 q 874 551 835 640 q 922 339 922 444 "},"´":{x_min:0,x_max:96,ha:251,o:"m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"±":{x_min:11,x_max:781,ha:792,o:"m 781 490 l 446 490 l 446 255 l 349 255 l 349 490 l 11 490 l 11 586 l 349 586 l 349 819 l 446 819 l 446 586 l 781 586 l 781 490 m 781 21 l 11 21 l 11 115 l 781 115 l 781 21 "},"|":{x_min:343,x_max:449,ha:792,o:"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"Ï‹":{x_min:0,x_max:617,ha:725,o:"m 482 800 l 372 800 l 372 925 l 482 925 l 482 800 m 239 800 l 129 800 l 129 925 l 239 925 l 239 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 "},"§":{x_min:0,x_max:593,ha:690,o:"m 593 425 q 554 312 593 369 q 467 233 516 254 q 537 83 537 172 q 459 -74 537 -12 q 288 -133 387 -133 q 115 -69 184 -133 q 47 96 47 -6 l 166 96 q 199 7 166 40 q 288 -26 232 -26 q 371 -5 332 -26 q 420 60 420 21 q 311 201 420 139 q 108 309 210 255 q 0 490 0 383 q 33 602 0 551 q 124 687 66 654 q 75 743 93 712 q 58 812 58 773 q 133 984 58 920 q 300 1043 201 1043 q 458 987 394 1043 q 529 814 529 925 l 411 814 q 370 908 404 877 q 289 939 336 939 q 213 911 246 939 q 180 841 180 883 q 286 720 180 779 q 484 612 480 615 q 593 425 593 534 m 467 409 q 355 544 467 473 q 196 630 228 612 q 146 587 162 609 q 124 525 124 558 q 239 387 124 462 q 398 298 369 315 q 448 345 429 316 q 467 409 467 375 "},b:{x_min:0,x_max:685,ha:783,o:"m 685 372 q 597 99 685 213 q 347 -25 501 -25 q 219 5 277 -25 q 121 93 161 36 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 634 q 214 723 157 692 q 341 754 272 754 q 591 637 493 754 q 685 372 685 526 m 554 356 q 499 550 554 470 q 328 644 437 644 q 162 556 223 644 q 108 369 108 478 q 160 176 108 256 q 330 83 221 83 q 498 169 435 83 q 554 356 554 245 "},q:{x_min:0,x_max:683,ha:876,o:"m 683 -278 l 564 -278 l 564 97 q 474 8 533 39 q 345 -23 415 -23 q 91 93 188 -23 q 0 364 0 203 q 87 635 0 522 q 337 760 184 760 q 466 727 408 760 q 564 637 523 695 l 564 737 l 683 737 l 683 -278 m 582 375 q 527 564 582 488 q 358 652 466 652 q 190 565 253 652 q 135 377 135 488 q 189 179 135 261 q 361 84 251 84 q 530 179 469 84 q 582 375 582 260 "},"Ω":{x_min:-0.171875,x_max:969.5625,ha:1068,o:"m 969 0 l 555 0 l 555 123 q 744 308 675 194 q 814 558 814 423 q 726 812 814 709 q 484 922 633 922 q 244 820 334 922 q 154 567 154 719 q 223 316 154 433 q 412 123 292 199 l 412 0 l 0 0 l 0 124 l 217 124 q 68 327 122 210 q 15 572 15 444 q 144 911 15 781 q 484 1041 274 1041 q 822 909 691 1041 q 953 569 953 777 q 899 326 953 443 q 750 124 846 210 l 969 124 l 969 0 "},"Ï":{x_min:0,x_max:617,ha:725,o:"m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 535 1040 l 346 819 l 262 819 l 397 1040 l 535 1040 "},z:{x_min:-0.015625,x_max:613.890625,ha:697,o:"m 613 0 l 0 0 l 0 100 l 433 630 l 20 630 l 20 738 l 594 738 l 593 636 l 163 110 l 613 110 l 613 0 "},"â„¢":{x_min:0,x_max:894,ha:1000,o:"m 389 951 l 229 951 l 229 503 l 160 503 l 160 951 l 0 951 l 0 1011 l 389 1011 l 389 951 m 894 503 l 827 503 l 827 939 l 685 503 l 620 503 l 481 937 l 481 503 l 417 503 l 417 1011 l 517 1011 l 653 580 l 796 1010 l 894 1011 l 894 503 "},"ή":{x_min:0.78125,x_max:697,ha:810,o:"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 721 124 755 q 200 630 193 687 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 m 479 1040 l 290 819 l 207 819 l 341 1040 l 479 1040 "},"Θ":{x_min:0,x_max:960,ha:1056,o:"m 960 507 q 833 129 960 280 q 476 -32 698 -32 q 123 129 255 -32 q 0 507 0 280 q 123 883 0 732 q 476 1045 255 1045 q 832 883 696 1045 q 960 507 960 732 m 817 500 q 733 789 817 669 q 476 924 639 924 q 223 792 317 924 q 142 507 142 675 q 222 222 142 339 q 476 89 315 89 q 730 218 636 89 q 817 500 817 334 m 716 449 l 243 449 l 243 571 l 716 571 l 716 449 "},"®":{x_min:-3,x_max:1008,ha:1106,o:"m 503 532 q 614 562 566 532 q 672 658 672 598 q 614 747 672 716 q 503 772 569 772 l 338 772 l 338 532 l 503 532 m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 788 146 l 678 146 q 653 316 655 183 q 527 449 652 449 l 338 449 l 338 146 l 241 146 l 241 854 l 518 854 q 688 808 621 854 q 766 658 766 755 q 739 563 766 607 q 668 497 713 519 q 751 331 747 472 q 788 164 756 190 l 788 146 "},"~":{x_min:0,x_max:833,ha:931,o:"m 833 958 q 778 753 833 831 q 594 665 716 665 q 402 761 502 665 q 240 857 302 857 q 131 795 166 857 q 104 665 104 745 l 0 665 q 54 867 0 789 q 237 958 116 958 q 429 861 331 958 q 594 765 527 765 q 704 827 670 765 q 729 958 729 874 l 833 958 "},"Ε":{x_min:0,x_max:736.21875,ha:778,o:"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},"³":{x_min:0,x_max:450,ha:547,o:"m 450 552 q 379 413 450 464 q 220 366 313 366 q 69 414 130 366 q 0 567 0 470 l 85 567 q 126 470 85 504 q 225 437 168 437 q 320 467 280 437 q 360 552 360 498 q 318 632 360 608 q 213 657 276 657 q 195 657 203 657 q 176 657 181 657 l 176 722 q 279 733 249 722 q 334 815 334 752 q 300 881 334 856 q 220 907 267 907 q 133 875 169 907 q 97 781 97 844 l 15 781 q 78 926 15 875 q 220 972 135 972 q 364 930 303 972 q 426 817 426 888 q 344 697 426 733 q 421 642 392 681 q 450 552 450 603 "},"[":{x_min:0,x_max:273.609375,ha:371,o:"m 273 -281 l 0 -281 l 0 1013 l 273 1013 l 273 920 l 124 920 l 124 -187 l 273 -187 l 273 -281 "},L:{x_min:0,x_max:645.828125,ha:696,o:"m 645 0 l 0 0 l 0 1013 l 140 1013 l 140 126 l 645 126 l 645 0 "},"σ":{x_min:0,x_max:803.390625,ha:894,o:"m 803 628 l 633 628 q 713 368 713 512 q 618 93 713 204 q 357 -25 518 -25 q 94 91 194 -25 q 0 368 0 201 q 94 644 0 533 q 356 761 194 761 q 481 750 398 761 q 608 739 564 739 l 803 739 l 803 628 m 360 85 q 529 180 467 85 q 584 374 584 262 q 527 566 584 490 q 352 651 463 651 q 187 559 247 651 q 135 368 135 478 q 189 175 135 254 q 360 85 251 85 "},"ζ":{x_min:0,x_max:573,ha:642,o:"m 573 -40 q 553 -162 573 -97 q 510 -278 543 -193 l 400 -278 q 441 -187 428 -219 q 462 -90 462 -132 q 378 -14 462 -14 q 108 45 197 -14 q 0 290 0 117 q 108 631 0 462 q 353 901 194 767 l 55 901 l 55 1012 l 561 1012 l 561 924 q 261 669 382 831 q 128 301 128 489 q 243 117 128 149 q 458 98 350 108 q 573 -40 573 80 "},"θ":{x_min:0,x_max:674,ha:778,o:"m 674 496 q 601 160 674 304 q 336 -26 508 -26 q 73 153 165 -26 q 0 485 0 296 q 72 840 0 683 q 343 1045 166 1045 q 605 844 516 1045 q 674 496 674 692 m 546 579 q 498 798 546 691 q 336 935 437 935 q 178 798 237 935 q 126 579 137 701 l 546 579 m 546 475 l 126 475 q 170 233 126 348 q 338 80 230 80 q 504 233 447 80 q 546 475 546 346 "},"Ο":{x_min:0,x_max:958,ha:1054,o:"m 485 1042 q 834 883 703 1042 q 958 511 958 735 q 834 136 958 287 q 481 -26 701 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 729 q 485 1042 263 1042 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 670 q 480 913 640 913 q 226 785 321 913 q 142 504 142 671 q 226 224 142 339 q 480 98 319 98 "},"Γ":{x_min:0,x_max:705.28125,ha:749,o:"m 705 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 705 1012 l 705 886 "}," ":{x_min:0,x_max:0,ha:375},"%":{x_min:-3,x_max:1089,ha:1186,o:"m 845 0 q 663 76 731 0 q 602 244 602 145 q 661 412 602 344 q 845 489 728 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 845 0 962 0 m 844 103 q 945 143 909 103 q 981 243 981 184 q 947 340 981 301 q 844 385 909 385 q 744 342 781 385 q 708 243 708 300 q 741 147 708 186 q 844 103 780 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 "},P:{x_min:0,x_max:726,ha:806,o:"m 424 1013 q 640 931 555 1013 q 726 719 726 850 q 637 506 726 587 q 413 426 548 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 379 889 l 140 889 l 140 548 l 372 548 q 522 589 459 548 q 593 720 593 637 q 528 845 593 801 q 379 889 463 889 "},"Έ":{x_min:0,x_max:1078.21875,ha:1118,o:"m 1078 0 l 342 0 l 342 1013 l 1067 1013 l 1067 889 l 481 889 l 481 585 l 1019 585 l 1019 467 l 481 467 l 481 125 l 1078 125 l 1078 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Î":{x_min:0.125,x_max:1136.546875,ha:1235,o:"m 1136 0 l 722 0 l 722 123 q 911 309 842 194 q 981 558 981 423 q 893 813 981 710 q 651 923 800 923 q 411 821 501 923 q 321 568 321 720 q 390 316 321 433 q 579 123 459 200 l 579 0 l 166 0 l 166 124 l 384 124 q 235 327 289 210 q 182 572 182 444 q 311 912 182 782 q 651 1042 441 1042 q 989 910 858 1042 q 1120 569 1120 778 q 1066 326 1120 443 q 917 124 1013 210 l 1136 124 l 1136 0 m 277 1040 l 83 800 l 0 800 l 140 1041 l 277 1040 "},_:{x_min:0,x_max:705.5625,ha:803,o:"m 705 -334 l 0 -334 l 0 -234 l 705 -234 l 705 -334 "},"Ϊ":{x_min:-110,x_max:246,ha:275,o:"m 246 1046 l 118 1046 l 118 1189 l 246 1189 l 246 1046 m 18 1046 l -110 1046 l -110 1189 l 18 1189 l 18 1046 m 136 0 l 0 0 l 0 1012 l 136 1012 l 136 0 "},"+":{x_min:23,x_max:768,ha:792,o:"m 768 372 l 444 372 l 444 0 l 347 0 l 347 372 l 23 372 l 23 468 l 347 468 l 347 840 l 444 840 l 444 468 l 768 468 l 768 372 "},"½":{x_min:0,x_max:1050,ha:1149,o:"m 1050 0 l 625 0 q 712 178 625 108 q 878 277 722 187 q 967 385 967 328 q 932 456 967 429 q 850 484 897 484 q 759 450 798 484 q 721 352 721 416 l 640 352 q 706 502 640 448 q 851 551 766 551 q 987 509 931 551 q 1050 385 1050 462 q 976 251 1050 301 q 829 179 902 215 q 717 68 740 133 l 1050 68 l 1050 0 m 834 985 l 215 -28 l 130 -28 l 750 984 l 834 985 m 224 422 l 142 422 l 142 811 l 0 811 l 0 867 q 104 889 62 867 q 164 973 157 916 l 224 973 l 224 422 "},"Ρ":{x_min:0,x_max:720,ha:783,o:"m 424 1013 q 637 933 554 1013 q 720 723 720 853 q 633 508 720 591 q 413 426 546 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 378 889 l 140 889 l 140 548 l 371 548 q 521 589 458 548 q 592 720 592 637 q 527 845 592 801 q 378 889 463 889 "},"'":{x_min:0,x_max:139,ha:236,o:"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"ª":{x_min:0,x_max:350,ha:397,o:"m 350 625 q 307 616 328 616 q 266 631 281 616 q 247 673 251 645 q 190 628 225 644 q 116 613 156 613 q 32 641 64 613 q 0 722 0 669 q 72 826 0 800 q 247 866 159 846 l 247 887 q 220 934 247 916 q 162 953 194 953 q 104 934 129 953 q 76 882 80 915 l 16 882 q 60 976 16 941 q 166 1011 104 1011 q 266 979 224 1011 q 308 891 308 948 l 308 706 q 311 679 308 688 q 331 670 315 670 l 350 672 l 350 625 m 247 757 l 247 811 q 136 790 175 798 q 64 726 64 773 q 83 682 64 697 q 132 667 103 667 q 207 690 174 667 q 247 757 247 718 "},"Î…":{x_min:0,x_max:450,ha:553,o:"m 450 800 l 340 800 l 340 925 l 450 925 l 450 800 m 406 1040 l 212 800 l 129 800 l 269 1040 l 406 1040 m 110 800 l 0 800 l 0 925 l 110 925 l 110 800 "},T:{x_min:0,x_max:777,ha:835,o:"m 777 894 l 458 894 l 458 0 l 319 0 l 319 894 l 0 894 l 0 1013 l 777 1013 l 777 894 "},"Φ":{x_min:0,x_max:915,ha:997,o:"m 527 0 l 389 0 l 389 122 q 110 231 220 122 q 0 509 0 340 q 110 785 0 677 q 389 893 220 893 l 389 1013 l 527 1013 l 527 893 q 804 786 693 893 q 915 509 915 679 q 805 231 915 341 q 527 122 696 122 l 527 0 m 527 226 q 712 310 641 226 q 779 507 779 389 q 712 705 779 627 q 527 787 641 787 l 527 226 m 389 226 l 389 787 q 205 698 275 775 q 136 505 136 620 q 206 308 136 391 q 389 226 276 226 "},"â‹":{x_min:0,x_max:0,ha:694},j:{x_min:-77.78125,x_max:167,ha:349,o:"m 167 871 l 42 871 l 42 1013 l 167 1013 l 167 871 m 167 -80 q 121 -231 167 -184 q -26 -278 76 -278 l -77 -278 l -77 -164 l -41 -164 q 26 -143 11 -164 q 42 -65 42 -122 l 42 737 l 167 737 l 167 -80 "},"Σ":{x_min:0,x_max:756.953125,ha:819,o:"m 756 0 l 0 0 l 0 107 l 395 523 l 22 904 l 22 1013 l 745 1013 l 745 889 l 209 889 l 566 523 l 187 125 l 756 125 l 756 0 "},"›":{x_min:18.0625,x_max:774,ha:792,o:"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},"<":{x_min:17.984375,x_max:773.609375,ha:792,o:"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"£":{x_min:0,x_max:704.484375,ha:801,o:"m 704 41 q 623 -10 664 5 q 543 -26 583 -26 q 359 15 501 -26 q 243 36 288 36 q 158 23 197 36 q 73 -21 119 10 l 6 76 q 125 195 90 150 q 175 331 175 262 q 147 443 175 383 l 0 443 l 0 512 l 108 512 q 43 734 43 623 q 120 929 43 854 q 358 1010 204 1010 q 579 936 487 1010 q 678 729 678 857 l 678 684 l 552 684 q 504 838 552 780 q 362 896 457 896 q 216 852 263 896 q 176 747 176 815 q 199 627 176 697 q 248 512 217 574 l 468 512 l 468 443 l 279 443 q 297 356 297 398 q 230 194 297 279 q 153 107 211 170 q 227 133 190 125 q 293 142 264 142 q 410 119 339 142 q 516 96 482 96 q 579 105 550 96 q 648 142 608 115 l 704 41 "},t:{x_min:0,x_max:367,ha:458,o:"m 367 0 q 312 -5 339 -2 q 262 -8 284 -8 q 145 28 183 -8 q 108 143 108 64 l 108 638 l 0 638 l 0 738 l 108 738 l 108 944 l 232 944 l 232 738 l 367 738 l 367 638 l 232 638 l 232 185 q 248 121 232 140 q 307 102 264 102 q 345 104 330 102 q 367 107 360 107 l 367 0 "},"¬":{x_min:0,x_max:706,ha:803,o:"m 706 411 l 706 158 l 630 158 l 630 335 l 0 335 l 0 411 l 706 411 "},"λ":{x_min:0,x_max:750,ha:803,o:"m 750 -7 q 679 -15 716 -15 q 538 59 591 -15 q 466 214 512 97 l 336 551 l 126 0 l 0 0 l 270 705 q 223 837 247 770 q 116 899 190 899 q 90 898 100 899 l 90 1004 q 152 1011 125 1011 q 298 938 244 1011 q 373 783 326 901 l 605 192 q 649 115 629 136 q 716 95 669 95 l 736 95 q 750 97 745 97 l 750 -7 "},W:{x_min:0,x_max:1263.890625,ha:1351,o:"m 1263 1013 l 995 0 l 859 0 l 627 837 l 405 0 l 265 0 l 0 1013 l 136 1013 l 342 202 l 556 1013 l 701 1013 l 921 207 l 1133 1012 l 1263 1013 "},">":{x_min:18.0625,x_max:774,ha:792,o:"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},v:{x_min:0,x_max:675.15625,ha:761,o:"m 675 738 l 404 0 l 272 0 l 0 738 l 133 737 l 340 147 l 541 737 l 675 738 "},"Ï„":{x_min:0.28125,x_max:644.5,ha:703,o:"m 644 628 l 382 628 l 382 179 q 388 120 382 137 q 436 91 401 91 q 474 94 447 91 q 504 97 501 97 l 504 0 q 454 -9 482 -5 q 401 -14 426 -14 q 278 67 308 -14 q 260 233 260 118 l 260 628 l 0 628 l 0 739 l 644 739 l 644 628 "},"ξ":{x_min:0,x_max:624.9375,ha:699,o:"m 624 -37 q 608 -153 624 -96 q 563 -278 593 -211 l 454 -278 q 491 -183 486 -200 q 511 -83 511 -126 q 484 -23 511 -44 q 370 1 452 1 q 323 0 354 1 q 283 -1 293 -1 q 84 76 169 -1 q 0 266 0 154 q 56 431 0 358 q 197 538 108 498 q 94 613 134 562 q 54 730 54 665 q 77 823 54 780 q 143 901 101 867 l 27 901 l 27 1012 l 576 1012 l 576 901 l 380 901 q 244 863 303 901 q 178 745 178 820 q 312 600 178 636 q 532 582 380 582 l 532 479 q 276 455 361 479 q 118 281 118 410 q 165 173 118 217 q 274 120 208 133 q 494 101 384 110 q 624 -37 624 76 "},"&":{x_min:-3,x_max:894.25,ha:992,o:"m 894 0 l 725 0 l 624 123 q 471 0 553 40 q 306 -41 390 -41 q 168 -7 231 -41 q 62 92 105 26 q 14 187 31 139 q -3 276 -3 235 q 55 433 -3 358 q 248 581 114 508 q 170 689 196 640 q 137 817 137 751 q 214 985 137 922 q 384 1041 284 1041 q 548 988 483 1041 q 622 824 622 928 q 563 666 622 739 q 431 556 516 608 l 621 326 q 649 407 639 361 q 663 493 653 426 l 781 493 q 703 229 781 352 l 894 0 m 504 818 q 468 908 504 877 q 384 940 433 940 q 293 907 331 940 q 255 818 255 875 q 289 714 255 767 q 363 628 313 678 q 477 729 446 682 q 504 818 504 771 m 556 209 l 314 499 q 179 395 223 449 q 135 283 135 341 q 146 222 135 253 q 183 158 158 192 q 333 80 241 80 q 556 209 448 80 "},"Λ":{x_min:0,x_max:862.5,ha:942,o:"m 862 0 l 719 0 l 426 847 l 143 0 l 0 0 l 356 1013 l 501 1013 l 862 0 "},I:{x_min:41,x_max:180,ha:293,o:"m 180 0 l 41 0 l 41 1013 l 180 1013 l 180 0 "},G:{x_min:0,x_max:921,ha:1011,o:"m 921 0 l 832 0 l 801 136 q 655 15 741 58 q 470 -28 568 -28 q 126 133 259 -28 q 0 499 0 284 q 125 881 0 731 q 486 1043 259 1043 q 763 957 647 1043 q 905 709 890 864 l 772 709 q 668 866 747 807 q 486 926 589 926 q 228 795 322 926 q 142 507 142 677 q 228 224 142 342 q 483 94 323 94 q 712 195 625 94 q 796 435 796 291 l 477 435 l 477 549 l 921 549 l 921 0 "},"ΰ":{x_min:0,x_max:617,ha:725,o:"m 524 800 l 414 800 l 414 925 l 524 925 l 524 800 m 183 800 l 73 800 l 73 925 l 183 925 l 183 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 489 1040 l 300 819 l 216 819 l 351 1040 l 489 1040 "},"`":{x_min:0,x_max:138.890625,ha:236,o:"m 138 699 l 0 699 l 0 861 q 36 974 0 929 q 138 1041 72 1020 l 138 977 q 82 931 95 969 q 69 839 69 893 l 138 839 l 138 699 "},"·":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"Î¥":{x_min:0.328125,x_max:819.515625,ha:889,o:"m 819 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 "},r:{x_min:0,x_max:355.5625,ha:432,o:"m 355 621 l 343 621 q 179 569 236 621 q 122 411 122 518 l 122 0 l 0 0 l 0 737 l 117 737 l 117 604 q 204 719 146 686 q 355 753 262 753 l 355 621 "},x:{x_min:0,x_max:675,ha:764,o:"m 675 0 l 525 0 l 331 286 l 144 0 l 0 0 l 256 379 l 12 738 l 157 737 l 336 473 l 516 738 l 661 738 l 412 380 l 675 0 "},"μ":{x_min:0,x_max:696.609375,ha:747,o:"m 696 -4 q 628 -14 657 -14 q 498 97 513 -14 q 422 8 470 41 q 313 -24 374 -24 q 207 3 258 -24 q 120 80 157 31 l 120 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 172 124 246 q 308 82 216 82 q 451 177 402 82 q 492 358 492 254 l 492 738 l 616 738 l 616 214 q 623 136 616 160 q 673 92 636 92 q 696 95 684 92 l 696 -4 "},h:{x_min:0,x_max:615,ha:724,o:"m 615 472 l 615 0 l 490 0 l 490 454 q 456 590 490 535 q 338 654 416 654 q 186 588 251 654 q 122 436 122 522 l 122 0 l 0 0 l 0 1013 l 122 1013 l 122 633 q 218 727 149 694 q 362 760 287 760 q 552 676 484 760 q 615 472 615 600 "},".":{x_min:0,x_max:142,ha:239,o:"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"φ":{x_min:-2,x_max:878,ha:974,o:"m 496 -279 l 378 -279 l 378 -17 q 101 88 204 -17 q -2 367 -2 194 q 68 626 -2 510 q 283 758 151 758 l 283 646 q 167 537 209 626 q 133 373 133 462 q 192 177 133 254 q 378 93 259 93 l 378 758 q 445 764 426 763 q 476 765 464 765 q 765 659 653 765 q 878 377 878 553 q 771 96 878 209 q 496 -17 665 -17 l 496 -279 m 496 93 l 514 93 q 687 183 623 93 q 746 380 746 265 q 691 569 746 491 q 522 658 629 658 l 496 656 l 496 93 "},";":{x_min:0,x_max:142,ha:239,o:"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 -12 q 105 -132 142 -82 q 0 -206 68 -182 l 0 -138 q 58 -82 43 -123 q 68 0 68 -56 l 0 0 l 0 151 l 142 151 l 142 -12 "},f:{x_min:0,x_max:378,ha:472,o:"m 378 638 l 246 638 l 246 0 l 121 0 l 121 638 l 0 638 l 0 738 l 121 738 q 137 935 121 887 q 290 1028 171 1028 q 320 1027 305 1028 q 378 1021 334 1026 l 378 908 q 323 918 346 918 q 257 870 273 918 q 246 780 246 840 l 246 738 l 378 738 l 378 638 "},"“":{x_min:1,x_max:348.21875,ha:454,o:"m 140 670 l 1 670 l 1 830 q 37 943 1 897 q 140 1011 74 990 l 140 947 q 82 900 97 940 q 68 810 68 861 l 140 810 l 140 670 m 348 670 l 209 670 l 209 830 q 245 943 209 897 q 348 1011 282 990 l 348 947 q 290 900 305 940 q 276 810 276 861 l 348 810 l 348 670 "},A:{x_min:0.03125,x_max:906.953125,ha:1008,o:"m 906 0 l 756 0 l 648 303 l 251 303 l 142 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 610 421 l 452 867 l 293 421 l 610 421 "},"‘":{x_min:1,x_max:139.890625,ha:236,o:"m 139 670 l 1 670 l 1 830 q 37 943 1 897 q 139 1011 74 990 l 139 947 q 82 900 97 940 q 68 810 68 861 l 139 810 l 139 670 "},"ÏŠ":{x_min:-70,x_max:283,ha:361,o:"m 283 800 l 173 800 l 173 925 l 283 925 l 283 800 m 40 800 l -70 800 l -70 925 l 40 925 l 40 800 m 283 3 q 232 -10 257 -5 q 181 -15 206 -15 q 84 26 118 -15 q 41 200 41 79 l 41 737 l 166 737 l 167 215 q 171 141 167 157 q 225 101 182 101 q 247 103 238 101 q 283 112 256 104 l 283 3 "},"Ï€":{x_min:-0.21875,x_max:773.21875,ha:857,o:"m 773 -7 l 707 -11 q 575 40 607 -11 q 552 174 552 77 l 552 226 l 552 626 l 222 626 l 222 0 l 97 0 l 97 626 l 0 626 l 0 737 l 773 737 l 773 626 l 676 626 l 676 171 q 695 103 676 117 q 773 90 714 90 l 773 -7 "},"ά":{x_min:0,x_max:765.5625,ha:809,o:"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 727 407 760 q 563 637 524 695 l 563 738 l 685 738 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 95 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 m 604 1040 l 415 819 l 332 819 l 466 1040 l 604 1040 "},O:{x_min:0,x_max:958,ha:1057,o:"m 485 1041 q 834 882 702 1041 q 958 512 958 734 q 834 136 958 287 q 481 -26 702 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 728 q 485 1041 263 1041 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 669 q 480 912 640 912 q 226 784 321 912 q 142 504 142 670 q 226 224 142 339 q 480 98 319 98 "},n:{x_min:0,x_max:615,ha:724,o:"m 615 463 l 615 0 l 490 0 l 490 454 q 453 592 490 537 q 331 656 410 656 q 178 585 240 656 q 117 421 117 514 l 117 0 l 0 0 l 0 738 l 117 738 l 117 630 q 218 728 150 693 q 359 764 286 764 q 552 675 484 764 q 615 463 615 593 "},l:{x_min:41,x_max:166,ha:279,o:"m 166 0 l 41 0 l 41 1013 l 166 1013 l 166 0 "},"¤":{x_min:40.09375,x_max:728.796875,ha:825,o:"m 728 304 l 649 224 l 512 363 q 383 331 458 331 q 256 363 310 331 l 119 224 l 40 304 l 177 441 q 150 553 150 493 q 184 673 150 621 l 40 818 l 119 898 l 267 749 q 321 766 291 759 q 384 773 351 773 q 447 766 417 773 q 501 749 477 759 l 649 898 l 728 818 l 585 675 q 612 618 604 648 q 621 553 621 587 q 591 441 621 491 l 728 304 m 384 682 q 280 643 318 682 q 243 551 243 604 q 279 461 243 499 q 383 423 316 423 q 487 461 449 423 q 525 553 525 500 q 490 641 525 605 q 384 682 451 682 "},"κ":{x_min:0,x_max:632.328125,ha:679,o:"m 632 0 l 482 0 l 225 384 l 124 288 l 124 0 l 0 0 l 0 738 l 124 738 l 124 446 l 433 738 l 596 738 l 312 466 l 632 0 "},p:{x_min:0,x_max:685,ha:786,o:"m 685 364 q 598 96 685 205 q 350 -23 504 -23 q 121 89 205 -23 l 121 -278 l 0 -278 l 0 738 l 121 738 l 121 633 q 220 726 159 691 q 351 761 280 761 q 598 636 504 761 q 685 364 685 522 m 557 371 q 501 560 557 481 q 330 651 437 651 q 162 559 223 651 q 108 366 108 479 q 162 177 108 254 q 333 87 224 87 q 502 178 441 87 q 557 371 557 258 "},"‡":{x_min:0,x_max:777,ha:835,o:"m 458 238 l 458 0 l 319 0 l 319 238 l 0 238 l 0 360 l 319 360 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 l 777 804 l 777 683 l 458 683 l 458 360 l 777 360 l 777 238 l 458 238 "},"ψ":{x_min:0,x_max:808,ha:907,o:"m 465 -278 l 341 -278 l 341 -15 q 87 102 180 -15 q 0 378 0 210 l 0 739 l 133 739 l 133 379 q 182 195 133 275 q 341 98 242 98 l 341 922 l 465 922 l 465 98 q 623 195 563 98 q 675 382 675 278 l 675 742 l 808 742 l 808 381 q 720 104 808 213 q 466 -13 627 -13 l 465 -278 "},"η":{x_min:0.78125,x_max:697,ha:810,o:"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 720 124 755 q 200 630 193 686 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 "}};var cssFontWeight="normal";var ascender=1189;var underlinePosition=-100;var cssFontStyle="normal";var boundingBox={yMin:-334,xMin:-111,yMax:1189,xMax:1672};var resolution=1000;var original_font_information={postscript_name:"Helvetiker-Regular",version_string:"Version 1.00 2004 initial release",vendor_url:"http://www.magenta.gr/",full_font_name:"Helvetiker",font_family_name:"Helvetiker",copyright:"Copyright (c) Îœagenta ltd, 2004",description:"",trademark:"",designer:"",designer_url:"",unique_font_identifier:"Îœagenta ltd:Helvetiker:22-10-104",license_url:"http://www.ellak.gr/fonts/MgOpen/license.html",license_description:"Copyright (c) 2004 by MAGENTA Ltd. All Rights Reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license (\"Fonts\") and associated documentation files (the \"Font Software\"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: \r\n\r\nThe above copyright and this permission notice shall be included in all copies of one or more of the Font Software typefaces.\r\n\r\nThe Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing the word \"MgOpen\", or if the modifications are accepted for inclusion in the Font Software itself by the each appointed Administrator.\r\n\r\nThis License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the \"MgOpen\" name.\r\n\r\nThe Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. \r\n\r\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL MAGENTA OR PERSONS OR BODIES IN CHARGE OF ADMINISTRATION AND MAINTENANCE OF THE FONT SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.",manufacturer_name:"Îœagenta ltd",font_sub_family_name:"Regular"};var descender=-334;var familyName="Helvetiker";var lineHeight=1522;var underlineThickness=50;var helvetiker_regular_typeface = {glyphs:glyphs,cssFontWeight:cssFontWeight,ascender:ascender,underlinePosition:underlinePosition,cssFontStyle:cssFontStyle,boundingBox:boundingBox,resolution:resolution,original_font_information:original_font_information,descender:descender,familyName:familyName,lineHeight:lineHeight,underlineThickness:underlineThickness}; + expand( _v1.positionScreen, _v2.positionScreen, this.overdraw ); + expand( _v2.positionScreen, _v3.positionScreen, this.overdraw ); + expand( _v3.positionScreen, _v1.positionScreen, this.overdraw ); -var json1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - glyphs: glyphs, - cssFontWeight: cssFontWeight, - ascender: ascender, - underlinePosition: underlinePosition, - cssFontStyle: cssFontStyle, - boundingBox: boundingBox, - resolution: resolution, - original_font_information: original_font_information, - descender: descender, - familyName: familyName, - lineHeight: lineHeight, - underlineThickness: underlineThickness, - 'default': helvetiker_regular_typeface -}); + } -// + _elemBox.setFromPoints( [ + _v1.positionScreen, + _v2.positionScreen, + _v3.positionScreen + ] ); -class Font { - constructor(data) { - this.isFont = true; - this.type = 'Font'; - this.data = data; - } - generateShapes(text, size = 100) { - const shapes = []; - const paths = createPaths(text, size, this.data); - for (let p = 0, pl = paths.length; p < pl; p++) { - shapes.push(...paths[p].toShapes()); - } - return shapes; - } -} -function createPaths(text, size, data) { - const chars = Array.from(text); - const scale = size / data.resolution; - const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale; - const paths = []; - let offsetX = 0, - offsetY = 0; - for (let i = 0; i < chars.length; i++) { - const char = chars[i]; - if (char === '\n') { - offsetX = 0; - offsetY -= line_height; - } else { - const ret = createPath(char, scale, offsetX, offsetY, data); - offsetX += ret.offsetX; - paths.push(ret.path); - } - } - return paths; -} -function createPath(char, scale, offsetX, offsetY, data) { - const glyph = data.glyphs[char] || data.glyphs['?']; - if (!glyph) { - console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.'); - return; - } - const path = new ShapePath(); - let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; - if (glyph.o) { - const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' ')); - for (let i = 0, l = outline.length; i < l;) { - const action = outline[i++]; - switch (action) { - case 'm': - // moveTo - - x = outline[i++] * scale + offsetX; - y = outline[i++] * scale + offsetY; - path.moveTo(x, y); - break; - case 'l': - // lineTo + if ( _clipBox.intersectsBox( _elemBox ) === true ) { - x = outline[i++] * scale + offsetX; - y = outline[i++] * scale + offsetY; - path.lineTo(x, y); - break; - case 'q': - // quadraticCurveTo - - cpx = outline[i++] * scale + offsetX; - cpy = outline[i++] * scale + offsetY; - cpx1 = outline[i++] * scale + offsetX; - cpy1 = outline[i++] * scale + offsetY; - path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - break; - case 'b': - // bezierCurveTo - - cpx = outline[i++] * scale + offsetX; - cpy = outline[i++] * scale + offsetY; - cpx1 = outline[i++] * scale + offsetX; - cpy1 = outline[i++] * scale + offsetY; - cpx2 = outline[i++] * scale + offsetX; - cpy2 = outline[i++] * scale + offsetY; - path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); - break; - } - } - } - return { - offsetX: glyph.ha * scale, - path: path - }; -} + renderFace3( _v1, _v2, _v3, element, material ); -// This set of controls performs orbiting, dollying (zooming), and panning. -// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). -// -// Orbit - left mouse / touch: one-finger move -// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish -// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move + } -const _changeEvent$1 = { - type: 'change' -}; -const _startEvent = { - type: 'start' -}; -const _endEvent = { - type: 'end' -}; -class OrbitControls extends EventDispatcher { - constructor(object, domElement) { - super(); - this.object = object; - this.domElement = domElement; - this.domElement.style.touchAction = 'none'; // disable touch scroll + } - // Set to false to disable this control - this.enabled = true; + } - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); + flushPath(); // just to flush last svg:path - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; + scene.traverseVisible( function ( object ) { - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; + if ( object.isSVGObject ) { - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyMatrix4( _viewProjectionMatrix ); - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = -Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians + if ( _vector3.z < - 1 || _vector3.z > 1 ) return; - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; + const x = _vector3.x * _svgWidthHalf; + const y = - _vector3.y * _svgHeightHalf; - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; + const node = object.node; + node.setAttribute( 'transform', 'translate(' + x + ',' + y + ')' ); - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; + _svg.appendChild( node ); - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push + } - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + } ); - // The four arrow keys - this.keys = { - LEFT: 'ArrowLeft', - UP: 'ArrowUp', - RIGHT: 'ArrowRight', - BOTTOM: 'ArrowDown' }; - // Mouse buttons - this.mouseButtons = { - LEFT: MOUSE.ROTATE, - MIDDLE: MOUSE.DOLLY, - RIGHT: MOUSE.PAN - }; + function calculateLights( lights ) { - // Touch fingers - this.touches = { - ONE: TOUCH.ROTATE, - TWO: TOUCH.DOLLY_PAN - }; + _ambientLight.setRGB( 0, 0, 0 ); + _directionalLights.setRGB( 0, 0, 0 ); + _pointLights.setRGB( 0, 0, 0 ); - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); - this.zoom0 = this.object.zoom; + for ( let l = 0, ll = lights.length; l < ll; l ++ ) { - // the target DOM element for key events - this._domElementKeyEvents = null; + const light = lights[ l ]; + const lightColor = light.color; - // - // public methods - // + if ( light.isAmbientLight ) { - this.getPolarAngle = function () { - return spherical.phi; - }; - this.getAzimuthalAngle = function () { - return spherical.theta; - }; - this.getDistance = function () { - return this.object.position.distanceTo(this.target); - }; - this.listenToKeyEvents = function (domElement) { - domElement.addEventListener('keydown', onKeyDown); - this._domElementKeyEvents = domElement; - }; - this.saveState = function () { - scope.target0.copy(scope.target); - scope.position0.copy(scope.object.position); - scope.zoom0 = scope.object.zoom; - }; - this.reset = function () { - scope.target.copy(scope.target0); - scope.object.position.copy(scope.position0); - scope.object.zoom = scope.zoom0; - scope.object.updateProjectionMatrix(); - scope.dispatchEvent(_changeEvent$1); - scope.update(); - state = STATE.NONE; - }; - this.resetOrthoPanZoom = function () { - panOffset.set(0, 0, 0); - scope.object.zoom = 1; - scope.object.updateProjectionMatrix(); - zoomChanged = true; - }; + _ambientLight.r += lightColor.r; + _ambientLight.g += lightColor.g; + _ambientLight.b += lightColor.b; - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { - const offset = new Vector3(); + } else if ( light.isDirectionalLight ) { - // so camera.up is the orbit axis - const quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0)); - const quatInverse = quat.clone().invert(); - const lastPosition = new Vector3(); - const lastQuaternion = new Quaternion(); - const twoPI = 2 * Math.PI; - return function update() { - const position = scope.object.position; - offset.copy(position).sub(scope.target); + _directionalLights.r += lightColor.r; + _directionalLights.g += lightColor.g; + _directionalLights.b += lightColor.b; - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion(quat); + } else if ( light.isPointLight ) { + + _pointLights.r += lightColor.r; + _pointLights.g += lightColor.g; + _pointLights.b += lightColor.b; - // angle from z-axis around y-axis - spherical.setFromVector3(offset); - if (scope.autoRotate && state === STATE.NONE) { - rotateLeft(getAutoRotationAngle()); - } - if (scope.enableDamping) { - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; - } else { - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; } - // restrict theta to be between desired limits + } - let min = scope.minAzimuthAngle; - let max = scope.maxAzimuthAngle; - if (isFinite(min) && isFinite(max)) { - if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI; - if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI; - if (min <= max) { - spherical.theta = Math.max(min, Math.min(max, spherical.theta)); - } else { - spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta); - } - } + } - // restrict phi to be between desired limits - spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); - spherical.makeSafe(); - spherical.radius *= scale; + function calculateLight( lights, position, normal, color ) { - // restrict radius to be between desired limits - spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); + for ( let l = 0, ll = lights.length; l < ll; l ++ ) { - // move target to panned location + const light = lights[ l ]; + const lightColor = light.color; - if (scope.enableDamping === true) { - scope.target.addScaledVector(panOffset, scope.dampingFactor); - } else { - scope.target.add(panOffset); - } - offset.setFromSpherical(spherical); + if ( light.isDirectionalLight ) { - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion(quatInverse); - position.copy(scope.target).add(offset); - scope.object.lookAt(scope.target); - if (scope.enableDamping === true) { - sphericalDelta.theta *= 1 - scope.dampingFactor; - sphericalDelta.phi *= 1 - scope.dampingFactor; - panOffset.multiplyScalar(1 - scope.dampingFactor); - } else { - sphericalDelta.set(0, 0, 0); - panOffset.set(0, 0, 0); - } - scale = 1; + const lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize(); - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + let amount = normal.dot( lightPosition ); - if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) { - scope.dispatchEvent(_changeEvent$1); - lastPosition.copy(scope.object.position); - lastQuaternion.copy(scope.object.quaternion); - zoomChanged = false; - return true; - } - return false; - }; - }(); - this.dispose = function () { - scope.domElement.removeEventListener('contextmenu', onContextMenu); - scope.domElement.removeEventListener('pointerdown', onPointerDown); - scope.domElement.removeEventListener('pointercancel', onPointerCancel); - scope.domElement.removeEventListener('wheel', onMouseWheel); - scope.domElement.removeEventListener('pointermove', onPointerMove); - scope.domElement.removeEventListener('pointerup', onPointerUp); - if (scope._domElementKeyEvents !== null) { - scope._domElementKeyEvents.removeEventListener('keydown', onKeyDown); - } + if ( amount <= 0 ) continue; - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? - }; + amount *= light.intensity; - // - // internals - // + color.r += lightColor.r * amount; + color.g += lightColor.g * amount; + color.b += lightColor.b * amount; - const scope = this; - const STATE = { - NONE: -1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; - let state = STATE.NONE; - const EPS = 0.000001; + } else if ( light.isPointLight ) { - // current position in spherical coordinates - const spherical = new Spherical(); - const sphericalDelta = new Spherical(); - let scale = 1; - const panOffset = new Vector3(); - let zoomChanged = false; - const rotateStart = new Vector2(); - const rotateEnd = new Vector2(); - const rotateDelta = new Vector2(); - const panStart = new Vector2(); - const panEnd = new Vector2(); - const panDelta = new Vector2(); - const dollyStart = new Vector2(); - const dollyEnd = new Vector2(); - const dollyDelta = new Vector2(); - const pointers = []; - const pointerPositions = {}; - function getAutoRotationAngle() { - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - } - function getZoomScale() { - return Math.pow(0.95, scope.zoomSpeed); - } - function rotateLeft(angle) { - sphericalDelta.theta -= angle; - } - function rotateUp(angle) { - sphericalDelta.phi -= angle; - } - const panLeft = function () { - const v = new Vector3(); - return function panLeft(distance, objectMatrix) { - v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix - v.multiplyScalar(-distance); - panOffset.add(v); - }; - }(); - const panUp = function () { - const v = new Vector3(); - return function panUp(distance, objectMatrix) { - if (scope.screenSpacePanning === true) { - v.setFromMatrixColumn(objectMatrix, 1); - } else { - v.setFromMatrixColumn(objectMatrix, 0); - v.crossVectors(scope.object.up, v); - } - v.multiplyScalar(distance); - panOffset.add(v); - }; - }(); + const lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ); - // deltaX and deltaY are in pixels; right and down are positive - const pan = function () { - const offset = new Vector3(); - return function pan(deltaX, deltaY) { - const element = scope.domElement; - if (scope.object.isPerspectiveCamera) { - // perspective - const position = scope.object.position; - offset.copy(position).sub(scope.target); - let targetDistance = offset.length(); + let amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() ); - // half of the fov is center to top of screen - targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); + if ( amount <= 0 ) continue; + + amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 ); + + if ( amount == 0 ) continue; + + amount *= light.intensity; + + color.r += lightColor.r * amount; + color.g += lightColor.g * amount; + color.b += lightColor.b * amount; - // we use only clientHeight here so aspect ratio does not distort speed - panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); - panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); - } else if (scope.object.isOrthographicCamera) { - // orthographic - panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix); - panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix); - } else { - // camera neither orthographic nor perspective - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.'); - scope.enablePan = false; } - }; - }(); - function dollyOut(dollyScale) { - if (scope.object.isPerspectiveCamera) { - scale /= dollyScale; - } else if (scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; - } - } - function dollyIn(dollyScale) { - if (scope.object.isPerspectiveCamera) { - scale *= dollyScale; - } else if (scope.object.isOrthographicCamera) { - scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale)); - scope.object.updateProjectionMatrix(); - zoomChanged = true; - } else { - console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.'); - scope.enableZoom = false; + } + } - // - // event callbacks - update the object state - // + function renderSprite( v1, element, material ) { - function handleMouseDownRotate(event) { - rotateStart.set(event.clientX, event.clientY); - } - function handleMouseDownDolly(event) { - dollyStart.set(event.clientX, event.clientY); - } - function handleMouseDownPan(event) { - panStart.set(event.clientX, event.clientY); - } - function handleMouseMoveRotate(event) { - rotateEnd.set(event.clientX, event.clientY); - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + let scaleX = element.scale.x * _svgWidthHalf; + let scaleY = element.scale.y * _svgHeightHalf; - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - rotateStart.copy(rotateEnd); - scope.update(); - } - function handleMouseMoveDolly(event) { - dollyEnd.set(event.clientX, event.clientY); - dollyDelta.subVectors(dollyEnd, dollyStart); - if (dollyDelta.y > 0) { - dollyOut(getZoomScale()); - } else if (dollyDelta.y < 0) { - dollyIn(getZoomScale()); - } - dollyStart.copy(dollyEnd); - scope.update(); - } - function handleMouseMovePan(event) { - panEnd.set(event.clientX, event.clientY); - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - scope.update(); - } - function handleMouseWheel(event) { - if (event.deltaY < 0) { - dollyIn(getZoomScale()); - } else if (event.deltaY > 0) { - dollyOut(getZoomScale()); - } - scope.update(); - } - function handleKeyDown(event) { - let needsUpdate = false; - switch (event.code) { - case scope.keys.UP: - pan(0, scope.keyPanSpeed); - needsUpdate = true; - break; - case scope.keys.BOTTOM: - pan(0, -scope.keyPanSpeed); - needsUpdate = true; - break; - case scope.keys.LEFT: - pan(scope.keyPanSpeed, 0); - needsUpdate = true; - break; - case scope.keys.RIGHT: - pan(-scope.keyPanSpeed, 0); - needsUpdate = true; - break; - } - if (needsUpdate) { - // prevent the browser from scrolling on cursor keys - event.preventDefault(); - scope.update(); - } - } - function handleTouchStartRotate() { - if (pointers.length === 1) { - rotateStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - rotateStart.set(x, y); - } - } - function handleTouchStartPan() { - if (pointers.length === 1) { - panStart.set(pointers[0].pageX, pointers[0].pageY); - } else { - const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); - const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); - panStart.set(x, y); - } - } - function handleTouchStartDolly() { - const dx = pointers[0].pageX - pointers[1].pageX; - const dy = pointers[0].pageY - pointers[1].pageY; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyStart.set(0, distance); - } - function handleTouchStartDollyPan() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enablePan) handleTouchStartPan(); - } - function handleTouchStartDollyRotate() { - if (scope.enableZoom) handleTouchStartDolly(); - if (scope.enableRotate) handleTouchStartRotate(); - } - function handleTouchMoveRotate(event) { - if (pointers.length == 1) { - rotateEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - rotateEnd.set(x, y); - } - rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); - const element = scope.domElement; - rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height + if ( material.isPointsMaterial ) { + + scaleX *= material.size; + scaleY *= material.size; - rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); - rotateStart.copy(rotateEnd); - } - function handleTouchMovePan(event) { - if (pointers.length === 1) { - panEnd.set(event.pageX, event.pageY); - } else { - const position = getSecondPointerPosition(event); - const x = 0.5 * (event.pageX + position.x); - const y = 0.5 * (event.pageY + position.y); - panEnd.set(x, y); } - panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); - pan(panDelta.x, panDelta.y); - panStart.copy(panEnd); - } - function handleTouchMoveDolly(event) { - const position = getSecondPointerPosition(event); - const dx = event.pageX - position.x; - const dy = event.pageY - position.y; - const distance = Math.sqrt(dx * dx + dy * dy); - dollyEnd.set(0, distance); - dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); - dollyOut(dollyDelta.y); - dollyStart.copy(dollyEnd); - } - function handleTouchMoveDollyPan(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enablePan) handleTouchMovePan(event); - } - function handleTouchMoveDollyRotate(event) { - if (scope.enableZoom) handleTouchMoveDolly(event); - if (scope.enableRotate) handleTouchMoveRotate(event); - } - // - // event handlers - FSM: listen for events and reset state - // + const path = 'M' + convert( v1.x - scaleX * 0.5 ) + ',' + convert( v1.y - scaleY * 0.5 ) + 'h' + convert( scaleX ) + 'v' + convert( scaleY ) + 'h' + convert( - scaleX ) + 'z'; + let style = ''; - function onPointerDown(event) { - if (scope.enabled === false) return; - if (pointers.length === 0) { - scope.domElement.setPointerCapture(event.pointerId); - scope.domElement.addEventListener('pointermove', onPointerMove); - scope.domElement.addEventListener('pointerup', onPointerUp); - } + if ( material.isSpriteMaterial || material.isPointsMaterial ) { - // + style = 'fill:' + material.color.getStyle() + ';fill-opacity:' + material.opacity; - addPointer(event); - if (event.pointerType === 'touch') { - onTouchStart(event); - } else { - onMouseDown(event); - } - } - function onPointerMove(event) { - if (scope.enabled === false) return; - if (event.pointerType === 'touch') { - onTouchMove(event); - } else { - onMouseMove(event); - } - } - function onPointerUp(event) { - removePointer(event); - if (pointers.length === 0) { - scope.domElement.releasePointerCapture(event.pointerId); - scope.domElement.removeEventListener('pointermove', onPointerMove); - scope.domElement.removeEventListener('pointerup', onPointerUp); - } - scope.dispatchEvent(_endEvent); - state = STATE.NONE; - } - function onPointerCancel(event) { - removePointer(event); - } - function onMouseDown(event) { - let mouseAction; - switch (event.button) { - case 0: - mouseAction = scope.mouseButtons.LEFT; - break; - case 1: - mouseAction = scope.mouseButtons.MIDDLE; - break; - case 2: - mouseAction = scope.mouseButtons.RIGHT; - break; - default: - mouseAction = -1; - } - switch (mouseAction) { - case MOUSE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseDownDolly(event); - state = STATE.DOLLY; - break; - case MOUSE.ROTATE: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } else { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } - break; - case MOUSE.PAN: - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (scope.enableRotate === false) return; - handleMouseDownRotate(event); - state = STATE.ROTATE; - } else { - if (scope.enablePan === false) return; - handleMouseDownPan(event); - state = STATE.PAN; - } - break; - default: - state = STATE.NONE; - } - if (state !== STATE.NONE) { - scope.dispatchEvent(_startEvent); - } - } - function onMouseMove(event) { - switch (state) { - case STATE.ROTATE: - if (scope.enableRotate === false) return; - handleMouseMoveRotate(event); - break; - case STATE.DOLLY: - if (scope.enableZoom === false) return; - handleMouseMoveDolly(event); - break; - case STATE.PAN: - if (scope.enablePan === false) return; - handleMouseMovePan(event); - break; - } - } - function onMouseWheel(event) { - if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE) return; - event.preventDefault(); - scope.dispatchEvent(_startEvent); - handleMouseWheel(event); - scope.dispatchEvent(_endEvent); - } - function onKeyDown(event) { - if (scope.enabled === false || scope.enablePan === false) return; - handleKeyDown(event); - } - function onTouchStart(event) { - trackPointer(event); - switch (pointers.length) { - case 1: - switch (scope.touches.ONE) { - case TOUCH.ROTATE: - if (scope.enableRotate === false) return; - handleTouchStartRotate(); - state = STATE.TOUCH_ROTATE; - break; - case TOUCH.PAN: - if (scope.enablePan === false) return; - handleTouchStartPan(); - state = STATE.TOUCH_PAN; - break; - default: - state = STATE.NONE; - } - break; - case 2: - switch (scope.touches.TWO) { - case TOUCH.DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchStartDollyPan(); - state = STATE.TOUCH_DOLLY_PAN; - break; - case TOUCH.DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchStartDollyRotate(); - state = STATE.TOUCH_DOLLY_ROTATE; - break; - default: - state = STATE.NONE; - } - break; - default: - state = STATE.NONE; - } - if (state !== STATE.NONE) { - scope.dispatchEvent(_startEvent); } + + addPath( style, path ); + } - function onTouchMove(event) { - trackPointer(event); - switch (state) { - case STATE.TOUCH_ROTATE: - if (scope.enableRotate === false) return; - handleTouchMoveRotate(event); - scope.update(); - break; - case STATE.TOUCH_PAN: - if (scope.enablePan === false) return; - handleTouchMovePan(event); - scope.update(); - break; - case STATE.TOUCH_DOLLY_PAN: - if (scope.enableZoom === false && scope.enablePan === false) return; - handleTouchMoveDollyPan(event); - scope.update(); - break; - case STATE.TOUCH_DOLLY_ROTATE: - if (scope.enableZoom === false && scope.enableRotate === false) return; - handleTouchMoveDollyRotate(event); - scope.update(); - break; - default: - state = STATE.NONE; + + function renderLine( v1, v2, material ) { + + const path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y ); + + if ( material.isLineBasicMaterial ) { + + let style = 'fill:none;stroke:' + material.color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap; + + if ( material.isLineDashedMaterial ) { + + style = style + ';stroke-dasharray:' + material.dashSize + ',' + material.gapSize; + + } + + addPath( style, path ); + } + } - function onContextMenu(event) { - if (scope.enabled === false) return; - event.preventDefault(); - } - function addPointer(event) { - pointers.push(event); - } - function removePointer(event) { - delete pointerPositions[event.pointerId]; - for (let i = 0; i < pointers.length; i++) { - if (pointers[i].pointerId == event.pointerId) { - pointers.splice(i, 1); - return; + + function renderFace3( v1, v2, v3, element, material ) { + + _this.info.render.vertices += 3; + _this.info.render.faces ++; + + const path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y ) + 'L' + convert( v3.positionScreen.x ) + ',' + convert( v3.positionScreen.y ) + 'z'; + let style = ''; + + if ( material.isMeshBasicMaterial ) { + + _color.copy( material.color ); + + if ( material.vertexColors ) { + + _color.multiply( element.color ); + + } + + } else if ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial ) { + + _diffuseColor.copy( material.color ); + + if ( material.vertexColors ) { + + _diffuseColor.multiply( element.color ); + } + + _color.copy( _ambientLight ); + + _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 ); + + calculateLight( _lights, _centroid, element.normalModel, _color ); + + _color.multiply( _diffuseColor ).add( material.emissive ); + + } else if ( material.isMeshNormalMaterial ) { + + _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix ).normalize(); + + _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 ); + } - } - function trackPointer(event) { - let position = pointerPositions[event.pointerId]; - if (position === undefined) { - position = new Vector2(); - pointerPositions[event.pointerId] = position; + + if ( material.wireframe ) { + + style = 'fill:none;stroke:' + _color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin; + + } else { + + style = 'fill:' + _color.getStyle() + ';fill-opacity:' + material.opacity; + } - position.set(event.pageX, event.pageY); - } - function getSecondPointerPosition(event) { - const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]; - return pointerPositions[pointer.pointerId]; + + addPath( style, path ); + } - // + // Hide anti-alias gaps - scope.domElement.addEventListener('contextmenu', onContextMenu); - scope.domElement.addEventListener('pointerdown', onPointerDown); - scope.domElement.addEventListener('pointercancel', onPointerCancel); - scope.domElement.addEventListener('wheel', onMouseWheel, { - passive: false - }); + function expand( v1, v2, pixels ) { - // force an update at start + let x = v2.x - v1.x, y = v2.y - v1.y; + const det = x * x + y * y; - this.update(); - } -} + if ( det === 0 ) return; + + const idet = pixels / Math.sqrt( det ); + + x *= idet; y *= idet; + + v2.x += x; v2.y += y; + v1.x -= x; v1.y -= y; -const _raycaster = new Raycaster(); -const _tempVector = new Vector3(); -const _tempVector2 = new Vector3(); -const _tempQuaternion = new Quaternion(); -const _unit = { - X: new Vector3(1, 0, 0), - Y: new Vector3(0, 1, 0), - Z: new Vector3(0, 0, 1) -}; -const _changeEvent = { - type: 'change' -}; -const _mouseDownEvent = { - type: 'mouseDown' -}; -const _mouseUpEvent = { - type: 'mouseUp', - mode: null -}; -const _objectChangeEvent = { - type: 'objectChange' -}; -class TransformControls extends Object3D { - constructor(camera, domElement) { - super(); - if (domElement === undefined) { - console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'); - domElement = document; } - this.isTransformControls = true; - this.visible = false; - this.domElement = domElement; - this.domElement.style.touchAction = 'none'; // disable touch scroll - const _gizmo = new TransformControlsGizmo(); - this._gizmo = _gizmo; - this.add(_gizmo); - const _plane = new TransformControlsPlane(); - this._plane = _plane; - this.add(_plane); - const scope = this; + function addPath( style, path ) { + + if ( _currentStyle === style ) { + + _currentPath += path; - // Defined getter, setter and store for a property - function defineProperty(propName, defaultValue) { - let propValue = defaultValue; - Object.defineProperty(scope, propName, { - get: function () { - return propValue !== undefined ? propValue : defaultValue; - }, - set: function (value) { - if (propValue !== value) { - propValue = value; - _plane[propName] = value; - _gizmo[propName] = value; - scope.dispatchEvent({ - type: propName + '-changed', - value: value - }); - scope.dispatchEvent(_changeEvent); - } - } - }); - scope[propName] = defaultValue; - _plane[propName] = defaultValue; - _gizmo[propName] = defaultValue; - } - - // Define properties with getters/setter - // Setting the defined property will automatically trigger change event - // Defined properties are passed down to gizmo and plane - - defineProperty('camera', camera); - defineProperty('object', undefined); - defineProperty('enabled', true); - defineProperty('axis', null); - defineProperty('mode', 'translate'); - defineProperty('translationSnap', null); - defineProperty('rotationSnap', null); - defineProperty('scaleSnap', null); - defineProperty('space', 'world'); - defineProperty('size', 1); - defineProperty('dragging', false); - defineProperty('showX', true); - defineProperty('showY', true); - defineProperty('showZ', true); - - // Reusable utility variables - - const worldPosition = new Vector3(); - const worldPositionStart = new Vector3(); - const worldQuaternion = new Quaternion(); - const worldQuaternionStart = new Quaternion(); - const cameraPosition = new Vector3(); - const cameraQuaternion = new Quaternion(); - const pointStart = new Vector3(); - const pointEnd = new Vector3(); - const rotationAxis = new Vector3(); - const rotationAngle = 0; - const eye = new Vector3(); - - // TODO: remove properties unused in plane and gizmo - - defineProperty('worldPosition', worldPosition); - defineProperty('worldPositionStart', worldPositionStart); - defineProperty('worldQuaternion', worldQuaternion); - defineProperty('worldQuaternionStart', worldQuaternionStart); - defineProperty('cameraPosition', cameraPosition); - defineProperty('cameraQuaternion', cameraQuaternion); - defineProperty('pointStart', pointStart); - defineProperty('pointEnd', pointEnd); - defineProperty('rotationAxis', rotationAxis); - defineProperty('rotationAngle', rotationAngle); - defineProperty('eye', eye); - this._offset = new Vector3(); - this._startNorm = new Vector3(); - this._endNorm = new Vector3(); - this._cameraScale = new Vector3(); - this._parentPosition = new Vector3(); - this._parentQuaternion = new Quaternion(); - this._parentQuaternionInv = new Quaternion(); - this._parentScale = new Vector3(); - this._worldScaleStart = new Vector3(); - this._worldQuaternionInv = new Quaternion(); - this._worldScale = new Vector3(); - this._positionStart = new Vector3(); - this._quaternionStart = new Quaternion(); - this._scaleStart = new Vector3(); - this._getPointer = getPointer.bind(this); - this._onPointerDown = onPointerDown.bind(this); - this._onPointerHover = onPointerHover.bind(this); - this._onPointerMove = onPointerMove.bind(this); - this._onPointerUp = onPointerUp.bind(this); - this.domElement.addEventListener('pointerdown', this._onPointerDown); - this.domElement.addEventListener('pointermove', this._onPointerHover); - this.domElement.addEventListener('pointerup', this._onPointerUp); - } - - // updateMatrixWorld updates key transformation variables - updateMatrixWorld() { - if (this.object !== undefined) { - this.object.updateMatrixWorld(); - if (this.object.parent === null) { - console.error('TransformControls: The attached 3D object must be a part of the scene graph.'); } else { - this.object.parent.matrixWorld.decompose(this._parentPosition, this._parentQuaternion, this._parentScale); + + flushPath(); + + _currentStyle = style; + _currentPath = path; + } - this.object.matrixWorld.decompose(this.worldPosition, this.worldQuaternion, this._worldScale); - this._parentQuaternionInv.copy(this._parentQuaternion).invert(); - this._worldQuaternionInv.copy(this.worldQuaternion).invert(); - } - this.camera.updateMatrixWorld(); - this.camera.matrixWorld.decompose(this.cameraPosition, this.cameraQuaternion, this._cameraScale); - if (this.camera.isOrthographicCamera) { - this.camera.getWorldDirection(this.eye).negate(); - } else { - this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(); + } - super.updateMatrixWorld(this); - } - pointerHover(pointer) { - if (this.object === undefined || this.dragging === true) return; - _raycaster.setFromCamera(pointer, this.camera); - const intersect = intersectObjectWithRay(this._gizmo.picker[this.mode], _raycaster); - if (intersect) { - this.axis = intersect.object.name; - } else { - this.axis = null; - } - } - pointerDown(pointer) { - if (this.object === undefined || this.dragging === true || pointer.button !== 0) return; - if (this.axis !== null) { - _raycaster.setFromCamera(pointer, this.camera); - const planeIntersect = intersectObjectWithRay(this._plane, _raycaster, true); - if (planeIntersect) { - this.object.updateMatrixWorld(); - this.object.parent.updateMatrixWorld(); - this._positionStart.copy(this.object.position); - this._quaternionStart.copy(this.object.quaternion); - this._scaleStart.copy(this.object.scale); - this.object.matrixWorld.decompose(this.worldPositionStart, this.worldQuaternionStart, this._worldScaleStart); - this.pointStart.copy(planeIntersect.point).sub(this.worldPositionStart); - } - this.dragging = true; - _mouseDownEvent.mode = this.mode; - this.dispatchEvent(_mouseDownEvent); - } - } - pointerMove(pointer) { - const axis = this.axis; - const mode = this.mode; - const object = this.object; - let space = this.space; - if (mode === 'scale') { - space = 'local'; - } else if (axis === 'E' || axis === 'XYZE' || axis === 'XYZ') { - space = 'world'; - } - if (object === undefined || axis === null || this.dragging === false || pointer.button !== -1) return; - _raycaster.setFromCamera(pointer, this.camera); - const planeIntersect = intersectObjectWithRay(this._plane, _raycaster, true); - if (!planeIntersect) return; - this.pointEnd.copy(planeIntersect.point).sub(this.worldPositionStart); - if (mode === 'translate') { - // Apply translate - - this._offset.copy(this.pointEnd).sub(this.pointStart); - if (space === 'local' && axis !== 'XYZ') { - this._offset.applyQuaternion(this._worldQuaternionInv); - } - if (axis.indexOf('X') === -1) this._offset.x = 0; - if (axis.indexOf('Y') === -1) this._offset.y = 0; - if (axis.indexOf('Z') === -1) this._offset.z = 0; - if (space === 'local' && axis !== 'XYZ') { - this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale); - } else { - this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale); - } - object.position.copy(this._offset).add(this._positionStart); - // Apply translation snap + function flushPath() { + + if ( _currentPath ) { + + _svgNode = getPathNode( _pathCount ++ ); + _svgNode.setAttribute( 'd', _currentPath ); + _svgNode.setAttribute( 'style', _currentStyle ); + _svg.appendChild( _svgNode ); - if (this.translationSnap) { - if (space === 'local') { - object.position.applyQuaternion(_tempQuaternion.copy(this._quaternionStart).invert()); - if (axis.search('X') !== -1) { - object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; - } - if (axis.search('Y') !== -1) { - object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; - } - if (axis.search('Z') !== -1) { - object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; - } - object.position.applyQuaternion(this._quaternionStart); - } - if (space === 'world') { - if (object.parent) { - object.position.add(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); - } - if (axis.search('X') !== -1) { - object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; - } - if (axis.search('Y') !== -1) { - object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; - } - if (axis.search('Z') !== -1) { - object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; - } - if (object.parent) { - object.position.sub(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); - } - } - } - } else if (mode === 'scale') { - if (axis.search('XYZ') !== -1) { - let d = this.pointEnd.length() / this.pointStart.length(); - if (this.pointEnd.dot(this.pointStart) < 0) d *= -1; - _tempVector2.set(d, d, d); - } else { - _tempVector.copy(this.pointStart); - _tempVector2.copy(this.pointEnd); - _tempVector.applyQuaternion(this._worldQuaternionInv); - _tempVector2.applyQuaternion(this._worldQuaternionInv); - _tempVector2.divide(_tempVector); - if (axis.search('X') === -1) { - _tempVector2.x = 1; - } - if (axis.search('Y') === -1) { - _tempVector2.y = 1; - } - if (axis.search('Z') === -1) { - _tempVector2.z = 1; - } } - // Apply scale + _currentPath = ''; + _currentStyle = ''; - object.scale.copy(this._scaleStart).multiply(_tempVector2); - if (this.scaleSnap) { - if (axis.search('X') !== -1) { - object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap; - } - if (axis.search('Y') !== -1) { - object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap; - } - if (axis.search('Z') !== -1) { - object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap; - } - } - } else if (mode === 'rotate') { - this._offset.copy(this.pointEnd).sub(this.pointStart); - const ROTATION_SPEED = 20 / this.worldPosition.distanceTo(_tempVector.setFromMatrixPosition(this.camera.matrixWorld)); - if (axis === 'E') { - this.rotationAxis.copy(this.eye); - this.rotationAngle = this.pointEnd.angleTo(this.pointStart); - this._startNorm.copy(this.pointStart).normalize(); - this._endNorm.copy(this.pointEnd).normalize(); - this.rotationAngle *= this._endNorm.cross(this._startNorm).dot(this.eye) < 0 ? 1 : -1; - } else if (axis === 'XYZE') { - this.rotationAxis.copy(this._offset).cross(this.eye).normalize(); - this.rotationAngle = this._offset.dot(_tempVector.copy(this.rotationAxis).cross(this.eye)) * ROTATION_SPEED; - } else if (axis === 'X' || axis === 'Y' || axis === 'Z') { - this.rotationAxis.copy(_unit[axis]); - _tempVector.copy(_unit[axis]); - if (space === 'local') { - _tempVector.applyQuaternion(this.worldQuaternion); - } - this.rotationAngle = this._offset.dot(_tempVector.cross(this.eye).normalize()) * ROTATION_SPEED; - } + } - // Apply rotation snap + function getPathNode( id ) { - if (this.rotationSnap) this.rotationAngle = Math.round(this.rotationAngle / this.rotationSnap) * this.rotationSnap; + if ( _svgPathPool[ id ] == null ) { + + _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' ); + + if ( _quality == 0 ) { + + _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed + + } + + return _svgPathPool[ id ]; - // Apply rotate - if (space === 'local' && axis !== 'E' && axis !== 'XYZE') { - object.quaternion.copy(this._quaternionStart); - object.quaternion.multiply(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)).normalize(); - } else { - this.rotationAxis.applyQuaternion(this._parentQuaternionInv); - object.quaternion.copy(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)); - object.quaternion.multiply(this._quaternionStart).normalize(); } - } - this.dispatchEvent(_changeEvent); - this.dispatchEvent(_objectChangeEvent); - } - pointerUp(pointer) { - if (pointer.button !== 0) return; - if (this.dragging && this.axis !== null) { - _mouseUpEvent.mode = this.mode; - this.dispatchEvent(_mouseUpEvent); - } - this.dragging = false; - this.axis = null; - } - dispose() { - this.domElement.removeEventListener('pointerdown', this._onPointerDown); - this.domElement.removeEventListener('pointermove', this._onPointerHover); - this.domElement.removeEventListener('pointermove', this._onPointerMove); - this.domElement.removeEventListener('pointerup', this._onPointerUp); - this.traverse(function (child) { - if (child.geometry) child.geometry.dispose(); - if (child.material) child.material.dispose(); - }); - } - - // Set current object - attach(object) { - this.object = object; - this.visible = true; - return this; - } - // Detach from object - detach() { - this.object = undefined; - this.visible = false; - this.axis = null; - return this; - } - reset() { - if (!this.enabled) return; - if (this.dragging) { - this.object.position.copy(this._positionStart); - this.object.quaternion.copy(this._quaternionStart); - this.object.scale.copy(this._scaleStart); - this.dispatchEvent(_changeEvent); - this.dispatchEvent(_objectChangeEvent); - this.pointStart.copy(this.pointEnd); + return _svgPathPool[ id ]; + } - } - getRaycaster() { - return _raycaster; + } - // TODO: deprecate +} + +let HelveticerRegularJson = json1; + +// end of jsroot part + + +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + /* eslint-disable no-undef */ + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + /* eslint-enable no-undef */ - getMode() { - return this.mode; - } - setMode(mode) { - this.mode = mode; - } - setTranslationSnap(translationSnap) { - this.translationSnap = translationSnap; - } - setRotationSnap(rotationSnap) { - this.rotationSnap = rotationSnap; - } - setScaleSnap(scaleSnap) { - this.scaleSnap = scaleSnap; - } - setSize(size) { - this.size = size; - } - setSpace(space) { - this.space = space; - } } -// mouse / touch event handlers +if ( typeof window !== 'undefined' ) { + + if ( window.__THREE__ ) { + + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); -function getPointer(event) { - if (this.domElement.ownerDocument.pointerLockElement) { - return { - x: 0, - y: 0, - button: event.button - }; } else { - const rect = this.domElement.getBoundingClientRect(); - return { - x: (event.clientX - rect.left) / rect.width * 2 - 1, - y: -(event.clientY - rect.top) / rect.height * 2 + 1, - button: event.button - }; - } -} -function onPointerHover(event) { - if (!this.enabled) return; - switch (event.pointerType) { - case 'mouse': - case 'pen': - this.pointerHover(this._getPointer(event)); - break; - } -} -function onPointerDown(event) { - if (!this.enabled) return; - if (!document.pointerLockElement) { - this.domElement.setPointerCapture(event.pointerId); + + window.__THREE__ = REVISION; + } - this.domElement.addEventListener('pointermove', this._onPointerMove); - this.pointerHover(this._getPointer(event)); - this.pointerDown(this._getPointer(event)); -} -function onPointerMove(event) { - if (!this.enabled) return; - this.pointerMove(this._getPointer(event)); -} -function onPointerUp(event) { - if (!this.enabled) return; - this.domElement.releasePointerCapture(event.pointerId); - this.domElement.removeEventListener('pointermove', this._onPointerMove); - this.pointerUp(this._getPointer(event)); + } -function intersectObjectWithRay(object, raycaster, includeInvisible) { - const allIntersections = raycaster.intersectObject(object, true); - for (let i = 0; i < allIntersections.length; i++) { - if (allIntersections[i].object.visible || includeInvisible) { - return allIntersections[i]; - } - } - return false; + +/** @ummary Create three.js Color instance, handles optional opacity + * @private */ +function getMaterialArgs(color$1, args) { + if (!args || !isObject(args)) args = {}; + + if (isStr(color$1) && (((color$1[0] === '#') && (color$1.length === 9)) || (color$1.indexOf('rgba') >= 0))) { + const col = color(color$1); + args.color = new Color(col.r, col.g, col.b); + args.opacity = col.opacity ?? 1; + args.transparent = args.opacity < 1; + } else + args.color = new Color(color$1); + return args; } -// +const HelveticerRegularFont = new Font(HelveticerRegularJson); -// Reusable utility variables - -const _tempEuler = new Euler(); -const _alignVector = new Vector3(0, 1, 0); -const _zeroVector = new Vector3(0, 0, 0); -const _lookAtMatrix = new Matrix4(); -const _tempQuaternion2 = new Quaternion(); -const _identityQuaternion = new Quaternion(); -const _dirVector = new Vector3(); -const _tempMatrix = new Matrix4(); -const _unitX = new Vector3(1, 0, 0); -const _unitY = new Vector3(0, 1, 0); -const _unitZ = new Vector3(0, 0, 1); -const _v1 = new Vector3(); -const _v2 = new Vector3(); -const _v3 = new Vector3(); -class TransformControlsGizmo extends Object3D { - constructor() { - super(); - this.isTransformControlsGizmo = true; - this.type = 'TransformControlsGizmo'; +function createSVGRenderer(as_is, precision, doc) { + if (as_is) { + if (doc !== undefined) + globalThis.docuemnt = doc; + const rndr = new SVGRenderer(); + rndr.setPrecision(precision); + return rndr; + } - // shared materials + const excl_style1 = ';stroke-opacity:1;stroke-width:1;stroke-linecap:round', + excl_style2 = ';fill-opacity:1', + doc_wrapper = { + svg_attr: {}, + svg_style: {}, + path_attr: {}, + accPath: '', + createElementNS(ns, kind) { + if (kind === 'path') { + return { + _wrapper: this, + setAttribute(name, value) { + // cut useless fill-opacity:1 at the end of many SVG attributes + if ((name === 'style') && value) { + const pos1 = value.indexOf(excl_style1); + if ((pos1 >= 0) && (pos1 === value.length - excl_style1.length)) + value = value.slice(0, value.length - excl_style1.length); + const pos2 = value.indexOf(excl_style2); + if ((pos2 >= 0) && (pos2 === value.length - excl_style2.length)) + value = value.slice(0, value.length - excl_style2.length); + } + this._wrapper.path_attr[name] = value; + } + }; + } - const gizmoMaterial = new MeshBasicMaterial({ - depthTest: false, - depthWrite: false, - fog: false, - toneMapped: false, - transparent: true - }); - const gizmoLineMaterial = new LineBasicMaterial({ - depthTest: false, - depthWrite: false, - fog: false, - toneMapped: false, - transparent: true - }); - - // Make unique material for each axis/color - - const matInvisible = gizmoMaterial.clone(); - matInvisible.opacity = 0.15; - const matHelper = gizmoLineMaterial.clone(); - matHelper.opacity = 0.5; - const matRed = gizmoMaterial.clone(); - matRed.color.setHex(0xff0000); - const matGreen = gizmoMaterial.clone(); - matGreen.color.setHex(0x00ff00); - const matBlue = gizmoMaterial.clone(); - matBlue.color.setHex(0x0000ff); - const matRedTransparent = gizmoMaterial.clone(); - matRedTransparent.color.setHex(0xff0000); - matRedTransparent.opacity = 0.5; - const matGreenTransparent = gizmoMaterial.clone(); - matGreenTransparent.color.setHex(0x00ff00); - matGreenTransparent.opacity = 0.5; - const matBlueTransparent = gizmoMaterial.clone(); - matBlueTransparent.color.setHex(0x0000ff); - matBlueTransparent.opacity = 0.5; - const matWhiteTransparent = gizmoMaterial.clone(); - matWhiteTransparent.opacity = 0.25; - const matYellowTransparent = gizmoMaterial.clone(); - matYellowTransparent.color.setHex(0xffff00); - matYellowTransparent.opacity = 0.25; - const matYellow = gizmoMaterial.clone(); - matYellow.color.setHex(0xffff00); - const matGray = gizmoMaterial.clone(); - matGray.color.setHex(0x787878); - - // reusable geometry - - const arrowGeometry = new CylinderGeometry(0, 0.04, 0.1, 12); - arrowGeometry.translate(0, 0.05, 0); - const scaleHandleGeometry = new BoxGeometry(0.08, 0.08, 0.08); - scaleHandleGeometry.translate(0, 0.04, 0); - const lineGeometry = new BufferGeometry(); - lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3)); - const lineGeometry2 = new CylinderGeometry(0.0075, 0.0075, 0.5, 3); - lineGeometry2.translate(0, 0.25, 0); - function CircleGeometry(radius, arc) { - const geometry = new TorusGeometry(radius, 0.0075, 3, 64, arc * Math.PI * 2); - geometry.rotateY(Math.PI / 2); - geometry.rotateX(Math.PI / 2); - return geometry; - } - - // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position - - function TranslateHelperGeometry() { - const geometry = new BufferGeometry(); - geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 1, 1, 1], 3)); - return geometry; - } - - // Gizmo definitions - custom hierarchy definitions for setupGizmo() function - - const gizmoTranslate = { - X: [[new Mesh(arrowGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]], [new Mesh(arrowGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]], [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]]], - Y: [[new Mesh(arrowGeometry, matGreen), [0, 0.5, 0]], [new Mesh(arrowGeometry, matGreen), [0, -0.5, 0], [Math.PI, 0, 0]], [new Mesh(lineGeometry2, matGreen)]], - Z: [[new Mesh(arrowGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]], [new Mesh(arrowGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]], [new Mesh(lineGeometry2, matBlue), null, [Math.PI / 2, 0, 0]]], - XYZ: [[new Mesh(new OctahedronGeometry(0.1, 0), matWhiteTransparent.clone()), [0, 0, 0]]], - XY: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent.clone()), [0.15, 0.15, 0]]], - YZ: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent.clone()), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]], - XZ: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent.clone()), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]] - }; - const pickerTranslate = { - X: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]]], - Y: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]]], - Z: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]]], - XYZ: [[new Mesh(new OctahedronGeometry(0.2, 0), matInvisible)]], - XY: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]]], - YZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]], - XZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]] - }; - const helperTranslate = { - START: [[new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, 'helper']], - END: [[new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, 'helper']], - DELTA: [[new Line(TranslateHelperGeometry(), matHelper), null, null, null, 'helper']], - X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']], - Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']], - Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']] - }; - const gizmoRotate = { - XYZE: [[new Mesh(CircleGeometry(0.5, 1), matGray), null, [0, Math.PI / 2, 0]]], - X: [[new Mesh(CircleGeometry(0.5, 0.5), matRed)]], - Y: [[new Mesh(CircleGeometry(0.5, 0.5), matGreen), null, [0, 0, -Math.PI / 2]]], - Z: [[new Mesh(CircleGeometry(0.5, 0.5), matBlue), null, [0, Math.PI / 2, 0]]], - E: [[new Mesh(CircleGeometry(0.75, 1), matYellowTransparent), null, [0, Math.PI / 2, 0]]] - }; - const helperRotate = { - AXIS: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']] - }; - const pickerRotate = { - XYZE: [[new Mesh(new SphereGeometry(0.25, 10, 8), matInvisible)]], - X: [[new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]]], - Y: [[new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]]], - Z: [[new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]]], - E: [[new Mesh(new TorusGeometry(0.75, 0.1, 2, 24), matInvisible)]] - }; - const gizmoScale = { - X: [[new Mesh(scaleHandleGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]], [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]], [new Mesh(scaleHandleGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]]], - Y: [[new Mesh(scaleHandleGeometry, matGreen), [0, 0.5, 0]], [new Mesh(lineGeometry2, matGreen)], [new Mesh(scaleHandleGeometry, matGreen), [0, -0.5, 0], [0, 0, Math.PI]]], - Z: [[new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]], [new Mesh(lineGeometry2, matBlue), [0, 0, 0], [Math.PI / 2, 0, 0]], [new Mesh(scaleHandleGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]]], - XY: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent), [0.15, 0.15, 0]]], - YZ: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]], - XZ: [[new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]], - XYZ: [[new Mesh(new BoxGeometry(0.1, 0.1, 0.1), matWhiteTransparent.clone())]] - }; - const pickerScale = { - X: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]]], - Y: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]]], - Z: [[new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]], [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]]], - XY: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]]], - YZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]], - XZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]], - XYZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [0, 0, 0]]] - }; - const helperScale = { - X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']], - Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']], - Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']] - }; + if (kind !== 'svg') { + console.error(`not supported element for SVGRenderer ${kind}`); + return null; + } - // Creates an Object3D with gizmos described in custom hierarchy definition. - - function setupGizmo(gizmoMap) { - const gizmo = new Object3D(); - for (const name in gizmoMap) { - for (let i = gizmoMap[name].length; i--;) { - const object = gizmoMap[name][i][0].clone(); - const position = gizmoMap[name][i][1]; - const rotation = gizmoMap[name][i][2]; - const scale = gizmoMap[name][i][3]; - const tag = gizmoMap[name][i][4]; - - // name and tag properties are essential for picking and updating logic. - object.name = name; - object.tag = tag; - if (position) { - object.position.set(position[0], position[1], position[2]); - } - if (rotation) { - object.rotation.set(rotation[0], rotation[1], rotation[2]); - } - if (scale) { - object.scale.set(scale[0], scale[1], scale[2]); - } - object.updateMatrix(); - const tempGeometry = object.geometry.clone(); - tempGeometry.applyMatrix4(object.matrix); - object.geometry = tempGeometry; - object.renderOrder = Infinity; - object.position.set(0, 0, 0); - object.rotation.set(0, 0, 0); - object.scale.set(1, 1, 1); - gizmo.add(object); - } - } - return gizmo; - } + return { + _wrapper: this, + childNodes: [], // may be accessed - make dummy + style: this.svg_style, // for background color + setAttribute(name, value) { + this._wrapper.svg_attr[name] = value; + }, + appendChild(_node) { + this._wrapper.accPath += ``; + this._wrapper.path_attr = {}; + }, + removeChild(_node) { + this.childNodes = []; + } + }; + } + }; - // Gizmo creation + let originalDocument; - this.gizmo = {}; - this.picker = {}; - this.helper = {}; - this.add(this.gizmo['translate'] = setupGizmo(gizmoTranslate)); - this.add(this.gizmo['rotate'] = setupGizmo(gizmoRotate)); - this.add(this.gizmo['scale'] = setupGizmo(gizmoScale)); - this.add(this.picker['translate'] = setupGizmo(pickerTranslate)); - this.add(this.picker['rotate'] = setupGizmo(pickerRotate)); - this.add(this.picker['scale'] = setupGizmo(pickerScale)); - this.add(this.helper['translate'] = setupGizmo(helperTranslate)); - this.add(this.helper['rotate'] = setupGizmo(helperRotate)); - this.add(this.helper['scale'] = setupGizmo(helperScale)); + if (isNodeJs()) { + originalDocument = globalThis.document; + globalThis.document = doc_wrapper; + } - // Pickers should be hidden always + const rndr = new SVGRenderer(); - this.picker['translate'].visible = false; - this.picker['rotate'].visible = false; - this.picker['scale'].visible = false; - } + if (isNodeJs()) + globalThis.document = originalDocument; - // updateMatrixWorld will update transformations and appearance of individual handles + rndr.doc_wrapper = doc_wrapper; // use it to get final SVG code - updateMatrixWorld(force) { - const space = this.mode === 'scale' ? 'local' : this.space; // scale always oriented to local rotation + rndr.originalRender = rndr.render; - const quaternion = space === 'local' ? this.worldQuaternion : _identityQuaternion; + rndr.render = function(scene, camera) { + const originalDocument = globalThis.document; + if (isNodeJs()) + globalThis.document = this.doc_wrapper; - // Show only gizmos for current transform mode + this.originalRender(scene, camera); - this.gizmo['translate'].visible = this.mode === 'translate'; - this.gizmo['rotate'].visible = this.mode === 'rotate'; - this.gizmo['scale'].visible = this.mode === 'scale'; - this.helper['translate'].visible = this.mode === 'translate'; - this.helper['rotate'].visible = this.mode === 'rotate'; - this.helper['scale'].visible = this.mode === 'scale'; - let handles = []; - handles = handles.concat(this.picker[this.mode].children); - handles = handles.concat(this.gizmo[this.mode].children); - handles = handles.concat(this.helper[this.mode].children); - for (let i = 0; i < handles.length; i++) { - const handle = handles[i]; + if (isNodeJs()) + globalThis.document = originalDocument; + }; - // hide aligned to camera + rndr.clearHTML = function() { + this.doc_wrapper.accPath = ''; + }; - handle.visible = true; - handle.rotation.set(0, 0, 0); - handle.position.copy(this.worldPosition); - let factor; - if (this.camera.isOrthographicCamera) { - factor = (this.camera.top - this.camera.bottom) / this.camera.zoom; - } else { - factor = this.worldPosition.distanceTo(this.cameraPosition) * Math.min(1.9 * Math.tan(Math.PI * this.camera.fov / 360) / this.camera.zoom, 7); - } - handle.scale.set(1, 1, 1).multiplyScalar(factor * this.size / 4); - - // TODO: simplify helpers and consider decoupling from gizmo - - if (handle.tag === 'helper') { - handle.visible = false; - if (handle.name === 'AXIS') { - handle.position.copy(this.worldPositionStart); - handle.visible = !!this.axis; - if (this.axis === 'X') { - _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, 0)); - handle.quaternion.copy(quaternion).multiply(_tempQuaternion); - if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { - handle.visible = false; - } - } - if (this.axis === 'Y') { - _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, Math.PI / 2)); - handle.quaternion.copy(quaternion).multiply(_tempQuaternion); - if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { - handle.visible = false; - } - } - if (this.axis === 'Z') { - _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0)); - handle.quaternion.copy(quaternion).multiply(_tempQuaternion); - if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { - handle.visible = false; - } - } - if (this.axis === 'XYZE') { - _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0)); - _alignVector.copy(this.rotationAxis); - handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(_zeroVector, _alignVector, _unitY)); - handle.quaternion.multiply(_tempQuaternion); - handle.visible = this.dragging; - } - if (this.axis === 'E') { - handle.visible = false; - } - } else if (handle.name === 'START') { - handle.position.copy(this.worldPositionStart); - handle.visible = this.dragging; - } else if (handle.name === 'END') { - handle.position.copy(this.worldPosition); - handle.visible = this.dragging; - } else if (handle.name === 'DELTA') { - handle.position.copy(this.worldPositionStart); - handle.quaternion.copy(this.worldQuaternionStart); - _tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1); - _tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()); - handle.scale.copy(_tempVector); - handle.visible = this.dragging; - } else { - handle.quaternion.copy(quaternion); - if (this.dragging) { - handle.position.copy(this.worldPositionStart); - } else { - handle.position.copy(this.worldPosition); - } - if (this.axis) { - handle.visible = this.axis.search(handle.name) !== -1; - } - } + rndr.makeOuterHTML = function() { + const wrap = this.doc_wrapper, + _textSizeAttr = `viewBox="${wrap.svg_attr.viewBox}" width="${wrap.svg_attr.width}" height="${wrap.svg_attr.height}"`, + _textClearAttr = wrap.svg_style.backgroundColor ? ` style="background:${wrap.svg_style.backgroundColor}"` : ''; - // If updating helper, skip rest of the loop - continue; - } + return `${wrap.accPath}`; + }; - // Align handles to current local or world rotation + rndr.fillTargetSVG = function(svg) { + if (isNodeJs()) { + const wrap = this.doc_wrapper; - handle.quaternion.copy(quaternion); - if (this.mode === 'translate' || this.mode === 'scale') { - // Hide translate and scale axis facing the camera + svg.setAttribute('viewBox', wrap.svg_attr.viewBox); + svg.setAttribute('width', wrap.svg_attr.width); + svg.setAttribute('height', wrap.svg_attr.height); + svg.style.background = wrap.svg_style.backgroundColor || ''; - const AXIS_HIDE_THRESHOLD = 0.99; - const PLANE_HIDE_THRESHOLD = 0.2; - if (handle.name === 'X') { - if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - if (handle.name === 'Y') { - if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - if (handle.name === 'Z') { - if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - if (handle.name === 'XY') { - if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - if (handle.name === 'YZ') { - if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - if (handle.name === 'XZ') { - if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { - handle.scale.set(1e-10, 1e-10, 1e-10); - handle.visible = false; - } - } - } else if (this.mode === 'rotate') { - // Align handles to current local or world rotation + svg.innerHTML = wrap.accPath; + } else { + const src = this.domElement; - _tempQuaternion2.copy(quaternion); - _alignVector.copy(this.eye).applyQuaternion(_tempQuaternion.copy(quaternion).invert()); - if (handle.name.search('E') !== -1) { - handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(this.eye, _zeroVector, _unitY)); - } - if (handle.name === 'X') { - _tempQuaternion.setFromAxisAngle(_unitX, Math.atan2(-_alignVector.y, _alignVector.z)); - _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); - handle.quaternion.copy(_tempQuaternion); - } - if (handle.name === 'Y') { - _tempQuaternion.setFromAxisAngle(_unitY, Math.atan2(_alignVector.x, _alignVector.z)); - _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); - handle.quaternion.copy(_tempQuaternion); - } - if (handle.name === 'Z') { - _tempQuaternion.setFromAxisAngle(_unitZ, Math.atan2(_alignVector.y, _alignVector.x)); - _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); - handle.quaternion.copy(_tempQuaternion); - } - } + svg.setAttribute('viewBox', src.getAttribute('viewBox')); + svg.setAttribute('width', src.getAttribute('width')); + svg.setAttribute('height', src.getAttribute('height')); + svg.style.background = src.style.backgroundColor; - // Hide disabled axes - handle.visible = handle.visible && (handle.name.indexOf('X') === -1 || this.showX); - handle.visible = handle.visible && (handle.name.indexOf('Y') === -1 || this.showY); - handle.visible = handle.visible && (handle.name.indexOf('Z') === -1 || this.showZ); - handle.visible = handle.visible && (handle.name.indexOf('E') === -1 || this.showX && this.showY && this.showZ); - - // highlight selected axis - - handle.material._color = handle.material._color || handle.material.color.clone(); - handle.material._opacity = handle.material._opacity || handle.material.opacity; - handle.material.color.copy(handle.material._color); - handle.material.opacity = handle.material._opacity; - if (this.enabled && this.axis) { - if (handle.name === this.axis) { - handle.material.color.setHex(0xffff00); - handle.material.opacity = 1.0; - } else if (this.axis.split('').some(function (a) { - return handle.name === a; - })) { - handle.material.color.setHex(0xffff00); - handle.material.opacity = 1.0; - } - } - } - super.updateMatrixWorld(force); - } + while (src.firstChild) { + const elem = src.firstChild; + src.removeChild(elem); + svg.appendChild(elem); + } + } + }; + + rndr.setPrecision(precision); + + return rndr; } -// -class TransformControlsPlane extends Mesh { - constructor() { - super(new PlaneGeometry(100000, 100000, 2, 2), new MeshBasicMaterial({ - visible: false, - wireframe: true, - side: DoubleSide, - transparent: true, - opacity: 0.1, - toneMapped: false - })); - this.isTransformControlsPlane = true; - this.type = 'TransformControlsPlane'; - } - updateMatrixWorld(force) { - let space = this.space; - this.position.copy(this.worldPosition); - if (this.mode === 'scale') space = 'local'; // scale always oriented to local rotation - - _v1.copy(_unitX).applyQuaternion(space === 'local' ? this.worldQuaternion : _identityQuaternion); - _v2.copy(_unitY).applyQuaternion(space === 'local' ? this.worldQuaternion : _identityQuaternion); - _v3.copy(_unitZ).applyQuaternion(space === 'local' ? this.worldQuaternion : _identityQuaternion); - - // Align the plane for current transform mode, axis and space. - - _alignVector.copy(_v2); - switch (this.mode) { - case 'translate': - case 'scale': - switch (this.axis) { - case 'X': - _alignVector.copy(this.eye).cross(_v1); - _dirVector.copy(_v1).cross(_alignVector); - break; - case 'Y': - _alignVector.copy(this.eye).cross(_v2); - _dirVector.copy(_v2).cross(_alignVector); - break; - case 'Z': - _alignVector.copy(this.eye).cross(_v3); - _dirVector.copy(_v3).cross(_alignVector); - break; - case 'XY': - _dirVector.copy(_v3); - break; - case 'YZ': - _dirVector.copy(_v1); - break; - case 'XZ': - _alignVector.copy(_v3); - _dirVector.copy(_v2); - break; - case 'XYZ': - case 'E': - _dirVector.set(0, 0, 0); - break; - } - break; - case 'rotate': - default: - // special case for rotate - _dirVector.set(0, 0, 0); - } - if (_dirVector.length() === 0) { - // If in rotate mode, make the plane parallel to camera - this.quaternion.copy(this.cameraQuaternion); - } else { - _tempMatrix.lookAt(_tempVector.set(0, 0, 0), _dirVector, _alignVector); - this.quaternion.setFromRotationMatrix(_tempMatrix); - } - super.updateMatrixWorld(force); - } +/** @ummary Define rendering kind which will be used for rendering of 3D elements + * @param {value} [render3d] - preconfigured value, will be used if applicable + * @param {value} [is_batch] - is batch mode is configured + * @return {value} - rendering kind, see constants.Render3D + * @private */ +function getRender3DKind(render3d, is_batch) { + if (is_batch === undefined) + is_batch = isBatchMode(); + + if (!render3d) render3d = is_batch ? settings.Render3DBatch : settings.Render3D; + const rc = constants$1.Render3D; + + if (render3d === rc.Default) render3d = is_batch ? rc.WebGLImage : rc.WebGL; + if (is_batch && (render3d === rc.WebGL)) render3d = rc.WebGLImage; + + return render3d; } -/** - * Full-screen textured quad shader - */ +const Handling3DDrawings = { -const CopyShader = { - uniforms: { - 'tDiffuse': { - value: null - }, - 'opacity': { - value: 1.0 - } - }, - vertexShader: /* glsl */` + /** @summary Access current 3d mode + * @param {string} [new_value] - when specified, set new 3d mode + * @return current value + * @private */ + access3dKind(new_value) { + const svg = this.getPadSvg(); + if (svg.empty()) return -1; - varying vec2 vUv; + // returns kind of currently created 3d canvas + const kind = svg.property('can3d'); + if (new_value !== undefined) svg.property('can3d', new_value); + return ((kind === null) || (kind === undefined)) ? -1 : kind; + }, - void main() { + /** @summary Returns size which availble for 3D drawing. + * @desc One uses frame sizes for the 3D drawing - like TH2/TH3 objects + * @private */ + getSizeFor3d(can3d /*, render3d */) { + if (can3d === undefined) { + // analyze which render/embed mode can be used + can3d = getRender3DKind(); + // all non-webgl elements can be embedded into SVG as is + if (can3d !== constants$1.Render3D.WebGL) + can3d = constants$1.Embed3D.EmbedSVG; + else if (settings.Embed3D !== constants$1.Embed3D.Default) + can3d = settings.Embed3D; + else if (browser.isFirefox) + can3d = constants$1.Embed3D.Embed; + else if (browser.chromeVersion > 95) + // version 96 works partially, 97 works fine + can3d = constants$1.Embed3D.Embed; + else + can3d = constants$1.Embed3D.Overlay; + } - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + const pad = this.getPadSvg(), + clname = 'draw3d_' + (this.getPadName() || 'canvas'); - }`, - fragmentShader: /* glsl */` + if (pad.empty()) { + // this is a case when object drawn without canvas - uniform float opacity; + const rect = getElementRect(this.selectDom()); + if ((rect.height < 10) && (rect.width > 10)) { + rect.height = Math.round(0.66 * rect.width); + this.selectDom().style('height', rect.height + 'px'); + } + rect.x = 0; rect.y = 0; rect.clname = clname; rect.can3d = -1; + return rect; + } - uniform sampler2D tDiffuse; + const fp = this.getFramePainter(), pp = this.getPadPainter(); + let size; - varying vec2 vUv; + if (fp?.mode3d && (can3d > 0)) + size = fp.getFrameRect(); + else { + let elem = (can3d > 0) ? pad : this.getCanvSvg(); + size = { x: 0, y: 0, width: elem.property('draw_width'), height: elem.property('draw_height') }; + if (Number.isNaN(size.width) || Number.isNaN(size.height)) { + size.width = pp.getPadWidth(); + size.height = pp.getPadHeight(); + } else if (fp && !fp.mode3d) { + elem = this.getFrameSvg(); + size.x = elem.property('draw_x'); + size.y = elem.property('draw_y'); + } + } - void main() { + size.clname = clname; + size.can3d = can3d; - gl_FragColor = texture2D( tDiffuse, vUv ); - gl_FragColor.a *= opacity; + const rect = pp?.getPadRect(); + if (rect) { + // while 3D canvas uses area also for the axis labels, extend area relative to normal frame + const dx = Math.round(size.width*0.07), dy = Math.round(size.height*0.05); + size.x = Math.max(0, size.x-dx); + size.y = Math.max(0, size.y-dy); + size.width = Math.min(size.width + 2*dx, rect.width - size.x); + size.height = Math.min(size.height + 2*dy, rect.height - size.y); + } - }` -}; + if (can3d === 1) + size = getAbsPosInCanvas(this.getPadSvg(), size); -class Pass { - constructor() { - // if set to true, the pass is processed by the composer - this.enabled = true; + return size; + }, - // if set to true, the pass indicates to swap read and write buffer after rendering - this.needsSwap = true; + /** @summary Clear all 3D drawings + * @return can3d value - how webgl canvas was placed + * @private */ + clear3dCanvas() { + const can3d = this.access3dKind(null); + if (can3d < 0) { + // remove first child from main element - if it is canvas + const main = this.selectDom().node(); + let chld = main?.firstChild; - // if set to true, the pass clears its buffer before rendering - this.clear = false; + if (chld && !chld.$jsroot) + chld = chld.nextSibling; - // if set to true, the result of the pass is rendered to screen. This is set automatically by EffectComposer. - this.renderToScreen = false; - } - setSize( /* width, height */) {} - render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ - ) { - console.error('THREE.Pass: .render() must be implemented in derived pass.'); - } - dispose() {} -} + if (chld?.$jsroot) { + delete chld.painter; + main.removeChild(chld); + } + return can3d; + } + + const size = this.getSizeFor3d(can3d); + if (size.can3d === 0) { + select(this.getCanvSvg().node().nextSibling).remove(); // remove html5 canvas + this.getCanvSvg().style('display', null); // show SVG canvas + } else { + if (this.getPadSvg().empty()) return; + + this.apply3dSize(size).remove(); + + this.getFrameSvg().style('display', null); // clear display property + } + return can3d; + }, + + /** @summary Add 3D canvas + * @private */ + add3dCanvas(size, canv, webgl) { + if (!canv || (size.can3d < -1)) return; + + if (size.can3d === -1) { + // case when 3D object drawn without canvas + + const main = this.selectDom().node(); + if (main !== null) { + main.appendChild(canv); + canv.painter = this; + canv.$jsroot = true; // mark canvas as added by jsroot + } + + return; + } + + if ((size.can3d > 0) && !webgl) + size.can3d = constants$1.Embed3D.EmbedSVG; + + this.access3dKind(size.can3d); + + if (size.can3d === 0) { + this.getCanvSvg().style('display', 'none'); // hide SVG canvas + + this.getCanvSvg().node().parentNode.appendChild(canv); // add directly + } else { + if (this.getPadSvg().empty()) return; + + // first hide normal frame + this.getFrameSvg().style('display', 'none'); + + const elem = this.apply3dSize(size); + elem.attr('title', '').node().appendChild(canv); + } + }, + + /** @summary Apply size to 3D elements + * @private */ + apply3dSize(size, onlyget) { + if (size.can3d < 0) + return select(null); + + let elem; + + if (size.can3d > 1) { + elem = this.getLayerSvg(size.clname); + if (onlyget) + return elem; + + const svg = this.getPadSvg(); + + if (size.can3d === constants$1.Embed3D.EmbedSVG) { + // this is SVG mode or image mode - just create group to hold element + + if (elem.empty()) + elem = svg.insert('g', '.primitives_layer').attr('class', size.clname); + + makeTranslate(elem, size.x, size.y); + } else { + if (elem.empty()) + elem = svg.insert('foreignObject', '.primitives_layer').attr('class', size.clname); + + elem.attr('x', size.x) + .attr('y', size.y) + .attr('width', size.width) + .attr('height', size.height) + .attr('viewBox', `0 0 ${size.width} ${size.height}`) + .attr('preserveAspectRatio', 'xMidYMid'); + } + } else { + let prnt = this.getCanvSvg().node().parentNode; + + elem = select(prnt).select('.' + size.clname); + if (onlyget) + return elem; + + // force redraw by resize + this.getCanvSvg().property('redraw_by_resize', true); + + if (elem.empty()) { + elem = select(prnt).append('div').attr('class', size.clname) + .style('user-select', 'none'); + } + + // our position inside canvas, but to set 'absolute' position we should use + // canvas element offset relative to first parent with non-static position + // now try to use getBoundingClientRect - it should be more precise + + const pos0 = prnt.getBoundingClientRect(), doc = getDocument(); + + while (prnt) { + if (prnt === doc) { prnt = null; break; } + try { + if (getComputedStyle(prnt).position !== 'static') break; + } catch (err) { + break; + } + prnt = prnt.parentNode; + } -// Helper for passes that need to fill the viewport with a single quad. + const pos1 = prnt?.getBoundingClientRect() ?? { top: 0, left: 0 }, + offx = Math.round(pos0.left - pos1.left), + offy = Math.round(pos0.top - pos1.top); -const _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + elem.style('position', 'absolute').style('left', (size.x + offx) + 'px').style('top', (size.y + offy) + 'px').style('width', size.width + 'px').style('height', size.height + 'px'); + } -// https://github.com/mrdoob/three.js/pull/21358 + return elem; + } -const _geometry$1 = new BufferGeometry(); -_geometry$1.setAttribute('position', new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); -_geometry$1.setAttribute('uv', new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); -class FullScreenQuad { - constructor(material) { - this._mesh = new Mesh(_geometry$1, material); - } - dispose() { - this._mesh.geometry.dispose(); - } - render(renderer) { - renderer.render(this._mesh, _camera); - } - get material() { - return this._mesh.material; - } - set material(value) { - this._mesh.material = value; - } -} +}; // Handling3DDrawings -class ShaderPass extends Pass { - constructor(shader, textureID) { - super(); - this.textureID = textureID !== undefined ? textureID : 'tDiffuse'; - if (shader instanceof ShaderMaterial) { - this.uniforms = shader.uniforms; - this.material = shader; - } else if (shader) { - this.uniforms = UniformsUtils.clone(shader.uniforms); - this.material = new ShaderMaterial({ - defines: Object.assign({}, shader.defines), - uniforms: this.uniforms, - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }); - } - this.fsQuad = new FullScreenQuad(this.material); - } - render(renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) { - if (this.uniforms[this.textureID]) { - this.uniforms[this.textureID].value = readBuffer.texture; - } - this.fsQuad.material = this.material; - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(writeBuffer); - // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600 - if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); - this.fsQuad.render(renderer); - } - } - dispose() { - this.material.dispose(); - this.fsQuad.dispose(); - } + +/** @summary Assigns method to handle 3D drawings inside SVG + * @private */ +function assign3DHandler(painter) { + Object.assign(painter, Handling3DDrawings); } -class MaskPass extends Pass { - constructor(scene, camera) { - super(); - this.scene = scene; - this.camera = camera; - this.clear = true; - this.needsSwap = false; - this.inverse = false; - } - render(renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) { - const context = renderer.getContext(); - const state = renderer.state; - // don't update color or depth +/** @summary Creates renderer for the 3D drawings + * @param {value} width - rendering width + * @param {value} height - rendering height + * @param {value} render3d - render type, see {@link constants.Render3D} + * @param {object} args - different arguments for creating 3D renderer + * @return {Promise} with renderer object + * @private */ +async function createRender3D(width, height, render3d, args) { + const rc = constants$1.Render3D, doc = getDocument(); - state.buffers.color.setMask(false); - state.buffers.depth.setMask(false); + render3d = getRender3DKind(render3d); - // lock buffers + if (!args) args = { antialias: true, alpha: true }; - state.buffers.color.setLocked(true); - state.buffers.depth.setLocked(true); + let promise; - // set up stencil + if (render3d === rc.SVG) { + // SVG rendering + const r = createSVGRenderer(false, 0, doc); + r.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); + promise = Promise.resolve(r); + } else if (isNodeJs()) { + // try to use WebGL inside node.js - need to create headless context + promise = Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(node_canvas => { + args.canvas = node_canvas.default.createCanvas(width, height); + args.canvas.addEventListener = () => {}; // dummy + args.canvas.removeEventListener = () => {}; // dummy + args.canvas.style = {}; + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }); + }).then(node_gl => { + const gl = node_gl.default(width, height, { preserveDrawingBuffer: true }); + if (!gl) throw Error('Fail to create headless-gl'); + args.context = gl; + gl.canvas = args.canvas; - let writeValue, clearValue; - if (this.inverse) { - writeValue = 0; - clearValue = 1; - } else { - writeValue = 1; - clearValue = 0; - } - state.buffers.stencil.setTest(true); - state.buffers.stencil.setOp(context.REPLACE, context.REPLACE, context.REPLACE); - state.buffers.stencil.setFunc(context.ALWAYS, writeValue, 0xffffffff); - state.buffers.stencil.setClear(clearValue); - state.buffers.stencil.setLocked(true); + const r = new WebGLRenderer(args); + r.jsroot_output = new WebGLRenderTarget(width, height); + r.setRenderTarget(r.jsroot_output); + r.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'image'); + return r; + }); + } else if (render3d === rc.WebGL) { + // interactive WebGL Rendering + promise = Promise.resolve(new WebGLRenderer(args)); + } else { + // rendering with WebGL directly into svg image + const r = new WebGLRenderer(args); + r.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'image'); + promise = Promise.resolve(r); + } - // draw into the stencil buffer + return promise.then(renderer => { + if (!renderer.jsroot_dom) + renderer.jsroot_dom = renderer.domElement; + else + renderer.jsroot_custom_dom = true; - renderer.setRenderTarget(readBuffer); - if (this.clear) renderer.clear(); - renderer.render(this.scene, this.camera); - renderer.setRenderTarget(writeBuffer); - if (this.clear) renderer.clear(); - renderer.render(this.scene, this.camera); + // res.renderer.setClearColor('#000000', 1); + // res.renderer.setClearColor(0x0, 0); + renderer.jsroot_render3d = render3d; - // unlock color and depth buffer for subsequent rendering + // which format used to convert into images + renderer.jsroot_image_format = 'png'; - state.buffers.color.setLocked(false); - state.buffers.depth.setLocked(false); + renderer.originalSetSize = renderer.setSize; - // only render where stencil is set to 1 + // apply size to dom element + renderer.setSize = function(width, height, updateStyle) { + if (this.jsroot_custom_dom) { + this.jsroot_dom.setAttribute('width', width); + this.jsroot_dom.setAttribute('height', height); + } - state.buffers.stencil.setLocked(false); - state.buffers.stencil.setFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 - state.buffers.stencil.setOp(context.KEEP, context.KEEP, context.KEEP); - state.buffers.stencil.setLocked(true); - } -} -class ClearMaskPass extends Pass { - constructor() { - super(); - this.needsSwap = false; - } - render(renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */) { - renderer.state.buffers.stencil.setLocked(false); - renderer.state.buffers.stencil.setTest(false); - } -} + this.originalSetSize(width, height, updateStyle); + }; -class EffectComposer { - constructor(renderer, renderTarget) { - this.renderer = renderer; - if (renderTarget === undefined) { - const size = renderer.getSize(new Vector2()); - this._pixelRatio = renderer.getPixelRatio(); - this._width = size.width; - this._height = size.height; - renderTarget = new WebGLRenderTarget(this._width * this._pixelRatio, this._height * this._pixelRatio); - renderTarget.texture.name = 'EffectComposer.rt1'; - } else { - this._pixelRatio = 1; - this._width = renderTarget.width; - this._height = renderTarget.height; - } - this.renderTarget1 = renderTarget; - this.renderTarget2 = renderTarget.clone(); - this.renderTarget2.texture.name = 'EffectComposer.rt2'; - this.writeBuffer = this.renderTarget1; - this.readBuffer = this.renderTarget2; - this.renderToScreen = true; - this.passes = []; + renderer.setSize(width, height); - // dependencies + return renderer; + }); +} - if (CopyShader === undefined) { - console.error('THREE.EffectComposer relies on CopyShader'); - } - if (ShaderPass === undefined) { - console.error('THREE.EffectComposer relies on ShaderPass'); - } - this.copyPass = new ShaderPass(CopyShader); - this.clock = new Clock(); - } - swapBuffers() { - const tmp = this.readBuffer; - this.readBuffer = this.writeBuffer; - this.writeBuffer = tmp; - } - addPass(pass) { - this.passes.push(pass); - pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); - } - insertPass(pass, index) { - this.passes.splice(index, 0, pass); - pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); - } - removePass(pass) { - const index = this.passes.indexOf(pass); - if (index !== -1) { - this.passes.splice(index, 1); - } - } - isLastEnabledPass(passIndex) { - for (let i = passIndex + 1; i < this.passes.length; i++) { - if (this.passes[i].enabled) { - return false; - } - } - return true; - } - render(deltaTime) { - // deltaTime value is in seconds - if (deltaTime === undefined) { - deltaTime = this.clock.getDelta(); - } - const currentRenderTarget = this.renderer.getRenderTarget(); - let maskActive = false; - for (let i = 0, il = this.passes.length; i < il; i++) { - const pass = this.passes[i]; - if (pass.enabled === false) continue; - pass.renderToScreen = this.renderToScreen && this.isLastEnabledPass(i); - pass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive); - if (pass.needsSwap) { - if (maskActive) { - const context = this.renderer.getContext(); - const stencil = this.renderer.state.buffers.stencil; +/** @summary Cleanup created renderer object + * @private */ +function cleanupRender3D(renderer) { + if (!renderer) return; - //context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff ); - stencil.setFunc(context.NOTEQUAL, 1, 0xffffffff); - this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime); + if (isNodeJs()) { + const ctxt = isFunc(renderer.getContext) ? renderer.getContext() : null, + ext = ctxt?.getExtension('STACKGL_destroy_context'); + if (isFunc(ext?.destroy)) + ext.destroy(); + } else { + // suppress warnings in Chrome about lost webgl context, not required in firefox + if (browser.isChrome && isFunc(renderer.forceContextLoss)) + renderer.forceContextLoss(); - //context.stencilFunc( context.EQUAL, 1, 0xffffffff ); - stencil.setFunc(context.EQUAL, 1, 0xffffffff); - } - this.swapBuffers(); - } - if (MaskPass !== undefined) { - if (pass instanceof MaskPass) { - maskActive = true; - } else if (pass instanceof ClearMaskPass) { - maskActive = false; - } - } - } - this.renderer.setRenderTarget(currentRenderTarget); - } - reset(renderTarget) { - if (renderTarget === undefined) { - const size = this.renderer.getSize(new Vector2()); - this._pixelRatio = this.renderer.getPixelRatio(); - this._width = size.width; - this._height = size.height; - renderTarget = this.renderTarget1.clone(); - renderTarget.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); - } - this.renderTarget1.dispose(); - this.renderTarget2.dispose(); - this.renderTarget1 = renderTarget; - this.renderTarget2 = renderTarget.clone(); - this.writeBuffer = this.renderTarget1; - this.readBuffer = this.renderTarget2; - } - setSize(width, height) { - this._width = width; - this._height = height; - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; - this.renderTarget1.setSize(effectiveWidth, effectiveHeight); - this.renderTarget2.setSize(effectiveWidth, effectiveHeight); - for (let i = 0; i < this.passes.length; i++) { - this.passes[i].setSize(effectiveWidth, effectiveHeight); - } - } - setPixelRatio(pixelRatio) { - this._pixelRatio = pixelRatio; - this.setSize(this._width, this._height); - } - dispose() { - this.renderTarget1.dispose(); - this.renderTarget2.dispose(); - this.copyPass.dispose(); - } + if (isFunc(renderer.dispose)) + renderer.dispose(); + } } -// Helper for passes that need to fill the viewport with a single quad. +/** @summary Cleanup previous renderings before doing next one + * @desc used together with SVG + * @private */ +function beforeRender3D(renderer) { + if (isFunc(renderer.clearHTML)) + renderer.clearHTML(); +} -new OrthographicCamera(-1, 1, 1, -1, 0, 1); +/** @summary Post-process result of rendering + * @desc used together with SVG or node.js image rendering + * @private */ +function afterRender3D(renderer) { + const rc = constants$1.Render3D; -// https://github.com/mrdoob/three.js/pull/21358 + if (renderer.jsroot_render3d === rc.WebGL) + return; -const _geometry = new BufferGeometry(); -_geometry.setAttribute('position', new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); -_geometry.setAttribute('uv', new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); + if (renderer.jsroot_render3d === rc.SVG) { + // case of SVGRenderer + renderer.fillTargetSVG(renderer.jsroot_dom); + } else if (isNodeJs()) { + // this is WebGL rendering in node.js + const canvas = renderer.domElement, + context = canvas.getContext('2d'), + pixels = new Uint8Array(4 * canvas.width * canvas.height); -class RenderPass extends Pass { - constructor(scene, camera, overrideMaterial, clearColor, clearAlpha) { - super(); - this.scene = scene; - this.camera = camera; - this.overrideMaterial = overrideMaterial; - this.clearColor = clearColor; - this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0; - this.clear = true; - this.clearDepth = false; - this.needsSwap = false; - this._oldClearColor = new Color$1(); - } - render(renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) { - const oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - let oldClearAlpha, oldOverrideMaterial; - if (this.overrideMaterial !== undefined) { - oldOverrideMaterial = this.scene.overrideMaterial; - this.scene.overrideMaterial = this.overrideMaterial; - } - if (this.clearColor) { - renderer.getClearColor(this._oldClearColor); - oldClearAlpha = renderer.getClearAlpha(); - renderer.setClearColor(this.clearColor, this.clearAlpha); - } - if (this.clearDepth) { - renderer.clearDepth(); - } - renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); + renderer.readRenderTargetPixels(renderer.jsroot_output, 0, 0, canvas.width, canvas.height, pixels); - // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600 - if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); - renderer.render(this.scene, this.camera); - if (this.clearColor) { - renderer.setClearColor(this._oldClearColor, oldClearAlpha); - } - if (this.overrideMaterial !== undefined) { - this.scene.overrideMaterial = oldOverrideMaterial; - } - renderer.autoClear = oldAutoClear; - } -} + // small code to flip Y scale + let indx1 = 0, indx2 = (canvas.height - 1) * 4 * canvas.width, k, d; + while (indx1 < indx2) { + for (k = 0; k < 4 * canvas.width; ++k) { + d = pixels[indx1 + k]; pixels[indx1 + k] = pixels[indx2 + k]; pixels[indx2 + k] = d; + } + indx1 += 4 * canvas.width; + indx2 -= 4 * canvas.width; + } -/** - * References: - * http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html - * https://learnopengl.com/Advanced-Lighting/SSAO - * https://github.com/McNopper/OpenGL/blob/master/Example28/shader/ssao.frag.glsl - */ + const imageData = context.createImageData(canvas.width, canvas.height); + imageData.data.set(pixels); + context.putImageData(imageData, 0, 0); -const SSAOShader = { - defines: { - 'PERSPECTIVE_CAMERA': 1, - 'KERNEL_SIZE': 32 - }, - uniforms: { - 'tDiffuse': { - value: null - }, - 'tNormal': { - value: null - }, - 'tDepth': { - value: null - }, - 'tNoise': { - value: null - }, - 'kernel': { - value: null - }, - 'cameraNear': { - value: null - }, - 'cameraFar': { - value: null - }, - 'resolution': { - value: new Vector2() - }, - 'cameraProjectionMatrix': { - value: new Matrix4() - }, - 'cameraInverseProjectionMatrix': { - value: new Matrix4() - }, - 'kernelRadius': { - value: 8 - }, - 'minDistance': { - value: 0.005 - }, - 'maxDistance': { - value: 0.05 - } - }, - vertexShader: /* glsl */` + const format = 'image/' + renderer.jsroot_image_format, + dataUrl = canvas.toDataURL(format); - varying vec2 vUv; + renderer.jsroot_dom.setAttribute('href', dataUrl); + } else { + const dataUrl = renderer.domElement.toDataURL('image/' + renderer.jsroot_image_format); + renderer.jsroot_dom.setAttribute('href', dataUrl); + } +} - void main() { +// ======================================================================================================== - vUv = uv; +/** + * @summary Tooltip handler for 3D drawings + * + * @private + */ - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +class TooltipFor3D { - }`, - fragmentShader: /* glsl */` + /** @summary constructor + * @param {object} dom - DOM element + * @param {object} canvas - canvas for 3D rendering */ + constructor(prnt, canvas) { + this.tt = null; + this.cont = null; + this.lastlbl = ''; + this.parent = prnt || getDocument().body; + this.canvas = canvas; // we need canvas to recalculate mouse events + this.abspos = !prnt; + } - uniform sampler2D tDiffuse; - uniform sampler2D tNormal; - uniform sampler2D tDepth; - uniform sampler2D tNoise; + /** @summary check parent */ + checkParent(prnt) { + if (prnt && (this.parent !== prnt)) { + this.hide(); + this.parent = prnt; + } + } + + /** @summary extract position from event + * @desc can be used to process it later when event is gone */ + extract_pos(e) { + if (isObject(e) && (e.u !== undefined) && (e.l !== undefined)) return e; + const res = { u: 0, l: 0 }; + if (this.abspos) { + res.l = e.pageX; + res.u = e.pageY; + } else { + res.l = e.offsetX; + res.u = e.offsetY; + } + return res; + } - uniform vec3 kernel[ KERNEL_SIZE ]; + /** @summary Method used to define position of next tooltip + * @desc event is delivered from canvas, + * but position should be calculated relative to the element where tooltip is placed */ + pos(e) { + if (!this.tt) return; - uniform vec2 resolution; + const pos = this.extract_pos(e); + if (!this.abspos) { + const rect1 = this.parent.getBoundingClientRect(), + rect2 = this.canvas.getBoundingClientRect(); - uniform float cameraNear; - uniform float cameraFar; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; + if ((rect1.left !== undefined) && (rect2.left!== undefined)) + pos.l += (rect2.left-rect1.left); - uniform float kernelRadius; - uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference - uniform float maxDistance; // avoid the influence of fragments which are too far away + if ((rect1.top !== undefined) && (rect2.top!== undefined)) + pos.u += rect2.top-rect1.top; - varying vec2 vUv; + if (pos.l + this.tt.offsetWidth + 3 >= this.parent.offsetWidth) + pos.l = this.parent.offsetWidth - this.tt.offsetWidth - 3; - #include + if (pos.u + this.tt.offsetHeight + 15 >= this.parent.offsetHeight) + pos.u = this.parent.offsetHeight - this.tt.offsetHeight - 15; - float getDepth( const in vec2 screenPosition ) { + // one should find parent with non-static position, + // all absolute coordinates calculated relative to such node + let abs_parent = this.parent; + while (abs_parent) { + const style = getComputedStyle(abs_parent); + if (!style || (style.position !== 'static')) break; + if (!abs_parent.parentNode || (abs_parent.parentNode.nodeType !== 1)) break; + abs_parent = abs_parent.parentNode; + } - return texture2D( tDepth, screenPosition ).x; + if (abs_parent && (abs_parent !== this.parent)) { + const rect0 = abs_parent.getBoundingClientRect(); + pos.l += (rect1.left - rect0.left); + pos.u += (rect1.top - rect0.top); + } + } - } + this.tt.style.top = `${pos.u+15}px`; + this.tt.style.left = `${pos.l+3}px`; + } - float getLinearDepth( const in vec2 screenPosition ) { + /** @summary Show tooltip */ + show(v /* , mouse_pos, status_func */) { + if (!v) return this.hide(); - #if PERSPECTIVE_CAMERA == 1 + if (isObject(v) && (v.lines || v.line)) { + if (v.only_status) return this.hide(); - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + if (v.line) + v = v.line; + else { + let res = v.lines[0]; + for (let n = 1; n < v.lines.length; ++n) + res += '
' + v.lines[n]; + v = res; + } + } - #else + if (this.tt === null) { + const doc = getDocument(); + this.tt = doc.createElement('div'); + this.tt.setAttribute('style', 'opacity: 1; filter: alpha(opacity=1); position: absolute; display: block; overflow: hidden; z-index: 101;'); + this.cont = doc.createElement('div'); + this.cont.setAttribute('style', 'display: block; padding: 2px 12px 3px 7px; margin-left: 5px; font-size: 11px; background: #777; color: #fff;'); + this.tt.appendChild(this.cont); + this.parent.appendChild(this.tt); + } - return texture2D( tDepth, screenPosition ).x; + if (this.lastlbl !== v) { + this.cont.innerHTML = v; + this.lastlbl = v; + this.tt.style.width = 'auto'; // let it be automatically resizing... + } + } - #endif + /** @summary Hide tooltip */ + hide() { + if (this.tt !== null) + this.parent.removeChild(this.tt); - } + this.tt = null; + this.lastlbl = ''; + } - float getViewZ( const in float depth ) { +} // class TooltipFor3D - #if PERSPECTIVE_CAMERA == 1 +/** @summary Create OrbitControls for painter + * @private */ +function createOrbitControl(painter, camera, scene, renderer, lookat) { + const enable_zoom = settings.Zooming && settings.ZoomMouse, + enable_select = isFunc(painter.processMouseClick); - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + let control = null; - #else + function control_mousedown(evnt) { + if (!control) return; - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + // function used to hide some events from orbit control and redirect them to zooming rect + if (control.mouse_zoom_mesh) { + evnt.stopImmediatePropagation(); + evnt.stopPropagation(); + return; + } - #endif + // only left-button is considered + if ((evnt.button!==undefined) && (evnt.button !== 0)) return; + if ((evnt.buttons!==undefined) && (evnt.buttons !== 1)) return; - } + if (control.enable_zoom) { + control.mouse_zoom_mesh = control.detectZoomMesh(evnt); + if (control.mouse_zoom_mesh) { + // just block orbit control + evnt.stopImmediatePropagation(); + evnt.stopPropagation(); + return; + } + } - vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + if (control.enable_select) + control.mouse_select_pnt = control.getMousePos(evnt, {}); + } - float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + function control_mouseup(evnt) { + if (!control) return; - vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + if (control.mouse_zoom_mesh && control.mouse_zoom_mesh.point2 && control.painter.get3dZoomCoord) { + let kind = control.mouse_zoom_mesh.object.zoom, + pos1 = control.painter.get3dZoomCoord(control.mouse_zoom_mesh.point, kind), + pos2 = control.painter.get3dZoomCoord(control.mouse_zoom_mesh.point2, kind); - clipPosition *= clipW; // unprojection. + if (pos1 > pos2) + [pos1, pos2] = [pos2, pos1]; - return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + if ((kind === 'z') && control.mouse_zoom_mesh.object.use_y_for_z) kind = 'y'; - } + // try to zoom + if ((pos1 < pos2) && control.painter.zoom(kind, pos1, pos2)) + control.mouse_zoom_mesh = null; + } - vec3 getViewNormal( const in vec2 screenPosition ) { + // if selection was drawn, it should be removed and picture rendered again + if (control.enable_zoom) + control.removeZoomMesh(); - return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + // only left-button is considered + // if ((evnt.button!==undefined) && (evnt.button !== 0)) return; + // if ((evnt.buttons!==undefined) && (evnt.buttons !== 1)) return; - } + if (control.enable_select && control.mouse_select_pnt) { + const pnt = control.getMousePos(evnt, {}), + same_pnt = (pnt.x === control.mouse_select_pnt.x) && (pnt.y === control.mouse_select_pnt.y); + delete control.mouse_select_pnt; - void main() { + if (same_pnt) { + const intersects = control.getMouseIntersects(pnt); + control.painter.processMouseClick(pnt, intersects, evnt); + } + } + } - float depth = getDepth( vUv ); - float viewZ = getViewZ( depth ); + function render3DFired(painter) { + if (!painter || painter.renderer === undefined) return false; + return painter.render_tmout !== undefined; // when timeout configured, object is prepared for rendering + } - vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); - vec3 viewNormal = getViewNormal( vUv ); + function control_mousewheel(evnt) { + if (!control) return; - vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); - vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); + // try to handle zoom extra + if (render3DFired(control.painter) || control.mouse_zoom_mesh) { + evnt.preventDefault(); + evnt.stopPropagation(); + evnt.stopImmediatePropagation(); + return; // already fired redraw, do not react on the mouse wheel + } - // compute matrix used to reorient a kernel vector + const intersect = control.detectZoomMesh(evnt); + if (!intersect) return; - vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); - vec3 bitangent = cross( viewNormal, tangent ); - mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); + evnt.preventDefault(); + evnt.stopPropagation(); + evnt.stopImmediatePropagation(); - float occlusion = 0.0; + if (isFunc(control.painter?.analyzeMouseWheelEvent)) { + let kind = intersect.object.zoom, + position = intersect.point[kind]; + const item = { name: kind, ignore: false }; - for ( int i = 0; i < KERNEL_SIZE; i ++ ) { + // z changes from 0..2*size_z3d, others -size_x3d..+size_x3d + switch (kind) { + case 'x': position = (position + control.painter.size_x3d)/2/control.painter.size_x3d; break; + case 'y': position = (position + control.painter.size_y3d)/2/control.painter.size_y3d; break; + case 'z': position = position/2/control.painter.size_z3d; break; + } - vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space - vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point + control.painter.analyzeMouseWheelEvent(evnt, item, position, false); - vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC - samplePointNDC /= samplePointNDC.w; + if ((kind === 'z') && intersect.object.use_y_for_z) kind = 'y'; - vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates + control.painter.zoom(kind, item.min, item.max); + } + } - float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture - float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value - float delta = sampleDepth - realDepth; + // assign own handler before creating OrbitControl - if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion + if (settings.Zooming && settings.ZoomWheel) + renderer.domElement.addEventListener('wheel', control_mousewheel); - occlusion += 1.0; + if (enable_zoom || enable_select) { + renderer.domElement.addEventListener('pointerdown', control_mousedown); + renderer.domElement.addEventListener('pointerup', control_mouseup); + } - } + control = new OrbitControls(camera, renderer.domElement); - } + control.enableDamping = false; + control.dampingFactor = 1.0; + control.enableZoom = true; + control.enableKeys = settings.HandleKeys; - occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); + if (lookat) { + control.target.copy(lookat); + control.target0.copy(lookat); + control.update(); + } - gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); + control.tooltip = new TooltipFor3D(painter.selectDom().node(), renderer.domElement); - }` -}; -const SSAODepthShader = { - defines: { - 'PERSPECTIVE_CAMERA': 1 - }, - uniforms: { - 'tDepth': { - value: null - }, - 'cameraNear': { - value: null - }, - 'cameraFar': { - value: null - } - }, - vertexShader: `varying vec2 vUv; + control.painter = painter; + control.camera = camera; + control.scene = scene; + control.renderer = renderer; + control.raycaster = new Raycaster(); + control.raycaster.params.Line.threshold = 10; + control.raycaster.params.Points.threshold = 5; + control.mouse_zoom_mesh = null; // zoom mesh, currently used in the zooming + control.block_ctxt = false; // require to block context menu command appearing after control ends, required in chrome which inject contextmenu when key released + control.block_mousemove = false; // when true, tooltip or cursor will not react on mouse move + control.cursor_changed = false; + control.control_changed = false; + control.control_active = false; + control.mouse_ctxt = { x: 0, y: 0, on: false }; + control.enable_zoom = enable_zoom; + control.enable_select = enable_select; - void main() { + control.cleanup = function() { + if (settings.Zooming && settings.ZoomWheel) + this.domElement.removeEventListener('wheel', control_mousewheel); + if (this.enable_zoom || this.enable_select) { + this.domElement.removeEventListener('pointerdown', control_mousedown); + this.domElement.removeEventListener('pointerup', control_mouseup); + } - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + this.domElement.removeEventListener('click', this.lstn_click); + this.domElement.removeEventListener('dblclick', this.lstn_dblclick); + this.domElement.removeEventListener('contextmenu', this.lstn_contextmenu); + this.domElement.removeEventListener('mousemove', this.lstn_mousemove); + this.domElement.removeEventListener('mouseleave', this.lstn_mouseleave); - }`, - fragmentShader: `uniform sampler2D tDepth; + this.dispose(); // this is from OrbitControl itself - uniform float cameraNear; - uniform float cameraFar; + this.tooltip.hide(); + delete this.tooltip; + delete this.painter; + delete this.camera; + delete this.scene; + delete this.renderer; + delete this.raycaster; + delete this.mouse_zoom_mesh; + }; - varying vec2 vUv; + control.HideTooltip = function() { + this.tooltip.hide(); + }; - #include + control.getMousePos = function(evnt, mouse) { + mouse.x = ('offsetX' in evnt) ? evnt.offsetX : evnt.layerX; + mouse.y = ('offsetY' in evnt) ? evnt.offsetY : evnt.layerY; + mouse.clientX = evnt.clientX; + mouse.clientY = evnt.clientY; + return mouse; + }; - float getLinearDepth( const in vec2 screenPosition ) { + control.getOriginDirectionIntersects = function(origin, direction) { + this.raycaster.set(origin, direction); + let intersects = this.raycaster.intersectObjects(this.scene.children, true); + // painter may want to filter intersects + if (isFunc(this.painter.filterIntersects)) + intersects = this.painter.filterIntersects(intersects); + return intersects; + }; - #if PERSPECTIVE_CAMERA == 1 + control.getMouseIntersects = function(mouse) { + // domElement gives correct coordinate with canvas render, but isn't always right for webgl renderer + if (!this.renderer) return []; - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + const sz = (this.renderer instanceof SVGRenderer) ? this.renderer.domElement : this.renderer.getSize(new Vector2()), + pnt = { x: mouse.x / sz.width * 2 - 1, y: -mouse.y / sz.height * 2 + 1 }; - #else + this.camera.updateMatrix(); + this.camera.updateMatrixWorld(); + this.raycaster.setFromCamera(pnt, this.camera); + let intersects = this.raycaster.intersectObjects(this.scene.children, true); - return texture2D( tDepth, screenPosition ).x; + // painter may want to filter intersects + if (isFunc(this.painter.filterIntersects)) + intersects = this.painter.filterIntersects(intersects); - #endif + return intersects; + }; - } + control.detectZoomMesh = function(evnt) { + const mouse = this.getMousePos(evnt, {}), + intersects = this.getMouseIntersects(mouse); + if (intersects) { + for (let n = 0; n < intersects.length; ++n) { + if (intersects[n].object.zoom && !intersects[n].object.zoom_disabled) + return intersects[n]; + } + } - void main() { + return null; + }; - float depth = getLinearDepth( vUv ); - gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + control.getInfoAtMousePosition = function(mouse_pos) { + const intersects = this.getMouseIntersects(mouse_pos); + let tip = null, painter = null; - }` -}; -const SSAOBlurShader = { - uniforms: { - 'tDiffuse': { - value: null - }, - 'resolution': { - value: new Vector2() - } - }, - vertexShader: `varying vec2 vUv; + for (let i = 0; i < intersects.length; ++i) { + if (intersects[i].object.tooltip) { + tip = intersects[i].object.tooltip(intersects[i]); + painter = intersects[i].object.painter; + break; + } + } - void main() { + if (tip && painter) { + return { obj: painter.getObject(), name: painter.getObject().fName, + bin: tip.bin, cont: tip.value, + binx: tip.ix, biny: tip.iy, binz: tip.iz, + grx: (tip.x1+tip.x2)/2, gry: (tip.y1+tip.y2)/2, grz: (tip.z1+tip.z2)/2 }; + } + }; - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + control.processDblClick = function(evnt) { + // first check if zoom mesh clicked + const zoom_intersect = this.detectZoomMesh(evnt); + if (zoom_intersect && this.painter) { + this.painter.unzoom(zoom_intersect.object.use_y_for_z ? 'y' : zoom_intersect.object.zoom); + return; + } - }`, - fragmentShader: `uniform sampler2D tDiffuse; + // then check if double-click handler assigned + const fp = this.painter?.getFramePainter(); + if (isFunc(fp?._dblclick_handler)) { + const info = this.getInfoAtMousePosition(this.getMousePos(evnt, {})); + if (info) { + fp._dblclick_handler(info); + return; + } + } - uniform vec2 resolution; + this.reset(); + }; - varying vec2 vUv; + control.changeEvent = function() { + this.mouse_ctxt.on = false; // disable context menu if any changes where done by orbit control + this.painter.render3D(0); + this.control_changed = true; + }; - void main() { + control.startEvent = function() { + this.control_active = true; + this.block_ctxt = false; + this.mouse_ctxt.on = false; - vec2 texelSize = ( 1.0 / resolution ); - float result = 0.0; + this.tooltip.hide(); - for ( int i = - 2; i <= 2; i ++ ) { + // do not reset here, problem of events sequence in orbitcontrol + // it issue change/start/stop event when do zooming + // control.control_changed = false; + }; - for ( int j = - 2; j <= 2; j ++ ) { + control.endEvent = function() { + this.control_active = false; + if (this.mouse_ctxt.on) { + this.mouse_ctxt.on = false; + this.contextMenu(this.mouse_ctxt, this.getMouseIntersects(this.mouse_ctxt)); + } /* else if (this.control_changed) { + // react on camera change when required + } */ + this.control_changed = false; + }; - vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; - result += texture2D( tDiffuse, vUv + offset ).r; + control.mainProcessContextMenu = function(evnt) { + evnt.preventDefault(); + this.getMousePos(evnt, this.mouse_ctxt); + if (this.control_active) + this.mouse_ctxt.on = true; + else if (this.block_ctxt) + this.block_ctxt = false; + else + this.contextMenu(this.mouse_ctxt, this.getMouseIntersects(this.mouse_ctxt)); + }; - } + control.contextMenu = function(/* pos, intersects */) { + // do nothing, function called when context menu want to be activated + }; - } + control.setTooltipEnabled = function(on) { + this.block_mousemove = !on; + if (on === false) { + this.tooltip.hide(); + this.removeZoomMesh(); + } + }; - gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); + control.removeZoomMesh = function() { + if (this.mouse_zoom_mesh?.object.showSelection()) + this.painter.render3D(); + this.mouse_zoom_mesh = null; // in any case clear mesh, enable orbit control again + }; - }` -}; + control.mainProcessMouseMove = function(evnt) { + if (!this.painter) return; // protect when cleanup -// Ported from Stefan Gustavson's java implementation -// http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf -// Read Stefan's excellent paper for details on how this code works. -// -// Sean McCullough banksean@gmail.com -// -// Added 4D noise + if (this.control_active && evnt.buttons && (evnt.buttons & 2)) + this.block_ctxt = true; // if right button in control was active, block next context menu -/** - * You can pass in a random number generator object if you like. - * It is assumed to have a random() method. - */ -class SimplexNoise { - constructor(r = Math) { - this.grad3 = [[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]]; - this.grad4 = [[0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], [-1, 0, 1, 1], [-1, 0, 1, -1], [-1, 0, -1, 1], [-1, 0, -1, -1], [1, 1, 0, 1], [1, 1, 0, -1], [1, -1, 0, 1], [1, -1, 0, -1], [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0]]; - this.p = []; - for (let i = 0; i < 256; i++) { - this.p[i] = Math.floor(r.random() * 256); - } - - // To remove the need for index wrapping, double the permutation table length - this.perm = []; - for (let i = 0; i < 512; i++) { - this.perm[i] = this.p[i & 255]; - } - - // A lookup table to traverse the simplex around a given point in 4D. - // Details can be found where this table is used, in the 4D noise method. - this.simplex = [[0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 0, 3], [0, 0, 0, 0], [1, 3, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 3, 0, 1], [2, 3, 1, 0], [1, 0, 2, 3], [1, 0, 3, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 3, 1], [0, 0, 0, 0], [2, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0]]; - } - dot(g, x, y) { - return g[0] * x + g[1] * y; - } - dot3(g, x, y, z) { - return g[0] * x + g[1] * y + g[2] * z; - } - dot4(g, x, y, z, w) { - return g[0] * x + g[1] * y + g[2] * z + g[3] * w; - } - noise(xin, yin) { - let n0; // Noise contributions from the ../../../src/Three_jsroot.js corners - let n1; - let n2; - // Skew the input space to determine which simplex cell we're in - const F2 = 0.5 * (Math.sqrt(3.0) - 1.0); - const s = (xin + yin) * F2; // Hairy factor for 2D - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const G2 = (3.0 - Math.sqrt(3.0)) / 6.0; - const t = (i + j) * G2; - const X0 = i - t; // Unskew the cell origin back to (x,y) space - const Y0 = j - t; - const x0 = xin - X0; // The x,y distances from the cell origin - const y0 = yin - Y0; - - // For the 2D case, the simplex shape is an equilateral triangle. - // Determine which simplex we are in. - let i1; // Offsets for second (middle) corner of simplex in (i,j) coords - - let j1; - if (x0 > y0) { - i1 = 1; - j1 = 0; - - // lower triangle, XY order: (0,0)->(1,0)->(1,1) - } else { - i1 = 0; - j1 = 1; - } // upper triangle, YX order: (0,0)->(0,1)->(1,1) - - // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and - // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where - // c = (3-sqrt(3))/6 - const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords - const y1 = y0 - j1 + G2; - const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords - const y2 = y0 - 1.0 + 2.0 * G2; - // Work out the hashed gradient indices of the three simplex corners - const ii = i & 255; - const jj = j & 255; - const gi0 = this.perm[ii + this.perm[jj]] % 12; - const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; - const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; - // Calculate the contribution from the three corners - let t0 = 0.5 - x0 * x0 - y0 * y0; - if (t0 < 0) n0 = 0.0;else { - t0 *= t0; - n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient - } - - let t1 = 0.5 - x1 * x1 - y1 * y1; - if (t1 < 0) n1 = 0.0;else { - t1 *= t1; - n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); - } - let t2 = 0.5 - x2 * x2 - y2 * y2; - if (t2 < 0) n2 = 0.0;else { - t2 *= t2; - n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); - } - - // Add contributions from each corner to get the final noise value. - // The result is scaled to return values in the interval [-1,1]. - return 70.0 * (n0 + n1 + n2); - } - - // 3D simplex noise - noise3d(xin, yin, zin) { - let n0; // Noise contributions from the four corners - let n1; - let n2; - let n3; - // Skew the input space to determine which simplex cell we're in - const F3 = 1.0 / 3.0; - const s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D - const i = Math.floor(xin + s); - const j = Math.floor(yin + s); - const k = Math.floor(zin + s); - const G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too - const t = (i + j + k) * G3; - const X0 = i - t; // Unskew the cell origin back to (x,y,z) space - const Y0 = j - t; - const Z0 = k - t; - const x0 = xin - X0; // The x,y,z distances from the cell origin - const y0 = yin - Y0; - const z0 = zin - Z0; - - // For the 3D case, the simplex shape is a slightly irregular tetrahedron. - // Determine which simplex we are in. - let i1; // Offsets for second corner of simplex in (i,j,k) coords - - let j1; - let k1; - let i2; // Offsets for third corner of simplex in (i,j,k) coords - let j2; - let k2; - if (x0 >= y0) { - if (y0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - - // X Y Z order - } else if (x0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - - // X Z Y order - } else { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } // Z X Y order - } else { - // x0 y0 ? 32 : 0; - const c2 = x0 > z0 ? 16 : 0; - const c3 = y0 > z0 ? 8 : 0; - const c4 = x0 > w0 ? 4 : 0; - const c5 = y0 > w0 ? 2 : 0; - const c6 = z0 > w0 ? 1 : 0; - const c = c1 + c2 + c3 + c4 + c5 + c6; - - // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. - // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; - const j1 = simplex[c][1] >= 3 ? 1 : 0; - const k1 = simplex[c][2] >= 3 ? 1 : 0; - const l1 = simplex[c][3] >= 3 ? 1 : 0; - // The number 2 in the "simplex" array is at the second largest coordinate. - const i2 = simplex[c][0] >= 2 ? 1 : 0; - const j2 = simplex[c][1] >= 2 ? 1 : 0; - const k2 = simplex[c][2] >= 2 ? 1 : 0; - const l2 = simplex[c][3] >= 2 ? 1 : 0; - // The number 1 in the "simplex" array is at the second smallest coordinate. - const i3 = simplex[c][0] >= 1 ? 1 : 0; - const j3 = simplex[c][1] >= 1 ? 1 : 0; - const k3 = simplex[c][2] >= 1 ? 1 : 0; - const l3 = simplex[c][3] >= 1 ? 1 : 0; - // The fifth corner has all coordinate offsets = 1, so no need to look that up. - const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords - const y1 = y0 - j1 + G4; - const z1 = z0 - k1 + G4; - const w1 = w0 - l1 + G4; - const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords - const y2 = y0 - j2 + 2.0 * G4; - const z2 = z0 - k2 + 2.0 * G4; - const w2 = w0 - l2 + 2.0 * G4; - const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords - const y3 = y0 - j3 + 3.0 * G4; - const z3 = z0 - k3 + 3.0 * G4; - const w3 = w0 - l3 + 3.0 * G4; - const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords - const y4 = y0 - 1.0 + 4.0 * G4; - const z4 = z0 - 1.0 + 4.0 * G4; - const w4 = w0 - 1.0 + 4.0 * G4; - // Work out the hashed gradient indices of the five simplex corners - const ii = i & 255; - const jj = j & 255; - const kk = k & 255; - const ll = l & 255; - const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; - const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; - const gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; - const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; - const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; - // Calculate the contribution from the five corners - let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if (t0 < 0) n0 = 0.0;else { - t0 *= t0; - n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); - } - let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if (t1 < 0) n1 = 0.0;else { - t1 *= t1; - n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); - } - let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if (t2 < 0) n2 = 0.0;else { - t2 *= t2; - n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); - } - let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if (t3 < 0) n3 = 0.0;else { - t3 *= t3; - n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); - } - let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if (t4 < 0) n4 = 0.0;else { - t4 *= t4; - n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); - } - - // Sum up and scale the result to cover the range [-1,1] - return 27.0 * (n0 + n1 + n2 + n3 + n4); - } -} - -class SSAOPass extends Pass { - constructor(scene, camera, width, height) { - super(); - this.width = width !== undefined ? width : 512; - this.height = height !== undefined ? height : 512; - this.clear = true; - this.camera = camera; - this.scene = scene; - this.kernelRadius = 8; - this.kernelSize = 32; - this.kernel = []; - this.noiseTexture = null; - this.output = 0; - this.minDistance = 0.005; - this.maxDistance = 0.1; - this._visibilityCache = new Map(); + if (this.control_active || this.block_mousemove || !this.processMouseMove) return; - // + if (this.mouse_zoom_mesh) { + // when working with zoom mesh, need special handling - this.generateSampleKernel(); - this.generateRandomKernelRotations(); + const zoom2 = this.detectZoomMesh(evnt), + pnt2 = (zoom2?.object === this.mouse_zoom_mesh.object) ? zoom2.point : this.mouse_zoom_mesh.object.globalIntersect(this.raycaster); - // beauty render target + if (pnt2) this.mouse_zoom_mesh.point2 = pnt2; - const depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; - this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height); + if (pnt2 && this.painter.enable_highlight) { + if (this.mouse_zoom_mesh.object.showSelection(this.mouse_zoom_mesh.point, pnt2)) + this.painter.render3D(0); + } - // normal render target with depth buffer + this.tooltip.hide(); + return; + } - this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { - minFilter: NearestFilter, - magFilter: NearestFilter, - depthTexture: depthTexture - }); + evnt.preventDefault(); - // ssao render target + // extract mouse position + this.tmout_mouse = this.getMousePos(evnt, {}); + this.tmout_ttpos = this.tooltip?.extract_pos(evnt); - this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height); - this.blurRenderTarget = this.ssaoRenderTarget.clone(); + if (this.tmout_handle) { + clearTimeout(this.tmout_handle); + delete this.tmout_handle; + } - // ssao material + if (!this.mouse_tmout) + this.delayedProcessMouseMove(); + else + this.tmout_handle = setTimeout(() => this.delayedProcessMouseMove(), this.mouse_tmout); + }; - if (SSAOShader === undefined) { - console.error('THREE.SSAOPass: The pass relies on SSAOShader.'); - } - this.ssaoMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOShader.defines), - uniforms: UniformsUtils.clone(SSAOShader.uniforms), - vertexShader: SSAOShader.vertexShader, - fragmentShader: SSAOShader.fragmentShader, - blending: NoBlending - }); - this.ssaoMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.ssaoMaterial.uniforms['tNormal'].value = this.normalRenderTarget.texture; - this.ssaoMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.ssaoMaterial.uniforms['tNoise'].value = this.noiseTexture; - this.ssaoMaterial.uniforms['kernel'].value = this.kernel; - this.ssaoMaterial.uniforms['cameraNear'].value = this.camera.near; - this.ssaoMaterial.uniforms['cameraFar'].value = this.camera.far; - this.ssaoMaterial.uniforms['resolution'].value.set(this.width, this.height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - - // normal material - - this.normalMaterial = new MeshNormalMaterial(); - this.normalMaterial.blending = NoBlending; - - // blur material - - this.blurMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAOBlurShader.defines), - uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), - vertexShader: SSAOBlurShader.vertexShader, - fragmentShader: SSAOBlurShader.fragmentShader - }); - this.blurMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.blurMaterial.uniforms['resolution'].value.set(this.width, this.height); - - // material for rendering the depth - - this.depthRenderMaterial = new ShaderMaterial({ - defines: Object.assign({}, SSAODepthShader.defines), - uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), - vertexShader: SSAODepthShader.vertexShader, - fragmentShader: SSAODepthShader.fragmentShader, - blending: NoBlending - }); - this.depthRenderMaterial.uniforms['tDepth'].value = this.normalRenderTarget.depthTexture; - this.depthRenderMaterial.uniforms['cameraNear'].value = this.camera.near; - this.depthRenderMaterial.uniforms['cameraFar'].value = this.camera.far; - - // material for rendering the content of a render target - - this.copyMaterial = new ShaderMaterial({ - uniforms: UniformsUtils.clone(CopyShader.uniforms), - vertexShader: CopyShader.vertexShader, - fragmentShader: CopyShader.fragmentShader, - transparent: true, - depthTest: false, - depthWrite: false, - blendSrc: DstColorFactor, - blendDst: ZeroFactor, - blendEquation: AddEquation, - blendSrcAlpha: DstAlphaFactor, - blendDstAlpha: ZeroFactor, - blendEquationAlpha: AddEquation - }); - this.fsQuad = new FullScreenQuad(null); - this.originalClearColor = new Color$1(); - } - dispose() { - // dispose render targets + control.delayedProcessMouseMove = function() { + // remove handle - allow to trigger new timeout + delete this.tmout_handle; + if (!this.painter) return; // protect when cleanup - this.beautyRenderTarget.dispose(); - this.normalRenderTarget.dispose(); - this.ssaoRenderTarget.dispose(); - this.blurRenderTarget.dispose(); + const mouse = this.tmout_mouse, + intersects = this.getMouseIntersects(mouse), + tip = this.processMouseMove(intersects); - // dispose materials + if (tip) { + let name = '', title = '', coord = '', info = ''; + if (mouse) coord = mouse.x.toFixed(0) + ',' + mouse.y.toFixed(0); + if (isStr(tip)) + info = tip; + else { + name = tip.name; title = tip.title; + if (tip.line) info = tip.line; else + if (tip.lines) { info = tip.lines.slice(1).join(' '); name = tip.lines[0]; } + } + this.painter.showObjectStatus(name, title, info, coord); + } - this.normalMaterial.dispose(); - this.blurMaterial.dispose(); - this.copyMaterial.dispose(); - this.depthRenderMaterial.dispose(); + this.cursor_changed = false; + if (tip && this.painter?.isTooltipAllowed()) { + this.tooltip.checkParent(this.painter.selectDom().node()); - // dipsose full screen quad + this.tooltip.show(tip, mouse); + this.tooltip.pos(this.tmout_ttpos); + } else { + this.tooltip.hide(); + if (intersects) { + for (let n = 0; n < intersects.length; ++n) { + if (intersects[n].object.zoom && !intersects[n].object.zoom_disabled) + this.cursor_changed = true; + } + } + } - this.fsQuad.dispose(); - } - render(renderer, writeBuffer /*, readBuffer, deltaTime, maskActive */) { - if (renderer.capabilities.isWebGL2 === false) this.noiseTexture.format = LuminanceFormat; + getDocument().body.style.cursor = this.cursor_changed ? 'pointer' : 'auto'; + }; - // render beauty + control.mainProcessMouseLeave = function() { + if (!this.painter) return; // protect when cleanup - renderer.setRenderTarget(this.beautyRenderTarget); - renderer.clear(); - renderer.render(this.scene, this.camera); + // do not enter main event at all + if (this.tmout_handle) { + clearTimeout(this.tmout_handle); + delete this.tmout_handle; + } + this.tooltip.hide(); + if (isFunc(this.processMouseLeave)) + this.processMouseLeave(); + if (this.cursor_changed) { + getDocument().body.style.cursor = 'auto'; + this.cursor_changed = false; + } + }; - // render normals and depth (honor only meshes, points and lines do not contribute to SSAO) + control.mainProcessDblClick = function(evnt) { + // suppress simple click handler if double click detected + if (this.single_click_tm) { + clearTimeout(this.single_click_tm); + delete this.single_click_tm; + } + this.processDblClick(evnt); + }; - this.overrideVisibility(); - this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0); - this.restoreVisibility(); + control.processClick = function(mouse_pos, kind) { + delete this.single_click_tm; - // render SSAO + if (kind === 1) { + const fp = this.painter?.getFramePainter(); + if (isFunc(fp?._click_handler)) { + const info = this.getInfoAtMousePosition(mouse_pos); + if (info) { + fp._click_handler(info); + return; + } + } + } - this.ssaoMaterial.uniforms['kernelRadius'].value = this.kernelRadius; - this.ssaoMaterial.uniforms['minDistance'].value = this.minDistance; - this.ssaoMaterial.uniforms['maxDistance'].value = this.maxDistance; - this.renderPass(renderer, this.ssaoMaterial, this.ssaoRenderTarget); + // method assigned in the Eve7 and used for object selection + if ((kind === 2) && isFunc(this.processSingleClick)) { + const intersects = this.getMouseIntersects(mouse_pos); + this.processSingleClick(intersects); + } + }; - // render blur + control.lstn_click = function(evnt) { + // ignore right-mouse click + if (evnt.detail === 2) return; - this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); + if (this.single_click_tm) { + clearTimeout(this.single_click_tm); + delete this.single_click_tm; + } - // output result to screen + let kind = 0; + if (isFunc(this.painter?.getFramePainter()?._click_handler)) + kind = 1; // user click handler + else if (this.processSingleClick && this.painter?.options?.mouse_click) + kind = 2; // eve7 click handler - switch (this.output) { - case SSAOPass.OUTPUT.SSAO: - this.copyMaterial.uniforms['tDiffuse'].value = this.ssaoRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; - case SSAOPass.OUTPUT.Blur: - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; - case SSAOPass.OUTPUT.Beauty: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; - case SSAOPass.OUTPUT.Depth: - this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); - break; - case SSAOPass.OUTPUT.Normal: - this.copyMaterial.uniforms['tDiffuse'].value = this.normalRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; - case SSAOPass.OUTPUT.Default: - this.copyMaterial.uniforms['tDiffuse'].value = this.beautyRenderTarget.texture; - this.copyMaterial.blending = NoBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - this.copyMaterial.uniforms['tDiffuse'].value = this.blurRenderTarget.texture; - this.copyMaterial.blending = CustomBlending; - this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); - break; - default: - console.warn('THREE.SSAOPass: Unknown output type.'); - } - } - renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { - // save original state - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); + // if normal event, set longer timeout waiting if double click not detected + if (kind) + this.single_click_tm = setTimeout(this.processClick.bind(this, this.getMousePos(evnt, {}), kind), 300); + }.bind(control); - // setup pass state - renderer.autoClear = false; - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } - this.fsQuad.material = passMaterial; - this.fsQuad.render(renderer); + control.addEventListener('change', () => control.changeEvent()); + control.addEventListener('start', () => control.startEvent()); + control.addEventListener('end', () => control.endEvent()); - // restore original state - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } - renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { - renderer.getClearColor(this.originalClearColor); - const originalClearAlpha = renderer.getClearAlpha(); - const originalAutoClear = renderer.autoClear; - renderer.setRenderTarget(renderTarget); - renderer.autoClear = false; - clearColor = overrideMaterial.clearColor || clearColor; - clearAlpha = overrideMaterial.clearAlpha || clearAlpha; - if (clearColor !== undefined && clearColor !== null) { - renderer.setClearColor(clearColor); - renderer.setClearAlpha(clearAlpha || 0.0); - renderer.clear(); - } - this.scene.overrideMaterial = overrideMaterial; - renderer.render(this.scene, this.camera); - this.scene.overrideMaterial = null; + control.lstn_contextmenu = evnt => control.mainProcessContextMenu(evnt); + control.lstn_dblclick = evnt => control.mainProcessDblClick(evnt); + control.lstn_mousemove = evnt => control.mainProcessMouseMove(evnt); + control.lstn_mouseleave = () => control.mainProcessMouseLeave(); - // restore original state + renderer.domElement.addEventListener('click', control.lstn_click); + renderer.domElement.addEventListener('dblclick', control.lstn_dblclick); + renderer.domElement.addEventListener('contextmenu', control.lstn_contextmenu); + renderer.domElement.addEventListener('mousemove', control.lstn_mousemove); + renderer.domElement.addEventListener('mouseleave', control.lstn_mouseleave); - renderer.autoClear = originalAutoClear; - renderer.setClearColor(this.originalClearColor); - renderer.setClearAlpha(originalClearAlpha); - } - setSize(width, height) { - this.width = width; - this.height = height; - this.beautyRenderTarget.setSize(width, height); - this.ssaoRenderTarget.setSize(width, height); - this.normalRenderTarget.setSize(width, height); - this.blurRenderTarget.setSize(width, height); - this.ssaoMaterial.uniforms['resolution'].value.set(width, height); - this.ssaoMaterial.uniforms['cameraProjectionMatrix'].value.copy(this.camera.projectionMatrix); - this.ssaoMaterial.uniforms['cameraInverseProjectionMatrix'].value.copy(this.camera.projectionMatrixInverse); - this.blurMaterial.uniforms['resolution'].value.set(width, height); - } - generateSampleKernel() { - const kernelSize = this.kernelSize; - const kernel = this.kernel; - for (let i = 0; i < kernelSize; i++) { - const sample = new Vector3(); - sample.x = Math.random() * 2 - 1; - sample.y = Math.random() * 2 - 1; - sample.z = Math.random(); - sample.normalize(); - let scale = i / kernelSize; - scale = lerp(0.1, 1, scale * scale); - sample.multiplyScalar(scale); - kernel.push(sample); - } - } - generateRandomKernelRotations() { - const width = 4, - height = 4; - if (SimplexNoise === undefined) { - console.error('THREE.SSAOPass: The pass relies on SimplexNoise.'); - } - const simplex = new SimplexNoise(); - const size = width * height; - const data = new Float32Array(size); - for (let i = 0; i < size; i++) { - const x = Math.random() * 2 - 1; - const y = Math.random() * 2 - 1; - const z = 0; - data[i] = simplex.noise3d(x, y, z); - } - this.noiseTexture = new DataTexture(data, width, height, RedFormat, FloatType); - this.noiseTexture.wrapS = RepeatWrapping; - this.noiseTexture.wrapT = RepeatWrapping; - this.noiseTexture.needsUpdate = true; - } - overrideVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - cache.set(object, object.visible); - if (object.isPoints || object.isLine) object.visible = false; - }); - } - restoreVisibility() { - const scene = this.scene; - const cache = this._visibilityCache; - scene.traverse(function (object) { - const visible = cache.get(object); - object.visible = visible; - }); - cache.clear(); - } -} -SSAOPass.OUTPUT = { - 'Default': 0, - 'SSAO': 1, - 'Blur': 2, - 'Beauty': 3, - 'Depth': 4, - 'Normal': 5 -}; + return control; +} -/** - * Luminosity - * http://en.wikipedia.org/wiki/Luminosity - */ +/** @summary Method cleanup three.js object as much as possible. + * @desc Simplify JS engine to remove it from memory + * @private */ +function disposeThreejsObject(obj, only_childs) { + if (!obj) return; -const LuminosityHighPassShader = { - shaderID: 'luminosityHighPass', - uniforms: { - 'tDiffuse': { - value: null - }, - 'luminosityThreshold': { - value: 1.0 - }, - 'smoothWidth': { - value: 1.0 - }, - 'defaultColor': { - value: new Color$1(0x000000) - }, - 'defaultOpacity': { - value: 0.0 - } - }, - vertexShader: /* glsl */` + if (obj.children) { + for (let i = 0; i < obj.children.length; i++) + disposeThreejsObject(obj.children[i]); + } - varying vec2 vUv; + if (only_childs) { + obj.children = []; + return; + } - void main() { + obj.children = undefined; - vUv = uv; + if (obj.geometry) { + obj.geometry.dispose(); + obj.geometry = undefined; + } + if (obj.material) { + if (obj.material.map) { + obj.material.map.dispose(); + obj.material.map = undefined; + } + obj.material.dispose(); + obj.material = undefined; + } - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + // cleanup jsroot fields to simplify browser cleanup job + delete obj.painter; + delete obj.bins_index; + delete obj.tooltip; + delete obj.stack; // used in geom painter + delete obj.drawn_highlight; // special highlight object - }`, - fragmentShader: /* glsl */` + obj = undefined; +} - uniform sampler2D tDiffuse; - uniform vec3 defaultColor; - uniform float defaultOpacity; - uniform float luminosityThreshold; - uniform float smoothWidth; - varying vec2 vUv; +/** @summary Create LineSegments mesh (or only geometry) + * @desc If required, calculates lineDistance attribute for dashed geometries + * @private */ +function createLineSegments(arr, material, index = undefined, only_geometry = false) { + const geom = new BufferGeometry(); - void main() { + geom.setAttribute('position', arr instanceof Float32Array ? new BufferAttribute(arr, 3) : new Float32BufferAttribute(arr, 3)); + if (index) geom.setIndex(new BufferAttribute(index, 1)); - vec4 texel = texture2D( tDiffuse, vUv ); + if (material.isLineDashedMaterial) { + const v1 = new Vector3(), + v2 = new Vector3(); + let d = 0, distances = null; - vec3 luma = vec3( 0.299, 0.587, 0.114 ); + if (index) { + distances = new Float32Array(index.length); + for (let n = 0; n < index.length; n += 2) { + const i1 = index[n], i2 = index[n+1]; + v1.set(arr[i1], arr[i1+1], arr[i1+2]); + v2.set(arr[i2], arr[i2+1], arr[i2+2]); + distances[n] = d; + d += v2.distanceTo(v1); + distances[n+1] = d; + } + } else { + distances = new Float32Array(arr.length/3); + for (let n = 0; n < arr.length; n += 6) { + v1.set(arr[n], arr[n+1], arr[n+2]); + v2.set(arr[n+3], arr[n+4], arr[n+5]); + distances[n/3] = d; + d += v2.distanceTo(v1); + distances[n/3+1] = d; + } + } + geom.setAttribute('lineDistance', new BufferAttribute(distances, 1)); + } - float v = dot( texel.xyz, luma ); + return only_geometry ? geom : new LineSegments(geom, material); +} - vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); +/** @summary Help structures for calculating Box mesh + * @private */ +const Box3D = { + Vertices: [new Vector3(1, 1, 1), new Vector3(1, 1, 0), + new Vector3(1, 0, 1), new Vector3(1, 0, 0), + new Vector3(0, 1, 0), new Vector3(0, 1, 1), + new Vector3(0, 0, 0), new Vector3(0, 0, 1)], + Indexes: [0, 2, 1, 2, 3, 1, 4, 6, 5, 6, 7, 5, 4, 5, 1, 5, 0, 1, + 7, 6, 2, 6, 3, 2, 5, 7, 0, 7, 2, 0, 1, 3, 4, 3, 6, 4], + Normals: [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1], + Segments: [0, 2, 2, 7, 7, 5, 5, 0, 1, 3, 3, 6, 6, 4, 4, 1, 1, 0, 3, 2, 6, 7, 4, 5], // segments addresses Vertices + MeshSegments: undefined +}; - float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); +// these segments address vertices from the mesh, we can use positions from box mesh +Box3D.MeshSegments = (function() { + const arr = new Int32Array(Box3D.Segments.length); - gl_FragColor = mix( outputColor, texel, alpha ); + for (let n = 0; n < arr.length; ++n) { + for (let k = 0; k < Box3D.Indexes.length; ++k) { + if (Box3D.Segments[n] === Box3D.Indexes[k]) { + arr[n] = k; + break; + } + } + } + return arr; +})(); - }` -}; /** - * UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a - * mip map chain of bloom textures and blurs them with different radii. Because - * of the weighted combination of mips, and because larger blurs are done on - * higher mips, this effect provides good quality and performance. + * @summary Abstract interactive control interface for 3D objects * - * Reference: - * - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/ + * @abstract + * @private */ -class UnrealBloomPass extends Pass { - constructor(resolution, strength, radius, threshold) { - super(); - this.strength = strength !== undefined ? strength : 1; - this.radius = radius; - this.threshold = threshold; - this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); - - // create color only once here, reuse it later inside the render function - this.clearColor = new Color$1(0, 0, 0); - - // render targets - this.renderTargetsHorizontal = []; - this.renderTargetsVertical = []; - this.nMips = 5; - let resx = Math.round(this.resolution.x / 2); - let resy = Math.round(this.resolution.y / 2); - this.renderTargetBright = new WebGLRenderTarget(resx, resy); - this.renderTargetBright.texture.name = 'UnrealBloomPass.bright'; - this.renderTargetBright.texture.generateMipmaps = false; - for (let i = 0; i < this.nMips; i++) { - const renderTargetHorizonal = new WebGLRenderTarget(resx, resy); - renderTargetHorizonal.texture.name = 'UnrealBloomPass.h' + i; - renderTargetHorizonal.texture.generateMipmaps = false; - this.renderTargetsHorizontal.push(renderTargetHorizonal); - const renderTargetVertical = new WebGLRenderTarget(resx, resy); - renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i; - renderTargetVertical.texture.generateMipmaps = false; - this.renderTargetsVertical.push(renderTargetVertical); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } - - // luminosity high pass material - if (LuminosityHighPassShader === undefined) console.error('THREE.UnrealBloomPass relies on LuminosityHighPassShader'); - const highPassShader = LuminosityHighPassShader; - this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); - this.highPassUniforms['luminosityThreshold'].value = threshold; - this.highPassUniforms['smoothWidth'].value = 0.01; - this.materialHighPassFilter = new ShaderMaterial({ - uniforms: this.highPassUniforms, - vertexShader: highPassShader.vertexShader, - fragmentShader: highPassShader.fragmentShader, - defines: {} - }); +class InteractiveControl { - // Gaussian Blur Materials - this.separableBlurMaterials = []; - const kernelSizeArray = [3, 5, 7, 9, 11]; - resx = Math.round(this.resolution.x / 2); - resy = Math.round(this.resolution.y / 2); - for (let i = 0; i < this.nMips; i++) { - this.separableBlurMaterials.push(this.getSeperableBlurMaterial(kernelSizeArray[i])); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } - - // Composite material - this.compositeMaterial = this.getCompositeMaterial(this.nMips); - this.compositeMaterial.uniforms['blurTexture1'].value = this.renderTargetsVertical[0].texture; - this.compositeMaterial.uniforms['blurTexture2'].value = this.renderTargetsVertical[1].texture; - this.compositeMaterial.uniforms['blurTexture3'].value = this.renderTargetsVertical[2].texture; - this.compositeMaterial.uniforms['blurTexture4'].value = this.renderTargetsVertical[3].texture; - this.compositeMaterial.uniforms['blurTexture5'].value = this.renderTargetsVertical[4].texture; - this.compositeMaterial.uniforms['bloomStrength'].value = strength; - this.compositeMaterial.uniforms['bloomRadius'].value = 0.1; - this.compositeMaterial.needsUpdate = true; - const bloomFactors = [1.0, 0.8, 0.6, 0.4, 0.2]; - this.compositeMaterial.uniforms['bloomFactors'].value = bloomFactors; - this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; - - // copy material - if (CopyShader === undefined) { - console.error('THREE.UnrealBloomPass relies on CopyShader'); - } - const copyShader = CopyShader; - this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); - this.copyUniforms['opacity'].value = 1.0; - this.materialCopy = new ShaderMaterial({ - uniforms: this.copyUniforms, - vertexShader: copyShader.vertexShader, - fragmentShader: copyShader.fragmentShader, - blending: AdditiveBlending, - depthTest: false, - depthWrite: false, - transparent: true - }); - this.enabled = true; - this.needsSwap = false; - this._oldClearColor = new Color$1(); - this.oldClearAlpha = 1; - this.basic = new MeshBasicMaterial(); - this.fsQuad = new FullScreenQuad(null); - } - dispose() { - for (let i = 0; i < this.renderTargetsHorizontal.length; i++) { - this.renderTargetsHorizontal[i].dispose(); - } - for (let i = 0; i < this.renderTargetsVertical.length; i++) { - this.renderTargetsVertical[i].dispose(); - } - this.renderTargetBright.dispose(); + cleanup() {} + extractIndex(/* intersect */) {} + setSelected(/* col, indx */) {} + setHighlight(/* col, indx */) {} + checkHighlightIndex(/* indx */) {} - // +} // class InteractiveControl - for (let i = 0; i < this.separableBlurMaterials.length; i++) { - this.separableBlurMaterials[i].dispose(); - } - this.compositeMaterial.dispose(); - this.materialCopy.dispose(); - this.basic.dispose(); - // +/** + * @summary Class for creation of 3D points + * + * @private + */ - this.fsQuad.dispose(); - } - setSize(width, height) { - let resx = Math.round(width / 2); - let resy = Math.round(height / 2); - this.renderTargetBright.setSize(resx, resy); - for (let i = 0; i < this.nMips; i++) { - this.renderTargetsHorizontal[i].setSize(resx, resy); - this.renderTargetsVertical[i].setSize(resx, resy); - this.separableBlurMaterials[i].uniforms['texSize'].value = new Vector2(resx, resy); - resx = Math.round(resx / 2); - resy = Math.round(resy / 2); - } - } - render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) { - renderer.getClearColor(this._oldClearColor); - this.oldClearAlpha = renderer.getClearAlpha(); - const oldAutoClear = renderer.autoClear; - renderer.autoClear = false; - renderer.setClearColor(this.clearColor, 0); - if (maskActive) renderer.state.buffers.stencil.setTest(false); +class PointsCreator { - // Render input to screen + /** @summary constructor + * @param {number} size - number of points + * @param {boolean} [iswebgl=true] - if WebGL is used + * @param {number} [scale=1] - scale factor */ + constructor(size, iswebgl, scale) { + this.webgl = (iswebgl === undefined) ? true : iswebgl; + this.scale = scale || 1; - if (this.renderToScreen) { - this.fsQuad.material = this.basic; - this.basic.map = readBuffer.texture; - renderer.setRenderTarget(null); - renderer.clear(); - this.fsQuad.render(renderer); - } + this.pos = new Float32Array(size*3); + this.geom = new BufferGeometry(); + this.geom.setAttribute('position', new BufferAttribute(this.pos, 3)); + this.indx = 0; + } - // 1. Extract Bright Areas + /** @summary Add point */ + addPoint(x, y, z) { + this.pos[this.indx] = x; + this.pos[this.indx+1] = y; + this.pos[this.indx+2] = z; + this.indx += 3; + } - this.highPassUniforms['tDiffuse'].value = readBuffer.texture; - this.highPassUniforms['luminosityThreshold'].value = this.threshold; - this.fsQuad.material = this.materialHighPassFilter; - renderer.setRenderTarget(this.renderTargetBright); - renderer.clear(); - this.fsQuad.render(renderer); + /** @summary Create points */ + createPoints(args) { + if (!isObject(args)) + args = { color: args }; + if (!args.color) + args.color = 'black'; - // 2. Blur All the mips progressively + let k = 1; - let inputRenderTarget = this.renderTargetBright; - for (let i = 0; i < this.nMips; i++) { - this.fsQuad.material = this.separableBlurMaterials[i]; - this.separableBlurMaterials[i].uniforms['colorTexture'].value = inputRenderTarget.texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionX; - renderer.setRenderTarget(this.renderTargetsHorizontal[i]); - renderer.clear(); - this.fsQuad.render(renderer); - this.separableBlurMaterials[i].uniforms['colorTexture'].value = this.renderTargetsHorizontal[i].texture; - this.separableBlurMaterials[i].uniforms['direction'].value = UnrealBloomPass.BlurDirectionY; - renderer.setRenderTarget(this.renderTargetsVertical[i]); - renderer.clear(); - this.fsQuad.render(renderer); - inputRenderTarget = this.renderTargetsVertical[i]; - } + // special dots + if (!args.style) k = 1.1; else + if (args.style === 1) k = 0.3; else + if (args.style === 6) k = 0.5; else + if (args.style === 7) k = 0.7; - // Composite All the mips + const makePoints = texture => { + const material_args = { size: 3*this.scale*k }; + if (texture) { + material_args.map = texture; + material_args.transparent = true; + } else + material_args.color = args.color || 'black'; - this.fsQuad.material = this.compositeMaterial; - this.compositeMaterial.uniforms['bloomStrength'].value = this.strength; - this.compositeMaterial.uniforms['bloomRadius'].value = this.radius; - this.compositeMaterial.uniforms['bloomTintColors'].value = this.bloomTintColors; - renderer.setRenderTarget(this.renderTargetsHorizontal[0]); - renderer.clear(); - this.fsQuad.render(renderer); + const pnts = new Points(this.geom, new PointsMaterial(material_args)); + pnts.nvertex = 1; + return pnts; + }; - // Blend it additively over the input texture + // this is plain creation of points, no need for texture loading - this.fsQuad.material = this.materialCopy; - this.copyUniforms['tDiffuse'].value = this.renderTargetsHorizontal[0].texture; - if (maskActive) renderer.state.buffers.stencil.setTest(true); - if (this.renderToScreen) { - renderer.setRenderTarget(null); - this.fsQuad.render(renderer); - } else { - renderer.setRenderTarget(readBuffer); - this.fsQuad.render(renderer); - } + if (k !== 1) { + const res = makePoints(); + return this.noPromise ? res : Promise.resolve(res); + } - // Restore renderer settings + const handler = new TAttMarkerHandler({ style: args.style, color: args.color, size: 7 }), + w = handler.fill ? 1 : 7, + imgdata = '' + + ``+ + '', + dataUrl = 'data:image/svg+xml;charset=utf8,' + (isNodeJs() ? imgdata : encodeURIComponent(imgdata)); + let promise; - renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); - renderer.autoClear = oldAutoClear; - } - getSeperableBlurMaterial(kernelRadius) { - return new ShaderMaterial({ - defines: { - 'KERNEL_RADIUS': kernelRadius, - 'SIGMA': kernelRadius - }, - uniforms: { - 'colorTexture': { - value: null - }, - 'texSize': { - value: new Vector2(0.5, 0.5) - }, - 'direction': { - value: new Vector2(0.5, 0.5) - } - }, - vertexShader: `varying vec2 vUv; - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`, - fragmentShader: `#include - varying vec2 vUv; - uniform sampler2D colorTexture; - uniform vec2 texSize; - uniform vec2 direction; + if (isNodeJs()) { + promise = Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(handle => handle.default.loadImage(dataUrl).then(img => { + const canvas = handle.default.createCanvas(64, 64), + ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0, 64, 64); + return new CanvasTexture(canvas); + })); + } else if (this.noPromise) { + // only for v6 support + return makePoints(new TextureLoader().load(dataUrl)); + } else { + promise = new Promise((resolveFunc, rejectFunc) => { + const loader = new TextureLoader(); + // eslint-disable-next-line prefer-promise-reject-errors + loader.load(dataUrl, res => resolveFunc(res), undefined, () => rejectFunc()); + }); + } - float gaussianPdf(in float x, in float sigma) { - return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; - } - void main() { - vec2 invSize = 1.0 / texSize; - float fSigma = float(SIGMA); - float weightSum = gaussianPdf(0.0, fSigma); - vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum; - for( int i = 1; i < KERNEL_RADIUS; i ++ ) { - float x = float(i); - float w = gaussianPdf(x, fSigma); - vec2 uvOffset = direction * invSize * x; - vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb; - vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb; - diffuseSum += (sample1 + sample2) * w; - weightSum += 2.0 * w; - } - gl_FragColor = vec4(diffuseSum/weightSum, 1.0); - }` - }); - } - getCompositeMaterial(nMips) { - return new ShaderMaterial({ - defines: { - 'NUM_MIPS': nMips - }, - uniforms: { - 'blurTexture1': { - value: null - }, - 'blurTexture2': { - value: null - }, - 'blurTexture3': { - value: null - }, - 'blurTexture4': { - value: null - }, - 'blurTexture5': { - value: null - }, - 'bloomStrength': { - value: 1.0 - }, - 'bloomFactors': { - value: null - }, - 'bloomTintColors': { - value: null - }, - 'bloomRadius': { - value: 0.0 - } - }, - vertexShader: `varying vec2 vUv; - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`, - fragmentShader: `varying vec2 vUv; - uniform sampler2D blurTexture1; - uniform sampler2D blurTexture2; - uniform sampler2D blurTexture3; - uniform sampler2D blurTexture4; - uniform sampler2D blurTexture5; - uniform float bloomStrength; - uniform float bloomRadius; - uniform float bloomFactors[NUM_MIPS]; - uniform vec3 bloomTintColors[NUM_MIPS]; + return promise.then(makePoints); + } - float lerpBloomFactor(const in float factor) { - float mirrorFactor = 1.2 - factor; - return mix(factor, mirrorFactor, bloomRadius); - } +} // class PointsCreator - void main() { - gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + - lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + - lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + - lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + - lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); - }` - }); - } -} -UnrealBloomPass.BlurDirectionX = new Vector2(1.0, 0.0); -UnrealBloomPass.BlurDirectionY = new Vector2(0.0, 1.0); -class RenderableObject { - constructor() { - this.id = 0; - this.object = null; - this.z = 0; - this.renderOrder = 0; - } -} +/** @summary Create material for 3D line + * @desc Takes into account dashed properties + * @private */ +function create3DLineMaterial(painter, arg, is_v7 = false) { + if (!painter || !arg) return null; -// + let color, lstyle, lwidth; + if (isStr(arg) || is_v7) { + color = painter.v7EvalColor(arg+'color', 'black'); + lstyle = parseInt(painter.v7EvalAttr(arg+'style', 0)); + lwidth = parseInt(painter.v7EvalAttr(arg+'width', 1)); + } else { + color = painter.getColor(arg.fLineColor); + lstyle = arg.fLineStyle; + lwidth = arg.fLineWidth; + } -class RenderableFace { - constructor() { - this.id = 0; - this.v1 = new RenderableVertex(); - this.v2 = new RenderableVertex(); - this.v3 = new RenderableVertex(); - this.normalModel = new Vector3(); - this.vertexNormalsModel = [new Vector3(), new Vector3(), new Vector3()]; - this.vertexNormalsLength = 0; - this.color = new Color$1(); - this.material = null; - this.uvs = [new Vector2(), new Vector2(), new Vector2()]; - this.z = 0; - this.renderOrder = 0; - } -} + const style = lstyle ? getSvgLineStyle(lstyle) : '', + dash = style ? style.split(',') : [], + material = (dash && dash.length >= 2) + ? new LineDashedMaterial({ color, dashSize: parseInt(dash[0]), gapSize: parseInt(dash[1]) }) + : new LineBasicMaterial({ color }); -// + if (lwidth && (lwidth > 1)) material.linewidth = lwidth; -class RenderableVertex { - constructor() { - this.position = new Vector3(); - this.positionWorld = new Vector3(); - this.positionScreen = new Vector4(); - this.visible = true; - } - copy(vertex) { - this.positionWorld.copy(vertex.positionWorld); - this.positionScreen.copy(vertex.positionScreen); - } + return material; } -// - -class RenderableLine { - constructor() { - this.id = 0; - this.v1 = new RenderableVertex(); - this.v2 = new RenderableVertex(); - this.vertexColors = [new Color$1(), new Color$1()]; - this.material = null; - this.z = 0; - this.renderOrder = 0; - } -} +/** + * A math namespace - all functions can be exported from base/math.mjs. + * Also all these functions can be used with TFormula calcualtions + * @namespace Math + */ -// +/* eslint-disable no-loss-of-precision */ +/* eslint-disable space-in-parens */ +/* eslint-disable curly */ +/* eslint-disable operator-linebreak */ +/* eslint-disable no-floating-decimal */ +/* eslint-disable brace-style */ +/* eslint-disable comma-spacing */ -class RenderableSprite { - constructor() { - this.id = 0; - this.object = null; - this.x = 0; - this.y = 0; - this.z = 0; - this.rotation = 0; - this.scale = new Vector2(); - this.material = null; - this.renderOrder = 0; - } -} +// this can be improved later -// +/* eslint-disable no-unreachable-loop */ +/* eslint-disable eqeqeq */ -class Projector { - constructor() { - let _object, - _objectCount, - _objectPoolLength = 0, - _vertex, - _vertexCount, - _vertexPoolLength = 0, - _face, - _faceCount, - _facePoolLength = 0, - _line, - _lineCount, - _linePoolLength = 0, - _sprite, - _spriteCount, - _spritePoolLength = 0, - _modelMatrix; - const _renderData = { - objects: [], - lights: [], - elements: [] - }, - _vector3 = new Vector3(), - _vector4 = new Vector4(), - _clipBox = new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)), - _boundingBox = new Box3(), - _points3 = new Array(3), - _viewMatrix = new Matrix4(), - _viewProjectionMatrix = new Matrix4(), - _modelViewProjectionMatrix = new Matrix4(), - _frustum = new Frustum(), - _objectPool = [], - _vertexPool = [], - _facePool = [], - _linePool = [], - _spritePool = []; +const kMACHEP = 1.11022302462515654042363166809e-16, + kMINLOG = -708.396418532264078748994506896, + kMAXLOG = 709.782712893383973096206318587, + kMAXSTIR = 108.116855767857671821730036754, + kBig = 4.503599627370496e15, + kBiginv = 2.22044604925031308085e-16, + kSqrt2 = 1.41421356237309515, + M_PI = 3.14159265358979323846264338328; - // +/** @summary Polynomialeval function + * @desc calculates a value of a polynomial of the form: + * a[0]x^N+a[1]x^(N-1) + ... + a[N] + * @memberof Math */ +function Polynomialeval(x, a, N) { + if (!N) return a[0]; - function RenderList() { - const normals = []; - const colors = []; - const uvs = []; - let object = null; - const normalMatrix = new Matrix3(); - function setObject(value) { - object = value; - normalMatrix.getNormalMatrix(object.matrixWorld); - normals.length = 0; - colors.length = 0; - uvs.length = 0; - } - function projectVertex(vertex) { - const position = vertex.position; - const positionWorld = vertex.positionWorld; - const positionScreen = vertex.positionScreen; - positionWorld.copy(position).applyMatrix4(_modelMatrix); - positionScreen.copy(positionWorld).applyMatrix4(_viewProjectionMatrix); - const invW = 1 / positionScreen.w; - positionScreen.x *= invW; - positionScreen.y *= invW; - positionScreen.z *= invW; - vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 && positionScreen.y >= -1 && positionScreen.y <= 1 && positionScreen.z >= -1 && positionScreen.z <= 1; - } - function pushVertex(x, y, z) { - _vertex = getNextVertexInPool(); - _vertex.position.set(x, y, z); - projectVertex(_vertex); - } - function pushNormal(x, y, z) { - normals.push(x, y, z); - } - function pushColor(r, g, b) { - colors.push(r, g, b); - } - function pushUv(x, y) { - uvs.push(x, y); - } - function checkTriangleVisibility(v1, v2, v3) { - if (v1.visible === true || v2.visible === true || v3.visible === true) return true; - _points3[0] = v1.positionScreen; - _points3[1] = v2.positionScreen; - _points3[2] = v3.positionScreen; - return _clipBox.intersectsBox(_boundingBox.setFromPoints(_points3)); - } - function checkBackfaceCulling(v1, v2, v3) { - return (v3.positionScreen.x - v1.positionScreen.x) * (v2.positionScreen.y - v1.positionScreen.y) - (v3.positionScreen.y - v1.positionScreen.y) * (v2.positionScreen.x - v1.positionScreen.x) < 0; - } - function pushLine(a, b) { - const v1 = _vertexPool[a]; - const v2 = _vertexPool[b]; + let pom = a[0]; + for (let i = 1; i <= N; ++i) + pom = pom *x + a[i]; + return pom; +} - // Clip +/** @summary Polynomial1eval function + * @desc calculates a value of a polynomial of the form: + * x^N+a[0]x^(N-1) + ... + a[N-1] + * @memberof Math */ +function Polynomial1eval(x, a, N) { + if (!N) return a[0]; - v1.positionScreen.copy(v1.position).applyMatrix4(_modelViewProjectionMatrix); - v2.positionScreen.copy(v2.position).applyMatrix4(_modelViewProjectionMatrix); - if (clipLine(v1.positionScreen, v2.positionScreen) === true) { - // Perform the perspective divide - v1.positionScreen.multiplyScalar(1 / v1.positionScreen.w); - v2.positionScreen.multiplyScalar(1 / v2.positionScreen.w); - _line = getNextLineInPool(); - _line.id = object.id; - _line.v1.copy(v1); - _line.v2.copy(v2); - _line.z = Math.max(v1.positionScreen.z, v2.positionScreen.z); - _line.renderOrder = object.renderOrder; - _line.material = object.material; - if (object.material.vertexColors) { - _line.vertexColors[0].fromArray(colors, a * 3); - _line.vertexColors[1].fromArray(colors, b * 3); - } - _renderData.elements.push(_line); - } - } - function pushTriangle(a, b, c, material) { - const v1 = _vertexPool[a]; - const v2 = _vertexPool[b]; - const v3 = _vertexPool[c]; - if (checkTriangleVisibility(v1, v2, v3) === false) return; - if (material.side === DoubleSide || checkBackfaceCulling(v1, v2, v3) === true) { - _face = getNextFaceInPool(); - _face.id = object.id; - _face.v1.copy(v1); - _face.v2.copy(v2); - _face.v3.copy(v3); - _face.z = (v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z) / 3; - _face.renderOrder = object.renderOrder; + let pom = x + a[0]; + for (let i = 1; i < N; ++i) + pom = pom *x + a[i]; + return pom; +} - // face normal - _vector3.subVectors(v3.position, v2.position); - _vector4.subVectors(v1.position, v2.position); - _vector3.cross(_vector4); - _face.normalModel.copy(_vector3); - _face.normalModel.applyMatrix3(normalMatrix).normalize(); - for (let i = 0; i < 3; i++) { - const normal = _face.vertexNormalsModel[i]; - normal.fromArray(normals, arguments[i] * 3); - normal.applyMatrix3(normalMatrix).normalize(); - const uv = _face.uvs[i]; - uv.fromArray(uvs, arguments[i] * 2); - } - _face.vertexNormalsLength = 3; - _face.material = material; - if (material.vertexColors) { - _face.color.fromArray(colors, a * 3); - } - _renderData.elements.push(_face); - } - } - return { - setObject: setObject, - projectVertex: projectVertex, - checkTriangleVisibility: checkTriangleVisibility, - checkBackfaceCulling: checkBackfaceCulling, - pushVertex: pushVertex, - pushNormal: pushNormal, - pushColor: pushColor, - pushUv: pushUv, - pushLine: pushLine, - pushTriangle: pushTriangle - }; - } - const renderList = new RenderList(); - function projectObject(object) { - if (object.visible === false) return; - if (object.isLight) { - _renderData.lights.push(object); - } else if (object.isMesh || object.isLine || object.isPoints) { - if (object.material.visible === false) return; - if (object.frustumCulled === true && _frustum.intersectsObject(object) === false) return; - addObject(object); - } else if (object.isSprite) { - if (object.material.visible === false) return; - if (object.frustumCulled === true && _frustum.intersectsSprite(object) === false) return; - addObject(object); - } - const children = object.children; - for (let i = 0, l = children.length; i < l; i++) { - projectObject(children[i]); - } - } - function addObject(object) { - _object = getNextObjectInPool(); - _object.id = object.id; - _object.object = object; - _vector3.setFromMatrixPosition(object.matrixWorld); - _vector3.applyMatrix4(_viewProjectionMatrix); - _object.z = _vector3.z; - _object.renderOrder = object.renderOrder; - _renderData.objects.push(_object); - } - this.projectScene = function (scene, camera, sortObjects, sortElements) { - _faceCount = 0; - _lineCount = 0; - _spriteCount = 0; - _renderData.elements.length = 0; - if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); - if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); - _viewMatrix.copy(camera.matrixWorldInverse); - _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix); - _frustum.setFromProjectionMatrix(_viewProjectionMatrix); +/** @summary lgam function, logarithm from gamma + * @memberof Math */ +function lgam(x) { + let p, q, u, w, z; + const kMAXLGM = 2.556348e305, + LS2PI = 0.91893853320467274178, + A = [ + 8.11614167470508450300E-4, + -5.95061904284301438324E-4, + 7.93650340457716943945E-4, + -2.77777777730099687205E-3, + 8.33333333333331927722E-2 + ], B = [ + -1.37825152569120859100E3, + -3.88016315134637840924E4, + -3.31612992738871184744E5, + -1.16237097492762307383E6, + -1.72173700820839662146E6, + -8.53555664245765465627E5 + ], C = [ + /* 1.00000000000000000000E0, */ + -3.51815701436523470549E2, + -1.70642106651881159223E4, + -2.20528590553854454839E5, + -1.13933444367982507207E6, + -2.53252307177582951285E6, + -2.01889141433532773231E6 + ]; - // + if ((x >= Number.MAX_VALUE) || (x == Number.POSITIVE_INFINITY)) + return Number.POSITIVE_INFINITY; - _objectCount = 0; - _renderData.objects.length = 0; - _renderData.lights.length = 0; - projectObject(scene); - if (sortObjects === true) { - _renderData.objects.sort(painterSort); - } + if ( x < -34.0 ) { + q = -x; + w = lgam(q); + p = Math.floor(q); + if ( p === q ) // _unur_FP_same(p,q) + return Number.POSITIVE_INFINITY; + z = q - p; + if ( z > 0.5 ) { + p += 1.0; + z = p - q; + } + z = q * Math.sin( Math.PI * z ); + if ( z < 1e-300 ) + return Number.POSITIVE_INFINITY; + z = Math.log(Math.PI) - Math.log( z ) - w; + return z; + } + if ( x < 13.0 ) { + z = 1.0; + p = 0.0; + u = x; + while ( u >= 3.0 ) { + p -= 1.0; + u = x + p; + z *= u; + } + while ( u < 2.0 ) { + if ( u < 1e-300 ) + return Number.POSITIVE_INFINITY; + z /= u; + p += 1.0; + u = x + p; + } + if ( z < 0.0 ) { + z = -z; + } + if ( u === 2.0 ) + return Math.log(z); + p -= 2.0; + x = x + p; + p = x * Polynomialeval(x, B, 5 ) / Polynomial1eval( x, C, 6); + return Math.log(z) + p; + } + if ( x > kMAXLGM ) + return Number.POSITIVE_INFINITY; - // + q = ( x - 0.5 ) * Math.log(x) - x + LS2PI; + if ( x > 1.0e8 ) + return q; - const objects = _renderData.objects; - for (let o = 0, ol = objects.length; o < ol; o++) { - const object = objects[o].object; - const geometry = object.geometry; - renderList.setObject(object); - _modelMatrix = object.matrixWorld; - _vertexCount = 0; - if (object.isMesh) { - let material = object.material; - const isMultiMaterial = Array.isArray(material); - const attributes = geometry.attributes; - const groups = geometry.groups; - if (attributes.position === undefined) continue; - const positions = attributes.position.array; - for (let i = 0, l = positions.length; i < l; i += 3) { - let x = positions[i]; - let y = positions[i + 1]; - let z = positions[i + 2]; - const morphTargets = geometry.morphAttributes.position; - if (morphTargets !== undefined) { - const morphTargetsRelative = geometry.morphTargetsRelative; - const morphInfluences = object.morphTargetInfluences; - for (let t = 0, tl = morphTargets.length; t < tl; t++) { - const influence = morphInfluences[t]; - if (influence === 0) continue; - const target = morphTargets[t]; - if (morphTargetsRelative) { - x += target.getX(i / 3) * influence; - y += target.getY(i / 3) * influence; - z += target.getZ(i / 3) * influence; - } else { - x += (target.getX(i / 3) - positions[i]) * influence; - y += (target.getY(i / 3) - positions[i + 1]) * influence; - z += (target.getZ(i / 3) - positions[i + 2]) * influence; - } - } - } - renderList.pushVertex(x, y, z); - } - if (attributes.normal !== undefined) { - const normals = attributes.normal.array; - for (let i = 0, l = normals.length; i < l; i += 3) { - renderList.pushNormal(normals[i], normals[i + 1], normals[i + 2]); - } - } - if (attributes.color !== undefined) { - const colors = attributes.color.array; - for (let i = 0, l = colors.length; i < l; i += 3) { - renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]); - } - } - if (attributes.uv !== undefined) { - const uvs = attributes.uv.array; - for (let i = 0, l = uvs.length; i < l; i += 2) { - renderList.pushUv(uvs[i], uvs[i + 1]); - } - } - if (geometry.index !== null) { - const indices = geometry.index.array; - if (groups.length > 0) { - for (let g = 0; g < groups.length; g++) { - const group = groups[g]; - material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material; - if (material === undefined) continue; - for (let i = group.start, l = group.start + group.count; i < l; i += 3) { - renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material); - } - } - } else { - for (let i = 0, l = indices.length; i < l; i += 3) { - renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material); - } - } - } else { - if (groups.length > 0) { - for (let g = 0; g < groups.length; g++) { - const group = groups[g]; - material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material; - if (material === undefined) continue; - for (let i = group.start, l = group.start + group.count; i < l; i += 3) { - renderList.pushTriangle(i, i + 1, i + 2, material); - } - } - } else { - for (let i = 0, l = positions.length / 3; i < l; i += 3) { - renderList.pushTriangle(i, i + 1, i + 2, material); - } - } - } - } else if (object.isLine) { - _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix, _modelMatrix); - const attributes = geometry.attributes; - if (attributes.position !== undefined) { - const positions = attributes.position.array; - for (let i = 0, l = positions.length; i < l; i += 3) { - renderList.pushVertex(positions[i], positions[i + 1], positions[i + 2]); - } - if (attributes.color !== undefined) { - const colors = attributes.color.array; - for (let i = 0, l = colors.length; i < l; i += 3) { - renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]); - } - } - if (geometry.index !== null) { - const indices = geometry.index.array; - for (let i = 0, l = indices.length; i < l; i += 2) { - renderList.pushLine(indices[i], indices[i + 1]); - } - } else { - const step = object.isLineSegments ? 2 : 1; - for (let i = 0, l = positions.length / 3 - 1; i < l; i += step) { - renderList.pushLine(i, i + 1); - } - } - } - } else if (object.isPoints) { - _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix, _modelMatrix); - const attributes = geometry.attributes; - if (attributes.position !== undefined) { - const positions = attributes.position.array; - for (let i = 0, l = positions.length; i < l; i += 3) { - _vector4.set(positions[i], positions[i + 1], positions[i + 2], 1); - _vector4.applyMatrix4(_modelViewProjectionMatrix); - pushPoint(_vector4, object, camera); - } - } - } else if (object.isSprite) { - object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); - _vector4.set(_modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1); - _vector4.applyMatrix4(_viewProjectionMatrix); - pushPoint(_vector4, object, camera); - } - } - if (sortElements === true) { - _renderData.elements.sort(painterSort); - } - return _renderData; - }; - function pushPoint(_vector4, object, camera) { - const invW = 1 / _vector4.w; - _vector4.z *= invW; - if (_vector4.z >= -1 && _vector4.z <= 1) { - _sprite = getNextSpriteInPool(); - _sprite.id = object.id; - _sprite.x = _vector4.x * invW; - _sprite.y = _vector4.y * invW; - _sprite.z = _vector4.z; - _sprite.renderOrder = object.renderOrder; - _sprite.object = object; - _sprite.rotation = object.rotation; - _sprite.scale.x = object.scale.x * Math.abs(_sprite.x - (_vector4.x + camera.projectionMatrix.elements[0]) / (_vector4.w + camera.projectionMatrix.elements[12])); - _sprite.scale.y = object.scale.y * Math.abs(_sprite.y - (_vector4.y + camera.projectionMatrix.elements[5]) / (_vector4.w + camera.projectionMatrix.elements[13])); - _sprite.material = object.material; - _renderData.elements.push(_sprite); - } - } + p = 1.0/(x*x); + if ( x >= 1000.0 ) + q += ((7.9365079365079365079365e-4 * p + - 2.7777777777777777777778e-3) *p + + 0.0833333333333333333333) / x; + else + q += Polynomialeval( p, A, 4 ) / x; + return q; +} - // Pools +/** @summary Stirling formula for the gamma function + * @memberof Math */ +function stirf(x) { + let y, w, v; - function getNextObjectInPool() { - if (_objectCount === _objectPoolLength) { - const object = new RenderableObject(); - _objectPool.push(object); - _objectPoolLength++; - _objectCount++; - return object; - } - return _objectPool[_objectCount++]; - } - function getNextVertexInPool() { - if (_vertexCount === _vertexPoolLength) { - const vertex = new RenderableVertex(); - _vertexPool.push(vertex); - _vertexPoolLength++; - _vertexCount++; - return vertex; - } - return _vertexPool[_vertexCount++]; - } - function getNextFaceInPool() { - if (_faceCount === _facePoolLength) { - const face = new RenderableFace(); - _facePool.push(face); - _facePoolLength++; - _faceCount++; - return face; - } - return _facePool[_faceCount++]; - } - function getNextLineInPool() { - if (_lineCount === _linePoolLength) { - const line = new RenderableLine(); - _linePool.push(line); - _linePoolLength++; - _lineCount++; - return line; - } - return _linePool[_lineCount++]; - } - function getNextSpriteInPool() { - if (_spriteCount === _spritePoolLength) { - const sprite = new RenderableSprite(); - _spritePool.push(sprite); - _spritePoolLength++; - _spriteCount++; - return sprite; - } - return _spritePool[_spriteCount++]; - } + const STIR = [ + 7.87311395793093628397E-4, + -2.29549961613378126380E-4, + -2.68132617805781232825E-3, + 3.47222221605458667310E-3, + 8.33333333333482257126E-2 + ], SQTPI = Math.sqrt(2*Math.PI); - // + w = 1.0/x; + w = 1.0 + w * Polynomialeval( w, STIR, 4 ); + y = Math.exp(x); - function painterSort(a, b) { - if (a.renderOrder !== b.renderOrder) { - return a.renderOrder - b.renderOrder; - } else if (a.z !== b.z) { - return b.z - a.z; - } else if (a.id !== b.id) { - return a.id - b.id; - } else { - return 0; - } - } - function clipLine(s1, s2) { - let alpha1 = 0, - alpha2 = 1; +/* #define kMAXSTIR kMAXLOG/log(kMAXLOG) */ - // Calculate the boundary coordinate of each vertex for the near and far clip planes, - // Z = -1 and Z = +1, respectively. + if ( x > kMAXSTIR ) + { /* Avoid overflow in pow() */ + v = Math.pow( x, 0.5 * x - 0.25 ); + y = v * (v / y); + } + else + { + y = Math.pow( x, x - 0.5 ) / y; + } + y = SQTPI * y * w; + return y; +} - const bc1near = s1.z + s1.w, - bc2near = s2.z + s2.w, - bc1far = -s1.z + s1.w, - bc2far = -s2.z + s2.w; - if (bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0) { - // Both vertices lie entirely within all clip planes. - return true; - } else if (bc1near < 0 && bc2near < 0 || bc1far < 0 && bc2far < 0) { - // Both vertices lie entirely outside one of the clip planes. - return false; - } else { - // The line segment spans at least one clip plane. +/** @summary complementary error function + * @memberof Math */ +function erfc(a) { + const erfP = [ + 2.46196981473530512524E-10, + 5.64189564831068821977E-1, + 7.46321056442269912687E0, + 4.86371970985681366614E1, + 1.96520832956077098242E2, + 5.26445194995477358631E2, + 9.34528527171957607540E2, + 1.02755188689515710272E3, + 5.57535335369399327526E2 + ], erfQ = [ + 1.32281951154744992508E1, + 8.67072140885989742329E1, + 3.54937778887819891062E2, + 9.75708501743205489753E2, + 1.82390916687909736289E3, + 2.24633760818710981792E3, + 1.65666309194161350182E3, + 5.57535340817727675546E2 + ], erfR = [ + 5.64189583547755073984E-1, + 1.27536670759978104416E0, + 5.01905042251180477414E0, + 6.16021097993053585195E0, + 7.40974269950448939160E0, + 2.97886665372100240670E0 + ], erfS = [ + 2.26052863220117276590E0, + 9.39603524938001434673E0, + 1.20489539808096656605E1, + 1.70814450747565897222E1, + 9.60896809063285878198E0, + 3.36907645100081516050E0 + ]; - if (bc1near < 0) { - // v1 lies outside the near plane, v2 inside - alpha1 = Math.max(alpha1, bc1near / (bc1near - bc2near)); - } else if (bc2near < 0) { - // v2 lies outside the near plane, v1 inside - alpha2 = Math.min(alpha2, bc1near / (bc1near - bc2near)); - } - if (bc1far < 0) { - // v1 lies outside the far plane, v2 inside - alpha1 = Math.max(alpha1, bc1far / (bc1far - bc2far)); - } else if (bc2far < 0) { - // v2 lies outside the far plane, v2 inside - alpha2 = Math.min(alpha2, bc1far / (bc1far - bc2far)); - } - if (alpha2 < alpha1) { - // The line segment spans two boundaries, but is outside both of them. - // (This can't happen when we're only clipping against just near/far but good - // to leave the check here for future usage if other clip planes are added.) - return false; - } else { - // Update the s1 and s2 vertices to match the clipped line segment. - s1.lerp(s2, alpha1); - s2.lerp(s1, 1 - alpha2); - return true; - } - } - } - } -} + let p,q,x,y,z; -class SVGRenderer { - constructor() { - let _renderData, - _elements, - _lights, - _svgWidth, - _svgHeight, - _svgWidthHalf, - _svgHeightHalf, - _v1, - _v2, - _v3, - _svgNode, - _pathCount = 0, - _precision = null, - _quality = 1, - _currentPath, - _currentStyle; - const _this = this, - _clipBox = new Box2(), - _elemBox = new Box2(), - _color = new Color$1(), - _diffuseColor = new Color$1(), - _ambientLight = new Color$1(), - _directionalLights = new Color$1(), - _pointLights = new Color$1(), - _clearColor = new Color$1(), - _vector3 = new Vector3(), - // Needed for PointLight - _centroid = new Vector3(), - _normal = new Vector3(), - _normalViewMatrix = new Matrix3(), - _viewMatrix = new Matrix4(), - _viewProjectionMatrix = new Matrix4(), - _svgPathPool = [], - _projector = new Projector(), - _svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - this.domElement = _svg; - this.autoClear = true; - this.sortObjects = true; - this.sortElements = true; - this.overdraw = 0.5; - this.info = { - render: { - vertices: 0, - faces: 0 - } - }; - this.setQuality = function (quality) { - switch (quality) { - case 'high': - _quality = 1; - break; - case 'low': - _quality = 0; - break; - } - }; - this.setClearColor = function (color) { - _clearColor.set(color); - }; - this.setPixelRatio = function () {}; - this.setSize = function (width, height) { - _svgWidth = width; - _svgHeight = height; - _svgWidthHalf = _svgWidth / 2; - _svgHeightHalf = _svgHeight / 2; - _svg.setAttribute('viewBox', -_svgWidthHalf + ' ' + -_svgHeightHalf + ' ' + _svgWidth + ' ' + _svgHeight); - _svg.setAttribute('width', _svgWidth); - _svg.setAttribute('height', _svgHeight); - _clipBox.min.set(-_svgWidthHalf, -_svgHeightHalf); - _clipBox.max.set(_svgWidthHalf, _svgHeightHalf); - }; - this.getSize = function () { - return { - width: _svgWidth, - height: _svgHeight - }; - }; - this.setPrecision = function (precision) { - _precision = precision; - }; - function removeChildNodes() { - _pathCount = 0; - while (_svg.childNodes.length > 0) { - _svg.removeChild(_svg.childNodes[0]); - } - } - function convert(c) { - return _precision !== null ? c.toFixed(_precision) : c; - } - this.clear = function () { - removeChildNodes(); - _svg.style.backgroundColor = _clearColor.getStyle(); - }; - this.render = function (scene, camera) { - if (camera instanceof Camera === false) { - console.error('THREE.SVGRenderer.render: camera is not an instance of Camera.'); - return; - } - const background = scene.background; - if (background && background.isColor) { - removeChildNodes(); - _svg.style.backgroundColor = background.getStyle(); - } else if (this.autoClear === true) { - this.clear(); - } - _this.info.render.vertices = 0; - _this.info.render.faces = 0; - _viewMatrix.copy(camera.matrixWorldInverse); - _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix); - _renderData = _projector.projectScene(scene, camera, this.sortObjects, this.sortElements); - _elements = _renderData.elements; - _lights = _renderData.lights; - _normalViewMatrix.getNormalMatrix(camera.matrixWorldInverse); - calculateLights(_lights); + if ( a < 0.0 ) + x = -a; + else + x = a; - // reset accumulated path + if ( x < 1.0 ) + return 1.0 - erf(a); - _currentPath = ''; - _currentStyle = ''; - for (let e = 0, el = _elements.length; e < el; e++) { - const element = _elements[e]; - const material = element.material; - if (material === undefined || material.opacity === 0) continue; - _elemBox.makeEmpty(); - if (element instanceof RenderableSprite) { - _v1 = element; - _v1.x *= _svgWidthHalf; - _v1.y *= -_svgHeightHalf; - renderSprite(_v1, element, material); - } else if (element instanceof RenderableLine) { - _v1 = element.v1; - _v2 = element.v2; - _v1.positionScreen.x *= _svgWidthHalf; - _v1.positionScreen.y *= -_svgHeightHalf; - _v2.positionScreen.x *= _svgWidthHalf; - _v2.positionScreen.y *= -_svgHeightHalf; - _elemBox.setFromPoints([_v1.positionScreen, _v2.positionScreen]); - if (_clipBox.intersectsBox(_elemBox) === true) { - renderLine(_v1, _v2, material); - } - } else if (element instanceof RenderableFace) { - _v1 = element.v1; - _v2 = element.v2; - _v3 = element.v3; - if (_v1.positionScreen.z < -1 || _v1.positionScreen.z > 1) continue; - if (_v2.positionScreen.z < -1 || _v2.positionScreen.z > 1) continue; - if (_v3.positionScreen.z < -1 || _v3.positionScreen.z > 1) continue; - _v1.positionScreen.x *= _svgWidthHalf; - _v1.positionScreen.y *= -_svgHeightHalf; - _v2.positionScreen.x *= _svgWidthHalf; - _v2.positionScreen.y *= -_svgHeightHalf; - _v3.positionScreen.x *= _svgWidthHalf; - _v3.positionScreen.y *= -_svgHeightHalf; - if (this.overdraw > 0) { - expand(_v1.positionScreen, _v2.positionScreen, this.overdraw); - expand(_v2.positionScreen, _v3.positionScreen, this.overdraw); - expand(_v3.positionScreen, _v1.positionScreen, this.overdraw); - } - _elemBox.setFromPoints([_v1.positionScreen, _v2.positionScreen, _v3.positionScreen]); - if (_clipBox.intersectsBox(_elemBox) === true) { - renderFace3(_v1, _v2, _v3, element, material); - } - } - } - flushPath(); // just to flush last svg:path + z = -a * a; - scene.traverseVisible(function (object) { - if (object.isSVGObject) { - _vector3.setFromMatrixPosition(object.matrixWorld); - _vector3.applyMatrix4(_viewProjectionMatrix); - if (_vector3.z < -1 || _vector3.z > 1) return; - const x = _vector3.x * _svgWidthHalf; - const y = -_vector3.y * _svgHeightHalf; - const node = object.node; - node.setAttribute('transform', 'translate(' + x + ',' + y + ')'); - _svg.appendChild(node); - } - }); - }; - function calculateLights(lights) { - _ambientLight.setRGB(0, 0, 0); - _directionalLights.setRGB(0, 0, 0); - _pointLights.setRGB(0, 0, 0); - for (let l = 0, ll = lights.length; l < ll; l++) { - const light = lights[l]; - const lightColor = light.color; - if (light.isAmbientLight) { - _ambientLight.r += lightColor.r; - _ambientLight.g += lightColor.g; - _ambientLight.b += lightColor.b; - } else if (light.isDirectionalLight) { - _directionalLights.r += lightColor.r; - _directionalLights.g += lightColor.g; - _directionalLights.b += lightColor.b; - } else if (light.isPointLight) { - _pointLights.r += lightColor.r; - _pointLights.g += lightColor.g; - _pointLights.b += lightColor.b; - } - } - } - function calculateLight(lights, position, normal, color) { - for (let l = 0, ll = lights.length; l < ll; l++) { - const light = lights[l]; - const lightColor = light.color; - if (light.isDirectionalLight) { - const lightPosition = _vector3.setFromMatrixPosition(light.matrixWorld).normalize(); - let amount = normal.dot(lightPosition); - if (amount <= 0) continue; - amount *= light.intensity; - color.r += lightColor.r * amount; - color.g += lightColor.g * amount; - color.b += lightColor.b * amount; - } else if (light.isPointLight) { - const lightPosition = _vector3.setFromMatrixPosition(light.matrixWorld); - let amount = normal.dot(_vector3.subVectors(lightPosition, position).normalize()); - if (amount <= 0) continue; - amount *= light.distance == 0 ? 1 : 1 - Math.min(position.distanceTo(lightPosition) / light.distance, 1); - if (amount == 0) continue; - amount *= light.intensity; - color.r += lightColor.r * amount; - color.g += lightColor.g * amount; - color.b += lightColor.b * amount; - } - } - } - function renderSprite(v1, element, material) { - let scaleX = element.scale.x * _svgWidthHalf; - let scaleY = element.scale.y * _svgHeightHalf; - if (material.isPointsMaterial) { - scaleX *= material.size; - scaleY *= material.size; - } - const path = 'M' + convert(v1.x - scaleX * 0.5) + ',' + convert(v1.y - scaleY * 0.5) + 'h' + convert(scaleX) + 'v' + convert(scaleY) + 'h' + convert(-scaleX) + 'z'; - let style = ''; - if (material.isSpriteMaterial || material.isPointsMaterial) { - style = 'fill:' + material.color.getStyle() + ';fill-opacity:' + material.opacity; - } - addPath(style, path); - } - function renderLine(v1, v2, material) { - const path = 'M' + convert(v1.positionScreen.x) + ',' + convert(v1.positionScreen.y) + 'L' + convert(v2.positionScreen.x) + ',' + convert(v2.positionScreen.y); - if (material.isLineBasicMaterial) { - let style = 'fill:none;stroke:' + material.color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap; - if (material.isLineDashedMaterial) { - style = style + ';stroke-dasharray:' + material.dashSize + ',' + material.gapSize; - } - addPath(style, path); - } - } - function renderFace3(v1, v2, v3, element, material) { - _this.info.render.vertices += 3; - _this.info.render.faces++; - const path = 'M' + convert(v1.positionScreen.x) + ',' + convert(v1.positionScreen.y) + 'L' + convert(v2.positionScreen.x) + ',' + convert(v2.positionScreen.y) + 'L' + convert(v3.positionScreen.x) + ',' + convert(v3.positionScreen.y) + 'z'; - let style = ''; - if (material.isMeshBasicMaterial) { - _color.copy(material.color); - if (material.vertexColors) { - _color.multiply(element.color); - } - } else if (material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial) { - _diffuseColor.copy(material.color); - if (material.vertexColors) { - _diffuseColor.multiply(element.color); - } - _color.copy(_ambientLight); - _centroid.copy(v1.positionWorld).add(v2.positionWorld).add(v3.positionWorld).divideScalar(3); - calculateLight(_lights, _centroid, element.normalModel, _color); - _color.multiply(_diffuseColor).add(material.emissive); - } else if (material.isMeshNormalMaterial) { - _normal.copy(element.normalModel).applyMatrix3(_normalViewMatrix).normalize(); - _color.setRGB(_normal.x, _normal.y, _normal.z).multiplyScalar(0.5).addScalar(0.5); - } - if (material.wireframe) { - style = 'fill:none;stroke:' + _color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin; - } else { - style = 'fill:' + _color.getStyle() + ';fill-opacity:' + material.opacity; - } - addPath(style, path); - } + if (z < -kMAXLOG) + return (a < 0) ? 2.0 : 0.0; - // Hide anti-alias gaps + z = Math.exp(z); - function expand(v1, v2, pixels) { - let x = v2.x - v1.x, - y = v2.y - v1.y; - const det = x * x + y * y; - if (det === 0) return; - const idet = pixels / Math.sqrt(det); - x *= idet; - y *= idet; - v2.x += x; - v2.y += y; - v1.x -= x; - v1.y -= y; - } - function addPath(style, path) { - if (_currentStyle === style) { - _currentPath += path; - } else { - flushPath(); - _currentStyle = style; - _currentPath = path; - } - } - function flushPath() { - if (_currentPath) { - _svgNode = getPathNode(_pathCount++); - _svgNode.setAttribute('d', _currentPath); - _svgNode.setAttribute('style', _currentStyle); - _svg.appendChild(_svgNode); - } - _currentPath = ''; - _currentStyle = ''; - } - function getPathNode(id) { - if (_svgPathPool[id] == null) { - _svgPathPool[id] = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - if (_quality == 0) { - _svgPathPool[id].setAttribute('shape-rendering', 'crispEdges'); //optimizeSpeed - } + if ( x < 8.0 ) { + p = Polynomialeval( x, erfP, 8 ); + q = Polynomial1eval( x, erfQ, 8 ); + } else { + p = Polynomialeval( x, erfR, 5 ); + q = Polynomial1eval( x, erfS, 6 ); + } + y = (z * p)/q; - return _svgPathPool[id]; - } - return _svgPathPool[id]; - } - } + if (a < 0) + y = 2.0 - y; + + if (y == 0) + return (a < 0) ? 2.0 : 0.0; + + return y; } -let HelveticerRegularJson = json1; +/** @summary error function + * @memberof Math */ +function erf(x) { + if (Math.abs(x) > 1.0) + return 1.0 - erfc(x); -// end of jsroot part + const erfT = [ + 9.60497373987051638749E0, + 9.00260197203842689217E1, + 2.23200534594684319226E3, + 7.00332514112805075473E3, + 5.55923013010394962768E4 + ], erfU = [ + 3.35617141647503099647E1, + 5.21357949780152679795E2, + 4.59432382970980127987E3, + 2.26290000613890934246E4, + 4.92673942608635921086E4 + ], -if (typeof __THREE_DEVTOOLS__ !== 'undefined') { - /* eslint-disable no-undef */ - __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', { - detail: { - revision: REVISION - } - })); - /* eslint-enable no-undef */ + z = x * x; + + return x * Polynomialeval(z, erfT, 4) / Polynomial1eval(z, erfU, 5); } -if (typeof window !== 'undefined') { - if (window.__THREE__) { - console.warn('WARNING: Multiple instances of Three.js being imported.'); - } else { - window.__THREE__ = REVISION; - } +/** @summary lognormal_cdf_c function + * @memberof Math */ +function lognormal_cdf_c(x, m, s, x0) { + if (x0 === undefined) x0 = 0; + const z = (Math.log((x-x0))-m)/(s*kSqrt2); + if (z > 1.) return 0.5*erfc(z); + else return 0.5*(1.0 - erf(z)); } -const HelveticerRegularFont = new Font(HelveticerRegularJson); +/** @summary lognormal_cdf_c function + * @memberof Math */ +function lognormal_cdf(x, m, s, x0 = 0) { + const z = (Math.log((x-x0))-m)/(s*kSqrt2); + if (z < -1.) return 0.5*erfc(-z); + else return 0.5*(1.0 + erf(z)); +} -function createSVGRenderer(as_is, precision, doc) { - if (as_is) { - if (doc !== undefined) - globalThis.docuemnt = doc; - let rndr = new SVGRenderer(); - rndr.setPrecision(precision); - return rndr; - } +/** @summary normal_cdf_c function + * @memberof Math */ +function normal_cdf_c(x, sigma, x0 = 0) { + const z = (x-x0)/(sigma*kSqrt2); + if (z > 1.) return 0.5*erfc(z); + else return 0.5*(1.-erf(z)); +} - const excl_style1 = ';stroke-opacity:1;stroke-width:1;stroke-linecap:round', - excl_style2 = ';fill-opacity:1'; +/** @summary normal_cdf function + * @memberof Math */ +function normal_cdf(x, sigma, x0 = 0) { + const z = (x-x0)/(sigma*kSqrt2); + if (z < -1.) return 0.5*erfc(-z); + else return 0.5*(1.0 + erf(z)); +} - let doc_wrapper = { - svg_attr: {}, - svg_style: {}, - path_attr: {}, - accPath: '', - createElementNS(ns,kind) { - if (kind == 'path') - return { - _wrapper: this, - setAttribute(name, value) { - // cut useless fill-opacity:1 at the end of many SVG attributes - if ((name == 'style') && value) { - let pos1 = value.indexOf(excl_style1); - if ((pos1 >= 0) && (pos1 == value.length - excl_style1.length)) - value = value.slice(0, value.length - excl_style1.length); - let pos2 = value.indexOf(excl_style2); - if ((pos2 >= 0) && (pos2 == value.length - excl_style2.length)) - value = value.slice(0, value.length - excl_style2.length); - } - this._wrapper.path_attr[name] = value; - } - } +/** @summary log normal pdf + * @memberof Math */ +function lognormal_pdf(x, m, s, x0 = 0) { + if ((x-x0) <= 0) + return 0.0; + const tmp = (Math.log((x-x0)) - m)/s; + return 1.0 / ((x-x0) * Math.abs(s) * Math.sqrt(2 * M_PI)) * Math.exp(-(tmp * tmp) /2); +} - if (kind != 'svg') { - console.error(`not supported element for SVGRenderer ${kind}`); - return null; - } +/** @summary normal pdf + * @memberof Math */ +function normal_pdf(x, sigma = 1, x0 = 0) { + const tmp = (x-x0)/sigma; + return (1.0/(Math.sqrt(2 * M_PI) * Math.abs(sigma))) * Math.exp(-tmp*tmp/2); +} - return { - _wrapper: this, - childNodes: [], // may be accessed - make dummy - style: this.svg_style, // for background color - setAttribute(name, value) { - this._wrapper.svg_attr[name] = value; - }, - appendChild(node) { - this._wrapper.accPath += ``; - this._wrapper.path_attr = {}; - }, - removeChild(node) { - this.childNodes = []; - } - }; - } - }; +/** @summary gamma calculation + * @memberof Math */ +function gamma(x) { + let p, q, z, i, sgngam = 1; - let originalDocument = globalThis.document; - globalThis.document = doc_wrapper; + if (x >= Number.MAX_VALUE) + return x; - let rndr = new SVGRenderer(); + q = Math.abs(x); - globalThis.document = originalDocument; + if ( q > 33.0 ) + { + if ( x < 0.0 ) + { + p = Math.floor(q); + if ( p == q ) + return Number.POSITIVE_INFINITY; + i = Math.round(p); + if ( (i & 1) == 0 ) + sgngam = -1; + z = q - p; + if ( z > 0.5 ) + { + p += 1.0; + z = q - p; + } + z = q * Math.sin(Math.PI * z); + if ( z == 0 ) + { + return sgngam > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + } + z = Math.abs(z); + z = Math.PI / (z * stirf(q)); + } + else + { + z = stirf(x); + } + return sgngam * z; + } - rndr.doc_wrapper = doc_wrapper; // use it to get final SVG code + z = 1.0; + while ( x >= 3.0 ) { + x -= 1.0; + z *= x; + } - rndr.originalRender = rndr.render; + let small = false; - rndr.render = function (scene, camera) { - let originalDocument = globalThis.document; - globalThis.document = this.doc_wrapper; + while (( x < 0.0 ) && !small) { + if ( x > -1.E-9 ) + small = true; + else { + z /= x; + x += 1.0; + } + } - this.originalRender(scene, camera); + while (( x < 2.0 ) && !small) { + if ( x < 1.e-9 ) + small = true; + else { + z /= x; + x += 1.0; + } + } - globalThis.document = originalDocument; - }; + if (small) { + if ( x == 0 ) + return Number.POSITIVE_INFINITY; + else + return z/((1.0 + 0.5772156649015329 * x) * x); + } - rndr.clearHTML = function() { - this.doc_wrapper.accPath = ''; - }; + if ( x == 2.0 ) + return z; - rndr.makeOuterHTML = function() { + const P = [ + 1.60119522476751861407E-4, + 1.19135147006586384913E-3, + 1.04213797561761569935E-2, + 4.76367800457137231464E-2, + 2.07448227648435975150E-1, + 4.94214826801497100753E-1, + 9.99999999999999996796E-1 + ], Q = [ + -2.31581873324120129819E-5, + 5.39605580493303397842E-4, + -4.45641913851797240494E-3, + 1.18139785222060435552E-2, + 3.58236398605498653373E-2, + -2.34591795718243348568E-1, + 7.14304917030273074085E-2, + 1.00000000000000000320E0]; - let wrap = this.doc_wrapper, - _textSizeAttr = `viewBox="${wrap.svg_attr['viewBox']}" width="${wrap.svg_attr['width']}" height="${wrap.svg_attr['height']}"`, - _textClearAttr = wrap.svg_style.backgroundColor ? ` style="background:${wrap.svg_style.backgroundColor}"` : ''; + x -= 2.0; + p = Polynomialeval( x, P, 6 ); + q = Polynomialeval( x, Q, 7 ); + return z * p / q; +} - return `${wrap.accPath}`; - }; +/** @summary ndtri function + * @memberof Math */ +function ndtri(y0) { + if ( y0 <= 0.0 ) + return Number.NEGATIVE_INFINITY; + if ( y0 >= 1.0 ) + return Number.POSITIVE_INFINITY; - rndr.setPrecision(precision); + const P0 = [ + -5.99633501014107895267E1, + 9.80010754185999661536E1, + -5.66762857469070293439E1, + 1.39312609387279679503E1, + -1.23916583867381258016E0 + ], Q0 = [ + 1.95448858338141759834E0, + 4.67627912898881538453E0, + 8.63602421390890590575E1, + -2.25462687854119370527E2, + 2.00260212380060660359E2, + -8.20372256168333339912E1, + 1.59056225126211695515E1, + -1.18331621121330003142E0 + ], P1 = [ + 4.05544892305962419923E0, + 3.15251094599893866154E1, + 5.71628192246421288162E1, + 4.40805073893200834700E1, + 1.46849561928858024014E1, + 2.18663306850790267539E0, + -1.40256079171354495875E-1, + -3.50424626827848203418E-2, + -8.57456785154685413611E-4 + ], Q1 = [ + 1.57799883256466749731E1, + 4.53907635128879210584E1, + 4.13172038254672030440E1, + 1.50425385692907503408E1, + 2.50464946208309415979E0, + -1.42182922854787788574E-1, + -3.80806407691578277194E-2, + -9.33259480895457427372E-4 + ], P2 = [ + 3.23774891776946035970E0, + 6.91522889068984211695E0, + 3.93881025292474443415E0, + 1.33303460815807542389E0, + 2.01485389549179081538E-1, + 1.23716634817820021358E-2, + 3.01581553508235416007E-4, + 2.65806974686737550832E-6, + 6.23974539184983293730E-9 + ], Q2 = [ + 6.02427039364742014255E0, + 3.67983563856160859403E0, + 1.37702099489081330271E0, + 2.16236993594496635890E-1, + 1.34204006088543189037E-2, + 3.28014464682127739104E-4, + 2.89247864745380683936E-6, + 6.79019408009981274425E-9 + ], s2pi = 2.50662827463100050242e0, dd = 0.13533528323661269189; - return rndr; + let code = 1, y = y0, x, y2, x1; + + if (y > (1.0 - dd)) { + y = 1.0 - y; + code = 0; + } + if ( y > dd ) { + y = y - 0.5; + y2 = y * y; + x = y + y * (y2 * Polynomialeval( y2, P0, 4)/ Polynomial1eval( y2, Q0, 8 )); + x = x * s2pi; + return x; + } + x = Math.sqrt(-2.0 * Math.log(y)); + const x0 = x - Math.log(x)/x, + z = 1.0/x; + if ( x < 8.0 ) + x1 = z * Polynomialeval( z, P1, 8 )/ Polynomial1eval( z, Q1, 8 ); + else + x1 = z * Polynomialeval( z, P2, 8 )/ Polynomial1eval( z, Q2, 8 ); + x = x0 - x1; + if ( code != 0 ) + x = -x; + return x; } +/** @summary normal_quantile function + * @memberof Math */ +function normal_quantile(z, sigma) { + return sigma * ndtri(z); +} -/** @ummary Define rendering kind which will be used for rendering of 3D elements - * @param {value} [render3d] - preconfigured value, will be used if applicable - * @return {value} - rendering kind, see constants.Render3D - * @private */ -function getRender3DKind(render3d) { - if (!render3d) render3d = isBatchMode() ? settings.Render3DBatch : settings.Render3D; - let rc = constants$1.Render3D; +/** @summary normal_quantile_c function + * @memberof Math */ +function normal_quantile_c(z, sigma) { + return -sigma * ndtri(z); +} - if (render3d == rc.Default) render3d = isBatchMode() ? rc.WebGLImage : rc.WebGL; - if (isBatchMode() && (render3d == rc.WebGL)) render3d = rc.WebGLImage; +/** @summary igamc function + * @memberof Math */ +function igamc(a,x) { + // LM: for negative values returns 0.0 + // This is correct if a is a negative integer since Gamma(-n) = +/- inf + if (a <= 0) return 0.0; - return render3d; -} + if (x <= 0) return 1.0; -let Handling3DDrawings = { + if ((x < 1.0) || (x < a)) + return (1.0 - igam(a,x)); - /** @summary Access current 3d mode - * @param {string} [new_value] - when specified, set new 3d mode - * @return current value - * @private */ - access3dKind(new_value) { - let svg = this.getPadSvg(); - if (svg.empty()) return -1; + let ax = a * Math.log(x) - x - lgam(a); + if ( ax < -kMAXLOG ) + return 0.0; - // returns kind of currently created 3d canvas - let kind = svg.property('can3d'); - if (new_value !== undefined) svg.property('can3d', new_value); - return ((kind === null) || (kind === undefined)) ? -1 : kind; - }, + ax = Math.exp(ax); - /** @summary Returns size which availble for 3D drawing. - * @desc One uses frame sizes for the 3D drawing - like TH2/TH3 objects - * @private */ - getSizeFor3d(can3d, render3d) { + /* continued fraction */ + let y = 1.0 - a, + z = x + y + 1.0, + c = 0.0, + pkm2 = 1.0, + qkm2 = x, + pkm1 = x + 1.0, + qkm1 = z * x, + ans = pkm1/qkm1, + yc, r, t, pk, qk; - if (can3d === undefined) { - // analyze which render/embed mode can be used - can3d = getRender3DKind(); - // all non-webgl elements can be embedded into SVG as is - if (can3d !== constants$1.Render3D.WebGL) - can3d = constants$1.Embed3D.EmbedSVG; - else if (settings.Embed3D != constants$1.Embed3D.Default) - can3d = settings.Embed3D; - else if (browser$1.isFirefox) - can3d = constants$1.Embed3D.Embed; - else if (browser$1.chromeVersion > 95) - // version 96 works partially, 97 works fine - can3d = constants$1.Embed3D.Embed; - else - can3d = constants$1.Embed3D.Overlay; + do { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk) + { + r = pk/qk; + t = Math.abs( (ans - r)/r ); + ans = r; + } + else + t = 1.0; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if ( Math.abs(pk) > kBig ) + { + pkm2 *= kBiginv; + pkm1 *= kBiginv; + qkm2 *= kBiginv; + qkm1 *= kBiginv; } + } while ( t > kMACHEP ); - let pad = this.getPadSvg(), - clname = 'draw3d_' + (this.getPadName() || 'canvas'); + return ans * ax; +} - if (pad.empty()) { - // this is a case when object drawn without canvas +/** @summary igam function + * @memberof Math */ +function igam(a, x) { + // LM: for negative values returns 1.0 instead of zero + // This is correct if a is a negative integer since Gamma(-n) = +/- inf + if (a <= 0) return 1.0; - let rect = getElementRect(this.selectDom()); + if (x <= 0) return 0.0; - if ((rect.height < 10) && (rect.width > 10)) { - rect.height = Math.round(0.66 * rect.width); - this.selectDom().style('height', rect.height + 'px'); - } - rect.x = 0; rect.y = 0; rect.clname = clname; rect.can3d = -1; - return rect; - } + if ((x > 1.0) && (x > a)) + return 1.0 - igamc(a,x); - let fp = this.getFramePainter(), pp = this.getPadPainter(), size; + /* Compute x**a * exp(-x) / gamma(a) */ + let ax = a * Math.log(x) - x - lgam(a); + if ( ax < -kMAXLOG ) + return 0.0; - if (fp?.mode3d && (can3d > 0)) { - size = fp.getFrameRect(); - } else { - let elem = (can3d > 0) ? pad : this.getCanvSvg(); - size = { x: 0, y: 0, width: elem.property('draw_width'), height: elem.property('draw_height') }; - if (Number.isNaN(size.width) || Number.isNaN(size.height)) { - size.width = pp.getPadWidth(); - size.height = pp.getPadHeight(); - } else if (fp && !fp.mode3d) { - elem = this.getFrameSvg(); - size.x = elem.property('draw_x'); - size.y = elem.property('draw_y'); - } - } + ax = Math.exp(ax); - size.clname = clname; - size.can3d = can3d; + /* power series */ + let r = a, c = 1.0, ans = 1.0; - let rect = pp?.getPadRect(); - if (rect) { - // while 3D canvas uses area also for the axis labels, extend area relative to normal frame - let dx = Math.round(size.width*0.07), dy = Math.round(size.height*0.05); + do { + r += 1.0; + c *= x/r; + ans += c; + } while ( c/ans > kMACHEP ); - size.x = Math.max(0, size.x-dx); - size.y = Math.max(0, size.y-dy); - size.width = Math.min(size.width + 2*dx, rect.width - size.x); - size.height = Math.min(size.height + 2*dy, rect.height - size.y); - } + return ans * ax/a; +} - if (can3d === 1) - size = getAbsPosInCanvas(this.getPadSvg(), size); - return size; - }, +/** @summary igami function + * @memberof Math */ +function igami(a, y0) { + // check the domain + if (a <= 0) { + console.error(`igami : Wrong domain for parameter a = ${a} (must be > 0)`); + return 0; + } + if (y0 <= 0) { + return Number.POSITIVE_INFINITY; + } + if (y0 >= 1) { + return 0; + } + const kMAXNUM = Number.MAX_VALUE, dithresh = 5.0 * kMACHEP; + let x0 = kMAXNUM, x1 = 0, x, yl = 0, yh = 1, y, d, lgm, i, dir; - /** @summary Clear all 3D drawings - * @return can3d value - how webgl canvas was placed - * @private */ - clear3dCanvas() { - let can3d = this.access3dKind(null); - if (can3d < 0) { - // remove first child from main element - if it is canvas - let main = this.selectDom().node(), - chld = main ? main.firstChild : null; + /* approximation to inverse function */ + d = 1.0/(9.0*a); + y = 1.0 - d - ndtri(y0) * Math.sqrt(d); + x = a * y * y * y; - if (chld && !chld.$jsroot) - chld = chld.nextSibling; + lgm = lgam(a); - if (chld && chld.$jsroot) { - delete chld.painter; - main.removeChild(chld); + for ( i=0; i<10; ++i ) { + if ( x > x0 || x < x1 ) + break; + y = igamc(a,x); + if ( y < yl || y > yh ) + break; + if ( y < y0 ) { + x0 = x; + yl = y; + } + else { + x1 = x; + yh = y; + } + /* compute the derivative of the function at this point */ + d = (a - 1.0) * Math.log(x) - x - lgm; + if ( d < -kMAXLOG ) + break; + d = -Math.exp(d); + /* compute the step to the next approximation of x */ + d = (y - y0)/d; + if ( Math.abs(d/x) < kMACHEP ) + return x; + x = x - d; + } + /* Resort to interval halving if Newton iteration did not converge. */ + d = 0.0625; + if ( x0 == kMAXNUM ) { + if ( x <= 0.0 ) + x = 1.0; + while ( x0 == kMAXNUM ) { + x = (1.0 + d) * x; + y = igamc( a, x ); + if ( y < y0 ) { + x0 = x; + yl = y; + break; } - return can3d; + d = d + d; } + } + d = 0.5; + dir = 0; - let size = this.getSizeFor3d(can3d); - - if (size.can3d === 0) { - select(this.getCanvSvg().node().nextSibling).remove(); // remove html5 canvas - this.getCanvSvg().style('display', null); // show SVG canvas - } else { - if (this.getPadSvg().empty()) return; - - this.apply3dSize(size).remove(); - - this.getFrameSvg().style('display', null); // clear display property + for ( i=0; i<400; ++i ) { + x = x1 + d * (x0 - x1); + y = igamc( a, x ); + lgm = (x0 - x1)/(x1 + x0); + if ( Math.abs(lgm) < dithresh ) + break; + lgm = (y - y0)/y0; + if ( Math.abs(lgm) < dithresh ) + break; + if ( x <= 0.0 ) + break; + if ( y >= y0 ) { + x1 = x; + yh = y; + if ( dir < 0 ) { + dir = 0; + d = 0.5; + } + else if ( dir > 1 ) + d = 0.5 * d + 0.5; + else + d = (y0 - yl)/(yh - yl); + dir += 1; } - return can3d; - }, - - /** @summary Add 3D canvas - * @private */ - add3dCanvas(size, canv, webgl) { - - if (!canv || (size.can3d < -1)) return; - - if (size.can3d === -1) { - // case when 3D object drawn without canvas - - let main = this.selectDom().node(); - if (main !== null) { - main.appendChild(canv); - canv.painter = this; - canv.$jsroot = true; // mark canvas as added by jsroot + else { + x0 = x; + yl = y; + if ( dir > 0 ) { + dir = 0; + d = 0.5; } - - return; + else if ( dir < -1 ) + d = 0.5 * d; + else + d = (y0 - yl)/(yh - yl); + dir -= 1; } + } + return x; +} - if ((size.can3d > 0) && !webgl) - size.can3d = constants$1.Embed3D.EmbedSVG; - - this.access3dKind(size.can3d); - - if (size.can3d === 0) { - this.getCanvSvg().style('display', 'none'); // hide SVG canvas +/** @summary landau_pdf function + * @desc LANDAU pdf : algorithm from CERNLIB G110 denlan + * same algorithm is used in GSL + * @memberof Math */ +function landau_pdf(x, xi, x0 = 0) { + if (xi <= 0) return 0; + const v = (x - x0)/xi; + let u, ue, us, denlan; + const p1 = [0.4259894875,-0.1249762550, 0.03984243700, -0.006298287635, 0.001511162253], + q1 = [1.0 ,-0.3388260629, 0.09594393323, -0.01608042283, 0.003778942063], + p2 = [0.1788541609, 0.1173957403, 0.01488850518, -0.001394989411, 0.0001283617211], + q2 = [1.0 , 0.7428795082, 0.3153932961, 0.06694219548, 0.008790609714], + p3 = [0.1788544503, 0.09359161662,0.006325387654, 0.00006611667319,-0.000002031049101], + q3 = [1.0 , 0.6097809921, 0.2560616665, 0.04746722384, 0.006957301675], + p4 = [0.9874054407, 118.6723273, 849.2794360, -743.7792444, 427.0262186], + q4 = [1.0 , 106.8615961, 337.6496214, 2016.712389, 1597.063511], + p5 = [1.003675074, 167.5702434, 4789.711289, 21217.86767, -22324.94910], + q5 = [1.0 , 156.9424537, 3745.310488, 9834.698876, 66924.28357], + p6 = [1.000827619, 664.9143136, 62972.92665, 475554.6998, -5743609.109], + q6 = [1.0 , 651.4101098, 56974.73333, 165917.4725, -2815759.939], + a1 = [0.04166666667,-0.01996527778, 0.02709538966], + a2 = [-1.845568670,-4.284640743]; - this.getCanvSvg().node().parentNode.appendChild(canv); // add directly - } else { - if (this.getPadSvg().empty()) return; + if (v < -5.5) { + u = Math.exp(v+1.0); + if (u < 1e-10) return 0.0; + ue = Math.exp(-1/u); + us = Math.sqrt(u); + denlan = 0.3989422803*(ue/us)*(1+(a1[0]+(a1[1]+a1[2]*u)*u)*u); + } else if (v < -1) { + u = Math.exp(-v-1); + denlan = Math.exp(-u)*Math.sqrt(u)* + (p1[0]+(p1[1]+(p1[2]+(p1[3]+p1[4]*v)*v)*v)*v)/ + (q1[0]+(q1[1]+(q1[2]+(q1[3]+q1[4]*v)*v)*v)*v); + } else if (v < 1) { + denlan = (p2[0]+(p2[1]+(p2[2]+(p2[3]+p2[4]*v)*v)*v)*v)/ + (q2[0]+(q2[1]+(q2[2]+(q2[3]+q2[4]*v)*v)*v)*v); + } else if (v < 5) { + denlan = (p3[0]+(p3[1]+(p3[2]+(p3[3]+p3[4]*v)*v)*v)*v)/ + (q3[0]+(q3[1]+(q3[2]+(q3[3]+q3[4]*v)*v)*v)*v); + } else if (v < 12) { + u = 1/v; + denlan = u*u*(p4[0]+(p4[1]+(p4[2]+(p4[3]+p4[4]*u)*u)*u)*u)/ + (q4[0]+(q4[1]+(q4[2]+(q4[3]+q4[4]*u)*u)*u)*u); + } else if (v < 50) { + u = 1/v; + denlan = u*u*(p5[0]+(p5[1]+(p5[2]+(p5[3]+p5[4]*u)*u)*u)*u)/ + (q5[0]+(q5[1]+(q5[2]+(q5[3]+q5[4]*u)*u)*u)*u); + } else if (v < 300) { + u = 1/v; + denlan = u*u*(p6[0]+(p6[1]+(p6[2]+(p6[3]+p6[4]*u)*u)*u)*u)/ + (q6[0]+(q6[1]+(q6[2]+(q6[3]+q6[4]*u)*u)*u)*u); + } else { + u = 1/(v-v*Math.log(v)/(v+1)); + denlan = u*u*(1+(a2[0]+a2[1]*u)*u); + } + return denlan/xi; +} - // first hide normal frame - this.getFrameSvg().style('display', 'none'); +/** @summary Landau function + * @memberof Math */ +function Landau(x, mpv, sigma, norm) { + if (sigma <= 0) return 0; + const den = landau_pdf((x - mpv) / sigma, 1, 0); + if (!norm) return den; + return den/sigma; +} - let elem = this.apply3dSize(size); +/** @summary inc_gamma_c + * @memberof Math */ +function inc_gamma_c(a,x) { + return igamc(a,x); +} - elem.attr('title', '').node().appendChild(canv); - } - }, +/** @summary inc_gamma + * @memberof Math */ +function inc_gamma(a,x) { + return igam(a,x); +} - /** @summary Apply size to 3D elements - * @private */ - apply3dSize(size, onlyget) { +/** @summary lgamma + * @memberof Math */ +function lgamma(z) { + return lgam(z); +} - if (size.can3d < 0) return select(null); +/** @summary Probability density function of the beta distribution. + * @memberof Math */ +function beta_pdf(x, a, b) { + if (x < 0 || x > 1.0) return 0; + if (x == 0 ) { + if (a < 1) return Number.POSITIVE_INFINITY; + else if (a > 1) return 0; + else if ( a == 1) return b; // to avoid a nan from log(0)*0 + } + if (x == 1 ) { + if (b < 1) return Number.POSITIVE_INFINITY; + else if (b > 1) return 0; + else if ( b == 1) return a; // to avoid a nan from log(0)*0 + } + return Math.exp(lgamma(a + b) - lgamma(a) - lgamma(b) + + Math.log(x) * (a -1.) + Math.log1p(-x) * (b - 1.)); +} - let elem; +/** @summary beta + * @memberof Math */ +function beta(x,y) { + return Math.exp(lgamma(x)+lgamma(y)-lgamma(x+y)); +} - if (size.can3d > 1) { +/** @summary chisquared_cdf_c + * @memberof Math */ +function chisquared_cdf_c(x,r,x0 = 0) { + return inc_gamma_c(0.5 * r, 0.5*(x-x0)); +} - elem = this.getLayerSvg(size.clname); +/** @summary Continued fraction expansion #1 for incomplete beta integral + * @memberof Math */ +function incbcf(a,b,x) { + let xk, pk, pkm1, pkm2, qk, qkm1, qkm2, + k1, k2, k3, k4, k5, k6, k7, k8, + r, t, ans, n; + const thresh = 3.0 * kMACHEP; - // elem = layer.select('.' + size.clname); - if (onlyget) return elem; + k1 = a; + k2 = a + b; + k3 = a; + k4 = a + 1.0; + k5 = 1.0; + k6 = b - 1.0; + k7 = k4; + k8 = a + 2.0; - let svg = this.getPadSvg(); + pkm2 = 0.0; + qkm2 = 1.0; + pkm1 = 1.0; + qkm1 = 1.0; + ans = 1.0; + r = 1.0; + n = 0; - if (size.can3d === constants$1.Embed3D.EmbedSVG) { - // this is SVG mode or image mode - just create group to hold element + do { + xk = -( x * k1 * k2 )/( k3 * k4 ); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - if (elem.empty()) - elem = svg.insert('g', '.primitives_layer').attr('class', size.clname); + xk = ( x * k5 * k6 )/( k7 * k8 ); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - elem.attr('transform', `translate(${size.x},${size.y})`); + if ( qk !=0 ) + r = pk/qk; + if ( r != 0 ) + { + t = Math.abs( (ans - r)/r ); + ans = r; + } + else + t = 1.0; - } else { + if ( t < thresh ) + break; // goto cdone; - if (elem.empty()) - elem = svg.insert('foreignObject', '.primitives_layer').attr('class', size.clname); + k1 += 1.0; + k2 += 1.0; + k3 += 2.0; + k4 += 2.0; + k5 += 1.0; + k6 -= 1.0; + k7 += 2.0; + k8 += 2.0; - elem.attr('x', size.x) - .attr('y', size.y) - .attr('width', size.width) - .attr('height', size.height) - .attr('viewBox', `0 0 ${size.width} ${size.height}`) - .attr('preserveAspectRatio', 'xMidYMid'); - } + if ((Math.abs(qk) + Math.abs(pk)) > kBig) { + pkm2 *= kBiginv; + pkm1 *= kBiginv; + qkm2 *= kBiginv; + qkm1 *= kBiginv; + } + if ((Math.abs(qk) < kBiginv) || (Math.abs(pk) < kBiginv)) { + pkm2 *= kBig; + pkm1 *= kBig; + qkm2 *= kBig; + qkm1 *= kBig; + } + } + while ( ++n < 300 ); - } else { - let prnt = this.getCanvSvg().node().parentNode; +// cdone: + return ans; +} - elem = select(prnt).select('.' + size.clname); - if (onlyget) return elem; +/** @summary Continued fraction expansion #2 for incomplete beta integral + * @memberof Math */ +function incbd(a,b,x) { + const z = x / (1.0-x), + thresh = 3.0 * kMACHEP; - // force redraw by resize - this.getCanvSvg().property('redraw_by_resize', true); + let xk, pk, pkm1, pkm2, qk, qkm1, qkm2, + k1, k2, k3, k4, k5, k6, k7, k8, + r, t, ans, n; - if (elem.empty()) - elem = select(prnt).append('div').attr('class', size.clname) - .style('user-select', 'none'); + k1 = a; + k2 = b - 1.0; + k3 = a; + k4 = a + 1.0; + k5 = 1.0; + k6 = a + b; + k7 = a + 1.0; + k8 = a + 2.0; - // our position inside canvas, but to set 'absolute' position we should use - // canvas element offset relative to first parent with non-static position - // now try to use getBoundingClientRect - it should be more precise + pkm2 = 0.0; + qkm2 = 1.0; + pkm1 = 1.0; + qkm1 = 1.0; + ans = 1.0; + r = 1.0; + n = 0; + do { + xk = -( z * k1 * k2 )/( k3 * k4 ); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - let pos0 = prnt.getBoundingClientRect(); + xk = ( z * k5 * k6 )/( k7 * k8 ); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; - while (prnt) { - if (prnt === document) { prnt = null; break; } - try { - if (getComputedStyle(prnt).position !== 'static') break; - } catch (err) { - break; - } - prnt = prnt.parentNode; - } + if ( qk != 0 ) + r = pk/qk; + if ( r != 0 ) + { + t = Math.abs( (ans - r)/r ); + ans = r; + } + else + t = 1.0; - let pos1 = prnt?.getBoundingClientRect() ?? { top: 0, left: 0 }, - offx = Math.round(pos0.left - pos1.left), - offy = Math.round(pos0.top - pos1.top); + if ( t < thresh ) + break; // goto cdone; - elem.style('position', 'absolute').style('left', (size.x + offx) + 'px').style('top', (size.y + offy) + 'px').style('width', size.width + 'px').style('height', size.height + 'px'); - } + k1 += 1.0; + k2 -= 1.0; + k3 += 2.0; + k4 += 2.0; + k5 += 1.0; + k6 += 1.0; + k7 += 2.0; + k8 += 2.0; - return elem; + if ((Math.abs(qk) + Math.abs(pk)) > kBig) { + pkm2 *= kBiginv; + pkm1 *= kBiginv; + qkm2 *= kBiginv; + qkm1 *= kBiginv; + } + if ((Math.abs(qk) < kBiginv) || (Math.abs(pk) < kBiginv)) { + pkm2 *= kBig; + pkm1 *= kBig; + qkm2 *= kBig; + qkm1 *= kBig; + } } + while ( ++n < 300 ); +// cdone: + return ans; +} -}; // Handling3DDrawings +/** @summary ROOT::Math::Cephes::pseries + * @memberof Math */ +function pseries(a,b,x) { + let s, t, u, v, n; + const ai = 1.0 / a; + u = (1.0 - b) * x; + v = u / (a + 1.0); + const t1 = v; + t = u; + n = 2.0; + s = 0.0; + const z = kMACHEP * ai; + while ( Math.abs(v) > z ) { + u = (n - b) * x / n; + t *= u; + v = t / (a + n); + s += v; + n += 1.0; + } + s += t1; + s += ai; -/** @summary Assigns method to handle 3D drawings inside SVG - * @private */ -function assign3DHandler(painter) { - Object.assign(painter, Handling3DDrawings); + u = a * Math.log(x); + if ( (a+b) < kMAXSTIR && Math.abs(u) < kMAXLOG ) + { + t = gamma(a+b) / (gamma(a)*gamma(b)); + s = s * t * Math.pow(x,a); + } + else + { + t = lgam(a+b) - lgam(a) - lgam(b) + u + Math.log(s); + if ( t < kMINLOG ) + s = 0.0; + else + s = Math.exp(t); + } + return s; } +/** @summary ROOT::Math::Cephes::incbet + * @memberof Math */ +function incbet(aa,bb,xx) { + let a, b, t, x, xc, w, y, flag; -/** @summary Creates renderer for the 3D drawings - * @param {value} width - rendering width - * @param {value} height - rendering height - * @param {value} render3d - render type, see {@link constants.Render3D} - * @param {object} args - different arguments for creating 3D renderer - * @return {Promise} with renderer object - * @private */ + if ( aa <= 0.0 || bb <= 0.0 ) + return 0.0; -async function createRender3D(width, height, render3d, args) { + // LM: changed: for X > 1 return 1. + if (xx <= 0.0) return 0.0; + if ( xx >= 1.0) return 1.0; - let rc = constants$1.Render3D, promise, need_workaround = false, doc = getDocument(); + flag = 0; - render3d = getRender3DKind(render3d); +/* - to test if that way is better for large b/ (comment out from Cephes version) + if ( (bb * xx) <= 1.0 && xx <= 0.95) + { + t = pseries(aa, bb, xx); + goto done; + } - if (!args) args = { antialias: true, alpha: true }; +**/ + w = 1.0 - xx; - if (render3d == rc.WebGL) { - // interactive WebGL Rendering - promise = Promise.resolve(new WebGLRenderer(args)); +/* Reverse a and b if x is greater than the mean. */ +/* aa,bb > 1 -> sharp rise at x=aa/(aa+bb) */ + if (xx > (aa/(aa+bb))) + { + flag = 1; + a = bb; + b = aa; + xc = xx; + x = w; + } + else + { + a = aa; + b = bb; + xc = w; + x = xx; + } - } else if (render3d == rc.SVG) { - // SVG rendering - let r = createSVGRenderer(false, 0, doc); + if ( flag == 1 && (b * x) <= 1.0 && x <= 0.95) { + t = pseries(a, b, x); + // goto done; + } else { + /* Choose expansion for better convergence. */ + y = x * (a+b-2.0) - (a-1.0); + if ( y < 0.0 ) + w = incbcf( a, b, x ); + else + w = incbd( a, b, x ) / xc; - if (isBatchMode()) { - need_workaround = true; + /* Multiply w by the factor + a b _ _ _ + x (1-x) | (a+b) / (a | (a) | (b)) . */ + + y = a * Math.log(x); + t = b * Math.log(xc); + if ( (a+b) < kMAXSTIR && Math.abs(y) < kMAXLOG && Math.abs(t) < kMAXLOG ) + { + t = Math.pow(xc,b); + t *= Math.pow(x,a); + t /= a; + t *= w; + t *= gamma(a+b) / (gamma(a) * gamma(b)); + // goto done; } else { - r.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); - // d3_select(r.jsroot_dom).attr('width', width).attr('height', height); + /* Resort to logarithms. */ + y += t + lgam(a+b) - lgam(a) - lgam(b); + y += Math.log(w/a); + if ( y < kMINLOG ) + t = 0.0; + else + t = Math.exp(y); } - promise = Promise.resolve(r); - } else if (isNodeJs()) { - // try to use WebGL inside node.js - need to create headless context - promise = Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(node_canvas => { - args.canvas = node_canvas.default.createCanvas(width, height); - args.canvas.addEventListener = function() { }; // dummy - args.canvas.removeEventListener = function() { }; // dummy - args.canvas.style = {}; - return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }); - }).then(node_gl => { - let gl = node_gl.default(width, height, { preserveDrawingBuffer: true }); - if (!gl) throw(Error('Fail to create headless-gl')); - args.context = gl; - gl.canvas = args.canvas; - - let r = new WebGLRenderer(args); + } - r.jsroot_output = new WebGLRenderTarget(width, height); - r.setRenderTarget(r.jsroot_output); - need_workaround = true; - return r; - }); +// done: - } else { - // rendering with WebGL directly into svg image - let r = new WebGLRenderer(args); - r.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'image'); - select(r.jsroot_dom).attr('width', width).attr('height', height); - promise = Promise.resolve(r); + if (flag == 1) { + if ( t <= kMACHEP ) + t = 1.0 - kMACHEP; + else + t = 1.0 - t; } + return t; +} - return promise.then(renderer => { +/** @summary copy of ROOT::Math::Cephes::incbi + * @memberof Math */ +function incbi(aa,bb,yy0) { + let a, b, y0, d, y, x, x0, x1, lgm, yp, di, dithresh, yl, yh, xt, + i, rflg, dir, nflg, ihalve = true; - if (need_workaround) { - if (!internals.svg_3ds) internals.svg_3ds = []; - renderer.workaround_id = internals.svg_3ds.length; - internals.svg_3ds[renderer.workaround_id] = ''; // dummy, provided in afterRender3D + // check the domain + if (aa <= 0) { + // MATH_ERROR_MSG('Cephes::incbi','Wrong domain for parameter a (must be > 0)'); + return 0; + } + if (bb <= 0) { + // MATH_ERROR_MSG('Cephes::incbi','Wrong domain for parameter b (must be > 0)'); + return 0; + } - // replace DOM element in renderer - renderer.jsroot_dom = doc.createElementNS('http://www.w3.org/2000/svg', 'path'); - renderer.jsroot_dom.setAttribute('jsroot_svg_workaround', renderer.workaround_id); - } else if (!renderer.jsroot_dom) { - renderer.jsroot_dom = renderer.domElement; + const process_done = () => { + if ( rflg ) { + if ( x <= kMACHEP ) + x = 1.0 - kMACHEP; + else + x = 1.0 - x; } + return x; + }; - // res.renderer.setClearColor('#000000', 1); - // res.renderer.setClearColor(0x0, 0); - renderer.setSize(width, height); - renderer.jsroot_render3d = render3d; - - // apply size to dom element - renderer.setJSROOTSize = function(width, height) { - if ((this.jsroot_render3d === constants$1.Render3D.WebGLImage) && !isBatchMode() && !isNodeJs()) - return select(this.jsroot_dom).attr('width', width).attr('height', height); - }; - - return renderer; - }); -} + i = 0; + if ( yy0 <= 0 ) + return 0.0; + if ( yy0 >= 1.0 ) + return 1.0; + x0 = 0.0; + yl = 0.0; + x1 = 1.0; + yh = 1.0; + nflg = 0; + if ( aa <= 1.0 || bb <= 1.0 ) + { + dithresh = 1.0e-6; + rflg = 0; + a = aa; + b = bb; + y0 = yy0; + x = a/(a+b); + y = incbet( a, b, x ); + // goto ihalve; // will start + } + else + { + dithresh = 1.0e-4; +/* approximation to inverse function */ -/** @summary Cleanup created renderer object - * @private */ -function cleanupRender3D(renderer) { - if (!renderer) return; + yp = -ndtri(yy0); - if (isNodeJs()) { - let ctxt = isFunc(renderer.getContext) ? renderer.getContext() : null, - ext = ctxt?.getExtension('STACKGL_destroy_context'); - if (ext) ext.destroy(); - } else { - // suppress warnings in Chrome about lost webgl context, not required in firefox - if (browser$1.isChrome && isFunc(renderer.forceContextLoss)) - renderer.forceContextLoss(); + if ( yy0 > 0.5 ) + { + rflg = 1; + a = bb; + b = aa; + y0 = 1.0 - yy0; + yp = -yp; + } + else + { + rflg = 0; + a = aa; + b = bb; + y0 = yy0; + } - if (isFunc(renderer.dispose)) - renderer.dispose(); + lgm = (yp * yp - 3.0)/6.0; + x = 2.0/(1.0/(2.0*a-1.0) + 1.0/(2.0*b-1.0)); + d = yp * Math.sqrt( x + lgm ) / x + - (1.0/(2.0*b-1.0) - 1.0/(2.0*a-1.0)) + * (lgm + 5.0/6.0 - 2.0/(3.0*x)); + d = 2.0 * d; + if ( d < kMINLOG ) { + // x = 1.0; + // goto under; + x = 0.0; + return process_done(); + } + x = a/(a + b * Math.exp(d)); + y = incbet( a, b, x ); + yp = (y - y0)/y0; + if ( Math.abs(yp) < 0.2 ) + ihalve = false; // instead goto newt; exclude ihalve for the first time } -} -/** @summary Cleanup previous renderings before doing next one - * @desc used together with SVG - * @private */ -function beforeRender3D(renderer) { - if (renderer.clearHTML) renderer.clearHTML(); -} + let mainloop = 1000; -/** @summary Post-process result of rendering - * @desc used together with SVG or node.js image rendering - * @private */ -function afterRender3D(renderer) { + // endless loop until coverage + while (mainloop-- > 0) { + /* Resort to interval halving if not close enough. */ + // ihalve: + if (ihalve) { + dir = 0; + di = 0.5; + for ( i=0; i<100; i++ ) + { + if ( i != 0 ) + { + x = x0 + di * (x1 - x0); + if ( x == 1.0 ) + x = 1.0 - kMACHEP; + if ( x == 0.0 ) + { + di = 0.5; + x = x0 + di * (x1 - x0); + if ( x == 0.0 ) + return process_done(); // goto under; + } + y = incbet( a, b, x ); + yp = (x1 - x0)/(x1 + x0); + if ( Math.abs(yp) < dithresh ) + break; // goto newt; + yp = (y-y0)/y0; + if ( Math.abs(yp) < dithresh ) + break; // goto newt; + } + if ( y < y0 ) + { + x0 = x; + yl = y; + if ( dir < 0 ) + { + dir = 0; + di = 0.5; + } + else if ( dir > 3 ) + di = 1.0 - (1.0 - di) * (1.0 - di); + else if ( dir > 1 ) + di = 0.5 * di + 0.5; + else + di = (y0 - y)/(yh - yl); + dir += 1; + if ( x0 > 0.75 ) + { + if ( rflg == 1 ) + { + rflg = 0; + a = aa; + b = bb; + y0 = yy0; + } + else + { + rflg = 1; + a = bb; + b = aa; + y0 = 1.0 - yy0; + } + x = 1.0 - x; + y = incbet( a, b, x ); + x0 = 0.0; + yl = 0.0; + x1 = 1.0; + yh = 1.0; + continue; // goto ihalve; + } + } + else + { + x1 = x; + if ( rflg == 1 && x1 < kMACHEP ) + { + x = 0.0; + return process_done(); // goto done; + } + yh = y; + if ( dir > 0 ) + { + dir = 0; + di = 0.5; + } + else if ( dir < -3 ) + di = di * di; + else if ( dir < -1 ) + di = 0.5 * di; + else + di = (y - y0)/(yh - yl); + dir -= 1; + } + } + // math_error( 'incbi', PLOSS ); + if ( x0 >= 1.0 ) { + x = 1.0 - kMACHEP; + return process_done(); // goto done; + } + if ( x <= 0.0 ) { + // math_error( 'incbi', UNDERFLOW ); + x = 0.0; + return process_done(); // goto done; + } + break; // if here, break ihalve + } // end of ihalve - let rc = constants$1.Render3D; - if (renderer.jsroot_render3d == rc.WebGL) return; + ihalve = true; // enter loop next time - if (renderer.jsroot_render3d == rc.SVG) { - // case of SVGRenderer - if (isBatchMode()) { - internals.svg_3ds[renderer.workaround_id] = renderer.makeOuterHTML(); - } else { - let parent = renderer.jsroot_dom.parentNode; - if (parent) { - parent.innerHTML = renderer.makeOuterHTML(); - renderer.jsroot_dom = parent.firstChild; - } - } - } else if (isNodeJs()) { - // this is WebGL rendering in node.js - let canvas = renderer.domElement, - context = canvas.getContext('2d'); + // newt: - let pixels = new Uint8Array(4 * canvas.width * canvas.height); - renderer.readRenderTargetPixels(renderer.jsroot_output, 0, 0, canvas.width, canvas.height, pixels); + if ( nflg ) + return process_done(); // goto done; + nflg = 1; + lgm = lgam(a+b) - lgam(a) - lgam(b); - // small code to flip Y scale - let indx1 = 0, indx2 = (canvas.height - 1) * 4 * canvas.width, k, d; - while (indx1 < indx2) { - for (k = 0; k < 4 * canvas.width; ++k) { - d = pixels[indx1 + k]; pixels[indx1 + k] = pixels[indx2 + k]; pixels[indx2 + k] = d; + for ( i=0; i<8; i++ ) + { + /* Compute the function at this point. */ + if ( i != 0 ) + y = incbet(a,b,x); + if ( y < yl ) + { + x = x0; + y = yl; } - indx1 += 4 * canvas.width; - indx2 -= 4 * canvas.width; + else if ( y > yh ) + { + x = x1; + y = yh; + } + else if ( y < y0 ) + { + x0 = x; + yl = y; + } + else + { + x1 = x; + yh = y; + } + if ( x == 1.0 || x == 0.0 ) + break; + /* Compute the derivative of the function at this point. */ + d = (a - 1.0) * Math.log(x) + (b - 1.0) * Math.log(1.0-x) + lgm; + if ( d < kMINLOG ) + return process_done(); // goto done; + if ( d > kMAXLOG ) + break; + d = Math.exp(d); + /* Compute the step to the next approximation of x. */ + d = (y - y0)/d; + xt = x - d; + if ( xt <= x0 ) + { + y = (x - x0) / (x1 - x0); + xt = x0 + 0.5 * y * (x - x0); + if ( xt <= 0.0 ) + break; + } + if ( xt >= x1 ) + { + y = (x1 - x) / (x1 - x0); + xt = x1 - 0.5 * y * (x1 - x); + if ( xt >= 1.0 ) + break; + } + x = xt; + if ( Math.abs(d/x) < 128.0 * kMACHEP ) + return process_done(); // goto done; } + /* Did not converge. */ + dithresh = 256.0 * kMACHEP; + } // endless loop instead of // goto ihalve; - let imageData = context.createImageData(canvas.width, canvas.height); - imageData.data.set(pixels); - context.putImageData(imageData, 0, 0); +// done: - let dataUrl = canvas.toDataURL('image/png'), - svg = ``; - internals.svg_3ds[renderer.workaround_id] = svg; - } else { - let dataUrl = renderer.domElement.toDataURL('image/png'); - select(renderer.jsroot_dom).attr('xlink:href', dataUrl); - } + return process_done(); } -/** @summary Special way to insert WebGL drawing into produced SVG batch code - * @desc Used only in batch mode for SVG images generation - * @private */ -internals.processSvgWorkarounds = function(svg, keep_workarounds) { - if (!internals.svg_3ds) return svg; - for (let k = 0; k < internals.svg_3ds.length; ++k) - svg = svg.replace(``, internals.svg_3ds[k]); - if (!keep_workarounds) - internals.svg_3ds = undefined; - return svg; -}; - -// ======================================================================================================== - -/** - * @summary Tooltip handler for 3D drawings - * - * @private - */ - -class TooltipFor3D { - - /** @summary constructor - * @param {object} dom - DOM element - * @param {object} canvas - canvas for 3D rendering */ - constructor(prnt, canvas) { - this.tt = null; - this.cont = null; - this.lastlbl = ''; - this.parent = prnt ? prnt : document.body; - this.canvas = canvas; // we need canvas to recalculate mouse events - this.abspos = !prnt; - } - - /** @summary check parent */ - checkParent(prnt) { - if (prnt && (this.parent !== prnt)) { - this.hide(); - this.parent = prnt; - } - } +/** @summary Calculates the normalized (regularized) incomplete beta function. + * @memberof Math */ +function inc_beta(x,a,b) { + return incbet(a,b,x); +} - /** @summary extract position from event - * @desc can be used to process it later when event is gone */ - extract_pos(e) { - if (isObject(e) && (e.u !== undefined) && (e.l !== undefined)) return e; - let res = { u: 0, l: 0 }; - if (this.abspos) { - res.l = e.pageX; - res.u = e.pageY; - } else { - res.l = e.offsetX; - res.u = e.offsetY; - } +const BetaIncomplete = inc_beta; - return res; - } +/** @summary ROOT::Math::beta_quantile + * @memberof Math */ +function beta_quantile(z,a,b) { + return incbi(a,b,z); +} - /** @summary Method used to define position of next tooltip - * @desc event is delivered from canvas, - * but position should be calculated relative to the element where tooltip is placed */ - pos(e) { +/** @summary Complement of the cumulative distribution function of the beta distribution. + * @memberof Math */ +function beta_cdf_c(x,a,b) { + return inc_beta(1-x, b, a); +} - if (!this.tt) return; +/** @summary chisquared_cdf + * @memberof Math */ +function chisquared_cdf(x,r,x0=0) { + return inc_gamma(0.5 * r, 0.5*(x-x0)); +} - let pos = this.extract_pos(e); - if (!this.abspos) { - let rect1 = this.parent.getBoundingClientRect(), - rect2 = this.canvas.getBoundingClientRect(); +/** @summary gamma_quantile_c function + * @memberof Math */ +function gamma_quantile_c(z, alpha, theta) { + return theta * igami( alpha, z); +} - if ((rect1.left !== undefined) && (rect2.left!== undefined)) pos.l += (rect2.left-rect1.left); +/** @summary gamma_quantile function + * @memberof Math */ +function gamma_quantile(z, alpha, theta) { + return theta * igami( alpha, 1.- z); +} - if ((rect1.top !== undefined) && (rect2.top!== undefined)) pos.u += rect2.top-rect1.top; +/** @summary breitwigner_cdf_c function + * @memberof Math */ +function breitwigner_cdf_c(x,gamma, x0 = 0) { + return 0.5 - Math.atan(2.0 * (x-x0) / gamma) / M_PI; +} - if (pos.l + this.tt.offsetWidth + 3 >= this.parent.offsetWidth) - pos.l = this.parent.offsetWidth - this.tt.offsetWidth - 3; +/** @summary breitwigner_cdf function + * @memberof Math */ +function breitwigner_cdf(x, gamma, x0 = 0) { + return 0.5 + Math.atan(2.0 * (x-x0) / gamma) / M_PI; +} - if (pos.u + this.tt.offsetHeight + 15 >= this.parent.offsetHeight) - pos.u = this.parent.offsetHeight - this.tt.offsetHeight - 15; +/** @summary cauchy_cdf_c function + * @memberof Math */ +function cauchy_cdf_c(x, b, x0 = 0) { + return 0.5 - Math.atan( (x-x0) / b) / M_PI; +} - // one should find parent with non-static position, - // all absolute coordinates calculated relative to such node - let abs_parent = this.parent; - while (abs_parent) { - let style = getComputedStyle(abs_parent); - if (!style || (style.position !== 'static')) break; - if (!abs_parent.parentNode || (abs_parent.parentNode.nodeType != 1)) break; - abs_parent = abs_parent.parentNode; - } +/** @summary cauchy_cdf function + * @memberof Math */ +function cauchy_cdf(x, b, x0 = 0) { + return 0.5 + Math.atan( (x-x0) / b) / M_PI; +} - if (abs_parent && (abs_parent !== this.parent)) { - let rect0 = abs_parent.getBoundingClientRect(); - pos.l += (rect1.left - rect0.left); - pos.u += (rect1.top - rect0.top); - } - } +/** @summary cauchy_pdf function + * @memberof Math */ +function cauchy_pdf(x, b = 1, x0 = 0) { + return b/(M_PI * ((x-x0)*(x-x0) + b*b)); +} - this.tt.style.top = (pos.u + 15) + 'px'; - this.tt.style.left = (pos.l + 3) + 'px'; +/** @summary gaussian_pdf function + * @memberof Math */ +function gaussian_pdf(x, sigma = 1, x0 = 0) { + const tmp = (x-x0)/sigma; + return (1.0/(Math.sqrt(2 * M_PI) * Math.abs(sigma))) * Math.exp(-tmp*tmp/2); +} + +/** @summary gamma_pdf function + * @memberof Math */ +function gamma_pdf(x, alpha, theta, x0 = 0) { + if ((x - x0) < 0) { + return 0.0; + } else if ((x - x0) == 0) { + return (alpha == 1) ? 1.0 / theta : 0; + } else if (alpha == 1) { + return Math.exp(-(x - x0) / theta) / theta; } + return Math.exp((alpha - 1) * Math.log((x - x0) / theta) - (x - x0) / theta - lgamma(alpha)) / theta; +} - /** @summary Show tooltip */ - show(v /*, mouse_pos, status_func*/) { - if (!v) return this.hide(); +/** @summary tdistribution_cdf_c function + * @memberof Math */ +function tdistribution_cdf_c(x, r, x0 = 0) { + const p = x - x0, + sign = (p > 0) ? 1. : -1; + return .5 - .5*inc_beta(p*p/(r + p*p), .5, .5*r)*sign; +} - if (isObject(v) && (v.lines || v.line)) { - if (v.only_status) return this.hide(); +/** @summary tdistribution_cdf function + * @memberof Math */ +function tdistribution_cdf(x, r, x0 = 0) { + const p = x - x0, + sign = (p > 0) ? 1. : -1; + return .5 + .5*inc_beta(p*p/(r + p*p), .5, .5*r)*sign; +} - if (v.line) { - v = v.line; - } else { - let res = v.lines[0]; - for (let n=1;n1 and large a and b IB looses precision use complement function + if (z > 0.9 && n > 1 && m > 1) return 1. - fdistribution_cdf(x, n, m, x0); - // function used to hide some events from orbit control and redirect them to zooming rect - if (control.mouse_zoom_mesh) { - evnt.stopImmediatePropagation(); - evnt.stopPropagation(); - return; - } + // for the complement use the fact that IB(x,a,b) = 1. - IB(1-x,b,a) + return inc_beta(m / (m + n * (x - x0)), .5 * m, .5 * n); +} - // only left-button is considered - if ((evnt.button!==undefined) && (evnt.button !== 0)) return; - if ((evnt.buttons!==undefined) && (evnt.buttons !== 1)) return; +/** @summary fdistribution_cdf function + * @memberof Math */ +function fdistribution_cdf(x, n, m, x0 = 0) { + if (n < 0 || m < 0) return Number.NaN; - if (control.enable_zoom) { - control.mouse_zoom_mesh = control.detectZoomMesh(evnt); - if (control.mouse_zoom_mesh) { - // just block orbit control - evnt.stopImmediatePropagation(); - evnt.stopPropagation(); - return; - } - } + const z = n * (x - x0) / (m + n * (x - x0)); + // fox z->1 and large a and b IB looses precision use complement function + if (z > 0.9 && n > 1 && m > 1) + return 1. - fdistribution_cdf_c(x, n, m, x0); - if (control.enable_select) - control.mouse_select_pnt = control.getMousePos(evnt, {}); - } + return inc_beta(z, .5 * n, .5 * m); +} - function control_mouseup(evnt) { - if (!control) return; +/** @summary Prob function + * @memberof Math */ +function Prob(chi2, ndf) { + if (ndf <= 0) return 0; // Set CL to zero in case ndf <= 0 - if (control.mouse_zoom_mesh && control.mouse_zoom_mesh.point2 && control.painter.get3dZoomCoord) { + if (chi2 <= 0) { + if (chi2 < 0) return 0; + else return 1; + } - let kind = control.mouse_zoom_mesh.object.zoom, - pos1 = control.painter.get3dZoomCoord(control.mouse_zoom_mesh.point, kind), - pos2 = control.painter.get3dZoomCoord(control.mouse_zoom_mesh.point2, kind); + return chisquared_cdf_c(chi2,ndf,0); +} - if (pos1 > pos2) { let v = pos1; pos1 = pos2; pos2 = v; } +/** @summary Gaus function + * @memberof Math */ +function Gaus(x, mean, sigma, norm) { + if (!sigma) return 1e30; + const arg = (x - mean) / sigma; + if (arg < -39 || arg > 39) return 0; + const res = Math.exp(-0.5*arg*arg); + return norm ? res/(2.50662827463100024*sigma) : res; // sqrt(2*Pi)=2.50662827463100024 +} - if ((kind === 'z') && control.mouse_zoom_mesh.object.use_y_for_z) kind = 'y'; +/** @summary BreitWigner function + * @memberof Math */ +function BreitWigner(x, mean, gamma) { + return gamma/((x-mean)*(x-mean) + gamma*gamma/4) / 2 / Math.PI; +} - // try to zoom - if (pos1 < pos2) - if (control.painter.zoom(kind, pos1, pos2)) - control.mouse_zoom_mesh = null; - } +/** @summary Calculates Beta-function Gamma(p)*Gamma(q)/Gamma(p+q). + * @memberof Math */ +function Beta(x,y) { + return Math.exp(lgamma(x) + lgamma(y) - lgamma(x+y)); +} - // if selection was drawn, it should be removed and picture rendered again - if (control.enable_zoom) - control.removeZoomMesh(); +/** @summary GammaDist function + * @memberof Math */ +function GammaDist(x, gamma, mu = 0, beta = 1) { + if ((x < mu) || (gamma <= 0) || (beta <= 0)) return 0; + return gamma_pdf(x, gamma, beta, mu); +} - // only left-button is considered - //if ((evnt.button!==undefined) && (evnt.button !== 0)) return; - //if ((evnt.buttons!==undefined) && (evnt.buttons !== 1)) return; +/** @summary probability density function of Laplace distribution + * @memberof Math */ +function LaplaceDist(x, alpha = 0, beta = 1) { + return Math.exp(-Math.abs((x-alpha)/beta)) / (2.*beta); +} - if (control.enable_select && control.mouse_select_pnt) { +/** @summary distribution function of Laplace distribution + * @memberof Math */ +function LaplaceDistI(x, alpha = 0, beta = 1) { + return (x <= alpha) ? 0.5*Math.exp(-Math.abs((x-alpha)/beta)) : 1 - 0.5*Math.exp(-Math.abs((x-alpha)/beta)); +} - let pnt = control.getMousePos(evnt, {}), - same_pnt = (pnt.x == control.mouse_select_pnt.x) && (pnt.y == control.mouse_select_pnt.y); - delete control.mouse_select_pnt; +/** @summary density function for Student's t- distribution + * @memberof Math */ +function Student(T, ndf) { + if (ndf < 1) return 0; - if (same_pnt) { - let intersects = control.getMouseIntersects(pnt); - control.painter.processMouseClick(pnt, intersects, evnt); - } - } - } + const r = ndf, + rh = 0.5*r, + rh1 = rh + 0.5, + denom = Math.sqrt(r*Math.PI)*gamma(rh)*Math.pow(1+T*T/r, rh1); + return gamma(rh1)/denom; +} - function render3DFired(painter) { - if (!painter || painter.renderer === undefined) return false; - return painter.render_tmout !== undefined; // when timeout configured, object is prepared for rendering - } +/** @summary cumulative distribution function of Student's + * @memberof Math */ +function StudentI(T, ndf) { + const r = ndf; - function control_mousewheel(evnt) { - if (!control) return; + return (T > 0) + ? (1 - 0.5*BetaIncomplete((r/(r + T*T)), r*0.5, 0.5)) + : 0.5*BetaIncomplete((r/(r + T*T)), r*0.5, 0.5); +} - // try to handle zoom extra +/** @summary LogNormal function + * @memberof Math */ +function LogNormal(x, sigma, theta = 0, m = 1) { + if ((x < theta) || (sigma <= 0) || (m <= 0)) return 0; + return lognormal_pdf(x, Math.log(m), sigma, theta); +} - if (render3DFired(control.painter) || control.mouse_zoom_mesh) { - evnt.preventDefault(); - evnt.stopPropagation(); - evnt.stopImmediatePropagation(); - return; // already fired redraw, do not react on the mouse wheel - } +/** @summary Computes the probability density function of the Beta distribution + * @memberof Math */ +function BetaDist(x, p, q) { + if ((x < 0) || (x > 1) || (p <= 0) || (q <= 0)) + return 0; + const beta = Beta(p, q); + return Math.pow(x, p-1) * Math.pow(1-x, q-1) / beta; +} - let intersect = control.detectZoomMesh(evnt); - if (!intersect) return; +/** @summary Computes the distribution function of the Beta distribution. + * @memberof Math */ +function BetaDistI(x, p, q) { + if ((x < 0) || (x > 1) || (p <= 0) || (q <= 0)) return 0; + return BetaIncomplete(x, p, q); +} - evnt.preventDefault(); - evnt.stopPropagation(); - evnt.stopImmediatePropagation(); +/** @summary gaus function for TFormula + * @memberof Math */ +function gaus(f, x, i) { + return f.GetParValue(i+0) * Math.exp(-0.5 * Math.pow((x-f.GetParValue(i+1)) / f.GetParValue(i+2), 2)); +} - if (isFunc(control.painter?.analyzeMouseWheelEvent)) { - let kind = intersect.object.zoom, - position = intersect.point[kind], - item = { name: kind, ignore: false }; +/** @summary gausn function for TFormula + * @memberof Math */ +function gausn(f, x, i) { + return gaus(f, x, i)/(Math.sqrt(2 * Math.PI) * f.GetParValue(i+2)); +} - // z changes from 0..2*size_z3d, others -size_x3d..+size_x3d - switch (kind) { - case 'x': position = (position + control.painter.size_x3d)/2/control.painter.size_x3d; break; - case 'y': position = (position + control.painter.size_y3d)/2/control.painter.size_y3d; break; - case 'z': position = position/2/control.painter.size_z3d; break; - } +/** @summary gausxy function for TFormula + * @memberof Math */ +function gausxy(f, x, y, i) { + return f.GetParValue(i+0) * Math.exp(-0.5 * Math.pow((x-f.GetParValue(i+1)) / f.GetParValue(i+2), 2)) + * Math.exp(-0.5 * Math.pow((y-f.GetParValue(i+3)) / f.GetParValue(i+4), 2)); +} - control.painter.analyzeMouseWheelEvent(evnt, item, position, false); +/** @summary expo function for TFormula + * @memberof Math */ +function expo(f, x, i) { + return Math.exp(f.GetParValue(i+0) + f.GetParValue(i+1) * x); +} - if ((kind === 'z') && intersect.object.use_y_for_z) kind = 'y'; +/** @summary landau function for TFormula + * @memberof Math */ +function landau(f, x, i) { + return Landau(x, f.GetParValue(i+1),f.GetParValue(i+2), false); +} - control.painter.zoom(kind, item.min, item.max); - } - } +/** @summary landaun function for TFormula + * @memberof Math */ +function landaun(f, x, i) { + return Landau(x, f.GetParValue(i+1),f.GetParValue(i+2), true); +} - // assign own handler before creating OrbitControl +/** @summary Crystal ball function + * @memberof Math */ +function crystalball_function(x, alpha, n, sigma, mean = 0) { + if (sigma < 0.) return 0.; + let z = (x - mean)/sigma; + if (alpha < 0) z = -z; + const abs_alpha = Math.abs(alpha); + if (z > -abs_alpha) + return Math.exp(-0.5 * z * z); + const nDivAlpha = n/abs_alpha, + AA = Math.exp(-0.5*abs_alpha*abs_alpha), + B = nDivAlpha - abs_alpha, + arg = nDivAlpha/(B-z); + return AA * Math.pow(arg,n); +} - if (settings.Zooming && settings.ZoomWheel) - renderer.domElement.addEventListener('wheel', control_mousewheel); +/** @summary pdf definition of the crystal_ball which is defined only for n > 1 otherwise integral is diverging + * @memberof Math */ +function crystalball_pdf(x, alpha, n, sigma, mean = 0) { + if (sigma < 0.) return 0.; + if (n <= 1) return Number.NaN; // pdf is not normalized for n <=1 + const abs_alpha = Math.abs(alpha), + C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), + D = Math.sqrt(M_PI/2.)*(1.+erf(abs_alpha/Math.sqrt(2.))), + N = 1./(sigma*(C+D)); + return N * crystalball_function(x,alpha,n,sigma,mean); +} - if (enable_zoom || enable_select) { - renderer.domElement.addEventListener('pointerdown', control_mousedown); - renderer.domElement.addEventListener('pointerup', control_mouseup); - } +/** @summary compute the integral of the crystal ball function + * @memberof Math */ +function crystalball_integral(x, alpha, n, sigma, mean = 0) { + if (sigma == 0) return 0; + if (alpha == 0) return 0.; + const useLog = (n == 1.0), + abs_alpha = Math.abs(alpha); - control = new OrbitControls(camera, renderer.domElement); + let z = (x-mean)/sigma, intgaus = 0., intpow = 0.; + if (alpha < 0 ) z = -z; - control.enableDamping = false; - control.dampingFactor = 1.0; - control.enableZoom = true; - control.enableKeys = settings.HandleKeys; + const sqrtpiover2 = Math.sqrt(M_PI/2.), + sqrt2pi = Math.sqrt( 2.*M_PI), + oneoversqrt2 = 1./Math.sqrt(2.); + if (z <= -abs_alpha) { + const A = Math.pow(n/abs_alpha,n) * Math.exp(-0.5 * alpha*alpha), + B = n/abs_alpha - abs_alpha; - if (lookat) { - control.target.copy(lookat); - control.target0.copy(lookat); - control.update(); + if (!useLog) { + const C = (n/abs_alpha) * (1./(n-1)) * Math.exp(-alpha*alpha/2.); + intpow = C - A /(n-1.) * Math.pow(B-z,-n+1); + } + else { + // for n=1 the primitive of 1/x is log(x) + intpow = -A * Math.log( n / abs_alpha ) + A * Math.log(B - z); + } + intgaus = sqrtpiover2*(1. + erf(abs_alpha*oneoversqrt2)); + } else { + intgaus = normal_cdf_c(z, 1); + intgaus *= sqrt2pi; + intpow = 0; } + return sigma * (intgaus + intpow); +} - control.tooltip = new TooltipFor3D(painter.selectDom().node(), renderer.domElement); +/** @summary crystalball_cdf function + * @memberof Math */ +function crystalball_cdf(x, alpha, n, sigma, mean = 0) { + if (n <= 1.) + return Number.NaN; - control.painter = painter; - control.camera = camera; - control.scene = scene; - control.renderer = renderer; - control.raycaster = new Raycaster(); - control.raycaster.params.Line.threshold = 10; - control.raycaster.params.Points.threshold = 5; - control.mouse_zoom_mesh = null; // zoom mesh, currently used in the zooming - control.block_ctxt = false; // require to block context menu command appearing after control ends, required in chrome which inject contextmenu when key released - control.block_mousemove = false; // when true, tooltip or cursor will not react on mouse move - control.cursor_changed = false; - control.control_changed = false; - control.control_active = false; - control.mouse_ctxt = { x:0, y: 0, on: false }; - control.enable_zoom = enable_zoom; - control.enable_select = enable_select; + const abs_alpha = Math.abs(alpha), + C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), + D = Math.sqrt(M_PI/2.)*(1. + erf(abs_alpha/Math.sqrt(2.))), + totIntegral = sigma*(C+D), + integral = crystalball_integral(x,alpha,n,sigma,mean); - control.cleanup = function() { - if (settings.Zooming && settings.ZoomWheel) - this.domElement.removeEventListener('wheel', control_mousewheel); - if (this.enable_zoom || this.enable_select) { - this.domElement.removeEventListener('pointerdown', control_mousedown); - this.domElement.removeEventListener('pointerup', control_mouseup); - } + return (alpha > 0) ? 1. - integral/totIntegral : integral/totIntegral; +} - this.domElement.removeEventListener('click', this.lstn_click); - this.domElement.removeEventListener('dblclick', this.lstn_dblclick); - this.domElement.removeEventListener('contextmenu', this.lstn_contextmenu); - this.domElement.removeEventListener('mousemove', this.lstn_mousemove); - this.domElement.removeEventListener('mouseleave', this.lstn_mouseleave); +/** @summary crystalball_cdf_c function + * @memberof Math */ +function crystalball_cdf_c(x, alpha, n, sigma, mean = 0) { + if (n <= 1.) + return Number.NaN; - this.dispose(); // this is from OrbitControl itself + const abs_alpha = Math.abs(alpha), + C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), + D = Math.sqrt(M_PI/2.)*(1. + erf(abs_alpha/Math.sqrt(2.))), + totIntegral = sigma*(C+D), + integral = crystalball_integral(x,alpha,n,sigma,mean); - this.tooltip.hide(); - delete this.tooltip; - delete this.painter; - delete this.camera; - delete this.scene; - delete this.renderer; - delete this.raycaster; - delete this.mouse_zoom_mesh; - }; + return (alpha > 0) ? integral/totIntegral : 1. - (integral/totIntegral); +} - control.HideTooltip = function() { - this.tooltip.hide(); - }; +/** @summary ChebyshevN function + * @memberof Math */ +function ChebyshevN(n, x, c) { + let d1 = 0.0, d2 = 0.0; + const y2 = 2.0 * x; - control.getMousePos = function(evnt, mouse) { - mouse.x = ('offsetX' in evnt) ? evnt.offsetX : evnt.layerX; - mouse.y = ('offsetY' in evnt) ? evnt.offsetY : evnt.layerY; - mouse.clientX = evnt.clientX; - mouse.clientY = evnt.clientY; - return mouse; - }; + for (let i = n; i >= 1; i--) { + const temp = d1; + d1 = y2 * d1 - d2 + c[i]; + d2 = temp; + } - control.getOriginDirectionIntersects = function(origin, direction) { - this.raycaster.set(origin, direction); - let intersects = this.raycaster.intersectObjects(this.scene.children, true); - // painter may want to filter intersects - if (isFunc(this.painter.filterIntersects)) - intersects = this.painter.filterIntersects(intersects); - return intersects; - }; + return x * d1 - d2 + c[0]; +} - control.getMouseIntersects = function(mouse) { - // domElement gives correct coordinate with canvas render, but isn't always right for webgl renderer - if (!this.renderer) return []; +/** @summary Chebyshev0 function + * @memberof Math */ +function Chebyshev0(x, c0) { + return c0; +} - let sz = (this.renderer instanceof WebGLRenderer) ? this.renderer.getSize(new Vector2()) : this.renderer.domElement, - pnt = { x: mouse.x / sz.width * 2 - 1, y: -mouse.y / sz.height * 2 + 1 }; +/** @summary Chebyshev1 function + * @memberof Math */ +function Chebyshev1(x, c0, c1) { + return c0 + c1*x; +} - this.camera.updateMatrix(); - this.camera.updateMatrixWorld(); - this.raycaster.setFromCamera( pnt, this.camera ); - let intersects = this.raycaster.intersectObjects(this.scene.children, true); +/** @summary Chebyshev2 function + * @memberof Math */ +function Chebyshev2(x, c0, c1, c2) { + return c0 + c1*x + c2*(2.0*x*x - 1.0); +} - // painter may want to filter intersects - if (isFunc(this.painter.filterIntersects)) - intersects = this.painter.filterIntersects(intersects); +/** @summary Chebyshev3 function + * @memberof Math */ +function Chebyshev3(x, ...args) { + return ChebyshevN(3, x, args); +} - return intersects; - }; +/** @summary Chebyshev4 function + * @memberof Math */ +function Chebyshev4(x, ...args) { + return ChebyshevN(4, x, args); +} - control.detectZoomMesh = function(evnt) { - let mouse = this.getMousePos(evnt, {}), - intersects = this.getMouseIntersects(mouse); - if (intersects) - for (let n = 0; n < intersects.length; ++n) - if (intersects[n].object.zoom) - return intersects[n]; +/** @summary Chebyshev5 function + * @memberof Math */ +function Chebyshev5(x, ...args) { + return ChebyshevN(5, x, args); +} - return null; - }; +/** @summary Chebyshev6 function + * @memberof Math */ +function Chebyshev6(x, ...args) { + return ChebyshevN(6, x, args); +} - control.getInfoAtMousePosition = function(mouse_pos) { - let intersects = this.getMouseIntersects(mouse_pos), - tip = null, painter = null; +/** @summary Chebyshev7 function + * @memberof Math */ +function Chebyshev7(x, ...args) { + return ChebyshevN(7, x, args); +} - for (let i = 0; i < intersects.length; ++i) - if (intersects[i].object.tooltip) { - tip = intersects[i].object.tooltip(intersects[i]); - painter = intersects[i].object.painter; - break; - } +/** @summary Chebyshev8 function + * @memberof Math */ +function Chebyshev8(x, ...args) { + return ChebyshevN(8, x, args); +} - if (tip && painter) - return { obj: painter.getObject(), name: painter.getObject().fName, - bin: tip.bin, cont: tip.value, - binx: tip.ix, biny: tip.iy, binz: tip.iz, - grx: (tip.x1+tip.x2)/2, gry: (tip.y1+tip.y2)/2, grz: (tip.z1+tip.z2)/2 }; - }; +/** @summary Chebyshev9 function + * @memberof Math */ +function Chebyshev9(x, ...args) { + return ChebyshevN(9, x, args); +} - control.processDblClick = function(evnt) { - // first check if zoom mesh clicked - let zoom_intersect = this.detectZoomMesh(evnt); - if (zoom_intersect && this.painter) { - this.painter.unzoom(zoom_intersect.object.use_y_for_z ? 'y' : zoom_intersect.object.zoom); - return; - } +/** @summary Chebyshev10 function + * @memberof Math */ +function Chebyshev10(x, ...args) { + return ChebyshevN(10, x, args); +} - // then check if double-click handler assigned - let fp = this.painter ? this.painter.getFramePainter() : null; - if (isFunc(fp?._dblclick_handler)) { - let info = this.getInfoAtMousePosition(this.getMousePos(evnt, {})); - if (info) { - fp._dblclick_handler(info); - return; - } - } +// ========================================================================= - this.reset(); - }; +/** @summary Caluclate ClopperPearson + * @memberof Math */ +function eff_ClopperPearson(total,passed,level,bUpper) { + const alpha = (1.0 - level) / 2; + if (bUpper) + return ((passed == total) ? 1.0 : beta_quantile(1 - alpha,passed + 1,total-passed)); - control.changeEvent = function() { - this.mouse_ctxt.on = false; // disable context menu if any changes where done by orbit control - this.painter.render3D(0); - this.control_changed = true; - }; + return ((passed == 0) ? 0.0 : beta_quantile(alpha,passed,total-passed+1.0)); +} - control.startEvent = function() { - this.control_active = true; - this.block_ctxt = false; - this.mouse_ctxt.on = false; +/** @summary Caluclate normal + * @memberof Math */ +function eff_Normal(total,passed,level,bUpper) { + if (total == 0) return bUpper ? 1 : 0; - this.tooltip.hide(); + const alpha = (1.0 - level)/2, + average = passed / total, + sigma = Math.sqrt(average * (1 - average) / total), + delta = normal_quantile(1 - alpha, sigma); - // do not reset here, problem of events sequence in orbitcontrol - // it issue change/start/stop event when do zooming - // control.control_changed = false; - }; + if (bUpper) + return ((average + delta) > 1) ? 1.0 : (average + delta); - control.endEvent = function() { - this.control_active = false; - if (this.mouse_ctxt.on) { - this.mouse_ctxt.on = false; - this.contextMenu(this.mouse_ctxt, this.getMouseIntersects(this.mouse_ctxt)); - } /* else if (this.control_changed) { - // react on camera change when required - } */ - this.control_changed = false; - }; + return ((average - delta) < 0) ? 0.0 : (average - delta); +} - control.mainProcessContextMenu = function(evnt) { - evnt.preventDefault(); - this.getMousePos(evnt, this.mouse_ctxt); - if (this.control_active) - this.mouse_ctxt.on = true; - else if (this.block_ctxt) - this.block_ctxt = false; - else - this.contextMenu(this.mouse_ctxt, this.getMouseIntersects(this.mouse_ctxt)); - }; +/** @summary Calculates the boundaries for the frequentist Wilson interval + * @memberof Math */ +function eff_Wilson(total,passed,level,bUpper) { + const alpha = (1.0 - level)/2; + if (total == 0) return bUpper ? 1 : 0; + const average = passed / total, + kappa = normal_quantile(1 - alpha,1), + mode = (passed + 0.5 * kappa * kappa) / (total + kappa * kappa), + delta = kappa / (total + kappa*kappa) * Math.sqrt(total * average * (1 - average) + kappa * kappa / 4); - control.contextMenu = function(/* pos, intersects */) { - // do nothing, function called when context menu want to be activated - }; + if (bUpper) + return ((mode + delta) > 1) ? 1.0 : (mode + delta); - control.setTooltipEnabled = function(on) { - this.block_mousemove = !on; - if (on === false) { - this.tooltip.hide(); - this.removeZoomMesh(); - } - }; + return ((mode - delta) < 0) ? 0.0 : (mode - delta); +} - control.removeZoomMesh = function() { - if (this.mouse_zoom_mesh && this.mouse_zoom_mesh.object.showSelection()) - this.painter.render3D(); - this.mouse_zoom_mesh = null; // in any case clear mesh, enable orbit control again - }; +/** @summary Calculates the boundaries for the frequentist Agresti-Coull interval + * @memberof Math */ +function eff_AgrestiCoull(total,passed,level,bUpper) { + const alpha = (1.0 - level)/2, + kappa = normal_quantile(1 - alpha,1), + mode = (passed + 0.5 * kappa * kappa) / (total + kappa * kappa), + delta = kappa * Math.sqrt(mode * (1 - mode) / (total + kappa * kappa)); - control.mainProcessMouseMove = function(evnt) { - if (!this.painter) return; // protect when cleanup + if (bUpper) + return ((mode + delta) > 1) ? 1.0 : (mode + delta); - if (this.control_active && evnt.buttons && (evnt.buttons & 2)) - this.block_ctxt = true; // if right button in control was active, block next context menu + return ((mode - delta) < 0) ? 0.0 : (mode - delta); +} - if (this.control_active || this.block_mousemove || !this.processMouseMove) return; +/** @summary Calculates the boundaries using the mid-P binomial + * @memberof Math */ +function eff_MidPInterval(total,passed,level,bUpper) { + const alpha = 1. - level, alpha_min = alpha/2 , tol = 1e-9; // tolerance + let pmin = 0, pmax = 1, p = 0; - if (this.mouse_zoom_mesh) { - // when working with zoom mesh, need special handling + // treat special case for 0 0 && passed < 1) { + const p0 = eff_MidPInterval(total, 0.0, level, bUpper), + p1 = eff_MidPInterval(total, 1.0, level, bUpper); + p = (p1 - p0) * passed + p0; + return p; + } - let zoom2 = this.detectZoomMesh(evnt), - pnt2 = (zoom2?.object === this.mouse_zoom_mesh.object) ? zoom2.point : this.mouse_zoom_mesh.object.globalIntersect(this.raycaster); + while (Math.abs(pmax - pmin) > tol) { + p = (pmin + pmax)/2; + // double v = 0.5 * ROOT::Math::binomial_pdf(int(passed), p, int(total)); + // make it work for non integer using the binomial - beta relationship + let v = 0.5 * beta_pdf(p, passed+1., total-passed+1)/(total+1); + // if (passed > 0) v += ROOT::Math::binomial_cdf(int(passed - 1), p, int(total)); + // compute the binomial cdf at passed -1 + if ( (passed-1) >= 0) v += beta_cdf_c(p, passed, total-passed+1); - if (pnt2) this.mouse_zoom_mesh.point2 = pnt2; + const vmin = bUpper ? alpha_min : 1.- alpha_min; + if (v > vmin) + pmin = p; + else + pmax = p; + } - if (pnt2 && this.painter.enable_highlight) - if (this.mouse_zoom_mesh.object.showSelection(this.mouse_zoom_mesh.point, pnt2)) - this.painter.render3D(0); + return p; +} - this.tooltip.hide(); - return; - } +/** @summary for a central confidence interval for a Beta distribution + * @memberof Math */ +function eff_Bayesian(total,passed,level,bUpper,alpha,beta) { + const a = passed + alpha, + b = total - passed + beta; + if (bUpper) { + if ((a > 0) && (b > 0)) + return beta_quantile((1+level)/2,a,b); + else + return 1; + } else { + if ((a > 0) && (b > 0)) + return beta_quantile((1-level)/2,a,b); + else + return 0; + } +} - evnt.preventDefault(); +/** @summary Return function to calculate boundary of TEfficiency + * @memberof Math */ +function getTEfficiencyBoundaryFunc(option, isbayessian) { + const kFCP = 0, // Clopper-Pearson interval (recommended by PDG) + kFNormal = 1, // Normal approximation + kFWilson = 2, // Wilson interval + kFAC = 3, // Agresti-Coull interval + kFFC = 4, // Feldman-Cousins interval, too complicated for JavaScript + // kBJeffrey = 5, // Jeffrey interval (Prior ~ Beta(0.5,0.5) + // kBUniform = 6, // Prior ~ Uniform = Beta(1,1) + // kBBayesian = 7, // User specified Prior ~ Beta(fBeta_alpha,fBeta_beta) + kMidP = 8; // Mid-P Lancaster interval - // extract mouse position - this.tmout_mouse = this.getMousePos(evnt, {}); - this.tmout_ttpos = this.tooltip ? this.tooltip.extract_pos(evnt) : null; + if (isbayessian) + return eff_Bayesian; - if (this.tmout_handle) { - clearTimeout(this.tmout_handle); - delete this.tmout_handle; - } + switch (option) { + case kFCP: return eff_ClopperPearson; + case kFNormal: return eff_Normal; + case kFWilson: return eff_Wilson; + case kFAC: return eff_AgrestiCoull; + case kFFC: console.log('Feldman-Cousins interval kFFC not supported; using kFCP'); return eff_ClopperPearson; + case kMidP: return eff_MidPInterval; + // case kBJeffrey: + // case kBUniform: + // case kBBayesian: return eff_ClopperPearson; + } + console.log(`Not recognized stat option ${option}, using kFCP`); + return eff_ClopperPearson; +} - if (!this.mouse_tmout) - this.delayedProcessMouseMove(); - else - this.tmout_handle = setTimeout(() => this.delayedProcessMouseMove(), this.mouse_tmout); - }; +var jsroot_math = /*#__PURE__*/Object.freeze({ +__proto__: null, +Beta: Beta, +BetaDist: BetaDist, +BetaDistI: BetaDistI, +BetaIncomplete: BetaIncomplete, +BreitWigner: BreitWigner, +Chebyshev0: Chebyshev0, +Chebyshev1: Chebyshev1, +Chebyshev10: Chebyshev10, +Chebyshev2: Chebyshev2, +Chebyshev3: Chebyshev3, +Chebyshev4: Chebyshev4, +Chebyshev5: Chebyshev5, +Chebyshev6: Chebyshev6, +Chebyshev7: Chebyshev7, +Chebyshev8: Chebyshev8, +Chebyshev9: Chebyshev9, +ChebyshevN: ChebyshevN, +FDist: fdistribution_pdf, +FDistI: fdistribution_cdf, +Gamma: gamma, +GammaDist: GammaDist, +Gaus: Gaus, +Landau: Landau, +LaplaceDist: LaplaceDist, +LaplaceDistI: LaplaceDistI, +LogNormal: LogNormal, +Polynomial1eval: Polynomial1eval, +Polynomialeval: Polynomialeval, +Prob: Prob, +Student: Student, +StudentI: StudentI, +beta: beta, +beta_cdf_c: beta_cdf_c, +beta_pdf: beta_pdf, +beta_quantile: beta_quantile, +breitwigner_cdf: breitwigner_cdf, +breitwigner_cdf_c: breitwigner_cdf_c, +cauchy_cdf: cauchy_cdf, +cauchy_cdf_c: cauchy_cdf_c, +cauchy_pdf: cauchy_pdf, +chisquared_cdf: chisquared_cdf, +chisquared_cdf_c: chisquared_cdf_c, +chisquared_pdf: chisquared_pdf, +crystalball_cdf: crystalball_cdf, +crystalball_cdf_c: crystalball_cdf_c, +crystalball_function: crystalball_function, +crystalball_pdf: crystalball_pdf, +erf: erf, +erfc: erfc, +expo: expo, +exponential_cdf: exponential_cdf, +exponential_cdf_c: exponential_cdf_c, +fdistribution_cdf: fdistribution_cdf, +fdistribution_cdf_c: fdistribution_cdf_c, +fdistribution_pdf: fdistribution_pdf, +gamma: gamma, +gamma_pdf: gamma_pdf, +gamma_quantile: gamma_quantile, +gamma_quantile_c: gamma_quantile_c, +gaus: gaus, +gausn: gausn, +gaussian_cdf: normal_cdf, +gaussian_cdf_c: normal_cdf_c, +gaussian_pdf: gaussian_pdf, +gausxy: gausxy, +getTEfficiencyBoundaryFunc: getTEfficiencyBoundaryFunc, +igam: igam, +igamc: igamc, +igami: igami, +inc_beta: inc_beta, +inc_gamma: inc_gamma, +inc_gamma_c: inc_gamma_c, +incbet: incbet, +incbi: incbi, +landau: landau, +landau_pdf: landau_pdf, +landaun: landaun, +lgam: lgam, +lgamma: lgamma, +lognormal_cdf: lognormal_cdf, +lognormal_cdf_c: lognormal_cdf_c, +lognormal_pdf: lognormal_pdf, +ndtri: ndtri, +normal_cdf: normal_cdf, +normal_cdf_c: normal_cdf_c, +normal_pdf: normal_pdf, +normal_quantile: normal_quantile, +normal_quantile_c: normal_quantile_c, +pseries: pseries, +stirf: stirf, +tdistribution_cdf: tdistribution_cdf, +tdistribution_cdf_c: tdistribution_cdf_c, +tdistribution_pdf: tdistribution_pdf, +tgamma: gamma +}); - control.delayedProcessMouseMove = function() { - // remove handle - allow to trigger new timeout - delete this.tmout_handle; - if (!this.painter) return; // protect when cleanup +/** @summary Display progress message in the left bottom corner. + * @desc Previous message will be overwritten + * if no argument specified, any shown messages will be removed + * @param {string} msg - message to display + * @param {number} tmout - optional timeout in milliseconds, after message will disappear + * @private */ +function showProgress(msg, tmout) { + if (isBatchMode() || (typeof document === 'undefined')) + return; + const id = 'jsroot_progressbox'; + let box = select('#' + id); - let mouse = this.tmout_mouse, - intersects = this.getMouseIntersects(mouse), - tip = this.processMouseMove(intersects); + if (!settings.ProgressBox) + return box.remove(); - if (tip) { - let name = '', title = '', coord = '', info = ''; - if (mouse) coord = mouse.x.toFixed(0) + ',' + mouse.y.toFixed(0); - if (isStr(tip)) { - info = tip; - } else { - name = tip.name; title = tip.title; - if (tip.line) info = tip.line; else - if (tip.lines) { info = tip.lines.slice(1).join(' '); name = tip.lines[0]; } - } - this.painter.showObjectStatus(name, title, info, coord); - } + if ((arguments.length === 0) || !msg) { + if ((tmout !== -1) || (!box.empty() && box.property('with_timeout'))) box.remove(); + return; + } - this.cursor_changed = false; - if (tip && this.painter?.isTooltipAllowed()) { - this.tooltip.checkParent(this.painter.selectDom().node()); + if (box.empty()) { + box = select(document.body) + .append('div').attr('id', id) + .attr('style', 'position: fixed; min-width: 100px; height: auto; overflow: visible; z-index: 101; border: 1px solid #999; background: #F8F8F8; left: 10px; bottom: 10px;'); + box.append('p'); + } - this.tooltip.show(tip, mouse); - this.tooltip.pos(this.tmout_ttpos); - } else { - this.tooltip.hide(); - if (intersects) - for (let n = 0; n < intersects.length; ++n) - if (intersects[n].object.zoom) this.cursor_changed = true; - } + box.property('with_timeout', false); - document.body.style.cursor = this.cursor_changed ? 'pointer' : 'auto'; - }; + if (isStr(msg)) + box.select('p').html(msg); + else { + box.html(''); + box.node().appendChild(msg); + } - control.mainProcessMouseLeave = function() { - if (!this.painter) return; // protect when cleanup + box.select('p').attr('style', 'font-size: 10px; margin-left: 10px; margin-right: 10px; margin-top: 3px; margin-bottom: 3px'); - // do not enter main event at all - if (this.tmout_handle) { - clearTimeout(this.tmout_handle); - delete this.tmout_handle; - } - this.tooltip.hide(); - if (isFunc(this.processMouseLeave)) - this.processMouseLeave(); - if (this.cursor_changed) { - document.body.style.cursor = 'auto'; - this.cursor_changed = false; - } - }; + if (Number.isFinite(tmout) && (tmout > 0)) { + box.property('with_timeout', true); + setTimeout(() => showProgress('', -1), tmout); + } +} - control.mainProcessDblClick = function(evnt) { - // suppress simple click handler if double click detected - if (this.single_click_tm) { - clearTimeout(this.single_click_tm); - delete this.single_click_tm; +/** @summary Tries to close current browser tab + * @desc Many browsers do not allow simple window.close() call, + * therefore try several workarounds + * @private */ +function closeCurrentWindow() { + if (!window) return; + window.close(); + window.open('', '_self').close(); +} + +/** @summary Tries to open ui5 + * @private */ +function tryOpenOpenUI(sources, args) { + if (!sources || (sources.length === 0)) { + if (isFunc(args.rejectFunc)) { + args.rejectFunc(Error('openui5 was not possible to load')); + args.rejectFunc = null; } - this.processDblClick(evnt); - }; + return; + } - control.processClick = function(mouse_pos, kind) { - delete this.single_click_tm; + // where to take openui5 sources + let src = sources.shift(); - if (kind == 1) { - let fp = this.painter ? this.painter.getFramePainter() : null; - if (isFunc(fp?._click_handler)) { - let info = this.getInfoAtMousePosition(mouse_pos); - if (info) { - fp._click_handler(info); - return; - } - } - } + if ((src.indexOf('roothandler') === 0) && (src.indexOf('://') < 0)) + src = src.replace(/:\//g, '://'); - // method assigned in the Eve7 and used for object selection - if ((kind == 2) && isFunc(this.processSingleClick)) { - let intersects = this.getMouseIntersects(mouse_pos); - this.processSingleClick(intersects); - } - }; + const element = document.createElement('script'); + element.setAttribute('type', 'text/javascript'); + element.setAttribute('id', 'sap-ui-bootstrap'); + // use nojQuery while we are already load jquery and jquery-ui, later one can use directly sap-ui-core.js - control.lstn_click = function(evnt) { - // ignore right-mouse click - if (evnt.detail == 2) return; + // this is location of openui5 scripts when working with THttpServer or when scripts are installed inside JSROOT + element.setAttribute('src', src + (args.ui5dbg ? 'resources/sap-ui-core-dbg.js' : 'resources/sap-ui-core.js')); // latest openui5 version - if (this.single_click_tm) { - clearTimeout(this.single_click_tm); - delete this.single_click_tm; - } + element.setAttribute('data-sap-ui-libs', args.openui5libs ?? 'sap.m, sap.ui.layout, sap.ui.unified, sap.ui.commons'); - let kind = 0, fp = this.painter?.getFramePainter(); - if (isFunc(fp?._click_handler)) - kind = 1; // user click handler - else if (this.processSingleClick && this.painter?.options?.mouse_click) - kind = 2; // eve7 click handler + element.setAttribute('data-sap-ui-theme', args.openui5theme || 'sap_belize'); + element.setAttribute('data-sap-ui-compatVersion', 'edge'); + element.setAttribute('data-sap-ui-async', 'true'); + // element.setAttribute('data-sap-ui-bindingSyntax', 'complex'); - // if normal event, set longer timeout waiting if double click not detected - if (kind) - this.single_click_tm = setTimeout(this.processClick.bind(this, this.getMousePos(evnt, {}), kind), 300); - }.bind(control); + element.setAttribute('data-sap-ui-preload', 'async'); // '' to disable Component-preload.js - control.addEventListener('change', () => control.changeEvent()); - control.addEventListener('start', () => control.startEvent()); - control.addEventListener('end', () => control.endEvent()); + element.setAttribute('data-sap-ui-evt-oninit', 'completeUI5Loading()'); - control.lstn_contextmenu = evnt => control.mainProcessContextMenu(evnt); - control.lstn_dblclick = evnt => control.mainProcessDblClick(evnt); - control.lstn_mousemove = evnt => control.mainProcessMouseMove(evnt); - control.lstn_mouseleave = () => control.mainProcessMouseLeave(); + element.onerror = function() { + // remove failed element + element.parentNode.removeChild(element); + // and try next + tryOpenOpenUI(sources, args); + }; - renderer.domElement.addEventListener('click', control.lstn_click); - renderer.domElement.addEventListener('dblclick', control.lstn_dblclick); - renderer.domElement.addEventListener('contextmenu', control.lstn_contextmenu); - renderer.domElement.addEventListener('mousemove', control.lstn_mousemove); - renderer.domElement.addEventListener('mouseleave', control.lstn_mouseleave); + element.onload = function() { + console.log(`Load openui5 from ${src}`); + }; - return control; + document.head.appendChild(element); } -/** @summary Method cleanup three.js object as much as possible. - * @desc Simplify JS engine to remove it from memory + +/** @summary load openui5 + * @return {Promise} for loading ready * @private */ -function disposeThreejsObject(obj, only_childs) { - if (!obj) return; +async function loadOpenui5(args) { + // very simple - openui5 was loaded before and will be used as is + if (typeof globalThis.sap === 'object') + return globalThis.sap; - if (obj.children) { - for (let i = 0; i < obj.children.length; i++) - disposeThreejsObject(obj.children[i]); - } + if (!args) args = {}; - if (only_childs) { - obj.children = []; - return; + let rootui5sys = exports.source_dir.replace(/jsrootsys/g, 'rootui5sys'); + + if (rootui5sys === exports.source_dir) { + // if jsrootsys location not detected, try to guess it + if (window.location.port && (window.location.pathname.indexOf('/win') >= 0) && (!args.openui5src || args.openui5src === 'nojsroot' || args.openui5src === 'jsroot')) + rootui5sys = window.location.origin + window.location.pathname + '../rootui5sys/'; + else + rootui5sys = undefined; } - obj.children = undefined; + const openui5_sources = []; + let openui5_dflt = 'https://openui5.hana.ondemand.com/1.98.0/', + openui5_root = rootui5sys ? rootui5sys + 'distribution/' : ''; - if (obj.geometry) { - obj.geometry.dispose(); - obj.geometry = undefined; - } - if (obj.material) { - if (obj.material.map) { - obj.material.map.dispose(); - obj.material.map = undefined; + if (isStr(args.openui5src)) { + switch (args.openui5src) { + case 'nodefault': openui5_dflt = ''; break; + case 'default': openui5_sources.push(openui5_dflt); openui5_dflt = ''; break; + case 'nojsroot': /* openui5_root = ''; */ break; + case 'jsroot': openui5_sources.push(openui5_root); openui5_root = ''; break; + default: openui5_sources.push(args.openui5src); break; } - obj.material.dispose(); - obj.material = undefined; - } - - // cleanup jsroot fields to simplify browser cleanup job - delete obj.painter; - delete obj.bins_index; - delete obj.tooltip; - delete obj.stack; // used in geom painter - delete obj.drawn_highlight; // special highlight object + } else if (args.ui5dbg) + openui5_root = ''; // exclude ROOT version in debug mode - obj = undefined; -} + if (openui5_root && (openui5_sources.indexOf(openui5_root) < 0)) + openui5_sources.push(openui5_root); + if (openui5_dflt && (openui5_sources.indexOf(openui5_dflt) < 0)) + openui5_sources.push(openui5_dflt); + return new Promise((resolve, reject) => { + args.resolveFunc = resolve; + args.rejectFunc = reject; -/** @summary Create LineSegments mesh (or only geometry) - * @desc If required, calculates lineDistance attribute for dashed geometries - * @private */ -function createLineSegments(arr, material, index = undefined, only_geometry = false) { + globalThis.completeUI5Loading = function() { + globalThis.sap.ui.loader.config({ + paths: { + jsroot: exports.source_dir, + rootui5: rootui5sys + } + }); - let geom = new BufferGeometry(); + if (args.resolveFunc) { + args.resolveFunc(globalThis.sap); + args.resolveFunc = null; + } + }; - geom.setAttribute('position', arr instanceof Float32Array ? new BufferAttribute(arr, 3) : new Float32BufferAttribute(arr, 3)); - if (index) geom.setIndex(new BufferAttribute(index, 1)); + tryOpenOpenUI(openui5_sources, args); + }); +} - if (material.isLineDashedMaterial) { +/* eslint-disable key-spacing */ +/* eslint-disable comma-spacing */ +/* eslint-disable object-curly-spacing */ - let v1 = new Vector3(), - v2 = new Vector3(), - d = 0, distances = null; +// some icons taken from http://uxrepo.com/ +const ToolbarIcons = { + camera: { path: 'M 152.00,304.00c0.00,57.438, 46.562,104.00, 104.00,104.00s 104.00-46.562, 104.00-104.00s-46.562-104.00-104.00-104.00S 152.00,246.562, 152.00,304.00z M 480.00,128.00L 368.00,128.00 c-8.00-32.00-16.00-64.00-48.00-64.00L 192.00,64.00 c-32.00,0.00-40.00,32.00-48.00,64.00L 32.00,128.00 c-17.60,0.00-32.00,14.40-32.00,32.00l0.00,288.00 c0.00,17.60, 14.40,32.00, 32.00,32.00l 448.00,0.00 c 17.60,0.00, 32.00-14.40, 32.00-32.00L 512.00,160.00 C 512.00,142.40, 497.60,128.00, 480.00,128.00z M 256.00,446.00c-78.425,0.00-142.00-63.574-142.00-142.00c0.00-78.425, 63.575-142.00, 142.00-142.00c 78.426,0.00, 142.00,63.575, 142.00,142.00 C 398.00,382.426, 334.427,446.00, 256.00,446.00z M 480.00,224.00l-64.00,0.00 l0.00-32.00 l 64.00,0.00 L 480.00,224.00 z' }, + disk: { path: 'M384,0H128H32C14.336,0,0,14.336,0,32v448c0,17.656,14.336,32,32,32h448c17.656,0,32-14.344,32-32V96L416,0H384z M352,160 V32h32v128c0,17.664-14.344,32-32,32H160c-17.664,0-32-14.336-32-32V32h128v128H352z M96,288c0-17.656,14.336-32,32-32h256 c17.656,0,32,14.344,32,32v192H96V288z' }, + question: { path: 'M256,512c141.375,0,256-114.625,256-256S397.375,0,256,0S0,114.625,0,256S114.625,512,256,512z M256,64 c63.719,0,128,36.484,128,118.016c0,47.453-23.531,84.516-69.891,110.016C300.672,299.422,288,314.047,288,320 c0,17.656-14.344,32-32,32c-17.664,0-32-14.344-32-32c0-40.609,37.25-71.938,59.266-84.031 C315.625,218.109,320,198.656,320,182.016C320,135.008,279.906,128,256,128c-30.812,0-64,20.227-64,64.672 c0,17.664-14.336,32-32,32s-32-14.336-32-32C128,109.086,193.953,64,256,64z M256,449.406c-18.211,0-32.961-14.75-32.961-32.969 c0-18.188,14.75-32.953,32.961-32.953c18.219,0,32.969,14.766,32.969,32.953C288.969,434.656,274.219,449.406,256,449.406z' }, + undo: { path: 'M450.159,48.042c8.791,9.032,16.983,18.898,24.59,29.604c7.594,10.706,14.146,22.207,19.668,34.489 c5.509,12.296,9.82,25.269,12.92,38.938c3.113,13.669,4.663,27.834,4.663,42.499c0,14.256-1.511,28.863-4.532,43.822 c-3.009,14.952-7.997,30.217-14.953,45.795c-6.955,15.577-16.202,31.52-27.755,47.826s-25.88,32.9-42.942,49.807 c-5.51,5.444-11.787,11.67-18.834,18.651c-7.033,6.98-14.496,14.366-22.39,22.168c-7.88,7.802-15.955,15.825-24.187,24.069 c-8.258,8.231-16.333,16.203-24.252,23.888c-18.3,18.13-37.354,37.016-57.191,56.65l-56.84-57.445 c19.596-19.472,38.54-38.279,56.84-56.41c7.75-7.685,15.772-15.604,24.108-23.757s16.438-16.163,24.33-24.057 c7.894-7.893,15.356-15.33,22.402-22.312c7.034-6.98,13.312-13.193,18.821-18.651c22.351-22.402,39.165-44.648,50.471-66.738 c11.279-22.09,16.932-43.567,16.932-64.446c0-15.785-3.217-31.005-9.638-45.671c-6.422-14.665-16.229-28.504-29.437-41.529 c-3.282-3.282-7.358-6.395-12.217-9.325c-4.871-2.938-10.381-5.503-16.516-7.697c-6.121-2.201-12.815-3.992-20.058-5.373 c-7.242-1.374-14.9-2.064-23.002-2.064c-8.218,0-16.802,0.834-25.788,2.507c-8.961,1.674-18.053,4.429-27.222,8.271 c-9.189,3.842-18.456,8.869-27.808,15.089c-9.358,6.219-18.521,13.819-27.502,22.793l-59.92,60.271l93.797,94.058H0V40.91 l93.27,91.597l60.181-60.532c13.376-15.018,27.222-27.248,41.536-36.697c14.308-9.443,28.608-16.776,42.89-21.992 c14.288-5.223,28.505-8.74,42.623-10.557C294.645,0.905,308.189,0,321.162,0c13.429,0,26.389,1.185,38.84,3.562 c12.478,2.377,24.2,5.718,35.192,10.029c11.006,4.311,21.126,9.404,30.374,15.265C434.79,34.724,442.995,41.119,450.159,48.042z' }, + arrow_right: { path: 'M30.796,226.318h377.533L294.938,339.682c-11.899,11.906-11.899,31.184,0,43.084c11.887,11.899,31.19,11.893,43.077,0 l165.393-165.386c5.725-5.712,8.924-13.453,8.924-21.539c0-8.092-3.213-15.84-8.924-21.551L338.016,8.925 C332.065,2.975,324.278,0,316.478,0c-7.802,0-15.603,2.968-21.539,8.918c-11.899,11.906-11.899,31.184,0,43.084l113.391,113.384 H30.796c-16.822,0-30.463,13.645-30.463,30.463C0.333,212.674,13.974,226.318,30.796,226.318z' }, + arrow_up: { path: 'M295.505,629.446V135.957l148.193,148.206c15.555,15.559,40.753,15.559,56.308,0c15.555-15.538,15.546-40.767,0-56.304 L283.83,11.662C276.372,4.204,266.236,0,255.68,0c-10.568,0-20.705,4.204-28.172,11.662L11.333,227.859 c-7.777,7.777-11.666,17.965-11.666,28.158c0,10.192,3.88,20.385,11.657,28.158c15.563,15.555,40.762,15.555,56.317,0 l148.201-148.219v493.489c0,21.993,17.837,39.82,39.82,39.82C277.669,669.267,295.505,651.439,295.505,629.446z' }, + arrow_diag: { path: 'M279.875,511.994c-1.292,0-2.607-0.102-3.924-0.312c-10.944-1.771-19.333-10.676-20.457-21.71L233.97,278.348 L22.345,256.823c-11.029-1.119-19.928-9.51-21.698-20.461c-1.776-10.944,4.031-21.716,14.145-26.262L477.792,2.149 c9.282-4.163,20.167-2.165,27.355,5.024c7.201,7.189,9.199,18.086,5.024,27.356L302.22,497.527 C298.224,506.426,289.397,511.994,279.875,511.994z M118.277,217.332l140.534,14.294c11.567,1.178,20.718,10.335,21.878,21.896 l14.294,140.519l144.09-320.792L118.277,217.332z' }, + auto_zoom: { path: 'M505.441,242.47l-78.303-78.291c-9.18-9.177-24.048-9.171-33.216,0c-9.169,9.172-9.169,24.045,0.006,33.217l38.193,38.188 H280.088V80.194l38.188,38.199c4.587,4.584,10.596,6.881,16.605,6.881c6.003,0,12.018-2.297,16.605-6.875 c9.174-9.172,9.174-24.039,0.011-33.217L273.219,6.881C268.803,2.471,262.834,0,256.596,0c-6.229,0-12.202,2.471-16.605,6.881 l-78.296,78.302c-9.178,9.172-9.178,24.045,0,33.217c9.177,9.171,24.051,9.171,33.21,0l38.205-38.205v155.4H80.521l38.2-38.188 c9.177-9.171,9.177-24.039,0.005-33.216c-9.171-9.172-24.039-9.178-33.216,0L7.208,242.464c-4.404,4.403-6.881,10.381-6.881,16.611 c0,6.227,2.477,12.207,6.881,16.61l78.302,78.291c4.587,4.581,10.599,6.875,16.605,6.875c6.006,0,12.023-2.294,16.61-6.881 c9.172-9.174,9.172-24.036-0.005-33.211l-38.205-38.199h152.593v152.063l-38.199-38.211c-9.171-9.18-24.039-9.18-33.216-0.022 c-9.178,9.18-9.178,24.059-0.006,33.222l78.284,78.302c4.41,4.404,10.382,6.881,16.611,6.881c6.233,0,12.208-2.477,16.611-6.881 l78.302-78.296c9.181-9.18,9.181-24.048,0-33.205c-9.174-9.174-24.054-9.174-33.21,0l-38.199,38.188v-152.04h152.051l-38.205,38.199 c-9.18,9.175-9.18,24.037-0.005,33.211c4.587,4.587,10.596,6.881,16.604,6.881c6.01,0,12.024-2.294,16.605-6.875l78.303-78.285 c4.403-4.403,6.887-10.378,6.887-16.611C512.328,252.851,509.845,246.873,505.441,242.47z' }, + statbox: { + path: 'M28.782,56.902H483.88c15.707,0,28.451-12.74,28.451-28.451C512.331,12.741,499.599,0,483.885,0H28.782 C13.074,0,0.331,12.741,0.331,28.451C0.331,44.162,13.074,56.902,28.782,56.902z' + + 'M483.885,136.845H28.782c-15.708,0-28.451,12.741-28.451,28.451c0,15.711,12.744,28.451,28.451,28.451H483.88 c15.707,0,28.451-12.74,28.451-28.451C512.331,149.586,499.599,136.845,483.885,136.845z' + + 'M483.885,273.275H28.782c-15.708,0-28.451,12.731-28.451,28.452c0,15.707,12.744,28.451,28.451,28.451H483.88 c15.707,0,28.451-12.744,28.451-28.451C512.337,286.007,499.599,273.275,483.885,273.275z' + + 'M256.065,409.704H30.492c-15.708,0-28.451,12.731-28.451,28.451c0,15.707,12.744,28.451,28.451,28.451h225.585 c15.707,0,28.451-12.744,28.451-28.451C284.516,422.436,271.785,409.704,256.065,409.704z' + }, + circle: { path: 'M256,256 m-150,0 a150,150 0 1,0 300,0 a150,150 0 1,0 -300,0' }, + three_circles: { path: 'M256,85 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 M256,255 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 M256,425 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 ' }, + diamand: { path: 'M256,0L384,256L256,511L128,256z' }, + rect: { path: 'M90,90h352v352h-352z' }, + cross: { path: 'M80,40l176,176l176,-176l40,40l-176,176l176,176l-40,40l-176,-176l-176,176l-40,-40l176,-176l-176,-176z' }, + vrgoggles: { size: '245.82 141.73', path: 'M175.56,111.37c-22.52,0-40.77-18.84-40.77-42.07S153,27.24,175.56,27.24s40.77,18.84,40.77,42.07S198.08,111.37,175.56,111.37ZM26.84,69.31c0-23.23,18.25-42.07,40.77-42.07s40.77,18.84,40.77,42.07-18.26,42.07-40.77,42.07S26.84,92.54,26.84,69.31ZM27.27,0C11.54,0,0,12.34,0,28.58V110.9c0,16.24,11.54,30.83,27.27,30.83H99.57c2.17,0,4.19-1.83,5.4-3.7L116.47,118a8,8,0,0,1,12.52-.18l11.51,20.34c1.2,1.86,3.22,3.61,5.39,3.61h72.29c15.74,0,27.63-14.6,27.63-30.83V28.58C245.82,12.34,233.93,0,218.19,0H27.27Z' }, + th2colorz: { recs: [{ x: 128, y: 486, w: 256, h: 26, f: 'rgb(38,62,168)' }, { y: 461, f: 'rgb(22,82,205)' }, { y: 435, f: 'rgb(16,100,220)' }, { y: 410, f: 'rgb(18,114,217)' }, { y: 384, f: 'rgb(20,129,214)' }, { y: 358, f: 'rgb(14,143,209)' }, { y: 333, f: 'rgb(9,157,204)' }, { y: 307, f: 'rgb(13,167,195)' }, { y: 282, f: 'rgb(30,175,179)' }, { y: 256, f: 'rgb(46,183,164)' }, { y: 230, f: 'rgb(82,186,146)' }, { y: 205, f: 'rgb(116,189,129)' }, { y: 179, f: 'rgb(149,190,113)' }, { y: 154, f: 'rgb(179,189,101)' }, { y: 128, f: 'rgb(209,187,89)' }, { y: 102, f: 'rgb(226,192,75)' }, { y: 77, f: 'rgb(244,198,59)' }, { y: 51, f: 'rgb(253,210,43)' }, { y: 26, f: 'rgb(251,230,29)' }, { y: 0, f: 'rgb(249,249,15)' }] }, + th2color: { recs: [{x:0,y:256,w:13,h:39,f:'rgb(38,62,168)'},{x:13,y:371,w:39,h:39},{y:294,h:39},{y:256,h:39},{y:218,h:39},{x:51,y:410,w:39,h:39},{y:371,h:39},{y:333,h:39},{y:294},{y:256,h:39},{y:218,h:39},{y:179,h:39},{y:141,h:39},{y:102,h:39},{y:64},{x:90,y:448,w:39,h:39},{y:410},{y:371,h:39},{y:333,h:39,f:'rgb(22,82,205)'},{y:294},{y:256,h:39,f:'rgb(16,100,220)'},{y:218,h:39},{y:179,h:39,f:'rgb(22,82,205)'},{y:141,h:39},{y:102,h:39,f:'rgb(38,62,168)'},{y:64},{y:0,h:27},{x:128,y:448,w:39,h:39},{y:410},{y:371,h:39},{y:333,h:39,f:'rgb(22,82,205)'},{y:294,f:'rgb(20,129,214)'},{y:256,h:39,f:'rgb(9,157,204)'},{y:218,h:39,f:'rgb(14,143,209)'},{y:179,h:39,f:'rgb(20,129,214)'},{y:141,h:39,f:'rgb(16,100,220)'},{y:102,h:39,f:'rgb(22,82,205)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{y:0,h:27},{x:166,y:486,h:14},{y:448,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39,f:'rgb(20,129,214)'},{y:294,f:'rgb(82,186,146)'},{y:256,h:39,f:'rgb(179,189,101)'},{y:218,h:39,f:'rgb(116,189,129)'},{y:179,h:39,f:'rgb(82,186,146)'},{y:141,h:39,f:'rgb(14,143,209)'},{y:102,h:39,f:'rgb(16,100,220)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:205,y:486,w:39,h:14},{y:448,h:39},{y:410},{y:371,h:39,f:'rgb(16,100,220)'},{y:333,h:39,f:'rgb(9,157,204)'},{y:294,f:'rgb(149,190,113)'},{y:256,h:39,f:'rgb(244,198,59)'},{y:218,h:39},{y:179,h:39,f:'rgb(226,192,75)'},{y:141,h:39,f:'rgb(13,167,195)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(22,82,205)'},{y:26,h:39,f:'rgb(38,62,168)'},{x:243,y:448,w:39,h:39},{y:410},{y:371,h:39,f:'rgb(18,114,217)'},{y:333,h:39,f:'rgb(30,175,179)'},{y:294,f:'rgb(209,187,89)'},{y:256,h:39,f:'rgb(251,230,29)'},{y:218,h:39,f:'rgb(249,249,15)'},{y:179,h:39,f:'rgb(226,192,75)'},{y:141,h:39,f:'rgb(30,175,179)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:282,y:448,h:39},{y:410},{y:371,h:39,f:'rgb(18,114,217)'},{y:333,h:39,f:'rgb(14,143,209)'},{y:294,f:'rgb(149,190,113)'},{y:256,h:39,f:'rgb(226,192,75)'},{y:218,h:39,f:'rgb(244,198,59)'},{y:179,h:39,f:'rgb(149,190,113)'},{y:141,h:39,f:'rgb(9,157,204)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:320,y:448,w:39,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39,f:'rgb(20,129,214)'},{y:294,f:'rgb(46,183,164)'},{y:256,h:39},{y:218,h:39,f:'rgb(82,186,146)'},{y:179,h:39,f:'rgb(9,157,204)'},{y:141,h:39,f:'rgb(20,129,214)'},{y:102,h:39,f:'rgb(16,100,220)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:358,y:448,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39},{y:294,f:'rgb(16,100,220)'},{y:256,h:39,f:'rgb(20,129,214)'},{y:218,h:39,f:'rgb(14,143,209)'},{y:179,h:39,f:'rgb(18,114,217)'},{y:141,h:39,f:'rgb(22,82,205)'},{y:102,h:39,f:'rgb(38,62,168)'},{y:64},{y:26,h:39},{x:397,y:448,w:39,h:39},{y:371,h:39},{y:333,h:39},{y:294,f:'rgb(22,82,205)'},{y:256,h:39},{y:218,h:39},{y:179,h:39,f:'rgb(38,62,168)'},{y:141,h:39},{y:102,h:39},{y:64},{y:26,h:39},{x:435,y:410,h:39},{y:371,h:39},{y:333,h:39},{y:294},{y:256,h:39},{y:218,h:39},{y:179,h:39},{y:141,h:39},{y:102,h:39},{y:64},{x:474,y:256,h:39},{y:179,h:39}] }, + th2draw3d: { + path: 'M172.768,0H51.726C23.202,0,0.002,23.194,0.002,51.712v89.918c0,28.512,23.2,51.718,51.724,51.718h121.042 c28.518,0,51.724-23.2,51.724-51.718V51.712C224.486,23.194,201.286,0,172.768,0z M177.512,141.63c0,2.611-2.124,4.745-4.75,4.745 H51.726c-2.626,0-4.751-2.134-4.751-4.745V51.712c0-2.614,2.125-4.739,4.751-4.739h121.042c2.62,0,4.75,2.125,4.75,4.739 L177.512,141.63L177.512,141.63z '+ + 'M460.293,0H339.237c-28.521,0-51.721,23.194-51.721,51.712v89.918c0,28.512,23.2,51.718,51.721,51.718h121.045 c28.521,0,51.721-23.2,51.721-51.718V51.712C512.002,23.194,488.802,0,460.293,0z M465.03,141.63c0,2.611-2.122,4.745-4.748,4.745 H339.237c-2.614,0-4.747-2.128-4.747-4.745V51.712c0-2.614,2.133-4.739,4.747-4.739h121.045c2.626,0,4.748,2.125,4.748,4.739 V141.63z '+ + 'M172.768,256.149H51.726c-28.524,0-51.724,23.205-51.724,51.726v89.915c0,28.504,23.2,51.715,51.724,51.715h121.042 c28.518,0,51.724-23.199,51.724-51.715v-89.915C224.486,279.354,201.286,256.149,172.768,256.149z M177.512,397.784 c0,2.615-2.124,4.736-4.75,4.736H51.726c-2.626-0.006-4.751-2.121-4.751-4.736v-89.909c0-2.626,2.125-4.753,4.751-4.753h121.042 c2.62,0,4.75,2.116,4.75,4.753L177.512,397.784L177.512,397.784z '+ + 'M460.293,256.149H339.237c-28.521,0-51.721,23.199-51.721,51.726v89.915c0,28.504,23.2,51.715,51.721,51.715h121.045 c28.521,0,51.721-23.199,51.721-51.715v-89.915C512.002,279.354,488.802,256.149,460.293,256.149z M465.03,397.784 c0,2.615-2.122,4.736-4.748,4.736H339.237c-2.614,0-4.747-2.121-4.747-4.736v-89.909c0-2.626,2.121-4.753,4.747-4.753h121.045 c2.615,0,4.748,2.116,4.748,4.753V397.784z' + }, - if (index) { - distances = new Float32Array(index.length); - for (let n = 0; n < index.length; n += 2) { - let i1 = index[n], i2 = index[n+1]; - v1.set(arr[i1],arr[i1+1],arr[i1+2]); - v2.set(arr[i2],arr[i2+1],arr[i2+2]); - distances[n] = d; - d += v2.distanceTo(v1); - distances[n+1] = d; - } - } else { - distances = new Float32Array(arr.length/3); - for (let n = 0; n < arr.length; n += 6) { - v1.set(arr[n],arr[n+1],arr[n+2]); - v2.set(arr[n+3],arr[n+4],arr[n+5]); - distances[n/3] = d; - d += v2.distanceTo(v1); - distances[n/3+1] = d; - } - } - geom.setAttribute('lineDistance', new BufferAttribute(distances, 1)); - } + createSVG(group, btn, size, title, arg) { + const use_dark = (arg === true) || (arg === false) ? arg : settings.DarkMode, + opacity0 = (arg === 'browser') ? (browser.touches ? 0.2 : 0) : (use_dark ? 0.8 : 0.2), + svg = group.append('svg:svg') + .attr('width', size + 'px') + .attr('height', size + 'px') + .attr('viewBox', '0 0 512 512') + .style('overflow', 'hidden') + .style('cursor', 'pointer') + .style('fill', use_dark ? 'rgba(255, 224, 160)' : 'steelblue') + .style('opacity', opacity0) + .property('opacity0', opacity0) + .property('opacity1', use_dark ? 1 : 0.8) + .on('mouseenter', function() { + const elem = select(this); + elem.style('opacity', elem.property('opacity1')); + const func = elem.node()._mouseenter; + if (isFunc(func)) func(); + }) + .on('mouseleave', function() { + const elem = select(this); + elem.style('opacity', elem.property('opacity0')); + const func = elem.node()._mouseleave; + if (isFunc(func)) func(); + }); - return only_geometry ? geom : new LineSegments(geom, material); -} + if ('recs' in btn) { + const rec = {}; + for (let n = 0; n < btn.recs.length; ++n) { + Object.assign(rec, btn.recs[n]); + svg.append('rect').attr('x', rec.x).attr('y', rec.y) + .attr('width', rec.w).attr('height', rec.h) + .style('fill', rec.f); + } + } else + svg.append('svg:path').attr('d', btn.path); -/** @summary Help structures for calculating Box mesh - * @private */ -const Box3D = { - Vertices: [ new Vector3(1, 1, 1), new Vector3(1, 1, 0), - new Vector3(1, 0, 1), new Vector3(1, 0, 0), - new Vector3(0, 1, 0), new Vector3(0, 1, 1), - new Vector3(0, 0, 0), new Vector3(0, 0, 1) ], - Indexes: [ 0,2,1, 2,3,1, 4,6,5, 6,7,5, 4,5,1, 5,0,1, 7,6,2, 6,3,2, 5,7,0, 7,2,0, 1,3,4, 3,6,4 ], - Normals: [ 1,0,0, -1,0,0, 0,1,0, 0,-1,0, 0,0,1, 0,0,-1 ], - Segments: [0, 2, 2, 7, 7, 5, 5, 0, 1, 3, 3, 6, 6, 4, 4, 1, 1, 0, 3, 2, 6, 7, 4, 5] // segments addresses Vertices -}; -// these segments address vertices from the mesh, we can use positions from box mesh -Box3D.MeshSegments = (function() { - let box3d = Box3D, - arr = new Int32Array(box3d.Segments.length); + // special rect to correctly get mouse events for whole button area + svg.append('svg:rect').attr('x', 0).attr('y', 0).attr('width', 512).attr('height', 512) + .style('opacity', 0).style('fill', 'none').style('pointer-events', 'visibleFill') + .append('svg:title').text(title); - for (let n = 0; n < arr.length; ++n) { - for (let k = 0; k < box3d.Indexes.length; ++k) - if (box3d.Segments[n] === box3d.Indexes[k]) { - arr[n] = k; break; - } + return svg; } - return arr; -})(); +}; // ToolbarIcons -/** - * @summary Abstract interactive control interface for 3D objects - * - * @abstract - * @private - */ -class InteractiveControl { - cleanup() {} - extractIndex(/*intersect*/) {} - setSelected(/*col, indx*/) {} - setHighlight(/*col, indx*/) {} - checkHighlightIndex(/*indx*/) {} -} // class InteractiveControl +/** @summary Register handle to react on window resize + * @desc function used to react on browser window resize event + * While many resize events could come in short time, + * resize will be handled with delay after last resize event + * @param {object|string} handle can be function or object with checkResize function or dom where painting was done + * @param {number} [delay] - one could specify delay after which resize event will be handled + * @protected */ +function registerForResize(handle, delay) { + if (!handle || isBatchMode() || (typeof window === 'undefined') || (typeof document === 'undefined')) return; + let myInterval = null, myDelay = delay || 300; + if (myDelay < 20) myDelay = 20; -/** - * @summary Class for creation of 3D points - * - * @private - */ + function ResizeTimer() { + myInterval = null; -class PointsCreator { + document.body.style.cursor = 'wait'; + if (isFunc(handle)) + handle(); + else if (isFunc(handle?.checkResize)) + handle.checkResize(); + else { + const node = new BasePainter(handle).selectDom(); + if (!node.empty()) { + const mdi = node.property('mdi'); + if (isFunc(mdi?.checkMDIResize)) + mdi.checkMDIResize(); + else + resize(node.node()); + } + } + document.body.style.cursor = 'auto'; + } - /** @summary constructor - * @param {number} size - number of points - * @param {boolean} [iswebgl=true] - if WebGL is used - * @param {number} [scale=1] - scale factor */ - constructor(size, iswebgl, scale) { - this.webgl = (iswebgl === undefined) ? true : iswebgl; - this.scale = scale || 1.; + window.addEventListener('resize', () => { + if (myInterval !== null) clearTimeout(myInterval); + myInterval = setTimeout(ResizeTimer, myDelay); + }); +} - this.pos = new Float32Array(size*3); - this.geom = new BufferGeometry(); - this.geom.setAttribute('position', new BufferAttribute(this.pos, 3)); - this.indx = 0; - } +/** @summary Detect mouse right button + * @private */ +function detectRightButton(event) { + return (event?.buttons === 2) || (event?.button === 2); +} - /** @summary Add point */ - addPoint(x,y,z) { - this.pos[this.indx] = x; - this.pos[this.indx+1] = y; - this.pos[this.indx+2] = z; - this.indx += 3; - } +/** @summary Add move handlers for drawn element + * @private */ +function addMoveHandler(painter, enabled = true) { + if (!settings.MoveResize || painter.isBatchMode() || !painter.draw_g) return; - /** @summary Create points */ - createPoints(args) { + if (!enabled) { + if (painter.draw_g.property('assigned_move')) { + const drag_move = drag().subject(Object); + drag_move.on('start', null).on('drag', null).on('end', null); + painter.draw_g + .style('cursor', null) + .property('assigned_move', null) + .call(drag_move); + } + return; + } - if (!isObject(args)) - args = { color: args }; - if (!args.color) - args.color = 'black'; + if (painter.draw_g.property('assigned_move')) return; - let k = 1; + const drag_move = drag().subject(Object); + let not_changed = true, move_disabled = false; - // special dots - if (!args.style) k = 1.1; else - if (args.style === 1) k = 0.3; else - if (args.style === 6) k = 0.5; else - if (args.style === 7) k = 0.7; + drag_move + .on('start', function(evnt) { + move_disabled = this.moveEnabled ? !this.moveEnabled() : false; + if (move_disabled) return; + if (detectRightButton(evnt.sourceEvent)) return; + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); + const pos = pointer(evnt, this.draw_g.node()); + not_changed = true; + if (this.moveStart) + this.moveStart(pos[0], pos[1]); + }.bind(painter)).on('drag', function(evnt) { + if (move_disabled) return; + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); + not_changed = false; + if (this.moveDrag) + this.moveDrag(evnt.dx, evnt.dy); + }.bind(painter)).on('end', function(evnt) { + if (move_disabled) return; + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); + if (this.moveEnd) + this.moveEnd(not_changed); - let makePoints = texture => { - let material_args = { size: 3*this.scale*k }; - if (texture) { - material_args.map = texture; - material_args.transparent = true; - } else { - material_args.color = args.color || 'black'; + let arg = null; + if (not_changed) { + // if not changed - provide click position + const pos = pointer(evnt, this.draw_g.node()); + arg = { x: pos[0], y: pos[1], dbl: false }; } + this.getPadPainter()?.selectObjectPainter(this, arg); + }.bind(painter)); - let pnts = new Points(this.geom, new PointsMaterial(material_args)); - pnts.nvertex = 1; - return pnts; - }; + painter.draw_g + .style('cursor', 'move') + .property('assigned_move', true) + .call(drag_move); +} - // this is plain creation of points, no need for texture loading +/** @summary Inject style + * @param {String} code - css string + * @private */ +function injectStyle(code, node, tag) { + if (isBatchMode() || !code || (typeof document === 'undefined')) + return true; - if (k !== 1) { - let res = makePoints(); - return this.noPromise ? res : Promise.resolve(res); + const styles = (node || document).getElementsByTagName('style'); + for (let n = 0; n < styles.length; ++n) { + if (tag && styles[n].getAttribute('tag') === tag) { + styles[n].innerHTML = code; + return true; } - let handler = new TAttMarkerHandler({ style: args.style, color: args.color, size: 7 }), - w = handler.fill ? 1 : 7, - imgdata = `` + - ``+ - ``, - dataUrl = 'data:image/svg+xml;charset=utf8,' + (isNodeJs() ? imgdata : encodeURIComponent(imgdata)), - promise; + if (styles[n].innerHTML === code) + return true; + } - if (isNodeJs()) { - promise = Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(handle => handle.default.loadImage(dataUrl).then(img => { - const canvas = handle.default.createCanvas(64, 64), - ctx = canvas.getContext('2d'); - ctx.drawImage(img, 0, 0, 64, 64); - return new CanvasTexture(canvas); - })); - } else if (this.noPromise) { - // only for v6 support - return makePoints(new TextureLoader().load(dataUrl)); - } else { - promise = new Promise((resolveFunc, rejectFunc) => { - let loader = new TextureLoader(); - loader.load(dataUrl, res => resolveFunc(res), undefined, () => rejectFunc()); - }); - } + const element = document.createElement('style'); + if (tag) element.setAttribute('tag', tag); + element.innerHTML = code; + (node || document.head).appendChild(element); + return true; +} - return promise.then(makePoints); +/** @summary Select predefined style + * @private */ +function selectgStyle(name) { + gStyle.fName = name; + switch (name) { + case 'Modern': Object.assign(gStyle, { fFrameBorderMode: 0, fFrameFillColor: 0, + fCanvasBorderMode: 0, fCanvasColor: 0, fPadBorderMode: 0, fPadColor: 0, fStatColor: 0, + fTitleAlign: 23, fTitleX: 0.5, fTitleBorderSize: 0, fTitleColor: 0, fTitleStyle: 0, + fOptStat: 1111, fStatY: 0.935, + fLegendBorderSize: 1, fLegendFont: 42, fLegendTextSize: 0, fLegendFillColor: 0 }); + break; + case 'Plain': Object.assign(gStyle, { fFrameBorderMode: 0, + fCanvasBorderMode: 0, fPadBorderMode: 0, fPadColor: 0, fCanvasColor: 0, + fTitleColor: 0, fTitleBorderSize: 0, fStatColor: 0, fStatBorderSize: 1, fLegendBorderSize: 1 }); + break; + case 'Bold': Object.assign(gStyle, { fCanvasColor: 10, fCanvasBorderMode: 0, + fFrameLineWidth: 3, fFrameFillColor: 10, + fPadColor: 10, fPadTickX: 1, fPadTickY: 1, fPadBottomMargin: 0.15, fPadLeftMargin: 0.15, + fTitleColor: 10, fTitleTextColor: 600, fStatColor: 10 }); + break; } +} -} // class PointsCreator - +/** @summary Save object as a cookie + * @private */ +function saveCookie(obj, expires, name) { + const arg = (expires <= 0) ? '' : btoa_func(JSON.stringify(obj)), + d = new Date(); + d.setTime((expires <= 0) ? 0 : d.getTime() + expires*24*60*60*1000); + if (typeof document !== 'undefined') + document.cookie = `${name}=${arg}; expires=${d.toUTCString()}; SameSite=None; Secure; path=/;`; +} -/** @summary Create material for 3D line - * @desc Takes into account dashed properties +/** @summary Read cookie with specified name * @private */ -function create3DLineMaterial(painter, arg, is_v7 = false) { - if (!painter || !arg) return null; +function readCookie(name) { + if (typeof document === 'undefined') + return null; + const decodedCookie = decodeURIComponent(document.cookie), + ca = decodedCookie.split(';'); + name += '='; + for (let i = 0; i < ca.length; i++) { + let c = ca[i]; + while (c.charAt(0) === ' ') + c = c.substring(1); + if (c.indexOf(name) === 0) { + const s = JSON.parse(atob_func(c.substring(name.length, c.length))); - let lcolor, lstyle, lwidth; - if (isStr(arg) || is_v7) { - lcolor = painter.v7EvalColor(arg+'color', 'black'); - lstyle = parseInt(painter.v7EvalAttr(arg+'style', 0)); - lwidth = parseInt(painter.v7EvalAttr(arg+'width', 1)); - } else { - lcolor = painter.getColor(arg.fLineColor); - lstyle = arg.fLineStyle; - lwidth = arg.fLineWidth; + return isObject(s) ? s : null; + } } + return null; +} - let style = lstyle ? getSvgLineStyle(lstyle) : '', - dash = style ? style.split(',') : [], material; - - if (dash && dash.length >= 2) - material = new LineDashedMaterial({ color: lcolor, dashSize: parseInt(dash[0]), gapSize: parseInt(dash[1]) }); - else - material = new LineBasicMaterial({ color: lcolor }); - - if (lwidth && (lwidth > 1)) material.linewidth = lwidth; +/** @summary Save JSROOT settings as specified cookie parameter + * @param {Number} expires - days when cookie will be removed by browser, negative - delete immediately + * @param {String} name - cookie parameter name + * @private */ +function saveSettings(expires = 365, name = 'jsroot_settings') { + saveCookie(settings, expires, name); +} - return material; +/** @summary Read JSROOT settings from specified cookie parameter + * @param {Boolean} only_check - when true just checks if settings were stored before with provided name + * @param {String} name - cookie parameter name + * @private */ +function readSettings(only_check = false, name = 'jsroot_settings') { + const s = readCookie(name); + if (!s) return false; + if (!only_check) + Object.assign(settings, s); + return true; } -/** @summary Text 3d axis visibility +/** @summary Save JSROOT gStyle object as specified cookie parameter + * @param {Number} expires - days when cookie will be removed by browser, negative - delete immediately + * @param {String} name - cookie parameter name * @private */ -function testAxisVisibility(camera, toplevel, fb, bb) { - let top; - if (toplevel && toplevel.children) - for (let n = 0; n < toplevel.children.length; ++n) { - top = toplevel.children[n]; - if (top.axis_draw) break; - top = undefined; - } +function saveStyle(expires = 365, name = 'jsroot_style') { + saveCookie(gStyle, expires, name); +} - if (!top) return; +/** @summary Read JSROOT gStyle object specified cookie parameter + * @param {Boolean} only_check - when true just checks if settings were stored before with provided name + * @param {String} name - cookie parameter name + * @private */ +function readStyle(only_check = false, name = 'jsroot_style') { + const s = readCookie(name); + if (!s) return false; + if (!only_check) + Object.assign(gStyle, s); + return true; +} - if (!camera) { - // this is case when axis drawing want to be removed - toplevel.remove(top); - return; - } +let _saveFileFunc = null; - fb = fb ? true : false; - bb = bb ? true : false; +/** @summary Returns image file content as it should be stored on the disc + * @desc Replaces all kind of base64 coding + * @private */ - let qudrant = 1, pos = camera.position; - if ((pos.x < 0) && (pos.y >= 0)) qudrant = 2; - if ((pos.x >= 0) && (pos.y >= 0)) qudrant = 3; - if ((pos.x >= 0) && (pos.y < 0)) qudrant = 4; +function getBinFileContent(content) { + const svg_prefix = 'data:image/svg+xml;charset=utf-8,'; - let testvisible = (id, range) => { - if (id <= qudrant) id+=4; - return (id > qudrant) && (id < qudrant+range); - }; + if (content.indexOf(svg_prefix) === 0) + return decodeURIComponent(content.slice(svg_prefix.length)); - for (let n = 0; n < top.children.length; ++n) { - let chld = top.children[n]; - if (chld.grid) chld.visible = bb && testvisible(chld.grid, 3); else - if (chld.zid) chld.visible = testvisible(chld.zid, 2); else - if (chld.xyid) chld.visible = testvisible(chld.xyid, 3); else - if (chld.xyboxid) { - let range = 5, shift = 0; - if (bb && !fb) { range = 3; shift = -2; } else - if (fb && !bb) range = 3; else - if (!fb && !bb) range = (chld.bottom ? 3 : 0); - chld.visible = testvisible(chld.xyboxid + shift, range); - if (!chld.visible && chld.bottom && bb) - chld.visible = testvisible(chld.xyboxid, 3); - } else if (chld.zboxid) { - let range = 2, shift = 0; - if (fb && bb) range = 5; else - if (bb && !fb) range = 4; else - if (!bb && fb) { shift = -2; range = 4; } - chld.visible = testvisible(chld.zboxid + shift, range); + if (content.indexOf('data:image/') === 0) { + const p = content.indexOf('base64,'); + if (p > 0) { + const base64 = content.slice(p + 7); + return atob_func(base64); } } + + return content; } -/** @summary Set default camera position +/** @summary Function store content as file with filename * @private */ -function setCameraPosition(fp, first_time) { - let pad = fp.getPadPainter().getRootPad(true), - max3dx = Math.max(0.75*fp.size_x3d, fp.size_z3d), - max3dy = Math.max(0.75*fp.size_y3d, fp.size_z3d); +async function saveFile(filename, content) { + if (isFunc(_saveFileFunc)) + return _saveFileFunc(filename, getBinFileContent(content)); + if (isNodeJs()) { + return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(fs => { + fs.writeFileSync(filename, getBinFileContent(content)); + return true; + }); + } else if (typeof document !== 'undefined') { + const a = document.createElement('a'); + a.download = filename; + a.href = content; + document.body.appendChild(a); - if (first_time) { - if (max3dx === max3dy) - fp.camera.position.set(-1.6*max3dx, -3.5*max3dy, 1.4*fp.size_z3d); - else if (max3dx > max3dy) - fp.camera.position.set(-2*max3dx, -3.5*max3dy, 1.4*fp.size_z3d); - else - fp.camera.position.set(-3.5*max3dx, -2*max3dy, 1.4*fp.size_z3d); + return new Promise(resolve => { + a.addEventListener('click', () => { a.parentNode.removeChild(a); resolve(true); }); + a.click(); + }); } - - if (pad && (first_time || !fp.zoomChangedInteractive())) - if (Number.isFinite(pad.fTheta) && Number.isFinite(pad.fPhi) && ((pad.fTheta !== fp.camera_Theta) || (pad.fPhi !== fp.camera_Phi))) { - fp.camera_Phi = pad.fPhi; - fp.camera_Theta = pad.fTheta; - max3dx = 3*Math.max(fp.size_x3d, fp.size_z3d); - max3dy = 3*Math.max(fp.size_y3d, fp.size_z3d); - let phi = (270-pad.fPhi)/180*Math.PI, theta = (pad.fTheta-10)/180*Math.PI; - fp.camera.position.set(max3dx*Math.cos(phi)*Math.cos(theta), - max3dy*Math.sin(phi)*Math.cos(theta), - fp.size_z3d + (max3dx+max3dy)*0.5*Math.sin(theta)); - first_time = true; - } - - if (first_time) - fp.camera.lookAt(fp.lookat); + return false; } -/** @summary Create all necessary components for 3D drawings in frame painter - * @return {Promise} when render3d !== -1 +/** @summary Function store content as file with filename * @private */ -function create3DScene(render3d, x3dscale, y3dscale) { - - if (render3d === -1) { - - if (!this.mode3d) return; +function setSaveFile(func) { + _saveFileFunc = func; +} - if (!this.clear3dCanvas) { - console.error(`Strange, why mode3d=${this.mode3d} is configured!!!!`); - return; +/** @summary Produce exec string for WebCanas to set color value + * @desc Color can be id or string, but should belong to list of known colors + * For higher color numbers TColor::GetColor(r,g,b) will be invoked to ensure color is exists + * @private */ +function getColorExec(col, method) { + const arr = getRootColors(); + let id = -1; + if (isStr(col)) { + if (!col || (col === 'none')) + id = 0; + else { + for (let k = 1; k < arr.length; ++k) + if (arr[k] === col) { id = k; break; } } + if ((id < 0) && (col.indexOf('rgb') === 0)) + id = 9999; + } else if (Number.isInteger(col) && arr[col]) { + id = col; + col = arr[id]; + } - testAxisVisibility(null, this.toplevel); - - this.clear3dCanvas(); + if (id < 0) return ''; - disposeThreejsObject(this.scene); - if (this.control) this.control.cleanup(); + // for higher color numbers ensure that such color exists + if (id >= 50) { + const c = color(col); + id = `TColor::GetColor(${c.r},${c.g},${c.b})`; + } - cleanupRender3D(this.renderer); + return `exec:${method}(${id})`; +} - delete this.size_x3d; - delete this.size_y3d; - delete this.size_z3d; - delete this.tooltip_mesh; - delete this.scene; - delete this.toplevel; - delete this.camera; - delete this.pointLight; - delete this.renderer; - delete this.control; - if (this.render_tmout) { - clearTimeout(this.render_tmout); - delete this.render_tmout; - } +const kToFront = '__front__'; - this.mode3d = false; +/** + * @summary Abstract class for creating context menu + * + * @desc Use {@link createMenu} to create instance of the menu + * @private + */ - return; - } +class JSRootMenu { - this.mode3d = true; // indicate 3d mode as hist painter does + constructor(painter, menuname, show_event) { + this.painter = painter; + this.menuname = menuname; + if (isObject(show_event) && (show_event.clientX !== undefined) && (show_event.clientY !== undefined)) + this.show_evnt = { clientX: show_event.clientX, clientY: show_event.clientY, skip_close: show_event.skip_close }; - if ('toplevel' in this) { - // it is indication that all 3D object created, just replace it with empty - this.scene.remove(this.toplevel); - disposeThreejsObject(this.toplevel); - delete this.tooltip_mesh; - delete this.toplevel; - if (this.control) this.control.HideTooltip(); + this.remove_handler = () => this.remove(); + this.element = null; + this.cnt = 0; + } - let newtop = new Object3D(); - this.scene.add(newtop); - this.toplevel = newtop; + native() { return false; } - this.resize3D(); // set actual sizes + async load() { return this; } - setCameraPosition(this, false); + /** @summary Returns object with mouse event position when context menu was actiavted + * @desc Return object will have members 'clientX' and 'clientY' */ + getEventPosition() { return this.show_evnt; } - return Promise.resolve(true); + add(/* name, arg, func, title */) { + throw Error('add() method has to be implemented in the menu'); } - render3d = getRender3DKind(render3d); - - assign3DHandler(this); - - let sz = this.getSizeFor3d(undefined, render3d); + /** @summary Returns menu size */ + size() { return this.cnt; } - this.size_z3d = 100; - this.size_x3d = this.size_y3d = (sz.height > 10) && (sz.width > 10) ? Math.round(sz.width/sz.height*this.size_z3d) : this.size_z3d; - if (x3dscale) this.size_x3d *= x3dscale; - if (y3dscale) this.size_y3d *= y3dscale; + /** @summary Close and remove menu */ + remove() { + if (!this.element) + return; - // three.js 3D drawing - this.scene = new Scene(); - //scene.fog = new Fog(0xffffff, 500, 3000); + if (this.show_evnt?.skip_close) { + this.show_evnt.skip_close = 0; + return; + } - this.toplevel = new Object3D(); - this.scene.add(this.toplevel); - this.scene_width = sz.width; - this.scene_height = sz.height; + this.element.remove(); + this.element = null; + if (isFunc(this.resolveFunc)) { + const func = this.resolveFunc; + delete this.resolveFunc; + func(); + } + document.body.removeEventListener('click', this.remove_handler); + } - this.camera = new PerspectiveCamera(45, this.scene_width / this.scene_height, 1, 40*this.size_z3d); + show(/* event */) { + throw Error('show() method has to be implemented in the menu class'); + } - this.camera_Phi = 30; - this.camera_Theta = 30; + /** @summary Add checked menu item + * @param {boolean} flag - flag + * @param {string} name - item name + * @param {function} func - func called when item is selected */ + addchk(flag, name, arg, func, title) { + let handler = func; + if (isFunc(arg)) { + title = func; + func = arg; + handler = res => func(res === '1'); + arg = flag ? '0' : '1'; + } + this.add((flag ? 'chk:' : 'unk:') + name, arg, handler, title); + } - this.pointLight = new PointLight(0xffffff,1); - this.camera.add(this.pointLight); - this.pointLight.position.set(this.size_x3d/2, this.size_y3d/2, this.size_z3d/2); - this.lookat = new Vector3(0,0,0.8*this.size_z3d); - this.camera.up = new Vector3(0,0,1); - this.scene.add( this.camera ); + /** @summary Add draw sub-menu with draw options + * @protected */ + addDrawMenu(top_name, opts, call_back, title) { + if (!opts || !opts.length) + return; - setCameraPosition(this, true); + let without_sub = false; + if (top_name.indexOf('nosub:') === 0) { + without_sub = true; + top_name = top_name.slice(6); + } - return createRender3D(this.scene_width, this.scene_height, render3d).then(r => { + if (opts.length === 1) { + if (opts[0] === kInspect) + top_name = top_name.replace('Draw', 'Inspect'); + this.add(top_name, opts[0], call_back); + return; + } - this.renderer = r; + if (!without_sub) + this.add('sub:' + top_name, opts[0], call_back, title); - this.webgl = (render3d === constants$1.Render3D.WebGL); - this.add3dCanvas(sz, this.renderer.jsroot_dom, this.webgl); + for (let i = 1; i < opts.length; ++i) { + let name = opts[i] || (this._use_plain_text ? '' : '<dflt>'), + group = i+1; + if ((opts.length > 5) && name) { + // check if there are similar options, which can be grouped once again + while ((group < opts.length) && (opts[group].indexOf(name) === 0)) group++; + } - this.first_render_tm = 0; - this.enable_highlight = false; + if (without_sub) + name = top_name + ' ' + name; - if (isBatchMode() || !this.webgl) - return this; + if (group >= i+2) { + this.add('sub:' + name, opts[i], call_back); + for (let k = i+1; k < group; ++k) + this.add(opts[k], opts[k], call_back); + this.add('endsub:'); + i = group - 1; + } else if (name === kInspect) { + this.add('sub:' + name, opts[i], call_back, 'Inspect object content'); + for (let k = 0; k < 10; ++k) + this.add(k.toString(), kInspect + k, call_back, `Inspect object and expand to level ${k}`); + this.add('endsub:'); + } else + this.add(name, opts[i], call_back); + } + if (!without_sub) { + this.add('', () => { + const opt = isFunc(this.painter?.getDrawOpt) ? this.painter.getDrawOpt() : opts[0]; + this.input('Provide draw option', opt, 'text').then(call_back); + }, 'Enter draw option in dialog'); + this.add('endsub:'); + } + } - this.control = createOrbitControl(this, this.camera, this.scene, this.renderer, this.lookat); + /** @summary Add color selection menu entries + * @protected */ + addColorMenu(name, value, set_func, fill_kind) { + if (value === undefined) return; + const useid = !isStr(value); + this.add('sub:' + name, () => { + this.input('Enter color ' + (useid ? '(only id number)' : '(name or id)'), value, useid ? 'int' : 'text', useid ? 0 : undefined, useid ? 9999 : undefined).then(col => { + const id = parseInt(col); + if (Number.isInteger(id) && getColor(id)) + col = getColor(id); + else + if (useid) return; - let frame_painter = this, obj_painter = this.getMainPainter(); + set_func(useid ? id : col); + }); + }); - this.control.processMouseMove = function(intersects) { + for (let ncolumn = 0; ncolumn < 5; ++ncolumn) { + this.add('column:'); - let tip = null, mesh = null, zoom_mesh = null; + for (let nrow = 0; nrow < 10; nrow++) { + let n = ncolumn*10 + nrow; + if (!useid) --n; // use -1 as none color - for (let i = 0; i < intersects.length; ++i) { - if (intersects[i].object.tooltip) { - tip = intersects[i].object.tooltip(intersects[i]); - if (tip) { mesh = intersects[i].object; break; } - } else if (intersects[i].object.zoom && !zoom_mesh) { - zoom_mesh = intersects[i].object; - } - } + let col = (n < 0) ? 'none' : getColor(n); + if ((n === 0) && (fill_kind === 1)) col = 'none'; + const lbl = (n <= 0) || (col[0] !== '#') ? col : `col ${n}`, + fill = (n === 1) ? 'white' : 'black', + stroke = (n === 1) ? 'red' : 'black', + rect = (value === (useid ? n : col)) ? `` : '', + svg = `${rect}${lbl}`; - if (tip && !tip.use_itself) { - let delta_x = 1e-4*frame_painter.size_x3d, - delta_y = 1e-4*frame_painter.size_y3d, - delta_z = 1e-4*frame_painter.size_z3d; - if ((tip.x1 > tip.x2) || (tip.y1 > tip.y2) || (tip.z1 > tip.z2)) console.warn('check 3D hints coordinates'); - tip.x1 -= delta_x; tip.x2 += delta_x; - tip.y1 -= delta_y; tip.y2 += delta_y; - tip.z1 -= delta_z; tip.z2 += delta_z; + this.add(svg, (useid ? n : col), res => set_func(useid ? parseInt(res) : res), 'Select color ' + col); } - frame_painter.highlightBin3D(tip, mesh); + this.add('endcolumn:'); + if (!this.native()) break; + } - if (!tip && zoom_mesh && frame_painter.get3dZoomCoord) { - let pnt = zoom_mesh.globalIntersect(this.raycaster), - axis_name = zoom_mesh.zoom, - axis_value = frame_painter.get3dZoomCoord(pnt, axis_name); + this.add('endsub:'); + } - if ((axis_name === 'z') && zoom_mesh.use_y_for_z) axis_name = 'y'; + /** @summary Add size selection menu entries + * @protected */ + addSizeMenu(name, min, max, step, size_value, set_func, title) { + if (size_value === undefined) return; - return { name: axis_name, - title: 'axis object', - line: axis_name + ' : ' + frame_painter.axisAsText(axis_name, axis_value), - only_status: true }; - } + let values = [], miss_current = false; + if (isObject(step)) { + values = step; step = 1; + } else { + for (let sz = min; sz <= max; sz += step) + values.push(sz); + } - return tip?.lines ? tip : ''; - }; + const match = v => Math.abs(v-size_value) < (max - min)*1e-5, + conv = (v, more) => { + if ((v === size_value) && miss_current) more = true; + if (step >= 1) return v.toFixed(0); + if (step >= 0.1) return v.toFixed(more ? 2 : 1); + return v.toFixed(more ? 4 : 2); + }; - this.control.processMouseLeave = function() { - frame_painter.highlightBin3D(null); - }; + if (values.findIndex(match) < 0) { + miss_current = true; + values.push(size_value); + values = values.sort((a, b) => a > b); + } - this.control.contextMenu = function(pos, intersects) { - let kind = 'painter', p = obj_painter; - if (intersects) - for (let n = 0; n < intersects.length; ++n) { - let mesh = intersects[n].object; - if (mesh.zoom) { kind = mesh.zoom; p = null; break; } - if (isFunc(mesh.painter?.fillContextMenu)) { - p = mesh.painter; break; - } - } + this.add('sub:' + name, () => this.input('Enter value of ' + name, conv(size_value, true), (step >= 1) ? 'int' : 'float').then(set_func), title); + values.forEach(v => this.addchk(match(v), conv(v), v, res => set_func((step >= 1) ? parseInt(res) : parseFloat(res)))); + this.add('endsub:'); + } - let fp = obj_painter.getFramePainter(); - if (isFunc(fp?.showContextMenu)) - fp.showContextMenu(kind, pos, p); + /** @summary Add palette menu entries + * @protected */ + addPaletteMenu(curr, set_func) { + const add = (id, name, title, more) => { + if (!name) + name = `pal ${id}`; + else if (!title) + title = name; + if (title) title += `, code ${id}`; + this.addchk((id === curr) || more, '' + name + '', id, set_func, title || name); }; - return this; - }); -} + this.add('sub:Palette', () => this.input('Enter palette code [1..113]', curr, 'int', 1, 113).then(set_func)); -/** @summary call 3D rendering of the frame - * @param {number} tmout - specifies delay, after which actual rendering will be invoked - * @desc Timeout used to avoid multiple rendering of the picture when several 3D drawings - * superimposed with each other. - * If tmeout <= 0, rendering performed immediately - * If tmout == -1111, immediate rendering with SVG renderer is performed - * @private */ -function render3D(tmout) { + this.add('column:'); - if (tmout === -1111) { - // special handling for direct SVG renderer - let doc = getDocument(), - rrr = createSVGRenderer(false, 0, doc); - rrr.setSize(this.scene_width, this.scene_height); - rrr.render(this.scene, this.camera); - if (rrr.makeOuterHTML) { - // use text mode, it is faster - let d = doc.createElement('div'); - d.innerHTML = rrr.makeOuterHTML(); - return d.childNodes[0]; - } - return rrr.domElement; - } + add(57, 'Bird', 'Default color palette', (curr > 113)); + add(55, 'Rainbow'); + add(51, 'Deep Sea'); + add(52, 'Grayscale', 'New gray scale'); + add(1, '', 'Old gray scale', (curr > 0) && (curr < 10)); + add(50, 'ROOT 5', 'Default color palette in ROOT 5', (curr >= 10) && (curr < 51)); + add(53, '', 'Dark body radiator'); + add(54, '', 'Two-color hue'); + add(56, '', 'Inverted dark body radiator'); + add(58, 'Cubehelix'); + add(59, '', 'Green Red Violet'); + add(60, '', 'Blue Red Yellow'); + add(61, 'Ocean'); - if (tmout === undefined) tmout = 5; // by default, rendering happens with timeout + this.add('endcolumn:'); - if ((tmout > 0) && !this.usesvg && !isBatchMode()) { - if (!this.render_tmout) - this.render_tmout = setTimeout(() => this.render3D(0), tmout); - return; - } + if (!this.native()) + return this.add('endsub:'); - if (this.render_tmout) { - clearTimeout(this.render_tmout); - delete this.render_tmout; - } + this.add('column:'); - if (!this.renderer) return; + add(62, '', 'Color Printable On Grey'); + add(63, 'Alpine'); + add(64, 'Aquamarine'); + add(65, 'Army'); + add(66, 'Atlantic'); + add(67, 'Aurora'); + add(68, 'Avocado'); + add(69, 'Beach'); + add(70, 'Black Body'); + add(71, '', 'Blue Green Yellow'); + add(72, 'Brown Cyan'); + add(73, 'CMYK'); + add(74, 'Candy'); - beforeRender3D(this.renderer); + this.add('endcolumn:'); + this.add('column:'); - let tm1 = new Date(); + add(75, 'Cherry'); + add(76, 'Coffee'); + add(77, '', 'Dark Rain Bow'); + add(78, '', 'Dark Terrain'); + add(79, 'Fall'); + add(80, 'Fruit Punch'); + add(81, 'Fuchsia'); + add(82, 'Grey Yellow'); + add(83, '', 'Green Brown Terrain'); + add(84, 'Green Pink'); + add(85, 'Island'); + add(86, 'Lake'); + add(87, '', 'Light Temperature'); - if (!this.opt3d) this.opt3d = { FrontBox: true, BackBox: true }; + this.add('endcolumn:'); + this.add('column:'); - testAxisVisibility(this.camera, this.toplevel, this.opt3d.FrontBox, this.opt3d.BackBox); + add(88, '', 'Light Terrain'); + add(89, 'Mint'); + add(90, 'Neon'); + add(91, 'Pastel'); + add(92, 'Pearl'); + add(93, 'Pigeon'); + add(94, 'Plum'); + add(95, 'Red Blue'); + add(96, 'Rose'); + add(97, 'Rust'); + add(98, '', 'Sandy Terrain'); + add(99, 'Sienna'); + add(100, 'Solar'); - // do rendering, most consuming time - this.renderer.render(this.scene, this.camera); + this.add('endcolumn:'); + this.add('column:'); - afterRender3D(this.renderer); + add(101, '', 'South West'); + add(102, '', 'Starry Night'); + add(103, '', 'Sunset'); + add(104, '', 'Temperature Map'); + add(105, '', 'Thermometer'); + add(106, 'Valentine'); + add(107, '', 'Visible Spectrum'); + add(108, '', 'Water Melon'); + add(109, 'Cool'); + add(110, 'Copper'); + add(111, '', 'Gist Earth'); + add(112, 'Viridis'); + add(113, 'Cividis'); - let tm2 = new Date(); + this.add('endcolumn:'); - if (this.first_render_tm === 0) { - this.first_render_tm = tm2.getTime() - tm1.getTime(); - this.enable_highlight = (this.first_render_tm < 1200) && this.isTooltipAllowed(); - console.log(`three.js r${REVISION}, first render tm = ${this.first_render_tm}`); + this.add('endsub:'); } -} - -/** @summary Check is 3D drawing need to be resized - * @private */ -function resize3D() { - - let sz = this.getSizeFor3d(this.access3dKind()); - this.apply3dSize(sz); - - if ((this.scene_width === sz.width) && (this.scene_height === sz.height)) return false; - - if ((sz.width < 10) || (sz.height < 10)) return false; + /** @summary Add rebin menu entries + * @protected */ + addRebinMenu(rebin_func) { + this.add('sub:Rebin', () => this.input('Enter rebin value', 2, 'int', 2).then(rebin_func)); + for (let sz = 2; sz <= 7; sz++) + this.add(sz.toString(), sz, res => rebin_func(parseInt(res))); + this.add('endsub:'); + } - this.scene_width = sz.width; - this.scene_height = sz.height; + /** @summary Add selection menu entries + * @param {String} name - name of submenu + * @param {Array} values - array of string entries used as list for selection + * @param {String|Number} value - currently elected value, either name or index + * @param {Function} set_func - function called when item selected, either name or index depending from value parameter + * @protected */ + addSelectMenu(name, values, value, set_func) { + const use_number = (typeof value === 'number'); + this.add('sub:' + name); + for (let n = 0; n < values.length; ++n) + this.addchk(use_number ? (n === value) : (values[n] === value), values[n], use_number ? n : values[n], res => set_func(use_number ? Number.parseInt(res) : res)); + this.add('endsub:'); + } - this.camera.aspect = this.scene_width / this.scene_height; - this.camera.updateProjectionMatrix(); + /** @summary Add RColor selection menu entries + * @protected */ + addRColorMenu(name, value, set_func) { + // if (value === undefined) return; + const colors = ['default', 'black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']; - this.renderer.setSize( this.scene_width, this.scene_height ); - if (this.renderer.setJSROOTSize) - this.renderer.setJSROOTSize(this.scene_width, this.scene_height); + this.add('sub:' + name, () => { + this.input('Enter color name - empty string will reset color', value).then(set_func); + }); + let fillcol = 'black'; + for (let n = 0; n < colors.length; ++n) { + const coltxt = colors[n]; + let match = false, bkgr = ''; + if (n > 0) { + bkgr = 'background-color:' + coltxt; + fillcol = (coltxt === 'white') ? 'black' : 'white'; - return true; -} + if (isStr(value) && value && (value !== 'auto') && (value[0] !== '[')) + match = (rgb(value).toString() === rgb(coltxt).toString()); + } else + match = !value; -/** @summary Hilight bin in frame painter 3D drawing - * @private */ -function highlightBin3D(tip, selfmesh) { + const svg = `${coltxt}`; + this.addchk(match, svg, coltxt, res => set_func(res === 'default' ? null : res)); + } + this.add('endsub:'); + } - let changed = false, tooltip_mesh = null, changed_self = true, - want_remove = !tip || (tip.x1 === undefined) || !this.enable_highlight, - mainp = this.getMainPainter(); + /** @summary Add items to change RAttrText + * @protected */ + addRAttrTextItems(fontHandler, opts, set_func) { + if (!opts) opts = {}; + this.addRColorMenu('color', fontHandler.color, value => set_func({ name: 'color', value })); + if (fontHandler.scaled) + this.addSizeMenu('size', 0.01, 0.10, 0.01, fontHandler.size /fontHandler.scale, value => set_func({ name: 'size', value })); + else + this.addSizeMenu('size', 6, 20, 2, fontHandler.size, value => set_func({ name: 'size', value })); - if (mainp && (!mainp.provideUserTooltip || !mainp.hasUserTooltip())) mainp = null; + this.addSelectMenu('family', ['Arial', 'Times New Roman', 'Courier New', 'Symbol'], fontHandler.name, value => set_func({ name: 'font_family', value })); - if (this.tooltip_selfmesh) { - changed_self = (this.tooltip_selfmesh !== selfmesh); - this.tooltip_selfmesh.material.color = this.tooltip_selfmesh.save_color; - delete this.tooltip_selfmesh; - changed = true; - } + this.addSelectMenu('style', ['normal', 'italic', 'oblique'], fontHandler.style || 'normal', res => set_func({ name: 'font_style', value: res === 'normal' ? null : res })); - if (this.tooltip_mesh) { - tooltip_mesh = this.tooltip_mesh; - this.toplevel.remove(this.tooltip_mesh); - delete this.tooltip_mesh; - changed = true; - } + this.addSelectMenu('weight', ['normal', 'lighter', 'bold', 'bolder'], fontHandler.weight || 'normal', res => set_func({ name: 'font_weight', value: res === 'normal' ? null : res })); - if (want_remove) { - if (changed) this.render3D(); - if (changed && mainp) mainp.provideUserTooltip(null); - return; + if (!opts.noalign) + this.add('align'); + if (!opts.noangle) + this.add('angle'); } - if (tip.use_itself) { - selfmesh.save_color = selfmesh.material.color; - selfmesh.material.color = new Color$1(tip.color); - this.tooltip_selfmesh = selfmesh; - changed = changed_self; - } else { - changed = true; - - const indicies = Box3D.Indexes, - normals = Box3D.Normals, - vertices = Box3D.Vertices, - color = new Color$1(tip.color ? tip.color : 0xFF0000), - opacity = tip.opacity || 1; - - let pos, norm; + /** @summary Add line style menu + * @private */ + addLineStyleMenu(name, value, set_func) { + this.add('sub:'+name, () => this.input('Enter line style id (1-solid)', value, 'int', 1, 11).then(val => { + if (getSvgLineStyle(val)) set_func(val); + })); + for (let n = 1; n < 11; ++n) { + const dash = getSvgLineStyle(n), + svg = `${n}`; - if (!tooltip_mesh) { - pos = new Float32Array(indicies.length*3); - norm = new Float32Array(indicies.length*3); - const geom = new BufferGeometry(); - geom.setAttribute('position', new BufferAttribute(pos, 3)); - geom.setAttribute('normal', new BufferAttribute(norm, 3)); - const material = new MeshBasicMaterial({ color: color, opacity: opacity, vertexColors: false }); - tooltip_mesh = new Mesh(geom, material); - } else { - pos = tooltip_mesh.geometry.attributes.position.array; - tooltip_mesh.geometry.attributes.position.needsUpdate = true; - tooltip_mesh.material.color = color; - tooltip_mesh.material.opacity = opacity; + this.addchk((value === n), svg, n, arg => set_func(parseInt(arg))); } + this.add('endsub:'); + } - if (tip.x1 === tip.x2) console.warn(`same tip X ${tip.x1} ${tip.x2}`); - if (tip.y1 === tip.y2) console.warn(`same tip Y ${tip.y1} ${tip.y2}`); - if (tip.z1 === tip.z2) { tip.z2 = tip.z1 + 0.0001; } // avoid zero faces + /** @summary Add fill style menu + * @private */ + addFillStyleMenu(name, value, color_index, painter, set_func) { + this.add('sub:' + name, () => { + this.input('Enter fill style id (1001-solid, 3000..3010)', value, 'int', 0, 4000).then(id => { + if ((id >= 0) && (id <= 4000)) set_func(id); + }); + }); - for (let k = 0, nn = -3; k < indicies.length; ++k) { - let vert = vertices[indicies[k]]; - pos[k*3] = tip.x1 + vert.x * (tip.x2 - tip.x1); - pos[k*3+1] = tip.y1 + vert.y * (tip.y2 - tip.y1); - pos[k*3+2] = tip.z1 + vert.z * (tip.z2 - tip.z1); + const supported = [1, 1001, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3010, 3021, 3022]; - if (norm) { - if (k % 6 === 0) nn += 3; - norm[k*3] = normals[nn]; - norm[k*3+1] = normals[nn+1]; - norm[k*3+2] = normals[nn+2]; + for (let n = 0; n < supported.length; ++n) { + let svg = supported[n]; + if (painter) { + const sample = painter.createAttFill({ std: false, pattern: supported[n], color: color_index || 1 }); + svg = `${supported[n].toString()}`; } + this.addchk(value === supported[n], svg, supported[n], arg => set_func(parseInt(arg))); } - this.tooltip_mesh = tooltip_mesh; - this.toplevel.add(tooltip_mesh); + this.add('endsub:'); } - if (changed) this.render3D(); - - if (changed && isFunc(tip.$painter?.redrawProjection)) - tip.$painter.redrawProjection(tip.ix-1, tip.ix, tip.iy-1, tip.iy); + /** @summary Add font selection menu + * @private */ + addFontMenu(name, value, set_func) { + const prec = value && Number.isInteger(value) ? value % 10 : 2; - if (changed && mainp?.getObject()) - mainp.provideUserTooltip({ obj: mainp.getObject(), name: mainp.getObject().fName, - bin: tip.bin, cont: tip.value, - binx: tip.ix, biny: tip.iy, binz: tip.iz, - grx: (tip.x1+tip.x2)/2, gry: (tip.y1+tip.y2)/2, grz: (tip.z1+tip.z2)/2 }); -} + this.add('sub:' + name, () => { + this.input('Enter font id from [0..20]', Math.floor(value/10), 'int', 0, 20).then(id => { + if ((id >= 0) && (id <= 20)) set_func(id*10 + prec); + }); + }); -/** @summary Set options used for 3D drawings - * @private */ -function set3DOptions(hopt) { - this.opt3d = hopt; -} + this.add('column:'); -/** @summary Draw axes in 3D mode - * @private */ -function drawXYZ(toplevel, AxisPainter, opts) { - if (!opts) opts = {}; + const doc = getDocument(); - let grminx = -this.size_x3d, grmaxx = this.size_x3d, - grminy = -this.size_y3d, grmaxy = this.size_y3d, - grminz = 0, grmaxz = 2*this.size_z3d, - scalingSize = this.size_z3d, - pad = opts.v7 ? null : this.getPadPainter().getRootPad(true), - xmin = this.xmin, xmax = this.xmax, - ymin = this.ymin, ymax = this.ymax, - zmin = this.zmin, zmax = this.zmax, - y_zoomed = false, z_zoomed = false; + for (let n = 1; n < 20; ++n) { + const id = n*10 + prec, + handler = new FontHandler(id, 14), + txt = select(doc.createElementNS('http://www.w3.org/2000/svg', 'text')); + let fullname = handler.getFontName(), qual = ''; + if (handler.weight) { qual += 'b'; fullname += ' ' + handler.weight; } + if (handler.style) { qual += handler.style[0]; fullname += ' ' + handler.style; } + if (qual) qual = ' ' + qual; + txt.attr('x', 1).attr('y', 15).text(fullname.split(' ')[0] + qual); + handler.setFont(txt); - if (!this.size_z3d) { - grminx = this.xmin; grmaxx = this.xmax; - grminy = this.ymin; grmaxy = this.ymax; - grminz = this.zmin; grmaxz = this.zmax; - scalingSize = (grmaxz - grminz); - } + const rect = (value !== id) ? '' : '', + svg = `${txt.node().outerHTML}${rect}`; + this.add(svg, id, arg => set_func(parseInt(arg)), `${id}: ${fullname}`); - if (('zoom_xmin' in this) && ('zoom_xmax' in this) && (this.zoom_xmin !== this.zoom_xmax)) { - xmin = this.zoom_xmin; xmax = this.zoom_xmax; - } - if (('zoom_ymin' in this) && ('zoom_ymax' in this) && (this.zoom_ymin !== this.zoom_ymax)) { - ymin = this.zoom_ymin; ymax = this.zoom_ymax; y_zoomed = true; - } - if (('zoom_zmin' in this) && ('zoom_zmax' in this) && (this.zoom_zmin !== this.zoom_zmax)) { - zmin = this.zoom_zmin; zmax = this.zoom_zmax; z_zoomed = true; - } + if (n === 10) { + this.add('endcolumn:'); + this.add('column:'); + } + } - if (opts.use_y_for_z) { - this.zmin = this.ymin; this.zmax = this.ymax; - zmin = ymin; zmax = ymax; z_zoomed = y_zoomed; - // if (!z_zoomed && (this.hmin!==this.hmax)) { zmin = this.hmin; zmax = this.hmax; } - ymin = 0; ymax = 1; + this.add('endcolumn:'); + this.add('endsub:'); } - // z axis range used for lego plot - this.lego_zmin = zmin; this.lego_zmax = zmax; + /** @summary Add align selection menu + * @private */ + addAlignMenu(name, value, set_func) { + this.add(`sub:${name}`, () => { + this.input('Enter align like 12 or 31', value).then(arg => { + const id = parseInt(arg); + if ((id < 11) || (id > 33)) return; + const h = Math.floor(id/10), v = id % 10; + if ((h > 0) && (h < 4) && (v > 0) && (v < 4)) set_func(id); + }); + }); - // factor 1.1 used in ROOT for lego plots - if ((opts.zmult !== undefined) && !z_zoomed) zmax *= opts.zmult; + const hnames = ['left', 'middle', 'right'], vnames = ['bottom', 'centered', 'top']; + for (let h = 1; h < 4; ++h) { + for (let v = 1; v < 4; ++v) + this.addchk(h*10+v === value, `${h*10+v}: ${hnames[h-1]} ${vnames[h-1]}`, h*10+v, arg => set_func(parseInt(arg))); + } - this.x_handle = new AxisPainter(null, this.xaxis); - if (opts.v7) { - this.x_handle.setPadName(this.getPadName()); - this.x_handle.snapid = this.snapid; + this.add('endsub:'); } - this.x_handle.configureAxis('xaxis', this.xmin, this.xmax, xmin, xmax, false, [grminx, grmaxx], - { log: pad ? pad.fLogx : 0 }); - this.x_handle.assignFrameMembers(this, 'x'); - this.x_handle.extractDrawAttributes(scalingSize); - this.y_handle = new AxisPainter(null, this.yaxis); - if (opts.v7) { - this.y_handle.setPadName(this.getPadName()); - this.y_handle.snapid = this.snapid; - } - this.y_handle.configureAxis('yaxis', this.ymin, this.ymax, ymin, ymax, false, [grminy, grmaxy], - { log: pad && !opts.use_y_for_z ? pad.fLogy : 0 }); - this.y_handle.assignFrameMembers(this, 'y'); - this.y_handle.extractDrawAttributes(scalingSize); + /** @summary Fill context menu for graphical attributes in painter + * @private */ + addAttributesMenu(painter, preffix) { + // this method used to fill entries for different attributes of the object + // like TAttFill, TAttLine, .... + // all menu call-backs need to be rebind, while menu can be used from other painter - this.z_handle = new AxisPainter(null, this.zaxis); - if (opts.v7) { - this.z_handle.setPadName(this.getPadName()); - this.z_handle.snapid = this.snapid; - } - this.z_handle.configureAxis('zaxis', this.zmin, this.zmax, zmin, zmax, false, [grminz, grmaxz], - { log: pad ? pad.fLogz : 0 }); - this.z_handle.assignFrameMembers(this, 'z'); - this.z_handle.extractDrawAttributes(scalingSize); + if (!preffix) preffix = ''; - this.setRootPadRange(pad, true); // set some coordinates typical for 3D projections in ROOT + if (painter.lineatt?.used) { + this.add(`sub:${preffix}Line att`); + this.addSizeMenu('width', 1, 10, 1, painter.lineatt.width, + arg => { painter.lineatt.change(undefined, arg); painter.interactiveRedraw(true, `exec:SetLineWidth(${arg})`); }); + this.addColorMenu('color', painter.lineatt.color, + arg => { painter.lineatt.change(arg); painter.interactiveRedraw(true, getColorExec(arg, 'SetLineColor')); }); + this.addLineStyleMenu('style', painter.lineatt.style, id => { + painter.lineatt.change(undefined, undefined, id); + painter.interactiveRedraw(true, `exec:SetLineStyle(${id})`); + }); + this.add('endsub:'); - let textMaterials = {}, lineMaterials = {}, text_scale = 1, - xticks = this.x_handle.createTicks(false, true), - yticks = this.y_handle.createTicks(false, true), - zticks = this.z_handle.createTicks(false, true); + if (painter.lineatt?.excl_side) { + this.add('sub:Exclusion'); + this.add('sub:side'); + for (let side = -1; side <= 1; ++side) { + this.addchk((painter.lineatt.excl_side === side), side, side, + arg => { painter.lineatt.changeExcl(parseInt(arg)); painter.interactiveRedraw(); }); + } + this.add('endsub:'); - function getLineMaterial(handle, kind) { - let color = (kind == 'ticks') ? handle.ticksColor : handle.lineatt.color, - linewidth = (kind == 'ticks') ? handle.ticksWidth : handle.lineatt.width; - if (!color) color = 'black'; - let name = `${color}_${linewidth}`; - if (!lineMaterials[name]) - lineMaterials[name] = new LineBasicMaterial({ color, linewidth, vertexColors: false }); - return lineMaterials[name]; - } + this.addSizeMenu('width', 10, 100, 10, painter.lineatt.excl_width, + arg => { painter.lineatt.changeExcl(undefined, arg); painter.interactiveRedraw(); }); - function getTextMaterial(handle, kind) { - let color = (kind == 'title') ? handle.titleFont?.color : handle.labelsFont?.color; - if (!color) color = 'black'; - if (!textMaterials[color]) - textMaterials[color] = new MeshBasicMaterial({ color, vertexColors: false }); - return textMaterials[color]; - } + this.add('endsub:'); + } + } - // main element, where all axis elements are placed - let top = new Object3D(); - top.axis_draw = true; // mark element as axis drawing - toplevel.add(top); + if (painter.fillatt?.used) { + this.add(`sub:${preffix}Fill att`); + this.addColorMenu('color', painter.fillatt.colorindx, arg => { + painter.fillatt.change(arg, undefined, painter.getCanvSvg()); + painter.interactiveRedraw(true, getColorExec(arg, 'SetFillColor')); + }, painter.fillatt.kind); + this.addFillStyleMenu('style', painter.fillatt.pattern, painter.fillatt.colorindx, painter, id => { + painter.fillatt.change(undefined, id, painter.getCanvSvg()); + painter.interactiveRedraw(true, `exec:SetFillStyle(${id})`); + }); + this.add('endsub:'); + } - let ticks = [], lbls = [], maxtextheight = 0; + if (painter.markeratt?.used) { + this.add(`sub:${preffix}Marker att`); + this.addColorMenu('color', painter.markeratt.color, + arg => { painter.markeratt.change(arg); painter.interactiveRedraw(true, getColorExec(arg, 'SetMarkerColor')); }); + this.addSizeMenu('size', 0.5, 6, 0.5, painter.markeratt.size, + arg => { painter.markeratt.change(undefined, undefined, arg); painter.interactiveRedraw(true, `exec:SetMarkerSize(${arg})`); }); - while (xticks.next()) { - let grx = xticks.grpos, - is_major = xticks.kind === 1, - lbl = this.x_handle.format(xticks.tick, 2); + this.add('sub:style'); + const supported = [1, 2, 3, 4, 5, 6, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]; - if (xticks.last_major()) { - if (!this.x_handle.fTitle) lbl = 'x'; - } else if (lbl === null) { - is_major = false; lbl = ''; + for (let n = 0; n < supported.length; ++n) { + const clone = new TAttMarkerHandler({ style: supported[n], color: painter.markeratt.color, size: 1.7 }), + svg = `${supported[n].toString()}`; + + this.addchk(painter.markeratt.style === supported[n], svg, supported[n], + arg => { painter.markeratt.change(undefined, parseInt(arg)); painter.interactiveRedraw(true, `exec:SetMarkerStyle(${arg})`); }); + } + this.add('endsub:'); + this.add('endsub:'); } - if (is_major && lbl && opts.draw) { - let text3d = new TextGeometry(lbl, { font: HelveticerRegularFont, size: this.x_handle.labelsFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - let draw_width = text3d.boundingBox.max.x - text3d.boundingBox.min.x, - draw_height = text3d.boundingBox.max.y - text3d.boundingBox.min.y; - text3d.center = true; // place central + if (painter.textatt?.used) { + this.add(`sub:${preffix}Text att`); - text3d.offsety = this.x_handle.labelsOffset + (grmaxy - grminy) * 0.005; + this.addFontMenu('font', painter.textatt.font, + arg => { painter.textatt.change(arg); painter.interactiveRedraw(true, `exec:SetTextFont(${arg})`); }); - maxtextheight = Math.max(maxtextheight, draw_height); + const rel = painter.textatt.size < 1.0; - text3d.grx = grx; - lbls.push(text3d); + this.addSizeMenu('size', rel ? 0.03 : 6, rel ? 0.20 : 26, rel ? 0.01 : 2, painter.textatt.size, + arg => { painter.textatt.change(undefined, parseFloat(arg)); painter.interactiveRedraw(true, `exec:SetTextSize(${arg})`); }); - let space = 0; - if (!xticks.last_major()) { - space = (xticks.next_major_grpos() - grx); - if (draw_width > 0) - text_scale = Math.min(text_scale, 0.9*space/draw_width); - } + this.addColorMenu('color', painter.textatt.color, + arg => { painter.textatt.change(undefined, undefined, arg); painter.interactiveRedraw(true, getColorExec(arg, 'SetTextColor')); }); - if (this.x_handle.isCenteredLabels()) { - if (!space) space = Math.min(grx - grminx, grmaxx - grx); - text3d.grx += space/2; - } - } + this.addAlignMenu('align', painter.textatt.align, arg => { + painter.textatt.change(undefined, undefined, undefined, arg); painter.interactiveRedraw(true, `exec:SetTextAlign(${arg})`); + }); - ticks.push(grx,0,0, grx,this.x_handle.ticksSize*(is_major ? -1 : -0.6),0); - } + this.addSizeMenu('angle', -180, 180, 45, painter.textatt.angle, + arg => { painter.textatt.change(undefined, undefined, undefined, undefined, parseFloat(arg)); painter.interactiveRedraw(true, `exec:SetTextAngle(${arg})`); }); - if (this.x_handle.fTitle && opts.draw) { - const text3d = new TextGeometry(translateLaTeX(this.x_handle.fTitle), { font: HelveticerRegularFont, size: this.x_handle.titleFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - text3d.center = this.x_handle.titleCenter; - text3d.opposite = this.x_handle.titleOpposite; - text3d.offsety = 1.6 * this.x_handle.titleOffset + (grmaxy - grminy) * 0.005; - text3d.grx = (grminx + grmaxx)/2; // default position for centered title - text3d.kind = 'title'; - lbls.push(text3d); + this.add('endsub:'); + } } - this.get3dZoomCoord = function(point, kind) { - // return axis coordinate from intersection point with axis geometry - let pos = point[kind], min = this[`scale_${kind}min`], max = this[`scale_${kind}max`]; + /** @summary Fill context menu for axis + * @private */ + addTAxisMenu(EAxisBits, painter, faxis, kind) { + const is_gaxis = faxis._typename === clTGaxis; + + this.add('Divisions', () => this.input('Set Ndivisions', faxis.fNdivisions, 'int', 0).then(val => { + faxis.fNdivisions = val; painter.interactiveRedraw('pad', `exec:SetNdivisions(${val})`, kind); + })); - switch(kind) { - case 'x': pos = (pos + this.size_x3d)/2/this.size_x3d; break; - case 'y': pos = (pos + this.size_y3d)/2/this.size_y3d; break; - case 'z': pos = pos/2/this.size_z3d; break; + this.add('sub:Labels'); + this.addchk(faxis.TestBit(EAxisBits.kCenterLabels), 'Center', + arg => { faxis.InvertBit(EAxisBits.kCenterLabels); painter.interactiveRedraw('pad', `exec:CenterLabels(${arg})`, kind); }); + this.addchk(faxis.TestBit(EAxisBits.kLabelsVert), 'Rotate', + arg => { faxis.InvertBit(EAxisBits.kLabelsVert); painter.interactiveRedraw('pad', `exec:SetBit(TAxis::kLabelsVert,${arg})`, kind); }); + this.addColorMenu('Color', faxis.fLabelColor, + arg => { faxis.fLabelColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetLabelColor'), kind); }); + this.addSizeMenu('Offset', -0.02, 0.1, 0.01, faxis.fLabelOffset, + arg => { faxis.fLabelOffset = arg; painter.interactiveRedraw('pad', `exec:SetLabelOffset(${arg})`, kind); }); + let a = faxis.fLabelSize >= 1; + this.addSizeMenu('Size', a ? 2 : 0.02, a ? 30 : 0.11, a ? 2 : 0.01, faxis.fLabelSize, + arg => { faxis.fLabelSize = arg; painter.interactiveRedraw('pad', `exec:SetLabelSize(${arg})`, kind); }); + this.add('endsub:'); + this.add('sub:Title'); + this.add('SetTitle', () => { + this.input('Enter axis title', faxis.fTitle).then(t => { + faxis.fTitle = t; + painter.interactiveRedraw('pad', `exec:SetTitle("${t}")`, kind); + }); + }); + this.addchk(faxis.TestBit(EAxisBits.kCenterTitle), 'Center', + arg => { faxis.InvertBit(EAxisBits.kCenterTitle); painter.interactiveRedraw('pad', `exec:CenterTitle(${arg})`, kind); }); + this.addchk(faxis.TestBit(EAxisBits.kOppositeTitle), 'Opposite', + () => { faxis.InvertBit(EAxisBits.kOppositeTitle); painter.redrawPad(); }); + this.addchk(faxis.TestBit(EAxisBits.kRotateTitle), 'Rotate', + arg => { faxis.InvertBit(EAxisBits.kRotateTitle); painter.interactiveRedraw('pad', is_gaxis ? `exec:SetBit(TAxis::kRotateTitle, ${arg})` : `exec:RotateTitle(${arg})`, kind); }); + if (is_gaxis) { + this.addColorMenu('Color', faxis.fTextColor, + arg => { faxis.fTextColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetTitleColor'), kind); }); + } else { + this.addColorMenu('Color', faxis.fTitleColor, + arg => { faxis.fTitleColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetTitleColor'), kind); }); } - if (this['log'+kind]) { - pos = Math.exp(Math.log(min) + pos*(Math.log(max)-Math.log(min))); + this.addSizeMenu('Offset', 0, 3, 0.2, faxis.fTitleOffset, + arg => { faxis.fTitleOffset = arg; painter.interactiveRedraw('pad', `exec:SetTitleOffset(${arg})`, kind); }); + a = faxis.fTitleSize >= 1; + this.addSizeMenu('Size', a ? 2 : 0.02, a ? 30 : 0.11, a ? 2 : 0.01, faxis.fTitleSize, + arg => { faxis.fTitleSize = arg; painter.interactiveRedraw('pad', `exec:SetTitleSize(${arg})`, kind); }); + this.add('endsub:'); + this.add('sub:Ticks'); + if (is_gaxis) { + this.addColorMenu('Color', faxis.fLineColor, + arg => { faxis.fLineColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetLineColor'), kind); }); + this.addSizeMenu('Size', -0.05, 0.055, 0.01, faxis.fTickSize, + arg => { faxis.fTickSize = arg; painter.interactiveRedraw('pad', `exec:SetTickLength(${arg})`, kind); }); } else { - pos = min + pos*(max-min); + this.addColorMenu('Color', faxis.fAxisColor, + arg => { faxis.fAxisColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetAxisColor'), kind); }); + this.addSizeMenu('Size', -0.05, 0.055, 0.01, faxis.fTickLength, + arg => { faxis.fTickLength = arg; painter.interactiveRedraw('pad', `exec:SetTickLength(${arg})`, kind); }); } - return pos; - }; + this.add('endsub:'); - const createZoomMesh = (kind, size_3d, use_y_for_z) => { - let positions, geom = new BufferGeometry(), tsz = Math.max(this[kind+'_handle'].ticksSize, 0.005 * size_3d); - if (kind === 'z') - positions = new Float32Array([0,0,0, tsz*4,0,2*size_3d, tsz*4,0,0, 0,0,0, 0,0,2*size_3d, tsz*4,0,2*size_3d]); - else - positions = new Float32Array([-size_3d,0,0, size_3d,-tsz*4,0, size_3d,0,0, -size_3d,0,0, -size_3d,-tsz*4,0, size_3d,-tsz*4,0]); + if (is_gaxis) { + this.add('Options', () => this.input('Enter TGaxis options like +L or -G', faxis.fChopt, 'string').then(arg => { + faxis.fChopt = arg; painter.interactiveRedraw('pad', `exec:SetOption("${arg}")`, kind); + })); + } + } - geom.setAttribute('position', new BufferAttribute(positions, 3)); - geom.computeVertexNormals(); + /** @summary Fill menu to edit settings properties + * @private */ + addSettingsMenu(with_hierarchy, alone, handle_func) { + if (alone) + this.add('header:Settings'); + else + this.add('sub:Settings'); - let material = new MeshBasicMaterial({ transparent: true, vertexColors: false, side: DoubleSide, opacity: 0 }), - mesh = new Mesh(geom, material); - mesh.zoom = kind; - mesh.size_3d = size_3d; - mesh.tsz = tsz; - mesh.use_y_for_z = use_y_for_z; - if (kind == 'y') mesh.rotateZ(Math.PI/2).rotateX(Math.PI); + this.add('sub:Files'); - mesh.v1 = new Vector3(positions[0], positions[1], positions[2]); - mesh.v2 = new Vector3(positions[6], positions[7], positions[8]); - mesh.v3 = new Vector3(positions[3], positions[4], positions[5]); + if (with_hierarchy) { + this.addchk(settings.OnlyLastCycle, 'Last cycle', flag => { + settings.OnlyLastCycle = flag; + if (handle_func) handle_func('refresh'); + }); - mesh.globalIntersect = function(raycaster) { - if (!this.v1 || !this.v2 || !this.v3) return undefined; + this.addchk(!settings.SkipStreamerInfos, 'Streamer infos', flag => { + settings.SkipStreamerInfos = !flag; + if (handle_func) handle_func('refresh'); + }); + } - let plane = new Plane(); - plane.setFromCoplanarPoints(this.v1, this.v2, this.v3); - plane.applyMatrix4(this.matrixWorld); + this.addchk(settings.UseStamp, 'Use stamp arg', flag => { settings.UseStamp = flag; }); + this.addSizeMenu('Max ranges', 1, 1000, [1, 10, 20, 50, 200, 1000], settings.MaxRanges, value => { settings.MaxRanges = value; }, 'Maximal number of ranges in single http request'); - let v1 = raycaster.ray.origin.clone(), - v2 = v1.clone().addScaledVector(raycaster.ray.direction, 1e10), - pnt = plane.intersectLine(new Line3(v1,v2), new Vector3()); + this.addchk(settings.HandleWrongHttpResponse, 'Handle wrong http response', flag => { settings.HandleWrongHttpResponse = flag; }); + this.addchk(settings.WithCredentials, 'With credentials', flag => { settings.WithCredentials = flag; }, 'Submit http request with user credentials'); - if (!pnt) return undefined; + this.add('endsub:'); - let min = -this.size_3d, max = this.size_3d; - if (this.zoom === 'z') { min = 0; max = 2*this.size_3d; } + this.add('sub:Toolbar'); + this.addchk(settings.ToolBar === false, 'Off', flag => { settings.ToolBar = !flag; }); + this.addchk(settings.ToolBar === true, 'On', flag => { settings.ToolBar = flag; }); + this.addchk(settings.ToolBar === 'popup', 'Popup', flag => { settings.ToolBar = flag ? 'popup' : false; }); + this.add('separator'); + this.addchk(settings.ToolBarSide === 'left', 'Left side', flag => { settings.ToolBarSide = flag ? 'left' : 'right'; }); + this.addchk(settings.ToolBarVert, 'Vertical', flag => { settings.ToolBarVert = flag; }); + this.add('endsub:'); - if (pnt[this.zoom] < min) - pnt[this.zoom] = min; - else if (pnt[this.zoom] > max) - pnt[this.zoom] = max; + this.add('sub:Interactive'); + this.addchk(settings.Tooltip, 'Tooltip', flag => { settings.Tooltip = flag; }); + this.addchk(settings.ContextMenu, 'Context menus', flag => { settings.ContextMenu = flag; }); + this.add('sub:Zooming'); + this.addchk(settings.Zooming, 'Global', flag => { settings.Zooming = flag; }); + this.addchk(settings.ZoomMouse, 'Mouse', flag => { settings.ZoomMouse = flag; }); + this.addchk(settings.ZoomWheel, 'Wheel', flag => { settings.ZoomWheel = flag; }); + this.addchk(settings.ZoomTouch, 'Touch', flag => { settings.ZoomTouch = flag; }); + this.add('endsub:'); + this.addchk(settings.HandleKeys, 'Keypress handling', flag => { settings.HandleKeys = flag; }); + this.addchk(settings.MoveResize, 'Move and resize', flag => { settings.MoveResize = flag; }); + this.addchk(settings.DragAndDrop, 'Drag and drop', flag => { settings.DragAndDrop = flag; }); + this.addchk(settings.DragGraphs, 'Drag graph points', flag => { settings.DragGraphs = flag; }); + this.addchk(settings.ProgressBox, 'Progress box', flag => { settings.ProgressBox = flag; }); + this.add('endsub:'); - return pnt; - }; + this.add('sub:Drawing'); + this.addSelectMenu('Optimize', ['None', 'Smart', 'Always'], settings.OptimizeDraw, value => { settings.OptimizeDraw = value; }); + this.addPaletteMenu(settings.Palette, pal => { settings.Palette = pal; }); + this.addchk(settings.AutoStat, 'Auto stat box', flag => { settings.AutoStat = flag; }); + this.addSelectMenu('Latex', ['Off', 'Symbols', 'Normal', 'MathJax', 'Force MathJax'], settings.Latex, value => { settings.Latex = value; }); + this.addSelectMenu('3D rendering', ['Default', 'WebGL', 'Image'], settings.Render3D, value => { settings.Render3D = value; }); + this.addSelectMenu('WebGL embeding', ['Default', 'Overlay', 'Embed'], settings.Embed3D, value => { settings.Embed3D = value; }); - mesh.showSelection = function(pnt1, pnt2) { - // used to show selection + this.add('endsub:'); - let tgtmesh = this.children ? this.children[0] : null, gg, kind = this.zoom; - if (!pnt1 || !pnt2) { - if (tgtmesh) { - this.remove(tgtmesh); - disposeThreejsObject(tgtmesh); - } - return tgtmesh; - } + this.add('sub:Geometry'); + this.add('Grad per segment: ' + settings.GeoGradPerSegm, () => this.input('Grad per segment in geometry', settings.GeoGradPerSegm, 'int', 1, 60).then(val => { settings.GeoGradPerSegm = val; })); + this.addchk(settings.GeoCompressComp, 'Compress composites', flag => { settings.GeoCompressComp = flag; }); + this.add('endsub:'); - if (!this.geometry) return false; + if (with_hierarchy) { + this.add('Hierarchy limit: ' + settings.HierarchyLimit, () => this.input('Max number of items in hierarchy', settings.HierarchyLimit, 'int', 10, 100000).then(val => { + settings.HierarchyLimit = val; + if (handle_func) handle_func('refresh'); + })); + } - if (!tgtmesh) { - gg = this.geometry.clone(); - let pos = gg.getAttribute('position').array; + this.add('Dark mode: ' + (settings.DarkMode ? 'On' : 'Off'), () => { + settings.DarkMode = !settings.DarkMode; + if (handle_func) handle_func('dark'); + }); - // original vertices [0, 2, 1, 0, 3, 2] - if (kind == 'z') pos[6] = pos[3] = pos[15] = this.tsz; - else pos[4] = pos[16] = pos[13] = -this.tsz; - tgtmesh = new Mesh(gg, new MeshBasicMaterial({ color: 0xFF00, side: DoubleSide, vertexColors: false })); - this.add(tgtmesh); - } else { - gg = tgtmesh.geometry; - } + const setStyleField = arg => { gStyle[arg.slice(1)] = parseInt(arg[0]); }, + addStyleIntField = (name, field, arr) => { + this.add('sub:' + name); + for (let v = 0; v < arr.length; ++v) + this.addchk(gStyle[field] === v, arr[v], `${v}${field}`, setStyleField); + this.add('endsub:'); + }; - let pos = gg.getAttribute('position').array; + this.add('sub:gStyle'); - if (kind == 'z') { - pos[2] = pos[11] = pos[8] = pnt1[kind]; - pos[5] = pos[17] = pos[14] = pnt2[kind]; - } else { - pos[0] = pos[9] = pos[12] = pnt1[kind]; - pos[6] = pos[3] = pos[15] = pnt2[kind]; - } + this.add('sub:Canvas'); + this.addColorMenu('Color', gStyle.fCanvasColor, col => { gStyle.fCanvasColor = col; }); + this.addchk(gStyle.fOptDate, 'Draw date', flag => { gStyle.fOptDate = flag ? 1 : 0; }); + this.addchk(gStyle.fOptFile, 'Draw item', flag => { gStyle.fOptFile = flag ? 1 : 0; }); + this.addSizeMenu('Date X', 0.01, 0.1, 0.01, gStyle.fDateX, x => { gStyle.fDateX = x; }, 'configure gStyle.fDateX for date/item name drawings'); + this.addSizeMenu('Date Y', 0.01, 0.1, 0.01, gStyle.fDateY, y => { gStyle.fDateY = y; }, 'configure gStyle.fDateY for date/item name drawings'); + this.add('endsub:'); - gg.getAttribute('position').needsUpdate = true; + this.add('sub:Pad'); + this.addColorMenu('Color', gStyle.fPadColor, col => { gStyle.fPadColor = col; }); + this.add('sub:Grid'); + this.addchk(gStyle.fPadGridX, 'X', flag => { gStyle.fPadGridX = flag; }); + this.addchk(gStyle.fPadGridY, 'Y', flag => { gStyle.fPadGridY = flag; }); + this.addColorMenu('Color', gStyle.fGridColor, col => { gStyle.fGridColor = col; }); + this.addSizeMenu('Width', 1, 10, 1, gStyle.fGridWidth, w => { gStyle.fGridWidth = w; }); + this.addLineStyleMenu('Style', gStyle.fGridStyle, st => { gStyle.fGridStyle = st; }); + this.add('endsub:'); + addStyleIntField('Ticks X', 'fPadTickX', ['normal', 'ticks on both sides', 'labels on both sides']); + addStyleIntField('Ticks Y', 'fPadTickY', ['normal', 'ticks on both sides', 'labels on both sides']); + addStyleIntField('Log X', 'fOptLogx', ['off', 'on', 'log 2']); + addStyleIntField('Log Y', 'fOptLogy', ['off', 'on', 'log 2']); + addStyleIntField('Log Z', 'fOptLogz', ['off', 'on', 'log 2']); + this.add('endsub:'); - return true; - }; + this.add('sub:Frame'); + this.addColorMenu('Fill color', gStyle.fFrameFillColor, col => { gStyle.fFrameFillColor = col; }); + this.addFillStyleMenu('Fill style', gStyle.fFrameFillStyle, gStyle.fFrameFillColor, null, id => { gStyle.fFrameFillStyle = id; }); + this.addColorMenu('Line color', gStyle.fFrameLineColor, col => { gStyle.fFrameLineColor = col; }); + this.addSizeMenu('Line width', 1, 10, 1, gStyle.fFrameLineWidth, w => { gStyle.fFrameLineWidth = w; }); + this.addLineStyleMenu('Line style', gStyle.fFrameLineStyle, st => { gStyle.fFrameLineStyle = st; }); + this.addSizeMenu('Border size', 0, 10, 1, gStyle.fFrameBorderSize, sz => { gStyle.fFrameBorderSize = sz; }); + // fFrameBorderMode: 0, + this.add('sub:Margins'); + this.addSizeMenu('Bottom', 0, 0.5, 0.05, gStyle.fPadBottomMargin, v => { gStyle.fPadBottomMargin = v; }); + this.addSizeMenu('Top', 0, 0.5, 0.05, gStyle.fPadTopMargin, v => { gStyle.fPadTopMargin = v; }); + this.addSizeMenu('Left', 0, 0.5, 0.05, gStyle.fPadLeftMargin, v => { gStyle.fPadLeftMargin = v; }); + this.addSizeMenu('Right', 0, 0.5, 0.05, gStyle.fPadRightMargin, v => { gStyle.fPadRightMargin = v; }); + this.add('endsub:'); + this.add('endsub:'); - return mesh; - }; + this.add('sub:Title'); + this.addColorMenu('Fill color', gStyle.fTitleColor, col => { gStyle.fTitleColor = col; }); + this.addFillStyleMenu('Fill style', gStyle.fTitleStyle, gStyle.fTitleColor, null, id => { gStyle.fTitleStyle = id; }); + this.addColorMenu('Text color', gStyle.fTitleTextColor, col => { gStyle.fTitleTextColor = col; }); + this.addSizeMenu('Border size', 0, 10, 1, gStyle.fTitleBorderSize, sz => { gStyle.fTitleBorderSize = sz; }); + this.addSizeMenu('Font size', 0.01, 0.1, 0.01, gStyle.fTitleFontSize, sz => { gStyle.fTitleFontSize = sz; }); + this.addFontMenu('Font', gStyle.fTitleFont, fnt => { gStyle.fTitleFont = fnt; }); + this.addSizeMenu('X: ' + gStyle.fTitleX.toFixed(2), 0.0, 1.0, 0.1, gStyle.fTitleX, v => { gStyle.fTitleX = v; }); + this.addSizeMenu('Y: ' + gStyle.fTitleY.toFixed(2), 0.0, 1.0, 0.1, gStyle.fTitleY, v => { gStyle.fTitleY = v; }); + this.addSizeMenu('W: ' + gStyle.fTitleW.toFixed(2), 0.0, 1.0, 0.1, gStyle.fTitleW, v => { gStyle.fTitleW = v; }); + this.addSizeMenu('H: ' + gStyle.fTitleH.toFixed(2), 0.0, 1.0, 0.1, gStyle.fTitleH, v => { gStyle.fTitleH = v; }); + this.add('endsub:'); - let xcont = new Object3D(), xtickslines; - xcont.position.set(0, grminy, grminz); - xcont.rotation.x = 1/4*Math.PI; - xcont.xyid = 2; + this.add('sub:Stat box'); + this.addColorMenu('Fill color', gStyle.fStatColor, col => { gStyle.fStatColor = col; }); + this.addFillStyleMenu('Fill style', gStyle.fStatStyle, gStyle.fStatColor, null, id => { gStyle.fStatStyle = id; }); + this.addColorMenu('Text color', gStyle.fStatTextColor, col => { gStyle.fStatTextColor = col; }); + this.addSizeMenu('Border size', 0, 10, 1, gStyle.fStatBorderSize, sz => { gStyle.fStatBorderSize = sz; }); + this.addSizeMenu('Font size', 0, 30, 5, gStyle.fStatFontSize, sz => { gStyle.fStatFontSize = sz; }); + this.addFontMenu('Font', gStyle.fStatFont, fnt => { gStyle.fStatFont = fnt; }); + this.add('Stat format', () => this.input('Stat format', gStyle.fStatFormat).then(fmt => { gStyle.fStatFormat = fmt; })); + this.addSizeMenu('X: ' + gStyle.fStatX.toFixed(2), 0.2, 1.0, 0.1, gStyle.fStatX, v => { gStyle.fStatX = v; }); + this.addSizeMenu('Y: ' + gStyle.fStatY.toFixed(2), 0.2, 1.0, 0.1, gStyle.fStatY, v => { gStyle.fStatY = v; }); + this.addSizeMenu('Width: ' + gStyle.fStatW.toFixed(2), 0.1, 1.0, 0.1, gStyle.fStatW, v => { gStyle.fStatW = v; }); + this.addSizeMenu('Height: ' + gStyle.fStatH.toFixed(2), 0.1, 1.0, 0.1, gStyle.fStatH, v => { gStyle.fStatH = v; }); + this.add('endsub:'); - if (opts.draw) { - xtickslines = createLineSegments(ticks, getLineMaterial(this.x_handle, 'ticks')); - xcont.add(xtickslines); - } + this.add('sub:Legend'); + this.addColorMenu('Fill color', gStyle.fLegendFillColor, col => { gStyle.fLegendFillColor = col; }); + this.addSizeMenu('Border size', 0, 10, 1, gStyle.fLegendBorderSize, sz => { gStyle.fLegendBorderSize = sz; }); + this.addFontMenu('Font', gStyle.fLegendFont, fnt => { gStyle.fLegendFont = fnt; }); + this.addSizeMenu('Text size', 0, 0.1, 0.01, gStyle.fLegendTextSize, v => { gStyle.fLegendTextSize = v; }, 'legend text size, when 0 - auto adjustment is used'); + this.add('endsub:'); - lbls.forEach(lbl => { - let w = lbl.boundingBox.max.x - lbl.boundingBox.min.x, - posx = lbl.center ? lbl.grx - w/2 : (lbl.opposite ? grminx : grmaxx - w), - m = new Matrix4(); - // matrix to swap y and z scales and shift along z to its position - m.set(text_scale, 0, 0, posx, - 0, text_scale, 0, -maxtextheight*text_scale - this.x_handle.ticksSize - lbl.offsety, - 0, 0, 1, 0, - 0, 0, 0, 1); + this.add('sub:Histogram'); + this.addchk(gStyle.fOptTitle === 1, 'Hist title', flag => { gStyle.fOptTitle = flag ? 1 : 0; }); + this.addchk(gStyle.fOrthoCamera, 'Orthographic camera', flag => { gStyle.fOrthoCamera = flag; }); + this.addchk(gStyle.fHistMinimumZero, 'Base0', flag => { gStyle.fHistMinimumZero = flag; }, 'when true, BAR and LEGO drawing using base = 0'); + this.add('Text format', () => this.input('Paint text format', gStyle.fPaintTextFormat).then(fmt => { gStyle.fPaintTextFormat = fmt; })); + this.add('Time offset', () => this.input('Time offset in seconds, default is 788918400 for 1/1/1995', gStyle.fTimeOffset, 'int').then(ofset => { gStyle.fTimeOffset = ofset; })); + this.addSizeMenu('ErrorX: ' + gStyle.fErrorX.toFixed(2), 0.0, 1.0, 0.1, gStyle.fErrorX, v => { gStyle.fErrorX = v; }); + this.addSizeMenu('End error', 0, 12, 1, gStyle.fEndErrorSize, v => { gStyle.fEndErrorSize = v; }, 'size in pixels of end error for E1 draw options, gStyle.fEndErrorSize'); + this.addSizeMenu('Top margin', 0.0, 0.5, 0.05, gStyle.fHistTopMargin, v => { gStyle.fHistTopMargin = v; }, 'Margin between histogram top and frame top'); + this.addColorMenu('Fill color', gStyle.fHistFillColor, col => { gStyle.fHistFillColor = col; }); + this.addFillStyleMenu('Fill style', gStyle.fHistFillStyle, gStyle.fHistFillColor, null, id => { gStyle.fHistFillStyle = id; }); + this.addColorMenu('Line color', gStyle.fHistLineColor, col => { gStyle.fHistLineColor = col; }); + this.addSizeMenu('Line width', 1, 10, 1, gStyle.fHistLineWidth, w => { gStyle.fHistLineWidth = w; }); + this.addLineStyleMenu('Line style', gStyle.fHistLineStyle, st => { gStyle.fHistLineStyle = st; }); + this.add('endsub:'); - let mesh = new Mesh(lbl, getTextMaterial(this.x_handle, lbl.kind)); - mesh.applyMatrix4(m); - xcont.add(mesh); - }); + this.add('separator'); + this.add('sub:Predefined'); + ['Modern', 'Plain', 'Bold'].forEach(name => this.addchk((gStyle.fName === name), name, name, selectgStyle)); + this.add('endsub:'); - if (opts.zoom) xcont.add(createZoomMesh('x', this.size_x3d)); - top.add(xcont); + this.add('endsub:'); // gStyle - xcont = new Object3D(); - xcont.position.set(0, grmaxy, grminz); - xcont.rotation.x = 3/4*Math.PI; + this.add('separator'); - if (opts.draw) - xcont.add(new LineSegments(xtickslines.geometry, xtickslines.material)); + this.add('Save settings', () => { + const promise = readSettings(true) ? Promise.resolve(true) : this.confirm('Save settings', 'Pressing OK one agreess that JSROOT will store settings as browser cookies'); + promise.then(res => { if (res) { saveSettings(); saveStyle(); } }); + }, 'Store settings and gStyle as cookies'); + this.add('Delete settings', () => { saveSettings(-1); saveStyle(-1); }, 'Delete settings and gStyle from cookies'); - lbls.forEach(lbl => { - let w = lbl.boundingBox.max.x - lbl.boundingBox.min.x, - posx = (lbl.center ? lbl.grx + w/2 : lbl.opposite ? grminx + w : grmaxx), - m = new Matrix4(); - // matrix to swap y and z scales and shift along z to its position - m.set(-text_scale, 0, 0, posx, - 0, text_scale, 0, -maxtextheight*text_scale - this.x_handle.ticksSize - lbl.offsety, - 0, 0, -1, 0, - 0, 0, 0, 1); - let mesh = new Mesh(lbl, getTextMaterial(this.x_handle, lbl.kind)); - mesh.applyMatrix4(m); - xcont.add(mesh); - }); + if (!alone) this.add('endsub:'); + } - xcont.xyid = 4; - if (opts.zoom) xcont.add(createZoomMesh('x', this.size_x3d)); - top.add(xcont); + /** @summary Run modal dialog + * @return {Promise} with html element inside dialg + * @private */ + async runModal() { + throw Error('runModal() must be reimplemented'); + } - lbls = []; text_scale = 1; maxtextheight = 0; ticks = []; + /** @summary Show modal info dialog + * @param {String} title - title + * @param {String} message - message + * @protected */ + info(title, message) { + return this.runModal(title, `

${message}

`, { height: 120, width: 400, resizable: true }); + } - while (yticks.next()) { - let gry = yticks.grpos, - is_major = (yticks.kind === 1), - lbl = this.y_handle.format(yticks.tick, 2); + /** @summary Show confirm dialog + * @param {String} title - title + * @param {String} message - message + * @return {Promise} with true when 'Ok' pressed or false when 'Cancel' pressed + * @protected */ + async confirm(title, message) { + return this.runModal(title, message, { btns: true, height: 120, width: 400 }).then(elem => { return !!elem; }); + } - if (yticks.last_major()) { - if (!this.y_handle.fTitle) lbl = 'y'; - } else if (lbl === null) { - is_major = false; lbl = ''; - } + /** @summary Input value + * @return {Promise} with input value + * @param {string} title - input dialog title + * @param value - initial value + * @param {string} [kind] - use 'text' (default), 'number', 'float' or 'int' + * @protected */ + async input(title, value, kind, min, max) { + if (!kind) kind = 'text'; + const inp_type = (kind === 'int') ? 'number' : 'text'; + let ranges = ''; + if ((value === undefined) || (value === null)) value = ''; + if (kind === 'int') { + if (min !== undefined) ranges += ` min="${min}"`; + if (max !== undefined) ranges += ` max="${max}"`; + } - if (is_major && lbl && opts.draw) { - const text3d = new TextGeometry(lbl, { font: HelveticerRegularFont, size: this.y_handle.labelsFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - let draw_width = text3d.boundingBox.max.x - text3d.boundingBox.min.x, - draw_height = text3d.boundingBox.max.y - text3d.boundingBox.min.y; - text3d.center = true; + const main_content = + '
'+ + ``+ + '
'; - maxtextheight = Math.max(maxtextheight, draw_height); + return new Promise(resolveFunc => { + this.runModal(title, main_content, { btns: true, height: 150, width: 400 }).then(element => { + if (!element) return; + let val = element.querySelector('.jsroot_dlginp').value; + if (kind === 'float') { + val = parseFloat(val); + if (Number.isFinite(val)) + resolveFunc(val); + } else if (kind === 'int') { + val = parseInt(val); + if (Number.isInteger(val)) + resolveFunc(val); + } else + resolveFunc(val); + }); + }); + } - text3d.gry = gry; - text3d.offsetx = this.y_handle.labelsOffset + (grmaxx - grminx) * 0.005; - lbls.push(text3d); + /** @summary Let input arguments from the method + * @return {Promise} with method argument */ + async showMethodArgsDialog(method) { + const dlg_id = this.menuname + '_dialog'; + let main_content = '
'; - let space = 0; - if (!yticks.last_major()) { - space = (yticks.next_major_grpos() - gry); - if (draw_width > 0) - text_scale = Math.min(text_scale, 0.9*space/draw_width); - } - if (this.y_handle.isCenteredLabels()) { - if (!space) space = Math.min(gry - grminy, grmaxy - gry); - text3d.gry += space/2; - } + for (let n = 0; n < method.fArgs.length; ++n) { + const arg = method.fArgs[n]; + arg.fValue = arg.fDefault; + if (arg.fValue === '""') arg.fValue = ''; + main_content += ` + `; } - ticks.push(0,gry,0, this.y_handle.ticksSize*(is_major ? -1 : -0.6),gry,0); - } - if (this.y_handle.fTitle && opts.draw) { - const text3d = new TextGeometry(translateLaTeX(this.y_handle.fTitle), { font: HelveticerRegularFont, size: this.y_handle.titleFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - text3d.center = this.y_handle.titleCenter; - text3d.opposite = this.y_handle.titleOpposite; - text3d.offsetx = 1.6 * this.y_handle.titleOffset + (grmaxx - grminx) * 0.005; - text3d.gry = (grminy + grmaxy)/2; // default position for centered title - text3d.kind = 'title'; - lbls.push(text3d); - } + main_content += '
'; - if (!opts.use_y_for_z) { - let yticksline, ycont = new Object3D(); - ycont.position.set(grminx, 0, grminz); - ycont.rotation.y = -1/4*Math.PI; - if (opts.draw) { - yticksline = createLineSegments(ticks, getLineMaterial(this.y_handle, 'ticks')); - ycont.add(yticksline); - } + return new Promise(resolveFunc => { + this.runModal(method.fClassName + '::' + method.fName, main_content, { btns: true, height: 100 + method.fArgs.length*60, width: 400, resizable: true }).then(element => { + if (!element) return; + let args = ''; - lbls.forEach(lbl => { + for (let k = 0; k < method.fArgs.length; ++k) { + const arg = method.fArgs[k]; + let value = element.querySelector(`#${dlg_id}_inp${k}`).value; + if (value === '') value = arg.fDefault; + if ((arg.fTitle === 'Option_t*') || (arg.fTitle === 'const char*')) { + // check quotes, + // TODO: need to make more precise checking of escape characters + if (!value) value = '""'; + if (value[0] !== '"') value = '"' + value; + if (value[value.length-1] !== '"') value += '"'; + } - let w = lbl.boundingBox.max.x - lbl.boundingBox.min.x, - posy = lbl.center ? lbl.gry + w/2 : (lbl.opposite ? grminy + w : grmaxy), - m = new Matrix4(); - // matrix to swap y and z scales and shift along z to its position - m.set(0, text_scale, 0, -maxtextheight*text_scale - this.y_handle.ticksSize - lbl.offsetx, - -text_scale, 0, 0, posy, - 0, 0, 1, 0, - 0, 0, 0, 1); + args += (k > 0 ? ',' : '') + value; + } - let mesh = new Mesh(lbl, getTextMaterial(this.y_handle, lbl.kind)); - mesh.applyMatrix4(m); - ycont.add(mesh); + resolveFunc(args); + }); }); + } - ycont.xyid = 3; - if (opts.zoom) ycont.add(createZoomMesh('y', this.size_y3d)); - top.add(ycont); + /** @summary Let input arguments from the Command + * @return {Promise} with command argument */ + async showCommandArgsDialog(cmdname, args) { + const dlg_id = this.menuname + '_dialog'; + let main_content = '
'; - ycont = new Object3D(); - ycont.position.set(grmaxx, 0, grminz); - ycont.rotation.y = -3/4*Math.PI; - if (opts.draw) - ycont.add(new LineSegments(yticksline.geometry, yticksline.material)); + for (let n = 0; n < args.length; ++n) { + main_content += ``+ + ``; + } - lbls.forEach(lbl => { - let w = lbl.boundingBox.max.x - lbl.boundingBox.min.x, - posy = lbl.center ? lbl.gry - w/2 : (lbl.opposite ? grminy : grmaxy - w), - m = new Matrix4(); - m.set(0, text_scale, 0, -maxtextheight*text_scale - this.y_handle.ticksSize - lbl.offsetx, - text_scale, 0, 0, posy, - 0, 0, -1, 0, - 0, 0, 0, 1); + main_content += '
'; - let mesh = new Mesh(lbl, getTextMaterial(this.y_handle, lbl.kind)); - mesh.applyMatrix4(m); - ycont.add(mesh); + return new Promise(resolveFunc => { + this.runModal('Arguments for command ' + cmdname, main_content, { btns: true, height: 110 + args.length*60, width: 400, resizable: true }).then(element => { + if (!element) + return resolveFunc(null); + + const resargs = []; + for (let k = 0; k < args.length; ++k) + resargs.push(element.querySelector(`#${dlg_id}_inp${k}`).value); + resolveFunc(resargs); + }); }); - ycont.xyid = 1; - if (opts.zoom) ycont.add(createZoomMesh('y', this.size_y3d)); - top.add(ycont); } - lbls = []; text_scale = 1; ticks = []; // just array, will be used for the buffer geometry - - let zgridx = null, zgridy = null, lastmajorz = null, maxzlblwidth = 0; +} // class JSRootMenu - if (this.size_z3d) { - zgridx = []; zgridy = []; - } +/** + * @summary Context menu class using plain HTML/JavaScript + * + * @desc Use {@link createMenu} to create instance of the menu + * based on {@link https://github.com/L1quidH2O/ContextMenu.js} + * @private + */ - while (zticks.next()) { - let grz = zticks.grpos, - is_major = (zticks.kind == 1), - lbl = this.z_handle.format(zticks.tick, 2); +class StandaloneMenu extends JSRootMenu { - if (lbl === null) { is_major = false; lbl = ''; } + constructor(painter, menuname, show_event) { + super(painter, menuname, show_event); - if (is_major && lbl && opts.draw) { - let text3d = new TextGeometry(lbl, { font: HelveticerRegularFont, size: this.z_handle.labelsFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - let draw_width = text3d.boundingBox.max.x - text3d.boundingBox.min.x, - draw_height = text3d.boundingBox.max.y - text3d.boundingBox.min.y; - text3d.translate(-draw_width, -draw_height/2, 0); - text3d.grz = grz; - lbls.push(text3d); + this.code = []; + this._use_plain_text = true; + this.stack = [this.code]; + } - if ((lastmajorz !== null) && (draw_height > 0)) - text_scale = Math.min(text_scale, 0.9*(grz - lastmajorz)/draw_height); + native() { return true; } - maxzlblwidth = Math.max(maxzlblwidth, draw_width); + /** @summary Load required modules, noop for that menu class */ + async load() { return this; } - lastmajorz = grz; - } + /** @summary Add menu item + * @param {string} name - item name + * @param {function} func - func called when item is selected */ + add(name, arg, func, title) { + let curr = this.stack[this.stack.length-1]; - // create grid - if (zgridx && is_major) - zgridx.push(grminx,0,grz, grmaxx,0,grz); + if (name === 'separator') + return curr.push({ divider: true }); - if (zgridy && is_major) - zgridy.push(0,grminy,grz, 0,grmaxy,grz); + if (name.indexOf('header:') === 0) + return curr.push({ text: name.slice(7), header: true }); - ticks.push(0,0,grz, this.z_handle.ticksSize*(is_major ? 1 : 0.6),0,grz); - } + if (name === 'endsub:') { + this.stack.pop(); + curr = this.stack[this.stack.length-1]; + if (curr[curr.length-1].sub.length === 0) + curr[curr.length-1].sub = undefined; + return; + } - if (zgridx && (zgridx.length > 0)) { + if (name === 'endcolumn:') + return this.stack.pop(); - const material = new LineDashedMaterial({ color: this.x_handle.ticksColor, dashSize: 2, gapSize: 2 }), - lines1 = createLineSegments(zgridx, material); - lines1.position.set(0,grmaxy,0); - lines1.grid = 2; // mark as grid - lines1.visible = false; - top.add(lines1); + if (isFunc(arg)) { title = func; func = arg; arg = name; } - const lines2 = new LineSegments(lines1.geometry, material); - lines2.position.set(0,grminy,0); - lines2.grid = 4; // mark as grid - lines2.visible = false; - top.add(lines2); - } + const elem = {}; + curr.push(elem); - if (zgridy && (zgridy.length > 0)) { + if (name === 'column:') { + elem.column = true; + elem.sub = []; + this.stack.push(elem.sub); + return; + } - const material = new LineDashedMaterial({ color: this.y_handle.ticksColor, dashSize: 2, gapSize: 2 }), - lines1 = createLineSegments(zgridy, material); + if (name.indexOf('sub:') === 0) { + name = name.slice(4); + elem.sub = []; + this.stack.push(elem.sub); + } - lines1.position.set(grmaxx,0, 0); - lines1.grid = 3; // mark as grid - lines1.visible = false; - top.add(lines1); + if (name.indexOf('chk:') === 0) { + elem.checked = true; + name = name.slice(4); + } else if (name.indexOf('unk:') === 0) { + elem.checked = false; + name = name.slice(4); + } - const lines2 = new LineSegments(lines1.geometry, material); - lines2.position.set(grminx, 0, 0); - lines2.grid = 1; // mark as grid - lines2.visible = false; - top.add(lines2); + elem.text = name; + elem.title = title; + elem.arg = arg; + elem.func = func; } - let zcont = [], zticksline = opts.draw ? createLineSegments(ticks, getLineMaterial(this.z_handle, 'ticks')) : null; - for (let n = 0; n < 4; ++n) { - zcont.push(new Object3D()); + /** @summary Returns size of main menu */ + size() { return this.code.length; } - lbls.forEach((lbl,indx) => { - let m = new Matrix4(), grz = lbl.grz; + /** @summary Build HTML elements of the menu + * @private */ + _buildContextmenu(menu, left, top, loc) { + const doc = getDocument(), + outer = doc.createElement('div'), + container_style = + 'position: absolute; top: 0; user-select: none; z-index: 100000; background-color: rgb(250, 250, 250); margin: 0; padding: 0px; width: auto;'+ + 'min-width: 100px; box-shadow: 0px 0px 10px rgb(0, 0, 0, 0.2); border: 3px solid rgb(215, 215, 215); font-family: Arial, helvetica, sans-serif, serif;'+ + 'font-size: 13px; color: rgb(0, 0, 0, 0.8); line-height: 15px;'; + + // if loc !== doc.body then its a submenu, so it needs to have position: relative; + if (loc === doc.body) { + // delete all elements with className jsroot_ctxt_container + const deleteElems = doc.getElementsByClassName('jsroot_ctxt_container'); + while (deleteElems.length > 0) + deleteElems[0].parentNode.removeChild(deleteElems[0]); - if (this.z_handle.isCenteredLabels()) { - if (indx < lbls.length - 1) - grz = (grz + lbls[indx+1].grz) / 2; - else if (indx > 0) - grz = Math.min(1.5*grz - lbls[indx-1].grz*0.5, grmaxz); - } + outer.className = 'jsroot_ctxt_container'; + outer.style = container_style; + outer.style.position = 'fixed'; + outer.style.left = left + 'px'; + outer.style.top = top + 'px'; + } else if ((left < 0) && (top === left)) { + // column + outer.className = 'jsroot_ctxt_column'; + outer.style.float = 'left'; + outer.style.width = (100/-left).toFixed(1) + '%'; + } else { + outer.className = 'jsroot_ctxt_container'; + outer.style = container_style; + outer.style.left = -loc.offsetLeft + loc.offsetWidth + 'px'; + } - // matrix to swap y and z scales and shift along z to its position - m.set(-text_scale, 0, 0, this.z_handle.ticksSize + (grmaxx - grminx) * 0.005 + this.z_handle.labelsOffset, - 0, 0, 1, 0, - 0, text_scale, 0, grz); - let mesh = new Mesh(lbl, getTextMaterial(this.z_handle)); - mesh.applyMatrix4(m); - zcont[n].add(mesh); + let need_check_area = false, ncols = 0; + menu.forEach(d => { + if (d.checked) need_check_area = true; + if (d.column) ncols++; }); - if (this.z_handle.fTitle && opts.draw) { - let text3d = new TextGeometry(translateLaTeX(this.z_handle.fTitle), { font: HelveticerRegularFont, size: this.z_handle.titleFont.size, height: 0, curveSegments: 5 }); - text3d.computeBoundingBox(); - let draw_width = text3d.boundingBox.max.x - text3d.boundingBox.min.x, - posz = this.z_handle.titleCenter ? (grmaxz + grminz - draw_width)/2 : (this.z_handle.titleOpposite ? grminz : grmaxz - draw_width); + menu.forEach(d => { + if (ncols > 0) { + outer.style.display = 'flex'; + if (d.column) this._buildContextmenu(d.sub, -ncols, -ncols, outer); + return; + } - text3d.rotateZ(Math.PI/2); + if (d.divider) { + const hr = doc.createElement('hr'); + hr.style = 'width: 85%; margin: 3px auto; border: 1px solid rgb(0, 0, 0, 0.15)'; + outer.appendChild(hr); + return; + } - let m = new Matrix4(); - m.set(-text_scale, 0, 0, this.z_handle.ticksSize + (grmaxx - grminx) * 0.005 + maxzlblwidth + this.z_handle.titleOffset, - 0, 0, 1, 0, - 0, text_scale, 0, posz); - let mesh = new Mesh(text3d, getTextMaterial(this.z_handle, 'title')); - mesh.applyMatrix4(m); - zcont[n].add(mesh); - } + const item = doc.createElement('div'); + item.style.position = 'relative'; + outer.appendChild(item); - if (opts.draw && zticksline) - zcont[n].add(n == 0 ? zticksline : new LineSegments(zticksline.geometry, zticksline.material)); - if (opts.zoom) - zcont[n].add(createZoomMesh('z', this.size_z3d, opts.use_y_for_z)); + if (d.header) { + item.style = 'background-color: lightblue; padding: 3px 7px; font-weight: bold; border-bottom: 1px;'; + item.innerHTML = d.text; + return; + } - zcont[n].zid = n + 2; - top.add(zcont[n]); - } + const hovArea = doc.createElement('div'); + hovArea.style.width = '100%'; + hovArea.style.height = '100%'; + hovArea.style.display = 'flex'; + hovArea.style.justifyContent = 'space-between'; + hovArea.style.cursor = 'pointer'; + if (d.title) hovArea.setAttribute('title', d.title); - zcont[0].position.set(grminx,grmaxy,0); - zcont[0].rotation.z = 3/4*Math.PI; + item.appendChild(hovArea); + if (!d.text) d.text = 'item'; - zcont[1].position.set(grmaxx,grmaxy,0); - zcont[1].rotation.z = 1/4*Math.PI; + const text = doc.createElement('div'); + text.style = 'margin: 0; padding: 3px 7px; pointer-events: none; white-space: nowrap'; - zcont[2].position.set(grmaxx,grminy,0); - zcont[2].rotation.z = -1/4*Math.PI; + if (d.text.indexOf('= 0) { + if (need_check_area) { + text.style.display = 'flex'; - zcont[3].position.set(grminx,grminy,0); - zcont[3].rotation.z = -3/4*Math.PI; + const chk = doc.createElement('span'); + chk.innerHTML = d.checked ? '\u2713' : ''; + chk.style.display = 'inline-block'; + chk.style.width = '1em'; + text.appendChild(chk); - let linex_material = getLineMaterial(this.x_handle), - linex_geom = createLineSegments([grminx,0,0, grmaxx,0,0], linex_material, null, true); - for(let n = 0; n < 2; ++n) { - let line = new LineSegments(linex_geom, linex_material); - line.position.set(0, grminy, n == 0 ? grminz : grmaxz); - line.xyboxid = 2; line.bottom = (n == 0); - top.add(line); + const sub = doc.createElement('div'); + sub.innerHTML = d.text; + text.appendChild(sub); + } else + text.innerHTML = d.text; + } else { + if (need_check_area) { + const chk = doc.createElement('span'); + chk.innerHTML = d.checked ? '\u2713' : ''; + chk.style.display = 'inline-block'; + chk.style.width = '1em'; + text.appendChild(chk); + } - line = new LineSegments(linex_geom, linex_material); - line.position.set(0, grmaxy, n == 0 ? grminz : grmaxz); - line.xyboxid = 4; line.bottom = (n == 0); - top.add(line); - } + const sub = doc.createElement('span'); + if (d.text.indexOf('') === 0) + sub.textContent = d.text.slice(6, d.text.length-7); + else + sub.textContent = d.text; + text.appendChild(sub); + } - let liney_material = getLineMaterial(this.y_handle), - liney_geom = createLineSegments([0,grminy,0, 0,grmaxy,0], liney_material, null, true); - for(let n = 0; n < 2; ++n) { - let line = new LineSegments(liney_geom, liney_material); - line.position.set(grminx, 0, n == 0 ? grminz : grmaxz); - line.xyboxid = 3; line.bottom = (n == 0); - top.add(line); + hovArea.appendChild(text); - line = new LineSegments(liney_geom, liney_material); - line.position.set(grmaxx, 0, n == 0 ? grminz : grmaxz); - line.xyboxid = 1; line.bottom = (n == 0); - top.add(line); - } + function changeFocus(item, on) { + if (on) { + item.classList.add('jsroot_ctxt_focus'); + item.style['background-color'] = 'rgb(220, 220, 220)'; + } else if (item.classList.contains('jsroot_ctxt_focus')) { + item.style['background-color'] = null; + item.classList.remove('jsroot_ctxt_focus'); + item.querySelector('.jsroot_ctxt_container')?.remove(); + } + } - let linez_material = getLineMaterial(this.z_handle), - linez_geom = createLineSegments([0,0,grminz, 0,0,grmaxz], linez_material, null, true); - for(let n = 0; n < 4; ++n) { - let line = new LineSegments(linez_geom, linez_material); - line.zboxid = zcont[n].zid; - line.position.copy(zcont[n].position); - top.add(line); - } -} + if (d.extraText || d.sub) { + const extraText = doc.createElement('span'); + extraText.className = 'jsroot_ctxt_extraText'; + extraText.style = 'margin: 0; padding: 3px 7px; color: rgb(0, 0, 0, 0.6);'; + extraText.textContent = d.sub ? '\u25B6' : d.extraText; + hovArea.appendChild(extraText); -/** @summary Assign 3D methods for frame painter - * @private */ -function assignFrame3DMethods(fpainter) { - Object.assign(fpainter, { create3DScene, render3D, resize3D, highlightBin3D, set3DOptions, drawXYZ }); -} + if (d.sub && browser.touches) { + extraText.addEventListener('click', evnt => { + evnt.preventDefault(); + evnt.stopPropagation(); + const was_active = item.parentNode.querySelector('.jsroot_ctxt_focus'); + if (was_active) + changeFocus(was_active, false); -/** @summary Draw histograms in 3D mode - * @private */ -function drawBinsLego(painter, is_v7 = false) { + if (item !== was_active) { + changeFocus(item, true); + this._buildContextmenu(d.sub, 0, 0, item); + } + }); + } + } - if (!painter.draw_content) return; + if (!browser.touches) { + hovArea.addEventListener('mouseenter', () => { + if (this.prevHovArea) + this.prevHovArea.style['background-color'] = null; + hovArea.style['background-color'] = 'rgb(235, 235, 235)'; + this.prevHovArea = hovArea; - // Perform TH1/TH2 lego plot with BufferGeometry + outer.childNodes.forEach(chld => changeFocus(chld, false)); - const vertices = Box3D.Vertices, - indicies = Box3D.Indexes, - vnormals = Box3D.Normals, - segments = Box3D.Segments, - // reduced line segments - rsegments = [0, 1, 1, 2, 2, 3, 3, 0], - // reduced vertices - rvertices = [ new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0), new Vector3(1, 0, 0) ], - main = painter.getFramePainter(), - handle = painter.prepareDraw({ rounding: false, use3d: true, extra: 1 }), - i1 = handle.i1, i2 = handle.i2, j1 = handle.j1, j2 = handle.j2, - histo = painter.getHisto(), - basehisto = histo ? histo.$baseh : null, - split_faces = (painter.options.Lego === 11) || (painter.options.Lego === 13), // split each layer on two parts - use16indx = (histo.getBin(i2, j2) < 0xFFFF); // if bin ID fit into 16 bit, use smaller arrays for intersect indexes + if (d.sub) { + changeFocus(item, true); + this._buildContextmenu(d.sub, 0, 0, item); + } + }); + } - if ((i1 >= i2) || (j1 >= j2)) return; + if (d.func) { + item.addEventListener('click', evnt => { + const func = this.painter ? d.func.bind(this.painter) : d.func; + func(d.arg); + evnt.stopPropagation(); + this.remove(); + }); + } + }); - let zmin, zmax, i, j, k, vert, x1, x2, y1, y2, binz1, binz2, reduced, nobottom, notop, - axis_zmin = main.z_handle.getScaleMin(), - axis_zmax = main.z_handle.getScaleMax(); + loc.appendChild(outer); - const getBinContent = (ii,jj,level) => { - // return bin content in binz1, binz2, reduced flags - // return true if bin should be displayed + const docWidth = doc.documentElement.clientWidth, docHeight = doc.documentElement.clientHeight; - binz2 = histo.getBinContent(ii+1, jj+1); - if (basehisto) - binz1 = basehisto.getBinContent(ii+1, jj+1); - else if (painter.options.BaseLine !== false) - binz1 = painter.options.BaseLine; - else - binz1 = painter.options.Zero ? axis_zmin : 0; - if (binz2 < binz1) - [binz1, binz2] = [binz2, binz1]; + // Now determine where the contextmenu will be + if (loc === doc.body) { + if (left + outer.offsetWidth > docWidth) { + // Does sub-contextmenu overflow window width? + outer.style.left = (docWidth - outer.offsetWidth) + 'px'; + } + if (outer.offsetHeight > docHeight) { + // is the contextmenu height larger than the window height? + outer.style.top = 0; + outer.style.overflowY = 'scroll'; + outer.style.overflowX = 'hidden'; + outer.style.height = docHeight + 'px'; + } else if (top + outer.offsetHeight > docHeight) { + // Does contextmenu overflow window height? + outer.style.top = (docHeight - outer.offsetHeight) + 'px'; + } + } else if (outer.className !== 'jsroot_ctxt_column') { + // if its sub-contextmenu + const dimensionsLoc = loc.getBoundingClientRect(), dimensionsOuter = outer.getBoundingClientRect(); - if ((binz1 >= zmax) || (binz2 < zmin)) return false; + // Does sub-contextmenu overflow window width? + if (dimensionsOuter.left + dimensionsOuter.width > docWidth) + outer.style.left = (-loc.offsetLeft - dimensionsOuter.width) + 'px'; - reduced = (binz2 === zmin) || (binz1 >= binz2); - if (!reduced || (level > 0)) return true; + if (dimensionsOuter.height > docHeight) { + // is the sub-contextmenu height larger than the window height? + outer.style.top = -dimensionsOuter.top + 'px'; + outer.style.overflowY = 'scroll'; + outer.style.overflowX = 'hidden'; + outer.style.height = docHeight + 'px'; + } else if (dimensionsOuter.height < docHeight && dimensionsOuter.height > docHeight / 2) { + // is the sub-contextmenu height smaller than the window height AND larger than half of window height? + if (dimensionsOuter.top - docHeight / 2 >= 0) { // If sub-contextmenu is closer to bottom of the screen + outer.style.top = (-dimensionsOuter.top - dimensionsOuter.height + docHeight) + 'px'; + } else { // If sub-contextmenu is closer to top of the screen + outer.style.top = (-dimensionsOuter.top) + 'px'; + } + } else if (dimensionsOuter.top + dimensionsOuter.height > docHeight) { + // Does sub-contextmenu overflow window height? + outer.style.top = (-dimensionsOuter.height + dimensionsLoc.height) + 'px'; + } + } + return outer; + } - if (basehisto) return false; // do not draw empty bins on top of other bins + /** @summary Show standalone menu */ + async show(event) { + this.remove(); - if (painter.options.Zero || (axis_zmin > 0)) return true; + if (!event && this.show_evnt) event = this.show_evnt; - return painter._show_empty_bins; - }; + const doc = getDocument(), + woffset = typeof window === 'undefined' ? { x: 0, y: 0 } : { x: window.pageXOffset, y: window.pageYOffset }; - let levels = [ axis_zmin, axis_zmax ], palette = null; + doc.body.addEventListener('click', this.remove_handler); - // DRAW ALL CUBES + const oldmenu = doc.getElementById(this.menuname); + if (oldmenu) oldmenu.remove(); - if ((painter.options.Lego === 12) || (painter.options.Lego === 14)) { - // drawing colors levels, axis can not exceed palette + this.element = this._buildContextmenu(this.code, (event?.clientX || 0) + woffset.x, (event?.clientY || 0) + woffset.y, doc.body); - if (is_v7) { - palette = main.getHistPalette(); - painter.createContour(main, palette, { full_z_range: true }); - levels = palette.getContour(); - axis_zmin = levels[0]; - axis_zmax = levels[levels.length-1]; - } else { - let cntr = painter.createContour(histo.fContour ? histo.fContour.length : 20, main.lego_zmin, main.lego_zmax); - levels = cntr.arr; - palette = painter.getHistPalette(); - // axis_zmin = levels[0]; - // axis_zmax = levels[levels.length-1]; - } + this.element.setAttribute('id', this.menuname); + + return this; } - for (let nlevel = 0; nlevel < levels.length-1; ++nlevel) { + /** @summary Run modal elements with standalone code */ + async runModal(title, main_content, args) { + if (!args) args = {}; + const dlg_id = this.menuname + '_dialog'; + select(`#${dlg_id}`).remove(); + select(`#${dlg_id}_block`).remove(); - zmin = levels[nlevel]; - zmax = levels[nlevel+1]; + const w = Math.min(args.width || 450, Math.round(0.9*browser.screenWidth)), + block = select('body').append('div') + .attr('id', `${dlg_id}_block`) + .attr('class', 'jsroot_dialog_block') + .attr('style', 'z-index: 100000; position: absolute; inset: 0px; opacity: 0.2; background-color: white'), + element = select('body') + .append('div') + .attr('id', dlg_id) + .attr('class', 'jsroot_dialog') + .style('position', 'absolute') + .style('width', `${w}px`) + .style('left', '50%') + .style('top', '50%') + .style('z-index', 100001) + .attr('tabindex', '0') + .html( + '
'+ + `
${title}
`+ + `
${main_content}
`+ + '
'+ + ''+ + (args.btns ? '' : '') + + '
'); - // artificially extend last level of color palette to maximal visible value - if (palette && (nlevel==levels.length-2) && zmax < axis_zmax) zmax = axis_zmax; + return new Promise(resolveFunc => { + element.on('keyup', evnt => { + if ((evnt.code === 'Enter') || (evnt.code === 'Escape')) { + evnt.preventDefault(); + evnt.stopPropagation(); + resolveFunc(evnt.code === 'Enter' ? element.node() : null); + element.remove(); + block.remove(); + } + }); + element.on('keydown', evnt => { + if ((evnt.code === 'Enter') || (evnt.code === 'Escape')) { + evnt.preventDefault(); + evnt.stopPropagation(); + } + }); + element.selectAll('.jsroot_dialog_button').on('click', evnt => { + resolveFunc(args.btns && (select(evnt.target).text() === 'Ok') ? element.node() : null); + element.remove(); + block.remove(); + }); - let z1 = 0, z2 = 0, numvertices = 0, num2vertices = 0, - grzmin = main.grz(zmin), grzmax = main.grz(zmax); + let f = element.select('.jsroot_dialog_content').select('input'); + if (f.empty()) f = element.select('.jsroot_dialog_footer').select('button'); + if (!f.empty()) f.node().focus(); + }); + } - // now calculate size of buffer geometry for boxes +} // class StandaloneMenu - for (i = i1; i < i2; ++i) - for (j = j1; j < j2; ++j) { +/** @summary Create JSROOT menu + * @desc See {@link JSRootMenu} class for detailed list of methods + * @param {object} [evnt] - event object like mouse context menu event + * @param {object} [handler] - object with handling function, in this case one not need to bind function + * @param {string} [menuname] - optional menu name + * @example + * import { createMenu } from 'https://root.cern/js/latest/modules/gui/menu.mjs'; + * let menu = await createMenu()); + * menu.add('First', () => console.log('Click first')); + * let flag = true; + * menu.addchk(flag, 'Checked', arg => console.log(`Now flag is ${arg}`)); + * menu.show(); */ +function createMenu(evnt, handler, menuname) { + const menu = new StandaloneMenu(handler, menuname || 'root_ctx_menu', evnt); + return menu.load(); +} - if (!getBinContent(i,j,nlevel)) continue; +/** @summary Close previousely created and shown JSROOT menu + * @param {string} [menuname] - optional menu name */ +function closeMenu(menuname) { + const element = getDocument().getElementById(menuname || 'root_ctx_menu'); + element?.remove(); + return !!element; +} - nobottom = !reduced && (nlevel > 0); - notop = !reduced && (binz2 > zmax) && (nlevel < levels.length-2); +/** @summary Fill and show context menu for painter object + * @private */ +function showPainterMenu(evnt, painter, kind) { + if (isFunc(evnt.stopPropagation)) { + evnt.stopPropagation(); // disable main context menu + evnt.preventDefault(); // disable browser context menu + } - numvertices += (reduced ? 12 : indicies.length); - if (nobottom) numvertices -= 6; - if (notop) numvertices -= 6; + createMenu(evnt, painter).then(menu => { + painter.fillContextMenu(menu); + if ((kind === kToFront) && isFunc(painter.bringToFront)) { + menu.add('Bring to front', () => painter.bringToFront(true)); + kind = undefined; + } + return painter.fillObjectExecMenu(menu, kind); + }).then(menu => menu.show()); +} - if (split_faces && !reduced) { - numvertices -= 12; - num2vertices += 12; - } - } +/** @summary Assign handler for context menu for painter draw element + * @private */ +function assignContextMenu(painter, kind) { + if (!painter?.isBatchMode() && painter?.draw_g) + painter.draw_g.on('contextmenu', settings.ContextMenu ? evnt => showPainterMenu(evnt, painter, kind) : null); +} - const positions = new Float32Array(numvertices*3), - normals = new Float32Array(numvertices*3), - face_to_bins_index = use16indx ? new Uint16Array(numvertices/3) : new Uint32Array(numvertices/3), - pos2 = (num2vertices === 0) ? null : new Float32Array(num2vertices*3), - norm2 = (num2vertices === 0) ? null : new Float32Array(num2vertices*3), - face_to_bins_indx2 = (num2vertices === 0) ? null : (use16indx ? new Uint16Array(num2vertices/3) : new Uint32Array(num2vertices/3)); +/** @summary Return time offset value for given TAxis object + * @private */ +function getTimeOffset(axis) { + const dflt_time_offset = 788918400000; + if (!axis) return dflt_time_offset; + const idF = axis.fTimeFormat.indexOf('%F'); + if (idF < 0) return gStyle.fTimeOffset * 1000; + let sof = axis.fTimeFormat.slice(idF + 2); + // default string in axis offset + if (sof.indexOf('1995-01-01 00:00:00s0') === 0) return dflt_time_offset; + // special case, used from DABC painters + if ((sof === '0') || (sof === '')) return 0; - let v = 0, v2 = 0, vert, k, nn; + // decode time from ROOT string + const next = (separ, min, max) => { + const pos = sof.indexOf(separ); + if (pos < 0) return min; + const val = parseInt(sof.slice(0, pos)); + sof = sof.slice(pos + 1); + if (!Number.isInteger(val) || (val < min) || (val > max)) return min; + return val; + }, year = next('-', 1970, 2300), + month = next('-', 1, 12) - 1, + day = next(' ', 1, 31), + hour = next(':', 0, 23), + min = next(':', 0, 59), + sec = next('s', 0, 59), + msec = next(' ', 0, 999), + dt = new Date(Date.UTC(year, month, day, hour, min, sec, msec)); - for (i = i1; i < i2; ++i) { - x1 = handle.grx[i] + handle.xbar1*(handle.grx[i+1] - handle.grx[i]); - x2 = handle.grx[i] + handle.xbar2*(handle.grx[i+1] - handle.grx[i]); - for (j = j1; j < j2; ++j) { + let offset = dt.getTime(); - if (!getBinContent(i,j,nlevel)) continue; + // now also handle suffix like GMT or GMT -0600 + sof = sof.toUpperCase(); - nobottom = !reduced && (nlevel > 0); - notop = !reduced && (binz2 > zmax) && (nlevel < levels.length-2); + if (sof.indexOf('GMT') === 0) { + sof = sof.slice(4).trim(); + if (sof.length > 3) { + let p = 0, sign = 1000; + if (sof[0] === '-') { p = 1; sign = -1000; } + offset -= sign * (parseInt(sof.slice(p, p+2)) * 3600 + parseInt(sof.slice(p+2, p+4)) * 60); + } + } - y1 = handle.gry[j] + handle.ybar1*(handle.gry[j+1] - handle.gry[j]); - y2 = handle.gry[j] + handle.ybar2*(handle.gry[j+1] - handle.gry[j]); + return offset; +} - z1 = (binz1 <= zmin) ? grzmin : main.grz(binz1); - z2 = (binz2 > zmax) ? grzmax : main.grz(binz2); +/** @summary Return true when GMT option configured in time format + * @private */ +function getTimeGMT(axis) { + const fmt = axis?.fTimeFormat ?? ''; + return (fmt.indexOf('gmt') > 0) || (fmt.indexOf('GMT') > 0); +} - nn = 0; // counter over the normals, each normals correspond to 6 vertices - k = 0; // counter over vertices +/** @summary Tries to choose time format for provided time interval + * @private */ +function chooseTimeFormat(awidth, ticks) { + if (awidth < 0.5) return ticks ? '%S.%L' : '%H:%M:%S.%L'; + if (awidth < 30) return ticks ? '%Mm%S' : '%H:%M:%S'; + awidth /= 60; if (awidth < 30) return ticks ? '%Hh%M' : '%d/%m %H:%M'; + awidth /= 60; if (awidth < 12) return ticks ? '%d-%Hh' : '%d/%m/%y %Hh'; + awidth /= 24; if (awidth < 15.218425) return ticks ? '%d/%m' : '%d/%m/%y'; + awidth /= 30.43685; if (awidth < 6) return '%d/%m/%y'; + awidth /= 12; if (awidth < 2) return ticks ? '%m/%y' : '%d/%m/%y'; + return '%Y'; +} - if (reduced) { - // we skip all side faces, keep only top and bottom - nn += 12; - k += 24; - } +/** + * @summary Base axis painter methods + * + * @private + */ - let size = indicies.length, bin_index = histo.getBin(i+1, j+1); - if (nobottom) size -= 6; +const AxisPainterMethods = { - // array over all vertices of the single bin - while(k < size) { + initAxisPainter() { + this.name = 'yaxis'; + this.kind = 'normal'; + this.func = null; + this.order = 0; // scaling order for axis labels - vert = vertices[indicies[k]]; + this.full_min = 0; + this.full_max = 1; + this.scale_min = 0; + this.scale_max = 1; + this.ticks = []; // list of major ticks + }, - if (split_faces && (k < 12)) { - pos2[v2] = x1 + vert.x * (x2 - x1); - pos2[v2+1] = y1 + vert.y * (y2 - y1); - pos2[v2+2] = z1 + vert.z * (z2 - z1); + /** @summary Cleanup axis painter */ + cleanupAxisPainter() { + this.ticks = []; + delete this.format; + delete this.func; + delete this.tfunc1; + delete this.tfunc2; + delete this.gr; + }, - norm2[v2] = vnormals[nn]; - norm2[v2+1] = vnormals[nn+1]; - norm2[v2+2] = vnormals[nn+2]; - if (v2 % 9 === 0) face_to_bins_indx2[v2/9] = bin_index; // remember which bin corresponds to the face - v2 += 3; - } else { - positions[v] = x1 + vert.x * (x2 - x1); - positions[v+1] = y1 + vert.y * (y2 - y1); - positions[v+2] = z1 + vert.z * (z2 - z1); + /** @summary Assign often used members of frame painter */ + assignFrameMembers(fp, axis) { + fp[`gr${axis}`] = this.gr; // fp.grx + fp[`log${axis}`] = this.log; // fp.logx + fp[`scale_${axis}min`] = this.scale_min; // fp.scale_xmin + fp[`scale_${axis}max`] = this.scale_max; // fp.scale_xmax + }, - normals[v] = vnormals[nn]; - normals[v+1] = vnormals[nn+1]; - normals[v+2] = vnormals[nn+2]; - if (v % 9 === 0) face_to_bins_index[v/9] = bin_index; // remember which bin corresponds to the face - v += 3; - } + /** @summary Convert axis value into the Date object */ + convertDate(v) { + return new Date(this.timeoffset + v*1000); + }, - ++k; + /** @summary Convert graphical point back into axis value */ + revertPoint(pnt) { + const value = this.func.invert(pnt); + return this.kind === 'time' ? (value - this.timeoffset) / 1000 : value; + }, - if (k % 6 === 0) { - nn += 3; - if (notop && (k === indicies.length - 12)) { - k += 6; nn += 3; // jump over notop indexes - } - } - } + /** @summary Provide label for time axis */ + formatTime(d, asticks) { + return asticks ? this.tfunc1(d) : this.tfunc2(d); + }, + + /** @summary Provide label for log axis */ + formatLog(d, asticks, fmt) { + const val = parseFloat(d), rnd = Math.round(val); + if (!asticks) + return ((rnd === val) && (Math.abs(rnd) < 1e9)) ? rnd.toString() : floatToString(val, fmt || gStyle.fStatFormat); + if (val <= 0) return null; + let vlog = Math.log10(val); + const base = this.logbase; + if (base !== 10) vlog = vlog / Math.log10(base); + if (this.moreloglabels || (Math.abs(vlog - Math.round(vlog)) < 0.001)) { + if (!this.noexp && (asticks !== 2)) { + const pow = Math.floor(vlog+0.01); + if ((pow === 0) && settings.StripAxisLabels) + return '1'; + return this.formatExp(base, pow, val); } + if (Math.abs(base - Math.E) < 0.001) + return floatToString(val, fmt || gStyle.fStatFormat); + return (vlog < 0) ? val.toFixed(Math.round(-vlog+0.5)) : val.toFixed(0); } + return null; + }, - let geometry = new BufferGeometry(); - geometry.setAttribute('position', new BufferAttribute(positions, 3)); - geometry.setAttribute('normal', new BufferAttribute(normals, 3)); - // geometry.computeVertexNormals(); + /** @summary Provide label for normal axis */ + formatNormal(d, asticks, fmt) { + let val = parseFloat(d); + if (asticks && this.order) + val = val / Math.pow(10, this.order); - let rootcolor = is_v7 ? 3 : histo.fFillColor, - fcolor = painter.getColor(rootcolor); + if (gStyle.fStripDecimals && (val === Math.round(val))) + return Math.abs(val) < 1e9 ? val.toFixed(0) : val.toExponential(4); - if (palette) { - fcolor = is_v7 ? palette.getColor(nlevel) : palette.calcColor(nlevel, levels.length); - } else if ((painter.options.Lego === 1) || (rootcolor < 2)) { - rootcolor = 1; - fcolor = 'white'; + if (asticks) { + if (this.ndig > 10) + return val.toExponential(this.ndig - 11); + let res = val.toFixed(this.ndig); + const p = res.indexOf('.'); + if ((p > 0) && settings.StripAxisLabels) { + while ((res.length >= p) && ((res[res.length-1] === '0') || (res[res.length-1] === '.'))) + res = res.slice(0, res.length - 1); + } + return res; } - let material = new MeshBasicMaterial({ color: fcolor, vertexColors: false }), - mesh = new Mesh(geometry, material); - - mesh.face_to_bins_index = face_to_bins_index; - mesh.painter = painter; - mesh.zmin = axis_zmin; - mesh.zmax = axis_zmax; - mesh.baseline = (painter.options.BaseLine !== false) ? painter.options.BaseLine : (painter.options.Zero ? axis_zmin : 0); - mesh.tip_color = (rootcolor===3) ? 0xFF0000 : 0x00FF00; - mesh.handle = handle; + return floatToString(val, fmt || gStyle.fStatFormat); + }, - mesh.tooltip = function(intersect) { - if (!Number.isInteger(intersect.faceIndex)) { - console.error(`faceIndex not provided, three.js version ${REVISION}`); - return null; - } + /** @summary Provide label for exponential form */ + formatExp(base, order, value) { + let res = ''; + if (value) { + value = Math.round(value/Math.pow(base, order)); + if ((value !== 0) && (value !== 1)) res = value.toString() + (settings.Latex ? '#times' : 'x'); + } + if (Math.abs(base - Math.E) < 0.001) + res += 'e'; + else + res += base.toString(); + if (settings.Latex > constants$1.Latex.Symbols) + return res + `^{${order}}`; + const superscript_symbols = { + 0: '\u2070', 1: '\xB9', 2: '\xB2', 3: '\xB3', 4: '\u2074', 5: '\u2075', + 6: '\u2076', 7: '\u2077', 8: '\u2078', 9: '\u2079', '-': '\u207B' + }, str = order.toString(); + for (let n = 0; n < str.length; ++n) + res += superscript_symbols[str[n]]; + return res; + }, - if ((intersect.faceIndex < 0) || (intersect.faceIndex >= this.face_to_bins_index.length)) return null; + /** @summary Convert 'raw' axis value into text */ + axisAsText(value, fmt) { + if (this.kind === 'time') + value = this.convertDate(value); + if (this.format) + return this.format(value, false, fmt); + return value.toPrecision(4); + }, - const p = this.painter, - handle = this.handle, - main = p.getFramePainter(), - histo = p.getHisto(), - tip = p.get3DToolTip(this.face_to_bins_index[intersect.faceIndex]); + /** @summary Produce ticks for d3.scaleLog + * @desc Fixing following problem, described [here]{@link https://stackoverflow.com/questions/64649793} */ + poduceLogTicks(func, number) { + const linearArray = arr => { + let sum1 = 0, sum2 = 0; + for (let k = 1; k < arr.length; ++k) { + const diff = (arr[k] - arr[k-1]); + sum1 += diff; + sum2 += diff**2; + } + const mean = sum1/(arr.length-1), + dev = sum2/(arr.length-1) - mean**2; - tip.x1 = Math.max(-main.size_x3d, handle.grx[tip.ix-1] + handle.xbar1*(handle.grx[tip.ix] - handle.grx[tip.ix-1])); - tip.x2 = Math.min(main.size_x3d, handle.grx[tip.ix-1] + handle.xbar2*(handle.grx[tip.ix] - handle.grx[tip.ix-1])); + if (dev <= 0) return true; + if (Math.abs(mean) < 1e-100) return false; + return Math.sqrt(dev)/mean < 1e-6; + }; - tip.y1 = Math.max(-main.size_y3d, handle.gry[tip.iy-1] + handle.ybar1*(handle.gry[tip.iy] - handle.gry[tip.iy-1])); - tip.y2 = Math.min(main.size_y3d, handle.gry[tip.iy-1] + handle.ybar2*(handle.gry[tip.iy] - handle.gry[tip.iy-1])); + let arr = func.ticks(number); - let binz1 = this.baseline, binz2 = tip.value; - if (histo.$baseh) binz1 = histo.$baseh.getBinContent(tip.ix, tip.iy); - if (binz2 4) && linearArray(arr)) { + number = Math.round(number*0.8); + arr = func.ticks(number); + } - tip.z1 = main.grz(Math.max(this.zmin,binz1)); - tip.z2 = main.grz(Math.min(this.zmax,binz2)); + // if still linear array, try to sort out 'bad' ticks + if ((number < 5) && linearArray(arr) && this.logbase && (this.logbase !== 10)) { + const arr2 = []; + arr.forEach(val => { + const pow = Math.log10(val) / Math.log10(this.logbase); + if (Math.abs(Math.round(pow) - pow) < 0.01) arr2.push(val); + }); + if (arr2.length > 0) arr = arr2; + } - tip.color = this.tip_color; + return arr; + }, - if (p.is_projection && (p.getDimension()==2)) tip.$painter = p; // used only for projections + /** @summary Produce axis ticks */ + produceTicks(ndiv, ndiv2) { + if (!this.noticksopt) { + const total = ndiv * (ndiv2 || 1); - return tip; - }; + if (this.log) return this.poduceLogTicks(this.func, total); - main.toplevel.add(mesh); + const dom = this.func.domain(), - if (num2vertices > 0) { - const geom2 = new BufferGeometry(); - geom2.setAttribute('position', new BufferAttribute(pos2, 3)); - geom2.setAttribute('normal', new BufferAttribute(norm2, 3)); - //geom2.computeVertexNormals(); + check = ticks => { + if (ticks.length <= total) return true; + if (ticks.length > total + 1) return false; + return (ticks[0] === dom[0]) || (ticks[total] === dom[1]); // special case of N+1 ticks, but match any range + }, - const color2 = (rootcolor < 2) ? new Color$1(0xFF0000) : new Color$1(rgb(fcolor).darker(0.5).toString()), - material2 = new MeshBasicMaterial({ color: color2, vertexColors: false }), - mesh2 = new Mesh(geom2, material2); - mesh2.face_to_bins_index = face_to_bins_indx2; - mesh2.painter = painter; - mesh2.handle = mesh.handle; - mesh2.tooltip = mesh.tooltip; - mesh2.zmin = mesh.zmin; - mesh2.zmax = mesh.zmax; - mesh2.baseline = mesh.baseline; - mesh2.tip_color = mesh.tip_color; + res1 = this.func.ticks(total); + if (ndiv2 || check(res1)) return res1; - main.toplevel.add(mesh2); + const res2 = this.func.ticks(Math.round(total * 0.7)); + return (res2.length > 2) && check(res2) ? res2 : res1; } - } - - // lego3 or lego4 do not draw border lines - if (painter.options.Lego > 12) return; - // DRAW LINE BOXES + const dom = this.func.domain(), ticks = []; + if (ndiv2) ndiv = (ndiv-1) * ndiv2; + for (let n = 0; n <= ndiv; ++n) + ticks.push((dom[0]*(ndiv-n) + dom[1]*n)/ndiv); + return ticks; + }, - let numlinevertices = 0, numsegments = 0; + /** @summary Method analyze mouse wheel event and returns item with suggested zooming range */ + analyzeWheelEvent(evnt, dmin, item, test_ignore) { + if (!item) item = {}; - zmax = axis_zmax; zmin = axis_zmin; + let delta = 0, delta_left = 1, delta_right = 1; - for (i = i1; i < i2; ++i) - for (j = j1; j < j2; ++j) { - if (!getBinContent(i,j,0)) continue; + if ('dleft' in item) { delta_left = item.dleft; delta = 1; } + if ('dright' in item) { delta_right = item.dright; delta = 1; } - // calculate required buffer size for line segments - numlinevertices += (reduced ? rvertices.length : vertices.length); - numsegments += (reduced ? rsegments.length : segments.length); - } + if (item.delta) + delta = item.delta; + else if (evnt) + delta = evnt.wheelDelta ? -evnt.wheelDelta : (evnt.deltaY || evnt.detail); - // On some platforms vertex index required to be Uint16 array - // While we cannot use index for large vertex list - // skip index usage at all. It happens for relatively large histograms (100x100 bins) - const uselineindx = (numlinevertices <= 0xFFF0); + if (!delta || (test_ignore && item.ignore)) return; - if (!uselineindx) numlinevertices = numsegments*3; + delta = (delta < 0) ? -0.2 : 0.2; + delta_left *= delta; + delta_right *= delta; - const lpositions = new Float32Array(numlinevertices * 3), - lindicies = uselineindx ? new Uint16Array(numsegments) : null, - grzmin = main.grz(axis_zmin), - grzmax = main.grz(axis_zmax); - let z1 = 0, z2 = 0, ll = 0, ii = 0; + const lmin = item.min = this.scale_min, + lmax = item.max = this.scale_max, + gmin = this.full_min, + gmax = this.full_max; - for (i = i1; i < i2; ++i) { - x1 = handle.grx[i] + handle.xbar1*(handle.grx[i+1] - handle.grx[i]); - x2 = handle.grx[i] + handle.xbar2*(handle.grx[i+1] - handle.grx[i]); - for (j = j1; j < j2; ++j) { + if ((item.min === item.max) && (delta < 0)) { + item.min = gmin; + item.max = gmax; + } - if (!getBinContent(i,j,0)) continue; + if (item.min >= item.max) return; - y1 = handle.gry[j] + handle.ybar1*(handle.gry[j+1] - handle.gry[j]); - y2 = handle.gry[j] + handle.ybar2*(handle.gry[j+1] - handle.gry[j]); + if (item.reverse) dmin = 1 - dmin; - z1 = (binz1 <= axis_zmin) ? grzmin : main.grz(binz1); - z2 = (binz2 > axis_zmax) ? grzmax : main.grz(binz2); + if ((dmin > 0) && (dmin < 1)) { + if (this.log) { + let factor = (item.min > 0) ? Math.log10(item.max/item.min) : 2; + if (factor > 10) factor = 10; else if (factor < 0.01) factor = 0.01; + item.min = item.min / Math.pow(10, factor*delta_left*dmin); + item.max = item.max * Math.pow(10, factor*delta_right*(1-dmin)); + } else if ((delta_left === -delta_right) && !item.reverse) { + // shift left/right, try to keep range constant + let delta = (item.max - item.min) * delta_right * dmin; - const seg = reduced ? rsegments : segments, - vvv = reduced ? rvertices : vertices; + if ((Math.round(item.max) === item.max) && (Math.round(item.min) === item.min) && (Math.abs(delta) > 1)) delta = Math.round(delta); - if (uselineindx) { - // array of indicies for the lines, to avoid duplication of points - for (k = 0; k < seg.length; ++k) { - // intersect_index[ii] = bin_index; - lindicies[ii++] = ll/3 + seg[k]; - } + if (item.min + delta < gmin) + delta = gmin - item.min; + else if (item.max + delta > gmax) + delta = gmax - item.max; - for (k = 0; k < vvv.length; ++k) { - vert = vvv[k]; - lpositions[ll] = x1 + vert.x * (x2 - x1); - lpositions[ll+1] = y1 + vert.y * (y2 - y1); - lpositions[ll+2] = z1 + vert.z * (z2 - z1); - ll += 3; + if (delta !== 0) { + item.min += delta; + item.max += delta; + } else { + delete item.min; + delete item.max; } } else { - // copy only vertex positions - for (k = 0; k < seg.length; ++k) { - vert = vvv[seg[k]]; - lpositions[ll] = x1 + vert.x * (x2 - x1); - lpositions[ll+1] = y1 + vert.y * (y2 - y1); - lpositions[ll+2] = z1 + vert.z * (z2 - z1); - // intersect_index[ll/3] = bin_index; - ll += 3; - } + let rx_left = (item.max - item.min), rx_right = rx_left; + if (delta_left > 0) rx_left = 1.001 * rx_left / (1-delta_left); + item.min += -delta_left*dmin*rx_left; + if (delta_right > 0) rx_right = 1.001 * rx_right / (1-delta_right); + item.max -= -delta_right*(1-dmin)*rx_right; } - } - } + if (item.min >= item.max) + item.min = item.max = undefined; + else if (delta_left !== delta_right) { + // extra check case when moving left or right + if (((item.min < gmin) && (lmin === gmin)) || + ((item.max > gmax) && (lmax === gmax))) + item.min = item.max = undefined; + } else { + if (item.min < gmin) item.min = gmin; + if (item.max > gmax) item.max = gmax; + } + } else + item.min = item.max = undefined; - // create boxes - const lcolor = is_v7 ? painter.v7EvalColor('line_color', 'lightblue') : painter.getColor(histo.fLineColor), - material = new LineBasicMaterial({ color: new Color$1(lcolor), linewidth: is_v7 ? painter.v7EvalAttr('line_width', 1) : histo.fLineWidth }), - line = createLineSegments(lpositions, material, uselineindx ? lindicies : null ); - /* - line.painter = painter; - line.intersect_index = intersect_index; - line.tooltip = function(intersect) { - if ((intersect.index < 0) || (intersect.index >= this.intersect_index.length)) return null; - return this.painter.get3DToolTip(this.intersect_index[intersect.index]); - } - */ + item.changed = ((item.min !== undefined) && (item.max !== undefined)); - main.toplevel.add(line); -} + return item; + } -/** @summary Draw TH2 histogram in error mode - * @private */ -function drawBinsError3D(painter, is_v7 = false) { - const main = painter.getFramePainter(), - histo = painter.getHisto(), - handle = painter.prepareDraw({ rounding: false, use3d: true, extra: 1 }), - zmin = main.z_handle.getScaleMin(), - zmax = main.z_handle.getScaleMax(); - let i, j, bin, binz, binerr, x1, y1, x2, y2, z1, z2, - nsegments = 0, lpos = null, binindx = null, lindx = 0; +}; // AxisPainterMethods - const check_skip_min = () => { - // return true if minimal histogram value should be skipped - if (painter.options.Zero || (zmin > 0)) return false; - return !painter._show_empty_bins; - }; - // loop over the points - first loop counts points, second fill arrays - for (let loop = 0; loop < 2; ++loop) { +/** + * @summary Painter for TAxis object + * + * @private + */ - for (i = handle.i1; i < handle.i2; ++i) { - x1 = handle.grx[i]; - x2 = handle.grx[i + 1]; - for (j = handle.j1; j < handle.j2; ++j) { - binz = histo.getBinContent(i + 1, j + 1); - if ((binz < zmin) || (binz > zmax)) continue; - if ((binz === zmin) && check_skip_min()) continue; +class TAxisPainter extends ObjectPainter { - // just count number of segments - if (loop === 0) { nsegments += 3; continue; } + /** @summary constructor + * @param {object|string} dom - identifier or dom element + * @param {object} axis - object to draw + * @param {boolean} embedded - if true, painter used in other objects painters */ + constructor(dom, axis, embedded) { + super(dom, axis); - bin = histo.getBin(i + 1, j + 1); - binerr = histo.getBinError(bin); - binindx[lindx / 18] = bin; + this.is_gaxis = axis?._typename === clTGaxis; - y1 = handle.gry[j]; - y2 = handle.gry[j + 1]; + Object.assign(this, AxisPainterMethods); + this.initAxisPainter(); - z1 = main.grz((binz - binerr < zmin) ? zmin : binz - binerr); - z2 = main.grz((binz + binerr > zmax) ? zmax : binz + binerr); + this.embedded = embedded; // indicate that painter embedded into the histo painter + this.invert_side = false; + this.lbls_both_sides = false; // draw labels on both sides + } - lpos[lindx] = x1; lpos[lindx + 3] = x2; - lpos[lindx + 1] = lpos[lindx + 4] = (y1 + y2) / 2; - lpos[lindx + 2] = lpos[lindx + 5] = (z1 + z2) / 2; - lindx += 6; + /** @summary cleanup painter */ + cleanup() { + this.cleanupAxisPainter(); + super.cleanup(); + } - lpos[lindx] = lpos[lindx + 3] = (x1 + x2) / 2; - lpos[lindx + 1] = y1; lpos[lindx + 4] = y2; - lpos[lindx + 2] = lpos[lindx + 5] = (z1 + z2) / 2; - lindx += 6; + /** @summary Use in GED to identify kind of axis */ + getAxisType() { return clTAxis; } - lpos[lindx] = lpos[lindx + 3] = (x1 + x2) / 2; - lpos[lindx + 1] = lpos[lindx + 4] = (y1 + y2) / 2; - lpos[lindx + 2] = z1; lpos[lindx + 5] = z2; - lindx += 6; - } - } + /** @summary Configure axis painter + * @desc Axis can be drawn inside frame group with offset to 0 point for the frame + * Therefore one should distinguish when caclulated coordinates used for axis drawing itself or for calculation of frame coordinates + * @private */ + configureAxis(name, min, max, smin, smax, vertical, range, opts) { + this.name = name; + this.full_min = min; + this.full_max = max; + this.kind = 'normal'; + this.vertical = vertical; + this.log = opts.log || 0; + this.noexp_changed = opts.noexp_changed; + this.symlog = opts.symlog || false; + this.reverse = opts.reverse || false; + this.swap_side = opts.swap_side || false; + this.fixed_ticks = opts.fixed_ticks || null; + this.maxTickSize = opts.maxTickSize || 0; - if (loop === 0) { - if (nsegments === 0) return; - lpos = new Float32Array(nsegments * 6); - binindx = new Int32Array(nsegments / 3); - } - } + const axis = this.getObject(); - // create lines - const lcolor = is_v7 ? painter.v7EvalColor('line_color', 'lightblue') : painter.getColor(histo.fLineColor), - material = new LineBasicMaterial({ color: new Color$1(lcolor), linewidth: is_v7 ? painter.v7EvalAttr('line_width', 1) : histo.fLineWidth }), - line = createLineSegments(lpos, material); + if (opts.time_scale || axis.fTimeDisplay) { + this.kind = 'time'; + this.timeoffset = getTimeOffset(axis); + this.timegmt = getTimeGMT(axis); + } else if (opts.axis_func) + this.kind = 'func'; + else + this.kind = !axis.fLabels ? 'normal' : 'labels'; - line.painter = painter; - line.intersect_index = binindx; - line.zmin = zmin; - line.zmax = zmax; - line.tip_color = (histo.fLineColor === 3) ? 0xFF0000 : 0x00FF00; - line.tooltip = function(intersect) { - if (!Number.isInteger(intersect.index)) { - console.error(`segment index not provided, three.js version ${REVISION}`); - return null; - } + if (this.kind === 'time') + this.func = time().domain([this.convertDate(smin), this.convertDate(smax)]); + else if (this.log) { + if ((this.log === 1) || (this.log === 10)) + this.logbase = 10; + else if (this.log === 3) + this.logbase = Math.E; + else + this.logbase = Math.round(this.log); - let pos = Math.floor(intersect.index / 6); - if ((pos < 0) || (pos >= this.intersect_index.length)) return null; - let p = this.painter, - histo = p.getHisto(), - main = p.getFramePainter(), - tip = p.get3DToolTip(this.intersect_index[pos]); + if (smax <= 0) smax = 1; - tip.x1 = Math.max(-main.size_x3d, main.grx(histo.fXaxis.GetBinLowEdge(tip.ix))); - tip.x2 = Math.min(main.size_x3d, main.grx(histo.fXaxis.GetBinLowEdge(tip.ix+1))); - tip.y1 = Math.max(-main.size_y3d, main.gry(histo.fYaxis.GetBinLowEdge(tip.iy))); - tip.y2 = Math.min(main.size_y3d, main.gry(histo.fYaxis.GetBinLowEdge(tip.iy+1))); + if ((smin <= 0) && axis && !opts.logcheckmin) { + for (let i = 0; i < axis.fNbins; ++i) { + smin = Math.max(smin, axis.GetBinLowEdge(i+1)); + if (smin > 0) break; + } + } - tip.z1 = main.grz(tip.value-tip.error < this.zmin ? this.zmin : tip.value-tip.error); - tip.z2 = main.grz(tip.value+tip.error > this.zmax ? this.zmax : tip.value+tip.error); + if ((smin <= 0) && opts.log_min_nz) + smin = this.log_min_nz = opts.log_min_nz; - tip.color = this.tip_color; + if ((smin <= 0) || (smin >= smax)) + smin = smax * (opts.logminfactor || 1e-4); - return tip; - }; + if (this.kind === 'func') + this.func = this.createFuncHandle(opts.axis_func, this.logbase, smin, smax); + else + this.func = log().base(this.logbase).domain([smin, smax]); + } else if (this.symlog) { + let v = Math.max(Math.abs(smin), Math.abs(smax)); + if (Number.isInteger(this.symlog) && (this.symlog > 0)) + v *= Math.pow(10, -1*this.symlog); + else + v *= 0.01; + this.func = symlog().constant(v).domain([smin, smax]); + } else if (this.kind === 'func') + this.func = this.createFuncHandle(opts.axis_func, 0, smin, smax); + else + this.func = linear().domain([smin, smax]); - main.toplevel.add(line); -} -/** @summary Draw TH2 as 3D contour plot - * @private */ -function drawBinsContour3D(painter, realz = false, is_v7 = false) { - // for contour plots one requires handle with full range - let main = painter.getFramePainter(), - handle = painter.prepareDraw({rounding: false, use3d: true, extra: 100, middle: 0.0 }), - histo = painter.getHisto(), // get levels - levels = painter.getContourLevels(), // init contour if not exists - palette = painter.getHistPalette(), - layerz = 2*main.size_z3d, pnts = []; - - painter.buildContour(handle, levels, palette, - (colindx, xp, yp, iminus, iplus, ilevel) => { - // ignore less than three points - if (iplus - iminus < 3) return; + if (this.vertical ^ this.reverse) { + const d = range[0]; range[0] = range[1]; range[1] = d; + } - if (realz) { - layerz = main.grz(levels[ilevel]); - if ((layerz < 0) || (layerz > 2*main.size_z3d)) return; - } + this.func.range(range); - for (let i=iminus;i this.func(this.convertDate(val)); + else if (this.log) + this.gr = val => (val < this.scale_min) ? (this.vertical ? this.func.range()[0]+5 : -5) : this.func(val); + else + this.gr = this.func; + delete this.format;// remove formatting func -/** @summary Draw TH2 histograms in surf mode - * @private */ -function drawBinsSurf3D(painter, is_v7 = false) { - let histo = painter.getHisto(), - main = painter.getFramePainter(), - handle = painter.prepareDraw({rounding: false, use3d: true, extra: 1, middle: 0.5 }), - i,j, x1, y1, x2, y2, z11, z12, z21, z22, - axis_zmin = main.z_handle.getScaleMin(); - // axis_zmax = main.z_handle.getScaleMax(); + let ndiv = 508; + if (this.is_gaxis) + ndiv = axis.fNdiv; + else if (axis) { + if (!axis.fNdivisions) + ndiv = 0; + else + ndiv = Math.max(axis.fNdivisions, 4); + } - // first adjust ranges + this.nticks = ndiv % 100; + this.nticks2 = (ndiv % 10000 - this.nticks) / 100; + this.nticks3 = Math.floor(ndiv/10000); - let main_grz = !main.logz ? main.grz : value => (value < axis_zmin) ? -0.1 : main.grz(value); + if (axis && !this.is_gaxis && (this.nticks > 20)) this.nticks = 20; - if ((handle.i2 - handle.i1 < 2) || (handle.j2 - handle.j1 < 2)) return; + let gr_range = Math.abs(this.func.range()[1] - this.func.range()[0]); + if (gr_range <= 0) gr_range = 100; - let ilevels = null, levels = null, dolines = true, dogrid = false, - donormals = false, palette = null; + if (this.kind === 'time') { + if (this.nticks > 8) this.nticks = 8; - if (is_v7) { - let need_palette = 0; - switch(painter.options.Surf) { - case 11: need_palette = 2; break; - case 12: - case 15: // make surf5 same as surf2 - case 17: need_palette = 2; dolines = false; break; - case 14: dolines = false; donormals = true; break; - case 16: need_palette = 1; dogrid = true; dolines = false; break; - default: ilevels = main.z_handle.createTicks(true); dogrid = true; break; - } + const scale_range = this.scale_max - this.scale_min, + idF = axis.fTimeFormat.indexOf('%F'), + tf2 = chooseTimeFormat(scale_range / gr_range, false); + let tf1 = (idF >= 0) ? axis.fTimeFormat.slice(0, idF) : axis.fTimeFormat; - if (need_palette > 0) { - palette = main.getHistPalette(); - if (need_palette == 2) - painter.createContour(main, palette, { full_z_range: true }); - ilevels = palette.getContour(); - } + if (!tf1 || (scale_range < 0.1 * (this.full_max - this.full_min))) + tf1 = chooseTimeFormat(scale_range / this.nticks, true); - } else { - switch(painter.options.Surf) { - case 11: ilevels = painter.getContourLevels(); palette = painter.getHistPalette(); break; - case 12: - case 15: // make surf5 same as surf2 - case 17: ilevels = painter.getContourLevels(); palette = painter.getHistPalette(); dolines = false; break; - case 14: dolines = false; donormals = true; break; - case 16: ilevels = painter.getContourLevels(); dogrid = true; dolines = false; break; - default: ilevels = main.z_handle.createTicks(true); dogrid = true; break; - } - } + this.tfunc1 = this.tfunc2 = this.timegmt ? utcFormat(tf1) : timeFormat(tf1); + if (tf2 !== tf1) + this.tfunc2 = this.timegmt ? utcFormat(tf2) : timeFormat(tf2); - if (ilevels) { - // recalculate levels into graphical coordinates - levels = new Float32Array(ilevels.length); - for (let ll=0;ll 1) { + this.nticks *= this.nticks2; // all log ticks (major or minor) created centrally + this.nticks2 = 1; + } + this.noexp = axis?.TestBit(EAxisBits.kNoExponent); + if ((this.scale_max < 300) && (this.scale_min > 0.3) && !this.noexp_changed) this.noexp = true; + this.moreloglabels = axis?.TestBit(EAxisBits.kMoreLogLabels); + this.format = this.formatLog; + } else if (this.kind === 'labels') { + this.nticks = 50; // for text output allow max 50 names + const scale_range = this.scale_max - this.scale_min; + if (this.nticks > scale_range) + this.nticks = Math.round(scale_range); - let loop, nfaces = [], pos = [], indx = [], // buffers for faces - nsegments = 0, lpos = null, lindx = 0, // buffer for lines - ngridsegments = 0, grid = null, gindx = 0, // buffer for grid lines segments - normindx = []; // buffer to remember place of vertex for each bin + this.regular_labels = true; - function CheckSide(z,level1, level2) { - if (zlevel2) return 1; - return 0; - } + if (axis && axis.fNbins && axis.fLabels) { + if ((axis.fNbins !== Math.round(axis.fXmax - axis.fXmin)) || + (axis.fXmin !== 0) || (axis.fXmax !== axis.fNbins)) + this.regular_labels = false; + } - function AddLineSegment(x1,y1,z1, x2,y2,z2) { - if (!dolines) return; - let side1 = CheckSide(z1,0,2*main.size_z3d), - side2 = CheckSide(z2,0,2*main.size_z3d); - if ((side1 === side2) && (side1 !== 0)) return; - if (!loop) return ++nsegments; + this.nticks2 = 1; - if (side1 !== 0) { - let diff = z2 - z1; - z1 = (side1 < 0) ? 0 : 2*main.size_z3d; - x1 = x2 - (x2-x1)/diff*(z2-z1); - y1 = y2 - (y2-y1)/diff*(z2-z1); - } - if (side2 !== 0) { - let diff = z1 - z2; - z2 = (side2 < 0) ? 0 : 2*main.size_z3d; - x2 = x1 - (x1-x2)/diff*(z1-z2); - y2 = y1 - (y1-y2)/diff*(z1-z2); + this.format = this.formatLabels; + } else { + this.order = 0; + this.ndig = 0; + this.format = this.formatNormal; } - - lpos[lindx] = x1; lpos[lindx+1] = y1; lpos[lindx+2] = z1; lindx+=3; - lpos[lindx] = x2; lpos[lindx+1] = y2; lpos[lindx+2] = z2; lindx+=3; } - let pntbuf = new Float32Array(6*3), k = 0, lastpart = 0, // maximal 6 points - gridpnts = new Float32Array(2*3), gridcnt = 0; - - function AddCrossingPoint(xx1,yy1,zz1, xx2,yy2,zz2, crossz, with_grid) { - if (k>=pntbuf.length) console.log('more than 6 points???'); - - let part = (crossz - zz1) / (zz2 - zz1), shift = 3; - if ((lastpart !== 0) && (Math.abs(part) < Math.abs(lastpart))) { - // while second crossing point closer than first to original, move it in memory - pntbuf[k] = pntbuf[k-3]; - pntbuf[k+1] = pntbuf[k-2]; - pntbuf[k+2] = pntbuf[k-1]; - k-=3; shift = 6; - } + /** @summary Return scale min */ + getScaleMin() { + return this.func?.domain()[0] ?? 0; + } - pntbuf[k] = xx1 + part*(xx2-xx1); - pntbuf[k+1] = yy1 + part*(yy2-yy1); - pntbuf[k+2] = crossz; + /** @summary Return scale max */ + getScaleMax() { + return this.func?.domain()[1] ?? 0; + } - if (with_grid && grid) { - gridpnts[gridcnt] = pntbuf[k]; - gridpnts[gridcnt+1] = pntbuf[k+1]; - gridpnts[gridcnt+2] = pntbuf[k+2]; - gridcnt+=3; + /** @summary Provide label for axis value */ + formatLabels(d) { + const a = this.getObject(); + let indx = parseFloat(d); + if (!this.regular_labels) + indx = Math.round((indx - a.fXmin)/(a.fXmax - a.fXmin) * a.fNbins); + else + indx = Math.floor(indx); + if ((indx < 0) || (indx >= a.fNbins)) return null; + for (let i = 0; i < a.fLabels.arr.length; ++i) { + const tstr = a.fLabels.arr[i]; + if (tstr.fUniqueID === indx+1) return tstr.fString; } - - k += shift; - lastpart = part; + return null; } - function RememberVertex(indx, ii,jj) { - let bin = ((ii-handle.i1) * (handle.j2-handle.j1) + (jj-handle.j1))*8; + /** @summary Creates array with minor/middle/major ticks */ + createTicks(only_major_as_array, optionNoexp, optionNoopt, optionInt) { + if (optionNoopt && this.nticks && (this.kind === 'normal')) + this.noticksopt = true; - if (normindx[bin] >= 0) - return console.error('More than 8 vertexes for the bin'); + const handle = { painter: this, nminor: 0, nmiddle: 0, nmajor: 0, func: this.func, minor: [], middle: [], major: [] }; + let ticks; - let pos = bin+8+normindx[bin]; // position where write index - normindx[bin]--; - normindx[pos] = indx; // at this moment index can be overwritten, means all 8 position are there - } + if (this.fixed_ticks) { + ticks = []; + this.fixed_ticks.forEach(v => { + if ((v >= this.scale_min) && (v <= this.scale_max)) ticks.push(v); + }); + } else if ((this.kind === 'labels') && !this.regular_labels) { + ticks = []; + handle.lbl_pos = []; + const axis = this.getObject(); + for (let n = 0; n < axis.fNbins; ++n) { + const x = axis.fXmin + n / axis.fNbins * (axis.fXmax - axis.fXmin); + if ((x >= this.scale_min) && (x < this.scale_max)) { + handle.lbl_pos.push(x); + if (x > this.scale_min) ticks.push(x); + } + } + } else + ticks = this.produceTicks(this.nticks); - function RecalculateNormals(arr) { - for (let ii=handle.i1;ii= 0) ? bin : bin+9+normindx[bin], - end = bin+8, sumx=0, sumy = 0, sumz = 0; + if (only_major_as_array) { + const res = handle.major, delta = (this.scale_max - this.scale_min)*1e-5; + if (res[0] > this.scale_min + delta) res.unshift(this.scale_min); + if (res[res.length-1] < this.scale_max - delta) res.push(this.scale_max); + return res; + } - for (let kk=beg;kk 1) && (!this.log || (this.logbase === 10)) && !this.fixed_ticks) { + handle.minor = handle.middle = this.produceTicks(handle.major.length, this.nticks2); - sumx = sumx/(end-beg); sumy = sumy/(end-beg); sumz = sumz/(end-beg); + const gr_range = Math.abs(this.func.range()[1] - this.func.range()[0]); - for (let kk=beg;kk gr_range/3.5)) + handle.minor = handle.middle = handle.major; + else if ((this.nticks3 > 1) && !this.log) { + handle.minor = this.produceTicks(handle.middle.length, this.nticks3); + if ((handle.minor.length <= handle.middle.length) || (handle.minor.length > gr_range/1.7)) + handle.minor = handle.middle; } } - } - - function AddMainTriangle(x1,y1,z1, x2,y2,z2, x3,y3,z3, is_first) { - for (let lvl=1;lvl= this.minor.length) return false; - if (!loop) { - let npnts = Math.abs(side2-side1) + Math.abs(side3-side2) + Math.abs(side1-side3); - if (side1 === 0) ++npnts; - if (side2 === 0) ++npnts; - if (side3 === 0) ++npnts; + this.tick = this.minor[this.nminor++]; + this.grpos = this.func(this.tick); + if (doround) this.grpos = Math.round(this.grpos); + this.kind = 3; - if ((npnts === 1) || (npnts === 2)) console.error(`FOUND npnts = ${npnts}`); + if ((this.nmiddle < this.middle.length) && (Math.abs(this.grpos - this.func(this.middle[this.nmiddle])) < 1)) { + this.nmiddle++; + this.kind = 2; + } - if (npnts > 2) { - if (nfaces[lvl] === undefined) nfaces[lvl] = 0; - nfaces[lvl] += npnts-2; - } + if ((this.nmajor < this.major.length) && (Math.abs(this.grpos - this.func(this.major[this.nmajor])) < 1)) { + this.nmajor++; + this.kind = 1; + } + return true; + }; - // check if any(contours for given level exists - if (((side1 > 0) || (side2 > 0) || (side3 > 0)) && - ((side1!==side2) || (side2!==side3) || (side3!==side1))) ++ngridsegments; + handle.last_major = function() { + return (this.kind !== 1) ? false : this.nmajor === this.major.length; + }; - continue; - } + handle.next_major_grpos = function() { + if (this.nmajor >= this.major.length) return null; + return this.func(this.major[this.nmajor]); + }; - gridcnt = 0; + handle.get_modifier = function() { + return this.painter.findLabelModifier(this.painter.getObject(), this.nmajor-1, this.major); + }; - k = 0; - if (side1 === 0) { pntbuf[k] = x1; pntbuf[k+1] = y1; pntbuf[k+2] = z1; k += 3; } + this.order = 0; + this.ndig = 0; - if (side1!==side2) { - // order is important, should move from 1->2 point, checked via lastpart - lastpart = 0; - if ((side1 < 0) || (side2 < 0)) AddCrossingPoint(x1,y1,z1, x2,y2,z2, levels[lvl-1]); - if ((side1 > 0) || (side2 > 0)) AddCrossingPoint(x1,y1,z1, x2,y2,z2, levels[lvl], true); - } + // at the moment when drawing labels, we can try to find most optimal text representation for them - if (side2 === 0) { pntbuf[k] = x2; pntbuf[k+1] = y2; pntbuf[k+2] = z2; k += 3; } + if (((this.kind === 'normal') || (this.kind === 'func')) && !this.log && (handle.major.length > 0)) { + let maxorder = 0, minorder = 0, exclorder3 = false; - if (side2!==side3) { - // order is important, should move from 2->3 point, checked via lastpart - lastpart = 0; - if ((side2 < 0) || (side3 < 0)) AddCrossingPoint(x2,y2,z2, x3,y3,z3, levels[lvl-1]); - if ((side2 > 0) || (side3 > 0)) AddCrossingPoint(x2,y2,z2, x3,y3,z3, levels[lvl], true); - } + if (!optionNoexp) { + const maxtick = Math.max(Math.abs(handle.major[0]), Math.abs(handle.major[handle.major.length-1])), + mintick = Math.min(Math.abs(handle.major[0]), Math.abs(handle.major[handle.major.length-1])), + ord1 = (maxtick > 0) ? Math.round(Math.log10(maxtick)/3)*3 : 0, + ord2 = (mintick > 0) ? Math.round(Math.log10(mintick)/3)*3 : 0; - if (side3 === 0) { pntbuf[k] = x3; pntbuf[k+1] = y3; pntbuf[k+2] = z3; k+=3; } + exclorder3 = (maxtick < 2e4); // do not show 10^3 for values below 20000 - if (side3 !== side1) { - // order is important, should move from 3->1 point, checked via lastpart - lastpart = 0; - if ((side3 < 0) || (side1 < 0)) AddCrossingPoint(x3,y3,z3, x1,y1,z1, levels[lvl-1]); - if ((side3 > 0) || (side1 > 0)) AddCrossingPoint(x3,y3,z3, x1,y1,z1, levels[lvl], true); + if (maxtick || mintick) { + maxorder = Math.max(ord1, ord2) + 3; + minorder = Math.min(ord1, ord2) - 3; + } } - if (k === 0) continue; - if (k < 9) { console.log('found less than 3 points', k/3); continue; } + // now try to find best combination of order and ndig for labels - if (grid && (gridcnt === 6)) { - for (let jj = 0; jj < 6; ++jj) - grid[gindx+jj] = gridpnts[jj]; - gindx+=6; - } + let bestorder = 0, bestndig = this.ndig, bestlen = 1e10; + for (let order = minorder; order <= maxorder; order+=3) { + if (exclorder3 && (order === 3)) continue; + this.order = order; + this.ndig = 0; + let lbls = [], indx = 0, totallen = 0; + while (indx < handle.major.length) { + const lbl = this.format(handle.major[indx], true); + if (lbls.indexOf(lbl) < 0) { + lbls.push(lbl); + const p = lbl.indexOf('.'); + if (!order && !optionNoexp && ((p > gStyle.fAxisMaxDigits) || ((p < 0) && (lbl.length > gStyle.fAxisMaxDigits)))) { + totallen += 1e10; // do not use order = 0 when too many digits are there + exclorder3 = false; + } + totallen += lbl.length; + indx++; + continue; + } + if (++this.ndig > 15) break; // not too many digits, anyway it will be exponential + lbls = []; indx = 0; totallen = 0; + } - // if three points and surf == 14, remember vertex for each point + // for order === 0 we should virtually remove '0.' and extra label on top + if (!order && (this.ndig < 4)) + totallen -= handle.major.length * 2 + 3; - let buf = pos[lvl], s = indx[lvl]; - if (donormals && (k===9)) { - RememberVertex(s, i, j); - RememberVertex(s+3, i+1, is_first ? j+1 : j); - RememberVertex(s+6, is_first ? i : i+1, j+1); + if (totallen < bestlen) { + bestlen = totallen; + bestorder = this.order; + bestndig = this.ndig; + } } - for (let k1 = 3; k1 < k-3; k1 += 3) { - buf[s] = pntbuf[0]; buf[s+1] = pntbuf[1]; buf[s+2] = pntbuf[2]; s+=3; - buf[s] = pntbuf[k1]; buf[s+1] = pntbuf[k1+1]; buf[s+2] = pntbuf[k1+2]; s+=3; - buf[s] = pntbuf[k1+3]; buf[s+1] = pntbuf[k1+4]; buf[s+2] = pntbuf[k1+5]; s+=3; - } - indx[lvl] = s; + this.order = bestorder; + this.ndig = bestndig; + if (optionInt) { + if (this.order) console.warn(`Axis painter - integer labels are configured, but axis order ${this.order} is preferable`); + if (this.ndig) console.warn(`Axis painter - integer labels are configured, but ${this.ndig} decimal digits are required`); + this.ndig = 0; + this.order = 0; + } } + + return handle; } - if (donormals) - // for each bin maximal 8 points reserved - normindx = new Int32Array((handle.i2-handle.i1)*(handle.j2-handle.j1)*8).fill(-1); + /** @summary Is labels should be centered */ + isCenteredLabels() { + if (this.kind === 'labels') return true; + if (this.log) return false; + return this.getObject()?.TestBit(EAxisBits.kCenterLabels); + } - for (loop = 0; loop < 2; ++loop) { - if (loop) { - for (let lvl = 1; lvl < levels.length; ++lvl) - if (nfaces[lvl]) { - pos[lvl] = new Float32Array(nfaces[lvl] * 9); - indx[lvl] = 0; - } - if (dolines && (nsegments > 0)) - lpos = new Float32Array(nsegments * 6); - if (dogrid && (ngridsegments > 0)) - grid = new Float32Array(ngridsegments * 6); - } - for (i = handle.i1;i < handle.i2-1; ++i) { - x1 = handle.grx[i]; - x2 = handle.grx[i+1]; - for (j = handle.j1; j < handle.j2-1; ++j) { - y1 = handle.gry[j]; - y2 = handle.gry[j+1]; - z11 = main_grz(histo.getBinContent(i+1, j+1)); - z12 = main_grz(histo.getBinContent(i+1, j+2)); - z21 = main_grz(histo.getBinContent(i+2, j+1)); - z22 = main_grz(histo.getBinContent(i+2, j+2)); + /** @summary Add interactive elements to draw axes title */ + addTitleDrag(title_g, vertical, offset_k, reverse, axis_length) { + if (!settings.MoveResize || this.isBatchMode()) return; - AddMainTriangle(x1,y1,z11, x2,y2,z22, x1,y2,z12, true); + let drag_rect = null, + acc_x, acc_y, new_x, new_y, sign_0, alt_pos, curr_indx; + const drag_move = drag().subject(Object); - AddMainTriangle(x1,y1,z11, x2,y1,z21, x2,y2,z22, false); + drag_move.on('start', evnt => { + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - AddLineSegment(x1,y2,z12, x1,y1,z11); - AddLineSegment(x1,y1,z11, x2,y1,z21); + const box = title_g.node().getBBox(), // check that elements visible, request precise value + title_length = vertical ? box.height : box.width; - if (i===handle.i2-2) AddLineSegment(x2,y1,z21, x2,y2,z22); - if (j===handle.j2-2) AddLineSegment(x1,y2,z12, x2,y2,z22); - } - } - } + new_x = acc_x = title_g.property('shift_x'); + new_y = acc_y = title_g.property('shift_y'); - for (let lvl = 1; lvl < levels.length; ++lvl) - if (pos[lvl]) { - if (indx[lvl] !== nfaces[lvl]*9) - console.error(`SURF faces missmatch lvl=${lvl} faces=${nfaces[lvl]} index=${indx[lvl]} check=${nfaces[lvl]*9 - indx[lvl]}`); - let geometry = new BufferGeometry(); - geometry.setAttribute('position', new BufferAttribute(pos[lvl], 3)); - geometry.computeVertexNormals(); - if (donormals && (lvl === 1)) RecalculateNormals(geometry.getAttribute('normal').array); + sign_0 = vertical ? (acc_x > 0) : (acc_y > 0); // sign should remain - let fcolor, material; - if (is_v7) { - fcolor = palette ? palette.getColor(lvl-1) : painter.getColor(5); - } else if (palette) { - fcolor = palette.calcColor(lvl, levels.length); - } else { - fcolor = histo.fFillColor > 1 ? painter.getColor(histo.fFillColor) : 'white'; - if ((painter.options.Surf === 14) && (histo.fFillColor < 2)) fcolor = painter.getColor(48); + alt_pos = vertical ? [axis_length, axis_length/2, 0] : [0, axis_length/2, axis_length]; // possible positions + const off = vertical ? -title_length/2 : title_length/2; + if (this.title_align === 'middle') { + alt_pos[0] += off; + alt_pos[2] -= off; + } else if (this.title_align === 'begin') { + alt_pos[1] -= off; + alt_pos[2] -= 2*off; + } else { // end + alt_pos[0] += 2*off; + alt_pos[1] += off; } - if (painter.options.Surf === 14) - material = new MeshLambertMaterial({ color: fcolor, side: DoubleSide, vertexColors: false }); - else - material = new MeshBasicMaterial({ color: fcolor, side: DoubleSide, vertexColors: false }); - let mesh = new Mesh(geometry, material); + if (this.titleCenter) + curr_indx = 1; + else if (reverse ^ this.titleOpposite) + curr_indx = 0; + else + curr_indx = 2; + + alt_pos[curr_indx] = vertical ? acc_y : acc_x; + + drag_rect = title_g.append('rect') + .attr('x', box.x) + .attr('y', box.y) + .attr('width', box.width) + .attr('height', box.height) + .style('cursor', 'move') + .call(addHighlightStyle, true); + // .style('pointer-events','none'); // let forward double click to underlying elements + }).on('drag', evnt => { + if (!drag_rect) return; - main.toplevel.add(mesh); + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - mesh.painter = painter; // to let use it with context menu - } + acc_x += evnt.dx; + acc_y += evnt.dy; + let set_x, set_y, besti = 0; + const p = vertical ? acc_y : acc_x; - if (lpos) { - if (nsegments*6 !== lindx) - console.error(`SURF lines mismmatch nsegm=${nsegments} lindx=${lindx} diff=${nsegments*6 - lindx}`); + for (let i = 1; i < 3; ++i) + if (Math.abs(p - alt_pos[i]) < Math.abs(p - alt_pos[besti])) besti = i; - const lcolor = painter.getColor(histo.fLineColor), - material = new LineBasicMaterial({ color: new Color$1(lcolor), linewidth: histo.fLineWidth }), - line = createLineSegments(lpos, material); - line.painter = painter; - main.toplevel.add(line); - } + if (vertical) { + set_x = acc_x; + set_y = alt_pos[besti]; + } else { + set_y = acc_y; + set_x = alt_pos[besti]; + } - if (grid) { - if (ngridsegments*6 !== gindx) - console.error(`SURF grid draw mismatch ngridsegm=${ngridsegments} gindx=${gindx} diff=${ngridsegments*6 - gindx}`); + if (sign_0 === (vertical ? (set_x > 0) : (set_y > 0))) { + new_x = set_x; new_y = set_y; curr_indx = besti; + makeTranslate(title_g, new_x, new_y); + } + }).on('end', evnt => { + if (!drag_rect) return; - const material = (painter.options.Surf === 1) - ? new LineDashedMaterial({ color: 0x0, dashSize: 2, gapSize: 2 }) - : new LineBasicMaterial({ color: new Color$1(painter.getColor(histo.fLineColor)) }), - line = createLineSegments(grid, material); - line.painter = painter; - main.toplevel.add(line); - } + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - if (painter.options.Surf === 17) - drawBinsContour3D(painter, false, is_v7); + title_g.property('shift_x', new_x) + .property('shift_y', new_y); - if (painter.options.Surf === 13) { + const axis = this.getObject(), abits = EAxisBits, + axis2 = this.source_axis, + set_bit = (bit, on) => { + if (axis.TestBit(bit) !== on) axis.InvertBit(bit); + if (axis2 && axis2.TestBit(bit) !== on) axis2.InvertBit(bit); + }; - handle = painter.prepareDraw({rounding: false, use3d: true, extra: 100, middle: 0.0 }); + this.titleOffset = (vertical ? new_x : new_y) / offset_k; + axis.fTitleOffset = this.titleOffset / this.offsetScaling / this.titleSize; + if (axis2) axis2.fTitleOffset = axis.fTitleOffset; - // get levels - let levels = painter.getContourLevels(), // init contour - palette = painter.getHistPalette(), - lastcolindx = -1, layerz = 2*main.size_z3d; + if (curr_indx === 1) { + set_bit(abits.kCenterTitle, true); this.titleCenter = true; + set_bit(abits.kOppositeTitle, false); this.titleOpposite = false; + } else if (curr_indx === 0) { + set_bit(abits.kCenterTitle, false); this.titleCenter = false; + set_bit(abits.kOppositeTitle, true); this.titleOpposite = true; + } else { + set_bit(abits.kCenterTitle, false); this.titleCenter = false; + set_bit(abits.kOppositeTitle, false); this.titleOpposite = false; + } - painter.buildContour(handle, levels, palette, - (colindx,xp,yp,iminus,iplus) => { - // no need for duplicated point - if ((xp[iplus] === xp[iminus]) && (yp[iplus] === yp[iminus])) iplus--; + this.submitAxisExec(`SetTitleOffset(${axis.fTitleOffset});;SetBit(${abits.kCenterTitle},${this.titleCenter?1:0})`); - // ignore less than three points - if (iplus - iminus < 3) return; + drag_rect.remove(); + drag_rect = null; + }); - let pnts = []; + title_g.style('cursor', 'move').call(drag_move); + } - for (let i = iminus; i <= iplus; ++i) - if ((i === iminus) || (xp[i] !== xp[i-1]) || (yp[i] !== yp[i-1])) - pnts.push(new Vector2(xp[i], yp[i])); + /** @summary Configure hist painter which creates axis - to be able submit execs + * @private */ + setHistPainter(hist_painter, axis_name) { + this.hist_painter = hist_painter; + this.hist_axis = axis_name; + } - if (pnts.length < 3) return; + /** @summary Submit exec for the axis - if possible + * @private */ + submitAxisExec(exec, only_gaxis) { + const snapid = this.hist_painter?.snapid; + if (snapid && this.hist_axis && !only_gaxis) + this.submitCanvExec(exec, `${snapid}#${this.hist_axis}`); + else if (this.is_gaxis) + this.submitCanvExec(exec); + } - const faces = ShapeUtils.triangulateShape(pnts , []); + /** @summary Produce svg path for axis ticks */ + produceTicksPath(handle, side, tickSize, ticksPlusMinus, secondShift, real_draw) { + let path1 = '', path2 = ''; + this.ticks = []; - if (!faces || (faces.length === 0)) return; + while (handle.next(true)) { + let h1 = Math.round(tickSize/4), h2 = 0; - if ((lastcolindx < 0) || (lastcolindx !== colindx)) { - lastcolindx = colindx; - layerz+=0.0001*main.size_z3d; // change layers Z - } + if (handle.kind < 3) + h1 = Math.round(tickSize/2); - const pos = new Float32Array(faces.length*9), - norm = new Float32Array(faces.length*9); - let indx = 0; + if (handle.kind === 1) { + // if not showing labels, not show large tick + // FIXME: for labels last tick is smaller, + if (/* (this.kind === 'labels') || */ (this.format(handle.tick, true) !== null)) h1 = tickSize; + this.ticks.push(handle.grpos); // keep graphical positions of major ticks + } - for (let n = 0; n < faces.length; ++n) { - let face = faces[n]; - for (let v = 0; v < 3; ++v) { - let pnt = pnts[face[v]]; - pos[indx] = pnt.x; - pos[indx+1] = pnt.y; - pos[indx+2] = layerz; - norm[indx] = 0; - norm[indx+1] = 0; - norm[indx+2] = 1; + if (ticksPlusMinus > 0) + h2 = -h1; + else if (side < 0) { + h2 = -h1; h1 = 0; + } - indx+=3; - } - } + path1 += this.vertical ? `M${h1},${handle.grpos}H${h2}` : `M${handle.grpos},${-h1}V${-h2}`; - const geometry = new BufferGeometry(); - geometry.setAttribute('position', new BufferAttribute(pos, 3)); - geometry.setAttribute('normal', new BufferAttribute(norm, 3)); + if (secondShift) + path2 += this.vertical ? `M${secondShift-h1},${handle.grpos}H${secondShift-h2}` : `M${handle.grpos},${secondShift+h1}V${secondShift+h2}`; + } - const material = new MeshBasicMaterial({ color: palette.getColor(colindx), side: DoubleSide, opacity: 0.5, vertexColors: false }), - mesh = new Mesh(geometry, material); - mesh.painter = painter; - main.toplevel.add(mesh); - } - ); + return real_draw ? path1 + path2 : ''; } -} - -/** @summary Return time offset value for given TAxis object - * @private */ -function getTimeOffset(axis) { - let dflt_time_offset = 788918400000; - if (!axis) return dflt_time_offset; - let idF = axis.fTimeFormat.indexOf('%F'); - if (idF < 0) return gStyle.fTimeOffset * 1000; - let sof = axis.fTimeFormat.slice(idF + 2); - // default string in axis offset - if (sof.indexOf('1995-01-01 00:00:00s0') == 0) return dflt_time_offset; - // special case, used from DABC painters - if ((sof == '0') || (sof == '')) return 0; - - // decode time from ROOT string - const next = (separ, min, max) => { - let pos = sof.indexOf(separ); - if (pos < 0) return min; - let val = parseInt(sof.slice(0, pos)); - sof = sof.slice(pos + 1); - if (!Number.isInteger(val) || (val < min) || (val > max)) return min; - return val; - }, year = next('-', 1970, 2300), - month = next('-', 1, 12) - 1, - day = next(' ', 1, 31), - hour = next(':', 0, 23), - min = next(':', 0, 59), - sec = next('s', 0, 59), - msec = next(' ', 0, 999), - dt = new Date(Date.UTC(year, month, day, hour, min, sec, msec)); - let offset = dt.getTime(); + /** @summary Returns modifier for axis label */ + findLabelModifier(axis, nlabel, positions) { + if (!axis.fModLabs) return null; + for (let n = 0; n < axis.fModLabs.arr.length; ++n) { + const mod = axis.fModLabs.arr[n]; - // now also handle suffix like GMT or GMT -0600 - sof = sof.toUpperCase(); + if ((mod.fLabValue !== undefined) && (mod.fLabNum === 0)) { + const eps = this.log ? positions[nlabel]*1e-6 : (this.scale_max - this.scale_min)*1e-6; + if (Math.abs(mod.fLabValue - positions[nlabel]) < eps) + return mod; + } - if (sof.indexOf('GMT') == 0) { - offset += dt.getTimezoneOffset() * 60000; - sof = sof.slice(4).trim(); - if (sof.length > 3) { - let p = 0, sign = 1000; - if (sof[0] == '-') { p = 1; sign = -1000; } - offset -= sign * (parseInt(sof.slice(p, p+2)) * 3600 + parseInt(sof.slice(p+2, p+4)) * 60); + if ((mod.fLabNum === nlabel + 1) || + ((mod.fLabNum < 0) && (nlabel === positions.length + mod.fLabNum))) + return mod; } + return null; } - return offset; -} - - -/** @summary Tries to choose time format for provided time interval - * @private */ -function chooseTimeFormat(awidth, ticks) { - if (awidth < .5) return ticks ? '%S.%L' : '%H:%M:%S.%L'; - if (awidth < 30) return ticks ? '%Mm%S' : '%H:%M:%S'; - awidth /= 60; if (awidth < 30) return ticks ? '%Hh%M' : '%d/%m %H:%M'; - awidth /= 60; if (awidth < 12) return ticks ? '%d-%Hh' : '%d/%m/%y %Hh'; - awidth /= 24; if (awidth < 15.218425) return ticks ? '%d/%m' : '%d/%m/%y'; - awidth /= 30.43685; if (awidth < 6) return '%d/%m/%y'; - awidth /= 12; if (awidth < 2) return ticks ? '%m/%y' : '%d/%m/%y'; - return '%Y'; -} + /** @summary Draw axis labels + * @return {Promise} with array label size and max width */ + async drawLabels(axis_g, axis, w, h, handle, side, labelsFont, labeloffset, tickSize, ticksPlusMinus, max_text_width, frame_ygap) { + const center_lbls = this.isCenteredLabels(), + rotate_lbls = axis.TestBit(EAxisBits.kLabelsVert), + label_g = [axis_g.append('svg:g').attr('class', 'axis_labels')], + lbl_pos = handle.lbl_pos || handle.major, + tilt_angle = gStyle.AxisTiltAngle ?? 25; + let textscale = 1, maxtextlen = 0, applied_scale = 0, + lbl_tilt = false, any_modified = false, max_textwidth = 0, max_tiltsize = 0; -/** - * @summary Base axis painter methods - * - * @private - */ + if (this.lbls_both_sides) + label_g.push(axis_g.append('svg:g').attr('class', 'axis_labels').attr('transform', this.vertical ? `translate(${w})` : `translate(0,${-h})`)); -const AxisPainterMethods = { + if (frame_ygap > 0) + max_tiltsize = frame_ygap / Math.sin(tilt_angle/180*Math.PI) - Math.tan(tilt_angle/180*Math.PI); - initAxisPainter() { - this.name = 'yaxis'; - this.kind = 'normal'; - this.func = null; - this.order = 0; // scaling order for axis labels + // function called when text is drawn to analyze width, required to correctly scale all labels + // must be function to correctly handle 'this' argument + function process_drawtext_ready(painter) { + const textwidth = this.result_width; + max_textwidth = Math.max(max_textwidth, textwidth); - this.full_min = 0; - this.full_max = 1; - this.scale_min = 0; - this.scale_max = 1; - this.ticks = []; // list of major ticks - }, + if (textwidth && ((!painter.vertical && !rotate_lbls) || (painter.vertical && rotate_lbls)) && !painter.log) { + let maxwidth = this.gap_before*0.45 + this.gap_after*0.45; + if (!this.gap_before) + maxwidth = 0.9*this.gap_after; + else if (!this.gap_after) + maxwidth = 0.9*this.gap_before; + textscale = Math.min(textscale, maxwidth / textwidth); + } else if (painter.vertical && max_text_width && this.normal_side && (max_text_width - labeloffset > 20) && (textwidth > max_text_width - labeloffset)) + textscale = Math.min(textscale, (max_text_width - labeloffset) / textwidth); - /** @summary Cleanup axis painter */ - cleanupAxisPainter() { - this.ticks = []; - delete this.format; - delete this.func; - delete this.tfunc1; - delete this.tfunc2; - delete this.gr; - }, + if ((textscale > 0.0001) && (textscale < 0.7) && !any_modified && + !painter.vertical && !rotate_lbls && (maxtextlen > 5) && (label_g.length === 1) && (lbl_tilt === false)) + lbl_tilt = true; - /** @summary Assign often used members of frame painter */ - assignFrameMembers(fp, axis) { - fp['gr'+axis] = this.gr; // fp.grx - fp['log'+axis] = this.log; // fp.logx - fp[`scale_${axis}min`] = this.scale_min; // fp.scale_xmin - fp[`scale_${axis}max`] = this.scale_max; // fp.scale_xmax - }, + let scale = textscale; - /** @summary Convert axis value into the Date object */ - convertDate(v) { - return new Date(this.timeoffset + v*1000); - }, + if (lbl_tilt) { + if (max_tiltsize && max_textwidth) { + scale = Math.min(1, 0.8*max_tiltsize/max_textwidth); + if (scale < textscale) { + // if due to tilt scale is even smaller - ignore tilting + lbl_tilt = 0; + scale = textscale; + } + } else + scale *= 3; + } - /** @summary Convert graphical point back into axis value */ - revertPoint(pnt) { - let value = this.func.invert(pnt); - return (this.kind == 'time') ? (value - this.timeoffset) / 1000 : value; - }, + if (((scale > 0.0001) && (scale < 1)) || (lbl_tilt !== false)) { + applied_scale = 1/scale; + painter.scaleTextDrawing(applied_scale, label_g[0]); + } + } - /** @summary Provide label for time axis */ - formatTime(d, asticks) { - return asticks ? this.tfunc1(d) : this.tfunc2(d); - }, + for (let lcnt = 0; lcnt < label_g.length; ++lcnt) { + if (lcnt > 0) side = -side; - /** @summary Provide label for log axis */ - formatLog(d, asticks, fmt) { - let val = parseFloat(d), rnd = Math.round(val); - if (!asticks) - return ((rnd === val) && (Math.abs(rnd) < 1e9)) ? rnd.toString() : floatToString(val, fmt || gStyle.fStatFormat); - if (val <= 0) return null; - let vlog = Math.log10(val), base = this.logbase; - if (base !== 10) vlog = vlog / Math.log10(base); - if (this.moreloglabels || (Math.abs(vlog - Math.round(vlog)) < 0.001)) { - if (!this.noexp && (asticks != 2)) - return this.formatExp(base, Math.floor(vlog+0.01), val); + let lastpos = 0; + const fix_coord = this.vertical ? -labeloffset*side : labeloffset*side + ticksPlusMinus*tickSize; - return vlog < 0 ? val.toFixed(Math.round(-vlog+0.5)) : val.toFixed(0); - } - return null; - }, + this.startTextDrawing(labelsFont, 'font', label_g[lcnt]); - /** @summary Provide label for normal axis */ - formatNormal(d, asticks, fmt) { - let val = parseFloat(d); - if (asticks && this.order) val = val / Math.pow(10, this.order); + for (let nmajor = 0; nmajor < lbl_pos.length; ++nmajor) { + let text = this.format(lbl_pos[nmajor], true); + if (text === null) continue; - if (val === Math.round(val)) - return Math.abs(val) < 1e9 ? val.toFixed(0) : val.toExponential(4); + const mod = this.findLabelModifier(axis, nmajor, lbl_pos); + if (mod?.fTextSize === 0) continue; - if (asticks) return (this.ndig>10) ? val.toExponential(this.ndig-11) : val.toFixed(this.ndig); + if (mod) any_modified = true; + if (mod?.fLabText) text = mod.fLabText; - return floatToString(val, fmt || gStyle.fStatFormat); - }, + const arg = { text, color: labelsFont.color, latex: 1, draw_g: label_g[lcnt], normal_side: (lcnt === 0) }; + let pos = Math.round(this.func(lbl_pos[nmajor])); - /** @summary Provide label for exponential form */ - formatExp(base, order, value) { - let res = ''; - if (value) { - value = Math.round(value/Math.pow(base,order)); - if ((value!=0) && (value!=1)) res = value.toString() + (settings.Latex ? '#times' : 'x'); - } - if (Math.abs(base-Math.exp(1)) < 0.001) - res += 'e'; - else - res += base.toString(); - if (settings.Latex > constants$1.Latex.Symbols) - return res + `^{${order}}`; - const superscript_symbols = { - '0': '\u2070', '1': '\xB9', '2': '\xB2', '3': '\xB3', '4': '\u2074', '5': '\u2075', - '6': '\u2076', '7': '\u2077', '8': '\u2078', '9': '\u2079', '-': '\u207B' - }; - let str = order.toString(); - for (let n = 0; n < str.length; ++n) - res += superscript_symbols[str[n]]; - return res; - }, + if (mod?.fTextColor > 0) arg.color = this.getColor(mod.fTextColor); - /** @summary Convert 'raw' axis value into text */ - axisAsText(value, fmt) { - if (this.kind == 'time') - value = this.convertDate(value); - if (this.format) - return this.format(value, false, fmt); - return value.toPrecision(4); - }, + arg.gap_before = (nmajor > 0) ? Math.abs(Math.round(pos - this.func(lbl_pos[nmajor-1]))) : 0; - /** @summary Produce ticks for d3.scaleLog - * @desc Fixing following problem, described [here]{@link https://stackoverflow.com/questions/64649793} */ - poduceLogTicks(func, number) { - const linearArray = arr => { - let sum1 = 0, sum2 = 0; - for (let k = 1; k < arr.length; ++k) { - let diff = (arr[k] - arr[k-1]); - sum1 += diff; - sum2 += diff**2; - } - let mean = sum1/(arr.length-1), - dev = sum2/(arr.length-1) - mean**2; + arg.gap_after = (nmajor < lbl_pos.length-1) ? Math.abs(Math.round(this.func(lbl_pos[nmajor+1])-pos)) : 0; - if (dev <= 0) return true; - if (Math.abs(mean) < 1e-100) return false; - return Math.sqrt(dev)/mean < 1e-6; - }; + if (center_lbls) { + const gap = arg.gap_after || arg.gap_before; + pos = Math.round(pos - ((this.vertical !== this.reverse) ? 0.5*gap : -0.5*gap)); + if ((pos < -5) || (pos > (this.vertical ? h : w) + 5)) continue; + } - let arr = func.ticks(number); + maxtextlen = Math.max(maxtextlen, text.length); - while ((number > 4) && linearArray(arr)) { - number = Math.round(number*0.8); - arr = func.ticks(number); - } + if (this.vertical) { + arg.x = fix_coord; + arg.y = pos; + arg.align = rotate_lbls ? ((side < 0) ? 23 : 20) : ((side < 0) ? 12 : 32); + } else { + arg.x = pos; + arg.y = fix_coord; + arg.align = rotate_lbls ? ((side < 0) ? 12 : 32) : ((side < 0) ? 20 : 23); + if (arg.align % 10 === 3) arg.y -= labelsFont.size*0.1; // font takes 10% more by top align + } - // if still linear array, try to sort out 'bad' ticks - if ((number < 5) && linearArray(arr) && this.logbase && (this.logbase != 10)) { - let arr2 = []; - arr.forEach(val => { - let pow = Math.log10(val) / Math.log10(this.logbase); - if (Math.abs(Math.round(pow) - pow) < 0.01) arr2.push(val); - }); - if (arr2.length > 0) arr = arr2; - } + if (rotate_lbls) + arg.rotate = 270; + else if (mod && mod.fTextAngle !== -1) + arg.rotate = -mod.fTextAngle; - return arr; - }, + // only for major text drawing scale factor need to be checked + if (lcnt === 0) arg.post_process = process_drawtext_ready; - /** @summary Produce axis ticks */ - produceTicks(ndiv, ndiv2) { - if (!this.noticksopt) { - let total = ndiv * (ndiv2 || 1); + this.drawText(arg); - if (this.log) return this.poduceLogTicks(this.func, total); + if (lastpos && (pos !== lastpos) && ((this.vertical && !rotate_lbls) || (!this.vertical && rotate_lbls))) { + const axis_step = Math.abs(pos - lastpos); + textscale = Math.min(textscale, 0.9*axis_step/labelsFont.size); + } - let dom = this.func.domain(); + lastpos = pos; + } - const check = ticks => { - if (ticks.length <= total) return true; - if (ticks.length > total + 1) return false; - return (ticks[0] === dom[0]) || (ticks[total] === dom[1]); // special case of N+1 ticks, but match any range - }; + if (this.order) { + let xoff = 0, yoff = 0; + if (this.name === 'xaxis') { + xoff = gStyle.fXAxisExpXOffset || 0; + yoff = gStyle.fXAxisExpYOffset || 0; + } else if (this.name === 'yaxis') { + xoff = gStyle.fYAxisExpXOffset || 0; + yoff = gStyle.fYAxisExpYOffset || 0; + } - let res1 = this.func.ticks(total); - if (ndiv2 || check(res1)) return res1; + if (xoff) xoff = Math.round(xoff * (this.getPadPainter()?.getPadWidth() ?? 0)); + if (yoff) yoff = Math.round(yoff * (this.getPadPainter()?.getPadHeight() ?? 0)); - let res2 = this.func.ticks(Math.round(total * 0.7)); - return (res2.length > 2) && check(res2) ? res2 : res1; + this.drawText({ color: labelsFont.color, + x: xoff + (this.vertical ? side*5 : w+5), + y: yoff + (this.has_obstacle ? fix_coord : (this.vertical ? -3 : -3*side)), + align: this.vertical ? ((side < 0) ? 30 : 10) : ((this.has_obstacle ^ (side < 0)) ? 13 : 10), + latex: 1, + text: '#times' + this.formatExp(10, this.order), + draw_g: label_g[lcnt] }); + } } - let dom = this.func.domain(), ticks = []; - if (ndiv2) ndiv = (ndiv-1) * ndiv2; - for (let n = 0; n <= ndiv; ++n) - ticks.push((dom[0]*(ndiv-n) + dom[1]*n)/ndiv); - return ticks; - }, + // first complete major labels drawing + return this.finishTextDrawing(label_g[0], true).then(() => { + if (label_g.length > 1) { + // now complete drawing of second half with scaling if necessary + if (applied_scale) + this.scaleTextDrawing(applied_scale, label_g[1]); + return this.finishTextDrawing(label_g[1], true); + } + }).then(() => { + if (lbl_tilt) { + label_g[0].selectAll('text').each(function() { + const txt = select(this), tr = txt.attr('transform'); + txt.attr('transform', `${tr} rotate(${tilt_angle})`).style('text-anchor', 'start'); + }); + } - /** @summary Method analyze mouse wheel event and returns item with suggested zooming range */ - analyzeWheelEvent(evnt, dmin, item, test_ignore) { - if (!item) item = {}; + return max_textwidth; + }); + } - let delta = 0, delta_left = 1, delta_right = 1; + /** @summary Extract major draw attributes, which are also used in interactive operations + * @private */ + extractDrawAttributes(scalingSize, w, h) { + const axis = this.getObject(), + pp = this.getPadPainter(), + pad_w = pp?.getPadWidth() || scalingSize || w/0.8, // use factor 0.8 as ratio between frame and pad size + pad_h = pp?.getPadHeight() || scalingSize || h/0.8; + let tickSize = 0, tickScalingSize = 0, titleColor, offset; - if ('dleft' in item) { delta_left = item.dleft; delta = 1; } - if ('dright' in item) { delta_right = item.dright; delta = 1; } + this.scalingSize = scalingSize || Math.max(Math.min(pad_w, pad_h), 10); - if (item.delta) { - delta = item.delta; - } else if (evnt) { - delta = evnt.wheelDelta ? -evnt.wheelDelta : (evnt.deltaY || evnt.detail); + if (this.is_gaxis) { + const optionSize = axis.fChopt.indexOf('S') >= 0; + this.optionUnlab = axis.fChopt.indexOf('U') >= 0; + this.optionMinus = (axis.fChopt.indexOf('-') >= 0) || axis.TestBit(EAxisBits.kTickMinus); + this.optionPlus = (axis.fChopt.indexOf('+') >= 0) || axis.TestBit(EAxisBits.kTickPlus); + this.optionNoopt = (axis.fChopt.indexOf('N') >= 0); // no ticks position optimization + this.optionInt = (axis.fChopt.indexOf('I') >= 0); // integer labels + this.optionText = (axis.fChopt.indexOf('T') >= 0); // text scaling? + this.createAttLine({ attr: axis }); + tickScalingSize = scalingSize || (this.vertical ? 1.7*h : 0.6*w); + tickSize = optionSize ? axis.fTickSize : 0.03; + titleColor = this.getColor(axis.fTextColor); + offset = axis.fLabelOffset; + if ((this.vertical && axis.fY1 > axis.fY2 && !this.optionMinus) || (!this.vertical && axis.fX1 > axis.fX2)) + offset = -offset; + } else { + this.optionUnlab = false; + this.optionMinus = this.vertical ^ this.invert_side; + this.optionPlus = !this.optionMinus; + this.optionNoopt = false; // no ticks position optimization + this.optionInt = false; // integer labels + this.optionText = false; + this.createAttLine({ color: axis.fAxisColor, width: 1, style: 1 }); + tickScalingSize = scalingSize || (this.vertical ? pad_w : pad_h); + tickSize = axis.fTickLength; + titleColor = this.getColor(axis.fTitleColor); + offset = axis.fLabelOffset; } - if (!delta || (test_ignore && item.ignore)) return; - - delta = (delta < 0) ? -0.2 : 0.2; - delta_left *= delta; - delta_right *= delta; - - let lmin = item.min = this.scale_min, - lmax = item.max = this.scale_max, - gmin = this.full_min, - gmax = this.full_max; - - if ((item.min === item.max) && (delta < 0)) { - item.min = gmin; - item.max = gmax; - } + offset += (this.vertical ? 0.002 : 0.005); - if (item.min >= item.max) return; + if (this.kind === 'labels') + this.optionText = true; - if (item.reverse) dmin = 1 - dmin; + this.optionNoexp = axis.TestBit(EAxisBits.kNoExponent); - if ((dmin > 0) && (dmin < 1)) { - if (this.log) { - let factor = (item.min > 0) ? Math.log10(item.max/item.min) : 2; - if (factor>10) factor = 10; else if (factor < 0.01) factor = 0.01; - item.min = item.min / Math.pow(10, factor*delta_left*dmin); - item.max = item.max * Math.pow(10, factor*delta_right*(1-dmin)); - } else if ((delta_left === -delta_right) && !item.reverse) { - // shift left/right, try to keep range constant - let delta = (item.max - item.min) * delta_right * dmin; + this.ticksSize = Math.round(tickSize * tickScalingSize); + if (scalingSize && (this.ticksSize < 0)) + this.ticksSize = -this.ticksSize; - if ((Math.round(item.max) === item.max) && (Math.round(item.min) === item.min) && (Math.abs(delta) > 1)) delta = Math.round(delta); + if (this.maxTickSize && (this.ticksSize > this.maxTickSize)) this.ticksSize = this.maxTickSize; - if (item.min + delta < gmin) - delta = gmin - item.min; - else if (item.max + delta > gmax) - delta = gmax - item.max; + // now used only in 3D drawing + this.ticksColor = this.lineatt.color; + this.ticksWidth = this.lineatt.width; - if (delta != 0) { - item.min += delta; - item.max += delta; - } else { - delete item.min; - delete item.max; - } + const k = this.optionText ? 0.66666 : 1; // set TGaxis.cxx, line 1504 + this.labelSize = Math.round((axis.fLabelSize < 1) ? k * axis.fLabelSize * this.scalingSize : k * axis.fLabelSize); + this.labelsOffset = Math.round(offset * this.scalingSize); + this.labelsFont = new FontHandler(axis.fLabelFont, this.labelSize, scalingSize); + if ((this.labelSize <= 0) || (Math.abs(axis.fLabelOffset) > 1.1)) this.optionUnlab = true; // disable labels when size not specified + this.labelsFont.setColor(this.getColor(axis.fLabelColor)); - } else { - let rx_left = (item.max - item.min), rx_right = rx_left; - if (delta_left > 0) rx_left = 1.001 * rx_left / (1-delta_left); - item.min += -delta_left*dmin*rx_left; - if (delta_right > 0) rx_right = 1.001 * rx_right / (1-delta_right); - item.max -= -delta_right*(1-dmin)*rx_right; - } - if (item.min >= item.max) { - item.min = item.max = undefined; - } else if (delta_left !== delta_right) { - // extra check case when moving left or right - if (((item.min < gmin) && (lmin === gmin)) || - ((item.max > gmax) && (lmax === gmax))) - item.min = item.max = undefined; - } else { - if (item.min < gmin) item.min = gmin; - if (item.max > gmax) item.max = gmax; - } + this.fTitle = axis.fTitle; + if (this.fTitle) { + this.titleSize = (axis.fTitleSize >= 1) ? axis.fTitleSize : Math.round(axis.fTitleSize * this.scalingSize); + this.titleFont = new FontHandler(axis.fTitleFont, this.titleSize, scalingSize); + this.titleFont.setColor(titleColor); + this.offsetScaling = (axis.fTitleSize >= 1) ? 1 : (this.vertical ? pad_w : pad_h) / this.scalingSize; + this.titleOffset = axis.fTitleOffset; + if (!this.titleOffset && this.name[0] === 'x') + this.titleOffset = gStyle.fXaxis.fTitleOffset; + this.titleOffset *= this.titleSize * this.offsetScaling; + this.titleCenter = axis.TestBit(EAxisBits.kCenterTitle); + this.titleOpposite = axis.TestBit(EAxisBits.kOppositeTitle); } else { - item.min = item.max = undefined; + delete this.titleSize; + delete this.titleFont; + delete this.offsetScaling; + delete this.titleOffset; + delete this.titleCenter; + delete this.titleOpposite; } + } - item.changed = ((item.min !== undefined) && (item.max !== undefined)); + /** @summary function draws TAxis or TGaxis object + * @return {Promise} for drawing ready */ + async drawAxis(layer, w, h, transform, secondShift, disable_axis_drawing, max_text_width, calculate_position, frame_ygap) { + const axis = this.getObject(), + swap_side = this.swap_side || false; + let axis_g = layer, draw_lines = true; - return item; - } + // shift for second ticks set (if any) + if (!secondShift) + secondShift = 0; + else if (this.invert_side) + secondShift = -secondShift; -}; // AxisPainterMethods + this.extractDrawAttributes(undefined, w, h); + if (this.is_gaxis) + draw_lines = axis.fLineColor !== 0; -/** - * @summary Painter for TAxis/TGaxis objects - * - * @private - */ + // indicate that attributes created not for TAttLine, therefore cannot be updated as TAttLine in GED + this.lineatt.not_standard = true; -class TAxisPainter extends ObjectPainter { + if (!this.is_gaxis || (this.name === 'zaxis')) { + axis_g = layer.selectChild(`.${this.name}_container`); + if (axis_g.empty()) + axis_g = layer.append('svg:g').attr('class', `${this.name}_container`); + else + axis_g.selectAll('*').remove(); + } - /** @summary constructor - * @param {object|string} dom - identifier or dom element - * @param {object} axis - object to draw - * @param {boolean} embedded - if true, painter used in other objects painters */ - constructor(dom, axis, embedded) { - super(dom, axis); + let axis_lines = ''; + if (draw_lines) { + axis_lines = 'M0,0' + (this.vertical ? `v${h}` : `h${w}`); + if (secondShift) + axis_lines += this.vertical ? `M${secondShift},0v${h}` : `M0,${secondShift}h${w}`; + } - Object.assign(this, AxisPainterMethods); - this.initAxisPainter(); + axis_g.attr('transform', transform); - this.embedded = embedded; // indicate that painter embedded into the histo painter - this.invert_side = false; - this.lbls_both_sides = false; // draw labels on both sides - } + let side = 1, ticksPlusMinus = 0; - /** @summary cleanup painter */ - cleanup() { - this.cleanupAxisPainter(); - super.cleanup(); - } + if (this.optionPlus && this.optionMinus) { + side = 1; ticksPlusMinus = 1; + } else if (this.optionMinus) + side = (swap_side ^ this.vertical) ? 1 : -1; + else if (this.optionPlus) + side = (swap_side ^ this.vertical) ? -1 : 1; - /** @summary Use in GED to identify kind of axis */ - getAxisType() { return clTAxis; } + // first draw ticks - /** @summary Configure axis painter - * @desc Axis can be drawn inside frame group with offset to 0 point for the frame - * Therefore one should distinguish when caclulated coordinates used for axis drawing itself or for calculation of frame coordinates - * @private */ - configureAxis(name, min, max, smin, smax, vertical, range, opts) { - this.name = name; - this.full_min = min; - this.full_max = max; - this.kind = 'normal'; - this.vertical = vertical; - this.log = opts.log || 0; - this.symlog = opts.symlog || false; - this.reverse = opts.reverse || false; - this.swap_side = opts.swap_side || false; - this.fixed_ticks = opts.fixed_ticks || null; - this.maxTickSize = opts.maxTickSize || 0; + const handle = this.createTicks(false, this.optionNoexp, this.optionNoopt, this.optionInt); - let axis = this.getObject(); + axis_lines += this.produceTicksPath(handle, side, this.ticksSize, ticksPlusMinus, secondShift, draw_lines && !disable_axis_drawing && !this.disable_ticks); - if (opts.time_scale || axis.fTimeDisplay) { - this.kind = 'time'; - this.timeoffset = getTimeOffset(axis); - } else { - this.kind = !axis.fLabels ? 'normal' : 'labels'; + if (!disable_axis_drawing && axis_lines && !this.lineatt.empty()) { + axis_g.append('svg:path') + .attr('d', axis_lines) + .call(this.lineatt.func); } - if (this.kind == 'time') { - this.func = time().domain([this.convertDate(smin), this.convertDate(smax)]); - } else if (this.log) { - this.logbase = this.log === 2 ? 2 : 10; - if (smax <= 0) smax = 1; + let title_shift_x = 0, title_shift_y = 0, title_g = null, labelsMaxWidth = 0; + // draw labels (sometime on both sides) + const pr = (disable_axis_drawing || this.optionUnlab) + ? Promise.resolve(0) + : this.drawLabels(axis_g, axis, w, h, handle, side, this.labelsFont, this.labelsOffset, this.ticksSize, ticksPlusMinus, max_text_width, frame_ygap); - if ((smin <= 0) && axis && !opts.logcheckmin) - for (let i = 0; i < axis.fNbins; ++i) { - smin = Math.max(smin, axis.GetBinLowEdge(i+1)); - if (smin > 0) break; - } + return pr.then(maxw => { + labelsMaxWidth = maxw; - if ((smin <= 0) && opts.log_min_nz) - smin = opts.log_min_nz; + if (settings.Zooming && !this.disable_zooming && !this.isBatchMode()) { + const labelSize = Math.max(this.labelsFont.size, 5), + r = axis_g.append('svg:rect') + .attr('class', 'axis_zoom') + .style('opacity', '0') + .style('cursor', 'crosshair'); - if ((smin <= 0) || (smin >= smax)) - smin = smax * (opts.logminfactor || 1e-4); + if (this.vertical) { + const rw = (labelsMaxWidth || 2*labelSize) + 3; + r.attr('x', (side > 0) ? -rw : 0).attr('y', 0) + .attr('width', rw).attr('height', h); + } else { + r.attr('x', 0).attr('y', (side > 0) ? 0 : -labelSize - 3) + .attr('width', w).attr('height', labelSize + 3); + } + } - this.func = log().base((this.log == 2) ? 2 : 10).domain([smin,smax]); - } else if (this.symlog) { - let v = Math.max(Math.abs(smin), Math.abs(smax)); - if (Number.isInteger(this.symlog) && (this.symlog > 0)) - v *= Math.pow(10,-1*this.symlog); - else - v *= 0.01; - this.func = symlog().constant(v).domain([smin,smax]); - } else { - this.func = linear().domain([smin,smax]); - } + this.position = 0; - if (this.vertical ^ this.reverse) { - let d = range[0]; range[0] = range[1]; range[1] = d; - } + if (calculate_position) { + const node1 = axis_g.node(), node2 = this.getPadSvg().node(); + if (node1 && node2 && node1.getBoundingClientRect && node2.getBoundingClientRect) { + const rect1 = node1.getBoundingClientRect(), + rect2 = node2.getBoundingClientRect(); - this.func.range(range); + this.position = rect1.left - rect2.left; // use to control left position of Y scale + } + if (node1 && !node2) + console.warn('Why PAD element missing when search for position'); + } - this.scale_min = smin; - this.scale_max = smax; + if (!this.fTitle || disable_axis_drawing) return true; - if (this.kind == 'time') - this.gr = val => this.func(this.convertDate(val)); - else if (this.log) - this.gr = val => (val < this.scale_min) ? (this.vertical ? this.func.range()[0]+5 : -5) : this.func(val); - else - this.gr = this.func; + title_g = axis_g.append('svg:g').attr('class', 'axis_title'); - let is_gaxis = (axis?._typename === clTGaxis); + let title_offest_k = side; + const rotate = axis.TestBit(EAxisBits.kRotateTitle) ? -1 : 1; - delete this.format;// remove formatting func + this.startTextDrawing(this.titleFont, 'font', title_g); - let ndiv = 508; - if (is_gaxis) - ndiv = axis.fNdiv; - else if (axis) - ndiv = Math.max(axis.fNdivisions, 4); + const xor_reverse = swap_side ^ this.titleOpposite, myxor = (rotate < 0) ^ xor_reverse; - this.nticks = ndiv % 100; - this.nticks2 = (ndiv % 10000 - this.nticks) / 100; - this.nticks3 = Math.floor(ndiv/10000); + this.title_align = this.titleCenter ? 'middle' : (myxor ? 'begin' : 'end'); - if (axis && !is_gaxis && (this.nticks > 20)) this.nticks = 20; + if (this.vertical) { + title_offest_k *= -1.6; - let gr_range = Math.abs(this.func.range()[1] - this.func.range()[0]); - if (gr_range <= 0) gr_range = 100; + title_shift_x = Math.round(title_offest_k * this.titleOffset); - if (this.kind == 'time') { - if (this.nticks > 8) this.nticks = 8; + if ((this.name === 'zaxis') && this.is_gaxis && ('getBoundingClientRect' in axis_g.node())) { + // special handling for color palette labels - draw them always on right side + const rect = axis_g.node().getBoundingClientRect(); + if (title_shift_x < rect.waddMoveHandleridth - this.ticksSize) + title_shift_x = Math.round(rect.width - this.ticksSize); + } - let scale_range = this.scale_max - this.scale_min, - idF = axis.fTimeFormat.indexOf('%F'), - tf1 = (idF >= 0) ? axis.fTimeFormat.slice(0, idF) : axis.fTimeFormat, - tf2 = chooseTimeFormat(scale_range / gr_range, false); + title_shift_y = Math.round(this.titleCenter ? h/2 : (xor_reverse ? h : 0)); - if (!tf1 || (scale_range < 0.1 * (this.full_max - this.full_min))) - tf1 = chooseTimeFormat(scale_range / this.nticks, true); + this.drawText({ align: this.title_align+';middle', + rotate: (rotate < 0) ? 90 : 270, + text: this.fTitle, color: this.titleFont.color, draw_g: title_g }); + } else { + title_offest_k *= 1.6; - this.tfunc1 = this.tfunc2 = timeFormat(tf1); - if (tf2 !== tf1) - this.tfunc2 = timeFormat(tf2); + title_shift_x = Math.round(this.titleCenter ? w/2 : (xor_reverse ? 0 : w)); + title_shift_y = Math.round(title_offest_k * this.titleOffset); + this.drawText({ align: this.title_align+';middle', + rotate: (rotate < 0) ? 180 : 0, + text: this.fTitle, color: this.titleFont.color, draw_g: title_g }); + } - this.format = this.formatTime; + this.addTitleDrag(title_g, this.vertical, title_offest_k, swap_side, this.vertical ? h : w); - } else if (this.log) { - if (this.nticks2 > 1) { - this.nticks *= this.nticks2; // all log ticks (major or minor) created centrally - this.nticks2 = 1; + return this.finishTextDrawing(title_g); + }).then(() => { + if (title_g) { + if (!this.titleOffset && this.vertical && labelsMaxWidth) + title_shift_x = Math.round(-side * (labelsMaxWidth + 0.7*this.offsetScaling*this.titleSize)); + makeTranslate(title_g, title_shift_x, title_shift_y); + title_g.property('shift_x', title_shift_x) + .property('shift_y', title_shift_y); } - this.noexp = axis ? axis.TestBit(EAxisBits.kNoExponent) : false; - if ((this.scale_max < 300) && (this.scale_min > 0.3)) this.noexp = true; - this.moreloglabels = axis ? axis.TestBit(EAxisBits.kMoreLogLabels) : false; - this.format = this.formatLog; + return this; + }); + } - } else if (this.kind == 'labels') { - this.nticks = 50; // for text output allow max 50 names - let scale_range = this.scale_max - this.scale_min; - if (this.nticks > scale_range) - this.nticks = Math.round(scale_range); +} // class TAxisPainter - this.regular_labels = true; +const logminfactorX = 0.0001, logminfactorY = 3e-4; - if (axis && axis.fNbins && axis.fLabels) { - if ((axis.fNbins != Math.round(axis.fXmax - axis.fXmin)) || - (axis.fXmin != 0) || (axis.fXmax != axis.fNbins)) { - this.regular_labels = false; +/** @summary Configure tooltip enable flag for painter + * @private */ +function setPainterTooltipEnabled(painter, on) { + if (!painter) return; + + const fp = painter.getFramePainter(); + if (isFunc(fp?.setTooltipEnabled)) { + fp.setTooltipEnabled(on); + fp.processFrameTooltipEvent(null); + } + // this is 3D control object + if (isFunc(painter.control?.setTooltipEnabled)) + painter.control.setTooltipEnabled(on); +} + +/** @summary Return pointers on touch event + * @private */ +function get_touch_pointers(event, node) { + return event.$touch_arr ?? pointers(event, node); +} + +/** @summary Returns coordinates transformation func + * @private */ +function getEarthProjectionFunc(id) { + switch (id) { + // Aitoff2xy + case 1: return (l, b) => { + const DegToRad = Math.PI/180, + alpha2 = (l/2)*DegToRad, + delta = b*DegToRad, + r2 = Math.sqrt(2), + f = 2*r2/Math.PI, + cdec = Math.cos(delta), + denom = Math.sqrt(1.0 + cdec*Math.cos(alpha2)); + return { + x: cdec*Math.sin(alpha2)*2.0*r2/denom/f/DegToRad, + y: Math.sin(delta)*r2/denom/f/DegToRad + }; + }; + // mercator + case 2: return (l, b) => { return { x: l, y: Math.log(Math.tan((Math.PI/2 + b/180*Math.PI)/2)) }; }; + // sinusoidal + case 3: return (l, b) => { return { x: l*Math.cos(b/180*Math.PI), y: b }; }; + // parabolic + case 4: return (l, b) => { return { x: l*(2.0*Math.cos(2*b/180*Math.PI/3) - 1), y: 180*Math.sin(b/180*Math.PI/3) }; }; + // Mollweide projection + case 5: return (l, b) => { + const theta0 = b * Math.PI/180; + let theta = theta0, num, den; + for (let i = 0; i < 100; i++) { + num = 2 * theta + Math.sin(2 * theta) - Math.PI * Math.sin(theta0); + den = 4 * (Math.cos(theta)**2); + if (den < 1e-20) { + theta = theta0; + break; } + theta -= num / den; + if (Math.abs(num / den) < 1e-4) break; } + return { + x: l * Math.cos(theta), + y: 90 * Math.sin(theta) + }; + }; + } +} - this.nticks2 = 1; +// global, allow single drag at once +let drag_rect = null, drag_kind = '', drag_painter = null; - this.format = this.formatLabels; - } else { - this.order = 0; - this.ndig = 0; - this.format = this.formatNormal; +/** @summary Check if dragging performed currently + * @private */ +function is_dragging(painter, kind) { + return drag_rect && (drag_painter === painter) && (drag_kind === kind); +} + +/** @summary Add drag for interactive rectangular elements for painter + * @private */ +function addDragHandler(_painter, arg) { + if (!settings.MoveResize) return; + + const painter = _painter, pp = painter.getPadPainter(); + if (pp?._fast_drawing || pp?.isBatchMode()) return; + + if (!isFunc(arg.getDrawG)) + arg.getDrawG = () => painter?.draw_g; + + function makeResizeElements(group, handler) { + function addElement(cursor, d) { + const clname = 'js_' + cursor.replace(/[-]/g, '_'); + let elem = group.selectChild('.' + clname); + if (arg.cleanup) return elem.remove(); + if (elem.empty()) elem = group.append('path').classed(clname, true); + elem.style('opacity', 0).style('cursor', cursor).attr('d', d); + if (handler) elem.call(handler); } - } - /** @summary Return scale min */ - getScaleMin() { - return this.func ? this.func.domain()[0] : 0; - } + addElement('nw-resize', 'M2,2h15v-5h-20v20h5Z'); + addElement('ne-resize', `M${arg.width-2},2h-15v-5h20v20h-5 Z`); + addElement('sw-resize', `M2,${arg.height-2}h15v5h-20v-20h5Z`); + addElement('se-resize', `M${arg.width-2},${arg.height-2}h-15v5h20v-20h-5Z`); - /** @summary Return scale max */ - getScaleMax() { - return this.func ? this.func.domain()[1] : 0; + if (!arg.no_change_x) { + addElement('w-resize', `M-3,18h5v${Math.max(0, arg.height-2*18)}h-5Z`); + addElement('e-resize', `M${arg.width+3},18h-5v${Math.max(0, arg.height-2*18)}h5Z`); + } + if (!arg.no_change_y) { + addElement('n-resize', `M18,-3v5h${Math.max(0, arg.width-2*18)}v-5Z`); + addElement('s-resize', `M18,${arg.height+3}v-5h${Math.max(0, arg.width-2*18)}v5Z`); + } } - /** @summary Provide label for axis value */ - formatLabels(d) { - let indx = parseFloat(d), a = this.getObject(); - if (!this.regular_labels) - indx = Math.round((indx - a.fXmin)/(a.fXmax - a.fXmin) * a.fNbins); - else - indx = Math.floor(indx); - if ((indx < 0) || (indx >= a.fNbins)) return null; - for (let i = 0; i < a.fLabels.arr.length; ++i) { - let tstr = a.fLabels.arr[i]; - if (tstr.fUniqueID === indx+1) return tstr.fString; + const complete_drag = (newx, newy, newwidth, newheight) => { + drag_painter = null; + drag_kind = ''; + if (drag_rect) { + drag_rect.remove(); + drag_rect = null; } - return null; - } - /** @summary Creates array with minor/middle/major ticks */ - createTicks(only_major_as_array, optionNoexp, optionNoopt, optionInt) { + const draw_g = arg.getDrawG(); - if (optionNoopt && this.nticks && (this.kind == 'normal')) - this.noticksopt = true; + if (!draw_g) + return false; - let handle = { nminor: 0, nmiddle: 0, nmajor: 0, func: this.func }, ticks; + const oldx = arg.x, oldy = arg.y; - if (this.fixed_ticks) { - ticks = []; - this.fixed_ticks.forEach(v => { - if ((v >= this.scale_min) && (v <= this.scale_max)) ticks.push(v); - }); - } else if ((this.kind == 'labels') && !this.regular_labels) { - ticks = []; - handle.lbl_pos = []; - let axis = this.getObject(); - for (let n = 0; n < axis.fNbins; ++n) { - let x = axis.fXmin + n / axis.fNbins * (axis.fXmax - axis.fXmin); - if ((x >= this.scale_min) && (x < this.scale_max)) { - handle.lbl_pos.push(x); - if (x > this.scale_min) ticks.push(x); - } - } - } else { - ticks = this.produceTicks(this.nticks); - } + if (arg.minwidth && newwidth < arg.minwidth) newwidth = arg.minwidth; + if (arg.minheight && newheight < arg.minheight) newheight = arg.minheight; - handle.minor = handle.middle = handle.major = ticks; + const change_size = (newwidth !== arg.width) || (newheight !== arg.height), + change_pos = (newx !== oldx) || (newy !== oldy); - if (only_major_as_array) { - let res = handle.major, delta = (this.scale_max - this.scale_min)*1e-5; - if (res[0] > this.scale_min + delta) res.unshift(this.scale_min); - if (res[res.length-1] < this.scale_max - delta) res.push(this.scale_max); - return res; - } + arg.x = newx; arg.y = newy; arg.width = newwidth; arg.height = newheight; - if ((this.nticks2 > 1) && (!this.log || (this.logbase === 10)) && !this.fixed_ticks) { - handle.minor = handle.middle = this.produceTicks(handle.major.length, this.nticks2); + if (!arg.no_transform) + makeTranslate(draw_g, newx, newy); - let gr_range = Math.abs(this.func.range()[1] - this.func.range()[0]); + setPainterTooltipEnabled(painter, true); - // avoid black filling by middle-size - if ((handle.middle.length <= handle.major.length) || (handle.middle.length > gr_range/3.5)) { - handle.minor = handle.middle = handle.major; - } else if ((this.nticks3 > 1) && !this.log) { - handle.minor = this.produceTicks(handle.middle.length, this.nticks3); - if ((handle.minor.length <= handle.middle.length) || (handle.minor.length > gr_range/1.7)) - handle.minor = handle.middle; + makeResizeElements(draw_g); + + if (change_size || change_pos) { + if (change_size && isFunc(arg.resize)) + arg.resize(newwidth, newheight); + + if (change_pos && isFunc(arg.move)) + arg.move(newx, newy, newx - oldx, newy - oldy); + + if (change_size || change_pos) { + if (arg.obj) { + const rect = arg.pad_rect ?? pp.getPadRect(); + arg.obj.fX1NDC = newx / rect.width; + arg.obj.fX2NDC = (newx + newwidth) / rect.width; + arg.obj.fY1NDC = 1 - (newy + newheight) / rect.height; + arg.obj.fY2NDC = 1 - newy / rect.height; + arg.obj.modified_NDC = true; // indicate that NDC was interactively changed, block in updated + } else if (isFunc(arg.move_resize)) + arg.move_resize(newx, newy, newwidth, newheight); + + if (isFunc(arg.redraw)) + arg.redraw(arg); } } - handle.reset = function() { - this.nminor = this.nmiddle = this.nmajor = 0; - }; + return change_size || change_pos; + }, - handle.next = function(doround) { - if (this.nminor >= this.minor.length) return false; + drag_move = drag().subject(Object), + drag_move_off = drag().subject(Object); - this.tick = this.minor[this.nminor++]; - this.grpos = this.func(this.tick); - if (doround) this.grpos = Math.round(this.grpos); - this.kind = 3; + drag_move_off.on('start', null).on('drag', null).on('end', null); - if ((this.nmiddle < this.middle.length) && (Math.abs(this.grpos - this.func(this.middle[this.nmiddle])) < 1)) { - this.nmiddle++; - this.kind = 2; - } + drag_move + .on('start', function(evnt) { + if (detectRightButton(evnt.sourceEvent) || drag_kind) return; + if (isFunc(arg.is_disabled) && arg.is_disabled('move')) return; - if ((this.nmajor < this.major.length) && (Math.abs(this.grpos - this.func(this.major[this.nmajor])) < 1) ) { - this.nmajor++; - this.kind = 1; - } - return true; - }; + closeMenu(); // close menu + setPainterTooltipEnabled(painter, false); // disable tooltip - handle.last_major = function() { - return (this.kind !== 1) ? false : this.nmajor == this.major.length; - }; + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - handle.next_major_grpos = function() { - if (this.nmajor >= this.major.length) return null; - return this.func(this.major[this.nmajor]); - }; + const pad_rect = arg.pad_rect ?? pp.getPadRect(), handle = { + x: arg.x, y: arg.y, width: arg.width, height: arg.height, + acc_x1: arg.x, acc_y1: arg.y, + pad_w: pad_rect.width - arg.width, + pad_h: pad_rect.height - arg.height, + drag_tm: new Date(), + path: `v${arg.height}h${arg.width}v${-arg.height}z`, + evnt_x: evnt.x, evnt_y: evnt.y + }; - this.order = 0; - this.ndig = 0; + drag_painter = painter; + drag_kind = 'move'; + drag_rect = select(arg.getDrawG().node().parentNode).append('path') + .attr('d', `M${handle.acc_x1},${handle.acc_y1}${handle.path}`) + .style('cursor', 'move') + .style('pointer-events', 'none') // let forward double click to underlying elements + .property('drag_handle', handle) + .call(addHighlightStyle, true); + }).on('drag', function(evnt) { + if (!is_dragging(painter, 'move')) return; - // at the moment when drawing labels, we can try to find most optimal text representation for them + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - if ((this.kind == 'normal') && !this.log && (handle.major.length > 0)) { + const handle = drag_rect.property('drag_handle'); - let maxorder = 0, minorder = 0, exclorder3 = false; + if (!arg.no_change_x) + handle.acc_x1 += evnt.dx; + if (!arg.no_change_y) + handle.acc_y1 += evnt.dy; - if (!optionNoexp) { - let maxtick = Math.max(Math.abs(handle.major[0]),Math.abs(handle.major[handle.major.length-1])), - mintick = Math.min(Math.abs(handle.major[0]),Math.abs(handle.major[handle.major.length-1])), - ord1 = (maxtick > 0) ? Math.round(Math.log10(maxtick)/3)*3 : 0, - ord2 = (mintick > 0) ? Math.round(Math.log10(mintick)/3)*3 : 0; + handle.x = Math.min(Math.max(handle.acc_x1, 0), handle.pad_w); + handle.y = Math.min(Math.max(handle.acc_y1, 0), handle.pad_h); - exclorder3 = (maxtick < 2e4); // do not show 10^3 for values below 20000 + drag_rect.attr('d', `M${handle.x},${handle.y}${handle.path}`); + }).on('end', function(evnt) { + if (!is_dragging(painter, 'move')) return; - if (maxtick || mintick) { - maxorder = Math.max(ord1,ord2) + 3; - minorder = Math.min(ord1,ord2) - 3; - } + evnt.sourceEvent.stopPropagation(); + evnt.sourceEvent.preventDefault(); + + const handle = drag_rect.property('drag_handle'); + + if (complete_drag(handle.x, handle.y, arg.width, arg.height) === false) { + const spent = (new Date()).getTime() - handle.drag_tm.getTime(); + + if (arg.ctxmenu && (spent > 600)) + showPainterMenu({ clientX: handle.evnt_x, clientY: handle.evnt_y, skip_close: 1 }, painter); + else if (arg.canselect && (spent <= 600)) + painter.getPadPainter()?.selectObjectPainter(painter); } + }); - // now try to find best combination of order and ndig for labels + const drag_resize = drag().subject(Object); - let bestorder = 0, bestndig = this.ndig, bestlen = 1e10; + drag_resize + .on('start', function(evnt) { + if (detectRightButton(evnt.sourceEvent) || drag_kind) return; + if (isFunc(arg.is_disabled) && arg.is_disabled('resize')) return; - for (let order = minorder; order <= maxorder; order+=3) { - if (exclorder3 && (order===3)) continue; - this.order = order; - this.ndig = 0; - let lbls = [], indx = 0, totallen = 0; - while (indx < handle.major.length) { - let lbl = this.format(handle.major[indx], true); - if (lbls.indexOf(lbl) < 0) { - lbls.push(lbl); - totallen += lbl.length; - indx++; - continue; - } - if (++this.ndig > 15) break; // not too many digits, anyway it will be exponential - lbls = []; indx = 0; totallen = 0; - } + closeMenu(); // close menu + setPainterTooltipEnabled(painter, false); // disable tooltip - // for order == 0 we should virtually remove '0.' and extra label on top - if (!order && (this.ndig < 4)) - totallen -= handle.major.length * 2 + 3; + evnt.sourceEvent.stopPropagation(); + evnt.sourceEvent.preventDefault(); - if (totallen < bestlen) { - bestlen = totallen; - bestorder = this.order; - bestndig = this.ndig; - } - } + const pad_rect = arg.pad_rect ?? pp.getPadRect(), handle = { + x: arg.x, y: arg.y, width: arg.width, height: arg.height, + acc_x1: arg.x, acc_y1: arg.y, + acc_x2: arg.x + arg.width, acc_y2: arg.y + arg.height, + pad_w: pad_rect.width, pad_h: pad_rect.height + }; - this.order = bestorder; - this.ndig = bestndig; + drag_painter = painter; + drag_kind = 'resize'; + drag_rect = select(arg.getDrawG().node().parentNode) + .append('rect') + .style('cursor', select(this).style('cursor')) + .attr('x', handle.acc_x1) + .attr('y', handle.acc_y1) + .attr('width', handle.acc_x2 - handle.acc_x1) + .attr('height', handle.acc_y2 - handle.acc_y1) + .property('drag_handle', handle) + .call(addHighlightStyle, true); + }).on('drag', function(evnt) { + if (!is_dragging(painter, 'resize')) return; - if (optionInt) { - if (this.order) console.warn(`Axis painter - integer labels are configured, but axis order ${this.order} is preferable`); - if (this.ndig) console.warn(`Axis painter - integer labels are configured, but ${this.ndig} decimal digits are required`); - this.ndig = 0; - this.order = 0; - } - } + evnt.sourceEvent.preventDefault(); + evnt.sourceEvent.stopPropagation(); - return handle; - } + const handle = drag_rect.property('drag_handle'), + elem = select(this); + let dx = evnt.dx, dy = evnt.dy; - /** @summary Is labels should be centered */ - isCenteredLabels() { - if (this.kind === 'labels') return true; - if (this.log) return false; - let axis = this.getObject(); - return axis && axis.TestBit(EAxisBits.kCenterLabels); - } + if (arg.no_change_x) dx = 0; + if (arg.no_change_y) dy = 0; - /** @summary Add interactive elements to draw axes title */ - addTitleDrag(title_g, vertical, offset_k, reverse, axis_length) { - if (!settings.MoveResize || isBatchMode()) return; + if (elem.classed('js_nw_resize')) { + handle.acc_x1 += dx; handle.acc_y1 += dy; + } else if (elem.classed('js_ne_resize')) { + handle.acc_x2 += dx; handle.acc_y1 += dy; + } else if (elem.classed('js_sw_resize')) { + handle.acc_x1 += dx; handle.acc_y2 += dy; + } else if (elem.classed('js_se_resize')) { + handle.acc_x2 += dx; handle.acc_y2 += dy; + } else if (elem.classed('js_w_resize')) + handle.acc_x1 += dx; + else if (elem.classed('js_n_resize')) + handle.acc_y1 += dy; + else if (elem.classed('js_e_resize')) + handle.acc_x2 += dx; + else if (elem.classed('js_s_resize')) + handle.acc_y2 += dy; + + const x1 = Math.max(0, handle.acc_x1), x2 = Math.min(handle.acc_x2, handle.pad_w), + y1 = Math.max(0, handle.acc_y1), y2 = Math.min(handle.acc_y2, handle.pad_h); - let drag_rect = null, - acc_x, acc_y, new_x, new_y, sign_0, alt_pos, curr_indx, - drag_move = drag().subject(Object); + handle.x = Math.min(x1, x2); + handle.y = Math.min(y1, y2); + handle.width = Math.abs(x2 - x1); + handle.height = Math.abs(y2 - y1); - drag_move - .on('start', evnt => { + drag_rect.attr('x', handle.x).attr('y', handle.y).attr('width', handle.width).attr('height', handle.height); + }).on('end', function(evnt) { + if (!is_dragging(painter, 'resize')) return; - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); + evnt.sourceEvent.preventDefault(); - let box = title_g.node().getBBox(), // check that elements visible, request precise value - title_length = vertical ? box.height : box.width; + const handle = drag_rect.property('drag_handle'); - new_x = acc_x = title_g.property('shift_x'); - new_y = acc_y = title_g.property('shift_y'); + complete_drag(handle.x, handle.y, handle.width, handle.height); + }); - sign_0 = vertical ? (acc_x > 0) : (acc_y > 0); // sign should remain + if (!arg.only_resize) + arg.getDrawG().style('cursor', arg.cleanup ? null : 'move').call(arg.cleanup ? drag_move_off : drag_move); - alt_pos = vertical ? [axis_length, axis_length/2, 0] : [0, axis_length/2, axis_length]; // possible positions - let off = vertical ? -title_length/2 : title_length/2; - if (this.title_align == 'middle') { - alt_pos[0] += off; - alt_pos[2] -= off; - } else if (this.title_align == 'begin') { - alt_pos[1] -= off; - alt_pos[2] -= 2*off; - } else { // end - alt_pos[0] += 2*off; - alt_pos[1] += off; - } + if (!arg.only_move) + makeResizeElements(arg.getDrawG(), drag_resize); +} - if (this.titleCenter) - curr_indx = 1; - else if (reverse ^ this.titleOpposite) - curr_indx = 0; - else - curr_indx = 2; +const TooltipHandler = { - alt_pos[curr_indx] = vertical ? acc_y : acc_x; + /** @desc only canvas info_layer can be used while other pads can overlay + * @return layer where frame tooltips are shown */ + hints_layer() { + return this.getCanvPainter()?.getLayerSvg('info_layer') ?? select(null); + }, - drag_rect = title_g.append('rect') - .classed('zoom', true) - .attr('x', box.x) - .attr('y', box.y) - .attr('width', box.width) - .attr('height', box.height) - .style('cursor', 'move'); -// .style('pointer-events','none'); // let forward double click to underlying elements - }).on('drag', evnt => { - if (!drag_rect) return; + /** @return true if tooltip is shown, use to prevent some other action */ + isTooltipShown() { + if (!this.tooltip_enabled || !this.isTooltipAllowed()) + return false; + const hintsg = this.hints_layer().selectChild('.objects_hints'); + return hintsg.empty() ? false : hintsg.property('hints_pad') === this.getPadName(); + }, - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); + /** @summary set tooltips enabled on/off */ + setTooltipEnabled(enabled) { + if (enabled !== undefined) + this.tooltip_enabled = enabled; + }, - acc_x += evnt.dx; - acc_y += evnt.dy; + /** @summary central function which let show selected hints for the object */ + processFrameTooltipEvent(pnt, evnt) { + if (pnt?.handler) { + // special use of interactive handler in the frame painter + const rect = this.draw_g?.selectChild('.main_layer'); + if (!rect || rect.empty()) + pnt = null; // disable + else if (pnt.touch && evnt) { + const pos = get_touch_pointers(evnt, rect.node()); + pnt = (pos && pos.length === 1) ? { touch: true, x: pos[0][0], y: pos[0][1] } : null; + } else if (evnt) { + const pos = pointer(evnt, rect.node()); + pnt = { touch: false, x: pos[0], y: pos[1] }; + } + } - let set_x, set_y, besti = 0, - p = vertical ? acc_y : acc_x; + let nhints = 0, nexact = 0, maxlen = 0, lastcolor1 = 0, usecolor1 = false, textheight = 11; + const hmargin = 3, wmargin = 3, hstep = 1.2, + frame_rect = this.getFrameRect(), + pp = this.getPadPainter(), + pad_width = pp.getPadWidth(), + font = new FontHandler(160, textheight), + disable_tootlips = !this.isTooltipAllowed() || !this.tooltip_enabled; - for (let i = 1; i < 3; ++i) - if (Math.abs(p - alt_pos[i]) < Math.abs(p - alt_pos[besti])) besti = i; + if (pnt) { + pnt.disabled = disable_tootlips; // indicate that highlighting is not required + pnt.painters = true; // get also painter + } - if (vertical) { - set_x = acc_x; - set_y = alt_pos[besti]; - } else { - set_y = acc_y; - set_x = alt_pos[besti]; - } + // collect tooltips from pad painter - it has list of all drawn objects + const hints = pp?.processPadTooltipEvent(pnt) ?? []; - if (sign_0 === (vertical ? (set_x > 0) : (set_y > 0))) { - new_x = set_x; new_y = set_y; curr_indx = besti; - title_g.attr('transform', `translate(${new_x},${new_y})`); - } + if (pp?._deliver_webcanvas_events && pp?.is_active_pad && pnt && isFunc(pp?.deliverWebCanvasEvent)) + pp.deliverWebCanvasEvent('move', frame_rect.x + pnt.x, frame_rect.y + pnt.y, hints); - }).on('end', evnt => { - if (!drag_rect) return; + if (pnt?.touch) textheight = 15; - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); + for (let n = 0; n < hints.length; ++n) { + const hint = hints[n]; + if (!hint) continue; - title_g.property('shift_x', new_x) - .property('shift_y', new_y); + if (hint.user_info !== undefined) + hint.painter?.provideUserTooltip(hint.user_info); - const axis = this.getObject(), abits = EAxisBits, - set_bit = (bit, on) => { if (axis.TestBit(bit) != on) axis.InvertBit(bit); }; + if (!hint.lines || (hint.lines.length === 0)) { + hints[n] = null; + continue; + } - this.titleOffset = (vertical ? new_x : new_y) / offset_k; - axis.fTitleOffset = this.titleOffset / this.titleSize; + // check if fully duplicated hint already exists + for (let k = 0; k < n; ++k) { + const hprev = hints[k]; + let diff = false; + if (!hprev || (hprev.lines.length !== hint.lines.length)) continue; + for (let l = 0; l < hint.lines.length && !diff; ++l) + if (hprev.lines[l] !== hint.lines[l]) diff = true; + if (!diff) { hints[n] = null; break; } + } + if (!hints[n]) continue; - if (curr_indx == 1) { - set_bit(abits.kCenterTitle, true); this.titleCenter = true; - set_bit(abits.kOppositeTitle, false); this.titleOpposite = false; - } else if (curr_indx == 0) { - set_bit(abits.kCenterTitle, false); this.titleCenter = false; - set_bit(abits.kOppositeTitle, true); this.titleOpposite = true; - } else { - set_bit(abits.kCenterTitle, false); this.titleCenter = false; - set_bit(abits.kOppositeTitle, false); this.titleOpposite = false; - } + nhints++; - this.submitAxisExec(`SetTitleOffset(${axis.fTitleOffset});;SetBit(${abits.kCenterTitle},${this.titleCenter?1:0})`); + if (hint.exact) nexact++; - drag_rect.remove(); - drag_rect = null; - }); + hint.lines.forEach(line => { maxlen = Math.max(maxlen, line.length); }); - title_g.style('cursor', 'move').call(drag_move); - } + hint.height = Math.round(hint.lines.length * textheight * hstep + 2 * hmargin - textheight * (hstep - 1)); - /** @summary Configure hist painter which creates axis - to be able submit execs - * @private */ - setHistPainter(hist_painter, axis_name) { - this.hist_painter = hist_painter; - this.hist_axis = axis_name; - } + if ((hint.color1 !== undefined) && (hint.color1 !== 'none')) { + if ((lastcolor1 !== 0) && (lastcolor1 !== hint.color1)) usecolor1 = true; + lastcolor1 = hint.color1; + } + } - /** @summary Submit exec for the axis - if possible - * @private */ - submitAxisExec(exec) { - let snapid = this.hist_painter?.snapid; - if (snapid && this.hist_axis) - this.submitCanvExec(exec, snapid + '#' + this.hist_axis); - } + const layer = this.hints_layer(), + show_only_best = nhints > 15, + coordinates = pnt ? Math.round(pnt.x) + ',' + Math.round(pnt.y) : ''; + let hintsg = layer.selectChild('.objects_hints'), // group with all tooltips + title = '', name = '', info = '', + hint = null, best_dist2 = 1e10, best_hint = null; - /** @summary Produce svg path for axis ticks */ - produceTicksPath(handle, side, tickSize, ticksPlusMinus, secondShift, real_draw) { - let path1 = '', path2 = ''; - this.ticks = []; + // try to select hint with exact match of the position when several hints available + for (let k = 0; k < (hints?.length || 0); ++k) { + if (!hints[k]) continue; + if (!hint) hint = hints[k]; - while (handle.next(true)) { + // select exact hint if this is the only one + if (hints[k].exact && (nexact < 2) && (!hint || !hint.exact)) { hint = hints[k]; break; } - let h1 = Math.round(tickSize/4), h2 = 0; + if (!pnt || (hints[k].x === undefined) || (hints[k].y === undefined)) continue; - if (handle.kind < 3) - h1 = Math.round(tickSize/2); + const dist2 = (pnt.x - hints[k].x) ** 2 + (pnt.y - hints[k].y) ** 2; + if (dist2 < best_dist2) { best_dist2 = dist2; best_hint = hints[k]; } + } - if (handle.kind == 1) { - // if not showing labels, not show large tick - // FIXME: for labels last tick is smaller, - if (/*(this.kind == 'labels') || */ (this.format(handle.tick,true) !== null)) h1 = tickSize; - this.ticks.push(handle.grpos); // keep graphical positions of major ticks - } + if ((!hint || !hint.exact) && (best_dist2 < 400)) hint = best_hint; - if (ticksPlusMinus > 0) { - h2 = -h1; - } else if (side < 0) { - h2 = -h1; h1 = 0; - } + if (hint) { + name = (hint.lines && hint.lines.length > 1) ? hint.lines[0] : hint.name; + title = hint.title || ''; + info = hint.line; + if (!info && hint.lines) info = hint.lines.slice(1).join(' '); + } - path1 += this.vertical ? `M${h1},${handle.grpos}H${h2}` : `M${handle.grpos},${-h1}V${-h2}`; + this.showObjectStatus(name, title, info, coordinates); - if (secondShift) - path2 += this.vertical ? `M${secondShift-h1},${handle.grpos}H${secondShift-h2}` : `M${handle.grpos},${secondShift+h1}V${secondShift+h2}`; + // end of closing tooltips + if (!pnt || disable_tootlips || (hints.length === 0) || (maxlen === 0) || (show_only_best && !best_hint)) { + hintsg.remove(); + return; } - return real_draw ? path1 + path2 : ''; - } + // we need to set pointer-events=none for all elements while hints + // placed in front of so-called interactive rect in frame, used to catch mouse events - /** @summary Returns modifier for axis label */ - findLabelModifier(axis, nlabel, num_labels) { - if (!axis.fModLabs) return null; - for (let n = 0; n < axis.fModLabs.arr.length; ++n) { - let mod = axis.fModLabs.arr[n]; - if (mod.fLabNum === nlabel + 1) return mod; - if ((mod.fLabNum < 0) && (nlabel === num_labels + mod.fLabNum)) return mod; + if (hintsg.empty()) { + hintsg = layer.append('svg:g') + .attr('class', 'objects_hints') + .style('pointer-events', 'none'); } - return null; - } - /** @summary Draw axis labels - * @return {Promise} with array label size and max width */ - async drawLabels(axis_g, axis, w, h, handle, side, labelsFont, labeloffset, tickSize, ticksPlusMinus, max_text_width) { - let center_lbls = this.isCenteredLabels(), - rotate_lbls = axis.TestBit(EAxisBits.kLabelsVert), - textscale = 1, maxtextlen = 0, applied_scale = 0, - label_g = [ axis_g.append('svg:g').attr('class','axis_labels') ], - lbl_pos = handle.lbl_pos || handle.major, lbl_tilt = false, max_textwidth = 0; + let frame_shift = { x: 0, y: 0 }, trans = frame_rect.transform || ''; + if (!pp.iscan) { + frame_shift = getAbsPosInCanvas(this.getPadSvg(), frame_shift); + trans = `translate(${frame_shift.x},${frame_shift.y}) ${trans}`; + } - if (this.lbls_both_sides) - label_g.push(axis_g.append('svg:g').attr('class','axis_labels').attr('transform', this.vertical ? `translate(${w})` : `translate(0,${-h})`)); + // copy transform attributes from frame itself + hintsg.attr('transform', trans) + .property('last_point', pnt) + .property('hints_pad', this.getPadName()); - // function called when text is drawn to analyze width, required to correctly scale all labels - // must be function to correctly handle 'this' argument - function process_drawtext_ready(painter) { - let textwidth = this.result_width; - max_textwidth = Math.max(max_textwidth, textwidth); + let viewmode = hintsg.property('viewmode') || '', + actualw = 0, posx = pnt.x + frame_rect.hint_delta_x; - if (textwidth && ((!painter.vertical && !rotate_lbls) || (painter.vertical && rotate_lbls)) && !painter.log) { - let maxwidth = this.gap_before*0.45 + this.gap_after*0.45; - if (!this.gap_before) maxwidth = 0.9*this.gap_after; else - if (!this.gap_after) maxwidth = 0.9*this.gap_before; - textscale = Math.min(textscale, maxwidth / textwidth); - } else if (painter.vertical && max_text_width && this.normal_side && (max_text_width - labeloffset > 20) && (textwidth > max_text_width - labeloffset)) { - textscale = Math.min(textscale, (max_text_width - labeloffset) / textwidth); - } + if (show_only_best || (nhints === 1)) { + viewmode = 'single'; + posx += 15; + } else { + // if there are many hints, place them left or right - if ((textscale > 0.0001) && (textscale < 0.7) && !painter.vertical && !rotate_lbls && (maxtextlen > 5) && (label_g.length == 1)) - lbl_tilt = true; + let bleft = 0.5, bright = 0.5; - let scale = textscale * (lbl_tilt ? 3 : 1); + if (viewmode === 'left') + bright = 0.7; + else if (viewmode === 'right') + bleft = 0.3; - if ((scale > 0.0001) && (scale < 1)) { - applied_scale = 1/scale; - painter.scaleTextDrawing(applied_scale, label_g[0]); - } + if (posx <= bleft * frame_rect.width) { + viewmode = 'left'; + posx = 20; + } else if (posx >= bright * frame_rect.width) { + viewmode = 'right'; + posx = frame_rect.width - 60; + } else + posx = hintsg.property('startx'); } - for (let lcnt = 0; lcnt < label_g.length; ++lcnt) { - - if (lcnt > 0) side = -side; - - let lastpos = 0, fix_coord = this.vertical ? -labeloffset*side : (labeloffset+2)*side + ticksPlusMinus*tickSize; + if (viewmode !== hintsg.property('viewmode')) { + hintsg.property('viewmode', viewmode); + hintsg.selectAll('*').remove(); + } - this.startTextDrawing(labelsFont, 'font', label_g[lcnt]); + let curry = 10, // normal y coordinate + gapy = 10, // y coordinate, taking into account all gaps + gapminx = -1111, gapmaxx = -1111; + const minhinty = -frame_shift.y, + cp = this.getCanvPainter(), + maxhinty = cp.getPadHeight() - frame_rect.y - frame_shift.y, + FindPosInGap = y => { + for (let n = 0; (n < hints.length) && (y < maxhinty); ++n) { + const hint = hints[n]; + if (!hint) continue; + if ((hint.y >= y - 5) && (hint.y <= y + hint.height + 5)) { + y = hint.y + 10; + n = -1; + } + } + return y; + }; - for (let nmajor = 0; nmajor < lbl_pos.length; ++nmajor) { + for (let n = 0; n < hints.length; ++n) { + let hint = hints[n], + group = hintsg.selectChild(`.painter_hint_${n}`); - let text = this.format(lbl_pos[nmajor], true); - if (text === null) continue; + if (show_only_best && (hint !== best_hint)) hint = null; - let mod = this.findLabelModifier(axis, nmajor, lbl_pos.length); - if (mod?.fTextSize === 0) continue; + if (hint === null) { + group.remove(); + continue; + } - if (mod?.fLabText) text = mod.fLabText; + const was_empty = group.empty(); - let arg = { text, color: labelsFont.color, latex: 1, draw_g: label_g[lcnt], normal_side: (lcnt == 0) }, - pos = Math.round(this.func(lbl_pos[nmajor])); + if (was_empty) { + group = hintsg.append('svg:svg') + .attr('class', `painter_hint_${n}`) + .attr('opacity', 0) // use attribute, not style to make animation with d3.transition() + .style('overflow', 'hidden') + .style('pointer-events', 'none'); + } - if (mod && mod.fTextColor > 0) arg.color = this.getColor(mod.fTextColor); + if (viewmode === 'single') + curry = pnt.touch ? (pnt.y - hint.height - 5) : Math.min(pnt.y + 15, maxhinty - hint.height - 3) + frame_rect.hint_delta_y; + else { + gapy = FindPosInGap(gapy); + if ((gapminx === -1111) && (gapmaxx === -1111)) gapminx = gapmaxx = hint.x; + gapminx = Math.min(gapminx, hint.x); + gapmaxx = Math.min(gapmaxx, hint.x); + } - arg.gap_before = (nmajor > 0) ? Math.abs(Math.round(pos - this.func(lbl_pos[nmajor-1]))) : 0; + group.attr('x', posx) + .attr('y', curry) + .property('curry', curry) + .property('gapy', gapy); - arg.gap_after = (nmajor < lbl_pos.length-1) ? Math.abs(Math.round(this.func(lbl_pos[nmajor+1])-pos)) : 0; + curry += hint.height + 5; + gapy += hint.height + 5; - if (center_lbls) { - let gap = arg.gap_after || arg.gap_before; - pos = Math.round(pos - (this.vertical ? 0.5*gap : -0.5*gap)); - if ((pos < -5) || (pos > (this.vertical ? h : w) + 5)) continue; - } + if (!was_empty) + group.selectAll('*').remove(); - maxtextlen = Math.max(maxtextlen, text.length); + group.attr('width', 60) + .attr('height', hint.height); - if (this.vertical) { - arg.x = fix_coord; - arg.y = pos; - arg.align = rotate_lbls ? ((side < 0) ? 23 : 20) : ((side < 0) ? 12 : 32); - } else { - arg.x = pos; - arg.y = fix_coord; - arg.align = rotate_lbls ? ((side < 0) ? 12 : 32) : ((side < 0) ? 20 : 23); - } + const r = group.append('rect') + .attr('x', 0) + .attr('y', 0) + .attr('width', 60) + .attr('height', hint.height) + .style('fill', 'lightgrey') + .style('pointer-events', 'none'); - if (rotate_lbls) - arg.rotate = 270; + if (nhints > 1) { + const col = usecolor1 ? hint.color1 : hint.color2; + if (col && (col !== 'none')) + r.style('stroke', col); + } + r.attr('stroke-width', hint.exact ? 3 : 1); - // only for major text drawing scale factor need to be checked - if (lcnt == 0) arg.post_process = process_drawtext_ready; + for (let l = 0; l < (hint.lines ? hint.lines.length : 0); l++) { + if (hint.lines[l] !== null) { + const txt = group.append('svg:text') + .attr('text-anchor', 'start') + .attr('x', wmargin) + .attr('y', hmargin + l * textheight * hstep) + .attr('dy', '.8em') + .style('fill', 'black') + .style('pointer-events', 'none') + .call(font.func) + .text(hint.lines[l]), - this.drawText(arg); + box = getElementRect(txt, 'bbox'); - if (lastpos && (pos != lastpos) && ((this.vertical && !rotate_lbls) || (!this.vertical && rotate_lbls))) { - let axis_step = Math.abs(pos-lastpos); - textscale = Math.min(textscale, 0.9*axis_step/labelsFont.size); + actualw = Math.max(actualw, box.width); } - - lastpos = pos; } - if (this.order) - this.drawText({ color: labelsFont.color, - x: this.vertical ? side*5 : w+5, - y: this.has_obstacle ? fix_coord : (this.vertical ? -3 : -3*side), - align: this.vertical ? ((side < 0) ? 30 : 10) : ( (this.has_obstacle ^ (side < 0)) ? 13 : 10 ), - latex: 1, - text: '#times' + this.formatExp(10, this.order), - draw_g: label_g[lcnt] - }); - } + function translateFn() { + // We only use 'd', but list d,i,a as params just to show can have them as params. + // Code only really uses d and t. + return function(/* d, i, a */) { + return function(t) { + return t < 0.8 ? '0' : (t - 0.8) * 5; + }; + }; + } - // first complete major labels drawing - return this.finishTextDrawing(label_g[0], true).then(() => { - if (label_g.length > 1) { - // now complete drawing of second half with scaling if necessary - if (applied_scale) - this.scaleTextDrawing(applied_scale, label_g[1]); - return this.finishTextDrawing(label_g[1], true); + if (was_empty) { + if (settings.TooltipAnimation > 0) + group.transition().duration(settings.TooltipAnimation).attrTween('opacity', translateFn()); + else + group.attr('opacity', 1); } - }).then(() => { - if (lbl_tilt) - label_g[0].selectAll('text').each(function() { - let txt = select(this), tr = txt.attr('transform'); - txt.attr('transform', tr + ' rotate(25)').style('text-anchor', 'start'); - }); + } - return max_textwidth; - }); - } + actualw += 2 * wmargin; - /** @summary Extract major draw attributes, which are also used in interactive operations - * @private */ - extractDrawAttributes(scalingSize, w, h) { - let axis = this.getObject(), - is_gaxis = axis?._typename === clTGaxis, - pp = this.getPadPainter(), - frect = pp?.getFrameRect(), - pad_w = Math.round((frect?.width || 8)/0.8), // use factor 0.8 as ratio between frame and pad size, frame size is visible and more obvios - pad_h = Math.round((frect?.height || 8)/0.8), - tickSize = 0, tickScalingSize = 0, titleColor; + const svgs = hintsg.selectAll('svg'); - this.scalingSize = scalingSize || Math.max(Math.min(pad_w, pad_h), 10); + if ((viewmode === 'right') && (posx + actualw > frame_rect.width - 20)) { + posx = frame_rect.width - actualw - 20; + svgs.attr('x', posx); + } - if (is_gaxis) { - let optionSize = axis.fChopt.indexOf('S') >= 0; - this.optionUnlab = axis.fChopt.indexOf('U') >= 0; - this.optionMinus = (axis.fChopt.indexOf('-') >= 0) || axis.TestBit(EAxisBits.kTickMinus); - this.optionPlus = (axis.fChopt.indexOf('+') >= 0) || axis.TestBit(EAxisBits.kTickPlus); - this.optionNoopt = (axis.fChopt.indexOf('N') >= 0); // no ticks position optimization - this.optionInt = (axis.fChopt.indexOf('I') >= 0); // integer labels + if ((viewmode === 'single') && (posx + actualw > pad_width - frame_rect.x) && (posx > actualw + 20)) { + posx -= (actualw + 20); + svgs.attr('x', posx); + } - this.createAttLine({ attr: axis }); - tickScalingSize = scalingSize || (this.vertical ? 1.7*h : 0.6*w); - tickSize = optionSize ? axis.fTickSize : 0.03; - titleColor = this.getColor(axis.fTextColor); - } else { - this.optionUnlab = false; - this.optionMinus = this.vertical ^ this.invert_side; - this.optionPlus = !this.optionMinus; - this.optionNoopt = false; // no ticks position optimization - this.optionInt = false; // integer labels - this.createAttLine({ color: axis.fAxisColor, width: 1, style: 1 }); - tickScalingSize = scalingSize || (this.vertical ? pad_w : pad_h); - tickSize = axis.fTickLength; - titleColor = this.getColor(axis.fTitleColor); + // if gap not very big, apply gapy coordinate to open view on the histogram + if ((viewmode !== 'single') && (gapy < maxhinty) && (gapy !== curry)) { + if ((gapminx <= posx + actualw + 5) && (gapmaxx >= posx - 5)) + svgs.attr('y', function() { return select(this).property('gapy'); }); + } else if ((viewmode !== 'single') && (curry > maxhinty)) { + const shift = Math.max((maxhinty - curry - 10), minhinty); + if (shift < 0) + svgs.attr('y', function() { return select(this).property('curry') + shift; }); } - this.optionNoexp = axis.TestBit(EAxisBits.kNoExponent); + if (actualw > 10) + svgs.attr('width', actualw).select('rect').attr('width', actualw); - this.ticksSize = Math.round(tickSize * tickScalingSize); - if (scalingSize && (this.ticksSize < 0)) - this.ticksSize = -this.ticksSize; + hintsg.property('startx', posx); - if (this.maxTickSize && (this.ticksSize > this.maxTickSize)) this.ticksSize = this.maxTickSize; + if (cp._highlight_connect && isFunc(cp.processHighlightConnect)) + cp.processHighlightConnect(hints); + }, - // now used only in 3D drawing - this.ticksColor = this.lineatt.color; - this.ticksWidth = this.lineatt.width; + /** @summary Assigns tooltip methods */ + assign(painter) { + Object.assign(painter, this, { tooltip_enabled: true }); + } - this.labelSize = Math.round((axis.fLabelSize < 1) ? axis.fLabelSize * this.scalingSize : axis.fLabelSize); - this.labelsOffset = Math.round(Math.abs(axis.fLabelOffset) * this.scalingSize); - this.labelsFont = new FontHandler(axis.fLabelFont, this.labelSize, scalingSize); - if ((this.labelSize <= 0) || (Math.abs(axis.fLabelOffset) > 1.1)) this.optionUnlab = true; // disable labels when size not specified - this.labelsFont.setColor(this.getColor(axis.fLabelColor)); +}, // TooltipHandler - this.fTitle = axis.fTitle; - if (this.fTitle) { - this.titleSize = (axis.fTitleSize >= 1) ? axis.fTitleSize : Math.round(axis.fTitleSize * this.scalingSize); - this.titleFont = new FontHandler(axis.fTitleFont, this.titleSize, scalingSize); - this.titleFont.setColor(titleColor); - this.titleOffset = axis.fTitleOffset * this.titleSize; // in pixels - this.titleCenter = axis.TestBit(EAxisBits.kCenterTitle); - this.titleOpposite = axis.TestBit(EAxisBits.kOppositeTitle); - } else { - delete this.titleSize; - delete this.titleFont; - delete this.titleOffset; - delete this.titleCenter; - delete this.titleOpposite; + +/** @summary Set of frame interactivity methods + * @private */ + + FrameInteractive = { + + /** @summary Adding basic interactivity */ + addBasicInteractivity() { + TooltipHandler.assign(this); + + if (!this._frame_rotate && !this._frame_fixpos) { + addDragHandler(this, { obj: this, x: this._frame_x, y: this._frame_y, width: this.getFrameWidth(), height: this.getFrameHeight(), + is_disabled: kind => { return (kind === 'move') && this.mode3d; }, + only_resize: true, minwidth: 20, minheight: 20, redraw: () => this.sizeChanged() }); } - } + const top_rect = this.draw_g.selectChild('path'), + main_svg = this.draw_g.selectChild('.main_layer'); - /** @summary function draws TAxis or TGaxis object - * @return {Promise} for drawing ready */ - async drawAxis(layer, w, h, transform, secondShift, disable_axis_drawing, max_text_width, calculate_position) { + top_rect.style('pointer-events', 'visibleFill') // let process mouse events inside frame + .style('cursor', 'default'); // show normal cursor - let axis = this.getObject(), - is_gaxis = axis?._typename === clTGaxis, - axis_g = layer, - draw_lines = true, - pp = this.getPadPainter(), - pad_w = pp?.getPadWidth() || 10, - pad_h = pp?.getPadHeight() || 10, - swap_side = this.swap_side || false; + main_svg.style('pointer-events', 'visibleFill') + .style('cursor', 'default') + .property('handlers_set', 0); - // shift for second ticks set (if any) - if (!secondShift) - secondShift = 0; - else if (this.invert_side) - secondShift = -secondShift; + const pp = this.getPadPainter(), + handlers_set = pp?._fast_drawing ? 0 : 1; - this.extractDrawAttributes(undefined, w, h); + if (main_svg.property('handlers_set') !== handlers_set) { + const close_handler = handlers_set ? this.processFrameTooltipEvent.bind(this, null) : null, + mouse_handler = handlers_set ? this.processFrameTooltipEvent.bind(this, { handler: true, touch: false }) : null; - if (is_gaxis) { - draw_lines = axis.fLineColor != 0; - } + main_svg.property('handlers_set', handlers_set) + .on('mouseenter', mouse_handler) + .on('mousemove', mouse_handler) + .on('mouseleave', close_handler); - // indicate that attributes created not for TAttLine, therefore cannot be updated as TAttLine in GED - this.lineatt.not_standard = true; + if (browser.touches) { + const touch_handler = handlers_set ? this.processFrameTooltipEvent.bind(this, { handler: true, touch: true }) : null; - if (!is_gaxis || (this.name === 'zaxis')) { - axis_g = layer.select('.' + this.name + '_container'); - if (axis_g.empty()) - axis_g = layer.append('svg:g').attr('class',this.name + '_container'); - else - axis_g.selectAll('*').remove(); + main_svg.on('touchstart', touch_handler) + .on('touchmove', touch_handler) + .on('touchend', close_handler) + .on('touchcancel', close_handler); + } } - let axis_lines = ''; - if (draw_lines) { - axis_lines = 'M0,0' + (this.vertical ? `v${h}` : `h${w}`); - if (secondShift) - axis_lines += this.vertical ? `M${secondShift},0v${h}` : `M0,${secondShift}h${w}`; - } + main_svg.attr('x', 0) + .attr('y', 0) + .attr('width', this.getFrameWidth()) + .attr('height', this.getFrameHeight()); - axis_g.attr('transform', transform || null); + const hintsg = this.hints_layer().selectChild('.objects_hints'); + // if tooltips were visible before, try to reconstruct them after short timeout + if (!hintsg.empty() && this.isTooltipAllowed() && (hintsg.property('hints_pad') === this.getPadName())) + setTimeout(this.processFrameTooltipEvent.bind(this, hintsg.property('last_point'), null), 10); + }, - let side = 1, ticksPlusMinus = 0; + /** @summary Add interactive handlers */ + async addFrameInteractivity(for_second_axes) { + const pp = this.getPadPainter(), + svg = this.getFrameSvg(); + if (pp?._fast_drawing || svg.empty()) + return this; - if (this.optionPlus && this.optionMinus) { - side = 1; ticksPlusMinus = 1; - } else if (this.optionMinus) { - side = (swap_side ^ this.vertical) ? 1 : -1; - } else if (this.optionPlus) { - side = (swap_side ^ this.vertical) ? -1 : 1; + if (for_second_axes) { + // add extra handlers for second axes + const svg_x2 = svg.selectAll('.x2axis_container'), + svg_y2 = svg.selectAll('.y2axis_container'); + if (settings.ContextMenu) { + svg_x2.on('contextmenu', evnt => this.showContextMenu('x2', evnt)); + svg_y2.on('contextmenu', evnt => this.showContextMenu('y2', evnt)); + } + svg_x2.on('mousemove', evnt => this.showAxisStatus('x2', evnt)); + svg_y2.on('mousemove', evnt => this.showAxisStatus('y2', evnt)); + return this; } - // first draw ticks - - const handle = this.createTicks(false, this.optionNoexp, this.optionNoopt, this.optionInt); + const svg_x = svg.selectAll('.xaxis_container'), + svg_y = svg.selectAll('.yaxis_container'); - axis_lines += this.produceTicksPath(handle, side, this.ticksSize, ticksPlusMinus, secondShift, draw_lines && !disable_axis_drawing && !this.disable_ticks); + this.can_zoom_x = this.can_zoom_y = settings.Zooming; - if (!disable_axis_drawing && axis_lines && !this.lineatt.empty()) - axis_g.append('svg:path') - .attr('d', axis_lines) - .call(this.lineatt.func); + if (pp?.options) { + if (pp.options.NoZoomX) this.can_zoom_x = false; + if (pp.options.NoZoomY) this.can_zoom_y = false; + } - let title_shift_x = 0, title_shift_y = 0, title_g = null, axis_rect = null, labelsMaxWidth = 0, - // draw labels (sometime on both sides) - pr = (disable_axis_drawing || this.optionUnlab) ? Promise.resolve(0) : - this.drawLabels(axis_g, axis, w, h, handle, side, this.labelsFont, this.labelsOffset, this.ticksSize, ticksPlusMinus, max_text_width); + if (!svg.property('interactive_set')) { + this.addFrameKeysHandler(); - return pr.then(maxw => { + this.zoom_kind = 0; // 0 - none, 1 - XY, 2 - only X, 3 - only Y, (+100 for touches) + this.zoom_rect = null; + this.zoom_origin = null; // original point where zooming started + this.zoom_curr = null; // current point for zooming + } - labelsMaxWidth = maxw; + if (settings.Zooming) { + if (settings.ZoomMouse) { + svg.on('mousedown', evnt => this.startRectSel(evnt)); + svg.on('dblclick', evnt => this.mouseDoubleClick(evnt)); + } + if (settings.ZoomWheel) + svg.on('wheel', evnt => this.mouseWheel(evnt)); + } - if (settings.Zooming && !this.disable_zooming && !isBatchMode()) { - let labelSize = Math.max(this.labelsFont.size, 5), - r = axis_g.append('svg:rect') - .attr('class', 'axis_zoom') - .style('opacity', '0') - .style('cursor', 'crosshair'); + if (browser.touches && ((settings.Zooming && settings.ZoomTouch) || settings.ContextMenu)) + svg.on('touchstart', evnt => this.startTouchZoom(evnt)); - if (this.vertical) { - let rw = (labelsMaxWidth || 2*labelSize) + 3; - r.attr('x', (side > 0) ? -rw : 0).attr('y', 0) - .attr('width', rw).attr('height', h); - } else { - r.attr('x', 0).attr('y', (side > 0) ? 0 : -labelSize - 3) - .attr('width', w).attr('height', labelSize + 3); - } + if (settings.ContextMenu) { + if (browser.touches) { + svg_x.on('touchstart', evnt => this.startSingleTouchHandling('x', evnt)); + svg_y.on('touchstart', evnt => this.startSingleTouchHandling('y', evnt)); } + svg.on('contextmenu', evnt => this.showContextMenu('', evnt)); + svg_x.on('contextmenu', evnt => this.showContextMenu('x', evnt)); + svg_y.on('contextmenu', evnt => this.showContextMenu('y', evnt)); + } - this.position = 0; + svg_x.on('mousemove', evnt => this.showAxisStatus('x', evnt)); + svg_y.on('mousemove', evnt => this.showAxisStatus('y', evnt)); - if (calculate_position) { - let node1 = axis_g.node(), node2 = this.getPadSvg().node(); - if (node1 && node2 && node1.getBoundingClientRect && node2.getBoundingClientRect) { - let rect1 = node1.getBoundingClientRect(), - rect2 = node2.getBoundingClientRect(); + svg.property('interactive_set', true); - this.position = rect1.left - rect2.left; // use to control left position of Y scale - } - if (node1 && !node2) - console.warn('Why PAD element missing when search for position'); - } + return this; + }, - if (!this.fTitle || disable_axis_drawing) return true; + /** @summary Add keys handler */ + addFrameKeysHandler() { + if (this.keys_handler || (typeof window === 'undefined')) return; - title_g = axis_g.append('svg:g').attr('class', 'axis_title'); + this.keys_handler = evnt => this.processKeyPress(evnt); - let title_offest_k = 1.6 / this.scalingSize, - rotate = axis.TestBit(EAxisBits.kRotateTitle) ? -1 : 1; + window.addEventListener('keydown', this.keys_handler, false); + }, - this.startTextDrawing(this.titleFont, 'font', title_g); + /** @summary Handle key press */ + processKeyPress(evnt) { + const allowed = ['PageUp', 'PageDown', 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown', 'PrintScreen', 'Escape', '*'], + main = this.selectDom(), + pp = this.getPadPainter(); + let key = evnt.key; - let xor_reverse = swap_side ^ this.titleOpposite, myxor = (rotate < 0) ^ xor_reverse; + if (!settings.HandleKeys || main.empty() || (this.enabledKeys === false) || + (getActivePad() !== pp) || (allowed.indexOf(key) < 0)) return false; - this.title_align = this.titleCenter ? 'middle' : (myxor ? 'begin' : 'end'); + if (evnt.shiftKey) key = `Shift ${key}`; + if (evnt.altKey) key = `Alt ${key}`; + if (evnt.ctrlKey) key = `Ctrl ${key}`; - if (this.vertical) { - title_offest_k *= -side*pad_w; + const zoom = { name: 'x', dleft: 0, dright: 0 }; - title_shift_x = Math.round(title_offest_k * this.titleOffset); + switch (key) { + case 'ArrowLeft': zoom.dleft = -1; zoom.dright = 1; break; + case 'ArrowRight': zoom.dleft = 1; zoom.dright = -1; break; + case 'Ctrl ArrowLeft': zoom.dleft = zoom.dright = -1; break; + case 'Ctrl ArrowRight': zoom.dleft = zoom.dright = 1; break; + case 'ArrowUp': zoom.name = 'y'; zoom.dleft = 1; zoom.dright = -1; break; + case 'ArrowDown': zoom.name = 'y'; zoom.dleft = -1; zoom.dright = 1; break; + case 'Ctrl ArrowUp': zoom.name = 'y'; zoom.dleft = zoom.dright = 1; break; + case 'Ctrl ArrowDown': zoom.name = 'y'; zoom.dleft = zoom.dright = -1; break; + case 'Escape': pp?.enlargePad(null, false, true); return true; + } - if ((this.name == 'zaxis') && is_gaxis && ('getBoundingClientRect' in axis_g.node())) { - // special handling for color palette labels - draw them always on right side - let rect = axis_g.node().getBoundingClientRect(); - if (title_shift_x < rect.width - this.ticksSize) - title_shift_x = Math.round(rect.width - this.ticksSize); - } + if (zoom.dleft || zoom.dright) { + if (!settings.Zooming) return false; + // in 3dmode with orbit control ignore simple arrows + if (this.mode3d && (key.indexOf('Ctrl') !== 0)) return false; + this.analyzeMouseWheelEvent(null, zoom, 0.5); + if (zoom.changed) { + this.zoom(zoom.name, zoom.min, zoom.max); + this.zoomChangedInteractive(zoom.name, true); + } + evnt.stopPropagation(); + evnt.preventDefault(); + } else { + const func = pp?.findPadButton(key); + if (func) { + pp.clickPadButton(func); + evnt.stopPropagation(); + evnt.preventDefault(); + } + } - title_shift_y = Math.round(this.titleCenter ? h/2 : (xor_reverse ? h : 0)); + return true; // just process any key press + }, - this.drawText({ align: this.title_align+';middle', - rotate: (rotate < 0) ? 90 : 270, - text: this.fTitle, color: this.titleFont.color, draw_g: title_g }); - } else { - title_offest_k *= side*pad_h; + /** @summary Function called when frame is clicked and object selection can be performed + * @desc such event can be used to select */ + processFrameClick(pnt, dblckick) { + const pp = this.getPadPainter(); + if (!pp) return; - title_shift_x = Math.round(this.titleCenter ? w/2 : (xor_reverse ? 0 : w)); - title_shift_y = Math.round(title_offest_k * this.titleOffset); - this.drawText({ align: this.title_align+';middle', - rotate: (rotate < 0) ? 180 : 0, - text: this.fTitle, color: this.titleFont.color, draw_g: title_g }); - } + pnt.painters = true; // provide painters reference in the hints + pnt.disabled = true; // do not invoke graphics - if (this.vertical && !this.titleOffset && ('getBoundingClientRect' in axis_g.node())) - axis_rect = axis_g.node().getBoundingClientRect(); + // collect tooltips from pad painter - it has list of all drawn objects + const hints = pp.processPadTooltipEvent(pnt); + let exact = null, res; + for (let k = 0; (k < hints.length) && !exact; ++k) { + if (hints[k] && hints[k].exact) + exact = hints[k]; + } - this.addTitleDrag(title_g, this.vertical, title_offest_k, swap_side, this.vertical ? h : w); + if (exact) { + const handler = dblckick ? this._dblclick_handler : this._click_handler; + if (handler) res = handler(exact.user_info, pnt); + } - return this.finishTextDrawing(title_g); - }).then(() => { - if (title_g) { - // fine-tuning of title position when possible - if (axis_rect) { - let title_rect = title_g.node().getBoundingClientRect(); - if ((axis_rect.left != axis_rect.right) && (title_rect.left != title_rect.right)) - title_shift_x = (side > 0) ? Math.round(axis_rect.left - title_rect.right - this.titleFont.size*0.3) : - Math.round(axis_rect.right - title_rect.left + this.titleFont.size*0.3); - else - title_shift_x = -1 * Math.round(((side > 0) ? (this.labelsOffset + labelsMaxWidth) : 0) + this.titleFont.size*0.7); - } + if (!dblckick) { + pp.selectObjectPainter(exact ? exact.painter : this, + { x: pnt.x + (this._frame_x || 0), y: pnt.y + (this._frame_y || 0) }); + } - title_g.attr('transform', `translate(${title_shift_x},${title_shift_y})`) - .property('shift_x', title_shift_x) - .property('shift_y', title_shift_y); - } + return res; + }, - return this; - }); - } + /** @summary Check mouse moving */ + shiftMoveHanlder(evnt, pos0) { + if (evnt.buttons === this._shifting_buttons) { + const frame = this.getFrameSvg(), + pos = pointer(evnt, frame.node()), + main_svg = this.draw_g.selectChild('.main_layer'), + dx = pos0[0] - pos[0], + dy = (this.scales_ndim === 1) ? 0 : pos0[1] - pos[1], + w = this.getFrameWidth(), h = this.getFrameHeight(); - /** @summary Convert TGaxis position into NDC to fix it when frame zoomed */ - convertTo(opt) { - let gaxis = this.getObject(), - x1 = this.axisToSvg('x', gaxis.fX1), - y1 = this.axisToSvg('y', gaxis.fY1), - x2 = this.axisToSvg('x', gaxis.fX2), - y2 = this.axisToSvg('y', gaxis.fY2); + this._shifting_dx = dx; + this._shifting_dy = dy; - if (opt == 'ndc') { - let pw = this.getPadPainter().getPadWidth(), - ph = this.getPadPainter().getPadHeight(); + main_svg.attr('viewBox', `${dx} ${dy} ${w} ${h}`); - gaxis.fX1 = x1 / pw; - gaxis.fX2 = x2 / pw; - gaxis.fY1 = (ph - y1) / ph; - gaxis.fY2 = (ph - y2)/ ph; - this.use_ndc = true; - } else if (opt == 'frame') { - let rect = this.getFramePainter().getFrameRect(); - gaxis.fX1 = (x1 - rect.x) / rect.width; - gaxis.fX2 = (x2 - rect.x) / rect.width; - gaxis.fY1 = (y1 - rect.y) / rect.height; - gaxis.fY2 = (y2 - rect.y) / rect.height; - this.bind_frame = true; + evnt.preventDefault(); + evnt.stopPropagation(); } - } - - /** @summary Redraw axis, used in standalone mode for TGaxis */ - redraw() { + }, - let gaxis = this.getObject(), x1, y1, x2, y2; + /** @summary mouse up handler for shifting */ + shiftUpHanlder(evnt) { + evnt.preventDefault(); - if (this.bind_frame) { - let rect = this.getFramePainter().getFrameRect(); - x1 = Math.round(rect.x + gaxis.fX1 * rect.width); - x2 = Math.round(rect.x + gaxis.fX2 * rect.width); - y1 = Math.round(rect.y + gaxis.fY1 * rect.height); - y2 = Math.round(rect.y + gaxis.fY2 * rect.height); - } else { - x1 = this.axisToSvg('x', gaxis.fX1, this.use_ndc); - y1 = this.axisToSvg('y', gaxis.fY1, this.use_ndc); - x2 = this.axisToSvg('x', gaxis.fX2, this.use_ndc); - y2 = this.axisToSvg('y', gaxis.fY2, this.use_ndc); - } - let w = x2 - x1, h = y1 - y2, - vertical = Math.abs(w) < Math.abs(h), - sz = vertical ? h : w, - reverse = false, - min = gaxis.fWmin, max = gaxis.fWmax; + select(window).on('mousemove.shiftHandler', null) + .on('mouseup.shiftHandler', null); - if (sz < 0) { - reverse = true; - sz = -sz; - if (vertical) y2 = y1; else x1 = x2; - } + if ((this._shifting_dx !== undefined) && (this._shifting_dy !== undefined)) + this.performScalesShift(); + }, - this.configureAxis(vertical ? 'yaxis' : 'xaxis', min, max, min, max, vertical, [0, sz], { - time_scale: gaxis.fChopt.indexOf('t') >= 0, - log: (gaxis.fChopt.indexOf('G') >= 0) ? 1 : 0, - reverse, - swap_side: reverse - }); + /** @summary Shift scales on defined positions */ + performScalesShift() { + const w = this.getFrameWidth(), h = this.getFrameHeight(), + main_svg = this.draw_g.selectChild('.main_layer'), + gr = this.getGrFuncs(), + xmin = gr.revertAxis('x', this._shifting_dx), + xmax = gr.revertAxis('x', this._shifting_dx + w), + ymin = gr.revertAxis('y', this._shifting_dy + h), + ymax = gr.revertAxis('y', this._shifting_dy); - this.createG(); + main_svg.attr('viewBox', `0 0 ${w} ${h}`); - return this.drawAxis(this.getG(), Math.abs(w), Math.abs(h), `translate(${x1},${y2})`); - } + delete this._shifting_dx; + delete this._shifting_dy; -} // class TAxisPainter + setPainterTooltipEnabled(this, true); -/** - * A math namespace - all functions can be exported from base/math.mjs. - * Also all these functions can be used with TFormula calcualtions - * @namespace Math - */ + if (this.scales_ndim === 1) + this.zoomSingle('x', xmin, xmax); + else + this.zoom(xmin, xmax, ymin, ymax); + }, -const kMACHEP = 1.11022302462515654042363166809e-16, - kMINLOG = -708.396418532264078748994506896, - kMAXLOG = 709.782712893383973096206318587, - kMAXSTIR = 108.116855767857671821730036754, - kBig = 4.503599627370496e15, - kBiginv = 2.22044604925031308085e-16, - kSqrt2 = 1.41421356237309515, - M_PI = 3.14159265358979323846264338328; + /** @summary Start mouse rect zooming */ + startRectSel(evnt) { + // ignore when touch selection is activated + if (this.zoom_kind > 100) return; -/** @summary Polynomialeval function - * @desc calculates a value of a polynomial of the form: - * a[0]x^N+a[1]x^(N-1) + ... + a[N] - * @memberof Math */ -function Polynomialeval(x, a, N) { - if (!N) return a[0]; + const frame = this.getFrameSvg(), + pos = pointer(evnt, frame.node()); - let pom = a[0]; - for (let i = 1; i <= N; ++i) - pom = pom *x + a[i]; - return pom; -} + if ((evnt.buttons === 3) || (evnt.button === 1)) { + this.clearInteractiveElements(); + this._shifting_buttons = evnt.buttons; -/** @summary Polynomial1eval function - * @desc calculates a value of a polynomial of the form: - * x^N+a[0]x^(N-1) + ... + a[N-1] - * @memberof Math */ -function Polynomial1eval(x, a, N) { - if (!N) return a[0]; + if (!evnt.$emul) { + select(window).on('mousemove.shiftHandler', evnt => this.shiftMoveHanlder(evnt, pos)) + .on('mouseup.shiftHandler', evnt => this.shiftUpHanlder(evnt), true); + } - let pom = x + a[0]; - for (let i = 1; i < N; ++i) - pom = pom *x + a[i]; - return pom; -} + setPainterTooltipEnabled(this, false); + evnt.preventDefault(); + evnt.stopPropagation(); + return; + } -/** @summary lgam function, logarithm from gamma - * @memberof Math */ -function lgam(x) { - let p, q, u, w, z; - const kMAXLGM = 2.556348e305, - LS2PI = 0.91893853320467274178, - A = [ - 8.11614167470508450300E-4, - -5.95061904284301438324E-4, - 7.93650340457716943945E-4, - -2.77777777730099687205E-3, - 8.33333333333331927722E-2 - ], B = [ - -1.37825152569120859100E3, - -3.88016315134637840924E4, - -3.31612992738871184744E5, - -1.16237097492762307383E6, - -1.72173700820839662146E6, - -8.53555664245765465627E5 - ], C = [ - /* 1.00000000000000000000E0, */ - -3.51815701436523470549E2, - -1.70642106651881159223E4, - -2.20528590553854454839E5, - -1.13933444367982507207E6, - -2.53252307177582951285E6, - -2.01889141433532773231E6 - ]; + // ignore all events from non-left button + if (evnt.button !== 0) return; - if ((x >= Number.MAX_VALUE) || (x == Number.POSITIVE_INFINITY)) - return Number.POSITIVE_INFINITY; + evnt.preventDefault(); - if ( x < -34.0 ) { - q = -x; - w = lgam(q); - p = Math.floor(q); - if ( p==q )//_unur_FP_same(p,q) - return Number.POSITIVE_INFINITY; - z = q - p; - if ( z > 0.5 ) { - p += 1.0; - z = p - q; - } - z = q * Math.sin( Math.PI * z ); - if ( z < 1e-300 ) - return Number.POSITIVE_INFINITY; - z = Math.log(Math.PI) - Math.log( z ) - w; - return z; - } - if ( x < 13.0 ) { - z = 1.0; - p = 0.0; - u = x; - while ( u >= 3.0 ) { - p -= 1.0; - u = x + p; - z *= u; - } - while ( u < 2.0 ) { - if ( u < 1e-300 ) - return Number.POSITIVE_INFINITY; - z /= u; - p += 1.0; - u = x + p; - } - if ( z < 0.0 ) { - z = -z; - } - if ( u == 2.0 ) - return Math.log(z); - p -= 2.0; - x = x + p; - p = x * Polynomialeval(x, B, 5 ) / Polynomial1eval( x, C, 6); - return Math.log(z) + p; - } - if ( x > kMAXLGM ) - return Number.POSITIVE_INFINITY; + this.clearInteractiveElements(); - q = ( x - 0.5 ) * Math.log(x) - x + LS2PI; - if ( x > 1.0e8 ) - return q; + const w = this.getFrameWidth(), h = this.getFrameHeight(); - p = 1.0/(x*x); - if ( x >= 1000.0 ) - q += ((7.9365079365079365079365e-4 * p - - 2.7777777777777777777778e-3) *p - + 0.0833333333333333333333) / x; - else - q += Polynomialeval( p, A, 4 ) / x; - return q; -} + this.zoom_lastpos = pos; + this.zoom_curr = [Math.max(0, Math.min(w, pos[0])), Math.max(0, Math.min(h, pos[1]))]; -/** @summary Stirling formula for the gamma function - * @memberof Math */ -function stirf(x) { - let y, w, v; + this.zoom_origin = [0, 0]; + this.zoom_second = false; - const STIR = [ - 7.87311395793093628397E-4, - -2.29549961613378126380E-4, - -2.68132617805781232825E-3, - 3.47222221605458667310E-3, - 8.33333333333482257126E-2, - ], SQTPI = Math.sqrt(2*Math.PI); + if ((pos[0] < 0) || (pos[0] > w)) { + this.zoom_second = (pos[0] > w) && this.y2_handle; + this.zoom_kind = 3; // only y + this.zoom_origin[1] = this.zoom_curr[1]; + this.zoom_curr[0] = w; + this.zoom_curr[1] += 1; + } else if ((pos[1] < 0) || (pos[1] > h)) { + this.zoom_second = (pos[1] < 0) && this.x2_handle; + this.zoom_kind = 2; // only x + this.zoom_origin[0] = this.zoom_curr[0]; + this.zoom_curr[0] += 1; + this.zoom_curr[1] = h; + } else { + this.zoom_kind = 1; // x and y + this.zoom_origin[0] = this.zoom_curr[0]; + this.zoom_origin[1] = this.zoom_curr[1]; + } - w = 1.0/x; - w = 1.0 + w * Polynomialeval( w, STIR, 4 ); - y = Math.exp(x); + if (!evnt.$emul) { + select(window).on('mousemove.zoomRect', evnt => this.moveRectSel(evnt)) + .on('mouseup.zoomRect', evnt => this.endRectSel(evnt), true); + } -/* #define kMAXSTIR kMAXLOG/log(kMAXLOG) */ + this.zoom_rect = null; - if( x > kMAXSTIR ) - { /* Avoid overflow in pow() */ - v = Math.pow( x, 0.5 * x - 0.25 ); - y = v * (v / y); - } - else - { - y = Math.pow( x, x - 0.5 ) / y; - } - y = SQTPI * y * w; - return y; -} + // disable tooltips in frame painter + setPainterTooltipEnabled(this, false); -/** @summary complementary error function - * @memberof Math */ -function erfc(a) { - const erfP = [ - 2.46196981473530512524E-10, - 5.64189564831068821977E-1, - 7.46321056442269912687E0, - 4.86371970985681366614E1, - 1.96520832956077098242E2, - 5.26445194995477358631E2, - 9.34528527171957607540E2, - 1.02755188689515710272E3, - 5.57535335369399327526E2 - ], erfQ = [ - 1.32281951154744992508E1, - 8.67072140885989742329E1, - 3.54937778887819891062E2, - 9.75708501743205489753E2, - 1.82390916687909736289E3, - 2.24633760818710981792E3, - 1.65666309194161350182E3, - 5.57535340817727675546E2 - ], erfR = [ - 5.64189583547755073984E-1, - 1.27536670759978104416E0, - 5.01905042251180477414E0, - 6.16021097993053585195E0, - 7.40974269950448939160E0, - 2.97886665372100240670E0 - ], erfS = [ - 2.26052863220117276590E0, - 9.39603524938001434673E0, - 1.20489539808096656605E1, - 1.70814450747565897222E1, - 9.60896809063285878198E0, - 3.36907645100081516050E0 - ]; + evnt.stopPropagation(); - let p,q,x,y,z; + if (this.zoom_kind !== 1) + return postponePromise(() => this.startLabelsMove(), 500); + }, - if( a < 0.0 ) - x = -a; - else - x = a; + /** @summary Starts labels move */ + startLabelsMove() { + if (this.zoom_rect) return; - if( x < 1.0 ) - return 1.0 - erf(a); + const handle = (this.zoom_kind === 2) ? this.x_handle : this.y_handle; - z = -a * a; + if (!isFunc(handle?.processLabelsMove) || !this.zoom_lastpos) return; - if(z < -kMAXLOG) - return (a < 0) ? 2.0 : 0.0; + if (handle.processLabelsMove('start', this.zoom_lastpos)) + this.zoom_labels = handle; + }, - z = Math.exp(z); + /** @summary Process mouse rect zooming */ + moveRectSel(evnt) { + if ((this.zoom_kind === 0) || (this.zoom_kind > 100)) return; - if( x < 8.0 ) { - p = Polynomialeval( x, erfP, 8 ); - q = Polynomial1eval( x, erfQ, 8 ); - } else { - p = Polynomialeval( x, erfR, 5 ); - q = Polynomial1eval( x, erfS, 6 ); - } - y = (z * p)/q; + evnt.preventDefault(); + const m = pointer(evnt, this.getFrameSvg().node()); - if(a < 0) - y = 2.0 - y; + if (this.zoom_labels) + return this.zoom_labels.processLabelsMove('move', m); - if(y == 0) - return (a < 0) ? 2.0 : 0.0; + this.zoom_lastpos[0] = m[0]; + this.zoom_lastpos[1] = m[1]; - return y; -} + m[0] = Math.max(0, Math.min(this.getFrameWidth(), m[0])); + m[1] = Math.max(0, Math.min(this.getFrameHeight(), m[1])); -/** @summary error function - * @memberof Math */ -function erf(x) { - if(Math.abs(x) > 1.0) - return 1.0 - erfc(x); + switch (this.zoom_kind) { + case 1: this.zoom_curr[0] = m[0]; this.zoom_curr[1] = m[1]; break; + case 2: this.zoom_curr[0] = m[0]; break; + case 3: this.zoom_curr[1] = m[1]; break; + } - const erfT = [ - 9.60497373987051638749E0, - 9.00260197203842689217E1, - 2.23200534594684319226E3, - 7.00332514112805075473E3, - 5.55923013010394962768E4 - ], erfU = [ - 3.35617141647503099647E1, - 5.21357949780152679795E2, - 4.59432382970980127987E3, - 2.26290000613890934246E4, - 4.92673942608635921086E4 - ]; + const x = Math.min(this.zoom_origin[0], this.zoom_curr[0]), + y = Math.min(this.zoom_origin[1], this.zoom_curr[1]), + w = Math.abs(this.zoom_curr[0] - this.zoom_origin[0]), + h = Math.abs(this.zoom_curr[1] - this.zoom_origin[1]); - let z = x * x; + if (!this.zoom_rect) { + // ignore small changes, can be switching to labels move + if ((this.zoom_kind !== 1) && ((w < 2) || (h < 2))) return; - return x * Polynomialeval(z, erfT, 4) / Polynomial1eval(z, erfU, 5); -} + this.zoom_rect = this.getFrameSvg() + .append('rect') + .style('pointer-events', 'none') + .call(addHighlightStyle, true); + } -/** @summary lognormal_cdf_c function - * @memberof Math */ -function lognormal_cdf_c(x, m, s, x0) { - if (x0 === undefined) x0 = 0; - let z = (Math.log((x-x0))-m)/(s*kSqrt2); - if (z > 1.) return 0.5*erfc(z); - else return 0.5*(1.0 - erf(z)); -} + this.zoom_rect.attr('x', x).attr('y', y).attr('width', w).attr('height', h); + }, -/** @summary lognormal_cdf_c function - * @memberof Math */ -function lognormal_cdf(x, m, s, x0 = 0) { - let z = (Math.log((x-x0))-m)/(s*kSqrt2); - if (z < -1.) return 0.5*erfc(-z); - else return 0.5*(1.0 + erf(z)); -} + /** @summary Finish mouse rect zooming */ + endRectSel(evnt) { + if ((this.zoom_kind === 0) || (this.zoom_kind > 100)) return; -/** @summary normal_cdf_c function - * @memberof Math */ -function normal_cdf_c(x, sigma, x0 = 0) { - let z = (x-x0)/(sigma*kSqrt2); - if (z > 1.) return 0.5*erfc(z); - else return 0.5*(1.-erf(z)); -} + evnt.preventDefault(); -/** @summary normal_cdf function - * @memberof Math */ -function normal_cdf(x, sigma, x0 = 0) { - let z = (x-x0)/(sigma*kSqrt2); - if (z < -1.) return erfc(-z); - else return 0.5*(1.0 + erf(z)); -} + if (!evnt.$emul) { + select(window).on('mousemove.zoomRect', null) + .on('mouseup.zoomRect', null); + } -/** @summary log normal pdf - * @memberof Math */ -function lognormal_pdf(x, m, s, x0 = 0) { - if ((x-x0) <= 0) - return 0.0; - let tmp = (Math.log((x-x0)) - m)/s; - return 1.0 / ((x-x0) * Math.abs(s) * Math.sqrt(2 * M_PI)) * Math.exp(-(tmp * tmp) /2); -} + const m = pointer(evnt, this.getFrameSvg().node()); + let kind = this.zoom_kind, pr; -/** @summary normal pdf - * @memberof Math */ -function normal_pdf(x, sigma = 1, x0 = 0) { - let tmp = (x-x0)/sigma; - return (1.0/(Math.sqrt(2 * M_PI) * Math.abs(sigma))) * Math.exp(-tmp*tmp/2); -} + if (this.zoom_labels) + this.zoom_labels.processLabelsMove('stop', m); + else { + const changed = [this.can_zoom_x, this.can_zoom_y]; + m[0] = Math.max(0, Math.min(this.getFrameWidth(), m[0])); + m[1] = Math.max(0, Math.min(this.getFrameHeight(), m[1])); -/** @summary gamma calculation - * @memberof Math */ -function gamma(x) { - let p, q, z, i, sgngam = 1; + switch (this.zoom_kind) { + case 1: this.zoom_curr[0] = m[0]; this.zoom_curr[1] = m[1]; break; + case 2: this.zoom_curr[0] = m[0]; changed[1] = false; break; // only X + case 3: this.zoom_curr[1] = m[1]; changed[0] = false; break; // only Y + } - if (x >= Number.MAX_VALUE) - return x; + const idx = this.swap_xy ? 1 : 0, idy = 1 - idx; + let xmin, xmax, ymin, ymax, isany = false, + namex = 'x', namey = 'y'; - q = Math.abs(x); + if (changed[idx] && (Math.abs(this.zoom_curr[idx] - this.zoom_origin[idx]) > 10)) { + if (this.zoom_second && (this.zoom_kind === 2)) namex = 'x2'; + xmin = Math.min(this.revertAxis(namex, this.zoom_origin[idx]), this.revertAxis(namex, this.zoom_curr[idx])); + xmax = Math.max(this.revertAxis(namex, this.zoom_origin[idx]), this.revertAxis(namex, this.zoom_curr[idx])); + isany = true; + } - if( q > 33.0 ) - { - if( x < 0.0 ) - { - p = Math.floor(q); - if( p == q ) - return Number.POSITIVE_INFINITY; - i = Math.round(p); - if( (i & 1) == 0 ) - sgngam = -1; - z = q - p; - if( z > 0.5 ) - { - p += 1.0; - z = q - p; + if (changed[idy] && (Math.abs(this.zoom_curr[idy] - this.zoom_origin[idy]) > 10)) { + if (this.zoom_second && (this.zoom_kind === 3)) namey = 'y2'; + ymin = Math.min(this.revertAxis(namey, this.zoom_origin[idy]), this.revertAxis(namey, this.zoom_curr[idy])); + ymax = Math.max(this.revertAxis(namey, this.zoom_origin[idy]), this.revertAxis(namey, this.zoom_curr[idy])); + isany = true; } - z = q * Math.sin( Math.PI * z ); - if( z == 0 ) - { - return sgngam > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + if (namex === 'x2') { + this.zoomChangedInteractive(namex, true); + pr = this.zoomSingle(namex, xmin, xmax); + kind = 0; + } else if (namey === 'y2') { + this.zoomChangedInteractive(namey, true); + pr = this.zoomSingle(namey, ymin, ymax); + kind = 0; + } else if (isany) { + this.zoomChangedInteractive('x', true); + this.zoomChangedInteractive('y', true); + pr = this.zoom(xmin, xmax, ymin, ymax); + kind = 0; } - z = Math.abs(z); - z = Math.PI / (z * stirf(q) ); - } - else - { - z = stirf(x); } - return sgngam * z; - } - z = 1.0; - while( x >= 3.0 ) - { - x -= 1.0; - z *= x; - } + const pnt = (kind === 1) ? { x: this.zoom_origin[0], y: this.zoom_origin[1] } : null; - let small = false; + this.clearInteractiveElements(); - while(( x < 0.0 ) && !small) - { - if( x > -1.E-9 ) - small = true; - else { - z /= x; - x += 1.0; + // if no zooming was done, select active object instead + switch (kind) { + case 1: + this.processFrameClick(pnt); + break; + case 2: + this.getPadPainter()?.selectObjectPainter(this, null, 'xaxis'); + break; + case 3: + this.getPadPainter()?.selectObjectPainter(this, null, 'yaxis'); + break; } - } - while(( x < 2.0 ) && !small) - { - if( x < 1.e-9 ) - small = true; - else { - z /= x; - x += 1.0; + // return promise - if any + return pr; + }, + + /** @summary Handle mouse double click on frame */ + mouseDoubleClick(evnt) { + evnt.preventDefault(); + const m = pointer(evnt, this.getFrameSvg().node()), + fw = this.getFrameWidth(), fh = this.getFrameHeight(); + this.clearInteractiveElements(); + + const valid_x = (m[0] >= 0) && (m[0] <= fw), + valid_y = (m[1] >= 0) && (m[1] <= fh); + + if (valid_x && valid_y && this._dblclick_handler) + if (this.processFrameClick({ x: m[0], y: m[1] }, true)) return; + + let kind = (this.can_zoom_x ? 'x' : '') + (this.can_zoom_y ? 'y' : '') + 'z'; + if (!valid_x) { + if (!this.can_zoom_y) return; + kind = this.swap_xy ? 'x' : 'y'; + if ((m[0] > fw) && this[kind+'2_handle']) kind += '2'; // let unzoom second axis + } else if (!valid_y) { + if (!this.can_zoom_x) return; + kind = this.swap_xy ? 'y' : 'x'; + if ((m[1] < 0) && this[kind+'2_handle']) kind += '2'; // let unzoom second axis } - } + return this.unzoom(kind).then(changed => { + if (changed) return; + const pp = this.getPadPainter(), rect = this.getFrameRect(); + return pp?.selectObjectPainter(pp, { x: m[0] + rect.x, y: m[1] + rect.y, dbl: true }); + }); + }, + + /** @summary Start touch zoom */ + startTouchZoom(evnt) { + evnt.preventDefault(); + evnt.stopPropagation(); - if (small) { - if( x == 0 ) - return Number.POSITIVE_INFINITY; - else - return z/((1.0 + 0.5772156649015329 * x) * x); - } + // in case when zooming was started, block any other kind of events + // also prevent zooming together with active dragging + if ((this.zoom_kind !== 0) || drag_kind) + return; - if( x == 2.0 ) - return z; + const arr = get_touch_pointers(evnt, this.getFrameSvg().node()); - const P = [ - 1.60119522476751861407E-4, - 1.19135147006586384913E-3, - 1.04213797561761569935E-2, - 4.76367800457137231464E-2, - 2.07448227648435975150E-1, - 4.94214826801497100753E-1, - 9.99999999999999996796E-1 - ], Q = [ - -2.31581873324120129819E-5, - 5.39605580493303397842E-4, - -4.45641913851797240494E-3, - 1.18139785222060435552E-2, - 3.58236398605498653373E-2, - -2.34591795718243348568E-1, - 7.14304917030273074085E-2, - 1.00000000000000000320E0 ]; + // normally double-touch will be handled + // touch with single click used for context menu + if (arr.length === 1) { + // this is touch with single element - x -= 2.0; - p = Polynomialeval( x, P, 6 ); - q = Polynomialeval( x, Q, 7 ); - return z * p / q; -} + const now = new Date().getTime(); + let tmdiff = 1e10, dx = 100, dy = 100; -/** @summary ndtri function - * @memberof Math */ -function ndtri(y0) { - if ( y0 <= 0.0 ) - return Number.NEGATIVE_INFINITY; - if ( y0 >= 1.0 ) - return Number.POSITIVE_INFINITY; + if (this.last_touch_time && this.last_touch_pos) { + tmdiff = now - this.last_touch_time; + dx = Math.abs(arr[0][0] - this.last_touch_pos[0]); + dy = Math.abs(arr[0][1] - this.last_touch_pos[1]); + } - const P0 = [ - -5.99633501014107895267E1, - 9.80010754185999661536E1, - -5.66762857469070293439E1, - 1.39312609387279679503E1, - -1.23916583867381258016E0 - ], Q0 = [ - 1.95448858338141759834E0, - 4.67627912898881538453E0, - 8.63602421390890590575E1, - -2.25462687854119370527E2, - 2.00260212380060660359E2, - -8.20372256168333339912E1, - 1.59056225126211695515E1, - -1.18331621121330003142E0 - ], P1 = [ - 4.05544892305962419923E0, - 3.15251094599893866154E1, - 5.71628192246421288162E1, - 4.40805073893200834700E1, - 1.46849561928858024014E1, - 2.18663306850790267539E0, - -1.40256079171354495875E-1, - -3.50424626827848203418E-2, - -8.57456785154685413611E-4 - ], Q1 = [ - 1.57799883256466749731E1, - 4.53907635128879210584E1, - 4.13172038254672030440E1, - 1.50425385692907503408E1, - 2.50464946208309415979E0, - -1.42182922854787788574E-1, - -3.80806407691578277194E-2, - -9.33259480895457427372E-4 - ], P2 = [ - 3.23774891776946035970E0, - 6.91522889068984211695E0, - 3.93881025292474443415E0, - 1.33303460815807542389E0, - 2.01485389549179081538E-1, - 1.23716634817820021358E-2, - 3.01581553508235416007E-4, - 2.65806974686737550832E-6, - 6.23974539184983293730E-9 - ], Q2 = [ - 6.02427039364742014255E0, - 3.67983563856160859403E0, - 1.37702099489081330271E0, - 2.16236993594496635890E-1, - 1.34204006088543189037E-2, - 3.28014464682127739104E-4, - 2.89247864745380683936E-6, - 6.79019408009981274425E-9 - ], s2pi = 2.50662827463100050242e0, dd = 0.13533528323661269189; + this.last_touch_time = now; + this.last_touch_pos = arr[0]; - let code = 1, y = y0, x, z, y2, x0, x1; + if ((tmdiff < 500) && (dx < 20) && (dy < 20)) { + this.clearInteractiveElements(); + this.unzoom('xyz'); - if ( y > (1.0 - dd) ) { - y = 1.0 - y; - code = 0; - } - if ( y > dd ) { - y = y - 0.5; - y2 = y * y; - x = y + y * (y2 * Polynomialeval( y2, P0, 4)/ Polynomial1eval( y2, Q0, 8 )); - x = x * s2pi; - return x; - } - x = Math.sqrt( -2.0 * Math.log(y) ); - x0 = x - Math.log(x)/x; - z = 1.0/x; - if ( x < 8.0 ) - x1 = z * Polynomialeval( z, P1, 8 )/ Polynomial1eval( z, Q1, 8 ); - else - x1 = z * Polynomialeval( z, P2, 8 )/ Polynomial1eval( z, Q2, 8 ); - x = x0 - x1; - if ( code != 0 ) - x = -x; - return x; -} + delete this.last_touch_time; + } else if (settings.ContextMenu) + this.startSingleTouchHandling('', evnt); + } -/** @summary normal_quantile function - * @memberof Math */ -function normal_quantile(z, sigma) { - return sigma * ndtri(z); -} + if ((arr.length !== 2) || !settings.Zooming || !settings.ZoomTouch) + return; -/** @summary normal_quantile_c function - * @memberof Math */ -function normal_quantile_c(z, sigma) { - return - sigma * ndtri(z); -} + this.clearInteractiveElements(); -/** @summary igamc function - * @memberof Math */ -function igamc(a,x) { - // LM: for negative values returns 0.0 - // This is correct if a is a negative integer since Gamma(-n) = +/- inf - if (a <= 0) return 0.0; + // clear single touch handler + this.endSingleTouchHandling(null); - if (x <= 0) return 1.0; + const pnt1 = arr[0], pnt2 = arr[1], w = this.getFrameWidth(), h = this.getFrameHeight(); - if((x < 1.0) || (x < a)) - return (1.0 - igam(a,x)); + this.zoom_curr = [Math.min(pnt1[0], pnt2[0]), Math.min(pnt1[1], pnt2[1])]; + this.zoom_origin = [Math.max(pnt1[0], pnt2[0]), Math.max(pnt1[1], pnt2[1])]; + this.zoom_second = false; - let ax = a * Math.log(x) - x - lgam(a); - if( ax < -kMAXLOG ) - return 0.0; + if ((this.zoom_curr[0] < 0) || (this.zoom_curr[0] > w)) { + this.zoom_second = (this.zoom_curr[0] > w) && this.y2_handle; + this.zoom_kind = 103; // only y + this.zoom_curr[0] = 0; + this.zoom_origin[0] = w; + } else if ((this.zoom_origin[1] > h) || (this.zoom_origin[1] < 0)) { + this.zoom_second = (this.zoom_origin[1] < 0) && this.x2_handle; + this.zoom_kind = 102; // only x + this.zoom_curr[1] = 0; + this.zoom_origin[1] = h; + } else + this.zoom_kind = 101; // x and y - ax = Math.exp(ax); + drag_kind = 'zoom'; // block other possible dragging - /* continued fraction */ - let y = 1.0 - a, - z = x + y + 1.0, - c = 0.0, - pkm2 = 1.0, - qkm2 = x, - pkm1 = x + 1.0, - qkm1 = z * x, - ans = pkm1/qkm1, - yc, r, t, pk, qk; + setPainterTooltipEnabled(this, false); - do { - c += 1.0; - y += 1.0; - z += 2.0; - yc = y * c; - pk = pkm1 * z - pkm2 * yc; - qk = qkm1 * z - qkm2 * yc; - if(qk) - { - r = pk/qk; - t = Math.abs( (ans - r)/r ); - ans = r; - } - else - t = 1.0; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; - if( Math.abs(pk) > kBig ) - { - pkm2 *= kBiginv; - pkm1 *= kBiginv; - qkm2 *= kBiginv; - qkm1 *= kBiginv; + this.zoom_rect = this.getFrameSvg().append('rect') + .attr('id', 'zoomRect') + .attr('x', this.zoom_curr[0]) + .attr('y', this.zoom_curr[1]) + .attr('width', this.zoom_origin[0] - this.zoom_curr[0]) + .attr('height', this.zoom_origin[1] - this.zoom_curr[1]) + .call(addHighlightStyle, true); + + if (!evnt.$emul) { + select(window).on('touchmove.zoomRect', evnt => this.moveTouchZoom(evnt)) + .on('touchcancel.zoomRect', evnt => this.endTouchZoom(evnt)) + .on('touchend.zoomRect', evnt => this.endTouchZoom(evnt)); } - } while( t > kMACHEP ); + }, - return ans * ax; -} + /** @summary Move touch zooming */ + moveTouchZoom(evnt) { + if (this.zoom_kind < 100) return; -/** @summary igam function - * @memberof Math */ -function igam(a, x) { + evnt.preventDefault(); - // LM: for negative values returns 1.0 instead of zero - // This is correct if a is a negative integer since Gamma(-n) = +/- inf - if (a <= 0) return 1.0; + const arr = get_touch_pointers(evnt, this.getFrameSvg().node()); - if (x <= 0) return 0.0; + if (arr.length !== 2) + return this.clearInteractiveElements(); - if( (x > 1.0) && (x > a ) ) - return 1.0 - igamc(a,x); + const pnt1 = arr[0], pnt2 = arr[1]; - /* Compute x**a * exp(-x) / gamma(a) */ - let ax = a * Math.log(x) - x - lgam(a); - if( ax < -kMAXLOG ) - return 0.0; + if (this.zoom_kind !== 103) { + this.zoom_curr[0] = Math.min(pnt1[0], pnt2[0]); + this.zoom_origin[0] = Math.max(pnt1[0], pnt2[0]); + } + if (this.zoom_kind !== 102) { + this.zoom_curr[1] = Math.min(pnt1[1], pnt2[1]); + this.zoom_origin[1] = Math.max(pnt1[1], pnt2[1]); + } - ax = Math.exp(ax); + this.zoom_rect.attr('x', this.zoom_curr[0]) + .attr('y', this.zoom_curr[1]) + .attr('width', this.zoom_origin[0] - this.zoom_curr[0]) + .attr('height', this.zoom_origin[1] - this.zoom_curr[1]); - /* power series */ - let r = a, c = 1.0, ans = 1.0; + if ((this.zoom_origin[0] - this.zoom_curr[0] > 10) || (this.zoom_origin[1] - this.zoom_curr[1] > 10)) + setPainterTooltipEnabled(this, false); - do { - r += 1.0; - c *= x/r; - ans += c; - } while( c/ans > kMACHEP ); + evnt.stopPropagation(); + }, - return ans * ax/a; -} + /** @summary End touch zooming handler */ + endTouchZoom(evnt) { + if (this.zoom_kind < 100) return; + drag_kind = ''; // reset global flag -/** @summary igami function - * @memberof Math */ -function igami(a, y0) { - // check the domain - if (a <= 0) { - console.error('igami : Wrong domain for parameter a (must be > 0)'); - return 0; - } - if (y0 <= 0) { - return Number.POSITIVE_INFINITY; - } - if (y0 >= 1) { - return 0; - } - const kMAXNUM = Number.MAX_VALUE; - let x0 = kMAXNUM, x1 = 0, x, yl = 0, yh = 1, y, d, lgm, dithresh = 5.0 * kMACHEP, i, dir; + evnt.preventDefault(); + if (!evnt.$emul) { + select(window).on('touchmove.zoomRect', null) + .on('touchend.zoomRect', null) + .on('touchcancel.zoomRect', null); + } - /* approximation to inverse function */ - d = 1.0/(9.0*a); - y = ( 1.0 - d - ndtri(y0) * Math.sqrt(d) ); - x = a * y * y * y; + let xmin, xmax, ymin, ymax, isany = false, namex = 'x', namey = 'y'; + const xid = this.swap_xy ? 1 : 0, yid = 1 - xid, changed = [true, true]; - lgm = lgam(a); + if (this.zoom_kind === 102) changed[1] = false; + if (this.zoom_kind === 103) changed[0] = false; - for( i=0; i<10; ++i ) { - if ( x > x0 || x < x1 ) - break; - y = igamc(a,x); - if ( y < yl || y > yh ) - break; - if ( y < y0 ) { - x0 = x; - yl = y; + if (changed[xid] && (Math.abs(this.zoom_curr[xid] - this.zoom_origin[xid]) > 10)) { + if (this.zoom_second && (this.zoom_kind === 102)) namex = 'x2'; + xmin = Math.min(this.revertAxis(namex, this.zoom_origin[xid]), this.revertAxis(namex, this.zoom_curr[xid])); + xmax = Math.max(this.revertAxis(namex, this.zoom_origin[xid]), this.revertAxis(namex, this.zoom_curr[xid])); + isany = true; } - else { - x1 = x; - yh = y; + + if (changed[yid] && (Math.abs(this.zoom_curr[yid] - this.zoom_origin[yid]) > 10)) { + if (this.zoom_second && (this.zoom_kind === 103)) namey = 'y2'; + ymin = Math.min(this.revertAxis(namey, this.zoom_origin[yid]), this.revertAxis(namey, this.zoom_curr[yid])); + ymax = Math.max(this.revertAxis(namey, this.zoom_origin[yid]), this.revertAxis(namey, this.zoom_curr[yid])); + isany = true; } - /* compute the derivative of the function at this point */ - d = (a - 1.0) * Math.log(x) - x - lgm; - if ( d < -kMAXLOG ) - break; - d = -Math.exp(d); - /* compute the step to the next approximation of x */ - d = (y - y0)/d; - if ( Math.abs(d/x) < kMACHEP ) - return x; - x = x - d; - } - /* Resort to interval halving if Newton iteration did not converge. */ - d = 0.0625; - if ( x0 == kMAXNUM ) { - if ( x <= 0.0 ) - x = 1.0; - while ( x0 == kMAXNUM ) { - x = (1.0 + d) * x; - y = igamc( a, x ); - if ( y < y0 ) { - x0 = x; - yl = y; - break; - } - d = d + d; + + this.clearInteractiveElements(); + delete this.last_touch_time; + + if (namex === 'x2') { + this.zoomChangedInteractive(namex, true); + this.zoomSingle(namex, xmin, xmax); + } else if (namey === 'y2') { + this.zoomChangedInteractive(namey, true); + this.zoomSingle(namey, ymin, ymax); + } else if (isany) { + this.zoomChangedInteractive('x', true); + this.zoomChangedInteractive('y', true); + this.zoom(xmin, xmax, ymin, ymax); } - } - d = 0.5; - dir = 0; - for( i=0; i<400; ++i ) { - x = x1 + d * (x0 - x1); - y = igamc( a, x ); - lgm = (x0 - x1)/(x1 + x0); - if ( Math.abs(lgm) < dithresh ) - break; - lgm = (y - y0)/y0; - if ( Math.abs(lgm) < dithresh ) - break; - if ( x <= 0.0 ) - break; - if ( y >= y0 ) { - x1 = x; - yh = y; - if ( dir < 0 ) { - dir = 0; - d = 0.5; - } - else if ( dir > 1 ) - d = 0.5 * d + 0.5; - else - d = (y0 - yl)/(yh - yl); - dir += 1; + evnt.stopPropagation(); + }, + + /** @summary Analyze zooming with mouse wheel */ + analyzeMouseWheelEvent(event, item, dmin, test_ignore, second_side) { + // if there is second handle, use it + const handle2 = second_side ? this[item.name + '2_handle'] : null; + if (handle2) { + item.second = Object.assign({}, item); + return handle2.analyzeWheelEvent(event, dmin, item.second, test_ignore); } - else { - x0 = x; - yl = y; - if ( dir > 0 ) { - dir = 0; - d = 0.5; + const handle = this[item.name + '_handle']; + return handle?.analyzeWheelEvent(event, dmin, item, test_ignore); + }, + + /** @summary return true if default Y zooming should be enabled + * @desc it is typically for 2-Dim histograms or + * when histogram not draw, defined by other painters */ + isAllowedDefaultYZooming() { + if (this.self_drawaxes) return true; + + const pad_painter = this.getPadPainter(); + if (pad_painter?.painters) { + for (let k = 0; k < pad_painter.painters.length; ++k) { + const subpainter = pad_painter.painters[k]; + if (subpainter?.wheel_zoomy !== undefined) + return subpainter.wheel_zoomy; } - else if ( dir < -1 ) - d = 0.5 * d; - else - d = (y0 - yl)/(yh - yl); - dir -= 1; } - } - return x; -} -/** @summary landau_pdf function - * @desc LANDAU pdf : algorithm from CERNLIB G110 denlan - * same algorithm is used in GSL - * @memberof Math */ -function landau_pdf(x, xi, x0 = 0) { - if (xi <= 0) return 0; - const v = (x - x0)/xi; - let u, ue, us, denlan; - const p1 = [0.4259894875,-0.1249762550, 0.03984243700, -0.006298287635, 0.001511162253], - q1 = [1.0 ,-0.3388260629, 0.09594393323, -0.01608042283, 0.003778942063], - p2 = [0.1788541609, 0.1173957403, 0.01488850518, -0.001394989411, 0.0001283617211], - q2 = [1.0 , 0.7428795082, 0.3153932961, 0.06694219548, 0.008790609714], - p3 = [0.1788544503, 0.09359161662,0.006325387654, 0.00006611667319,-0.000002031049101], - q3 = [1.0 , 0.6097809921, 0.2560616665, 0.04746722384, 0.006957301675], - p4 = [0.9874054407, 118.6723273, 849.2794360, -743.7792444, 427.0262186], - q4 = [1.0 , 106.8615961, 337.6496214, 2016.712389, 1597.063511], - p5 = [1.003675074, 167.5702434, 4789.711289, 21217.86767, -22324.94910], - q5 = [1.0 , 156.9424537, 3745.310488, 9834.698876, 66924.28357], - p6 = [1.000827619, 664.9143136, 62972.92665, 475554.6998, -5743609.109], - q6 = [1.0 , 651.4101098, 56974.73333, 165917.4725, -2815759.939], - a1 = [0.04166666667,-0.01996527778, 0.02709538966], - a2 = [-1.845568670,-4.284640743]; + return false; + }, - if (v < -5.5) { - u = Math.exp(v+1.0); - if (u < 1e-10) return 0.0; - ue = Math.exp(-1/u); - us = Math.sqrt(u); - denlan = 0.3989422803*(ue/us)*(1+(a1[0]+(a1[1]+a1[2]*u)*u)*u); - } else if(v < -1) { - u = Math.exp(-v-1); - denlan = Math.exp(-u)*Math.sqrt(u)* - (p1[0]+(p1[1]+(p1[2]+(p1[3]+p1[4]*v)*v)*v)*v)/ - (q1[0]+(q1[1]+(q1[2]+(q1[3]+q1[4]*v)*v)*v)*v); - } else if(v < 1) { - denlan = (p2[0]+(p2[1]+(p2[2]+(p2[3]+p2[4]*v)*v)*v)*v)/ - (q2[0]+(q2[1]+(q2[2]+(q2[3]+q2[4]*v)*v)*v)*v); - } else if(v < 5) { - denlan = (p3[0]+(p3[1]+(p3[2]+(p3[3]+p3[4]*v)*v)*v)*v)/ - (q3[0]+(q3[1]+(q3[2]+(q3[3]+q3[4]*v)*v)*v)*v); - } else if(v < 12) { - u = 1/v; - denlan = u*u*(p4[0]+(p4[1]+(p4[2]+(p4[3]+p4[4]*u)*u)*u)*u)/ - (q4[0]+(q4[1]+(q4[2]+(q4[3]+q4[4]*u)*u)*u)*u); - } else if(v < 50) { - u = 1/v; - denlan = u*u*(p5[0]+(p5[1]+(p5[2]+(p5[3]+p5[4]*u)*u)*u)*u)/ - (q5[0]+(q5[1]+(q5[2]+(q5[3]+q5[4]*u)*u)*u)*u); - } else if(v < 300) { - u = 1/v; - denlan = u*u*(p6[0]+(p6[1]+(p6[2]+(p6[3]+p6[4]*u)*u)*u)*u)/ - (q6[0]+(q6[1]+(q6[2]+(q6[3]+q6[4]*u)*u)*u)*u); - } else { - u = 1/(v-v*Math.log(v)/(v+1)); - denlan = u*u*(1+(a2[0]+a2[1]*u)*u); - } - return denlan/xi; -} + /** @summary Handles mouse wheel event */ + mouseWheel(evnt) { + evnt.stopPropagation(); + evnt.preventDefault(); + this.clearInteractiveElements(); -/** @summary Landau function - * @memberof Math */ -function Landau(x, mpv, sigma, norm) { - if (sigma <= 0) return 0; - const den = landau_pdf((x - mpv) / sigma, 1, 0); - if (!norm) return den; - return den/sigma; -} + const itemx = { name: 'x', reverse: this.reverse_x }, + itemy = { name: 'y', reverse: this.reverse_y, ignore: !this.isAllowedDefaultYZooming() }, + cur = pointer(evnt, this.getFrameSvg().node()), + w = this.getFrameWidth(), h = this.getFrameHeight(); -/** @summary inc_gamma_c - * @memberof Math */ -function inc_gamma_c(a,x) { - return igamc(a,x); -} + if (this.can_zoom_x) + this.analyzeMouseWheelEvent(evnt, this.swap_xy ? itemy : itemx, cur[0] / w, (cur[1] >= 0) && (cur[1] <= h), cur[1] < 0); -/** @summary inc_gamma - * @memberof Math */ -function inc_gamma(a,x) { - return igam(a,x); -} + if (this.can_zoom_y) + this.analyzeMouseWheelEvent(evnt, this.swap_xy ? itemx : itemy, 1 - cur[1] / h, (cur[0] >= 0) && (cur[0] <= w), cur[0] > w); -/** @summary lgamma - * @memberof Math */ -function lgamma(z) { - return lgam(z); -} + let pr = this.zoom(itemx.min, itemx.max, itemy.min, itemy.max); -/** @summary Probability density function of the beta distribution. - * @memberof Math */ -function beta_pdf(x, a, b) { - if (x < 0 || x > 1.0) return 0; - if (x == 0 ) { - if (a < 1) return Number.POSITIVE_INFINITY; - else if (a > 1) return 0; - else if ( a == 1) return b; // to avoid a nan from log(0)*0 - } - if (x == 1 ) { - if (b < 1) return Number.POSITIVE_INFINITY; - else if (b > 1) return 0; - else if ( b == 1) return a; // to avoid a nan from log(0)*0 - } - return Math.exp(lgamma(a + b) - lgamma(a) - lgamma(b) + - Math.log(x) * (a -1.) + Math.log1p(-x) * (b - 1.)); -} + if (itemx.changed) this.zoomChangedInteractive('x', true); + if (itemy.changed) this.zoomChangedInteractive('y', true); -/** @summary beta - * @memberof Math */ -function beta(x,y) { - return Math.exp(lgamma(x)+lgamma(y)-lgamma(x+y)); -} + if (itemx.second) { + pr = pr.then(() => this.zoomSingle('x2', itemx.second.min, itemx.second.max)); + if (itemx.second.changed) this.zoomChangedInteractive('x2', true); + } + if (itemy.second) { + pr = pr.then(() => this.zoomSingle('y2', itemy.second.min, itemy.second.max)); + if (itemy.second.changed) this.zoomChangedInteractive('y2', true); + } -/** @summary chisquared_cdf_c - * @memberof Math */ -function chisquared_cdf_c(x,r,x0 = 0) { - return inc_gamma_c ( 0.5 * r , 0.5*(x-x0) ); -} + return pr; + }, -/** @summary Continued fraction expansion #1 for incomplete beta integral - * @memberof Math */ -function incbcf(a,b,x) { - let xk, pk, pkm1, pkm2, qk, qkm1, qkm2, - k1, k2, k3, k4, k5, k6, k7, k8, - r, t, ans, thresh, n; + /** @summary Show frame context menu */ + showContextMenu(kind, evnt, obj) { + // disable context menu left/right buttons clicked + if (evnt?.buttons === 3) + return evnt.preventDefault(); - k1 = a; - k2 = a + b; - k3 = a; - k4 = a + 1.0; - k5 = 1.0; - k6 = b - 1.0; - k7 = k4; - k8 = a + 2.0; + // ignore context menu when touches zooming is ongoing or + if (('zoom_kind' in this) && (this.zoom_kind > 100)) return; - pkm2 = 0.0; - qkm2 = 1.0; - pkm1 = 1.0; - qkm1 = 1.0; - ans = 1.0; - r = 1.0; - n = 0; - thresh = 3.0 * kMACHEP; - do - { + let pnt, menu_painter = this, exec_painter = null, + frame_corner = false, fp = null; // object used to show context menu + const svg_node = this.getFrameSvg().node(); - xk = -( x * k1 * k2 )/( k3 * k4 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + if (isFunc(evnt?.stopPropagation)) { + evnt.preventDefault(); + evnt.stopPropagation(); // disable main context menu + const ms = pointer(evnt, svg_node), + tch = get_touch_pointers(evnt, svg_node); + if (tch.length === 1) + pnt = { x: tch[0][0], y: tch[0][1], touch: true }; + else if (ms.length === 2) + pnt = { x: ms[0], y: ms[1], touch: false }; + } else if ((evnt?.x !== undefined) && (evnt?.y !== undefined) && (evnt?.clientX === undefined)) { + pnt = evnt; + const rect = svg_node.getBoundingClientRect(); + evnt = { clientX: rect.left + pnt.x, clientY: rect.top + pnt.y }; + } - xk = ( x * k5 * k6 )/( k7 * k8 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + if ((kind === 'painter') && obj) { + menu_painter = obj; + kind = ''; + } else if (kind === 'main') { + menu_painter = this.getMainPainter(true); + kind = ''; + } else if (!kind) { + const pp = this.getPadPainter(); + let sel = null; + + fp = this; + if (pnt && pp) { + pnt.painters = true; // assign painter for every tooltip + const hints = pp.processPadTooltipEvent(pnt); + let bestdist = 1000; + for (let n = 0; n < hints.length; ++n) { + if (hints[n]?.menu) { + const dist = hints[n].menu_dist ?? 7; + if (dist < bestdist) { sel = hints[n].painter; bestdist = dist; } + } + } + } - if( qk !=0 ) - r = pk/qk; - if( r != 0 ) - { - t = Math.abs( (ans - r)/r ); - ans = r; - } - else - t = 1.0; + if (sel) menu_painter = sel; + else kind = 'frame'; - if( t < thresh ) - break; // goto cdone; + if (pnt) frame_corner = (pnt.x > 0) && (pnt.x < 20) && (pnt.y > 0) && (pnt.y < 20); - k1 += 1.0; - k2 += 1.0; - k3 += 2.0; - k4 += 2.0; - k5 += 1.0; - k6 -= 1.0; - k7 += 2.0; - k8 += 2.0; + fp.setLastEventPos(pnt); + } else if ((kind === 'x') || (kind === 'y') || (kind === 'z') || (kind === 'pal')) { + exec_painter = this.getMainPainter(true); // histogram painter delivers items for axis menu - if( (Math.abs(qk) + Math.abs(pk)) > kBig ) - { - pkm2 *= kBiginv; - pkm1 *= kBiginv; - qkm2 *= kBiginv; - qkm1 *= kBiginv; - } - if( (Math.abs(qk) < kBiginv) || (Math.abs(pk) < kBiginv) ) - { - pkm2 *= kBig; - pkm1 *= kBig; - qkm2 *= kBig; - qkm1 *= kBig; + if (this.v7_frame && isFunc(exec_painter?.v7EvalAttr)) + exec_painter = null; } - } - while( ++n < 300 ); -// cdone: - return ans; -} + if (!exec_painter) exec_painter = menu_painter; -/** @summary Continued fraction expansion #2 for incomplete beta integral - * @memberof Math */ -function incbd(a,b,x) { - let xk, pk, pkm1, pkm2, qk, qkm1, qkm2, - k1, k2, k3, k4, k5, k6, k7, k8, - r, t, ans, z, thresh, n; + if (!isFunc(menu_painter?.fillContextMenu)) return; - k1 = a; - k2 = b - 1.0; - k3 = a; - k4 = a + 1.0; - k5 = 1.0; - k6 = a + b; - k7 = a + 1.0; k8 = a + 2.0; + this.clearInteractiveElements(); - pkm2 = 0.0; - qkm2 = 1.0; - pkm1 = 1.0; - qkm1 = 1.0; - z = x / (1.0-x); - ans = 1.0; - r = 1.0; - n = 0; - thresh = 3.0 * kMACHEP; - do - { + return createMenu(evnt, menu_painter).then(menu => { + let domenu = menu.painter.fillContextMenu(menu, kind, obj); - xk = -( z * k1 * k2 )/( k3 * k4 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + // fill frame menu by default - or append frame elements when activated in the frame corner + if (fp && (!domenu || (frame_corner && (kind !== 'frame')))) + domenu = fp.fillContextMenu(menu); - xk = ( z * k5 * k6 )/( k7 * k8 ); - pk = pkm1 + pkm2 * xk; - qk = qkm1 + qkm2 * xk; - pkm2 = pkm1; - pkm1 = pk; - qkm2 = qkm1; - qkm1 = qk; + if (domenu) { + return exec_painter.fillObjectExecMenu(menu, kind).then(menu => { + // suppress any running zooming + setPainterTooltipEnabled(menu.painter, false); + return menu.show().then(() => setPainterTooltipEnabled(menu.painter, true)); + }); + } + }); + }, - if( qk != 0 ) - r = pk/qk; - if( r != 0 ) - { - t = Math.abs( (ans - r)/r ); - ans = r; - } - else - t = 1.0; + /** @summary Activate touch handling on frame + * @private */ + startSingleTouchHandling(kind, evnt) { + const arr = get_touch_pointers(evnt, this.getFrameSvg().node()); + if (arr.length !== 1) return; - if( t < thresh ) - break; // goto cdone; + evnt.preventDefault(); + evnt.stopPropagation(); + closeMenu(); - k1 += 1.0; - k2 -= 1.0; - k3 += 2.0; - k4 += 2.0; - k5 += 1.0; - k6 += 1.0; - k7 += 2.0; - k8 += 2.0; + const tm = new Date().getTime(); - if( (Math.abs(qk) + Math.abs(pk)) > kBig ) - { - pkm2 *= kBiginv; - pkm1 *= kBiginv; - qkm2 *= kBiginv; - qkm1 *= kBiginv; - } - if( (Math.abs(qk) < kBiginv) || (Math.abs(pk) < kBiginv) ) - { - pkm2 *= kBig; - pkm1 *= kBig; - qkm2 *= kBig; - qkm1 *= kBig; + this._shifting_dx = 0; + this._shifting_dy = 0; + + setPainterTooltipEnabled(this, false); + + select(window).on('touchmove.singleTouch', kind ? null : evnt => this.moveTouchHandling(evnt, kind, arr[0])) + .on('touchcancel.singleTouch', evnt => this.endSingleTouchHandling(evnt, kind, arr[0], tm)) + .on('touchend.singleTouch', evnt => this.endSingleTouchHandling(evnt, kind, arr[0], tm)); + }, + + /** @summary Moving of touch pointer + * @private */ + moveTouchHandling(evnt, kind, pos0) { + const frame = this.getFrameSvg(), + main_svg = this.draw_g.selectChild('.main_layer'); + let pos; + + try { + pos = get_touch_pointers(evnt, frame.node())[0]; + } catch (err) { + pos = [0, 0]; + if (evnt?.changedTouches) + pos = [evnt.changedTouches[0].clientX, evnt.changedTouches[0].clientY]; } - } - while( ++n < 300 ); -//cdone: - return ans; -} -/** @summary ROOT::Math::Cephes::pseries - * @memberof Math */ -function pseries(a,b,x) { - let s, t, u, v, n, t1, z, ai; + const dx = pos0[0] - pos[0], + dy = (this.scales_ndim === 1) ? 0 : pos0[1] - pos[1], + w = this.getFrameWidth(), h = this.getFrameHeight(); - ai = 1.0 / a; - u = (1.0 - b) * x; - v = u / (a + 1.0); - t1 = v; - t = u; - n = 2.0; - s = 0.0; - z = kMACHEP * ai; - while( Math.abs(v) > z ) - { - u = (n - b) * x / n; - t *= u; - v = t / (a + n); - s += v; - n += 1.0; - } - s += t1; - s += ai; + this._shifting_dx = dx; + this._shifting_dy = dy; - u = a * Math.log(x); - if( (a+b) < kMAXSTIR && Math.abs(u) < kMAXLOG ) - { - t = gamma(a+b) / (gamma(a)*gamma(b)); - s = s * t * Math.pow(x,a); - } - else - { - t = lgam(a+b) - lgam(a) - lgam(b) + u + Math.log(s); - if( t < kMINLOG ) - s = 0.0; - else - s = Math.exp(t); - } - return s; -} + main_svg.attr('viewBox', `${dx} ${dy} ${w} ${h}`); + }, -/** @summary ROOT::Math::Cephes::incbet - * @memberof Math */ -function incbet(aa,bb,xx) { - let a, b, t, x, xc, w, y, flag; + /** @summary Process end-touch event, which can cause content menu to appear + * @private */ + endSingleTouchHandling(evnt, kind, pos, tm) { + evnt?.preventDefault(); + evnt?.stopPropagation(); - if( aa <= 0.0 || bb <= 0.0 ) - return 0.0; + setPainterTooltipEnabled(this, true); - // LM: changed: for X > 1 return 1. - if (xx <= 0.0) return 0.0; - if ( xx >= 1.0) return 1.0; + select(window).on('touchmove.singleTouch', null) + .on('touchcancel.singleTouch', null) + .on('touchend.singleTouch', null); - flag = 0; + if (evnt === null) return; -/* - to test if that way is better for large b/ (comment out from Cephes version) - if( (bb * xx) <= 1.0 && xx <= 0.95) - { - t = pseries(aa, bb, xx); - goto done; - } + if (Math.abs(this._shifting_dx) > 2 || Math.abs(this._shifting_dy) > 2) + this.performScalesShift(); + else if (new Date().getTime() - tm > 700) + this.showContextMenu(kind, { x: pos[0], y: pos[1] }); + }, -**/ - w = 1.0 - xx; + /** @summary Clear frame interactive elements */ + clearInteractiveElements() { + closeMenu(); + this.zoom_kind = 0; + this.zoom_rect?.remove(); + delete this.zoom_rect; + delete this.zoom_curr; + delete this.zoom_origin; + delete this.zoom_lastpos; + delete this.zoom_labels; -/* Reverse a and b if x is greater than the mean. */ -/* aa,bb > 1 -> sharp rise at x=aa/(aa+bb) */ - if( xx > (aa/(aa+bb)) ) - { - flag = 1; - a = bb; - b = aa; - xc = xx; - x = w; - } - else - { - a = aa; - b = bb; - xc = w; - x = xx; + // enable tooltip in frame painter + setPainterTooltipEnabled(this, true); + }, + + /** @summary Assign frame interactive methods */ + assign(painter) { + Object.assign(painter, this); } - if( flag == 1 && (b * x) <= 1.0 && x <= 0.95) - { - t = pseries(a, b, x); - // goto done; - } else { +}; // FrameInterative - /* Choose expansion for better convergence. */ - y = x * (a+b-2.0) - (a-1.0); - if( y < 0.0 ) - w = incbcf( a, b, x ); - else - w = incbd( a, b, x ) / xc; - /* Multiply w by the factor - a b _ _ _ - x (1-x) | (a+b) / ( a | (a) | (b) ) . */ +/** + * @summary Painter class for TFrame, main handler for interactivity + * @private + */ - y = a * Math.log(x); - t = b * Math.log(xc); - if( (a+b) < kMAXSTIR && Math.abs(y) < kMAXLOG && Math.abs(t) < kMAXLOG ) - { - t = Math.pow(xc,b); - t *= Math.pow(x,a); - t /= a; - t *= w; - t *= gamma(a+b) / (gamma(a) * gamma(b)); - // goto done; - } else { - /* Resort to logarithms. */ - y += t + lgam(a+b) - lgam(a) - lgam(b); - y += Math.log(w/a); - if( y < kMINLOG ) - t = 0.0; - else - t = Math.exp(y); - } +class TFramePainter extends ObjectPainter { + + /** @summary constructor + * @param {object|string} dom - DOM element for drawing or element id + * @param {object} tframe - TFrame object */ + constructor(dom, tframe) { + super(dom, (tframe && tframe.$dummy) ? null : tframe); + this.zoom_kind = 0; + this.mode3d = false; + this.shrink_frame_left = 0.0; + this.xmin = this.xmax = 0; // no scale specified, wait for objects drawing + this.ymin = this.ymax = 0; // no scale specified, wait for objects drawing + this.ranges_set = false; + this.axes_drawn = false; + this.keys_handler = null; + this.projection = 0; // different projections } -//done: + /** @summary Returns frame painter - object itself */ + getFramePainter() { return this; } - if( flag == 1 ) - { - if( t <= kMACHEP ) - t = 1.0 - kMACHEP; - else - t = 1.0 - t; - } - return t; -} + /** @summary Returns true if it is ROOT6 frame + * @private */ + is_root6() { return true; } -/** @summary copy of ROOT::Math::Cephes::incbi - * @memberof Math */ -function incbi(aa,bb,yy0) { - let a, b, y0, d, y, x, x0, x1, lgm, yp, di, dithresh, yl, yh, xt; - let i, rflg, dir, nflg, ihalve = true; + /** @summary Returns frame or sub-objects, used in GED editor */ + getObject(place) { + if (place === 'xaxis') return this.xaxis; + if (place === 'yaxis') return this.yaxis; + return super.getObject(); + } - // check the domain - if (aa <= 0) { - // MATH_ERROR_MSG('Cephes::incbi','Wrong domain for parameter a (must be > 0)'); - return 0; + /** @summary Set active flag for frame - can block some events + * @private */ + setFrameActive(on) { + this.enabledKeys = on && settings.HandleKeys; + // used only in 3D mode where control is used + if (this.control) + this.control.enableKeys = this.enabledKeys; } - if (bb <= 0) { - // MATH_ERROR_MSG('Cephes::incbi','Wrong domain for parameter b (must be > 0)'); - return 0; + + /** @summary Shrink frame size + * @private */ + shrinkFrame(shrink_left, shrink_right) { + this.fX1NDC += shrink_left; + this.fX2NDC -= shrink_right; } - const process_done = () => { - if( rflg ) { - if( x <= kMACHEP ) - x = 1.0 - kMACHEP; - else - x = 1.0 - x; - } - return x; - }; + /** @summary Set position of last context menu event */ + setLastEventPos(pnt) { + this.fLastEventPnt = pnt; + } - i = 0; - if( yy0 <= 0 ) - return 0.0; - if( yy0 >= 1.0 ) - return 1.0; - x0 = 0.0; - yl = 0.0; - x1 = 1.0; - yh = 1.0; - nflg = 0; + /** @summary Return position of last event + * @private */ + getLastEventPos() { return this.fLastEventPnt; } - if( aa <= 1.0 || bb <= 1.0 ) - { - dithresh = 1.0e-6; - rflg = 0; - a = aa; - b = bb; - y0 = yy0; - x = a/(a+b); - y = incbet( a, b, x ); - // goto ihalve; // will start - } - else - { - dithresh = 1.0e-4; -/* approximation to inverse function */ + /** @summary Returns coordinates transformation func */ + getProjectionFunc() { return getEarthProjectionFunc(this.projection); } - yp = -ndtri(yy0); + /** @summary Rcalculate frame ranges using specified projection functions */ + recalculateRange(Proj, change_x, change_y) { + this.projection = Proj || 0; - if( yy0 > 0.5 ) - { - rflg = 1; - a = bb; - b = aa; - y0 = 1.0 - yy0; - yp = -yp; - } - else - { - rflg = 0; - a = aa; - b = bb; - y0 = yy0; + if ((this.projection === 2) && ((this.scale_ymin <= -90 || this.scale_ymax >= 90))) { + console.warn(`Mercator Projection: Latitude out of range ${this.scale_ymin} ${this.scale_ymax}`); + this.projection = 0; } - lgm = (yp * yp - 3.0)/6.0; - x = 2.0/( 1.0/(2.0*a-1.0) + 1.0/(2.0*b-1.0) ); - d = yp * Math.sqrt( x + lgm ) / x - - ( 1.0/(2.0*b-1.0) - 1.0/(2.0*a-1.0) ) - * (lgm + 5.0/6.0 - 2.0/(3.0*x)); - d = 2.0 * d; - if( d < kMINLOG ) - { - // x = 1.0; - // goto under; - x = 0.0; - return process_done(); - } - x = a/( a + b * Math.exp(d) ); - y = incbet( a, b, x ); - yp = (y - y0)/y0; - if( Math.abs(yp) < 0.2 ) - ihalve = false; // instead goto newt; exclude ihalve for the first time - } + const func = this.getProjectionFunc(); + if (!func) return; - let mainloop = 1000; + const pnts = [func(this.scale_xmin, this.scale_ymin), + func(this.scale_xmin, this.scale_ymax), + func(this.scale_xmax, this.scale_ymax), + func(this.scale_xmax, this.scale_ymin)]; + if (this.scale_xmin < 0 && this.scale_xmax > 0) { + pnts.push(func(0, this.scale_ymin)); + pnts.push(func(0, this.scale_ymax)); + } + if (this.scale_ymin < 0 && this.scale_ymax > 0) { + pnts.push(func(this.scale_xmin, 0)); + pnts.push(func(this.scale_xmax, 0)); + } - // endless loop until coverage - while (mainloop-- > 0) { + this.original_xmin = this.scale_xmin; + this.original_xmax = this.scale_xmax; + this.original_ymin = this.scale_ymin; + this.original_ymax = this.scale_ymax; - /* Resort to interval halving if not close enough. */ - // ihalve: - while(ihalve) { + if (change_x) + this.scale_xmin = this.scale_xmax = pnts[0].x; + if (change_y) + this.scale_ymin = this.scale_ymax = pnts[0].y; - dir = 0; - di = 0.5; - for( i=0; i<100; i++ ) - { - if( i != 0 ) - { - x = x0 + di * (x1 - x0); - if( x == 1.0 ) - x = 1.0 - kMACHEP; - if( x == 0.0 ) - { - di = 0.5; - x = x0 + di * (x1 - x0); - if( x == 0.0 ) - return process_done(); // goto under; - } - y = incbet( a, b, x ); - yp = (x1 - x0)/(x1 + x0); - if( Math.abs(yp) < dithresh ) - break; // goto newt; - yp = (y-y0)/y0; - if( Math.abs(yp) < dithresh ) - break; // goto newt; - } - if( y < y0 ) - { - x0 = x; - yl = y; - if( dir < 0 ) - { - dir = 0; - di = 0.5; - } - else if( dir > 3 ) - di = 1.0 - (1.0 - di) * (1.0 - di); - else if( dir > 1 ) - di = 0.5 * di + 0.5; - else - di = (y0 - y)/(yh - yl); - dir += 1; - if( x0 > 0.75 ) - { - if( rflg == 1 ) - { - rflg = 0; - a = aa; - b = bb; - y0 = yy0; - } - else - { - rflg = 1; - a = bb; - b = aa; - y0 = 1.0 - yy0; - } - x = 1.0 - x; - y = incbet( a, b, x ); - x0 = 0.0; - yl = 0.0; - x1 = 1.0; - yh = 1.0; - continue; // goto ihalve; - } - } - else - { - x1 = x; - if( rflg == 1 && x1 < kMACHEP ) - { - x = 0.0; - return process_done(); // goto done; - } - yh = y; - if( dir > 0 ) - { - dir = 0; - di = 0.5; - } - else if( dir < -3 ) - di = di * di; - else if( dir < -1 ) - di = 0.5 * di; - else - di = (y - y0)/(yh - yl); - dir -= 1; - } - } - //math_error( 'incbi', PLOSS ); - if( x0 >= 1.0 ) { - x = 1.0 - kMACHEP; - return process_done(); //goto done; + for (let n = 1; n < pnts.length; ++n) { + if (change_x) { + this.scale_xmin = Math.min(this.scale_xmin, pnts[n].x); + this.scale_xmax = Math.max(this.scale_xmax, pnts[n].x); } - if( x <= 0.0 ) { - //math_error( 'incbi', UNDERFLOW ); - x = 0.0; - return process_done(); //goto done; + if (change_y) { + this.scale_ymin = Math.min(this.scale_ymin, pnts[n].y); + this.scale_ymax = Math.max(this.scale_ymax, pnts[n].y); } - break; // if here, break ihalve + } + } - } // end of ihalve + /** @summary Configure frame axes ranges */ + setAxesRanges(xaxis, xmin, xmax, yaxis, ymin, ymax, zaxis, zmin, zmax, hpainter) { + this.ranges_set = true; - ihalve = true; // enter loop next time + this.xaxis = xaxis; + this.xmin = xmin; + this.xmax = xmax; - // newt: + this.yaxis = yaxis; + this.ymin = ymin; + this.ymax = ymax; - if( nflg ) - return process_done(); //goto done; - nflg = 1; - lgm = lgam(a+b) - lgam(a) - lgam(b); + this.zaxis = zaxis; + this.zmin = zmin; + this.zmax = zmax; - for( i=0; i<8; i++ ) - { - /* Compute the function at this point. */ - if( i != 0 ) - y = incbet(a,b,x); - if( y < yl ) - { - x = x0; - y = yl; - } - else if( y > yh ) - { - x = x1; - y = yh; - } - else if( y < y0 ) - { - x0 = x; - yl = y; - } - else - { - x1 = x; - yh = y; - } - if( x == 1.0 || x == 0.0 ) - break; - /* Compute the derivative of the function at this point. */ - d = (a - 1.0) * Math.log(x) + (b - 1.0) * Math.log(1.0-x) + lgm; - if( d < kMINLOG ) - return process_done(); // goto done; - if( d > kMAXLOG ) - break; - d = Math.exp(d); - /* Compute the step to the next approximation of x. */ - d = (y - y0)/d; - xt = x - d; - if( xt <= x0 ) - { - y = (x - x0) / (x1 - x0); - xt = x0 + 0.5 * y * (x - x0); - if( xt <= 0.0 ) - break; + if (hpainter?.check_pad_range) { + delete hpainter.check_pad_range; + const ndim = hpainter.getDimension(); + this.applyAxisZoom('x'); + if (ndim > 1) + this.applyAxisZoom('y'); + if (ndim > 2) + this.applyAxisZoom('z'); + } + + if (hpainter && !hpainter._checked_zooming) { + hpainter._checked_zooming = true; + + if (hpainter.options.minimum !== kNoZoom) { + this.zoom_zmin = hpainter.options.minimum; + this.zoom_zmax = this.zmax; } - if( xt >= x1 ) - { - y = (x1 - x) / (x1 - x0); - xt = x1 - 0.5 * y * (x1 - x); - if( xt >= 1.0 ) - break; + if (hpainter.options.maximum !== kNoZoom) { + this.zoom_zmax = hpainter.options.maximum; + if (this.zoom_zmin === undefined) this.zoom_zmin = this.zmin; } - x = xt; - if( Math.abs(d/x) < 128.0 * kMACHEP ) - return process_done(); // goto done; } - /* Did not converge. */ - dithresh = 256.0 * kMACHEP; + } - } // endless loop instead of // goto ihalve; + /** @summary Configure secondary frame axes ranges */ + setAxes2Ranges(second_x, xaxis, xmin, xmax, second_y, yaxis, ymin, ymax) { + if (second_x) { + this.x2axis = xaxis; + this.x2min = xmin; + this.x2max = xmax; + } + if (second_y) { + this.y2axis = yaxis; + this.y2min = ymin; + this.y2max = ymax; + } + } -// done: + /** @summary Retuns associated axis object */ + getAxis(name) { + switch (name) { + case 'x': return this.xaxis; + case 'y': return this.yaxis; + case 'z': return this.zaxis; + case 'x2': return this.x2axis; + case 'y2': return this.y2axis; + } + return null; + } - return process_done(); -} + /** @summary Apply axis zooming from pad user range + * @private */ + applyPadUserRange(pad, name) { + if (!pad) return; -/** @summary Calculates the normalized (regularized) incomplete beta function. - * @memberof Math */ -function inc_beta(x,a,b) { - return incbet(a,b,x); -} + // seems to be, not allways user range calculated + let umin = pad[`fU${name}min`], + umax = pad[`fU${name}max`], + eps = 1e-7; -const BetaIncomplete = inc_beta; + if (name === 'x') { + if ((Math.abs(pad.fX1) > eps) || (Math.abs(pad.fX2 - 1) > eps)) { + const dx = pad.fX2 - pad.fX1; + umin = pad.fX1 + dx*pad.fLeftMargin; + umax = pad.fX2 - dx*pad.fRightMargin; + } + } else { + if ((Math.abs(pad.fY1) > eps) || (Math.abs(pad.fY2 - 1) > eps)) { + const dy = pad.fY2 - pad.fY1; + umin = pad.fY1 + dy*pad.fBottomMargin; + umax = pad.fY2 - dy*pad.fTopMargin; + } + } -/** @summary ROOT::Math::beta_quantile - * @memberof Math */ -function beta_quantile(z,a,b) { - return incbi(a,b,z); -} + if ((umin >= umax) || (Math.abs(umin) < eps && Math.abs(umax-1) < eps)) return; -/** @summary Complement of the cumulative distribution function of the beta distribution. - * @memberof Math */ -function beta_cdf_c(x,a,b) { - return inc_beta(1-x, b, a); -} + if (pad[`fLog${name}`] > 0) { + umin = Math.exp(umin * Math.log(10)); + umax = Math.exp(umax * Math.log(10)); + } -/** @summary chisquared_cdf - * @memberof Math */ -function chisquared_cdf(x,r,x0=0) { - return inc_gamma ( 0.5 * r , 0.5*(x-x0) ); -} + let aname = name; + if (this.swap_xy) aname = (name === 'x') ? 'y' : 'x'; + const smin = `scale_${aname}min`, + smax = `scale_${aname}max`; -/** @summary gamma_quantile_c function - * @memberof Math */ -function gamma_quantile_c(z, alpha, theta) { - return theta * igami( alpha, z); -} + eps = (this[smax] - this[smin]) * 1e-7; -/** @summary gamma_quantile function - * @memberof Math */ -function gamma_quantile(z, alpha, theta) { - return theta * igami( alpha, 1.- z); -} + if ((Math.abs(umin - this[smin]) > eps) || (Math.abs(umax - this[smax]) > eps)) { + this[`zoom_${aname}min`] = umin; + this[`zoom_${aname}max`] = umax; + } + } -/** @summary breitwigner_cdf_c function - * @memberof Math */ -function breitwigner_cdf_c(x,gamma, x0 = 0) { - return 0.5 - Math.atan(2.0 * (x-x0) / gamma) / M_PI; -} + /** @summary Apply zooming from TAxis attributes */ + applyAxisZoom(name) { + if (this.zoomChangedInteractive(name)) return; + this[`zoom_${name}min`] = this[`zoom_${name}max`] = 0; -/** @summary breitwigner_cdf function - * @memberof Math */ -function breitwigner_cdf(x, gamma, x0 = 0) { - return 0.5 + Math.atan(2.0 * (x-x0) / gamma) / M_PI; -} + const axis = this.getAxis(name); -/** @summary cauchy_cdf_c function - * @memberof Math */ -function cauchy_cdf_c(x, b, x0 = 0) { - return 0.5 - Math.atan( (x-x0) / b) / M_PI; -} + if (axis?.TestBit(EAxisBits.kAxisRange)) { + if ((axis.fFirst !== axis.fLast) && ((axis.fFirst > 1) || (axis.fLast < axis.fNbins))) { + this[`zoom_${name}min`] = axis.fFirst > 1 ? axis.GetBinLowEdge(axis.fFirst) : axis.fXmin; + this[`zoom_${name}max`] = axis.fLast < axis.fNbins ? axis.GetBinLowEdge(axis.fLast + 1) : axis.fXmax; + // reset user range for main painter + axis.InvertBit(EAxisBits.kAxisRange); + axis.fFirst = 1; axis.fLast = axis.fNbins; + } + } + } -/** @summary cauchy_cdf function - * @memberof Math */ -function cauchy_cdf(x, b, x0 = 0) { - return 0.5 + Math.atan( (x-x0) / b) / M_PI; -} + /** @summary Create x,y objects which maps user coordinates into pixels + * @desc While only first painter really need such object, all others just reuse it + * following functions are introduced + * this.GetBin[X/Y] return bin coordinate + * this.[x,y] these are d3.scale objects + * this.gr[x,y] converts root scale into graphical value + * @private */ + createXY(opts) { + this.cleanXY(); // remove all previous configurations -/** @summary cauchy_pdf function - * @memberof Math */ -function cauchy_pdf(x, b = 1, x0 = 0) { - return b/(M_PI * ((x-x0)*(x-x0) + b*b)); -} + if (!opts) opts = { ndim: 1 }; -/** @summary gaussian_pdf function - * @memberof Math */ -function gaussian_pdf(x, sigma = 1, x0 = 0) { - let tmp = (x-x0)/sigma; - return (1.0/(Math.sqrt(2 * M_PI) * Math.abs(sigma))) * Math.exp(-tmp*tmp/2); -} + this.swap_xy = opts.swap_xy || false; + this.reverse_x = opts.reverse_x || false; + this.reverse_y = opts.reverse_y || false; -/** @summary gamma_pdf function - * @memberof Math */ -function gamma_pdf(x, alpha, theta, x0 = 0) { - if ((x - x0) < 0) { - return 0.0; - } else if ((x - x0) == 0) { - return (alpha == 1) ? 1.0 / theta : 0; - } else if (alpha == 1) { - return Math.exp(-(x - x0) / theta) / theta; - } - return Math.exp((alpha - 1) * Math.log((x - x0) / theta) - (x - x0) / theta - lgamma(alpha)) / theta; -} + this.logx = this.logy = 0; -/** @summary tdistribution_cdf_c function - * @memberof Math */ -function tdistribution_cdf_c(x, r, x0 = 0) { - let p = x - x0, - sign = (p > 0) ? 1. : -1; - return .5 - .5*inc_beta(p*p/(r + p*p), .5, .5*r)*sign; -} + const w = this.getFrameWidth(), h = this.getFrameHeight(), + pp = this.getPadPainter(), + pad = pp.getRootPad(); -/** @summary tdistribution_cdf function - * @memberof Math */ -function tdistribution_cdf(x, r, x0 = 0) { - let p = x - x0, - sign = (p > 0) ? 1. : -1; - return .5 + .5*inc_beta(p*p/(r + p*p), .5, .5*r)*sign; -} + this.scales_ndim = opts.ndim; -/** @summary tdistribution_pdf function - * @memberof Math */ -function tdistribution_pdf(x, r, x0 = 0) { - return (Math.exp (lgamma((r + 1.0)/2.0) - lgamma(r/2.0)) / Math.sqrt (M_PI * r)) - * Math.pow ((1.0 + (x-x0)*(x-x0)/r), -(r + 1.0)/2.0); -} + this.scale_xmin = this.xmin; + this.scale_xmax = this.xmax; -/** @summary exponential_cdf_c function - * @memberof Math */ -function exponential_cdf_c(x, lambda, x0 = 0) { - return ((x-x0) < 0) ? 1.0 : Math.exp(-lambda * (x-x0)); -} + this.scale_ymin = this.ymin; + this.scale_ymax = this.ymax; -/** @summary exponential_cdf function - * @memberof Math */ -function exponential_cdf(x, lambda, x0 = 0) { - return ((x-x0) < 0) ? 0.0 : -Math.expm1(-lambda * (x-x0)); -} + if (opts.extra_y_space) { + const log_scale = this.swap_xy ? pad.fLogx : pad.fLogy; + if (log_scale && (this.scale_ymax > 0)) + this.scale_ymax = Math.exp(Math.log(this.scale_ymax)*1.1); + else + this.scale_ymax += (this.scale_ymax - this.scale_ymin)*0.1; + } -/** @summary chisquared_pdf - * @memberof Math */ -function chisquared_pdf(x, r, x0 = 0) { - if ((x-x0) < 0) return 0.0; - const a = r/2 -1.; - // let return inf for case x = x0 and treat special case of r = 2 otherwise will return nan - if (x == x0 && a == 0) return 0.5; + if (opts.check_pad_range) { + // take zooming out of pad or axis attributes + this.applyAxisZoom('x'); + if (opts.ndim > 1) this.applyAxisZoom('y'); + if (opts.ndim > 2) this.applyAxisZoom('z'); - return Math.exp ((r/2 - 1) * Math.log((x-x0)/2) - (x-x0)/2 - lgamma(r/2))/2; -} + if (opts.check_pad_range === 'pad_range') { + const canp = this.getCanvPainter(); + // ignore range set in the online canvas + if (!canp || !canp.online_canvas) { + this.applyPadUserRange(pad, 'x'); + this.applyPadUserRange(pad, 'y'); + } + } + } -/** @summary Probability density function of the F-distribution. - * @memberof Math */ -function fdistribution_pdf(x, n, m, x0 = 0) { - if (n < 0 || m < 0) - return Number.NaN; - if ((x-x0) < 0) - return 0.0; + if ((opts.zoom_ymin !== opts.zoom_ymax) && ((this.zoom_ymin === this.zoom_ymax) || !this.zoomChangedInteractive('y'))) { + this.zoom_ymin = opts.zoom_ymin; + this.zoom_ymax = opts.zoom_ymax; + } - return Math.exp((n/2) * Math.log(n) + (m/2) * Math.log(m) + lgamma((n+m)/2) - lgamma(n/2) - lgamma(m/2) - + (n/2 -1) * Math.log(x-x0) - ((n+m)/2) * Math.log(m + n*(x-x0)) ); -} + let orig_x = true, orig_y = true; -/** @summary fdistribution_cdf_c function - * @memberof Math */ -function fdistribution_cdf_c(x, n, m, x0 = 0) { - if (n < 0 || m < 0) return Number.NaN; + if (this.zoom_xmin !== this.zoom_xmax) { + this.scale_xmin = this.zoom_xmin; + this.scale_xmax = this.zoom_xmax; + orig_x = false; + } - let z = m / (m + n * (x - x0)); - // fox z->1 and large a and b IB looses precision use complement function - if (z > 0.9 && n > 1 && m > 1) return 1. - fdistribution_cdf(x, n, m, x0); + if (this.zoom_ymin !== this.zoom_ymax) { + this.scale_ymin = this.zoom_ymin; + this.scale_ymax = this.zoom_ymax; + orig_y = false; + } - // for the complement use the fact that IB(x,a,b) = 1. - IB(1-x,b,a) - return inc_beta(m / (m + n * (x - x0)), .5 * m, .5 * n); -} + // projection should be assigned + this.recalculateRange(opts.Proj, orig_x, orig_y); -/** @summary fdistribution_cdf function - * @memberof Math */ -function fdistribution_cdf(x, n, m, x0 = 0) { - if (n < 0 || m < 0) return Number.NaN; + this.x_handle = new TAxisPainter(this.getDom(), this.xaxis, true); + this.x_handle.setPadName(this.getPadName()); + this.x_handle.setHistPainter(opts.hist_painter, 'x'); - let z = n * (x - x0) / (m + n * (x - x0)); - // fox z->1 and large a and b IB looses precision use complement function - if (z > 0.9 && n > 1 && m > 1) - return 1. - fdistribution_cdf_c(x, n, m, x0); + this.x_handle.configureAxis('xaxis', this.xmin, this.xmax, this.scale_xmin, this.scale_xmax, this.swap_xy, this.swap_xy ? [0, h] : [0, w], + { reverse: this.reverse_x, + log: this.swap_xy ? pad.fLogy : pad.fLogx, + noexp_changed: this.x_noexp_changed, + symlog: this.swap_xy ? opts.symlog_y : opts.symlog_x, + logcheckmin: this.swap_xy, + logminfactor: logminfactorX }); - return inc_beta(z, .5 * n, .5 * m); -} + this.x_handle.assignFrameMembers(this, 'x'); -/** @summary Prob function - * @memberof Math */ -function Prob(chi2, ndf) { - if (ndf <= 0) return 0; // Set CL to zero in case ndf <= 0 + this.y_handle = new TAxisPainter(this.getDom(), this.yaxis, true); + this.y_handle.setPadName(this.getPadName()); + this.y_handle.setHistPainter(opts.hist_painter, 'y'); - if (chi2 <= 0) { - if (chi2 < 0) return 0; - else return 1; - } + this.y_handle.configureAxis('yaxis', this.ymin, this.ymax, this.scale_ymin, this.scale_ymax, !this.swap_xy, this.swap_xy ? [0, w] : [0, h], + { reverse: this.reverse_y, + log: this.swap_xy ? pad.fLogx : pad.fLogy, + noexp_changed: this.y_noexp_changed, + symlog: this.swap_xy ? opts.symlog_x : opts.symlog_y, + logcheckmin: (opts.ndim < 2) || this.swap_xy, + log_min_nz: opts.ymin_nz && (opts.ymin_nz < 0.01*this.ymax) ? 0.3 * opts.ymin_nz : 0, + logminfactor: logminfactorY }); - return chisquared_cdf_c(chi2,ndf,0); -} + this.y_handle.assignFrameMembers(this, 'y'); -/** @summary Gaus function - * @memberof Math */ -function Gaus(x, mean, sigma) { - return Math.exp(-0.5 * Math.pow((x-mean) / sigma, 2)); -} + this.setRootPadRange(pad); + } -/** @summary BreitWigner function - * @memberof Math */ -function BreitWigner(x, mean, gamma) { - return gamma/((x-mean)*(x-mean) + gamma*gamma/4) / 2 / Math.PI; -} + /** @summary Create x,y objects for drawing of second axes + * @private */ + createXY2(opts) { + if (!opts) opts = { ndim: this.scales_ndim ?? 1 }; -/** @summary Calculates Beta-function Gamma(p)*Gamma(q)/Gamma(p+q). - * @memberof Math */ -function Beta(x,y) { - return Math.exp(lgamma(x) + lgamma(y) - lgamma(x+y)); -} + this.reverse_x2 = opts.reverse_x || false; + this.reverse_y2 = opts.reverse_y || false; -/** @summary GammaDist function - * @memberof Math */ -function GammaDist(x, gamma, mu = 0, beta = 1) { - if ((x < mu) || (gamma <= 0) || (beta <= 0)) return 0; - return gamma_pdf(x, gamma, beta, mu); -} + this.logx2 = this.logy2 = 0; -/** @summary probability density function of Laplace distribution - * @memberof Math */ -function LaplaceDist(x, alpha = 0, beta = 1) { - return Math.exp(-Math.abs((x-alpha)/beta)) / (2.*beta); -} + const w = this.getFrameWidth(), h = this.getFrameHeight(), + pp = this.getPadPainter(), + pad = pp.getRootPad(); -/** @summary distribution function of Laplace distribution - * @memberof Math */ -function LaplaceDistI(x, alpha = 0, beta = 1) { - return (x <= alpha) ? 0.5*Math.exp(-Math.abs((x-alpha)/beta)) : 1 - 0.5*Math.exp(-Math.abs((x-alpha)/beta)); -} + if (opts.second_x) { + this.scale_x2min = this.x2min; + this.scale_x2max = this.x2max; + } -/** @summary density function for Student's t- distribution - * @memberof Math */ -function Student(T, ndf) { - if (ndf < 1) return 0; + if (opts.second_y) { + this.scale_y2min = this.y2min; + this.scale_y2max = this.y2max; + } - let r = ndf, - rh = 0.5*r, - rh1 = rh + 0.5, - denom = Math.sqrt(r*Math.PI)*gamma(rh)*Math.pow(1+T*T/r, rh1); - return gamma(rh1)/denom; -} + if (opts.extra_y_space && opts.second_y) { + const log_scale = this.swap_xy ? pad.fLogx : pad.fLogy; + if (log_scale && (this.scale_y2max > 0)) + this.scale_y2max = Math.exp(Math.log(this.scale_y2max)*1.1); + else + this.scale_y2max += (this.scale_y2max - this.scale_y2min)*0.1; + } -/** @summary cumulative distribution function of Student's - * @memberof Math */ -function StudentI(T, ndf) { - let r = ndf; + if ((this.zoom_x2min !== this.zoom_x2max) && opts.second_x) { + this.scale_x2min = this.zoom_x2min; + this.scale_x2max = this.zoom_x2max; + } - return (T > 0) ? (1 - 0.5*BetaIncomplete((r/(r + T*T)), r*0.5, 0.5)) - : 0.5*BetaIncomplete((r/(r + T*T)), r*0.5, 0.5); -} + if ((this.zoom_y2min !== this.zoom_y2max) && opts.second_y) { + this.scale_y2min = this.zoom_y2min; + this.scale_y2max = this.zoom_y2max; + } -/** @summary LogNormal function - * @memberof Math */ -function LogNormal(x, sigma, theta = 0, m = 1) { - if ((x < theta) || (sigma <= 0) || (m <= 0)) return 0; - return lognormal_pdf(x, Math.log(m), sigma, theta); -} + if (opts.second_x) { + this.x2_handle = new TAxisPainter(this.getDom(), this.x2axis, true); + this.x2_handle.setPadName(this.getPadName()); + this.x2_handle.setHistPainter(opts.hist_painter, 'x'); -/** @summary Computes the probability density function of the Beta distribution - * @memberof Math */ -function BetaDist(x, p, q) { - if ((x < 0) || (x > 1) || (p <= 0) || (q <= 0)) - return 0; - let beta = Beta(p, q); - return Math.pow(x, p-1) * Math.pow(1-x, q-1) / beta; -} + this.x2_handle.configureAxis('x2axis', this.x2min, this.x2max, this.scale_x2min, this.scale_x2max, this.swap_xy, this.swap_xy ? [0, h] : [0, w], + { reverse: this.reverse_x2, + log: this.swap_xy ? pad.fLogy : pad.fLogx, + noexp_changed: this.x2_noexp_changed, + logcheckmin: this.swap_xy, + logminfactor: logminfactorX }); -/** @summary Computes the distribution function of the Beta distribution. - * @memberof Math */ -function BetaDistI(x, p, q) { - if ((x < 0) || (x > 1) || (p <= 0) || (q <= 0)) return 0; - return BetaIncomplete(x, p, q); -} + this.x2_handle.assignFrameMembers(this, 'x2'); + } -/** @summary gaus function for TFormula - * @memberof Math */ -function gaus(f, x, i) { - return f.GetParValue(i+0) * Math.exp(-0.5 * Math.pow((x-f.GetParValue(i+1)) / f.GetParValue(i+2), 2)); -} + if (opts.second_y) { + this.y2_handle = new TAxisPainter(this.getDom(), this.y2axis, true); + this.y2_handle.setPadName(this.getPadName()); + this.y2_handle.setHistPainter(opts.hist_painter, 'y'); -/** @summary gausn function for TFormula - * @memberof Math */ -function gausn(f, x, i) { - return gaus(f, x, i)/(Math.sqrt(2 * Math.PI) * f.GetParValue(i+2)); -} + this.y2_handle.configureAxis('y2axis', this.y2min, this.y2max, this.scale_y2min, this.scale_y2max, !this.swap_xy, this.swap_xy ? [0, w] : [0, h], + { reverse: this.reverse_y2, + log: this.swap_xy ? pad.fLogx : pad.fLogy, + noexp_changed: this.y2_noexp_changed, + logcheckmin: (opts.ndim < 2) || this.swap_xy, + log_min_nz: opts.ymin_nz && (opts.ymin_nz < 0.01*this.y2max) ? 0.3 * opts.ymin_nz : 0, + logminfactor: logminfactorY }); -/** @summary gausxy function for TFormula - * @memberof Math */ -function gausxy(f, x, y, i) { - return f.GetParValue(i+0) * Math.exp(-0.5 * Math.pow((x-f.GetParValue(i+1)) / f.GetParValue(i+2), 2)) - * Math.exp(-0.5 * Math.pow((y-f.GetParValue(i+3)) / f.GetParValue(i+4), 2)); -} + this.y2_handle.assignFrameMembers(this, 'y2'); + } + } -/** @summary expo function for TFormula - * @memberof Math */ -function expo(f, x, i) { - return Math.exp(f.GetParValue(i+0) + f.GetParValue(i+1) * x); -} + /** @summary Return functions to create x/y points based on coordinates + * @desc In default case returns frame painter itself + * @private */ + getGrFuncs(second_x, second_y) { + const use_x2 = second_x && this.grx2, + use_y2 = second_y && this.gry2; + if (!use_x2 && !use_y2) return this; -/** @summary landau function for TFormula - * @memberof Math */ -function landau(f, x, i) { - return Landau(x, f.GetParValue(i+1),f.GetParValue(i+2), false); -} + return { + use_x2, + grx: use_x2 ? this.grx2 : this.grx, + logx: this.logx, + x_handle: use_x2 ? this.x2_handle : this.x_handle, + scale_xmin: use_x2 ? this.scale_x2min : this.scale_xmin, + scale_xmax: use_x2 ? this.scale_x2max : this.scale_xmax, + use_y2, + gry: use_y2 ? this.gry2 : this.gry, + logy: this.logy, + y_handle: use_y2 ? this.y2_handle : this.y_handle, + scale_ymin: use_y2 ? this.scale_y2min : this.scale_ymin, + scale_ymax: use_y2 ? this.scale_y2max : this.scale_ymax, + swap_xy: this.swap_xy, + fp: this, + revertAxis(name, v) { + if ((name === 'x') && this.use_x2) name = 'x2'; + if ((name === 'y') && this.use_y2) name = 'y2'; + return this.fp.revertAxis(name, v); + }, + axisAsText(name, v) { + if ((name === 'x') && this.use_x2) name = 'x2'; + if ((name === 'y') && this.use_y2) name = 'y2'; + return this.fp.axisAsText(name, v); + } + }; + } -/** @summary landaun function for TFormula - * @memberof Math */ -function landaun(f, x, i) { - return Landau(x, f.GetParValue(i+1),f.GetParValue(i+2), true); -} + /** @summary Set selected range back to TPad object + * @private */ + setRootPadRange(pad, is3d) { + if (!pad || !this.ranges_set) return; -/** @summary Crystal ball function - * @memberof Math */ -function crystalball_function(x, alpha, n, sigma, mean = 0) { - if (sigma < 0.) return 0.; - let z = (x - mean)/sigma; - if (alpha < 0) z = -z; - let abs_alpha = Math.abs(alpha); - if (z > - abs_alpha) - return Math.exp(- 0.5 * z * z); - let nDivAlpha = n/abs_alpha, - AA = Math.exp(-0.5*abs_alpha*abs_alpha), - B = nDivAlpha - abs_alpha, - arg = nDivAlpha/(B-z); - return AA * Math.pow(arg,n); -} + if (is3d) { + // this is fake values, algorithm should be copied from TView3D class of ROOT + // pad.fLogx = pad.fLogy = 0; + pad.fUxmin = pad.fUymin = -0.9; + pad.fUxmax = pad.fUymax = 0.9; + } else { + pad.fLogx = this.swap_xy ? this.logy : this.logx; + pad.fUxmin = pad.fLogx ? Math.log10(this.scale_xmin) : this.scale_xmin; + pad.fUxmax = pad.fLogx ? Math.log10(this.scale_xmax) : this.scale_xmax; + pad.fLogy = this.swap_xy ? this.logx : this.logy; + pad.fUymin = pad.fLogy ? Math.log10(this.scale_ymin) : this.scale_ymin; + pad.fUymax = pad.fLogy ? Math.log10(this.scale_ymax) : this.scale_ymax; + } -/** @summary pdf definition of the crystal_ball which is defined only for n > 1 otherwise integral is diverging - * @memberof Math */ -function crystalball_pdf(x, alpha, n, sigma, mean = 0) { - if (sigma < 0.) return 0.; - if (n <= 1) return Number.NaN; // pdf is not normalized for n <=1 - let abs_alpha = Math.abs(alpha), - C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), - D = Math.sqrt(M_PI/2.)*(1.+erf(abs_alpha/Math.sqrt(2.))), - N = 1./(sigma*(C+D)); - return N * crystalball_function(x,alpha,n,sigma,mean); -} + const rx = pad.fUxmax - pad.fUxmin, + ry = pad.fUymax - pad.fUymin; + let mx = 1 - pad.fLeftMargin - pad.fRightMargin, + my = 1 - pad.fBottomMargin - pad.fTopMargin; -/** @summary compute the integral of the crystal ball function - * @memberof Math */ -function crystalball_integral(x, alpha, n, sigma, mean = 0) { - if (sigma == 0) return 0; - if (alpha == 0) return 0.; - let useLog = (n == 1.0), - z = (x-mean)/sigma; - if (alpha < 0 ) z = -z; + if (mx <= 0) mx = 0.01; // to prevent overflow + if (my <= 0) my = 0.01; - let abs_alpha = Math.abs(alpha), - intgaus = 0., intpow = 0.; + pad.fX1 = pad.fUxmin - rx/mx*pad.fLeftMargin; + pad.fX2 = pad.fUxmax + rx/mx*pad.fRightMargin; + pad.fY1 = pad.fUymin - ry/my*pad.fBottomMargin; + pad.fY2 = pad.fUymax + ry/my*pad.fTopMargin; + } - const sqrtpiover2 = Math.sqrt(M_PI/2.), - sqrt2pi = Math.sqrt( 2.*M_PI), - oneoversqrt2 = 1./Math.sqrt(2.); - if (z <= -abs_alpha) { - let A = Math.pow(n/abs_alpha,n) * Math.exp(-0.5 * alpha*alpha), - B = n/abs_alpha - abs_alpha; - if (!useLog) { - let C = (n/abs_alpha) * (1./(n-1)) * Math.exp(-alpha*alpha/2.); - intpow = C - A /(n-1.) * Math.pow(B-z,-n+1) ; - } - else { - // for n=1 the primitive of 1/x is log(x) - intpow = -A * Math.log( n / abs_alpha ) + A * Math.log( B -z ); - } - intgaus = sqrtpiover2*(1. + erf(abs_alpha*oneoversqrt2)); - } - else - { - intgaus = normal_cdf_c(z, 1); - intgaus *= sqrt2pi; - intpow = 0; - } - return sigma * (intgaus + intpow); -} + /** @summary Draw axes grids + * @desc Called immediately after axes drawing */ + drawGrids() { + const layer = this.getFrameSvg().selectChild('.axis_layer'); -/** @summary crystalball_cdf function - * @memberof Math */ -function crystalball_cdf(x, alpha, n, sigma, mean = 0) { - if (n <= 1.) - return Number.NaN; + layer.selectAll('.xgrid').remove(); + layer.selectAll('.ygrid').remove(); - let abs_alpha = Math.abs(alpha), - C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), - D = Math.sqrt(M_PI/2.)*(1. + erf(abs_alpha/Math.sqrt(2.))), - totIntegral = sigma*(C+D), - integral = crystalball_integral(x,alpha,n,sigma,mean); + const pp = this.getPadPainter(), + pad = pp?.getRootPad(true), + h = this.getFrameHeight(), + w = this.getFrameWidth(), + grid_style = gStyle.fGridStyle; - return (alpha > 0) ? 1. - integral/totIntegral : integral/totIntegral; -} + // add a grid on x axis, if the option is set + if (pad?.fGridx && this.x_handle?.ticks) { + const colid = (gStyle.fGridColor > 0) ? gStyle.fGridColor : (this.getAxis('x')?.fAxisColor ?? 1); + let gridx = ''; -/** @summary crystalball_cdf_c function - * @memberof Math */ -function crystalball_cdf_c(x, alpha, n, sigma, mean = 0) { - if (n <= 1.) - return Number.NaN; + this.x_handle.ticks.forEach(pos => { + gridx += this.swap_xy ? `M0,${pos}h${w}` : `M${pos},0v${h}`; + }); - let abs_alpha = Math.abs(alpha), - C = n/abs_alpha * 1./(n-1.) * Math.exp(-alpha*alpha/2.), - D = Math.sqrt(M_PI/2.)*(1. + erf(abs_alpha/Math.sqrt(2.))), - totIntegral = sigma*(C+D), - integral = crystalball_integral(x,alpha,n,sigma,mean); + layer.append('svg:path') + .attr('class', 'xgrid') + .attr('d', gridx) + .style('stroke', this.getColor(colid) || 'black') + .style('stroke-width', gStyle.fGridWidth) + .style('stroke-dasharray', getSvgLineStyle(grid_style)); + } - return (alpha > 0) ? integral/totIntegral : 1. - (integral/totIntegral); -} + // add a grid on y axis, if the option is set + if (pad?.fGridy && this.y_handle?.ticks) { + const colid = (gStyle.fGridColor > 0) ? gStyle.fGridColor : (this.getAxis('y')?.fAxisColor ?? 1); + let gridy = ''; -/** @summary ChebyshevN function - * @memberof Math */ -function ChebyshevN(n, x, c) { - let d1 = 0.0, d2 = 0.0, y2 = 2.0 * x; + this.y_handle.ticks.forEach(pos => { + gridy += this.swap_xy ? `M${pos},0v${h}` : `M0,${pos}h${w}`; + }); - for (let i = n; i >= 1; i--) { - let temp = d1; - d1 = y2 * d1 - d2 + c[i]; - d2 = temp; + layer.append('svg:path') + .attr('class', 'ygrid') + .attr('d', gridy) + .style('stroke', this.getColor(colid) || 'black') + .style('stroke-width', gStyle.fGridWidth) + .style('stroke-dasharray', getSvgLineStyle(grid_style)); + } } - return x * d1 - d2 + c[0]; -} - -/** @summary Chebyshev1 function - * @memberof Math */ -function Chebyshev1(x, c0, c1) { - return c0 + c1*x; -} + /** @summary Converts 'raw' axis value into text */ + axisAsText(axis, value) { + const handle = this[`${axis}_handle`]; -/** @summary Chebyshev2 function - * @memberof Math */ -function Chebyshev2(x, c0, c1, c2) { - return c0 + c1*x + c2*(2.0*x*x - 1.0); -} + if (handle) + return handle.axisAsText(value, settings[axis.toUpperCase() + 'ValuesFormat']); -/** @summary Chebyshev3 function - * @memberof Math */ -function Chebyshev3(x, ...args) { - return ChebyshevN(3, x, args); -} + return value.toPrecision(4); + } -/** @summary Chebyshev4 function - * @memberof Math */ -function Chebyshev4(x, ...args) { - return ChebyshevN(4, x, args); -} + /** @summary Identify if requested axes are drawn + * @desc Checks if x/y axes are drawn. Also if second side is already there */ + hasDrawnAxes(second_x, second_y) { + return !second_x && !second_y ? this.axes_drawn : false; + } -/** @summary Chebyshev5 function - * @memberof Math */ -function Chebyshev5(x, ...args) { - return ChebyshevN(5, x, args); -} + /** @summary draw axes, + * @return {Promise} which ready when drawing is completed */ + async drawAxes(shrink_forbidden, disable_x_draw, disable_y_draw, + AxisPos, has_x_obstacle, has_y_obstacle) { + this.cleanAxesDrawings(); -/** @summary Chebyshev6 function - * @memberof Math */ -function Chebyshev6(x, ...args) { - return ChebyshevN(6, x, args); -} + if ((this.xmin === this.xmax) || (this.ymin === this.ymax)) + return false; -/** @summary Chebyshev7 function - * @memberof Math */ -function Chebyshev7(x, ...args) { - return ChebyshevN(7, x, args); -} + if (AxisPos === undefined) AxisPos = 0; -/** @summary Chebyshev8 function - * @memberof Math */ -function Chebyshev8(x, ...args) { - return ChebyshevN(8, x, args); -} + const layer = this.getFrameSvg().selectChild('.axis_layer'), + w = this.getFrameWidth(), + h = this.getFrameHeight(), + pp = this.getPadPainter(), + pad = pp.getRootPad(true); -/** @summary Chebyshev9 function - * @memberof Math */ -function Chebyshev9(x, ...args) { - return ChebyshevN(9, x, args); -} + this.x_handle.invert_side = (AxisPos >= 10); + this.x_handle.lbls_both_sides = !this.x_handle.invert_side && (pad?.fTickx > 1); // labels on both sides + this.x_handle.has_obstacle = has_x_obstacle; -/** @summary Chebyshev10 function - * @memberof Math */ -function Chebyshev10(x, ...args) { - return ChebyshevN(10, x, args); -} + this.y_handle.invert_side = ((AxisPos % 10) === 1); + this.y_handle.lbls_both_sides = !this.y_handle.invert_side && (pad?.fTicky > 1); // labels on both sides + this.y_handle.has_obstacle = has_y_obstacle; -// ========================================================================= + const draw_horiz = this.swap_xy ? this.y_handle : this.x_handle, + draw_vertical = this.swap_xy ? this.x_handle : this.y_handle; -/** @summary Caluclate ClopperPearson - * @memberof Math */ -function eff_ClopperPearson(total,passed,level,bUpper) { - let alpha = (1.0 - level) / 2; - if(bUpper) - return ((passed == total) ? 1.0 : beta_quantile(1 - alpha,passed + 1,total-passed)); + if ((!disable_x_draw || !disable_y_draw) && pp._fast_drawing) + disable_x_draw = disable_y_draw = true; - return ((passed == 0) ? 0.0 : beta_quantile(alpha,passed,total-passed+1.0)); -} + let pr = Promise.resolve(true); -/** @summary Caluclate normal - * @memberof Math */ -function eff_Normal(total,passed,level,bUpper) { - if (total == 0) return bUpper ? 1 : 0; + if (!disable_x_draw || !disable_y_draw) { + const can_adjust_frame = !shrink_forbidden && settings.CanAdjustFrame, - let alpha = (1.0 - level)/2, - average = passed / total, - sigma = Math.sqrt(average * (1 - average) / total), - delta = normal_quantile(1 - alpha, sigma); + pr1 = draw_horiz.drawAxis(layer, w, h, + draw_horiz.invert_side ? null : `translate(0,${h})`, + pad?.fTickx ? -h : 0, disable_x_draw, + undefined, false, pp.getPadHeight() - h - this.getFrameY()), - if(bUpper) - return ((average + delta) > 1) ? 1.0 : (average + delta); + pr2 = draw_vertical.drawAxis(layer, w, h, + draw_vertical.invert_side ? `translate(${w})` : null, + pad?.fTicky ? w : 0, disable_y_draw, + draw_vertical.invert_side ? 0 : this._frame_x, can_adjust_frame); - return ((average - delta) < 0) ? 0.0 : (average - delta); -} + pr = Promise.all([pr1, pr2]).then(() => { + this.drawGrids(); -/** @summary Calculates the boundaries for the frequentist Wilson interval - * @memberof Math */ -function eff_Wilson(total,passed,level,bUpper) { - let alpha = (1.0 - level)/2; - if (total == 0) return bUpper ? 1 : 0; - let average = passed / total, - kappa = normal_quantile(1 - alpha,1), - mode = (passed + 0.5 * kappa * kappa) / (total + kappa * kappa), - delta = kappa / (total + kappa*kappa) * Math.sqrt(total * average * (1 - average) + kappa * kappa / 4); + if (!can_adjust_frame) return; - if(bUpper) - return ((mode + delta) > 1) ? 1.0 : (mode + delta); + let shrink = 0.0; + const ypos = draw_vertical.position; - return ((mode - delta) < 0) ? 0.0 : (mode - delta); -} + if ((-0.2 * w < ypos) && (ypos < 0)) { + shrink = -ypos / w + 0.001; + this.shrink_frame_left += shrink; + } else if ((ypos > 0) && (ypos < 0.3 * w) && (this.shrink_frame_left > 0) && (ypos / w > this.shrink_frame_left)) { + shrink = -this.shrink_frame_left; + this.shrink_frame_left = 0.0; + } -/** @summary Calculates the boundaries for the frequentist Agresti-Coull interval - * @memberof Math */ -function eff_AgrestiCoull(total,passed,level,bUpper) { - let alpha = (1.0 - level)/2, - kappa = normal_quantile(1 - alpha,1), - mode = (passed + 0.5 * kappa * kappa) / (total + kappa * kappa), - delta = kappa * Math.sqrt(mode * (1 - mode) / (total + kappa * kappa)); + if (!shrink) return; - if(bUpper) - return ((mode + delta) > 1) ? 1.0 : (mode + delta); + this.shrinkFrame(shrink, 0); + return this.redraw().then(() => this.drawAxes(true)); + }); + } - return ((mode - delta) < 0) ? 0.0 : (mode - delta); -} + return pr.then(() => { + if (!shrink_forbidden) + this.axes_drawn = true; + return true; + }); + } -/** @summary Calculates the boundaries using the mid-P binomial - * @memberof Math */ -function eff_MidPInterval(total,passed,level,bUpper) { - const alpha = 1. - level, alpha_min = alpha/2 , tol = 1e-9; // tolerance - let pmin = 0, pmax = 1, p = 0; + /** @summary draw second axes (if any) */ + drawAxes2(second_x, second_y) { + const layer = this.getFrameSvg().selectChild('.axis_layer'), + w = this.getFrameWidth(), + h = this.getFrameHeight(), + pp = this.getPadPainter(), + pad = pp.getRootPad(true); - // treat special case for 0 0 && passed < 1) { - let p0 = eff_MidPInterval(total,0.0,level,bUpper); - let p1 = eff_MidPInterval(total,1.0,level,bUpper); - p = (p1 - p0) * passed + p0; - return p; - } + if (second_x) { + this.x2_handle.invert_side = true; + this.x2_handle.lbls_both_sides = false; + this.x2_handle.has_obstacle = false; + } - while (Math.abs(pmax - pmin) > tol) { - p = (pmin + pmax)/2; - //double v = 0.5 * ROOT::Math::binomial_pdf(int(passed), p, int(total)); - // make it work for non integer using the binomial - beta relationship - let v = 0.5 * beta_pdf(p, passed+1., total-passed+1)/(total+1); - //if (passed > 0) v += ROOT::Math::binomial_cdf(int(passed - 1), p, int(total)); - // compute the binomial cdf at passed -1 - if ( (passed-1) >= 0) v += beta_cdf_c(p, passed, total-passed+1); + if (second_y) { + this.y2_handle.invert_side = true; + this.y2_handle.lbls_both_sides = false; + } - let vmin = bUpper ? alpha_min : 1.- alpha_min; - if (v > vmin) - pmin = p; - else - pmax = p; - } + let draw_horiz = this.swap_xy ? this.y2_handle : this.x2_handle, + draw_vertical = this.swap_xy ? this.x2_handle : this.y2_handle; - return p; -} + if ((draw_horiz || draw_vertical) && pp._fast_drawing) + draw_horiz = draw_vertical = null; -/** @summary for a central confidence interval for a Beta distribution - * @memberof Math */ -function eff_Bayesian(total,passed,level,bUpper,alpha,beta) { - let a = passed + alpha, - b = total - passed + beta; - if(bUpper) { - if((a > 0) && (b > 0)) - return beta_quantile((1+level)/2,a,b); - else - return 1; - } else { - if((a > 0) && (b > 0)) - return beta_quantile((1-level)/2,a,b); - else - return 0; - } -} + let pr1, pr2; -/** @summary Return function to calculate boundary of TEfficiency - * @memberof Math */ -function getTEfficiencyBoundaryFunc(option, isbayessian) { - const kFCP = 0, ///< Clopper-Pearson interval (recommended by PDG) - kFNormal = 1, ///< Normal approximation - kFWilson = 2, ///< Wilson interval - kFAC = 3, ///< Agresti-Coull interval - kFFC = 4, ///< Feldman-Cousins interval, too complicated for JavaScript - // kBJeffrey = 5, ///< Jeffrey interval (Prior ~ Beta(0.5,0.5) - // kBUniform = 6, ///< Prior ~ Uniform = Beta(1,1) - // kBBayesian = 7, ///< User specified Prior ~ Beta(fBeta_alpha,fBeta_beta) - kMidP = 8; ///< Mid-P Lancaster interval + if (draw_horiz) { + pr1 = draw_horiz.drawAxis(layer, w, h, + draw_horiz.invert_side ? null : `translate(0,${h})`, + pad?.fTickx ? -h : 0, false, + undefined, false); + } - if (isbayessian) - return eff_Bayesian; + if (draw_vertical) { + pr2 = draw_vertical.drawAxis(layer, w, h, + draw_vertical.invert_side ? `translate(${w})` : null, + pad?.fTicky ? w : 0, false, + draw_vertical.invert_side ? 0 : this._frame_x, false); + } - switch (option) { - case kFCP: return eff_ClopperPearson; - case kFNormal: return eff_Normal; - case kFWilson: return eff_Wilson; - case kFAC: return eff_AgrestiCoull; - case kFFC: console.log('Feldman-Cousins interval kFFC not supported; using kFCP'); return eff_ClopperPearson; - case kMidP: return eff_MidPInterval; - // case kBJeffrey: - // case kBUniform: - // case kBBayesian: return eff_ClopperPearson; + return Promise.all([pr1, pr2]); } - console.log(`Not recognized stat option ${option}, using kFCP`); - return eff_ClopperPearson; -} -var jsroot_math = /*#__PURE__*/Object.freeze({ -__proto__: null, -gamma: gamma, -tgamma: gamma, -Gamma: gamma, -Polynomialeval: Polynomialeval, -Polynomial1eval: Polynomial1eval, -stirf: stirf, -gamma_pdf: gamma_pdf, -ndtri: ndtri, -normal_quantile: normal_quantile, -normal_quantile_c: normal_quantile_c, -lognormal_cdf_c: lognormal_cdf_c, -lognormal_cdf: lognormal_cdf, -igami: igami, -igamc: igamc, -igam: igam, -lgam: lgam, -lgamma: lgamma, -erfc: erfc, -erf: erf, -beta_pdf: beta_pdf, -inc_beta: inc_beta, -BetaIncomplete: BetaIncomplete, -pseries: pseries, -incbet: incbet, -incbi: incbi, -beta_quantile: beta_quantile, -chisquared_cdf_c: chisquared_cdf_c, -beta: beta, -inc_gamma: inc_gamma, -inc_gamma_c: inc_gamma_c, -landau_pdf: landau_pdf, -beta_cdf_c: beta_cdf_c, -Landau: Landau, -fdistribution_pdf: fdistribution_pdf, -FDist: fdistribution_pdf, -fdistribution_cdf: fdistribution_cdf, -FDistI: fdistribution_cdf, -fdistribution_cdf_c: fdistribution_cdf_c, -normal_cdf_c: normal_cdf_c, -gaussian_cdf_c: normal_cdf_c, -normal_cdf: normal_cdf, -gaussian_cdf: normal_cdf, -lognormal_pdf: lognormal_pdf, -normal_pdf: normal_pdf, -crystalball_function: crystalball_function, -crystalball_pdf: crystalball_pdf, -crystalball_cdf: crystalball_cdf, -crystalball_cdf_c: crystalball_cdf_c, -chisquared_cdf: chisquared_cdf, -gamma_quantile_c: gamma_quantile_c, -gamma_quantile: gamma_quantile, -breitwigner_cdf_c: breitwigner_cdf_c, -breitwigner_cdf: breitwigner_cdf, -cauchy_cdf_c: cauchy_cdf_c, -cauchy_cdf: cauchy_cdf, -cauchy_pdf: cauchy_pdf, -gaussian_pdf: gaussian_pdf, -tdistribution_cdf_c: tdistribution_cdf_c, -tdistribution_cdf: tdistribution_cdf, -tdistribution_pdf: tdistribution_pdf, -exponential_cdf_c: exponential_cdf_c, -exponential_cdf: exponential_cdf, -chisquared_pdf: chisquared_pdf, -Beta: Beta, -GammaDist: GammaDist, -LaplaceDist: LaplaceDist, -LaplaceDistI: LaplaceDistI, -LogNormal: LogNormal, -Student: Student, -StudentI: StudentI, -gaus: gaus, -gausn: gausn, -gausxy: gausxy, -expo: expo, -Prob: Prob, -Gaus: Gaus, -BreitWigner: BreitWigner, -BetaDist: BetaDist, -BetaDistI: BetaDistI, -landau: landau, -landaun: landaun, -ChebyshevN: ChebyshevN, -Chebyshev1: Chebyshev1, -Chebyshev2: Chebyshev2, -Chebyshev3: Chebyshev3, -Chebyshev4: Chebyshev4, -Chebyshev5: Chebyshev5, -Chebyshev6: Chebyshev6, -Chebyshev7: Chebyshev7, -Chebyshev8: Chebyshev8, -Chebyshev9: Chebyshev9, -Chebyshev10: Chebyshev10, -getTEfficiencyBoundaryFunc: getTEfficiencyBoundaryFunc -}); -/** @summary Display progress message in the left bottom corner. - * @desc Previous message will be overwritten - * if no argument specified, any shown messages will be removed - * @param {string} msg - message to display - * @param {number} tmout - optional timeout in milliseconds, after message will disappear - * @private */ -function showProgress(msg, tmout) { - if (isBatchMode() || (typeof document === 'undefined')) return; - let id = 'jsroot_progressbox', - box = select('#' + id); + /** @summary Update frame attributes + * @private */ + updateAttributes(force) { + const pp = this.getPadPainter(), + pad = pp?.getRootPad(true), + tframe = this.getObject(); - if (!settings.ProgressBox) - return box.remove(); + if ((this.fX1NDC === undefined) || (force && !this.modified_NDC)) { + if (!pad) { + this.fX1NDC = gStyle.fPadLeftMargin; + this.fX2NDC = 1 - gStyle.fPadRightMargin; + this.fY1NDC = gStyle.fPadBottomMargin; + this.fY2NDC = 1 - gStyle.fPadTopMargin; + } else { + this.fX1NDC = pad.fLeftMargin; + this.fX2NDC = 1 - pad.fRightMargin; + this.fY1NDC = pad.fBottomMargin; + this.fY2NDC = 1 - pad.fTopMargin; + } + } - if ((arguments.length == 0) || !msg) { - if ((tmout !== -1) || (!box.empty() && box.property('with_timeout'))) box.remove(); - return; - } + if (this.fillatt === undefined) { + if (tframe) + this.createAttFill({ attr: tframe }); + else if (pad?.fFrameFillColor) + this.createAttFill({ pattern: pad.fFrameFillStyle, color: pad.fFrameFillColor }); + else if (pad) + this.createAttFill({ attr: pad }); + else + this.createAttFill({ pattern: 1001, color: 0 }); - if (box.empty()) { - box = select(document.body) - .append('div').attr('id', id) - .attr('style', 'position: fixed; min-width: 100px; height: auto; overflow: visible; z-index: 101; border: 1px solid #999; background: #F8F8F8; left: 10px; bottom: 10px;'); - box.append('p'); + // force white color for the canvas frame + if (!tframe && this.fillatt.empty() && pp?.iscan) + this.fillatt.setSolidColor('white'); + else if ((pad?.fFillStyle === 4000) && !this.fillatt.empty()) // special case of transpad.C macro, which set transparent pad + this.fillatt.setOpacity(0); + } + + if (!tframe && (pad?.fFrameLineColor !== undefined)) + this.createAttLine({ color: pad.fFrameLineColor, width: pad.fFrameLineWidth, style: pad.fFrameLineStyle }); + else + this.createAttLine({ attr: tframe, color: 'black' }); } - box.property('with_timeout', false); + /** @summary Function called at the end of resize of frame + * @desc One should apply changes to the pad + * @private */ + sizeChanged() { + const pad = this.getPadPainter()?.getRootPad(true); - if (isStr(msg)) { - box.select('p').html(msg); - } else { - box.html(''); - box.node().appendChild(msg); - } - injectStyle('#jsroot_progressbox p { font-size: 10px; margin-left: 10px; margin-right: 10px; margin-top: 3px; margin-bottom: 3px; }', box.node()); + if (pad) { + pad.fLeftMargin = this.fX1NDC; + pad.fRightMargin = 1 - this.fX2NDC; + pad.fBottomMargin = this.fY1NDC; + pad.fTopMargin = 1 - this.fY2NDC; + this.setRootPadRange(pad); + } - if (Number.isFinite(tmout) && (tmout > 0)) { - box.property('with_timeout', true); - setTimeout(() => showProgress('', -1), tmout); + this.interactiveRedraw('pad', 'frame'); } -} -/** @summary Tries to close current browser tab - * @desc Many browsers do not allow simple window.close() call, - * therefore try several workarounds - * @private */ -function closeCurrentWindow() { - if (!window) return; - window.close(); - window.open('', '_self').close(); -} + /** @summary Remove all kinds of X/Y function for axes transformation */ + cleanXY() { + delete this.grx; + delete this.gry; + delete this.grz; + delete this.grx2; + delete this.gry2; + this.x_handle?.cleanup(); + this.y_handle?.cleanup(); + this.z_handle?.cleanup(); + this.x2_handle?.cleanup(); + this.y2_handle?.cleanup(); -function tryOpenOpenUI(sources, args) { - if (!sources || (sources.length == 0)) { - if (args.rejectFunc) { - args.rejectFunc(Error('openui5 was not possible to load')); - args.rejectFunc = null; - } - return; + delete this.x_handle; + delete this.y_handle; + delete this.z_handle; + delete this.x2_handle; + delete this.y2_handle; } - // where to take openui5 sources - let src = sources.shift(); - - if ((src.indexOf('roothandler') == 0) && (src.indexOf('://') < 0)) - src = src.replace(/\:\//g, '://'); + /** @summary remove all axes drawings */ + cleanAxesDrawings() { + this.x_handle?.removeG(); + this.y_handle?.removeG(); + this.z_handle?.removeG(); + this.x2_handle?.removeG(); + this.y2_handle?.removeG(); - let element = document.createElement('script'); - element.setAttribute('type', 'text/javascript'); - element.setAttribute('id', 'sap-ui-bootstrap'); - // use nojQuery while we are already load jquery and jquery-ui, later one can use directly sap-ui-core.js + this.draw_g?.selectChild('.axis_layer').selectAll('*').remove(); + this.axes_drawn = false; + } - // this is location of openui5 scripts when working with THttpServer or when scripts are installed inside JSROOT - element.setAttribute('src', src + 'resources/sap-ui-core.js'); // latest openui5 version + /** @summary Returns frame rectangle plus extra info for hint display */ + cleanFrameDrawings() { + // cleanup all 3D drawings if any + if (isFunc(this.create3DScene)) + this.create3DScene(-1); - element.setAttribute('data-sap-ui-libs', args.openui5libs ?? 'sap.m, sap.ui.layout, sap.ui.unified, sap.ui.commons'); + this.cleanAxesDrawings(); + this.cleanXY(); - element.setAttribute('data-sap-ui-theme', args.openui5theme || 'sap_belize'); - element.setAttribute('data-sap-ui-compatVersion', 'edge'); - // element.setAttribute('data-sap-ui-bindingSyntax', 'complex'); + this.ranges_set = false; - element.setAttribute('data-sap-ui-preload', 'async'); // '' to disable Component-preload.js + this.xmin = this.xmax = 0; + this.ymin = this.ymax = 0; + this.zmin = this.zmax = 0; - element.setAttribute('data-sap-ui-evt-oninit', 'completeUI5Loading()'); + this.zoom_xmin = this.zoom_xmax = 0; + this.zoom_ymin = this.zoom_ymax = 0; + this.zoom_zmin = this.zoom_zmax = 0; - element.onerror = function() { - // remove failed element - element.parentNode.removeChild(element); - // and try next - tryOpenOpenUI(sources, args); - }; + this.scale_xmin = this.scale_xmax = 0; + this.scale_ymin = this.scale_ymax = 0; + this.scale_zmin = this.scale_zmax = 0; - element.onload = function() { - console.log(`Load openui5 from ${src}`); - }; + this.draw_g?.selectChild('.main_layer').selectAll('*').remove(); + this.draw_g?.selectChild('.upper_layer').selectAll('*').remove(); - document.head.appendChild(element); -} + this.xaxis = null; + this.yaxis = null; + this.zaxis = null; + if (this.draw_g) { + this.draw_g.selectAll('*').remove(); + this.draw_g.on('mousedown', null) + .on('dblclick', null) + .on('wheel', null) + .on('contextmenu', null) + .property('interactive_set', null); + this.draw_g.remove(); + } -// return Promise let loader wait before dependent source will be invoked + delete this.draw_g; // frame element managet by the pad -async function loadOpenui5(args) { - // very simple - openui5 was loaded before and will be used as is - if (typeof sap == 'object') - return sap; + if (this.keys_handler) { + window.removeEventListener('keydown', this.keys_handler, false); + this.keys_handler = null; + } + } - if (!args) args = {}; + /** @summary Cleanup frame */ + cleanup() { + this.cleanFrameDrawings(); + delete this._click_handler; + delete this._dblclick_handler; + delete this.enabledKeys; - let rootui5sys = exports.source_dir.replace(/jsrootsys/g, 'rootui5sys'); + const pp = this.getPadPainter(); + if (pp?.frame_painter_ref === this) + delete pp.frame_painter_ref; - if (rootui5sys == exports.source_dir) { - // if jsrootsys location not detected, try to guess it - if (window.location.port && (window.location.pathname.indexOf('/win') >= 0) && (!args.openui5src || args.openui5src == 'nojsroot' || args.openui5src == 'jsroot')) - rootui5sys = window.location.origin + window.location.pathname + '../rootui5sys/'; - else - rootui5sys = undefined; + super.cleanup(); } - let openui5_sources = [], - openui5_dflt = 'https://openui5.hana.ondemand.com/1.98.0/', - openui5_root = rootui5sys ? rootui5sys + 'distribution/' : ''; + /** @summary Redraw TFrame */ + redraw(/* reason */) { + const pp = this.getPadPainter(); + if (pp) pp.frame_painter_ref = this; // keep direct reference to the frame painter - if (isStr(args.openui5src)) { - switch (args.openui5src) { - case 'nodefault': openui5_dflt = ''; break; - case 'default': openui5_sources.push(openui5_dflt); openui5_dflt = ''; break; - case 'nojsroot': /* openui5_root = ''; */ break; - case 'jsroot': openui5_sources.push(openui5_root); openui5_root = ''; break; - default: openui5_sources.push(args.openui5src); break; - } - } + // first update all attributes from objects + this.updateAttributes(); - if (openui5_root && (openui5_sources.indexOf(openui5_root) < 0)) openui5_sources.push(openui5_root); - if (openui5_dflt && (openui5_sources.indexOf(openui5_dflt) < 0)) openui5_sources.push(openui5_dflt); + const rect = pp?.getPadRect() ?? { width: 10, height: 10 }, + lm = Math.round(rect.width * this.fX1NDC), + tm = Math.round(rect.height * (1 - this.fY2NDC)); + let w = Math.round(rect.width * (this.fX2NDC - this.fX1NDC)), + h = Math.round(rect.height * (this.fY2NDC - this.fY1NDC)), + rotate = false, fixpos = false, trans; - return new Promise((resolve, reject) => { + if (pp?.options) { + if (pp.options.RotateFrame) rotate = true; + if (pp.options.FixFrame) fixpos = true; + } - args.resolveFunc = resolve; - args.rejectFunc = reject; + if (rotate) { + trans = `rotate(-90,${lm},${tm}) translate(${lm-h},${tm})`; + [w, h] = [h, w]; + } else + trans = makeTranslate(lm, tm); - globalThis.completeUI5Loading = function() { - sap.ui.loader.config({ - paths: { - jsroot: exports.source_dir, - rootui5: rootui5sys - } - }); + this._frame_x = lm; + this._frame_y = tm; + this._frame_width = w; + this._frame_height = h; + this._frame_rotate = rotate; + this._frame_fixpos = fixpos; - if (args.resolveFunc) { - args.resolveFunc(sap); - args.resolveFunc = null; - } - }; + if (this.mode3d) return this; // no need to create any elements in 3d mode - tryOpenOpenUI(openui5_sources, args); - }); + // this is svg:g object - container for every other items belonging to frame + this.draw_g = this.getFrameSvg(); -} + let top_rect, main_svg; -// some icons taken from http://uxrepo.com/ -const ToolbarIcons = { - camera: { path: 'M 152.00,304.00c0.00,57.438, 46.562,104.00, 104.00,104.00s 104.00-46.562, 104.00-104.00s-46.562-104.00-104.00-104.00S 152.00,246.562, 152.00,304.00z M 480.00,128.00L 368.00,128.00 c-8.00-32.00-16.00-64.00-48.00-64.00L 192.00,64.00 c-32.00,0.00-40.00,32.00-48.00,64.00L 32.00,128.00 c-17.60,0.00-32.00,14.40-32.00,32.00l0.00,288.00 c0.00,17.60, 14.40,32.00, 32.00,32.00l 448.00,0.00 c 17.60,0.00, 32.00-14.40, 32.00-32.00L 512.00,160.00 C 512.00,142.40, 497.60,128.00, 480.00,128.00z M 256.00,446.00c-78.425,0.00-142.00-63.574-142.00-142.00c0.00-78.425, 63.575-142.00, 142.00-142.00c 78.426,0.00, 142.00,63.575, 142.00,142.00 C 398.00,382.426, 334.427,446.00, 256.00,446.00z M 480.00,224.00l-64.00,0.00 l0.00-32.00 l 64.00,0.00 L 480.00,224.00 z' }, - disk: { path: 'M384,0H128H32C14.336,0,0,14.336,0,32v448c0,17.656,14.336,32,32,32h448c17.656,0,32-14.344,32-32V96L416,0H384z M352,160 V32h32v128c0,17.664-14.344,32-32,32H160c-17.664,0-32-14.336-32-32V32h128v128H352z M96,288c0-17.656,14.336-32,32-32h256 c17.656,0,32,14.344,32,32v192H96V288z' }, - question: { path: 'M256,512c141.375,0,256-114.625,256-256S397.375,0,256,0S0,114.625,0,256S114.625,512,256,512z M256,64 c63.719,0,128,36.484,128,118.016c0,47.453-23.531,84.516-69.891,110.016C300.672,299.422,288,314.047,288,320 c0,17.656-14.344,32-32,32c-17.664,0-32-14.344-32-32c0-40.609,37.25-71.938,59.266-84.031 C315.625,218.109,320,198.656,320,182.016C320,135.008,279.906,128,256,128c-30.812,0-64,20.227-64,64.672 c0,17.664-14.336,32-32,32s-32-14.336-32-32C128,109.086,193.953,64,256,64z M256,449.406c-18.211,0-32.961-14.75-32.961-32.969 c0-18.188,14.75-32.953,32.961-32.953c18.219,0,32.969,14.766,32.969,32.953C288.969,434.656,274.219,449.406,256,449.406z' }, - undo: { path: 'M450.159,48.042c8.791,9.032,16.983,18.898,24.59,29.604c7.594,10.706,14.146,22.207,19.668,34.489 c5.509,12.296,9.82,25.269,12.92,38.938c3.113,13.669,4.663,27.834,4.663,42.499c0,14.256-1.511,28.863-4.532,43.822 c-3.009,14.952-7.997,30.217-14.953,45.795c-6.955,15.577-16.202,31.52-27.755,47.826s-25.88,32.9-42.942,49.807 c-5.51,5.444-11.787,11.67-18.834,18.651c-7.033,6.98-14.496,14.366-22.39,22.168c-7.88,7.802-15.955,15.825-24.187,24.069 c-8.258,8.231-16.333,16.203-24.252,23.888c-18.3,18.13-37.354,37.016-57.191,56.65l-56.84-57.445 c19.596-19.472,38.54-38.279,56.84-56.41c7.75-7.685,15.772-15.604,24.108-23.757s16.438-16.163,24.33-24.057 c7.894-7.893,15.356-15.33,22.402-22.312c7.034-6.98,13.312-13.193,18.821-18.651c22.351-22.402,39.165-44.648,50.471-66.738 c11.279-22.09,16.932-43.567,16.932-64.446c0-15.785-3.217-31.005-9.638-45.671c-6.422-14.665-16.229-28.504-29.437-41.529 c-3.282-3.282-7.358-6.395-12.217-9.325c-4.871-2.938-10.381-5.503-16.516-7.697c-6.121-2.201-12.815-3.992-20.058-5.373 c-7.242-1.374-14.9-2.064-23.002-2.064c-8.218,0-16.802,0.834-25.788,2.507c-8.961,1.674-18.053,4.429-27.222,8.271 c-9.189,3.842-18.456,8.869-27.808,15.089c-9.358,6.219-18.521,13.819-27.502,22.793l-59.92,60.271l93.797,94.058H0V40.91 l93.27,91.597l60.181-60.532c13.376-15.018,27.222-27.248,41.536-36.697c14.308-9.443,28.608-16.776,42.89-21.992 c14.288-5.223,28.505-8.74,42.623-10.557C294.645,0.905,308.189,0,321.162,0c13.429,0,26.389,1.185,38.84,3.562 c12.478,2.377,24.2,5.718,35.192,10.029c11.006,4.311,21.126,9.404,30.374,15.265C434.79,34.724,442.995,41.119,450.159,48.042z' }, - arrow_right: { path: 'M30.796,226.318h377.533L294.938,339.682c-11.899,11.906-11.899,31.184,0,43.084c11.887,11.899,31.19,11.893,43.077,0 l165.393-165.386c5.725-5.712,8.924-13.453,8.924-21.539c0-8.092-3.213-15.84-8.924-21.551L338.016,8.925 C332.065,2.975,324.278,0,316.478,0c-7.802,0-15.603,2.968-21.539,8.918c-11.899,11.906-11.899,31.184,0,43.084l113.391,113.384 H30.796c-16.822,0-30.463,13.645-30.463,30.463C0.333,212.674,13.974,226.318,30.796,226.318z' }, - arrow_up: { path: 'M295.505,629.446V135.957l148.193,148.206c15.555,15.559,40.753,15.559,56.308,0c15.555-15.538,15.546-40.767,0-56.304 L283.83,11.662C276.372,4.204,266.236,0,255.68,0c-10.568,0-20.705,4.204-28.172,11.662L11.333,227.859 c-7.777,7.777-11.666,17.965-11.666,28.158c0,10.192,3.88,20.385,11.657,28.158c15.563,15.555,40.762,15.555,56.317,0 l148.201-148.219v493.489c0,21.993,17.837,39.82,39.82,39.82C277.669,669.267,295.505,651.439,295.505,629.446z' }, - arrow_diag: { path: 'M279.875,511.994c-1.292,0-2.607-0.102-3.924-0.312c-10.944-1.771-19.333-10.676-20.457-21.71L233.97,278.348 L22.345,256.823c-11.029-1.119-19.928-9.51-21.698-20.461c-1.776-10.944,4.031-21.716,14.145-26.262L477.792,2.149 c9.282-4.163,20.167-2.165,27.355,5.024c7.201,7.189,9.199,18.086,5.024,27.356L302.22,497.527 C298.224,506.426,289.397,511.994,279.875,511.994z M118.277,217.332l140.534,14.294c11.567,1.178,20.718,10.335,21.878,21.896 l14.294,140.519l144.09-320.792L118.277,217.332z' }, - auto_zoom: { path: 'M505.441,242.47l-78.303-78.291c-9.18-9.177-24.048-9.171-33.216,0c-9.169,9.172-9.169,24.045,0.006,33.217l38.193,38.188 H280.088V80.194l38.188,38.199c4.587,4.584,10.596,6.881,16.605,6.881c6.003,0,12.018-2.297,16.605-6.875 c9.174-9.172,9.174-24.039,0.011-33.217L273.219,6.881C268.803,2.471,262.834,0,256.596,0c-6.229,0-12.202,2.471-16.605,6.881 l-78.296,78.302c-9.178,9.172-9.178,24.045,0,33.217c9.177,9.171,24.051,9.171,33.21,0l38.205-38.205v155.4H80.521l38.2-38.188 c9.177-9.171,9.177-24.039,0.005-33.216c-9.171-9.172-24.039-9.178-33.216,0L7.208,242.464c-4.404,4.403-6.881,10.381-6.881,16.611 c0,6.227,2.477,12.207,6.881,16.61l78.302,78.291c4.587,4.581,10.599,6.875,16.605,6.875c6.006,0,12.023-2.294,16.61-6.881 c9.172-9.174,9.172-24.036-0.005-33.211l-38.205-38.199h152.593v152.063l-38.199-38.211c-9.171-9.18-24.039-9.18-33.216-0.022 c-9.178,9.18-9.178,24.059-0.006,33.222l78.284,78.302c4.41,4.404,10.382,6.881,16.611,6.881c6.233,0,12.208-2.477,16.611-6.881 l78.302-78.296c9.181-9.18,9.181-24.048,0-33.205c-9.174-9.174-24.054-9.174-33.21,0l-38.199,38.188v-152.04h152.051l-38.205,38.199 c-9.18,9.175-9.18,24.037-0.005,33.211c4.587,4.587,10.596,6.881,16.604,6.881c6.01,0,12.024-2.294,16.605-6.875l78.303-78.285 c4.403-4.403,6.887-10.378,6.887-16.611C512.328,252.851,509.845,246.873,505.441,242.47z' }, - statbox: { - path: 'M28.782,56.902H483.88c15.707,0,28.451-12.74,28.451-28.451C512.331,12.741,499.599,0,483.885,0H28.782 C13.074,0,0.331,12.741,0.331,28.451C0.331,44.162,13.074,56.902,28.782,56.902z' + - 'M483.885,136.845H28.782c-15.708,0-28.451,12.741-28.451,28.451c0,15.711,12.744,28.451,28.451,28.451H483.88 c15.707,0,28.451-12.74,28.451-28.451C512.331,149.586,499.599,136.845,483.885,136.845z' + - 'M483.885,273.275H28.782c-15.708,0-28.451,12.731-28.451,28.452c0,15.707,12.744,28.451,28.451,28.451H483.88 c15.707,0,28.451-12.744,28.451-28.451C512.337,286.007,499.599,273.275,483.885,273.275z' + - 'M256.065,409.704H30.492c-15.708,0-28.451,12.731-28.451,28.451c0,15.707,12.744,28.451,28.451,28.451h225.585 c15.707,0,28.451-12.744,28.451-28.451C284.516,422.436,271.785,409.704,256.065,409.704z' - }, - circle: { path: 'M256,256 m-150,0 a150,150 0 1,0 300,0 a150,150 0 1,0 -300,0' }, - three_circles: { path: 'M256,85 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 M256,255 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 M256,425 m-70,0 a70,70 0 1,0 140,0 a70,70 0 1,0 -140,0 ' }, - diamand: { path: 'M256,0L384,256L256,511L128,256z' }, - rect: { path: 'M80,80h352v352h-352z' }, - cross: { path: 'M80,40l176,176l176,-176l40,40l-176,176l176,176l-40,40l-176,-176l-176,176l-40,-40l176,-176l-176,-176z' }, - vrgoggles: { size: '245.82 141.73', path: 'M175.56,111.37c-22.52,0-40.77-18.84-40.77-42.07S153,27.24,175.56,27.24s40.77,18.84,40.77,42.07S198.08,111.37,175.56,111.37ZM26.84,69.31c0-23.23,18.25-42.07,40.77-42.07s40.77,18.84,40.77,42.07-18.26,42.07-40.77,42.07S26.84,92.54,26.84,69.31ZM27.27,0C11.54,0,0,12.34,0,28.58V110.9c0,16.24,11.54,30.83,27.27,30.83H99.57c2.17,0,4.19-1.83,5.4-3.7L116.47,118a8,8,0,0,1,12.52-.18l11.51,20.34c1.2,1.86,3.22,3.61,5.39,3.61h72.29c15.74,0,27.63-14.6,27.63-30.83V28.58C245.82,12.34,233.93,0,218.19,0H27.27Z' }, - th2colorz: { recs: [{ x: 128, y: 486, w: 256, h: 26, f: 'rgb(38,62,168)' }, { y: 461, f: 'rgb(22,82,205)' }, { y: 435, f: 'rgb(16,100,220)' }, { y: 410, f: 'rgb(18,114,217)' }, { y: 384, f: 'rgb(20,129,214)' }, { y: 358, f: 'rgb(14,143,209)' }, { y: 333, f: 'rgb(9,157,204)' }, { y: 307, f: 'rgb(13,167,195)' }, { y: 282, f: 'rgb(30,175,179)' }, { y: 256, f: 'rgb(46,183,164)' }, { y: 230, f: 'rgb(82,186,146)' }, { y: 205, f: 'rgb(116,189,129)' }, { y: 179, f: 'rgb(149,190,113)' }, { y: 154, f: 'rgb(179,189,101)' }, { y: 128, f: 'rgb(209,187,89)' }, { y: 102, f: 'rgb(226,192,75)' }, { y: 77, f: 'rgb(244,198,59)' }, { y: 51, f: 'rgb(253,210,43)' }, { y: 26, f: 'rgb(251,230,29)' }, { y: 0, f: 'rgb(249,249,15)' }] }, - th2color: { recs: [{x:0,y:256,w:13,h:39,f:'rgb(38,62,168)'},{x:13,y:371,w:39,h:39},{y:294,h:39},{y:256,h:39},{y:218,h:39},{x:51,y:410,w:39,h:39},{y:371,h:39},{y:333,h:39},{y:294},{y:256,h:39},{y:218,h:39},{y:179,h:39},{y:141,h:39},{y:102,h:39},{y:64},{x:90,y:448,w:39,h:39},{y:410},{y:371,h:39},{y:333,h:39,f:'rgb(22,82,205)'},{y:294},{y:256,h:39,f:'rgb(16,100,220)'},{y:218,h:39},{y:179,h:39,f:'rgb(22,82,205)'},{y:141,h:39},{y:102,h:39,f:'rgb(38,62,168)'},{y:64},{y:0,h:27},{x:128,y:448,w:39,h:39},{y:410},{y:371,h:39},{y:333,h:39,f:'rgb(22,82,205)'},{y:294,f:'rgb(20,129,214)'},{y:256,h:39,f:'rgb(9,157,204)'},{y:218,h:39,f:'rgb(14,143,209)'},{y:179,h:39,f:'rgb(20,129,214)'},{y:141,h:39,f:'rgb(16,100,220)'},{y:102,h:39,f:'rgb(22,82,205)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{y:0,h:27},{x:166,y:486,h:14},{y:448,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39,f:'rgb(20,129,214)'},{y:294,f:'rgb(82,186,146)'},{y:256,h:39,f:'rgb(179,189,101)'},{y:218,h:39,f:'rgb(116,189,129)'},{y:179,h:39,f:'rgb(82,186,146)'},{y:141,h:39,f:'rgb(14,143,209)'},{y:102,h:39,f:'rgb(16,100,220)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:205,y:486,w:39,h:14},{y:448,h:39},{y:410},{y:371,h:39,f:'rgb(16,100,220)'},{y:333,h:39,f:'rgb(9,157,204)'},{y:294,f:'rgb(149,190,113)'},{y:256,h:39,f:'rgb(244,198,59)'},{y:218,h:39},{y:179,h:39,f:'rgb(226,192,75)'},{y:141,h:39,f:'rgb(13,167,195)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(22,82,205)'},{y:26,h:39,f:'rgb(38,62,168)'},{x:243,y:448,w:39,h:39},{y:410},{y:371,h:39,f:'rgb(18,114,217)'},{y:333,h:39,f:'rgb(30,175,179)'},{y:294,f:'rgb(209,187,89)'},{y:256,h:39,f:'rgb(251,230,29)'},{y:218,h:39,f:'rgb(249,249,15)'},{y:179,h:39,f:'rgb(226,192,75)'},{y:141,h:39,f:'rgb(30,175,179)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:282,y:448,h:39},{y:410},{y:371,h:39,f:'rgb(18,114,217)'},{y:333,h:39,f:'rgb(14,143,209)'},{y:294,f:'rgb(149,190,113)'},{y:256,h:39,f:'rgb(226,192,75)'},{y:218,h:39,f:'rgb(244,198,59)'},{y:179,h:39,f:'rgb(149,190,113)'},{y:141,h:39,f:'rgb(9,157,204)'},{y:102,h:39,f:'rgb(18,114,217)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:320,y:448,w:39,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39,f:'rgb(20,129,214)'},{y:294,f:'rgb(46,183,164)'},{y:256,h:39},{y:218,h:39,f:'rgb(82,186,146)'},{y:179,h:39,f:'rgb(9,157,204)'},{y:141,h:39,f:'rgb(20,129,214)'},{y:102,h:39,f:'rgb(16,100,220)'},{y:64,f:'rgb(38,62,168)'},{y:26,h:39},{x:358,y:448,h:39},{y:410},{y:371,h:39,f:'rgb(22,82,205)'},{y:333,h:39},{y:294,f:'rgb(16,100,220)'},{y:256,h:39,f:'rgb(20,129,214)'},{y:218,h:39,f:'rgb(14,143,209)'},{y:179,h:39,f:'rgb(18,114,217)'},{y:141,h:39,f:'rgb(22,82,205)'},{y:102,h:39,f:'rgb(38,62,168)'},{y:64},{y:26,h:39},{x:397,y:448,w:39,h:39},{y:371,h:39},{y:333,h:39},{y:294,f:'rgb(22,82,205)'},{y:256,h:39},{y:218,h:39},{y:179,h:39,f:'rgb(38,62,168)'},{y:141,h:39},{y:102,h:39},{y:64},{y:26,h:39},{x:435,y:410,h:39},{y:371,h:39},{y:333,h:39},{y:294},{y:256,h:39},{y:218,h:39},{y:179,h:39},{y:141,h:39},{y:102,h:39},{y:64},{x:474,y:256,h:39},{y:179,h:39}] }, - th2draw3d: { - path: 'M172.768,0H51.726C23.202,0,0.002,23.194,0.002,51.712v89.918c0,28.512,23.2,51.718,51.724,51.718h121.042 c28.518,0,51.724-23.2,51.724-51.718V51.712C224.486,23.194,201.286,0,172.768,0z M177.512,141.63c0,2.611-2.124,4.745-4.75,4.745 H51.726c-2.626,0-4.751-2.134-4.751-4.745V51.712c0-2.614,2.125-4.739,4.751-4.739h121.042c2.62,0,4.75,2.125,4.75,4.739 L177.512,141.63L177.512,141.63z '+ - 'M460.293,0H339.237c-28.521,0-51.721,23.194-51.721,51.712v89.918c0,28.512,23.2,51.718,51.721,51.718h121.045 c28.521,0,51.721-23.2,51.721-51.718V51.712C512.002,23.194,488.802,0,460.293,0z M465.03,141.63c0,2.611-2.122,4.745-4.748,4.745 H339.237c-2.614,0-4.747-2.128-4.747-4.745V51.712c0-2.614,2.133-4.739,4.747-4.739h121.045c2.626,0,4.748,2.125,4.748,4.739 V141.63z '+ - 'M172.768,256.149H51.726c-28.524,0-51.724,23.205-51.724,51.726v89.915c0,28.504,23.2,51.715,51.724,51.715h121.042 c28.518,0,51.724-23.199,51.724-51.715v-89.915C224.486,279.354,201.286,256.149,172.768,256.149z M177.512,397.784 c0,2.615-2.124,4.736-4.75,4.736H51.726c-2.626-0.006-4.751-2.121-4.751-4.736v-89.909c0-2.626,2.125-4.753,4.751-4.753h121.042 c2.62,0,4.75,2.116,4.75,4.753L177.512,397.784L177.512,397.784z '+ - 'M460.293,256.149H339.237c-28.521,0-51.721,23.199-51.721,51.726v89.915c0,28.504,23.2,51.715,51.721,51.715h121.045 c28.521,0,51.721-23.199,51.721-51.715v-89.915C512.002,279.354,488.802,256.149,460.293,256.149z M465.03,397.784 c0,2.615-2.122,4.736-4.748,4.736H339.237c-2.614,0-4.747-2.121-4.747-4.736v-89.909c0-2.626,2.121-4.753,4.747-4.753h121.045 c2.615,0,4.748,2.116,4.748,4.753V397.784z' - }, + if (this.draw_g.empty()) { + this.draw_g = this.getLayerSvg('primitives_layer').append('svg:g').attr('class', 'root_frame'); - createSVG(group, btn, size, title) { - injectStyle('.jsroot_svg_toolbar_btn { fill: steelblue; cursor: pointer; opacity: 0.3; } .jsroot_svg_toolbar_btn:hover { opacity: 1.0; }', group.node()); + // empty title on the frame required to suppress title of the canvas + if (!this.isBatchMode()) + this.draw_g.append('svg:title').text(''); - let svg = group.append('svg:svg') - .attr('class', 'jsroot_svg_toolbar_btn') - .attr('width', size + 'px') - .attr('height', size + 'px') - .attr('viewBox', '0 0 512 512') - .style('overflow', 'hidden'); + top_rect = this.draw_g.append('svg:path'); - if ('recs' in btn) { - let rec = {}; - for (let n = 0; n < btn.recs.length; ++n) { - Object.assign(rec, btn.recs[n]); - svg.append('rect').attr('x', rec.x).attr('y', rec.y) - .attr('width', rec.w).attr('height', rec.h) - .style('fill', rec.f); - } + main_svg = this.draw_g.append('svg:svg') + .attr('class', 'main_layer') + .attr('x', 0) + .attr('y', 0) + .attr('overflow', 'hidden'); + + this.draw_g.append('svg:g').attr('class', 'axis_layer'); + this.draw_g.append('svg:g').attr('class', 'upper_layer'); } else { - svg.append('svg:path').attr('d', btn.path); + top_rect = this.draw_g.selectChild('path'); + main_svg = this.draw_g.selectChild('.main_layer'); } - // special rect to correctly get mouse events for whole button area - svg.append('svg:rect').attr('x', 0).attr('y', 0).attr('width', 512).attr('height', 512) - .style('opacity', 0).style('fill', 'none').style('pointer-events', 'visibleFill') - .append('svg:title').text(title); - - return svg; - } + this.axes_drawn = false; -}; // ToolbarIcons + this.draw_g.attr('transform', trans); + top_rect.attr('d', `M0,0H${w}V${h}H0Z`) + .call(this.fillatt.func) + .call(this.lineatt.func); -/** @summary Register handle to react on window resize - * @desc function used to react on browser window resize event - * While many resize events could come in short time, - * resize will be handled with delay after last resize event - * @param {object|string} handle can be function or object with checkResize function or dom where painting was done - * @param {number} [delay] - one could specify delay after which resize event will be handled - * @protected */ -function registerForResize(handle, delay) { + main_svg.attr('width', w) + .attr('height', h) + .attr('viewBox', `0 0 ${w} ${h}`); - if (!handle || isBatchMode() || (typeof window == 'undefined')) return; + return this; + } - let myInterval = null, myDelay = delay ? delay : 300; + /** @summary Change log state of specified axis + * @param {number} value - 0 (linear), 1 (log) or 2 (log2) */ + changeAxisLog(axis, value) { + const pp = this.getPadPainter(), + pad = pp?.getRootPad(true); + if (!pad) return; - if (myDelay < 20) myDelay = 20; + pp._interactively_changed = true; - function ResizeTimer() { - myInterval = null; + const name = `fLog${axis}`; - document.body.style.cursor = 'wait'; - if (isFunc(handle)) - handle(); - else if (isFunc(handle?.checkResize)) { - handle.checkResize(); - } else { - let node = new BasePainter(handle).selectDom(); - if (!node.empty()) { - let mdi = node.property('mdi'); - if (isFunc(mdi?.checkMDIResize)) { - mdi.checkMDIResize(); - } else { - resize(node.node()); - } - } + // do not allow log scale for labels + if (!pad[name]) { + if (this.swap_xy && axis === 'x') + axis = 'y'; + else if (this.swap_xy && axis === 'y') + axis = 'x'; + const handle = this[`${axis}_handle`]; + if (handle?.kind === 'labels') return; } - document.body.style.cursor = 'auto'; - } - window.addEventListener('resize', () => { - if (myInterval !== null) clearTimeout(myInterval); - myInterval = setTimeout(ResizeTimer, myDelay); - }); -} - -function detectRightButton(event) { - if ('buttons' in event) return event.buttons === 2; - if ('which' in event) return event.which === 3; - if ('button' in event) return event.button === 2; - return false; -} - -/** @summary Add move handlers for drawn element - * @private */ -function addMoveHandler(painter, enabled) { + if ((value === 'toggle') || (value === undefined)) + value = pad[name] ? 0 : 1; - if (enabled === undefined) enabled = true; + // directly change attribute in the pad + pad[name] = value; - if (!settings.MoveResize || isBatchMode() || !painter.draw_g) return; + return this.interactiveRedraw('pad', `log${axis}`); + } - if (!enabled) { - if (painter.draw_g.property('assigned_move')) { - let drag_move = drag().subject(Object); - drag_move.on('start', null).on('drag', null).on('end', null); - painter.draw_g - .style('cursor', null) - .property('assigned_move', null) - .call(drag_move); - } - return; + /** @summary Toggle log state on the specified axis */ + toggleAxisLog(axis) { + return this.changeAxisLog(axis, 'toggle'); } - if (painter.draw_g.property('assigned_move')) return; + /** @summary Fill context menu for the frame + * @desc It could be appended to the histogram menus */ + fillContextMenu(menu, kind, obj) { + const main = this.getMainPainter(true), + pp = this.getPadPainter(), + pad = pp?.getRootPad(true), + is_pal = kind === 'pal'; - let drag_move = drag().subject(Object), - not_changed = true, move_disabled = false; + if (is_pal) kind = 'z'; - drag_move - .on('start', function(evnt) { - move_disabled = this.moveEnabled ? !this.moveEnabled() : false; - if (move_disabled) return; - if (detectRightButton(evnt.sourceEvent)) return; - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); - let pos = pointer(evnt, this.draw_g.node()); - not_changed = true; - if (this.moveStart) - this.moveStart(pos[0], pos[1]); - }.bind(painter)).on('drag', function(evnt) { - if (move_disabled) return; - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); - not_changed = false; - if (this.moveDrag) - this.moveDrag(evnt.dx, evnt.dy); - }.bind(painter)).on('end', function(evnt) { - if (move_disabled) return; - evnt.sourceEvent.preventDefault(); - evnt.sourceEvent.stopPropagation(); - if (this.moveEnd) - this.moveEnd(not_changed); - this.getPadPainter()?.selectObjectPainter(this); - }.bind(painter)); + if ((kind === 'x') || (kind === 'y') || (kind === 'z') || (kind === 'x2') || (kind === 'y2')) { + const faxis = obj || this[kind+'axis'], + handle = this[`${kind}_handle`]; + if (!isFunc(faxis?.TestBit)) + return false; - painter.draw_g - .style('cursor', 'move') - .property('assigned_move', true) - .call(drag_move); -} + menu.add(`header: ${kind.toUpperCase()} axis`); + menu.add('Unzoom', () => this.unzoom(kind)); + if (pad) { + const member = 'fLog'+kind[0]; + menu.add('sub:SetLog '+kind[0], () => { + menu.input('Enter log kind: 0 - off, 1 - log10, 2 - log2, 3 - ln, ...', pad[member], 'int', 0, 10000).then(v => { + this.changeAxisLog(kind[0], v); + }); + }); + menu.addchk(pad[member] === 0, 'linear', () => this.changeAxisLog(kind[0], 0)); + menu.addchk(pad[member] === 1, 'log10', () => this.changeAxisLog(kind[0], 1)); + menu.addchk(pad[member] === 2, 'log2', () => this.changeAxisLog(kind[0], 2)); + menu.addchk(pad[member] === 3, 'ln', () => this.changeAxisLog(kind[0], 3)); + menu.addchk(pad[member] === 4, 'log4', () => this.changeAxisLog(kind[0], 4)); + menu.addchk(pad[member] === 8, 'log8', () => this.changeAxisLog(kind[0], 8)); + menu.add('endsub:'); + } + menu.addchk(faxis.TestBit(EAxisBits.kMoreLogLabels), 'More log', flag => { + faxis.InvertBit(EAxisBits.kMoreLogLabels); + if (main?.snapid && (kind.length === 1)) + main.interactiveRedraw('pad', `exec:SetMoreLogLabels(${flag})`, kind); + else + this.interactiveRedraw('pad'); + }); + menu.addchk(handle?.noexp ?? faxis.TestBit(EAxisBits.kNoExponent), 'No exponent', flag => { + if (flag !== faxis.TestBit(EAxisBits.kNoExponent)) + faxis.InvertBit(EAxisBits.kNoExponent); + if (handle) handle.noexp_changed = true; + this[`${kind}_noexp_changed`] = true; + if (main?.snapid && (kind.length === 1)) + main.interactiveRedraw('pad', `exec:SetNoExponent(${flag})`, kind); + else + this.interactiveRedraw('pad'); + }); -/** @summary Inject style - * @param {String} code - css string - * @private */ -function injectStyle(code, node, tag) { - if (isBatchMode() || !code || (typeof document === 'undefined')) - return true; + if ((kind === 'z') && isFunc(main?.fillPaletteMenu)) + main.fillPaletteMenu(menu, !is_pal); - let styles = (node || document).getElementsByTagName('style'); - for (let n = 0; n < styles.length; ++n) { - if (tag && styles[n].getAttribute('tag') == tag) { - styles[n].innerHTML = code; - return true; - } + if ((handle?.kind === 'labels') && (faxis.fNbins > 20)) { + menu.add('Find label', () => menu.input('Label id').then(id => { + if (!id) return; + for (let bin = 0; bin < faxis.fNbins; ++bin) { + const lbl = handle.formatLabels(bin); + if (lbl === id) + return this.zoom(kind, Math.max(0, bin - 4), Math.min(faxis.fNbins, bin+5)); + } + })); + } - if (styles[n].innerHTML == code) + menu.addTAxisMenu(EAxisBits, main || this, faxis, kind); return true; - } + } - let element = document.createElement('style'); - if (tag) element.setAttribute('tag', tag); - element.innerHTML = code; - (node || document.head).appendChild(element); - return true; -} + const alone = menu.size() === 0; -/** @summary Select predefined style - * @private */ -function selectgStyle(name) { - gStyle.fName = name; - switch (name) { - case 'Modern': Object.assign(gStyle, { - fFrameBorderMode: 0, fFrameFillColor: 0, fCanvasBorderMode: 0, - fCanvasColor: 0, fPadBorderMode: 0, fPadColor: 0, fStatColor: 0, - fTitleAlign: 23, fTitleX: 0.5, fTitleBorderSize: 0, fTitleColor: 0, fTitleStyle: 0, - fOptStat: 1111, fStatY: 0.935, - fLegendBorderSize: 1, fLegendFont: 42, fLegendTextSize: 0, fLegendFillColor: 0 }); break; - case 'Plain': Object.assign(gStyle, { - fFrameBorderMode: 0, fCanvasBorderMode: 0, fPadBorderMode: 0, - fPadColor: 0, fCanvasColor: 0, - fTitleColor: 0, fTitleBorderSize: 0, fStatColor: 0, fStatBorderSize: 1, fLegendBorderSize: 1 }); break; - case 'Bold': Object.assign(gStyle, { - fCanvasColor: 10, fCanvasBorderMode: 0, - fFrameLineWidth: 3, fFrameFillColor: 10, - fPadColor: 10, fPadTickX: 1, fPadTickY: 1, fPadBottomMargin: 0.15, fPadLeftMargin: 0.15, - fTitleColor: 10, fTitleTextColor: 600, fStatColor: 10 }); break; - } -} + if (alone) + menu.add('header:Frame'); + else + menu.add('separator'); -function saveCookie(obj, expires, name) { - let arg = (expires <= 0) ? '' : btoa_func(JSON.stringify(obj)), - d = new Date(); - d.setTime((expires <= 0) ? 0 : d.getTime() + expires*24*60*60*1000); - document.cookie = `${name}=${arg}; expires=${d.toUTCString()}; SameSite=None; Secure; path=/;`; -} + if (this.zoom_xmin !== this.zoom_xmax) + menu.add('Unzoom X', () => this.unzoom('x')); + if (this.zoom_ymin !== this.zoom_ymax) + menu.add('Unzoom Y', () => this.unzoom('y')); + if (this.zoom_zmin !== this.zoom_zmax) + menu.add('Unzoom Z', () => this.unzoom('z')); + if (this.zoom_x2min !== this.zoom_x2max) + menu.add('Unzoom X2', () => this.unzoom('x2')); + if (this.zoom_y2min !== this.zoom_y2max) + menu.add('Unzoom Y2', () => this.unzoom('y2')); + menu.add('Unzoom all', () => this.unzoom('all')); -function readCookie(name) { - if (typeof document == 'undefined') return null; - let decodedCookie = decodeURIComponent(document.cookie), - ca = decodedCookie.split(';'); - name += '='; - for(let i = 0; i < ca.length; i++) { - let c = ca[i]; - while (c.charAt(0) == ' ') - c = c.substring(1); - if (c.indexOf(name) == 0) { - let s = JSON.parse(atob_func(c.substring(name.length, c.length))); + if (pad) { + menu.addchk(pad.fLogx, 'SetLogx', () => this.toggleAxisLog('x')); + menu.addchk(pad.fLogy, 'SetLogy', () => this.toggleAxisLog('y')); - return isObject(s) ? s : null; + if (isFunc(main?.getDimension) && (main.getDimension() > 1)) + menu.addchk(pad.fLogz, 'SetLogz', () => this.toggleAxisLog('z')); + menu.add('separator'); } - } - return null; -} -/** @summary Save JSROOT settings as specified cookie parameter - * @param {Number} expires - days when cookie will be removed by browser, negative - delete immediately - * @param {String} name - cookie parameter name - * @private */ -function saveSettings(expires = 365, name = 'jsroot_settings') { - saveCookie(settings, expires, name); -} + menu.addchk(this.isTooltipAllowed(), 'Show tooltips', () => this.setTooltipAllowed('toggle')); + menu.addAttributesMenu(this, alone ? '' : 'Frame '); + menu.add('Save to gStyle', () => { + gStyle.fPadBottomMargin = this.fY1NDC; + gStyle.fPadTopMargin = 1 - this.fY2NDC; + gStyle.fPadLeftMargin = this.fX1NDC; + gStyle.fPadRightMargin = 1 - this.fX2NDC; + this.fillatt?.saveToStyle('fFrameFillColor', 'fFrameFillStyle'); + this.lineatt?.saveToStyle('fFrameLineColor', 'fFrameLineWidth', 'fFrameLineStyle'); + }, 'Store frame position and graphical attributes to gStyle'); -/** @summary Read JSROOT settings from specified cookie parameter - * @param {Boolean} only_check - when true just checks if settings were stored before with provided name - * @param {String} name - cookie parameter name - * @private */ -function readSettings(only_check = false, name = 'jsroot_settings') { - let s = readCookie(name); - if (!s) return false; - if (!only_check) - Object.assign(settings, s); - return true; -} + menu.add('separator'); + menu.add('Save as frame.png', () => pp.saveAs('png', 'frame', 'frame.png')); + menu.add('Save as frame.svg', () => pp.saveAs('svg', 'frame', 'frame.svg')); -/** @summary Save JSROOT gStyle object as specified cookie parameter - * @param {Number} expires - days when cookie will be removed by browser, negative - delete immediately - * @param {String} name - cookie parameter name - * @private */ -function saveStyle(expires = 365, name = 'jsroot_style') { - saveCookie(gStyle, expires, name); -} + return true; + } -/** @summary Read JSROOT gStyle object specified cookie parameter - * @param {Boolean} only_check - when true just checks if settings were stored before with provided name - * @param {String} name - cookie parameter name - * @private */ -function readStyle(only_check = false, name = 'jsroot_style') { - let s = readCookie(name); - if (!s) return false; - if (!only_check) - Object.assign(gStyle, s); - return true; -} + /** @summary Fill option object used in TWebCanvas + * @private */ + fillWebObjectOptions(res) { + if (!res) { + if (!this.snapid) return null; + res = { _typename: 'TWebObjectOptions', snapid: this.snapid.toString(), opt: this.getDrawOpt(), fcust: '', fopt: [] }; + } -let _saveFileFunc = null; + res.fcust = 'frame'; + res.fopt = [this.scale_xmin || 0, this.scale_ymin || 0, this.scale_xmax || 0, this.scale_ymax || 0]; + return res; + } + /** @summary Returns frame X position */ + getFrameX() { return this._frame_x || 0; } -/** @summary Returns image file content as it should be stored on the disc - * @desc Replaces all kind of base64 coding - * @private */ + /** @summary Returns frame Y position */ + getFrameY() { return this._frame_y || 0; } -function getBinFileContent(content) { - const svg_prefix = 'data:image/svg+xml;charset=utf-8,'; + /** @summary Returns frame width */ + getFrameWidth() { return this._frame_width || 0; } - if (content.indexOf(svg_prefix) == 0) - return decodeURIComponent(content.slice(svg_prefix.length)); + /** @summary Returns frame height */ + getFrameHeight() { return this._frame_height || 0; } - if (content.indexOf('data:image/') == 0) { - let p = content.indexOf('base64,'); - if (p > 0) { - let base64 = content.slice(p + 7); - return atob_func(base64); - } + /** @summary Returns frame rectangle plus extra info for hint display */ + getFrameRect() { + return { + x: this._frame_x || 0, + y: this._frame_y || 0, + width: this.getFrameWidth(), + height: this.getFrameHeight(), + transform: this.draw_g?.attr('transform') || '', + hint_delta_x: 0, + hint_delta_y: 0 + }; } - return content; -} - -/** @summary Function store content as file with filename - * @private */ -async function saveFile(filename, content) { - if (isFunc(_saveFileFunc)) - return _saveFileFunc(filename, getBinFileContent(content)); - if (isNodeJs()) { - return Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder$1; }).then(fs => { - fs.writeFileSync(filename, getBinFileContent(content)); - return true; - }); - } else if (typeof document == 'object') { - let a = document.createElement('a'); - a.download = filename; - a.href = content; - document.body.appendChild(a); + /** @summary Configure user-defined click handler + * @desc Function will be called every time when frame click was perfromed + * As argument, tooltip object with selected bins will be provided + * If handler function returns true, default handling of click will be disabled */ + configureUserClickHandler(handler) { + this._click_handler = isFunc(handler) ? handler : null; + } - return new Promise(resolve => { - a.addEventListener('click', () => { a.parentNode.removeChild(a); resolve(true); }); - a.click(); - }); + /** @summary Configure user-defined dblclick handler + * @desc Function will be called every time when double click was called + * As argument, tooltip object with selected bins will be provided + * If handler function returns true, default handling of dblclick (unzoom) will be disabled */ + configureUserDblclickHandler(handler) { + this._dblclick_handler = isFunc(handler) ? handler : null; } - return false; -} -/** @summary Function store content as file with filename - * @private */ -function setSaveFile(func) { - _saveFileFunc = func; -} + /** @summary Function can be used for zooming into specified range + * @desc if both limits for each axis 0 (like xmin === xmax === 0), axis will be unzoomed + * @param {number} xmin + * @param {number} xmax + * @param {number} [ymin] + * @param {number} [ymax] + * @param {number} [zmin] + * @param {number} [zmax] + * @return {Promise} with boolean flag if zoom operation was performed */ + async zoom(xmin, xmax, ymin, ymax, zmin, zmax) { + if (xmin === 'x') { xmin = xmax; xmax = ymin; ymin = undefined; } else + if (xmin === 'y') { ymax = ymin; ymin = xmax; xmin = xmax = undefined; } else + if (xmin === 'z') { zmin = xmax; zmax = ymin; xmin = xmax = ymin = undefined; } -/** @summary Produce exec string for WebCanas to set color value - * @desc Color can be id or string, but should belong to list of known colors - * For higher color numbers TColor::GetColor(r,g,b) will be invoked to ensure color is exists - * @private */ -function getColorExec(col, method) { - let id = -1, arr = getRootColors(); - if (isStr(col)) { - if (!col || (col == 'none')) { - id = 0; - } else { - for (let k = 1; k < arr.length; ++k) - if (arr[k] == col) { id = k; break; } - } - if ((id < 0) && (col.indexOf('rgb') == 0)) - id = 9999; - } else if (Number.isInteger(col) && arr[col]) { - id = col; - col = arr[id]; - } + let zoom_x = (xmin !== xmax), zoom_y = (ymin !== ymax), zoom_z = (zmin !== zmax), + unzoom_x = false, unzoom_y = false, unzoom_z = false; - if (id < 0) return ''; + if (zoom_x) { + let cnt = 0; + if (xmin <= this.xmin) { xmin = this.xmin; cnt++; } + if (xmax >= this.xmax) { xmax = this.xmax; cnt++; } + if (cnt === 2) { zoom_x = false; unzoom_x = true; } + } else + unzoom_x = (xmin === xmax) && (xmin === 0); - // for higher color numbers ensure that such color exists - if (id >= 50) { - let c = color$1(col); - id = `TColor::GetColor(${c.r},${c.g},${c.b})`; - } + if (zoom_y) { + let cnt = 0; + if ((ymin <= this.ymin) || (!this.ymin && this.logy && + ((!this.y_handle?.log_min_nz && ymin < logminfactorY*this.ymax) || (ymin < this.y_handle?.log_min_nz)))) { + ymin = this.ymin; + cnt++; + } + if (ymax >= this.ymax) { ymax = this.ymax; cnt++; } + if ((cnt === 2) && (this.scales_ndim !== 1)) { + zoom_y = false; + unzoom_y = true; + } + } else + unzoom_y = (ymin === ymax) && (ymin === 0); - return `exec:${method}(${id})`; -} + if (zoom_z) { + let cnt = 0; + if (zmin <= this.zmin) { zmin = this.zmin; cnt++; } + if (zmax >= this.zmax) { zmax = this.zmax; cnt++; } + if ((cnt === 2) && (this.scales_ndim > 2)) { zoom_z = false; unzoom_z = true; } + } else + unzoom_z = (zmin === zmax) && (zmin === 0); -/** - * @summary Abstract class for creating context menu - * - * @desc Use {@link createMenu} to create instance of the menu - * @private - */ -class JSRootMenu { - constructor(painter, menuname, show_event) { - this.painter = painter; - this.menuname = menuname; - if (isObject(show_event) && (show_event.clientX !== undefined) && (show_event.clientY !== undefined)) - this.show_evnt = { clientX: show_event.clientX, clientY: show_event.clientY }; + let changed = false; + + // first process zooming (if any) + if (zoom_x || zoom_y || zoom_z) { + this.forEachPainter(obj => { + if (!isFunc(obj.canZoomInside)) return; + if (zoom_x && obj.canZoomInside('x', xmin, xmax)) { + this.zoom_xmin = xmin; + this.zoom_xmax = xmax; + changed = true; + zoom_x = false; + } + if (zoom_y && obj.canZoomInside('y', ymin, ymax)) { + this.zoom_ymin = ymin; + this.zoom_ymax = ymax; + changed = true; + zoom_y = false; + } + if (zoom_z && obj.canZoomInside('z', zmin, zmax)) { + this.zoom_zmin = zmin; + this.zoom_zmax = zmax; + changed = true; + zoom_z = false; + } + }); + } + + // and process unzoom, if any + if (unzoom_x || unzoom_y || unzoom_z) { + if (unzoom_x) { + if (this.zoom_xmin !== this.zoom_xmax) changed = true; + this.zoom_xmin = this.zoom_xmax = 0; + } + if (unzoom_y) { + if (this.zoom_ymin !== this.zoom_ymax) changed = true; + this.zoom_ymin = this.zoom_ymax = 0; + } + if (unzoom_z) { + if (this.zoom_zmin !== this.zoom_zmax) changed = true; + this.zoom_zmin = this.zoom_zmax = 0; + } + + // than try to unzoom all overlapped objects + if (!changed) { + this.getPadPainter()?.painters?.forEach(painter => { + if (isFunc(painter?.unzoomUserRange)) { + if (painter.unzoomUserRange(unzoom_x, unzoom_y, unzoom_z)) + changed = true; + } + }); + } + } - this.remove_handler = () => this.remove(); - this.element = null; - this.cnt = 0; + return changed ? this.interactiveRedraw('pad', 'zoom').then(() => true) : false; } - native() { return false; } + /** @summary Provide zooming of single axis + * @desc One can specify names like x/y/z but also second axis x2 or y2 + * @private */ + async zoomSingle(name, vmin, vmax) { + if (!this[name+'_handle']) + return false; - async load() { return this; } + let zoom_v = (vmin !== vmax), unzoom_v = false; - /** @summary Returns object with mouse event position when context menu was actiavted - * @desc Return object will have members 'clientX' and 'clientY' */ - getEventPosition() { return this.show_evnt; } + if (zoom_v) { + let cnt = 0; + if (vmin <= this[name+'min']) { vmin = this[name+'min']; cnt++; } + if (vmax >= this[name+'max']) { vmax = this[name+'max']; cnt++; } + if (cnt === 2) { zoom_v = false; unzoom_v = true; } + } else + unzoom_v = (vmin === vmax) && (vmin === 0); - add(/*name, arg, func, title*/) { - throw Error('add() method has to be implemented in the menu'); - } - /** @summary Returns menu size */ - size() { return this.cnt; } + let changed = false; - /** @summary Close and remove menu */ - remove() { - if (this.element !== null) { - this.element.remove(); - if (this.resolveFunc) { - this.resolveFunc(); - delete this.resolveFunc; - } - document.body.removeEventListener('click', this.remove_handler); + // first process zooming + if (zoom_v) { + this.forEachPainter(obj => { + if (!isFunc(obj.canZoomInside)) return; + if (zoom_v && obj.canZoomInside(name[0], vmin, vmax)) { + this[`zoom_${name}min`] = vmin; + this[`zoom_${name}max`] = vmax; + changed = true; + zoom_v = false; + } + }); } - this.element = null; - } - - show(/*event*/) { - throw Error('show() method has to be implemented in the menu class'); - } - /** @summary Add checked menu item - * @param {boolean} flag - flag - * @param {string} name - item name - * @param {function} func - func called when item is selected */ - addchk(flag, name, arg, func, title) { - let handler = func; - if (isFunc(arg)) { - title = func; - func = arg; - handler = res => func(res == '1'); - arg = flag ? '0' : '1'; + // and process unzoom, if any + if (unzoom_v) { + if (this[`zoom_${name}min`] !== this[`zoom_${name}max`]) changed = true; + this[`zoom_${name}min`] = this[`zoom_${name}max`] = 0; } - this.add((flag ? 'chk:' : 'unk:') + name, arg, handler, title); - } - /** @summary Add draw sub-menu with draw options - * @protected */ - addDrawMenu(top_name, opts, call_back) { - if (!opts || !opts.length) - return; + if (!changed) return false; - let without_sub = false; - if (top_name.indexOf('nosub:') == 0) { - without_sub = true; - top_name = top_name.slice(6); - } + return this.interactiveRedraw('pad', 'zoom').then(() => true); + } - if (opts.length === 1) { - if (opts[0] === 'inspect') - top_name = top_name.replace('Draw', 'Inspect'); - this.add(top_name, opts[0], call_back); - return; - } + /** @summary Checks if specified axis zoomed */ + isAxisZoomed(axis) { + return this[`zoom_${axis}min`] !== this[`zoom_${axis}max`]; + } - if (!without_sub) this.add('sub:' + top_name, opts[0], call_back); + /** @summary Unzoom speicified axes + * @return {Promise} with boolean flag if zooming changed */ + async unzoom(dox, doy, doz) { + if (dox === 'all') + return this.unzoom('x2').then(() => this.unzoom('y2')).then(() => this.unzoom('xyz')); - for (let i = 0; i < opts.length; ++i) { - let name = opts[i] || (this._use_plain_text ? '' : '<dflt>'), - group = i+1; - if ((opts.length > 5) && name) { - // check if there are similar options, which can be grouped once again - while ((group < opts.length) && (opts[group].indexOf(name) == 0)) group++; - } + if ((dox === 'x2') || (dox === 'y2')) { + return this.zoomSingle(dox, 0, 0).then(changed => { + if (changed) this.zoomChangedInteractive(dox, 'unzoom'); + return changed; + }); + } - if (without_sub) name = top_name + ' ' + name; + if (typeof dox === 'undefined') dox = doy = doz = true; else + if (isStr(dox)) { doz = dox.indexOf('z') >= 0; doy = dox.indexOf('y') >= 0; dox = dox.indexOf('x') >= 0; } - if (group < i+2) { - this.add(name, opts[i], call_back); - } else { - this.add('sub:' + name, opts[i], call_back); - for (let k = i+1; k < group; ++k) - this.add(opts[k], opts[k], call_back); - this.add('endsub:'); - i = group-1; - } - } - if (!without_sub) this.add('endsub:'); - } + return this.zoom(dox ? 0 : undefined, dox ? 0 : undefined, + doy ? 0 : undefined, doy ? 0 : undefined, + doz ? 0 : undefined, doz ? 0 : undefined).then(changed => { + if (changed && dox) this.zoomChangedInteractive('x', 'unzoom'); + if (changed && doy) this.zoomChangedInteractive('y', 'unzoom'); + if (changed && doz) this.zoomChangedInteractive('z', 'unzoom'); - /** @summary Add color selection menu entries - * @protected */ - addColorMenu(name, value, set_func, fill_kind) { - if (value === undefined) return; - let useid = !isStr(value); - this.add('sub:' + name, () => { - this.input('Enter color ' + (useid ? '(only id number)' : '(name or id)'), value, useid ? 'int' : 'text', useid ? 0 : undefined, useid ? 9999 : undefined).then(col => { - let id = parseInt(col); - if (Number.isInteger(id) && getColor(id)) { - col = getColor(id); - } else { - if (useid) return; - } - set_func(useid ? id : col); - }); + return changed; }); + } - for(let ncolumn = 0; ncolumn < 5; ++ncolumn) { - this.add('column:'); - - for (let nrow = 0; nrow < 10; nrow++) { - let n = ncolumn*10 + nrow; - if (!useid) --n; // use -1 as none color + /** @summary Mark/check if zoom for specific axis was changed interactively + * @private */ + zoomChangedInteractive(axis, value) { + if (axis === 'reset') { + this.zoom_changed_x = this.zoom_changed_y = this.zoom_changed_z = undefined; + return; + } + if (!axis || axis === 'any') + return this.zoom_changed_x || this.zoom_changed_y || this.zoom_changed_z; - let col = (n < 0) ? 'none' : getColor(n); - if ((n == 0) && (fill_kind == 1)) col = 'none'; - let lbl = (n <= 0) || (col[0] != '#') ? col : `col ${n}`, - fill = (n == 1) ? 'white' : 'black', - stroke = (n == 1) ? 'red' : 'black', - rect = (value == (useid ? n : col)) ? `` : '', - svg = `${rect}${lbl}`; + if ((axis !== 'x') && (axis !== 'y') && (axis !== 'z')) return; - this.add(svg, (useid ? n : col), res => set_func(useid ? parseInt(res) : res), 'Select color ' + col); - } + const fld = 'zoom_changed_' + axis; + if (value === undefined) + return this[fld]; - this.add('endcolumn:'); - if (!this.native()) break; + if (value === 'unzoom') { + // special handling of unzoom, only if was never changed before flag set to true + this[fld] = (this[fld] === undefined); + return; } - this.add('endsub:'); + if (value) + this[fld] = true; } - /** @summary Add size selection menu entries - * @protected */ - addSizeMenu(name, min, max, step, size_value, set_func, title) { - - if (size_value === undefined) return; - - let values = [], miss_current = false; - if (isObject(step)) { - values = step; step = 1; - } else for (let sz = min; sz <= max; sz += step) - values.push(sz); + /** @summary Convert graphical coordinate into axis value */ + revertAxis(axis, pnt) { return this[`${axis}_handle`]?.revertPoint(pnt) ?? 0; } - const match = v => Math.abs(v-size_value) < (max - min)*1e-5, - conv = (v, more) => { - if ((v === size_value) && miss_current) more = true; - if (step >= 1) return v.toFixed(0); - if (step >= 0.1) return v.toFixed(more ? 2 : 1); - return v.toFixed(more ? 4 : 2); - }; + /** @summary Show axis status message + * @desc method called normally when mouse enter main object element + * @private */ + showAxisStatus(axis_name, evnt) { + const taxis = this.getAxis(axis_name), + m = pointer(evnt, this.getFrameSvg().node()); + let hint_name = axis_name, + hint_title = clTAxis, + id = (axis_name === 'x') ? 0 : 1; - if (values.findIndex(match) < 0) { - miss_current = true; - values.push(size_value); - values = values.sort((a,b) => a > b); + if (taxis) { + hint_name = taxis.fName; + hint_title = taxis.fTitle || `TAxis object for ${axis_name}`; } + if (this.swap_xy) id = 1 - id; - this.add('sub:' + name, () => this.input('Enter value of ' + name, conv(size_value, true), (step >= 1) ? 'int' : 'float').then(set_func), title); - values.forEach(v => this.addchk(match(v), conv(v), v, res => set_func((step >= 1) ? parseInt(res) : parseFloat(res)))); - this.add('endsub:'); - } + const axis_value = this.revertAxis(axis_name, m[id]); - /** @summary Add palette menu entries - * @protected */ - addPaletteMenu(curr, set_func) { - const add = (id, name, title, more) => { - if (!name) - name = `pal ${id}`; - else if (!title) - title = name; - if (title) title += `, code ${id}`; - this.addchk((id === curr) || more, '
' + name + '', id, set_func, title || name); - }; + this.showObjectStatus(hint_name, hint_title, `${axis_name} : ${this.axisAsText(axis_name, axis_value)}`, `${m[0]},${m[1]}`); + } - this.add('sub:Palette', () => this.input('Enter palette code [1..113]', curr, 'int', 1, 113).then(set_func)); + /** @summary Add interactive keys handlers + * @private */ + addKeysHandler() { + if (this.isBatchMode()) return; + FrameInteractive.assign(this); + this.addFrameKeysHandler(); + } - this.add('column:'); + /** @summary Add interactive functionality to the frame + * @private */ + addInteractivity(for_second_axes) { + if (this.isBatchMode() || (!settings.Zooming && !settings.ContextMenu)) + return false; - add(57, 'Bird', 'Default color palette', (curr > 113)); - add(55, 'Rainbow'); - add(51, 'Deep Sea'); - add(52, 'Grayscale', 'New gray scale'); - add(1, '', 'Old gray scale', (curr > 0) && (curr < 10)); - add(50, 'ROOT 5', 'Default color palette in ROOT 5', (curr >= 10) && (curr < 51)); - add(53, '', 'Dark body radiator'); - add(54, '', 'Two-color hue'); - add(56, '', 'Inverted dark body radiator'); - add(58, 'Cubehelix'); - add(59, '', 'Green Red Violet'); - add(60, '', 'Blue Red Yellow'); - add(61, 'Ocean'); + FrameInteractive.assign(this); + if (!for_second_axes) + this.addBasicInteractivity(); - this.add('endcolumn:'); + return this.addFrameInteractivity(for_second_axes); + } - if (!this.native()) - return this.add('endsub:'); +} // class TFramePainter - this.add('column:'); +/** @summary Current hierarchy painter + * @desc Instance of {@link HierarchyPainter} object + * @private */ +let first_hpainter = null; - add(62, '', 'Color Printable On Grey'); - add(63, 'Alpine'); - add(64, 'Aquamarine'); - add(65, 'Army'); - add(66, 'Atlantic'); - add(67, 'Aurora'); - add(68, 'Avocado'); - add(69, 'Beach'); - add(70, 'Black Body'); - add(71, '', 'Blue Green Yellow'); - add(72, 'Brown Cyan'); - add(73, 'CMYK'); - add(74, 'Candy'); +/** @summary Returns current hierarchy painter object + * @private */ +function getHPainter() { return first_hpainter; } - this.add('endcolumn:'); - this.add('column:'); +/** @summary Set hierarchy painter object + * @private */ +function setHPainter(hp) { first_hpainter = hp; } - add(75, 'Cherry'); - add(76, 'Coffee'); - add(77, '', 'Dark Rain Bow'); - add(78, '', 'Dark Terrain'); - add(79, 'Fall'); - add(80, 'Fruit Punch'); - add(81, 'Fuchsia'); - add(82, 'Grey Yellow'); - add(83, '', 'Green Brown Terrain'); - add(84, 'Green Pink'); - add(85, 'Island'); - add(86, 'Lake'); - add(87, '', 'Light Temperature'); +/** + * @summary Base class to manage multiple document interface for drawings + * + * @private + */ - this.add('endcolumn:'); - this.add('column:'); +class MDIDisplay extends BasePainter { - add(88, '', 'Light Terrain'); - add(89, 'Mint'); - add(90, 'Neon'); - add(91, 'Pastel'); - add(92, 'Pearl'); - add(93, 'Pigeon'); - add(94, 'Plum'); - add(95, 'Red Blue'); - add(96, 'Rose'); - add(97, 'Rust'); - add(98, '', 'Sandy Terrain'); - add(99, 'Sienna'); - add(100, 'Solar'); + /** @summary constructor */ + constructor(frameid) { + super(); + this.frameid = frameid; + if (frameid !== '$batch$') { + this.setDom(frameid); + this.selectDom().property('mdi', this); + } + this.cleanupFrame = cleanup; // use standard cleanup function by default + this.active_frame_title = ''; // keep title of active frame + } - this.add('endcolumn:'); - this.add('column:'); + /** @summary Assign func which called for each newly created frame */ + setInitFrame(func) { + this.initFrame = func; + this.forEachFrame(frame => func(frame)); + } - add(101, '', 'South West'); - add(102, '', 'Starry Night'); - add(103, '', 'Sunset'); - add(104, '', 'Temperature Map'); - add(105, '', 'Thermometer'); - add(106, 'Valentine'); - add(107, '', 'Visible Spectrum'); - add(108, '', 'Water Melon'); - add(109, 'Cool'); - add(110, 'Copper'); - add(111, '', 'Gist Earth'); - add(112, 'Viridis'); - add(113, 'Cividis'); + /** @summary method called before new frame is created */ + beforeCreateFrame(title) { this.active_frame_title = title; } - this.add('endcolumn:'); + /** @summary method called after new frame is created + * @private */ + afterCreateFrame(frame) { + if (isFunc(this.initFrame)) + this.initFrame(frame); + return frame; + } - this.add('endsub:'); + /** @summary method dedicated to iterate over existing panels + * @param {function} userfunc is called with arguments (frame) + * @param {boolean} only_visible let select only visible frames */ + forEachFrame(userfunc, only_visible) { + console.warn(`forEachFrame not implemented in MDIDisplay ${typeof userfunc} ${only_visible}`); } - /** @summary Add rebin menu entries - * @protected */ - addRebinMenu(rebin_func) { - this.add('sub:Rebin', () => this.input('Enter rebin value', 2, 'int', 2).then(rebin_func)); - for (let sz = 2; sz <= 7; sz++) - this.add(sz.toString(), sz, res => rebin_func(parseInt(res))); - this.add('endsub:'); + /** @summary method dedicated to iterate over existing panles + * @param {function} userfunc is called with arguments (painter, frame) + * @param {boolean} only_visible let select only visible frames */ + forEachPainter(userfunc, only_visible) { + this.forEachFrame(frame => { + new ObjectPainter(frame).forEachPainter(painter => userfunc(painter, frame)); + }, only_visible); } - /** @summary Add selection menu entries - * @param {String} name - name of submenu - * @param {Array} values - array of string entries used as list for selection - * @param {String|Number} value - currently elected value, either name or index - * @param {Function} set_func - function called when item selected, either name or index depending from value parameter - * @protected */ - addSelectMenu(name, values, value, set_func) { - let use_number = (typeof value == 'number'); - this.add('sub:' + name); - for (let n = 0; n < values.length; ++n) - this.addchk(use_number ? (n == value) : (values[n] == value), values[n], use_number ? n : values[n], res => set_func(use_number ? Number.parseInt(res) : res)); - this.add('endsub:'); + /** @summary Returns total number of drawings */ + numDraw() { + let cnt = 0; + this.forEachFrame(() => ++cnt); + return cnt; } - /** @summary Add RColor selection menu entries - * @protected */ - addRColorMenu(name, value, set_func) { - // if (value === undefined) return; - let colors = ['default', 'black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']; + /** @summary Serach for the frame using item name */ + findFrame(searchtitle, force) { + let found_frame = null; - this.add('sub:' + name, () => { - this.input('Enter color name - empty string will reset color', value).then(set_func); + this.forEachFrame(frame => { + if (select(frame).attr('frame_title') === searchtitle) + found_frame = frame; }); - let fillcol = 'black'; - for (let n = 0; n < colors.length; ++n) { - let coltxt = colors[n], match = false, bkgr = ''; - if (n > 0) { - bkgr = 'background-color:' + coltxt; - fillcol = (coltxt == 'white') ? 'black' : 'white'; - if (isStr(value) && value && (value != 'auto') && (value[0] != '[')) - match = (rgb(value).toString() == rgb(coltxt).toString()); - } else { - match = !value; - } - let svg = `${coltxt}`; - this.addchk(match, svg, coltxt, res => set_func(res == 'default' ? null : res)); - } - this.add('endsub:'); + if (!found_frame && force) + found_frame = this.createFrame(searchtitle); + + return found_frame; } - /** @summary Add items to change RAttrText - * @protected */ - addRAttrTextItems(fontHandler, opts, set_func) { - if (!opts) opts = {}; - this.addRColorMenu('color', fontHandler.color, sel => set_func({ name: 'color', value: sel })); - if (fontHandler.scaled) - this.addSizeMenu('size', 0.01, 0.10, 0.01, fontHandler.size /fontHandler.scale, sz => set_func({ name: 'size', value: sz })); - else - this.addSizeMenu('size', 6, 20, 2, fontHandler.size, sz => set_func({ name: 'size', value: sz })); + /** @summary Activate frame */ + activateFrame(frame) { this.active_frame_title = frame ? select(frame).attr('frame_title') : ''; } - this.addSelectMenu('family', ['Arial', 'Times New Roman', 'Courier New', 'Symbol'], fontHandler.name, res => set_func( {name: 'font_family', value: res })); + /** @summary Return active frame */ + getActiveFrame() { return this.findFrame(this.active_frame_title); } - this.addSelectMenu('style', ['normal', 'italic', 'oblique'], fontHandler.style || 'normal', res => set_func( {name: 'font_style', value: res == 'normal' ? null : res })); + /** @summary perform resize for each frame + * @protected */ + checkMDIResize(only_frame_id, size) { + let resized_frame = null; - this.addSelectMenu('weight', ['normal', 'lighter', 'bold', 'bolder'], fontHandler.weight || 'normal', res => set_func( {name: 'font_weight', value: res == 'normal' ? null : res })); + this.forEachPainter((painter, frame) => { + if (only_frame_id && (select(frame).attr('id') !== only_frame_id)) return; - if (!opts.noalign) - this.add('align'); - if (!opts.noangle) - this.add('angle'); + if ((painter.getItemName() !== null) && isFunc(painter.checkResize)) { + // do not call resize for many painters on the same frame + if (resized_frame === frame) return; + painter.checkResize(size); + resized_frame = frame; + } + }); } - /** @summary Fill context menu for text attributes - * @private */ - addTextAttributesMenu(painter, prefix) { - // for the moment, text attributes accessed directly from objects + /** @summary Cleanup all drawings */ + cleanup() { + this.active_frame_title = ''; + + this.forEachFrame(this.cleanupFrame); - let obj = painter.getObject(); - if ((obj?.fTextColor === undefined) || (obj?.fTextAlign == undefined)) return; + this.selectDom().html('').property('mdi', null); + } - this.add('sub:' + (prefix || 'Text')); - this.addColorMenu('color', obj.fTextColor, - arg => { obj.fTextColor = arg; painter.interactiveRedraw(true, getColorExec(arg, 'SetTextColor')); }); +} // class MDIDisplay - let align = [11, 12, 13, 21, 22, 23, 31, 32, 33]; - this.add('sub:align'); - for (let n = 0; n < align.length; ++n) { - this.addchk(align[n] == obj.fTextAlign, - align[n], align[n], - // align[n].toString() + '_h:' + hnames[Math.floor(align[n]/10) - 1] + '_v:' + vnames[align[n]%10-1], align[n], - function(arg) { this.getObject().fTextAlign = parseInt(arg); this.interactiveRedraw(true, `exec:SetTextAlign(${arg})`); }.bind(painter)); - } - this.add('endsub:'); +/** + * @summary Custom MDI display + * + * @desc All HTML frames should be created before and add via {@link CustomDisplay#addFrame} calls + * @private + */ - this.addFontMenu('font', obj.fTextFont, function(fnt) { - this.getObject().fTextFont = fnt; this.interactiveRedraw(true, `exec:SetTextFont(${fnt})`); }.bind(painter) - ); +class CustomDisplay extends MDIDisplay { - this.add('endsub:'); + constructor() { + super('dummy'); + this.frames = {}; // array of configured frames } - /** @summary Add line style menu - * @private */ - addLineStyleMenu(name, value, set_func) { - this.add('sub:'+name, () => this.input('Enter line style id (1-solid)', value, 'int', 1, 11).then(val => { - if (getSvgLineStyle(val)) set_func(val); - })); - for (let n = 1; n < 11; ++n) { - let dash = getSvgLineStyle(n), - svg = `${n}`; + addFrame(divid, itemname) { + const prev = this.frames[divid] || ''; + this.frames[divid] = prev + (itemname + ';'); + } - this.addchk((value == n), svg, n, arg => set_func(parseInt(arg))); + forEachFrame(userfunc) { + const ks = Object.keys(this.frames); + for (let k = 0; k < ks.length; ++k) { + const node = select('#'+ks[k]); + if (!node.empty()) + userfunc(node.node()); } - this.add('endsub:'); } - /** @summary Add fill style menu - * @private */ - addFillStyleMenu(name, value, color_index, painter, set_func) { - this.add('sub:' + name, () => { - this.input('Enter fill style id (1001-solid, 3000..3010)', value, 'int', 0, 4000).then(id => { - if ((id >= 0) && (id <= 4000)) set_func(id); - }); - }); - - let supported = [1, 1001, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3010, 3021, 3022]; + createFrame(title) { + this.beforeCreateFrame(title); - for (let n = 0; n < supported.length; ++n) { - let svg = supported[n]; - if (painter) { - let sample = painter.createAttFill({ std: false, pattern: supported[n], color: color_index || 1 }); - svg = `${supported[n].toString()}`; - } - this.addchk(value == supported[n], svg, supported[n], arg => set_func(parseInt(arg))); + const ks = Object.keys(this.frames); + for (let k = 0; k < ks.length; ++k) { + const items = this.frames[ks[k]]; + if (items.indexOf(title+';') >= 0) + return select('#'+ks[k]).node(); } - this.add('endsub:'); + return null; } - /** @summary Add font selection menu - * @private */ - addFontMenu(name, value, set_func) { - this.add('sub:' + name, () => { - this.input('Enter font id from [0..20]', Math.floor(value/10), 'int', 0, 20).then(id => { - if ((id >= 0) && (id <= 20)) set_func(id*10 + 2); - }); - }); + cleanup() { + super.cleanup(); + this.forEachFrame(frame => select(frame).html('')); + } - this.add('column:'); +} // class CustomDisplay - for (let n = 1; n < 20; ++n) { - let handler = new FontHandler(n*10+2, 14), - txt = select(document.createElementNS('http://www.w3.org/2000/svg', 'text')), - fullname = handler.getFontName(), - name = ' ' + fullname.split(' ')[0] + ' '; - if (handler.weight) { name = 'b' + name; fullname += ' ' + handler.weight; } - if (handler.style) { name = handler.style[0] + name; fullname += ' ' + handler.style; } - txt.attr('x', 1).attr('y',15).text(name); - handler.setFont(txt); +/** + * @summary Generic grid MDI display + * + * @private + */ - let rect = (value != n*10+2) ? '' : ``, - svg = `${txt.node().outerHTML}${rect}`; - this.add(svg, n, arg => set_func(parseInt(arg)*10+2), fullname); +class GridDisplay extends MDIDisplay { + + /** @summary Create GridDisplay instance + * @param {string} frameid - where grid display is created + * @param {string} kind - kind of grid + * @desc following kinds are supported + * - vertical or horizontal - only first letter matters, defines basic orientation + * - 'x' in the name disable interactive separators + * - v4 or h4 - 4 equal elements in specified direction + * - v231 - created 3 vertical elements, first divided on 2, second on 3 and third on 1 part + * - v23_52 - create two vertical elements with 2 and 3 subitems, size ratio 5:2 + * - gridNxM - normal grid layout without interactive separators + * - gridiNxM - grid layout with interactive separators + * - simple - no layout, full frame used for object drawings */ + constructor(frameid, kind, kind2) { + super(frameid); + + this.framecnt = 0; + this.getcnt = 0; + this.groups = []; + this.vertical = kind && (kind[0] === 'v'); + this.use_separarators = !kind || (kind.indexOf('x') < 0); + this.simple_layout = false; + + const dom = this.selectDom(); + dom.style('overflow', 'hidden'); - if (n == 10) { - this.add('endcolumn:'); - this.add('column:'); - } + if (kind === 'simple') { + this.simple_layout = true; + this.use_separarators = false; + this.framecnt = 1; + return; } - this.add('endcolumn:'); - this.add('endsub:'); - } + let num = 2, arr, sizes, chld_sizes; - /** @summary Fill context menu for graphical attributes in painter - * @private */ - addAttributesMenu(painter, preffix) { - // this method used to fill entries for different attributes of the object - // like TAttFill, TAttLine, .... - // all menu call-backs need to be rebind, while menu can be used from other painter + if (kind === 'projxy') { + this.vertical = false; + this.use_separarators = true; + arr = [2, 2]; + sizes = [1, 3]; + chld_sizes = [[3, 1], [3, 1]]; + kind = ''; + this.match_sizes = true; + } else if ((kind.indexOf('grid') === 0) || kind2) { + if (kind2) kind = kind + 'x' + kind2; + else kind = kind.slice(4).trim(); + this.use_separarators = false; + if (kind[0] === 'i') { + this.use_separarators = true; + kind = kind.slice(1); + } - if (!preffix) preffix = ''; + const separ = kind.indexOf('x'); + let sizex, sizey; - if (painter.lineatt?.used) { - this.add('sub:' + preffix + 'Line att'); - this.addSizeMenu('width', 1, 10, 1, painter.lineatt.width, - arg => { painter.lineatt.change(undefined, arg); painter.interactiveRedraw(true, `exec:SetLineWidth(${arg})`); }); - this.addColorMenu('color', painter.lineatt.color, - arg => { painter.lineatt.change(arg); painter.interactiveRedraw(true, getColorExec(arg, 'SetLineColor')); }); - this.addLineStyleMenu('style', painter.lineatt.style, id => { - painter.lineatt.change(undefined, undefined, id); - painter.interactiveRedraw(true, `exec:SetLineStyle(${id})`); - }); - this.add('endsub:'); + if (separ > 0) { + sizey = parseInt(kind.slice(separ + 1)); + sizex = parseInt(kind.slice(0, separ)); + } else + sizex = sizey = parseInt(kind); - if (painter.lineatt?.excl_side) { - this.add('sub:Exclusion'); - this.add('sub:side'); - for (let side = -1; side <= 1; ++side) - this.addchk((painter.lineatt.excl_side == side), side, side, function(arg) { - this.lineatt.changeExcl(parseInt(arg)); - this.interactiveRedraw(); - }.bind(painter)); - this.add('endsub:'); - this.addSizeMenu('width', 10, 100, 10, painter.lineatt.excl_width, - arg => { painter.lineatt.changeExcl(undefined, arg); painter.interactiveRedraw(); }); + if (!Number.isInteger(sizex)) sizex = 3; + if (!Number.isInteger(sizey)) sizey = 3; - this.add('endsub:'); + if (sizey > 1) { + this.vertical = true; + num = sizey; + if (sizex > 1) + arr = new Array(num).fill(sizex); + } else if (sizex > 1) { + this.vertical = false; + num = sizex; + } else { + this.simple_layout = true; + this.use_separarators = false; + this.framecnt = 1; + return; } + kind = ''; } - if (painter.fillatt?.used) { - this.add('sub:' + preffix + 'Fill att'); - this.addColorMenu('color', painter.fillatt.colorindx, arg => { - painter.fillatt.change(arg, undefined, painter.getCanvSvg()); - painter.interactiveRedraw(true, getColorExec(arg, 'SetFillColor')); - }, painter.fillatt.kind); - this.addFillStyleMenu('style', painter.fillatt.pattern, painter.fillatt.colorindx, painter, id => { - painter.fillatt.change(undefined, id, painter.getCanvSvg()); - painter.interactiveRedraw(true, `exec:SetFillStyle(${id})`); - }); - this.add('endsub:'); + if (kind && kind.indexOf('_') > 0) { + let arg = parseInt(kind.slice(kind.indexOf('_')+1), 10); + if (Number.isInteger(arg) && (arg > 10)) { + kind = kind.slice(0, kind.indexOf('_')); + sizes = []; + while (arg > 0) { + sizes.unshift(Math.max(arg % 10, 1)); + arg = Math.round((arg-sizes[0])/10); + if (sizes[0] === 0) sizes[0] = 1; + } + } } - if (painter.markeratt?.used) { - this.add('sub:' + preffix + 'Marker att'); - this.addColorMenu('color', painter.markeratt.color, - arg => { painter.markeratt.change(arg); painter.interactiveRedraw(true, getColorExec(arg, 'SetMarkerColor'));}); - this.addSizeMenu('size', 0.5, 6, 0.5, painter.markeratt.size, - arg => { painter.markeratt.change(undefined, undefined, arg); painter.interactiveRedraw(true, `exec:SetMarkerSize(${arg})`); }); - - this.add('sub:style'); - let supported = [1, 2, 3, 4, 5, 6, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]; - - for (let n = 0; n < supported.length; ++n) { - - let clone = new TAttMarkerHandler({ style: supported[n], color: painter.markeratt.color, size: 1.7 }), - svg = `${supported[n].toString()}`; - - this.addchk(painter.markeratt.style == supported[n], svg, supported[n], - function(arg) { this.markeratt.change(undefined, parseInt(arg)); this.interactiveRedraw(true, `exec:SetMarkerStyle(${arg})`); }.bind(painter)); + kind = kind ? parseInt(kind.replace(/^\D+/g, ''), 10) : 0; + if (Number.isInteger(kind) && (kind > 1)) { + if (kind < 10) + num = kind; + else { + arr = []; + while (kind > 0) { + arr.unshift(kind % 10); + kind = Math.round((kind-arr[0])/10); + if (arr[0] === 0) arr[0] = 1; + } + num = arr.length; } - this.add('endsub:'); - this.add('endsub:'); } - } - /** @summary Fill context menu for axis - * @private */ - addTAxisMenu(EAxisBits, painter, faxis, kind) { - this.add('Divisions', () => this.input('Set Ndivisions', faxis.fNdivisions, 'int', 0).then(val => { - faxis.fNdivisions = val; - painter.interactiveRedraw('pad', `exec:SetNdivisions(${val})`, kind); - })); + if (sizes?.length !== num) + sizes = undefined; + if (chld_sizes?.length !== num) + chld_sizes = undefined; - this.add('sub:Labels'); - this.addchk(faxis.TestBit(EAxisBits.kCenterLabels), 'Center', - arg => { faxis.InvertBit(EAxisBits.kCenterLabels); painter.interactiveRedraw('pad', `exec:CenterLabels(${arg})`, kind); }); - this.addchk(faxis.TestBit(EAxisBits.kLabelsVert), 'Rotate', - arg => { faxis.InvertBit(EAxisBits.kLabelsVert); painter.interactiveRedraw('pad', `exec:SetBit(TAxis::kLabelsVert,${arg})`, kind); }); - this.addColorMenu('Color', faxis.fLabelColor, - arg => { faxis.fLabelColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetLabelColor'), kind); }); - this.addSizeMenu('Offset', 0, 0.1, 0.01, faxis.fLabelOffset, - arg => { faxis.fLabelOffset = arg; painter.interactiveRedraw('pad', `exec:SetLabelOffset(${arg})`, kind); }); - this.addSizeMenu('Size', 0.02, 0.11, 0.01, faxis.fLabelSize, - arg => { faxis.fLabelSize = arg; painter.interactiveRedraw('pad', `exec:SetLabelSize(${arg})`, kind); }); - this.add('endsub:'); - this.add('sub:Title'); - this.add('SetTitle', () => { - this.input('Enter axis title', faxis.fTitle).then(t => { - faxis.fTitle = t; - painter.interactiveRedraw('pad', `exec:SetTitle("${t}")`, kind); - }); - }); - this.addchk(faxis.TestBit(EAxisBits.kCenterTitle), 'Center', - arg => { faxis.InvertBit(EAxisBits.kCenterTitle); painter.interactiveRedraw('pad', `exec:CenterTitle(${arg})`, kind); }); - this.addchk(faxis.TestBit(EAxisBits.kOppositeTitle), 'Opposite', - () => { faxis.InvertBit(EAxisBits.kOppositeTitle); painter.redrawPad(); }); - this.addchk(faxis.TestBit(EAxisBits.kRotateTitle), 'Rotate', - arg => { faxis.InvertBit(EAxisBits.kRotateTitle); painter.interactiveRedraw('pad', `exec:RotateTitle(${arg})`, kind); }); - this.addColorMenu('Color', faxis.fTitleColor, - arg => { faxis.fTitleColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetTitleColor'), kind); }); - this.addSizeMenu('Offset', 0, 3, 0.2, faxis.fTitleOffset, - arg => { faxis.fTitleOffset = arg; painter.interactiveRedraw('pad', `exec:SetTitleOffset(${arg})`, kind); }); - this.addSizeMenu('Size', 0.02, 0.11, 0.01, faxis.fTitleSize, - arg => { faxis.fTitleSize = arg; painter.interactiveRedraw('pad', `exec:SetTitleSize(${arg})`, kind); }); - this.add('endsub:'); - this.add('sub:Ticks'); - if (faxis._typename == clTGaxis) { - this.addColorMenu('Color', faxis.fLineColor, - arg => { faxis.fLineColor = arg; painter.interactiveRedraw('pad'); }); - this.addSizeMenu('Size', -0.05, 0.055, 0.01, faxis.fTickSize, - arg => { faxis.fTickSize = arg; painter.interactiveRedraw('pad'); }); - } else { - this.addColorMenu('Color', faxis.fAxisColor, - arg => { faxis.fAxisColor = arg; painter.interactiveRedraw('pad', getColorExec(arg, 'SetAxisColor'), kind); }); - this.addSizeMenu('Size', -0.05, 0.055, 0.01, faxis.fTickLength, - arg => { faxis.fTickLength = arg; painter.interactiveRedraw('pad', `exec:SetTickLength(${arg})`, kind); }); - } - this.add('endsub:'); + if (!this.simple_layout) + this.createGroup(this, dom, num, arr, sizes, chld_sizes); } - /** @summary Fill menu to edit settings properties + /** @summary Create frames group * @private */ - addSettingsMenu(with_hierarchy, alone, handle_func) { - if (alone) - this.add('header:Settings'); - else - this.add('sub:Settings'); - - this.add('sub:Files'); - - if (with_hierarchy) { - this.addchk(settings.OnlyLastCycle, 'Last cycle', flag => { - settings.OnlyLastCycle = flag; - if (handle_func) handle_func('refresh'); - }); - - this.addchk(!settings.SkipStreamerInfos, 'Streamer infos', flag => { - settings.SkipStreamerInfos = !flag; - if (handle_func) handle_func('refresh'); - }); + createGroup(handle, main, num, childs, sizes, childs_sizes) { + if (!sizes) sizes = new Array(num); + let sum1 = 0, sum2 = 0; + for (let n = 0; n < num; ++n) + sum1 += (sizes[n] || 1); + for (let n = 0; n < num; ++n) { + sizes[n] = Math.round(100 * (sizes[n] || 1) / sum1); + sum2 += sizes[n]; + if (n === num-1) sizes[n] += (100-sum2); // make 100% } - this.addchk(settings.UseStamp, 'Use stamp arg', flag => { settings.UseStamp = flag; }); - this.addSizeMenu('Max ranges', 1, 1000, [1, 10, 20, 50, 200, 1000], settings.MaxRanges, value => { settings.MaxRanges = value; }, 'Maximal number of ranges in single http request'); - - this.addchk(settings.HandleWrongHttpResponse, 'Handle wrong http response', flag => { settings.HandleWrongHttpResponse = flag; }); - - this.add('endsub:'); + for (let cnt = 0; cnt < num; ++cnt) { + const group = { id: cnt, drawid: -1, position: 0, size: sizes[cnt], parent: handle }; + if (cnt > 0) group.position = handle.groups[cnt-1].position + handle.groups[cnt-1].size; + group.position0 = group.position; - this.add('sub:Toolbar'); - this.addchk(settings.ToolBar === false, 'Off', flag => { settings.ToolBar = !flag; }); - this.addchk(settings.ToolBar === true, 'On', flag => { settings.ToolBar = flag; }); - this.addchk(settings.ToolBar === 'popup', 'Popup', flag => { settings.ToolBar = flag ? 'popup' : false; }); - this.add('separator'); - this.addchk(settings.ToolBarSide == 'left', 'Left side', flag => { settings.ToolBarSide = flag ? 'left' : 'right'; }); - this.addchk(settings.ToolBarVert, 'Vertical', flag => { settings.ToolBarVert = flag; }); - this.add('endsub:'); + if (!childs || !childs[cnt] || childs[cnt] < 2) + group.drawid = this.framecnt++; - this.add('sub:Interactive'); - this.addchk(settings.Tooltip, 'Tooltip', flag => { settings.Tooltip = flag; }); - this.addchk(settings.ContextMenu, 'Context menus', flag => { settings.ContextMenu = flag; }); - this.add('sub:Zooming'); - this.addchk(settings.Zooming, 'Global', flag => { settings.Zooming = flag; }); - this.addchk(settings.ZoomMouse, 'Mouse', flag => { settings.ZoomMouse = flag; }); - this.addchk(settings.ZoomWheel, 'Wheel', flag => { settings.ZoomWheel = flag; }); - this.addchk(settings.ZoomTouch, 'Touch', flag => { settings.ZoomTouch = flag; }); - this.add('endsub:'); - this.addchk(settings.HandleKeys, 'Keypress handling', flag => { settings.HandleKeys = flag; }); - this.addchk(settings.MoveResize, 'Move and resize', flag => { settings.MoveResize = flag; }); - this.addchk(settings.DragAndDrop, 'Drag and drop', flag => { settings.DragAndDrop = flag; }); - this.addchk(settings.DragGraphs, 'Drag graph points', flag => { settings.DragGraphs = flag; }); - this.addchk(settings.ProgressBox, 'Progress box', flag => { settings.ProgressBox = flag; }); - this.add('endsub:'); + handle.groups.push(group); - this.add('sub:Drawing'); - this.addSelectMenu('Optimize', ['None', 'Smart', 'Always'], settings.OptimizeDraw, value => { settings.OptimizeDraw = value; }); - this.addPaletteMenu(settings.Palette, pal => { settings.Palette = pal; }); - this.addchk(settings.AutoStat, 'Auto stat box', flag => { settings.AutoStat = flag; }); - this.addSelectMenu('Latex', ['Off', 'Symbols', 'Normal', 'MathJax', 'Force MathJax'], settings.Latex, value => { settings.Latex = value; }); - this.addSelectMenu('3D rendering', ['Default', 'WebGL', 'Image'], settings.Render3D, value => { settings.Render3D = value; }); - this.addSelectMenu('WebGL embeding', ['Default', 'Overlay', 'Embed'], settings.Embed3D, value => { settings.Embed3D = value; }); + const elem = main.append('div').attr('groupid', group.id); - this.add('endsub:'); + // remember HTML node only when need to match sizes of different groups + if (handle.match_sizes) + group.node = elem.node(); - this.add('sub:Geometry'); - this.add('Grad per segment: ' + settings.GeoGradPerSegm, () => this.input('Grad per segment in geometry', settings.GeoGradPerSegm, 'int', 1, 60).then(val => { settings.GeoGradPerSegm = val; })); - this.addchk(settings.GeoCompressComp, 'Compress composites', flag => { settings.GeoCompressComp = flag; }); - this.add('endsub:'); + if (handle.vertical) + elem.style('float', 'bottom').style('height', group.size.toFixed(2)+'%').style('width', '100%'); + else + elem.style('float', 'left').style('width', group.size.toFixed(2)+'%').style('height', '100%'); - if (with_hierarchy) - this.add('Hierarchy limit: ' + settings.HierarchyLimit, () => this.input('Max number of items in hierarchy', settings.HierarchyLimit, 'int', 10, 100000).then(val => { - settings.HierarchyLimit = val; - if (handle_func) handle_func('refresh'); - })); + if (group.drawid >= 0) { + elem.classed('jsroot_newgrid', true); + if (isStr(this.frameid)) + elem.attr('id', `${this.frameid}_${group.drawid}`); + } else + elem.style('display', 'flex').style('flex-direction', handle.vertical ? 'row' : 'column'); - this.add('Dark mode: ' + (settings.DarkMode ? 'On' : 'Off'), () => { - settings.DarkMode = !settings.DarkMode; - if (handle_func) handle_func('dark'); - }); - const setStyleField = arg => { gStyle[arg.slice(1)] = parseInt(arg[0]); }, - addStyleIntField = (name, field, arr) => { - this.add('sub:' + name); - for (let v = 0; v < arr.length; ++v) - this.addchk(gStyle[field] == v, arr[v], `${v}${field}`, setStyleField); - this.add('endsub:'); - }; + if (childs && (childs[cnt] > 1)) { + group.vertical = !handle.vertical; + group.groups = []; + elem.style('overflow', 'hidden'); + this.createGroup(group, elem, childs[cnt], null, childs_sizes ? childs_sizes[cnt] : null); + } + } - this.add('sub:gStyle'); + if (this.use_separarators && isFunc(this.createSeparator)) { + for (let cnt = 1; cnt < num; ++cnt) + this.createSeparator(handle, main, handle.groups[cnt]); + } + } - this.add('sub:Canvas'); - this.addColorMenu('Color', gStyle.fCanvasColor, col => { gStyle.fCanvasColor = col; }); - this.addchk(gStyle.fOptDate, 'Draw date', flag => { gStyle.fOptDate = flag ? 1 : 0; }); - this.addchk(gStyle.fOptFile, 'Draw item', flag => { gStyle.fOptFile = flag ? 1 : 0; }); - this.addSizeMenu('Date X', 0.01, 0.1, 0.01, gStyle.fDateX, x => { gStyle.fDateX = x; }, 'configure gStyle.fDateX for date/item name drawings'); - this.addSizeMenu('Date Y', 0.01, 0.1, 0.01, gStyle.fDateY, y => { gStyle.fDateY = y; }, 'configure gStyle.fDateY for date/item name drawings'); - this.add('endsub:'); + /** @summary Handle interactive sepearator movement + * @private */ + handleSeparator(elem, action) { + const findGroup = (node, grid) => { + let chld = node?.firstChild; + while (chld) { + if (chld.getAttribute('groupid') === grid) + return select(chld); + chld = chld.nextSibling; + } + // should never happen, but keep it here like + return select(node).select(`[groupid='${grid}']`); + }, setGroupSize = (h, node, grid) => { + const name = h.vertical ? 'height' : 'width', + size = h.groups[grid].size.toFixed(2)+'%'; + findGroup(node, grid).style(name, size) + .selectAll('.jsroot_separator').style(name, size); + }, resizeGroup = (node, grid) => { + let sel = findGroup(node, grid); + if (!sel.classed('jsroot_newgrid')) + sel = sel.select('.jsroot_newgrid'); + sel.each(function() { resize(this); }); + }, posSepar = (h, group, separ) => { + separ.style(h.vertical ? 'top' : 'left', `calc(${group.position.toFixed(2)}% - 2px)`); + }, separ = select(elem), + parent = elem.parentNode, + handle = separ.property('handle'), + id = separ.property('separator_id'), + group = handle.groups[id]; + let needResize = false, needSetSize = false; + + if (action === 'start') { + group.startpos = group.position; + group.acc_drag = 0; + return; + } - this.add('sub:Pad'); - this.addColorMenu('Color', gStyle.fPadColor, col => { gStyle.fPadColor = col; }); - this.add('sub:Grid'); - this.addchk(gStyle.fPadGridX, 'X', flag => { gStyle.fPadGridX = flag; }); - this.addchk(gStyle.fPadGridY, 'Y', flag => { gStyle.fPadGridY = flag; }); - this.addColorMenu('Color', gStyle.fGridColor, col => { gStyle.fGridColor = col; }); - this.addSizeMenu('Width', 1, 10, 1, gStyle.fGridWidth, w => { gStyle.fGridWidth = w; }); - this.addLineStyleMenu('Style', gStyle.fGridStyle, st => { gStyle.fGridStyle = st; }); - this.add('endsub:'); - addStyleIntField('Ticks X', 'fPadTickX', ['normal', 'ticks on both sides', 'labels on both sides']); - addStyleIntField('Ticks Y', 'fPadTickY', ['normal', 'ticks on both sides', 'labels on both sides']); - addStyleIntField('Log X', 'fOptLogx', ['off', 'on', 'log 2']); - addStyleIntField('Log Y', 'fOptLogy', ['off', 'on', 'log 2']); - addStyleIntField('Log Z', 'fOptLogz', ['off', 'on', 'log 2']); - this.addchk(gStyle.fOptTitle == 1, 'Hist title', flag => { gStyle.fOptTitle = flag ? 1 : 0; }); - this.add('endsub:'); + if (action === 'end') { + if (Math.abs(group.startpos - group.position) < 0.5) + return; + needResize = true; + } else { + let pos; + if (action === 'restore') + pos = group.position0; + else if (handle.vertical) { + group.acc_drag += action.dy; + pos = group.startpos + ((group.acc_drag + 2) / parent.clientHeight) * 100; + } else { + group.acc_drag += action.dx; + pos = group.startpos + ((group.acc_drag + 2) / parent.clientWidth) * 100; + } - this.add('sub:Frame'); - this.addColorMenu('Fill color', gStyle.fFrameFillColor, col => { gStyle.fFrameFillColor = col; }); - this.addFillStyleMenu('Fill style', gStyle.fFrameFillStyle, gStyle.fFrameFillColor, null, id => { gStyle.fFrameFillStyle = id; }); - this.addColorMenu('Line color', gStyle.fFrameLineColor, col => { gStyle.fFrameLineColor = col; }); - this.addSizeMenu('Line width', 1, 10, 1, gStyle.fFrameLineWidth, w => { gStyle.fFrameLineWidth = w; }); - this.addLineStyleMenu('Line style', gStyle.fFrameLineStyle, st => { gStyle.fFrameLineStyle = st; }); - this.addSizeMenu('Border size', 0, 10, 1, gStyle.fFrameBorderSize, sz => { gStyle.fFrameBorderSize = sz; }); - // fFrameBorderMode: 0, - this.add('sub:Margins'); - this.addSizeMenu('Bottom', 0, 0.5, 0.05, gStyle.fPadBottomMargin, v => { gStyle.fPadBottomMargin = v; }); - this.addSizeMenu('Top', 0, 0.5, 0.05, gStyle.fPadTopMargin, v => { gStyle.fPadTopMargin = v; }); - this.addSizeMenu('Left', 0, 0.5, 0.05, gStyle.fPadLeftMargin, v => { gStyle.fPadLeftMargin = v; }); - this.addSizeMenu('Right', 0, 0.5, 0.05, gStyle.fPadRightMargin, v => { gStyle.fPadRightMargin = v; }); - this.add('endsub:'); - this.add('endsub:'); + const diff = group.position - pos; - this.add('sub:Title'); - this.addColorMenu('Fill color', gStyle.fTitleColor, col => { gStyle.fTitleColor = col; }); - this.addFillStyleMenu('Fill style', gStyle.fTitleStyle, gStyle.fTitleColor, null, id => { gStyle.fTitleStyle = id; }); - this.addColorMenu('Text color', gStyle.fTitleTextColor, col => { gStyle.fTitleTextColor = col; }); - this.addSizeMenu('Border size', 0, 10, 1, gStyle.fTitleBorderSize, sz => { gStyle.fTitleBorderSize = sz; }); - this.addSizeMenu('Font size', 0.01, 0.1, 0.01, gStyle.fTitleFontSize, sz => { gStyle.fTitleFontSize = sz; }); - this.addFontMenu('Font', gStyle.fTitleFont, fnt => { gStyle.fTitleFont = fnt; }); - this.addSizeMenu('X: ' + gStyle.fTitleX.toFixed(2), 0., 1., 0.1, gStyle.fTitleX, v => { gStyle.fTitleX = v; }); - this.addSizeMenu('Y: ' + gStyle.fTitleY.toFixed(2), 0., 1., 0.1, gStyle.fTitleY, v => { gStyle.fTitleY = v; }); - this.addSizeMenu('W: ' + gStyle.fTitleW.toFixed(2), 0., 1., 0.1, gStyle.fTitleW, v => { gStyle.fTitleW = v; }); - this.addSizeMenu('H: ' + gStyle.fTitleH.toFixed(2), 0., 1., 0.1, gStyle.fTitleH, v => { gStyle.fTitleH = v; }); - this.add('endsub:'); + if (Math.abs(diff) < 0.3) return; // if no significant change, do nothing - this.add('sub:Stat box'); - this.addColorMenu('Fill color', gStyle.fStatColor, col => { gStyle.fStatColor = col; }); - this.addFillStyleMenu('Fill style', gStyle.fStatStyle, gStyle.fStatColor, null, id => { gStyle.fStatStyle = id; }); - this.addColorMenu('Text color', gStyle.fStatTextColor, col => { gStyle.fStatTextColor = col; }); - this.addSizeMenu('Border size', 0, 10, 1, gStyle.fStatBorderSize, sz => { gStyle.fStatBorderSize = sz; }); - this.addSizeMenu('Font size', 0, 30, 5, gStyle.fStatFontSize, sz => { gStyle.fStatFontSize = sz; }); - this.addFontMenu('Font', gStyle.fStatFont, fnt => { gStyle.fStatFont = fnt; }); - this.add('Stat format', () => this.input('Stat format', gStyle.fStatFormat).then(fmt => { gStyle.fStatFormat = fmt; })); - this.addSizeMenu('X: ' + gStyle.fStatX.toFixed(2), 0.2, 1., 0.1, gStyle.fStatX, v => { gStyle.fStatX = v; }); - this.addSizeMenu('Y: ' + gStyle.fStatY.toFixed(2), 0.2, 1., 0.1, gStyle.fStatY, v => { gStyle.fStatY = v; }); - this.addSizeMenu('Width: ' + gStyle.fStatW.toFixed(2), 0.1, 1., 0.1, gStyle.fStatW, v => { gStyle.fStatW = v; }); - this.addSizeMenu('Height: ' + gStyle.fStatH.toFixed(2), 0.1, 1., 0.1, gStyle.fStatH, v => { gStyle.fStatH = v; }); - this.add('endsub:'); + // do not change if size too small + if (Math.min(handle.groups[id-1].size - diff, group.size+diff) < 3) return; - this.add('sub:Legend'); - this.addColorMenu('Fill color', gStyle.fLegendFillColor, col => { gStyle.fLegendFillColor = col; }); - this.addSizeMenu('Border size', 0, 10, 1, gStyle.fLegendBorderSize, sz => { gStyle.fLegendBorderSize = sz; }); - this.addFontMenu('Font', gStyle.fLegendFont, fnt => { gStyle.fLegendFont = fnt; }); - this.addSizeMenu('Text size', 0, 0.1, 0.01, gStyle.fLegendTextSize, v => { gStyle.fLegendTextSize = v; }, 'legend text size, when 0 - auto adjustment is used'); - this.add('endsub:'); + handle.groups[id-1].size -= diff; + group.size += diff; + group.position = pos; - this.add('sub:Histogram'); - this.addchk(gStyle.fHistMinimumZero, 'Base0', flag => { gStyle.fHistMinimumZero = flag; }, 'when true, BAR and LEGO drawing using base = 0'); - this.add('Text format', () => this.input('Paint text format', gStyle.fPaintTextFormat).then(fmt => { gStyle.fPaintTextFormat = fmt; })); - this.add('Time offset', () => this.input('Time offset in seconds, default is 788918400 for 1/1/1995', gStyle.fTimeOffset, 'int').then(ofset => { gStyle.fTimeOffset = ofset; })); - this.addSizeMenu('ErrorX: ' + gStyle.fErrorX.toFixed(2), 0., 1., 0.1, gStyle.fErrorX, v => { gStyle.fErrorX = v; }); - this.addSizeMenu('End error', 0, 12, 1, gStyle.fEndErrorSize, v => { gStyle.fEndErrorSize = v; }, 'size in pixels of end error for E1 draw options, gStyle.fEndErrorSize'); - this.addSizeMenu('Top margin', 0., 0.5, 0.05, gStyle.fHistTopMargin, v => { gStyle.fHistTopMargin = v; }, 'Margin between histogram top and frame top'); - this.addColorMenu('Fill color', gStyle.fHistFillColor, col => { gStyle.fHistFillColor = col; }); - this.addFillStyleMenu('Fill style', gStyle.fHistFillStyle, gStyle.fHistFillColor, null, id => { gStyle.fHistFillStyle = id; }); - this.addColorMenu('Line color', gStyle.fHistLineColor, col => { gStyle.fHistLineColor = col; }); - this.addSizeMenu('Line width', 1, 10, 1, gStyle.fHistLineWidth, w => { gStyle.fHistLineWidth = w; }); - this.addLineStyleMenu('Line style', gStyle.fHistLineStyle, st => { gStyle.fHistLineStyle = st; }); - this.add('endsub:'); + posSepar(handle, group, separ); - this.add('separator'); - this.add('sub:Predefined'); - ['Modern', 'Plain', 'Bold'].forEach(name => this.addchk((gStyle.fName == name), name, name, selectgStyle)); - this.add('endsub:'); + needSetSize = true; + needResize = (action === 'restore'); + } - this.add('endsub:'); // gStyle + if (needSetSize) { + setGroupSize(handle, parent, id-1); + setGroupSize(handle, parent, id); + } - this.add('separator'); + if (needResize) { + resizeGroup(parent, id-1); + resizeGroup(parent, id); + } - this.add('Save settings', () => { - let promise = readSettings(true) ? Promise.resolve(true) : this.confirm('Save settings', 'Pressing OK one agreess that JSROOT will store settings as browser cookies'); - promise.then(res => { if (res) { saveSettings(); saveStyle(); } }); - }, 'Store settings and gStyle as cookies'); - this.add('Delete settings', () => { saveSettings(-1); saveStyle(-1); }, 'Delete settings and gStyle from cookies'); + // now handling match of the sizes + if (!handle.parent?.match_sizes) + return; - if (!alone) this.add('endsub:'); + for (let k = 0; k < handle.parent.groups.length; ++k) { + const hh = handle.parent.groups[k]; + if ((hh === handle) || !hh.node) continue; + hh.groups[id].size = handle.groups[id].size; + hh.groups[id].position = handle.groups[id].position; + hh.groups[id-1].size = handle.groups[id-1].size; + hh.groups[id-1].position = handle.groups[id-1].position; + if (needSetSize) { + select(hh.node).selectAll('.jsroot_separator').each(function() { + const s = select(this); + if (s.property('separator_id') === id) + posSepar(hh, hh.groups[id], s); + }); + setGroupSize(hh, hh.node, id-1); + setGroupSize(hh, hh.node, id); + } + if (needResize) { + resizeGroup(hh.node, id-1); + resizeGroup(hh.node, id); + } + } } - /** @summary Run modal dialog - * @return {Promise} with html element inside dialg + /** @summary Create group separator * @private */ - async runModal() { - throw Error('runModal() must be reimplemented'); - } - - /** @summary Show modal info dialog - * @param {String} title - title - * @param {String} message - message - * @protected */ - info(title, message) { - return this.runModal(title,`

${message}

`, { height: 120, width: 400, resizable: true }); - } - - /** @summary Show confirm dialog - * @param {String} title - title - * @param {String} message - message - * @return {Promise} with true when 'Ok' pressed or false when 'Cancel' pressed - * @protected */ - async confirm(title, message) { - return this.runModal(title, message, { btns: true, height: 120, width: 400 }).then(elem => { return !!elem; }); - } - - /** @summary Input value - * @return {Promise} with input value - * @param {string} title - input dialog title - * @param value - initial value - * @param {string} [kind] - use 'text' (default), 'number', 'float' or 'int' - * @protected */ - async input(title, value, kind, min, max) { - - if (!kind) kind = 'text'; - let inp_type = (kind == 'int') ? 'number' : 'text', ranges = ''; - if ((value === undefined) || (value === null)) value = ''; - if (kind == 'int') { - if (min !== undefined) ranges += ` min="${min}"`; - if (max !== undefined) ranges += ` max="${max}"`; - } + createSeparator(handle, main, group) { + const separ = main.append('div'); - let main_content = - '
'+ - ``+ - '
'; + separ.classed('jsroot_separator', true) + .property('handle', handle) + .property('separator_id', group.id) + .attr('style', 'pointer-events: all; border: 0; margin: 0; padding: 0; position: absolute;') + .style(handle.vertical ? 'top' : 'left', `calc(${group.position.toFixed(2)}% - 2px)`) + .style(handle.vertical ? 'width' : 'height', (handle.size?.toFixed(2) || 100)+'%') + .style(handle.vertical ? 'height' : 'width', '5px') + .style('cursor', handle.vertical ? 'ns-resize' : 'ew-resize') + .append('div').attr('style', 'position: absolute;' + (handle.vertical + ? 'left: 0; right: 0; top: 50%; height: 3px; border-top: 1px dotted #ff0000' + : 'top: 0; bottom: 0; left: 50%; width: 3px; border-left: 1px dotted #ff0000')); - return new Promise(resolveFunc => { + const pthis = this, drag_move = + drag().on('start', function() { pthis.handleSeparator(this, 'start'); }) + .on('drag', function(evnt) { pthis.handleSeparator(this, evnt); }) + .on('end', function() { pthis.handleSeparator(this, 'end'); }); - this.runModal(title, main_content, { btns: true, height: 150, width: 400 }).then(element => { - if (!element) return; - let val = element.querySelector(`.jsroot_dlginp`).value; - if (kind == 'float') { - val = parseFloat(val); - if (Number.isFinite(val)) - resolveFunc(val); - } else if (kind == 'int') { - val = parseInt(val); - if (Number.isInteger(val)) - resolveFunc(val); - } else { - resolveFunc(val); - } - }); + separ.call(drag_move).on('dblclick', function() { pthis.handleSeparator(this, 'restore'); }); - }); + // need to get touches events handling in drag + if (browser.touches && !main.on('touchmove')) + main.on('touchmove', () => {}); } - /** @summary Let input arguments from the method - * @return {Promise} with method argument */ - async showMethodArgsDialog(method) { - let dlg_id = this.menuname + '_dialog', - main_content = '
'; - for (let n = 0; n < method.fArgs.length; ++n) { - let arg = method.fArgs[n]; - arg.fValue = arg.fDefault; - if (arg.fValue == '\"\"') arg.fValue = ''; - main_content += ` - `; + /** @summary Call function for each frame */ + forEachFrame(userfunc) { + if (this.simple_layout) + userfunc(this.getGridFrame()); + else { + this.selectDom().selectAll('.jsroot_newgrid').each(function() { + userfunc(this); + }); } + } - main_content += '
'; + /** @summary Returns active frame */ + getActiveFrame() { + if (this.simple_layout) + return this.getGridFrame(); - return new Promise(resolveFunc => { + let found = super.getActiveFrame(); + if (found) return found; - this.runModal(method.fClassName + '::' + method.fName, main_content, { btns: true, height: 100 + method.fArgs.length*60, width: 400, resizable: true }).then(element => { - if (!element) return; - let args = ''; + this.forEachFrame(frame => { if (!found) found = frame; }); - for (let k = 0; k < method.fArgs.length; ++k) { - let arg = method.fArgs[k]; - let value = element.querySelector(`#${dlg_id}_inp${k}`).value; - if (value === '') value = arg.fDefault; - if ((arg.fTitle == 'Option_t*') || (arg.fTitle == 'const char*')) { - // check quotes, - // TODO: need to make more precise checking of escape characters - if (!value) value = '""'; - if (value[0] != '"') value = '"' + value; - if (value[value.length-1] != '"') value += '"'; - } + return found; + } - args += (k > 0 ? ',' : '') + value; - } + /** @summary Returns number of frames in grid layout */ + numGridFrames() { return this.framecnt; } - resolveFunc(args); - }); + /** @summary Return grid frame by its id */ + getGridFrame(id) { + if (this.simple_layout) + return this.selectDom('origin').node(); + let res = null; + this.selectDom().selectAll('.jsroot_newgrid').each(function() { + if (id-- === 0) res = this; }); + return res; } - /** @summary Let input arguments from the Command - * @return {Promise} with command argument */ - async showCommandArgsDialog(cmdname, args) { - let dlg_id = this.menuname + '_dialog', - main_content = '
'; + /** @summary Create new frame */ + createFrame(title) { + this.beforeCreateFrame(title); - for (let n = 0; n < args.length; ++n) - main_content += ``+ - ``; + let frame = null, maxloop = this.framecnt || 2; - main_content += '
'; + while (!frame && maxloop--) { + frame = this.getGridFrame(this.getcnt); + if (!this.simple_layout && this.framecnt) + this.getcnt = (this.getcnt+1) % this.framecnt; - return new Promise(resolveFunc => { + if (select(frame).classed('jsroot_fixed_frame')) frame = null; + } - this.runModal('Arguments for command ' + cmdname, main_content, { btns: true, height: 110 + args.length*60, width: 400, resizable: true}).then(element => { - if (!element) - return resolveFunc(null); + if (frame) { + this.cleanupFrame(frame); + select(frame).attr('frame_title', title); + } - let resargs = []; - for (let k = 0; k < args.length; ++k) - resargs.push(element.querySelector(`#${dlg_id}_inp${k}`).value); - resolveFunc(resargs); - }); - }); + return this.afterCreateFrame(frame); } -} // class JSRootMenu +} // class GridDisplay + + +// ================================================ /** - * @summary Context menu class using plain HTML/JavaScript + * @summary Tabs-based display * - * @desc Use {@link createMenu} to create instance of the menu - * based on {@link https://github.com/L1quidH2O/ContextMenu.js} * @private */ -class StandaloneMenu extends JSRootMenu { +class TabsDisplay extends MDIDisplay { - constructor(painter, menuname, show_event) { - super(painter, menuname, show_event); + constructor(frameid) { + super(frameid); + this.cnt = 0; // use to count newly created frames + this.selectDom().style('overflow', 'hidden'); + } - this.code = []; - this._use_plain_text = true; - this.stack = [ this.code ]; + /** @summary Cleanup all drawings */ + cleanup() { + this.selectDom().style('overflow', null); + this.cnt = 0; + super.cleanup(); } - native() { return true; } + /** @summary call function for each frame */ + forEachFrame(userfunc, only_visible) { + if (!isFunc(userfunc)) return; - /** @summary Load required modules, noop for that menu class */ - async load() { return this; } + if (only_visible) { + const active = this.getActiveFrame(); + if (active) userfunc(active); + return; + } - /** @summary Add menu item - * @param {string} name - item name - * @param {function} func - func called when item is selected */ - add(name, arg, func, title) { - let curr = this.stack[this.stack.length-1]; + const main = this.selectDom().select('.jsroot_tabs_main'); - if (name == 'separator') - return curr.push({ divider: true }); + main.selectAll('.jsroot_tabs_draw').each(function() { + userfunc(this); + }); + } - if (name.indexOf('header:') == 0) - return curr.push({ text: name.slice(7), header: true }); + /** @summary modify tab state by id */ + modifyTabsFrame(frame_id, action) { + const top = this.selectDom().select('.jsroot_tabs'), + labels = top.select('.jsroot_tabs_labels'), + main = top.select('.jsroot_tabs_main'); - if ((name == 'endsub:') || (name == 'endcolumn:')) - return this.stack.pop(); + labels.selectAll('.jsroot_tabs_label').each(function() { + const id = select(this).property('frame_id'), + is_same = (id === frame_id), + active_color = settings.DarkMode ? '#333' : 'white'; + + if (action === 'activate') { + select(this).style('background', is_same ? active_color : (settings.DarkMode ? 'black' : '#ddd')) + .style('color', settings.DarkMode ? '#ddd' : 'inherit') + .style('border-color', active_color); + } else if ((action === 'close') && is_same) + this.parentNode.remove(); + }); - if (isFunc(arg)) { title = func; func = arg; arg = name; } + let selected_frame, other_frame; - let elem = {}; - curr.push(elem); + main.selectAll('.jsroot_tabs_draw').each(function() { + const match = select(this).property('frame_id') === frame_id; + if (match) + selected_frame = this; + else + other_frame = this; + if (action === 'activate') + select(this).style('background', settings.DarkMode ? 'black' : 'white'); + }); - if (name == 'column:') { - elem.column = true; - elem.sub = []; - this.stack.push(elem.sub); - return; - } + if (!selected_frame) return; - if (name.indexOf('sub:') == 0) { - name = name.slice(4); - elem.sub = []; - this.stack.push(elem.sub); - } + if (action === 'activate') + selected_frame.parentNode.appendChild(selected_frame); + // super.activateFrame(selected_frame); + else if (action === 'close') { + const was_active = (selected_frame === this.getActiveFrame()); + cleanup(selected_frame); + selected_frame.remove(); - if (name.indexOf('chk:') == 0) { - elem.checked = true; - name = name.slice(4); - } else if (name.indexOf('unk:') == 0) { - elem.checked = false; - name = name.slice(4); + if (was_active) + this.activateFrame(other_frame); } - - elem.text = name; - elem.title = title; - elem.arg = arg; - elem.func = func; } - /** @summary Returns size of main menu */ - size() { return this.code.length; } - - /** @summary Build HTML elements of the menu - * @private */ - _buildContextmenu(menu, left, top, loc) { - - let outer = document.createElement('div'); - outer.className = 'jsroot_ctxt_container'; + /** @summary actiavte frame */ + activateFrame(frame) { + if (frame) + this.modifyTabsFrame(select(frame).property('frame_id'), 'activate'); + super.activateFrame(frame); + } - //if loc !== document.body then its a submenu, so it needs to have position: relative; - if (loc === document.body) { - //delete all elements with className jsroot_ctxt_container - let deleteElems = document.getElementsByClassName('jsroot_ctxt_container'); - while (deleteElems.length > 0) - deleteElems[0].parentNode.removeChild(deleteElems[0]); + /** @summary create new frame */ + createFrame(title) { + this.beforeCreateFrame(title); - outer.style.position = 'fixed'; - outer.style.left = left + 'px'; - outer.style.top = top + 'px'; + const dom = this.selectDom(); + let top = dom.select('.jsroot_tabs'), labels, main; - injectStyle( - `.jsroot_ctxt_container { - position: absolute; top: 0; user-select: none; z-index: 100000; background-color: rgb(250, 250, 250); margin: 0; padding: 0px; width: auto; - min-width: 100px; box-shadow: 0px 0px 10px rgb(0, 0, 0, 0.2); border: 3px solid rgb(215, 215, 215); font-family: Arial, helvetica, sans-serif, serif; - font-size: 13px; color: rgb(0, 0, 0, 0.8); - } - .jsroot_ctxt_column { float: left; } - .jsroot_ctxt_divider { width: 85%; margin: 3px auto; border: 1px solid rgb(0, 0, 0, 0.15); } - .jsroot_ctxt_header { background-color: lightblue; padding: 3px 7px; font-weight: bold; border-bottom: 1px; } - .jsroot_ctxt_text { margin: 0; padding: 3px 7px; pointer-events: none; white-space: nowrap; } - .jsroot_ctxt_extraText { margin: 0; padding: 3px 7px; color: rgb(0, 0, 0, 0.6); } - .jsroot_ctxt_focus { background-color: rgb(220, 220, 220); } - .jsroot_ctxt_item:hover { background-color: rgb(235, 235, 235); }`, this.element); - } else if ((left < 0) && (top == left)) { - // column - outer.className = 'jsroot_ctxt_column'; - outer.style.width = (100/-left).toFixed(1) + '%'; + if (top.empty()) { + top = dom.append('div').attr('class', 'jsroot_tabs') + .attr('style', 'display: flex; flex-direction: column; position: absolute; overflow: hidden; inset: 0px 0px 0px 0px'); + labels = top.append('div').attr('class', 'jsroot_tabs_labels') + .attr('style', 'white-space: nowrap; position: relative; overflow-x: auto'); + main = top.append('div').attr('class', 'jsroot_tabs_main') + .attr('style', 'margin: 0; flex: 1 1 0%; position: relative'); } else { - outer.style.left = -loc.offsetLeft + loc.offsetWidth + 'px'; + labels = top.select('.jsroot_tabs_labels'); + main = top.select('.jsroot_tabs_main'); } - let need_check_area = false, ncols = 0; - menu.forEach(d => { - if (d.checked) need_check_area = true; - if (d.column) ncols++; - }); - - menu.forEach(d => { - if (ncols > 0) { - outer.style.display = 'flex'; - if (d.column) this._buildContextmenu(d.sub, -ncols, -ncols, outer); - return; - } - - if (d.divider) { - let hr = document.createElement('hr'); - hr.className = 'jsroot_ctxt_divider'; - outer.appendChild(hr); - return; - } + const frame_id = this.cnt++, mdi = this; + let lbl = title; - let item = document.createElement('div'); - item.style.position = 'relative'; - outer.appendChild(item); + if (!lbl || !isStr(lbl)) lbl = `frame_${frame_id}`; - if (d.header) { - item.className = 'jsroot_ctxt_header'; - item.innerHTML = d.text; - return; - } + if (lbl.length > 15) { + let p = lbl.lastIndexOf('/'); + if (p === lbl.length-1) p = lbl.lastIndexOf('/', p-1); + if ((p > 0) && (lbl.length - p < 20) && (lbl.length - p > 1)) + lbl = lbl.slice(p+1); + else + lbl = '...' + lbl.slice(lbl.length-17); + } - let hovArea = document.createElement('div'); - hovArea.style.width = '100%'; - hovArea.style.height = '100%'; - hovArea.className = 'jsroot_ctxt_item'; - hovArea.style.display = 'flex'; - hovArea.style.justifyContent = 'space-between'; - hovArea.style.cursor = 'pointer'; - if (d.title) hovArea.setAttribute('title', d.title); + labels.append('span') + .attr('tabindex', 0) + .append('label') + .attr('class', 'jsroot_tabs_label') + .attr('style', 'border: 1px solid; display: inline-block; font-size: 1rem; left: 1px;'+ + 'margin-left: 3px; padding: 0px 5px 1px 5px; position: relative; vertical-align: bottom;') + .property('frame_id', frame_id) + .text(lbl) + .attr('title', title) + .on('click', function(evnt) { + evnt.preventDefault(); // prevent handling in close button + mdi.modifyTabsFrame(select(this).property('frame_id'), 'activate'); + }).append('button') + .attr('title', 'close') + .attr('style', 'margin-left: .5em; padding: 0; font-size: 0.5em; width: 1.8em; height: 1.8em; vertical-align: center;') + .html('✕') + .on('click', function() { + mdi.modifyTabsFrame(select(this.parentNode).property('frame_id'), 'close'); + }); - item.appendChild(hovArea); - if (!d.text) d.text = 'item'; + const draw_frame = main.append('div') + .attr('frame_title', title) + .attr('class', 'jsroot_tabs_draw') + .attr('style', 'overflow: hidden; position: absolute; inset: 0px') + .property('frame_id', frame_id); - let text = document.createElement('div'); - text.className = 'jsroot_ctxt_text'; + this.modifyTabsFrame(frame_id, 'activate'); - if (d.text.indexOf('= 0) { - if (need_check_area) { - text.style.display = 'flex'; + return this.afterCreateFrame(draw_frame.node()); + } - let chk = document.createElement('span'); - chk.innerHTML = d.checked ? '\u2713' : ''; - chk.style.display = 'inline-block'; - chk.style.width = '1em'; - text.appendChild(chk); + /** @summary Handle changes in dark mode */ + changeDarkMode() { + const frame = this.getActiveFrame(); + this.modifyTabsFrame(select(frame).property('frame_id'), 'activate'); + } - let sub = document.createElement('div'); - sub.innerHTML = d.text; - text.appendChild(sub); - } else { - text.innerHTML = d.text; - } +} // class TabsDisplay - } else { - if (need_check_area) { - let chk = document.createElement('span'); - chk.innerHTML = d.checked ? '\u2713' : ''; - chk.style.display = 'inline-block'; - chk.style.width = '1em'; - text.appendChild(chk); - } - let sub = document.createElement('span'); - if (d.text.indexOf('') == 0) - sub.textContent = d.text.slice(6, d.text.length-7); - else - sub.textContent = d.text; - text.appendChild(sub); +/** + * @summary Generic flexible MDI display + * + * @private + */ - } +class FlexibleDisplay extends MDIDisplay { - hovArea.appendChild(text); + constructor(frameid) { + super(frameid); + this.cnt = 0; // use to count newly created frames + this.selectDom().on('contextmenu', evnt => this.showContextMenu(evnt)) + .style('overflow', 'auto'); + } - if (d.hasOwnProperty('extraText') || d.sub) { - let extraText = document.createElement('span'); - extraText.className = 'jsroot_ctxt_extraText jsroot_ctxt_text'; - extraText.textContent = d.sub ? '\u25B6' : d.extraText; - hovArea.appendChild(extraText); - } + /** @summary Cleanup all drawings */ + cleanup() { + this.selectDom().style('overflow', null) + .on('contextmenu', null); + this.cnt = 0; + super.cleanup(); + } - hovArea.addEventListener('mouseenter', () => { - let focused = outer.childNodes; - focused.forEach(d => { - if (d.classList.contains('jsroot_ctxt_focus')) { - d.removeChild(d.getElementsByClassName('jsroot_ctxt_container')[0]); - d.classList.remove('jsroot_ctxt_focus'); - } - }); - }); + /** @summary call function for each frame */ + forEachFrame(userfunc, only_visible) { + if (!isFunc(userfunc)) return; - if (d.sub) - hovArea.addEventListener('mouseenter', () => { - item.classList.add('jsroot_ctxt_focus'); - this._buildContextmenu(d.sub, 0, 0, item); - }); + const mdi = this, top = this.selectDom().select('.jsroot_flex_top'); + top.selectAll('.jsroot_flex_draw').each(function() { + // check if only visible specified + if (only_visible && (mdi.getFrameState(this) === 'min')) return; - if (d.func) - item.addEventListener('click', evnt => { - let func = this.painter ? d.func.bind(this.painter) : d.func; - func(d.arg); - evnt.stopPropagation(); - this.remove(); - }); + userfunc(this); }); + } - loc.appendChild(outer); + /** @summary return active frame */ + getActiveFrame() { + let found = super.getActiveFrame(); + if (found && select(found.parentNode).property('state') !== 'min') return found; - let docWidth = document.documentElement.clientWidth, docHeight = document.documentElement.clientHeight; + found = null; + this.forEachFrame(frame => { found = frame; }, true); + return found; + } - //Now determine where the contextmenu will be - if (loc === document.body) { - if (left + outer.offsetWidth > docWidth) { - //Does sub-contextmenu overflow window width? - outer.style.left = (docWidth - outer.offsetWidth) + 'px'; - } - if (outer.offsetHeight > docHeight) { - //is the contextmenu height larger than the window height? - outer.style.top = 0; - outer.style.overflowY = 'scroll'; - outer.style.overflowX = 'hidden'; - outer.style.height = docHeight + 'px'; - } else if (top + outer.offsetHeight > docHeight) { - //Does contextmenu overflow window height? - outer.style.top = (docHeight - outer.offsetHeight) + 'px'; - } + /** @summary actiavte frame */ + activateFrame(frame) { + if ((frame === 'first') || (frame === 'last')) { + let res = null; + this.forEachFrame(f => { if (frame === 'last' || !res) res = f; }, true); + frame = res; + } + if (!frame) return; + if (frame.getAttribute('class') !== 'jsroot_flex_draw') return; - } else if (outer.className != 'jsroot_ctxt_column') { + if (this.getActiveFrame() === frame) return; - //if its sub-contextmenu - let dimensionsLoc = loc.getBoundingClientRect(), dimensionsOuter = outer.getBoundingClientRect(); + super.activateFrame(frame); - //Does sub-contextmenu overflow window width? - if (dimensionsOuter.left + dimensionsOuter.width > docWidth) { - outer.style.left = (-loc.offsetLeft - dimensionsOuter.width) + 'px'; - } + const main = frame.parentNode; + main.parentNode.append(main); - if (dimensionsOuter.height > docHeight) { - //is the sub-contextmenu height larger than the window height? - outer.style.top = -dimensionsOuter.top + 'px'; - outer.style.overflowY = 'scroll'; - outer.style.overflowX = 'hidden'; - outer.style.height = docHeight + 'px'; - } else if (dimensionsOuter.height < docHeight && dimensionsOuter.height > docHeight / 2) { - //is the sub-contextmenu height smaller than the window height AND larger than half of window height? - if (dimensionsOuter.top - docHeight / 2 >= 0) { //If sub-contextmenu is closer to bottom of the screen - outer.style.top = (-dimensionsOuter.top - dimensionsOuter.height + docHeight) + 'px'; - } else { //If sub-contextmenu is closer to top of the screen - outer.style.top = (-dimensionsOuter.top) + 'px'; - } - } else if (dimensionsOuter.top + dimensionsOuter.height > docHeight) { - //Does sub-contextmenu overflow window height? - outer.style.top = (-dimensionsOuter.height + dimensionsLoc.height) + 'px'; - } + if (this.getFrameState(frame) !== 'min') { + selectActivePad({ pp: getElementCanvPainter(frame), active: true }); + resize(frame); } - return outer; } - /** @summary Show standalone menu */ - async show(event) { - this.remove(); - - if (!event && this.show_evnt) event = this.show_evnt; - - document.body.addEventListener('click', this.remove_handler); - - let oldmenu = document.getElementById(this.menuname); - if (oldmenu) oldmenu.remove(); + /** @summary get frame state */ + getFrameState(frame) { + const main = select(frame.parentNode); + return main.property('state'); + } - this.element = this._buildContextmenu(this.code, (event?.clientX || 0) + window.pageXOffset, (event?.clientY || 0) + window.pageYOffset, document.body); + /** @summary returns frame rect */ + getFrameRect(frame) { + if (this.getFrameState(frame) === 'max') { + const top = this.selectDom().select('.jsroot_flex_top'); + return { x: 0, y: 0, w: top.node().clientWidth, h: top.node().clientHeight }; + } - this.element.setAttribute('id', this.menuname); + const main = select(frame.parentNode), left = main.style('left'), top = main.style('top'); - return this; + return { x: parseInt(left.slice(0, left.length-2)), y: parseInt(top.slice(0, top.length-2)), + w: main.node().clientWidth, h: main.node().clientHeight }; } - /** @summary Run modal elements with standalone code */ - async runModal(title, main_content, args) { - if (!args) args = {}; - let dlg_id = this.menuname + '_dialog'; - select(`#${dlg_id}`).remove(); - select(`#${dlg_id}_block`).remove(); + /** @summary change frame state */ + changeFrameState(frame, newstate, no_redraw) { + const main = select(frame.parentNode), + state = main.property('state'), + top = this.selectDom().select('.jsroot_flex_top'); - let block = select('body').append('div').attr('id', dlg_id+'_block').attr('class', 'jsroot_dialog_block'); + if (state === newstate) + return false; - let element = select('body') - .append('div') - .attr('id',dlg_id) - .attr('class','jsroot_dialog').style('width',(args.width || 450) + 'px') - .attr('tabindex', '0') - .html( - `
-
${title}
-
${main_content}
- -
`); + if (state === 'normal') + main.property('original_style', main.attr('style')); - injectStyle( - `.jsroot_dialog_block { z-index: 100000; position: absolute; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.2; background-color: white; } - .jsroot_dialog { z-index: 100001; position: absolute; left: 50%; top: 50%; } - .jsroot_dialog_body { position: relative; left: -50%; top: -50%; border: solid green 3px; padding: 5px; display: flex; flex-flow: column; background-color: white; } - .jsroot_dialog_header { flex: 0 1 auto; padding: 5px; } - .jsroot_dialog_content { flex: 1 1 auto; padding: 5px; } - .jsroot_dialog_footer { flex: 0 1 auto; padding: 5px; } - .jsroot_dialog_button { float: right; margin-right: 1em; }`, element.node()); + // clear any previous settings + top.style('overflow', null); - return new Promise(resolveFunc => { - element.on('keyup', evnt => { - if ((evnt.code == 'Enter') || (evnt.code == 'Escape')) { - evnt.preventDefault(); - evnt.stopPropagation(); - resolveFunc(evnt.code == 'Enter' ? element.node() : null); - element.remove(); - block.remove(); - } - }); - element.on('keydown', evnt => { - if ((evnt.code == 'Enter') || (evnt.code == 'Escape')) { - evnt.preventDefault(); - evnt.stopPropagation(); - } - }); - element.selectAll('.jsroot_dialog_button').on('click', evnt => { - resolveFunc(args.btns && (select(evnt.target).text() == 'Ok') ? element.node() : null); - element.remove(); - block.remove(); - }); + switch (newstate) { + case 'min': + main.style('height', 'auto').style('width', 'auto'); + main.select('.jsroot_flex_draw').style('display', 'none'); + break; + case 'max': + main.style('height', '100%').style('width', '100%').style('left', '').style('top', ''); + main.select('.jsroot_flex_draw').style('display', null); + top.style('overflow', 'hidden'); + break; + default: + main.select('.jsroot_flex_draw').style('display', null); + main.attr('style', main.property('original_style')); + } - let f = element.select('.jsroot_dialog_content').select('input'); - if (f.empty()) f = element.select('.jsroot_dialog_footer').select('button'); - if (!f.empty()) f.node().focus(); + main.select('.jsroot_flex_header').selectAll('button').each(function(d) { + const btn = select(this); + if (((d.t === 'minimize') && (newstate === 'min')) || + ((d.t === 'maximize') && (newstate === 'max'))) + btn.html('▞').attr('title', 'restore'); + else + btn.html(d.n).attr('title', d.t); }); - } -} // class StandaloneMenu + main.property('state', newstate); + main.select('.jsroot_flex_resize').style('display', (newstate === 'normal') ? null : 'none'); -/** - * @summary Context menu class using Bootstrap - * - * @desc Use {@link createMenu} to create instance of the menu - * @private - */ + // adjust position of new minified rect + if (newstate === 'min') { + const rect = this.getFrameRect(frame), + top = this.selectDom().select('.jsroot_flex_top'), + ww = top.node().clientWidth, + hh = top.node().clientHeight, + arr = [], step = 4, + crossX = (r1, r2) => ((r1.x <= r2.x) && (r1.x + r1.w >= r2.x)) || ((r2.x <= r1.x) && (r2.x + r2.w >= r1.x)), + crossY = (r1, r2) => ((r1.y <= r2.y) && (r1.y + r1.h >= r2.y)) || ((r2.y <= r1.y) && (r2.y + r2.h >= r1.y)); -class BootstrapMenu extends JSRootMenu { + this.forEachFrame(f => { if ((f!==frame) && (this.getFrameState(f) === 'min')) arr.push(this.getFrameRect(f)); }); - constructor(painter, menuname, show_event) { - super(painter, menuname, show_event); + rect.y = hh; + do { + rect.x = step; + rect.y -= rect.h + step; + let maxx = step, iscrossed = false; + arr.forEach(r => { + if (crossY(r, rect)) { + maxx = Math.max(maxx, r.x + r.w + step); + if (crossX(r, rect)) iscrossed = true; + } + }); + if (iscrossed) rect.x = maxx; + } while ((rect.x + rect.w > ww - step) && (rect.y > 0)); + if (rect.y < 0) { rect.x = step; rect.y = hh - rect.h - step; } - this.code = ''; - this.funcs = {}; - this.lvl = 0; - } + main.style('left', rect.x + 'px').style('top', rect.y + 'px'); + } else if (!no_redraw) + resize(frame); - /** @summary Load bootstrap functionality, required for menu - * @private */ - loadBS(with_js) { - let ext = 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/'; - let promise = internals.bs_path ? Promise.resolve(true) : - loadScript(exports.source_dir + 'style/bootstrap.min.css') - .then(() => { internals.bs_path = exports.source_dir + 'scripts/'; }) - .catch(() => { internals.bs_path = ext + 'js/'; return loadScript(ext + 'css/bootstrap.min.css'); }); - return promise.then(() => (!with_js || (typeof bootstrap != 'undefined')) ? true : loadScript(internals.bs_path + 'bootstrap.bundle.min.js')); + return true; } - /** @summary Load bootstrap functionality */ - load() { return this.loadBS().then(() => this); } + /** @summary handle button click + * @private */ + _clickButton(btn) { + const kind = select(btn).datum(), + main = select(btn.parentNode.parentNode), + frame = main.select('.jsroot_flex_draw').node(); - /** @summary Add menu item - * @param {string} name - item name - * @param {function} func - func called when item is selected */ - add(name, arg, func, title) { - if (name == 'separator') { - this.code += ''; + if (kind.t === 'close') { + this.cleanupFrame(frame); + main.remove(); + this.activateFrame('last'); // set active as last non-minfied window return; } - if ((name == 'column:') || (name == 'endcolumn:')) - return; - - if (name.indexOf('header:') == 0) { - this.code += ``; - return; - } + const state = main.property('state'); + let newstate; + if (kind.t === 'maximize') + newstate = (state === 'max') ? 'normal' : 'max'; + else + newstate = (state === 'min') ? 'normal' : 'min'; - let newlevel = false, extras = '', cl = 'dropdown-item btn-sm', checked = ''; + if (this.changeFrameState(frame, newstate)) + this.activateFrame(newstate !== 'min' ? frame : 'last'); + } - if (name == 'endsub:') { - this.lvl--; - this.code += ''; - this.code += ''; - return; - } - if (name.indexOf('sub:') == 0) { name = name.slice(4); newlevel = true; } + /** @summary create new frame */ + createFrame(title) { + this.beforeCreateFrame(title); - if (isFunc(arg)) { func = arg; arg = name; } + const mdi = this, + dom = this.selectDom(); + let top = dom.select('.jsroot_flex_top'); - if (name.indexOf('chk:') == 0) { - checked = '\u2713'; - name = name.slice(4); - } else if (name.indexOf('unk:') == 0) { - name = name.slice(4); + if (top.empty()) { + top = dom.append('div') + .attr('class', 'jsroot_flex_top') + .attr('style', 'overflow: auto; position: relative; height: 100%; width: 100%'); } - if (title) extras += ` title="${title}"`; - if (arg !== undefined) extras += ` arg="${arg}"`; - if (newlevel) { extras += ` data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded='false'`; cl += ' dropdown-toggle'; } - - let item = ``; - - if (newlevel) item = `
  • ${item}`; - else item = `
  • ${item}
  • `; - - this.code += item; + const w = top.node().clientWidth, + h = top.node().clientHeight, + main = top.append('div'); - if (newlevel) { - this.code += `
    '; - return; - } - if (name.indexOf('sub:') == 0) { name = name.slice(4); newlevel = true; } - - if (isFunc(arg)) { func = arg; arg = name; } - - if (name.indexOf('chk:') == 0) { - checked = '\u2713'; - name = name.slice(4); - } else if (name.indexOf('unk:') == 0) { - name = name.slice(4); - } - - if (title) extras += ` title="${title}"`; - if (arg !== undefined) extras += ` arg="${arg}"`; - if (newlevel) { extras += ` data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded='false'`; cl += ' dropdown-toggle'; } - - let item = ``; - - if (newlevel) item = `
  • ${item}`; - else item = `
  • ${item}
  • `; - - this.code += item; - - if (newlevel) { - this.code += `
    DATA AND CATEGORIES
      @@ -119,7 +119,7 @@

      Miscellaneous small improvements

    • RooDataHist - Add new named argument constructor that can collate multiple ROOT THn histgrams into a n+1 dimensional RooDataHist

    • RooDataSet - Add new named argument constructor that can collate multiple input RooDataSets into a n+1 dimensional RooDataSet.
      Add createHistogram() method for simplified plotting

    • RooFitResult - Add new method correlationHist() that returns a labeled TH2 with the contents of the fit correlation matrix

      -
    • RooFFTConvPdf - Automatically put sampling windows of 'resolution model' p.d.f. centered around zero, even if fit range of convolution observable does not bracket zero. Improve internal effeciency

      +
    • RooFFTConvPdf - Automatically put sampling windows of 'resolution model' p.d.f. centered around zero, even if fit range of convolution observable does not bracket zero. Improve internal efficiency

    • RooAbsData - Add ability to plot efficiency distribution with correct binomial errors given a RooRealVar and a RooCategory category observable encoding distribution and accept/reject state respectively. See rf701_efficiencyfit.C for details

    • RooAbsPdf - Included extended ML term by default in fit if p.d.f is extendable. You can still use Extended() to override default behavior. Do not run MINOS by default anymore if no fit options are provided.

    • RooProfileLL - Add option to always start minimization from global minimimum (takes more time, but improves reproducibility). Can now profile multi-core paralellized likelihoods as well.

      @@ -164,7 +164,7 @@

      RooStats concrete classes

    • HybridCalculator: hypothesis test calculator using a Bayesian-frequentist hybrid method (often called in HEP as CLs method). This class extends the functionality of the TLimit class by taking advantage of the RooFit package. The result of the calculator is returned as an HybridResult pointer. HybridResult implements the HypoTestResult interface. The class HybridPlot allows for a graphical representation of a HybridResult.
      - HybridCalculator implements the interface class HypoTestCalculator. A contructor exists taking as input the pdf's (expressed as RooAbsPdf instances) for the signal+background (alternate) and backgorund only (null) hypothesis and the data set (as RooAbsData instance). One can provide optionally also the nuisance parameters and its pdf which will be marginalized by the calculator. The HypoTestCalculator interface provides also the possibility of setting the model via a Rooworkspace class and names of the pdf. This possibility is not yet supported for the HybridCalculator class. + HybridCalculator implements the interface class HypoTestCalculator. A constructor exists taking as input the pdf's (expressed as RooAbsPdf instances) for the signal+background (alternate) and background only (null) hypothesis and the data set (as RooAbsData instance). One can provide optionally also the nuisance parameters and its pdf which will be marginalized by the calculator. The HypoTestCalculator interface provides also the possibility of setting the model via a Rooworkspace class and names of the pdf. This possibility is not yet supported for the HybridCalculator class.
    @@ -188,4 +188,4 @@

    RooStats tutorials macros

    - \ No newline at end of file + diff --git a/roofit/doc/v524/index.html b/roofit/doc/v524/index.html index d69f688d12460..a18460c233dba 100644 --- a/roofit/doc/v524/index.html +++ b/roofit/doc/v524/index.html @@ -21,7 +21,7 @@

    Error visualization

    Two techniques for error visualization are implemented. The default is -linear error progation, and results in an error band that is by +linear error propagation, and results in an error band that is by construction symmetric. The linear error is calculated as
     
    @@ -45,7 +45,7 @@ 

    Error visualization

    parameter values, as sampled from a multi-variate Gaussian p.d.f. that is constructed from the fit results covariance matrix. The error(x) is determined by calculating a central interval that capture N% of the -variations for each valye of x, where N% is controlled by Z (i.e. Z=1 +variations for each value of x, where N% is controlled by Z (i.e. Z=1 gives N=68%). The number of sampling curves is chosen to be such that at least 100 curves are expected to be outside the N% interval. Intervals from the sampling method can be asymmetric, and may perform better in the @@ -119,7 +119,7 @@

    New minimizer interface to Minuit2, GSLMinimizer etc...

    New numeric integration algorithms available

    -

    RooFit can now interface all MathCore numeric intergration +

    RooFit can now interface all MathCore numeric integration algorithms. In this release ROOT::Math::AdaptiveIntegratorMultiDim, which implements the 'Genz & Malik' algorithm has been interfaced in RooAdaptiveIntegratorND and is now the default numeric integrator @@ -395,7 +395,7 @@

    Various workspace improvements

    New object factory interface to workspace to facilitate script driven model definition

    -

    A object factory has been added to RooFit to simplify the proces of creating p.d.f. +

    A object factory has been added to RooFit to simplify the process of creating p.d.f. and function expressions consisting of multiple objects. The factory has two goals: the first is to provide a back-end for higher level factories and tools to process the creation of objects. The second is to provide a simple end-user language to @@ -500,7 +500,7 @@

    Compact demo of several new major features

  • workspace CINT interface to easily access contents in a typesafe way
  • new adaptive ND numeric integration technique to normalize arbitrary p.d.f. in fast and reliable way -
  • new adapative TFoam sampling technique to efficiently generate toy MC data from strongly +
  • new adaptive TFoam sampling technique to efficiently generate toy MC data from strongly peaked datasets
  • parallel processing in likelihood construction and use of profile likelihood operator to represent profile likelihoods as regular RooFit functions @@ -589,7 +589,7 @@

    New Tutorials

    implementation
  • rs401c_FeldmanCousins.C Demonstrates use of FeldmanCousins interval calculator with a Poisson problem, reproduces -resulst from table IV and V of the original +results from table IV and V of the original paper Phys.Rev.D57:3873-3889,1998.
  • rs401d_FeldmanCousins.C Demonstrates use of FeldmanCousins interval calculator with the neutrino oscillation toy @@ -717,7 +717,7 @@

    Bernstein Correction

    in the approach was  to provide a well defined algorithm that specifies the order of polynomial to be included  -in the correction.  This is an emperical algorithm, so in addition to the +in the correction.  This is an empirical algorithm, so in addition to the nominal model it  needs either a real data set or a simulated one.  In the early work, the nominal model was taken diff --git a/roofit/doc/v526/index.html b/roofit/doc/v526/index.html index 32dfa76716e64..c88a0173365e8 100644 --- a/roofit/doc/v526/index.html +++ b/roofit/doc/v526/index.html @@ -73,7 +73,7 @@

    Workspace and factory improvements

  • The Print() method now accepts option "t", which prints the contents tree-style instead of a flat list of components, - as ilustrated below + as illustrated below
     *** Print() ***
     
    @@ -219,8 +219,8 @@ 

    Miscellaneous improvements data classes

  • The RooHist class that represents data as a histogram in a RooPlot has been modified - so that it can show approximate Poisson errors for non-integer data. Thes approximate - error are calculated from interpolation of the error bars of the nearest integers. NB: A weighted dataset + so that it can show approximate Poisson errors for non-integer data. These approximate + errors are calculated from interpolation of the error bars of the nearest integers. NB: A weighted dataset plotted with RooAbsData::plotOn() will be default show sum-of-weights-squared errors. Only when Poisson error are forced through a DataError(RooAbsData::Poisson) argument these approximate Poisson error bars are shown
  • @@ -245,7 +245,7 @@

    Miscellaneous improvements other

    RooStats

    This release contains significant bug fixes and it is strongly -reccomended to update to this version if using older ones. +recommended to update to this version if using older ones.

    Major Changes in LimitCalculator and HypoTestCalculator classes: usage of ModelConfig class

    diff --git a/roofit/doc/v528/index.html b/roofit/doc/v528/index.html index 33d5c6b2eef8a..2a1c86953286f 100644 --- a/roofit/doc/v528/index.html +++ b/roofit/doc/v528/index.html @@ -5,7 +5,7 @@

    RooFit

    • Assorted small bug fixes have been applied. No major new features have been introduced since 5.26
    • -
    • Normalization of
    • RooRealSumPdf
    • changed from sum of coefficents to sum of coefficients*integrals of input functions. +
    • Normalization of
    • RooRealSumPdf
    • changed from sum of coefficients to sum of coefficients*integrals of input functions.
    • New PDF RooNonCentralChiSquare which is useful for asymptotic analysis of likelihood ratio tests -- like expected significance and error bands.
    • Ability to "seal" data in RooNLLVar, so that an experiment can publish likleihood functions without exposing the data necessary to evaluate the likelihood function.
    @@ -38,7 +38,7 @@

    Top-Level XML File

  • what is the relative uncertainty on the luminosity
  • what is (are) the parameter(s) of interest that will be measured
  • which parameters should be fixed/floating (eg. nuisance parameters) -
  • which type of constriants are desired +
  • which type of constraints are desired
    • Gaussian by default
    • Gamma, LogNormal, and Uniform @@ -158,7 +158,7 @@

      TestStatSampler and TestStatistics

      • Cleanup of the interfaces.
      • TestStatistics now have a method PValueIsRightTail to specify the sign conventions for the test statistic. This is used when making plots and calculating p-values.
      • -
      • make clear that TestStatistic::Evaluate should take data and values of the parameters that defien the null.
      • +
      • make clear that TestStatistic::Evaluate should take data and values of the parameters that define the null.
      • Add method TestStatSampler::SetParametersForTestStat that allows for greater control of parameters used for generating toy data and parameters used for evaluating the test statistic.
      • @@ -168,7 +168,7 @@

        TestStatSampler and TestStatistics

        • SimpleLikelihoodRatioTestStat : log L_1 / L_0
        • RatioOfProfiledLikelihoodsTestStat: log L(mu_1, hat(nu_1))/L(mu_0,hat(nu_0))
        • -
        • MaxLikelihoodEstiamteTestStat: the MLE of a specified parameter
        • +
        • MaxLikelihoodEstimateTestStat: the MLE of a specified parameter
        @@ -229,7 +229,7 @@

        New Tutorials

        • IntervalExamples.C: Standard Gaussian with known answer using 4 techniques
        • FourBinInstructional.C: Example of a standard data-driven approach for estimating backgrounds. A lot of discussion.
        • -
        • HybridInstructional.C: Example of protoype on/off problem with a data-driven background estimate. A lot of discussion
        • +
        • HybridInstructional.C: Example of prototype on/off problem with a data-driven background estimate. A lot of discussion
        • HybridStandardForm.C: Variant on above in 'standard form'
        • MultivariateGaussianTest.C: A validation example with an N-D multivariate Gaussian
        diff --git a/roofit/doc/v530/index.html b/roofit/doc/v530/index.html index 4a1795f85b1d7..049720305a4cc 100644 --- a/roofit/doc/v530/index.html +++ b/roofit/doc/v530/index.html @@ -16,7 +16,7 @@

        HistFactory

      • code = 1: piece-wise log (new default)
      • code = 2: parabolic interp with linear extrap ( common at tevatron, avoids kink for asymmetric uncert)
      -The piece-wise logarithmic interpolation paired with a Gaussian constraint is equivalent to a log-normal constraint in a transformed version of the nuisance parameter. The benifit of this approach is that it is easy to avoid the normalization from taking on unphysical negative values. This is the prescription used by the CMS Higgs group, and agreed upon by the LHC Higgs Combination Group. +The piece-wise logarithmic interpolation paired with a Gaussian constraint is equivalent to a log-normal constraint in a transformed version of the nuisance parameter. The benefit of this approach is that it is easy to avoid the normalization from taking on unphysical negative values. This is the prescription used by the CMS Higgs group, and agreed upon by the LHC Higgs Combination Group. There is not yet XML-based steering for the different interpolation types, but there is a simple script to modify it.
      @@ -111,4 +111,4 @@ 

      BayesianCalculator

      (ADAPTIVE, VEGAS, MISER, PLAIN for multi-dimension). In addition one can use an integration types by generating nuisance toy MC (method TOYMC). If the nuisance parameters are uncorrelated, this last method can scale up for a large number of nuisance parameters. It has been tested to work up to 50-100 parameters. - \ No newline at end of file + diff --git a/roofit/doc/v532/index.html b/roofit/doc/v532/index.html index 8e657f0036d28..f1a7788a7b21b 100644 --- a/roofit/doc/v532/index.html +++ b/roofit/doc/v532/index.html @@ -10,7 +10,7 @@

      RooFit Package

      transparent to end-use cases
        -
      • New implementation of RooFit data types. The implentation of data stored in RooDataSet and RooDataHist +

      • New implementation of RooFit data types. The implementation of data stored in RooDataSet and RooDataHist was historically handled by ROOT TTrees (though class RooTreeDataStore). The default storage type has now been changed to class RooVectorDataStore which stores the information in STL arrays. Existing datasets based on trees can be read in transparently, and are converted to vector form in the @@ -20,7 +20,7 @@

        RooFit Package

        faster than for TTrees), 2) ability to rewrite columns on the fly. The first advantage is important for the existing constant-term precalculation optimization in roofit likelihoods as these are now also stored in vectors rather than trees. The faster access speed of vectors make that the constant - term optimization inside likelihoods results in a larger speed increase. This is particulatly noticable in pdfs with + term optimization inside likelihoods results in a larger speed increase. This is particulatly noticeable in pdfs with many constant expressions from pdfs that were moderately fast to begin with (e.g. RooHistPdf). The second advantages allows new types of algorithmic likelihood optimization in RooFit detailed below.

      • @@ -33,7 +33,7 @@

        RooFit Package

        For composite pdfs a further optimization has been included: for a M(x,a,b) = f*F(x,a)+(1-f)G(x,b) it is e.g. not needed to recalculate G(x,b) if only parameter a has changed w.r.t to the previous likelihood - calculation. This optimization is now implemented by extending the value caching orignally designed + calculation. This optimization is now implemented by extending the value caching originally designed for constant terms to be usable for non-constant terms, with a check executed at the beginning of each likelihood evaluation if selected columns need to be updated because parameters have changed. The speed gain of this optimization depends much on the structure of the pdf: in models with many free parameters most of the @@ -73,7 +73,7 @@

        RooFit Package

        but it is also possible to generate other component pdfs forcibly binned by adding GenBinned(tagname) to generate(). In that case all component pdfs labeled with pdf->setAttribute(tagname) will be generated binned. To generate all component binned, the shorthand method AllBinned() can be used. All binned - datasets made by generate are repesented as weighted unbinned datasets (of type RooDataSet) rather + datasets made by generate are represented as weighted unbinned datasets (of type RooDataSet) rather than binned datasets of type RooDataHist so that mixed binned/unbinned data is always represented through a uniform interface. @@ -84,7 +84,7 @@

        RooFit Package

        terms were erroneously recalculated even if no relevant parameters was changed.
      • General performance tuning of RooFit to reduce computational overhead. Extensive profiling of - CPU times in call graphas and and analysis heap memory use have been performed and many small + CPU times in call graphas and analysis heap memory use have been performed and many small changes have been made to make the code more efficient and use less memory.
      @@ -102,7 +102,7 @@

      AsymptoticCalculator

    • The Asimov data set is generated with the utility function AsymptoticCalculator::MakeAsimovData and then it is used to evaluate the likelihood.
    • -
    • This class implements the HypoTestCalculatorGeneric interface and can be used as an alternative Hypotesis test +
    • This class implements the HypoTestCalculatorGeneric interface and can be used as an alternative Hypothesis test calculator in the HypoTestInverter class. It can then plugged in the HypoTestInverter for computing asymptotic CLs and CLs+b limits. In this way the limits will be computed by just performing a fit for each test parameter value and without generating any toys. diff --git a/roofit/histfactory/CMakeLists.txt b/roofit/histfactory/CMakeLists.txt index 15bc3a1f63d13..87522be34dc48 100644 --- a/roofit/histfactory/CMakeLists.txt +++ b/roofit/histfactory/CMakeLists.txt @@ -17,11 +17,17 @@ if (xml) set(HISTFACTORY_XML_LIBRARIES XMLParser) endif() +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(HistFactory HEADERS RooStats/HistFactory/Asimov.h RooStats/HistFactory/Channel.h RooStats/HistFactory/Data.h + RooStats/HistFactory/Detail/HistFactoryImpl.h RooStats/HistFactory/FlexibleInterpVar.h RooStats/HistFactory/HistFactoryException.h RooStats/HistFactory/HistFactoryModelUtils.h @@ -43,6 +49,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(HistFactory src/Channel.cxx src/Data.cxx src/FlexibleInterpVar.cxx + src/HistFactoryImpl.cxx src/HistFactoryModelUtils.cxx src/HistFactoryNavigation.cxx src/HistoToWorkspaceFactoryFast.cxx @@ -73,6 +80,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(HistFactory Graf Gpad RooStats + ${EXTRA_DICT_OPTS} ) # For recent clang, this can facilitate auto-vectorisation. @@ -94,8 +102,13 @@ if(xml) ) endif() -file(COPY config/prepareHistFactory DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) -install(FILES ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/prepareHistFactory +if(MSVC) + set(prepareHistFactory_script prepareHistFactory.bat) +else() + set(prepareHistFactory_script prepareHistFactory) +endif() +file(COPY config/${prepareHistFactory_script} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +install(FILES ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${prepareHistFactory_script} PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ WORLD_EXECUTE WORLD_READ diff --git a/roofit/histfactory/config/prepareHistFactory.bat b/roofit/histfactory/config/prepareHistFactory.bat new file mode 100644 index 0000000000000..ba6700ab420cd --- /dev/null +++ b/roofit/histfactory/config/prepareHistFactory.bat @@ -0,0 +1,53 @@ +@echo off +setlocal enabledelayedexpansion + +rem HistFactory workplace setup script + +for /f "tokens=*" %%g in ('root-config --etcdir') do (set ROOTETCDIR=%%g) +echo Using etcdir !ROOTETCDIR! +for /f "tokens=*" %%g in ('root-config --tutdir') do (set ROOTTUTDIR=%%g) +echo Using tutorials dir !ROOTTUTDIR! + +if not "%1" == "" ( + set DIR=%~1 + echo HistFactory workplace will be created in: !DIR! +) else ( + set DIR=. + echo HistFactory workplace will be created in the current directory +) + +echo "Creating directory structure..." +mkdir !DIR!\config +mkdir !DIR!\config\examples +mkdir !DIR!\data +mkdir !DIR!\results + +echo "Copying skeleton configuration files..." +copy !ROOTETCDIR!\HistFactorySchema.dtd !DIR!\config\ +copy !ROOTTUTDIR!\histfactory\example.xml !DIR!\config\ +copy !ROOTTUTDIR!\histfactory\example_channel.xml !DIR!\config\ + +copy !ROOTETCDIR!\HistFactorySchema.dtd !DIR!\config\examples +copy !ROOTTUTDIR!\histfactory\example_Expression.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_Expression_channel.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_ShapeSys.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_ShapeSys_channel.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_ShapeSys2D.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_ShapeSys2D_channel.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_DataDriven.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_DataDriven_signalRegion.xml !DIR!\config\examples\ +copy !ROOTTUTDIR!\histfactory\example_DataDriven_controlRegion.xml !DIR!\config\examples\ + +rem echo "Making skeleton data files..." +root.exe -b -q !ROOTTUTDIR!\histfactory\makeExample.C +move ShapeSys.root !DIR!\data\ +move ShapeSys2D.root !DIR!\data\ +move StatError.root !DIR!\data\ +move dataDriven.root !DIR!\data\ +move example.root !DIR!\data\ + +echo Done! +rem echo "You can run the example with: hist2workspace !DIR!\config\example.xml" + +exit /b 0 + diff --git a/roofit/histfactory/doc/README b/roofit/histfactory/doc/README index c4bb351e68b75..a32b9cfad3479 100644 --- a/roofit/histfactory/doc/README +++ b/roofit/histfactory/doc/README @@ -10,7 +10,7 @@ This package was written by V2 Update (Feb. 2011) The original HistFactory made models that consisted of a Poisson term for each bin. -In this "number counting form" the dataset has one row and the collumns corresponded to the number of +In this "number counting form" the dataset has one row and the columns corresponded to the number of events for each bin. This led to severe performance problems in statistical tools that generated pseudo-experiments and evaluated likelihood ratio test statistics. Now the HistFactory can produce the equivalent model as an ExtendedPdf, with a histogram shape and an overall Poisson for the total number of events. diff --git a/roofit/histfactory/inc/LinkDef.h b/roofit/histfactory/inc/LinkDef.h index a3403a9980b32..8f6523e796b4f 100644 --- a/roofit/histfactory/inc/LinkDef.h +++ b/roofit/histfactory/inc/LinkDef.h @@ -44,6 +44,11 @@ targetClass="RooStats::HistFactory::HistoSys" target="" \ code="{newObj->SetHistoLow ( onfile.fhLow.ReleaseObject() ); \ newObj->SetHistoHigh( onfile.fhHigh.ReleaseObject() ); }" +#pragma link C++ class RooStats::HistFactory::OverallSys+ ; +#pragma link C++ class RooStats::HistFactory::NormFactor+ ; +#pragma link C++ class RooStats::HistFactory::HistoFactor+ ; +#pragma link C++ class RooStats::HistFactory::ShapeSys+ ; +#pragma link C++ class RooStats::HistFactory::ShapeFactor+ ; #pragma link C++ class std::vector< RooStats::HistFactory::Channel >+ ; #pragma link C++ class std::vector< RooStats::HistFactory::Sample >+ ; diff --git a/roofit/histfactory/inc/RooStats/HistFactory/Detail/HistFactoryImpl.h b/roofit/histfactory/inc/RooStats/HistFactory/Detail/HistFactoryImpl.h new file mode 100644 index 0000000000000..cc9e1c62f0740 --- /dev/null +++ b/roofit/histfactory/inc/RooStats/HistFactory/Detail/HistFactoryImpl.h @@ -0,0 +1,63 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef HistFactoryImplHelpers_h +#define HistFactoryImplHelpers_h + +#include + +#include +#include + +#include + +namespace RooStats { +namespace HistFactory { +namespace Detail { + +namespace MagicConstants { + +constexpr double defaultGammaMin = 0; +constexpr double defaultShapeFactorGammaMax = 1000; +constexpr double defaultShapeSysGammaMax = 10; +constexpr double defaultStatErrorGammaMax = 10; +constexpr double minShapeUncertainty = 0.0; + +} // namespace MagicConstants + +template +Arg_t &getOrCreate(RooWorkspace &ws, std::string const &name, Params_t &&...params) +{ + Arg_t *arg = static_cast(ws.obj(name)); + if (arg) + return *arg; + Arg_t newArg(name.c_str(), name.c_str(), std::forward(params)...); + ws.import(newArg, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + return *static_cast(ws.obj(name)); +} + +void configureConstrainedGammas(RooArgList const &gammas, std::span relSigmas, double minSigma); + +struct CreateGammaConstraintsOutput { + std::vector> constraints; + std::vector globalObservables; +}; + +CreateGammaConstraintsOutput createGammaConstraints(RooArgList const ¶mList, + std::span relSigmas, double minSigma, + Constraint::Type type); + +} // namespace Detail +} // namespace HistFactory +} // namespace RooStats + +#endif diff --git a/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h b/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h index c2f21d2974447..011bfa6c3c51a 100644 --- a/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h +++ b/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h @@ -11,13 +11,10 @@ #ifndef ROOSTATS_FLEXIBLEINTERPVAR #define ROOSTATS_FLEXIBLEINTERPVAR -#include "RooAbsPdf.h" -#include "RooRealProxy.h" -#include "RooListProxy.h" -#include +#include +#include -class RooRealVar; -class RooArgList ; +#include namespace RooStats{ namespace HistFactory{ @@ -25,18 +22,15 @@ namespace HistFactory{ class FlexibleInterpVar : public RooAbsReal { public: - FlexibleInterpVar() ; - FlexibleInterpVar(const char *name, const char *title, - const RooArgList& _paramList, - double nominal, const RooArgList& low, const RooArgList& high); + FlexibleInterpVar(); FlexibleInterpVar(const char *name, const char *title, const RooArgList& _paramList, - double nominal, std::vector low, std::vector high); + double nominal, std::vector const& low, std::vector const& high); FlexibleInterpVar(const char *name, const char *title, - const RooArgList& _paramList, double nominal, std::vector low, - std::vector high,std::vector code); + const RooArgList& _paramList, double nominal, std::vector const& low, + std::vector const& high,std::vector const& code); FlexibleInterpVar(const char *name, const char *title); FlexibleInterpVar(const FlexibleInterpVar&, const char*); @@ -49,6 +43,7 @@ namespace HistFactory{ void setHigh(RooAbsReal& param, double newHigh); void printAllInterpCodes(); + const std::vector& interpolationCodes() const { return _interpCode; } TObject* clone(const char* newname) const override { return new FlexibleInterpVar(*this, newname); } ~FlexibleInterpVar() override ; @@ -56,30 +51,27 @@ namespace HistFactory{ void printMultiline(std::ostream& os, Int_t contents, bool verbose = false, TString indent = "") const override; virtual void printFlexibleInterpVars(std::ostream& os) const; - const RooListProxy& variables() const; - double nominal() const; - const std::vector& low() const; - const std::vector& high() const; + const RooListProxy& variables() const { return _paramList; } + double nominal() const { return _nominal; } + const std::vector& low() const { return _low; } + const std::vector& high() const { return _high; } - private: + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; - double PolyInterpValue(int i, double x) const; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: RooListProxy _paramList ; - double _nominal; + double _nominal = 0.0; std::vector _low; std::vector _high; std::vector _interpCode; - double _interpBoundary; - - mutable bool _logInit ; /// _polCoeff; ///, std::vector>&); + RooFit::OwningPtr MakeSingleChannelModel( Measurement& measurement, Channel& channel ); + RooFit::OwningPtr MakeCombinedModel(std::vector, std::vector>&); - static RooWorkspace* MakeCombinedModel( Measurement& measurement ); + static RooFit::OwningPtr MakeCombinedModel( Measurement& measurement ); static void PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, std::string filename); @@ -68,28 +68,21 @@ namespace RooStats{ protected: - void AddConstraintTerms(RooWorkspace* proto, Measurement& measurement, std::string prefix, std::string interpName, + void AddConstraintTerms(RooWorkspace& proto, Measurement& measurement, std::string prefix, std::string interpName, std::vector& systList, std::vector& likelihoodTermNames, std::vector& totSystTermNames); - std::unique_ptr CreateNormFactor(RooWorkspace* proto, std::string& channel, + std::unique_ptr CreateNormFactor(RooWorkspace& proto, std::string& channel, std::string& sigmaEpsilon, Sample& sample, bool doRatio); - RooWorkspace* MakeSingleChannelWorkspace(Measurement& measurement, Channel& channel); + std::unique_ptr MakeSingleChannelWorkspace(Measurement& measurement, Channel& channel); - void MakeTotalExpected(RooWorkspace* proto, const std::string& totName, + void MakeTotalExpected(RooWorkspace& proto, const std::string& totName, const std::vector& sampleScaleFactors, std::vector>& sampleHistFuncs) const; - RooDataSet* MergeDataSets(RooWorkspace* combined, - std::vector>& wspace_vec, - std::vector const& channel_names, - std::string const& dataSetName, - RooArgList const& obsList, - RooCategory* channelCat); - - RooHistFunc* MakeExpectedHistFunc(const TH1* hist, RooWorkspace* proto, std::string prefix, + RooHistFunc* MakeExpectedHistFunc(const TH1* hist, RooWorkspace& proto, std::string prefix, const RooArgList& observables) const; std::unique_ptr MakeScaledUncertaintyHist(const std::string& Name, @@ -97,11 +90,6 @@ namespace RooStats{ TH1* MakeAbsolUncertaintyHist( const std::string& Name, const TH1* Hist ); - RooArgList createStatConstraintTerms( RooWorkspace* proto, - std::vector& constraintTerms, - ParamHistFunc& paramHist, const TH1* uncertHist, - Constraint::Type type, double minSigma ); - void ConfigureHistFactoryDataset(RooDataSet& obsData, TH1 const& nominal, RooWorkspace& proto, std::vector const& obsNameVec); @@ -121,7 +109,7 @@ namespace RooStats{ std::vector fPreprocessFunctions; const Configuration fCfg; - RooArgList createObservables(const TH1 *hist, RooWorkspace *proto) const; + RooArgList createObservables(const TH1 *hist, RooWorkspace &proto) const; ClassDefOverride(RooStats::HistFactory::HistoToWorkspaceFactoryFast,3) }; diff --git a/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h b/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h index 0224dc3047f9c..109fb27799e7b 100644 --- a/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h +++ b/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h @@ -1,10 +1,6 @@ - #ifndef HISTFACTORY_MAKEMODELANDMEASUREMENTSFAST_H #define HISTFACTORY_MAKEMODELANDMEASUREMENTSFAST_H -#include -#include - #include "RooStats/HistFactory/Measurement.h" #include "RooStats/HistFactory/Channel.h" #include "RooStats/HistFactory/HistoToWorkspaceFactoryFast.h" @@ -12,19 +8,23 @@ #include "RooWorkspace.h" #include "RooPlot.h" +#include +#include +#include + class TFile; namespace RooStats{ namespace HistFactory{ - RooWorkspace* MakeModelAndMeasurementFast( + RooFit::OwningPtr MakeModelAndMeasurementFast( RooStats::HistFactory::Measurement& measurement, HistoToWorkspaceFactoryFast::Configuration const& cfg={} ); void FormatFrameForLikelihood(RooPlot* frame, std::string xTitle=std::string("#sigma / #sigma_{SM}"), std::string yTitle=std::string("-log likelihood")); void FitModel(RooWorkspace *, std::string data_name="obsData"); - void FitModelAndPlot(const std::string& measurementName, const std::string& fileNamePrefix, RooWorkspace *, std::string, std::string, TFile*, FILE*); + void FitModelAndPlot(const std::string& measurementName, const std::string& fileNamePrefix, RooWorkspace &, std::string, std::string, TFile&, std::ostream&); } } diff --git a/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h b/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h index 0aaf45dcfb311..b1323e911df00 100644 --- a/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h +++ b/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h @@ -102,9 +102,11 @@ class ParamHistFunc : public RooAbsReal { Int_t addParamSet( const RooArgList& params ); static Int_t GetNumBins( const RooArgSet& vars ); double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; -private: + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + + private: static NumBins getNumBinsPerDim(RooArgSet const& vars); ClassDefOverride(ParamHistFunc, 7) diff --git a/roofit/histfactory/inc/RooStats/HistFactory/PiecewiseInterpolation.h b/roofit/histfactory/inc/RooStats/HistFactory/PiecewiseInterpolation.h index b2cb88b074713..b9c6c9732af36 100644 --- a/roofit/histfactory/inc/RooStats/HistFactory/PiecewiseInterpolation.h +++ b/roofit/histfactory/inc/RooStats/HistFactory/PiecewiseInterpolation.h @@ -31,7 +31,11 @@ class PiecewiseInterpolation : public RooAbsReal { public: PiecewiseInterpolation() ; - PiecewiseInterpolation(const char *name, const char *title, const RooAbsReal& nominal, const RooArgList& lowSet, const RooArgList& highSet, const RooArgList& paramSet, bool takeOwnerShip=false) ; + PiecewiseInterpolation(const char *name, const char *title, const RooAbsReal& nominal, const RooArgList& lowSet, const RooArgList& highSet, const RooArgList& paramSet +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES + , bool takeOwnership=false +#endif + ); ~PiecewiseInterpolation() override ; PiecewiseInterpolation(const PiecewiseInterpolation& other, const char *name = nullptr); @@ -58,6 +62,7 @@ class PiecewiseInterpolation : public RooAbsReal { double analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName=nullptr) const override ; void setPositiveDefinite(bool flag=true){_positiveDefinite=flag;} + bool positiveDefinite() const {return _positiveDefinite;} void setInterpCode(RooAbsReal& param, int code, bool silent=false); void setAllInterpCodes(int code); @@ -67,6 +72,8 @@ class PiecewiseInterpolation : public RooAbsReal { std::list* plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const override ; bool isBinnedDistribution(const RooArgSet& obs) const override ; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + protected: class CacheElem : public RooAbsCacheElement { @@ -97,7 +104,7 @@ class PiecewiseInterpolation : public RooAbsReal { std::vector _interpCode; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; ClassDefOverride(PiecewiseInterpolation,4) // Sum of RooAbsReal objects }; diff --git a/roofit/histfactory/inc/RooStats/HistFactory/Systematics.h b/roofit/histfactory/inc/RooStats/HistFactory/Systematics.h index 7e4ef55cad753..847198fa73e24 100644 --- a/roofit/histfactory/inc/RooStats/HistFactory/Systematics.h +++ b/roofit/histfactory/inc/RooStats/HistFactory/Systematics.h @@ -27,21 +27,6 @@ namespace HistFactory { Type GetType( const std::string& Name ); } - - // Base class for common functions - /* - class Systematic { - - public: - - virtual void Print(std::ostream& = std::cout); - virtual void writeToFile(const std::string& FileName, - const std::string& Directory); - - - }; - */ - /** \class OverallSys * \ingroup HistFactory * Configuration for a constrained overall systematic to scale sample normalisations. diff --git a/roofit/histfactory/src/Channel.cxx b/roofit/histfactory/src/Channel.cxx index 9824f645db962..81b24aa69248e 100644 --- a/roofit/histfactory/src/Channel.cxx +++ b/roofit/histfactory/src/Channel.cxx @@ -22,7 +22,7 @@ #include "RooStats/HistFactory/Channel.h" #include "HFMsgService.h" -#include +#include #include "TFile.h" #include "TKey.h" @@ -222,7 +222,7 @@ void RooStats::HistFactory::Channel::CollectHistograms() { // Get the Data Histogram: - if( fData.GetInputFile() != "" ) { + if( !fData.GetInputFile().empty() ) { fData.SetHisto( GetHistogram(fData.GetInputFile(), fData.GetHistoPath(), fData.GetHistoName(), @@ -231,7 +231,7 @@ void RooStats::HistFactory::Channel::CollectHistograms() { // Collect any histograms for additional Datasets for(auto& data : fAdditionalData) { - if( data.GetInputFile() != "" ) { + if( !data.GetInputFile().empty() ) { data.SetHisto( GetHistogram(data.GetInputFile(), data.GetHistoPath(), data.GetHistoName(), fileHandles) ); } } @@ -330,11 +330,9 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { // Check that all internal histogram pointers // are properly configured (ie that they're not nullptr) - try { - - if( fData.GetHisto() == nullptr && fData.GetInputFile() != "" ) { + if( fData.GetHisto() == nullptr && !fData.GetInputFile().empty() ) { cxcoutEHF << "Error: Data Histogram for channel " << GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } // Get the histograms for the samples: @@ -345,7 +343,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { // Get the nominal histogram: if( sample.GetHisto() == nullptr ) { cxcoutEHF << "Error: Nominal Histogram for sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } else { @@ -359,7 +357,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { NegativeBinContent.push_back(histNominal->GetBinContent(ibin)); } } - if(NegativeBinNumber.size()>0) { + if(!NegativeBinNumber.empty()) { cxcoutWHF << "WARNING: Nominal Histogram " << histNominal->GetName() << " for Sample = " << sample.GetName() << " in Channel = " << GetName() << " has negative entries in bin numbers = "; @@ -376,7 +374,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { if( sample.GetStatError().GetUseHisto() ) { if( sample.GetStatError().GetErrorHist() == nullptr ) { cxcoutEHF << "Error: Statistical Error Histogram for sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } } @@ -389,12 +387,12 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { if( histoSys.GetHistoLow() == nullptr ) { cxcoutEHF << "Error: HistoSyst Low for Systematic " << histoSys.GetName() << " in sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } if( histoSys.GetHistoHigh() == nullptr ) { cxcoutEHF << "Error: HistoSyst High for Systematic " << histoSys.GetName() << " in sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } } // End Loop over HistoSys @@ -408,12 +406,12 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { if( histoFactor.GetHistoLow() == nullptr ) { cxcoutEHF << "Error: HistoSyst Low for Systematic " << histoFactor.GetName() << " in sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } if( histoFactor.GetHistoHigh() == nullptr ) { cxcoutEHF << "Error: HistoSyst High for Systematic " << histoFactor.GetName() << " in sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } } // End Loop over HistoFactor @@ -427,25 +425,14 @@ bool RooStats::HistFactory::Channel::CheckHistograms() const { if( shapeSys.GetErrorHist() == nullptr ) { cxcoutEHF << "Error: HistoSyst High for Systematic " << shapeSys.GetName() << " in sample " << sample.GetName() << " is nullptr." << std::endl; - throw hf_exc(); + return false; } } // End Loop over ShapeSys } // End Loop over Samples - } - catch(std::exception& e) - { - std::cout << e.what() << std::endl; - return false; - } - return true; - - - - } diff --git a/roofit/histfactory/src/ConfigParser.cxx b/roofit/histfactory/src/ConfigParser.cxx index 2a96183303877..835d4570dfa88 100644 --- a/roofit/histfactory/src/ConfigParser.cxx +++ b/roofit/histfactory/src/ConfigParser.cxx @@ -84,7 +84,7 @@ namespace { std::string param = string_list.at(i); // Split the string - size_t eql_location = param.find("="); + size_t eql_location = param.find('='); // If there is no '=' deliminator, we only // set the variable constant @@ -122,8 +122,6 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF // (This is what will be returned) std::vector< HistFactory::Measurement > measurement_list; - try { - // Open the Driver XML File TDOMParser xmlparser; Int_t parseError = xmlparser.ParseFile( input.c_str() ); @@ -150,8 +148,8 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF std::string OutputFilePrefix; TListIter attribIt = rootNode->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -190,7 +188,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF // if no channels are found std::vector< std::string > xml_channel_files; node = rootNode->GetChildren(); - while( node != 0 ) { + while( node != nullptr ) { if( node->GetNodeName() == TString( "Input" ) ) { if( node->GetText() == nullptr ) { cxcoutEHF << "Error: node: " << node->GetName() @@ -222,16 +220,16 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF // and then we add them to all measurements // For now, we create this list twice - // simply for compatability + // simply for compatibility // std::vector< std::string > preprocessFunctions; std::vector< RooStats::HistFactory::PreprocessFunction > functionObjects; node = rootNode->GetChildren(); - while( node != 0 ) { + while( node != nullptr ) { if( node->GetNodeName() == TString( "Function" ) ) { // For now, add both the objects itself and - // it's command string (for easy compatability) + // it's command string (for easy compatibility) RooStats::HistFactory::PreprocessFunction Func = ParseFunctionConfig( node ); // preprocessFunctions.push_back( Func.GetCommand() ); functionObjects.push_back( Func ); @@ -244,7 +242,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF // Fill the list of measurements node = rootNode->GetChildren(); - while( node != 0 ) { + while( node != nullptr ) { if( node->GetNodeName() == TString( "" ) ) { cxcoutEHF << "Error: Node found in Measurement Driver XML with no name" << std::endl; @@ -332,15 +330,8 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF measurement.GetChannels().push_back( channel_list.at(j) ); } } - } - catch(std::exception& e) - { - std::cout << e.what() << std::endl; - throw hf_exc(); - } return measurement_list; - } @@ -371,7 +362,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode(TXMLNode // curAttr is guaranteed non-null above const std::string curAttrName(curAttr->GetName() ? curAttr->GetName() : ""), curAttrValue(curAttr->GetValue() ? curAttr->GetValue() : ""); - if (curAttrName == "") { + if (curAttrName.empty()) { cxcoutEHF << "Found XML attribute in Measurement with no name.\n"; // ADD Output Here throw hf_exc(); @@ -405,7 +396,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode(TXMLNode cxcoutEHF << "Found XML child node of Measurement with no name\n"; throw hf_exc(); } else if (childNodeName == "POI") { - if (childText == "") { + if (childText.empty()) { cxcoutEHF << "Error: node: " << childName << " has no text.\n"; throw hf_exc(); } @@ -579,7 +570,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) { if( rootNode->GetNodeName() != TString( "Channel" ) ){ cxcoutEHF << "Error: In parsing a Channel XML, " - << "Encounterd XML with DOCTYPE: " << rootNode->GetNodeName() + << "Encountered XML with DOCTYPE: " << rootNode->GetNodeName() << std::endl; cxcoutEHF << " DOCTYPE for channels must be 'Channel' " << " Check that your XML is properly written" << std::endl; @@ -599,8 +590,8 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) { // Walk through the root node and // get its attributes TListIter attribIt = rootNode->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -646,7 +637,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) { // Check that the channel was properly initiated: - if( channel.GetName() == "" ) { + if( channel.GetName().empty() ) { cxcoutEHF << "Error: Channel created with no name" << std::endl; throw hf_exc(); } @@ -660,7 +651,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) { bool firstData=true; - while( node != 0 ) { + while( node != nullptr ) { // Restore the Channel-Wide Defaults m_currentInputFile = channel.GetInputFile(); @@ -674,7 +665,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) { else if( node->GetNodeName() == TString( "Data" ) ) { if( firstData ) { RooStats::HistFactory::Data data = CreateDataElement(node); - if( data.GetName() != "" ) { + if( !data.GetName().empty() ) { cxcoutEHF << "Error: You can only rename the datasets of additional data sets. " << " Remove the 'Name=" << data.GetName() << "' tag" << " from channel: " << channel.GetName() << std::endl; @@ -729,8 +720,8 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) { // Now, set the attributes TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -767,11 +758,11 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) { } // Check the properties of the data node: - if( data.GetInputFile() == "" ) { + if( data.GetInputFile().empty() ) { cxcoutEHF << "Error: Data Node has no InputFile" << std::endl; throw hf_exc(); } - if( data.GetHistoName() == "" ) { + if( data.GetHistoName().empty() ) { cxcoutEHF << "Error: Data Node has no HistoName" << std::endl; throw hf_exc(); } @@ -780,7 +771,7 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) { << " InputFile: " << data.GetInputFile() << " HistoName: " << data.GetHistoName() << " HistoPath: " << data.GetHistoPath() - << (data.GetName() != "" ? " Name: " : "") << data.GetName() << std::endl; + << (!data.GetName().empty() ? " Name: " : "") << data.GetName() << std::endl; // data.hist = GetHisto(data.FileName, data.HistoPath, data.HistoName); @@ -801,8 +792,8 @@ HistFactory::StatErrorConfig ConfigParser::CreateStatErrorConfigElement( TXMLNod // Loop over the node's attributes TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -815,7 +806,7 @@ HistFactory::StatErrorConfig ConfigParser::CreateStatErrorConfigElement( TXMLNod if( attrName == TString( "ConstraintType" ) ) { // Allowable Values: Gaussian - if( attrVal == "" ) { + if( attrVal.empty() ) { cxcoutEHF << "Error: Bad Value for StatErrorConfig Constraint Type Found" << std::endl; throw hf_exc(); } @@ -863,8 +854,8 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) { // Now, set the attributes TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -917,15 +908,15 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) { } // Quickly check the properties of the Sample Node - if( sample.GetName() == "" ) { + if( sample.GetName().empty() ) { cxcoutEHF << "Error: Sample Node has no Name" << std::endl; throw hf_exc(); } - if( sample.GetInputFile() == "" ) { + if( sample.GetInputFile().empty() ) { cxcoutEHF << "Error: Sample Node has no InputFile" << std::endl; throw hf_exc(); } - if( sample.GetHistoName() == "" ) { + if( sample.GetHistoName().empty() ) { cxcoutEHF << "Error: Sample Node has no HistoName" << std::endl; throw hf_exc(); } @@ -935,7 +926,7 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) { TXMLNode* child = node->GetChildren(); - while( child != 0 ) { + while( child != nullptr ) { if( child->GetNodeName() == TString( "" ) ) { cxcoutEHF << "Error: Encountered node in Sample with no name" << std::endl; @@ -1001,8 +992,8 @@ HistFactory::NormFactor ConfigParser::MakeNormFactor( TXMLNode* node ) { HistFactory::NormFactor norm; TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -1034,7 +1025,7 @@ HistFactory::NormFactor ConfigParser::MakeNormFactor( TXMLNode* node ) { } // End loop over properties - if( norm.GetName() == "" ) { + if( norm.GetName().empty() ) { cxcoutEHF << "Error: NormFactor Node has no Name" << std::endl; throw hf_exc(); } @@ -1096,7 +1087,7 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) { histoSys.SetHistoPathHigh( m_currentHistoPath ); TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; + TXMLAttr* curAttr = nullptr; /* string Name, histoPathHigh, histoPathLow, histoNameLow, histoNameHigh, inputFileHigh, inputFileLow; @@ -1105,7 +1096,7 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) { histoNameLow=histoName; histoNameHigh=histoName; */ - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -1149,23 +1140,23 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) { } // End loop over properties - if( histoSys.GetName() == "" ) { + if( histoSys.GetName().empty() ) { cxcoutEHF << "Error: HistoSys Node has no Name" << std::endl; throw hf_exc(); } - if( histoSys.GetInputFileHigh() == "" ) { + if( histoSys.GetInputFileHigh().empty() ) { cxcoutEHF << "Error: HistoSysSample Node has no InputFileHigh" << std::endl; throw hf_exc(); } - if( histoSys.GetInputFileLow() == "" ) { + if( histoSys.GetInputFileLow().empty() ) { cxcoutEHF << "Error: HistoSysSample Node has no InputFileLow" << std::endl; throw hf_exc(); } - if( histoSys.GetHistoNameHigh() == "" ) { + if( histoSys.GetHistoNameHigh().empty() ) { cxcoutEHF << "Error: HistoSysSample Node has no HistoNameHigh" << std::endl; throw hf_exc(); } - if( histoSys.GetHistoNameLow() == "" ) { + if( histoSys.GetHistoNameLow().empty() ) { cxcoutEHF << "Error: HistoSysSample Node has no HistoNameLow" << std::endl; throw hf_exc(); } @@ -1185,8 +1176,8 @@ HistFactory::OverallSys ConfigParser::MakeOverallSys( TXMLNode* node ) { HistFactory::OverallSys overallSys; TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -1215,7 +1206,7 @@ HistFactory::OverallSys ConfigParser::MakeOverallSys( TXMLNode* node ) { } - if( overallSys.GetName() == "" ) { + if( overallSys.GetName().empty() ) { cxcoutEHF << "Error: Encountered OverallSys with no name" << std::endl; throw hf_exc(); } @@ -1235,7 +1226,7 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) { HistFactory::ShapeFactor shapeFactor; TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; + TXMLAttr* curAttr = nullptr; // A Shape Factor may or may not include an initial shape // This will be set by strings pointing to a histogram @@ -1244,7 +1235,7 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) { std::string ShapeInputFile = m_currentInputFile; std::string ShapeInputPath = m_currentHistoPath; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -1282,7 +1273,7 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) { } - if( shapeFactor.GetName() == "" ) { + if( shapeFactor.GetName().empty() ) { cxcoutEHF << "Error: Encountered ShapeFactor with no name" << std::endl; throw hf_exc(); } @@ -1290,7 +1281,7 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) { // Set the Histogram name, path, and file // if an InitialHist is set if( shapeFactor.HasInitialShape() ) { - if( shapeFactor.GetHistoName() == "" ) { + if( shapeFactor.GetHistoName().empty() ) { cxcoutEHF << "Error: ShapeFactor: " << shapeFactor.GetName() << " is configured to have an initial shape, but " << "its histogram doesn't have a name" @@ -1321,10 +1312,10 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) { TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; + TXMLAttr* curAttr = nullptr; //EstimateSummary::ConstraintType ConstraintType = EstimateSummary::Gaussian; //"Gaussian"; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node @@ -1353,7 +1344,7 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) { } else if( attrName == TString( "ConstraintType" ) ) { - if( attrVal=="" ) { + if( attrVal.empty() ) { cxcoutEHF << "Error: ShapeSys Constraint type is empty" << std::endl; throw hf_exc(); } @@ -1378,15 +1369,15 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) { } // End loop over attributes - if( shapeSys.GetName() == "" ) { + if( shapeSys.GetName().empty() ) { cxcoutEHF << "Error: Encountered ShapeSys with no Name" << std::endl; throw hf_exc(); } - if( shapeSys.GetInputFile() == "" ) { + if( shapeSys.GetInputFile().empty() ) { cxcoutEHF << "Error: Encountered ShapeSys with no InputFile" << std::endl; throw hf_exc(); } - if( shapeSys.GetHistoName() == "" ) { + if( shapeSys.GetHistoName().empty() ) { cxcoutEHF << "Error: Encountered ShapeSys with no HistoName" << std::endl; throw hf_exc(); } @@ -1410,8 +1401,8 @@ HistFactory::StatError ConfigParser::ActivateStatError( TXMLNode* node ) { // Loop over the node's attributes TListIter attribIt = node->GetAttributes(); - TXMLAttr* curAttr = 0; - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + TXMLAttr* curAttr = nullptr; + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { // Get the Name, Val of this node TString attrName = curAttr->GetName(); @@ -1453,15 +1444,15 @@ HistFactory::StatError ConfigParser::ActivateStatError( TXMLNode* node ) { // If this is set AND the InputFile or // HistoPath aren't set, we set those // to the current default values - if( statError.GetHistoName() != "" ) { + if( !statError.GetHistoName().empty() ) { statError.SetUseHisto( true ); // Check that a file has been set // (Possibly using the default) - if( statError.GetInputFile() == "" ) { + if( statError.GetInputFile().empty() ) { statError.SetInputFile( m_currentInputFile ); } - if( statError.GetHistoPath() == "" ) { + if( statError.GetHistoPath().empty() ) { statError.SetHistoPath( m_currentHistoPath ); } @@ -1492,14 +1483,14 @@ RooStats::HistFactory::PreprocessFunction ConfigParser::ParseFunctionConfig( TXM //std::string name, expression, dependents; TListIter attribIt = functionNode->GetAttributes(); - TXMLAttr* curAttr = 0; + TXMLAttr* curAttr = nullptr; std::string Name = ""; std::string Expression = ""; std::string Dependents = ""; // Add protection to ensure that all parts are there - while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != 0 ) { + while( ( curAttr = dynamic_cast< TXMLAttr* >( attribIt() ) ) != nullptr ) { if( curAttr->GetName() == TString( "Name" ) ) { Name = curAttr->GetValue(); //func.SetName( curAttr->GetValue() ); @@ -1515,15 +1506,15 @@ RooStats::HistFactory::PreprocessFunction ConfigParser::ParseFunctionConfig( TXM } } - if( Name=="" ){ + if( Name.empty() ){ cxcoutEHF << "Error processing PreprocessFunction: Name attribute is empty" << std::endl; throw hf_exc(); } - if( Expression=="" ){ + if( Expression.empty() ){ cxcoutEHF << "Error processing PreprocessFunction: Expression attribute is empty" << std::endl; throw hf_exc(); } - if( Dependents=="" ){ + if( Dependents.empty() ){ cxcoutEHF << "Error processing PreprocessFunction: Dependents attribute is empty" << std::endl; throw hf_exc(); } @@ -1557,7 +1548,7 @@ bool ConfigParser::IsAcceptableNode( TXMLNode* node ) { bool ConfigParser::CheckTrueFalse( std::string attrVal, std::string NodeTitle ) { - if( attrVal == "" ) { + if( attrVal.empty() ) { cxcoutEHF << "Error: In " << NodeTitle << " Expected either 'True' or 'False' but found empty" << std::endl; throw hf_exc(); diff --git a/roofit/histfactory/src/FlexibleInterpVar.cxx b/roofit/histfactory/src/FlexibleInterpVar.cxx index e287a7a62b132..3e70c8e173356 100644 --- a/roofit/histfactory/src/FlexibleInterpVar.cxx +++ b/roofit/histfactory/src/FlexibleInterpVar.cxx @@ -15,34 +15,27 @@ * \ingroup HistFactory */ -#include "Riostream.h" -#include -#include "TMath.h" +#include +#include -#include "RooAbsReal.h" -#include "RooRealVar.h" -#include "RooArgList.h" -#include "RooMsgService.h" -#include "RooTrace.h" +#include +#include -#include "RooStats/HistFactory/FlexibleInterpVar.h" - -using namespace std; +#include +#include ClassImp(RooStats::HistFactory::FlexibleInterpVar); using namespace RooStats; using namespace HistFactory; + //////////////////////////////////////////////////////////////////////////////// /// Default constructor FlexibleInterpVar::FlexibleInterpVar() { - _nominal = 0; - _interpBoundary=1.; - _logInit = false ; - TRACE_CREATE + TRACE_CREATE; } @@ -50,101 +43,40 @@ FlexibleInterpVar::FlexibleInterpVar() FlexibleInterpVar::FlexibleInterpVar(const char* name, const char* title, const RooArgList& paramList, - double argNominal, std::vector lowVec, std::vector highVec) : - RooAbsReal(name, title), - _paramList("paramList","List of paramficients",this), - _nominal(argNominal), _low(lowVec), _high(highVec), _interpBoundary(1.) + double argNominal, std::vector const& lowVec, std::vector const& highVec) : + FlexibleInterpVar{name, title, paramList, argNominal, lowVec, highVec, std::vector(lowVec.size(), 0)} { - _logInit = false ; - - for (auto param : paramList) { - if (!dynamic_cast(param)) { - coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") ERROR: paramficient " << param->GetName() - << " is not of type RooAbsReal" << endl ; - R__ASSERT(0) ; - } - _paramList.add(*param) ; - _interpCode.push_back(0); // default code - } - if (int(_low.size() ) != _paramList.getSize() || _low.size() != _high.size()) { - coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") invalid input low/high vectors " << endl; - R__ASSERT(int(_low.size() ) == _paramList.getSize()); - R__ASSERT(_low.size() == _high.size()); - } - - TRACE_CREATE } -//////////////////////////////////////////////////////////////////////////////// - -FlexibleInterpVar::FlexibleInterpVar(const char* name, const char* title, - const RooArgList& paramList, - double argNominal, const RooArgList& lowList, const RooArgList& highList) : - RooAbsReal(name, title), - _paramList("paramList","List of paramficients",this), - _nominal(argNominal), _interpBoundary(1.) -{ - for (auto const *val : static_range_cast(lowList)){ - _low.push_back(val->getVal()) ; - } - - for (auto const *val : static_range_cast(highList)) { - _high.push_back(val->getVal()) ; - } - - _logInit = false ; - - for (auto param : paramList) { - if (!dynamic_cast(param)) { - coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") ERROR: paramficient " << param->GetName() - << " is not of type RooAbsReal" << endl ; - R__ASSERT(0) ; - } - _paramList.add(*param) ; - _interpCode.push_back(0); // default code - } - if (int(_low.size() ) != _paramList.getSize() || _low.size() != _high.size()) { - coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") invalid input low/high lists " << endl; - R__ASSERT(int(_low.size() ) == _paramList.getSize()); - R__ASSERT(_low.size() == _high.size()); - } - - TRACE_CREATE -} - - - //////////////////////////////////////////////////////////////////////////////// FlexibleInterpVar::FlexibleInterpVar(const char* name, const char* title, const RooArgList& paramList, - double argNominal, vector lowVec, vector highVec, - vector code) : + double argNominal, std::vector const& lowVec, std::vector const& highVec, + std::vector const& code) : RooAbsReal(name, title), _paramList("paramList","List of paramficients",this), _nominal(argNominal), _low(lowVec), _high(highVec), _interpCode(code), _interpBoundary(1.) { - _logInit = false ; - for (auto param : paramList) { if (!dynamic_cast(param)) { coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") ERROR: paramficient " << param->GetName() - << " is not of type RooAbsReal" << endl ; + << " is not of type RooAbsReal" << std::endl ; // use R__ASSERT which remains also in release mode R__ASSERT(0) ; } _paramList.add(*param) ; } - if (int(_low.size() ) != _paramList.getSize() || _low.size() != _high.size() || _low.size() != _interpCode.size()) { - coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") invalid input vectors " << endl; - R__ASSERT(int(_low.size() ) == _paramList.getSize()); + if (_low.size() != _paramList.size() || _low.size() != _high.size() || _low.size() != _interpCode.size()) { + coutE(InputArguments) << "FlexibleInterpVar::ctor(" << GetName() << ") invalid input std::vectors " << std::endl; + R__ASSERT(_low.size() == _paramList.size()); R__ASSERT(_low.size() == _high.size()); R__ASSERT(_low.size() == _interpCode.size()); } - TRACE_CREATE + TRACE_CREATE; } //////////////////////////////////////////////////////////////////////////////// @@ -152,11 +84,9 @@ FlexibleInterpVar::FlexibleInterpVar(const char* name, const char* title, FlexibleInterpVar::FlexibleInterpVar(const char* name, const char* title) : RooAbsReal(name, title), - _paramList("paramList","List of coefficients",this), - _nominal(0), _interpBoundary(1.) + _paramList("paramList","List of coefficients",this) { - _logInit = false ; - TRACE_CREATE + TRACE_CREATE; } //////////////////////////////////////////////////////////////////////////////// @@ -167,10 +97,7 @@ FlexibleInterpVar::FlexibleInterpVar(const FlexibleInterpVar& other, const char* _nominal(other._nominal), _low(other._low), _high(other._high), _interpCode(other._interpCode), _interpBoundary(other._interpBoundary) { - // Copy constructor - _logInit = false ; - TRACE_CREATE - + TRACE_CREATE; } @@ -179,7 +106,7 @@ FlexibleInterpVar::FlexibleInterpVar(const FlexibleInterpVar& other, const char* FlexibleInterpVar::~FlexibleInterpVar() { - TRACE_DESTROY + TRACE_DESTROY; } @@ -189,15 +116,14 @@ void FlexibleInterpVar::setInterpCode(RooAbsReal& param, int code){ int index = _paramList.index(¶m); if(index<0){ coutE(InputArguments) << "FlexibleInterpVar::setInterpCode ERROR: " << param.GetName() - << " is not in list" << endl ; - } else { - coutW(InputArguments) << "FlexibleInterpVar::setInterpCode : " << param.GetName() - << " is now " << code << endl ; - _interpCode.at(index) = code; + << " is not in list" << std::endl; + } else if(_interpCode.at(index) != code){ + coutI(InputArguments) << "FlexibleInterpVar::setInterpCode : " << param.GetName() + << " is now " << code << std::endl; + _interpCode.at(index) = code; + // GHL: Adding suggestion by Swagato: + setValueDirty(); } - // GHL: Adding suggestion by Swagato: - _logInit = false ; - setValueDirty(); } //////////////////////////////////////////////////////////////////////////////// @@ -207,19 +133,15 @@ void FlexibleInterpVar::setAllInterpCodes(int code){ _interpCode.at(i) = code; } // GHL: Adding suggestion by Swagato: - _logInit = false ; setValueDirty(); - } //////////////////////////////////////////////////////////////////////////////// void FlexibleInterpVar::setNominal(double newNominal){ - coutW(InputArguments) << "FlexibleInterpVar::setNominal : nominal is now " << newNominal << endl ; + coutW(InputArguments) << "FlexibleInterpVar::setNominal : nominal is now " << newNominal << std::endl ; _nominal = newNominal; - _logInit = false ; - setValueDirty(); } @@ -229,15 +151,13 @@ void FlexibleInterpVar::setLow(RooAbsReal& param, double newLow){ int index = _paramList.index(¶m); if(index<0){ coutE(InputArguments) << "FlexibleInterpVar::setLow ERROR: " << param.GetName() - << " is not in list" << endl ; + << " is not in list" << std::endl ; } else { coutW(InputArguments) << "FlexibleInterpVar::setLow : " << param.GetName() - << " is now " << newLow << endl ; + << " is now " << newLow << std::endl ; _low.at(index) = newLow; } - _logInit = false ; - setValueDirty(); } @@ -247,14 +167,13 @@ void FlexibleInterpVar::setHigh(RooAbsReal& param, double newHigh){ int index = _paramList.index(¶m); if(index<0){ coutE(InputArguments) << "FlexibleInterpVar::setHigh ERROR: " << param.GetName() - << " is not in list" << endl ; + << " is not in list" << std::endl ; } else { coutW(InputArguments) << "FlexibleInterpVar::setHigh : " << param.GetName() - << " is now " << newHigh << endl ; + << " is now " << newHigh << std::endl ; _high.at(index) = newHigh; } - _logInit = false ; setValueDirty(); } @@ -262,210 +181,91 @@ void FlexibleInterpVar::setHigh(RooAbsReal& param, double newHigh){ void FlexibleInterpVar::printAllInterpCodes(){ for(unsigned int i=0; i<_interpCode.size(); ++i){ - coutI(InputArguments) <<"interp code for " << _paramList.at(i)->GetName() << " = " << _interpCode.at(i) <GetName() << " = " << _interpCode.at(i) << std::endl; // GHL: Adding suggestion by Swagato: - if( _low.at(i) <= 0.001 ) coutE(InputArguments) << GetName() << ", " << _paramList.at(i)->GetName() << ": low value = " << _low.at(i) << endl; - if( _high.at(i) <= 0.001 ) coutE(InputArguments) << GetName() << ", " << _paramList.at(i)->GetName() << ": high value = " << _high.at(i) << endl; + if( _low.at(i) <= 0.001 ) coutE(InputArguments) << GetName() << ", " << _paramList.at(i)->GetName() << ": low value = " << _low.at(i) << std::endl; + if( _high.at(i) <= 0.001 ) coutE(InputArguments) << GetName() << ", " << _paramList.at(i)->GetName() << ": high value = " << _high.at(i) << std::endl; } } -//////////////////////////////////////////////////////////////////////////////// - -double FlexibleInterpVar::PolyInterpValue(int i, double x) const { - // code for polynomial interpolation used when interpCode=4 - - double boundary = _interpBoundary; - - double x0 = boundary; +//////////////////////////////////////////////////////////////////////////////// +/// Calculate and return value of polynomial - // cache the polynomial coefficient values - // which do not depend on x but on the boundaries values - if (!_logInit) { - - _logInit=true ; - - unsigned int n = _low.size(); - assert(n == _high.size() ); - - _polCoeff.resize(n*6) ; - - for (unsigned int j = 0; j < n ; j++) { - - // location of the 6 coefficient for the j-th variable - double * coeff = &_polCoeff[j * 6]; - - // GHL: Swagato's suggestions - double pow_up = std::pow(_high[j]/_nominal, x0); - double pow_down = std::pow(_low[j]/_nominal, x0); - double logHi = std::log(_high[j]) ; - double logLo = std::log(_low[j] ); - double pow_up_log = _high[j] <= 0.0 ? 0.0 : pow_up * logHi; - double pow_down_log = _low[j] <= 0.0 ? 0.0 : -pow_down * logLo; - double pow_up_log2 = _high[j] <= 0.0 ? 0.0 : pow_up_log * logHi; - double pow_down_log2= _low[j] <= 0.0 ? 0.0 : -pow_down_log* logLo; - - double S0 = (pow_up+pow_down)/2; - double A0 = (pow_up-pow_down)/2; - double S1 = (pow_up_log+pow_down_log)/2; - double A1 = (pow_up_log-pow_down_log)/2; - double S2 = (pow_up_log2+pow_down_log2)/2; - double A2 = (pow_up_log2-pow_down_log2)/2; - - //fcns+der+2nd_der are eq at bd - - // cache coefficient of the polynomial - coeff[0] = 1./(8*x0) *( 15*A0 - 7*x0*S1 + x0*x0*A2); - coeff[1] = 1./(8*x0*x0) *(-24 + 24*S0 - 9*x0*A1 + x0*x0*S2); - coeff[2] = 1./(4*pow(x0, 3))*( - 5*A0 + 5*x0*S1 - x0*x0*A2); - coeff[3] = 1./(4*pow(x0, 4))*( 12 - 12*S0 + 7*x0*A1 - x0*x0*S2); - coeff[4] = 1./(8*pow(x0, 5))*( + 3*A0 - 3*x0*S1 + x0*x0*A2); - coeff[5] = 1./(8*pow(x0, 6))*( -8 + 8*S0 - 5*x0*A1 + x0*x0*S2); - +double FlexibleInterpVar::evaluate() const +{ + double total(_nominal); + for (std::size_t i = 0; i < _paramList.size(); ++i) { + if (_interpCode[i] < 0 || _interpCode[i] > 4) { + coutE(InputArguments) << "FlexibleInterpVar::evaluate ERROR: param " << i + << " with unknown interpolation code" << std::endl; } - + double paramVal = static_cast(&_paramList[i])->getVal(); + total = RooFit::Detail::EvaluateFuncs::flexibleInterp( + _interpCode[i], _low[i], _high[i], _interpBoundary, _nominal, paramVal, total); } - // GHL: Swagato's suggestions - // if( _low[i] == 0 ) _low[i] = 0.0001; - // if( _high[i] == 0 ) _high[i] = 0.0001; - - // get pointer to location of coefficients in the vector - - assert(int(_polCoeff.size()) > i ); - const double * coefficients = &_polCoeff.front() + 6*i; - - double a = coefficients[0]; - double b = coefficients[1]; - double c = coefficients[2]; - double d = coefficients[3]; - double e = coefficients[4]; - double f = coefficients[5]; - + if(total<=0) { + total= TMath::Limits::Min(); + } - // evaluate the 6-th degree polynomial using Horner's method - double value = 1. + x * (a + x * ( b + x * ( c + x * ( d + x * ( e + x * f ) ) ) ) ); - return value; + return total; } -//////////////////////////////////////////////////////////////////////////////// -/// Const getters - -const RooListProxy& FlexibleInterpVar::variables() const { return _paramList; } -double FlexibleInterpVar::nominal() const { return _nominal; } -const std::vector& FlexibleInterpVar::low() const { return _low; } -const std::vector& FlexibleInterpVar::high() const { return _high; } - -//////////////////////////////////////////////////////////////////////////////// -/// Calculate and return value of polynomial +void FlexibleInterpVar::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + unsigned int n = _interpCode.size(); + + std::string resName = "total_" + ctx.getTmpVarName(); + ctx.addToCodeBody(this, "double " + resName + " = " + std::to_string(_nominal) + ";\n"); + std::string code = ""; + for (std::size_t i = 0; i < n; ++i) { + code += resName + " = " + + ctx.buildCall("RooFit::Detail::EvaluateFuncs::flexibleInterp", _interpCode[i], + _low[i], _high[i], _interpBoundary, + _nominal, _paramList[i], resName) + + ";\n"; + } + code += resName + " = " + resName + " <= 0 ? TMath::Limits::Min() : " + resName + ";\n"; + ctx.addToCodeBody(this, code); + ctx.addResult(this, resName); +} -double FlexibleInterpVar::evaluate() const +void FlexibleInterpVar::computeBatch(double* output, size_t /*nEvents*/, RooFit::Detail::DataMap const& dataMap) const { double total(_nominal) ; - int i=0; - - for (auto arg : _paramList) { - auto param = static_cast(arg); - - Int_t icode = _interpCode[i] ; - - switch(icode) { - - case 0: { - // piece-wise linear - if(param->getVal()>0) - total += param->getVal()*(_high[i] - _nominal ); - else - total += param->getVal()*(_nominal - _low[i]); - break ; - } - case 1: { - // pice-wise log - if(param->getVal()>=0) - total *= pow(_high[i]/_nominal, +param->getVal()); - else - total *= pow(_low[i]/_nominal, -param->getVal()); - break ; - } - case 2: { - // parabolic with linear - double a = 0.5*(_high[i]+_low[i])-_nominal; - double b = 0.5*(_high[i]-_low[i]); - double c = 0; - if(param->getVal()>1 ){ - total += (2*a+b)*(param->getVal()-1)+_high[i]-_nominal; - } else if(param->getVal()<-1 ) { - total += -1*(2*a-b)*(param->getVal()+1)+_low[i]-_nominal; - } else { - total += a*pow(param->getVal(),2) + b*param->getVal()+c; - } - break ; - } - case 3: { - //parabolic version of log-normal - double a = 0.5*(_high[i]+_low[i])-_nominal; - double b = 0.5*(_high[i]-_low[i]); - double c = 0; - if(param->getVal()>1 ){ - total += (2*a+b)*(param->getVal()-1)+_high[i]-_nominal; - } else if(param->getVal()<-1 ) { - total += -1*(2*a-b)*(param->getVal()+1)+_low[i]-_nominal; - } else { - total += a*pow(param->getVal(),2) + b*param->getVal()+c; - } - break ; - } - - case 4: { - double boundary = _interpBoundary; - double x = param->getVal(); - //std::cout << icode << " param " << param->GetName() << " " << param->getVal() << " boundary " << boundary << std::endl; - if(x >= boundary) - { - total *= std::pow(_high[i]/_nominal, +param->getVal()); - } - else if (x <= -boundary) - { - total *= std::pow(_low[i]/_nominal, -param->getVal()); - } - else if (x != 0) - { - total *= PolyInterpValue(i, x); - } - break ; - } - default: { - coutE(InputArguments) << "FlexibleInterpVar::evaluate ERROR: " << param->GetName() - << " with unknown interpolation code" << endl ; - } - } - ++i; + for (std::size_t i = 0; i < _paramList.size(); ++i) { + if (_interpCode[i] < 0 || _interpCode[i] > 4) { + coutE(InputArguments) << "FlexibleInterpVar::evaluate ERROR: param " << i << " with unknown interpolation code" + << std::endl; + } + total = RooFit::Detail::EvaluateFuncs::flexibleInterp(_interpCode[i], _low[i], + _high[i], _interpBoundary, _nominal, + dataMap.at(&_paramList[i])[0], total); } if(total<=0) { total= TMath::Limits::Min(); } - return total; + output[0] = total; } -void FlexibleInterpVar::printMultiline(ostream& os, Int_t contents, +void FlexibleInterpVar::printMultiline(std::ostream& os, Int_t contents, bool verbose, TString indent) const { RooAbsReal::printMultiline(os,contents,verbose,indent); - os << indent << "--- FlexibleInterpVar ---" << endl; + os << indent << "--- FlexibleInterpVar ---" << std::endl; printFlexibleInterpVars(os); } -void FlexibleInterpVar::printFlexibleInterpVars(ostream& os) const +void FlexibleInterpVar::printFlexibleInterpVars(std::ostream& os) const { for (int i=0;i<(int)_low.size();i++) { auto& param = static_cast(_paramList[i]); - os << setw(36) << param.GetName()<<": "< + +#include + +#include +#include +#include +#include +#include +#include + +namespace RooStats { +namespace HistFactory { +namespace Detail { + +/** + * \brief Configure constrained gamma parameters for fitting. + * + * This function configures constrained gamma parameters for fitting. If a + * given relative sigma is less than or equal to zero or below a threshold, the + * gamma parameter is set to be constant. The function also sets reasonable + * ranges for the gamma parameter and provides a reasonable starting point for + * pre-fit errors. + * + * @param gammas The gamma parameters to be configured. + * @param sigmaRel The relative sigma values to be used for configuring the + * limits and errors. + * @param minSigma The minimum relative sigma threshold. If a relative sigma is + * below this threshold, the gamma parameter is set to be + * constant. + */ +void configureConstrainedGammas(RooArgList const &gammas, std::span relSigmas, double minSigma) +{ + assert(gammas.size() == relSigmas.size()); + + for (std::size_t i = 0; i < gammas.size(); ++i) { + auto &gamma = *static_cast(gammas.at(i)); + double sigmaRel = relSigmas[i]; + + // If the sigma is zero, the parameter might as well be constant + if (sigmaRel <= 0) { + gamma.setConstant(true); + continue; + } + + // Set reasonable ranges + gamma.setMax(1. + 5. * sigmaRel); + gamma.setMin(0.); + + // Give reasonable starting point for pre-fit errors by setting it to the + // absolute sigma Mostly useful for pre-fit plotting. + // Note: in commit 2129c4d920 "[HF] Reduce verbosity of HistFactory." + // from 2020, there was a check added to do this only for Gaussian + // constrained parameters and for Poisson constrained parameters if they + // are stat errors without any justification. In the ROOT 6.30 + // development cycle, this check got removed again to cause less surprise + // to the user. + gamma.setError(sigmaRel); + + // If the sigma value is less than a supplied threshold, set the variable to + // constant + if (sigmaRel < minSigma) { + oocxcoutW(static_cast(nullptr), HistFactory) + << "Warning: relative sigma " << sigmaRel << " for \"" << gamma.GetName() << "\" falls below threshold of " + << minSigma << ". Setting: " << gamma.GetName() << " to constant" << std::endl; + gamma.setConstant(true); + } + } +} + +// Take a RooArgList of RooAbsReals and create N constraint terms (one for +// each gamma) whose relative uncertainty is the value of the ith RooAbsReal +CreateGammaConstraintsOutput createGammaConstraints(RooArgList const ¶mSet, + std::span relSigmas, double minSigma, + Constraint::Type type) +{ + CreateGammaConstraintsOutput out; + + // Check that there are N elements in the RooArgList + if (relSigmas.size() != paramSet.size()) { + std::cout << "Error: In createGammaConstraints, encountered bad number of relative sigmas" << std::endl; + std::cout << "Given vector with " << relSigmas.size() << " bins," + << " but require exactly " << paramSet.size() << std::endl; + throw hf_exc(); + } + + configureConstrainedGammas(paramSet, relSigmas, minSigma); + + for (std::size_t i = 0; i < paramSet.size(); ++i) { + + RooRealVar &gamma = static_cast(paramSet[i]); + + oocxcoutI(static_cast(nullptr), HistFactory) + << "Creating constraint for: " << gamma.GetName() << ". Type of constraint: " << type << std::endl; + + const double sigmaRel = relSigmas[i]; + + // If the sigma is <= 0, + // do cont create the term + if (sigmaRel <= 0) { + oocxcoutI(static_cast(nullptr), HistFactory) + << "Not creating constraint term for " << gamma.GetName() << " because sigma = " << sigmaRel + << " (sigma<=0)" + << " (bin number = " << i << ")" << std::endl; + continue; + } + + // Make Constraint Term + std::string constrName = std::string(gamma.GetName()) + "_constraint"; + std::string nomName = std::string("nom_") + gamma.GetName(); + + if (type == Constraint::Gaussian) { + + // Type 1 : RooGaussian + + // Make sigma + std::string sigmaName = std::string(gamma.GetName()) + "_sigma"; + auto constrSigma = std::make_unique(sigmaName.c_str(), sigmaName.c_str(), sigmaRel); + + // Make "observed" value + auto constrNom = std::make_unique(nomName.c_str(), nomName.c_str(), 1.0, 0, 10); + constrNom->setConstant(true); + + // Make the constraint: + auto term = std::make_unique(constrName.c_str(), constrName.c_str(), *constrNom, gamma, *constrSigma); + + out.globalObservables.push_back(constrNom.get()); + + term->addOwnedComponents(std::move(constrSigma)); + term->addOwnedComponents(std::move(constrNom)); + + out.constraints.emplace_back(std::move(term)); + } else if (type == Constraint::Poisson) { + + // this is correct Poisson equivalent to a Gaussian with mean 1 and stdev sigma + const double tau = 1. / (sigmaRel * sigmaRel); + + // Make nominal "observed" value + auto constrNom = std::make_unique(nomName.c_str(), nomName.c_str(), tau); + constrNom->setMin(0); + constrNom->setConstant(true); + + // Make the scaling term + std::string scalingName = std::string(gamma.GetName()) + "_tau"; + auto poissonScaling = std::make_unique(scalingName.c_str(), scalingName.c_str(), tau); + + // Make mean for scaled Poisson + std::string poisMeanName = std::string(gamma.GetName()) + "_poisMean"; + auto constrMean = std::make_unique(poisMeanName.c_str(), poisMeanName.c_str(), gamma, *poissonScaling); + + // Type 2 : RooPoisson + auto term = std::make_unique(constrName.c_str(), constrName.c_str(), *constrNom, *constrMean); + term->setNoRounding(true); + + out.globalObservables.push_back(constrNom.get()); + + term->addOwnedComponents(std::move(poissonScaling)); + term->addOwnedComponents(std::move(constrMean)); + term->addOwnedComponents(std::move(constrNom)); + + out.constraints.emplace_back(std::move(term)); + } else { + + std::cout << "Error: Did not recognize Stat Error constraint term type: " << type + << " for : " << gamma.GetName() << std::endl; + throw hf_exc(); + } + } // end loop over parameters + + return out; +} + +} // namespace Detail +} // namespace HistFactory +} // namespace RooStats diff --git a/roofit/histfactory/src/HistFactoryModelUtils.cxx b/roofit/histfactory/src/HistFactoryModelUtils.cxx index a9cfdd0287d5f..0972f7d563fa2 100644 --- a/roofit/histfactory/src/HistFactoryModelUtils.cxx +++ b/roofit/histfactory/src/HistFactoryModelUtils.cxx @@ -44,7 +44,8 @@ namespace HistFactory{ RooAbsPdf* sum_pdf = nullptr; bool FoundSumPdf=false; - for (auto *sum_pdf_arg : *sim_channel->getComponents()) { + std::unique_ptr components{sim_channel->getComponents()}; + for (auto *sum_pdf_arg : *components) { std::string NodeClassName = sum_pdf_arg->ClassName(); if( NodeClassName == std::string("RooRealSumPdf") ) { FoundSumPdf=true; @@ -83,7 +84,7 @@ namespace HistFactory{ } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast(&pdf); std::unique_ptr cat{static_cast(sim->indexCat().Clone())}; - for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) { + for (int ic = 0, nc = cat->numBins((const char *)nullptr); ic < nc; ++ic) { cat->setBin(ic); FactorizeHistFactoryPdf(observables, *sim->getPdf(cat->getCurrentLabel()), obsTerms, constraints); } @@ -101,7 +102,8 @@ namespace HistFactory{ // Find the servers of this channel bool FoundParamHistFunc=false; - for( auto *paramfunc_arg : *channel->getComponents() ) { + std::unique_ptr components{channel->getComponents()}; + for( auto *paramfunc_arg : *components) { std::string NodeName = paramfunc_arg->GetName(); std::string NodeClassName = paramfunc_arg->ClassName(); if( NodeClassName != std::string("ParamHistFunc") ) continue; @@ -171,7 +173,7 @@ namespace HistFactory{ if(verbose) dataForChan->Print(); // Generate observables defined by the pdf associated with this state - RooArgSet* obstmp = pdftmp->getObservables(*dataForChan->get()) ; + std::unique_ptr obstmp{pdftmp->getObservables(*dataForChan->get())}; RooRealVar* obs = ((RooRealVar*)obstmp->first()); if(verbose) obs->Print(); diff --git a/roofit/histfactory/src/HistFactoryNavigation.cxx b/roofit/histfactory/src/HistFactoryNavigation.cxx index ea10bffe949b5..4807cf1843211 100644 --- a/roofit/histfactory/src/HistFactoryNavigation.cxx +++ b/roofit/histfactory/src/HistFactoryNavigation.cxx @@ -16,8 +16,8 @@ #include "RooCategory.h" #include "RooSimultaneous.h" #include "RooWorkspace.h" +#include "RooFit/ModelConfig.h" -#include "RooStats/ModelConfig.h" #include "RooStats/HistFactory/HistFactoryNavigation.h" #include "RooStats/HistFactory/HistFactoryException.h" @@ -324,7 +324,7 @@ namespace RooStats { std::string channel_name = fChannelNameVec.at(i_chan); // If we pass a channel string, we only print that one channel - if( channel_to_print != "" && channel_name != channel_to_print) continue; + if( !channel_to_print.empty() && channel_name != channel_to_print) continue; std::unique_ptr data_hist{GetDataHist(data, channel_name, channel_name+"_tmp")}; std::cout << std::setw(_label_print_width) << channel_name + " (data)"; @@ -354,7 +354,8 @@ namespace RooStats { void HistFactoryNavigation::PrintParameters(bool IncludeConstantParams) { // Get the list of parameters - RooArgSet* params = fModel->getParameters(*fObservables); + RooArgSet params; + fModel->getParameters(fObservables, params); std::cout << std::endl; @@ -366,7 +367,7 @@ namespace RooStats { << std::endl; // Loop over the parameters and print their values, etc - for (auto const *param : static_range_cast(*params)) { + for (auto const *param : static_range_cast(params)) { if( !IncludeConstantParams && param->isConstant() ) continue; std::cout << std::setw(30) << param->GetName(); @@ -383,7 +384,8 @@ namespace RooStats { bool IncludeConstantParams) { // Get the list of parameters - RooArgSet* params = fModel->getParameters(*fObservables); + RooArgSet params; + fModel->getParameters(fObservables, params); // Get the pdf for this channel RooAbsPdf* channel_pdf = GetChannelPdf(channel); @@ -398,7 +400,7 @@ namespace RooStats { << std::endl; // Loop over the parameters and print their values, etc - for (auto const *param : static_range_cast(*params)) { + for (auto const *param : static_range_cast(params)) { if( !IncludeConstantParams && param->isConstant() ) continue; if( findChild(param->GetName(), channel_pdf)==nullptr ) continue; std::cout << std::setw(30) << param->GetName(); @@ -417,7 +419,8 @@ namespace RooStats { bool IncludeConstantParams) { // Get the list of parameters - RooArgSet* params = fModel->getParameters(*fObservables); + RooArgSet params; + fModel->getParameters(fObservables, params); // Get the pdf for this channel RooAbsReal* sample_func = SampleFunction(channel, sample); @@ -432,7 +435,7 @@ namespace RooStats { << std::endl; // Loop over the parameters and print their values, etc - for (auto const *param : static_range_cast(*params)) { + for (auto const *param : static_range_cast(params)) { if( !IncludeConstantParams && param->isConstant() ) continue; if( findChild(param->GetName(), sample_func)==nullptr ) continue; std::cout << std::setw(30) << param->GetName(); @@ -452,7 +455,7 @@ namespace RooStats { // (Could be optimized, it uses an intermediate histogram for now...) // Get the histogram, fetch the bin content, and return - std::unique_ptr channel_hist_tmp{GetChannelHist(channel, (channel+"_tmp").c_str())}; + std::unique_ptr channel_hist_tmp{GetChannelHist(channel, channel+"_tmp")}; return channel_hist_tmp->GetBinContent(bin); } @@ -464,7 +467,7 @@ namespace RooStats { // Could be optimized, it uses an intermediate histogram for now...) // Get the histogram, fetch the bin content, and return - std::unique_ptr sample_hist_tmp{GetSampleHist(channel, sample, (channel+"_tmp").c_str())}; + std::unique_ptr sample_hist_tmp{GetSampleHist(channel, sample, channel+"_tmp")}; return sample_hist_tmp->GetBinContent(bin); } @@ -485,7 +488,7 @@ namespace RooStats { RooAbsReal* HistFactoryNavigation::SampleFunction(const std::string& channel, const std::string& sample){ - // Return the function object pointer cooresponding + // Return the function object pointer corresponding // to a particular sample in a particular channel std::map< std::string, std::map< std::string, RooAbsReal*> >::iterator channel_itr; @@ -532,7 +535,7 @@ namespace RooStats { RooArgList observable_list( *GetObservableSet(channel) ); std::string name = hist_name; - if(hist_name=="") name = channel + "_" + sample + "_hist"; + if(hist_name.empty()) name = channel + "_" + sample + "_hist"; RooAbsReal* sample_function = SampleFunction(channel, sample); @@ -579,7 +582,7 @@ namespace RooStats { total_hist->Add(sample_hist.get()); } - if(hist_name=="") total_hist->SetName(hist_name.c_str()); + if(hist_name.empty()) total_hist->SetName(hist_name.c_str()); else total_hist->SetName( (channel + "_hist").c_str() ); return total_hist; @@ -641,7 +644,7 @@ namespace RooStats { RooSimultaneous* simPdf = (RooSimultaneous*) fModel; RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat()); - dataset_list.reset(data->split(*channelCat)); + dataset_list = std::unique_ptr{data->split(*channelCat)}; data = dynamic_cast( dataset_list->FindObject(channel.c_str()) ); @@ -746,11 +749,6 @@ namespace RooStats { //RooAbsPdf* modelPdf = mc->GetPdf(); //RooArgSet* observables = mc->GetObservables(); - // Create vectors to hold the channel pdf's - // as well as the set of observables for each channel - //std::map< std::string, RooAbsPdf* > channelPdfMap; - //std::map< std::string, RooArgSet* > channelObservMap; - // Check if it is a simultaneous pdf or not // (if it's an individual channel, it won't be, if it's // combined, it's simultaneous) @@ -769,13 +767,13 @@ namespace RooStats { const std::string& ChannelName = nameIdx.first; fChannelNameVec.push_back( ChannelName ); RooAbsPdf* pdftmp = simPdf->getPdf(ChannelName.c_str()) ; - RooArgSet* obstmp = pdftmp->getObservables(*observables) ; + RooArgSet* obstmp = std::unique_ptr{pdftmp->getObservables(*observables)}.release(); fChannelPdfMap[ChannelName] = pdftmp; fChannelObservMap[ChannelName] = obstmp; } } else { - RooArgSet* obstmp = modelPdf->getObservables(*observables) ; + RooArgSet* obstmp = std::unique_ptr{modelPdf->getObservables(*observables)}.release(); // The channel name is model_CHANNEL std::string ChannelName = modelPdf->GetName(); ChannelName = ChannelName.replace(0, 6, ""); @@ -800,7 +798,8 @@ namespace RooStats { // the (one) that is a RooRealSumPdf // Based on the mode, we assume that node is // the "unconstrained" pdf node for that channel - for (auto *arg : *pdf->getComponents()) { + std::unique_ptr comps{pdf->getComponents()}; + for (auto *arg : *comps) { std::string ClassName = arg->ClassName(); if( ClassName == "RooRealSumPdf" ) { fChannelSumNodeMap[ChannelName] = static_cast (arg); @@ -836,8 +835,8 @@ namespace RooStats { size_t index = SampleName.find("L_x_"); SampleName.replace( index, 4, "" ); } - if( SampleName.find(ChannelName.c_str()) != std::string::npos ) { - size_t index = SampleName.find(ChannelName.c_str()); + if( SampleName.find(ChannelName) != std::string::npos ) { + size_t index = SampleName.find(ChannelName); SampleName = SampleName.substr(0, index-1); } @@ -861,7 +860,8 @@ namespace RooStats { // Check if it is a "component", // ie a sub node: - for (auto arg : *parent->getComponents()) { + std::unique_ptr comps{parent->getComponents()}; + for (auto arg : *comps) { std::string ArgName = arg->GetName(); if (ArgName == name) { term = arg; @@ -875,7 +875,8 @@ namespace RooStats { // Check if it's a Parameter // (ie a RooRealVar) RooArgSet args; - for (auto *param : *parent->getParameters(&args)) { + std::unique_ptr parameters{parent->getParameters(&args)}; + for (auto *param : *parameters) { std::string ParamName = param->GetName(); if( ParamName == name ) { term = param; @@ -947,7 +948,7 @@ namespace RooStats { // Find its value double sigma = 0.0; - if( ConstraintType == "" ) { + if( ConstraintType.empty() ) { std::cout << "Error: Constraint type is an empty string." << " This simply should not be." << std::endl; throw hf_exc(); @@ -1012,6 +1013,12 @@ namespace RooStats { throw hf_exc(); } + + const std::string attrib = "ORIGNAME:" + ToReplace; + const bool oldAttrib = ReplaceWith->getAttribute(attrib.c_str()); + ReplaceWith->setAttribute(attrib.c_str()); + RooArgSet newServerSet{*ReplaceWith}; + // Now that we have the node we want to replace, we have to // get its parent node @@ -1025,14 +1032,15 @@ namespace RooStats { if( findChild(client->GetName(), fModel) == nullptr) continue; // Now, do the replacement: - bool valueProp=false; - bool shapeProp=false; - client->replaceServer( *nodeToReplace, *ReplaceWith, valueProp, shapeProp ); + client->redirectServers(newServerSet); std::cout << "Replaced: " << ToReplace << " with: " << ReplaceWith->GetName() << " in node: " << client->GetName() << std::endl; } + // reset temporary attribute for server redirection + ReplaceWith->setAttribute(attrib.c_str(), oldAttrib); + return; } @@ -1096,12 +1104,7 @@ namespace RooStats { RooFit::MsgLevel levelBefore = RooMsgService::instance().globalKillBelow(); RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL); std::unique_ptr hist; - try { - hist.reset(MakeHistFromRooFunction( component, observable_list, NodeName+"_tmp")); - } catch(...) { - RooMsgService::instance().setGlobalKillBelow(levelBefore); - throw; - } + hist.reset(MakeHistFromRooFunction( component, observable_list, NodeName+"_tmp")); RooMsgService::instance().setGlobalKillBelow(levelBefore); // Print the hist @@ -1191,7 +1194,8 @@ namespace RooStats { // set the constant as // Get the list of parameters - RooArgSet* params = fModel->getParameters(*fObservables); + RooArgSet params; + fModel->getParameters(fObservables, params); std::cout << std::endl; @@ -1203,7 +1207,7 @@ namespace RooStats { << std::endl; // Loop over the parameters and print their values, etc - for (auto *param : static_range_cast(*params)) { + for (auto *param : static_range_cast(params)) { std::string ParamName = param->GetName(); TString ParamNameTString(ParamName); diff --git a/roofit/histfactory/src/HistRef.cxx b/roofit/histfactory/src/HistRef.cxx index 07f41f3328c49..f7d3af851a132 100644 --- a/roofit/histfactory/src/HistRef.cxx +++ b/roofit/histfactory/src/HistRef.cxx @@ -24,7 +24,7 @@ namespace HistFactory { TH1 * HistRef::CopyObject(const TH1 * h) { // implementation of method copying the contained pointer // (just use Clone) - if (!h) return 0; + if (!h) return nullptr; return static_cast(h->Clone()); } } diff --git a/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx b/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx index 41edcd7fbb1b6..0f33f29acb7f0 100644 --- a/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx +++ b/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx @@ -19,20 +19,14 @@ */ -#ifndef __CINT__ #include "RooGlobalFunc.h" -#endif - #include "RooDataSet.h" #include "RooRealVar.h" #include "RooConstVar.h" -#include "RooAddition.h" #include "RooProduct.h" #include "RooProdPdf.h" -#include "RooAddPdf.h" #include "RooGaussian.h" #include "RooPoisson.h" -#include "RooExponential.h" #include "RooRandom.h" #include "RooCategory.h" #include "RooSimultaneous.h" @@ -42,19 +36,18 @@ #include "RooFitResult.h" #include "RooDataHist.h" #include "RooHistFunc.h" -#include "RooHistPdf.h" #include "RooRealSumPdf.h" #include "RooWorkspace.h" -#include "RooCustomizer.h" -#include "RooPlot.h" #include "RooHelpers.h" #include "RooBinning.h" #include "RooBinWidthFunction.h" +#include "RooFit/ModelConfig.h" + #include "RooStats/RooStatsUtils.h" -#include "RooStats/ModelConfig.h" #include "RooStats/HistFactory/PiecewiseInterpolation.h" #include "RooStats/HistFactory/ParamHistFunc.h" #include "RooStats/AsymptoticCalculator.h" + #include "HFMsgService.h" #include "TH1.h" @@ -63,6 +56,7 @@ #include "TMatrixDSym.h" // specific to this package +#include #include "RooStats/HistFactory/LinInterpVar.h" #include "RooStats/HistFactory/FlexibleInterpVar.h" #include "RooStats/HistFactory/HistoToWorkspaceFactoryFast.h" @@ -73,18 +67,27 @@ #include #include -#define VERBOSE +constexpr double alphaLow = -5.0; +constexpr double alphaHigh = 5.0; -#define alpha_Low "-5" -#define alpha_High "5" -#define NoHistConst_Low "0" -#define NoHistConst_High "2000" +std::vector histToVector(TH1 const &hist) +{ + // Must get the full size of the TH1 (No direct method to do this...) + int numBins = hist.GetNbinsX() * hist.GetNbinsY() * hist.GetNbinsZ(); + std::vector out(numBins); + for (int i = 0; i < numBins; ++i) { + out[i] = hist.GetBinContent(i + 1); + } + return out; +} // use this order for safety on library loading -using namespace RooFit ; using namespace RooStats ; using namespace std ; +using namespace RooStats::HistFactory::Detail; +using namespace RooStats::HistFactory::Detail::MagicConstants; + ClassImp(RooStats::HistFactory::HistoToWorkspaceFactoryFast); namespace RooStats{ @@ -122,24 +125,21 @@ namespace HistFactory{ throw hf_exc(); } - std::vector poi_list = measurement.GetPOIList(); - if( poi_list.empty() ) { + if( measurement.GetPOIList().empty() ) { cxcoutWHF << "No Parametetrs of interest are set" << std::endl; } std::stringstream sstream; sstream << "Setting Parameter(s) of Interest as: "; - for(unsigned int i = 0; i < poi_list.size(); ++i) { - sstream << poi_list.at(i) << " "; + for(auto const& item : measurement.GetPOIList()) { + sstream << item << " "; } cxcoutIHF << sstream.str() << endl; RooArgSet params; - for( unsigned int i = 0; i < poi_list.size(); ++i ) { - std::string poi_name = poi_list.at(i); - RooRealVar* poi = (RooRealVar*) ws_single->var(poi_name); - if(poi){ + for(auto const& poi_name : measurement.GetPOIList()) { + if(RooRealVar* poi = (RooRealVar*) ws_single->var(poi_name)){ params.add(*poi); } else { @@ -160,7 +160,7 @@ namespace HistFactory{ << " in workspace" << std::endl; throw hf_exc(); } - if(poi_list.size()!=0){ + if(!measurement.GetPOIList().empty()){ proto_config->GuessObsAndNuisance(*expData, RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::INFO)); } @@ -177,7 +177,7 @@ namespace HistFactory{ // Create a SnapShot of the nominal values std::string SnapShotName = "NominalParamValues"; - ws_single->saveSnapshot(SnapShotName.c_str(), ws_single->allVars()); + ws_single->saveSnapshot(SnapShotName, ws_single->allVars()); for( unsigned int i=0; i asimov_dataset{static_cast(AsymptoticCalculator::GenerateAsimovData(*pdf, *observables))}; + std::unique_ptr asimov_dataset{AsymptoticCalculator::GenerateAsimovData(*pdf, *observables)}; cxcoutPHF << "Importing Asimov dataset" << std::endl; - bool failure = ws_single->import(*asimov_dataset, Rename(AsimovName.c_str())); + bool failure = ws_single->import(*asimov_dataset, RooFit::Rename(AsimovName.c_str())); if( failure ) { std::cout << "Error: Failed to import Asimov dataset: " << AsimovName << std::endl; @@ -207,8 +207,8 @@ namespace HistFactory{ } - // We want to eliminate this interface and use the measurment directly - RooWorkspace* HistoToWorkspaceFactoryFast::MakeSingleChannelModel( Measurement& measurement, Channel& channel ) { + // We want to eliminate this interface and use the measurement directly + RooFit::OwningPtr HistoToWorkspaceFactoryFast::MakeSingleChannelModel( Measurement& measurement, Channel& channel ) { // This is a pretty light-weight wrapper function // @@ -223,7 +223,7 @@ namespace HistFactory{ string ch_name = channel.GetName(); // Create a workspace for a SingleChannel from the Measurement Object - RooWorkspace* ws_single = this->MakeSingleChannelWorkspace(measurement, channel); + std::unique_ptr ws_single{this->MakeSingleChannelWorkspace(measurement, channel)}; if( ws_single == nullptr ) { cxcoutF(HistFactory) << "Error: Failed to make Single-Channel workspace for channel: " << ch_name << " and measurement: " << measurement.GetName() << std::endl; @@ -232,13 +232,13 @@ namespace HistFactory{ // Finally, configure that workspace based on // properties of the measurement - HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "model_"+ch_name, ws_single, measurement ); + HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "model_"+ch_name, ws_single.get(), measurement ); - return ws_single; + return RooFit::Detail::owningPtr(std::move(ws_single)); } - RooWorkspace* HistoToWorkspaceFactoryFast::MakeCombinedModel( Measurement& measurement ) { + RooFit::OwningPtr HistoToWorkspaceFactoryFast::MakeCombinedModel( Measurement& measurement ) { // This function takes a fully configured measurement // which may contain several channels and returns @@ -259,9 +259,7 @@ namespace HistFactory{ vector> channel_workspaces; vector channel_names; - for( unsigned int chanItr = 0; chanItr < measurement.GetChannels().size(); ++chanItr ) { - - HistFactory::Channel& channel = measurement.GetChannels().at( chanItr ); + for(HistFactory::Channel& channel : measurement.GetChannels()) { if( ! channel.CheckHistograms() ) { cxcoutFHF << "MakeModelAndMeasurementsFast: Channel: " << channel.GetName() @@ -273,39 +271,44 @@ namespace HistFactory{ channel_names.push_back(ch_name); // GHL: Renaming to 'MakeSingleChannelWorkspace' - RooWorkspace* ws_single = factory.MakeSingleChannelModel( measurement, channel ); - - channel_workspaces.emplace_back(ws_single); - + channel_workspaces.emplace_back(factory.MakeSingleChannelModel(measurement, channel)); } // Now, combine the individual channel workspaces to // form the combined workspace - RooWorkspace* ws = factory.MakeCombinedModel( channel_names, channel_workspaces ); + std::unique_ptr ws{factory.MakeCombinedModel( channel_names, channel_workspaces )}; // Configure the workspace - HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "simPdf", ws, measurement ); + HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement("simPdf", ws.get(), measurement); // Done. Return the pointer - return ws; + return RooFit::Detail::owningPtr(std::move(ws)); } +namespace { + +template +Arg_t *factory(RooWorkspace &ws, const char *expr, Args_t &&...args) +{ + return static_cast(ws.factory(TString::Format(expr, std::forward(args)...).Data())); +} + +} // namespace + /// Create observables of type RooRealVar. Creates 1 to 3 observables, depending on the type of the histogram. -RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWorkspace *proto) const { +RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWorkspace &proto) const { RooArgList observables; for (unsigned int idx=0; idx < fObsNameVec.size(); ++idx) { - if (!proto->var(fObsNameVec[idx])) { + if (!proto.var(fObsNameVec[idx])) { const TAxis *axis = (idx == 0) ? hist->GetXaxis() : (idx == 1 ? hist->GetYaxis() : hist->GetZaxis()); - Int_t nbins = axis->GetNbins(); - double xmin = axis->GetXmin(); - double xmax = axis->GetXmax(); + int nbins = axis->GetNbins(); // create observable - auto obs = static_cast(proto->factory( - Form("%s[%f,%f]", fObsNameVec[idx].c_str(), xmin, xmax))); + auto obs = factory(proto, "%s[%f,%f]", fObsNameVec[idx].c_str(), axis->GetXmin(), axis->GetXmax()); + if(strlen(axis->GetTitle())>0) obs->SetTitle(axis->GetTitle()); obs->setBins(nbins); if (axis->IsVariableBinSize()) { RooBinning binning(nbins, axis->GetXbins()->GetArray()); @@ -313,20 +316,20 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } } - observables.add(*proto->var(fObsNameVec[idx])); + observables.add(*proto.var(fObsNameVec[idx])); } return observables; } /// Create the nominal hist function from `hist`, and register it in the workspace. - RooHistFunc* HistoToWorkspaceFactoryFast::MakeExpectedHistFunc(const TH1* hist,RooWorkspace* proto, string prefix, + RooHistFunc* HistoToWorkspaceFactoryFast::MakeExpectedHistFunc(const TH1* hist,RooWorkspace &proto, string prefix, const RooArgList& observables) const { if(hist) { cxcoutI(HistFactory) << "processing hist " << hist->GetName() << endl; } else { cxcoutF(HistFactory) << "hist is empty" << endl; - R__ASSERT(hist != 0); + R__ASSERT(hist != nullptr); return nullptr; } @@ -340,13 +343,10 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo prefix += "_Hist_alphanominal"; - RooDataHist histDHist((prefix + "DHist").c_str(),"",observables,hist); - RooHistFunc histFunc(prefix.c_str(),"",observables,histDHist,0); + RooDataHist histDHist(prefix + "DHist","",observables,hist); - proto->import(histFunc, RecycleConflictNodes()); - auto histFuncInWS = static_cast(proto->arg(prefix.c_str())); - - return histFuncInWS; + proto.import(RooHistFunc(prefix.c_str(),"",observables,histDHist,0), RooFit::RecycleConflictNodes()); + return static_cast(proto.arg(prefix)); } namespace { @@ -359,7 +359,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // do nothing if the constraint term already exists if(proto.pdf(constraintName)) return; - // case systematic is uniform (asssume they are like a Gaussian but with + // case systematic is uniform (assume they are like a Gaussian but with // a large width (100 instead of 1) const double gaussSigma = isUniform ? 100. : 1.0; if (isUniform) { @@ -370,6 +370,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo command << "Gaussian::" << constraintName << "(" << paramName << ",nom_" << paramName << "[0.,-10,10]," << gaussSigma << ")"; constraintTermNames.emplace_back(proto.factory(command.str())->GetName()); + proto.var(paramName)->setError(gaussSigma); // give param initial error to match gaussSigma auto * normParam = proto.var(std::string("nom_") + paramName); normParam->setConstant(); const_cast(proto.set("globalObservables"))->add(*normParam); @@ -379,16 +380,8 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo RooArgList makeInterpolationParameters(std::vector const& histoSysList, RooWorkspace& proto) { RooArgList params( ("alpha_Hist") ); - // range is set using defined macro (see top of the page) - string range=string("[")+alpha_Low+","+alpha_High+"]"; - for(auto const& histoSys : histoSysList) { - const std::string histoSysName = histoSys.GetName(); - RooRealVar* temp = proto.var("alpha_" + histoSysName); - if(!temp){ - temp = (RooRealVar*) proto.factory("alpha_" + histoSysName + range); - } - params.add(* temp ); + params.add(getOrCreate(proto, "alpha_" + histoSys.GetName(), alphaLow, alphaHigh)); } return params; @@ -398,26 +391,24 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo /// and return a pointer to it. RooAbsArg* makeLinInterp(RooArgList const& interpolationParams, RooHistFunc* nominalFunc, - RooWorkspace* proto, const std::vector& histoSysList, + RooWorkspace& proto, const std::vector& histoSysList, const string& prefix, - const RooArgList& observables) { + const RooArgList& obsList) { // now make function that linearly interpolates expectation between variations // get low/high variations to interpolate between - vector low, high; - RooArgSet lowSet, highSet; - //ES// for(unsigned int j=0; j low; + std::vector high; + RooArgSet lowSet; + RooArgSet highSet; for(unsigned int j=0; j(str+"lowDHist","",obsList, histoSys.GetHistoLow()); + auto highDHist = std::make_unique(str+"highDHist","",obsList, histoSys.GetHistoHigh()); + lowSet.addOwned(std::make_unique((str+"low").c_str(),"",obsList,std::move(lowDHist),0)); + highSet.addOwned(std::make_unique((str+"high").c_str(),"",obsList,std::move(highDHist),0)); } // this is sigma(params), a piece-wise linear interpolation @@ -425,22 +416,19 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo interp.setPositiveDefinite(); interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise linear to 6th order polynomial interpolation + linear extrapolation ) // KC: interpo codes 1 etc. don't have proper analytic integral. - RooArgSet observableSet(observables); - interp.setBinIntegrator(observableSet); + RooArgSet obsSet(obsList); + interp.setBinIntegrator(obsSet); interp.forceNumInt(); - proto->import(interp, RecycleConflictNodes()); // individual params have already been imported in first loop of this function - - auto interpInWS = proto->arg(prefix.c_str()); - assert(interpInWS); + proto.import(interp, RooFit::RecycleConflictNodes()); // individual params have already been imported in first loop of this function - return interpInWS; + return proto.arg(prefix); } } // GHL: Consider passing the NormFactor list instead of the entire sample - std::unique_ptr HistoToWorkspaceFactoryFast::CreateNormFactor(RooWorkspace* proto, string& channel, string& sigmaEpsilon, Sample& sample, bool doRatio){ + std::unique_ptr HistoToWorkspaceFactoryFast::CreateNormFactor(RooWorkspace& proto, string& channel, string& sigmaEpsilon, Sample& sample, bool doRatio){ std::vector prodNames; @@ -449,22 +437,16 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo string overallNorm_times_sigmaEpsilon = sample.GetName() + "_" + channel + "_scaleFactors"; - auto sigEps = proto->arg(sigmaEpsilon.c_str()); + auto sigEps = proto.arg(sigmaEpsilon); assert(sigEps); auto normFactor = std::make_unique(overallNorm_times_sigmaEpsilon.c_str(), overallNorm_times_sigmaEpsilon.c_str(), RooArgList(*sigEps)); - if(normList.size() > 0){ + if(!normList.empty()){ - for(vector::iterator itr = normList.begin(); itr != normList.end(); ++itr){ - - NormFactor& norm = *itr; - - string varname; + for(NormFactor &norm : normList) { + string varname = norm.GetName(); if(doRatio) { - varname = norm.GetName() + "_" + channel; - } - else { - varname=norm.GetName(); + varname += "_" + channel; } // GHL: Check that the NormFactor doesn't already exist @@ -473,10 +455,10 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo std::stringstream range; range << "[" << norm.GetVal() << "," << norm.GetLow() << "," << norm.GetHigh() << "]"; - if( proto->obj(varname) == nullptr) { + if( proto.obj(varname) == nullptr) { cxcoutI(HistFactory) << "making normFactor: " << norm.GetName() << endl; // remove "doRatio" and name can be changed when ws gets imported to the combined model. - proto->factory(varname + range.str()); + proto.factory(varname + range.str()); } prodNames.push_back(varname); @@ -486,7 +468,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo for (const auto& name : prodNames) { - auto arg = proto->arg(name.c_str()); + auto arg = proto.arg(name); assert(arg); normFactor->addTerm(arg); } @@ -499,7 +481,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo cxcoutI(HistFactory) <<" is duplicated for , but only one factor will be included. \n Instead, define something like" << "\n\t \nin your top-level XML's entry and use \nin your top-level XML's entry and use & systList, vector& constraintTermNames, vector& totSystTermNames) { // add variables for all the relative overall uncertainties we expect - // range is set using defined macro (see top of the page) - - string range=string("[0,")+alpha_Low+","+alpha_High+"]"; totSystTermNames.push_back(prefix); RooArgSet params(prefix.c_str()); @@ -543,18 +522,18 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } double tauVal = 1./(relerr*relerr); double sqtau = 1./relerr; - RooAbsArg * beta = proto->factory(TString::Format("beta_%s[1,0,10]",name) ); + RooAbsArg * beta = factory(proto, "beta_%s[1,0,10]", name); // the global observable (y_s) - RooAbsArg * yvar = proto->factory(TString::Format("nom_%s[%f,0,10]",beta->GetName(),tauVal)) ; + RooAbsArg * yvar = factory(proto, "nom_%s[%f,0,10]",beta->GetName(),tauVal); // the rate of the gamma distribution (theta) - RooAbsArg * theta = proto->factory(TString::Format("theta_%s[%f]",name,1./tauVal)); + RooAbsArg * theta = factory(proto, "theta_%s[%f]",name,1./tauVal); // find alpha as function of beta - RooAbsArg* alphaOfBeta = proto->factory(TString::Format("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",name,name,-sqtau,sqtau)); + RooAbsArg* alphaOfBeta = factory(proto, "PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",name,name,-sqtau,sqtau); // add now the constraint itself Gamma_beta_constraint(beta, y+1, tau, 0 ) // build the gamma parameter k = as y_s + 1 - RooAbsArg * kappa = proto->factory(TString::Format("sum::k_%s(%s,1.)",name,yvar->GetName()) ); - RooAbsArg * gamma = proto->factory(TString::Format("Gamma::%sConstraint(%s, %s, %s, 0.0)",beta->GetName(),beta->GetName(), kappa->GetName(), theta->GetName() ) ); + RooAbsArg * kappa = factory(proto, "sum::k_%s(%s,1.)",name,yvar->GetName()); + RooAbsArg * gamma = factory(proto, "Gamma::%sConstraint(%s, %s, %s, 0.0)",beta->GetName(),beta->GetName(), kappa->GetName(), theta->GetName()); if (RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::DEBUG)) { alphaOfBeta->Print("t"); gamma->Print("t"); @@ -563,7 +542,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // set global observables RooRealVar * gobs = dynamic_cast(yvar); assert(gobs); gobs->setConstant(true); - const_cast(proto->set("globalObservables"))->add(*yvar); + const_cast(proto.set("globalObservables"))->add(*yvar); // add alphaOfBeta in the list of params to interpolate params.add(*alphaOfBeta); @@ -571,13 +550,10 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } else { - RooRealVar* alpha = (RooRealVar*) proto->var(prefix + sys.GetName()); - if(!alpha) { - alpha = (RooRealVar*) proto->factory(prefix + sys.GetName() + range); - } + RooRealVar* alpha = &getOrCreate(proto, prefix + sys.GetName(), 0, alphaLow, alphaHigh); // add the Gaussian constraint part const bool isUniform = meas.GetUniformSyst().count(sys.GetName()) > 0; - makeGaussianConstraint(*alpha, *proto, isUniform, constraintTermNames); + makeGaussianConstraint(*alpha, proto, isUniform, constraintTermNames); // check if exists a log-normal constraint if (meas.GetLogNormSyst().count(sys.GetName()) == 0 && meas.GetGammaSyst().count(sys.GetName()) == 0 ) { @@ -590,16 +566,16 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo double relerr = meas.GetLogNormSyst().find(sys.GetName() )->second; double tauVal = 1./relerr; std::string tauName = "tau_" + sys.GetName(); - proto->factory(TString::Format("%s[%f]",tauName.c_str(),tauVal ) ); + factory(proto, "%s[%f]",tauName.c_str(),tauVal); double kappaVal = 1. + relerr; std::string kappaName = "kappa_" + sys.GetName(); - proto->factory(TString::Format("%s[%f]",kappaName.c_str(),kappaVal ) ); + factory(proto, "%s[%f]",kappaName.c_str(),kappaVal); const char * alphaName = alpha->GetName(); std::string alphaOfBetaName = "alphaOfBeta_" + sys.GetName(); - RooAbsArg * alphaOfBeta = proto->factory(TString::Format("expr::%s('%s*(pow(%s,%s)-1.)',%s,%s,%s)",alphaOfBetaName.c_str(), + RooAbsArg * alphaOfBeta = factory(proto, "expr::%s('%s*(pow(%s,%s)-1.)',%s,%s,%s)",alphaOfBetaName.c_str(), tauName.c_str(),kappaName.c_str(),alphaName, - tauName.c_str(),kappaName.c_str(),alphaName ) ); + tauName.c_str(),kappaName.c_str(),alphaName); cxcoutI(HistFactory) << "Added a log-normal constraint for " << name << std::endl; if (RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::DEBUG)) @@ -616,7 +592,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } // end sys loop - if(systList.size() > 0){ + if(!systList.empty()){ // this is epsilon(alpha_j), a piece-wise linear interpolation // LinInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec); @@ -626,21 +602,17 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo FlexibleInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec); interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise linear to 6th order polynomial interpolation + linear extrapolation ) //interp.setAllInterpCodes(0); // simple linear interpolation - proto->import(interp); // params have already been imported in first loop of this function + proto.import(interp); // params have already been imported in first loop of this function } else{ // some strange behavior if params,lowVec,highVec are empty. //cout << "WARNING: No OverallSyst terms" << endl; RooConstVar interp( (interpName).c_str(), "", 1.); - proto->import(interp); // params have already been imported in first loop of this function + proto.import(interp); // params have already been imported in first loop of this function } - - // std::cout << "after creating FlexibleInterpVar " << std::endl; - // proto->Print(); - } - void HistoToWorkspaceFactoryFast::MakeTotalExpected(RooWorkspace* proto, const string& totName, + void HistoToWorkspaceFactoryFast::MakeTotalExpected(RooWorkspace& proto, const string& totName, const vector& sampleScaleFactors, std::vector>& sampleHistFuncs) const { assert(sampleScaleFactors.size() == sampleHistFuncs.size()); @@ -659,8 +631,8 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Prepare a function to divide all bin contents by bin width to get a density: const std::string binWidthFunctionName = totName + "_binWidth"; RooBinWidthFunction binWidth(binWidthFunctionName.c_str(), "Divide by bin width to obtain probability density", *firstHistFunc, true); - proto->import(binWidth); - auto binWidthWS = proto->function(binWidthFunctionName.c_str()); + proto.import(binWidth); + auto binWidthWS = proto.function(binWidthFunctionName); assert(binWidthWS); // Loop through samples and create products of their functions: @@ -686,9 +658,9 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo name = name.substr(0, pos) + "shapes"; } - RooProduct shapeProduct(name.c_str(), name.c_str(), RooArgSet(thisSampleHistFuncs.begin(), thisSampleHistFuncs.end())); - proto->import(shapeProduct, RecycleConflictNodes()); - shapeList.add(*proto->function(name.c_str())); + RooProduct shapeProduct(name.c_str(), thisSampleHistFuncs.front()->GetTitle(), RooArgSet(thisSampleHistFuncs.begin(), thisSampleHistFuncs.end())); + proto.import(shapeProduct, RooFit::RecycleConflictNodes()); + shapeList.add(*proto.function(name)); } } @@ -707,7 +679,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo tot.setAttribute("BinnedLikelihood"); } - proto->import(tot, RecycleConflictNodes()); + proto.import(tot, RooFit::RecycleConflictNodes()); } ////////////////////////////////////////////////////////////////////////////// @@ -738,14 +710,14 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo /////////////////////////////////////////////// - RooWorkspace* HistoToWorkspaceFactoryFast::MakeSingleChannelWorkspace(Measurement& measurement, Channel& channel) { + std::unique_ptr HistoToWorkspaceFactoryFast::MakeSingleChannelWorkspace(Measurement& measurement, Channel& channel) { // check inputs (see JIRA-6890 ) if (channel.GetSamples().empty()) { Error("MakeSingleChannelWorkspace", "The input Channel does not contain any sample - return a nullptr"); - return 0; + return nullptr; } const TH1* channel_hist_template = channel.GetSamples().front().GetHisto(); @@ -759,7 +731,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo << " in channel " << channel.GetName() << " does not contain a histogram. This is the channel:\n"; channel.Print(stream); Error("MakeSingleChannelWorkspace", "%s", stream.str().c_str()); - return 0; + return nullptr; } if( ! channel.CheckHistograms() ) { @@ -797,7 +769,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo fObsNameVec.push_back( fObsName ); } - if (fObsNameVec.empty() || fObsNameVec.size() >= 3) { + if (fObsNameVec.empty() || fObsNameVec.size() > 3) { throw hf_exc("HistFactory is limited to 1- to 3-dimensional histograms."); } @@ -809,16 +781,16 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // // our main workspace that we are using to construct the model // - RooWorkspace* proto = new RooWorkspace(channel_name.c_str(), (channel_name+" workspace").c_str()); - auto proto_config = make_unique("ModelConfig", proto); - proto_config->SetWorkspace(*proto); + auto protoOwner = std::make_unique(channel_name.c_str(), (channel_name+" workspace").c_str()); + RooWorkspace &proto = *protoOwner; + auto proto_config = make_unique("ModelConfig", &proto); + proto_config->SetWorkspace(proto); // preprocess functions - vector::iterator funcIter = fPreprocessFunctions.begin(); - for(;funcIter!= fPreprocessFunctions.end(); ++funcIter){ - cxcoutI(HistFactory) << "will preprocess this line: " << *funcIter <factory(*funcIter); - proto->Print(); + for(auto const& func : fPreprocessFunctions){ + cxcoutI(HistFactory) << "will preprocess this line: " << func <factory(lumiStr.str()); - cxcoutI(HistFactory) << "lumi str = " << lumiStr.str() << endl; - - std::stringstream lumiErrorStr; - lumiErrorStr << "nominalLumi["<factory("Gaussian::lumiConstraint(Lumi,"+lumiErrorStr.str()+")"); - proto->var("nominalLumi")->setConstant(); - proto->defineSet("globalObservables","nominalLumi"); - //likelihoodTermNames.push_back("lumiConstraint"); - constraintTermNames.push_back("lumiConstraint"); - cxcoutI(HistFactory) << "lumi Error str = " << lumiErrorStr.str() << endl; - - //proto->factory("SigXsecOverSM[1.,0.5,1..8]"); + getOrCreate(proto, "Lumi", fNomLumi, 0.0, 10 * fNomLumi); + + // only include a lumiConstraint if there's a lumi uncert, otherwise just set the lumi constant + if(fLumiError != 0) { + std::stringstream lumiErrorStr; + lumiErrorStr << "nominalLumi["<setError(fLumiError/fNomLumi); // give initial error value + proto.var("nominalLumi")->setConstant(); + proto.defineSet("globalObservables","nominalLumi"); + //likelihoodTermNames.push_back("lumiConstraint"); + constraintTermNames.push_back("lumiConstraint"); + } else { + proto.var("Lumi")->setConstant(); + } + //proto.factory("SigXsecOverSM[1.,0.5,1..8]"); /////////////////////////////////// // loop through estimates, add expectation, floating bin predictions, // and terms that constrain floating to expectation via uncertainties @@ -909,12 +881,12 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo string constraintPrefix = sample.GetName() + "_" + channel_name + "_Hist_alpha"; // make list of abstract parameters that interpolate in space of variations - RooArgList interpParams = makeInterpolationParameters(sample.GetHistoSysList(), *proto); + RooArgList interpParams = makeInterpolationParameters(sample.GetHistoSysList(), proto); - // next, cerate the constraint terms + // next, create the constraint terms for(std::size_t i = 0; i < interpParams.size(); ++i) { bool isUniform = measurement.GetUniformSyst().count(sample.GetHistoSysList()[i].GetName()) > 0; - makeGaussianConstraint(interpParams[i], *proto, isUniform, constraintTermNames); + makeGaussianConstraint(interpParams[i], proto, isUniform, constraintTermNames); } // finally, create the interpolated function @@ -922,6 +894,8 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo sample.GetHistoSysList(), constraintPrefix, observables) ); } + sampleHistFuncs.front()->SetTitle( (nominal && strlen(nominal->GetTitle())>0) ? nominal->GetTitle() : sample.GetName().c_str() ); + //////////////////////////////////// // Add StatErrors to this Channel // //////////////////////////////////// @@ -989,7 +963,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Next, try to get the common ParamHistFunc (it may have been // created by another sample in this channel) // or create it if it doesn't yet exist: - ParamHistFunc* paramHist = dynamic_cast( proto->function(statFuncName.c_str()) ); + RooAbsReal* paramHist = dynamic_cast( proto.function(statFuncName) ); if( paramHist == nullptr ) { // Get a RooArgSet of the observables: @@ -997,25 +971,23 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo RooArgList theObservables; std::vector::iterator itr = fObsNameVec.begin(); for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) { - theObservables.add( *proto->var(*itr) ); + theObservables.add( *proto.var(*itr) ); } // Create the list of terms to // control the bin heights: std::string ParamSetPrefix = "gamma_stat_" + channel_name; - double gammaMin = 0.0; - double gammaMax = 10.0; - RooArgList statFactorParams = ParamHistFunc::createParamSet(*proto, - ParamSetPrefix.c_str(), + RooArgList statFactorParams = ParamHistFunc::createParamSet(proto, + ParamSetPrefix, theObservables, - gammaMin, gammaMax); + defaultGammaMin, defaultStatErrorGammaMax); ParamHistFunc statUncertFunc(statFuncName.c_str(), statFuncName.c_str(), theObservables, statFactorParams ); - proto->import( statUncertFunc, RecycleConflictNodes() ); + proto.import( statUncertFunc, RooFit::RecycleConflictNodes() ); - paramHist = (ParamHistFunc*) proto->function( statFuncName.c_str() ); + paramHist = proto.function( statFuncName); } // apply stat function to sample @@ -1028,7 +1000,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Create a ShapeFactor for this channel // /////////////////////////////////////////// - if( sample.GetShapeFactorList().size() > 0 ) { + if( !sample.GetShapeFactorList().empty() ) { if( fObsNameVec.size() > 3 ) { cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions." @@ -1040,18 +1012,15 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo << " to be include a ShapeFactor." << std::endl; - for(unsigned int i=0; i < sample.GetShapeFactorList().size(); ++i) { - - ShapeFactor& shapeFactor = sample.GetShapeFactorList().at(i); + for(ShapeFactor& shapeFactor : sample.GetShapeFactorList()) { std::string funcName = channel_name + "_" + shapeFactor.GetName() + "_shapeFactor"; - ParamHistFunc* paramHist = (ParamHistFunc*) proto->function( funcName.c_str() ); + RooAbsArg *paramHist = proto.function(funcName); if( paramHist == nullptr ) { RooArgList theObservables; - std::vector::iterator itr = fObsNameVec.begin(); - for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) { - theObservables.add( *proto->var(*itr) ); + for(std::string const& varName : fObsNameVec) { + theObservables.add( *proto.var(varName) ); } // Create the Parameters @@ -1059,9 +1028,9 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // GHL: Again, we are putting hard ranges on the gamma's // We should change this to range from 0 to /inf - RooArgList shapeFactorParams = ParamHistFunc::createParamSet(*proto, - funcParams.c_str(), - theObservables, 0, 1000); + RooArgList shapeFactorParams = ParamHistFunc::createParamSet(proto, + funcParams, + theObservables, defaultGammaMin, defaultShapeFactorGammaMax); // Create the Function ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(), @@ -1084,8 +1053,8 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo shapeFactorFunc.setConstant(true); } - proto->import( shapeFactorFunc, RecycleConflictNodes() ); - paramHist = (ParamHistFunc*) proto->function( funcName.c_str() ); + proto.import( shapeFactorFunc, RooFit::RecycleConflictNodes() ); + paramHist = proto.function(funcName); } // End: Create ShapeFactor ParamHistFunc @@ -1105,12 +1074,12 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions." << std::endl; throw hf_exc(); - } else { + } // List of ShapeSys ParamHistFuncs std::vector ShapeSysNames; - for( unsigned int i = 0; i < sample.GetShapeSysList().size(); ++i) { + for(RooStats::HistFactory::ShapeSys& shapeSys : sample.GetShapeSysList()) { // Create the ParamHistFunc's // Create their constraint terms and add them @@ -1121,37 +1090,34 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Send the name of that product to the RooRealSumPdf - RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at(i); - cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " in channel: " << channel_name << " to include a ShapeSys." << std::endl; std::string funcName = channel_name + "_" + shapeSys.GetName() + "_ShapeSys"; ShapeSysNames.push_back( funcName ); - ParamHistFunc* paramHist = (ParamHistFunc*) proto->function( funcName.c_str() ); + auto paramHist = static_cast(proto.function(funcName)); if( paramHist == nullptr ) { //std::string funcParams = "gamma_" + it->shapeFactorName; //paramHist = CreateParamHistFunc( proto, fObsNameVec, funcParams, funcName ); RooArgList theObservables; - std::vector::iterator itr = fObsNameVec.begin(); - for(; itr!=fObsNameVec.end(); ++itr ) { - theObservables.add( *proto->var(*itr) ); + for(std::string const& varName : fObsNameVec) { + theObservables.add( *proto.var(varName) ); } // Create the Parameters std::string funcParams = "gamma_" + shapeSys.GetName(); - RooArgList shapeFactorParams = ParamHistFunc::createParamSet(*proto, - funcParams.c_str(), - theObservables, 0, 10); + RooArgList shapeFactorParams = ParamHistFunc::createParamSet(proto, + funcParams, + theObservables, defaultGammaMin, defaultShapeSysGammaMax); // Create the Function ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(), theObservables, shapeFactorParams ); - proto->import( shapeFactorFunc, RecycleConflictNodes() ); - paramHist = (ParamHistFunc*) proto->function( funcName.c_str() ); + proto.import( shapeFactorFunc, RooFit::RecycleConflictNodes() ); + paramHist = static_cast(proto.function(funcName)); } // End: Create ShapeFactor ParamHistFunc @@ -1171,40 +1137,41 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo systype = Constraint::Poisson; } - double minShapeUncertainty = 0.0; - RooArgList shapeConstraints = createStatConstraintTerms(proto, constraintTermNames, - *paramHist, shapeErrorHist, - systype, - minShapeUncertainty); + auto shapeConstraintsInfo = createGammaConstraints( + paramHist->paramList(), histToVector(*shapeErrorHist), + minShapeUncertainty, + systype); + for (auto const& term : shapeConstraintsInfo.constraints) { + proto.import(*term, RooFit::RecycleConflictNodes()); + constraintTermNames.emplace_back(term->GetName()); + } + // Add the "observed" value to the list of global observables: + RooArgSet *globalSet = const_cast(proto.set("globalObservables")); + for (RooAbsArg * glob : shapeConstraintsInfo.globalObservables) { + globalSet->add(*proto.var(glob->GetName())); + } + } // End: Loop over ShapeSys vector in this EstimateSummary // Now that we have the list of ShapeSys ParamHistFunc names, // we create the total RooProduct - // we multiply the expected functio - + // we multiply the expected function - for( unsigned int i = 0; i < ShapeSysNames.size(); ++i ) { - auto func = proto->function(ShapeSysNames.at(i).c_str()); - assert(func); - sampleHistFuncs.push_back(func); + for(std::string const& name : ShapeSysNames) { + sampleHistFuncs.push_back(proto.function(name)); } - } // End: NumObsVar == 1 - } // End: !GetShapeSysList.empty() // GHL: This was pretty confusing before, // hopefully using the measurement directly // will improve it - auto lumi = proto->arg("Lumi"); + RooAbsArg *lumi = proto.arg("Lumi"); if( !sample.GetNormalizeByTheory() ) { if (!lumi) { - TString lumiParamString; - lumiParamString += measurement.GetLumi(); - lumiParamString.ReplaceAll(' ', TString()); - lumi = proto->factory(("Lumi[" + lumiParamString + "]").Data()); + lumi = proto.factory("Lumi[" + std::to_string(measurement.GetLumi()) + "]"); } else { static_cast(lumi)->setVal(measurement.GetLumi()); } @@ -1215,8 +1182,8 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Append the name of the "node" // that is to be summed with the // RooRealSumPdf - proto->import(*normFactors, RecycleConflictNodes()); - auto normFactorsInWS = dynamic_cast(proto->arg(normFactors->GetName())); + proto.import(*normFactors, RooFit::RecycleConflictNodes()); + auto normFactorsInWS = dynamic_cast(proto.arg(normFactors->GetName())); assert(normFactorsInWS); sampleScaleFactors.push_back(normFactorsInWS); @@ -1237,7 +1204,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // Using this TH1* of fractinal stat errors, // create a set of constraint terms: - ParamHistFunc* chanStatUncertFunc = (ParamHistFunc*) proto->function( statFuncName.c_str() ); + auto chanStatUncertFunc = static_cast(proto.function( statFuncName )); cxcoutI(HistFactory) << "About to create Constraint Terms from: " << chanStatUncertFunc->GetName() << " params: " << chanStatUncertFunc->paramList() @@ -1258,10 +1225,19 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } double statRelErrorThreshold = channel.GetStatErrorConfig().GetRelErrorThreshold(); - RooArgList statConstraints = createStatConstraintTerms(proto, constraintTermNames, - *chanStatUncertFunc, fracStatError.get(), - statConstraintType, - statRelErrorThreshold); + auto statConstraintsInfo = createGammaConstraints( + chanStatUncertFunc->paramList(), histToVector(*fracStatError), + statRelErrorThreshold, + statConstraintType); + for (auto const& term : statConstraintsInfo.constraints) { + proto.import(*term, RooFit::RecycleConflictNodes()); + constraintTermNames.emplace_back(term->GetName()); + } + // Add the "observed" value to the list of global observables: + RooArgSet *globalSet = const_cast(proto.set("globalObservables")); + for (RooAbsArg * glob : statConstraintsInfo.globalObservables) { + globalSet->add(*proto.var(glob->GetName())); + } } // END: Loop over stat Hist Pairs @@ -1275,71 +1251,54 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo ////////////////////////////////////// // fix specified parameters for(unsigned int i=0; ivar(systToFix.at(i)); - if(temp) { - // set the parameter constant - temp->setConstant(); - - // remove the corresponding auxiliary observable from the global observables - RooRealVar* auxMeas = nullptr; - if(systToFix.at(i)=="Lumi"){ - auxMeas = proto->var("nominalLumi"); - } else { - auxMeas = proto->var(std::string("nom_") + temp->GetName()); - } - - if(auxMeas){ - const_cast(proto->set("globalObservables"))->remove(*auxMeas); - } else{ - cxcoutE(HistFactory) << "could not corresponding auxiliary measurement " - << TString::Format("nom_%s",temp->GetName()) << endl; - } - } else { + RooRealVar* temp = proto.var(systToFix.at(i)); + if(!temp) { cxcoutE(HistFactory) << "could not find variable " << systToFix.at(i) << " could not set it to constant" << endl; } + // set the parameter constant + temp->setConstant(); } ////////////////////////////////////// // final proto model for(unsigned int i=0; iarg(constraintTermNames[i].c_str())); + RooAbsArg* proto_arg = proto.arg(constraintTermNames[i]); if( proto_arg==nullptr ) { cxcoutF(HistFactory) << "Error: Cannot find arg set: " << constraintTermNames.at(i) - << " in workspace: " << proto->GetName() << std::endl; + << " in workspace: " << proto.GetName() << std::endl; throw hf_exc(); } constraintTerms.add( *proto_arg ); - // constraintTerms.add(* proto_arg(proto->arg(constraintTermNames[i].c_str())) ); + // constraintTerms.add(* proto_arg(proto.arg(constraintTermNames[i].c_str())) ); } for(unsigned int i=0; iarg(likelihoodTermNames[i].c_str())); + RooAbsArg* proto_arg = (proto.arg(likelihoodTermNames[i])); if( proto_arg==nullptr ) { cxcoutF(HistFactory) << "Error: Cannot find arg set: " << likelihoodTermNames.at(i) - << " in workspace: " << proto->GetName() << std::endl; + << " in workspace: " << proto.GetName() << std::endl; throw hf_exc(); } likelihoodTerms.add( *proto_arg ); } - proto->defineSet("constraintTerms",constraintTerms); - proto->defineSet("likelihoodTerms",likelihoodTerms); + proto.defineSet("constraintTerms",constraintTerms); + proto.defineSet("likelihoodTerms",likelihoodTerms); // list of observables RooArgList observables; std::string observablesStr; - std::vector::iterator itr = fObsNameVec.begin(); - for(; itr!=fObsNameVec.end(); ++itr ) { - observables.add( *proto->var(*itr) ); + for(std::string const& name : fObsNameVec) { + observables.add( *proto.var(name) ); if (!observablesStr.empty()) { observablesStr += ","; } - observablesStr += *itr; + observablesStr += name; } - // We create two sets, one for backwards compatability + // We create two sets, one for backwards compatibility // The other to make a consistent naming convention // between individual channels and the combined workspace - proto->defineSet("observables", TString::Format("%s",observablesStr.c_str())); - proto->defineSet("observablesSet", TString::Format("%s",observablesStr.c_str())); + proto.defineSet("observables", observablesStr.c_str()); + proto.defineSet("observablesSet", observablesStr.c_str()); // Create the ParamHistFunc // after observables have been made @@ -1349,26 +1308,26 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo auto model = make_unique( ("model_"+channel_name).c_str(), // MB : have changed this into conditional pdf. Much faster for toys! - "product of Poissons accross bins for a single channel", - constraintTerms, Conditional(likelihoodTerms,observables)); - proto->import(*model,RecycleConflictNodes()); + "product of Poissons across bins for a single channel", + constraintTerms, RooFit::Conditional(likelihoodTerms,observables)); + // can give channel a title by setting title of corresponding data histogram + if (channel.GetData().GetHisto() && strlen(channel.GetData().GetHisto()->GetTitle())>0) { + model->SetTitle(channel.GetData().GetHisto()->GetTitle()); + } + proto.import(*model,RooFit::RecycleConflictNodes()); proto_config->SetPdf(*model); proto_config->SetObservables(observables); - proto_config->SetGlobalObservables(*proto->set("globalObservables")); - // proto->writeToFile(("results/model_"+channel+".root").c_str()); + proto_config->SetGlobalObservables(*proto.set("globalObservables")); + // proto.writeToFile(("results/model_"+channel+".root").c_str()); // fill out nuisance parameters in model config - // proto_config->GuessObsAndNuisance(*proto->data("asimovData")); - proto->import(*proto_config,proto_config->GetName()); - proto->importClassCode(); + // proto_config->GuessObsAndNuisance(*proto.data("asimovData")); + proto.import(*proto_config,proto_config->GetName()); + proto.importClassCode(); /////////////////////////// // make data sets // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels - const char* weightName="weightVar"; - proto->factory(TString::Format("%s[0,-1e10,1e10]",weightName)); - proto->defineSet("obsAndWeight",TString::Format("%s,%s",weightName,observablesStr.c_str())); - // New Asimov Generation: Use the code in the Asymptotic calculator // Need to get the ModelConfig... int asymcalcPrintLevel = 0; @@ -1376,15 +1335,15 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo if (RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::DEBUG)) asymcalcPrintLevel = 2; AsymptoticCalculator::SetPrintLevel(asymcalcPrintLevel); unique_ptr asimov_dataset(AsymptoticCalculator::GenerateAsimovData(*model, observables)); - proto->import(dynamic_cast(*asimov_dataset), Rename("asimovData")); + proto.import(*asimov_dataset, RooFit::Rename("asimovData")); // GHL: Determine to use data if the hist isn't 'nullptr' if(TH1 const* mnominal = channel.GetData().GetHisto()) { // This works and is natural, but the memory size of the simultaneous // dataset grows exponentially with channels. - RooDataSet dataset{"obsData","",*proto->set("obsAndWeight"),weightName}; - ConfigureHistFactoryDataset( dataset, *mnominal, *proto, fObsNameVec ); - proto->import(dataset); + RooDataSet dataset{"obsData","",*proto.set("observables"), RooFit::WeightVar("weightVar")}; + ConfigureHistFactoryDataset( dataset, *mnominal, proto, fObsNameVec ); + proto.import(dataset); } // End: Has non-null 'data' entry @@ -1404,16 +1363,17 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels - RooDataSet dataset{dataName.c_str(), "", *proto->set("obsAndWeight"), weightName}; - ConfigureHistFactoryDataset( dataset, *mnominal, *proto, fObsNameVec ); - proto->import(dataset); + RooDataSet dataset{dataName, "", *proto.set("observables"), RooFit::WeightVar("weightVar")}; + ConfigureHistFactoryDataset( dataset, *mnominal, proto, fObsNameVec ); + proto.import(dataset); } - if (RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::INFO)) - proto->Print(); + if (RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::INFO)) { + proto.Print(); + } - return proto; + return protoOwner; } @@ -1442,7 +1402,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo if(obsNameVec.size()==1) { double fval = mnominal.GetBinContent(i); - obsDataUnbinned.add( *proto.set("obsAndWeight"), fval ); + obsDataUnbinned.add( *proto.set("observables"), fval ); } else { // 2 or more dimensions for(int j=1; j<=ay->GetNbins(); ++j) { @@ -1451,14 +1411,14 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo if(obsNameVec.size()==2) { double fval = mnominal.GetBinContent(i,j); - obsDataUnbinned.add( *proto.set("obsAndWeight"), fval ); + obsDataUnbinned.add( *proto.set("observables"), fval ); } else { // 3 dimensions for(int k=1; k<=az->GetNbins(); ++k) { double zval = az->GetBinCenter(k); proto.var( obsNameVec[2] )->setVal( zval ); double fval = mnominal.GetBinContent(i,j,k); - obsDataUnbinned.add( *proto.set("obsAndWeight"), fval ); + obsDataUnbinned.add( *proto.set("observables"), fval ); } } } @@ -1468,35 +1428,25 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo void HistoToWorkspaceFactoryFast::GuessObsNameVec(const TH1* hist) { - fObsNameVec.clear(); - - // determine histogram dimensionality - unsigned int histndim(1); - std::string classname = hist->ClassName(); - if (classname.find("TH1")==0) { histndim=1; } - else if (classname.find("TH2")==0) { histndim=2; } - else if (classname.find("TH3")==0) { histndim=3; } - - for ( unsigned int idx=0; idx{"x", "y", "z"}; + fObsNameVec.resize(hist->GetDimension()); } - RooWorkspace* HistoToWorkspaceFactoryFast::MakeCombinedModel(vector ch_names, vector>& chs) + RooFit::OwningPtr + HistoToWorkspaceFactoryFast::MakeCombinedModel(std::vector ch_names, + std::vector> &chs) { RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::INFO, 0, RooFit::ObjectHandling, false); // check first the inputs (see JIRA-6890) if (ch_names.empty() || chs.empty() ) { Error("MakeCombinedModel","Input vectors are empty - return a nullptr"); - return 0; + return nullptr; } if (chs.size() < ch_names.size() ) { Error("MakeCombinedModel","Input vector of workspace has an invalid size - return a nullptr"); - return 0; + return nullptr; } // @@ -1508,8 +1458,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo RooArgList obsList; for(unsigned int i = 0; i< ch_names.size(); ++i){ - ModelConfig * config = (ModelConfig *) chs[i]->obj("ModelConfig"); - obsList.add(*config->GetObservables()); + obsList.add(*static_cast(chs[i]->obj("ModelConfig"))->GetObservables()); } cxcoutI(HistFactory) <<"full list of observables:\n" << obsList << std::endl; @@ -1543,15 +1492,14 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo cxcoutP(HistFactory) << "\n-----------------------------------------\n" << "\tEntering combination" << "\n-----------------------------------------\n" << endl; - RooWorkspace* combined = new RooWorkspace("combined"); - // RooWorkspace* combined = chs[0]; + auto combined = std::make_unique("combined"); RooCategory* channelCat = dynamic_cast( combined->factory(channelString.str()) ); if (!channelCat) throw std::runtime_error("Unable to construct a category from string " + channelString.str()); auto simPdf= std::make_unique("simPdf","",pdfMap, *channelCat); - auto combined_config = std::make_unique("ModelConfig", combined); + auto combined_config = std::make_unique("ModelConfig", combined.get()); combined_config->SetWorkspace(*combined); // combined_config->SetNuisanceParameters(*constrainedParams); @@ -1559,8 +1507,6 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo combined->defineSet("globalObservables",globalObs); combined_config->SetGlobalObservables(*combined->set("globalObservables")); - combined->factory("weightVar[0,-1e10,1e10]"); - obsList.add(*combined->var("weightVar")); combined->defineSet("observables",{obsList, *channelCat}, /*importMissing=*/true); combined_config->SetObservables(*combined->set("observables")); @@ -1569,9 +1515,17 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo for(RooAbsData * data : chs[0]->allData()) { // We are excluding the Asimov data, because it needs to be regenerated // later after the parameter values are set. - if(std::string("asimovData") != data->GetName()) { - MergeDataSets(combined, chs, ch_names, data->GetName(), obsList, channelCat); + if(std::string("asimovData") == data->GetName()) { + continue; + } + // Loop through channels, get their individual datasets, + // and add them to the combined dataset + std::map dataMap; + for(unsigned int i = 0; i < ch_names.size(); ++i){ + dataMap[ch_names[i]] = chs[i]->data(data->GetName()); } + combined->import(RooDataSet{data->GetName(), "", obsList, RooFit::Index(*channelCat), + RooFit::WeightVar("weightVar"), RooFit::Import(dataMap)}); } @@ -1581,13 +1535,12 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo cxcoutP(HistFactory) << "\n-----------------------------------------\n" << "\tImporting combined model" << "\n-----------------------------------------\n" << endl; - combined->import(*simPdf,RecycleConflictNodes()); + combined->import(*simPdf,RooFit::RecycleConflictNodes()); - std::map< std::string, double>::iterator param_itr = fParamValues.begin(); - for( ; param_itr != fParamValues.end(); ++param_itr ){ + for(auto const& param_itr : fParamValues) { // make sure they are fixed - std::string paramName = param_itr->first; - double paramVal = param_itr->second; + std::string paramName = param_itr.first; + double paramVal = param_itr.second; if(RooRealVar* temp = combined->var( paramName )) { temp->setVal( paramVal ); @@ -1630,69 +1583,18 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // First Asimov // Create Asimov data for the combined dataset - std::unique_ptr asimov_combined{static_cast(AsymptoticCalculator::GenerateAsimovData( + std::unique_ptr asimov_combined{AsymptoticCalculator::GenerateAsimovData( *combined->pdf("simPdf"), - obsList))}; + obsList)}; if( asimov_combined ) { - combined->import( *asimov_combined, Rename("asimovData")); + combined->import( *asimov_combined, RooFit::Rename("asimovData")); } else { std::cout << "Error: Failed to create combined asimov dataset" << std::endl; throw hf_exc(); } - return combined; - } - - - RooDataSet* HistoToWorkspaceFactoryFast::MergeDataSets(RooWorkspace* combined, - std::vector>& wspace_vec, - std::vector const& channel_names, - std::string const& dataSetName, - RooArgList const& obsList, - RooCategory* channelCat) { - - // Create the total dataset - std::unique_ptr simData; - - // Loop through channels, get their individual datasets, - // and add them to the combined dataset - for(unsigned int i = 0; i< channel_names.size(); ++i){ - - // Grab the dataset for the existing channel - cxcoutPHF << "Merging data for channel " << channel_names[i].c_str() << std::endl; - RooDataSet* obsDataInChannel = (RooDataSet*) wspace_vec[i]->data(dataSetName.c_str()); - if( !obsDataInChannel ) { - std::cout << "Error: Can't find DataSet: " << dataSetName - << " in channel: " << channel_names.at(i) - << std::endl; - throw hf_exc(); - } - - // Create the new Dataset - auto tempData = std::make_unique(channel_names[i].c_str(),"", - obsList, Index(*channelCat), - WeightVar("weightVar"), - Import(channel_names[i].c_str(),*obsDataInChannel)); - if(simData) { - simData->append(*tempData); - } - else { - simData = std::move(tempData); - } - } // End Loop Over Channels - - // Check that we successfully created the dataset - // and import it into the workspace - if(simData) { - combined->import(*simData, Rename(dataSetName.c_str())); - return static_cast(combined->data(dataSetName)); - } - else { - std::cout << "Error: Unable to merge observable datasets" << std::endl; - throw hf_exc(); - return nullptr; - } + return RooFit::Detail::owningPtr(std::move(combined)); } @@ -1702,14 +1604,14 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo // a TH1 representing the binwise // errors (taken from the nominal TH1) - TH1* ErrorHist = (TH1*) Nominal->Clone( Name.c_str() ); + auto ErrorHist = static_cast(Nominal->Clone( Name.c_str() )); ErrorHist->Reset(); - Int_t numBins = Nominal->GetNbinsX()*Nominal->GetNbinsY()*Nominal->GetNbinsZ(); - Int_t binNumber = 0; + int numBins = Nominal->GetNbinsX()*Nominal->GetNbinsY()*Nominal->GetNbinsZ(); + int binNumber = 0; // Loop over bins - for( Int_t i_bin = 0; i_bin < numBins; ++i_bin) { + for( int i_bin = 0; i_bin < numBins; ++i_bin) { binNumber++; // Ignore underflow / overflow @@ -1767,7 +1669,7 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } const TH1* HistTemplate = HistVec.at(0).first; - Int_t numBins = HistTemplate->GetNbinsX()*HistTemplate->GetNbinsY()*HistTemplate->GetNbinsZ(); + int numBins = HistTemplate->GetNbinsX()*HistTemplate->GetNbinsY()*HistTemplate->GetNbinsZ(); // Check that all histograms // have the same bins @@ -1789,10 +1691,10 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo std::vector TotalBinContent( numBins, 0.0); std::vector HistErrorsSqr( numBins, 0.0); - Int_t binNumber = 0; + int binNumber = 0; // Loop over bins - for( Int_t i_bins = 0; i_bins < numBins; ++i_bins) { + for( int i_bins = 0; i_bins < numBins; ++i_bins) { binNumber++; while( HistTemplate->IsBinUnderflow(binNumber) || HistTemplate->IsBinOverflow(binNumber) ){ @@ -1804,18 +1706,10 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo const TH1* nominal = HistVec.at(i_hist).first; const TH1* error = HistVec.at(i_hist).second.get(); - //Int_t binNumber = i_bins + 1; + //int binNumber = i_bins + 1; double histValue = nominal->GetBinContent( binNumber ); double histError = error->GetBinContent( binNumber ); - /* - std::cout << " Getting Bin content for Stat Uncertainty" - << " Nom name: " << nominal->GetName() - << " Err name: " << error->GetName() - << " HistNumber: " << i_hist << " bin: " << binNumber - << " Value: " << histValue << " Error: " << histError - << std::endl; - */ if( histError != histError ) { cxcoutE(HistFactory) << "In histogram " << error->GetName() @@ -1837,9 +1731,9 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo ErrorHist->Reset(); // Fill the output histogram - for( Int_t i = 0; i < numBins; ++i) { + for( int i = 0; i < numBins; ++i) { - // Int_t binNumber = i + 1; + // int binNumber = i + 1; binNumber++; while( ErrorHist->IsBinUnderflow(binNumber) || ErrorHist->IsBinOverflow(binNumber) ){ binNumber++; @@ -1888,172 +1782,6 @@ RooArgList HistoToWorkspaceFactoryFast::createObservables(const TH1 *hist, RooWo } - - RooArgList HistoToWorkspaceFactoryFast:: - createStatConstraintTerms( RooWorkspace* proto, vector& constraintTermNames, - ParamHistFunc& paramHist, const TH1* uncertHist, - Constraint::Type type, double minSigma ) { - - - // Take a RooArgList of RooAbsReal's and - // create N constraint terms (one for - // each gamma) whose relative uncertainty - // is the value of the ith RooAbsReal - // - // The integer "type" controls the type - // of constraint term: - // - // type == 0 : NONE - // type == 1 : Gaussian - // type == 2 : Poisson - // type == 3 : LogNormal - - RooArgList ConstraintTerms; - - RooArgList paramSet = paramHist.paramList(); - - // Must get the full size of the TH1 - // (No direct method to do this...) - Int_t numBins = uncertHist->GetNbinsX()*uncertHist->GetNbinsY()*uncertHist->GetNbinsZ(); - Int_t numParams = paramSet.getSize(); - // Int_t numBins = uncertHist->GetNbinsX()*uncertHist->GetNbinsY()*uncertHist->GetNbinsZ(); - - // Check that there are N elements - // in the RooArgList - if( numBins != numParams ) { - std::cout << "Error: In createStatConstraintTerms, encountered bad number of bins" << std::endl; - std::cout << "Given histogram with " << numBins << " bins," - << " but require exactly " << numParams << std::endl; - throw hf_exc(); - } - - Int_t TH1BinNumber = 0; - for( Int_t i = 0; i < paramSet.getSize(); ++i) { - - TH1BinNumber++; - - while( uncertHist->IsBinUnderflow(TH1BinNumber) || uncertHist->IsBinOverflow(TH1BinNumber) ){ - TH1BinNumber++; - } - - RooRealVar& gamma = (RooRealVar&) (paramSet[i]); - - cxcoutI(HistFactory) << "Creating constraint for: " << gamma.GetName() - << ". Type of constraint: " << type << std::endl; - - // Get the sigma from the hist - // (the relative uncertainty) - const double sigmaRel = uncertHist->GetBinContent(TH1BinNumber); - - // If the sigma is <= 0, - // do cont create the term - if( sigmaRel <= 0 ){ - cxcoutI(HistFactory) << "Not creating constraint term for " - << gamma.GetName() - << " because sigma = " << sigmaRel - << " (sigma<=0)" - << " (TH1 bin number = " << TH1BinNumber << ")" - << std::endl; - gamma.setConstant(true); - continue; - } - - // set reasonable ranges for gamma parameters - gamma.setMax( 1 + 5*sigmaRel ); - gamma.setMin( 0. ); - - // Make Constraint Term - std::string constrName = string(gamma.GetName()) + "_constraint"; - std::string nomName = string("nom_") + gamma.GetName(); - std::string sigmaName = string(gamma.GetName()) + "_sigma"; - std::string poisMeanName = string(gamma.GetName()) + "_poisMean"; - - if( type == Constraint::Gaussian ) { - - // Type 1 : RooGaussian - - // Make sigma - - RooConstVar constrSigma( sigmaName.c_str(), sigmaName.c_str(), sigmaRel ); - - // Make "observed" value - RooRealVar constrNom(nomName.c_str(), nomName.c_str(), 1.0,0,10); - constrNom.setConstant( true ); - - // Make the constraint: - RooGaussian gauss( constrName.c_str(), constrName.c_str(), - constrNom, gamma, constrSigma ); - - proto->import( gauss, RecycleConflictNodes() ); - - // Give reasonable starting point for pre-fit errors by setting it to the absolute sigma - // Mostly useful for pre-fit plotting. - gamma.setError(sigmaRel); - } else if( type == Constraint::Poisson ) { - - double tau = 1/sigmaRel/sigmaRel; // this is correct Poisson equivalent to a Gaussian with mean 1 and stdev sigma - - // Make nominal "observed" value - RooRealVar constrNom(nomName.c_str(), nomName.c_str(), tau); - constrNom.setMin(0); - constrNom.setConstant( true ); - - // Make the scaling term - std::string scalingName = string(gamma.GetName()) + "_tau"; - RooConstVar poissonScaling( scalingName.c_str(), scalingName.c_str(), tau); - - // Make mean for scaled Poisson - RooProduct constrMean( poisMeanName.c_str(), poisMeanName.c_str(), RooArgSet(gamma, poissonScaling) ); - //proto->import( constrSigma, RecycleConflictNodes() ); - //proto->import( constrSigma ); - - // Type 2 : RooPoisson - RooPoisson pois(constrName.c_str(), constrName.c_str(), constrNom, constrMean); - pois.setNoRounding(true); - proto->import( pois, RecycleConflictNodes() ); - - if (std::string(gamma.GetName()).find("gamma_stat") != std::string::npos) { - // Give reasonable starting point for pre-fit errors. - // Mostly useful for pre-fit plotting. - gamma.setError(sigmaRel); - } - - } else { - - std::cout << "Error: Did not recognize Stat Error constraint term type: " - << type << " for : " << paramHist.GetName() << std::endl; - throw hf_exc(); - } - - // If the sigma value is less - // than a supplied threshold, - // set the variable to constant - if( sigmaRel < minSigma ) { - cxcoutW(HistFactory) << "Warning: Bin " << i << " = " << sigmaRel - << " and is < " << minSigma - << ". Setting: " << gamma.GetName() << " to constant" - << std::endl; - gamma.setConstant(true); - } - - constraintTermNames.push_back( constrName ); - ConstraintTerms.add( *proto->pdf(constrName) ); - - // Add the "observed" value to the - // list of global observables: - RooArgSet* globalSet = const_cast(proto->set("globalObservables")); - - RooRealVar* nomVarInWorkspace = proto->var(nomName); - if( ! globalSet->contains(*nomVarInWorkspace) ) { - globalSet->add( *nomVarInWorkspace ); - } - - } // end loop over parameters - - return ConstraintTerms; - -} - } // namespace RooStats } // namespace HistFactory diff --git a/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx b/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx index 513e9144accdb..311ec51ef15fe 100644 --- a/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx +++ b/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx @@ -10,24 +10,8 @@ #include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h" -// from std -#include -#include -#include -#include -#include - -// from root -#include "TFile.h" -#include "TH1F.h" -#include "TCanvas.h" -#include "TStyle.h" -#include "TLine.h" -#include "TSystem.h" - - // from roofit -#include "RooStats/ModelConfig.h" +#include "RooFit/ModelConfig.h" // from this package #include "RooStats/HistFactory/Measurement.h" @@ -35,11 +19,18 @@ #include "HFMsgService.h" -using namespace RooFit; -//using namespace RooStats; -//using namespace HistFactory; +#include +#include +#include +#include +#include +#include -//using namespace std; +#include +#include +#include +#include +#include /** ******************************************************************************************** @@ -93,18 +84,16 @@ using namespace RooFit;
    */ -RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::HistFactory::Measurement& measurement, HistoToWorkspaceFactoryFast::Configuration const& cfg) +RooFit::OwningPtr +RooStats::HistFactory::MakeModelAndMeasurementFast(RooStats::HistFactory::Measurement &measurement, + HistoToWorkspaceFactoryFast::Configuration const &cfg) { - // This will be returned - RooWorkspace* ws = nullptr; std::unique_ptr outFile; - FILE* tableFile=nullptr; + std::ofstream tableFile; auto& msgSvc = RooMsgService::instance(); msgSvc.getStream(1).removeTopic(RooFit::ObjectHandling); - try { - cxcoutIHF << "Making Model and Measurements (Fast) for measurement: " << measurement.GetName() << std::endl; double lumiError = measurement.GetLumi()*measurement.GetLumiRelErr(); @@ -132,11 +121,11 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist // to get the directory name. // We do by finding last occurrence of "/" and using as directory name what is before // if we do not have a "/" in the prefix there is no output directory to be checked or created - size_t pos = prefix.rfind("/"); + size_t pos = prefix.rfind('/'); if (pos != std::string::npos) { std::string outputDir = prefix.substr(0,pos); cxcoutDHF << "Checking if output directory : " << outputDir << " - exists" << std::endl; - if (gSystem->OpenDirectory( outputDir.c_str() ) == 0 ) { + if (gSystem->OpenDirectory( outputDir.c_str() ) == nullptr ) { cxcoutDHF << "Output directory : " << outputDir << " - does not exist, try to create" << std::endl; int success = gSystem->MakeDirectory( outputDir.c_str() ); if( success != 0 ) { @@ -152,11 +141,8 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist cxcoutIHF << "Creating the output file: " << outputFileName << std::endl; outFile = std::make_unique(outputFileName.c_str(), "recreate"); - // Create the table file - // This holds the table of fitted values and errors - std::string tableFileName = measurement.GetOutputFilePrefix() + "_results.table"; - cxcoutIHF << "Creating the table file: " << tableFileName << std::endl; - tableFile = fopen( tableFileName.c_str(), "a"); + // Create the table file, which holds the table of fitted values and errors + tableFile.open(measurement.GetOutputFilePrefix() + "_results.table", std::ios::out | std::ios::app); cxcoutIHF << "Creating the HistoToWorkspaceFactoryFast factory" << std::endl; HistoToWorkspaceFactoryFast factory{measurement, cfg}; @@ -167,7 +153,7 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist factory.SetFunctionsToPreprocess( measurement.GetPreprocessFunctions() ); // for results tables - fprintf(tableFile, " %s &", rowTitle.c_str() ); + tableFile << " " << rowTitle << " &"; // First: Loop to make the individual channels for( unsigned int chanItr = 0; chanItr < measurement.GetChannels().size(); ++chanItr ) { @@ -183,28 +169,26 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist std::string ch_name = channel.GetName(); cxcoutPHF << "Starting to process channel: " << ch_name << std::endl; channel_names.push_back(ch_name); - RooWorkspace* ws_single = factory.MakeSingleChannelModel( measurement, channel ); - channel_workspaces.emplace_back(ws_single); - - // Make the output - std::string ChannelFileName = measurement.GetOutputFilePrefix() + "_" - + ch_name + "_" + rowTitle + "_model.root"; - ws_single->writeToFile( ChannelFileName.c_str() ); - - // Now, write the measurement to the file - // Make a new measurement for only this channel - RooStats::HistFactory::Measurement meas_chan( measurement ); - meas_chan.GetChannels().clear(); - meas_chan.GetChannels().push_back( channel ); - cxcoutIHF << "Opening File to hold channel: " << ChannelFileName << std::endl; + std::unique_ptr ws_single{factory.MakeSingleChannelModel( measurement, channel )}; + { - std::unique_ptr chanFile{TFile::Open( ChannelFileName.c_str(), "UPDATE" )}; + // Make the output + std::string ChannelFileName = measurement.GetOutputFilePrefix() + "_" + + ch_name + "_" + rowTitle + "_model.root"; + cxcoutIHF << "Opening File to hold channel: " << ChannelFileName << std::endl; + std::unique_ptr chanFile{TFile::Open( ChannelFileName.c_str(), "RECREATE" )}; + chanFile->WriteTObject(ws_single.get()); + // Now, write the measurement to the file + // Make a new measurement for only this channel + RooStats::HistFactory::Measurement meas_chan( measurement ); + meas_chan.GetChannels().clear(); + meas_chan.GetChannels().push_back( channel ); cxcoutIHF << "About to write channel measurement to file" << std::endl; meas_chan.writeToFile( chanFile.get() ); cxcoutPHF << "Successfully wrote channel to file" << std::endl; } - // Get the Paramater of Interest as a RooRealVar + // Get the Parameter of Interest as a RooRealVar RooRealVar* poi = dynamic_cast( ws_single->var(measurement.GetPOI())); // do fit unless exportOnly requested @@ -214,16 +198,18 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist << ", no parameter of interest" << std::endl; } else { if(ws_single->data("obsData")) { - FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), ws_single, - ch_name, "obsData", outFile.get(), tableFile); + FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), *ws_single, + ch_name, "obsData", *outFile, tableFile); } else { - FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), ws_single, - ch_name, "asimovData", outFile.get(), tableFile); + FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), *ws_single, + ch_name, "asimovData", *outFile, tableFile); } } } - fprintf(tableFile, " & " ); + tableFile << " & "; + + channel_workspaces.emplace_back(std::move(ws_single)); } // End loop over channels /*** @@ -233,25 +219,25 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist ***/ // Use HistFactory to combine the individual channel workspaces - ws = factory.MakeCombinedModel(channel_names, channel_workspaces); + std::unique_ptr ws{factory.MakeCombinedModel(channel_names, channel_workspaces)}; // Configure that workspace - HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "simPdf", ws, measurement ); + HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement("simPdf", ws.get(), measurement); // Get the Parameter of interest as a RooRealVar RooRealVar* poi = dynamic_cast( ws->var(measurement.GetPOI())); - std::string CombinedFileName = measurement.GetOutputFilePrefix() + "_combined_" - + rowTitle + "_model.root"; - cxcoutPHF << "Writing combined workspace to file: " << CombinedFileName << std::endl; - ws->writeToFile( CombinedFileName.c_str() ); - cxcoutPHF << "Writing combined measurement to file: " << CombinedFileName << std::endl; { - std::unique_ptr combFile{TFile::Open( CombinedFileName.c_str(), "UPDATE" )}; + std::string CombinedFileName = measurement.GetOutputFilePrefix() + "_combined_" + + rowTitle + "_model.root"; + cxcoutPHF << "Writing combined workspace to file: " << CombinedFileName << std::endl; + std::unique_ptr combFile{TFile::Open( CombinedFileName.c_str(), "RECREATE" )}; if( combFile == nullptr ) { cxcoutEHF << "Error: Failed to open file " << CombinedFileName << std::endl; throw hf_exc(); } + combFile->WriteTObject(ws.get()); + cxcoutPHF << "Writing combined measurement to file: " << CombinedFileName << std::endl; measurement.writeToFile( combFile.get() ); } @@ -263,63 +249,39 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist } else { if(ws->data("obsData")){ - FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), ws,"combined", - "obsData", outFile.get(), tableFile); + FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), *ws,"combined", + "obsData", *outFile, tableFile); } else { - FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), ws,"combined", - "asimovData", outFile.get(), tableFile); + FitModelAndPlot(measurement.GetName(), measurement.GetOutputFilePrefix(), *ws,"combined", + "asimovData", *outFile, tableFile); } } } - fprintf(tableFile, " \\\\ \n"); - - fclose( tableFile ); - - } - catch(...) { - if( tableFile ) fclose(tableFile); - throw; - } + tableFile << " \\\\ \n"; msgSvc.getStream(1).addTopic(RooFit::ObjectHandling); - return ws; - + return RooFit::Detail::owningPtr(std::move(ws)); } /////////////////////////////////////////////// -void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName, - const std::string& FileNamePrefix, - RooWorkspace * combined, std::string channel, - std::string data_name, - TFile* outFile, FILE* tableFile ) { - - if( outFile == nullptr ) { - cxcoutEHF << "Error: Output File in FitModelAndPlot is nullptr" << std::endl; - throw hf_exc(); - } - - if( tableFile == nullptr ) { - cxcoutEHF << "Error: tableFile in FitModelAndPlot is nullptr" << std::endl; - throw hf_exc(); - } - - if( combined == nullptr ) { - cxcoutEHF << "Error: Supplied workspace in FitModelAndPlot is nullptr" << std::endl; - throw hf_exc(); - } +void RooStats::HistFactory::FitModelAndPlot(const std::string &MeasurementName, const std::string &FileNamePrefix, + RooWorkspace &combined, std::string channel, std::string data_name, + TFile &outFile, std::ostream &tableStream) +{ + using namespace RooFit; - ModelConfig* combined_config = (ModelConfig *) combined->obj("ModelConfig"); + auto combined_config = static_cast(combined.obj("ModelConfig")); if(!combined_config){ cxcoutEHF << "Error: no ModelConfig found in Measurement: " << MeasurementName << std::endl; throw hf_exc(); } - RooAbsData* simData = combined->data(data_name.c_str()); + RooAbsData* simData = combined.data(data_name); if(!simData){ cxcoutEHF << "Error: Failed to get dataset: " << data_name << " in measurement: " << MeasurementName << std::endl; @@ -347,14 +309,15 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName, PoiPlusNuisance.add( *combined_config->GetNuisanceParameters() ); } PoiPlusNuisance.add( *combined_config->GetParametersOfInterest() ); - combined->saveSnapshot("InitialValues", PoiPlusNuisance); + combined.saveSnapshot("InitialValues", PoiPlusNuisance); /////////////////////////////////////// // Do the fit cxcoutPHF << "\n---------------" << "\nDoing "<< channel << " Fit" << "\n---------------\n\n" << std::endl; - model->fitTo(*simData, Minos(true), PrintLevel(RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::DEBUG) ? 1 : -1)); + const int printLevel = RooMsgService::instance().isActive(static_cast(nullptr), RooFit::HistFactory, RooFit::DEBUG) ? 1 : -1; + model->fitTo(*simData, Minos(true), PrintLevel(printLevel)); // If there are no parameters of interest, // we exit the function here @@ -376,18 +339,14 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName, RooRealVar* poi = static_cast(POIs->first()); // Print the MINOS errors to the TableFile - fprintf(tableFile, " %.4f / %.4f ", poi->getErrorLo(), poi->getErrorHi()); + const auto oldPrecision = tableStream.precision(); + tableStream.precision(4); + tableStream << " " << poi->getErrorLo() << " / " << poi->getErrorHi() << " "; + tableStream.precision(oldPrecision); // Make the Profile Likelihood Plot - RooAbsReal* nll = model->createNLL(*simData); - RooAbsReal* profile = nll->createProfile(*poi); - if( profile==nullptr ) { - cxcoutEHF << "Error: Failed to make ProfileLikelihood for: " << poi->GetName() - << " using model: " << model->GetName() - << " and data: " << simData->GetName() - << std::endl; - throw hf_exc(); - } + std::unique_ptr nll{model->createNLL(*simData)}; + std::unique_ptr profile{nll->createProfile(*poi)}; std::unique_ptr frame{poi->frame()}; @@ -410,7 +369,7 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName, // may make it more attractive) // Save to the output file - TDirectory* channel_dir = outFile->mkdir(channel.c_str()); + TDirectory* channel_dir = outFile.mkdir(channel.c_str()); if( channel_dir == nullptr ) { cxcoutEHF << "Error: Failed to make channel directory: " << channel << std::endl; throw hf_exc(); @@ -443,12 +402,14 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName, g.Write(); // Finally, restore the initial values - combined->loadSnapshot("InitialValues"); + combined.loadSnapshot("InitialValues"); } -void RooStats::HistFactory::FitModel(RooWorkspace * combined, std::string data_name ) { +void RooStats::HistFactory::FitModel(RooWorkspace * combined, std::string data_name ) +{ + using namespace RooFit; cxcoutIHF << "In Fit Model" << std::endl; ModelConfig * combined_config = (ModelConfig *) combined->obj("ModelConfig"); @@ -457,7 +418,7 @@ void RooStats::HistFactory::FitModel(RooWorkspace * combined, std::string data_n return; } - RooAbsData* simData = combined->data(data_name.c_str()); + RooAbsData* simData = combined->data(data_name); if(!simData){ cxcoutEHF << "no data " << data_name << " exiting" << std::endl; return; @@ -476,7 +437,9 @@ void RooStats::HistFactory::FitModel(RooWorkspace * combined, std::string data_n void RooStats::HistFactory::FormatFrameForLikelihood(RooPlot* frame, std::string /*XTitle*/, - std::string YTitle){ + std::string YTitle) +{ + using namespace RooFit; gStyle->SetCanvasBorderMode(0); gStyle->SetPadBorderMode(0); diff --git a/roofit/histfactory/src/Measurement.cxx b/roofit/histfactory/src/Measurement.cxx index 302cf58908cd7..0e216af146f76 100644 --- a/roofit/histfactory/src/Measurement.cxx +++ b/roofit/histfactory/src/Measurement.cxx @@ -287,7 +287,7 @@ void RooStats::HistFactory::Measurement::PrintXML( std::string directory, std::s cxcoutPHF << "Printing XML Files for measurement: " << GetName() << std::endl; std::string XMLName = std::string(GetName()) + ".xml"; - if( directory != "" ) XMLName = directory + "/" + XMLName; + if( !directory.empty() ) XMLName = directory + "/" + XMLName; ofstream xml( XMLName.c_str() ); @@ -370,7 +370,7 @@ void RooStats::HistFactory::Measurement::PrintXML( std::string directory, std::s xml << " " << std::endl; // Set the Constant Parameters - if(fConstantParams.size()) { + if(!fConstantParams.empty()) { xml << " "; for( unsigned int i = 0; i < fConstantParams.size(); ++i ) { if (i==0) xml << fConstantParams.at(i); @@ -443,7 +443,7 @@ void RooStats::HistFactory::Measurement::PrintXML( std::string directory, std::s void RooStats::HistFactory::Measurement::writeToFile( TFile* file ) { - // Create a tempory measurement + // Create a temporary measurement // (This is the one that is actually written) RooStats::HistFactory::Measurement outMeas( *this ); @@ -618,8 +618,8 @@ std::string RooStats::HistFactory::Measurement::GetDirPath( TDirectory* dir ) std::string path = dir->GetPath(); - if( path.find(":") != std::string::npos ) { - size_t index = path.find(":"); + if( path.find(':') != std::string::npos ) { + size_t index = path.find(':'); path.replace( 0, index+1, "" ); } diff --git a/roofit/histfactory/src/ParamHistFunc.cxx b/roofit/histfactory/src/ParamHistFunc.cxx index c137d0c9bd6fa..52bb6b601d06e 100644 --- a/roofit/histfactory/src/ParamHistFunc.cxx +++ b/roofit/histfactory/src/ParamHistFunc.cxx @@ -46,10 +46,10 @@ #include "RooRealVar.h" #include "RooArgList.h" #include "RooWorkspace.h" -#include "RunContext.h" #include "TH1.h" +#include #include #include #include @@ -478,10 +478,10 @@ RooArgList ParamHistFunc::createParamSet(const std::string& Prefix, Int_t numBin VarNameStream << Prefix << "_bin_" << i; std::string VarName = VarNameStream.str(); - RooRealVar* gamma = new RooRealVar( VarName.c_str(), VarName.c_str(), - gamma_nominal, gamma_min, gamma_max ); + auto gamma = std::make_unique(VarName.c_str(), VarName.c_str(), + gamma_nominal, gamma_min, gamma_max); gamma->setConstant( false ); - paramSet.add( *gamma ); + paramSet.addOwned(std::move(gamma)); } @@ -586,13 +586,27 @@ double ParamHistFunc::evaluate() const return getParameter().getVal(); } +void ParamHistFunc::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + auto const &n = _numBinsPerDim; + + // check if _numBins needs to be filled + if (n.x == 0) { + _numBinsPerDim = getNumBinsPerDim(_dataVars); + } + + std::string const &idx = _dataSet.calculateTreeIndexForCodeSquash(this, ctx, _dataVars, true); + std::string const ¶mNames = ctx.buildArg(_paramSet); + + ctx.addResult(this, paramNames + "[" + idx + "]"); +} //////////////////////////////////////////////////////////////////////////////// /// Find all bins corresponding to the values of the observables in `evalData`, and evaluate /// the associated parameters. /// \param[in,out] evalData Input/output data for evaluating the ParamHistFunc. /// \param[in] normSet Normalisation set passed on to objects that are serving values to us. -void ParamHistFunc::computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const { +void ParamHistFunc::computeBatch(double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const { auto const& n = _numBinsPerDim; // check if _numBins needs to be filled @@ -641,7 +655,7 @@ Int_t ParamHistFunc::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& anal // Check if this configuration was created before Int_t sterileIdx(-1) ; - CacheElem* cache = (CacheElem*) _normIntMgr.getObj(normSet,&analVars,&sterileIdx,(const char*)0) ; + CacheElem* cache = (CacheElem*) _normIntMgr.getObj(normSet,&analVars,&sterileIdx,(const char*)nullptr) ; if (cache) { return _normIntMgr.lastIndex()+1 ; } @@ -650,7 +664,7 @@ Int_t ParamHistFunc::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& anal cache = new CacheElem ; // Store cache element - Int_t code = _normIntMgr.setObj(normSet,&analVars,(RooAbsCacheElement*)cache,0) ; + Int_t code = _normIntMgr.setObj(normSet,&analVars,cache,nullptr) ; return code+1 ; @@ -673,7 +687,6 @@ double ParamHistFunc::analyticalIntegralWN(Int_t /*code*/, const RooArgSet* /*no for (unsigned int i=0; i < _paramSet.size(); ++i) { const auto& param = static_cast(_paramSet[i]); - assert(static_cast(i) == _dataSet.getIndex(param)); // We assume that each parameter i belongs to bin i // Get the gamma's value const double paramVal = param.getVal(); @@ -700,12 +713,12 @@ std::list* ParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, double RooAbsLValue* lvarg = &obs; // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; std::list* hint = new std::list ; - // Widen range slighty + // Widen range slightly xlo = xlo - 0.01*(xhi-xlo) ; xhi = xhi + 0.01*(xhi-xlo) ; @@ -735,7 +748,7 @@ std::list* ParamHistFunc::binBoundaries(RooAbsRealLValue& obs, double xl RooAbsLValue* lvarg = &obs; // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; std::list* hint = new std::list ; diff --git a/roofit/histfactory/src/PiecewiseInterpolation.cxx b/roofit/histfactory/src/PiecewiseInterpolation.cxx index 4514238f624f0..3c855351f89ac 100644 --- a/roofit/histfactory/src/PiecewiseInterpolation.cxx +++ b/roofit/histfactory/src/PiecewiseInterpolation.cxx @@ -20,6 +20,8 @@ #include "RooStats/HistFactory/PiecewiseInterpolation.h" +#include "RooFit/Detail/EvaluateFuncs.h" + #include "Riostream.h" #include "TBuffer.h" @@ -31,10 +33,9 @@ #include "RooMsgService.h" #include "RooNumIntConfig.h" #include "RooTrace.h" -#include "RunContext.h" #include -#include +#include #include using namespace std; @@ -42,6 +43,7 @@ using namespace std; ClassImp(PiecewiseInterpolation); ; +using RooFit::Detail::EvaluateFuncs::piecewiseInterpolation; //////////////////////////////////////////////////////////////////////////////// @@ -68,8 +70,11 @@ PiecewiseInterpolation::PiecewiseInterpolation() : _normIntMgr(this) PiecewiseInterpolation::PiecewiseInterpolation(const char* name, const char* title, const RooAbsReal& nominal, const RooArgList& lowSet, const RooArgList& highSet, - const RooArgList& paramSet, - bool takeOwnership) : + const RooArgList& paramSet +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES + , bool takeOwnership +#endif + ) : RooAbsReal(name, title), _normIntMgr(this), _nominal("!nominal","nominal value", this, (RooAbsReal&)nominal), @@ -92,9 +97,11 @@ PiecewiseInterpolation::PiecewiseInterpolation(const char* name, const char* tit RooErrorHandler::softAbort() ; } _lowSet.add(*comp) ; +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES if (takeOwnership) { - _ownedList.addOwned(*comp) ; + _ownedList.addOwned(std::unique_ptr{comp}); } +#endif } @@ -105,9 +112,11 @@ PiecewiseInterpolation::PiecewiseInterpolation(const char* name, const char* tit RooErrorHandler::softAbort() ; } _highSet.add(*comp) ; +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES if (takeOwnership) { - _ownedList.addOwned(*comp) ; + _ownedList.addOwned(std::unique_ptr{comp}); } +#endif } @@ -118,16 +127,18 @@ PiecewiseInterpolation::PiecewiseInterpolation(const char* name, const char* tit RooErrorHandler::softAbort() ; } _paramSet.add(*comp) ; +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES if (takeOwnership) { - _ownedList.addOwned(*comp) ; + _ownedList.addOwned(std::unique_ptr{comp}); } +#endif _interpCode.push_back(0); // default code: linear interpolation } // Choose special integrator by default specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator") ; - TRACE_CREATE + TRACE_CREATE; } @@ -146,7 +157,7 @@ PiecewiseInterpolation::PiecewiseInterpolation(const PiecewiseInterpolation& oth _interpCode(other._interpCode) { // Member _ownedList is intentionally not copy-constructed -- ownership is not transferred - TRACE_CREATE + TRACE_CREATE; } @@ -156,7 +167,7 @@ PiecewiseInterpolation::PiecewiseInterpolation(const PiecewiseInterpolation& oth PiecewiseInterpolation::~PiecewiseInterpolation() { - TRACE_DESTROY + TRACE_DESTROY; } @@ -177,121 +188,11 @@ double PiecewiseInterpolation::evaluate() const auto high = static_cast(_highSet.at(i)); Int_t icode = _interpCode[i] ; - switch(icode) { - case 0: { - // piece-wise linear - if(param->getVal()>0) - sum += param->getVal()*(high->getVal() - nominal ); - else - sum += param->getVal()*(nominal - low->getVal()); - break ; - } - case 1: { - // pice-wise log - if(param->getVal()>=0) - sum *= pow(high->getVal()/nominal, +param->getVal()); - else - sum *= pow(low->getVal()/nominal, -param->getVal()); - break ; - } - case 2: { - // parabolic with linear - double a = 0.5*(high->getVal()+low->getVal())-nominal; - double b = 0.5*(high->getVal()-low->getVal()); - double c = 0; - if(param->getVal()>1 ){ - sum += (2*a+b)*(param->getVal()-1)+high->getVal()-nominal; - } else if(param->getVal()<-1 ) { - sum += -1*(2*a-b)*(param->getVal()+1)+low->getVal()-nominal; - } else { - sum += a*pow(param->getVal(),2) + b*param->getVal()+c; - } - break ; - } - case 3: { - //parabolic version of log-normal - double a = 0.5*(high->getVal()+low->getVal())-nominal; - double b = 0.5*(high->getVal()-low->getVal()); - double c = 0; - if(param->getVal()>1 ){ - sum += (2*a+b)*(param->getVal()-1)+high->getVal()-nominal; - } else if(param->getVal()<-1 ) { - sum += -1*(2*a-b)*(param->getVal()+1)+low->getVal()-nominal; - } else { - sum += a*pow(param->getVal(),2) + b*param->getVal()+c; - } - break ; - } - case 4: { - - // WVE **************************************************************** - // WVE *** THIS CODE IS CRITICAL TO HISTFACTORY FIT CPU PERFORMANCE *** - // WVE *** Do not modify unless you know what you are doing... *** - // WVE **************************************************************** - - double x = param->getVal(); - if (x>1) { - sum += x*(high->getVal() - nominal ); - } else if (x<-1) { - sum += x*(nominal - low->getVal()); - } else { - double eps_plus = high->getVal() - nominal; - double eps_minus = nominal - low->getVal(); - double S = 0.5 * (eps_plus + eps_minus); - double A = 0.0625 * (eps_plus - eps_minus); - - //fcns+der+2nd_der are eq at bd - - double val = nominal + x * (S + x * A * ( 15 + x * x * (-10 + x * x * 3 ) ) ); - - - if (val < 0) val = 0; - sum += val-nominal; - } - break ; - - // WVE **************************************************************** - } - case 5: { - - double x0 = 1.0;//boundary; - double x = param->getVal(); - - if (x > x0 || x < -x0) - { - if(x>0) - sum += x*(high->getVal() - nominal ); - else - sum += x*(nominal - low->getVal()); - } - else if (nominal != 0) - { - double eps_plus = high->getVal() - nominal; - double eps_minus = nominal - low->getVal(); - double S = (eps_plus + eps_minus)/2; - double A = (eps_plus - eps_minus)/2; - - //fcns+der are eq at bd - double a = S; - double b = 3*A/(2*x0); - //double c = 0; - double d = -A/(2*x0*x0*x0); - - double val = nominal + a*x + b*pow(x, 2) + 0/*c*pow(x, 3)*/ + d*pow(x, 4); - if (val < 0) val = 0; - - //cout << "Using interp code 5, val = " << val << endl; - - sum += val-nominal; - } - break ; - } - default: { + if(icode < 0 || icode > 5) { coutE(InputArguments) << "PiecewiseInterpolation::evaluate ERROR: " << param->GetName() << " with unknown interpolation code" << icode << endl ; - break ; - } } + sum = piecewiseInterpolation(icode, low->getVal(), high->getVal(), nominal, param->getVal(), sum); } if(_positiveDefinite && (sum<0)){ @@ -307,12 +208,40 @@ double PiecewiseInterpolation::evaluate() const } +void PiecewiseInterpolation::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + unsigned int n = _interpCode.size(); + + std::string resName = "total_" + ctx.getTmpVarName(); + ctx.addToCodeBody(this, "double " + resName + " = " + ctx.getResult(_nominal) + ";\n"); + std::string code = ""; + for (std::size_t i = 0; i < n; ++i) { + if (_interpCode[i] < 0 || _interpCode[i] > 5) { + coutE(InputArguments) << "PiecewiseInterpolation::evaluate ERROR: " << _paramSet[i].GetName() + << " with unknown interpolation code" << _interpCode[i] << endl; + } + std::string funcCall; + if (_interpCode[i] < 4) + funcCall = ctx.buildCall("RooFit::Detail::EvaluateFuncs::flexibleInterp", _interpCode[i], 0, + _lowSet[i], _highSet[i], 1, _nominal, _paramSet[i], resName); + else + funcCall = ctx.buildCall("RooFit::Detail::EvaluateFuncs::piecewiseInterpolation", _interpCode[i], + _lowSet[i], _highSet[i], _nominal, _paramSet[i], resName); + + code += resName + " = " + funcCall + ";\n"; + } + if (_positiveDefinite) + code += resName + " = " + resName + " < 0 ? 0 : " + resName + ";\n"; + + ctx.addToCodeBody(this, code); + ctx.addResult(this, resName); +} //////////////////////////////////////////////////////////////////////////////// /// Interpolate between input distributions for all values of the observable in `evalData`. /// \param[in,out] evalData Struct holding spans pointing to input data. The results of this function will be stored here. /// \param[in] normSet Arguments to normalise over. -void PiecewiseInterpolation::computeBatch(cudaStream_t*, double* sum, size_t /*size*/, RooFit::Detail::DataMap const& dataMap) const { +void PiecewiseInterpolation::computeBatch(double* sum, size_t /*size*/, RooFit::Detail::DataMap const& dataMap) const { auto nominal = dataMap.at(_nominal); for(unsigned int j=0; j < nominal.size(); ++j) { sum[j] = nominal[j]; @@ -324,109 +253,14 @@ void PiecewiseInterpolation::computeBatch(cudaStream_t*, double* sum, size_t /*s auto high = dataMap.at(_highSet.at(i)); const int icode = _interpCode[i]; - switch(icode) { - case 0: { - // piece-wise linear - for (unsigned int j=0; j < nominal.size(); ++j) { - if(param >0) - sum[j] += param * (high[j] - nominal[j]); - else - sum[j] += param * (nominal[j] - low[j] ); - } - break; - } - case 1: { - // pice-wise log - for (unsigned int j=0; j < nominal.size(); ++j) { - if(param >=0) - sum[j] *= pow(high[j]/ nominal[j], +param); - else - sum[j] *= pow(low[j] / nominal[j], -param); - } - break; - } - case 2: - // parabolic with linear - for (unsigned int j=0; j < nominal.size(); ++j) { - const double a = 0.5*(high[j]+low[j])-nominal[j]; - const double b = 0.5*(high[j]-low[j]); - const double c = 0; - if (param > 1.) { - sum[j] += (2*a+b)*(param -1)+high[j]-nominal[j]; - } else if (param < -1.) { - sum[j] += -1*(2*a-b)*(param +1)+low[j]-nominal[j]; - } else { - sum[j] += a*pow(param ,2) + b*param +c; - } - } - break; - case 3: { - //parabolic version of log-normal - for (unsigned int j=0; j < nominal.size(); ++j) { - const double a = 0.5*(high[j]+low[j])-nominal[j]; - const double b = 0.5*(high[j]-low[j]); - const double c = 0; - if (param > 1.) { - sum[j] += (2*a+b)*(param -1)+high[j]-nominal[j]; - } else if (param < -1.) { - sum[j] += -1*(2*a-b)*(param +1)+low[j]-nominal[j]; - } else { - sum[j] += a*pow(param ,2) + b*param +c; - } - } - break; - } - case 4: - for (unsigned int j=0; j < nominal.size(); ++j) { - const double x = param; - if (x > 1.) { - sum[j] += x * (high[j] - nominal[j]); - } else if (x < -1.) { - sum[j] += x * (nominal[j] - low[j]); - } else { - const double eps_plus = high[j] - nominal[j]; - const double eps_minus = nominal[j] - low[j]; - const double S = 0.5 * (eps_plus + eps_minus); - const double A = 0.0625 * (eps_plus - eps_minus); - - double val = nominal[j] + x * (S + x * A * ( 15. + x * x * (-10. + x * x * 3. ) ) ); - - if (val < 0.) val = 0.; - sum[j] += val - nominal[j]; - } - } - break; - case 5: - for (unsigned int j=0; j < nominal.size(); ++j) { - if (param > 1. || param < -1.) { - if(param>0) - sum[j] += param * (high[j] - nominal[j]); - else - sum[j] += param * (nominal[j] - low[j] ); - } else if (nominal[j] != 0) { - const double eps_plus = high[j] - nominal[j]; - const double eps_minus = nominal[j] - low[j]; - const double S = (eps_plus + eps_minus)/2; - const double A = (eps_plus - eps_minus)/2; - - //fcns+der are eq at bd - const double a = S; - const double b = 3*A/(2*1.); - //double c = 0; - const double d = -A/(2*1.*1.*1.); - - double val = nominal[j] + a * param + b * pow(param, 2) + d * pow(param, 4); - if (val < 0.) val = 0.; - - sum[j] += val - nominal[j]; - } - } - break; - default: - coutE(InputArguments) << "PiecewiseInterpolation::evaluateSpan(): " << _paramSet[i].GetName() + if (icode < 0 || icode > 5) { + coutE(InputArguments) << "PiecewiseInterpolation::computeBatch(): " << _paramSet[i].GetName() << " with unknown interpolation code" << icode << std::endl; - throw std::invalid_argument("PiecewiseInterpolation::evaluateSpan() got invalid interpolation code " + std::to_string(icode)); - break; + throw std::invalid_argument("PiecewiseInterpolation::computeBatch() got invalid interpolation code " + std::to_string(icode)); + } + + for (unsigned int j=0; j < nominal.size(); ++j) { + sum[j] = piecewiseInterpolation(icode, low[j], high[j], nominal[j], param, sum[j]); } } @@ -507,23 +341,20 @@ Int_t PiecewiseInterpolation::getAnalyticalIntegralWN(RooArgSet& allVars, RooArg // Make list of function projection and normalization integrals RooAbsReal *func ; - RooAbsReal *funcInt; // do variations for (auto it = _paramSet.begin(); it != _paramSet.end(); ++it) { auto i = it - _paramSet.begin(); func = static_cast(_lowSet.at(i)); - funcInt = func->createIntegral(analVars) ; - cache->_lowIntList.addOwned(*funcInt) ; + cache->_lowIntList.addOwned(std::unique_ptr{func->createIntegral(analVars)}); func = static_cast(_highSet.at(i)); - funcInt = func->createIntegral(analVars) ; - cache->_highIntList.addOwned(*funcInt); + cache->_highIntList.addOwned(std::unique_ptr{func->createIntegral(analVars)}); } // Store cache element - Int_t code = _normIntMgr.setObj(normSet,&analVars,(RooAbsCacheElement*)cache,0) ; + Int_t code = _normIntMgr.setObj(normSet,&analVars,(RooAbsCacheElement*)cache,nullptr) ; return code+1 ; } @@ -670,7 +501,7 @@ double PiecewiseInterpolation::analyticalIntegralWN(Int_t code, const RooArgSet* else value += param->getVal()*(nominal - low->getVal()); } else if(_interpCode.at(i)==1){ - // pice-wise log + // piece-wise log if(param->getVal()>=0) value *= pow(high->getVal()/nominal, +param->getVal()); else diff --git a/roofit/histfactory/src/RooBarlowBeestonLL.cxx b/roofit/histfactory/src/RooBarlowBeestonLL.cxx index a1fee619e6253..cb831bff5f25b 100644 --- a/roofit/histfactory/src/RooBarlowBeestonLL.cxx +++ b/roofit/histfactory/src/RooBarlowBeestonLL.cxx @@ -75,14 +75,11 @@ RooStats::HistFactory::RooBarlowBeestonLL::RooBarlowBeestonLL(const char *name, // Determine actual parameters and observables /* - RooArgSet* actualObs = nllIn.getObservables(observables) ; - RooArgSet* actualPars = nllIn.getParameters(observables) ; + std::unique_ptr actualObs{nllIn.getObservables(observables)}; + std::unique_ptr actualPars{nllIn.getParameters(observables)}; _obs.add(*actualObs) ; _par.add(*actualPars) ; - - delete actualObs ; - delete actualPars ; */ } @@ -137,7 +134,7 @@ void RooStats::HistFactory::RooBarlowBeestonLL::initializeBarlowCache() { // Get a list of constraint terms RooArgList obsTerms; RooArgList constraints; - RooArgSet* obsSet = _pdf->getObservables(*_data); + RooArgSet* obsSet = std::unique_ptr{_pdf->getObservables(*_data)}.release(); FactorizeHistFactoryPdf(*obsSet, *_pdf, obsTerms, constraints); if( obsTerms.empty() ) { @@ -151,25 +148,18 @@ void RooStats::HistFactory::RooBarlowBeestonLL::initializeBarlowCache() { return; } - /* - // Get the channels for this pdf - RooArgSet* channels = new RooArgSet(); - RooArgSet* channelsWithConstraints = new RooArgSet(); - getChannelsFromModel( _pdf, channels, channelsWithConstraints ); - */ - // Loop over the channels RooSimultaneous* simPdf = (RooSimultaneous*) _pdf; RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat()); for (const auto& nameIdx : *channelCat) { - // Warning: channel cat name is not necesarily the same name + // Warning: channel cat name is not necessarily the same name // as the pdf's (for example, if someone does edits) RooAbsPdf* channelPdf = simPdf->getPdf(nameIdx.first.c_str()); std::string channel_name = channelPdf->GetName(); // First, we check if this channel uses Stat Uncertainties: - RooArgList* gammas = new RooArgList(); + RooArgList* gammas = nullptr; ParamHistFunc* param_func=nullptr; bool hasStatUncert = getStatUncertaintyFromChannel( channelPdf, param_func, gammas ); if( ! hasStatUncert ) { @@ -398,12 +388,11 @@ void RooStats::HistFactory::RooBarlowBeestonLL::FactorizePdf(const RooArgSet &ob } } else if (id == typeid(RooSimultaneous) ) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast(&pdf); - RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().Clone(); + std::unique_ptr cat{(RooAbsCategoryLValue *) sim->indexCat().Clone()}; for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) { cat->setBin(ic); FactorizePdf(observables, *sim->getPdf(cat->getLabel()), obsTerms, constraints); } - delete cat; } else if (pdf.dependsOn(observables)) { if (!obsTerms.contains(pdf)) obsTerms.add(pdf); } else { @@ -632,7 +621,7 @@ void RooStats::HistFactory::RooBarlowBeestonLL::validateAbsMin() const // Save current values of non-marginalized parameters - RooArgSet* obsStart = (RooArgSet*) _obs.snapshot(false) ; + std::unique_ptr obsStart{(RooArgSet*) _obs.snapshot(false)}; // Start from previous global minimum if (_paramAbsMin.getSize()>0) { @@ -654,9 +643,8 @@ void RooStats::HistFactory::RooBarlowBeestonLL::validateAbsMin() const _paramAbsMin.removeAll() ; // Only store non-constant parameters here! - RooArgSet* tmp = (RooArgSet*) _par.selectByAttrib("Constant",false) ; + std::unique_ptr tmp{(RooArgSet*) _par.selectByAttrib("Constant",false)}; _paramAbsMin.addClone(*tmp) ; - delete tmp ; _obsAbsMin.addClone(_obs) ; @@ -682,7 +670,6 @@ void RooStats::HistFactory::RooBarlowBeestonLL::validateAbsMin() const // Restore original parameter values const_cast(_obs) = *obsStart ; - delete obsStart ; } } diff --git a/roofit/histfactory/src/Sample.cxx b/roofit/histfactory/src/Sample.cxx index fce52ab67a0af..33bd57c4d55ca 100644 --- a/roofit/histfactory/src/Sample.cxx +++ b/roofit/histfactory/src/Sample.cxx @@ -298,7 +298,7 @@ void RooStats::HistFactory::Sample::PrintXML( std::ofstream& xml ) const { // Some helper functions // (Not strictly necessary because -// methods are publicly accessable) +// methods are publicly accessible) void RooStats::HistFactory::Sample::ActivateStatError() { diff --git a/roofit/histfactory/src/Systematics.cxx b/roofit/histfactory/src/Systematics.cxx index 9073e84f0afce..7857069c20e98 100644 --- a/roofit/histfactory/src/Systematics.cxx +++ b/roofit/histfactory/src/Systematics.cxx @@ -33,7 +33,7 @@ std::string RooStats::HistFactory::Constraint::Name( Constraint::Type type ) { RooStats::HistFactory::Constraint::Type RooStats::HistFactory::Constraint::GetType( const std::string& Name ) { - if( Name == "" ) { + if( Name.empty() ) { std::cout << "Error: Given empty name for ConstraintType" << std::endl; throw hf_exc(); } @@ -214,7 +214,7 @@ void RooStats::HistFactory::ShapeFactor::Print( std::ostream& stream ) const { stream << "\t \t Name: " << fName << std::endl; - if( fHistoNameHigh != "" ) { + if( !fHistoNameHigh.empty() ) { stream << "\t \t " << " Shape Hist Name: " << fHistoNameHigh << " Shape Hist Path Name: " << fHistoPathHigh diff --git a/roofit/histfactory/src/hist2workspace.cxx b/roofit/histfactory/src/hist2workspace.cxx index 5a24c162ef6d3..ef81986727a42 100644 --- a/roofit/histfactory/src/hist2workspace.cxx +++ b/roofit/histfactory/src/hist2workspace.cxx @@ -110,22 +110,7 @@ int main(int argc, char** argv) { driverArg = argv[i]; } - try { - RooStats::HistFactory::fastDriver(driverArg, cfg); - } - catch(const std::string &str) { - std::cerr << "hist2workspace - Caught exception: " << str << std::endl ; - return 1; - } - catch( const std::exception& e ) { - std::cerr << "hist2workspace - Caught Exception: " << e.what() << std::endl; - return 1; - } - catch(...) { - std::cerr << "hist2workspace - Caught Exception" << std::endl; - return 1; - } - + RooStats::HistFactory::fastDriver(driverArg, cfg); return 0; } diff --git a/roofit/histfactory/test/CMakeLists.txt b/roofit/histfactory/test/CMakeLists.txt index c70fd30b58689..39bd8a42baa82 100644 --- a/roofit/histfactory/test/CMakeLists.txt +++ b/roofit/histfactory/test/CMakeLists.txt @@ -7,7 +7,14 @@ # @author Stephan Hageboeck CERN, 2019 ROOT_ADD_GTEST(testHistFactory testHistFactory.cxx - LIBRARIES RooFitCommon RooFitCore RooFit RooStats HistFactory + LIBRARIES RooFitCore RooFit RooStats HistFactory RooFitHS3 COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/ref_6.16_example_UsingC_channel1_meas_model.root ${CMAKE_CURRENT_SOURCE_DIR}/ref_6.16_example_UsingC_combined_meas_model.root) +if(clad) + if(NOT MSVC OR win_broken_tests) + target_compile_definitions(testHistFactory PUBLIC TEST_CODEGEN_AD) + endif() +endif(clad) + ROOT_ADD_GTEST(testParamHistFunc testParamHistFunc.cxx LIBRARIES RooFitCore HistFactory) +ROOT_ADD_GTEST(testHistFactoryPlotting testHistFactoryPlotting.cxx LIBRARIES RooFitCore HistFactory) diff --git a/roofit/histfactory/test/testHistFactory.cxx b/roofit/histfactory/test/testHistFactory.cxx index 98f3c7ea2da43..a15a7f1f219b8 100644 --- a/roofit/histfactory/test/testHistFactory.cxx +++ b/roofit/histfactory/test/testHistFactory.cxx @@ -1,26 +1,32 @@ // Tests for the HistFactory // Authors: Stephan Hageboeck, CERN 01/2019 - -#include "RooStats/HistFactory/Measurement.h" -#include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h" -#include "RooStats/HistFactory/Sample.h" -#include "RooStats/ModelConfig.h" - -#include "RooFit/Common.h" -#include "RooWorkspace.h" -#include "RooArgSet.h" -#include "RooSimultaneous.h" -#include "RooRealSumPdf.h" -#include "RooRealVar.h" -#include "RooHelpers.h" -#include "RooFitResult.h" -#include "RooPlot.h" -#include "RunContext.h" - -#include "TROOT.h" -#include "TFile.h" -#include "TCanvas.h" -#include "gtest/gtest.h" +// Jonas Rembser, CERN 06/2023 + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include // Backward compatibility for gtest version < 1.10.0 #ifndef INSTANTIATE_TEST_SUITE_P @@ -29,86 +35,145 @@ #include -using namespace RooStats; -using namespace RooStats::HistFactory; +namespace { + +// If the JSON files should be written out for debugging purpose. +const bool writeJsonFiles = false; + +std::vector getValues(RooAbsReal const &real, RooRealVar &obs, bool normalize, bool useBatchMode) +{ + std::vector out; + // We want to evaluate the function at the bin centers + std::vector binCenters(obs.numBins()); + for (int iBin = 0; iBin < obs.numBins(); ++iBin) { + obs.setBin(iBin); + binCenters[iBin] = obs.getVal(); + out.push_back(normalize ? real.getVal(obs) : real.getVal()); + } + + if (useBatchMode == false) { + return out; + } + + std::unique_ptr clone; + if (normalize) { + clone = RooFit::Detail::compileForNormSet(real, obs); + } else { + clone.reset(static_cast(real.cloneTree())); + } + + RooFit::Evaluator evaluator(*clone); + evaluator.setInput(obs.GetName(), binCenters, false); + std::span results = evaluator.run(); + out.assign(results.begin(), results.end()); + return out; +} + +} // namespace TEST(Sample, CopyAssignment) { - Sample s("s"); - { - Sample s1("s1"); - auto hist1 = new TH1D("hist1", "hist1", 10, 0, 10); - s1.SetHisto(hist1); - s = s1; - //Now go out of scope. Should delete hist1, that's owned by s1. - } - - auto hist = s.GetHisto(); - ASSERT_EQ(hist->GetNbinsX(), 10); + RooStats::HistFactory::Sample s("s"); + { + RooStats::HistFactory::Sample s1("s1"); + auto hist1 = new TH1D("hist1", "hist1", 10, 0, 10); + s1.SetHisto(hist1); + s = s1; + // Now go out of scope. Should delete hist1, that's owned by s1. + } + + auto hist = s.GetHisto(); + ASSERT_EQ(hist->GetNbinsX(), 10); } +TEST(HistFactory, Read_ROOT6_16_Model) +{ + RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; -TEST(HistFactory, Read_ROOT6_16_Model) { - std::string filename = "./ref_6.16_example_UsingC_channel1_meas_model.root"; - std::unique_ptr file(TFile::Open(filename.c_str())); - if (!file || !file->IsOpen()) { - filename = TROOT::GetRootSys() + "/roofit/histfactory/test/" + filename; - file.reset(TFile::Open(filename.c_str())); - } + std::string filename = "./ref_6.16_example_UsingC_channel1_meas_model.root"; + std::unique_ptr file(TFile::Open(filename.c_str())); + if (!file || !file->IsOpen()) { + filename = TROOT::GetRootSys() + "/roofit/histfactory/test/" + filename; + file.reset(TFile::Open(filename.c_str())); + } - ASSERT_TRUE(file && file->IsOpen()); - RooWorkspace* ws; - file->GetObject("channel1", ws); - ASSERT_NE(ws, nullptr); + ASSERT_TRUE(file && file->IsOpen()); + RooWorkspace *ws; + file->GetObject("channel1", ws); + ASSERT_NE(ws, nullptr); - auto mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); + auto mc = dynamic_cast(ws->obj("ModelConfig")); + ASSERT_NE(mc, nullptr); - RooAbsPdf* pdf = mc->GetPdf(); - ASSERT_NE(pdf, nullptr); + RooAbsPdf *pdf = mc->GetPdf(); + ASSERT_NE(pdf, nullptr); - const RooArgSet* obs = mc->GetObservables(); - ASSERT_NE(obs, nullptr); + const RooArgSet *obs = mc->GetObservables(); + ASSERT_NE(obs, nullptr); - EXPECT_NEAR(pdf->getVal(), 0.17488817, 1.E-8); - EXPECT_NEAR(pdf->getVal(*obs), 0.95652174, 1.E-8); + EXPECT_NEAR(pdf->getVal(), 0.17488817, 1.E-8); + EXPECT_NEAR(pdf->getVal(*obs), 0.95652174, 1.E-8); } +TEST(HistFactory, Read_ROOT6_16_Combined_Model) +{ + RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; -TEST(HistFactory, Read_ROOT6_16_Combined_Model) { - std::string filename = "./ref_6.16_example_UsingC_combined_meas_model.root"; - std::unique_ptr file(TFile::Open(filename.c_str())); - if (!file || !file->IsOpen()) { - filename = TROOT::GetRootSys() + "/roofit/histfactory/test/" + filename; - file.reset(TFile::Open(filename.c_str())); - } + std::string filename = "./ref_6.16_example_UsingC_combined_meas_model.root"; + std::unique_ptr file(TFile::Open(filename.c_str())); + if (!file || !file->IsOpen()) { + filename = TROOT::GetRootSys() + "/roofit/histfactory/test/" + filename; + file.reset(TFile::Open(filename.c_str())); + } - ASSERT_TRUE(file && file->IsOpen()); - RooWorkspace* ws; - file->GetObject("combined", ws); - ASSERT_NE(ws, nullptr); + ASSERT_TRUE(file && file->IsOpen()); + RooWorkspace *ws; + file->GetObject("combined", ws); + ASSERT_NE(ws, nullptr); - auto mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); + auto mc = dynamic_cast(ws->obj("ModelConfig")); + ASSERT_NE(mc, nullptr); - RooAbsPdf* pdf = mc->GetPdf(); - ASSERT_NE(pdf, nullptr); + RooAbsPdf *pdf = mc->GetPdf(); + ASSERT_NE(pdf, nullptr); - const RooArgSet* obs = mc->GetObservables(); - ASSERT_NE(obs, nullptr); + const RooArgSet *obs = mc->GetObservables(); + ASSERT_NE(obs, nullptr); - EXPECT_NEAR(pdf->getVal(), 0.17488817, 1.E-8); - EXPECT_NEAR(pdf->getVal(*obs), 0.95652174, 1.E-8); + EXPECT_NEAR(pdf->getVal(), 0.17488817, 1.E-8); + EXPECT_NEAR(pdf->getVal(*obs), 0.95652174, 1.E-8); } - /// What kind of model is set up. Use this to instantiate /// a test suite. -/// \note Make sure that equidistant bins have even numbers, -/// so those tests can be found using `% 2 == kEquidistantBins`. -enum MakeModelMode {kEquidistantBins=0, kCustomBins=1, - kEquidistantBins_histoSyst = 2, kCustomBins_histoSyst = 3, - kEquidistantBins_statSyst = 4, kCustomBins_statSyst = 5}; +enum class MakeModelMode { OverallSyst, HistoSyst, StatSyst, ShapeSyst }; + +using HFTestParam = std::tuple; + +std::string getName(HFTestParam const ¶m) +{ + const MakeModelMode mode = std::get<0>(param); + const bool customBins = std::get<1>(param); + auto const &evalBackend = std::get<2>(param); + + std::stringstream ss; + + ss << (customBins ? "CustomBins" : "EquidistantBins"); + + if (mode == MakeModelMode::OverallSyst) + ss << "_OverallSyst"; + if (mode == MakeModelMode::HistoSyst) + ss << "_HistoSyst"; + if (mode == MakeModelMode::StatSyst) + ss << "_StatSyst"; + if (mode == MakeModelMode::ShapeSyst) + ss << "_ShapeSyst"; + + ss << "_Backend_" << evalBackend.name(); + + return ss.str(); +} + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Fixture class to set up a toy hist factory model. /// In the SetUp() phase @@ -116,508 +181,605 @@ enum MakeModelMode {kEquidistantBins=0, kCustomBins=1, /// equidistant or custom bins are used, and shape systematics are added. /// - A Measurement with the histograms in the file is created. /// - The corresponding workspace is created. -class HFFixture : public testing::TestWithParam { +class HFFixture : public testing::TestWithParam { public: - std::string _inputFile{"TestMakeModel.root"}; - static constexpr bool _verbose = false; - double _customBins[3] = {0., 1.8, 2.}; - const double _targetMu = 2.; - const double _targetNominal[2] = {110., 120.}; - const double _targetSysUp[2] = {112., 140.}; - const double _targetSysDo[2] = {108., 100.}; - std::unique_ptr ws; - std::set _systNames; // Systematics defined during set up - - void SetUp() { - { - TFile example(_inputFile.c_str(), "RECREATE"); - TH1F *data, *signal, *bkg1, *bkg2, *statUnc, *systUncUp, *systUncDo; - data = signal = bkg1 = bkg2 = statUnc = systUncUp = systUncDo = nullptr; - if (GetParam() % 2 == kEquidistantBins) { - data = new TH1F("data","data", 2,1,2); - signal = new TH1F("signal","signal histogram (pb)", 2,1,2); - bkg1 = new TH1F("background1","background 1 histogram (pb)", 2,1,2); - bkg2 = new TH1F("background2","background 2 histogram (pb)", 2,1,2); - statUnc = new TH1F("background1_statUncert", "statUncert", 2,1,2); - systUncUp = new TH1F("shapeUnc_sigUp", "signal shape uncert.", 2,1,2); - systUncDo = new TH1F("shapeUnc_sigDo", "signal shape uncert.", 2,1,2); - } else if (GetParam() % 2 == kCustomBins) { - data = new TH1F("data","data", 2, _customBins); - signal = new TH1F("signal","signal histogram (pb)", 2, _customBins); - bkg1 = new TH1F("background1","background 1 histogram (pb)", 2, _customBins); - bkg2 = new TH1F("background2","background 2 histogram (pb)", 2, _customBins); - statUnc = new TH1F("background1_statUncert", "statUncert", 2, _customBins); - systUncUp = new TH1F("shapeUnc_sigUp", "signal shape uncert.", 2, _customBins); - systUncDo = new TH1F("shapeUnc_sigDo", "signal shape uncert.", 2, _customBins); - } else { - // Harden the test and make clang-tidy happy: - FAIL() << "This should not be reachable."; + std::string _inputFile{"TestMakeModel.root"}; + static constexpr bool _verbose = false; + double _customBins[3] = {0., 1.8, 2.}; + const double _tgtMu = 2.; + const double _tgtNom[2] = {110., 120.}; + const double _tgtSysUp[2] = {112., 140.}; + const double _tgtSysDo[2] = {108., 100.}; + const double _tgtShapeSystBkg1[2] = {0.15, 0.0}; + const double _tgtShapeSystBkg2[2] = {0.0, 0.10}; + std::unique_ptr ws; + std::set _systNames; // Systematics defined during set up + std::unique_ptr _measurement; + std::string _name; + + TH1D *createHisto(const char *name, const char *title, bool customBins) + { + if (customBins) + return new TH1D{name, title, 2, _customBins}; + return new TH1D{name, title, 2, 1, 2}; + } + + void SetUp() + { + using namespace RooStats::HistFactory; + + _name = getName(GetParam()); + + const MakeModelMode makeModelMode = std::get<0>(GetParam()); + const bool customBins = std::get<1>(GetParam()); + + { + TFile example(_inputFile.c_str(), "RECREATE"); + + TH1D *data = createHisto("data", "data", customBins); + TH1D *signal = createHisto("signal", "signal histogram (pb)", customBins); + TH1D *bkg1 = createHisto("background1", "background 1 histogram (pb)", customBins); + TH1D *bkg2 = createHisto("background2", "background 2 histogram (pb)", customBins); + TH1D *statUnc = createHisto("background1_statUncert", "statUncert", customBins); + TH1D *systUncUp = createHisto("histoUnc_sigUp", "signal shape uncert.", customBins); + TH1D *systUncDo = createHisto("histoUnc_sigDo", "signal shape uncert.", customBins); + TH1D *shapeSystBkg1 = createHisto("background1_shapeSyst", "background 1 shapeSyst", customBins); + TH1D *shapeSystBkg2 = createHisto("background2_shapeSyst", "background 2 shapeSyst", customBins); + + bkg1->SetBinContent(1, 100); + bkg2->SetBinContent(2, 100); + + for (unsigned int bin = 0; bin < 2; ++bin) { + signal->SetBinContent(bin + 1, _tgtNom[bin] - 100.); + systUncUp->SetBinContent(bin + 1, _tgtSysUp[bin] - 100.); + systUncDo->SetBinContent(bin + 1, _tgtSysDo[bin] - 100.); + shapeSystBkg1->SetBinContent(bin + 1, _tgtShapeSystBkg1[bin]); + shapeSystBkg2->SetBinContent(bin + 1, _tgtShapeSystBkg2[bin]); + + if (makeModelMode == MakeModelMode::OverallSyst) { + data->SetBinContent(bin + 1, _tgtMu * signal->GetBinContent(bin + 1) + 100.); + } else if (makeModelMode == MakeModelMode::HistoSyst) { + // Set data such that alpha = -1., fit should pull parameter. + data->SetBinContent(bin + 1, _tgtMu * systUncDo->GetBinContent(bin + 1) + 100.); + } else if (makeModelMode == MakeModelMode::StatSyst) { + // Tighten the stat. errors of the model, and kick bin 0, so the gammas have to adapt + signal->SetBinError(bin + 1, 0.1 * std::sqrt(signal->GetBinContent(bin + 1))); + bkg1->SetBinError(bin + 1, 0.1 * std::sqrt(bkg1->GetBinContent(bin + 1))); + bkg2->SetBinError(bin + 1, 0.1 * std::sqrt(bkg2->GetBinContent(bin + 1))); + + data->SetBinContent(bin + 1, _tgtMu * signal->GetBinContent(bin + 1) + 100. + (bin == 0 ? 50. : 0.)); + } else if (makeModelMode == MakeModelMode::ShapeSyst) { + // Distort data such that the shape systematics will pull gamma + // down in one bin and up in the other. + data->SetBinContent(bin + 1, _tgtMu * signal->GetBinContent(bin + 1) + (bin == 0 ? 85. : 110)); + } + + // A small statistical uncertainty + statUnc->SetBinContent(bin + 1, .05); // 5% uncertainty + } + + for (auto hist : {data, signal, bkg1, bkg2, statUnc, systUncUp, systUncDo, shapeSystBkg1, shapeSystBkg2}) { + example.WriteTObject(hist); + } + } + + // Create the measurement + _measurement = std::make_unique("meas", "meas"); + RooStats::HistFactory::Measurement &meas = *_measurement; + + meas.SetOutputFilePrefix("example_variableBins"); + meas.SetPOI("SigXsecOverSM"); + meas.AddConstantParam("Lumi"); + if (makeModelMode == MakeModelMode::HistoSyst || makeModelMode == MakeModelMode::ShapeSyst) { + meas.AddConstantParam("gamma_stat_channel1_bin_0"); + meas.AddConstantParam("gamma_stat_channel1_bin_1"); } - bkg1->SetBinContent(1, 100); - bkg2->SetBinContent(2, 100); - - for (unsigned int bin=0; bin < 2; ++bin) { - signal-> SetBinContent(bin+1, _targetNominal[bin] - 100.); - systUncUp->SetBinContent(bin+1, _targetSysUp[bin] - 100.); - systUncDo->SetBinContent(bin+1, _targetSysDo[bin] - 100.); - - if (GetParam() <= kCustomBins) { - data->SetBinContent(bin+1, _targetMu * signal->GetBinContent(bin+1) + 100.); - } else if (GetParam() <= kCustomBins_histoSyst) { - // Set data such that alpha = -1., fit should pull parameter. - data->SetBinContent(bin+1, _targetMu * systUncDo->GetBinContent(bin+1) + 100.); - } else if (GetParam() <= kCustomBins_statSyst) { - // Tighten the stat. errors of the model, and kick bin 0, so the gammas have to adapt - signal->SetBinError(bin+1, 0.1 * sqrt(signal->GetBinContent(bin+1))); - bkg1 ->SetBinError(bin+1, 0.1 * sqrt(bkg1 ->GetBinContent(bin+1))); - bkg2 ->SetBinError(bin+1, 0.1 * sqrt(bkg2 ->GetBinContent(bin+1))); - - data->SetBinContent(bin+1, _targetMu * signal->GetBinContent(bin+1) + 100. + (bin == 0 ? 50. : 0.)); - } - - // A small statistical uncertainty - statUnc->SetBinContent(bin+1, .05); // 5% uncertainty + meas.SetExportOnly(true); + + meas.SetLumi(1.0); + meas.SetLumiRelErr(0.10); + + // Create a channel + RooStats::HistFactory::Channel chan("channel1"); + chan.SetData("data", _inputFile); + chan.SetStatErrorConfig(0.005, "Poisson"); + _systNames.insert("gamma_stat_channel1_bin_0"); + _systNames.insert("gamma_stat_channel1_bin_1"); + + // Now, create some samples + + // Create the signal sample + RooStats::HistFactory::Sample signal("signal", "signal", _inputFile); + + signal.AddNormFactor("SigXsecOverSM", 1, 0, 3); + if (makeModelMode == MakeModelMode::HistoSyst) { + signal.AddHistoSys("SignalShape", "histoUnc_sigDo", _inputFile, "", "histoUnc_sigUp", _inputFile, ""); + _systNames.insert("alpha_SignalShape"); } + chan.AddSample(signal); + + // Background 1 + RooStats::HistFactory::Sample background1("background1", "background1", _inputFile); + background1.ActivateStatError("background1_statUncert", _inputFile); + if (makeModelMode == MakeModelMode::OverallSyst) { + background1.AddOverallSys("syst2", 0.95, 1.05); + background1.AddOverallSys("syst3", 0.99, 1.01); + _systNames.insert("alpha_syst2"); + _systNames.insert("alpha_syst3"); + } + if (makeModelMode == MakeModelMode::ShapeSyst) { + background1.AddShapeSys("background1Shape", Constraint::Gaussian, "background1_shapeSyst", _inputFile); + meas.AddConstantParam("gamma_background1Shape_bin_1"); + _systNames.insert("gamma_background1Shape_bin_0"); + _systNames.insert("gamma_background1Shape_bin_1"); + } + chan.AddSample(background1); + + // Background 2 + RooStats::HistFactory::Sample background2("background2", "background2", _inputFile); + background2.ActivateStatError(); + if (makeModelMode == MakeModelMode::OverallSyst) { + background2.AddOverallSys("syst3", 0.99, 1.01); + background2.AddOverallSys("syst4", 0.95, 1.05); + _systNames.insert("alpha_syst3"); + _systNames.insert("alpha_syst4"); + } + if (makeModelMode == MakeModelMode::ShapeSyst) { + background2.AddShapeSys("background2Shape", Constraint::Poisson, "background2_shapeSyst", _inputFile); + meas.AddConstantParam("gamma_background2Shape_bin_0"); + _systNames.insert("gamma_background2Shape_bin_0"); + _systNames.insert("gamma_background2Shape_bin_1"); + } + chan.AddSample(background2); + // Done with this channel + // Add it to the measurement: + meas.AddChannel(chan); - for (auto hist : {data, signal, bkg1, bkg2, statUnc, systUncUp, systUncDo}) { - example.WriteTObject(hist); + if (!_verbose) { + RooMsgService::instance().getStream(1).minLevel = RooFit::PROGRESS; + RooMsgService::instance().getStream(2).minLevel = RooFit::WARNING; } - } - - - // Create the measurement - Measurement meas("meas", "meas"); - - meas.SetOutputFilePrefix( "example_variableBins" ); - meas.SetPOI( "SigXsecOverSM" ); - meas.AddConstantParam("alpha_syst1"); - meas.AddConstantParam("Lumi"); - if (GetParam() == kEquidistantBins_histoSyst || GetParam() == kCustomBins_histoSyst) { - // We are testing the shape systematics. Switch off the normalisation - // systematics for the background here: - meas.AddConstantParam("alpha_syst2"); - meas.AddConstantParam("alpha_syst4"); - meas.AddConstantParam("gamma_stat_channel1_bin_0"); - meas.AddConstantParam("gamma_stat_channel1_bin_1"); - } else if (GetParam() == kEquidistantBins_statSyst || GetParam() == kCustomBins_statSyst) { - // Fix all systematics but the gamma parameters - // Cannot set the POI constant here, happens in the fit test. - meas.AddConstantParam("alpha_syst2"); - meas.AddConstantParam("alpha_syst3"); - meas.AddConstantParam("alpha_syst4"); - meas.AddConstantParam("alpha_SignalShape"); - } - - meas.SetExportOnly(true); - - meas.SetLumi( 1.0 ); - meas.SetLumiRelErr( 0.10 ); - - - // Create a channel - Channel chan( "channel1" ); - chan.SetData( "data", _inputFile); - chan.SetStatErrorConfig( 0.005, "Poisson" ); - _systNames.insert("gamma_stat_channel1_bin_0"); - _systNames.insert("gamma_stat_channel1_bin_1"); - - - - // Now, create some samples - - // Create the signal sample - Sample signal( "signal", "signal", _inputFile); - signal.AddOverallSys( "syst1", 0.95, 1.05 ); - _systNames.insert("alpha_syst1"); - - signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 ); - if (GetParam() >= kEquidistantBins_histoSyst) { - signal.AddHistoSys("SignalShape", - "shapeUnc_sigDo", _inputFile, "", - "shapeUnc_sigUp", _inputFile, ""); - _systNames.insert("alpha_SignalShape"); - } - chan.AddSample( signal ); - - // Background 1 - Sample background1( "background1", "background1", _inputFile); - background1.ActivateStatError( "background1_statUncert", _inputFile); - background1.AddOverallSys( "syst2", 0.95, 1.05 ); - background1.AddOverallSys( "syst3", 0.99, 1.01 ); - _systNames.insert("alpha_syst2"); - _systNames.insert("alpha_syst3"); - chan.AddSample( background1 ); - - // Background 2 - Sample background2( "background2", "background2", _inputFile); - background2.ActivateStatError(); - background2.AddOverallSys( "syst3", 0.99, 1.01 ); - background2.AddOverallSys( "syst4", 0.95, 1.05 ); - _systNames.insert("alpha_syst3"); - _systNames.insert("alpha_syst4"); - chan.AddSample( background2 ); - - - // Done with this channel - // Add it to the measurement: - meas.AddChannel( chan ); - - if (!_verbose) { - RooMsgService::instance().getStream(1).minLevel = RooFit::PROGRESS; - RooMsgService::instance().getStream(2).minLevel = RooFit::WARNING; - } - RooHelpers::HijackMessageStream hijackW(RooFit::WARNING, RooFit::HistFactory); - - // Collect the histograms from their files, - meas.CollectHistograms(); - - // Now, create the measurement - ws.reset( MakeModelAndMeasurementFast(meas) ); - - EXPECT_TRUE(hijackW.str().empty()) << "Warnings logged for HistFactory:\n" << hijackW.str(); - } - - void TearDown() { - - } + RooHelpers::HijackMessageStream hijackW(RooFit::WARNING, RooFit::HistFactory); + + // Collect the histograms from their files, + meas.CollectHistograms(); + + // Now, create the measurement + ws = std::unique_ptr(MakeModelAndMeasurementFast(meas)); + + EXPECT_TRUE(hijackW.str().empty()) << "Warnings logged for HistFactory:\n" << hijackW.str(); + } + + void TearDown() {} }; +class HFFixtureEval : public HFFixture {}; + +class HFFixtureFit : public HFFixture {}; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Test that the model consists of what is expected -TEST_P(HFFixture, ModelProperties) { - auto simPdf = dynamic_cast(ws->pdf("simPdf")); - ASSERT_NE(simPdf, nullptr); - - auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); - ASSERT_NE(channelPdf, nullptr); - - auto obs = dynamic_cast(ws->var("obs_x_channel1")); - - // Nice to inspect the model if needed: - if (false) - channelPdf->graphVizTree((RooFit::tmpPath() + "graphVizTree.dot").c_str()); - - // Check bin widths - ASSERT_NE(obs, nullptr); - if (GetParam() % 2 == kEquidistantBins) { - EXPECT_DOUBLE_EQ(obs->getBinWidth(0), 0.5); - EXPECT_DOUBLE_EQ(obs->getBinWidth(1), 0.5); - EXPECT_EQ(obs->numBins(), 2); - } else if (GetParam() % 2 == kCustomBins) { - EXPECT_DOUBLE_EQ(obs->getBinWidth(0), _customBins[1] - _customBins[0]); - EXPECT_DOUBLE_EQ(obs->getBinWidth(1), _customBins[2] - _customBins[1]); - EXPECT_EQ(obs->numBins(), 2); - } - - RooStats::ModelConfig* mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); - - - // Check that parameters are in the model - for (const auto& systName : _systNames) { - auto& var = *ws->var(systName); - - EXPECT_TRUE(channelPdf->dependsOnValue(var)) << "Expect channel pdf to depend on " << systName; - if (!var.isConstant()) { - EXPECT_NE(mc->GetNuisanceParameters()->find(systName.c_str()), nullptr) << systName << " should be in list of nuisance parameters."; - } - } - - // Check that sub models depend on their systematic uncertainties. - for (auto& subModelName : std::initializer_list{"signal_channel1_shapes", "background1_channel1_shapes", "background2_channel1_shapes"}) { - auto subModel = ws->function(subModelName); - ASSERT_NE(subModel, nullptr) << "Unable to retrieve sub model with name " << subModelName; - if (subModelName.find("signal") != std::string::npos) { - EXPECT_FALSE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_0"))); - EXPECT_FALSE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_1"))); - } else { - EXPECT_TRUE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_0"))); - EXPECT_TRUE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_1"))); - } - } - - EXPECT_TRUE (ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); - EXPECT_TRUE (ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst1"))); - EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); - EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); - EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); - - EXPECT_FALSE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); - EXPECT_FALSE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst1"))); - EXPECT_TRUE (ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); - EXPECT_TRUE (ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); - EXPECT_FALSE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); - - EXPECT_FALSE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); - EXPECT_FALSE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst1"))); - EXPECT_FALSE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); - EXPECT_TRUE (ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); - EXPECT_TRUE (ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); - - EXPECT_EQ(*mc->GetParametersOfInterest()->begin(), ws->var("SigXsecOverSM")); -} +TEST_P(HFFixture, ModelProperties) +{ + const MakeModelMode makeModelMode = std::get<0>(GetParam()); + const bool customBins = std::get<1>(GetParam()); + + auto simPdf = dynamic_cast(ws->pdf("simPdf")); + ASSERT_NE(simPdf, nullptr); + + auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); + ASSERT_NE(channelPdf, nullptr); + + auto obs = dynamic_cast(ws->var("obs_x_channel1")); + + // Nice to inspect the model if needed: + // channelPdf->graphVizTree("graphVizTree.dot"); + + // Check bin widths + ASSERT_NE(obs, nullptr); + if (!customBins) { + EXPECT_DOUBLE_EQ(obs->getBinWidth(0), 0.5); + EXPECT_DOUBLE_EQ(obs->getBinWidth(1), 0.5); + EXPECT_EQ(obs->numBins(), 2); + } else { + EXPECT_DOUBLE_EQ(obs->getBinWidth(0), _customBins[1] - _customBins[0]); + EXPECT_DOUBLE_EQ(obs->getBinWidth(1), _customBins[2] - _customBins[1]); + EXPECT_EQ(obs->numBins(), 2); + } + + auto mc = dynamic_cast(ws->obj("ModelConfig")); + ASSERT_NE(mc, nullptr); + + // Check that parameters are in the model + for (const auto &systName : _systNames) { + auto &var = *ws->var(systName); + + EXPECT_TRUE(channelPdf->dependsOnValue(var)) << "Expect channel pdf to depend on " << systName; + if (!var.isConstant()) { + EXPECT_NE(mc->GetNuisanceParameters()->find(systName.c_str()), nullptr) + << systName << " should be in list of nuisance parameters."; + } + } + + // Check that sub models depend on their systematic uncertainties. + for (auto &subModelName : std::initializer_list{"signal_channel1_shapes", "background1_channel1_shapes", + "background2_channel1_shapes"}) { + auto subModel = ws->function(subModelName); + ASSERT_NE(subModel, nullptr) << "Unable to retrieve sub model with name " << subModelName; + if (subModelName.find("signal") != std::string::npos) { + EXPECT_FALSE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_0"))); + EXPECT_FALSE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_1"))); + } else { + EXPECT_TRUE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_0"))); + EXPECT_TRUE(subModel->dependsOn(*ws->var("gamma_stat_channel1_bin_1"))); + } + } + EXPECT_TRUE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); + EXPECT_FALSE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); + EXPECT_FALSE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("SigXsecOverSM"))); + + if (makeModelMode == MakeModelMode::OverallSyst) { + EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); + EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); + EXPECT_FALSE(ws->function("signal_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); + + EXPECT_TRUE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); + EXPECT_TRUE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); + EXPECT_FALSE(ws->function("background1_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); + + EXPECT_FALSE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst2"))); + EXPECT_TRUE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst3"))); + EXPECT_TRUE(ws->function("background2_channel1_scaleFactors")->dependsOn(*ws->var("alpha_syst4"))); + } + + EXPECT_EQ(*mc->GetParametersOfInterest()->begin(), ws->var("SigXsecOverSM")); +} /// Test that the values returned are as expected. -TEST_P(HFFixture, Evaluation) { - auto simPdf = dynamic_cast(ws->pdf("simPdf")); - ASSERT_NE(simPdf, nullptr); - - auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); - ASSERT_NE(channelPdf, nullptr); - - auto obs = dynamic_cast(ws->var("obs_x_channel1")); - - RooStats::ModelConfig* mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); - - // Test evaluating the model: - double normResults[2] = {0., 0.}; - for (unsigned int i=0; i < 2; ++i) { - obs->setBin(i); - EXPECT_NEAR(channelPdf->getVal(), - _targetNominal[i]/obs->getBinWidth(i), 1.E-9); - EXPECT_NEAR(channelPdf->getVal(mc->GetObservables()), - _targetNominal[i]/obs->getBinWidth(i)/(_targetNominal[0]+_targetNominal[1]), 1.E-9); - normResults[i] = channelPdf->getVal(mc->GetObservables()); - } - EXPECT_NEAR(normResults[0] * obs->getBinWidth(0) + normResults[1] * obs->getBinWidth(1), 1, 1.E-9) << "Integral over PDF range should be 1."; - - - // Test that shape uncertainties have an effect: - if (GetParam() >= kEquidistantBins_histoSyst) { - auto var = ws->var("alpha_SignalShape"); - ASSERT_NE(var, nullptr); - - // Test syst up: - var->setVal(1.); - for (unsigned int i=0; i < 2; ++i) { - obs->setBin(i); - EXPECT_NEAR(channelPdf->getVal(), - _targetSysUp[i]/obs->getBinWidth(i), 1.E-6); - EXPECT_NEAR(channelPdf->getVal(mc->GetObservables()), - _targetSysUp[i]/obs->getBinWidth(i)/(_targetSysUp[0]+_targetSysUp[1]), 1.E-6); - } - - // Test syst down: - var->setVal(-1.); - for (unsigned int i=0; i < 2; ++i) { - obs->setBin(i); - EXPECT_NEAR(channelPdf->getVal(), - _targetSysDo[i]/obs->getBinWidth(i), 1.E-6); - EXPECT_NEAR(channelPdf->getVal(mc->GetObservables()), - _targetSysDo[i]/obs->getBinWidth(i)/(_targetSysDo[0]+_targetSysDo[1]), 1.E-6); - } - } +TEST_P(HFFixtureEval, Evaluation) +{ + const double defaultEps = 1e-9; + const double systEps = 1e-6; + + const MakeModelMode makeModelMode = std::get<0>(GetParam()); + const bool useBatchMode = std::get<2>(GetParam()) != RooFit::EvalBackend::Legacy(); + + RooHelpers::HijackMessageStream evalMessages(RooFit::INFO, RooFit::FastEvaluations); + + auto simPdf = dynamic_cast(ws->pdf("simPdf")); + ASSERT_NE(simPdf, nullptr); + + auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); + ASSERT_NE(channelPdf, nullptr); + + auto obs = dynamic_cast(ws->var("obs_x_channel1")); + + auto mc = dynamic_cast(ws->obj("ModelConfig")); + ASSERT_NE(mc, nullptr); + + // Test evaluating the model: + std::vector normResults = getValues(*channelPdf, *obs, true, useBatchMode); + std::vector unnormResults = getValues(*channelPdf, *obs, false, useBatchMode); + + for (int i = 0; i < obs->numBins(); ++i) { + EXPECT_NEAR(unnormResults[i], _tgtNom[i] / obs->getBinWidth(i), defaultEps); + EXPECT_NEAR(normResults[i], _tgtNom[i] / obs->getBinWidth(i) / (_tgtNom[0] + _tgtNom[1]), defaultEps); + } + EXPECT_NEAR(normResults[0] * obs->getBinWidth(0) + normResults[1] * obs->getBinWidth(1), 1, defaultEps) + << "Integral over PDF range should be 1."; + + // Test that shape uncertainties have an effect: + if (makeModelMode == MakeModelMode::HistoSyst) { + auto var = ws->var("alpha_SignalShape"); + ASSERT_NE(var, nullptr); + + // Test syst up: + var->setVal(1.); + std::vector normResultsSyst = getValues(*channelPdf, *obs, true, useBatchMode); + std::vector unnormResultsSyst = getValues(*channelPdf, *obs, false, useBatchMode); + for (int i = 0; i < obs->numBins(); ++i) { + EXPECT_NEAR(unnormResultsSyst[i], _tgtSysUp[i] / obs->getBinWidth(i), systEps); + EXPECT_NEAR(normResultsSyst[i], _tgtSysUp[i] / obs->getBinWidth(i) / (_tgtSysUp[0] + _tgtSysUp[1]), systEps); + } + + // Test syst down: + var->setVal(-1.); + normResultsSyst = getValues(*channelPdf, *obs, true, useBatchMode); + unnormResultsSyst = getValues(*channelPdf, *obs, false, useBatchMode); + for (int i = 0; i < obs->numBins(); ++i) { + EXPECT_NEAR(unnormResultsSyst[i], _tgtSysDo[i] / obs->getBinWidth(i), systEps); + EXPECT_NEAR(normResultsSyst[i], _tgtSysDo[i] / obs->getBinWidth(i) / (_tgtSysDo[0] + _tgtSysDo[1]), systEps); + } + } + + EXPECT_TRUE(evalMessages.str().empty()) << "RooFit issued " << evalMessages.str().substr(0, 1000) << " [...]"; +} + +void setInitialFitParameters(RooWorkspace &ws, MakeModelMode makeModelMode) +{ + if (makeModelMode == MakeModelMode::OverallSyst) { + // The final parameters of alpha_syst2 and alpha_syst4 are very close to the + // pre-fit value zero. For the fit to converge reliably, the pre-fit values + // are set away from the minimum. + ws.var("alpha_syst2")->setVal(1.0); + ws.var("alpha_syst4")->setVal(-1.0); + } + if (makeModelMode == MakeModelMode::ShapeSyst) { + ws.var("gamma_background1Shape_bin_0")->setVal(0.7); + ws.var("gamma_background2Shape_bin_1")->setVal(1.3); + } } +TEST_P(HFFixture, HistFactoryJSONTool) +{ + const MakeModelMode makeModelMode = std::get<0>(GetParam()); -/// Test that the values returned are as expected. -TEST_P(HFFixture, BatchEvaluation) { - RooHelpers::HijackMessageStream evalMessages(RooFit::INFO, RooFit::FastEvaluations); - - auto simPdf = dynamic_cast(ws->pdf("simPdf")); - ASSERT_NE(simPdf, nullptr); - - auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); - ASSERT_NE(channelPdf, nullptr); - - auto obs = dynamic_cast(ws->var("obs_x_channel1")); - - RooStats::ModelConfig* mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); - - // Test evaluating the model: - RooBatchCompute::RunContext evalDataOrig; - auto batch = evalDataOrig.makeBatch(obs, 2); - obs->setBin(0); - batch[0] = obs->getVal(); - obs->setBin(1); - batch[1] = obs->getVal(); - - RooBatchCompute::RunContext evalData1; - evalData1.spans = evalDataOrig.spans; - auto results = channelPdf->getValues(evalData1, nullptr); - RooBatchCompute::RunContext evalData2; - evalData2.spans = evalDataOrig.spans; - auto normResults = channelPdf->getValues(evalData2, mc->GetObservables()); - - for (unsigned int i=0; i < 2; ++i) { - obs->setBin(i); - EXPECT_NEAR(results[i], - _targetNominal[i]/obs->getBinWidth(i), 1.E-9); - EXPECT_NEAR(normResults[i], - _targetNominal[i]/obs->getBinWidth(i)/(_targetNominal[0]+_targetNominal[1]), 1.E-9); - } - EXPECT_NEAR(normResults[0] * obs->getBinWidth(0) + normResults[1] * obs->getBinWidth(1), 1, 1.E-9) << "Integral over PDF range should be 1."; - - - // Test that shape uncertainties have an effect: - if (GetParam() >= kEquidistantBins_histoSyst) { - auto var = ws->var("alpha_SignalShape"); - ASSERT_NE(var, nullptr); - - // Test syst up: - var->setVal(1.); - RooBatchCompute::RunContext evalData3; - evalData3.spans = evalDataOrig.spans; - auto resultsSyst = channelPdf->getValues(evalData3, nullptr); - RooBatchCompute::RunContext evalData4; - evalData4.spans = evalDataOrig.spans; - auto normResultsSyst = channelPdf->getValues(evalData4, mc->GetObservables()); - for (unsigned int i=0; i < 2; ++i) { - EXPECT_NEAR(resultsSyst[i], - _targetSysUp[i]/obs->getBinWidth(i), 1.E-6); - EXPECT_NEAR(normResultsSyst[i], - _targetSysUp[i]/obs->getBinWidth(i)/(_targetSysUp[0]+_targetSysUp[1]), 1.E-6); - } - - // Test syst down: - var->setVal(-1.); - RooBatchCompute::RunContext evalData5; - evalData5.spans = evalDataOrig.spans; - resultsSyst = channelPdf->getValues(evalData5, nullptr); - RooBatchCompute::RunContext evalData6; - evalData6.spans = evalDataOrig.spans; - normResultsSyst = channelPdf->getValues(evalData6, mc->GetObservables()); - for (unsigned int i=0; i < 2; ++i) { - obs->setBin(i); - EXPECT_NEAR(resultsSyst[i], - _targetSysDo[i]/obs->getBinWidth(i), 1.E-6); - EXPECT_NEAR(normResultsSyst[i], - _targetSysDo[i]/obs->getBinWidth(i)/(_targetSysDo[0]+_targetSysDo[1]), 1.E-6); - } - } - - EXPECT_TRUE(evalMessages.str().empty()) << "RooFit issued " << evalMessages.str().substr(0, 1000) << " [...]"; + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + if (writeJsonFiles) { + RooStats::HistFactory::JSONTool{*_measurement}.PrintJSON(_name + "_1.json"); + } + std::stringstream ss; + RooStats::HistFactory::JSONTool{*_measurement}.PrintJSON(ss); + + RooWorkspace wsFromJson{"ws1"}; + RooJSONFactoryWSTool{wsFromJson}.importJSONfromString(ss.str()); + + auto *mc = dynamic_cast(ws->obj("ModelConfig")); + EXPECT_TRUE(mc != nullptr); + + auto *mcFromJson = dynamic_cast(wsFromJson.obj("ModelConfig")); + EXPECT_TRUE(mcFromJson != nullptr); + + RooAbsPdf *pdf = mc->GetPdf(); + EXPECT_TRUE(pdf != nullptr); + + RooAbsPdf *pdfFromJson = mcFromJson->GetPdf(); + EXPECT_TRUE(pdfFromJson != nullptr); + + RooAbsData *data = ws->data("obsData"); + EXPECT_TRUE(data != nullptr); + + RooAbsData *dataFromJson = wsFromJson.data("obsData"); + EXPECT_TRUE(dataFromJson != nullptr); + + RooArgSet const &globs = *mc->GetGlobalObservables(); + RooArgSet const &globsFromJson = *mcFromJson->GetGlobalObservables(); + + setInitialFitParameters(*ws, makeModelMode); + setInitialFitParameters(wsFromJson, makeModelMode); + + using namespace RooFit; + using Res = std::unique_ptr; + + Res result{pdf->fitTo(*data, Strategy(1), Minos(*mc->GetParametersOfInterest()), GlobalObservables(globs), + PrintLevel(-1), Save())}; + + Res resultFromJson{pdfFromJson->fitTo(*dataFromJson, Strategy(1), Minos(*mcFromJson->GetParametersOfInterest()), + GlobalObservables(globsFromJson), PrintLevel(-1), Save())}; + + // Do also the reverse comparison to check that the set of constant parameters matches + EXPECT_TRUE(result->isIdentical(*resultFromJson)); + EXPECT_TRUE(resultFromJson->isIdentical(*result)); } +TEST_P(HFFixture, HS3ClosureLoop) +{ + const MakeModelMode makeModelMode = std::get<0>(GetParam()); + + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + auto *mc = dynamic_cast(ws->obj("ModelConfig")); + EXPECT_TRUE(mc != nullptr); + + RooAbsPdf *pdf = mc->GetPdf(); + EXPECT_TRUE(pdf != nullptr); + + std::string const &js = RooJSONFactoryWSTool{*ws}.exportJSONtoString(); + if (writeJsonFiles) { + RooJSONFactoryWSTool{*ws}.exportJSON(_name + "_2.json"); + } + + RooWorkspace wsFromJson("new"); + RooJSONFactoryWSTool newtool{wsFromJson}; + newtool.importJSONfromString(js); + + std::string const &js3 = RooJSONFactoryWSTool{wsFromJson}.exportJSONtoString(); + + if (writeJsonFiles) { + RooJSONFactoryWSTool{wsFromJson}.exportJSON(_name + "_3.json"); + } + + // Chack that JSON > WS > JSON doesn't change the JSON + EXPECT_EQ(js, js3) << "The JSON -> WS -> JSON roundtrip did not result in the original JSON!"; + + auto *newmc = dynamic_cast(wsFromJson.obj("ModelConfig")); + EXPECT_TRUE(newmc != nullptr); + + RooAbsPdf *newpdf = newmc->GetPdf(); + EXPECT_TRUE(newpdf != nullptr); + + RooAbsData *data = ws->data("obsData"); + EXPECT_TRUE(data != nullptr); + + RooAbsData *newdata = wsFromJson.data("obsData"); + EXPECT_TRUE(newdata != nullptr); + + RooArgSet const &globs = *mc->GetGlobalObservables(); + RooArgSet const &globsFromJson = *newmc->GetGlobalObservables(); + + setInitialFitParameters(*ws, makeModelMode); + setInitialFitParameters(wsFromJson, makeModelMode); + + using namespace RooFit; + using Res = std::unique_ptr; + + Res result{pdf->fitTo(*data, Strategy(1), Minos(*mc->GetParametersOfInterest()), GlobalObservables(globs), + PrintLevel(-1), Save())}; + + Res resultFromJson{newpdf->fitTo(*newdata, Strategy(1), Minos(*newmc->GetParametersOfInterest()), + GlobalObservables(globsFromJson), PrintLevel(-1), Save())}; + + // Do also the reverse comparison to check that the set of constant parameters matches + EXPECT_TRUE(result->isIdentical(*resultFromJson)); + EXPECT_TRUE(resultFromJson->isIdentical(*result)); +} /// Fit the model to data, and check parameters. -TEST_P(HFFixture, Fit) { - constexpr bool createPlot = false; - constexpr bool verbose = false; +TEST_P(HFFixtureFit, Fit) +{ + const MakeModelMode makeModelMode = std::get<0>(GetParam()); + RooFit::EvalBackend evalBackend = std::get<2>(GetParam()); - auto simPdf = dynamic_cast(ws->pdf("simPdf")); - ASSERT_NE(simPdf, nullptr); + constexpr bool verbose = false; - auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); - ASSERT_NE(channelPdf, nullptr); + auto simPdf = dynamic_cast(ws->pdf("simPdf")); + ASSERT_NE(simPdf, nullptr); - // Test fitting the model to data - RooAbsData* data = dynamic_cast(ws->data("obsData")); - ASSERT_NE(data, nullptr); + auto channelPdf = dynamic_cast(ws->pdf("channel1_model")); + ASSERT_NE(channelPdf, nullptr); - RooStats::ModelConfig* mc = dynamic_cast(ws->obj("ModelConfig")); - ASSERT_NE(mc, nullptr); + // Test fitting the model to data + RooAbsData *data = dynamic_cast(ws->data("obsData")); + ASSERT_NE(data, nullptr); - for (bool batchFit : {true, false}) { - for (bool constTermOptimisation : {true, false}) { // This tests both correct pre-caching of constant terms and (if false) that all evaluateSpan() are correct. - SCOPED_TRACE(batchFit ? "Batch fit" : "Normal fit"); - SCOPED_TRACE(constTermOptimisation ? "const term optimisation" : "No const term optimisation"); + auto mc = dynamic_cast(ws->obj("ModelConfig")); + ASSERT_NE(mc, nullptr); + + // This tests both correct pre-caching of constant terms and (if false) that all computeBatch() are correct. + for (bool constTermOptimization : {true, false}) { + + // constTermOptimization makes only sense in the legacy backend + if (constTermOptimization && evalBackend != RooFit::EvalBackend::Legacy()) { + continue; + } + SCOPED_TRACE(constTermOptimization ? "const term optimisation" : "No const term optimisation"); // Stop if one of the previous runs had a failure to keep the terminal clean. if (HasFailure()) - break; + break; - std::unique_ptr pars( simPdf->getParameters(*data) ); + std::unique_ptr pars(simPdf->getParameters(*data)); // Kick parameters: for (auto par : *pars) { - auto real = dynamic_cast(par); - if (real && !real->isConstant()) - real->setVal(real->getVal() * 0.95); + auto real = dynamic_cast(par); + if (real && !real->isConstant()) + real->setVal(real->getVal() * 0.95); } - if (GetParam() >= kEquidistantBins_statSyst) { - auto poi = dynamic_cast(pars->find("SigXsecOverSM")); - ASSERT_NE(poi, nullptr); - poi->setVal(2.); - poi->setConstant(); + if (makeModelMode == MakeModelMode::StatSyst) { + auto poi = dynamic_cast(pars->find("SigXsecOverSM")); + ASSERT_NE(poi, nullptr); + poi->setVal(2.); + poi->setConstant(); } - auto fitResult = simPdf->fitTo(*data, - RooFit::BatchMode(batchFit), - RooFit::Optimize(constTermOptimisation), - RooFit::GlobalObservables(*mc->GetGlobalObservables()), - RooFit::Save(), - RooFit::PrintLevel(verbose ? 1 : -1)); + using namespace RooFit; + std::unique_ptr fitResult{simPdf->fitTo(*data, evalBackend, Optimize(constTermOptimization), + GlobalObservables(*mc->GetGlobalObservables()), Save(), + PrintLevel(verbose ? 1 : -1))}; ASSERT_NE(fitResult, nullptr); if (verbose) - fitResult->Print(); + fitResult->Print("v"); EXPECT_EQ(fitResult->status(), 0); - - auto checkParam = [fitResult](const std::string& param, double target, double absPrecision) { - auto par = dynamic_cast(fitResult->floatParsFinal().find(param.c_str())); - if (!par) { - // Parameter was constant in this fit - par = dynamic_cast(fitResult->constPars().find(param.c_str())); - ASSERT_NE(par, nullptr); - EXPECT_DOUBLE_EQ(par->getVal(), target) << "Constant parameter " << param << " is off target."; - } else { - EXPECT_NEAR(par->getVal(), target, par->getError()) << "Parameter " << param << " close to target " << target << " within uncertainty"; - EXPECT_NEAR(par->getVal(), target, absPrecision) << "Parameter " << param << " close to target " << target; - } + auto checkParam = [&](const std::string ¶m, double target, double absPrecision = 1.e-2) { + auto par = dynamic_cast(fitResult->floatParsFinal().find(param.c_str())); + if (!par) { + // Parameter was constant in this fit + par = dynamic_cast(fitResult->constPars().find(param.c_str())); + if (evalBackend != RooFit::EvalBackend::Codegen()) { + ASSERT_NE(par, nullptr) << param; + EXPECT_DOUBLE_EQ(par->getVal(), target) << "Constant parameter " << param << " is off target."; + } else { + // We expect "codegen" to strip away constant RooRealVars + ASSERT_EQ(par, nullptr) << param; + } + } else { + EXPECT_NEAR(par->getVal(), target, par->getError()) + << "Parameter " << param << " close to target " << target << " within uncertainty"; + EXPECT_NEAR(par->getVal(), target, absPrecision) << "Parameter " << param << " close to target " << target; + } }; - if (GetParam() <= kCustomBins) { - // Model is set up such that background scale factors should be close to 1, and signal == 2 - checkParam("SigXsecOverSM", 2., 1.E-2); - checkParam("alpha_syst2", 0., 1.E-2); - checkParam("alpha_syst3", 0., 1.E-2); - checkParam("alpha_syst4", 0., 1.E-2); - checkParam("gamma_stat_channel1_bin_0", 1., 1.E-2); - checkParam("gamma_stat_channel1_bin_1", 1., 1.E-2); - } else if (GetParam() <= kCustomBins_histoSyst) { - // Model is set up with a -1 sigma pull on the signal shape parameter. - checkParam("SigXsecOverSM", 2., 1.E-1); // Higher tolerance: Expect a pull due to shape syst. - checkParam("alpha_syst2", 0., 1.E-2); - checkParam("alpha_syst3", 0., 3.E-2); // Micro pull due to shape syst. - checkParam("alpha_syst4", 0., 1.E-2); - checkParam("gamma_stat_channel1_bin_0", 1., 1.E-2); - checkParam("gamma_stat_channel1_bin_1", 1., 1.E-2); - checkParam("alpha_SignalShape", -0.9, 5.E-2); // Pull slightly lower than 1 because of constraint term - } else if (GetParam() <= kCustomBins_statSyst) { - // Model is set up with a -1 sigma pull on the signal shape parameter. - checkParam("SigXsecOverSM", 2., 1.E-1); // Higher tolerance: Expect a pull due to shape syst. - checkParam("alpha_syst2", 0., 1.E-2); - checkParam("alpha_syst3", 0., 1.E-2); - checkParam("alpha_syst4", 0., 1.E-2); - checkParam("gamma_stat_channel1_bin_0", 1.09, 1.E-2); // This should be pulled - checkParam("gamma_stat_channel1_bin_1", 1., 1.E-2); - checkParam("alpha_SignalShape", 0., 1.E-2); + if (makeModelMode == MakeModelMode::OverallSyst) { + // Model is set up such that background scale factors should be close to 1, and signal == 2 + checkParam("SigXsecOverSM", 2.); + checkParam("alpha_syst2", 0.); + checkParam("alpha_syst3", 0.); + checkParam("alpha_syst4", 0.); + checkParam("gamma_stat_channel1_bin_0", 1.); + checkParam("gamma_stat_channel1_bin_1", 1.); + } else if (makeModelMode == MakeModelMode::HistoSyst) { + // Model is set up with a -1 sigma pull on the signal shape parameter. + checkParam("SigXsecOverSM", 2., 1.1E-1); // Higher tolerance: Expect a pull due to shape syst. + checkParam("gamma_stat_channel1_bin_0", 1.); + checkParam("gamma_stat_channel1_bin_1", 1.); + checkParam("alpha_SignalShape", -0.9, 5.E-2); // Pull slightly lower than 1 because of constraint term + } else if (makeModelMode == MakeModelMode::StatSyst) { + // Model is set up with a -1 sigma pull on the signal shape parameter. + checkParam("SigXsecOverSM", 2., 1.1E-1); // Higher tolerance: Expect a pull due to shape syst. + checkParam("gamma_stat_channel1_bin_0", 1.09); // This should be pulled + checkParam("gamma_stat_channel1_bin_1", 1.); + } else if (makeModelMode == MakeModelMode::ShapeSyst) { + // This should be pulled down + checkParam("gamma_background1Shape_bin_0", 0.8866, 0.03); + // This should be pulled up, but not so much because the free signal + // strength will fit the excess in this bin. + checkParam("gamma_background2Shape_bin_1", 1.0250, 0.03); } - } - } - - - if (createPlot) { - auto obs = dynamic_cast(ws->var("obs_x_channel1")); - auto frame = obs->frame(); - data->plotOn(frame); - channelPdf->plotOn(frame); - channelPdf->plotOn(frame, RooFit::Components("signal_channel1_shapes"), RooFit::LineColor(kRed)); - TCanvas canv; - frame->Draw(); - canv.Draw(); - canv.SaveAs((RooFit::tmpPath() + "HFTest" + std::to_string(GetParam()) + ".png").c_str()); - - channelPdf->graphVizTree((RooFit::tmpPath() + "HFTest" + std::to_string(GetParam()) + ".dot").c_str()); - } + } + + if (false) { + auto obs = dynamic_cast(ws->var("obs_x_channel1")); + auto frame = obs->frame(); + data->plotOn(frame); + channelPdf->plotOn(frame); + channelPdf->plotOn(frame, RooFit::Components("signal_channel1_shapes"), RooFit::LineColor(kRed)); + TCanvas canv; + frame->Draw(); + canv.Draw(); + canv.SaveAs(("HFTest" + _name + ".png").c_str()); + + channelPdf->graphVizTree(("HFTest" + _name + ".dot").c_str()); + } } +std::string getNameFromInfo(testing::TestParamInfo const ¶mInfo) +{ + return getName(paramInfo.param); +} -INSTANTIATE_TEST_SUITE_P(MakeModelWithNormSysts, - HFFixture, - testing::Values(kEquidistantBins, kCustomBins)); - -INSTANTIATE_TEST_SUITE_P(MakeModelWithHistoSysts, - HFFixture, - testing::Values(kEquidistantBins_histoSyst, kCustomBins_histoSyst)); - -INSTANTIATE_TEST_SUITE_P(MakeModelWithHistoAndStatSysts, - HFFixture, - testing::Values(kEquidistantBins_statSyst, kCustomBins_statSyst)); - +INSTANTIATE_TEST_SUITE_P(HistFactory, HFFixture, + testing::Combine(testing::Values(MakeModelMode::OverallSyst, MakeModelMode::HistoSyst, + MakeModelMode::StatSyst, MakeModelMode::ShapeSyst), + testing::Values(false, true), // non-uniform bins or not + testing::Values(RooFit::EvalBackend::Legacy())), + getNameFromInfo); + +INSTANTIATE_TEST_SUITE_P(HistFactory, HFFixtureEval, + testing::Combine(testing::Values(MakeModelMode::OverallSyst, MakeModelMode::HistoSyst, + MakeModelMode::StatSyst, MakeModelMode::ShapeSyst), + testing::Values(false, true), // non-uniform bins or not + testing::Values(RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu())), + getNameFromInfo); + +INSTANTIATE_TEST_SUITE_P(HistFactory, HFFixtureFit, + testing::Combine(testing::Values(MakeModelMode::OverallSyst, MakeModelMode::HistoSyst, + MakeModelMode::StatSyst, MakeModelMode::ShapeSyst), + testing::Values(false, true), // non-uniform bins or not + testing::Values(RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu())), + getNameFromInfo); + +#ifdef TEST_CODEGEN_AD +// TODO: merge with the previous HFFixtureFix test suite once the codegen AD +// supports all of HistFactory +INSTANTIATE_TEST_SUITE_P(HistFactoryCodeGen, HFFixtureFit, + testing::Combine(testing::Values(MakeModelMode::OverallSyst, MakeModelMode::HistoSyst, + MakeModelMode::StatSyst, MakeModelMode::ShapeSyst), + testing::Values(false), // no non-uniform bins + testing::Values(RooFit::EvalBackend::Codegen())), + getNameFromInfo); +#endif diff --git a/roofit/histfactory/test/testHistFactoryPlotting.cxx b/roofit/histfactory/test/testHistFactoryPlotting.cxx new file mode 100644 index 0000000000000..b8527c4cefbaa --- /dev/null +++ b/roofit/histfactory/test/testHistFactoryPlotting.cxx @@ -0,0 +1,177 @@ +// Tests for the ParamHistFunc +// Authors: Jonas Rembser, CERN 08/2023 + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +void createToyHistos1D() +{ + // Save histograms in this root file + std::unique_ptr histoFile{TFile::Open("histoFile.root", "RECREATE")}; + + // Set number of events in signal and background (N_Sig = N_BG = N_DATA/2) + int nEvents = 10000; + + // Functions used to fill histograms + TF1 func1{"func1", "1 + 0.01 * x", 3000, 6000}; // background + TF1 func2{"func2", "0.2 * exp(-( (x-4000.)*(x-4000.)/(2.0*200.*200.) ) )", 3000, 6000}; // signal + + // Histograms + TH1D *histoBG = new TH1D("histoBG", "background histo", 15, 3000, 6000); + TH1D *histoSig = new TH1D("histoSig", "signal histo", 15, 3000, 6000); + TH1D *histoData = new TH1D("histoData", "data histo", 15, 3000, 6000); + + // define observable x + double x_bg; // background + double x_sig; // signal + + // Fill background and signal histograms + for (int i = 0; i < nEvents; ++i) { + x_bg = func1.GetRandom(); + x_sig = func2.GetRandom(); + histoBG->Fill(x_bg); + histoSig->Fill(x_sig); + } + + // Fill data histogram + for (int i = 0; i < nEvents; ++i) { + x_bg = func1.GetRandom(); + histoData->Fill(x_bg); + x_sig = func2.GetRandom(); + histoData->Fill(x_sig); + } + + histoFile->Write(); +} + +/// Test that plotting HistFactory components works correctly. Covers the +/// problem reported in this forum post: +/// https://root-forum.cern.ch/t/problems-plotting-individual-components-with-roofit-histfactory +TEST(HistFactoryPlotting, ComponentSelection) +{ + RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING}; + + using namespace RooFit; + + // Make histograms + createToyHistos1D(); + + // -------------------------------------- + // Load histograms + // -------------------------------------- + + // file with histograms + std::string histoFileName = "histoFile.root"; + + // load histograms + std::unique_ptr histoFile{TFile::Open(histoFileName.c_str(), "READ")}; + std::vector templateHistos; + templateHistos.emplace_back(histoFile->Get("histoSig")); + templateHistos.emplace_back(histoFile->Get("histoBG")); + + // -------------------------------------- + // Setup measurement & channel + // -------------------------------------- + + // -- Define the measurement + RooStats::HistFactory::Measurement meas("B2D0MuNu", "B2D0MuNu fit"); + + meas.SetExportOnly(true); // Tells histfactory to not run the fit + meas.SetPOI("num_histoSig"); // set to Bogus parma. of interest + meas.SetLumi(1.0); + meas.SetLumiRelErr(0.1); + + // -- Define the channel (in our case, there is only one) + RooStats::HistFactory::Channel B2D0MuNu("BMCorr"); + B2D0MuNu.SetData("histoData", "histoFile.root"); + + // -- Add the histograms to the channel + for (auto const &histo : templateHistos) { + + RooStats::HistFactory::Sample sample(histo->GetName(), histo->GetName(), histoFileName); + + sample.SetNormalizeByTheory(false); + // fix normalisation + sample.AddNormFactor("norm_" + std::string{histo->GetName()}, 1 / histo->Integral(), 1 / histo->Integral(), + 1 / histo->Integral()); + // free yield + sample.AddNormFactor("num_" + std::string{histo->GetName()}, histo->Integral(), 1.0, histo->Integral() * 2); + + // add histograms to channel + B2D0MuNu.AddSample(sample); + } + + // add channel to measurements + meas.AddChannel(B2D0MuNu); + meas.SetExportOnly(true); + meas.CollectHistograms(); + + // -------------------------------------- + // Setting up workspace + // -------------------------------------- + + // -- Define workspace + std::unique_ptr ws{RooStats::HistFactory::MakeModelAndMeasurementFast(meas)}; + + // Get model manually + auto *modelConf = static_cast(ws->obj("ModelConfig")); + auto *model = static_cast(modelConf->GetPdf()); + + // fix the Lumi to not have it also fitted + RooArgSet const *nuis = modelConf->GetNuisanceParameters(); + (static_cast(nuis->find("Lumi")))->setConstant(true); + (static_cast(nuis->find("norm_histoSig")))->setConstant(true); // fix norm + (static_cast(nuis->find("norm_histoBG")))->setConstant(true); // fix norm + + auto *obs = static_cast(modelConf->GetObservables()); + auto *idx = static_cast(obs->find("channelCat")); + RooAbsData *data = ws->data("obsData"); + auto *obs_x = static_cast(obs->find("obs_x_BMCorr")); + + // plot data, total pdf and individual components + std::unique_ptr frame{obs_x->frame()}; + data->plotOn(frame.get(), DataError(RooAbsData::Poisson), MarkerSize(0.4), DrawOption("ZP"), Name("pdf_Data")); + model->plotOn(frame.get(), ProjWData(*idx, *data), Name("pdf_model"), LineColor(kGreen)); + model->plotOn(frame.get(), ProjWData(*idx, *data), Name("pdf_sig"), Components("*histoSig*"), LineColor(kBlue)); + model->plotOn(frame.get(), ProjWData(*idx, *data), Name("pdf_bg"), Components("*histoBG*"), LineColor(kRed)); + + auto *curveFull = static_cast(frame->findObject("pdf_model")); + auto *curgeSig = static_cast(frame->findObject("pdf_sig")); + auto *curgeBg = static_cast(frame->findObject("pdf_bg")); + + for (int i = 0; i < curveFull->GetN(); ++i) { + double x1, x2, x3; + double y1, y2, y3; + curveFull->GetPoint(i, x1, y1); + curgeSig->GetPoint(i, x2, y2); + curgeBg->GetPoint(i, x3, y3); + // The points for the components should add up to the points of the full model. + EXPECT_DOUBLE_EQ(y2 + y3, y1); + } + + constexpr bool makePlot = false; + + if (makePlot) { + gROOT->SetBatch(true); + TCanvas c1{}; + frame->Draw(); + c1.SaveAs("hf_component_plot.png"); + } +} diff --git a/roofit/histfactory/test/testParamHistFunc.cxx b/roofit/histfactory/test/testParamHistFunc.cxx index 891f27f218ad0..9e4a93eae9d91 100644 --- a/roofit/histfactory/test/testParamHistFunc.cxx +++ b/roofit/histfactory/test/testParamHistFunc.cxx @@ -8,8 +8,13 @@ #include #include #include +#include +#include + +#include "../src/RooFit/BatchModeDataHelpers.h" #include +#include /// Validate the ParamHistFunc in the n-dimensional case, comparing both the /// BatchMode and the old implementation results to a manually-compute @@ -51,7 +56,7 @@ TEST(ParamHistFunc, ValidateND) std::vector resultsScalar(nEntries); // Do some things in one go: - // * assing random integer values to each variable in each iteration + // * assign random integer values to each variable in each iteration // * fill the dataset used for batched evaluation // * compute the reference result manually // * compute the result with the ParamHistFunc without BatchMode @@ -66,7 +71,15 @@ TEST(ParamHistFunc, ValidateND) } // Get the results in BatchMode using the dataset - auto resultsBatch = paramHistFunc.getValues(data); + std::unique_ptr clone = RooFit::Detail::compileForNormSet(paramHistFunc, *data.get()); + RooFit::Evaluator evaluator(*clone); + std::stack> vectorBuffers; + auto dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(data, "", nullptr, /*skipZeroWeights=*/true, + /*takeGlobalObservablesFromData=*/false, vectorBuffers); + for (auto const &item : dataSpans) { + evaluator.setInput(item.first->GetName(), item.second, false); + } + std::span resultsBatch = evaluator.run(); // Validate the results for (std::size_t i = 0; i < nEntries; ++i) { diff --git a/roofit/hs3/CMakeLists.txt b/roofit/hs3/CMakeLists.txt index f4309e0705c1f..89881ed10ca8d 100644 --- a/roofit/hs3/CMakeLists.txt +++ b/roofit/hs3/CMakeLists.txt @@ -15,19 +15,21 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitHS3 RooFitHS3/RooJSONFactoryWSTool.h RooFitHS3/HistFactoryJSONTool.h SOURCES + src/Domains.cxx src/JSONIO.cxx src/RooJSONFactoryWSTool.cxx src/HistFactoryJSONTool.cxx src/JSONFactories_RooFitCore.cxx src/JSONFactories_HistFactory.cxx + src/JSONIOUtils.cxx DICTIONARY_OPTIONS "-writeEmptyRootPCM" + DEPENDENCIES + RooFitCore + RooFitJSONInterface LIBRARIES RooFit - RooFitCore - RooStats HistFactory - RooFitJSONInterface ) ROOT_ADD_TEST_SUBDIRECTORY(test) diff --git a/roofit/hs3/README.md b/roofit/hs3/README.md index 8d5cffdefe518..e601744fea0bb 100644 --- a/roofit/hs3/README.md +++ b/roofit/hs3/README.md @@ -144,7 +144,7 @@ Any importer should take the following form: int member2(p[""].val_int()); MyClass theobj(name.c_str(), member1, member2); - tool->workspace()->import(theobj, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsImport(theobj); return true; } }; diff --git a/roofit/hs3/inc/RooFitHS3/HistFactoryJSONTool.h b/roofit/hs3/inc/RooFitHS3/HistFactoryJSONTool.h index 1c543184474e3..c417389216e91 100644 --- a/roofit/hs3/inc/RooFitHS3/HistFactoryJSONTool.h +++ b/roofit/hs3/inc/RooFitHS3/HistFactoryJSONTool.h @@ -16,6 +16,12 @@ #include #include +namespace RooFit { +namespace Detail { +class JSONNode; +} // namespace Detail +} // namespace RooFit + namespace RooStats { namespace HistFactory { @@ -30,6 +36,8 @@ class JSONTool { void PrintYAML(std::ostream &os = std::cout); void PrintYAML(std::string const &filename); + static void activateStatError(RooFit::Detail::JSONNode &sampleNode); + private: RooStats::HistFactory::Measurement &_measurement; }; diff --git a/roofit/hs3/inc/RooFitHS3/JSONIO.h b/roofit/hs3/inc/RooFitHS3/JSONIO.h index 7a1ef90103ddd..e787f5e7cfe67 100644 --- a/roofit/hs3/inc/RooFitHS3/JSONIO.h +++ b/roofit/hs3/inc/RooFitHS3/JSONIO.h @@ -33,9 +33,24 @@ namespace JSONIO { class Importer { public: - virtual bool importPdf(RooJSONFactoryWSTool *, const RooFit::Detail::JSONNode &) const { return false; } - virtual bool importFunction(RooJSONFactoryWSTool *, const RooFit::Detail::JSONNode &) const { return false; } virtual ~Importer() {} + virtual bool importArg(RooJSONFactoryWSTool *tool, const RooFit::Detail::JSONNode &node) const + { + return importFunction(tool, node); + } + // These two functions importPdf() and importFunction() are supposed to get + // deprecated at some point, and get superseded by the general importArg(). + // The reason for having these functions call each other in a loop by + // default is backwards compatibility: no matter which function is + // overridden, it will be called eventually. + virtual bool importFunction(RooJSONFactoryWSTool *tool, const RooFit::Detail::JSONNode &node) const + { + return importPdf(tool, node); + } + virtual bool importPdf(RooJSONFactoryWSTool *tool, const RooFit::Detail::JSONNode &node) const + { + return importArg(tool, node); + } }; class Exporter { public: @@ -61,10 +76,10 @@ using ExportMap = std::map; using ImportExpressionMap = std::map; +void setupKeys(); ImportMap &importers(); ExportMap &exporters(); -ImportExpressionMap &pdfImportExpressions(); -ImportExpressionMap &functionImportExpressions(); +ImportExpressionMap &importExpressions(); ExportKeysMap &exportKeys(); template diff --git a/roofit/hs3/inc/RooFitHS3/RooJSONFactoryWSTool.h b/roofit/hs3/inc/RooFitHS3/RooJSONFactoryWSTool.h index 079535dd50245..fa40c64c0408c 100644 --- a/roofit/hs3/inc/RooFitHS3/RooJSONFactoryWSTool.h +++ b/roofit/hs3/inc/RooFitHS3/RooJSONFactoryWSTool.h @@ -13,95 +13,119 @@ #ifndef RooFitHS3_RooJSONFactoryWSTool_h #define RooFitHS3_RooJSONFactoryWSTool_h +#include + +#include +#include +#include +#include + #include -#include #include -#include -#include - -class RooArgList; -class RooAbsData; -class RooArgSet; -class RooAbsArg; -class RooAbsPdf; -class RooDataHist; -class RooDataSet; -class RooRealVar; -class RooWorkspace; +#include namespace RooFit { +namespace JSONIO { namespace Detail { -class JSONNode; -class JSONTree; -} // namespace Detail +class Domains; +} +} // namespace JSONIO } // namespace RooFit - -class TH1; -class TClass; +namespace RooStats { +class ModelConfig; +} class RooJSONFactoryWSTool { public: - static std::ostream &log(int level); + static constexpr bool useListsInsteadOfDicts = true; + + struct CombinedData { + std::string name; + std::map components; + }; + + RooJSONFactoryWSTool(RooWorkspace &ws); + + ~RooJSONFactoryWSTool(); static std::string name(const RooFit::Detail::JSONNode &n); - template - T *request(const std::string &objname, const std::string &requestAuthor); + static RooFit::Detail::JSONNode &appendNamedChild(RooFit::Detail::JSONNode &node, std::string const &name); + static RooFit::Detail::JSONNode const *findNamedChild(RooFit::Detail::JSONNode const &node, std::string const &name); - RooJSONFactoryWSTool(RooWorkspace &ws) : _workspace{ws} {} - RooWorkspace *workspace() { return &_workspace; } + static void fillSeq(RooFit::Detail::JSONNode &node, RooAbsCollection const &coll); - static void error(const char *s) { throw std::runtime_error(s); } - static void error(const std::string &s) { throw std::runtime_error(s); } template - static std::string concat(const T *items, const std::string &sep = ",") + T *request(const std::string &objname, const std::string &requestAuthor) { - // Returns a string being the concatenation of strings in input list - // (names of objects obtained using GetName()) separated by string . - bool first = true; - std::string text; - - // iterate over strings in list - for (auto it : *items) { - if (!first) { - // insert separator string - text += sep; - } else { - first = false; - } - if (!it) - text += "nullptr"; - else - text += it->GetName(); + if (T *out = requestImpl(objname)) { + return out; } - return text; + throw DependencyMissingError(requestAuthor, objname, T::Class()->GetName()); } + template - static std::vector names(const T *items) + T *requestArg(const RooFit::Detail::JSONNode &node, const std::string &key) { - // Returns a string being the concatenation of strings in input list - // (names of objects obtained using GetName()) separated by string . - std::vector names; - // iterate over strings in list - for (auto it : *items) { - if (!it) - names.push_back("nullptr"); - else - names.push_back(it->GetName()); + std::string requestAuthor(RooJSONFactoryWSTool::name(node)); + if (!node.has_child(key)) { + RooJSONFactoryWSTool::error("no \"" + key + "\" given in \"" + requestAuthor + "\""); } - return names; + return request(node[key].val(), requestAuthor); } - static std::string genPrefix(const RooFit::Detail::JSONNode &p, bool trailing_underscore); - static void exportHistogram(const TH1 &h, RooFit::Detail::JSONNode &n, const std::vector &obsnames, - const TH1 *errH = nullptr, bool writeObservables = true, bool writeErrors = true); - static void writeObservables(const TH1 &h, RooFit::Detail::JSONNode &n, const std::vector &varnames); + template + Coll_t requestCollection(const RooFit::Detail::JSONNode &node, const std::string &seqName) + { + std::string requestAuthor(RooJSONFactoryWSTool::name(node)); + if (!node.has_child(seqName)) { + RooJSONFactoryWSTool::error("no \"" + seqName + "\" given in \"" + requestAuthor + "\""); + } + if (!node[seqName].is_seq()) { + RooJSONFactoryWSTool::error("\"" + seqName + "\" in \"" + requestAuthor + "\" is not a sequence"); + } - static std::unique_ptr readBinnedData(RooWorkspace &ws, const RooFit::Detail::JSONNode &n, - const std::string &namecomp, RooArgList observables); + Coll_t out; + for (const auto &elem : node[seqName].children()) { + out.add(*request(elem.val(), requestAuthor)); + } + return out; + } - static void - getObservables(RooWorkspace &ws, const RooFit::Detail::JSONNode &n, const std::string &obsnamecomp, RooArgSet &out); + template + RooArgSet requestArgSet(const RooFit::Detail::JSONNode &node, const std::string &seqName) + { + return requestCollection(node, seqName); + } + + template + RooArgList requestArgList(const RooFit::Detail::JSONNode &node, const std::string &seqName) + { + return requestCollection(node, seqName); + } + + RooWorkspace *workspace() { return &_workspace; } + + template + Obj_t &wsImport(Obj_t const &obj) + { + _workspace.import(obj, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + return *static_cast(_workspace.obj(obj.GetName())); + } + + template + Obj_t &wsEmplace(RooStringView name, Args_t &&...args) + { + return wsImport(Obj_t(name.c_str(), name.c_str(), std::forward(args)...)); + } + + [[noreturn]] static void error(const char *s); + [[noreturn]] inline static void error(const std::string &s) { error(s.c_str()); } + static std::ostream &warning(const std::string &s); + + static RooArgSet readAxes(const RooFit::Detail::JSONNode &node); + static std::unique_ptr + readBinnedData(const RooFit::Detail::JSONNode &n, const std::string &namecomp, RooArgSet const &vars); bool importJSON(std::string const &filename); bool importYML(std::string const &filename); @@ -116,41 +140,17 @@ class RooJSONFactoryWSTool { std::string exportYMLtoString(); bool importJSONfromString(const std::string &s); bool importYMLfromString(const std::string &s); + void importJSONElement(const std::string &name, const std::string &jsonString); + void importVariableElement(const RooFit::Detail::JSONNode &n); - void importFunctions(const RooFit::Detail::JSONNode &n); - void importFunction(const RooFit::Detail::JSONNode &n, bool isPdf); - RooFit::Detail::JSONNode *exportObject(const RooAbsArg *func); + void importFunction(const RooFit::Detail::JSONNode &n, bool importAllDependants); + void importFunction(const std::string &jsonString, bool importAllDependants); static std::unique_ptr createNewJSONTree(); -private: - struct Config { - static bool stripObservables; - }; - - struct Var { - int nbins; - double min; - double max; - std::vector bounds; - - Var(int n) : nbins(n), min(0), max(n) {} - Var(const RooFit::Detail::JSONNode &val); - }; - - RooFit::Detail::JSONNode &orootnode(); - const RooFit::Detail::JSONNode &irootnode() const; - - std::map> loadData(const RooFit::Detail::JSONNode &n); - std::unique_ptr unbinned(RooDataHist const &hist); - RooRealVar *getWeightVar(const char *name); - static RooRealVar *createObservable(RooWorkspace &ws, const std::string &name, const RooJSONFactoryWSTool::Var &var); - - class MissingRootnodeError : public std::exception { - public: - const char *what() const noexcept override { return "no rootnode set"; } - }; + static RooFit::Detail::JSONNode &makeVariablesNode(RooFit::Detail::JSONNode &rootNode); + // error handling helpers class DependencyMissingError : public std::exception { std::string _parent, _child, _class, _message; @@ -166,35 +166,67 @@ class RooJSONFactoryWSTool { const char *what() const noexcept override { return _message.c_str(); } }; - // error handling helpers - void exportData(RooAbsData *data, RooFit::Detail::JSONNode &n); - static std::vector> generateBinIndices(const RooArgList &vars); - static std::map - readObservables(const RooFit::Detail::JSONNode &n, const std::string &obsnamecomp); + template + static RooFit::Detail::JSONNode &getRooFitInternal(RooFit::Detail::JSONNode &node, Keys_t const &...keys) + { + return node.get("misc", "ROOT_internal", keys...); + } + + static void + exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, RooFit::Detail::JSONNode &output); + + static void exportArray(std::size_t n, double const *contents, RooFit::Detail::JSONNode &output); + + static void exportCategory(RooAbsCategory const &cat, RooFit::Detail::JSONNode &node); + + void queueExport(RooAbsArg const &arg) { _serversToExport.push_back(&arg); } + + RooFit::Detail::JSONNode &createAdHoc(const std::string &toplevel, const std::string &name); + RooAbsReal *importTransformed(const std::string &name, const std::string &tag, const std::string &operation_name, + const std::string &formula); + std::string exportTransformed(const RooAbsReal *original, const std::string &tag, const std::string &operation_name, + const std::string &formula); + + void setAttribute(const std::string &obj, const std::string &attrib); + bool hasAttribute(const std::string &obj, const std::string &attrib); + std::string getStringAttribute(const std::string &obj, const std::string &attrib); + void setStringAttribute(const std::string &obj, const std::string &attrib, const std::string &value); + +private: + template + T *requestImpl(const std::string &objname); + + void exportObject(RooAbsArg const &func, std::set &exportedObjectNames); + + void exportData(RooAbsData const &data); + RooJSONFactoryWSTool::CombinedData exportCombinedData(RooAbsData const &data); void importAllNodes(const RooFit::Detail::JSONNode &n); - void importPdfs(const RooFit::Detail::JSONNode &n); - void importVariables(const RooFit::Detail::JSONNode &n); void importVariable(const RooFit::Detail::JSONNode &n); - void configureVariable(const RooFit::Detail::JSONNode &p, RooRealVar &v); void importDependants(const RooFit::Detail::JSONNode &n); - void configureToplevelPdf(const RooFit::Detail::JSONNode &n, RooAbsPdf &pdf); - - bool find(const RooFit::Detail::JSONNode &n, const std::string &elem); - void append(RooFit::Detail::JSONNode &n, const std::string &elem); - - void exportAttributes(const RooAbsArg *arg, RooFit::Detail::JSONNode &n); void exportVariable(const RooAbsArg *v, RooFit::Detail::JSONNode &n); void exportVariables(const RooArgSet &allElems, RooFit::Detail::JSONNode &n); void exportAllObjects(RooFit::Detail::JSONNode &n); - void exportDependants(const RooAbsArg *source); + + void exportModelConfig(RooFit::Detail::JSONNode &rootnode, RooStats::ModelConfig const &mc, + const std::vector &d); + + void exportSingleModelConfig(RooFit::Detail::JSONNode &rootnode, RooStats::ModelConfig const &mc, + std::string const &analysisName, + std::map const *dataComponents); // member variables - const RooFit::Detail::JSONNode *_rootnode_input = nullptr; - RooFit::Detail::JSONNode *_rootnode_output = nullptr; + const RooFit::Detail::JSONNode *_rootnodeInput = nullptr; + const RooFit::Detail::JSONNode *_attributesNode = nullptr; + RooFit::Detail::JSONNode *_rootnodeOutput = nullptr; + RooFit::Detail::JSONNode *_varsNode = nullptr; RooWorkspace &_workspace; + + // objects to represent intermediate information + std::unique_ptr _domains; + std::vector _serversToExport; }; #endif diff --git a/roofit/hs3/src/Domains.cxx b/roofit/hs3/src/Domains.cxx new file mode 100644 index 0000000000000..3eb3a7d51cb92 --- /dev/null +++ b/roofit/hs3/src/Domains.cxx @@ -0,0 +1,107 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN, Jan 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include "Domains.h" + +#include +#include +#include + +#include + +namespace RooFit { +namespace JSONIO { +namespace Detail { + +void Domains::readVariable(const char *name, double min, double max) +{ + _map["default_domain"].readVariable(name, min, max); +} +void Domains::readVariable(RooRealVar const &var) +{ + readVariable(var.GetName(), var.getMin(), var.getMax()); +} +void Domains::writeVariable(RooRealVar &var) const +{ + _map.at("default_domain").writeVariable(var); +} + +void Domains::readJSON(RooFit::Detail::JSONNode const &node) +{ + _map["default_domain"].readJSON(*RooJSONFactoryWSTool::findNamedChild(node, "default_domain")); +} +void Domains::writeJSON(RooFit::Detail::JSONNode &node) const +{ + for (auto const &domain : _map) { + domain.second.writeJSON(RooJSONFactoryWSTool::appendNamedChild(node, domain.first)); + } +} +void Domains::ProductDomain::readVariable(const char *name, double min, double max) +{ + auto &elem = _map[name]; + + if (!RooNumber::isInfinite(min)) { + elem.hasMin = true; + elem.min = min; + } + if (!RooNumber::isInfinite(max)) { + elem.hasMax = true; + elem.max = max; + } +} +void Domains::ProductDomain::writeVariable(RooRealVar &var) const +{ + auto found = _map.find(var.GetName()); + if (found != _map.end()) { + auto const &elem = found->second; + if (elem.hasMin) + var.setMin(elem.min); + if (elem.hasMax) + var.setMax(elem.max); + } +} +void Domains::ProductDomain::readJSON(RooFit::Detail::JSONNode const &node) +{ + // In the future, throw an exception if the type is not product domain + for (auto const &varNode : node["axes"].children()) { + auto &elem = _map[RooJSONFactoryWSTool::name(varNode)]; + + if (varNode.has_child("min")) { + elem.min = varNode["min"].val_double(); + elem.hasMin = true; + } + if (varNode.has_child("max")) { + elem.max = varNode["max"].val_double(); + elem.hasMax = true; + } + } +} +void Domains::ProductDomain::writeJSON(RooFit::Detail::JSONNode &node) const +{ + node.set_map(); + node["type"] << "product_domain"; + + auto &variablesNode = node["axes"]; + + for (auto const &item : _map) { + auto const &elem = item.second; + RooFit::Detail::JSONNode &varnode = RooJSONFactoryWSTool::appendNamedChild(variablesNode, item.first); + if (elem.hasMin) + varnode["min"] << elem.min; + if (elem.hasMax) + varnode["max"] << elem.max; + } +} + +} // namespace Detail +} // namespace JSONIO +} // namespace RooFit diff --git a/roofit/hs3/src/Domains.h b/roofit/hs3/src/Domains.h new file mode 100644 index 0000000000000..6d542dbe82cef --- /dev/null +++ b/roofit/hs3/src/Domains.h @@ -0,0 +1,69 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN, Jan 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_JSONIO_Detail_Domains_h +#define RooFit_JSONIO_Detail_Domains_h + +#include +#include +#include + +class RooRealVar; + +namespace RooFit { +namespace Detail { +class JSONNode; +class JSONTree; +} // namespace Detail +} // namespace RooFit + +namespace RooFit { +namespace JSONIO { +namespace Detail { + +class Domains { +public: + void readVariable(const char *name, double min, double max); + void readVariable(RooRealVar const &); + void writeVariable(RooRealVar &) const; + + void readJSON(RooFit::Detail::JSONNode const &); + void writeJSON(RooFit::Detail::JSONNode &) const; + +private: + class ProductDomain { + public: + void readVariable(const char *name, double min, double max); + void writeVariable(RooRealVar &) const; + + void readJSON(RooFit::Detail::JSONNode const &); + void writeJSON(RooFit::Detail::JSONNode &) const; + + private: + struct ProductDomainElement { + bool hasMin = false; + bool hasMax = false; + double min = 0.0; + double max = 0.0; + }; + + std::map _map; + }; + + std::map _map; +}; + +} // namespace Detail +} // namespace JSONIO +} // namespace RooFit + +#endif diff --git a/roofit/hs3/src/HistFactoryJSONTool.cxx b/roofit/hs3/src/HistFactoryJSONTool.cxx index 3601c7dae0282..17171b00bfc19 100644 --- a/roofit/hs3/src/HistFactoryJSONTool.cxx +++ b/roofit/hs3/src/HistFactoryJSONTool.cxx @@ -14,88 +14,208 @@ #include #include -#include "RooStats/HistFactory/Measurement.h" -#include "RooStats/HistFactory/Channel.h" -#include "RooStats/HistFactory/Sample.h" +#include +#include +#include + +#include "Domains.h" + +#include using RooFit::Detail::JSONNode; using RooFit::Detail::JSONTree; namespace { -void exportSample(const RooStats::HistFactory::Sample &sample, JSONNode &s) +bool checkRegularBins(const TAxis &ax) +{ + double w = ax.GetXmax() - ax.GetXmin(); + double bw = w / ax.GetNbins(); + for (int i = 0; i <= ax.GetNbins(); ++i) { + if (std::abs(ax.GetBinUpEdge(i) - (ax.GetXmin() + (bw * i))) > w * 1e-6) + return false; + } + return true; +} + +inline void writeAxis(JSONNode &axis, const TAxis &ax) +{ + bool regular = (!ax.IsVariableBinSize()) || checkRegularBins(ax); + axis.set_map(); + if (regular) { + axis["nbins"] << ax.GetNbins(); + axis["min"] << ax.GetXmin(); + axis["max"] << ax.GetXmax(); + } else { + auto &edges = axis["edges"]; + edges.set_seq(); + for (int i = 0; i <= ax.GetNbins(); ++i) { + edges.append_child() << ax.GetBinUpEdge(i); + } + } +} + +std::vector getObsnames(RooStats::HistFactory::Channel const &c) +{ + std::vector obsnames{"obs_x_" + c.GetName(), "obs_y_" + c.GetName(), "obs_z_" + c.GetName()}; + obsnames.resize(c.GetData().GetHisto()->GetDimension()); + return obsnames; +} + +void writeObservables(const TH1 &h, JSONNode &node, const std::vector &varnames) +{ + // axes need to be ordered, so this is a sequence and not a map + auto &observables = node["axes"].set_seq(); + auto &x = observables.append_child().set_map(); + x["name"] << varnames[0]; + writeAxis(x, *h.GetXaxis()); + if (h.GetDimension() > 1) { + auto &y = observables.append_child().set_map(); + y["name"] << varnames[1]; + writeAxis(y, *(h.GetYaxis())); + if (h.GetDimension() > 2) { + auto &z = observables.append_child().set_map(); + z["name"] << varnames[2]; + writeAxis(z, *(h.GetZaxis())); + } + } +} + +void exportSimpleHistogram(const TH1 &histo, JSONNode &node) +{ + node.set_seq(); + const int nBins = histo.GetNbinsX() * histo.GetNbinsY() * histo.GetNbinsZ(); + for (int i = 1; i <= nBins; ++i) { + const double val = histo.GetBinContent(i); + node.append_child() << val; + } +} + +void exportHistogram(const TH1 &histo, JSONNode &node, const std::vector &varnames, + const TH1 *errH = nullptr, bool doWriteObservables = true, bool writeErrors = true) { - const std::vector obsnames{"obs_x_" + sample.GetChannelName(), "obs_y_" + sample.GetChannelName(), - "obs_z_" + sample.GetChannelName()}; + node.set_map(); + auto &weights = node["contents"].set_seq(); + JSONNode *errors = nullptr; + if (writeErrors) { + errors = &node["errors"].set_seq(); + } + if (doWriteObservables) { + writeObservables(histo, node, varnames); + } + const int nBins = histo.GetNbinsX() * histo.GetNbinsY() * histo.GetNbinsZ(); + for (int i = 1; i <= nBins; ++i) { + const double val = histo.GetBinContent(i); + weights.append_child() << val; + if (writeErrors) { + const double err = errH ? val * errH->GetBinContent(i) : histo.GetBinError(i); + errors->append_child() << err; + } + } +} - s.set_map(); +void exportSample(const RooStats::HistFactory::Sample &sample, JSONNode &channelNode, + std::vector const &obsnames) +{ + auto &s = RooJSONFactoryWSTool::appendNamedChild(channelNode["samples"], sample.GetName()); - if (sample.GetOverallSysList().size() > 0) { - auto &overallSys = s["overallSystematics"]; - overallSys.set_map(); + if (!sample.GetOverallSysList().empty()) { + auto &modifiers = s["modifiers"].set_seq(); for (const auto &sys : sample.GetOverallSysList()) { - auto &node = overallSys[sys.GetName()]; - node.set_map(); - node["low"] << sys.GetLow(); - node["high"] << sys.GetHigh(); + auto &node = modifiers.append_child().set_map(); + node["name"] << sys.GetName(); + node["type"] << "normsys"; + auto &data = node["data"]; + data.set_map(); + data["lo"] << sys.GetLow(); + data["hi"] << sys.GetHigh(); } } - if (sample.GetNormFactorList().size() > 0) { - auto &normFactors = s["normFactors"]; - normFactors.set_seq(); - for (auto &sys : sample.GetNormFactorList()) { - normFactors.append_child() << sys.GetName(); + if (!sample.GetNormFactorList().empty()) { + auto &modifiers = s["modifiers"].set_seq(); + for (const auto &nf : sample.GetNormFactorList()) { + auto &mod = modifiers.append_child().set_map(); + mod["name"] << nf.GetName(); + mod["type"] << "normfactor"; } + auto &mod = modifiers.append_child().set_map(); + mod["name"] << "Lumi"; + mod["type"] << "normfactor"; + mod["constraint_name"] << "lumiConstraint"; } - if (sample.GetHistoSysList().size() > 0) { - auto &histoSys = s["histogramSystematics"]; - histoSys.set_map(); + if (!sample.GetHistoSysList().empty()) { + auto &modifiers = s["modifiers"].set_seq(); for (size_t i = 0; i < sample.GetHistoSysList().size(); ++i) { auto &sys = sample.GetHistoSysList()[i]; - auto &node = histoSys[sys.GetName()]; - node.set_map(); - RooJSONFactoryWSTool::exportHistogram(*(sys.GetHistoLow()), node["dataLow"], obsnames); - RooJSONFactoryWSTool::exportHistogram(*(sys.GetHistoHigh()), node["dataHigh"], obsnames); + auto &node = modifiers.append_child().set_map(); + node["name"] << sys.GetName(); + node["type"] << "histosys"; + auto &data = node["data"].set_map(); + exportSimpleHistogram(*sys.GetHistoLow(), data["lo"].set_map()["contents"]); + exportSimpleHistogram(*sys.GetHistoHigh(), data["hi"].set_map()["contents"]); + } + } + + if (!sample.GetShapeSysList().empty()) { + auto &modifiers = s["modifiers"].set_seq(); + for (size_t i = 0; i < sample.GetShapeSysList().size(); ++i) { + auto &sys = sample.GetShapeSysList()[i]; + auto &node = modifiers.append_child().set_map(); + node["name"] << sys.GetName(); + node["type"] << "shapesys"; + if (sys.GetConstraintType() == RooStats::HistFactory::Constraint::Gaussian) + node["constraint"] << "Gauss"; + if (sys.GetConstraintType() == RooStats::HistFactory::Constraint::Poisson) + node["constraint"] << "Poisson"; + auto &data = node["data"].set_map(); + exportSimpleHistogram(*sys.GetErrorHist(), data["vals"]); } } - auto &tags = s["dict"]; - tags.set_map(); + auto &tags = s["dict"].set_map(); tags["normalizeByTheory"] << sample.GetNormalizeByTheory(); - s["statError"] << sample.GetStatError().GetActivate(); + if (sample.GetStatError().GetActivate()) { + RooStats::HistFactory::JSONTool::activateStatError(s); + } auto &data = s["data"]; - RooJSONFactoryWSTool::exportHistogram(*sample.GetHisto(), data, obsnames, - sample.GetStatError().GetActivate() && sample.GetStatError().GetUseHisto() - ? sample.GetStatError().GetErrorHist() - : nullptr); + const bool useStatError = sample.GetStatError().GetActivate() && sample.GetStatError().GetUseHisto(); + TH1 const *errH = useStatError ? sample.GetStatError().GetErrorHist() : nullptr; + + if (!channelNode.has_child("axes")) { + writeObservables(*sample.GetHisto(), channelNode, obsnames); + } + exportHistogram(*sample.GetHisto(), data, obsnames, errH, false); } void exportChannel(const RooStats::HistFactory::Channel &c, JSONNode &ch) { - ch.set_map(); - ch["type"] << "histfactory"; + ch["type"] << "histfactory_dist"; - auto &staterr = ch["statError"]; - staterr.set_map(); + auto &staterr = ch["statError"].set_map(); staterr["relThreshold"] << c.GetStatErrorConfig().GetRelErrorThreshold(); staterr["constraint"] << RooStats::HistFactory::Constraint::Name(c.GetStatErrorConfig().GetConstraintType()); - auto &samples = ch["samples"]; - samples.set_map(); + const std::vector obsnames = getObsnames(c); + for (const auto &s : c.GetSamples()) { - auto &sample = samples[s.GetName()]; - exportSample(s, sample); - auto &ns = sample["namespaces"]; - ns.set_seq(); - ns.append_child() << c.GetName(); + exportSample(s, ch, obsnames); } } -void exportMeasurement(RooStats::HistFactory::Measurement &measurement, JSONNode &n) +void setAttribute(JSONNode &rootnode, const std::string &obj, const std::string &attrib) +{ + auto node = &RooJSONFactoryWSTool::getRooFitInternal(rootnode, "attributes").set_map()[obj].set_map(); + auto &tags = (*node)["tags"]; + tags.set_seq(); + tags.append_child() << attrib; +} + +void exportMeasurement(RooStats::HistFactory::Measurement &measurement, JSONNode &rootnode, + RooFit::JSONIO::Detail::Domains &domains) { using namespace RooStats::HistFactory; @@ -104,36 +224,11 @@ void exportMeasurement(RooStats::HistFactory::Measurement &measurement, JSONNode throw std::runtime_error("unable to export histograms, please call CollectHistograms first"); } - auto &pdflist = n["pdfs"]; - pdflist.set_map(); - - // collect information - std::map constraints; - std::map normfactors; - for (const auto &ch : measurement.GetChannels()) { - for (const auto &s : ch.GetSamples()) { - for (const auto &sys : s.GetOverallSysList()) { - constraints[sys.GetName()] = RooStats::HistFactory::Constraint::Gaussian; - } - for (const auto &sys : s.GetHistoSysList()) { - constraints[sys.GetName()] = RooStats::HistFactory::Constraint::Gaussian; - } - for (const auto &sys : s.GetShapeSysList()) { - constraints[sys.GetName()] = sys.GetConstraintType(); - } - for (const auto &norm : s.GetNormFactorList()) { - normfactors[norm.GetName()] = norm; - } - } - } - // preprocess functions if (!measurement.GetFunctionObjects().empty()) { - auto &funclist = n["functions"]; - funclist.set_map(); + auto &funclist = rootnode["functions"]; for (const auto &func : measurement.GetFunctionObjects()) { - auto &f = funclist[func.GetName()]; - f.set_map(); + auto &f = RooJSONFactoryWSTool::appendNamedChild(funclist, func.GetName()); f["name"] << func.GetName(); f["expression"] << func.GetExpression(); f["dependents"] << func.GetDependents(); @@ -141,81 +236,140 @@ void exportMeasurement(RooStats::HistFactory::Measurement &measurement, JSONNode } } + auto &pdflist = rootnode["distributions"]; + + auto &analysisNode = RooJSONFactoryWSTool::appendNamedChild(rootnode["analyses"], "simPdf"); + analysisNode["domains"].set_seq().append_child() << "default_domain"; + + auto &analysisPois = analysisNode["parameters_of_interest"].set_seq(); + + for (const auto &poi : measurement.GetPOIList()) { + analysisPois.append_child() << poi; + } + + analysisNode["likelihood"] << measurement.GetName(); + + auto &likelihoodNode = RooJSONFactoryWSTool::appendNamedChild(rootnode["likelihoods"], measurement.GetName()); + likelihoodNode["distributions"].set_seq(); + likelihoodNode["data"].set_seq(); + // the simpdf - auto &sim = pdflist[measurement.GetName()]; - sim.set_map(); - sim["type"] << "simultaneous"; - sim["index"] << "channelCat"; - auto &simdict = sim["dict"]; - simdict.set_map(); - simdict["InterpolationScheme"] << measurement.GetInterpolationScheme(); - auto &simtags = sim["tags"]; - simtags.set_seq(); - simtags.append_child() << "toplevel"; - auto &ch = sim["channels"]; - ch.set_map(); for (const auto &c : measurement.GetChannels()) { + auto pdfName = std::string("model_") + c.GetName(); - ch[c.GetName()] << pdfName; - exportChannel(c, pdflist[pdfName]); + auto realSumPdfName = c.GetName() + std::string("_model"); + + likelihoodNode["distributions"].append_child() << pdfName; + likelihoodNode["data"].append_child() << std::string("obsData_") + c.GetName(); + exportChannel(c, RooJSONFactoryWSTool::appendNamedChild(pdflist, pdfName)); + setAttribute(rootnode, realSumPdfName, "BinnedLikelihood"); } - // the variables - auto &varlist = n["variables"]; - varlist.set_map(); - for (const auto &c : measurement.GetChannels()) { - for (const auto &s : c.GetSamples()) { - for (const auto &norm : s.GetNormFactorList()) { - if (!varlist.has_child(norm.GetName())) { - auto &v = varlist[norm.GetName()]; - v.set_map(); - v["value"] << norm.GetVal(); - v["min"] << norm.GetLow(); - v["max"] << norm.GetHigh(); - } + struct VariableInfo { + double val = 0.0; + double minVal = -5.0; + double maxVal = 5.0; + bool isConstant = false; + bool writeDomain = true; + }; + std::unordered_map variables; + + for (const auto &channel : measurement.GetChannels()) { + for (const auto &sample : channel.GetSamples()) { + for (const auto &norm : sample.GetNormFactorList()) { + auto &info = variables[norm.GetName()]; + info.val = norm.GetVal(); + info.minVal = norm.GetLow(); + info.maxVal = norm.GetHigh(); } - for (const auto &sys : s.GetOverallSysList()) { - std::string parname("alpha_"); - parname += sys.GetName(); - if (!varlist.has_child(parname)) { - auto &v = varlist[parname]; - v.set_map(); - v["value"] << 0.; - v["min"] << -5.; - v["max"] << 5.; - } + for (const auto &sys : sample.GetOverallSysList()) { + variables[std::string("alpha_") + sys.GetName()] = VariableInfo{}; } } } for (const auto &sys : measurement.GetConstantParams()) { - std::string parname = "alpha_" + sys; - if (!varlist.has_child(parname)) { - auto &v = varlist[parname]; - v.set_map(); - } - varlist[parname]["const"] << true; + auto &info = variables[sys]; + info.isConstant = true; + bool isGamma = sys.find("gamma_") != std::string::npos; + // Gammas are 1.0 by default, alphas are 0.0 + info.val = isGamma ? 1.0 : 0.0; + // For the gamma parameters, HistFactory will figure out the ranges + // itself based on the template bin contents and errors. + info.writeDomain = !isGamma; } - for (const auto &poi : measurement.GetPOIList()) { - if (!varlist[poi].has_child("tags")) { - auto &tags = varlist[poi]["tags"]; - tags.set_seq(); + // the lumi variables + { + double nominal = measurement.GetLumi(); + double error = measurement.GetLumi() * measurement.GetLumiRelErr(); + + auto &info1 = variables["Lumi"]; + info1.val = nominal; + info1.minVal = 0; + info1.maxVal = 10 * nominal; + info1.isConstant = true; + + auto &info2 = variables["nominalLumi"]; + info2.val = nominal; + info2.minVal = 0; + info2.maxVal = nominal + 10 * error; + info2.isConstant = true; + } + + JSONNode &varlist = RooJSONFactoryWSTool::makeVariablesNode(rootnode); + for (auto const &item : variables) { + std::string const &parname = item.first; + VariableInfo const &info = item.second; + + auto &v = RooJSONFactoryWSTool::appendNamedChild(varlist, parname); + v["value"] << info.val; + if (info.isConstant) + v["const"] << true; + if (info.writeDomain) { + domains.readVariable(parname.c_str(), info.minVal, info.maxVal); } - varlist[poi]["tags"].append_child() << "poi"; } // the data - auto &datalist = n["data"]; - datalist.set_map(); - auto &obsdata = datalist["obsData"]; - obsdata.set_map(); - obsdata["index"] << "channelCat"; + auto &child1 = rootnode.get("misc", "ROOT_internal", "combined_datasets").set_map()["obsData"].set_map(); + auto &child2 = rootnode.get("misc", "ROOT_internal", "combined_distributions").set_map()["simPdf"].set_map(); + + child1["index_cat"] << "channelCat"; + auto &labels1 = child1["labels"].set_seq(); + auto &indices1 = child1["indices"].set_seq(); + + child2["index_cat"] << "channelCat"; + auto &labels2 = child2["labels"].set_seq(); + auto &indices2 = child2["indices"].set_seq(); + auto &pdfs2 = child2["distributions"].set_seq(); + + std::vector channelNames; for (const auto &c : measurement.GetChannels()) { - const std::vector obsnames{"obs_x_" + c.GetName(), "obs_y_" + c.GetName(), "obs_z_" + c.GetName()}; + labels1.append_child() << c.GetName(); + indices1.append_child() << int(channelNames.size()); + labels2.append_child() << c.GetName(); + indices2.append_child() << int(channelNames.size()); + pdfs2.append_child() << (std::string("model_") + c.GetName()); - auto &chdata = obsdata[c.GetName()]; - RooJSONFactoryWSTool::exportHistogram(*c.GetData().GetHisto(), chdata, obsnames); + JSONNode &dataOutput = + RooJSONFactoryWSTool::appendNamedChild(rootnode["data"], std::string("obsData_") + c.GetName()); + dataOutput["type"] << "binned"; + + exportHistogram(*c.GetData().GetHisto(), dataOutput, getObsnames(c)); + channelNames.push_back(c.GetName()); } + + auto &modelConfigAux = RooJSONFactoryWSTool::getRooFitInternal(rootnode, "ModelConfigs", "simPdf").set_map(); + modelConfigAux["combined_data_name"] << "obsData"; + modelConfigAux["pdfName"] << "simPdf"; + modelConfigAux["mcName"] << "ModelConfig"; + + // Finally write lumi constraint + auto &lumiConstraint = RooJSONFactoryWSTool::appendNamedChild(pdflist, "lumiConstraint"); + lumiConstraint["mean"] << "nominalLumi"; + lumiConstraint["sigma"] << (measurement.GetLumi() * measurement.GetLumiRelErr()); + lumiConstraint["type"] << "gaussian_dist"; + lumiConstraint["x"] << "Lumi"; } } // namespace @@ -223,9 +377,11 @@ void exportMeasurement(RooStats::HistFactory::Measurement &measurement, JSONNode void RooStats::HistFactory::JSONTool::PrintJSON(std::ostream &os) { std::unique_ptr tree = RooJSONFactoryWSTool::createNewJSONTree(); - auto &n = tree->rootnode(); - exportMeasurement(_measurement, n); - n.writeJSON(os); + auto &rootnode = tree->rootnode(); + RooFit::JSONIO::Detail::Domains domains; + exportMeasurement(_measurement, rootnode, domains); + domains.writeJSON(rootnode["domains"]); + rootnode.writeJSON(os); } void RooStats::HistFactory::JSONTool::PrintJSON(std::string const &filename) { @@ -233,24 +389,25 @@ void RooStats::HistFactory::JSONTool::PrintJSON(std::string const &filename) this->PrintJSON(out); } -#ifdef ROOFIT_HS3_WITH_RYML void RooStats::HistFactory::JSONTool::PrintYAML(std::ostream &os) { - TRYMLTree p; - auto &n = p.rootnode(); - n.set_map(); - exportMeasurement(_measurement, n); - n.writeYML(os); -} -#else -void RooStats::HistFactory::JSONTool::PrintYAML(std::ostream & /*os*/) -{ - std::cerr << "YAML export only support with rapidyaml!" << std::endl; + std::unique_ptr tree = RooJSONFactoryWSTool::createNewJSONTree(); + auto &rootnode = tree->rootnode().set_map(); + RooFit::JSONIO::Detail::Domains domains; + exportMeasurement(_measurement, rootnode, domains); + domains.writeJSON(rootnode["domains"]); + rootnode.writeYML(os); } -#endif void RooStats::HistFactory::JSONTool::PrintYAML(std::string const &filename) { std::ofstream out(filename); this->PrintYAML(out); } + +void RooStats::HistFactory::JSONTool::activateStatError(JSONNode &sampleNode) +{ + auto &node = sampleNode["modifiers"].set_seq().append_child().set_map(); + node["name"] << "mcstat"; + node["type"] << "staterror"; +} diff --git a/roofit/hs3/src/JSONFactories_HistFactory.cxx b/roofit/hs3/src/JSONFactories_HistFactory.cxx index d8d59c8ee9c94..c7b51fdec9832 100644 --- a/roofit/hs3/src/JSONFactories_HistFactory.cxx +++ b/roofit/hs3/src/JSONFactories_HistFactory.cxx @@ -10,15 +10,16 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +#include #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -26,105 +27,84 @@ #include #include #include +#include #include #include #include -#include - -#include - #include "static_execute.h" +#include "JSONIOUtils.h" using RooFit::Detail::JSONNode; +using namespace RooStats::HistFactory; +using namespace RooStats::HistFactory::Detail; +using namespace RooStats::HistFactory::Detail::MagicConstants; + namespace { -class Scope { -public: - void setObservables(const RooArgList &args) - { - for (auto *arg : args) { - _observables.push_back(arg); +inline void writeAxis(JSONNode &axis, RooRealVar const &obs) +{ + auto &binning = obs.getBinning(); + if (binning.isUniform()) { + axis["nbins"] << obs.numBins(); + axis["min"] << obs.getMin(); + axis["max"] << obs.getMax(); + } else { + auto &edges = axis["edges"]; + edges.set_seq(); + double val = binning.binLow(0); + edges.append_child() << val; + for (int i = 0; i < binning.numBins(); ++i) { + val = binning.binHigh(i); + edges.append_child() << val; } } - void setObject(const std::string &name, RooAbsArg *obj) { _objects[name] = obj; } - RooAbsArg *getObject(const std::string &name) const { return _objects.at(name); } - - void getObservables(RooArgSet &out) const { out.add(_observables.begin(), _observables.end()); } - -private: - std::vector _observables; - std::map _objects; -}; +} -inline void collectNames(const JSONNode &n, std::vector &names) +double round_prec(double d, int nSig) { - for (const auto &c : n.children()) { - names.push_back(RooJSONFactoryWSTool::name(c)); - } + if (d == 0.0) + return 0.0; + int ndigits = std::floor(std::log10(std::abs(d))) + 1 - nSig; + double sf = std::pow(10, ndigits); + if (std::abs(d / sf) < 2) + ndigits--; + return sf * std::round(d / sf); +} + +// To avoid repeating the same string literals that can potentially get out of +// sync. +namespace Literals { +constexpr auto staterror = "staterror"; } -inline void stackError(const JSONNode &n, std::vector &sumW, std::vector &sumW2) +void erasePrefix(std::string &str, std::string_view prefix) { - if (!n.is_map()) - return; - if (!n.has_child("counts")) - throw "no counts given"; - if (!n["counts"].is_seq()) - throw "counts are not in list form"; - if (!n.has_child("errors")) - throw "no errors given"; - if (!n["errors"].is_seq()) - throw "errors are not in list form"; - if (n["counts"].num_children() != n["errors"].num_children()) { - throw "inconsistent bin numbers"; - } - const size_t nbins = n["counts"].num_children(); - for (size_t ibin = 0; ibin < nbins; ++ibin) { - double w = n["counts"][ibin].val_float(); - double e = n["errors"][ibin].val_float(); - if (ibin < sumW.size()) - sumW[ibin] += w; - else - sumW.push_back(w); - if (ibin < sumW2.size()) - sumW2[ibin] += e * e; - else - sumW2.push_back(e * e); + if (startsWith(str, prefix)) { + str.erase(0, prefix.size()); } } -std::vector getVarnames(const RooHistFunc *hf) +void eraseSuffix(std::string &str, std::string_view suffix) { - const RooDataHist &dh = hf->dataHist(); - RooArgList vars(*dh.get()); - return RooJSONFactoryWSTool::names(&vars); + if (endsWith(str, suffix)) { + str.erase(str.size() - suffix.size()); + } } -std::unique_ptr histFunc2TH1(const RooHistFunc *hf) +template +void sortByName(Coll &coll) { - if (!hf) - RooJSONFactoryWSTool::error("null pointer passed to histFunc2TH1"); - const RooDataHist &dh = hf->dataHist(); - RooArgSet *vars = hf->getVariables(); - auto varnames = RooJSONFactoryWSTool::names(vars); - std::unique_ptr hist{hf->createHistogram(RooJSONFactoryWSTool::concat(vars).c_str())}; - hist->SetDirectory(nullptr); - auto volumes = dh.binVolumes(0, dh.numEntries()); - for (size_t i = 0; i < volumes.size(); ++i) { - hist->SetBinContent(i + 1, hist->GetBinContent(i + 1) / volumes[i]); - hist->SetBinError(i + 1, std::sqrt(hist->GetBinContent(i + 1))); - } - return hist; + std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return l.name < r.name; }); } template T *findClient(RooAbsArg *gamma) { for (const auto &client : gamma->clients()) { - if (client->InheritsFrom(T::Class())) { - return static_cast(client); + if (auto casted = dynamic_cast(client)) { + return casted; } else { T *c = findClient(client); if (c) @@ -134,419 +114,310 @@ T *findClient(RooAbsArg *gamma) return nullptr; } -RooRealVar *getNP(RooWorkspace &ws, const char *parname) +RooAbsPdf *findConstraint(RooAbsArg *g) { - RooRealVar *par = ws.var(parname); - if (!ws.var(parname)) { - par = static_cast(ws.factory(std::string(parname) + "[0.,-5,5]")); - } - if (par) { - par->setAttribute("np"); - } - std::string globname = std::string("nom_") + parname; - RooRealVar *nom = ws.var(globname); - if (!nom) { - nom = static_cast(ws.factory(globname + "[0.]")); - } - if (nom) { - nom->setAttribute("glob"); - nom->setRange(-5, 5); - nom->setConstant(true); - } - std::string constrname = std::string("sigma_") + parname; - RooRealVar *sigma = ws.var(constrname); - if (!sigma) { - sigma = static_cast(ws.factory(constrname + "[1.]")); - } - if (sigma) { - sigma->setRange(sigma->getVal(), sigma->getVal()); - sigma->setConstant(true); - } - if (!par) - RooJSONFactoryWSTool::error(TString::Format("unable to find nuisance parameter '%s'", parname)); - return par; + RooPoisson *constraint_p = findClient(g); + if (constraint_p) + return constraint_p; + RooGaussian *constraint_g = findClient(g); + if (constraint_g) + return constraint_g; + RooLognormal *constraint_l = findClient(g); + if (constraint_l) + return constraint_l; + return nullptr; } -RooAbsPdf *getConstraint(RooWorkspace &ws, const std::string &sysname) + +std::string toString(TClass *c) { - RooAbsPdf *pdf = ws.pdf((sysname + "_constraint").c_str()); - if (!pdf) { - pdf = static_cast( - ws.factory(TString::Format("RooGaussian::%s_constraint(alpha_%s,nom_alpha_%s,sigma_alpha_%s)", sysname.c_str(), - sysname.c_str(), sysname.c_str(), sysname.c_str()) - .Data())); + if (!c) { + return "Const"; } - if (!pdf) { - RooJSONFactoryWSTool::error(TString::Format("unable to find constraint term '%s'", sysname.c_str())); + if (c == RooPoisson::Class()) { + return "Poisson"; } - return pdf; + if (c == RooGaussian::Class()) { + return "Gauss"; + } + if (c == RooLognormal::Class()) { + return "Lognormal"; + } + return "unknown"; } -bool importHistSample(RooWorkspace &ws, Scope const &scope, const JSONNode &p) +RooRealVar &createNominal(RooWorkspace &ws, std::string const &parname, double val, double min, double max) { - std::string name(RooJSONFactoryWSTool::name(p)); - std::string prefix = RooJSONFactoryWSTool::genPrefix(p, true); - if (prefix.size() > 0) - name = prefix + name; - if (!p.has_child("data")) { - RooJSONFactoryWSTool::error("function '" + name + "' is of histogram type, but does not define a 'data' key"); - } - try { - std::stack> ownedArgsStack; - RooArgSet shapeElems; - RooArgSet normElems; - RooArgSet varlist; - scope.getObservables(varlist); - - auto getBinnedData = [&](std::string const &binnedDataName) -> RooDataHist & { - auto *dh = dynamic_cast(ws.embeddedData(binnedDataName)); - if (!dh) { - auto dhForImport = RooJSONFactoryWSTool::readBinnedData(ws, p["data"], binnedDataName, varlist); - ws.import(*dhForImport, RooFit::Silence(true), RooFit::Embedded()); - dh = static_cast(ws.embeddedData(dhForImport->GetName())); - } - return *dh; - }; + RooRealVar &nom = getOrCreate(ws, "nom_" + parname, val, min, max); + nom.setConstant(true); + return nom; +} - RooDataHist &dh = getBinnedData(name); - auto hf = std::make_unique(("hist_" + name).c_str(), RooJSONFactoryWSTool::name(p).c_str(), - *(dh.get()), dh); - ownedArgsStack.push(std::make_unique( - TString::Format("%s_binWidth", (!prefix.empty() ? prefix : name).c_str()).Data(), - TString::Format("%s_binWidth", (!prefix.empty() ? prefix : name).c_str()).Data(), *hf, true)); - shapeElems.add(*ownedArgsStack.top()); - - if (p.has_child("statError") && p["statError"].val_bool()) { - RooAbsArg *phf = scope.getObject("mcstat"); - if (phf) { - shapeElems.add(*phf); - } else { - RooJSONFactoryWSTool::error("function '" + name + - "' has 'statError' active, but no element called 'mcstat' in scope!"); - } - } +/// Get the conventional name of the constraint pdf for a constrained +/// parameter. +std::string constraintName(std::string const ¶mName) +{ + return paramName + "Constraint"; +} - if (p.has_child("normFactors")) { - for (const auto &nf : p["normFactors"].children()) { - std::string nfname(RooJSONFactoryWSTool::name(nf)); - if (RooAbsReal *r = ws.var(nfname)) { - normElems.add(*r); - } else { - normElems.add(*static_cast(ws.factory(nfname + "[1.]"))); - } - } - } +RooAbsPdf &getConstraint(RooWorkspace &ws, const std::string &pname) +{ + RooRealVar *constrParam = ws.var(pname); + constrParam->setError(1.0); + return getOrCreate(ws, constraintName(pname), *constrParam, *ws.var("nom_" + pname), 1.); +} - if (p.has_child("overallSystematics")) { - RooArgList nps; - std::vector low; - std::vector high; - for (const auto &sys : p["overallSystematics"].children()) { - std::string sysname(RooJSONFactoryWSTool::name(sys)); - std::string parname(sys.has_child("parameter") ? RooJSONFactoryWSTool::name(sys["parameter"]) - : "alpha_" + sysname); - if (RooRealVar *par = ::getNP(ws, parname.c_str())) { - nps.add(*par); - low.push_back(sys["low"].val_float()); - high.push_back(sys["high"].val_float()); - } else { - RooJSONFactoryWSTool::error("overall systematic '" + sysname + "' doesn't have a valid parameter!"); - } - } - auto v = std::make_unique( - ("overallSys_" + name).c_str(), ("overallSys_" + name).c_str(), nps, 1., low, high); - v->setAllInterpCodes(4); // default HistFactory interpCode - normElems.add(*v); - ownedArgsStack.push(std::move(v)); - } - - if (p.has_child("histogramSystematics")) { - RooArgList nps; - RooArgList low; - RooArgList high; - for (const auto &sys : p["histogramSystematics"].children()) { - std::string sysname(RooJSONFactoryWSTool::name(sys)); - std::string parname(sys.has_child("parameter") ? RooJSONFactoryWSTool::name(sys["parameter"]) - : "alpha_" + sysname); - RooAbsReal *par = ::getNP(ws, parname.c_str()); - nps.add(*par); - RooDataHist &dh_low = getBinnedData(sysname + "Low_" + name); - ownedArgsStack.push(std::make_unique( - (sysname + "Low_" + name).c_str(), RooJSONFactoryWSTool::name(p).c_str(), *(dh_low.get()), dh_low)); - low.add(*ownedArgsStack.top()); - RooDataHist &dh_high = getBinnedData(sysname + "High_" + name); - ownedArgsStack.push(std::make_unique( - (sysname + "High_" + name).c_str(), RooJSONFactoryWSTool::name(p).c_str(), *(dh_high.get()), dh_high)); - high.add(*ownedArgsStack.top()); - } - auto v = std::make_unique(("histoSys_" + name).c_str(), ("histoSys_" + name).c_str(), - *hf, low, high, nps, false); - v->setAllInterpCodes(4); // default interpCode for HistFactory - shapeElems.add(*v); - ownedArgsStack.push(std::move(v)); - } else { - shapeElems.add(*hf); - ownedArgsStack.push(std::move(hf)); - } - - if (p.has_child("shapeSystematics")) { - for (const auto &sys : p["shapeSystematics"].children()) { - std::string sysname(RooJSONFactoryWSTool::name(sys)); - std::string funcName = prefix + sysname + "_ShapeSys"; - RooAbsArg *phf = scope.getObject(funcName); - if (!phf) { - RooJSONFactoryWSTool::error("PHF '" + funcName + - "' should have been created but cannot be found in scope."); - } - shapeElems.add(*phf); - } - } +ParamHistFunc &createPHF(const std::string &sysname, const std::string &phfname, const std::vector &vals, + RooJSONFactoryWSTool &tool, RooArgList &constraints, const RooArgSet &observables, + const std::string &constraintType, double gammaMin, double gammaMax, double minSigma) +{ + RooWorkspace &ws = *tool.workspace(); - RooProduct shape(name.c_str(), (name + "_shape").c_str(), shapeElems); - ws.import(shape, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); - if (normElems.size() > 0) { - RooProduct norm((name + "_norm").c_str(), (name + "_norm").c_str(), normElems); - ws.import(norm, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); - } else { - ws.factory("RooConstVar::" + name + "_norm(1.)"); + RooArgList gammas = ParamHistFunc::createParamSet(ws, "gamma_" + sysname, observables, gammaMin, gammaMax); + + auto &phf = tool.wsEmplace(phfname, observables, gammas); + + if (constraintType != "Const") { + auto constraintsInfo = createGammaConstraints( + gammas, vals, minSigma, constraintType == "Poisson" ? Constraint::Poisson : Constraint::Gaussian); + for (auto const &term : constraintsInfo.constraints) { + ws.import(*term, RooFit::RecycleConflictNodes()); + constraints.add(*ws.pdf(term->GetName())); + } + } else { + for (auto *gamma : static_range_cast(gammas)) { + gamma->setConstant(true); } - } catch (const std::runtime_error &e) { - RooJSONFactoryWSTool::error("function '" + name + - "' is of histogram type, but 'data' is not a valid definition. " + e.what() + "."); } - return true; + + return phf; } -class RooRealSumPdfFactory : public RooFit::JSONIO::Importer { -public: - std::unique_ptr createPHF(const std::string &sysname, const std::string &phfname, - const std::vector &vals, RooWorkspace &w, RooArgList &constraints, - const RooArgSet &observables, const std::string &constraintType, - RooArgList &gammas, double gamma_min, double gamma_max) const - { - RooArgList ownedComponents; - - std::string funcParams = "gamma_" + sysname; - gammas.add(ParamHistFunc::createParamSet(w, funcParams.c_str(), observables, gamma_min, gamma_max)); - auto phf = std::make_unique(phfname.c_str(), phfname.c_str(), observables, gammas); - for (auto &g : gammas) { - g->setAttribute("np"); - } - - if (constraintType == "Gauss") { - for (size_t i = 0; i < vals.size(); ++i) { - TString nomname = TString::Format("nom_%s", gammas[i].GetName()); - TString poisname = TString::Format("%s_constraint", gammas[i].GetName()); - TString sname = TString::Format("%s_sigma", gammas[i].GetName()); - auto nom = std::make_unique(nomname.Data(), nomname.Data(), 1); - nom->setAttribute("glob"); - nom->setConstant(true); - nom->setRange(0, std::max(10., gamma_max)); - auto sigma = std::make_unique(sname.Data(), sname.Data(), vals[i]); - auto g = static_cast(gammas.at(i)); - auto gaus = std::make_unique(poisname.Data(), poisname.Data(), *nom, *g, *sigma); - gaus->addOwnedComponents(std::move(nom), std::move(sigma)); - constraints.add(*gaus, true); - ownedComponents.addOwned(std::move(gaus), true); - } - } else if (constraintType == "Poisson") { - for (size_t i = 0; i < vals.size(); ++i) { - double tau_float = vals[i]; - TString tname = TString::Format("%s_tau", gammas[i].GetName()); - TString nomname = TString::Format("nom_%s", gammas[i].GetName()); - TString prodname = TString::Format("%s_poisMean", gammas[i].GetName()); - TString poisname = TString::Format("%s_constraint", gammas[i].GetName()); - auto tau = std::make_unique(tname.Data(), tname.Data(), tau_float); - auto nom = std::make_unique(nomname.Data(), nomname.Data(), tau_float); - nom->setAttribute("glob"); - nom->setConstant(true); - nom->setMin(0); - RooArgSet elems{gammas[i], *tau}; - auto prod = std::make_unique(prodname.Data(), prodname.Data(), elems); - auto pois = std::make_unique(poisname.Data(), poisname.Data(), *nom, *prod); - pois->addOwnedComponents(std::move(tau), std::move(nom), std::move(prod)); - pois->setNoRounding(true); - constraints.add(*pois, true); - ownedComponents.addOwned(std::move(pois), true); - } - } else { - RooJSONFactoryWSTool::error("unknown constraint type " + constraintType); - } - for (auto &g : gammas) { - for (auto client : g->clients()) { - if (client->InheritsFrom(RooAbsPdf::Class()) && !constraints.find(*client)) { - constraints.add(*client); - } - } - } - phf->recursiveRedirectServers(observables); - // Transfer ownership of gammas and owned constraints to the ParamHistFunc - phf->addOwnedComponents(std::move(ownedComponents)); +bool hasStaterror(const JSONNode &comp) +{ + if (!comp.has_child("modifiers")) + return false; + for (const auto &mod : comp["modifiers"].children()) { + if (mod["type"].val() == ::Literals::staterror) + return true; + } + return false; +} + +bool importHistSample(RooJSONFactoryWSTool &tool, RooDataHist &dh, RooArgSet const &varlist, + RooAbsArg const *mcStatObject, const std::string &fprefix, const JSONNode &p, + RooArgList &constraints) +{ + RooWorkspace &ws = *tool.workspace(); + + std::string sampleName = RooJSONFactoryWSTool::name(p); + std::string prefixedName = fprefix + "_" + sampleName; - return phf; + std::string channelName = fprefix; + erasePrefix(channelName, "model_"); + + if (!p.has_child("data")) { + RooJSONFactoryWSTool::error("sample '" + sampleName + "' does not define a 'data' key"); } - std::unique_ptr createPHFMCStat(const std::string &name, const std::vector &sumW, - const std::vector &sumW2, RooWorkspace &w, - RooArgList &constraints, const RooArgSet &observables, - double statErrorThreshold, const std::string &statErrorType) const - { - if (sumW.empty()) - return nullptr; - - RooArgList gammas; - std::string phfname = std::string("mc_stat_") + name; - std::string sysname = std::string("stat_") + name; - std::vector vals(sumW.size()); - std::vector errs(sumW.size()); - - for (size_t i = 0; i < sumW.size(); ++i) { - errs[i] = std::sqrt(sumW2[i]) / sumW[i]; - if (statErrorType == "Gauss") { - vals[i] = std::max(errs[i], 0.); // avoid negative sigma. This NP will be set constant anyway later - } else if (statErrorType == "Poisson") { - vals[i] = sumW[i] * sumW[i] / sumW2[i]; - } - } + auto &hf = tool.wsEmplace("hist_" + prefixedName, varlist, dh); + hf.SetTitle(RooJSONFactoryWSTool::name(p).c_str()); - auto phf = createPHF(sysname, phfname, vals, w, constraints, observables, statErrorType, gammas, 0, 10); + RooArgList shapeElems; + RooArgList normElems; - // set constant NPs which are below the MC stat threshold, and remove them from the np list - for (size_t i = 0; i < sumW.size(); ++i) { - auto g = static_cast(gammas.at(i)); - g->setError(errs[i]); - if (errs[i] < statErrorThreshold) { - g->setConstant(true); // all negative errs are set constant - } - } + shapeElems.add(tool.wsEmplace(prefixedName + "_binWidth", hf, true)); - return phf; + if (hasStaterror(p)) { + shapeElems.add(*mcStatObject); } - std::unique_ptr createPHFShapeSys(const JSONNode &p, const std::string &phfname, RooWorkspace &w, - RooArgList &constraints, const RooArgSet &observables) const - { - std::string sysname(RooJSONFactoryWSTool::name(p)); - std::vector vals; - for (const auto &v : p["vals"].children()) { - vals.push_back(v.val_float()); + if (p.has_child("modifiers")) { + RooArgList overall_nps; + std::vector overall_low; + std::vector overall_high; + + RooArgList histNps; + RooArgList histoLo; + RooArgList histoHi; + + for (const auto &mod : p["modifiers"].children()) { + std::string const &modtype = mod["type"].val(); + std::string const &sysname = mod["name"].val(); + if (modtype == "staterror") { + // this is dealt with at a different place, ignore it for now + } else if (modtype == "normfactor") { + RooRealVar &constrParam = getOrCreate(ws, sysname, 1., -3, 5); + normElems.add(constrParam); + if (auto constrInfo = mod.find("constraint_name")) { + auto constraint = tool.request(constrInfo->val(), sampleName); + if (auto gauss = dynamic_cast(constraint)) { + constrParam.setError(gauss->getSigma().getVal()); + } + constraints.add(*constraint); + } + } else if (modtype == "normsys") { + auto *parameter = mod.find("parameter"); + std::string parname(parameter ? parameter->val() : "alpha_" + sysname); + createNominal(ws, parname, 0.0, -10, 10); + overall_nps.add(getOrCreate(ws, parname, 0., -5, 5)); + auto &data = mod["data"]; + // the below contains a a hack to cut off variations that go below 0 + // this is needed because with interpolation code 4, which is the default, interpolation is done in + // log-space. hence, values <= 0 result in NaN which propagate throughout the model and cause evaluations to + // fail if you know a nicer way to solve this, please go ahead and fix the lines below + overall_low.push_back(data["lo"].val_double() > 0 ? data["lo"].val_double() + : std::numeric_limits::epsilon()); + overall_high.push_back(data["hi"].val_double() > 0 ? data["hi"].val_double() + : std::numeric_limits::epsilon()); + constraints.add(getConstraint(ws, parname)); + } else if (modtype == "histosys") { + auto *parameter = mod.find("parameter"); + std::string parname(parameter ? parameter->val() : "alpha_" + sysname); + createNominal(ws, parname, 0.0, -10, 10); + histNps.add(getOrCreate(ws, parname, 0., -5, 5)); + auto &data = mod["data"]; + histoLo.add(tool.wsEmplace( + sysname + "Low_" + prefixedName, varlist, + RooJSONFactoryWSTool::readBinnedData(data["lo"], sysname + "Low_" + prefixedName, varlist))); + histoHi.add(tool.wsEmplace( + sysname + "High_" + prefixedName, varlist, + RooJSONFactoryWSTool::readBinnedData(data["hi"], sysname + "High_" + prefixedName, varlist))); + constraints.add(getConstraint(ws, parname)); + } else if (modtype == "shapesys") { + std::string funcName = channelName + "_" + sysname + "_ShapeSys"; + // funName should be "__ShapeSys" + std::vector vals; + for (const auto &v : mod["data"]["vals"].children()) { + vals.push_back(v.val_double()); + } + std::string constraint(mod["constraint"].val()); + shapeElems.add(createPHF(sysname, funcName, vals, tool, constraints, varlist, constraint, defaultGammaMin, + defaultShapeSysGammaMax, minShapeUncertainty)); + } else if (modtype == "custom") { + RooAbsReal *obj = ws.function(sysname); + if (!obj) { + RooJSONFactoryWSTool::error("unable to find custom modifier '" + sysname + "'"); + } + if (obj->dependsOn(varlist)) { + shapeElems.add(*obj); + } else { + normElems.add(*obj); + } + } else { + RooJSONFactoryWSTool::error("modifier '" + sysname + "' of unknown type '" + modtype + "'"); + } + } + + std::string interpName = sampleName + "_" + channelName + "_epsilon"; + if (!overall_nps.empty()) { + auto &v = tool.wsEmplace(interpName, overall_nps, 1., overall_low, + overall_high); + v.setAllInterpCodes(4); // default HistFactory interpCode + normElems.add(v); + } else { + RooConstVar interp(interpName.c_str(), "", 1.); + ws.import(interp); + } + if (!histNps.empty()) { + auto &v = tool.wsEmplace("histoSys_" + prefixedName, hf, histoLo, histoHi, histNps); + v.setPositiveDefinite(); + v.setAllInterpCodes(4); // default interpCode for HistFactory + shapeElems.add(v); + } else { + shapeElems.add(hf); } - RooArgList gammas; - return createPHF(sysname, phfname, vals, w, constraints, observables, p["constraint"].val(), gammas, 0, 1000); } - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override - { - RooWorkspace &ws = *tool->workspace(); + tool.wsEmplace(prefixedName + "_shapes", shapeElems); + if (!normElems.empty()) { + tool.wsEmplace(prefixedName + "_scaleFactors", normElems); + } else { + ws.factory("RooConstVar::" + prefixedName + "_scaleFactors(1.)"); + } - Scope scope; + return true; +} - std::string name(RooJSONFactoryWSTool::name(p)); - RooArgList funcs; - RooArgList coefs; - RooArgList constraints; +class HistFactoryImporter : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name = RooJSONFactoryWSTool::name(p); if (!p.has_child("samples")) { RooJSONFactoryWSTool::error("no samples in '" + name + "', skipping."); } - std::vector usesStatError; - double statErrorThreshold = 0; - std::string statErrorType = "Poisson"; - if (p.has_child("statError")) { - auto &staterr = p["statError"]; + double statErrThresh = 0; + std::string statErrType = "Poisson"; + if (p.has_child(::Literals::staterror)) { + auto &staterr = p[::Literals::staterror]; if (staterr.has_child("relThreshold")) - statErrorThreshold = staterr["relThreshold"].val_float(); + statErrThresh = staterr["relThreshold"].val_double(); if (staterr.has_child("constraint")) - statErrorType = staterr["constraint"].val(); + statErrType = staterr["constraint"].val(); } std::vector sumW; std::vector sumW2; - std::vector dummy; - std::vector sysnames; - std::vector funcnames; - std::vector coefnames; - RooArgSet observables; - if (p.has_child("observables")) { - RooJSONFactoryWSTool::getObservables(ws, p, name, observables); - scope.setObservables(observables); - } + RooArgSet observables = RooJSONFactoryWSTool::readAxes(p); + + std::string fprefix = name; + + std::vector> data; for (const auto &comp : p["samples"].children()) { - std::string fname(RooJSONFactoryWSTool::name(comp)); - auto &def = comp.is_container() ? comp : p["functions"][fname.c_str()]; - std::string fprefix = RooJSONFactoryWSTool::genPrefix(def, true); - try { - if (observables.empty()) { - RooJSONFactoryWSTool::getObservables(ws, comp["data"], fprefix, observables); - scope.setObservables(observables); + std::unique_ptr dh = RooJSONFactoryWSTool::readBinnedData( + comp["data"], fprefix + "_" + RooJSONFactoryWSTool::name(comp) + "_dataHist", observables); + size_t nbins = dh->numEntries(); + + if (hasStaterror(comp)) { + if (sumW.empty()) { + sumW.resize(nbins); + sumW2.resize(nbins); } - if (def.has_child("overallSystematics")) - ::collectNames(def["overallSystematics"], sysnames); - if (def.has_child("histogramSystematics")) - ::collectNames(def["histogramSystematics"], sysnames); - if (def.has_child("shapeSystematics")) { // ShapeSys are special case. Create PHFs here if needed - std::vector shapeSysNames; - ::collectNames(def["shapeSystematics"], shapeSysNames); - for (auto &sysname : shapeSysNames) { - std::string phfname = name + "_" + sysname + "_ShapeSys"; - auto phf = scope.getObject(phfname); - if (!phf) { - auto newphf = - createPHFShapeSys(def["shapeSystematics"][sysname], phfname, ws, constraints, observables); - ws.import(*newphf, RooFit::RecycleConflictNodes(), RooFit::Silence(true)); - scope.setObject(phfname, ws.function(phfname.c_str())); - } - } + for (size_t i = 0; i < nbins; ++i) { + sumW[i] += dh->weight(i); + sumW2[i] += dh->weightSquared(i); } - } catch (const char *s) { - RooJSONFactoryWSTool::error("function '" + name + "' unable to collect observables from function " + fname + - ". " + s); } - try { - if (comp["statError"].val_bool()) { - ::stackError(def["data"], sumW, sumW2); - } - } catch (const char *s) { - RooJSONFactoryWSTool::error("function '" + name + "' unable to sum statError from function " + fname + - ". " + s); - } - funcnames.push_back(fprefix + fname); - coefnames.push_back(fprefix + fname + "_norm"); + data.emplace_back(std::move(dh)); } - auto phf = createPHFMCStat(name, sumW, sumW2, ws, constraints, observables, statErrorThreshold, statErrorType); - if (phf) { - ws.import(*phf, RooFit::RecycleConflictNodes(), RooFit::Silence(true)); - scope.setObject("mcstat", ws.function(phf->GetName())); - } + RooAbsArg *mcStatObject = nullptr; + RooArgList constraints; + if (!sumW.empty()) { + std::string phfName = name; + erasePrefix(phfName, "model_"); + + std::vector errs(sumW.size()); + for (size_t i = 0; i < sumW.size(); ++i) { + errs[i] = std::sqrt(sumW2[i]) / sumW[i]; + // avoid negative sigma. This NP will be set constant anyway later + errs[i] = std::max(errs[i], 0.); + } - for (const auto &sampleNode : p["samples"].children()) { - importHistSample(ws, scope, sampleNode); + mcStatObject = &createPHF("stat_" + phfName, "mc_stat_" + phfName, errs, *tool, constraints, observables, + statErrType, defaultGammaMin, defaultStatErrorGammaMax, statErrThresh); } - for (const auto &fname : funcnames) { - RooAbsReal *func = tool->request(fname.c_str(), name); - funcs.add(*func); - } - for (const auto &coefname : coefnames) { - RooAbsReal *coef = tool->request(coefname.c_str(), name); - coefs.add(*coef); - } - for (auto sysname : sysnames) { - RooAbsPdf *pdf = ::getConstraint(ws, sysname.c_str()); - constraints.add(*pdf); + int idx = 0; + RooArgList funcs; + RooArgList coefs; + for (const auto &comp : p["samples"].children()) { + importHistSample(*tool, *data[idx], observables, mcStatObject, fprefix, comp, constraints); + ++idx; + + std::string const &compName = RooJSONFactoryWSTool::name(comp); + funcs.add(*tool->request(fprefix + "_" + compName + "_shapes", name)); + coefs.add(*tool->request(fprefix + "_" + compName + "_scaleFactors", name)); } + if (constraints.empty()) { - RooRealSumPdf sum(name.c_str(), name.c_str(), funcs, coefs, true); - sum.setAttribute("BinnedLikelihood"); - ws.import(sum, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsEmplace(name, funcs, coefs, true); } else { - RooRealSumPdf sum((name + "_model").c_str(), name.c_str(), funcs, coefs, true); - sum.setAttribute("BinnedLikelihood"); - ws.import(sum, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); - RooArgList lhelems; - lhelems.add(sum); - RooProdPdf prod(name.c_str(), name.c_str(), RooArgSet(constraints), RooFit::Conditional(lhelems, observables)); - ws.import(prod, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + std::string sumName = name + "_model"; + erasePrefix(sumName, "model_"); + auto &sum = tool->wsEmplace(sumName, funcs, coefs, true); + sum.SetTitle(name.c_str()); + tool->wsEmplace(name, constraints, RooFit::Conditional(sum, observables)); } - return true; } }; @@ -560,17 +431,13 @@ class FlexibleInterpVarStreamer : public RooFit::JSONIO::Exporter { } bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const RooStats::HistFactory::FlexibleInterpVar *fip = - static_cast(func); + auto fip = static_cast(func); elem["type"] << key(); - auto &vars = elem["vars"]; - vars.set_seq(); - for (const auto &v : fip->variables()) { - vars.append_child() << v->GetName(); - } + RooJSONFactoryWSTool::fillSeq(elem["vars"], fip->variables()); + elem["interpolationCodes"].fill_seq(fip->interpolationCodes()); elem["nom"] << fip->nominal(); - elem["high"] << fip->high(); - elem["low"] << fip->low(); + elem["high"].fill_seq(fip->high()); + elem["low"].fill_seq(fip->low()); return true; } }; @@ -586,41 +453,47 @@ class PiecewiseInterpolationStreamer : public RooFit::JSONIO::Exporter { { const PiecewiseInterpolation *pip = static_cast(func); elem["type"] << key(); - elem["interpolationCodes"] << pip->interpolationCodes(); - auto &vars = elem["vars"]; - vars.set_seq(); - for (const auto &v : pip->paramList()) { - vars.append_child() << v->GetName(); - } + elem["interpolationCodes"].fill_seq(pip->interpolationCodes()); + elem["positiveDefinite"] << pip->positiveDefinite(); + RooJSONFactoryWSTool::fillSeq(elem["vars"], pip->paramList()); + elem["nom"] << pip->nominalHist()->GetName(); + RooJSONFactoryWSTool::fillSeq(elem["high"], pip->highList()); + RooJSONFactoryWSTool::fillSeq(elem["low"], pip->lowList()); + return true; + } +}; + +class PiecewiseInterpolationFactory : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name(RooJSONFactoryWSTool::name(p)); - auto &nom = elem["nom"]; - nom << pip->nominalHist()->GetName(); + RooArgList vars{tool->requestArgList(p, "vars")}; - auto &high = elem["high"]; - high.set_seq(); - for (const auto &v : pip->highList()) { - high.append_child() << v->GetName(); - } + auto &pip = tool->wsEmplace(name, *tool->requestArg(p, "nom"), + tool->requestArgList(p, "low"), + tool->requestArgList(p, "high"), vars); - auto &low = elem["low"]; - low.set_seq(); - for (const auto &v : pip->lowList()) { - low.append_child() << v->GetName(); + pip.setPositiveDefinite(p["positiveDefinite"].val_bool()); + + if (p.has_child("interpolationCodes")) { + std::size_t i = 0; + for (auto const &node : p["interpolationCodes"].children()) { + pip.setInterpCode(*static_cast(vars.at(i)), node.val_int(), true); + ++i; + } } + return true; } }; -class PiecewiseInterpolationFactory : public RooFit::JSONIO::Importer { +class FlexibleInterpVarFactory : public RooFit::JSONIO::Importer { public: - bool importFunction(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { - RooWorkspace &ws = *tool->workspace(); - std::string name(RooJSONFactoryWSTool::name(p)); - if (!p.has_child("vars")) { - RooJSONFactoryWSTool::error("no vars of '" + name + "'"); - } if (!p.has_child("high")) { RooJSONFactoryWSTool::error("no high variations of '" + name + "'"); } @@ -631,316 +504,490 @@ class PiecewiseInterpolationFactory : public RooFit::JSONIO::Importer { RooJSONFactoryWSTool::error("no nominal variation of '" + name + "'"); } - std::string nomname(p["nom"].val()); - RooAbsReal *nominal = tool->request(nomname, name); + double nom(p["nom"].val_double()); - RooArgList vars; - for (const auto &d : p["vars"].children()) { - std::string objname(RooJSONFactoryWSTool::name(d)); - RooRealVar *obj = tool->request(objname, name); - vars.add(*obj); - } + RooArgList vars{tool->requestArgList(p, "vars")}; - RooArgList high; - for (const auto &d : p["high"].children()) { - std::string objname(RooJSONFactoryWSTool::name(d)); - RooAbsReal *obj = tool->request(objname, name); - high.add(*obj); - } + std::vector high; + high << p["high"]; + + std::vector low; + low << p["low"]; - RooArgList low; - for (const auto &d : p["low"].children()) { - std::string objname(RooJSONFactoryWSTool::name(d)); - RooAbsReal *obj = tool->request(objname, name); - low.add(*obj); + if (vars.size() != low.size() || vars.size() != high.size()) { + RooJSONFactoryWSTool::error("FlexibleInterpVar '" + name + + "' has non-matching lengths of 'vars', 'high' and 'low'!"); } - PiecewiseInterpolation pip(name.c_str(), name.c_str(), *nominal, low, high, vars); + auto &fip = tool->wsEmplace(name, vars, nom, low, high); if (p.has_child("interpolationCodes")) { - for (size_t i = 0; i < vars.size(); ++i) { - pip.setInterpCode(*static_cast(vars.at(i)), p["interpolationCodes"][i].val_int(), true); + size_t i = 0; + for (auto const &node : p["interpolationCodes"].children()) { + fip.setInterpCode(*static_cast(vars.at(i)), node.val_int()); + ++i; } } - ws.import(pip, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); return true; } }; -class HistFactoryStreamer : public RooFit::JSONIO::Exporter { -public: - bool autoExportDependants() const override { return false; } - void collectElements(RooArgSet &elems, RooProduct *prod) const - { +void collectElements(RooArgSet &elems, RooAbsArg *arg) +{ + if (auto prod = dynamic_cast(arg)) { for (const auto &e : prod->components()) { - if (e->InheritsFrom(RooProduct::Class())) { - collectElements(elems, (RooProduct *)e); - } else { - elems.add(*e); - } + collectElements(elems, e); } + } else { + elems.add(*arg); } - bool tryExport(const RooProdPdf *prodpdf, JSONNode &elem) const +} + +struct NormFactor { + std::string name; + RooAbsArg const *param = nullptr; + RooAbsPdf const *constraint = nullptr; + NormFactor(RooAbsArg const &par, RooAbsPdf const *constr = nullptr) + : name{par.GetName()}, param{&par}, constraint{constr} { - std::string chname(prodpdf->GetName()); - RooRealSumPdf *sumpdf = nullptr; - for (const auto &v : prodpdf->pdfList()) { - if (v->InheritsFrom(RooRealSumPdf::Class())) { - sumpdf = static_cast(v); + } +}; + +struct NormSys { + std::string name; + RooAbsArg const *param = nullptr; + double low; + double high; + TClass *constraint = RooGaussian::Class(); + NormSys(const std::string &n, RooAbsArg *const p, double h, double l, TClass *c) + : name(n), param(p), low(l), high(h), constraint(c) + { + } +}; +struct HistoSys { + std::string name; + RooAbsArg const *param = nullptr; + std::vector low; + std::vector high; + TClass *constraint = RooGaussian::Class(); + HistoSys(const std::string &n, RooAbsArg *const p, RooHistFunc *l, RooHistFunc *h, TClass *c) + : name(n), param(p), constraint(c) + { + low.assign(l->dataHist().weightArray(), l->dataHist().weightArray() + l->dataHist().numEntries()); + high.assign(h->dataHist().weightArray(), h->dataHist().weightArray() + h->dataHist().numEntries()); + } +}; +struct ShapeSys { + std::string name; + std::vector constraints; + TClass *constraint = nullptr; + ShapeSys(const std::string &n) : name{n} {} +}; +struct Sample { + std::string name; + std::vector hist; + std::vector histError; + std::vector normfactors; + std::vector normsys; + std::vector histosys; + std::vector shapesys; + std::vector otherElements; + bool useBarlowBeestonLight = false; + TClass *barlowBeestonLightConstraint = RooPoisson::Class(); + Sample(const std::string &n) : name{n} {} +}; + +void addNormFactor(RooRealVar const *par, Sample &sample, RooWorkspace *ws) +{ + std::string parname = par->GetName(); + bool isConstrained = false; + for (RooAbsArg const *pdf : ws->allPdfs()) { + if (auto gauss = dynamic_cast(pdf)) { + if (parname == gauss->getX().GetName()) { + sample.normfactors.emplace_back(*par, gauss); + isConstrained = true; } } - if (!sumpdf) + } + if (!isConstrained) + sample.normfactors.emplace_back(*par); +} + +bool tryExportHistFactory(RooJSONFactoryWSTool *tool, const std::string &pdfname, const RooRealSumPdf *sumpdf, + JSONNode &elem) +{ + RooWorkspace *ws = tool->workspace(); + RooArgSet customModifiers; + + if (!sumpdf) + return false; + + std::string chname = pdfname; + erasePrefix(chname, "model_"); + eraseSuffix(chname, "_model"); + + for (RooAbsArg *sample : sumpdf->funcList()) { + if (!dynamic_cast(sample) && !dynamic_cast(sample)) { return false; - for (const auto &sample : sumpdf->funcList()) { - if (!sample->InheritsFrom(RooProduct::Class()) && !sample->InheritsFrom(RooRealSumPdf::Class())) - return false; - } - - bool has_poisson_constraints = false; - bool has_gauss_constraints = false; - std::map tot_yield; - std::map tot_yield2; - std::map rel_errors; - std::map> bb_histograms; - std::map> nonbb_histograms; - std::vector varnames; - - for (size_t sampleidx = 0; sampleidx < sumpdf->funcList().size(); ++sampleidx) { - const auto func = sumpdf->funcList().at(sampleidx); - const auto coef = sumpdf->coefList().at(sampleidx); - std::string samplename = func->GetName(); - if (samplename.find("L_x_") == 0) - samplename = samplename.substr(4); - auto end = samplename.find("_" + chname); - if (end < samplename.size()) - samplename = samplename.substr(0, end); - - RooArgSet elems; - if (func->InheritsFrom(RooProduct::Class())) { - collectElements(elems, (RooProduct *)func); - } else { - elems.add(*func); - } - if (coef->InheritsFrom(RooProduct::Class())) { - collectElements(elems, (RooProduct *)coef); - } else { - elems.add(*coef); + } + } + + std::map tot_yield; + std::map tot_yield2; + std::map rel_errors; + RooArgSet const *varSet = nullptr; + long unsigned int nBins = 0; + + std::vector samples; + + for (size_t sampleidx = 0; sampleidx < sumpdf->funcList().size(); ++sampleidx) { + PiecewiseInterpolation *pip = nullptr; + RooStats::HistFactory::FlexibleInterpVar *fip = nullptr; + std::vector phfs; + + const auto func = sumpdf->funcList().at(sampleidx); + Sample sample(func->GetName()); + erasePrefix(sample.name, "L_x_"); + eraseSuffix(sample.name, "_shapes"); + eraseSuffix(sample.name, "_" + chname); + erasePrefix(sample.name, pdfname + "_"); + RooArgSet elems; + collectElements(elems, func); + collectElements(elems, sumpdf->coefList().at(sampleidx)); + + auto updateObservables = [&](RooDataHist const &dataHist) { + if (varSet == nullptr) { + varSet = dataHist.get(); + nBins = dataHist.numEntries(); } - std::unique_ptr hist; - std::vector phfs; - PiecewiseInterpolation *pip = nullptr; - std::vector norms; - - RooStats::HistFactory::FlexibleInterpVar *fip = nullptr; - for (const auto &e : elems) { - if (e->InheritsFrom(RooConstVar::Class())) { - if (((RooConstVar *)e)->getVal() == 1.) - continue; - norms.push_back(e); - } else if (e->InheritsFrom(RooRealVar::Class())) { - norms.push_back(e); - } else if (e->InheritsFrom(RooHistFunc::Class())) { - const RooHistFunc *hf = static_cast(e); - if (varnames.empty()) { - varnames = getVarnames(hf); - } - if (!hist) { - hist = histFunc2TH1(hf); - } - } else if (e->InheritsFrom(RooStats::HistFactory::FlexibleInterpVar::Class())) { - fip = static_cast(e); - } else if (e->InheritsFrom(PiecewiseInterpolation::Class())) { - pip = static_cast(e); - } else if (e->InheritsFrom(ParamHistFunc::Class())) { - phfs.push_back((ParamHistFunc *)e); - } + if (sample.hist.empty()) { + auto *w = dataHist.weightArray(); + sample.hist.assign(w, w + dataHist.numEntries()); } - if (pip) { - if (!hist && pip->nominalHist()->InheritsFrom(RooHistFunc::Class())) { - hist = histFunc2TH1(static_cast(pip->nominalHist())); - } - if (varnames.empty() && pip->nominalHist()->InheritsFrom(RooHistFunc::Class())) { - varnames = getVarnames(dynamic_cast(pip->nominalHist())); + }; + + for (RooAbsArg *e : elems) { + if (TString(e->GetName()).Contains("binWidth")) { + // The bin width modifiers are handled separately. We can't just + // check for the RooBinWidthFunction type here, because prior to + // ROOT 6.26, the multiplication with the inverse bin width was + // done in a different way (like a normfactor with a RooRealVar, + // but it was stored in the dataset). + // Fortunately, the name was similar, so we can match the modifier + // name. + } else if (auto constVar = dynamic_cast(e)) { + if (constVar->getVal() != 1.) { + sample.normfactors.emplace_back(*e); } + } else if (auto par = dynamic_cast(e)) { + addNormFactor(par, sample, ws); + } else if (auto hf = dynamic_cast(e)) { + updateObservables(hf->dataHist()); + } else if (auto phf = dynamic_cast(e)) { + phfs.push_back(phf); + } else if (!fip && (fip = dynamic_cast(e))) { + } else if (!pip && (pip = dynamic_cast(e))) { + } else if (auto real = dynamic_cast(e)) { + sample.otherElements.push_back(real); } - if (!hist) { - return false; - } + } - elem["name"] << chname; - elem["type"] << key(); + // see if we can get the observables + if (pip) { + if (auto nh = dynamic_cast(pip->nominalHist())) { + updateObservables(nh->dataHist()); + } + } - auto &samples = elem["samples"]; - samples.set_map(); - auto &s = samples[samplename]; - s.set_map(); + // sort and configure norms + sortByName(sample.normfactors); - for (const auto &norm : norms) { - auto &nfs = s["normFactors"]; - nfs.set_seq(); - nfs.append_child() << norm->GetName(); + // sort and configure the normsys + if (fip) { + for (size_t i = 0; i < fip->variables().size(); ++i) { + RooAbsArg *var = fip->variables().at(i); + std::string sysname(var->GetName()); + erasePrefix(sysname, "alpha_"); + sample.normsys.emplace_back(sysname, var, fip->high()[i], fip->low()[i], findConstraint(var)->IsA()); } - - if (pip) { - auto &systs = s["histogramSystematics"]; - systs.set_map(); - for (size_t i = 0; i < pip->paramList().size(); ++i) { - std::string sysname(pip->paramList().at(i)->GetName()); - if (sysname.find("alpha_") == 0) { - sysname = sysname.substr(6); - } - auto &sys = systs[sysname]; - sys.set_map(); - auto &dataLow = sys["dataLow"]; - if (pip->lowList().at(i)->InheritsFrom(RooHistFunc::Class())) { - auto histLow = histFunc2TH1(static_cast(pip->lowList().at(i))); - RooJSONFactoryWSTool::exportHistogram(*histLow, dataLow, varnames, 0, false, false); - } - auto &dataHigh = sys["dataHigh"]; - if (pip->highList().at(i)->InheritsFrom(RooHistFunc::Class())) { - auto histHigh = histFunc2TH1(static_cast(pip->highList().at(i))); - RooJSONFactoryWSTool::exportHistogram(*histHigh, dataHigh, varnames, 0, false, false); + sortByName(sample.normsys); + } + + // sort and configure the histosys + if (pip) { + for (size_t i = 0; i < pip->paramList().size(); ++i) { + RooAbsArg *var = pip->paramList().at(i); + std::string sysname(var->GetName()); + erasePrefix(sysname, "alpha_"); + if (auto lo = dynamic_cast(pip->lowList().at(i))) { + if (auto hi = dynamic_cast(pip->highList().at(i))) { + sample.histosys.emplace_back(sysname, var, lo, hi, findConstraint(var)->IsA()); } } } - - if (fip) { - auto &systs = s["overallSystematics"]; - systs.set_map(); - for (size_t i = 0; i < fip->variables().size(); ++i) { - std::string sysname(fip->variables().at(i)->GetName()); - if (sysname.find("alpha_") == 0) { - sysname = sysname.substr(6); + sortByName(sample.histosys); + } + + for (ParamHistFunc *phf : phfs) { + if (startsWith(std::string(phf->GetName()), "mc_stat_")) { // MC stat uncertainty + int idx = 0; + for (const auto &g : phf->paramList()) { + ++idx; + RooAbsPdf *constraint = findConstraint(g); + if (tot_yield.find(idx) == tot_yield.end()) { + tot_yield[idx] = 0; + tot_yield2[idx] = 0; } - auto &sys = systs[sysname]; - sys.set_map(); - sys["low"] << fip->low()[i]; - sys["high"] << fip->high()[i]; - } - } - bool has_mc_stat = false; - for (auto phf : phfs) { - if (TString(phf->GetName()).BeginsWith("mc_stat_")) { // MC stat uncertainty - has_mc_stat = true; - s["statError"] << 1; - int idx = 0; - for (const auto &g : phf->paramList()) { - ++idx; - RooPoisson *constraint_p = findClient(g); - RooGaussian *constraint_g = findClient(g); - if (tot_yield.find(idx) == tot_yield.end()) { - tot_yield[idx] = 0; - tot_yield2[idx] = 0; - } - tot_yield[idx] += hist->GetBinContent(idx); - tot_yield2[idx] += (hist->GetBinContent(idx) * hist->GetBinContent(idx)); - if (constraint_p) { + tot_yield[idx] += sample.hist[idx - 1]; + tot_yield2[idx] += (sample.hist[idx - 1] * sample.hist[idx - 1]); + if (constraint) { + sample.barlowBeestonLightConstraint = constraint->IsA(); + if (RooPoisson *constraint_p = dynamic_cast(constraint)) { double erel = 1. / std::sqrt(constraint_p->getX().getVal()); rel_errors[idx] = erel; - has_poisson_constraints = true; - } else if (constraint_g) { + } else if (RooGaussian *constraint_g = dynamic_cast(constraint)) { double erel = constraint_g->getSigma().getVal() / constraint_g->getMean().getVal(); rel_errors[idx] = erel; - has_gauss_constraints = true; + } else { + RooJSONFactoryWSTool::error( + "currently, only RooPoisson and RooGaussian are supported as constraint types"); } } - bb_histograms[samplename] = std::move(hist); - } else { // other ShapeSys - auto &shapesysts = s["shapeSystematics"]; - shapesysts.set_map(); - // Getting the name of the syst is tricky. - TString sysName(phf->GetName()); - sysName.Remove(sysName.Index("_ShapeSys")); - sysName.Remove(0, chname.size() + 1); - auto &sys = shapesysts[sysName.Data()]; - sys.set_map(); - auto &cstrts = sys["vals"]; - cstrts.set_seq(); - bool is_poisson = false; - for (const auto &g : phf->paramList()) { - RooPoisson *constraint_p = findClient(g); - RooGaussian *constraint_g = findClient(g); - if (constraint_p) { - is_poisson = true; - cstrts.append_child() << constraint_p->getX().getVal(); - } else if (constraint_g) { - is_poisson = false; - cstrts.append_child() << constraint_g->getSigma().getVal() / constraint_g->getMean().getVal(); + } + sample.useBarlowBeestonLight = true; + } else { // other ShapeSys + ShapeSys sys(phf->GetName()); + erasePrefix(sys.name, chname + "_"); + eraseSuffix(sys.name, "_ShapeSys"); + + for (const auto &g : phf->paramList()) { + RooAbsPdf *constraint = findConstraint(g); + if (!constraint) + constraint = ws->pdf(constraintName(g->GetName())); + if (!constraint && !g->isConstant()) + RooJSONFactoryWSTool::error("cannot find constraint for " + std::string(g->GetName())); + else if (!constraint) { + sys.constraints.push_back(0.0); + } else if (auto constraint_p = dynamic_cast(constraint)) { + sys.constraints.push_back(1. / std::sqrt(constraint_p->getX().getVal())); + if (!sys.constraint) { + sys.constraint = RooPoisson::Class(); + } + } else if (auto constraint_g = dynamic_cast(constraint)) { + sys.constraints.push_back(constraint_g->getSigma().getVal() / constraint_g->getMean().getVal()); + if (!sys.constraint) { + sys.constraint = RooGaussian::Class(); } - } - if (is_poisson) { - sys["constraint"] << "Poisson"; - } else { - sys["constraint"] << "Gauss"; } } + sample.shapesys.emplace_back(std::move(sys)); } - if (!has_mc_stat) { - nonbb_histograms[samplename] = std::move(hist); - s["statError"] << 0; - } - auto &ns = s["namespaces"]; - ns.set_seq(); - ns.append_child() << chname; } + sortByName(sample.shapesys); - auto &samples = elem["samples"]; - for (const auto &hist : nonbb_histograms) { - auto &s = samples[hist.first]; - auto &data = s["data"]; - RooJSONFactoryWSTool::writeObservables(*hist.second, elem, varnames); - RooJSONFactoryWSTool::exportHistogram(*hist.second, data, varnames, 0, false, false); + // add the sample + samples.emplace_back(std::move(sample)); + } + + sortByName(samples); + + for (auto &sample : samples) { + if (sample.hist.empty()) { + return false; } - for (const auto &hist : bb_histograms) { - auto &s = samples[hist.first]; + if (sample.useBarlowBeestonLight) { + sample.histError.resize(sample.hist.size()); for (auto bin : rel_errors) { // reverse engineering the correct partial error // the (arbitrary) convention used here is that all samples should have the same relative error const int i = bin.first; const double relerr_tot = bin.second; - const double count = hist.second->GetBinContent(i); - hist.second->SetBinError(i, relerr_tot * tot_yield[i] / std::sqrt(tot_yield2[i]) * count); + const double count = sample.hist[i - 1]; + // this reconstruction is inherently imprecise, so we truncate it at some decimal places to make sure that + // we don't carry around too many useless digits + sample.histError[i - 1] = round_prec(relerr_tot * tot_yield[i] / std::sqrt(tot_yield2[i]) * count, 7); } - auto &data = s["data"]; - RooJSONFactoryWSTool::writeObservables(*hist.second, elem, varnames); - RooJSONFactoryWSTool::exportHistogram(*hist.second, data, varnames, 0, false, true); } - auto &statError = elem["statError"]; - statError.set_map(); - if (has_poisson_constraints) { - statError["constraint"] << "Poisson"; - } else if (has_gauss_constraints) { - statError["constraint"] << "Gauss"; + } + + bool observablesWritten = false; + for (const auto &sample : samples) { + + elem["type"] << "histfactory_dist"; + + auto &s = RooJSONFactoryWSTool::appendNamedChild(elem["samples"], sample.name); + + auto &modifiers = s["modifiers"]; + modifiers.set_seq(); + + for (const auto &nf : sample.normfactors) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << nf.name; + mod["parameter"] << nf.param->GetName(); + mod["type"] << "normfactor"; + if (nf.constraint) { + mod["constraint_name"] << nf.constraint->GetName(); + tool->queueExport(*nf.constraint); + } + } + + for (const auto &sys : sample.normsys) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << sys.name; + mod["type"] << "normsys"; + mod["parameter"] << sys.param->GetName(); + mod["constraint"] << toString(sys.constraint); + auto &data = mod["data"].set_map(); + data["lo"] << sys.low; + data["hi"] << sys.high; + } + + for (const auto &sys : sample.histosys) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << sys.name; + mod["type"] << "histosys"; + mod["parameter"] << sys.param->GetName(); + mod["constraint"] << toString(sys.constraint); + auto &data = mod["data"].set_map(); + if (nBins != sys.low.size() || nBins != sys.high.size()) { + std::stringstream ss; + ss << "inconsistent binning: " << nBins << " bins expected, but " << sys.low.size() << "/" + << sys.high.size() << " found in nominal histogram errors!"; + RooJSONFactoryWSTool::error(ss.str().c_str()); + } + RooJSONFactoryWSTool::exportArray(nBins, sys.low.data(), data["lo"].set_map()["contents"]); + RooJSONFactoryWSTool::exportArray(nBins, sys.high.data(), data["hi"].set_map()["contents"]); + } + + for (const auto &sys : sample.shapesys) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << sys.name; + mod["type"] << "shapesys"; + mod["constraint"] << toString(sys.constraint); + if (sys.constraint) { + auto &data = mod["data"].set_map(); + auto &vals = data["vals"]; + vals.fill_seq(sys.constraints); + } + } + + for (const auto &other : sample.otherElements) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << other->GetName(); + customModifiers.add(*other); + mod["type"] << "custom"; + } + + if (sample.useBarlowBeestonLight) { + auto &mod = modifiers.append_child(); + mod.set_map(); + mod["name"] << ::Literals::staterror; + mod["type"] << ::Literals::staterror; + mod["constraint"] << toString(sample.barlowBeestonLightConstraint); + } + + if (!observablesWritten) { + auto &output = elem["axes"].set_seq(); + for (auto *obs : static_range_cast(*varSet)) { + auto &out = output.append_child().set_map(); + out["name"] << obs->GetName(); + writeAxis(out, *obs); + } + observablesWritten = true; + } + auto &dataNode = s["data"].set_map(); + if (nBins != sample.hist.size()) { + std::stringstream ss; + ss << "inconsistent binning: " << nBins << " bins expected, but " << sample.hist.size() + << " found in nominal histogram!"; + RooJSONFactoryWSTool::error(ss.str().c_str()); + } + RooJSONFactoryWSTool::exportArray(nBins, sample.hist.data(), dataNode["contents"]); + if (!sample.histError.empty()) { + if (nBins != sample.histError.size()) { + std::stringstream ss; + ss << "inconsistent binning: " << nBins << " bins expected, but " << sample.histError.size() + << " found in nominal histogram errors!"; + RooJSONFactoryWSTool::error(ss.str().c_str()); + } + RooJSONFactoryWSTool::exportArray(nBins, sample.histError.data(), dataNode["errors"]); + } + } + + // Export all the custom modifiers + for (RooAbsArg *modifier : customModifiers) { + tool->queueExport(*modifier); + } + + // Export all model parameters + RooArgSet parameters; + sumpdf->getParameters(varSet, parameters); + for (RooAbsArg *param : parameters) { + // This should exclude the global observables + if (!startsWith(std::string{param->GetName()}, "nom_")) { + tool->queueExport(*param); } - return true; } + return true; +} + +class HistFactoryStreamer_ProdPdf : public RooFit::JSONIO::Exporter { +public: + bool autoExportDependants() const override { return false; } + bool tryExport(RooJSONFactoryWSTool *tool, const RooProdPdf *prodpdf, JSONNode &elem) const + { + RooRealSumPdf *sumpdf = nullptr; + for (RooAbsArg *v : prodpdf->pdfList()) { + sumpdf = dynamic_cast(v); + } + return tryExportHistFactory(tool, prodpdf->GetName(), sumpdf, elem); + } std::string const &key() const override { - static const std::string keystring = "histfactory"; + static const std::string keystring = "histfactory_dist"; return keystring; } - bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *p, JSONNode &elem) const override + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *p, JSONNode &elem) const override { - const RooProdPdf *prodpdf = static_cast(p); - if (tryExport(prodpdf, elem)) { - return true; - } - return false; + return tryExport(tool, static_cast(p), elem); } }; -STATIC_EXECUTE( +class HistFactoryStreamer_SumPdf : public RooFit::JSONIO::Exporter { +public: + bool autoExportDependants() const override { return false; } + bool tryExport(RooJSONFactoryWSTool *tool, const RooRealSumPdf *sumpdf, JSONNode &elem) const + { + return tryExportHistFactory(tool, sumpdf->GetName(), sumpdf, elem); + } + std::string const &key() const override + { + static const std::string keystring = "histfactory_dist"; + return keystring; + } + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *p, JSONNode &elem) const override + { + return tryExport(tool, static_cast(p), elem); + } +}; +STATIC_EXECUTE([]() { using namespace RooFit::JSONIO; - registerImporter("histfactory", true); + registerImporter("histfactory_dist", true); registerImporter("interpolation", true); + registerImporter("interpolation0d", true); registerExporter(RooStats::HistFactory::FlexibleInterpVar::Class(), true); registerExporter(PiecewiseInterpolation::Class(), true); - registerExporter(RooProdPdf::Class(), true); - -) + registerExporter(RooProdPdf::Class(), true); + registerExporter(RooRealSumPdf::Class(), true); +}); } // namespace diff --git a/roofit/hs3/src/JSONFactories_RooFitCore.cxx b/roofit/hs3/src/JSONFactories_RooFitCore.cxx index df27ea0e9df81..b1076590d062a 100644 --- a/roofit/hs3/src/JSONFactories_RooFitCore.cxx +++ b/roofit/hs3/src/JSONFactories_RooFitCore.cxx @@ -17,21 +17,32 @@ #include #include #include +#include +#include #include #include #include #include #include -#include +#include +#include +#include +#include +#include +#include #include #include -#include +#include #include +#include #include #include "static_execute.h" +#include +#include + using RooFit::Detail::JSONNode; /////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -39,219 +50,292 @@ using RooFit::Detail::JSONNode; /////////////////////////////////////////////////////////////////////////////////////////////////////// namespace { +/** + * Extracts arguments from a mathematical expression. + * + * This function takes a string representing a mathematical + * expression and extracts the arguments from it. The arguments are + * defined as sequences of characters that do not contain digits, + * spaces, or parentheses, and that start with a letter. Function + * calls such as "exp( ... )", identified as being followed by an + * opening parenthesis, are not treated as arguments. The extracted + * arguments are returned as a vector of strings. + * + * @param expr A string representing a mathematical expression. + * @return A vector of strings representing the extracted arguments. + */ +std::vector extractArguments(std::string expr) +{ + // Get rid of whitespaces + expr.erase(std::remove_if(expr.begin(), expr.end(), [](unsigned char c) { return std::isspace(c); }), expr.end()); + + std::vector arguments; + size_t startidx = expr.size(); + for (size_t i = 0; i < expr.size(); ++i) { + if (startidx >= expr.size()) { + if (isalpha(expr[i])) { + startidx = i; + } + } else { + if (!isdigit(expr[i]) && !isalpha(expr[i]) && expr[i] != '_') { + if (expr[i] == '(') { + startidx = expr.size(); + continue; + } + std::string arg(expr.substr(startidx, i - startidx)); + startidx = expr.size(); + arguments.push_back(arg); + } + } + } + if (startidx < expr.size()) { + arguments.push_back(expr.substr(startidx)); + } + return arguments; +} -class RooGenericPdfFactory : public RooFit::JSONIO::Importer { +template +class RooFormulaArgFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - if (!p.has_child("dependents")) { - RooJSONFactoryWSTool::error("no dependents of '" + name + "'"); - } - if (!p.has_child("formula")) { - RooJSONFactoryWSTool::error("no formula given for '" + name + "'"); + if (!p.has_child("expression")) { + RooJSONFactoryWSTool::error("no expression given for '" + name + "'"); } + TString formula(p["expression"].val()); RooArgList dependents; - for (const auto &d : p["dependents"].children()) { - std::string objname(RooJSONFactoryWSTool::name(d)); - TObject *obj = tool->workspace()->obj(objname); - if (obj->InheritsFrom(RooAbsArg::Class())) { - dependents.add(*static_cast(obj)); - } + for (const auto &d : extractArguments(formula.Data())) { + dependents.add(*tool->request(d, name)); } - TString formula(p["formula"].val()); - RooGenericPdf thepdf(name.c_str(), formula.Data(), dependents); - tool->workspace()->import(thepdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsImport(RooArg_t{name.c_str(), formula, dependents}); return true; } }; -class RooFormulaVarFactory : public RooFit::JSONIO::Importer { +class RooAddPdfFactory : public RooFit::JSONIO::Importer { public: - bool importFunction(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - if (!p.has_child("dependents")) { - RooJSONFactoryWSTool::error("no dependents of '" + name + "'"); - } - if (!p.has_child("formula")) { - RooJSONFactoryWSTool::error("no formula given for '" + name + "'"); - } - RooArgList dependents; - for (const auto &d : p["dependents"].children()) { - std::string objname(RooJSONFactoryWSTool::name(d)); - TObject *obj = tool->workspace()->obj(objname); - if (obj->InheritsFrom(RooAbsArg::Class())) { - dependents.add(*static_cast(obj)); - } - } - TString formula(p["formula"].val()); - RooFormulaVar thevar(name.c_str(), formula.Data(), dependents); - tool->workspace()->import(thevar, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsEmplace(name, tool->requestArgList(p, "summands"), + tool->requestArgList(p, "coefficients")); return true; } }; -class RooProdPdfFactory : public RooFit::JSONIO::Importer { +class RooBinWidthFunctionFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - RooArgSet factors; - if (!p.has_child("pdfs")) { - RooJSONFactoryWSTool::error("no pdfs of '" + name + "'"); - } - if (!p["pdfs"].is_seq()) { - RooJSONFactoryWSTool::error("pdfs '" + name + "' are not a list."); - } - for (const auto &comp : p["pdfs"].children()) { - std::string pdfname(comp.val()); - RooAbsPdf *pdf = tool->request(pdfname, name); - factors.add(*pdf); - } - RooProdPdf prod(name.c_str(), name.c_str(), factors); - tool->workspace()->import(prod, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + RooHistFunc *hf = static_cast(tool->request(p["histogram"].val(), name)); + tool->wsEmplace(name, *hf, p["divideByBinWidth"].val_bool()); return true; } }; -class RooAddPdfFactory : public RooFit::JSONIO::Importer { +class RooBinSamplingPdfFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - RooArgList pdfs; - RooArgList coefs; - if (!p.has_child("summands")) { - RooJSONFactoryWSTool::error("no summands of '" + name + "'"); - } - if (!p["summands"].is_seq()) { - RooJSONFactoryWSTool::error("summands '" + name + "' are not a list."); - } - if (!p.has_child("coefficients")) { - RooJSONFactoryWSTool::error("no coefficients of '" + name + "'"); - } - if (!p["coefficients"].is_seq()) { - RooJSONFactoryWSTool::error("coefficients '" + name + "' are not a list."); + + RooAbsPdf *pdf = tool->requestArg(p, "pdf"); + RooRealVar *obs = tool->requestArg(p, "observable"); + + if (!pdf->dependsOn(*obs)) { + RooJSONFactoryWSTool::error(std::string("pdf '") + pdf->GetName() + "' does not depend on observable '" + + obs->GetName() + "' as indicated by parent RooBinSamplingPdf '" + name + + "', please check!"); } - for (const auto &comp : p["summands"].children()) { - std::string pdfname(comp.val()); - RooAbsPdf *pdf = tool->request(pdfname, name); - pdfs.add(*pdf); + + if (!p.has_child("epsilon")) { + RooJSONFactoryWSTool::error("no epsilon given in '" + name + "'"); } - for (const auto &comp : p["coefficients"].children()) { - std::string coefname(comp.val()); - RooAbsReal *coef = tool->request(coefname, name); - coefs.add(*coef); + double epsilon(p["epsilon"].val_double()); + + tool->wsEmplace(name, *obs, *pdf, epsilon); + + return true; + } +}; + +class RooRealSumPdfFactory : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name(RooJSONFactoryWSTool::name(p)); + + bool extended = false; + if (p.has_child("extended") && p["extended"].val_bool()) { + extended = true; } - RooAddPdf add(name.c_str(), name.c_str(), pdfs, coefs); - tool->workspace()->import(add, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsEmplace(name, tool->requestArgList(p, "samples"), + tool->requestArgList(p, "coefficients"), extended); return true; } }; -class RooBinWidthFunctionFactory : public RooFit::JSONIO::Importer { +class RooRealSumFuncFactory : public RooFit::JSONIO::Importer { public: - bool importFunction(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - bool divideByBinWidth = p["divideByBinWidth"].val_bool(); - RooHistFunc *hf = dynamic_cast(tool->request(p["histogram"].val(), name)); - RooBinWidthFunction func(name.c_str(), name.c_str(), *hf, divideByBinWidth); - tool->workspace()->import(func, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsEmplace(name, tool->requestArgList(p, "samples"), + tool->requestArgList(p, "coefficients")); return true; } }; -class RooSimultaneousFactory : public RooFit::JSONIO::Importer { +class RooPolynomialFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - if (!p.has_child("channels")) { - RooJSONFactoryWSTool::error("no channel components of '" + name + "'"); + if (!p.has_child("coefficients")) { + RooJSONFactoryWSTool::error("no coefficients given in '" + name + "'"); } - std::map components; - std::string indexname(p["index"].val()); - RooCategory cat(indexname.c_str(), indexname.c_str()); - for (const auto &comp : p["channels"].children()) { - std::string catname(RooJSONFactoryWSTool::name(comp)); - RooJSONFactoryWSTool::log(RooFit::INFO) << "importing category " << catname << std::endl; - std::string pdfname(comp.has_val() ? comp.val() : RooJSONFactoryWSTool::name(comp)); - RooAbsPdf *pdf = tool->request(pdfname, name); - components[catname] = pdf; - cat.defineType(catname.c_str()); + RooAbsReal *x = tool->requestArg(p, "x"); + RooArgList coefs; + int order = 0; + int lowestOrder = 0; + for (const auto &coef : p["coefficients"].children()) { + // As long as the coefficients match the default coefficients in + // RooFit, we don't have to instantiate RooFit objects but can + // increase the lowestOrder flag. + if (order == 0 && coef.val() == "1.0") { + ++lowestOrder; + } else if (coefs.empty() && coef.val() == "0.0") { + ++lowestOrder; + } else { + coefs.add(*tool->request(coef.val(), name)); + } + ++order; } - RooSimultaneous simpdf(name.c_str(), name.c_str(), components, cat); - tool->workspace()->import(simpdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + + tool->wsEmplace(name, *x, coefs, lowestOrder); return true; } }; -class RooBinSamplingPdfFactory : public RooFit::JSONIO::Importer { +class RooPoissonFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); + RooAbsReal *x = tool->requestArg(p, "x"); + RooAbsReal *mean = tool->requestArg(p, "mean"); + tool->wsEmplace(name, *x, *mean, !p["integer"].val_bool()); + return true; + } +}; - if (!p.has_child("pdf")) { - RooJSONFactoryWSTool::error("no pdf given in '" + name + "'"); - } - std::string pdfname(p["pdf"].val()); - RooAbsPdf *pdf = tool->request(pdfname, name); - - if (!p.has_child("observable")) { - RooJSONFactoryWSTool::error("no observable given in '" + name + "'"); - } - std::string obsname(p["observable"].val()); - RooRealVar *obs = tool->request(obsname, name); - - if (!pdf->dependsOn(*obs)) { - pdf->Print("t"); - RooJSONFactoryWSTool::error("pdf '" + pdfname + "' does not depend on observable '" + obsname + - "' as indicated by parent RooBinSamplingPdf '" + name + "', please check!"); - } +class RooLogNormalFactory : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name(RooJSONFactoryWSTool::name(p)); + RooAbsReal *x = tool->requestArg(p, "x"); + RooAbsReal *mu = tool->requestArg(p, "mu"); + RooAbsReal *sigma = tool->requestArg(p, "sigma"); - if (!p.has_child("epsilon")) { - RooJSONFactoryWSTool::error("no epsilon given in '" + name + "'"); - } - double epsilon(p["epsilon"].val_float()); + // TODO: check if the pdf was originally exported by ROOT, in which case + // it can be imported back without using the standard parametrization. + tool->wsEmplace(name, *x, *mu, *sigma, true); + return true; + } +}; - RooBinSamplingPdf thepdf(name.c_str(), name.c_str(), *obs, *pdf, epsilon); - tool->workspace()->import(thepdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); +class RooExponentialFactory : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name(RooJSONFactoryWSTool::name(p)); + RooAbsReal *x = tool->requestArg(p, "x"); + RooAbsReal *c = tool->requestArg(p, "c"); + // TODO: check if the pdf was originally exported by ROOT, in which case + // it can be imported back without using the standard parametrization. + tool->wsEmplace(name, *x, *c, true); return true; } }; -class RooRealSumPdfFactory : public RooFit::JSONIO::Importer { +class RooExpPolyFactory : public RooFit::JSONIO::Importer { public: - bool importPdf(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { std::string name(RooJSONFactoryWSTool::name(p)); - if (!p.has_child("samples")) { - RooJSONFactoryWSTool::error("no samples given in '" + name + "'"); - } if (!p.has_child("coefficients")) { RooJSONFactoryWSTool::error("no coefficients given in '" + name + "'"); } - RooArgList samples; - for (const auto &sample : p["samples"].children()) { - RooAbsReal *s = tool->request(sample.val(), name); - samples.add(*s); - } - RooArgList coefficients; + RooAbsReal *x = tool->requestArg(p, "x"); + RooArgList coefs; + int order = 0; + int lowestOrder = 0; for (const auto &coef : p["coefficients"].children()) { - RooAbsReal *c = tool->request(coef.val(), name); - coefficients.add(*c); + // As long as the coefficients match the default coefficients in + // RooFit, we don't have to instantiate RooFit objects but can + // increase the lowestOrder flag. + if (order == 0 && coef.val() == "1.0") { + ++lowestOrder; + } else if (coefs.empty() && coef.val() == "0.0") { + ++lowestOrder; + } else { + coefs.add(*tool->request(coef.val(), name)); + } + ++order; } - bool extended = false; - if (p.has_child("extended") && p["extended"].val_bool()) { - extended = true; + tool->wsEmplace(name, *x, coefs, lowestOrder); + return true; + } +}; + +class RooMultiVarGaussianFactory : public RooFit::JSONIO::Importer { +public: + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name(RooJSONFactoryWSTool::name(p)); + bool has_cov = p.has_child("covariances"); + bool has_corr = p.has_child("correlations") && p.has_child("standard_deviations"); + if (!has_cov && !has_corr) { + RooJSONFactoryWSTool::error("no covariances or correlations+standard_deviations given in '" + name + "'"); + } + + TMatrixDSym covmat; + + if (has_cov) { + int n = p["covariances"].num_children(); + int i = 0; + covmat.ResizeTo(n, n); + for (const auto &row : p["covariances"].children()) { + int j = 0; + for (const auto &val : row.children()) { + covmat(i, j) = val.val_double(); + ++j; + } + ++i; + } + } else { + std::vector variances; + for (const auto &v : p["standard_deviations"].children()) { + variances.push_back(v.val_double()); + } + covmat.ResizeTo(variances.size(), variances.size()); + int i = 0; + for (const auto &row : p["correlations"].children()) { + int j = 0; + for (const auto &val : row.children()) { + covmat(i, j) = val.val_double() * variances[i] * variances[j]; + ++j; + } + ++i; + } } - RooRealSumPdf thepdf(name.c_str(), name.c_str(), samples, coefficients, extended); - tool->workspace()->import(thepdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + tool->wsEmplace(name, tool->requestArgList(p, "x"), + tool->requestArgList(p, "mean"), covmat); return true; } }; @@ -260,109 +344,106 @@ class RooRealSumPdfFactory : public RooFit::JSONIO::Importer { // specialized exporter implementations /////////////////////////////////////////////////////////////////////////////////////////////////////// -class RooRealSumPdfStreamer : public RooFit::JSONIO::Exporter { +class RooAddPdfStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const static std::string keystring = "sumpdf"; - return keystring; + const RooAddPdf *pdf = static_cast(func); + elem["type"] << key(); + RooJSONFactoryWSTool::fillSeq(elem["summands"], pdf->pdfList()); + RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList()); + elem["extended"] << (pdf->extendMode() != RooAbsPdf::CanNotBeExtended); + return true; } +}; + +class RooRealSumPdfStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { const RooRealSumPdf *pdf = static_cast(func); elem["type"] << key(); - auto &samples = elem["samples"]; - samples.set_seq(); - auto &coefs = elem["coefficients"]; - coefs.set_seq(); - for (const auto &s : pdf->funcList()) { - samples.append_child() << s->GetName(); - } - for (const auto &c : pdf->coefList()) { - coefs.append_child() << c->GetName(); - } - elem["extended"] << (pdf->extendMode() == RooAbsPdf::CanBeExtended); + RooJSONFactoryWSTool::fillSeq(elem["samples"], pdf->funcList()); + RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList()); + elem["extended"] << (pdf->extendMode() != RooAbsPdf::CanNotBeExtended); return true; } }; -class RooSimultaneousStreamer : public RooFit::JSONIO::Exporter { +class RooRealSumFuncStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override - { - const static std::string keystring = "simultaneous"; - return keystring; - } + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const RooSimultaneous *sim = static_cast(func); + const RooRealSumFunc *pdf = static_cast(func); elem["type"] << key(); - elem["index"] << sim->indexCat().GetName(); - auto &channels = elem["channels"]; - channels.set_map(); - const auto &indexCat = sim->indexCat(); - for (const auto &cat : indexCat) { - const auto catname = cat.first.c_str(); - RooAbsPdf *pdf = sim->getPdf(catname); - if (!pdf) - RooJSONFactoryWSTool::error("no pdf found for category"); - channels[catname] << pdf->GetName(); - } + RooJSONFactoryWSTool::fillSeq(elem["samples"], pdf->funcList()); + RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList()); return true; } }; class RooHistFuncStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override - { - static const std::string keystring = "histogram"; - return keystring; - } - bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem) const override { const RooHistFunc *hf = static_cast(func); - const RooDataHist &dh = hf->dataHist(); elem["type"] << key(); - RooArgList vars(*dh.get()); - std::unique_ptr hist{hf->createHistogram(RooJSONFactoryWSTool::concat(&vars).c_str())}; - auto &data = elem["data"]; - RooJSONFactoryWSTool::exportHistogram(*hist, data, RooJSONFactoryWSTool::names(&vars)); + RooDataHist const &dh = hf->dataHist(); + tool->exportHisto(*dh.get(), dh.numEntries(), dh.weightArray(), elem["data"].set_map()); return true; } }; class RooHistFuncFactory : public RooFit::JSONIO::Importer { public: - bool importFunction(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { - RooWorkspace &ws = *tool->workspace(); - std::string name(RooJSONFactoryWSTool::name(p)); if (!p.has_child("data")) { RooJSONFactoryWSTool::error("function '" + name + "' is of histogram type, but does not define a 'data' key"); } - RooArgSet varlist; - RooJSONFactoryWSTool::getObservables(ws, p["data"], name, varlist); - RooDataHist *dh = dynamic_cast(ws.embeddedData(name)); - if (!dh) { - auto dhForImport = RooJSONFactoryWSTool::readBinnedData(ws, p["data"], name, varlist); - ws.import(*dhForImport, RooFit::Silence(true), RooFit::Embedded()); - dh = static_cast(ws.embeddedData(dhForImport->GetName())); - } - RooHistFunc hf(name.c_str(), name.c_str(), *(dh->get()), *dh); - ws.import(hf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + std::unique_ptr dataHist = + RooJSONFactoryWSTool::readBinnedData(p["data"], name, RooJSONFactoryWSTool::readAxes(p["data"])); + tool->wsEmplace(name, *dataHist->get(), *dataHist); return true; } }; -class RooBinSamplingPdfStreamer : public RooFit::JSONIO::Exporter { +class RooHistPdfStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem) const override + { + const RooHistPdf *hf = static_cast(func); + elem["type"] << key(); + RooDataHist const &dh = hf->dataHist(); + tool->exportHisto(*dh.get(), dh.numEntries(), dh.weightArray(), elem["data"].set_map()); + return true; + } +}; + +class RooHistPdfFactory : public RooFit::JSONIO::Importer { public: - std::string const &key() const override + bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { - static const std::string keystring = "binsampling"; - return keystring; + std::string name(RooJSONFactoryWSTool::name(p)); + if (!p.has_child("data")) { + RooJSONFactoryWSTool::error("function '" + name + "' is of histogram type, but does not define a 'data' key"); + } + std::unique_ptr dataHist = + RooJSONFactoryWSTool::readBinnedData(p["data"], name, RooJSONFactoryWSTool::readAxes(p["data"])); + tool->wsEmplace(name, *dataHist->get(), *dataHist); + return true; } +}; + +class RooBinSamplingPdfStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { const RooBinSamplingPdf *pdf = static_cast(func); @@ -374,107 +455,244 @@ class RooBinSamplingPdfStreamer : public RooFit::JSONIO::Exporter { } }; -class RooProdPdfStreamer : public RooFit::JSONIO::Exporter { +class RooBinWidthFunctionStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - static const std::string keystring = "pdfprod"; - return keystring; + const RooBinWidthFunction *pdf = static_cast(func); + elem["type"] << key(); + elem["histogram"] << pdf->histFunc().GetName(); + elem["divideByBinWidth"] << pdf->divideByBinWidth(); + return true; } +}; + +template +class RooFormulaArgStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const RooProdPdf *pdf = static_cast(func); + const RooArg_t *pdf = static_cast(func); elem["type"] << key(); - auto &factors = elem["pdfs"]; - for (const auto &f : pdf->pdfList()) { - factors.append_child() << f->GetName(); - } + TString expression(pdf->expression()); + for (size_t i = 0; i < pdf->nParameters(); ++i) { + RooAbsArg *par = pdf->getParameter(i); + std::stringstream ss_1; + ss_1 << "x[" << i << "]"; + std::stringstream ss_2; + ss_2 << "@" << i << ""; + expression.ReplaceAll(ss_1.str().c_str(), par->GetName()); + expression.ReplaceAll(ss_2.str().c_str(), par->GetName()); + } + elem["expression"] << expression.Data(); return true; } }; -class RooGenericPdfStreamer : public RooFit::JSONIO::Exporter { +class RooPolynomialStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - static const std::string keystring = "genericpdf"; - return keystring; + auto *pdf = static_cast(func); + elem["type"] << key(); + elem["x"] << pdf->x().GetName(); + auto &coefs = elem["coefficients"].set_seq(); + // Write out the default coefficient that RooFit uses for the lower + // orders before the order of the first coefficient. Like this, the + // output is more self-documenting. + for (int i = 0; i < pdf->lowestOrder(); ++i) { + coefs.append_child() << (i == 0 ? "1.0" : "0.0"); + } + for (const auto &coef : pdf->coefList()) { + coefs.append_child() << coef->GetName(); + } + return true; } +}; + +class RooExpPolyStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const RooGenericPdf *pdf = static_cast(func); + auto *pdf = static_cast(func); elem["type"] << key(); - elem["formula"] << pdf->expression(); - auto &factors = elem["dependents"]; - for (const auto &f : pdf->dependents()) { - factors.append_child() << f->GetName(); + elem["x"] << pdf->x().GetName(); + auto &coefs = elem["coefficients"].set_seq(); + // Write out the default coefficient that RooFit uses for the lower + // orders before the order of the first coefficient. Like this, the + // output is more self-documenting. + for (int i = 0; i < pdf->lowestOrder(); ++i) { + coefs.append_child() << (i == 0 ? "1.0" : "0.0"); + } + for (const auto &coef : pdf->coefList()) { + coefs.append_child() << coef->GetName(); } return true; } }; -class RooBinWidthFunctionStreamer : public RooFit::JSONIO::Exporter { +class RooPoissonStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - static const std::string keystring = "binwidth"; - return keystring; + auto *pdf = static_cast(func); + elem["type"] << key(); + elem["x"] << pdf->getX().GetName(); + elem["mean"] << pdf->getMean().GetName(); + elem["integer"] << !pdf->getNoRounding(); + return true; } - bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override +}; + +class RooLogNormalStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem) const override { - const RooBinWidthFunction *pdf = static_cast(func); + auto *pdf = static_cast(func); + elem["type"] << key(); - elem["histogram"] << pdf->histFunc().GetName(); - elem["divideByBinWidth"] << pdf->divideByBinWidth(); + elem["x"] << pdf->getX().GetName(); + + auto &m0 = pdf->getMedian(); + auto &k = pdf->getShapeK(); + + if(pdf->useStandardParametrization()) { + elem["mu"] << m0.GetName(); + elem["sigma"] << k.GetName(); + } else { + elem["mu"] << tool->exportTransformed(&m0, "lognormal", "log", "log(%s)"); + elem["sigma"] << tool->exportTransformed(&k, "lognormal", "log", "log(%s)"); + } + return true; } }; -class RooFormulaVarStreamer : public RooFit::JSONIO::Exporter { +class RooExponentialStreamer : public RooFit::JSONIO::Exporter { public: - std::string const &key() const override + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem) const override { - static const std::string keystring = "formulavar"; - return keystring; + auto *pdf = static_cast(func); + elem["type"] << key(); + elem["x"] << pdf->variable().GetName(); + auto &c = pdf->coefficient(); + if (pdf->negateCoefficient()) { + elem["c"] << c.GetName(); + } else { + elem["c"] << tool->exportTransformed(&c, "exponential", "inverted", "-%s"); + } + + return true; } +}; + +class RooMultiVarGaussianStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override { - const RooFormulaVar *var = static_cast(func); + auto *pdf = static_cast(func); elem["type"] << key(); - elem["formula"] << var->expression(); - auto &factors = elem["dependents"]; - for (const auto &f : var->dependents()) { - factors.append_child() << f->GetName(); + RooJSONFactoryWSTool::fillSeq(elem["x"], pdf->xVec()); + RooJSONFactoryWSTool::fillSeq(elem["mean"], pdf->muVec()); + elem["covariances"].fill_mat(pdf->covarianceMatrix()); + return true; + } +}; + +class RooTFnBindingStreamer : public RooFit::JSONIO::Exporter { +public: + std::string const &key() const override; + bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override + { + auto *pdf = static_cast(func); + elem["type"] << key(); + + TString formula(pdf->function().GetExpFormula()); + formula.ReplaceAll("x", pdf->observables()[0].GetName()); + formula.ReplaceAll("y", pdf->observables()[1].GetName()); + formula.ReplaceAll("z", pdf->observables()[2].GetName()); + for (size_t i = 0; i < pdf->parameters().size(); ++i) { + TString pname(TString::Format("[%d]", (int)i)); + formula.ReplaceAll(pname, pdf->parameters()[i].GetName()); } + elem["expression"] << formula.Data(); return true; } }; +#define DEFINE_EXPORTER_KEY(class_name, name) \ + std::string const &class_name::key() const \ + { \ + const static std::string keystring = name; \ + return keystring; \ + } + +DEFINE_EXPORTER_KEY(RooAddPdfStreamer, "mixture_dist"); +DEFINE_EXPORTER_KEY(RooBinSamplingPdfStreamer, "binsampling"); +DEFINE_EXPORTER_KEY(RooBinWidthFunctionStreamer, "binwidth"); +DEFINE_EXPORTER_KEY(RooExpPolyStreamer, "exp_poly_dist"); +DEFINE_EXPORTER_KEY(RooExponentialStreamer, "exponential_dist"); +template <> +DEFINE_EXPORTER_KEY(RooFormulaArgStreamer, "generic_function"); +template <> +DEFINE_EXPORTER_KEY(RooFormulaArgStreamer, "generic_dist"); +DEFINE_EXPORTER_KEY(RooHistFuncStreamer, "histogram"); +DEFINE_EXPORTER_KEY(RooHistPdfStreamer, "histogram_dist"); +DEFINE_EXPORTER_KEY(RooLogNormalStreamer, "lognormal_dist"); +DEFINE_EXPORTER_KEY(RooMultiVarGaussianStreamer, "multivariate_normal_dist"); +DEFINE_EXPORTER_KEY(RooPoissonStreamer, "poisson_dist"); +DEFINE_EXPORTER_KEY(RooPolynomialStreamer, "polynomial_dist"); +DEFINE_EXPORTER_KEY(RooRealSumFuncStreamer, "weighted_sum"); +DEFINE_EXPORTER_KEY(RooRealSumPdfStreamer, "weighted_sum_dist"); +DEFINE_EXPORTER_KEY(RooTFnBindingStreamer, "generic_function"); + /////////////////////////////////////////////////////////////////////////////////////////////////////// // instantiate all importers and exporters /////////////////////////////////////////////////////////////////////////////////////////////////////// -STATIC_EXECUTE( - +STATIC_EXECUTE([]() { using namespace RooFit::JSONIO; - registerImporter("pdfprod", false); registerImporter("genericpdf", false); - registerImporter("formulavar", false); - registerImporter("binsampling", false); - registerImporter("pdfsum", false); registerImporter("histogram", false); - registerImporter("simultaneous", false); + registerImporter("mixture_dist", false); + registerImporter("binsampling_dist", false); registerImporter("binwidth", false); - registerImporter("sumpdf", false); - - registerExporter(RooBinWidthFunction::Class(), false); - registerExporter(RooProdPdf::Class(), false); - registerExporter(RooSimultaneous::Class(), false); + registerImporter("exp_poly_dist", false); + registerImporter("exponential_dist", false); + registerImporter>("generic_function", false); + registerImporter>("generic_dist", false); + registerImporter("histogram", false); + registerImporter("histogram_dist", false); + registerImporter("lognormal_dist", false); + registerImporter("multivariate_normal_dist", false); + registerImporter("poisson_dist", false); + registerImporter("polynomial_dist", false); + registerImporter("weighted_sum_dist", false); + registerImporter("weighted_sum", false); + + registerExporter(RooAddPdf::Class(), false); registerExporter(RooBinSamplingPdf::Class(), false); + registerExporter(RooBinWidthFunction::Class(), false); + registerExporter(RooExpPoly::Class(), false); + registerExporter(RooExponential::Class(), false); + registerExporter>(RooFormulaVar::Class(), false); + registerExporter>(RooGenericPdf::Class(), false); registerExporter(RooHistFunc::Class(), false); - registerExporter(RooGenericPdf::Class(), false); - registerExporter(RooFormulaVar::Class(), false); + registerExporter(RooHistPdf::Class(), false); + registerExporter(RooLognormal::Class(), false); + registerExporter(RooMultiVarGaussian::Class(), false); + registerExporter(RooPoisson::Class(), false); + registerExporter(RooPolynomial::Class(), false); + registerExporter(RooRealSumFunc::Class(), false); registerExporter(RooRealSumPdf::Class(), false); - -) + registerExporter(RooTFnBinding::Class(), false); +}); } // namespace diff --git a/roofit/hs3/src/JSONIO.cxx b/roofit/hs3/src/JSONIO.cxx index b611e29d7dfc8..c63a534200e05 100644 --- a/roofit/hs3/src/JSONIO.cxx +++ b/roofit/hs3/src/JSONIO.cxx @@ -13,11 +13,11 @@ #include #include -#include #include #include +#include #include #include @@ -25,6 +25,20 @@ namespace RooFit { namespace JSONIO { +void setupKeys() +{ + static bool isAlreadySetup = false; + if (isAlreadySetup) { + return; + } + + isAlreadySetup = true; + + auto etcDir = std::string(TROOT::GetEtcDir()); + loadExportKeys(etcDir + "/RooFitHS3_wsexportkeys.json"); + loadFactoryExpressions(etcDir + "/RooFitHS3_wsfactoryexpressions.json"); +} + ImportMap &importers() { static ImportMap _importers; @@ -37,20 +51,16 @@ ExportMap &exporters() return _exporters; } -ImportExpressionMap &pdfImportExpressions() +ImportExpressionMap &importExpressions() { - static ImportExpressionMap _pdfFactoryExpressions; - return _pdfFactoryExpressions; -} - -ImportExpressionMap &functionImportExpressions() -{ - static ImportExpressionMap _funcFactoryExpressions; - return _funcFactoryExpressions; + setupKeys(); + static ImportExpressionMap _factoryExpressions; + return _factoryExpressions; } ExportKeysMap &exportKeys() { + setupKeys(); static ExportKeysMap _exportKeys; return _exportKeys; } @@ -124,8 +134,7 @@ void printExporters() void loadFactoryExpressions(const std::string &fname) { - auto &pdfFactoryExpressions = RooFit::JSONIO::pdfImportExpressions(); - auto &funcFactoryExpressions = RooFit::JSONIO::functionImportExpressions(); + auto &factoryExpressions = RooFit::JSONIO::importExpressions(); // load a yml file defining the factory expressions std::ifstream infile(fname); @@ -133,65 +142,45 @@ void loadFactoryExpressions(const std::string &fname) std::cerr << "unable to read file '" << fname << "'" << std::endl; return; } - try { - std::unique_ptr tree = RooFit::Detail::JSONTree::create(infile); - const RooFit::Detail::JSONNode &n = tree->rootnode(); - for (const auto &cl : n.children()) { - std::string key(RooJSONFactoryWSTool::name(cl)); - if (!cl.has_child("class")) { - std::cerr << "error in file '" << fname << "' for entry '" << key << "': 'class' key is required!" - << std::endl; - continue; - } - std::string classname(cl["class"].val()); - TClass *c = TClass::GetClass(classname.c_str()); - if (!c) { - std::cerr << "unable to find class " << classname << ", skipping." << std::endl; - } else { - RooFit::JSONIO::ImportExpression ex; - ex.tclass = c; - if (!cl.has_child("arguments")) { - std::cerr << "class " << classname << " seems to have no arguments attached, skipping" << std::endl; - continue; - } - for (const auto &arg : cl["arguments"].children()) { - ex.arguments.push_back(arg.val()); - } - if (c->InheritsFrom(RooAbsPdf::Class())) { - pdfFactoryExpressions[key] = ex; - } else if (c->InheritsFrom(RooAbsReal::Class())) { - funcFactoryExpressions[key] = ex; - } else { - std::cerr << "class " << classname << " seems to not inherit from any suitable class, skipping" - << std::endl; - } - } + + std::unique_ptr tree = RooFit::Detail::JSONTree::create(infile); + const RooFit::Detail::JSONNode &n = tree->rootnode(); + for (const auto &cl : n.children()) { + std::string key = cl.key(); + if (!cl.has_child("class")) { + std::cerr << "error in file '" << fname << "' for entry '" << key << "': 'class' key is required!" + << std::endl; + continue; + } + std::string classname(cl["class"].val()); + TClass *c = TClass::GetClass(classname.c_str()); + if (!c) { + std::cerr << "unable to find class " << classname << ", skipping." << std::endl; + continue; } - } catch (const std::exception &ex) { - std::cout << "caught" << std::endl; - std::cerr << "unable to load factory expressions: " << ex.what() << std::endl; + RooFit::JSONIO::ImportExpression ex; + ex.tclass = c; + if (!cl.has_child("arguments")) { + std::cerr << "class " << classname << " seems to have no arguments attached, skipping" << std::endl; + continue; + } + for (const auto &arg : cl["arguments"].children()) { + ex.arguments.push_back(arg.val()); + } + factoryExpressions[key] = ex; } } void clearFactoryExpressions() { // clear all factory expressions - RooFit::JSONIO::pdfImportExpressions().clear(); - RooFit::JSONIO::functionImportExpressions().clear(); + RooFit::JSONIO::importExpressions().clear(); } void printFactoryExpressions() { // print all factory expressions - for (auto it : RooFit::JSONIO::pdfImportExpressions()) { - std::cout << it.first; - std::cout << " " << it.second.tclass->GetName(); - for (auto v : it.second.arguments) { - std::cout << " " << v; - } - std::cout << std::endl; - } - for (auto it : RooFit::JSONIO::functionImportExpressions()) { + for (auto it : RooFit::JSONIO::importExpressions()) { std::cout << it.first; std::cout << " " << it.second.tclass->GetName(); for (auto v : it.second.arguments) { @@ -215,35 +204,32 @@ void loadExportKeys(const std::string &fname) std::cerr << "unable to read file '" << fname << "'" << std::endl; return; } - try { - std::unique_ptr tree = RooFit::Detail::JSONTree::create(infile); - const RooFit::Detail::JSONNode &n = tree->rootnode(); - for (const auto &cl : n.children()) { - std::string classname(RooJSONFactoryWSTool::name(cl)); - TClass *c = TClass::GetClass(classname.c_str()); - if (!c) { - std::cerr << "unable to find class " << classname << ", skipping." << std::endl; - } else { - RooFit::JSONIO::ExportKeys ex; - if (!cl.has_child("type")) { - std::cerr << "class " << classname << "has not type key set, skipping" << std::endl; - continue; - } - if (!cl.has_child("proxies")) { - std::cerr << "class " << classname << "has no proxies identified, skipping" << std::endl; - continue; - } - ex.type = cl["type"].val(); - for (const auto &k : cl["proxies"].children()) { - std::string key(RooJSONFactoryWSTool::name(k)); - std::string val(k.val()); - ex.proxies[key] = val; - } - exportKeys[c] = ex; - } + + std::unique_ptr tree = RooFit::Detail::JSONTree::create(infile); + const RooFit::Detail::JSONNode &n = tree->rootnode(); + for (const auto &cl : n.children()) { + std::string classname = cl.key(); + TClass *c = TClass::GetClass(classname.c_str()); + if (!c) { + std::cerr << "unable to find class " << classname << ", skipping." << std::endl; + continue; + } + RooFit::JSONIO::ExportKeys ex; + auto *type = cl.find("type"); + auto *proxies = cl.find("proxies"); + if (!type) { + std::cerr << "class " << classname << "has not type key set, skipping" << std::endl; + continue; + } + if (!proxies) { + std::cerr << "class " << classname << "has no proxies identified, skipping" << std::endl; + continue; + } + ex.type = type->val(); + for (const auto &k : proxies->children()) { + ex.proxies[k.key()] = k.val(); } - } catch (const std::exception &ex) { - std::cerr << "unable to load export keys: " << ex.what() << std::endl; + exportKeys[c] = ex; } } diff --git a/roofit/hs3/src/JSONIOUtils.cxx b/roofit/hs3/src/JSONIOUtils.cxx new file mode 100644 index 0000000000000..1c69bece4ab87 --- /dev/null +++ b/roofit/hs3/src/JSONIOUtils.cxx @@ -0,0 +1,74 @@ +#include "JSONIOUtils.h" + +using RooFit::Detail::JSONNode; +using RooFit::Detail::JSONTree; + +bool startsWith(std::string_view str, std::string_view prefix) +{ + return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix); +} + +bool endsWith(std::string_view str, std::string_view suffix) +{ + return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix); +} + +std::unique_ptr varJSONString(const JSONNode &treeRoot) +{ + std::string varName = treeRoot.find("name")->val(); + double val = 0; + double maxVal = 0; + double minVal = 0; + bool isConstant = false; + bool isRange = false; + + if (auto n = treeRoot.find("value")) { + val = n->val_double(); + isConstant = true; + } + + auto maxNode = treeRoot.find("max"); + auto minNode = treeRoot.find("min"); + if (maxNode && minNode) { + maxVal = maxNode->val_double(); + minVal = minNode->val_double(); + isRange = true; + } + if (!isConstant) { + val = (maxVal + minVal) / 2; + } + // Check if variable is at least a range or constant else throw error + if (!isConstant && !isRange) { + throw std::invalid_argument("Invalid Syntax: Please provide either 'value' or 'min' and 'max' or both"); + } + + std::unique_ptr jsonDict = RooFit::Detail::JSONTree::create(); + JSONNode &n = jsonDict->rootnode().set_map(); + JSONNode &_domains = n["domains"].set_seq().append_child().set_map(); + JSONNode &_parameterPoints = n["parameter_points"].set_seq().append_child().set_map(); + + _domains["name"] << "default_domain"; + _domains["type"] << "product_domain"; + JSONNode &_axes = _domains["axes"].set_seq().append_child().set_map(); + _axes["name"] << varName; + + _parameterPoints["name"] << "default_values"; + JSONNode &_parameters = _parameterPoints["parameters"].set_seq().append_child().set_map(); + _parameters["name"] << varName; + _parameters["value"] << val; + + if (isRange) { + _axes["max"] << maxVal; + _axes["min"] << minVal; + } + + if (isConstant && !isRange) { + _parameters["const"] << true; + JSONNode &_misc = n["misc"].set_map(); + JSONNode &rootInternal = _misc["ROOT_internal"].set_map(); + JSONNode &_var = rootInternal[varName].set_map(); + _var["tags"] << "Constant"; + } + + return jsonDict; +} \ No newline at end of file diff --git a/roofit/hs3/src/JSONIOUtils.h b/roofit/hs3/src/JSONIOUtils.h new file mode 100644 index 0000000000000..27fb961486035 --- /dev/null +++ b/roofit/hs3/src/JSONIOUtils.h @@ -0,0 +1,11 @@ +#ifndef JSONIOUtils_h +#define JSONIOUtils_h + +#include +#include + +bool startsWith(std::string_view str, std::string_view prefix); +bool endsWith(std::string_view str, std::string_view suffix); +std::unique_ptr varJSONString(const RooFit::Detail::JSONNode &treeRoot); + +#endif diff --git a/roofit/hs3/src/RooJSONFactoryWSTool.cxx b/roofit/hs3/src/RooJSONFactoryWSTool.cxx index 54f441857d8d0..b050204d9b52f 100644 --- a/roofit/hs3/src/RooJSONFactoryWSTool.cxx +++ b/roofit/hs3/src/RooJSONFactoryWSTool.cxx @@ -12,11 +12,10 @@ #include #include -#include -#include #include #include +#include #include #include #include @@ -24,12 +23,14 @@ #include #include #include -#include +#include +#include +#include -#include "TROOT.h" -#include "TH1.h" +#include "JSONIOUtils.h" +#include "Domains.h" -#include "RConfigure.h" +#include #include #include @@ -50,18 +51,18 @@ exporting to and importing from JSON and YML. In order to import a workspace from a JSON file, you can do -~~~ {.py} +~~ {.py} ws = ROOT.RooWorkspace("ws") tool = ROOT.RooJSONFactoryWSTool(ws) tool.importJSON("myjson.json") -~~~ +~~ Similarly, in order to export a workspace to a JSON file, you can do -~~~ {.py} +~~ {.py} tool = ROOT.RooJSONFactoryWSTool(ws) tool.exportJSON("myjson.json") -~~~ +~~ For more details, consult the tutorial rf515_hfJSON. @@ -79,26 +80,81 @@ consult the README to learn how to do that. -You can always get a list of all the avialable importers and exporters by calling the following functions: -~~~ {.py} +You can always get a list of all the available importers and exporters by calling the following functions: +~~ {.py} ROOT.RooFit.JSONIO.printImporters() ROOT.RooFit.JSONIO.printExporters() ROOT.RooFit.JSONIO.printFactoryExpressions() ROOT.RooFit.JSONIO.printExportKeys() -~~~ +~~ Alternatively, you can generate a LaTeX version of the available importers and exporters by calling -~~~ {.py} +~~ {.py} tool = ROOT.RooJSONFactoryWSTool(ws) tool.writedoc("hs3.tex") -~~~ +~~ */ +constexpr auto hs3VersionTag = "0.1.90"; + using RooFit::Detail::JSONNode; using RooFit::Detail::JSONTree; namespace { + +/** + * @brief Check if the number of components in CombinedData matches the number of categories in the RooSimultaneous PDF. + * + * This function checks whether the number of components in the provided CombinedData 'data' matches the number of + * categories in the provided RooSimultaneous PDF 'pdf'. + * + * @param data The reference to the CombinedData to be checked. + * @param pdf The pointer to the RooSimultaneous PDF for comparison. + * @return bool Returns true if the number of components in 'data' matches the number of categories in 'pdf'; otherwise, + * returns false. + */ +bool matches(const RooJSONFactoryWSTool::CombinedData &data, const RooSimultaneous *pdf) +{ + return data.components.size() == pdf->indexCat().size(); +} + +/** + * @struct Var + * @brief Structure to store variable information. + * + * This structure represents variable information such as the number of bins, minimum and maximum values, + * and a vector of binning edges for a variable. + */ +struct Var { + int nbins; // Number of bins + double min; // Minimum value + double max; // Maximum value + std::vector edges; // Vector of edges + + /** + * @brief Constructor for Var. + * @param n Number of bins. + */ + Var(int n) : nbins(n), min(0), max(n) {} + + /** + * @brief Constructor for Var from JSONNode. + * @param val JSONNode containing variable information. + */ + Var(const JSONNode &val); +}; + +/** + * @brief Check if a string represents a valid number. + * + * This function checks whether the provided string 'str' represents a valid number. + * The function returns true if the entire string can be parsed as a number (integer or floating-point); otherwise, it + * returns false. + * + * @param str The string to be checked. + * @return bool Returns true if the string 'str' represents a valid number; otherwise, returns false. + */ bool isNumber(const std::string &str) { bool first = true; @@ -109,161 +165,126 @@ bool isNumber(const std::string &str) } return true; } -} // namespace - -RooFit::Detail::JSONNode &RooJSONFactoryWSTool::orootnode() -{ - if (_rootnode_output) - return *_rootnode_output; - throw MissingRootnodeError(); -} -const RooFit::Detail::JSONNode &RooJSONFactoryWSTool::irootnode() const -{ - if (_rootnode_input) - return *_rootnode_input; - throw MissingRootnodeError(); -} -template <> -RooRealVar *RooJSONFactoryWSTool::request(const std::string &objname, const std::string &requestAuthor) +/** + * @brief Check if a string is a valid name. + * + * A valid name should start with a letter or an underscore, followed by letters, digits, or underscores. + * Only characters from the ASCII character set are allowed. + * + * @param str The string to be checked. + * @return bool Returns true if the string is a valid name; otherwise, returns false. + */ +bool isValidName(const std::string &str) { - RooRealVar *retval = _workspace.var(objname); - if (retval) - return retval; - if (irootnode().has_child("variables")) { - const JSONNode &vars = irootnode()["variables"]; - if (vars.has_child(objname)) { - this->importVariable(vars[objname]); - retval = _workspace.var(objname); - if (retval) - return retval; - } + // Check if the string is empty or starts with a non-letter/non-underscore character + if (str.empty() || !(std::isalpha(str[0]) || str[0] == '_')) { + return false; } - throw DependencyMissingError(requestAuthor, objname, "RooRealVar"); -} -template <> -RooAbsPdf *RooJSONFactoryWSTool::request(const std::string &objname, const std::string &requestAuthor) -{ - RooAbsPdf *retval = _workspace.pdf(objname); - if (retval) - return retval; - if (irootnode().has_child("pdfs")) { - const JSONNode &pdfs = irootnode()["pdfs"]; - if (pdfs.has_child(objname)) { - this->importFunction(pdfs[objname], true); - retval = _workspace.pdf(objname); - if (retval) - return retval; + // Check the remaining characters in the string + for (char c : str) { + // Allow letters, digits, and underscore + if (!(std::isalnum(c) || c == '_')) { + return false; } } - throw DependencyMissingError(requestAuthor, objname, "RooAbsPdf"); + + // If all characters are valid, the string is a valid name + return true; } -template <> -RooAbsReal *RooJSONFactoryWSTool::request(const std::string &objname, const std::string &requestAuthor) +/** + * @brief Configure a RooRealVar based on information from a JSONNode. + * + * This function configures the provided RooRealVar 'v' based on the information provided in the JSONNode 'p'. + * The JSONNode 'p' contains information about various properties of the RooRealVar, such as its value, error, number of + * bins, etc. The function reads these properties from the JSONNode and sets the corresponding properties of the + * RooRealVar accordingly. + * + * @param domains The reference to the RooFit::JSONIO::Detail::Domains containing domain information for variables (not + * used in this function). + * @param p The JSONNode containing information about the properties of the RooRealVar 'v'. + * @param v The reference to the RooRealVar to be configured. + * @return void + */ +void configureVariable(RooFit::JSONIO::Detail::Domains &domains, const JSONNode &p, RooRealVar &v) { - RooAbsReal *retval = nullptr; - retval = _workspace.pdf(objname); - if (retval) - return retval; - retval = _workspace.function(objname); - if (retval) - return retval; - retval = _workspace.var(objname); - if (retval) - return retval; - if (isNumber(objname)) - return dynamic_cast(_workspace.factory(objname)); - if (irootnode().has_child("pdfs")) { - const JSONNode &pdfs = irootnode()["pdfs"]; - if (pdfs.has_child(objname)) { - this->importFunction(pdfs[objname], true); - retval = _workspace.pdf(objname.c_str()); - if (retval) - return retval; - } - } - if (irootnode().has_child("variables")) { - const JSONNode &vars = irootnode()["variables"]; - if (vars.has_child(objname)) { - this->importVariable(vars[objname]); - retval = _workspace.var(objname); - if (retval) - return retval; - } - } - if (irootnode().has_child("functions")) { - const JSONNode &funcs = irootnode()["functions"]; - if (funcs.has_child(objname)) { - this->importFunction(funcs[objname], false); - retval = _workspace.function(objname); - if (retval) - return retval; - } - } - throw DependencyMissingError(requestAuthor, objname, "RooAbsReal"); + if (auto n = p.find("value")) + v.setVal(n->val_double()); + domains.writeVariable(v); + if (auto n = p.find("nbins")) + v.setBins(n->val_int()); + if (auto n = p.find("relErr")) + v.setError(v.getVal() * n->val_double()); + if (auto n = p.find("err")) + v.setError(n->val_double()); + if (auto n = p.find("const")) + v.setConstant(n->val_bool()); + else + v.setConstant(false); } -namespace { - -void logInputArgumentsError(std::stringstream &&ss) +JSONNode const *getVariablesNode(JSONNode const &rootNode) { - oocoutE(nullptr, InputArguments) << ss.str(); + auto paramPointsNode = rootNode.find("parameter_points"); + if (!paramPointsNode) + return nullptr; + auto out = RooJSONFactoryWSTool::findNamedChild(*paramPointsNode, "default_values"); + if (out == nullptr) + return nullptr; + return &((*out)["parameters"]); } -} // namespace - -RooJSONFactoryWSTool::Var::Var(const JSONNode &val) +Var::Var(const JSONNode &val) { - if (val.is_map()) { - if (!val.has_child("nbins")) + if (val.find("edges")) { + for (auto const &child : val.children()) { + this->edges.push_back(child.val_double()); + } + this->nbins = this->edges.size(); + this->min = this->edges[0]; + this->max = this->edges[this->nbins - 1]; + } else { + if (!val.find("nbins")) this->nbins = 1; else this->nbins = val["nbins"].val_int(); - if (!val.has_child("min")) + if (!val.find("min")) this->min = 0; else - this->min = val["min"].val_float(); - if (!val.has_child("max")) + this->min = val["min"].val_double(); + if (!val.find("max")) this->max = 1; else - this->max = val["max"].val_float(); - } else if (val.is_seq()) { - for (size_t i = 0; i < val.num_children(); ++i) { - this->bounds.push_back(val[i].val_float()); - } - this->nbins = this->bounds.size(); - this->min = this->bounds[0]; - this->max = this->bounds[this->nbins - 1]; + this->max = val["max"].val_double(); } } -std::string RooJSONFactoryWSTool::genPrefix(const JSONNode &p, bool trailing_underscore) +std::string genPrefix(const JSONNode &p, bool trailing_underscore) { std::string prefix; if (!p.is_map()) return prefix; - if (p.has_child("namespaces")) { - for (const auto &ns : p["namespaces"].children()) { - if (prefix.size() > 0) + if (auto node = p.find("namespaces")) { + for (const auto &ns : node->children()) { + if (!prefix.empty()) prefix += "_"; prefix += ns.val(); } } - if (trailing_underscore && prefix.size() > 0) + if (trailing_underscore && !prefix.empty()) prefix += "_"; return prefix; } -namespace { // helpers for serializing / deserializing binned datasets -inline void genIndicesHelper(std::vector> &combinations, std::vector &curr_comb, - const std::vector &vars_numbins, size_t curridx) +void genIndicesHelper(std::vector> &combinations, std::vector &curr_comb, + const std::vector &vars_numbins, size_t curridx) { if (curridx == vars_numbins.size()) { // we have filled a combination. Copy it. - combinations.push_back(std::vector(curr_comb)); + combinations.emplace_back(curr_comb); } else { for (int i = 0; i < vars_numbins[curridx]; ++i) { curr_comb[curridx] = i; @@ -272,272 +293,642 @@ inline void genIndicesHelper(std::vector> &combinations, std::v } } -std::string containerName(RooAbsArg const *elem) -{ - std::string contname = "functions"; - if (elem->InheritsFrom(RooAbsPdf::Class())) - contname = "pdfs"; - if (elem->InheritsFrom(RooRealVar::Class()) || elem->InheritsFrom(RooConstVar::Class())) - contname = "variables"; - return contname; -} -} // namespace - -bool RooJSONFactoryWSTool::Config::stripObservables = true; - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// helper functions specific to JSON -/////////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace { - -inline void importAttributes(RooAbsArg *arg, const JSONNode &n) +/** + * @brief Import attributes from a JSONNode into a RooAbsArg. + * + * This function imports attributes, represented by the provided JSONNode 'node', into the provided RooAbsArg 'arg'. + * The attributes are read from the JSONNode and applied to the RooAbsArg. + * + * @param arg The pointer to the RooAbsArg to which the attributes will be imported. + * @param node The JSONNode containing information about the attributes to be imported. + * @return void + */ +void importAttributes(RooAbsArg *arg, JSONNode const &node) { - if (!n.is_map()) - return; - if (n.has_child("dict") && n["dict"].is_map()) { - for (const auto &attr : n["dict"].children()) { - arg->setStringAttribute(RooJSONFactoryWSTool::name(attr).c_str(), attr.val().c_str()); + if (auto seq = node.find("dict")) { + for (const auto &attr : seq->children()) { + arg->setStringAttribute(attr.key().c_str(), attr.val().c_str()); } } - if (n.has_child("tags") && n["tags"].is_seq()) { - for (const auto &attr : n["tags"].children()) { + if (auto seq = node.find("tags")) { + for (const auto &attr : seq->children()) { arg->setAttribute(attr.val().c_str()); } } } -inline bool checkRegularBins(const TAxis &ax) -{ - double w = ax.GetXmax() - ax.GetXmin(); - double bw = w / ax.GetNbins(); - for (int i = 0; i <= ax.GetNbins(); ++i) { - if (fabs(ax.GetBinUpEdge(i) - (ax.GetXmin() + (bw * i))) > w * 1e-6) - return false; - } - return true; -} -inline void writeAxis(JSONNode &bounds, const TAxis &ax) -{ - bool regular = (!ax.IsVariableBinSize()) || checkRegularBins(ax); - if (regular) { - bounds.set_map(); - bounds["nbins"] << ax.GetNbins(); - bounds["min"] << ax.GetXmin(); - bounds["max"] << ax.GetXmax(); - } else { - bounds.set_seq(); - for (int i = 0; i <= ax.GetNbins(); ++i) { - bounds.append_child() << ax.GetBinUpEdge(i); - } - } -} -} // namespace -/////////////////////////////////////////////////////////////////////////////////////////////////////// // RooWSFactoryTool expression handling -/////////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace { std::string generate(const RooFit::JSONIO::ImportExpression &ex, const JSONNode &p, RooJSONFactoryWSTool *tool) { - std::string name(RooJSONFactoryWSTool::name(p)); std::stringstream expression; std::string classname(ex.tclass->GetName()); - size_t colon = classname.find_last_of(":"); - if (colon < classname.size()) { - expression << classname.substr(colon + 1); - } else { - expression << classname; - } - expression << "::" << name << "("; + size_t colon = classname.find_last_of(':'); + expression << (colon < classname.size() ? classname.substr(colon + 1) : classname); bool first = true; + const auto &name = RooJSONFactoryWSTool::name(p); for (auto k : ex.arguments) { - if (!first) - expression << ","; + expression << (first ? "::" + name + "(" : ","); first = false; - if (k == "true") { - expression << "1"; - continue; - } else if (k == "false") { - expression << "0"; - continue; + if (k == "true" || k == "false") { + expression << (k == "true" ? "1" : "0"); } else if (!p.has_child(k)) { - std::stringstream err; - err << "factory expression for class '" << ex.tclass->GetName() << "', which expects key '" << k - << "' missing from input for object '" << name << "', skipping."; - RooJSONFactoryWSTool::error(err.str().c_str()); - } - if (p[k].is_seq()) { - expression << "{"; - bool f = true; - for (const auto &x : p[k].children()) { - if (!f) - expression << ","; - f = false; - std::string obj(x.val()); - tool->request(obj, name); - expression << obj; + std::stringstream errMsg; + errMsg << "node '" << name << "' is missing key '" << k << "'"; + RooJSONFactoryWSTool::error(errMsg.str()); + } else if (p[k].is_seq()) { + bool firstInner = true; + for (RooAbsArg *arg : tool->requestArgList(p, k)) { + expression << (firstInner ? "{" : ",") << arg->GetName(); + firstInner = false; } expression << "}"; } else { - std::string obj(p[k].val()); - tool->request(obj, name); - expression << obj; + tool->requestArg(p, p[k].key()); + expression << p[k].val(); } } expression << ")"; return expression.str(); } -}; // namespace -std::vector> RooJSONFactoryWSTool::generateBinIndices(const RooArgList &vars) +/** + * @brief Generate bin indices for a set of RooRealVars. + * + * This function generates all possible combinations of bin indices for the provided RooArgSet 'vars' containing + * RooRealVars. Each bin index represents a possible bin selection for the corresponding RooRealVar. The bin indices are + * stored in a vector of vectors, where each inner vector represents a combination of bin indices for all RooRealVars. + * + * @param vars The RooArgSet containing the RooRealVars for which bin indices will be generated. + * @return std::vector> A vector of vectors containing all possible combinations of bin indices. + */ +std::vector> generateBinIndices(const RooArgSet &vars) { std::vector> combinations; std::vector vars_numbins; vars_numbins.reserve(vars.size()); for (const auto *absv : static_range_cast(vars)) { - vars_numbins.push_back(absv->numBins()); + vars_numbins.push_back(absv->getBins()); } std::vector curr_comb(vars.size()); ::genIndicesHelper(combinations, curr_comb, vars_numbins, 0); return combinations; } -void RooJSONFactoryWSTool::writeObservables(const TH1 &h, JSONNode &n, const std::vector &varnames) +template +JSONNode const *findRooFitInternal(JSONNode const &node, Keys_t const &...keys) +{ + return node.find("misc", "ROOT_internal", keys...); +} + +/** + * @brief Check if a RooAbsArg is a literal constant variable. + * + * This function checks whether the provided RooAbsArg 'arg' is a literal constant variable. + * A literal constant variable is a RooConstVar with a numeric value as a name. + * + * @param arg The reference to the RooAbsArg to be checked. + * @return bool Returns true if 'arg' is a literal constant variable; otherwise, returns false. + */ +bool isLiteralConstVar(RooAbsArg const &arg) +{ + bool isRooConstVar = dynamic_cast(&arg); + return isRooConstVar && isNumber(arg.GetName()); +} + +/** + * @brief Export attributes of a RooAbsArg to a JSONNode. + * + * This function exports the attributes of the provided RooAbsArg 'arg' to the JSONNode 'rootnode'. + * + * @param arg The pointer to the RooAbsArg from which attributes will be exported. + * @param rootnode The JSONNode to which the attributes will be exported. + * @return void + */ +void exportAttributes(const RooAbsArg *arg, JSONNode &rootnode) +{ + // If this RooConst is a literal number, we don't need to export the attributes. + if (isLiteralConstVar(*arg)) { + return; + } + + JSONNode *node = nullptr; + + auto initializeNode = [&]() { + if (node) + return; + + node = &RooJSONFactoryWSTool::getRooFitInternal(rootnode, "attributes").set_map()[arg->GetName()].set_map(); + }; + + // We have to remember if the variable was a constant RooRealVar or a + // RooConstVar in RooFit to reconstruct the workspace correctly. The HS3 + // standard does not make this distinction. + bool isRooConstVar = dynamic_cast(arg); + if (isRooConstVar) { + initializeNode(); + (*node)["is_const_var"] << 1; + } + + // export all string attributes of an object + if (!arg->stringAttributes().empty()) { + for (const auto &it : arg->stringAttributes()) { + // Skip some RooFit internals + if (it.first == "factory_tag" || it.first == "PROD_TERM_TYPE") + continue; + initializeNode(); + (*node)["dict"].set_map()[it.first] << it.second; + } + } + if (!arg->attributes().empty()) { + for (auto const &attr : arg->attributes()) { + // Skip some RooFit internals + if (attr == "SnapShot_ExtRefClone" || attr == "RooRealConstant_Factory_Object") + continue; + initializeNode(); + (*node)["tags"].set_seq().append_child() << attr; + } + } +} + +/** + * @brief Create several observables in the workspace. + * + * This function obtains a list of observables from the provided + * RooWorkspace 'ws' based on their names given in the 'axes" field of + * the JSONNode 'node'. The observables are added to the RooArgSet + * 'out'. + * + * @param ws The RooWorkspace in which the observables will be created. + * @param node The JSONNode containing information about the observables to be created. + * @param out The RooArgSet to which the created observables will be added. + * @return void + */ +void getObservables(RooWorkspace const &ws, const JSONNode &node, RooArgSet &out) { - auto &observables = n["observables"]; - observables.set_map(); - auto &x = observables[varnames[0]]; - writeAxis(x, *(h.GetXaxis())); - if (h.GetDimension() > 1) { - auto &y = observables[varnames[1]]; - writeAxis(y, *(h.GetYaxis())); - if (h.GetDimension() > 2) { - auto &z = observables[varnames[2]]; - writeAxis(z, *(h.GetZaxis())); + std::map vars; + for (const auto &p : node["axes"].children()) { + vars.emplace(RooJSONFactoryWSTool::name(p), Var(p)); + } + + for (auto v : vars) { + std::string name(v.first); + if (ws.var(name)) { + out.add(*ws.var(name)); + } else { + std::stringstream errMsg; + errMsg << "The observable \"" << name << "\" could not be found in the workspace!"; + RooJSONFactoryWSTool::error(errMsg.str()); } } } -void RooJSONFactoryWSTool::exportHistogram(const TH1 &h, JSONNode &n, const std::vector &varnames, - const TH1 *errH, bool writeObservables, bool writeErrors) +/** + * @brief Import data from the JSONNode into the workspace. + * + * This function imports data, represented by the provided JSONNode 'p', into the workspace represented by the provided + * RooWorkspace. The data information is read from the JSONNode and added to the workspace. + * + * @param p The JSONNode representing the data to be imported. + * @param workspace The RooWorkspace to which the data will be imported. + * @return std::unique_ptr A unique pointer to the RooAbsData object representing the imported data. + * The caller is responsible for managing the memory of the returned object. + */ +std::unique_ptr loadData(const JSONNode &p, RooWorkspace &workspace) { - n.set_map(); - auto &weights = n["counts"]; - weights.set_seq(); - if (writeErrors) { - n["errors"].set_seq(); - } - if (writeObservables) { - RooJSONFactoryWSTool::writeObservables(h, n, varnames); - } - for (int i = 1; i <= h.GetNbinsX(); ++i) { - if (h.GetDimension() == 1) { - weights.append_child() << h.GetBinContent(i); - if (writeErrors) { - n["errors"].append_child() << (errH ? h.GetBinContent(i) * errH->GetBinContent(i) : h.GetBinError(i)); + std::string name(RooJSONFactoryWSTool::name(p)); + + if (!::isValidName(name)) { + std::stringstream ss; + ss << "RooJSONFactoryWSTool() data name '" << name << "' is not valid!" << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + } + + std::string const &type = p["type"].val(); + if (type == "binned") { + // binned + return RooJSONFactoryWSTool::readBinnedData(p, name, RooJSONFactoryWSTool::readAxes(p)); + } else if (type == "unbinned") { + // unbinned + RooArgSet vars; + getObservables(workspace, p, vars); + RooArgList varlist(vars); + auto data = std::make_unique(name, name, vars, RooFit::WeightVar()); + auto &coords = p["entries"]; + auto &weights = p["weights"]; + if (coords.num_children() != weights.num_children()) { + RooJSONFactoryWSTool::error("inconsistent number of entries and weights!"); + } + if (!coords.is_seq()) { + RooJSONFactoryWSTool::error("key 'entries' is not a list!"); + } + std::vector weightVals; + for (auto const &weight : weights.children()) { + weightVals.push_back(weight.val_double()); + } + std::size_t i = 0; + for (auto const &point : coords.children()) { + if (!point.is_seq()) { + std::stringstream errMsg; + errMsg << "coordinate point '" << i << "' is not a list!"; + RooJSONFactoryWSTool::error(errMsg.str()); } + if (point.num_children() != varlist.size()) { + RooJSONFactoryWSTool::error("inconsistent number of entries and observables!"); + } + std::size_t j = 0; + for (auto const &pointj : point.children()) { + auto *v = static_cast(varlist.at(j)); + v->setVal(pointj.val_double()); + ++j; + } + data->add(vars, weightVals[i]); + ++i; + } + return data; + } + + std::stringstream ss; + ss << "RooJSONFactoryWSTool() failed to create dataset " << name << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + return nullptr; +} + +/** + * @brief Import an analysis from the JSONNode into the workspace. + * + * This function imports an analysis, represented by the provided JSONNodes 'analysisNode' and 'likelihoodsNode', + * into the workspace represented by the provided RooWorkspace. The analysis information is read from the JSONNodes + * and added to the workspace as one or more RooStats::ModelConfig objects. + * + * @param rootnode The root JSONNode representing the entire JSON file. + * @param analysisNode The JSONNode representing the analysis to be imported. + * @param likelihoodsNode The JSONNode containing information about likelihoods associated with the analysis. + * @param workspace The RooWorkspace to which the analysis will be imported. + * @param datasets A vector of unique pointers to RooAbsData objects representing the data associated with the analysis. + * @return void + */ +void importAnalysis(const JSONNode &rootnode, const JSONNode &analysisNode, const JSONNode &likelihoodsNode, + RooWorkspace &workspace, const std::vector> &datasets) +{ + // if this is a toplevel pdf, also create a modelConfig for it + std::string const &analysisName = RooJSONFactoryWSTool::name(analysisNode); + JSONNode const *mcAuxNode = findRooFitInternal(rootnode, "ModelConfigs", analysisName); + + JSONNode const *mcNameNode = mcAuxNode ? mcAuxNode->find("mcName") : nullptr; + std::string mcname = mcNameNode ? mcNameNode->val() : analysisName; + if (workspace.obj(mcname)) + return; + + workspace.import(RooStats::ModelConfig{mcname.c_str(), mcname.c_str()}); + auto *mc = static_cast(workspace.obj(mcname)); + mc->SetWS(workspace); + + std::vector nllDistNames; + std::vector nllDataNames; + + auto *nllNode = RooJSONFactoryWSTool::findNamedChild(likelihoodsNode, analysisNode["likelihood"].val()); + if (!nllNode) { + throw std::runtime_error("likelihood node not found!"); + } + for (auto &nameNode : (*nllNode)["distributions"].children()) { + nllDistNames.push_back(nameNode.val()); + } + RooArgSet extConstraints; + for (auto &nameNode : (*nllNode)["aux_distributions"].children()) { + RooAbsArg *extConstraint = workspace.arg(nameNode.val()); + if (extConstraint) { + extConstraints.add(*extConstraint); + } + } + RooArgSet observables; + for (auto &nameNode : (*nllNode)["data"].children()) { + nllDataNames.push_back(nameNode.val()); + for (const auto &d : datasets) { + if (d->GetName() == nameNode.val()) { + observables.add(*d->get()); + } + } + } + + JSONNode const *pdfNameNode = mcAuxNode ? mcAuxNode->find("pdfName") : nullptr; + std::string const pdfName = pdfNameNode ? pdfNameNode->val() : "simPdf"; + + RooAbsPdf *pdf = static_cast(workspace.pdf(pdfName)); + + if (!pdf) { + // if there is no simultaneous pdf, we can check whether there is only one pdf in the list + if (nllDistNames.size() == 1) { + // if so, we can use that one to populate the ModelConfig + pdf = workspace.pdf(nllDistNames[0]); } else { - for (int j = 1; j <= h.GetNbinsY(); ++j) { - if (h.GetDimension() == 2) { - weights.append_child() << h.GetBinContent(i, j); - if (writeErrors) { - n["errors"].append_child() - << (errH ? h.GetBinContent(i, j) * errH->GetBinContent(i, j) : h.GetBinError(i, j)); - } - } else { - for (int k = 1; k <= h.GetNbinsZ(); ++k) { - weights.append_child() << h.GetBinContent(i, j, k); - if (writeErrors) { - n["errors"].append_child() - << (errH ? h.GetBinContent(i, j, k) * errH->GetBinContent(i, j, k) : h.GetBinError(i, j, k)); - } - } - } + // otherwise, we have no choice but to build a simPdf by hand + std::string simPdfName = analysisName + "_simPdf"; + std::string indexCatName = analysisName + "_categoryIndex"; + RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()}; + std::map pdfMap; + for (std::size_t i = 0; i < nllDistNames.size(); ++i) { + indexCat.defineType(nllDistNames[i], i); + pdfMap[nllDistNames[i]] = workspace.pdf(nllDistNames[i]); } + RooSimultaneous simPdf{simPdfName.c_str(), simPdfName.c_str(), pdfMap, indexCat}; + workspace.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + pdf = static_cast(workspace.pdf(simPdfName)); + } + } + + mc->SetPdf(*pdf); + + if (!extConstraints.empty()) + mc->SetExternalConstraints(extConstraints); + + auto readArgSet = [&](std::string const &name) { + RooArgSet out; + for (auto const &child : analysisNode[name].children()) { + out.add(*workspace.arg(child.val())); + } + return out; + }; + + mc->SetParametersOfInterest(readArgSet("parameters_of_interest")); + mc->SetObservables(observables); + RooArgSet pars; + pdf->getParameters(&observables, pars); + + // Figure out the set parameters that appear in the main measurement: + // getAllConstraints() has the side effect to remove all parameters from + // "mainPars" that are not part of any pdf over observables. + RooArgSet mainPars{pars}; + pdf->getAllConstraints(observables, mainPars, /*stripDisconnected*/ true); + + RooArgSet nps; + RooArgSet globs; + for (const auto &p : pars) { + if (mc->GetParametersOfInterest()->find(*p)) + continue; + if (p->isConstant() && !mainPars.find(*p)) + globs.add(*p); + else + nps.add(*p); + } + mc->SetGlobalObservables(globs); + mc->SetNuisanceParameters(nps); + + if (mcAuxNode) { + if (auto found = mcAuxNode->find("combined_data_name")) { + pdf->setStringAttribute("combined_data_name", found->val().c_str()); } } } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// helper namespace -/////////////////////////////////////////////////////////////////////////////////////////////////////// +void combinePdfs(const JSONNode &rootnode, RooWorkspace &ws) +{ + auto *combinedPdfInfoNode = findRooFitInternal(rootnode, "combined_distributions"); + + // If there is no info on combining pdfs + if (combinedPdfInfoNode == nullptr) { + return; + } + + for (auto &info : combinedPdfInfoNode->children()) { + + // parse the information + std::string combinedName = info.key(); + std::string indexCatName = info["index_cat"].val(); + std::vector labels; + std::vector indices; + std::vector pdfNames; + for (auto &n : info["indices"].children()) { + indices.push_back(n.val_int()); + } + for (auto &n : info["labels"].children()) { + labels.push_back(n.val()); + } + for (auto &n : info["distributions"].children()) { + pdfNames.push_back(n.val()); + } + + RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()}; + std::map pdfMap; -bool RooJSONFactoryWSTool::find(const JSONNode &n, const std::string &elem) + for (std::size_t iChannel = 0; iChannel < labels.size(); ++iChannel) { + indexCat.defineType(labels[iChannel], indices[iChannel]); + pdfMap[labels[iChannel]] = ws.pdf(pdfNames[iChannel]); + } + + RooSimultaneous simPdf{combinedName.c_str(), combinedName.c_str(), pdfMap, indexCat}; + ws.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); + } +} + +void combineDatasets(const JSONNode &rootnode, std::vector> &datasets) { - // find an attribute - if (n.is_seq()) { - for (const auto &t : n.children()) { - if (t.val() == elem) - return true; + auto *combinedDataInfoNode = findRooFitInternal(rootnode, "combined_datasets"); + + // If there is no info on combining datasets + if (combinedDataInfoNode == nullptr) { + return; + } + + for (auto &info : combinedDataInfoNode->children()) { + + // parse the information + std::string combinedName = info.key(); + std::string indexCatName = info["index_cat"].val(); + std::vector labels; + std::vector indices; + for (auto &n : info["indices"].children()) { + indices.push_back(n.val_int()); } - return false; - } else if (n.is_map()) { - return n.has_child(elem.c_str()); + for (auto &n : info["labels"].children()) { + labels.push_back(n.val()); + } + + // Create the combined dataset for RooFit + std::map> dsMap; + RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()}; + RooArgSet allVars{indexCat}; + for (std::size_t iChannel = 0; iChannel < labels.size(); ++iChannel) { + auto componentName = combinedName + "_" + labels[iChannel]; + // We move the found channel data out of the "datasets" vector, such that + // the data components don't get imported anymore. + std::unique_ptr &component = *std::find_if( + datasets.begin(), datasets.end(), [&](auto &d) { return d && d->GetName() == componentName; }); + allVars.add(*component->get()); + dsMap.insert({labels[iChannel], std::move(component)}); + indexCat.defineType(labels[iChannel], indices[iChannel]); + } + + auto combined = std::make_unique(combinedName, combinedName, allVars, RooFit::Import(dsMap), + RooFit::Index(indexCat)); + datasets.emplace_back(std::move(combined)); } - return false; } -void RooJSONFactoryWSTool::append(JSONNode &n, const std::string &elem) +template +void sortByName(T &coll) +{ + std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return strcmp(l->GetName(), r->GetName()) < 0; }); +} + +} // namespace + +RooJSONFactoryWSTool::RooJSONFactoryWSTool(RooWorkspace &ws) : _workspace{ws} {} + +RooJSONFactoryWSTool::~RooJSONFactoryWSTool() {} + +void RooJSONFactoryWSTool::fillSeq(JSONNode &node, RooAbsCollection const &coll) { - // append an attribute - n.set_seq(); - if (!find(n, elem)) { - n.append_child() << elem; + node.set_seq(); + for (RooAbsArg const *arg : coll) { + if (isLiteralConstVar(*arg)) + node.append_child() << static_cast(arg)->getVal(); + else + node.append_child() << arg->GetName(); } } -void RooJSONFactoryWSTool::exportAttributes(const RooAbsArg *arg, JSONNode &n) +JSONNode &RooJSONFactoryWSTool::appendNamedChild(JSONNode &node, std::string const &name) { - // export all string attributes of an object - if (arg->stringAttributes().size() > 0) { - auto &dict = n["dict"]; - dict.set_map(); - for (const auto &it : arg->stringAttributes()) { - dict[it.first] << it.second; + if (!useListsInsteadOfDicts) { + return node.set_map()[name].set_map(); + } + JSONNode &child = node.set_seq().append_child().set_map(); + child["name"] << name; + return child; +} + +JSONNode const *RooJSONFactoryWSTool::findNamedChild(JSONNode const &node, std::string const &name) +{ + if (!useListsInsteadOfDicts) { + if (!node.is_map()) + return nullptr; + return node.find(name); + } + if (!node.is_seq()) + return nullptr; + for (JSONNode const &child : node.children()) { + if (child["name"].val() == name) + return &child; + } + + return nullptr; +} + +std::string RooJSONFactoryWSTool::name(const JSONNode &n) +{ + return useListsInsteadOfDicts ? n["name"].val() : n.key(); +} + +JSONNode &RooJSONFactoryWSTool::makeVariablesNode(JSONNode &rootNode) +{ + return appendNamedChild(rootNode["parameter_points"], "default_values")["parameters"]; +} + +template <> +RooRealVar *RooJSONFactoryWSTool::requestImpl(const std::string &objname) +{ + if (RooRealVar *retval = _workspace.var(objname)) + return retval; + if (JSONNode const *vars = getVariablesNode(*_rootnodeInput)) { + if (auto node = vars->find(objname)) { + this->importVariable(*node); + if (RooRealVar *retval = _workspace.var(objname)) + return retval; } } - if (arg->attributes().size() > 0) { - auto &tags = n["tags"]; - tags.set_seq(); - for (const auto &it : arg->attributes()) { - RooJSONFactoryWSTool::append(tags, it); + return nullptr; +} + +template <> +RooAbsPdf *RooJSONFactoryWSTool::requestImpl(const std::string &objname) +{ + if (RooAbsPdf *retval = _workspace.pdf(objname)) + return retval; + if (auto distributionsNode = _rootnodeInput->find("distributions")) { + if (auto child = findNamedChild(*distributionsNode, objname)) { + this->importFunction(*child, true); + if (RooAbsPdf *retval = _workspace.pdf(objname)) + return retval; } } + return nullptr; } -void RooJSONFactoryWSTool::exportVariable(const RooAbsArg *v, JSONNode &n) +template <> +RooAbsReal *RooJSONFactoryWSTool::requestImpl(const std::string &objname) +{ + if (RooAbsReal *retval = _workspace.function(objname)) + return retval; + if (isNumber(objname)) + return &RooFit::RooConst(std::stod(objname)); + if (RooAbsPdf *pdf = requestImpl(objname)) + return pdf; + if (RooRealVar *var = requestImpl(objname)) + return var; + if (auto functionNode = _rootnodeInput->find("functions")) { + if (auto child = findNamedChild(*functionNode, objname)) { + this->importFunction(*child, true); + if (RooAbsReal *retval = _workspace.function(objname)) + return retval; + } + } + return nullptr; +} + +/** + * @brief Export a variable from the workspace to a JSONNode. + * + * This function exports a variable, represented by the provided RooAbsArg pointer 'v', from the workspace to a + * JSONNode. The variable's information is added to the JSONNode as key-value pairs. + * + * @param v The pointer to the RooAbsArg representing the variable to be exported. + * @param node The JSONNode to which the variable will be exported. + * @return void + */ +void RooJSONFactoryWSTool::exportVariable(const RooAbsArg *v, JSONNode &node) { auto *cv = dynamic_cast(v); auto *rrv = dynamic_cast(v); if (!cv && !rrv) return; - n.set_map(); + // for RooConstVar, if name and value are the same, we don't need to do anything + if (cv && strcmp(cv->GetName(), TString::Format("%g", cv->getVal()).Data()) == 0) { + return; + } + + // this variable was already exported + if (findNamedChild(node, v->GetName())) { + return; + } + + JSONNode &var = appendNamedChild(node, v->GetName()); - JSONNode &var = n[v->GetName()]; - var.set_map(); if (cv) { var["value"] << cv->getVal(); var["const"] << true; } else if (rrv) { var["value"] << rrv->getVal(); - if (rrv->getMin() > -1e30) { - var["min"] << rrv->getMin(); - } - if (rrv->getMax() < 1e30) { - var["max"] << rrv->getMax(); - } if (rrv->isConstant()) { var["const"] << rrv->isConstant(); } - if (rrv->numBins() != 100) { - var["nbins"] << rrv->numBins(); + if (rrv->getBins() != 100) { + var["nbins"] << rrv->getBins(); } + _domains->readVariable(*rrv); } - RooJSONFactoryWSTool::exportAttributes(v, var); } +/** + * @brief Export variables from the workspace to a JSONNode. + * + * This function exports variables, represented by the provided RooArgSet, from the workspace to a JSONNode. + * The variables' information is added to the JSONNode as key-value pairs. + * + * @param allElems The RooArgSet representing the variables to be exported. + * @param n The JSONNode to which the variables will be exported. + * @return void + */ void RooJSONFactoryWSTool::exportVariables(const RooArgSet &allElems, JSONNode &n) { // export a list of RooRealVar objects @@ -546,89 +937,172 @@ void RooJSONFactoryWSTool::exportVariables(const RooArgSet &allElems, JSONNode & } } -JSONNode *RooJSONFactoryWSTool::exportObject(const RooAbsArg *func) +RooAbsReal *RooJSONFactoryWSTool::importTransformed(const std::string &name, const std::string &tag, + const std::string &operation_name, const std::string &formula) { - auto &n = orootnode()[containerName(func)]; - n.set_map(); + RooAbsReal *transformed = nullptr; + const std::string tagname = "autogen_transform_" + tag; + if (this->hasAttribute(name, tagname)) { + const std::string &original = this->getStringAttribute(name, tagname + "_original"); + transformed = this->workspace()->function(original); + if (transformed) + return transformed; + } + const std::string newname = name + "_" + tag + "_" + operation_name; + transformed = this->workspace()->function(newname); + if (!transformed) { + auto *original = this->workspace()->arg(name); + if (!original) { + error("unable to import transformed of '" + name + "', original not present."); + } + RooArgSet components{*original}; + const std::string &expression = TString::Format(formula.c_str(), name.c_str()).Data(); + transformed = &wsEmplace(newname, expression.c_str(), components); + transformed->setAttribute(tagname.c_str()); + } + return transformed; +} - auto const &exporters = RooFit::JSONIO::exporters(); - auto const &exportKeys = RooFit::JSONIO::exportKeys(); +std::string RooJSONFactoryWSTool::exportTransformed(const RooAbsReal *original, const std::string &tag, + const std::string &operation_name, const std::string &formula) +{ + const std::string tagname = "autogen_transform_" + tag; + if (original->getAttribute(tagname.c_str())) { + if (const RooFormulaVar *trafo = dynamic_cast(original)) { + return trafo->dependents().first()->GetName(); + } + } - // if this element already exists, skip - if (n.has_child(func->GetName())) - return &n[func->GetName()]; + std::string newname = std::string(original->GetName()) + "_" + tag + "_" + operation_name; + auto &trafo_node = this->createAdHoc("functions", newname); + trafo_node["type"] << "generic_function"; + trafo_node["expression"] << TString::Format(formula.c_str(), original->GetName()).Data(); + this->setAttribute(newname, tagname); + this->setStringAttribute(newname, tagname + "_original", original->GetName()); + return newname; +} - if (func->InheritsFrom(RooConstVar::Class()) && - strcmp(func->GetName(), TString::Format("%g", ((RooConstVar *)func)->getVal()).Data()) == 0) { - // for RooConstVar, if name and value are the same, we don't need to do anything - return nullptr; - } else if (func->InheritsFrom(RooAbsCategory::Class())) { +RooFit::Detail::JSONNode &RooJSONFactoryWSTool::createAdHoc(const std::string &toplevel, const std::string &name) +{ + auto &collectionNode = (*_rootnodeOutput)[toplevel]; + return appendNamedChild(collectionNode, name); +} + +/** + * @brief Export an object from the workspace to a JSONNode. + * + * This function exports an object, represented by the provided RooAbsArg, from the workspace to a JSONNode. + * The object's information is added to the JSONNode as key-value pairs. + * + * @param func The RooAbsArg representing the object to be exported. + * @param exportedObjectNames A set of strings containing names of previously exported objects to avoid duplicates. + * This set is updated with the name of the newly exported object. + * @return void + */ +void RooJSONFactoryWSTool::exportObject(RooAbsArg const &func, std::set &exportedObjectNames) +{ + const std::string name = func.GetName(); + + // if this element was already exported, skip + if (exportedObjectNames.find(name) != exportedObjectNames.end()) + return; + + exportedObjectNames.insert(name); + + if (auto simPdf = dynamic_cast(&func)) { + // RooSimultaneous is not used in the HS3 standard, we only export the + // dependents and some ROOT internal information. + for (RooAbsArg *s : func.servers()) { + this->exportObject(*s, exportedObjectNames); + } + + std::vector channelNames; + for (auto const &item : simPdf->indexCat()) { + channelNames.push_back(item.first); + } + + auto &infoNode = getRooFitInternal(*_rootnodeOutput, "combined_distributions").set_map(); + auto &child = infoNode[simPdf->GetName()].set_map(); + child["index_cat"] << simPdf->indexCat().GetName(); + exportCategory(simPdf->indexCat(), child); + child["distributions"].set_seq(); + for (auto const &item : simPdf->indexCat()) { + child["distributions"].append_child() << simPdf->getPdf(item.first.c_str())->GetName(); + } + + return; + } else if (dynamic_cast(&func)) { // categories are created by the respective RooSimultaneous, so we're skipping the export here - return nullptr; - } else if (func->InheritsFrom(RooRealVar::Class()) || func->InheritsFrom(RooConstVar::Class())) { - // for variables, call the variable exporter - exportVariable(func, n); - return nullptr; + return; + } else if (dynamic_cast(&func) || dynamic_cast(&func)) { + exportVariable(&func, *_varsNode); + return; } - TClass *cl = TClass::GetClass(func->ClassName()); + auto &collectionNode = (*_rootnodeOutput)[dynamic_cast(&func) ? "distributions" : "functions"]; + + auto const &exporters = RooFit::JSONIO::exporters(); + auto const &exportKeys = RooFit::JSONIO::exportKeys(); + + TClass *cl = func.IsA(); + + auto &elem = appendNamedChild(collectionNode, name); auto it = exporters.find(cl); if (it != exporters.end()) { // check if we have a specific exporter available for (auto &exp : it->second) { - try { - auto &elem = n[func->GetName()]; + _serversToExport.clear(); + if (!exp->exportObject(this, &func, elem)) { + // The exporter might have messed with the content of the node + // before failing. That's why we clear it and only reset the name. + elem.clear(); elem.set_map(); - if (!exp->exportObject(this, func, elem)) { - continue; + if (useListsInsteadOfDicts) { + elem["name"] << name; + } + continue; + } + if (exp->autoExportDependants()) { + for (RooAbsArg *s : func.servers()) { + this->exportObject(*s, exportedObjectNames); } - if (exp->autoExportDependants()) { - RooJSONFactoryWSTool::exportDependants(func); + } else { + for (RooAbsArg const *s : _serversToExport) { + this->exportObject(*s, exportedObjectNames); } - RooJSONFactoryWSTool::exportAttributes(func, elem); - return &elem; - } catch (const std::exception &ex) { - std::cerr << "error exporting " << func->Class()->GetName() << " " << func->GetName() << ": " << ex.what() - << ". skipping." << std::endl; - return nullptr; } + return; } } // generic export using the factory expressions const auto &dict = exportKeys.find(cl); if (dict == exportKeys.end()) { - std::cerr << "unable to export class '" << cl->GetName() << "' - no export keys available!" << std::endl; - std::cerr << "there are several possible reasons for this:" << std::endl; - std::cerr << " 1. " << cl->GetName() << " is a custom class that you or some package you are using added." - << std::endl; - std::cerr << " 2. " << cl->GetName() - << " is a ROOT class that nobody ever bothered to write a serialization definition for." << std::endl; - std::cerr << " 3. something is wrong with your setup, e.g. you might have called " - "RooJSONFactoryWSTool::clearExportKeys() and/or never successfully read a file defining these " - "keys with RooJSONFactoryWSTool::loadExportKeys(filename)" - << std::endl; - std::cerr << "either way, please make sure that:" << std::endl; - std::cerr << " 3: you are reading a file with export keys - call RooJSONFactoryWSTool::printExportKeys() to " - "see what is available" - << std::endl; - std::cerr << " 2 & 1: you might need to write a serialization definition yourself. check " + std::cerr << "unable to export class '" << cl->GetName() << "' - no export keys available!\n" + << "there are several possible reasons for this:\n" + << " 1. " << cl->GetName() << " is a custom class that you or some package you are using added.\n" + << " 2. " << cl->GetName() + << " is a ROOT class that nobody ever bothered to write a serialization definition for.\n" + << " 3. something is wrong with your setup, e.g. you might have called " + "RooFit::JSONIO::clearExportKeys() and/or never successfully read a file defining these " + "keys with RooFit::JSONIO::loadExportKeys(filename)\n" + << "either way, please make sure that:\n" + << " 3: you are reading a file with export keys - call RooFit::JSONIO::printExportKeys() to " + "see what is available\n" + << " 2 & 1: you might need to write a serialization definition yourself. check " "https://github.com/root-project/root/blob/master/roofit/hs3/README.md to " - "see how to do this!" - << std::endl; - return nullptr; + "see how to do this!\n"; + return; } - RooJSONFactoryWSTool::exportDependants(func); - - auto &elem = n[func->GetName()]; - elem.set_map(); elem["type"] << dict->second.type; - size_t nprox = func->numProxies(); + size_t nprox = func.numProxies(); + for (size_t i = 0; i < nprox; ++i) { - RooAbsProxy *p = func->getProxy(i); + RooAbsProxy *p = func.getProxy(i); + // some proxies start with a "!". This is a magic symbol that we don't want to stream std::string pname(p->name()); if (pname[0] == '!') pname.erase(0, 1); @@ -636,867 +1110,1004 @@ JSONNode *RooJSONFactoryWSTool::exportObject(const RooAbsArg *func) auto k = dict->second.proxies.find(pname); if (k == dict->second.proxies.end()) { std::cerr << "failed to find key matching proxy '" << pname << "' for type '" << dict->second.type - << "', skipping" << std::endl; - return nullptr; + << "', encountered in '" << func.GetName() << "', skipping" << std::endl; + return; } - RooListProxy *l = dynamic_cast(p); - if (l) { - auto &items = elem[k->second]; - items.set_seq(); - for (auto e : *l) { - items.append_child() << e->GetName(); - } + // empty string is interpreted as an instruction to ignore this value + if (k->second.empty()) + continue; + + if (auto l = dynamic_cast(p)) { + fillSeq(elem[k->second], *l); } - RooRealProxy *r = dynamic_cast(p); - if (r) { - elem[k->second] << r->arg().GetName(); + if (auto r = dynamic_cast(p)) { + if (isLiteralConstVar(r->arg())) + elem[k->second] << r->arg().getVal(); + else + elem[k->second] << r->arg().GetName(); } } - RooJSONFactoryWSTool::exportAttributes(func, elem); - return &elem; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing functions -void RooJSONFactoryWSTool::importFunctions(const JSONNode &n) -{ - // import a list of RooAbsReal objects - if (!n.is_map()) - return; - for (const auto &p : n.children()) { - importFunction(p, false); + // export all the servers of a given RooAbsArg + for (RooAbsArg *s : func.servers()) { + this->exportObject(*s, exportedObjectNames); } } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing functions -void RooJSONFactoryWSTool::importFunction(const JSONNode &p, bool isPdf) +/** + * @brief Import a function from the JSONNode into the workspace. + * + * This function imports a function from the given JSONNode into the workspace. + * The function's information is read from the JSONNode and added to the workspace. + * + * @param p The JSONNode representing the function to be imported. + * @param importAllDependants A boolean flag indicating whether to import all dependants (servers) of the function. + * @return void + */ +void RooJSONFactoryWSTool::importFunction(const JSONNode &p, bool importAllDependants) { auto const &importers = RooFit::JSONIO::importers(); - auto const &pdfFactoryExpressions = RooFit::JSONIO::pdfImportExpressions(); - auto const &funcFactoryExpressions = RooFit::JSONIO::functionImportExpressions(); + auto const &factoryExpressions = RooFit::JSONIO::importExpressions(); // some preparations: what type of function are we dealing with here? std::string name(RooJSONFactoryWSTool::name(p)); - // if it's an empty name, it's a lost cause, let's just skip it - if (name.empty()) + if (!::isValidName(name)) { + std::stringstream ss; + ss << "RooJSONFactoryWSTool() function name '" << name << "' is not valid!" << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + } + + // if the RooAbsArg already exists, we don't need to do anything + if (_workspace.arg(name)) { return; - // if the function already exists, we don't need to do anything - if (isPdf) { - if (_workspace.pdf(name.c_str())) - return; - } else { - if (_workspace.function(name)) - return; } // if the key we found is not a map, it's an error if (!p.is_map()) { std::stringstream ss; ss << "RooJSONFactoryWSTool() function node " + name + " is not a map!"; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return; } - std::string prefix = RooJSONFactoryWSTool::genPrefix(p, true); + std::string prefix = genPrefix(p, true); if (!prefix.empty()) name = prefix + name; if (!p.has_child("type")) { std::stringstream ss; ss << "RooJSONFactoryWSTool() no type given for function '" << name << "', skipping." << std::endl; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return; } - bool toplevel = false; - if (isPdf && p.has_child("tags")) { - toplevel = RooJSONFactoryWSTool::find(p["tags"], "toplevel"); + std::string functype(p["type"].val()); + + // import all dependents if importing a workspace, not for creating new objects + if (!importAllDependants) { + this->importDependants(p); } - std::string functype(p["type"].val()); - this->importDependants(p); - - try { - // check for specific implementations - auto it = importers.find(functype); - bool ok = false; - if (it != importers.end()) { - for (auto &imp : it->second) { - ok = isPdf ? imp->importPdf(this, p) : imp->importFunction(this, p); - if (ok) - break; - } + // check for specific implementations + auto it = importers.find(functype); + bool ok = false; + if (it != importers.end()) { + for (auto &imp : it->second) { + ok = imp->importArg(this, p); + if (ok) + break; } - if (!ok) { // generic import using the factory expressions - auto expr = isPdf ? pdfFactoryExpressions.find(functype) : funcFactoryExpressions.find(functype); - if (expr != (isPdf ? pdfFactoryExpressions.end() : funcFactoryExpressions.end())) { - std::string expression = ::generate(expr->second, p, this); - if (!_workspace.factory(expression)) { - std::stringstream ss; - ss << "RooJSONFactoryWSTool() failed to create " << expr->second.tclass->GetName() << " '" << name - << "', skipping. expression was\n" - << expression << std::endl; - logInputArgumentsError(std::move(ss)); - } - } else { + } + if (!ok) { // generic import using the factory expressions + auto expr = factoryExpressions.find(functype); + if (expr != factoryExpressions.end()) { + std::string expression = ::generate(expr->second, p, this); + if (!_workspace.factory(expression)) { std::stringstream ss; - ss << "RooJSONFactoryWSTool() no handling for type '" << functype << "' implemented, skipping." - << "\n" - << "there are several possible reasons for this:\n" - << " 1. " << functype << " is a custom type that is not available in RooFit.\n" - << " 2. " << functype - << " is a ROOT class that nobody ever bothered to write a deserialization definition for.\n" - << " 3. something is wrong with your setup, e.g. you might have called " - "RooJSONFactoryWSTool::clearFactoryExpressions() and/or never successfully read a file defining " - "these expressions with RooJSONFactoryWSTool::loadFactoryExpressions(filename)\n" - << "either way, please make sure that:\n" - << " 3: you are reading a file with factory expressions - call " - "RooJSONFactoryWSTool::printFactoryExpressions() " - "to see what is available\n" - << " 2 & 1: you might need to write a deserialization definition yourself. check " - "https://github.com/root-project/root/blob/master/roofit/hs3/README.md to see " - "how to do this!" - << std::endl; - logInputArgumentsError(std::move(ss)); - return; + ss << "RooJSONFactoryWSTool() failed to create " << expr->second.tclass->GetName() << " '" << name + << "', skipping. expression was\n" + << expression << std::endl; + RooJSONFactoryWSTool::error(ss.str()); } - } - RooAbsReal *func = _workspace.function(name); - if (!func) { - std::stringstream err; - err << "something went wrong importing function '" << name << "'."; - RooJSONFactoryWSTool::error(err.str().c_str()); } else { - ::importAttributes(func, p); - - if (isPdf && toplevel) { - configureToplevelPdf(p, *static_cast(func)); - } + std::stringstream ss; + ss << "RooJSONFactoryWSTool() no handling for type '" << functype << "' implemented, skipping." + << "\n" + << "there are several possible reasons for this:\n" + << " 1. " << functype << " is a custom type that is not available in RooFit.\n" + << " 2. " << functype + << " is a ROOT class that nobody ever bothered to write a deserialization definition for.\n" + << " 3. something is wrong with your setup, e.g. you might have called " + "RooFit::JSONIO::clearFactoryExpressions() and/or never successfully read a file defining " + "these expressions with RooFit::JSONIO::loadFactoryExpressions(filename)\n" + << "either way, please make sure that:\n" + << " 3: you are reading a file with factory expressions - call " + "RooFit::JSONIO::printFactoryExpressions() " + "to see what is available\n" + << " 2 & 1: you might need to write a deserialization definition yourself. check " + "https://github.com/root-project/root/blob/master/roofit/hs3/README.md to see " + "how to do this!" + << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + return; } - } catch (const RooJSONFactoryWSTool::DependencyMissingError &ex) { - throw; - } catch (const RooJSONFactoryWSTool::MissingRootnodeError &ex) { - throw; - } catch (const std::exception &ex) { - std::stringstream ss; - ss << "RooJSONFactoryWSTool(): error importing " << name << ": " << ex.what() << ". skipping." << std::endl; - logInputArgumentsError(std::move(ss)); + } + RooAbsReal *func = _workspace.function(name); + if (!func) { + std::stringstream err; + err << "something went wrong importing function '" << name << "'."; + RooJSONFactoryWSTool::error(err.str()); } } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// generating an unbinned dataset from a binned one - -std::unique_ptr RooJSONFactoryWSTool::unbinned(RooDataHist const &hist) +/** + * @brief Import a function from a JSON string into the workspace. + * + * This function imports a function from the provided JSON string into the workspace. + * The function's information is read from the JSON string and added to the workspace. + * + * @param jsonString The JSON string containing the function information. + * @param importAllDependants A boolean flag indicating whether to import all dependants (servers) of the function. + * @return void + */ +void RooJSONFactoryWSTool::importFunction(const std::string &jsonString, bool importAllDependants) { - RooArgSet obs(*hist.get()); - RooRealVar *weight = this->getWeightVar("weight"); - obs.add(*weight, true); - auto data = std::make_unique(hist.GetName(), hist.GetTitle(), obs, RooFit::WeightVar(*weight)); - for (int i = 0; i < hist.numEntries(); ++i) { - data->add(*hist.get(i), hist.weight(i)); - } - return data; + this->importFunction((JSONTree::create(jsonString))->rootnode(), importAllDependants); } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// generating a weight variable - -RooRealVar *RooJSONFactoryWSTool::getWeightVar(const char *weightName) +/** + * @brief Export histogram data to a JSONNode. + * + * This function exports histogram data, represented by the provided variables and contents, to a JSONNode. + * The histogram's axes information and bin contents are added as key-value pairs to the JSONNode. + * + * @param vars The RooArgSet representing the variables associated with the histogram. + * @param n The number of bins in the histogram. + * @param contents A pointer to the array containing the bin contents of the histogram. + * @param output The JSONNode to which the histogram data will be exported. + * @return void + */ +void RooJSONFactoryWSTool::exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, JSONNode &output) { - RooRealVar *weightVar = _workspace.var(weightName); - if (!weightVar) { - _workspace.factory(std::string(weightName) + "[0.,0.,10000000]"); + auto &observablesNode = output["axes"].set_seq(); + // axes have to be ordered to get consistent bin indices + for (auto *var : static_range_cast(vars)) { + JSONNode &obsNode = observablesNode.append_child().set_map(); + obsNode["name"] << var->GetName(); + if (var->getBinning().isUniform()) { + obsNode["min"] << var->getMin(); + obsNode["max"] << var->getMax(); + obsNode["nbins"] << var->getBins(); + } else { + auto &edges = obsNode["edges"]; + edges.set_seq(); + double val = var->getBinning().binLow(0); + edges.append_child() << val; + for (int i = 0; i < var->getBinning().numBins(); ++i) { + val = var->getBinning().binHigh(i); + edges.append_child() << val; + } + } } - weightVar = _workspace.var(weightName); - return weightVar; + + return exportArray(n, contents, output["contents"]); } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing data -std::map> RooJSONFactoryWSTool::loadData(const JSONNode &n) +/** + * @brief Export an array of doubles to a JSONNode. + * + * This function exports an array of doubles, represented by the provided size and contents, + * to a JSONNode. The array elements are added to the JSONNode as a sequence of values. + * + * @param n The size of the array. + * @param contents A pointer to the array containing the double values. + * @param output The JSONNode to which the array will be exported. + * @return void + */ +void RooJSONFactoryWSTool::exportArray(std::size_t n, double const *contents, JSONNode &output) { - std::map> dataMap; - if (!n.is_map()) { - return dataMap; - } - for (const auto &p : n.children()) { - std::string name(RooJSONFactoryWSTool::name(p)); - if (name.empty()) - continue; - if (_workspace.data(name.c_str())) - continue; - if (!p.is_map()) - continue; - if (p.has_child("counts")) { - // binned - RooArgSet vars; - this->getObservables(_workspace, p, name, vars); - dataMap[name] = this->readBinnedData(_workspace, p, name, vars); - } else if (p.has_child("coordinates")) { - // unbinned - RooArgSet vars; - this->getObservables(_workspace, p, name, vars); - RooArgList varlist(vars); - RooRealVar *weightVar = this->getWeightVar("weight"); - vars.add(*weightVar, true); - auto data = std::make_unique(name, name, vars, RooFit::WeightVar(*weightVar)); - auto &coords = p["coordinates"]; - auto &weights = p["weights"]; - if (coords.num_children() != weights.num_children()) { - RooJSONFactoryWSTool::error("inconsistent number of coordinates and weights!"); - } - if (!coords.is_seq()) { - RooJSONFactoryWSTool::error("key 'coordinates' is not a list!"); - } - for (size_t i = 0; i < coords.num_children(); ++i) { - auto &point = coords[i]; - if (!point.is_seq()) { - RooJSONFactoryWSTool::error(TString::Format("coordinate point '%d' is not a list!", (int)i).Data()); - } - if (point.num_children() != varlist.size()) { - RooJSONFactoryWSTool::error("inconsistent number of coordinates and observables!"); - } - for (size_t j = 0; j < point.num_children(); ++j) { - auto *v = static_cast(varlist.at(j)); - v->setVal(point[j].val_float()); - } - data->add(vars, weights[i].val_float()); - } - dataMap[name] = std::move(data); - } else if (p.has_child("index")) { - // combined measurement - auto subMap = loadData(p); - auto catname = p["index"].val(); - RooCategory *channelCat = _workspace.cat(catname); - if (!channelCat) { - std::stringstream ss; - ss << "RooJSONFactoryWSTool() failed to retrieve channel category " << catname << std::endl; - logInputArgumentsError(std::move(ss)); - } else { - RooArgSet allVars; - allVars.add(*channelCat, true); - std::stack> ownedDataSets; - std::map datasets; - for (const auto &subd : subMap) { - allVars.add(*subd.second->get(), true); - if (subd.second->InheritsFrom(RooDataHist::Class())) { - ownedDataSets.push(unbinned(static_cast(*subd.second))); - datasets[subd.first] = ownedDataSets.top().get(); - } else { - datasets[subd.first] = static_cast(subd.second.get()); - } - } - RooRealVar *weightVar = this->getWeightVar("weight"); - allVars.add(*weightVar, true); - dataMap[name] = - std::make_unique(name.c_str(), name.c_str(), allVars, RooFit::Index(*channelCat), - RooFit::Import(datasets), RooFit::WeightVar(*weightVar)); - } + output.set_seq(); + for (std::size_t i = 0; i < n; ++i) { + double w = contents[i]; + // To make sure there are no unnecessary floating points in the JSON + if (int(w) == w) { + output.append_child() << int(w); } else { - std::stringstream ss; - ss << "RooJSONFactoryWSTool() failed to create dataset " << name << std::endl; - logInputArgumentsError(std::move(ss)); + output.append_child() << w; } } - return dataMap; } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// exporting data -void RooJSONFactoryWSTool::exportData(RooAbsData *data, JSONNode &n) +/** + * @brief Export a RooAbsCategory object to a JSONNode. + * + * This function exports a RooAbsCategory object, represented by the provided categories and indices, + * to a JSONNode. The category labels and corresponding indices are added to the JSONNode as key-value pairs. + * + * @param cat The RooAbsCategory object to be exported. + * @param node The JSONNode to which the category data will be exported. + * @return void + */ +void RooJSONFactoryWSTool::exportCategory(RooAbsCategory const &cat, JSONNode &node) +{ + auto &labels = node["labels"].set_seq(); + auto &indices = node["indices"].set_seq(); + + for (auto const &item : cat) { + labels.append_child() << item.first; + indices.append_child() << item.second; + } +} + +/** + * @brief Export combined data from the workspace to a custom struct. + * + * This function exports combined data from the workspace, represented by the provided RooAbsData object, + * to a CombinedData struct. The struct contains information such as variables, categories, + * and bin contents of the combined data. + * + * @param data The RooAbsData object representing the combined data to be exported. + * @return CombinedData A custom struct containing the exported combined data. + */ +RooJSONFactoryWSTool::CombinedData RooJSONFactoryWSTool::exportCombinedData(RooAbsData const &data) { - RooArgSet observables(*data->get()); - auto &output = n[data->GetName()]; - output.set_map(); - // find category observables RooAbsCategory *cat = nullptr; - for (const auto &obs : observables) { - if (obs->InheritsFrom(RooAbsCategory::Class())) { + for (RooAbsArg *obs : *data.get()) { + if (dynamic_cast(obs)) { if (cat) { - RooJSONFactoryWSTool::error("dataset '" + std::string(data->GetName()) + + RooJSONFactoryWSTool::error("dataset '" + std::string(data.GetName()) + " has several category observables!"); - } else { - cat = (RooAbsCategory *)(obs); } + cat = static_cast(obs); } } - if (cat) { - // this is a composite dataset - RooDataSet *ds = (RooDataSet *)(data); - output["index"] << cat->GetName(); - std::unique_ptr dataList{ds->split(*(cat), true)}; - if (!dataList) { - RooJSONFactoryWSTool::error("unable to split dataset '" + std::string(ds->GetName()) + "' at '" + - std::string(cat->GetName()) + "'"); - } - for (RooAbsData *absData : static_range_cast(*dataList)) { - this->exportData(absData, output); - } - } else if (data->InheritsFrom(RooDataHist::Class())) { - // this is a binned dataset - RooDataHist *dh = (RooDataHist *)(data); - exportVariables(observables, output["observables"]); - auto &weights = output["counts"]; - weights.set_seq(); - for (int i = 0; i < dh->numEntries(); ++i) { - dh->get(i); - weights.append_child() << dh->weight(); - } - } else { - // this is a regular unbinned dataset - RooDataSet *ds = (RooDataSet *)(data); - - bool singlePoint = (ds->numEntries() <= 1); - RooArgSet reduced_obs; - if (Config::stripObservables) { - if (!singlePoint) { - std::map> obs_values; - for (int i = 0; i < ds->numEntries(); ++i) { - ds->get(i); - for (const auto &obs : observables) { - RooRealVar *rv = (RooRealVar *)(obs); - obs_values[rv].push_back(rv->getVal()); - } - } - for (auto &obs_it : obs_values) { - auto &vals = obs_it.second; - double v0 = vals[0]; - bool is_const_val = std::all_of(vals.begin(), vals.end(), [v0](double v) { return v == v0; }); - if (!is_const_val) - reduced_obs.add(*(obs_it.first), true); - } - } - } else { - reduced_obs.add(observables); - } - if (reduced_obs.size() > 0) { - exportVariables(reduced_obs, output["observables"]); - } - auto &weights = singlePoint && Config::stripObservables ? output["counts"] : output["weights"]; - weights.set_seq(); - for (int i = 0; i < ds->numEntries(); ++i) { - ds->get(i); - if (!(Config::stripObservables && singlePoint)) { - auto &coordinates = output["coordinates"]; - coordinates.set_seq(); - auto &point = coordinates.append_child(); - point.set_seq(); - for (const auto &obs : reduced_obs) { - RooRealVar *rv = (RooRealVar *)(obs); - point.append_child() << rv->getVal(); - } + // prepare return value + RooJSONFactoryWSTool::CombinedData datamap; + + if (!cat) + return datamap; + // this is a combined dataset + + datamap.name = data.GetName(); + + // Write information necessary to reconstruct the combined dataset upon import + auto &child = getRooFitInternal(*_rootnodeOutput, "combined_datasets").set_map()[data.GetName()].set_map(); + child["index_cat"] << cat->GetName(); + exportCategory(*cat, child); + + // Find a RooSimultaneous model that would fit to this dataset + RooSimultaneous const *simPdf = nullptr; + auto *combinedPdfInfoNode = findRooFitInternal(*_rootnodeOutput, "combined_distributions"); + if (combinedPdfInfoNode) { + for (auto &info : combinedPdfInfoNode->children()) { + if (info["index_cat"].val() == cat->GetName()) { + simPdf = static_cast(_workspace.pdf(info.key())); } - weights.append_child() << ds->weight(); } } -} -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// create several observables -void RooJSONFactoryWSTool::getObservables(RooWorkspace &ws, const JSONNode &n, const std::string &obsnamecomp, - RooArgSet &out) -{ - auto vars = RooJSONFactoryWSTool::readObservables(n, obsnamecomp); - for (auto v : vars) { - std::string name(v.first); - if (ws.var(name)) { - out.add(*ws.var(name)); - } else { - out.add(*RooJSONFactoryWSTool::createObservable(ws, name, v.second)); - } - } -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// create an observable -RooRealVar * -RooJSONFactoryWSTool::createObservable(RooWorkspace &ws, const std::string &name, const RooJSONFactoryWSTool::Var &var) -{ - ws.factory(name + "[" + std::to_string(var.min) + "]"); - RooRealVar *rrv = ws.var(name); - rrv->setMin(var.min); - rrv->setMax(var.max); - rrv->setConstant(true); - rrv->setBins(var.nbins); - rrv->setAttribute("observable"); - return rrv; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// reading binned data -std::unique_ptr RooJSONFactoryWSTool::readBinnedData(RooWorkspace &ws, const JSONNode &n, - const std::string &namecomp, RooArgList varlist) -{ - if (!n.is_map()) - RooJSONFactoryWSTool::error("data is not a map"); - if (varlist.empty()) { - std::string obsname = "obs_x_" + namecomp; - varlist.add(*ws.factory(obsname + "[0.]")); - } - auto bins = RooJSONFactoryWSTool::generateBinIndices(varlist); - if (!n.has_child("counts")) - RooJSONFactoryWSTool::error("no counts given"); - if (!n["counts"].is_seq()) - RooJSONFactoryWSTool::error("counts are not in list form"); - auto &counts = n["counts"]; - if (counts.num_children() != bins.size()) - RooJSONFactoryWSTool::error(TString::Format("inconsistent bin numbers: counts=%d, bins=%d", - (int)counts.num_children(), (int)(bins.size()))); - auto dh = std::make_unique(("dataHist_" + namecomp).c_str(), namecomp.c_str(), varlist); - // temporarily disable dirty flag propagation when filling the RDH - std::vector initVals; - for (auto &v : varlist) { - v->setDirtyInhibit(true); - initVals.push_back(((RooRealVar *)v)->getVal()); - } - for (size_t ibin = 0; ibin < bins.size(); ++ibin) { - for (size_t i = 0; i < bins[ibin].size(); ++i) { - RooRealVar *v = (RooRealVar *)(varlist.at(i)); - v->setBin(bins[ibin][i]); - } - dh->add(varlist, counts[ibin].val_float()); - } - // re-enable dirty flag propagation - for (size_t i = 0; i < varlist.size(); ++i) { - RooRealVar *v = (RooRealVar *)(varlist.at(i)); - v->setVal(initVals[i]); - v->setDirtyInhibit(false); + // If there is an associated simultaneous pdf for the index category, we + // use the RooAbsData::split() overload that takes the RooSimultaneous. + // Like this, the observables that are not relevant for a given channel + // are automatically split from the component datasets. + std::unique_ptr dataList{simPdf ? data.split(*simPdf, true) : data.split(*cat, true)}; + + for (RooAbsData *absData : static_range_cast(*dataList)) { + std::string catName(absData->GetName()); + absData->SetName((std::string(data.GetName()) + "_" + catName).c_str()); + datamap.components[catName] = absData->GetName(); + this->exportData(*absData); } - return dh; + return datamap; } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// read observables -std::map -RooJSONFactoryWSTool::readObservables(const JSONNode &n, const std::string &obsnamecomp) -{ - std::map vars; - if (!n.is_map()) - return vars; - if (n.has_child("observables")) { - auto &observables = n["observables"]; - if (!observables.is_map()) - return vars; - if (observables.has_child("nbins")) { - vars.emplace(std::make_pair("obs_x_" + obsnamecomp, RooJSONFactoryWSTool::Var(observables))); - } else { - for (const auto &p : observables.children()) { - vars.emplace(std::make_pair(RooJSONFactoryWSTool::name(p), RooJSONFactoryWSTool::Var(p))); +/** + * @brief Export data from the workspace to a JSONNode. + * + * This function exports data represented by the provided RooAbsData object, + * to a JSONNode. The data's information is added as key-value pairs to the JSONNode. + * + * @param data The RooAbsData object representing the data to be exported. + * @return void + */ +void RooJSONFactoryWSTool::exportData(RooAbsData const &data) +{ + // find category observables + RooAbsCategory *cat = nullptr; + for (RooAbsArg *obs : *data.get()) { + if (dynamic_cast(obs)) { + if (cat) { + RooJSONFactoryWSTool::error("dataset '" + std::string(data.GetName()) + + " has several category observables!"); } + cat = static_cast(obs); } - } else { - vars.emplace(std::make_pair("obs_x_" + obsnamecomp, RooJSONFactoryWSTool::Var(n["counts"].num_children()))); } - return vars; -} -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing pdfs -void RooJSONFactoryWSTool::importPdfs(const JSONNode &n) -{ - // import a list of RooAbsPdf objects - if (!n.is_map()) + if (cat) return; - for (const auto &p : n.children()) { - this->importFunction(p, true); + + JSONNode &output = appendNamedChild((*_rootnodeOutput)["data"], data.GetName()); + + // this is a binned dataset + if (auto dh = dynamic_cast(&data)) { + output["type"] << "binned"; + return exportHisto(*dh->get(), dh->numEntries(), dh->weightArray(), output); + } + + // this is a regular unbinned dataset + + // This works around a problem in RooStats/HistFactory that was only fixed + // in ROOT 6.30: until then, the weight variable of the observed dataset, + // called "weightVar", was added to the observables. Therefore, it also got + // added to the Asimov dataset. But the Asimov has its own weight variable, + // called "binWeightAsimov", making "weightVar" an actual observable in the + // Asimov data. But this is only by accident and should be removed. + RooArgSet variables = *data.get(); + if (auto weightVar = variables.find("weightVar")) { + variables.remove(*weightVar); + } + + // Check if this actually represents a binned dataset, and then import it + // like a RooDataHist. This happens frequently when people create combined + // RooDataSets from binned data to fit HistFactory models. In this case, it + // doesn't make sense to export them like an unbinned dataset, because the + // coordinates are redundant information with the binning. We only do this + // for 1D data for now. + if (data.isWeighted() && variables.size() == 1) { + bool isBinnedData = false; + auto &x = static_cast(*variables[0]); + std::vector contents; + int i = 0; + for (; i < data.numEntries(); ++i) { + data.get(i); + if (x.getBin() != i) + break; + contents.push_back(data.weight()); + } + if (i == x.getBins()) + isBinnedData = true; + if (isBinnedData) { + output["type"] << "binned"; + return exportHisto(variables, data.numEntries(), contents.data(), output); + } + } + + output["type"] << "unbinned"; + + for (RooAbsArg *arg : variables) { + exportVariable(arg, output["axes"]); + } + auto &coords = output["entries"].set_seq(); + auto *weights = data.isWeighted() ? &output["weights"].set_seq() : nullptr; + for (int i = 0; i < data.numEntries(); ++i) { + data.get(i); + coords.append_child().fill_seq(variables, [](auto x) { return static_cast(x)->getVal(); }); + if (weights) + weights->append_child() << data.weight(); } } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// configure a pdf as "toplevel" by creating a modelconfig for it -void RooJSONFactoryWSTool::configureToplevelPdf(const JSONNode &p, RooAbsPdf &pdf) +/** + * @brief Read axes from the JSONNode and create a RooArgSet representing them. + * + * This function reads axes information from the given JSONNode and + * creates a RooArgSet with variables representing these axes. + * + * @param topNode The JSONNode containing the axes information to be read. + * @return RooArgSet A RooArgSet containing the variables created from the JSONNode. + */ +RooArgSet RooJSONFactoryWSTool::readAxes(const JSONNode &topNode) { - // if this is a toplevel pdf, also create a modelConfig for it - std::string mcname = "ModelConfig"; - if (p.has_child("dict")) { - if (p["dict"].has_child("ModelConfig")) { - mcname = p["dict"]["ModelConfig"].val(); - } - } - { - RooStats::ModelConfig mc{mcname.c_str(), pdf.GetName()}; - _workspace.import(mc); - } - auto *inwsmc = dynamic_cast(_workspace.obj(mcname)); - if (inwsmc) { - inwsmc->SetWS(_workspace); - inwsmc->SetPdf(pdf); - RooArgSet observables; - RooArgSet nps; - RooArgSet pois; - RooArgSet globs; - std::unique_ptr pdfVars{pdf.getVariables()}; - for (auto &var : _workspace.allVars()) { - if (!pdfVars->find(*var)) - continue; - if (var->getAttribute("observable")) { - observables.add(*var, true); - } - if (var->getAttribute("np")) { - nps.add(*var, true); - } - if (var->getAttribute("poi")) { - pois.add(*var, true); + RooArgSet vars; + + for (JSONNode const &node : topNode["axes"].children()) { + if (node.has_child("edges")) { + std::vector edges; + for (auto const &bound : node["edges"].children()) { + edges.push_back(bound.val_double()); } - if (var->getAttribute("glob")) { - globs.add(*var, true); + auto obs = std::make_unique(node["name"].val().c_str(), node["name"].val().c_str(), edges[0], + edges[edges.size() - 1]); + RooBinning bins(obs->getMin(), obs->getMax()); + for (auto b : edges) { + bins.addBoundary(b); } + obs->setBinning(bins); + vars.addOwned(std::move(obs)); + } else { + auto obs = std::make_unique(node["name"].val().c_str(), node["name"].val().c_str(), + node["min"].val_double(), node["max"].val_double()); + obs->setBins(node["nbins"].val_int()); + vars.addOwned(std::move(obs)); } - inwsmc->SetObservables(observables); - inwsmc->SetParametersOfInterest(pois); - inwsmc->SetNuisanceParameters(nps); - inwsmc->SetGlobalObservables(globs); - } else { - std::stringstream ss; - ss << "RooJSONFactoryWSTool() object '" << mcname << "' in workspace is not of type RooStats::ModelConfig!" - << std::endl; - logInputArgumentsError(std::move(ss)); } + + return vars; } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing variables -void RooJSONFactoryWSTool::importVariables(const JSONNode &n) +/** + * @brief Read binned data from the JSONNode and create a RooDataHist object. + * + * This function reads binned data from the given JSONNode and creates a RooDataHist object. + * The binned data is associated with the specified name and variables (RooArgSet) in the workspace. + * + * @param n The JSONNode representing the binned data to be read. + * @param name The name to be associated with the created RooDataHist object. + * @param vars The RooArgSet representing the variables associated with the binned data. + * @return std::unique_ptr A unique pointer to the created RooDataHist object. + */ +std::unique_ptr +RooJSONFactoryWSTool::readBinnedData(const JSONNode &n, const std::string &name, RooArgSet const &vars) { - // import a list of RooRealVar objects - if (!n.is_map()) - return; - for (const auto &p : n.children()) { - importVariable(p); + if (!n.has_child("contents")) + RooJSONFactoryWSTool::error("no contents given"); + + JSONNode const &contents = n["contents"]; + + if (!contents.is_seq()) + RooJSONFactoryWSTool::error("contents are not in list form"); + + JSONNode const *errors = nullptr; + if (n.has_child("errors")) { + errors = &n["errors"]; + if (!errors->is_seq()) + RooJSONFactoryWSTool::error("errors are not in list form"); + } + + auto bins = generateBinIndices(vars); + if (contents.num_children() != bins.size()) { + std::stringstream errMsg; + errMsg << "inconsistent bin numbers: contents=" << contents.num_children() << ", bins=" << bins.size(); + RooJSONFactoryWSTool::error(errMsg.str()); + } + auto dh = std::make_unique(name, name, vars); + std::vector contentVals; + contentVals.reserve(contents.num_children()); + for (auto const &cont : contents.children()) { + contentVals.push_back(cont.val_double()); + } + std::vector errorVals; + if (errors) { + errorVals.reserve(errors->num_children()); + for (auto const &err : errors->children()) { + errorVals.push_back(err.val_double()); + } + } + for (size_t ibin = 0; ibin < bins.size(); ++ibin) { + const double err = errors ? errorVals[ibin] : -1; + dh->set(ibin, contentVals[ibin], err); } + return dh; } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// importing variable +/** + * @brief Import a variable from the JSONNode into the workspace. + * + * This function imports a variable from the given JSONNode into the workspace. + * The variable's information is read from the JSONNode and added to the workspace. + * + * @param p The JSONNode representing the variable to be imported. + * @return void + */ void RooJSONFactoryWSTool::importVariable(const JSONNode &p) { // import a RooRealVar object std::string name(RooJSONFactoryWSTool::name(p)); + + if (!::isValidName(name)) { + std::stringstream ss; + ss << "RooJSONFactoryWSTool() variable name '" << name << "' is not valid!" << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + } + if (_workspace.var(name)) return; if (!p.is_map()) { std::stringstream ss; - ss << "RooJSONFactoryWSTool() node '" << name << "' is not a map, skipping." << std::endl; - logInputArgumentsError(std::move(ss)); + ss << "RooJSONFactoryWSTool() node '" << name << "' is not a map, skipping."; + oocoutE(nullptr, InputArguments) << ss.str() << std::endl; return; } - RooRealVar v(name.c_str(), name.c_str(), 1.); - configureVariable(p, v); - ::importAttributes(&v, p); - _workspace.import(v, RooFit::RecycleConflictNodes(true), RooFit::Silence(true)); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// configuring variable -void RooJSONFactoryWSTool::configureVariable(const JSONNode &p, RooRealVar &v) -{ - if (p.has_child("value")) - v.setVal(p["value"].val_float()); - if (p.has_child("min")) - v.setMin(p["min"].val_float()); - if (p.has_child("max")) - v.setMax(p["max"].val_float()); - if (p.has_child("nbins")) - v.setBins(p["nbins"].val_int()); - if (p.has_child("relErr")) - v.setError(v.getVal() * p["relErr"].val_float()); - if (p.has_child("err")) - v.setError(p["err"].val_float()); - if (p.has_child("const")) - v.setConstant(p["const"].val_bool()); - else - v.setConstant(false); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// export all dependants (servers) of a RooAbsArg -void RooJSONFactoryWSTool::exportDependants(const RooAbsArg *source) -{ - // export all the servers of a given RooAbsArg - auto servers(source->servers()); - for (auto s : servers) { - this->exportObject(s); + if (_attributesNode) { + if (auto *attrNode = _attributesNode->find(name)) { + // We should not create RooRealVar objects for RooConstVars! + if (attrNode->has_child("is_const_var") && (*attrNode)["is_const_var"].val_int() == 1) { + wsEmplace(name, p["value"].val_double()); + return; + } + } } + configureVariable(*_domains, p, wsEmplace(name, 1.)); } -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// import all dependants (servers) of a node +/** + * @brief Import all dependants (servers) of a node into the workspace. + * + * This function imports all the dependants (servers) of the given JSONNode into the workspace. + * The dependants' information is read from the JSONNode and added to the workspace. + * + * @param n The JSONNode representing the node whose dependants are to be imported. + * @return void + */ void RooJSONFactoryWSTool::importDependants(const JSONNode &n) { // import all the dependants of an object - if (n.has_child("variables")) { - this->importVariables(n["variables"]); + if (JSONNode const *varsNode = getVariablesNode(n)) { + for (const auto &p : varsNode->children()) { + importVariable(p); + } + } + if (auto seq = n.find("functions")) { + for (const auto &p : seq->children()) { + this->importFunction(p, true); + } } - if (n.has_child("functions")) { - this->importFunctions(n["functions"]); + if (auto seq = n.find("distributions")) { + for (const auto &p : seq->children()) { + this->importFunction(p, true); + } + } +} + +void RooJSONFactoryWSTool::exportModelConfig(JSONNode &rootnode, RooStats::ModelConfig const &mc, + const std::vector &combDataSets) +{ + auto pdf = dynamic_cast(mc.GetPdf()); + if (pdf == nullptr) { + warning("RooFitHS3 only supports ModelConfigs with RooSimultaneous! Skipping ModelConfig."); + return; } - if (n.has_child("pdfs")) { - this->importPdfs(n["pdfs"]); + + for (std::size_t i = 0; i < std::max(combDataSets.size(), std::size_t(1)); ++i) { + const bool hasdata = i < combDataSets.size(); + if (hasdata && !matches(combDataSets.at(i), pdf)) + continue; + + std::string analysisName(pdf->GetName()); + if (hasdata) + analysisName += "_" + combDataSets[i].name; + + exportSingleModelConfig(rootnode, mc, analysisName, hasdata ? &combDataSets[i].components : nullptr); } } -std::string RooJSONFactoryWSTool::name(const JSONNode &n) +void RooJSONFactoryWSTool::exportSingleModelConfig(JSONNode &rootnode, RooStats::ModelConfig const &mc, + std::string const &analysisName, + std::map const *dataComponents) { - std::stringstream ss; - if (n.is_container() && n.has_child("name")) { - ss << n["name"].val(); - } else if (n.has_key()) { - ss << n.key(); - } else { - ss << n.val(); + auto pdf = static_cast(mc.GetPdf()); + + JSONNode &analysisNode = appendNamedChild(rootnode["analyses"], analysisName); + + analysisNode["domains"].set_seq().append_child() << "default_domain"; + + analysisNode["likelihood"] << analysisName; + + auto &nllNode = appendNamedChild(rootnode["likelihoods"], analysisName); + nllNode["distributions"].set_seq(); + nllNode["data"].set_seq(); + + if (dataComponents) { + for (auto const &item : pdf->indexCat()) { + const auto &dataComp = dataComponents->find(item.first); + nllNode["distributions"].append_child() << pdf->getPdf(item.first)->GetName(); + nllNode["data"].append_child() << dataComp->second; + } } - return ss.str(); + + if (mc.GetExternalConstraints()) { + auto &extConstrNode = nllNode["aux_distributions"]; + extConstrNode.set_seq(); + for (const auto &constr : *mc.GetExternalConstraints()) { + extConstrNode.append_child() << constr->GetName(); + } + } + + auto writeList = [&](const char *name, RooArgSet const *args) { + if (!args) + return; + + std::vector names; + names.reserve(args->size()); + for (RooAbsArg const *arg : *args) + names.push_back(arg->GetName()); + std::sort(names.begin(), names.end()); + analysisNode[name].fill_seq(names); + }; + + writeList("parameters_of_interest", mc.GetParametersOfInterest()); + + auto &modelConfigAux = getRooFitInternal(rootnode, "ModelConfigs", analysisName); + modelConfigAux.set_map(); + modelConfigAux["pdfName"] << pdf->GetName(); + modelConfigAux["mcName"] << mc.GetName(); } +/** + * @brief Export all objects in the workspace to a JSONNode. + * + * This function exports all the objects in the workspace to the provided JSONNode. + * The objects' information is added as key-value pairs to the JSONNode. + * + * @param n The JSONNode to which the objects will be exported. + * @return void + */ void RooJSONFactoryWSTool::exportAllObjects(JSONNode &n) { - // export all ModelConfig objects and attached Pdfs - std::vector mcs; - std::vector toplevel; - _rootnode_output = &n; - for (auto obj : _workspace.allGenericObjects()) { - if (obj->InheritsFrom(RooStats::ModelConfig::Class())) { - auto *mc = static_cast(obj); - auto &vars = n["variables"]; - if (mc->GetObservables()) { - for (auto obs : *mc->GetObservables()) { - if (auto *v = dynamic_cast(obs)) { - exportVariable(v, vars); - auto &tags = vars[v->GetName()]["tags"]; - tags.set_seq(); - RooJSONFactoryWSTool::append(tags, "observable"); - } - } - } - if (mc->GetParametersOfInterest()) { - for (auto poi : *mc->GetParametersOfInterest()) { - if (auto *v = dynamic_cast(poi)) { - exportVariable(v, vars); - auto &tags = vars[v->GetName()]["tags"]; - tags.set_seq(); - RooJSONFactoryWSTool::append(tags, "poi"); - } - } - } - if (mc->GetNuisanceParameters()) { - for (auto np : *mc->GetNuisanceParameters()) { - if (auto *v = dynamic_cast(np)) { - exportVariable(v, vars); - auto &tags = vars[v->GetName()]["tags"]; - tags.set_seq(); - RooJSONFactoryWSTool::append(tags, "np"); - } - } - } - if (mc->GetGlobalObservables()) { - for (auto *np : *mc->GetGlobalObservables()) { - if (auto *v = dynamic_cast(np)) { - exportVariable(v, vars); - auto &tags = vars[v->GetName()]["tags"]; - tags.set_seq(); - RooJSONFactoryWSTool::append(tags, "glob"); - } - } + _domains = std::make_unique(); + _varsNode = &makeVariablesNode(n); + _rootnodeOutput = &n; + + // export all toplevel pdfs + std::vector allpdfs; + for (auto &arg : _workspace.allPdfs()) { + if (!arg->hasClients()) { + if (auto *pdf = dynamic_cast(arg)) { + allpdfs.push_back(pdf); } - mcs.push_back(mc); } } - for (auto pdf : _workspace.allPdfs()) { - if (!pdf->hasClients() || pdf->getAttribute("toplevel")) { - bool hasMC = false; - for (const auto &mc : mcs) { - if (mc->GetPdf() == pdf) - hasMC = true; - } - if (!hasMC) - toplevel.push_back(static_cast(pdf)); - } - } - for (auto d : _workspace.allData()) { - auto &data = n["data"]; - data.set_map(); - this->exportData(d, data); - } - for (const auto *snsh_obj : _workspace.getSnapshots()) { - const RooArgSet *snsh = static_cast(snsh_obj); - auto &snapshots = n["snapshots"]; - snapshots.set_map(); - this->exportVariables(*snsh, snapshots[snsh->GetName()]); - } - for (const auto &mc : mcs) { - auto &pdfs = n["pdfs"]; - pdfs.set_map(); - RooAbsPdf *pdf = mc->GetPdf(); - RooJSONFactoryWSTool::exportObject(pdf); - auto &node = pdfs[pdf->GetName()]; - node.set_map(); - auto &tags = node["tags"]; - tags.set_seq(); - if (!pdf->getAttribute("toplevel")) - RooJSONFactoryWSTool::append(tags, "toplevel"); - auto &dict = node["dict"]; - dict.set_map(); - dict["ModelConfig"] << mc->GetName(); - } - for (const auto &pdf : toplevel) { - auto &pdfs = n["pdfs"]; - pdfs.set_map(); - RooJSONFactoryWSTool::exportObject(pdf); - auto &node = pdfs[pdf->GetName()]; - node.set_map(); - auto &tags = node["tags"]; - tags.set_seq(); - if (!pdf->getAttribute("toplevel")) - RooJSONFactoryWSTool::append(tags, "toplevel"); - auto &dict = node["dict"]; - dict.set_map(); - if (toplevel.size() + mcs.size() == 1) { - dict["ModelConfig"] << "ModelConfig"; - } else { - dict["ModelConfig"] << std::string(pdf->GetName()) + "_modelConfig"; + sortByName(allpdfs); + std::set exportedObjectNames; + for (RooAbsPdf *p : allpdfs) { + this->exportObject(*p, exportedObjectNames); + } + + // export attributes of all objects + for (RooAbsArg *arg : _workspace.components()) { + exportAttributes(arg, n); + } + + // export all datasets + std::vector alldata; + for (auto &d : _workspace.allData()) { + alldata.push_back(d); + } + sortByName(alldata); + // first, take care of combined datasets + std::vector combData; + for (auto &d : alldata) { + auto data = this->exportCombinedData(*d); + if (!data.components.empty()) + combData.push_back(data); + } + // next, take care of regular datasets + for (auto &d : alldata) { + this->exportData(*d); + } + + // export all ModelConfig objects and attached Pdfs + for (TObject *obj : _workspace.allGenericObjects()) { + if (auto mc = dynamic_cast(obj)) { + exportModelConfig(n, *mc, combData); + } + } + + for (auto *snsh : static_range_cast(_workspace.getSnapshots())) { + RooArgSet snapshotSorted; + // We only want to add the variables that actually got exported and skip + // the ones that the pdfs encoded implicitly (like in the case of + // HistFactory). + for (RooAbsArg *arg : *snsh) { + if (exportedObjectNames.find(arg->GetName()) != exportedObjectNames.end()) + snapshotSorted.add(*arg); + } + snapshotSorted.sort(); + std::string name(snsh->GetName()); + if (name != "default_values") { + this->exportVariables(snapshotSorted, appendNamedChild(n["parameter_points"], name)["parameters"]); } } - _rootnode_output = nullptr; + _varsNode = nullptr; + _domains->writeJSON(n["domains"]); + _domains.reset(); + _rootnodeOutput = nullptr; } +/** + * @brief Import the workspace from a JSON string. + * + * @param s The JSON string containing the workspace data. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importJSONfromString(const std::string &s) { - // import the workspace from JSON std::stringstream ss(s); return importJSON(ss); } +/** + * @brief Import the workspace from a YML string. + * + * @param s The YML string containing the workspace data. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importYMLfromString(const std::string &s) { - // import the workspace from YML std::stringstream ss(s); return importYML(ss); } +/** + * @brief Export the workspace to a JSON string. + * + * @return std::string The JSON string representing the exported workspace. + */ std::string RooJSONFactoryWSTool::exportJSONtoString() { - // export the workspace to JSON std::stringstream ss; exportJSON(ss); return ss.str(); } +/** + * @brief Export the workspace to a YML string. + * + * @return std::string The YML string representing the exported workspace. + */ std::string RooJSONFactoryWSTool::exportYMLtoString() { - // export the workspace to YML std::stringstream ss; exportYML(ss); return ss.str(); } -/// Create a new JSON tree with version information. +/** + * @brief Create a new JSON tree with version information. + * + * @return std::unique_ptr A unique pointer to the created JSON tree. + */ std::unique_ptr RooJSONFactoryWSTool::createNewJSONTree() { std::unique_ptr tree = JSONTree::create(); JSONNode &n = tree->rootnode(); n.set_map(); - n["metadata"].set_map(); - // The currently implemented HS3 standard is version 0.1 - n["metadata"]["version"] << "0.1"; + auto &metadata = n["metadata"].set_map(); + + // add the mandatory hs3 version number + metadata["hs3_version"] << hs3VersionTag; + + // Add information about the ROOT version that was used to generate this file + auto &rootInfo = appendNamedChild(metadata["packages"], "ROOT"); + std::string versionName = gROOT->GetVersion(); + // We want to consistently use dots such that the version name can be easily + // digested automatically. + std::replace(versionName.begin(), versionName.end(), '/', '.'); + rootInfo["version"] << versionName; + return tree; } +/** + * @brief Export the workspace to JSON format and write to the output stream. + * + * @param os The output stream to write the JSON data to. + * @return bool Returns true on successful export, false otherwise. + */ bool RooJSONFactoryWSTool::exportJSON(std::ostream &os) { - // export the workspace in JSON std::unique_ptr tree = createNewJSONTree(); JSONNode &n = tree->rootnode(); this->exportAllObjects(n); n.writeJSON(os); return true; } + +/** + * @brief Export the workspace to JSON format and write to the specified file. + * + * @param filename The name of the JSON file to create and write the data to. + * @return bool Returns true on successful export, false otherwise. + */ bool RooJSONFactoryWSTool::exportJSON(std::string const &filename) { - // export the workspace in JSON std::ofstream out(filename.c_str()); if (!out.is_open()) { std::stringstream ss; ss << "RooJSONFactoryWSTool() invalid output file '" << filename << "'." << std::endl; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return false; } return this->exportJSON(out); } +/** + * @brief Export the workspace to YML format and write to the output stream. + * + * @param os The output stream to write the YML data to. + * @return bool Returns true on successful export, false otherwise. + */ bool RooJSONFactoryWSTool::exportYML(std::ostream &os) { - // export the workspace in YML std::unique_ptr tree = createNewJSONTree(); JSONNode &n = tree->rootnode(); this->exportAllObjects(n); n.writeYML(os); return true; } + +/** + * @brief Export the workspace to YML format and write to the specified file. + * + * @param filename The name of the YML file to create and write the data to. + * @return bool Returns true on successful export, false otherwise. + */ bool RooJSONFactoryWSTool::exportYML(std::string const &filename) { - // export the workspace in YML std::ofstream out(filename.c_str()); if (!out.is_open()) { std::stringstream ss; ss << "RooJSONFactoryWSTool() invalid output file '" << filename << "'." << std::endl; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return false; } return this->exportYML(out); } -void RooJSONFactoryWSTool::importAllNodes(const RooFit::Detail::JSONNode &n) +bool RooJSONFactoryWSTool::hasAttribute(const std::string &obj, const std::string &attrib) { - _rootnode_input = &n; - gROOT->ProcessLine("using namespace RooStats::HistFactory;"); - this->importDependants(n); + if (!_attributesNode) + return false; + if (auto attrNode = _attributesNode->find(obj)) { + if (auto seq = attrNode->find("tags")) { + for (auto &a : seq->children()) { + if (a.val() == attrib) + return true; + } + } + } + return false; +} +void RooJSONFactoryWSTool::setAttribute(const std::string &obj, const std::string &attrib) +{ + auto node = &RooJSONFactoryWSTool::getRooFitInternal(*_rootnodeOutput, "attributes").set_map()[obj].set_map(); + auto &tags = (*node)["tags"]; + tags.set_seq(); + tags.append_child() << attrib; +} - if (n.has_child("data")) { - auto data = this->loadData(n["data"]); - for (const auto &d : data) { - _workspace.import(*d.second); +std::string RooJSONFactoryWSTool::getStringAttribute(const std::string &obj, const std::string &attrib) +{ + if (!_attributesNode) + return ""; + if (auto attrNode = _attributesNode->find(obj)) { + if (auto dict = attrNode->find("dict")) { + if (auto *a = dict->find(attrib)) { + return a->val(); + } } } + return ""; +} +void RooJSONFactoryWSTool::setStringAttribute(const std::string &obj, const std::string &attrib, + const std::string &value) +{ + auto node = &RooJSONFactoryWSTool::getRooFitInternal(*_rootnodeOutput, "attributes").set_map()[obj].set_map(); + auto &dict = (*node)["dict"]; + dict.set_map(); + dict[attrib] << value; +} + +/** + * @brief Imports all nodes of the JSON data and adds them to the workspace. + * + * @param n The JSONNode representing the root node of the JSON data. + * @return void + */ +void RooJSONFactoryWSTool::importAllNodes(const JSONNode &n) +{ + // Per HS3 standard, the hs3_version in the metadata is required. So we + // error out if it is missing. TODO: now we are only checking if the + // hs3_version tag exists, but in the future when the HS3 specification + // versions are actually frozen, we should also check if the hs3_version is + // one that RooFit can actually read. + auto metadata = n.find("metadata"); + if (!metadata || !metadata->find("hs3_version")) { + std::stringstream ss; + ss << "The HS3 version is missing in the JSON!\n" + << "Please include the HS3 version in the metadata field, e.g.:\n" + << " \"metadata\" :\n" + << " {\n" + << " \"hs3_version\" : \"" << hs3VersionTag << "\"\n" + << " }"; + error(ss.str()); + } + + _domains = std::make_unique(); + if (auto domains = n.find("domains")) { + _domains->readJSON(*domains); + } + + _rootnodeInput = &n; - _workspace.saveSnapshot("fromJSON", _workspace.allVars()); - if (n.has_child("snapshots")) { - for (const auto &snsh : n["snapshots"].children()) { + _attributesNode = findRooFitInternal(*_rootnodeInput, "attributes"); + + this->importDependants(n); + + if (auto paramPointsNode = n.find("parameter_points")) { + for (const auto &snsh : paramPointsNode->children()) { std::string name = RooJSONFactoryWSTool::name(snsh); - if (name == "fromJSON") - continue; + + if (!::isValidName(name)) { + std::stringstream ss; + ss << "RooJSONFactoryWSTool() node name '" << name << "' is not valid!" << std::endl; + RooJSONFactoryWSTool::error(ss.str()); + } + RooArgSet vars; - for (const auto &var : snsh.children()) { - std::string vname = RooJSONFactoryWSTool::name(var); - RooRealVar *rrv = _workspace.var(vname); - if (!rrv) - continue; - this->configureVariable(var, *rrv); - vars.add(*rrv); + for (const auto &var : snsh["parameters"].children()) { + if (RooRealVar *rrv = _workspace.var(RooJSONFactoryWSTool::name(var))) { + configureVariable(*_domains, var, *rrv); + vars.add(*rrv); + } } - _workspace.saveSnapshot(name.c_str(), vars); + _workspace.saveSnapshot(name, vars); + } + } + + combinePdfs(*_rootnodeInput, _workspace); + + // Import attributes + if (_attributesNode) { + for (const auto &elem : _attributesNode->children()) { + if (RooAbsArg *arg = _workspace.arg(elem.key())) + importAttributes(arg, elem); + } + } + + _attributesNode = nullptr; + + // We delay the import of the data to after combineDatasets(), because it + // might be that some datasets are merged to combined datasets there. In + // that case, we will remove the components from the "datasets" vector so they + // don't get imported. + std::vector> datasets; + if (auto dataNode = n.find("data")) { + for (const auto &p : dataNode->children()) { + datasets.push_back(loadData(p, _workspace)); + } + } + + // Now, read in analyses and likelihoods if there are any + + if (auto analysesNode = n.find("analyses")) { + for (JSONNode const &analysisNode : analysesNode->children()) { + importAnalysis(*_rootnodeInput, analysisNode, n["likelihoods"], _workspace, datasets); } } - _workspace.loadSnapshot("fromJSON"); - _rootnode_input = nullptr; + combineDatasets(*_rootnodeInput, datasets); + + for (auto const &d : datasets) { + if (d) + _workspace.import(*d); + } + + _rootnodeInput = nullptr; + _domains.reset(); } +/** + * @brief Imports a JSON file from the given input stream to the workspace. + * + * @param is The input stream containing the JSON data. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importJSON(std::istream &is) { // import a JSON file to the workspace - try { - std::unique_ptr tree = JSONTree::create(is); - this->importAllNodes(tree->rootnode()); - } catch (const std::exception &ex) { - std::cerr << "unable to import JSON: " << ex.what() << std::endl; - return false; - } + std::unique_ptr tree = JSONTree::create(is); + this->importAllNodes(tree->rootnode()); return true; } +/** + * @brief Imports a JSON file from the given filename to the workspace. + * + * @param filename The name of the JSON file to import. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importJSON(std::string const &filename) { // import a JSON file to the workspace @@ -1504,24 +2115,32 @@ bool RooJSONFactoryWSTool::importJSON(std::string const &filename) if (!infile.is_open()) { std::stringstream ss; ss << "RooJSONFactoryWSTool() invalid input file '" << filename << "'." << std::endl; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return false; } return this->importJSON(infile); } +/** + * @brief Imports a YML file from the given input stream to the workspace. + * + * @param is The input stream containing the YML data. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importYML(std::istream &is) { // import a YML file to the workspace - try { - std::unique_ptr tree = JSONTree::create(is); - this->importAllNodes(tree->rootnode()); - } catch (const std::exception &ex) { - std::cerr << "unable to import JSON: " << ex.what() << std::endl; - return false; - } + std::unique_ptr tree = JSONTree::create(is); + this->importAllNodes(tree->rootnode()); return true; } + +/** + * @brief Imports a YML file from the given filename to the workspace. + * + * @param filename The name of the YML file to import. + * @return bool Returns true on successful import, false otherwise. + */ bool RooJSONFactoryWSTool::importYML(std::string const &filename) { // import a YML file to the workspace @@ -1529,14 +2148,87 @@ bool RooJSONFactoryWSTool::importYML(std::string const &filename) if (!infile.is_open()) { std::stringstream ss; ss << "RooJSONFactoryWSTool() invalid input file '" << filename << "'." << std::endl; - logInputArgumentsError(std::move(ss)); + RooJSONFactoryWSTool::error(ss.str()); return false; } return this->importYML(infile); } -std::ostream &RooJSONFactoryWSTool::log(int level) +void RooJSONFactoryWSTool::importJSONElement(const std::string &name, const std::string &jsonString) +{ + std::unique_ptr tree = RooFit::Detail::JSONTree::create(jsonString); + JSONNode &n = tree->rootnode(); + n["name"] << name; + + bool isVariable = true; + if (n.find("type")) { + isVariable = false; + } + + if (isVariable) { + this->importVariableElement(n); + } else { + this->importFunction(n, false); + } +} + +void RooJSONFactoryWSTool::importVariableElement(const JSONNode &elementNode) +{ + std::unique_ptr tree = varJSONString(elementNode); + JSONNode &n = tree->rootnode(); + _domains = std::make_unique(); + if (auto domains = n.find("domains")) + _domains->readJSON(*domains); + + _rootnodeInput = &n; + _attributesNode = findRooFitInternal(*_rootnodeInput, "attributes"); + + JSONNode const *varsNode = getVariablesNode(n); + const auto &p = varsNode->child(0); + importVariable(p); + + auto paramPointsNode = n.find("parameter_points"); + const auto &snsh = paramPointsNode->child(0); + std::string name = RooJSONFactoryWSTool::name(snsh); + RooArgSet vars; + const auto &var = snsh["parameters"].child(0); + if (RooRealVar *rrv = _workspace.var(RooJSONFactoryWSTool::name(var))) { + configureVariable(*_domains, var, *rrv); + vars.add(*rrv); + } + + // Import attributes + if (_attributesNode) { + for (const auto &elem : _attributesNode->children()) { + if (RooAbsArg *arg = _workspace.arg(elem.key())) + importAttributes(arg, elem); + } + } + + _attributesNode = nullptr; + _rootnodeInput = nullptr; + _domains.reset(); +} + +/** + * @brief Writes a warning message to the RooFit message service. + * + * @param str The warning message to be logged. + * @return std::ostream& A reference to the output stream. + */ +std::ostream &RooJSONFactoryWSTool::warning(std::string const &str) +{ + return RooMsgService::instance().log(nullptr, RooFit::MsgLevel::ERROR, RooFit::IO) << str << std::endl; +} + +/** + * @brief Writes an error message to the RooFit message service and throws a runtime_error. + * + * @param s The error message to be logged and thrown. + * @return void + */ +void RooJSONFactoryWSTool::error(const char *s) { - return RooMsgService::instance().log(static_cast(nullptr), static_cast(level), - RooFit::IO); + RooMsgService::instance().log(nullptr, RooFit::MsgLevel::ERROR, RooFit::IO) << s << std::endl; + throw std::runtime_error(s); } diff --git a/roofit/hs3/src/static_execute.h b/roofit/hs3/src/static_execute.h index d7a10dc300b03..ce980554ba5ac 100644 --- a/roofit/hs3/src/static_execute.h +++ b/roofit/hs3/src/static_execute.h @@ -15,7 +15,7 @@ // Execute code on library loading by running code in the constructor of a // class that is a static class member of another class. -#define STATIC_EXECUTE(MY_CODE) \ +#define STATIC_EXECUTE(MY_FUNC) \ struct StaticExecutorWrapper { \ struct Executor { \ template \ @@ -27,6 +27,6 @@ static Executor executor; \ }; \ \ - StaticExecutorWrapper::Executor StaticExecutorWrapper::executor{[]() { MY_CODE }}; + StaticExecutorWrapper::Executor StaticExecutorWrapper::executor{MY_FUNC}; #endif diff --git a/roofit/hs3/test/CMakeLists.txt b/roofit/hs3/test/CMakeLists.txt index b001e594abd80..d152337c8a7a8 100644 --- a/roofit/hs3/test/CMakeLists.txt +++ b/roofit/hs3/test/CMakeLists.txt @@ -1,5 +1,2 @@ -ROOT_ADD_PYUNITTEST(roofit-hs3-histfactory-json test_hs3_histfactory_json.py - COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/test_hs3_histfactory_json_input.root - ) - ROOT_ADD_GTEST(testRooFitHS3 testRooFitHS3.cxx LIBRARIES RooFitCore RooFit RooFitHS3) +ROOT_ADD_GTEST(testHS3SimultaneousFit testHS3SimultaneousFit.cxx LIBRARIES RooFitCore RooFit RooFitHS3 RooStats) diff --git a/roofit/hs3/test/testHS3SimultaneousFit.cxx b/roofit/hs3/test/testHS3SimultaneousFit.cxx new file mode 100644 index 0000000000000..320915513fec6 --- /dev/null +++ b/roofit/hs3/test/testHS3SimultaneousFit.cxx @@ -0,0 +1,120 @@ +// Test for the JSON IO of a full workspace with a multi-channel model and +// data. +// Author: Jonas Rembser, CERN 02/2023 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace { + +std::unique_ptr writeJSONAndFitModel(std::string &jsonStr) +{ + using namespace RooFit; + + RooWorkspace ws{"workspace"}; + + // Build two channels for different observables where the distributions + // share one parameter: the mean for the signal. + + // Channel 1: Gaussian signal and exponential background + ws.factory("Gaussian::sig_1(x_1[0, 10], mean[5.0, 0, 10], sigma_1[0.5, 0.1, 10.0])"); + ws.factory("Exponential::bkg_1(x_1, c_1[-0.2, -100, -0.001])"); + ws.factory("SUM::model_1(n_sig_1[10000, 0, 10000000] * sig_1, nbkg_2[100000, 0, 10000000] * bkg_1)"); + + // Channel 2: Crystal ball signal and polynomial background + ws.factory("CBShape::sig_2(x_2[0, 10], mean[5.0, 0, 10], sigma_2[0.8, 0.1, 10.0], alpha[0.9, 0.1, 10.0], " + "ncb[1.0, 0.1, 10.0])"); + ws.factory("Polynomial::bkg_2(x_2, {3.0, a_1[-0.3, -10, 10], a_2[0.01, -10, 10]}, 0)"); + ws.factory("SUM::model_2(n_sig_2[30000, 0, 10000000] * sig_2, nbkg_2[100000, 0, 10000000] * bkg_2)"); + + // Simultaneous PDF and model config + ws.factory("SIMUL::simPdf(channelCat[channel_1=0, channel_2=1], channel_1=model_1, channel_2=model_2)"); + + RooStats::ModelConfig modelConfig{"ModelConfig"}; + + modelConfig.SetWS(ws); + modelConfig.SetPdf("simPdf"); + modelConfig.SetParametersOfInterest("mean"); + modelConfig.SetObservables("x_1,x_2"); + + ws.import(modelConfig); + + RooRealVar &x1 = *ws.var("x_1"); + RooRealVar &x2 = *ws.var("x_2"); + x1.setBins(20); + x2.setBins(20); + + std::map> datasets; + datasets["channel_1"] = std::unique_ptr{ws.pdf("model_1")->generateBinned(x1)}; + datasets["channel_2"] = std::unique_ptr{ws.pdf("model_2")->generateBinned(x2)}; + + datasets["channel_1"]->SetName("obsData_channel_1"); + datasets["channel_2"]->SetName("obsData_channel_2"); + + RooDataSet obsData{"obsData", "obsData", {x1, x2}, Index(*ws.cat("channelCat")), Import(datasets)}; + ws.import(obsData); + + auto &pdf = *ws.pdf("simPdf"); + auto &data = *ws.data("obsData"); + + // Export before fitting to keep the prefit values + jsonStr = RooJSONFactoryWSTool{ws}.exportJSONtoString(); + + return std::unique_ptr{ + pdf.fitTo(data, Save(), PrintLevel(-1), PrintEvalErrors(-1), Minimizer("Minuit2"))}; +} + +std::unique_ptr readJSONAndFitModel(std::string const &jsonStr) +{ + using namespace RooFit; + + RooWorkspace ws{"workspace"}; + RooJSONFactoryWSTool tool{ws}; + + tool.importJSONfromString(jsonStr); + + // Make sure that there is exactly one dataset in the new workspace, and + // that there are no spurious datasets left over from first importing the + // channel datasets that later get merged to the combined dataset + EXPECT_EQ(ws.allData().size(), 1) << "Unexpected number of datasets in the new workspace"; + + auto &pdf = *ws.pdf("simPdf"); + auto &data = *ws.data("obsData"); + + return std::unique_ptr{ + pdf.fitTo(data, Save(), PrintLevel(-1), PrintEvalErrors(-1), Minimizer("Minuit2"))}; +} + +} // namespace + +TEST(RooFitHS3, SimultaneousFit) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + using namespace RooFit; + + std::string jsonStr; + + std::unique_ptr res1 = writeJSONAndFitModel(jsonStr); + std::unique_ptr res2 = readJSONAndFitModel(jsonStr); + + // todo: also check the modelconfig for equality + + EXPECT_TRUE(res2->isIdentical(*res1)); +} diff --git a/roofit/hs3/test/testRooFitHS3.cxx b/roofit/hs3/test/testRooFitHS3.cxx index 3217ccd9a7eb5..fc14946cf4ee7 100644 --- a/roofit/hs3/test/testRooFitHS3.cxx +++ b/roofit/hs3/test/testRooFitHS3.cxx @@ -1,79 +1,346 @@ -#include "RooRealVar.h" -#include "RooConstVar.h" -#include "RooWorkspace.h" - -#include "TROOT.h" +// Tests for the RooJSONFactoryWSTool +// Authors: Carsten D. Burgard, DESY/ATLAS, 12/2021 +// Jonas Rembser, CERN 12/2022 #include #include -#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace { + +// If the JSON files should be written out for debugging purpose. +const bool writeJsonFiles = true; + +// Validate the JSON IO for a given RooAbsReal in a RooWorkspace. The workspace +// will be written out and read back, and then the values of the old and new +// RooAbsReal will be compared for equality in each bin of the observable that +// is called "x" by convention. +int validate(RooWorkspace &ws1, std::string const &argName, bool exact = true) +{ + RooWorkspace ws2; + + if (writeJsonFiles) { + RooJSONFactoryWSTool{ws1}.exportJSON(argName + ".json"); + } + RooJSONFactoryWSTool{ws2}.importJSONfromString(RooJSONFactoryWSTool{ws1}.exportJSONtoString()); + + RooRealVar &x1 = *ws1.var("x"); + RooRealVar &x2 = *ws2.var("x"); + + RooAbsReal &arg1 = *ws1.function(argName); + RooAbsReal &arg2 = *ws2.function(argName); + + RooArgSet nset1{x1}; + RooArgSet nset2{x2}; + + bool allGood = true; + for (int i = 0; i < x1.numBins(); ++i) { + x1.setBin(i); + x2.setBin(i); + const double val1 = arg1.getVal(nset1); + const double val2 = arg2.getVal(nset2); + allGood &= (exact ? (val1 == val2) : std::abs(val1 - val2) < 1e-10); + } + + return allGood ? 0 : 1; +} + +int validate(std::vector const &expressions, bool exact = true) +{ + RooWorkspace ws; + for (std::size_t iExpr = 0; iExpr < expressions.size() - 1; ++iExpr) { + ws.factory(expressions[iExpr]); + } + const std::string argName = ws.factory(expressions.back())->GetName(); + return validate(ws, argName, exact); +} + +int validate(RooAbsArg const &arg, bool exact = true) +{ + RooWorkspace ws; + ws.import(arg, RooFit::Silence()); + return validate(ws, arg.GetName(), exact); +} -#include "RooGlobalFunc.h" +} // namespace + +// Test that the IO of attributes and string attributes works. +TEST(RooFitHS3, AttributesIO) +{ -// includes for RooArgusBG -#include "RooArgusBG.h" -#include "RooGaussian.h" -#include "RooAddPdf.h" + std::string jsonString; -// includes for SimultaneousGaussians -#include "RooRealVar.h" -#include "RooSimultaneous.h" -#include "RooProdPdf.h" -#include "RooCategory.h" + // Export to JSON + { + RooWorkspace ws{"workspace"}; + ws.factory("Gaussian::pdf(x[0, 10], mean[5], sigma[1.0, 0.1, 10])"); + RooAbsPdf &pdf = *ws.pdf("pdf"); -using namespace RooFit; + // set attributes + pdf.setAttribute("attr0"); + pdf.setStringAttribute("key0", "val0"); + + jsonString = RooJSONFactoryWSTool{ws}.exportJSONtoString(); + } + + // Import JSON + RooWorkspace ws{"workspace"}; + RooJSONFactoryWSTool{ws}.importJSONfromString(jsonString); + RooAbsPdf &pdf = *ws.pdf("pdf"); + + EXPECT_TRUE(pdf.getAttribute("attr0")) << "IO of attribute didn't work!"; + EXPECT_FALSE(pdf.getAttribute("attr1")) << "unexpected attribute found!"; + + EXPECT_STREQ(pdf.getStringAttribute("key0"), "val0") << "IO of string attribute didn't work!"; + EXPECT_STREQ(pdf.getStringAttribute("key1"), nullptr) << "unexpected string attribute found!"; +} + +TEST(RooFitHS3, RooAddPdf) +{ + int status = validate({"Gaussian::sig(x[5.20, 5.30], sigmean[5.28, 5.20, 5.30], sigwidth[0.0027, 0.001, 1.])", + "ArgusBG::bkg(x, 5.291, argpar[-20.0, -100., -1.])", + "SUM::model(nsig[200, 0., 10000] * sig, nbkg[800, 0., 10000] * bkg)"}); + EXPECT_EQ(status, 0); + + // With the next part of the test, we want to cover the closure of + // coefficient normalization reference observables. + RooWorkspace ws; + ws.factory("Gaussian::sig_1(x[5.20, 5.30], sigmean[5.28, 5.20, 5.30], sigwidth[0.0027, 0.001, 1.])"); + ws.factory("Uniform::sig_2(x_2[0, 10])"); + + ws.factory("ArgusBG::bkg_1(x, 5.291, argpar[-20.0, -100., -1.])"); + // Some pdf in x_2 needs to be non linear, otherwise the reference + // normalization set makes no difference. + ws.factory("Polynomial::bkg_2(x_2, {a2[1.0, 0.0, 2.0]}, 2)"); + + ws.factory("PROD::sig(sig_1, sig_2)"); + ws.factory("PROD::bkg(bkg_1, bkg_2)"); + + ws.factory("nsig[200, 0., 10000]"); + ws.factory("nbkg[800, 0., 10000]"); + RooAddPdf addPdf{"model_cond", "model_cond", {*ws.pdf("sig"), *ws.pdf("bkg")}, {*ws.var("nsig"), *ws.var("nbkg")}}; + addPdf.fixCoefNormalization({*ws.var("x"), *ws.var("x_2")}); + status = validate(addPdf); + EXPECT_EQ(status, 0); +} TEST(RooFitHS3, RooArgusBG) { - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + int status = validate({"ArgusBG::argusBG(x[0, 20], x0[10], c[-1], p[0.5])"}); + EXPECT_EQ(status, 0); +} - // --- Observable --- - RooRealVar mes("mes", "m_{ES} (GeV)", 5.20, 5.30); +TEST(RooFitHS3, RooBifurGauss) +{ + int status = validate({"BifurGauss::bifurGauss(x[0, 10], mean[5], sigmaL[1.0, 0.1, 10], sigmaR[2.0, 0.1, 10])"}); + EXPECT_EQ(status, 0); +} - // --- Parameters --- - RooRealVar sigmean("sigmean", "B^{#pm} mass", 5.28, 5.20, 5.30); - RooRealVar sigwidth("sigwidth", "B^{#pm} width", 0.0027, 0.001, 1.); +TEST(RooFitHS3, RooCBShape) +{ + int status = validate({"CBShape::cbShape(x[-10, 10], x0[0], sigma[2.0], alpha[1.4], n[1.2])"}); + EXPECT_EQ(status, 0); +} - // --- Build Gaussian PDF --- - RooGaussian signalModel("signal", "signal PDF", mes, sigmean, sigwidth); +/// Test that the IO of pdfs that contain RooConstVars works. +TEST(RooFitHS3, RooConstVar) +{ + RooRealVar x{"x", "x", 100, 0, 1000}; + RooConstVar mean{"mean", "mean", 100}; + int status = validate(RooPoisson{"pdf_with_const_var", "pdf_with_const_var", x, mean}); + EXPECT_EQ(status, 0); +} - // --- Build Argus background PDF --- - RooRealVar argpar("argpar", "argus shape parameter", -20.0, -100., -1.); - RooArgusBG background("background", "Argus PDF", mes, RooConst(5.291), argpar); +TEST(RooFitHS3, RooExponential) +{ + int status = validate({"Exponential::exponential_1(x[0, 10], c[-0.1])"}); + EXPECT_EQ(status, 0); + RooWorkspace ws; + ws.factory("x[0, 10]"); + ws.factory("c[-0.1]"); + RooExponential exponential2{"exponential_2", "exponential_2", *ws.var("x"), *ws.var("c"), true}; + status = validate(exponential2); + EXPECT_EQ(status, 0); +} - // --- Construct signal+background PDF --- - RooRealVar nsig("nsig", "#signal events", 200, 0., 10000); - RooRealVar nbkg("nbkg", "#background events", 800, 0., 10000); - RooAddPdf model("model", "g+a", RooArgList(signalModel, background), RooArgList(nsig, nbkg)); +TEST(RooFitHS3, RooExpPoly) +{ + // To silence the numeric integration + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); - auto etcDir = std::string(TROOT::GetEtcDir()); - RooFit::JSONIO::loadExportKeys(etcDir + "/RooFitHS3_wsexportkeys.json"); - RooFit::JSONIO::loadFactoryExpressions(etcDir + "/RooFitHS3_wsfactoryexpressions.json"); + // Test different values for "lowestOrder" + int status = 0; + status = validate({"ExpPoly::exppoly0(x[0, 10], {a_0[3.0], a_1[-0.3, -10, 10], a_2[0.01, -10, 10]}, 0)"}); + EXPECT_EQ(status, 0); + status = validate({"ExpPoly::exppoly1(x[0, 10], {a_1[-0.1, -10, 10], a_2[0.003, -10, 10]}, 1)"}); + EXPECT_EQ(status, 0); + status = validate({"ExpPoly::exppoly1(x[0, 10], {a_2[0.003, -10, 10]}, 2)"}); + EXPECT_EQ(status, 0); +} - RooWorkspace work; - work.import(model); - RooJSONFactoryWSTool tool(work); - tool.exportJSON("argus.json"); -}; +TEST(RooFitHS3, RooGamma) +{ + int status = validate({"Gamma::gamma_dist(x[5.0, 10.0], gamma[1.0, 0.1, 10.0], beta[1.0, 0.1, 10.0], mu[5.0])"}); + EXPECT_EQ(status, 0); +} -TEST(RooFitHS3, SimultaneousGaussians) +TEST(RooFitHS3, RooGaussian) +{ + int status = validate({"Gaussian::gaussian(x[0, 10], mean[5], sigma[1.0, 0.1, 10])"}); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooGenericPdf) +{ + // To silence the numeric integration + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + // At this point, only basic arithmetic operations with +, -, * and / are + // defined in the HS3 standard. + int status = validate({"x[0, 10]", "c[5]", "a[1.0, 0.1, 10]", "EXPR::genericPdf1('a * x + c', {x, a, c})"}); + EXPECT_EQ(status, 0); + + // Test that it also works with index notation builtin to TFormula + status = validate({"x[0, 10]", "c[5]", "a[1.0, 0.1, 10]", "EXPR::genericPdf2('x[1] * x[0] + x[2]', {x, a, c})"}); + EXPECT_EQ(status, 0); + + // Test for ordinal notation + status = validate({"x[0, 10]", "c[5]", "a[1.0, 0.1, 10]", "EXPR::genericPdf3('@1 * @0 + @2', {x, a, c})"}); + EXPECT_EQ(status, 0); + + // Test for variable names with numbers and extra whitespaces in it + status = validate({"m_001_mu[1.0, 0.1, 10]", "x[0, 5]", "m_003_mu[5]", + "EXPR::genericPdf4('@0 * 2 * @1 + @2', {m_001_mu, x, m_003_mu})"}); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooHistPdf) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + RooRealVar x{"x", "x", 0.0, 0.02}; + x.setBins(2); + + RooDataHist dataHist{"myDataHist", "myDataHist", x}; + dataHist.set(0, 23, -1); + dataHist.set(1, 17, -1); + + int status = validate(RooHistPdf{"histPdf", "histPdf", x, dataHist}); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooLandau) +{ + int status = validate({"Landau::landau(x[0, 10], mean[5], sigma[1.0, 0.1, 10])"}); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooLognormal) +{ + RooWorkspace ws; + int status = validate({"Lognormal::lognormal_1(x[1.0, 1.1, 10], mu_2[2.0, 1.1, 10], k_1[2.0, 1.1, 5.0])"}); + EXPECT_EQ(status, 0); + ws.factory("x[1.0, 1.1, 10]"); + ws.factory("mu_2[0.7, 0.1, 2.3]"); + ws.factory("k_2[0.7, 0.1, 1.6]"); + RooLognormal lognormal2{"lognormal_2", "lognormal_2", *ws.var("x"), *ws.var("mu_2"), *ws.var("k_2"), true}; + status = validate(lognormal2); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooMultiVarGaussian) +{ + // To silence the numeric differentiation + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + using RooFit::RooConst; + + RooRealVar x{"x", "x", 0, 10}; + RooRealVar y{"y", "y", 0, 10}; + RooRealVar mean{"mean", "mean", 3}; + TMatrixDSym cov{2}; + cov(0, 0) = 1.0; + cov(0, 1) = 0.2; + cov(1, 0) = 0.2; + cov(1, 1) = 1.0; + RooMultiVarGaussian multiVarGauss{"multi_var_gauss", "", {x, y}, {mean, RooConst(5.0)}, cov}; + int status = validate(multiVarGauss); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooPoisson) +{ + int status = 0; + + for (auto noRounding : {false, true}) { + + std::string name = "poisson"; + name += noRounding ? "_true" : "_false"; + + RooRealVar x{"x", "x", 0, 10}; + RooRealVar mean{"mean", "mean", 5}; + RooPoisson poisson{name.c_str(), name.c_str(), x, mean, noRounding}; + status = validate(poisson); + EXPECT_EQ(status, 0); + } +} + +TEST(RooFitHS3, RooPolynomial) { - using namespace RooFit; + // Test different values for "lowestOrder" + int status = 0; + status = validate({"Polynomial::poly0(x[0, 10], {a_0[3.0], a_1[-0.3, -10, 10], a_2[0.01, -10, 10]}, 0)"}); + EXPECT_EQ(status, 0); + status = validate({"Polynomial::poly1(x[0, 10], {a_1[-0.1, -10, 10], a_2[0.003, -10, 10]}, 1)"}); + EXPECT_EQ(status, 0); + status = validate({"Polynomial::poly1(x[0, 10], {a_2[0.003, -10, 10]}, 2)"}); + EXPECT_EQ(status, 0); +} - // Import keys and factory expressions files for the RooJSONFactoryWSTool. - auto etcDir = std::string(TROOT::GetEtcDir()); - RooFit::JSONIO::loadExportKeys(etcDir + "/RooFitHS3_wsexportkeys.json"); - RooFit::JSONIO::loadFactoryExpressions(etcDir + "/RooFitHS3_wsfactoryexpressions.json"); +TEST(RooFitHS3, RooPower) +{ + int status = 0; + status = validate({"Power::power(x[0, 10], {a_0[3.0], a_1[-0.3, -10, 10]}, {1.0, 2.0})"}); + EXPECT_EQ(status, 0); +} + +TEST(RooFitHS3, RooUniform) +{ + int status = 0; + status = validate({"Uniform::uniform({x[0.0, 10.0], y[0.0, 5.0]})"}); + EXPECT_EQ(status, 0); +} +TEST(RooFitHS3, SimultaneousGaussians) +{ // Create a test model: RooSimultaneous with Gaussian in one component, and // product of two Gaussians in the other. RooRealVar x("x", "x", -8, 8); RooRealVar mean("mean", "mean", 0, -8, 8); RooRealVar sigma("sigma", "sigma", 0.3, 0.1, 10); RooGaussian g1("g1", "g1", x, mean, sigma); - RooGaussian g2("g2", "g2", x, mean, RooConst(0.3)); + RooGaussian g2("g2", "g2", x, mean, 0.3); RooProdPdf model("model", "model", RooArgList{g1, g2}); RooGaussian model_ctl("model_ctl", "model_ctl", x, mean, sigma); RooCategory sample("sample", "sample", {{"physics", 0}, {"control", 1}}); @@ -81,25 +348,6 @@ TEST(RooFitHS3, SimultaneousGaussians) simPdf.addPdf(model, "physics"); simPdf.addPdf(model_ctl, "control"); - // this is a handy way of triggering the creation of a ModelConfig upon re-import - simPdf.setAttribute("toplevel"); - - // Export to JSON - { - RooWorkspace ws{"workspace"}; - ws.import(simPdf); - RooJSONFactoryWSTool tool{ws}; - tool.exportJSON("simPdf.json"); - // Output can be pretty-printed with `python -m json.tool simPdf.json` - } - - // Import JSON - { - RooWorkspace ws{"workspace"}; - RooJSONFactoryWSTool tool{ws}; - tool.importJSON("simPdf.json"); - - ASSERT_TRUE(ws.pdf("g1")); - ASSERT_TRUE(ws.pdf("g2")); - } + int status = validate(simPdf); + EXPECT_EQ(status, 0); } diff --git a/roofit/hs3/test/test_hs3_histfactory_json.py b/roofit/hs3/test/test_hs3_histfactory_json.py deleted file mode 100644 index 4e55f261128d8..0000000000000 --- a/roofit/hs3/test/test_hs3_histfactory_json.py +++ /dev/null @@ -1,169 +0,0 @@ -import unittest -import ROOT - -msg = ROOT.RooMsgService.instance() -msg.setGlobalKillBelow(ROOT.RooFit.WARNING) - - -class TestHS3HistFactoryJSON(unittest.TestCase): - def measurement(self, inputFileName="test_hs3_histfactory_json_input.root"): - ROOT.gROOT.SetBatch(True) - meas = ROOT.RooStats.HistFactory.Measurement("meas", "meas") - meas.SetOutputFilePrefix("./results/example_") - meas.SetPOI("mu") - meas.AddConstantParam("Lumi") - meas.SetLumi(1.0) - meas.SetLumiRelErr(0.10) - meas.SetExportOnly(False) - meas.SetBinHigh(2) - # meas.AddConstantParam("syst1") - chan = ROOT.RooStats.HistFactory.Channel("channel1") - chan.SetData("data", inputFileName) - chan.SetStatErrorConfig(0.01, "Poisson") - sig = ROOT.RooStats.HistFactory.Sample("signal", "signal", inputFileName) - sig.AddOverallSys("syst1", 0.95, 1.05) - sig.AddNormFactor("mu", 1, -3, 5) - chan.AddSample(sig) - background1 = ROOT.RooStats.HistFactory.Sample("background1", "background1", inputFileName) - background1.ActivateStatError("background1_statUncert", inputFileName) - background1.AddOverallSys("syst2", 0.95, 1.05) - chan.AddSample(background1) - background2 = ROOT.RooStats.HistFactory.Sample("background2", "background2", inputFileName) - background2.ActivateStatError() - background2.AddOverallSys("syst3", 0.95, 1.05) - chan.AddSample(background2) - meas.AddChannel(chan) - meas.CollectHistograms() - return meas - - def toJSON(self, meas, fname): - tool = ROOT.RooStats.HistFactory.JSONTool(meas) - tool.PrintJSON(fname) - - def toWS(self, meas): - w = ROOT.RooStats.HistFactory.MakeModelAndMeasurementFast(meas) - return w - - def test_create(self): - meas = self.measurement() - self.toJSON(meas, "hf.json") - - def importToWS(self, infile, wsname): - ws = ROOT.RooWorkspace(wsname) - tool = ROOT.RooJSONFactoryWSTool(ws) - tool.importJSON(infile) - return ws - - def test_closure(self): - meas = self.measurement() - self.toJSON(meas, "hf.json") - ws = self.toWS(meas) - ws_from_js = self.importToWS("hf.json", "ws1") - - noset = ROOT.RooArgSet() - - mc = ws["ModelConfig"] - assert mc - - mc_from_js = ws_from_js["ModelConfig"] - assert mc_from_js - - pdf = mc.GetPdf() - assert pdf - - pdf_from_js = ws_from_js[meas.GetName()] - assert pdf_from_js - - data = ws["obsData"] - assert data - - data_from_js = ws_from_js["obsData"] - assert data_from_js - - pdf.fitTo(data, Strategy=1, Minos=mc.GetParametersOfInterest(), GlobalObservables=mc.GetGlobalObservables()) - - pdf_from_js.fitTo( - data_from_js, - Strategy=1, - Minos=mc_from_js.GetParametersOfInterest(), - GlobalObservables=mc_from_js.GetGlobalObservables(), - ) - - from math import isclose - - assert isclose( - ws.var("mu").getVal(), - ws_from_js.var("mu").getVal(), - rel_tol=1e-4, - abs_tol=1e-4, - ) - assert isclose( - ws.var("mu").getError(), - ws_from_js.var("mu").getError(), - rel_tol=1e-4, - abs_tol=1e-4, - ) - - def test_closure_loop(self): - meas = self.measurement() - ws = self.toWS(meas) - - tool = ROOT.RooJSONFactoryWSTool(ws) - js = tool.exportJSONtoString() - - newws = ROOT.RooWorkspace("new") - newtool = ROOT.RooJSONFactoryWSTool(newws) - newtool.importJSONfromString(js) - - mc = ws["ModelConfig"] - assert mc - - newmc = newws["ModelConfig"] - assert newmc - - pdf = mc.GetPdf() - assert pdf - - newpdf = newmc.GetPdf() - assert newpdf - - data = ws["obsData"] - assert data - - newdata = newws["obsData"] - assert newdata - - pdf.fitTo( - data, - Strategy=1, - Minos=mc.GetParametersOfInterest(), - GlobalObservables=mc.GetGlobalObservables(), - PrintLevel=-1, - ) - - newpdf.fitTo( - newdata, - Strategy=1, - Minos=newmc.GetParametersOfInterest(), - GlobalObservables=newmc.GetGlobalObservables(), - PrintLevel=-1, - ) - - from math import isclose - - assert isclose( - ws.var("mu").getVal(), - newws.var("mu").getVal(), - rel_tol=1e-4, - abs_tol=1e-4, - ) - assert isclose( - ws.var("mu").getError(), - newws.var("mu").getError(), - rel_tol=1e-4, - abs_tol=1e-4, - ) - - -if __name__ == "__main__": - unittest.main(verbosity=2) diff --git a/roofit/hs3/test/test_hs3_histfactory_json_input.root b/roofit/hs3/test/test_hs3_histfactory_json_input.root deleted file mode 100644 index 0ad0c6c6610e3..0000000000000 Binary files a/roofit/hs3/test/test_hs3_histfactory_json_input.root and /dev/null differ diff --git a/roofit/jsoninterface/CMakeLists.txt b/roofit/jsoninterface/CMakeLists.txt index a224566698265..ae4b3430fe59d 100644 --- a/roofit/jsoninterface/CMakeLists.txt +++ b/roofit/jsoninterface/CMakeLists.txt @@ -9,22 +9,18 @@ # @author Jonas Rembser, CERN ############################################################################ -if(roofit_hs3_ryml) - # If RapidYAML can be found on the system, we will use RapidYAML instead of - # nlohmann-json. Like this we can also convert to yaml. +# If RapidYAML can be found on the system, we will also compile the RapidYAML backend besides the +# nlohmann-json backend. Like this we can also convert to yaml. - message(STATUS "Looking for RapidYAML (used by RooFit)") - find_package(ryml) - if(${RYML_FOUND}) - message(STATUS "RapidYAML found, compiling RooFit JSON Interface with RapidYAML parser") - set(ParserSource src/RYMLParser.cxx) - add_compile_definitions(ROOFIT_WITH_RYML) - else() - set(ParserSource src/JSONParser.cxx) - message(STATUS "RapidYAML not found, compiling RooFit with nlohmann-json parser") - endif() +message(STATUS "Looking for RapidYAML (used by RooFit)") +find_package(ryml) +if(${RYML_FOUND}) + message(STATUS "RapidYAML found, compiling also RooFit JSON Interface with RapidYAML parser") + set(ParserSources src/JSONParser.cxx src/RYMLParser.cxx) + add_compile_definitions(ROOFIT_WITH_RYML) else() - set(ParserSource src/JSONParser.cxx) + set(ParserSources src/JSONParser.cxx) + message(STATUS "RapidYAML not found, only compiling RooFit with nlohmann-json parser") endif() ROOT_STANDARD_LIBRARY_PACKAGE(RooFitJSONInterface @@ -32,21 +28,21 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitJSONInterface RooFit/Detail/JSONInterface.h SOURCES src/JSONInterface.cxx - ${ParserSource} + ${ParserSources} DICTIONARY_OPTIONS "-writeEmptyRootPCM" LIBRARIES Core ) -if((roofit_hs3_ryml) AND (${RYML_FOUND})) +if(${RYML_FOUND}) target_include_directories(RooFitJSONInterface PRIVATE ${RYML_INCLUDE_DIRS}) target_link_libraries(RooFitJSONInterface PRIVATE -lc4core -lryml) target_link_directories(RooFitJSONInterface PRIVATE ${RYML_LIB_DIR}) +endif() + +if(builtin_nlohmannjson) + target_include_directories(RooFitJSONInterface PRIVATE ${CMAKE_SOURCE_DIR}/builtins) else() - if(builtin_nlohmannjson) - target_include_directories(RooFitJSONInterface PRIVATE ${CMAKE_SOURCE_DIR}/builtins) - else() - target_link_libraries(RooFitJSONInterface PUBLIC nlohmann_json::nlohmann_json) - endif() + target_link_libraries(RooFitJSONInterface PUBLIC nlohmann_json::nlohmann_json) endif() diff --git a/roofit/jsoninterface/inc/RooFit/Detail/JSONInterface.h b/roofit/jsoninterface/inc/RooFit/Detail/JSONInterface.h index e37af3d3c88e2..3ea3186f4d8c9 100644 --- a/roofit/jsoninterface/inc/RooFit/Detail/JSONInterface.h +++ b/roofit/jsoninterface/inc/RooFit/Detail/JSONInterface.h @@ -57,8 +57,14 @@ class JSONNode { Nd &operator*() const { return it->current(); } Nd &operator->() const { return it->current(); } - bool operator!=(const child_iterator_t &that) const { return !this->it->equal(*that.it); } - bool operator==(const child_iterator_t &that) const { return this->it->equal(*that.it); } + friend bool operator!=(child_iterator_t const &lhs, child_iterator_t const &rhs) + { + return !lhs.it->equal(*rhs.it); + } + friend bool operator==(child_iterator_t const &lhs, child_iterator_t const &rhs) + { + return lhs.it->equal(*rhs.it); + } }; using child_iterator = child_iterator_t; @@ -81,32 +87,24 @@ class JSONNode { public: virtual JSONNode &operator<<(std::string const &s) = 0; + inline JSONNode &operator<<(const char *s) { return *this << std::string(s); } virtual JSONNode &operator<<(int i) = 0; virtual JSONNode &operator<<(double d) = 0; - template - JSONNode &operator<<(const std::vector &v) - { - this->set_seq(); - for (const auto &e : v) { - this->append_child() << e; - }; - return *this; - } + virtual JSONNode &operator<<(bool b) = 0; virtual const JSONNode &operator>>(std::string &v) const = 0; virtual JSONNode &operator[](std::string const &k) = 0; - virtual JSONNode &operator[](size_t pos) = 0; virtual const JSONNode &operator[](std::string const &k) const = 0; - virtual const JSONNode &operator[](size_t pos) const = 0; virtual bool is_container() const = 0; virtual bool is_map() const = 0; virtual bool is_seq() const = 0; - virtual void set_map() = 0; - virtual void set_seq() = 0; + virtual JSONNode &set_map() = 0; + virtual JSONNode &set_seq() = 0; + virtual void clear() = 0; virtual std::string key() const = 0; virtual std::string val() const = 0; virtual int val_int() const { return atoi(this->val().c_str()); } - virtual float val_float() const { return atof(this->val().c_str()); } + virtual double val_double() const { return std::stod(this->val()); } virtual bool val_bool() const { return atoi(this->val().c_str()); } template T val_t() const; @@ -123,6 +121,65 @@ class JSONNode { virtual const_children_view children() const; virtual JSONNode &child(size_t pos) = 0; virtual const JSONNode &child(size_t pos) const = 0; + + template + void fill_seq(Collection const &coll) + { + set_seq(); + for (auto const &item : coll) { + append_child() << item; + } + } + + template + void fill_seq(Collection const &coll, TransformationFunc func) + { + set_seq(); + for (auto const &item : coll) { + append_child() << func(item); + } + } + + template + void fill_mat(Matrix const &mat) + { + set_seq(); + for (int i = 0; i < mat.GetNrows(); ++i) { + auto &row = append_child(); + row.set_seq(); + for (int j = 0; j < mat.GetNcols(); ++j) { + row.append_child() << mat(i, j); + } + } + } + + JSONNode const *find(std::string const &key) const + { + auto &n = *this; + return n.has_child(key) ? &n[key] : nullptr; + } + + template + JSONNode const *find(std::string const &key, Keys_t const &...keys) const + { + auto &n = *this; + return n.has_child(key) ? n[key].find(keys...) : nullptr; + } + + JSONNode &get(std::string const &key) + { + auto &n = *this; + n.set_map(); + return n[key]; + } + + template + JSONNode &get(std::string const &key, Keys_t const &...keys) + { + auto &next = get(key); + next.set_map(); + return next.get(keys...); + } }; class JSONTree { @@ -133,21 +190,74 @@ class JSONTree { static std::unique_ptr create(); static std::unique_ptr create(std::istream &is); + static std::unique_ptr create(std::string const &str); + + static std::string getBackend(); + static void setBackend(std::string const &name); + + static bool hasBackend(std::string const &name); + +private: + // Internally, we store the backend type with an enum to be more memory efficient. + enum class Backend { NlohmannJson, Ryml }; + + static Backend &getBackendEnum(); + + template + static std::unique_ptr createImpl(Args &&...args); }; std::ostream &operator<<(std::ostream &os, RooFit::Detail::JSONNode const &s); + +template +std::vector &operator<<(std::vector &v, RooFit::Detail::JSONNode::children_view const &cv) +{ + for (const auto &e : cv) { + v.push_back(e.val_t()); + } + return v; +} + +template +std::vector &operator<<(std::vector &v, RooFit::Detail::JSONNode::const_children_view const &cv) +{ + for (const auto &e : cv) { + v.push_back(e.val_t()); + } + return v; +} + template std::vector &operator<<(std::vector &v, RooFit::Detail::JSONNode const &n) { if (!n.is_seq()) { throw std::runtime_error("node " + n.key() + " is not of sequence type!"); } - for (const auto &e : n.children()) { - v.push_back(e.val_t()); - } + v << n.children(); return v; } +template <> +inline int JSONNode::val_t() const +{ + return val_int(); +} +template <> +inline double JSONNode::val_t() const +{ + return val_double(); +} +template <> +inline bool JSONNode::val_t() const +{ + return val_bool(); +} +template <> +inline std::string JSONNode::val_t() const +{ + return val(); +} + } // namespace Detail } // namespace RooFit diff --git a/roofit/jsoninterface/src/JSONInterface.cxx b/roofit/jsoninterface/src/JSONInterface.cxx index e2af273d2f87d..bbef71984785d 100644 --- a/roofit/jsoninterface/src/JSONInterface.cxx +++ b/roofit/jsoninterface/src/JSONInterface.cxx @@ -12,20 +12,19 @@ #include +#include "JSONParser.h" #ifdef ROOFIT_WITH_RYML #include "RYMLParser.h" -using Tree_t = TRYMLTree; -#else -#include "JSONParser.h" -using Tree_t = TJSONTree; #endif +#include + namespace { -template -class ChildItImpl final : public RooFit::Detail::JSONNode::child_iterator_t::Impl { +template +class ChildItImpl final : public RooFit::Detail::JSONNode::child_iterator_t::Impl { public: - using child_iterator = RooFit::Detail::JSONNode::child_iterator_t; - ChildItImpl(Nd &n, size_t p) : node(n), pos(p) {} + using child_iterator = RooFit::Detail::JSONNode::child_iterator_t; + ChildItImpl(Node_t &n, size_t p) : node(n), pos(p) {} ChildItImpl(const ChildItImpl &other) : node(other.node), pos(other.pos) {} std::unique_ptr clone() const override { @@ -33,15 +32,15 @@ class ChildItImpl final : public RooFit::Detail::JSONNode::child_iterator_t: } void forward() override { ++pos; } void backward() override { --pos; } - Nd ¤t() override { return node.child(pos); } + Node_t ¤t() override { return node.child(pos); } bool equal(const typename child_iterator::Impl &other) const override { - auto it = dynamic_cast *>(&other); + auto it = dynamic_cast *>(&other); return it && &(it->node) == &(this->node) && (it->pos) == this->pos; } private: - Nd &node; + Node_t &node; size_t pos; }; } // namespace @@ -69,40 +68,75 @@ std::ostream &operator<<(std::ostream &os, JSONNode const &s) return os; } -template <> -int JSONNode::val_t() const +template +std::unique_ptr JSONTree::createImpl(Args &&...args) { - return val_int(); + if (getBackendEnum() == Backend::Ryml) { +#ifdef ROOFIT_WITH_RYML + return std::make_unique(std::forward(args)...); +#else + throw std::runtime_error( + "Requesting JSON tree with rapidyaml backend, but rapidyaml could not be found by ROOT when it was compiled."); +#endif + } + return std::make_unique(std::forward(args)...); } -template <> -float JSONNode::val_t() const + +std::unique_ptr JSONTree::create() { - return val_float(); + return createImpl(); } -template <> -double JSONNode::val_t() const + +std::unique_ptr JSONTree::create(std::istream &is) { - return val_float(); + return createImpl(is); } -template <> -bool JSONNode::val_t() const + +std::unique_ptr JSONTree::create(std::string const &str) { - return val_bool(); + std::stringstream ss{str}; + return JSONTree::create(ss); } -template <> -std::string JSONNode::val_t() const + +/// Check if ROOT was compiled with support for a certain JSON backend library. +/// \param[in] name Name of the backend. +bool JSONTree::hasBackend(std::string const &name) { - return val(); + if (name == "rapidyaml") { +#ifdef ROOFIT_WITH_RYML + return true; +#else + return false; +#endif + } + if (name == "nlohmann-json") + return true; + return false; } -std::unique_ptr JSONTree::create() +JSONTree::Backend &JSONTree::getBackendEnum() { - return std::make_unique(); + static Backend backend = Backend::NlohmannJson; + return backend; } -std::unique_ptr JSONTree::create(std::istream &is) +/// Returns the name of the library that serves as the backend for the JSON +/// interface, which is either `"nlohmann-json"` or `"rapidyaml"`. +/// \return Backend name as a string. +std::string JSONTree::getBackend() +{ + return getBackendEnum() == Backend::Ryml ? "rapidyaml" : "nlohmann-json"; +} + +/// Set the library that serves as the backend for the JSON interface. Note that the `"rapidyaml"` backend is only +/// supported if rapidyaml was found on the system when ROOT was compiled. \param[in] name Name of the backend, can be +/// either `"nlohmann-json"` or `"rapidyaml"`. +void JSONTree::setBackend(std::string const &name) { - return std::make_unique(is); + if (name == "rapidyaml") + getBackendEnum() = Backend::Ryml; + if (name == "nlohmann-json") + getBackendEnum() = Backend::NlohmannJson; } } // namespace Detail diff --git a/roofit/jsoninterface/src/JSONParser.cxx b/roofit/jsoninterface/src/JSONParser.cxx index 6d44c6a06adc9..fc6e927d0f99f 100644 --- a/roofit/jsoninterface/src/JSONParser.cxx +++ b/roofit/jsoninterface/src/JSONParser.cxx @@ -14,14 +14,7 @@ #include -#include "nlohmann/json.hpp" - -// TJSONTree interface - -TJSONTree::Node &TJSONTree::rootnode() -{ - return root; -} +#include // TJSONTree methods @@ -40,21 +33,11 @@ TJSONTree::Node &TJSONTree::incache(const TJSONTree::Node &n) return _nodecache.back(); } -TJSONTree *TJSONTree::Node::get_tree() -{ - return tree; -} - const TJSONTree::Node::Impl &TJSONTree::Node::get_node() const { return *node; } -const TJSONTree *TJSONTree::Node::get_tree() const -{ - return tree; -} - TJSONTree::Node::Impl &TJSONTree::Node::get_node() { return *node; @@ -152,6 +135,12 @@ TJSONTree::Node &TJSONTree::Node::operator<<(double d) return *this; } +TJSONTree::Node &TJSONTree::Node::operator<<(bool b) +{ + node->get() = b; + return *this; +} + const TJSONTree::Node &TJSONTree::Node::operator>>(std::string &v) const { v = node->get().get(); @@ -163,21 +152,11 @@ TJSONTree::Node &TJSONTree::Node::operator[](std::string const &k) return Impl::mkNode(tree, k, node->get()[k]); } -TJSONTree::Node &TJSONTree::Node::operator[](size_t pos) -{ - return Impl::mkNode(tree, "", node->get()[pos]); -} - const TJSONTree::Node &TJSONTree::Node::operator[](std::string const &k) const { return Impl::mkNode(tree, k, node->get()[k]); } -const TJSONTree::Node &TJSONTree::Node::operator[](size_t pos) const -{ - return Impl::mkNode(tree, "", node->get()[pos]); -} - bool TJSONTree::Node::is_container() const { return node->get().is_array() || node->get().is_object(); @@ -205,7 +184,7 @@ bool isResettingPossible(nlohmann::json const &node) } if (node.type() == nlohmann::json::value_t::string) { - if (node.get() == "") { + if (node.get().empty()) { return true; } } @@ -213,10 +192,10 @@ bool isResettingPossible(nlohmann::json const &node) } } // namespace -void TJSONTree::Node::set_map() +TJSONTree::Node &TJSONTree::Node::set_map() { if (node->get().type() == nlohmann::json::value_t::object) - return; + return *this; if (isResettingPossible(node->get())) { node->get() = nlohmann::json::object(); @@ -224,12 +203,13 @@ void TJSONTree::Node::set_map() throw std::runtime_error("cannot declare " + this->key() + " to be of map-type, already of type " + node->get().type_name()); } + return *this; } -void TJSONTree::Node::set_seq() +TJSONTree::Node &TJSONTree::Node::set_seq() { if (node->get().type() == nlohmann::json::value_t::array) - return; + return *this; if (isResettingPossible(node->get())) { node->get() = nlohmann::json::array(); @@ -237,6 +217,12 @@ void TJSONTree::Node::set_seq() throw std::runtime_error("cannot declare " + this->key() + " to be of seq-type, already of type " + node->get().type_name()); } + return *this; +} + +void TJSONTree::Node::clear() +{ + node->get().clear(); } std::string TJSONTree::Node::key() const @@ -251,7 +237,7 @@ std::string TJSONTree::Node::val() const case nlohmann::json::value_t::boolean: return node->get().get() ? "true" : "false"; case nlohmann::json::value_t::number_integer: return std::to_string(node->get().get()); case nlohmann::json::value_t::number_unsigned: return std::to_string(node->get().get()); - case nlohmann::json::value_t::number_float: return std::to_string(node->get().get()); + case nlohmann::json::value_t::number_float: return std::to_string(node->get().get()); default: throw std::runtime_error(std::string("node " + node->key() + ": implicit string conversion for type " + node->get().type_name() + " not supported!")); @@ -262,9 +248,9 @@ int TJSONTree::Node::val_int() const { return node->get().get(); } -float TJSONTree::Node::val_float() const +double TJSONTree::Node::val_double() const { - return node->get().get(); + return node->get().get(); } bool TJSONTree::Node::val_bool() const { @@ -284,7 +270,7 @@ bool TJSONTree::Node::val_bool() const bool TJSONTree::Node::has_key() const { - return node->key().size() > 0; + return !node->key().empty(); } bool TJSONTree::Node::has_val() const @@ -346,7 +332,9 @@ class TJSONTree::Node::ChildItImpl final : public RooFit::Detail::JSONNode::chil } bool equal(const typename child_iterator::Impl &other) const override { - auto it = dynamic_cast *>(&other); + // We can use static_cast here because we never compare Iterators for + // different JSON node types. + auto it = static_cast *>(&other); return it && it->iter == this->iter; } diff --git a/roofit/jsoninterface/src/JSONParser.h b/roofit/jsoninterface/src/JSONParser.h index 1273598d6816f..d05625df6657e 100644 --- a/roofit/jsoninterface/src/JSONParser.h +++ b/roofit/jsoninterface/src/JSONParser.h @@ -30,8 +30,8 @@ class TJSONTree : public RooFit::Detail::JSONTree { friend TJSONTree; std::unique_ptr node; - const TJSONTree *get_tree() const; - TJSONTree *get_tree(); + const TJSONTree *get_tree() const { return tree; } + TJSONTree *get_tree() { return tree; } const Impl &get_node() const; Impl &get_node(); @@ -46,20 +46,20 @@ class TJSONTree : public RooFit::Detail::JSONTree { Node &operator<<(std::string const &s) override; Node &operator<<(int i) override; Node &operator<<(double d) override; + Node &operator<<(bool b) override; const Node &operator>>(std::string &v) const override; Node &operator[](std::string const &k) override; - Node &operator[](size_t pos) override; const Node &operator[](std::string const &k) const override; - const Node &operator[](size_t pos) const override; bool is_container() const override; bool is_map() const override; bool is_seq() const override; - void set_map() override; - void set_seq() override; + Node &set_map() override; + Node &set_seq() override; + void clear() override; std::string key() const override; std::string val() const override; int val_int() const override; - float val_float() const override; + double val_double() const override; bool val_bool() const override; bool has_key() const override; bool has_val() const override; @@ -80,10 +80,10 @@ class TJSONTree : public RooFit::Detail::JSONTree { public: TJSONTree(); - virtual ~TJSONTree(); + ~TJSONTree() override; TJSONTree(std::istream &is); TJSONTree::Node &incache(const TJSONTree::Node &n); - Node &rootnode() override; + Node &rootnode() override { return root; } }; #endif diff --git a/roofit/jsoninterface/src/RYMLParser.cxx b/roofit/jsoninterface/src/RYMLParser.cxx index 68f9686c597ea..b04d0cc5978db 100644 --- a/roofit/jsoninterface/src/RYMLParser.cxx +++ b/roofit/jsoninterface/src/RYMLParser.cxx @@ -109,16 +109,23 @@ void TRYMLTree::Node::writeYML(std::ostream &os) const os << node->get(); } -void TRYMLTree::Node::set_map() +TRYMLTree::Node &TRYMLTree::Node::set_map() { // assign this node to be a map (JSON object) node->get() |= c4::yml::MAP; + return *this; } -void TRYMLTree::Node::set_seq() +TRYMLTree::Node &TRYMLTree::Node::set_seq() { // assign this node to be a sequence (JSON array) node->get() |= c4::yml::SEQ; + return *this; +} + +void TRYMLTree::Node::clear() +{ + throw std::logic_error("Function not yet implemented"); } TRYMLTree::TRYMLTree(std::istream &is) @@ -171,11 +178,18 @@ TRYMLTree::Node &TRYMLTree::Node::operator<<(int i) TRYMLTree::Node &TRYMLTree::Node::operator<<(double d) { - // write an float to this node + // write a double to this node node->get() << d; return *this; } +TRYMLTree::Node &TRYMLTree::Node::operator<<(bool b) +{ + // write a bool to this node + node->get() << b; + return *this; +} + const TRYMLTree::Node &TRYMLTree::Node::operator>>(std::string &v) const { // read a string from this node @@ -189,24 +203,12 @@ TRYMLTree::Node &TRYMLTree::Node::operator[](std::string const &k) return Impl::mkNode(tree, node->get()[c4::to_csubstr(tree->incache(k))]); } -TRYMLTree::Node &TRYMLTree::Node::operator[](size_t pos) -{ - // get a child node with the given index - return Impl::mkNode(tree, node->get()[pos]); -} - const TRYMLTree::Node &TRYMLTree::Node::operator[](std::string const &k) const { // get a child node with the given key (const version) return Impl::mkNode(tree, node->get()[c4::to_csubstr(tree->incache(k))]); } -const TRYMLTree::Node &TRYMLTree::Node::operator[](size_t pos) const -{ - // get a child node with the given index (const version) - return Impl::mkNode(tree, node->get()[pos]); -} - bool TRYMLTree::Node::is_container() const { // return true if this node can have child nodes diff --git a/roofit/jsoninterface/src/RYMLParser.h b/roofit/jsoninterface/src/RYMLParser.h index 513779c70d0c3..673d196f0ef2e 100644 --- a/roofit/jsoninterface/src/RYMLParser.h +++ b/roofit/jsoninterface/src/RYMLParser.h @@ -35,33 +35,33 @@ class TRYMLTree : public RooFit::Detail::JSONTree { std::unique_ptr node; public: - virtual void writeJSON(std::ostream &os) const override; - virtual void writeYML(std::ostream &) const override; + void writeJSON(std::ostream &os) const override; + void writeYML(std::ostream &) const override; Node(TRYMLTree *t, const Impl &other); Node(const Node &other); - virtual Node &operator<<(std::string const &s) override; - virtual Node &operator<<(int i) override; - virtual Node &operator<<(double d) override; - virtual const Node &operator>>(std::string &v) const override; - virtual Node &operator[](std::string const &k) override; - virtual Node &operator[](size_t pos) override; - virtual const Node &operator[](std::string const &k) const override; - virtual const Node &operator[](size_t pos) const override; - virtual bool is_container() const override; - virtual bool is_map() const override; - virtual bool is_seq() const override; - virtual void set_map() override; - virtual void set_seq() override; - virtual std::string key() const override; - virtual std::string val() const override; - virtual bool has_key() const override; - virtual bool has_val() const override; - virtual bool has_child(std::string const &) const override; - virtual Node &append_child() override; - virtual size_t num_children() const override; - virtual Node &child(size_t pos) override; - virtual const Node &child(size_t pos) const override; + Node &operator<<(std::string const &s) override; + Node &operator<<(int i) override; + Node &operator<<(double d) override; + Node &operator<<(bool b) override; + const Node &operator>>(std::string &v) const override; + Node &operator[](std::string const &k) override; + const Node &operator[](std::string const &k) const override; + bool is_container() const override; + bool is_map() const override; + bool is_seq() const override; + Node &set_map() override; + Node &set_seq() override; + void clear() override; + std::string key() const override; + std::string val() const override; + bool has_key() const override; + bool has_val() const override; + bool has_child(std::string const &) const override; + Node &append_child() override; + size_t num_children() const override; + Node &child(size_t pos) override; + const Node &child(size_t pos) const override; }; protected: @@ -75,9 +75,9 @@ class TRYMLTree : public RooFit::Detail::JSONTree { public: TRYMLTree(); - ~TRYMLTree(); + ~TRYMLTree() override; TRYMLTree(std::istream &is); - Node &rootnode(); + Node &rootnode() override; }; #endif diff --git a/roofit/multiprocess/CMakeLists.txt b/roofit/multiprocess/CMakeLists.txt index e4536a18dd807..d99e60a5e8f33 100644 --- a/roofit/multiprocess/CMakeLists.txt +++ b/roofit/multiprocess/CMakeLists.txt @@ -17,7 +17,7 @@ ROOT_LINKER_LIBRARY(RooFitMultiProcess src/ProcessTimer.cxx src/HeatmapAnalyzer.cxx LIBRARIES - RooFitCommon + Core DEPENDENCIES RooFitZMQ ) diff --git a/roofit/multiprocess/src/HeatmapAnalyzer.cxx b/roofit/multiprocess/src/HeatmapAnalyzer.cxx index 27fcbde0943b2..5221c76a23068 100644 --- a/roofit/multiprocess/src/HeatmapAnalyzer.cxx +++ b/roofit/multiprocess/src/HeatmapAnalyzer.cxx @@ -44,12 +44,12 @@ namespace MultiProcess { /// \param[in] logs_dir Directory where log files are stored in the format /// outputted by RooFit::MultiProcess::ProcessTimer. /// There can be other files in this directory as well. -HeatmapAnalyzer::HeatmapAnalyzer(std::string const& logs_dir) +HeatmapAnalyzer::HeatmapAnalyzer(std::string const &logs_dir) { TSystemDirectory dir(logs_dir.c_str(), logs_dir.c_str()); - TList *duration_files = dir.GetListOfFiles(); + std::unique_ptr durationFiles{dir.GetListOfFiles()}; - for (const auto &&file : *duration_files) { + for (TObject *file : *durationFiles) { if (std::string(file->GetName()).find("p_") == std::string::npos) continue; @@ -81,8 +81,6 @@ HeatmapAnalyzer::HeatmapAnalyzer(std::string const& logs_dir) } sortTaskNames(tasks_names_); - - duration_files->Delete(); } //////////////////////////////////////////////////////////////////////////////// @@ -96,15 +94,16 @@ std::unique_ptr HeatmapAnalyzer::analyze(int analyzed_gradient) int gradient_start_t = gradients_["master:gradient"][analyzed_gradient * 2 - 2]; int gradient_end_t = gradients_["master:gradient"][analyzed_gradient * 2 - 1]; - - std::unique_ptr total_matrix = std::make_unique("heatmap", "", eval_partitions_names_.size(), 0, 1, tasks_names_.size(), 0, 1); + std::unique_ptr total_matrix = + std::make_unique("heatmap", "", eval_partitions_names_.size(), 0, 1, tasks_names_.size(), 0, 1); // loop over all logfiles stored in durations_ for (json &durations_json : durations_) { // partial heatmap is the heatmap that will be filled in for the current durations logfile - std::unique_ptr partial_matrix = std::make_unique("partial_heatmap", "", eval_partitions_names_.size(), 0, 1, tasks_names_.size(), 0, 1); + std::unique_ptr partial_matrix = + std::make_unique("partial_heatmap", "", eval_partitions_names_.size(), 0, 1, tasks_names_.size(), 0, 1); - // remove unneccesary components (those that are out of range) + // remove unnecessary components (those that are out of range) for (auto &&el : durations_json.items()) { auto beg_interval = std::upper_bound(durations_json[el.key()].begin(), durations_json[el.key()].end(), gradient_start_t); @@ -126,7 +125,7 @@ std::unique_ptr HeatmapAnalyzer::analyze(int analyzed_gradient) std::string task_name = findTaskForDuration(durations_json, durations_json[eval_partition_name][idx], durations_json[eval_partition_name][idx + 1]); - if (task_name == "") + if (task_name.empty()) continue; // add found combination of task, partition evaluation, and duration to partial matrix @@ -135,8 +134,8 @@ std::unique_ptr HeatmapAnalyzer::analyze(int analyzed_gradient) find(eval_partitions_names_.begin(), eval_partitions_names_.end(), eval_partition_name) - eval_partitions_names_.begin() + 1; partial_matrix->SetBinContent(eval_partitions_idx, tasks_idx, - durations_json[eval_partition_name][idx + 1].get() - - durations_json[eval_partition_name][idx].get()); + durations_json[eval_partition_name][idx + 1].get() - + durations_json[eval_partition_name][idx].get()); } } // add all partial matrices to form one matrix with entire gradient evaluation information @@ -144,7 +143,7 @@ std::unique_ptr HeatmapAnalyzer::analyze(int analyzed_gradient) } // do not need the legend in case heatmap is plotted - total_matrix->SetStats(0); + total_matrix->SetStats(false); // set the axes labels on the heatmap matrix TAxis *y = total_matrix->GetYaxis(); @@ -210,4 +209,4 @@ void HeatmapAnalyzer::sortTaskNames(std::vector &task_names) } } // namespace MultiProcess -} // namespace RooFit \ No newline at end of file +} // namespace RooFit diff --git a/roofit/multiprocess/src/JobManager.cxx b/roofit/multiprocess/src/JobManager.cxx index d4b7a6d8341dd..ae9b9808b65cc 100644 --- a/roofit/multiprocess/src/JobManager.cxx +++ b/roofit/multiprocess/src/JobManager.cxx @@ -136,11 +136,11 @@ Job *JobManager::get_job_object(std::size_t job_object_id) /// \return Returns 'true' when removed successfully, 'false' otherwise. bool JobManager::remove_job_object(std::size_t job_object_id) { - bool removed_succesfully = job_objects_.erase(job_object_id) == 1; + bool removed_successfully = job_objects_.erase(job_object_id) == 1; if (job_objects_.empty()) { instance_.reset(nullptr); } - return removed_succesfully; + return removed_successfully; } ProcessManager &JobManager::process_manager() const diff --git a/roofit/multiprocess/src/Messenger.cxx b/roofit/multiprocess/src/Messenger.cxx index 179472ac506df..ae430d936ea66 100644 --- a/roofit/multiprocess/src/Messenger.cxx +++ b/roofit/multiprocess/src/Messenger.cxx @@ -14,7 +14,7 @@ #include "RooFit/MultiProcess/Messenger.h" #include "RooFit/MultiProcess/util.h" -#include +#include #include // sigprocmask etc @@ -65,7 +65,8 @@ Messenger::Messenger(const ProcessManager &process_manager) sigemptyset(&ppoll_sigmask); auto makeAddrPrefix = [](pid_t pid) -> std::string { - return "ipc://" + RooFit::tmpPath() + std::to_string(pid) + "_roofitMP"; + std::string tmpPath = gSystem->TempDirectory(); + return "ipc://" + tmpPath + "/roofit_" + std::to_string(pid) + "_roofitMP"; }; // high water mark for master-queue sending, which can be quite a busy channel, especially at the start of a run diff --git a/roofit/multiprocess/test/test_HeatmapAnalyzer.cxx b/roofit/multiprocess/test/test_HeatmapAnalyzer.cxx index 6c9fa1e550469..976ed93a48713 100644 --- a/roofit/multiprocess/test/test_HeatmapAnalyzer.cxx +++ b/roofit/multiprocess/test/test_HeatmapAnalyzer.cxx @@ -26,4 +26,4 @@ TEST(TestMPHeatmapAnalyzer, Analyze) GTEST_ASSERT_EQ(hm->GetBinContent(2, 1), 15); GTEST_ASSERT_EQ(hm->GetBinContent(1, 2), 10); GTEST_ASSERT_EQ(hm->GetBinContent(2, 2), 20); -} \ No newline at end of file +} diff --git a/roofit/multiprocess/test/test_ProcessTimer.cxx b/roofit/multiprocess/test/test_ProcessTimer.cxx index d8c1eca782a73..7befaab9a2b67 100644 --- a/roofit/multiprocess/test/test_ProcessTimer.cxx +++ b/roofit/multiprocess/test/test_ProcessTimer.cxx @@ -20,7 +20,11 @@ using namespace std; -TEST(TestMPProcessTimer, Timings) +/// It's not easy to guarantee that this test always passes. It is not +/// deterministic because we time something across multiple processes and +/// sometimes some processes might be doing something else during the running +/// of these tests. That's why the test is disabled for now. +TEST(TestMPProcessTimer, DISABLED_Timings) { RooFit::MultiProcess::ProcessManager pm(1); @@ -72,4 +76,4 @@ TEST(TestMPProcessTimer, Timings) duration = chrono::duration_cast(*std::next(it) - *it).count(); EXPECT_NEAR(duration, 1000, 100); } -} \ No newline at end of file +} diff --git a/roofit/multiprocess/test/utils.h b/roofit/multiprocess/test/utils.h index ae30eb165ee1c..71b4d7d3b3632 100644 --- a/roofit/multiprocess/test/utils.h +++ b/roofit/multiprocess/test/utils.h @@ -31,7 +31,7 @@ generate_1D_gaussian_pdf_nll(RooWorkspace &w, unsigned long N_events) RooAbsPdf *pdf = w.pdf("g"); RooRealVar *mu = w.var("mu"); - RooDataSet *data = pdf->generate(RooArgSet(*w.var("x")), N_events); + std::unique_ptr data{pdf->generate(RooArgSet(*w.var("x")), N_events)}; mu->setVal(-2.9); std::unique_ptr nll{pdf->createNLL(*data)}; @@ -53,7 +53,7 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev double mean[n], sigma[n]; for (unsigned ix = 0; ix < n; ++ix) { mean[ix] = RooRandom::randomGenerator()->Gaus(0, 2); - sigma[ix] = 0.1 + abs(RooRandom::randomGenerator()->Gaus(0, 2)); + sigma[ix] = 0.1 + std::abs(RooRandom::randomGenerator()->Gaus(0, 2)); } // create gaussians and also the observables and parameters they depend on @@ -77,7 +77,7 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev { std::ostringstream os; os << "x" << ix; - obs_set.add(*w.arg(os.str().c_str())); + obs_set.add(*w.arg(os.str())); } } @@ -94,7 +94,7 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev RooRealVar a(os.str().c_str(), os2.str().c_str(), N_events / 10, 0., 10 * N_events); w.import(a); // gather in count_set - count_set.add(*w.arg(os.str().c_str())); + count_set.add(*w.arg(os.str())); } // ... and for the uniform background components for (unsigned ix = 0; ix < n; ++ix) { @@ -104,14 +104,14 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev RooRealVar a(os.str().c_str(), os2.str().c_str(), N_events / 10, 0., 10 * N_events); w.import(a); // gather in count_set - count_set.add(*w.arg(os.str().c_str())); + count_set.add(*w.arg(os.str())); } RooAddPdf *sum = new RooAddPdf("sum", "gaussians+uniforms", pdf_set, count_set); w.import(*sum); // keep sum around after returning // --- Generate a toyMC sample from composite PDF --- - RooDataSet *data = sum->generate(obs_set, N_events); + std::unique_ptr data{sum->generate(obs_set, N_events)}; std::unique_ptr nll{sum->createNLL(*data)}; @@ -120,13 +120,13 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev { std::ostringstream os; os << "m" << ix; - dynamic_cast(w.arg(os.str().c_str()))->setVal(RooRandom::randomGenerator()->Gaus(0, 2)); + dynamic_cast(w.arg(os.str()))->setVal(RooRandom::randomGenerator()->Gaus(0, 2)); } { std::ostringstream os; os << "s" << ix; - dynamic_cast(w.arg(os.str().c_str())) - ->setVal(0.1 + abs(RooRandom::randomGenerator()->Gaus(0, 2))); + dynamic_cast(w.arg(os.str())) + ->setVal(0.1 + std::abs(RooRandom::randomGenerator()->Gaus(0, 2))); } } @@ -139,12 +139,12 @@ generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_ev { std::ostringstream os; os << "m" << ix; - all_values->add(*w.arg(os.str().c_str())); + all_values->add(*w.arg(os.str())); } { std::ostringstream os; os << "s" << ix; - all_values->add(*w.arg(os.str().c_str())); + all_values->add(*w.arg(os.str())); } } diff --git a/roofit/roofit/CMakeLists.txt b/roofit/roofit/CMakeLists.txt index 01305c1341a76..050963e669500 100644 --- a/roofit/roofit/CMakeLists.txt +++ b/roofit/roofit/CMakeLists.txt @@ -22,6 +22,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFit RooBlindTools.h RooBMixDecay.h RooBreitWigner.h + RooBSpline.h + RooBSplineBases.h RooBukinPdf.h RooCBShape.h RooCrystalBall.h @@ -85,6 +87,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFit src/RooBlindTools.cxx src/RooBMixDecay.cxx src/RooBreitWigner.cxx + src/RooBSpline.cxx + src/RooBSplineBases.cxx src/RooBukinPdf.cxx src/RooCBShape.cxx src/RooCrystalBall.cxx diff --git a/roofit/roofit/doc/index.md b/roofit/roofit/doc/index.md index 1a2b2ba616542..ae2cc8a99aef1 100644 --- a/roofit/roofit/doc/index.md +++ b/roofit/roofit/doc/index.md @@ -1,4 +1,4 @@ -\defgroup Roofit Roofit +\defgroup Roofit RooFit \brief RooFit main classes for building likelihood models, mainly PDFs. \ingroup Roofitmain diff --git a/roofit/roofit/inc/LinkDef1.h b/roofit/roofit/inc/LinkDef1.h index bcba2a2532569..55e773ecc4885 100644 --- a/roofit/roofit/inc/LinkDef1.h +++ b/roofit/roofit/inc/LinkDef1.h @@ -11,6 +11,8 @@ #pragma link C++ class RooBifurGauss+ ; #pragma link C++ class RooBMixDecay+ ; #pragma link C++ class RooBreitWigner+ ; +#pragma link C++ class RooBSpline+ ; +#pragma link C++ class RooBSplineBases+ ; #pragma link C++ class RooBukinPdf+ ; #pragma link C++ class RooCrystalBall+ ; #pragma link C++ class RooCBShape+ ; diff --git a/roofit/roofit/inc/Roo2DKeysPdf.h b/roofit/roofit/inc/Roo2DKeysPdf.h index 6a7154896bf56..109a97cb76ec3 100644 --- a/roofit/roofit/inc/Roo2DKeysPdf.h +++ b/roofit/roofit/inc/Roo2DKeysPdf.h @@ -55,7 +55,7 @@ class Roo2DKeysPdf : public RooAbsPdf // *********** inline void setWidthScaleFactor(double widthScaleFactor); -// choose the kernel bandwith to use. The default is 0 +// choose the kernel bandwidth to use. The default is 0 // 0 = use adaptive kernel estimator (uses local population to vary with of kernels) // 1 = use trivial kernel estimator (uses all data and sigma to estimate uniform kernel bandwidth) Int_t calculateBandWidth(Int_t kernel = -999); diff --git a/roofit/roofit/inc/RooArgusBG.h b/roofit/roofit/inc/RooArgusBG.h index 72802e02cd374..d53f839ce98a4 100644 --- a/roofit/roofit/inc/RooArgusBG.h +++ b/roofit/roofit/inc/RooArgusBG.h @@ -22,10 +22,16 @@ class RooArgusBG : public RooAbsPdf { public: RooArgusBG() {} ; + // One of the original constructors without RooAbsReal::Ref for backwards compatibility. + inline RooArgusBG(const char *name, const char *title, + RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c, RooAbsReal& _p) + : RooArgusBG{name, title, RooAbsReal::Ref{_m}, RooAbsReal::Ref{_m0}, RooAbsReal::Ref{_c}, RooAbsReal::Ref{_p}} {} + // One of the original constructors without RooAbsReal::Ref for backwards compatibility. + inline RooArgusBG(const char *name, const char *title, + RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c) + : RooArgusBG{name, title, RooAbsReal::Ref{_m}, RooAbsReal::Ref{_m0}, RooAbsReal::Ref{_c}} {} RooArgusBG(const char *name, const char *title, - RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c); - RooArgusBG(const char *name, const char *title, - RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c, RooAbsReal& _p); + RooAbsReal::Ref _m, RooAbsReal::Ref _m0, RooAbsReal::Ref _c, RooAbsReal::Ref _p=0.5); RooArgusBG(const RooArgusBG& other,const char* name=nullptr) ; TObject* clone(const char* newname) const override { return new RooArgusBG(*this,newname); } inline ~RooArgusBG() override { } @@ -40,7 +46,7 @@ class RooArgusBG : public RooAbsPdf { RooRealProxy p ; double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } diff --git a/roofit/roofit/inc/RooBCPEffDecay.h b/roofit/roofit/inc/RooBCPEffDecay.h index 20e4f1aa6af54..545228c7f9f70 100644 --- a/roofit/roofit/inc/RooBCPEffDecay.h +++ b/roofit/roofit/inc/RooBCPEffDecay.h @@ -37,7 +37,6 @@ class RooBCPEffDecay : public RooAbsAnaConvPdf { RooBCPEffDecay(const RooBCPEffDecay& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooBCPEffDecay(*this,newname) ; } - ~RooBCPEffDecay() override; double coefficient(Int_t basisIndex) const override ; diff --git a/roofit/roofit/inc/RooBCPGenDecay.h b/roofit/roofit/inc/RooBCPGenDecay.h index 0cff78f227f22..4ad0c152907ef 100644 --- a/roofit/roofit/inc/RooBCPGenDecay.h +++ b/roofit/roofit/inc/RooBCPGenDecay.h @@ -38,7 +38,6 @@ class RooBCPGenDecay : public RooAbsAnaConvPdf { RooBCPGenDecay(const RooBCPGenDecay& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooBCPGenDecay(*this,newname) ; } - ~RooBCPGenDecay() override; double coefficient(Int_t basisIndex) const override ; diff --git a/roofit/roofit/inc/RooBDecay.h b/roofit/roofit/inc/RooBDecay.h index a1972ae1b8909..ef792b0b38066 100644 --- a/roofit/roofit/inc/RooBDecay.h +++ b/roofit/roofit/inc/RooBDecay.h @@ -42,10 +42,9 @@ class RooBDecay : public RooAbsAnaConvPdf { return new RooBDecay(*this,newname); } - ~RooBDecay() override; double coefficient(Int_t basisIndex) const override; - RooArgSet* coefVars(Int_t coefIdx) const override ; + RooFit::OwningPtr coefVars(Int_t coefIdx) const override ; Int_t getCoefAnalyticalIntegral(Int_t coef, RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; double coefAnalyticalIntegral(Int_t coef, Int_t code, const char* rangeName=nullptr) const override ; diff --git a/roofit/roofit/inc/RooBMixDecay.h b/roofit/roofit/inc/RooBMixDecay.h index 92a61ccbb9287..0ad6a3794eb9d 100644 --- a/roofit/roofit/inc/RooBMixDecay.h +++ b/roofit/roofit/inc/RooBMixDecay.h @@ -35,7 +35,6 @@ class RooBMixDecay : public RooAbsAnaConvPdf { RooBMixDecay(const RooBMixDecay& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooBMixDecay(*this,newname) ; } - ~RooBMixDecay() override; double coefficient(Int_t basisIndex) const override ; @@ -46,6 +45,9 @@ class RooBMixDecay : public RooAbsAnaConvPdf { void initGenerator(Int_t code) override ; void generateEvent(Int_t code) override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; + inline bool canComputeBatchWithCuda() const override { return true; } + protected: DecayType _type ; diff --git a/roofit/roofit/inc/RooBSpline.h b/roofit/roofit/inc/RooBSpline.h new file mode 100644 index 0000000000000..606008ef25348 --- /dev/null +++ b/roofit/roofit/inc/RooBSpline.h @@ -0,0 +1,97 @@ +/************************************************************************* + * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#ifndef ROOBSPLINE +#define ROOBSPLINE + +#include "RooAbsPdf.h" +#include "RooRealProxy.h" +#include "RooListProxy.h" +#include "RooSetProxy.h" + +#include "RooBSplineBases.h" + +#include "RooObjCacheManager.h" +#include "RooNumIntConfig.h" + + +#include + + +class RooRealVar; +class RooArgList ; + +class RooBSpline : public RooAbsReal { +public: + + RooBSpline() ; + RooBSpline(const char* name, const char* title, + const RooArgList& controlPoints, RooBSplineBases& bases, const RooArgSet& vars); + //RooBSpline(const char* name, const char* title, int order, vector& tValues, + // const RooArgList& controlPoints, RooAbsReal& t, const RooArgSet& vars, int nrClose=0); + + RooBSpline(const char *name, const char *title); + RooBSpline(const RooBSpline&, const char*); + + virtual TObject* clone(const char* newname) const { return new RooBSpline(*this, newname); } + virtual ~RooBSpline() ; + +/* Double_t getCurvature() const; */ + +// RooBSplinePenalty* getRealPenalty(int k, RooRealVar* obs, RooRealVar* beta, const char* name = "") const; + + + void setWeights(const RooArgList& weights); + + Bool_t setBinIntegrator(RooArgSet& allVars) ; + Int_t getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet,const char* rangeName=0) const ; + Double_t analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName=0) const ; + + const RooArgList& getControlPoints() const {return _controlPoints;} + + RooBSplineBases* getBases() const {return (RooBSplineBases*)&_bases.arg();} + int getOrder() const {return _n;} + + protected: + + RooListProxy _controlPoints; + //RooListProxy _t_ary; + int _m; +/* double* _t_ary; //[_m] */ +/* RooRealProxy _t; */ + int _n; + RooListProxy _weights; + RooRealProxy _bases; + RooSetProxy _vars; + + + // Cache the integrals + class CacheElem : public RooAbsCacheElement { + public: + virtual ~CacheElem(); + // Payload + RooArgList _I ; + virtual RooArgList containedArgs(Action) ; + }; + mutable RooObjCacheManager _cacheMgr ; // The cache manager + + + Double_t evaluate() const; + + ClassDef(RooBSpline,2) // Uniform B-Spline + public: + + int getM() const {return _m;} + int getN() const { return _n;} + const RooArgList& getWeights() const { return _weights; } + const RooArgSet& getVariables() const { return _vars; } + + +}; + +#endif diff --git a/roofit/roofit/inc/RooBSplineBases.h b/roofit/roofit/inc/RooBSplineBases.h new file mode 100644 index 0000000000000..bd5a7bc1f85a1 --- /dev/null +++ b/roofit/roofit/inc/RooBSplineBases.h @@ -0,0 +1,61 @@ +/************************************************************************* + * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#ifndef ROOBSPLINEBASES +#define ROOBSPLINEBASES + +#include "RooAbsPdf.h" +#include "RooRealProxy.h" +#include "RooListProxy.h" + +#include + + +class RooRealVar; +class RooArgList ; + +class RooBSplineBases : public RooAbsReal { +public: + + RooBSplineBases() ; + RooBSplineBases(const char* name, const char* title, int order, std::vector& tValues, + RooAbsReal& t, int nrClose=0); + + RooBSplineBases(const char *name, const char *title); + RooBSplineBases(const RooBSplineBases&, const char*); + + virtual TObject* clone(const char* newname) const { return new RooBSplineBases(*this, newname); } + virtual ~RooBSplineBases() ; + + int getOrder() const {return _n;} + int getM() const {return _m;} + int getNrClose() const {return _nrClose;} + const RooAbsReal& getT() const { return _t.arg(); } + Double_t getBasisVal(int n, int i, bool rebuild=true) const; + const std::vector& getTValues() const {return _tValues;} + const std::vector& getTAry() const {return _t_ary;} + const std::vector>& getBin() const {return _bin;} + + protected: + + void buildTAry() const; + + std::vector _tValues; + int _m; + RooRealProxy _t; + int _n; + int _nrClose; + mutable std::vector _t_ary; + mutable std::vector > _bin; + + Double_t evaluate() const; + + ClassDef(RooBSplineBases,1) // Uniform B-Spline + }; + +#endif diff --git a/roofit/roofit/inc/RooBernstein.h b/roofit/roofit/inc/RooBernstein.h index 694d9bac5c539..088ef7c033a9e 100644 --- a/roofit/roofit/inc/RooBernstein.h +++ b/roofit/roofit/inc/RooBernstein.h @@ -46,7 +46,7 @@ class RooBernstein : public RooAbsPdf { std::string _refRangeName ; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } ClassDefOverride(RooBernstein,2) // Bernstein polynomial PDF diff --git a/roofit/roofit/inc/RooBifurGauss.h b/roofit/roofit/inc/RooBifurGauss.h index 22083bb1cb1a6..951b24628e47f 100644 --- a/roofit/roofit/inc/RooBifurGauss.h +++ b/roofit/roofit/inc/RooBifurGauss.h @@ -43,7 +43,7 @@ class RooBifurGauss : public RooAbsPdf { RooRealProxy sigmaR; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooBreitWigner.h b/roofit/roofit/inc/RooBreitWigner.h index 2dc22544311f2..0293e9e496a1c 100644 --- a/roofit/roofit/inc/RooBreitWigner.h +++ b/roofit/roofit/inc/RooBreitWigner.h @@ -41,7 +41,7 @@ class RooBreitWigner : public RooAbsPdf { RooRealProxy width ; double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } // void initGenerator(); diff --git a/roofit/roofit/inc/RooBukinPdf.h b/roofit/roofit/inc/RooBukinPdf.h index fd8a03b44e624..00c420c362aa1 100644 --- a/roofit/roofit/inc/RooBukinPdf.h +++ b/roofit/roofit/inc/RooBukinPdf.h @@ -48,7 +48,7 @@ class RooBukinPdf : public RooAbsPdf { RooRealProxy rho1; RooRealProxy rho2; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooCBShape.h b/roofit/roofit/inc/RooCBShape.h index 180e506d81487..cef8f33df95da 100644 --- a/roofit/roofit/inc/RooCBShape.h +++ b/roofit/roofit/inc/RooCBShape.h @@ -51,7 +51,7 @@ class RooCBShape : public RooAbsPdf { RooRealProxy n; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } diff --git a/roofit/roofit/inc/RooCFunction2Binding.h b/roofit/roofit/inc/RooCFunction2Binding.h index 8596b13e9122e..f2a3a9fd04e5d 100644 --- a/roofit/roofit/inc/RooCFunction2Binding.h +++ b/roofit/roofit/inc/RooCFunction2Binding.h @@ -164,7 +164,7 @@ template void RooCFunction2Ref::Streamer(TBuffer &R__b) { // Custom streamer for function pointer reference object. When writing, - // the function pointer is substituted by its registerd name. When function + // the function pointer is substituted by its registered name. When function // is unregistered name 'UNKNOWN' is written and a warning is issues. When // reading back, the embedded name is converted back to a function pointer // using the mapping service. When name UNKNOWN is encountered a warning is diff --git a/roofit/roofit/inc/RooCFunction3Binding.h b/roofit/roofit/inc/RooCFunction3Binding.h index 7b89b994bfe39..7bd30674c0e18 100644 --- a/roofit/roofit/inc/RooCFunction3Binding.h +++ b/roofit/roofit/inc/RooCFunction3Binding.h @@ -168,7 +168,7 @@ template void RooCFunction3Ref::Streamer(TBuffer &R__b) { // Custom streamer for function pointer reference object. When writing, - // the function pointer is substituted by its registerd name. When function + // the function pointer is substituted by its registered name. When function // is unregistered name 'UNKNOWN' is written and a warning is issues. When // reading back, the embedded name is converted back to a function pointer // using the mapping service. When name UNKNOWN is encountered a warning is @@ -195,7 +195,7 @@ void RooCFunction3Ref::Streamer(TBuffer &R__b) } else { - // Lookup pointer to C function wih given name + // Lookup pointer to C function with given name _ptr = fmap().lookupPtr(tmpName.Data()) ; if (_ptr==nullptr) { diff --git a/roofit/roofit/inc/RooCFunction4Binding.h b/roofit/roofit/inc/RooCFunction4Binding.h index 43ea29f848dff..a5a368c1123b3 100644 --- a/roofit/roofit/inc/RooCFunction4Binding.h +++ b/roofit/roofit/inc/RooCFunction4Binding.h @@ -161,7 +161,7 @@ template void RooCFunction4Ref::Streamer(TBuffer &R__b) { // Custom streamer for function pointer reference object. When writing, - // the function pointer is substituted by its registerd name. When function + // the function pointer is substituted by its registered name. When function // is unregistered name 'UNKNOWN' is written and a warning is issues. When // reading back, the embedded name is converted back to a function pointer // using the mapping service. When name UNKNOWN is encountered a warning is @@ -188,7 +188,7 @@ void RooCFunction4Ref::Streamer(TBuffer &R__b) } else { - // Lookup pointer to C function wih given name + // Lookup pointer to C function with given name _ptr = fmap().lookupPtr(tmpName.Data()) ; if (_ptr==nullptr) { diff --git a/roofit/roofit/inc/RooChebychev.h b/roofit/roofit/inc/RooChebychev.h index e7a18e1f80683..c9754ac09ca5d 100644 --- a/roofit/roofit/inc/RooChebychev.h +++ b/roofit/roofit/inc/RooChebychev.h @@ -38,14 +38,17 @@ class RooChebychev : public RooAbsPdf { void selectNormalizationRange(const char* rangeName=nullptr, bool force=false) override ; -private: + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(Int_t code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + private: RooRealProxy _x; RooListProxy _coefList ; mutable TNamed* _refRangeName ; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } double evalAnaInt(const double a, const double b) const; diff --git a/roofit/roofit/inc/RooChiSquarePdf.h b/roofit/roofit/inc/RooChiSquarePdf.h index 025cc780b35ef..d062be92e53fe 100644 --- a/roofit/roofit/inc/RooChiSquarePdf.h +++ b/roofit/roofit/inc/RooChiSquarePdf.h @@ -41,7 +41,7 @@ class RooChiSquarePdf : public RooAbsPdf { RooRealProxy _ndof; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } ClassDefOverride(RooChiSquarePdf,1) // Chi Square distribution (eg. the PDF ) diff --git a/roofit/roofit/inc/RooDstD0BG.h b/roofit/roofit/inc/RooDstD0BG.h index 76bae33ba1f33..531bd04db91d8 100644 --- a/roofit/roofit/inc/RooDstD0BG.h +++ b/roofit/roofit/inc/RooDstD0BG.h @@ -45,7 +45,7 @@ class RooDstD0BG : public RooAbsPdf { RooRealProxy C,A,B ; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooExpPoly.h b/roofit/roofit/inc/RooExpPoly.h index d06491ebb688b..0c1cd74964e20 100644 --- a/roofit/roofit/inc/RooExpPoly.h +++ b/roofit/roofit/inc/RooExpPoly.h @@ -18,11 +18,19 @@ class RooExpPoly : public RooAbsPdf { public: RooExpPoly() {} - RooExpPoly(const char *name, const char *title, RooAbsReal &x); RooExpPoly(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, int lowestOrder = 1); - RooExpPoly(const RooExpPoly &other, const char *name = 0); - virtual TObject *clone(const char *newname) const override { return new RooExpPoly(*this, newname); } + RooExpPoly(const RooExpPoly &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooExpPoly(*this, newname); } + + /// Get the x variable. + RooAbsReal const &x() const { return _x.arg(); } + + /// Get the coefficient list. + RooArgList const &coefList() const { return _coefList; } + + /// Return the order for the first coefficient in the list. + int lowestOrder() const { return _lowestOrder; } double getLogVal(const RooArgSet *nset) const override; @@ -38,6 +46,10 @@ class RooExpPoly : public RooAbsPdf { RooListProxy _coefList; int _lowestOrder; + // CUDA support + void computeBatch(double *output, size_t size, RooFit::Detail::DataMap const &) const override; + inline bool canComputeBatchWithCuda() const override { return true; } + /// Evaluation double evaluate() const override; double evaluateLog() const; diff --git a/roofit/roofit/inc/RooExponential.h b/roofit/roofit/inc/RooExponential.h index c9e646d02315b..085b186d80e7f 100644 --- a/roofit/roofit/inc/RooExponential.h +++ b/roofit/roofit/inc/RooExponential.h @@ -16,34 +16,43 @@ #ifndef ROO_EXPONENTIAL #define ROO_EXPONENTIAL -#include "RooAbsPdf.h" -#include "RooRealProxy.h" - -class RooRealVar; -class RooAbsReal; +#include +#include class RooExponential : public RooAbsPdf { public: - RooExponential() {} ; - RooExponential(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _c); - RooExponential(const RooExponential& other, const char* name=nullptr); - TObject* clone(const char* newname) const override { return new RooExponential(*this,newname); } - inline ~RooExponential() override { } + RooExponential() {} + RooExponential(const char *name, const char *title, RooAbsReal &variable, RooAbsReal &coefficient, + bool negateCoefficient = false); + RooExponential(const RooExponential &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooExponential(*this, newname); } + + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName = nullptr) const override; + double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override; + + /// Get the x variable. + RooAbsReal const &variable() const { return x.arg(); } + + /// Get the coefficient "c". + RooAbsReal const &coefficient() const { return c.arg(); } + + bool negateCoefficient() const { return _negateCoefficient; } - Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override; - double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string buildCallToAnalyticIntegral(Int_t code, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const override; protected: - RooRealProxy x; - RooRealProxy c; + RooRealProxy x; + RooRealProxy c; + bool _negateCoefficient = false; - double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; - inline bool canComputeBatchWithCuda() const override { return true; } + double evaluate() const override; + void computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &) const override; + inline bool canComputeBatchWithCuda() const override { return true; } private: - ClassDefOverride(RooExponential,1) // Exponential PDF + ClassDefOverride(RooExponential, 2) // Exponential PDF }; #endif diff --git a/roofit/roofit/inc/RooGamma.h b/roofit/roofit/inc/RooGamma.h index 3125ab9b76fe9..62ae928edefe5 100644 --- a/roofit/roofit/inc/RooGamma.h +++ b/roofit/roofit/inc/RooGamma.h @@ -32,6 +32,10 @@ class RooGamma : public RooAbsPdf { Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const override; void generateEvent(Int_t code) override; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(Int_t code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + protected: RooRealProxy x ; @@ -40,7 +44,7 @@ class RooGamma : public RooAbsPdf { RooRealProxy mu ; double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooGaussModel.h b/roofit/roofit/inc/RooGaussModel.h index c3203e853bc38..d3a090012cc84 100644 --- a/roofit/roofit/inc/RooGaussModel.h +++ b/roofit/roofit/inc/RooGaussModel.h @@ -59,13 +59,25 @@ class RooGaussModel : public RooResolutionModel { void advertiseAymptoticIntegral(bool flag) { _asympInt = flag ; } // added FMV,07/24/03 + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; + + bool canComputeBatchWithCuda() const override { return getBasisType(_basisCode) == expBasis; } + protected: double evaluate() const override ; + static double evaluate(double x, double mean, double sigma, double param1, double param2, int basisCode); // Calculate common normalization factors std::complex evalCerfInt(double sign, double wt, double tau, double umin, double umax, double c) const; +private: + + static BasisType getBasisType(int basisCode) + { + return static_cast(basisCode == 0 ? 0 : (basisCode / 10) + 1); + } + bool _flatSFInt ; bool _asympInt ; // added FMV,07/24/03 diff --git a/roofit/roofit/inc/RooGaussian.h b/roofit/roofit/inc/RooGaussian.h index 8802345901277..fdcec93363f32 100644 --- a/roofit/roofit/inc/RooGaussian.h +++ b/roofit/roofit/inc/RooGaussian.h @@ -24,8 +24,12 @@ class RooAbsReal; class RooGaussian : public RooAbsPdf { public: RooGaussian() { }; + // Original constructor without RooAbsReal::Ref for backwards compatibility. + inline RooGaussian(const char *name, const char *title, + RooAbsReal& _x, RooAbsReal& _mean, RooAbsReal& _sigma) + : RooGaussian{name, title, RooAbsReal::Ref{_x}, RooAbsReal::Ref{_mean}, RooAbsReal::Ref{_sigma}} {} RooGaussian(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _mean, RooAbsReal& _sigma); + RooAbsReal::Ref _x, RooAbsReal::Ref _mean, RooAbsReal::Ref _sigma); RooGaussian(const RooGaussian& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooGaussian(*this,newname); @@ -47,6 +51,10 @@ class RooGaussian : public RooAbsPdf { /// Get the sigma parameter. RooAbsReal const& getSigma() const { return sigma.arg(); } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(Int_t code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + protected: RooRealProxy x ; @@ -54,7 +62,7 @@ class RooGaussian : public RooAbsPdf { RooRealProxy sigma ; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooHistConstraint.h b/roofit/roofit/inc/RooHistConstraint.h index 2c7d189e0ddea..37730779a9b82 100644 --- a/roofit/roofit/inc/RooHistConstraint.h +++ b/roofit/roofit/inc/RooHistConstraint.h @@ -21,7 +21,7 @@ class RooHistConstraint : public RooAbsPdf { /// It makes only sense to use the RooHistConstraint when normalized over the /// set of all gammas, in which case it is self-normalized because the used - /// TMath::Poisson funciton is normalized. + /// TMath::Poisson function is normalized. bool selfNormalized() const override { return true; } protected: diff --git a/roofit/roofit/inc/RooIntegralMorph.h b/roofit/roofit/inc/RooIntegralMorph.h index 6891a8721ad15..14eb297724815 100644 --- a/roofit/roofit/inc/RooIntegralMorph.h +++ b/roofit/roofit/inc/RooIntegralMorph.h @@ -68,17 +68,17 @@ class RooIntegralMorph : public RooAbsCachedPdf { void interpolateGap(Int_t ixlo, Int_t ixhi) ; RooIntegralMorph* _self ; // - RooArgSet* _nset ; + std::unique_ptr _nset ; RooAbsPdf* _pdf1 ; // PDF1 RooAbsPdf* _pdf2 ; // PDF2 RooRealVar* _x ; // X RooAbsReal* _alpha ; // ALPHA - RooAbsReal* _c1 ; // CDF of PDF 1 - RooAbsReal* _c2 ; // CDF of PDF 2 - RooAbsFunc* _cb1 ; // Binding of CDF1 - RooAbsFunc* _cb2 ; // Binding of CDF2 - RooBrentRootFinder* _rf1 ; // ROOT finder on CDF1 - RooBrentRootFinder* _rf2 ; // ROOT finder of CDF2 ; + std::unique_ptr _c1 ; // CDF of PDF 1 + std::unique_ptr _c2 ; // CDF of PDF 2 + std::unique_ptr _cb1 ; // Binding of CDF1 + std::unique_ptr _cb2 ; // Binding of CDF2 + std::unique_ptr _rf1; // ROOT finder on CDF1 + std::unique_ptr _rf2; // ROOT finder of CDF2 ; std::vector _yatX ; // std::vector _calcX; // @@ -94,8 +94,8 @@ class RooIntegralMorph : public RooAbsCachedPdf { friend class MorphCacheElem ; PdfCacheElem* createCache(const RooArgSet* nset) const override ; const char* inputBaseName() const override ; - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualObservables(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualParameters(const RooArgSet& nset) const override ; void fillCacheObject(PdfCacheElem& cache) const override ; RooRealProxy pdf1 ; // First input shape diff --git a/roofit/roofit/inc/RooJohnson.h b/roofit/roofit/inc/RooJohnson.h index 13ed836354df0..ea16d91bc5432 100644 --- a/roofit/roofit/inc/RooJohnson.h +++ b/roofit/roofit/inc/RooJohnson.h @@ -57,7 +57,7 @@ class RooJohnson final : public RooAbsPdf { double _massThreshold{-1.E300}; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } ClassDefOverride(RooJohnson,1) diff --git a/roofit/roofit/inc/RooKeysPdf.h b/roofit/roofit/inc/RooKeysPdf.h index 945ae2fbd189f..2600a59ede57b 100644 --- a/roofit/roofit/inc/RooKeysPdf.h +++ b/roofit/roofit/inc/RooKeysPdf.h @@ -63,7 +63,7 @@ class RooKeysPdf : public RooAbsPdf { double *_weights; //[_nEvents] double _sumWgt ; - enum { _nPoints = 1000 }; + constexpr static int _nPoints{1000}; double _lookupTable[_nPoints+1]; double g(double x,double sigma) const; diff --git a/roofit/roofit/inc/RooLandau.h b/roofit/roofit/inc/RooLandau.h index 480fc1b22c2bb..37bbd6e16079f 100644 --- a/roofit/roofit/inc/RooLandau.h +++ b/roofit/roofit/inc/RooLandau.h @@ -24,7 +24,10 @@ class RooRealVar; class RooLandau : public RooAbsPdf { public: RooLandau() {} ; - RooLandau(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _mean, RooAbsReal& _sigma); + // Original constructor without RooAbsReal::Ref for backwards compatibility. + inline RooLandau(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _mean, RooAbsReal& _sigma) + : RooLandau{name, title, RooAbsReal::Ref{_x}, RooAbsReal::Ref{_mean}, RooAbsReal::Ref{_sigma}} {} + RooLandau(const char *name, const char *title, RooAbsReal::Ref _x, RooAbsReal::Ref _mean, RooAbsReal::Ref _sigma); RooLandau(const RooLandau& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooLandau(*this,newname); } inline ~RooLandau() override { } @@ -32,6 +35,13 @@ class RooLandau : public RooAbsPdf { Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const override; void generateEvent(Int_t code) override; + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName = nullptr) const override; + double analyticalIntegral(Int_t code, const char *rangeName) const override; + + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(Int_t code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + protected: RooRealProxy x ; @@ -39,7 +49,7 @@ class RooLandau : public RooAbsPdf { RooRealProxy sigma ; double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooLognormal.h b/roofit/roofit/inc/RooLognormal.h index 8114c6fcffddf..c87903ce60465 100644 --- a/roofit/roofit/inc/RooLognormal.h +++ b/roofit/roofit/inc/RooLognormal.h @@ -1,49 +1,60 @@ - /***************************************************************************** - * Project: RooFit * - * @(#)root/roofit:$Id$ * - * * - * RooFit Lognormal PDF * - * * - * Author: Gregory Schott and Stefan Schmitz * - * * - *****************************************************************************/ +/***************************************************************************** + * Project: RooFit * + * @(#)root/roofit:$Id$ * + * * + * RooFit Lognormal PDF * + * * + * Author: Gregory Schott and Stefan Schmitz * + * * + *****************************************************************************/ #ifndef ROO_LOGNORMAL #define ROO_LOGNORMAL -#include "RooAbsPdf.h" -#include "RooRealProxy.h" - -class RooRealVar; +#include +#include class RooLognormal : public RooAbsPdf { public: - RooLognormal() {} ; - RooLognormal(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _m0, RooAbsReal& _k); - RooLognormal(const RooLognormal& other, const char* name=nullptr) ; - TObject* clone(const char* newname) const override { return new RooLognormal(*this,newname); } - inline ~RooLognormal() override { } + RooLognormal() {} + RooLognormal(const char *name, const char *title, RooAbsReal &_x, RooAbsReal &_m0, RooAbsReal &_k, + bool useStandardParametrization = false); + RooLognormal(const RooLognormal &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooLognormal(*this, newname); } - Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; - double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName = nullptr) const override; + double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override; - Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const override; - void generateEvent(Int_t code) override; + Int_t getGenerator(const RooArgSet &directVars, RooArgSet &generateVars, bool staticInitOK = true) const override; + void generateEvent(Int_t code) override; -protected: + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(int code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; - RooRealProxy x ; - RooRealProxy m0 ; - RooRealProxy k ; + /// Get the x variable. + RooAbsReal const &getX() const { return x.arg(); } - double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; - inline bool canComputeBatchWithCuda() const override { return true; } + /// Get the median parameter. + RooAbsReal const &getMedian() const { return m0.arg(); } -private: + /// Get the shape parameter. + RooAbsReal const &getShapeK() const { return k.arg(); } + + bool useStandardParametrization() const { return _useStandardParametrization; } - ClassDefOverride(RooLognormal,1) // log-normal PDF +protected: + RooRealProxy x; ///< the variable + RooRealProxy m0; ///< the median, exp(mu) + RooRealProxy k; ///< the shape parameter, exp(sigma) + bool _useStandardParametrization = false; + + double evaluate() const override; + void computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &) const override; + inline bool canComputeBatchWithCuda() const override { return true; } + +private: + ClassDefOverride(RooLognormal, 2) // log-normal PDF }; #endif diff --git a/roofit/roofit/inc/RooMomentMorphFuncND.h b/roofit/roofit/inc/RooMomentMorphFuncND.h index f8a75eec13f69..d4925046dcffc 100644 --- a/roofit/roofit/inc/RooMomentMorphFuncND.h +++ b/roofit/roofit/inc/RooMomentMorphFuncND.h @@ -24,10 +24,13 @@ #include class RooChangeTracker; +class RooRealSumFunc; class RooMomentMorphFuncND : public RooAbsReal { public: + using Base_t = RooAbsReal; + class Grid2 { public: Grid2(){}; @@ -44,7 +47,7 @@ class RooMomentMorphFuncND : public RooAbsReal { _grid.push_back(binning_y.clone()); _grid.push_back(binning_z.clone()); }; - Grid2(const std::vector binnings) + Grid2(std::vector const &binnings) { for (unsigned int i = 0; i < binnings.size(); i++) { _grid.push_back(binnings[i]->clone()); @@ -66,20 +69,22 @@ class RooMomentMorphFuncND : public RooAbsReal { mutable std::vector> _nref; mutable std::vector _nnuis; - ClassDef(RooMomentMorphFuncND::Grid2, 1) + ClassDef(RooMomentMorphFuncND::Grid2, 1); }; + using Grid = Grid2; + protected: class CacheElem : public RooAbsCacheElement { public: CacheElem(RooAbsReal &sumFunc, RooChangeTracker &tracker, const RooArgList &flist) - : _sumFunc(&sumFunc), _tracker(&tracker) + : _sum(&sumFunc), _tracker(&tracker) { _frac.add(flist); }; ~CacheElem() override; RooArgList containedArgs(Action) override; - RooAbsReal *_sumFunc; + RooAbsReal *_sum; RooChangeTracker *_tracker; RooArgList _frac; @@ -103,12 +108,26 @@ class RooMomentMorphFuncND : public RooAbsReal { TObject *clone(const char *newname) const override { return new RooMomentMorphFuncND(*this, newname); } void setMode(const Setting &setting) { _setting = setting; } - virtual bool selfNormalized() const { return true; } + /// Setting flag makes this RooMomentMorphFuncND instance behave like the + /// former RooMomentMorphND class, with the the only difference being the + /// base class. If you want to create a pdf object that behaves exactly like + /// the old RooMomentMorphND, you can do it as follows: + /// + /// ```C++ + /// RooMomentMorphFuncND func{}; + /// + /// func.setPdfMode(); // change behavior to be exactly like the former RooMomentMorphND + /// + /// // Pass the selfNormalized=true` flag to the wrapper because the + /// RooMomentMorphFuncND already normalizes itself in pdf mode. + /// RooWrapperPdf pdf{"pdf_name", "pdf_name", func, /*selfNormalized=*/true}; + /// ``` + void setPdfMode(bool flag=true) { _isPdfMode = flag; } bool setBinIntegrator(RooArgSet &allVars); void useHorizontalMorphing(bool val) { _useHorizMorph = val; } double evaluate() const override; - virtual double getVal(const RooArgSet *set = nullptr) const; + double getValV(const RooArgSet *set = nullptr) const override; protected: void initialize(); @@ -118,41 +137,31 @@ class RooMomentMorphFuncND : public RooAbsReal { RooAbsReal *sumFunc(const RooArgSet *nset); CacheElem *getCache(const RooArgSet *nset) const; - template - struct Digits { - typename std::vector::const_iterator begin; - typename std::vector::const_iterator end; - typename std::vector::const_iterator me; - }; - - template - static void cartesian_product(std::vector> &out, std::vector> &in); - template - static bool next_combination(const Iterator first, Iterator k, const Iterator last); void findShape(const std::vector &x) const; friend class CacheElem; friend class Grid2; - mutable RooObjCacheManager _cacheMgr; /// _M; + mutable std::unique_ptr _MSqr; mutable std::vector> _squareVec; mutable std::vector _squareIdx; Setting _setting; bool _useHorizMorph; + bool _isPdfMode = false; inline int sij(const int &i, const int &j) const { return (i * _obsList.getSize() + j); } - ClassDefOverride(RooMomentMorphFuncND, 2) + ClassDefOverride(RooMomentMorphFuncND, 4); }; #endif diff --git a/roofit/roofit/inc/RooMomentMorphND.h b/roofit/roofit/inc/RooMomentMorphND.h deleted file mode 100644 index aa427cfa687d5..0000000000000 --- a/roofit/roofit/inc/RooMomentMorphND.h +++ /dev/null @@ -1,145 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * * - * This code was autogenerated by RooClassFactory * - *****************************************************************************/ - -#ifndef ROOMOMENTMORPHND -#define ROOMOMENTMORPHND - -#include "RooAbsPdf.h" -#include "RooRealProxy.h" -#include "RooCategoryProxy.h" -#include "RooAbsReal.h" -#include "RooAbsCategory.h" -#include "RooSetProxy.h" -#include "RooListProxy.h" -#include "RooArgList.h" -#include "RooBinning.h" - -#include "TMatrixD.h" -#include "TMap.h" - -#include -#include - -class RooChangeTracker; - -class RooMomentMorphND : public RooAbsPdf { - -public: - class Grid { - public: - Grid(){}; - Grid(const Grid &other); - Grid(const RooAbsBinning &binning_x) { _grid.push_back(binning_x.clone()); }; - Grid(const RooAbsBinning &binning_x, const RooAbsBinning &binning_y) - { - _grid.push_back(binning_x.clone()); - _grid.push_back(binning_y.clone()); - }; - Grid(const RooAbsBinning &binning_x, const RooAbsBinning &binning_y, const RooAbsBinning &binning_z) - { - _grid.push_back(binning_x.clone()); - _grid.push_back(binning_y.clone()); - _grid.push_back(binning_z.clone()); - }; - Grid(const std::vector binnings) - { - for (unsigned int i = 0; i < binnings.size(); i++) { - _grid.push_back(binnings[i]->clone()); - } - }; - - ~Grid(); - - void addPdf(const RooAbsPdf &pdf, int bin_x); - void addPdf(const RooAbsPdf &pdf, int bin_x, int bin_y); - void addPdf(const RooAbsPdf &pdf, int bin_x, int bin_y, int bin_z); - void addPdf(const RooAbsPdf &pdf, std::vector bins); - void addBinning(const RooAbsBinning &binning) { _grid.push_back(binning.clone()); }; - - mutable std::vector _grid; - mutable RooArgList _pdfList; - mutable std::map, int> _pdfMap; - - mutable std::vector> _nref; - mutable std::vector _nnuis; - }; - -protected: - class CacheElem : public RooAbsCacheElement { - public: - CacheElem(RooAbsPdf &sumPdf, RooChangeTracker &tracker, const RooArgList &flist) - : _sumPdf(&sumPdf), _tracker(&tracker) - { - _frac.add(flist); - }; - ~CacheElem() override; - RooArgList containedArgs(Action) override; - RooAbsPdf *_sumPdf; - RooChangeTracker *_tracker; - RooArgList _frac; - - RooRealVar *frac(int i); - const RooRealVar *frac(int i) const; - void calculateFractions(const RooMomentMorphND &self, bool verbose = true) const; - }; - -public: - enum Setting { Linear, SineLinear, NonLinear, NonLinearPosFractions, NonLinearLinFractions }; - - RooMomentMorphND(); - RooMomentMorphND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, - const RooArgList &pdfList, const RooArgList &mrefList, Setting setting); - RooMomentMorphND(const char *name, const char *title, const RooArgList &parList, const RooArgList &obsList, - const Grid &referenceGrid, const Setting &setting); - RooMomentMorphND(const RooMomentMorphND &other, const char *name = nullptr); - RooMomentMorphND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, - const RooArgList &pdfList, const TVectorD &mrefpoints, Setting setting); - ~RooMomentMorphND() override; - TObject *clone(const char *newname) const override { return new RooMomentMorphND(*this, newname); } - - void setMode(const Setting &setting) { _setting = setting; } - bool selfNormalized() const override { return true; } - bool setBinIntegrator(RooArgSet &allVars); - void useHorizontalMorphing(bool val) { _useHorizMorph = val; } - - double evaluate() const override; - virtual double getVal(const RooArgSet *set = nullptr) const; - -protected: - void initialize(); - void initializeParameters(const RooArgList &parList); - void initializeObservables(const RooArgList &obsList); - - RooAbsPdf *sumPdf(const RooArgSet *nset); - CacheElem *getCache(const RooArgSet *nset) const; - - void findShape(const std::vector &x) const; - - friend class CacheElem; - friend class Grid; - - mutable RooObjCacheManager _cacheMgr; ///> _squareVec; - mutable std::vector _squareIdx; - - Setting _setting; - bool _useHorizMorph; - - inline int sij(const int &i, const int &j) const { return (i * _obsList.getSize() + j); } - - ClassDefOverride(RooMomentMorphND, 2) -}; - -#endif diff --git a/roofit/roofit/inc/RooNDKeysPdf.h b/roofit/roofit/inc/RooNDKeysPdf.h index e70a37d0da784..6fe4c6b4ba35b 100644 --- a/roofit/roofit/inc/RooNDKeysPdf.h +++ b/roofit/roofit/inc/RooNDKeysPdf.h @@ -90,11 +90,6 @@ class RooNDKeysPdf : public RooAbsPdf { Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; - inline void fixShape(bool fix) { - createPdf(false); - _fixedShape=fix; - } - TMatrixD getWeights(const int &k) const; struct BoxInfo { @@ -117,12 +112,12 @@ class RooNDKeysPdf : public RooAbsPdf { double evaluate() const override; - void createPdf(bool firstCall = true); + void createPdf(bool firstCall, RooDataSet const& data); void setOptions(); - void initialize(); - void loadDataSet(bool firstCall); + void initialize(RooDataSet const& data); + void loadDataSet(bool firstCall, RooDataSet const& data); void mirrorDataSet(); - void loadWeightSet(); + void loadWeightSet(RooDataSet const& data); void calculateShell(BoxInfo *bi) const; void calculatePreNorm(BoxInfo *bi) const; void sortDataIndices(BoxInfo *bi = nullptr); @@ -138,8 +133,6 @@ class RooNDKeysPdf : public RooAbsPdf { const_cast(this)->calculateBandWidth(); } - std::unique_ptr _ownedData{nullptr}; - const RooDataSet* _data; //! do not persist mutable TString _options; double _widthFactor; double _nSigma; @@ -207,7 +200,7 @@ class RooNDKeysPdf : public RooAbsPdf { RooChangeTracker *_tracker{nullptr}; // - ClassDefOverride(RooNDKeysPdf, 1) // General N-dimensional non-parametric kernel estimation p.d.f + ClassDefOverride(RooNDKeysPdf, 2) // General N-dimensional non-parametric kernel estimation p.d.f }; #endif diff --git a/roofit/roofit/inc/RooNovosibirsk.h b/roofit/roofit/inc/RooNovosibirsk.h index 607c3f62a689e..8093d788668a1 100644 --- a/roofit/roofit/inc/RooNovosibirsk.h +++ b/roofit/roofit/inc/RooNovosibirsk.h @@ -45,7 +45,7 @@ class RooNovosibirsk : public RooAbsPdf { protected: double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/inc/RooParamHistFunc.h b/roofit/roofit/inc/RooParamHistFunc.h index e907d650d073c..4a61f49aa50fa 100644 --- a/roofit/roofit/inc/RooParamHistFunc.h +++ b/roofit/roofit/inc/RooParamHistFunc.h @@ -43,6 +43,8 @@ class RooParamHistFunc : public RooAbsReal { const RooArgList& paramList() const { return _p ; } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + protected: friend class RooHistConstraint ; diff --git a/roofit/roofit/inc/RooParametricStepFunction.h b/roofit/roofit/inc/RooParametricStepFunction.h index a375e2d5a9118..48defbbc1e627 100644 --- a/roofit/roofit/inc/RooParametricStepFunction.h +++ b/roofit/roofit/inc/RooParametricStepFunction.h @@ -15,12 +15,12 @@ #ifndef ROO_PARAMETRIC_STEP_FUNCTION #define ROO_PARAMETRIC_STEP_FUNCTION -#include "TArrayD.h" -#include "RooAbsPdf.h" -#include "RooRealProxy.h" -#include "RooListProxy.h" +#include +#include +#include + +#include -class RooRealVar; class RooArgList ; class RooParametricStepFunction : public RooAbsPdf { @@ -29,7 +29,7 @@ class RooParametricStepFunction : public RooAbsPdf { RooParametricStepFunction() {} RooParametricStepFunction(const char *name, const char *title, - RooAbsReal& x, const RooArgList& coefList, TArrayD& limits, Int_t nBins=1) ; + RooAbsReal& x, const RooArgList& coefList, TArrayD const& limits, Int_t nBins=1) ; RooParametricStepFunction(const RooParametricStepFunction& other, const char* name = nullptr); TObject* clone(const char* newname) const override { return new RooParametricStepFunction(*this, newname); } @@ -39,6 +39,8 @@ class RooParametricStepFunction : public RooAbsPdf { Int_t getnBins() const { return _nBins; } double* getLimits() { return _limits.GetArray(); } + std::list* plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const override ; + protected: double lastBinValue() const ; diff --git a/roofit/roofit/inc/RooPoisson.h b/roofit/roofit/inc/RooPoisson.h index f5b581b298dd8..b89b9a1fd0ce1 100644 --- a/roofit/roofit/inc/RooPoisson.h +++ b/roofit/roofit/inc/RooPoisson.h @@ -19,7 +19,10 @@ class RooPoisson : public RooAbsPdf { public: RooPoisson() { _noRounding = false ; } ; - RooPoisson(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _mean, bool noRounding=false); + // Original constructor without RooAbsReal::Ref for backwards compatibility. + inline RooPoisson(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _mean, bool noRounding=false) + : RooPoisson{name, title, RooAbsReal::Ref{_x}, RooAbsReal::Ref{_mean}, noRounding} {} + RooPoisson(const char *name, const char *title, RooAbsReal::Ref _x, RooAbsReal::Ref _mean, bool noRounding=false); RooPoisson(const RooPoisson& other, const char* name=nullptr) ; TObject* clone(const char* newname) const override { return new RooPoisson(*this,newname); } inline ~RooPoisson() override { } @@ -32,6 +35,8 @@ class RooPoisson : public RooAbsPdf { /// Switch off/on rounding of `x` to the nearest integer. void setNoRounding(bool flag = true) {_noRounding = flag;} + bool getNoRounding() const { return _noRounding; } + /// Switch on or off protection against negative means. void protectNegativeMean(bool flag = true) {_protectNegative = flag;} @@ -41,6 +46,10 @@ class RooPoisson : public RooAbsPdf { /// Get the mean parameter. RooAbsReal const& getMean() const { return mean.arg(); } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(int code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + protected: RooRealProxy x ; @@ -49,7 +58,7 @@ class RooPoisson : public RooAbsPdf { bool _protectNegative{true}; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } ClassDefOverride(RooPoisson,3) // A Poisson PDF diff --git a/roofit/roofit/inc/RooPolynomial.h b/roofit/roofit/inc/RooPolynomial.h index 8b6d1314d13ed..c8f9fb90a6237 100644 --- a/roofit/roofit/inc/RooPolynomial.h +++ b/roofit/roofit/inc/RooPolynomial.h @@ -16,44 +16,58 @@ #ifndef ROO_POLYNOMIAL #define ROO_POLYNOMIAL -#include - -#include "RooAbsPdf.h" -#include "RooRealProxy.h" -#include "RooListProxy.h" +#include +#include +#include -class RooRealVar; -class RooArgList ; +#include class RooPolynomial : public RooAbsPdf { public: + RooPolynomial() {} + RooPolynomial(const char *name, const char *title, RooAbsReal &x); + RooPolynomial(const char *name, const char *title, RooAbsReal &_x, const RooArgList &_coefList, + Int_t lowestOrder = 1); + + RooPolynomial(const RooPolynomial &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooPolynomial(*this, newname); } + + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName = nullptr) const override; + double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override; + + /// Get the x variable. + RooAbsReal const &x() const { return _x.arg(); } + + /// Get the coefficient list. + RooArgList const &coefList() const { return _coefList; } - RooPolynomial() ; - RooPolynomial(const char* name, const char* title, RooAbsReal& x) ; - RooPolynomial(const char *name, const char *title, - RooAbsReal& _x, const RooArgList& _coefList, Int_t lowestOrder=1) ; + /// Return the order for the first coefficient in the list. + int lowestOrder() const { return _lowestOrder; } - RooPolynomial(const RooPolynomial& other, const char *name = nullptr); - TObject* clone(const char* newname) const override { return new RooPolynomial(*this, newname); } - ~RooPolynomial() override ; + // If this polynomial has no terms it's a uniform distribution, and a uniform + // pdf is a reducer node because it doesn't depend on the observables. + bool isReducerNode() const override { return _coefList.empty(); } - Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; - double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string buildCallToAnalyticIntegral(Int_t code, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const override; protected: + RooRealProxy _x; + RooListProxy _coefList; + Int_t _lowestOrder = 1; - RooRealProxy _x; - RooListProxy _coefList ; - Int_t _lowestOrder ; + mutable std::vector _wksp; //! do not persist - mutable std::vector _wksp; //! do not persist + /// Evaluation + double evaluate() const override; + void computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &) const override; - /// Evaluation - double evaluate() const override; - //void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::DataMap&) const; - //inline bool canComputeBatchWithCuda() const { return true; } + // It doesn't make sense to use the GPU if the polynomial has no terms. + inline bool canComputeBatchWithCuda() const override { return !_coefList.empty(); } - ClassDefOverride(RooPolynomial,1) // Polynomial PDF +private: + ClassDefOverride(RooPolynomial, 1); // Polynomial PDF }; #endif diff --git a/roofit/roofit/inc/RooPower.h b/roofit/roofit/inc/RooPower.h index 0785b471d1d04..e1e44bb8ef80e 100644 --- a/roofit/roofit/inc/RooPower.h +++ b/roofit/roofit/inc/RooPower.h @@ -20,11 +20,19 @@ class RooPower : public RooAbsPdf { public: RooPower() {} - RooPower(const char *name, const char *title, RooAbsReal &x); RooPower(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, const RooArgList &expList); RooPower(const RooPower &other, const char *name = nullptr); - virtual TObject *clone(const char *newname) const override { return new RooPower(*this, newname); } + TObject *clone(const char *newname) const override { return new RooPower(*this, newname); } + + /// Get the base of the exponentiated terms (aka. x variable). + RooAbsReal const &base() const { return *_x; } + + /// Get the list of coefficients. + RooArgList const &coefList() const { return _coefList; } + + /// Get the list of exponents. + RooArgList const &expList() const { return _expList; } std::string getFormulaExpression(bool expand) const; @@ -38,6 +46,10 @@ class RooPower : public RooAbsPdf { mutable std::vector _wksp; //! do not persist + // CUDA support + void computeBatch(double *output, size_t size, RooFit::Detail::DataMap const &) const override; + inline bool canComputeBatchWithCuda() const override { return true; } + /// Evaluation double evaluate() const override; diff --git a/roofit/roofit/inc/RooSpline.h b/roofit/roofit/inc/RooSpline.h new file mode 100644 index 0000000000000..e01caa3b4c382 --- /dev/null +++ b/roofit/roofit/inc/RooSpline.h @@ -0,0 +1,51 @@ +/* + * Project: RooFit + * Author: + * Ruggero Turra , 2016 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_RooSpline_h +#define RooFit_RooSpline_h + +#include +#include + +#include + +#include + +#include + +class TGraph; + +class RooSpline : public RooAbsReal { +public: + RooSpline() = default; + RooSpline(const char *name, const char *title, RooAbsReal &x, std::span x0, std::span y0, + int order = 3, bool logx = false, bool logy = false); + RooSpline(const char *name, const char *title, RooAbsReal &x, const TGraph &gr, int order = 3, bool logx = false, + bool logy = false); + RooSpline(const RooSpline &other, const char *name = nullptr); + + /// Virtual copy constructor. + /// \param[in] newname The name of the cloned object (optional). + TObject *clone(const char *newname) const override { return new RooSpline(*this, newname); } + +protected: + double evaluate() const override; + +private: + std::unique_ptr _spline; ///< The spline object. + RooRealProxy _x; ///< The independent variable. + bool _logx = false; ///< Flag indicating logarithmic scaling of x values. + bool _logy = false; ///< Flag indicating logarithmic scaling of y values. + + ClassDefOverride(RooSpline, 1); // A RooFit class for creating spline functions +}; +#endif diff --git a/roofit/roofit/inc/RooStepFunction.h b/roofit/roofit/inc/RooStepFunction.h index 6c0d7f08a8d13..879e660a88904 100644 --- a/roofit/roofit/inc/RooStepFunction.h +++ b/roofit/roofit/inc/RooStepFunction.h @@ -17,18 +17,16 @@ #ifndef ROO_STEP_FUNCTION #define ROO_STEP_FUNCTION -#include "TArrayD.h" -#include "RooAbsReal.h" -#include "RooRealProxy.h" -#include "RooListProxy.h" +#include +#include +#include -class RooRealVar; class RooArgList ; class RooStepFunction : public RooAbsReal { public: - RooStepFunction() ; + RooStepFunction() {} RooStepFunction(const char *name, const char *title, RooAbsReal& x, const RooArgList& coefList, const RooArgList& limits, bool interpolate=false) ; @@ -38,6 +36,8 @@ class RooStepFunction : public RooAbsReal { const RooArgList& coefficients() { return _coefList; } const RooArgList& boundaries() { return _boundaryList; } + std::list* plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const override ; + protected: double evaluate() const override; @@ -47,7 +47,7 @@ class RooStepFunction : public RooAbsReal { RooRealProxy _x; RooListProxy _coefList ; RooListProxy _boundaryList ; - bool _interpolate ; + bool _interpolate = false; ClassDefOverride(RooStepFunction,1) // Step Function }; diff --git a/roofit/roofit/inc/RooTFnBinding.h b/roofit/roofit/inc/RooTFnBinding.h index c5dbeeeeafb0b..d360d66defb2f 100644 --- a/roofit/roofit/inc/RooTFnBinding.h +++ b/roofit/roofit/inc/RooTFnBinding.h @@ -24,6 +24,10 @@ class RooTFnBinding : public RooAbsReal { void printArgs(std::ostream& os) const override ; + const RooArgList& observables() const { return _olist;} + const RooArgList& parameters() const { return _plist; } + const TF1& function() const { return *_func; } + protected: RooListProxy _olist ; diff --git a/roofit/roofit/inc/RooUniform.h b/roofit/roofit/inc/RooUniform.h index e1d57754f9cfb..1330d64707d79 100644 --- a/roofit/roofit/inc/RooUniform.h +++ b/roofit/roofit/inc/RooUniform.h @@ -40,7 +40,6 @@ class RooUniform : public RooAbsPdf { RooListProxy x ; double evaluate() const override ; - RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* /*normSet*/ = nullptr) const override; private: diff --git a/roofit/roofit/inc/RooVoigtian.h b/roofit/roofit/inc/RooVoigtian.h index 092015ab6952a..b6ca3978ec5ae 100644 --- a/roofit/roofit/inc/RooVoigtian.h +++ b/roofit/roofit/inc/RooVoigtian.h @@ -45,7 +45,7 @@ class RooVoigtian : public RooAbsPdf { RooRealProxy sigma ; double evaluate() const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } private: diff --git a/roofit/roofit/src/Roo2DKeysPdf.cxx b/roofit/roofit/src/Roo2DKeysPdf.cxx index 6112ef6535929..68ae7edb3b92c 100644 --- a/roofit/roofit/src/Roo2DKeysPdf.cxx +++ b/roofit/roofit/src/Roo2DKeysPdf.cxx @@ -555,7 +555,7 @@ void Roo2DKeysPdf::writeHistToFile(char * outputFile, const char * histName) con void Roo2DKeysPdf::writeNTupleToFile(char * outputFile, const char * name) const { - TFile * file = 0; + TFile * file = nullptr; //make sure that any existing file is not over written file = new TFile(outputFile, "UPDATE"); diff --git a/roofit/roofit/src/RooArgusBG.cxx b/roofit/roofit/src/RooArgusBG.cxx index 0e3fa75af6d81..641e8141967c8 100644 --- a/roofit/roofit/src/RooArgusBG.cxx +++ b/roofit/roofit/src/RooArgusBG.cxx @@ -42,20 +42,7 @@ ClassImp(RooArgusBG); /// Constructor. RooArgusBG::RooArgusBG(const char *name, const char *title, - RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c) : - RooAbsPdf(name, title), - m("m","Mass",this,_m), - m0("m0","Resonance mass",this,_m0), - c("c","Slope parameter",this,_c), - p("p","Power",this,(RooRealVar&)RooRealConstant::value(0.5)) -{ -} - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor. - -RooArgusBG::RooArgusBG(const char *name, const char *title, - RooAbsReal& _m, RooAbsReal& _m0, RooAbsReal& _c, RooAbsReal& _p) : + RooAbsReal::Ref _m, RooAbsReal::Ref _m0, RooAbsReal::Ref _c, RooAbsReal::Ref _p) : RooAbsPdf(name, title), m("m","Mass",this,_m), m0("m0","Resonance mass",this,_m0), @@ -88,10 +75,9 @@ double RooArgusBG::evaluate() const { //////////////////////////////////////////////////////////////////////////////// -void RooArgusBG::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooArgusBG::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::ArgusBG, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::ArgusBG, output, nEvents, {dataMap.at(m), dataMap.at(m0), dataMap.at(c), dataMap.at(p)}); } diff --git a/roofit/roofit/src/RooBCPEffDecay.cxx b/roofit/roofit/src/RooBCPEffDecay.cxx index 6630a9c5a0a7b..3c156d27dc6d2 100644 --- a/roofit/roofit/src/RooBCPEffDecay.cxx +++ b/roofit/roofit/src/RooBCPEffDecay.cxx @@ -32,19 +32,35 @@ using namespace std; ClassImp(RooBCPEffDecay); -//////////////////////////////////////////////////////////////////////////////// -/// Constructor. +/// \brief Constructor for RooBCPEffDecay. +/// +/// Creates an instance of RooBCPEffDecay with the specified parameters. +/// +/// \param[in] name The name of the PDF. +/// \param[in] title The title of the PDF. +/// \param[in] t The time variable. +/// \param[in] tag The CP state category. +/// \param[in] tau The decay time parameter. +/// \param[in] dm The mixing frequency parameter. +/// \param[in] avgMistag The average mistag rate parameter. +/// \param[in] CPeigenval The CP eigen value parameter. +/// \param[in] absLambda The absolute value of the complex lambda parameter. +/// \param[in] argLambda The argument of the complex lambda parameter. +/// \param[in] effRatio The B0/B0bar efficiency ratio. +/// \param[in] delMistag Delta mistag rate parameter. +/// \param[in] model The resolution model. +/// \param[in] type The decay type. RooBCPEffDecay::RooBCPEffDecay(const char *name, const char *title, RooRealVar& t, RooAbsCategory& tag, RooAbsReal& tau, RooAbsReal& dm, RooAbsReal& avgMistag, RooAbsReal& CPeigenval, - RooAbsReal& a, RooAbsReal& b, + RooAbsReal& absLambda, RooAbsReal& argLambda, RooAbsReal& effRatio, RooAbsReal& delMistag, const RooResolutionModel& model, DecayType type) : RooAbsAnaConvPdf(name,title,model,t), - _absLambda("absLambda","Absolute value of lambda",this,a), - _argLambda("argLambda","Arg(Lambda)",this,b), + _absLambda("absLambda","Absolute value of lambda",this,absLambda), + _argLambda("argLambda","Arg(Lambda)",this,argLambda), _effRatio("effRatio","B0/B0bar efficiency ratio",this,effRatio), _CPeigenval("CPeigenval","CP eigen value",this,CPeigenval), _avgMistag("avgMistag","Average mistag rate",this,avgMistag), @@ -98,13 +114,6 @@ RooBCPEffDecay::RooBCPEffDecay(const RooBCPEffDecay& other, const char* name) : { } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor. - -RooBCPEffDecay::~RooBCPEffDecay() -{ -} - //////////////////////////////////////////////////////////////////////////////// /// B0 : _tag = +1 /// @@ -206,7 +215,7 @@ void RooBCPEffDecay::generateEvent(Int_t code) } // Generate delta-t dependent - while(1) { + while(true) { double rand = RooRandom::uniform() ; double tval(0) ; @@ -225,7 +234,7 @@ void RooBCPEffDecay::generateEvent(Int_t code) // Accept event if T is in generated range double maxDil = 1.0 ; double al2 = _absLambda*_absLambda ; - double maxAcceptProb = (1+al2) + fabs(maxDil*_CPeigenval*_absLambda*_argLambda) + fabs(maxDil*(1-al2)/2); + double maxAcceptProb = (1+al2) + std::abs(maxDil*_CPeigenval*_absLambda*_argLambda) + std::abs(maxDil*(1-al2)/2); double acceptProb = (1+al2)/2*(1-_tag*_delMistag) - (_tag*(1-2*_avgMistag))*(_CPeigenval*_absLambda*_argLambda)*sin(_dm*tval) - (_tag*(1-2*_avgMistag))*(1-al2)/2*cos(_dm*tval); diff --git a/roofit/roofit/src/RooBCPGenDecay.cxx b/roofit/roofit/src/RooBCPGenDecay.cxx index 57f4320cc79d7..7628c410abb02 100644 --- a/roofit/roofit/src/RooBCPGenDecay.cxx +++ b/roofit/roofit/src/RooBCPGenDecay.cxx @@ -33,23 +33,38 @@ using namespace std; ClassImp(RooBCPGenDecay); -//////////////////////////////////////////////////////////////////////////////// -/// Constructor +/// \brief Constructor for RooBCPGenDecay. +/// +/// Creates an instance of RooBCPGenDecay with the specified parameters. +/// +/// \param[in] name The name of the PDF. +/// \param[in] title The title of the PDF. +/// \param[in] t The time variable. +/// \param[in] tag The CP state category. +/// \param[in] tau The decay time parameter. +/// \param[in] dm The mixing frequency parameter. +/// \param[in] avgMistag The average mistag rate parameter. +/// \param[in] avgC Coefficient of cos term. +/// \param[in] avgS Coefficient of sin term. +/// \param[in] delMistag Delta mistag rate parameter. +/// \param[in] mu Tag efficiency difference parameter. +/// \param[in] model The resolution model. +/// \param[in] type The decay type. RooBCPGenDecay::RooBCPGenDecay(const char *name, const char *title, RooRealVar& t, RooAbsCategory& tag, RooAbsReal& tau, RooAbsReal& dm, RooAbsReal& avgMistag, - RooAbsReal& a, RooAbsReal& b, + RooAbsReal& avgC, RooAbsReal& avgS, RooAbsReal& delMistag, RooAbsReal& mu, const RooResolutionModel& model, DecayType type) : RooAbsAnaConvPdf(name,title,model,t), - _avgC("C","Coefficient of cos term",this,a), - _avgS("S","Coefficient of sin term",this,b), + _avgC("C","Coefficient of cos term",this,avgC), + _avgS("S","Coefficient of sin term",this,avgS), _avgMistag("avgMistag","Average mistag rate",this,avgMistag), _delMistag("delMistag","Delta mistag rate",this,delMistag), - _mu("mu","Tagg efficiency difference",this,mu), + _mu("mu","Tag efficiency difference",this,mu), _t("t","time",this,t), _tau("tau","decay time",this,tau), _dm("dm","mixing frequency",this,dm), @@ -98,13 +113,6 @@ RooBCPGenDecay::RooBCPGenDecay(const RooBCPGenDecay& other, const char* name) : { } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooBCPGenDecay::~RooBCPGenDecay() -{ -} - //////////////////////////////////////////////////////////////////////////////// /// B0 : _tag = +1 /// B0bar : _tag = -1 @@ -205,7 +213,7 @@ void RooBCPGenDecay::generateEvent(Int_t code) } // Generate delta-t dependent - while(1) { + while(true) { double rand = RooRandom::uniform() ; double tval(0) ; @@ -224,7 +232,7 @@ void RooBCPGenDecay::generateEvent(Int_t code) // Accept event if T is in generated range double maxDil = 1.0 ; // 2 in next line is conservative and inefficient - allows for delMistag=1! - double maxAcceptProb = 2 + fabs(maxDil*_avgS) + fabs(maxDil*_avgC); + double maxAcceptProb = 2 + std::abs(maxDil*_avgS) + std::abs(maxDil*_avgC); double acceptProb = (1-_tag*_delMistag + _mu*_tag*(1. - 2.*_avgMistag)) + (_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgS*sin(_dm*tval) - (_tag*(1-2*_avgMistag) + _mu*(1. - _tag*_delMistag))*_avgC*cos(_dm*tval); diff --git a/roofit/roofit/src/RooBDecay.cxx b/roofit/roofit/src/RooBDecay.cxx index 200214da3d28e..6652e544403dd 100644 --- a/roofit/roofit/src/RooBDecay.cxx +++ b/roofit/roofit/src/RooBDecay.cxx @@ -21,7 +21,7 @@ Most general description of B decay time distribution with effects of CP violation, mixing and life time differences. This function can -be analytically convolved with any RooResolutionModel implementation +be analytically convolved with any RooResolutionModel implementation. **/ #include "Riostream.h" @@ -36,7 +36,22 @@ using namespace std; ClassImp(RooBDecay); -//////////////////////////////////////////////////////////////////////////////// +/// \brief Constructor for RooBDecay. +/// +/// Creates an instance of RooBDecay with the specified parameters. +/// +/// \param[in] name The name of the PDF. +/// \param[in] title The title of the PDF. +/// \param[in] t The time variable. +/// \param[in] tau The average decay time parameter. +/// \param[in] dgamma The Delta Gamma parameter. +/// \param[in] f0 The Cosh Coefficient. +/// \param[in] f1 The Sinh Coefficient. +/// \param[in] f2 The Cos Coefficient. +/// \param[in] f3 The Sin Coefficient. +/// \param[in] dm The Delta Mass parameter. +/// \param[in] model The resolution model. +/// \param[in] type The decay type. RooBDecay::RooBDecay(const char *name, const char* title, RooRealVar& t, RooAbsReal& tau, RooAbsReal& dgamma, @@ -99,13 +114,6 @@ RooBDecay::RooBDecay(const RooBDecay& other, const char* name) : { } -//////////////////////////////////////////////////////////////////////////////// -///Destructor - -RooBDecay::~RooBDecay() -{ -} - //////////////////////////////////////////////////////////////////////////////// double RooBDecay::coefficient(Int_t basisIndex) const @@ -132,7 +140,7 @@ double RooBDecay::coefficient(Int_t basisIndex) const //////////////////////////////////////////////////////////////////////////////// -RooArgSet* RooBDecay::coefVars(Int_t basisIndex) const +RooFit::OwningPtr RooBDecay::coefVars(Int_t basisIndex) const { if(basisIndex == _basisCosh) { @@ -151,7 +159,7 @@ RooArgSet* RooBDecay::coefVars(Int_t basisIndex) const return _f3.arg().getVariables(); } - return 0 ; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -216,14 +224,14 @@ void RooBDecay::generateEvent(Int_t code) { R__ASSERT(code==1); double gammamin = 1/_tau-TMath::Abs(_dgamma)/2; - while(1) { + while(true) { double t = -log(RooRandom::uniform())/gammamin; if (_type == Flipped || (_type == DoubleSided && RooRandom::uniform() <0.5) ) t *= -1; if ( t<_t.min() || t>_t.max() ) continue; double dgt = _dgamma*t/2; double dmt = _dm*t; - double ft = fabs(t); + double ft = std::abs(t); double f = exp(-ft/_tau)*(_f0*cosh(dgt)+_f1*sinh(dgt)+_f2*cos(dmt)+_f3*sin(dmt)); if(f < 0) { cout << "RooBDecay::generateEvent(" << GetName() << ") ERROR: PDF value less than zero" << endl; diff --git a/roofit/roofit/src/RooBMixDecay.cxx b/roofit/roofit/src/RooBMixDecay.cxx index 419586b276608..946e625e6b73a 100644 --- a/roofit/roofit/src/RooBMixDecay.cxx +++ b/roofit/roofit/src/RooBMixDecay.cxx @@ -28,13 +28,27 @@ This function can be analytically convolved with any RooResolutionModel implemen #include "RooBMixDecay.h" #include "RooRealIntegral.h" #include "RooRandom.h" +#include "RooBatchCompute.h" using namespace std; ClassImp(RooBMixDecay); -//////////////////////////////////////////////////////////////////////////////// -/// Constructor +/// \brief Constructor for RooBMixDecay. +/// +/// Creates an instance of RooBMixDecay with the specified parameters. +/// +/// \param[in] name The name of the PDF. +/// \param[in] title The title of the PDF. +/// \param[in] t The time variable. +/// \param[in] mixState The mixing state category. +/// \param[in] tagFlav The flavour of tagged B0 category. +/// \param[in] tau The mixing life time parameter. +/// \param[in] dm The mixing frequency parameter. +/// \param[in] mistag The mistag rate parameter. +/// \param[in] delMistag The delta mistag rate parameter. +/// \param[in] model The resolution model. +/// \param[in] type The decay type. RooBMixDecay::RooBMixDecay(const char *name, const char *title, RooRealVar& t, RooAbsCategory& mixState, @@ -91,13 +105,6 @@ RooBMixDecay::RooBMixDecay(const RooBMixDecay& other, const char* name) : { } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooBMixDecay::~RooBMixDecay() -{ -} - //////////////////////////////////////////////////////////////////////////////// /// Comp with tFit MC: must be (1 - tagFlav*...) @@ -114,6 +121,13 @@ double RooBMixDecay::coefficient(Int_t basisIndex) const return 0 ; } +void RooBMixDecay::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const +{ + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::BMixDecay, output, nEvents, + {dataMap.at(&_convSet[0]), dataMap.at(&_convSet[1]), dataMap.at(_tagFlav), + dataMap.at(_delMistag), dataMap.at(_mixState), dataMap.at(_mistag)}); +} + //////////////////////////////////////////////////////////////////////////////// /// cout << "RooBMixDecay::getCoefAI " ; allVars.Print("1") ; @@ -263,7 +277,7 @@ void RooBMixDecay::generateEvent(Int_t code) } // Generate delta-t dependent - while(1) { + while(true) { double rand = RooRandom::uniform() ; double tval(0) ; diff --git a/roofit/roofit/src/RooBSpline.cxx b/roofit/roofit/src/RooBSpline.cxx new file mode 100644 index 0000000000000..ec2103f11547b --- /dev/null +++ b/roofit/roofit/src/RooBSpline.cxx @@ -0,0 +1,446 @@ +/************************************************************************* + * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +//_________________________________________________ +// + +#include "RooFit.h" + +#include "Riostream.h" +#include "Riostream.h" +#include +#include +#include "TMath.h" + +#include "RooAbsReal.h" +#include "RooRealVar.h" +#include "RooArgList.h" +#include "RooMsgService.h" +#include "TMath.h" + +#include "RooBSpline.h" +#include "RooBSplineBases.h" + +using namespace std ; + +ClassImp(RooBSpline) + +//using namespace RooStats; +//using namespace HistFactory; + +//_____________________________________________________________________________ +RooBSpline::RooBSpline() +{ + // Default constructor +// _t_ary=NULL; +} + + +//_____________________________________________________________________________ +RooBSpline::RooBSpline(const char* name, const char* title, + const RooArgList& controlPoints, RooBSplineBases& bases, const RooArgSet& vars) : + RooAbsReal(name, title), + _controlPoints("controlPoints","List of control points",this), + _m(bases.getTValues().size()+2*bases.getOrder()), +// _t_ary(NULL), +// _t("t_param", "t_param", this, *t), + _n(bases.getOrder()), + _weights("weights","List of weights",this), + _bases("bases","Basis polynomials",this,bases), + _vars("observables","List of observables",this), + _cacheMgr(this,10) +{ + //cout << "in Ctor" << endl; + //cout << "t = " << t << endl; + + if (_m-2*_n != controlPoints.getSize()) + { + cout << "ERROR::Nr t values (" << _m-2*_n << ") != nr control points (" << controlPoints.getSize() << ")" << endl; + } + + //bool even = fabs(_n/2-_n/2.) < 0.0000000001; + bool first=1; + TIterator* pointIter = controlPoints.createIterator() ; + RooAbsArg* point ; + RooAbsArg* lastPoint=NULL ; + while((point = (RooAbsArg*)pointIter->Next())) { + if (!dynamic_cast(point)) { + coutE(InputArguments) << "RooBSpline::ctor(" << GetName() << ") ERROR: control point " << point->GetName() + << " is not of type RooAbsReal" << endl ; + assert(0) ; + } + //RooAbsReal* pointReal = (RooAbsReal*)point; + //cout << "Adding control point " << point->GetName() << ", has val " << pointReal->getVal() << endl; + _controlPoints.add(*point) ; + if (first) + { + for (int i=0;i<(_n)/2;i++) + { + _controlPoints.add(*point) ; + } + } + first=false; + lastPoint=point; + } + for (int i=0;i<(_n)/2;i++) _controlPoints.add(*lastPoint); + delete pointIter ; + + + TIterator* varItr = vars.createIterator(); + RooAbsArg* arg; + while ((arg=(RooAbsArg*)varItr->Next())) { + //cout << "======== Adding "<GetName()<<" to list of _vars of "<getVal(); // build the basis polynomials + bool useWeight = _weights.getSize(); + double S = 0; + //bool even = fabs(_n/2-_n/2.) < 0.0000000001; + for (int i=0;i<_m-_n-1;i++) + { + //if (even && i <_m-_n-2) p=_n-1; + double basis = bases->getBasisVal(_n,i,false); + if (basis > 0) + { + int p=i; + //if (even && i > 0) p=i-1; + RooAbsReal* point = (RooAbsReal*)_controlPoints.at(p); + //cout << "name=" << GetName() << ", point addy=" << point << endl; + double weight = 1.0; + if (useWeight) + { + RooAbsReal* weightVar = (RooAbsReal*)_weights.at(p); + weight = weightVar->getVal(); + } + S += basis * point->getVal() * weight; + } + } + + //cout << "Out RooBSpline::evaluate()" << endl; + return S; +} + + + +void RooBSpline::setWeights(const RooArgList& weights) +{ + _weights.removeAll(); + bool first=1; + TIterator* pointIter = weights.createIterator() ; + RooAbsArg* point ; + RooAbsArg* lastPoint=NULL ; + while((point = (RooAbsArg*)pointIter->Next())) { + if (!dynamic_cast(point)) { + coutE(InputArguments) << "RooBSpline::ctor(" << GetName() << ") ERROR: control point " << point->GetName() + << " is not of type RooAbsReal" << endl ; + assert(0) ; + } + _weights.add(*point) ; + if (first) + { + for (int i=0;i<_n/2;i++) + { + _weights.add(*point) ; + } + } + first=false; + lastPoint=point; + } + for (int i=0;i<(_n+1)/2;i++) _weights.add(*lastPoint); + delete pointIter; +} + + + + +//_____________________________________________________________________________ +Bool_t RooBSpline::setBinIntegrator(RooArgSet& allVars) +{ + //cout << "In RooBSpline::setBinIntegrator" << endl; + if(allVars.getSize()==1){ + RooAbsReal* temp = const_cast(this); + temp->specialIntegratorConfig(kTRUE)->method1D().setLabel("RooBinIntegrator") ; + int nbins = ((RooRealVar*) allVars.first())->numBins(); + temp->specialIntegratorConfig(kTRUE)->getConfigSection("RooBinIntegrator").setRealValue("numBins",nbins); + return true; + }else{ + cout << "Currently BinIntegrator only knows how to deal with 1-d "<_I.addOwned( *point->createIntegral(analVars,rangeName) ); + } + } + + Int_t code = _cacheMgr.setObj(&analVars,&analVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)); + return 2+code; + } + + return 0; +} + + +//_____________________________________________________________________________ +Double_t RooBSpline::analyticalIntegralWN(Int_t code, const RooArgSet* /*normSet*/,const char* rangeName) const +{ + //cout << "In RooBSpline::analyticalIntegralWN" << endl; + double integral = 0; + if (code == 1) + { + return getVal(); + } + else if (code >= 2) + { +// RooRealVar* obs = (RooRealVar*)_vars.first(); +// int nrBins = obs->getBins(); +// int initValue=obs->getBin(); +// +// for (int ibin=0;ibinsetBin(ibin); +// integral+=getVal(); +// } +// +// obs->setBin(initValue); + + + +// +// // From RooAddition: +// // check if we already have integrals for this combination of factors +// +// // we always do things ourselves -- actually, always delegate further down the line ;-) +// RooArgSet analVars( _vars ); +// analVars.add(*normSet); +// +// Int_t sterileIndex(-1); +// CacheElem* cache = (CacheElem*) _cacheMgr.getObj(&analVars,&analVars,&sterileIndex,RooNameReg::ptr(rangeName)); +// if (cache==0) { +// // we don't, so we make it right here.... +// cache = new CacheElem; +// for (int i=0;i<_m-_n-1;i++) { +// RooAbsReal* point = (RooAbsReal*)_controlPoints.at(i); +// cache->_I.addOwned( *point->createIntegral(_vars,*normSet) ); +// } +// } +// + + + // Calculate integral internally from appropriate integral cache + + // note: rangeName implicit encoded in code: see _cacheMgr.setObj in getPartIntList... + CacheElem *cache = (CacheElem*) _cacheMgr.getObjByIndex(code-2); + if (cache==0) { + // cache got sterilized, trigger repopulation of this slot, then try again... + //cout << "Cache got sterilized" << endl; + std::unique_ptr vars( getParameters(RooArgSet()) ); + RooArgSet dummy; +#if ROOT_VERSION_CODE >= ROOT_VERSION(6,25,0) + auto iset( _cacheMgr.selectFromSet2(*vars,code-2) ); + Int_t code2 = getAnalyticalIntegral(iset,dummy,rangeName); +#else + std::unique_ptr iset( _cacheMgr.nameSet2ByIndex(code-2)->select(*vars) ); + Int_t code2 = getAnalyticalIntegral(*iset,dummy,rangeName); +#endif + assert(code==code2); // must have revived the right (sterilized) slot... + return analyticalIntegral(code2,rangeName); + } + assert(cache!=0); + + + + + RooBSplineBases* bases = (RooBSplineBases*)&_bases.arg(); + bases->getVal(); // build the basis polynomials + bool useWeight = _weights.getSize(); + double S = 0; + //bool even = fabs(_n/2-_n/2.) < 0.0000000001; + for (int i=0;i<_m-_n-1;i++) + { + //if (even && i <_m-_n-2) p=_n-1; + double basis = bases->getBasisVal(_n,i,false); + if (basis > 0) + { + int p=i; + //if (even && i > 0) p=i-1; + //RooAbsReal* point = (RooAbsReal*)_controlPoints.at(p); + //cout << "name=" << GetName() << endl; + double weight = 1.0; + if (useWeight) + { + RooAbsReal* weightVar = (RooAbsReal*)_weights.at(p); + weight = weightVar->getVal(); + } + + + RooAbsReal* intReal = (RooAbsReal*)cache->_I.at(p); //point->createIntegral(_vars,*normSet); + S += basis * intReal->getVal() * weight; + //cout << "adding "<getVal()<<" to integral" << endl; + //delete intReal; + } + } + + integral = S; + } + //cout << "Spline " << GetName() << " has integral " << integral << " obtained with code "<< code << endl; + return integral; +} + +// //_____________________________________________________________________________ +// RooBSplinePenalty* RooBSpline::getRealPenalty(int k, RooRealVar* obs,RooRealVar* beta,const char* name) const +// { +// if (name == "") +// { +// stringstream nameStr; +// nameStr << GetName() << "_penalty"; +// name = nameStr.str().c_str(); +// } + +// RooArgList controlPoints; +// for (int i=_n/2;i<_controlPoints.getSize()-(_n+1)/2;i++) +// { +// //cout << "adding point with val " << ((RooAbsReal*)_controlPoints.at(i))->getVal() << endl; +// controlPoints.add(*_controlPoints.at(i)); +// } + +// vector tValues; +// for (int i=_n;i<_m-_n;i++) +// { +// tValues.push_back(_t_ary[i]); +// } + +// RooBSplinePenalty* pen = new RooBSplinePenalty(name, name, _n, tValues, controlPoints, k, obs, beta); + +// int nrWeights = _weights.getSize(); +// if (nrWeights > 0) +// { +// RooArgSet weights; +// int counter = 0; +// for (int i=_n/2;isetWeights(weights); +// } + +// return pen; +// } + + + + + + +//_____________________________________________________________________________ +RooArgList RooBSpline::CacheElem::containedArgs(Action) +{ + // Return list of all RooAbsArgs in cache element + RooArgList ret(_I) ; + return ret ; +} + +RooBSpline::CacheElem::~CacheElem() +{ + // Destructor +} diff --git a/roofit/roofit/src/RooBSplineBases.cxx b/roofit/roofit/src/RooBSplineBases.cxx new file mode 100644 index 0000000000000..fcb8ef6a226b0 --- /dev/null +++ b/roofit/roofit/src/RooBSplineBases.cxx @@ -0,0 +1,421 @@ +/************************************************************************* + * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include "RooFit.h" + +#include "Riostream.h" +#include "Riostream.h" +#include +#include "TMath.h" + +#include "RooAbsReal.h" +#include "RooRealVar.h" +#include "RooArgList.h" +#include "RooMsgService.h" +#include "TMath.h" + +#include "RooBSplineBases.h" + +using namespace std ; + +ClassImp(RooBSplineBases) + +//using namespace RooStats; +//using namespace HistFactory; + +//_____________________________________________________________________________ +RooBSplineBases::RooBSplineBases() +{ + // Default constructor +// _t_ary=NULL; +// _bin=NULL; +} + + +//_____________________________________________________________________________ +RooBSplineBases::RooBSplineBases(const char* name, const char* title, int order, vector& tValues, + RooAbsReal& t, int nrClose) : + RooAbsReal(name, title), + _tValues(tValues), + _m(tValues.size()+2*order), + //_t_ary(NULL), + _t("t_param", "t_param", this, t), + _n(order), + _nrClose(nrClose) + //_nPlusOne(order+1)//, + //_bin(NULL) +{ + //cout << "in Ctor" << endl; + //cout << "t = " << t << endl; + buildTAry(); + +// _bin=new double*[_n+1]; +// for (int n=0;n<_n+1;n++) +// { +// _bin[n] = new double[_m]; +// for (int i=0;i<_m;i++) +// { +// _bin[n][i] = 0; +// } +// } + +// _t_ary = new double[_m]; +// for (int i=_n;i<_m-_n;i++) // add the main knots +// { +// _t_ary[i] = tValues[i-_n]; +// //cout << "Adding main point: " << i << " = " << _t_ary[i] << endl; +// } + +// double firstDelta=_t_ary[_n+1]-_t_ary[_n]; // extrapolate to the lower non-closed knots +// for (int i=nrClose;i<_n;i++) +// { +// _t_ary[i] = _t_ary[_n]+firstDelta*(i-_n); +// //cout << "Adding lower open: " << i << " = " << _t_ary[i] << endl; +// } + +// for (int i=0;i _t_ary[_m-_n-1]) + { + if (t > _t_ary[_m-_n-1]) t = _t_ary[_m-_n-1]; + if (t < _t_ary[_n]) t = _t_ary[_n]; + } + + + + +//build the basis splines + +// if (_bin) +// { +// //cout << "Deleting bin: " << _bin << endl; +// for (int i=0;i<_n+1;i++) +// { +// //cout << "Deleting bin[" << i << "]: " << _bin[i] << endl; +// delete[] _bin[i]; +// _bin[i]=NULL; +// // for (int j=0;j<_m;j++) +// // { +// // _bin[i][j]=0; +// // } +// } +// delete[] _bin; +// _bin=NULL; +// } + +// bool remake=(_bin==NULL); +// if (remake) _bin = new double*[_n+1]; + +// if (!_bin) +// { +// _bin=new double*[_n+1]; +// for (int n=0;n<_n+1;n++) +// { +// _bin[n] = new double[_m]; +// } +// } + //_bin = new double*[_n+1]; + for (int n=0;n<_n+1;n++) + { + //cout << "_bin[n] = " << _bin[n] << endl; + //if (remake) _bin[n] = new double[_m]; + //_bin[n] = new double[_m]; + for (int i=0;i<_m;i++) + { + //cout << "Resetting to zero" << endl; + _bin[n][i] = 0; + } + for (int i=0;i<_m-n-1;i++) + { + if (n == 0) + { + if (t >= _t_ary[i] && t < _t_ary[i+1] && i >= _n && i <= _m-_n-1) + { + //cout << "Setting " << i << " to 1" << endl; + _bin[n][i] = 1; + } + } + else + { + //cout << "Getting term1" << endl; + double term1 = 0; + if (_t_ary[i+n] - _t_ary[i] > 0.000000000001) term1 = _bin[n-1][i] / (_t_ary[i+n] - _t_ary[i]); + + //cout << "Getting term2" << endl; + double term2 = 0; + if (_t_ary[i+n+1] - _t_ary[i+1] > 0.0000000000001) term2 = _bin[n-1][i+1] / (_t_ary[i+n+1] - _t_ary[i+1]); + + //cout << "Setting bin" << endl; + _bin[n][i] = (t - _t_ary[i]) * term1 + (_t_ary[i+n+1] - t) * term2; + } + if (_bin[n][i] < 0.000000000001) _bin[n][i] = 0; + } + } + //cout << "Out RooBSplineBases::evaluate()" << endl; + return t; +} + +Double_t RooBSplineBases::getBasisVal(int n, int i, bool rebuild) const +{ + if (rebuild) getVal(); +// if (rebuild || !_bin) getVal(); +// if (!_bin) +// { +// getVal(); +// } + if (i >= _m-_n-1) return 0.; + //cout << "Getting basis for n=" << n << ", i=" << i << ", rebuild ? " << rebuild << ", order = " << _n << ", name=" << GetName() << endl; + return _bin[n][i]; +} + + + +//_____________________________________________________________________________ +#if ROOT_VERSION_CODE >= ROOT_VERSION(6,29,0) + +#include +#include +#include +#include + +using namespace RooFit::Detail; + +namespace { +class RooBSplineBasesStreamer : public RooFit::JSONIO::Exporter { +public: + virtual const std::string& key() const override { + static const std::string _key = "BSplineBases"; + return _key; + } + + virtual bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override + { + const RooBSplineBases *spline = static_cast(func); + elem["type"] << key(); + elem["order"] << spline->getOrder(); + elem["nrClose"] << spline->getNrClose(); + elem["t"] << spline->getT().GetName(); + elem["tValues"].fill_seq(spline->getTValues()); + return true; + } +}; +} // namespace + + +namespace { +class RooBSplineBasesFactory : public RooFit::JSONIO::Importer { +public: + virtual bool importFunction(RooJSONFactoryWSTool *tool, const JSONNode &p) const override + { + std::string name = RooJSONFactoryWSTool::name(p); + + auto& tvals = p["tValues"]; + std::vector tValues; + tValues << tvals; + + int nrClose = p["nrClose"].val_int(); + int order = p["order"].val_int(); + + RooAbsReal* t = tool->workspace()->var(p["t"].val().c_str()); + + RooBSplineBases bases(name.c_str(),name.c_str(),order,tValues,*t,nrClose); + tool->workspace()->import(bases); + + return true; + } +}; +} // namespace + + +namespace { + int register_serializations(){ + RooFit::JSONIO::registerImporter("BSplineBases", std::make_unique()); + RooFit::JSONIO::registerExporter(RooBSplineBases::Class(), std::make_unique()); + return 1; + } + int _dummy = register_serializations(); +} + +#endif diff --git a/roofit/roofit/src/RooBernstein.cxx b/roofit/roofit/src/RooBernstein.cxx index 3ddac0e7ddb9c..5410d4ed56d2c 100644 --- a/roofit/roofit/src/RooBernstein.cxx +++ b/roofit/roofit/src/RooBernstein.cxx @@ -129,7 +129,7 @@ double RooBernstein::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Bernstein distribution. -void RooBernstein::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooBernstein::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { const int nCoef = _coefList.size(); std::vector extraArgs(nCoef+2); @@ -138,8 +138,7 @@ void RooBernstein::computeBatch(cudaStream_t* stream, double* output, size_t nEv extraArgs[nCoef] = _x.min(); extraArgs[nCoef+1] = _x.max(); - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Bernstein, output, nEvents, {dataMap.at(_x)}, extraArgs); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Bernstein, output, nEvents, {dataMap.at(_x)}, extraArgs); } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofit/src/RooBifurGauss.cxx b/roofit/roofit/src/RooBifurGauss.cxx index d69ce464d62b6..a1ac34e589725 100644 --- a/roofit/roofit/src/RooBifurGauss.cxx +++ b/roofit/roofit/src/RooBifurGauss.cxx @@ -78,10 +78,9 @@ double RooBifurGauss::evaluate() const { //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of BifurGauss distribution. -void RooBifurGauss::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooBifurGauss::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::BifurGauss, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::BifurGauss, output, nEvents, {dataMap.at(x),dataMap.at(mean),dataMap.at(sigmaL),dataMap.at(sigmaR)}); } diff --git a/roofit/roofit/src/RooBreitWigner.cxx b/roofit/roofit/src/RooBreitWigner.cxx index 78ae4426fa4a9..bcbc398ebdb93 100644 --- a/roofit/roofit/src/RooBreitWigner.cxx +++ b/roofit/roofit/src/RooBreitWigner.cxx @@ -23,7 +23,7 @@ that models a non-relativistic Breit-Wigner shape **/ #include "Riostream.h" -#include +#include #include "RooBreitWigner.h" #include "RooRealVar.h" @@ -63,10 +63,9 @@ double RooBreitWigner::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of BreitWigner distribution. -void RooBreitWigner::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooBreitWigner::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::BreitWigner, output, nEvents, {dataMap.at(x), dataMap.at(mean), dataMap.at(width)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::BreitWigner, output, nEvents, {dataMap.at(x), dataMap.at(mean), dataMap.at(width)}); } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofit/src/RooBukinPdf.cxx b/roofit/roofit/src/RooBukinPdf.cxx index bcc50460aa96b..9639be9f997ff 100644 --- a/roofit/roofit/src/RooBukinPdf.cxx +++ b/roofit/roofit/src/RooBukinPdf.cxx @@ -96,7 +96,7 @@ double RooBukinPdf::evaluate() const r4=sqrt(xi*xi+1); r1=xi/r4; - if(fabs(xi) > exp(-6.)){ + if(std::abs(xi) > exp(-6.)){ r5=xi/log(r4+xi); } else @@ -113,7 +113,7 @@ double RooBukinPdf::evaluate() const //--- Center else if(x < x2) { - if(fabs(xi) > exp(-6.)) { + if(std::abs(xi) > exp(-6.)) { r2=log(1 + 4 * xi * r4 * (x-Xp)/hp)/log(1+2*xi*(xi-r4)); r2=-r3*r2*r2; } @@ -128,7 +128,7 @@ double RooBukinPdf::evaluate() const r2=rho2*(x-x2)*(x-x2)/(Xp-x2)/(Xp-x2)-r3 - 4 * r3 * (x-x2)/hp * r5 * r4/(r4+xi)/(r4+xi); } - if(fabs(r2) > 100){ + if(std::abs(r2) > 100){ fit_result = 0; } else{ @@ -141,9 +141,8 @@ double RooBukinPdf::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Bukin distribution. -void RooBukinPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooBukinPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Bukin, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Bukin, output, nEvents, {dataMap.at(x), dataMap.at(Xp), dataMap.at(sigp), dataMap.at(xi), dataMap.at(rho1), dataMap.at(rho2)}); } diff --git a/roofit/roofit/src/RooCBShape.cxx b/roofit/roofit/src/RooCBShape.cxx index 342c3e196aeae..88df885facb07 100644 --- a/roofit/roofit/src/RooCBShape.cxx +++ b/roofit/roofit/src/RooCBShape.cxx @@ -76,7 +76,7 @@ double RooCBShape::evaluate() const { double t = (m-m0)/sigma; if (alpha < 0) t = -t; - double absAlpha = fabs((double)alpha); + double absAlpha = std::abs((double)alpha); if (t >= -absAlpha) { return exp(-0.5*t*t); @@ -91,11 +91,10 @@ double RooCBShape::evaluate() const { //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Crystal ball Shape distribution. -void RooCBShape::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooCBShape::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::CBShape, output, nEvents, - {dataMap.at(m), dataMap.at(m0), dataMap.at(sigma), dataMap.at(alpha), dataMap.at(n)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::CBShape, output, nEvents, + {dataMap.at(m), dataMap.at(m0), dataMap.at(sigma), dataMap.at(alpha), dataMap.at(n)}); } //////////////////////////////////////////////////////////////////////////////// @@ -119,10 +118,10 @@ double RooCBShape::analyticalIntegral(Int_t code, const char* rangeName) const double result = 0.0; bool useLog = false; - if( fabs(n-1.0) < 1.0e-05 ) + if( std::abs(n-1.0) < 1.0e-05 ) useLog = true; - double sig = fabs((double)sigma); + double sig = std::abs((double)sigma); double tmin = (m.min(rangeName)-m0)/sig; double tmax = (m.max(rangeName)-m0)/sig; @@ -133,7 +132,7 @@ double RooCBShape::analyticalIntegral(Int_t code, const char* rangeName) const tmax = -tmp; } - double absAlpha = fabs((double)alpha); + double absAlpha = std::abs((double)alpha); if( tmin >= -absAlpha ) { result += sig*sqrtPiOver2*( ApproxErf(tmax/sqrt2) diff --git a/roofit/roofit/src/RooChebychev.cxx b/roofit/roofit/src/RooChebychev.cxx index 1baffc60b6126..df3cee08b8a54 100644 --- a/roofit/roofit/src/RooChebychev.cxx +++ b/roofit/roofit/src/RooChebychev.cxx @@ -29,84 +29,16 @@ starts with the coefficient that goes with \f$ T_1(x)=x \f$ (i.e. the linear ter #include "RooNameReg.h" #include "RooBatchCompute.h" +#include +#include + #include ClassImp(RooChebychev); -namespace { // anonymous namespace to hide implementation details -/// use fast FMA if available, fall back to normal arithmetic if not -static inline double fast_fma( - const double x, const double y, const double z) noexcept -{ -#if defined(FP_FAST_FMA) // check if std::fma has fast hardware implementation - return std::fma(x, y, z); -#else // defined(FP_FAST_FMA) - // std::fma might be slow, so use a more pedestrian implementation -#if defined(__clang__) -#pragma STDC FP_CONTRACT ON // hint clang that using an FMA is okay here -#endif // defined(__clang__) - return (x * y) + z; -#endif // defined(FP_FAST_FMA) -} - -/// Chebychev polynomials of first or second kind -enum class Kind : int { First = 1, Second = 2 }; - -/** @brief ChebychevIterator evaluates increasing orders at given x - * - * @author Manuel Schiller - * @date 2019-03-24 - */ -template -class ChebychevIterator { -private: - T _last = 1; - T _curr = 0; - T _twox = 0; - -public: - /// default constructor - constexpr ChebychevIterator() = default; - /// copy constructor - ChebychevIterator(const ChebychevIterator &) = default; - /// move constructor - ChebychevIterator(ChebychevIterator &&) = default; - /// construct from given x in [-1, 1] - constexpr ChebychevIterator(const T &x) - : _curr(static_cast(KIND) * x), _twox(2 * x) - {} - - /// (copy) assignment - ChebychevIterator &operator=(const ChebychevIterator &) = default; - /// move assignment - ChebychevIterator &operator=(ChebychevIterator &&) = default; - - /// get value of Chebychev polynomial at current order - constexpr inline T operator*() const noexcept { return _last; } - // get value of Chebychev polynomial at (current + 1) order - constexpr inline T lookahead() const noexcept { return _curr; } - /// move on to next order, return reference to new value - inline ChebychevIterator &operator++() noexcept - { - //T newval = fast_fma(_twox, _curr, -_last); - T newval = _twox*_curr -_last; - _last = _curr; - _curr = newval; - return *this; - } - /// move on to next order, return copy of new value - inline ChebychevIterator operator++(int) noexcept - { - ChebychevIterator retVal(*this); - operator++(); - return retVal; - } -}; -} // anonymous namespace - //////////////////////////////////////////////////////////////////////////////// -RooChebychev::RooChebychev() : _refRangeName(0) +RooChebychev::RooChebychev() : _refRangeName(nullptr) { } @@ -118,7 +50,7 @@ RooChebychev::RooChebychev(const char* name, const char* title, RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefficients","List of coefficients",this), - _refRangeName(0) + _refRangeName(nullptr) { for (const auto coef : coefList) { if (!dynamic_cast(coef)) { @@ -149,7 +81,7 @@ void RooChebychev::selectNormalizationRange(const char* rangeName, bool force) _refRangeName = (TNamed*) RooNameReg::instance().constPtr(rangeName) ; } if (!rangeName) { - _refRangeName = 0 ; + _refRangeName = nullptr ; } } @@ -160,37 +92,37 @@ double RooChebychev::evaluate() const // first bring the range of the variable _x to the normalised range [-1, 1] // calculate sum_k c_k T_k(x) where x is given in the normalised range, // c_0 = 1, and the higher coefficients are given in _coefList - const double xmax = _x.max(_refRangeName?_refRangeName->GetName():0); - const double xmin = _x.min(_refRangeName?_refRangeName->GetName():0); - // transform to range [-1, +1] - const double x = (_x - 0.5 * (xmax + xmin)) / (0.5 * (xmax - xmin)); - // extract current values of coefficients - using size_type = typename RooListProxy::Storage_t::size_type; - const size_type iend = _coefList.size(); - double sum = 1.; - if (iend > 0) { - ChebychevIterator chit(x); - ++chit; - for (size_type i = 0; iend != i; ++i, ++chit) { - auto c = static_cast(_coefList[i]).getVal(); - //sum = fast_fma(*chit, c, sum); - sum += *chit*c; - } - } - return sum; + double xmax = _x.max(_refRangeName ? _refRangeName->GetName() : nullptr); + double xmin = _x.min(_refRangeName ? _refRangeName->GetName() : nullptr); + + std::vector coeffs; + for (auto it : _coefList) + coeffs.push_back(static_cast(*it).getVal()); + return RooFit::Detail::EvaluateFuncs::chebychevEvaluate(coeffs.data(), _coefList.size(), _x, xmin, xmax); +} + +void RooChebychev::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // first bring the range of the variable _x to the normalised range [-1, 1] + // calculate sum_k c_k T_k(x) where x is given in the normalised range, + // c_0 = 1, and the higher coefficients are given in _coefList + double xmax = _x.max(_refRangeName ? _refRangeName->GetName() : nullptr); + double xmin = _x.min(_refRangeName ? _refRangeName->GetName() : nullptr); + + ctx.addResult(this, + ctx.buildCall("RooFit::Detail::EvaluateFuncs::chebychevEvaluate", _coefList, _coefList.size(), _x, xmin, xmax)); } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Chebychev. -void RooChebychev::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooChebychev::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { RooBatchCompute::ArgVector extraArgs; for (auto* coef:_coefList) extraArgs.push_back( static_cast(coef)->getVal() ); extraArgs.push_back( _x.min(_refRangeName?_refRangeName->GetName() : nullptr) ); extraArgs.push_back( _x.max(_refRangeName?_refRangeName->GetName() : nullptr) ); - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Chebychev, output, nEvents, {dataMap.at(_x)}, extraArgs); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Chebychev, output, nEvents, {dataMap.at(_x)}, extraArgs); } //////////////////////////////////////////////////////////////////////////////// @@ -208,49 +140,27 @@ double RooChebychev::analyticalIntegral(Int_t code, const char* rangeName) const { assert(1 == code); (void)code; - const double xmax = _x.max(_refRangeName?_refRangeName->GetName():0); - const double xmin = _x.min(_refRangeName?_refRangeName->GetName():0); - const double halfrange = .5 * (xmax - xmin), mid = .5 * (xmax + xmin); - // the full range of the function is mapped to the normalised [-1, 1] range - const double b = (_x.max(rangeName) - mid) / halfrange; - const double a = (_x.min(rangeName) - mid) / halfrange; + double xmax = _x.max(_refRangeName ? _refRangeName->GetName() : nullptr); + double xmaxFull = _x.max(rangeName); + double xmin = _x.min(_refRangeName ? _refRangeName->GetName() : nullptr); + double xminFull = _x.min(rangeName); + unsigned int sz = _coefList.size(); - // take care to multiply with the right factor to account for the mapping to - // normalised range [-1, 1] - return halfrange * evalAnaInt(a, b); -} + std::vector coeffs; + for (auto it : _coefList) + coeffs.push_back(static_cast(*it).getVal()); -//////////////////////////////////////////////////////////////////////////////// + return RooFit::Detail::AnalyticalIntegrals::chebychevIntegral(coeffs.data(), sz, xmin, xmax, xminFull, xmaxFull); +} -double RooChebychev::evalAnaInt(const double a, const double b) const +std::string RooChebychev::buildCallToAnalyticIntegral(Int_t /* code */, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const { - // coefficient for integral(T_0(x)) is 1 (implicit), integrate by hand - // T_0(x) and T_1(x), and use for n > 1: integral(T_n(x) dx) = - // (T_n+1(x) / (n + 1) - T_n-1(x) / (n - 1)) / 2 - double sum = b - a; // integrate T_0(x) by hand + double xmax = _x.max(_refRangeName ? _refRangeName->GetName() : nullptr); + double xmaxFull = _x.max(rangeName); + double xmin = _x.min(_refRangeName ? _refRangeName->GetName() : nullptr); + double xminFull = _x.min(rangeName); + unsigned int sz = _coefList.size(); - using size_type = typename RooListProxy::Storage_t::size_type; - const size_type iend = _coefList.size(); - if (iend > 0) { - { - // integrate T_1(x) by hand... - const double c = static_cast(_coefList[0]).getVal(); - sum = fast_fma(0.5 * (b + a) * (b - a), c, sum); - } - if (1 < iend) { - ChebychevIterator bit(b), ait(a); - ++bit, ++ait; - double nminus1 = 1.; - for (size_type i = 1; iend != i; ++i) { - // integrate using recursion relation - const double c = static_cast(_coefList[i]).getVal(); - const double term2 = (*bit - *ait) / nminus1; - ++bit, ++ait, ++nminus1; - const double term1 = (bit.lookahead() - ait.lookahead()) / (nminus1 + 1.); - const double intTn = 0.5 * (term1 - term2); - sum = fast_fma(intTn, c, sum); - } - } - } - return sum; + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::chebychevIntegral", _coefList, sz, xmin, xmax, xminFull, xmaxFull); } diff --git a/roofit/roofit/src/RooChi2MCSModule.cxx b/roofit/roofit/src/RooChi2MCSModule.cxx index 5471d025ea442..f315d7ad1a5a8 100644 --- a/roofit/roofit/src/RooChi2MCSModule.cxx +++ b/roofit/roofit/src/RooChi2MCSModule.cxx @@ -44,7 +44,7 @@ ClassImp(RooChi2MCSModule); RooChi2MCSModule::RooChi2MCSModule() : RooAbsMCStudyModule("RooChi2MCSModule","RooChi2Module"), - _data(0), _chi2(0), _ndof(0), _chi2red(0), _prob(0) + _data(nullptr), _chi2(nullptr), _ndof(nullptr), _chi2red(nullptr), _prob(nullptr) { // Constructor of module @@ -55,7 +55,7 @@ RooChi2MCSModule::RooChi2MCSModule() : RooChi2MCSModule::RooChi2MCSModule(const RooChi2MCSModule& other) : RooAbsMCStudyModule(other), - _data(0), _chi2(0), _ndof(0), _chi2red(0), _prob(0) + _data(nullptr), _chi2(nullptr), _ndof(nullptr), _chi2red(nullptr), _prob(nullptr) { } @@ -123,16 +123,16 @@ RooDataSet* RooChi2MCSModule::finalizeRun() bool RooChi2MCSModule::processAfterFit(Int_t /*sampleNum*/) { RooAbsData* data = genSample() ; + std::unique_ptr binnedDataOwned; RooDataHist* binnedData = dynamic_cast(data) ; - bool deleteData(false) ; if (!binnedData) { - deleteData = true ; - binnedData = ((RooDataSet*)data)->binnedClone() ; + binnedDataOwned = std::unique_ptr{static_cast(data)->binnedClone()}; + binnedData = binnedDataOwned.get(); } std::unique_ptr chi2Var{fitModel()->createChi2(*binnedData,RooFit::Extended(extendedGen()),RooFit::DataError(RooAbsData::SumW2))}; - RooArgSet* floatPars = (RooArgSet*) fitParams()->selectByAttrib("Constant",false) ; + std::unique_ptr floatPars{static_cast(fitParams()->selectByAttrib("Constant",false))}; _chi2->setVal(chi2Var->getVal()) ; _ndof->setVal(binnedData->numEntries()-floatPars->getSize()-1) ; @@ -141,10 +141,5 @@ bool RooChi2MCSModule::processAfterFit(Int_t /*sampleNum*/) _data->add(RooArgSet(*_chi2,*_ndof,*_chi2red,*_prob)) ; - if (deleteData) { - delete binnedData ; - } - delete floatPars ; - return true ; } diff --git a/roofit/roofit/src/RooChiSquarePdf.cxx b/roofit/roofit/src/RooChiSquarePdf.cxx index 1bca36c14f527..1f1a61b161918 100644 --- a/roofit/roofit/src/RooChiSquarePdf.cxx +++ b/roofit/roofit/src/RooChiSquarePdf.cxx @@ -62,10 +62,10 @@ double RooChiSquarePdf::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of ChiSquare distribution. -void RooChiSquarePdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooChiSquarePdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::ChiSquare, output, nEvents, {dataMap.at(_x)}, {_ndof}); + RooBatchCompute::ArgVector extraArgs{_ndof}; + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::ChiSquare, output, nEvents, {dataMap.at(_x)}, extraArgs); } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofit/src/RooDecay.cxx b/roofit/roofit/src/RooDecay.cxx index a7bd9a9b12d15..daed83b948789 100644 --- a/roofit/roofit/src/RooDecay.cxx +++ b/roofit/roofit/src/RooDecay.cxx @@ -110,7 +110,7 @@ void RooDecay::generateEvent(Int_t code) R__ASSERT(code==1) ; // Generate delta-t dependent - while(1) { + while(true) { double rand = RooRandom::uniform() ; double tval(0) ; diff --git a/roofit/roofit/src/RooDstD0BG.cxx b/roofit/roofit/src/RooDstD0BG.cxx index 83aa5f79d4df0..a038ae680f151 100644 --- a/roofit/roofit/src/RooDstD0BG.cxx +++ b/roofit/roofit/src/RooDstD0BG.cxx @@ -32,7 +32,7 @@ D*-D0 mass difference distributions. It computes #include "RooDstD0BG.h" #include "RooRealVar.h" -#include "RooIntegrator1D.h" +#include "RooRombergIntegrator.h" #include "RooAbsFunc.h" #include "RooBatchCompute.h" @@ -79,10 +79,9 @@ double RooDstD0BG::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of D*-D0 mass difference distribution. -void RooDstD0BG::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooDstD0BG::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::DstD0BG, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::DstD0BG, output, nEvents, {dataMap.at(dm), dataMap.at(dm0), dataMap.at(C), dataMap.at(A), dataMap.at(B)}); } @@ -126,8 +125,8 @@ double RooDstD0BG::analyticalIntegral(Int_t code, const char* rangeName) const // not stable for m/c >> 1. // Do numerical integral RooArgSet vset(dm.arg(),"vset"); - RooAbsFunc *func= bindVars(vset); - RooIntegrator1D integrator(*func,min,max); + std::unique_ptr func{bindVars(vset)}; + RooRombergIntegrator integrator(*func,min,max); return integrator.integral(); } } diff --git a/roofit/roofit/src/RooExpPoly.cxx b/roofit/roofit/src/RooExpPoly.cxx index 19063c870aeb5..1977af7b29158 100644 --- a/roofit/roofit/src/RooExpPoly.cxx +++ b/roofit/roofit/src/RooExpPoly.cxx @@ -30,6 +30,7 @@ RooExpPoly::RooExpPoly(const char*, const char*, RooAbsReal&, const RooArgList&, #include #include #include +#include "RooBatchCompute.h" #include #include @@ -62,7 +63,9 @@ ClassImp(RooExpPoly); /// \f] RooExpPoly::RooExpPoly(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, int lowestOrder) - : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList", "List of coefficients", this), + : RooAbsPdf(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), _lowestOrder(lowestOrder) { // Check lowest order @@ -82,19 +85,13 @@ RooExpPoly::RooExpPoly(const char *name, const char *title, RooAbsReal &x, const } } -//////////////////////////////////////////////////////////////////////////////// - -RooExpPoly::RooExpPoly(const char *name, const char *title, RooAbsReal &x) - : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList", "List of coefficients", this), - _lowestOrder(1) -{ -} - //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooExpPoly::RooExpPoly(const RooExpPoly &other, const char *name) - : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList", this, other._coefList), + : RooAbsPdf(other, name), + _x("x", this, other._x), + _coefList("coefList", this, other._coefList), _lowestOrder(other._lowestOrder) { } @@ -135,6 +132,27 @@ double RooExpPoly::evaluateLog() const //////////////////////////////////////////////////////////////////////////////// +/// Compute multiple values of ExpPoly distribution. +void RooExpPoly::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const +{ + RooBatchCompute::VarVector vars; + vars.reserve(_coefList.size() + 1); + vars.push_back(dataMap.at(_x)); + + std::vector coefVals; + for (RooAbsArg *coef : _coefList) { + vars.push_back(dataMap.at(coef)); + } + + RooBatchCompute::ArgVector args; + args.push_back(_lowestOrder); + args.push_back(_coefList.size()); + + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::ExpPoly, output, nEvents, vars, args); +} + +//////////////////////////////////////////////////////////////////////////////// + void RooExpPoly::adjustLimits() { // Adjust the limits of all the coefficients to reflect the numeric boundaries @@ -168,7 +186,7 @@ double RooExpPoly::evaluate() const // Calculate and return value of function const double logval = this->evaluateLog(); - const double val = exp(logval); + const double val = std::exp(logval); if (std::isinf(val)) { coutE(InputArguments) << "RooExpPoly::evaluate(" << GetName() << ") ERROR: result of exponentiation is infinite! exponent was " << logval << std::endl; diff --git a/roofit/roofit/src/RooExponential.cxx b/roofit/roofit/src/RooExponential.cxx index a4eef6c6616b7..8d6411fe7db23 100644 --- a/roofit/roofit/src/RooExponential.cxx +++ b/roofit/roofit/src/RooExponential.cxx @@ -30,65 +30,123 @@ range and values of the arguments. #include "RooRealVar.h" #include "RooBatchCompute.h" +#include +#include #include -using namespace std; - ClassImp(RooExponential); //////////////////////////////////////////////////////////////////////////////// -RooExponential::RooExponential(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _c) : - RooAbsPdf(name, title), - x("x","Dependent",this,_x), - c("c","Exponent",this,_c) +RooExponential::RooExponential(const char *name, const char *title, RooAbsReal &variable, RooAbsReal &coefficient, + bool negateCoefficient) + : RooAbsPdf{name, title}, + x{"x", "Dependent", this, variable}, + c{"c", "Exponent", this, coefficient}, + _negateCoefficient{negateCoefficient} { } //////////////////////////////////////////////////////////////////////////////// -RooExponential::RooExponential(const RooExponential& other, const char* name) : - RooAbsPdf(other, name), x("x",this,other.x), c("c",this,other.c) +RooExponential::RooExponential(const RooExponential &other, const char *name) + : RooAbsPdf{other, name}, x{"x", this, other.x}, c{"c", this, other.c}, _negateCoefficient{other._negateCoefficient} { } //////////////////////////////////////////////////////////////////////////////// -double RooExponential::evaluate() const{ - return exp(c*x); +double RooExponential::evaluate() const +{ + double coef = c; + if (_negateCoefficient) { + coef = -coef; + } + return std::exp(coef * x); } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Exponential distribution. -void RooExponential::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooExponential::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const +{ + auto computer = _negateCoefficient ? RooBatchCompute::ExponentialNeg : RooBatchCompute::Exponential; + RooBatchCompute::compute(dataMap.config(this), computer, output, nEvents, {dataMap.at(x), dataMap.at(c)}); +} + +Int_t RooExponential::getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char * /*rangeName*/) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Exponential, output, nEvents, {dataMap.at(x),dataMap.at(c)}); + if (matchArgs(allVars, analVars, x)) + return 1; + if (matchArgs(allVars, analVars, c)) + return 2; + return 0; } +//////////////////////////////////////////////////////////////////////////////// -Int_t RooExponential::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const +double RooExponential::analyticalIntegral(Int_t code, const char *rangeName) const { - if (matchArgs(allVars,analVars,x)) return 1; - if (matchArgs(allVars,analVars,c)) return 2; - return 0 ; + assert(code == 1 || code == 2); + + bool isOverX = code == 1; + + double coef = c; + if (_negateCoefficient) { + coef = -coef; + } + + double constant = isOverX ? coef : x; + auto &integrand = isOverX ? x : c; + + double min = integrand.min(rangeName); + double max = integrand.max(rangeName); + + if (!isOverX && _negateCoefficient) { + std::swap(min, max); + min = -min; + max = -max; + } + + return RooFit::Detail::AnalyticalIntegrals::exponentialIntegral(min, max, constant); } //////////////////////////////////////////////////////////////////////////////// -double RooExponential::analyticalIntegral(Int_t code, const char* rangeName) const +void RooExponential::translate(RooFit::Detail::CodeSquashContext &ctx) const { - assert(code == 1 || code ==2); + // Build a call to the stateless exponential defined later. + std::string coef; + if (_negateCoefficient) { + coef += "-"; + } + coef += ctx.getResult(c); + ctx.addResult(this, "std::exp(" + coef + " * " + ctx.getResult(x) + ")"); +} + +//////////////////////////////////////////////////////////////////////////////// + +std::string RooExponential::buildCallToAnalyticIntegral(Int_t code, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + bool isOverX = code == 1; + + std::string constant; + if (_negateCoefficient && isOverX) { + constant += "-"; + } + constant += ctx.getResult(isOverX ? c : x); + + auto &integrand = isOverX ? x : c; - auto& constant = code == 1 ? c : x; - auto& integrand = code == 1 ? x : c; + double min = integrand.min(rangeName); + double max = integrand.max(rangeName); - if (constant == 0.0) { - return integrand.max(rangeName) - integrand.min(rangeName); - } + if (!isOverX && _negateCoefficient) { + std::swap(min, max); + min = -min; + max = -max; + } - return (exp(constant*integrand.max(rangeName)) - exp(constant*integrand.min(rangeName))) - / constant; + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::exponentialIntegral", min, max, constant); } diff --git a/roofit/roofit/src/RooFit/Detail/Algorithms.h b/roofit/roofit/src/RooFit/Detail/Algorithms.h new file mode 100644 index 0000000000000..cec8e1464d6bb --- /dev/null +++ b/roofit/roofit/src/RooFit/Detail/Algorithms.h @@ -0,0 +1,104 @@ +/* + * Project: RooFit + * + * Copyright (c) 2022, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_Algorithms_h +#define RooFit_Detail_Algorithms_h + +#include + +namespace RooFit { +namespace Detail { + +//_____________________________________________________________________________ +// from http://stackoverflow.com/a/5279601 +template +void cartesianProduct(std::vector> &out, std::vector> &in) +{ + struct Digits { + typename std::vector::const_iterator begin; + typename std::vector::const_iterator end; + typename std::vector::const_iterator me; + }; + + std::vector vd; + vd.reserve(in.size()); + + for (auto it = in.begin(); it != in.end(); ++it) { + Digits d = {(*it).begin(), (*it).end(), (*it).begin()}; + vd.push_back(d); + } + + while (true) { + std::vector result; + for (auto it = vd.begin(); it != vd.end(); ++it) { + result.push_back(*(it->me)); + } + out.push_back(result); + + for (auto it = vd.begin();;) { + ++(it->me); + if (it->me == it->end) { + if (it + 1 == vd.end()) { + return; + } else { + it->me = it->begin; + ++it; + } + } else { + break; + } + } + } +} + +//_____________________________________________________________________________ +// from http://stackoverflow.com/a/5097100/8747 +template +bool nextCombination(const Iterator first, Iterator k, const Iterator last) +{ + if ((first == last) || (first == k) || (last == k)) { + return false; + } + Iterator itr1 = first; + Iterator itr2 = last; + ++itr1; + if (last == itr1) { + return false; + } + itr1 = last; + --itr1; + itr1 = k; + --itr2; + while (first != itr1) { + if (*--itr1 < *itr2) { + Iterator j = k; + while (!(*itr1 < *j)) + ++j; + iter_swap(itr1, j); + ++itr1; + ++j; + itr2 = k; + rotate(itr1, j, last); + while (last != j) { + ++j; + ++itr2; + } + rotate(k, itr2, last); + return true; + } + } + rotate(first, k, last); + return false; +} + +} // namespace Detail +} // namespace RooFit + +#endif diff --git a/roofit/roofit/src/RooGExpModel.cxx b/roofit/roofit/src/RooGExpModel.cxx index 9ceef15204414..233d5fc0d9d05 100644 --- a/roofit/roofit/src/RooGExpModel.cxx +++ b/roofit/roofit/src/RooGExpModel.cxx @@ -211,7 +211,7 @@ namespace { double logErfC(double xx) { double t,z,ans; - z=fabs(xx); + z=std::abs(xx); t=1.0/(1.0+0.5*z); if(xx >= 0.0) @@ -469,10 +469,10 @@ double RooGExpModel::calcDecayConv(double sign, double tau, double sig, double r sign *= fsign ; // modified FMV,08/13/03 double cFly; - if ((sign<0)&&(fabs(tau-rtau)300) { + if (std::abs(xp/MeanTau)>300) { return 0 ; } @@ -848,7 +848,7 @@ double RooGExpModel::calcSinConvNorm(double sign, double tau, double sig, double double term2 = evalCerfInt(-fsign, rtau, fsign*umin2, fsign*umax2, c2)*fsign*sign; // WVE Handle 0/0 numeric divergence - if (fabs(tau-rtau)<1e-10 && fabs(term1+term2)<1e-10) { + if (std::abs(tau-rtau)<1e-10 && std::abs(term1+term2)<1e-10) { cout << "epsilon method" << endl ; static double epsilon = 1e-4 ; return calcSinConvNorm(sign,tau+epsilon,sig,rtau-epsilon,fsign,rangeName) ; diff --git a/roofit/roofit/src/RooGamma.cxx b/roofit/roofit/src/RooGamma.cxx index 0a36e67c9e88e..30375cb8c5f04 100644 --- a/roofit/roofit/src/RooGamma.cxx +++ b/roofit/roofit/src/RooGamma.cxx @@ -73,7 +73,7 @@ RooGamma::RooGamma(const char *name, const char *title, //////////////////////////////////////////////////////////////////////////////// RooGamma::RooGamma(const RooGamma& other, const char* name) : - RooAbsPdf(other,name), x("x",this,other.x), gamma("mean",this,other.gamma), + RooAbsPdf(other,name), x("x",this,other.x), gamma("gamma",this,other.gamma), beta("beta",this,other.beta), mu("mu",this,other.mu) { } @@ -85,13 +85,19 @@ double RooGamma::evaluate() const return TMath::GammaDist(x, gamma, mu, beta) ; } +//////////////////////////////////////////////////////////////////////////////// + +void RooGamma::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + ctx.addResult(this, ctx.buildCall("TMath::GammaDist", x, gamma, mu, beta)); +} + //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Gamma PDF. -void RooGamma::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooGamma::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Gamma, output, nEvents, - {dataMap.at(x), dataMap.at(gamma), dataMap.at(beta), dataMap.at(mu)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Gamma, output, nEvents, + {dataMap.at(x), dataMap.at(gamma), dataMap.at(beta), dataMap.at(mu)}); } //////////////////////////////////////////////////////////////////////////////// @@ -104,21 +110,64 @@ Int_t RooGamma::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, c //////////////////////////////////////////////////////////////////////////////// -double RooGamma::analyticalIntegral(Int_t code, const char* rangeName) const +double RooGamma::analyticalIntegral(Int_t /*code*/, const char *rangeName) const { - R__ASSERT(code==1) ; + // integral of the Gamma distribution via ROOT::Math + return ROOT::Math::gamma_cdf(x.max(rangeName), gamma, beta, mu) - + ROOT::Math::gamma_cdf(x.min(rangeName), gamma, beta, mu); +} + +//////////////////////////////////////////////////////////////////////////////// - //integral of the Gamma distribution via ROOT::Math - double integral = ROOT::Math::gamma_cdf(x.max(rangeName), gamma, beta, mu) - ROOT::Math::gamma_cdf(x.min(rangeName), gamma, beta, mu); - return integral ; +std::string RooGamma::buildCallToAnalyticIntegral(Int_t /*code*/, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + const std::string a = ctx.buildCall("ROOT::Math::gamma_cdf", x.max(rangeName), gamma, beta, mu); + const std::string b = ctx.buildCall("ROOT::Math::gamma_cdf", x.min(rangeName), gamma, beta, mu); + return a + " - " + b; } +namespace { + +inline double randomGamma(double gamma, double beta, double mu, double xmin, double xmax) +{ + while (true) { + + double d = gamma - 1. / 3.; + double c = 1. / TMath::Sqrt(9. * d); + double xgen = 0; + double v = 0; + + while (v <= 0.) { + xgen = RooRandom::randomGenerator()->Gaus(); + v = 1. + c * xgen; + } + v = v * v * v; + double u = RooRandom::randomGenerator()->Uniform(); + if (u < 1. - .0331 * (xgen * xgen) * (xgen * xgen)) { + double x = ((d * v) * beta + mu); + if ((x < xmax) && (x > xmin)) { + return x; + } + } + if (TMath::Log(u) < 0.5 * xgen * xgen + d * (1. - v + TMath::Log(v))) { + double x = ((d * v) * beta + mu); + if ((x < xmax) && (x > xmin)) { + return x; + } + } + } +} + +} // namespace + //////////////////////////////////////////////////////////////////////////////// -Int_t RooGamma::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool /*staticInitOK*/) const +Int_t RooGamma::getGenerator(const RooArgSet &directVars, RooArgSet &generateVars, bool /*staticInitOK*/) const { - if (matchArgs(directVars,generateVars,x)) return 1 ; - return 0 ; + if (matchArgs(directVars, generateVars, x)) + return 1; + return 0; } //////////////////////////////////////////////////////////////////////////////// @@ -130,41 +179,22 @@ Int_t RooGamma::getGenerator(const RooArgSet& directVars, RooArgSet &generateVar /// The speed of this algorithm depends on the speed of generating normal variates. /// The algorithm is limited to \f$ \gamma \geq 0 \f$ ! -void RooGamma::generateEvent(Int_t code) +void RooGamma::generateEvent(Int_t /*code*/) { - R__ASSERT(code==1) ; - - - while(1) { - - double d = 0; - double c = 0; - double xgen = 0; - double v = 0; - double u = 0; - d = gamma -1./3.; c = 1./TMath::Sqrt(9.*d); - - while(v <= 0.){ - xgen = RooRandom::randomGenerator()->Gaus(); v = 1. + c*xgen; - } - v = v*v*v; u = RooRandom::randomGenerator()->Uniform(); - if( u < 1.-.0331*(xgen*xgen)*(xgen*xgen) ) { - if ( (((d*v)* beta + mu ) < x.max()) && (((d*v)* beta + mu) > x.min()) ) { - x = ((d*v)* beta + mu) ; - break; - } - } - if( TMath::Log(u) < 0.5*xgen*xgen + d*(1.-v + TMath::Log(v)) ) { - if ( (((d*v)* beta + mu ) < x.max()) && (((d*v)* beta + mu) > x.min()) ) { - x = ((d*v)* beta + mu) ; - break; - } - } - - } - - - return; + if (gamma >= 1) { + x = randomGamma(gamma, beta, mu, x.min(), x.max()); + return; + } + + double xVal = 0.0; + bool accepted = false; + + while (!accepted) { + double u = RooRandom::randomGenerator()->Uniform(); + double tmp = randomGamma(1 + gamma, beta, mu, 0, std::numeric_limits::infinity()); + xVal = tmp * std::pow(u, 1.0 / gamma); + accepted = xVal < x.max() && xVal > x.min(); + } + + x = xVal; } - - diff --git a/roofit/roofit/src/RooGaussModel.cxx b/roofit/roofit/src/RooGaussModel.cxx index d824cccf43394..d64ef26631676 100644 --- a/roofit/roofit/src/RooGaussModel.cxx +++ b/roofit/roofit/src/RooGaussModel.cxx @@ -28,53 +28,17 @@ for analytical convolutions with classes inheriting from RooAbsAnaConvPdf #include "RooMath.h" #include "RooRealConstant.h" #include "RooRandom.h" +#include "RooBatchCompute.h" #include "TError.h" - -namespace { - -//////////////////////////////////////////////////////////////////////////////// -/// use the approximation: erf(z) = exp(-z*z)/(std::sqrt(pi)*z) -/// to explicitly cancel the divergent exp(y*y) behaviour of -/// CWERF for z = x + i y with large negative y - -std::complex evalCerfApprox(double _x, double u, double c) -{ - static const double rootpi= std::sqrt(std::atan2(0.,-1.)); - const std::complex z(_x * c, u + c); - const std::complex zc(u + c, - _x * c); - const std::complex zsq((z.real() + z.imag()) * (z.real() - z.imag()), - 2. * z.real() * z.imag()); - const std::complex v(-zsq.real() - u*u, -zsq.imag()); - const std::complex ev = std::exp(v); - const std::complex mez2zcrootpi = -std::exp(zsq)/(zc*rootpi); - - return 2. * (ev * (mez2zcrootpi + 1.)); -} - -// Calculate exp(-u^2) cwerf(swt*c + i(u+c)), taking care of numerical instabilities -inline std::complex evalCerf(double swt, double u, double c) -{ - if(swt == 0.0) { - // For a purely complex argument z, the faddeeva function equals to - // exp(z*z) * erfc(z). Together with coefficient exp(-u*u), this means the - // function can be simplified to: - const double z = u + c; - return z > -4.0 ? (std::exp(c * (c + 2.*u)) * std::erfc(z)) : evalCerfApprox(0.,u,c); - // This version with std::erfc is about twice as fast as the faddeeva_fast - // code path, speeding up in particular the analytical convolution of an - // exponential decay with a Gaussian (like in RooDecay). - } - std::complex z(swt*c,u+c); - return (z.imag()>-4.0) ? (std::exp(-u*u)*RooMath::faddeeva_fast(z)) : evalCerfApprox(swt,u,c); -} - -} // namespace - +#include using namespace std; +using RooHeterogeneousMath::evalCerf; +using RooHeterogeneousMath::evalCerfApprox; + ClassImp(RooGaussModel); //////////////////////////////////////////////////////////////////////////////// @@ -168,89 +132,127 @@ Int_t RooGaussModel::basisCode(const char* name) const //////////////////////////////////////////////////////////////////////////////// double RooGaussModel::evaluate() const +{ + auto arg1 = static_cast(basis().getParameter(1)); + auto arg2 = static_cast(basis().getParameter(2)); + double param1 = arg1 ? arg1->getVal() : 0.0; + double param2 = arg2 ? arg2->getVal() : 0.0; + return evaluate(x, mean * msf, sigma * ssf, param1, param2, _basisCode); +} + +void RooGaussModel::computeBatch(double *output, size_t size, + RooFit::Detail::DataMap const &dataMap) const +{ + auto xVals = dataMap.at(x); + auto meanVals = dataMap.at(mean); + auto meanSfVals = dataMap.at(msf); + auto sigmaVals = dataMap.at(sigma); + auto sigmaSfVals = dataMap.at(ssf); + + auto param1 = static_cast(basis().getParameter(1)); + auto param2 = static_cast(basis().getParameter(2)); + const double zeroVal = 0.0; + auto param1Vals = param1 ? dataMap.at(param1) : std::span{&zeroVal, 1}; + auto param2Vals = param2 ? dataMap.at(param2) : std::span{&zeroVal, 1}; + + BasisType basisType = getBasisType(_basisCode); + double basisSign = _basisCode - 10 * (basisType - 1) - 2; + + // We have an implementation also for CUDA right now only for the most used + // basis type, which is expBasis. If the need to support other basis types + // arises, they can be implemented following this example. Remember to also + // adapt RooGaussModel::canComputeBatchWithCuda(). + if (basisType == expBasis) { + RooBatchCompute::ArgVector extraArgs{basisSign}; + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::GaussModelExpBasis, output, size, + {xVals, meanVals, meanSfVals, sigmaVals, sigmaSfVals, param1Vals}, extraArgs); + return; + } + + // For now, if the arrays don't have the expected input shape, fall back to the scalar mode + if (xVals.size() != size || meanVals.size() != 1 || meanSfVals.size() != 1 || sigmaVals.size() != 1 || + sigmaSfVals.size() != 1 || param1Vals.size() != 1 || param2Vals.size() != 1) { + return RooAbsPdf::computeBatch(output, size, dataMap); + } + + for (unsigned int i = 0; i < size; ++i) { + output[i] = evaluate(xVals[i], meanVals[0] * meanSfVals[0], sigmaVals[0] * sigmaSfVals[0], param1Vals[0], + param2Vals[0], _basisCode); + } +} + +double RooGaussModel::evaluate(double x, double mean, double sigma, double param1, double param2, int basisCode) { // *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime *** static double root2(std::sqrt(2.)) ; static double root2pi(std::sqrt(2.*std::atan2(0.,-1.))) ; static double rootpi(std::sqrt(std::atan2(0.,-1.))) ; - BasisType basisType = (BasisType)( (_basisCode == 0) ? 0 : (_basisCode/10) + 1 ); - BasisSign basisSign = (BasisSign)( _basisCode - 10*(basisType-1) - 2 ) ; + BasisType basisType = getBasisType(basisCode); + BasisSign basisSign = (BasisSign)( basisCode - 10*(basisType-1) - 2 ) ; - double tau = (_basisCode!=noBasis)?((RooAbsReal*)basis().getParameter(1))->getVal():0 ; - if (basisType == coshBasis && _basisCode!=noBasis ) { - double dGamma = ((RooAbsReal*)basis().getParameter(2))->getVal(); + double tau = (basisCode!=noBasis) ? param1 : 0.0; + if (basisType == coshBasis && basisCode!=noBasis ) { + double dGamma = param2; if (dGamma==0) basisType = expBasis; } if (basisType==none || ((basisType==expBasis || basisType==cosBasis) && tau==0.)) { - double xprime = (x-(mean*msf))/(sigma*ssf) ; - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 1st form" << endl ; - - double result = std::exp(-0.5*xprime*xprime)/(sigma*ssf*root2pi) ; - if (_basisCode!=0 && basisSign==Both) result *= 2 ; + double xprime = (x-mean)/sigma ; + double result = std::exp(-0.5*xprime*xprime)/(sigma*root2pi) ; + if (basisCode!=0 && basisSign==Both) result *= 2 ; return result ; } // *** 2nd form: 0, used for sinBasis, linBasis, and quadBasis with tau=0 *** if (tau==0) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 2nd form" << endl ; return 0. ; } // *** 3nd form: Convolution with exp(-t/tau), used for expBasis and cosBasis(omega=0) *** - double omega = (basisType==sinBasis || basisType==cosBasis) ? ((RooAbsReal*)basis().getParameter(2))->getVal() : 0 ; - double dgamma = (basisType==sinhBasis || basisType==coshBasis) ? ((RooAbsReal*)basis().getParameter(2))->getVal() : 0 ; + double omega = (basisType==sinBasis || basisType==cosBasis) ? param2 : 0 ; + double dgamma = (basisType==sinhBasis || basisType==coshBasis) ? param2 : 0 ; double _x = omega *tau ; double _y = tau*dgamma/2; - double xprime = (x-(mean*msf))/tau ; - double c = (sigma*ssf)/(root2*tau) ; + double xprime = (x-mean)/tau ; + double c = sigma/(root2*tau) ; double u = xprime/(2*c) ; if (basisType==expBasis || (basisType==cosBasis && _x==0.)) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 3d form tau=" << tau << endl ; double result(0) ; if (basisSign!=Minus) result += evalCerf(0,-u,c).real(); if (basisSign!=Plus) result += evalCerf(0, u,c).real(); - if (TMath::IsNaN(result)) { cxcoutE(Tracing) << "RooGaussModel::getVal(" << GetName() << ") got nan during case 1 " << endl; } return result ; } // *** 4th form: Convolution with exp(-t/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) *** if (basisType==sinBasis) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 4th form omega = " << omega << ", tau = " << tau << endl ; double result(0) ; if (_x==0.) return result ; if (basisSign!=Minus) result += -evalCerf(-_x,-u,c).imag(); if (basisSign!=Plus) result += -evalCerf( _x, u,c).imag(); - if (TMath::IsNaN(result)) cxcoutE(Tracing) << "RooGaussModel::getVal(" << GetName() << ") got nan during case 3 " << endl; return result ; } // *** 5th form: Convolution with exp(-t/tau)*cos(omega*t), used for cosBasis(omega<>0) *** if (basisType==cosBasis) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 5th form omega = " << omega << ", tau = " << tau << endl ; double result(0) ; if (basisSign!=Minus) result += evalCerf(-_x,-u,c).real(); if (basisSign!=Plus) result += evalCerf( _x, u,c).real(); - if (TMath::IsNaN(result)) cxcoutE(Tracing) << "RooGaussModel::getVal(" << GetName() << ") got nan during case 4 " << endl; return result ; } // ***8th form: Convolution with exp(-|t|/tau)*cosh(dgamma*t/2), used for coshBasisSum *** if (basisType==coshBasis || basisType ==sinhBasis) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 8th form tau = " << tau << endl ; double result(0); int sgn = ( basisType == coshBasis ? +1 : -1 ); if (basisSign!=Minus) result += 0.5*( evalCerf(0,-u,c*(1-_y)).real()+sgn*evalCerf(0,-u,c*(1+_y)).real()) ; if (basisSign!=Plus) result += 0.5*(sgn*evalCerf(0, u,c*(1-_y)).real()+ evalCerf(0, u,c*(1+_y)).real()) ; - if (TMath::IsNaN(result)) cxcoutE(Tracing) << "RooGaussModel::getVal(" << GetName() << ") got nan during case 8 " << endl; return result ; } // *** 6th form: Convolution with (t/tau)*exp(-t/tau), used for linBasis *** if (basisType==linBasis) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 6th form tau = " << tau << endl ; R__ASSERT(basisSign==Plus); // This should only be for positive times double f0 = std::exp(-xprime+c*c) * RooMath::erfc(-u+c); @@ -260,7 +262,6 @@ double RooGaussModel::evaluate() const // *** 7th form: Convolution with (t/tau)^2*exp(-t/tau), used for quadBasis *** if (basisType==quadBasis) { - if (verboseEval()>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 7th form tau = " << tau << endl ; R__ASSERT(basisSign==Plus); // This should only be for positive times double f0 = std::exp(-xprime+c*c) * RooMath::erfc(-u+c); diff --git a/roofit/roofit/src/RooGaussian.cxx b/roofit/roofit/src/RooGaussian.cxx index 2aee1ec604850..2240cc5f1432b 100644 --- a/roofit/roofit/src/RooGaussian.cxx +++ b/roofit/roofit/src/RooGaussian.cxx @@ -23,9 +23,11 @@ Plain Gaussian p.d.f #include "RooGaussian.h" #include "RooBatchCompute.h" #include "RooHelpers.h" -#include "RooMath.h" #include "RooRandom.h" +#include +#include + #include ClassImp(RooGaussian); @@ -33,14 +35,14 @@ ClassImp(RooGaussian); //////////////////////////////////////////////////////////////////////////////// RooGaussian::RooGaussian(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _mean, - RooAbsReal& _sigma) : + RooAbsReal::Ref _x, RooAbsReal::Ref _mean, + RooAbsReal::Ref _sigma) : RooAbsPdf(name,title), x("x","Observable",this,_x), mean("mean","Mean",this,_mean), sigma("sigma","Width",this,_sigma) { - RooHelpers::checkRangeOfParameters(this, {&_sigma}, 0); + RooHelpers::checkRangeOfParameters(this, {&static_cast(_sigma)}, 0); } //////////////////////////////////////////////////////////////////////////////// @@ -55,18 +57,15 @@ RooGaussian::RooGaussian(const RooGaussian& other, const char* name) : double RooGaussian::evaluate() const { - const double arg = x - mean; - const double sig = sigma; - return std::exp(-0.5*arg*arg/(sig*sig)); + return RooFit::Detail::EvaluateFuncs::gaussianEvaluate(x, mean, sigma); } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Gaussian distribution. -void RooGaussian::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooGaussian::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Gaussian, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Gaussian, output, nEvents, {dataMap.at(x), dataMap.at(mean), dataMap.at(sigma)}); } @@ -83,38 +82,12 @@ Int_t RooGaussian::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars double RooGaussian::analyticalIntegral(Int_t code, const char* rangeName) const { - assert(code==1 || code==2); - - //The normalisation constant 1./sqrt(2*pi*sigma^2) is left out in evaluate(). - //Therefore, the integral is scaled up by that amount to make RooFit normalise - //correctly. - const double resultScale = std::sqrt(TMath::TwoPi()) * sigma; - - //Here everything is scaled and shifted into a standard normal distribution: - const double xscale = TMath::Sqrt2() * sigma; - double max = 0.; - double min = 0.; - if (code == 1){ - max = (x.max(rangeName)-mean)/xscale; - min = (x.min(rangeName)-mean)/xscale; - } else { //No == 2 test because of assert - max = (mean.max(rangeName)-x)/xscale; - min = (mean.min(rangeName)-x)/xscale; - } - - - //Here we go for maximum precision: We compute all integrals in the UPPER - //tail of the Gaussian, because erfc has the highest precision there. - //Therefore, the different cases for range limits in the negative hemisphere are mapped onto - //the equivalent points in the upper hemisphere using erfc(-x) = 2. - erfc(x) - const double ecmin = std::erfc(std::abs(min)); - const double ecmax = std::erfc(std::abs(max)); + using namespace RooFit::Detail::AnalyticalIntegrals; + auto& constant = code == 1 ? mean : x; + auto& integrand = code == 1 ? x : mean; - return resultScale * 0.5 * ( - min*max < 0.0 ? 2.0 - (ecmin + ecmax) - : max <= 0. ? ecmax - ecmin : ecmin - ecmax - ); + return gaussianIntegral(integrand.min(rangeName), integrand.max(rangeName), constant, sigma); } //////////////////////////////////////////////////////////////////////////////// @@ -133,7 +106,7 @@ void RooGaussian::generateEvent(Int_t code) assert(code==1 || code==2) ; double xgen ; if(code==1){ - while(1) { + while(true) { xgen = RooRandom::randomGenerator()->Gaus(mean,sigma); if (xgenx.min()) { x = xgen ; @@ -141,7 +114,7 @@ void RooGaussian::generateEvent(Int_t code) } } } else if(code==2){ - while(1) { + while(true) { xgen = RooRandom::randomGenerator()->Gaus(x,sigma); if (xgenmean.min()) { mean = xgen ; @@ -154,3 +127,23 @@ void RooGaussian::generateEvent(Int_t code) return; } + +//////////////////////////////////////////////////////////////////////////////// + +void RooGaussian::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // Build a call to the stateless gaussian defined later. + ctx.addResult(this, ctx.buildCall("RooFit::Detail::EvaluateFuncs::gaussianEvaluate", x, mean, sigma)); +} + +//////////////////////////////////////////////////////////////////////////////// + +std::string RooGaussian::buildCallToAnalyticIntegral(Int_t code, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + auto& constant = code == 1 ? mean : x; + auto& integrand = code == 1 ? x : mean; + + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::gaussianIntegral", + integrand.min(rangeName), integrand.max(rangeName), constant, sigma); +} diff --git a/roofit/roofit/src/RooHistConstraint.cxx b/roofit/roofit/src/RooHistConstraint.cxx index 78211538dbee7..cd80ad69d0b9b 100644 --- a/roofit/roofit/src/RooHistConstraint.cxx +++ b/roofit/roofit/src/RooHistConstraint.cxx @@ -30,7 +30,7 @@ ClassImp(RooHistConstraint); /// \param[in] name Name of the PDF. This is used to identify it in a likelihood model. /// \param[in] title Title for plotting etc. /// \param[in] phfSet Set of parametrised histogram functions (RooParamHistFunc). -/// \param[in] threshold Threshold (bin content) up to which statistcal uncertainties are taken into account. +/// \param[in] threshold Threshold (bin content) up to which statistical uncertainties are taken into account. RooHistConstraint::RooHistConstraint(const char *name, const char *title, const RooArgSet& phfSet, int threshold) : RooAbsPdf(name,title), diff --git a/roofit/roofit/src/RooIntegralMorph.cxx b/roofit/roofit/src/RooIntegralMorph.cxx index 13e49e2f7f720..cda913c346fb0 100644 --- a/roofit/roofit/src/RooIntegralMorph.cxx +++ b/roofit/roofit/src/RooIntegralMorph.cxx @@ -110,7 +110,7 @@ RooIntegralMorph::RooIntegralMorph(const char *name, const char *title, x("x","x",this,_x), alpha("alpha","alpha",this,_alpha), _cacheAlpha(doCacheAlpha), - _cache(0) + _cache(nullptr) { } @@ -124,7 +124,7 @@ RooIntegralMorph::RooIntegralMorph(const RooIntegralMorph& other, const char* na x("x",this,other.x), alpha("alpha",this,other.alpha), _cacheAlpha(other._cacheAlpha), - _cache(0) + _cache(nullptr) { } @@ -133,31 +133,31 @@ RooIntegralMorph::RooIntegralMorph(const RooIntegralMorph& other, const char* na /// Returns the 'x' observable unless doCacheAlpha is set in which /// case a set with both x and alpha -RooArgSet* RooIntegralMorph::actualObservables(const RooArgSet& /*nset*/) const +RooFit::OwningPtr RooIntegralMorph::actualObservables(const RooArgSet& /*nset*/) const { RooArgSet* obs = new RooArgSet ; if (_cacheAlpha) { obs->add(alpha.arg()) ; } obs->add(x.arg()) ; - return obs ; + return RooFit::OwningPtr{obs}; } //////////////////////////////////////////////////////////////////////////////// /// Parameters of the cache. Returns parameters of both pdf1 and pdf2 /// and parameter cache, in case doCacheAlpha is not set. -RooArgSet* RooIntegralMorph::actualParameters(const RooArgSet& /*nset*/) const +RooFit::OwningPtr RooIntegralMorph::actualParameters(const RooArgSet& /*nset*/) const { - RooArgSet* par1 = pdf1.arg().getParameters(RooArgSet()) ; - RooArgSet* par2 = pdf2.arg().getParameters(RooArgSet()) ; - par1->add(*par2,true) ; + auto par1 = pdf1->getParameters(static_cast(nullptr)); + RooArgSet par2; + pdf2->getParameters(nullptr, par2); + par1->add(par2,true) ; par1->remove(x.arg(),true,true) ; if (!_cacheAlpha) { par1->add(alpha.arg()) ; } - delete par2 ; - return par1 ; + return RooFit::OwningPtr{std::move(par1)}; } //////////////////////////////////////////////////////////////////////////////// @@ -185,26 +185,23 @@ void RooIntegralMorph::fillCacheObject(PdfCacheElem& cache) const if (!_cacheAlpha) { - TIterator* dIter = cache.hist()->sliceIterator((RooAbsArg&)x.arg(),RooArgSet()) ; - mcache.calculate(dIter) ; - delete dIter ; + std::unique_ptr dIter{cache.hist()->sliceIterator(const_cast(x.arg()),RooArgSet())}; + mcache.calculate(dIter.get()); } else { - TIterator* slIter = cache.hist()->sliceIterator((RooAbsArg&)alpha.arg(),RooArgSet()) ; + std::unique_ptr slIter{cache.hist()->sliceIterator(const_cast(alpha.arg()),RooArgSet())}; double alphaSave = alpha ; RooArgSet alphaSet(alpha.arg()) ; coutP(Eval) << "RooIntegralMorph::fillCacheObject(" << GetName() << ") filling multi-dimensional cache" ; while(slIter->Next()) { alphaSet.assign(*cache.hist()->get()) ; - TIterator* dIter = cache.hist()->sliceIterator((RooAbsArg&)x.arg(),RooArgSet(alpha.arg())) ; - mcache.calculate(dIter) ; + std::unique_ptr dIter{cache.hist()->sliceIterator(const_cast(x.arg()),RooArgSet(alpha.arg()))}; + mcache.calculate(dIter.get()); ccoutP(Eval) << "." << flush; - delete dIter ; } - ccoutP(Eval) << endl ; + ccoutP(Eval) << std::endl; - delete slIter ; const_cast(this)->alpha = alphaSave ; } } @@ -244,19 +241,19 @@ RooIntegralMorph::MorphCacheElem::MorphCacheElem(RooIntegralMorph& self, const R { // Mark in base class that normalization of cached pdf is invariant under pdf parameters _x = (RooRealVar*)self.x.absArg() ; - _nset = new RooArgSet(*_x) ; + _nset = std::make_unique(*_x); _alpha = (RooAbsReal*)self.alpha.absArg() ; _pdf1 = (RooAbsPdf*)(self.pdf1.absArg()) ; _pdf2 = (RooAbsPdf*)(self.pdf2.absArg()) ; - _c1 = _pdf1->createCdf(*_x); - _c2 = _pdf2->createCdf(*_x) ; - _cb1 = _c1->bindVars(*_x,_nset) ; - _cb2 = _c2->bindVars(*_x,_nset) ; + _c1 = std::unique_ptr{_pdf1->createCdf(*_x)}; + _c2 = std::unique_ptr{_pdf2->createCdf(*_x)}; + _cb1 = std::unique_ptr{_c1->bindVars(*_x,_nset.get())}; + _cb2 = std::unique_ptr{_c2->bindVars(*_x,_nset.get())}; _self = &self ; - _rf1 = new RooBrentRootFinder(*_cb1) ; - _rf2 = new RooBrentRootFinder(*_cb2) ; + _rf1 = std::make_unique(*_cb1); + _rf2 = std::make_unique(*_cb2); _ccounter = 0 ; _rf1->setTol(1e-12) ; @@ -278,10 +275,6 @@ RooIntegralMorph::MorphCacheElem::MorphCacheElem(RooIntegralMorph& self, const R RooIntegralMorph::MorphCacheElem::~MorphCacheElem() { - delete _rf1 ; - delete _rf2 ; - // delete[] _yatX ; - // delete[] _calcX ; } //////////////////////////////////////////////////////////////////////////////// @@ -389,7 +382,7 @@ void RooIntegralMorph::MorphCacheElem::calculate(TIterator* dIter) // Calculate additional offset to apply if bin ixlo does not have X value calculated at bin center double xBinC = xmin + (i+0.5)*binw ; double xOffset = xBinC-_calcX[i] ; - if (fabs(xOffset/binw)>1e-3) { + if (std::abs(xOffset/binw)>1e-3) { double slope = (_yatX[i+1]-_yatX[i-1])/(_calcX[i+1]-_calcX[i-1]) ; double newY = _yatX[i] + slope*xOffset ; //cout << "bin " << i << " needs to be re-centered " << xOffset/binw << " slope = " << slope << " origY = " << _yatX[i] << " newY = " << newY << endl ; @@ -421,8 +414,10 @@ void RooIntegralMorph::MorphCacheElem::calculate(TIterator* dIter) _rf1->findRoot(x1,x1,xMax,y) ; _rf2->findRoot(x2,x2,xMax,y) ; - _x->setVal(x1) ; double f1x1 = _pdf1->getVal(_nset) ; - _x->setVal(x2) ; double f2x2 = _pdf2->getVal(_nset) ; + _x->setVal(x1); + double f1x1 = _pdf1->getVal(_nset.get()); + _x->setVal(x2); + double f2x2 = _pdf2->getVal(_nset.get()); double fbarX = f1x1*f2x2 / ( _alpha->getVal()*f2x2 + (1-_alpha->getVal())*f1x1 ) ; dIter->Next() ; @@ -481,7 +476,7 @@ void RooIntegralMorph::MorphCacheElem::fillGap(Int_t ixlo, Int_t ixhi, double sp // Policy: If centration quality is better than 1% OR better than 1/10 of a bin, fill interval with linear interpolation - if (fabs(cq)<0.01 || fabs(cq*(ixhi-ixlo))<0.1 || ymid<_ycutoff ) { + if (std::abs(cq)<0.01 || std::abs(cq*(ixhi-ixlo))<0.1 || ymid<_ycutoff ) { // Fill remaining gaps on either side with linear interpolation if (iX-ixlo>1) { @@ -584,7 +579,7 @@ void RooIntegralMorph::MorphCacheElem::findRange() // Terminate if value of X no longer moves by >0.1 bin size double X = _alpha->getVal()*x1 + (1-_alpha->getVal())*x2 ; - if (fabs(X-Xlast)/(xmax-xmin)<0.0001) { + if (std::abs(X-Xlast)/(xmax-xmin)<0.0001) { break ; } Xlast=X ; @@ -621,7 +616,7 @@ void RooIntegralMorph::MorphCacheElem::findRange() // Terminate if value of X no longer moves by >0.1 bin size double X = _alpha->getVal()*x1 + (1-_alpha->getVal())*x2 ; - if (fabs(X-Xlast)/(xmax-xmin)<0.0001) { + if (std::abs(X-Xlast)/(xmax-xmin)<0.0001) { break ; } Xlast=X ; diff --git a/roofit/roofit/src/RooJeffreysPrior.cxx b/roofit/roofit/src/RooJeffreysPrior.cxx index 97f290e199802..9d684b2cb877f 100644 --- a/roofit/roofit/src/RooJeffreysPrior.cxx +++ b/roofit/roofit/src/RooJeffreysPrior.cxx @@ -107,7 +107,7 @@ double RooJeffreysPrior::evaluate() const //and we start to clone again. auto& pdf = _nominal.arg(); RooAbsPdf* clonePdf = static_cast(pdf.cloneTree()); - auto vars = clonePdf->getParameters(_obsSet); + std::unique_ptr vars{clonePdf->getParameters(_obsSet)}; for (auto varTmp : *vars) { auto& var = static_cast(*varTmp); auto range = var.getRange(); @@ -117,7 +117,7 @@ double RooJeffreysPrior::evaluate() const cacheElm = new CacheElem; cacheElm->_pdf.reset(clonePdf); - cacheElm->_pdfVariables.reset(vars); + cacheElm->_pdfVariables = std::move(vars); _cacheMgr.setObj(nullptr, cacheElm); } diff --git a/roofit/roofit/src/RooJohnson.cxx b/roofit/roofit/src/RooJohnson.cxx index 282d59bb37404..84be5f1aad5d2 100644 --- a/roofit/roofit/src/RooJohnson.cxx +++ b/roofit/roofit/src/RooJohnson.cxx @@ -112,12 +112,12 @@ double RooJohnson::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of the Johnson distribution. -void RooJohnson::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooJohnson::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Johnson, output, nEvents, + RooBatchCompute::ArgVector extraArgs{_massThreshold}; + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Johnson, output, nEvents, {dataMap.at(_mass), dataMap.at(_mu), dataMap.at(_lambda), dataMap.at(_gamma), dataMap.at(_delta)}, - {_massThreshold}); + extraArgs); } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofit/src/RooKeysPdf.cxx b/roofit/roofit/src/RooKeysPdf.cxx index b3b54d854df72..5994551acf78f 100644 --- a/roofit/roofit/src/RooKeysPdf.cxx +++ b/roofit/roofit/src/RooKeysPdf.cxx @@ -54,7 +54,7 @@ const double RooKeysPdf::_nSigma = std::sqrt(-2. * //////////////////////////////////////////////////////////////////////////////// /// coverity[UNINIT_CTOR] - RooKeysPdf::RooKeysPdf() : _nEvents(0), _dataPts(0), _dataWgts(0), _weights(0), _sumWgt(0), + RooKeysPdf::RooKeysPdf() : _nEvents(0), _dataPts(nullptr), _dataWgts(nullptr), _weights(nullptr), _sumWgt(0), _mirrorLeft(false), _mirrorRight(false), _asymLeft(false), _asymRight(false) { @@ -70,9 +70,9 @@ RooKeysPdf::RooKeysPdf(const char *name, const char *title, RooAbsPdf(name,title), _x("x","observable",this,x), _nEvents(0), - _dataPts(0), - _dataWgts(0), - _weights(0), + _dataPts(nullptr), + _dataWgts(nullptr), + _weights(nullptr), _mirrorLeft(mirror==MirrorLeft || mirror==MirrorBoth || mirror==MirrorLeftAsymRight), _mirrorRight(mirror==MirrorRight || mirror==MirrorBoth || mirror==MirrorAsymLeftRight), _asymLeft(mirror==MirrorAsymLeft || mirror==MirrorAsymLeftRight || mirror==MirrorAsymBoth), @@ -99,9 +99,9 @@ RooKeysPdf::RooKeysPdf(const char *name, const char *title, RooAbsPdf(name,title), _x("x","Observable",this,xpdf), _nEvents(0), - _dataPts(0), - _dataWgts(0), - _weights(0), + _dataPts(nullptr), + _dataWgts(nullptr), + _weights(nullptr), _mirrorLeft(mirror==MirrorLeft || mirror==MirrorBoth || mirror==MirrorLeftAsymRight), _mirrorRight(mirror==MirrorRight || mirror==MirrorBoth || mirror==MirrorAsymLeftRight), _asymLeft(mirror==MirrorAsymLeft || mirror==MirrorAsymLeftRight || mirror==MirrorAsymBoth), @@ -123,7 +123,7 @@ RooKeysPdf::RooKeysPdf(const char *name, const char *title, RooKeysPdf::RooKeysPdf(const RooKeysPdf& other, const char* name): RooAbsPdf(other,name), _x("x",this,other._x), _nEvents(other._nEvents), - _dataPts(0), _dataWgts(0), _weights(0), _sumWgt(0), + _dataPts(nullptr), _dataWgts(nullptr), _weights(nullptr), _sumWgt(0), _mirrorLeft( other._mirrorLeft ), _mirrorRight( other._mirrorRight ), _asymLeft(other._asymLeft), _asymRight(other._asymRight), _rho( other._rho ) { diff --git a/roofit/roofit/src/RooLagrangianMorphFunc.cxx b/roofit/roofit/src/RooLagrangianMorphFunc.cxx index e0f70eab6d12b..3ae5d056ba89e 100644 --- a/roofit/roofit/src/RooLagrangianMorphFunc.cxx +++ b/roofit/roofit/src/RooLagrangianMorphFunc.cxx @@ -61,6 +61,7 @@ describe the same process or not. #include "TRandom3.h" #include +#include #include #include #include @@ -254,7 +255,7 @@ inline RooFit::SuperFloat invertMatrix(const Matrix &matrix, Matrix &inverse) // back-substitute to get the inverse lu_substitute(lu, pm, inverse); } catch (boost::numeric::ublas::internal_logic &error) { - // coutE(Eval) << "boost::numberic::ublas error: matrix is not invertible!" + // coutE(Eval) << "boost::numeric::ublas error: matrix is not invertible!" // << std::endl; } RooFit::SuperFloat inorm = norm_inf(inverse); @@ -317,7 +318,7 @@ inline double invertMatrix(const Matrix &matrix, Matrix &inverse) // sanitize numeric problems for (size_t i = 0; i < n; ++i) for (size_t j = 0; j < n; ++j) - if (fabs(inverse(i, j)) < 1e-9) + if (std::abs(inverse(i, j)) < 1e-9) inverse(i, j) = 0; return condition; } @@ -341,9 +342,9 @@ typedef std::map> FormulaList; /////////////////////////////////////////////////////////////////////////////// /// (-?-) -inline TString makeValidName(const char *input) +inline TString makeValidName(std::string const& input) { - TString retval(input); + TString retval(input.c_str()); retval.ReplaceAll("/", "_"); retval.ReplaceAll("^", ""); retval.ReplaceAll("*", "X"); @@ -799,14 +800,14 @@ void collectHistograms(const char *name, TDirectory *file, std::map(histname, histname, vars, hist.get()); + auto dh = std::make_unique(histname.Data(), histname.Data(), vars, hist.get()); // add it to the list - auto hf = std::make_unique(funcname, funcname, var, std::move(dh)); + auto hf = std::make_unique(funcname.Data(), funcname.Data(), var, std::move(dh)); int idx = physics.getSize(); list_hf[sample] = idx; physics.addOwned(std::move(hf)); @@ -865,13 +866,13 @@ void collectCrosssections(const char *name, TDirectory *file, std::mapsecond)); xs->setVal(xsection->GetVal()); } else { - std::string objname = Form("phys_%s_%s", name, sample.c_str()); + std::string objname = "phys_" + std::string(name) + "_" + sample; auto xsOwner = std::make_unique(objname.c_str(), objname.c_str(), xsection->GetVal()); xs = xsOwner.get(); xs->setConstant(true); @@ -1060,8 +1061,8 @@ inline void inverseSanity(const Matrix &matrix, const Matrix &inverse, double &u if (inverse(i, j) > largestWeight) { largestWeight = (double)inverse(i, j); } - if (fabs(unity(i, j) - static_cast(i == j)) > unityDeviation) { - unityDeviation = fabs((double)unity(i, j)) - static_cast(i == j); + if (std::abs(unity(i, j) - static_cast(i == j)) > unityDeviation) { + unityDeviation = std::abs((double)unity(i, j)) - static_cast(i == j); } } } @@ -1207,7 +1208,7 @@ FormulaList buildFormulas(const char *mfname, const RooLagrangianMorphFunc::Para if (val == nNP) { if (flagsZero.find(obj->GetName()) != flagsZero.end() && flagsZero.at(obj->GetName())) { removedByFlag = true; - reason = Form("flag %s is zero", obj->GetName()); + reason = "flag " + std::string(obj->GetName()) + " is zero"; } ss.add(*obj); } @@ -1263,7 +1264,7 @@ inline void buildSampleWeights(T1 &weights, const char *fname, const RooLagrangi for (auto sampleit : inputParameters) { const std::string sample(sampleit.first); std::stringstream title; - TString name_full(makeValidName(sample.c_str())); + TString name_full(makeValidName(sample)); if (fname) { name_full.Append("_"); name_full.Append(fname); @@ -1391,22 +1392,22 @@ class RooLagrangianMorphFunc::CacheElem : public RooAbsCacheElement { if (false) { if (unitywarning) { - oocxcoutW((TObject *)0, Eval) << "Warning: The matrix inversion seems to be unstable. This can " + oocxcoutW((TObject *)nullptr, Eval) << "Warning: The matrix inversion seems to be unstable. This can " "be a result to input samples that are not sufficiently " "different to provide any morphing power." << std::endl; } else if (weightwarning) { - oocxcoutW((TObject *)0, Eval) << "Warning: Some weights are excessively large. This can be a " + oocxcoutW((TObject *)nullptr, Eval) << "Warning: Some weights are excessively large. This can be a " "result to input samples that are not sufficiently different to " "provide any morphing power." << std::endl; } - oocxcoutW((TObject *)0, Eval) << " Please consider the couplings " + oocxcoutW((TObject *)nullptr, Eval) << " Please consider the couplings " "encoded in your samples to cross-check:" << std::endl; for (auto sampleit : inputParameters) { const std::string sample(sampleit.first); - oocxcoutW((TObject *)0, Eval) << " " << sample << ": "; + oocxcoutW((TObject *)nullptr, Eval) << " " << sample << ": "; // set all vars to value stored in input file setParams(sampleit.second, operators, true); bool first = true; @@ -1416,10 +1417,10 @@ class RooLagrangianMorphFunc::CacheElem : public RooAbsCacheElement { obj = dynamic_cast(itr); if (!first) std::cerr << ", "; - oocxcoutW((TObject *)0, Eval) << obj->GetName() << "=" << obj->getVal(); + oocxcoutW((TObject *)nullptr, Eval) << obj->GetName() << "=" << obj->getVal(); first = false; } - oocxcoutW((TObject *)0, Eval) << std::endl; + oocxcoutW((TObject *)nullptr, Eval) << std::endl; } } #ifndef USE_UBLAS @@ -1459,7 +1460,7 @@ class RooLagrangianMorphFunc::CacheElem : public RooAbsCacheElement { RooArgList scaleElements; for (auto sampleit : inputParameters) { // for now, we assume all the lists are nicely ordered - TString prodname(makeValidName(sampleit.first.c_str())); + TString prodname(makeValidName(sampleit.first)); RooAbsReal *obj = static_cast(physics.at(storage.at(prodname.Data()))); @@ -1495,7 +1496,7 @@ class RooLagrangianMorphFunc::CacheElem : public RooAbsCacheElement { } // put everything together - _sumFunc = make_unique(Form("%s_morphfunc", name), name, sumElements, scaleElements); + _sumFunc = make_unique((std::string(name) + "_morphfunc").c_str(), name, sumElements, scaleElements); if (!observable) std::cerr << "unable to access observable" << std::endl; @@ -1537,8 +1538,8 @@ class RooLagrangianMorphFunc::CacheElem : public RooAbsCacheElement { return cache; } - oocxcoutP((TObject *)0, ObjectHandling) << "observable: " << func->getObservable()->GetName() << std::endl; - oocxcoutP((TObject *)0, ObjectHandling) << "binWidth: " << func->getBinWidth()->GetName() << std::endl; + oocxcoutP((TObject *)nullptr, ObjectHandling) << "observable: " << func->getObservable()->GetName() << std::endl; + oocxcoutP((TObject *)nullptr, ObjectHandling) << "binWidth: " << func->getBinWidth()->GetName() << std::endl; setParams(func->_flags, 1); cache->buildMorphingFunction(func->GetName(), func->_config.paramCards, func->_sampleMap, func->_physics, @@ -1620,7 +1621,7 @@ RooRealVar *RooLagrangianMorphFunc::setupObservable(const char *obsname, TClass // cxcoutP(ObjectHandling) << "setting up observable" << std::endl; RooRealVar *obs = nullptr; bool obsExists(false); - if (_observables.at(0) != 0) { + if (_observables.at(0) != nullptr) { obs = (RooRealVar *)_observables.at(0); obsExists = true; } @@ -1660,7 +1661,7 @@ RooRealVar *RooLagrangianMorphFunc::setupObservable(const char *obsname, TClass } } - TString sbw = Form("binWidth_%s", makeValidName(obs->GetName()).Data()); + TString sbw = TString::Format("binWidth_%s", makeValidName(obs->GetName()).Data()); auto binWidth = std::make_unique(sbw.Data(), sbw.Data(), 1.); double bw = obs->numBins() / (obs->getMax() - obs->getMin()); binWidth->setVal(bw); @@ -1881,7 +1882,7 @@ void RooLagrangianMorphFunc::disableInterference(const std::vector { // disable interference between the listed operators std::stringstream name; - name << "noInteference"; + name << "noInterference"; for (auto c : nonInterfering) { name << c; } @@ -1908,7 +1909,7 @@ void RooLagrangianMorphFunc::disableInterferences(const std::vectorgetComponents(); + std::unique_ptr args{mf->getComponents()}; TString prodname(name); prodname.Append("_"); prodname.Append(this->GetName()); @@ -2230,15 +2231,15 @@ void RooLagrangianMorphFunc::randomizeParameters(double z) } //////////////////////////////////////////////////////////////////////////////// -/// retrive the new physics objects and update the weights in the morphing -/// function +/// Retrieve the new physics objects and update the weights in the morphing +/// function. bool RooLagrangianMorphFunc::updateCoefficients() { auto cache = this->getCache(); std::string filename = _config.fileName; - TDirectory *file = openFile(filename.c_str()); + TDirectory *file = openFile(filename); if (!file) { coutE(InputArguments) << "unable to open file '" << filename << "'!" << std::endl; return false; @@ -2262,12 +2263,13 @@ bool RooLagrangianMorphFunc::updateCoefficients() bool RooLagrangianMorphFunc::useCoefficients(const TMatrixD &inverse) { - auto cache = static_cast(_cacheMgr.getObj(0, (RooArgSet *)0)); + auto cache = static_cast( + _cacheMgr.getObj(nullptr, static_cast(nullptr))); Matrix m = makeSuperMatrix(inverse); if (cache) { std::string filename = _config.fileName; cache->_inverse = m; - TDirectory *file = openFile(filename.c_str()); + TDirectory *file = openFile(filename); if (!file) { coutE(InputArguments) << "unable to open file '" << filename << "'!" << std::endl; return false; @@ -2285,7 +2287,7 @@ bool RooLagrangianMorphFunc::useCoefficients(const TMatrixD &inverse) cache = RooLagrangianMorphFunc::CacheElem::createCache(this, m); if (!cache) coutE(Caching) << "unable to create cache!" << std::endl; - _cacheMgr.setObj(0, 0, cache, 0); + _cacheMgr.setObj(nullptr, nullptr, cache, nullptr); } return true; } @@ -2296,7 +2298,8 @@ bool RooLagrangianMorphFunc::useCoefficients(const TMatrixD &inverse) bool RooLagrangianMorphFunc::useCoefficients(const char *filename) { - auto cache = static_cast(_cacheMgr.getObj(0, (RooArgSet *)0)); + auto cache = static_cast( + _cacheMgr.getObj(nullptr, static_cast(nullptr))); if (cache) { return false; } @@ -2324,7 +2327,8 @@ bool RooLagrangianMorphFunc::writeCoefficients(const char *filename) typename RooLagrangianMorphFunc::CacheElem *RooLagrangianMorphFunc::getCache() const { - auto cache = static_cast(_cacheMgr.getObj(0, (RooArgSet *)0)); + auto cache = static_cast( + _cacheMgr.getObj(nullptr, static_cast(nullptr))); if (!cache) { cxcoutP(Caching) << "creating cache from getCache function for " << this << std::endl; cxcoutP(Caching) << "current storage has size " << _sampleMap.size() << std::endl; @@ -2479,7 +2483,7 @@ void RooLagrangianMorphFunc::setParameters(TH1 *paramhist) void RooLagrangianMorphFunc::setParameters(const char *foldername) { std::string filename = _config.fileName; - TDirectory *file = openFile(filename.c_str()); + TDirectory *file = openFile(filename); auto paramhist = loadFromFileResidentFolder(file, foldername, "param_card"); setParams(paramhist.get(), _operators, false); closeFile(file); @@ -2553,7 +2557,7 @@ TH1 *RooLagrangianMorphFunc::createTH1(const std::string &name, bool correlateEr auto hist = std::make_unique(name.c_str(), name.c_str(), nbins, observable->getBinning().array()); - RooArgSet *args = mf->getComponents(); + std::unique_ptr args{mf->getComponents()}; for (int i = 0; i < nbins; ++i) { observable->setBin(i); double val = 0; @@ -2591,7 +2595,7 @@ int RooLagrangianMorphFunc::countContributingFormulas() const auto mf = std::make_unique(*(this->getFunc())); if (!mf) coutE(InputArguments) << "unable to retrieve morphing function" << std::endl; - RooArgSet *args = mf->getComponents(); + std::unique_ptr args{mf->getComponents()}; for (auto itr : *args) { RooProduct *prod = dynamic_cast(itr); if (prod->getVal() != 0) { @@ -2678,9 +2682,8 @@ void RooLagrangianMorphFunc::printEvaluation() const std::cerr << "Error: unable to retrieve morphing function" << std::endl; return; } - RooArgSet *args = mf->getComponents(); - for (auto itr : *args) { - RooAbsReal *formula = dynamic_cast(itr); + std::unique_ptr args{mf->getComponents()}; + for (auto *formula : dynamic_range_cast(*args)) { if (formula) { TString name(formula->GetName()); name.Remove(0, 2); @@ -3075,7 +3078,7 @@ std::string LMIFace::create(RooFactoryWSTool &ft, const char * /*typeName*/, con for (const auto &subarg : subargs) { std::vector parts = ROOT::Split(subarg, "="); if (parts.size() == 2) { - ft.ws().arg(parts[0].c_str())->setAttribute("NewPhysics", atoi(parts[1].c_str())); + ft.ws().arg(parts[0])->setAttribute("NewPhysics", atoi(parts[1].c_str())); } else throw std::string(Form("%s::create() ERROR: unknown token %s encountered, check input provided for %s", instanceName, subarg.c_str(), args[i].c_str())); diff --git a/roofit/roofit/src/RooLandau.cxx b/roofit/roofit/src/RooLandau.cxx index 1de1c25d0c5cb..8fa7acd2f1c74 100644 --- a/roofit/roofit/src/RooLandau.cxx +++ b/roofit/roofit/src/RooLandau.cxx @@ -27,18 +27,19 @@ Landau distribution p.d.f #include "RooBatchCompute.h" #include "TMath.h" +#include "Math/ProbFunc.h" ClassImp(RooLandau); //////////////////////////////////////////////////////////////////////////////// -RooLandau::RooLandau(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _mean, RooAbsReal& _sigma) : +RooLandau::RooLandau(const char *name, const char *title, RooAbsReal::Ref _x, RooAbsReal::Ref _mean, RooAbsReal::Ref _sigma) : RooAbsPdf(name,title), x("x","Dependent",this,_x), mean("mean","Mean",this,_mean), sigma("sigma","Width",this,_sigma) { - RooHelpers::checkRangeOfParameters(this, {&_sigma}, 0.0); + RooHelpers::checkRangeOfParameters(this, {&static_cast(_sigma)}, 0.0); } //////////////////////////////////////////////////////////////////////////////// @@ -58,13 +59,19 @@ double RooLandau::evaluate() const return TMath::Landau(x, mean, sigma); } +//////////////////////////////////////////////////////////////////////////////// + +void RooLandau::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + ctx.addResult(this, ctx.buildCall("TMath::Landau", x, mean, sigma)); +} + //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Landau distribution. -void RooLandau::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooLandau::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Landau, output, nEvents, - {dataMap.at(x), dataMap.at(mean), dataMap.at(sigma)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Landau, output, nEvents, + {dataMap.at(x), dataMap.at(mean), dataMap.at(sigma)}); } //////////////////////////////////////////////////////////////////////////////// @@ -72,7 +79,39 @@ void RooLandau::computeBatch(cudaStream_t* stream, double* output, size_t nEvent Int_t RooLandau::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool /*staticInitOK*/) const { if (matchArgs(directVars,generateVars,x)) return 1 ; - return 0 ; + return 0; +} + +Int_t RooLandau::getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char * /*rangeName*/) const +{ + if (matchArgs(allVars, analVars, x)) + return 1; + return 0; +} + +Double_t RooLandau::analyticalIntegral(Int_t /*code*/, const char *rangeName) const +{ + // Don't do anything with "code". It can only be "1" anyway (see + // implementation of getAnalyticalIntegral). + + const double meanVal = mean; + const double sigmaVal = sigma; + + const double a = ROOT::Math::landau_cdf(x.max(rangeName), sigmaVal, meanVal); + const double b = ROOT::Math::landau_cdf(x.min(rangeName), sigmaVal, meanVal); + return sigmaVal * (a - b); +} + +//////////////////////////////////////////////////////////////////////////////// + +std::string RooLandau::buildCallToAnalyticIntegral(Int_t /*code*/, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + // Don't do anything with "code". It can only be "1" anyway (see + // implementation of getAnalyticalIntegral). + const std::string a = ctx.buildCall("ROOT::Math::landau_cdf", x.max(rangeName), sigma, mean); + const std::string b = ctx.buildCall("ROOT::Math::landau_cdf", x.min(rangeName), sigma, mean); + return ctx.getResult(sigma) + " * " + "(" + a + " - " + b + ")"; } //////////////////////////////////////////////////////////////////////////////// @@ -81,7 +120,7 @@ void RooLandau::generateEvent(Int_t code) { assert(1 == code); (void)code; double xgen ; - while(1) { + while(true) { xgen = RooRandom::randomGenerator()->Landau(mean,sigma); if (xgenx.min()) { x = xgen ; diff --git a/roofit/roofit/src/RooLognormal.cxx b/roofit/roofit/src/RooLognormal.cxx index a35655e1f1a37..d06597cf686c1 100644 --- a/roofit/roofit/src/RooLognormal.cxx +++ b/roofit/roofit/src/RooLognormal.cxx @@ -1,12 +1,12 @@ - /***************************************************************************** - * Project: RooFit * - * @(#)root/roofit:$Id$ * - * * - * RooFit Lognormal PDF * - * * - * Author: Gregory Schott and Stefan Schmitz * - * * - *****************************************************************************/ +/***************************************************************************** + * Project: RooFit * + * @(#)root/roofit:$Id$ * + * * + * RooFit Lognormal PDF * + * * + * Author: Gregory Schott and Stefan Schmitz * + * * + *****************************************************************************/ /** \class RooLognormal \ingroup Roofit @@ -16,8 +16,8 @@ RooFit Lognormal PDF. The two parameters are: - `k = exp(sigma)`: sigma is called the shape parameter in the TMath parameterization \f[ - \mathrm{RooLognormal}(x \, | \, m_0, k) = \frac{1}{\sqrt{2\pi \cdot \ln(k) \cdot x}} \cdot \exp\left( \frac{-\ln^2(\frac{x}{m_0})}{2 \ln^2(k)} \right) -\f] + \mathrm{RooLognormal}(x \, | \, m_0, k) = \frac{1}{\sqrt{2\pi \cdot \ln(k) \cdot x}} \cdot \exp\left( +\frac{-\ln^2(\frac{x}{m_0})}{2 \ln^2(k)} \right) \f] The parameterization here is physics driven and differs from the ROOT::Math::lognormal_pdf() in `x,m,s,x0` with: - `m = log(m0)` @@ -37,29 +37,34 @@ ClassImp(RooLognormal); //////////////////////////////////////////////////////////////////////////////// -RooLognormal::RooLognormal(const char *name, const char *title, - RooAbsReal& _x, RooAbsReal& _m0, - RooAbsReal& _k) : - RooAbsPdf(name,title), - x("x","Observable",this,_x), - m0("m0","m0",this,_m0), - k("k","k",this,_k) +RooLognormal::RooLognormal(const char *name, const char *title, RooAbsReal &_x, RooAbsReal &_m0, RooAbsReal &_k, + bool useStandardParametrization) + : RooAbsPdf{name, title}, + x{"x", "Observable", this, _x}, + m0{"m0", "m0", this, _m0}, + k{"k", "k", this, _k}, + _useStandardParametrization{useStandardParametrization} { - RooHelpers::checkRangeOfParameters(this, {&_x, &_m0, &_k}, 0.); + RooHelpers::checkRangeOfParameters(this, {&_x, &_m0, &_k}, 0.); - auto par = dynamic_cast(&_k); - if (par && par->getMin()<=1 && par->getMax()>=1 ) { + auto par = dynamic_cast(&_k); + const double unsafeValue = useStandardParametrization ? 0.0 : 1.0; + if (par && par->getMin() <= unsafeValue && par->getMax() >= unsafeValue) { coutE(InputArguments) << "The parameter '" << par->GetName() << "' with range [" << par->getMin("") << ", " - << par->getMax() << "] of the " << this->ClassName() << " '" << this->GetName() - << "' can reach the unsafe value 1.0 " << ". Advise to limit its range." << std::endl; - } + << par->getMax() << "] of the " << this->ClassName() << " '" << this->GetName() + << "' can reach the unsafe value " << unsafeValue << " " + << ". Advise to limit its range." << std::endl; + } } //////////////////////////////////////////////////////////////////////////////// -RooLognormal::RooLognormal(const RooLognormal& other, const char* name) : - RooAbsPdf(other,name), x("x",this,other.x), m0("m0",this,other.m0), - k("k",this,other.k) +RooLognormal::RooLognormal(const RooLognormal &other, const char *name) + : RooAbsPdf(other, name), + x("x", this, other.x), + m0("m0", this, other.m0), + k{"k", this, other.k}, + _useStandardParametrization{other._useStandardParametrization} { } @@ -71,66 +76,75 @@ RooLognormal::RooLognormal(const RooLognormal& other, const char* name) : double RooLognormal::evaluate() const { - double ln_k = TMath::Abs(TMath::Log(k)); - double ln_m0 = TMath::Log(m0); + const double ln_k = std::abs(_useStandardParametrization ? k : std::log(k)); + const double ln_m0 = _useStandardParametrization ? m0 : std::log(m0); - double ret = ROOT::Math::lognormal_pdf(x,ln_m0,ln_k); - return ret ; + return ROOT::Math::lognormal_pdf(x, ln_m0, ln_k); +} + +void RooLognormal::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string funcName = _useStandardParametrization ? "logNormalEvaluateStandard" : "logNormalEvaluate"; + ctx.addResult(this, ctx.buildCall("RooFit::Detail::EvaluateFuncs::" + funcName, x, k, m0)); } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Lognormal distribution. -void RooLognormal::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooLognormal::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Lognormal, output, nEvents, - {dataMap.at(x), dataMap.at(m0), dataMap.at(k)}); + auto computer = _useStandardParametrization ? RooBatchCompute::LognormalStandard : RooBatchCompute::Lognormal; + RooBatchCompute::compute(dataMap.config(this), computer, output, nEvents, + {dataMap.at(x), dataMap.at(m0), dataMap.at(k)}); } //////////////////////////////////////////////////////////////////////////////// -Int_t RooLognormal::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const +Int_t RooLognormal::getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char * /*rangeName*/) const { - if (matchArgs(allVars,analVars,x)) return 1 ; - return 0 ; + return matchArgs(allVars, analVars, x) ? 1 : 0; } //////////////////////////////////////////////////////////////////////////////// -double RooLognormal::analyticalIntegral(Int_t code, const char* rangeName) const +double RooLognormal::analyticalIntegral(Int_t /*code*/, const char *rangeName) const { - R__ASSERT(code==1) ; + static const double root2 = std::sqrt(2.); - static const double root2 = sqrt(2.) ; - - double ln_k = TMath::Abs(TMath::Log(k)); - double ret = 0.5*( RooMath::erf( TMath::Log(x.max(rangeName)/m0)/(root2*ln_k) ) - RooMath::erf( TMath::Log(x.min(rangeName)/m0)/(root2*ln_k) ) ) ; + double ln_k = std::abs(_useStandardParametrization ? k : std::log(k)); + double scaledMin = _useStandardParametrization ? std::log(x.min(rangeName)) - m0 : std::log(x.min(rangeName) / m0); + double scaledMax = _useStandardParametrization ? std::log(x.max(rangeName)) - m0 : std::log(x.max(rangeName) / m0); + return 0.5 * (RooMath::erf(scaledMax / (root2 * ln_k)) - RooMath::erf(scaledMin / (root2 * ln_k))); +} - return ret ; +std::string RooLognormal::buildCallToAnalyticIntegral(int /*code*/, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string funcName = _useStandardParametrization ? "logNormalIntegralStandard" : "logNormalIntegral"; + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::" + funcName, x.min(rangeName), x.max(rangeName), m0, k); } //////////////////////////////////////////////////////////////////////////////// -Int_t RooLognormal::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool /*staticInitOK*/) const +Int_t RooLognormal::getGenerator(const RooArgSet &directVars, RooArgSet &generateVars, bool /*staticInitOK*/) const { - if (matchArgs(directVars,generateVars,x)) return 1 ; - return 0 ; + return matchArgs(directVars, generateVars, x) ? 1 : 0; } //////////////////////////////////////////////////////////////////////////////// -void RooLognormal::generateEvent(Int_t code) +void RooLognormal::generateEvent(Int_t /*code*/) { - R__ASSERT(code==1) ; - - double xgen ; - while(1) { - xgen = TMath::Exp(RooRandom::randomGenerator()->Gaus(TMath::Log(m0),TMath::Log(k))); - if (xgen<=x.max() && xgen>=x.min()) { - x = xgen ; - break; - } - } - - return; + const double ln_k = std::abs(_useStandardParametrization ? k : std::log(k)); + const double ln_m0 = _useStandardParametrization ? m0 : std::log(m0); + + double xgen; + while (true) { + xgen = std::exp(RooRandom::randomGenerator()->Gaus(ln_m0, ln_k)); + if (xgen <= x.max() && xgen >= x.min()) { + x = xgen; + break; + } + } + + return; } diff --git a/roofit/roofit/src/RooMomentMorph.cxx b/roofit/roofit/src/RooMomentMorph.cxx index 6ec54e7882446..2c0e5bbc3514c 100644 --- a/roofit/roofit/src/RooMomentMorph.cxx +++ b/roofit/roofit/src/RooMomentMorph.cxx @@ -33,7 +33,7 @@ ClassImp(RooMomentMorph); /// coverity[UNINIT_CTOR] RooMomentMorph::RooMomentMorph() - : _cacheMgr(this,10,true,true), _curNormSet(0), _mref(0), _M(0), _useHorizMorph(true) + : _cacheMgr(this,10,true,true), _curNormSet(nullptr), _mref(nullptr), _M(nullptr), _useHorizMorph(true) { } @@ -138,7 +138,7 @@ RooMomentMorph::RooMomentMorph(const char *name, const char *title, RooMomentMorph::RooMomentMorph(const RooMomentMorph& other, const char* name) : RooAbsPdf(other,name), _cacheMgr(other._cacheMgr,this), - _curNormSet(0), + _curNormSet(nullptr), m("m",this,other.m), _varList("varList",this,other._varList), _pdfList("pdfList",this,other._pdfList), diff --git a/roofit/roofit/src/RooMomentMorphFunc.cxx b/roofit/roofit/src/RooMomentMorphFunc.cxx index f8c834029ba33..5abd000a36ba9 100644 --- a/roofit/roofit/src/RooMomentMorphFunc.cxx +++ b/roofit/roofit/src/RooMomentMorphFunc.cxx @@ -30,7 +30,7 @@ ClassImp(RooMomentMorphFunc) //_____________________________________________________________________________ RooMomentMorphFunc::RooMomentMorphFunc() - : _cacheMgr(this, 10, true, true), _curNormSet(0), _mref(0), _M(0), _useHorizMorph(true) + : _cacheMgr(this, 10, true, true), _curNormSet(nullptr), _mref(nullptr), _M(nullptr), _useHorizMorph(true) { } @@ -121,7 +121,7 @@ RooMomentMorphFunc::RooMomentMorphFunc(const char *name, const char *title, RooA //_____________________________________________________________________________ RooMomentMorphFunc::RooMomentMorphFunc(const RooMomentMorphFunc &other, const char *name) - : RooAbsReal(other, name), _cacheMgr(other._cacheMgr, this), _curNormSet(0), m("m", this, other.m), + : RooAbsReal(other, name), _cacheMgr(other._cacheMgr, this), _curNormSet(nullptr), m("m", this, other.m), _varList("varList", this, other._varList), _pdfList("pdfList", this, other._pdfList), _setting(other._setting), _useHorizMorph(other._useHorizMorph) { @@ -176,14 +176,14 @@ void RooMomentMorphFunc::initialize() //_____________________________________________________________________________ RooMomentMorphFunc::CacheElem *RooMomentMorphFunc::getCache(const RooArgSet * /*nset*/) const { - CacheElem *cache = (CacheElem *)_cacheMgr.getObj(0, (RooArgSet *)0); + auto cache = static_cast(_cacheMgr.getObj(nullptr, static_cast(nullptr))); if (cache) { return cache; } Int_t nVar = _varList.getSize(); Int_t nPdf = _pdfList.getSize(); - RooAbsReal *null = 0; + RooAbsReal *null = nullptr; vector meanrv(nPdf * nVar, null); vector sigmarv(nPdf * nVar, null); vector myrms(nVar, null); @@ -213,7 +213,7 @@ RooMomentMorphFunc::CacheElem *RooMomentMorphFunc::getCache(const RooArgSet * /* ownedComps.add(*(RooRealVar *)(fracl.at(i))); } - RooRealSumFunc *theSumFunc = 0; + RooRealSumFunc *theSumFunc = nullptr; std::string sumfuncName = Form("%s_sumfunc", GetName()); if (_useHorizMorph) { @@ -306,7 +306,7 @@ RooMomentMorphFunc::CacheElem *RooMomentMorphFunc::getCache(const RooArgSet * /* // Store it in the cache cache = new CacheElem(*theSumFunc, *tracker, fracl); - _cacheMgr.setObj(0, 0, cache, 0); + _cacheMgr.setObj(nullptr, nullptr, cache, nullptr); return cache; } @@ -483,17 +483,17 @@ int RooMomentMorphFunc::idxmax(const double &mval) const //_____________________________________________________________________________ std::list *RooMomentMorphFunc::plotSamplingHint(RooAbsRealLValue &obs, double xlo, double xhi) const { - return sumFunc(0)->plotSamplingHint(obs, xlo, xhi); + return sumFunc(nullptr)->plotSamplingHint(obs, xlo, xhi); } //_____________________________________________________________________________ std::list *RooMomentMorphFunc::binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const { - return sumFunc(0)->binBoundaries(obs, xlo, xhi); + return sumFunc(nullptr)->binBoundaries(obs, xlo, xhi); } //_____________________________________________________________________________ bool RooMomentMorphFunc::isBinnedDistribution(const RooArgSet &obs) const { - return sumFunc(0)->isBinnedDistribution(obs); + return sumFunc(nullptr)->isBinnedDistribution(obs); } diff --git a/roofit/roofit/src/RooMomentMorphFuncND.cxx b/roofit/roofit/src/RooMomentMorphFuncND.cxx index 830e21c042635..75f59b0707e17 100644 --- a/roofit/roofit/src/RooMomentMorphFuncND.cxx +++ b/roofit/roofit/src/RooMomentMorphFuncND.cxx @@ -8,6 +8,7 @@ #include "RooMomentMorphFuncND.h" #include "RooAbsCategory.h" +#include "RooAddPdf.h" #include "RooRealIntegral.h" #include "RooRealConstant.h" #include "RooRealVar.h" @@ -22,6 +23,8 @@ #include "RooNumIntConfig.h" #include "RooHistPdf.h" +#include "RooFit/Detail/Algorithms.h" + #include "TMath.h" #include "TVector.h" #include "TMap.h" @@ -31,26 +34,26 @@ using namespace std; -// ClassImp for RooMomentMorphFuncND -ClassImp(RooMomentMorphFuncND) - - // ClassImp for RooMomentMorphFuncND - ClassImp(RooMomentMorphFuncND::Grid2) +ClassImp(RooMomentMorphFuncND); +ClassImp(RooMomentMorphFuncND::Grid2); - //_____________________________________________________________________________ - RooMomentMorphFuncND::RooMomentMorphFuncND() - : _cacheMgr(this, 10, true, true), _curNormSet(0), _M(0), _MSqr(0), _setting(RooMomentMorphFuncND::Linear), _useHorizMorph(true) +//_____________________________________________________________________________ +RooMomentMorphFuncND::RooMomentMorphFuncND() : _cacheMgr(this, 10, true, true), _setting(RooMomentMorphFuncND::Linear), _useHorizMorph(true) { - TRACE_CREATE + TRACE_CREATE; } //_____________________________________________________________________________ -RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, const RooArgList &parList, - const RooArgList &obsList, const Grid2 &referenceGrid, - const Setting &setting) - : RooAbsReal(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _referenceGrid(referenceGrid), - _pdfList("pdfList", "List of pdfs", this), _setting(setting), _useHorizMorph(true) +RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, const RooArgList &parList, const RooArgList &obsList, + const Grid2 &referenceGrid, const Setting &setting) + : RooMomentMorphFuncND::Base_t(name, title), + _cacheMgr(this, 10, true, true), + _parList("parList", "List of morph parameters", this), + _obsList("obsList", "List of observables", this), + _referenceGrid(referenceGrid), + _pdfList("pdfList", "List of pdfs", this), + _setting(setting), + _useHorizMorph(true) { // morph parameters initializeParameters(parList); @@ -63,15 +66,18 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, // general initialization initialize(); - TRACE_CREATE + TRACE_CREATE; } //_____________________________________________________________________________ -RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, RooAbsReal &_m, - const RooArgList &varList, const RooArgList &pdfList, - const TVectorD &mrefpoints, Setting setting) - : RooAbsReal(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _pdfList("pdfList", "List of pdfs", this), _setting(setting), +RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, + const RooArgList &pdfList, const TVectorD &mrefpoints, Setting setting) + : RooMomentMorphFuncND::Base_t(name, title), + _cacheMgr(this, 10, true, true), + _parList("parList", "List of morph parameters", this), + _obsList("obsList", "List of observables", this), + _pdfList("pdfList", "List of pdfs", this), + _setting(setting), _useHorizMorph(true) { // make reference grid @@ -81,7 +87,7 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, for (int i = 0; i < mrefpoints.GetNrows(); ++i) { for (int j = 0; j < grid.numBoundaries(); ++j) { if (mrefpoints[i] == grid.array()[j]) { - _referenceGrid.addPdf(*(RooAbsReal *)pdfList.at(i), j); + _referenceGrid.addPdf(*(Base_t *)pdfList.at(i), j); break; } } @@ -100,22 +106,25 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, // general initialization initialize(); - TRACE_CREATE + TRACE_CREATE; } //_____________________________________________________________________________ -RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, RooAbsReal &_m, - const RooArgList &varList, const RooArgList &pdfList, - const RooArgList &mrefList, Setting setting) - : RooAbsReal(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _pdfList("pdfList", "List of pdfs", this), _setting(setting), +RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, + const RooArgList &pdfList, const RooArgList &mrefList, Setting setting) + : RooMomentMorphFuncND::Base_t(name, title), + _cacheMgr(this, 10, true, true), + _parList("parList", "List of morph parameters", this), + _obsList("obsList", "List of observables", this), + _pdfList("pdfList", "List of pdfs", this), + _setting(setting), _useHorizMorph(true) { // make reference grid TVectorD mrefpoints(mrefList.getSize()); Int_t i = 0; for (auto *mref : mrefList) { - if (!dynamic_cast(mref)) { + if (!dynamic_cast(mref)) { coutE(InputArguments) << "RooMomentMorphFuncND::ctor(" << GetName() << ") ERROR: mref " << mref->GetName() << " is not of type RooAbsReal" << endl; throw string("RooMomentMorphFuncND::ctor() ERROR mref is not of type RooAbsReal"); @@ -124,8 +133,8 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, coutW(InputArguments) << "RooMomentMorphFuncND::ctor(" << GetName() << ") WARNING mref point " << i << " is not a constant, taking a snapshot of its value" << endl; } - mrefpoints[i] = static_cast(mref)->getVal(); - ++i; + mrefpoints[i] = static_cast(mref)->getVal(); + i++; } RooBinning grid(mrefpoints.GetNrows() - 1, mrefpoints.GetMatrixArray()); @@ -133,7 +142,7 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, for (i = 0; i < mrefpoints.GetNrows(); ++i) { for (int j = 0; j < grid.numBoundaries(); ++j) { if (mrefpoints[i] == grid.array()[j]) { - _referenceGrid.addPdf(static_cast(pdfList[i]), j); + _referenceGrid.addPdf(static_cast(pdfList[i]), j); break; } } @@ -152,32 +161,30 @@ RooMomentMorphFuncND::RooMomentMorphFuncND(const char *name, const char *title, // general initialization initialize(); - TRACE_CREATE + TRACE_CREATE; } //_____________________________________________________________________________ RooMomentMorphFuncND::RooMomentMorphFuncND(const RooMomentMorphFuncND &other, const char *name) - : RooAbsReal(other, name), _cacheMgr(other._cacheMgr, this), _curNormSet(0), - _parList("parList", this, other._parList), _obsList("obsList", this, other._obsList), - _referenceGrid(other._referenceGrid), _pdfList("pdfList", this, other._pdfList), _M(0), _MSqr(0), - _setting(other._setting), _useHorizMorph(other._useHorizMorph) + : RooMomentMorphFuncND::Base_t(other, name), + _cacheMgr(other._cacheMgr, this), + _parList("parList", this, other._parList), + _obsList("obsList", this, other._obsList), + _referenceGrid(other._referenceGrid), + _pdfList("pdfList", this, other._pdfList), + _setting(other._setting), + _useHorizMorph(other._useHorizMorph) { - // general initialization initialize(); - TRACE_CREATE + TRACE_CREATE; } //_____________________________________________________________________________ RooMomentMorphFuncND::~RooMomentMorphFuncND() { - if (_M) - delete _M; - if (_MSqr) - delete _MSqr; - - TRACE_DESTROY + TRACE_DESTROY; } //_____________________________________________________________________________ @@ -206,41 +213,6 @@ void RooMomentMorphFuncND::initializeObservables(const RooArgList &obsList) } } -//_____________________________________________________________________________ -// from http://stackoverflow.com/a/5279601 -template -void RooMomentMorphFuncND::cartesian_product(vector> &out, vector> &in) -{ - vector> vd; - - for (typename vector>::const_iterator it = in.begin(); it != in.end(); ++it) { - Digits d = {(*it).begin(), (*it).end(), (*it).begin()}; - vd.push_back(d); - } - - while (1) { - vector result; - for (typename vector>::const_iterator it = vd.begin(); it != vd.end(); ++it) { - result.push_back(*(it->me)); - } - out.push_back(result); - - for (typename vector>::iterator it = vd.begin();;) { - ++(it->me); - if (it->me == it->end) { - if (it + 1 == vd.end()) { - return; - } else { - it->me = it->begin; - ++it; - } - } else { - break; - } - } - } -} - //_____________________________________________________________________________ void RooMomentMorphFuncND::initialize() { @@ -268,8 +240,8 @@ void RooMomentMorphFuncND::initialize() } // Transformation matrix for NonLinear settings - _M = new TMatrixD(nPdf, nPdf); - _MSqr = new TMatrixD(depth, depth); + _M = std::make_unique(nPdf, nPdf); + _MSqr = std::make_unique(depth, depth); if (_setting == NonLinear || _setting == NonLinearPosFractions || _setting == NonLinearLinFractions) { TMatrixD M(nPdf, nPdf); @@ -293,7 +265,7 @@ void RooMomentMorphFuncND::initialize() } vector> output; - cartesian_product(output, powers); + RooFit::Detail::cartesianProduct(output, powers); int nCombs = output.size(); for (int k = 0; k < nPdf; ++k) { @@ -320,17 +292,23 @@ void RooMomentMorphFuncND::initialize() //_____________________________________________________________________________ RooMomentMorphFuncND::Grid2::Grid2(const RooMomentMorphFuncND::Grid2 &other) - : _grid(other._grid), _pdfList(other._pdfList), _pdfMap(other._pdfMap), _nref(other._nref) + : _pdfList(other._pdfList), _pdfMap(other._pdfMap), _nref(other._nref) { + for (unsigned int i = 0; i < other._grid.size(); i++) { + _grid.push_back(other._grid[i]->clone()); + } } //_____________________________________________________________________________ RooMomentMorphFuncND::Grid2::~Grid2() { + for (RooAbsBinning *binning : _grid) { + delete binning; + } } //_____________________________________________________________________________ -void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x) +void RooMomentMorphFuncND::Grid2::addPdf(const RooMomentMorphFuncND::Base_t &pdf, int bin_x) { vector thisBoundaries; vector thisBoundaryCoordinates; @@ -342,7 +320,7 @@ void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x) } //_____________________________________________________________________________ -void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x, int bin_y) +void RooMomentMorphFuncND::Grid2::addPdf(const RooMomentMorphFuncND::Base_t &pdf, int bin_x, int bin_y) { vector thisBoundaries; vector thisBoundaryCoordinates; @@ -356,7 +334,7 @@ void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x, int b } //_____________________________________________________________________________ -void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x, int bin_y, int bin_z) +void RooMomentMorphFuncND::Grid2::addPdf(const RooMomentMorphFuncND::Base_t &pdf, int bin_x, int bin_y, int bin_z) { vector thisBoundaries; vector thisBoundaryCoordinates; @@ -372,7 +350,7 @@ void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, int bin_x, int b } //_____________________________________________________________________________ -void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, vector bins) +void RooMomentMorphFuncND::Grid2::addPdf(const RooMomentMorphFuncND::Base_t &pdf, vector bins) { vector thisBoundaryCoordinates; int nBins = bins.size(); @@ -387,7 +365,7 @@ void RooMomentMorphFuncND::Grid2::addPdf(const RooAbsReal &pdf, vector bins //_____________________________________________________________________________ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet * /*nset*/) const { - CacheElem *cache = static_cast(_cacheMgr.getObj(0, (RooArgSet *)0)); + auto cache = static_cast(_cacheMgr.getObj(nullptr, static_cast(nullptr))); if (cache) { return cache; } @@ -395,7 +373,7 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet int nObs = _obsList.getSize(); int nPdf = _referenceGrid._pdfList.getSize(); - RooAbsReal *null = 0; + RooAbsReal *null = nullptr; vector meanrv(nPdf * nObs, null); vector sigmarv(nPdf * nObs, null); vector myrms(nObs, null); @@ -415,7 +393,7 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet for (int i = 0; i < 3 * nPdf; ++i) { string fracName = Form("frac_%d", i); - double initval = 0.0; + double initval = _isPdfMode ? 1.0 : 0.0; RooRealVar *frac = new RooRealVar(fracName.c_str(), fracName.c_str(), initval); // to be set later fracl.add(*frac); @@ -428,17 +406,17 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet ownedComps.add(*(RooRealVar *)(fracl.at(i))); } - RooRealSumFunc *theSumFunc = 0; - string sumfuncName = Form("%s_sumfunc", GetName()); + RooAbsReal *theSum = nullptr; + string sumName = Form("%s_sum", GetName()); + RooArgList transPdfList; if (_useHorizMorph) { // mean and sigma RooArgList obsList(_obsList); for (int i = 0; i < nPdf; ++i) { for (int j = 0; j < nObs; ++j) { - RooAbsMoment *mom = nObs == 1 - ? ((RooAbsReal *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j)) - : ((RooAbsReal *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j), obsList); + RooAbsMoment *mom = nObs == 1 ? ((Base_t *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j)) + : ((Base_t *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j), obsList); mom->setLocalNoDirtyInhibit(true); mom->mean()->setLocalNoDirtyInhibit(true); @@ -450,7 +428,7 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet } } - // slope and offsets (to be set later, depend on nuisance parameters) + // slope and offset (to be set later, depend on nuisance parameters) for (int j = 0; j < nObs; ++j) { RooArgList meanList("meanList"); RooArgList rmsList("rmsList"); @@ -466,17 +444,16 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet } // construction of unit pdfs - RooArgList transPdfList; Int_t i = 0; - for (auto const *pdf : static_range_cast(_pdfList)) { + for (auto const *pdf : static_range_cast(_pdfList)) { string pdfName = Form("pdf_%d", i); RooCustomizer cust(*pdf, pdfName.c_str()); Int_t j = 0; for (auto *var : static_range_cast(obsList)) { - // slope and offsets formulas + // slope and offset formulas string slopeName = Form("%s_slope_%d_%d", GetName(), i, j); string offsetName = Form("%s_offset_%d_%d", GetName(), i, j); @@ -499,30 +476,33 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet cust.replaceArg(*var, *transVar[sij(i, j)]); ++j; } - transPdf[i] = (RooAbsReal *)cust.build(); + transPdf[i] = static_cast(cust.build()); transPdfList.add(*transPdf[i]); ownedComps.add(*transPdf[i]); ++i; } + } - // sum pdf - theSumFunc = new RooRealSumFunc(sumfuncName.c_str(), sumfuncName.c_str(), transPdfList, coefList); + // sum pdf + RooArgList const &pdfList = _useHorizMorph ? transPdfList : static_cast(_pdfList); + if (_isPdfMode) { + theSum = new RooAddPdf(sumName.c_str(), sumName.c_str(), pdfList, coefList); } else { - theSumFunc = new RooRealSumFunc(sumfuncName.c_str(), sumfuncName.c_str(), _pdfList, coefList); + theSum = new RooRealSumFunc(sumName.c_str(), sumName.c_str(), pdfList, coefList); } // *** WVE this is important *** this declares that frac effectively depends on the morphing parameters // This will prevent the likelihood optimizers from erroneously declaring terms constant - theSumFunc->addServerList((RooAbsCollection &)_parList); - theSumFunc->addOwnedComponents(ownedComps); + theSum->addServerList((RooAbsCollection &)_parList); + theSum->addOwnedComponents(ownedComps); // change tracker for fraction parameters string trackerName = Form("%s_frac_tracker", GetName()); RooChangeTracker *tracker = new RooChangeTracker(trackerName.c_str(), trackerName.c_str(), _parList, true); // Store it in the cache - cache = new CacheElem(*theSumFunc, *tracker, fracl); - _cacheMgr.setObj(0, 0, cache, 0); + cache = new CacheElem(*theSum, *tracker, fracl); + _cacheMgr.setObj(nullptr, nullptr, cache, nullptr); return cache; } @@ -530,33 +510,33 @@ RooMomentMorphFuncND::CacheElem *RooMomentMorphFuncND::getCache(const RooArgSet //_____________________________________________________________________________ RooArgList RooMomentMorphFuncND::CacheElem::containedArgs(Action) { - return RooArgList(*_sumFunc, *_tracker); + return RooArgList(*_sum, *_tracker); } //_____________________________________________________________________________ RooMomentMorphFuncND::CacheElem::~CacheElem() { - delete _sumFunc; + delete _sum; delete _tracker; } //_____________________________________________________________________________ -double RooMomentMorphFuncND::getVal(const RooArgSet *set) const +double RooMomentMorphFuncND::getValV(const RooArgSet *set) const { - // Special version of getVal() overrides RooAbsReal::getVal() to save value of current normalization set + // Special version of getValV() overrides Base_t::getValV() to save value of current normalization set _curNormSet = set ? (RooArgSet *)set : (RooArgSet *)&_obsList; - return RooAbsReal::getVal(set); + return Base_t::getValV(set); } //_____________________________________________________________________________ -RooAbsReal *RooMomentMorphFuncND::sumFunc(const RooArgSet *nset) +RooMomentMorphFuncND::Base_t *RooMomentMorphFuncND::sumFunc(const RooArgSet *nset) { CacheElem *cache = getCache(nset ? nset : _curNormSet); if (cache->_tracker->hasChanged(true)) { cache->calculateFractions(*this, false); // verbose turned off } - return cache->_sumFunc; + return cache->_sum; } //_____________________________________________________________________________ @@ -568,7 +548,7 @@ double RooMomentMorphFuncND::evaluate() const cache->calculateFractions(*this, false); // verbose turned off } - double ret = cache->_sumFunc->getVal(_obsList.nset()); + double ret = cache->_sum->getVal(_obsList.nset()); return ret; } @@ -585,45 +565,6 @@ const RooRealVar *RooMomentMorphFuncND::CacheElem::frac(int i) const return (RooRealVar *)(_frac.at(i)); } -//_____________________________________________________________________________ -// from http://stackoverflow.com/a/5097100/8747 -template -bool RooMomentMorphFuncND::next_combination(const Iterator first, Iterator k, const Iterator last) -{ - if ((first == last) || (first == k) || (last == k)) { - return false; - } - Iterator itr1 = first; - Iterator itr2 = last; - ++itr1; - if (last == itr1) { - return false; - } - itr1 = last; - --itr1; - itr1 = k; - --itr2; - while (first != itr1) { - if (*--itr1 < *itr2) { - Iterator j = k; - while (!(*itr1 < *j)) ++j; - iter_swap(itr1, j); - ++itr1; - ++j; - itr2 = k; - rotate(itr1, j, last); - while (last != j) { - ++j; - ++itr2; - } - rotate(k, itr2, last); - return true; - } - } - rotate(first, k, last); - return false; -} - //_____________________________________________________________________________ void RooMomentMorphFuncND::CacheElem::calculateFractions(const RooMomentMorphFuncND &self, bool verbose) const { @@ -651,7 +592,7 @@ void RooMomentMorphFuncND::CacheElem::calculateFractions(const RooMomentMorphFun } vector> output; - cartesian_product(output, powers); + RooFit::Detail::cartesianProduct(output, powers); int nCombs = output.size(); vector deltavec(nPdf, 1.0); @@ -715,10 +656,10 @@ void RooMomentMorphFuncND::CacheElem::calculateFractions(const RooMomentMorphFun ((RooRealVar *)frac(2 * nPdf + i))->setVal(initval); } - vector mtmp; + std::vector mtmp; // loop over parList - for(auto * m : static_range_cast(self._parList)) { + for (auto *m : static_range_cast(self._parList)) { mtmp.push_back(m->getVal()); } @@ -742,7 +683,7 @@ void RooMomentMorphFuncND::CacheElem::calculateFractions(const RooMomentMorphFun } deltavec[nperm + 1] = dtmp; nperm++; - } while (next_combination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); + } while (RooFit::Detail::nextCombination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); } double origFrac1(0.), origFrac2(0.); @@ -781,14 +722,14 @@ void RooMomentMorphFuncND::findShape(const vector &x) const int nRef = _referenceGrid._nref.size(); // Find hypercube enclosing the location to morph to - bool isEnclosed = true; - for (int i = 0; i < nPar; i++) { - if (x[i] < _referenceGrid._grid[i]->lowBound()) - isEnclosed = false; - if (x[i] > _referenceGrid._grid[i]->highBound()) - isEnclosed = false; - } - (void)isEnclosed; // Silence warning for isEnclosed being unused. + // bool isEnclosed = true; + // for (int i = 0; i < nPar; i++) { + // if (x[i] < _referenceGrid._grid[i]->lowBound()) + // isEnclosed = false; + // if (x[i] > _referenceGrid._grid[i]->highBound()) + // isEnclosed = false; + // } + // cout << "isEnclosed = " << isEnclosed << endl; int depth = TMath::Power(2, nPar); @@ -803,7 +744,7 @@ void RooMomentMorphFuncND::findShape(const vector &x) const } vector> output; - cartesian_product(output, boundaries); + RooFit::Detail::cartesianProduct(output, boundaries); _squareVec = output; for (int isq = 0; isq < depth; isq++) { @@ -848,7 +789,7 @@ void RooMomentMorphFuncND::findShape(const vector &x) const } M(k, nperm + 1) = dtmp; nperm++; - } while (next_combination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); + } while (RooFit::Detail::nextCombination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); } } diff --git a/roofit/roofit/src/RooMomentMorphND.cxx b/roofit/roofit/src/RooMomentMorphND.cxx deleted file mode 100644 index 159340a02731d..0000000000000 --- a/roofit/roofit/src/RooMomentMorphND.cxx +++ /dev/null @@ -1,872 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * * - * This code was autogenerated by RooClassFactory * - *****************************************************************************/ - -#include "Riostream.h" - -#include "RooMomentMorphND.h" -#include "RooAbsCategory.h" -#include "RooRealIntegral.h" -#include "RooRealConstant.h" -#include "RooRealVar.h" -#include "RooFormulaVar.h" -#include "RooCustomizer.h" -#include "RooAddPdf.h" -#include "RooAddition.h" -#include "RooAbsMoment.h" -#include "RooMoment.h" -#include "RooLinearVar.h" -#include "RooChangeTracker.h" -#include "RooNumIntConfig.h" -#include "RooHistPdf.h" - -#include "TMath.h" -#include "TVector.h" -#include "TMap.h" - -#include -#include - -using namespace std; - -ClassImp(RooMomentMorphND) - -//_____________________________________________________________________________ -RooMomentMorphND::RooMomentMorphND() - : _cacheMgr(this, 10, true, true), _curNormSet(0), _M(0), _MSqr(0), _setting(RooMomentMorphND::Linear), _useHorizMorph(true) -{ - TRACE_CREATE -} - -//_____________________________________________________________________________ -RooMomentMorphND::RooMomentMorphND(const char *name, const char *title, const RooArgList &parList, - const RooArgList &obsList, const Grid &referenceGrid, const Setting &setting) - : RooAbsPdf(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _referenceGrid(referenceGrid), - _pdfList("pdfList", "List of pdfs", this), _setting(setting), _useHorizMorph(true) -{ - // morph parameters - initializeParameters(parList); - - // observables - initializeObservables(obsList); - - _pdfList.add(_referenceGrid._pdfList); - - // general initialization - initialize(); - - TRACE_CREATE -} - -//_____________________________________________________________________________ -RooMomentMorphND::RooMomentMorphND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, - const RooArgList &pdfList, const TVectorD &mrefpoints, Setting setting) - : RooAbsPdf(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _pdfList("pdfList", "List of pdfs", this), _setting(setting), - _useHorizMorph(true) -{ - // make reference grid - RooBinning grid(mrefpoints.GetNrows() - 1, mrefpoints.GetMatrixArray()); - _referenceGrid.addBinning(grid); - - for (int i = 0; i < mrefpoints.GetNrows(); ++i) { - for (int j = 0; j < grid.numBoundaries(); ++j) { - if (mrefpoints[i] == grid.array()[j]) { - _referenceGrid.addPdf(*(RooAbsPdf *)pdfList.at(i), j); - break; - } - } - } - - _pdfList.add(_referenceGrid._pdfList); - - // morph parameters - RooArgList parList; - parList.add(_m); - initializeParameters(parList); - - // observables - initializeObservables(varList); - - // general initialization - initialize(); - - TRACE_CREATE -} - -//_____________________________________________________________________________ -RooMomentMorphND::RooMomentMorphND(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList, - const RooArgList &pdfList, const RooArgList &mrefList, Setting setting) - : RooAbsPdf(name, title), _cacheMgr(this, 10, true, true), _parList("parList", "List of morph parameters", this), - _obsList("obsList", "List of observables", this), _pdfList("pdfList", "List of pdfs", this), _setting(setting), - _useHorizMorph(true) -{ - // make reference grid - TVectorD mrefpoints(mrefList.getSize()); - Int_t i = 0; - for (auto *mref : mrefList) { - if (!dynamic_cast(mref)) { - coutE(InputArguments) << "RooMomentMorphND::ctor(" << GetName() << ") ERROR: mref " << mref->GetName() - << " is not of type RooAbsReal" << endl; - throw string("RooMomentMorphND::ctor() ERROR mref is not of type RooAbsReal"); - } - if (!dynamic_cast(mref)) { - coutW(InputArguments) << "RooMomentMorphND::ctor(" << GetName() << ") WARNING mref point " << i - << " is not a constant, taking a snapshot of its value" << endl; - } - mrefpoints[i] = static_cast(mref)->getVal(); - i++; - } - - RooBinning grid(mrefpoints.GetNrows() - 1, mrefpoints.GetMatrixArray()); - _referenceGrid.addBinning(grid); - - for (i = 0; i < mrefpoints.GetNrows(); ++i) { - for (int j = 0; j < grid.numBoundaries(); ++j) { - if (mrefpoints[i] == grid.array()[j]) { - _referenceGrid.addPdf(static_cast(pdfList[i]), j); - break; - } - } - } - - _pdfList.add(_referenceGrid._pdfList); - - // morph parameters - RooArgList parList; - parList.add(_m); - initializeParameters(parList); - - // observables - initializeObservables(varList); - - // general initialization - initialize(); - - TRACE_CREATE -} - -//_____________________________________________________________________________ -RooMomentMorphND::RooMomentMorphND(const RooMomentMorphND &other, const char *name) - : RooAbsPdf(other, name), _cacheMgr(other._cacheMgr, this), _curNormSet(0), - _parList("parList", this, other._parList), _obsList("obsList", this, other._obsList), - _referenceGrid(other._referenceGrid), _pdfList("pdfList", this, other._pdfList), _M(0), _MSqr(0), - _setting(other._setting), _useHorizMorph(other._useHorizMorph) -{ - // general initialization - initialize(); - - TRACE_CREATE -} - -//_____________________________________________________________________________ -RooMomentMorphND::~RooMomentMorphND() -{ - if (_M) - delete _M; - if (_MSqr) - delete _MSqr; - - TRACE_DESTROY -} - -//_____________________________________________________________________________ -void RooMomentMorphND::initializeParameters(const RooArgList &parList) -{ - for (auto *par : parList) { - if (!dynamic_cast(par)) { - coutE(InputArguments) << "RooMomentMorphND::ctor(" << GetName() << ") ERROR: parameter " << par->GetName() - << " is not of type RooAbsReal" << endl; - throw string("RooMomentMorphND::initializeParameters() ERROR parameter is not of type RooAbsReal"); - } - _parList.add(*par); - } -} - -//_____________________________________________________________________________ -void RooMomentMorphND::initializeObservables(const RooArgList &obsList) -{ - for (auto *var : obsList){ - if (!dynamic_cast(var)) { - coutE(InputArguments) << "RooMomentMorphND::ctor(" << GetName() << ") ERROR: variable " << var->GetName() - << " is not of type RooAbsReal" << endl; - throw string("RooMomentMorphND::initializeObservables() ERROR variable is not of type RooAbsReal"); - } - _obsList.add(*var); - } -} - -//_____________________________________________________________________________ -// from http://stackoverflow.com/a/5279601 -template -struct Digits { - typename vector::const_iterator begin; - typename vector::const_iterator end; - typename vector::const_iterator me; -}; - -template -inline void cartesian_product(vector> &out, vector> &in) -{ - vector> vd; - - for (typename vector>::const_iterator it = in.begin(); it != in.end(); ++it) { - Digits d = {(*it).begin(), (*it).end(), (*it).begin()}; - vd.push_back(d); - } - - while (1) { - vector result; - for (typename vector>::const_iterator it = vd.begin(); it != vd.end(); ++it) { - result.push_back(*(it->me)); - } - out.push_back(result); - - for (typename vector>::iterator it = vd.begin();;) { - ++(it->me); - if (it->me == it->end) { - if (it + 1 == vd.end()) { - return; - } else { - it->me = it->begin; - ++it; - } - } else { - break; - } - } - } -} - -//_____________________________________________________________________________ -void RooMomentMorphND::initialize() -{ - for (vector::iterator itr = _referenceGrid._grid.begin(); itr != _referenceGrid._grid.end(); - ++itr) { - _referenceGrid._nnuis.push_back((*itr)->numBins() + 1); - } - - int nPar = _parList.getSize(); - int nDim = _referenceGrid._grid.size(); - int nPdf = _referenceGrid._pdfList.getSize(); - int nRef = _referenceGrid._nref.size(); - int depth = TMath::Power(2, nPar); - - if (nPar != nDim) { - coutE(InputArguments) << "RooMomentMorphND::initialize(" << GetName() << ") ERROR: nPar != nDim" - << ": " << nPar << " !=" << nDim << endl; - assert(0); - } - - if (nPdf != nRef) { - coutE(InputArguments) << "RooMomentMorphND::initialize(" << GetName() << ") ERROR: nPdf != nRef" - << ": " << nPdf << " !=" << nRef << endl; - assert(0); - } - - // Transformation matrix for NonLinear settings - _M = new TMatrixD(nPdf, nPdf); - _MSqr = new TMatrixD(depth, depth); - if (_setting == NonLinear || _setting == NonLinearPosFractions || _setting == NonLinearLinFractions) { - TMatrixD M(nPdf, nPdf); - - vector> dm(nPdf); - for (int k = 0; k < nPdf; ++k) { - vector dm2; - for (int idim = 0; idim < nPar; idim++) { - double delta = _referenceGrid._nref[k][idim] - _referenceGrid._nref[0][idim]; - dm2.push_back(delta); - } - dm[k] = dm2; - } - - vector> powers; - for (int idim = 0; idim < nPar; idim++) { - vector xtmp; - for (int ix = 0; ix < _referenceGrid._nnuis[idim]; ix++) { - xtmp.push_back(ix); - } - powers.push_back(xtmp); - } - - vector> output; - cartesian_product(output, powers); - int nCombs = output.size(); - - for (int k = 0; k < nPdf; ++k) { - int nperm = 0; - for (int i = 0; i < nCombs; i++) { - double tmpDm = 1.0; - for (int ix = 0; ix < nPar; ix++) { - double delta = dm[k][ix]; - tmpDm *= TMath::Power(delta, static_cast(output[i][ix])); - } - M(k, nperm) = tmpDm; - nperm++; - } - } - - // M.Print(); - (*_M) = M.Invert(); - } - - // Resize transformation vectors - _squareVec.resize(TMath::Power(2, nPar)); - _squareIdx.resize(TMath::Power(2, nPar)); -} - -//_____________________________________________________________________________ -RooMomentMorphND::Grid::Grid(const RooMomentMorphND::Grid &other) - : _grid(other._grid), _pdfList(other._pdfList), _pdfMap(other._pdfMap), _nref(other._nref) -{ -} - -//_____________________________________________________________________________ -RooMomentMorphND::Grid::~Grid() -{ -} - -//_____________________________________________________________________________ -void RooMomentMorphND::Grid::addPdf(const RooAbsPdf &pdf, int bin_x) -{ - vector thisBoundaries; - vector thisBoundaryCoordinates; - thisBoundaries.push_back(bin_x); - thisBoundaryCoordinates.push_back(_grid[0]->array()[bin_x]); - _pdfList.add(pdf); - _pdfMap[thisBoundaries] = _pdfList.getSize() - 1; - _nref.push_back(thisBoundaryCoordinates); -} - -//_____________________________________________________________________________ -void RooMomentMorphND::Grid::addPdf(const RooAbsPdf &pdf, int bin_x, int bin_y) -{ - vector thisBoundaries; - vector thisBoundaryCoordinates; - thisBoundaries.push_back(bin_x); - thisBoundaryCoordinates.push_back(_grid[0]->array()[bin_x]); - thisBoundaries.push_back(bin_y); - thisBoundaryCoordinates.push_back(_grid[1]->array()[bin_y]); - _pdfList.add(pdf); - _pdfMap[thisBoundaries] = _pdfList.getSize() - 1; - _nref.push_back(thisBoundaryCoordinates); -} - -//_____________________________________________________________________________ -void RooMomentMorphND::Grid::addPdf(const RooAbsPdf &pdf, int bin_x, int bin_y, int bin_z) -{ - vector thisBoundaries; - vector thisBoundaryCoordinates; - thisBoundaries.push_back(bin_x); - thisBoundaryCoordinates.push_back(_grid[0]->array()[bin_x]); - thisBoundaries.push_back(bin_y); - thisBoundaryCoordinates.push_back(_grid[1]->array()[bin_y]); - thisBoundaries.push_back(bin_z); - thisBoundaryCoordinates.push_back(_grid[2]->array()[bin_z]); - _pdfList.add(pdf); - _pdfMap[thisBoundaries] = _pdfList.getSize() - 1; - _nref.push_back(thisBoundaryCoordinates); -} - -//_____________________________________________________________________________ -void RooMomentMorphND::Grid::addPdf(const RooAbsPdf &pdf, vector bins) -{ - vector thisBoundaryCoordinates; - int nBins = bins.size(); - for (int i = 0; i < nBins; i++) { - thisBoundaryCoordinates.push_back(_grid[i]->array()[bins[i]]); - } - _pdfList.add(pdf); - _pdfMap[bins] = _pdfList.getSize() - 1; - _nref.push_back(thisBoundaryCoordinates); -} - -//_____________________________________________________________________________ -RooMomentMorphND::CacheElem *RooMomentMorphND::getCache(const RooArgSet * /*nset*/) const -{ - CacheElem *cache = static_cast(_cacheMgr.getObj(0, (RooArgSet *)0)); - if (cache) { - return cache; - } - - int nObs = _obsList.getSize(); - int nPdf = _referenceGrid._pdfList.getSize(); - - RooAbsReal *null = 0; - vector meanrv(nPdf * nObs, null); - vector sigmarv(nPdf * nObs, null); - vector myrms(nObs, null); - vector mypos(nObs, null); - vector slope(nPdf * nObs, null); - vector offsetrv(nPdf * nObs, null); - vector transVar(nPdf * nObs, null); - vector transPdf(nPdf, null); - - RooArgSet ownedComps; - RooArgList fracl; - - // fraction parameters - RooArgList coefList("coefList"); // fractions multiplied with input pdfs - RooArgList coefList2("coefList2"); // fractions multiplied with mean position of observable contribution - RooArgList coefList3("coefList3"); // fractions multiplied with rms position of observable contribution - - for (int i = 0; i < 3 * nPdf; ++i) { - string fracName = Form("frac_%d", i); - RooRealVar *frac = new RooRealVar(fracName.c_str(), fracName.c_str(), /*value=*/1.); // to be set later - - fracl.add(*frac); - if (i < nPdf) - coefList.add(*(RooRealVar *)(fracl.at(i))); - else if (i < 2 * nPdf) - coefList2.add(*(RooRealVar *)(fracl.at(i))); - else - coefList3.add(*(RooRealVar *)(fracl.at(i))); - ownedComps.add(*(RooRealVar *)(fracl.at(i))); - } - - RooAddPdf *theSumPdf = 0; - string sumpdfName = Form("%s_sumpdf", GetName()); - - if (_useHorizMorph) { - // mean and sigma - RooArgList obsList(_obsList); - for (int i = 0; i < nPdf; ++i) { - for (int j = 0; j < nObs; ++j) { - RooAbsMoment *mom = nObs == 1 ? ((RooAbsPdf *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j)) - : ((RooAbsPdf *)_pdfList.at(i))->sigma((RooRealVar &)*obsList.at(j), obsList); - - mom->setLocalNoDirtyInhibit(true); - mom->mean()->setLocalNoDirtyInhibit(true); - - sigmarv[sij(i, j)] = mom; - meanrv[sij(i, j)] = mom->mean(); - - ownedComps.add(*sigmarv[sij(i, j)]); - } - } - - // slope and offset (to be set later, depend on nuisance parameters) - for (int j = 0; j < nObs; ++j) { - RooArgList meanList("meanList"); - RooArgList rmsList("rmsList"); - for (int i = 0; i < nPdf; ++i) { - meanList.add(*meanrv[sij(i, j)]); - rmsList.add(*sigmarv[sij(i, j)]); - } - string myrmsName = Form("%s_rms_%d", GetName(), j); - string myposName = Form("%s_pos_%d", GetName(), j); - mypos[j] = new RooAddition(myposName.c_str(), myposName.c_str(), meanList, coefList2); - myrms[j] = new RooAddition(myrmsName.c_str(), myrmsName.c_str(), rmsList, coefList3); - ownedComps.add(RooArgSet(*myrms[j], *mypos[j])); - } - - // construction of unit pdfs - RooArgList transPdfList; - - Int_t i = 0; - for (auto const *pdf : static_range_cast(_pdfList)) { - - string pdfName = Form("pdf_%d", i); - RooCustomizer cust(*pdf, pdfName.c_str()); - - Int_t j = 0; - for (auto *var : static_range_cast(obsList)) { - // slope and offset formulas - string slopeName = Form("%s_slope_%d_%d", GetName(), i, j); - string offsetName = Form("%s_offset_%d_%d", GetName(), i, j); - - slope[sij(i, j)] = - new RooFormulaVar(slopeName.c_str(), "@0/@1", RooArgList(*sigmarv[sij(i, j)], *myrms[j])); - offsetrv[sij(i, j)] = new RooFormulaVar(offsetName.c_str(), "@0-(@1*@2)", - RooArgList(*meanrv[sij(i, j)], *mypos[j], *slope[sij(i, j)])); - ownedComps.add(RooArgSet(*slope[sij(i, j)], *offsetrv[sij(i, j)])); - - // linear transformations, so pdf can be renormalized easily - string transVarName = Form("%s_transVar_%d_%d", GetName(), i, j); - transVar[sij(i, j)] = new RooLinearVar(transVarName.c_str(), transVarName.c_str(), *var, *slope[sij(i, j)], - *offsetrv[sij(i, j)]); - - // *** WVE this is important *** this declares that frac effectively depends on the morphing parameters - // This will prevent the likelihood optimizers from erroneously declaring terms constant - transVar[sij(i, j)]->addServerList((RooAbsCollection &)_parList); - - ownedComps.add(*transVar[sij(i, j)]); - cust.replaceArg(*var, *transVar[sij(i, j)]); - ++j; - } - transPdf[i] = static_cast(cust.build()); - transPdfList.add(*transPdf[i]); - ownedComps.add(*transPdf[i]); - ++i; - } - - // sum pdf - theSumPdf = new RooAddPdf(sumpdfName.c_str(), sumpdfName.c_str(), transPdfList, coefList); - } else { - theSumPdf = new RooAddPdf(sumpdfName.c_str(), sumpdfName.c_str(), _pdfList, coefList); - } - - // *** WVE this is important *** this declares that frac effectively depends on the morphing parameters - // This will prevent the likelihood optimizers from erroneously declaring terms constant - theSumPdf->addServerList((RooAbsCollection &)_parList); - theSumPdf->addOwnedComponents(ownedComps); - - // change tracker for fraction parameters - string trackerName = Form("%s_frac_tracker", GetName()); - RooChangeTracker *tracker = new RooChangeTracker(trackerName.c_str(), trackerName.c_str(), _parList, true); - - // Store it in the cache - cache = new CacheElem(*theSumPdf, *tracker, fracl); - _cacheMgr.setObj(0, 0, cache, 0); - - cache->calculateFractions(*this, false); - return cache; -} - -//_____________________________________________________________________________ -RooArgList RooMomentMorphND::CacheElem::containedArgs(Action) -{ - return RooArgList(*_sumPdf, *_tracker); -} - -//_____________________________________________________________________________ -RooMomentMorphND::CacheElem::~CacheElem() -{ - delete _sumPdf; - delete _tracker; -} - -//_____________________________________________________________________________ -double RooMomentMorphND::getVal(const RooArgSet *set) const -{ - // Special version of getVal() overrides RooAbsReal::getVal() to save value of current normalization set - _curNormSet = set ? (RooArgSet *)set : (RooArgSet *)&_obsList; - return RooAbsPdf::getVal(set); -} - -//_____________________________________________________________________________ -RooAbsPdf *RooMomentMorphND::sumPdf(const RooArgSet *nset) -{ - CacheElem *cache = getCache(nset ? nset : _curNormSet); - - if (cache->_tracker->hasChanged(true)) { - cache->calculateFractions(*this, false); // verbose turned off - } - return cache->_sumPdf; -} - -//_____________________________________________________________________________ -double RooMomentMorphND::evaluate() const -{ - CacheElem *cache = getCache(_curNormSet); - - if (cache->_tracker->hasChanged(true)) { - cache->calculateFractions(*this, false); // verbose turned off - } - - double ret = cache->_sumPdf->getVal(_obsList.nset()); - - return ret; -} - -//_____________________________________________________________________________ -RooRealVar *RooMomentMorphND::CacheElem::frac(int i) -{ - return (RooRealVar *)(_frac.at(i)); -} - -//_____________________________________________________________________________ -const RooRealVar *RooMomentMorphND::CacheElem::frac(int i) const -{ - return (RooRealVar *)(_frac.at(i)); -} - -//_____________________________________________________________________________ -// from http://stackoverflow.com/a/5097100/8747 -template -inline bool next_combination(const Iterator first, Iterator k, const Iterator last) -{ - if ((first == last) || (first == k) || (last == k)) { - return false; - } - Iterator itr1 = first; - Iterator itr2 = last; - ++itr1; - if (last == itr1) { - return false; - } - itr1 = last; - --itr1; - itr1 = k; - --itr2; - while (first != itr1) { - if (*--itr1 < *itr2) { - Iterator j = k; - while (!(*itr1 < *j)) ++j; - iter_swap(itr1, j); - ++itr1; - ++j; - itr2 = k; - rotate(itr1, j, last); - while (last != j) { - ++j; - ++itr2; - } - rotate(k, itr2, last); - return true; - } - } - rotate(first, k, last); - return false; -} - -//_____________________________________________________________________________ -void RooMomentMorphND::CacheElem::calculateFractions(const RooMomentMorphND &self, bool verbose) const -{ - int nPdf = self._pdfList.getSize(); - int nPar = self._parList.getSize(); - - double fracLinear(1.); - double fracNonLinear(1.); - - if (self._setting == NonLinear || self._setting == NonLinearLinFractions || self._setting == NonLinearPosFractions) { - // Calculate the delta vector - vector dm2; - for (int idim = 0; idim < nPar; idim++) { - double delta = ((RooRealVar *)self._parList.at(idim))->getVal() - self._referenceGrid._nref[0][idim]; - dm2.push_back(delta); - } - - vector> powers; - for (int idim = 0; idim < nPar; idim++) { - vector xtmp; - for (int ix = 0; ix < self._referenceGrid._nnuis[idim]; ix++) { - xtmp.push_back(ix); - } - powers.push_back(xtmp); - } - - vector> output; - cartesian_product(output, powers); - int nCombs = output.size(); - - vector deltavec(nPdf, 1.0); - - int nperm = 0; - for (int i = 0; i < nCombs; i++) { - double tmpDm = 1.0; - for (int ix = 0; ix < nPar; ix++) { - double delta = dm2[ix]; - tmpDm *= TMath::Power(delta, static_cast(output[i][ix])); - } - deltavec[nperm] = tmpDm; - nperm++; - } - - double sumposfrac = 0.0; - for (int i = 0; i < nPdf; ++i) { - double ffrac = 0.0; - - for (int j = 0; j < nPdf; ++j) { - ffrac += (*self._M)(j, i) * deltavec[j] * fracNonLinear; - } - - if (ffrac >= 0) { - sumposfrac += ffrac; - } - - // fractions for pdf - if (self._setting != NonLinearLinFractions) { - ((RooRealVar *)frac(i))->setVal(ffrac); - } - - // fractions for rms and mean - ((RooRealVar *)frac(nPdf + i))->setVal(ffrac); // need to add up - ((RooRealVar *)frac(2 * nPdf + i))->setVal(ffrac); // need to add up - - if (verbose) { - cout << "NonLinear fraction " << ffrac << endl; - frac(i)->Print(); - frac(nPdf + i)->Print(); - frac(2 * nPdf + i)->Print(); - } - } - - if (self._setting == NonLinearPosFractions) { - for (int i = 0; i < nPdf; ++i) { - if (((RooRealVar *)frac(i))->getVal() < 0) - ((RooRealVar *)frac(i))->setVal(0.); - ((RooRealVar *)frac(i))->setVal(((RooRealVar *)frac(i))->getVal() / sumposfrac); - } - } - } - - if (self._setting == Linear || self._setting == NonLinearLinFractions) { - // zero all fractions - // for (int i = 0; i < 3*nPdf; ++i) { - for (int i = 0; i < nPdf; ++i) { - double initval = 0; - ((RooRealVar *)frac(i))->setVal(initval); - ((RooRealVar *)frac(nPdf + i))->setVal(initval); - ((RooRealVar *)frac(2 * nPdf + i))->setVal(initval); - } - - std::vector mtmp; - - // loop over parList - for (auto * m : static_range_cast(self._parList)) { - mtmp.push_back(m->getVal()); - } - - self.findShape(mtmp); // this sets _squareVec and _squareIdx quantities - - int depth = TMath::Power(2, nPar); - vector deltavec(depth, 1.0); - - int nperm = 0; - - vector xtmp; - for (int ix = 0; ix < nPar; ix++) { - xtmp.push_back(ix); - } - - for (int iperm = 1; iperm <= nPar; ++iperm) { - do { - double dtmp = mtmp[xtmp[0]] - self._squareVec[0][xtmp[0]]; - for (int itmp = 1; itmp < iperm; ++itmp) { - dtmp *= mtmp[xtmp[itmp]] - self._squareVec[0][xtmp[itmp]]; - } - deltavec[nperm + 1] = dtmp; - nperm++; - } while (next_combination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); - } - - double origFrac1(0.), origFrac2(0.); - for (int i = 0; i < depth; ++i) { - double ffrac = 0.; - for (int j = 0; j < depth; ++j) { - ffrac += (*self._MSqr)(j, i) * deltavec[j] * fracLinear; - } - - // set fractions for pdf - origFrac1 = ((RooRealVar *)frac(self._squareIdx[i]))->getVal(); // already set in case of smoothlinear - ((RooRealVar *)frac(self._squareIdx[i]))->setVal(origFrac1 + ffrac); // need to add up - - // set fractions for rms and mean - if (self._setting != NonLinearLinFractions) { - origFrac2 = - ((RooRealVar *)frac(nPdf + self._squareIdx[i]))->getVal(); // already set in case of smoothlinear - ((RooRealVar *)frac(nPdf + self._squareIdx[i]))->setVal(origFrac2 + ffrac); // need to add up - ((RooRealVar *)frac(2 * nPdf + self._squareIdx[i]))->setVal(origFrac2 + ffrac); // need to add up - } - - if (verbose) { - cout << "Linear fraction " << ffrac << endl; - frac(self._squareIdx[i])->Print(); - frac(nPdf + self._squareIdx[i])->Print(); - frac(2 * nPdf + self._squareIdx[i])->Print(); - } - } - } -} - -//_____________________________________________________________________________ -void RooMomentMorphND::findShape(const vector &x) const -{ - int nPar = _parList.getSize(); - int nRef = _referenceGrid._nref.size(); - - // Find hypercube enclosing the location to morph to - // bool isEnclosed = true; - // for (int i = 0; i < nPar; i++) { - // if (x[i] < _referenceGrid._grid[i]->lowBound()) - // isEnclosed = false; - // if (x[i] > _referenceGrid._grid[i]->highBound()) - // isEnclosed = false; - // } - - // cout << "isEnclosed = " << isEnclosed << endl; - - int depth = TMath::Power(2, nPar); - - vector> boundaries(nPar); - for (int idim = 0; idim < nPar; idim++) { - int bin = _referenceGrid._grid[idim]->binNumber(x[idim]); - double lo = _referenceGrid._grid[idim]->binLow(bin); - double hi = _referenceGrid._grid[idim]->binHigh(bin); - boundaries[idim].push_back(lo); - boundaries[idim].push_back(hi); - } - - vector> output; - cartesian_product(output, boundaries); - _squareVec = output; - - for (int isq = 0; isq < depth; isq++) { - for (int iref = 0; iref < nRef; iref++) { - if (_squareVec[isq] == _referenceGrid._nref[iref]) { - _squareIdx[isq] = iref; - break; - } - } - } - - // cout << endl; - - // for (int isq = 0; isq < _squareVec.size(); isq++) { - // cout << _squareIdx[isq]; - // cout << " ("; - // for (int isqq = 0; isqq < _squareVec[isq].size(); isqq++) { - // cout << _squareVec[isq][isqq] << ((isqq<_squareVec[isq].size()-1)?",":""); - // } - // cout << ") "; - // } - - // construct transformation matrix for linear extrapolation - TMatrixD M(depth, depth); - - vector xtmp; - for (int ix = 0; ix < nPar; ix++) { - xtmp.push_back(ix); - } - - for (int k = 0; k < depth; ++k) { - M(k, 0) = 1.0; - - int nperm = 0; - vector squareBase = _squareVec[0]; - - for (int iperm = 1; iperm <= nPar; ++iperm) { - do { - double dtmp = _squareVec[k][xtmp[0]] - squareBase[xtmp[0]]; - for (int itmp = 1; itmp < iperm; ++itmp) { - dtmp *= _squareVec[k][xtmp[itmp]] - squareBase[xtmp[itmp]]; - } - M(k, nperm + 1) = dtmp; - nperm++; - } while (next_combination(xtmp.begin(), xtmp.begin() + iperm, xtmp.end())); - } - } - - // M.Print(); - (*_MSqr) = M.Invert(); -} - -//_____________________________________________________________________________ -bool RooMomentMorphND::setBinIntegrator(RooArgSet &allVars) -{ - if (allVars.getSize() == 1) { - RooAbsReal *temp = const_cast(this); - temp->specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator"); - int nbins = ((RooRealVar *)allVars.first())->numBins(); - temp->specialIntegratorConfig(true)->getConfigSection("RooBinIntegrator").setRealValue("numBins", nbins); - return true; - } else { - cout << "Currently BinIntegrator only knows how to deal with 1-d " << endl; - return false; - } - return false; -} diff --git a/roofit/roofit/src/RooNDKeysPdf.cxx b/roofit/roofit/src/RooNDKeysPdf.cxx index c1ddec364f987..4f73ddd55e409 100644 --- a/roofit/roofit/src/RooNDKeysPdf.cxx +++ b/roofit/roofit/src/RooNDKeysPdf.cxx @@ -58,7 +58,7 @@ ClassImp(RooNDKeysPdf); /// - 'v' = Verbose flag /// /// The parameter rho (default = 1) provides an overall scale factor that can -/// be applied to the bandwith calculated for each kernel. The nSigma parameter +/// be applied to the bandwidth calculated for each kernel. The nSigma parameter /// determines the size of the box that is used to search for contributing kernels /// around a given point in observable space. The nSigma parameters is used /// in case of non-adaptive bandwidths and for the 1st non-adaptive pass for @@ -70,7 +70,7 @@ ClassImp(RooNDKeysPdf); RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList &varList, const RooDataSet &data, TString options, double rho, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _data(&data), _options(options), _widthFactor(rho), + _rhoList("rhoList", "List of rho parameters", this), _options(options), _widthFactor(rho), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { // Constructor @@ -85,7 +85,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList _varName.push_back(var->GetName()); } - createPdf(); + createPdf(true, data); } //////////////////////////////////////////////////////////////////////////////// @@ -94,7 +94,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList &varList, const TH1 &hist, TString options, double rho, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _ownedData(createDatasetFromHist(varList, hist)), _data(_ownedData.get()), + _rhoList("rhoList", "List of rho parameters", this), _options(options), _widthFactor(rho), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { @@ -108,7 +108,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList _varName.push_back(var->GetName()); } - createPdf(); + createPdf(true, *std::unique_ptr{createDatasetFromHist(varList, hist)}); } //////////////////////////////////////////////////////////////////////////////// @@ -117,7 +117,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList &varList, const RooDataSet &data, const TVectorD &rho, TString options, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _data(&data), _options(options), _widthFactor(-1.0), + _rhoList("rhoList", "List of rho parameters", this), _options(options), _widthFactor(-1.0), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { for (const auto var : varList) { @@ -146,7 +146,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList _rho[j] = rho[j]; /*cout<<"RooNDKeysPdf ctor, _rho["<hasChanged(true); // first evaluation always true for new parameters (?) - createPdf(); + createPdf(true, data); } //////////////////////////////////////////////////////////////////////////////// @@ -202,7 +202,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList &varList, const TH1 &hist, const RooArgList &rhoList, TString options, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _ownedData(createDatasetFromHist(varList, hist)), _data(_ownedData.get()), + _rhoList("rhoList", "List of rho parameters", this), _options(options), _widthFactor(-1), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { @@ -240,7 +240,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList _tracker = new RooChangeTracker("tracker", "track rho parameters", _rhoList, true); // check for value updates (void)_tracker->hasChanged(true); // first evaluation always true for new parameters (?) - createPdf(); + createPdf(true, *std::unique_ptr{createDatasetFromHist(varList, hist)}); } //////////////////////////////////////////////////////////////////////////////// @@ -249,7 +249,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, const RooArgList RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, RooAbsReal &x, const RooDataSet &data, Mirror mirror, double rho, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _data(&data), _options("a"), _widthFactor(rho), + _rhoList("rhoList", "List of rho parameters", this), _options("a"), _widthFactor(rho), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { _varList.add(x); @@ -262,7 +262,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, RooAbsReal &x, c _options = "m"; } - createPdf(); + createPdf(true, data); } //////////////////////////////////////////////////////////////////////////////// @@ -272,14 +272,14 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, RooAbsReal &x, c RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, RooAbsReal &x, RooAbsReal &y, const RooDataSet &data, TString options, double rho, double nSigma, bool rotate, bool sortInput) : RooAbsPdf(name, title), _varList("varList", "List of variables", this), - _rhoList("rhoList", "List of rho parameters", this), _data(&data), _options(options), _widthFactor(rho), + _rhoList("rhoList", "List of rho parameters", this), _options(options), _widthFactor(rho), _nSigma(nSigma), _rotate(rotate), _sortInput(sortInput), _nAdpt(1) { _varList.add(RooArgSet(x, y)); _varName.push_back(x.GetName()); _varName.push_back(y.GetName()); - createPdf(); + createPdf(true, data); } //////////////////////////////////////////////////////////////////////////////// @@ -287,8 +287,7 @@ RooNDKeysPdf::RooNDKeysPdf(const char *name, const char *title, RooAbsReal &x, R RooNDKeysPdf::RooNDKeysPdf(const RooNDKeysPdf &other, const char *name) : RooAbsPdf(other, name), _varList("varList", this, other._varList), _rhoList("rhoList", this, other._rhoList), - _ownedData(other._ownedData ? new RooDataSet(*other._ownedData) : nullptr), - _data(_ownedData ? _ownedData.get() : other._data), _options(other._options), _widthFactor(other._widthFactor), + _options(other._options), _widthFactor(other._widthFactor), _nSigma(other._nSigma), _rotate(other._rotate), _sortInput(other._sortInput), _nAdpt(other._nAdpt) { @@ -380,24 +379,24 @@ RooNDKeysPdf::~RooNDKeysPdf() //////////////////////////////////////////////////////////////////////////////// /// evaluation order of constructor. -void RooNDKeysPdf::createPdf(bool firstCall) +void RooNDKeysPdf::createPdf(bool firstCall, RooDataSet const& data) { if (firstCall) { // set options setOptions(); // initialization - initialize(); + initialize(data); } // copy dataset, calculate sigma_i's, determine min and max event weight - loadDataSet(firstCall); + loadDataSet(firstCall, data); // mirror dataset around dataset boundaries -- does not depend on event weights if (_mirror) mirrorDataSet(); // store indices and weights of events with high enough weights - loadWeightSet(); + loadWeightSet(data); // store indices of events in variable boundaries and box shell. //calculateShell(&_fullBoxInfo); @@ -451,10 +450,10 @@ void RooNDKeysPdf::setOptions() //////////////////////////////////////////////////////////////////////////////// /// initialization -void RooNDKeysPdf::initialize() +void RooNDKeysPdf::initialize(RooDataSet const& data) { _nDim = _varList.getSize(); - _nEvents = (Int_t)_data->numEntries(); + _nEvents = (Int_t)data.numEntries(); _nEventsM = _nEvents; _fixedShape= false; @@ -476,7 +475,7 @@ void RooNDKeysPdf::initialize() _d = static_cast(_nDim); - vector dummy(_nDim,0.); + std::vector dummy(_nDim,0.); _dataPts.resize(_nEvents,dummy); _weights0.resize(_nEvents,dummy); @@ -498,16 +497,16 @@ void RooNDKeysPdf::initialize() _xDatLo3s.resize(_nDim,0.); _xDatHi3s.resize(_nDim,0.); - boxInfoInit(&_fullBoxInfo,0,0xFFFF); + boxInfoInit(&_fullBoxInfo,nullptr,0xFFFF); _minWeight=0; _maxWeight=0; _wMap.clear(); - _covMat = 0; - _corrMat= 0; - _rotMat = 0; - _sigmaR = 0; + _covMat = nullptr; + _corrMat= nullptr; + _rotMat = nullptr; + _sigmaR = nullptr; _dx = new TVectorD(_nDim); _dx->Zero(); _dataPtsR.resize(_nEvents,*_dx); @@ -521,7 +520,7 @@ void RooNDKeysPdf::initialize() //////////////////////////////////////////////////////////////////////////////// /// copy the dataset and calculate some useful variables -void RooNDKeysPdf::loadDataSet(bool firstCall) +void RooNDKeysPdf::loadDataSet(bool firstCall, RooDataSet const& data) { // first some initialization _nEventsW=0.; @@ -538,7 +537,7 @@ void RooNDKeysPdf::loadDataSet(bool firstCall) _rotMat->Zero(); _sigmaR->Zero(); - const RooArgSet* values= _data->get(); + const RooArgSet* values= data.get(); vector dVars(_nDim); for (Int_t j=0; j<_nDim; j++) { dVars[j] = (RooRealVar*)values->find(_varName[j].c_str()); @@ -548,12 +547,12 @@ void RooNDKeysPdf::loadDataSet(bool firstCall) _idx.clear(); for (Int_t i=0; i<_nEvents; i++) { - _data->get(i); // fills dVars + data.get(i); // fills dVars _idx.push_back(i); - vector& point = _dataPts[i]; + std::vector& point = _dataPts[i]; TVectorD& pointV = _dataPtsR[i]; - double myweight = _data->weight(); // default is one? + double myweight = data.weight(); // default is one? if ( TMath::Abs(myweight)>_maxWeight ) { _maxWeight = TMath::Abs(myweight); } _nEventsW += myweight; @@ -741,13 +740,13 @@ void RooNDKeysPdf::mirrorDataSet() //////////////////////////////////////////////////////////////////////////////// -void RooNDKeysPdf::loadWeightSet() +void RooNDKeysPdf::loadWeightSet(RooDataSet const& data) { _wMap.clear(); for (Int_t i=0; i<_nEventsM; i++) { - _data->get(_idx[i]); - double myweight = _data->weight(); + data.get(_idx[i]); + double myweight = data.weight(); //if ( TMath::Abs(myweight)>_minWeight ) { _wMap[i] = myweight; //} @@ -924,8 +923,8 @@ void RooNDKeysPdf::calculateBandWidth() vector dummy(_nDim, 0.); _weights1.resize(_nEvents, dummy); - std::vector> *weights_prev(0); - std::vector> *weights_new(0); + std::vector> *weights_prev(nullptr); + std::vector> *weights_new(nullptr); // cout << "Number of adaptive iterations: " << _nAdpt << endl; @@ -1175,7 +1174,7 @@ double RooNDKeysPdf::analyticalIntegral(Int_t code, const char* rangeName) const vector doInt(_nDim,true); // get BoxInfo - BoxInfo* bi(0); + BoxInfo* bi(nullptr); if (rangeName) { string rangeNameStr(rangeName) ; @@ -1242,9 +1241,9 @@ double RooNDKeysPdf::analyticalIntegral(Int_t code, const char* rangeName) const chi[j] = (bi->xVarHi[j]-x[j])/weight[j]; if (chi[j]>0) // inVarRange - prob *= (0.5 + TMath::Erf(fabs(chi[j])/sqrt(2.))/2.); + prob *= (0.5 + TMath::Erf(std::abs(chi[j])/sqrt(2.))/2.); else // outside Var range - prob *= (0.5 - TMath::Erf(fabs(chi[j])/sqrt(2.))/2.); + prob *= (0.5 - TMath::Erf(std::abs(chi[j])/sqrt(2.))/2.); } norm += prob * _wMap.at(_idx[bi->sIdcs[i]]); @@ -1260,8 +1259,8 @@ double RooNDKeysPdf::analyticalIntegral(Int_t code, const char* rangeName) const RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const TH1 &hist) const { + RooArgSet varSet{varList}; std::vector varVec; - RooArgSet varsAndWeightSet; for (const auto var : varList) { if (!dynamic_cast(var)) { @@ -1269,14 +1268,9 @@ RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const << var->GetName() << " is not of type RooRealVar. Skip." << endl; continue; } - varsAndWeightSet.add(*var); // used for dataset creation varVec.push_back(static_cast(var)); // used for setting the variables. } - /// Add weight - RooRealVar weight("weight", "event weight", 0); - varsAndWeightSet.add(weight); - /// determine histogram dimensionality unsigned int histndim(0); std::string classname = hist.ClassName(); @@ -1296,7 +1290,7 @@ RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const } /// dataset creation - RooDataSet *dataFromHist = new RooDataSet("datasetFromHist", "datasetFromHist", varsAndWeightSet, weight.GetName()); + RooDataSet *dataFromHist = new RooDataSet("datasetFromHist", "datasetFromHist", varSet, RooFit::WeightVar()); /// dataset filling for (int i = 1; i <= hist.GetXaxis()->GetNbins(); ++i) { @@ -1307,8 +1301,7 @@ RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const if (varVec.size() == 1) { double fval = hist.GetBinContent(i); - weight.setVal(fval); - dataFromHist->add(varsAndWeightSet, fval); + dataFromHist->add(varSet, fval); } else { // 2 or more dimensions for (int j = 1; j <= hist.GetYaxis()->GetNbins(); ++j) { @@ -1317,8 +1310,7 @@ RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const if (varVec.size() == 2) { double fval = hist.GetBinContent(i, j); - weight.setVal(fval); - dataFromHist->add(varsAndWeightSet, fval); + dataFromHist->add(varSet, fval); } else { // 3 dimensions for (int k = 1; k <= hist.GetZaxis()->GetNbins(); ++k) { @@ -1326,8 +1318,7 @@ RooDataSet* RooNDKeysPdf::createDatasetFromHist(const RooArgList &varList, const varVec[2]->setVal(zval); double fval = hist.GetBinContent(i, j, k); - weight.setVal(fval); - dataFromHist->add(varsAndWeightSet, fval); + dataFromHist->add(varSet, fval); } } } diff --git a/roofit/roofit/src/RooNonCPEigenDecay.cxx b/roofit/roofit/src/RooNonCPEigenDecay.cxx index a4200cc039794..af83ebfdf162e 100644 --- a/roofit/roofit/src/RooNonCPEigenDecay.cxx +++ b/roofit/roofit/src/RooNonCPEigenDecay.cxx @@ -211,7 +211,7 @@ RooNonCPEigenDecay::~RooNonCPEigenDecay( void ) /// - B0bar : _tag == +1 /// - rho+ : _rhoQ == +1 /// - rho- : _rhoQ == -1 -/// - the charge correction factor "_correctQ" serves to implement mis-charges +/// - the charge correction factor "_correctQ" serves to implement misidentified charges double RooNonCPEigenDecay::coefficient( Int_t basisIndex ) const { diff --git a/roofit/roofit/src/RooNovosibirsk.cxx b/roofit/roofit/src/RooNovosibirsk.cxx index 74d2d47cc2c92..ac9a7bbf75a4a 100644 --- a/roofit/roofit/src/RooNovosibirsk.cxx +++ b/roofit/roofit/src/RooNovosibirsk.cxx @@ -89,10 +89,9 @@ double RooNovosibirsk::evaluate() const } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of Novosibirsk distribution. -void RooNovosibirsk::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooNovosibirsk::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Novosibirsk, output, nEvents, + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Novosibirsk, output, nEvents, {dataMap.at(x), dataMap.at(peak), dataMap.at(width), dataMap.at(tail)}); } diff --git a/roofit/roofit/src/RooParamHistFunc.cxx b/roofit/roofit/src/RooParamHistFunc.cxx index d34dacf51ffdc..ea2f3d49e9ee0 100644 --- a/roofit/roofit/src/RooParamHistFunc.cxx +++ b/roofit/roofit/src/RooParamHistFunc.cxx @@ -24,7 +24,7 @@ #include "RooAbsCategory.h" #include "RooRealVar.h" #include "RooHelpers.h" -#include +#include #include "TMath.h" @@ -127,6 +127,21 @@ double RooParamHistFunc::evaluate() const return ret ; } +void RooParamHistFunc::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string const &idx = _dh.calculateTreeIndexForCodeSquash(this, ctx, _x); + std::string arrName = ctx.buildArg(_p); + std::string result = arrName + "[" + idx + "]"; + if (_relParam) { + // get weight[idx] * binv[idx]. Here we get the bin volume for the first element as we assume the distribution to + // be binned uniformly. + std::string const &weightName = _dh.declWeightArrayForCodeSquash(this, ctx, false); + std::string nominalVal = weightName + "[" + idx + "] * " + std::to_string(_dh.binVolume(0)); + result += " * " + nominalVal; + } + ctx.addResult(this, result); +} + //////////////////////////////////////////////////////////////////////////////// double RooParamHistFunc::getActual(Int_t ibin) @@ -167,11 +182,11 @@ list* RooParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, double x // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast(_dh.get()->find(obs.GetName())) ; if (!lvarg) { - return 0 ; + return nullptr ; } // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; list* hint = new list ; @@ -204,11 +219,11 @@ std::list* RooParamHistFunc::binBoundaries(RooAbsRealLValue& obs, double // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast(_dh.get()->find(obs.GetName())) ; if (!lvarg) { - return 0 ; + return nullptr ; } // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; list* hint = new list ; @@ -231,9 +246,8 @@ Int_t RooParamHistFunc::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& a const RooArgSet* /*normSet*/, const char* /*rangeName*/) const { // Simplest scenario, integrate over all dependents - RooAbsCollection *allVarsCommon = allVars.selectCommon(_x) ; - bool intAllObs = (allVarsCommon->getSize()==_x.getSize()) ; - delete allVarsCommon ; + std::unique_ptr allVarsCommon{allVars.selectCommon(_x)}; + bool intAllObs = (allVarsCommon->size()==_x.size()) ; if (intAllObs && matchArgs(allVars,analVars,_x)) { return 1 ; } diff --git a/roofit/roofit/src/RooParametricStepFunction.cxx b/roofit/roofit/src/RooParametricStepFunction.cxx index 369aeea3599c0..229983ae1fc81 100644 --- a/roofit/roofit/src/RooParametricStepFunction.cxx +++ b/roofit/roofit/src/RooParametricStepFunction.cxx @@ -78,15 +78,10 @@ xframe->Draw(); ~~~ */ -#include "Riostream.h" -#include "TArrayD.h" -#include +#include -#include "RooParametricStepFunction.h" -#include "RooRealVar.h" -#include "RooArgList.h" - -#include "TError.h" +#include +#include ClassImp(RooParametricStepFunction); @@ -94,7 +89,7 @@ ClassImp(RooParametricStepFunction); /// Constructor RooParametricStepFunction::RooParametricStepFunction(const char* name, const char* title, - RooAbsReal& x, const RooArgList& coefList, TArrayD& limits, Int_t nBins) : + RooAbsReal& x, const RooArgList& coefList, TArrayD const& limits, Int_t nBins) : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList","List of coefficients",this), @@ -110,9 +105,11 @@ RooParametricStepFunction::RooParametricStepFunction(const char* name, const cha for (auto *coef : coefList) { if (!dynamic_cast(coef)) { - std::cout << "RooParametricStepFunction::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() - << " is not of type RooAbsReal" << std::endl ; - R__ASSERT(0) ; + std::stringstream errorMsg; + errorMsg << "RooParametricStepFunction::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() + << " is not of type RooAbsReal"; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::invalid_argument(errorMsg.str().c_str()); } _coefList.add(*coef) ; } @@ -144,10 +141,8 @@ Int_t RooParametricStepFunction::getAnalyticalIntegral(RooArgSet& allVars, RooAr //////////////////////////////////////////////////////////////////////////////// -double RooParametricStepFunction::analyticalIntegral(Int_t code, const char* rangeName) const +double RooParametricStepFunction::analyticalIntegral(Int_t /*code*/, const char* rangeName) const { - R__ASSERT(code==1) ; - // Case without range is trivial: p.d.f is by construction normalized if (!rangeName) { return 1.0 ; @@ -210,20 +205,10 @@ double RooParametricStepFunction::evaluate() const // in Bin i-1 (starting with Bin 0) if (i<_nBins) { // not in last Bin - RooRealVar* tmp = (RooRealVar*) _coefList.at(i-1); - value = tmp->getVal(); + value = static_cast(_coefList.at(i-1))->getVal(); break; } else { - // in last Bin - double sum(0.); - double binSize(0.); - for (Int_t j=1;j<_nBins;j++){ - RooRealVar* tmp = (RooRealVar*) _coefList.at(j-1); - binSize = _limits[j] - _limits[j-1]; - sum = sum + tmp->getVal()*binSize; - } - binSize = _limits[_nBins] - _limits[_nBins-1]; - value = (1.0 - sum)/binSize; + value = lastBinValue(); if (value<=0.0){ value = 0.000001; // cout << "RooParametricStepFunction: sum of values gt 1.0 -- beware!!" <* RooParametricStepFunction::plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const +{ + if(obs.namePtr() != _x->namePtr()) { + return nullptr; + } + + // Retrieve position of all bin boundaries + std::span boundaries{_limits.GetArray(), static_cast(_limits.GetSize())}; + + // Use the helper function from RooCurve to make sure to get sampling hints + // that work with the RooFitPlotting. + return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi); +} diff --git a/roofit/roofit/src/RooPoisson.cxx b/roofit/roofit/src/RooPoisson.cxx index 7187a52bbdf86..10b48fec3b3d5 100644 --- a/roofit/roofit/src/RooPoisson.cxx +++ b/roofit/roofit/src/RooPoisson.cxx @@ -18,6 +18,8 @@ Poisson pdf #include "RooNaNPacker.h" #include "RooBatchCompute.h" +#include "RooFit/Detail/AnalyticalIntegrals.h" +#include "RooFit/Detail/EvaluateFuncs.h" #include "Math/ProbFuncMathCore.h" ClassImp(RooPoisson); @@ -26,8 +28,8 @@ ClassImp(RooPoisson); /// Constructor RooPoisson::RooPoisson(const char *name, const char *title, - RooAbsReal& _x, - RooAbsReal& _mean, + RooAbsReal::Ref _x, + RooAbsReal::Ref _mean, bool noRounding) : RooAbsPdf(name,title), x("x","x",this,_x), @@ -59,17 +61,26 @@ double RooPoisson::evaluate() const np.setPayload(-mean); return np._payload; } - return TMath::Poisson(k,mean) ; + return RooFit::Detail::EvaluateFuncs::poissonEvaluate(k, mean); +} + +void RooPoisson::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string xName = ctx.getResult(x); + if (!_noRounding) + xName = "std::floor(" + xName + ")"; + + ctx.addResult(this, ctx.buildCall("RooFit::Detail::EvaluateFuncs::poissonEvaluate", xName, mean)); } //////////////////////////////////////////////////////////////////////////////// /// Compute multiple values of the Poisson distribution. -void RooPoisson::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooPoisson::computeBatch(double *output, size_t nEvents, + RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Poisson, output, nEvents, - {dataMap.at(x), dataMap.at(mean)}, - {static_cast(_protectNegative), static_cast(_noRounding)}); + RooBatchCompute::ArgVector extraArgs{static_cast(_protectNegative), static_cast(_noRounding)}; + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Poisson, output, nEvents, + {dataMap.at(x), dataMap.at(mean)}, extraArgs); } //////////////////////////////////////////////////////////////////////////////// @@ -87,62 +98,25 @@ double RooPoisson::analyticalIntegral(Int_t code, const char* rangeName) const { R__ASSERT(code == 1 || code == 2) ; - const double mu = mean; // evaluating the proxy once for less overhead - - if(_protectNegative && mu < 0.0) { - return std::exp(-2.0 * mu); // make it fall quickly - } - - if (code == 1) { - // Implement integral over x as summation. Add special handling in case - // range boundaries are not on integer values of x - const double xmin = std::max(0., x.min(rangeName)); - const double xmax = x.max(rangeName); - - if (xmax < 0. || xmax < xmin) { - return 0.; - } - const double delta = 100.0 * std::sqrt(mu); - // If the limits are more than many standard deviations away from the mean, - // we might as well return the integral of the full Poisson distribution to - // save computing time. - if (xmin < std::max(mu - delta, 0.0) && xmax > mu + delta) { - return 1.; - } - - // The range as integers. ixmin is included, ixmax outside. - const unsigned int ixmin = xmin; - const unsigned int ixmax = std::min(xmax + 1., - (double)std::numeric_limits::max()); - - // Sum from 0 to just before the bin outside of the range. - if (ixmin == 0) { - return ROOT::Math::poisson_cdf(ixmax - 1, mu); - } - else { - // If necessary, subtract from 0 to the beginning of the range - if (ixmin <= mu) { - return ROOT::Math::poisson_cdf(ixmax - 1, mu) - ROOT::Math::poisson_cdf(ixmin - 1, mu); - } - else { - //Avoid catastrophic cancellation in the high tails: - return ROOT::Math::poisson_cdf_c(ixmin - 1, mu) - ROOT::Math::poisson_cdf_c(ixmax - 1, mu); - } - - } - - } else if(code == 2) { - - // the integral with respect to the mean is the integral of a gamma distribution - - // negative ix does not need protection (gamma returns 0.0) - const double ix = _noRounding ? x + 1 : int(TMath::Floor(x)) + 1.0; - - using ROOT::Math::gamma_cdf; - return gamma_cdf(mean.max(rangeName), ix, 1.0) - gamma_cdf(mean.min(rangeName), ix, 1.0); - } + RooRealProxy const &integrand = code == 1 ? x : mean; + return RooFit::Detail::AnalyticalIntegrals::poissonIntegral( + code, mean, _noRounding ? x : std::floor(x), integrand.min(rangeName), integrand.max(rangeName), _protectNegative); +} - return 0.0; +std::string +RooPoisson::buildCallToAnalyticIntegral(int code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const +{ + R__ASSERT(code == 1 || code == 2); + std::string xName = ctx.getResult(x); + if (!_noRounding) + xName = "std::floor(" + xName + ")"; + + RooRealProxy const &integrand = code == 1 ? x : mean; + // Since the integral function is the same for both codes, we need to make sure the indexed observables do not appear + // in the function if they are not required. + xName = code == 1 ? "0" : xName; + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::poissonIntegral", code, mean, xName, + integrand.min(rangeName), integrand.max(rangeName), _protectNegative); } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofit/src/RooPolynomial.cxx b/roofit/roofit/src/RooPolynomial.cxx index a07262b466a84..aabbcdd4fbf1b 100644 --- a/roofit/roofit/src/RooPolynomial.cxx +++ b/roofit/roofit/src/RooPolynomial.cxx @@ -32,21 +32,16 @@ RooPolynomial::RooPolynomial(const char*, const char*, RooAbsReal&, const RooArg #include "RooPolynomial.h" #include "RooArgList.h" #include "RooMsgService.h" -#include "RooBatchCompute.h" +#include "RooPolyVar.h" + +#include +#include #include "TError.h" #include -using namespace std; ClassImp(RooPolynomial); -//////////////////////////////////////////////////////////////////////////////// -/// coverity[UNINIT_CTOR] - -RooPolynomial::RooPolynomial() -{ -} - //////////////////////////////////////////////////////////////////////////////// /// Create a polynomial in the variable `x`. /// \param[in] name Name of the PDF @@ -67,127 +62,116 @@ RooPolynomial::RooPolynomial() /// \mathrm{pol}(x) = 1 * x^0 + (0 * x^{\ldots}) + a * x^2 + b * x^3. /// \f] - -RooPolynomial::RooPolynomial(const char* name, const char* title, - RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) : - RooAbsPdf(name, title), - _x("x", "Dependent", this, x), - _coefList("coefList","List of coefficients",this), - _lowestOrder(lowestOrder) +RooPolynomial::RooPolynomial(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, + Int_t lowestOrder) + : RooAbsPdf(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), + _lowestOrder(lowestOrder) { - // Check lowest order - if (_lowestOrder<0) { - coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() - << ") WARNING: lowestOrder must be >=0, setting value to 0" << endl ; - _lowestOrder=0 ; - } - - for (auto *coef : coefList) { - if (!dynamic_cast(coef)) { - coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() - << " is not of type RooAbsReal" << endl ; - R__ASSERT(0) ; - } - _coefList.add(*coef) ; - } + // Check lowest order + if (_lowestOrder < 0) { + coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() + << ") WARNING: lowestOrder must be >=0, setting value to 0" << std::endl; + _lowestOrder = 0; + } + + for (auto *coef : coefList) { + if (!dynamic_cast(coef)) { + coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() + << " is not of type RooAbsReal" << std::endl; + R__ASSERT(0); + } + _coefList.add(*coef); + } } //////////////////////////////////////////////////////////////////////////////// -RooPolynomial::RooPolynomial(const char* name, const char* title, - RooAbsReal& x) : - RooAbsPdf(name, title), - _x("x", "Dependent", this, x), - _coefList("coefList","List of coefficients",this), - _lowestOrder(1) -{ } +RooPolynomial::RooPolynomial(const char *name, const char *title, RooAbsReal &x) + : RooAbsPdf(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), + _lowestOrder(1) +{ +} //////////////////////////////////////////////////////////////////////////////// /// Copy constructor -RooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) : - RooAbsPdf(other, name), - _x("x", this, other._x), - _coefList("coefList",this,other._coefList), - _lowestOrder(other._lowestOrder) -{ } +RooPolynomial::RooPolynomial(const RooPolynomial &other, const char *name) + : RooAbsPdf(other, name), + _x("x", this, other._x), + _coefList("coefList", this, other._coefList), + _lowestOrder(other._lowestOrder) +{ +} //////////////////////////////////////////////////////////////////////////////// -/// Destructor -RooPolynomial::~RooPolynomial() -{ } +double RooPolynomial::evaluate() const +{ + const unsigned sz = _coefList.getSize(); + if (!sz) + return _lowestOrder ? 1. : 0.; + + RooPolyVar::fillCoeffValues(_wksp, _coefList); -//////////////////////////////////////////////////////////////////////////////// + return RooFit::Detail::EvaluateFuncs::polynomialEvaluate(_wksp.data(), sz, _lowestOrder, _x); +} -double RooPolynomial::evaluate() const +void RooPolynomial::translate(RooFit::Detail::CodeSquashContext &ctx) const { - // Calculate and return value of polynomial - - const unsigned sz = _coefList.getSize(); - const int lowestOrder = _lowestOrder; - if (!sz) return lowestOrder ? 1. : 0.; - _wksp.clear(); - _wksp.reserve(sz); - { - const RooArgSet* nset = _coefList.nset(); - for (auto *c : static_range_cast(_coefList)) { - _wksp.push_back(c->getVal(nset)); - } - } - const double x = _x; - double retVal = _wksp[sz - 1]; - for (unsigned i = sz - 1; i--; ) retVal = _wksp[i] + x * retVal; - return retVal * std::pow(x, lowestOrder) + (lowestOrder ? 1.0 : 0.0); + const unsigned sz = _coefList.size(); + if (!sz) { + ctx.addResult(this, std::to_string((_lowestOrder ? 1. : 0.))); + return; + } + + ctx.addResult( + this, ctx.buildCall("RooFit::Detail::EvaluateFuncs::polynomialEvaluate", _coefList, sz, _lowestOrder, _x)); } -// The batch mode support for RooPolynomial was commented out, because that -// implementation can't deal with observables used as polynomial coefficients -// yet. - -////////////////////////////////////////////////////////////////////////////////// -///// Compute multiple values of Polynomial. -//void RooPolynomial::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::DataMap& dataMap) const -//{ - //RooBatchCompute::ArgVector extraArgs; - //for (auto* coef:_coefList) - //extraArgs.push_back( static_cast(coef)->getVal() ); - //extraArgs.push_back(_lowestOrder); - //auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - //dispatch->compute(stream, RooBatchCompute::Polynomial, output, nEvents, dataMap, {&*_x,&*_norm}, extraArgs); -//} +/// Compute multiple values of Polynomial. +void RooPolynomial::computeBatch(double *output, size_t nEvents, + RooFit::Detail::DataMap const &dataMap) const +{ + return RooPolyVar::computeBatchImpl(this, output, nEvents, dataMap, _x.arg(), _coefList, _lowestOrder); +} //////////////////////////////////////////////////////////////////////////////// /// Advertise to RooFit that this function can be analytically integrated. -Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const +Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char * /*rangeName*/) const { - if (matchArgs(allVars, analVars, _x)) return 1; - return 0; + if (matchArgs(allVars, analVars, _x)) + return 1; + return 0; } //////////////////////////////////////////////////////////////////////////////// /// Do the analytical integral according to the code that was returned by getAnalyticalIntegral(). -double RooPolynomial::analyticalIntegral(Int_t code, const char* rangeName) const +double RooPolynomial::analyticalIntegral(Int_t code, const char *rangeName) const { - R__ASSERT(code==1) ; - - const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); - const int lowestOrder = _lowestOrder; - const unsigned sz = _coefList.getSize(); - if (!sz) return xmax - xmin; - _wksp.clear(); - _wksp.reserve(sz); - { - const RooArgSet* nset = _coefList.nset(); - unsigned i = 1 + lowestOrder; - for (auto *c : static_range_cast(_coefList)) { - _wksp.push_back(c->getVal(nset) / double(i)); - ++i; - } - } - double min = _wksp[sz - 1], max = _wksp[sz - 1]; - for (unsigned i = sz - 1; i--; ) - min = _wksp[i] + xmin * min, max = _wksp[i] + xmax * max; - return max * std::pow(xmax, 1 + lowestOrder) - min * std::pow(xmin, 1 + lowestOrder) + - (lowestOrder ? (xmax - xmin) : 0.); + R__ASSERT(code == 1); + + const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); + const unsigned sz = _coefList.getSize(); + if (!sz) + return _lowestOrder ? xmax - xmin : 0.0; + + RooPolyVar::fillCoeffValues(_wksp, _coefList); + + return RooFit::Detail::AnalyticalIntegrals::polynomialIntegral(_wksp.data(), sz, _lowestOrder, xmin, xmax); +} + +std::string RooPolynomial::buildCallToAnalyticIntegral(Int_t /* code */, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const +{ + const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); + const unsigned sz = _coefList.getSize(); + if (!sz) + return std::to_string(_lowestOrder ? xmax - xmin : 0.0); + + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::polynomialIntegral", _coefList, sz, _lowestOrder, + xmin, xmax); } diff --git a/roofit/roofit/src/RooPower.cxx b/roofit/roofit/src/RooPower.cxx index b7b57d9b1bc75..9d188c254970d 100644 --- a/roofit/roofit/src/RooPower.cxx +++ b/roofit/roofit/src/RooPower.cxx @@ -22,6 +22,7 @@ RooPower implements a power law PDF of the form #include #include #include +#include "RooBatchCompute.h" #include @@ -53,7 +54,9 @@ ClassImp(RooPower); RooPower::RooPower(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, const RooArgList &expList) - : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList", "List of coefficients", this), + : RooAbsPdf(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), _expList("expList", "List of exponents", this) { if (coefList.size() != expList.size()) { @@ -80,20 +83,36 @@ RooPower::RooPower(const char *name, const char *title, RooAbsReal &x, const Roo } //////////////////////////////////////////////////////////////////////////////// +/// Copy constructor -RooPower::RooPower(const char *name, const char *title, RooAbsReal &x) - : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList", "List of coefficients", this), - _expList("expList", "List of exponents", this) +RooPower::RooPower(const RooPower &other, const char *name) + : RooAbsPdf(other, name), + _x("x", this, other._x), + _coefList("coefList", this, other._coefList), + _expList("expList", this, other._expList) { } //////////////////////////////////////////////////////////////////////////////// -/// Copy constructor -RooPower::RooPower(const RooPower &other, const char *name) - : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList", this, other._coefList), - _expList("expList", this, other._expList) +/// Compute multiple values of Power distribution. +void RooPower::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { + RooBatchCompute::VarVector vars; + vars.reserve(2 * _coefList.size() + 1); + vars.push_back(dataMap.at(_x)); + + assert(_coefList.size() == _expList.size()); + + for (std::size_t i = 0; i < _coefList.size(); ++i) { + vars.push_back(dataMap.at(&_coefList[i])); + vars.push_back(dataMap.at(&_expList[i])); + } + + RooBatchCompute::ArgVector args; + args.push_back(_coefList.size()); + + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Power, output, nEvents, vars, args); } //////////////////////////////////////////////////////////////////////////////// @@ -121,7 +140,7 @@ double RooPower::evaluate() const double x = this->_x; double retval = 0; for (unsigned int i = 0; i < sz; ++i) { - retval += coefs[i] * pow(x, exps[i]); + retval += coefs[i] * std::pow(x, exps[i]); } return retval; } @@ -186,5 +205,5 @@ std::string RooPower::getFormulaExpression(bool expand) const ss << _expList.at(i)->GetName(); ss << ")"; } - return ss.str().c_str(); + return ss.str(); } diff --git a/roofit/roofit/src/RooSpline.cxx b/roofit/roofit/src/RooSpline.cxx new file mode 100644 index 0000000000000..cad65cb69d1fc --- /dev/null +++ b/roofit/roofit/src/RooSpline.cxx @@ -0,0 +1,132 @@ +/* + * Project: RooFit + * Author: + * Ruggero Turra , 2016 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include + +#include + +#include + +#include +#include +#include + +/** \class RooSpline + \ingroup Roofit + \brief A RooFit class for creating spline functions. + +This class provides the functionality to create spline functions in RooFit, +, using ROOT TSpline. It supports splines of order 3 or 5. It also support +interpolation in the log-space (x or y), for example +exp(spline({x0}, {log y0})), useful when you have something (as xsections) +that is more similar to exponentials than polynomials. + +Usage example: +~~~ {.cpp} +RooRealVar x{"x", "x", 0, 5}; + +std::vector x0{1., 2, 3}; +std::vector y0{10., 20, 50}; + +RooSpline spline{"myspline", "my spline", x, x0, y0}; + +auto frame = x.frame(); +spline.plotOn(frame); +frame->Draw(); +~~~ +*/ + +ClassImp(RooSpline); + +/// Constructor for creating a spline from a TGraph. +/// \param[in] name The name of the spline. +/// \param[in] title The title of the spline. +/// \param[in] x The independent variable. +/// \param[in] gr The input TGraph containing the data points. +/// \param[in] order The order of the spline (3 or 5). +/// \param[in] logx If true, the x values are logarithmically scaled before spline creation. +/// \param[in] logy If true, the y values are logarithmically scaled before spline creation. +RooSpline::RooSpline(const char *name, const char *title, RooAbsReal &x, const TGraph &gr, int order, bool logy, + bool logx) + : RooSpline(name, title, x, {gr.GetX(), gr.GetX() + gr.GetN()}, {gr.GetY(), gr.GetY() + gr.GetN()}, order, logx, + logy) +{ +} + +/// Constructor for creating a spline from raw data. +/// \param[in] name The name of the spline. +/// \param[in] title The title of the spline. +/// \param[in] x The independent variable. +/// \param[in] x0 The array of x values for the spline points. +/// \param[in] y0 The array of y values for the spline points. +/// \param[in] order The order of the spline (3 or 5). +/// \param[in] logx If true, the x values are logarithmically scaled before spline creation. +/// \param[in] logy If true, the y values are logarithmically scaled before spline creation. +RooSpline::RooSpline(const char *name, const char *title, RooAbsReal &x, std::span x0, + std::span y0, int order, bool logx, bool logy) + : RooAbsReal{name, title}, _x{"x", "x", this, x}, _logx{logx}, _logy{logy} +{ + const std::string title_spline = std::string(title) + "_spline"; + if (x0.size() != y0.size()) { + std::stringstream errMsg; + errMsg << "RooSpline::ctor(" << GetName() << ") ERROR: size of x and y are not equal"; + coutE(InputArguments) << errMsg.str() << std::endl; + throw std::invalid_argument(errMsg.str()); + } + + // To do the logarithm inplace if necessary. + std::vector x0Copy; + x0Copy.assign(x0.begin(), x0.end()); + std::vector y0Copy; + y0Copy.assign(y0.begin(), y0.end()); + + if (_logx) { + for (auto &xRef : x0Copy) { + xRef = std::log(xRef); + } + } + if (_logy) { + for (auto &yRef : y0Copy) { + yRef = std::log(yRef); + } + } + + if (order == 3) { + _spline = std::make_unique(title_spline.c_str(), &x0Copy[0], &y0Copy[0], x0.size()); + } else if (order == 5) { + _spline = std::make_unique(title_spline.c_str(), &x0Copy[0], &y0Copy[0], x0.size()); + } else { + std::stringstream errMsg; + errMsg << "supported orders are 3 or 5"; + coutE(InputArguments) << errMsg.str() << std::endl; + throw std::invalid_argument(errMsg.str()); + } +} + +/// Copy constructor. +/// \param[in] other The RooSpline object to copy from. +/// \param[in] name The name of the new RooSpline object (optional). +RooSpline::RooSpline(const RooSpline &other, const char *name) + : RooAbsReal(other, name), + _spline(static_cast(other._spline->Clone())), + _x("x", this, other._x), + _logx(other._logx), + _logy(other._logy) +{ +} + +/// Evaluate the spline function at the current point. +double RooSpline::evaluate() const +{ + const double x_val = (!_logx) ? _x : std::exp(_x); + return (!_logy) ? _spline->Eval(x_val) : std::exp(_spline->Eval(x_val)); +} diff --git a/roofit/roofit/src/RooStepFunction.cxx b/roofit/roofit/src/RooStepFunction.cxx index 5c27c5ecd2a3d..b70b20a6c00b4 100644 --- a/roofit/roofit/src/RooStepFunction.cxx +++ b/roofit/roofit/src/RooStepFunction.cxx @@ -28,31 +28,19 @@ Note that in contrast to RooParametricStepFunction, a RooStepFunction is NOT a P but a not-normalized function (RooAbsReal) **/ -#include "Riostream.h" -#include "TArrayD.h" -#include +#include -#include "RooStepFunction.h" -#include "RooRealVar.h" -#include "RooArgList.h" -#include "RooMsgService.h" -#include "RooMath.h" - -using namespace std; +#include +#include +#include +#include +#include ClassImp(RooStepFunction); //////////////////////////////////////////////////////////////////////////////// /// Constructor -RooStepFunction::RooStepFunction() -{ - _interpolate = false ; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - RooStepFunction::RooStepFunction(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList, const RooArgList& boundaryList, bool interpolate) : RooAbsReal(name, title), @@ -63,8 +51,8 @@ RooStepFunction::RooStepFunction(const char* name, const char* title, { for (auto *coef : coefList) { if (!dynamic_cast(coef)) { - cout << "RooStepFunction::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() - << " is not of type RooAbsReal" << endl ; + std::cout << "RooStepFunction::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() + << " is not of type RooAbsReal" << std::endl ; assert(0) ; } _coefList.add(*coef) ; @@ -72,16 +60,16 @@ RooStepFunction::RooStepFunction(const char* name, const char* title, for (auto *boundary : boundaryList) { if (!dynamic_cast(boundary)) { - cout << "RooStepFunction::ctor(" << GetName() << ") ERROR: boundary " << boundary->GetName() - << " is not of type RooAbsReal" << endl ; + std::cout << "RooStepFunction::ctor(" << GetName() << ") ERROR: boundary " << boundary->GetName() + << " is not of type RooAbsReal" << std::endl; assert(0) ; } _boundaryList.add(*boundary) ; } - if (_boundaryList.getSize()!=_coefList.getSize()+1) { - coutE(InputArguments) << "RooStepFunction::ctor(" << GetName() << ") ERROR: Number of boundaries must be number of coefficients plus 1" << endl ; - throw string("RooStepFunction::ctor() ERROR: Number of boundaries must be number of coefficients plus 1") ; + if (_boundaryList.size()!=_coefList.size()+1) { + coutE(InputArguments) << "RooStepFunction::ctor(" << GetName() << ") ERROR: Number of boundaries must be number of coefficients plus 1" << std::endl ; + throw std::invalid_argument("RooStepFunction::ctor() ERROR: Number of boundaries must be number of coefficients plus 1") ; } } @@ -100,12 +88,12 @@ RooStepFunction::RooStepFunction(const RooStepFunction& other, const char* name) //////////////////////////////////////////////////////////////////////////////// -/// Transfer contents to vector for use below +/// Transfer contents to std::vector for use below double RooStepFunction::evaluate() const { - vector b(_boundaryList.getSize()) ; - vector c(_coefList.getSize()+3) ; + std::vector b(_boundaryList.size()) ; + std::vector c(_coefList.size()+3) ; Int_t nb(0) ; for (auto * boundary : static_range_cast(_boundaryList)) { b[nb++] = boundary->getVal() ; @@ -136,7 +124,7 @@ double RooStepFunction::evaluate() const // Make array of (0,coefficient values,0) Int_t nc(0) ; - vector y(_coefList.size()+3) ; + std::vector y(_coefList.size()+3) ; y[nc++] = 0 ; for(auto * coef : static_range_cast(_coefList)) { y[nc++] = coef->getVal() ; @@ -153,3 +141,22 @@ double RooStepFunction::evaluate() const return 0; } } + + +std::list *RooStepFunction::plotSamplingHint(RooAbsRealLValue &obs, double xlo, double xhi) const +{ + if (obs.namePtr() != _x->namePtr()) { + return nullptr; + } + + // Retrieve position of all bin boundaries + std::vector boundaries; + boundaries.reserve(_boundaryList.size()); + for (auto *boundary : static_range_cast(_boundaryList)) { + boundaries.push_back(boundary->getVal()); + } + + // Use the helper function from RooCurve to make sure to get sampling hints + // that work with the RooFitPlotting. + return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi); +} diff --git a/roofit/roofit/src/RooUniform.cxx b/roofit/roofit/src/RooUniform.cxx index c115aee3ffe38..22fcb5b589c2c 100644 --- a/roofit/roofit/src/RooUniform.cxx +++ b/roofit/roofit/src/RooUniform.cxx @@ -23,7 +23,6 @@ Flat p.d.f. in N dimensions #include "RooArgSet.h" #include "RooRealVar.h" #include "RooUniform.h" -#include "RunContext.h" ClassImp(RooUniform); @@ -51,28 +50,6 @@ double RooUniform::evaluate() const return 1 ; } -//////////////////////////////////////////////////////////////////////////////// -///Compute multiple values of the uniform distribution (effectively return a span with ones) -RooSpan RooUniform::evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* /*normSet*/) const -{ - size_t nEvents = 1; - for (auto elm : x) { - size_t nEventsCurrent = static_cast(elm)->getValues(evalData).size(); - if(nEventsCurrent != 1 && nEvents != 1 && nEventsCurrent != nEvents) { - auto errorMsg = std::string("RooUniform::evaluateSpan(): number of entries for input variables does not match") - + "in RooUniform with name \"" + GetName() + "\"."; - coutE(FastEvaluations) << errorMsg << std::endl ; - throw std::runtime_error(errorMsg); - } - nEvents = std::max(nEvents, nEventsCurrent); - } - RooSpan values = evalData.makeBatch(this, nEvents); - for (size_t i=0; icompute(stream, RooBatchCompute::Voigtian, output, nEvents, - {dataMap.at(x), dataMap.at(mean), dataMap.at(width), dataMap.at(sigma)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Voigtian, output, nEvents, + {dataMap.at(x), dataMap.at(mean), dataMap.at(width), dataMap.at(sigma)}); } diff --git a/roofit/roofit/test/CMakeLists.txt b/roofit/roofit/test/CMakeLists.txt index fda40d1f361ee..b1069d7e57f50 100644 --- a/roofit/roofit/test/CMakeLists.txt +++ b/roofit/roofit/test/CMakeLists.txt @@ -6,13 +6,14 @@ # @author Stephan Hageboeck, CERN, 2019 -ROOT_ADD_GTEST(testRooGaussian testRooGaussian.cxx LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testRooPoisson testRooPoisson.cxx LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testRooBernstein testRooBernstein.cxx LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testRooCrystalBall testRooCrystalBall.cxx LIBRARIES Gpad RooFitCore RooFit) -ROOT_ADD_GTEST(testRooJohnson testRooJohnson.cxx LIBRARIES Gpad RooFitCore RooFit) -ROOT_ADD_GTEST(testRooKeysPdf testRooKeysPdf.cxx LIBRARIES Gpad RooFitCore RooFit) -ROOT_ADD_GTEST(testRooParamHistFunc testRooParamHistFunc.cxx LIBRARIES Gpad RooFitCore RooFit) +ROOT_ADD_GTEST(testRooGaussian testRooGaussian.cxx LIBRARIES RooFit) +ROOT_ADD_GTEST(testRooPoisson testRooPoisson.cxx LIBRARIES RooFit) +ROOT_ADD_GTEST(testRooBernstein testRooBernstein.cxx LIBRARIES RooFit) +ROOT_ADD_GTEST(testRooCrystalBall testRooCrystalBall.cxx LIBRARIES Gpad RooFit) +ROOT_ADD_GTEST(testRooJohnson testRooJohnson.cxx LIBRARIES Gpad RooFit) +ROOT_ADD_GTEST(testRooKeysPdf testRooKeysPdf.cxx LIBRARIES Gpad RooFit) +ROOT_ADD_GTEST(testRooLandau testRooLandau.cxx LIBRARIES RooFit) +ROOT_ADD_GTEST(testRooParamHistFunc testRooParamHistFunc.cxx LIBRARIES Gpad RooFit) ROOT_ADD_GTEST(testRooExponential testRooExponential.cxx COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/exponentialPdf.root - LIBRARIES Core RooFitCore RooFit) + LIBRARIES Core RooFit) diff --git a/roofit/roofit/test/testRooBernstein.cxx b/roofit/roofit/test/testRooBernstein.cxx index e139c363f87dc..8ad615391e822 100644 --- a/roofit/roofit/test/testRooBernstein.cxx +++ b/roofit/roofit/test/testRooBernstein.cxx @@ -55,10 +55,10 @@ void IntegrationChecker(double a0, double a1, double a2, double a3) auto numInt_full = bern.createIntegral(x, "FULL"); // closure - EXPECT_LT(fabs(int_full->getVal() - int_range1->getVal() - int_range2->getVal() - int_range3->getVal()), 1e-10); - EXPECT_LT(fabs(numInt_full->getVal() - numInt_range1->getVal() - numInt_range2->getVal() - numInt_range3->getVal()), 1e-10); + EXPECT_LT(std::abs(int_full->getVal() - int_range1->getVal() - int_range2->getVal() - int_range3->getVal()), 1e-10); + EXPECT_LT(std::abs(numInt_full->getVal() - numInt_range1->getVal() - numInt_range2->getVal() - numInt_range3->getVal()), 1e-10); - // comparision with polynomial + // Comparison with polynomial double accAnaVsNum = 1.; EXPECT_NEAR(int_range1->getVal(), numInt_range1->getVal(), accAnaVsNum/100.*numInt_range1->getVal()) diff --git a/roofit/roofit/test/testRooCrystalBall.cxx b/roofit/roofit/test/testRooCrystalBall.cxx index c5dd801cf6011..d404a9ed097aa 100644 --- a/roofit/roofit/test/testRooCrystalBall.cxx +++ b/roofit/roofit/test/testRooCrystalBall.cxx @@ -1,21 +1,16 @@ // Author: Jonas Rembser, CERN 02/2021 -#include "RooCrystalBall.h" -#include "RooCBShape.h" - -#include "RooRealVar.h" -#include "RooGaussian.h" -#include "RooLinearVar.h" -#include "RooRealConstant.h" -#include "RooFirstMoment.h" -#include "RooGenericPdf.h" -#include "RooNumIntConfig.h" -#include "RooDataSet.h" -#include "RooFormulaVar.h" -#include "RooFitResult.h" - -#include "TCanvas.h" -#include "RooPlot.h" +#include +#include + +#include +#include +#include +#include +#include +#include + +#include #include #include @@ -112,7 +107,7 @@ TEST(RooCrystalBall, SingleTailAndFullySymmetric) RooCBShape crystalBallOnlyLeftTailOld("cb1Old", "cb3Old", x, x0, sigma, alpha, n); RooCBShape crystalBallOnlyRightTailOld("cb2Old", "cb2Old", x, x0, sigma, minusAlpha, n); - //RooSDSCBShape crystalBallFullySymmetricOld("cb3Old", "cb3Old", x, x0, sigma, alpha, n); + // RooSDSCBShape crystalBallFullySymmetricOld("cb3Old", "cb3Old", x, x0, sigma, alpha, n); auto formulaOnlyLeftTail = makeCrystalBallFormulaOnlyLeftTail(); auto formulaOnlyRightTail = makeCrystalBallFormulaOnlyRightTail(); @@ -157,7 +152,7 @@ TEST(RooCrystalBall, SingleTailAndFullySymmetric) << theX << " " << theX0 << " " << theSigma << " " << theAlpha << " " << theN; // Compare fully symmetric version with RooSDSCBShape which should match - //EXPECT_FLOAT_EQ(crystalBallFullySymmetricOld.getVal(), crystalBallFullySymmetricRef->getVal()) + // EXPECT_FLOAT_EQ(crystalBallFullySymmetricOld.getVal(), crystalBallFullySymmetricRef->getVal()) // << theX << " " << theX0 << " " << theSigma << " " << theAlpha << " " << theN; } } @@ -178,7 +173,7 @@ TEST(RooCrystalBall, DoubleSided) // in the symmetric Gaussian core case, we also compare with the old implementation `RooDSCBShape` RooCrystalBall crystalBall("crystalBall", "crystalBall", x, x0, sigma, alphaL, nL, alphaR, nR); - //RooDSCBShape crystalBallOld("crystalBallOld", "crystalBallOld", x, x0, sigma, alphaL, nL, alphaR, nR); + // RooDSCBShape crystalBallOld("crystalBallOld", "crystalBallOld", x, x0, sigma, alphaL, nL, alphaR, nR); auto formula = makeCrystalBallFormulaDoubleSided(); @@ -207,9 +202,9 @@ TEST(RooCrystalBall, DoubleSided) << theX << " " << theX0 << " " << theSigma << " " << theAlphaL << " " << theNL << " " << theAlphaR << " " << theNR; - //EXPECT_FLOAT_EQ(crystalBallOld.getVal(), crystalBallRef->getVal()) - // << theX << " " << theX0 << " " << theSigma << " " << theAlphaL << " " << theNL << " " - // << theAlphaR << " " << theNR; + // EXPECT_FLOAT_EQ(crystalBallOld.getVal(), crystalBallRef->getVal()) + // << theX << " " << theX0 << " " << theSigma << " " << theAlphaL << " " << theNL << " " + // << theAlphaR << " " << theNR; } } } @@ -276,10 +271,10 @@ TEST(RooCrystalBall, Integral) crystalBallNumInt.setIntegratorConfig(intConfig); crystalBallNumInt.forceNumInt(true); - auto integral = crystalBall.createIntegral(x); - auto integralRanged = crystalBall.createIntegral(x, "integrationRange"); - auto numInt = crystalBallNumInt.createIntegral(x); - auto numIntRanged = crystalBallNumInt.createIntegral(x, "integrationRange"); + std::unique_ptr integral{crystalBall.createIntegral(x)}; + std::unique_ptr integralRanged{crystalBall.createIntegral(x, "integrationRange")}; + std::unique_ptr numInt{crystalBallNumInt.createIntegral(x)}; + std::unique_ptr numIntRanged{crystalBallNumInt.createIntegral(x, "integrationRange")}; for (double theX0 : {0.}) { for (double theSigmaL : {10., 20.}) { @@ -358,13 +353,13 @@ TEST(RooCrystalBall, Generator) alphaR = 1.3; nR = 0.1; - auto frame = x.frame(RooFit::Title("RooCrystalBall")); - auto data = crystalBall.generate(x, RooFit::NumEvents(10000)); - data->plotOn(frame); - crystalBall.plotOn(frame, RooFit::LineColor(kRed), RooFit::LineColor(kDotted)); + std::unique_ptr frame{x.frame(RooFit::Title("RooCrystalBall"))}; + std::unique_ptr data{crystalBall.generate(x, RooFit::NumEvents(10000))}; + data->plotOn(frame.get()); + crystalBall.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::LineColor(kDotted)); crystalBall.fitTo(*data, RooFit::PrintLevel(-1)); - crystalBall.plotOn(frame, RooFit::LineColor(kBlue), RooFit::LineColor(kDashed)); - crystalBall.paramOn(frame); + crystalBall.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::LineColor(kDashed)); + crystalBall.paramOn(frame.get()); EXPECT_LT(frame->chiSquare(), 1.); @@ -376,14 +371,14 @@ TEST(RooCrystalBall, Generator) alphaR = 1.0; nR = 0.2; - frame = x.frame(RooFit::Title("RooCrystalBall")); - auto data2 = crystalBall.generate(x, 10000.); - data2->plotOn(frame); - crystalBall.plotOn(frame, RooFit::LineColor(kBlue)); + frame = std::unique_ptr{x.frame(RooFit::Title("RooCrystalBall"))}; + std::unique_ptr data2{crystalBall.generate(x, 10000.)}; + data2->plotOn(frame.get()); + crystalBall.plotOn(frame.get(), RooFit::LineColor(kBlue)); EXPECT_LT(frame->chiSquare(), 1.); auto res = crystalBall.fitTo(*data2, RooFit::Save(), RooFit::PrintLevel(-1)); - crystalBall.plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed)); - crystalBall.paramOn(frame); + crystalBall.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::LineStyle(kDashed)); + crystalBall.paramOn(frame.get()); EXPECT_LT(frame->chiSquare(res->floatParsInit().size()), 1.); } diff --git a/roofit/roofit/test/testRooKeysPdf.cxx b/roofit/roofit/test/testRooKeysPdf.cxx index ca4b505acb26a..7d0ded913b954 100644 --- a/roofit/roofit/test/testRooKeysPdf.cxx +++ b/roofit/roofit/test/testRooKeysPdf.cxx @@ -1,9 +1,11 @@ // Tests for the RooKeysPdf and friends // Authors: Jonas Rembser, CERN 07/2022 -#include +#include #include #include +#include +#include #include "gtest/gtest.h" @@ -17,13 +19,12 @@ TEST(RooKeysPdf, WeightedDataset) // this validates that dataset weights are correctly dealt with. RooRealVar x("x", "x", 0, 20); - RooRealVar weight("weight", "weight", 0, 2000); const std::size_t nEvents0 = 100; const std::size_t nEvents1 = 400; RooDataSet data1{"data1", "data1", x}; - RooDataSet data2{"data2", "data2", {x, weight}, "weight"}; + RooDataSet data2{"data2", "data2", x, RooFit::WeightVar()}; x.setVal(5); for (std::size_t i = 0; i < nEvents0; ++i) { @@ -54,3 +55,29 @@ TEST(RooKeysPdf, WeightedDataset) xVal += 0.1; } } + +// Test generation with proto data, covering GitHub issue #12286. +TEST(RooKeysPdf, GenerationWithProtoData) +{ + using namespace RooFit; + + RooRealVar x{"x", "", 0, 1}; + RooGenericPdf pdfX{"pdf_x", "x", {x}}; + + std::unique_ptr dtBase{pdfX.generate(x, 10000)}; + + RooKeysPdf pdfKeys{"pdf_keys", "", x, *dtBase, RooKeysPdf::MirrorBoth}; + + RooRealVar y{"y", "", 0, 1}; + RooDataSet proto{"proto_y", "", y}; + proto.add(y); + + std::unique_ptr dtKeysWithProto{pdfKeys.generate(x, NumEvents(10000), ProtoData(proto))}; + + std::unique_ptr frame{x.frame()}; + dtKeysWithProto->plotOn(frame.get()); + pdfKeys.plotOn(frame.get()); + + // If the dataset generation worked, the chi-square is not too terrible + EXPECT_LE(frame->chiSquare(), 2.0); +} diff --git a/roofit/roofit/test/testRooLandau.cxx b/roofit/roofit/test/testRooLandau.cxx new file mode 100644 index 0000000000000..2cfef130e4a1f --- /dev/null +++ b/roofit/roofit/test/testRooLandau.cxx @@ -0,0 +1,65 @@ +// Author: Jonas Rembser, CERN 01/2023 + +#include +#include +#include +#include + +#include + +#include + +TEST(RooLandau, Integral) +{ + RooWorkspace ws; + ws.factory("Landau::landau(x[-100, 100], mean[-100, 100], sigma[0.01, 100])"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &mean = *ws.var("mean"); + RooRealVar &sigma = *ws.var("sigma"); + + RooAbsPdf *landau = ws.pdf("landau"); + + std::unique_ptr landauNumInt{static_cast(landau->clone())}; + landauNumInt->forceNumInt(true); + + RooNumIntConfig intConfig(*RooAbsReal::defaultIntegratorConfig()); + intConfig.setEpsAbs(1.E-15); + intConfig.setEpsRel(1.E-12); + + intConfig.getConfigSection("RooIntegrator1D").setRealValue("maxSteps", 100); + landauNumInt->setIntegratorConfig(intConfig); + + std::unique_ptr integral{landau->createIntegral(x)}; + std::unique_ptr integralRanged{landau->createIntegral(x, "integrationRange")}; + std::unique_ptr numInt{landauNumInt->createIntegral(x)}; + std::unique_ptr numIntRanged{landauNumInt->createIntegral(x, "integrationRange")}; + + for (double meanVal : {-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0}) { + for (double sigmaVal : {1., 2., 5., 10.}) { + mean.setVal(meanVal); + sigma.setVal(sigmaVal); + + for (double r1 : {-2., -1.5, -0.5, -0.2, 0.2, 0.5, 1.5, 2.}) { + for (double r2 : {-2., -1.5, -0.5, -0.2, 0.2, 0.5, 1.5, 2.}) { + if (r2 <= r1) { + continue; + } + x.setRange("integrationRange", r1, r2); + + constexpr double accAnaVsNum = 1.; + EXPECT_NEAR(integralRanged->getVal(), numIntRanged->getVal(), + accAnaVsNum / 100. * numIntRanged->getVal()) + << "Analytical vs numerical integral (subrange)" + << " within " << accAnaVsNum << "%. With mean=" << meanVal << " sigma=" << sigmaVal + << ", integration from x=" << r1 << " to x=" << r2; + } + } + + constexpr double accAnaVsNum = 3.; + EXPECT_NEAR(integral->getVal(), numInt->getVal(), accAnaVsNum / 100. * numIntRanged->getVal()) + << "Analytical vs numerical integral (full range) " + << " within " << accAnaVsNum << "%. With mean=" << meanVal << " sigma=" << sigmaVal; + } + } +} diff --git a/roofit/roofit/test/testRooParamHistFunc.cxx b/roofit/roofit/test/testRooParamHistFunc.cxx index 0b9dcd1d0e328..5244ceb6f201e 100644 --- a/roofit/roofit/test/testRooParamHistFunc.cxx +++ b/roofit/roofit/test/testRooParamHistFunc.cxx @@ -1,7 +1,7 @@ // Tests for RooParamHistFunc // Author: Jonas Rembser, CERN 03/2020 -#include +#include #include #include #include @@ -20,8 +20,7 @@ TEST(RooParamHistFunc, Integration) // inspired by this issue on GitHub: // https://github.com/root-project/root/issues/7182 - auto& msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); constexpr int nBins = 20; constexpr double xMin = 0; @@ -76,8 +75,7 @@ TEST(RooParamHistFunc, IntegrationAndCloning) // The test was inspired by this error reported on the forum: // https://root-forum.cern.ch/t/barlow-beeston-in-subrange/43909/5 - auto& msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); using namespace RooFit; diff --git a/roofit/roofitZMQ/test/CMakeLists.txt b/roofit/roofitZMQ/test/CMakeLists.txt index 5019e99a23088..ade7488ea80a0 100644 --- a/roofit/roofitZMQ/test/CMakeLists.txt +++ b/roofit/roofitZMQ/test/CMakeLists.txt @@ -1,5 +1,5 @@ -ROOT_ADD_GTEST(test_RooFitZMQ test_ZMQ.cpp LIBRARIES RooFitZMQ RooFitCommon) -ROOT_ADD_GTEST(test_RooFitZMQ_polling test_polling.cxx LIBRARIES RooFitZMQ RooFitCommon) -ROOT_ADD_GTEST(test_RooFitZMQ_HWM test_HWM.cxx LIBRARIES RooFitZMQ RooFitCommon) -ROOT_ADD_GTEST(test_RooFitZMQ_load_balancing test_ZMQ_load_balancing.cxx LIBRARIES RooFitZMQ RooFitCommon) -ROOT_ADD_GTEST(test_RooFitZMQ_mkstemp test_mkstemp.cxx LIBRARIES RooFitZMQ RooFitCommon) +ROOT_ADD_GTEST(test_RooFitZMQ test_ZMQ.cpp LIBRARIES RooFitZMQ Core) +ROOT_ADD_GTEST(test_RooFitZMQ_polling test_polling.cxx LIBRARIES RooFitZMQ Core) +ROOT_ADD_GTEST(test_RooFitZMQ_HWM test_HWM.cxx LIBRARIES RooFitZMQ Core) +ROOT_ADD_GTEST(test_RooFitZMQ_load_balancing test_ZMQ_load_balancing.cxx LIBRARIES RooFitZMQ Core) +ROOT_ADD_GTEST(test_RooFitZMQ_mkstemp test_mkstemp.cxx LIBRARIES RooFitZMQ Core) diff --git a/roofit/roofitZMQ/test/test_HWM.cxx b/roofit/roofitZMQ/test/test_HWM.cxx index 178661d404101..69639294d3ea1 100644 --- a/roofit/roofitZMQ/test/test_HWM.cxx +++ b/roofit/roofitZMQ/test/test_HWM.cxx @@ -12,7 +12,7 @@ #include "RooFit_ZMQ/ZeroMQSvc.h" -#include +#include #include "gtest/gtest.h" @@ -27,7 +27,8 @@ class HighWaterMarkTest : public ::testing::Test { child_pid = fork(); } while (child_pid == -1); // retry if fork fails - const std::string ipc = "ipc://" + RooFit::tmpPath() + "ZMQ_test_fork_polling_P2C.ipc"; + std::string tmpPath = gSystem->TempDirectory(); + const std::string ipc = "ipc://" + std::string{tmpPath} + "/roofit_ZMQ_test_fork_polling_P2C.ipc"; if (child_pid > 0) { // parent pusher.reset(zmqSvc().socket_ptr(zmq::socket_type::push)); diff --git a/roofit/roofitZMQ/test/test_ZMQ.cpp b/roofit/roofitZMQ/test/test_ZMQ.cpp index 27048549cf5fa..f072d64e9ed44 100644 --- a/roofit/roofitZMQ/test/test_ZMQ.cpp +++ b/roofit/roofitZMQ/test/test_ZMQ.cpp @@ -12,7 +12,7 @@ #include "RooFit_ZMQ/ZeroMQSvc.h" -#include +#include #include "gtest/gtest.h" @@ -100,8 +100,7 @@ void elaborate_bind(const ZmqLingeringSocketPtr<> &socket, std::string name) class AllSocketTypes : public ::testing::TestWithParam, - std::pair /* socket_names */>> { -}; + std::pair /* socket_names */>> {}; TEST_P(AllSocketTypes, forkHandshake) { @@ -146,7 +145,8 @@ TEST_P(AllSocketTypes, forkHandshake) } } -std::string ipc{"ipc://" + RooFit::tmpPath() + "ZMQ_test_fork.ipc"}; +std::string tmpPath = gSystem->TempDirectory(); +std::string ipc{"ipc://" + tmpPath + "/roofit_ZMQ_test_fork.ipc"}; std::string tcp_server{"tcp://127.0.0.1:6660"}; std::string tcp_client{"tcp://*:6660"}; auto socket_name_options = ::testing::Values(std::make_pair(tcp_server, tcp_client), std::make_pair(ipc, ipc)); @@ -165,8 +165,7 @@ INSTANTIATE_TEST_SUITE_P(PAIRPAIR, AllSocketTypes, class AsyncSocketTypes : public ::testing::TestWithParam< std::tuple, - std::pair /* socket_names */, bool /* expect_throw */>> { -}; + std::pair /* socket_names */, bool /* expect_throw */>> {}; TEST_P(AsyncSocketTypes, forkMultiSendReceive) { diff --git a/roofit/roofitZMQ/test/test_ZMQ_load_balancing.cxx b/roofit/roofitZMQ/test/test_ZMQ_load_balancing.cxx index 4d3080b721419..aead1d63cf6f2 100644 --- a/roofit/roofitZMQ/test/test_ZMQ_load_balancing.cxx +++ b/roofit/roofitZMQ/test/test_ZMQ_load_balancing.cxx @@ -13,7 +13,7 @@ #include "RooFit_ZMQ/ZeroMQSvc.h" #include "RooFit_ZMQ/ZeroMQPoller.h" -#include +#include #include "gtest/gtest.h" @@ -38,12 +38,14 @@ class ZMQPushPullTest : public ::testing::Test { } } + std::string tmpPath = gSystem->TempDirectory(); + if (child_pid > 0) { // parent pusher.reset(zmqSvc().socket_ptr(zmq::socket_type::push)); - pusher->bind("ipc://" + RooFit::tmpPath() + "ZMQ_test_push_pull_P2C.ipc"); + pusher->bind("ipc://" + tmpPath + "/roofit_ZMQ_test_push_pull_P2C.ipc"); } else { // child puller.reset(zmqSvc().socket_ptr(zmq::socket_type::pull)); - puller->connect("ipc://" + RooFit::tmpPath() + "ZMQ_test_push_pull_P2C.ipc"); + puller->connect("ipc://" + tmpPath + "/roofit_ZMQ_test_push_pull_P2C.ipc"); poller.register_socket(*puller, zmq::event_flags::pollin); } diff --git a/roofit/roofitZMQ/test/test_mkstemp.cxx b/roofit/roofitZMQ/test/test_mkstemp.cxx index 34dafd847c3f8..6e2a10947d3cf 100644 --- a/roofit/roofitZMQ/test/test_mkstemp.cxx +++ b/roofit/roofitZMQ/test/test_mkstemp.cxx @@ -12,7 +12,7 @@ #include "RooFit_ZMQ/ZeroMQSvc.h" -#include +#include #include "gtest/gtest.h" @@ -21,10 +21,12 @@ TEST(BindToTmpFile, mkstemp) { - std::string filename = RooFit::tmpPath() + "roofitMP_XXXXXX"; - while (mkstemp(const_cast(filename.c_str())) < 0) { + std::string tmpPath = gSystem->TempDirectory(); + + std::string filename = tmpPath + "/roofit_MP_XXXXXX"; + while (mkstemp(const_cast(filename.c_str())) < 0) { } - EXPECT_NE(filename, RooFit::tmpPath() + "roofitMP_XXXXXX"); + EXPECT_NE(filename, tmpPath + "/roofit_MP_XXXXXX"); auto socket = zmqSvc().socket(zmq::socket_type::push); std::string address = "ipc://" + filename; try { diff --git a/roofit/roofitZMQ/test/test_polling.cxx b/roofit/roofitZMQ/test/test_polling.cxx index c51d928917b30..b832d0b0fae4b 100644 --- a/roofit/roofitZMQ/test/test_polling.cxx +++ b/roofit/roofitZMQ/test/test_polling.cxx @@ -13,7 +13,7 @@ #include "RooFit_ZMQ/ZeroMQSvc.h" #include "RooFit_ZMQ/ZeroMQPoller.h" -#include +#include #include "gtest/gtest.h" @@ -38,8 +38,9 @@ std::string unique_tmp_ipc_address(const char *filename_template) strcpy(filename_template_mutable, filename_template); while (mkstemp(filename_template_mutable) >= 0) { } + std::string tmpPath = gSystem->TempDirectory(); std::stringstream ss; - ss << "ipc://" << RooFit::tmpPath() << filename_template_mutable << ".ipc"; + ss << "ipc://" << tmpPath << "/roofit_" << filename_template_mutable << ".ipc"; return ss.str(); } diff --git a/roofit/roofitcore/CMakeLists.txt b/roofit/roofitcore/CMakeLists.txt index d9fc3e6ab1071..0d122450ba786 100644 --- a/roofit/roofitcore/CMakeLists.txt +++ b/roofit/roofitcore/CMakeLists.txt @@ -13,10 +13,34 @@ if (roofit_multiprocess) set(RooFitMPTestStatisticsSources src/TestStatistics/LikelihoodJob.cxx src/TestStatistics/LikelihoodGradientJob.cxx) endif() +if(roofit_multiprocess) + list(APPEND EXTRA_LIBRARIES RooFitMultiProcess) +endif() + +if(cuda) + list(APPEND EXTRA_LIBRARIES RooFitCuda) +endif() + +if(roofit_multiprocess) + list(APPEND EXTRA_DEPENDENCIES Minuit2) +endif() + +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore HEADERS + RooFit/Config.h + RooFit/Detail/AnalyticalIntegrals.h + RooFit/Detail/EvaluateFuncs.h + RooFit/Detail/CodeSquashContext.h RooFit/Detail/DataMap.h + RooFit/Detail/NormalizationHelpers.h + RooFit/Evaluator.h RooFit/Floats.h + RooFit/ModelConfig.h Roo1DTable.h RooAbsAnaConvPdf.h RooAbsArg.h @@ -42,10 +66,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooAbsProxy.h RooAbsReal.h RooAbsRealLValue.h - RooAbsRootFinder.h RooAbsSelfCachedPdf.h RooAbsSelfCachedReal.h - RooAbsString.h RooAbsStudy.h RooAbsTestStatistic.h RooAdaptiveIntegratorND.h @@ -78,7 +100,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooConstVar.h RooConvCoefVar.h RooConvGenContext.h - RooConvIntegrandBinding.h RooCurve.h RooCustomizer.h RooDataHist.h @@ -105,15 +126,13 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooFirstMoment.h RooFit.h RooFitResult.h - RooFormula.h RooFormulaVar.h RooFracRemainder.h RooFunctor.h + RooFuncWrapper.h RooGenContext.h RooGenericPdf.h RooGenFitStudy.h - RooGenFunction.h - RooGenProdProj.h RooGlobalFunc.h RooGrid.h RooHistError.h @@ -121,10 +140,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooHist.h RooHistPdf.h RooImproperIntegrator1D.h - RooIntegrator1D.h - RooIntegrator2D.h - RooIntegratorBinding.h - RooInt.h + RooRombergIntegrator.h RooInvTransform.h RooLinearCombination.h RooLinearVar.h @@ -141,7 +157,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooMoment.h RooMsgService.h RooMultiCategory.h - RooMultiGenFunction.h RooMultiVarGaussian.h RooNameReg.h RooNLLVar.h @@ -174,7 +189,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooRandomizeParamMCSModule.h RooRangeBinning.h RooRangeBoolean.h - RooRealAnalytic.h RooRealBinding.h RooRealConstant.h RooRealIntegral.h @@ -189,10 +203,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooRefCountList.h RooSTLRefCountList.h RooResolutionModel.h - RooScaledFunc.h RooSecondMoment.h - RooSegmentedIntegrator1D.h - RooSegmentedIntegrator2D.h RooSetProxy.h RooSharedProperties.h RooSimGenContext.h @@ -206,7 +217,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooStudyPackage.h RooSuperCategory.h RooTable.h - RooTFoamBinding.h RooThresholdCategory.h RooTObjWrap.h RooTrace.h @@ -220,12 +230,10 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooXYChi2Var.h RooHelpers.h RooWrapperPdf.h - RooNaNPacker.h RooBinSamplingPdf.h RooBinWidthFunction.h RooFitLegacy/RooCatTypeLegacy.h RooFitLegacy/RooCategorySharedProperties.h - RooFitLegacy/RooMinuit.h RooFitLegacy/RooTreeData.h RooFit/TestStatistics/LikelihoodGradientWrapper.h RooFit/TestStatistics/LikelihoodWrapper.h @@ -235,17 +243,16 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore RooFit/TestStatistics/RooSumL.h RooFit/TestStatistics/RooRealL.h RooFit/TestStatistics/RooUnbinnedL.h - RooFit/TestStatistics/optional_parameter_types.h RooFit/TestStatistics/buildLikelihood.h - RunContext.h SOURCES src/ConstraintHelpers.cxx src/BatchModeHelpers.cxx src/BatchModeDataHelpers.cxx - src/CUDAHelpers.cxx src/Buffers.cxx src/BidirMMapPipe.cxx src/BidirMMapPipe.h + src/FitHelpers.cxx + src/ModelConfig.cxx src/NormalizationHelpers.cxx src/Roo1DTable.cxx src/RooAbsAnaConvPdf.cxx @@ -274,9 +281,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooAbsProxy.cxx src/RooAbsReal.cxx src/RooAbsRealLValue.cxx - src/RooAbsRootFinder.cxx - src/RooAbsSelfCachedPdf.cxx - src/RooAbsSelfCachedReal.cxx src/RooAbsStudy.cxx src/RooAbsTestStatistic.cxx src/RooAcceptReject.cxx @@ -340,10 +344,10 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooFormulaVar.cxx src/RooFracRemainder.cxx src/RooFunctor.cxx + src/RooFuncWrapper.cxx src/RooGenContext.cxx src/RooGenericPdf.cxx src/RooGenFitStudy.cxx - src/RooGenFunction.cxx src/RooGenProdProj.cxx src/RooGlobalFunc.cxx src/RooGrid.cxx @@ -352,10 +356,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooHistFunc.cxx src/RooHistPdf.cxx src/RooImproperIntegrator1D.cxx - src/RooInt.cxx - src/RooIntegrator1D.cxx - src/RooIntegrator2D.cxx - src/RooIntegratorBinding.cxx + src/RooRombergIntegrator.cxx src/RooInvTransform.cxx src/RooLinearCombination.cxx src/RooLinearVar.cxx @@ -371,10 +372,10 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooMoment.cxx src/RooMsgService.cxx src/RooMultiCategory.cxx - src/RooMultiGenFunction.cxx src/RooMultiVarGaussian.cxx src/RooNameReg.cxx - src/RooFitDriver.cxx + src/RooFit/Evaluator.cxx + src/RooEvaluatorWrapper.cxx src/RooNLLVar.cxx src/RooNLLVarNew.cxx src/RooNormSetCache.cxx @@ -408,7 +409,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooRandomizeParamMCSModule.cxx src/RooRangeBinning.cxx src/RooRangeBoolean.cxx - src/RooRealAnalytic.cxx src/RooRealBinding.cxx src/RooRealConstant.cxx src/RooRealIntegral.cxx @@ -417,13 +417,9 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooRealSumPdf.cxx src/RooRealVar.cxx src/RooRecursiveFraction.cxx - src/RooRefCountList.cxx src/RooSTLRefCountList.cxx src/RooResolutionModel.cxx - src/RooScaledFunc.cxx src/RooSecondMoment.cxx - src/RooSegmentedIntegrator1D.cxx - src/RooSegmentedIntegrator2D.cxx src/RooSentinel.cxx src/RooSharedProperties.cxx src/RooSimGenContext.cxx @@ -452,8 +448,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/RooBinSamplingPdf.cxx src/RooBinWidthFunction.cxx src/RooFitLegacy/RooCatTypeLegacy.cxx - src/RooFitLegacy/RooMinuit.cxx - src/RunContext.cxx + src/RooFit/Detail/CodeSquashContext.cxx + src/RooFit/Detail/DataMap.cxx src/TestStatistics/ConstantTermsOptimizer.cxx src/TestStatistics/LikelihoodGradientWrapper.cxx src/TestStatistics/LikelihoodWrapper.cxx @@ -465,14 +461,13 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore src/TestStatistics/RooSumL.cxx src/TestStatistics/RooRealL.cxx src/TestStatistics/RooUnbinnedL.cxx - src/TestStatistics/optional_parameter_types.cxx src/TestStatistics/buildLikelihood.cxx ${RooFitMPTestStatisticsSources} DICTIONARY_OPTIONS "-writeEmptyRootPCM" LIBRARIES RooBatchCompute - RooFitCommon + ${EXTRA_LIBRARIES} DEPENDENCIES Core Hist @@ -480,21 +475,16 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitCore Matrix Tree Minuit - Minuit2 RIO MathCore Foam Smatrix + ${EXTRA_DEPENDENCIES} LINKDEF inc/LinkDef.h + ${EXTRA_DICT_OPTS} ) -if (roofit_multiprocess) - target_link_libraries(RooFitCore PRIVATE RooFitMultiProcess) - set(RooFitCore_MultiProcess_TestStatistics_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/res") - target_include_directories(RooFitCore PRIVATE ${RooFitCore_MultiProcess_TestStatistics_INCLUDE_DIR}) -endif() - # For recent clang, this can facilitate auto-vectorisation. # In RooFit, the errno side effect is not needed, anyway: if(NOT MSVC) diff --git a/roofit/roofitcore/doc/index.md b/roofit/roofitcore/doc/index.md index 7388857ffc1c8..028d8fa525a7d 100644 --- a/roofit/roofitcore/doc/index.md +++ b/roofit/roofitcore/doc/index.md @@ -3,13 +3,13 @@ For an introduction check the tutorials \ref tutorial_roofit, [user's guides](https://root.cern.ch/root-user-guides-and-manuals), [courses](https://root.cern.ch/courses) or [the RooFit chapter of the Manual](https://root.cern/manual/roofit/). -\defgroup Roofitcore Roofitcore +\defgroup Roofitcore RooFit Core \brief RooFit core classes. These provide the infrastructure for building likelihood models. \ingroup Roofitmain -\defgroup Roofitlegacy Roofitlegacy -\brief Old RooFit classes +\defgroup Roofitlegacy RooFit Legacy +\brief Old RooFit classes. \ingroup Roofitmain This group contains classes that are provided for backward compatibility, but there's no need to use them in new code. diff --git a/roofit/roofitcore/inc/LinkDef.h b/roofit/roofitcore/inc/LinkDef.h index 96ba8a06d6df7..204dd7fe0d0ee 100644 --- a/roofit/roofitcore/inc/LinkDef.h +++ b/roofit/roofitcore/inc/LinkDef.h @@ -13,16 +13,16 @@ code="{ _proxyList.GetSize() ; if (onfile._proxyList.GetSize()>0) { RooAbsArg::_ioEvoList[newObj] = std::make_unique(onfile._proxyList); } }" #pragma read sourceClass="RooAbsArg" targetClass="RooAbsArg" version="[1-6]"\ source="RooRefCountList _serverList" target="_serverList" \ - code="{ _serverList = RooFit::STLRefCountListHelpers::convert(onfile._serverList); }" + code="{ _serverList = RooSTLRefCountList::convert(onfile._serverList); }" #pragma read sourceClass="RooAbsArg" targetClass="RooAbsArg" version="[1-6]"\ source="RooRefCountList _clientList" target="_clientList" \ - code="{ _clientList = RooFit::STLRefCountListHelpers::convert(onfile._clientList); }" + code="{ _clientList = RooSTLRefCountList::convert(onfile._clientList); }" #pragma read sourceClass="RooAbsArg" targetClass="RooAbsArg" version="[1-6]"\ source="RooRefCountList _clientListValue" target="_clientListValue" \ - code="{ _clientListValue = RooFit::STLRefCountListHelpers::convert(onfile._clientListValue); }" + code="{ _clientListValue = RooSTLRefCountList::convert(onfile._clientListValue); }" #pragma read sourceClass="RooAbsArg" targetClass="RooAbsArg" version="[1-6]"\ source="RooRefCountList _clientListShape" target="_clientListShape" \ - code="{ _clientListShape = RooFit::STLRefCountListHelpers::convert(onfile._clientListShape); }" + code="{ _clientListShape = RooSTLRefCountList::convert(onfile._clientListShape); }" #pragma link C++ class RooSTLRefCountList+; #pragma link C++ class RooStringVar+ ; #pragma read sourceClass="RooAbsString" targetClass="RooStringVar" version="[1]" source="Int_t _len; char *_value" target="_string" code="{_string.assign(onfile._value, onfile._len);}" @@ -64,7 +64,6 @@ #pragma link C++ class RooAbsProxy+ ; #pragma link C++ class RooAbsReal+ ; #pragma link C++ class RooAbsRealLValue+ ; -#pragma link C++ class RooAbsRootFinder+ ; #pragma link C++ class RooAddGenContext+ ; #pragma link C++ class RooAddition+ ; #pragma link C++ class RooAddModel+ ; @@ -91,7 +90,6 @@ }" #pragma link C++ class RooConvCoefVar+ ; #pragma link C++ class RooConvGenContext+ ; -#pragma link C++ class RooConvIntegrandBinding+ ; #pragma link C++ class RooCurve+ ; #pragma link C++ class RooDataHist- ; #pragma link C++ class RooDataProjBinding+ ; @@ -119,20 +117,13 @@ #pragma link C++ class RooErrorVar+ ; #pragma link C++ class RooFitResult- ; #pragma link C++ class RooFIter+ ; -#pragma link C++ class RooFormula+ ; #pragma link C++ class RooFormulaVar+ ; #pragma link C++ class RooGenContext+ ; #pragma link C++ class RooGenericPdf+ ; -#pragma link C++ class RooGenProdProj+ ; -#pragma link C++ class RooGrid+ ; -#pragma link C++ class RooHistError+ ; #pragma link C++ class RooHist+ ; #pragma link C++ class RooImproperIntegrator1D+ ; -#pragma link C++ class RooIntegrator1D+ ; +#pragma link C++ class RooRombergIntegrator+ ; #pragma link C++ class RooBinIntegrator+ ; -#pragma link C++ class RooIntegrator2D+ ; -#pragma link C++ class RooIntegratorBinding+ ; -#pragma link C++ class RooInt+ ; #pragma link C++ class RooInvTransform+ ; #pragma link C++ class RooLinearVar+ ; #pragma link C++ class RooLinearCombination+ ; @@ -152,7 +143,6 @@ #pragma link C++ class RooMultiCategory+ ; #pragma link off class RooNameReg+ ; #pragma link C++ class RooNLLVar+ ; -#pragma link C++ class RooNumber+ ; #pragma link C++ class RooNumConvolution+ ; #pragma link C++ class RooNumConvPdf+ ; #pragma link C++ class RooNumIntConfig+ ; @@ -187,7 +177,6 @@ #pragma link C++ class RooCacheManager+ ; #pragma link C++ class RooRandomizeParamMCSModule+ ; #pragma link C++ class RooRangeBinning+ ; -#pragma link C++ class RooRealAnalytic+ ; #pragma link C++ class RooRealBinding+ ; #pragma link C++ class RooRealConstant+ ; #pragma link C++ class RooRealIntegral+ ; @@ -216,9 +205,6 @@ for (TObject * binning : onfile._altBinning) { _altBinning[binning->GetName()] = static_cast(binning); } \ }" #pragma link C++ class RooRefCountList+ ; -#pragma link C++ class RooScaledFunc+ ; -#pragma link C++ class RooSegmentedIntegrator1D+ ; -#pragma link C++ class RooSegmentedIntegrator2D+ ; #pragma link C++ class RooSetProxy+ ; #pragma link C++ class RooCollectionProxy+ ; #pragma read sourceClass="RooSetProxy" targetClass="RooCollectionProxy"; @@ -314,9 +300,6 @@ #pragma link C++ class RooBinningCategory+ ; #pragma link C++ class RooDerivative+ ; #pragma link C++ class RooFunctor+ ; -#pragma link C++ class RooGenFunction+ ; -#pragma link C++ class RooMultiGenFunction+ ; -#pragma link C++ class RooTFoamBinding+ ; #pragma link C++ class RooAdaptiveIntegratorND+ ; #pragma link C++ class RooNumGenConfig+ ; #pragma link C++ class RooMultiVarGaussian+ ; @@ -330,7 +313,12 @@ #pragma link C++ class RooRangeBoolean+ ; #pragma link C++ class RooVectorDataStore- ; #pragma link C++ class RooVectorDataStore::RealVector+; -#pragma link C++ class RooVectorDataStore::RealFullVector- ; +#pragma link C++ class RooVectorDataStore::RealFullVector+ ; +#pragma read sourceClass="RooVectorDataStore::RealFullVector" targetClass="RooVectorDataStore::RealFullVector" version="[1]" \ + source="std::vector* _vecE; std::vector* _vecEL; std::vector* _vecEH" target="_vecE, _vecEL, _vecEH" \ + code="{ if(onfile._vecE) { _vecE = *onfile._vecE; } \ + if(onfile._vecEL) { _vecEL = *onfile._vecEL; } \ + if(onfile._vecEH) { _vecEH = *onfile._vecEH; } }"; #pragma link C++ class RooVectorDataStore::CatVector+; #pragma read sourceClass="RooVectorDataStore::CatVector" targetClass="RooVectorDataStore::CatVector" version="[1]" \ source="std::vector _vec;" target="_vec" \ @@ -345,6 +333,7 @@ #pragma link C++ class RooMoment+ ; #pragma link C++ class RooFirstMoment+ ; #pragma link C++ class RooSecondMoment+ ; +#pragma link C++ class RooStats::ModelConfig+; #pragma link C++ class RooStudyManager+ ; #pragma link C++ class RooStudyPackage+ ; #pragma link C++ class RooAbsStudy+ ; diff --git a/roofit/roofitcore/inc/RooAbsAnaConvPdf.h b/roofit/roofitcore/inc/RooAbsAnaConvPdf.h index a112df06db178..62552120e7e1b 100644 --- a/roofit/roofitcore/inc/RooAbsAnaConvPdf.h +++ b/roofit/roofitcore/inc/RooAbsAnaConvPdf.h @@ -63,7 +63,7 @@ class RooAbsAnaConvPdf : public RooAbsPdf { bool forceAnalyticalInt(const RooAbsArg& dep) const override ; virtual double coefficient(Int_t basisIndex) const = 0 ; - virtual RooArgSet* coefVars(Int_t coefIdx) const ; + virtual RooFit::OwningPtr coefVars(Int_t coefIdx) const ; bool isDirectGenSafe(const RooAbsArg& arg) const override ; @@ -80,6 +80,8 @@ class RooAbsAnaConvPdf : public RooAbsPdf { return const_cast(this)->convVar(); } + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + protected: double getCoefNorm(Int_t coefIdx, const RooArgSet* nset, const TNamed* rangeName) const ; diff --git a/roofit/roofitcore/inc/RooAbsArg.h b/roofit/roofitcore/inc/RooAbsArg.h index 0f3f547b44911..14cf2982419f0 100644 --- a/roofit/roofitcore/inc/RooAbsArg.h +++ b/roofit/roofitcore/inc/RooAbsArg.h @@ -16,16 +16,19 @@ #ifndef ROO_ABS_ARG #define ROO_ABS_ARG -#include "TNamed.h" -#include "TObjArray.h" -#include "TRefArray.h" -#include "RooPrintable.h" -#include "RooSTLRefCountList.h" -#include "RooAbsCache.h" -#include "RooNameReg.h" -#include "RooLinkedListIter.h" +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include + #include #include #include @@ -33,6 +36,7 @@ #include #include #include +#include class TTree ; @@ -49,6 +53,11 @@ using RooSetProxy = RooCollectionProxy; using RooListProxy = RooCollectionProxy; class RooExpensiveObjectCache ; class RooWorkspace ; +namespace RooFit { +namespace Detail { +class CodeSquashContext; +} +} class RooRefArray : public TObjArray { public: @@ -91,7 +100,6 @@ class RooAbsArg : public TNamed, public RooPrintable { virtual bool isDerived() const { return true ; } - bool isCloneOf(const RooAbsArg& other) const ; /// Check whether this object depends on values from an element in the `serverList`. /// @@ -110,7 +118,13 @@ class RooAbsArg : public TNamed, public RooPrintable { return dependsOn(server,ignoreArg,true) ; } bool dependsOn(const RooAbsCollection& serverList, const RooAbsArg* ignoreArg=nullptr, bool valueOnly=false) const ; - bool dependsOn(const RooAbsArg& server, const RooAbsArg* ignoreArg=nullptr, bool valueOnly=false) const ; + /// Test whether we depend on (ie, are served by) the specified object. + /// Note that RooAbsArg objects are considered equivalent if they have + /// the same name. + inline bool dependsOn(const RooAbsArg& server, const RooAbsArg* ignoreArg=nullptr, bool valueOnly=false) const { + return dependsOn(server.namePtr(), ignoreArg, valueOnly); + } + bool dependsOn(TNamed const* namePtr, const RooAbsArg* ignoreArg=nullptr, bool valueOnly=false) const ; bool overlaps(const RooAbsArg& testArg, bool valueOnly=false) const ; bool hasClients() const { return !_clientList.empty(); } @@ -156,12 +170,9 @@ class RooAbsArg : public TNamed, public RooPrintable { } // --- Obsolete functions for backward compatibility - /// \deprecated Use getObservables() - inline RooArgSet* getDependents(const RooArgSet& set) const { return getObservables(set) ; } - /// \deprecated Use getObservables() - inline RooArgSet* getDependents(const RooAbsData* set) const { return getObservables(set) ; } - /// \deprecated Use getObservables() - inline RooArgSet* getDependents(const RooArgSet* depList) const { return getObservables(depList) ; } + RooFit::OwningPtr getDependents(const RooArgSet& set) const; + RooFit::OwningPtr getDependents(const RooAbsData* set) const; + RooFit::OwningPtr getDependents(const RooArgSet* depList) const; /// \deprecated Use observableOverlaps() inline bool dependentOverlaps(const RooAbsData* dset, const RooAbsArg& testArg) const { return observableOverlaps(dset,testArg) ; } /// \deprecated Use observableOverlaps() @@ -245,7 +256,7 @@ class RooAbsArg : public TNamed, public RooPrintable { /// Create a fundamental-type object that stores our type of value. The /// created object will have a valid value, but not necessarily the same /// as our value. The caller is responsible for deleting the returned object. - virtual RooAbsArg *createFundamental(const char* newname=nullptr) const = 0; + virtual RooFit::OwningPtr createFundamental(const char* newname=nullptr) const = 0; /// Is this argument an l-value, i.e., can it appear on the left-hand side /// of an assignment expression? LValues are also special since they can @@ -257,6 +268,7 @@ class RooAbsArg : public TNamed, public RooPrintable { // Server redirection interface bool redirectServers(const RooAbsCollection& newServerList, bool mustReplaceAll=false, bool nameChange=false, bool isRecursionStep=false) ; + bool redirectServers(std::unordered_map const& replacements); bool recursiveRedirectServers(const RooAbsCollection& newServerList, bool mustReplaceAll=false, bool nameChange=false, bool recurseInNewSet=true) ; virtual bool redirectServersHook(const RooAbsCollection & newServerList, bool mustReplaceAll, @@ -266,7 +278,9 @@ class RooAbsArg : public TNamed, public RooPrintable { void addServer(RooAbsArg& server, bool valueProp=true, bool shapeProp=false, std::size_t refCount = 1); void addServerList(RooAbsCollection& serverList, bool valueProp=true, bool shapeProp=false) ; - void replaceServer(RooAbsArg& oldServer, RooAbsArg& newServer, bool valueProp, bool shapeProp) ; + void + R__SUGGEST_ALTERNATIVE("This interface is unsafe! Use RooAbsArg::redirectServers()") + replaceServer(RooAbsArg& oldServer, RooAbsArg& newServer, bool valueProp, bool shapeProp) ; void changeServer(RooAbsArg& server, bool valueProp, bool shapeProp) ; void removeServer(RooAbsArg& server, bool force=false) ; RooAbsArg *findNewServer(const RooAbsCollection &newSet, bool nameChange) const; @@ -277,34 +291,22 @@ class RooAbsArg : public TNamed, public RooPrintable { // Parameter & observable interpretation of servers - RooArgSet* getVariables(bool stripDisconnected=true) const ; - RooArgSet* getParameters(const RooAbsData* data, bool stripDisconnected=true) const ; - /// Return the parameters of this p.d.f when used in conjuction with dataset 'data' - RooArgSet* getParameters(const RooAbsData& data, bool stripDisconnected=true) const { - return getParameters(&data,stripDisconnected) ; - } - /// Return the parameters of the p.d.f given the provided set of observables - RooArgSet* getParameters(const RooArgSet& observables, bool stripDisconnected=true) const { - return getParameters(&observables,stripDisconnected); - } - RooArgSet* getParameters(const RooArgSet* observables, bool stripDisconnected=true) const; + RooFit::OwningPtr getVariables(bool stripDisconnected=true) const ; + RooFit::OwningPtr getParameters(const RooAbsData* data, bool stripDisconnected=true) const; + RooFit::OwningPtr getParameters(const RooAbsData& data, bool stripDisconnected=true) const; + RooFit::OwningPtr getParameters(const RooArgSet& observables, bool stripDisconnected=true) const; + RooFit::OwningPtr getParameters(const RooArgSet* observables, bool stripDisconnected=true) const; virtual bool getParameters(const RooArgSet* observables, RooArgSet& outputSet, bool stripDisconnected=true) const; - /// Given a set of possible observables, return the observables that this PDF depends on. - RooArgSet* getObservables(const RooArgSet& set, bool valueOnly=true) const { - return getObservables(&set,valueOnly) ; - } - RooArgSet* getObservables(const RooAbsData* data) const ; - /// Return the observables of this pdf given the observables defined by `data`. - RooArgSet* getObservables(const RooAbsData& data) const { - return getObservables(&data) ; - } - RooArgSet* getObservables(const RooArgSet* depList, bool valueOnly=true) const ; + RooFit::OwningPtr getObservables(const RooArgSet& set, bool valueOnly=true) const; + RooFit::OwningPtr getObservables(const RooAbsData* data) const; + RooFit::OwningPtr getObservables(const RooAbsData& data) const; + RooFit::OwningPtr getObservables(const RooArgSet* depList, bool valueOnly=true) const; bool getObservables(const RooAbsCollection* depList, RooArgSet& outputSet, bool valueOnly=true) const; bool observableOverlaps(const RooAbsData* dset, const RooAbsArg& testArg) const ; bool observableOverlaps(const RooArgSet* depList, const RooAbsArg& testArg) const ; virtual bool checkObservables(const RooArgSet* nset) const ; bool recursiveCheckObservables(const RooArgSet* nset) const ; - RooArgSet* getComponents() const ; + RooFit::OwningPtr getComponents() const ; @@ -362,7 +364,6 @@ class RooAbsArg : public TNamed, public RooPrintable { inline bool isConstant() const { return _isConstant ; //getAttribute("Constant") ; } - RooLinkedList getCloningAncestors() const ; // Sorting Int_t Compare(const TObject* other) const override ; @@ -380,7 +381,7 @@ class RooAbsArg : public TNamed, public RooPrintable { return true ; } virtual bool hasRange(const char*) const { - // Has this argument a defined range (dummy interface always returns flase) + // Has this argument a defined range (dummy interface always returns false) return false ; } @@ -530,7 +531,7 @@ class RooAbsArg : public TNamed, public RooPrintable { // * passing an initializer list // Before, there was only an overload taking a RooArg set, which caused an // implicit creation of a RooArgSet when a RooArgList was passed. This needs - // to be avoided, because if the passed RooArgList is owning the argumnets, + // to be avoided, because if the passed RooArgList is owning the arguments, // this information will be lost with the copy. The solution is to have one // overload that takes a general RooAbsCollection, and one overload for // RooArgList that is invoked in the case of passing an initializer list. @@ -549,6 +550,7 @@ class RooAbsArg : public TNamed, public RooPrintable { void setProhibitServerRedirect(bool flag) { _prohibitServerRedirect = flag ; } void setWorkspace(RooWorkspace &ws) { _myws = &ws; } + inline RooWorkspace* workspace() const { return _myws; } RooAbsProxy* getProxy(Int_t index) const ; Int_t numProxies() const ; @@ -577,10 +579,12 @@ class RooAbsArg : public TNamed, public RooPrintable { virtual void applyWeightSquared(bool flag); - virtual std::unique_ptr fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const; + virtual std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const; virtual bool isCategory() const { return false; } + virtual void translate(RooFit::Detail::CodeSquashContext &ctx) const; + protected: void graphVizAddConnections(std::set >&) ; @@ -691,7 +695,7 @@ class RooAbsArg : public TNamed, public RooPrintable { // Debug stuff static bool _verboseDirty ; // Static flag controlling verbose messaging for dirty state changes static bool _inhibitDirty ; // Static flag controlling global inhibit of dirty state propagation - bool _deleteWatch ; //! Delete watch flag + bool _deleteWatch = false; //! Delete watch flag bool inhibitDirty() const ; @@ -701,38 +705,38 @@ class RooAbsArg : public TNamed, public RooPrintable { /// Returns the token for retrieving results in the BatchMode. For internal use only. std::size_t dataToken() const { return _dataToken; } - - /// Sets the token for retrieving results in the BatchMode. For internal use only. - void setDataToken(std::size_t index) { _dataToken = index; } + bool hasDataToken() const { return _dataToken != std::numeric_limits::max(); } + void setDataToken(std::size_t index); + void resetDataToken() { _dataToken = std::numeric_limits::max(); } protected: - mutable bool _valueDirty ; // Flag set if value needs recalculating because input values modified - mutable bool _shapeDirty ; // Flag set if value needs recalculating because input shapes modified + mutable bool _valueDirty = true; // Flag set if value needs recalculating because input values modified + mutable bool _shapeDirty = true; // Flag set if value needs recalculating because input shapes modified - mutable OperMode _operMode ; // Dirty state propagation mode + mutable OperMode _operMode = Auto; // Dirty state propagation mode mutable bool _fast = false; // Allow fast access mode in getVal() and proxies // Owned components - RooArgSet* _ownedComponents ; //! Set of owned component + RooArgSet* _ownedComponents = nullptr; //! Set of owned component - mutable bool _prohibitServerRedirect ; //! Prohibit server redirects -- Debugging tool + mutable bool _prohibitServerRedirect = false; //! Prohibit server redirects -- Debugging tool - mutable RooExpensiveObjectCache* _eocache{nullptr}; // Pointer to global cache manager for any expensive components created by this object + mutable RooExpensiveObjectCache* _eocache{nullptr}; //! Pointer to global cache manager for any expensive components created by this object - mutable const TNamed * _namePtr ; //! De-duplicated name pointer. This will be equal for all objects with the same name. - bool _isConstant ; //! Cached isConstant status + mutable const TNamed * _namePtr = nullptr; //! De-duplicated name pointer. This will be equal for all objects with the same name. + bool _isConstant = false; //! Cached isConstant status - mutable bool _localNoInhibitDirty ; //! Prevent 'AlwaysDirty' mode for this node + mutable bool _localNoInhibitDirty = false; //! Prevent 'AlwaysDirty' mode for this node /* RooArgSet _leafNodeCache ; //! Cached leaf nodes */ /* RooArgSet _branchNodeCache //! Cached branch nodes */ - mutable RooWorkspace *_myws; //! In which workspace do I live, if any + mutable RooWorkspace *_myws = nullptr; //! In which workspace do I live, if any - std::size_t _dataToken = 0; //! Set by the RooFitDriver for this arg to retrieve its result in the run context + std::size_t _dataToken = std::numeric_limits::max(); //! Set by the RooFitDriver for this arg to retrieve its result in the run context - /// \cond Internal + /// \cond ROOFIT_INTERNAL // Legacy streamers need the following statics: friend class RooFitResult; @@ -742,7 +746,11 @@ class RooAbsArg : public TNamed, public RooPrintable { static std::stack _ioReadStack ; // reading stack /// \endcond - ClassDefOverride(RooAbsArg,8) // Abstract variable + private: + void substituteServer(RooAbsArg *oldServer, RooAbsArg *newServer); + bool callRedirectServersHook(RooAbsCollection const& newSet, bool mustReplaceAll, bool nameChange, bool isRecursionStep); + + ClassDefOverride(RooAbsArg,9) // Abstract variable }; std::ostream& operator<<(std::ostream& os, const RooAbsArg &arg); diff --git a/roofit/roofitcore/inc/RooAbsCachedPdf.h b/roofit/roofitcore/inc/RooAbsCachedPdf.h index 6d4efbfd0fc96..230f8fc5e2424 100644 --- a/roofit/roofitcore/inc/RooAbsCachedPdf.h +++ b/roofit/roofitcore/inc/RooAbsCachedPdf.h @@ -57,6 +57,7 @@ class RooAbsCachedPdf : public RooAbsPdf { Int_t getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName=nullptr) const override ; double analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName=nullptr) const override ; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; class PdfCacheElem : public RooAbsCacheElement { public: @@ -70,6 +71,7 @@ class RooAbsCachedPdf : public RooAbsPdf { RooDataHist* hist() { return _hist.get() ; } const RooArgSet& nset() { return _nset ; } RooChangeTracker* paramTracker() { return _paramTracker.get() ; } + void setUnitNorm() { pdf()->setUnitNorm(true); } private: // Payload @@ -81,9 +83,11 @@ class RooAbsCachedPdf : public RooAbsPdf { } ; + using CacheElem = PdfCacheElem; + protected: - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; PdfCacheElem* getCache(const RooArgSet* nset, bool recalculate=true) const ; @@ -99,8 +103,8 @@ class RooAbsCachedPdf : public RooAbsPdf { return new PdfCacheElem(*this,nset) ; } virtual const char* inputBaseName() const = 0 ; - virtual RooArgSet* actualObservables(const RooArgSet& nset) const = 0 ; - virtual RooArgSet* actualParameters(const RooArgSet& nset) const = 0 ; + virtual RooFit::OwningPtr actualObservables(const RooArgSet& nset) const = 0 ; + virtual RooFit::OwningPtr actualParameters(const RooArgSet& nset) const = 0 ; virtual RooAbsArg& pdfObservable(RooAbsArg& histObservable) const { return histObservable ; } virtual void fillCacheObject(PdfCacheElem& cache) const = 0 ; diff --git a/roofit/roofitcore/inc/RooAbsCachedReal.h b/roofit/roofitcore/inc/RooAbsCachedReal.h index cbce297cd7330..d649bb4017073 100644 --- a/roofit/roofitcore/inc/RooAbsCachedReal.h +++ b/roofit/roofitcore/inc/RooAbsCachedReal.h @@ -75,6 +75,9 @@ class RooAbsCachedReal : public RooAbsReal { bool cacheSource() { return _cacheSource ; } void setCacheSource(bool flag) { _cacheSource = flag ; } + // Not Relevant for RooAbsCachedReal, only the RooAbsCachedPdf. + void setUnitNorm() { } + private: // Payload RooHistFunc* _func ; @@ -84,6 +87,8 @@ class RooAbsCachedReal : public RooAbsReal { bool _cacheSource ; } ; + using CacheElem = FuncCacheElem; + FuncCacheElem* getCache(const RooArgSet* nset) const ; virtual const char* payloadUniqueSuffix() const { return nullptr ; } @@ -95,8 +100,8 @@ class RooAbsCachedReal : public RooAbsReal { } virtual FuncCacheElem* createCache(const RooArgSet* nset) const ; virtual const char* inputBaseName() const = 0 ; - virtual RooArgSet* actualObservables(const RooArgSet& nset) const = 0 ; - virtual RooArgSet* actualParameters(const RooArgSet& nset) const = 0 ; + virtual RooFit::OwningPtr actualObservables(const RooArgSet& nset) const = 0 ; + virtual RooFit::OwningPtr actualParameters(const RooArgSet& nset) const = 0 ; virtual void fillCacheObject(FuncCacheElem& cache) const = 0 ; mutable RooObjCacheManager _cacheMgr ; /// #include -#ifdef R__LESS_INCLUDES class RooCatType; -#else -#include "RooCatType.h" -#endif - class TTree; class RooVectorDataStore; class Roo1DTable; @@ -90,7 +85,7 @@ class RooAbsCategory : public RooAbsArg { return true ; } - RooAbsArg *createFundamental(const char* newname=nullptr) const override; + RooFit::OwningPtr createFundamental(const char* newname=nullptr) const override; /// Iterator for category state names. Points to pairs of index and name. std::map::const_iterator begin() const { diff --git a/roofit/roofitcore/inc/RooAbsCategoryLValue.h b/roofit/roofitcore/inc/RooAbsCategoryLValue.h index ceede1b2e3f4c..0c71a1d1915f1 100644 --- a/roofit/roofitcore/inc/RooAbsCategoryLValue.h +++ b/roofit/roofitcore/inc/RooAbsCategoryLValue.h @@ -16,11 +16,12 @@ #ifndef ROO_ABS_CATEGORY_LVALUE #define ROO_ABS_CATEGORY_LVALUE -#include "RooAbsCategory.h" -#include "RooAbsLValue.h" +#include +#include + #include #include -#include +#include // for std::pair class RooAbsCategoryLValue : public RooAbsCategory, public RooAbsLValue { public: @@ -30,7 +31,7 @@ class RooAbsCategoryLValue : public RooAbsCategory, public RooAbsLValue { } RooAbsCategoryLValue(const char *name, const char *title); RooAbsCategoryLValue(const RooAbsCategoryLValue& other, const char* name=nullptr) ; - ~RooAbsCategoryLValue() override; + ~RooAbsCategoryLValue() override = default; // Value modifiers //////////////////////////////////////////////////////////////////////////////// @@ -94,7 +95,7 @@ class RooAbsCategoryLValue : public RooAbsCategory, public RooAbsLValue { const RooAbsBinning* getBinningPtr(const char* /*rangeName*/) const override { return nullptr ; } std::list getBinningNames() const override { return std::list(1, "") ; } - Int_t getBin(const RooAbsBinning* /*ptr*/) const override { return getBin((const char*)0) ; } + Int_t getBin(const RooAbsBinning* /*ptr*/) const override { return getBin((const char*)nullptr) ; } inline void setConstant(bool value= true) { diff --git a/roofit/roofitcore/inc/RooAbsCollection.h b/roofit/roofitcore/inc/RooAbsCollection.h index 55503c0d6c01a..1a72f70a7dc27 100644 --- a/roofit/roofitcore/inc/RooAbsCollection.h +++ b/roofit/roofitcore/inc/RooAbsCollection.h @@ -22,13 +22,14 @@ #include "RooPrintable.h" #include "RooCmdArg.h" #include "RooLinkedListIter.h" +#include "RooFit/UniqueId.h" // The range casts are not used in this file, but if you want to work with // RooFit collections you also want to have static_range_cast and // dynamic_range_cast available without including RangeCast.h every time. -#include "ROOT/RRangeCast.hxx" +#include -#include "ROOT/RSpan.hxx" +#include #include #include @@ -53,8 +54,6 @@ ROOT::RRangeCast dynamic_range_cast(Range_t &&coll) } -class RooCmdArg; - namespace RooFit { namespace Detail { struct HashAssistedFind; @@ -90,6 +89,12 @@ class RooAbsCollection : public TObject, public RooPrintable { // Move constructor RooAbsCollection(RooAbsCollection && other); + /// Returns a unique ID that is different for every instantiated + /// RooAbsCollection. This ID can be used to check whether two collections + /// are the same object, which is safer than memory address comparisons that + /// might result in false positives when memory is recycled. + RooFit::UniqueId const& uniqueId() const { return _uniqueId; } + // Copy list and contents (and optionally 'deep' servers) RooAbsCollection *snapshot(bool deepCopy=true) const ; bool snapshot(RooAbsCollection& output, bool deepCopy=true) const ; @@ -110,7 +115,16 @@ class RooAbsCollection : public TObject, public RooPrintable { // List content management virtual bool add(const RooAbsArg& var, bool silent=false) ; +// The following function is not memory safe, because it takes ownership of var +// without moving it. It is not publicly available in the memory safe +// interfaces mode. +#ifdef ROOFIT_MEMORY_SAFE_INTERFACES +protected: +#endif virtual bool addOwned(RooAbsArg& var, bool silent=false); +#ifdef ROOFIT_MEMORY_SAFE_INTERFACES +public: +#endif bool addOwned(std::unique_ptr var, bool silent=false); virtual RooAbsArg *addClone(const RooAbsArg& var, bool silent=false) ; virtual bool replace(const RooAbsArg& var1, const RooAbsArg& var2) ; @@ -308,10 +322,10 @@ class RooAbsCollection : public TObject, public RooPrintable { Int_t defaultPrintContents(Option_t* opt) const override ; // Latex printing methods - void printLatex(const RooCmdArg& arg1=RooCmdArg(), const RooCmdArg& arg2=RooCmdArg(), - const RooCmdArg& arg3=RooCmdArg(), const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(), const RooCmdArg& arg8=RooCmdArg()) const ; + void printLatex(const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; void printLatex(std::ostream& ofs, Int_t ncol, const char* option="NEYU", Int_t sigDigit=1, const RooLinkedList& siblingLists=RooLinkedList(), const RooCmdArg* formatCmd=nullptr) const ; @@ -363,9 +377,6 @@ class RooAbsCollection : public TObject, public RooPrintable { void deleteList() ; - // Support for snapshot method - bool addServerClonesToList(const RooAbsArg& var) ; - inline TNamed* structureTag() { if (_structureTag==nullptr) makeStructureTag() ; return _structureTag ; } inline TNamed* typedStructureTag() { if (_typedStructureTag==nullptr) makeTypedStructureTag() ; return _typedStructureTag ; } @@ -398,6 +409,8 @@ class RooAbsCollection : public TObject, public RooPrintable { void insert(RooAbsArg*); + const RooFit::UniqueId _uniqueId; //! + ClassDefOverride(RooAbsCollection,3) // Collection of RooAbsArg objects }; diff --git a/roofit/roofitcore/inc/RooAbsData.h b/roofit/roofitcore/inc/RooAbsData.h index 285e9a6a10bc2..3fde00fd1b3ff 100644 --- a/roofit/roofitcore/inc/RooAbsData.h +++ b/roofit/roofitcore/inc/RooAbsData.h @@ -20,18 +20,18 @@ #include "RooAbsCategory.h" #include "RooArgSet.h" #include "RooArgList.h" -#include "RooSpan.h" #include "RooNameReg.h" #include "RooFit/UniqueId.h" #include "RooFit/Detail/DataMap.h" -#include // R__DEPRECATED -#include "TNamed.h" +#include + +#include +#include #include #include -class RooAbsArg; class RooAbsReal ; class RooRealVar; class RooAbsRealLValue; @@ -45,12 +45,7 @@ class TH2F; class RooAbsBinning ; class Roo1DTable ; class RooAbsDataStore ; -template class TMatrixTSym; -using TMatrixDSym = TMatrixTSym; class RooFormulaVar; -namespace RooBatchCompute{ -struct RunContext; -} namespace RooFit { namespace TestStatistics { class RooAbsL; @@ -69,15 +64,15 @@ class RooAbsData : public TNamed, public RooPrintable { RooAbsData& operator=(const RooAbsData& other); ~RooAbsData() override ; - virtual RooAbsData* emptyClone(const char* newName=nullptr, const char* newTitle=nullptr, const RooArgSet* vars=nullptr, const char* wgtVarName=nullptr) const = 0 ; + virtual RooFit::OwningPtr emptyClone(const char* newName=nullptr, const char* newTitle=nullptr, const RooArgSet* vars=nullptr, const char* wgtVarName=nullptr) const = 0 ; // Reduction methods - RooAbsData* reduce(const RooCmdArg& arg1,const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg(),const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(),const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg()) ; - RooAbsData* reduce(const char* cut) ; - RooAbsData* reduce(const RooFormulaVar& cutVar) ; - RooAbsData* reduce(const RooArgSet& varSubset, const char* cut=nullptr) ; - RooAbsData* reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) ; + RooFit::OwningPtr reduce(const RooCmdArg& arg1,const RooCmdArg& arg2={},const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={},const RooCmdArg& arg7={},const RooCmdArg& arg8={}) ; + RooFit::OwningPtr reduce(const char* cut) ; + RooFit::OwningPtr reduce(const RooFormulaVar& cutVar) ; + RooFit::OwningPtr reduce(const RooArgSet& varSubset, const char* cut=nullptr) ; + RooFit::OwningPtr reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) ; RooAbsDataStore* store() { return _dstore.get(); } const RooAbsDataStore* store() const { return _dstore.get(); } @@ -99,7 +94,7 @@ class RooAbsData : public TNamed, public RooPrintable { virtual bool changeObservableName(const char* from, const char* to) ; // Add one ore more rows of data - virtual void add(const RooArgSet& row, double weight=1, double weightError=0.0) = 0 ; // DERIVED + virtual void add(const RooArgSet& row, double weight=1) = 0 ; // DERIVED virtual void fill() ; // Load a given row of data @@ -133,8 +128,8 @@ class RooAbsData : public TNamed, public RooPrintable { virtual const RooArgSet* get(Int_t index) const ; - using RealSpans = std::map>; - using CategorySpans = std::map>; + using RealSpans = std::map>; + using CategorySpans = std::map>; RealSpans getBatches(std::size_t first = 0, std::size_t len = std::numeric_limits::max()) const; CategorySpans getCategoryBatches(std::size_t first = 0, std::size_t len = std::numeric_limits::max()) const; @@ -143,7 +138,7 @@ class RooAbsData : public TNamed, public RooPrintable { /// Return event weights of all events in range [first, first+len). /// If no contiguous structure of weights is stored, an empty batch can be returned. /// This indicates that the weight is constant. Use weight() to retrieve it. - virtual RooSpan getWeightBatch(std::size_t first, std::size_t len, bool sumW2=false) const = 0; + virtual std::span getWeightBatch(std::size_t first, std::size_t len, bool sumW2=false) const = 0; /// Return number of entries in dataset, i.e., count unweighted entries. virtual Int_t numEntries() const ; @@ -172,39 +167,36 @@ class RooAbsData : public TNamed, public RooPrintable { virtual Roo1DTable* table(const RooAbsCategory& cat, const char* cuts="", const char* opts="") const ; /// \see RooPlot* plotOn(RooPlot* frame, const RooLinkedList& cmdList) const virtual RooPlot* plotOn(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; virtual RooPlot* plotOn(RooPlot* frame, const RooLinkedList& cmdList) const ; // WVE --- This needs to be public to avoid CINT problems struct PlotOpt { - PlotOpt() : cuts(""), drawOptions("P"), bins(nullptr), etype(RooAbsData::Poisson), cutRange(nullptr), histName(nullptr), histInvisible(false), - addToHistName(nullptr),addToWgtSelf(1.),addToWgtOther(1.),xErrorSize(1),refreshFrameNorm(false),correctForBinWidth(true), - scaleFactor(1.) {} ; - const char* cuts ; - Option_t* drawOptions ; - RooAbsBinning* bins ; - RooAbsData::ErrorType etype ; - const char* cutRange ; - const char* histName ; - bool histInvisible ; - const char* addToHistName ; - double addToWgtSelf ; - double addToWgtOther ; - double xErrorSize ; - bool refreshFrameNorm ; - bool correctForBinWidth ; - double scaleFactor ; + const char* cuts = ""; + Option_t* drawOptions = "P"; + RooAbsBinning* bins = nullptr; + RooAbsData::ErrorType etype = RooAbsData::Poisson; + const char* cutRange = nullptr; + const char* histName = nullptr; + bool histInvisible = false; + const char* addToHistName = nullptr; + double addToWgtSelf = 1.0; + double addToWgtOther = 1.0; + double xErrorSize = 1.0; + bool refreshFrameNorm = false; + bool correctForBinWidth = true; + double scaleFactor = 1.0; } ; // Split a dataset by a category - virtual TList* split(const RooAbsCategory& splitCat, bool createEmptyDataSets=false) const ; + virtual RooFit::OwningPtr split(const RooAbsCategory& splitCat, bool createEmptyDataSets=false) const ; // Split a dataset by categories of a RooSimultaneous - virtual TList* split(const RooSimultaneous& simpdf, bool createEmptyDataSets=false) const ; + virtual RooFit::OwningPtr split(const RooSimultaneous& simpdf, bool createEmptyDataSets=false) const ; // Fast splitting for SimMaster setData bool canSplitFast() const ; @@ -212,21 +204,15 @@ class RooAbsData : public TNamed, public RooPrintable { /// Calls createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooLinkedList& argList) const TH1 *createHistogram(const char *name, const RooAbsRealLValue& xvar, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; - // Developer note: the `binArgX` parameter has no default `none` value, - // because then the signature would be ambiguous with the deprecated bin - // integer overload below. When the deprecated overload is removed, a default - // value must be set (tutorial failures will remind us to do that). + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; TH1 *createHistogram(const char* varNameList, - const RooCmdArg& binArgX, const RooCmdArg& binArgY=RooCmdArg::none(), - const RooCmdArg& binArgZ=RooCmdArg::none()) const; + const RooCmdArg& binArgX={}, const RooCmdArg& binArgY={}, + const RooCmdArg& binArgZ={}) const; /// Create and fill a ROOT histogram TH1,TH2 or TH3 with the values of this dataset. TH1 *createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooLinkedList& argList) const ; - TH1 *createHistogram(const char* varNameList, Int_t xbins=0, Int_t ybins=0, Int_t zbins=0) const - R__DEPRECATED(6, 30, "Use the overload of RooAbsData::createHistogram that takes RooFit command arguments."); TH2F* createHistogram(const RooAbsRealLValue& var1, const RooAbsRealLValue& var2, const char* cuts="", const char *name= "hist") const; TH2F* createHistogram(const RooAbsRealLValue& var1, const RooAbsRealLValue& var2, int nx, int ny, @@ -262,19 +248,19 @@ class RooAbsData : public TNamed, public RooPrintable { double covariance(RooRealVar &x,RooRealVar &y, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcov(x,y,cutSpec,cutRange,false) ; } double correlation(RooRealVar &x,RooRealVar &y, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcov(x,y,cutSpec,cutRange,true) ; } - TMatrixDSym* covarianceMatrix(const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return covarianceMatrix(*get(),cutSpec,cutRange) ; } - TMatrixDSym* correlationMatrix(const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return correlationMatrix(*get(),cutSpec,cutRange) ; } - TMatrixDSym* covarianceMatrix(const RooArgList& vars, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcovMatrix(vars,cutSpec,cutRange,false) ; } - TMatrixDSym* correlationMatrix(const RooArgList& vars, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcovMatrix(vars,cutSpec,cutRange,true) ; } + RooFit::OwningPtr covarianceMatrix(const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return covarianceMatrix(*get(),cutSpec,cutRange) ; } + RooFit::OwningPtr correlationMatrix(const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return correlationMatrix(*get(),cutSpec,cutRange) ; } + RooFit::OwningPtr covarianceMatrix(const RooArgList& vars, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcovMatrix(vars,cutSpec,cutRange,false) ; } + RooFit::OwningPtr correlationMatrix(const RooArgList& vars, const char* cutSpec=nullptr, const char* cutRange=nullptr) const { return corrcovMatrix(vars,cutSpec,cutRange,true) ; } RooRealVar* meanVar(const RooRealVar &var, const char* cutSpec=nullptr, const char* cutRange=nullptr) const ; RooRealVar* rmsVar(const RooRealVar &var, const char* cutSpec=nullptr, const char* cutRange=nullptr) const ; virtual RooPlot* statOn(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; virtual RooPlot* statOn(RooPlot* frame, const char *what, const char *label= "", Int_t sigDigits= 2, @@ -288,8 +274,6 @@ class RooAbsData : public TNamed, public RooPrintable { bool hasFilledCache() const ; void addOwnedComponent(const char* idxlabel, RooAbsData& data) ; - static void claimVars(RooAbsData*) ; - static bool releaseVars(RooAbsData*) ; enum StorageType { Tree, Vector, Composite }; @@ -329,8 +313,10 @@ class RooAbsData : public TNamed, public RooPrintable { StorageType storageType; + void initializeVars(RooArgSet const& vars); + double corrcov(const RooRealVar& x, const RooRealVar& y, const char* cutSpec, const char* cutRange, bool corr) const ; - TMatrixDSym* corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, bool corr) const ; + RooFit::OwningPtr corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, bool corr) const ; virtual void optimizeReadingWithCaching(RooAbsArg& arg, const RooArgSet& cacheList, const RooArgSet& keepObsList) ; bool allClientsCached(RooAbsArg*, const RooArgSet&) ; @@ -353,7 +339,7 @@ class RooAbsData : public TNamed, public RooPrintable { virtual void setArgStatus(const RooArgSet& set, bool active) ; virtual void attachCache(const RooAbsArg* newOwner, const RooArgSet& cachedVars) ; - virtual RooAbsData* reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, + virtual std::unique_ptr reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, std::size_t nStart = 0, std::size_t = std::numeric_limits::max()) = 0 ; RooRealVar* dataRealVar(const char* methodname, const RooRealVar& extVar) const ; @@ -371,6 +357,8 @@ class RooAbsData : public TNamed, public RooPrintable { mutable const TNamed * _namePtr = nullptr; /// _uniqueId; /// getWeightBatch(std::size_t first, std::size_t len) const = 0; + virtual std::span getWeightBatch(std::size_t first, std::size_t len) const = 0; // Change observable name virtual bool changeObservableName(const char* from, const char* to) =0 ; diff --git a/roofit/roofitcore/inc/RooAbsFunc.h b/roofit/roofitcore/inc/RooAbsFunc.h index c56595df61896..4a022d02d776e 100644 --- a/roofit/roofitcore/inc/RooAbsFunc.h +++ b/roofit/roofitcore/inc/RooAbsFunc.h @@ -16,8 +16,8 @@ #ifndef ROO_ABS_FUNC #define ROO_ABS_FUNC -#include "Rtypes.h" -#include "RooSpan.h" +#include +#include #include #include diff --git a/roofit/roofitcore/inc/RooAbsIntegrator.h b/roofit/roofitcore/inc/RooAbsIntegrator.h index 1d4f855d0658d..c0d57c65044b9 100644 --- a/roofit/roofitcore/inc/RooAbsIntegrator.h +++ b/roofit/roofitcore/inc/RooAbsIntegrator.h @@ -23,10 +23,6 @@ class RooAbsIntegrator : public TObject { public: RooAbsIntegrator() ; RooAbsIntegrator(const RooAbsFunc& function, bool printEvalCounter=false); - /// Destructor - inline ~RooAbsIntegrator() override { - } - virtual RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const = 0 ; /// Is integrator in valid state inline bool isValid() const { @@ -51,11 +47,6 @@ class RooAbsIntegrator : public TObject { double calculate(const double *yvec=nullptr) ; virtual double integral(const double *yvec=nullptr)=0 ; - virtual bool canIntegrate1D() const = 0 ; - virtual bool canIntegrate2D() const = 0 ; - virtual bool canIntegrateND() const = 0 ; - virtual bool canIntegrateOpenEnded() const = 0 ; - bool printEvalCounter() const { return _printEvalCounter ; } void setPrintEvalCounter(bool value) { _printEvalCounter = value ; } @@ -65,9 +56,9 @@ class RooAbsIntegrator : public TObject { protected: - const RooAbsFunc *_function; ///< Pointer to function binding of integrand - bool _valid; ///< Is integrator in valid state? - bool _printEvalCounter ; ///< If true print number of function evaluation required for integration + const RooAbsFunc *_function = nullptr; ///< Pointer to function binding of integrand + bool _valid = false; ///< Is integrator in valid state? + bool _printEvalCounter = false; ///< If true print number of function evaluation required for integration ClassDefOverride(RooAbsIntegrator,0) // Abstract interface for real-valued function integrators }; diff --git a/roofit/roofitcore/inc/RooAbsMCStudyModule.h b/roofit/roofitcore/inc/RooAbsMCStudyModule.h index 061a963028903..f26ce8c5bd60d 100644 --- a/roofit/roofitcore/inc/RooAbsMCStudyModule.h +++ b/roofit/roofitcore/inc/RooAbsMCStudyModule.h @@ -34,7 +34,7 @@ class RooAbsMCStudyModule : public TNamed { RooAbsMCStudyModule(const RooAbsMCStudyModule& other) ; ~RooAbsMCStudyModule() override {} ; - /// Initializer method called upon attachement to given RooMCStudy object + /// Initializer method called upon attachment to given RooMCStudy object bool doInitializeInstance(RooMCStudy& /*study*/) ; /// Initializer called immediately after attachment to RooMCStudy object and initialization of module base class @@ -77,9 +77,7 @@ class RooAbsMCStudyModule : public TNamed { // which are only functional after module has been attached to a RooMCStudy object /// Refit model using original or specified data sample - RooFitResult* refit(RooAbsData* inGenSample=nullptr) { - if (_mcs) return _mcs->refit(inGenSample) ; else return nullptr ; - } + RooFit::OwningPtr refit(RooAbsData* inGenSample=nullptr); /// Return generate sample RooAbsData* genSample() { diff --git a/roofit/roofitcore/inc/RooAbsOptTestStatistic.h b/roofit/roofitcore/inc/RooAbsOptTestStatistic.h index b142a3d3b8657..b3f0b9ef9a826 100644 --- a/roofit/roofitcore/inc/RooAbsOptTestStatistic.h +++ b/roofit/roofitcore/inc/RooAbsOptTestStatistic.h @@ -29,7 +29,6 @@ class RooAbsOptTestStatistic : public RooAbsTestStatistic { public: // Constructors, assignment etc - RooAbsOptTestStatistic() ; RooAbsOptTestStatistic(const char *name, const char *title, RooAbsReal& real, RooAbsData& data, const RooArgSet& projDeps, RooAbsTestStatistic::Configuration const& cfg); @@ -74,21 +73,23 @@ class RooAbsOptTestStatistic : public RooAbsTestStatistic { virtual RooArgSet requiredExtraObservables() const { return RooArgSet() ; } void optimizeCaching() ; void optimizeConstantTerms(bool,bool=true) ; - - RooArgSet* _normSet ; ///< Pointer to set with observables used for normalization - RooArgSet* _funcCloneSet ; ///< Set owning all components of internal clone of input function - RooAbsData* _dataClone{nullptr}; ///< Pointer to internal clone if input data - RooAbsReal* _funcClone ; ///< Pointer to internal clone of input function - RooArgSet* _projDeps ; ///< Set of projected observable - bool _ownData ; ///< Do we own the dataset - bool _sealed ; ///< Is test statistic sealed -- i.e. no access to data + void runRecalculateCache(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const override; + + RooArgSet* _normSet = nullptr; ///< Pointer to set with observables used for normalization + RooArgSet* _funcCloneSet = nullptr; ///< Set owning all components of internal clone of input function + RooAbsData* _dataClone = nullptr; ///< Pointer to internal clone if input data + RooAbsReal* _funcClone = nullptr; ///< Pointer to internal clone of input function + RooArgSet* _projDeps = nullptr; ///< Set of projected observable + bool _ownData = false; ///< Do we own the dataset + bool _sealed = false; ///< Is test statistic sealed -- i.e. no access to data TString _sealNotice ; ///< User-defined notice shown when reading a sealed likelihood - RooArgSet* _funcObsSet ; ///< List of observables in the pdf expression + RooArgSet* _funcObsSet = nullptr; ///< List of observables in the pdf expression RooArgSet _cachedNodes ; /// +#include +#include +#include +#include +#include -class RooDataSet; -class RooDataHist ; class RooArgSet ; class RooAbsGenContext ; class RooFitResult ; @@ -36,9 +36,6 @@ class RooMinimizer ; class RooNumGenConfig ; class RooRealIntegral ; -namespace RooBatchCompute { -struct RunContext; -} class RooAbsPdf : public RooAbsReal { public: @@ -57,18 +54,18 @@ class RooAbsPdf : public RooAbsReal { /// \param[in] whatVars Set of observables to generate for each event according to this model. /// \param[in] nEvents How many events to generate /// \param arg1,arg2,arg3,arg4,arg5 Optional command arguments. - RooDataSet *generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg& arg1, - const RooCmdArg& arg2=RooCmdArg::none(), const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none()) { + RooFit::OwningPtr generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg& arg1, + const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={}) { return generate(whatVars,RooFit::NumEvents(nEvents),arg1,arg2,arg3,arg4,arg5) ; } - RooDataSet *generate(const RooArgSet &whatVars, - const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; - RooDataSet *generate(const RooArgSet &whatVars, double nEvents = 0, bool verbose=false, bool autoBinned=true, + RooFit::OwningPtr generate(const RooArgSet &whatVars, + const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; + RooFit::OwningPtr generate(const RooArgSet &whatVars, double nEvents = 0, bool verbose=false, bool autoBinned=true, const char* binnedTag="", bool expectedData=false, bool extended = false) const; - RooDataSet *generate(const RooArgSet &whatVars, const RooDataSet &prototype, Int_t nEvents= 0, + RooFit::OwningPtr generate(const RooArgSet &whatVars, const RooDataSet &prototype, Int_t nEvents= 0, bool verbose=false, bool randProtoOrder=false, bool resampleProto=false) const; @@ -97,38 +94,38 @@ class RooAbsPdf : public RooAbsReal { ///Prepare GenSpec configuration object for efficient generation of multiple datasets from identical specification. GenSpec* prepareMultiGen(const RooArgSet &whatVars, - const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; ///Generate according to GenSpec obtained from prepareMultiGen(). - RooDataSet* generate(GenSpec&) const ; + RooFit::OwningPtr generate(GenSpec&) const ; //////////////////////////////////////////////////////////////////////////////// - /// As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&) + /// As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&) const. /// \param[in] whatVars set /// \param[in] nEvents How many events to generate /// \param arg1,arg2,arg3,arg4,arg5 ordered arguments - virtual RooDataHist *generateBinned(const RooArgSet &whatVars, double nEvents, const RooCmdArg& arg1, - const RooCmdArg& arg2=RooCmdArg::none(), const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none()) const { + virtual RooFit::OwningPtr generateBinned(const RooArgSet &whatVars, double nEvents, const RooCmdArg& arg1, + const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={}) const { return generateBinned(whatVars,RooFit::NumEvents(nEvents),arg1,arg2,arg3,arg4,arg5); } - virtual RooDataHist *generateBinned(const RooArgSet &whatVars, - const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) const; - virtual RooDataHist *generateBinned(const RooArgSet &whatVars, double nEvents, bool expectedData=false, bool extended=false) const; + virtual RooFit::OwningPtr generateBinned(const RooArgSet &whatVars, + const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) const; + virtual RooFit::OwningPtr generateBinned(const RooArgSet &whatVars, double nEvents, bool expectedData=false, bool extended=false) const; - virtual RooDataSet* generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) ; + virtual RooFit::OwningPtr generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) ; ///Helper calling plotOn(RooPlot*, RooLinkedList&) const RooPlot* plotOn(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none(), - const RooCmdArg& arg9=RooCmdArg::none(), const RooCmdArg& arg10=RooCmdArg::none() + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}, + const RooCmdArg& arg9={}, const RooCmdArg& arg10={} ) const override { return RooAbsReal::plotOn(frame,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) ; } @@ -136,14 +133,10 @@ class RooAbsPdf : public RooAbsReal { /// Add a box with parameter values (and errors) to the specified frame virtual RooPlot* paramOn(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - - virtual RooPlot* paramOn(RooPlot* frame, const RooAbsData* data, const char *label= "", Int_t sigDigits = 2, - Option_t *options = "NELU", double xmin=0.65, - double xmax = 0.9, double ymax = 0.9) ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; // Built-in generator support virtual Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const; @@ -159,67 +152,18 @@ class RooAbsPdf : public RooAbsReal { void setGeneratorConfig() ; void setGeneratorConfig(const RooNumGenConfig& config) ; - // -log(L) fits to binned and unbinned data - virtual RooFitResult* fitTo(RooAbsData& data, const RooLinkedList& cmdList={}) ; - /// Takes an arbitrary number of RooCmdArg command options and calls - /// RooAbsPdf::fitTo(RooAbsData& data, const RooLinkedList& cmdList). - template - RooFitResult* fitTo(RooAbsData& data, RooCmdArg const& arg1, Args const&... args) + template + RooFit::OwningPtr fitTo(RooAbsData& data, CmdArgs_t const&... cmdArgs) { - return fitTo(data, *RooFit::Detail::createCmdList(&arg1, &args...)); + return RooFit::Detail::owningPtr(fitToImpl(data, *RooFit::Detail::createCmdList(&cmdArgs...))); } - /// Configuration struct for RooAbsPdf::minimizeNLL with all the default - //values that also should be taked as the default values for - //RooAbsPdf::fitTo. - struct MinimizerConfig { - double recoverFromNaN = 10.; - int optConst = 2; - int verbose = 0; - int doSave = 0; - int doTimer = 0; - int printLevel = 1; - int strat = 1; - int initHesse = 0; - int hesse = 1; - int minos = 0; - int numee = 10; - int doEEWall = 1; - int doWarn = 1; - int doSumW2 = -1; - int doAsymptotic = -1; - int maxCalls = -1; - int parallelize = 0; - bool enableParallelGradient = true; - bool enableParallelDescent = false; - bool timingAnalysis = false; - const RooArgSet* minosSet = nullptr; - std::string minType; - std::string minAlg = "minuit"; - }; - std::unique_ptr minimizeNLL(RooAbsReal & nll, RooAbsData const& data, MinimizerConfig const& cfg); - - virtual RooAbsReal* createNLL(RooAbsData& data, const RooLinkedList& cmdList={}) ; - /// Takes an arbitrary number of RooCmdArg command options and calls - /// RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList). - template - RooAbsReal* createNLL(RooAbsData& data, RooCmdArg const& arg1, Args const&... args) + template + RooFit::OwningPtr createNLL(RooAbsData& data, CmdArgs_t const&... cmdArgs) { - return createNLL(data, *RooFit::Detail::createCmdList(&arg1, &args...)); + return RooFit::Detail::owningPtr(createNLLImpl(data, *RooFit::Detail::createCmdList(&cmdArgs...))); } - // Chi^2 fits to histograms - using RooAbsReal::chi2FitTo ; - using RooAbsReal::createChi2 ; - RooFitResult* chi2FitTo(RooDataHist& data, const RooLinkedList& cmdList) override ; - RooAbsReal* createChi2(RooDataHist& data, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) override ; - - // Chi^2 fits to X-Y datasets - RooAbsReal* createChi2(RooDataSet& data, const RooLinkedList& cmdList) override ; - - // Constraint management virtual RooArgSet* getConstraints(const RooArgSet& /*observables*/, RooArgSet& /*constrainedParams*/, bool /*stripDisconnected*/, bool /*removeConstraintsFromPdf*/=false) const @@ -234,21 +178,18 @@ class RooAbsPdf : public RooAbsReal { virtual RooAbsPdf* createProjection(const RooArgSet& iset) ; // Create cumulative density function from p.d.f - RooAbsReal* createCdf(const RooArgSet& iset, const RooArgSet& nset=RooArgSet()) ; - RooAbsReal* createCdf(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooAbsReal* createScanCdf(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) ; + RooFit::OwningPtr createCdf(const RooArgSet& iset, const RooArgSet& nset=RooArgSet()) ; + RooFit::OwningPtr createCdf(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooFit::OwningPtr createScanCdf(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) ; // Function evaluation support double getValV(const RooArgSet* set=nullptr) const override ; virtual double getLogVal(const RooArgSet* set=nullptr) const ; - RooSpan getLogValBatch(std::size_t begin, std::size_t batchSize, - const RooArgSet* normSet = nullptr) const; - RooSpan getLogProbabilities(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet = nullptr) const; - void getLogProbabilities(RooSpan pdfValues, double * output) const; + void getLogProbabilities(std::span pdfValues, double * output) const; /// \copydoc getNorm(const RooArgSet*) const double getNorm(const RooArgSet& nset) const { @@ -287,11 +228,13 @@ class RooAbsPdf : public RooAbsReal { /// Return expected number of events to be used in calculation of extended /// likelihood. This function should not be overridden, as it just redirects /// to the actual virtual function but takes a RooArgSet reference instead of - /// pointer (\see expectedEvents(const RooArgSet*) const). + /// pointer. \see expectedEvents(const RooArgSet*) const double expectedEvents(const RooArgSet& nset) const { return expectedEvents(&nset) ; } + virtual std::unique_ptr createExpectedEventsFunc(const RooArgSet* nset) const; + // Printing interface (human readable) void printValue(std::ostream& os) const override ; void printMultiline(std::ostream& os, Int_t contents, bool verbose=false, TString indent="") const override ; @@ -299,9 +242,9 @@ class RooAbsPdf : public RooAbsReal { static void verboseEval(Int_t stat) ; static int verboseEval() ; - double extendedTerm(double sumEntries, double expected, double sumEntriesW2=0.0) const; - double extendedTerm(double sumEntries, RooArgSet const* nset, double sumEntriesW2=0.0) const; - double extendedTerm(RooAbsData const& data, bool weightSquared) const; + double extendedTerm(double sumEntries, double expected, double sumEntriesW2=0.0, bool doOffset=false) const; + double extendedTerm(double sumEntries, RooArgSet const* nset, double sumEntriesW2=0.0, bool doOffset=false) const; + double extendedTerm(RooAbsData const& data, bool weightSquared, bool doOffset=false) const; void setNormRange(const char* rangeName) ; const char* normRange() const { @@ -321,18 +264,20 @@ class RooAbsPdf : public RooAbsReal { virtual RooAbsGenContext* autoGenContext(const RooArgSet &vars, const RooDataSet* prototype=nullptr, const RooArgSet* auxProto=nullptr, bool verbose=false, bool autoBinned=true, const char* binnedTag="") const ; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + private: - RooDataSet *generate(RooAbsGenContext& context, const RooArgSet& whatVars, const RooDataSet* prototype, + std::unique_ptr generate(RooAbsGenContext& context, const RooArgSet& whatVars, const RooDataSet* prototype, double nEvents, bool verbose, bool randProtoOrder, bool resampleProto, bool skipInit=false, bool extended=false) const ; // Implementation version virtual RooPlot* paramOn(RooPlot* frame, const RooArgSet& params, bool showConstants=false, - const char *label= "", Int_t sigDigits = 2, Option_t *options = "NELU", double xmin=0.65, - double xmax= 0.99,double ymax=0.95, const RooCmdArg* formatCmd=nullptr) ; + const char *label= "", double xmin=0.65, + double xmax= 0.99,double ymax=0.95, const RooCmdArg* formatCmd=nullptr) ; - void logBatchComputationErrors(RooSpan& outputs, std::size_t begin) const; + void logBatchComputationErrors(std::span& outputs, std::size_t begin) const; bool traceEvalPdf(double value) const; /// Setter for the _normSet member, which should never be set directly. @@ -345,6 +290,9 @@ class RooAbsPdf : public RooAbsReal { protected: + virtual std::unique_ptr createNLLImpl(RooAbsData& data, const RooLinkedList& cmdList); + virtual std::unique_ptr fitToImpl(RooAbsData& data, const RooLinkedList& cmdList); + /// Checks if `normSet` is the currently active normalization set of this /// PDF, meaning is exactly the same object as the one the `_normSet` member /// points to (or both are `nullptr`). @@ -386,7 +334,7 @@ class RooAbsPdf : public RooAbsReal { mutable Int_t _errorCount ; ///< Number of errors remaining to print mutable Int_t _traceCount ; ///< Number of traces remaining to print - mutable Int_t _negCount ; ///< Number of negative probablities remaining to print + mutable Int_t _negCount ; ///< Number of negative probabilities remaining to print bool _selectComp ; ///< Component selection flag for RooAbsPdf::plotCompOn @@ -398,8 +346,9 @@ class RooAbsPdf : public RooAbsReal { private: mutable RooFit::UniqueId::Value_t _normSetId = RooFit::UniqueId::nullval; /// +#include +#include + +class RooAbsArg; class RooAbsCollection; class RooArgSet; @@ -57,6 +61,7 @@ class RooAbsProxy { friend class RooAbsArg ; virtual bool changePointer(const RooAbsCollection& newServerSet, bool nameChange=false, bool factoryInitMode=false) = 0 ; + virtual bool changePointer(std::unordered_map const& replacements) = 0 ; friend class RooAbsPdf ; virtual void changeNormSet(const RooArgSet* newNormSet) ; diff --git a/roofit/roofitcore/inc/RooAbsReal.h b/roofit/roofitcore/inc/RooAbsReal.h index f48c086637df9..954c730819516 100644 --- a/roofit/roofitcore/inc/RooAbsReal.h +++ b/roofit/roofitcore/inc/RooAbsReal.h @@ -22,9 +22,10 @@ #include "RooArgSet.h" #include "RooArgList.h" #include "RooGlobalFunc.h" -#include "RooSpan.h" -#include "RooBatchComputeTypes.h" #include "RooFit/Detail/DataMap.h" +#include "RooFit/Detail/CodeSquashContext.h" + +#include class RooDataSet ; class RooPlot; @@ -35,17 +36,13 @@ class RooLinkedList ; class RooNumIntConfig ; class RooDataHist ; class RooFunctor ; -class RooGenFunction ; -class RooMultiGenFunction ; class RooFitResult ; class RooAbsMoment ; class RooDerivative ; class RooVectorDataStore ; struct TreeReadBuffer; /// A space to attach TBranches -namespace ROOT { -namespace Experimental { -class RooFitDriver ; -} +namespace RooBatchCompute { +struct RunContext; } class TH1; @@ -63,6 +60,21 @@ class RooAbsReal : public RooAbsArg { public: using value_type = double; + /// A RooAbsReal::Ref can be constructed from a `RooAbsReal&` or a `double` + /// that will be implicitly converted to a RooConstVar&. The RooAbsReal::Ref + /// can be used as a replacement for `RooAbsReal&`. With this type + /// definition, you can write RooFit interfaces that accept both RooAbsReal, + /// or simply a number that will be implicitly converted to a RooConstVar&. + class Ref { + public: + inline Ref(RooAbsReal &ref) : _ref{ref} {} + Ref(double val); + inline operator RooAbsReal &() const { return _ref; } + + private: + RooAbsReal &_ref; + }; + // Constructors, assignment etc RooAbsReal() ; RooAbsReal(const char *name, const char *title, const char *unit= "") ; @@ -121,23 +133,7 @@ class RooAbsReal : public RooAbsArg { virtual double getValV(const RooArgSet* normalisationSet = nullptr) const ; - /// \deprecated getValBatch() has been removed in favour of the faster getValues(). If your code is affected - /// by this change, please consult the release notes for ROOT 6.24 for guidance on how to make this transition. - /// https://root.cern/doc/v624/release-notes.html -#ifndef R__MACOSX - virtual RooSpan getValBatch(std::size_t /*begin*/, std::size_t /*maxSize*/, const RooArgSet* /*normSet*/ = nullptr) = delete; -#else - //AppleClang in MacOS10.14 has a linker bug and fails to link programs that create objects of classes containing virtual deleted methods. - //This can be safely deleted when MacOS10.14 is no longer supported by ROOT. See https://reviews.llvm.org/D37830 - virtual RooSpan getValBatch(std::size_t /*begin*/, std::size_t /*maxSize*/, const RooArgSet* /*normSet*/ = nullptr) final { - throw std::logic_error("Deprecated getValBatch() has been removed in favour of the faster getValues(). If your code is affected by this change, please consult the release notes for ROOT 6.24 for guidance on how to make this transition. https://root.cern/doc/v624/release-notes.html"); - } -#endif - /// \copydoc getValBatch(std::size_t, std::size_t, const RooArgSet*) - virtual RooSpan getValues(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet = nullptr) const; - std::vector getValues(RooAbsData const& data, RooFit::BatchModeOption batchMode=RooFit::BatchModeOption::Cpu) const; - - double getPropagatedError(const RooFitResult &fr, const RooArgSet &nset = RooArgSet()) const; + double getPropagatedError(const RooFitResult &fr, const RooArgSet &nset = {}) const; bool operator==(double value) const ; bool operator==(const RooAbsArg& other) const override; @@ -155,10 +151,10 @@ class RooAbsReal : public RooAbsArg { TString getTitle(bool appendUnit= false) const; // Lightweight interface adaptors (caller takes ownership) - RooAbsFunc *bindVars(const RooArgSet &vars, const RooArgSet* nset=nullptr, bool clipInvalid=false) const; + RooFit::OwningPtr bindVars(const RooArgSet &vars, const RooArgSet* nset=nullptr, bool clipInvalid=false) const; // Create a fundamental-type object that can hold our value. - RooAbsArg *createFundamental(const char* newname=nullptr) const override; + RooFit::OwningPtr createFundamental(const char* newname=nullptr) const override; // Analytical integration support virtual Int_t getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName=nullptr) const ; @@ -178,66 +174,65 @@ class RooAbsReal : public RooAbsArg { bool getForceNumInt() const { return _forceNumInt ; } // Chi^2 fits to histograms - virtual RooFitResult* chi2FitTo(RooDataHist& data, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - virtual RooFitResult* chi2FitTo(RooDataHist& data, const RooLinkedList& cmdList) ; + virtual RooFit::OwningPtr chi2FitTo(RooDataHist& data, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + virtual RooFit::OwningPtr chi2FitTo(RooDataHist& data, const RooLinkedList& cmdList) ; - virtual RooAbsReal* createChi2(RooDataHist& data, const RooLinkedList& cmdList) ; - virtual RooAbsReal* createChi2(RooDataHist& data, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; + virtual RooFit::OwningPtr createChi2(RooDataHist& data, const RooLinkedList& cmdList) ; + virtual RooFit::OwningPtr createChi2(RooDataHist& data, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; // Chi^2 fits to X-Y datasets - virtual RooFitResult* chi2FitTo(RooDataSet& xydata, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - virtual RooFitResult* chi2FitTo(RooDataSet& xydata, const RooLinkedList& cmdList) ; - - virtual RooAbsReal* createChi2(RooDataSet& data, const RooLinkedList& cmdList) ; - virtual RooAbsReal* createChi2(RooDataSet& data, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; + virtual RooFit::OwningPtr chi2FitTo(RooDataSet& xydata, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + virtual RooFit::OwningPtr chi2FitTo(RooDataSet& xydata, const RooLinkedList& cmdList) ; + virtual RooFit::OwningPtr createChi2(RooDataSet& data, const RooLinkedList& cmdList) ; + virtual RooFit::OwningPtr createChi2(RooDataSet& data, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; - virtual RooAbsReal* createProfile(const RooArgSet& paramsOfInterest) ; + virtual RooFit::OwningPtr createProfile(const RooArgSet& paramsOfInterest) ; - RooAbsReal* createIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; /// Create integral over observables in iset in range named rangeName. - RooAbsReal* createIntegral(const RooArgSet& iset, const char* rangeName) const { + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const char* rangeName) const { return createIntegral(iset,nullptr,nullptr,rangeName) ; } /// Create integral over observables in iset in range named rangeName with integrand normalized over observables in nset - RooAbsReal* createIntegral(const RooArgSet& iset, const RooArgSet& nset, const char* rangeName=nullptr) const { + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooArgSet& nset, const char* rangeName=nullptr) const { return createIntegral(iset,&nset,nullptr,rangeName) ; } /// Create integral over observables in iset in range named rangeName with integrand normalized over observables in nset while /// using specified configuration for any numeric integration. - RooAbsReal* createIntegral(const RooArgSet& iset, const RooArgSet& nset, const RooNumIntConfig& cfg, const char* rangeName=nullptr) const { + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooArgSet& nset, const RooNumIntConfig& cfg, const char* rangeName=nullptr) const { return createIntegral(iset,&nset,&cfg,rangeName) ; } /// Create integral over observables in iset in range named rangeName using specified configuration for any numeric integration. - RooAbsReal* createIntegral(const RooArgSet& iset, const RooNumIntConfig& cfg, const char* rangeName=nullptr) const { + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooNumIntConfig& cfg, const char* rangeName=nullptr) const { return createIntegral(iset,nullptr,&cfg,rangeName) ; } - virtual RooAbsReal* createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const ; + virtual RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const ; void setParameterizeIntegral(const RooArgSet& paramVars) ; // Create running integrals - RooAbsReal* createRunningIntegral(const RooArgSet& iset, const RooArgSet& nset=RooArgSet()) ; - RooAbsReal* createRunningIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooAbsReal* createIntRI(const RooArgSet& iset, const RooArgSet& nset=RooArgSet()) ; - RooAbsReal* createScanRI(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) ; + RooFit::OwningPtr createRunningIntegral(const RooArgSet& iset, const RooArgSet& nset={}) ; + RooFit::OwningPtr createRunningIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooFit::OwningPtr createIntRI(const RooArgSet& iset, const RooArgSet& nset={}) ; + RooFit::OwningPtr createScanRI(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) ; // Optimized accept/reject generator support @@ -270,11 +265,11 @@ class RooAbsReal : public RooAbsArg { // User entry point for plotting virtual RooPlot* plotOn(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg(), const RooCmdArg& arg2=RooCmdArg(), - const RooCmdArg& arg3=RooCmdArg(), const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(), const RooCmdArg& arg8=RooCmdArg(), - const RooCmdArg& arg9=RooCmdArg(), const RooCmdArg& arg10=RooCmdArg() + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}, + const RooCmdArg& arg9={}, const RooCmdArg& arg10={} ) const ; @@ -290,13 +285,13 @@ class RooAbsReal : public RooAbsArg { const RooArgSet* condObs=nullptr, bool setError=true) const; // Create 1,2, and 3D histograms from and fill it - TH1 *createHistogram(const char* varNameList, Int_t xbins=0, Int_t ybins=0, Int_t zbins=0) const ; + TH1 *createHistogram(RooStringView varNameList, Int_t xbins=0, Int_t ybins=0, Int_t zbins=0) const ; TH1* createHistogram(const char *name, const RooAbsRealLValue& xvar, RooLinkedList& argList) const ; TH1 *createHistogram(const char *name, const RooAbsRealLValue& xvar, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; // Fill a RooDataHist RooDataHist* fillDataHist(RooDataHist *hist, const RooArgSet* nset, double scaleFactor, @@ -324,6 +319,22 @@ class RooAbsReal : public RooAbsArg { } ; enum ErrorLoggingMode { PrintErrors, CollectErrors, CountErrors, Ignore } ; + + /// Context to temporarily change the error logging mode as long as the context is alive. + class EvalErrorContext { + public: + EvalErrorContext(ErrorLoggingMode m) : _old{evalErrorLoggingMode()} { setEvalErrorLoggingMode(m); } + + EvalErrorContext(EvalErrorContext const&) = delete; + EvalErrorContext(EvalErrorContext &&) = delete; + EvalErrorContext& operator=(EvalErrorContext const&) = delete; + EvalErrorContext& operator=(EvalErrorContext &&) = delete; + + ~EvalErrorContext() { setEvalErrorLoggingMode(_old); } + private: + ErrorLoggingMode _old; + }; + static ErrorLoggingMode evalErrorLoggingMode() ; static void setEvalErrorLoggingMode(ErrorLoggingMode m) ; void logEvalError(const char* message, const char* serverValueString=nullptr) const ; @@ -343,9 +354,6 @@ class RooAbsReal : public RooAbsArg { virtual std::list* binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const; virtual std::list* plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const; - RooGenFunction* iGenFunction(RooRealVar& x, const RooArgSet& nset=RooArgSet()) ; - RooMultiGenFunction* iGenFunction(const RooArgSet& observables, const RooArgSet& nset=RooArgSet()) ; - RooFunctor* functor(const RooArgList& obs, const RooArgList& pars=RooArgList(), const RooArgSet& nset=RooArgSet()) const ; TF1* asTF(const RooArgList& obs, const RooArgList& pars=RooArgList(), const RooArgSet& nset=RooArgSet()) const ; @@ -372,7 +380,40 @@ class RooAbsReal : public RooAbsArg { static void setHideOffset(bool flag); static bool hideOffset() ; + bool isSelectedComp() const ; + void selectComp(bool flag) { + // If flag is true, only selected component will be included in evaluates of RooAddPdf components + _selectComp = flag ; + } + + const RooAbsReal* createPlotProjection(const RooArgSet& depVars, const RooArgSet& projVars, RooArgSet*& cloneSet) const ; + const RooAbsReal *createPlotProjection(const RooArgSet &dependentVars, const RooArgSet *projectedVars, + RooArgSet *&cloneSet, const char* rangeName=nullptr, const RooArgSet* condObs=nullptr) const; + virtual void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const; + + virtual bool hasGradient() const { return false; } + virtual void gradient(double *) const { + if(!hasGradient()) throw std::runtime_error("RooAbsReal::gradient(double *) not implemented by this class!"); + } + + virtual std::string + buildCallToAnalyticIntegral(Int_t code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const; + + // PlotOn with command list + virtual RooPlot* plotOn(RooPlot* frame, RooLinkedList& cmdList) const ; + protected: + friend class BatchInterfaceAccessor; + friend class RooVectorDataStore; + friend class RooRealBinding; + friend class RooRealSumPdf; + friend class RooRealSumFunc; + friend class RooAddHelpers; + friend class RooAddPdf; + friend class RooAddModel; + friend class AddCacheElem; + friend class RooFit::Detail::DataMap; + // Hook for objects with normalization-dependent parameters interpretation virtual void selectNormalization(const RooArgSet* depSet=nullptr, bool force=false) ; virtual void selectNormalizationRange(const char* rangeName=nullptr, bool force=false) ; @@ -384,20 +425,6 @@ class RooAbsReal : public RooAbsArg { TString integralNameSuffix(const RooArgSet& iset, const RooArgSet* nset=nullptr, const char* rangeName=nullptr, bool omitEmpty=false) const ; - - bool isSelectedComp() const ; - - - public: - const RooAbsReal* createPlotProjection(const RooArgSet& depVars, const RooArgSet& projVars, RooArgSet*& cloneSet) const ; - const RooAbsReal *createPlotProjection(const RooArgSet &dependentVars, const RooArgSet *projectedVars, - RooArgSet *&cloneSet, const char* rangeName=nullptr, const RooArgSet* condObs=nullptr) const; - virtual void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const; - - protected: - - RooFitResult* chi2FitDriver(RooAbsReal& fcn, RooLinkedList& cmdList) ; - void plotOnCompSelect(RooArgSet* selNodes) const ; RooPlot* plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, double Z, const RooArgSet* params, const RooLinkedList& argList, bool method1) const ; @@ -417,55 +444,22 @@ class RooAbsReal : public RooAbsArg { bool matchArgs(const RooArgSet& allDeps, RooArgSet& numDeps, const RooArgSet& set) const ; - - RooAbsReal* createIntObj(const RooArgSet& iset, const RooArgSet* nset, const RooNumIntConfig* cfg, const char* rangeName) const ; + RooFit::OwningPtr createIntObj(const RooArgSet& iset, const RooArgSet* nset, const RooNumIntConfig* cfg, const char* rangeName) const ; void findInnerMostIntegration(const RooArgSet& allObs, RooArgSet& innerObs, const char* rangeName) const ; - // Internal consistency checking (needed by RooDataSet) /// Check if current value is valid. bool isValid() const override { return isValidReal(_value); } /// Interface function to check if given value is a valid value for this object. Returns true unless overridden. virtual bool isValidReal(double /*value*/, bool printError = false) const { (void)printError; return true; } - // Function evaluation and error tracing double traceEval(const RooArgSet* set) const ; /// Evaluate this PDF / function / constant. Needs to be overridden by all derived classes. virtual double evaluate() const = 0; - /// \deprecated evaluateBatch() has been removed in favour of the faster evaluateSpan(). If your code is affected - /// by this change, please consult the release notes for ROOT 6.24 for guidance on how to make this transition. - /// https://root.cern/doc/v624/release-notes.html -#ifndef R__MACOSX - virtual RooSpan evaluateBatch(std::size_t /*begin*/, std::size_t /*maxSize*/) = delete; -#else - //AppleClang in MacOS10.14 has a linker bug and fails to link programs that create objects of classes containing virtual deleted methods. - //This can be safely deleted when MacOS10.14 is no longer supported by ROOT. See https://reviews.llvm.org/D37830 - virtual RooSpan evaluateBatch(std::size_t /*begin*/, std::size_t /*maxSize*/) final { - throw std::logic_error("Deprecated evaluatedBatch() has been removed in favour of the faster evaluateSpan(). If your code is affected by this change, please consult the release notes for ROOT 6.24 for guidance on how to make this transition. https://root.cern/doc/v624/release-notes.html"); - } -#endif - - virtual RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const; - - - //---------- Interface to access batch data --------------------------- - // - friend class BatchInterfaceAccessor; - - private: - void checkBatchComputation(const RooBatchCompute::RunContext& evalData, std::size_t evtNo, const RooArgSet* normSet = nullptr, double relAccuracy = 1.E-13) const; - - /// Debug version of getVal(), which is slow and does error checking. - double _DEBUG_getVal(const RooArgSet* normalisationSet) const; - - //-------------------------------------------------------------------- - - protected: // Hooks for RooDataSet interface - friend class RooVectorDataStore ; void syncCache(const RooArgSet* set=nullptr) override { getVal(set) ; } void copyCache(const RooAbsArg* source, bool valueOnly=false, bool setValDirty=true) override ; void attachToTree(TTree& t, Int_t bufSize=32000) override ; @@ -473,90 +467,49 @@ class RooAbsReal : public RooAbsArg { void setTreeBranchStatus(TTree& t, bool active) override ; void fillTreeBranch(TTree& t) override ; - friend class RooRealBinding ; - double _plotMin ; ///< Minimum of plot range - double _plotMax ; ///< Maximum of plot range - Int_t _plotBins ; ///< Number of plot bins - mutable double _value ; ///< Cache for current value of object - TString _unit ; ///< Unit for objects value - TString _label ; ///< Plot label for objects value - bool _forceNumInt ; ///< Force numerical integration if flag set - - RooNumIntConfig* _specIntegratorConfig ; // Numeric integrator configuration specific for this object - struct PlotOpt { - PlotOpt() : drawOptions("L"), scaleFactor(1.0), stype(Relative), projData(nullptr), binProjData(false), projSet(nullptr), precision(1e-3), - shiftToZero(false),projDataSet(nullptr),normRangeName(nullptr),rangeLo(0),rangeHi(0),postRangeFracScale(false),wmode(RooCurve::Extended), - projectionRangeName(nullptr),curveInvisible(false), curveName(nullptr),addToCurveName(nullptr),addToWgtSelf(1.),addToWgtOther(1.), - numCPU(1),interleave(RooFit::Interleave),curveNameSuffix(""), numee(10), eeval(0), doeeval(false), progress(false), errorFR(nullptr) {} - Option_t* drawOptions ; - double scaleFactor ; - ScaleType stype ; - const RooAbsData* projData ; - bool binProjData ; - const RooArgSet* projSet ; - double precision ; - bool shiftToZero ; - const RooArgSet* projDataSet ; - const char* normRangeName ; - double rangeLo ; - double rangeHi ; - bool postRangeFracScale ; - RooCurve::WingMode wmode ; - const char* projectionRangeName ; - bool curveInvisible ; - const char* curveName ; - const char* addToCurveName ; - double addToWgtSelf ; - double addToWgtOther ; - Int_t numCPU ; - RooFit::MPSplit interleave ; - const char* curveNameSuffix ; - Int_t numee ; - double eeval ; - bool doeeval ; - bool progress ; - const RooFitResult* errorFR ; - } ; + Option_t *drawOptions = "L"; + double scaleFactor = 1.0; + ScaleType stype = Relative; + const RooAbsData *projData = nullptr; + bool binProjData = false; + const RooArgSet *projSet = nullptr; + double precision = 1e-3; + bool shiftToZero = false; + const RooArgSet *projDataSet = nullptr; + const char *normRangeName = nullptr; + double rangeLo = 0.0; + double rangeHi = 0.0; + bool postRangeFracScale = false; + RooCurve::WingMode wmode = RooCurve::Extended; + const char *projectionRangeName = nullptr; + bool curveInvisible = false; + const char *curveName = nullptr; + const char *addToCurveName = nullptr; + double addToWgtSelf = 1.0; + double addToWgtOther = 1.0; + Int_t numCPU = 1; + RooFit::MPSplit interleave = RooFit::Interleave; + const char *curveNameSuffix = ""; + Int_t numee = 10; + double eeval = 0.0; + bool doeeval = false; + bool progress = false; + const RooFitResult *errorFR = nullptr; + }; // Plot implementation functions virtual RooPlot *plotOn(RooPlot* frame, PlotOpt o) const; -public: - // PlotOn with command list - virtual RooPlot* plotOn(RooPlot* frame, RooLinkedList& cmdList) const ; - - protected: virtual RooPlot *plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asymCat, PlotOpt o) const; - -private: - - static ErrorLoggingMode _evalErrorMode ; - static std::map > > _evalErrorList ; - static Int_t _evalErrorCount ; - bool matchArgsByName(const RooArgSet &allArgs, RooArgSet &matchedArgs, const TList &nameList) const; - std::unique_ptr _treeReadBuffer; //! A buffer for reading values from trees - -protected: - bool redirectServersHook(const RooAbsCollection & newServerList, bool mustReplaceAll, bool nameChange, bool isRecursiveStep) override; - friend class RooRealSumPdf ; - friend class RooRealSumFunc; - friend class RooAddHelpers ; - friend class RooAddPdf ; - friend class RooAddModel ; - void selectComp(bool flag) { - // If flag is true, only selected component will be included in evaluates of RooAddPdf components - _selectComp = flag ; - } static void globalSelectComp(bool flag) ; - bool _selectComp ; //! Component selection flag for RooAbsPdf::plotCompOn - static bool _globalSelectComp ; // Global activation switch for component selection + // This struct can be used to flip the global switch to select components. // Doing this with RAII prevents forgetting to reset the state. struct GlobalSelectComponentRAII { @@ -575,20 +528,34 @@ class RooAbsReal : public RooAbsArg { }; - mutable RooArgSet* _lastNSet ; /// _specIntegratorConfig; // Numeric integrator configuration specific for this object + std::unique_ptr _treeReadBuffer; //! A buffer for reading values from trees + bool _selectComp = true; //! Component selection flag for RooAbsPdf::plotCompOn + mutable RooFit::UniqueId::Value_t _lastNormSetId = RooFit::UniqueId::nullval; ///>> _evalErrorList; + static Int_t _evalErrorCount; + static bool _globalSelectComp; // Global activation switch for component selection + static bool _hideOffset; ///< Offset hiding flag + + ClassDefOverride(RooAbsReal,3); // Abstract real-valued variable }; diff --git a/roofit/roofitcore/inc/RooAbsRealLValue.h b/roofit/roofitcore/inc/RooAbsRealLValue.h index 05e14a3c02fd0..b08d17b15c668 100644 --- a/roofit/roofitcore/inc/RooAbsRealLValue.h +++ b/roofit/roofitcore/inc/RooAbsRealLValue.h @@ -67,9 +67,9 @@ class RooAbsRealLValue : public RooAbsReal, public RooAbsLValue { // Get fit range limits - /// Retrive binning configuration with given name or default binning. + /// Retrieve binning configuration with given name or default binning. virtual const RooAbsBinning& getBinning(const char* name=nullptr, bool verbose=true, bool createOnTheFly=false) const = 0 ; - /// Retrive binning configuration with given name or default binning. + /// Retrieve binning configuration with given name or default binning. virtual RooAbsBinning& getBinning(const char* name=nullptr, bool verbose=true, bool createOnTheFly=false) = 0 ; /// Check if binning with given name has been defined. virtual bool hasBinning(const char* name) const = 0 ; @@ -120,9 +120,9 @@ class RooAbsRealLValue : public RooAbsReal, public RooAbsLValue { // Build 1-dimensional plots - RooPlot* frame(const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + RooPlot* frame(const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; RooPlot *frame(const RooLinkedList& cmdList) const ; RooPlot *frame(double lo, double hi, Int_t nbins) const; RooPlot *frame(double lo, double hi) const; @@ -131,10 +131,10 @@ class RooAbsRealLValue : public RooAbsReal, public RooAbsLValue { // Create empty 1,2, and 3D histograms from a list of 1-3 RooAbsReals TH1 *createHistogram(const char *name, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; TH1 *createHistogram(const char *name, const RooLinkedList& cmdList) const ; TH1F *createHistogram(const char *name, const char *yAxisLabel) const ; @@ -153,7 +153,7 @@ class RooAbsRealLValue : public RooAbsReal, public RooAbsLValue { static TH1* createHistogram(const char *name, RooArgList &vars, const char *tAxisLabel, double* xlo, double* xhi, Int_t* nBins) ; static TH1* createHistogram(const char *name, RooArgList &vars, const char *tAxisLabel, const RooAbsBinning** bins) ; - RooAbsReal* createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const override; + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const override; protected: diff --git a/roofit/roofitcore/inc/RooAbsRootFinder.h b/roofit/roofitcore/inc/RooAbsRootFinder.h deleted file mode 100644 index aef5db38b3f6a..0000000000000 --- a/roofit/roofitcore/inc/RooAbsRootFinder.h +++ /dev/null @@ -1,37 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooAbsRootFinder.h,v 1.6 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_ABS_ROOT_FINDER -#define ROO_ABS_ROOT_FINDER - -#include "Rtypes.h" - -class RooAbsFunc; - -class RooAbsRootFinder { -public: - RooAbsRootFinder(const RooAbsFunc& function); - inline virtual ~RooAbsRootFinder() { } - - virtual bool findRoot(double &result, double xlo, double xhi, double value= 0) const = 0; - -protected: - const RooAbsFunc *_function; ///< Pointer to input function - bool _valid; ///< True if current state is valid - - ClassDef(RooAbsRootFinder,0) // Abstract interface for 1-dim real-valued function root finders -}; - -#endif diff --git a/roofit/roofitcore/inc/RooAbsSelfCachedPdf.h b/roofit/roofitcore/inc/RooAbsSelfCachedPdf.h index 1be337029c27b..1d7dce1919343 100644 --- a/roofit/roofitcore/inc/RooAbsSelfCachedPdf.h +++ b/roofit/roofitcore/inc/RooAbsSelfCachedPdf.h @@ -1,44 +1 @@ -/***************************************************************************** - * Project: RooFit * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -#ifndef ROOABSSELFCACHEDPDF -#define ROOABSSELFCACHEDPDF - -#include "RooAbsCachedPdf.h" -#include "RooRealProxy.h" -#include "RooAbsReal.h" -#include "RooHistPdf.h" - - -class RooAbsSelfCachedPdf : public RooAbsCachedPdf { -public: - - RooAbsSelfCachedPdf() {} ; - RooAbsSelfCachedPdf(const char *name, const char *title, Int_t ipOrder=0); - RooAbsSelfCachedPdf(const RooAbsSelfCachedPdf& other, const char* name=nullptr) ; - ~RooAbsSelfCachedPdf() override ; - -protected: - - const char* inputBaseName() const override { - // Use own name as base name for caches - return GetName() ; - } - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; - void fillCacheObject(PdfCacheElem& cache) const override ; - -private: - - ClassDefOverride(RooAbsSelfCachedPdf,0) // Abstract base class for self-caching p.d.f.s -}; - -#endif +#include diff --git a/roofit/roofitcore/inc/RooAbsSelfCachedReal.h b/roofit/roofitcore/inc/RooAbsSelfCachedReal.h index 1ac03b26f3797..f7d21b6b36d6c 100644 --- a/roofit/roofitcore/inc/RooAbsSelfCachedReal.h +++ b/roofit/roofitcore/inc/RooAbsSelfCachedReal.h @@ -1,44 +1,149 @@ -/***************************************************************************** - * Project: RooFit * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -#ifndef ROOABSSELFCACHEDREAL -#define ROOABSSELFCACHEDREAL - -#include "RooAbsCachedReal.h" -#include "RooRealProxy.h" -#include "RooAbsReal.h" -#include "RooHistPdf.h" - - -class RooAbsSelfCachedReal : public RooAbsCachedReal { +/* + * Project: RooFit + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_RooAbsSelfCachedReal_h +#define RooFit_RooAbsSelfCachedReal_h + +/** +\file RooAbsSelfCached.h +\class RooAbsSelfCached +\ingroup Roofitcore + +RooAbsSelfCached is an abstract base class for functions whose +output is cached in terms of a histogram in all observables between +getVal() and evaluate(). For certain p.d.f.s that are very +expensive to calculate it may be beneficial to implement them as a +RooAbsSelfCached rather than a RooAbsReal/Pdf. Class +RooAbsSelfCached is designed to have its interface identical to +that of RooAbsReal/Pdf, so any p.d.f can make use of its caching +functionality by merely switching its base class. Existing +RooAbsReal/Pdf objects can also be cached a posteriori with the +RooCachedReal/Pdf wrapper function that takes any RooAbsReal/Pdf object as +input. +**/ + +#include +#include +#include +#include +#include +#include + +#include + +template +class RooAbsSelfCached : public Base_t { public: + RooAbsSelfCached() {} + /// Constructor + RooAbsSelfCached(const char *name, const char *title, int ipOrder = 0) : Base_t(name, title, ipOrder) {} - RooAbsSelfCachedReal() {} ; - RooAbsSelfCachedReal(const char *name, const char *title, Int_t ipOrder=0); - RooAbsSelfCachedReal(const RooAbsSelfCachedReal& other, const char* name=nullptr) ; - ~RooAbsSelfCachedReal() override ; + /// Copy constructor + RooAbsSelfCached(const RooAbsSelfCached &other, const char *name = nullptr) : Base_t(other, name) {} protected: - - const char* inputBaseName() const override { - // Use own name as base name for caches - return GetName() ; - } - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; - void fillCacheObject(FuncCacheElem& cache) const override ; + const char *inputBaseName() const override + { + // Use own name as base name for caches + return Base_t::GetName(); + } + RooFit::OwningPtr actualObservables(const RooArgSet &nset) const override; + RooFit::OwningPtr actualParameters(const RooArgSet &nset) const override; + void fillCacheObject(typename Base_t::CacheElem &cache) const override; private: - - ClassDefOverride(RooAbsSelfCachedReal,0) // Abstract base class for self-caching functions + ClassDefOverride(RooAbsSelfCached, 0); // Abstract base class for self-caching functions }; +using RooAbsSelfCachedReal = RooAbsSelfCached; +using RooAbsSelfCachedPdf = RooAbsSelfCached; + +//////////////////////////////////////////////////////////////////////////////// +/// Fill cache with sampling of function as defined by the evaluate() implementation + +template +void RooAbsSelfCached::fillCacheObject(typename Base_t::CacheElem &cache) const +{ + RooDataHist &cacheHist = *cache.hist(); + + // Make deep clone of self in non-caching mde and attach to dataset observables + RooArgSet cloneSet; + RooArgSet(*this).snapshot(cloneSet, true); + RooAbsSelfCached *clone2 = (RooAbsSelfCached *)cloneSet.find(Base_t::GetName()); + clone2->disableCache(true); + clone2->attachDataSet(cacheHist); + + // Iterator over all bins of RooDataHist and fill weights + for (int i = 0; i < cacheHist.numEntries(); i++) { + const RooArgSet *obs = cacheHist.get(i); + double wgt = clone2->getVal(obs); + cacheHist.set(i, wgt, 0.); + } + + cache.setUnitNorm(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Defines observables to be cached, given a set of user defined observables +/// Returns the subset of nset that are observables this p.d.f + +template +RooFit::OwningPtr RooAbsSelfCached::actualObservables(const RooArgSet &nset) const +{ + // Make list of servers + RooArgSet serverSet; + + for (auto server : Base_t::servers()) { + serverSet.add(*server); + } + + // Return servers that are in common with given normalization set + return RooFit::OwningPtr{static_cast(serverSet.selectCommon(nset))}; +} + +template <> +inline RooFit::OwningPtr RooAbsSelfCached::actualObservables(const RooArgSet & /*nset*/) const +{ + // Make list of servers + auto serverSet = new RooArgSet; + + for (auto server : servers()) { + serverSet->add(*server); + } + + // Return servers that are in common with given normalization set. + // For unknown reasons, the original implementation in RooAbsSelfCachedPdf + // skipped the "selectCommon" strep, which is why this is the only method + // that is implemented separately for RooAbsSelfCachedPdf. + return RooFit::OwningPtr{serverSet}; +} + +//////////////////////////////////////////////////////////////////////////////// +/// Defines parameters on which cache contents depends. Returns +/// subset of variables of self that is not contained in the +/// supplied nset + +template +RooFit::OwningPtr RooAbsSelfCached::actualParameters(const RooArgSet &nset) const +{ + // Make list of servers + RooArgSet *serverSet = new RooArgSet; + + for (auto server : Base_t::servers()) { + serverSet->add(*server); + } + + // Remove all given observables from server list + serverSet->remove(nset, true, true); + + return RooFit::OwningPtr{serverSet}; +} + #endif diff --git a/roofit/roofitcore/inc/RooAbsString.h b/roofit/roofitcore/inc/RooAbsString.h deleted file mode 100644 index 96f1127f1967f..0000000000000 --- a/roofit/roofitcore/inc/RooAbsString.h +++ /dev/null @@ -1,22 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooAbsString.h,v 1.26 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_ABS_STRING -#define ROO_ABS_STRING - -#include "RooStringVar.h" -using RooAbsString = RooStringVar; - -#endif diff --git a/roofit/roofitcore/inc/RooAbsStudy.h b/roofit/roofitcore/inc/RooAbsStudy.h index 690951974173d..572cd2f717188 100644 --- a/roofit/roofitcore/inc/RooAbsStudy.h +++ b/roofit/roofitcore/inc/RooAbsStudy.h @@ -59,7 +59,7 @@ class RooAbsStudy : public TNamed { friend class RooStudyPackage ; void registerSummaryOutput(const RooArgSet& allVars, const RooArgSet& varsWithError=RooArgSet(), const RooArgSet& varsWithAsymError=RooArgSet()) ; void storeSummaryOutput(const RooArgSet& vars) ; - void storeDetailedOutput(TNamed& object) ; + void storeDetailedOutput(std::unique_ptr object) ; void aggregateSummaryOutput(TList* chunkList) ; private: diff --git a/roofit/roofitcore/inc/RooAbsTestStatistic.h b/roofit/roofitcore/inc/RooAbsTestStatistic.h index 347b16da21aa0..544540df758de 100644 --- a/roofit/roofitcore/inc/RooAbsTestStatistic.h +++ b/roofit/roofitcore/inc/RooAbsTestStatistic.h @@ -54,7 +54,6 @@ class RooAbsTestStatistic : public RooAbsReal { }; // Constructors, assignment etc - RooAbsTestStatistic() {} RooAbsTestStatistic(const char *name, const char *title, RooAbsReal& real, RooAbsData& data, const RooArgSet& projDeps, Configuration const& cfg); RooAbsTestStatistic(const RooAbsTestStatistic& other, const char* name=nullptr); @@ -77,6 +76,12 @@ class RooAbsTestStatistic : public RooAbsReal { double offset() const override { return _offset.Sum() ; } virtual double offsetCarry() const { return _offset.Carry(); } + enum GOFOpMode { SimMaster,MPMaster,Slave } ; + GOFOpMode operMode() const { + // Return test statistic operation mode of this instance (SimMaster, MPMaster or Slave) + return _gofOpMode ; + } + protected: void printCompactTreeHook(std::ostream& os, const char* indent="") override ; @@ -87,6 +92,9 @@ class RooAbsTestStatistic : public RooAbsReal { virtual double evaluatePartition(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const = 0 ; virtual double getCarry() const; + // Overridden in cache-optimized test statistic + virtual void runRecalculateCache(std::size_t /*firstEvent*/, std::size_t /*lastEvent*/, std::size_t /*stepSize*/) const {} + void setMPSet(Int_t setNum, Int_t numSets) ; void setSimCount(Int_t simCount) { // Store total number of components p.d.f. of a RooSimultaneous in this component test statistic @@ -109,11 +117,6 @@ class RooAbsTestStatistic : public RooAbsReal { RooSetProxy _paramSet ; ///< Parameters of the test statistic (=parameters of the input function) - enum GOFOpMode { SimMaster,MPMaster,Slave } ; - GOFOpMode operMode() const { - // Return test statistic operation mode of this instance (SimMaster, MPMaster or Slave) - return _gofOpMode ; - } // Original arguments RooAbsReal* _func = nullptr; ///< Pointer to original input function @@ -151,10 +154,10 @@ class RooAbsTestStatistic : public RooAbsReal { Int_t _nCPU = 1; ///< Number of processors to use in parallel calculation mode pRooRealMPFE* _mpfeArray = nullptr; /// _offset = 0.0; /// _offset {0.0}; /// + +namespace ROOT { +namespace Math { +class AdaptiveIntegratorMultiDim; +} +} +class RooFunctor; class RooAdaptiveIntegratorND : public RooAbsIntegrator { public: // Constructors, assignment etc - RooAdaptiveIntegratorND() ; RooAdaptiveIntegratorND(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; ~RooAdaptiveIntegratorND() override; bool checkLimits() const override; @@ -39,11 +43,6 @@ class RooAdaptiveIntegratorND : public RooAbsIntegrator { using RooAbsIntegrator::setLimits ; bool setLimits(double* xmin, double* xmax) override; - bool canIntegrate1D() const override { return false ; } - bool canIntegrate2D() const override { return true ; } - bool canIntegrateND() const override { return true ; } - bool canIntegrateOpenEnded() const override { return false ; } - bool setUseIntegrandLimits(bool flag) override {_useIntegrandLimits = flag ; return true ; } protected: @@ -59,7 +58,8 @@ class RooAdaptiveIntegratorND : public RooAbsIntegrator { Int_t _nmax ; ///< Max number of divisions Int_t _nError ; ///< Number of error occurrences Int_t _nWarn ; ///< Max number of warnings to be issued ; - RooMultiGenFunction* _func ; /// _rooFunctor ; /// _func; /// _coefCache; /// _coefCache; /// createExpectedEventsFunc(const RooArgSet* nset) const override; + const RooArgList& pdfList() const { // Return list of component p.d.fs return _pdfList ; @@ -78,7 +79,7 @@ class RooAddPdf : public RooAbsPdf { void fixCoefNormalization(const RooArgSet& refCoefNorm) ; void fixCoefRange(const char* rangeName) ; - const RooArgSet& getCoefNormalization() const { return _refCoefNorm ; } + const RooArgSet& getCoefNormalization() const; const char* getCoefRange() const { return _refCoefRangeName?RooNameReg::str(_refCoefRangeName):"" ; } void resetErrorCounters(Int_t resetValue=10) override; @@ -92,13 +93,16 @@ class RooAddPdf : public RooAbsPdf { CacheMode canNodeBeCached() const override { return RooAbsArg::NotAdvised ; }; void setCacheAndTrackHints(RooArgSet&) override; -protected: + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + protected: void selectNormalization(const RooArgSet* depSet=nullptr, bool force=false) override; void selectNormalizationRange(const char* rangeName=nullptr, bool force=false) override; mutable RooSetProxy _refCoefNorm ; ///< Reference observable set for coefficient interpretation - mutable TNamed* _refCoefRangeName = nullptr ; ///< Reference range name for coefficient interpreation + mutable TNamed* _refCoefRangeName = nullptr ; ///< Reference range name for coefficient interpretation mutable std::vector _coefCache; /// _copyOfLastNormSet = nullptr; ///* plotSamplingHint(RooAbsRealLValue& /*obs*/, double /*xlo*/, double /*xhi*/) const override ; bool isBinnedDistribution(const RooArgSet& obs) const override ; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: diff --git a/roofit/roofitcore/inc/RooArgProxy.h b/roofit/roofitcore/inc/RooArgProxy.h index 52451e0179d9a..858bf3dbf2bee 100644 --- a/roofit/roofitcore/inc/RooArgProxy.h +++ b/roofit/roofitcore/inc/RooArgProxy.h @@ -71,6 +71,7 @@ class RooArgProxy : public TNamed, public RooAbsProxy { friend class RooRealIntegral; bool changePointer(const RooAbsCollection& newServerSet, bool nameChange=false, bool factoryInitMode=false) override ; + bool changePointer(std::unordered_map const& replacements) override; virtual void changeDataSet(const RooArgSet* newNormSet) ; diff --git a/roofit/roofitcore/inc/RooArgSet.h b/roofit/roofitcore/inc/RooArgSet.h index 1927b09ecbe48..c6acc5abc37ad 100644 --- a/roofit/roofitcore/inc/RooArgSet.h +++ b/roofit/roofitcore/inc/RooArgSet.h @@ -17,7 +17,6 @@ #define ROO_ARG_SET #include "RooAbsCollection.h" -#include "RooFit/UniqueId.h" class RooAbsArg ; class RooArgList ; @@ -33,7 +32,7 @@ class RooArgList ; // # Update April 2022: // // Using pointers comparisons for caching RooFit results caused too many bugs, -// even wih the memory pool. For example, if the RooArgSet is created on the +// even with the memory pool. For example, if the RooArgSet is created on the // stack, there is no guarantee that memory is not reused. Also, pointer // comparisons still work if the RooArgSets for the cache entry are already out // of scope, which can also cause problems. Therefore, when RooArgSets are used @@ -185,12 +184,6 @@ class RooArgSet : public RooAbsCollection { return RooAbsCollection::snapshot(output, deepCopy); } - /// Returns a unique ID that is different for every instantiated RooArgSet. - /// This ID can be used to check whether two RooAbsData are the same object, - /// which is safer than memory address comparisons that might result in false - /// positives when memory is recycled. - RooFit::UniqueId const& uniqueId() const { return _uniqueId; } - protected: bool checkForDup(const RooAbsArg& arg, bool silent) const ; bool canBeAdded(const RooAbsArg& arg, bool silent) const override { @@ -228,7 +221,6 @@ class RooArgSet : public RooAbsCollection { //to leak depending if RooArgSets are still alive. This depends on the order of destructions. static MemPool* memPool(); #endif - const RooFit::UniqueId _uniqueId; //! ClassDefOverride(RooArgSet,1) // Set of RooAbsArg objects }; diff --git a/roofit/roofitcore/inc/RooBinIntegrator.h b/roofit/roofitcore/inc/RooBinIntegrator.h index cfea2edd296d7..45546ebb7905b 100644 --- a/roofit/roofitcore/inc/RooBinIntegrator.h +++ b/roofit/roofitcore/inc/RooBinIntegrator.h @@ -21,20 +21,14 @@ #include #include -namespace RooBatchCompute { -struct RunContext; -} - class RooBinIntegrator : public RooAbsIntegrator { public: // Constructors, assignment etc - RooBinIntegrator() ; RooBinIntegrator(const RooAbsFunc& function, int numBins=100) ; RooBinIntegrator(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; ~RooBinIntegrator() override; bool checkLimits() const override; @@ -44,11 +38,6 @@ class RooBinIntegrator : public RooAbsIntegrator { bool setLimits(double* xmin, double* xmax) override; bool setUseIntegrandLimits(bool flag) override {_useIntegrandLimits = flag ; return true ; } - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return true ; } - bool canIntegrateND() const override { return true ; } - bool canIntegrateOpenEnded() const override { return false ; } - protected: friend class RooNumIntFactory ; @@ -63,9 +52,6 @@ class RooBinIntegrator : public RooAbsIntegrator { bool _useIntegrandLimits = false; ///< If true limits of function binding are ued - std::unique_ptr _evalData; /// _evalDataOrig; /// createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const override { @@ -106,16 +106,11 @@ class RooBinSamplingPdf : public RooAbsPdf { const RooAbsPdf& pdf() const { return _pdf.arg(); } const RooAbsReal& observable() const { return _observable.arg(); } - std::unique_ptr fillNormSetForServer(RooArgSet const& /*normSet*/, - RooAbsArg const& /*server*/) const override { - // servers are evaluated unnormalized - return std::make_unique(); - } + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; protected: double evaluate() const override; - RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const override; - RooSpan binBoundaries() const; + std::span binBoundaries() const; private: template diff --git a/roofit/roofitcore/inc/RooBinWidthFunction.h b/roofit/roofitcore/inc/RooBinWidthFunction.h index 4bb4e3c2a85d1..44b9d19973c65 100644 --- a/roofit/roofitcore/inc/RooBinWidthFunction.h +++ b/roofit/roofitcore/inc/RooBinWidthFunction.h @@ -22,30 +22,20 @@ #include "RooTemplateProxy.h" #include "RooHistFunc.h" -namespace BatchHelpers { struct RunContext; } - class RooBinWidthFunction : public RooAbsReal { static bool _enabled; - -public: + +public: static void enableClass(); static void disableClass(); - static bool isClassEnabled(); - + static bool isClassEnabled(); + /// Create an empty instance. RooBinWidthFunction() : _histFunc("HistFuncForBinWidth", "Handle to a RooHistFunc, whose bin volumes should be returned.", this, /*valueServer=*/true, /*shapeServer=*/true) { } - /// Create an instance. - /// \param name Name to identify the object. - /// \param title Title for e.g. plotting. - /// \param histFunc RooHistFunc object whose bin widths should be returned. - /// \param divideByBinWidth If true, return inverse bin width. - RooBinWidthFunction(const char* name, const char* title, const RooHistFunc& histFunc, bool divideByBinWidth) : - RooAbsReal(name, title), - _histFunc("HistFuncForBinWidth", "Handle to a RooHistFunc, whose bin volumes should be returned.", this, histFunc, /*valueServer=*/true, /*shapeServer=*/true), - _divideByBinWidth(divideByBinWidth) { } + RooBinWidthFunction(const char* name, const char* title, const RooHistFunc& histFunc, bool divideByBinWidth); /// Copy an existing object. RooBinWidthFunction(const RooBinWidthFunction& other, const char* newname = nullptr) : @@ -53,7 +43,7 @@ class RooBinWidthFunction : public RooAbsReal { _histFunc("HistFuncForBinWidth", this, other._histFunc), _divideByBinWidth(other._divideByBinWidth) { } - ~RooBinWidthFunction() override { } + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; /// Copy the object and return as TObject*. TObject* clone(const char* newname = nullptr) const override { @@ -77,7 +67,7 @@ class RooBinWidthFunction : public RooAbsReal { bool divideByBinWidth() const { return _divideByBinWidth; } const RooHistFunc& histFunc() const { return (*_histFunc); } double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; private: RooTemplateProxy _histFunc; diff --git a/roofit/roofitcore/inc/RooBinnedGenContext.h b/roofit/roofitcore/inc/RooBinnedGenContext.h index 4801dc97d6386..e995f1cdd7c77 100644 --- a/roofit/roofitcore/inc/RooBinnedGenContext.h +++ b/roofit/roofitcore/inc/RooBinnedGenContext.h @@ -46,10 +46,10 @@ class RooBinnedGenContext : public RooAbsGenContext { RooBinnedGenContext(const RooBinnedGenContext& other) ; - const RooArgSet* _vars ; - RooArgSet* _pdfSet ; ///< Set owned all nodes of internal clone of p.d.f + std::unique_ptr _vars; + RooArgSet _pdfSet ; ///< Set owned all nodes of internal clone of p.d.f RooAbsPdf *_pdf ; ///< Pointer to cloned p.d.f - RooDataHist* _hist ; ///< Histogram + std::unique_ptr _hist ; ///< Histogram bool _expectedData ; ///< Asimov? ClassDefOverride(RooBinnedGenContext,0) // Specialized context for generating a dataset from a binned pdf diff --git a/roofit/roofitcore/inc/RooBinning.h b/roofit/roofitcore/inc/RooBinning.h index c25b6be79a11f..c2f00e4394713 100644 --- a/roofit/roofitcore/inc/RooBinning.h +++ b/roofit/roofitcore/inc/RooBinning.h @@ -79,7 +79,7 @@ class RooBinning : public RooAbsBinning { double _xhi; ///< Upper bound bool _ownBoundLo; ///< Does the lower bound coincide with a bin boundary bool _ownBoundHi; ///< Does the upper bound coincide with a bin boundary - Int_t _nbins; ///< Numer of bins + Int_t _nbins; ///< Number of bins std::vector _boundaries; ///< Boundaries mutable double* _array; /// -class RooBrentRootFinder : public RooAbsRootFinder { +class RooAbsFunc; + +class RooBrentRootFinder { public: RooBrentRootFinder(const RooAbsFunc& function); - inline ~RooBrentRootFinder() override { } + virtual ~RooBrentRootFinder() = default; - bool findRoot(double &result, double xlo, double xhi, double value= 0) const override; + bool findRoot(double &result, double xlo, double xhi, double value= 0) const; /// Set convergence tolerance parameter void setTol(double tol) { @@ -31,11 +33,14 @@ class RooBrentRootFinder : public RooAbsRootFinder { } protected: - enum { MaxIterations = 512 }; + static constexpr int MaxIterations = 512; + + const RooAbsFunc *_function; ///< Pointer to input function + bool _valid; ///< True if current state is valid double _tol ; - ClassDefOverride(RooBrentRootFinder,0) // Abstract interface for 1-dim real-valued function root finders + ClassDef(RooBrentRootFinder,0) }; #endif diff --git a/roofit/roofitcore/inc/RooCacheManager.h b/roofit/roofitcore/inc/RooCacheManager.h index c04ab237d27d0..0238daff9eb05 100644 --- a/roofit/roofitcore/inc/RooCacheManager.h +++ b/roofit/roofitcore/inc/RooCacheManager.h @@ -167,7 +167,7 @@ RooCacheManager::RooCacheManager(const RooCacheManager& other, RooAbsArg* own Int_t i ; for (i=0 ; i::getObjByIndex(Int_t index) const } -/// Create RooArgSet contatining the objects that are both in the cached set 1 +/// Create RooArgSet containing the objects that are both in the cached set 1 //with a given index and an input argSet. template RooArgSet RooCacheManager::selectFromSet1(RooArgSet const& argSet, int index) const @@ -325,7 +325,7 @@ RooArgSet RooCacheManager::selectFromSet1(RooArgSet const& argSet, int index) } -/// Create RooArgSet contatining the objects that are both in the cached set 2 +/// Create RooArgSet containing the objects that are both in the cached set 2 //with a given index and an input argSet. template RooArgSet RooCacheManager::selectFromSet2(RooArgSet const& argSet, int index) const diff --git a/roofit/roofitcore/inc/RooCachedPdf.h b/roofit/roofitcore/inc/RooCachedPdf.h index 5ecccd683bae4..e433f3b555d57 100644 --- a/roofit/roofitcore/inc/RooCachedPdf.h +++ b/roofit/roofitcore/inc/RooCachedPdf.h @@ -34,8 +34,8 @@ class RooCachedPdf : public RooAbsCachedPdf { const char* inputBaseName() const override { return pdf.arg().GetName() ; } ; - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualObservables(const RooArgSet& nset) const override; + RooFit::OwningPtr actualParameters(const RooArgSet& nset) const override ; void fillCacheObject(PdfCacheElem& cachePdf) const override ; double evaluate() const override { // Dummy evaluate, it is never called diff --git a/roofit/roofitcore/inc/RooCachedReal.h b/roofit/roofitcore/inc/RooCachedReal.h index 23229be3dfeae..e8d00e1b42b1e 100644 --- a/roofit/roofitcore/inc/RooCachedReal.h +++ b/roofit/roofitcore/inc/RooCachedReal.h @@ -49,8 +49,8 @@ class RooCachedReal : public RooAbsCachedReal { const char* inputBaseName() const override { return func.arg().GetName() ; } ; - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualObservables(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualParameters(const RooArgSet& nset) const override; void fillCacheObject(FuncCacheElem& cacheFunc) const override ; /// Dummy evaluate, it is never called double evaluate() const override { diff --git a/roofit/roofitcore/inc/RooCatType.h b/roofit/roofitcore/inc/RooCatType.h deleted file mode 100644 index 8bddefa0fedf9..0000000000000 --- a/roofit/roofitcore/inc/RooCatType.h +++ /dev/null @@ -1,24 +0,0 @@ -// Author: Stephan Hageboeck, CERN 10 Feb 2020 - -/***************************************************************************** - * RooFit - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2019, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -#ifndef ROOFIT_ROOFITCORE_INC_ROOCATTYPE_H_ -#define ROOFIT_ROOFITCORE_INC_ROOCATTYPE_H_ - -/// RooCatType is deprecated, because it is slower and wastes more space than plain index numbers. -/// Consult the documentation of RooAbsCategory for ways to replace it. -#include "RooFitLegacy/RooCatTypeLegacy.h" - -#endif /* ROOFIT_ROOFITCORE_INC_ROOCATTYPE_H_ */ diff --git a/roofit/roofitcore/inc/RooChi2Var.h b/roofit/roofitcore/inc/RooChi2Var.h index 9634bbf9caea7..5382f244f1cca 100644 --- a/roofit/roofitcore/inc/RooChi2Var.h +++ b/roofit/roofitcore/inc/RooChi2Var.h @@ -27,14 +27,9 @@ class RooChi2Var : public RooAbsOptTestStatistic { // Constructors, assignment etc RooChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataHist& data, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(),const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none(),const RooCmdArg& arg9=RooCmdArg::none()) ; - - RooChi2Var(const char *name, const char* title, RooAbsPdf& pdf, RooDataHist& data, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(),const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none(),const RooCmdArg& arg9=RooCmdArg::none()) ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; enum FuncMode { Function, Pdf, ExtendedPdf } ; diff --git a/roofit/roofitcore/inc/RooClassFactory.h b/roofit/roofitcore/inc/RooClassFactory.h index 96a156ee62afe..f47b06e02f404 100644 --- a/roofit/roofitcore/inc/RooClassFactory.h +++ b/roofit/roofitcore/inc/RooClassFactory.h @@ -14,49 +14,46 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ -#ifndef ROO_CODE_FACTORY -#define ROO_CODE_FACTORY +#ifndef RooFit_RooClassFactory_h +#define RooFit_RooClassFactory_h -#include "TNamed.h" -#include "RooArgSet.h" -#include "RooPrintable.h" - -#include #include class RooAbsReal; class RooAbsPdf; +class RooArgList; // RooFit class code and instance factory class RooClassFactory { public: - - // Constructors, assignment etc - RooClassFactory() ; - ~RooClassFactory() ; - - static RooAbsReal* makeFunctionInstance(const char* className, const char* name, const char* expression, const RooArgList& vars, const char* intExpression=nullptr) ; - static RooAbsReal* makeFunctionInstance(const char* name, const char* expression, const RooArgList& vars, const char* intExpression=nullptr) ; - - static RooAbsPdf* makePdfInstance(const char* className, const char* name, const char* expression, const RooArgList& vars, const char* intExpression=nullptr) ; - static RooAbsPdf* makePdfInstance(const char* name, const char* expression, const RooArgList& vars, const char* intExpression=nullptr) ; - - static bool makeAndCompilePdf(const char* name, const char* expression, const RooArgList& vars, const char* intExpression=nullptr) ; - static bool makeAndCompileFunction(const char* name, const char* expression, const RooArgList& args, const char* intExpression=nullptr) ; - - static bool makePdf(const char* name, const char* realArgNames=nullptr, const char* catArgNames=nullptr, - const char* expression="1.0", bool hasAnaInt=false, bool hasIntGen=false, const char* intExpression=nullptr) ; - static bool makeFunction(const char* name, const char* realArgNames=nullptr, const char* catArgNames=nullptr, - const char* expression="1.0", bool hasAnaInt=false, const char* intExpression=nullptr) ; - static bool makeClass(const char* className, const char* name, const char* realArgNames=nullptr, const char* catArgNames=nullptr, - const char* expression="1.0", bool hasAnaInt=false, bool hasIntGen=false, const char* intExpression=nullptr) ; - -protected: - - - - RooClassFactory(const RooClassFactory&) ; -} ; + static RooAbsReal *makeFunctionInstance(std::string const &className, std::string const &name, + std::string const &expression, const RooArgList &vars, + std::string const &intExpression = ""); + static RooAbsReal *makeFunctionInstance(std::string const &name, std::string const &expression, + const RooArgList &vars, std::string const &intExpression = ""); + + static RooAbsPdf *makePdfInstance(std::string const &className, std::string const &name, + std::string const &expression, const RooArgList &vars, + std::string const &intExpression = ""); + static RooAbsPdf *makePdfInstance(std::string const &name, std::string const &expression, const RooArgList &vars, + std::string const &intExpression = ""); + + static bool makeAndCompilePdf(std::string const &name, std::string const &expression, const RooArgList &vars, + std::string const &intExpression = ""); + static bool makeAndCompileFunction(std::string const &name, std::string const &expression, const RooArgList &args, + std::string const &intExpression = ""); + + static bool makePdf(std::string const &name, std::string const &realArgNames = "", + std::string const &catArgNames = "", std::string const &expression = "1.0", + bool hasAnaInt = false, bool hasIntGen = false, std::string const &intExpression = ""); + static bool makeFunction(std::string const &name, std::string const &realArgNames = "", + std::string const &catArgNames = "", std::string const &expression = "1.0", + bool hasAnaInt = false, std::string const &intExpression = ""); + static bool makeClass(std::string const &baseName, const std::string &className, + std::string const &realArgNames = "", std::string const &catArgNames = "", + std::string const &expression = "1.0", bool hasAnaInt = false, bool hasIntGen = false, + std::string const &intExpression = ""); +}; #endif diff --git a/roofit/roofitcore/inc/RooCmdArg.h b/roofit/roofitcore/inc/RooCmdArg.h index 21eb46c52b5c0..32093caee60b0 100644 --- a/roofit/roofitcore/inc/RooCmdArg.h +++ b/roofit/roofitcore/inc/RooCmdArg.h @@ -23,7 +23,7 @@ class RooArgSet ; -class RooCmdArg final : public TNamed { +class RooCmdArg : public TNamed { public: RooCmdArg(); @@ -93,7 +93,7 @@ class RooCmdArg final : public TNamed { } /// Return string stored in slot idx const char* getString(Int_t idx) const { - return (_s[idx].size()>0) ? _s[idx].c_str() : nullptr ; + return (!_s[idx].empty()) ? _s[idx].c_str() : nullptr ; } /// Return TObject stored in slot idx const TObject* getObject(Int_t idx) const { diff --git a/roofit/roofitcore/inc/RooCmdConfig.h b/roofit/roofitcore/inc/RooCmdConfig.h index f09feccd6fc37..b5b70f288197d 100644 --- a/roofit/roofitcore/inc/RooCmdConfig.h +++ b/roofit/roofitcore/inc/RooCmdConfig.h @@ -18,6 +18,7 @@ #define ROO_CMD_CONFIG #include +#include #include #include @@ -31,7 +32,7 @@ class RooArgSet; class RooCmdConfig : public TObject { public: - RooCmdConfig(const char* methodName); + RooCmdConfig(RooStringView methodName); RooCmdConfig(const RooCmdConfig& other) ; /// If flag is true verbose messaging is activated @@ -52,11 +53,11 @@ class RooCmdConfig : public TObject { void defineMutex(const char* head, Args_t && ... tail); void defineMutex(const char*) {} // to end the recursion of defineMutex() - bool defineInt(const char* name, const char* argName, Int_t intNum, Int_t defValue=0) ; - bool defineDouble(const char* name, const char* argName, Int_t doubleNum, double defValue=0.0) ; - bool defineString(const char* name, const char* argName, Int_t stringNum, const char* defValue="",bool appendMode=false) ; - bool defineObject(const char* name, const char* argName, Int_t setNum, const TObject* obj=nullptr, bool isArray=false) ; - bool defineSet(const char* name, const char* argName, Int_t setNum, const RooArgSet* set=nullptr) ; + bool defineInt(const char* name, const char* argName, int intNum, int defValue=0) ; + bool defineDouble(const char* name, const char* argName, int doubleNum, double defValue=0.0) ; + bool defineString(const char* name, const char* argName, int stringNum, const char* defValue="",bool appendMode=false) ; + bool defineObject(const char* name, const char* argName, int setNum, const TObject* obj=nullptr, bool isArray=false) ; + bool defineSet(const char* name, const char* argName, int setNum, const RooArgSet* set=nullptr) ; bool process(const RooCmdArg& arg) ; template @@ -65,12 +66,12 @@ class RooCmdConfig : public TObject { template bool process(It_t begin, It_t end); - Int_t getInt(const char* name, Int_t defaultValue=0) ; - double getDouble(const char* name, double defaultValue=0.0) ; - const char* getString(const char* name, const char* defaultValue="",bool convEmptyToNull=false) ; - TObject* getObject(const char* name, TObject* obj=nullptr) ; - RooArgSet* getSet(const char* name, RooArgSet* set=nullptr) ; - const RooLinkedList& getObjectList(const char* name) ; + int getInt(const char* name, int defaultValue=0) const; + double getDouble(const char* name, double defaultValue=0.0) const; + const char* getString(const char* name, const char* defaultValue="",bool convEmptyToNull=false) const; + TObject* getObject(const char* name, TObject* obj=nullptr) const; + RooArgSet* getSet(const char* name, RooArgSet* set=nullptr) const; + const RooLinkedList& getObjectList(const char* name) const; bool ok(bool verbose) const ; @@ -84,20 +85,20 @@ class RooCmdConfig : public TObject { template - static Int_t decodeIntOnTheFly( - const char* callerID, const char* cmdArgName, Int_t intIdx, Int_t defVal, Args_t && ...args); + static int decodeIntOnTheFly( + const char* callerID, const char* cmdArgName, int intIdx, int defVal, Args_t && ...args); template static std::string decodeStringOnTheFly( - const char* callerID, const char* cmdArgName, Int_t intIdx, const char* defVal, Args_t && ...args); + const char* callerID, const char* cmdArgName, int intIdx, const char* defVal, Args_t && ...args); template static TObject* decodeObjOnTheFly( - const char* callerID, const char* cmdArgName, Int_t objIdx, TObject* defVal, Args_t && ...args); + const char* callerID, const char* cmdArgName, int objIdx, TObject* defVal, Args_t && ...args); template static RooArgSet* decodeSetOnTheFly( - const char* callerID, const char* cmdArgName, Int_t objIdx, RooArgSet* defVal, Args_t && ...args); + const char* callerID, const char* cmdArgName, int objIdx, RooArgSet* defVal, Args_t && ...args); static double decodeDoubleOnTheFly(const char* callerID, const char* cmdArgName, int idx, double defVal, std::initializer_list> args); @@ -113,7 +114,7 @@ class RooCmdConfig : public TObject { int num; }; - TString _name ; + std::string _name; bool _verbose = false; bool _error = false; @@ -185,8 +186,8 @@ bool RooCmdConfig::process(It_t begin, It_t end) { /// For use in base member initializers in constructors template -Int_t RooCmdConfig::decodeIntOnTheFly( - const char* callerID, const char* cmdArgName, Int_t intIdx, Int_t defVal, Args_t && ...args) +int RooCmdConfig::decodeIntOnTheFly( + const char* callerID, const char* cmdArgName, int intIdx, int defVal, Args_t && ...args) { RooCmdConfig pc(callerID) ; pc.allowUndefined() ; @@ -202,7 +203,7 @@ Int_t RooCmdConfig::decodeIntOnTheFly( template std::string RooCmdConfig::decodeStringOnTheFly( - const char* callerID, const char* cmdArgName, Int_t strIdx, const char* defVal, Args_t && ...args) + const char* callerID, const char* cmdArgName, int strIdx, const char* defVal, Args_t && ...args) { RooCmdConfig pc(callerID) ; pc.allowUndefined() ; @@ -220,7 +221,7 @@ std::string RooCmdConfig::decodeStringOnTheFly( template TObject* RooCmdConfig::decodeObjOnTheFly( - const char* callerID, const char* cmdArgName, Int_t objIdx, TObject* defVal, Args_t && ...args) + const char* callerID, const char* cmdArgName, int objIdx, TObject* defVal, Args_t && ...args) { RooCmdConfig pc(callerID) ; pc.allowUndefined() ; @@ -232,7 +233,7 @@ TObject* RooCmdConfig::decodeObjOnTheFly( template RooArgSet* RooCmdConfig::decodeSetOnTheFly( - const char* callerID, const char* cmdArgName, Int_t objIdx, RooArgSet* defVal, Args_t && ...args) + const char* callerID, const char* cmdArgName, int objIdx, RooArgSet* defVal, Args_t && ...args) { RooCmdConfig pc(callerID) ; pc.allowUndefined() ; diff --git a/roofit/roofitcore/inc/RooCollectionProxy.h b/roofit/roofitcore/inc/RooCollectionProxy.h index 21447276c6f1c..001dcd65ed655 100644 --- a/roofit/roofitcore/inc/RooCollectionProxy.h +++ b/roofit/roofitcore/inc/RooCollectionProxy.h @@ -55,10 +55,12 @@ class RooCollectionProxy final : public RooCollection_t, public RooAbsProxy { /// Copy constructor. template RooCollectionProxy(const char *inName, RooAbsArg *owner, const Other_t &other) - : RooCollection_t(other, inName), _owner(owner), _defValueServer(other.defValueServer()), + : RooCollection_t(other, inName), + _owner(owner), + _defValueServer(other.defValueServer()), _defShapeServer(other.defShapeServer()) { - _owner->registerProxy(*this); + _owner->registerProxy(*this); } /// Initializes this RooCollection proxy from another proxy. Should not be @@ -86,11 +88,11 @@ class RooCollectionProxy final : public RooCollection_t, public RooAbsProxy { // Assignment is deleted because it is not clear how it should behave. // Should default assignment be used? But then, it will use the assignment // operators of the RooFit collections, which actually don't do assignment, - // but value syncronization! Should it be re-implemented to be actual + // but value synchronization! Should it be re-implemented to be actual // assignment? That would be inconsistent with the base class! So it's // better to not support it at all. - RooCollectionProxy& operator=(RooCollectionProxy const& other) = delete; - RooCollectionProxy& operator=(RooCollectionProxy && other) = delete; + RooCollectionProxy &operator=(RooCollectionProxy const &other) = delete; + RooCollectionProxy &operator=(RooCollectionProxy &&other) = delete; ~RooCollectionProxy() override { @@ -113,7 +115,17 @@ class RooCollectionProxy final : public RooCollection_t, public RooAbsProxy { } using RooAbsCollection::addOwned; + +// The following function is not memory safe, because it takes ownership of var +// without moving it. It is not publicly available in the memory safe +// interfaces mode. +#ifdef ROOFIT_MEMORY_SAFE_INTERFACES +protected: +#endif bool addOwned(RooAbsArg &var, bool silent = false) override; +#ifdef ROOFIT_MEMORY_SAFE_INTERFACES +public: +#endif using RooAbsCollection::addClone; RooAbsArg *addClone(const RooAbsArg &var, bool silent = false) override; @@ -154,6 +166,8 @@ class RooCollectionProxy final : public RooCollection_t, public RooAbsProxy { bool changePointer(const RooAbsCollection &newServerSet, bool nameChange = false, bool factoryInitMode = false) override; + bool changePointer(std::unordered_map const &replacements) override; + void checkValid() const { if (!_owner) { @@ -291,6 +305,20 @@ bool RooCollectionProxy::changePointer(const RooAbsCollection & return !error; } +template +bool RooCollectionProxy::changePointer( + std::unordered_map const &replacements) +{ + bool error(false); + for (auto const &arg : *this) { + auto newArgFound = replacements.find(arg); + if (newArgFound != replacements.end()) { + error |= !RooCollection_t::replace(*arg, *newArgFound->second); + } + } + return !error; +} + //////////////////////////////////////////////////////////////////////////////// /// Printing name of proxy on ostream. If addContents is true /// also print names of objects in set diff --git a/roofit/roofitcore/inc/RooCompositeDataStore.h b/roofit/roofitcore/inc/RooCompositeDataStore.h index e04b8a6a38aeb..d2a5d289aa14e 100644 --- a/roofit/roofitcore/inc/RooCompositeDataStore.h +++ b/roofit/roofitcore/inc/RooCompositeDataStore.h @@ -110,7 +110,7 @@ class RooCompositeDataStore : public RooAbsDataStore { (void)first; (void)len; return {}; } - RooSpan getWeightBatch(std::size_t first, std::size_t len) const override; + std::span getWeightBatch(std::size_t first, std::size_t len) const override; protected: diff --git a/roofit/roofitcore/inc/RooConstVar.h b/roofit/roofitcore/inc/RooConstVar.h index baebaf8ff3932..ea75bbfb08758 100644 --- a/roofit/roofitcore/inc/RooConstVar.h +++ b/roofit/roofitcore/inc/RooConstVar.h @@ -19,9 +19,6 @@ #include "RooAbsReal.h" class RooArgSet ; -namespace RooBatchCompute { - struct RunContext; -} class RooConstVar final : public RooAbsReal { public: @@ -37,8 +34,6 @@ class RooConstVar final : public RooAbsReal { return _value; } - RooSpan getValues(RooBatchCompute::RunContext& evalData, const RooArgSet*) const override; - void writeToStream(std::ostream& os, bool compact) const override ; /// Returns false, as the value of the constant doesn't depend on other objects. @@ -54,6 +49,8 @@ class RooConstVar final : public RooAbsReal { _value = value; } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + protected: double evaluate() const override { diff --git a/roofit/roofitcore/inc/RooConstraintSum.h b/roofit/roofitcore/inc/RooConstraintSum.h index 3362ce5206376..3e79a6ffc5b8c 100644 --- a/roofit/roofitcore/inc/RooConstraintSum.h +++ b/roofit/roofitcore/inc/RooConstraintSum.h @@ -41,10 +41,11 @@ class RooConstraintSum : public RooAbsReal { return setData(static_cast(data), cloneData); } - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; - std::unique_ptr fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const override; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: RooListProxy _set1 ; ///< Set of constraint terms diff --git a/roofit/roofitcore/inc/RooConvCoefVar.h b/roofit/roofitcore/inc/RooConvCoefVar.h index 7dbd87fc5ef2e..52f6380cf1072 100644 --- a/roofit/roofitcore/inc/RooConvCoefVar.h +++ b/roofit/roofitcore/inc/RooConvCoefVar.h @@ -17,7 +17,7 @@ #define ROO_CONV_COEF_VAR #include -#include +#include #include "RooAbsReal.h" #include "RooRealVar.h" diff --git a/roofit/roofitcore/inc/RooCurve.h b/roofit/roofitcore/inc/RooCurve.h index 06060c7fb3499..e2c657b63ccd5 100644 --- a/roofit/roofitcore/inc/RooCurve.h +++ b/roofit/roofitcore/inc/RooCurve.h @@ -16,11 +16,15 @@ #ifndef ROO_CURVE #define ROO_CURVE -#include "TGraph.h" -#include "RooPlotable.h" +#include + +#include + +#include +#include + #include #include -#include "TMatrixDfwd.h" class RooAbsReal; class RooRealVar; @@ -71,6 +75,8 @@ class RooCurve : public TGraph, public RooPlotable { RooCurve* makeErrorBand(const std::vector& variations, double Z=1) const ; RooCurve* makeErrorBand(const std::vector& plusVar, const std::vector& minusVar, const TMatrixD& V, double Z=1) const ; + static std::list* plotSamplingHintForBinBoundaries(std::span boundaries, double xlo, double xhi); + protected: void calcBandInterval(const std::vector& variations,Int_t i,double Z,double& lo, double& hi, bool approxGauss) const ; @@ -83,12 +89,19 @@ class RooCurve : public TGraph, public RooPlotable { Int_t numee=0, bool doEEVal=false, double eeVal=0.0,std::list* samplingHint=nullptr) ; void addRange(const RooAbsFunc& func, double x1, double x2, double y1, double y2, double minDy, double minDx, - Int_t numee=0, bool doEEVal=false, double eeVal=0.0); + int numee, bool doEEVal, double eeVal, double epsilon); + + void shiftCurveToZero(); - void shiftCurveToZero(double prevYMax) ; + bool _showProgress = false; /// histMap, double initWgt=1.0) ; RooDataHist(RooStringView name, RooStringView title, const RooArgList& vars, RooCategory& indexCat, std::map dhistMap, double wgt=1.0) ; //RooDataHist(const char *name, const char *title, const RooArgList& vars, double initWgt=1.0) ; - RooDataHist(RooStringView name, RooStringView title, const RooArgList& vars, const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg(), const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(),const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(),const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg()) ; + RooDataHist(RooStringView name, RooStringView title, const RooArgList& vars, const RooCmdArg& arg1, const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={},const RooCmdArg& arg5={},const RooCmdArg& arg6={},const RooCmdArg& arg7={},const RooCmdArg& arg8={}) ; RooDataHist& operator=(const RooDataHist&) = delete; RooDataHist(const RooDataHist& other, const char* newname = nullptr) ; @@ -58,13 +58,13 @@ class RooDataHist : public RooAbsData, public RooDirItem { ~RooDataHist() override ; /// Return empty clone of this RooDataHist. - RooAbsData* emptyClone(const char* newName=nullptr, const char* newTitle=nullptr, const RooArgSet*vars=nullptr, const char* /*wgtVarName*/=nullptr) const override { - return new RooDataHist(newName?newName:GetName(),newTitle?newTitle:GetTitle(),vars?*vars:*get()) ; + RooFit::OwningPtr emptyClone(const char* newName=nullptr, const char* newTitle=nullptr, const RooArgSet*vars=nullptr, const char* /*wgtVarName*/=nullptr) const override { + return RooFit::Detail::owningPtr(std::make_unique(newName?newName:GetName(),newTitle?newTitle:GetTitle(),vars?*vars:*get())); } /// Add `wgt` to the bin content enclosed by the coordinates passed in `row`. - virtual void add(const RooArgSet& row, double wgt=1.0) { add(row,wgt,-1.); } - void add(const RooArgSet& row, double weight, double sumw2) override ; + void add(const RooArgSet& row, double wgt=1.0) override { add(row,wgt,-1.); } + void add(const RooArgSet& row, double weight, double sumw2); void set(std::size_t binNumber, double weight, double wgtErr); void set(const RooArgSet& row, double weight, double wgtErr=-1.) ; void set(const RooArgSet& row, double weight, double wgtErrLo, double wgtErrHi) ; @@ -83,10 +83,10 @@ class RooDataHist : public RooAbsData, public RooDirItem { bool isWeighted() const override { return true; } bool isNonPoissonWeighted() const override ; - RooSpan getWeightBatch(std::size_t first, std::size_t len, bool sumW2=false) const override; + std::span getWeightBatch(std::size_t first, std::size_t len, bool sumW2=false) const override; /// Retrieve all bin volumes. Bins are indexed according to getIndex(). - RooSpan binVolumes(std::size_t first, std::size_t len) const { + std::span binVolumes(std::size_t first, std::size_t len) const { return {_binv + first, len}; } @@ -99,7 +99,7 @@ class RooDataHist : public RooAbsData, public RooDirItem { const std::map >& ranges, std::function getBinScale = [](int){ return 1.0; } ); - void weights(double* output, RooSpan xVals, int intOrder, bool correctForBinSize, bool cdfBoundaries); + void weights(double* output, std::span xVals, int intOrder, bool correctForBinSize, bool cdfBoundaries); /// Return weight of i-th bin. \see getIndex() double weight(std::size_t i) const { return _wgt[i]; } double weightFast(const RooArgSet& bin, int intOrder, bool correctForBinSize, bool cdfBoundaries); @@ -210,8 +210,12 @@ class RooDataHist : public RooAbsData, public RooDirItem { double const* wgtErrHiArray() const { return _errHi; } double const* sumW2Array() const { return _sumw2; } -protected: + std::string calculateTreeIndexForCodeSquash(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, + const RooAbsCollection &coords, bool reverse = false) const; + std::string declWeightArrayForCodeSquash(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, + bool correctForBinSize) const; + protected: friend class RooDataHistSliceIter ; std::size_t calcTreeIndex(const RooAbsCollection& coords, bool fast) const; @@ -220,7 +224,7 @@ class RooDataHist : public RooAbsData, public RooDirItem { Int_t calcTreeIndex() const { return static_cast(calcTreeIndex(_vars, true)); } void initialize(const char* binningName=nullptr,bool fillTree=true) ; - RooAbsData* reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, + std::unique_ptr reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, std::size_t nStart=0, std::size_t nStop=std::numeric_limits::max()) override; double interpolateDim(int iDim, double xval, size_t centralIdx, int intOrder, bool correctForBinSize, bool cdfBoundaries) ; const std::vector& calculatePartialBinVolume(const RooArgSet& dimSet) const ; @@ -252,8 +256,8 @@ class RooDataHist : public RooAbsData, public RooDirItem { mutable double _cache_sum{0.}; /// xVals, bool correctForBinSize, bool cdfBoundaries); - void interpolateLinear(double* output, RooSpan xVals, bool correctForBinSize, bool cdfBoundaries); + void interpolateQuadratic(double* output, std::span xVals, bool correctForBinSize, bool cdfBoundaries); + void interpolateLinear(double* output, std::span xVals, bool correctForBinSize, bool cdfBoundaries); double weightInterpolated(const RooArgSet& bin, int intOrder, bool correctForBinSize, bool cdfBoundaries); void _adjustBinning(RooRealVar &theirVar, const TAxis &axis, RooRealVar *ourVar, Int_t *offset); @@ -261,7 +265,8 @@ class RooDataHist : public RooAbsData, public RooDirItem { void initializeAsymErrArrays() const; VarInfo const& getVarInfo(); - static std::unique_ptr makeDefaultDataStore(const char* name, const char* title, RooArgSet const& vars); + static std::unique_ptr + makeDefaultDataStore(RooStringView name, RooStringView title, RooArgSet const &vars); VarInfo _varInfo; /// _interpolationBuffer; /// getValues(std::vector> coordinates) const override; - protected: mutable bool _first ; ///< Bit indicating if operator() has been called yet @@ -40,7 +38,6 @@ class RooDataProjBinding : public RooRealBinding { RooSuperCategory* _superCat ; ///< Supercategory constructed from _data's category variables Roo1DTable* _catTable ; ///< Supercategory table generated from _data - mutable std::unique_ptr> _batchBuffer; /// emptyClone(const char* newName=nullptr, const char* newTitle=nullptr, const RooArgSet* vars=nullptr, const char* wgtVarName=nullptr) const override; - RooDataHist* binnedClone(const char* newName=nullptr, const char* newTitle=nullptr) const ; + RooFit::OwningPtr binnedClone(const char* newName=nullptr, const char* newTitle=nullptr) const ; double sumEntries() const override; double sumEntries(const char* cutSpec, const char* cutRange=nullptr) const override; virtual RooPlot* plotOnXY(RooPlot* frame, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) const ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) const ; /// Read data from a text file and create a dataset from it. @@ -127,10 +129,11 @@ class RooDataSet : public RooAbsData, public RooDirItem { const RooArgSet* get(Int_t index) const override; const RooArgSet* get() const override; - RooSpan getWeightBatch(std::size_t first, std::size_t len, bool sumW2) const override; + std::span getWeightBatch(std::size_t first, std::size_t len, bool sumW2) const override; /// Add one ore more rows of data - void add(const RooArgSet& row, double weight=1.0, double weightError=0.0) override; + void add(const RooArgSet& row, double weight, double weightError); + void add(const RooArgSet& row, double weight=1.0) override { add(row, weight, 0.0); } virtual void add(const RooArgSet& row, double weight, double weightErrorLo, double weightErrorHi); virtual void addFast(const RooArgSet& row, double weight=1.0, double weightError=0.0); @@ -161,18 +164,17 @@ class RooDataSet : public RooAbsData, public RooDirItem { void initialize(const char* wgtVarName) ; // Cache copy feature is not publicly accessible - RooAbsData* reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, + std::unique_ptr reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange=nullptr, std::size_t nStart=0, std::size_t nStop = std::numeric_limits::max()) override; - RooDataSet(RooStringView name, RooStringView title, RooDataSet *ntuple, - const RooArgSet& vars, const RooFormulaVar* cutVar, const char* cutRange, - std::size_t nStart, std::size_t nStop); - - RooArgSet addWgtVar(const RooArgSet& origVars, const RooAbsArg* wgtVar) ; - RooArgSet _varsNoWgt ; ///< Vars without weight variable - RooRealVar* _wgtVar ; ///< Pointer to weight variable (if set) + RooArgSet _varsNoWgt; ///< Vars without weight variable + RooRealVar *_wgtVar = nullptr; ///< Pointer to weight variable (if set) private: + + void loadValuesFromSlices(RooCategory &indexCat, std::map const &slices, + const char *rangeName, RooFormulaVar const *cutVar, const char *cutSpec); + #ifdef USEMEMPOOLFORDATASET typedef MemPoolForRooSets MemPool; ///< 150 = about 100kb static MemPool * memPool(); diff --git a/roofit/roofitcore/inc/RooDataWeightedAverage.h b/roofit/roofitcore/inc/RooDataWeightedAverage.h index 520360b2f7a08..b2e21ee0a20e2 100644 --- a/roofit/roofitcore/inc/RooDataWeightedAverage.h +++ b/roofit/roofitcore/inc/RooDataWeightedAverage.h @@ -23,10 +23,6 @@ class RooDataWeightedAverage : public RooAbsOptTestStatistic { public: // Constructors, assignment etc - RooDataWeightedAverage() { - // Default constructor - } ; - RooDataWeightedAverage(const char *name, const char *title, RooAbsReal& real, RooAbsData& data, const RooArgSet& projDeps, RooAbsTestStatistic::Configuration const& cfg, bool showProgress=false) ; @@ -52,6 +48,13 @@ class RooDataWeightedAverage : public RooAbsOptTestStatistic { double evaluatePartition(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const override ; ClassDefOverride(RooDataWeightedAverage,0) // Optimized calculator of data weighted average of a RooAbsReal + +// Undocumented preprocessor define such that the implementation in +// RooDataWeightedAverage.cxx can suppress the deprecation warning. +#ifndef __ROOFIT_SUPPRESS_ROODATAWEIGHTEDAVERAGE_DEPRECATION_WARNING +} R__DEPRECATED(6, 32, "RooDataWeightedAverage is an implementation detail of RooFit that will be removed from the public user interface."); +#else }; +#endif #endif diff --git a/roofit/roofitcore/inc/RooEffGenContext.h b/roofit/roofitcore/inc/RooEffGenContext.h index 191e3ac6d80d1..527af4864f7f7 100644 --- a/roofit/roofitcore/inc/RooEffGenContext.h +++ b/roofit/roofitcore/inc/RooEffGenContext.h @@ -22,23 +22,24 @@ class RooAbsReal; class RooEffGenContext : public RooAbsGenContext { public: - RooEffGenContext(const RooAbsPdf &model, - const RooAbsPdf &pdf,const RooAbsReal& eff, - const RooArgSet &vars, const RooDataSet *prototype= nullptr, - const RooArgSet* auxProto=nullptr, bool verbose=false, const RooArgSet* forceDirect=nullptr); - ~RooEffGenContext() override; + RooEffGenContext(const RooAbsPdf &model, const RooAbsPdf &pdf, const RooAbsReal &eff, const RooArgSet &vars, + const RooDataSet *prototype = nullptr, const RooArgSet *auxProto = nullptr, bool verbose = false, + const RooArgSet *forceDirect = nullptr); + ~RooEffGenContext() override; + + void printMultiline(std::ostream &os, Int_t content, bool verbose = false, TString indent = "") const override; protected: - void initGenerator(const RooArgSet &theEvent) override; - void generateEvent(RooArgSet &theEvent, Int_t remaining) override; + void initGenerator(const RooArgSet &theEvent) override; + void generateEvent(RooArgSet &theEvent, Int_t remaining) override; private: - RooArgSet* _cloneSet; ///< Internal clone of p.d.f. - RooAbsReal* _eff; ///< Pointer to efficiency function - RooAbsGenContext* _generator; ///< Generator context for p.d.f - RooArgSet* _vars; ///< Vars to generate - double _maxEff; ///< Maximum of efficiency in vars + RooArgSet _cloneSet; ///< Internal clone of p.d.f. + RooAbsReal *_eff; ///< Pointer to efficiency function + RooAbsGenContext *_generator; ///< Generator context for p.d.f + RooArgSet _vars; ///< Vars to generate + double _maxEff; ///< Maximum of efficiency in vars - ClassDefOverride(RooEffGenContext, 1) // Context for generating a dataset from a PDF + ClassDefOverride(RooEffGenContext, 0); // Context for generating a dataset from a PDF }; #endif diff --git a/roofit/roofitcore/inc/RooErrorHandler.h b/roofit/roofitcore/inc/RooErrorHandler.h index 242f8457fa691..22ddd90caef5f 100644 --- a/roofit/roofitcore/inc/RooErrorHandler.h +++ b/roofit/roofitcore/inc/RooErrorHandler.h @@ -16,7 +16,7 @@ #ifndef ROO_ERROR_HANDLER #define ROO_ERROR_HANDLER -#include +#include #include #include "RtypesCore.h" diff --git a/roofit/roofitcore/inc/RooExtendPdf.h b/roofit/roofitcore/inc/RooExtendPdf.h index 78afdb645fc03..dfb287e3554ea 100644 --- a/roofit/roofitcore/inc/RooExtendPdf.h +++ b/roofit/roofitcore/inc/RooExtendPdf.h @@ -22,12 +22,14 @@ class RooExtendPdf : public RooAbsPdf { public: - RooExtendPdf() ; + RooExtendPdf() = default; + // Original constructor without RooAbsReal::Ref for backwards compatibility. RooExtendPdf(const char *name, const char *title, RooAbsPdf& pdf, - RooAbsReal& norm, const char* rangeName=nullptr) ; + RooAbsReal& norm, const char* rangeName=nullptr); + RooExtendPdf(const char *name, const char *title, RooAbsPdf& pdf, + RooAbsReal::Ref norm, const char* rangeName=nullptr) ; RooExtendPdf(const RooExtendPdf& other, const char* name=nullptr) ; TObject* clone(const char* newname) const override { return new RooExtendPdf(*this,newname) ; } - ~RooExtendPdf() override ; double evaluate() const override { return _pdf ; } @@ -44,12 +46,15 @@ class RooExtendPdf : public RooAbsPdf { bool selfNormalized() const override { return true ; } ExtendMode extendMode() const override { return CanBeExtended ; } double expectedEvents(const RooArgSet* nset) const override ; + std::unique_ptr createExpectedEventsFunc(const RooArgSet* nset) const override; + + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: - RooTemplateProxy _pdf; ///< Input p.d.f - RooTemplateProxy _n; ///< Number of expected events - const TNamed* _rangeName ; ///< Name of subset range + RooTemplateProxy _pdf; ///< Input p.d.f + RooTemplateProxy _n; ///< Number of expected events + const TNamed* _rangeName = nullptr; ///< Name of subset range ClassDefOverride(RooExtendPdf,2) // Wrapper p.d.f adding an extended likelihood term to an existing p.d.f diff --git a/roofit/roofitcore/inc/RooExtendedTerm.h b/roofit/roofitcore/inc/RooExtendedTerm.h index 51e6ea408f344..6169ba613c942 100644 --- a/roofit/roofitcore/inc/RooExtendedTerm.h +++ b/roofit/roofitcore/inc/RooExtendedTerm.h @@ -22,11 +22,10 @@ class RooExtendedTerm : public RooAbsPdf { public: - RooExtendedTerm() ; + RooExtendedTerm() = default; RooExtendedTerm(const char *name, const char *title, const RooAbsReal& n) ; RooExtendedTerm(const RooExtendedTerm& other, const char* name=nullptr) ; TObject* clone(const char* newname) const override { return new RooExtendedTerm(*this,newname) ; } - ~RooExtendedTerm() override ; double evaluate() const override { return 1. ; } @@ -34,6 +33,8 @@ class RooExtendedTerm : public RooAbsPdf { /// Return number of expected events, in other words the value of the associated n parameter. double expectedEvents(const RooArgSet* nset) const override ; + std::unique_ptr createExpectedEventsFunc(const RooArgSet* nset) const override; + protected: RooRealProxy _n ; ///< Number of expected events diff --git a/roofit/roofitcore/inc/RooFFTConvPdf.h b/roofit/roofitcore/inc/RooFFTConvPdf.h index 592194a2895fb..0c93c35feb103 100644 --- a/roofit/roofitcore/inc/RooFFTConvPdf.h +++ b/roofit/roofitcore/inc/RooFFTConvPdf.h @@ -95,8 +95,8 @@ class RooFFTConvPdf : public RooAbsCachedPdf { double evaluate() const override { RooArgSet dummy(_x.arg()) ; return getVal(&dummy) ; } ; // dummy const char* inputBaseName() const override ; - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualObservables(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualParameters(const RooArgSet& nset) const override ; RooAbsArg& pdfObservable(RooAbsArg& histObservable) const override ; void fillCacheObject(PdfCacheElem& cache) const override ; void fillCacheSlice(FFTCacheElem& cache, const RooArgSet& slicePosition) const ; @@ -104,7 +104,7 @@ class RooFFTConvPdf : public RooAbsCachedPdf { PdfCacheElem* createCache(const RooArgSet* nset) const override ; TString histNameSuffix() const override ; - // mutable std:: map _cacheAuxInfo ; //! Auxilary Cache information (do not persist) + // mutable std::map _cacheAuxInfo ; //! Auxiliary Cache information (do not persist) double _bufFrac ; // Sampling buffer size as fraction of domain size BufStrat _bufStrat ; // Strategy to fill the buffer diff --git a/roofit/roofitcore/inc/RooFit/Config.h b/roofit/roofitcore/inc/RooFit/Config.h new file mode 100644 index 0000000000000..ad95c61d0a9bd --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Config.h @@ -0,0 +1,74 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Config_h +#define RooFit_Config_h + +// Define ROOFIT_MEMORY_SAFE_INTERFACES to change RooFit interfaces to be +// memory safe. +// #define ROOFIT_MEMORY_SAFE_INTERFACES + +// The memory safe interfaces mode implies that all RooFit::OwningPtr are +// std::unique_ptr. +#ifdef ROOFIT_MEMORY_SAFE_INTERFACES +#ifndef ROOFIT_OWNING_PTR_IS_UNIQUE_PTR +#define ROOFIT_OWNING_PTR_IS_UNIQUE_PTR +#endif +#endif + +#include + +namespace RooFit { + +/// An alias for raw pointers for indicating that the return type of a RooFit +/// function is an owning pointer that must be deleted by the caller. For +/// RooFit developers, it can be very useful to make this an alias to +/// std::unique_ptr, in order to check that your code has no memory +/// problems. Changing this alias is equivalent to forcing all code immediately +/// wraps the result of functions returning a RooFit::OwningPtr in a +/// std::unique_ptr. +template +#ifdef ROOFIT_OWNING_PTR_IS_UNIQUE_PTR +using OwningPtr = std::unique_ptr; +#else +using OwningPtr = T *; +#endif + +namespace Detail { + +/// Internal helper to turn a std::unique_ptr into an OwningPtr. +template +OwningPtr owningPtr(std::unique_ptr &&ptr) +{ +#ifdef ROOFIT_OWNING_PTR_IS_UNIQUE_PTR + return std::move(ptr); +#else + return ptr.release(); +#endif +} + +/// internal helper to turn a std::unique_ptr into an owningptr. +template +OwningPtr owningPtr(std::unique_ptr &&ptr) +{ +#ifdef ROOFIT_OWNING_PTR_IS_UNIQUE_PTR + return std::unique_ptr{static_cast(ptr.release())}; +#else + return static_cast(ptr.release()); +#endif +} + +} // namespace Detail + +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/Detail/AnalyticalIntegrals.h b/roofit/roofitcore/inc/RooFit/Detail/AnalyticalIntegrals.h new file mode 100644 index 0000000000000..8faeb9f23ab62 --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Detail/AnalyticalIntegrals.h @@ -0,0 +1,265 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * Garima Singh, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_AnalyticalIntegrals_h +#define RooFit_Detail_AnalyticalIntegrals_h + +#include +#include + +#include + +namespace RooFit { + +namespace Detail { + +namespace AnalyticalIntegrals { + +/// @brief Function to calculate the integral of an un-normalized RooGaussian over x. To calculate the integral over +/// mean, just interchange the respective values of x and mean. +/// @param xMin Minimum value of variable to integrate wrt. +/// @param xMax Maximum value of of variable to integrate wrt. +/// @param mean Mean. +/// @param sigma Sigma. +/// @return The integral of an un-normalized RooGaussian over the value in x. +inline double gaussianIntegral(double xMin, double xMax, double mean, double sigma) +{ + // The normalisation constant 1./sqrt(2*pi*sigma^2) is left out in evaluate(). + // Therefore, the integral is scaled up by that amount to make RooFit normalise + // correctly. + double resultScale = std::sqrt(TMath::TwoPi()) * sigma; + + // Here everything is scaled and shifted into a standard normal distribution: + double xscale = TMath::Sqrt2() * sigma; + double scaledMin = 0.; + double scaledMax = 0.; + scaledMin = (xMin - mean) / xscale; + scaledMax = (xMax - mean) / xscale; + + // Here we go for maximum precision: We compute all integrals in the UPPER + // tail of the Gaussian, because erfc has the highest precision there. + // Therefore, the different cases for range limits in the negative hemisphere are mapped onto + // the equivalent points in the upper hemisphere using erfc(-x) = 2. - erfc(x) + double ecmin = TMath::Erfc(std::abs(scaledMin)); + double ecmax = TMath::Erfc(std::abs(scaledMax)); + + double cond = 0.0; + // Don't put this "prd" inside the "if" because clad will not be able to differentiate the code correctly (as of + // v1.1)! + double prd = scaledMin * scaledMax; + if (prd < 0.0) + cond = 2.0 - (ecmin + ecmax); + else if (scaledMax <= 0.0) + cond = ecmax - ecmin; + else + cond = ecmin - ecmax; + return resultScale * 0.5 * cond; +} + +inline double exponentialIntegral(double xMin, double xMax, double constant) +{ + if (constant == 0.0) { + return xMax - xMin; + } + + return (std::exp(constant * xMax) - std::exp(constant * xMin)) / constant; +} + +/// In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0. +template +inline double polynomialIntegral(double const *coeffs, int nCoeffs, int lowestOrder, double xMin, double xMax) +{ + int denom = lowestOrder + nCoeffs; + double min = coeffs[nCoeffs - 1] / double(denom); + double max = coeffs[nCoeffs - 1] / double(denom); + + for (int i = nCoeffs - 2; i >= 0; i--) { + denom--; + min = (coeffs[i] / double(denom)) + xMin * min; + max = (coeffs[i] / double(denom)) + xMax * max; + } + + max = max * std::pow(xMax, 1 + lowestOrder); + min = min * std::pow(xMin, 1 + lowestOrder); + + return max - min + (pdfMode && lowestOrder > 0.0 ? xMax - xMin : 0.0); +} + +/// use fast FMA if available, fall back to normal arithmetic if not +inline double fast_fma(double x, double y, double z) noexcept +{ +#if defined(FP_FAST_FMA) // check if std::fma has fast hardware implementation + return std::fma(x, y, z); +#else // defined(FP_FAST_FMA) + // std::fma might be slow, so use a more pedestrian implementation +#if defined(__clang__) +#pragma STDC FP_CONTRACT ON // hint clang that using an FMA is okay here +#endif // defined(__clang__) + return (x * y) + z; +#endif // defined(FP_FAST_FMA) +} + +inline double chebychevIntegral(double const *coeffs, unsigned int nCoeffs, double xMin, double xMax, double xMinFull, + double xMaxFull) +{ + const double halfrange = .5 * (xMax - xMin); + const double mid = .5 * (xMax + xMin); + + // the full range of the function is mapped to the normalised [-1, 1] range + const double b = (xMaxFull - mid) / halfrange; + const double a = (xMinFull - mid) / halfrange; + + // coefficient for integral(T_0(x)) is 1 (implicit), integrate by hand + // T_0(x) and T_1(x), and use for n > 1: integral(T_n(x) dx) = + // (T_n+1(x) / (n + 1) - T_n-1(x) / (n - 1)) / 2 + double sum = b - a; // integrate T_0(x) by hand + + const unsigned int iend = nCoeffs; + if (iend > 0) { + { + // integrate T_1(x) by hand... + const double c = coeffs[0]; + sum = fast_fma(0.5 * (b + a) * (b - a), c, sum); + } + if (1 < iend) { + double bcurr = b; + double btwox = 2 * b; + double blast = 1; + + double acurr = a; + double atwox = 2 * a; + double alast = 1; + + double newval = atwox * acurr - alast; + alast = acurr; + acurr = newval; + + newval = btwox * bcurr - blast; + blast = bcurr; + bcurr = newval; + double nminus1 = 1.; + for (unsigned int i = 1; iend != i; ++i) { + // integrate using recursion relation + const double c = coeffs[i]; + const double term2 = (blast - alast) / nminus1; + + newval = atwox * acurr - alast; + alast = acurr; + acurr = newval; + + newval = btwox * bcurr - blast; + blast = bcurr; + bcurr = newval; + + ++nminus1; + const double term1 = (bcurr - acurr) / (nminus1 + 1.); + const double intTn = 0.5 * (term1 - term2); + sum = fast_fma(intTn, c, sum); + } + } + } + + // take care to multiply with the right factor to account for the mapping to + // normalised range [-1, 1] + return halfrange * sum; +} + +// Clad does not like std::max and std::min so redefined here for simplicity. +inline double max(double x, double y) +{ + return x >= y ? x : y; +} + +inline double min(double x, double y) +{ + return x <= y ? x : y; +} + +// The last param should be of type bool but it is not as that causes some issues with Cling for some reason... +inline double +poissonIntegral(int code, double mu, double x, double integrandMin, double integrandMax, unsigned int protectNegative) +{ + if (protectNegative && mu < 0.0) { + return std::exp(-2.0 * mu); // make it fall quickly + } + + if (code == 1) { + // Implement integral over x as summation. Add special handling in case + // range boundaries are not on integer values of x + integrandMin = max(0, integrandMin); + + if (integrandMax < 0. || integrandMax < integrandMin) { + return 0; + } + const double delta = 100.0 * std::sqrt(mu); + // If the limits are more than many standard deviations away from the mean, + // we might as well return the integral of the full Poisson distribution to + // save computing time. + if (integrandMin < max(mu - delta, 0.0) && integrandMax > mu + delta) { + return 1.; + } + + // The range as integers. ixMin is included, ixMax outside. + const unsigned int ixMin = integrandMin; + const unsigned int ixMax = min(integrandMax + 1, (double)std::numeric_limits::max()); + + // Sum from 0 to just before the bin outside of the range. + if (ixMin == 0) { + return ROOT::Math::gamma_cdf_c(mu, ixMax, 1); + } else { + // If necessary, subtract from 0 to the beginning of the range + if (ixMin <= mu) { + return ROOT::Math::gamma_cdf_c(mu, ixMax, 1) - ROOT::Math::gamma_cdf_c(mu, ixMin, 1); + } else { + // Avoid catastrophic cancellation in the high tails: + return ROOT::Math::gamma_cdf(mu, ixMin, 1) - ROOT::Math::gamma_cdf(mu, ixMax, 1); + } + } + } + + // the integral with respect to the mean is the integral of a gamma distribution + // negative ix does not need protection (gamma returns 0.0) + const double ix = 1 + x; + + return ROOT::Math::gamma_cdf(integrandMax, ix, 1.0) - ROOT::Math::gamma_cdf(integrandMin, ix, 1.0); +} + +inline double logNormalIntegral(double xMin, double xMax, double m0, double k) +{ + const double root2 = std::sqrt(2.); + + double ln_k = TMath::Abs(std::log(k)); + double ret = + 0.5 * (TMath::Erf(std::log(xMax / m0) / (root2 * ln_k)) - TMath::Erf(std::log(xMin / m0) / (root2 * ln_k))); + + return ret; +} + +inline double logNormalIntegralStandard(double xMin, double xMax, double mu, double sigma) +{ + const double root2 = std::sqrt(2.); + + double ln_k = std::abs(sigma); + double ret = + 0.5 * (TMath::Erf((std::log(xMax) - mu) / (root2 * ln_k)) - TMath::Erf((std::log(xMin) - mu) / (root2 * ln_k))); + + return ret; +} + +} // namespace AnalyticalIntegrals + +} // namespace Detail + +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/Detail/CodeSquashContext.h b/roofit/roofitcore/inc/RooFit/Detail/CodeSquashContext.h new file mode 100644 index 0000000000000..d6683e43b358f --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Detail/CodeSquashContext.h @@ -0,0 +1,182 @@ +/* + * Project: RooFit + * Authors: + * Garima Singh, CERN 2023 + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_CodeSquashContext_h +#define RooFit_Detail_CodeSquashContext_h + +#include +#include +#include + +#include +#include +#include +#include +#include + +template +class RooTemplateProxy; + +class TString; + +namespace RooFit { + +namespace Detail { + +/// @brief A class to maintain the context for squashing of RooFit models into code. +class CodeSquashContext { +public: + CodeSquashContext(std::map const &outputSizes) : _nodeOutputSizes(outputSizes) + { + } + + void addResult(RooAbsArg const *key, std::string const &value); + void addResult(const char *key, std::string const &value); + + std::string const &getResult(RooAbsArg const &arg); + + template + std::string const &getResult(RooTemplateProxy const &key) + { + return getResult(key.arg()); + } + + /// @brief Figure out the output size of a node. It is the size of the + /// vector observable that it depends on, or 1 if it doesn't depend on any + /// or is a reducer node. + /// @param key The node to look up the size for. + std::size_t outputSize(RooFit::Detail::DataKey key) const + { + auto found = _nodeOutputSizes.find(key); + if (found != _nodeOutputSizes.end()) + return found->second; + return 1; + } + + void addToGlobalScope(std::string const &str); + std::string assembleCode(std::string const &returnExpr); + void addVecObs(const char *key, int idx); + + void addToCodeBody(RooAbsArg const *klass, std::string const &in); + + void addToCodeBody(std::string const &in, bool isScopeIndep = false); + + /// @brief Build the code to call the function with name `funcname`, passing some arguments. + /// The arguments can either be doubles or some RooFit arguments whose + /// results will be looked up in the context. + template + std::string buildCall(std::string const &funcname, Args_t const &...args) + { + std::stringstream ss; + ss << funcname << "(" << buildArgs(args...) << ")"; + return ss.str(); + } + + /// @brief A class to manage loop scopes using the RAII technique. To wrap your code around a loop, + /// simply place it between a brace inclosed scope with a call to beginLoop at the top. For e.g. + /// { + /// auto scope = ctx.beginLoop({<-set of vector observables to loop over->}); + /// // your loop body code goes here. + /// } + class LoopScope { + public: + LoopScope(CodeSquashContext &ctx, std::vector &&vars) : _ctx{ctx}, _vars{vars} {} + ~LoopScope() { _ctx.endLoop(*this); } + + std::vector const &vars() const { return _vars; } + + private: + CodeSquashContext &_ctx; + const std::vector _vars; + }; + + std::unique_ptr beginLoop(RooAbsArg const *in); + + std::string getTmpVarName(); + std::string makeValidVarName(TString in) const; + + std::string buildArg(RooAbsCollection const &x); + std::string buildArg(std::span arr); + +private: + bool isScopeIndependent(RooAbsArg const *in) const; + + void endLoop(LoopScope const &scope); + + void addResult(TNamed const *key, std::string const &value); + + template {}, bool>::type = true> + std::string buildArg(T x) + { + return RooNumber::toString(x); + } + + // If input is integer, we want to print it into the code like one (i.e. avoid the unnecessary '.0000'). + template {}, bool>::type = true> + std::string buildArg(T x) + { + return std::to_string(x); + } + + std::string buildArg(std::string const &x) { return x; } + + std::string buildArg(RooAbsArg const &arg) { return getResult(arg); } + + template + std::string buildArg(RooTemplateProxy const &arg) + { + return getResult(arg); + } + + std::string buildArgs() { return ""; } + + template + std::string buildArgs(Arg_t const &arg) + { + return buildArg(arg); + } + + template + std::string buildArgs(Arg_t const &arg, Args_t const &...args) + { + return buildArg(arg) + ", " + buildArgs(args...); + } + + /// @brief Map of node names to their result strings. + std::unordered_map _nodeNames; + /// @brief Block of code that is placed before the rest of the function body. + std::string _globalScope; + /// @brief A map to keep track of the observable indices if they are non scalar. + std::unordered_map _vecObsIndices; + /// @brief Map of node output sizes. + std::map _nodeOutputSizes; + /// @brief Stores the squashed code body. + std::string _code; + /// @brief The current number of for loops the started. + int _loopLevel = 0; + /// @brief Index to get unique names for temporary variables. + int _tmpVarIdx = 0; + /// @brief Keeps track of the position to go back and insert code to. + int _scopePtr = -1; + /// @brief Stores code that eventually gets injected into main code body. + /// Mainly used for placing decls outside of loops. + std::string _tempScope; + /// @brief A map to keep track of list names as assigned by addResult. + std::unordered_map::Value_t, std::string> listNames; +}; + +} // namespace Detail + +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/Detail/DataMap.h b/roofit/roofitcore/inc/RooFit/Detail/DataMap.h index 835e6a1156fc1..007431e4726e4 100644 --- a/roofit/roofitcore/inc/RooFit/Detail/DataMap.h +++ b/roofit/roofitcore/inc/RooFit/Detail/DataMap.h @@ -14,7 +14,8 @@ #define RooFit_Detail_DataMap_h #include -#include + +#include #include #include @@ -26,6 +27,10 @@ template class RooTemplateProxy; +namespace RooBatchCompute { +class Config; +} + /// \class RooFit::DataKey /// To use as a key type for RooFit data maps and containers. A RooFit::DataKey /// can be constructed with no runtime overhead from a RooAbsArg (or any @@ -77,39 +82,46 @@ namespace Detail { class DataMap { public: - auto empty() const { return _dataMap.empty(); } - auto begin() { return _dataMap.begin(); } - auto end() { return _dataMap.end(); } - auto begin() const { return _dataMap.begin(); } - auto end() const { return _dataMap.end(); } - auto size() const { return _dataMap.size(); } - auto resize(std::size_t n) { return _dataMap.resize(n); } - - inline auto &at(RooAbsArg const *arg, RooAbsArg const * /*caller*/ = nullptr) + auto size() const + { + return _dataMap.size(); + } + void resize(std::size_t n); + + inline void set(RooAbsArg const *arg, std::span const &span) { + if (!arg->hasDataToken()) + return; std::size_t idx = arg->dataToken(); - return _dataMap[idx]; + _dataMap[idx] = span; } - inline auto &at(RooAbsArg const *arg, RooAbsArg const *caller = nullptr) const + void setConfig(RooAbsArg const *arg, RooBatchCompute::Config const &config); + + std::span at(RooAbsArg const *arg, RooAbsArg const *caller = nullptr); + + inline std::span at(RooAbsArg const *arg, RooAbsArg const *caller = nullptr) const { return const_cast(this)->at(arg, caller); } template - inline auto &at(RooTemplateProxy const &proxy) + inline std::span at(RooTemplateProxy const &proxy) { return at(&proxy.arg(), proxy.owner()); } template - inline auto &at(RooTemplateProxy const &proxy) const + inline std::span at(RooTemplateProxy const &proxy) const { return at(&proxy.arg(), proxy.owner()); } + RooBatchCompute::Config config(RooAbsArg const *arg) const; + private: - std::vector> _dataMap; + std::vector> _dataMap; + std::vector _cfgs; }; } // namespace Detail diff --git a/roofit/roofitcore/inc/RooFit/Detail/EvaluateFuncs.h b/roofit/roofitcore/inc/RooFit/Detail/EvaluateFuncs.h new file mode 100644 index 0000000000000..2d52e1602cb39 --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Detail/EvaluateFuncs.h @@ -0,0 +1,238 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * Garima Singh, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_EvaluateFuncs_h +#define RooFit_Detail_EvaluateFuncs_h + +#include +#include + +#include + +namespace RooFit { + +namespace Detail { + +namespace EvaluateFuncs { + +/// @brief Function to evaluate an un-normalized RooGaussian. +inline double gaussianEvaluate(double x, double mean, double sigma) +{ + const double arg = x - mean; + const double sig = sigma; + return std::exp(-0.5 * arg * arg / (sig * sig)); +} + +/// In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0. +template +inline double polynomialEvaluate(double const *coeffs, int nCoeffs, int lowestOrder, double x) +{ + double retVal = coeffs[nCoeffs - 1]; + for (int i = nCoeffs - 2; i >= 0; i--) + retVal = coeffs[i] + x * retVal; + retVal = retVal * std::pow(x, lowestOrder); + return retVal + (pdfMode && lowestOrder > 0 ? 1.0 : 0.0); +} + +inline double chebychevEvaluate(double *coeffs, unsigned int nCoeffs, double x_in, double xMin, double xMax) +{ + // transform to range [-1, +1] + const double xPrime = (x_in - 0.5 * (xMax + xMin)) / (0.5 * (xMax - xMin)); + + // extract current values of coefficients + double sum = 1.; + if (nCoeffs > 0) { + double curr = xPrime; + double twox = 2 * xPrime; + double last = 1; + double newval = twox * curr - last; + last = curr; + curr = newval; + for (unsigned int i = 0; nCoeffs != i; ++i) { + sum += last * coeffs[i]; + newval = twox * curr - last; + last = curr; + curr = newval; + } + } + return sum; +} + +inline double constraintSumEvaluate(double const *comp, unsigned int compSize) +{ + double sum = 0; + for (unsigned int i = 0; i < compSize; i++) { + sum -= std::log(comp[i]); + } + return sum; +} + +inline unsigned int getUniformBinning(double low, double high, double val, unsigned int numBins) +{ + double binWidth = (high - low) / numBins; + return val >= high ? numBins - 1 : std::abs((val - low) / binWidth); +} + +inline double poissonEvaluate(double x, double par) +{ + if (par < 0) + return TMath::QuietNaN(); + + if (x < 0) + return 0; + else if (x == 0.0) + return std::exp(-par); + else { + double out = x * std::log(par) - TMath::LnGamma(x + 1.) - par; + return std::exp(out); + } +} + +inline double interpolate6thDegree(double x, double low, double high, double nominal, double boundary) +{ + double t = x / boundary; + double eps_plus = high - nominal; + double eps_minus = nominal - low; + double S = 0.5 * (eps_plus + eps_minus); + double A = 0.0625 * (eps_plus - eps_minus); + + return x * (S + t * A * (15 + t * t * (-10 + t * t * 3))); +} + +inline double flexibleInterp(unsigned int code, double low, double high, double boundary, double nominal, + double paramVal, double total) +{ + if (code == 0) { + // piece-wise linear + if (paramVal > 0) + return total + paramVal * (high - nominal); + else + return total + paramVal * (nominal - low); + } else if (code == 1) { + // piece-wise log + if (paramVal >= 0) + return total * std::pow(high / nominal, +paramVal); + else + return total * std::pow(low / nominal, -paramVal); + } else if (code == 2) { + // parabolic with linear + double a = 0.5 * (high + low) - nominal; + double b = 0.5 * (high - low); + double c = 0; + if (paramVal > 1) { + return total + (2 * a + b) * (paramVal - 1) + high - nominal; + } else if (paramVal < -1) { + return total + -1 * (2 * a - b) * (paramVal + 1) + low - nominal; + } else { + return total + a * std::pow(paramVal, 2) + b * paramVal + c; + } + } else if (code == 3) { + // parabolic version of log-normal + double a = 0.5 * (high + low) - nominal; + double b = 0.5 * (high - low); + double c = 0; + if (paramVal > 1) { + return total + (2 * a + b) * (paramVal - 1) + high - nominal; + } else if (paramVal < -1) { + return total + -1 * (2 * a - b) * (paramVal + 1) + low - nominal; + } else { + return total + a * std::pow(paramVal, 2) + b * paramVal + c; + } + } else if (code == 4) { + double x = paramVal; + if (x >= boundary) { + return total * std::pow(high / nominal, +paramVal); + } else if (x <= -boundary) { + return total * std::pow(low / nominal, -paramVal); + } + + return total * std::exp(interpolate6thDegree(x, std::log(low), std::log(high), std::log(nominal), boundary)); + } + + return total; +} + +inline double +piecewiseInterpolation(unsigned int code, double low, double high, double nominal, double param, double sum) +{ + if (code == 4) { + + // WVE **************************************************************** + // WVE *** THIS CODE IS CRITICAL TO HISTFACTORY FIT CPU PERFORMANCE *** + // WVE *** Do not modify unless you know what you are doing... *** + // WVE **************************************************************** + + double x = param; + if (x > 1.0) { + return sum + x * (high - nominal); + } else if (x < -1.0) { + return sum + x * (nominal - low); + } else { + // fcns+der+2nd_der are eq at bd + double val = nominal + interpolate6thDegree(x, low, high, nominal, 1.0); + + if (val < 0) + val = 0; + return sum + val - nominal; + } + // WVE **************************************************************** + } else { + + double x0 = 1.0; // boundary; + double x = param; + + if (x > x0 || x < -x0) { + if (x > 0) + return sum + x * (high - nominal); + else + return sum + x * (nominal - low); + } else if (nominal != 0) { + double eps_plus = high - nominal; + double eps_minus = nominal - low; + double S = (eps_plus + eps_minus) / 2; + double A = (eps_plus - eps_minus) / 2; + + // fcns+der are eq at bd + double a = S; + double b = 3 * A / (2 * x0); + // double c = 0; + double d = -A / (2 * x0 * x0 * x0); + + double val = nominal + a * x + b * std::pow(x, 2) + 0 /*c*pow(x, 3)*/ + d * std::pow(x, 4); + if (val < 0) + val = 0; + + return sum + val - nominal; + } + } + + return sum; +} + +inline double logNormalEvaluate(double x, double k, double m0) +{ + return ROOT::Math::lognormal_pdf(x, std::log(m0), std::abs(std::log(k))); +} + +inline double logNormalEvaluateStandard(double x, double sigma, double mu) +{ + return ROOT::Math::lognormal_pdf(x, mu, std::abs(sigma)); +} + +} // namespace EvaluateFuncs + +} // namespace Detail + +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/Detail/NormalizationHelpers.h b/roofit/roofitcore/inc/RooFit/Detail/NormalizationHelpers.h new file mode 100644 index 0000000000000..c66954d0f0549 --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Detail/NormalizationHelpers.h @@ -0,0 +1,81 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2022 + * + * Copyright (c) 2022, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_NormalizationHelpers_h +#define RooFit_Detail_NormalizationHelpers_h + +#include +#include +#include + +class RooAbsArg; +class RooArgSet; + +class TNamed; + +namespace RooFit { + +namespace Detail { + +class CompileContext { +public: + CompileContext(RooArgSet const &topLevelNormSet); + + ~CompileContext(); + + template + T *compile(T &arg, RooAbsArg &owner, RooArgSet const &normSet) + { + return static_cast(compileImpl(arg, owner, normSet)); + } + + void compileServers(RooAbsArg &arg, RooArgSet const &normSet); + void compileServer(RooAbsArg &server, RooAbsArg &arg, RooArgSet const &normSet); + + void markAsCompiled(RooAbsArg &arg) const; + + // This information is used for the binned likelihood optimization. + void setLikelihoodMode(bool flag) { _likelihoodMode = flag; } + bool likelihoodMode() const { return _likelihoodMode; } + void setBinnedLikelihoodMode(bool flag) { _binnedLikelihoodMode = flag; } + bool binnedLikelihoodMode() const { return _binnedLikelihoodMode; } + void setBinWidthFuncFlag(bool flag) { _binWidthFuncFlag = flag; } + bool binWidthFuncFlag() const { return _binWidthFuncFlag; } + +private: + RooAbsArg *compileImpl(RooAbsArg &arg, RooAbsArg &owner, RooArgSet const &normSet); + void add(RooAbsArg &arg); + RooAbsArg *find(RooAbsArg &arg) const; + bool isMarkedAsCompiled(RooAbsArg const &arg) const; + + RooArgSet const &_topLevelNormSet; + std::unordered_map _clonedArgsSet; + std::unordered_map _replacements; + + bool _likelihoodMode = false; + bool _binnedLikelihoodMode = false; + bool _binWidthFuncFlag = false; +}; + +template +std::unique_ptr compileForNormSet(T const &arg, RooArgSet const &normSet) +{ + RooFit::Detail::CompileContext ctx{normSet}; + std::unique_ptr head = arg.compileForNormSet(normSet, ctx); + return std::unique_ptr{static_cast(head.release())}; +} + +} // namespace Detail + +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/Evaluator.h b/roofit/roofitcore/inc/RooFit/Evaluator.h new file mode 100644 index 0000000000000..1c2fa65252aac --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/Evaluator.h @@ -0,0 +1,77 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2021 + * Emmanouil Michalainas, CERN 2021 + * + * Copyright (c) 2021, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Evaluator_h +#define RooFit_Evaluator_h + +#include +#include + +#include + +#include +#include + +class RooAbsArg; + +namespace RooFit { + +namespace Detail { +class BufferManager; +} + +struct NodeInfo; + +namespace Detail { +class BufferManager; +} + +class Evaluator { +public: + Evaluator(const RooAbsReal &absReal, bool useGPU=false); + ~Evaluator(); + + std::span run(); + void setInput(std::string const &name, std::span inputArray, bool isOnDevice); + RooArgSet getParameters() const; + void print(std::ostream &os) const; + +private: + void processVariable(NodeInfo &nodeInfo); + void setClientsDirty(NodeInfo &nodeInfo); +#ifdef R__HAS_CUDA + std::span getValHeterogeneous(); + void markGPUNodes(); + void assignToGPU(NodeInfo &info); +#endif + void computeCPUNode(const RooAbsArg *node, NodeInfo &info); + void setOperMode(RooAbsArg *arg, RooAbsArg::OperMode opMode); + void syncDataTokens(); + void updateOutputSizes(); + + std::unique_ptr _bufferManager; + RooAbsReal &_topNode; + const bool _useGPU = false; + int _nEvaluations = 0; + bool _needToUpdateOutputSizes = false; + RooFit::Detail::DataMap _dataMapCPU; +#ifdef R__HAS_CUDA + RooFit::Detail::DataMap _dataMapCUDA; +#endif + std::vector _nodes; // the ordered computation graph + std::stack _changeOperModeRAIIs; // for resetting state of computation graph +}; + +} // end namespace RooFit + +#endif diff --git a/roofit/roofitcore/inc/RooFit/ModelConfig.h b/roofit/roofitcore/inc/RooFit/ModelConfig.h new file mode 100644 index 0000000000000..b7cae5f7e58ce --- /dev/null +++ b/roofit/roofitcore/inc/RooFit/ModelConfig.h @@ -0,0 +1,376 @@ +/* + * Project: RooFit + * Authors: + * Kyle Cranmer, + * Lorenzo Moneta, + * Gregory Schott, + * Wouter Verkerke, + * Sven Kreiss + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_ModelConfig_h +#define RooFit_ModelConfig_h + +#include +#include +#include +#include +#include + +#include + +#include + +class RooFitResult; + +// ModelConfig kept in the RooStats namespace for backwards compatibility. +namespace RooStats { + +class ModelConfig final : public TNamed, public RooWorkspaceHandle { + +public: + ModelConfig(RooWorkspace *ws = nullptr) : TNamed() + { + if (ws) + SetWS(*ws); + } + + ModelConfig(const char *name, RooWorkspace *ws = nullptr) : TNamed(name, name) + { + if (ws) + SetWS(*ws); + } + + ModelConfig(const char *name, const char *title, RooWorkspace *ws = nullptr) : TNamed(name, title) + { + if (ws) + SetWS(*ws); + } + + /// clone + ModelConfig *Clone(const char *name = "") const override + { + ModelConfig *mc = new ModelConfig(*this); + if (strcmp(name, "") == 0) + mc->SetName(this->GetName()); + else + mc->SetName(name); + return mc; + } + + /// Set a workspace that owns all the necessary components for the analysis. + void SetWS(RooWorkspace &ws) override; + //// alias for SetWS(...) + virtual void SetWorkspace(RooWorkspace &ws) { SetWS(ws); } + + /// Remove the existing reference to a workspace and replace it with this new one. + void ReplaceWS(RooWorkspace *ws) override + { + fRefWS = nullptr; + SetWS(*ws); + } + + /// Set the proto DataSet, add to the workspace if not already there + virtual void SetProtoData(RooAbsData &data) + { + ImportDataInWS(data); + SetProtoData(data.GetName()); + } + + /// Set the Pdf, add to the workspace if not already there + virtual void SetPdf(const RooAbsPdf &pdf) + { + ImportPdfInWS(pdf); + SetPdf(pdf.GetName()); + } + + /// Set the Prior Pdf, add to the workspace if not already there + virtual void SetPriorPdf(const RooAbsPdf &pdf) + { + ImportPdfInWS(pdf); + SetPriorPdf(pdf.GetName()); + } + + /// Specify parameters of the PDF. + virtual void SetParameters(const RooArgSet &set) + { + if (!SetHasOnlyParameters(set, "ModelConfig::SetParameters")) + return; + fPOIName = std::string(GetName()) + "_POI"; + DefineSetInWS(fPOIName.c_str(), set); + } + + /// Specify parameters of interest. + virtual void SetParametersOfInterest(const RooArgSet &set) + { + if (!SetHasOnlyParameters(set, "ModelConfig::SetParametersOfInterest")) + return; + SetParameters(set); + } + + /// Specify parameters + /// using a list of comma-separated list of arguments already in the workspace. + virtual void SetParameters(const char *argList) + { + if (!GetWS()) + return; + SetParameters(GetWS()->argSet(argList)); + } + + /// Specify parameters of interest + /// using a comma-separated list of arguments already in the workspace. + virtual void SetParametersOfInterest(const char *argList) { SetParameters(argList); } + + /// Specify the nuisance parameters (parameters that are not POI). + virtual void SetNuisanceParameters(const RooArgSet &set) + { + if (!SetHasOnlyParameters(set, "ModelConfig::SetNuisanceParameters")) + return; + fNuisParamsName = std::string(GetName()) + "_NuisParams"; + DefineSetInWS(fNuisParamsName.c_str(), set); + } + + /// Specify the nuisance parameters + /// using a comma-separated list of arguments already in the workspace. + virtual void SetNuisanceParameters(const char *argList) + { + if (!GetWS()) + return; + SetNuisanceParameters(GetWS()->argSet(argList)); + } + + /// Specify the constraint parameters + virtual void SetConstraintParameters(const RooArgSet &set) + { + if (!SetHasOnlyParameters(set, "ModelConfig::SetConstrainedParameters")) + return; + fConstrParamsName = std::string(GetName()) + "_ConstrainedParams"; + DefineSetInWS(fConstrParamsName.c_str(), set); + } + /// Specify the constraint parameters + /// through a comma-separated list of arguments already in the workspace. + virtual void SetConstraintParameters(const char *argList) + { + if (!GetWS()) + return; + SetConstraintParameters(GetWS()->argSet(argList)); + } + + /// Specify the observables. + virtual void SetObservables(const RooArgSet &set) + { + if (!SetHasOnlyParameters(set, "ModelConfig::SetObservables")) + return; + fObservablesName = std::string(GetName()) + "_Observables"; + DefineSetInWS(fObservablesName.c_str(), set); + } + /// specify the observables + /// through a comma-separated list of arguments already in the workspace. + virtual void SetObservables(const char *argList) + { + if (!GetWS()) + return; + SetObservables(GetWS()->argSet(argList)); + } + + virtual void SetConditionalObservables(const RooArgSet &set); + /// Specify the conditional observables + /// through a comma-separated list of arguments already in the workspace. + virtual void SetConditionalObservables(const char *argList) + { + if (!GetWS()) + return; + SetConditionalObservables(GetWS()->argSet(argList)); + } + + virtual void SetGlobalObservables(const RooArgSet &set); + /// Specify the global observables + /// through a comma-separated list of arguments already in the workspace. + virtual void SetGlobalObservables(const char *argList) + { + if (!GetWS()) + return; + SetGlobalObservables(GetWS()->argSet(argList)); + } + + void SetExternalConstraints(const RooArgSet &set); + /// Specify the external constraints + /// through a comma-separated list of arguments already in the workspace. + virtual void SetExternalConstraints(const char *argList) + { + if (!GetWS()) + return; + SetExternalConstraints(GetWS()->argSet(argList)); + } + + /// Set parameter values for a particular hypothesis if using a common PDF + /// by saving a snapshot in the workspace. + virtual void SetSnapshot(const RooArgSet &set); + + /// Specify the name of the PDF in the workspace to be used. + virtual void SetPdf(const char *name) + { + if (!GetWS()) + return; + + if (GetWS()->pdf(name)) + fPdfName = name; + else { + std::stringstream ss; + ss << "pdf " << name << " does not exist in workspace"; + const std::string errorMsg = ss.str(); + coutE(ObjectHandling) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); + } + } + + /// Specify the name of the PDF in the workspace to be used. + virtual void SetPriorPdf(const char *name) + { + if (!GetWS()) + return; + + if (GetWS()->pdf(name)) + fPriorPdfName = name; + else { + std::stringstream ss; + ss << "pdf " << name << " does not exist in workspace"; + const std::string errorMsg = ss.str(); + coutE(ObjectHandling) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); + } + } + + /// Specify the name of the dataset in the workspace to be used. + virtual void SetProtoData(const char *name) + { + if (!GetWS()) + return; + + if (GetWS()->data(name)) + fProtoDataName = name; + else { + std::stringstream ss; + ss << "dataset " << name << " does not exist in workspace"; + const std::string errorMsg = ss.str(); + coutE(ObjectHandling) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); + } + } + + /* getter methods */ + + /// get model PDF (return nullptr if pdf has not been specified or does not exist) + RooAbsPdf *GetPdf() const { return (GetWS()) ? GetWS()->pdf(fPdfName) : nullptr; } + + /// get RooArgSet containing the parameter of interest (return nullptr if not existing) + const RooArgSet *GetParametersOfInterest() const { return (GetWS()) ? GetWS()->set(fPOIName) : nullptr; } + + /// get RooArgSet containing the nuisance parameters (return nullptr if not existing) + const RooArgSet *GetNuisanceParameters() const { return (GetWS()) ? GetWS()->set(fNuisParamsName) : nullptr; } + + /// get RooArgSet containing the constraint parameters (return nullptr if not existing) + const RooArgSet *GetConstraintParameters() const { return (GetWS()) ? GetWS()->set(fConstrParamsName) : nullptr; } + + /// get parameters prior pdf (return nullptr if not existing) + RooAbsPdf *GetPriorPdf() const { return (GetWS()) ? GetWS()->pdf(fPriorPdfName) : nullptr; } + + /// get RooArgSet for observables (return nullptr if not existing) + const RooArgSet *GetObservables() const { return (GetWS()) ? GetWS()->set(fObservablesName) : nullptr; } + + /// get RooArgSet for conditional observables (return nullptr if not existing) + const RooArgSet *GetConditionalObservables() const + { + return (GetWS()) ? GetWS()->set(fConditionalObsName) : nullptr; + } + + /// get RooArgSet for global observables (return nullptr if not existing) + const RooArgSet *GetGlobalObservables() const { return (GetWS()) ? GetWS()->set(fGlobalObsName) : nullptr; } + + /// get RooArgSet for global observables (return nullptr if not existing) + const RooArgSet *GetExternalConstraints() const { return (GetWS()) ? GetWS()->set(fExtConstraintsName) : nullptr; } + + /// get Proto data set (return nullptr if not existing) + RooAbsData *GetProtoData() const { return (GetWS()) ? GetWS()->data(fProtoDataName) : nullptr; } + + /// get RooArgSet for parameters for a particular hypothesis (return nullptr if not existing) + const RooArgSet *GetSnapshot() const; + + void LoadSnapshot() const; + + RooWorkspace *GetWS() const override; + /// alias for GetWS() + RooWorkspace *GetWorkspace() const { return GetWS(); } + + void GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig = true); + + /// overload the print method + void Print(Option_t *option = "") const override; + + template + std::unique_ptr createNLL(RooAbsData &data, CmdArgs_t const &...cmdArgs) const + { + return createNLLImpl(data, *RooFit::Detail::createCmdList(&cmdArgs...)); + } + + template + std::unique_ptr fitTo(RooAbsData &data, CmdArgs_t const &...cmdArgs) + { + return fitToImpl(data, *RooFit::Detail::createCmdList(&cmdArgs...)); + } + +protected: + /// helper function to check that content of a given set is exclusively parameters + bool SetHasOnlyParameters(const RooArgSet &set, const char *errorMsgPrefix = nullptr); + + /// helper functions to define a set in the WS + void DefineSetInWS(const char *name, const RooArgSet &set); + + /// internal function to import Pdf in WS + void ImportPdfInWS(const RooAbsPdf &pdf); + + /// internal function to import data in WS + void ImportDataInWS(RooAbsData &data); + + TRef fRefWS; ///< WS reference used in the file + + std::string fWSName; ///< name of the WS + + std::string fPdfName; ///< name of PDF in workspace + std::string fDataName; ///< name of data set in workspace + std::string fPOIName; ///< name for RooArgSet specifying parameters of interest + + std::string fNuisParamsName; ///< name for RooArgSet specifying nuisance parameters + std::string fConstrParamsName; ///< name for RooArgSet specifying constrained parameters + std::string fPriorPdfName; ///< name for RooAbsPdf specifying a prior on the parameters + + std::string fConditionalObsName; ///< name for RooArgSet specifying conditional observables + std::string fGlobalObsName; ///< name for RooArgSet specifying global observables + std::string fExtConstraintsName; ///< name for RooArgSet specifying external constraints + std::string fProtoDataName; ///< name for RooArgSet specifying dataset that should be used as proto-data + + std::string fSnapshotName; ///< name for RooArgSet that specifies a particular hypothesis + + std::string fObservablesName; ///< name for RooArgSet specifying observable parameters. + +private: + std::unique_ptr createNLLImpl(RooAbsData &data, const RooLinkedList &cmdList) const; + std::unique_ptr fitToImpl(RooAbsData &data, const RooLinkedList &cmdList); + + ClassDefOverride(ModelConfig, + 6); ///< A class that holds configuration information for a model using a workspace as a store +}; + +} // end namespace RooStats + +namespace RooFit { +using ModelConfig = RooStats::ModelConfig; +} + +#endif diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/LikelihoodWrapper.h b/roofit/roofitcore/inc/RooFit/TestStatistics/LikelihoodWrapper.h index 53d56c925ce83..9808fc707b263 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/LikelihoodWrapper.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/LikelihoodWrapper.h @@ -17,7 +17,8 @@ #include "RooAbsArg.h" // enum ConstOpCode #include -#include "Math/MinimizerOptions.h" +#include +#include #include // shared_ptr #include @@ -103,7 +104,7 @@ class LikelihoodWrapper { bool do_offset_ = false; ROOT::Math::KahanSum offset_; - ROOT::Math::KahanSum offset_save_ = 0; /// offset_save_ {0.}; /// applyOffsetting(ROOT::Math::KahanSum current_value); void swapOffsets(); diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/RooAbsL.h b/roofit/roofitcore/inc/RooFit/TestStatistics/RooAbsL.h index a59e6c3ae170a..819d06b43816a 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/RooAbsL.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/RooAbsL.h @@ -36,9 +36,16 @@ class RooAbsL { static bool isExtendedHelper(RooAbsPdf *pdf, Extended extended); /// Convenience wrapper class used to distinguish between pdf/data owning and non-owning constructors. - struct ClonePdfData { - RooAbsPdf *pdf; - RooAbsData *data; + class ClonePdfData { + public: + ClonePdfData(RooAbsPdf *inPdf, RooAbsData *inData) : pdf{inPdf}, data{inData} {} + ClonePdfData(std::unique_ptr inPdf, RooAbsData *inData) + : pdf{inPdf.get()}, data{inData}, ownedPdf{std::move(inPdf)} + { + } + RooAbsPdf *pdf = nullptr; + RooAbsData *data = nullptr; + std::shared_ptr ownedPdf; }; private: @@ -74,8 +81,9 @@ class RooAbsL { } } - bool operator==(const Section& rhs) { - return begin_fraction == rhs.begin_fraction && end_fraction == rhs.end_fraction; + friend bool operator==(const Section &lhs, const Section &rhs) + { + return lhs.begin_fraction == rhs.begin_fraction && lhs.end_fraction == rhs.end_fraction; } double begin_fraction; @@ -99,7 +107,7 @@ class RooAbsL { evaluatePartition(Section events, std::size_t components_begin, std::size_t components_end) = 0; // necessary from MinuitFcnGrad to reach likelihood properties: - virtual RooArgSet *getParameters(); + virtual std::unique_ptr getParameters(); /// \brief Interface function signaling a request to perform constant term optimization. /// diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/RooBinnedL.h b/roofit/roofitcore/inc/RooFit/TestStatistics/RooBinnedL.h index 639617c90a601..9e754494e6126 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/RooBinnedL.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/RooBinnedL.h @@ -31,18 +31,18 @@ namespace TestStatistics { class RooBinnedL : public RooAbsL { public: RooBinnedL(RooAbsPdf *pdf, RooAbsData *data); - ~RooBinnedL(); + ~RooBinnedL() override; ROOT::Math::KahanSum evaluatePartition(Section bins, std::size_t components_begin, std::size_t components_end) override; - virtual std::string GetClassName() const override { return "RooBinnedL"; }; + std::string GetClassName() const override { return "RooBinnedL"; } private: mutable bool _first = true; /// _binw; /// paramTracker_; - Section lastSection_ = {0, 0}; // used for cache together with the parameter tracker - mutable ROOT::Math::KahanSum cachedResult_ = 0; + Section lastSection_ = {0, 0}; // used for cache together with the parameter tracker + mutable ROOT::Math::KahanSum cachedResult_{0.}; }; } // namespace TestStatistics diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/RooSubsidiaryL.h b/roofit/roofitcore/inc/RooFit/TestStatistics/RooSubsidiaryL.h index 76f822c241cf3..44c663ca33c12 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/RooSubsidiaryL.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/RooSubsidiaryL.h @@ -28,7 +28,7 @@ class RooSubsidiaryL : public RooAbsL { ROOT::Math::KahanSum evaluatePartition(Section events, std::size_t components_begin, std::size_t components_end) override; - inline RooArgSet *getParameters() override { return ¶meter_set_; } + inline std::unique_ptr getParameters() override { return std::make_unique(parameter_set_); } inline std::string GetName() const override { return std::string("subsidiary_pdf_of_") + parent_pdf_name_; } inline std::string GetTitle() const override @@ -36,9 +36,9 @@ class RooSubsidiaryL : public RooAbsL { return std::string("Subsidiary PDF set of simultaneous PDF ") + parent_pdf_name_; } - virtual std::string GetInfo() const override { return GetClassName() + "::" + parent_pdf_name_; } + std::string GetInfo() const override { return GetClassName() + "::" + parent_pdf_name_; } - virtual std::string GetClassName() const override { return "RooSubsidiaryL"; }; + std::string GetClassName() const override { return "RooSubsidiaryL"; } inline std::size_t numDataEntries() const override { diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/RooSumL.h b/roofit/roofitcore/inc/RooFit/TestStatistics/RooSumL.h index d40913df3dff3..cb70523ac2d52 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/RooSumL.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/RooSumL.h @@ -14,7 +14,6 @@ #define ROOT_ROOFIT_TESTSTATISTICS_RooSumL #include -#include #include "Math/Util.h" // KahanSum @@ -38,9 +37,9 @@ class RooSumL : public RooAbsL { void constOptimizeTestStatistic(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) override; - virtual std::string GetClassName() const override { return "RooSumL"; }; + std::string GetClassName() const override { return "RooSumL"; } - const std::vector>& GetComponents() const { return components_; }; + const std::vector> &GetComponents() const { return components_; }; private: std::vector> components_; diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/RooUnbinnedL.h b/roofit/roofitcore/inc/RooFit/TestStatistics/RooUnbinnedL.h index 73e490592bd3d..b8d3c708988d2 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/RooUnbinnedL.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/RooUnbinnedL.h @@ -14,6 +14,7 @@ #define ROOT_ROOFIT_TESTSTATISTICS_RooUnbinnedL #include +#include #include "Math/Util.h" // KahanSum @@ -21,36 +22,35 @@ class RooAbsPdf; class RooAbsData; class RooArgSet; -namespace RooBatchCompute { -struct RunContext; -} class RooChangeTracker; namespace RooFit { + +class Evaluator; + namespace TestStatistics { class RooUnbinnedL : public RooAbsL { public: RooUnbinnedL(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended extended = RooAbsL::Extended::Auto, - bool useBatchedEvaluations = false); + RooFit::EvalBackend evalBackend = RooFit::EvalBackend::Legacy()); RooUnbinnedL(const RooUnbinnedL &other); - ~RooUnbinnedL(); + ~RooUnbinnedL() override; bool setApplyWeightSquared(bool flag); ROOT::Math::KahanSum evaluatePartition(Section events, std::size_t components_begin, std::size_t components_end) override; - void setUseBatchedEvaluations(bool flag); - - virtual std::string GetClassName() const override { return "RooUnbinnedL"; }; + std::string GetClassName() const override { return "RooUnbinnedL"; } private: - bool apply_weight_squared = false; ///< Apply weights squared? - mutable bool _first = true; /// paramTracker_; - Section lastSection_ = {0, 0}; // used for cache together with the parameter tracker - mutable ROOT::Math::KahanSum cachedResult_ = 0; + Section lastSection_ = {0, 0}; // used for cache together with the parameter tracker + mutable ROOT::Math::KahanSum cachedResult_{0.}; + std::shared_ptr evaluator_; ///> _vectorBuffers; // used for preserving resources in batched evaluation }; } // namespace TestStatistics diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/buildLikelihood.h b/roofit/roofitcore/inc/RooFit/TestStatistics/buildLikelihood.h index 99adcbc519cc0..19d6aa4d93f63 100644 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/buildLikelihood.h +++ b/roofit/roofitcore/inc/RooFit/TestStatistics/buildLikelihood.h @@ -13,8 +13,8 @@ #ifndef ROOT_ROOFIT_TESTSTATISTICS_likelihood_builders #define ROOT_ROOFIT_TESTSTATISTICS_likelihood_builders +#include #include -#include #include @@ -25,21 +25,39 @@ class RooAbsData; namespace RooFit { namespace TestStatistics { -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended extended = RooAbsL::Extended::Auto, - ConstrainedParameters constrained_parameters = {}, ExternalConstraints external_constraints = {}, - GlobalObservables global_observables = {}, std::string global_observables_tag = {}); - -// delegating builder calls, for more convenient "optional" parameter passing -std::unique_ptr -buildLikelihood(RooAbsPdf* pdf, RooAbsData* data, ConstrainedParameters constrained_parameters); -std::unique_ptr buildLikelihood(RooAbsPdf* pdf, RooAbsData* data, ExternalConstraints external_constraints); -std::unique_ptr buildLikelihood(RooAbsPdf* pdf, RooAbsData* data, GlobalObservables global_observables); -std::unique_ptr buildLikelihood(RooAbsPdf* pdf, RooAbsData* data, std::string global_observables_tag); -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constrained_parameters, GlobalObservables global_observables); - -} +class NLLFactory { +public: + NLLFactory(RooAbsPdf &pdf, RooAbsData &data); + std::unique_ptr build(); + + NLLFactory &Extended(RooAbsL::Extended extended); + NLLFactory &ConstrainedParameters(const RooArgSet &constrainedParameters); + NLLFactory &ExternalConstraints(const RooArgSet &externalconstraints); + NLLFactory &GlobalObservables(const RooArgSet &globalObservables); + NLLFactory &GlobalObservablesTag(const char *globalObservablesTag); + NLLFactory &EvalBackend(RooFit::EvalBackend evalBackend); + +private: + std::vector> getSimultaneousComponents(); + + RooAbsPdf &_pdf; + RooAbsData &_data; + + RooAbsL::Extended _extended = RooAbsL::Extended::Auto; + RooArgSet _constrainedParameters; + RooArgSet _externalConstraints; + RooArgSet _globalObservables; + std::string _globalObservablesTag; + RooFit::EvalBackend _evalBackend = RooFit::EvalBackend::Legacy(); +}; + +/// Delegating function to build a likelihood without additional arguments. +inline std::unique_ptr buildLikelihood(RooAbsPdf *pdf, RooAbsData *data) +{ + return NLLFactory{*pdf, *data}.build(); } +} // namespace TestStatistics +} // namespace RooFit + #endif // ROOT_ROOFIT_TESTSTATISTICS_likelihood_builders diff --git a/roofit/roofitcore/inc/RooFit/TestStatistics/optional_parameter_types.h b/roofit/roofitcore/inc/RooFit/TestStatistics/optional_parameter_types.h deleted file mode 100644 index 35a592cb69aad..0000000000000 --- a/roofit/roofitcore/inc/RooFit/TestStatistics/optional_parameter_types.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Project: RooFit - * Authors: - * PB, Patrick Bos, Netherlands eScience Center, p.bos@esciencecenter.nl - * - * Copyright (c) 2021, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#ifndef ROOT_ROOFIT_TESTSTATISTICS_optional_parameter_types -#define ROOT_ROOFIT_TESTSTATISTICS_optional_parameter_types - -#include - -namespace RooFit { -namespace TestStatistics { - -// strongly named container types for use as optional parameters in the test statistics constructors - -/// Optional parameter used in buildLikelihood(), see documentation there. -struct ConstrainedParameters { - ConstrainedParameters(); - explicit ConstrainedParameters(const RooArgSet ¶meters); - RooArgSet set; -}; - -/// Optional parameter used in buildLikelihood(), see documentation there. -struct ExternalConstraints { - ExternalConstraints(); - explicit ExternalConstraints(const RooArgSet &constraints); - RooArgSet set; -}; - -/// Optional parameter used in buildLikelihood(), see documentation there. -struct GlobalObservables { - GlobalObservables(); - explicit GlobalObservables(const RooArgSet &observables); - RooArgSet set; -}; - -} -} - -#endif // ROOT_ROOFIT_TESTSTATISTICS_optional_parameter_types diff --git a/roofit/roofitcore/inc/RooFit/UniqueId.h b/roofit/roofitcore/inc/RooFit/UniqueId.h index 7d8c99fdf5533..607e32ce810bf 100644 --- a/roofit/roofitcore/inc/RooFit/UniqueId.h +++ b/roofit/roofitcore/inc/RooFit/UniqueId.h @@ -62,7 +62,8 @@ struct UniqueId { bool operator<(UniqueId const &other) const { return _val < other._val; } /// Get an ID that is less than the ID of any object (similar to nullptr). - static UniqueId const& nullid() { + static UniqueId const &nullid() + { static const UniqueId nid{nullval}; return nid; } @@ -83,10 +84,11 @@ std::atomic::Value_t> UniqueId::counter{UniqueId /// A helper function to replace pointer comparisons with UniqueId comparisons. /// With pointer comparisons, we can also have `nullptr`. In the UniqueId case, /// this translates to the `nullid`. -template -UniqueId const& getUniqueId(Class const *ptr) +template >().uniqueId())>> +UniqueId_t const &getUniqueId(Class const *ptr) { - return ptr ? ptr->uniqueId() : UniqueId::nullid(); + return ptr ? ptr->uniqueId() : UniqueId_t::nullid(); } } // namespace RooFit diff --git a/roofit/roofitcore/inc/RooFitLegacy/RooMinuit.h b/roofit/roofitcore/inc/RooFitLegacy/RooMinuit.h deleted file mode 100644 index a241cbbb33dd2..0000000000000 --- a/roofit/roofitcore/inc/RooFitLegacy/RooMinuit.h +++ /dev/null @@ -1,158 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooMinuit.h,v 1.15 2007/07/12 20:30:28 wouter Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_MINUIT -#define ROO_MINUIT - -#include "TObject.h" -#include "TStopwatch.h" -#include -#include "TMatrixDSymfwd.h" -#include -#include -#include - -#include - -class RooAbsReal ; -class RooFitResult ; -class RooArgList ; -class RooRealVar ; -class RooArgSet ; -class RooAbsArg ; -class TVirtualFitter ; -class TH2F ; -class RooPlot ; - -void RooMinuitGlue(Int_t& /*np*/, double* /*gin*/, double &f, double *par, Int_t /*flag*/) ; - -class RooMinuit : public TObject { -public: - - RooMinuit(RooAbsReal& function) ; - ~RooMinuit() override ; - - enum Strategy { Speed=0, Balance=1, Robustness=2 } ; - enum PrintLevel { None=-1, Reduced=0, Normal=1, ExtraForProblem=2, Maximum=3 } ; - void setStrategy(Int_t strat) ; - void setErrorLevel(double level) ; - void setEps(double eps) ; - void optimizeConst(Int_t flag) ; - void setEvalErrorWall(bool flag) { _doEvalErrorWall = flag ; } - void setOffsetting(bool flag) ; - - RooFitResult* fit(const char* options) ; - - Int_t migrad() ; - Int_t hesse() ; - Int_t minos() ; - Int_t minos(const RooArgSet& minosParamList) ; // added FMV, 08/18/03 - Int_t seek() ; - Int_t simplex() ; - Int_t improve() ; - - RooFitResult* save(const char* name=nullptr, const char* title=nullptr) ; - RooPlot* contour(RooRealVar& var1, RooRealVar& var2, - double n1=1, double n2=2, double n3=0.0, - double n4=0.0, double n5=0.0, double n6=0.0) ; - - Int_t setPrintLevel(Int_t newLevel) ; - void setNoWarn() ; - Int_t setWarnLevel(Int_t newLevel) ; - void setPrintEvalErrors(Int_t numEvalErrors) { _printEvalErrors = numEvalErrors ; } - void setVerbose(bool flag=true) { _verbose = flag ; } - void setProfile(bool flag=true) { _profile = flag ; } - void setMaxEvalMultiplier(Int_t n) { _maxEvalMult = n ; } - bool setLogFile(const char* logfile=nullptr) ; - - static void cleanup() ; - - Int_t evalCounter() const { return _evalCounter ; } - void zeroEvalCount() { _evalCounter = 0 ; } - -protected: - - friend class RooAbsPdf ; - void applyCovarianceMatrix(TMatrixDSym& V) ; - - friend void RooMinuitGlue(Int_t &np, double *gin, double &f, double *par, Int_t flag) ; - - void profileStart() ; - void profileStop() ; - - bool synchronize(bool verbose) ; - void backProp() ; - - inline Int_t getNPar() const { return _nPar ; } - inline std::ofstream* logfile() const { return _logfile ; } - inline double& maxFCN() { return _maxFCN ; } - - double getPdfParamVal(Int_t index) ; - double getPdfParamErr(Int_t index) ; - virtual bool setPdfParamVal(Int_t index, double value, bool verbose=false) ; - void setPdfParamErr(Int_t index, double value) ; - void setPdfParamErr(Int_t index, double loVal, double hiVal) ; - void clearPdfParamAsymErr(Int_t index) ; - - void saveStatus(const char* label, Int_t status) { _statusHistory.push_back(std::pair(label,status)) ; } - - void updateFloatVec() ; - -private: - - Int_t _evalCounter ; - Int_t _printLevel ; - Int_t _warnLevel ; - Int_t _status ; - Int_t _optConst ; - bool _profile ; - bool _handleLocalErrors ; - Int_t _numBadNLL ; - Int_t _nPar ; - Int_t _printEvalErrors ; - bool _doEvalErrorWall ; - Int_t _maxEvalMult ; - RooArgList* _floatParamList ; - std::vector _floatParamVec ; - RooArgList* _initFloatParamList ; - RooArgList* _constParamList ; - RooArgList* _initConstParamList ; - RooAbsReal* _func ; - - double _maxFCN ; - std::ofstream* _logfile ; - bool _verbose ; - TStopwatch _timer ; - TStopwatch _cumulTimer ; - - TMatrixDSym* _extV ; - - static TVirtualFitter *_theFitter ; - - std::vector > _statusHistory ; - - RooMinuit(const RooMinuit&) ; - -// Undocumented preprocessor define such that the implementation in -// RooMinuit.cxx can suppress the deprecation warning. -#ifndef __ROOFIT_SUPPRESS_ROOMINIMIZER_DEPRECATION_WARNING -} R__DEPRECATED(6, 30, "Please use RooMinimizer instead of RooMinuit"); -#else -}; -#endif - - -#endif - diff --git a/roofit/roofitcore/inc/RooFitResult.h b/roofit/roofitcore/inc/RooFitResult.h index 8b0bf18d5d1d7..a816e425a68c7 100644 --- a/roofit/roofitcore/inc/RooFitResult.h +++ b/roofit/roofitcore/inc/RooFitResult.h @@ -157,11 +157,8 @@ class RooFitResult : public TNamed, public RooPrintable, public RooDirItem { void SetName(const char *name) override ; void SetNameTitle(const char *name, const char* title) override ; -protected: - friend class RooAbsPdf ; - friend class RooMinuit ; - friend class RooMinimizer ; + void setCovarianceMatrix(TMatrixDSym& V) ; void setConstParList(const RooArgList& list) ; void setInitParList(const RooArgList& list) ; @@ -171,12 +168,14 @@ class RooFitResult : public TNamed, public RooPrintable, public RooDirItem { inline void setStatus(Int_t val) { _status = val ; } inline void setCovQual(Int_t val) { _covQual = val ; } inline void setNumInvalidNLL(Int_t val) { _numBadNLL=val ; } - void fillCorrMatrix() ; + void setStatusHistory(std::vector >& hist) { _statusHistory = hist ; } void fillCorrMatrix(const std::vector& globalCC, const TMatrixDSym& corrs, const TMatrixDSym& covs) ; + +protected: + + void fillCorrMatrix() ; void fillLegacyCorrMatrix() const ; void fillPrefitCorrMatrix(); - void setStatusHistory(std::vector >& hist) { _statusHistory = hist ; } - double correlation(Int_t row, Int_t col) const; double covariance(Int_t row, Int_t col) const; diff --git a/roofit/roofitcore/inc/RooFormula.h b/roofit/roofitcore/inc/RooFormula.h deleted file mode 100644 index b72c656fd1736..0000000000000 --- a/roofit/roofitcore/inc/RooFormula.h +++ /dev/null @@ -1,99 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooFormula.h,v 1.34 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_FORMULA -#define ROO_FORMULA - -#include "RooPrintable.h" -#include "RooArgList.h" -#include "RooArgSet.h" -#include "RooFit/Detail/DataMap.h" -#include "RooBatchComputeTypes.h" - -#include "TFormula.h" - -#include -#include -#include - -class RooAbsReal; - -class RooFormula : public TNamed, public RooPrintable { -public: - // Constructors etc. - RooFormula() ; - RooFormula(const char* name, const char* formula, const RooArgList& varList, bool checkVariables = true); - RooFormula(const RooFormula& other, const char* name=nullptr); - TObject* Clone(const char* newName = nullptr) const override {return new RooFormula(*this, newName);} - - //////////////////////////////////////////////////////////////////////////////// - /// Return list of arguments which are used in the formula. - RooArgSet actualDependents() const {return usedVariables();} - bool changeDependents(const RooAbsCollection& newDeps, bool mustReplaceAll, bool nameChange) ; - - /// Return pointer to the parameter with given name. - /// \return Parameter if in use, nullptr if not in use. - RooAbsArg* getParameter(const char* name) const { - return usedVariables().find(name); - } - - /// Return pointer to parameter at given index. This returns - /// irrespective of whether the parameter is in use. - RooAbsArg* getParameter(Int_t index) const { - return _origList.at(index); - } - - bool ok() const { return _tFormula != nullptr; } - /// Evalute all parameters/observables, and then evaluate formula. - double eval(const RooArgSet* nset=nullptr) const; - RooSpan evaluateSpan(const RooAbsReal* dataOwner, RooBatchCompute::RunContext& inputData, const RooArgSet* nset = nullptr) const; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const; - - /// DEBUG: Dump state information - void dump() const; - bool reCompile(const char* newFormula) ; - - - void printValue(std::ostream& os) const override ; - void printName(std::ostream& os) const override ; - void printTitle(std::ostream& os) const override ; - void printClassName(std::ostream& os) const override ; - void printArgs(std::ostream& os) const override ; - void printMultiline(std::ostream& os, Int_t contents, bool verbose=false, TString indent="") const override ; - - void Print(Option_t *options= nullptr) const override { - // Printing interface (human readable) - printStream(defaultPrintStream(),defaultPrintContents(options),defaultPrintStyle(options)); - } - - std::string formulaString() const { - return _tFormula ? _tFormula->GetTitle() : ""; - } - -private: - RooFormula& operator=(const RooFormula& other); - std::string processFormula(std::string origFormula) const; - RooArgList usedVariables() const; - std::string reconstructFormula(std::string internalRepr) const; - void installFormulaOrThrow(const std::string& formulaa); - - RooArgList _origList; /// _isCategory; /// _tFormula; /// class RooArgSet ; +class RooFormula ; class RooFormulaVar : public RooAbsReal { public: // Constructors, assignment etc - RooFormulaVar() { } + RooFormulaVar(); + ~RooFormulaVar() override; RooFormulaVar(const char *name, const char *title, const char* formula, const RooArgList& dependents, bool checkVariables = true); RooFormulaVar(const char *name, const char *title, const RooArgList& dependents, bool checkVariables = true); RooFormulaVar(const RooFormulaVar& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooFormulaVar(*this,newname); } - inline bool ok() const { return getFormula().ok() ; } + bool ok() const; const char* expression() const { return _formExpr.Data(); } const RooArgList& dependents() const { return _actualVars; } @@ -48,6 +49,10 @@ class RooFormulaVar : public RooAbsReal { inline RooAbsArg* getParameter(Int_t index) const { return _actualVars.at(index) ; } + /// Return the number of parameters. + inline size_t nParameters() const { + return _actualVars.size(); + } // I/O streaming interface (machine readable) bool readFromStream(std::istream& is, bool compact, bool verbose=false) override ; @@ -59,11 +64,7 @@ class RooFormulaVar : public RooAbsReal { // Debugging /// Dump the formula to stdout. - void dumpFormula() { getFormula().dump() ; } - /// Get reference to the internal formula object. - const RooFormula& formula() const { - return getFormula(); - } + void dumpFormula(); double defaultErrorLevel() const override ; @@ -72,12 +73,7 @@ class RooFormulaVar : public RooAbsReal { // Function evaluation double evaluate() const override ; - RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const override; - inline void computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const override - { - formula().computeBatch(stream, output, nEvents, dataMap); - } - + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const override; protected: // Post-processing of server redirection @@ -89,7 +85,7 @@ class RooFormulaVar : public RooAbsReal { RooFormula& getFormula() const; RooListProxy _actualVars ; ///< Actual parameters used by formula engine - std::unique_ptr _formula{nullptr}; /// +#include + +#include +#include +#include + +class RooSimultaneous; + +/// @brief A wrapper class to store a C++ function of type 'double (*)(double*, double*)'. +/// The parameters can be accessed as params[] in the function body. +/// The observables can be accessed as obs[i + j], where i represents the observable position and j +/// represents the data entry. +class RooFuncWrapper final : public RooAbsReal { +public: + RooFuncWrapper(const char *name, const char *title, std::string const &funcBody, RooArgSet const ¶mSet, + const RooAbsData *data, RooSimultaneous const *simPdf, bool createGradient); + + RooFuncWrapper(const char *name, const char *title, RooAbsReal const &obj, RooArgSet const &normSet, + const RooAbsData *data, RooSimultaneous const *simPdf, bool createGradient); + + RooFuncWrapper(const RooFuncWrapper &other, const char *name = nullptr); + + TObject *clone(const char *newname) const override { return new RooFuncWrapper(*this, newname); } + + double defaultErrorLevel() const override { return 0.5; } + + bool hasGradient() const override { return _hasGradient; } + void gradient(double *out) const override; + + void gradient(const double *x, double *g) const; + + std::size_t getNumParams() const { return _params.size(); } + + void dumpCode(); + + void dumpGradient(); + + /// No constant term optimization is possible in code-generation mode. + void constOptimizeTestStatistic(ConstOpCode /*opcode*/, bool /*doAlsoTrackingOpt*/) override {} + +protected: + double evaluate() const override; + +private: + std::string buildCode(RooAbsReal const &head); + + void updateGradientVarBuffer() const; + + void loadParamsAndData(std::string funcName, RooAbsArg const *head, RooArgSet const ¶mSet, + const RooAbsData *data, RooSimultaneous const *simPdf); + + void declareAndDiffFunction(std::string funcName, std::string const &funcBody, bool createGradient); + + void buildFuncAndGradFunctors(); + + using Func = double (*)(double *, double const *); + using Grad = void (*)(double *, double const *, double *); + + struct ObsInfo { + ObsInfo(std::size_t i, std::size_t n) : idx{i}, size{n} {} + std::size_t idx = 0; + std::size_t size = 0; + }; + + RooListProxy _params; + Func _func; + Grad _grad; + bool _hasGradient = false; + mutable std::vector _gradientVarBuffer; + std::vector _observables; + std::map _obsInfos; + std::map _nodeOutputSizes; +}; + +#endif diff --git a/roofit/roofitcore/inc/RooGenContext.h b/roofit/roofitcore/inc/RooGenContext.h index 9988ebb3d344e..1723544fe98b5 100644 --- a/roofit/roofitcore/inc/RooGenContext.h +++ b/roofit/roofitcore/inc/RooGenContext.h @@ -47,7 +47,7 @@ class RooGenContext : public RooAbsGenContext { RooArgSet _directVars,_uniformVars,_otherVars; ///< List of observables generated internally, randomly, and by accept/reject sampling Int_t _code; ///< Internal generation code double _maxProb{0.}, _area{0.}, _norm{0.}; ///< Maximum probability, p.d.f area and normalization - RooRealIntegral *_acceptRejectFunc; ///< Projection function to be passed to accept/reject sampler + std::unique_ptr _acceptRejectFunc; ///< Projection function to be passed to accept/reject sampler RooAbsNumGenerator *_generator; ///< MC sampling generation engine RooRealVar *_maxVar ; ///< Variable holding maximum value of p.d.f Int_t _updateFMaxPerEvent ; ///< If true, maximum p.d.f value needs to be recalculated for each event diff --git a/roofit/roofitcore/inc/RooGenFitStudy.h b/roofit/roofitcore/inc/RooGenFitStudy.h index 7206ca6d50ca2..0a0486158c742 100644 --- a/roofit/roofitcore/inc/RooGenFitStudy.h +++ b/roofit/roofitcore/inc/RooGenFitStudy.h @@ -40,8 +40,8 @@ class RooGenFitStudy : public RooAbsStudy { ~RooGenFitStudy() override ; RooAbsStudy* clone(const char* newname="") const override { return new RooGenFitStudy(newname?newname:GetName(),GetTitle()) ; } - void setGenConfig(const char* pdfName, const char* obsName, const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg()) ; - void setFitConfig(const char* pdfName, const char* obsName, const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg()) ; + void setGenConfig(const char* pdfName, const char* obsName, const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}) ; + void setFitConfig(const char* pdfName, const char* obsName, const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}) ; bool attach(RooWorkspace& w) override ; bool initialize() override ; @@ -68,10 +68,10 @@ class RooGenFitStudy : public RooAbsStudy { RooAbsPdf::GenSpec* _genSpec ; /// _params; /// evaluateSpan(RooBatchCompute::RunContext& inputData, const RooArgSet* normSet) const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; - - bool setFormula(const char* formula) ; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; // Post-processing of server redirection bool redirectServersHook(const RooAbsCollection& newServerList, bool mustReplaceAll, bool nameChange, bool isRecursive) override ; - bool isValidReal(double value, bool printError) const override ; + bool isValidReal(double /*value*/, bool /*printError*/) const override { return true; } - std::unique_ptr _formula{nullptr}; ///&) ; RooCmdArg Import(TH1& histo, bool importDensity=false) ; // RooDataSet::ctor arguments -RooCmdArg WeightVar(const char* name, bool reinterpretAsWeight=false) ; +RooCmdArg WeightVar(const char* name="weight", bool reinterpretAsWeight=false) ; RooCmdArg WeightVar(const RooRealVar& arg, bool reinterpretAsWeight=false) ; -RooCmdArg Import(const char* state, RooDataSet& data) ; +RooCmdArg Import(const char* state, RooAbsData& data) ; RooCmdArg Import(const std::map& ) ; +template +RooCmdArg Import(std::map const& map) { + RooCmdArg container("ImportDataSliceMany",0,0,0,0,nullptr,nullptr,nullptr,nullptr) ; + for (auto const& item : map) { + container.addArg(Import(item.first.c_str(), *item.second)) ; + } + container.setProcessRecArgs(true,false) ; + return container ; +} + RooCmdArg Link(const char* state, RooAbsData& data) ; RooCmdArg Link(const std::map&) ; -RooCmdArg Import(RooDataSet& data) ; +RooCmdArg Import(RooAbsData& data) ; RooCmdArg Import(TTree& tree) ; RooCmdArg ImportFromFile(const char* fname, const char* tname) ; RooCmdArg StoreError(const RooArgSet& aset) ; @@ -185,11 +187,10 @@ RooCmdArg OwnLinked() ; // RooAbsPdf::printLatex arguments RooCmdArg Columns(Int_t ncol) ; RooCmdArg OutputFile(const char* fileName) ; -RooCmdArg Format(const char* format, Int_t sigDigit) ; -RooCmdArg Format(const char* what, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(),const RooCmdArg& arg8=RooCmdArg::none()) ; +RooCmdArg Format(const char* what, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={}) ; RooCmdArg Sibling(const RooAbsCollection& sibling) ; // RooAbsRealLValue::frame arguments @@ -222,12 +223,12 @@ RooCmdArg Parallelize(int nWorkers) ; RooCmdArg ModularL(bool flag=false) ; RooCmdArg TimingAnalysis(bool timingAnalysis) ; -RooCmdArg BatchMode(std::string const& batchMode="cpu"); -// The const char * overload is necessary, otherwise the compiler will cast a -// C-Style string to a bool and choose the BatchMode(bool) overload if one -// calls for example BatchMode("off"). -inline RooCmdArg BatchMode(const char * batchMode) { return BatchMode(std::string(batchMode)); } -inline RooCmdArg BatchMode(bool batchModeOn) { return BatchMode(batchModeOn ? "cpu" : "off"); } +//RooCmdArg BatchMode(std::string const& batchMode="cpu"); +//// The const char * overload is necessary, otherwise the compiler will cast a +//// C-Style string to a bool and choose the BatchMode(bool) overload if one +//// calls for example BatchMode("off"). +//inline RooCmdArg BatchMode(const char * batchMode) { return BatchMode(std::string(batchMode)); } +//inline RooCmdArg BatchMode(bool batchModeOn) { return BatchMode(batchModeOn ? "cpu" : "off"); } RooCmdArg IntegrateBins(double precision); @@ -235,6 +236,34 @@ RooCmdArg IntegrateBins(double precision); RooCmdArg PrefitDataFraction(double data_ratio = 0.0) ; RooCmdArg Optimize(Int_t flag=2) ; +class EvalBackend : public RooCmdArg { +public: + enum class Value { Legacy, Cpu, Cuda, Codegen, CodegenNoGrad }; + + EvalBackend(Value value); + + EvalBackend(std::string const &name); + + static EvalBackend Legacy(); + static EvalBackend Cpu(); + static EvalBackend Cuda(); + static EvalBackend Codegen(); + static EvalBackend CodegenNoGrad(); + + Value value() const { return static_cast(getInt(0)); } + + bool operator==(EvalBackend const &other) const { return value() == other.value(); } + + bool operator!=(EvalBackend const &other) const { return value() != other.value(); } + + std::string name() const; + + static Value &defaultValue(); +private: + static Value toValue(std::string const& name); + static std::string toName(Value value); +}; + //////////////////////////////////////////////////////////////////////////////// /// Create a RooCmdArg to declare conditional observables. /// \param[in] argsOrArgSet Can either be one or more RooRealVar with the @@ -322,8 +351,8 @@ RooCmdArg Asimov(bool flag=true) ; /** @} */ // RooAbsRealLValue::createHistogram arguments -RooCmdArg YVar(const RooAbsRealLValue& var, const RooCmdArg& arg=RooCmdArg::none()) ; -RooCmdArg ZVar(const RooAbsRealLValue& var, const RooCmdArg& arg=RooCmdArg::none()) ; +RooCmdArg YVar(const RooAbsRealLValue& var, const RooCmdArg& arg={}) ; +RooCmdArg ZVar(const RooAbsRealLValue& var, const RooCmdArg& arg={}) ; RooCmdArg AxisLabel(const char* name) ; RooCmdArg Scaling(bool flag) ; @@ -343,15 +372,15 @@ RooCmdArg NumIntConfig(const RooNumIntConfig& cfg) ; // RooMCStudy::ctor arguments RooCmdArg Silence(bool flag=true) ; RooCmdArg FitModel(RooAbsPdf& pdf) ; -RooCmdArg FitOptions(const RooCmdArg& arg1 ,const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; +RooCmdArg FitOptions(const RooCmdArg& arg1 ,const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; RooCmdArg Binned(bool flag=true) ; // RooMCStudy::plot* arguments -RooCmdArg Frame(const RooCmdArg& arg1 ,const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; +RooCmdArg Frame(const RooCmdArg& arg1 ,const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; RooCmdArg FrameBins(Int_t nbins) ; RooCmdArg FrameRange(double xlo, double xhi) ; RooCmdArg FitGauss(bool flag=true) ; @@ -401,9 +430,9 @@ RooCmdArg ScanNoCdf() ; // Generic container arguments (to be able to supply more command line arguments) RooCmdArg MultiArg(const RooCmdArg& arg1, const RooCmdArg& arg2, - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(),const RooCmdArg& arg8=RooCmdArg::none()) ; + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={}) ; RooConstVar& RooConst(double val) ; @@ -416,14 +445,27 @@ namespace Detail { // Function to pack an arbitrary number of RooCmdArgs into a RooLinkedList. Implementation detail of many high-level RooFit functions. template -inline std::unique_ptr createCmdList(Args &&... args) +inline std::unique_ptr createCmdList(RooCmdArg const* arg1, Args &&...args) +{ + auto cmdList = std::make_unique(); + for (auto &arg : {arg1, static_cast(args)...}) { + cmdList->Add(const_cast(arg)); + } + return cmdList; +} + +inline std::unique_ptr createCmdList() +{ + return std::make_unique(); +} + +inline std::unique_ptr createCmdList(RooLinkedList const *cmdList) { - auto cmdList = std::make_unique(); - for (auto * arg : {args...}) { - cmdList->Add(const_cast(arg)); - //cmdList->Add(new RooCmdArg{arg}); - } - return cmdList; + auto cmdListCopy = std::make_unique(); + for (auto *arg : *cmdList) { + cmdListCopy->Add(arg); + } + return cmdListCopy; } } // namespace Detail diff --git a/roofit/roofitcore/inc/RooGrid.h b/roofit/roofitcore/inc/RooGrid.h index f422e8e62294d..934df16777ced 100644 --- a/roofit/roofitcore/inc/RooGrid.h +++ b/roofit/roofitcore/inc/RooGrid.h @@ -16,27 +16,21 @@ #ifndef ROO_GRID #define ROO_GRID -#include "TObject.h" -#include "RooPrintable.h" +#include +#include #include class RooAbsFunc; -class RooGrid : public TObject, public RooPrintable { +// Utility class for RooMCIntegrator holding a multi-dimensional grid +class RooGrid { public: RooGrid() {} RooGrid(const RooAbsFunc &function); // Printing interface - void printName(std::ostream& os) const override ; - void printTitle(std::ostream& os) const override ; - void printClassName(std::ostream& os) const override ; - void printMultiline(std::ostream& os, Int_t contents, bool verbose=false, TString indent="") const override; - - inline void Print(Option_t *options= nullptr) const override { - printStream(defaultPrintStream(),defaultPrintContents(options),defaultPrintStyle(options)); - } + void print(std::ostream& os, bool verbose=false, std::string const& indent="") const; inline bool isValid() const { return _valid; } inline UInt_t getDimension() const { return _dim; } @@ -59,16 +53,14 @@ class RooGrid : public TObject, public RooPrintable { enum { maxBins = 50 }; // must be even // Accessor for the j-th normalized grid point along the i-th dimension -public: inline double coord(Int_t i, Int_t j) const { return _xi[i*_dim + j]; } inline double value(Int_t i,Int_t j) const { return _d[i*_dim + j]; } + protected: inline double& coord(Int_t i, Int_t j) { return _xi[i*_dim + j]; } inline double& value(Int_t i,Int_t j) { return _d[i*_dim + j]; } inline double& newCoord(Int_t i) { return _xin[i]; } -protected: - bool _valid = false; ///< Is configuration valid UInt_t _dim = 0; ///< Number of dimensions, bins and boxes UInt_t _bins = 0; ///< Number of bins @@ -83,7 +75,6 @@ class RooGrid : public TObject, public RooPrintable { std::vector _xin; /// _weight; /// getRangeOrBinningInterval(RooAbsArg const* arg, const char* rangeName); -bool checkIfRangesOverlap(RooArgSet const& observables, - RooAbsData const& data, - std::vector const& rangeNames); +bool checkIfRangesOverlap(RooArgSet const& observables, std::vector const& rangeNames); -std::string getColonSeparatedNameString(RooArgSet const& argSet); +std::string getColonSeparatedNameString(RooArgSet const& argSet, char delim=':'); RooArgSet selectFromArgSet(RooArgSet const&, std::string const& names); +namespace Detail { + +bool snapshotImpl(RooAbsCollection const& input, RooAbsCollection& output, bool deepCopy, RooArgSet const *observables); +RooAbsArg *cloneTreeWithSameParametersImpl(RooAbsArg const &arg, RooArgSet const *observables); + +} // namespace Detail /// Clone RooAbsArg object and reattach to original parameters. template std::unique_ptr cloneTreeWithSameParameters(T const& arg, RooArgSet const* observables=nullptr) { - std::unique_ptr clone{static_cast(arg.cloneTree())}; - RooArgSet origParams; - arg.getParameters(observables, origParams); - clone->recursiveRedirectServers(origParams); - return clone; + return std::unique_ptr{static_cast(Detail::cloneTreeWithSameParametersImpl(arg, observables))}; } std::string getRangeNameForSimComponent(std::string const& rangeName, bool splitRange, std::string const& catName); @@ -157,7 +157,9 @@ struct BinnedLOutput { bool isBinnedL = false; }; -BinnedLOutput getBinnedL(RooAbsPdf &pdf); +BinnedLOutput getBinnedL(RooAbsPdf const &pdf); + +void getSortedComputationGraph(RooAbsArg const &func, RooArgSet &out); } diff --git a/roofit/roofitcore/inc/RooHistError.h b/roofit/roofitcore/inc/RooHistError.h index c6ea7cad4ac76..0a66db2dba1bc 100644 --- a/roofit/roofitcore/inc/RooHistError.h +++ b/roofit/roofitcore/inc/RooHistError.h @@ -131,7 +131,6 @@ class RooHistError { Int_t _N1 ; } ; - ClassDef(RooHistError,1) // Utility class for calculating histogram errors }; #endif diff --git a/roofit/roofitcore/inc/RooHistFunc.h b/roofit/roofitcore/inc/RooHistFunc.h index f4819c60ea5f5..58a631573ec8e 100644 --- a/roofit/roofitcore/inc/RooHistFunc.h +++ b/roofit/roofitcore/inc/RooHistFunc.h @@ -51,6 +51,10 @@ class RooHistFunc : public RooAbsReal { return *_dataHist ; } + /// Replaces underlying RooDataHist with a clone, which is now owned, and returns the clone. + /// If the underlying RooDataHist is already owned, then that is returned instead of being cloned. + RooDataHist* cloneAndOwnDataHist(const char* newname=""); + /// Get total bin volume spanned by this hist function. /// In 1-d, this is e.g. the range spanned on the x-axis. double totVolume() const; @@ -70,6 +74,8 @@ class RooHistFunc : public RooAbsReal { Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + bool forceAnalyticalInt(const RooAbsArg& dep) const override; + /// Set use of special boundary conditions for c.d.f.s void setCdfBoundaries(bool flag) { _cdfBoundaries = flag ; @@ -93,13 +99,16 @@ class RooHistFunc : public RooAbsReal { Int_t getBin() const; std::vector getBins(RooFit::Detail::DataMap const& dataMap) const; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(int code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; protected: bool importWorkspaceHook(RooWorkspace& ws) override ; bool areIdentical(const RooDataHist& dh1, const RooDataHist& dh2) ; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; friend class RooAbsCachedReal ; void ioStreamerPass2() override ; diff --git a/roofit/roofitcore/inc/RooHistPdf.h b/roofit/roofitcore/inc/RooHistPdf.h index 5381df1700cd7..49b768ea69fad 100644 --- a/roofit/roofitcore/inc/RooHistPdf.h +++ b/roofit/roofitcore/inc/RooHistPdf.h @@ -49,6 +49,10 @@ class RooHistPdf : public RooAbsPdf { return *_dataHist ; } + /// Replaces underlying RooDataHist with a clone, which is now owned, and returns the clone. + /// If the underlying RooDataHist is already owned, then that is returned instead of being cloned. + RooDataHist* cloneAndOwnDataHist(const char* newname=""); + void setInterpolationOrder(Int_t order) { // Set histogram interpolation order _intOrder = order ; @@ -61,6 +65,8 @@ class RooHistPdf : public RooAbsPdf { Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + bool forceAnalyticalInt(const RooAbsArg& dep) const override; + void setCdfBoundaries(bool flag) { // Set use of special boundary conditions for c.d.f.s _cdfBoundaries = flag ; @@ -88,10 +94,13 @@ class RooHistPdf : public RooAbsPdf { std::list* binBoundaries(RooAbsRealLValue& /*obs*/, double /*xlo*/, double /*xhi*/) const override ; bool isBinnedDistribution(const RooArgSet&) const override { return _intOrder==0 ; } - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; -protected: + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string + buildCallToAnalyticIntegral(int code, const char *rangeName, RooFit::Detail::CodeSquashContext &ctx) const override; + protected: bool areIdentical(const RooDataHist& dh1, const RooDataHist& dh2) ; bool importWorkspaceHook(RooWorkspace& ws) override ; @@ -115,17 +124,19 @@ class RooHistPdf : public RooAbsPdf { friend class RooHistFunc; + static bool forceAnalyticalInt(RooArgSet const& pdfObsList, RooAbsArg const& dep); + static Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName, RooArgSet const& histObsList, - RooSetProxy const& pdfObsList, + RooArgSet const& pdfObsList, Int_t intOrder) ; static double analyticalIntegral(Int_t code, const char* rangeName, RooArgSet const& histObsList, - RooSetProxy const& pdfObsList, + RooArgSet const& pdfObsList, RooDataHist& dataHist, bool histFuncMode) ; @@ -137,6 +148,12 @@ class RooHistPdf : public RooAbsPdf { double xlo, double xhi); + static void rooHistTranslateImpl(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, int intOrder, + RooDataHist const *dataHist, const RooArgSet &obs, bool correctForBinSize); + + static std::string rooHistIntegralTranslateImpl(int code, RooAbsArg const *klass, RooDataHist const *dataHist, + const RooArgSet &obs, bool histFuncMode); + ClassDefOverride(RooHistPdf,4) // Histogram based PDF }; diff --git a/roofit/roofitcore/inc/RooImproperIntegrator1D.h b/roofit/roofitcore/inc/RooImproperIntegrator1D.h index 1f059fbd3488f..c86fce6106b49 100644 --- a/roofit/roofitcore/inc/RooImproperIntegrator1D.h +++ b/roofit/roofitcore/inc/RooImproperIntegrator1D.h @@ -20,16 +20,14 @@ #include "RooNumIntConfig.h" class RooInvTransform; -class RooIntegrator1D; +class RooRombergIntegrator; class RooImproperIntegrator1D : public RooAbsIntegrator { public: - RooImproperIntegrator1D() ; RooImproperIntegrator1D(const RooAbsFunc& function); RooImproperIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config); RooImproperIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, const RooNumIntConfig& config); - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; bool checkLimits() const override; using RooAbsIntegrator::setLimits ; @@ -37,11 +35,6 @@ class RooImproperIntegrator1D : public RooAbsIntegrator { bool setUseIntegrandLimits(bool flag) override {_useIntegrandLimits = flag ; return true ; } double integral(const double* yvec=nullptr) override ; - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return false ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return true ; } - protected: friend class RooNumIntFactory ; @@ -59,9 +52,9 @@ class RooImproperIntegrator1D : public RooAbsIntegrator { RooAbsFunc* _origFunc = nullptr; ///< Original function binding std::unique_ptr _function; ///< Binding with inverse of function RooNumIntConfig _config ; ///< Configuration object - mutable std::unique_ptr _integrator1; ///< Piece integrator 1 - mutable std::unique_ptr _integrator2; ///< Piece integrator 2 - mutable std::unique_ptr _integrator3; ///< Piece integrator 3 + mutable std::unique_ptr _integrator1; ///< Piece integrator 1 + mutable std::unique_ptr _integrator2; ///< Piece integrator 2 + mutable std::unique_ptr _integrator3; ///< Piece integrator 3 ClassDefOverride(RooImproperIntegrator1D,0) // 1-dimensional improper integration engine }; diff --git a/roofit/roofitcore/inc/RooInt.h b/roofit/roofitcore/inc/RooInt.h deleted file mode 100644 index f8f5ac09bf8de..0000000000000 --- a/roofit/roofitcore/inc/RooInt.h +++ /dev/null @@ -1,44 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooInt.h,v 1.6 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_INT -#define ROO_INT - -#include "Rtypes.h" -#include "TNamed.h" - -class RooInt : public TNamed { -public: - - RooInt() : _value(0) {} ; - RooInt(Int_t value) : TNamed(), _value(value) {} ; - RooInt(const RooInt& other) : TNamed(other), _value(other._value) {} - ~RooInt() override {} ; - - // double cast operator - inline operator Int_t() const { return _value ; } - RooInt& operator=(Int_t value) { _value = value ; return *this ; } - - // Sorting interface ; - Int_t Compare(const TObject* other) const override ; - bool IsSortable() const override { return true ; } - -protected: - - Int_t _value ; ///< Payload - ClassDefOverride(RooInt,1) // Container class for Int_t -}; - -#endif diff --git a/roofit/roofitcore/inc/RooIntegrator1D.h b/roofit/roofitcore/inc/RooIntegrator1D.h deleted file mode 100644 index 53f158d62edc9..0000000000000 --- a/roofit/roofitcore/inc/RooIntegrator1D.h +++ /dev/null @@ -1,95 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooIntegrator1D.h,v 1.21 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_INTEGRATOR_1D -#define ROO_INTEGRATOR_1D - -#include "RooAbsIntegrator.h" -#include "RooNumIntConfig.h" - -class RooIntegrator1D : public RooAbsIntegrator { -public: - - // Constructors, assignment etc - enum SummationRule { Trapezoid, Midpoint }; - RooIntegrator1D() {} - - RooIntegrator1D(const RooAbsFunc& function, SummationRule rule= Trapezoid, - Int_t maxSteps= 0, double eps= 0) ; - RooIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, - SummationRule rule= Trapezoid, Int_t maxSteps= 0, double eps= 0) ; - - RooIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, - const RooNumIntConfig& config) ; - - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; - - bool checkLimits() const override; - double integral(const double *yvec=nullptr) override ; - - using RooAbsIntegrator::setLimits ; - bool setLimits(double* xmin, double* xmax) override; - bool setUseIntegrandLimits(bool flag) override {_useIntegrandLimits = flag ; return true ; } - - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return false ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return false ; } - -protected: - - friend class RooNumIntFactory ; - static void registerIntegrator(RooNumIntFactory& fact) ; - - bool initialize(); - - bool _useIntegrandLimits; ///< If true limits of function binding are used - - // Integrator configuration - SummationRule _rule; - Int_t _maxSteps ; ///< Maximum number of steps - Int_t _minStepsZero ; ///< Minimum number of steps to declare convergence to zero - Int_t _fixSteps ; ///< Fixed number of steps - double _epsAbs ; ///< Absolute convergence tolerance - double _epsRel ; ///< Relative convergence tolerance - bool _doExtrap ; ///< Apply conversion step? - enum { _nPoints = 5 }; - - // Numerical integrator support functions - double addTrapezoids(Int_t n) ; - double addMidpoints(Int_t n) ; - void extrapolate(Int_t n) ; - - // Numerical integrator workspace - double _xmin; /// _h ; /// _s ; /// _c ; /// _d ; /// _x ; //! do not persist - - ClassDefOverride(RooIntegrator1D,0) // 1-dimensional numerical integration engine -}; - -#endif diff --git a/roofit/roofitcore/inc/RooIntegrator2D.h b/roofit/roofitcore/inc/RooIntegrator2D.h deleted file mode 100644 index d1b2b37671969..0000000000000 --- a/roofit/roofitcore/inc/RooIntegrator2D.h +++ /dev/null @@ -1,57 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooIntegrator2D.h,v 1.8 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_INTEGRATOR_2D -#define ROO_INTEGRATOR_2D - -#include "RooIntegrator1D.h" -#include "RooNumIntConfig.h" - -class RooIntegrator2D : public RooIntegrator1D { -public: - - // Constructors, assignment etc - RooIntegrator2D() ; - RooIntegrator2D(const RooAbsFunc& function, RooIntegrator1D::SummationRule rule=RooIntegrator1D::Trapezoid, - Int_t maxSteps= 0, double eps= 0) ; - RooIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, double ymin, double ymax, - SummationRule rule= Trapezoid, Int_t maxSteps= 0, double eps= 0) ; - - RooIntegrator2D(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, double ymin, double ymax, - const RooNumIntConfig& config) ; - - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; - ~RooIntegrator2D() override ; - - bool checkLimits() const override; - - bool canIntegrate1D() const override { return false ; } - bool canIntegrate2D() const override { return true ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return false ; } - -protected: - - friend class RooNumIntFactory ; - static void registerIntegrator(RooNumIntFactory& fact) ; - - RooIntegrator1D* _xIntegrator ; ///< Integrator in first dimension - RooAbsFunc* _xint ; ///< Function binding representing integral over first dimension - - ClassDefOverride(RooIntegrator2D,0) // 2-dimensional numerical integration engine -}; - -#endif diff --git a/roofit/roofitcore/inc/RooIntegratorBinding.h b/roofit/roofitcore/inc/RooIntegratorBinding.h deleted file mode 100644 index 6b240f9f5f8b5..0000000000000 --- a/roofit/roofitcore/inc/RooIntegratorBinding.h +++ /dev/null @@ -1,40 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooIntegratorBinding.h,v 1.4 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_INTEGRATOR_BINDING -#define ROO_INTEGRATOR_BINDING - -#include "RooAbsFunc.h" -#include "RooAbsIntegrator.h" - -class RooIntegratorBinding : public RooAbsFunc { -public: - RooIntegratorBinding(RooAbsIntegrator& integrator) : - RooAbsFunc(integrator.integrand()->getDimension()-1), _integrator(&integrator) {} ; - ~RooIntegratorBinding() override {} ; - - inline double operator()(const double xvector[]) const override { _ncall++ ; return _integrator->integral(xvector) ; } - inline double getMinLimit(UInt_t index) const override { return _integrator->integrand()->getMinLimit(index+1); } - inline double getMaxLimit(UInt_t index) const override { return _integrator->integrand()->getMaxLimit(index+1); } - -protected: - RooAbsIntegrator* _integrator ; ///< Numeric integrator - - - ClassDefOverride(RooIntegratorBinding,0) // Function binding representing output of numeric integrator -}; - -#endif - diff --git a/roofit/roofitcore/inc/RooLinearVar.h b/roofit/roofitcore/inc/RooLinearVar.h index 65d3e9ef23ec6..991e1523c2a1b 100644 --- a/roofit/roofitcore/inc/RooLinearVar.h +++ b/roofit/roofitcore/inc/RooLinearVar.h @@ -22,7 +22,6 @@ #include #include "RooAbsRealLValue.h" #include "RooRealProxy.h" -#include "RooFormula.h" #include "RooLinTransBinning.h" class RooArgSet ; diff --git a/roofit/roofitcore/inc/RooLinkedList.h b/roofit/roofitcore/inc/RooLinkedList.h index 1446fc8d9eb76..a7736d41c014e 100644 --- a/roofit/roofitcore/inc/RooLinkedList.h +++ b/roofit/roofitcore/inc/RooLinkedList.h @@ -29,12 +29,18 @@ class RooLinkedListIterImpl ; class RooFIter; class TIterator ; class RooAbsArg ; +template +class RooSTLRefCountList; + +/// \cond ROOFIT_INTERNAL namespace RooLinkedListImplDetails { class Chunk; class Pool; } +/// \endcond + class RooLinkedList : public TObject { public: // Constructor @@ -108,7 +114,7 @@ class RooLinkedList : public TObject { RooLinkedListElem* createElement(TObject* obj, RooLinkedListElem* elem=nullptr) ; void deleteElement(RooLinkedListElem*) ; - + template friend class RooSTLRefCountList; friend class RooLinkedListIterImpl ; friend class RooFIterForLinkedList ; diff --git a/roofit/roofitcore/inc/RooLinkedListElem.h b/roofit/roofitcore/inc/RooLinkedListElem.h index 08305d7982a69..f4657b254ee3d 100644 --- a/roofit/roofitcore/inc/RooLinkedListElem.h +++ b/roofit/roofitcore/inc/RooLinkedListElem.h @@ -22,11 +22,15 @@ class TObject ; class RooLinkedListElem ; class TBuffer ; +/// \cond ROOFIT_INTERNAL + namespace RooLinkedListImplDetails { class Chunk; class Pool; } +/// \endcond + class RooLinkedListElem { public: // Initial element ctor diff --git a/roofit/roofitcore/inc/RooLinkedListIter.h b/roofit/roofitcore/inc/RooLinkedListIter.h index 9fee42f860987..f9f5cb3f2f710 100644 --- a/roofit/roofitcore/inc/RooLinkedListIter.h +++ b/roofit/roofitcore/inc/RooLinkedListIter.h @@ -21,7 +21,7 @@ #include #include -#include +#include /// Interface for RooFIter-compatible iterators class GenericRooFIter diff --git a/roofit/roofitcore/inc/RooMCIntegrator.h b/roofit/roofitcore/inc/RooMCIntegrator.h index 87890dd221875..7cdd2fe9c572b 100644 --- a/roofit/roofitcore/inc/RooMCIntegrator.h +++ b/roofit/roofitcore/inc/RooMCIntegrator.h @@ -27,11 +27,9 @@ class RooMCIntegrator : public RooAbsIntegrator { // Constructors, assignment etc enum SamplingMode { Importance, ImportanceOnly, Stratified }; enum GeneratorType { QuasiRandom, PseudoRandom }; - RooMCIntegrator() ; RooMCIntegrator(const RooAbsFunc& function, SamplingMode mode= Importance, GeneratorType genType= QuasiRandom, bool verbose= false); RooMCIntegrator(const RooAbsFunc& function, const RooNumIntConfig& config); - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; ~RooMCIntegrator() override; bool checkLimits() const override; @@ -48,11 +46,6 @@ class RooMCIntegrator : public RooAbsIntegrator { const RooGrid &grid() const { return _grid; } - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return true ; } - bool canIntegrateND() const override { return true ; } - bool canIntegrateOpenEnded() const override { return false ; } - protected: friend class RooNumIntFactory ; diff --git a/roofit/roofitcore/inc/RooMCStudy.h b/roofit/roofitcore/inc/RooMCStudy.h index 608d39f144706..9dd5af7dd7e36 100644 --- a/roofit/roofitcore/inc/RooMCStudy.h +++ b/roofit/roofitcore/inc/RooMCStudy.h @@ -33,9 +33,9 @@ class RooMCStudy : public TNamed { public: RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; ~RooMCStudy() override ; @@ -62,30 +62,30 @@ class RooMCStudy : public TNamed { } // Plot methods - RooPlot* plotParamOn(RooPlot* frame, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooPlot* plotParam(const RooRealVar& param, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooPlot* plotParam(const char* paramName, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooPlot* plotNLL(const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooPlot* plotError(const RooRealVar& param, const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; - RooPlot* plotPull(const RooRealVar& param, const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(), const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(), const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none()) ; + RooPlot* plotParamOn(RooPlot* frame, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooPlot* plotParam(const RooRealVar& param, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooPlot* plotParam(const char* paramName, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooPlot* plotNLL(const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooPlot* plotError(const RooRealVar& param, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; + RooPlot* plotPull(const RooRealVar& param, const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; RooPlot* plotNLL(double lo, double hi, Int_t nBins=100) ; @@ -100,7 +100,7 @@ class RooMCStudy : public TNamed { bool run(bool generate, bool fit, Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char* asciiFilePat) ; bool fitSample(RooAbsData* genSample) ; - RooFitResult* doFit(RooAbsData* genSample) ; + RooFit::OwningPtr doFit(RooAbsData* genSample) ; void calcPulls() ; @@ -125,7 +125,7 @@ class RooMCStudy : public TNamed { TList _genDataList ; // List of generated data sample TList _fitResList ; // List of RooFitResult fit output objects - std::unique_ptr _genParData; // List of of generated parameters of each sample + std::unique_ptr _genParData; // List of generated parameters of each sample std::unique_ptr _fitParData; // Data set of fit parameters of each sample RooLinkedList _fitOptList ; // Fit option command list bool _extendedGen ; // Add poisson term to number of events to generate? @@ -141,7 +141,7 @@ class RooMCStudy : public TNamed { std::list _modList ; ///< List of additional study modules ; // Utilities for modules ; - RooFitResult* refit(RooAbsData* genSample=nullptr) ; + RooFit::OwningPtr refit(RooAbsData* genSample=nullptr) ; void resetFitParams() ; void RecursiveRemove(TObject *obj) override; diff --git a/roofit/roofitcore/inc/RooMinimizer.h b/roofit/roofitcore/inc/RooMinimizer.h index 8ec3c3bb98211..373d204e10db3 100644 --- a/roofit/roofitcore/inc/RooMinimizer.h +++ b/roofit/roofitcore/inc/RooMinimizer.h @@ -44,15 +44,19 @@ class RooMinimizer : public TObject { public: /// Config argument to RooMinimizer ctor struct Config { + Config() {} - double recoverFromNaN = 10.; // RooAbsMinimizerFcn config - int printEvalErrors = 10; // RooAbsMinimizerFcn config - int doEEWall = 1; // RooAbsMinimizerFcn config - int offsetting = -1; // RooAbsMinimizerFcn config - const char *logf = nullptr; // RooAbsMinimizerFcn config - - // RooAbsMinimizerFcn config that can only be set in ctor, 0 means no parallelization (default), - // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which + + bool useGradient = true; // Use the gradient provided by the RooAbsReal, if there is one. + + double recoverFromNaN = 10.; // RooAbsMinimizerFcn config + int printEvalErrors = 10; // RooAbsMinimizerFcn config + int doEEWall = 1; // RooAbsMinimizerFcn config + int offsetting = -1; // RooAbsMinimizerFcn config + const char *logf = nullptr; // RooAbsMinimizerFcn config + + // RooAbsMinimizerFcn config that can only be set in ctor, 0 means no parallelization (default), + // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which // defaults to the number of available processors, n means parallelization with n CPU's int parallelize = 0; @@ -64,10 +68,10 @@ class RooMinimizer : public TObject { // argument is ignored when parallelize is 0 bool enableParallelDescent = false; - bool verbose = false; // local config - bool profile = false; // local config - bool timingAnalysis = false; // local config - std::string minimizerType = ""; // local config + bool verbose = false; // local config + bool profile = false; // local config + bool timingAnalysis = false; // local config + std::string minimizerType = ""; // local config private: int getDefaultWorkers(); }; @@ -80,7 +84,7 @@ class RooMinimizer : public TObject { enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 }; // Setters on _theFitter - void setStrategy(int strat); + void setStrategy(int istrat); void setErrorLevel(double level); void setEps(double eps); void setMaxIterations(int n); @@ -106,7 +110,7 @@ class RooMinimizer : public TObject { int minimize(const char *type, const char *alg = nullptr); - RooFitResult *save(const char *name = nullptr, const char *title = nullptr); + RooFit::OwningPtr save(const char *name = nullptr, const char *title = nullptr); RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0, double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50); @@ -129,12 +133,18 @@ class RooMinimizer : public TObject { std::string const &minimizerType() const { return _cfg.minimizerType; } static void cleanup(); - static RooFitResult *lastMinuitFit(); - static RooFitResult *lastMinuitFit(const RooArgList &varList); + static RooFit::OwningPtr lastMinuitFit(); + static RooFit::OwningPtr lastMinuitFit(const RooArgList &varList); void saveStatus(const char *label, int status) { - _statusHistory.push_back(std::pair(label, status)); + _statusHistory.emplace_back(label, status); + } + + /// Clears the Minuit status history. + void clearStatusHistory() + { + _statusHistory.clear(); } int evalCounter() const; @@ -151,6 +161,9 @@ class RooMinimizer : public TObject { private: friend class RooAbsMinimizerFcn; + friend class RooMinimizerFcn; + + std::unique_ptr makeEvalErrorContext() const; void addParamsToProcessTimer(); diff --git a/roofit/roofitcore/inc/RooMinuit.h b/roofit/roofitcore/inc/RooMinuit.h deleted file mode 100644 index 1bb80cfe270c7..0000000000000 --- a/roofit/roofitcore/inc/RooMinuit.h +++ /dev/null @@ -1,5 +0,0 @@ -#warning "The deprecated RooMinuit class was replaced by the more general RooMinimizer. \ -The RooMinuit class will be gone in ROOT 6.30! \ -Migrating to the RooMinimizer is easy because the interface is backwards compatible. - -#include "RooFitLegacy/RooMinuit.h" diff --git a/roofit/roofitcore/inc/RooMsgService.h b/roofit/roofitcore/inc/RooMsgService.h index f03c711116464..cec4735dc7c70 100644 --- a/roofit/roofitcore/inc/RooMsgService.h +++ b/roofit/roofitcore/inc/RooMsgService.h @@ -150,8 +150,8 @@ class RooMsgService : public TObject { static bool anyDebug() ; // User interface -- Add or delete reporting streams ; - Int_t addStream(RooFit::MsgLevel level, const RooCmdArg& arg1=RooCmdArg(), const RooCmdArg& arg2=RooCmdArg(), const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(), const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg()); + Int_t addStream(RooFit::MsgLevel level, const RooCmdArg& arg1={}, const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, const RooCmdArg& arg6={}); void deleteStream(Int_t id) ; StreamConfig& getStream(Int_t id) { return _streams[id] ; } @@ -203,9 +203,9 @@ class RooMsgService : public TObject { std::vector _streams ; std::stack > _streamsSaved ; - std::ostream* _devnull ; + std::unique_ptr _devnull ; - std::map _files ; + std::map> _files ; RooFit::MsgLevel _globMinLevel ; RooFit::MsgLevel _lastMsgLevel ; @@ -218,7 +218,7 @@ class RooMsgService : public TObject { RooMsgService() ; RooMsgService(const RooMsgService&) ; - RooWorkspace* _debugWorkspace ; + std::unique_ptr _debugWorkspace; Int_t _debugCode ; diff --git a/roofit/roofitcore/inc/RooMultiGenFunction.h b/roofit/roofitcore/inc/RooMultiGenFunction.h deleted file mode 100644 index cb94d3b4f93b4..0000000000000 --- a/roofit/roofitcore/inc/RooMultiGenFunction.h +++ /dev/null @@ -1,52 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_MULTI_GEN_FUNCTION -#define ROO_MULTI_GEN_FUNCTION - -#include "RooFunctor.h" -#include "Math/IFunction.h" - -class RooAbsReal ; -class RooArgList ; -class RooArgSet ; -class RooAbsFunc ; - -class RooMultiGenFunction : public ROOT::Math::IMultiGenFunction { - -public: - RooMultiGenFunction(const RooAbsFunc& func) ; - RooMultiGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters) ; - RooMultiGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters, const RooArgSet& nset) ; - RooMultiGenFunction(const RooMultiGenFunction& other) ; - ~RooMultiGenFunction() override ; - - ROOT::Math::IBaseFunctionMultiDim* Clone() const override { - return new RooMultiGenFunction(*this) ; - } - - unsigned int NDim() const override { return _ftor.nObs() ; } - -protected: - - double DoEval(const double*) const override ; - - RooFunctor _ftor ; - - ClassDef(RooMultiGenFunction,0) // Export RooAbsReal as functor -}; - -#endif - diff --git a/roofit/roofitcore/inc/RooMultiVarGaussian.h b/roofit/roofitcore/inc/RooMultiVarGaussian.h index bf65a47135719..9f8c5efaa7d3b 100644 --- a/roofit/roofitcore/inc/RooMultiVarGaussian.h +++ b/roofit/roofitcore/inc/RooMultiVarGaussian.h @@ -32,10 +32,10 @@ class RooMultiVarGaussian : public RooAbsPdf { public: RooMultiVarGaussian() {} ; - RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec, const RooArgList& mu, const TMatrixDSym& covMatrix) ; + RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec, const RooArgList& mu, const TMatrixDBase& covMatrix) ; RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec, const RooFitResult& fr, bool reduceToConditional=true) ; - RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec, const TVectorD& mu, const TMatrixDSym& covMatrix) ; - RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec,const TMatrixDSym& covMatrix) ; + RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec, const TVectorD& mu, const TMatrixDBase& covMatrix) ; + RooMultiVarGaussian(const char *name, const char *title, const RooArgList& xvec,const TMatrixDBase& covMatrix) ; void setAnaIntZ(double z) { _z = z ; } RooMultiVarGaussian(const RooMultiVarGaussian& other, const char* name=nullptr) ; @@ -50,6 +50,8 @@ class RooMultiVarGaussian : public RooAbsPdf { void generateEvent(Int_t code) override; const TMatrixDSym& covarianceMatrix() const { return _cov ; } + const RooArgList& xVec() const { return _x;} + const RooArgList& muVec() const { return _mu; } class AnaIntData { public: @@ -71,16 +73,14 @@ class RooMultiVarGaussian : public RooAbsPdf { class BitBlock { public: - BitBlock() : b0(0), b1(0), b2(0), b3(0) {} ; - void setBit(Int_t ibit) ; bool getBit(Int_t ibit) ; - bool operator==(const BitBlock& other) ; + friend bool operator==(BitBlock const& lhs, BitBlock const& rhs); - Int_t b0 ; - Int_t b1 ; - Int_t b2 ; - Int_t b3 ; + Int_t b0 = 0; + Int_t b1 = 0; + Int_t b2 = 0; + Int_t b3 = 0; } ; static void blockDecompose(const TMatrixD& input, const std::vector& map1, const std::vector& map2, TMatrixDSym& S11, TMatrixD& S12, TMatrixD& S21, TMatrixDSym& S22) ; diff --git a/roofit/roofitcore/inc/RooNLLVar.h b/roofit/roofitcore/inc/RooNLLVar.h index b5ef5017ab7f4..fabe2bf713c9f 100644 --- a/roofit/roofitcore/inc/RooNLLVar.h +++ b/roofit/roofitcore/inc/RooNLLVar.h @@ -22,20 +22,14 @@ #include #include -class RooRealSumPdf ; -namespace RooBatchCompute { -struct RunContext; -} - class RooNLLVar : public RooAbsOptTestStatistic { public: // Constructors, assignment etc - RooNLLVar(); RooNLLVar(const char *name, const char* title, RooAbsPdf& pdf, RooAbsData& data, - const RooCmdArg& arg1=RooCmdArg::none(), const RooCmdArg& arg2=RooCmdArg::none(),const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none(), - const RooCmdArg& arg7=RooCmdArg::none(), const RooCmdArg& arg8=RooCmdArg::none(),const RooCmdArg& arg9=RooCmdArg::none()) ; + const RooCmdArg& arg1={}, const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; RooNLLVar(const char *name, const char *title, RooAbsPdf& pdf, RooAbsData& data, bool extended, @@ -57,23 +51,15 @@ class RooNLLVar : public RooAbsOptTestStatistic { double defaultErrorLevel() const override { return 0.5 ; } - void batchMode(bool on = true) { - _batchEvaluations = on; - } - - void templateRatioOffset(bool on = true) { - _templateRatioOffset = on; - } + void enableBinOffsetting(bool on = true); using ComputeResult = std::pair, double>; - static RooNLLVar::ComputeResult computeBatchedFunc(const RooAbsPdf *pdfClone, RooAbsData *dataClone, - std::unique_ptr &evalData, - RooArgSet *normSet, bool weightSq, std::size_t stepSize, - std::size_t firstEvent, std::size_t lastEvent); static RooNLLVar::ComputeResult computeScalarFunc(const RooAbsPdf *pdfClone, RooAbsData *dataClone, RooArgSet *normSet, bool weightSq, std::size_t stepSize, std::size_t firstEvent, - std::size_t lastEvent, bool templateRatioOffset=false); + std::size_t lastEvent, RooAbsPdf const* offsetPdf = nullptr); + + bool setData(RooAbsData& data, bool cloneData=true) override; protected: @@ -83,19 +69,17 @@ class RooNLLVar : public RooAbsOptTestStatistic { static RooArgSet _emptySet ; // Supports named argument constructor private: - ComputeResult computeBatched(std::size_t stepSize, std::size_t firstEvent, std::size_t lastEvent) const; ComputeResult computeScalar(std::size_t stepSize, std::size_t firstEvent, std::size_t lastEvent) const; bool _extended{false}; - bool _batchEvaluations{false}; - bool _templateRatioOffset{false}; + bool _doBinOffset{false}; bool _weightSq{false}; ///< Apply weights squared? mutable bool _first{true}; /// _offsetSaveW2{0.0}; /// _binw ; /// _evalData; /// _offsetPdf; /// - -#include -#include -#include -#include -#include -#include - -/// Little struct that can pack a float into the unused bits of the mantissa of a -/// NaN double. This can be used to transport information about violation -/// of function definition ranges, negative PDFs or other computation -/// problems in RooFit. -/// To separate NaNs that contain packed floats from regular NaNs, a tag is -/// written into the upper bits of the mantissa. If this tag is found, a payload -/// can be recovered. Otherwise, the NaN is assumed to originate from other sources -/// than a RooFit class that wants to signal to the minimiser. -struct RooNaNPacker { - double _payload; - - // In double-valued NaNs, on can abuse the lowest 51 bit for payloads. - // We use this to pack a float into the lowest 32 bits, which leaves - // 19-bit to include a magic tag to tell NaNs with payload from ordinary - // NaNs: - static constexpr uint64_t magicTagMask = 0x3ffff00000000; - static constexpr uint64_t magicTag = 0x321ab00000000; - - constexpr RooNaNPacker() : - _payload(0.) { } - - /// Create NaN with a packed floating point number. - explicit RooNaNPacker(float value) : - _payload(packFloatIntoNaN(value)) { } - - /// Pack float into mantissa of NaN. - void setPayload(float payload) { - _payload = packFloatIntoNaN(payload); - - if (!std::isnan(_payload)) { - // Big-endian machine or other. Just return NaN. - warn(); - _payload = std::numeric_limits::quiet_NaN(); - } - } - - /// Accumulate a packed float from another NaN into `this`. - void accumulate(double val) { - *this += unpackNaN(val); - } - - /// Unpack floats from NaNs, and sum the packed values. - template - static double accumulatePayloads(It_t begin, It_t end) { - double sum = std::accumulate(begin, end, 0.f, [](float acc, double val) { - return acc += unpackNaN(val); - }); - - return packFloatIntoNaN(sum); - } - - /// Add to the packed float. - RooNaNPacker& operator+=(float val) { - setPayload(getPayload() + val); - return *this; - } - - /// Multiply the packed float. - RooNaNPacker& operator*=(float val) { - setPayload(getPayload() * val); - return *this; - } - - /// Retrieve packed float. Returns zero if number is not NaN - /// or if float wasn't packed by this class. - float getPayload() const { - return isNaNWithPayload(_payload) ? unpackNaN(_payload) : 0.; - } - - /// Retrieve a NaN with the current float payload packed into the mantissa. - double getNaNWithPayload() const { - return _payload; - } - - /// Test if this struct has a float packed into its mantissa. - bool isNaNWithPayload() const { - return isNaNWithPayload(_payload); - } - - /// Test if `val` has a float packed into its mantissa. - static bool isNaNWithPayload(double val) { - uint64_t tmp; - std::memcpy(&tmp, &val, sizeof(uint64_t)); - return std::isnan(val) && (tmp & magicTagMask) == magicTag; - } - - /// Pack float into mantissa of a NaN. Adds a tag to the - /// upper bits of the mantissa, so a "normal" NaN can be - /// differentiated from a NaN with a payload. - static double packFloatIntoNaN(float payload) { - double result = std::numeric_limits::quiet_NaN(); - uint64_t tmp; - std::memcpy(&tmp, &result, sizeof(uint64_t)); - tmp |= magicTag; - std::memcpy(&tmp, &payload, sizeof(float)); - std::memcpy(&result, &tmp, sizeof(uint64_t)); - return result; - } - - /// If `val` is NaN and a this NaN has been tagged as containing - /// a payload, unpack the float from the mantissa. - /// Return 0 otherwise. - static float unpackNaN(double val) { - float tmp; - std::memcpy(&tmp, &val, sizeof(float)); - return isNaNWithPayload(val) ? tmp : 0.; - } - - /// Warn that packing only works on little-endian machines. - static void warn() { - static bool haveWarned = false; - if (!haveWarned) - Warning("RooNaNPacker", "Fast recovery from undefined function values only implemented for little-endian machines." - " If necessary, request an extension of functionality on https://root.cern"); - haveWarned = true; - } -}; - - -#endif /* ROOFIT_ROOFITCORE_INC_ROONANPACKER_H_ */ diff --git a/roofit/roofitcore/inc/RooNormSetCache.h b/roofit/roofitcore/inc/RooNormSetCache.h index ca598d65be231..5ec8b1f617318 100644 --- a/roofit/roofitcore/inc/RooNormSetCache.h +++ b/roofit/roofitcore/inc/RooNormSetCache.h @@ -18,58 +18,21 @@ #include -#include -#include +#include +#include #include class RooNormSetCache { -private: - class Pair { - public: - using Value_t = RooFit::UniqueId::Value_t; - Pair(const RooArgSet* set1, const RooArgSet* set2) - : _pair{RooFit::getUniqueId(set1), RooFit::getUniqueId(set2)} {} - bool operator==(Pair const &other) const { return _pair == other._pair; } - bool operator<(Pair const &other) const { return _pair < other._pair; } - - Value_t const& first() const { return _pair.first; } - Value_t const& second() const { return _pair.second; } - private: - std::pair _pair; - }; - - typedef std::vector PairVectType; - typedef std::map PairIdxMapType; public: RooNormSetCache(std::size_t max = 32) : _max(max) {} - void add(const RooArgSet* set1, const RooArgSet* set2 = nullptr); - - inline int index(const RooArgSet* set1, const RooArgSet* set2 = nullptr, - const TNamed* set2RangeName = nullptr) - { - // Match range name first - if (set2RangeName != _set2RangeName) return -1; - const Pair pair(set1, set2); - PairIdxMapType::const_iterator it = _pairToIdx.lower_bound(pair); - if (_pairToIdx.end() != it && it->first == pair) { - return it->second; - } - return -1; - } - inline bool contains(const RooArgSet* set1, const RooArgSet* set2 = nullptr, const TNamed* set2RangeName = nullptr) - { return (index(set1,set2,set2RangeName) >= 0); } - - inline bool containsSet1(const RooArgSet* set1) { - const Pair pair(set1, (const RooArgSet*)0); - PairIdxMapType::const_iterator it = _pairToIdx.lower_bound(pair); - if (_pairToIdx.end() != it && it->first.first() == RooFit::getUniqueId(set1)) - return true; - return false; + // Match range name first + if (set2RangeName != _set2RangeName) return false; + return _pairSet.find({RooFit::getUniqueId(set1), RooFit::getUniqueId(set2)}) != _pairSet.end(); } const std::string& nameSet1() const { return _name1; } @@ -80,16 +43,17 @@ class RooNormSetCache { bool autoRefill = true); void clear(); - std::size_t entries() const { return _pairs.size(); } - - void initialize(const RooNormSetCache& other) { clear(); *this = other; } private: - PairVectType _pairs; ///::Value_t; + using Pair_t = std::pair; + + std::deque _pairs; /// _pairSet; /// _conv ; /// _integrator ; /// + class RooNumIntConfig ; class RooAbsFunc ; @@ -30,21 +33,36 @@ typedef void (*RooNumIntInitializerFunc)(RooNumIntFactory&) ; class RooNumIntFactory : public TObject { public: + using Creator = std::function(RooAbsFunc const& function, const RooNumIntConfig& config)>; + static RooNumIntFactory& instance() ; - ~RooNumIntFactory() override = default; - bool storeProtoIntegrator(RooAbsIntegrator* proto, const RooArgSet& defConfig, const char* depName="") ; - const RooAbsIntegrator* getProtoIntegrator(const char* name) const; - const char* getDepIntegratorName(const char* name) const; + bool registerPlugin(std::string const &name, Creator const &creator, const RooArgSet &defConfig, bool canIntegrate1D, + bool canIntegrate2D, bool canIntegrateND, bool canIntegrateOpenEnded, const char *depName = ""); - RooAbsIntegrator* createIntegrator(RooAbsFunc& func, const RooNumIntConfig& config, Int_t ndim=0, bool isBinned=false) const; + std::unique_ptr createIntegrator(RooAbsFunc& func, const RooNumIntConfig& config, Int_t ndim=0, bool isBinned=false) const; private: friend class RooNumIntConfig ; - std::map,std::string> > _map; + struct PluginInfo { + Creator creator; + bool canIntegrate1D = false; + bool canIntegrate2D = false; + bool canIntegrateND = false; + bool canIntegrateOpenEnded = false; + std::string depName; + }; + + PluginInfo const* getPluginInfo(const char* name) const + { + auto item = _map.find(name); + return item == _map.end() ? nullptr : &item->second; + } + + std::map _map; RooNumIntFactory() {} // NOLINT: not allowed to use = default because of TObject::kIsOnHeap detection, see ROOT-10300 RooNumIntFactory(const RooNumIntFactory& other) = delete; @@ -56,5 +74,3 @@ class RooNumIntFactory : public TObject { }; #endif - - diff --git a/roofit/roofitcore/inc/RooNumRunningInt.h b/roofit/roofitcore/inc/RooNumRunningInt.h index c54ceaaa19f08..f86672c0feb00 100644 --- a/roofit/roofitcore/inc/RooNumRunningInt.h +++ b/roofit/roofitcore/inc/RooNumRunningInt.h @@ -47,15 +47,15 @@ class RooNumRunningInt : public RooAbsCachedReal { const char* binningName() const override { return _binningName.c_str() ; } FuncCacheElem* createCache(const RooArgSet* nset) const override ; const char* inputBaseName() const override ; - RooArgSet* actualObservables(const RooArgSet& nset) const override ; - RooArgSet* actualParameters(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualObservables(const RooArgSet& nset) const override ; + RooFit::OwningPtr actualParameters(const RooArgSet& nset) const override ; void fillCacheObject(FuncCacheElem& cacheFunc) const override ; double evaluate() const override ; const char* payloadUniqueSuffix() const override { return func.arg().aggregateCacheUniqueSuffix() ; } RooRealProxy func ; ///< Proxy to functions whose running integral is calculated - RooRealProxy x ; ///< Intergrated observable + RooRealProxy x ; ///< Integrated observable std::string _binningName ; ///< Name of binning to be used for cache histogram private: diff --git a/roofit/roofitcore/inc/RooNumber.h b/roofit/roofitcore/inc/RooNumber.h index 2165b105427c6..2b6a265352136 100644 --- a/roofit/roofitcore/inc/RooNumber.h +++ b/roofit/roofitcore/inc/RooNumber.h @@ -16,20 +16,34 @@ #ifndef ROO_NUMBER #define ROO_NUMBER -#include "Rtypes.h" +#include +#include class RooNumber { public: + /// Return internal infinity representation. + constexpr static double infinity() { return std::numeric_limits::infinity(); } + /// Return true if x is infinite by RooNumber internal specification. + constexpr static int isInfinite(double x) { return (x >= +infinity()) ? +1 : ((x <= -infinity()) ? -1 : 0); } - virtual ~RooNumber() {} ; + /// Set the relative epsilon that is used by range checks in RooFit, + /// e.g., in RooAbsRealLValue::inRange(). + inline static void setRangeEpsRel(double epsRel) { staticRangeEpsRel() = epsRel; } + /// Get the relative epsilon that is used by range checks in RooFit, + /// e.g., in RooAbsRealLValue::inRange(). + inline static double rangeEpsRel() { return staticRangeEpsRel(); } - static double infinity() ; - static Int_t isInfinite(double x) ; + /// Set the absolute epsilon that is used by range checks in RooFit, + /// e.g., in RooAbsRealLValue::inRange(). + inline static void setRangeEpsAbs(double epsRel) { staticRangeEpsAbs() = epsRel; } + /// Get the absolute epsilon that is used by range checks in RooFit, + /// e.g., in RooAbsRealLValue::inRange(). + inline static double rangeEpsAbs() { return staticRangeEpsAbs(); } + static std::string toString(double x); - private: - static double _Infinity ; - - ClassDef(RooNumber,0) // wrapper class for portable numerics +private: + static double &staticRangeEpsRel(); + static double &staticRangeEpsAbs(); }; #endif diff --git a/roofit/roofitcore/inc/RooObjCacheManager.h b/roofit/roofitcore/inc/RooObjCacheManager.h index 8b1ea6968705b..f3248a04c1f00 100644 --- a/roofit/roofitcore/inc/RooObjCacheManager.h +++ b/roofit/roofitcore/inc/RooObjCacheManager.h @@ -18,7 +18,6 @@ #include "Rtypes.h" -#include "RooNormSetCache.h" #include "RooAbsReal.h" #include "RooArgSet.h" #include "RooArgList.h" diff --git a/roofit/roofitcore/inc/RooPlot.h b/roofit/roofitcore/inc/RooPlot.h index 7f63507eaf041..86a71753529f4 100644 --- a/roofit/roofitcore/inc/RooPlot.h +++ b/roofit/roofitcore/inc/RooPlot.h @@ -20,7 +20,7 @@ #include "TNamed.h" #include -#include +#include class TH1 ; @@ -108,7 +108,7 @@ class RooPlot : public TNamed, public RooPrintable { // container management const char* nameOf(Int_t idx) const ; - TObject *findObject(const char *name, const TClass* clas=nullptr) const; + TObject *findObject(const char *name, const TClass* tClass=nullptr) const; TObject* getObject(Int_t idx) const ; Stat_t numItems() const {return _items.size();} @@ -204,6 +204,8 @@ class RooPlot : public TNamed, public RooPrintable { static void fillItemsFromTList(Items & items, TList const& tlist); + void createInternalPlotVarClone(); + protected: RooPlot(const RooPlot& other) = delete; // cannot be copied @@ -227,7 +229,7 @@ class RooPlot : public TNamed, public RooPrintable { void updateYAxis(double ymin, double ymax, const char *label= ""); void updateFitRangeNorm(const TH1* hist); - void updateFitRangeNorm(const RooPlotable* rp, bool refeshNorm=false); + void updateFitRangeNorm(const RooPlotable* rp, bool refreshNorm=false); TH1* _hist = nullptr; ///< Histogram that we uses as basis for drawing the content Items _items; ///< A list of the items we contain. diff --git a/roofit/roofitcore/inc/RooPlotable.h b/roofit/roofitcore/inc/RooPlotable.h index 127165a9dd351..2ec957bc77ec1 100644 --- a/roofit/roofitcore/inc/RooPlotable.h +++ b/roofit/roofitcore/inc/RooPlotable.h @@ -25,9 +25,6 @@ class RooArgSet; class RooPlotable : public RooPrintable { public: - inline RooPlotable() : _ymin(0), _ymax(0), _normValue(0) { } - inline ~RooPlotable() override { } - inline const char* getYAxisLabel() const { return _yAxisLabel.Data(); } inline void setYAxisLabel(const char *label) { _yAxisLabel= label; } inline void updateYAxisLimits(double y) { @@ -52,7 +49,9 @@ class RooPlotable : public RooPrintable { TObject *crossCast(); protected: TString _yAxisLabel; - double _ymin, _ymax, _normValue; + double _ymin = 0.0; + double _ymax = 0.0; + double _normValue = 0.0; ClassDefOverride(RooPlotable,1) // Abstract interface for plotable objects in a RooPlot }; diff --git a/roofit/roofitcore/inc/RooPolyFunc.h b/roofit/roofitcore/inc/RooPolyFunc.h old mode 100755 new mode 100644 index 80ce29d8eb768..c7fdbc53666a9 --- a/roofit/roofitcore/inc/RooPolyFunc.h +++ b/roofit/roofitcore/inc/RooPolyFunc.h @@ -17,6 +17,7 @@ #define RooFit_RooFit_RooPolyFunc_h #include "RooAbsReal.h" +#include "RooRealVar.h" #include "RooListProxy.h" #include @@ -36,6 +37,16 @@ class RooPolyFunc : public RooAbsReal { TObject *clone(const char *newname) const override { return new RooPolyFunc(*this, newname); } std::string asString() const; + inline const RooArgList &variables() const { return _vars; } + inline const std::vector> &terms() const { return _terms; } + inline RooRealVar *getCoefficient(const RooArgList &term) + { + return static_cast(term.at(term.size() - 1)); + } + inline RooRealVar *getExponent(const RooArgList &term, RooRealVar *v) + { + return static_cast(term.at(_vars.index(v))); + } void addTerm(double coefficient); void addTerm(double coefficient, const RooAbsCollection &exponents); @@ -43,11 +54,8 @@ class RooPolyFunc : public RooAbsReal { void addTerm(double coefficient, const RooAbsReal &var1, int exp1, const RooAbsReal &var2, int exp2); static std::unique_ptr - taylorExpand(const char *name, const char *title, RooAbsReal &func, const RooAbsCollection &observables, - std::vector const &observableValues, int order = 1, double eps1 = 1e-6, double eps2 = 1e-3); - static std::unique_ptr taylorExpand(const char *name, const char *title, RooAbsReal &func, - const RooAbsCollection &observables, double observablesValue = 0.0, - int order = 1, double eps = 1e-6, double eps2 = 1e-3); + taylorExpand(const char *name, const char *title, RooAbsReal &func, const RooArgList &observables, int order = 1, + std::vector const &observableValues = {}, double eps1 = 1e-6, double eps2 = 1e-3); protected: void setCoordinate(const RooAbsCollection &observables, std::vector const &observableValues); diff --git a/roofit/roofitcore/inc/RooPolyVar.h b/roofit/roofitcore/inc/RooPolyVar.h index 62c3602009abb..9aa1c20481f9f 100644 --- a/roofit/roofitcore/inc/RooPolyVar.h +++ b/roofit/roofitcore/inc/RooPolyVar.h @@ -16,41 +16,50 @@ #ifndef ROO_POLY_VAR #define ROO_POLY_VAR -#include - -#include "RooAbsReal.h" -#include "RooRealProxy.h" -#include "RooListProxy.h" +#include +#include +#include -class RooRealVar; -class RooArgList ; +#include class RooPolyVar : public RooAbsReal { public: + RooPolyVar() {} + RooPolyVar(const char *name, const char *title, RooAbsReal &x); + RooPolyVar(const char *name, const char *title, RooAbsReal &_x, const RooArgList &_coefList, Int_t lowestOrder = 0); - RooPolyVar() ; - RooPolyVar(const char* name, const char* title, RooAbsReal& x) ; - RooPolyVar(const char *name, const char *title, - RooAbsReal& _x, const RooArgList& _coefList, Int_t lowestOrder=0) ; + RooPolyVar(const RooPolyVar &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooPolyVar(*this, newname); } - RooPolyVar(const RooPolyVar& other, const char *name = nullptr); - TObject* clone(const char* newname) const override { return new RooPolyVar(*this, newname); } - ~RooPolyVar() override ; + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName = nullptr) const override; + double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override; - Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; - double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + std::string buildCallToAnalyticIntegral(Int_t code, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const override; protected: + RooRealProxy _x; + RooListProxy _coefList; + Int_t _lowestOrder = 0; + + mutable std::vector _wksp; /// _wksp; /// &wksp, RooListProxy const &coefList); - ClassDefOverride(RooPolyVar,1) // Polynomial function + ClassDefOverride(RooPolyVar, 1) // Polynomial function }; #endif diff --git a/roofit/roofitcore/inc/RooProdGenContext.h b/roofit/roofitcore/inc/RooProdGenContext.h index 859d9cc261e5d..bfa4aaf4585fd 100644 --- a/roofit/roofitcore/inc/RooProdGenContext.h +++ b/roofit/roofitcore/inc/RooProdGenContext.h @@ -58,10 +58,10 @@ class RooProdGenContext : public RooAbsGenContext { bool _ccdRefresh ; double * _ccdTable ; const RooProdPdf *_pdf ; ///< Original PDF - std::list _gcList ; ///< List of component generator contexts + std::list> _gcList ; ///< List of component generator contexts RooArgSet _ownedMultiProds ; ///< Owned auxiliary multi-term product PDFs - ClassDefOverride(RooProdGenContext,0) // Context for efficient generation of a a dataset from a RooProdPdf + ClassDefOverride(RooProdGenContext,0) // Context for efficient generation of a dataset from a RooProdPdf }; #endif diff --git a/roofit/roofitcore/inc/RooProdPdf.h b/roofit/roofitcore/inc/RooProdPdf.h index 900e17b615e44..3a86953cff171 100644 --- a/roofit/roofitcore/inc/RooProdPdf.h +++ b/roofit/roofitcore/inc/RooProdPdf.h @@ -40,16 +40,16 @@ class RooProdPdf : public RooAbsPdf { RooProdPdf(const char* name, const char* title, const RooArgSet& fullPdfSet, const RooLinkedList& cmdArgList) ; RooProdPdf(const char* name, const char* title, const RooArgSet& fullPdfSet, - const RooCmdArg& arg1 , const RooCmdArg& arg2=RooCmdArg(), - const RooCmdArg& arg3=RooCmdArg(), const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(), const RooCmdArg& arg8=RooCmdArg()) ; + const RooCmdArg& arg1 , const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; RooProdPdf(const char* name, const char* title, - const RooCmdArg& arg1, const RooCmdArg& arg2=RooCmdArg(), - const RooCmdArg& arg3=RooCmdArg(), const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(), const RooCmdArg& arg8=RooCmdArg()) ; + const RooCmdArg& arg1, const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}) ; RooProdPdf(const RooProdPdf& other, const char* name=nullptr) ; TObject* clone(const char* newname) const override { return new RooProdPdf(*this,newname) ; } @@ -62,9 +62,13 @@ class RooProdPdf : public RooAbsPdf { ExtendMode extendMode() const override ; double expectedEvents(const RooArgSet* nset) const override ; + std::unique_ptr createExpectedEventsFunc(const RooArgSet* nset) const override; const RooArgList& pdfList() const { return _pdfList ; } + void addPdfs(RooAbsCollection const& pdfs); + void removePdfs(RooAbsCollection const& pdfs); + Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const override; void initGenerator(Int_t code) override ; void generateEvent(Int_t code) override; @@ -93,12 +97,12 @@ class RooProdPdf : public RooAbsPdf { RooArgSet* findPdfNSet(RooAbsPdf const& pdf) const ; - void writeCacheToStream(std::ostream& os, RooArgSet const* nset) const; - - std::unique_ptr fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const override; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; private: + std::unique_ptr fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const; + double evaluate() const override ; std::unique_ptr makeCondPdfRatioCorr(RooAbsReal& term, const RooArgSet& termNset, const RooArgSet& termImpSet, const char* normRange, const char* refRange) const ; @@ -154,10 +158,10 @@ class RooProdPdf : public RooAbsPdf { CacheElem* getCacheElem(RooArgSet const* nset) const ; void rearrangeProduct(CacheElem&) const; - RooAbsReal* specializeIntegral(RooAbsReal& orig, const char* targetRangeName) const ; - RooAbsReal* specializeRatio(RooFormulaVar& input, const char* targetRangeName) const ; + std::unique_ptr specializeIntegral(RooAbsReal& orig, const char* targetRangeName) const ; + std::unique_ptr specializeRatio(RooFormulaVar& input, const char* targetRangeName) const ; double calculate(const RooProdPdf::CacheElem& cache, bool verbose=false) const ; - void calculateBatch(const RooProdPdf::CacheElem& cache, cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const; + void calculateBatch(RooAbsArg const* caller, const RooProdPdf::CacheElem &cache, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const; friend class RooProdGenContext ; @@ -183,7 +187,7 @@ class RooProdPdf : public RooAbsPdf { private: - void removePdfs(RooArgSet const& pdfs); + ClassDefOverride(RooProdPdf,6) // PDF representing a product of PDFs }; diff --git a/roofit/roofitcore/inc/RooProduct.h b/roofit/roofitcore/inc/RooProduct.h index ea38c8a3ac29b..ec4d89a262e2e 100644 --- a/roofit/roofitcore/inc/RooProduct.h +++ b/roofit/roofitcore/inc/RooProduct.h @@ -47,6 +47,9 @@ class RooProduct : public RooAbsReal { RooArgList components() { RooArgList tmp(_compRSet) ; tmp.add(_compCSet) ; return tmp ; } + const RooArgList& realComponents() const { return _compRSet; } + const RooArgList& categorialComponents() const { return _compCSet; } + ~RooProduct() override ; class ProdMap ; @@ -60,6 +63,7 @@ class RooProduct : public RooAbsReal { CacheMode canNodeBeCached() const override { return RooAbsArg::NotAdvised ; } ; void setCacheAndTrackHints(RooArgSet&) override ; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: void ioStreamerPass2() override ; @@ -80,7 +84,7 @@ class RooProduct : public RooAbsReal { double calculate(const RooArgList& partIntList) const; double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; const char* makeFPName(const char *pfx,const RooArgSet& terms) const ; ProdMap* groupProductTerms(const RooArgSet&) const; diff --git a/roofit/roofitcore/inc/RooProfileLL.h b/roofit/roofitcore/inc/RooProfileLL.h index 312393160a428..084b96d182e78 100644 --- a/roofit/roofitcore/inc/RooProfileLL.h +++ b/roofit/roofitcore/inc/RooProfileLL.h @@ -35,7 +35,7 @@ class RooProfileLL : public RooAbsReal { const RooArgSet& bestFitParams() const ; const RooArgSet& bestFitObs() const ; - RooAbsReal* createProfile(const RooArgSet& paramsOfInterest) override ; + RooFit::OwningPtr createProfile(const RooArgSet& paramsOfInterest) override ; bool redirectServersHook(const RooAbsCollection& /*newServerList*/, bool /*mustReplaceAll*/, bool /*nameChange*/, bool /*isRecursive*/) override ; @@ -52,16 +52,16 @@ class RooProfileLL : public RooAbsReal { RooRealProxy _nll ; ///< Input -log(L) function RooSetProxy _obs ; ///< Parameters of profile likelihood RooSetProxy _par ; ///< Marginalised parameters of likelihood - bool _startFromMin ; ///< Always start minimization for global minimum? + bool _startFromMin = true; ///< Always start minimization for global minimum? mutable std::unique_ptr _minimizer = nullptr ; /// _paramFixed ; ///< Parameter constant status at last time of use - mutable Int_t _neval ; ///< Number evaluations used in last minimization + mutable Int_t _neval = 0; ///< Number evaluations used in last minimization double evaluate() const override ; diff --git a/roofit/roofitcore/inc/RooProjectedPdf.h b/roofit/roofitcore/inc/RooProjectedPdf.h index 031a1301f216c..7ad5a472cb6c0 100644 --- a/roofit/roofitcore/inc/RooProjectedPdf.h +++ b/roofit/roofitcore/inc/RooProjectedPdf.h @@ -41,6 +41,12 @@ class RooProjectedPdf : public RooAbsPdf { void printMetaArgs(std::ostream& os) const override ; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + + // Handle case of projecting an Extended pdf + double expectedEvents(const RooArgSet* nset) const override { return static_cast(intpdf.absArg())->expectedEvents(nset); } + ExtendMode extendMode() const override { return static_cast(intpdf.absArg())->extendMode(); } + protected: diff --git a/roofit/roofitcore/inc/RooRatio.h b/roofit/roofitcore/inc/RooRatio.h index da408304160bd..e324619b8f8be 100644 --- a/roofit/roofitcore/inc/RooRatio.h +++ b/roofit/roofitcore/inc/RooRatio.h @@ -49,7 +49,7 @@ class RooRatio : public RooAbsReal { protected: double evaluate() const override; - void computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const&) const override; inline bool canComputeBatchWithCuda() const override { return true; } RooRealProxy _numerator; diff --git a/roofit/roofitcore/inc/RooRealAnalytic.h b/roofit/roofitcore/inc/RooRealAnalytic.h deleted file mode 100644 index 1f1543471f624..0000000000000 --- a/roofit/roofitcore/inc/RooRealAnalytic.h +++ /dev/null @@ -1,40 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooRealAnalytic.h,v 1.8 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_REAL_ANALYTIC -#define ROO_REAL_ANALYTIC - -#include "RooRealBinding.h" - -class RooRealAnalytic : public RooRealBinding { -public: - inline RooRealAnalytic(const RooAbsReal &func, const RooArgSet &vars, Int_t code, const RooArgSet* normSet=nullptr, const TNamed* rangeName=nullptr) : - RooRealBinding(func,vars,normSet,rangeName), _code(code) { } - inline ~RooRealAnalytic() override { } - - double operator()(const double xvector[]) const override; - RooSpan getValues(std::vector> coordinates) const override; - -protected: - Int_t _code; - -private: - mutable std::unique_ptr> _batchBuffer; /// + #include #include class RooAbsRealLValue; class RooAbsReal; class RooArgSet; -namespace RooBatchCompute{ struct RunContext; } class RooRealBinding : public RooAbsFunc { public: @@ -33,8 +34,6 @@ class RooRealBinding : public RooAbsFunc { ~RooRealBinding() override; double operator()(const double xvector[]) const override; - virtual RooSpan getValues(std::vector> coordinates) const; - RooSpan getValuesOfBoundFunction(RooBatchCompute::RunContext& evalData) const; double getMinLimit(UInt_t dimension) const override; double getMaxLimit(UInt_t dimension) const override; @@ -56,13 +55,12 @@ class RooRealBinding : public RooAbsFunc { const RooArgSet *_nset; mutable bool _xvecValid; bool _clipInvalid ; - mutable double* _xsave ; + mutable std::vector _xsave ; const TNamed* _rangeName ; /// _compList ; /// _compSave ; /// _evalData; ///< Memory for batch evaluations ClassDefOverride(RooRealBinding,0) // Function binding to RooAbsReal object }; diff --git a/roofit/roofitcore/inc/RooRealIntegral.h b/roofit/roofitcore/inc/RooRealIntegral.h index 5fc4458aebab5..1ff706eda42de 100644 --- a/roofit/roofitcore/inc/RooRealIntegral.h +++ b/roofit/roofitcore/inc/RooRealIntegral.h @@ -54,7 +54,7 @@ class RooRealIntegral : public RooAbsReal { const RooArgSet& anaIntVars() const { return _anaList ; } RooArgSet intVars() const { RooArgSet tmp(_sumList) ; tmp.add(_intList) ; tmp.add(_anaList) ; tmp.add(_facList) ; return tmp ; } - const char* intRange() { return _rangeName ? _rangeName->GetName() : nullptr ; } + const char* intRange() const { return _rangeName ? _rangeName->GetName() : nullptr ; } const RooAbsReal& integrand() const { return *_function; } void setCacheNumeric(bool flag) { @@ -76,13 +76,14 @@ class RooRealIntegral : public RooAbsReal { return _function->plotSamplingHint(obs,xlo,xhi) ; } - RooAbsReal* createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const override ; + RooFit::OwningPtr createIntegral(const RooArgSet& iset, const RooArgSet* nset=nullptr, const RooNumIntConfig* cfg=nullptr, const char* rangeName=nullptr) const override ; void setAllowComponentSelection(bool allow); bool getAllowComponentSelection() const; - std::unique_ptr fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const override; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: mutable bool _valid = false; diff --git a/roofit/roofitcore/inc/RooRealSumFunc.h b/roofit/roofitcore/inc/RooRealSumFunc.h index 20d3663855414..29a765b45191f 100644 --- a/roofit/roofitcore/inc/RooRealSumFunc.h +++ b/roofit/roofitcore/inc/RooRealSumFunc.h @@ -58,9 +58,9 @@ class RooRealSumFunc : public RooAbsReal { CacheMode canNodeBeCached() const override { return RooAbsArg::NotAdvised; }; void setCacheAndTrackHints(RooArgSet &) override; - std::unique_ptr fillNormSetForServer(RooArgSet const& /*normSet*/, RooAbsArg const& /*server*/) const override { - return std::make_unique(); - } + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: mutable RooObjCacheManager _normIntMgr; //! The integration cache manager diff --git a/roofit/roofitcore/inc/RooRealSumPdf.h b/roofit/roofitcore/inc/RooRealSumPdf.h index af38d44534037..27eb80bec2489 100644 --- a/roofit/roofitcore/inc/RooRealSumPdf.h +++ b/roofit/roofitcore/inc/RooRealSumPdf.h @@ -36,7 +36,7 @@ class RooRealSumPdf : public RooAbsPdf { double evaluate() const override ; bool checkObservables(const RooArgSet* nset) const override ; - void computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const&) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; bool forceAnalyticalInt(const RooAbsArg& arg) const override { return arg.isFundamental() ; } Int_t getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& numVars, const RooArgSet* normSet, const char* rangeName=nullptr) const override ; @@ -68,9 +68,11 @@ class RooRealSumPdf : public RooAbsPdf { CacheMode canNodeBeCached() const override { return RooAbsArg::NotAdvised ; } ; void setCacheAndTrackHints(RooArgSet&) override ; - std::unique_ptr fillNormSetForServer(RooArgSet const& /*normSet*/, RooAbsArg const& /*server*/) const override { - return std::make_unique(); - } + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + + std::unique_ptr createExpectedEventsFunc(const RooArgSet* nset) const override; + + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; protected: @@ -109,8 +111,11 @@ class RooRealSumPdf : public RooAbsPdf { bool doFloor, bool & hasWarnedBefore); - static bool checkObservables(RooAbsReal const& caller, RooArgSet const* nset, - RooArgList const& funcList, RooArgList const& coefList); + static void translateImpl(RooFit::Detail::CodeSquashContext &ctx, RooAbsArg const *klass, RooArgList const &funcList, + RooArgList const &coefList); + + static bool checkObservables(RooAbsReal const &caller, RooArgSet const *nset, RooArgList const &funcList, + RooArgList const &coefList); static Int_t getAnalyticalIntegralWN(RooAbsReal const& caller, RooObjCacheManager & normIntMgr, RooArgList const& funcList, RooArgList const& coefList, diff --git a/roofit/roofitcore/inc/RooRealVar.h b/roofit/roofitcore/inc/RooRealVar.h index ab1e3e4cdfbb0..0cd3199d630d7 100644 --- a/roofit/roofitcore/inc/RooRealVar.h +++ b/roofit/roofitcore/inc/RooRealVar.h @@ -33,9 +33,6 @@ class RooErrorVar ; class RooVectorDataStore ; class RooExpensiveObjectCache ; class RooRealVarSharedProperties; -namespace RooBatchCompute{ -struct RunContext; -} class RooRealVar : public RooAbsRealLValue { public: @@ -53,7 +50,6 @@ class RooRealVar : public RooAbsRealLValue { // Parameter value and error accessors double getValV(const RooArgSet* nset=nullptr) const override ; - RooSpan getValues(RooBatchCompute::RunContext& inputData, const RooArgSet* = nullptr) const final; /// Returns how many times the value of this RooRealVar was reset. std::size_t valueResetCounter() const { return _valueResetCounter; } @@ -136,6 +132,8 @@ class RooRealVar : public RooAbsRealLValue { static void cleanup() ; + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + protected: static bool _printScientific ; @@ -172,10 +170,7 @@ class RooRealVar : public RooAbsRealLValue { std::size_t _valueResetCounter = 0; /// -protected: - ClassDefOverride(RooRefCountList,1) // RooLinkedList with reference counting +class RooRefCountList : public RooLinkedList { +public: + RooRefCountList() {} + ClassDefOverride(RooRefCountList, 1) // RooLinkedList alias for backwards compatibility }; #endif + +/// \endcond diff --git a/roofit/roofitcore/inc/RooRombergIntegrator.h b/roofit/roofitcore/inc/RooRombergIntegrator.h new file mode 100644 index 0000000000000..a463b1b3ef6c6 --- /dev/null +++ b/roofit/roofitcore/inc/RooRombergIntegrator.h @@ -0,0 +1,90 @@ +/***************************************************************************** + * Project: RooFit * + * Package: RooFitCore * + * File: $Id: RooRombergIntegrator.h,v 1.21 2007/05/11 09:11:30 verkerke Exp $ + * Authors: * + * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * + * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * + * * + * Copyright (c) 2000-2005, Regents of the University of California * + * and Stanford University. All rights reserved. * + * * + * Redistribution and use in source and binary forms, * + * with or without modification, are permitted according to the terms * + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * + *****************************************************************************/ +#ifndef ROO_INTEGRATOR_1D +#define ROO_INTEGRATOR_1D + +#include "RooAbsIntegrator.h" +#include "RooNumIntConfig.h" + +#include + +#include + +namespace RooFit { +namespace Detail { + +std::pair integrate1d(std::function func, bool doTrapezoid, int maxSteps, int minStepsZero, + int fixSteps, double epsAbs, double epsRel, bool doExtrap, double xmin, double xmax, + std::span hArr, std::span sArr); + +} // namespace Detail +} // namespace RooFit + +class RooRombergIntegrator : public RooAbsIntegrator { +public: + // Constructors, assignment etc + enum SummationRule { Trapezoid, Midpoint }; + + RooRombergIntegrator(const RooAbsFunc &function, SummationRule rule = Trapezoid, int maxSteps = 0, double eps = 0); + RooRombergIntegrator(const RooAbsFunc &function, double xmin, double xmax, SummationRule rule = Trapezoid, + int maxSteps = 0, double eps = 0); + + RooRombergIntegrator(const RooAbsFunc &function, const RooNumIntConfig &config, int nDim = 1, + bool doSegmentation = false); + RooRombergIntegrator(const RooAbsFunc &function, double xmin, double xmax, const RooNumIntConfig &config, + int nDim = 1); + + bool checkLimits() const override; + double integral(const double *yvec = nullptr) override; + + using RooAbsIntegrator::setLimits; + bool setLimits(double *xmin, double *xmax) override; + bool setUseIntegrandLimits(bool flag) override + { + _useIntegrandLimits = flag; + return true; + } + +protected: + friend class RooNumIntFactory; + static void registerIntegrator(RooNumIntFactory &fact); + + bool initialize(); + double integral(int iDim, int nSeg, std::span wksp); + + bool _useIntegrandLimits; ///< If true limits of function binding are used + + // Integrator configuration + int _nDim = 1; + SummationRule _rule; + int _maxSteps; ///< Maximum number of steps + int _minStepsZero = 999; ///< Minimum number of steps to declare convergence to zero + int _fixSteps = 0; ///< Fixed number of steps + double _epsAbs; ///< Absolute convergence tolerance + double _epsRel; ///< Relative convergence tolerance + bool _doExtrap = true; ///< Apply conversion step? + int _nSeg = 1; ///< Number of segments + std::vector _xmin; /// _xmax; /// _wksp; /// _x; //! do not persist + + ClassDefOverride(RooRombergIntegrator, 0) // 1-dimensional numerical integration engine +}; + +#endif diff --git a/roofit/roofitcore/inc/RooSTLRefCountList.h b/roofit/roofitcore/inc/RooSTLRefCountList.h index 262e41211c0d7..f466ebf563dea 100644 --- a/roofit/roofitcore/inc/RooSTLRefCountList.h +++ b/roofit/roofitcore/inc/RooSTLRefCountList.h @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + // Author: Stephan Hageboeck, CERN, 12/2018 /***************************************************************************** * Project: RooFit * @@ -25,6 +27,7 @@ #include #include +class RooLinkedList; /** * \class RooSTLRefCountList @@ -57,6 +60,9 @@ class RooSTLRefCountList { ///Add an object or increase refCount if it is already present. Only compares ///pointers to check for existing objects void Add(T * obj, std::size_t initialCount = 1) { + // Nothing to add because `refCount` would be zero. + if(initialCount == 0) return; + auto foundItem = findByPointer(obj); if (foundItem != _storage.end()) { @@ -128,7 +134,7 @@ class RooSTLRefCountList { } - ///Find an item by comparing its adress. + ///Find an item by comparing its address. template typename Container_t::const_iterator findByPointer(const Obj_t * item) const { return std::find(_storage.begin(), _storage.end(), item); @@ -148,22 +154,25 @@ class RooSTLRefCountList { } - ///Find an item by comparing RooAbsArg::namePtr() adresses. - T* findByNamePointer(const T * item) const { + ///Find an item by comparing RooAbsArg::namePtr() addresses. + inline T* findByNamePointer(const T * item) const { + return findByNamePointer(item->namePtr()); + } + + T* findByNamePointer(TNamed const* namePtr) const { if(size() < minSizeForNamePointerOrdering) { - auto nptr = item->namePtr(); - auto byNamePointer = [nptr](const T * element) { - return element->namePtr() == nptr; + auto byNamePointer = [namePtr](const T * element) { + return element->namePtr() == namePtr; }; auto found = std::find_if(_storage.begin(), _storage.end(), byNamePointer); return found != _storage.end() ? *found : nullptr; } else { - //As the collection is guaranteed to be sorted by namePtr() adress, we + //As the collection is guaranteed to be sorted by namePtr() address, we //can use a binary search to look for `item` in this collection. - auto first = lowerBoundByNamePointer(item); + auto first = lowerBoundByNamePointer(namePtr); if(first == _orderedStorage.end()) return nullptr; - if(item->namePtr() != (*first)->namePtr()) return nullptr; + if(namePtr != (*first)->namePtr()) return nullptr; return *first; } } @@ -191,12 +200,18 @@ class RooSTLRefCountList { ///Decrease ref count of given object. Shrink list if ref count reaches 0. ///\param obj Decrease ref count of given object. Compare by pointer. ///\param force If true, remove irrespective of ref count. - void Remove(const T * obj, bool force = false) { + ///Returns by how much the `refCount` for the element to be removed was + ///decreased (zero if nothing was removed). If `force == false`, it can + ///only be zero or one, if `force == true`, it can be the full `refCount` + ///for that element. + int Remove(const T * obj, bool force = false) { auto item = findByPointer(obj); if (item != _storage.end()) { const std::size_t pos = item - _storage.begin(); + const UInt_t origRefCount = _refCount[pos]; + if (force || --_refCount[pos] == 0) { //gcc4.x doesn't know how to erase at the position of a const_iterator //Therefore, erase at begin + pos instead of 'item' @@ -211,8 +226,31 @@ class RooSTLRefCountList { // _storage at the beginning of Remove(). _orderedStorage.erase(std::find(_orderedStorage.begin(), _orderedStorage.end(), obj)); } + return origRefCount; } + return 1; } + + return 0; + } + + + ///Replace an element with a new value, keeping the same `refCount`. Will + ///return the `refCount` for that element if the replacement succeeded, + ///otherwise returns zero in case the `oldObj` could not be found in the + ///collection. + int Replace(const T * oldObj, T * newObj) { + auto item = findByPointer(oldObj); + + if (item != _storage.end()) { + const std::size_t pos = item - _storage.begin(); + _storage[pos] = newObj; + // The content has changed, so the ordered-by-name storage was invalidated. + _orderedStorage.clear(); + return _refCount[pos]; + } + + return 0; } @@ -221,17 +259,22 @@ class RooSTLRefCountList { Remove(obj, true); } + static RooSTLRefCountList convert(const RooLinkedList& old); private: //Return an iterator to the last element in this sorted collection with a - //RooAbsArg::namePtr() adress smaller than for `item`. - typename std::vector::const_iterator lowerBoundByNamePointer(const T * item) const { + //RooAbsArg::namePtr() address smaller than for `item`. + inline typename std::vector::const_iterator lowerBoundByNamePointer(const T * item) const { + return lowerBoundByNamePointer(item->namePtr()); + } + + typename std::vector::const_iterator lowerBoundByNamePointer(TNamed const* namePtr) const { //If the _orderedStorage has not been initialized yet or needs resorting //for other reasons, (re-)initialize it now. if(orderedStorageNeedsSorting() || _orderedStorage.size() != _storage.size()) initializeOrderedStorage(); - return std::lower_bound(_orderedStorage.begin(), _orderedStorage.end(), item->namePtr(), + return std::lower_bound(_orderedStorage.begin(), _orderedStorage.end(), namePtr, [](const auto& x, TNamed const* npt) -> bool { return x->namePtr() < npt; }); @@ -276,14 +319,6 @@ class RooSTLRefCountList { template std::size_t const* RooSTLRefCountList::_renameCounter = nullptr; -class RooAbsArg; -class RooRefCountList; - -namespace RooFit { -namespace STLRefCountListHelpers { - /// Converter from the old RooRefCountList to RooSTLRefCountList. - RooSTLRefCountList convert(const RooRefCountList& old); -} -} - #endif /* ROOFIT_ROOFITCORE_INC_ROOSTLREFCOUNTLIST_H_ */ + +/// \endcond diff --git a/roofit/roofitcore/inc/RooScaledFunc.h b/roofit/roofitcore/inc/RooScaledFunc.h deleted file mode 100644 index 126364b6dc9cc..0000000000000 --- a/roofit/roofitcore/inc/RooScaledFunc.h +++ /dev/null @@ -1,46 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooScaledFunc.h,v 1.6 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_SCALED_FUNC -#define ROO_SCALED_FUNC - -#include "RooAbsFunc.h" -#include - -class RooScaledFunc : public RooAbsFunc { -public: - inline RooScaledFunc(const RooAbsFunc &func, double scaleFactor) : - RooAbsFunc(func.getDimension()), _func(&func), _scaleFactor(scaleFactor) { } - inline ~RooScaledFunc() override { } - - inline double operator()(const double xvector[]) const override { - return _scaleFactor*(*_func)(xvector); - } - inline double getMinLimit(UInt_t index) const override { return _func->getMinLimit(index); } - inline double getMaxLimit(UInt_t index) const override { return _func->getMaxLimit(index); } - - std::list* plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const override { - return _func->plotSamplingHint(obs,xlo,xhi) ; - } - -protected: - const RooAbsFunc *_func; - double _scaleFactor; - - ClassDefOverride(RooScaledFunc,0) // Function binding applying scaling to another function binding -}; - -#endif - diff --git a/roofit/roofitcore/inc/RooSegmentedIntegrator1D.h b/roofit/roofitcore/inc/RooSegmentedIntegrator1D.h deleted file mode 100644 index 37ce3e2974876..0000000000000 --- a/roofit/roofitcore/inc/RooSegmentedIntegrator1D.h +++ /dev/null @@ -1,66 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooSegmentedIntegrator1D.h,v 1.7 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_SEGMENTED_INTEGRATOR_1D -#define ROO_SEGMENTED_INTEGRATOR_1D - -#include "RooAbsIntegrator.h" -#include "RooIntegrator1D.h" -#include "RooNumIntConfig.h" - -class RooSegmentedIntegrator1D : public RooAbsIntegrator { -public: - - // Constructors, assignment etc - RooSegmentedIntegrator1D() ; - RooSegmentedIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooSegmentedIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, const RooNumIntConfig& config) ; - - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; - ~RooSegmentedIntegrator1D() override; - - bool checkLimits() const override; - double integral(const double *yvec=nullptr) override ; - - using RooAbsIntegrator::setLimits ; - bool setLimits(double *xmin, double *xmax) override; - bool setUseIntegrandLimits(bool flag) override { _useIntegrandLimits = flag ; return true ; } - - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return false ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return false ; } - -protected: - - friend class RooNumIntFactory ; - static void registerIntegrator(RooNumIntFactory& fact) ; - - mutable double _xmin ; - mutable double _xmax ; - mutable double _range ; - bool _valid ; - Int_t _nseg ; // Number of segments - bool _useIntegrandLimits ; - - RooNumIntConfig _config ; - RooIntegrator1D** _array ; ///< Array of segment integrators - - bool initialize(); - - ClassDefOverride(RooSegmentedIntegrator1D,0) // 1-dimensional piece-wise numerical integration engine -}; - -#endif diff --git a/roofit/roofitcore/inc/RooSegmentedIntegrator2D.h b/roofit/roofitcore/inc/RooSegmentedIntegrator2D.h deleted file mode 100644 index cdf910bd4eb51..0000000000000 --- a/roofit/roofitcore/inc/RooSegmentedIntegrator2D.h +++ /dev/null @@ -1,53 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * File: $Id: RooSegmentedIntegrator2D.h,v 1.7 2007/05/11 09:11:30 verkerke Exp $ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ -#ifndef ROO_SEGMENTED_INTEGRATOR_2D -#define ROO_SEGMENTED_INTEGRATOR_2D - -#include "RooSegmentedIntegrator1D.h" -#include "RooIntegrator1D.h" -#include "RooNumIntConfig.h" - -class RooSegmentedIntegrator2D : public RooSegmentedIntegrator1D { -public: - - // Constructors, assignment etc - RooSegmentedIntegrator2D() ; - - RooSegmentedIntegrator2D(const RooAbsFunc& function, const RooNumIntConfig& config) ; - RooSegmentedIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, double ymin, double ymax, - const RooNumIntConfig& config) ; - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; - ~RooSegmentedIntegrator2D() override ; - - bool checkLimits() const override; - - bool canIntegrate1D() const override { return false ; } - bool canIntegrate2D() const override { return true ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return false ; } - -protected: - - friend class RooNumIntFactory ; - static void registerIntegrator(RooNumIntFactory& fact) ; - - RooSegmentedIntegrator1D* _xIntegrator ; - RooAbsFunc* _xint ; - - ClassDefOverride(RooSegmentedIntegrator2D,0) // 2-dimensional piece-wise numerical integration engine -}; - -#endif diff --git a/roofit/roofitcore/inc/RooSimSplitGenContext.h b/roofit/roofitcore/inc/RooSimSplitGenContext.h index 0a317b59daafb..6df6bd9f00b51 100644 --- a/roofit/roofitcore/inc/RooSimSplitGenContext.h +++ b/roofit/roofitcore/inc/RooSimSplitGenContext.h @@ -48,7 +48,7 @@ class RooSimSplitGenContext : public RooAbsGenContext { RooSimSplitGenContext(const RooSimSplitGenContext& other) ; RooAbsCategoryLValue* _idxCat ; ///< Clone of index category - RooArgSet* _idxCatSet ; ///< Owner of index category components + RooArgSet _idxCatSet ; ///< Owner of index category components const RooSimultaneous *_pdf ; ///< Original PDF std::vector _gcList ; ///< List of component generator contexts std::vector _gcIndex ; ///< Index value corresponding to component diff --git a/roofit/roofitcore/inc/RooSimWSTool.h b/roofit/roofitcore/inc/RooSimWSTool.h index 9b6b87cc98147..c38e884fbcef5 100644 --- a/roofit/roofitcore/inc/RooSimWSTool.h +++ b/roofit/roofitcore/inc/RooSimWSTool.h @@ -51,9 +51,9 @@ class RooSimWSTool { class ObjSplitRule ; RooSimultaneous* build(const char* simPdfName, const char* protoPdfName, - const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; RooSimultaneous* build(const char* simPdfName,BuildConfig& bc, bool verbose=true) ; @@ -84,9 +84,9 @@ class RooSimWSTool::SplitRule : public TNamed { friend class RooSimWSTool ; friend class BuildConfig ; friend class MultiBuildConfig ; - void configure(const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; + void configure(const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; std::list _miStateNameList ; std::map,std::string> > _paramSplitMap ; //,remainderStateName>> @@ -98,9 +98,9 @@ class RooSimWSTool::BuildConfig { public: BuildConfig(const char* pdfName, SplitRule& sr) ; - BuildConfig(const char* pdfName, const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; + BuildConfig(const char* pdfName, const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; BuildConfig(const RooArgSet& legacyBuildConfig) ; @@ -128,9 +128,9 @@ class RooSimWSTool::MultiBuildConfig : public RooSimWSTool::BuildConfig ~MultiBuildConfig() override {} ; void addPdf(const char* miStateList, const char* pdfName, SplitRule& sr) ; void addPdf(const char* miStateList, const char* pdfName, - const RooCmdArg& arg1=RooCmdArg::none(),const RooCmdArg& arg2=RooCmdArg::none(), - const RooCmdArg& arg3=RooCmdArg::none(),const RooCmdArg& arg4=RooCmdArg::none(), - const RooCmdArg& arg5=RooCmdArg::none(),const RooCmdArg& arg6=RooCmdArg::none()) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={}, + const RooCmdArg& arg3={},const RooCmdArg& arg4={}, + const RooCmdArg& arg5={},const RooCmdArg& arg6={}) ; protected: friend class RooSimWSTool ; diff --git a/roofit/roofitcore/inc/RooSimultaneous.h b/roofit/roofitcore/inc/RooSimultaneous.h index 95b687f96d0a6..c729a724fe1cd 100644 --- a/roofit/roofitcore/inc/RooSimultaneous.h +++ b/roofit/roofitcore/inc/RooSimultaneous.h @@ -28,15 +28,30 @@ #include "RooArgList.h" #include #include + class RooAbsCategoryLValue ; class RooFitResult ; class RooPlot ; class RooAbsData ; class RooLinkedList ; +class RooSuperCategory ; class RooSimultaneous : public RooAbsPdf { public: + /// Internal struct used for initialization. + struct InitializationOutput { + + ~InitializationOutput(); + + void addPdf(const RooAbsPdf &pdf, std::string const &catLabel); + + std::vector finalPdfs; + std::vector finalCatLabels; + RooAbsCategoryLValue *indexCat = nullptr; + std::unique_ptr superIndex; + }; + // Constructors, assignment etc inline RooSimultaneous() : _plotCoefNormRange(nullptr), _partIntMgr(this,10) {} RooSimultaneous(const char *name, const char *title, RooAbsCategoryLValue& indexCat) ; @@ -60,26 +75,20 @@ class RooSimultaneous : public RooAbsPdf { using RooAbsPdf::plotOn ; RooPlot* plotOn(RooPlot* frame, - const RooCmdArg& arg1 , const RooCmdArg& arg2=RooCmdArg(), - const RooCmdArg& arg3=RooCmdArg(), const RooCmdArg& arg4=RooCmdArg(), - const RooCmdArg& arg5=RooCmdArg(), const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(), const RooCmdArg& arg8=RooCmdArg(), - const RooCmdArg& arg9=RooCmdArg(), const RooCmdArg& arg10=RooCmdArg()) const override { + const RooCmdArg& arg1 , const RooCmdArg& arg2={}, + const RooCmdArg& arg3={}, const RooCmdArg& arg4={}, + const RooCmdArg& arg5={}, const RooCmdArg& arg6={}, + const RooCmdArg& arg7={}, const RooCmdArg& arg8={}, + const RooCmdArg& arg9={}, const RooCmdArg& arg10={}) const override { return RooAbsReal::plotOn(frame,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) ; } RooPlot* plotOn(RooPlot* frame, RooLinkedList& cmdList) const override ; - // Backward compatibility function - virtual RooPlot *plotOn(RooPlot *frame, Option_t* drawOptions, double scaleFactor=1.0, - ScaleType stype=Relative, const RooAbsData* projData=nullptr, const RooArgSet* projSet=nullptr, - double precision=1e-3, bool shiftToZero=false, const RooArgSet* projDataSet=nullptr, - double rangeLo=0.0, double rangeHi=0.0, RooCurve::WingMode wmode=RooCurve::Extended) const; - - RooAbsPdf* getPdf(const char* catName) const ; + RooAbsPdf* getPdf(RooStringView catName) const ; const RooAbsCategoryLValue& indexCat() const { return (RooAbsCategoryLValue&) _indexCat.arg() ; } - RooDataSet* generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) override ; + RooFit::OwningPtr generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) override ; virtual RooDataHist* fillDataHist(RooDataHist *hist, const RooArgSet* nset, double scaleFactor, bool correctForBinVolume=false, bool showProgress=false) const ; @@ -89,14 +98,22 @@ class RooSimultaneous : public RooAbsPdf { std::map const& precisions, bool useCategoryNames=false); -protected: + RooAbsGenContext* autoGenContext(const RooArgSet &vars, const RooDataSet* prototype=nullptr, const RooArgSet* auxProto=nullptr, + bool verbose=false, bool autoBinned=true, const char* binnedTag="") const override ; + RooAbsGenContext* genContext(const RooArgSet &vars, const RooDataSet *prototype=nullptr, + const RooArgSet* auxProto=nullptr, bool verbose= false) const override ; - void initialize(RooAbsCategoryLValue& inIndexCat, std::map pdfMap) ; + std::unique_ptr compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext & ctx) const override; + +protected: void selectNormalization(const RooArgSet* depSet=nullptr, bool force=false) override ; void selectNormalizationRange(const char* rangeName=nullptr, bool force=false) override ; + + RooArgSet const& flattenedCatList() const; + mutable RooSetProxy _plotCoefNormSet ; - const TNamed* _plotCoefNormRange ; + const TNamed* _plotCoefNormRange = nullptr; class CacheElem : public RooAbsCacheElement { public: @@ -109,14 +126,21 @@ class RooSimultaneous : public RooAbsPdf { friend class RooSimGenContext ; friend class RooSimSplitGenContext ; - RooAbsGenContext* autoGenContext(const RooArgSet &vars, const RooDataSet* prototype=nullptr, const RooArgSet* auxProto=nullptr, - bool verbose=false, bool autoBinned=true, const char* binnedTag="") const override ; - RooAbsGenContext* genContext(const RooArgSet &vars, const RooDataSet *prototype=nullptr, - const RooArgSet* auxProto=nullptr, bool verbose= false) const override ; RooCategoryProxy _indexCat ; ///< Index category TList _pdfProxyList ; ///< List of PDF proxies (named after applicable category state) - Int_t _numPdf ; ///< Number of registered PDFs + Int_t _numPdf = 0; ///< Number of registered PDFs + +private: + + /// Private internal constructor. + RooSimultaneous(const char *name, const char *title, InitializationOutput && initInfo); + + static std::unique_ptr + initialize(std::string const& name, RooAbsCategoryLValue &inIndexCat, + std::map const &pdfMap); + + mutable std::unique_ptr _indexCatSet ; /// createFundamental(const char* newname=nullptr) const override { + return RooFit::Detail::owningPtr(std::make_unique(newname ? newname : GetName(), GetTitle(), "", 1)); } protected: @@ -72,6 +72,7 @@ class RooStringVar final : public RooAbsArg { private: std::string _string; + std::string* _stringAddr; //! Required to connect to TTree branch ClassDefOverride(RooStringVar,2) // String-valued variable }; diff --git a/roofit/roofitcore/inc/RooStringView.h b/roofit/roofitcore/inc/RooStringView.h index 9bee9bbbd7018..eedd9eb5515f6 100644 --- a/roofit/roofitcore/inc/RooStringView.h +++ b/roofit/roofitcore/inc/RooStringView.h @@ -18,8 +18,8 @@ #include -/// The RooStringView is a wrapper around a C-syle string that can also be -/// constructed from a `std::string` or a Tstring. As such, it serves as a +/// The RooStringView is a wrapper around a C-style string that can also be +/// constructed from a `std::string` or a TString. As such, it serves as a /// drop-in replacement for `const char*` in public RooFit interfaces, keeping /// the possibility to pass a C-style string without copying but also accepting /// a `std::string`. @@ -31,6 +31,7 @@ class RooStringView { RooStringView(std::string const &str) : _cstr{str.c_str()} {} // If the string is a temporary, we have to store it ourselves, otherwise the C-style string would be invalid. RooStringView(std::string &&str) : _strp{std::make_shared(std::move(str))}, _cstr{_strp->c_str()} {} + const char * c_str() const { return _cstr; } operator const char *() { return _cstr; } operator std::string_view() { return _cstr; } diff --git a/roofit/roofitcore/inc/RooTObjWrap.h b/roofit/roofitcore/inc/RooTObjWrap.h index 340e6e8761dcc..002484cbb17fa 100644 --- a/roofit/roofitcore/inc/RooTObjWrap.h +++ b/roofit/roofitcore/inc/RooTObjWrap.h @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + /***************************************************************************** * Project: RooFit * * Package: RooFitCore * @@ -13,6 +15,7 @@ * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ + #ifndef ROO_TOBJ_WRAP #define ROO_TOBJ_WRAP @@ -48,3 +51,5 @@ class RooTObjWrap : public TNamed { }; #endif + +/// \endcond diff --git a/roofit/roofitcore/inc/RooTemplateProxy.h b/roofit/roofitcore/inc/RooTemplateProxy.h index 14888aed82a88..6ca7886767487 100644 --- a/roofit/roofitcore/inc/RooTemplateProxy.h +++ b/roofit/roofitcore/inc/RooTemplateProxy.h @@ -160,9 +160,19 @@ class RooTemplateProxy : public RooArgProxy { /// \param[in] valueServer Notify the owner if value changes. /// \param[in] shapeServer Notify the owner if shape (e.g. binning) changes. /// \param[in] proxyOwnsArg Proxy will delete the payload if owning. + template::value>> RooTemplateProxy(const char* theName, const char* desc, RooAbsArg* owner, - bool valueServer=true, bool shapeServer=false, bool proxyOwnsArg=false) - : RooArgProxy(theName, desc, owner, valueServer, shapeServer, proxyOwnsArg) { } + Bool valueServer=true, bool shapeServer=false, bool proxyOwnsArg=false) + : RooArgProxy(theName, desc, owner, valueServer, shapeServer, proxyOwnsArg) { + // Note for developers: the type of the first bool parameter is templated + // such that implicit conversion from int or pointers to bool is disabled. + // This is because there is another constructor with the signature + // `RooTemplateProxy(name, title, owner, T& ref)`. It happened already more + // than once that other developers accidentally used a `T*` pointer instead + // of a reference, in which case it resolved to this constructor via + // implicit conversion to bool. This is completely meaningless and should + // not happen. + } //////////////////////////////////////////////////////////////////////////////// /// Constructor with owner and proxied object. @@ -184,7 +194,7 @@ class RooTemplateProxy : public RooArgProxy { /// It will accept any RooTemplateProxy instance, and attempt a dynamic_cast on its payload. /// \param[in] theName Name of this proxy. /// \param[in] owner Pointer to the owner this proxy should be registered to. - /// \param[in] other Instance of a differen proxy whose payload should be copied. + /// \param[in] other Instance of a different proxy whose payload should be copied. /// \param[in] allowWrongTypes Instead of throwing a std::invalid_argument, only issue an /// error message when payload with wrong type is found. This is unsafe, but may be necessary /// when reading back legacy types. Defaults to false. @@ -227,7 +237,7 @@ class RooTemplateProxy : public RooArgProxy { bool setArg(T& newRef) { if (_arg) { if (std::string(arg().GetName()) != newRef.GetName()) { - newRef.setAttribute(Form("ORIGNAME:%s", arg().GetName())) ; + newRef.setAttribute(("ORIGNAME:" + std::string(arg().GetName())).c_str()) ; } return changePointer(RooArgSet(newRef), true); } else { diff --git a/roofit/roofitcore/inc/RooTreeDataStore.h b/roofit/roofitcore/inc/RooTreeDataStore.h index 4baf4ca61c020..e39b7756c8d9a 100644 --- a/roofit/roofitcore/inc/RooTreeDataStore.h +++ b/roofit/roofitcore/inc/RooTreeDataStore.h @@ -17,7 +17,6 @@ #define ROO_TREE_DATA_STORE #include "RooAbsDataStore.h" -#include "RunContext.h" #include "ROOT/RStringView.hxx" @@ -81,7 +80,7 @@ class RooTreeDataStore : public RooAbsDataStore { (void)first; (void)len; return {}; } - RooSpan getWeightBatch(std::size_t first, std::size_t len) const override; + std::span getWeightBatch(std::size_t first, std::size_t len) const override; // Change observable name bool changeObservableName(const char* from, const char* to) override ; diff --git a/roofit/roofitcore/inc/RooTruthModel.h b/roofit/roofitcore/inc/RooTruthModel.h index 6b9d1a74d88b4..ccc16f34626e1 100644 --- a/roofit/roofitcore/inc/RooTruthModel.h +++ b/roofit/roofitcore/inc/RooTruthModel.h @@ -53,6 +53,9 @@ class RooTruthModel : public RooResolutionModel { Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=nullptr) const override ; double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override ; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; + inline bool canComputeBatchWithCuda() const override { return true; } + protected: double evaluate() const override ; void changeBasis(RooFormulaVar* basis) override ; diff --git a/roofit/roofitcore/inc/RooUnitTest.h b/roofit/roofitcore/inc/RooUnitTest.h index 4a70ddf200587..18bfb5895f8c6 100644 --- a/roofit/roofitcore/inc/RooUnitTest.h +++ b/roofit/roofitcore/inc/RooUnitTest.h @@ -37,14 +37,14 @@ class TFile; class RooUnitTest : public TNamed { public: - RooUnitTest(const char* name, TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode="off") ; + RooUnitTest(const char* name, TFile* refFile, bool writeRef, Int_t verbose) ; ~RooUnitTest() override ; void setDebug(bool flag) { _debug = flag ; } void setSilentMode() ; void clearSilentMode() ; void regPlot(RooPlot* frame, const char* refName) ; - void regResult(RooFitResult* r, const char* refName) ; + void regResult(std::unique_ptr r, const char* refName) ; void regValue(double value, const char* refName) ; void regTable(RooTable* t, const char* refName) ; void regWS(RooWorkspace* ws, const char* refName) ; @@ -77,7 +77,6 @@ class RooUnitTest : public TNamed { bool _debug ; bool _write ; Int_t _verb ; - std::string _batchMode="off"; std::list > _regPlots ; std::list > _regResults ; std::list > _regValues ; diff --git a/roofit/roofitcore/inc/RooVectorDataStore.h b/roofit/roofitcore/inc/RooVectorDataStore.h index bfacf1875f861..bd717db735f1e 100644 --- a/roofit/roofitcore/inc/RooVectorDataStore.h +++ b/roofit/roofitcore/inc/RooVectorDataStore.h @@ -123,7 +123,7 @@ class RooVectorDataStore : public RooAbsDataStore { RooAbsData::RealSpans getBatches(std::size_t first, std::size_t len) const override; RooAbsData::CategorySpans getCategoryBatches(std::size_t /*first*/, std::size_t len) const override; - RooSpan getWeightBatch(std::size_t first, std::size_t len) const override; + std::span getWeightBatch(std::size_t first, std::size_t len) const override; // Change observable name bool changeObservableName(const char* from, const char* to) override; @@ -289,32 +289,32 @@ class RooVectorDataStore : public RooAbsDataStore { *_nativeBuf = *_buf ; } - RooSpan getRange(std::size_t first, std::size_t last) const { + std::span getRange(std::size_t first, std::size_t last) const { auto beg = std::min(_vec.cbegin() + first, _vec.cend()); auto end = std::min(_vec.cbegin() + last, _vec.cend()); - return RooSpan(beg, end); + return std::span(&*beg, std::distance(beg, end)); } std::size_t size() const { return _vec.size() ; } - void resize(Int_t siz) { - if (siz < Int_t(_vec.capacity()) / 2 && _vec.capacity() > (VECTOR_BUFFER_SIZE / sizeof(double))) { + void resize(Int_t newSize) { + if (newSize < Int_t(_vec.capacity()) / 2 && _vec.capacity() > (VECTOR_BUFFER_SIZE / sizeof(double))) { // do an expensive copy, if we save at least a factor 2 in size std::vector tmp; - tmp.reserve(std::max(siz, Int_t(VECTOR_BUFFER_SIZE / sizeof(double)))); + tmp.reserve(std::max(newSize, Int_t(VECTOR_BUFFER_SIZE / sizeof(double)))); if (!_vec.empty()) - tmp.assign(_vec.begin(), std::min(_vec.end(), _vec.begin() + siz)); - if (Int_t(tmp.size()) != siz) - tmp.resize(siz); + tmp.assign(_vec.begin(), std::min(_vec.end(), _vec.begin() + newSize)); + if (Int_t(tmp.size()) != newSize) + tmp.resize(newSize); _vec.swap(tmp); } else { - _vec.resize(siz); + _vec.resize(newSize); } } - void reserve(Int_t siz) { - _vec.reserve(siz); + void reserve(Int_t newSize) { + _vec.reserve(newSize); } const std::vector& data() const { @@ -340,187 +340,92 @@ class RooVectorDataStore : public RooAbsDataStore { class RealFullVector : public RealVector { public: - RealFullVector(UInt_t initialCapacity=(VECTOR_BUFFER_SIZE / sizeof(double))) : RealVector(initialCapacity), - _bufE(nullptr), _bufEL(nullptr), _bufEH(nullptr), - _nativeBufE(nullptr), _nativeBufEL(nullptr), _nativeBufEH(nullptr), - _vecE(nullptr), _vecEL(nullptr), _vecEH(nullptr) { - } + RealFullVector(UInt_t initialCapacity=(VECTOR_BUFFER_SIZE / sizeof(double))) : RealVector(initialCapacity) {} RealFullVector(RooAbsReal* arg, UInt_t initialCapacity=(VECTOR_BUFFER_SIZE / sizeof(double))) : - RealVector(arg,initialCapacity), - _bufE(nullptr), _bufEL(nullptr), _bufEH(nullptr), - _nativeBufE(nullptr), _nativeBufEL(nullptr), _nativeBufEH(nullptr), - _vecE(nullptr), _vecEL(nullptr), _vecEH(nullptr) { - } - - ~RealFullVector() override { - if (_vecE) delete _vecE ; - if (_vecEL) delete _vecEL ; - if (_vecEH) delete _vecEH ; - } + RealVector(arg,initialCapacity) {} RealFullVector(const RealFullVector& other, RooAbsReal* real=nullptr) : RealVector(other,real), _bufE(other._bufE), _bufEL(other._bufEL), _bufEH(other._bufEH), - _nativeBufE(other._nativeBufE), _nativeBufEL(other._nativeBufEL), _nativeBufEH(other._nativeBufEH) { - _vecE = (other._vecE) ? new std::vector(*other._vecE) : nullptr ; - _vecEL = (other._vecEL) ? new std::vector(*other._vecEL) : nullptr ; - _vecEH = (other._vecEH) ? new std::vector(*other._vecEH) : nullptr ; + _vecE{other._vecE}, _vecEL{other._vecEL}, _vecEH{other._vecEH} + { } - RealFullVector(const RealVector& other, RooAbsReal* real=nullptr) : RealVector(other,real), - _bufE(nullptr), _bufEL(nullptr), _bufEH(nullptr), - _nativeBufE(nullptr), _nativeBufEL(nullptr), _nativeBufEH(nullptr) { - _vecE = nullptr ; - _vecEL = nullptr ; - _vecEH = nullptr ; - } + RealFullVector(const RealVector& other, RooAbsReal* real=nullptr) : RealVector(other,real) {} - RealFullVector& operator=(const RealFullVector& other) { - if (&other==this) return *this; - RealVector::operator=(other); - _bufE = other._bufE; - _bufEL = other._bufEL; - _bufEH = other._bufEH; - _nativeBufE = other._nativeBufE; - _nativeBufEL = other._nativeBufEL; - _nativeBufEH = other._nativeBufEH; - std::vector* src[3] = { other._vecE, other._vecEL, other._vecEH }; - std::vector* dst[3] = { _vecE, _vecEL, _vecEH }; - for (unsigned i = 0; i < 3; ++i) { - if (src[i]) { - if (dst[i]) { - if (dst[i]->size() <= src[i]->capacity() / 2 && - src[i]->capacity() > (VECTOR_BUFFER_SIZE / sizeof(double))) { - std::vector tmp; - tmp.reserve(std::max(src[i]->size(), VECTOR_BUFFER_SIZE / sizeof(double))); - tmp.assign(src[i]->begin(), src[i]->end()); - dst[i]->swap(tmp); - } else { - *dst[i] = *src[i]; - } - } else { - dst[i] = new std::vector(*src[i]); - } - } else { - delete dst[i]; - dst[i] = nullptr; - } - } - return *this; - } + RealFullVector& operator=(RealFullVector const& other) = delete; void setErrorBuffer(double* newBuf) { - /* std::cout << "setErrorBuffer(" << _nativeReal->GetName() << ") newBuf = " << newBuf << std::endl ; */ _bufE = newBuf ; - if (!_vecE) _vecE = new std::vector ; - _vecE->reserve(_vec.capacity()) ; - if (!_nativeBufE) _nativeBufE = _bufE ; + _vecE.reserve(_vec.capacity()) ; } void setAsymErrorBuffer(double* newBufL, double* newBufH) { - _bufEL = newBufL ; _bufEH = newBufH ; - if (!_vecEL) { - _vecEL = new std::vector ; - _vecEH = new std::vector ; - _vecEL->reserve(_vec.capacity()) ; - _vecEH->reserve(_vec.capacity()) ; - } - if (!_nativeBufEL) { - _nativeBufEL = _bufEL ; - _nativeBufEH = _bufEH ; - } + _bufEL = newBufL; + _bufEH = newBufH; + _vecEL.reserve(_vec.capacity()) ; + _vecEH.reserve(_vec.capacity()) ; } void fill() { RealVector::fill() ; - if (_vecE) _vecE->push_back(*_bufE) ; - if (_vecEL) _vecEL->push_back(*_bufEL) ; - if (_vecEH) _vecEH->push_back(*_bufEH) ; + if (_bufE) _vecE.push_back(*_bufE) ; + if (_bufEL) _vecEL.push_back(*_bufEL) ; + if (_bufEH) _vecEH.push_back(*_bufEH) ; } ; void write(Int_t i) { RealVector::write(i) ; - if (_vecE) (*_vecE)[i] = *_bufE ; - if (_vecEL) (*_vecEL)[i] = *_bufEL ; - if (_vecEH) (*_vecEH)[i] = *_bufEH ; + if (_bufE) _vecE[i] = *_bufE ; + if (_bufEL) _vecEL[i] = *_bufEL ; + if (_bufEH) _vecEH[i] = *_bufEH ; } void reset() { RealVector::reset(); - if (_vecE) { - std::vector tmp; - _vecE->swap(tmp); - } - if (_vecEL) { - std::vector tmp; - _vecEL->swap(tmp); - } - if (_vecEH) { - std::vector tmp; - _vecEH->swap(tmp); - } + _vecE.clear(); + _vecEL.clear(); + _vecEH.clear(); } inline void load(Int_t idx) const { RealVector::load(idx) ; - if (_vecE) { - *_bufE = (*_vecE)[idx]; - *_nativeBufE = (*_vecE)[idx] ; - } - if (_vecEL) { - *_bufEL = (*_vecEL)[idx] ; - *_nativeBufEL = (*_vecEL)[idx] ; - } - if (_vecEH) { - *_bufEH = (*_vecEH)[idx] ; - *_nativeBufEH = (*_vecEH)[idx] ; - } + if (_bufE) *_bufE = _vecE[idx]; + if (_bufEL) *_bufEL = _vecEL[idx]; + if (_bufEH) *_bufEH = _vecEH[idx]; } - void resize(Int_t siz) { - RealVector::resize(siz); - std::vector* vlist[3] = { _vecE, _vecEL, _vecEH }; - for (unsigned i = 0; i < 3; ++i) { - if (!vlist[i]) continue; - if (vlist[i]) { - if (siz < Int_t(vlist[i]->capacity()) / 2 && vlist[i]->capacity() > (VECTOR_BUFFER_SIZE / sizeof(double))) { - // if we gain a factor of 2 in memory, we copy and swap - std::vector tmp; - tmp.reserve(std::max(siz, Int_t(VECTOR_BUFFER_SIZE / sizeof(double)))); - if (!vlist[i]->empty()) - tmp.assign(vlist[i]->begin(), - std::min(_vec.end(), _vec.begin() + siz)); - if (Int_t(tmp.size()) != siz) - tmp.resize(siz); - vlist[i]->swap(tmp); - } else { - vlist[i]->resize(siz); - } - } - } + void resize(Int_t newSize) { + RealVector::resize(newSize); + if(_bufE) _vecE.resize(newSize); + if(_bufEL) _vecEL.resize(newSize); + if(_bufEH) _vecEH.resize(newSize); } - void reserve(Int_t siz) { - RealVector::reserve(siz); - if (_vecE) _vecE->reserve(siz); - if (_vecEL) _vecEL->reserve(siz); - if (_vecEH) _vecEH->reserve(siz); + void reserve(Int_t newSize) { + RealVector::reserve(newSize); + if(_bufE) _vecE.reserve(newSize); + if(_bufEL) _vecEL.reserve(newSize); + if(_bufEH) _vecEH.reserve(newSize); } - std::vector* dataE() { return _vecE; } - std::vector* dataEL() { return _vecEL; } - std::vector* dataEH() { return _vecEH; } + double* bufE() const { return _bufE; } + double* bufEL() const { return _bufEL; } + double* bufEH() const { return _bufEH; } + + std::vector const& dataE() const { return _vecE; } + std::vector const& dataEL() const { return _vecEL; } + std::vector const& dataEH() const { return _vecEH; } private: - friend class RooVectorDataStore ; - double *_bufE ; /// *_vecE, *_vecEL, *_vecEH ; - ClassDefOverride(RealFullVector,1) // STL-vector-based Data Storage class - } ; + + double *_bufE = nullptr; /// _vecE; + std::vector _vecEL; + std::vector _vecEH; + ClassDefOverride(RealFullVector,2); // STL-vector-based Data Storage class + }; class CatVector { @@ -591,33 +496,33 @@ class RooVectorDataStore : public RooAbsDataStore { *_nativeBuf = *_buf; } - RooSpan getRange(std::size_t first, std::size_t last) const { + std::span getRange(std::size_t first, std::size_t last) const { auto beg = std::min(_vec.cbegin() + first, _vec.cend()); auto end = std::min(_vec.cbegin() + last, _vec.cend()); - return RooSpan(beg, end); + return std::span(&*beg, std::distance(beg, end)); } std::size_t size() const { return _vec.size() ; } - void resize(Int_t siz) { - if (siz < Int_t(_vec.capacity()) / 2 && _vec.capacity() > VECTOR_BUFFER_SIZE) { + void resize(Int_t newSize) { + if (newSize < Int_t(_vec.capacity()) / 2 && _vec.capacity() > VECTOR_BUFFER_SIZE) { // do an expensive copy, if we save at least a factor 2 in size std::vector tmp; - tmp.reserve(std::max(siz, VECTOR_BUFFER_SIZE)); + tmp.reserve(std::max(newSize, VECTOR_BUFFER_SIZE)); if (!_vec.empty()) - tmp.assign(_vec.begin(), std::min(_vec.end(), _vec.begin() + siz)); - if (Int_t(tmp.size()) != siz) - tmp.resize(siz); + tmp.assign(_vec.begin(), std::min(_vec.end(), _vec.begin() + newSize)); + if (Int_t(tmp.size()) != newSize) + tmp.resize(newSize); _vec.swap(tmp); } else { - _vec.resize(siz); + _vec.resize(newSize); } } - void reserve(Int_t siz) { - _vec.reserve(siz); + void reserve(Int_t newSize) { + _vec.reserve(newSize); } void setBufArg(RooAbsCategory* arg) { _cat = arg; } diff --git a/roofit/roofitcore/inc/RooWorkspace.h b/roofit/roofitcore/inc/RooWorkspace.h index 05b0cb1c79e23..b2aba1a5004c5 100644 --- a/roofit/roofitcore/inc/RooWorkspace.h +++ b/roofit/roofitcore/inc/RooWorkspace.h @@ -45,34 +45,36 @@ class RooWorkspace : public TNamed { RooWorkspace() ; RooWorkspace(const char* name, bool doCINTExport) - R__SUGGEST_ALTERNATIVE("The \"doCINTExprot\" argument has no effect anymore since ROOT 6." + R__SUGGEST_ALTERNATIVE("The \"doCINTExport\" argument has no effect anymore since ROOT 6." "Consider using RooWorkspace(const char* name, const char* title=nullptr)."); RooWorkspace(const char* name, const char* title=nullptr) ; RooWorkspace(const RooWorkspace& other) ; ~RooWorkspace() override ; + TObject *Clone(const char *newname="") const override; + bool importClassCode(const char* pat="*", bool doReplace=false) ; bool importClassCode(TClass* theClass, bool doReplace=false) ; // Import functions for dataset, functions, generic objects bool import(const RooAbsArg& arg, - const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(),const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg(),const RooCmdArg& arg9=RooCmdArg()) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={},const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; bool import(const RooArgSet& args, - const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(),const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg(),const RooCmdArg& arg9=RooCmdArg()) ; - bool import(RooAbsData& data, - const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(),const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg(),const RooCmdArg& arg9=RooCmdArg()) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={},const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; + bool import(RooAbsData const& data, + const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={},const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; bool import(const char *fileSpec, - const RooCmdArg& arg1=RooCmdArg(),const RooCmdArg& arg2=RooCmdArg(),const RooCmdArg& arg3=RooCmdArg(), - const RooCmdArg& arg4=RooCmdArg(),const RooCmdArg& arg5=RooCmdArg(),const RooCmdArg& arg6=RooCmdArg(), - const RooCmdArg& arg7=RooCmdArg(),const RooCmdArg& arg8=RooCmdArg(),const RooCmdArg& arg9=RooCmdArg()) ; - bool import(TObject& object, bool replaceExisting=false) ; - bool import(TObject& object, const char* aliasName, bool replaceExisting=false) ; + const RooCmdArg& arg1={},const RooCmdArg& arg2={},const RooCmdArg& arg3={}, + const RooCmdArg& arg4={},const RooCmdArg& arg5={},const RooCmdArg& arg6={}, + const RooCmdArg& arg7={},const RooCmdArg& arg8={},const RooCmdArg& arg9={}) ; + bool import(TObject const& object, bool replaceExisting=false) ; + bool import(TObject const& object, const char* aliasName, bool replaceExisting=false) ; // Transaction management interface for multi-step import operations bool startTransaction() ; @@ -85,16 +87,17 @@ class RooWorkspace : public TNamed { bool extendSet(const char* name, const char* newContents) ; bool renameSet(const char* name, const char* newName) ; bool removeSet(const char* name) ; - const RooArgSet* set(const char* name) ; + const RooArgSet* set(RooStringView name) ; + inline const std::map& sets() const { return _namedSets; } // Import, load and save parameter value snapshots - bool saveSnapshot(const char* name, const char* paramNames) ; - bool saveSnapshot(const char* name, const RooArgSet& params, bool importValues=false) ; + bool saveSnapshot(RooStringView, const char* paramNames) ; + bool saveSnapshot(RooStringView, const RooArgSet& params, bool importValues=false) ; bool loadSnapshot(const char* name) ; const RooArgSet* getSnapshot(const char* name) const ; // Retrieve list of parameter snapshots - RooLinkedList getSnapshots(){ return _snapshots; } + RooLinkedList const& getSnapshots() const { return _snapshots; } void merge(const RooWorkspace& /*other*/) {} ; diff --git a/roofit/roofitcore/inc/RooWrapperPdf.h b/roofit/roofitcore/inc/RooWrapperPdf.h index 1dbf16bb8c051..2fc224e498b60 100644 --- a/roofit/roofitcore/inc/RooWrapperPdf.h +++ b/roofit/roofitcore/inc/RooWrapperPdf.h @@ -29,37 +29,47 @@ class RooWrapperPdf final : public RooAbsPdf { /// \param[in] name A name to identify this object. /// \param[in] title Title (for e.g. plotting) /// \param[in] inputFunction Any RooAbsReal that should be converted into a PDF. Although it's possible + /// \param[in] selfNormalized The return value the RooAbsPdf::selfNormalized() function for the wrapped PDF object. + /// If it is `true`, then no automatic normalization will be + /// performed when evaluating the function. In this case, the + /// effect RooWrapperPdf is not to change the evaluated values, + /// but only to wrap the function in something that is of type + /// RooAbsPdf, which can be useful if some interface reqiures it. /// to pass a PDF, it only makes sense for non-PDF functions. - RooWrapperPdf(const char *name, const char *title, RooAbsReal& inputFunction) : + RooWrapperPdf(const char *name, const char *title, RooAbsReal& inputFunction, bool selfNormalized=false) : RooAbsPdf(name, title), - _func("inputFunction", "Function to be converted into a PDF", this, inputFunction) { } + _func("inputFunction", "Function to be converted into a PDF", this, inputFunction), + _selfNormalized{selfNormalized} { } ~RooWrapperPdf() override {}; RooWrapperPdf(const RooWrapperPdf& other, const char *name = nullptr) : RooAbsPdf(other, name), - _func("inputFunction", this, other._func) { } + _func("inputFunction", this, other._func), + _selfNormalized{other._selfNormalized} { } TObject* clone(const char* newname) const override { return new RooWrapperPdf(*this, newname); } + bool selfNormalized() const override { return _selfNormalized; } + // Analytical Integration handling bool forceAnalyticalInt(const RooAbsArg& dep) const override { - return _func.arg().forceAnalyticalInt(dep); + return _func->forceAnalyticalInt(dep); } Int_t getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName=nullptr) const override { - return _func.arg().getAnalyticalIntegralWN(allVars, analVars, normSet, rangeName); + return _func->getAnalyticalIntegralWN(allVars, analVars, normSet, rangeName); } Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& numVars, const char* rangeName=nullptr) const override { - return _func.arg().getAnalyticalIntegral(allVars, numVars, rangeName); + return _func->getAnalyticalIntegral(allVars, numVars, rangeName); } double analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const override { - return _func.arg().analyticalIntegralWN(code, normSet, rangeName); + return _func->analyticalIntegralWN(code, normSet, rangeName); } double analyticalIntegral(Int_t code, const char* rangeName=nullptr) const override { - return _func.arg().analyticalIntegral(code, rangeName); + return _func->analyticalIntegral(code, rangeName); } @@ -99,12 +109,13 @@ class RooWrapperPdf final : public RooAbsPdf { private: RooRealProxy _func; + bool _selfNormalized = false; double evaluate() const override { return _func; } - ClassDefOverride(RooWrapperPdf,1) + ClassDefOverride(RooWrapperPdf,2); }; #endif diff --git a/roofit/roofitcore/inc/RooXYChi2Var.h b/roofit/roofitcore/inc/RooXYChi2Var.h index 6fc31a40ab3f6..10aaf3b1cc02f 100644 --- a/roofit/roofitcore/inc/RooXYChi2Var.h +++ b/roofit/roofitcore/inc/RooXYChi2Var.h @@ -30,11 +30,13 @@ class RooXYChi2Var : public RooAbsOptTestStatistic { public: // Constructors, assignment etc - RooXYChi2Var() ; RooXYChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataSet& data, bool integrate=false) ; RooXYChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataSet& data, RooRealVar& yvar, bool integrate=false) ; - RooXYChi2Var(const char *name, const char* title, RooAbsPdf& extPdf, RooDataSet& data, bool integrate=false) ; - RooXYChi2Var(const char *name, const char* title, RooAbsPdf& extPdf, RooDataSet& data, RooRealVar& yvar, bool integrate=false) ; + /// \cond ROOFIT_INTERNAL + // For internal use in RooAbsReal::createChi2(). + RooXYChi2Var(const char *name, const char *title, RooAbsReal& func, RooAbsData& data, RooRealVar *yvar, bool integrate, + RooAbsTestStatistic::Configuration const& cfg); + /// \endcond ROOFIT_INTERNAL RooXYChi2Var(const RooXYChi2Var& other, const char* name=nullptr); TObject* clone(const char* newname) const override { return new RooXYChi2Var(*this,newname); } @@ -80,7 +82,7 @@ class RooXYChi2Var : public RooAbsOptTestStatistic { double evaluatePartition(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const override ; RooNumIntConfig _intConfig ; ///< Numeric integrator configuration for integration of function over bin - RooAbsReal* _funcInt = nullptr; /// _funcInt; /// _binList ; /// -#include - -class RooArgSet; -class RooAbsArg; -class RooArgProxy; - -namespace RooBatchCompute { - -struct RunContext { - /// Create an empty RunContext that doesn't have access to any computation results. - RunContext() { } - /// Deleted because copying the owned memory is expensive. - /// If needed, it can be implemented, though. - /// \warning Remember to relocate all spans in `spans` to new location - /// in `ownedMemory` after data have been copied! - RunContext(const RunContext&) = delete; - /// Move a RunContext. All spans pointing to data retrieved from the original remain valid. - RunContext(RunContext&&) = default; - RooSpan getBatch(const RooArgProxy& proxy) const; - RooSpan getBatch(const RooAbsArg* owner) const; - /// Retrieve a batch of data corresponding to the element passed as `owner`. - RooSpan operator[](const RooAbsArg* owner) const { return getBatch(owner); } - RooSpan getWritableBatch(const RooAbsArg* owner); - RooSpan makeBatch(const RooAbsArg* owner, std::size_t size); - - /// Clear all computation results without freeing memory. - void clear(); - - /// Once an object has computed its value(s), the span pointing to the results is registered here. - std::map> spans; - std::map spansCuda; - - /// Memory owned by this struct. It is associated to nodes in the computation graph using their pointers. - std::map> ownedMemory; - std::map ownedMemoryCuda; - - const char* rangeName{nullptr}; ///< If evaluation should only occur in a range, the range name can be passed here. - std::vector logProbabilities; ///< Possibility to register log probabilities. -}; - -} - -#endif diff --git a/roofit/roofitcore/src/BatchModeDataHelpers.cxx b/roofit/roofitcore/src/BatchModeDataHelpers.cxx index a66bee1a6e9e2..e087773bb0735 100644 --- a/roofit/roofitcore/src/BatchModeDataHelpers.cxx +++ b/roofit/roofitcore/src/BatchModeDataHelpers.cxx @@ -12,43 +12,33 @@ #include "RooFit/BatchModeDataHelpers.h" #include +#include #include "RooNLLVarNew.h" +#include +#include #include #include -//////////////////////////////////////////////////////////////////////////////// -/// Extract all content from a RooFit datasets as a map of spans. -/// Spans with the weights and squared weights will be also stored in the map, -/// keyed with the names `_weight` and the `_weight_sumW2`. If the dataset is -/// unweighted, these weight spans will only contain the single value `1.0`. -/// Entries with zero weight will be skipped. -/// -/// \return A `std::map` with spans keyed to name pointers. -/// \param[in] data The input dataset. -/// \param[in] rangeName Select only entries from the data in a given range -/// (empty string for no range). -/// \param[in] prefix A string prefix to use for all key names for the data -/// map. -/// \param[in] buffers Pass here an empty stack of `double` vectors, which will -/// be used as memory for the data if the memory in the dataset -/// object can't be used directly (e.g. because you used the range -/// selection or the splitting by categories). -/// \param[in] skipZeroWeights Skip entries with zero weight when filling the -/// data spans. Be very careful with enabling it, because the user -/// might not expect that the batch results are not aligned with the -/// original dataset anymore! -std::map> -RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_view rangeName, - std::string const &prefix, std::stack> &buffers, - bool skipZeroWeights) +namespace { + +// To avoid deleted move assignment. +template +void assignSpan(std::span &to, std::span const &from) { - std::map> dataSpans; // output variable + to = from; +} + +std::map> +getSingleDataSpans(RooAbsData const &data, std::string_view rangeName, std::string const &prefix, + std::stack> &buffers, bool skipZeroWeights) +{ + std::map> dataSpans; // output variable auto &nameReg = RooNameReg::instance(); - auto insert = [&](const char *key, RooSpan span) { + auto insert = [&](const char *key, std::span span) { const TNamed *namePtr = nameReg.constPtr((prefix + key).c_str()); dataSpans[namePtr] = span; }; @@ -83,12 +73,12 @@ RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_v auto &bufferSumW2 = buffers.top(); if (weight.empty()) { // If the dataset has no weight, we fill the data spans with a scalar - // unity weight so we don't need to check for the existance of weights + // unity weight so we don't need to check for the existence of weights // later in the likelihood. buffer.push_back(1.0); bufferSumW2.push_back(1.0); - weight = RooSpan(buffer.data(), 1); - weightSumW2 = RooSpan(bufferSumW2.data(), 1); + assignSpan(weight, {buffer.data(), 1}); + assignSpan(weightSumW2, {bufferSumW2.data(), 1}); nNonZeroWeight = nEvents; } else { buffer.reserve(nEvents); @@ -102,10 +92,9 @@ RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_v hasZeroWeight[i] = true; } } - weight = RooSpan(buffer.data(), nNonZeroWeight); - weightSumW2 = RooSpan(bufferSumW2.data(), nNonZeroWeight); + assignSpan(weight, {buffer.data(), nNonZeroWeight}); + assignSpan(weightSumW2, {bufferSumW2.data(), nNonZeroWeight}); } - using namespace ROOT::Experimental; insert(RooNLLVarNew::weightVarName, weight); insert(RooNLLVarNew::weightVarNameSumW2, weightSumW2); } @@ -114,7 +103,7 @@ RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_v // the data map for (auto const &item : data.getBatches(0, nEvents)) { - RooSpan span{item.second}; + std::span span{item.second}; buffers.emplace(); auto &buffer = buffers.top(); @@ -132,7 +121,7 @@ RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_v // the data map for (auto const &item : data.getCategoryBatches(0, nEvents)) { - RooSpan intSpan{item.second}; + std::span intSpan{item.second}; buffers.emplace(); auto &buffer = buffers.top(); @@ -183,9 +172,131 @@ RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string_v ++j; } } - dataSpans[item.first] = RooSpan{buffer, nEvents}; + assignSpan(dataSpans[item.first], {buffer, nEvents}); + } + } + + return dataSpans; +} + +} // namespace + +//////////////////////////////////////////////////////////////////////////////// +/// Extract all content from a RooFit datasets as a map of spans. +/// Spans with the weights and squared weights will be also stored in the map, +/// keyed with the names `_weight` and the `_weight_sumW2`. If the dataset is +/// unweighted, these weight spans will only contain the single value `1.0`. +/// Entries with zero weight will be skipped. +/// +/// \return A `std::map` with spans keyed to name pointers. +/// \param[in] data The input dataset. +/// \param[in] rangeName Select only entries from the data in a given range +/// (empty string for no range). +/// \param[in] simPdf A simultaneous pdf to use as a guide for splitting the +/// dataset. The spans from each channel data will be prefixed with +/// the channel name. +/// \param[in] skipZeroWeights Skip entries with zero weight when filling the +/// data spans. Be very careful with enabling it, because the user +/// might not expect that the batch results are not aligned with the +/// original dataset anymore! +/// \param[in] takeGlobalObservablesFromData Take also the global observables +/// stored in the dataset. +/// \param[in] buffers Pass here an empty stack of `double` vectors, which will +/// be used as memory for the data if the memory in the dataset +/// object can't be used directly (e.g. because you used the range +/// selection or the splitting by categories). +std::map> +RooFit::BatchModeDataHelpers::getDataSpans(RooAbsData const &data, std::string const &rangeName, + RooSimultaneous const *simPdf, bool skipZeroWeights, + bool takeGlobalObservablesFromData, std::stack> &buffers) +{ + std::vector> datasets; + std::vector isBinnedL; + bool splitRange = false; + std::vector> splitDataSets; + + if (simPdf) { + std::unique_ptr splits{data.split(*simPdf, true)}; + for (auto *d : static_range_cast(*splits)) { + RooAbsPdf *simComponent = simPdf->getPdf(d->GetName()); + // If there is no PDF for that component, we also don't need to fill the data + if (!simComponent) { + continue; + } + datasets.emplace_back(std::string("_") + d->GetName() + "_", d); + isBinnedL.emplace_back(simComponent->getAttribute("BinnedLikelihoodActive")); + // The dataset need to be kept alive because the datamap points to their content + splitDataSets.emplace_back(d); + } + splitRange = simPdf->getAttribute("SplitRange"); + } else { + datasets.emplace_back("", &data); + isBinnedL.emplace_back(false); + } + + std::map> dataSpans; // output variable + + for (std::size_t iData = 0; iData < datasets.size(); ++iData) { + auto const &toAdd = datasets[iData]; + auto spans = getSingleDataSpans( + *toAdd.second, RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, toAdd.second->GetName()), + toAdd.first, buffers, skipZeroWeights && !isBinnedL[iData]); + for (auto const &item : spans) { + dataSpans.insert(item); + } + } + + if (takeGlobalObservablesFromData && data.getGlobalObservables()) { + buffers.emplace(); + auto &buffer = buffers.top(); + buffer.reserve(data.getGlobalObservables()->size()); + for (auto *arg : static_range_cast(*data.getGlobalObservables())) { + buffer.push_back(arg->getVal()); + assignSpan(dataSpans[arg], {&buffer.back(), 1}); } } return dataSpans; } + +//////////////////////////////////////////////////////////////////////////////// +/// Figure out the output size for each node in the computation graph that +/// leads up to the top node, given some vector data as an input. The input +/// data spans are in general not of the same size, for example in the case of +/// a simultaneous fit. +/// +/// \return A `std::map` with output sizes for each node in the computation graph. +/// \param[in] topNode The top node of the computation graph. +/// \param[in] inputSizeFunc A function to get the input sizes. +std::map RooFit::BatchModeDataHelpers::determineOutputSizes( + RooAbsArg const &topNode, std::function const &inputSizeFunc) +{ + std::map output; + + RooArgSet serverSet; + RooHelpers::getSortedComputationGraph(topNode, serverSet); + + for (RooAbsArg *arg : serverSet) { + std::size_t inputSize = inputSizeFunc(arg); + if (inputSize > 0) { + output[arg] = inputSize; + } + } + + for (RooAbsArg *arg : serverSet) { + std::size_t size = 1; + if (output.find(arg) != output.end()) { + continue; + } + if (!arg->isReducerNode()) { + for (RooAbsArg *server : arg->servers()) { + if (server->isValueServer(*arg)) { + size = std::max(output.at(server), size); + } + } + } + output[arg] = size; + } + + return output; +} diff --git a/roofit/roofitcore/src/BatchModeHelpers.cxx b/roofit/roofitcore/src/BatchModeHelpers.cxx index 577ace02bea79..e3848045a69af 100644 --- a/roofit/roofitcore/src/BatchModeHelpers.cxx +++ b/roofit/roofitcore/src/BatchModeHelpers.cxx @@ -19,27 +19,21 @@ #include #include #include -#include "RooFitDriver.h" #include "RooNLLVarNew.h" #include #include #include -using ROOT::Experimental::RooFitDriver; -using ROOT::Experimental::RooNLLVarNew; - namespace { -std::unique_ptr createSimultaneousNLL(RooSimultaneous const &simPdf, RooArgSet &observables, bool isExtended, - std::string const &rangeName, RooFit::OffsetMode offset, - bool splitRange) +std::unique_ptr createSimultaneousNLL(RooSimultaneous const &simPdf, bool isExtended, + std::string const &rangeName, RooFit::OffsetMode offset) { RooAbsCategoryLValue const &simCat = simPdf.indexCat(); // Prepare the NLL terms for each component RooArgList nllTerms; - RooArgSet newObservables; for (auto const &catState : simCat) { std::string const &catName = catState.first; RooAbsCategory::value_type catIndex = catState.second; @@ -56,18 +50,12 @@ std::unique_ptr createSimultaneousNLL(RooSimultaneous const &simPdf, } if (RooAbsPdf *pdf = simPdf.getPdf(catName.c_str())) { - auto binnedInfo = RooHelpers::getBinnedL(*pdf); - if (binnedInfo.binnedPdf) { - pdf = binnedInfo.binnedPdf; - } auto name = std::string("nll_") + pdf->GetName(); - if (!rangeName.empty()) { - pdf->setNormRange(RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, catName).c_str()); - } - auto nll = std::make_unique(name.c_str(), name.c_str(), *pdf, observables, isExtended, offset, - binnedInfo.isBinnedL); - // Rename the observables and weights - newObservables.add(nll->prefixArgNames(std::string("_") + catName + "_")); + std::unique_ptr observables( + static_cast(std::unique_ptr(pdf->getVariables())->selectByAttrib("__obs__", true))); + auto nll = std::make_unique(name.c_str(), name.c_str(), *pdf, *observables, isExtended, offset); + // Rename the special variables + nll->setPrefix(std::string("_") + catName + "_"); nllTerms.addOwned(std::move(nll)); } } @@ -76,106 +64,18 @@ std::unique_ptr createSimultaneousNLL(RooSimultaneous const &simPdf, nll->setSimCount(nllTerms.size()); } - observables.clear(); - observables.add(newObservables); - // Time to sum the NLLs auto nll = std::make_unique("mynll", "mynll", nllTerms); nll->addOwnedComponents(std::move(nllTerms)); return nll; } -class RooAbsRealWrapper final : public RooAbsReal { -public: - RooAbsRealWrapper(std::unique_ptr driver, std::string const &rangeName, RooSimultaneous const *simPdf, - bool splitRange, bool takeGlobalObservablesFromData) - : RooAbsReal{"RooFitDriverWrapper", "RooFitDriverWrapper"}, _driver{std::move(driver)}, - _topNode("topNode", "top node", this, _driver->topNode()), _rangeName{rangeName}, _simPdf{simPdf}, - _splitRange{splitRange}, _takeGlobalObservablesFromData{takeGlobalObservablesFromData} - { - } - - RooAbsRealWrapper(const RooAbsRealWrapper &other, const char *name = nullptr) - : RooAbsReal{other, name}, _driver{other._driver}, _topNode("topNode", this, other._topNode), _data{other._data}, - _parameters{other._parameters}, _rangeName{other._rangeName}, _simPdf{other._simPdf}, - _splitRange{other._splitRange}, _takeGlobalObservablesFromData{other._takeGlobalObservablesFromData} - { - } - - TObject *clone(const char *newname) const override { return new RooAbsRealWrapper(*this, newname); } - - double defaultErrorLevel() const override { return _driver->topNode().defaultErrorLevel(); } - - bool getParameters(const RooArgSet *observables, RooArgSet &outputSet, bool /*stripDisconnected*/) const override - { - outputSet.add(_parameters); - if (observables) { - outputSet.remove(*observables); - } - // If we take the global observables as data, we have to return these as - // parameters instead of the parameters in the model. Otherwise, the - // constant parameters in the fit result that are global observables will - // not have the right values. - if (_takeGlobalObservablesFromData && _data->getGlobalObservables()) { - outputSet.replace(*_data->getGlobalObservables()); - } - return false; - } - - bool setData(RooAbsData &data, bool /*cloneData*/) override - { - _data = &data; - - // Figure out what are the parameters for the current dataset - _parameters.clear(); - RooArgSet params; - _driver->topNode().getParameters(_data->get(), params, true); - for (RooAbsArg *param : params) { - if (!param->getAttribute("__obs__")) { - _parameters.add(*param); - } - } - - _driver->setData(*_data, _rangeName, _simPdf, _splitRange, /*skipZeroWeights=*/true, - _takeGlobalObservablesFromData); - return true; - } - - double getValV(const RooArgSet *) const override { return evaluate(); } - - void applyWeightSquared(bool flag) override - { - const_cast(_driver->topNode()).applyWeightSquared(flag); - } - - void printMultiline(std::ostream &os, Int_t /*contents*/, bool /*verbose*/ = false, - TString /*indent*/ = "") const override - { - _driver->print(os); - } - -protected: - double evaluate() const override { return _driver ? _driver->getVal() : 0.0; } - -private: - std::shared_ptr _driver; - RooRealProxy _topNode; - RooAbsData *_data = nullptr; - RooArgSet _parameters; - std::string _rangeName; - RooSimultaneous const *_simPdf = nullptr; - bool _splitRange = false; - const bool _takeGlobalObservablesFromData; -}; - } // namespace std::unique_ptr -RooFit::BatchModeHelpers::createNLL(std::unique_ptr &&pdf, RooAbsData &data, - std::unique_ptr &&constraints, std::string const &rangeName, - RooArgSet const &projDeps, bool isExtended, double integrateOverBinsPrecision, - RooFit::BatchModeOption batchMode, RooFit::OffsetMode offset, bool splitRange, - bool takeGlobalObservablesFromData) +RooFit::BatchModeHelpers::createNLL(RooAbsPdf &pdf, RooAbsData &data, std::unique_ptr &&constraints, + std::string const &rangeName, RooArgSet const &projDeps, bool isExtended, + double integrateOverBinsPrecision, RooFit::OffsetMode offset) { if (constraints) { // Redirect the global observables to the ones from the dataset if applicable. @@ -187,23 +87,18 @@ RooFit::BatchModeHelpers::createNLL(std::unique_ptr &&pdf, RooAbsData } RooArgSet observables; - pdf->getObservables(data.get(), observables); + pdf.getObservables(data.get(), observables); observables.remove(projDeps, true, true); - // Set the normalization range - if (!rangeName.empty()) { - pdf->setNormRange(rangeName.c_str()); - } - - oocxcoutI(pdf.get(), Fitting) << "RooAbsPdf::fitTo(" << pdf->GetName() - << ") fixing normalization set for coefficient determination to observables in data" - << "\n"; - pdf->fixAddCoefNormalization(observables, false); + oocxcoutI(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName() + << ") fixing normalization set for coefficient determination to observables in data" + << "\n"; + pdf.fixAddCoefNormalization(observables, false); // Deal with the IntegrateBins argument RooArgList binSamplingPdfs; - std::unique_ptr wrappedPdf = RooBinSamplingPdf::create(*pdf, data, integrateOverBinsPrecision); - RooAbsPdf &finalPdf = wrappedPdf ? *wrappedPdf : *pdf; + std::unique_ptr wrappedPdf = RooBinSamplingPdf::create(pdf, data, integrateOverBinsPrecision); + RooAbsPdf &finalPdf = wrappedPdf ? *wrappedPdf : pdf; if (wrappedPdf) { binSamplingPdfs.addOwned(std::move(wrappedPdf)); } @@ -214,8 +109,7 @@ RooFit::BatchModeHelpers::createNLL(std::unique_ptr &&pdf, RooAbsData auto simPdf = dynamic_cast(&finalPdf); if (simPdf) { simPdf->wrapPdfsInBinSamplingPdfs(data, integrateOverBinsPrecision); - // Warning! This mutates "observables" - nllTerms.addOwned(createSimultaneousNLL(*simPdf, observables, isExtended, rangeName, offset, splitRange)); + nllTerms.addOwned(createSimultaneousNLL(*simPdf, isExtended, rangeName, offset)); } else { nllTerms.addOwned( std::make_unique("RooNLLVarNew", "RooNLLVarNew", finalPdf, observables, isExtended, offset)); @@ -224,55 +118,10 @@ RooFit::BatchModeHelpers::createNLL(std::unique_ptr &&pdf, RooAbsData nllTerms.addOwned(std::move(constraints)); } - std::string nllName = std::string("nll_") + pdf->GetName() + "_" + data.GetName(); + std::string nllName = std::string("nll_") + pdf.GetName() + "_" + data.GetName(); auto nll = std::make_unique(nllName.c_str(), nllName.c_str(), nllTerms); nll->addOwnedComponents(std::move(binSamplingPdfs)); nll->addOwnedComponents(std::move(nllTerms)); - auto driver = std::make_unique(*nll, observables, batchMode); - - auto driverWrapper = std::make_unique(std::move(driver), rangeName, simPdf, splitRange, - takeGlobalObservablesFromData); - driverWrapper->setData(data, false); - driverWrapper->addOwnedComponents(std::move(nll)); - driverWrapper->addOwnedComponents(std::move(pdf)); - - return driverWrapper; -} - -void RooFit::BatchModeHelpers::logArchitectureInfo(RooFit::BatchModeOption batchMode) -{ - // We have to exit early if the message stream is not active. Otherwise it's - // possible that this funciton skips logging because it thinks it has - // already logged, but actually it didn't. - if (!RooMsgService::instance().isActive(static_cast(nullptr), RooFit::Fitting, RooFit::INFO)) { - return; - } - - // Don't repeat logging architecture info if the batchMode option didn't change - { - // Second element of pair tracks whether this function has already been called - static std::pair lastBatchMode; - if (lastBatchMode.second && lastBatchMode.first == batchMode) - return; - lastBatchMode = {batchMode, true}; - } - - auto log = [](std::string_view message) { - oocxcoutI(static_cast(nullptr), Fitting) << message << std::endl; - }; - - if (batchMode == RooFit::BatchModeOption::Cuda && !RooBatchCompute::dispatchCUDA) { - throw std::runtime_error(std::string("In: ") + __func__ + "(), " + __FILE__ + ":" + __LINE__ + - ": Cuda implementation of the computing library is not available\n"); - } - if (RooBatchCompute::dispatchCPU->architecture() == RooBatchCompute::Architecture::GENERIC) { - log("using generic CPU library compiled with no vectorizations"); - } else { - log(std::string("using CPU computation library compiled with -m") + - RooBatchCompute::dispatchCPU->architectureName()); - } - if (batchMode == RooFit::BatchModeOption::Cuda) { - log("using CUDA computation library"); - } + return nll; } diff --git a/roofit/roofitcore/src/BidirMMapPipe.cxx b/roofit/roofitcore/src/BidirMMapPipe.cxx index 6405e603ad22c..3c499cda4f045 100644 --- a/roofit/roofitcore/src/BidirMMapPipe.cxx +++ b/roofit/roofitcore/src/BidirMMapPipe.cxx @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + /** @file BidirMMapPipe.cxx * * implementation of BidirMMapPipe, a class which forks off a child process @@ -6,11 +8,12 @@ * @author Manuel Schiller * @date 2013-07-07 */ + #ifndef _WIN32 #include "BidirMMapPipe.h" -#include +#include #include #include @@ -114,7 +117,7 @@ namespace BidirMMapPipe_impl { unsigned short m_pos; ///< index of next byte in payload area /// copy construction forbidden Page(const Page&) {} - /// assigment forbidden + /// assignment forbidden Page& operator=(const Page&) = delete; public: /// constructor @@ -461,7 +464,8 @@ namespace BidirMMapPipe_impl { return retVal; } if (FileBacked == s_mmapworks || Unknown == s_mmapworks) { - std::string name = RooFit::tmpPath() + "BidirMMapPipe-XXXXXX"; + std::string tmpPath = gSystem->TempDirectory(); + std::string name = tmpPath + "/roofit_BidirMMapPipe-XXXXXX"; int fd; // open temp file if (-1 == (fd = ::mkstemp(const_cast(name.c_str())))) throw Exception("mkstemp", errno); @@ -828,7 +832,7 @@ BidirMMapPipe::BidirMMapPipe(bool useExceptions, bool useSocketpair) : pthread_mutex_unlock(&s_openpipesmutex); // ok, put our pages on freelist m_freelist = m_pages[PagesPerEnd]; - // handshare with other end (to make sure it's alive)... + // handshake with other end (to make sure it's alive)... c = 'C'; // ...hild if (1 != xferraw(m_outpipe, &c, 1, ::write)) throw Exception("handshake: xferraw write", EPIPE); @@ -864,7 +868,7 @@ BidirMMapPipe::BidirMMapPipe(bool useExceptions, bool useSocketpair) : pthread_mutex_unlock(&s_openpipesmutex); // ok, put our pages on freelist m_freelist = m_pages[0u]; - // handshare with other end (to make sure it's alive)... + // handshake with other end (to make sure it's alive)... c = 'P'; // ...arent if (1 != xferraw(m_outpipe, &c, 1, ::write)) throw Exception("handshake: xferraw write", EPIPE); @@ -1998,3 +2002,5 @@ int main() #endif // _WIN32 // vim: ft=cpp:sw=4:tw=78:et + +/// \endcond diff --git a/roofit/roofitcore/src/BidirMMapPipe.h b/roofit/roofitcore/src/BidirMMapPipe.h index 686f4866b89e7..959490b55d4b7 100644 --- a/roofit/roofitcore/src/BidirMMapPipe.h +++ b/roofit/roofitcore/src/BidirMMapPipe.h @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + /** @file BidirMMapPipe.h * * header file for BidirMMapPipe, a class which forks off a child process and @@ -142,7 +144,7 @@ namespace BidirMMapPipe_impl { } impl; public: /// default constructor - Pages() : m_pimpl(0) { } + Pages() : m_pimpl(nullptr) { } /// destructor ~Pages(); @@ -449,7 +451,7 @@ class BidirMMapPipe { */ size_type read(void* addr, size_type sz); - /** @brief wirte to pipe + /** @brief write to pipe * * @param addr where to get data to write from * @param sz size of data to write (in bytes) @@ -556,7 +558,7 @@ class BidirMMapPipe { * conditions are polled for, otherwise only the indicated ones. On * return, the revents fields contain the events that occurred for each * pipe; error Error, EndOfFile or Invalid events are always set, - * regardless of wether they were in the set of requested events. + * regardless of whether they were in the set of requested events. * * poll may block slightly longer than specified by timeout due to OS * timer granularity and OS scheduling. Due to its implementation, the @@ -943,7 +945,7 @@ class BidirMMapPipe { * * @param plist linked list of pages to send * - * the implementation gathers the different write(s) whereever + * the implementation gathers the different write(s) wherever * possible; if mmap works, this results in a single write to transfer * the list of pages sent, if we need to copy things through the pipe, * we have one write to transfer which pages are sent, and then one @@ -992,3 +994,5 @@ END_NAMESPACE_ROOFIT #endif // BIDIRMMAPPIPE_H // vim: ft=cpp:sw=4:tw=78:et + +/// \endcond diff --git a/roofit/roofitcore/src/Buffers.cxx b/roofit/roofitcore/src/Buffers.cxx index ebfe32154c02c..e34020f709928 100644 --- a/roofit/roofitcore/src/Buffers.cxx +++ b/roofit/roofitcore/src/Buffers.cxx @@ -12,14 +12,17 @@ #include "RooFit/Detail/Buffers.h" -#include - +#include #include #include #include -namespace ROOT { -namespace Experimental { +#ifdef R__HAS_CUDA +namespace CudaInterface = RooFit::Detail::CudaInterface; +using CudaInterface::CudaStream; +#endif + +namespace RooFit { namespace Detail { class ScalarBufferContainer { @@ -44,7 +47,6 @@ class ScalarBufferContainer { class CPUBufferContainer { public: - CPUBufferContainer() {} CPUBufferContainer(std::size_t size) : _vec(size) {} std::size_t size() const { return _vec.size(); } @@ -66,93 +68,53 @@ class CPUBufferContainer { std::vector _vec; }; +#ifdef R__HAS_CUDA class GPUBufferContainer { public: - GPUBufferContainer() {} - GPUBufferContainer(std::size_t size) - { - _data = static_cast(RooBatchCompute::dispatchCUDA->cudaMalloc(size * sizeof(double))); - _size = size; - } - ~GPUBufferContainer() - { - if (_data) - RooBatchCompute::dispatchCUDA->cudaFree(_data); - } - GPUBufferContainer(const GPUBufferContainer &) = delete; - GPUBufferContainer &operator=(const GPUBufferContainer &) = delete; - GPUBufferContainer(GPUBufferContainer &&other) { *this = std::move(other); } - GPUBufferContainer &operator=(GPUBufferContainer &&other) - { - _data = other._data; - other._data = nullptr; - _size = other._size; - other._size = 0; - return *this; - } - std::size_t size() const { return _size; } + GPUBufferContainer(std::size_t size) : _arr(size) {} + std::size_t size() const { return _arr.size(); } double const *cpuReadPtr() const { throw std::bad_function_call(); return nullptr; } - double const *gpuReadPtr() const { return static_cast(_data); } + double const *gpuReadPtr() const { return _arr.data(); } double *cpuWritePtr() const { throw std::bad_function_call(); return nullptr; } - double *gpuWritePtr() const { return static_cast(_data); } + double *gpuWritePtr() const { return const_cast(_arr.data()); } private: - double *_data = nullptr; - std::size_t _size; + CudaInterface::DeviceArray _arr; }; class PinnedBufferContainer { public: - PinnedBufferContainer() {} - PinnedBufferContainer(std::size_t size) - { - _data = static_cast(RooBatchCompute::dispatchCUDA->cudaMallocHost(size * sizeof(double))); - _size = size; - _gpuBuffer = GPUBufferContainer{size}; - } - PinnedBufferContainer(const PinnedBufferContainer &) = delete; - PinnedBufferContainer &operator=(const PinnedBufferContainer &) = delete; - PinnedBufferContainer(PinnedBufferContainer &&other) { *this = std::move(other); } - PinnedBufferContainer &operator=(PinnedBufferContainer &&other) - { - _data = other._data; - other._data = nullptr; - _size = other._size; - other._size = 0; - _gpuBuffer = std::move(other._gpuBuffer); - return *this; - } - std::size_t size() const { return _size; } + PinnedBufferContainer(std::size_t size) : _arr{size}, _gpuBuffer{size} {} + std::size_t size() const { return _arr.size(); } - void setCudaStream(cudaStream_t *stream) { _cudaStream = stream; } + void setCudaStream(CudaStream *stream) { _cudaStream = stream; } double const *cpuReadPtr() const { if (_lastAccess == LastAccessType::GPU_WRITE) { - RooBatchCompute::dispatchCUDA->memcpyToCPU(_data, _gpuBuffer.gpuWritePtr(), _size * sizeof(double), - _cudaStream); + CudaInterface::copyDeviceToHost(_gpuBuffer.gpuReadPtr(), const_cast(_arr.data()), size(), + _cudaStream); } _lastAccess = LastAccessType::CPU_READ; - return static_cast(_data); + return const_cast(_arr.data()); } double const *gpuReadPtr() const { if (_lastAccess == LastAccessType::CPU_WRITE) { - RooBatchCompute::dispatchCUDA->memcpyToCUDA(_gpuBuffer.gpuWritePtr(), _data, _size * sizeof(double), - _cudaStream); + CudaInterface::copyHostToDevice(_arr.data(), _gpuBuffer.gpuWritePtr(), size(), _cudaStream); } _lastAccess = LastAccessType::GPU_READ; @@ -162,7 +124,7 @@ class PinnedBufferContainer { double *cpuWritePtr() { _lastAccess = LastAccessType::CPU_WRITE; - return static_cast(_data); + return _arr.data(); } double *gpuWritePtr() { @@ -173,23 +135,23 @@ class PinnedBufferContainer { private: enum class LastAccessType { CPU_READ, GPU_READ, CPU_WRITE, GPU_WRITE }; - double *_data = nullptr; - std::size_t _size; + CudaInterface::PinnedHostArray _arr; GPUBufferContainer _gpuBuffer; - cudaStream_t *_cudaStream = nullptr; + CudaStream *_cudaStream = nullptr; mutable LastAccessType _lastAccess = LastAccessType::CPU_READ; }; +#endif // R__HAS_CUDA template class BufferImpl : public AbsBuffer { public: - using Queue = std::queue; + using Queue = std::queue>; using QueuesMap = std::map; BufferImpl(std::size_t size, QueuesMap &queuesMap) : _queue{queuesMap[size]} { if (_queue.empty()) { - _vec = Container(size); + _vec = std::make_unique(size); } else { _vec = std::move(_queue.front()); _queue.pop(); @@ -198,60 +160,62 @@ class BufferImpl : public AbsBuffer { ~BufferImpl() override { _queue.emplace(std::move(_vec)); } - double const *cpuReadPtr() const override { return _vec.cpuReadPtr(); } - double const *gpuReadPtr() const override { return _vec.gpuReadPtr(); } + double const *cpuReadPtr() const override { return _vec->cpuReadPtr(); } + double const *gpuReadPtr() const override { return _vec->gpuReadPtr(); } - double *cpuWritePtr() override { return _vec.cpuWritePtr(); } - double *gpuWritePtr() override { return _vec.gpuWritePtr(); } + double *cpuWritePtr() override { return _vec->cpuWritePtr(); } + double *gpuWritePtr() override { return _vec->gpuWritePtr(); } - Container &vec() { return _vec; } + Container &vec() { return *_vec; } private: - Container _vec; + std::unique_ptr _vec; Queue &_queue; }; using ScalarBuffer = BufferImpl; using CPUBuffer = BufferImpl; +#ifdef R__HAS_CUDA using GPUBuffer = BufferImpl; using PinnedBuffer = BufferImpl; +#endif struct BufferQueuesMaps { ScalarBuffer::QueuesMap scalarBufferQueuesMap; CPUBuffer::QueuesMap cpuBufferQueuesMap; +#ifdef R__HAS_CUDA GPUBuffer::QueuesMap gpuBufferQueuesMap; PinnedBuffer::QueuesMap pinnedBufferQueuesMap; +#endif }; BufferManager::BufferManager() { - _queuesMaps = new BufferQueuesMaps; + _queuesMaps = std::make_unique(); } -BufferManager::~BufferManager() -{ - delete _queuesMaps; -} +BufferManager::~BufferManager() = default; -AbsBuffer *BufferManager::makeScalarBuffer() +std::unique_ptr BufferManager::makeScalarBuffer() { - return new ScalarBuffer{1, _queuesMaps->scalarBufferQueuesMap}; + return std::make_unique(1, _queuesMaps->scalarBufferQueuesMap); } -AbsBuffer *BufferManager::makeCpuBuffer(std::size_t size) +std::unique_ptr BufferManager::makeCpuBuffer(std::size_t size) { - return new CPUBuffer{size, _queuesMaps->cpuBufferQueuesMap}; + return std::make_unique(size, _queuesMaps->cpuBufferQueuesMap); } -AbsBuffer *BufferManager::makeGpuBuffer(std::size_t size) +#ifdef R__HAS_CUDA +std::unique_ptr BufferManager::makeGpuBuffer(std::size_t size) { - return new GPUBuffer{size, _queuesMaps->gpuBufferQueuesMap}; + return std::make_unique(size, _queuesMaps->gpuBufferQueuesMap); } -AbsBuffer *BufferManager::makePinnedBuffer(std::size_t size, cudaStream_t *stream) +std::unique_ptr BufferManager::makePinnedBuffer(std::size_t size, CudaStream *stream) { - auto out = new PinnedBuffer{size, _queuesMaps->pinnedBufferQueuesMap}; + auto out = std::make_unique(size, _queuesMaps->pinnedBufferQueuesMap); out->vec().setCudaStream(stream); return out; } +#endif // R__HAS_CUDA } // end namespace Detail -} // end namespace Experimental -} // end namespace ROOT +} // end namespace RooFit diff --git a/roofit/roofitcore/src/CUDAHelpers.cxx b/roofit/roofitcore/src/CUDAHelpers.cxx deleted file mode 100644 index db9ca59cef855..0000000000000 --- a/roofit/roofitcore/src/CUDAHelpers.cxx +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Project: RooFit - * Authors: - * Jonas Rembser, CERN 2022 - * - * Copyright (c) 2022, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#include "RooFit/CUDAHelpers.h" - -#include - -/// Measure the time for transfering data from host to device and vice-versa. -std::pair RooFit::CUDAHelpers::memcpyBenchmark(std::size_t nBytes) -{ - using namespace std::chrono; - - std::pair ret; - auto hostArr = static_cast(RooBatchCompute::dispatchCUDA->cudaMallocHost(nBytes)); - auto deviArr = static_cast(RooBatchCompute::dispatchCUDA->cudaMalloc(nBytes)); - for (int i = 0; i < 5; i++) { - auto start = steady_clock::now(); - RooBatchCompute::dispatchCUDA->memcpyToCUDA(deviArr, hostArr, nBytes); - ret.first += duration_cast(steady_clock::now() - start); - start = steady_clock::now(); - RooBatchCompute::dispatchCUDA->memcpyToCPU(hostArr, deviArr, nBytes); - ret.second += duration_cast(steady_clock::now() - start); - } - RooBatchCompute::dispatchCUDA->cudaFreeHost(hostArr); - RooBatchCompute::dispatchCUDA->cudaFree(deviArr); - ret.first /= 5; - ret.second /= 5; - return ret; -} diff --git a/roofit/roofitcore/src/ConstraintHelpers.cxx b/roofit/roofitcore/src/ConstraintHelpers.cxx index e9a9da1069db4..75d699acba9dd 100644 --- a/roofit/roofitcore/src/ConstraintHelpers.cxx +++ b/roofit/roofitcore/src/ConstraintHelpers.cxx @@ -30,7 +30,7 @@ getGlobalObservables(RooAbsPdf const &pdf, RooArgSet const *globalObservables, c throw std::invalid_argument(errMsg); } if (globalObservables) { - // pass-throught of global observables + // pass-through of global observables return std::make_unique(*globalObservables); } diff --git a/roofit/roofitcore/src/FitHelpers.cxx b/roofit/roofitcore/src/FitHelpers.cxx new file mode 100644 index 0000000000000..a4d80494a2fb1 --- /dev/null +++ b/roofit/roofitcore/src/FitHelpers.cxx @@ -0,0 +1,359 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include "FitHelpers.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace RooFit { +namespace FitHelpers { + +//////////////////////////////////////////////////////////////////////////////// +/// Use the asymptotically correct approach to estimate errors in the presence of weights. +/// This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303). +/// Applies the calculated covaraince matrix to the RooMinimizer and returns +/// the quality of the covariance matrix. +/// See also the documentation of RooAbsPdf::fitTo(), where this function is used. +/// \param[in] minimizer The RooMinimizer to get the fit result from. The state +/// of the minimizer will be altered by this function: the covariance +/// matrix caltulated here will be applied to it via +/// RooMinimizer::applyCovarianceMatrix(). +/// \param[in] data The dataset that was used for the fit. +int calcAsymptoticCorrectedCovariance(RooAbsReal &pdf, RooMinimizer &minimizer, RooAbsData const &data) +{ + // Calculated corrected errors for weighted likelihood fits + std::unique_ptr rw(minimizer.save()); + // Weighted inverse Hessian matrix + const TMatrixDSym &matV = rw->covarianceMatrix(); + oocoutI(&pdf, Fitting) + << "RooAbsPdf::fitTo(" << pdf.GetName() + << ") Calculating covariance matrix according to the asymptotically correct approach. If you find this " + "method useful please consider citing https://arxiv.org/abs/1911.01303.\n"; + + // Initialise matrix containing first derivatives + auto nFloatPars = rw->floatParsFinal().getSize(); + TMatrixDSym num(nFloatPars); + for (int k = 0; k < nFloatPars; k++) { + for (int l = 0; l < nFloatPars; l++) { + num(k, l) = 0.0; + } + } + RooArgSet obs; + pdf.getObservables(data.get(), obs); + // Create derivative objects + std::vector> derivatives; + const RooArgList &floated = rw->floatParsFinal(); + std::unique_ptr floatingparams{ + static_cast(pdf.getParameters(data)->selectByAttrib("Constant", false))}; + for (const auto paramresult : floated) { + auto paraminternal = static_cast(floatingparams->find(*paramresult)); + assert(floatingparams->find(*paramresult)->IsA() == RooRealVar::Class()); + derivatives.emplace_back(pdf.derivative(*paraminternal, obs, 1)); + } + + // Loop over data + for (int j = 0; j < data.numEntries(); j++) { + // Sets obs to current data point, this is where the pdf will be evaluated + obs.assign(*data.get(j)); + // Determine first derivatives + std::vector diffs(floated.getSize(), 0.0); + for (int k = 0; k < floated.getSize(); k++) { + const auto paramresult = static_cast(floated.at(k)); + auto paraminternal = static_cast(floatingparams->find(*paramresult)); + // first derivative to parameter k at best estimate point for this measurement + double diff = derivatives[k]->getVal(); + // need to reset to best fit point after differentiation + *paraminternal = paramresult->getVal(); + diffs[k] = diff; + } + // Fill numerator matrix + double prob = pdf.getVal(&obs); + for (int k = 0; k < floated.getSize(); k++) { + for (int l = 0; l < floated.getSize(); l++) { + num(k, l) += data.weightSquared() * diffs[k] * diffs[l] / (prob * prob); + } + } + } + num.Similarity(matV); + + // Propagate corrected errors to parameters objects + minimizer.applyCovarianceMatrix(num); + + // The derivatives are found in RooFit and not with the minimizer (e.g. + // minuit), so the quality of the corrected covariance matrix corresponds to + // the quality of the original covariance matrix + return rw->covQual(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Apply correction to errors and covariance matrix. This uses two covariance +/// matrices, one with the weights, the other with squared weights, to obtain +/// the correct errors for weighted likelihood fits. +/// Applies the calculated covaraince matrix to the RooMinimizer and returns +/// the quality of the covariance matrix. +/// See also the documentation of RooAbsPdf::fitTo(), where this function is used. +/// \param[in] minimizer The RooMinimizer to get the fit result from. The state +/// of the minimizer will be altered by this function: the covariance +/// matrix caltulated here will be applied to it via +/// RooMinimizer::applyCovarianceMatrix(). +/// \param[in] nll The NLL object that was used for the fit. +int calcSumW2CorrectedCovariance(RooAbsReal const &pdf, RooMinimizer &minimizer, RooAbsReal &nll) +{ + // Calculated corrected errors for weighted likelihood fits + std::unique_ptr rw{minimizer.save()}; + nll.applyWeightSquared(true); + oocoutI(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName() + << ") Calculating sum-of-weights-squared correction matrix for covariance matrix\n"; + minimizer.hesse(); + std::unique_ptr rw2{minimizer.save()}; + nll.applyWeightSquared(false); + + // Apply correction matrix + const TMatrixDSym &matV = rw->covarianceMatrix(); + TMatrixDSym matC = rw2->covarianceMatrix(); + ROOT::Math::CholeskyDecompGenDim decomp(matC.GetNrows(), matC); + if (!decomp) { + oocoutE(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName() + << ") ERROR: Cannot apply sum-of-weights correction to covariance matrix: correction " + "matrix calculated with weight-squared is singular\n"; + return -1; + } + + // replace C by its inverse + decomp.Invert(matC); + // the class lies about the matrix being symmetric, so fill in the + // part above the diagonal + for (int i = 0; i < matC.GetNrows(); ++i) { + for (int j = 0; j < i; ++j) { + matC(j, i) = matC(i, j); + } + } + matC.Similarity(matV); + // C now contains V C^-1 V + // Propagate corrected errors to parameters objects + minimizer.applyCovarianceMatrix(matC); + + return std::min(rw->covQual(), rw2->covQual()); +} + +namespace { + +/// Configuration struct for RooAbsPdf::minimizeNLL with all the default values +/// that also should be taked as the default values for RooAbsPdf::fitTo. +struct MinimizerConfig { + double recoverFromNaN = 10.; + int optConst = 2; + int verbose = 0; + int doSave = 0; + int doTimer = 0; + int printLevel = 1; + int strategy = 1; + int initHesse = 0; + int hesse = 1; + int minos = 0; + int numee = 10; + int doEEWall = 1; + int doWarn = 1; + int doSumW2 = -1; + int doAsymptotic = -1; + int maxCalls = -1; + int doOffset = -1; + int parallelize = 0; + bool enableParallelGradient = true; + bool enableParallelDescent = false; + bool timingAnalysis = false; + const RooArgSet *minosSet = nullptr; + std::string minType; + std::string minAlg = "minuit"; +}; + +} // namespace + +void defineMinimizationOptions(RooCmdConfig &pc) +{ + // Default-initialized instance of MinimizerConfig to get the default + // minimizer parameter values. + MinimizerConfig minimizerDefaults; + + pc.defineDouble("RecoverFromUndefinedRegions", "RecoverFromUndefinedRegions", 0, minimizerDefaults.recoverFromNaN); + pc.defineInt("optConst", "Optimize", 0, minimizerDefaults.optConst); + pc.defineInt("verbose", "Verbose", 0, minimizerDefaults.verbose); + pc.defineInt("doSave", "Save", 0, minimizerDefaults.doSave); + pc.defineInt("doTimer", "Timer", 0, minimizerDefaults.doTimer); + pc.defineInt("printLevel", "PrintLevel", 0, minimizerDefaults.printLevel); + pc.defineInt("strategy", "Strategy", 0, minimizerDefaults.strategy); + pc.defineInt("initHesse", "InitialHesse", 0, minimizerDefaults.initHesse); + pc.defineInt("hesse", "Hesse", 0, minimizerDefaults.hesse); + pc.defineInt("minos", "Minos", 0, minimizerDefaults.minos); + pc.defineInt("numee", "PrintEvalErrors", 0, minimizerDefaults.numee); + pc.defineInt("doEEWall", "EvalErrorWall", 0, minimizerDefaults.doEEWall); + pc.defineInt("doWarn", "Warnings", 0, minimizerDefaults.doWarn); + pc.defineInt("doSumW2", "SumW2Error", 0, minimizerDefaults.doSumW2); + pc.defineInt("doAsymptoticError", "AsymptoticError", 0, minimizerDefaults.doAsymptotic); + pc.defineInt("maxCalls", "MaxCalls", 0, minimizerDefaults.maxCalls); + pc.defineInt("doOffset", "OffsetLikelihood", 0, 0); + pc.defineInt("parallelize", "Parallelize", 0, 0); // Three parallelize arguments + pc.defineInt("enableParallelGradient", "ParallelGradientOptions", 0, 0); + pc.defineInt("enableParallelDescent", "ParallelDescentOptions", 0, 0); + pc.defineInt("timingAnalysis", "TimingAnalysis", 0, 0); + pc.defineString("mintype", "Minimizer", 0, minimizerDefaults.minType.c_str()); + pc.defineString("minalg", "Minimizer", 1, minimizerDefaults.minAlg.c_str()); + pc.defineSet("minosSet", "Minos", 0, minimizerDefaults.minosSet); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Minimizes a given NLL variable by finding the optimal parameters with the +/// RooMinimzer. The NLL variable can be created with RooAbsPdf::createNLL. +/// If you are looking for a function that combines likelihood creation with +/// fitting, see RooAbsPdf::fitTo. +/// \param[in] nll The negative log-likelihood variable to minimize. +/// \param[in] data The dataset that was also used for the NLL. It's a necessary +/// parameter because it is used in the asymptotic error correction. +/// \param[in] cfg Configuration struct with all the configuration options for +/// the RooMinimizer. These are a subset of the options that you can +/// also pass to RooAbsPdf::fitTo via the RooFit command arguments. +std::unique_ptr minimize(RooAbsReal &pdf, RooAbsReal &nll, RooAbsData const &data, RooCmdConfig const &pc) +{ + MinimizerConfig cfg; + cfg.recoverFromNaN = pc.getDouble("RecoverFromUndefinedRegions"); + cfg.optConst = pc.getInt("optConst"); + cfg.verbose = pc.getInt("verbose"); + cfg.doSave = pc.getInt("doSave"); + cfg.doTimer = pc.getInt("doTimer"); + cfg.printLevel = pc.getInt("printLevel"); + cfg.strategy = pc.getInt("strategy"); + cfg.initHesse = pc.getInt("initHesse"); + cfg.hesse = pc.getInt("hesse"); + cfg.minos = pc.getInt("minos"); + cfg.numee = pc.getInt("numee"); + cfg.doEEWall = pc.getInt("doEEWall"); + cfg.doWarn = pc.getInt("doWarn"); + cfg.doSumW2 = pc.getInt("doSumW2"); + cfg.doAsymptotic = pc.getInt("doAsymptoticError"); + cfg.maxCalls = pc.getInt("maxCalls"); + cfg.minosSet = pc.getSet("minosSet"); + cfg.minType = pc.getString("mintype", ""); + cfg.minAlg = pc.getString("minalg", "minuit"); + cfg.doOffset = pc.getInt("doOffset"); + cfg.parallelize = pc.getInt("parallelize"); + cfg.enableParallelGradient = pc.getInt("enableParallelGradient"); + cfg.enableParallelDescent = pc.getInt("enableParallelDescent"); + cfg.timingAnalysis = pc.getInt("timingAnalysis"); + + // Determine if the dataset has weights + bool weightedData = data.isNonPoissonWeighted(); + + std::string msgPrefix = std::string{"RooAbsPdf::fitTo("} + pdf.GetName() + "): "; + + // Warn user that a method to determine parameter uncertainties should be provided if weighted data is offered + if (weightedData && cfg.doSumW2 == -1 && cfg.doAsymptotic == -1) { + oocoutW(&pdf, InputArguments) << msgPrefix << + R"(WARNING: a likelihood fit is requested of what appears to be weighted data. + While the estimated values of the parameters will always be calculated taking the weights into account, + there are multiple ways to estimate the errors of the parameters. You are advised to make an + explicit choice for the error calculation: + - Either provide SumW2Error(true), to calculate a sum-of-weights-corrected HESSE error matrix + (error will be proportional to the number of events in MC). + - Or provide SumW2Error(false), to return errors from original HESSE error matrix + (which will be proportional to the sum of the weights, i.e., a dataset with events). + - Or provide AsymptoticError(true), to use the asymptotically correct expression + (for details see https://arxiv.org/abs/1911.01303)." +)"; + } + + if (cfg.minos && (cfg.doSumW2 == 1 || cfg.doAsymptotic == 1)) { + oocoutE(&pdf, InputArguments) + << msgPrefix + << " sum-of-weights and asymptotic error correction do not work with MINOS errors. Not fitting.\n"; + return nullptr; + } + if (cfg.doAsymptotic == 1 && cfg.minos) { + oocoutW(&pdf, InputArguments) << msgPrefix << "WARNING: asymptotic correction does not apply to MINOS errors\n"; + } + + // avoid setting both SumW2 and Asymptotic for uncertainty correction + if (cfg.doSumW2 == 1 && cfg.doAsymptotic == 1) { + oocoutE(&pdf, InputArguments) << msgPrefix + << "ERROR: Cannot compute both asymptotically correct and SumW2 errors.\n"; + return nullptr; + } + + // Instantiate RooMinimizer + RooMinimizer::Config minimizerConfig; + minimizerConfig.enableParallelGradient = cfg.enableParallelGradient; + minimizerConfig.enableParallelDescent = cfg.enableParallelDescent; + minimizerConfig.parallelize = cfg.parallelize; + minimizerConfig.timingAnalysis = cfg.timingAnalysis; + minimizerConfig.offsetting = cfg.doOffset; + RooMinimizer m(nll, minimizerConfig); + + m.setMinimizerType(cfg.minType.c_str()); + m.setEvalErrorWall(cfg.doEEWall); + m.setRecoverFromNaNStrength(cfg.recoverFromNaN); + m.setPrintEvalErrors(cfg.numee); + if (cfg.maxCalls > 0) + m.setMaxFunctionCalls(cfg.maxCalls); + if (cfg.printLevel != 1) + m.setPrintLevel(cfg.printLevel); + if (cfg.optConst) + m.optimizeConst(cfg.optConst); // Activate constant term optimization + if (cfg.verbose) + m.setVerbose(1); // Activate verbose options + if (cfg.doTimer) + m.setProfile(1); // Activate timer options + if (cfg.strategy != 1) + m.setStrategy(cfg.strategy); // Modify fit strategy + if (cfg.initHesse) + m.hesse(); // Initialize errors with hesse + m.minimize(cfg.minType.c_str(), cfg.minAlg.c_str()); // Minimize using chosen algorithm + if (cfg.hesse) + m.hesse(); // Evaluate errors with Hesse + + int corrCovQual = -1; + + if (m.getNPar() > 0) { + if (cfg.doAsymptotic == 1) + corrCovQual = RooFit::FitHelpers::calcAsymptoticCorrectedCovariance(pdf, m, data); // Asymptotically correct + if (cfg.doSumW2 == 1) + corrCovQual = RooFit::FitHelpers::calcSumW2CorrectedCovariance(pdf, m, nll); + } + + if (cfg.minos) + cfg.minosSet ? m.minos(*cfg.minosSet) : m.minos(); // Evaluate errs with Minos + + // Optionally return fit result + std::unique_ptr ret; + if (cfg.doSave) { + auto name = std::string("fitresult_") + pdf.GetName() + "_" + data.GetName(); + auto title = std::string("Result of fit of p.d.f. ") + pdf.GetName() + " to dataset " + data.GetName(); + ret = std::unique_ptr{m.save(name.c_str(), title.c_str())}; + if ((cfg.doSumW2 == 1 || cfg.doAsymptotic == 1) && m.getNPar() > 0) + ret->setCovQual(corrCovQual); + } + + if (cfg.optConst) + m.optimizeConst(0); + return ret; +} + +} // namespace FitHelpers +} // namespace RooFit diff --git a/roofit/roofitcore/src/FitHelpers.h b/roofit/roofitcore/src/FitHelpers.h new file mode 100644 index 0000000000000..a0d7863d63d6e --- /dev/null +++ b/roofit/roofitcore/src/FitHelpers.h @@ -0,0 +1,42 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_FitHelpers_h +#define RooFit_FitHelpers_h + +#include +#include + +class RooAbsData; +class RooAbsPdf; +class RooAbsReal; +class RooArgSet; +class RooCmdConfig; +class RooFitResult; +class RooLinkedList; +class RooMinimizer; + +namespace RooFit { +namespace FitHelpers { + +int calcAsymptoticCorrectedCovariance(RooAbsPdf &pdf, RooMinimizer &minimizer, RooAbsData const &data); +int calcSumW2CorrectedCovariance(RooAbsPdf const &pdf, RooMinimizer &minimizer, RooAbsReal &nll); + +void defineMinimizationOptions(RooCmdConfig &pc); +std::unique_ptr minimize(RooAbsReal &model, RooAbsReal &nll, RooAbsData const &data, RooCmdConfig const &pc); + +constexpr int extendedFitDefault = 2; + +} // namespace FitHelpers +} // namespace RooFit + +#endif diff --git a/roofit/roofitcore/src/ModelConfig.cxx b/roofit/roofitcore/src/ModelConfig.cxx new file mode 100644 index 0000000000000..0db23c21b6bb9 --- /dev/null +++ b/roofit/roofitcore/src/ModelConfig.cxx @@ -0,0 +1,468 @@ +/* + * Project: RooFit + * Authors: + * Kyle Cranmer, + * Lorenzo Moneta, + * Gregory Schott, + * Wouter Verkerke, + * Sven Kreiss + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +/** \class RooStats::ModelConfig + \ingroup Roostats + +ModelConfig is a simple class that holds configuration information specifying how a model +should be used in the context of various RooStats tools. A single model can be used +in different ways, and this class should carry all that is needed to specify how it should be used. +ModelConfig requires a workspace to be set. + +A ModelConfig holds sets of parameters of the likelihood function that have different interpretations: +- **Parameter of interest** Parameters that are measured (*i.e.* fitted). +- **Nuisance parameters** Parameters that are fitted, but their post-fit value is not interesting. Often, +they might be constrained because external knowledge about them exists, *e.g.* from external measurements. +- **Constraint parameters** No direct use in RooFit/RooStats. Can be used by the user for bookkeeping. +- **Observables** Parameters that have been measured externally, *i.e.* they exist in a dataset. These are not fitted, +but read during fitting from the entries of a dataset. +- **Conditional observables** Observables that are not integrated when the normalisation of the PDF is calculated. +See *e.g.* `rf306_condpereventerrors` in the RooFit tutorials. +- **Global observables** Observables that to the fit look like "constant" values, *i.e.* they are not being +fitted and they are not loaded from a dataset, but some knowledge exists that allows to set them to a +specific value. Examples: +-- A signal efficiency measured in a Monte Carlo study. +-- When constraining a parameter \f$ b \f$, the target value (\f$ b_0 \f$) that this parameter is constrained to: +\f[ + \mathrm{Constraint}_b = \mathrm{Gauss}(b_0 \, | \, b, 0.2) +\f] +- **External constraints** Include given external constraints to likelihood by multiplying them with the original +likelihood. +*/ + +#include + +#include +#include +#include + +#include + +ClassImp(RooStats::ModelConfig); + +namespace { + +void removeConstantParameters(RooAbsCollection &coll) +{ + RooArgSet constSet; + for (auto const *myarg : static_range_cast(coll)) { + if (myarg->isConstant()) + constSet.add(*myarg); + } + coll.remove(constSet); +} + +} // namespace + +using namespace std; + +namespace RooStats { + +//////////////////////////////////////////////////////////////////////////////// +/// Makes sensible guesses of observables, parameters of interest +/// and nuisance parameters if one or multiple have been set by the creator of this ModelConfig. +/// +/// Defaults: +/// - Observables: determined from data, +/// - Global observables: explicit obs - obs from data - constant observables +/// - Parameters of interest: empty, +/// - Nuisance parameters: all parameters except parameters of interest +/// +/// We use nullptr to mean not set, so we don't want to fill +/// with empty RooArgSets. + +void ModelConfig::GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig) +{ + + // observables + if (!GetObservables()) { + SetObservables(*std::unique_ptr{GetPdf()->getObservables(data)}); + } + // global observables + if (!GetGlobalObservables()) { + RooArgSet co(*GetObservables()); + co.remove(*std::unique_ptr{GetPdf()->getObservables(data)}); + removeConstantParameters(co); + if (!co.empty()) + SetGlobalObservables(co); + + // TODO BUG This does not work as observables with the same name are already in the workspace. + /* + RooArgSet o(*GetObservables()); + o.remove(co); + SetObservables(o); + */ + } + + // parameters + // if (!GetParametersOfInterest()) { + // SetParametersOfInterest(RooArgSet()); + // } + if (!GetNuisanceParameters()) { + RooArgSet params; + GetPdf()->getParameters(data.get(), params); + RooArgSet p(params); + p.remove(*GetParametersOfInterest()); + removeConstantParameters(p); + if (!p.empty()) + SetNuisanceParameters(p); + } + + // print Modelconfig as an info message + + if (printModelConfig) { + std::ostream &oldstream = RooPrintable::defaultPrintStream(&ccoutI(InputArguments)); + Print(); + RooPrintable::defaultPrintStream(&oldstream); + } +} + +//////////////////////////////////////////////////////////////////////////////// +/// print contents of Model on the default print stream +/// It can be changed using RooPrintable + +void ModelConfig::Print(Option_t *) const +{ + ostream &os = RooPrintable::defaultPrintStream(); + + os << endl << "=== Using the following for " << GetName() << " ===" << endl; + + // args + if (GetObservables()) { + os << "Observables: "; + GetObservables()->Print(""); + } + if (GetParametersOfInterest()) { + os << "Parameters of Interest: "; + GetParametersOfInterest()->Print(""); + } + if (GetNuisanceParameters()) { + os << "Nuisance Parameters: "; + GetNuisanceParameters()->Print(""); + } + if (GetGlobalObservables()) { + os << "Global Observables: "; + GetGlobalObservables()->Print(""); + } + if (GetConstraintParameters()) { + os << "Constraint Parameters: "; + GetConstraintParameters()->Print(""); + } + if (GetConditionalObservables()) { + os << "Conditional Observables: "; + GetConditionalObservables()->Print(""); + } + if (GetProtoData()) { + os << "Proto Data: "; + GetProtoData()->Print(""); + } + + // pdfs + if (GetPdf()) { + os << "PDF: "; + GetPdf()->Print(""); + } + if (GetPriorPdf()) { + os << "Prior PDF: "; + GetPriorPdf()->Print(""); + } + + // snapshot + const RooArgSet *snapshot = GetSnapshot(); + if (snapshot) { + os << "Snapshot: " << endl; + snapshot->Print("v"); + delete snapshot; + } + + os << endl; +} + +//////////////////////////////////////////////////////////////////////////////// +/// If a workspace already exists in this ModelConfig, RooWorkspace::merge(ws) will be called +/// on the existing workspace. + +void ModelConfig::SetWS(RooWorkspace &ws) +{ + if (!fRefWS.GetObject()) { + fRefWS = &ws; + fWSName = ws.GetName(); + } else { + RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); + RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + GetWS()->merge(ws); + RooMsgService::instance().setGlobalKillBelow(level); + } +} + +//////////////////////////////////////////////////////////////////////////////// +/// get from TRef + +RooWorkspace *ModelConfig::GetWS() const +{ + RooWorkspace *ws = dynamic_cast(fRefWS.GetObject()); + if (!ws) { + coutE(ObjectHandling) << "workspace not set" << endl; + return nullptr; + } + return ws; +} + +//////////////////////////////////////////////////////////////////////////////// +/// save snapshot in the workspace +/// and use values passed with the set + +void ModelConfig::SetSnapshot(const RooArgSet &set) +{ + if (!GetWS()) + return; + + fSnapshotName = GetName(); + if (!fSnapshotName.empty()) + fSnapshotName += "_"; + fSnapshotName += set.GetName(); + if (!fSnapshotName.empty()) + fSnapshotName += "_"; + fSnapshotName += "snapshot"; + GetWS()->saveSnapshot(fSnapshotName, set, true); // import also the given parameter values + DefineSetInWS(fSnapshotName.c_str(), set); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Load the snapshot from ws and return the corresponding set with the snapshot values. +/// User must delete returned RooArgSet. + +const RooArgSet *ModelConfig::GetSnapshot() const +{ + if (!GetWS()) + return nullptr; + if (!fSnapshotName.length()) + return nullptr; + // calling loadSnapshot will also copy the current parameter values in the workspaces + // since we do not want to change the model parameters - we restore the previous ones + if (!GetWS()->set(fSnapshotName)) + return nullptr; + RooArgSet snapshotVars(*GetWS()->set(fSnapshotName)); + if (snapshotVars.empty()) + return nullptr; + // make my snapshot which will contain a copy of the snapshot variables + RooArgSet tempSnapshot; + snapshotVars.snapshot(tempSnapshot); + // load snapshot value from the workspace + if (!(GetWS()->loadSnapshot(fSnapshotName.c_str()))) + return nullptr; + // by doing this snapshotVars will have the snapshot values - make the snapshot to return + const RooArgSet *modelSnapshot = dynamic_cast(snapshotVars.snapshot()); + // restore now the variables of snapshot in ws to their original values + // need to const cast since assign is not const (but in reality in just assign values and does not change the set) + // and anyway the set is const + snapshotVars.assignFast(tempSnapshot); + return modelSnapshot; +} + +//////////////////////////////////////////////////////////////////////////////// +/// load the snapshot from ws if it exists + +void ModelConfig::LoadSnapshot() const +{ + if (!GetWS()) + return; + GetWS()->loadSnapshot(fSnapshotName.c_str()); +} + +//////////////////////////////////////////////////////////////////////////////// +/// helper functions to avoid code duplication + +void ModelConfig::DefineSetInWS(const char *name, const RooArgSet &set) +{ + if (!GetWS()) + return; + + const RooArgSet *prevSet = GetWS()->set(name); + if (prevSet) { + // be careful not to remove passed set in case it is the same updated + if (prevSet != &set) + GetWS()->removeSet(name); + } + + // suppress warning when we re-define a previously defined set (when set == prevSet ) + // and set is not removed in that case + RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); + RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + + GetWS()->defineSet(name, set, true); + + RooMsgService::instance().setGlobalKillBelow(level); +} + +//////////////////////////////////////////////////////////////////////////////// +/// internal function to import Pdf in WS + +void ModelConfig::ImportPdfInWS(const RooAbsPdf &pdf) +{ + if (!GetWS()) + return; + + if (!GetWS()->pdf(pdf.GetName())) { + RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); + RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + GetWS()->import(pdf, RooFit::RecycleConflictNodes()); + RooMsgService::instance().setGlobalKillBelow(level); + } +} + +//////////////////////////////////////////////////////////////////////////////// +/// internal function to import data in WS + +void ModelConfig::ImportDataInWS(RooAbsData &data) +{ + if (!GetWS()) + return; + + if (!GetWS()->data(data.GetName())) { + RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); + RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + GetWS()->import(data); + RooMsgService::instance().setGlobalKillBelow(level); + } +} + +//////////////////////////////////////////////////////////////////////////////// + +bool ModelConfig::SetHasOnlyParameters(const RooArgSet &set, const char *errorMsgPrefix) +{ + + RooArgSet nonparams; + for (auto const *arg : set) { + if (!arg->isFundamental()) { + nonparams.add(*arg); + } + } + + if (errorMsgPrefix && !nonparams.empty()) { + cout << errorMsgPrefix << " ERROR: specified set contains non-parameters: " << nonparams << endl; + } + return (nonparams.empty()); +} + +/// Specify the external constraints. +void ModelConfig::SetExternalConstraints(const RooArgSet &set) +{ + fExtConstraintsName = std::string(GetName()) + "_ExternalConstraints"; + DefineSetInWS(fExtConstraintsName.c_str(), set); +} + +/// Specify the conditional observables. +void ModelConfig::SetConditionalObservables(const RooArgSet &set) +{ + if (!SetHasOnlyParameters(set, "ModelConfig::SetConditionalObservables")) + return; + fConditionalObsName = std::string(GetName()) + "_ConditionalObservables"; + DefineSetInWS(fConditionalObsName.c_str(), set); +} + +/// Specify the global observables. +void ModelConfig::SetGlobalObservables(const RooArgSet &set) +{ + + if (!SetHasOnlyParameters(set, "ModelConfig::SetGlobalObservables")) + return; + + // make global observables constant + for (auto *arg : set) { + arg->setAttribute("Constant", true); + } + + fGlobalObsName = std::string(GetName()) + "_GlobalObservables"; + DefineSetInWS(fGlobalObsName.c_str(), set); +} + +namespace { + +std::unique_ptr +finalizeCmdList(ModelConfig const &modelConfig, RooLinkedList const &cmdList, std::vector &cmdArgs) +{ + auto addCmdArg = [&](RooCmdArg const &cmdArg) { + if (cmdList.FindObject(cmdArg.GetName())) { + std::stringstream ss; + ss << "Illegal command argument \"" << cmdArg.GetName() + << "\" passed to ModelConfig::createNLL(). This option is retrieved from the ModelConfig itself."; + const std::string errorMsg = ss.str(); + oocoutE(&modelConfig, InputArguments) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); + } + cmdArgs.push_back(cmdArg); + }; + + if (auto args = modelConfig.GetConditionalObservables()) { + addCmdArg(RooFit::ConditionalObservables(*args)); + } + + if (auto args = modelConfig.GetGlobalObservables()) { + addCmdArg(RooFit::GlobalObservables(*args)); + } + + if (auto args = modelConfig.GetExternalConstraints()) { + addCmdArg(RooFit::ExternalConstraints(*args)); + } + + auto finalCmdList = std::make_unique(cmdList); + for (RooCmdArg &arg : cmdArgs) { + finalCmdList->Add(&arg); + } + + return finalCmdList; +} + +} // namespace + +/** @fn RooStats::ModelConfig::createNLL() + * + * Wrapper around RooAbsPdf::createNLL(), where + * the pdf and some configuration options are retrieved from the ModelConfig. + * + * The options taken from the ModelConfig are: + * + * * ConditionalObservables() + * * GlobalObservables() + * * ExternalConstraints() + * + * Except for the options above, you can still pass all the other command + * arguments supported by RooAbsPdf::createNLL(). + */ + +std::unique_ptr ModelConfig::createNLLImpl(RooAbsData &data, const RooLinkedList &cmdList) const +{ + std::vector cmdArgs; + auto finalCmdList = finalizeCmdList(*this, cmdList, cmdArgs); + return std::unique_ptr{GetPdf()->createNLL(data, *finalCmdList)}; +} + +/** @fn RooStats::ModelConfig::fitTo() + * + * Wrapper around RooAbsPdf::fitTo(), where + * the pdf and some configuration options are retrieved from the ModelConfig. + * + * See ModelConfig::createNLL() for more information. + */ +std::unique_ptr ModelConfig::fitToImpl(RooAbsData &data, const RooLinkedList &cmdList) +{ + std::vector cmdArgs; + auto finalCmdList = finalizeCmdList(*this, cmdList, cmdArgs); + return std::unique_ptr{GetPdf()->fitTo(data, *finalCmdList)}; +} + +} // end namespace RooStats diff --git a/roofit/roofitcore/src/NormalizationHelpers.cxx b/roofit/roofitcore/src/NormalizationHelpers.cxx index 922f8a8aacdd6..014ba67e4fb36 100644 --- a/roofit/roofitcore/src/NormalizationHelpers.cxx +++ b/roofit/roofitcore/src/NormalizationHelpers.cxx @@ -1,373 +1,82 @@ /* * Project: RooFit * Authors: - * Jonas Rembser, CERN 2022 + * Jonas Rembser, CERN 2023 * - * Copyright (c) 2022, CERN + * Copyright (c) 2023, CERN * * Redistribution and use in source and binary forms, * with or without modification, are permitted according to the terms * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ -#include "NormalizationHelpers.h" +#include -#include -#include -#include -#include +#include +#include +#include -#include "RooNormalizedPdf.h" +#include -#include "RooBatchCompute.h" +RooFit::Detail::CompileContext::CompileContext(RooArgSet const &topLevelNormSet) : _topLevelNormSet{topLevelNormSet} {} -/// A RooProdPdf with a fixed normalization set can be replaced by this class. -/// Its purpose is to provide the right client-server interface for the -/// evaluation of RooProdPdf cache elements that were created for a given -/// normalization set. -class RooFixedProdPdf : public RooAbsPdf { -public: - RooFixedProdPdf(RooProdPdf const &prodPdf, RooArgSet const &normSet) - : RooAbsPdf(prodPdf.GetName(), prodPdf.GetTitle()), _cache(prodPdf.createCacheElem(&normSet, nullptr)), - _servers("!servers", "List of servers", this), _prodPdf{prodPdf} - { - auto &cache = *_cache; +RooFit::Detail::CompileContext::~CompileContext() {} - // The actual servers for a given normalization set depend on whether the - // cache is rearranged or not. See RooProdPdf::calculateBatch to see - // which args in the cache are used directly. - if (cache._isRearranged) { - _servers.add(*cache._rearrangedNum); - _servers.add(*cache._rearrangedDen); - } else { - for (std::size_t i = 0; i < cache._partList.size(); ++i) { - _servers.add(cache._partList[i]); - } - } - } - RooFixedProdPdf(const RooFixedProdPdf &other, const char *name = nullptr) - : RooAbsPdf(other, name), _servers("!servers", this, other._servers), _prodPdf{other._prodPdf} - { - } - TObject *clone(const char *newname) const override { return new RooFixedProdPdf(*this, newname); } - - bool selfNormalized() const override { return true; } - - inline bool canComputeBatchWithCuda() const override { return true; } - - void computeBatch(cudaStream_t *stream, double *output, size_t nEvents, - RooFit::Detail::DataMap const &dataMap) const override - { - _prodPdf.calculateBatch(*_cache, stream, output, nEvents, dataMap); - } - - ExtendMode extendMode() const override { return _prodPdf.extendMode(); } - double expectedEvents(const RooArgSet *nset) const override { return _prodPdf.expectedEvents(nset); } - - // Analytical Integration handling - bool forceAnalyticalInt(const RooAbsArg &dep) const override { return _prodPdf.forceAnalyticalInt(dep); } - Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, - const char *rangeName = nullptr) const override - { - return _prodPdf.getAnalyticalIntegralWN(allVars, analVars, normSet, rangeName); - } - Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &numVars, const char *rangeName = nullptr) const override - { - return _prodPdf.getAnalyticalIntegral(allVars, numVars, rangeName); - } - double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName) const override - { - return _prodPdf.analyticalIntegralWN(code, normSet, rangeName); - } - double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override - { - return _prodPdf.analyticalIntegral(code, rangeName); - } - -private: - double evaluate() const override { return _prodPdf.calculate(*_cache); } - - std::unique_ptr _cache; - RooSetProxy _servers; - RooProdPdf const &_prodPdf; -}; - -namespace { - -using RooFit::Detail::DataKey; -using ServerLists = std::map>; - -class GraphChecker { -public: - GraphChecker(RooAbsArg const &topNode) - { - // Get the list of servers for each node by data key. - { - RooArgList nodes; - topNode.treeNodeServerList(&nodes, nullptr, true, true, false, true); - RooArgSet nodesSet{nodes}; - for (RooAbsArg *node : nodesSet) { - _serverLists[node]; - for (RooAbsArg *server : node->servers()) { - _serverLists[node].push_back(server); - } - } - } - for (auto &item : _serverLists) { - auto &l = item.second; - std::sort(l.begin(), l.end()); - l.erase(std::unique(l.begin(), l.end()), l.end()); - } - } - - bool dependsOn(DataKey arg, DataKey testArg) - { - - std::pair p{arg, testArg}; - - auto found = _results.find(p); - if (found != _results.end()) - return found->second; - - if (arg == testArg) - return true; - - auto const &serverList = _serverLists.at(arg); - - // Next test direct dependence - auto foundServer = std::find(serverList.begin(), serverList.end(), testArg); - if (foundServer != serverList.end()) { - _results.emplace(p, true); - return true; - } - - // If not, recurse - for (auto const &server : serverList) { - bool t = dependsOn(server, testArg); - _results.emplace(std::pair{server, testArg}, t); - if (t) { - return true; - } - } - - _results.emplace(p, false); - return false; - } - -private: - ServerLists _serverLists; - std::map, bool> _results; -}; - -void treeNodeServerListAndNormSets(const RooAbsArg &arg, RooAbsCollection &list, RooArgSet const &normSet, - std::unordered_map &normSets, GraphChecker const &checker) +void RooFit::Detail::CompileContext::add(RooAbsArg &arg) { - if (normSets.find(&arg) != normSets.end()) - return; - - list.add(arg, true); - - // normalization sets only need to be added for pdfs - if (dynamic_cast(&arg)) { - normSets.insert({&arg, new RooArgSet{normSet}}); - } - - // Recurse if current node is derived - if (arg.isDerived() && !arg.isFundamental()) { - for (const auto server : arg.servers()) { - - if (!server->isValueServer(arg)) { - continue; - } - - auto differentSet = arg.fillNormSetForServer(normSet, *server); - if (differentSet) { - differentSet->sort(); - } - - auto &serverNormSet = differentSet ? *differentSet : normSet; - - // Make sure that the server is not already part of the computation - // graph with a different normalization set. - auto found = normSets.find(server); - if (found != normSets.end()) { - if (found->second->size() != serverNormSet.size() || !serverNormSet.hasSameLayout(*found->second)) { - std::stringstream ss; - ss << server->ClassName() << "::" << server->GetName() - << " is requested to be evaluated with two different normalization sets in the same model!"; - ss << " This is not supported yet. The conflicting norm sets are:\n RooArgSet"; - serverNormSet.printValue(ss); - ss << " requested by " << arg.ClassName() << "::" << arg.GetName() << "\n RooArgSet"; - found->second->printValue(ss); - ss << " first requested by other client"; - auto errMsg = ss.str(); - oocoutE(server, Minimization) << errMsg << std::endl; - throw std::runtime_error(errMsg); - } - continue; - } - - treeNodeServerListAndNormSets(*server, list, serverNormSet, normSets, checker); - } - } + _clonedArgsSet.emplace(arg.namePtr(), &arg); } -std::vector> unfoldIntegrals(RooAbsArg const &topNode, RooArgSet const &normSet, - std::unordered_map &normSets, - RooArgSet &replacedArgs, RooArgSet &newArgs) +RooAbsArg *RooFit::Detail::CompileContext::find(RooAbsArg &arg) const { - std::vector> newNodes; - - // No normalization set: we don't need to create any integrals - if (normSet.empty()) - return newNodes; - - GraphChecker checker{topNode}; - - RooArgSet nodes; - // The norm sets are sorted to compare them for equality more easliy - RooArgSet normSetSorted{normSet}; - normSetSorted.sort(); - treeNodeServerListAndNormSets(topNode, nodes, normSetSorted, normSets, checker); - - // Clean normsets of the variables that the arg does not depend on - for (auto &item : normSets) { - if (!item.second || item.second->empty()) - continue; - auto actualNormSet = new RooArgSet{}; - for (auto *narg : *item.second) { - if (checker.dependsOn(item.first, narg)) - // Add the arg from the actual node list in the computation graph. - // Like this, we don't accidentally add internal variable clones - // that the client args returned. Looking this up is fast because - // of the name pointer hash map optimization. - actualNormSet->add(*nodes.find(*narg)); - } - delete item.second; - item.second = actualNormSet; - } - - // Function to `oldArg` with `newArg` in the computation graph. - auto replaceArg = [&](RooAbsArg &newArg, RooAbsArg const &oldArg) { - const std::string attrib = std::string("ORIGNAME:") + oldArg.GetName(); - - newArg.setAttribute(attrib.c_str()); - - RooArgList newServerList{newArg}; - - RooArgList originalClients; - for (auto *client : oldArg.clients()) { - if (nodes.containsInstance(*client)) { - originalClients.add(*client); - } - } - for (auto *client : originalClients) { - if (dynamic_cast(client)) - continue; - client->redirectServers(newServerList, false, true); - } - - replacedArgs.add(oldArg); - newArgs.add(newArg); - - newArg.setAttribute(attrib.c_str(), false); - }; - - // Replace all pdfs that need to be normalized with a pdf wrapper that - // applies the right normalization. - for (RooAbsArg *node : nodes) { - if (auto pdf = dynamic_cast(node)) { - RooArgSet const &currNormSet = *normSets.at(pdf); - - if (currNormSet.empty()) - continue; - - // The call to getVal() sets up cached states for this normalization - // set, which is important in case this pdf is also used by clients - // using the getVal() interface (without this, test 28 in stressRooFit - // is failing for example). - pdf->getVal(currNormSet); - - if (pdf->selfNormalized() && !dynamic_cast(pdf)) - continue; - - auto normalizedPdf = std::make_unique(*pdf, currNormSet); - - replaceArg(*normalizedPdf, *pdf); - - newNodes.emplace_back(std::move(normalizedPdf)); - } + auto existingServerClone = _clonedArgsSet.find(arg.namePtr()); + if (existingServerClone != _clonedArgsSet.end()) { + return existingServerClone->second; } + return nullptr; +} - for (RooAbsArg *node : nodes) { - - if (auto prodPdf = dynamic_cast(node)) { - RooArgSet const &currNormSet = *normSets.at(prodPdf); - auto normalizedPdf = std::make_unique(*prodPdf, currNormSet); - - replaceArg(*normalizedPdf, *prodPdf); - - newNodes.emplace_back(std::move(normalizedPdf)); - - continue; - } +void RooFit::Detail::CompileContext::compileServers(RooAbsArg &arg, RooArgSet const &normSet) +{ + for (RooAbsArg *server : arg.servers()) { + this->compile(*server, arg, normSet); } - - return newNodes; + arg.redirectServers(_replacements); } -void foldIntegrals(RooAbsArg &topNode, RooArgSet &replacedArgs, RooArgSet &newArgs) +void RooFit::Detail::CompileContext::compileServer(RooAbsArg &server, RooAbsArg &arg, RooArgSet const &normSet) { - assert(replacedArgs.size() == newArgs.size()); + this->compile(server, arg, normSet); + arg.redirectServers(_replacements); +} - for (std::size_t i = 0; i < replacedArgs.size(); ++i) { - replacedArgs[i]->setAttribute((std::string("ORIGNAME:") + newArgs[i]->GetName()).c_str()); +RooAbsArg *RooFit::Detail::CompileContext::compileImpl(RooAbsArg &arg, RooAbsArg &owner, RooArgSet const &normSet) +{ + if (auto existingServerClone = this->find(arg)) { + return existingServerClone; } - - topNode.recursiveRedirectServers(replacedArgs, false, true); - - for (std::size_t i = 0; i < replacedArgs.size(); ++i) { - replacedArgs[i]->setAttribute((std::string("ORIGNAME:") + newArgs[i]->GetName()).c_str(), false); + if (arg.isFundamental() && !_topLevelNormSet.find(arg)) { + return nullptr; + } + if (isMarkedAsCompiled(arg)) { + return nullptr; } -} - -} // namespace -/// \class NormalizationIntegralUnfolder -/// \ingroup Roofitcore -/// -/// A NormalizationIntegralUnfolder takes the top node of a computation graph -/// and a normalization set for its constructor. The normalization integrals -/// for the PDFs in that graph will be created, and placed into the computation -/// graph itself, rewiring the existing RooAbsArgs. When the unfolder goes out -/// of scope, all changes to the computation graph will be reverted. -/// -/// Note that for evaluation, the original topNode should not be used anymore, -/// because if it is a pdf there is now a new normalized pdf wrapping it, -/// serving as the new top node. This normalized top node can be retreived by -/// NormalizationIntegralUnfolder::arg(). + std::unique_ptr newArg = arg.compileForNormSet(normSet, *this); + markAsCompiled(*newArg); + _replacements[&arg] = newArg.get(); + this->add(*newArg); + RooAbsArg *out = newArg.get(); + owner.addOwnedComponents(std::move(newArg)); + return out; +} -RooFit::NormalizationIntegralUnfolder::NormalizationIntegralUnfolder(RooAbsArg const &topNode, RooArgSet const &normSet) - : _topNodeWrapper{std::make_unique("_dummy", "_dummy", RooArgList{topNode})}, _normSetWasEmpty{ - normSet.empty()} +void RooFit::Detail::CompileContext::markAsCompiled(RooAbsArg &arg) const { - auto ownedArgs = unfoldIntegrals(*_topNodeWrapper, normSet, _normSets, _replacedArgs, _newArgs); - for (std::unique_ptr &arg : ownedArgs) { - _topNodeWrapper->addOwnedComponents(std::move(arg)); - } - _arg = &static_cast(*_topNodeWrapper).list()[0]; + arg.setAttribute("_COMPILED"); } -RooFit::NormalizationIntegralUnfolder::~NormalizationIntegralUnfolder() +bool RooFit::Detail::CompileContext::isMarkedAsCompiled(RooAbsArg const &arg) const { - // If there was no normalization set to compile the computation graph for, - // we also don't need to fold the integrals back in. - if (_normSetWasEmpty) - return; - - foldIntegrals(*_topNodeWrapper, _replacedArgs, _newArgs); - - for (auto &item : _normSets) { - delete item.second; - } + return arg.getAttribute("_COMPILED"); } diff --git a/roofit/roofitcore/src/NormalizationHelpers.h b/roofit/roofitcore/src/NormalizationHelpers.h deleted file mode 100644 index c01beca8c3206..0000000000000 --- a/roofit/roofitcore/src/NormalizationHelpers.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Project: RooFit - * Authors: - * Jonas Rembser, CERN 2022 - * - * Copyright (c) 2022, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#ifndef RooFit_NormalizationHelpers_h -#define RooFit_NormalizationHelpers_h - -#include -#include - -#include -#include -#include - -class RooAbsArg; - -namespace RooFit { - -class NormalizationIntegralUnfolder { -public: - NormalizationIntegralUnfolder(RooAbsArg const &topNode, RooArgSet const &normSet); - ~NormalizationIntegralUnfolder(); - - inline RooAbsArg &arg() const { return *_arg; } - -private: - std::unique_ptr _topNodeWrapper; - RooAbsArg *_arg = nullptr; - std::unordered_map _normSets; - RooArgSet _replacedArgs; - RooArgSet _newArgs; - bool _normSetWasEmpty; -}; - -} // namespace RooFit - -#endif diff --git a/roofit/roofitcore/src/Roo1DTable.cxx b/roofit/roofitcore/src/Roo1DTable.cxx index c35170c3a4b4a..1bf11addeef6e 100644 --- a/roofit/roofitcore/src/Roo1DTable.cxx +++ b/roofit/roofitcore/src/Roo1DTable.cxx @@ -263,14 +263,14 @@ double Roo1DTable::get(const char* label, bool silent) const double Roo1DTable::get(const int index, bool silent) const { - const RooCatType* cat = 0; + const RooCatType* cat = nullptr; int i = 0; for (; i < _types.GetEntries(); ++i) { cat = static_cast(_types[i]); if (cat->getVal() == index) { break; } else { - cat = 0; + cat = nullptr; } } if (!cat) { diff --git a/roofit/roofitcore/src/RooAICRegistry.cxx b/roofit/roofitcore/src/RooAICRegistry.cxx index 6a48270341d18..e6f95aaed741c 100644 --- a/roofit/roofitcore/src/RooAICRegistry.cxx +++ b/roofit/roofitcore/src/RooAICRegistry.cxx @@ -34,7 +34,19 @@ associated normalization and integration sets. using namespace std; ClassImp(RooAICRegistry); -; + +namespace { + +RooArgSet * makeSnapshot(RooArgSet const* set) { + if(!set) { + return nullptr; + } + auto out = new RooArgSet; + set->snapshot(*out, false); + return out; +} + +} //////////////////////////////////////////////////////////////////////////////// @@ -52,21 +64,21 @@ RooAICRegistry::RooAICRegistry(UInt_t size) /// Copy constructor RooAICRegistry::RooAICRegistry(const RooAICRegistry& other) - : _clArr(other._clArr), _asArr1(other._clArr.size(), 0), _asArr2(other._clArr.size(), 0), - _asArr3(other._clArr.size(), 0), _asArr4(other._clArr.size(), 0) + : _clArr(other._clArr), _asArr1(other._clArr.size(), nullptr), _asArr2(other._clArr.size(), nullptr), + _asArr3(other._clArr.size(), nullptr), _asArr4(other._clArr.size(), nullptr) { // Copy code-list array if other PDF has one UInt_t size = other._clArr.size(); if (size) { - _asArr1.resize(size, 0); - _asArr2.resize(size, 0); - _asArr3.resize(size, 0); - _asArr4.resize(size, 0); + _asArr1.resize(size, nullptr); + _asArr2.resize(size, nullptr); + _asArr3.resize(size, nullptr); + _asArr4.resize(size, nullptr); for(UInt_t i = 0; i < size; ++i) { - _asArr1[i] = other._asArr1[i] ? ((RooArgSet*)other._asArr1[i]->snapshot(false)) : 0; - _asArr2[i] = other._asArr2[i] ? ((RooArgSet*)other._asArr2[i]->snapshot(false)) : 0; - _asArr3[i] = other._asArr3[i] ? ((RooArgSet*)other._asArr3[i]->snapshot(false)) : 0; - _asArr4[i] = other._asArr4[i] ? ((RooArgSet*)other._asArr4[i]->snapshot(false)) : 0; + _asArr1[i] = makeSnapshot(other._asArr1[i]); + _asArr2[i] = makeSnapshot(other._asArr2[i]); + _asArr3[i] = makeSnapshot(other._asArr3[i]); + _asArr4[i] = makeSnapshot(other._asArr4[i]); } } } @@ -133,10 +145,10 @@ Int_t RooAICRegistry::store(const std::vector& codeList, RooArgSet* set1, // Store code list and return index _clArr.push_back(codeList); - _asArr1.push_back(set1 ? (RooArgSet*)set1->snapshot(false) : 0); - _asArr2.push_back(set2 ? (RooArgSet*)set2->snapshot(false) : 0); - _asArr3.push_back(set3 ? (RooArgSet*)set3->snapshot(false) : 0); - _asArr4.push_back(set4 ? (RooArgSet*)set4->snapshot(false) : 0); + _asArr1.emplace_back(makeSnapshot(set1)); + _asArr2.emplace_back(makeSnapshot(set2)); + _asArr3.emplace_back(makeSnapshot(set3)); + _asArr4.emplace_back(makeSnapshot(set4)); if (set1) delete set1 ; if (set2) delete set2 ; diff --git a/roofit/roofitcore/src/RooAbsAnaConvPdf.cxx b/roofit/roofitcore/src/RooAbsAnaConvPdf.cxx index fd2fa5c756368..9a8a96d37abb3 100644 --- a/roofit/roofitcore/src/RooAbsAnaConvPdf.cxx +++ b/roofit/roofitcore/src/RooAbsAnaConvPdf.cxx @@ -62,6 +62,7 @@ #include "RooAbsAnaConvPdf.h" +#include "RooNormalizedPdf.h" #include "RooMsgService.h" #include "Riostream.h" #include "RooResolutionModel.h" @@ -182,14 +183,14 @@ Int_t RooAbsAnaConvPdf::declareBasis(const char* expression, const RooArgList& p basisName.Append(arg->GetName()) ; } - RooFormulaVar* basisFunc = new RooFormulaVar(basisName, expression, basisArgs); + auto basisFunc = std::make_unique(basisName, expression, basisArgs); basisFunc->setAttribute("RooWorkspace::Recycle") ; basisFunc->setAttribute("NOCacheAndTrack") ; basisFunc->setOperMode(operMode()) ; - _basisList.addOwned(*basisFunc) ; // Instantiate resModel x basisFunc convolution - RooAbsReal* conv = ((RooResolutionModel*)_model.absArg())->convolution(basisFunc,this) ; + RooAbsReal* conv = static_cast(_model.absArg())->convolution(basisFunc.get(),this); + _basisList.addOwned(std::move(basisFunc)); if (!conv) { coutE(InputArguments) << "RooAbsAnaConvPdf::declareBasis(" << GetName() << "): unable to construct convolution with basis function '" << expression << "'" << endl ; @@ -213,8 +214,8 @@ bool RooAbsAnaConvPdf::changeModel(const RooResolutionModel& newModel) auto conv = static_cast(convArg); // Build new resolution model - RooResolutionModel* newConv = newModel.convolution((RooFormulaVar*)&conv->basis(),this) ; - if (!newConvSet.add(*newConv)) { + std::unique_ptr newConv{newModel.convolution(const_cast(&conv->basis()),this)}; + if (!newConvSet.addOwned(std::move(newConv))) { allOK = false ; break ; } @@ -222,20 +223,22 @@ bool RooAbsAnaConvPdf::changeModel(const RooResolutionModel& newModel) // Check if all convolutions were successfully built if (!allOK) { - // Delete new basis functions created sofar - std::for_each(newConvSet.begin(), newConvSet.end(), [](RooAbsArg* arg){delete arg;}); - return true ; } // Replace old convolutions with new set _convSet.removeAll() ; - _convSet.addOwned(newConvSet) ; + _convSet.addOwned(std::move(newConvSet)); + + const std::string attrib = std::string("ORIGNAME:") + _model->GetName(); + const bool oldAttrib = newModel.getAttribute(attrib.c_str()); + const_cast(newModel).setAttribute(attrib.c_str()); + + redirectServers(RooArgSet{newModel}, false, true); - // Update server link by hand, since _model.setArg() below will not do this - replaceServer((RooAbsArg&)_model.arg(),(RooAbsArg&)newModel,false,false) ; + // reset temporary attribute for server redirection + const_cast(newModel).setAttribute(attrib.c_str(), oldAttrib); - _model.setArg((RooResolutionModel&)newModel) ; return false ; } @@ -256,10 +259,9 @@ RooAbsGenContext* RooAbsAnaConvPdf::genContext(const RooArgSet &vars, const RooD RooResolutionModel* conv = dynamic_cast(_model.absArg()); assert(conv); - RooArgSet* modelDep = _model.absArg()->getObservables(&vars) ; + std::unique_ptr modelDep {_model->getObservables(&vars)}; modelDep->remove(*convVar(),true,true) ; Int_t numAddDep = modelDep->getSize() ; - delete modelDep ; // Check if physics PDF and resolution model can both directly generate the convolution variable RooArgSet dummy ; @@ -311,8 +313,8 @@ bool RooAbsAnaConvPdf::isDirectGenSafe(const RooAbsArg& arg) const RooAbsRealLValue* RooAbsAnaConvPdf::convVar() { - RooResolutionModel* conv = (RooResolutionModel*) _convSet.at(0) ; - if (!conv) return 0 ; + auto* conv = static_cast(_convSet.at(0)); + if (!conv) return nullptr; return &conv->convVar() ; } @@ -333,13 +335,12 @@ double RooAbsAnaConvPdf::evaluate() const auto conv = static_cast(convArg); double coef = coefficient(index++) ; if (coef!=0.) { - double c = conv->getVal(0) ; - double r = coef ; + const double c = conv->getVal(nullptr); cxcoutD(Eval) << "RooAbsAnaConvPdf::evaluate(" << GetName() << ") val += coef*conv [" << index-1 << "/" - << _convSet.getSize() << "] coef = " << r << " conv = " << c << endl ; - result += conv->getVal(0)*coef ; + << _convSet.size() << "] coef = " << coef << " conv = " << c << endl ; + result += c * coef; } else { - cxcoutD(Eval) << "RooAbsAnaConvPdf::evaluate(" << GetName() << ") [" << index-1 << "/" << _convSet.getSize() << "] coef = 0" << endl ; + cxcoutD(Eval) << "RooAbsAnaConvPdf::evaluate(" << GetName() << ") [" << index-1 << "/" << _convSet.size() << "] coef = 0" << endl ; } } @@ -480,17 +481,17 @@ double RooAbsAnaConvPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normS Int_t index(0) ; double answer(0) ; - if (normCoefSet==0&&normConvSet==0) { + if (normCoefSet==nullptr&&normConvSet==nullptr) { // Integral over unnormalized function double integral(0) ; const TNamed *_rangeName = RooNameReg::ptr(rangeName); for (auto convArg : _convSet) { - auto conv = static_cast(convArg); + auto conv = static_cast(convArg); double coef = getCoefNorm(index++,intCoefSet,_rangeName) ; //cout << "coefInt[" << index << "] = " << coef << " " ; intCoefSet->Print("1") ; if (coef!=0) { - integral += coef* conv->getNormObj(0,intConvSet,_rangeName)->getVal(); + integral += coef* conv->getNormObj(nullptr,intConvSet,_rangeName)->getVal(); cxcoutD(Eval) << "RooAbsAnaConv::aiWN(" << GetName() << ") [" << index-1 << "] integral += " << conv->getNorm(intConvSet) << endl ; } @@ -504,19 +505,19 @@ double RooAbsAnaConvPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normS double norm(0) ; const TNamed *_rangeName = RooNameReg::ptr(rangeName); for (auto convArg : _convSet) { - auto conv = static_cast(convArg); + auto conv = static_cast(convArg); double coefInt = getCoefNorm(index,intCoefSet,_rangeName) ; //cout << "coefInt[" << index << "] = " << coefInt << "*" << term << " " << (intCoefSet?*intCoefSet:RooArgSet()) << endl ; if (coefInt!=0) { - double term = conv->getNormObj(0,intConvSet,_rangeName)->getVal(); + double term = conv->getNormObj(nullptr,intConvSet,_rangeName)->getVal(); integral += coefInt*term ; } double coefNorm = getCoefNorm(index,normCoefSet) ; //cout << "coefNorm[" << index << "] = " << coefNorm << "*" << term << " " << (normCoefSet?*normCoefSet:RooArgSet()) << endl ; if (coefNorm!=0) { - double term = conv->getNormObj(0,normConvSet)->getVal(); + double term = conv->getNormObj(nullptr,normConvSet)->getVal(); norm += coefNorm*term ; } @@ -581,9 +582,9 @@ bool RooAbsAnaConvPdf::forceAnalyticalInt(const RooAbsArg& /*dep*/) const double RooAbsAnaConvPdf::getCoefNorm(Int_t coefIdx, const RooArgSet* nset, const TNamed* rangeName) const { - if (nset==0) return coefficient(coefIdx) ; + if (nset==nullptr) return coefficient(coefIdx) ; - CacheElem* cache = (CacheElem*) _coefNormMgr.getObj(nset,0,0,rangeName) ; + CacheElem* cache = (CacheElem*) _coefNormMgr.getObj(nset,nullptr,nullptr,rangeName) ; if (!cache) { cache = new CacheElem ; @@ -593,11 +594,10 @@ double RooAbsAnaConvPdf::getCoefNorm(Int_t coefIdx, const RooArgSet* nset, const makeCoefVarList(cache->_coefVarList) ; for (i=0 ; i_coefVarList.getSize() ; i++) { - RooAbsReal* coefInt = static_cast(*cache->_coefVarList.at(i)).createIntegral(*nset,RooNameReg::str(rangeName)) ; - cache->_normList.addOwned(*coefInt) ; + cache->_normList.addOwned(std::unique_ptr{static_cast(*cache->_coefVarList.at(i)).createIntegral(*nset,RooNameReg::str(rangeName))}); } - _coefNormMgr.setObj(nset,0,cache,rangeName) ; + _coefNormMgr.setObj(nset,nullptr,cache,rangeName) ; } return ((RooAbsReal*)cache->_normList.at(coefIdx))->getVal() ; @@ -610,12 +610,10 @@ double RooAbsAnaConvPdf::getCoefNorm(Int_t coefIdx, const RooArgSet* nset, const void RooAbsAnaConvPdf::makeCoefVarList(RooArgList& varList) const { - // Instantate a coefficient variables + // Instantiate a coefficient variables for (Int_t i=0 ; i<_convSet.getSize() ; i++) { - RooArgSet* cvars = coefVars(i) ; - RooAbsReal* coefVar = new RooConvCoefVar(Form("%s_coefVar_%d",GetName(),i),"coefVar",*this,i,cvars) ; - varList.addOwned(*coefVar) ; - delete cvars ; + auto cvars = coefVars(i); + varList.addOwned(std::make_unique(Form("%s_coefVar_%d",GetName(),i),"coefVar",*this,i,&*cvars)); } } @@ -624,9 +622,9 @@ void RooAbsAnaConvPdf::makeCoefVarList(RooArgList& varList) const //////////////////////////////////////////////////////////////////////////////// /// Return set of parameters with are used exclusively by the coefficient functions -RooArgSet* RooAbsAnaConvPdf::coefVars(Int_t /*coefIdx*/) const +RooFit::OwningPtr RooAbsAnaConvPdf::coefVars(Int_t /*coefIdx*/) const { - RooArgSet* cVars = getParameters((RooArgSet*)0) ; + auto cVars = getParameters(static_cast(nullptr)); std::vector tmp; for (auto arg : *cVars) { for (auto convSetArg : _convSet) { @@ -638,7 +636,7 @@ RooArgSet* RooAbsAnaConvPdf::coefVars(Int_t /*coefIdx*/) const cVars->remove(tmp.begin(), tmp.end(), true, true); - return cVars ; + return RooFit::OwningPtr{std::move(cVars)}; } @@ -655,7 +653,7 @@ void RooAbsAnaConvPdf::printMultiline(ostream& os, Int_t contents, bool verbose, RooAbsPdf::printMultiline(os,contents,verbose,indent); os << indent << "--- RooAbsAnaConvPdf ---" << endl; - for (auto * conv : static_range_cast(_convSet)) { + for (RooAbsArg * conv : _convSet) { conv->printMultiline(os,contents,verbose,indent) ; } } @@ -671,4 +669,68 @@ void RooAbsAnaConvPdf::setCacheAndTrackHints(RooArgSet& trackNodes) //cout << "tracking node RooAddPdf component " << carg->ClassName() << "::" << carg->GetName() << endl ; } } -} \ No newline at end of file +} + +std::unique_ptr +RooAbsAnaConvPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + // If there is only one component in the linear sum of convolutions, we can + // just return that one, normalized. + if(_convSet.size() == 1) { + if (normSet.empty()) { + return _convSet[0].compileForNormSet(normSet, ctx); + } + std::unique_ptr pdfClone(static_cast(_convSet[0].Clone())); + ctx.compileServers(*pdfClone, normSet); + + auto newArg = std::make_unique(*pdfClone, normSet); + + // The direct servers are this pdf and the normalization integral, which + // don't need to be compiled further. + for (RooAbsArg *server : newArg->servers()) { + server->setAttribute("_COMPILED"); + } + newArg->setAttribute("_COMPILED"); + newArg->addOwnedComponents(std::move(pdfClone)); + return newArg; + } + + // Here, we can't use directly the function from the RooAbsPdf base class, + // because the convolution argument servers need to be evaluated + // unnormalized, even if they are pdfs. + + if (normSet.empty()) { + return RooAbsPdf::compileForNormSet(normSet, ctx); + } + std::unique_ptr pdfClone(static_cast(this->Clone())); + + // The actual resolution model is not serving the RooAbsAnaConvPdf + // in the evaluation. It was only used get the convolutions with a given + // basis. We can remove it for the compiled model. + pdfClone->removeServer(const_cast(pdfClone->_model.arg()), true); + + // The other servers will be compiled with the original normSet, but the + // _convSet has to be evaluated unnormalized. + RooArgList convArgClones; + for (RooAbsArg *convArg : _convSet) { + if (auto convArgClone = ctx.compile(*convArg, *pdfClone, {})) { + convArgClones.add(*convArgClone); + } + } + pdfClone->redirectServers(convArgClones, false, true); + + // Compile remaining servers that are evaluated normalized + ctx.compileServers(*pdfClone, normSet); + + // Finally, this RooAbsAnaConvPdf needs to be normalized + auto newArg = std::make_unique(*pdfClone, normSet); + + // The direct servers are this pdf and the normalization integral, which + // don't need to be compiled further. + for (RooAbsArg *server : newArg->servers()) { + server->setAttribute("_COMPILED"); + } + newArg->setAttribute("_COMPILED"); + newArg->addOwnedComponents(std::move(pdfClone)); + return newArg; +} diff --git a/roofit/roofitcore/src/RooAbsArg.cxx b/roofit/roofitcore/src/RooAbsArg.cxx index 1228b961e3ccc..ffaac26a7cb6f 100644 --- a/roofit/roofitcore/src/RooAbsArg.cxx +++ b/roofit/roofitcore/src/RooAbsArg.cxx @@ -27,7 +27,7 @@ a computation graph models an expression tree that can be evaluated. Therefore, RooAbsArg provides functionality to connect objects of type RooAbsArg into a computation graph to pass values between those objects. A value can e.g. be a real-valued number, (instances of RooAbsReal), or an integer, that is, -catgory index (instances of RooAbsCategory). The third subclass of RooAbsArg is RooStringVar, +category index (instances of RooAbsCategory). The third subclass of RooAbsArg is RooStringVar, but it is rarely used. The "shapes" that a RooAbsArg can possess can e.g. be the definition @@ -66,43 +66,38 @@ for single nodes. */ -#include "TBuffer.h" -#include "TClass.h" -#include "TVirtualStreamerInfo.h" -#include "strlcpy.h" - -#include "RooSecondMoment.h" -#include "RooWorkspace.h" - -#include "RooMsgService.h" -#include "RooAbsArg.h" -#include "RooArgSet.h" -#include "RooArgProxy.h" -#include "RooSetProxy.h" -#include "RooListProxy.h" -#include "RooAbsData.h" -#include "RooAbsCategoryLValue.h" -#include "RooTrace.h" -#include "RooRealIntegral.h" -#include "RooConstVar.h" -#include "RooExpensiveObjectCache.h" -#include "RooAbsDataStore.h" -#include "RooResolutionModel.h" -#include "RooVectorDataStore.h" -#include "RooTreeDataStore.h" -#include "RooHelpers.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include #include #include #include -#include -#include #include using namespace std; ClassImp(RooAbsArg); -; bool RooAbsArg::_verboseDirty(false) ; bool RooAbsArg::_inhibitDirty(false) ; @@ -116,12 +111,8 @@ std::stack RooAbsArg::_ioReadStack ; /// Default constructor RooAbsArg::RooAbsArg() - : TNamed(), _deleteWatch(false), _valueDirty(true), _shapeDirty(true), _operMode(Auto), _fast(false), _ownedComponents(nullptr), - _prohibitServerRedirect(false), _namePtr(0), _isConstant(false), _localNoInhibitDirty(false), - _myws(0) { _namePtr = RooNameReg::instance().constPtr(GetName()) ; - } //////////////////////////////////////////////////////////////////////////////// @@ -130,9 +121,7 @@ RooAbsArg::RooAbsArg() /// dirty flags set. RooAbsArg::RooAbsArg(const char *name, const char *title) - : TNamed(name, title), _deleteWatch(false), _valueDirty(true), _shapeDirty(true), _operMode(Auto), _fast(false), - _ownedComponents(0), _prohibitServerRedirect(false), _namePtr(0), _isConstant(false), - _localNoInhibitDirty(false), _myws(0) + : TNamed(name, title) { if (name == nullptr || strlen(name) == 0) { throw std::logic_error("Each RooFit object needs a name. " @@ -146,12 +135,14 @@ RooAbsArg::RooAbsArg(const char *name, const char *title) /// object. Transient properties and client-server links are not copied RooAbsArg::RooAbsArg(const RooAbsArg &other, const char *name) - : TNamed(name ? name : other.GetName(), other.GetTitle()), RooPrintable(other), + : TNamed(name ? name : other.GetName(), other.GetTitle()), + RooPrintable(other), _boolAttrib(other._boolAttrib), - _stringAttrib(other._stringAttrib), _deleteWatch(other._deleteWatch), _operMode(Auto), _fast(false), - _ownedComponents(0), _prohibitServerRedirect(false), + _stringAttrib(other._stringAttrib), + _deleteWatch(other._deleteWatch), _namePtr(name ? RooNameReg::instance().constPtr(name) : other._namePtr), - _isConstant(other._isConstant), _localNoInhibitDirty(other._localNoInhibitDirty), _myws(0) + _isConstant(other._isConstant), + _localNoInhibitDirty(other._localNoInhibitDirty) { // Copy server list by hand @@ -164,10 +155,6 @@ RooAbsArg::RooAbsArg(const RooAbsArg &other, const char *name) setValueDirty() ; setShapeDirty() ; - - //setAttribute(Form("CloneOf(%08x)",&other)) ; - //cout << "RooAbsArg::cctor(" << this << ") #bools = " << _boolAttrib.size() << " #strings = " << _stringAttrib.size() << endl ; - } @@ -186,10 +173,9 @@ RooAbsArg::~RooAbsArg() bool first(true) ; for (auto client : clientListTmp) { client->setAttribute("ServerDied") ; - TString attr("ServerDied:"); - attr.Append(GetName()); - attr.Append(Form("(%zx)",(size_t)this)) ; - client->setAttribute(attr.Data()); + std::stringstream attr; + attr << "ServerDied:" << GetName() << "(" << reinterpret_cast(this) << ")"; + client->setAttribute(attr.str().c_str()); client->removeServer(*this,true); if (_verboseDirty) { @@ -206,7 +192,7 @@ RooAbsArg::~RooAbsArg() if (_ownedComponents) { delete _ownedComponents ; - _ownedComponents = 0 ; + _ownedComponents = nullptr ; } } @@ -230,15 +216,6 @@ void RooAbsArg::verboseDirty(bool flag) _verboseDirty = flag ; } -//////////////////////////////////////////////////////////////////////////////// -/// Check if this object was created as a clone of 'other' - -bool RooAbsArg::isCloneOf(const RooAbsArg& other) const -{ - return (getAttribute(Form("CloneOf(%zx)",(size_t)&other)) || - other.getAttribute(Form("CloneOf(%zx)",(size_t)this))) ; -} - //////////////////////////////////////////////////////////////////////////////// /// Set (default) or clear a named boolean attribute of this object. @@ -246,7 +223,7 @@ bool RooAbsArg::isCloneOf(const RooAbsArg& other) const void RooAbsArg::setAttribute(const Text_t* name, bool value) { // Preserve backward compatibility - any strong - if(string("Constant")==name) { + if(std::string{"Constant"} == name) { _isConstant = value ; } @@ -302,7 +279,7 @@ const Text_t* RooAbsArg::getStringAttribute(const Text_t* key) const if (iter!=_stringAttrib.end()) { return iter->second.c_str() ; } else { - return 0 ; + return nullptr ; } } @@ -402,9 +379,11 @@ void RooAbsArg::addServerList(RooAbsCollection& serverList, bool valueProp, bool void RooAbsArg::removeServer(RooAbsArg& server, bool force) { if (_prohibitServerRedirect) { - cxcoutF(LinkStateMgmt) << "RooAbsArg::addServer(" << this << "," << GetName() << "): PROHIBITED SERVER REMOVAL REQUESTED: removing server " - << server.GetName() << "(" << &server << ")" << endl ; - assert(0) ; + std::stringstream ss; + ss << "RooAbsArg::addServer(" << this << "," << GetName() << "): PROHIBITED SERVER REMOVAL REQUESTED: removing server " + << server.GetName() << "(" << &server << ")"; + cxcoutF(LinkStateMgmt) << ss.str() << std::endl; + throw std::runtime_error(ss.str()); } if (_verboseDirty) { @@ -422,12 +401,34 @@ void RooAbsArg::removeServer(RooAbsArg& server, bool force) //////////////////////////////////////////////////////////////////////////////// -/// Replace 'oldServer' with 'newServer' +/// Replace 'oldServer' with 'newServer', specifying whether the new server has +/// value or shape server properties. +/// +/// \warning This function should not be used! This method is quite unsafe for +/// many reasons. For once, the new server will be put at the end of the server +/// list, no matter the position of the original server. This might mess up +/// code that expects the servers to be in a certain order. Furthermore, the +/// proxy objects corresponding to the server are not updated, leaving the +/// object in an invalid state where the servers are out of sync with the +/// proxies. This can have very bad consequences. Finally, by having to +/// manually specify the value and shape server properties, it is very easy to +/// get them wrong. +/// +/// If you want to safely replace a server, you should use +/// RooAbsArg::redirectServers(), which replaces the server in-place at the +/// same position of the server list, keeps the same value and shape server +/// properties, and also updates the corresponding proxies. void RooAbsArg::replaceServer(RooAbsArg& oldServer, RooAbsArg& newServer, bool propValue, bool propShape) { + coutW(LinkStateMgmt) << "replaceServer()" + << " is unsafe, because the server list will be out of sync with the proxy objects!" + << " If you want to safely replace a server, use RooAbsArg::redirectServers()." + << " See the docs to replaceServers() for more info." << std::endl; + Int_t count = _serverList.refCount(&oldServer); removeServer(oldServer, true); + addServer(newServer, propValue, propShape, count); } @@ -538,9 +539,38 @@ void RooAbsArg::treeNodeServerList(RooAbsCollection* list, const RooAbsArg* arg, /// function is responsible for deleting the returned argset. /// The complement of this function is getObservables() -RooArgSet* RooAbsArg::getParameters(const RooAbsData* set, bool stripDisconnected) const +RooFit::OwningPtr RooAbsArg::getParameters(const RooAbsData* set, bool stripDisconnected) const +{ + return getParameters(set?set->get():nullptr,stripDisconnected) ; +} + + +/// Return the parameters of this p.d.f when used in conjunction with dataset 'data'. +RooFit::OwningPtr RooAbsArg::getParameters(const RooAbsData& data, bool stripDisconnected) const { - return getParameters(set?set->get():0,stripDisconnected) ; + return getParameters(&data,stripDisconnected) ; +} + + +/// Return the parameters of the p.d.f given the provided set of observables. +RooFit::OwningPtr RooAbsArg::getParameters(const RooArgSet& observables, bool stripDisconnected) const +{ + return getParameters(&observables,stripDisconnected); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Create a list of leaf nodes in the arg tree starting with +/// ourself as top node that don't match any of the names the args in the +/// supplied argset. The caller of this function is responsible +/// for deleting the returned argset. The complement of this function +/// is getObservables(). + +RooFit::OwningPtr RooAbsArg::getParameters(const RooArgSet* observables, bool stripDisconnected) const +{ + auto * outputSet = new RooArgSet; + getParameters(observables, *outputSet, stripDisconnected); + return RooFit::OwningPtr{outputSet}; } @@ -583,7 +613,7 @@ void RooAbsArg::addParameters(RooAbsCollection& params, const RooArgSet* nset, b //////////////////////////////////////////////////////////////////////////////// /// Obtain an estimate of the number of parameters of the function and its daughters. -/// Calling `addParamters` for large functions (NLL) can cause many reallocations of +/// Calling `addParameters` for large functions (NLL) can cause many reallocations of /// `params` due to the recursive behaviour. This utility function aims to pre-compute /// the total number of parameters, so that enough memory is reserved. /// The estimate is not fully accurate (overestimate) as there is no equivalent to `getParametersHook`. @@ -616,19 +646,6 @@ std::size_t RooAbsArg::getParametersSizeEstimate(const RooArgSet* nset) const return res; } -//////////////////////////////////////////////////////////////////////////////// -/// Create a list of leaf nodes in the arg tree starting with -/// ourself as top node that don't match any of the names the args in the -/// supplied argset. The caller of this function is responsible -/// for deleting the returned argset. The complement of this function -/// is getObservables(). - -RooArgSet* RooAbsArg::getParameters(const RooArgSet* observables, bool stripDisconnected) const { - auto * outputSet = new RooArgSet; - getParameters(observables, *outputSet, stripDisconnected); - return outputSet; -} - //////////////////////////////////////////////////////////////////////////////// /// Fills a list with leaf nodes in the arg tree starting with @@ -678,6 +695,19 @@ bool RooAbsArg::getParameters(const RooArgSet* observables, RooArgSet& outputSet } +/// Given a set of possible observables, return the observables that this PDF depends on. +RooFit::OwningPtr RooAbsArg::getObservables(const RooArgSet &set, bool valueOnly) const +{ + return getObservables(&set, valueOnly); +} + +/// Return the observables of this pdf given the observables defined by `data`. +RooFit::OwningPtr RooAbsArg::getObservables(const RooAbsData &data) const +{ + return getObservables(&data); +} + + //////////////////////////////////////////////////////////////////////////////// /// Create a list of leaf nodes in the arg tree starting with /// ourself as top node that match any of the names of the variable list @@ -685,9 +715,9 @@ bool RooAbsArg::getParameters(const RooArgSet* observables, RooArgSet& outputSet /// function is responsible for deleting the returned argset. /// The complement of this function is getParameters(). -RooArgSet* RooAbsArg::getObservables(const RooAbsData* set) const +RooFit::OwningPtr RooAbsArg::getObservables(const RooAbsData* set) const { - if (!set) return new RooArgSet ; + if (!set) return RooFit::OwningPtr{new RooArgSet}; return getObservables(set->get()) ; } @@ -700,11 +730,11 @@ RooArgSet* RooAbsArg::getObservables(const RooAbsData* set) const /// for deleting the returned argset. The complement of this function /// is getParameters(). -RooArgSet* RooAbsArg::getObservables(const RooArgSet* dataList, bool valueOnly) const +RooFit::OwningPtr RooAbsArg::getObservables(const RooArgSet* dataList, bool valueOnly) const { auto depList = new RooArgSet; getObservables(dataList, *depList, valueOnly); - return depList; + return RooFit::OwningPtr{depList}; } @@ -728,7 +758,7 @@ bool RooAbsArg::getObservables(const RooAbsCollection* dataList, RooArgSet& outp // Make iterator over tree leaf node list RooArgSet leafList("leafNodeServerList") ; - treeNodeServerList(&leafList,0,false,true,valueOnly) ; + treeNodeServerList(&leafList,nullptr,false,true,valueOnly) ; if (valueOnly) { for (const auto arg : leafList) { @@ -748,18 +778,34 @@ bool RooAbsArg::getObservables(const RooAbsCollection* dataList, RooArgSet& outp } +/// \deprecated Use getObservables() +RooFit::OwningPtr RooAbsArg::getDependents(const RooArgSet &set) const +{ + return getObservables(set); +} + +/// \deprecated Use getObservables() +RooFit::OwningPtr RooAbsArg::getDependents(const RooAbsData *set) const +{ + return getObservables(set); +} + +/// \deprecated Use getObservables() +RooFit::OwningPtr RooAbsArg::getDependents(const RooArgSet *depList) const +{ + return getObservables(depList); +} + + //////////////////////////////////////////////////////////////////////////////// /// Create a RooArgSet with all components (branch nodes) of the /// expression tree headed by this object. -RooArgSet* RooAbsArg::getComponents() const +RooFit::OwningPtr RooAbsArg::getComponents() const { - TString name(GetName()) ; - name.Append("_components") ; - - RooArgSet* set = new RooArgSet(name) ; + RooArgSet* set = new RooArgSet((std::string(GetName()) + "_components").c_str()) ; branchNodeServerList(set) ; - return set ; + return RooFit::OwningPtr{set}; } @@ -817,21 +863,16 @@ bool RooAbsArg::dependsOn(const RooAbsCollection& serverList, const RooAbsArg* i //////////////////////////////////////////////////////////////////////////////// -/// Test whether we depend on (ie, are served by) the specified object. -/// Note that RooAbsArg objects are considered equivalent if they have -/// the same name. - -bool RooAbsArg::dependsOn(const RooAbsArg& testArg, const RooAbsArg* ignoreArg, bool valueOnly) const +/// Test whether we depend on (ie, are served by) an object with a specific name. +bool RooAbsArg::dependsOn(TNamed const* testArgNamePtr, const RooAbsArg* ignoreArg, bool valueOnly) const { if (this==ignoreArg) return false ; // First check if testArg is self - //if (!TString(testArg.GetName()).CompareTo(GetName())) return true ; - if (testArg.namePtr()==namePtr()) return true ; - + if (testArgNamePtr == namePtr()) return true ; // Next test direct dependence - RooAbsArg* foundServer = findServer(testArg) ; + RooAbsArg *foundServer = _serverList.findByNamePointer(testArgNamePtr); if (foundServer) { // Return true if valueOnly is FALSE or if server is value server, otherwise keep looking @@ -843,7 +884,7 @@ bool RooAbsArg::dependsOn(const RooAbsArg& testArg, const RooAbsArg* ignoreArg, // If not, recurse for (const auto server : _serverList) { if ( !valueOnly || server->isValueServer(*this)) { - if (server->dependsOn(testArg,ignoreArg,valueOnly)) { + if (server->dependsOn(testArgNamePtr,ignoreArg,valueOnly)) { return true ; } } @@ -883,10 +924,7 @@ bool RooAbsArg::observableOverlaps(const RooAbsData* dset, const RooAbsArg& test bool RooAbsArg::observableOverlaps(const RooArgSet* nset, const RooAbsArg& testArg) const { - RooArgSet* depList = getObservables(nset) ; - bool ret = testArg.dependsOn(*depList) ; - delete depList ; - return ret ; + return testArg.dependsOn(*std::unique_ptr{getObservables(nset)}); } @@ -907,7 +945,7 @@ void RooAbsArg::setValueDirty(const RooAbsArg* source) } // Cyclical dependency interception - if (source==0) { + if (source==nullptr) { source=this ; } else if (source==this) { // Cyclical dependency, abort @@ -951,7 +989,7 @@ void RooAbsArg::setShapeDirty(const RooAbsArg* source) } // Set 'dirty' shape state for this object and propagate flag to all its clients - if (source==0) { + if (source==nullptr) { source=this ; } else if (source==this) { // Cyclical dependency, abort @@ -1000,85 +1038,61 @@ bool RooAbsArg::redirectServers(const RooAbsCollection& newSetOrig, bool mustRep { // Trivial case, no servers if (_serverList.empty()) return false ; - if (newSetOrig.empty()) return false ; + + // We don't need to do anything if there are no new servers or if the only + // new server is this RooAbsArg itself. And by returning early, we avoid + // potentially annoying side effects of the redirectServersHook. + if (newSetOrig.empty() || (newSetOrig.size() == 1 && newSetOrig[0] == this)) return false ; // Strip any non-matching removal nodes from newSetOrig - RooAbsCollection* newSet ; + std::unique_ptr newSetOwned; + RooAbsCollection const* newSet = &newSetOrig; if (nameChange) { - newSet = new RooArgSet ; - for (auto arg : newSetOrig) { + newSetOwned = std::make_unique(); + for (auto arg : *newSet) { if (string("REMOVAL_DUMMY")==arg->GetName()) { if (arg->getAttribute("REMOVE_ALL")) { - newSet->add(*arg) ; + newSetOwned->add(*arg) ; } else if (arg->getAttribute(Form("REMOVE_FROM_%s",getStringAttribute("ORIGNAME")))) { - newSet->add(*arg) ; + newSetOwned->add(*arg) ; } } else { - newSet->add(*arg) ; + newSetOwned->add(*arg) ; } } - } else { - newSet = (RooAbsCollection*) &newSetOrig ; + newSet = newSetOwned.get(); } // Replace current servers with new servers with the same name from the given list - bool ret(false) ; - - //Copy original server list to not confuse the iterator while deleting - std::vector origServerList, origServerValue, origServerShape; - auto origSize = _serverList.size(); - origServerList.reserve(origSize); - origServerValue.reserve(origSize); - - for (const auto oldServer : _serverList) { - origServerList.push_back(oldServer) ; - - // Retrieve server side link state information - if (oldServer->_clientListValue.containsByNamePtr(this)) { - origServerValue.push_back(oldServer) ; - } - if (oldServer->_clientListShape.containsByNamePtr(this)) { - origServerShape.push_back(oldServer) ; - } - } - - // Delete all previously registered servers - for (auto oldServer : origServerList) { + for (auto oldServer : _serverList) { RooAbsArg * newServer= oldServer->findNewServer(*newSet, nameChange); - if (newServer && _verboseDirty) { - cxcoutD(LinkStateMgmt) << "RooAbsArg::redirectServers(" << (void*)this << "," << GetName() << "): server " << oldServer->GetName() - << " redirected from " << oldServer << " to " << newServer << endl ; - } - if (!newServer) { if (mustReplaceAll) { - coutE(LinkStateMgmt) << "RooAbsArg::redirectServers(" << (void*)this << "," << GetName() << "): server " << oldServer->GetName() - << " (" << (void*)oldServer << ") not redirected" << (nameChange?"[nameChange]":"") << endl ; - ret = true ; + std::stringstream ss; + ss << "RooAbsArg::redirectServers(" << (void*)this << "," << GetName() << "): server " << oldServer->GetName() + << " (" << (void*)oldServer << ") not redirected" << (nameChange?"[nameChange]":""); + const std::string errorMsg = ss.str(); + coutE(LinkStateMgmt) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); } continue ; } - auto findByNamePtr = [&oldServer](const RooAbsArg * item) { - return oldServer->namePtr() == item->namePtr(); - }; - bool propValue = std::any_of(origServerValue.begin(), origServerValue.end(), findByNamePtr); - bool propShape = std::any_of(origServerShape.begin(), origServerShape.end(), findByNamePtr); - if (newServer != this) { - replaceServer(*oldServer,*newServer,propValue,propShape) ; + substituteServer(oldServer, newServer); } } - setValueDirty() ; setShapeDirty() ; + bool ret(false) ; + // Process the proxies for (int i=0 ; iredirectServersHook(*newSet,mustReplaceAll,nameChange,isRecursionStep) ; - } - ret |= redirectServersHook(*newSet,mustReplaceAll,nameChange,isRecursionStep) ; + ret |= callRedirectServersHook(*newSet, mustReplaceAll, nameChange, isRecursionStep); + return ret; +} - if (nameChange) { - delete newSet ; - } +/// Private helper function for RooAbsArg::redirectServers(). +void RooAbsArg::substituteServer(RooAbsArg *oldServer, RooAbsArg *newServer) +{ + _serverList.Replace(oldServer, newServer); - return ret ; + const int clientListRefCount = oldServer->_clientList.Remove(this, true); + const int clientListValueRefCount = oldServer->_clientListValue.Remove(this, true); + const int clientListShapeRefCount = oldServer->_clientListShape.Remove(this, true); + + newServer->_clientList.Add(this, clientListRefCount); + newServer->_clientListValue.Add(this, clientListValueRefCount); + newServer->_clientListShape.Add(this, clientListShapeRefCount); + + if (clientListValueRefCount > 0 && newServer->operMode() == ADirty && operMode() != ADirty) { + setOperMode(ADirty); + } +} + +/// Private helper function for RooAbsArg::redirectServers(). +bool RooAbsArg::callRedirectServersHook(RooAbsCollection const &newSet, bool mustReplaceAll, bool nameChange, + bool isRecursionStep) +{ + bool ret = false; + for (Int_t i = 0; i < numCaches(); i++) { + ret |= getCache(i)->redirectServersHook(newSet, mustReplaceAll, nameChange, isRecursionStep); + } + ret |= redirectServersHook(newSet, mustReplaceAll, nameChange, isRecursionStep); + + return ret; +} + +//////////////////////////////////////////////////////////////////////////////// +/// Replace some servers of this object. If there are proxies that correspond +/// to the replaced servers, these proxies are adjusted as well. +/// \param[in] replacements Map that specifies which args replace which servers. +bool RooAbsArg::redirectServers(std::unordered_map const &replacements) +{ + bool ret(false); + bool nameChange = false; + + RooArgList newList; + + // Replace current servers with new servers with the same name from the given list + for (auto oldServer : _serverList) { + + auto newServerFound = replacements.find(oldServer); + RooAbsArg *newServer = newServerFound != replacements.end() ? newServerFound->second : nullptr; + + if (!newServer || newServer == this) { + continue; + } + + if (nameChange == false) + nameChange = strcmp(newServerFound->first->GetName(), newServerFound->second->GetName()) != 0; + + substituteServer(oldServer, newServer); + newList.add(*newServer); + } + + // No servers were replaced, we don't need to process proxies and call the + // redirectServersHook. + if (newList.empty()) + return ret; + + setValueDirty(); + setShapeDirty(); + + // Process the proxies + for (int i = 0; i < numProxies(); i++) { + if (RooAbsProxy *p = getProxy(i)) { + p->changePointer(replacements); + } + } + + // Optional subclass post-processing + ret |= callRedirectServersHook(newList, false, nameChange, false); + return ret; } //////////////////////////////////////////////////////////////////////////////// @@ -1117,7 +1201,7 @@ bool RooAbsArg::redirectServers(const RooAbsCollection& newSetOrig, bool mustRep /// \return Pointer to the new server or `nullptr` if there's no unique match. RooAbsArg *RooAbsArg::findNewServer(const RooAbsCollection &newSet, bool nameChange) const { - RooAbsArg *newServer = 0; + RooAbsArg *newServer = nullptr; if (!nameChange) { newServer = newSet.find(*this) ; } @@ -1127,76 +1211,89 @@ RooAbsArg *RooAbsArg::findNewServer(const RooAbsCollection &newSet, bool nameCha TString nameAttrib("ORIGNAME:") ; nameAttrib.Append(GetName()) ; - RooArgSet* tmp = (RooArgSet*) newSet.selectByAttrib(nameAttrib,true) ; - if(0 != tmp) { + if (auto tmp = std::unique_ptr{newSet.selectByAttrib(nameAttrib,true)}) { // Check if any match was found if (tmp->empty()) { - delete tmp ; - return 0 ; + return nullptr; } // Check if match is unique - if(tmp->getSize()>1) { - coutF(LinkStateMgmt) << "RooAbsArg::redirectServers(" << GetName() << "): FATAL Error, " << tmp->getSize() << " servers with " - << nameAttrib << " attribute" << endl ; + if(tmp->size()>1) { + std::stringstream ss; + ss << "RooAbsArg::redirectServers(" << GetName() << "): FATAL Error, " << tmp->size() << " servers with " + << nameAttrib << " attribute"; + coutF(LinkStateMgmt) << ss.str() << std::endl; tmp->Print("v") ; - assert(0) ; + throw std::runtime_error(ss.str()); } // use the unique element in the set newServer= tmp->first(); - delete tmp ; } } return newServer; } +namespace { + +bool recursiveRedirectServersImpl(RooAbsArg *arg, RooAbsCollection const &newSet, bool mustReplaceAll, bool nameChange, + bool recurseInNewSet, std::set &callStack) +{ + // Cyclic recursion protection + { + auto it = callStack.lower_bound(arg); + if (it != callStack.end() && arg == *it) { + return false; + } + callStack.insert(it, arg); + } + + // Do not recurse into newset if not so specified + // if (!recurseInNewSet && newSet.contains(*arg)) { + // return false; + // } + + // Apply the redirectServers function recursively on all branch nodes in this argument tree. + bool ret(false); + + oocxcoutD(arg, LinkStateMgmt) << "RooAbsArg::recursiveRedirectServers(" << arg << "," << arg->GetName() + << ") newSet = " << newSet << " mustReplaceAll = " << (mustReplaceAll ? "T" : "F") + << " nameChange = " << (nameChange ? "T" : "F") + << " recurseInNewSet = " << (recurseInNewSet ? "T" : "F") << endl; + + // Do redirect on self (identify operation as recursion step) + ret |= arg->redirectServers(newSet, mustReplaceAll, nameChange, true); + + // Do redirect on servers + for (const auto server : arg->servers()) { + ret |= recursiveRedirectServersImpl(server, newSet, mustReplaceAll, nameChange, recurseInNewSet, callStack); + } + + callStack.erase(arg); + return ret; +} + +} // namespace + //////////////////////////////////////////////////////////////////////////////// /// Recursively replace all servers with the new servers in `newSet`. -/// This substitutes objects that we receive values from (also indirectly through other objects) with new objects that have the same name. +/// This substitutes objects that we receive values from (also indirectly +/// through other objects) with new objects that have the same name. /// /// *Copied from redirectServers:* /// /// \copydetails RooAbsArg::redirectServers /// \param newSet Roo collection /// \param recurseInNewSet be recursive -bool RooAbsArg::recursiveRedirectServers(const RooAbsCollection& newSet, bool mustReplaceAll, bool nameChange, bool recurseInNewSet) -{ - // Cyclic recursion protection - static std::set callStack; - { - std::set::iterator it = callStack.lower_bound(this); - if (it != callStack.end() && this == *it) { - return false; - } else { - callStack.insert(it, this); - } - } - - // Do not recurse into newset if not so specified -// if (!recurseInNewSet && newSet.contains(*this)) { -// return false ; -// } - - - // Apply the redirectServers function recursively on all branch nodes in this argument tree. - bool ret(false) ; - - cxcoutD(LinkStateMgmt) << "RooAbsArg::recursiveRedirectServers(" << this << "," << GetName() << ") newSet = " << newSet << " mustReplaceAll = " - << (mustReplaceAll?"T":"F") << " nameChange = " << (nameChange?"T":"F") << " recurseInNewSet = " << (recurseInNewSet?"T":"F") << endl ; - - // Do redirect on self (identify operation as recursion step) - ret |= redirectServers(newSet,mustReplaceAll,nameChange,true) ; - - // Do redirect on servers - for (const auto server : _serverList){ - ret |= server->recursiveRedirectServers(newSet,mustReplaceAll,nameChange,recurseInNewSet) ; - } +bool RooAbsArg::recursiveRedirectServers(RooAbsCollection const &newSet, bool mustReplaceAll, bool nameChange, + bool recurseInNewSet) +{ + // For cyclic recursion protection + std::set callStack; - callStack.erase(this); - return ret ; + return recursiveRedirectServersImpl(this, newSet, mustReplaceAll, nameChange, recurseInNewSet, callStack); } @@ -1225,7 +1322,7 @@ bool RooAbsArg::redirectServersHook(const RooAbsCollection & /*newServerList*/, //////////////////////////////////////////////////////////////////////////////// /// Register an RooArgProxy in the proxy list. This function is called by owned -/// proxies upon creation. After registration, this arg wil forward pointer +/// proxies upon creation. After registration, this arg will forward pointer /// changes from serverRedirects and updates in cached normalization sets /// to the proxies immediately after they occur. The proxied argument is /// also added as value and/or shape server @@ -1270,7 +1367,7 @@ void RooAbsArg::unRegisterProxy(RooArgProxy& proxy) //////////////////////////////////////////////////////////////////////////////// /// Register an RooSetProxy in the proxy list. This function is called by owned -/// proxies upon creation. After registration, this arg wil forward pointer +/// proxies upon creation. After registration, this arg will forward pointer /// changes from serverRedirects and updates in cached normalization sets /// to the proxies immediately after they occur. @@ -1305,7 +1402,7 @@ void RooAbsArg::unRegisterProxy(RooSetProxy& proxy) //////////////////////////////////////////////////////////////////////////////// /// Register an RooListProxy in the proxy list. This function is called by owned -/// proxies upon creation. After registration, this arg wil forward pointer +/// proxies upon creation. After registration, this arg will forward pointer /// changes from serverRedirects and updates in cached normalization sets /// to the proxies immediately after they occur. @@ -1446,9 +1543,9 @@ void RooAbsArg::printClassName(ostream& os) const } +/// Print address of this RooAbsArg. void RooAbsArg::printAddress(ostream& os) const { - // Print addrss of this RooAbsArg os << this ; } @@ -1465,7 +1562,7 @@ void RooAbsArg::printArgs(ostream& os) const os << "[ " ; for (Int_t i=0 ; iname()).BeginsWith("!")) { p->print(os) ; os << " " ; @@ -1609,7 +1706,7 @@ void RooAbsArg::printAttribList(ostream& os) const void RooAbsArg::attachArgs(const RooAbsCollection &set) { RooArgSet branches; - branchNodeServerList(&branches,0,true); + branchNodeServerList(&branches,nullptr,true); for(auto const& branch : branches) { branch->redirectServers(set,false,false); @@ -1793,14 +1890,14 @@ bool RooAbsArg::findConstantNodes(const RooArgSet& observables, RooArgSet& cache // Check if node depends on any non-constant parameter bool canOpt(true) ; - RooArgSet* paramSet = getParameters(observables) ; - for(RooAbsArg * param : *paramSet) { + RooArgSet paramSet; + getParameters(&observables, paramSet); + for(RooAbsArg * param : paramSet) { if (!param->isConstant()) { canOpt=false ; break ; } } - delete paramSet ; if (getAttribute("NeverConstant")) { @@ -1869,7 +1966,7 @@ void RooAbsArg::setOperMode(OperMode mode, bool recurseADirty) if (mode==_operMode) return ; _operMode = mode ; - _fast = ((mode==AClean) || dynamic_cast(this)!=0 || dynamic_cast(this)!=0 ) ; + _fast = ((mode==AClean) || dynamic_cast(this) || dynamic_cast(this) ) ; for (Int_t i=0 ;ioperModeHook() ; } @@ -1954,7 +2051,7 @@ void RooAbsArg::printComponentTree(const char* indent, const char* namePat, Int_ { if (nLevel==0) return ; if (isFundamental()) return ; - RooResolutionModel* rmodel = dynamic_cast(this) ; + auto rmodel = dynamic_cast(this) ; if (rmodel && rmodel->isConvolved()) return ; if (InheritsFrom("RooConstVar")) return ; @@ -2052,38 +2149,14 @@ RooAbsCache* RooAbsArg::getCache(Int_t index) const //////////////////////////////////////////////////////////////////////////////// -/// Return RooArgSet with all variables (tree leaf nodes of expresssion tree) +/// Return RooArgSet with all variables (tree leaf nodes of expression tree) -RooArgSet* RooAbsArg::getVariables(bool stripDisconnected) const +RooFit::OwningPtr RooAbsArg::getVariables(bool stripDisconnected) const { return getParameters(RooArgSet(),stripDisconnected) ; } -//////////////////////////////////////////////////////////////////////////////// -/// Return ancestors in cloning chain of this RooAbsArg. NOTE: Returned pointers -/// are not guaranteed to be 'live', so do not dereference without proper caution - -RooLinkedList RooAbsArg::getCloningAncestors() const -{ - RooLinkedList retVal ; - - set::const_iterator iter= _boolAttrib.begin() ; - while(iter != _boolAttrib.end()) { - if (TString(*iter).BeginsWith("CloneOf(")) { - char buf[128] ; - strlcpy(buf,iter->c_str(),128) ; - strtok(buf,"(") ; - char* ptrToken = strtok(0,")") ; - RooAbsArg* ptr = (RooAbsArg*) strtoll(ptrToken,0,16) ; - retVal.Add(ptr) ; - } - } - - return retVal ; -} - - //////////////////////////////////////////////////////////////////////////////// /// Create a GraphViz .dot file visualizing the expression tree headed by /// this RooAbsArg object. Use the GraphViz tool suite to make e.g. a gif @@ -2134,7 +2207,7 @@ void RooAbsArg::graphVizTree(ostream& os, const char* delimiter, bool useTitle, string nodeLabel = (useTitle && !nodeTitle.empty()) ? nodeTitle : nodeName; // if using latex, replace ROOT's # with normal latex backslash - string::size_type position = nodeLabel.find("#") ; + string::size_type position = nodeLabel.find('#') ; while(useLatex && position!=nodeLabel.npos){ nodeLabel.replace(position, 1, "\\"); } @@ -2219,32 +2292,12 @@ bool RooAbsArg::addOwnedComponents(RooArgList&& comps) { RooAbsArg* RooAbsArg::cloneTree(const char* newname) const { - // Clone tree using snapshot - RooArgSet clonedNodes; - RooArgSet(*this).snapshot(clonedNodes, true); - - // Find the head node in the cloneSet - RooAbsArg* head = clonedNodes.find(*this) ; - assert(head); - - // We better to release the ownership before removing the "head". Otherwise, - // "head" might also be deleted as the clonedNodes collection owns it. - // (Actually this does not happen because even an owning collection doesn't - // delete the element when removed by pointer lookup, but it's better not to - // rely on this unexpected fact). - clonedNodes.releaseOwnership(); - - // Remove the head node from the cloneSet - // To release it from the set ownership - clonedNodes.remove(*head) ; - - // Add the set as owned component of the head - head->addOwnedComponents(std::move(clonedNodes)) ; + // In the RooHelpers, there is a more general implementation that we will reuse here + RooAbsArg *head = RooHelpers::Detail::cloneTreeWithSameParametersImpl(*this, nullptr); // Adjust name of head node if requested if (newname) { - head->TNamed::SetName(newname) ; - head->_namePtr = RooNameReg::instance().constPtr(newname) ; + head->SetName(newname) ; } // Return the head @@ -2435,7 +2488,7 @@ void RooRefArray::Streamer(TBuffer &R__b) R__c = R__b.WriteVersion(RooRefArray::IsA(), true); // Make a temporary refArray and write that to the streamer - TRefArray refArray(GetEntriesFast()); + TRefArray refArray; for(TObject * tmpObj : *this) { refArray.Add(tmpObj) ; } @@ -2470,15 +2523,44 @@ void RooAbsArg::applyWeightSquared(bool flag) { } -/// Fills a RooArgSet to be used as the normalization set for a server, given a -/// normalization set for this RooAbsArg. If the output is a `nullptr`, it -/// means that the normalization set doesn't change. +std::unique_ptr RooAbsArg::compileForNormSet(RooArgSet const & normSet, RooFit::Detail::CompileContext & ctx) const +{ + auto newArg = std::unique_ptr{static_cast(Clone())}; + ctx.markAsCompiled(*newArg); + ctx.compileServers(*newArg, normSet); + return newArg; +} + + +//////////////////////////////////////////////////////////////////////////////// +/// This function defines a translation for each RooAbsReal based object that can be used +/// to express the class as simple C++ code. The function adds the code represented by +/// each class as an std::string (that is later concatenated with code strings from translate calls) +/// to form the C++ code that AD tools can understand. Any class that wants to support AD, has to +/// implement this function. /// -/// \param[in] normSet The normalization set for this RooAbsArg. -/// \param[in] server A server of this RooAbsArg that we determine the -/// normalization set for. -/// \param[out] serverNormSet Output parameter. Normalization set for the -/// server. -std::unique_ptr RooAbsArg::fillNormSetForServer(RooArgSet const& /*normSet*/, RooAbsArg const& /*server*/) const { - return nullptr; +/// \param[in] ctx An object to manage auxiliary information for code-squashing. Also takes the +/// code string that this class outputs into the squashed code through the 'addToCodeBody' function. +void RooAbsArg::translate(RooFit::Detail::CodeSquashContext & /*ctx*/) const +{ + std::stringstream errorMsg; + errorMsg << "Translate function for class \"" << ClassName() << "\" has not yet been implemented."; + coutE(Minimization) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); +} + +/// Sets the token for retrieving results in the BatchMode. For internal use only. +void RooAbsArg::setDataToken(std::size_t index) +{ + if (_dataToken == index) { + return; + } + if (_dataToken != std::numeric_limits::max()) { + std::stringstream errMsg; + errMsg << "The data token for \"" << GetName() << "\" is already set!" + << " Are you trying to evaluate the same object by multiple RooFit::Evaluator instances?" + << " This is not allowed."; + throw std::runtime_error(errMsg.str()); + } + _dataToken = index; } diff --git a/roofit/roofitcore/src/RooAbsCachedPdf.cxx b/roofit/roofitcore/src/RooAbsCachedPdf.cxx index 5b3a909f8b612..159a0c0ce71c6 100644 --- a/roofit/roofitcore/src/RooAbsCachedPdf.cxx +++ b/roofit/roofitcore/src/RooAbsCachedPdf.cxx @@ -33,6 +33,7 @@ for changes to trigger a refilling of the cache histogram. #include "RooDataHist.h" #include "RooHistPdf.h" #include "RooExpensiveObjectCache.h" +#include "RooNormalizedPdf.h" ClassImp(RooAbsCachedPdf); @@ -113,7 +114,7 @@ RooAbsCachedPdf::PdfCacheElem* RooAbsCachedPdf::getCache(const RooArgSet* nset, { // Check if this configuration was created becfore int sterileIdx = -1 ; - auto cache = static_cast(_cacheMgr.getObj(nset,0,&sterileIdx)); + auto cache = static_cast(_cacheMgr.getObj(nset,nullptr,&sterileIdx)); // Check if we have a cache histogram in the global expensive object cache if (cache) { @@ -130,12 +131,12 @@ RooAbsCachedPdf::PdfCacheElem* RooAbsCachedPdf::getCache(const RooArgSet* nset, cache = createCache(nset) ; // Check if we have contents registered already in global expensive object cache - auto htmp = static_cast(expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters())); + auto histTmp = static_cast(expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters())); - if (htmp) { + if (histTmp) { cache->hist()->reset() ; - cache->hist()->add(*htmp) ; + cache->hist()->add(*histTmp) ; } else { @@ -149,11 +150,11 @@ RooAbsCachedPdf::PdfCacheElem* RooAbsCachedPdf::getCache(const RooArgSet* nset, // Store this cache configuration - int code = _cacheMgr.setObj(nset,0,(static_cast(cache)),0) ; + int code = _cacheMgr.setObj(nset,nullptr,(static_cast(cache)),nullptr) ; coutI(Caching) << "RooAbsCachedPdf::getCache(" << GetName() << ") creating new cache " << cache << " with pdf " << cache->pdf()->GetName() << " for nset " << (nset?*nset:RooArgSet()) << " with code " << code ; - if (htmp) { + if (histTmp) { ccoutI(Caching) << " from preexisting content." ; } ccoutI(Caching) << std::endl ; @@ -181,7 +182,7 @@ RooAbsCachedPdf::PdfCacheElem::PdfCacheElem(const RooAbsCachedPdf& self, const R // Create RooDataHist auto hname = std::string(self.GetName()) + "_" + self.inputBaseName() + "_CACHEHIST" - + self.cacheNameSuffix(orderedObs).c_str() + self.histNameSuffix().Data(); + + self.cacheNameSuffix(orderedObs) + self.histNameSuffix().Data(); _hist = std::make_unique(hname,hname,orderedObs,self.binningName()) ; _hist->removeSelfFromDir() ; @@ -378,7 +379,7 @@ double RooAbsCachedPdf::analyticalIntegralWN(int code, const RooArgSet* normSet, return getVal(normSet) ; } - RooArgSet *allVars(0),*anaVars(0),*normSet2(0),*dummy(0) ; + RooArgSet *allVars(nullptr),*anaVars(nullptr),*normSet2(nullptr),*dummy(nullptr) ; const std::vector codeList = _anaReg.retrieve(code-1,allVars,anaVars,normSet2,dummy) ; PdfCacheElem* cache = getCache(normSet2?normSet2:anaVars,false) ; @@ -396,8 +397,30 @@ double RooAbsCachedPdf::analyticalIntegralWN(int code, const RooArgSet* normSet, } -void RooAbsCachedPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooAbsCachedPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { auto * cachePdf = getCachePdf(_normSet); - cachePdf->computeBatch(stream, output, nEvents, dataMap); + cachePdf->computeBatch(output, nEvents, dataMap); +} + + +std::unique_ptr +RooAbsCachedPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + if (normSet.empty()) { + return RooAbsPdf::compileForNormSet(normSet, ctx); + } + std::unique_ptr pdfClone(static_cast(this->Clone())); + ctx.compileServers(*pdfClone, {}); + + auto newArg = std::make_unique(*pdfClone, normSet); + + // The direct servers are this pdf and the normalization integral, which + // don't need to be compiled further. + for (RooAbsArg *server : newArg->servers()) { + ctx.markAsCompiled(*server); + } + ctx.markAsCompiled(*newArg); + newArg->addOwnedComponents(std::move(pdfClone)); + return newArg; } diff --git a/roofit/roofitcore/src/RooAbsCachedReal.cxx b/roofit/roofitcore/src/RooAbsCachedReal.cxx index 31df9d53ec5ad..f1f09b9a2ab52 100644 --- a/roofit/roofitcore/src/RooAbsCachedReal.cxx +++ b/roofit/roofitcore/src/RooAbsCachedReal.cxx @@ -125,7 +125,7 @@ RooAbsCachedReal::FuncCacheElem* RooAbsCachedReal::getCache(const RooArgSet* nse { // Check if this configuration was created becfore Int_t sterileIdx(-1) ; - FuncCacheElem* cache = (FuncCacheElem*) _cacheMgr.getObj(nset,0,&sterileIdx) ; + FuncCacheElem* cache = (FuncCacheElem*) _cacheMgr.getObj(nset,nullptr,&sterileIdx) ; if (cache) { if (cache->paramTracker()->hasChanged(true)) { ccoutD(Eval) << "RooAbsCachedReal::getCache(" << GetName() << ") cached function " @@ -144,12 +144,12 @@ RooAbsCachedReal::FuncCacheElem* RooAbsCachedReal::getCache(const RooArgSet* nse } // Check if we have contents registered already in global expensive object cache - RooDataHist* htmp = (RooDataHist*) expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters()) ; + RooDataHist* histTmp = (RooDataHist*) expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters()) ; - if (htmp) { + if (histTmp) { cache->hist()->reset() ; - cache->hist()->add(*htmp) ; + cache->hist()->add(*histTmp) ; } else { @@ -161,7 +161,7 @@ RooAbsCachedReal::FuncCacheElem* RooAbsCachedReal::getCache(const RooArgSet* nse } // Store this cache configuration - Int_t code = _cacheMgr.setObj(nset,0,((RooAbsCacheElement*)cache),0) ; + Int_t code = _cacheMgr.setObj(nset,nullptr,((RooAbsCacheElement*)cache),nullptr) ; ccoutD(Caching) << "RooAbsCachedReal("<func()->GetName() << " for nset " << (nset?*nset:RooArgSet()) << " with code " << code << endl ; return cache ; @@ -181,9 +181,9 @@ RooAbsCachedReal::FuncCacheElem::FuncCacheElem(const RooAbsCachedReal& self, con { // Disable source caching by default _cacheSource = false ; - _sourceClone = 0 ; + _sourceClone = nullptr ; - RooArgSet* nset2 = self.actualObservables(nset?*nset:RooArgSet()) ; + std::unique_ptr nset2{self.actualObservables(nset?*nset:RooArgSet())}; RooArgSet orderedObs ; self.preferredObservableScanOrder(*nset2,orderedObs) ; @@ -194,7 +194,7 @@ RooAbsCachedReal::FuncCacheElem::FuncCacheElem(const RooAbsCachedReal& self, con _hist = new RooDataHist(hname,hname,*nset2,self.binningName()) ; _hist->removeSelfFromDir() ; - RooArgSet* observables= self.actualObservables(*nset2) ; + std::unique_ptr observables{self.actualObservables(*nset2)}; // Create RooHistFunc TString funcname = self.inputBaseName() ; @@ -207,7 +207,7 @@ RooAbsCachedReal::FuncCacheElem::FuncCacheElem(const RooAbsCachedReal& self, con _func->setValueDirty() ; // Create pseudo-object that tracks changes in parameter values - RooArgSet* params = self.actualParameters(orderedObs) ; + std::unique_ptr params{self.actualParameters(orderedObs)}; string name= Form("%s_CACHEPARAMS",_func->GetName()) ; _paramTracker = new RooChangeTracker(name.c_str(),name.c_str(),*params,true) ; _paramTracker->hasChanged(true) ; // clear dirty flag as cache is up-to-date upon creation @@ -215,12 +215,6 @@ RooAbsCachedReal::FuncCacheElem::FuncCacheElem(const RooAbsCachedReal& self, con // Introduce formal dependency of RooHistFunc on parameters so that const optimization code // makes the correct decisions _func->addServerList(*params) ; - - - delete observables ; - delete params ; - delete nset2 ; - } diff --git a/roofit/roofitcore/src/RooAbsCategory.cxx b/roofit/roofitcore/src/RooAbsCategory.cxx index d9896fcc81e0a..069cff7ef1688 100644 --- a/roofit/roofitcore/src/RooAbsCategory.cxx +++ b/roofit/roofitcore/src/RooAbsCategory.cxx @@ -63,8 +63,6 @@ the following replacements should be used: #include #include -using namespace std; - ClassImp(RooAbsCategory); /// A category state to signify an invalid category. The category name is empty, @@ -247,13 +245,13 @@ const std::map::value_type& RooAbsCateg if (hasIndex(index)) { coutE(InputArguments) << "RooAbsCategory::" << __func__ << "(" << GetName() << "): index " - << index << " already assigned" << endl ; + << index << " already assigned" << std::endl; return invalidCategory(); } if (hasLabel(label)) { coutE(InputArguments) << "RooAbsCategory::" << __func__ << "(" << GetName() << "): label " - << label << " already assigned or not allowed" << endl ; + << label << " already assigned or not allowed" << std::endl; return invalidCategory(); } @@ -319,7 +317,7 @@ const RooCatType* RooAbsCategory::lookupType(RooAbsCategory::value_type index, b if (printError) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":lookupType: no match for index " - << index << endl; + << index << std::endl; } return nullptr; @@ -347,7 +345,7 @@ const RooCatType* RooAbsCategory::lookupType(const char* label, bool printError) if (printError) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":lookupType: no match for label " - << label << endl; + << label << std::endl; } return nullptr; } @@ -376,7 +374,7 @@ Roo1DTable* RooAbsCategory::createTable(const char *label) const //////////////////////////////////////////////////////////////////////////////// /// Read object contents from stream (dummy for now) -bool RooAbsCategory::readFromStream(istream&, bool, bool) +bool RooAbsCategory::readFromStream(std::istream&, bool, bool) { return false ; } @@ -386,7 +384,7 @@ bool RooAbsCategory::readFromStream(istream&, bool, bool) //////////////////////////////////////////////////////////////////////////////// /// Write object contents to ostream -void RooAbsCategory::writeToStream(ostream& os, bool /* compact */) const +void RooAbsCategory::writeToStream(std::ostream& os, bool /* compact */) const { os << getCurrentLabel() ; } @@ -396,9 +394,9 @@ void RooAbsCategory::writeToStream(ostream& os, bool /* compact */) const //////////////////////////////////////////////////////////////////////////////// /// Print value (label name) -void RooAbsCategory::printValue(ostream& os) const +void RooAbsCategory::printValue(std::ostream& os) const { - os << getCurrentLabel() << "(idx = " << getCurrentIndex() << ")" << endl ; + os << getCurrentLabel() << "(idx = " << getCurrentIndex() << ")" << std::endl; } @@ -409,17 +407,17 @@ void RooAbsCategory::printValue(ostream& os) const /// /// Shape : label, index, defined types -void RooAbsCategory::printMultiline(ostream& os, Int_t contents, bool verbose, TString indent) const +void RooAbsCategory::printMultiline(std::ostream& os, Int_t contents, bool verbose, TString indent) const { RooAbsArg::printMultiline(os,contents,verbose,indent); - os << indent << "--- RooAbsCategory ---" << endl; + os << indent << "--- RooAbsCategory ---" << std::endl; if (stateNames().empty()) { - os << indent << " ** No values defined **" << endl; + os << indent << " ** No values defined **" << std::endl; return; } - os << indent << " Value = " << getCurrentIndex() << " \"" << getCurrentLabel() << ')' << endl; - os << indent << " Possible states:" << endl; + os << indent << " Value = " << getCurrentIndex() << " \"" << getCurrentLabel() << ')' << std::endl; + os << indent << " Possible states:" << std::endl; indent.Append(" "); for (const auto& type : stateNames()) { os << indent << type.first << '\t' << type.second << "\n"; @@ -447,26 +445,26 @@ void RooAbsCategory::attachToVStore(RooVectorDataStore& vstore) void RooAbsCategory::attachToTree(TTree& tree, Int_t bufSize) { // First check if there is an integer branch matching the category name - TString cleanName(cleanBranchName()) ; - TBranch* branch = tree.GetBranch(cleanName) ; + std::string cleanName = cleanBranchName().Data(); + TBranch* branch = tree.GetBranch(cleanName.c_str()); if (!branch) { cleanName += "_idx"; - branch = tree.GetBranch(cleanName); + branch = tree.GetBranch(cleanName.c_str()); } if (branch) { - TLeaf* leaf = (TLeaf*)branch->GetListOfLeaves()->At(0) ; + TLeaf* leaf = static_cast(branch->GetListOfLeaves()->At(0)); // Check that leaf is _not_ an array Int_t dummy ; TLeaf* counterLeaf = leaf->GetLeafCounter(dummy) ; if (counterLeaf) { coutE(Eval) << "RooAbsCategory::attachToTree(" << GetName() << ") ERROR: TTree branch " << GetName() - << " is an array and cannot be attached to a RooAbsCategory" << endl ; + << " is an array and cannot be attached to a RooAbsCategory" << std::endl; return ; } - TString typeName(leaf->GetTypeName()) ; + const std::string typeName = leaf->GetTypeName(); // For different type names, store a function to attach @@ -483,26 +481,24 @@ void RooAbsCategory::attachToTree(TTree& tree, Int_t bufSize) {"UShort_t", [&](){ return createTreeReadBuffer(cleanName, tree); }}, }; - auto typeDetails = typeMap.find(typeName.Data()); + auto typeDetails = typeMap.find(typeName); if (typeDetails != typeMap.end()) { coutI(DataHandling) << "RooAbsCategory::attachToTree(" << GetName() << ") TTree " << typeName << " branch \"" << cleanName - << "\" will be converted to int." << endl ; + << "\" will be converted to int." << std::endl; _treeReadBuffer = typeDetails->second(); } else { _treeReadBuffer = nullptr; - if (!typeName.CompareTo("Int_t")) { - tree.SetBranchAddress(cleanName, &_currentIndex); + if (typeName == "Int_t") { + tree.SetBranchAddress(cleanName.c_str(), &_currentIndex); } else { - coutE(InputArguments) << "RooAbsCategory::attachToTree(" << GetName() << ") data type " << typeName << " is not supported." << endl ; + coutE(InputArguments) << "RooAbsCategory::attachToTree(" << GetName() << ") data type " << typeName << " is not supported." << std::endl; } } } else { - TString format(cleanName); - format.Append("/I"); void* ptr = &_currentIndex; - tree.Branch(cleanName, ptr, (const Text_t*)format, bufSize); + tree.Branch(cleanName.c_str(), ptr, (cleanName + "/I").c_str(), bufSize); } } @@ -513,13 +509,10 @@ void RooAbsCategory::attachToTree(TTree& tree, Int_t bufSize) void RooAbsCategory::fillTreeBranch(TTree& t) { - TString idxName(GetName()) ; - idxName.Append("_idx") ; - // First determine if branch is taken - TBranch* idxBranch = t.GetBranch(idxName) ; + TBranch* idxBranch = t.GetBranch((std::string(GetName()) + "_idx").c_str()) ; if (!idxBranch) { - coutF(DataHandling) << "RooAbsCategory::fillTreeBranch(" << GetName() << ") ERROR: not attached to tree" << endl ; + coutF(DataHandling) << "RooAbsCategory::fillTreeBranch(" << GetName() << ") ERROR: not attached to tree" << std::endl; throw std::runtime_error("RooAbsCategory::fillTreeBranch(): Category is not attached to a tree."); } @@ -535,7 +528,7 @@ void RooAbsCategory::setTreeBranchStatus(TTree& t, bool active) { TBranch* branch = t.GetBranch(Form("%s_idx",GetName())) ; if (branch) { - t.SetBranchStatus(Form("%s_idx",GetName()),active?1:0) ; + t.SetBranchStatus(Form("%s_idx",GetName()),active?true:false) ; } } @@ -639,17 +632,17 @@ unsigned int RooAbsCategory::getCurrentOrdinalNumber() const { //////////////////////////////////////////////////////////////////////////////// /// Create a RooCategory fundamental object with our properties. -RooAbsArg *RooAbsCategory::createFundamental(const char* newname) const +RooFit::OwningPtr RooAbsCategory::createFundamental(const char* newname) const { // Add and precalculate new category column - RooCategory *fund= new RooCategory(newname?newname:GetName(),GetTitle()) ; + auto fund = std::make_unique(newname?newname:GetName(),GetTitle()) ; // Copy states for (const auto& type : stateNames()) { fund->defineStateUnchecked(type.first, type.second); } - return fund; + return RooFit::Detail::owningPtr(std::move(fund)); } @@ -665,7 +658,7 @@ bool RooAbsCategory::isSignType(bool mustHaveZero) const if (mustHaveZero && theStateNames.size() != 3) return false; for (const auto& type : theStateNames) { - if (abs(type.second)>1) + if (std::abs(type.second)>1) return false; } @@ -699,7 +692,7 @@ RooCatType* RooAbsCategory::retrieveLegacyState(value_type index) const { auto result = _legacyStates.find(index); if (result == _legacyStates.end()) { result = _legacyStates.emplace(index, - std::unique_ptr(new RooCatType(lookupName(index).c_str(), index))).first; + std::make_unique(lookupName(index).c_str(), index)).first; } return result->second.get(); @@ -713,7 +706,5 @@ RooAbsCategory::value_type RooAbsCategory::nextAvailableStateIndex() const { return 0; return 1 + std::max_element(theStateNames.begin(), theStateNames.end(), - [](const std::map::value_type& left, - const std::map::value_type& right) { - return left.second < right.second; })->second; + [](auto const& left, auto const& right) { return left.second < right.second; })->second; } diff --git a/roofit/roofitcore/src/RooAbsCategoryLValue.cxx b/roofit/roofitcore/src/RooAbsCategoryLValue.cxx index 528529d574112..65959bce69b4b 100644 --- a/roofit/roofitcore/src/RooAbsCategoryLValue.cxx +++ b/roofit/roofitcore/src/RooAbsCategoryLValue.cxx @@ -28,13 +28,11 @@ of the value. RooAbsCategoryLValue may be derived, but its functional relation to other RooAbsArgs must be invertible. */ -#include "RooAbsCategoryLValue.h" +#include -#include "RooArgSet.h" -#include "RooRandom.h" -#include "RooMsgService.h" +#include +#include -using namespace std; ClassImp(RooAbsCategoryLValue); @@ -62,15 +60,6 @@ RooAbsCategoryLValue::RooAbsCategoryLValue(const RooAbsCategoryLValue& other, co -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooAbsCategoryLValue::~RooAbsCategoryLValue() -{ -} - - - //////////////////////////////////////////////////////////////////////////////// /// Assignment operator from integer index number @@ -127,7 +116,7 @@ bool RooAbsCategoryLValue::setOrdinal(UInt_t n) //////////////////////////////////////////////////////////////////////////////// /// Copy the cached value from given source and raise dirty flag. -/// It is the callers responsability to ensure that the sources +/// It is the callers responsibility to ensure that the sources /// cache is clean(valid) before this function is called, e.g. by /// calling syncCache() on the source. @@ -176,22 +165,22 @@ void RooAbsCategoryLValue::setBin(Int_t ibin, const char* rangeName) // Check validity of ibin if (ibin<0 || ibin>=numBins(rangeName)) { coutE(InputArguments) << "RooAbsCategoryLValue::setBin(" << GetName() << ") ERROR: bin index " << ibin - << " is out of range (0," << numBins(rangeName)-1 << ")" << endl ; + << " is out of range (0," << numBins(rangeName)-1 << ")" << std::endl; return ; } - if (rangeName) { + if (rangeName && getBinningPtr(rangeName)) { coutF(InputArguments) << "RooAbsCategoryLValue::setBin(" << GetName() << ") ERROR: ranges not implemented" " for setting bins in categories." << std::endl; throw std::logic_error("Ranges not implemented for setting bins in categories."); } // Retrieve state corresponding to bin - const auto& type = getOrdinal(ibin); - assert(type.second != std::numeric_limits::min()); + value_type val = getOrdinal(ibin).second; + assert(val != std::numeric_limits::min()); // Set value to requested state - setIndex(type.second); + setIndex(val); } diff --git a/roofit/roofitcore/src/RooAbsCollection.cxx b/roofit/roofitcore/src/RooAbsCollection.cxx index 43c0040385bcd..bf6addf512b0b 100644 --- a/roofit/roofitcore/src/RooAbsCollection.cxx +++ b/roofit/roofitcore/src/RooAbsCollection.cxx @@ -31,7 +31,6 @@ implemented using the container denoted by RooAbsCollection::Storage_t. #include "TClass.h" #include "TRegexp.h" #include "RooStreamParser.h" -#include "RooFormula.h" #include "RooAbsRealLValue.h" #include "RooAbsCategoryLValue.h" #include "RooStringVar.h" @@ -42,8 +41,9 @@ implemented using the container denoted by RooAbsCollection::Storage_t. #include "RooRealVar.h" #include "RooGlobalFunc.h" #include "RooMsgService.h" -#include "strlcpy.h" +#include +#include #include #include #include @@ -66,7 +66,7 @@ namespace Detail { */ struct HashAssistedFind { - /// Inititalise empty hash map for fast finding by name. + /// Initialise empty hash map for fast finding by name. template HashAssistedFind(It_t first, It_t last) : currentRooNameRegCounter{ RooNameReg::instance().renameCounter() }, @@ -253,73 +253,10 @@ RooAbsCollection* RooAbsCollection::snapshot(bool deepCopy) const bool RooAbsCollection::snapshot(RooAbsCollection& output, bool deepCopy) const { - // Copy contents - output.reserve(_list.size()); - for (auto orig : _list) { - output.add(*static_cast(orig->Clone())); - } - - // Add external dependents - bool error(false) ; - if (deepCopy) { - // Recursively add clones of all servers - // Can only do index access because collection might reallocate when growing - for (Storage_t::size_type i = 0; i < output._list.size(); ++i) { - const auto var = output._list[i]; - error |= output.addServerClonesToList(*var); - } - } - - // Handle eventual error conditions - if (error) { - coutE(ObjectHandling) << "RooAbsCollection::snapshot(): Errors occurred in deep clone process, snapshot not created" << std::endl; - output._ownCont = true ; - return true ; - } - - - - // Redirect all server connections to internal list members - for (auto var : output) { - var->redirectServers(output,deepCopy); - } - - - // Transfer ownership of contents to list - output._ownCont = true ; - return false ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Add clones of servers of given argument to end of list - -bool RooAbsCollection::addServerClonesToList(const RooAbsArg& var) -{ - bool ret(false) ; - - // This can be a very heavy operation if existing elements depend on many others, - // so make sure that we have the hash map available for faster finding. - if (var.servers().size() > 20 || _list.size() > 30) - useHashMapForFind(true); - - for (const auto server : var.servers()) { - RooAbsArg* tmp = find(*server) ; - - if (!tmp) { - auto* serverClone = static_cast(server->Clone()); - serverClone->setAttribute("SnapShot_ExtRefClone") ; - insert(serverClone); - ret |= addServerClonesToList(*server) ; - } - } - - return ret ; + return RooHelpers::Detail::snapshotImpl(*this, output, deepCopy, nullptr); } - //////////////////////////////////////////////////////////////////////////////// /// Assign values from the elements in `other` to our elements. /// \warning This is not a conventional assignment operator. To avoid confusion, prefer using RooAbsCollection::assign(). @@ -354,10 +291,10 @@ void RooAbsCollection::assign(const RooAbsCollection& other) const //////////////////////////////////////////////////////////////////////////////// /// Sets the value of any argument in our set that also appears in the other set. -/// \param[in] other Collection holding the arguments to syncronize values with. +/// \param[in] other Collection holding the arguments to synchronize values with. /// \param[in] forceIfSizeOne If set to true and both our collection /// and the other collection have a size of one, the arguments are -/// always syncronized without checking if they have the same name. +/// always synchronized without checking if they have the same name. RooAbsCollection &RooAbsCollection::assignValueOnly(const RooAbsCollection& other, bool forceIfSizeOne) { @@ -643,7 +580,7 @@ bool RooAbsCollection::replace(const RooAbsArg& var1, const RooAbsArg& var2) // is var2's name already in this list? if (dynamic_cast(this)) { RooAbsArg *other = find(var2); - if(other != 0 && other != &var1) { + if(other != nullptr && other != &var1) { coutE(ObjectHandling) << "RooAbsCollection: cannot replace \"" << name << "\" with already existing \"" << var2.GetName() << "\"" << std::endl; return false; @@ -656,7 +593,7 @@ bool RooAbsCollection::replace(const RooAbsArg& var1, const RooAbsArg& var2) } *var1It = const_cast(&var2); //FIXME try to get rid of const_cast - if (_allRRV && dynamic_cast(&var2)==0) { + if (_allRRV && dynamic_cast(&var2)==nullptr) { _allRRV=false ; } @@ -735,12 +672,6 @@ bool RooAbsCollection::remove(const RooAbsCollection& list, bool /*silent*/, boo _list.erase(std::remove_if(_list.begin(), _list.end(), nameMatchAndMark), _list.end()); - std::set toBeDeleted(markedItems.begin(), markedItems.end()); - if (_ownCont) { - for (auto arg : toBeDeleted) { - delete arg; - } - } } else { auto argMatchAndMark = [&list, &markedItems](const RooAbsArg* elm) { @@ -760,6 +691,13 @@ bool RooAbsCollection::remove(const RooAbsCollection& list, bool /*silent*/, boo } } + if (matchByNameOnly && _ownCont) { + std::set toBeDeleted(markedItems.begin(), markedItems.end()); + for (auto arg : toBeDeleted) { + delete arg; + } + } + return oldSize != _list.size(); } @@ -801,7 +739,7 @@ void RooAbsCollection::setAttribAll(const Text_t* name, bool value) //////////////////////////////////////////////////////////////////////////////// /// Create a subset of the current collection, consisting only of those -/// elements with the specified attribute set. The caller is responsibe +/// elements with the specified attribute set. The caller is responsible /// for deleting the returned collection RooAbsCollection* RooAbsCollection::selectByAttrib(const char* name, bool value) const @@ -886,7 +824,7 @@ RooAbsCollection* RooAbsCollection::selectByName(const char* nameList, bool verb sel->add(*arg) ; } } - wcExpr = strtok(0,",") ; + wcExpr = strtok(nullptr,",") ; } return sel ; @@ -1007,7 +945,7 @@ double RooAbsCollection::getRealValue(const char* name, double defVal, bool verb //////////////////////////////////////////////////////////////////////////////// -/// Set value of a RooAbsRealLValye stored in set with given name to newVal +/// Set value of a RooAbsRealLValue stored in set with given name to newVal /// No error messages are printed unless the verbose flag is set bool RooAbsCollection::setRealValue(const char* name, double newVal, bool verbose) @@ -1208,7 +1146,7 @@ void RooAbsCollection::printClassName(std::ostream& os) const /// Define default RooPrinable print options for given Print() flag string /// For inline printing only show value of objects, for default print show /// name,class name value and extras of each object. In verbose mode -/// also add object adress, argument and title +/// also add object address, argument and title Int_t RooAbsCollection::defaultPrintContents(Option_t* opt) const { @@ -1344,7 +1282,7 @@ void RooAbsCollection::printLatex(const RooCmdArg& arg1, const RooCmdArg& arg2, pc.defineString("outputFile","OutputFile",0,"") ; pc.defineString("format","Format",0,"NEYVU") ; pc.defineInt("sigDigit","Format",0,1) ; - pc.defineObject("siblings","Sibling",0,0,true) ; + pc.defineObject("siblings","Sibling",0,nullptr,true) ; pc.defineInt("dummy","FormatArgs",0,0) ; pc.defineMutex("Format","FormatArgs") ; @@ -1367,7 +1305,7 @@ void RooAbsCollection::printLatex(const RooCmdArg& arg1, const RooCmdArg& arg2, if (pc.hasProcessed("FormatArgs")) { auto* formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; formatCmd->addArg(RooFit::LatexTableStyle()) ; - printLatex(ofs,pc.getInt("ncol"),0,0,pc.getObjectList("siblings"),formatCmd) ; + printLatex(ofs,pc.getInt("ncol"),nullptr,0,pc.getObjectList("siblings"),formatCmd) ; } else { printLatex(ofs,pc.getInt("ncol"),pc.getString("format"),pc.getInt("sigDigit"),pc.getObjectList("siblings")) ; } @@ -1375,7 +1313,7 @@ void RooAbsCollection::printLatex(const RooCmdArg& arg1, const RooCmdArg& arg2, if (pc.hasProcessed("FormatArgs")) { auto* formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; formatCmd->addArg(RooFit::LatexTableStyle()) ; - printLatex(std::cout,pc.getInt("ncol"),0,0,pc.getObjectList("siblings"),formatCmd) ; + printLatex(std::cout,pc.getInt("ncol"),nullptr,0,pc.getObjectList("siblings"),formatCmd) ; } else { printLatex(std::cout,pc.getInt("ncol"),pc.getString("format"),pc.getInt("sigDigit"),pc.getObjectList("siblings")) ; } @@ -1422,7 +1360,7 @@ void RooAbsCollection::printLatex(std::ostream& ofs, Int_t ncol, const char* opt RooLinkedList listListRRV ; // Make list of RRV-only components - RooArgList* prevList = 0 ; + RooArgList* prevList = nullptr ; for(auto * col : static_range_cast(listList)) { RooArgList* list = new RooArgList ; for (auto* arg : *col) { @@ -1499,7 +1437,7 @@ bool RooAbsCollection::allInRange(const char* rangeSpec) const // Parse rangeSpec specification std::vector cutVec ; if (rangeSpec && strlen(rangeSpec)>0) { - if (strchr(rangeSpec,',')==0) { + if (strchr(rangeSpec,',')==nullptr) { cutVec.push_back(rangeSpec) ; } else { const size_t bufSize = strlen(rangeSpec)+1; @@ -1508,7 +1446,7 @@ bool RooAbsCollection::allInRange(const char* rangeSpec) const const char* oneRange = strtok(buf.data(),",") ; while(oneRange) { cutVec.push_back(oneRange) ; - oneRange = strtok(0,",") ; + oneRange = strtok(nullptr,",") ; } } } @@ -1610,7 +1548,7 @@ std::unique_ptr RooAbsCollection::makeLegacy void RooAbsCollection::insert(RooAbsArg* item) { _list.push_back(item); - if (_allRRV && dynamic_cast(item)==0) { + if (_allRRV && dynamic_cast(item)==nullptr) { _allRRV= false; } diff --git a/roofit/roofitcore/src/RooAbsData.cxx b/roofit/roofitcore/src/RooAbsData.cxx index 334f8fe5a74b6..e7a328b1201bd 100644 --- a/roofit/roofitcore/src/RooAbsData.cxx +++ b/roofit/roofitcore/src/RooAbsData.cxx @@ -46,7 +46,9 @@ with this change. Usage example for a model with global observables `g1` and `g2`: ``` -auto data = model.generate(x, 1000); // data has only the single observables x +using namespace RooFit; + +std::unique_ptr data{model.generate(x, 1000)}; // data has only the single observables x data->setGlobalObservables(g1, g2); // now, data also stores a snapshot of g1 and g2 // If you fit the model to the data, the global observables and their values @@ -83,6 +85,7 @@ observable snapshots are stored in the dataset. #include "TMath.h" #include "TTree.h" +#include "RooFormula.h" #include "RooFormulaVar.h" #include "RooCmdConfig.h" #include "RooAbsRealLValue.h" @@ -93,6 +96,7 @@ observable snapshots are stored in the dataset. #include "RooVectorDataStore.h" #include "RooTreeDataStore.h" #include "RooDataHist.h" +#include "RooDataSet.h" #include "RooCompositeDataStore.h" #include "RooCategory.h" #include "RooTrace.h" @@ -107,7 +111,6 @@ observable snapshots are stored in the dataset. #include "RooHelpers.h" #include "ROOT/StringUtils.hxx" -#include "TMatrixDSym.h" #include "TPaveText.h" #include "TH1.h" #include "TH2.h" @@ -118,12 +121,7 @@ observable snapshots are stored in the dataset. #include -using namespace std; - ClassImp(RooAbsData); -; - -static std::map _dcc ; RooAbsData::StorageType RooAbsData::defaultStorageType=RooAbsData::Vector ; @@ -132,7 +130,7 @@ RooAbsData::StorageType RooAbsData::defaultStorageType=RooAbsData::Vector ; void RooAbsData::setDefaultStorageType(RooAbsData::StorageType s) { if (RooAbsData::Composite == s) { - cout << "Composite storage is not a valid *default* storage type." << endl; + std::cout << "Composite storage is not a valid *default* storage type." << std::endl; } else { defaultStorageType = s; } @@ -145,64 +143,28 @@ RooAbsData::StorageType RooAbsData::getDefaultStorageType( ) return defaultStorageType; } -//////////////////////////////////////////////////////////////////////////////// - -void RooAbsData::claimVars(RooAbsData* data) -{ - _dcc[data]++ ; - //cout << "RooAbsData(" << data << ") claim incremented to " << _dcc[data] << endl ; -} - -//////////////////////////////////////////////////////////////////////////////// -/// If return value is true variables can be deleted - -bool RooAbsData::releaseVars(RooAbsData* data) -{ - if (_dcc[data]>0) { - _dcc[data]-- ; - } - - //cout << "RooAbsData(" << data << ") claim decremented to " << _dcc[data] << endl ; - return (_dcc[data]==0) ; -} - //////////////////////////////////////////////////////////////////////////////// /// Default constructor RooAbsData::RooAbsData() { - claimVars(this) ; storageType = defaultStorageType; RooTrace::create(this) ; } -//////////////////////////////////////////////////////////////////////////////// -/// Constructor from a set of variables. Only fundamental elements of vars -/// (RooRealVar,RooCategory etc) are stored as part of the dataset - -RooAbsData::RooAbsData(RooStringView name, RooStringView title, const RooArgSet& vars, RooAbsDataStore* dstore) : - TNamed(name,title), - _vars("Dataset Variables"), - _cachedVars("Cached Variables"), - _dstore(dstore) +void RooAbsData::initializeVars(RooArgSet const& vars) { - if (dynamic_cast(dstore)) { - storageType = RooAbsData::Tree; - } else if (dynamic_cast(dstore)) { - storageType = RooAbsData::Vector; - } else { - storageType = RooAbsData::Composite; + if(!_vars.empty()) { + throw std::runtime_error("RooAbsData::initializeVars(): the variables are already initialized!"); } - // cout << "created dataset " << this << endl ; - claimVars(this); // clone the fundamentals of the given data set into internal buffer for (const auto var : vars) { if (!var->isFundamental()) { coutE(InputArguments) << "RooAbsDataStore::initialize(" << GetName() << "): Data set cannot contain non-fundamental types, ignoring " << var->GetName() - << endl; + << std::endl; throw std::invalid_argument(std::string("Only fundamental variables can be placed into datasets. This is violated for ") + var->GetName()); } else { _vars.addClone(*var); @@ -213,98 +175,92 @@ RooAbsData::RooAbsData(RooStringView name, RooStringView title, const RooArgSet& for (auto var : _vars) { var->attachArgs(_vars); } - - _namePtr = RooNameReg::instance().constPtr(GetName()) ; - - RooTrace::create(this); } //////////////////////////////////////////////////////////////////////////////// -/// Copy constructor +/// Constructor from a set of variables. Only fundamental elements of vars +/// (RooRealVar,RooCategory etc) are stored as part of the dataset -RooAbsData::RooAbsData(const RooAbsData& other, const char* newname) : - TNamed(newname ? newname : other.GetName(),other.GetTitle()), - RooPrintable(other), _vars(), +RooAbsData::RooAbsData(RooStringView name, RooStringView title, const RooArgSet& vars, RooAbsDataStore* dstore) : + TNamed(name,title), + _vars("Dataset Variables"), _cachedVars("Cached Variables"), - _namePtr(newname ? RooNameReg::instance().constPtr(newname) : other._namePtr) + _dstore(dstore) { - //cout << "created dataset " << this << endl ; - claimVars(this) ; - _vars.addClone(other._vars) ; - - // reconnect any parameterized ranges to internal dataset observables - for (auto var : _vars) { - var->attachArgs(_vars); - } - - - if (other._ownedComponents.size()>0) { + if (dynamic_cast(dstore)) { + storageType = RooAbsData::Tree; + } else if (dynamic_cast(dstore)) { + storageType = RooAbsData::Vector; + } else { + storageType = RooAbsData::Composite; + } - // copy owned components here + initializeVars(vars); - map smap ; - for (auto& itero : other._ownedComponents) { - RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); - _ownedComponents[itero.first] = dclone; - smap[itero.first] = dclone->store(); - } + _namePtr = RooNameReg::instance().constPtr(GetName()) ; - RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; - _dstore = std::make_unique(newname?newname:other.GetName(),other.GetTitle(),_vars,*idx,smap) ; - storageType = RooAbsData::Composite; + RooTrace::create(this); +} - } else { +void RooAbsData::copyImpl(const RooAbsData &other, const char *newName) +{ + _namePtr = newName ? RooNameReg::instance().constPtr(newName) : other._namePtr; - // Convert to vector store if default is vector - _dstore.reset(other._dstore->clone(_vars,newname?newname:other.GetName())); - storageType = other.storageType; - } + _vars.addClone(other._vars); - copyGlobalObservables(other); + // reconnect any parameterized ranges to internal dataset observables + for (auto var : _vars) { + var->attachArgs(_vars); + } - RooTrace::create(this) ; -} + if (!other._ownedComponents.empty()) { -RooAbsData& RooAbsData::operator=(const RooAbsData& other) { - TNamed::operator=(other); - RooPrintable::operator=(other); + // copy owned components here - claimVars(this); - _vars.Clear(); - _vars.addClone(other._vars); - _namePtr = other._namePtr; + std::map smap; + for (auto &itero : other._ownedComponents) { + RooAbsData *dclone = (RooAbsData *)itero.second->Clone(); + _ownedComponents[itero.first] = dclone; + smap[itero.first] = dclone->store(); + } - // reconnect any parameterized ranges to internal dataset observables - for (const auto var : _vars) { - var->attachDataSet(*this) ; - } + auto compStore = static_cast(other.store()); + auto idx = static_cast(_vars.find(*(const_cast(compStore)->index()))); + _dstore = std::make_unique(newName ? newName : other.GetName(), other.GetTitle(), _vars, + *idx, smap); + storageType = RooAbsData::Composite; + } else { - if (other._ownedComponents.size()>0) { + // Convert to vector store if default is vector + _dstore.reset(other._dstore->clone(_vars, newName ? newName : other.GetName())); + storageType = other.storageType; + } - // copy owned components here + copyGlobalObservables(other); +} - map smap ; - for (auto& itero : other._ownedComponents) { - RooAbsData* dclone = (RooAbsData*) itero.second->Clone(); - _ownedComponents[itero.first] = dclone; - smap[itero.first] = dclone->store(); - } +//////////////////////////////////////////////////////////////////////////////// +/// Copy constructor - RooCategory* idx = (RooCategory*) _vars.find(*((RooCompositeDataStore*)other.store())->index()) ; - _dstore = std::make_unique(GetName(), GetTitle(), _vars, *idx, smap); - storageType = RooAbsData::Composite; +RooAbsData::RooAbsData(const RooAbsData &other, const char *newName) + : TNamed{newName ? newName : other.GetName(), other.GetTitle()}, + RooPrintable{other}, + _cachedVars{"Cached Variables"} +{ + copyImpl(other, newName); - } else { + RooTrace::create(this); +} - // Convert to vector store if default is vector - _dstore.reset(other._dstore->clone(_vars)); - storageType = other.storageType; - } +RooAbsData &RooAbsData::operator=(const RooAbsData &other) +{ + TNamed::operator=(other); + RooPrintable::operator=(other); - copyGlobalObservables(other); + copyImpl(other, nullptr); - return *this; + return *this; } @@ -324,15 +280,9 @@ void RooAbsData::copyGlobalObservables(const RooAbsData& other) { RooAbsData::~RooAbsData() { - if (releaseVars(this)) { - // will cause content to be deleted subsequently in dtor - } else { - _vars.releaseOwnership() ; - } - // Delete owned dataset components - for(map::iterator iter = _ownedComponents.begin() ; iter!= _ownedComponents.end() ; ++iter) { - delete iter->second ; + for (auto& item : _ownedComponents) { + delete item.second; } RooTrace::destroy(this) ; @@ -447,19 +397,19 @@ void RooAbsData::setDirtyProp(bool flag) ///
    `Title(const char* name)` Give specified title to output dataset /// -RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, +RooFit::OwningPtr RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsData::reduce(%s)",GetName())) ; + RooCmdConfig pc("RooAbsData::reduce(" + std::string(GetName()) + ")"); pc.defineString("name","Name",0,"") ; pc.defineString("title","Title",0,"") ; pc.defineString("cutRange","CutRange",0,"") ; pc.defineString("cutSpec","CutSpec",0,"") ; - pc.defineObject("cutVar","CutVar",0,0) ; + pc.defineObject("cutVar","CutVar",0,nullptr) ; pc.defineInt("evtStart","EventRange",0,0) ; pc.defineInt("evtStop","EventRange",1,std::numeric_limits::max()) ; - pc.defineSet("varSel","SelectVars",0,0) ; + pc.defineSet("varSel","SelectVars",0,nullptr) ; pc.defineMutex("CutVar","CutSpec") ; // Process & check varargs @@ -469,14 +419,14 @@ RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const } // Extract values from named arguments - const char* cutRange = pc.getString("cutRange",0,true) ; - const char* cutSpec = pc.getString("cutSpec",0,true) ; - RooFormulaVar* cutVar = static_cast(pc.getObject("cutVar",0)) ; - Int_t nStart = pc.getInt("evtStart",0) ; - Int_t nStop = pc.getInt("evtStop",std::numeric_limits::max()) ; + const char* cutRange = pc.getString("cutRange",nullptr,true) ; + const char* cutSpec = pc.getString("cutSpec",nullptr,true) ; + RooFormulaVar* cutVar = static_cast(pc.getObject("cutVar",nullptr)) ; + int nStart = pc.getInt("evtStart",0) ; + int nStop = pc.getInt("evtStop",std::numeric_limits::max()) ; RooArgSet* varSet = pc.getSet("varSel"); - const char* name = pc.getString("name",0,true) ; - const char* title = pc.getString("title",0,true) ; + const char* name = pc.getString("name",nullptr,true) ; + const char* title = pc.getString("title",nullptr,true) ; // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset ; @@ -485,7 +435,7 @@ RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " - << arg->GetName() << " not in dataset, ignored" << endl ; + << arg->GetName() << " not in dataset, ignored" << std::endl ; varSubset.remove(*arg) ; } } @@ -493,7 +443,7 @@ RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const varSubset.add(*get()) ; } - RooAbsData* ret = nullptr; + std::unique_ptr ret; if (cutSpec) { RooFormulaVar cutVarTmp(cutSpec,cutSpec,*get()) ; @@ -511,7 +461,7 @@ RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const if (title) ret->SetTitle(title) ; ret->copyGlobalObservables(*this); - return ret ; + return RooFit::Detail::owningPtr(std::move(ret)); } //////////////////////////////////////////////////////////////////////////////// @@ -520,12 +470,12 @@ RooAbsData* RooAbsData::reduce(const RooCmdArg& arg1,const RooCmdArg& arg2,const /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. -RooAbsData* RooAbsData::reduce(const char* cut) +RooFit::OwningPtr RooAbsData::reduce(const char* cut) { RooFormulaVar cutVar(cut,cut,*get()) ; - RooAbsData* ret = reduceEng(*get(),&cutVar,0,0,std::numeric_limits::max()) ; + auto ret = reduceEng(*get(),&cutVar,nullptr,0,std::numeric_limits::max()) ; ret->copyGlobalObservables(*this); - return ret; + return RooFit::Detail::owningPtr(std::move(ret)); } //////////////////////////////////////////////////////////////////////////////// @@ -533,11 +483,11 @@ RooAbsData* RooAbsData::reduce(const char* cut) /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. -RooAbsData* RooAbsData::reduce(const RooFormulaVar& cutVar) +RooFit::OwningPtr RooAbsData::reduce(const RooFormulaVar& cutVar) { - RooAbsData* ret = reduceEng(*get(),&cutVar,0,0,std::numeric_limits::max()) ; + auto ret = reduceEng(*get(),&cutVar,nullptr,0,std::numeric_limits::max()) ; ret->copyGlobalObservables(*this); - return ret; + return RooFit::Detail::owningPtr(std::move(ret)); } //////////////////////////////////////////////////////////////////////////////// @@ -548,27 +498,27 @@ RooAbsData* RooAbsData::reduce(const RooFormulaVar& cutVar) /// other variables, such as intermediate formula objects, use the equivalent /// reduce method specifying the as a RooFormulVar reference. -RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const char* cut) +RooFit::OwningPtr RooAbsData::reduce(const RooArgSet& varSubset, const char* cut) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; for (const auto arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " - << arg->GetName() << " not in dataset, ignored" << endl ; + << arg->GetName() << " not in dataset, ignored" << std::endl ; varSubset2.remove(*arg) ; } } - RooAbsData* ret = nullptr; + std::unique_ptr ret; if (cut && strlen(cut)>0) { RooFormulaVar cutVar(cut, cut, *get(), false); - ret = reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits::max()); + ret = reduceEng(varSubset2,&cutVar,nullptr,0,std::numeric_limits::max()); } else { - ret = reduceEng(varSubset2,0,0,0,std::numeric_limits::max()); + ret = reduceEng(varSubset2,nullptr,nullptr,0,std::numeric_limits::max()); } ret->copyGlobalObservables(*this); - return ret; + return RooFit::Detail::owningPtr(std::move(ret)); } //////////////////////////////////////////////////////////////////////////////// @@ -578,21 +528,21 @@ RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const char* cut) /// The 'cutVar' formula variable is used to select the subset of data points to be /// retained in the reduced data collection. -RooAbsData* RooAbsData::reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) +RooFit::OwningPtr RooAbsData::reduce(const RooArgSet& varSubset, const RooFormulaVar& cutVar) { // Make sure varSubset doesn't contain any variable not in this dataset RooArgSet varSubset2(varSubset) ; for(RooAbsArg * arg : varSubset) { if (!_vars.find(arg->GetName())) { coutW(InputArguments) << "RooAbsData::reduce(" << GetName() << ") WARNING: variable " - << arg->GetName() << " not in dataset, ignored" << endl ; + << arg->GetName() << " not in dataset, ignored" << std::endl ; varSubset2.remove(*arg) ; } } - RooAbsData* ret = reduceEng(varSubset2,&cutVar,0,0,std::numeric_limits::max()) ; + auto ret = reduceEng(varSubset2,&cutVar,nullptr,0,std::numeric_limits::max()) ; ret->copyGlobalObservables(*this); - return ret; + return RooFit::Detail::owningPtr(std::move(ret)); } @@ -608,80 +558,6 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdA return plotOn(frame,l) ; } -//////////////////////////////////////////////////////////////////////////////// -/// Create and fill a ROOT histogram TH1,TH2 or TH3 with the values of this dataset for the variables with given names -/// The range of each observable that is histogrammed is always automatically calculated from the distribution in -/// the dataset. The number of bins can be controlled using the [xyz]bins parameters. For a greater degree of control -/// use the createHistogram() method below with named arguments -/// -/// The caller takes ownership of the returned histogram -/// -/// \deprecated This function is deprecated and will be removed in ROOT v6.30. -/// Use the overload -/// RooAbsData::createHistogram(const char*, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&) -/// that takes RooFit command arguments. - -TH1 *RooAbsData::createHistogram(const char* varNameList, Int_t xbins, Int_t ybins, Int_t zbins) const -{ - coutW(DataHandling) << "'RooAbsData::createHistogram' is deprecated and will be removed in ROOT v6.30: " - << "Use the overload of 'RooAbsData::createHistogram' that takes RooFit command arguments." - << std::endl; - - // Parse list of variable names - const auto varNames = ROOT::Split(varNameList, ",:"); - RooLinkedList argList; - RooRealVar* vars[3] = {nullptr, nullptr, nullptr}; - - for (unsigned int i = 0; i < varNames.size(); ++i) { - if (i >= 3) { - coutW(InputArguments) << "RooAbsData::createHistogram(" << GetName() << "): Can only create 3-dimensional histograms. Variable " - << i << " " << varNames[i] << " unused." << std::endl; - continue; - } - - vars[i] = static_cast( get()->find(varNames[i].data()) ); - if (!vars[i]) { - coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << ") ERROR: dataset does not contain an observable named " << varNames[i] << std::endl; - return nullptr; - } - } - - if (!vars[0]) { - coutE(InputArguments) << "RooAbsData::createHistogram(" << GetName() << "): No variable to be histogrammed in list '" << varNameList << "'" << std::endl; - return nullptr; - } - - if (xbins<=0 || !vars[0]->hasMax() || !vars[0]->hasMin() ) { - argList.Add(RooFit::AutoBinning(xbins==0?vars[0]->numBins():abs(xbins)).Clone()) ; - } else { - argList.Add(RooFit::Binning(xbins).Clone()) ; - } - - if (vars[1]) { - if (ybins<=0 || !vars[1]->hasMax() || !vars[1]->hasMin() ) { - argList.Add(RooFit::YVar(*vars[1],RooFit::AutoBinning(ybins==0?vars[1]->numBins():abs(ybins))).Clone()) ; - } else { - argList.Add(RooFit::YVar(*vars[1],RooFit::Binning(ybins)).Clone()) ; - } - } - if (vars[2]) { - if (zbins<=0 || !vars[2]->hasMax() || !vars[2]->hasMin() ) { - argList.Add(RooFit::ZVar(*vars[2],RooFit::AutoBinning(zbins==0?vars[2]->numBins():abs(zbins))).Clone()) ; - } else { - argList.Add(RooFit::ZVar(*vars[2],RooFit::Binning(zbins)).Clone()) ; - } - } - - - // Call implementation function - TH1* result = createHistogram(GetName(), *vars[0], argList); - - // Delete temporary list of RooCmdArgs - argList.Delete() ; - - return result ; -} - TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, @@ -800,11 +676,11 @@ TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, RooLinkedList argList(argListIn) ; // Define configuration for this method - RooCmdConfig pc(Form("RooAbsData::createHistogram(%s)",GetName())) ; + RooCmdConfig pc("RooAbsData::createHistogram(" + std::string(GetName()) + ")"); pc.defineString("cutRange","CutRange",0,"",true) ; pc.defineString("cutString","CutSpec",0,"") ; - pc.defineObject("yvar","YVar",0,0) ; - pc.defineObject("zvar","ZVar",0,0) ; + pc.defineObject("yvar","YVar",0,nullptr) ; + pc.defineObject("zvar","ZVar",0,nullptr) ; pc.allowUndefined() ; // Process & check varargs @@ -813,8 +689,8 @@ TH1 *RooAbsData::createHistogram(const char *name, const RooAbsRealLValue& xvar, return nullptr; } - const char* cutSpec = pc.getString("cutString",0,true) ; - const char* cutRange = pc.getString("cutRange",0,true) ; + const char* cutSpec = pc.getString("cutString",nullptr,true) ; + const char* cutRange = pc.getString("cutRange",nullptr,true) ; RooArgList vars(xvar) ; RooAbsArg* yvar = static_cast(pc.getObject("yvar")) ; @@ -882,18 +758,17 @@ Roo1DTable* RooAbsData::table(const RooArgSet& catSet, const char* cuts, const c { RooArgSet catSet2 ; - string prodName("(") ; + std::string prodName("(") ; for(auto * arg : catSet) { if (dynamic_cast(arg)) { - RooAbsCategory* varsArg = dynamic_cast(_vars.find(arg->GetName())) ; - if (varsArg != 0) catSet2.add(*varsArg) ; + if (auto varsArg = dynamic_cast(_vars.find(arg->GetName()))) catSet2.add(*varsArg) ; else catSet2.add(*arg) ; if (prodName.length()>1) { prodName += " x " ; } prodName += arg->GetName() ; } else { - coutW(InputArguments) << "RooAbsData::table(" << GetName() << ") non-RooAbsCategory input argument " << arg->GetName() << " ignored" << endl ; + coutW(InputArguments) << "RooAbsData::table(" << GetName() << ") non-RooAbsCategory input argument " << arg->GetName() << " ignored" << std::endl ; } } prodName += ")" ; @@ -905,7 +780,7 @@ Roo1DTable* RooAbsData::table(const RooArgSet& catSet, const char* cuts, const c //////////////////////////////////////////////////////////////////////////////// /// Print name of dataset -void RooAbsData::printName(ostream& os) const +void RooAbsData::printName(std::ostream& os) const { os << GetName() ; } @@ -913,7 +788,7 @@ void RooAbsData::printName(ostream& os) const //////////////////////////////////////////////////////////////////////////////// /// Print title of dataset -void RooAbsData::printTitle(ostream& os) const +void RooAbsData::printTitle(std::ostream& os) const { os << GetTitle() ; } @@ -921,14 +796,14 @@ void RooAbsData::printTitle(ostream& os) const //////////////////////////////////////////////////////////////////////////////// /// Print class name of dataset -void RooAbsData::printClassName(ostream& os) const +void RooAbsData::printClassName(std::ostream& os) const { os << ClassName() ; } //////////////////////////////////////////////////////////////////////////////// -void RooAbsData::printMultiline(ostream& os, Int_t contents, bool verbose, TString indent) const +void RooAbsData::printMultiline(std::ostream& os, Int_t contents, bool verbose, TString indent) const { _dstore->printMultiline(os,contents,verbose,indent) ; } @@ -994,26 +869,26 @@ double RooAbsData::moment(const RooRealVar& var, double order, double offset, co auto varPtr = dynamic_cast(arg); // Check if found variable is of type RooRealVar if (!varPtr) { - coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; + coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << std::endl ; return 0; } // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { - coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") WARNING: empty dataset" << endl ; + coutE(InputArguments) << "RooDataSet::moment(" << GetName() << ") WARNING: empty dataset" << std::endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present std::unique_ptr select; if (cutSpec) { - select.reset(new RooFormula("select",cutSpec,*get())); + select = std::make_unique("select",cutSpec,*get()); } // Calculate requested moment ROOT::Math::KahanSum sum; - for(Int_t index= 0; index < numEntries(); index++) { + for(int index= 0; index < numEntries(); index++) { const RooArgSet* vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; @@ -1021,7 +896,7 @@ double RooAbsData::moment(const RooRealVar& var, double order, double offset, co sum += weight() * TMath::Power(varPtr->getVal() - offset,order); } - return sum/sumEntries(cutSpec, cutRange); + return sum.Sum()/sumEntries(cutSpec, cutRange); } //////////////////////////////////////////////////////////////////////////////// @@ -1032,12 +907,12 @@ RooRealVar* RooAbsData::dataRealVar(const char* methodname, const RooRealVar& ex // Lookup variable in dataset RooRealVar *xdata = (RooRealVar*) _vars.find(extVar.GetName()); if(!xdata) { - coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not in data" << endl ; + coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not in data" << std::endl ; return nullptr; } // Check if found variable is of type RooRealVar if (!dynamic_cast(xdata)) { - coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not of type RooRealVar in data" << endl ; + coutE(InputArguments) << "RooDataSet::" << methodname << "(" << GetName() << ") ERROR: variable : " << extVar.GetName() << " is not of type RooRealVar in data" << std::endl ; return nullptr; } return xdata; @@ -1055,17 +930,18 @@ double RooAbsData::corrcov(const RooRealVar &x, const RooRealVar &y, const char* // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { - coutW(InputArguments) << "RooDataSet::" << (corr?"correlation":"covariance") << "(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; + coutW(InputArguments) << "RooDataSet::" << (corr?"correlation":"covariance") << "(" << GetName() << ") WARNING: empty dataset, returning zero" << std::endl ; return 0; } // Setup RooFormulaVar for cutSpec if it is present - RooFormula* select = cutSpec ? new RooFormula("select",cutSpec,*get()) : 0 ; + std::unique_ptr select; + if (cutSpec) select = std::make_unique("select",cutSpec,*get()); // Calculate requested moment double xysum(0),xsum(0),ysum(0),x2sum(0),y2sum(0); const RooArgSet* vars ; - for(Int_t index= 0; index < numEntries(); index++) { + for(int index= 0; index < numEntries(); index++) { vars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && vars->allInRange(cutRange)) continue ; @@ -1088,9 +964,6 @@ double RooAbsData::corrcov(const RooRealVar &x, const RooRealVar &y, const char* y2sum/=sumEntries(cutSpec, cutRange) ; } - // Cleanup - if (select) delete select ; - // Return covariance or correlation as requested if (corr) { return (xysum-xsum*ysum)/(sqrt(x2sum-(xsum*xsum))*sqrt(y2sum-(ysum*ysum))) ; @@ -1102,7 +975,7 @@ double RooAbsData::corrcov(const RooRealVar &x, const RooRealVar &y, const char* //////////////////////////////////////////////////////////////////////////////// /// Return covariance matrix from data for given list of observables -TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, bool corr) const +RooFit::OwningPtr RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSpec, const char* cutRange, bool corr) const { RooArgList varList ; for(auto * var : static_range_cast(vars)) { @@ -1116,7 +989,7 @@ TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSp // Check if dataset is not empty if(sumEntries(cutSpec, cutRange) == 0.) { - coutW(InputArguments) << "RooDataSet::covariance(" << GetName() << ") WARNING: empty dataset, returning zero" << endl ; + coutW(InputArguments) << "RooDataSet::covariance(" << GetName() << ") WARNING: empty dataset, returning zero" << std::endl ; return nullptr; } @@ -1128,7 +1001,7 @@ TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSp std::vector x2sum(varList.size()) ; // Calculate and - for(Int_t index= 0; index < numEntries(); index++) { + for(int index= 0; index < numEntries(); index++) { const RooArgSet* dvars = get(index) ; if (select && select->eval()==0) continue ; if (cutRange && dvars->allInRange(cutRange)) continue ; @@ -1161,7 +1034,7 @@ TMatrixDSym* RooAbsData::corrcovMatrix(const RooArgList& vars, const char* cutSp } // Calculate covariance matrix - TMatrixDSym* C = new TMatrixDSym(varList.size()) ; + auto C = std::make_unique(varList.size()) ; for (std::size_t ix=0 ; ix(&arg7)) ; cmdList.Add(const_cast(&arg8)) ; // Select the pdf-specific commands - RooCmdConfig pc(Form("RooTreeData::statOn(%s)",GetName())) ; + RooCmdConfig pc("RooTreeData::statOn(" + std::string(GetName()) + ")"); pc.defineString("what","What",0,"MNR") ; pc.defineString("label","Label",0,"") ; pc.defineDouble("xmin","Layout",0,0.65) ; pc.defineDouble("xmax","Layout",1,0.99) ; - pc.defineInt("ymaxi","Layout",0,Int_t(0.95*10000)) ; + pc.defineInt("ymaxi","Layout",0,int(0.95*10000)) ; pc.defineString("formatStr","Format",0,"NELU") ; pc.defineInt("sigDigit","Format",0,2) ; pc.defineInt("dummy","FormatArgs",0,0) ; @@ -1307,15 +1180,15 @@ RooPlot* RooAbsData::statOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdA double xmax = pc.getDouble("xmax") ; double ymax = pc.getInt("ymaxi") / 10000. ; const char* formatStr = pc.getString("formatStr") ; - Int_t sigDigit = pc.getInt("sigDigit") ; + int sigDigit = pc.getInt("sigDigit") ; const char* what = pc.getString("what") ; - const char* cutSpec = pc.getString("cutString",0,true) ; - const char* cutRange = pc.getString("cutRange",0,true) ; + const char* cutSpec = pc.getString("cutString",nullptr,true) ; + const char* cutRange = pc.getString("cutRange",nullptr,true) ; if (pc.hasProcessed("FormatArgs")) { RooCmdArg* formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; - return statOn(frame,what,label,0,0,xmin,xmax,ymax,cutSpec,cutRange,formatCmd) ; + return statOn(frame,what,label,0,nullptr,xmin,xmax,ymax,cutSpec,cutRange,formatCmd) ; } else { return statOn(frame,what,label,sigDigit,formatStr,xmin,xmax,ymax,cutSpec,cutRange) ; } @@ -1335,7 +1208,7 @@ RooPlot* RooAbsData::statOn(RooPlot* frame, const char* what, const char *label, bool showN = whatStr.find('N') != std::string::npos; bool showR = whatStr.find('R') != std::string::npos; bool showM = whatStr.find('M') != std::string::npos; - Int_t nPar= 0; + int nPar= 0; if (showN) nPar++ ; if (showR) nPar++ ; if (showM) nPar++ ; @@ -1392,14 +1265,14 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char { // Do we have a valid histogram to use? if(nullptr == hist) { - coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << endl; + coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << std::endl; return nullptr; } // Check that the number of plotVars matches the input histogram's dimension std::size_t hdim= hist->GetDimension(); if(hdim != plotVars.size()) { - coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << endl; + coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << std::endl; return nullptr; } @@ -1410,18 +1283,18 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char for(std::size_t index= 0; index < plotVars.size(); index++) { const RooAbsArg *var= plotVars.at(index); const RooAbsReal *realVar= dynamic_cast(var); - if(0 == realVar) { + if(realVar == nullptr) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot plot variable \"" << var->GetName() - << "\" of type " << var->ClassName() << endl; + << "\" of type " << var->ClassName() << std::endl; return nullptr; } RooAbsArg *found= _vars.find(realVar->GetName()); if(!found) { RooAbsArg *clone= plotClones.addClone(*realVar,true); // do not complain about duplicates - assert(0 != clone); + assert(nullptr != clone); if(!clone->dependsOn(_vars)) { coutE(InputArguments) << ClassName() << "::" << GetName() - << ":fillHistogram: Data does not contain the variable '" << realVar->GetName() << "'." << endl; + << ":fillHistogram: Data does not contain the variable '" << realVar->GetName() << "'." << std::endl; return nullptr; } else { @@ -1439,31 +1312,31 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char if (cuts != nullptr && strlen(cuts) > 0) { select = std::make_unique(cuts, cuts, _vars, false); if (!select || !select->ok()) { - coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: invalid cuts \"" << cuts << "\"" << endl; + coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: invalid cuts \"" << cuts << "\"" << std::endl; return nullptr; } } // Lookup each of the variables we are binning in our tree variables - const RooAbsReal *xvar = 0; - const RooAbsReal *yvar = 0; - const RooAbsReal *zvar = 0; + const RooAbsReal *xvar = nullptr; + const RooAbsReal *yvar = nullptr; + const RooAbsReal *zvar = nullptr; switch(hdim) { case 3: zvar= dynamic_cast(localVars.find(plotVars.at(2)->GetName())); - assert(0 != zvar); + assert(nullptr != zvar); // fall through to next case... case 2: yvar= dynamic_cast(localVars.find(plotVars.at(1)->GetName())); - assert(0 != yvar); + assert(nullptr != yvar); // fall through to next case... case 1: xvar= dynamic_cast(localVars.find(plotVars.at(0)->GetName())); - assert(0 != xvar); + assert(nullptr != xvar); break; default: coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot fill histogram with " - << hdim << " dimensions" << endl; + << hdim << " dimensions" << std::endl; break; } @@ -1474,10 +1347,10 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char if (hist->GetSumw2()->fN==0) { hist->Sumw2() ; } - Int_t nevent= numEntries() ; //(Int_t)_tree->GetEntries(); - for(Int_t i=0; i < nevent; ++i) { + int nevent= numEntries() ; //(int)_tree->GetEntries(); + for(int i=0; i < nevent; ++i) { - //Int_t entryNumber= _tree->GetEntryNumber(i); + //int entryNumber= _tree->GetEntryNumber(i); //if (entryNumber<0) break; get(i); @@ -1510,7 +1383,7 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char continue ; } - Int_t bin(0); + int bin(0); switch(hdim) { case 1: bin= hist->FindBin(xvar->getVal()); @@ -1547,7 +1420,7 @@ TH1 *RooAbsData::fillHistogram(TH1 *hist, const RooArgList &plotVars, const char //hist->AddBinContent(bin,weight()); hist->SetBinError(bin,sqrt(error2)) ; - //cout << "RooTreeData::fillHistogram() bin = " << bin << " weight() = " << weight() << " we = " << we << endl ; + //cout << "RooTreeData::fillHistogram() bin = " << bin << " weight() = " << weight() << " we = " << we << std::endl ; } @@ -1602,112 +1475,139 @@ SplittingSetup initSplit(RooAbsData const &data, RooAbsCategory const &splitCat) // Add weight variable explicitly if dataset has weights, but no top-level weight // variable exists (can happen with composite datastores) - if (data.isWeighted() && !data.IsA()->InheritsFrom(RooDataHist::Class())) { - auto newweight = std::make_unique("weight", "weight", -1e9, 1e9); - setup.subsetVars.add(*newweight); - setup.addWeightVar = true; - setup.ownedSet.addOwned(std::move(newweight)); - } + setup.addWeightVar = data.isWeighted(); return setup; } -TList *splitImpl(RooAbsData const &data, const RooAbsCategory &cloneCat, bool createEmptyDataSets, - std::function createEmptyData) +RooFit::OwningPtr splitImpl(RooAbsData const &data, const RooAbsCategory &cloneCat, bool createEmptyDataSets, + std::function(const char *label)> createEmptyData) { - auto dsetList = new TList; + auto dsetList = std::make_unique(); // If createEmptyDataSets is true, prepopulate with empty sets corresponding to all states if (createEmptyDataSets) { for (const auto &nameIdx : cloneCat) { - RooAbsData *subset = createEmptyData(nameIdx.first.c_str()); - dsetList->Add((RooAbsArg *)subset); + dsetList->Add(createEmptyData(nameIdx.first.c_str()).release()); } } + bool isDataHist = dynamic_cast(&data); + // Loop over dataset and copy event to matching subset - const bool propWeightSquared = data.isWeighted(); - for (Int_t i = 0; i < data.numEntries(); ++i) { + for (int i = 0; i < data.numEntries(); ++i) { const RooArgSet *row = data.get(i); - RooAbsData *subset = (RooAbsData *)dsetList->FindObject(cloneCat.getCurrentLabel()); + auto subset = static_cast(dsetList->FindObject(cloneCat.getCurrentLabel())); if (!subset) { - subset = createEmptyData(cloneCat.getCurrentLabel()); - dsetList->Add((RooAbsArg *)subset); + subset = createEmptyData(cloneCat.getCurrentLabel()).release(); + dsetList->Add(subset); + } + + // For datasets with weight errors or sumW2, the interface to fill + // RooDataHist and RooDataSet is not the same. + if (isDataHist) { + static_cast(subset)->add(*row, data.weight(), data.weightSquared()); + } else { + static_cast(subset)->add(*row, data.weight(), data.weightError()); } - subset->add(*row, data.weight(), propWeightSquared ? data.weightSquared() : 0.0); } - return dsetList; + return RooFit::Detail::owningPtr(std::move(dsetList)); } } // namespace -//////////////////////////////////////////////////////////////////////////////// -/// Split dataset into subsets based on states of given splitCat in this dataset. -/// A TList of RooDataSets is returned in which each RooDataSet is named -/// after the state name of splitCat of which it contains the dataset subset. -/// The observables splitCat itself is no longer present in the sub datasets. -/// If createEmptyDataSets is false (default) this method only creates datasets for states -/// which have at least one entry The caller takes ownership of the returned list and its contents - -TList* RooAbsData::split(const RooAbsCategory& splitCat, bool createEmptyDataSets) const -{ - SplittingSetup setup = initSplit(*this, splitCat); - - // Something went wrong - if(!setup.cloneCat) return nullptr; +/** + * \brief Split the dataset into subsets based on states of a categorical variable in this dataset. + * + * Returns a list of sub-datasets, which each dataset named after a given state + * name in the `splitCat`. The observables `splitCat` itself is no longer present + * in the sub-datasets. + * + * \note If you mean to split a dataset into sub-datasets that correspond to + * the individual channels of a RooSimultaneous, it is better to use + * RooAbsData::split(const RooSimultaneous &, bool), because then the + * sub-datasets only contain variables that the pdf for the corresponding + * channel depends on. This is much faster in case of many channels, and the + * resulting sub-datasets don't waste memory for unused columns. + * + * \param splitCat The categorical variable used for splitting the dataset. + * \param createEmptyDataSets Flag indicating whether to create empty datasets + * for missing categories (`false` by default). + * + * \return An owning pointer to a TList of subsets of the dataset. + * Returns `nullptr` if an error occurs. + */ + +RooFit::OwningPtr RooAbsData::split(const RooAbsCategory &splitCat, bool createEmptyDataSets) const +{ + SplittingSetup setup = initSplit(*this, splitCat); + + // Something went wrong + if (!setup.cloneCat) + return nullptr; - auto createEmptyData = [&](const char * label) -> RooAbsData* { - return emptyClone(label, label, &setup.subsetVars, setup.addWeightVar ? "weight" : nullptr); - }; + auto createEmptyData = [&](const char *label) -> std::unique_ptr { + return std::unique_ptr{ + emptyClone(label, label, &setup.subsetVars, setup.addWeightVar ? "weight" : nullptr)}; + }; - return splitImpl(*this, *setup.cloneCat, createEmptyDataSets, createEmptyData); + return splitImpl(*this, *setup.cloneCat, createEmptyDataSets, createEmptyData); } -//////////////////////////////////////////////////////////////////////////////// -/// Split dataset into subsets based on the categorisation of the RooSimultaneous -/// A TList of RooDataSets is returned in which each RooDataSet is named -/// after the state name of splitCat of which it contains the dataset subset. -/// The observables splitCat itself is no longer present in the sub datasets, as well as the -/// observables of the other categories. -/// If createEmptyDataSets is false (default) this method only creates datasets for states -/// which have at least one entry The caller takes ownership of the returned list and its contents - -TList* RooAbsData::split(const RooSimultaneous& simpdf, bool createEmptyDataSets) const -{ - auto& splitCat = const_cast(simpdf.indexCat()); - - SplittingSetup setup = initSplit(*this, splitCat); - - // Something went wrong - if(!setup.cloneCat) return nullptr; +/** + * \brief Split the dataset into subsets based on the channels of a RooSimultaneous. + * + * Returns a list of sub-datasets, which each dataset named after the + * applicable state name of the RooSimultaneous index category. The index + * category itself is no longer present in the sub-datasets. The sub-datasets + * only contain variables that the pdf for the corresponding channel depends + * on. + * + * \param simPdf The simultaneous pdf used for splitting the dataset. + * \param createEmptyDataSets Flag indicating whether to create empty datasets + * for missing categories (`false` by default). + * + * \return An owning pointer to a TList of subsets of the dataset. + * Returns `nullptr` if an error occurs. + */ +RooFit::OwningPtr RooAbsData::split(const RooSimultaneous &simPdf, bool createEmptyDataSets) const +{ + auto &splitCat = const_cast(simPdf.indexCat()); + + SplittingSetup setup = initSplit(*this, splitCat); + + // Something went wrong + if (!setup.cloneCat) + return nullptr; - // Get the observables for a given pdf in the RooSimultaneous, or an empty - // RooArgSet if no pdf is set - auto getPdfObservables = [this, &simpdf](const char * label) { - RooArgSet obsSet; - if(RooAbsPdf* catPdf = simpdf.getPdf(label)) { - catPdf->getObservables(this->get(), obsSet); - } - return obsSet; - }; + // Get the observables for a given pdf in the RooSimultaneous, or an empty + // RooArgSet if no pdf is set + auto getPdfObservables = [this, &simPdf](const char *label) { + RooArgSet obsSet; + if (RooAbsPdf *catPdf = simPdf.getPdf(label)) { + catPdf->getObservables(this->get(), obsSet); + } + return obsSet; + }; - // By default, remove all category observables from the subdatasets - RooArgSet allObservables; - for( const auto& catPair : splitCat) { - allObservables.add(getPdfObservables(catPair.first.c_str())); - } - setup.subsetVars.remove(allObservables, true, true); + // By default, remove all category observables from the subdatasets + RooArgSet allObservables; + for (const auto &catPair : splitCat) { + allObservables.add(getPdfObservables(catPair.first.c_str())); + } + setup.subsetVars.remove(allObservables, true, true); - auto createEmptyData = [&](const char * label) -> RooAbsData* { - // Add in the subset only the observables corresponding to this category - RooArgSet subsetVarsCat(setup.subsetVars); - subsetVarsCat.add(getPdfObservables(label)); - return this->emptyClone(label, label, &subsetVarsCat, setup.addWeightVar ? "weight" : nullptr); - }; + auto createEmptyData = [&](const char *label) -> std::unique_ptr { + // Add in the subset only the observables corresponding to this category + RooArgSet subsetVarsCat(setup.subsetVars); + subsetVarsCat.add(getPdfObservables(label)); + return std::unique_ptr{ + this->emptyClone(label, label, &subsetVarsCat, setup.addWeightVar ? "weight" : nullptr)}; + }; - return splitImpl(*this, *setup.cloneCat, createEmptyDataSets, createEmptyData); + return splitImpl(*this, *setup.cloneCat, createEmptyDataSets, createEmptyData); } //////////////////////////////////////////////////////////////////////////////// @@ -1805,7 +1705,7 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const // New experimental plotOn() with varargs... // Define configuration for this method - RooCmdConfig pc(Form("RooAbsData::plotOn(%s)",GetName())) ; + RooCmdConfig pc("RooAbsData::plotOn(" + std::string(GetName()) + ")"); pc.defineString("drawOption","DrawOption",0,"P") ; pc.defineString("cutRange","CutRange",0,"",true) ; pc.defineString("cutString","CutSpec",0,"") ; @@ -1826,7 +1726,7 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const pc.defineDouble("markerSize","MarkerSize",0,-999) ; pc.defineInt("fillColor","FillColor",0,-999) ; pc.defineInt("fillStyle","FillStyle",0,-999) ; - pc.defineInt("errorType","DataError",0,(Int_t)RooAbsData::Auto) ; + pc.defineInt("errorType","DataError",0,(int)RooAbsData::Auto) ; pc.defineInt("histInvisible","Invisible",0,0) ; pc.defineInt("refreshFrameNorm","RefreshNorm",0,1) ; pc.defineString("addToHistName","AddTo",0,"") ; @@ -1863,9 +1763,9 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const o.etype = (RooAbsData::ErrorType) pc.getInt("errorType") ; o.histInvisible = pc.getInt("histInvisible") ; o.xErrorSize = pc.getDouble("xErrorSize") ; - o.cutRange = pc.getString("cutRange",0,true) ; - o.histName = pc.getString("histName",0,true) ; - o.addToHistName = pc.getString("addToHistName",0,true) ; + o.cutRange = pc.getString("cutRange",nullptr,true) ; + o.histName = pc.getString("histName",nullptr,true) ; + o.addToHistName = pc.getString("addToHistName",nullptr,true) ; o.addToWgtSelf = pc.getDouble("addToWgtSelf") ; o.addToWgtOther = pc.getDouble("addToWgtOther") ; o.refreshFrameNorm = pc.getInt("refreshFrameNorm") ; @@ -1876,13 +1776,13 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const o.etype = isNonPoissonWeighted() ? SumW2 : Poisson ; if (o.etype == SumW2) { coutI(InputArguments) << "RooAbsData::plotOn(" << GetName() - << ") INFO: dataset has non-integer weights, auto-selecting SumW2 errors instead of Poisson errors" << endl ; + << ") INFO: dataset has non-integer weights, auto-selecting SumW2 errors instead of Poisson errors" << std::endl ; } } if (o.addToHistName && !frame->findObject(o.addToHistName,RooHist::Class())) { coutE(InputArguments) << "RooAbsData::plotOn(" << GetName() << ") cannot find existing histogram " << o.addToHistName - << " to add to in RooPlot" << endl ; + << " to add to in RooPlot" << std::endl ; return frame ; } @@ -1895,14 +1795,14 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const ret = plotEffOn(frame,*effCat,o) ; } - Int_t lineColor = pc.getInt("lineColor") ; - Int_t lineStyle = pc.getInt("lineStyle") ; - Int_t lineWidth = pc.getInt("lineWidth") ; - Int_t markerColor = pc.getInt("markerColor") ; - Int_t markerStyle = pc.getInt("markerStyle") ; + int lineColor = pc.getInt("lineColor") ; + int lineStyle = pc.getInt("lineStyle") ; + int lineWidth = pc.getInt("lineWidth") ; + int markerColor = pc.getInt("markerColor") ; + int markerStyle = pc.getInt("markerStyle") ; Size_t markerSize = pc.getDouble("markerSize") ; - Int_t fillColor = pc.getInt("fillColor") ; - Int_t fillStyle = pc.getInt("fillStyle") ; + int fillColor = pc.getInt("fillColor") ; + int fillStyle = pc.getInt("fillStyle") ; if (lineColor!=-999) ret->getAttLine()->SetLineColor(lineColor) ; if (lineStyle!=-999) ret->getAttLine()->SetLineStyle(lineStyle) ; if (lineWidth!=-999) ret->getAttLine()->SetLineWidth(lineWidth) ; @@ -1933,14 +1833,14 @@ RooPlot* RooAbsData::plotOn(RooPlot* frame, const RooLinkedList& argList) const /// \see RooAbsData::plotOn(RooPlot*,const RooLinkedList&) const RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const { - if(0 == frame) { - coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << endl; + if(nullptr == frame) { + coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << std::endl; return nullptr; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); - if(0 == var) { + if(nullptr == var) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotOn: frame does not specify a plot variable" << endl; + << ":plotOn: frame does not specify a plot variable" << std::endl; return nullptr; } @@ -1960,9 +1860,9 @@ RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const // Keep track of sum-of-weights error hist->Sumw2() ; - if(0 == fillHistogram(hist.get(), RooArgList(*var),o.cuts,o.cutRange)) { + if(nullptr == fillHistogram(hist.get(), RooArgList(*var),o.cuts,o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotOn: fillHistogram() failed" << endl; + << ":plotOn: fillHistogram() failed" << std::endl; return nullptr; } @@ -1977,9 +1877,9 @@ RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const // convert this histogram to a RooHist object on the heap RooHist *graph= new RooHist(*hist,nomBinWidth,1,o.etype,o.xErrorSize,o.correctForBinWidth,o.scaleFactor); - if(0 == graph) { + if(nullptr == graph) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotOn: unable to create a RooHist object" << endl; + << ":plotOn: unable to create a RooHist object" << std::endl; return nullptr; } @@ -1994,7 +1894,7 @@ RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const // Store the number of entries before the cut, if any was made if ((o.cuts && strlen(o.cuts)) || o.cutRange) { - coutI(Plotting) << "RooTreeData::plotOn: plotting " << hist->GetSumOfWeights() << " events out of " << nEnt << " total events" << endl ; + coutI(Plotting) << "RooTreeData::plotOn: plotting " << hist->GetSumOfWeights() << " events out of " << nEnt << " total events" << std::endl ; graph->setRawEntries(nEnt) ; } @@ -2003,7 +1903,7 @@ RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const RooHist* otherGraph = static_cast(frame->findObject(o.addToHistName,RooHist::Class())) ; if (!graph->hasIdenticalBinning(*otherGraph)) { - coutE(Plotting) << "RooTreeData::plotOn: ERROR Histogram to be added to, '" << o.addToHistName << "',has different binning" << endl ; + coutE(Plotting) << "RooTreeData::plotOn: ERROR Histogram to be added to, '" << o.addToHistName << "',has different binning" << std::endl ; delete graph ; return frame ; } @@ -2053,14 +1953,14 @@ RooPlot *RooAbsData::plotOn(RooPlot *frame, PlotOpt o) const RooPlot* RooAbsData::plotAsymOn(RooPlot* frame, const RooAbsCategoryLValue& asymCat, PlotOpt o) const { - if(0 == frame) { - coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame is null" << endl; + if(nullptr == frame) { + coutE(Plotting) << ClassName() << "::" << GetName() << ":plotAsymOn: frame is null" << std::endl; return nullptr; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); - if(0 == var) { + if(nullptr == var) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotAsymOn: frame does not specify a plot variable" << endl; + << ":plotAsymOn: frame does not specify a plot variable" << std::endl; return nullptr; } @@ -2096,7 +1996,7 @@ RooPlot* RooAbsData::plotAsymOn(RooPlot* frame, const RooAbsCategoryLValue& asym if(! fillHistogram(hist1.get(), RooArgList(*var),cuts1.c_str(),o.cutRange) || ! fillHistogram(hist2.get(), RooArgList(*var),cuts2.c_str(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotAsymOn: createHistogram() failed" << endl; + << ":plotAsymOn: createHistogram() failed" << std::endl; return nullptr; } @@ -2143,14 +2043,14 @@ RooPlot* RooAbsData::plotAsymOn(RooPlot* frame, const RooAbsCategoryLValue& asym RooPlot* RooAbsData::plotEffOn(RooPlot* frame, const RooAbsCategoryLValue& effCat, PlotOpt o) const { - if(0 == frame) { - coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame is null" << endl; + if(nullptr == frame) { + coutE(Plotting) << ClassName() << "::" << GetName() << ":plotEffOn: frame is null" << std::endl; return nullptr; } RooAbsRealLValue *var= (RooAbsRealLValue*) frame->getPlotVar(); - if(0 == var) { + if(nullptr == var) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotEffOn: frame does not specify a plot variable" << endl; + << ":plotEffOn: frame does not specify a plot variable" << std::endl; return nullptr; } @@ -2186,7 +2086,7 @@ RooPlot* RooAbsData::plotEffOn(RooPlot* frame, const RooAbsCategoryLValue& effCa if(! fillHistogram(hist1.get(), RooArgList(*var),cuts1.c_str(),o.cutRange) || ! fillHistogram(hist2.get(), RooArgList(*var),cuts2.c_str(),o.cutRange)) { coutE(Plotting) << ClassName() << "::" << GetName() - << ":plotEffOn: createHistogram() failed" << endl; + << ":plotEffOn: createHistogram() failed" << std::endl; return nullptr; } @@ -2234,13 +2134,13 @@ Roo1DTable* RooAbsData::table(const RooAbsCategory& cat, const char* cuts, const if (!tableVar) { if (!cat.dependsOn(_vars)) { coutE(Plotting) << "RooTreeData::Table(" << GetName() << "): Argument " << cat.GetName() - << " is not in dataset and is also not dependent on data set" << endl ; + << " is not in dataset and is also not dependent on data set" << std::endl ; return nullptr; } // Clone derived variable - tableSet.reset(static_cast(RooArgSet(cat).snapshot(true))); - if (!tableSet) { + tableSet = std::make_unique(); + if (RooArgSet(cat).snapshot(*tableSet, true)) { coutE(Plotting) << "RooTreeData::table(" << GetName() << ") Couldn't deep-clone table category, abort." << std::endl; return nullptr; } @@ -2262,8 +2162,8 @@ Roo1DTable* RooAbsData::table(const RooAbsCategory& cat, const char* cuts, const Roo1DTable* table2 = tableVar->createTable(tableName.c_str()); // Dump contents - Int_t nevent= numEntries() ; - for(Int_t i=0; i < nevent; ++i) { + int nevent= numEntries() ; + for(int i=0; i < nevent; ++i) { get(i); if (cutVar && cutVar->getVal()==0) continue ; @@ -2284,27 +2184,27 @@ bool RooAbsData::getRange(const RooAbsRealLValue& var, double& lowest, double& h // Lookup variable in dataset const auto arg = _vars.find(var.GetName()); if (!arg) { - coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << endl ; + coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: unknown variable: " << var.GetName() << std::endl ; return true; } auto varPtr = dynamic_cast(arg); // Check if found variable is of type RooRealVar if (!varPtr) { - coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << endl ; + coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") ERROR: variable " << var.GetName() << " is not of type RooRealVar" << std::endl ; return true; } // Check if dataset is not empty if(sumEntries() == 0.) { - coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") WARNING: empty dataset" << endl ; + coutE(InputArguments) << "RooDataSet::getRange(" << GetName() << ") WARNING: empty dataset" << std::endl ; return true; } // Look for highest and lowest value lowest = RooNumber::infinity() ; highest = -RooNumber::infinity() ; - for (Int_t i=0 ; igetVal()getVal() ; @@ -2372,10 +2272,10 @@ void RooAbsData::optimizeReadingWithCaching(RooAbsArg& arg, const RooArgSet& cac RooAbsReal* loFunc = rrv->getBinning().lowBoundFunc() ; RooAbsReal* hiFunc = rrv->getBinning().highBoundFunc() ; if (loFunc) { - loFunc->leafNodeServerList(&depObs,0,true) ; + loFunc->leafNodeServerList(&depObs,nullptr,true) ; } if (hiFunc) { - hiFunc->leafNodeServerList(&depObs,0,true) ; + hiFunc->leafNodeServerList(&depObs,nullptr,true) ; } if (!depObs.empty()) { pruneSet.remove(depObs,true,true) ; @@ -2392,7 +2292,7 @@ void RooAbsData::optimizeReadingWithCaching(RooAbsArg& arg, const RooArgSet& cac // Deactivate tree branches here cxcoutI(Optimization) << "RooTreeData::optimizeReadingForTestStatistic(" << GetName() << "): Observables " << pruneSet - << " in dataset are either not used at all, orserving exclusively p.d.f nodes that are now cached, disabling reading of these observables for TTree" << endl ; + << " in dataset are either not used at all, orserving exclusively p.d.f nodes that are now cached, disabling reading of these observables for TTree" << std::endl ; setArgStatus(pruneSet,false) ; } } @@ -2504,7 +2404,7 @@ const TTree *RooAbsData::tree() const return _dstore->tree(); } else { coutW(InputArguments) << "RooAbsData::tree(" << GetName() << ") WARNING: is not of StorageType::Tree. " - << "Use GetClonedTree() instead or convert to tree storage." << endl; + << "Use GetClonedTree() instead or convert to tree storage." << std::endl; return nullptr; } } @@ -2574,7 +2474,7 @@ void RooAbsData::SetName(const char* name) TNamed::SetName(name) ; auto newPtr = RooNameReg::instance().constPtr(GetName()) ; if (newPtr != _namePtr) { - //cout << "Rename '" << _namePtr->GetName() << "' to '" << name << "' (set flag in new name)" << endl; + //cout << "Rename '" << _namePtr->GetName() << "' to '" << name << "' (set flag in new name)" << std::endl; _namePtr = newPtr; const_cast(_namePtr)->SetBit(RooNameReg::kRenamedArg); RooNameReg::incrementRenameCounter(); @@ -2598,7 +2498,7 @@ void RooAbsData::SetNameTitle(const char *name, const char *title) /// Return sum of squared weights of this data. double RooAbsData::sumEntriesW2() const { - const RooSpan eventWeights = getWeightBatch(0, numEntries(), /*sumW2=*/true); + const std::span eventWeights = getWeightBatch(0, numEntries(), /*sumW2=*/true); if (eventWeights.empty()) { return numEntries() * weightSquared(); } @@ -2697,7 +2597,7 @@ TH2F *RooAbsData::createHistogram(const RooAbsRealLValue &var1, const RooAbsReal // Create selection formula if selection cuts are specified std::unique_ptr select; - if (0 != cuts && strlen(cuts)) { + if (nullptr != cuts && strlen(cuts)) { select = std::make_unique(cuts, cuts, _vars); if (!select->ok()) { return nullptr; @@ -2710,13 +2610,13 @@ TH2F *RooAbsData::createHistogram(const RooAbsRealLValue &var1, const RooAbsReal auto *histogram = new TH2F(histName.c_str(), "Events", nx, var1.getMin(), var1.getMax(), ny, var2.getMin(), var2.getMax()); if (!histogram) { - coutE(DataHandling) << GetName() << "::createHistogram: unable to create a new histogram" << endl; + coutE(DataHandling) << GetName() << "::createHistogram: unable to create a new histogram" << std::endl; return nullptr; } // Dump contents - Int_t nevent = numEntries(); - for (Int_t i = 0; i < nevent; ++i) { + int nevent = numEntries(); + for (int i = 0; i < nevent; ++i) { get(i); if (select && select->eval() == 0) diff --git a/roofit/roofitcore/src/RooAbsGenContext.cxx b/roofit/roofitcore/src/RooAbsGenContext.cxx index cc004bf83541f..a240dfc7e6f80 100644 --- a/roofit/roofitcore/src/RooAbsGenContext.cxx +++ b/roofit/roofitcore/src/RooAbsGenContext.cxx @@ -52,7 +52,7 @@ RooAbsGenContext::RooAbsGenContext(const RooAbsPdf& model, const RooArgSet &vars _prototype(prototype), _isValid(true), _verbose(verbose), - _genData(0) + _genData(nullptr) { // Check PDF dependents if (model.recursiveCheckObservables(&vars)) { @@ -66,7 +66,7 @@ RooAbsGenContext::RooAbsGenContext(const RooAbsPdf& model, const RooArgSet &vars // Analyze the prototype dataset, if one is specified _nextProtoIndex= 0; - if(0 != _prototype) { + if(nullptr != _prototype) { for (RooAbsArg const* proto : *_prototype->get()) { // is this variable being generated or taken from the prototype? if(!_theEvent.contains(*proto)) { @@ -133,7 +133,7 @@ RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool exten { if(!isValid()) { coutE(Generation) << ClassName() << "::" << GetName() << ": context is not valid" << endl; - return 0; + return nullptr; } // Calculate the expected number of events if necessary @@ -145,14 +145,14 @@ RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool exten if (_extendMode == RooAbsPdf::CanNotBeExtended) { coutE(Generation) << ClassName() << "::" << GetName() << ":generate: PDF not extendable: cannot calculate expected number of events" << endl; - return 0; + return nullptr; } nEvents= _expectedEvents; } if(nEvents <= 0) { coutE(Generation) << ClassName() << "::" << GetName() << ":generate: cannot calculate expected number of events" << endl; - return 0; + return nullptr; } coutI(Generation) << ClassName() << "::" << GetName() << ":generate: will generate " << nEvents << " events" << endl; @@ -180,7 +180,7 @@ RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool exten // ok= false; } // coverity[DEADCODE] - if(!ok) return 0; + if(!ok) return nullptr; } if (_verbose) Print("v") ; @@ -203,20 +203,20 @@ RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool exten while(_genData->numEntries()= _prototype->numEntries()) _nextProtoIndex= 0; Int_t actualProtoIdx = !_protoOrder.empty() ? _protoOrder[_nextProtoIndex] : _nextProtoIndex ; const RooArgSet *subEvent= _prototype->get(actualProtoIdx); _nextProtoIndex++; - if(0 != subEvent) { + if(nullptr != subEvent) { _theEvent.assign(*subEvent); } else { coutE(Generation) << ClassName() << "::" << GetName() << ":generate: cannot load event " << actualProtoIdx << " from prototype dataset" << endl; - return 0; + return nullptr; } } @@ -233,7 +233,7 @@ RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool exten } RooDataSet* output = _genData ; - _genData = 0 ; + _genData = nullptr ; output->setDirtyProp(true) ; return output; @@ -341,12 +341,12 @@ void RooAbsGenContext::resampleData(double& ratio) Int_t nOrig = _genData->numEntries() ; Int_t nTarg = Int_t(nOrig*ratio+0.5) ; - RooDataSet* trimmedData = (RooDataSet*) _genData->reduce(RooFit::EventRange(0,nTarg)) ; + std::unique_ptr trimmedData{_genData->reduce(RooFit::EventRange(0,nTarg))}; cxcoutD(Generation) << "RooGenContext::resampleData*( existing production trimmed from " << nOrig << " to " << trimmedData->numEntries() << " events" << endl ; delete _genData ; - _genData = trimmedData ; + _genData = static_cast(trimmedData.release()); if (_prototype) { // Push back proto index by trimmed amount to force recycling of the diff --git a/roofit/roofitcore/src/RooAbsHiddenReal.cxx b/roofit/roofitcore/src/RooAbsHiddenReal.cxx index 449edb67f4765..1260fb2d22ea9 100644 --- a/roofit/roofitcore/src/RooAbsHiddenReal.cxx +++ b/roofit/roofitcore/src/RooAbsHiddenReal.cxx @@ -38,7 +38,7 @@ using namespace std; ClassImp(RooAbsHiddenReal); ; -RooCategory* RooAbsHiddenReal::_dummyBlindState = 0; +RooCategory* RooAbsHiddenReal::_dummyBlindState = nullptr; //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofitcore/src/RooAbsIntegrator.cxx b/roofit/roofitcore/src/RooAbsIntegrator.cxx index b1a12e9be0267..f09123cc9ea6e 100644 --- a/roofit/roofitcore/src/RooAbsIntegrator.cxx +++ b/roofit/roofitcore/src/RooAbsIntegrator.cxx @@ -32,17 +32,8 @@ functions that implement the RooAbsFunc interface. using namespace std; ClassImp(RooAbsIntegrator); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooAbsIntegrator::RooAbsIntegrator() : _function(0), _valid(false), _printEvalCounter(false) -{ -} - +RooAbsIntegrator::RooAbsIntegrator() = default; //////////////////////////////////////////////////////////////////////////////// /// Copy constructor diff --git a/roofit/roofitcore/src/RooAbsMCStudyModule.cxx b/roofit/roofitcore/src/RooAbsMCStudyModule.cxx index 872d9bc1b7fde..872fdb3bf45ec 100644 --- a/roofit/roofitcore/src/RooAbsMCStudyModule.cxx +++ b/roofit/roofitcore/src/RooAbsMCStudyModule.cxx @@ -31,18 +31,19 @@ summaryData() is merged with the 'master' summary dataset in RooMCStudy. Look at RooDLLSignificanceMCSModule for an example of an implementation. **/ -#include "RooAbsMCStudyModule.h" +#include + +#include using namespace std; ClassImp(RooAbsMCStudyModule); - ; //////////////////////////////////////////////////////////////////////////////// /// Constructor -RooAbsMCStudyModule::RooAbsMCStudyModule(const char* name, const char* title) : TNamed(name,title), _mcs(0) +RooAbsMCStudyModule::RooAbsMCStudyModule(const char* name, const char* title) : TNamed(name,title), _mcs(nullptr) { } @@ -65,3 +66,6 @@ bool RooAbsMCStudyModule::doInitializeInstance(RooMCStudy& study) return initializeInstance() ; } +RooFit::OwningPtr RooAbsMCStudyModule::refit(RooAbsData* inGenSample) { + if (_mcs) return _mcs->refit(inGenSample) ; else return nullptr ; +} diff --git a/roofit/roofitcore/src/RooAbsMinimizerFcn.cxx b/roofit/roofitcore/src/RooAbsMinimizerFcn.cxx index 96ae6967310a5..87b48afb652c9 100644 --- a/roofit/roofitcore/src/RooAbsMinimizerFcn.cxx +++ b/roofit/roofitcore/src/RooAbsMinimizerFcn.cxx @@ -69,17 +69,21 @@ RooAbsMinimizerFcn::RooAbsMinimizerFcn(RooArgList paramList, RooMinimizer *conte _nDim = _floatParamList->getSize(); // Save snapshot of initial lists - _initFloatParamList.reset((RooArgList *)_floatParamList->snapshot(false)); - _initConstParamList.reset((RooArgList *)_constParamList->snapshot(false)); + _initFloatParamList = std::make_unique(); + _initConstParamList = std::make_unique(); + _floatParamList->snapshot(*_initFloatParamList, false); + _constParamList->snapshot(*_initConstParamList, false); } RooAbsMinimizerFcn::RooAbsMinimizerFcn(const RooAbsMinimizerFcn &other) : _context(other._context), _maxFCN(other._maxFCN), _funcOffset(other._funcOffset), _numBadNLL(other._numBadNLL), _evalCounter(other._evalCounter), _nDim(other._nDim), _optConst(other._optConst), _floatParamList(new RooArgList(*other._floatParamList)), _constParamList(new RooArgList(*other._constParamList)), - _initFloatParamList((RooArgList *)other._initFloatParamList->snapshot(false)), - _initConstParamList((RooArgList *)other._initConstParamList->snapshot(false)), _logfile(other._logfile) + _initFloatParamList(std::make_unique()), _initConstParamList(std::make_unique()), + _logfile(other._logfile) { + other._initFloatParamList->snapshot(*_initFloatParamList, false); + other._initConstParamList->snapshot(*_initConstParamList, false); } /// Internal function to synchronize TMinimizer with current @@ -132,7 +136,7 @@ bool RooAbsMinimizerFcn::synchronizeParameterSettings(std::vectorassign(*_constParamList); // Synchronize MINUIT with function state // Handle floatParamList @@ -456,7 +460,7 @@ void RooAbsMinimizerFcn::finishDoEval() const void RooAbsMinimizerFcn::setOptimizeConst(int flag) { - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); + auto ctx = _context->makeEvalErrorContext(); if (_optConst && !flag) { if (_context->getPrintLevel() > -1) @@ -479,15 +483,13 @@ void RooAbsMinimizerFcn::setOptimizeConst(int flag) oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: const optimization wasn't active" << endl; } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); } void RooAbsMinimizerFcn::optimizeConstantTerms(bool constStatChange, bool constValChange) { - if (constStatChange) { + auto ctx = _context->makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); + if (constStatChange) { oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::optimizeConstantTerms: set of constant parameters changed, rerunning const optimizer" @@ -499,8 +501,6 @@ void RooAbsMinimizerFcn::optimizeConstantTerms(bool constStatChange, bool constV << endl; setOptimizeConstOnFunction(RooAbsArg::ValueChange, true); } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); } std::vector RooAbsMinimizerFcn::getParameterValues() const diff --git a/roofit/roofitcore/src/RooAbsMinimizerFcn.h b/roofit/roofitcore/src/RooAbsMinimizerFcn.h index e2e25f652fe0c..0a11eb9d6c41d 100644 --- a/roofit/roofitcore/src/RooAbsMinimizerFcn.h +++ b/roofit/roofitcore/src/RooAbsMinimizerFcn.h @@ -76,8 +76,8 @@ class RooAbsMinimizerFcn { unsigned int getNDim() const { return _nDim; } - // In the past, the `getNDim` function was called just `NDim`. The funciton - // was renamed to match the code convention (lower case for funciton names), + // In the past, the `getNDim` function was called just `NDim`. The function + // was renamed to match the code convention (lower case for function names), // but we have to keep an overload with the old name to not break existing // user code. inline unsigned int NDim() const { return getNDim(); } @@ -90,7 +90,6 @@ class RooAbsMinimizerFcn { /// Enable or disable offsetting on the function to be minimized, which enhances numerical precision. virtual void setOffsetting(bool flag) = 0; - virtual bool fit(ROOT::Fit::Fitter &) const = 0; virtual ROOT::Math::IMultiGenFunction *getMultiGenFcn() = 0; RooMinimizer::Config const &cfg() const { return _context->_cfg; } diff --git a/roofit/roofitcore/src/RooAbsMoment.cxx b/roofit/roofitcore/src/RooAbsMoment.cxx index 2a7a0e8dd6ecb..df22be9495a95 100644 --- a/roofit/roofitcore/src/RooAbsMoment.cxx +++ b/roofit/roofitcore/src/RooAbsMoment.cxx @@ -25,7 +25,7 @@ derivator class. **/ #include "Riostream.h" -#include +#include #include "RooAbsMoment.h" #include "RooAbsReal.h" diff --git a/roofit/roofitcore/src/RooAbsNumGenerator.cxx b/roofit/roofitcore/src/RooAbsNumGenerator.cxx index a727bc30ec0a7..5a789d3c10218 100644 --- a/roofit/roofitcore/src/RooAbsNumGenerator.cxx +++ b/roofit/roofitcore/src/RooAbsNumGenerator.cxx @@ -36,10 +36,11 @@ implementations like RooAcceptReject and RooFoam #include "RooMsgService.h" #include "RooRealBinding.h" -#include +#include using namespace std; +RooAbsNumGenerator::RooAbsNumGenerator() = default; //////////////////////////////////////////////////////////////////////////////// @@ -49,26 +50,25 @@ using namespace std; /// cloned and so will not be disturbed during the generation process. RooAbsNumGenerator::RooAbsNumGenerator(const RooAbsReal &func, const RooArgSet &genVars, bool verbose, const RooAbsReal* maxFuncVal) : - _cloneSet(0), _funcClone(0), _funcMaxVal(maxFuncVal), _verbose(verbose), _funcValStore(0), _funcValPtr(0), _cache(0) + _funcClone(nullptr), _funcMaxVal(maxFuncVal), _verbose(verbose) { // Clone the function and all nodes that it depends on so that this generator // is independent of any existing objects. RooArgSet nodes(func,func.GetName()); - _cloneSet= (RooArgSet*) nodes.snapshot(true); - if (!_cloneSet) { + if (nodes.snapshot(_cloneSet, true)) { oocoutE(nullptr, Generation) << "RooAbsNumGenerator::RooAbsNumGenerator(" << func.GetName() << ") Couldn't deep-clone function, abort," << endl ; RooErrorHandler::softAbort() ; } // Find the clone in the snapshot list - _funcClone = (RooAbsReal*)_cloneSet->find(func.GetName()); + _funcClone = (RooAbsReal*)_cloneSet.find(func.GetName()); // Check that each argument is fundamental, and separate them into // sets of categories and reals. Check that the area of the generating // space is finite. _isValid= true; - const RooAbsArg *found = 0; + const RooAbsArg *found = nullptr; for (RooAbsArg const* arg : genVars) { if(!arg->isFundamental()) { oocoutE(nullptr, Generation) << func.GetName() << "::RooAbsNumGenerator: cannot generate values for derived \"" @@ -77,21 +77,21 @@ RooAbsNumGenerator::RooAbsNumGenerator(const RooAbsReal &func, const RooArgSet & continue; } // look for this argument in the generating function's dependents - found= (const RooAbsArg*)_cloneSet->find(arg->GetName()); + found= (const RooAbsArg*)_cloneSet.find(arg->GetName()); if(found) { arg= found; } else { // clone any variables we generate that we haven't cloned already - arg= _cloneSet->addClone(*arg); + arg= _cloneSet.addClone(*arg); } - assert(0 != arg); + assert(nullptr != arg); // is this argument a category or a real? const RooCategory *catVar= dynamic_cast(arg); const RooRealVar *realVar= dynamic_cast(arg); - if(0 != catVar) { + if(nullptr != catVar) { _catVars.add(*catVar); } - else if(0 != realVar) { + else if(nullptr != realVar) { if(realVar->hasMin() && realVar->hasMax()) { _realVars.add(*realVar); } @@ -113,19 +113,17 @@ RooAbsNumGenerator::RooAbsNumGenerator(const RooAbsReal &func, const RooArgSet & } // create a fundamental type for storing function values - _funcValStore= dynamic_cast(_funcClone->createFundamental()); - assert(0 != _funcValStore); + _funcValStore= std::unique_ptr{_funcClone->createFundamental()}; // create a new dataset to cache trial events and function values RooArgSet cacheArgs(_catVars); cacheArgs.add(_realVars); cacheArgs.add(*_funcValStore); - _cache= new RooDataSet("cache","Accept-Reject Event Cache",cacheArgs); - assert(0 != _cache); + _cache= std::make_unique("cache","Accept-Reject Event Cache",cacheArgs); // attach our function clone to the cache dataset const RooArgSet *cacheVars= _cache->get(); - assert(0 != cacheVars); + assert(nullptr != cacheVars); _funcClone->recursiveRedirectServers(*cacheVars,false); // update ours sets of category and real args to refer to the cache dataset @@ -139,17 +137,7 @@ RooAbsNumGenerator::RooAbsNumGenerator(const RooAbsReal &func, const RooArgSet & } - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooAbsNumGenerator::~RooAbsNumGenerator() -{ - delete _cloneSet; - delete _cache ; - delete _funcValStore ; -} - +RooAbsNumGenerator::~RooAbsNumGenerator() = default; //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofitcore/src/RooAbsNumGenerator.h b/roofit/roofitcore/src/RooAbsNumGenerator.h index 48979c86db8de..3cadc47709fbc 100644 --- a/roofit/roofitcore/src/RooAbsNumGenerator.h +++ b/roofit/roofitcore/src/RooAbsNumGenerator.h @@ -27,7 +27,7 @@ class RooNumGenConfig ; class RooAbsNumGenerator { public: - RooAbsNumGenerator() : _cloneSet(nullptr), _funcClone(nullptr), _funcMaxVal(nullptr), _verbose(false), _isValid(false), _funcValStore(nullptr), _funcValPtr(nullptr), _cache(nullptr) {} + RooAbsNumGenerator(); RooAbsNumGenerator(const RooAbsReal &func, const RooArgSet &genVars, bool verbose=false, const RooAbsReal* maxFuncVal=nullptr); virtual RooAbsNumGenerator* clone(const RooAbsReal&, const RooArgSet& genVars, const RooArgSet& condVars, const RooNumGenConfig& config, bool verbose=false, const RooAbsReal* maxFuncVal=nullptr) const = 0 ; @@ -61,14 +61,16 @@ class RooAbsNumGenerator { protected: - RooArgSet *_cloneSet; ///< Set owning clone of input function - RooAbsReal *_funcClone; ///< Pointer to top level node of cloned function - const RooAbsReal *_funcMaxVal ; ///< Container for maximum function value - RooArgSet _catVars,_realVars ; ///< Sets of discrete and real valued observabeles - bool _verbose, _isValid; ///< Verbose and valid flag - RooRealVar *_funcValStore,*_funcValPtr; ///< RRVs storing function value in context and in output dataset - - RooDataSet *_cache; ///< Dataset holding generared values of observables + RooArgSet _cloneSet; ///< Set owning clone of input function + RooAbsReal *_funcClone = nullptr; ///< Pointer to top level node of cloned function + const RooAbsReal *_funcMaxVal = nullptr; ///< Container for maximum function value + RooArgSet _catVars; ///< Set of discrete observabeles + RooArgSet _realVars; ///< Set of real valued observabeles + bool _verbose = false; ///< Verbose flag + bool _isValid = false; ///< Valid flag + std::unique_ptr _funcValStore; ///< RRV storing function value in context + RooRealVar *_funcValPtr = nullptr; ///< RRV storing function value in output dataset + std::unique_ptr _cache; ///< Dataset holding generared values of observables }; #endif diff --git a/roofit/roofitcore/src/RooAbsOptTestStatistic.cxx b/roofit/roofitcore/src/RooAbsOptTestStatistic.cxx index ab19c28626b01..a0673785167cf 100644 --- a/roofit/roofitcore/src/RooAbsOptTestStatistic.cxx +++ b/roofit/roofitcore/src/RooAbsOptTestStatistic.cxx @@ -37,7 +37,7 @@ parallelized calculation of test statistics. #include "Riostream.h" #include "TClass.h" -#include +#include #include "RooAbsOptTestStatistic.h" @@ -66,31 +66,6 @@ parallelized calculation of test statistics. using namespace std; ClassImp(RooAbsOptTestStatistic); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Default Constructor - -RooAbsOptTestStatistic:: RooAbsOptTestStatistic() -{ - // Initialize all non-persisted data members - - _funcObsSet = 0 ; - _funcCloneSet = 0 ; - _funcClone = 0 ; - - _normSet = 0 ; - _projDeps = 0 ; - - _origFunc = 0 ; - _origData = 0 ; - - _ownData = true ; - _sealed = false ; - _optimized = false ; -} - //////////////////////////////////////////////////////////////////////////////// @@ -118,62 +93,42 @@ RooAbsOptTestStatistic:: RooAbsOptTestStatistic() /// - cloneInputData Not used. Data is always cloned. /// - integrateOverBinsPrecision If > 0, PDF in binned fits are integrated over the bins. This sets the precision. If = 0, /// only unbinned PDFs fit to RooDataHist are integrated. If < 0, PDFs are never integrated. -RooAbsOptTestStatistic::RooAbsOptTestStatistic(const char *name, const char *title, RooAbsReal& real, - RooAbsData& indata, const RooArgSet& projDeps, - RooAbsTestStatistic::Configuration const& cfg) : - RooAbsTestStatistic(name,title,real,indata,projDeps,cfg), - _projDeps(0), - _sealed(false), - _optimized(false), - _integrateBinsPrecision(cfg.integrateOverBinsPrecision) +RooAbsOptTestStatistic::RooAbsOptTestStatistic(const char *name, const char *title, RooAbsReal &real, + RooAbsData &indata, const RooArgSet &projDeps, + RooAbsTestStatistic::Configuration const &cfg) + : RooAbsTestStatistic(name, title, real, indata, projDeps, cfg), + _integrateBinsPrecision(cfg.integrateOverBinsPrecision) { - // Don't do a thing in master mode - - if (operMode()!=Slave) { - _funcObsSet = 0 ; - _funcCloneSet = 0 ; - _funcClone = 0 ; - _normSet = 0 ; - _projDeps = 0 ; - _origFunc = 0 ; - _origData = 0 ; - _ownData = false ; - _sealed = false ; - return ; - } - - _origFunc = 0 ; //other._origFunc ; - _origData = 0 ; // other._origData ; + // Don't do a thing in master mode + if (operMode() != Slave) { + return; + } - initSlave(real, indata, projDeps, _rangeName.c_str(), _addCoefRangeName.c_str()) ; + initSlave(real, indata, projDeps, _rangeName.c_str(), _addCoefRangeName.c_str()); } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor -RooAbsOptTestStatistic::RooAbsOptTestStatistic(const RooAbsOptTestStatistic& other, const char* name) : - RooAbsTestStatistic(other,name), _sealed(other._sealed), _sealNotice(other._sealNotice), _optimized(false), - _integrateBinsPrecision(other._integrateBinsPrecision) +RooAbsOptTestStatistic::RooAbsOptTestStatistic(const RooAbsOptTestStatistic &other, const char *name) + : RooAbsTestStatistic(other, name), + _sealed(other._sealed), + _sealNotice(other._sealNotice), + _skipZeroWeights(other._skipZeroWeights), + _integrateBinsPrecision(other._integrateBinsPrecision) { - // Don't do a thing in master mode - if (operMode()!=Slave) { - - _funcObsSet = 0 ; - _funcCloneSet = 0 ; - _funcClone = 0 ; - _normSet = other._normSet ? ((RooArgSet*) other._normSet->snapshot()) : 0 ; - _projDeps = 0 ; - _origFunc = 0 ; - _origData = 0 ; - _ownData = false ; - return ; - } + // Don't do a thing in master mode + if (operMode() != Slave) { - _origFunc = 0 ; //other._origFunc ; - _origData = 0 ; // other._origData ; - _projDeps = 0 ; + if (other._normSet) { + _normSet = new RooArgSet; + other._normSet->snapshot(*_normSet); + } + return; + } - initSlave(*other._funcClone,*other._dataClone,other._projDeps?*other._projDeps:RooArgSet(),other._rangeName.c_str(),other._addCoefRangeName.c_str()) ; + initSlave(*other._funcClone, *other._dataClone, other._projDeps ? *other._projDeps : RooArgSet(), + other._rangeName.c_str(), other._addCoefRangeName.c_str()); } @@ -188,20 +143,19 @@ void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, con // Clone FUNC _funcClone = RooHelpers::cloneTreeWithSameParameters(real, indata.get()).release(); - _funcCloneSet = 0 ; + _funcCloneSet = nullptr ; // Attach FUNC to data set - _funcObsSet = _funcClone->getObservables(indata) ; + _funcObsSet = std::unique_ptr{_funcClone->getObservables(indata)}.release(); if (_funcClone->getAttribute("BinnedLikelihood")) { _funcClone->setAttribute("BinnedLikelihoodActive") ; } // Mark all projected dependents as such - if (projDeps.getSize()>0) { - RooArgSet *projDataDeps = (RooArgSet*) _funcObsSet->selectCommon(projDeps) ; + if (!projDeps.empty()) { + std::unique_ptr projDataDeps{static_cast(_funcObsSet->selectCommon(projDeps))}; projDataDeps->setAttribAll("projectedDependent") ; - delete projDataDeps ; } // If PDF is a RooProdPdf (with possible constraint terms) @@ -221,7 +175,8 @@ void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, con } // Store normalization set - _normSet = (RooArgSet*) indata.get()->snapshot(false) ; + _normSet = new RooArgSet; + indata.get()->snapshot(*_normSet, false); // Expand list of observables with any observables used in parameterized ranges. // This NEEDS to be a counting loop since we are inserting during the loop. @@ -229,7 +184,7 @@ void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, con auto realDepRLV = dynamic_cast((*_funcObsSet)[i]); if (realDepRLV && realDepRLV->isDerived()) { RooArgSet tmp2; - realDepRLV->leafNodeServerList(&tmp2, 0, true); + realDepRLV->leafNodeServerList(&tmp2, nullptr, true); _funcObsSet->add(tmp2,true); } } @@ -270,7 +225,7 @@ void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, con // Copy data and strip entries lost by adjusted fit range, _dataClone ranges will be copied from realDepSet ranges if (rangeName && strlen(rangeName)) { - _dataClone = indata.reduce(RooFit::SelectVars(*_funcObsSet),RooFit::CutRange(rangeName)) ; + _dataClone = std::unique_ptr{indata.reduce(RooFit::SelectVars(*_funcObsSet),RooFit::CutRange(rangeName))}.release(); // cout << "RooAbsOptTestStatistic: reducing dataset to fit in range named " << rangeName << " resulting dataset has " << _dataClone->sumEntries() << " events" << endl ; } else { _dataClone = (RooAbsData*) indata.Clone() ; @@ -344,15 +299,16 @@ void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, con // Remove projected dependents from normalization set if (projDeps.getSize()>0) { - _projDeps = (RooArgSet*) projDeps.snapshot(false) ; + _projDeps = new RooArgSet; + projDeps.snapshot(*_projDeps, false) ; //RooArgSet* tobedel = (RooArgSet*) _normSet->selectCommon(*_projDeps) ; _normSet->remove(*_projDeps,true,true) ; // Mark all projected dependents as such - RooArgSet *projDataDeps = (RooArgSet*) _funcObsSet->selectCommon(*_projDeps) ; - projDataDeps->setAttribAll("projectedDependent") ; - delete projDataDeps ; + RooArgSet projDataDeps; + _funcObsSet->selectCommon(*_projDeps, projDataDeps); + projDataDeps.setAttribAll("projectedDependent") ; } @@ -627,7 +583,7 @@ void RooAbsOptTestStatistic::optimizeConstantTerms(bool activate, bool applyTrac _funcClone->findConstantNodes(*_dataClone->get(),_cachedNodes) ; // Cache constant nodes with dataset - also cache entries corresponding to zero-weights in data when using BinnedLikelihood - _dataClone->cacheArgs(this,_cachedNodes,_normSet,!_funcClone->getAttribute("BinnedLikelihood")) ; + _dataClone->cacheArgs(this,_cachedNodes,_normSet, _skipZeroWeights); // Put all cached nodes in AClean value caching mode so that their evaluate() is never called for (auto cacheArg : _cachedNodes) { @@ -709,7 +665,7 @@ bool RooAbsOptTestStatistic::setDataSlave(RooAbsData& indata, bool cloneData, bo _dataClone = nullptr ; } - if (!cloneData && _rangeName.size()>0) { + if (!cloneData && !_rangeName.empty()) { coutW(InputArguments) << "RooAbsOptTestStatistic::setData(" << GetName() << ") WARNING: test statistic was constructed with range selection on data, " << "ignoring request to _not_ clone the input dataset" << endl ; cloneData = true ; @@ -718,9 +674,9 @@ bool RooAbsOptTestStatistic::setDataSlave(RooAbsData& indata, bool cloneData, bo if (cloneData) { // Cloning input dataset if (_rangeName.empty()) { - _dataClone = (RooAbsData*) indata.reduce(*indata.get()) ; + _dataClone = std::unique_ptr{indata.reduce(*indata.get())}.release(); } else { - _dataClone = ((RooAbsData&)indata).reduce(RooFit::SelectVars(*indata.get()),RooFit::CutRange(_rangeName.c_str())) ; + _dataClone = std::unique_ptr{indata.reduce(RooFit::SelectVars(*indata.get()),RooFit::CutRange(_rangeName.c_str()))}.release(); } _ownData = true ; @@ -738,8 +694,8 @@ bool RooAbsOptTestStatistic::setDataSlave(RooAbsData& indata, bool cloneData, bo _data = _dataClone ; // ReCache constant nodes with dataset - if (_cachedNodes.getSize()>0) { - _dataClone->cacheArgs(this,_cachedNodes,_normSet) ; + if (!_cachedNodes.empty()) { + _dataClone->cacheArgs(this,_cachedNodes,_normSet, _skipZeroWeights); } // Adjust internal event count @@ -816,3 +772,8 @@ const char* RooAbsOptTestStatistic::cacheUniqueSuffix() const { return Form("_%lx", _dataClone->uniqueId().value()) ; } + +void RooAbsOptTestStatistic::runRecalculateCache(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const +{ + _dataClone->store()->recalculateCache(_projDeps, firstEvent, lastEvent, stepSize, _skipZeroWeights); +} diff --git a/roofit/roofitcore/src/RooAbsPdf.cxx b/roofit/roofitcore/src/RooAbsPdf.cxx index 39c1ce16084eb..cb6d5af7a7a44 100644 --- a/roofit/roofitcore/src/RooAbsPdf.cxx +++ b/roofit/roofitcore/src/RooAbsPdf.cxx @@ -22,7 +22,7 @@ RooAbsPdf is the abstract interface for all probability density functions. The class provides hybrid analytical/numerical -normalization for its implementations, error tracing and a MC +normalization for its implementations, error tracing, and a Monte Carlo generator interface. ### A Minimal PDF Implementation @@ -37,33 +37,33 @@ return the PDF's value (which does not need to be normalised). Although the normalization of a PDF is an integral part of a probability density function, normalization is treated separately in RooAbsPdf. The reason is that a RooAbsPdf object is more than a -PDF: it can be a building block for a more complex, composite PDF +PDF: it can be a building block for a more complex composite PDF if any of its variables are functions instead of variables. In -such cases the normalization of the composite may not be simply the -integral over the dependents of the top level PDF as these are +such cases, the normalization of the composite PDF may not simply be +integral over the dependents of the top-level PDF: these are functions with potentially non-trivial Jacobian terms themselves. \note Therefore, no explicit attempt should be made to normalize the function output in evaluate(). In particular, normalisation constants can be omitted to speed up the function evaluations, and included later -in the integration of the PDF (see below), which is called rarely in +in the integration of the PDF (see below), which is rarely called in comparison to the `evaluate()` function. In addition, RooAbsPdf objects do not have a static concept of what -variables are parameters and what variables are dependents (which +variables are parameters, and what variables are dependents (which need to be integrated over for a correct PDF normalization). Instead, the choice of normalization is always specified each time a normalized value is requested from the PDF via the getVal() method. RooAbsPdf manages the entire normalization logic of each PDF with -help of a RooRealIntegral object, which coordinates the integration +the help of a RooRealIntegral object, which coordinates the integration of a given choice of normalization. By default, RooRealIntegral will -perform a fully numeric integration of all dependents. However, +perform an entirely numeric integration of all dependents. However, PDFs can advertise one or more (partial) analytical integrals of their function, and these will be used by RooRealIntegral, if it -determines that this is safe (i.e. no hidden Jacobian terms, +determines that this is safe (i.e., no hidden Jacobian terms, multiplication with other PDFs that have one or more dependents in -commen etc). +common, etc). #### Implementing analytical integrals To implement analytical integrals, two functions must be implemented. First, @@ -75,7 +75,7 @@ should return the analytical integrals that are supported. `integSet` is the set of dependents for which integration is requested. The function should copy the subset of dependents it can analytically integrate to `anaIntSet`, and return a unique identification code for -this integration configuration. If no integration can be +this integration configuration. If no integration can be performed, zero should be returned. Second, ``` @@ -89,8 +89,8 @@ codes returned by `getAnalyticalIntegral()`, except code zero. The integration range for each dependent to be integrated can be obtained from the dependent's proxy functions `min()` and `max()`. Never call these proxy functions for any proxy not known to -be a dependent via the integration code. Doing so may be -ill-defined, e.g. in case the proxy holds a function, and will +be a dependent via the integration code. Doing so may be +ill-defined, e.g., in case the proxy holds a function, and will trigger an assert. Integrated category dependents should always be summed over all of their states. @@ -119,25 +119,26 @@ function implements the actual generator for the advertised observables. The generated dependent values should be stored in the proxy objects. For this, the assignment operator can be used (i.e. `xProxy = 3.0` ). Never call assign to any proxy not known to be a dependent -via the generation code. Doing so may be ill-defined, e.g. in case +via the generation code. Doing so may be ill-defined, e.g. in case the proxy holds a function, and will trigger an assert. ### Batched function evaluations (Advanced usage) To speed up computations with large numbers of data events in unbinned fits, -it is beneficial to override `evaluateSpan()`. Like this, large spans of +it is beneficial to override `computeBatch()`. Like this, large spans of computations can be done, without having to call `evaluate()` for each single data event. -`evaluateSpan()` should execute the same computation as `evaluate()`, but it +`computeBatch()` should execute the same computation as `evaluate()`, but it may choose an implementation that is capable of SIMD computations. -If evaluateSpan is not implemented, the classic and slower `evaluate()` will be +If computeBatch is not implemented, the classic and slower `evaluate()` will be called for each data event. */ #include "RooAbsPdf.h" +#include "FitHelpers.h" +#include "RooNormalizedPdf.h" #include "RooMsgService.h" -#include "RooDataSet.h" #include "RooArgSet.h" #include "RooArgProxy.h" #include "RooRealProxy.h" @@ -155,15 +156,11 @@ called for each data event. #include "RooRandom.h" #include "RooNumIntConfig.h" #include "RooProjectedPdf.h" -#include "RooCustomizer.h" #include "RooParamBinning.h" #include "RooNumCdf.h" #include "RooFitResult.h" #include "RooNumGenConfig.h" #include "RooCachedReal.h" -#include "RooXYChi2Var.h" -#include "RooChi2Var.h" -#include "RooMinimizer.h" #include "RooRealIntegral.h" #include "RooWorkspace.h" #include "RooNaNPacker.h" @@ -171,19 +168,19 @@ called for each data event. #include "RooFormulaVar.h" #include "RooDerivative.h" #include "RooFit/BatchModeHelpers.h" -#include "RooVDTHeaders.h" #include "RooFit/TestStatistics/buildLikelihood.h" #include "RooFit/TestStatistics/RooRealL.h" -#include "RooFit/TestStatistics/optional_parameter_types.h" -#include "RunContext.h" #include "ConstraintHelpers.h" +#include "RooFit/Evaluator.h" +#include "RooEvaluatorWrapper.h" +#include "RooSimultaneous.h" +#include "RooFuncWrapper.h" #include "ROOT/StringUtils.hxx" #include "TMath.h" #include "TPaveText.h" #include "TMatrixD.h" #include "TMatrixDSym.h" -#include "Math/CholeskyDecomp.h" #include #include @@ -191,21 +188,34 @@ called for each data event. #include #include -namespace { - -bool interpretExtendedCmdArg(RooAbsPdf const& pdf, int extendedCmdArg) { - // Process automatic extended option - if (extendedCmdArg == 2) { - bool ext = pdf.extendMode() == RooAbsPdf::CanBeExtended || pdf.extendMode() == RooAbsPdf::MustBeExtended; - if (ext) { - oocoutI(&pdf, Minimization) - << "p.d.f. provides expected number of events, including extended term in likelihood." << std::endl; - } - return ext; - } - return extendedCmdArg; +bool RooAbsPdf::interpretExtendedCmdArg(int extendedCmdArg) const +{ + // Process automatic extended option + if (extendedCmdArg == RooFit::FitHelpers::extendedFitDefault) { + bool ext = this->extendMode() == RooAbsPdf::CanBeExtended || this->extendMode() == RooAbsPdf::MustBeExtended; + if (ext) { + coutI(Minimization) << "p.d.f. provides expected number of events, including extended term in likelihood." + << std::endl; + } + return ext; + } + // If Extended(false) was explicitly set, but the pdf MUST be extended, then + // it's time to print an error. This happens when you're fitting a RooAddPdf + // with coefficient that represent yields, and without the additional + // constraint these coefficients are degenerate because the RooAddPdf + // normalizes itself. Nothing correct can come out of this. + if (extendedCmdArg == 0) { + if (this->extendMode() == RooAbsPdf::MustBeExtended) { + std::string errMsg = "You used the Extended(false) option on a pdf where the fit MUST be extended! " + "The parameters are not well defined and you're getting nonsensical results."; + coutE(InputArguments) << errMsg << std::endl; + } + } + return extendedCmdArg; } +namespace { + inline double getLog(double prob, RooAbsReal const *caller) { @@ -242,7 +252,7 @@ void resetFitrangeAttributes(RooAbsArg& pdf, RooAbsData const& data, std::string // Clear possible range attributes from previous fits. pdf.removeStringAttribute("fitrange"); - // No fitrange was speficied, so we do nothing. Or "SplitRange" is used, and + // No fitrange was specified, so we do nothing. Or "SplitRange" is used, and // then there are no uniquely defined ranges for the observables (as they // are different in each category). if(!rangeName || splitRange) return; @@ -427,11 +437,11 @@ double RooAbsPdf::getValV(const RooArgSet* nset) const //////////////////////////////////////////////////////////////////////////////// -/// Analytical integral with normalization (see RooAbsReal::analyticalIntegralWN() for further information) +/// Analytical integral with normalization (see RooAbsReal::analyticalIntegralWN() for further information). /// -/// This function applies the normalization specified by 'normSet' to the integral returned +/// This function applies the normalization specified by `normSet` to the integral returned /// by RooAbsReal::analyticalIntegral(). The passthrough scenario (code=0) is also changed -/// to return a normalized answer +/// to return a normalized answer. double RooAbsPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const { @@ -514,7 +524,6 @@ double RooAbsPdf::getNorm(const RooArgSet* nset) const const RooAbsReal* RooAbsPdf::getNormObj(const RooArgSet* nset, const RooArgSet* iset, const TNamed* rangeName) const { - // Check normalization is already stored CacheElem* cache = (CacheElem*) _normMgr.getObj(nset,iset,0,rangeName) ; if (cache) { @@ -524,7 +533,12 @@ const RooAbsReal* RooAbsPdf::getNormObj(const RooArgSet* nset, const RooArgSet* // If not create it now RooArgSet depList; getObservables(iset, depList); - RooAbsReal* norm = createIntegral(depList,*nset, *getIntegratorConfig(), RooNameReg::str(rangeName)) ; + + // Normalization is always over all pdf components. Overriding the global + // component selection temporarily makes all RooRealIntegrals created during + // that time always include all components. + GlobalSelectComponentRAII globalSelComp(true); + RooAbsReal* norm = std::unique_ptr{createIntegral(depList,*nset, *getIntegratorConfig(), RooNameReg::str(rangeName))}.release(); // Store it in the cache cache = new CacheElem(*norm) ; @@ -600,7 +614,15 @@ bool RooAbsPdf::syncNormalization(const RooArgSet* nset, bool adjustProxies) con const char* nr = (_normRangeOverride.Length()>0 ? _normRangeOverride.Data() : (_normRange.Length()>0 ? _normRange.Data() : 0)) ; // cout << "RooAbsPdf::syncNormalization(" << GetName() << ") rangeName for normalization is " << (nr?nr:"") << endl ; - RooAbsReal* normInt = createIntegral(depList,*getIntegratorConfig(),nr) ; + RooAbsReal* normInt; + { + // Normalization is always over all pdf components. Overriding the global + // component selection temporarily makes all RooRealIntegrals created during + // that time always include all components. + GlobalSelectComponentRAII selCompRAII(true); + normInt = std::unique_ptr{createIntegral(depList,*getIntegratorConfig(),nr)}.release(); + } + static_cast(normInt)->setAllowComponentSelection(false); normInt->getVal() ; // cout << "resulting normInt = " << normInt->GetName() << endl ; @@ -712,7 +734,7 @@ bool checkInfNaNNeg(const T& inputs) { /// \param[in,out] outputs Array to be scanned & fixed. /// \param[in] begin Begin of event range. Only needed to print the correct event number /// where the error occurred. -void RooAbsPdf::logBatchComputationErrors(RooSpan& outputs, std::size_t begin) const { +void RooAbsPdf::logBatchComputationErrors(std::span& outputs, std::size_t begin) const { for (unsigned int i=0; i& outputs, std::s } -//////////////////////////////////////////////////////////////////////////////// -/// Compute the log-likelihoods for all events in the requested batch. -/// The arguments are passed over to getValues(). -/// \param[in] evalData Struct with data that should be used for evaluation. -/// \param[in] normSet Optional normalisation set to be used during computations. -/// \return Returns a batch of doubles that contains the log probabilities. -RooSpan RooAbsPdf::getLogProbabilities(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { - auto pdfValues = getValues(evalData, normSet); - - evalData.logProbabilities.resize(pdfValues.size()); - RooSpan results( evalData.logProbabilities ); - getLogProbabilities(getValues(evalData, normSet), results.data()); - return results; -} - - -void RooAbsPdf::getLogProbabilities(RooSpan pdfValues, double * output) const { +void RooAbsPdf::getLogProbabilities(std::span pdfValues, double * output) const { for (std::size_t i = 0; i < pdfValues.size(); ++i) { output[i] = getLog(pdfValues[i], this); } @@ -765,6 +771,13 @@ void RooAbsPdf::getLogProbabilities(RooSpan pdfValues, double * ou /// \param[in] observedSumW2 The number of observed events when weighting with /// squared weights. If non-zero, the weight-squared error /// correction is applied to the extended term. +/// \param[in] doOffset Offset the extended term by a counterterm where the +/// expected number of events equals the observed number of events. +/// This constant shift results in a term closer to zero that is +/// approximately chi-square distributed. It is useful to do this +/// also when summing multiple NLL terms to avoid numeric precision +/// loss that happens if you sum multiple terms of different orders +/// of magnitude. /// /// The weight-squared error correction works as follows: /// adjust poisson such that @@ -776,7 +789,7 @@ void RooAbsPdf::getLogProbabilities(RooSpan pdfValues, double * ou /// weighted by the effective weight \f$ \sum w_{i}^2 / \sum w_{i} \f$ in the likelihood. /// Since here we compute the likelihood with the weight square, we need to multiply by the /// square of the effective weight: -/// - \f$ W_\mathrm{expect} = N_\mathrm{expect} \cdot \sum w_{i} / \sum w_{i}^2 \f$ : effective expected entrie +/// - \f$ W_\mathrm{expect} = N_\mathrm{expect} \cdot \sum w_{i} / \sum w_{i}^2 \f$ : effective expected entries /// - \f$ W_\mathrm{observed} = \sum w_{i} \cdot \sum w_{i} / \sum w_{i}^2 \f$ : effective observed entries /// /// The extended term for the likelihood weighted by the square of the weight will be then: @@ -789,26 +802,26 @@ void RooAbsPdf::getLogProbabilities(RooSpan pdfValues, double * ou /// /// Since the weights are constants in the likelihood we can use \f$\log{N_\mathrm{expect}}\f$ instead of \f$\log{W_\mathrm{expect}}\f$. /// -/// See also RooAbsPdf::extendedTerm(RooAbsData const& data, bool weightSquared), +/// See also RooAbsPdf::extendedTerm(RooAbsData const& data, bool weightSquared, bool doOffset), /// which takes a dataset to extract \f$N_\mathrm{observed}\f$ and the /// normalization set. -double RooAbsPdf::extendedTerm(double sumEntries, RooArgSet const* nset, double sumEntriesW2) const +double RooAbsPdf::extendedTerm(double sumEntries, RooArgSet const* nset, double sumEntriesW2, bool doOffset) const { - return extendedTerm(sumEntries, expectedEvents(nset), sumEntriesW2); + return extendedTerm(sumEntries, expectedEvents(nset), sumEntriesW2, doOffset); } -double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEntriesW2) const +double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEntriesW2, bool doOffset) const { // check if this PDF supports extended maximum likelihood fits if(!canBeExtended()) { - coutE(InputArguments) << fName << ": this PDF does not support extended maximum likelihood" - << endl; - return 0; + coutE(InputArguments) << GetName() << ": this PDF does not support extended maximum likelihood" + << std::endl; + return 0.0; } - if(expected < 0) { - coutE(InputArguments) << fName << ": calculated negative expected events: " << expected - << endl; + if(expected < 0.0) { + coutE(InputArguments) << GetName() << ": calculated negative expected events: " << expected + << std::endl; logEvalError("extendedTerm #expected events is <0 return a NaN"); return TMath::QuietNaN(); } @@ -816,7 +829,7 @@ double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEnt // Explicitly handle case Nobs=Nexp=0 if (std::abs(expected)<1e-10 && std::abs(sumEntries)<1e-10) { - return 0 ; + return 0.0; } // Check for errors in Nexpected @@ -825,7 +838,9 @@ double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEnt return TMath::QuietNaN() ; } - double extra = expected - sumEntries*log(expected); + double extra = doOffset + ? (expected - sumEntries) - sumEntries * (std::log(expected) - std::log(sumEntries)) + : expected - sumEntries * std::log(expected); if(sumEntriesW2 != 0.0) { extra *= sumEntriesW2 / sumEntries; @@ -839,9 +854,9 @@ double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEnt /// of this PDF for the given number of observed events. /// /// This function is a wrapper around -/// RooAbsPdf::extendedTerm(double observed, const RooArgSet* nset), where the -/// number of observed events and observables to be used as the normalization -/// set for the pdf is extracted from a RooAbsData. +/// RooAbsPdf::extendedTerm(double, RooArgSet const *, double, bool) const, +/// where the number of observed events and observables to be used as the +/// normalization set for the pdf is extracted from a RooAbsData. /// /// For successful operation, the PDF implementation must indicate that /// it is extendable by overloading `canBeExtended()`, and must @@ -852,115 +867,164 @@ double RooAbsPdf::extendedTerm(double sumEntries, double expected, double sumEnt /// \param[in] weightSquared If set to `true`, the extended term will be scaled by /// the ratio of squared event weights over event weights: /// \f$ \sum w_{i}^2 / \sum w_{i} \f$. -/// Indended to be used by fits with the `SumW2Error()` option that -/// can be passed to RooAbsPdf::fitTo(RooAbsData&, const RooLinkedList&) +/// Intended to be used by fits with the `SumW2Error()` option that +/// can be passed to RooAbsPdf::fitTo() /// (see the documentation of said function to learn more about the /// interpretation of fits with squared weights). +/// \param[in] doOffset See RooAbsPdf::extendedTerm(double, RooArgSet const*, double, bool) const. -double RooAbsPdf::extendedTerm(RooAbsData const& data, bool weightSquared) const { +double RooAbsPdf::extendedTerm(RooAbsData const& data, bool weightSquared, bool doOffset) const { double sumW = data.sumEntries(); double sumW2 = 0.0; if (weightSquared) { sumW2 = data.sumEntriesW2(); } - return extendedTerm(sumW, data.get(), sumW2); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct representation of -log(L) of PDF with given dataset. If dataset is unbinned, an unbinned likelihood is constructed. If the dataset -/// is binned, a binned likelihood is constructed. -/// -/// The following named arguments are supported -/// -///
    -///
    Type of CmdArg Effect on nll -///
    `ConditionalObservables(Args_t &&... argsOrArgSet)` Do not normalize PDF over listed observables. -// Arguments can either be multiple RooRealVar or a single RooArgSet containing them. -///
    `Extended(bool flag)` Add extended likelihood term, off by default -///
    `Range(const char* name)` Fit only data inside range with given name -///
    `Range(double lo, double hi)` Fit only data inside given range. A range named "fit" is created on the fly on all observables. -/// Multiple comma separated range names can be specified. -///
    `SumCoefRange(const char* name)` Set the range in which to interpret the coefficients of RooAddPdf components -///
    `NumCPU(int num, int strat)` Parallelize NLL calculation on num CPUs -/// -///
    Strategy Effect -///
    0 = RooFit::BulkPartition (Default) Divide events in N equal chunks -///
    1 = RooFit::Interleave Process event i%N in process N. Recommended for binned data with -/// a substantial number of zero-bins, which will be distributed across processes more equitably in this strategy -///
    2 = RooFit::SimComponents Process each component likelihood of a RooSimultaneous fully in a single process -/// and distribute components over processes. This approach can be benificial if normalization calculation time -/// dominates the total computation time of a component (since the normalization calculation must be performed -/// in each process in strategies 0 and 1. However beware that if the RooSimultaneous components do not share many -/// parameters this strategy is inefficient: as most minuit-induced likelihood calculations involve changing -/// a single parameter, only 1 of the N processes will be active most of the time if RooSimultaneous components -/// do not share many parameters -///
    3 = RooFit::Hybrid Follow strategy 0 for all RooSimultaneous components, except those with less than -/// 30 dataset entries, for which strategy 2 is followed. -///
    -///
    `BatchMode(bool on)` Batch evaluation mode. See fitTo(). -///
    `Optimize(bool flag)` Activate constant term optimization (on by default) -///
    `SplitRange(bool flag)` Use separate fit ranges in a simultaneous fit. Actual range name for each subsample is assumed to -/// be `rangeName_indexState`, where `indexState` is the state of the master index category of the simultaneous fit. -/// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this: -/// ``` -/// myVariable.setRange("range_pi0", 135, 210); -/// myVariable.setRange("range_gamma", 50, 210); -/// ``` -///
    `Constrain(const RooArgSet&pars)` For p.d.f.s that contain internal parameter constraint terms (that is usually product PDFs, where one -/// term of the product depends on parameters but not on the observable(s),), only apply constraints to the given subset of parameters. -///
    `ExternalConstraints(const RooArgSet& )` Include given external constraints to likelihood by multiplying them with the original likelihood. -///
    `GlobalObservables(const RooArgSet&)` Define the set of normalization observables to be used for the constraint terms. -/// If none are specified the constrained parameters are used. -///
    `GlobalObservablesSource(const char* sourceName)` Which source to prioritize for global observable values. -/// Can be either: -/// - `data`: to take the values from the dataset, -/// falling back to the pdf value if a given global observable is not available. -/// If no `GlobalObservables` or `GlobalObservablesTag` command argument is given, the set -/// of global observables will be automatically defined to be the set stored in the data. -/// - `model`: to take all values from the pdf and completely ignore the set of global observables stored in the data -/// (not even using it to automatically define the set of global observables -/// if the `GlobalObservables` or `GlobalObservablesTag` command arguments are not given). -/// The default option is `data`. -///
    `GlobalObservablesTag(const char* tagName)` Define the set of normalization observables to be used for the constraint terms by -/// a string attribute associated with pdf observables that match the given tagName. -///
    `Verbose(bool flag)` Controls RooFit informational messages in likelihood construction -///
    `CloneData(bool flag)` Use clone of dataset in NLL (default is true) -///
    `Offset(std::string const& mode)` Likelihood offsetting mode. Can be either: -/// - `"off"` (default): no offsetting -/// - `"initial"`: Offset likelihood by initial value (so that starting value of FCN in minuit is zero). -/// This can improve numeric stability in simultaneous fits with components with large likelihood values. -/// - `"bin"`: Offset by the likelihood bin-by-bin with a template histogram model based on the obersved data. -/// This results in per-bin values that are all in the same order of magnitude, which reduces precision loss in the sum, -/// which can drastically improve numeric stability. -/// Furthermore, 2 * NLL defined like this is approximately chi-square distributed, allowing for goodness-of-fit tests. -///
    `IntegrateBins(double precision)` In binned fits, integrate the PDF over the bins instead of using the probability density at the bin centre. -/// This can reduce the bias observed when fitting functions with high curvature to binned data. -/// - precision > 0: Activate bin integration everywhere. Use precision between 0.01 and 1.E-6, depending on binning. -/// Note that a low precision such as 0.01 might yield identical results to 1.E-4, since the integrator might reach 1.E-4 already in its first -/// integration step. If lower precision is desired (more speed), a RooBinSamplingPdf has to be created manually, and its integrator -/// has to be manipulated directly. -/// - precision = 0: Activate bin integration only for continuous PDFs fit to a RooDataHist. -/// - precision < 0: Deactivate. -/// \see RooBinSamplingPdf -///
    `ModularL(bool flag)` Enable or disable modular likelihoods, which will become the default in a future release. -/// This does not change any user-facing code, but only enables a different likelihood class in the back-end. Note that this -/// should be set to true for parallel minimization of likelihoods! -/// Note that it is currently not recommended to use Modular likelihoods without any parallelization enabled in the minimization, since -/// some features such as offsetting might not yet work in this case. -///
    -/// -/// - -RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) + return extendedTerm(sumW, data.get(), sumW2, doOffset); +} + + +/** @fn RooAbsPdf::createNLL() + * + * @brief Construct representation of -log(L) of PDF with given dataset. + * + * If dataset is unbinned, an unbinned likelihood is constructed. + * If the dataset is binned, a binned likelihood is constructed. + * + * @param data Reference to a RooAbsData object representing the dataset. + * @param cmdArgs Variadic template arguments representing optional command arguments. + * You can pass either an arbitrary number of RooCmdArg instances + * or a single RooLinkedList that points to the RooCmdArg objects. + * @return An owning pointer to the created RooAbsReal NLL object. + * + * @tparam CmdArgs_t Template types for optional command arguments. + * Can either be an arbitrary number of RooCmdArg or a single RooLinkedList. + * + * \note This front-end function should not be re-implemented in derived PDF types. + * If you mean to customize the NLL creation routine, + * you need to override the virtual RooAbsPdf::createNLLImpl() method. + * + * The following named arguments are supported: + * + * + *
    Type of CmdArg Effect on NLL + *
    `ConditionalObservables(Args_t &&... argsOrArgSet)` Do not normalize PDF over listed observables. + * Arguments can either be multiple RooRealVar or a single RooArgSet containing them. + *
    `Range(const char* name)` Fit only data inside range with given name. Multiple comma-separated range names can be specified. + * In this case, the unnormalized PDF \f$f(x)\f$ is normalized by the integral over all ranges \f$r_i\f$: + * \f[ + * p(x) = \frac{f(x)}{\sum_i \int_{r_i} f(x) dx}. + * \f] + *
    `Range(double lo, double hi)` Fit only data inside given range. A range named "fit" is created on the fly on all observables. + *
    `SumCoefRange(const char* name)` Set the range in which to interpret the coefficients of RooAddPdf components + *
    `NumCPU(int num, int istrat)` Parallelize NLL calculation on num CPUs + * + *
    Strategy Effect + *
    0 = RooFit::BulkPartition - *default* Divide events in N equal chunks + *
    1 = RooFit::Interleave Process event i%N in process N. Recommended for binned data with + * a substantial number of zero-bins, which will be distributed across processes more equitably in this strategy + *
    2 = RooFit::SimComponents Process each component likelihood of a RooSimultaneous fully in a single process + * and distribute components over processes. This approach can be beneficial if normalization calculation time + * dominates the total computation time of a component (since the normalization calculation must be performed + * in each process in strategies 0 and 1. However beware that if the RooSimultaneous components do not share many + * parameters this strategy is inefficient: as most minuit-induced likelihood calculations involve changing + * a single parameter, only 1 of the N processes will be active most of the time if RooSimultaneous components + * do not share many parameters + *
    3 = RooFit::Hybrid Follow strategy 0 for all RooSimultaneous components, except those with less than + * 30 dataset entries, for which strategy 2 is followed. + *
    + *
    `EvalBackend(std::string const&)` Choose a likelihood evaluation backend: + * + *
    Backend Description + *
    **legacy** - *default* The original likelihood evaluation method. + * Evaluates the PDF for each single data entry at a time before summing the negative log probabilities. + * This is the default if `EvalBackend()` is not passed. + *
    **cpu** New vectorized evaluation mode, using faster math functions and auto-vectorisation. + * If all RooAbsArg objects in the model support it, likelihood computations are 2 to 10 times faster, + * unless your dataset is so small that the vectorization is not worth it. + * The relative difference of the single log-likelihoods w.r.t. the legacy mode is usually better than \f$10^{-12}\f$, + * and for fit parameters it's usually better than \f$10^{-6}\f$. In past ROOT releases, this backend could be activated with the now deprecated `BatchMode()` option. + *
    **cuda** Evaluate the likelihood on a GPU that supports CUDA. + * This backend re-uses code from the **cpu** backend, but compiled in CUDA kernels. + * Hence, the results are expected to be identical, modulo some numerical differences that can arise from the different order in which the GPU is summing the log probabilities. + * This backend can drastically speed up the fit if all RooAbsArg object in the model support it. + *
    **codegen** **Experimental** - Generates and compiles minimal C++ code for the NLL on-the-fly and wraps it in the returned RooAbsReal. + * Also generates and compiles the code for the gradient using Automatic Differentiation (AD) with [Clad](https://github.com/vgvassilev/clad). + * This analytic gradient is passed to the minimizer, which can result in significant speedups for many-parameter fits, + * even compared to the **cpu** backend. However, if one of the RooAbsArg objects in the model does not support the code generation, + * this backend can't be used. + *
    **codegen_no_grad** **Experimental** - Same as **codegen**, but doesn't generate and compile the gradient code and use the regular numerical differentiation instead. + * This is expected to be slower, but useful for debugging problems with the analytic gradient. + *
    + *
    `Optimize(bool flag)` Activate constant term optimization (on by default) + *
    `SplitRange(bool flag)` Use separate fit ranges in a simultaneous fit. Actual range name for each subsample is assumed to + * be `rangeName_indexState`, where `indexState` is the state of the master index category of the simultaneous fit. + * Using `Range("range"), SplitRange()` as switches, different ranges could be set like this: + * ``` + * myVariable.setRange("range_pi0", 135, 210); + * myVariable.setRange("range_gamma", 50, 210); + * ``` + *
    `Constrain(const RooArgSet&pars)` For p.d.f.s that contain internal parameter constraint terms (that is usually product PDFs, where one + * term of the product depends on parameters but not on the observable(s),), only apply constraints to the given subset of parameters. + *
    `ExternalConstraints(const RooArgSet& )` Include given external constraints to likelihood by multiplying them with the original likelihood. + *
    `GlobalObservables(const RooArgSet&)` Define the set of normalization observables to be used for the constraint terms. + * If none are specified the constrained parameters are used. + *
    `GlobalObservablesSource(const char* sourceName)` Which source to prioritize for global observable values. + * Can be either: + * - `data`: to take the values from the dataset, + * falling back to the pdf value if a given global observable is not available. + * If no `GlobalObservables` or `GlobalObservablesTag` command argument is given, the set + * of global observables will be automatically defined to be the set stored in the data. + * - `model`: to take all values from the pdf and completely ignore the set of global observables stored in the data + * (not even using it to automatically define the set of global observables + * if the `GlobalObservables` or `GlobalObservablesTag` command arguments are not given). + * The default option is `data`. + *
    `GlobalObservablesTag(const char* tagName)` Define the set of normalization observables to be used for the constraint terms by + * a string attribute associated with pdf observables that match the given tagName. + *
    `Verbose(bool flag)` Controls RooFit informational messages in likelihood construction + *
    `CloneData(bool flag)` Use clone of dataset in NLL (default is true). + * \warning Deprecated option that is ignored. It is up to the implementation of the NLL creation method if the data is cloned or not. + *
    `Offset(std::string const& mode)` Likelihood offsetting mode. Can be either: + * + *
    Mode Description + *
    **none** - *default* No offsetting. + *
    **initial** Offset likelihood by initial value (so that starting value of FCN in minuit is zero). + * This can improve numeric stability in simultaneous fits with components with large likelihood values. + *
    **bin** Offset likelihood bin-by-bin with a template histogram model based on the obersved data. + * This results in per-bin values that are all in the same order of magnitude, which reduces precision loss in the sum, + * which can drastically improve numeric stability. + * Furthermore, \f$2\cdot \text{NLL}\f$ defined like this is approximately chi-square distributed, allowing for goodness-of-fit tests. + *
    + *
    `IntegrateBins(double precision)` In binned fits, integrate the PDF over the bins instead of using the probability density at the bin centre. + * This can reduce the bias observed when fitting functions with high curvature to binned data. + * - precision > 0: Activate bin integration everywhere. Use precision between 0.01 and 1.E-6, depending on binning. + * Note that a low precision such as 0.01 might yield identical results to 1.E-4, since the integrator might reach 1.E-4 already in its first + * integration step. If lower precision is desired (more speed), a RooBinSamplingPdf has to be created manually, and its integrator + * has to be manipulated directly. + * - precision = 0: Activate bin integration only for continuous PDFs fit to a RooDataHist. + * - precision < 0: Deactivate. + * \see RooBinSamplingPdf + *
    `ModularL(bool flag)` Enable or disable modular likelihoods, which will become the default in a future release. + * This does not change any user-facing code, but only enables a different likelihood class in the back-end. Note that this + * should be set to true for parallel minimization of likelihoods! + * Note that it is currently not recommended to use Modular likelihoods without any parallelization enabled in the minimization, since + * some features such as offsetting might not yet work in this case. + *
    + */ + + +/** @brief Protected implementation of the NLL creation routine. + * + * This virtual function can be overridden in case you want to change the NLL creation logic for custom PDFs. + * + * \note Never call this function directly. Instead, call RooAbsPdf::createNLL(). + */ + +std::unique_ptr RooAbsPdf::createNLLImpl(RooAbsData& data, const RooLinkedList& cmdList) { auto baseName = std::string("nll_") + GetName() + "_" + data.GetName(); - // Figure out the integer that corresponds to the default BatchMode option. - const int defaultBatchModeInt = RooFit::BatchMode(RooFit::Experimental::defaultBatchMode()).getInt(0); - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::createNLL(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::createNLL(" + std::string(GetName()) + ")"); pc.defineString("rangeName","RangeWithName",0,"",true) ; pc.defineString("addCoefRange","SumCoefRange",0,"") ; @@ -969,7 +1033,7 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) pc.defineDouble("rangeLo","Range",0,-999.) ; pc.defineDouble("rangeHi","Range",1,-999.) ; pc.defineInt("splitRange","SplitRange",0,0) ; - pc.defineInt("ext","Extended",0,2) ; + pc.defineInt("ext","Extended",0,RooFit::FitHelpers::extendedFitDefault) ; pc.defineInt("numcpu","NumCPU",0,1) ; pc.defineInt("interleave","NumCPU",1,0) ; pc.defineInt("verbose","Verbose",0,0) ; @@ -980,7 +1044,7 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) pc.defineSet("glObs","GlobalObservables",0,0) ; pc.defineInt("doOffset","OffsetLikelihood",0,0) ; pc.defineSet("extCons","ExternalConstraints",0,0) ; - pc.defineInt("BatchMode", "BatchMode", 0, defaultBatchModeInt); + pc.defineInt("EvalBackend", "EvalBackend", 0, static_cast(RooFit::EvalBackend::defaultValue())); pc.defineDouble("IntegrateBins", "IntegrateBins", 0, -1.); pc.defineMutex("Range","RangeWithName") ; pc.defineMutex("GlobalObservables","GlobalObservablesTag") ; @@ -1018,23 +1082,25 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) const std::string rangeName = pc.getString("globstag", "", false); - RooFit::TestStatistics::ConstrainedParameters cPars(cParsSet); - RooFit::TestStatistics::ExternalConstraints extCons(extConsSet); - RooFit::TestStatistics::GlobalObservables glObs(glObsSet); + RooFit::TestStatistics::NLLFactory builder{*this, data}; + builder.Extended(ext) + .ConstrainedParameters(cParsSet) + .ExternalConstraints(extConsSet) + .GlobalObservables(glObsSet) + .GlobalObservablesTag(rangeName.c_str()); - return new RooFit::TestStatistics::RooRealL("likelihood", "", - RooFit::TestStatistics::buildLikelihood(this, &data, ext, cPars, extCons, glObs, rangeName)); + return std::make_unique("likelihood", "", builder.build()); } // Decode command line arguments const char* rangeName = pc.getString("rangeName",0,true) ; const char* addCoefRangeName = pc.getString("addCoefRange",0,true) ; - const bool ext = interpretExtendedCmdArg(*this, pc.getInt("ext")) ; + const bool ext = this->interpretExtendedCmdArg(pc.getInt("ext")) ; Int_t numcpu = pc.getInt("numcpu") ; Int_t numcpu_strategy = pc.getInt("interleave"); - // strategy 3 works only for RooSimultaneus. + // strategy 3 works only for RooSimultaneous. if (numcpu_strategy==3 && !this->InheritsFrom("RooSimultaneous") ) { - coutW(Minimization) << "Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneus, " + coutW(Minimization) << "Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneous, " "falling back to default strategy = 0" << endl; numcpu_strategy = 0; } @@ -1101,11 +1167,35 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) ); }; - auto batchMode = static_cast(pc.getInt("BatchMode")); + auto evalBackend = static_cast(pc.getInt("EvalBackend")); // Construct BatchModeNLL if requested - if (batchMode != RooFit::BatchModeOption::Off && batchMode != RooFit::BatchModeOption::Old) { - std::unique_ptr pdfClone = RooHelpers::cloneTreeWithSameParameters(*this, data.get()); + if (evalBackend != RooFit::EvalBackend::Value::Legacy) { + + // Set the normalization range. We need to do it now, because it will be + // considered in `compileForNormSet`. + TString oldNormRange = _normRange; + setNormRange(rangeName); + + RooArgSet normSet; + getObservables(data.get(), normSet); + normSet.remove(projDeps, true, true); + + this->setAttribute("SplitRange", splitRange); + this->setStringAttribute("RangeName", rangeName); + + RooFit::Detail::CompileContext ctx{normSet}; + ctx.setLikelihoodMode(true); + std::unique_ptr head = this->compileForNormSet(normSet, ctx); + std::unique_ptr pdfClone = std::unique_ptr{static_cast(head.release())}; + + // reset attributes + this->setAttribute("SplitRange", false); + this->setStringAttribute("RangeName", nullptr); + + // Reset the normalization range + _normRange = oldNormRange; + if (addCoefRangeName) { cxcoutI(Fitting) << "RooAbsPdf::fitTo(" << GetName() << ") fixing interpretation of coefficients of any component to range " @@ -1113,19 +1203,46 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) pdfClone->fixAddCoefRange(addCoefRangeName, false); } - return RooFit::BatchModeHelpers::createNLL(std::move(pdfClone), - data, - createConstr(*pdfClone, /*removeConstraintsFromPdf=*/true), - rangeName ? rangeName : "", - projDeps, - ext, - pc.getDouble("IntegrateBins"), - batchMode, - offset, - static_cast(splitRange), - takeGlobalObservablesFromData).release(); + std::unique_ptr compiledConstr; + if(std::unique_ptr constr = createConstr(*this)) { + compiledConstr = RooFit::Detail::compileForNormSet(*constr, *data.get()); + compiledConstr->addOwnedComponents(std::move(constr)); + } + + auto nll = RooFit::BatchModeHelpers::createNLL( + *pdfClone, + data, + std::move(compiledConstr), + rangeName ? rangeName : "", + projDeps, + ext, + pc.getDouble("IntegrateBins"), + offset); + + std::unique_ptr nllWrapper; + + if(evalBackend == RooFit::EvalBackend::Value::Codegen || evalBackend == RooFit::EvalBackend::Value::CodegenNoGrad) { + static int iFuncWrapper = 0; + std::string wrapperName = "nll_func_wrapper_" + std::to_string(iFuncWrapper++); + bool createGradient = evalBackend == RooFit::EvalBackend::Value::Codegen; + auto simPdf = dynamic_cast(pdfClone.get()); + nllWrapper = std::make_unique(wrapperName.c_str(), wrapperName.c_str(), *nll, normSet, &data, + simPdf, createGradient); + } else { + auto evaluator = std::make_unique(*nll, evalBackend == RooFit::EvalBackend::Value::Cuda); + nllWrapper = std::make_unique(*nll, + std::move(evaluator), rangeName ? rangeName : "", dynamic_cast(pdfClone.get()), takeGlobalObservablesFromData); + nllWrapper->setData(data, false); + } + + nllWrapper->addOwnedComponents(std::move(nll)); + nllWrapper->addOwnedComponents(std::move(pdfClone)); + return nllWrapper; } + auto binnedLInfo = RooHelpers::getBinnedL(*this); + RooAbsPdf &actualPdf = binnedLInfo.binnedPdf ? *binnedLInfo.binnedPdf : *this; + // Construct NLL RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; std::unique_ptr nll ; @@ -1137,12 +1254,11 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) cfg.splitCutRange = static_cast(splitRange); cfg.cloneInputData = static_cast(cloneData); cfg.integrateOverBinsPrecision = pc.getDouble("IntegrateBins"); - cfg.binnedL = false; + cfg.binnedL = binnedLInfo.isBinnedL; cfg.takeGlobalObservablesFromData = takeGlobalObservablesFromData; cfg.rangeName = rangeName ? rangeName : ""; - auto nllVar = std::make_unique(baseName.c_str(),"-log(likelihood)",*this,data,projDeps, ext, cfg); - nllVar->batchMode(batchMode == RooFit::BatchModeOption::Old); - nllVar->templateRatioOffset(offset == RooFit::OffsetMode::Bin); + auto nllVar = std::make_unique(baseName.c_str(),"-log(likelihood)",actualPdf,data,projDeps, ext, cfg); + nllVar->enableBinOffsetting(offset == RooFit::OffsetMode::Bin); nll = std::move(nllVar); RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; @@ -1166,7 +1282,7 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) constraintTerm->setOperMode(RooAbsArg::ADirty); auto orignll = std::move(nll) ; - nll = std::make_unique(Form("%s_with_constr",baseName.c_str()),"nllWithCons",RooArgSet(*orignll,*constraintTerm)) ; + nll = std::make_unique((baseName + "_with_constr").c_str(),"nllWithCons",RooArgSet(*orignll,*constraintTerm)) ; nll->addOwnedComponents(std::move(orignll),std::move(constraintTerm)) ; } @@ -1178,463 +1294,168 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList) nll->enableOffsetting(true) ; } - return nll.release() ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Use the asymptotically correct approach to estimate errors in the presence of weights. -/// This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303). -/// Applies the calculated covaraince matrix to the RooMinimizer and returns -/// the quality of the covariance matrix. -/// See also the documentation of RooAbsPdf::fitTo(), where this function is used. -/// \param[in] minimizer The RooMinimizer to get the fit result from. The state -/// of the minimizer will be altered by this function: the covariance -/// matrix caltulated here will be applied to it via -/// RooMinimizer::applyCovarianceMatrix(). -/// \param[in] data The dataset that was used for the fit. -int RooAbsPdf::calcAsymptoticCorrectedCovariance(RooMinimizer &minimizer, RooAbsData const &data) -{ - // Calculated corrected errors for weighted likelihood fits - std::unique_ptr rw(minimizer.save()); - // Weighted inverse Hessian matrix - const TMatrixDSym &matV = rw->covarianceMatrix(); - coutI(Fitting) - << "RooAbsPdf::fitTo(" << this->GetName() - << ") Calculating covariance matrix according to the asymptotically correct approach. If you find this " - "method useful please consider citing https://arxiv.org/abs/1911.01303." - << endl; - - // Initialise matrix containing first derivatives - auto nFloatPars = rw->floatParsFinal().getSize(); - TMatrixDSym num(nFloatPars); - for (int k = 0; k < nFloatPars; k++) { - for (int l = 0; l < nFloatPars; l++) { - num(k, l) = 0.0; - } - } - RooArgSet obs; - this->getObservables(data.get(), obs); - // Create derivative objects - std::vector> derivatives; - const RooArgList &floated = rw->floatParsFinal(); - std::unique_ptr floatingparams{ - static_cast(this->getParameters(data)->selectByAttrib("Constant", false))}; - for (const auto paramresult : floated) { - auto paraminternal = static_cast(floatingparams->find(*paramresult)); - assert(floatingparams->find(*paramresult)->IsA() == RooRealVar::Class()); - derivatives.emplace_back(this->derivative(*paraminternal, obs, 1)); - } - - // Loop over data - for (int j = 0; j < data.numEntries(); j++) { - // Sets obs to current data point, this is where the pdf will be evaluated - obs.assign(*data.get(j)); - // Determine first derivatives - std::vector diffs(floated.getSize(), 0.0); - for (int k = 0; k < floated.getSize(); k++) { - const auto paramresult = static_cast(floated.at(k)); - auto paraminternal = static_cast(floatingparams->find(*paramresult)); - // first derivative to parameter k at best estimate point for this measurement - double diff = derivatives[k]->getVal(); - // need to reset to best fit point after differentiation - *paraminternal = paramresult->getVal(); - diffs[k] = diff; - } - // Fill numerator matrix - double prob = getVal(&obs); - for (int k = 0; k < floated.getSize(); k++) { - for (int l = 0; l < floated.getSize(); l++) { - num(k, l) += data.weightSquared() * diffs[k] * diffs[l] / (prob * prob); - } - } - } - num.Similarity(matV); - - // Propagate corrected errors to parameters objects - minimizer.applyCovarianceMatrix(num); - - // The derivatives are found in RooFit and not with the minimizer (e.g. - // minuit), so the quality of the corrected covariance matrix corresponds to - // the quality of the original covariance matrix - return rw->covQual(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Apply correction to errors and covariance matrix. This uses two covariance -/// matrices, one with the weights, the other with squared weights, to obtain -/// the correct errors for weighted likelihood fits. -/// Applies the calculated covaraince matrix to the RooMinimizer and returns -/// the quality of the covariance matrix. -/// See also the documentation of RooAbsPdf::fitTo(), where this function is used. -/// \param[in] minimizer The RooMinimizer to get the fit result from. The state -/// of the minimizer will be altered by this function: the covariance -/// matrix caltulated here will be applied to it via -/// RooMinimizer::applyCovarianceMatrix(). -/// \param[in] nll The NLL object that was used for the fit. -int RooAbsPdf::calcSumW2CorrectedCovariance(RooMinimizer &minimizer, RooAbsReal &nll) const -{ - // Calculated corrected errors for weighted likelihood fits - std::unique_ptr rw{minimizer.save()}; - nll.applyWeightSquared(true); - coutI(Fitting) << "RooAbsPdf::fitTo(" << this->GetName() - << ") Calculating sum-of-weights-squared correction matrix for covariance matrix" - << std::endl; - minimizer.hesse(); - std::unique_ptr rw2{minimizer.save()}; - nll.applyWeightSquared(false); - - // Apply correction matrix - const TMatrixDSym &matV = rw->covarianceMatrix(); - TMatrixDSym matC = rw2->covarianceMatrix(); - ROOT::Math::CholeskyDecompGenDim decomp(matC.GetNrows(), matC); - if (!decomp) { - coutE(Fitting) << "RooAbsPdf::fitTo(" << this->GetName() - << ") ERROR: Cannot apply sum-of-weights correction to covariance matrix: correction " - "matrix calculated with weight-squared is singular" - << std::endl; - return -1; - } - - // replace C by its inverse - decomp.Invert(matC); - // the class lies about the matrix being symmetric, so fill in the - // part above the diagonal - for (int i = 0; i < matC.GetNrows(); ++i) { - for (int j = 0; j < i; ++j) { - matC(j, i) = matC(i, j); - } - } - matC.Similarity(matV); - // C now contiains V C^-1 V - // Propagate corrected errors to parameters objects - minimizer.applyCovarianceMatrix(matC); - - return std::min(rw->covQual(), rw2->covQual()); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Minimizes a given NLL variable by finding the optimal parameters with the -/// RooMinimzer. The NLL variable can be created with RooAbsPdf::createNLL. -/// If you are looking for a function that combines likelihood creation with -/// fitting, see RooAbsPdf::fitTo. -/// \param[in] nll The negative log-likelihood variable to minimize. -/// \param[in] data The dataset that was als used for the NLL. It's a necessary -/// parameter because it is used in the asymptotic error correction. -/// \param[in] cfg Configuration struct with all the configuration options for -/// the RooMinimizer. These are a subset of the options that you can -/// also pass to RooAbsPdf::fitTo via the RooFit command arguments. -std::unique_ptr RooAbsPdf::minimizeNLL(RooAbsReal & nll, - RooAbsData const& data, MinimizerConfig const& cfg) { - - // Determine if the dataset has weights - bool weightedData = data.isNonPoissonWeighted(); - - // Warn user that a method to determine parameter uncertainties should be provided if weighted data is offered - if (weightedData && cfg.doSumW2==-1 && cfg.doAsymptotic==-1) { - coutW(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") WARNING: a likelihood fit is requested of what appears to be weighted data.\n" - << " While the estimated values of the parameters will always be calculated taking the weights into account,\n" - << " there are multiple ways to estimate the errors of the parameters. You are advised to make an \n" - << " explicit choice for the error calculation:\n" - << " - Either provide SumW2Error(true), to calculate a sum-of-weights-corrected HESSE error matrix\n" - << " (error will be proportional to the number of events in MC).\n" - << " - Or provide SumW2Error(false), to return errors from original HESSE error matrix\n" - << " (which will be proportional to the sum of the weights, i.e., a dataset with events).\n" - << " - Or provide AsymptoticError(true), to use the asymptotically correct expression\n" - << " (for details see https://arxiv.org/abs/1911.01303)." - << endl ; - } - - if (cfg.minos && (cfg.doSumW2==1 || cfg.doAsymptotic == 1)) { - coutE(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << "): sum-of-weights and asymptotic error correction do not work with MINOS errors. Not fitting." << endl; - return nullptr; - } - if (cfg.doAsymptotic==1 && cfg.minos) { - coutW(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") WARNING: asymptotic correction does not apply to MINOS errors" << endl ; - } - - //avoid setting both SumW2 and Asymptotic for uncertainty correction - if (cfg.doSumW2==1 && cfg.doAsymptotic==1) { - coutE(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") ERROR: Cannot compute both asymptotically correct and SumW2 errors." << endl ; - return nullptr; - } - - // Instantiate RooMinimizer - RooMinimizer::Config minimizerConfig; - minimizerConfig.enableParallelGradient = cfg.enableParallelGradient; - minimizerConfig.enableParallelDescent = cfg.enableParallelDescent; - minimizerConfig.parallelize = cfg.parallelize; - minimizerConfig.timingAnalysis = cfg.timingAnalysis; - RooMinimizer m(nll, minimizerConfig); - - m.setMinimizerType(cfg.minType.c_str()); - m.setEvalErrorWall(cfg.doEEWall); - m.setRecoverFromNaNStrength(cfg.recoverFromNaN); - m.setPrintEvalErrors(cfg.numee); - if (cfg.maxCalls > 0) m.setMaxFunctionCalls(cfg.maxCalls); - if (cfg.printLevel!=1) m.setPrintLevel(cfg.printLevel); - if (cfg.optConst) m.optimizeConst(cfg.optConst); // Activate constant term optimization - if (cfg.verbose) m.setVerbose(1); // Activate verbose options - if (cfg.doTimer) m.setProfile(1); // Activate timer options - if (cfg.strat!=1) m.setStrategy(cfg.strat); // Modify fit strategy - if (cfg.initHesse) m.hesse(); // Initialize errors with hesse - m.minimize(cfg.minType.c_str(), cfg.minAlg.c_str()); // Minimize using chosen algorithm - if (cfg.hesse) m.hesse(); // Evaluate errors with Hesse - - int corrCovQual = -1; - - if (m.getNPar()>0) { - if (cfg.doAsymptotic == 1) corrCovQual = calcAsymptoticCorrectedCovariance(m, data); // Asymptotically correct - if (cfg.doSumW2 == 1) corrCovQual = calcSumW2CorrectedCovariance(m, nll); - } - - if (cfg.minos) cfg.minosSet ? m.minos(*cfg.minosSet) : m.minos(); // Evaluate errs with Minos - - // Optionally return fit result - std::unique_ptr ret; - if (cfg.doSave) { - auto name = std::string("fitresult_") + GetName() + "_" + data.GetName(); - auto title = std::string("Result of fit of p.d.f. ") + GetName() + " to dataset " + data.GetName(); - ret.reset(m.save(name.c_str(),title.c_str())); - if((cfg.doSumW2==1 || cfg.doAsymptotic==1) && m.getNPar()>0) ret->setCovQual(corrCovQual); - } - - if (cfg.optConst) m.optimizeConst(0) ; - return ret ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Fit PDF to given dataset. If dataset is unbinned, an unbinned maximum likelihood is performed. If the dataset -/// is binned, a binned maximum likelihood is performed. By default the fit is executed through the MINUIT -/// commands MIGRAD, HESSE in succession. -/// \param[in] data Data to fit the PDF to -/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 One or more arguments to control the behaviour of the fit -/// \return RooFitResult with fit status and parameters if option Save() is used, `nullptr` otherwise. The user takes ownership of the fit result. -/// -/// The following named arguments are supported -/// -/// -///
    Type of CmdArg Options to control construction of -log(L) -///
    `ConditionalObservables(Args_t &&... argsOrArgSet)` Do not normalize PDF over listed observables. -// Arguments can either be multiple RooRealVar or a single RooArgSet containing them. -///
    `Extended(bool flag)` Add extended likelihood term, off by default -///
    `Range(const char* name)` Fit only data inside range with given name. Multiple comma-separated range names can be specified. -/// In this case, the unnormalized PDF \f$f(x)\f$ is normalized by the integral over all ranges \f$r_i\f$: -/// \f[ -/// p(x) = \frac{f(x)}{\sum_i \int_{r_i} f(x) dx}. -/// \f] -///
    `Range(double lo, double hi)` Fit only data inside given range. A range named "fit" is created on the fly on all observables. -///
    `SumCoefRange(const char* name)` Set the range in which to interpret the coefficients of RooAddPdf components -///
    `NumCPU(int num, int strat)` Parallelize NLL calculation on `num` CPUs -/// -///
    Strategy Effect -///
    0 = RooFit::BulkPartition (Default) Divide events in N equal chunks -///
    1 = RooFit::Interleave Process event i%N in process N. Recommended for binned data with -/// a substantial number of zero-bins, which will be distributed across processes more equitably in this strategy -///
    2 = RooFit::SimComponents Process each component likelihood of a RooSimultaneous fully in a single process -/// and distribute components over processes. This approach can be benificial if normalization calculation time -/// dominates the total computation time of a component (since the normalization calculation must be performed -/// in each process in strategies 0 and 1. However beware that if the RooSimultaneous components do not share many -/// parameters this strategy is inefficient: as most minuit-induced likelihood calculations involve changing -/// a single parameter, only 1 of the N processes will be active most of the time if RooSimultaneous components -/// do not share many parameters -///
    3 = RooFit::Hybrid Follow strategy 0 for all RooSimultaneous components, except those with less than -/// 30 dataset entries, for which strategy 2 is followed. -///
    -///
    `SplitRange(bool flag)` Use separate fit ranges in a simultaneous fit. Actual range name for each subsample is assumed -/// to by `rangeName_indexState` where indexState is the state of the master index category of the simultaneous fit. -/// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this: -/// ``` -/// myVariable.setRange("range_pi0", 135, 210); -/// myVariable.setRange("range_gamma", 50, 210); -/// ``` -///
    `Constrain(const RooArgSet&pars)` For p.d.f.s that contain internal parameter constraint terms (that is usually product PDFs, where one -/// term of the product depends on parameters but not on the observable(s),), only apply constraints to the given subset of parameters. -///
    `ExternalConstraints(const RooArgSet& )` Include given external constraints to likelihood by multiplying them with the original likelihood. -///
    `GlobalObservables(const RooArgSet&)` Define the set of normalization observables to be used for the constraint terms. -/// If none are specified the constrained parameters are used. -///
    `Offset(std::string const& mode)` Likelihood offsetting mode. See createNLL(RooAbsData&, RooLinkedList const&). -///
    `BatchMode(bool on)` **Experimental** batch evaluation mode. This computes a batch of likelihood values at a time, -/// uses faster math functions and possibly auto vectorisation (this depends on the compiler flags). -/// Depending on hardware capabilities, the compiler flags and whether a batch evaluation function was -/// implemented for the PDFs of the model, likelihood computations are 2x to 10x faster. -/// The relative difference of the single log-likelihoods w.r.t. the legacy mode is usually better than 1.E-12, -/// and fit parameters usually agree to better than 1.E-6. -///
    `IntegrateBins(double precision)` In binned fits, integrate the PDF over the bins instead of using the probability density at the bin centre. -/// This can reduce the bias observed when fitting functions with high curvature to binned data. -/// - precision > 0: Activate bin integration everywhere. Use precision between 0.01 and 1.E-6, depending on binning. -/// Note that a low precision such as 0.01 might yield identical results to 1.E-4, since the integrator might reach 1.E-4 already in its first -/// integration step. If lower precision is desired (more speed), a RooBinSamplingPdf has to be created manually, and its integrator -/// has to be manipulated directly. -/// - precision = 0: Activate bin integration only for continuous PDFs fit to a RooDataHist. -/// - precision < 0: Deactivate. -/// \see RooBinSamplingPdf -/// -///
    Options to control flow of fit procedure -///
    `Minimizer("", "")` Choose minimization package and optionally the algorithm to use. Default is MINUIT/MIGRAD through the RooMinimizer interface, -/// but others can be specified (through RooMinimizer interface). -/// -///
    Type Algorithm -///
    Minuit migrad, simplex, minimize (=migrad+simplex), migradimproved (=migrad+improve) -///
    Minuit2 migrad, simplex, minimize, scan -///
    GSLMultiMin conjugatefr, conjugatepr, bfgs, bfgs2, steepestdescent -///
    GSLSimAn - -///
    -/// -///
    `InitialHesse(bool flag)` Flag controls if HESSE before MIGRAD as well, off by default -///
    `Optimize(bool flag)` Activate constant term optimization of test statistic during minimization (on by default) -///
    `Hesse(bool flag)` Flag controls if HESSE is run after MIGRAD, on by default -///
    `Minos(bool flag)` Flag controls if MINOS is run after HESSE, off by default -///
    `Minos(const RooArgSet& set)` Only run MINOS on given subset of arguments -///
    `Save(bool flag)` Flag controls if RooFitResult object is produced and returned, off by default -///
    `Strategy(Int_t flag)` Set Minuit strategy (0 to 2, default is 1) -///
    `MaxCalls(int n)` Change maximum number of likelihood function calss from MINUIT (if `n <= 0`, the default of 500 * #%parameters is used) -///
    `EvalErrorWall(bool flag=true)` When parameters are in disallowed regions (e.g. PDF is negative), return very high value to fitter -/// to force it out of that region. This can, however, mean that the fitter gets lost in this region. If -/// this happens, try switching it off. -///
    `RecoverFromUndefinedRegions(double strength)` When PDF is invalid (e.g. parameter in undefined region), try to direct minimiser away from that region. -/// `strength` controls the magnitude of the penalty term. Leaving out this argument defaults to 10. Switch off with `strength = 0.`. -/// -///
    `SumW2Error(bool flag)` Apply correction to errors and covariance matrix. -/// This uses two covariance matrices, one with the weights, the other with squared weights, -/// to obtain the correct errors for weighted likelihood fits. If this option is activated, the -/// corrected covariance matrix is calculated as \f$ V_\mathrm{corr} = V C^{-1} V \f$, where \f$ V \f$ is the original -/// covariance matrix and \f$ C \f$ is the inverse of the covariance matrix calculated using the -/// squared weights. This allows to switch between two interpretations of errors: -/// -///
    SumW2Error Interpretation -///
    true The errors reflect the uncertainty of the Monte Carlo simulation. -/// Use this if you want to know how much accuracy you can get from the available Monte Carlo statistics. -/// -/// **Example**: Simulation with 1000 events, the average weight is 0.1. -/// The errors are as big as if one fitted to 1000 events. -///
    false The errors reflect the errors of a dataset, which is as big as the sum of weights. -/// Use this if you want to know what statistical errors you would get if you had a dataset with as many -/// events as the (weighted) Monte Carlo simulation represents. -/// -/// **Example** (Data as above): -/// The errors are as big as if one fitted to 100 events. -///
    -/// \note If the `SumW2Error` correction is enabled, the covariance matrix quality stored in the RooFitResult -/// object will be the minimum of the original covariance matrix quality and the quality of the covariance -/// matrix calculated with the squared weights. -///
    `AsymptoticError()` Use the asymptotically correct approach to estimate errors in the presence of weights. -/// This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303). -///
    `PrefitDataFraction(double fraction)` -/// Runs a prefit on a small dataset of size fraction*(actual data size). This can speed up fits -/// by finding good starting values for the parameters for the actual fit. -/// \warning Prefitting may give bad results when used in binned analysis. -/// -///
    Options to control informational output -///
    `Verbose(bool flag)` Flag controls if verbose output is printed (NLL, parameter changes during fit). -///
    `Timer(bool flag)` Time CPU and wall clock consumption of fit steps, off by default. -///
    `PrintLevel(Int_t level)` Set Minuit print level (-1 to 3, default is 1). At -1 all RooFit informational messages are suppressed as well. -/// See RooMinimizer::PrintLevel for the meaning of the levels. -///
    `Warnings(bool flag)` Enable or disable MINUIT warnings (enabled by default) -///
    `PrintEvalErrors(Int_t numErr)` Control number of p.d.f evaluation errors printed per likelihood evaluation. -/// A negative value suppresses output completely, a zero value will only print the error count per p.d.f component, -/// a positive value will print details of each error up to `numErr` messages per p.d.f component. -///
    `ModularL(bool flag)` Enable or disable modular likelihoods, which will become the default in a future release. -/// This does not change any user-facing code, but only enables a different likelihood class in the back-end. -/// This option is forced to true in case parallelization is requested with the `Parallelize` named argument. -/// Note that it is currently not recommended to use modular likelihoods without any parallelization enabled, since -/// some features such as offsetting might not yet work in this case. -///
    `Parallelize(Int_t nWorkers)` Control global parallelization settings. Arguments 1 and above enable the use of RooFit's parallel minimization -/// backend and uses the number given as the number of workers to use in the parallelization. -1 also enables -/// RooFit's parallel minimization backend, and sets the number of workers to the number of available processes. -/// 0 disables this feature. -///
    `ParallelGradientOptions(bool enable=true, int orderStrategy=0, int chainFactor=1)` **Experimental** Control gradient parallelization settings. The first argument -/// only disables or enables gradient parallelization, this is on by default. -/// The second argument determines the internal partial derivative calculation -/// ordering strategy. The third argument determines the number of partial -/// derivatives that are executed per task package on each worker. -///
    `ParallelDescentOptions(bool enable=false, int splitStrategy=0, int numSplits=4)` **Experimental** Control settings related to the parallelization of likelihoods -/// outside of the gradient calculation but in the minimization, most prominently -/// in the linesearch step. The first argument this disables or enables likelihood -/// parallelization. The second argument determines whether to split the task batches -/// per event or per likelihood component. And the third argument how many events or -/// respectively components to include in each batch. -///
    `TimingAnalysis(bool flag)` **Experimental** log timings. This feature logs timings with NewStyle likelihoods on multiple processes simultaneously -/// and outputs the timings at the end of a run to json log files, which can be analyzed with the -/// `RooFit::MultiProcess::HeatmapAnalyzer`. Only works with simultaneous likelihoods. -///
    -/// - -RooFitResult* RooAbsPdf::fitTo(RooAbsData& data, const RooLinkedList& cmdList) + return nll; +} + + + +/** @fn RooAbsPdf::fitTo() + * + * @brief Fit PDF to given dataset. + * + * If dataset is unbinned, an unbinned maximum likelihood is performed. + * If the dataset is binned, a binned maximum likelihood is performed. + * By default the fit is executed through the MINUIT commands MIGRAD, HESSE in succession. + * + * @param data Reference to a RooAbsData object representing the dataset. + * @param cmdArgs Variadic template arguments representing optional command arguments. + * You can pass either an arbitrary number of RooCmdArg instances + * or a single RooLinkedList that points to the RooCmdArg objects. + * @return An owning pointer to the created RooAbsReal NLL object. + * @return RooFitResult with fit status and parameters if option Save() is used, `nullptr` otherwise. The user takes ownership of the fit result. + * + * @tparam CmdArgs_t Template types for optional command arguments. + * Can either be an arbitrary number of RooCmdArg or a single RooLinkedList. + * + * \note This front-end function should not be re-implemented in derived PDF types. + * If you mean to customize the likelihood fitting routine, + * you need to override the virtual RooAbsPdf::fitToImpl() method. + * + * The following named arguments are supported: + * + * + *
    Type of CmdArg Options to control construction of -log(L) + *
    All command arguments that can also be passed to the NLL creation method. + * \see RooAbsPdf::createNLL() + * + *
    Options to control flow of fit procedure + *
    `Minimizer("", "")` Choose minimization package and optionally the algorithm to use. Default is MINUIT/MIGRAD through the RooMinimizer interface, + * but others can be specified (through RooMinimizer interface). + * + *
    Type Algorithm + *
    Minuit migrad, simplex, minimize (=migrad+simplex), migradimproved (=migrad+improve) + *
    Minuit2 migrad, simplex, minimize, scan + *
    GSLMultiMin conjugatefr, conjugatepr, bfgs, bfgs2, steepestdescent + *
    GSLSimAn - + *
    + * + *
    `InitialHesse(bool flag)` Flag controls if HESSE before MIGRAD as well, off by default + *
    `Optimize(bool flag)` Activate constant term optimization of test statistic during minimization (on by default) + *
    `Hesse(bool flag)` Flag controls if HESSE is run after MIGRAD, on by default + *
    `Minos(bool flag)` Flag controls if MINOS is run after HESSE, off by default + *
    `Minos(const RooArgSet& set)` Only run MINOS on given subset of arguments + *
    `Save(bool flag)` Flag controls if RooFitResult object is produced and returned, off by default + *
    `Strategy(Int_t flag)` Set Minuit strategy (0 to 2, default is 1) + *
    `MaxCalls(int n)` Change maximum number of likelihood function calls from MINUIT (if `n <= 0`, the default of 500 * #%parameters is used) + *
    `EvalErrorWall(bool flag=true)` When parameters are in disallowed regions (e.g. PDF is negative), return very high value to fitter + * to force it out of that region. This can, however, mean that the fitter gets lost in this region. If + * this happens, try switching it off. + *
    `RecoverFromUndefinedRegions(double strength)` When PDF is invalid (e.g. parameter in undefined region), try to direct minimiser away from that region. + * `strength` controls the magnitude of the penalty term. Leaving out this argument defaults to 10. Switch off with `strength = 0.`. + * + *
    `SumW2Error(bool flag)` Apply correction to errors and covariance matrix. + * This uses two covariance matrices, one with the weights, the other with squared weights, + * to obtain the correct errors for weighted likelihood fits. If this option is activated, the + * corrected covariance matrix is calculated as \f$ V_\mathrm{corr} = V C^{-1} V \f$, where \f$ V \f$ is the original + * covariance matrix and \f$ C \f$ is the inverse of the covariance matrix calculated using the + * squared weights. This allows to switch between two interpretations of errors: + * + *
    SumW2Error Interpretation + *
    true The errors reflect the uncertainty of the Monte Carlo simulation. + * Use this if you want to know how much accuracy you can get from the available Monte Carlo statistics. + * + * **Example**: Simulation with 1000 events, the average weight is 0.1. + * The errors are as big as if one fitted to 1000 events. + *
    false The errors reflect the errors of a dataset, which is as big as the sum of weights. + * Use this if you want to know what statistical errors you would get if you had a dataset with as many + * events as the (weighted) Monte Carlo simulation represents. + * + * **Example** (Data as above): + * The errors are as big as if one fitted to 100 events. + *
    + * \note If the `SumW2Error` correction is enabled, the covariance matrix quality stored in the RooFitResult + * object will be the minimum of the original covariance matrix quality and the quality of the covariance + * matrix calculated with the squared weights. + *
    `AsymptoticError()` Use the asymptotically correct approach to estimate errors in the presence of weights. + * This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303). + *
    `PrefitDataFraction(double fraction)` + * Runs a prefit on a small dataset of size fraction*(actual data size). This can speed up fits + * by finding good starting values for the parameters for the actual fit. + * \warning Prefitting may give bad results when used in binned analysis. + * + *
    Options to control informational output + *
    `Verbose(bool flag)` Flag controls if verbose output is printed (NLL, parameter changes during fit). + *
    `Timer(bool flag)` Time CPU and wall clock consumption of fit steps, off by default. + *
    `PrintLevel(Int_t level)` Set Minuit print level (-1 to 3, default is 1). At -1 all RooFit informational messages are suppressed as well. + * See RooMinimizer::PrintLevel for the meaning of the levels. + *
    `Warnings(bool flag)` Enable or disable MINUIT warnings (enabled by default) + *
    `PrintEvalErrors(Int_t numErr)` Control number of p.d.f evaluation errors printed per likelihood evaluation. + * A negative value suppresses output completely, a zero value will only print the error count per p.d.f component, + * a positive value will print details of each error up to `numErr` messages per p.d.f component. + *
    `Parallelize(Int_t nWorkers)` Control global parallelization settings. Arguments 1 and above enable the use of RooFit's parallel minimization + * backend and uses the number given as the number of workers to use in the parallelization. -1 also enables + * RooFit's parallel minimization backend, and sets the number of workers to the number of available processes. + * 0 disables this feature. + * In case parallelization is requested, this option implies `ModularL(true)` in the internal call to the NLL creation method. + *
    `ParallelGradientOptions(bool enable=true, int orderStrategy=0, int chainFactor=1)` **Experimental** - Control gradient parallelization settings. The first argument + * only disables or enables gradient parallelization, this is on by default. + * The second argument determines the internal partial derivative calculation + * ordering strategy. The third argument determines the number of partial + * derivatives that are executed per task package on each worker. + *
    `ParallelDescentOptions(bool enable=false, int splitStrategy=0, int numSplits=4)` **Experimental** - Control settings related to the parallelization of likelihoods + * outside of the gradient calculation but in the minimization, most prominently + * in the linesearch step. The first argument this disables or enables likelihood + * parallelization. The second argument determines whether to split the task batches + * per event or per likelihood component. And the third argument how many events or + * respectively components to include in each batch. + *
    `TimingAnalysis(bool flag)` **Experimental** - Log timings. This feature logs timings with NewStyle likelihoods on multiple processes simultaneously + * and outputs the timings at the end of a run to json log files, which can be analyzed with the + * `RooFit::MultiProcess::HeatmapAnalyzer`. Only works with simultaneous likelihoods. + *
    + */ + + +/** @brief Protected implementation of the likelihood fitting routine. + * + * This virtual function can be overridden in case you want to change the likelihood fitting logic for custom PDFs. + * + * \note Never call this function directly. Instead, call RooAbsPdf::fitTo(). + */ + +std::unique_ptr RooAbsPdf::fitToImpl(RooAbsData& data, const RooLinkedList& cmdList) { // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::fitTo(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::fitTo(" + std::string(GetName()) + ")"); RooLinkedList fitCmdList(cmdList) ; - RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList,"ProjectedObservables,Extended,Range," + std::string nllCmdListString = "ProjectedObservables,Extended,Range," "RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints," - "CloneData,GlobalObservables,GlobalObservablesSource,GlobalObservablesTag,OffsetLikelihood," - "BatchMode,IntegrateBins,ModularL"); + "CloneData,GlobalObservables,GlobalObservablesSource,GlobalObservablesTag," + "EvalBackend,IntegrateBins,ModularL"; - // Default-initialized instance of MinimizerConfig to get the default - // minimizer parameter values. - MinimizerConfig minimizerDefaults; + if (!cmdList.FindObject("ModularL") || static_cast(cmdList.FindObject("ModularL"))->getInt(0) == 0) + nllCmdListString += ",OffsetLikelihood"; + + RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList, nllCmdListString.c_str()); pc.defineDouble("prefit", "Prefit",0,0); - pc.defineDouble("RecoverFromUndefinedRegions", "RecoverFromUndefinedRegions",0,minimizerDefaults.recoverFromNaN); - pc.defineInt("optConst","Optimize",0,minimizerDefaults.optConst) ; - pc.defineInt("verbose","Verbose",0,minimizerDefaults.verbose) ; - pc.defineInt("doSave","Save",0,minimizerDefaults.doSave) ; - pc.defineInt("doTimer","Timer",0,minimizerDefaults.doTimer) ; - pc.defineInt("printLevel","PrintLevel",0,minimizerDefaults.printLevel) ; - pc.defineInt("strat","Strategy",0,minimizerDefaults.strat) ; - pc.defineInt("initHesse","InitialHesse",0,minimizerDefaults.initHesse) ; - pc.defineInt("hesse","Hesse",0,minimizerDefaults.hesse) ; - pc.defineInt("minos","Minos",0,minimizerDefaults.minos) ; - pc.defineInt("numee","PrintEvalErrors",0,minimizerDefaults.numee) ; - pc.defineInt("doEEWall","EvalErrorWall",0,minimizerDefaults.doEEWall) ; - pc.defineInt("doWarn","Warnings",0,minimizerDefaults.doWarn) ; - pc.defineInt("doSumW2","SumW2Error",0,minimizerDefaults.doSumW2) ; - pc.defineInt("doAsymptoticError","AsymptoticError",0,minimizerDefaults.doAsymptotic) ; - pc.defineInt("maxCalls","MaxCalls",0,minimizerDefaults.maxCalls); - pc.defineInt("doOffset","OffsetLikelihood",0,0) ; - pc.defineInt("parallelize", "Parallelize", 0, 0); // Three parallelize arguments - pc.defineInt("enableParallelGradient", "ParallelGradientOptions", 0, 0); - pc.defineInt("enableParallelDescent", "ParallelDescentOptions", 0, 0); - pc.defineInt("timingAnalysis", "TimingAnalysis", 0, 0); - pc.defineString("mintype","Minimizer",0,minimizerDefaults.minType.c_str()) ; - pc.defineString("minalg","Minimizer",1,minimizerDefaults.minAlg.c_str()) ; - pc.defineSet("minosSet","Minos",0,minimizerDefaults.minosSet) ; - pc.defineMutex("Range","RangeWithName") ; + RooFit::FitHelpers::defineMinimizationOptions(pc); // Process and check varargs pc.process(fitCmdList) ; if (!pc.ok(true)) { - return 0 ; + return nullptr; } - // TimingAnalysis works only for RooSimultaneus. + // TimingAnalysis works only for RooSimultaneous. if (pc.getInt("timingAnalysis") && !this->InheritsFrom("RooSimultaneous") ) { - coutW(Minimization) << "The timingAnalysis feature was built for minimization with RooSimulteneous " - "and is not implemented for other PDF's. Please create a RooSimultenous to " + coutW(Minimization) << "The timingAnalysis feature was built for minimization with RooSimultaneous " + "and is not implemented for other PDF's. Please create a RooSimultaneous to " "enable this feature." << endl; } // Decode command line arguments double prefit = pc.getDouble("prefit"); - Int_t optConst = pc.getInt("optConst") ; - - if (optConst > 1) { - // optConst >= 2 is pre-computating values, which are never used when - // the batchMode is on. This just wastes time. - - RooCmdConfig conf(Form("RooAbsPdf::fitTo(%s)", GetName())); - conf.defineInt("BatchMode","BatchMode",0,0); - conf.allowUndefined(true); - conf.process(nllCmdList); - if (conf.getInt("BatchMode") != 0) { - optConst = 1; - } - } if (prefit != 0) { size_t nEvents = static_cast(prefit*data.numEntries()); @@ -1646,13 +1467,9 @@ RooFitResult* RooAbsPdf::fitTo(RooAbsData& data, const RooLinkedList& cmdList) } else { size_t step = data.numEntries()/nEvents; - RooArgSet tinyVars(*data.get()); - RooRealVar weight("weight","weight",1); - - if (data.isWeighted()) tinyVars.add(weight); - RooDataSet tiny("tiny", "tiny", tinyVars, - data.isWeighted() ? RooFit::WeightVar(weight) : RooCmdArg()); + RooDataSet tiny("tiny", "tiny", *data.get(), + data.isWeighted() ? RooFit::WeightVar() : RooCmdArg()); for (int i=0; i nll{createNLL(data,nllCmdList)}; - MinimizerConfig cfg; - cfg.recoverFromNaN = pc.getDouble("RecoverFromUndefinedRegions"); - cfg.optConst = optConst; - cfg.verbose = pc.getInt("verbose"); - cfg.doSave = pc.getInt("doSave"); - cfg.doTimer = pc.getInt("doTimer"); - cfg.printLevel = pc.getInt("printLevel"); - cfg.strat = pc.getInt("strat"); - cfg.initHesse = pc.getInt("initHesse"); - cfg.hesse = pc.getInt("hesse"); - cfg.minos = pc.getInt("minos"); - cfg.numee = pc.getInt("numee"); - cfg.doEEWall = pc.getInt("doEEWall"); - cfg.doWarn = pc.getInt("doWarn"); - cfg.doSumW2 = pc.getInt("doSumW2"); - cfg.doAsymptotic = pc.getInt("doAsymptoticError"); - cfg.maxCalls = pc.getInt("maxCalls"); - cfg.minosSet = pc.getSet("minosSet"); - cfg.minType = pc.getString("mintype",""); - cfg.minAlg = pc.getString("minalg","minuit"); - cfg.parallelize = pc.getInt("parallelize"); - cfg.enableParallelGradient = pc.getInt("enableParallelGradient"); - cfg.enableParallelDescent = pc.getInt("enableParallelDescent"); - cfg.timingAnalysis = pc.getInt("timingAnalysis"); - return minimizeNLL(*nll, data, cfg).release(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Calls RooAbsPdf::createChi2(RooDataSet& data, const RooLinkedList& cmdList) and returns fit result. - -RooFitResult* RooAbsPdf::chi2FitTo(RooDataHist& data, const RooLinkedList& cmdList) -{ - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::chi2FitTo(%s)",GetName())) ; - - // Pull arguments to be passed to chi2 construction from list - RooLinkedList fitCmdList(cmdList) ; - RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList,"Range,RangeWithName,NumCPU,Optimize,ProjectedObservables,AddCoefRange,SplitRange,DataError,Extended,IntegrateBins") ; - - std::unique_ptr chi2{createChi2(data,chi2CmdList)}; - return chi2FitDriver(*chi2,fitCmdList) ; -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Create a \f$ \chi^2 \f$ from a histogram and this function. -/// -/// Options to control construction of the chi-square -/// ------------------------------------------ -/// The list of supported command arguments is given in the documentation for -/// RooChi2Var::RooChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataHist& hdata, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&). - -RooAbsReal* RooAbsPdf::createChi2(RooDataHist& data, const RooCmdArg& arg1, const RooCmdArg& arg2, - const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, - const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) -{ - RooLinkedList cmdList ; - cmdList.Add((TObject*)&arg1) ; cmdList.Add((TObject*)&arg2) ; - cmdList.Add((TObject*)&arg3) ; cmdList.Add((TObject*)&arg4) ; - cmdList.Add((TObject*)&arg5) ; cmdList.Add((TObject*)&arg6) ; - cmdList.Add((TObject*)&arg7) ; cmdList.Add((TObject*)&arg8) ; - - RooCmdConfig pc(Form("RooAbsPdf::createChi2(%s)",GetName())) ; - pc.defineString("rangeName","RangeWithName",0,"",true) ; - pc.allowUndefined(true) ; - pc.process(cmdList) ; - if (!pc.ok(true)) { - return 0 ; - } - const char* rangeName = pc.getString("rangeName",0,true) ; - - // Construct Chi2 - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal* chi2 ; - string baseName = Form("chi2_%s_%s",GetName(),data.GetName()) ; - - // Clear possible range attributes from previous fits. - removeStringAttribute("fitrange"); - - if (!rangeName || strchr(rangeName,',')==0) { - // Simple case: default range, or single restricted range - - chi2 = new RooChi2Var(baseName.c_str(),baseName.c_str(),*this,data,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; - - } else { - - // Find which argument is RangeWithName - const RooCmdArg* rarg(0) ; - string rcmd = "RangeWithName" ; - if (arg1.GetName()==rcmd) rarg = &arg1 ; - if (arg2.GetName()==rcmd) rarg = &arg2 ; - if (arg3.GetName()==rcmd) rarg = &arg3 ; - if (arg4.GetName()==rcmd) rarg = &arg4 ; - if (arg5.GetName()==rcmd) rarg = &arg5 ; - if (arg6.GetName()==rcmd) rarg = &arg6 ; - if (arg7.GetName()==rcmd) rarg = &arg7 ; - if (arg8.GetName()==rcmd) rarg = &arg8 ; - - // Composite case: multiple ranges - RooArgList chi2List ; - for (std::string& token : ROOT::Split(rangeName, ",")) { - RooCmdArg subRangeCmd = RooFit::Range(token.c_str()) ; - // Construct chi2 while substituting original RangeWithName argument with subrange argument created above - RooAbsReal* chi2Comp = new RooChi2Var(Form("%s_%s", baseName.c_str(), token.c_str()), "chi^2", *this, data, - &arg1==rarg?subRangeCmd:arg1,&arg2==rarg?subRangeCmd:arg2, - &arg3==rarg?subRangeCmd:arg3,&arg4==rarg?subRangeCmd:arg4, - &arg5==rarg?subRangeCmd:arg5,&arg6==rarg?subRangeCmd:arg6, - &arg7==rarg?subRangeCmd:arg7,&arg8==rarg?subRangeCmd:arg8) ; - chi2List.add(*chi2Comp) ; - } - chi2 = new RooAddition(baseName.c_str(),"chi^2",chi2List,true) ; - } - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - - - return chi2 ; -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Argument-list version of RooAbsPdf::createChi2() - -RooAbsReal* RooAbsPdf::createChi2(RooDataSet& data, const RooLinkedList& cmdList) -{ - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::createChi2(%s)",GetName())) ; - - pc.defineInt("integrate","Integrate",0,0) ; - pc.defineObject("yvar","YVar",0,0) ; - - // Process and check varargs - pc.process(cmdList) ; - if (!pc.ok(true)) { - return 0 ; - } - - // Decode command line arguments - bool integrate = pc.getInt("integrate") ; - RooRealVar* yvar = (RooRealVar*) pc.getObject("yvar") ; - - string name = Form("chi2_%s_%s",GetName(),data.GetName()) ; - - if (yvar) { - return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,*yvar,integrate) ; - } else { - return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,integrate) ; - } + return RooFit::FitHelpers::minimize(*this, *nll, data, pc); } - - //////////////////////////////////////////////////////////////////////////////// /// Print value of p.d.f, also print normalization integral that was last used, if any @@ -1849,9 +1512,9 @@ void RooAbsPdf::printValue(ostream& os) const getVal() ; if (_norm) { - os << evaluate() << "/" << _norm->getVal() ; + os << getVal() << "/" << _norm->getVal() ; } else { - os << evaluate() ; + os << getVal(); } } @@ -1970,11 +1633,11 @@ RooAbsGenContext* RooAbsPdf::autoGenContext(const RooArgSet &vars, const RooData /// - chatLevel /// \see rf902_numgenconfig.C -RooDataSet *RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2, const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6) { // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::generate(" + std::string(GetName()) + ")"); pc.defineObject("proto","PrototypeData",0,0) ; pc.defineString("dsetName","Name",0,"") ; pc.defineInt("randProto","PrototypeData",0,0) ; @@ -1992,7 +1655,7 @@ RooDataSet *RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1 // Process and check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6) ; if (!pc.ok(true)) { - return 0 ; + return nullptr; } // Decode command line arguments @@ -2032,11 +1695,11 @@ RooDataSet *RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1 // Forward to appropriate implementation - RooDataSet* data ; + std::unique_ptr data; if (protoData) { - data = generate(whatVars,*protoData,Int_t(nEvents),verbose,randProto,resampleProto) ; + data = std::unique_ptr{generate(whatVars,*protoData,Int_t(nEvents),verbose,randProto,resampleProto)}; } else { - data = generate(whatVars,nEvents,verbose,autoBinned,binnedTag,expectedData, extended) ; + data = std::unique_ptr{generate(whatVars,nEvents,verbose,autoBinned,binnedTag,expectedData, extended)}; } // Rename dataset to given name if supplied @@ -2044,7 +1707,7 @@ RooDataSet *RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1 data->SetName(dsetName) ; } - return data ; + return RooFit::Detail::owningPtr(std::move(data)); } @@ -2066,7 +1729,7 @@ RooAbsPdf::GenSpec* RooAbsPdf::prepareMultiGen(const RooArgSet &whatVars, { // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::generate(" + std::string(GetName()) + ")"); pc.defineObject("proto","PrototypeData",0,0) ; pc.defineString("dsetName","Name",0,"") ; pc.defineInt("randProto","PrototypeData",0,0) ; @@ -2108,7 +1771,7 @@ RooAbsPdf::GenSpec* RooAbsPdf::prepareMultiGen(const RooArgSet &whatVars, /// combination than calling the standard generate() multiple times as /// initialization overhead is only incurred once. -RooDataSet *RooAbsPdf::generate(RooAbsPdf::GenSpec& spec) const +RooFit::OwningPtr RooAbsPdf::generate(RooAbsPdf::GenSpec& spec) const { //Int_t nEvt = spec._extended ? RooRandom::randomGenerator()->Poisson(spec._nGen) : spec._nGen ; //Int_t nEvt = spec._extended ? RooRandom::randomGenerator()->Poisson(spec._nGen==0?expectedEvents(spec._whatVars):spec._nGen) : spec._nGen ; @@ -2116,10 +1779,10 @@ RooDataSet *RooAbsPdf::generate(RooAbsPdf::GenSpec& spec) const double nEvt = spec._nGen == 0 ? expectedEvents(spec._whatVars) : spec._nGen; - RooDataSet* ret = generate(*spec._genContext,spec._whatVars,spec._protoData, nEvt,false,spec._randProto,spec._resampleProto, - spec._init,spec._extended) ; + std::unique_ptr ret{generate(*spec._genContext,spec._whatVars,spec._protoData, nEvt,false,spec._randProto,spec._resampleProto, + spec._init,spec._extended)}; spec._init = true ; - return ret ; + return RooFit::Detail::owningPtr(std::move(ret)); } @@ -2145,10 +1808,10 @@ RooDataSet *RooAbsPdf::generate(RooAbsPdf::GenSpec& spec) const /// \return New dataset. Returns zero in case of an error. The caller takes ownership of the returned /// dataset. -RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, double nEvents, bool verbose, bool autoBinned, const char* binnedTag, bool expectedData, bool extended) const +RooFit::OwningPtr RooAbsPdf::generate(const RooArgSet &whatVars, double nEvents, bool verbose, bool autoBinned, const char* binnedTag, bool expectedData, bool extended) const { if (nEvents==0 && extendMode()==CanNotBeExtended) { - return new RooDataSet("emptyData","emptyData",whatVars) ; + return RooFit::Detail::owningPtr(std::make_unique("emptyData","emptyData",whatVars)); } // Request for binned generation @@ -2157,14 +1820,14 @@ RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, double nEvents, bool context->setExpectedData(true) ; } - RooDataSet *generated = 0; + std::unique_ptr generated; if(0 != context && context->isValid()) { - generated= context->generate(nEvents, false, extended); + generated = std::unique_ptr{context->generate(nEvents, false, extended)}; } else { coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") cannot create a valid context" << endl; } - return generated; + return RooFit::Detail::owningPtr(std::move(generated)); } @@ -2173,15 +1836,15 @@ RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, double nEvents, bool //////////////////////////////////////////////////////////////////////////////// /// Internal method -RooDataSet *RooAbsPdf::generate(RooAbsGenContext& context, const RooArgSet &whatVars, const RooDataSet *prototype, +std::unique_ptr RooAbsPdf::generate(RooAbsGenContext& context, const RooArgSet &whatVars, const RooDataSet *prototype, double nEvents, bool /*verbose*/, bool randProtoOrder, bool resampleProto, bool skipInit, bool extended) const { if (nEvents==0 && (prototype==0 || prototype->numEntries()==0)) { - return new RooDataSet("emptyData","emptyData",whatVars) ; + return std::make_unique("emptyData","emptyData",whatVars); } - RooDataSet *generated = 0; + std::unique_ptr generated; // Resampling implies reshuffling in the implementation if (resampleProto) { @@ -2196,7 +1859,7 @@ RooDataSet *RooAbsPdf::generate(RooAbsGenContext& context, const RooArgSet &what } if(context.isValid()) { - generated= context.generate(nEvents,skipInit,extended); + generated = std::unique_ptr{context.generate(nEvents,skipInit,extended)}; } else { coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") do not have a valid generator context" << endl; @@ -2229,17 +1892,15 @@ RooDataSet *RooAbsPdf::generate(RooAbsGenContext& context, const RooArgSet &what /// \return The new dataset. Returns zero in case of an error. The caller takes ownership of the /// returned dataset. -RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, const RooDataSet& prototype, +RooFit::OwningPtr RooAbsPdf::generate(const RooArgSet &whatVars, const RooDataSet& prototype, Int_t nEvents, bool verbose, bool randProtoOrder, bool resampleProto) const { std::unique_ptr context{genContext(whatVars,&prototype,0,verbose)}; if (context) { - RooDataSet* data = generate(*context,whatVars,&prototype,nEvents,verbose,randProtoOrder,resampleProto) ; - return data ; - } else { - coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") ERROR creating generator context" << endl ; - return nullptr; + return RooFit::Detail::owningPtr(generate(*context,whatVars,&prototype,nEvents,verbose,randProtoOrder,resampleProto)); } + coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") ERROR creating generator context" << endl ; + return nullptr; } @@ -2280,7 +1941,7 @@ Int_t* RooAbsPdf::randomizeProtoOrder(Int_t nProto, Int_t, bool resampleProto) c /// and return a code that specifies the generator algorithm we will use. A code of /// zero indicates that we cannot generate any of the directVars (in this case, nothing /// should be added to generatedVars). Any non-zero codes will be passed to our generateEvent() -/// implementation, but otherwise its value is arbitrary. The default implemetation of +/// implementation, but otherwise its value is arbitrary. The default implementation of /// this method returns zero. Subclasses will usually implement this method using the /// matchArgs() methods to advertise the algorithms they provide. @@ -2356,17 +2017,16 @@ bool RooAbsPdf::isDirectGenSafe(const RooAbsArg& arg) const /// | `Name(const char* name)` | Name of the output dataset /// | `Verbose(bool flag)` | Print informational messages during event generation /// | `NumEvents(int nevt)` | Generate specified number of events -/// | `Extended()` | The actual number of events generated will be sampled from a Poisson distribution with mu=nevt. -/// This can be *much* faster for peaked PDFs, but the number of events is not exactly what was requested. +/// | `Extended()` | The actual number of events generated will be sampled from a Poisson distribution with mu=nevt. This can be *much* faster for peaked PDFs, but the number of events is not exactly what was requested. /// | `ExpectedData()` | Return a binned dataset _without_ statistical fluctuations (also aliased as Asimov()) /// -RooDataHist *RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2, const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6) const { // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::generate(" + std::string(GetName()) + ")"); pc.defineString("dsetName","Name",0,"") ; pc.defineInt("verbose","Verbose",0,0) ; pc.defineInt("extended","Extended",0,0) ; @@ -2377,7 +2037,7 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdAr // Process and check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6) ; if (!pc.ok(true)) { - return 0 ; + return nullptr; } // Decode command line arguments @@ -2405,14 +2065,14 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdAr } // Forward to appropriate implementation - RooDataHist* data = generateBinned(whatVars,nEvents,expectedData,extended) ; + auto data = generateBinned(whatVars,nEvents,expectedData,extended); // Rename dataset to given name if supplied if (dsetName && strlen(dsetName)>0) { data->SetName(dsetName) ; } - return data ; + return data; } @@ -2443,16 +2103,15 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdAr /// Any variables of this PDF that are not in `whatVars` will use their /// current values and be treated as fixed parameters. /// \return RooDataHist* owned by the caller. Returns `nullptr` in case of an error. -RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents, bool expectedData, bool extended) const +RooFit::OwningPtr RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents, bool expectedData, bool extended) const { // Create empty RooDataHist - RooDataHist* hist = new RooDataHist("genData","genData",whatVars) ; + auto hist = std::make_unique("genData","genData",whatVars); // Scale to number of events and introduce Poisson fluctuations if (nEvents<=0) { if (!canBeExtended()) { coutE(InputArguments) << "RooAbsPdf::generateBinned(" << GetName() << ") ERROR: No event count provided and p.d.f does not provide expected number of events" << endl ; - delete hist ; return nullptr; } else { @@ -2466,7 +2125,7 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents } // Sample p.d.f. distribution - fillDataHist(hist,&whatVars,1,true) ; + fillDataHist(hist.get(),&whatVars,1,true) ; vector histOut(hist->numEntries()) ; double histMax(-1) ; @@ -2503,7 +2162,7 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents // Second pass for regular mode - Trim/Extend dataset to exact number of entries // Calculate difference between what is generated so far and what is requested - Int_t nEvtExtra = abs(Int_t(nEvents)-histOutSum) ; + Int_t nEvtExtra = std::abs(Int_t(nEvents)-histOutSum) ; Int_t wgt = (histOutSum>nEvents) ? -1 : 1 ; // Perform simple binned accept/reject procedure to get to exact event count @@ -2555,7 +2214,7 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents } - return hist; + return RooFit::Detail::owningPtr(std::move(hist)); } @@ -2563,7 +2222,7 @@ RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, double nEvents //////////////////////////////////////////////////////////////////////////////// /// Special generator interface for generation of 'global observables' -- for RooStats tools -RooDataSet* RooAbsPdf::generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) +RooFit::OwningPtr RooAbsPdf::generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) { return generate(whatVars,nEvents) ; } @@ -2638,7 +2297,7 @@ void removeRangeOverlap(std::vector>& ranges) { /// `Name(const chat* name)` Give curve specified name in frame. Useful if curve is to be referenced later /// `Asymmetry(const RooCategory& c)` Show the asymmetry of the PDF in given two-state category /// \f$ \frac{F(+)-F(-)}{F(+)+F(-)} \f$ rather than the PDF projection. Category must have two -/// states with indices -1 and +1 or three states with indeces -1,0 and +1. +/// states with indices -1 and +1 or three states with indices -1,0 and +1. /// `ShiftToZero(bool flag)` Shift entire curve such that lowest visible point is at exactly zero. /// Mostly useful when plotting -log(L) or \f$ \chi^2 \f$ distributions /// `AddTo(const char* name, double_t wgtSelf, double_t wgtOther)` Create a projection of this PDF onto the x-axis, but @@ -2733,7 +2392,7 @@ RooPlot* RooAbsPdf::plotOn(RooPlot* frame, RooLinkedList& cmdList) const if (plotSanityChecks(frame)) return frame ; // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::plotOn(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::plotOn(" + std::string(GetName()) + ")"); pc.defineDouble("scaleFactor","Normalization",0,1.0) ; pc.defineInt("scaleType","Normalization",0,Relative) ; pc.defineSet("compSet","SelectCompSet",0) ; @@ -2770,9 +2429,7 @@ RooPlot* RooAbsPdf::plotOn(RooPlot* frame, RooLinkedList& cmdList) const nameSuffix.append(compSpec) ; nameSuffix.append("]") ; } else if (compSet) { - nameSuffix.append("_Comp[") ; - nameSuffix.append(compSet->contentsString().c_str()) ; - nameSuffix.append("]") ; + nameSuffix += "_Comp[" + compSet->contentsString() + "]"; } // Remove PDF-only commands from command list @@ -2845,7 +2502,7 @@ RooPlot* RooAbsPdf::plotOn(RooPlot* frame, RooLinkedList& cmdList) const ccoutI(Plotting) << endl ; } - nameSuffix.append(Form("_Range[%s]",pc.getString("rangeName"))) ; + nameSuffix.append("_Range[" + std::string(pc.getString("rangeName")) + "]"); } // Specification of a normalization range override those in a regular range if (pc.hasProcessed("NormRange")) { @@ -2863,7 +2520,7 @@ RooPlot* RooAbsPdf::plotOn(RooPlot* frame, RooLinkedList& cmdList) const hasCustomRange = true ; coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") p.d.f. curve is normalized using explicit choice of ranges '" << pc.getString("normRangeName", "", false) << "'" << endl ; - nameSuffix.append(Form("_NormRange[%s]",pc.getString("rangeName"))) ; + nameSuffix.append("_NormRange[" + std::string(pc.getString("rangeName")) + "]"); } @@ -2874,7 +2531,7 @@ RooPlot* RooAbsPdf::plotOn(RooPlot* frame, RooLinkedList& cmdList) const if (oldSize != rangeLim.size() && !pc.hasProcessed("NormRange")) { // User gave overlapping ranges. This leads to double-counting events and integrals, and must - // therefore be avoided. If a NormRange has been given, the overlap is alreay gone. + // therefore be avoided. If a NormRange has been given, the overlap is already gone. // It's safe to plot even with overlap now. coutE(Plotting) << "Requested plot/integration ranges overlap. For correct plotting, new ranges " "will be defined." << std::endl; @@ -3031,12 +2688,10 @@ RooPlot* RooAbsPdf::plotOn(RooPlot *frame, PlotOpt o) const /// Type of CmdArg Effect on parameter box /// `Parameters(const RooArgSet& param)` Only the specified subset of parameters will be shown. By default all non-constant parameters are shown. /// `ShowConstants(bool flag)` Also display constant parameters -/// `Format(const char* optStr)` \deprecated Classing parameter formatting options, provided for backward compatibility -/// /// `Format(const char* what,...)` Parameter formatting options. /// | Parameter | Format /// | ---------------------- | -------------------------- -/// | `const char* what` | Controls what is shown. "N" adds name, "E" adds error, "A" shows asymmetric error, "U" shows unit, "H" hides the value +/// | `const char* what` | Controls what is shown. "N" adds name (alternatively, "T" adds the title), "E" adds error, "A" shows asymmetric error, "U" shows unit, "H" hides the value /// | `FixedPrecision(int n)`| Controls precision, set fixed number of digits /// | `AutoPrecision(int n)` | Controls precision. Number of shown digits is calculated from error + n specified additional digits (1 is sensible default) /// `Label(const chat* label)` Add label to parameter box. Use `\n` for multi-line labels. @@ -3064,17 +2719,14 @@ RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdA cmdList.Add(const_cast(&arg7)) ; cmdList.Add(const_cast(&arg8)) ; // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::paramOn(%s)",GetName())) ; + RooCmdConfig pc("RooAbsPdf::paramOn(" + std::string(GetName()) + ")"); pc.defineString("label","Label",0,"") ; pc.defineDouble("xmin","Layout",0,0.65) ; pc.defineDouble("xmax","Layout",1,0.9) ; pc.defineInt("ymaxi","Layout",0,Int_t(0.9*10000)) ; pc.defineInt("showc","ShowConstants",0,0) ; pc.defineSet("params","Parameters",0,0) ; - pc.defineString("formatStr","Format",0,"NELU") ; - pc.defineInt("sigDigit","Format",0,2) ; pc.defineInt("dummy","FormatArgs",0,0) ; - pc.defineMutex("Format","FormatArgs") ; // Process and check varargs pc.process(cmdList) ; @@ -3082,58 +2734,25 @@ RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdA return frame ; } + auto formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; + const char* label = pc.getString("label") ; double xmin = pc.getDouble("xmin") ; double xmax = pc.getDouble("xmax") ; double ymax = pc.getInt("ymaxi") / 10000. ; - Int_t showc = pc.getInt("showc") ; - - - const char* formatStr = pc.getString("formatStr") ; - Int_t sigDigit = pc.getInt("sigDigit") ; + int showc = pc.getInt("showc") ; // Decode command line arguments - RooArgSet* params = pc.getSet("params"); - if (!params) { - std::unique_ptr paramsPtr{getParameters(frame->getNormVars())} ; - if (pc.hasProcessed("FormatArgs")) { - const RooCmdArg* formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; - paramOn(frame,*paramsPtr,showc,label,0,0,xmin,xmax,ymax,formatCmd) ; - } else { - paramOn(frame,*paramsPtr,showc,label,sigDigit,formatStr,xmin,xmax,ymax) ; - } - } else { - std::unique_ptr pdfParams{getParameters(frame->getNormVars())} ; - std::unique_ptr selParams{static_cast(pdfParams->selectCommon(*params))} ; - if (pc.hasProcessed("FormatArgs")) { - const RooCmdArg* formatCmd = static_cast(cmdList.FindObject("FormatArgs")) ; - paramOn(frame,*selParams,showc,label,0,0,xmin,xmax,ymax,formatCmd) ; - } else { - paramOn(frame,*selParams,showc,label,sigDigit,formatStr,xmin,xmax,ymax) ; - } + std::unique_ptr params{getParameters(frame->getNormVars())} ; + if(RooArgSet* requestedParams = pc.getSet("params")) { + params = std::unique_ptr{static_cast(params->selectCommon(*requestedParams))}; } + paramOn(frame,*params,showc,label,xmin,xmax,ymax,formatCmd); return frame ; } - - -//////////////////////////////////////////////////////////////////////////////// -/// \deprecated Obsolete, provided for backward compatibility. Don't use. - -RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooAbsData* data, const char *label, - Int_t sigDigits, Option_t *options, double xmin, - double xmax ,double ymax) -{ - std::unique_ptr params{getParameters(data)} ; - TString opts(options) ; - paramOn(frame,*params,opts.Contains("c"),label,sigDigits,options,xmin,xmax,ymax) ; - return frame ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Add a text box with the current parameter values and their errors to the frame. /// Observables of this PDF appearing in the 'data' dataset will be omitted. @@ -3144,13 +2763,10 @@ RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooAbsData* data, const char * /// values specify the initial relative position of the text box in the plot frame. RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooArgSet& params, bool showConstants, const char *label, - Int_t sigDigits, Option_t *options, double xmin, - double xmax ,double ymax, const RooCmdArg* formatCmd) + double xmin, double xmax ,double ymax, const RooCmdArg* formatCmd) { // parse the options - TString opts = options; - opts.ToLower(); bool showLabel= (label != 0 && strlen(label) > 0); // calculate the box's size, adjusting for constant parameters @@ -3168,7 +2784,7 @@ RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooArgSet& params, bool showCo // create the box and set its options TPaveText *box= new TPaveText(xmin,ymax,xmax,ymin,"BRNDC"); if(!box) return 0; - box->SetName(Form("%s_paramBox",GetName())) ; + box->SetName((std::string(GetName()) + "_paramBox").c_str()); box->SetFillColor(0); box->SetBorderSize(0); box->SetTextAlign(12); @@ -3179,7 +2795,7 @@ RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooArgSet& params, bool showCo auto var = static_cast(param); if(var->isConstant() && !showConstants) continue; - std::unique_ptr formatted{options ? var->format(sigDigits, options) : var->format(*formatCmd)}; + std::unique_ptr formatted{formatCmd ? var->format(*formatCmd) : var->format(2, "NELU")}; box->AddText(formatted->Data()); } @@ -3288,7 +2904,7 @@ RooAbsPdf* RooAbsPdf::createProjection(const RooArgSet& iset) /// over z results in a maximum value of 1. To construct such a cdf pass /// z as argument to the optional nset argument -RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooArgSet& nset) +RooFit::OwningPtr RooAbsPdf::createCdf(const RooArgSet& iset, const RooArgSet& nset) { return createCdf(iset,RooFit::SupNormSet(nset)) ; } @@ -3310,12 +2926,12 @@ RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooArgSet& nset) /// | ScanNoCdf() | Never apply scanning technique /// | ScanParameters(Int_t nbins, Int_t intOrder) | Parameters for scanning technique of making CDF: number of sampled bins and order of interpolation applied on numeric cdf -RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsPdf::createCdf(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsReal::createCdf(%s)",GetName())) ; + RooCmdConfig pc("RooAbsReal::createCdf(" + std::string(GetName()) + ")"); pc.defineSet("supNormSet","SupNormSet",0,0) ; pc.defineInt("numScanBins","ScanParameters",0,1000) ; pc.defineInt("intOrder","ScanParameters",1,2) ; @@ -3350,8 +2966,8 @@ RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooCmdArg& arg1, c return createScanCdf(iset,nset,numScanBins,intOrder) ; } if (doScanNum) { - std::unique_ptr tmp{static_cast(createIntegral(iset))} ; - Int_t isNum= (tmp->numIntRealVars().getSize()>0) ; + std::unique_ptr tmp{createIntegral(iset)} ; + Int_t isNum= !static_cast(*tmp).numIntRealVars().empty(); if (isNum) { coutI(NumIntegration) << "RooAbsPdf::createCdf(" << GetName() << ") integration over observable(s) " << iset << " involves numeric integration," << endl @@ -3365,14 +2981,14 @@ RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooCmdArg& arg1, c return 0 ; } -RooAbsReal* RooAbsPdf::createScanCdf(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) +RooFit::OwningPtr RooAbsPdf::createScanCdf(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) { string name = string(GetName()) + "_NUMCDF_" + integralNameSuffix(iset,&nset).Data() ; RooRealVar* ivar = (RooRealVar*) iset.first() ; ivar->setBins(numScanBins,"numcdf") ; - RooNumCdf* ret = new RooNumCdf(name.c_str(),name.c_str(),*this,*ivar,"numcdf") ; + auto ret = std::make_unique(name.c_str(),name.c_str(),*this,*ivar,"numcdf"); ret->setInterpolationOrder(intOrder) ; - return ret ; + return RooFit::Detail::owningPtr(std::move(ret)); } @@ -3585,3 +3201,38 @@ bool RooAbsPdf::redirectServersHook(const RooAbsCollection & newServerList, bool setActiveNormSet(nullptr); return RooAbsReal::redirectServersHook(newServerList, mustReplaceAll, nameChange, isRecursiveStep); } + + +std::unique_ptr +RooAbsPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + if (normSet.empty() || selfNormalized()) { + return RooAbsReal::compileForNormSet(normSet, ctx); + } + std::unique_ptr pdfClone(static_cast(this->Clone())); + ctx.compileServers(*pdfClone, normSet); + + auto newArg = std::make_unique(*pdfClone, normSet); + + // The direct servers are this pdf and the normalization integral, which + // don't need to be compiled further. + for (RooAbsArg *server : newArg->servers()) { + ctx.markAsCompiled(*server); + } + ctx.markAsCompiled(*newArg); + newArg->addOwnedComponents(std::move(pdfClone)); + return newArg; +} + +/// Returns an object that represents the expected number of events for a given +/// normalization set, similar to how createIntegral() returns an object that +/// returns the integral. This is used to build the computation graph for the +/// final likelihood. +std::unique_ptr RooAbsPdf::createExpectedEventsFunc(const RooArgSet * /*nset*/) const +{ + std::stringstream errMsg; + errMsg << "The pdf \"" << GetName() << "\" of type " << ClassName() + << " did not overload RooAbsPdf::createExpectedEventsFunc()!"; + coutE(InputArguments) << errMsg.str() << std::endl; + return nullptr; +} diff --git a/roofit/roofitcore/src/RooAbsProxy.cxx b/roofit/roofitcore/src/RooAbsProxy.cxx index 25bde6264ca0c..e072c4bb70c99 100644 --- a/roofit/roofitcore/src/RooAbsProxy.cxx +++ b/roofit/roofitcore/src/RooAbsProxy.cxx @@ -23,7 +23,7 @@ \class RooAbsProxy \ingroup Roofitcore -RooAbsProxy is the abstact interface for proxy classes. +RooAbsProxy is the abstract interface for proxy classes. Proxy classes hold pointers to other Roofit objects and process serverRedirect changes so that the proxied pointers are updated accordingly on a clone or copy of @@ -34,13 +34,12 @@ of the owning class using namespace std; ClassImp(RooAbsProxy); -; //////////////////////////////////////////////////////////////////////////////// /// Constructor -RooAbsProxy::RooAbsProxy() : _nset(0) +RooAbsProxy::RooAbsProxy() : _nset(nullptr) { } diff --git a/roofit/roofitcore/src/RooAbsReal.cxx b/roofit/roofitcore/src/RooAbsReal.cxx index d71e41946ed5d..8f1cbfbfec2e9 100644 --- a/roofit/roofitcore/src/RooAbsReal.cxx +++ b/roofit/roofitcore/src/RooAbsReal.cxx @@ -11,7 +11,7 @@ * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * - * std::listed in LICENSE (http://roofit.sourceforge.net/license.txt) * + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// @@ -29,54 +29,51 @@ \ingroup Roofitcore */ - -#include "RooFitDriver.h" -#include "RooMsgService.h" - #include "RooAbsReal.h" -#include "RooArgSet.h" -#include "RooArgList.h" -#include "RooBinning.h" -#include "RooPlot.h" -#include "RooCurve.h" -#include "RooHist.h" -#include "RooRealVar.h" -#include "RooArgProxy.h" -#include "RooFormulaVar.h" -#include "RooRealBinding.h" -#include "RooRealIntegral.h" + +#include "FitHelpers.h" #include "RooAbsCategoryLValue.h" -#include "RooCustomizer.h" #include "RooAbsData.h" -#include "RooScaledFunc.h" #include "RooAddPdf.h" -#include "RooCmdConfig.h" -#include "RooCategory.h" -#include "RooNumIntConfig.h" #include "RooAddition.h" -#include "RooDataSet.h" +#include "RooArgList.h" +#include "RooArgProxy.h" +#include "RooArgSet.h" +#include "RooBinning.h" +#include "RooBrentRootFinder.h" +#include "RooCachedReal.h" +#include "RooCategory.h" +#include "RooChi2Var.h" +#include "RooCmdConfig.h" +#include "RooConstVar.h" +#include "RooCurve.h" +#include "RooCustomizer.h" #include "RooDataHist.h" -#include "RooDataWeightedAverage.h" -#include "RooNumRunningInt.h" -#include "RooGlobalFunc.h" -#include "RooParamBinning.h" -#include "RooProfileLL.h" -#include "RooFunctor.h" +#include "RooDataSet.h" #include "RooDerivative.h" -#include "RooGenFunction.h" -#include "RooMultiGenFunction.h" -#include "RooXYChi2Var.h" -#include "RooMinimizer.h" -#include "RooChi2Var.h" +#include "RooFirstMoment.h" +#include "RooFit/BatchModeDataHelpers.h" +#include "RooFit/Evaluator.h" #include "RooFitResult.h" +#include "RooFormulaVar.h" +#include "RooFunctor.h" +#include "RooGlobalFunc.h" +#include "RooHelpers.h" +#include "RooHist.h" #include "RooMoment.h" -#include "RooFirstMoment.h" +#include "RooMsgService.h" +#include "RooNumIntConfig.h" +#include "RooNumRunningInt.h" +#include "RooParamBinning.h" +#include "RooPlot.h" +#include "RooProduct.h" +#include "RooProfileLL.h" +#include "RooRealBinding.h" +#include "RooRealIntegral.h" +#include "RooRealVar.h" #include "RooSecondMoment.h" -#include "RooBrentRootFinder.h" #include "RooVectorDataStore.h" -#include "RooCachedReal.h" -#include "RooHelpers.h" -#include "RunContext.h" +#include "RooXYChi2Var.h" #include "TreeReadBuffer.h" #include "ValueChecking.h" @@ -108,6 +105,65 @@ #include #include +namespace { + +// Internal helper RooAbsFunc that evaluates the scaled data-weighted average of +// given RooAbsReal as a function of a single variable using the RooFit::Evaluator. +class ScaledDataWeightedAverage : public RooAbsFunc { +public: + ScaledDataWeightedAverage(RooAbsReal const &arg, RooAbsData const &data, double scaleFactor, RooAbsRealLValue &var) + : RooAbsFunc{1}, _var{var}, _dataWeights{data.getWeightBatch(0, data.numEntries())}, _scaleFactor{scaleFactor} + { + _arg = RooFit::Detail::compileForNormSet(arg, *data.get()); + _arg->recursiveRedirectServers(RooArgList{var}); + _evaluator = std::make_unique(*_arg); + std::stack>{}.swap(_vectorBuffers); + auto dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(data, "", nullptr, /*skipZeroWeights=*/false, + /*takeGlobalObservablesFromData=*/true, + _vectorBuffers); + for (auto const& item : dataSpans) { + _evaluator->setInput(item.first->GetName(), item.second, false); + } + } + + double operator()(const double xvector[]) const override + { + double oldVal = _var.getVal(); + _var.setVal(xvector[0]); + + double out = 0.0; + std::span pdfValues = _evaluator->run(); + if (_dataWeights.empty()) { + out = std::accumulate(pdfValues.begin(), pdfValues.end(), 0.0) / pdfValues.size(); + } else { + double weightsSum = 0.0; + for (std::size_t i = 0; i < pdfValues.size(); ++i) { + out += pdfValues[i] * _dataWeights[i]; + weightsSum += _dataWeights[i]; + } + out /= weightsSum; + } + out *= _scaleFactor; + + _var.setVal(oldVal); + return out; + } + double getMinLimit(UInt_t /*dimension*/) const override { return _var.getMin(); } + double getMaxLimit(UInt_t /*dimension*/) const override { return _var.getMax(); } + +private: + RooAbsRealLValue &_var; + std::unique_ptr _arg; + std::span _dataWeights; + double _scaleFactor; + std::unique_ptr _evaluator; + std::stack> _vectorBuffers; +}; + +} // namespace + +using namespace std ; + ClassImp(RooAbsReal) bool RooAbsReal::_globalSelectComp = false; @@ -125,52 +181,41 @@ std::map /// coverity[UNINIT_CTOR] /// Default constructor -RooAbsReal::RooAbsReal() : _specIntegratorConfig(0), _selectComp(true), _lastNSet(0) -{ -} - +RooAbsReal::RooAbsReal() {} //////////////////////////////////////////////////////////////////////////////// /// Constructor with unit label RooAbsReal::RooAbsReal(const char *name, const char *title, const char *unit) : - RooAbsArg(name,title), _plotMin(0), _plotMax(0), _plotBins(100), - _value(0), _unit(unit), _forceNumInt(false), _specIntegratorConfig(0), _selectComp(true), _lastNSet(0) + RooAbsArg(name,title), _unit(unit) { setValueDirty() ; setShapeDirty() ; - } - //////////////////////////////////////////////////////////////////////////////// /// Constructor with plot range and unit label RooAbsReal::RooAbsReal(const char *name, const char *title, double inMinVal, double inMaxVal, const char *unit) : - RooAbsArg(name,title), _plotMin(inMinVal), _plotMax(inMaxVal), _plotBins(100), - _value(0), _unit(unit), _forceNumInt(false), _specIntegratorConfig(0), _selectComp(true), _lastNSet(0) + RooAbsArg(name,title), _plotMin(inMinVal), _plotMax(inMaxVal), _unit(unit) { setValueDirty() ; setShapeDirty() ; - } - //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooAbsReal::RooAbsReal(const RooAbsReal& other, const char* name) : RooAbsArg(other,name), _plotMin(other._plotMin), _plotMax(other._plotMax), _plotBins(other._plotBins), _value(other._value), _unit(other._unit), _label(other._label), - _forceNumInt(other._forceNumInt), _selectComp(other._selectComp), _lastNSet(0) + _forceNumInt(other._forceNumInt), _selectComp(other._selectComp) { if (other._specIntegratorConfig) { - _specIntegratorConfig = new RooNumIntConfig(*other._specIntegratorConfig) ; - } else { - _specIntegratorConfig = 0 ; + _specIntegratorConfig = std::make_unique(*other._specIntegratorConfig) ; } } @@ -178,11 +223,7 @@ RooAbsReal::RooAbsReal(const RooAbsReal& other, const char* name) : //////////////////////////////////////////////////////////////////////////////// /// Destructor -RooAbsReal::~RooAbsReal() -{ - if (_specIntegratorConfig) delete _specIntegratorConfig ; -} - +RooAbsReal::~RooAbsReal() {} //////////////////////////////////////////////////////////////////////////////// @@ -220,8 +261,8 @@ bool RooAbsReal::isIdentical(const RooAbsArg& other, bool assumeSameType) const //////////////////////////////////////////////////////////////////////////////// -/// Return this variable's title std::string. If appendUnit is true and -/// this variable has units, also append a std::string " ()". +/// Return this variable's title string. If appendUnit is true and +/// this variable has units, also append a string " ()". TString RooAbsReal::getTitle(bool appendUnit) const { @@ -243,9 +284,9 @@ TString RooAbsReal::getTitle(bool appendUnit) const double RooAbsReal::getValV(const RooArgSet* nset) const { - if (nset && nset!=_lastNSet) { - ((RooAbsReal*) this)->setProxyNormSet(nset) ; - _lastNSet = (RooArgSet*) nset ; + if (nset && nset->uniqueId().value() != _lastNormSetId) { + const_cast(this)->setProxyNormSet(nset); + _lastNormSetId = nset->uniqueId().value(); } if (isValueDirtyAndClear()) { @@ -254,58 +295,10 @@ double RooAbsReal::getValV(const RooArgSet* nset) const } // cout << "RooAbsReal::getValV(" << GetName() << ") writing _value = " << _value << std::endl ; - double ret(_value) ; - if (hideOffset()) ret += offset() ; - - return ret ; + return hideOffset() ? _value + offset() : _value; } -//////////////////////////////////////////////////////////////////////////////// -/// Compute batch of values for input data stored in `evalData`. -/// -/// This is a faster, multi-value version of getVal(). It calls evaluateSpan() to trigger computations, and -/// finalises those (e.g. error checking or automatic normalisation) before returning a span with the results. -/// This span will also be stored in `evalData`, so subsquent calls of getValues() will return immediately. -/// -/// If `evalData` is empty, a single value will be returned, which is the result of evaluating the current value -/// of each object that's serving values to us. If `evalData` contains a batch of values for one or more of the -/// objects serving values to us, a batch of values for each entry stored in `evalData` is returned. To fill a -/// RunContext with values from a dataset, use RooAbsData::getBatches(). -/// -/// \param[in] evalData Object holding spans of input data. The results are also stored here. -/// \param[in] normSet Use these variables for normalisation (relevant for PDFs), and pass this normalisation -/// on to object serving values to us. -/// \return RooSpan pointing to the computation results. The memory this span points to is owned by `evalData`. -RooSpan RooAbsReal::getValues(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { - auto item = evalData.spans.find(this); - if (item != evalData.spans.end()) { - return item->second; - } - - normSet = normSet ? normSet : _lastNSet; - - std::map> dataSpans; - for (auto const &evalDataItem : evalData.spans) { - dataSpans[evalDataItem.first] = evalDataItem.second; - } - - ROOT::Experimental::RooFitDriver driver(*this, normSet ? *normSet : RooArgSet{}); - driver.setData(dataSpans); - auto& results = evalData.ownedMemory[this]; - results = driver.getValues(); // the compiler should use the move assignment here - evalData.spans[this] = results; - return results; -} - -//////////////////////////////////////////////////////////////////////////////// - -std::vector RooAbsReal::getValues(RooAbsData const& data, RooFit::BatchModeOption batchMode) const { - ROOT::Experimental::RooFitDriver driver(*this, *data.get(), batchMode); - driver.setData(data, ""); - return driver.getValues(); -} - //////////////////////////////////////////////////////////////////////////////// Int_t RooAbsReal::numEvalErrorItems() @@ -477,7 +470,7 @@ void RooAbsReal::printMultiline(std::ostream& os, Int_t contents, bool verbose, /// present function. The nuisance parameters are defined as all parameters /// of the function except the stated paramsOfInterest -RooAbsReal* RooAbsReal::createProfile(const RooArgSet& paramsOfInterest) +RooFit::OwningPtr RooAbsReal::createProfile(const RooArgSet& paramsOfInterest) { // Construct name of profile object auto name = std::string(GetName()) + "_Profile["; @@ -493,7 +486,8 @@ RooAbsReal* RooAbsReal::createProfile(const RooArgSet& paramsOfInterest) name.append("]") ; // Create and return profile object - return new RooProfileLL(name.c_str(),(std::string("Profile of ") + GetTitle()).c_str(),*this,paramsOfInterest) ; + auto out = std::make_unique(name.c_str(),(std::string("Profile of ") + GetTitle()).c_str(),*this,paramsOfInterest); + return RooFit::Detail::owningPtr(std::move(out)); } @@ -502,7 +496,7 @@ RooAbsReal* RooAbsReal::createProfile(const RooArgSet& paramsOfInterest) //////////////////////////////////////////////////////////////////////////////// -/// Create an object that represents the integral of the function over one or more observables std::listed in `iset`. +/// Create an object that represents the integral of the function over one or more observables listed in `iset`. /// The actual integration calculation is only performed when the returned object is evaluated. The name /// of the integral object is automatically constructed from the name of the input function, the variables /// it integrates and the range integrates over. @@ -519,28 +513,28 @@ RooAbsReal* RooAbsReal::createProfile(const RooArgSet& paramsOfInterest) /// | `NumIntConfig(const RooNumIntConfig&)` | Use given configuration for any numeric integration, if necessary /// | `Range(const char* name)` | Integrate only over given range. Multiple ranges may be specified by passing multiple Range() arguments -RooAbsReal* RooAbsReal::createIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsReal::createIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsReal::createIntegral(%s)",GetName())) ; + RooCmdConfig pc("RooAbsReal::createIntegral(" + std::string(GetName()) + ")"); pc.defineString("rangeName","RangeWithName",0,"",true) ; - pc.defineSet("normSet","NormSet",0,0) ; - pc.defineObject("numIntConfig","NumIntConfig",0,0) ; + pc.defineSet("normSet","NormSet",0,nullptr) ; + pc.defineObject("numIntConfig","NumIntConfig",0,nullptr) ; // Process & check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; if (!pc.ok(true)) { - return 0 ; + return nullptr; } // Extract values from named arguments - const char* rangeName = pc.getString("rangeName",0,true) ; - const RooArgSet* nset = pc.getSet("normSet",0); - const RooNumIntConfig* cfg = static_cast(pc.getObject("numIntConfig",0)) ; + const char* rangeName = pc.getString("rangeName",nullptr,true) ; + const RooArgSet* nset = pc.getSet("normSet",nullptr); + const RooNumIntConfig* cfg = static_cast(pc.getObject("numIntConfig",nullptr)) ; return createIntegral(iset,nset,cfg,rangeName) ; } @@ -550,7 +544,7 @@ RooAbsReal* RooAbsReal::createIntegral(const RooArgSet& iset, const RooCmdArg& a //////////////////////////////////////////////////////////////////////////////// -/// Create an object that represents the integral of the function over one or more observables std::listed in iset. +/// Create an object that represents the integral of the function over one or more observables listed in iset. /// The actual integration calculation is only performed when the return object is evaluated. The name /// of the integral object is automatically constructed from the name of the input function, the variables /// it integrates and the range integrates over. If nset is specified the integrand is request @@ -560,37 +554,44 @@ RooAbsReal* RooAbsReal::createIntegral(const RooArgSet& iset, const RooCmdArg& a /// aspect of the integral. It will not force the integral to be performed numerically, which is /// decided automatically by RooRealIntegral. -RooAbsReal* RooAbsReal::createIntegral(const RooArgSet& iset, const RooArgSet* nset, +RooFit::OwningPtr RooAbsReal::createIntegral(const RooArgSet& iset, const RooArgSet* nset, const RooNumIntConfig* cfg, const char* rangeName) const { - if (!rangeName || strchr(rangeName,',')==0) { + if (!rangeName || strchr(rangeName,',')==nullptr) { // Simple case: integral over full range or single limited range - return createIntObj(iset,nset,cfg,rangeName) ; + return createIntObj(iset,nset,cfg,rangeName); } // Integral over multiple ranges - RooArgSet components ; + std::vector tokens = ROOT::Split(rangeName, ","); - auto tokens = ROOT::Split(rangeName, ","); + if(RooHelpers::checkIfRangesOverlap(iset, tokens)) { + std::stringstream errMsg; + errMsg << GetName() << " : integrating with respect to the variables " << iset << " on the ranges \"" << rangeName + << "\" is not possible because the ranges are overlapping"; + const std::string errMsgString = errMsg.str(); + coutE(Integration) << errMsgString << std::endl; + throw std::invalid_argument(errMsgString); + } + RooArgSet components ; for (const std::string& token : tokens) { - RooAbsReal* compIntegral = createIntObj(iset,nset,cfg, token.c_str()); - components.add(*compIntegral); + components.addOwned(std::unique_ptr{createIntObj(iset,nset,cfg, token.c_str())}); } - TString title(GetTitle()) ; - title.Prepend("Integral of ") ; - TString fullName(GetName()) ; - fullName.Append(integralNameSuffix(iset,nset,rangeName)) ; + const std::string title = std::string("Integral of ") + GetTitle(); + const std::string fullName = std::string(GetName()) + integralNameSuffix(iset,nset,rangeName).Data(); - return new RooAddition(fullName.Data(),title.Data(),components,true) ; + auto out = std::make_unique(fullName.c_str(), title.c_str(), components); + out->addOwnedComponents(std::move(components)); + return RooFit::Detail::owningPtr(std::move(out)); } //////////////////////////////////////////////////////////////////////////////// /// Internal utility function for createIntegral() that creates the actual integral object. -RooAbsReal* RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* nset2, +RooFit::OwningPtr RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* nset2, const RooNumIntConfig* cfg, const char* rangeName) const { // Make internal use copies of iset and nset @@ -601,22 +602,20 @@ RooAbsReal* RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* ns // Initialize local variables perparing for recursive loop bool error = false ; const RooAbsReal* integrand = this ; - RooAbsReal* integral = 0 ; + std::unique_ptr integral; // Handle trivial case of no integration here explicitly if (iset.empty()) { - TString title(GetTitle()) ; - title.Prepend("Integral of ") ; + const std::string title = std::string("Integral of ") + GetTitle(); + const std::string name = std::string(GetName()) + integralNameSuffix(iset,nset,rangeName).Data(); - TString name(GetName()) ; - name.Append(integralNameSuffix(iset,nset,rangeName)) ; - - return new RooRealIntegral(name,title,*this,iset,nset,cfg,rangeName) ; + auto out = std::make_unique(name.c_str(), title.c_str(), *this, iset, nset, cfg, rangeName); + return RooFit::Detail::owningPtr(std::move(out)); } // Process integration over remaining integration variables - while(iset.getSize()>0) { + while(!iset.empty()) { // Find largest set of observables that can be integrated in one go @@ -631,41 +630,38 @@ RooAbsReal* RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* ns } // Prepare name and title of integral to be created - TString title(integrand->GetTitle()) ; - title.Prepend("Integral of ") ; + const std::string title = std::string("Integral of ") + integrand->GetTitle(); + const std::string name = std::string(integrand->GetName()) + integrand->integralNameSuffix(innerSet,nset,rangeName).Data(); - TString name(integrand->GetName()) ; - name.Append(integrand->integralNameSuffix(innerSet,nset,rangeName)) ; + std::unique_ptr innerIntegral = std::move(integral); // Construct innermost integral - integral = new RooRealIntegral(name,title,*integrand,innerSet,nset,cfg,rangeName) ; + integral = std::make_unique(name.c_str(),title.c_str(),*integrand,innerSet,nset,cfg,rangeName); // Integral of integral takes ownership of innermost integral - if (integrand != this) { - integral->addOwnedComponents(*integrand) ; + if (innerIntegral) { + integral->addOwnedComponents(std::move(innerIntegral)); } - // Remove already integrated observables from to-do std::list + // Remove already integrated observables from to-do list iset.remove(innerSet) ; // Send info message on recursion if needed - if (integrand == this && iset.getSize()>0) { + if (integrand == this && !iset.empty()) { coutI(Integration) << GetName() << " : multidimensional integration over observables with parameterized ranges in terms of other integrated observables detected, using recursive integration strategy to construct final integral" << std::endl ; } // Prepare for recursion, next integral should integrate last integrand - integrand = integral ; + integrand = integral.get(); // Only need normalization set in innermost integration - nset = 0 ; + nset = nullptr; } if (error) { coutE(Integration) << GetName() << " : ERROR while defining recursive integral over observables with parameterized integration ranges, please check that integration rangs specify uniquely defined integral " << std::endl; - delete integral ; - integral = 0 ; - return integral ; + return nullptr; } @@ -677,23 +673,23 @@ RooAbsReal* RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* ns RooArgSet cacheParams = RooHelpers::selectFromArgSet(*intParams, cacheParamsStr); - if (cacheParams.getSize()>0) { - cxcoutD(Caching) << "RooAbsReal::createIntObj(" << GetName() << ") INFO: constructing " << cacheParams.getSize() + if (!cacheParams.empty()) { + cxcoutD(Caching) << "RooAbsReal::createIntObj(" << GetName() << ") INFO: constructing " << cacheParams.size() << "-dim value cache for integral over " << iset2 << " as a function of " << cacheParams << " in range " << (rangeName?rangeName:"") << std::endl ; std::string name = Form("%s_CACHE_[%s]",integral->GetName(),cacheParams.contentsString().c_str()) ; - RooCachedReal* cachedIntegral = new RooCachedReal(name.c_str(),name.c_str(),*integral,cacheParams) ; + auto cachedIntegral = std::make_unique(name.c_str(),name.c_str(),*integral,cacheParams); cachedIntegral->setInterpolationOrder(2) ; - cachedIntegral->addOwnedComponents(*integral) ; + cachedIntegral->addOwnedComponents(std::move(integral)); cachedIntegral->setCacheSource(true) ; if (integral->operMode()==ADirty) { cachedIntegral->setOperMode(ADirty) ; } //cachedIntegral->disableCache(true) ; - integral = cachedIntegral ; + return RooFit::Detail::owningPtr(std::move(cachedIntegral)); } } - return integral ; + return RooFit::Detail::owningPtr(std::move(integral)); } @@ -708,7 +704,7 @@ RooAbsReal* RooAbsReal::createIntObj(const RooArgSet& iset2, const RooArgSet* ns void RooAbsReal::findInnerMostIntegration(const RooArgSet& allObs, RooArgSet& innerObs, const char* rangeName) const { - // Make std::lists of + // Make lists of // a) integrated observables with fixed ranges, // b) integrated observables with parameterized ranges depending on other integrated observables // c) integrated observables used in definition of any parameterized ranges of integrated observables @@ -719,8 +715,7 @@ void RooAbsReal::findInnerMostIntegration(const RooArgSet& allObs, RooArgSet& in // Loop over all integrated observables for (const auto aarg : allObs) { // Check if observable is real-valued lvalue - RooAbsRealLValue* arglv = dynamic_cast(aarg) ; - if (arglv) { + if (auto arglv = dynamic_cast(aarg)) { // Check if range is parameterized RooAbsBinning& binning = arglv->getBinning(rangeName,false,true) ; @@ -741,11 +736,11 @@ void RooAbsReal::findInnerMostIntegration(const RooArgSet& allObs, RooArgSet& in } } - // Make std::list of fixed-range observables that are _not_ involved in the parameterization of ranges of other observables + // Make list of fixed-range observables that are _not_ involved in the parameterization of ranges of other observables RooArgSet obsWithFixedRangeNP(obsWithFixedRange) ; obsWithFixedRangeNP.remove(obsServingAsRangeParams) ; - // Make std::list of param-range observables that are _not_ involved in the parameterization of ranges of other observables + // Make list of param-range observables that are _not_ involved in the parameterization of ranges of other observables RooArgSet obsWithParamRangeNP(obsWithParamRange) ; obsWithParamRangeNP.remove(obsServingAsRangeParams) ; @@ -758,13 +753,13 @@ void RooAbsReal::findInnerMostIntegration(const RooArgSet& allObs, RooArgSet& in //////////////////////////////////////////////////////////////////////////////// -/// Construct std::string with unique suffix name to give to integral object that encodes +/// Construct string with unique suffix name to give to integral object that encodes /// integrated observables, normalization observables and the integration range name TString RooAbsReal::integralNameSuffix(const RooArgSet& iset, const RooArgSet* nset, const char* rangeName, bool omitEmpty) const { TString name ; - if (iset.getSize()>0) { + if (!iset.empty()) { RooArgSet isetTmp(iset) ; isetTmp.sort() ; @@ -788,7 +783,7 @@ TString RooAbsReal::integralNameSuffix(const RooArgSet& iset, const RooArgSet* n name.Append("_Int[]") ; } - if (nset && nset->getSize()>0 ) { + if (nset && !nset->empty()) { RooArgSet nsetTmp(*nset) ; nsetTmp.sort() ; @@ -861,13 +856,13 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar // Check that the dependents are all fundamental. Filter out any that we - // do not depend on, and make substitutions by name in our leaf std::list. + // do not depend on, and make substitutions by name in our leaf list. // Check for overlaps with the projection variables. for (const auto arg : dependentVars) { if(!arg->isFundamental() && !dynamic_cast(arg)) { coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: variable \"" << arg->GetName() << "\" of wrong type: " << arg->ClassName() << std::endl; - return 0; + return nullptr; } RooAbsArg *found= treeNodes.find(arg->GetName()); @@ -896,25 +891,25 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar } // check if this arg is also in the projection set - if(0 != projectedVars && projectedVars->find(arg->GetName())) { + if(nullptr != projectedVars && projectedVars->find(arg->GetName())) { coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: \"" << arg->GetName() << "\" cannot be both a dependent and a projected variable." << std::endl; - return 0; + return nullptr; } } - // Remove the projected variables from the std::list of leaf nodes, if necessary. - if(0 != projectedVars) leafNodes.remove(*projectedVars,true); + // Remove the projected variables from the list of leaf nodes, if necessary. + if(nullptr != projectedVars) leafNodes.remove(*projectedVars,true); // Make a deep-clone of ourself so later operations do not disturb our original state - cloneSet= (RooArgSet*)RooArgSet(*this).snapshot(true); - if (!cloneSet) { + cloneSet = new RooArgSet; + if (RooArgSet(*this).snapshot(*cloneSet, true)) { coutE(Plotting) << "RooAbsPdf::createPlotProjection(" << GetName() << ") Couldn't deep-clone PDF, abort," << std::endl ; - return 0 ; + return nullptr ; } RooAbsReal *theClone= (RooAbsReal*)cloneSet->find(GetName()); - // The remaining entries in our std::list of leaf nodes are the external + // The remaining entries in our list of leaf nodes are the external // dependents (x) and parameters (p) of the projection. Patch them back // into the theClone. This orphans the nodes they replace, but the orphans // are still in the cloneList and so will be cleaned up eventually. @@ -925,8 +920,8 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar // Create the set of normalization variables to use in the projection integrand RooArgSet normSet(dependentVars); - if(0 != projectedVars) normSet.add(*projectedVars); - if(0 != condObs) { + if(nullptr != projectedVars) normSet.add(*projectedVars); + if(nullptr != condObs) { normSet.remove(*condObs,true,true) ; } @@ -934,7 +929,7 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar // create a null projection anyway to bind our normalization over the dependents // consistently with the way they would be bound with a non-trivial projection. RooArgSet empty; - if(0 == projectedVars) projectedVars= ∅ + if(nullptr == projectedVars) projectedVars= ∅ TString name = GetName() ; name += integralNameSuffix(*projectedVars,&normSet,rangeName,true) ; @@ -943,34 +938,32 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar title.Prepend("Projection of "); - RooAbsReal* projected= theClone->createIntegral(*projectedVars,normSet,rangeName) ; + std::unique_ptr projected{theClone->createIntegral(*projectedVars,normSet,rangeName)}; - if(0 == projected || !projected->isValid()) { + if(nullptr == projected || !projected->isValid()) { coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: cannot integrate out "; projectedVars->printStream(std::cout,kName|kArgs,kSingleLine); - // cleanup and exit - if(0 != projected) delete projected; - return 0; + return nullptr; } if(projected->InheritsFrom(RooRealIntegral::Class())){ - static_cast(projected)->setAllowComponentSelection(true); + static_cast(*projected).setAllowComponentSelection(true); } projected->SetName(name.Data()) ; projected->SetTitle(title.Data()) ; // Add the projection integral to the cloneSet so that it eventually gets cleaned up by the caller. - cloneSet->addOwned(*projected); + RooAbsReal *projectedPtr = projected.get(); + cloneSet->addOwned(std::move(projected)); // return a const pointer to remind the caller that they do not delete the returned object // directly (it is contained in the cloneSet instead). - return projected; + return projectedPtr; } - //////////////////////////////////////////////////////////////////////////////// /// Fill the ROOT histogram 'hist' with values sampled from this /// function at the bin centers. Our value is calculated by first @@ -980,7 +973,7 @@ const RooAbsReal *RooAbsReal::createPlotProjection(const RooArgSet &dependentVar /// be any TH1 subclass, and therefore of arbitrary /// dimension. Variables are matched with the (x,y,...) dimensions of /// the input histogram according to the order in which they appear -/// in the input plotVars std::list. If scaleForDensity is true the +/// in the input plotVars list. If scaleForDensity is true the /// histogram is filled with a the functions density rather than /// the functions value (i.e. the value at the bin center is multiplied /// with bin volume) @@ -990,29 +983,29 @@ TH1 *RooAbsReal::fillHistogram(TH1 *hist, const RooArgList &plotVars, const RooArgSet* condObs, bool setError) const { // Do we have a valid histogram to use? - if(0 == hist) { + if(nullptr == hist) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << std::endl; - return 0; + return nullptr; } // Check that the number of plotVars matches the input histogram's dimension Int_t hdim= hist->GetDimension(); if(hdim != plotVars.getSize()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << std::endl; - return 0; + return nullptr; } // Check that the plot variables are all actually RooRealVars and print a warning if we do not - // explicitly depend on one of them. Fill a set (not std::list!) of cloned plot variables. + // explicitly depend on one of them. Fill a set (not list!) of cloned plot variables. RooArgSet plotClones; for(Int_t index= 0; index < plotVars.getSize(); index++) { const RooAbsArg *var= plotVars.at(index); const RooRealVar *realVar= dynamic_cast(var); - if(0 == realVar) { + if(nullptr == realVar) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot plot variable \"" << var->GetName() << "\" of type " << var->ClassName() << std::endl; - return 0; + return nullptr; } if(!this->dependsOn(*realVar)) { coutE(InputArguments) << ClassName() << "::" << GetName() @@ -1037,25 +1030,25 @@ TH1 *RooAbsReal::fillHistogram(TH1 *hist, const RooArgList &plotVars, } // Create a standalone projection object to use for calculating bin contents - RooArgSet *cloneSet = 0; - const RooAbsReal *projected= createPlotProjection(plotClones,projectedVars,cloneSet,0,condObs); + RooArgSet *cloneSet = nullptr; + const RooAbsReal *projected= createPlotProjection(plotClones,projectedVars,cloneSet,nullptr,condObs); cxcoutD(Plotting) << "RooAbsReal::fillHistogram(" << GetName() << ") plot projection object is " << projected->GetName() << std::endl ; // Prepare to loop over the histogram bins Int_t xbins(0),ybins(1),zbins(1); - RooRealVar *xvar = 0; - RooRealVar *yvar = 0; - RooRealVar *zvar = 0; - TAxis *xaxis = 0; - TAxis *yaxis = 0; - TAxis *zaxis = 0; + RooRealVar *xvar = nullptr; + RooRealVar *yvar = nullptr; + RooRealVar *zvar = nullptr; + TAxis *xaxis = nullptr; + TAxis *yaxis = nullptr; + TAxis *zaxis = nullptr; switch(hdim) { case 3: zbins= hist->GetNbinsZ(); zvar= dynamic_cast(plotClones.find(plotVars.at(2)->GetName())); zaxis= hist->GetZaxis(); - assert(0 != zvar && 0 != zaxis); + assert(nullptr != zvar && nullptr != zaxis); if (scaleForDensity) { scaleFactor*= (zaxis->GetXmax() - zaxis->GetXmin())/zbins; } @@ -1064,7 +1057,7 @@ TH1 *RooAbsReal::fillHistogram(TH1 *hist, const RooArgList &plotVars, ybins= hist->GetNbinsY(); yvar= dynamic_cast(plotClones.find(plotVars.at(1)->GetName())); yaxis= hist->GetYaxis(); - assert(0 != yvar && 0 != yaxis); + assert(nullptr != yvar && nullptr != yaxis); if (scaleForDensity) { scaleFactor*= (yaxis->GetXmax() - yaxis->GetXmin())/ybins; } @@ -1073,7 +1066,7 @@ TH1 *RooAbsReal::fillHistogram(TH1 *hist, const RooArgList &plotVars, xbins= hist->GetNbinsX(); xvar= dynamic_cast(plotClones.find(plotVars.at(0)->GetName())); xaxis= hist->GetXaxis(); - assert(0 != xvar && 0 != xaxis); + assert(nullptr != xvar && nullptr != xaxis); if (scaleForDensity) { scaleFactor*= (xaxis->GetXmax() - xaxis->GetXmin())/xbins; } @@ -1162,9 +1155,9 @@ RooDataHist* RooAbsReal::fillDataHist(RooDataHist *hist, const RooArgSet* normSe bool correctForBinSize, bool showProgress) const { // Do we have a valid histogram to use? - if(0 == hist) { + if(nullptr == hist) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillDataHist: no valid RooDataHist to fill" << std::endl; - return 0; + return nullptr; } // Call checkObservables @@ -1176,8 +1169,9 @@ RooDataHist* RooAbsReal::fillDataHist(RooDataHist *hist, const RooArgSet* normSe // Make deep clone of self and attach to dataset observables //RooArgSet* origObs = getObservables(hist) ; - std::unique_ptr cloneSet{static_cast(RooArgSet(*this).snapshot(true))}; - RooAbsReal* theClone = (RooAbsReal*) cloneSet->find(GetName()) ; + RooArgSet cloneSet; + RooArgSet(*this).snapshot(cloneSet, true); + RooAbsReal* theClone = static_cast(cloneSet.find(GetName())); theClone->recursiveRedirectServers(*hist->get()) ; //const_cast(this)->recursiveRedirectServers(*hist->get()) ; @@ -1216,50 +1210,50 @@ RooDataHist* RooAbsReal::fillDataHist(RooDataHist *hist, const RooArgSet* normSe /// RooAbsReal::createHistogram(const char *, const RooAbsRealLValue&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&) const /// -TH1* RooAbsReal::createHistogram(const char* varNameList, Int_t xbins, Int_t ybins, Int_t zbins) const +TH1* RooAbsReal::createHistogram(RooStringView varNameList, Int_t xbins, Int_t ybins, Int_t zbins) const { - // Parse std::list of variable names - char buf[1024] ; - strlcpy(buf,varNameList,1024) ; - char* varName = strtok(buf,",:") ; - std::unique_ptr vars{getVariables()}; - RooRealVar* xvar = (RooRealVar*) vars->find(varName) ; - varName = strtok(0,",") ; - RooRealVar* yvar = varName ? (RooRealVar*) vars->find(varName) : 0 ; - varName = strtok(0,",") ; - RooRealVar* zvar = varName ? (RooRealVar*) vars->find(varName) : 0 ; + auto varNames = ROOT::Split(varNameList, ",:"); + std::vector histVars(3, nullptr); - // Construct std::list of named arguments to pass to the implementation version of createHistogram() + for(std::size_t iVar = 0; iVar < varNames.size(); ++iVar) { + if(varNames[iVar].empty()) continue; + if(iVar >= 3) { + std::stringstream errMsg; + errMsg << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR more than three variable names passed, but maximum number of supported variables is three"; + coutE(Plotting) << errMsg.str() << std::endl; + throw std::invalid_argument(errMsg.str()); + } + auto var = static_cast(vars->find(varNames[iVar].c_str())); + if(!var) { + std::stringstream errMsg; + errMsg << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR variable " << varNames[iVar] << " does not exist in argset: " << *vars; + coutE(Plotting) << errMsg.str() << std::endl; + throw std::runtime_error(errMsg.str()); + } + histVars[iVar] = var; + } + + // Construct list of named arguments to pass to the implementation version of createHistogram() RooLinkedList argList ; if (xbins>0) { argList.Add(RooFit::Binning(xbins).Clone()) ; } - if (yvar) { - if (ybins>0) { - argList.Add(RooFit::YVar(*yvar,RooFit::Binning(ybins)).Clone()) ; - } else { - argList.Add(RooFit::YVar(*yvar).Clone()) ; - } + if (histVars[1]) { + argList.Add(RooFit::YVar(*histVars[1], ybins > 0 ? RooFit::Binning(ybins) : RooCmdArg::none()).Clone()) ; } - - if (zvar) { - if (zbins>0) { - argList.Add(RooFit::ZVar(*zvar,RooFit::Binning(zbins)).Clone()) ; - } else { - argList.Add(RooFit::ZVar(*zvar).Clone()) ; - } + if (histVars[2]) { + argList.Add(RooFit::ZVar(*histVars[2], zbins > 0 ? RooFit::Binning(zbins) : RooCmdArg::none()).Clone()) ; } - // Call implementation function - TH1* result = createHistogram(GetName(),*xvar,argList) ; + TH1* result = createHistogram(GetName(), *histVars[0], argList) ; - // Delete temporary std::list of RooCmdArgs + // Delete temporary list of RooCmdArgs argList.Delete() ; return result ; @@ -1272,7 +1266,7 @@ TH1* RooAbsReal::createHistogram(const char* varNameList, Int_t xbins, Int_t ybi /// /// \param[in] name Name of the ROOT histogram /// \param[in] xvar Observable to be std::mapped on x axis of ROOT histogram -/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 Arguments according to std::list below +/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 Arguments according to list below /// \return TH1 *, one of TH{1,2,3}. The caller takes ownership. /// /// @@ -1318,16 +1312,16 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsReal::createHistogram(%s)",GetName())) ; + RooCmdConfig pc("RooAbsReal::createHistogram(" + std::string(GetName()) + ")"); pc.defineInt("scaling","Scaling",0,1) ; pc.defineInt("intBinning","IntrinsicBinning",0,2) ; pc.defineInt("extended","Extended",0,2) ; pc.defineSet("compSet","SelectCompSet",0); pc.defineString("compSpec","SelectCompSpec",0) ; - pc.defineSet("projObs","ProjectedObservables",0,0) ; - pc.defineObject("yvar","YVar",0,0) ; - pc.defineObject("zvar","ZVar",0,0) ; + pc.defineSet("projObs","ProjectedObservables",0,nullptr) ; + pc.defineObject("yvar","YVar",0,nullptr) ; + pc.defineObject("zvar","ZVar",0,nullptr) ; pc.defineMutex("SelectCompSet","SelectCompSpec") ; pc.defineMutex("IntrinsicBinning","Binning") ; pc.defineMutex("IntrinsicBinning","BinningName") ; @@ -1337,7 +1331,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, // Process & check varargs pc.process(argList) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } RooArgList vars(xvar) ; @@ -1351,7 +1345,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, } auto projObs = pc.getSet("projObs"); - RooArgSet* intObs = 0 ; + RooArgSet* intObs = nullptr ; bool doScaling = pc.getInt("scaling") ; Int_t doIntBinning = pc.getInt("intBinning") ; @@ -1359,7 +1353,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, // If doExtended is two, selection is automatic, set to 1 of pdf is extended, to zero otherwise const RooAbsPdf* pdfSelf = dynamic_cast(this) ; - if (!pdfSelf && doExtended>0) { + if (!pdfSelf && doExtended == 1) { coutW(InputArguments) << "RooAbsReal::createHistogram(" << GetName() << ") WARNING extended mode requested for a non-pdf object, ignored" << std::endl ; doExtended=0 ; } @@ -1369,13 +1363,15 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, } if (pdfSelf && doExtended==2) { doExtended = pdfSelf->extendMode()==RooAbsPdf::CanNotBeExtended ? 0 : 1 ; + } else if(!pdfSelf) { + doExtended = 0; } const char* compSpec = pc.getString("compSpec") ; const RooArgSet* compSet = pc.getSet("compSet"); bool haveCompSel = ( (compSpec && strlen(compSpec)>0) || compSet) ; - RooBinning* intBinning(0) ; + std::unique_ptr intBinning; if (doIntBinning>0) { // Given RooAbsPdf* pdf and RooRealVar* obs std::unique_ptr> bl{binBoundaries(const_cast(xvar),xvar.getMin(),xvar.getMax())}; @@ -1390,22 +1386,21 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, coutI(InputArguments) << "RooAbsReal::createHistogram(" << GetName() << ") INFO: Model has intrinsic binning definition, selecting that binning for the histogram"<< std::endl ; } - std::vector ba(bl->size()); + std::vector edges(bl->size()); int i=0 ; - for (auto const& elem : *bl) { ba[i++] = elem ; } - intBinning = new RooBinning(bl->size()-1,ba.data()) ; + for (auto const& elem : *bl) { edges[i++] = elem ; } + intBinning = std::make_unique(bl->size()-1,edges.data()) ; } } RooLinkedList argListCreate(argList) ; RooCmdConfig::stripCmdList(argListCreate,"Scaling,ProjectedObservables,IntrinsicBinning,SelectCompSet,SelectCompSpec,Extended") ; - TH1* histo(0) ; + TH1* histo(nullptr) ; if (intBinning) { RooCmdArg tmp = RooFit::Binning(*intBinning) ; argListCreate.Add(&tmp) ; histo = xvar.createHistogram(name,argListCreate) ; - delete intBinning ; } else { histo = xvar.createHistogram(name,argListCreate) ; } @@ -1441,7 +1436,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, } else { coutE(Plotting) << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR: component selection expression '" << compSpec << "' does not select any components of p.d.f." << std::endl ; } - return 0 ; + return nullptr ; } } @@ -1455,7 +1450,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, // Deactivate component selection if (haveCompSel) { - plotOnCompSelect(0) ; + plotOnCompSelect(nullptr) ; } @@ -1467,7 +1462,7 @@ TH1* RooAbsReal::createHistogram(const char *name, const RooAbsRealLValue& xvar, /// Helper function for plotting of composite p.d.fs. Given /// a set of selected components that should be plotted, /// find all nodes that (in)directly depend on these selected -/// nodes. Mark all directly and indirecty selected nodes +/// nodes. Mark all directly and indirectly selected nodes /// as 'selected' using the selectComp() method void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const @@ -1495,19 +1490,19 @@ void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const } - // Add all nodes below selected nodes + // Add all nodes below selected nodes that are value servers RooArgSet tmp; for (const auto arg : branchNodeSet) { for (const auto selNode : *selNodes) { - if (selNode->dependsOn(*arg)) { + if (selNode->dependsOn(*arg, nullptr, /*valueOnly=*/true)) { tmp.add(*arg,true); } } } - // Add all nodes that depend on selected nodes + // Add all nodes that depend on selected nodes by value for (const auto arg : branchNodeSet) { - if (arg->dependsOn(*selNodes)) { + if (arg->dependsOn(*selNodes, nullptr, /*valueOnly=*/true)) { tmp.add(*arg,true); } } @@ -1543,7 +1538,7 @@ void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const /// This function takes the following named arguments ///
    ///
    Projection control -///
    `Slice(const RooArgSet& set)` Override default projection behaviour by omitting observables std::listed +///
    `Slice(const RooArgSet& set)` Override default projection behaviour by omitting observables listed /// in set from the projection, i.e. by not integrating over these. /// Slicing is usually only sensible in discrete observables, by e.g. creating a slice /// of the PDF at the current value of the category observable. @@ -1554,7 +1549,7 @@ void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const /// Slice(std::map const&) argument explained below. /// ///
    `Slice(std::map const&)` Omits multiple categories from the projection, as explianed above. -/// Can be used with initializer std::lists for convenience, e.g. +/// Can be used with initializer lists for convenience, e.g. /// ```{.cpp} /// pdf.plotOn(frame, Slice({{&tagCategory, "2tag"}, {&jetCategory, "3jet"}}); /// ``` @@ -1568,7 +1563,7 @@ void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const /// ///
    `ProjWData(const RooArgSet& s, const RooAbsData& d)` As above but only consider subset 's' of observables in dataset 'd' for projection through data averaging /// -///
    `ProjectionRange(const char* rn)` Override default range of projection integrals to a different range speficied by given range name. +///
    `ProjectionRange(const char* rn)` Override default range of projection integrals to a different range specified by given range name. /// This technique allows you to project a finite width slice in a real-valued observable /// ///
    `NumCPU(Int_t ncpu)` Number of CPUs to use simultaneously to calculate data-weighted projections (only in combination with ProjWData) @@ -1591,7 +1586,7 @@ void RooAbsReal::plotOnCompSelect(RooArgSet* selNodes) const /// ///
    `Asymmetry(const RooCategory& c)` Show the asymmetry of the PDF in given two-state category [F(+)-F(-)] / [F(+)+F(-)] rather than /// the PDF projection. Category must have two states with indices -1 and +1 or three states with -/// indeces -1,0 and +1. +/// indices -1,0 and +1. /// ///
    `ShiftToZero(bool flag)` Shift entire curve such that lowest visible point is at exactly zero. Mostly useful when plotting \f$ -\log(L) \f$ or \f$ \chi^2 \f$ distributions /// @@ -1692,7 +1687,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const } // Define configuration for this method - RooCmdConfig pc(Form("RooAbsReal::plotOn(%s)",GetName())) ; + RooCmdConfig pc("RooAbsReal::plotOn(" + std::string(GetName()) + ")"); pc.defineString("drawOption","DrawOption",0,"L") ; pc.defineString("projectionRangeName","ProjectionRange",0,"",true) ; pc.defineString("curveNameSuffix","CurveNameSuffix",0,"") ; @@ -1700,7 +1695,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const pc.defineDouble("scaleFactor","Normalization",0,1.0) ; pc.defineInt("scaleType","Normalization",0,Relative) ; pc.defineSet("sliceSet","SliceVars",0) ; - pc.defineObject("sliceCatList","SliceCat",0,0,true) ; + pc.defineObject("sliceCatList","SliceCat",0,nullptr,true) ; // This dummy is needed for plotOn to recognize the "SliceCatMany" command. // It is not used directly, but the "SliceCat" commands are nested in it. // Removing this dummy definition results in "ERROR: unrecognized command: SliceCatMany". @@ -1787,8 +1782,8 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const const RooAbsCategoryLValue* asymCat = (const RooAbsCategoryLValue*) pc.getObject("asymCat") ; - // Look for category slice arguments and add them to the master slice std::list if found - const char* sliceCatState = pc.getString("sliceCatState",0,true) ; + // Look for category slice arguments and add them to the master slice list if found + const char* sliceCatState = pc.getString("sliceCatState",nullptr,true) ; const RooLinkedList& sliceCatList = pc.getObjectList("sliceCatList") ; if (sliceCatState) { @@ -1820,9 +1815,9 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const o.postRangeFracScale = pc.getInt("rangeAdjustNorm") ; if (vlines==2) vlines=0 ; // Default is NoWings if range was specified } else if (pc.hasProcessed("RangeWithName")) { - o.normRangeName = pc.getString("rangeName",0,true) ; - o.rangeLo = frame->getPlotVar()->getMin(pc.getString("rangeName",0,true)) ; - o.rangeHi = frame->getPlotVar()->getMax(pc.getString("rangeName",0,true)) ; + o.normRangeName = pc.getString("rangeName",nullptr,true) ; + o.rangeLo = frame->getPlotVar()->getMin(pc.getString("rangeName",nullptr,true)) ; + o.rangeHi = frame->getPlotVar()->getMax(pc.getString("rangeName",nullptr,true)) ; o.postRangeFracScale = pc.getInt("rangeWNAdjustNorm") ; if (vlines==2) vlines=0 ; // Default is NoWings if range was specified } @@ -1835,11 +1830,11 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const } o.wmode = (vlines==2)?RooCurve::Extended:(vlines==1?RooCurve::Straight:RooCurve::NoWings) ; - o.projectionRangeName = pc.getString("projectionRangeName",0,true) ; - o.curveName = pc.getString("curveName",0,true) ; + o.projectionRangeName = pc.getString("projectionRangeName",nullptr,true) ; + o.curveName = pc.getString("curveName",nullptr,true) ; o.curveInvisible = pc.getInt("curveInvisible") ; o.progress = pc.getInt("showProg") ; - o.addToCurveName = pc.getString("addToCurveName",0,true) ; + o.addToCurveName = pc.getString("addToCurveName",nullptr,true) ; o.addToWgtSelf = pc.getDouble("addToWgtSelf") ; o.addToWgtOther = pc.getDouble("addToWgtOther") ; @@ -1930,7 +1925,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot* frame, RooLinkedList& argList) const /// of the scale factor is unique for generic real functions, for PDFs there are various interpretations /// possible, which can be selection with 'stype' (see RooAbsPdf::plotOn() for details). /// -/// The default projection behaviour can be overriden by supplying an optional set of dependents +/// The default projection behaviour can be overridden by supplying an optional set of dependents /// to project. For most cases, plotSliceOn() and plotProjOn() provide a more intuitive interface /// to modify the default projection behaviour. //_____________________________________________________________________________ @@ -1958,7 +1953,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") ProjDataVars = " << projDataVars << std::endl ; - // Make std::list of variables to be projected + // Make list of variables to be projected RooArgSet projectedVars ; RooArgSet sliceSet ; if (o.projSet) { @@ -1966,7 +1961,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const makeProjectionSet(frame->getPlotVar(),o.projSet,projectedVars,false) ; cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") calculated projectedVars = " << *o.projSet << std::endl ; - // Print std::list of non-projected variables + // Print list of non-projected variables if (frame->getNormVars()) { RooArgSet sliceSetTmp; getObservables(frame->getNormVars(), sliceSetTmp) ; @@ -1994,7 +1989,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") projectedVars = " << projectedVars << " sliceSet = " << sliceSet << std::endl ; - RooArgSet* projDataNeededVars = 0 ; + RooArgSet* projDataNeededVars = nullptr ; // Take out data-projected dependents from projectedVars if (o.projData) { projDataNeededVars = (RooArgSet*) projectedVars.selectCommon(projDataVars) ; @@ -2006,18 +2001,18 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const double oldPlotVarVal = plotVar->getVal(); // Inform user about projections - if (projectedVars.getSize()) { + if (!projectedVars.empty()) { coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName() << " integrates over variables " << projectedVars << (o.projectionRangeName?Form(" in range %s",o.projectionRangeName):"") << std::endl; } - if (projDataNeededVars && projDataNeededVars->getSize()>0) { + if (projDataNeededVars && !projDataNeededVars->empty()) { coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName() << " averages using data variables " << *projDataNeededVars << std::endl ; } // Create projection integral - RooArgSet* projectionCompList = 0 ; + RooArgSet* projectionCompList = nullptr ; RooArgSet deps; getObservables(frame->getNormVars(), deps) ; @@ -2046,7 +2041,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const // Always fix RooAddPdf normalizations RooArgSet fullNormSet(deps) ; fullNormSet.add(projectedVars) ; - if (projDataNeededVars && projDataNeededVars->getSize()>0) { + if (projDataNeededVars && !projDataNeededVars->empty()) { fullNormSet.add(*projDataNeededVars) ; } @@ -2058,12 +2053,13 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const } // Apply data projection, if requested - if (o.projData && projDataNeededVars && projDataNeededVars->getSize()>0) { + if (o.projData && projDataNeededVars && !projDataNeededVars->empty()) { // If data set contains more rows than needed, make reduced copy first RooAbsData* projDataSel = (RooAbsData*)o.projData; + std::unique_ptr projDataSelOwned; - if (projDataNeededVars->getSize()get()->getSize()) { + if (projDataNeededVars->size() < o.projData->get()->size()) { // Determine if there are any slice variables in the projection set std::unique_ptr sliceDataSet{static_cast(sliceSet.selectCommon(*o.projData->get()))}; @@ -2088,17 +2084,16 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const } if (!cutString.IsNull()) { - projDataSel = ((RooAbsData*)o.projData)->reduce(*projDataNeededVars,cutString) ; - coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") reducing given projection dataset to entries with " << cutString << std::endl ; - } else { - projDataSel = ((RooAbsData*)o.projData)->reduce(*projDataNeededVars) ; + coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") reducing given projection dataset to entries with " << cutString << std::endl ; } + projDataSelOwned = std::unique_ptr{const_cast(o.projData)->reduce(*projDataNeededVars, cutString.IsNull() ? nullptr : cutString)}; + projDataSel = projDataSelOwned.get(); coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") only the following components of the projection data will be used: " << *projDataNeededVars << std::endl ; } // Request binning of unbinned projection dataset that consists exclusively of category observables - if (!o.binProjData && dynamic_cast(projDataSel)!=0) { + if (!o.binProjData && dynamic_cast(projDataSel)!=nullptr) { // Determine if dataset contains only categories bool allCat(true) ; @@ -2115,30 +2110,12 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const // Bin projection dataset if requested if (o.binProjData) { - RooAbsData* tmp = new RooDataHist(Form("%s_binned",projDataSel->GetName()),"Binned projection data",*projDataSel->get(),*projDataSel) ; - if (projDataSel!=o.projData) delete projDataSel ; - projDataSel = tmp ; + projDataSelOwned = std::make_unique(std::string(projDataSel->GetName()) + "_binned","Binned projection data",*projDataSel->get(),*projDataSel); + projDataSel = projDataSelOwned.get(); } - - - // Attach dataset - projection->getVal(projDataSel->get()) ; - projection->attachDataSet(*projDataSel) ; - - // Construct optimized data weighted average - RooAbsTestStatistic::Configuration cfg; - cfg.nCPU = o.numCPU; - cfg.interleave = o.interleave; - RooDataWeightedAverage dwa(Form("%sDataWgtAvg",GetName()),"Data Weighted average",*projection,*projDataSel,RooArgSet()/**projDataSel->get()*/, - std::move(cfg), true) ; - //RooDataWeightedAverage dwa(Form("%sDataWgtAvg",GetName()),"Data Weighted average",*projection,*projDataSel,*projDataSel->get(),o.numCPU,o.interleave,true) ; - - // Do _not_ activate cache-and-track as necessary information to define normalization observables are not present in the underlying dataset - dwa.constOptimizeTestStatistic(Activate,false) ; - - RooRealBinding projBind(dwa,*plotVar) ; - RooScaledFunc scaleBind(projBind,o.scaleFactor); + // Construct scaled data weighted average + ScaledDataWeightedAverage scaleBind{*projection, *projDataSel, o.scaleFactor, *plotVar}; // Set default range, if not specified if (o.rangeLo==0 && o.rangeHi==0) { @@ -2147,15 +2124,15 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const } // Construct name of curve for data weighed average - TString curveName(projection->GetName()) ; - curveName.Append(Form("_DataAvg[%s]",projDataSel->get()->contentsString().c_str())) ; + std::string curveName(projection->GetName()) ; + curveName.append("_DataAvg[" + projDataSel->get()->contentsString() + "]"); // Append slice set specification if any - if (sliceSet.getSize()>0) { - curveName.Append(Form("_Slice[%s]",sliceSet.contentsString().c_str())) ; + if (!sliceSet.empty()) { + curveName.append("_Slice[" + sliceSet.contentsString() + "]"); } // Append any suffixes imported from RooAbsPdf::plotOn if (o.curveNameSuffix) { - curveName.Append(o.curveNameSuffix) ; + curveName.append(o.curveNameSuffix) ; } // Curve constructor for data weighted average @@ -2164,7 +2141,7 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const o.rangeLo,o.rangeHi,frame->GetNbinsX(),o.precision,o.precision,o.shiftToZero,o.wmode,o.numee,o.doeeval,o.eeval) ; RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - curve->SetName(curveName.Data()) ; + curve->SetName(curveName.c_str()) ; // Add self to other curve if requested if (o.addToCurveName) { @@ -2185,8 +2162,6 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const // add this new curve to the specified plot frame frame->addPlotable(curve, o.drawOptions, o.curveInvisible); - if (projDataSel!=o.projData) delete projDataSel ; - } else { // Set default range, if not specified @@ -2206,7 +2181,6 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const // Evaluate fractional correction integral always on full p.d.f, not component. GlobalSelectComponentRAII selectCompRAII(true); std::unique_ptr intFrac{projection->createIntegral(*plotVar,*plotVar,o.normRangeName)}; - _globalSelectComp = true; //It's unclear why this is done a second time. Maybe unnecessary. if(o.stype != RooAbsReal::Raw || this->InheritsFrom(RooAbsPdf::Class())){ // this scaling should only be !=1 when plotting partial ranges // still, raw means raw @@ -2218,13 +2192,13 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const // Curve constructor for regular projections // Set default name of curve - TString curveName(projection->GetName()) ; - if (sliceSet.getSize()>0) { - curveName.Append(Form("_Slice[%s]",sliceSet.contentsString().c_str())) ; + std::string curveName(projection->GetName()) ; + if (!sliceSet.empty()) { + curveName.append("_Slice[" + sliceSet.contentsString() + "]"); } if (o.curveNameSuffix) { // Append any suffixes imported from RooAbsPdf::plotOn - curveName.Append(o.curveNameSuffix) ; + curveName.append(o.curveNameSuffix) ; } TString opt(o.drawOptions); @@ -2243,9 +2217,9 @@ RooPlot* RooAbsReal::plotOn(RooPlot *frame, PlotOpt o) const } else { RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; RooCurve *curve = new RooCurve(*projection,*plotVar,o.rangeLo,o.rangeHi,frame->GetNbinsX(), - o.scaleFactor,0,o.precision,o.precision,o.shiftToZero,o.wmode,o.numee,o.doeeval,o.eeval,o.progress); + o.scaleFactor,nullptr,o.precision,o.precision,o.shiftToZero,o.wmode,o.numee,o.doeeval,o.eeval,o.progress); RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - curve->SetName(curveName.Data()) ; + curve->SetName(curveName.c_str()) ; // Add self to other curve if requested if (o.addToCurveName) { @@ -2323,7 +2297,7 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym // Otherwise no projections are performed, // // The asymmetry function can be multiplied with an optional scale factor. The default projection - // behaviour can be overriden by supplying an optional set of dependents to project. + // behaviour can be overridden by supplying an optional set of dependents to project. // Sanity checks if (plotSanityChecks(frame)) return frame ; @@ -2353,13 +2327,13 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym return frame ; } - // Make std::list of variables to be projected + // Make list of variables to be projected RooArgSet projectedVars ; RooArgSet sliceSet ; if (o.projSet) { makeProjectionSet(frame->getPlotVar(),o.projSet,projectedVars,false) ; - // Print std::list of non-projected variables + // Print list of non-projected variables if (frame->getNormVars()) { RooArgSet sliceSetTmp; getObservables(frame->getNormVars(), sliceSetTmp) ; @@ -2383,7 +2357,7 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym // Take out data-projected dependens from projectedVars - RooArgSet* projDataNeededVars = 0 ; + RooArgSet* projDataNeededVars = nullptr ; if (o.projData) { projDataNeededVars = (RooArgSet*) projectedVars.selectCommon(projDataVars) ; projectedVars.remove(projDataVars,true,true) ; @@ -2399,11 +2373,11 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym RooRealVar* plotVar = (RooRealVar*) realVar->Clone() ; // Inform user about projections - if (projectedVars.getSize()) { + if (!projectedVars.empty()) { coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") plot on " << plotVar->GetName() << " projects variables " << projectedVars << std::endl ; } - if (projDataNeededVars && projDataNeededVars->getSize()>0) { + if (projDataNeededVars && !projDataNeededVars->empty()) { coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName() << " averages using data variables "<< *projDataNeededVars << std::endl ; } @@ -2454,14 +2428,16 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym // If data set contains more rows than needed, make reduced copy first RooAbsData* projDataSel = (RooAbsData*)o.projData; - if (projDataNeededVars && projDataNeededVars->getSize()get()->getSize()) { + std::unique_ptr projDataSelOwned; + if (projDataNeededVars && projDataNeededVars->size() < o.projData->get()->size()) { // Determine if there are any slice variables in the projection set - RooArgSet* sliceDataSet = (RooArgSet*) sliceSet.selectCommon(*o.projData->get()) ; + RooArgSet sliceDataSet; + sliceSet.selectCommon(*o.projData->get(), sliceDataSet); TString cutString ; - if (!sliceDataSet->empty()) { + if (!sliceDataSet.empty()) { bool first(true) ; - for(RooAbsArg * sliceVar : *sliceDataSet) { + for(RooAbsArg * sliceVar : sliceDataSet) { if (!first) { cutString.Append("&&") ; } else { @@ -2477,34 +2453,20 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym } } } - delete sliceDataSet ; if (!cutString.IsNull()) { - projDataSel = ((RooAbsData*)o.projData)->reduce(*projDataNeededVars,cutString) ; coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") reducing given projection dataset to entries with " << cutString << std::endl ; - } else { - projDataSel = ((RooAbsData*)o.projData)->reduce(*projDataNeededVars) ; } + projDataSelOwned = std::unique_ptr{const_cast(o.projData)->reduce(*projDataNeededVars,cutString.IsNull() ? nullptr : cutString)}; + projDataSel = projDataSelOwned.get(); coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") only the following components of the projection data will be used: " << *projDataNeededVars << std::endl ; } - RooAbsTestStatistic::Configuration cfg; - cfg.nCPU = o.numCPU; - cfg.interleave = o.interleave; - RooDataWeightedAverage dwa(Form("%sDataWgtAvg",GetName()),"Data Weighted average",funcAsym,*projDataSel,RooArgSet()/**projDataSel->get()*/, - std::move(cfg),true) ; - //RooDataWeightedAverage dwa(Form("%sDataWgtAvg",GetName()),"Data Weighted average",*funcAsym,*projDataSel,*projDataSel->get(),o.numCPU,o.interleave,true) ; - dwa.constOptimizeTestStatistic(Activate) ; - - RooRealBinding projBind(dwa,*plotVar) ; - - ((RooAbsReal*)posProj)->attachDataSet(*projDataSel) ; - ((RooAbsReal*)negProj)->attachDataSet(*projDataSel) ; - - RooScaledFunc scaleBind(projBind,o.scaleFactor); + // Construct scaled data weighted average + ScaledDataWeightedAverage scaleBind{funcAsym, *projDataSel, o.scaleFactor, *plotVar}; // Set default range, if not specified if (o.rangeLo==0 && o.rangeHi==0) { @@ -2516,7 +2478,7 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym TString curveName(funcAsym.GetName()) ; curveName.Append(Form("_DataAvg[%s]",projDataSel->get()->contentsString().c_str())) ; // Append slice set specification if any - if (sliceSet.getSize()>0) { + if (!sliceSet.empty()) { curveName.Append(Form("_Slice[%s]",sliceSet.contentsString().c_str())) ; } // Append any suffixes imported from RooAbsPdf::plotOn @@ -2535,9 +2497,6 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym frame->addPlotable(curve, o.drawOptions); ccoutW(Eval) << std::endl ; - - if (projDataSel!=o.projData) delete projDataSel ; - } else { // Set default range, if not specified @@ -2548,7 +2507,7 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; RooCurve* curve= new RooCurve(funcAsym,*plotVar,o.rangeLo,o.rangeHi,frame->GetNbinsX(), - o.scaleFactor,0,o.precision,o.precision,false,o.wmode,o.numee,o.doeeval,o.eeval); + o.scaleFactor,nullptr,o.precision,o.precision,false,o.wmode,o.numee,o.doeeval,o.eeval); RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; dynamic_cast(curve)->SetLineColor(2) ; @@ -2556,7 +2515,7 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym // Set default name of curve TString curveName(funcAsym.GetName()) ; - if (sliceSet.getSize()>0) { + if (!sliceSet.empty()) { curveName.Append(Form("_Slice[%s]",sliceSet.contentsString().c_str())) ; } if (o.curveNameSuffix) { @@ -2582,17 +2541,19 @@ RooPlot* RooAbsReal::plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue& asym //////////////////////////////////////////////////////////////////////////////// -/// Calculate error on self by *linearly* propagating errors on parameters using the covariance matrix -/// from a fit result. -/// The error is calculated as follows +/// \brief Propagates parameter uncertainties to an uncertainty estimate for this RooAbsReal. +/// +/// Estimates the uncertainty \f$\sigma_f(x;\theta)\f$ on a function \f$f(x;\theta)\f$ represented by this RooAbsReal. +/// Here, \f$\theta\f$ is a vector of parameters with uncertainties \f$\sigma_\theta\f$, and \f$x\f$ are usually observables. +/// The uncertainty is estimated by *linearly* propagating the parameter uncertainties using the correlation matrix from a fit result. +/// +/// The square of the uncertainty on \f$f(x;\theta)\f$ is calculated as follows: /// \f[ -/// \mathrm{error}^2(x) = F_\mathbf{a}(x) \cdot \mathrm{Cov}(\mathbf{a},\mathbf{a}') \cdot F_{\mathbf{a}'}^{\mathrm{T}}(x) +/// \sigma_f(x)^2 = \Delta f_i(x) \cdot \mathrm{Corr}_{i, j} \cdot \Delta f_j(x), /// \f] -/// where \f$ F_mathbf{a}(x) = \frac{ f(x, mathbf{a} + \mathrm{d}mathbf{a}) - f(x, mathbf{a} - \mathrm{d}mathbf{a}) }{2} \f$, -/// with \f$ f(x) = \f$ `this` and \f$ \mathrm{d}mathbf{a} \f$ the vector of one-sigma uncertainties of all -/// fit parameters taken from the fit result and -/// \f$ \mathrm{Cov}(mathbf{a},mathbf{a}') \f$ = the covariance matrix from the fit result. -/// +/// where \f$ \Delta f_i(x) = \frac{1}{2} \left(f(x;\theta_i + \sigma_{\theta_i}) - f(x; \theta_i - \sigma_{\theta_i}) \right) \f$ +/// is the vector of function variations when changing the parameters one at a time, and +/// \f$ \mathrm{Corr}_{i,j} = \left(\sigma_{\theta_i} \sigma_{\theta_j}\right)^{-1} \cdot \mathrm{Cov}_{i,j} \f$ is the correlation matrix from the fit result. double RooAbsReal::getPropagatedError(const RooFitResult &fr, const RooArgSet &nset) const { @@ -2611,7 +2572,7 @@ double RooAbsReal::getPropagatedError(const RooFitResult &fr, const RooArgSet &n if(rrvFitRes->namePtr() == namePtr()) return rrvFitRes->getError(); // Strip out parameters with zero error - if (rrvFitRes->getError() <= rrvFitRes->getVal() * std::numeric_limits::epsilon()) continue; + if (rrvFitRes->getError() <= std::abs(rrvFitRes->getVal()) * std::numeric_limits::epsilon()) continue; // Ignore parameters in the fit result that this RooAbsReal doesn't depend on if(!rrvInAbsReal) continue; @@ -2659,7 +2620,7 @@ double RooAbsReal::getPropagatedError(const RooFitResult &fr, const RooArgSet &n // Re-evaluate this RooAbsReal with the central parameters just to be // extra-safe that a call to `getPropagatedError()` doesn't change any state. - // It should not be necessarry because thanks to the dirty flag propagation + // It should not be necessary because thanks to the dirty flag propagation // the RooAbsReal is re-evaluated anyway the next time getVal() is called. // Still there are imaginable corner cases where it would not be triggered, // for example if the user changes the RooFit operation more after the error @@ -2667,7 +2628,7 @@ double RooAbsReal::getPropagatedError(const RooFitResult &fr, const RooArgSet &n getVal(nset); TMatrixDSym C(paramList.getSize()) ; - std::vector errVec(paramList.getSize()) ; + std::vector errVec(paramList.size()) ; for (int i=0 ; iNcurve=100, Z=2->Ncurve=659, Z=3->Ncurve=11111) /// Intervals from the sampling method can be asymmetric, and may perform better in the presence of strong correlations, but may take (much) /// longer to calculate. @@ -2728,7 +2689,7 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, RooLinkedList plotArgListTmp(argList) ; RooCmdConfig::stripCmdList(plotArgListTmp,"VisualizeError,MoveToBack") ; - // Strip any 'internal normalization' arguments from std::list + // Strip any 'internal normalization' arguments from list RooLinkedList plotArgList ; for (auto * cmd : static_range_cast(plotArgListTmp)) { if (std::string("Normalization")==cmd->GetName()) { @@ -2757,9 +2718,9 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOnWithErrorBand: no curve for central value available" << std::endl; return frame; } - frame->remove(0,false) ; + frame->remove(nullptr,false) ; - RooCurve* band(0) ; + RooCurve* band(nullptr) ; if (!linMethod) { // *** Interval method *** @@ -2787,13 +2748,13 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, // Generate variation curves with above set of parameter values double ymin = frame->GetMinimum() ; double ymax = frame->GetMaximum() ; - RooDataSet* d = paramPdf->generate(errorParams,n) ; + std::unique_ptr generatedData{paramPdf->generate(errorParams,n)}; std::vector cvec ; - for (int i=0 ; inumEntries() ; i++) { - cloneParams.assign(*d->get(i)) ; + for (int i=0 ; inumEntries() ; i++) { + cloneParams.assign(*generatedData->get(i)) ; plotFunc(*cloneFunc); cvec.push_back(frame->getCurve()) ; - frame->remove(0,false) ; + frame->remove(nullptr,false) ; } frame->SetMinimum(ymin) ; frame->SetMaximum(ymax) ; @@ -2840,7 +2801,7 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, } - // Make std::list of parameter instances of cloneFunc in order of error matrix + // Make list of parameter instances of cloneFunc in order of error matrix RooArgList paramList ; const RooArgList& fpf = fr.floatParsFinal() ; std::vector fpf_idx ; @@ -2856,7 +2817,7 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, // Create std::vector of plus,minus variations for each parameter - TMatrixDSym V(paramList.getSize()==fr.floatParsFinal().getSize()? + TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ? fr.covarianceMatrix(): fr.reducedCovarianceMatrix(paramList)) ; @@ -2874,20 +2835,20 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, plotFunc(*cloneFunc); plusVar.push_back(frame->getCurve()) ; - frame->remove(0,false) ; + frame->remove(nullptr,false) ; // Make Minus variation ((RooRealVar*)paramList.at(ivar))->setVal(cenVal-Z*errVal) ; plotFunc(*cloneFunc); minusVar.push_back(frame->getCurve()) ; - frame->remove(0,false) ; + frame->remove(nullptr,false) ; ((RooRealVar*)paramList.at(ivar))->setVal(cenVal) ; } TMatrixDSym C(paramList.getSize()) ; - std::vector errVec(paramList.getSize()) ; + std::vector errVec(paramList.size()) ; for (int i=0 ; igetAttMarker()->SetMarkerSize(markerSize) ; // Adjust name if requested - if (pc.getString("curveName",0,true)) { - band->SetName(pc.getString("curveName",0,true)) ; - } else if (pc.getString("curveNameSuffix",0,true)) { + if (pc.getString("curveName",nullptr,true)) { + band->SetName(pc.getString("curveName",nullptr,true)) ; + } else if (pc.getString("curveNameSuffix",nullptr,true)) { TString name(band->GetName()) ; - name.Append(pc.getString("curveNameSuffix",0,true)) ; + name.Append(pc.getString("curveNameSuffix",nullptr,true)) ; band->SetName(name.Data()) ; } @@ -2984,7 +2945,7 @@ RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, bool RooAbsReal::plotSanityChecks(RooPlot* frame) const { // check that we are passed a valid plot frame to use - if(0 == frame) { + if(nullptr == frame) { coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << std::endl; return true; } @@ -3019,7 +2980,7 @@ bool RooAbsReal::plotSanityChecks(RooPlot* frame) const //////////////////////////////////////////////////////////////////////////////// /// Utility function for plotOn() that constructs the set of /// observables to project when plotting ourselves as function of -/// 'plotVar'. 'allVars' is the std::list of variables that must be +/// 'plotVar'. 'allVars' is the list of variables that must be /// projected, but may contain variables that we do not depend on. If /// 'silent' is cleared, warnings about inconsistent input parameters /// will be printed. @@ -3033,7 +2994,7 @@ void RooAbsReal::makeProjectionSet(const RooAbsArg* plotVar, const RooArgSet* al projectedVars.removeAll() ; if (!allVars) return ; - // Start out with suggested std::list of variables + // Start out with suggested list of variables projectedVars.add(*allVars) ; // Take out plot variable @@ -3101,15 +3062,14 @@ void RooAbsReal::globalSelectComp(bool flag) /// F(x1,x2,x3,x4) returns an object f(x1,x3) that is evaluated using the /// current values of x2 and x4. The caller takes ownership of the returned adaptor. -RooAbsFunc *RooAbsReal::bindVars(const RooArgSet &vars, const RooArgSet* nset, bool clipInvalid) const +RooFit::OwningPtr RooAbsReal::bindVars(const RooArgSet &vars, const RooArgSet* nset, bool clipInvalid) const { - RooAbsFunc *binding= new RooRealBinding(*this,vars,nset,clipInvalid); - if(binding && !binding->isValid()) { + auto binding = std::make_unique(*this,vars,nset,clipInvalid); + if(!binding->isValid()) { coutE(InputArguments) << ClassName() << "::" << GetName() << ":bindVars: cannot bind to " << vars << std::endl ; - delete binding; - binding= 0; + return nullptr; } - return binding; + return RooFit::Detail::owningPtr(std::unique_ptr{std::move(binding)}); } @@ -3136,8 +3096,7 @@ void RooAbsReal::copyCache(const RooAbsArg* source, bool /*valueOnly*/, bool set void RooAbsReal::attachToVStore(RooVectorDataStore& vstore) { - RooVectorDataStore::RealVector* rv = vstore.addReal(this) ; - rv->setBuffer(this,&_value) ; + vstore.addReal(this)->setBuffer(this,&_value); } @@ -3240,7 +3199,7 @@ void RooAbsReal::setTreeBranchStatus(TTree& t, bool active) { TBranch* branch = t.GetBranch(cleanBranchName()) ; if (branch) { - t.SetBranchStatus(cleanBranchName(),active?1:0) ; + t.SetBranchStatus(cleanBranchName(),active?true:false) ; } } @@ -3250,13 +3209,13 @@ void RooAbsReal::setTreeBranchStatus(TTree& t, bool active) /// Create a RooRealVar fundamental object with our properties. The new /// object will be created without any fit limits. -RooAbsArg *RooAbsReal::createFundamental(const char* newname) const +RooFit::OwningPtr RooAbsReal::createFundamental(const char* newname) const { - RooRealVar *fund= new RooRealVar(newname?newname:GetName(),GetTitle(),_value,getUnit()); + auto fund = std::make_unique(newname?newname:GetName(),GetTitle(),_value,getUnit()); fund->removeRange(); fund->setPlotLabel(getPlotLabel()); fund->setAttribute("fundamentalCopy"); - return fund; + return RooFit::Detail::owningPtr(std::move(fund)); } @@ -3404,7 +3363,7 @@ RooNumIntConfig* RooAbsReal::defaultIntegratorConfig() RooNumIntConfig* RooAbsReal::specialIntegratorConfig() const { - return _specIntegratorConfig ; + return _specIntegratorConfig.get(); } @@ -3417,9 +3376,9 @@ RooNumIntConfig* RooAbsReal::specialIntegratorConfig() const RooNumIntConfig* RooAbsReal::specialIntegratorConfig(bool createOnTheFly) { if (!_specIntegratorConfig && createOnTheFly) { - _specIntegratorConfig = new RooNumIntConfig(*defaultIntegratorConfig()) ; + _specIntegratorConfig = std::make_unique(*defaultIntegratorConfig()) ; } - return _specIntegratorConfig ; + return _specIntegratorConfig.get(); } @@ -3457,10 +3416,7 @@ RooNumIntConfig* RooAbsReal::getIntegratorConfig() void RooAbsReal::setIntegratorConfig(const RooNumIntConfig& config) { - if (_specIntegratorConfig) { - delete _specIntegratorConfig ; - } - _specIntegratorConfig = new RooNumIntConfig(config) ; + _specIntegratorConfig = std::make_unique(config); } @@ -3471,10 +3427,7 @@ void RooAbsReal::setIntegratorConfig(const RooNumIntConfig& config) void RooAbsReal::setIntegratorConfig() { - if (_specIntegratorConfig) { - delete _specIntegratorConfig ; - } - _specIntegratorConfig = 0 ; + _specIntegratorConfig.reset(); } @@ -3532,7 +3485,7 @@ double RooAbsReal::maxVal(Int_t /*code*/) const //////////////////////////////////////////////////////////////////////////////// -/// Interface to insert remote error logging messages received by RooRealMPFE into current error loggin stream +/// Interface to insert remote error logging messages received by RooRealMPFE into current error logging stream. void RooAbsReal::logEvalError(const RooAbsReal* originator, const char* origName, const char* message, const char* serverValueString) { @@ -3580,14 +3533,14 @@ void RooAbsReal::logEvalError(const RooAbsReal* originator, const char* origName /// protocol than generic RooFit warning message (which go straight through RooMsgService) /// because evaluation errors can occur in very large numbers in the use of likelihood /// evaluations. In logEvalError mode, controlled by global method enableEvalErrorLogging() -/// messages reported through this function are not printed but all stored in a std::list, +/// messages reported through this function are not printed but all stored in a list, /// along with server values at the time of reporting. Error messages logged in this /// way can be printed in a structured way, eliminating duplicates and with the ability -/// to truncate the std::list by printEvalErrors. This is the standard mode of error logging +/// to truncate the list by printEvalErrors. This is the standard mode of error logging /// during MINUIT operations. If enableEvalErrorLogging() is false, all errors /// reported through this method are passed for immediate printing through RooMsgService. -/// A std::string with server names and values is constructed automatically for error logging -/// purposes, unless a custom std::string with similar information is passed as argument. +/// A string with server names and values is constructed automatically for error logging +/// purposes, unless a custom string with similar information is passed as argument. void RooAbsReal::logEvalError(const char* message, const char* serverValueString) const { @@ -3640,8 +3593,8 @@ void RooAbsReal::logEvalError(const char* message, const char* serverValueString << " server values: " << ee._srvval << std::endl ; } else if (_evalErrorMode==CollectErrors) { if (_evalErrorList[this].second.size() >= 2048) { - // avoid overflowing the error std::list, so if there are very many, print - // the oldest one first, and pop it off the std::list + // avoid overflowing the error list, so if there are very many, print + // the oldest one first, and pop it off the list const EvalError& oee = _evalErrorList[this].second.front(); // print to debug stream, since these would normally be suppressed, and // we do not want to increase the error count in the message service... @@ -3652,7 +3605,7 @@ void RooAbsReal::logEvalError(const char* message, const char* serverValueString << " server values: " << oee._srvval << std::endl ; _evalErrorList[this].second.pop_front(); } - _evalErrorList[this].first = oss2.str().c_str() ; + _evalErrorList[this].first = oss2.str() ; _evalErrorList[this].second.push_back(ee) ; } @@ -3701,7 +3654,7 @@ std::list* RooAbsReal::plotSamplingHint(RooAbsRealLValue& /*obs*/, doubl //////////////////////////////////////////////////////////////////////////////// /// Print all outstanding logged evaluation error on the given ostream. If maxPerNode -/// is zero, only the number of errors for each source (object with unique name) is std::listed. +/// is zero, only the number of errors for each source (object with unique name) is listed. /// If maxPerNode is greater than zero, up to maxPerNode detailed error messages are shown /// per source of errors. A truncation message is shown if there were more errors logged /// than shown. @@ -3775,10 +3728,10 @@ void RooAbsReal::fixAddCoefNormalization(const RooArgSet& addNormSet, bool force std::unique_ptr compSet{getComponents()}; for(auto * pdf : dynamic_range_cast(*compSet)) { if (pdf) { - if (addNormSet.getSize()>0) { + if (!addNormSet.empty()) { pdf->selectNormalization(&addNormSet,force) ; } else { - pdf->selectNormalization(0,force) ; + pdf->selectNormalization(nullptr,force) ; } } } @@ -3811,7 +3764,7 @@ void RooAbsReal::fixAddCoefRange(const char* rangeName, bool force) /// Interface method for function objects to indicate their preferred order of observables /// for scanning their values into a (multi-dimensional) histogram or RooDataSet. The observables /// to be ordered are offered in argument 'obs' and should be copied in their preferred -/// order into argument 'orderdObs', This default implementation indicates no preference +/// order into argument 'orderedObs', This default implementation indicates no preference /// and copies the original order of 'obs' into 'orderedObs' void RooAbsReal::preferredObservableScanOrder(const RooArgSet& obs, RooArgSet& orderedObs) const @@ -3826,7 +3779,7 @@ void RooAbsReal::preferredObservableScanOrder(const RooArgSet& obs, RooArgSet& o //////////////////////////////////////////////////////////////////////////////// /// Calls createRunningIntegral(const RooArgSet&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&) -RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooArgSet& nset) +RooFit::OwningPtr RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooArgSet& nset) { return createRunningIntegral(iset,RooFit::SupNormSet(nset)) ; } @@ -3834,7 +3787,7 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooAr //////////////////////////////////////////////////////////////////////////////// -/// Create an object that represents the running integral of the function over one or more observables std::listed in iset, i.e. +/// Create an object that represents the running integral of the function over one or more observables listed in iset, i.e. /// \f[ /// \int_{x_\mathrm{lo}}^x f(x') \, \mathrm{d}x' /// \f] @@ -3870,13 +3823,13 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooAr /// | `ScanAll()` | Always apply scanning technique /// | `ScanNone()` | Never apply scanning technique -RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsReal::createRunningIntegral(%s)",GetName())) ; - pc.defineSet("supNormSet","SupNormSet",0,0) ; + RooCmdConfig pc("RooAbsReal::createRunningIntegral(" + std::string(GetName()) + ")"); + pc.defineSet("supNormSet","SupNormSet",0,nullptr) ; pc.defineInt("numScanBins","ScanParameters",0,1000) ; pc.defineInt("intOrder","ScanParameters",1,2) ; pc.defineInt("doScanNum","ScanNum",0,1) ; @@ -3887,12 +3840,12 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCm // Process & check varargs pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } // Extract values from named arguments RooArgSet nset ; - if (const RooArgSet* snset = pc.getSet("supNormSet",0)) { + if (const RooArgSet* snset = pc.getSet("supNormSet",nullptr)) { nset.add(*snset) ; } Int_t numScanBins = pc.getInt("numScanBins") ; @@ -3909,8 +3862,8 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCm return createScanRI(iset,nset,numScanBins,intOrder) ; } if (doScanNum) { - std::unique_ptr tmp{static_cast(createIntegral(iset))}; - Int_t isNum= (tmp->numIntRealVars().size()==1) ; + std::unique_ptr tmp{createIntegral(iset)} ; + Int_t isNum= !static_cast(*tmp).numIntRealVars().empty(); if (isNum) { coutI(NumIntegration) << "RooAbsPdf::createRunningIntegral(" << GetName() << ") integration over observable(s) " << iset << " involves numeric integration," << std::endl @@ -3921,7 +3874,7 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCm return isNum ? createScanRI(iset,nset,numScanBins,intOrder) : createIntRI(iset,nset) ; } - return 0 ; + return nullptr; } @@ -3930,14 +3883,14 @@ RooAbsReal* RooAbsReal::createRunningIntegral(const RooArgSet& iset, const RooCm /// Utility function for createRunningIntegral that construct an object /// implementing the numeric scanning technique for calculating the running integral -RooAbsReal* RooAbsReal::createScanRI(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) +RooFit::OwningPtr RooAbsReal::createScanRI(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder) { std::string name = std::string(GetName()) + "_NUMRUNINT_" + integralNameSuffix(iset,&nset).Data() ; RooRealVar* ivar = (RooRealVar*) iset.first() ; ivar->setBins(numScanBins,"numcdf") ; - RooNumRunningInt* ret = new RooNumRunningInt(name.c_str(),name.c_str(),*this,*ivar,"numrunint") ; + auto ret = std::make_unique(name.c_str(),name.c_str(),*this,*ivar,"numrunint") ; ret->setInterpolationOrder(intOrder) ; - return ret ; + return RooFit::Detail::owningPtr(std::move(ret)); } @@ -3947,9 +3900,9 @@ RooAbsReal* RooAbsReal::createScanRI(const RooArgSet& iset, const RooArgSet& nse /// object implementing the standard (analytical) integration /// technique for calculating the running integral. -RooAbsReal* RooAbsReal::createIntRI(const RooArgSet& iset, const RooArgSet& nset) +RooFit::OwningPtr RooAbsReal::createIntRI(const RooArgSet& iset, const RooArgSet& nset) { - // Make std::list of input arguments keeping only RooRealVars + // Make list of input arguments keeping only RooRealVars RooArgList ilist ; for(RooAbsArg * arg : iset) { if (dynamic_cast(arg)) { @@ -3963,7 +3916,7 @@ RooAbsReal* RooAbsReal::createIntRI(const RooArgSet& iset, const RooArgSet& nset RooArgList loList ; RooArgSet clonedBranchNodes ; - // Setup customizer that stores all cloned branches in our non-owning std::list + // Setup customizer that stores all cloned branches in our non-owning list RooCustomizer cust(*this,"cdf") ; cust.setCloneBranchSet(clonedBranchNodes) ; cust.setOwning(false) ; @@ -3992,14 +3945,14 @@ RooAbsReal* RooAbsReal::createIntRI(const RooArgSet& iset, const RooArgSet& nset // Construct final normalization set for c.d.f = integrated observables + any extra specified by user RooArgSet finalNset(nset) ; finalNset.add(cloneList,true) ; - RooAbsReal* cdf = tmp->createIntegral(cloneList,finalNset,"CDF") ; + std::unique_ptr cdf{tmp->createIntegral(cloneList,finalNset,"CDF")}; // Transfer ownership of cloned items to top-level c.d.f object cdf->addOwnedComponents(*tmp) ; cdf->addOwnedComponents(cloneList) ; cdf->addOwnedComponents(loList) ; - return cdf ; + return RooFit::Detail::owningPtr(std::move(cdf)); } @@ -4038,31 +3991,31 @@ TF1* RooAbsReal::asTF(const RooArgList& obs, const RooArgList& pars, const RooAr getObservables(&obs, realObs) ; if (realObs.size() != obs.size()) { coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified observables are not variables of this p.d.f" << std::endl ; - return 0 ; + return nullptr ; } RooArgSet realPars; getObservables(&pars, realPars) ; if (realPars.size() != pars.size()) { coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified parameters are not variables of this p.d.f" << std::endl ; - return 0 ; + return nullptr ; } // Check that all obs and par are of type RooRealVar for (int i=0 ; i(obs.at(i))==0) { + if (dynamic_cast(obs.at(i))==nullptr) { coutE(ObjectHandling) << "RooAbsReal::asTF(" << GetName() << ") ERROR: proposed observable " << obs.at(0)->GetName() << " is not of type RooRealVar" << std::endl ; - return 0 ; + return nullptr ; } } for (int i=0 ; i(pars.at(i))==0) { + if (dynamic_cast(pars.at(i))==nullptr) { coutE(ObjectHandling) << "RooAbsReal::asTF(" << GetName() << ") ERROR: proposed parameter " << pars.at(0)->GetName() << " is not of type RooRealVar" << std::endl ; - return 0 ; + return nullptr ; } } // Create functor and TFx of matching dimension - TF1* tf=0 ; + TF1* tf=nullptr ; RooFunctor* f ; switch(obs.getSize()) { case 1: { @@ -4087,9 +4040,9 @@ TF1* RooAbsReal::asTF(const RooArgList& obs, const RooArgList& pars, const RooAr break ; } default: - coutE(InputArguments) << "RooAbsReal::asTF(" << GetName() << ") ERROR: " << obs.getSize() + coutE(InputArguments) << "RooAbsReal::asTF(" << GetName() << ") ERROR: " << obs.size() << " observables specified, but a ROOT TFx can only have 1,2 or 3 observables" << std::endl ; - return 0 ; + return nullptr ; } // Set initial parameter values of TFx to those of RooRealVars @@ -4180,26 +4133,6 @@ double RooAbsReal::findRoot(RooRealVar& x, double xmin, double xmax, double yval - -//////////////////////////////////////////////////////////////////////////////// - -RooGenFunction* RooAbsReal::iGenFunction(RooRealVar& x, const RooArgSet& nset) -{ - return new RooGenFunction(*this,x,RooArgList(),nset.getSize()>0?nset:RooArgSet(x)) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction* RooAbsReal::iGenFunction(const RooArgSet& observables, const RooArgSet& nset) -{ - return new RooMultiGenFunction(*this,observables,RooArgList(),nset.getSize()>0?nset:observables) ; -} - - - - //////////////////////////////////////////////////////////////////////////////// /// Perform a \f$ \chi^2 \f$ fit to given histogram. By default the fit is executed through the MINUIT /// commands MIGRAD, HESSE in succession @@ -4208,6 +4141,16 @@ RooMultiGenFunction* RooAbsReal::iGenFunction(const RooArgSet& observables, cons /// /// ///
    Options to control construction of chi2 +///
    `Extended(bool flag)` **Only applicable when fitting a RooAbsPdf**. Scale the normalized pdf by the number of events predicted by the model instead of scaling by the total data weight. +/// This imposes a constraint on the predicted number of events analogous to the extended term in a likelihood fit. +/// - If you don't pass this command, an extended fit will be done by default if the pdf makes a prediction on the number of events +/// (in RooFit jargon, "if the pdf can be extended"). +/// - Passing `Extended(true)` when the the pdf makes no prediction on the expected number of events will result in error messages, +/// and the chi2 will fall back to the total data weight to scale the normalized pdf. +/// - There are cases where the fit **must** be done in extended mode. This happens for example when you have a RooAddPdf +/// where the coefficients represent component yields. If the fit is not extended, these coefficients will not be +/// well-defined, as the RooAddPdf always normalizes itself. If you pass `Extended(false)` in such a case, an error will be +/// printed and you'll most likely get garbage results. ///
    `Range(const char* name)` Fit only data inside range with given name ///
    `Range(double lo, double hi)` Fit only data inside given range. A range named "fit" is created on the fly on all observables. /// Multiple comma separated range names can be specified. @@ -4220,7 +4163,7 @@ RooMultiGenFunction* RooAbsReal::iGenFunction(const RooArgSet& observables, cons ///
    `Hesse(bool flag)` Flag controls if HESSE is run after MIGRAD, on by default ///
    `Minos(bool flag)` Flag controls if MINOS is run after HESSE, on by default ///
    `Minos(const RooArgSet& set)` Only run MINOS on given subset of arguments -///
    `Save(bool flag)` Flac controls if RooFitResult object is produced and returned, off by default +///
    `Save(bool flag)` Flag controls if RooFitResult object is produced and returned, off by default ///
    `Strategy(Int_t flag)` Set Minuit strategy (0 through 2, default is 1) /// ///
    Options to control informational output @@ -4235,7 +4178,7 @@ RooMultiGenFunction* RooAbsReal::iGenFunction(const RooArgSet& observables, cons ///
    /// -RooFitResult* RooAbsReal::chi2FitTo(RooDataHist& data, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsReal::chi2FitTo(RooDataHist& data, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { @@ -4251,21 +4194,34 @@ RooFitResult* RooAbsReal::chi2FitTo(RooDataHist& data, const RooCmdArg& arg1, c //////////////////////////////////////////////////////////////////////////////// -/// \copydoc RooAbsReal::chi2FitTo(RooDataHist&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&) +/// Calls RooAbsReal::createChi2(RooDataSet& data, const RooLinkedList& cmdList) and returns fit result. +/// +/// For the list of possible commands in the `cmdList`, see +/// RooAbsReal::chi2FitTo(RooDataHist&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&) and +/// RooAbsPdf::chi2FitTo(RooDataHist&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&). -RooFitResult* RooAbsReal::chi2FitTo(RooDataHist& data, const RooLinkedList& cmdList) +RooFit::OwningPtr RooAbsReal::chi2FitTo(RooDataHist &data, const RooLinkedList &cmdList) { - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::chi2FitTo(%s)",GetName())) ; + // Select the pdf-specific commands + RooCmdConfig pc("RooAbsPdf::chi2FitTo(" + std::string(GetName()) + ")"); - // Pull arguments to be passed to chi2 construction from std::list - RooLinkedList fitCmdList(cmdList) ; - RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList,"Range,RangeWithName,NumCPU,Optimize,IntegrateBins") ; + // Pull arguments to be passed to chi2 construction from list + RooLinkedList fitCmdList(cmdList); - std::unique_ptr chi2{createChi2(data,chi2CmdList)}; - RooFitResult* ret = chi2FitDriver(*chi2,fitCmdList) ; + auto createChi2DataHistCmdArgs = "Range,RangeWithName,NumCPU,Optimize,IntegrateBins,ProjectedObservables," + "AddCoefRange,SplitRange,DataError,Extended"; + RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList, createChi2DataHistCmdArgs); - return ret ; + RooFit::FitHelpers::defineMinimizationOptions(pc); + + // Process and check varargs + pc.process(fitCmdList); + if (!pc.ok(true)) { + return nullptr; + } + + std::unique_ptr chi2{createChi2(data, chi2CmdList)}; + return RooFit::Detail::owningPtr(RooFit::FitHelpers::minimize(*this, *chi2, data, pc)); } @@ -4276,19 +4232,29 @@ RooFitResult* RooAbsReal::chi2FitTo(RooDataHist& data, const RooLinkedList& cmdL /// /// \param arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 ordered arguments /// -/// The std::list of supported command arguments is given in the documentation for +/// The list of supported command arguments is given in the documentation for /// RooChi2Var::RooChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataHist& hdata, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,const RooCmdArg&,const RooCmdArg&). /// /// \param data Histogram with data /// \return \f$ \chi^2 \f$ variable -RooAbsReal* RooAbsReal::createChi2(RooDataHist& data, const RooCmdArg& arg1, const RooCmdArg& arg2, - const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, - const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) +RooFit::OwningPtr RooAbsReal::createChi2(RooDataHist &data, const RooCmdArg &arg1, const RooCmdArg &arg2, + const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6, + const RooCmdArg &arg7, const RooCmdArg &arg8) { - std::string name = Form("chi2_%s_%s",GetName(),data.GetName()) ; + // Construct Chi2 + RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); + std::string baseName = "chi2_" + std::string(GetName()) + "_" + data.GetName(); + + // Clear possible range attributes from previous fits. + removeStringAttribute("fitrange"); + + auto chi2 = std::make_unique(baseName.c_str(), baseName.c_str(), *this, data, arg1, arg2, arg3, arg4, + arg5, arg6, arg7, arg8); + RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); - return new RooChi2Var(name.c_str(),name.c_str(),*this,data,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; + return RooFit::Detail::owningPtr(std::move(chi2)); } @@ -4299,7 +4265,7 @@ RooAbsReal* RooAbsReal::createChi2(RooDataHist& data, const RooCmdArg& arg1, co /// \param data hist data /// \param cmdList List with RooCmdArg() from the table -RooAbsReal* RooAbsReal::createChi2(RooDataHist& data, const RooLinkedList& cmdList) +RooFit::OwningPtr RooAbsReal::createChi2(RooDataHist& data, const RooLinkedList& cmdList) { // Fill array of commands const RooCmdArg* cmds[8] ; @@ -4336,7 +4302,7 @@ RooAbsReal* RooAbsReal::createChi2(RooDataHist& data, const RooLinkedList& cmdLi ///
    `Hesse(bool flag)` Flag controls if HESSE is run after MIGRAD, on by default ///
    `Minos(bool flag)` Flag controls if MINOS is run after HESSE, on by default ///
    `Minos(const RooArgSet& set)` Only run MINOS on given subset of arguments -///
    `Save(bool flag)` Flac controls if RooFitResult object is produced and returned, off by default +///
    `Save(bool flag)` Flag controls if RooFitResult object is produced and returned, off by default ///
    `Strategy(Int_t flag)` Set Minuit strategy (0 through 2, default is 1) /// ///
    Options to control informational output @@ -4350,7 +4316,7 @@ RooAbsReal* RooAbsReal::createChi2(RooDataHist& data, const RooLinkedList& cmdLi /// a positive value is will print details of each error up to numErr messages per p.d.f component. ///
    -RooFitResult* RooAbsReal::chi2FitTo(RooDataSet& xydata, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsReal::chi2FitTo(RooDataSet& xydata, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { @@ -4368,19 +4334,26 @@ RooFitResult* RooAbsReal::chi2FitTo(RooDataSet& xydata, const RooCmdArg& arg1, //////////////////////////////////////////////////////////////////////////////// /// \copydoc RooAbsReal::chi2FitTo(RooDataSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&) -RooFitResult* RooAbsReal::chi2FitTo(RooDataSet& xydata, const RooLinkedList& cmdList) +RooFit::OwningPtr RooAbsReal::chi2FitTo(RooDataSet &xydata, const RooLinkedList &cmdList) { - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::chi2FitTo(%s)",GetName())) ; + // Select the pdf-specific commands + RooCmdConfig pc("RooAbsPdf::chi2FitTo(" + std::string(GetName()) + ")"); - // Pull arguments to be passed to chi2 construction from std::list - RooLinkedList fitCmdList(cmdList) ; - RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList,"YVar,Integrate") ; + // Pull arguments to be passed to chi2 construction from list + RooLinkedList fitCmdList(cmdList); + auto createChi2DataSetCmdArgs = "YVar,Integrate,RangeWithName,NumCPU,Verbose"; + RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList, createChi2DataSetCmdArgs); - std::unique_ptr xychi2{createChi2(xydata,chi2CmdList)}; - RooFitResult* ret = chi2FitDriver(*xychi2,fitCmdList) ; + RooFit::FitHelpers::defineMinimizationOptions(pc); - return ret ; + // Process and check varargs + pc.process(fitCmdList); + if (!pc.ok(true)) { + return nullptr; + } + + std::unique_ptr xychi2{createChi2(xydata, chi2CmdList)}; + return RooFit::Detail::owningPtr(RooFit::FitHelpers::minimize(*this, *xychi2, xydata, pc)); } @@ -4400,7 +4373,7 @@ RooFitResult* RooAbsReal::chi2FitTo(RooDataSet& xydata, const RooLinkedList& cmd /// | `Integrate(bool flag)` | Integrate function over range specified by X errors rather than take value at bin center. /// -RooAbsReal* RooAbsReal::createChi2(RooDataSet& data, const RooCmdArg& arg1, const RooCmdArg& arg2, +RooFit::OwningPtr RooAbsReal::createChi2(RooDataSet& data, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) { @@ -4413,157 +4386,58 @@ RooAbsReal* RooAbsReal::createChi2(RooDataSet& data, const RooCmdArg& arg1, con } - //////////////////////////////////////////////////////////////////////////////// /// See RooAbsReal::createChi2(RooDataSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&) -RooAbsReal* RooAbsReal::createChi2(RooDataSet& data, const RooLinkedList& cmdList) +RooFit::OwningPtr RooAbsReal::createChi2(RooDataSet &data, const RooLinkedList &cmdList) { - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::fitTo(%s)",GetName())) ; - - pc.defineInt("integrate","Integrate",0,0) ; - pc.defineObject("yvar","YVar",0,0) ; + // Select the pdf-specific commands + RooCmdConfig pc("RooAbsReal::createChi2(" + std::string(GetName()) + ")"); + + pc.defineInt("integrate", "Integrate", 0, 0); + pc.defineObject("yvar", "YVar", 0, nullptr); + pc.defineString("rangeName", "RangeWithName", 0, "", true); + pc.defineInt("numcpu", "NumCPU", 0, 1); + pc.defineInt("interleave", "NumCPU", 1, 0); + pc.defineInt("verbose", "Verbose", 0, 0); + + // Process and check varargs + pc.process(cmdList); + if (!pc.ok(true)) { + return nullptr; + } - // Process and check varargs - pc.process(cmdList) ; - if (!pc.ok(true)) { - return 0 ; - } + // Decode command line arguments + bool integrate = pc.getInt("integrate"); + RooRealVar *yvar = static_cast(pc.getObject("yvar")); + const char *rangeName = pc.getString("rangeName", 0, true); + Int_t numcpu = pc.getInt("numcpu"); + Int_t numcpu_strategy = pc.getInt("interleave"); + // strategy 3 works only for RooSimultaneous. + if (numcpu_strategy == 3 && !this->InheritsFrom("RooSimultaneous")) { + coutW(Minimization) << "Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneous, " + "falling back to default strategy = 0" + << endl; + numcpu_strategy = 0; + } + RooFit::MPSplit interl = (RooFit::MPSplit)numcpu_strategy; + bool verbose = pc.getInt("verbose"); - // Decode command line arguments - bool integrate = pc.getInt("integrate") ; - RooRealVar* yvar = (RooRealVar*) pc.getObject("yvar") ; + RooAbsTestStatistic::Configuration cfg; + cfg.rangeName = rangeName ? rangeName : ""; + cfg.nCPU = numcpu; + cfg.interleave = interl; + cfg.verbose = verbose; + cfg.verbose = false; - std::string name = Form("chi2_%s_%s",GetName(),data.GetName()) ; + std::string name = "chi2_" + std::string(GetName()) + "_" + data.GetName(); - if (yvar) { - return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,*yvar,integrate) ; - } else { - return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,integrate) ; - } + return RooFit::Detail::owningPtr( + std::make_unique(name.c_str(), name.c_str(), *this, data, yvar, integrate, cfg)); } - - - -//////////////////////////////////////////////////////////////////////////////// -/// Internal driver function for chi2 fits - -RooFitResult* RooAbsReal::chi2FitDriver(RooAbsReal& fcn, RooLinkedList& cmdList) -{ - // Select the pdf-specific commands - RooCmdConfig pc(Form("RooAbsPdf::chi2FitDriver(%s)",GetName())) ; - - pc.defineInt("optConst","Optimize",0,1) ; - pc.defineInt("verbose","Verbose",0,0) ; - pc.defineInt("doSave","Save",0,0) ; - pc.defineInt("doTimer","Timer",0,0) ; - pc.defineInt("plevel","PrintLevel",0,1) ; - pc.defineInt("strat","Strategy",0,1) ; - pc.defineInt("initHesse","InitialHesse",0,0) ; - pc.defineInt("hesse","Hesse",0,1) ; - pc.defineInt("minos","Minos",0,0) ; - pc.defineInt("ext","Extended",0,2) ; - pc.defineInt("numee","PrintEvalErrors",0,10) ; - pc.defineInt("doWarn","Warnings",0,1) ; - pc.defineString("mintype","Minimizer",0,"") ; - pc.defineString("minalg","Minimizer",1,"minuit") ; - pc.defineSet("minosSet","Minos",0,nullptr) ; - - // Process and check varargs - pc.process(cmdList) ; - if (!pc.ok(true)) { - return 0 ; - } - - // Decode command line arguments - const char* minType = pc.getString("mintype","") ; - const char* minAlg = pc.getString("minalg","minuit") ; - Int_t optConst = pc.getInt("optConst") ; - Int_t verbose = pc.getInt("verbose") ; - Int_t doSave = pc.getInt("doSave") ; - Int_t doTimer = pc.getInt("doTimer") ; - Int_t plevel = pc.getInt("plevel") ; - Int_t strat = pc.getInt("strat") ; - Int_t initHesse= pc.getInt("initHesse") ; - Int_t hesse = pc.getInt("hesse") ; - Int_t minos = pc.getInt("minos") ; - Int_t numee = pc.getInt("numee") ; - Int_t doWarn = pc.getInt("doWarn") ; - const RooArgSet* minosSet = pc.getSet("minosSet"); - - RooFitResult *ret = 0 ; - - // Instantiate MINUIT - RooMinimizer m(fcn) ; - m.setMinimizerType(minType); - - if (doWarn==0) { - // m.setNoWarn() ; WVE FIX THIS - } - - m.setPrintEvalErrors(numee) ; - if (plevel!=1) { - m.setPrintLevel(plevel) ; - } - - if (optConst) { - // Activate constant term optimization - m.optimizeConst(optConst); - } - - if (verbose) { - // Activate verbose options - m.setVerbose(1) ; - } - if (doTimer) { - // Activate timer options - m.setProfile(1) ; - } - - if (strat!=1) { - // Modify fit strategy - m.setStrategy(strat) ; - } - - if (initHesse) { - // Initialize errors with hesse - m.hesse() ; - } - - // Minimize using migrad - m.minimize(minType, minAlg) ; - - if (hesse) { - // Evaluate errors with Hesse - m.hesse() ; - } - - if (minos) { - // Evaluate errs with Minos - if (minosSet) { - m.minos(*minosSet) ; - } else { - m.minos() ; - } - } - - // Optionally return fit result - if (doSave) { - std::string name = Form("fitresult_%s",fcn.GetName()) ; - std::string title = Form("Result of fit of %s ",GetName()) ; - ret = m.save(name.c_str(),title.c_str()) ; - } - - // Cleanup - return ret ; - -} - - //////////////////////////////////////////////////////////////////////////////// /// Return current evaluation error logging mode. @@ -4595,116 +4469,27 @@ void RooAbsReal::setParameterizeIntegral(const RooArgSet& paramVars) for (auto const* arg : paramVars) { if (!dependsOnValue(*arg)) { coutW(InputArguments) << "RooAbsReal::setParameterizeIntegral(" << GetName() - << ") function does not depend on std::listed parameter " << arg->GetName() << ", ignoring" << std::endl ; + << ") function does not depend on listed parameter " << arg->GetName() << ", ignoring" << std::endl ; continue ; } - if (plist.size()>0) plist += ":" ; + if (!plist.empty()) plist += ":" ; plist += arg->GetName() ; } setStringAttribute("CACHEPARAMINT",plist.c_str()) ; } -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate this object for a batch/span of data points. -/// This is the backend used by getValues() to perform computations. A span pointing to the computation results -/// will be stored in `evalData`, and also be returned to getValues(), which then finalises the computation. -/// -/// \note Derived classes should override this function to reach maximal performance. If this function is not overridden, the slower, -/// single-valued evaluate() will be called in a loop. -/// -/// A computation proceeds as follows: -/// - Request input data from all our servers using `getValues(evalData, normSet)`. Those will return -/// - batches of size 1 if their value is constant over the entire dataset. -/// - batches of the size of the dataset stored in `evalData` otherwise. -/// If `evalData` already contains values for those objects, these will return data -/// without recomputing those. -/// - Create a new batch in `evalData` of the same size as those returned from the servers. -/// - Use the input data to perform the computations, and store those in the batch. -/// -/// \note Error checking and normalisation (of PDFs) will be performed in getValues(). -/// -/// \param[in,out] evalData Object holding data that should be used in computations. -/// Computation results have to be stored here. -/// \param[in] normSet Optional normalisation set passed down to the servers of this object. -/// \return Span pointing to the results. The memory is owned by `evalData`. -RooSpan RooAbsReal::evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { - - // Find all servers that are serving real numbers to us, retrieve their batch data, - // and switch them into "always clean" operating mode, so they return always the last-set value. - struct ServerData { - RooAbsReal* server; - RooSpan batch; - double oldValue; - RooAbsArg::OperMode oldOperMode; - }; - std::vector ourServers; - std::size_t dataSize = 1; - - for (auto absArgServer : servers()) { - if (absArgServer->IsA()->InheritsFrom(RooAbsReal::Class()) && absArgServer->isValueServer(*this)) { - auto server = static_cast(absArgServer); - ourServers.push_back({server, - server->getValues(evalData, normSet), - server->getVal(normSet), - server->operMode()}); - // Prevent the server from evaluating; just return cached result, which we will side load: - server->setOperMode(RooAbsArg::AClean); - dataSize = std::max(dataSize, ourServers.back().batch.size()); - } - } - - - // Make sure that we restore all state when we finish: - struct RestoreStateRAII { - RestoreStateRAII(std::vector& servers) : - _servers{servers} { } - - ~RestoreStateRAII() { - for (auto& serverData : _servers) { - serverData.server->setCachedValue(serverData.oldValue, true); - serverData.server->setOperMode(serverData.oldOperMode); - } - } - - std::vector& _servers; - } restoreState{ourServers}; - - - // Advising to implement the batch interface makes only sense if the batch was not a scalar. - // Otherwise, there would be no speedup benefit. - if(dataSize > 1 && RooMsgService::instance().isActive(this, RooFit::FastEvaluations, RooFit::INFO)) { - coutI(FastEvaluations) << "The class " << ClassName() << " does not implement the faster batch evaluation interface." - << " Consider requesting or implementing it to benefit from a speed up." << std::endl; - } - - - // For each event, write temporary values into our servers' caches, and run a single-value computation. - auto outputData = evalData.makeBatch(this, dataSize); - - for (std::size_t i=0; i < outputData.size(); ++i) { - for (auto& serv : ourServers) { - serv.server->setCachedValue(serv.batch[std::min(i, serv.batch.size()-1)], /*notifyClients=*/ false); - } - - outputData[i] = evaluate(); - } - - return outputData; -} - - /** Base function for computing multiple values of a RooAbsReal \param output The array where the results are stored \param nEvents The number of events to be processed \param dataMap A std::map containing the input data for the computations **/ -void RooAbsReal::computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { +void RooAbsReal::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { // Find all servers that are serving real numbers to us, retrieve their batch data, // and switch them into "always clean" operating mode, so they return always the last-set value. struct ServerData { RooAbsArg* server; - RooSpan batch; + std::span batch; double oldValue; RooAbsArg::OperMode oldOperMode; bool oldValueDirty; @@ -4770,8 +4555,22 @@ void RooAbsReal::computeBatch(cudaStream_t*, double* output, size_t nEvents, Roo } } - - +//////////////////////////////////////////////////////////////////////////////// +/// This function defines the analytical integral translation for the class. +/// +/// \param[in] code The code that decides the integrands. +/// \param[in] rangeName Name of the normalization range. +/// \param[in] ctx An object to manage auxiliary information for code-squashing. +/// +/// \returns The representative code string of the integral for the given object. +std::string RooAbsReal::buildCallToAnalyticIntegral(Int_t /* code */, const char * /* rangeName */, + RooFit::Detail::CodeSquashContext & /*ctx*/) const +{ + std::stringstream errorMsg; + errorMsg << "An analytical integral function for class \"" << ClassName() << "\" has not yet been implemented."; + coutE(Minimization) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); +} double RooAbsReal::_DEBUG_getVal(const RooArgSet* normalisationSet) const { @@ -4813,82 +4612,10 @@ double RooAbsReal::_DEBUG_getVal(const RooArgSet* normalisationSet) const { } -//////////////////////////////////////////////////////////////////////////////// -/// Walk through expression tree headed by the `this` object, and check a batch computation. -/// -/// Check if the results in `evalData` for event `evtNo` are identical to the current value of the nodes. -/// If a difference is found, an exception is thrown, and propagates up the expression tree. The tree is formatted -/// to see where the computation error happened. -/// @param evalData Data with results of batch computation. This is checked against the current value of the expression tree. -/// @param evtNo Event from `evalData` to check for. -/// @param normSet Optional normalisation set that was used in computation. -/// @param relAccuracy Accuracy required for passing the check. -void RooAbsReal::checkBatchComputation(const RooBatchCompute::RunContext& evalData, std::size_t evtNo, const RooArgSet* normSet, double relAccuracy) const { - for (const auto server : _serverList) { - try { - auto realServer = dynamic_cast(server); - if (realServer) - realServer->checkBatchComputation(evalData, evtNo, normSet, relAccuracy); - } catch (CachingError& error) { - throw CachingError(std::move(error), - FormatPdfTree() << *this); - } - } - - const auto item = evalData.spans.find(this); - if (item == evalData.spans.end()) - return; - - auto batch = item->second; - const double value = getVal(normSet); - const double batchVal = batch.size() == 1 ? batch[0] : batch[evtNo]; - const double relDiff = value != 0. ? (value - batchVal)/value : value - batchVal; - - if (fabs(relDiff) > relAccuracy && fabs(value) > 1.E-300) { - FormatPdfTree formatter; - formatter << "--> (Batch computation wrong:)\n"; - printStream(formatter.stream(), kName | kClassName | kArgs | kExtras | kAddress, kInline); - formatter << "\n batch=" << batch.data() << " size=" << batch.size() << std::setprecision(17) - << "\n batch[" << std::setw(7) << evtNo-1 << "]= " << (evtNo > 0 && evtNo - 1 < batch.size() ? std::to_string(batch[evtNo-1]) : "---") - << "\n batch[" << std::setw(7) << evtNo << "]= " << batchVal << " !!!" - << "\n expected ('value'): " << value - << "\n eval(unnorm.) : " << evaluate() - << "\n delta " << " = " << value - batchVal - << "\n rel delta " << " = " << relDiff - << "\n _batch[" << std::setw(7) << evtNo+1 << "]= " << (batch.size() > evtNo+1 ? std::to_string(batch[evtNo+1]) : "---"); - - - - formatter << "\nServers: "; - for (const auto server : _serverList) { - formatter << "\n - "; - server->printStream(formatter.stream(), kName | kClassName | kArgs | kExtras | kAddress | kValue, kInline); - formatter << std::setprecision(17); - - auto serverAsReal = dynamic_cast(server); - if (serverAsReal) { - auto serverBatch = evalData.spans.count(serverAsReal) != 0 ? evalData.spans.find(serverAsReal)->second : RooSpan(); - if (serverBatch.size() > evtNo) { - formatter << "\n _batch[" << evtNo-1 << "]=" << (serverBatch.size() > evtNo-1 ? std::to_string(serverBatch[evtNo-1]) : "---") - << "\n _batch[" << evtNo << "]=" << serverBatch[evtNo] - << "\n _batch[" << evtNo+1 << "]=" << (serverBatch.size() > evtNo+1 ? std::to_string(serverBatch[evtNo+1]) : "---"); - } - else { - formatter << std::setprecision(17) - << "\n getVal()=" << serverAsReal->getVal(normSet); - } - } - } - - throw CachingError(formatter); - } -} - - bool RooAbsReal::redirectServersHook(const RooAbsCollection & newServerList, bool mustReplaceAll, bool nameChange, bool isRecursiveStep) { - _lastNSet = nullptr ; + _lastNormSetId = RooFit::UniqueId::nullval; return RooAbsArg::redirectServersHook(newServerList, mustReplaceAll, nameChange, isRecursiveStep); } @@ -4903,3 +4630,6 @@ void RooAbsReal::enableOffsetting(bool flag) } } } + + +RooAbsReal::Ref::Ref(double val) : _ref{RooFit::RooConst(val)} {} diff --git a/roofit/roofitcore/src/RooAbsRealLValue.cxx b/roofit/roofitcore/src/RooAbsRealLValue.cxx index 53cd9be946f31..15445c39865df 100644 --- a/roofit/roofitcore/src/RooAbsRealLValue.cxx +++ b/roofit/roofitcore/src/RooAbsRealLValue.cxx @@ -40,6 +40,7 @@ interpreted as a parameter. #include "RooArgList.h" #include "RooAbsBinning.h" #include "RooBinning.h" +#include "RooNumber.h" #include "RooUniformBinning.h" #include "RooCmdConfig.h" #include "RooAbsData.h" @@ -89,10 +90,19 @@ RooAbsRealLValue::~RooAbsRealLValue() //////////////////////////////////////////////////////////////////////////////// /// Return true if the input value is within our fit range. Otherwise, return /// false and write a clipped value into clippedValPtr if it is non-zero. - +/// +/// Implements the following check to see if the value x is in the range [a, b]: +/// check if `[x - eps * x, x + eps * x]` overlaps with `[a, b]`, where the +/// parameter `eps` is defined as: +/// ``` +/// std::max(RooNumber::rangeEpsRel() * std::abs(x), RooNumber::rangeEpsAbs()) +/// ``` +/// By default, RooNumber::rangeEpsRel() and RooNumber::rangeEpsRel() are set to zero. +/// You can change them with RooNumber::setRangeEpsRel(double) and RooNumber::setRangeEpsAbs(double), +/// but this should be only done if there is no other solution. bool RooAbsRealLValue::inRange(double value, const char* rangeName, double* clippedValPtr) const { - // double range = getMax() - getMin() ; // ok for +/-INIFINITY + // double range = getMax() - getMin() ; // ok for +/-INFINITY double clippedValue(value); bool isInRange(true) ; @@ -100,13 +110,15 @@ bool RooAbsRealLValue::inRange(double value, const char* rangeName, double* clip double min = binning.lowBound() ; double max = binning.highBound() ; + const double epsilon = std::max(RooNumber::rangeEpsRel() * std::abs(value), RooNumber::rangeEpsAbs()); + // test this value against our upper fit limit - if(!RooNumber::isInfinite(max) && value > (max+1e-6)) { + if(!RooNumber::isInfinite(max) && value > (max+epsilon)) { clippedValue = max; isInRange = false ; } // test this value against our lower fit limit - if(!RooNumber::isInfinite(min) && value < min-1e-6) { + if(!RooNumber::isInfinite(min) && value < min-epsilon) { clippedValue = min ; isInRange = false ; } @@ -117,6 +129,8 @@ bool RooAbsRealLValue::inRange(double value, const char* rangeName, double* clip } +//////////////////////////////////////////////////////////////////////////////// +/// Vectorized version of RooAbsRealLValue::inRange(double, const char*, double*). void RooAbsRealLValue::inRange(std::span values, std::string const& rangeName, std::vector& out) const { if(rangeName.empty()) { return; @@ -125,11 +139,16 @@ void RooAbsRealLValue::inRange(std::span values, std::string const const RooAbsBinning& binning = getBinning(rangeName.c_str()) ; const double min = binning.lowBound() ; const double max = binning.highBound() ; + const bool infiniteMin = RooNumber::isInfinite(min); const bool infiniteMax = RooNumber::isInfinite(max); + const double epsRel = RooNumber::rangeEpsRel(); + const double epsAbs = RooNumber::rangeEpsAbs(); + for(std::size_t i = 0; i < values.size(); ++i) { - out[i] = out[i] && ((infiniteMax | (values[i] <= (max+1e-6))) && (infiniteMin | (values[i] >= (min-1e-6)))); + const double eps = std::max(epsRel * std::abs(values[i]), epsAbs); + out[i] = out[i] && ((infiniteMax | (values[i] <= (max+eps))) && (infiniteMin | (values[i] >= (min-eps)))); } } @@ -140,7 +159,7 @@ void RooAbsRealLValue::inRange(std::span values, std::string const bool RooAbsRealLValue::isValidReal(double value, bool verbose) const { - if (!inRange(value,0)) { + if (!inRange(value,nullptr)) { if (verbose) coutI(InputArguments) << "RooRealVar::isValid(" << GetName() << "): value " << value << " out of range (" << getMin() << " - " << getMax() << ")" << endl ; @@ -177,7 +196,7 @@ RooAbsArg& RooAbsRealLValue::operator=(double newValue) { double clipValue ; // Clip - inRange(newValue,0,&clipValue) ; + inRange(newValue,nullptr,&clipValue) ; setVal(clipValue) ; return *this ; @@ -223,7 +242,7 @@ RooPlot* RooAbsRealLValue::frame(const RooCmdArg& arg1, const RooCmdArg& arg2, c RooPlot* RooAbsRealLValue::frame(const RooLinkedList& cmdList) const { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsRealLValue::frame(%s)",GetName())) ; + RooCmdConfig pc("RooAbsRealLValue::frame(" + std::string(GetName()) + ")"); pc.defineDouble("min","Range",0,getMin()) ; pc.defineDouble("max","Range",1,getMax()) ; pc.defineInt("nbins","Bins",0,getBins()) ; @@ -231,14 +250,14 @@ RooPlot* RooAbsRealLValue::frame(const RooLinkedList& cmdList) const pc.defineString("name","Name",0,"") ; pc.defineString("title","Title",0,"") ; pc.defineMutex("Range","RangeWithName","AutoRange") ; - pc.defineObject("rangeData","AutoRange",0,0) ; + pc.defineObject("rangeData","AutoRange",0,nullptr) ; pc.defineDouble("rangeMargin","AutoRange",0,0.1) ; pc.defineInt("rangeSym","AutoRange",0,0) ; // Process & check varargs pc.process(cmdList) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } // Extract values from named arguments @@ -251,7 +270,7 @@ RooPlot* RooAbsRealLValue::frame(const RooLinkedList& cmdList) const xmax = getMax() ; } } else if (pc.hasProcessed("RangeWithName")) { - const char* rangeName=pc.getString("rangeName",0,true) ; + const char* rangeName=pc.getString("rangeName",nullptr,true) ; xmin = getMin(rangeName) ; xmax = getMax(rangeName) ; } else if (pc.hasProcessed("AutoRange")) { @@ -284,8 +303,8 @@ RooPlot* RooAbsRealLValue::frame(const RooLinkedList& cmdList) const } Int_t nbins = pc.getInt("nbins") ; - const char* name = pc.getString("name",0,true) ; - const char* title = pc.getString("title",0,true) ; + const char* name = pc.getString("name",nullptr,true) ; + const char* title = pc.getString("title",nullptr,true) ; RooPlot* theFrame = new RooPlot(*this,xmin,xmax,nbins) ; @@ -340,11 +359,11 @@ RooPlot *RooAbsRealLValue::frame(Int_t nbins) const // Plot range of variable may not be infinite or empty if (getMin()==getMax()) { coutE(InputArguments) << "RooAbsRealLValue::frame(" << GetName() << ") ERROR: empty fit range, must specify plot range" << endl ; - return 0 ; + return nullptr ; } if (RooNumber::isInfinite(getMin())||RooNumber::isInfinite(getMax())) { coutE(InputArguments) << "RooAbsRealLValue::frame(" << GetName() << ") ERROR: open ended fit range, must specify plot range" << endl ; - return 0 ; + return nullptr ; } return new RooPlot(*this,getMin(),getMax(),nbins); @@ -365,11 +384,11 @@ RooPlot *RooAbsRealLValue::frame() const // Plot range of variable may not be infinite or empty if (getMin()==getMax()) { coutE(InputArguments) << "RooAbsRealLValue::frame(" << GetName() << ") ERROR: empty fit range, must specify plot range" << endl ; - return 0 ; + return nullptr ; } if (RooNumber::isInfinite(getMin())||RooNumber::isInfinite(getMax())) { coutE(InputArguments) << "RooAbsRealLValue::frame(" << GetName() << ") ERROR: open ended fit range, must specify plot range" << endl ; - return 0 ; + return nullptr ; } return new RooPlot(*this,getMin(),getMax(),getBins()); @@ -490,10 +509,20 @@ bool RooAbsRealLValue::fitRangeOKForPlotting() const /// Check if current value is inside range with given name. Multiple comma-separated /// ranges can be passed. In this case, it will be checked if the value is in any of /// these ranges. +/// +/// Implements the following check to see if the value x is in the range [a, b]: +/// check if `[x - eps * x, x + eps * x]` overlaps with `[a, b]`, where the +/// parameter `eps` is defined as: +/// ``` +/// std::max(RooNumber::rangeEpsRel() * std::abs(x), RooNumber::rangeEpsAbs()) +/// ``` +/// By default, RooNumber::rangeEpsRel() and RooNumber::rangeEpsRel() are set to zero. +/// You can change them with RooNumber::setRangeEpsRel(double) and RooNumber::setRangeEpsAbs(double), +/// but this should be only done if there is no other solution. bool RooAbsRealLValue::inRange(const char* name) const { const double val = getVal() ; - const double epsilon = 1e-8 * fabs(val) ; + const double epsilon = std::max(RooNumber::rangeEpsRel() * std::abs(val), RooNumber::rangeEpsAbs()); if (!name || name[0] == '\0') { const auto minMax = getRange(nullptr); return minMax.first - epsilon <= val && val <= minMax.second + epsilon; @@ -557,23 +586,23 @@ TH1* RooAbsRealLValue::createHistogram(const char *name, const RooCmdArg& arg1, TH1* RooAbsRealLValue::createHistogram(const char *name, const RooLinkedList& cmdList) const { // Define configuration for this method - RooCmdConfig pc(Form("RooAbsRealLValue::createHistogram(%s)",GetName())) ; + RooCmdConfig pc("RooAbsRealLValue::createHistogram(" + std::string(GetName()) + ")"); - pc.defineObject("xbinning","Binning",0,0) ; + pc.defineObject("xbinning","Binning",0,nullptr) ; pc.defineString("xbinningName","BinningName",0,"") ; pc.defineInt("nxbins","BinningSpec",0) ; pc.defineDouble("xlo","BinningSpec",0,0) ; pc.defineDouble("xhi","BinningSpec",1,0) ; - pc.defineObject("yvar","YVar",0,0) ; - pc.defineObject("ybinning","YVar::Binning",0,0) ; + pc.defineObject("yvar","YVar",0,nullptr) ; + pc.defineObject("ybinning","YVar::Binning",0,nullptr) ; pc.defineString("ybinningName","YVar::BinningName",0,"") ; pc.defineInt("nybins","YVar::BinningSpec",0) ; pc.defineDouble("ylo","YVar::BinningSpec",0,0) ; pc.defineDouble("yhi","YVar::BinningSpec",1,0) ; - pc.defineObject("zvar","ZVar",0,0) ; - pc.defineObject("zbinning","ZVar::Binning",0,0) ; + pc.defineObject("zvar","ZVar",0,nullptr) ; + pc.defineObject("zbinning","ZVar::Binning",0,nullptr) ; pc.defineString("zbinningName","ZVar::BinningName",0,"") ; pc.defineInt("nzbins","ZVar::BinningSpec",0) ; pc.defineDouble("zlo","ZVar::BinningSpec",0,0) ; @@ -586,7 +615,7 @@ TH1* RooAbsRealLValue::createHistogram(const char *name, const RooLinkedList& cm // Process & check varargs pc.process(cmdList) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } // Initialize arrays for call to implementation version of createHistogram @@ -600,7 +629,7 @@ TH1* RooAbsRealLValue::createHistogram(const char *name, const RooLinkedList& cm if (pc.hasProcessed("Binning")) { binning[0] = static_cast(pc.getObject("xbinning")) ; } else if (pc.hasProcessed("BinningName")) { - binning[0] = &getBinning(pc.getString("xbinningName",0,true)) ; + binning[0] = &getBinning(pc.getString("xbinningName",nullptr,true)) ; } else if (pc.hasProcessed("BinningSpec")) { double xlo = pc.getDouble("xlo") ; double xhi = pc.getDouble("xhi") ; @@ -616,7 +645,7 @@ TH1* RooAbsRealLValue::createHistogram(const char *name, const RooLinkedList& cm if (pc.hasProcessed("YVar::Binning")) { binning[1] = static_cast(pc.getObject("ybinning")) ; } else if (pc.hasProcessed("YVar::BinningName")) { - binning[1] = &yvar.getBinning(pc.getString("ybinningName",0,true)) ; + binning[1] = &yvar.getBinning(pc.getString("ybinningName",nullptr,true)) ; } else if (pc.hasProcessed("YVar::BinningSpec")) { double ylo = pc.getDouble("ylo") ; double yhi = pc.getDouble("yhi") ; @@ -633,7 +662,7 @@ TH1* RooAbsRealLValue::createHistogram(const char *name, const RooLinkedList& cm if (pc.hasProcessed("ZVar::Binning")) { binning[2] = static_cast(pc.getObject("zbinning")) ; } else if (pc.hasProcessed("ZVar::BinningName")) { - binning[2] = &zvar.getBinning(pc.getString("zbinningName",0,true)) ; + binning[2] = &zvar.getBinning(pc.getString("zbinningName",nullptr,true)) ; } else if (pc.hasProcessed("ZVar::BinningSpec")) { double zlo = pc.getDouble("zlo") ; double zhi = pc.getDouble("zhi") ; @@ -669,7 +698,7 @@ TH1F *RooAbsRealLValue::createHistogram(const char *name, const char *yAxisLabel if (!fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } RooArgList list(*this) ; @@ -727,7 +756,7 @@ TH2F *RooAbsRealLValue::createHistogram(const char *name, const RooAbsRealLValue if ((!xlo && xhi) || (xlo && !xhi)) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR must specify either no range, or both limits" << endl ; - return 0 ; + return nullptr ; } double xlo_fit[2] ; @@ -743,12 +772,12 @@ TH2F *RooAbsRealLValue::createHistogram(const char *name, const RooAbsRealLValue if (!fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } if (!yvar.fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range of " << yvar.GetName() << " empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } xlo_fit[0] = getMin() ; @@ -801,7 +830,7 @@ TH3F *RooAbsRealLValue::createHistogram(const char *name, const RooAbsRealLValue if ((!xlo && xhi) || (xlo && !xhi)) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR must specify either no range, or both limits" << endl ; - return 0 ; + return nullptr ; } double xlo_fit[3] ; @@ -816,17 +845,17 @@ TH3F *RooAbsRealLValue::createHistogram(const char *name, const RooAbsRealLValue if (!fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } if (!yvar.fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range of " << yvar.GetName() << " empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } if (!zvar.fitRangeOKForPlotting()) { coutE(InputArguments) << "RooAbsRealLValue::createHistogram(" << GetName() << ") ERROR: fit range of " << zvar.GetName() << " empty or open ended, must explicitly specify range" << endl ; - return 0 ; + return nullptr ; } xlo_fit[0] = getMin() ; @@ -879,8 +908,8 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const const RooAbsBinning* bin[3] ; Int_t ndim = vars.getSize() ; bin[0] = new RooUniformBinning(xlo[0],xhi[0],nBins[0]) ; - bin[1] = (ndim>1) ? new RooUniformBinning(xlo[1],xhi[1],nBins[1]) : 0 ; - bin[2] = (ndim>2) ? new RooUniformBinning(xlo[2],xhi[2],nBins[2]) : 0 ; + bin[1] = (ndim>1) ? new RooUniformBinning(xlo[1],xhi[1],nBins[1]) : nullptr ; + bin[2] = (ndim>2) ? new RooUniformBinning(xlo[2],xhi[2],nBins[2]) : nullptr ; TH1* ret = createHistogram(name,vars,tAxisLabel,bin) ; @@ -905,7 +934,7 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const Int_t dim= vars.getSize(); if(dim < 1 || dim > 3) { oocoutE(nullptr,InputArguments) << "RooAbsReal::createHistogram: dimension not supported: " << dim << endl; - return 0; + return nullptr; } // Check that all variables are AbsReals and prepare a name of the form __... @@ -919,7 +948,7 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const xyz[index]= dynamic_cast(arg); if(!xyz[index]) { oocoutE(nullptr,InputArguments) << "RooAbsRealLValue::createHistogram: variable is not real lvalue: " << arg->GetName() << endl; - return 0; + return nullptr; } histName.Append("_"); histName.Append(arg->GetName()); @@ -928,7 +957,7 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const histTitle.Prepend("Histogram of "); // Create the histogram - TH1 *histogram = 0; + TH1 *histogram = nullptr; switch(dim) { case 1: if (bins[0]->isUniform()) { @@ -966,7 +995,7 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const } if(!histogram) { oocoutE(nullptr,InputArguments) << "RooAbsReal::createHistogram: unable to create a new histogram" << endl; - return 0; + return nullptr; } // Set the histogram coordinate axis labels from the titles of each variable, adding units if necessary. @@ -989,7 +1018,7 @@ TH1 *RooAbsRealLValue::createHistogram(const char *name, RooArgList &vars, const } // Set the t-axis title if given one - if((0 != tAxisLabel) && (0 != strlen(tAxisLabel))) { + if((nullptr != tAxisLabel) && (0 != strlen(tAxisLabel))) { TString axisTitle(tAxisLabel); axisTitle.Append(" / ( "); for(Int_t index2= 0; index2 < dim; index2++) { @@ -1032,7 +1061,7 @@ bool RooAbsRealLValue::isJacobianOK(const RooArgSet&) const } -RooAbsReal* RooAbsRealLValue::createIntegral(const RooArgSet&, const RooArgSet*, const RooNumIntConfig*, const char*) const +RooFit::OwningPtr RooAbsRealLValue::createIntegral(const RooArgSet&, const RooArgSet*, const RooNumIntConfig*, const char*) const { std::stringstream errStream; errStream << "Attempting to integrate the " << ClassName() << " \"" << GetName() diff --git a/roofit/roofitcore/src/RooAbsRootFinder.cxx b/roofit/roofitcore/src/RooAbsRootFinder.cxx deleted file mode 100644 index 2898b6c0c1419..0000000000000 --- a/roofit/roofitcore/src/RooAbsRootFinder.cxx +++ /dev/null @@ -1,48 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooAbsRootFinder.cxx -\class RooAbsRootFinder -\ingroup Roofitcore - -RooAbsRootFinder is the abstract interface for finding roots of real-valued -1-dimensional function that implements the RooAbsFunc interface. -**/ - -#include "RooAbsRootFinder.h" -#include "RooAbsFunc.h" -#include "RooMsgService.h" -#include "Riostream.h" - -using namespace std; - -ClassImp(RooAbsRootFinder); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor take function binding as argument - -RooAbsRootFinder::RooAbsRootFinder(const RooAbsFunc& function) : - _function(&function), _valid(function.isValid()) -{ - if(_function->getDimension() != 1) { - oocoutE(nullptr,Eval) << "RooAbsRootFinder:: cannot find roots for function of dimension " - << _function->getDimension() << endl; - _valid= false; - } -} diff --git a/roofit/roofitcore/src/RooAbsSelfCachedPdf.cxx b/roofit/roofitcore/src/RooAbsSelfCachedPdf.cxx deleted file mode 100644 index 08b17f9a343d2..0000000000000 --- a/roofit/roofitcore/src/RooAbsSelfCachedPdf.cxx +++ /dev/null @@ -1,143 +0,0 @@ - /***************************************************************************** - * Project: RooFit * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooAbsSelfCachedPdf.cxx -\class RooAbsSelfCachedPdf -\ingroup Roofitcore - -RooAbsSelfCachedPdf is an abstract base class for probability -density functions whose output is cached in terms of a histogram in -all observables between getVal() and evaluate(). For certain -p.d.f.s that are very expensive to calculate it may be beneficial -to implement them as a RooAbsSelfCachedPdf rather than a -RooAbsPdf. Class RooAbsSelfCachedPdf is designed to have its -interface identical to that of RooAbsPdf, so any p.d.f can make use -of its caching functionality by merely switching its base class. -Existing RooAbsPdf objects can also be cached a posteriori with the -RooCachedPdf wrapper p.d.f. that takes any RooAbsPdf object as -input. -**/ - -#include "Riostream.h" - -#include "RooAbsSelfCachedPdf.h" -#include "RooAbsReal.h" -#include "RooMsgService.h" -#include "RooDataHist.h" -#include "RooHistPdf.h" - -using namespace std ; - -ClassImp(RooAbsSelfCachedPdf); - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -RooAbsSelfCachedPdf::RooAbsSelfCachedPdf(const char *name, const char *title, Int_t ipOrder) : - RooAbsCachedPdf(name,title,ipOrder) - { - } - - - -//////////////////////////////////////////////////////////////////////////////// -/// Copy constructor - -RooAbsSelfCachedPdf::RooAbsSelfCachedPdf(const RooAbsSelfCachedPdf& other, const char* name) : - RooAbsCachedPdf(other,name) - { - } - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooAbsSelfCachedPdf::~RooAbsSelfCachedPdf() -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Fill cache with sampling of p.d.f as defined by the evaluate() implementation - -void RooAbsSelfCachedPdf::fillCacheObject(RooAbsCachedPdf::PdfCacheElem& cache) const -{ - RooDataHist& cacheHist = *cache.hist() ; - - // Make deep clone of self in non-caching mde and attach to dataset observables - RooArgSet* cloneSet = (RooArgSet*) RooArgSet(*this).snapshot(true) ; - RooAbsSelfCachedPdf* clone2 = (RooAbsSelfCachedPdf*) cloneSet->find(GetName()) ; - clone2->disableCache(true) ; - clone2->attachDataSet(cacheHist) ; - - // Iterator over all bins of RooDataHist and fill weights - for (Int_t i=0 ; igetVal(obs) ; - cacheHist.set(i, wgt, 0.); - } - - cache.pdf()->setUnitNorm(true) ; - - delete cloneSet ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Defines observables to be cached, given a set of user defined observables -/// Returns the subset of nset that are observables this p.d.f - -RooArgSet* RooAbsSelfCachedPdf::actualObservables(const RooArgSet& /*nset*/) const -{ - // Make list of servers - RooArgSet *serverSet = new RooArgSet; - - for (auto server : _serverList) { - serverSet->add(*server) ; - } - - // Return servers that are in common with given normalization set - return serverSet; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Defines parameters on which cache contents depends. Returns -/// subset of variables of self that is not contained in the -/// supplied nset - -RooArgSet* RooAbsSelfCachedPdf::actualParameters(const RooArgSet& nset) const -{ - RooArgSet *serverSet = new RooArgSet; - - for (auto server : _serverList) { - serverSet->add(*server) ; - } - - // Remove all given observables from server list - serverSet->remove(nset,true,true); - - return serverSet; -} - - - - - - - diff --git a/roofit/roofitcore/src/RooAbsSelfCachedReal.cxx b/roofit/roofitcore/src/RooAbsSelfCachedReal.cxx deleted file mode 100644 index 9212c80a425db..0000000000000 --- a/roofit/roofitcore/src/RooAbsSelfCachedReal.cxx +++ /dev/null @@ -1,142 +0,0 @@ - /***************************************************************************** - * Project: RooFit * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooAbsSelfCachedReal.cxx -\class RooAbsSelfCachedReal -\ingroup Roofitcore - -RooAbsSelfCachedReal is an abstract base class for functions whose -output is cached in terms of a histogram in all observables between -getVal() and evaluate(). For certain p.d.f.s that are very -expensive to calculate it may be beneficial to implement them as a -RooAbsSelfCachedReal rather than a RooAbsReal. Class -RooAbsSelfCachedReal is designed to have its interface identical to -that of RooAbsReal, so any p.d.f can make use of its caching -functionality by merely switching its base class. Existing -RooAbsReal objects can also be cached a posteriori with the -RooCachedReal wrapper function that takes any RooAbsReal object as -input. -**/ - -#include "Riostream.h" - -#include "RooAbsSelfCachedReal.h" -#include "RooAbsReal.h" -#include "RooMsgService.h" -#include "RooDataHist.h" -#include "RooHistPdf.h" - -using namespace std ; - -ClassImp(RooAbsSelfCachedReal); - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -RooAbsSelfCachedReal::RooAbsSelfCachedReal(const char *name, const char *title, Int_t ipOrder) : - RooAbsCachedReal(name,title,ipOrder) - { - } - - - -//////////////////////////////////////////////////////////////////////////////// -/// Copy constructor - -RooAbsSelfCachedReal::RooAbsSelfCachedReal(const RooAbsSelfCachedReal& other, const char* name) : - RooAbsCachedReal(other,name) - { - } - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooAbsSelfCachedReal::~RooAbsSelfCachedReal() -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Fill cache with sampling of function as defined by the evaluate() implementation - -void RooAbsSelfCachedReal::fillCacheObject(RooAbsCachedReal::FuncCacheElem& cache) const -{ - RooDataHist& cacheHist = *cache.hist() ; - - // Make deep clone of self in non-caching mde and attach to dataset observables - RooArgSet* cloneSet = (RooArgSet*) RooArgSet(*this).snapshot(true) ; - RooAbsSelfCachedReal* clone2 = (RooAbsSelfCachedReal*) cloneSet->find(GetName()) ; - clone2->disableCache(true) ; - clone2->attachDataSet(cacheHist) ; - - // Iterator over all bins of RooDataHist and fill weights - for (Int_t i=0 ; igetVal(obs) ; - cacheHist.set(i, wgt, 0.); - } - - delete cloneSet ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Defines observables to be cached, given a set of user defined observables -/// Returns the subset of nset that are observables this p.d.f - -RooArgSet* RooAbsSelfCachedReal::actualObservables(const RooArgSet& nset) const -{ - // Make list of servers - RooArgSet serverSet; - - for (auto server : _serverList) { - serverSet.add(*server); - } - - // Return servers that are in common with given normalization set - return (RooArgSet*) serverSet.selectCommon(nset); - -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Defines parameters on which cache contents depends. Returns -/// subset of variables of self that is not contained in the -/// supplied nset - -RooArgSet* RooAbsSelfCachedReal::actualParameters(const RooArgSet& nset) const -{ - // Make list of servers - RooArgSet *serverSet = new RooArgSet; - - for (auto server : _serverList) { - serverSet->add(*server); - } - - // Remove all given observables from server list - serverSet->remove(nset,true,true); - - return serverSet; -} - - - - - - - diff --git a/roofit/roofitcore/src/RooAbsStudy.cxx b/roofit/roofitcore/src/RooAbsStudy.cxx index 52207b98e6a65..e1833021b6baa 100644 --- a/roofit/roofitcore/src/RooAbsStudy.cxx +++ b/roofit/roofitcore/src/RooAbsStudy.cxx @@ -39,7 +39,7 @@ ClassImp(RooAbsStudy); //////////////////////////////////////////////////////////////////////////////// /// Constructor -RooAbsStudy::RooAbsStudy(const char* name, const char* title) : TNamed(name,title), _storeDetails(0), _summaryData(0), _detailData(0), _ownDetailData(true) +RooAbsStudy::RooAbsStudy(const char* name, const char* title) : TNamed(name,title), _storeDetails(false), _summaryData(nullptr), _detailData(nullptr), _ownDetailData(true) { } @@ -49,7 +49,7 @@ RooAbsStudy::RooAbsStudy(const char* name, const char* title) : TNamed(name,titl /// Copy constructor RooAbsStudy::RooAbsStudy(const RooAbsStudy& other) : TNamed(other), _storeDetails(other._storeDetails), _summaryData(other._summaryData), - _detailData(0), _ownDetailData(other._ownDetailData) + _detailData(nullptr), _ownDetailData(other._ownDetailData) { } @@ -79,9 +79,9 @@ void RooAbsStudy::registerSummaryOutput(const RooArgSet& allVars, const RooArgSe return ; } - string name = Form("%s_summary_data",GetName()) ; - string title = Form("%s Summary Data",GetTitle()) ; - _summaryData = new RooDataSet(name.c_str(),title.c_str(),allVars,RooFit::StoreError(varsWithError),RooFit::StoreAsymError(varsWithAsymError)) ; + std::string name = std::string(GetName()) + "_summary_data"; + std::string title = std::string(GetTitle()) + " Summary Data"; + _summaryData = new RooDataSet(name,title,allVars,RooFit::StoreError(varsWithError),RooFit::StoreAsymError(varsWithAsymError)) ; } @@ -100,9 +100,9 @@ void RooAbsStudy::storeSummaryOutput(const RooArgSet& vars) //////////////////////////////////////////////////////////////////////////////// -void RooAbsStudy::storeDetailedOutput(TNamed& object) +void RooAbsStudy::storeDetailedOutput(std::unique_ptr object) { - if (_storeDetails) { + if (!_storeDetails) return; if (!_detailData) { _detailData = new RooLinkedList ; @@ -110,12 +110,9 @@ void RooAbsStudy::storeDetailedOutput(TNamed& object) //cout << "RooAbsStudy::ctor() detailData name = " << _detailData->GetName() << endl ; } - object.SetName(TString::Format("%s_detailed_data_%d",GetName(),_detailData->GetSize())) ; + object->SetName(TString::Format("%s_detailed_data_%d",GetName(),_detailData->GetSize())) ; //cout << "storing detailed data with name " << object.GetName() << endl ; - _detailData->Add(&object) ; - } else { - delete &object ; - } + _detailData->Add(object.release()); } @@ -144,7 +141,7 @@ void RooAbsStudy::aggregateSummaryOutput(TList* chunkList) if (auto dlist = dynamic_cast(obj)) { if (TString(dlist->GetName()).BeginsWith(Form("%s_detailed_data",GetName()))) { - for(auto * dobj : static_range_cast(*dlist)) storeDetailedOutput(*dobj) ; + for(auto * dobj : static_range_cast(*dlist)) storeDetailedOutput(std::unique_ptr{dobj}) ; } } } diff --git a/roofit/roofitcore/src/RooAbsTestStatistic.cxx b/roofit/roofitcore/src/RooAbsTestStatistic.cxx index 2e704e6e8f233..97649b9f9f2f0 100644 --- a/roofit/roofitcore/src/RooAbsTestStatistic.cxx +++ b/roofit/roofitcore/src/RooAbsTestStatistic.cxx @@ -72,7 +72,7 @@ ClassImp(RooAbsTestStatistic); /// - rangeName Fit data only in range with given name /// - addCoefRangeName If not null, all RooAddPdf components of `real` will be instructed to fix their fraction definitions to the given named range. /// - nCPU If larger than one, the test statistic calculation will be parallelized over multiple processes. -/// By default the data is split with 'bulk' partitioning (each process calculates a contigious block of fraction 1/nCPU +/// By default the data is split with 'bulk' partitioning (each process calculates a contiguous block of fraction 1/nCPU /// of the data). For binned data this approach may be suboptimal as the number of bins with >0 entries /// in each processing block many vary greatly thereby distributing the workload rather unevenly. /// - interleave is set to true, the interleave partitioning strategy is used where each partition @@ -256,6 +256,7 @@ double RooAbsTestStatistic::evaluate() const break ; } + runRecalculateCache(nFirst, nLast, nStep); double ret = evaluatePartition(nFirst,nLast,nStep); if (numSets()==1) { @@ -473,6 +474,7 @@ void RooAbsTestStatistic::initSimMode(RooSimultaneous* simpdf, RooAbsData* data, // *** START HERE // WVE HACK determine if we have a RooRealSumPdf and then treat it like a binned likelihood auto binnedInfo = RooHelpers::getBinnedL(*pdf); + RooAbsReal &actualPdf = binnedInfo.binnedPdf ? *binnedInfo.binnedPdf : *pdf; // WVE END HACK // Below here directly pass binnedPdf instead of PROD(binnedPdf,constraints) as constraints are evaluated elsewhere anyway // and omitting them reduces model complexity and associated handling/cloning times @@ -491,7 +493,7 @@ void RooAbsTestStatistic::initSimMode(RooSimultaneous* simpdf, RooAbsData* data, } cfg.rangeName = RooHelpers::getRangeNameForSimComponent(rangeName, _splitRange, catName); cfg.nCPU = _nCPU; - _gofArray.emplace_back(create(catName.c_str(),catName.c_str(),(binnedInfo.binnedPdf?*binnedInfo.binnedPdf:*pdf),*dset,*projDeps,cfg)); + _gofArray.emplace_back(create(catName.c_str(),catName.c_str(),actualPdf,*dset,*projDeps,cfg)); // *** END HERE // Fill per-component split mode with Bulk Partition for now so that Auto will map to bulk-splitting of all components @@ -501,13 +503,12 @@ void RooAbsTestStatistic::initSimMode(RooSimultaneous* simpdf, RooAbsData* data, // Servers may have been redirected between instantiation and (deferred) initialization - RooArgSet *actualParams = binnedInfo.binnedPdf ? binnedInfo.binnedPdf->getParameters(dset) : pdf->getParameters(dset); - RooArgSet* selTargetParams = (RooArgSet*) _paramSet.selectCommon(*actualParams); + RooArgSet actualParams; + actualPdf.getParameters(dset->get(), actualParams); + RooArgSet selTargetParams; + _paramSet.selectCommon(actualParams, selTargetParams); - _gofArray.back()->recursiveRedirectServers(*selTargetParams); - - delete selTargetParams; - delete actualParams; + _gofArray.back()->recursiveRedirectServers(selTargetParams); } } for(auto& gof : _gofArray) { @@ -588,7 +589,7 @@ void RooAbsTestStatistic::enableOffsetting(bool flag) _doOffset = flag ; // Clear offset if feature is disabled to that it is recalculated next time it is enabled if (!_doOffset) { - _offset = 0 ; + _offset = ROOT::Math::KahanSum{0.} ; } setValueDirty() ; break ; diff --git a/roofit/roofitcore/src/RooAcceptReject.cxx b/roofit/roofitcore/src/RooAcceptReject.cxx index c0bcc496eac69..b97932aa8e93c 100644 --- a/roofit/roofitcore/src/RooAcceptReject.cxx +++ b/roofit/roofitcore/src/RooAcceptReject.cxx @@ -44,7 +44,7 @@ do not define internal methods #include "TFoam.h" #include "TNamed.h" -#include +#include using namespace std; @@ -173,9 +173,9 @@ const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining, double& resamp } } - event= 0; + event= nullptr; double oldMax2(_maxFuncVal); - while(0 == event) { + while(nullptr == event) { // Use any cached events first if (_maxFuncVal>oldMax2) { oocxcoutD(static_cast(nullptr), Generation) << "RooAcceptReject::generateEvent maxFuncVal has changed, need to resample already accepted events by factor" @@ -192,7 +192,7 @@ const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining, double& resamp // Always generate at least one more event so we don't get stuck. if(_totalEvents*_maxFuncVal <= 0) { oocoutE(nullptr, Generation) << "RooAcceptReject::generateEvent: cannot estimate efficiency...giving up" << endl; - return 0; + return nullptr; } double eff= _funcSum/(_totalEvents*_maxFuncVal); @@ -221,8 +221,8 @@ const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining, double& resamp _maxFuncVal = _funcMaxVal->getVal() ; // Generate enough trials to produce a single accepted event - event = 0 ; - while(0==event) { + event = nullptr ; + while(nullptr==event) { addEventToCache() ; event = nextAcceptedEvent() ; } @@ -242,7 +242,7 @@ const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining, double& resamp const RooArgSet *RooAcceptReject::nextAcceptedEvent() { - const RooArgSet *event = 0; + const RooArgSet *event = nullptr; while((event= _cache->get(_eventsUsed))) { _eventsUsed++ ; // accept this cached event? diff --git a/roofit/roofitcore/src/RooAdaptiveIntegratorND.cxx b/roofit/roofitcore/src/RooAdaptiveIntegratorND.cxx index 02dfed1de03e2..5c45f324334a3 100644 --- a/roofit/roofitcore/src/RooAdaptiveIntegratorND.cxx +++ b/roofit/roofitcore/src/RooAdaptiveIntegratorND.cxx @@ -28,15 +28,16 @@ numerical integration algorithm. #include "TClass.h" #include "RooAdaptiveIntegratorND.h" +#include "RooFunctor.h" #include "RooArgSet.h" #include "RooRealVar.h" #include "RooNumber.h" #include "RooMsgService.h" #include "RooNumIntFactory.h" -#include "RooMultiGenFunction.h" #include "Math/AdaptiveIntegratorMultiDim.h" +#include "Math/Functor.h" -#include +#include @@ -57,25 +58,15 @@ void RooAdaptiveIntegratorND::registerIntegrator(RooNumIntFactory& fact) RooRealVar maxEvalND("maxEvalND","Max number of function evaluations for >3-dim integrals",10000000) ; RooRealVar maxWarn("maxWarn","Max number of warnings on precision not reached that is printed",5) ; - fact.storeProtoIntegrator(new RooAdaptiveIntegratorND(),RooArgSet(maxEval2D,maxEval3D,maxEvalND,maxWarn)) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default ctor + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config); + }; -RooAdaptiveIntegratorND::RooAdaptiveIntegratorND() -{ - _epsRel = 1e-7 ; - _epsAbs = 1e-7 ; - _nmax = 10000 ; - _func = 0 ; - _integrator = 0 ; - _nError = 0 ; - _nWarn = 0 ; - _useIntegrandLimits = true ; - _intName = "(none)" ; + fact.registerPlugin("RooAdaptiveIntegratorND", creator, {maxEval2D,maxEval3D,maxEvalND,maxWarn}, + /*canIntegrate1D=*/false, + /*canIntegrate2D=*/true, + /*canIntegrateND=*/true, + /*canIntegrateOpenEnded=*/false); } @@ -89,7 +80,8 @@ RooAdaptiveIntegratorND::RooAdaptiveIntegratorND(const RooAbsFunc& function, con RooAbsIntegrator(function) { - _func = new RooMultiGenFunction(function) ; + _rooFunctor = std::make_unique(function); + _func = std::make_unique(*_rooFunctor, static_cast(_rooFunctor->nObs())); _nWarn = static_cast(config.getConfigSection("RooAdaptiveIntegratorND").getRealValue("maxWarn")) ; switch (_func->NDim()) { case 1: throw string(Form("RooAdaptiveIntegratorND::ctor ERROR dimension of function must be at least 2")) ; @@ -111,27 +103,12 @@ RooAdaptiveIntegratorND::RooAdaptiveIntegratorND(const RooAbsFunc& function, con } - -//////////////////////////////////////////////////////////////////////////////// -/// Virtual constructor with given function and configuration. Needed by RooNumIntFactory - -RooAbsIntegrator* RooAdaptiveIntegratorND::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - RooAbsIntegrator* ret = new RooAdaptiveIntegratorND(function,config) ; - - return ret ; -} - - - - //////////////////////////////////////////////////////////////////////////////// /// Destructor RooAdaptiveIntegratorND::~RooAdaptiveIntegratorND() { delete _integrator ; - delete _func ; if (_nError>_nWarn) { coutW(NumIntegration) << "RooAdaptiveIntegratorND::dtor(" << _intName << ") WARNING: Number of suppressed warningings about integral evaluations where target precision was not reached is " << _nError-_nWarn << endl ; diff --git a/roofit/roofitcore/src/RooAddGenContext.cxx b/roofit/roofitcore/src/RooAddGenContext.cxx index 29105065123a6..e1e96c9b1af4b 100644 --- a/roofit/roofitcore/src/RooAddGenContext.cxx +++ b/roofit/roofitcore/src/RooAddGenContext.cxx @@ -56,7 +56,8 @@ RooAddGenContext::RooAddGenContext(const RooAddPdf &model, const RooArgSet &vars ccxcoutI(Generation) << std::endl; // Constructor. Build an array of generator contexts for each product component PDF - _pdfSet.reset(static_cast(RooArgSet(model).snapshot(true))); + _pdfSet = std::make_unique(); + RooArgSet(model).snapshot(*_pdfSet, true); _pdf = (RooAddPdf*) _pdfSet->find(model.GetName()) ; _pdf->setOperMode(RooAbsArg::ADirty,true) ; @@ -70,7 +71,8 @@ RooAddGenContext::RooAddGenContext(const RooAddPdf &model, const RooArgSet &vars _nComp = model._pdfList.getSize() ; _coefThresh.resize(_nComp+1); - _vars.reset(static_cast(vars.snapshot(false))); + _vars = std::make_unique(); + vars.snapshot(*_vars, false); for (const auto arg : model._pdfList) { auto pdf = dynamic_cast(arg); @@ -104,12 +106,14 @@ RooAddGenContext::RooAddGenContext(const RooAddModel &model, const RooArgSet &va ccxcoutI(Generation) << std::endl; // Constructor. Build an array of generator contexts for each product component PDF - _pdfSet.reset(static_cast(RooArgSet(model).snapshot(true))); + _pdfSet = std::make_unique(); + RooArgSet(model).snapshot(*_pdfSet, true); _pdf = (RooAbsPdf*) _pdfSet->find(model.GetName()) ; _nComp = model._pdfList.getSize() ; _coefThresh.resize(_nComp+1); - _vars.reset(static_cast(vars.snapshot(false))); + _vars = std::make_unique(); + vars.snapshot(*_vars, false); for (const auto obj : model._pdfList) { auto pdf = static_cast(obj); @@ -137,7 +141,7 @@ void RooAddGenContext::attach(const RooArgSet& args) //////////////////////////////////////////////////////////////////////////////// -/// One-time initialization of generator contex. Attach theEvent +/// One-time initialization of generator context. Attach theEvent /// to internal p.d.f clone and forward initialization call to /// the component generators @@ -166,7 +170,7 @@ void RooAddGenContext::initGenerator(const RooArgSet &theEvent) void RooAddGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) { - // Throw a random number to determin which component to generate + // Throw a random number to determine which component to generate updateThresholds() ; double rand = RooRandom::uniform() ; for (Int_t i=0 ; i<_nComp ; i++) { @@ -195,7 +199,7 @@ void RooAddGenContext::updateThresholds() std::stringstream errMsgStream; errMsgStream << "RooAddGenContext::updateThresholds(): coefficient number " << i << " of the " << pdf->ClassName() << " \"" << pdf->GetName() << "\"" << " is negative!" - << " The current RooAddGenConext doesn't support negative coefficients." + << " The current RooAddGenContext doesn't support negative coefficients." << " Please recreate a new generator context with " << pdf->ClassName() << "::genContext()"; auto const errMsg = errMsgStream.str(); cxcoutE(Generation) << errMsg << std::endl; diff --git a/roofit/roofitcore/src/RooAddHelpers.cxx b/roofit/roofitcore/src/RooAddHelpers.cxx index 404ddfdbfc872..faddc5ad34770 100644 --- a/roofit/roofitcore/src/RooAddHelpers.cxx +++ b/roofit/roofitcore/src/RooAddHelpers.cxx @@ -26,6 +26,11 @@ AddCacheElem::AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, R const RooArgSet *nset, const RooArgSet *iset, RooArgSet const &refCoefNormSet, std::string const &refCoefNormRange, int verboseEval) { + // Projection integrals are always over all pdf components. Overriding the + // global component selection temporarily makes all RooRealIntegrals created + // during that time always include all components. + RooAbsReal::GlobalSelectComponentRAII compRAII(true); + // We put the normRange into a std::string to not have to deal with // nullptr vs. "" ambiguities const std::string normRange = addPdf.normRange() ? addPdf.normRange() : ""; @@ -41,6 +46,15 @@ AddCacheElem::AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, R fullDepList.remove(*iset, true, true); } + // Reduce iset/nset to actual dependents of this PDF + RooArgSet nset2; + addPdf.getObservables(nset, nset2); + + if (nset2.empty() && !refCoefNormSet.empty()) { + // Evaluating RooAddPdf without normalization, but have reference normalization for coefficient definition + nset2.add(refCoefNormSet); + } + bool hasPdfWithCustomRange = false; // Fill with dummy unit RRVs for now @@ -74,7 +88,7 @@ AddCacheElem::AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, R } if (!normRange.empty()) { - auto snormTerm = std::unique_ptr(pdf->createIntegral(*nset, *nset, normRange.c_str())); + auto snormTerm = std::unique_ptr(pdf->createIntegral(nset2, nset2, normRange.c_str())); if (snorm) { auto oldSnorm = std::move(snorm); snorm = std::make_unique("snorm", "snorm", *oldSnorm.get(), *snormTerm.get()); @@ -101,21 +115,6 @@ AddCacheElem::AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, R return; } - // Reduce iset/nset to actual dependents of this PDF - RooArgSet nset2; - if (nset) - addPdf.getObservables(nset, nset2); - oocxcoutD(&addPdf, Caching) << addPdf.ClassName() << "(" << addPdf.GetName() - << ")::getPC nset = " << (nset ? *nset : RooArgSet()) << " nset2 = " << nset2 - << std::endl; - - if (nset2.empty() && !refCoefNormSet.empty()) { - // cout << "WVE: evaluating RooAddPdf without normalization, but have reference normalization for coefficient - // definition" << std::endl ; - - nset2.add(refCoefNormSet); - } - if (!nset2.equals(refCoefNormSet) || projectCoefsForRangeReasons) { // Recalculate projection integrals of PDFs @@ -289,13 +288,9 @@ void RooAddHelpers::updateCoefficients(RooAbsPdf const &addPdf, std::vector 0) && diff --git a/roofit/roofitcore/src/RooAddModel.cxx b/roofit/roofitcore/src/RooAddModel.cxx index 8fd3fe357ee64..fdc55bdd20006 100644 --- a/roofit/roofitcore/src/RooAddModel.cxx +++ b/roofit/roofitcore/src/RooAddModel.cxx @@ -51,6 +51,7 @@ #include "RooRealVar.h" #include "RooAddGenContext.h" #include "RooNameReg.h" +#include "RooBatchCompute.h" using namespace std; @@ -80,7 +81,7 @@ RooAddModel::RooAddModel() : RooAddModel::RooAddModel(const char *name, const char *title, const RooArgList& inPdfList, const RooArgList& inCoefList, bool ownPdfList) : RooResolutionModel(name,title,(static_cast(inPdfList.at(0)))->convVar()), _refCoefNorm("!refCoefNorm","Reference coefficient normalization set",this,false,false), - _refCoefRangeName(0), + _refCoefRangeName(nullptr), _projCacheMgr(this,10), _intCacheMgr(this,10), _codeReg(10), @@ -206,8 +207,8 @@ void RooAddModel::fixCoefNormalization(const RooArgSet& refCoefNorm) /// instructs RooAddModel to freeze its interpretation in the given /// named range. If the current normalization range is different /// from the reference range, the appropriate fraction coefficients -/// are automically calculation from the reference fractions using -/// ratios if integrals +/// are automatically calculated from the reference fractions using +/// ratios of integrals. void RooAddModel::fixCoefRange(const char* rangeName) { @@ -232,7 +233,7 @@ RooResolutionModel* RooAddModel::convolution(RooFormulaVar* inBasis, RooAbsArg* ccoutE(InputArguments) << "basis->findServer(0) = " << inBasis->findServer(0) << " " << inBasis->findServer(0)->GetName() << endl ; ccoutE(InputArguments) << "x.absArg() = " << x.absArg() << " " << x.absArg()->GetName() << endl ; inBasis->Print("v") ; - return 0 ; + return nullptr ; } TString newName(GetName()) ; @@ -282,7 +283,7 @@ RooResolutionModel* RooAddModel::convolution(RooFormulaVar* inBasis, RooAbsArg* Int_t RooAddModel::basisCode(const char* name) const { - bool first(true), code(0) ; + bool first(true), code(false) ; for (auto obj : _pdfList) { auto model = static_cast(obj); Int_t subCode = model->basisCode(name) ; @@ -290,7 +291,7 @@ Int_t RooAddModel::basisCode(const char* name) const code = subCode ; first = false ; } else if (subCode==0) { - code = 0 ; + code = false ; } } @@ -309,7 +310,7 @@ Int_t RooAddModel::basisCode(const char* name) const AddCacheElem* RooAddModel::getProjCache(const RooArgSet* nset, const RooArgSet* iset) const { // Check if cache already exists - auto cache = static_cast(_projCacheMgr.getObj(nset,iset,0,normRange())); + auto cache = static_cast(_projCacheMgr.getObj(nset,iset,nullptr,normRange())); if (cache) { return cache ; } @@ -376,6 +377,42 @@ double RooAddModel::evaluate() const return value ; } +void RooAddModel::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const +{ + // Like many other functions in this class, the implementation was copy-pasted from the RooAddPdf + RooBatchCompute::Config config = dataMap.config(this); + + _coefCache.resize(_pdfList.size()); + for (std::size_t i = 0; i < _coefList.size(); ++i) { + auto coefVals = dataMap.at(&_coefList[i]); + // We don't support per-event coefficients in this function. If the CPU + // mode is used, we can just fall back to the RooAbsReal implementation. + // With CUDA, we can't do that because the inputs might be on the device. + // That's why we throw an exception then. + if (coefVals.size() > 1) { + if (config.useCuda()) { + throw std::runtime_error("The RooAddPdf doesn't support per-event coefficients in CUDA mode yet!"); + } + RooAbsReal::computeBatch(output, nEvents, dataMap); + return; + } + _coefCache[i] = coefVals[0]; + } + + RooBatchCompute::VarVector pdfs; + RooBatchCompute::ArgVector coefs; + AddCacheElem *cache = getProjCache(nullptr); + updateCoefficients(*cache, nullptr); + + for (unsigned int pdfNo = 0; pdfNo < _pdfList.size(); ++pdfNo) { + auto pdf = static_cast(&_pdfList[pdfNo]); + if (pdf->isSelectedComp()) { + pdfs.push_back(dataMap.at(pdf)); + coefs.push_back(_coefCache[pdfNo] / cache->suppNormVal(pdfNo)); + } + } + RooBatchCompute::compute(config, RooBatchCompute::AddPdf, output, nEvents, pdfs, coefs); +} //////////////////////////////////////////////////////////////////////////////// @@ -392,7 +429,7 @@ void RooAddModel::resetErrorCounters(Int_t resetValue) //////////////////////////////////////////////////////////////////////////////// /// Check if PDF is valid for given normalization set. -/// Coeffient and PDF must be non-overlapping, but pdf-coefficient +/// Coefficient and PDF must be non-overlapping, but pdf-coefficient /// pairs may overlap each other bool RooAddModel::checkObservables(const RooArgSet* nset) const @@ -458,8 +495,7 @@ void RooAddModel::getCompIntList(const RooArgSet* nset, const RooArgSet* iset, p for (auto obj : _pdfList) { auto model = static_cast(obj); - RooAbsReal* intPdf = model->createIntegral(*iset,nset,0,isetRangeName) ; - cache->_intList.addOwned(*intPdf) ; + cache->_intList.addOwned(std::unique_ptr{model->createIntegral(*iset,nset,nullptr,isetRangeName)}); } // Store the partial integral list and return the assigned code ; @@ -487,7 +523,7 @@ double RooAddModel::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, c RooArgList* compIntList ; // If cache has been sterilized, revive this slot - if (cache==0) { + if (cache==nullptr) { std::unique_ptr vars{getParameters(RooArgSet())} ; RooArgSet nset = _intCacheMgr.selectFromSet1(*vars, code-1) ; RooArgSet iset = _intCacheMgr.selectFromSet2(*vars, code-1) ; diff --git a/roofit/roofitcore/src/RooAddPdf.cxx b/roofit/roofitcore/src/RooAddPdf.cxx index 3ad7ba0317752..08eb8a1f154bd 100644 --- a/roofit/roofitcore/src/RooAddPdf.cxx +++ b/roofit/roofitcore/src/RooAddPdf.cxx @@ -63,23 +63,32 @@ An (enforced) condition for this assumption is that each \f$ \mathrm{PDF}_i \f$ */ -#include "RooAddPdf.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "RooAddHelpers.h" -#include "RooAddGenContext.h" -#include "RooBatchCompute.h" -#include "RooDataSet.h" -#include "RooGlobalFunc.h" -#include "RooRealProxy.h" -#include "RooRealVar.h" -#include "RooRealConstant.h" -#include "RooRealSumPdf.h" -#include "RooRecursiveFraction.h" + +#include #include #include -#include #include +#include ClassImp(RooAddPdf); @@ -95,7 +104,7 @@ RooAddPdf::RooAddPdf(const char *name, const char *title) : _coefList("!coefficients","List of coefficients",this), _coefErrCount{_errorCount} { - TRACE_CREATE + TRACE_CREATE; } @@ -291,7 +300,7 @@ RooAddPdf::RooAddPdf(const RooAddPdf& other, const char* name) : { _coefErrCount = _errorCount ; finalizeConstruction(); - TRACE_CREATE + TRACE_CREATE; } @@ -311,12 +320,53 @@ void RooAddPdf::fixCoefNormalization(const RooArgSet& refCoefNorm) return ; } + // Also set an attribute with this information, which is the easiest way to + // preserve this in the JSON IO. + setStringAttribute("ref_coef_norm", RooHelpers::getColonSeparatedNameString(refCoefNorm, ',').c_str()); + _refCoefNorm.removeAll() ; _refCoefNorm.add(refCoefNorm) ; _projCacheMgr.reset() ; } +const RooArgSet &RooAddPdf::getCoefNormalization() const +{ + materializeRefCoefNormFromAttribute(); + return _refCoefNorm; +} + +// For the JSON IO, we are not storing the _refCoefNorm directly. Instead, it +// is stored by names in a string attribute. This function should be called +// internally before _refCoefNorm is used to materialize it from the attribute +// if necessary. +void RooAddPdf::materializeRefCoefNormFromAttribute() const +{ + // _refCoefNorm was already materialized + if (!_refCoefNorm.empty()) + return; + + std::vector names; + if (auto attrib = getStringAttribute("ref_coef_norm")) { + names = ROOT::Split(attrib, ",", /*skipEmpty=*/true); + } else { + return; + } + + RooArgSet refCoefNorm; + + RooArgSet serverSet; + RooHelpers::getSortedComputationGraph(*this, serverSet); + for (std::string const &name : names) { + if (RooAbsArg *arg = serverSet.find(name.c_str())) { + refCoefNorm.add(*arg); + } else { + throw std::runtime_error("Internal logic error in RooAddPdf::materializeRefCoefNormFromAttribute()"); + } + } + + const_cast(this)->fixCoefNormalization(refCoefNorm); +} //////////////////////////////////////////////////////////////////////////////// @@ -355,18 +405,18 @@ void RooAddPdf::fixCoefRange(const char* rangeName) AddCacheElem* RooAddPdf::getProjCache(const RooArgSet* nset, const RooArgSet* iset) const { // Check if cache already exists - auto cache = static_cast(_projCacheMgr.getObj(nset,iset,0,normRange())); + auto cache = static_cast(_projCacheMgr.getObj(nset,iset,nullptr,normRange())); if (cache) { return cache ; } + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); + //Create new cache cache = new AddCacheElem{*this, _pdfList, _coefList, nset, iset, _refCoefNorm, _refCoefRangeName ? RooNameReg::str(_refCoefRangeName) : "", _verboseEval}; - //std::cout << std::endl; - //cache->print(); - //std::cout << std::endl; _projCacheMgr.setObj(nset,iset,cache,RooNameReg::ptr(normRange())) ; @@ -410,6 +460,9 @@ std::pair RooAddPdf::getNormAndCache(const RooA if(nset && nset->empty()) nset = nullptr; if (nset == nullptr) { + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); + if (!_refCoefNorm.empty()) { nset = &_refCoefNorm ; } @@ -433,7 +486,7 @@ std::pair RooAddPdf::getNormAndCache(const RooA // the last-used normalization set needs an update. if(nset == nullptr) { nset = _copyOfLastNormSet.get(); - } else if(nset->uniqueId() != _idOfLastUsedNormSet) { + } else if((RooFit::UniqueId::Value_t)nset->uniqueId() != _idOfLastUsedNormSet) { _copyOfLastNormSet = std::make_unique(*nset); _idOfLastUsedNormSet = nset->uniqueId(); } @@ -467,7 +520,7 @@ double RooAddPdf::getValV(const RooArgSet* normSet) const // Process change in last data set used bool nsetChanged(false) ; - if (!isActiveNormSet(nset) || _norm==0) { + if (!isActiveNormSet(nset) || _norm==nullptr) { nsetChanged = syncNormalization(nset) ; } @@ -491,11 +544,17 @@ double RooAddPdf::getValV(const RooArgSet* normSet) const return _value; } +void RooAddPdf::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + RooRealSumPdf::translateImpl(ctx, this, _pdfList, _coefList); +} //////////////////////////////////////////////////////////////////////////////// /// Compute addition of PDFs in batches. -void RooAddPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooAddPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { + RooBatchCompute::Config config = dataMap.config(this); + _coefCache.resize(_pdfList.size()); for(std::size_t i = 0; i < _coefList.size(); ++i) { auto coefVals = dataMap.at(&_coefList[i]); @@ -504,10 +563,10 @@ void RooAddPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvent // With CUDA, we can't do that because the inputs might be on the device. // That's why we throw an exception then. if(coefVals.size() > 1) { - if(stream) { + if (config.useCuda()) { throw std::runtime_error("The RooAddPdf doesn't support per-event coefficients in CUDA mode yet!"); } - RooAbsReal::computeBatch(stream, output, nEvents, dataMap); + RooAbsReal::computeBatch(output, nEvents, dataMap); return; } _coefCache[i] = coefVals[0]; @@ -515,12 +574,10 @@ void RooAddPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvent RooBatchCompute::VarVector pdfs; RooBatchCompute::ArgVector coefs; - auto normAndCache = getNormAndCache(nullptr); - const RooArgSet* nset = normAndCache.first; - AddCacheElem* cache = normAndCache.second; + AddCacheElem* cache = getProjCache(nullptr); // We don't sync the coefficient values from the _coefList to the _coefCache // because we have already done it using the dataMap. - updateCoefficients(*cache, nset, /*syncCoefValues=*/false); + updateCoefficients(*cache, nullptr, /*syncCoefValues=*/false); for (unsigned int pdfNo = 0; pdfNo < _pdfList.size(); ++pdfNo) { @@ -531,8 +588,7 @@ void RooAddPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvent coefs.push_back(_coefCache[pdfNo] / cache->suppNormVal(pdfNo) ); } } - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::AddPdf, output, nEvents, pdfs, coefs); + RooBatchCompute::compute(config, RooBatchCompute::AddPdf, output, nEvents, pdfs, coefs); } @@ -550,7 +606,7 @@ void RooAddPdf::resetErrorCounters(Int_t resetValue) //////////////////////////////////////////////////////////////////////////////// /// Check if PDF is valid for given normalization set. -/// Coeffient and PDF must be non-overlapping, but pdf-coefficient +/// Coefficient and PDF must be non-overlapping, but pdf-coefficient /// pairs may overlap each other bool RooAddPdf::checkObservables(const RooArgSet* nset) const @@ -572,6 +628,8 @@ bool RooAddPdf::checkObservables(const RooArgSet* nset) const Int_t RooAddPdf::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const { + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); RooArgSet allAnalVars(*std::unique_ptr{getObservables(allVars)}) ; @@ -653,7 +711,7 @@ double RooAddPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, con cxcoutD(Caching) << "RooAddPdf::aiWN(" << GetName() << ") calling getProjCache with nset = " << (normSet?*normSet:RooArgSet()) << std::endl ; - if ((normSet==0 || normSet->empty()) && !_refCoefNorm.empty()) { + if ((normSet==nullptr || normSet->empty()) && !_refCoefNorm.empty()) { // cout << "WVE integration of RooAddPdf without normalization, but have reference set, using ref set for normalization" << std::endl ; normSet = &_refCoefNorm ; } @@ -726,6 +784,74 @@ double RooAddPdf::expectedEvents(const RooArgSet* nset) const } +std::unique_ptr RooAddPdf::createExpectedEventsFunc(const RooArgSet *nset) const +{ + std::unique_ptr out; + + auto name = std::string(GetName()) + "_expectedEvents"; + if (_allExtendable) { + RooArgSet sumSet; + for (auto *pdf : static_range_cast(_pdfList)) { + sumSet.addOwned(pdf->createExpectedEventsFunc(nset)); + } + out = std::make_unique(name.c_str(), name.c_str(), sumSet); + out->addOwnedComponents(std::move(sumSet)); + } else { + out = std::make_unique(name.c_str(), name.c_str(), _coefList); + } + + RooArgList prodList; + + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); + + if (!_allExtendable) { + // If the _refCoefNorm is empty or it's equal to normSet anyway, this is not + // a conditional pdf and we don't need to do any transformation. See also + // RooAddPdf::compleForNormSet() for more explanations on a similar logic. + if (!_refCoefNorm.empty() && !nset->equals(_refCoefNorm)) { + prodList.addOwned(std::unique_ptr{createIntegral(*nset, _refCoefNorm)}); + } + + // Optionally multiply with fractional normalization. I this case, we + // replace the original factor stored in "out". + if (!_normRange.IsNull()) { + std::unique_ptr owner; + RooArgList terms; + // The integrals own each other in a chain. We do this because it's + // not possible to add two objects with the same name via + // addOwnedComponents(), and it happens in some user models that some + // component pdfs are the same. Hence, the integrals might share names + // too and we can't add them all in one go as owned objects of the + // final integral sum. + for (auto *pdf : static_range_cast(_pdfList)) { + auto next = std::unique_ptr{pdf->createIntegral(*nset, *nset, _normRange)}; + terms.add(*next); + if (owner) + next->addOwnedComponents(std::move(owner)); + owner = std::move(next); + } + auto fracIntegName = std::string(GetName()) + "_integSum"; + auto fracInteg = + std::make_unique(fracIntegName.c_str(), fracIntegName.c_str(), _coefList, terms); + fracInteg->addOwnedComponents(std::move(owner)); + + out = std::move(fracInteg); + } + } + + std::string finalName = std::string(out->GetName()) + "_finalized"; + if (prodList.empty()) { + // If there are no additional factors, just return the single factor we have + return out; + } else { + prodList.addOwned(std::move(out)); + } + auto finalOut = std::make_unique(finalName.c_str(), finalName.c_str(), prodList); + finalOut->addOwnedComponents(std::move(prodList)); + return finalOut; +} + //////////////////////////////////////////////////////////////////////////////// /// Interface function used by test statistics to freeze choice of observables @@ -733,6 +859,8 @@ double RooAddPdf::expectedEvents(const RooArgSet* nset) const void RooAddPdf::selectNormalization(const RooArgSet* depSet, bool force) { + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); if (!force && !_refCoefNorm.empty()) { return ; @@ -829,3 +957,56 @@ bool RooAddPdf::redirectServersHook(const RooAbsCollection & newServerList, bool _copyOfLastNormSet.reset(); return RooAbsPdf::redirectServersHook(newServerList, mustReplaceAll, nameChange, isRecursiveStep); } + + +std::unique_ptr +RooAddPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + // Make sure _refCoefNorm is defined + materializeRefCoefNormFromAttribute(); + + auto newArg = std::unique_ptr{static_cast(Clone())}; + ctx.markAsCompiled(*newArg); + + // In case conditional observables, e.g. p(x|y), the _refCoefNorm is set to + // all observables (x, y) and the normSet doesn't contain the conditional + // observables (so it only contains x in this example). + + // If the _refCoefNorm is empty or it's equal to normSet anyway, this is not + // a conditional pdf and we don't need to do any transformation. + if(_refCoefNorm.empty() || normSet.equals(_refCoefNorm)) { + ctx.compileServers(*newArg, normSet); + return newArg; + } + + // In the conditional case, things become more complicated. The original + // getValV() method is covering this case with very complicated logic, + // caching multiple new RooFit objects to scale the individual coefficients + // of the RooAddPdf. + // + // However, it's not complicated what we need to do mathematically: + // + // Since: + // 1. p(x, y) = p(x | y) * p(y) + // 2. p(y) = Integral of p(x, y) over x + // + // We conclude: + // p(x, y) + // p(x | y) = -------------------------- + // Integral of p(x, y) over x + // + // What follows is the implementation of this formula in RooFit. By doing + // this here in compileForNormSet(), we don't invoke the old RooAddPdf + // projection caches (note that no conditional pdfs are on the right hand + // side of the equation). + std::string finalName = std::string(GetName()) + "_conditional"; + std::unique_ptr denom{newArg->createIntegral(normSet, _refCoefNorm)}; + auto finalArg = std::make_unique(finalName.c_str(), "@0/@1", RooArgList{*newArg, *denom}); + ctx.compileServers(*denom, _refCoefNorm); + ctx.markAsCompiled(*denom); + ctx.markAsCompiled(*finalArg); + ctx.compileServers(*newArg, _refCoefNorm); + finalArg->addOwnedComponents(std::move(newArg)); + finalArg->addOwnedComponents(std::move(denom)); + return finalArg; +} diff --git a/roofit/roofitcore/src/RooAddition.cxx b/roofit/roofitcore/src/RooAddition.cxx index 4e6e9c309a691..01f82770935f4 100644 --- a/roofit/roofitcore/src/RooAddition.cxx +++ b/roofit/roofitcore/src/RooAddition.cxx @@ -52,19 +52,25 @@ ClassImp(RooAddition); /// \param[in] sumSet The value of the function will be the sum of the values in this set /// \param[in] takeOwnership If true, the RooAddition object will take ownership of the arguments in `sumSet` -RooAddition::RooAddition(const char* name, const char* title, const RooArgList& sumSet, bool takeOwnership) +RooAddition::RooAddition(const char* name, const char* title, const RooArgList& sumSet +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES + , bool takeOwnership +#endif + ) : RooAbsReal(name, title) , _set("!set","set of components",this) , _cacheMgr(this,10) { - for (const auto comp : sumSet) { + for (RooAbsArg *comp : sumSet) { if (!dynamic_cast(comp)) { coutE(InputArguments) << "RooAddition::ctor(" << GetName() << ") ERROR: component " << comp->GetName() << " is not of type RooAbsReal" << std::endl; RooErrorHandler::softAbort() ; } _set.add(*comp) ; - if (takeOwnership) _ownedList.addOwned(*comp) ; +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES + if (takeOwnership) _ownedList.addOwned(std::unique_ptr{comp}); +#endif } } @@ -85,7 +91,11 @@ RooAddition::RooAddition(const char* name, const char* title, const RooArgList& /// \param[in] sumSet2 Right-hand element of the pair-wise products /// \param[in] takeOwnership If true, the RooAddition object will take ownership of the arguments in the `sumSets` /// -RooAddition::RooAddition(const char* name, const char* title, const RooArgList& sumSet1, const RooArgList& sumSet2, bool takeOwnership) +RooAddition::RooAddition(const char* name, const char* title, const RooArgList& sumSet1, const RooArgList& sumSet2 +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES + , bool takeOwnership +#endif + ) : RooAbsReal(name, title) , _set("!set","set of components",this) , _cacheMgr(this,10) @@ -110,20 +120,21 @@ RooAddition::RooAddition(const char* name, const char* title, const RooArgList& << " in first list is not of type RooAbsReal" << std::endl; RooErrorHandler::softAbort() ; } - // TODO: add flag to RooProduct c'tor to make it assume ownership... TString _name(name); _name.Append( "_["); _name.Append(comp1->GetName()); _name.Append( "_x_"); _name.Append(comp2->GetName()); _name.Append( "]"); - RooProduct *prod = new RooProduct( _name, _name , RooArgSet(*comp1, *comp2) /*, takeOwnership */ ) ; + auto prod = std::make_unique( _name, _name , RooArgSet(*comp1, *comp2)); _set.add(*prod); - _ownedList.addOwned(*prod) ; + _ownedList.addOwned(std::move(prod)); +#ifndef ROOFIT_MEMORY_SAFE_INTERFACES if (takeOwnership) { - _ownedList.addOwned(*comp1) ; - _ownedList.addOwned(*comp2) ; + _ownedList.addOwned(std::unique_ptr{comp1}); + _ownedList.addOwned(std::unique_ptr{comp2}); } +#endif } } @@ -158,7 +169,7 @@ double RooAddition::evaluate() const //////////////////////////////////////////////////////////////////////////////// /// Compute addition of PDFs in batches. -void RooAddition::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooAddition::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { RooBatchCompute::VarVector pdfs; RooBatchCompute::ArgVector coefs; @@ -169,10 +180,49 @@ void RooAddition::computeBatch(cudaStream_t* stream, double* output, size_t nEve pdfs.push_back(dataMap.at(arg)); coefs.push_back(1.0); } - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::AddPdf, output, nEvents, pdfs, coefs); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::AddPdf, output, nEvents, pdfs, coefs); } +//////////////////////////////////////////////////////////////////////////////// + +void RooAddition::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // If the number of elements to sum is less than 3, just build a sum expression. + // else build a loop to sum over the values. + unsigned int eleSize = _set.size(); + std::string result; + if (eleSize > 3) { + std::string className = GetName(); + std::string varName = "elements" + className; + std::string sumName = "sum" + className; + std::string code = ""; + std::string decl = "double " + varName + "[" + std::to_string(eleSize) + "]{"; + int idx = 0; + for (RooAbsArg *it : _set) { + decl += ctx.getResult(*it) + ","; + ctx.addResult(it, varName + "[" + std::to_string(idx) + "]"); + idx++; + } + decl.back() = '}'; + code += decl + ";\n"; + + ctx.addToGlobalScope("double " + sumName + " = 0;\n"); + std::string iterator = "i_" + className; + code += "for(int " + iterator + " = 0; " + iterator + " < " + std::to_string(eleSize) + "; " + iterator + + "++) {\n" + sumName + " += " + varName + "[" + iterator + "];\n}\n"; + result = sumName; + ctx.addResult(this, result); + + ctx.addToCodeBody(this, code); + } + + result = "("; + for (RooAbsArg *it : _set) { + result += ctx.getResult(*it) + '+'; + } + result.back() = ')'; + ctx.addResult(this, result); +} //////////////////////////////////////////////////////////////////////////////// /// Return the default error level for MINUIT error analysis @@ -185,12 +235,12 @@ void RooAddition::computeBatch(cudaStream_t* stream, double* output, size_t nEve double RooAddition::defaultErrorLevel() const { - RooAbsReal* nllArg(0) ; - RooAbsReal* chi2Arg(0) ; + RooAbsReal* nllArg(nullptr) ; + RooAbsReal* chi2Arg(nullptr) ; std::unique_ptr comps{getComponents()}; for(RooAbsArg * arg : *comps) { - if (dynamic_cast(arg) || dynamic_cast(arg)) { + if (dynamic_cast(arg) || dynamic_cast(arg)) { nllArg = (RooAbsReal*)arg ; } if (dynamic_cast(arg)) { @@ -235,7 +285,7 @@ bool RooAddition::setData(RooAbsData& data, bool cloneData) void RooAddition::printMetaArgs(std::ostream& os) const { - // We can use the implementation of RooRealSumPdf with an empy coefficient list. + // We can use the implementation of RooRealSumPdf with an empty coefficient list. static const RooArgList coefs{}; RooRealSumPdf::printMetaArgs(_set, coefs, os); } @@ -250,16 +300,15 @@ Int_t RooAddition::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars // check if we already have integrals for this combination of factors Int_t sterileIndex(-1); CacheElem* cache = (CacheElem*) _cacheMgr.getObj(&analVars,&analVars,&sterileIndex,RooNameReg::ptr(rangeName)); - if (cache!=0) { + if (cache!=nullptr) { Int_t code = _cacheMgr.lastIndex(); return code+1; } // we don't, so we make it right here.... cache = new CacheElem; - for (const auto arg : _set) {// checked in c'tor that this will work... - RooAbsReal *I = static_cast(arg)->createIntegral(analVars,rangeName); - cache->_I.addOwned(*I); + for (auto *arg : static_range_cast(_set)) {// checked in c'tor that this will work... + cache->_I.addOwned(std::unique_ptr{arg->createIntegral(analVars,rangeName)}); } Int_t code = _cacheMgr.setObj(&analVars,&analVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)); @@ -273,7 +322,7 @@ double RooAddition::analyticalIntegral(Int_t code, const char* rangeName) const { // note: rangeName implicit encoded in code: see _cacheMgr.setObj in getPartIntList... CacheElem *cache = (CacheElem*) _cacheMgr.getObjByIndex(code-1); - if (cache==0) { + if (cache==nullptr) { // cache got sterilized, trigger repopulation of this slot, then try again... std::unique_ptr vars( getParameters(RooArgSet()) ); RooArgSet iset = _cacheMgr.selectFromSet2(*vars, code-1); @@ -282,7 +331,7 @@ double RooAddition::analyticalIntegral(Int_t code, const char* rangeName) const assert(code==code2); // must have revived the right (sterilized) slot... return analyticalIntegral(code2,rangeName); } - assert(cache!=0); + assert(cache!=nullptr); // loop over cache, and sum... double result(0); diff --git a/roofit/roofitcore/src/RooArgList.cxx b/roofit/roofitcore/src/RooArgList.cxx index 464a03f8bb05b..29b02bbdc2db5 100644 --- a/roofit/roofitcore/src/RooArgList.cxx +++ b/roofit/roofitcore/src/RooArgList.cxx @@ -110,7 +110,7 @@ RooArgList::RooArgList(const TCollection& tcoll, const char* name) : //////////////////////////////////////////////////////////////////////////////// /// Copy constructor. Note that a copy of a list is always non-owning, /// even the source list is owning. To create an owning copy of -/// a list (owning or not), use the snaphot() method. +/// a list (owning or not), use the snapshot() method. RooArgList::RooArgList(const RooArgList& other, const char *name) : RooAbsCollection(other,name) diff --git a/roofit/roofitcore/src/RooArgProxy.cxx b/roofit/roofitcore/src/RooArgProxy.cxx index 36055c936603d..77b9d27c6555e 100644 --- a/roofit/roofitcore/src/RooArgProxy.cxx +++ b/roofit/roofitcore/src/RooArgProxy.cxx @@ -46,7 +46,7 @@ ClassImp(RooArgProxy); RooArgProxy::RooArgProxy(const char* inName, const char* desc, RooAbsArg* owner, bool valueServer, bool shapeServer, bool proxyOwnsArg) : - TNamed(inName,desc), _owner(owner), _arg(0), + TNamed(inName,desc), _owner(owner), _arg(nullptr), _valueServer(valueServer), _shapeServer(shapeServer), _ownArg(proxyOwnsArg) { _owner->registerProxy(*this) ; @@ -79,7 +79,7 @@ RooArgProxy::RooArgProxy(const char* inName, RooAbsArg* owner, const RooArgProxy _isFund(other._isFund), _ownArg(other._ownArg) { if (_ownArg) { - _arg = _arg ? (RooAbsArg*) _arg->Clone() : 0 ; + _arg = _arg ? (RooAbsArg*) _arg->Clone() : nullptr ; } _owner->registerProxy(*this) ; @@ -131,6 +131,31 @@ bool RooArgProxy::changePointer(const RooAbsCollection& newServerList, bool name return newArg != nullptr; } +bool RooArgProxy::changePointer(std::unordered_map const &replacements) +{ + if (!_arg) + return true; + + RooAbsArg *newArg = nullptr; + + auto newArgFound = replacements.find(_arg); + if (newArgFound != replacements.end()) { + newArg = newArgFound->second; + } + + if (newArg) { + if (_ownArg) { + // We refer to an object that somebody gave to us. Now, we are not owning it, any more. + delete _arg; + _ownArg = false; + } + + _arg = newArg; + _isFund = _arg->isFundamental(); + } + + return newArg != nullptr; +} //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofitcore/src/RooArgSet.cxx b/roofit/roofitcore/src/RooArgSet.cxx index cf96a7a72e641..1bda00b2592cf 100644 --- a/roofit/roofitcore/src/RooArgSet.cxx +++ b/roofit/roofitcore/src/RooArgSet.cxx @@ -37,10 +37,10 @@ /// ownership status. Arguments supplied in the constructor are always added /// as unowned elements. /// -/// +/// /// Uniquely identifying RooArgSet objects /// --------------------------------------- -/// +/// /// \warning Before v6.28, it was ensured that no RooArgSet objects on the heap /// were located at an address that had already been used for a RooArgSet before. /// With v6.28, this is not guaranteed anymore. Hence, if your code uses pointer @@ -121,7 +121,7 @@ void* RooArgSet::operator new (size_t bytes) //////////////////////////////////////////////////////////////////////////////// -/// Overloaded new operator with placement does not guarante that all +/// Overloaded new operator with placement does not guarantee that all /// RooArgSets allocated with new have a unique address, but uses the global /// operator. @@ -435,7 +435,7 @@ bool RooArgSet::readFromStream(istream& is, bool compact, const char* flagReadAt bool inSection(section?false:true) ; bool reprocessToken = false ; - while (1) { + while (true) { if (is.eof() || is.fail() || parser.atEOF()) { break ; @@ -467,7 +467,7 @@ bool RooArgSet::readFromStream(istream& is, bool compact, const char* flagReadAt } coutI(InputArguments) << "RooArgSet::readFromStream(" << GetName() << "): processing include file " << filename << endl ; - if (readFromStream(incfs,compact,flagReadAtt,inSection?0:section,verbose)) return true ; + if (readFromStream(incfs,compact,flagReadAtt,inSection?nullptr:section,verbose)) return true ; continue ; } @@ -638,7 +638,7 @@ bool RooArgSet::isInRange(const char* rangeSpec) return true ; } - token = strtok(0,",") ; + token = strtok(nullptr,",") ; } return false ; diff --git a/roofit/roofitcore/src/RooBinIntegrator.cxx b/roofit/roofitcore/src/RooBinIntegrator.cxx index de110cc8c0858..3f8e4e0015e4a 100644 --- a/roofit/roofitcore/src/RooBinIntegrator.cxx +++ b/roofit/roofitcore/src/RooBinIntegrator.cxx @@ -28,17 +28,15 @@ contents of all bins. #include "RooArgSet.h" #include "RooRealVar.h" #include "RooNumber.h" -#include "RooIntegratorBinding.h" #include "RooNumIntConfig.h" #include "RooNumIntFactory.h" #include "RooMsgService.h" -#include "RunContext.h" #include "RooRealBinding.h" #include "TClass.h" #include "Math/Util.h" -#include +#include @@ -54,19 +52,21 @@ ClassImp(RooBinIntegrator); void RooBinIntegrator::registerIntegrator(RooNumIntFactory& fact) { - RooRealVar numBins("numBins","Number of bins in range",100) ; - RooBinIntegrator* proto = new RooBinIntegrator() ; - fact.storeProtoIntegrator(proto,RooArgSet(numBins)) ; - RooNumIntConfig::defaultConfig().method1D().setLabel(proto->ClassName()) ; -} + RooRealVar numBins("numBins","Number of bins in range",100) ; + std::string name = "RooBinIntegrator"; + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config); + }; -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor + fact.registerPlugin(name, creator, {numBins}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/true, + /*canIntegrateND=*/true, + /*canIntegrateOpenEnded=*/false); -RooBinIntegrator::RooBinIntegrator() : _numBins(0), _useIntegrandLimits(false), _x(0) -{ + RooNumIntConfig::defaultConfig().method1D().setLabel(name); } @@ -86,20 +86,6 @@ RooBinIntegrator::RooBinIntegrator(const RooAbsFunc& function, int numBins): _xmin.resize(_function->getDimension()) ; _xmax.resize(_function->getDimension()) ; - auto realBinding = dynamic_cast(_function); - - // We could use BatchMode for RooRealBindings as they implement getValues(). - // However, this is not efficient right now, because every time getValue() is - // called, a new RooFitDriver is created. Needs to be refactored. - - //const bool useBatchMode = realBinding; - const bool useBatchMode = false; - - if (useBatchMode) { - _evalData.reset(new RooBatchCompute::RunContext()); - _evalDataOrig.reset(new RooBatchCompute::RunContext()); - } - for (UInt_t i=0 ; i<_function->getDimension() ; i++) { _xmin[i]= _function->getMinLimit(i); _xmax[i]= _function->getMaxLimit(i); @@ -116,13 +102,6 @@ RooBinIntegrator::RooBinIntegrator(const RooAbsFunc& function, int numBins): } _binb.emplace_back(tmp->begin(), tmp->end()); - if (useBatchMode) { - const std::vector& binb = _binb.back(); - RooSpan binCentres = _evalDataOrig->makeBatch(realBinding->observable(i), binb.size() - 1); - for (unsigned int ibin = 0; ibin < binb.size() - 1; ++ibin) { - binCentres[ibin] = (binb[ibin + 1] + binb[ibin]) / 2.; - } - } } checkLimits(); @@ -138,18 +117,6 @@ RooBinIntegrator::RooBinIntegrator(const RooAbsFunc& function, const RooNumIntCo } -//////////////////////////////////////////////////////////////////////////////// -/// Clone integrator with new function binding and configuration. Needed by RooNumIntFactory - -RooAbsIntegrator* RooBinIntegrator::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooBinIntegrator(function,config) ; -} - - - - - //////////////////////////////////////////////////////////////////////////////// /// Destructor @@ -182,7 +149,7 @@ bool RooBinIntegrator::setLimits(double *xmin, double *xmax) bool RooBinIntegrator::checkLimits() const { if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); + assert(nullptr != integrand() && integrand()->isValid()); _xmin.resize(_function->getDimension()) ; _xmax.resize(_function->getDimension()) ; for (UInt_t i=0 ; i<_function->getDimension() ; i++) { @@ -215,28 +182,12 @@ double RooBinIntegrator::integral(const double *) if (_function->getDimension() == 1) { const std::vector& binb = _binb[0]; - if (_evalData) { - // Real bindings support batch evaluations. Can fast track now. - auto realBinding = static_cast(integrand()); - - // Reset computation results to only contain known bin centres, and keep all memory intact: - _evalData->spans = _evalDataOrig->spans; - auto results = realBinding->getValuesOfBoundFunction(*_evalData); - assert(results.size() == binb.size() - 1); - - for (unsigned int ibin = 0; ibin < binb.size() - 1; ++ibin) { - const double width = binb[ibin + 1] - binb[ibin]; - sum += results[ibin] * width; - } - } else { - // Need to use single-value interface - for (unsigned int ibin=0; ibin < binb.size() - 1; ++ibin) { - const double xhi = binb[ibin + 1]; - const double xlo = binb[ibin]; - const double xcenter = (xhi+xlo)/2.; - const double binInt = integrand(xvec(xcenter))*(xhi-xlo) ; - sum += binInt ; - } + for (unsigned int ibin=0; ibin < binb.size() - 1; ++ibin) { + const double xhi = binb[ibin + 1]; + const double xlo = binb[ibin]; + const double xcenter = (xhi+xlo)/2.; + const double binInt = integrand(xvec(xcenter))*(xhi-xlo) ; + sum += binInt ; } } else if (_function->getDimension() == 2) { const std::vector& binbx = _binb[0]; @@ -283,7 +234,7 @@ double RooBinIntegrator::integral(const double *) } } - return sum; + return sum.Sum(); } diff --git a/roofit/roofitcore/src/RooBinSamplingPdf.cxx b/roofit/roofitcore/src/RooBinSamplingPdf.cxx index b1a3d677459a2..29d9d9ba7d180 100644 --- a/roofit/roofitcore/src/RooBinSamplingPdf.cxx +++ b/roofit/roofitcore/src/RooBinSamplingPdf.cxx @@ -93,7 +93,6 @@ #include "RooHelpers.h" #include "RooRealBinding.h" -#include "RunContext.h" #include "RooRealVar.h" #include "RooGlobalFunc.h" #include "RooDataHist.h" @@ -161,11 +160,11 @@ double RooBinSamplingPdf::evaluate() const { /// Integrate the PDF over all its bins, and return a batch with those values. /// \param[in,out] evalData Struct with evaluation data. /// \param[in] normSet Normalisation set that's used to evaluate the PDF. -RooSpan RooBinSamplingPdf::evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { +void RooBinSamplingPdf::computeBatch(double* output, size_t /*size*/, RooFit::Detail::DataMap const& dataMap) const +{ // Retrieve binning, which we need to compute the probabilities auto boundaries = binBoundaries(); - auto xValues = _observable->getValues(evalData, normSet); - auto results = evalData.makeBatch(this, xValues.size()); + auto xValues = dataMap.at(_observable); // Important: When the integrator samples x, caching of sub-tree values needs to be off. RooHelpers::DisableCachingRAII disableCaching(inhibitDirty()); @@ -177,17 +176,15 @@ RooSpan RooBinSamplingPdf::evaluateSpan(RooBatchCompute::RunContext& eva const unsigned int bin = std::distance(boundaries.begin(), upperIt) - 1; assert(bin < boundaries.size()); - results[i] = integrate(normSet, boundaries[bin], boundaries[bin+1]) / (boundaries[bin+1]-boundaries[bin]); + output[i] = integrate(nullptr, boundaries[bin], boundaries[bin+1]) / (boundaries[bin+1]-boundaries[bin]); } - - return results; } //////////////////////////////////////////////////////////////////////////////// /// Get the bin boundaries for the observable. /// These will be recomputed whenever the shape of this object is dirty. -RooSpan RooBinSamplingPdf::binBoundaries() const { +std::span RooBinSamplingPdf::binBoundaries() const { if (isShapeDirty() || _binBoundaries.empty()) { _binBoundaries.clear(); const RooAbsBinning& binning = _observable->getBinning(nullptr); @@ -278,12 +275,12 @@ std::list* RooBinSamplingPdf::plotSamplingHint(RooAbsRealLValue& obs, do /// \note When RooBinSamplingPdf is loaded from files, integrator options will fall back to the default values. std::unique_ptr& RooBinSamplingPdf::integrator() const { if (!_integrator) { - _integrator.reset(new ROOT::Math::IntegratorOneDim(*this, + _integrator = std::make_unique(*this, ROOT::Math::IntegrationOneDim::kADAPTIVE, // GSL Integrator. Will really get it only if MathMore enabled. -1., _relEpsilon, // Abs epsilon = default, rel epsilon set by us. 0, // We don't limit the sub-intervals. Steer run time via _relEpsilon. 2 // This should read ROOT::Math::Integration::kGAUSS21, but this is in MathMore, so we cannot include it here. - )); + ); } return _integrator; diff --git a/roofit/roofitcore/src/RooBinWidthFunction.cxx b/roofit/roofitcore/src/RooBinWidthFunction.cxx index 3a4ed3e61d396..a02272294a114 100644 --- a/roofit/roofitcore/src/RooBinWidthFunction.cxx +++ b/roofit/roofitcore/src/RooBinWidthFunction.cxx @@ -18,6 +18,7 @@ /** * \class RooBinWidthFunction + * \ingroup Roofitcore * * RooBinWidthFunction is a class that returns the bin width (or volume) given a RooHistFunc. * It can be used to normalise by bin width or to compute event densities. Using the extra @@ -26,8 +27,9 @@ #include "RooBinWidthFunction.h" +#include "RooConstVar.h" #include "RooDataHist.h" -#include "RunContext.h" +#include "RooGlobalFunc.h" bool RooBinWidthFunction::_enabled = true; @@ -46,6 +48,38 @@ void RooBinWidthFunction::disableClass() { _enabled = false; } +/// Create an instance. +/// \param name Name to identify the object. +/// \param title Title for e.g. plotting. +/// \param histFunc RooHistFunc object whose bin widths should be returned. +/// \param divideByBinWidth If true, return inverse bin width. +RooBinWidthFunction::RooBinWidthFunction(const char *name, const char *title, const RooHistFunc &histFunc, bool divideByBinWidth) + : RooAbsReal(name, title), + _histFunc("HistFuncForBinWidth", "Handle to a RooHistFunc, whose bin volumes should be returned.", this, histFunc, + /*valueServer=*/false, /*shapeServer=*/false), + _divideByBinWidth(divideByBinWidth) +{ + // The RooHistFunc is only used to access this histogram observables in a + // convenient way. That's why this proxy is not "serving" this + // RooBinWidthFunction in any way (see proxy constructor arguments in the + // initializer list above). + // + // However, the variables of the histFunc **need to be** value servers, + // because the width of the current bin depends on the values of the + // observables: + for (RooAbsArg * server : histFunc.servers()) { + addServer(*server, /*valueServer=*/true, /*shapeServer=*/false); + } + // The reason why we can't simply use the histFunc as an "indirect proxy" is + // the way HistFactory is implemented. The same RooBinWidthFunction is used + // for all samples (e.g. signal and backgrounds), but uses the RooHistFunc + // of only one of the samples (this is okay because the binnings for all + // samples in the template histogram stack is the same). This entangling of + // the computation graph for the different samples messes up the component + // selection when plotting only some samples with + // `plotOn(..., RooFit::Components(...))`. +} + /// Compute current bin of observable, and return its volume or inverse volume, depending /// on configuration chosen in the constructor. /// If the bin is not valid, return a volume of 1. @@ -63,7 +97,7 @@ double RooBinWidthFunction::evaluate() const { /// Compute bin index for all values of the observable(s) in `evalData`, and return their volumes or inverse volumes, depending /// on the configuration chosen in the constructor. /// If a bin is not valid, return a volume of 1. -void RooBinWidthFunction::computeBatch(cudaStream_t*, double* output, size_t, RooFit::Detail::DataMap const& dataMap) const { +void RooBinWidthFunction::computeBatch(double* output, size_t, RooFit::Detail::DataMap const& dataMap) const { const RooDataHist& dataHist = _histFunc->dataHist(); std::vector bins = _histFunc->getBins(dataMap); auto volumes = dataHist.binVolumes(0, dataHist.numEntries()); @@ -75,12 +109,31 @@ void RooBinWidthFunction::computeBatch(cudaStream_t*, double* output, size_t, Ro } else { if (_divideByBinWidth) { for (std::size_t i=0; i < bins.size(); ++i) { - output[i] = bins[i] >= 0 ? 1./volumes[bins[i]] : 1.; + output[i] = bins[i] >= 0 ? 1./volumes[bins[i]] : 1.; } } else { for (std::size_t i=0; i < bins.size(); ++i) { - output[i] = bins[i] >= 0 ? volumes[bins[i]] : 1.; + output[i] = bins[i] >= 0 ? volumes[bins[i]] : 1.; } } } } + + +std::unique_ptr +RooBinWidthFunction::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + // If this is a binned likelihood, the pdf values can be directly + // interpreted as yields for Poisson terms in the NLL, and it doesn't make + // sense to divide them by the bin width to get a probability density. The + // NLL would only have to multiply by the bin with again. + if (ctx.binnedLikelihoodMode()) { + auto newArg = std::unique_ptr{static_cast(RooFit::RooConst(1.0).Clone())}; + ctx.markAsCompiled(*newArg); + // To propagate the information to the NLL that the pdf values can + // directly be interpreted as yields. + ctx.setBinWidthFuncFlag(true); + return newArg; + } + return RooAbsReal::compileForNormSet(normSet, ctx); +} diff --git a/roofit/roofitcore/src/RooBinnedGenContext.cxx b/roofit/roofitcore/src/RooBinnedGenContext.cxx index d748c8a5a5181..6f39bb09cd58b 100644 --- a/roofit/roofitcore/src/RooBinnedGenContext.cxx +++ b/roofit/roofitcore/src/RooBinnedGenContext.cxx @@ -37,7 +37,6 @@ generator context specific for binned pdfs. using namespace std; ClassImp(RooBinnedGenContext); -; //////////////////////////////////////////////////////////////////////////////// @@ -55,8 +54,8 @@ RooBinnedGenContext::RooBinnedGenContext(const RooAbsPdf &model, const RooArgSet ccxcoutI(Generation) << endl ; // Constructor. Build an array of generator contexts for each product component PDF - _pdfSet = (RooArgSet*) RooArgSet(model).snapshot(true) ; - _pdf = (RooAbsPdf*) _pdfSet->find(model.GetName()) ; + RooArgSet(model).snapshot(_pdfSet, true); + _pdf = (RooAbsPdf*) _pdfSet.find(model.GetName()) ; _pdf->setOperMode(RooAbsArg::ADirty,true) ; // Fix normalization set of this RooAddPdf @@ -68,34 +67,16 @@ RooBinnedGenContext::RooBinnedGenContext(const RooAbsPdf &model, const RooArgSet } _pdf->recursiveRedirectServers(_theEvent) ; - _vars = _pdf->getObservables(vars) ; - - // If pdf has boundary definitions, follow those for the binning - for (auto* rvar: dynamic_range_cast(*_vars)) { - if (rvar) { - list* binb = model.binBoundaries(*rvar,rvar->getMin(),rvar->getMax()) ; - delete binb ; - } - } - + _vars = std::unique_ptr{_pdf->getObservables(vars)}; // Create empty RooDataHist - _hist = new RooDataHist("genData","genData",*_vars) ; + _hist = std::make_unique("genData","genData",*_vars); _expectedData = false ; } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor. Delete all owned subgenerator contexts - -RooBinnedGenContext::~RooBinnedGenContext() -{ - delete _vars ; - delete _pdfSet ; - delete _hist ; -} - +RooBinnedGenContext::~RooBinnedGenContext() = default; //////////////////////////////////////////////////////////////////////////////// @@ -109,9 +90,9 @@ void RooBinnedGenContext::attach(const RooArgSet& args) //////////////////////////////////////////////////////////////////////////////// -/// One-time initialization of generator contex. Attach theEvent +/// One-time initialization of generator context. Attach theEvent /// to internal p.d.f clone and forward initialization call to -/// the component generators +/// the component generators. void RooBinnedGenContext::initGenerator(const RooArgSet &theEvent) { @@ -141,25 +122,22 @@ RooDataSet *RooBinnedGenContext::generate(double nEvt, bool /*skipInit*/, bool e if (!_pdf->canBeExtended()) { coutE(InputArguments) << "RooAbsPdf::generateBinned(" << GetName() << ") ERROR: No event count provided and p.d.f does not provide expected number of events" << endl ; - return 0 ; + return nullptr ; } else { // Don't round in expectedData mode if (_expectedData || extended) { - nEvents = _pdf->expectedEvents(_vars) ; + nEvents = _pdf->expectedEvents(_vars.get()); } else { - nEvents = Int_t(_pdf->expectedEvents(_vars)+0.5) ; + nEvents = Int_t(_pdf->expectedEvents(_vars.get())+0.5) ; } } } // Sample p.d.f. distribution - _pdf->fillDataHist(_hist,_vars,1,true) ; + _pdf->fillDataHist(_hist.get(),_vars.get(),1,true) ; // Output container - RooRealVar weight("weight","weight",0,1e9) ; - RooArgSet tmp(*_vars) ; - tmp.add(weight) ; - RooDataSet* wudata = new RooDataSet("wu","wu",tmp,RooFit::WeightVar("weight")) ; + RooDataSet* wudata = new RooDataSet("wu","wu",*_vars,RooFit::WeightVar()) ; vector histOut(_hist->numEntries()) ; double histMax(-1) ; @@ -196,7 +174,7 @@ RooDataSet *RooBinnedGenContext::generate(double nEvt, bool /*skipInit*/, bool e // Second pass for regular mode - Trim/Extend dataset to exact number of entries // Calculate difference between what is generated so far and what is requested - Int_t nEvtExtra = abs(Int_t(nEvents)-histOutSum) ; + Int_t nEvtExtra = std::abs(Int_t(nEvents)-histOutSum) ; Int_t wgt = (histOutSum>nEvents) ? -1 : 1 ; // Perform simple binned accept/reject procedure to get to exact event count diff --git a/roofit/roofitcore/src/RooBinning.cxx b/roofit/roofitcore/src/RooBinning.cxx index 3c17e4f015af7..4893aee15034a 100644 --- a/roofit/roofitcore/src/RooBinning.cxx +++ b/roofit/roofitcore/src/RooBinning.cxx @@ -51,7 +51,7 @@ ClassImp(RooBinning); RooBinning::RooBinning(double xlo, double xhi, const char* name) : RooAbsBinning(name), _xlo(0), _xhi(0), _ownBoundLo(true), _ownBoundHi(true), - _array(0), _blo(0) + _array(nullptr), _blo(0) { setRange(xlo,xhi); } @@ -62,7 +62,7 @@ RooBinning::RooBinning(double xlo, double xhi, const char* name) : RooBinning::RooBinning(Int_t nbins, double xlo, double xhi, const char* name) : RooAbsBinning(name), _xlo(0), _xhi(0), _ownBoundLo(true), _ownBoundHi(true), - _array(0), _blo(0) + _array(nullptr), _blo(0) { _boundaries.reserve(1 + nbins); setRange(xlo, xhi); @@ -76,7 +76,7 @@ RooBinning::RooBinning(Int_t nbins, double xlo, double xhi, const char* name) : RooBinning::RooBinning(Int_t nbins, const double* boundaries, const char* name) : RooAbsBinning(name), _xlo(0), _xhi(0), _ownBoundLo(true), _ownBoundHi(true), - _array(0), _blo(0) + _array(nullptr), _blo(0) { // Variable bin size constructor _boundaries.reserve(1 + nbins); @@ -90,7 +90,7 @@ RooBinning::RooBinning(Int_t nbins, const double* boundaries, const char* name) RooBinning::RooBinning(const RooBinning& other, const char* name) : RooAbsBinning(name), _xlo(other._xlo), _xhi(other._xhi), _ownBoundLo(other._ownBoundLo), _ownBoundHi(other._ownBoundHi), - _nbins(other._nbins), _boundaries(other._boundaries), _array(0), + _nbins(other._nbins), _boundaries(other._boundaries), _array(nullptr), _blo(other._blo) { } diff --git a/roofit/roofitcore/src/RooBinningCategory.cxx b/roofit/roofitcore/src/RooBinningCategory.cxx index 89ad0e77642e5..572b789868193 100644 --- a/roofit/roofitcore/src/RooBinningCategory.cxx +++ b/roofit/roofitcore/src/RooBinningCategory.cxx @@ -78,7 +78,7 @@ void RooBinningCategory::initialize(const char* catTypeName) { const int nbins = _inputVar->getBinning(_bname.Length() > 0 ? _bname.Data() : nullptr).numBins(); for (Int_t i=0 ; i0 ? Form("%s_%s_bin%d",_inputVar.arg().GetName(),_bname.Data(),i) : Form("%s_bin%d",_inputVar.arg().GetName(),i)) ; defineState(name,i); diff --git a/roofit/roofitcore/src/RooBrentRootFinder.cxx b/roofit/roofitcore/src/RooBrentRootFinder.cxx index 52018529b6a85..73cff723c520d 100644 --- a/roofit/roofitcore/src/RooBrentRootFinder.cxx +++ b/roofit/roofitcore/src/RooBrentRootFinder.cxx @@ -26,23 +26,27 @@ in the GNU scientific library (v0.99). #include "RooBrentRootFinder.h" #include "RooAbsFunc.h" -#include +#include #include "Riostream.h" #include "RooMsgService.h" using namespace std; ClassImp(RooBrentRootFinder); -; //////////////////////////////////////////////////////////////////////////////// /// Constructor taking function binding as input RooBrentRootFinder::RooBrentRootFinder(const RooAbsFunc& function) : - RooAbsRootFinder(function), + _function(&function), _valid(function.isValid()), _tol(2.2204460492503131e-16) { + if(_function->getDimension() != 1) { + oocoutE(nullptr,Eval) << "RooBrentRootFinder:: cannot find roots for function of dimension " + << _function->getDimension() << endl; + _valid= false; + } } @@ -61,7 +65,7 @@ bool RooBrentRootFinder::findRoot(double &result, double xlo, double xhi, double double fa= (*_function)(&a) - value; double fb= (*_function)(&b) - value; if(fb*fa > 0) { - oocxcoutD((TObject*)0,Eval) << "RooBrentRootFinder::findRoot(" << _function->getName() << "): initial interval does not bracket a root: (" + oocxcoutD((TObject*)nullptr,Eval) << "RooBrentRootFinder::findRoot(" << _function->getName() << "): initial interval does not bracket a root: (" << a << "," << b << "), value = " << value << " f[xlo] = " << fa << " f[xhi] = " << fb << endl; return false; } @@ -80,7 +84,7 @@ bool RooBrentRootFinder::findRoot(double &result, double xlo, double xhi, double e = b - a; } - if (fabs (fc) < fabs (fb)) { + if (std::abs(fc) < std::abs(fb)) { ac_equal = true; a = b; b = c; @@ -90,18 +94,18 @@ bool RooBrentRootFinder::findRoot(double &result, double xlo, double xhi, double fc = fa; } - double tol = 0.5 * _tol * fabs(b); + double tol = 0.5 * _tol * std::abs(b); double m = 0.5 * (c - b); - if (fb == 0 || fabs(m) <= tol) { + if (fb == 0 || std::abs(m) <= tol) { //cout << "RooBrentRootFinder: iter = " << iter << " m = " << m << " tol = " << tol << endl ; result= b; _function->restoreXVec() ; return true; } - if (fabs (e) < tol || fabs (fa) <= fabs (fb)) { + if (std::abs(e) < tol || std::abs(fa) <= std::abs(fb)) { // Bounds decreasing too slowly: use bisection d = m; e = m; @@ -129,8 +133,8 @@ bool RooBrentRootFinder::findRoot(double &result, double xlo, double xhi, double p = -p; } - double min1= 3 * m * q - fabs (tol * q); - double min2= fabs (e * q); + double min1= 3 * m * q - std::abs(tol * q); + double min2= std::abs(e * q); if (2 * p < (min1 < min2 ? min1 : min2)) { // Accept the interpolation e = d; @@ -146,7 +150,7 @@ bool RooBrentRootFinder::findRoot(double &result, double xlo, double xhi, double a = b; fa = fb; // Evaluate new trial root - if (fabs (d) > tol) { + if (std::abs(d) > tol) { b += d; } else { diff --git a/roofit/roofitcore/src/RooCacheManager.cxx b/roofit/roofitcore/src/RooCacheManager.cxx index c032265131e9d..3f571a725da31 100644 --- a/roofit/roofitcore/src/RooCacheManager.cxx +++ b/roofit/roofitcore/src/RooCacheManager.cxx @@ -21,12 +21,12 @@ Template class RooCacheManager manages the storage of any type of data indexed on the choice of normalization and optionally the set of integrated observables. -The purpose of this class is to faciliate storage of intermediate results +The purpose of this class is to facilitate storage of intermediate results in operator p.d.f.s whose value and inner working are often highly dependent on the user provided choice of normalization in getVal(). For efficiency reasons these normalization set pointer are -derefenced as little as possible. This class contains a lookup +dereferenced as little as possible. This class contains a lookup table for RooArgSet pointer pairs -> normalization lists. Distinct pointer pairs that represent the same normalization/projection are recognized and will all point to the same normalization list. Lists @@ -44,8 +44,3 @@ using namespace std ; #define ROOFIT_R__NO_CLASS_TEMPLATE_SPECIALIZATION templateClassImp(RooCacheManager); #endif - - - - - diff --git a/roofit/roofitcore/src/RooCachedPdf.cxx b/roofit/roofitcore/src/RooCachedPdf.cxx index 6d45f2d5fa625..92261efce6645 100644 --- a/roofit/roofitcore/src/RooCachedPdf.cxx +++ b/roofit/roofitcore/src/RooCachedPdf.cxx @@ -40,7 +40,7 @@ ClassImp(RooCachedPdf); /// in the binning named "cache" in the observables of the function. The dimensions /// of the cache are automatically matched to the number of observables used /// in each use context. Multiple cache in different observable may exists -/// simultanously if the cached p.d.f is used with multiple observable +/// simultaneously if the cached p.d.f is used with multiple observable /// configurations simultaneously RooCachedPdf::RooCachedPdf(const char *name, const char *title, RooAbsPdf& _pdf) : @@ -139,13 +139,13 @@ void RooCachedPdf::preferredObservableScanOrder(const RooArgSet& obs, RooArgSet& /// of the external input p.d.f given the choice of observables defined /// in nset -RooArgSet* RooCachedPdf::actualObservables(const RooArgSet& nset) const +RooFit::OwningPtr RooCachedPdf::actualObservables(const RooArgSet& nset) const { - if (_cacheObs.getSize()>0) { - return pdf.arg().getObservables(_cacheObs) ; + if (!_cacheObs.empty()) { + return pdf->getObservables(_cacheObs); } - return pdf.arg().getObservables(nset) ; + return pdf->getObservables(nset); } @@ -156,12 +156,9 @@ RooArgSet* RooCachedPdf::actualObservables(const RooArgSet& nset) const /// the cache observables. If this p.d.f is operated in automatic mode, /// return the parameters of the external input p.d.f -RooArgSet* RooCachedPdf::actualParameters(const RooArgSet& nset) const +RooFit::OwningPtr RooCachedPdf::actualParameters(const RooArgSet& nset) const { - if (_cacheObs.getSize()>0) { - return pdf.arg().getParameters(_cacheObs) ; - } - return pdf.arg().getParameters(nset) ; + return pdf.arg().getParameters(_cacheObs.empty() ? nset : _cacheObs) ; } diff --git a/roofit/roofitcore/src/RooCachedReal.cxx b/roofit/roofitcore/src/RooCachedReal.cxx index 2c89c0dba16f3..6f308a6caa29f 100644 --- a/roofit/roofitcore/src/RooCachedReal.cxx +++ b/roofit/roofitcore/src/RooCachedReal.cxx @@ -156,7 +156,7 @@ void RooCachedReal::fillCacheObject(RooAbsCachedReal::FuncCacheElem& cache) cons // Delete source clone if we don't cache it if (!cache.cacheSource()) { - cache.setSourceClone(0) ; + cache.setSourceClone(nullptr) ; } cache.func()->setCdfBoundaries(_useCdfBoundaries) ; @@ -173,13 +173,9 @@ void RooCachedReal::fillCacheObject(RooAbsCachedReal::FuncCacheElem& cache) cons /// of the external input p.d.f given the choice of observables defined /// in nset -RooArgSet* RooCachedReal::actualObservables(const RooArgSet& nset) const +RooFit::OwningPtr RooCachedReal::actualObservables(const RooArgSet& nset) const { - if (_cacheObs.getSize()>0) { - return func.arg().getObservables(_cacheObs) ; - } - - return func.arg().getObservables(nset) ; + return func->getObservables(_cacheObs.empty() ? nset : _cacheObs); } @@ -190,12 +186,9 @@ RooArgSet* RooCachedReal::actualObservables(const RooArgSet& nset) const /// the cache observables. If this p.d.f is operated in automatic mode, /// return the parameters of the external input p.d.f -RooArgSet* RooCachedReal::actualParameters(const RooArgSet& nset) const +RooFit::OwningPtr RooCachedReal::actualParameters(const RooArgSet& nset) const { - if (_cacheObs.getSize()>0) { - return func.arg().getParameters(_cacheObs) ; - } - return func.arg().getParameters(nset) ; + return func->getParameters(_cacheObs.empty() ? nset : _cacheObs); } @@ -205,7 +198,3 @@ void RooCachedReal::operModeHook() ((RooAbsArg*)func.absArg())->setOperMode(ADirty) ; } } - - - - diff --git a/roofit/roofitcore/src/RooCategory.cxx b/roofit/roofitcore/src/RooCategory.cxx index 863240f52b787..7987cf6c9e425 100644 --- a/roofit/roofitcore/src/RooCategory.cxx +++ b/roofit/roofitcore/src/RooCategory.cxx @@ -103,7 +103,7 @@ std::map> RooCategory::_shar RooCategory::RooCategory() { - TRACE_CREATE + TRACE_CREATE; } @@ -112,11 +112,11 @@ RooCategory::RooCategory() /// Constructor. Types must be defined using defineType() before variable can be used RooCategory::RooCategory(const char *name, const char *title) : RooAbsCategoryLValue(name,title), - _ranges(new RangeMap_t()) + _ranges{std::make_unique()} { setValueDirty() ; setShapeDirty() ; - TRACE_CREATE + TRACE_CREATE; } @@ -127,7 +127,7 @@ RooCategory::RooCategory(const char *name, const char *title) : /// \param[in] allowedStates Map of allowed states. Pass e.g. `{ {"0Lep", 0}, {"1Lep:, 1} }` RooCategory::RooCategory(const char* name, const char* title, const std::map& allowedStates) : RooAbsCategoryLValue(name,title), - _ranges(new RangeMap_t()) + _ranges{std::make_unique()} { defineTypes(allowedStates); } @@ -141,7 +141,7 @@ RooCategory::RooCategory(const RooCategory& other, const char* name) : RooAbsCategoryLValue(other, name), _ranges(other._ranges) { - TRACE_CREATE + TRACE_CREATE; } @@ -150,7 +150,7 @@ RooCategory::RooCategory(const RooCategory& other, const char* name) : RooCategory::~RooCategory() { - TRACE_DESTROY + TRACE_DESTROY; } @@ -487,7 +487,7 @@ void RooCategory::installLegacySharedProp(const RooCategorySharedProperties* pro _ranges = std::move(existingObject); } else { // This range is unknown, make a new object - _ranges = std::make_shared>>(); + _ranges = std::make_unique>>(); auto& rangesMap = *_ranges; // Copy the data: @@ -507,7 +507,7 @@ void RooCategory::installLegacySharedProp(const RooCategorySharedProperties* pro /// In current versions of the class, a map with ranges can be shared between instances. -/// If an instance with the same name alreday uses the same map, the instances will start sharing. +/// If an instance with the same name already uses the same map, the instances will start sharing. /// Otherwise, this instance will be registered, and future copies being read will share with this /// one. void RooCategory::installSharedRange(std::unique_ptr&& rangeMap) { @@ -521,16 +521,12 @@ void RooCategory::installSharedRange(std::unique_ptr&& rangeMap) { if (a.size() != b.size()) return false; - auto vecsEqual = [](const std::vector& aa, const std::vector& bb) { - return aa.size() == bb.size() && std::equal(aa.begin(), aa.end(), bb.begin()); - }; - for (const auto& itemA : a) { const auto itemB = b.find(itemA.first); if (itemB == b.end()) return false; - if (!vecsEqual(itemA.second, itemB->second)) + if (itemA.second != itemB->second) return false; } diff --git a/roofit/roofitcore/src/RooChangeTracker.cxx b/roofit/roofitcore/src/RooChangeTracker.cxx index 50ad80aa34e3f..cbf4fd6e2e212 100644 --- a/roofit/roofitcore/src/RooChangeTracker.cxx +++ b/roofit/roofitcore/src/RooChangeTracker.cxx @@ -32,7 +32,7 @@ though usually only one observable actually changes. #include "Riostream.h" -#include +#include #include "RooChangeTracker.h" #include "RooAbsReal.h" diff --git a/roofit/roofitcore/src/RooChi2Var.cxx b/roofit/roofitcore/src/RooChi2Var.cxx index fd329a7e24262..b5b745746507a 100644 --- a/roofit/roofitcore/src/RooChi2Var.cxx +++ b/roofit/roofitcore/src/RooChi2Var.cxx @@ -51,6 +51,8 @@ */ #include "RooChi2Var.h" + +#include "FitHelpers.h" #include "RooDataHist.h" #include "RooAbsPdf.h" #include "RooCmdConfig.h" @@ -67,7 +69,7 @@ using namespace std; namespace { template - RooAbsTestStatistic::Configuration makeRooAbsTestStatisticCfgForFunc(Args const& ... args) { + RooAbsTestStatistic::Configuration makeRooAbsTestStatisticCfg(Args const& ... args) { RooAbsTestStatistic::Configuration cfg; cfg.rangeName = RooCmdConfig::decodeStringOnTheFly("RooChi2Var::RooChi2Var","RangeWithName",0,"",args...); cfg.nCPU = RooCmdConfig::decodeIntOnTheFly("RooChi2Var::RooChi2Var","NumCPU",0,1,args...); @@ -75,12 +77,6 @@ namespace { cfg.verbose = static_cast(RooCmdConfig::decodeIntOnTheFly("RooChi2Var::RooChi2Var","Verbose",0,1,args...)); cfg.cloneInputData = false; cfg.integrateOverBinsPrecision = RooCmdConfig::decodeDoubleOnTheFly("RooChi2Var::RooChi2Var", "IntegrateBins", 0, -1., {args...}); - return cfg; - } - - template - RooAbsTestStatistic::Configuration makeRooAbsTestStatisticCfgForPdf(Args const& ... args) { - auto cfg = makeRooAbsTestStatisticCfgForFunc(args...); cfg.addCoefRangeName = RooCmdConfig::decodeStringOnTheFly("RooChi2Var::RooChi2Var","AddCoefRange",0,"",args...); cfg.splitCutRange = static_cast(RooCmdConfig::decodeIntOnTheFly("RooChi2Var::RooChi2Var","SplitRange",0,0,args...)); return cfg; @@ -88,7 +84,6 @@ namespace { } ClassImp(RooChi2Var); -; RooArgSet RooChi2Var::_emptySet ; @@ -140,19 +135,19 @@ RooChi2Var::RooChi2Var(const char *name, const char* title, RooAbsReal& func, Ro const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6, const RooCmdArg& arg7,const RooCmdArg& arg8,const RooCmdArg& arg9) : RooAbsOptTestStatistic(name,title,func,hdata,_emptySet, - makeRooAbsTestStatisticCfgForFunc(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)) + makeRooAbsTestStatisticCfg(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)) { RooCmdConfig pc("RooChi2Var::RooChi2Var") ; pc.defineInt("etype","DataError",0,(Int_t)RooDataHist::Auto) ; - pc.defineInt("extended","Extended",0,false) ; + pc.defineInt("extended","Extended",0,RooFit::FitHelpers::extendedFitDefault); pc.allowUndefined() ; pc.process(arg1) ; pc.process(arg2) ; pc.process(arg3) ; pc.process(arg4) ; pc.process(arg5) ; pc.process(arg6) ; pc.process(arg7) ; pc.process(arg8) ; pc.process(arg9) ; - if (func.IsA()->InheritsFrom(RooAbsPdf::Class())) { - _funcMode = pc.getInt("extended") ? ExtendedPdf : Pdf ; + if (auto pdf = dynamic_cast(&func)) { + _funcMode = pdf->interpretExtendedCmdArg(pc.getInt("extended")) ? ExtendedPdf : Pdf ; } else { _funcMode = Function ; } @@ -165,61 +160,6 @@ RooChi2Var::RooChi2Var(const char *name, const char* title, RooAbsReal& func, Ro } -//////////////////////////////////////////////////////////////////////////////// -/// RooChi2Var constructor. Optional arguments taken -/// -/// \param[in] name Name of the PDF -/// \param[in] title Title for plotting etc. -/// \param[in] pdf PDF to fit -/// \param[in] hdata Data histogram -/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9 Optional arguments according to table below. -/// -///
    Argument Effect -///
    -/// Extended() Include extended term in calculation -///
    -/// DataError() Choose between Poisson errors and Sum-of-weights errors -///
    -/// NumCPU() Activate parallel processing feature -///
    -/// Range() Fit only selected region -///
    -/// SumCoefRange() Set the range in which to interpret the coefficients of RooAddPdf components -///
    -/// SplitRange() Fit range is split by index category of simultaneous PDF -///
    -/// ConditionalObservables() Define projected observables -///
    -/// Verbose() Verbose output of GOF framework -///
    -/// IntegrateBins() Integrate PDF within each bin. This sets the desired precision. - -RooChi2Var::RooChi2Var(const char *name, const char* title, RooAbsPdf& pdf, RooDataHist& hdata, - const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3, - const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6, - const RooCmdArg& arg7,const RooCmdArg& arg8,const RooCmdArg& arg9) : - RooAbsOptTestStatistic(name,title,pdf,hdata, - *RooCmdConfig::decodeSetOnTheFly("RooChi2Var::RooChi2Var","ProjectedObservables",0,&_emptySet, - arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9), - makeRooAbsTestStatisticCfgForPdf(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)) -{ - RooCmdConfig pc("RooChi2Var::RooChi2Var") ; - pc.defineInt("extended","Extended",0,false) ; - pc.defineInt("etype","DataError",0,(Int_t)RooDataHist::Auto) ; - pc.allowUndefined() ; - - pc.process(arg1) ; pc.process(arg2) ; pc.process(arg3) ; - pc.process(arg4) ; pc.process(arg5) ; pc.process(arg6) ; - pc.process(arg7) ; pc.process(arg8) ; pc.process(arg9) ; - - _funcMode = pc.getInt("extended") ? ExtendedPdf : Pdf ; - _etype = (RooDataHist::ErrorType) pc.getInt("etype") ; - if (_etype==RooAbsData::Auto) { - _etype = hdata.isNonPoissonWeighted()? RooAbsData::SumW2 : RooAbsData::Expected ; - } -} - - //////////////////////////////////////////////////////////////////////////////// /// Copy constructor @@ -240,12 +180,8 @@ RooChi2Var::RooChi2Var(const RooChi2Var& other, const char* name) : double RooChi2Var::evaluatePartition(std::size_t firstEvent, std::size_t lastEvent, std::size_t stepSize) const { - double result(0), carry(0); - _dataClone->store()->recalculateCache( _projDeps, firstEvent, lastEvent, stepSize, false) ; - - // Determine normalization factor depending on type of input function double normFactor(1) ; switch (_funcMode) { diff --git a/roofit/roofitcore/src/RooClassFactory.cxx b/roofit/roofitcore/src/RooClassFactory.cxx index 9ac86c061c6d8..4a0db9aea008a 100644 --- a/roofit/roofitcore/src/RooClassFactory.cxx +++ b/roofit/roofitcore/src/RooClassFactory.cxx @@ -39,8 +39,12 @@ instantiate objects. #include "RooWorkspace.h" #include "RooGlobalFunc.h" #include "RooAbsPdf.h" -#include "strlcpy.h" + +#include + +#include #include +#include using namespace std; @@ -51,11 +55,11 @@ class ClassFacIFace : public RooFactoryWSTool::IFace { std::string create(RooFactoryWSTool& ft, const char* typeName, const char* instanceName, std::vector args) override ; } ; -static Int_t init(); +static int init(); -Int_t dummy = init(); +int dummy = init(); -static Int_t init() +static int init() { RooFactoryWSTool::IFace* iface = new ClassFacIFace ; RooFactoryWSTool::registerSpecial("CEXPR",iface) ; @@ -64,53 +68,137 @@ static Int_t init() return 0 ; } -} +bool makeAndCompileClass(std::string const &baseClassName, std::string const &name, std::string const &expression, + const RooArgList &vars, std::string const &intExpression) +{ + // A structure to store the inputs to this function, to check if has been + // called already with the same arguments. + class ClassInfo { + public: + ClassInfo(std::string const &baseClassName, std::string const &name, std::string const &expression, + const RooArgList &vars, std::string const &intExpression) + : _baseClassName{baseClassName}, _name{name}, _expression{expression}, _intExpression{intExpression} + { + _argNames.reserve(vars.size()); + _argsAreCategories.reserve(vars.size()); + for (RooAbsArg *arg : vars) { + _argNames.emplace_back(arg->GetName()); + _argsAreCategories.emplace_back(arg->isCategory()); + } + } + bool operator==(const ClassInfo &other) const + { + return other._baseClassName == _baseClassName && other._name == _name && other._expression == _expression && + other._argNames == _argNames && other._argsAreCategories == _argsAreCategories && + other._intExpression == _intExpression; + } -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor + std::string _baseClassName; + std::string _name; + std::string _expression; + std::vector _argNames; + std::vector _argsAreCategories; + std::string _intExpression; + }; -RooClassFactory::RooClassFactory() -{ -} + static std::vector infosVec; + static std::mutex infosVecMutex; // protects infosVec + ClassInfo info{baseClassName, name, expression, vars, intExpression}; + // Check if this class was already compiled + auto found = std::find_if(infosVec.begin(), infosVec.end(), [&](auto const &elem) { return elem._name == name; }); + if (found != infosVec.end()) { + if (*found == info) { + return false; + } + std::stringstream ss; + ss << "RooClassFactory ERROR The type, expressions, or variables for the class \"" << name + << "\" are not identical to what you passed last time this class was compiled! This is not allowed."; + oocoutE(nullptr, InputArguments) << ss.str() << std::endl; + throw std::runtime_error(ss.str()); + } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor + // Making a new compiled class is not thread safe + const std::lock_guard lock(infosVecMutex); + + infosVec.emplace_back(info); + + std::string realArgNames, catArgNames; + for (RooAbsArg *arg : vars) { + if (dynamic_cast(arg)) { + if (!realArgNames.empty()) + realArgNames += ","; + realArgNames += arg->GetName(); + } else if (arg->isCategory()) { + if (!catArgNames.empty()) + catArgNames += ","; + catArgNames += arg->GetName(); + } else { + oocoutE(nullptr, InputArguments) << "RooClassFactory ERROR input argument " << arg->GetName() + << " is neither RooAbsReal nor RooAbsCategory and is ignored" << endl; + } + } -RooClassFactory::~RooClassFactory() + bool ret = RooClassFactory::makeClass(baseClassName, name, realArgNames.c_str(), catArgNames.c_str(), expression, + !intExpression.empty(), false, intExpression); + if (ret) { + return ret; + } + + TInterpreter::EErrorCode ecode; + gInterpreter->ProcessLineSynch((".L " + name + ".cxx+").c_str(), &ecode); + return (ecode != TInterpreter::kNoError); +} + +RooAbsReal *makeClassInstance(std::string const &baseClassName, std::string const &className, std::string const &name, + std::string const &expression, const RooArgList &vars, std::string const &intExpression) { + // Use class factory to compile and link specialized function + bool error = makeAndCompileClass(baseClassName, className, expression, vars, intExpression); + + // Check that class was created OK + if (error) { + RooErrorHandler::softAbort(); + } + + // Create interpreter line that instantiates specialized object + std::string line = std::string("new ") + className + "(\"" + name + "\",\"" + name + "\""; + + // Make list of pointer values (represented in hex ascii) to be passed to cint + // Note that the order of passing arguments must match the convention in which + // the class code is generated: first all reals, then all categories + + std::string argList; + // First pass the RooAbsReal arguments in the list order + for (RooAbsArg *var : vars) { + if (dynamic_cast(var)) { + argList += Form(",*reinterpret_cast(0x%zx)", (std::size_t)var); + } + } + // Next pass the RooAbsCategory arguments in the list order + for (RooAbsArg *var : vars) { + if (var->isCategory()) { + argList += Form(",*reinterpret_cast(0x%zx)", (std::size_t)var); + } + } + + line += argList + ") ;"; + + // Let interpreter instantiate specialized formula + return reinterpret_cast(gInterpreter->ProcessLineSynch(line.c_str())); } +} // namespace //////////////////////////////////////////////////////////////////////////////// -bool RooClassFactory::makeAndCompilePdf(const char* name, const char* expression, const RooArgList& vars, const char* intExpression) +bool RooClassFactory::makeAndCompilePdf(std::string const &name, std::string const &expression, const RooArgList &vars, + std::string const &intExpression) { - string realArgNames,catArgNames ; - for (RooAbsArg * arg : vars) { - if (dynamic_cast(arg)) { - if (realArgNames.size()>0) realArgNames += "," ; - realArgNames += arg->GetName() ; - } else if (dynamic_cast(arg)) { - if (catArgNames.size()>0) catArgNames += "," ; - catArgNames += arg->GetName() ; - } else { - oocoutE(nullptr,InputArguments) << "RooClassFactory::makeAndCompilePdf ERROR input argument " << arg->GetName() - << " is neither RooAbsReal nor RooAbsCategory and is ignored" << endl ; - } - } - - bool ret = makePdf(name,realArgNames.c_str(),catArgNames.c_str(),expression,intExpression?true:false,false,intExpression) ; - if (ret) { - return ret ; - } - - TInterpreter::EErrorCode ecode; - gInterpreter->ProcessLineSynch(Form(".L %s.cxx+",name),&ecode) ; - return (ecode!=TInterpreter::kNoError) ; + return makeAndCompileClass("RooAbsPdf", name, expression, vars, intExpression); } @@ -128,30 +216,10 @@ bool RooClassFactory::makeAndCompilePdf(const char* name, const char* expression /// "" is the C++ expression that calculates that /// integral. -bool RooClassFactory::makeAndCompileFunction(const char* name, const char* expression, const RooArgList& vars, const char* intExpression) +bool RooClassFactory::makeAndCompileFunction(std::string const &name, std::string const &expression, const RooArgList &vars, + std::string const &intExpression) { - string realArgNames,catArgNames ; - for (RooAbsArg * arg : vars) { - if (dynamic_cast(arg)) { - if (realArgNames.size()>0) realArgNames += "," ; - realArgNames += arg->GetName() ; - } else if (dynamic_cast(arg)) { - if (catArgNames.size()>0) catArgNames += "," ; - catArgNames += arg->GetName() ; - } else { - oocoutE(nullptr,InputArguments) << "RooClassFactory::makeAndCompileFunction ERROR input argument " << arg->GetName() - << " is neither RooAbsReal nor RooAbsCategory and is ignored" << endl ; - } - } - - bool ret = makeFunction(name,realArgNames.c_str(),catArgNames.c_str(),expression,intExpression?true:false,intExpression) ; - if (ret) { - return ret ; - } - - TInterpreter::EErrorCode ecode; - gInterpreter->ProcessLineSynch(Form(".L %s.cxx+",name),&ecode) ; - return (ecode!=TInterpreter::kNoError) ; + return makeAndCompileClass("RooAbsReal", name, expression, vars, intExpression); } @@ -175,16 +243,17 @@ bool RooClassFactory::makeAndCompileFunction(const char* name, const char* expre /// "" is the C++ expression that calculates that /// integral. -RooAbsReal* RooClassFactory::makeFunctionInstance(const char* name, const char* expression, const RooArgList& vars, const char* intExpression) +RooAbsReal* RooClassFactory::makeFunctionInstance(std::string const &name, std::string const &expression, const RooArgList& vars, std::string const &intExpression) { // Construct unique class name for this function expression - string tmpName(name) ; + std::string tmpName(name) ; tmpName[0] = toupper(tmpName[0]) ; - string className = Form("Roo%sFunc",tmpName.c_str()) ; + string className = "Roo" + tmpName + "Func"; return makeFunctionInstance(className.c_str(),name,expression,vars,intExpression) ; } + //////////////////////////////////////////////////////////////////////////////// /// Write, compile and load code and instantiate object for a /// RooAbsReal implementation with class name 'name', taking all @@ -205,73 +274,27 @@ RooAbsReal* RooClassFactory::makeFunctionInstance(const char* name, const char* /// "" is the C++ expression that calculates that /// integral. -RooAbsReal* RooClassFactory::makeFunctionInstance(const char* className, const char* name, const char* expression, const RooArgList& vars, const char* intExpression) +RooAbsReal *RooClassFactory::makeFunctionInstance(std::string const &className, std::string const &name, std::string const &expression, + const RooArgList &vars, std::string const &intExpression) { - // Use class factory to compile and link specialized function - bool error = makeAndCompileFunction(className,expression,vars,intExpression) ; - - // Check that class was created OK - if (error) { - RooErrorHandler::softAbort() ; - } - - // Create interpreter line that instantiates specialized object - std::string line = std::string("new ") + className + "(\"" + name + "\",\"" + name + "\""; - - // Make list of pointer values (represented in hex ascii) to be passed to cint - // Note that the order of passing arguments must match the convention in which - // the class code is generated: first all reals, then all categories - - std::string argList ; - // First pass the RooAbsReal arguments in the list order - for(RooAbsArg * var : vars) { - if (dynamic_cast(var)) { - argList += Form(",*((RooAbsReal*)0x%zx)",(size_t)var) ; - } - } - // Next pass the RooAbsCategory arguments in the list order - for(RooAbsArg * var : vars) { - if (dynamic_cast(var)) { - argList += Form(",*((RooAbsCategory*)0x%zx)",(size_t)var) ; - } - } - - line += argList + ") ;" ; - - // Let interpreter instantiate specialized formula - return (RooAbsReal*) gInterpreter->ProcessLineSynch(line.c_str()) ; + return static_cast(makeClassInstance("RooAbsRal", className, name, expression, vars, intExpression)); } - - //////////////////////////////////////////////////////////////////////////////// -/// Write, compile and load code and instantiate object for a -/// RooAbsPdf implementation with class name 'name', taking all -/// elements of 'vars' as constructor arguments. The initial value -/// expression is taken to be 'expression' which can be any one-line -/// C++ expression in terms of variables that occur in 'vars'. -/// -/// The returned object is an instance of the object you just defined -/// connected to the variables listed in 'vars'. The name of the -/// object is 'name', its class name RooClass. -/// -/// This function is an effective compiled replacement of RooGenericPdf +/// Write, compile and load code and instantiate object for a RooAbsPdf +/// implementation. The difference to makeFunctionInstance() is the base +/// class of the written class (RooAbsPdf instead of RooAbsReal). /// -/// You can add optional expressions for analytical integrals to be -/// advertised by your class in the syntax -/// ":;:" -/// where "" a name of the observable integrated over and -/// "" is the C++ expression that calculates that -/// integral. +/// \see RooClassFactory::makeFunctionInstance(const char*, const char*, RooArgList const&, const char*) -RooAbsPdf* RooClassFactory::makePdfInstance(const char* name, const char* expression, - const RooArgList& vars, const char* intExpression) +RooAbsPdf* RooClassFactory::makePdfInstance(std::string const &name, std::string const &expression, + const RooArgList& vars, std::string const &intExpression) { // Construct unique class name for this function expression - string tmpName(name) ; + std::string tmpName(name) ; tmpName[0] = toupper(tmpName[0]) ; - string className = Form("Roo%sPdf",tmpName.c_str()) ; + string className = "Roo" + tmpName + "Pdf"; return makePdfInstance(className.c_str(),name,expression,vars,intExpression) ; } @@ -296,66 +319,23 @@ RooAbsPdf* RooClassFactory::makePdfInstance(const char* name, const char* expres /// "" is the C++ expression that calculates that /// integral. -RooAbsPdf* RooClassFactory::makePdfInstance(const char* className, const char* name, const char* expression, - const RooArgList& vars, const char* intExpression) +RooAbsPdf *RooClassFactory::makePdfInstance(std::string const &className, std::string const &name, std::string const &expression, + const RooArgList &vars, std::string const &intExpression) { - // Use class factory to compile and link specialized function - bool error = makeAndCompilePdf(className,expression,vars,intExpression) ; - - // Check that class was created OK - if (error) { - RooErrorHandler::softAbort() ; - } - - // Create interpreter line that instantiates specialized object - std::string line = std::string("new ") + className + "(\"" + name + "\",\"" + name + "\""; - - // Make list of pointer values (represented in hex ascii) to be passed to cint - // Note that the order of passing arguments must match the convention in which - // the class code is generated: first all reals, then all categories - - std::string argList ; - // First pass the RooAbsReal arguments in the list order - for (RooAbsArg * var : vars) { - if (dynamic_cast(var)) { - argList += Form(",*((RooAbsReal*)0x%zx)",(size_t)var) ; - } - } - // Next pass the RooAbsCategory arguments in the list order - for (RooAbsArg * var : vars) { - if (dynamic_cast(var)) { - argList += Form(",*((RooAbsCategory*)0x%zx)",(size_t)var) ; - } - } - - line += argList + ") ;" ; - - // Let interpreter instantiate specialized formula - return (RooAbsPdf*) gInterpreter->ProcessLineSynch(line.c_str()) ; + return static_cast(makeClassInstance("RooAbsPdf", className, name, expression, vars, intExpression)); } //////////////////////////////////////////////////////////////////////////////// -/// Write code for a RooAbsPdf implementation with class name 'name', -/// taking RooAbsReal arguments with names listed in argNames and -/// RooAbsCategory arguments with names listed in catArgNames as -/// constructor arguments (use a comma separated list for multiple -/// arguments). The initial value expression is taken to be -/// 'expression' which can be any one-line C++ expression in terms of -/// variables that occur in 'vars'. Skeleton code for handling of -/// analytical integrals is added if hasAnaInt is true. You can add -/// optional expressions for analytical integrals to be advertised by -/// your class in the syntax -/// ":;:" -/// where "" a name of the observable integrated over and -/// "" is the C++ expression that calculates that -/// integral. Skeleton code for internal event generation is added -/// if hasIntGen is true +/// Write code for a RooAbsPdf implementation with class name 'name'. +/// The difference to makePdf() is the base +/// class of the written class (RooAbsPdf instead of RooAbsReal). /// +/// \see RooClassFactory::makePdf(const char*, const char*, std::string const &, const char*, RooArgList const&, bool, bool, const char*) -bool RooClassFactory::makePdf(const char* name, const char* argNames, const char* catArgNames, const char* expression, - bool hasAnaInt, bool hasIntGen, const char* intExpression) +bool RooClassFactory::makePdf(std::string const &name, std::string const &argNames, std::string const &catArgNames, std::string const &expression, + bool hasAnaInt, bool hasIntGen, std::string const &intExpression) { return makeClass("RooAbsPdf",name,argNames,catArgNames,expression,hasAnaInt,hasIntGen,intExpression) ; } @@ -377,12 +357,63 @@ bool RooClassFactory::makePdf(const char* name, const char* argNames, const char /// "" is the C++ expression that calculates that /// integral. -bool RooClassFactory::makeFunction(const char* name, const char* argNames, const char* catArgNames, const char* expression, bool hasAnaInt, const char* intExpression) +bool RooClassFactory::makeFunction(std::string const &name, std::string const &argNames, std::string const &catArgNames, std::string const &expression, bool hasAnaInt, std::string const &intExpression) { return makeClass("RooAbsReal",name,argNames,catArgNames,expression,hasAnaInt,false,intExpression) ; } +namespace { + +std::string listVars(std::vector const &alist, std::vector const &isCat = {}) +{ + std::stringstream ss; + for (std::size_t i = 0; i < alist.size(); ++i) { + if (!isCat.empty()) { + ss << (isCat[i] ? "int" : "double") << " "; + } + ss << alist[i]; + if (i < alist.size() - 1) { + ss << ", "; + } + } + return ss.str(); +} + +std::string declareVarSpans(std::vector const &alist) +{ + std::stringstream ss; + for (std::size_t i = 0; i < alist.size(); ++i) { + ss << " " + << "std::span " << alist[i] << "Span = dataMap.at(" << alist[i] << ");\n"; + } + return ss.str(); +} + +std::string getFromVarSpans(std::vector const &alist) +{ + std::stringstream ss; + for (std::size_t i = 0; i < alist.size(); ++i) { + std::string name = alist[i] + "Span"; + ss << name << ".size() > 1 ? " << name << "[i] : " << name << "[0]"; + if (i < alist.size() - 1) { + ss << ",\n "; + } + } + return ss.str(); +} + +/// Replace all occurrences of `what` with `with` inside of `inOut`. +void replaceAll(std::string &inOut, std::string_view what, std::string_view with) +{ + for (std::string::size_type pos{}; inOut.npos != (pos = inOut.find(what.data(), pos, what.length())); + pos += with.length()) { + inOut.replace(pos, what.length(), with.data(), with.length()); + } +} + +} // namespace + //////////////////////////////////////////////////////////////////////////////// /// Write code for a 'baseName' implementation with class name 'className', /// taking RooAbsReal arguments with names listed in argNames and @@ -401,26 +432,17 @@ bool RooClassFactory::makeFunction(const char* name, const char* argNames, const /// if hasIntGen is true /// -bool RooClassFactory::makeClass(const char* baseName, const char* className, const char* realArgNames, const char* catArgNames, - const char* expression, bool hasAnaInt, bool hasIntGen, const char* intExpression) +bool RooClassFactory::makeClass(std::string const& baseName, std::string const& className, std::string const &realArgNames, std::string const &catArgNames, + std::string const &expression, bool hasAnaInt, bool hasIntGen, std::string const &intExpression) { // Check that arguments were given - if (!baseName) { - oocoutE(nullptr,InputArguments) << "RooClassFactory::makeClass: ERROR: a base class name must be given" << endl ; - return true ; - } - - if (!className) { - oocoutE(nullptr,InputArguments) << "RooClassFactory::makeClass: ERROR: a class name must be given" << endl ; - return true ; - } - if ((!realArgNames || !*realArgNames) && (!catArgNames || !*catArgNames)) { + if (realArgNames.empty() && catArgNames.empty()) { oocoutE(nullptr,InputArguments) << "RooClassFactory::makeClass: ERROR: A list of input argument names must be given" << endl ; return true ; } - if (intExpression && !hasAnaInt) { + if (!intExpression.empty() && !hasAnaInt) { oocoutE(nullptr,InputArguments) << "RooClassFactory::makeClass: ERROR no analytical integration code requestion, but expression for analytical integral provided" << endl ; return true ; } @@ -429,56 +451,35 @@ bool RooClassFactory::makeClass(const char* baseName, const char* className, con vector alist ; vector isCat ; - if (realArgNames && *realArgNames) { - const size_t bufSize = strlen(realArgNames)+1; - std::vector buf(bufSize); - strlcpy(buf.data(),realArgNames,bufSize) ; - char* token = strtok(buf.data(),",") ; - while(token) { - alist.push_back(token) ; - isCat.push_back(false) ; - token = strtok(0,",") ; - } + for(auto const& token : ROOT::Split(realArgNames, ",", /*skipEmpyt=*/true)) { + alist.push_back(token) ; + isCat.push_back(false) ; } - if (catArgNames && *catArgNames) { - const size_t bufSize = strlen(catArgNames)+1; - std::vector buf(bufSize); - strlcpy(buf.data(),catArgNames,bufSize) ; - char* token = strtok(buf.data(),",") ; - while(token) { - alist.push_back(token) ; - isCat.push_back(true) ; - token = strtok(0,",") ; - } + for(auto const& token : ROOT::Split(catArgNames, ",", /*skipEmpyt=*/true)) { + alist.push_back(token) ; + isCat.push_back(true) ; } - TString impFileName(className), hdrFileName(className) ; - impFileName += ".cxx" ; - hdrFileName += ".h" ; + std::stringstream hf; + hf << R"(/***************************************************************************** + * Project: RooFit * + * * + * This code was autogenerated by RooClassFactory * + *****************************************************************************/ - TString ifdefName(className) ; - ifdefName.ToUpper() ; +#ifndef CLASS_NAME_h +#define CLASS_NAME_h - ofstream hf(hdrFileName) ; - hf << "/*****************************************************************************" << endl - << " * Project: RooFit *" << endl - << " * *" << endl - << " * This code was autogenerated by RooClassFactory * " << endl - << " *****************************************************************************/" << endl - << endl - << "#ifndef " << ifdefName << endl - << "#define " << ifdefName << endl - << "" << endl - << "#include \"" << baseName << ".h\"" << endl - << "#include \"RooRealProxy.h\"" << endl - << "#include \"RooCategoryProxy.h\"" << endl - << "#include \"RooAbsReal.h\"" << endl - << "#include \"RooAbsCategory.h\"" << endl - << " " << endl - << "class " << className << " : public " << baseName << " {" << endl - << "public:" << endl - << " " << className << "() {} ; " << endl - << " " << className << "(const char *name, const char *title," << endl ; +#include +#include +#include +#include +#include + +class CLASS_NAME : public BASE_NAME { +public: + CLASS_NAME() {} + CLASS_NAME(const char *name, const char *title,)"; // Insert list of input arguments unsigned int i ; @@ -496,22 +497,23 @@ bool RooClassFactory::makeClass(const char* baseName, const char* className, con } } - hf << " " << className << "(const " << className << "& other, const char* name=0) ;" << endl - << " virtual TObject* clone(const char* newname) const override { return new " << className << "(*this,newname); }" << endl - << " inline virtual ~" << className << "() { }" << endl - << endl ; + hf << R"( CLASS_NAME(CLASS_NAME const &other, const char *name=nullptr); + TObject* clone(const char *newname) const override { return new CLASS_NAME(*this, newname); } +)"; if (hasAnaInt) { - hf << " Int_t getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName=0) const ;" << endl - << " double analyticalIntegral(Int_t code, const char* rangeName=0) const ;" << endl - << "" << endl ; + hf << R"( + int getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char *rangeName=nullptr) const override; + double analyticalIntegral(int code, const char *rangeName=nullptr) const override; +)"; } if (hasIntGen) { - hf << " Int_t getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const;" << endl - << " void initGenerator(Int_t code) {} ; // optional pre-generation initialization" << endl - << " void generateEvent(Int_t code);" << endl - << endl ; + hf << R"( + int getGenerator(const RooArgSet& directVars, RooArgSet &generateVars, bool staticInitOK=true) const override; + void initGenerator(int code) override {} // optional pre-generation initialization + void generateEvent(int code) override; +)"; } hf << "protected:" << endl @@ -526,42 +528,42 @@ bool RooClassFactory::makeClass(const char* baseName, const char* className, con } } - hf << " " << endl - << " double evaluate() const override;" << endl - << "" << endl - << "private:" << endl - << "" << endl - << " ClassDefOverride(" << className << ",1) // Your description goes here..." << endl - << "};" << endl - << " " << endl - << "#endif" << endl ; + hf << R"( + double evaluate() const override; + void computeBatch(double* output, std::size_t size, RooFit::Detail::DataMap const&) const override; +private: - ofstream cf(impFileName) ; + ClassDefOverride(CLASS_NAME, 1) // Your description goes here... +}; - cf << "/***************************************************************************** " << endl - << " * Project: RooFit * " << endl - << " * * " << endl - << " * This code was autogenerated by RooClassFactory * " << endl - << " *****************************************************************************/ " << endl - << endl - << "// Your description goes here... " << endl - << endl +#endif // CLASS_NAME_h)"; - << "#include \"Riostream.h\" " << endl - << endl + std::stringstream cf; - << "#include \"" << className << ".h\" " << endl - << "#include \"RooAbsReal.h\" " << endl - << "#include \"RooAbsCategory.h\" " << endl - << "#include " << endl - << "#include \"TMath.h\" " << endl - << endl + cf << R"(/***************************************************************************** + * Project: RooFit * + * * + * This code was autogenerated by RooClassFactory * + *****************************************************************************/ - << "ClassImp(" << className << "); " << endl - << endl +// Your description goes here... + +#include "CLASS_NAME.h" - << " " << className << "::" << className << "(const char *name, const char *title, " << endl ; +#include +#include + +#include +#include + +#include +#include + +ClassImp(CLASS_NAME); + +CLASS_NAME::CLASS_NAME(const char *name, const char *title, +)"; // Insert list of proxy constructors for (i=0 ; i intExpr ; // Parse analytical integration expression if provided // Expected form is observable:expression,observable,observable:expression;[...] - if (intExpression && *intExpression) { - const size_t bufSize = strlen(intExpression)+1; + if (!intExpression.empty()) { + const std::size_t bufSize = intExpression.size()+1; std::vector buf(bufSize); - strlcpy(buf.data(),intExpression,bufSize) ; + strlcpy(buf.data(),intExpression.c_str(),bufSize) ; char* ptr = strtok(buf.data(),":") ; while(ptr) { intObs.push_back(ptr) ; - intExpr.push_back(strtok(0,";")) ; - ptr = strtok(0,":") ; + intExpr.push_back(strtok(nullptr,";")) ; + ptr = strtok(nullptr,":") ; } } - cf << " Int_t " << className << "::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const " << endl - << " { " << endl - << " // LIST HERE OVER WHICH VARIABLES ANALYTICAL INTEGRATION IS SUPPORTED, " << endl - << " // ASSIGN A NUMERIC CODE FOR EACH SUPPORTED (SET OF) PARAMETERS " << endl - << " // THE EXAMPLE BELOW ASSIGNS CODE 1 TO INTEGRATION OVER VARIABLE X" << endl - << " // YOU CAN ALSO IMPLEMENT MORE THAN ONE ANALYTICAL INTEGRAL BY REPEATING THE matchArgs " << endl - << " // EXPRESSION MULTIPLE TIMES" << endl - << endl ; - - if (intObs.size()>0) { - for (UInt_t ii=0 ; ii0) { - for (UInt_t ii=0 ; iiIsA()) ; - - } else { - - throw string(Form("RooClassFactory::ClassFacIFace::create() ERROR: Unknown meta-type %s requested",typeName)) ; - - } return string(instanceName) ; } diff --git a/roofit/roofitcore/src/RooCmdArg.cxx b/roofit/roofitcore/src/RooCmdArg.cxx index 5d42546cd2fe6..bef31bcd57e48 100644 --- a/roofit/roofitcore/src/RooCmdArg.cxx +++ b/roofit/roofitcore/src/RooCmdArg.cxx @@ -61,9 +61,9 @@ RooCmdArg::RooCmdArg() : TNamed("","") { _procSubArgs = false ; _prefixSubArgs = true ; - _c = 0 ; - _o[0] = 0 ; - _o[1] = 0 ; + _c = nullptr ; + _o[0] = nullptr ; + _o[1] = nullptr ; _i[0] = 0 ; _i[1] = 0 ; _d[0] = 0 ; @@ -89,7 +89,7 @@ RooCmdArg::RooCmdArg(const char* name, Int_t i1, Int_t i2, double d1, double d2, if (s3) _s[2] = s3 ; _o[0] = (TObject*) o1 ; _o[1] = (TObject*) o2 ; - _c = 0 ; + _c = nullptr ; if (c1||c2) _c = new RooArgSet[2] ; if (c1) _c[0].add(*c1) ; @@ -124,7 +124,7 @@ RooCmdArg::RooCmdArg(const RooCmdArg& other) : _c[0].add(other._c[0]) ; _c[1].add(other._c[1]) ; } else { - _c = 0 ; + _c = nullptr ; } _procSubArgs = other._procSubArgs ; @@ -197,7 +197,7 @@ void RooCmdArg::addArg(const RooCmdArg& arg) /// Return RooArgSet stored in slot idx const RooArgSet* RooCmdArg::getSet(Int_t idx) const { - return _c ? &_c[idx] : 0 ; + return _c ? &_c[idx] : nullptr ; } diff --git a/roofit/roofitcore/src/RooCmdConfig.cxx b/roofit/roofitcore/src/RooCmdConfig.cxx index 41ce398459ebd..32fe72d08df4b 100644 --- a/roofit/roofitcore/src/RooCmdConfig.cxx +++ b/roofit/roofitcore/src/RooCmdConfig.cxx @@ -56,7 +56,7 @@ ClassImp(RooCmdConfig); /// is used as prefix for any warning or error messages /// generated by this parser -RooCmdConfig::RooCmdConfig(const char* methodName) : +RooCmdConfig::RooCmdConfig(RooStringView methodName) : TObject(), _name(methodName) { @@ -139,10 +139,10 @@ void RooCmdConfig::defineDependency(const char* refArgName, const char* neededAr /// Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName /// Define default value for this int property to be defVal in case named argument is not processed -bool RooCmdConfig::defineInt(const char* name, const char* argName, Int_t intNum, Int_t defVal) +bool RooCmdConfig::defineInt(const char* name, const char* argName, int intNum, int defVal) { if (findVar(_iList, name) != _iList.end()) { - coutE(InputArguments) << "RooCmdConfig::defintInt: name '" << name << "' already defined" << endl ; + coutE(InputArguments) << "RooCmdConfig::defineInt: name '" << name << "' already defined" << endl ; return true ; } @@ -161,7 +161,7 @@ bool RooCmdConfig::defineInt(const char* name, const char* argName, Int_t intNum /// Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argName /// Define default value for this double property to be defVal in case named argument is not processed -bool RooCmdConfig::defineDouble(const char* name, const char* argName, Int_t doubleNum, double defVal) +bool RooCmdConfig::defineDouble(const char* name, const char* argName, int doubleNum, double defVal) { if (findVar(_dList, name) != _dList.end()) { coutE(InputArguments) << "RooCmdConfig::defineDouble: name '" << name << "' already defined" << endl ; @@ -185,7 +185,7 @@ bool RooCmdConfig::defineDouble(const char* name, const char* argName, Int_t dou /// If appendMode is true, values found in multiple matching RooCmdArg arguments will be concatenated /// in the output string. If it is false, only the value of the last processed instance is retained -bool RooCmdConfig::defineString(const char* name, const char* argName, Int_t stringNum, const char* defVal, bool appendMode) +bool RooCmdConfig::defineString(const char* name, const char* argName, int stringNum, const char* defVal, bool appendMode) { if (findVar(_sList, name) != _sList.end()) { coutE(InputArguments) << "RooCmdConfig::defineString: name '" << name << "' already defined" << endl ; @@ -210,7 +210,7 @@ bool RooCmdConfig::defineString(const char* name, const char* argName, Int_t str /// If isArray is true, an array of TObjects is harvested in case multiple matching named arguments are processed. /// If isArray is false, only the TObject in the last processed named argument is retained -bool RooCmdConfig::defineObject(const char* name, const char* argName, Int_t setNum, const TObject* defVal, bool isArray) +bool RooCmdConfig::defineObject(const char* name, const char* argName, int setNum, const TObject* defVal, bool isArray) { if (findVar(_oList, name) != _oList.end()) { @@ -236,7 +236,7 @@ bool RooCmdConfig::defineObject(const char* name, const char* argName, Int_t set /// If isArray is true, an array of TObjects is harvested in case multiple matching named arguments are processed. /// If isArray is false, only the TObject in the last processed named argument is retained -bool RooCmdConfig::defineSet(const char* name, const char* argName, Int_t setNum, const RooArgSet* defVal) +bool RooCmdConfig::defineSet(const char* name, const char* argName, int setNum, const RooArgSet* defVal) { if (findVar(_cList, name) != _cList.end()) { @@ -262,7 +262,7 @@ void RooCmdConfig::print() const { // Find registered integer fields for this opcode for(auto const& ri : _iList) { - cout << ri.name << "[Int_t] = " << ri.val << endl ; + cout << ri.name << "[int] = " << ri.val << endl ; } // Find registered double fields for this opcode @@ -309,7 +309,7 @@ bool RooCmdConfig::process(const RooLinkedList& argList) bool RooCmdConfig::process(const RooCmdArg& arg) { - // Retrive command code + // Retrieve command code const char* opc = arg.opcode() ; // Ignore empty commands @@ -358,7 +358,7 @@ bool RooCmdConfig::process(const RooCmdArg& arg) ri.val = arg.getInt(ri.num) ; anyField = true ; if (_verbose) { - cout << "RooCmdConfig::process " << ri.name << "[Int_t]" << " set to " << ri.val << endl ; + cout << "RooCmdConfig::process " << ri.name << "[int]" << " set to " << ri.val << endl ; } } } @@ -446,7 +446,7 @@ bool RooCmdConfig::process(const RooCmdArg& arg) bool depRet = false ; if (arg.procSubArgs()) { - for (Int_t ia=0 ; ia(arg.subArgs().At(ia)) ; if (strlen(subArg->GetName())>0) { RooCmdArg subArgCopy(*subArg) ; @@ -477,7 +477,7 @@ bool RooCmdConfig::hasProcessed(const char* cmdName) const /// Return integer property registered with name 'name'. If no /// property is registered, return defVal -Int_t RooCmdConfig::getInt(const char* name, Int_t defVal) +int RooCmdConfig::getInt(const char* name, int defVal) const { auto found = findVar(_iList, name); return found != _iList.end() ? found->val : defVal; @@ -489,7 +489,7 @@ Int_t RooCmdConfig::getInt(const char* name, Int_t defVal) /// Return double property registered with name 'name'. If no /// property is registered, return defVal -double RooCmdConfig::getDouble(const char* name, double defVal) +double RooCmdConfig::getDouble(const char* name, double defVal) const { auto found = findVar(_dList, name); return found != _dList.end() ? found->val : defVal; @@ -502,7 +502,7 @@ double RooCmdConfig::getDouble(const char* name, double defVal) /// property is registered, return defVal. If convEmptyToNull /// is true, empty string will be returned as null pointers -const char* RooCmdConfig::getString(const char* name, const char* defVal, bool convEmptyToNull) +const char* RooCmdConfig::getString(const char* name, const char* defVal, bool convEmptyToNull) const { auto found = findVar(_sList, name); if(found == _sList.end()) return defVal; @@ -515,7 +515,7 @@ const char* RooCmdConfig::getString(const char* name, const char* defVal, bool c /// Return TObject property registered with name 'name'. If no /// property is registered, return defVal -TObject* RooCmdConfig::getObject(const char* name, TObject* defVal) +TObject* RooCmdConfig::getObject(const char* name, TObject* defVal) const { auto found = findVar(_oList, name); return found != _oList.end() ? found->val.At(0) : defVal ; @@ -526,7 +526,7 @@ TObject* RooCmdConfig::getObject(const char* name, TObject* defVal) /// Return RooArgSet property registered with name 'name'. If no /// property is registered, return defVal -RooArgSet* RooCmdConfig::getSet(const char* name, RooArgSet* defVal) +RooArgSet* RooCmdConfig::getSet(const char* name, RooArgSet* defVal) const { auto found = findVar(_cList, name); return found != _cList.end() ? found->val : defVal ; @@ -537,7 +537,7 @@ RooArgSet* RooCmdConfig::getSet(const char* name, RooArgSet* defVal) //////////////////////////////////////////////////////////////////////////////// /// Return list of objects registered with name 'name' -const RooLinkedList& RooCmdConfig::getObjectList(const char* name) +const RooLinkedList& RooCmdConfig::getObjectList(const char* name) const { const static RooLinkedList defaultDummy ; auto found = findVar(_oList, name); diff --git a/roofit/roofitcore/src/RooCompositeDataStore.cxx b/roofit/roofitcore/src/RooCompositeDataStore.cxx index 724807011f463..dc604f1f95a07 100644 --- a/roofit/roofitcore/src/RooCompositeDataStore.cxx +++ b/roofit/roofitcore/src/RooCompositeDataStore.cxx @@ -225,7 +225,7 @@ const RooArgSet* RooCompositeDataStore::get(Int_t idx) const return &_vars ; } - return 0 ; + return nullptr ; } @@ -319,7 +319,7 @@ bool RooCompositeDataStore::changeObservableName(const char* from, const char* t RooAbsArg* RooCompositeDataStore::addColumn(RooAbsArg& newVar, bool adjustRange) { - RooAbsArg* ret(0) ; + RooAbsArg* ret(nullptr) ; for (auto const& item : _dataMap) { ret = item.second->addColumn(newVar,adjustRange) ; } @@ -470,9 +470,9 @@ void RooCompositeDataStore::dump() /// Get the weights of the events in the range [first, first+len). /// This implementation will fill a vector with every event retrieved one by one /// (even if the weight is constant). Then, it returns a span. -RooSpan RooCompositeDataStore::getWeightBatch(std::size_t first, std::size_t len) const { +std::span RooCompositeDataStore::getWeightBatch(std::size_t first, std::size_t len) const { if (!_weightBuffer) { - _weightBuffer.reset(new std::vector()); + _weightBuffer = std::make_unique>(); _weightBuffer->reserve(len); for (std::size_t i = 0; i < static_cast(numEntries()); ++i) { diff --git a/roofit/roofitcore/src/RooConstVar.cxx b/roofit/roofitcore/src/RooConstVar.cxx index 0abf7a471a96b..62b22e610ffe1 100644 --- a/roofit/roofitcore/src/RooConstVar.cxx +++ b/roofit/roofitcore/src/RooConstVar.cxx @@ -23,7 +23,7 @@ RooConstVar represent a constant real-valued object **/ #include "RooConstVar.h" -#include "RunContext.h" +#include "RooNumber.h" using namespace std; @@ -51,18 +51,6 @@ RooConstVar::RooConstVar(const RooConstVar& other, const char* name) : _fast = true; } - -//////////////////////////////////////////////////////////////////////////////// -/// Return batch with 1 constant element. -RooSpan RooConstVar::getValues(RooBatchCompute::RunContext& evalData, const RooArgSet*) const { - auto item = evalData.spans.find(this); - if (item == evalData.spans.end()) { - return evalData.spans[this] = {&_value, 1}; - } - - return evalData.spans[this]; -} - //////////////////////////////////////////////////////////////////////////////// /// Write object contents to stream @@ -71,3 +59,17 @@ void RooConstVar::writeToStream(ostream& os, bool /*compact*/) const os << _value ; } +//////////////////////////////////////////////////////////////////////////////// + +void RooConstVar::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // Just return a stringy-field version of the const value. + // Formats to the maximum precision. + constexpr auto max_precision{std::numeric_limits::digits10 + 1}; + std::stringstream ss; + ss.precision(max_precision); + // Just use toString to make sure we do not output 'inf'. + // This is really ugly for large numbers... + ss << std::fixed << RooNumber::toString(_value); + ctx.addResult(this, ss.str()); +} diff --git a/roofit/roofitcore/src/RooConstraintSum.cxx b/roofit/roofitcore/src/RooConstraintSum.cxx index df5b7490dbc73..943abe997c7e1 100644 --- a/roofit/roofitcore/src/RooConstraintSum.cxx +++ b/roofit/roofitcore/src/RooConstraintSum.cxx @@ -87,8 +87,12 @@ double RooConstraintSum::evaluate() const return sum; } +void RooConstraintSum::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + ctx.addResult(this, ctx.buildCall("RooFit::Detail::EvaluateFuncs::constraintSumEvaluate", _set1, _set1.size())); +} -void RooConstraintSum::computeBatch(cudaStream_t *, double *output, size_t /*size*/, +void RooConstraintSum::computeBatch(double *output, size_t /*size*/, RooFit::Detail::DataMap const &dataMap) const { double sum(0); @@ -100,9 +104,17 @@ void RooConstraintSum::computeBatch(cudaStream_t *, double *output, size_t /*siz output[0] = sum; } +std::unique_ptr RooConstraintSum::compileForNormSet(RooArgSet const & /*normSet*/, RooFit::Detail::CompileContext & ctx) const +{ + std::unique_ptr newArg{static_cast(this->Clone())}; + + for (const auto server : newArg->servers()) { + RooArgSet nset; + server->getObservables(&_paramSet, nset); + ctx.compileServer(*server, *newArg, nset); + } -std::unique_ptr RooConstraintSum::fillNormSetForServer(RooArgSet const& /*normSet*/, RooAbsArg const& /*server*/) const { - return std::make_unique(_paramSet); + return newArg; } diff --git a/roofit/roofitcore/src/RooConvCoefVar.cxx b/roofit/roofitcore/src/RooConvCoefVar.cxx index c1ac4c862b394..55549b4a1d948 100644 --- a/roofit/roofitcore/src/RooConvCoefVar.cxx +++ b/roofit/roofitcore/src/RooConvCoefVar.cxx @@ -19,10 +19,10 @@ \class RooConvCoefVar \ingroup Roofitcore -RooConvCoefVar is an auxilary class that represents the coefficient +RooConvCoefVar is an auxiliary class that represents the coefficient of a RooAbsAnaConvPdf implementation as a separate RooAbsReal object to be able to interface these coefficient terms with the generic -RooRealIntegral integration mechanism +RooRealIntegral integration mechanism. **/ #include "RooAbsAnaConvPdf.h" @@ -31,12 +31,11 @@ RooRealIntegral integration mechanism using namespace std; ClassImp(RooConvCoefVar); -; //////////////////////////////////////////////////////////////////////////////// -/// Constuctor given a RooAbsAnaConvPdf a coefficient index and a set with the -/// convoluted observable(s) +/// Constructor given a RooAbsAnaConvPdf a coefficient index and a set with the +/// convoluted observable(s). RooConvCoefVar::RooConvCoefVar(const char *name, const char *title, const RooAbsAnaConvPdf& input, Int_t coefIdx, const RooArgSet* varList) : diff --git a/roofit/roofitcore/src/RooConvGenContext.cxx b/roofit/roofitcore/src/RooConvGenContext.cxx index cb5cad7937b25..5cc1d3b3d7c95 100644 --- a/roofit/roofitcore/src/RooConvGenContext.cxx +++ b/roofit/roofitcore/src/RooConvGenContext.cxx @@ -64,7 +64,8 @@ RooConvGenContext::RooConvGenContext(const RooAbsAnaConvPdf &model, const RooArg << " for generation of observable(s) " << vars << endl ; // Clone PDF and change model to internal truth model - _pdfCloneSet.reset(RooArgSet(model).snapshot(true)); + _pdfCloneSet = std::make_unique(); + RooArgSet(model).snapshot(*_pdfCloneSet, true); if (!_pdfCloneSet) { coutE(Generation) << "RooConvGenContext::RooConvGenContext(" << GetName() << ") Couldn't deep-clone PDF, abort," << endl ; RooErrorHandler::softAbort() ; @@ -80,18 +81,18 @@ RooConvGenContext::RooConvGenContext(const RooAbsAnaConvPdf &model, const RooArg convV->removeRange(); // Create generator for physics X truth model - _pdfVars.reset(pdfClone->getObservables(&vars)); + _pdfVars = std::unique_ptr{pdfClone->getObservables(&vars)}; _pdfGen.reset(pdfClone->genContext(*_pdfVars,prototype,auxProto,verbose)); // Clone resolution model and use as normal PDF - _modelCloneSet.reset(RooArgSet(*model._convSet.at(0)).snapshot(true)); + _modelCloneSet = std::make_unique(); + RooArgSet(*model._convSet.at(0)).snapshot(*_modelCloneSet, true); if (!_modelCloneSet) { coutE(Generation) << "RooConvGenContext::RooConvGenContext(" << GetName() << ") Couldn't deep-clone resolution model, abort," << std::endl; RooErrorHandler::softAbort() ; } - auto modelClone = static_cast(_modelCloneSet->find(model._convSet.at(0)->GetName())->Clone("smearing")); - _modelCloneSet->addOwned(*modelClone) ; - modelClone->changeBasis(0) ; + std::unique_ptr modelClone{static_cast(_modelCloneSet->find(model._convSet.at(0)->GetName())->Clone("smearing"))}; + modelClone->changeBasis(nullptr) ; convV = dynamic_cast(&modelClone->convVar()); if (!convV) { throw std::runtime_error("RooConvGenContext only works with convolution variables of type RooRealVar."); @@ -99,12 +100,14 @@ RooConvGenContext::RooConvGenContext(const RooAbsAnaConvPdf &model, const RooArg convV->removeRange(); // Create generator for resolution model as PDF - _modelVars.reset(modelClone->getObservables(&vars)); + _modelVars = std::unique_ptr{modelClone->getObservables(&vars)}; _modelVars->add(modelClone->convVar()) ; _convVarName = modelClone->convVar().GetName() ; _modelGen.reset(modelClone->genContext(*_modelVars,prototype,auxProto,verbose)); + _modelCloneSet->addOwned(std::move(modelClone)); + if (prototype) { _pdfVars->add(*prototype->get()) ; _modelVars->add(*prototype->get()) ; @@ -141,7 +144,8 @@ RooConvGenContext::RooConvGenContext(const RooNumConvPdf &model, const RooArgSet { RooArgSet clonedPdfObservables; model.conv().clonePdf().getObservables(&vars, clonedPdfObservables); - _pdfVarsOwned.reset(clonedPdfObservables.snapshot(true)); + _pdfVarsOwned = std::make_unique(); + clonedPdfObservables.snapshot(*_pdfVarsOwned, true); } _pdfVars = std::make_unique(*_pdfVarsOwned) ; _pdfGen.reset(static_cast(model.conv().clonePdf()).genContext(*_pdfVars,prototype,auxProto,verbose)); @@ -150,7 +154,8 @@ RooConvGenContext::RooConvGenContext(const RooNumConvPdf &model, const RooArgSet { RooArgSet clonedModelObservables; model.conv().cloneModel().getObservables(&vars, clonedModelObservables); - _modelVarsOwned.reset(clonedModelObservables.snapshot(true)); + _modelVarsOwned = std::make_unique(); + clonedModelObservables.snapshot(*_modelVarsOwned, true); } _modelVars = std::make_unique(*_modelVarsOwned) ; _convVarName = model.conv().cloneVar().GetName() ; @@ -187,24 +192,28 @@ RooConvGenContext::RooConvGenContext(const RooFFTConvPdf &model, const RooArgSet _convVarName = model._x.arg().GetName() ; // Create generator for physics model - _pdfCloneSet.reset(RooArgSet(model._pdf1.arg()).snapshot(true)); + _pdfCloneSet = std::make_unique(); + RooArgSet(model._pdf1.arg()).snapshot(*_pdfCloneSet, true); RooAbsPdf* pdfClone = (RooAbsPdf*) _pdfCloneSet->find(model._pdf1.arg().GetName()) ; RooRealVar* cvPdf = (RooRealVar*) _pdfCloneSet->find(model._x.arg().GetName()) ; cvPdf->removeRange() ; RooArgSet tmp1; pdfClone->getObservables(&vars, tmp1) ; - _pdfVarsOwned.reset(tmp1.snapshot(true)); + _pdfVarsOwned = std::make_unique(); + tmp1.snapshot(*_pdfVarsOwned, true); _pdfVars = std::make_unique(*_pdfVarsOwned) ; _pdfGen.reset(pdfClone->genContext(*_pdfVars,prototype,auxProto,verbose)); // Create generator for resolution model - _modelCloneSet.reset(RooArgSet(model._pdf2.arg()).snapshot(true)); + _modelCloneSet = std::make_unique(); + RooArgSet(model._pdf2.arg()).snapshot(*_modelCloneSet, true); RooAbsPdf* modelClone = (RooAbsPdf*) _modelCloneSet->find(model._pdf2.arg().GetName()) ; RooRealVar* cvModel = (RooRealVar*) _modelCloneSet->find(model._x.arg().GetName()) ; cvModel->removeRange() ; RooArgSet tmp2; modelClone->getObservables(&vars, tmp2) ; - _modelVarsOwned.reset(tmp2.snapshot(true)); + _modelVarsOwned = std::make_unique(); + tmp2.snapshot(*_modelVarsOwned, true); _modelVars = std::make_unique(*_modelVarsOwned) ; _modelGen.reset(modelClone->genContext(*_pdfVars,prototype,auxProto,verbose)); @@ -269,7 +278,7 @@ void RooConvGenContext::initGenerator(const RooArgSet &theEvent) void RooConvGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) { - while(1) { + while(true) { // Generate pdf and model data _modelGen->generateEvent(*_modelVars,remaining) ; diff --git a/roofit/roofitcore/src/RooConvIntegrandBinding.cxx b/roofit/roofitcore/src/RooConvIntegrandBinding.cxx index 4f48fb7e1c421..82f552a8b5fad 100644 --- a/roofit/roofitcore/src/RooConvIntegrandBinding.cxx +++ b/roofit/roofitcore/src/RooConvIntegrandBinding.cxx @@ -31,13 +31,10 @@ RooNumConvPdf #include "RooAbsRealLValue.h" #include "RooMsgService.h" -#include +#include using namespace std; -ClassImp(RooConvIntegrandBinding); -; - //////////////////////////////////////////////////////////////////////////////// @@ -45,7 +42,7 @@ RooConvIntegrandBinding::RooConvIntegrandBinding(const RooAbsReal& func, const R RooAbsReal& xprime, RooAbsReal& x, const RooArgSet* nset, bool clipInvalid) : - RooAbsFunc(2), _func(&func), _model(&model), _vars(0), _nset(nset), _clipInvalid(clipInvalid) + RooAbsFunc(2), _func(&func), _model(&model), _vars(nullptr), _nset(nset), _clipInvalid(clipInvalid) { // Constructor where func and model // @@ -67,21 +64,21 @@ RooConvIntegrandBinding::RooConvIntegrandBinding(const RooAbsReal& func, const R // allocate memory _vars= new RooAbsRealLValue*[2]; - if(0 == _vars) { + if(nullptr == _vars) { _valid= false; return; } // check that all of the arguments are real valued and store them _vars[0]= dynamic_cast(&xprime); - if(0 == _vars[0]) { + if(nullptr == _vars[0]) { oocoutE(&func,InputArguments) << "RooConvIntegrandBinding: cannot bind to "; xprime.Print("1"); _valid= false; } _vars[1]= dynamic_cast(&x); - if(0 == _vars[1]) { + if(nullptr == _vars[1]) { oocoutE(&func,InputArguments) << "RooConvIntegrandBinding: cannot bind to "; x.Print("1"); _valid= false; @@ -97,7 +94,7 @@ RooConvIntegrandBinding::RooConvIntegrandBinding(const RooAbsReal& func, const R RooConvIntegrandBinding::~RooConvIntegrandBinding() { - if(0 != _vars) delete[] _vars; + if(nullptr != _vars) delete[] _vars; } diff --git a/roofit/roofitcore/inc/RooConvIntegrandBinding.h b/roofit/roofitcore/src/RooConvIntegrandBinding.h similarity index 55% rename from roofit/roofitcore/inc/RooConvIntegrandBinding.h rename to roofit/roofitcore/src/RooConvIntegrandBinding.h index d86993fc370a7..10613fed87530 100644 --- a/roofit/roofitcore/inc/RooConvIntegrandBinding.h +++ b/roofit/roofitcore/src/RooConvIntegrandBinding.h @@ -22,34 +22,32 @@ class RooAbsRealLValue; class RooAbsReal; class RooArgSet; +// RooAbsFunc representation of convolution integrands class RooConvIntegrandBinding : public RooAbsFunc { public: - RooConvIntegrandBinding(const RooAbsReal& func, const RooAbsReal& model, - RooAbsReal& x, RooAbsReal& xprime, - const RooArgSet* nset=nullptr, bool clipInvalid=false); - ~RooConvIntegrandBinding() override; - - double operator()(const double xvector[]) const override; - double getMinLimit(UInt_t dimension) const override; - double getMaxLimit(UInt_t dimension) const override; - inline void setNormalizationSet(const RooArgSet* nset) { - // Use the supplied nset as normalization set for calls to func and model - _nset = nset ; - } + RooConvIntegrandBinding(const RooAbsReal &func, const RooAbsReal &model, RooAbsReal &x, RooAbsReal &xprime, + const RooArgSet *nset = nullptr, bool clipInvalid = false); + ~RooConvIntegrandBinding() override; + + double operator()(const double xvector[]) const override; + double getMinLimit(UInt_t dimension) const override; + double getMaxLimit(UInt_t dimension) const override; + inline void setNormalizationSet(const RooArgSet *nset) + { + // Use the supplied nset as normalization set for calls to func and model + _nset = nset; + } protected: - void loadValues(const double xvector[], bool clipInvalid=false) const; + void loadValues(const double xvector[], bool clipInvalid = false) const; - const RooAbsReal *_func; ///< Pointer to input function - const RooAbsReal *_model ; ///< Pointer to input resolution model + const RooAbsReal *_func; ///< Pointer to input function + const RooAbsReal *_model; ///< Pointer to input resolution model - RooAbsRealLValue **_vars; ///< Array of pointers to variables - const RooArgSet *_nset; ///< Normalization set to be used for function evaluations - mutable bool _xvecValid; ///< If true _xvec defines a valid point - bool _clipInvalid ; ///< If true, invalid x values are clipped into their valid range - - ClassDefOverride(RooConvIntegrandBinding,0) // RooAbsFunc representation of convolution integrands + RooAbsRealLValue **_vars; ///< Array of pointers to variables + const RooArgSet *_nset; ///< Normalization set to be used for function evaluations + mutable bool _xvecValid; ///< If true _xvec defines a valid point + bool _clipInvalid; ///< If true, invalid x values are clipped into their valid range }; #endif - diff --git a/roofit/roofitcore/src/RooCurve.cxx b/roofit/roofitcore/src/RooCurve.cxx index 0c9a6407aa846..30927a348bf8c 100644 --- a/roofit/roofitcore/src/RooCurve.cxx +++ b/roofit/roofitcore/src/RooCurve.cxx @@ -43,8 +43,9 @@ To retrieve a RooCurve from a RooPlot, use RooPlot::getCurve(). #include "RooRealVar.h" #include "RooRealIntegral.h" #include "RooRealBinding.h" -#include "RooScaledFunc.h" #include "RooMsgService.h" +#include "RooProduct.h" +#include "RooConstVar.h" #include "Riostream.h" #include "TMath.h" @@ -64,7 +65,7 @@ ClassImp(RooCurve); //////////////////////////////////////////////////////////////////////////////// /// Default constructor. -RooCurve::RooCurve() : _showProgress(false) +RooCurve::RooCurve() { initialize(); } @@ -108,29 +109,17 @@ RooCurve::RooCurve(const RooAbsReal &f, RooAbsRealLValue &x, double xlo, double } setYAxisLabel(title.Data()); - RooAbsFunc *funcPtr = 0; - RooAbsFunc *rawPtr = 0; - funcPtr= f.bindVars(x,normVars,true); - - // apply a scale factor if necessary - if(scaleFactor != 1) { - rawPtr= funcPtr; - funcPtr= new RooScaledFunc(*rawPtr,scaleFactor); - } - assert(0 != funcPtr); + RooProduct scaledFunc{"scaled_func", "scaled_func", {f, RooFit::RooConst(scaleFactor)}}; + std::unique_ptr funcPtr{scaledFunc.bindVars(x, normVars, true)}; // calculate the points to add to our curve - double prevYMax = getYAxisMax() ; if(xbins > 0){ // regular mode - use the sampling hint to decide where to evaluate the pdf - list* hint = f.plotSamplingHint(x,xlo,xhi) ; - addPoints(*funcPtr,xlo,xhi,xbins+1,prec,resolution,wmode,nEvalError,doEEVal,eeVal,hint); + std::unique_ptr> hint{f.plotSamplingHint(x,xlo,xhi)}; + addPoints(*funcPtr,xlo,xhi,xbins+1,prec,resolution,wmode,nEvalError,doEEVal,eeVal,hint.get()); if (_showProgress) { ccoutP(Plotting) << endl ; } - if (hint) { - delete hint ; - } } else { // if number of bins is set to <= 0, skip any interpolation and just evaluate the pdf at the bin centers // this is useful when plotting a pdf like a histogram @@ -142,10 +131,7 @@ RooCurve::RooCurve(const RooAbsReal &f, RooAbsRealLValue &x, double xlo, double } initialize(); - // cleanup - delete funcPtr; - if(rawPtr) delete rawPtr; - if (shiftToZero) shiftCurveToZero(prevYMax) ; + if (shiftToZero) shiftCurveToZero() ; // Adjust limits for (int i=0 ; imaxVal) maxVal=y ; - } - - // Second iteration, lower all points by minVal - for (i=1 ; iprevYMax) { - double newMax = maxVal - minVal ; - setYAxisLimits(getYAxisMin(), newMax::infinity(); + double maxVal = -std::numeric_limits::infinity(); + + // First iteration, find current lowest point + for (int i = 1; i < GetN() - 1; i++) { + double x; + double y; + GetPoint(i, x, y); + minVal = std::min(y, minVal); + maxVal = std::max(y, maxVal); + } + + // Second iteration, lower all points by minVal + for (int i = 1; i < GetN() - 1; i++) { + double x; + double y; + GetPoint(i, x, y); + SetPoint(i, x, y - minVal); + } + + setYAxisLimits(0, maxVal - minVal); } @@ -326,6 +299,7 @@ void RooCurve::addPoints(const RooAbsFunc &func, double xlo, double xhi, } double dx= (xhi-xlo)/(minPoints-1.); + const double epsilon = (xhi - xlo) * relativeXEpsilon();; std::vector yval(minPoints); // Get list of initial x values. If function provides sampling hint use that, @@ -342,7 +316,7 @@ void RooCurve::addPoints(const RooAbsFunc &func, double xlo, double xhi, for (unsigned int step=0; step < xval.size(); ++step) { double xx = xval[step]; if (step == static_cast(minPoints-1)) - xx -= 1e-15; + xx -= 1e-9 * dx; yval[step]= func(&xx); if (_showProgress) { @@ -396,7 +370,7 @@ void RooCurve::addPoints(const RooAbsFunc &func, double xlo, double xhi, // If precision is <0, no attempt at recursive interpolation is made addPoint(x2,yval[step]) ; } else { - addRange(func,x1,x2,yval[step-1],yval[step],prec*yrangeEst,minDx,numee,doEEVal,eeVal); + addRange(func,x1,x2,yval[step-1],yval[step],prec*yrangeEst,minDx,numee,doEEVal,eeVal,epsilon); } step++ ; } @@ -421,10 +395,10 @@ void RooCurve::addPoints(const RooAbsFunc &func, double xlo, double xhi, void RooCurve::addRange(const RooAbsFunc& func, double x1, double x2, double y1, double y2, double minDy, double minDx, - Int_t numee, bool doEEVal, double eeVal) + int numee, bool doEEVal, double eeVal, double epsilon) { // Explicitly skip empty ranges to eliminate point duplication - if (fabs(x2-x1)<1e-20) { + if (std::abs(x2-x1) <= epsilon) { return ; } @@ -449,10 +423,10 @@ void RooCurve::addRange(const RooAbsFunc& func, double x1, double x2, // test if the midpoint is sufficiently close to a straight line across this interval double dy= ymid - 0.5*(y1+y2); - if((xmid - x1 >= minDx) && fabs(dy)>0 && fabs(dy) >= minDy) { + if((xmid - x1 >= minDx) && std::abs(dy)>0 && std::abs(dy) >= minDy) { // fill in each subrange - addRange(func,x1,xmid,y1,ymid,minDy,minDx,numee,doEEVal,eeVal); - addRange(func,xmid,x2,ymid,y2,minDy,minDx,numee,doEEVal,eeVal); + addRange(func,x1,xmid,y1,ymid,minDy,minDx,numee,doEEVal,eeVal,epsilon); + addRange(func,xmid,x2,ymid,y2,minDy,minDx,numee,doEEVal,eeVal,epsilon); } else { // add the endpoint @@ -591,7 +565,7 @@ double RooCurve::chiSquare(const RooHist& hist, Int_t nFitParam) const } // Return chisq/nDOF - return chisq / (nbin-nFitParam) ; + return chisq.Sum() / (nbin-nFitParam) ; } @@ -671,8 +645,8 @@ Int_t RooCurve::findPoint(double xvalue, double tolerance) const Int_t ibest(-1) ; for (i=0 ; i(this)->GetPoint(ibest,xbest,ybest) ; // Handle trivial case of being dead on - if (fabs(xbest-xvalue)& variations, double Z) const { RooCurve* band = new RooCurve ; - band->SetName(Form("%s_errorband",GetName())) ; + band->SetName((std::string(GetName()) + "_errorband").c_str()); band->SetLineWidth(1) ; band->SetFillColor(kCyan) ; band->SetLineColor(kCyan) ; @@ -776,7 +750,7 @@ RooCurve* RooCurve::makeErrorBand(const vector& plusVar, const vector { RooCurve* band = new RooCurve ; - band->SetName(Form("%s_errorband",GetName())) ; + band->SetName((std::string(GetName()) + "_errorband").c_str()); band->SetLineWidth(1) ; band->SetFillColor(kCyan) ; band->SetLineColor(kCyan) ; @@ -897,7 +871,7 @@ bool RooCurve::isIdentical(const RooCurve& other, double tol, bool verbose) cons bool ret(true) ; for(Int_t i= 2; i < n-2; i++) { double yTest = interpolate(other.fX[i],1e-10) ; - double rdy = fabs(yTest-other.fY[i])/Yrange ; + double rdy = std::abs(yTest-other.fY[i])/Yrange ; if (rdy>tol) { ret = false; if(!verbose) continue; @@ -913,3 +887,37 @@ bool RooCurve::isIdentical(const RooCurve& other, double tol, bool verbose) cons } + +//////////////////////////////////////////////////////////////////////////////// +/// Returns sampling hints for a histogram with given boundaries. This helper +/// function is meant to be used by binned RooAbsReals to produce sampling +/// hints that are working well with RooFits plotting. + +std::list * +RooCurve::plotSamplingHintForBinBoundaries(std::span boundaries, double xlo, double xhi) +{ + auto hint = new std::list; + + // Make sure the difference between two points around a bin boundary is + // larger than the relative epsilon for which the RooCurve considers two + // points as the same. Otherwise, the points right of the bin boundary would + // be skipped. + const double delta = (xhi - xlo) * RooCurve::relativeXEpsilon(); + + // Sample points right next to the plot limits + hint->push_back(xlo + delta); + hint->push_back(xhi - delta); + + // Sample points very close to the left and right of the bin boundaries that + // are strictly in between the plot limits. + for (const double x : boundaries) { + if (x - xlo > delta && xhi - x > delta) { + hint->push_back(x - delta); + hint->push_back(x + delta); + } + } + + hint->sort(); + + return hint; +} diff --git a/roofit/roofitcore/src/RooCustomizer.cxx b/roofit/roofitcore/src/RooCustomizer.cxx index a390aab87408a..8f74ddc939816 100644 --- a/roofit/roofitcore/src/RooCustomizer.cxx +++ b/roofit/roofitcore/src/RooCustomizer.cxx @@ -24,7 +24,7 @@ * RooCustomizer supports two kinds of modifications: * * - replaceArg(leaf_arg, repl_arg): - * Replaces each occurence of leaf_arg with repl_arg in the composite pdf. + * Replaces each occurrence of leaf_arg with repl_arg in the composite pdf. * * - splitArg(split_arg): * Build multiple clones of the same prototype. Each @@ -252,12 +252,12 @@ RooCustomizer::RooCustomizer(const RooAbsArg& pdf, const char* name) : _owning(false), _name(name), _masterPdf((RooAbsArg*)&pdf), - _masterCat(0), + _masterCat(nullptr), _masterBranchList("masterBranchList"), _masterLeafList("masterLeafList"), _internalCloneBranchList("cloneBranchList"), - _cloneNodeListAll(0), - _cloneNodeListOwned(0) + _cloneNodeListAll(nullptr), + _cloneNodeListOwned(nullptr) { _cloneBranchList = &_internalCloneBranchList ; @@ -341,7 +341,7 @@ void RooCustomizer::splitArg(const RooAbsArg& arg, const RooAbsCategory& splitCa //////////////////////////////////////////////////////////////////////////////// -/// Replace any occurence of arg 'orig' with arg 'subst' +/// Replace any occurrence of arg 'orig' with arg 'subst' void RooCustomizer::replaceArg(const RooAbsArg& orig, const RooAbsArg& subst) { @@ -366,7 +366,7 @@ void RooCustomizer::replaceArg(const RooAbsArg& orig, const RooAbsArg& subst) RooAbsArg* RooCustomizer::build(bool verbose) { // Execute build - RooAbsArg* ret = doBuild(_name.Length()>0?_name.Data():0,verbose) ; + RooAbsArg* ret = doBuild(_name.Length()>0?_name.Data():nullptr,verbose) ; // Make root object own all cloned nodes @@ -404,14 +404,14 @@ RooAbsArg* RooCustomizer::build(const char* masterCatState, bool verbose) if (_sterile) { oocoutE(nullptr, InputArguments) << "RooCustomizer::build(" << _name << ") ERROR cannot use leaf spitting build() on this sterile customizer" << endl ; - return 0 ; + return nullptr ; } // Set masterCat to given state if (_masterCat->setLabel(masterCatState)) { oocoutE(nullptr, InputArguments) << "RooCustomizer::build(" << _masterPdf->GetName() << "): ERROR label '" << masterCatState << "' not defined for master splitting category " << _masterCat->GetName() << endl ; - return 0 ; + return nullptr ; } return doBuild(masterCatState,verbose) ; @@ -436,7 +436,7 @@ RooAbsArg* RooCustomizer::doBuild(const char* masterCatState, bool verbose) // cout << "loop over " << nodeList.getSize() << " nodes" << endl ; for (auto node : nodeList) { - RooAbsArg* theSplitArg = !_sterile?(RooAbsArg*) _splitArgList.FindObject(node->GetName()):0 ; + RooAbsArg* theSplitArg = !_sterile?(RooAbsArg*) _splitArgList.FindObject(node->GetName()):nullptr ; if (theSplitArg) { RooAbsCategory* splitCat = (RooAbsCategory*) _splitCatList.At(_splitArgList.IndexOf(theSplitArg)) ; if (verbose) { @@ -501,7 +501,7 @@ RooAbsArg* RooCustomizer::doBuild(const char* masterCatState, bool verbose) // Add to one-time use list and life-time use list clonedMasterNodes.add(*clone) ; if (_owning) { - _cloneNodeListOwned->addOwned(*clone) ; + _cloneNodeListOwned->addOwned(std::unique_ptr{clone}); } else { _cloneNodeListOwned->add(*clone) ; } @@ -565,7 +565,7 @@ RooAbsArg* RooCustomizer::doBuild(const char* masterCatState, bool verbose) } // Clone branches, changes their names - RooAbsArg* cloneTopPdf = 0; + RooAbsArg* cloneTopPdf = nullptr; RooArgSet clonedMasterBranches("clonedMasterBranches") ; for (auto branch : masterBranchesToBeCloned) { @@ -598,7 +598,7 @@ RooAbsArg* RooCustomizer::doBuild(const char* masterCatState, bool verbose) _cloneBranchList->add(clonedMasterBranches) ; } - // Reconnect cloned branches to each other and to cloned nodess + // Reconnect cloned branches to each other and to cloned nodes for (auto branch : clonedMasterBranches) { branch->redirectServers(clonedMasterBranches,false,true) ; branch->redirectServers(clonedMasterNodes,false,true) ; @@ -683,14 +683,14 @@ std::string CustIFace::create(RooFactoryWSTool& ft, const char* typeName, const } // Check that first arg exists as RooAbsArg - RooAbsArg* arg = ft.ws().arg(args[0].c_str()) ; + RooAbsArg* arg = ft.ws().arg(args[0]) ; if (!arg) { throw string(Form("RooCustomizer::CustIFace::create() ERROR: input RooAbsArg %s does not exist",args[0].c_str())) ; } // If name of new object is same as original, execute in sterile mode (i.e no suffixes attached), and rename original nodes in workspace upon import if (args[0]==instanceName) { - instanceName=0 ; + instanceName=nullptr ; } // Create a customizer @@ -705,7 +705,7 @@ std::string CustIFace::create(RooFactoryWSTool& ft, const char* typeName, const } *sep = 0 ; RooAbsArg* orig = ft.ws().arg(buf) ; - RooAbsArg* subst(0) ; + RooAbsArg* subst(nullptr) ; if (string(sep+1).find("$REMOVE")==0) { // Create a removal dummy ; @@ -721,7 +721,7 @@ std::string CustIFace::create(RooFactoryWSTool& ft, const char* typeName, const while(tok) { //cout << "$REMOVE is restricted to " << tok << endl ; subst->setAttribute(Form("REMOVE_FROM_%s",tok)) ; - tok = R__STRTOK_R(0,",)",&saveptr) ; + tok = R__STRTOK_R(nullptr,",)",&saveptr) ; } } else { // Otherwise mark as universal removal node @@ -757,7 +757,7 @@ std::string CustIFace::create(RooFactoryWSTool& ft, const char* typeName, const // Now import everything. What we didn't touch gets recycled, everything else was cloned here: ft.ws().import(cust.cloneBranchList(), RooFit::Silence(true), RooFit::RecycleConflictNodes(true), RooFit::NoRecursion(false)); } else { - ft.ws().import(cust.cloneBranchList(), RooFit::Silence(true), RooFit::RenameConflictNodes("orig",1), RooFit::NoRecursion(true)); + ft.ws().import(cust.cloneBranchList(), RooFit::Silence(true), RooFit::RenameConflictNodes("orig",true), RooFit::NoRecursion(true)); } return string(instanceName?instanceName:targ->GetName()) ; diff --git a/roofit/roofitcore/src/RooDLLSignificanceMCSModule.cxx b/roofit/roofitcore/src/RooDLLSignificanceMCSModule.cxx index e4386a6e5ac59..e9675181eb33d 100644 --- a/roofit/roofitcore/src/RooDLLSignificanceMCSModule.cxx +++ b/roofit/roofitcore/src/RooDLLSignificanceMCSModule.cxx @@ -55,7 +55,7 @@ ClassImp(RooDLLSignificanceMCSModule); RooDLLSignificanceMCSModule::RooDLLSignificanceMCSModule(const RooRealVar& param, double nullHypoValue) : RooAbsMCStudyModule(Form("RooDLLSignificanceMCSModule_%s",param.GetName()),Form("RooDLLSignificanceMCSModule_%s",param.GetName())), _parName(param.GetName()), - _data(0), _nll0h(0), _dll0h(0), _sig0h(0), _nullValue(nullHypoValue) + _data(nullptr), _nll0h(nullptr), _dll0h(nullptr), _sig0h(nullptr), _nullValue(nullHypoValue) { } @@ -68,7 +68,7 @@ RooDLLSignificanceMCSModule::RooDLLSignificanceMCSModule(const RooRealVar& param RooDLLSignificanceMCSModule::RooDLLSignificanceMCSModule(const char* parName, double nullHypoValue) : RooAbsMCStudyModule(Form("RooDLLSignificanceMCSModule_%s",parName),Form("RooDLLSignificanceMCSModule_%s",parName)), _parName(parName), - _data(0), _nll0h(0), _dll0h(0), _sig0h(0), _nullValue(nullHypoValue) + _data(nullptr), _nll0h(nullptr), _dll0h(nullptr), _sig0h(nullptr), _nullValue(nullHypoValue) { } @@ -80,7 +80,7 @@ RooDLLSignificanceMCSModule::RooDLLSignificanceMCSModule(const char* parName, do RooDLLSignificanceMCSModule::RooDLLSignificanceMCSModule(const RooDLLSignificanceMCSModule& other) : RooAbsMCStudyModule(other), _parName(other._parName), - _data(0), _nll0h(0), _dll0h(0), _sig0h(0), _nullValue(other._nullValue) + _data(nullptr), _nll0h(nullptr), _dll0h(nullptr), _sig0h(nullptr), _nullValue(other._nullValue) { } @@ -167,14 +167,14 @@ RooDataSet* RooDLLSignificanceMCSModule::finalizeRun() //////////////////////////////////////////////////////////////////////////////// /// Save likelihood from nominal fit, fix chosen parameter to its /// null hypothesis value and rerun fit Save difference in likelihood -/// and associated Gaussian significance in auxilary dataset +/// and associated Gaussian significance in auxiliary dataset bool RooDLLSignificanceMCSModule::processAfterFit(Int_t /*sampleNum*/) { RooRealVar* par = static_cast(fitParams()->find(_parName.c_str())) ; par->setVal(_nullValue) ; par->setConstant(true) ; - RooFitResult* frnull = refit() ; + std::unique_ptr frnull{refit()}; par->setConstant(false) ; _nll0h->setVal(frnull->minNll()) ; @@ -187,7 +187,5 @@ bool RooDLLSignificanceMCSModule::processAfterFit(Int_t /*sampleNum*/) _data->add(RooArgSet(*_nll0h,*_dll0h,*_sig0h)) ; - delete frnull ; - return true ; } diff --git a/roofit/roofitcore/src/RooDataHist.cxx b/roofit/roofitcore/src/RooDataHist.cxx index a3e66b9b2f23d..02fe5761d540a 100644 --- a/roofit/roofitcore/src/RooDataHist.cxx +++ b/roofit/roofitcore/src/RooDataHist.cxx @@ -63,9 +63,9 @@ See RooAbsData::plotOn(). #include "RooFormulaVar.h" #include "RooFormula.h" #include "RooUniformBinning.h" -#include "RooSpan.h" -#include "ROOT/StringUtils.hxx" +#include +#include #include "TAxis.h" #include "TH1.h" @@ -88,11 +88,12 @@ RooDataHist::RooDataHist() } -std::unique_ptr RooDataHist::makeDefaultDataStore(const char* name, const char* title, RooArgSet const& vars) +std::unique_ptr +RooDataHist::makeDefaultDataStore(RooStringView name, RooStringView title, RooArgSet const &vars) { - return RooAbsData::defaultStorageType == RooAbsData::Tree - ? static_cast>(std::make_unique(name, title, vars)) - : static_cast>(std::make_unique(name, title, vars)); + return RooAbsData::defaultStorageType == RooAbsData::Tree + ? static_cast>(std::make_unique(name, title, vars)) + : static_cast>(std::make_unique(name, title, vars)); } @@ -273,27 +274,23 @@ RooDataHist::RooDataHist(RooStringView name, RooStringView title, const RooArgLi RooDataHist::RooDataHist(RooStringView name, RooStringView title, const RooArgList& vars, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) : - RooAbsData(name,title,RooArgSet(vars,(RooAbsArg*)RooCmdConfig::decodeObjOnTheFly("RooDataHist::RooDataHist", "IndexCat",0,0,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8))) + RooAbsData(name,title,RooArgSet(vars,(RooAbsArg*)RooCmdConfig::decodeObjOnTheFly("RooDataHist::RooDataHist", "IndexCat",0,nullptr,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8))) { // Initialize datastore _dstore = makeDefaultDataStore(name, title, _vars); // Define configuration for this method - RooCmdConfig pc(Form("RooDataHist::ctor(%s)",GetName())) ; + RooCmdConfig pc("RooDataHist::ctor(" + std::string(GetName()) + ")"); pc.defineObject("impHist","ImportHisto",0) ; pc.defineInt("impDens","ImportHisto",0) ; pc.defineObject("indexCat","IndexCat",0) ; - pc.defineObject("impSliceHist","ImportHistoSlice",0,0,true) ; // array - pc.defineString("impSliceState","ImportHistoSlice",0,"",true) ; // array - pc.defineObject("impSliceDHist","ImportDataHistSlice",0,0,true) ; // array - pc.defineString("impSliceDState","ImportDataHistSlice",0,"",true) ; // array + pc.defineObject("impSliceData","ImportDataSlice",0,nullptr,true) ; // array + pc.defineString("impSliceState","ImportDataSlice",0,"",true) ; // array pc.defineDouble("weight","Weight",0,1) ; - pc.defineObject("dummy1","ImportDataHistSliceMany",0) ; - pc.defineObject("dummy2","ImportHistoSliceMany",0) ; - pc.defineSet("glObs","GlobalObservables",0,0) ; - pc.defineMutex("ImportHisto","ImportHistoSlice","ImportDataHistSlice") ; - pc.defineDependency("ImportHistoSlice","IndexCat") ; - pc.defineDependency("ImportDataHistSlice","IndexCat") ; + pc.defineObject("dummy1","ImportDataSliceMany",0) ; + pc.defineSet("glObs","GlobalObservables",0,nullptr) ; + pc.defineMutex("ImportHisto","ImportDataSlice"); + pc.defineDependency("ImportDataSlice","IndexCat") ; RooLinkedList l ; l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ; @@ -312,11 +309,9 @@ RooDataHist::RooDataHist(RooStringView name, RooStringView title, const RooArgLi TH1* impHist = static_cast(pc.getObject("impHist")) ; bool impDens = pc.getInt("impDens") ; double initWgt = pc.getDouble("weight") ; - const char* impSliceNames = pc.getString("impSliceState","",true) ; - const RooLinkedList& impSliceHistos = pc.getObjectList("impSliceHist") ; RooCategory* indexCat = static_cast(pc.getObject("indexCat")) ; - const char* impSliceDNames = pc.getString("impSliceDState","",true) ; - const RooLinkedList& impSliceDHistos = pc.getObjectList("impSliceDHist") ; + const char* impSliceNames = pc.getString("impSliceState","",true) ; + const RooLinkedList& impSliceHistos = pc.getObjectList("impSliceData") ; if (impHist) { @@ -327,29 +322,32 @@ RooDataHist::RooDataHist(RooStringView name, RooStringView title, const RooArgLi } else if (indexCat) { - if (!impSliceHistos.empty()) { - - // Initialize importing mapped set of TH1s + // Initialize importing mapped set of RooDataHists and TH1s + std::map dmap ; std::map hmap ; auto hiter = impSliceHistos.begin() ; - for (const auto& token : ROOT::Split(impSliceNames, ",")) { - auto histo = static_cast(*hiter); - assert(histo); - hmap[token] = histo; + for (const auto& token : ROOT::Split(impSliceNames, ",", /*skipEmpty=*/true)) { + if(auto dHist = dynamic_cast(*hiter)) { + dmap[token] = dHist; + } + if(auto hHist = dynamic_cast(*hiter)) { + hmap[token] = hHist; + } ++hiter; } - importTH1Set(vars,*indexCat,hmap,initWgt,false) ; - } else { - - // Initialize importing mapped set of RooDataHists - std::map dmap ; - auto hiter = impSliceDHistos.begin() ; - for (const auto& token : ROOT::Split(impSliceDNames, ",")) { - dmap[token] = static_cast(*hiter); - ++hiter; + if(!dmap.empty() && !hmap.empty()) { + std::stringstream errorMsgStream; + errorMsgStream << "RooDataHist::ctor(" << GetName() << ") ERROR: you can't import mix of TH1 and RooDataHist"; + const std::string errorMsg = errorMsgStream.str(); + coutE(InputArguments) << errorMsg << std::endl; + throw std::invalid_argument(errorMsg); + } + if (!dmap.empty()) { + importDHistSet(vars,*indexCat,dmap,initWgt); + } + if (!hmap.empty()) { + importTH1Set(vars,*indexCat,hmap,initWgt,false); } - importDHistSet(vars,*indexCat,dmap,initWgt) ; - } } else { @@ -383,8 +381,8 @@ void RooDataHist::importTH1(const RooArgList& vars, const TH1& histo, double wgt // Define x,y,z as 1st, 2nd and 3rd observable RooRealVar* xvar = (RooRealVar*) _vars.find(vars.at(0)->GetName()) ; - RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : 0 ) ; - RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : 0 ) ; + RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : nullptr ) ; + RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : nullptr ) ; // Transfer contents Int_t xmin(0),ymin(0),zmin(0) ; @@ -446,7 +444,7 @@ bool hasConsistentLayoutAndBinning(RooDataHist const& h1, RooDataHist const& h2) auto const& vars1 = *h1.get(); auto const& vars2 = *h2.get(); - // Check if numer of variables and names is consistent + // Check if number of variables and names is consistent if(!vars1.hasSameLayout(vars2)) { return false; } @@ -494,7 +492,7 @@ void RooDataHist::importTH1Set(const RooArgList& vars, RooCategory& indexCat, st { RooCategory* icat = (RooCategory*) _vars.find(indexCat.GetName()) ; - TH1* histo(0) ; + TH1* histo(nullptr) ; bool init(false) ; for (const auto& hiter : hmap) { // Store pointer to first histogram from which binning specification will be taken @@ -537,8 +535,8 @@ void RooDataHist::importTH1Set(const RooArgList& vars, RooCategory& indexCat, st // Define x,y,z as 1st, 2nd and 3rd observable RooRealVar* xvar = (RooRealVar*) _vars.find(vars.at(0)->GetName()) ; - RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : 0 ) ; - RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : 0 ) ; + RooRealVar* yvar = (RooRealVar*) (vars.at(1) ? _vars.find(vars.at(1)->GetName()) : nullptr ) ; + RooRealVar* zvar = (RooRealVar*) (vars.at(2) ? _vars.find(vars.at(2)->GetName()) : nullptr ) ; // Transfer contents Int_t xmin(0),ymin(0),zmin(0) ; @@ -558,7 +556,7 @@ void RooDataHist::importTH1Set(const RooArgList& vars, RooCategory& indexCat, st double avgBV = volume / numEntries() ; Int_t ic(0),ix(0),iy(0),iz(0) ; - for (ic=0 ; ic < icat->numBins(0) ; ic++) { + for (ic=0 ; ic < icat->numBins(nullptr) ; ic++) { icat->setBin(ic) ; histo = hmap[icat->getCurrentLabel()] ; for (ix=0 ; ix < xvar->getBins() ; ix++) { @@ -660,7 +658,7 @@ void RooDataHist::_adjustBinning(RooRealVar &theirVar, const TAxis &axis, const std::string ourVarName(ourVar->GetName() ? ourVar->GetName() : ""), ownName(GetName() ? GetName() : ""); // RooRealVar is derived from RooAbsRealLValue which is itself // derived from RooAbsReal and a virtual class RooAbsLValue - // supplying setter fuctions, check if ourVar is indeed derived + // supplying setter functions, check if ourVar is indeed derived // as real if (!dynamic_cast(ourVar)) { coutE(InputArguments) << "RooDataHist::adjustBinning(" << ownName << ") ERROR: dimension " << ourVarName @@ -684,7 +682,7 @@ void RooDataHist::_adjustBinning(RooRealVar &theirVar, const TAxis &axis, theirVar.setBinning(xbins); - if (true || fabs(xloAdj - xlo) > tolerance || fabs(xhiAdj - xhi) > tolerance) { + if (true || std::abs(xloAdj - xlo) > tolerance || std::abs(xhiAdj - xhi) > tolerance) { coutI(DataHandling) << "RooDataHist::adjustBinning(" << ownName << "): fit range of variable " << ourVarName << " expanded to nearest bin boundaries: [" << xlo << "," << xhi << "] --> [" << xloAdj << "," << xhiAdj << "]" @@ -708,7 +706,7 @@ void RooDataHist::_adjustBinning(RooRealVar &theirVar, const TAxis &axis, xbins.setRange(xloAdj, xhiAdj); theirVar.setRange(xloAdj, xhiAdj); - if (fabs(xloAdj - xlo) > tolerance || fabs(xhiAdj - xhi) > tolerance) { + if (std::abs(xloAdj - xlo) > tolerance || std::abs(xhiAdj - xhi) > tolerance) { coutI(DataHandling) << "RooDataHist::adjustBinning(" << ownName << "): fit range of variable " << ourVarName << " expanded to nearest bin boundaries: [" << xlo << "," << xhi << "] --> [" << xloAdj << "," << xhiAdj << "]" @@ -797,7 +795,7 @@ void RooDataHist::initialize(const char* binningName, bool fillTree) assert(lvarg); _lvvars.push_back(lvarg); - const RooAbsBinning* binning = lvarg->getBinningPtr(0); + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); _lvbins.emplace_back(binning ? binning->clone() : nullptr); } @@ -897,8 +895,8 @@ RooDataHist::RooDataHist(const RooDataHist& other, const char* newname) : auto lvarg = dynamic_cast(rvarg); assert(lvarg); _lvvars.push_back(lvarg); - const RooAbsBinning* binning = lvarg->getBinningPtr(0); - _lvbins.emplace_back(binning ? binning->clone() : 0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); + _lvbins.emplace_back(binning ? binning->clone() : nullptr) ; } registerWeightArraysToDataStore(); @@ -910,24 +908,24 @@ RooDataHist::RooDataHist(const RooDataHist& other, const char* newname) : //////////////////////////////////////////////////////////////////////////////// /// Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods -RooAbsData* RooDataHist::reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange, +std::unique_ptr RooDataHist::reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange, std::size_t nStart, std::size_t nStop) { checkInit() ; RooArgSet myVarSubset; _vars.selectCommon(varSubset, myVarSubset); - RooDataHist *rdh = new RooDataHist(GetName(), GetTitle(), myVarSubset); + auto rdh = std::make_unique(GetName(), GetTitle(), myVarSubset); - RooFormulaVar* cloneVar = 0; + RooFormulaVar* cloneVar = nullptr; std::unique_ptr tmp; if (cutVar) { + tmp = std::make_unique(); // Deep clone cutVar and attach clone to this dataset - tmp.reset(static_cast(RooArgSet(*cutVar).snapshot())); - if (!tmp) { + if (RooArgSet(*cutVar).snapshot(*tmp)) { coutE(DataHandling) << "RooDataHist::reduceEng(" << GetName() << ") Couldn't deep-clone cut variable, abort," << endl ; return nullptr; } - cloneVar = (RooFormulaVar*) tmp->find(*cutVar) ; + cloneVar = static_cast(tmp->find(*cutVar)); cloneVar->attachDataSet(*this) ; } @@ -988,8 +986,61 @@ Int_t RooDataHist::getIndex(const RooAbsCollection& coord, bool fast) const { return calcTreeIndex(coord, fast); } +std::string RooDataHist::declWeightArrayForCodeSquash(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, + bool correctForBinSize) const +{ + std::string weightName = ctx.makeValidVarName(klass->GetName()) + "_HistWeights"; + + std::string arrayDecl = "double " + weightName + "[" + std::to_string(_arrSize) + "] = {"; + for (Int_t i = 0; i < _arrSize; i++) { + arrayDecl += " " + std::to_string(_wgt[i]) + (correctForBinSize ? " / " + std::to_string(_binv[i]) : "") + ","; + } + arrayDecl.back() = ' '; + arrayDecl += "};\n"; + ctx.addToCodeBody(arrayDecl, true); + return weightName; +} + +std::string RooDataHist::calculateTreeIndexForCodeSquash(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, + const RooAbsCollection &coords, bool reverse) const +{ + assert(coords.size() == _vars.size()); + + std::string idxName = "idx_" + ctx.getTmpVarName(); + ctx.addToCodeBody(klass, "unsigned int " + idxName + " = 0;\n"); + int idxMult = 1; + + for (std::size_t i = 0; i < _vars.size(); ++i) { + + std::size_t iVar = reverse ? _vars.size() - 1 - i : i; + const RooAbsArg *internalVar = _vars[iVar]; + const RooAbsArg *theVar = coords[iVar]; + + const RooAbsBinning *binning = _lvbins[iVar].get(); + if (!binning) { + coutE(InputArguments) << "RooHistPdf::weight(" << GetName() + << ") ERROR: Code Squashing currently does not support category values." << std::endl; + return ""; + } else if (!dynamic_cast(binning)) { + coutE(InputArguments) << "RooHistPdf::weight(" << GetName() + << ") ERROR: Code Squashing currently only supports uniformly binned cases." + << std::endl; + return ""; + } + + std::string const &bin = ctx.buildCall("RooFit::Detail::EvaluateFuncs::getUniformBinning", binning->lowBound(), + binning->highBound(), *theVar, binning->numBins()); + ctx.addToCodeBody(klass, idxName + " += " + std::to_string(idxMult) + " * " + bin + ";\n"); + + // Use RooAbsLValue here because it also generalized to categories, which + // is useful in the future. dynamic_cast because it's a cross-cast. + idxMult *= dynamic_cast(internalVar)->numBins(); + } + + return idxName; +} //////////////////////////////////////////////////////////////////////////////// /// Calculate the bin index corresponding to the coordinates passed as argument. @@ -1092,13 +1143,13 @@ RooPlot *RooDataHist::plotOn(RooPlot *frame, PlotOpt o) const /// \param[in] xVals An array of event coordinates for which the weights should be /// calculated. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// Underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the /// interpolation. -void RooDataHist::interpolateQuadratic(double* output, RooSpan xVals, +void RooDataHist::interpolateQuadratic(double* output, std::span xVals, bool correctForBinSize, bool cdfBoundaries) { const std::size_t nBins = numEntries(); @@ -1199,13 +1250,13 @@ void RooDataHist::interpolateQuadratic(double* output, RooSpan xVa /// \param[in] xVals An array of event coordinates for which the weights should be /// calculated. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// Underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the /// interpolation. -void RooDataHist::interpolateLinear(double* output, RooSpan xVals, +void RooDataHist::interpolateLinear(double* output, std::span xVals, bool correctForBinSize, bool cdfBoundaries) { const std::size_t nBins = numEntries(); @@ -1287,13 +1338,13 @@ void RooDataHist::interpolateLinear(double* output, RooSpan xVals, /// calculated. /// \param[in] intOrder Interpolation order; 0th and 1st order are supported. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// Underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the /// interpolation. -void RooDataHist::weights(double* output, RooSpan xVals, int intOrder, bool correctForBinSize, bool cdfBoundaries) +void RooDataHist::weights(double* output, std::span xVals, int intOrder, bool correctForBinSize, bool cdfBoundaries) { auto const nEvents = xVals.size(); @@ -1335,7 +1386,7 @@ void RooDataHist::weights(double* output, RooSpan xVals, int intOr /// used for the interpolation. If zero, the bare weight for /// the bin enclosing the coordinatesis returned. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the @@ -1369,7 +1420,7 @@ double RooDataHist::weightFast(const RooArgSet& bin, Int_t intOrder, bool correc /// used for the interpolation. If zero, the bare weight for /// the bin enclosing the coordinatesis returned. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the @@ -1406,7 +1457,7 @@ double RooDataHist::weight(const RooArgSet& bin, Int_t intOrder, bool correctFor /// \param[in] intOrder Interpolation order, i.e. how many neighbouring bins are /// used for the interpolation. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the @@ -1519,11 +1570,11 @@ void RooDataHist::weightError(double& lo, double& hi, ErrorType etype) const switch (etype) { case Auto: - throw std::invalid_argument(Form("RooDataHist::weightError(%s) error type Auto not allowed here",GetName())) ; + throw std::invalid_argument("RooDataHist::weightError(" + std::string(GetName()) + ") error type Auto not allowed here"); break ; case Expected: - throw std::invalid_argument(Form("RooDataHist::weightError(%s) error type Expected not allowed here",GetName())) ; + throw std::invalid_argument("RooDataHist::weightError(" + std::string(GetName()) + ") error type Expected not allowed here"); break ; case Poisson: @@ -1574,7 +1625,7 @@ void RooDataHist::weightError(double& lo, double& hi, ErrorType etype) const /// \param[in] intOrder Interpolation order, i.e. how many neighbouring bins are /// used for the interpolation. /// \param[in] correctForBinSize Enable the inverse bin volume correction factor. -/// \param[in] cdfBoundaries Enable the special boundary coundition for a cdf: +/// \param[in] cdfBoundaries Enable the special boundary condition for a cdf: /// underflow bins are assumed to have weight zero and /// overflow bins have weight one. Otherwise, the /// histogram is mirrored at the boundaries for the @@ -1759,12 +1810,12 @@ void RooDataHist::add(const RooAbsData& dset, const RooFormulaVar* cutVar, doubl { checkInit() ; - RooFormulaVar* cloneVar = 0; + RooFormulaVar* cloneVar = nullptr; std::unique_ptr tmp; if (cutVar) { // Deep clone cutVar and attach clone to this dataset - tmp.reset(static_cast(RooArgSet(*cutVar).snapshot())); - if (!tmp) { + tmp = std::make_unique(); + if(RooArgSet(*cutVar).snapshot(*tmp)) { coutE(DataHandling) << "RooDataHist::add(" << GetName() << ") Couldn't deep-clone cut variable, abort," << endl ; return ; } @@ -1812,9 +1863,9 @@ double RooDataHist::sum(bool correctForBinSize, bool inverseBinCor) const // Store result in cache _cache_sum_valid = cache_code; - _cache_sum = kahanSum; + _cache_sum = kahanSum.Sum(); - return kahanSum; + return kahanSum.Sum(); } @@ -1849,7 +1900,7 @@ double RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet, bool pbinv = &calculatePartialBinVolume(sumSet); } - // Calculate mask and refence plot bins for non-iterating variables + // Calculate mask and reference plot bins for non-iterating variables std::vector mask(_vars.size()); std::vector refBin(_vars.size()); @@ -1888,7 +1939,7 @@ double RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet, bool _vars.assign(varSave) ; - return total; + return total.Sum(); } //////////////////////////////////////////////////////////////////////////////// @@ -1962,7 +2013,7 @@ double RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet, if (skip) continue; // Work out bin volume - // It's not necessary to figure out the bin volume for the slice-only set explicitely here. + // It's not necessary to figure out the bin volume for the slice-only set explicitly here. // We need to loop over the sumSet anyway to get the partial bin containment correction, // so we can get the slice-only set volume later by dividing _binv[ibin] / binVolumeSumSetFull. double binVolumeSumSetFull = 1.; @@ -1997,7 +2048,7 @@ double RooDataHist::sum(const RooArgSet& sumSet, const RooArgSet& sliceSet, _vars.assign(varSave); - return total; + return total.Sum(); } @@ -2055,7 +2106,7 @@ const std::vector& RooDataHist::calculatePartialBinVolume(const RooArgSe //////////////////////////////////////////////////////////////////////////////// /// Sum the weights of all bins. double RooDataHist::sumEntries() const { - return ROOT::Math::KahanSum::Accumulate(_wgt, _wgt + _arrSize); + return ROOT::Math::KahanSum::Accumulate(_wgt, _wgt + _arrSize).Sum(); } @@ -2069,7 +2120,7 @@ double RooDataHist::sumEntries(const char* cutSpec, const char* cutRange) const { checkInit() ; - if (cutSpec==0 && cutRange==0) { + if (cutSpec==nullptr && cutRange==nullptr) { return sumEntries(); } else { @@ -2089,7 +2140,7 @@ double RooDataHist::sumEntries(const char* cutSpec, const char* cutRange) const kahanSum += weight(i); } - return kahanSum; + return kahanSum.Sum(); } } @@ -2161,7 +2212,7 @@ TIterator* RooDataHist::sliceIterator(RooAbsArg& sliceArg, const RooArgSet& othe RooAbsArg* intArg = _vars.find(sliceArg) ; if (!intArg) { coutE(InputArguments) << "RooDataHist::sliceIterator() variable " << sliceArg.GetName() << " is not part of this RooDataHist" << endl ; - return 0 ; + return nullptr ; } return new RooDataHistSliceIter(*this,*intArg) ; } @@ -2228,7 +2279,7 @@ bool RooDataHist::isNonPoissonWeighted() const for (Int_t i=0; i < _arrSize; ++i) { const double wgt = _wgt[i]; double intpart; - if (fabs(std::modf(wgt, &intpart)) > 1.E-10) + if (std::abs(std::modf(wgt, &intpart)) > 1.E-10) return true; } @@ -2281,7 +2332,7 @@ void RooDataHist::Streamer(TBuffer &R__b) { if (R__v > 2) { R__b.ReadClassBuffer(RooDataHist::Class(),this,R__v,R__s,R__c); R__b.CheckByteCount(R__s, R__c, RooDataHist::IsA()); - initialize(0, false); + initialize(nullptr, false); } else { // Legacy dataset conversion happens here. Legacy RooDataHist inherits from RooTreeData @@ -2294,7 +2345,7 @@ void RooDataHist::Streamer(TBuffer &R__b) { Version_t R__v1 = R__b.ReadVersion(&R__s1, &R__c1); if (R__v1) { } RooAbsData::Streamer(R__b); - TTree* X_tree(0) ; R__b >> X_tree; + TTree* X_tree(nullptr) ; R__b >> X_tree; RooArgSet X_truth ; X_truth.Streamer(R__b); TString X_blindString ; X_blindString.Streamer(R__b); R__b.CheckByteCount(R__s1, R__c1, TClass::GetClass("RooTreeData")); @@ -2344,7 +2395,7 @@ void RooDataHist::Streamer(TBuffer &R__b) { //////////////////////////////////////////////////////////////////////////////// /// Return event weights of all events in range [first, first+len). /// If cacheValidEntries() has been called, out-of-range events will have a weight of 0. -RooSpan RooDataHist::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const { +std::span RooDataHist::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const { return {(sumW2 && _sumw2 ? _sumw2 : _wgt) + first, len}; } diff --git a/roofit/roofitcore/src/RooDataHistSliceIter.cxx b/roofit/roofitcore/src/RooDataHistSliceIter.cxx index 1cfded5b4866d..12f562e371280 100644 --- a/roofit/roofitcore/src/RooDataHistSliceIter.cxx +++ b/roofit/roofitcore/src/RooDataHistSliceIter.cxx @@ -100,7 +100,7 @@ RooDataHistSliceIter::~RooDataHistSliceIter() const TCollection* RooDataHistSliceIter::GetCollection() const { - return 0 ; + return nullptr ; } @@ -112,7 +112,7 @@ const TCollection* RooDataHistSliceIter::GetCollection() const TObject* RooDataHistSliceIter::Next() { if (_curStep==_nStep) { - return 0 ; + return nullptr ; } // Select appropriate entry in RooDataHist diff --git a/roofit/roofitcore/src/RooDataProjBinding.cxx b/roofit/roofitcore/src/RooDataProjBinding.cxx index 5e199f9c3f958..32803cc267edb 100644 --- a/roofit/roofitcore/src/RooDataProjBinding.cxx +++ b/roofit/roofitcore/src/RooDataProjBinding.cxx @@ -54,8 +54,8 @@ ClassImp(RooDataProjBinding); RooDataProjBinding::RooDataProjBinding(const RooAbsReal &real, const RooAbsData& data, const RooArgSet &vars, const RooArgSet* nset) : - RooRealBinding(real,vars,0), _first(true), _real(&real), _data(&data), _nset(nset), - _superCat(0), _catTable(0) + RooRealBinding(real,vars,nullptr), _first(true), _real(&real), _data(&data), _nset(nset), + _superCat(nullptr), _catTable(nullptr) { // Determine if dataset contains only categories bool allCat(true) ; @@ -153,26 +153,3 @@ double RooDataProjBinding::operator()(const double xvector[]) const if (wgtSum==0) return 0 ; return result / wgtSum ; } - - -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate the function at the specified values of the dependents. -RooSpan RooDataProjBinding::getValues(std::vector> coordinates) const { - assert(isValid()); - - if (!_batchBuffer) - _batchBuffer.reset(new std::vector()); - _batchBuffer->resize(coordinates.front().size()); - - std::unique_ptr xVec( new double[coordinates.size()] ); - - for (std::size_t i=0; i < coordinates.front().size(); ++i) { - for (unsigned int dim=0; dim < coordinates.size(); ++dim) { - xVec.get()[dim] = coordinates[dim][i]; - } - - (*_batchBuffer)[i] = this->operator()(xVec.get()); - } - - return {*_batchBuffer}; -} diff --git a/roofit/roofitcore/src/RooDataSet.cxx b/roofit/roofitcore/src/RooDataSet.cxx index 68f759f522abf..638f98ca73b6d 100644 --- a/roofit/roofitcore/src/RooDataSet.cxx +++ b/roofit/roofitcore/src/RooDataSet.cxx @@ -88,6 +88,7 @@ the new `RooAbsData::uniqueId()`. #include "RooAbsReal.h" #include "Roo1DTable.h" #include "RooCategory.h" +#include "RooFormula.h" #include "RooFormulaVar.h" #include "RooArgList.h" #include "RooRealVar.h" @@ -180,14 +181,114 @@ void RooDataSet::operator delete (void* ptr) //////////////////////////////////////////////////////////////////////////////// /// Default constructor for persistence -RooDataSet::RooDataSet() : _wgtVar(0) +RooDataSet::RooDataSet() { - TRACE_CREATE + TRACE_CREATE; } +namespace { + +struct FinalizeVarsOutput { + RooArgSet finalVars; + std::unique_ptr weight; + std::string weightVarName; + RooArgSet errorSet; +}; + +FinalizeVarsOutput finalizeVars(RooArgSet const &vars, + RooAbsArg * indexCat, + const char* wgtVarName, + RooAbsData* impData, + RooLinkedList const &impSliceData, + RooArgSet * errorSet) +{ + FinalizeVarsOutput out; + out.finalVars.add(vars); + + // Gather all imported weighted datasets to infer the weight variable name + // and whether we need weight errors + std::vector weightedImpDatasets; + if(impData && impData->isWeighted()) weightedImpDatasets.push_back(impData); + for(auto * data : static_range_cast(impSliceData)) { + if(data->isWeighted()) { + weightedImpDatasets.push_back(data); + } + } + + bool needsWeightErrors = false; + + // Figure out if the weight needs to store errors + for(RooAbsData * data : weightedImpDatasets) { + if(dynamic_cast(data)) { + needsWeightErrors = true; + } + } + + if (indexCat) { + out.finalVars.add(*indexCat, true); + } + + out.weightVarName = wgtVarName ? wgtVarName : ""; + + if(out.weightVarName.empty()) { + // Even if no weight variable is specified, we want to have one if we are + // importing weighted datasets + for(RooAbsData * data : weightedImpDatasets) { + if(auto ds = dynamic_cast(data)) { + // If the imported data is a RooDataSet, we take over its weight variable name + out.weightVarName = ds->weightVar()->GetName(); + break; + } else { + out.weightVarName = RooFit::WeightVar().getString(0); // to get the default weight variable name + // Don't break here! The next imported data might be a RooDataSet, + // and in that case we want to take over its weight name instead of + // using the default one. + } + } + } + + // If the weight variable is required but is not in the set, create and add + // it on the fly + RooAbsArg * wgtVar = out.finalVars.find(out.weightVarName.c_str()); + if (!out.weightVarName.empty() && !wgtVar) { + const char* name = out.weightVarName.c_str(); + out.weight = std::make_unique(name, name, 1.0); + wgtVar = out.weight.get(); + out.finalVars.add(*out.weight); + } + + if(needsWeightErrors) { + out.errorSet.add(*wgtVar); + } + + // Combine the error set figured out by finalizeVars and the ones passed by the user + if(errorSet) out.errorSet.add(*errorSet, /*silent=*/true); + return out; +} + +// generating an unbinned dataset from a binned one +std::unique_ptr makeDataSetFromDataHist(RooDataHist const &hist) +{ + using namespace RooFit; + + RooCmdArg const& wgtVarCmdArg = RooFit::WeightVar(); + const char* wgtName = wgtVarCmdArg.getString(0); + // Instantiate weight variable here such that we can pass it to StoreError() + RooRealVar wgtVar{wgtName, wgtName, 1.0}; + + RooArgSet vars{*hist.get(), wgtVar}; + // We have to explicitly store the errors that are implied by the sum of weights squared. + auto data = std::make_unique(hist.GetName(), hist.GetTitle(), vars, wgtVarCmdArg, StoreError(wgtVar)); + for (int i = 0; i < hist.numEntries(); ++i) { + data->add(*hist.get(i), hist.weight(i), std::sqrt(hist.weightSquared(i))); + } + + return data; +} +} // namespace //////////////////////////////////////////////////////////////////////////////// /// Construct an unbinned dataset from a RooArgSet defining the dimensions of the data space. Optionally, data @@ -195,16 +296,16 @@ RooDataSet::RooDataSet() : _wgtVar(0) /// /// ///
    %RooCmdArg Effect -///
    Import(TTree*) Import contents of given TTree. Only braches of the TTree that have names +///
    Import(TTree*) Import contents of given TTree. Only branches of the TTree that have names /// corresponding to those of the RooAbsArgs that define the RooDataSet are /// imported. ///
    ImportFromFile(const char* fileName, const char* treeName) Import tree with given name from file with given name. -///
    Import(RooDataSet&) -/// Import contents of given RooDataSet. Only observables that are common with the definition of this dataset will be imported +///
    Import(RooAbsData&) +/// Import contents of given RooDataSet or RooDataHist. Only observables that are common with the definition of this dataset will be imported ///
    Index(RooCategory&) Prepare import of datasets into a N+1 dimensional RooDataSet /// where the extra discrete dimension labels the source of the imported histogram. -///
    Import(const char*, RooDataSet&) -/// Import a dataset to be associated with the given state name of the index category +///
    Import(const char*, RooAbsData&) +/// Import a RooDataSet or RooDataHist to be associated with the given state name of the index category /// specified in Index(). If the given state name is not yet defined in the index /// category it will be added on the fly. The import command can be specified multiple times. ///
    Link(const char*, RooDataSet&) Link contents of supplied RooDataSet to this dataset for given index category state name. @@ -212,8 +313,8 @@ RooDataSet::RooDataSet() : _wgtVar(0) /// of this dataset. Note that link is active for both reading and writing, so modifications /// to the aggregate dataset will also modify its components. Link() and Import() are mutually exclusive. ///
    OwnLinked() Take ownership of all linked datasets -///
    Import(map&) As above, but allows specification of many imports in a single operation -///
    Link(map&) As above, but allows specification of many links in a single operation +///
    Import(std::map&) As above, but allows specification of many imports in a single operation +///
    Link(std::map&) As above, but allows specification of many links in a single operation ///
    Cut(const char*)
    /// Cut(RooFormulaVar&) ///
    Apply the given cut specification when importing data @@ -230,17 +331,19 @@ RooDataSet::RooDataSet() : _wgtVar(0) RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& vars, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) : - RooAbsData(name,title,RooArgSet(vars,(RooAbsArg*)RooCmdConfig::decodeObjOnTheFly("RooDataSet::RooDataSet", "IndexCat",0,0,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8))) + RooAbsData(name,title,{}) { + TRACE_CREATE; + // Define configuration for this method - RooCmdConfig pc(Form("RooDataSet::ctor(%s)",GetName())) ; + RooCmdConfig pc("RooDataSet::ctor(" + std::string(GetName()) + ")"); pc.defineInt("ownLinked","OwnLinked",0) ; pc.defineObject("impTree","ImportTree",0) ; pc.defineObject("impData","ImportData",0) ; pc.defineObject("indexCat","IndexCat",0) ; - pc.defineObject("impSliceData","ImportDataSlice",0,0,true) ; // array + pc.defineObject("impSliceData","ImportDataSlice",0,nullptr,true) ; // array pc.defineString("impSliceState","ImportDataSlice",0,"",true) ; // array - pc.defineObject("lnkSliceData","LinkDataSlice",0,0,true) ; // array + pc.defineObject("lnkSliceData","LinkDataSlice",0,nullptr,true) ; // array pc.defineString("lnkSliceState","LinkDataSlice",0,"",true) ; // array pc.defineString("cutSpec","CutSpec",0,"") ; pc.defineObject("cutVar","CutVar",0) ; @@ -255,7 +358,7 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& pc.defineObject("dummy2","LinkDataSliceMany",0) ; pc.defineSet("errorSet","StoreError",0) ; pc.defineSet("asymErrSet","StoreAsymError",0) ; - pc.defineSet("glObs","GlobalObservables",0,0) ; + pc.defineSet("glObs","GlobalObservables",0,nullptr) ; pc.defineMutex("ImportTree","ImportData","ImportDataSlice","LinkDataSlice","ImportFromFile") ; pc.defineMutex("CutSpec","CutVar") ; pc.defineMutex("WeightVarName","WeightVar") ; @@ -273,15 +376,16 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& // Process & check varargs pc.process(l) ; if (!pc.ok(true)) { - assert(0) ; - return ; + const std::string errMsg = "Error in RooDataSet constructor: command argument list could not be processed"; + coutE(InputArguments) << errMsg << std::endl; + throw std::invalid_argument(errMsg); } if(pc.getSet("glObs")) setGlobalObservables(*pc.getSet("glObs")); // Extract relevant objects TTree* impTree = static_cast(pc.getObject("impTree")) ; - RooDataSet* impData = static_cast(pc.getObject("impData")) ; + auto impData = static_cast(pc.getObject("impData")) ; RooFormulaVar* cutVar = static_cast(pc.getObject("cutVar")) ; const char* cutSpec = pc.getString("cutSpec","",true) ; const char* cutRange = pc.getString("cutRange","",true) ; @@ -292,13 +396,25 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& const char* lnkSliceNames = pc.getString("lnkSliceState","",true) ; const RooLinkedList& lnkSliceData = pc.getObjectList("lnkSliceData") ; RooCategory* indexCat = static_cast(pc.getObject("indexCat")) ; - RooArgSet* errorSet = pc.getSet("errorSet") ; RooArgSet* asymErrorSet = pc.getSet("asymErrSet") ; const char* fname = pc.getString("fname") ; const char* tname = pc.getString("tname") ; Int_t ownLinked = pc.getInt("ownLinked") ; Int_t newWeight = pc.getInt("newWeight1") + pc.getInt("newWeight2") ; + // Lookup name of weight variable if it was specified by object reference + if(wgtVar) { + wgtVarName = wgtVar->GetName(); + } + + auto finalVarsInfo = finalizeVars(vars,indexCat,wgtVarName,impData,impSliceData, pc.getSet("errorSet")); + initializeVars(finalVarsInfo.finalVars); + if(!finalVarsInfo.weightVarName.empty()) { + wgtVarName = finalVarsInfo.weightVarName.c_str(); + } + + RooArgSet* errorSet = finalVarsInfo.errorSet.empty() ? nullptr : &finalVarsInfo.errorSet; + // Case 1 --- Link multiple dataset as slices if (lnkSliceNames) { @@ -311,24 +427,18 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& auto hiter = lnkSliceData.begin(); while (token) { hmap[token] = static_cast(*hiter); - token = strtok(0, ","); + token = strtok(nullptr, ","); ++hiter; } } - // Lookup name of weight variable if it was specified by object reference - if (wgtVar) { - // coverity[UNUSED_VALUE] - wgtVarName = wgtVar->GetName() ; - } - appendToDir(this,true) ; // Initialize RooDataSet with optional weight variable - initialize(0) ; + initialize(nullptr) ; map storeMap ; - RooCategory* icat = (RooCategory*) (indexCat ? _vars.find(indexCat->GetName()) : 0 ) ; + RooCategory* icat = (RooCategory*) (indexCat ? _vars.find(indexCat->GetName()) : nullptr ) ; if (!icat) { throw std::string("RooDataSet::RooDataSet() ERROR in constructor, cannot find index category") ; } @@ -353,18 +463,8 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& // Create composite datastore _dstore = std::make_unique(name,title,_vars,*icat,storeMap) ; - } else { - - if (wgtVar) { - wgtVarName = wgtVar->GetName() ; - } - - // Clone weight variable of imported dataset if we are not weighted - if (!wgtVar && !wgtVarName && impData && impData->_wgtVar) { - _wgtVar = (RooRealVar*) impData->_wgtVar->createFundamental() ; - _vars.addOwned(*_wgtVar) ; - wgtVarName = _wgtVar->GetName() ; - } + return; + } // Create empty datastore RooTreeDataStore* tstore = nullptr; @@ -383,7 +483,7 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& // Make import mapping if index category is specified - map hmap ; + std::map hmap ; if (indexCat) { auto hiter = impSliceData.begin() ; for (const auto& token : ROOT::Split(impSliceNames, ",")) { @@ -408,213 +508,71 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& } } - // Lookup name of weight variable if it was specified by object reference - if (wgtVar) { - wgtVarName = wgtVar->GetName() ; - } - - appendToDir(this,true) ; // Initialize RooDataSet with optional weight variable - if (wgtVarName && *wgtVarName) { - // Use the supplied weight column - initialize(wgtVarName) ; - - } else { - if (impData && impData->_wgtVar && vars.find(impData->_wgtVar->GetName())) { - - // Use the weight column of the source data set - initialize(impData->_wgtVar->GetName()) ; - - } else if (indexCat) { - - RooDataSet* firstDS = hmap.begin()->second ; - if (firstDS->_wgtVar && vars.find(firstDS->_wgtVar->GetName())) { - initialize(firstDS->_wgtVar->GetName()) ; - } else { - initialize(0) ; - } - } else { - initialize(0) ; + initialize(wgtVarName); + + // Import one or more datasets + std::unique_ptr cutVarTmp; + + if (indexCat) { + // Case 2 --- Import multiple RooDataSets as slices + loadValuesFromSlices(*indexCat, hmap, cutRange, cutVar, cutSpec); + } else if (impData) { + // Case 3 --- Import RooDataSet + std::unique_ptr impDataSet; + + // If we are importing a RooDataHist, first convert it to a RooDataSet + if(impData->InheritsFrom(RooDataHist::Class())) { + impDataSet = makeDataSetFromDataHist(static_cast(*impData)); + impData = impDataSet.get(); } - } - - // Import one or more datasets with a cut specification - if (cutSpec && *cutSpec) { - - // Create a RooFormulaVar cut from given cut expression - if (indexCat) { - - // Case 2a --- Import multiple RooDataSets as slices with cutspec - RooCategory* icat = (RooCategory*) _vars.find(indexCat->GetName()) ; - for (map::iterator hiter = hmap.begin() ; hiter!=hmap.end() ; ++hiter) { - // Define state labels in index category (both in provided indexCat and in internal copy in dataset) - if (!indexCat->hasLabel(hiter->first)) { - indexCat->defineType(hiter->first) ; - coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << hiter->first << "\" in index category " << indexCat->GetName() << endl ; - } - if (!icat->hasLabel(hiter->first)) { - icat->defineType(hiter->first) ; - } - icat->setLabel(hiter->first.c_str()) ; - - RooFormulaVar cutVarTmp(cutSpec,cutSpec,hiter->second->_vars) ; - _dstore->loadValues(hiter->second->store(),&cutVarTmp,cutRange) ; - } - - } else if (impData) { - - // Case 3a --- Import RooDataSet with cutspec - RooFormulaVar cutVarTmp(cutSpec,cutSpec,impData->_vars) ; - _dstore->loadValues(impData->store(),&cutVarTmp,cutRange); - } else if (impTree) { - - // Case 4a --- Import TTree from memory with cutspec - RooFormulaVar cutVarTmp(cutSpec,cutSpec,_vars) ; - if (tstore) { - tstore->loadValues(impTree,&cutVarTmp,cutRange); - } else { - RooTreeDataStore tmpstore(name,title,_vars,wgtVarName) ; - tmpstore.loadValues(impTree,&cutVarTmp,cutRange) ; - _dstore->append(tmpstore) ; - } - } else if (fname && strlen(fname)) { - - // Case 5a --- Import TTree from file with cutspec - std::unique_ptr f{TFile::Open(fname)}; - if (!f) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' cannot be opened or does not exist" << endl ; - throw string(Form("RooDataSet::ctor(%s) ERROR file %s cannot be opened or does not exist",GetName(),fname)) ; - } - TTree* t = dynamic_cast(f->Get(tname)) ; - if (!t) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' does not contain a TTree named '" << tname << "'" << endl ; - throw string(Form("RooDataSet::ctor(%s) ERROR file %s does not contain a TTree named %s",GetName(),fname,tname)) ; - } - RooFormulaVar cutVarTmp(cutSpec,cutSpec,_vars) ; - if (tstore) { - tstore->loadValues(t,&cutVarTmp,cutRange); - } else { - RooTreeDataStore tmpstore(name,title,_vars,wgtVarName) ; - tmpstore.loadValues(t,&cutVarTmp,cutRange) ; - _dstore->append(tmpstore) ; - } - f->Close() ; - + if (cutSpec) { + cutVarTmp = std::make_unique(cutSpec, cutSpec, *impData->get()); + cutVar = cutVarTmp.get(); } - - // Import one or more datasets with a cut formula - } else if (cutVar) { - - if (indexCat) { - - // Case 2b --- Import multiple RooDataSets as slices with cutvar - - RooCategory* icat = (RooCategory*) _vars.find(indexCat->GetName()) ; - for (map::iterator hiter = hmap.begin() ; hiter!=hmap.end() ; ++hiter) { - // Define state labels in index category (both in provided indexCat and in internal copy in dataset) - if (!indexCat->hasLabel(hiter->first)) { - indexCat->defineType(hiter->first) ; - coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << hiter->first << "\" in index category " << indexCat->GetName() << endl ; - } - if (!icat->hasLabel(hiter->first)) { - icat->defineType(hiter->first) ; - } - icat->setLabel(hiter->first.c_str()) ; - _dstore->loadValues(hiter->second->store(),cutVar,cutRange) ; - } - - - } else if (impData) { - // Case 3b --- Import RooDataSet with cutvar - _dstore->loadValues(impData->store(),cutVar,cutRange); - } else if (impTree) { - // Case 4b --- Import TTree from memory with cutvar - if (tstore) { - tstore->loadValues(impTree,cutVar,cutRange); - } else { - RooTreeDataStore tmpstore(name,title,_vars,wgtVarName) ; - tmpstore.loadValues(impTree,cutVar,cutRange) ; - _dstore->append(tmpstore) ; - } - } else if (fname && strlen(fname)) { - // Case 5b --- Import TTree from file with cutvar - std::unique_ptr f{TFile::Open(fname)}; - if (!f) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' cannot be opened or does not exist" << endl ; - throw string(Form("RooDataSet::ctor(%s) ERROR file %s cannot be opened or does not exist",GetName(),fname)) ; - } - TTree* t = dynamic_cast(f->Get(tname)) ; - if (!t) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' does not contain a TTree named '" << tname << "'" << endl ; - throw string(Form("RooDataSet::ctor(%s) ERROR file %s does not contain a TTree named %s",GetName(),fname,tname)) ; - } - if (tstore) { - tstore->loadValues(t,cutVar,cutRange); - } else { - RooTreeDataStore tmpstore(name,title,_vars,wgtVarName) ; - tmpstore.loadValues(t,cutVar,cutRange) ; - _dstore->append(tmpstore) ; - } - - f->Close() ; + _dstore->loadValues(impData->store(), cutVar, cutRange); + + } else if (impTree || (fname && strlen(fname))) { + // Case 4 --- Import TTree from memory / file + std::unique_ptr file; + + if (impTree == nullptr) { + file.reset(TFile::Open(fname)); + if (!file) { + std::stringstream ss; + ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname + << "' cannot be opened or does not exist"; + const std::string errMsg = ss.str(); + coutE(InputArguments) << errMsg << std::endl; + throw std::invalid_argument(errMsg); + } + + file->GetObject(tname, impTree); + if (!impTree) { + std::stringstream ss; + ss << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname + << "' does not contain a TTree named '" << tname << "'";; + const std::string errMsg = ss.str(); + coutE(InputArguments) << errMsg << std::endl; + throw std::invalid_argument(errMsg); + } } - // Import one or more datasets without cuts - } else { - - if (indexCat) { - - RooCategory* icat = (RooCategory*) _vars.find(indexCat->GetName()) ; - for (map::iterator hiter = hmap.begin() ; hiter!=hmap.end() ; ++hiter) { - // Define state labels in index category (both in provided indexCat and in internal copy in dataset) - if (!indexCat->hasLabel(hiter->first)) { - indexCat->defineType(hiter->first) ; - coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << hiter->first << "\" in index category " << indexCat->GetName() << endl ; - } - if (!icat->hasLabel(hiter->first)) { - icat->defineType(hiter->first) ; - } - icat->setLabel(hiter->first.c_str()) ; - // Case 2c --- Import multiple RooDataSets as slices - _dstore->loadValues(hiter->second->store(),0,cutRange) ; - } - - } else if (impData) { - // Case 3c --- Import RooDataSet - _dstore->loadValues(impData->store(),0,cutRange); - - } else if (impTree || (fname && strlen(fname))) { - // Case 4c --- Import TTree from memory / file - std::unique_ptr file; - - if (impTree == nullptr) { - file.reset(TFile::Open(fname)); - if (!file) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' cannot be opened or does not exist" << endl ; - throw std::invalid_argument(Form("RooDataSet::ctor(%s) ERROR file %s cannot be opened or does not exist",GetName(),fname)) ; - } - - file->GetObject(tname, impTree); - if (!impTree) { - coutE(InputArguments) << "RooDataSet::ctor(" << GetName() << ") ERROR file '" << fname << "' does not contain a TTree named '" << tname << "'" << endl ; - throw std::invalid_argument(Form("RooDataSet::ctor(%s) ERROR file %s does not contain a TTree named %s",GetName(),fname,tname)) ; - } - } - - if (tstore) { - tstore->loadValues(impTree,0,cutRange); - } else { - RooTreeDataStore tmpstore(name,title,_vars,wgtVarName) ; - tmpstore.loadValues(impTree,0,cutRange) ; - _dstore->append(tmpstore) ; - } + if (cutSpec) { + cutVarTmp = std::make_unique(cutSpec, cutSpec, _vars); + cutVar = cutVarTmp.get(); } - } - } - TRACE_CREATE + if (tstore) { + tstore->loadValues(impTree, cutVar, cutRange); + } else { + RooTreeDataStore tmpstore(name, title, _vars, wgtVarName); + tmpstore.loadValues(impTree, cutVar, cutRange); + _dstore->append(tmpstore); + } + } } @@ -622,17 +580,11 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& //////////////////////////////////////////////////////////////////////////////// /// Constructor of an empty data set from a RooArgSet defining the dimensions /// of the data space. +/// \deprecated Use the more explicit `RooDataSet(name, title, vars, RooFit::WeightVar(wgtVarName))`. -RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& vars, const char* wgtVarName) : - RooAbsData(name,title,vars) +RooDataSet::RooDataSet(RooStringView name, RooStringView title, const RooArgSet& vars, const char* wgtVarName) + : RooDataSet(name,title,vars, RooFit::WeightVar(wgtVarName)) { -// cout << "RooDataSet::ctor(" << this << ") storageType = " << ((defaultStorageType==Tree)?"Tree":"Vector") << endl ; - _dstore = defaultStorageType==Tree ? static_cast>(std::make_unique(name,title,_vars,wgtVarName)) : - static_cast>(std::make_unique(name,title,_vars,wgtVarName)) ; - - appendToDir(this,true) ; - initialize(wgtVarName) ; - TRACE_CREATE } @@ -685,10 +637,10 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, RooDataSet *dset // Use the weight column of the source data set initialize(dset->_wgtVar->GetName()) ; } else { - initialize(0) ; + initialize(nullptr); } } - TRACE_CREATE + TRACE_CREATE; } @@ -773,7 +725,7 @@ RooDataSet::RooDataSet(RooStringView name, RooStringView title, TTree* theTree, appendToDir(this,true) ; initialize(wgtVarName) ; - TRACE_CREATE + TRACE_CREATE; } @@ -785,65 +737,49 @@ RooDataSet::RooDataSet(RooDataSet const & other, const char* newname) : RooAbsData(other,newname), RooDirItem() { appendToDir(this,true) ; - initialize(other._wgtVar?other._wgtVar->GetName():0) ; - TRACE_CREATE -} - -//////////////////////////////////////////////////////////////////////////////// -/// Protected constructor for internal use only - -RooDataSet::RooDataSet(RooStringView name, RooStringView title, RooDataSet *dset, - const RooArgSet& vars, const RooFormulaVar* cutVar, const char* cutRange, - std::size_t nStart, std::size_t nStop) : - RooAbsData(name,title,vars) -{ - _dstore = dset->_dstore->reduce(name, title, _vars, cutVar, cutRange, nStart, nStop); - - _cachedVars.add(_dstore->cachedVars()); - - appendToDir(this, true); - initialize(dset->_wgtVar ? dset->_wgtVar->GetName() : 0); - TRACE_CREATE + initialize(other._wgtVar?other._wgtVar->GetName():nullptr); + TRACE_CREATE; } //////////////////////////////////////////////////////////////////////////////// -/// Helper function for constructor that adds optional weight variable to construct -/// total set of observables +/// Return an empty clone of this dataset. If vars is not null, only the variables in vars +/// are added to the definition of the empty clone -RooArgSet RooDataSet::addWgtVar(const RooArgSet& origVars, const RooAbsArg* wgtVar) +RooFit::OwningPtr RooDataSet::emptyClone(const char* newName, const char* newTitle, const RooArgSet* vars, const char* wgtVarName) const { - RooArgSet tmp(origVars) ; - if (wgtVar) tmp.add(*wgtVar) ; - return tmp ; -} + bool useOldWeight = _wgtVar && (wgtVarName == nullptr || strcmp(wgtVarName, _wgtVar->GetName()) == 0); + if(newName == nullptr) newName = GetName(); + if(newTitle == nullptr) newTitle = GetTitle(); + if(useOldWeight) wgtVarName = _wgtVar->GetName(); -//////////////////////////////////////////////////////////////////////////////// -/// Return an empty clone of this dataset. If vars is not null, only the variables in vars -/// are added to the definition of the empty clone + RooArgSet vars2; + if(vars == nullptr) { + vars2.add(_vars); + } else { + for(RooAbsArg *var : *vars) { + // We should take the variables from the original dataset if + // available, such that we can query the "StoreError" and + // "StoreAsymError" attributes. + auto varInData = _vars.find(*var); + vars2.add(varInData ? *varInData : *var); + } + // We also need to add the weight variable of the original dataset if + // it's not added yet, again to query the error attributes correctly. + if(useOldWeight && !vars2.find(wgtVarName)) vars2.add(*_wgtVar); + } -RooAbsData* RooDataSet::emptyClone(const char* newName, const char* newTitle, const RooArgSet* vars, const char* wgtVarName) const -{ - // If variables are given, be sure to include weight variable if it exists and is not included - RooArgSet vars2 ; - RooRealVar* tmpWgtVar = _wgtVar ; - if (wgtVarName && vars && !_wgtVar) { - tmpWgtVar = (RooRealVar*) vars->find(wgtVarName) ; - } + RooArgSet errorSet; + RooArgSet asymErrorSet; - if (vars) { - vars2.add(*vars) ; - if (_wgtVar && !vars2.find(_wgtVar->GetName())) { - vars2.add(*_wgtVar) ; - } - } else { - vars2.add(_vars) ; - } + for(RooAbsArg *var : vars2) { + if(var->getAttribute("StoreError")) errorSet.add(*var);; + if(var->getAttribute("StoreAsymError")) asymErrorSet.add(*var);; + } - RooDataSet* dset = new RooDataSet(newName?newName:GetName(),newTitle?newTitle:GetTitle(),vars2,tmpWgtVar?tmpWgtVar->GetName():0) ; - //if (_wgtVar) dset->setWeightVar(_wgtVar->GetName()) ; - return dset ; + using namespace RooFit; + return RooFit::Detail::owningPtr(std::make_unique(newName, newTitle, vars2, WeightVar(wgtVarName), StoreError(errorSet), StoreAsymError(asymErrorSet))); } @@ -856,7 +792,7 @@ void RooDataSet::initialize(const char* wgtVarName) { _varsNoWgt.removeAll() ; _varsNoWgt.add(_vars) ; - _wgtVar = 0 ; + _wgtVar = nullptr ; if (wgtVarName) { RooAbsArg* wgt = _varsNoWgt.find(wgtVarName) ; if (!wgt) { @@ -879,36 +815,40 @@ void RooDataSet::initialize(const char* wgtVarName) //////////////////////////////////////////////////////////////////////////////// /// Implementation of RooAbsData virtual method that drives the RooAbsData::reduce() methods -RooAbsData* RooDataSet::reduceEng(const RooArgSet& varSubset, const RooFormulaVar* cutVar, const char* cutRange, - std::size_t nStart, std::size_t nStop) +std::unique_ptr RooDataSet::reduceEng(const RooArgSet &varSubset, const RooFormulaVar *cutVar, + const char *cutRange, std::size_t nStart, std::size_t nStop) { - checkInit() ; - RooArgSet tmp(varSubset) ; - if (_wgtVar) { - tmp.add(*_wgtVar) ; - } + checkInit(); + RooArgSet tmp(varSubset); + if (_wgtVar) { + tmp.add(*_wgtVar); + } - if (!cutRange || strchr(cutRange,',')==0) { - return new RooDataSet(GetName(), GetTitle(), this, tmp, cutVar, cutRange, nStart, nStop) ; - } else { - // Composite case: multiple ranges - auto tokens = ROOT::Split(cutRange, ","); - if (RooHelpers::checkIfRangesOverlap(tmp, *this, tokens)) { - std::stringstream errMsg; - errMsg << "Error in RooAbsData::reduce! The ranges " << cutRange << " are overlapping!"; - throw std::runtime_error(errMsg.str()); - } - RooDataSet * out = nullptr; - for (const auto& token : tokens) { - if(!out) { - out = new RooDataSet(GetName(), GetTitle(), this, tmp, cutVar, token.c_str(), nStart, nStop); - } else { - RooDataSet appendedData{GetName(), GetTitle(), this, tmp, cutVar, token.c_str(), nStart, nStop}; - out->append(appendedData); + auto createEmptyClone = [&]() { return emptyClone(GetName(), GetTitle(), &tmp); }; + + std::unique_ptr out{createEmptyClone()}; + + if (!cutRange || strchr(cutRange, ',') == nullptr) { + auto &ds = static_cast(*out); + ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, cutRange, nStart, nStop); + ds._cachedVars.add(_dstore->cachedVars()); + } else { + // Composite case: multiple ranges + auto tokens = ROOT::Split(cutRange, ","); + if (RooHelpers::checkIfRangesOverlap(tmp, tokens)) { + std::stringstream errMsg; + errMsg << "Error in RooAbsData::reduce! The ranges " << cutRange << " are overlapping!"; + throw std::runtime_error(errMsg.str()); } - } - return out; - } + for (const auto &token : tokens) { + std::unique_ptr appendedData{createEmptyClone()}; + auto &ds = static_cast(*appendedData); + ds._dstore = _dstore->reduce(ds.GetName(), ds.GetTitle(), ds._vars, cutVar, token.c_str(), nStart, nStop); + ds._cachedVars.add(_dstore->cachedVars()); + static_cast(*out).append(ds); + } + } + return out; } @@ -919,7 +859,7 @@ RooAbsData* RooDataSet::reduceEng(const RooArgSet& varSubset, const RooFormulaVa RooDataSet::~RooDataSet() { removeFromDir(this) ; - TRACE_DESTROY + TRACE_DESTROY; } @@ -927,7 +867,7 @@ RooDataSet::~RooDataSet() //////////////////////////////////////////////////////////////////////////////// /// Return binned clone of this dataset -RooDataHist* RooDataSet::binnedClone(const char* newName, const char* newTitle) const +RooFit::OwningPtr RooDataSet::binnedClone(const char* newName, const char* newTitle) const { std::string title; std::string name; @@ -942,7 +882,7 @@ RooDataHist* RooDataSet::binnedClone(const char* newName, const char* newTitle) title = std::string(GetTitle()) + "_binned" ; } - return new RooDataHist(name,title,*get(),*this) ; + return RooFit::Detail::owningPtr(std::make_unique(name,title,*get(),*this)); } @@ -974,7 +914,7 @@ double RooDataSet::weightSquared() const //////////////////////////////////////////////////////////////////////////////// /// \see RooAbsData::getWeightBatch(). -RooSpan RooDataSet::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const { +std::span RooDataSet::getWeightBatch(std::size_t first, std::size_t len, bool sumW2 /*=false*/) const { std::size_t nEntries = this->numEntries(); // for the casting to std::size_t @@ -982,10 +922,10 @@ RooSpan RooDataSet::getWeightBatch(std::size_t first, std::size_t throw std::runtime_error("RooDataSet::getWeightBatch(): requested range not valid for dataset."); } - RooSpan allWeights = _dstore->getWeightBatch(0, numEntries()); + std::span allWeights = _dstore->getWeightBatch(0, numEntries()); if(allWeights.empty()) return {}; - if(!sumW2) return {std::cbegin(allWeights) + first, std::cbegin(allWeights) + first + len}; + if(!sumW2) return {&*(std::cbegin(allWeights) + first), len}; // Treat the sumW2 case with a result buffer, first reset buffer if the // number of entries doesn't match with the dataset anymore @@ -1001,7 +941,7 @@ RooSpan RooDataSet::getWeightBatch(std::size_t first, std::size_t } } - return RooSpan(_sumW2Buffer->begin() + first, _sumW2Buffer->begin() + first + len); + return std::span(&*(_sumW2Buffer->begin() + first), len); } @@ -1029,7 +969,7 @@ double RooDataSet::weightError(ErrorType etype) const const RooArgSet* RooDataSet::get(Int_t index) const { const RooArgSet* ret = RooAbsData::get(index) ; - return ret ? &_varsNoWgt : 0 ; + return ret ? &_varsNoWgt : nullptr ; } @@ -1094,7 +1034,7 @@ bool RooDataSet::isNonPoissonWeighted() const // Now examine individual weights for (int i=0 ; i1e-10) return true ; + if (std::abs(weight()-Int_t(weight()))>1e-10) return true ; } // If sum of weights is less than number of events there are negative (integer) weights if (sumEntries() 1.E-15 //Exception for standard wgt^2 errors, which need not be stored. + && std::abs(wgt*wgt - wgtError)/wgtError > 1.E-15 //Exception for standard wgt^2 errors, which need not be stored. && _errorMsgCount < 5 && !_wgtVar->getAttribute("StoreError")) { coutE(DataHandling) << "An event weight error was passed to the RooDataSet '" << GetName() << "', but the weight variable '" << _wgtVar->GetName() @@ -1319,7 +1259,7 @@ bool RooDataSet::merge(listdsetList) // Replace current data store with merged store _dstore.reset(mergedStore); - initialize(_wgtVar?_wgtVar->GetName():0) ; + initialize(_wgtVar?_wgtVar->GetName():nullptr) ; return false ; } @@ -1347,10 +1287,11 @@ void RooDataSet::append(RooDataSet& data) RooAbsArg* RooDataSet::addColumn(RooAbsArg& var, bool adjustRange) { checkInit() ; - RooAbsArg* ret = _dstore->addColumn(var,adjustRange) ; - _vars.addOwned(*ret) ; - initialize(_wgtVar?_wgtVar->GetName():0) ; - return ret ; + std::unique_ptr ret{_dstore->addColumn(var,adjustRange)}; + RooAbsArg* retPtr = ret.get(); + _vars.addOwned(std::move(ret)); + initialize(_wgtVar?_wgtVar->GetName():nullptr) ; + return retPtr; } @@ -1412,7 +1353,7 @@ RooPlot* RooDataSet::plotOnXY(RooPlot* frame, const RooCmdArg& arg1, const RooCm argList.Add((TObject*)&arg7) ; argList.Add((TObject*)&arg8) ; // Process named arguments - RooCmdConfig pc(Form("RooDataSet::plotOnXY(%s)",GetName())) ; + RooCmdConfig pc("RooDataSet::plotOnXY(" + std::string(GetName()) + ")"); pc.defineString("drawOption","DrawOption",0,"P") ; pc.defineString("histName","Name",0,"") ; pc.defineInt("lineColor","LineColor",0,-999) ; @@ -1425,8 +1366,8 @@ RooPlot* RooDataSet::plotOnXY(RooPlot* frame, const RooCmdArg& arg1, const RooCm pc.defineInt("fillStyle","FillStyle",0,-999) ; pc.defineInt("histInvisible","Invisible",0,0) ; pc.defineDouble("scaleFactor","Rescale",0,1.) ; - pc.defineObject("xvar","XVar",0,0) ; - pc.defineObject("yvar","YVar",0,0) ; + pc.defineObject("xvar","XVar",0,nullptr) ; + pc.defineObject("yvar","YVar",0,nullptr) ; // Process & check varargs @@ -1438,7 +1379,7 @@ RooPlot* RooDataSet::plotOnXY(RooPlot* frame, const RooCmdArg& arg1, const RooCm // Extract values from named arguments const char* drawOptions = pc.getString("drawOption") ; Int_t histInvisible = pc.getInt("histInvisible") ; - const char* histName = pc.getString("histName",0,true) ; + const char* histName = pc.getString("histName",nullptr,true) ; double scaleFactor = pc.getDouble("scaleFactor") ; RooRealVar* xvar = (RooRealVar*) _vars.find(frame->getPlotVar()->GetName()) ; @@ -1449,13 +1390,13 @@ RooPlot* RooDataSet::plotOnXY(RooPlot* frame, const RooCmdArg& arg1, const RooCm // Sanity check. XY plotting only applies to weighted datasets if no YVar is specified if (!_wgtVar && !yvar) { coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR: no YVar() argument specified and dataset is not weighted" << endl ; - return 0 ; + return nullptr ; } - RooRealVar* dataY = yvar ? (RooRealVar*) _vars.find(yvar->GetName()) : 0 ; + RooRealVar* dataY = yvar ? (RooRealVar*) _vars.find(yvar->GetName()) : nullptr ; if (yvar && !dataY) { coutE(InputArguments) << "RooDataSet::plotOnXY(" << GetName() << ") ERROR on YVar() argument, dataset does not contain a variable named " << yvar->GetName() << endl ; - return 0 ; + return nullptr ; } @@ -1464,7 +1405,7 @@ RooPlot* RooDataSet::plotOnXY(RooPlot* frame, const RooCmdArg& arg1, const RooCm if (histName) { graph->SetName(histName) ; } else { - graph->SetName(Form("hxy_%s",GetName())) ; + graph->SetName(("hxy_" + std::string(GetName())).c_str()); } for (int i=0 ; iIsA()!=RooCategory::Class()) { oocoutE(nullptr,DataHandling) << "RooDataSet::read: ERROR: variable list already contains" << "a non-RooCategory blindState member" << endl ; - return 0 ; + return nullptr ; } oocoutW(nullptr,DataHandling) << "RooDataSet::read: WARNING: recycling existing " << "blindState category in variable list" << endl ; @@ -1607,10 +1548,10 @@ RooDataSet *RooDataSet::read(const char *fileList, const RooArgList &varList, blindCat = (RooCategory*) data->_vars.find("blindState") ; // Find index category, if requested - RooCategory *indexCat = 0; + RooCategory *indexCat = nullptr; //RooCategory *indexCatOrig = 0; if (indexCatName) { - RooAbsArg* tmp = 0; + RooAbsArg* tmp = nullptr; tmp = data->_vars.find(indexCatName) ; if (!tmp) { oocoutE(data.get(),DataHandling) << "RooDataSet::read: no index category named " @@ -1659,7 +1600,7 @@ RooDataSet *RooDataSet::read(const char *fileList, const RooArgList &varList, if (indexCat->defineType(newLabel,fileSeqNum)) { oocoutE(data.get(), DataHandling) << "RooDataSet::read: Error, cannot register automatic type name " << newLabel << " in index category " << indexCat->GetName() << endl ; - return 0 ; + return nullptr ; } // Assign new category number indexCat->setIndex(fileSeqNum) ; @@ -1773,7 +1714,7 @@ bool RooDataSet::write(ostream & ofs) const { } if (ofs.fail()) { - coutW(DataHandling) << "RooDataSet::write(" << GetName() << "): WARNING error(s) have occured in writing" << endl ; + coutW(DataHandling) << "RooDataSet::write(" << GetName() << "): WARNING error(s) have occurred in writing" << endl ; } return ofs.fail() ; @@ -1881,7 +1822,7 @@ void RooDataSet::Streamer(TBuffer &R__b) Version_t R__v1 = R__b.ReadVersion(&R__s1, &R__c1); if (R__v1) { } RooAbsData::Streamer(R__b); - TTree* X_tree(0) ; R__b >> X_tree; + TTree* X_tree(nullptr) ; R__b >> X_tree; RooArgSet X_truth ; X_truth.Streamer(R__b); TString X_blindString ; X_blindString.Streamer(R__b); R__b.CheckByteCount(R__s1, R__c1, TClass::GetClass("RooTreeData")); @@ -1920,14 +1861,56 @@ void RooDataSet::convertToTreeStore() } -// Compile-time test if we can still use TStrings for the constructors of -// RooDataClasses, either for both name and title or for only one of them. namespace { + + // Compile-time test if we can still use TStrings for the constructors of + // RooDataClasses, either for both name and title or for only one of them. TString tstr = "tstr"; const char * cstr = "cstr"; RooRealVar x{"x", "x", 1.0}; RooArgSet vars{x}; - RooDataSet d1(tstr, tstr, vars, nullptr); - RooDataSet d2(tstr, cstr, vars, nullptr); - RooDataSet d3(cstr, tstr, vars, nullptr); + RooDataSet d1(tstr, tstr, vars); + RooDataSet d2(tstr, cstr, vars); + RooDataSet d3(cstr, tstr, vars); + +} // namespace + + +void RooDataSet::loadValuesFromSlices(RooCategory &indexCat, std::map const &slices, + const char *rangeName, RooFormulaVar const *cutVar, const char *cutSpec) +{ + + if (cutVar && cutSpec) { + throw std::invalid_argument("Only one of cutVar or cutSpec should be not a nullptr!"); + } + + auto &indexCatInData = *static_cast(_vars.find(indexCat.GetName())); + + for (auto const &item : slices) { + std::unique_ptr sliceDataSet; + RooAbsData* sliceData = item.second; + + // If we are importing a RooDataHist, first convert it to a RooDataSet + if(sliceData->InheritsFrom(RooDataHist::Class())) { + sliceDataSet = makeDataSetFromDataHist(static_cast(*sliceData)); + sliceData = sliceDataSet.get(); + } + + // Define state labels in index category (both in provided indexCat and in internal copy in dataset) + if (!indexCat.hasLabel(item.first)) { + indexCat.defineType(item.first); + coutI(InputArguments) << "RooDataSet::ctor(" << GetName() << ") defining state \"" << item.first + << "\" in index category " << indexCat.GetName() << std::endl; + } + if (!indexCatInData.hasLabel(item.first)) { + indexCatInData.defineType(item.first); + } + indexCatInData.setLabel(item.first.c_str()); + std::unique_ptr cutVarTmp; + if (cutSpec) { + cutVarTmp = std::make_unique(cutSpec, cutSpec, *sliceData->get()); + cutVar = cutVarTmp.get(); + } + _dstore->loadValues(sliceData->store(), cutVar, rangeName); + } } diff --git a/roofit/roofitcore/src/RooDataWeightedAverage.cxx b/roofit/roofitcore/src/RooDataWeightedAverage.cxx index baa95d1be248e..7f0c56c3005b2 100644 --- a/roofit/roofitcore/src/RooDataWeightedAverage.cxx +++ b/roofit/roofitcore/src/RooDataWeightedAverage.cxx @@ -23,16 +23,20 @@ Class RooDataWeightedAverage calculate a weighted average of a function or p.d.f given a dataset with observable values, i.e. DWA(f(x),D(x)) = sum_i f(x_i) where x_i is draw from D(i). This class is an implementation of RooAbsOptTestStatistics -can make use of the optimization and parallization infrastructure +can make use of the optimization and parallelization infrastructure of that base class. The main use of RooDataWeightedAverage is to calculate curves in RooPlots that are added with ProjWData() plot option. **/ +#define __ROOFIT_SUPPRESS_ROODATAWEIGHTEDAVERAGE_DEPRECATION_WARNING +// At least for building the implementation we have to suppress the deprecation warning +#include "RooDataWeightedAverage.h" +#undef __ROOFIT_SUPPRESS_ROODATAWEIGHTEDAVERAGE_DEPRECATION_WARNING + #include "Riostream.h" -#include "RooDataWeightedAverage.h" #include "RooAbsData.h" #include "RooAbsPdf.h" #include "RooCmdConfig.h" @@ -90,7 +94,7 @@ RooDataWeightedAverage::~RooDataWeightedAverage() //////////////////////////////////////////////////////////////////////////////// /// Return global normalization term by which raw (combined) test statistic should -/// be defined to obtain final test statistic. For a data weighted avarage this +/// be defined to obtain final test statistic. For a data weighted average this /// the sum of all weights double RooDataWeightedAverage::globalNormalization() const @@ -107,8 +111,6 @@ double RooDataWeightedAverage::evaluatePartition(std::size_t firstEvent, std::si { double result(0) ; - _dataClone->store()->recalculateCache( _projDeps, firstEvent, lastEvent, stepSize,false) ; - if (setNum()==0 && _showProgress) { ccoutP(Plotting) << "." ; cout.flush() ; @@ -126,6 +128,3 @@ double RooDataWeightedAverage::evaluatePartition(std::size_t firstEvent, std::si return result ; } - - - diff --git a/roofit/roofitcore/src/RooDerivative.cxx b/roofit/roofitcore/src/RooDerivative.cxx index 993e99b4ab7f0..f94a057bd77a1 100644 --- a/roofit/roofitcore/src/RooDerivative.cxx +++ b/roofit/roofitcore/src/RooDerivative.cxx @@ -25,7 +25,7 @@ derivator class. **/ #include "Riostream.h" -#include +#include #include "RooDerivative.h" #include "RooAbsReal.h" @@ -48,7 +48,7 @@ ClassImp(RooDerivative); //////////////////////////////////////////////////////////////////////////////// /// Default constructor -RooDerivative::RooDerivative() : _order(1), _eps(1e-7), _ftor(0), _rd(0) +RooDerivative::RooDerivative() : _order(1), _eps(1e-7), _ftor(nullptr), _rd(nullptr) { } @@ -63,8 +63,8 @@ RooDerivative::RooDerivative(const char* name, const char* title, RooAbsReal& fu _nset("nset","nset",this,false,false), _func("function","function",this,func), _x("x","x",this,x), - _ftor(0), - _rd(0) + _ftor(nullptr), + _rd(nullptr) { if (_order<0 || _order>3 ) { throw std::string(Form("RooDerivative::ctor(%s) ERROR, derivation order must be 1,2 or 3",name)) ; @@ -80,8 +80,8 @@ RooDerivative::RooDerivative(const char* name, const char* title, RooAbsReal& fu _nset("nset","nset",this,false,false), _func("function","function",this,func), _x("x","x",this,x), - _ftor(0), - _rd(0) + _ftor(nullptr), + _rd(nullptr) { if (_order<0 || _order>3) { throw std::string(Form("RooDerivative::ctor(%s) ERROR, derivation order must be 1,2 or 3",name)) ; @@ -100,8 +100,8 @@ RooDerivative::RooDerivative(const RooDerivative& other, const char* name) : _nset("nset",this,other._nset), _func("function",this,other._func), _x("x",this,other._x), - _ftor(0), - _rd(0) + _ftor(nullptr), + _rd(nullptr) { } @@ -146,7 +146,7 @@ bool RooDerivative::redirectServersHook(const RooAbsCollection& newServerList, b { delete _ftor ; delete _rd ; - _ftor = 0 ; - _rd = 0 ; + _ftor = nullptr ; + _rd = nullptr ; return RooAbsReal::redirectServersHook(newServerList, mustReplaceAll, nameChange, isRecursive); } diff --git a/roofit/roofitcore/src/RooDouble.cxx b/roofit/roofitcore/src/RooDouble.cxx index a17ebe8057de6..9eb19a2c3074d 100644 --- a/roofit/roofitcore/src/RooDouble.cxx +++ b/roofit/roofitcore/src/RooDouble.cxx @@ -29,8 +29,6 @@ value. using namespace std; ClassImp(RooDouble); -; - //////////////////////////////////////////////////////////////////////////////// @@ -43,7 +41,7 @@ RooDouble::RooDouble(double value) : TNamed(), _value(value) //////////////////////////////////////////////////////////////////////////////// /// Implement comparison to other TObjects that are also RooDouble -/// to faciliate sorting of RooDoubles in a ROOT container +/// to facilitate sorting of RooDoubles in a ROOT container. Int_t RooDouble::Compare(const TObject* other) const { diff --git a/roofit/roofitcore/src/RooEffGenContext.cxx b/roofit/roofitcore/src/RooEffGenContext.cxx index f8e2b601b9957..25d08709d7c3a 100644 --- a/roofit/roofitcore/src/RooEffGenContext.cxx +++ b/roofit/roofitcore/src/RooEffGenContext.cxx @@ -12,7 +12,6 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ - /** \file RooEffGenContext.cxx \class RooEffGenContext @@ -38,18 +37,16 @@ ClassImp(RooEffGenContext); //////////////////////////////////////////////////////////////////////////////// /// Constructor of generator context for RooEffProd products -RooEffGenContext::RooEffGenContext(const RooAbsPdf &model, - const RooAbsPdf& pdf, const RooAbsReal& eff, - const RooArgSet &vars, - const RooDataSet *prototype, const RooArgSet* auxProto, - bool verbose, const RooArgSet* /*forceDirect*/) : - RooAbsGenContext(model, vars, prototype, auxProto, verbose), _maxEff(0.) +RooEffGenContext::RooEffGenContext(const RooAbsPdf &model, const RooAbsPdf &pdf, const RooAbsReal &eff, + const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet *auxProto, + bool verbose, const RooArgSet * /*forceDirect*/) + : RooAbsGenContext(model, vars, prototype, auxProto, verbose), _maxEff(0.) { - RooArgSet x(eff,eff.GetName()); - _cloneSet = static_cast(x.snapshot(true)); - _eff = dynamic_cast(_cloneSet->find(eff.GetName())); + RooArgSet x(eff, eff.GetName()); + x.snapshot(_cloneSet, true); + _eff = dynamic_cast(_cloneSet.find(eff.GetName())); _generator = pdf.genContext(vars, prototype, auxProto, verbose); - _vars = static_cast(vars.snapshot(true)); + vars.snapshot(_vars, true); } //////////////////////////////////////////////////////////////////////////////// @@ -58,8 +55,6 @@ RooEffGenContext::RooEffGenContext(const RooAbsPdf &model, RooEffGenContext::~RooEffGenContext() { delete _generator; - delete _cloneSet; - delete _vars; } //////////////////////////////////////////////////////////////////////////////// @@ -71,11 +66,11 @@ void RooEffGenContext::initGenerator(const RooArgSet &theEvent) _generator->initGenerator(theEvent); // Check if PDF supports maximum finding - Int_t code = _eff->getMaxVal(*_vars); + Int_t code = _eff->getMaxVal(_vars); if (!code) { - _maxEff = 1.; + _maxEff = 1.; } else { - _maxEff = _eff->maxVal(code); + _maxEff = _eff->maxVal(code); } } @@ -89,9 +84,9 @@ void RooEffGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) while (true) { _generator->generateEvent(theEvent, remaining); double val = _eff->getVal(); - if (val > _maxEff && !_eff->getMaxVal(*_vars)) { + if (val > _maxEff && !_eff->getMaxVal(_vars)) { coutE(Generation) << ClassName() << "::" << GetName() - << ":generateEvent: value of efficiency is larger than assumed maximum of 1." << std::endl; + << ":generateEvent: value of efficiency is larger than assumed maximum of 1." << std::endl; continue; } if (val > RooRandom::uniform() * _maxEff) { @@ -99,3 +94,20 @@ void RooEffGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) } } } + +//////////////////////////////////////////////////////////////////////////////// +/// Detailed printing interface + +void RooEffGenContext::printMultiline(ostream &os, Int_t content, bool verbose, TString indent) const +{ + RooAbsGenContext::printMultiline(os, content, verbose, indent); + os << indent << "--- RooEffGenContext ---" << endl; + os << indent << "Using EFF "; + _eff->printStream(os, kName | kArgs | kClassName, kSingleLine, indent); + os << indent << "PDF generator" << endl; + + TString indent2(indent); + indent2.Append(" "); + + _generator->printMultiline(os, content, verbose, indent2); +} diff --git a/roofit/roofitcore/src/RooEllipse.cxx b/roofit/roofitcore/src/RooEllipse.cxx index 47435315bf0f5..fef4cc49d5963 100644 --- a/roofit/roofitcore/src/RooEllipse.cxx +++ b/roofit/roofitcore/src/RooEllipse.cxx @@ -29,7 +29,7 @@ an error contour. #include "Riostream.h" #include "TClass.h" -#include +#include using namespace std; diff --git a/roofit/roofitcore/src/RooErrorVar.cxx b/roofit/roofitcore/src/RooErrorVar.cxx index 37dc5763c091e..2752b3125737b 100644 --- a/roofit/roofitcore/src/RooErrorVar.cxx +++ b/roofit/roofitcore/src/RooErrorVar.cxx @@ -19,8 +19,8 @@ \class RooErrorVar \ingroup Roofitcore -RooErrorVar is an auxilary class that represents the error -of a RooRealVar as a seperate object. The main reason of +RooErrorVar is an auxiliary class that represents the error +of a RooRealVar as a separate object. The main reason of existence of this class is to facilitate the reuse of existing techniques to perform calculations that involve a RooRealVars error, such as calculating the pull value. @@ -114,7 +114,7 @@ const RooAbsBinning& RooErrorVar::getBinning(const char* name, bool verbose, boo RooAbsBinning& RooErrorVar::getBinning(const char* name, bool /*verbose*/, bool createOnTheFly) { // Return default (normalization) binning and range if no name is specified - if (name==0) { + if (name==nullptr) { return *_binning ; } @@ -225,7 +225,7 @@ void RooErrorVar::setMin(const char* name, double value) // Clip current value in window if it fell out if (!name) { double clipValue ; - if (!inRange(_value,0,&clipValue)) { + if (!inRange(_value,nullptr,&clipValue)) { setVal(clipValue) ; } } @@ -255,7 +255,7 @@ void RooErrorVar::setMax(const char* name, double value) // Clip current value in window if it fell out if (!name) { double clipValue ; - if (!inRange(_value,0,&clipValue)) { + if (!inRange(_value,nullptr,&clipValue)) { setVal(clipValue) ; } } diff --git a/roofit/roofitcore/src/RooEvaluatorWrapper.cxx b/roofit/roofitcore/src/RooEvaluatorWrapper.cxx new file mode 100644 index 0000000000000..5919de34a0f42 --- /dev/null +++ b/roofit/roofitcore/src/RooEvaluatorWrapper.cxx @@ -0,0 +1,88 @@ +/// \cond ROOFIT_INTERNAL + +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +/** +\internal +\file RooEvaluatorWrapper.cxx +\class RooEvaluatorWrapper +\ingroup Roofitcore + +Wraps a RooFit::Evaluator that evaluates a RooAbsReal back into a RooAbsReal. +**/ + +#include "RooEvaluatorWrapper.h" + +#include +#include +#include +#include +#include +#include "RooFit/BatchModeDataHelpers.h" +#include + +#include + +RooEvaluatorWrapper::RooEvaluatorWrapper(RooAbsReal &topNode, std::unique_ptr evaluator, + std::string const &rangeName, RooSimultaneous const *simPdf, + bool takeGlobalObservablesFromData) + : RooAbsReal{"RooEvaluatorWrapper", "RooEvaluatorWrapper"}, + _evaluator{std::move(evaluator)}, + _topNode("topNode", "top node", this, topNode), + _rangeName{rangeName}, + _simPdf{simPdf}, + _takeGlobalObservablesFromData{takeGlobalObservablesFromData} +{ +} + +RooEvaluatorWrapper::RooEvaluatorWrapper(const RooEvaluatorWrapper &other, const char *name) + : RooAbsReal{other, name}, + _evaluator{other._evaluator}, + _topNode("topNode", this, other._topNode), + _data{other._data}, + _rangeName{other._rangeName}, + _simPdf{other._simPdf}, + _takeGlobalObservablesFromData{other._takeGlobalObservablesFromData} +{ +} + +bool RooEvaluatorWrapper::getParameters(const RooArgSet *observables, RooArgSet &outputSet, + bool /*stripDisconnected*/) const +{ + outputSet.add(_evaluator->getParameters()); + if (observables) { + outputSet.remove(*observables); + } + // If we take the global observables as data, we have to return these as + // parameters instead of the parameters in the model. Otherwise, the + // constant parameters in the fit result that are global observables will + // not have the right values. + if (_takeGlobalObservablesFromData && _data->getGlobalObservables()) { + outputSet.replace(*_data->getGlobalObservables()); + } + return false; +} + +bool RooEvaluatorWrapper::setData(RooAbsData &data, bool /*cloneData*/) +{ + _data = &data; + std::stack>{}.swap(_vectorBuffers); + auto dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(*_data, _rangeName, _simPdf, /*skipZeroWeights=*/true, + _takeGlobalObservablesFromData, _vectorBuffers); + for (auto const &item : dataSpans) { + _evaluator->setInput(item.first->GetName(), item.second, false); + } + return true; +} + +/// \endcond diff --git a/roofit/roofitcore/src/RooEvaluatorWrapper.h b/roofit/roofitcore/src/RooEvaluatorWrapper.h new file mode 100644 index 0000000000000..ce26b50d708c6 --- /dev/null +++ b/roofit/roofitcore/src/RooEvaluatorWrapper.h @@ -0,0 +1,79 @@ +/// \cond ROOFIT_INTERNAL + +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_RooEvaluatorWrapper_h +#define RooFit_RooEvaluatorWrapper_h + +#include +#include "RooFit/Detail/DataMap.h" +#include +#include +#include +#include + +#include "RooFit/Detail/Buffers.h" + +#include +#include +#include + +class RooAbsArg; +class RooAbsCategory; +class RooSimultaneous; + +class RooEvaluatorWrapper final : public RooAbsReal { +public: + RooEvaluatorWrapper(RooAbsReal &topNode, std::unique_ptr evaluator, std::string const &rangeName, + RooSimultaneous const *simPdf, bool takeGlobalObservablesFromData); + + RooEvaluatorWrapper(const RooEvaluatorWrapper &other, const char *name = nullptr); + + TObject *clone(const char *newname) const override { return new RooEvaluatorWrapper(*this, newname); } + + double defaultErrorLevel() const override { return _topNode->defaultErrorLevel(); } + + bool getParameters(const RooArgSet *observables, RooArgSet &outputSet, bool stripDisconnected) const override; + + bool setData(RooAbsData &data, bool cloneData) override; + + double getValV(const RooArgSet *) const override { return evaluate(); } + + void applyWeightSquared(bool flag) override { _topNode->applyWeightSquared(flag); } + + void printMultiline(std::ostream &os, Int_t /*contents*/, bool /*verbose*/ = false, + TString /*indent*/ = "") const override + { + _evaluator->print(os); + } + + /// The RooFit::Evaluator is dealing with constant terms itself. + void constOptimizeTestStatistic(ConstOpCode /*opcode*/, bool /*doAlsoTrackingOpt*/) override {} + +protected: + double evaluate() const override { return _evaluator ? _evaluator->run()[0] : 0.0; } + +private: + std::shared_ptr _evaluator; + RooRealProxy _topNode; + RooAbsData *_data = nullptr; + RooArgSet _parameters; + std::string _rangeName; + RooSimultaneous const *_simPdf = nullptr; + const bool _takeGlobalObservablesFromData; + std::stack> _vectorBuffers; // used for preserving resources +}; + +#endif + +/// \endcond diff --git a/roofit/roofitcore/src/RooExpensiveObjectCache.cxx b/roofit/roofitcore/src/RooExpensiveObjectCache.cxx index 30d359cd60959..5e0bf0a55a6e3 100644 --- a/roofit/roofitcore/src/RooExpensiveObjectCache.cxx +++ b/roofit/roofitcore/src/RooExpensiveObjectCache.cxx @@ -96,7 +96,7 @@ const TObject* RooExpensiveObjectCache::retrieveObject(const char* name, TClass* // If no cache element found, return 0 ; if (!eo) { - return 0 ; + return nullptr ; } // If parameters also match, return payload ; @@ -104,7 +104,7 @@ const TObject* RooExpensiveObjectCache::retrieveObject(const char* name, TClass* return eo->payload() ; } - return 0 ; + return nullptr ; } @@ -119,7 +119,7 @@ const TObject* RooExpensiveObjectCache::getObj(Int_t uid) return iter->second->payload() ; } } - return 0 ; + return nullptr ; } @@ -172,7 +172,7 @@ void RooExpensiveObjectCache::clearAll() //////////////////////////////////////////////////////////////////////////////// -/// Construct ExpensiveObject oject for inPayLoad and store reference values +/// Construct ExpensiveObject object for inPayLoad and store reference values /// for all RooAbsReal and RooAbsCategory parameters in params. RooExpensiveObjectCache::ExpensiveObject::ExpensiveObject(Int_t uidIn, const char* inOwnerName, TObject& inPayload, RooArgSet const& params) @@ -237,7 +237,7 @@ bool RooExpensiveObjectCache::ExpensiveObject::matches(TClass* tc, const RooArgS for(RooAbsArg * arg : params) { RooAbsReal* real = dynamic_cast(arg) ; if (real) { - if (fabs(real->getVal()-_realRefParams[real->GetName()])>1e-12) { + if (std::abs(real->getVal()-_realRefParams[real->GetName()])>1e-12) { return false ; } } else { @@ -273,7 +273,7 @@ void RooExpensiveObjectCache::print() const void RooExpensiveObjectCache::ExpensiveObject::print() const { std::cout << _payload->ClassName() << "::" << _payload->GetName() ; - if (_realRefParams.size()>0 || _catRefParams.size()>0) { + if (!_realRefParams.empty() || !_catRefParams.empty()) { std::cout << " parameters=( " ; auto iter = _realRefParams.begin() ; while(iter!=_realRefParams.end()) { diff --git a/roofit/roofitcore/src/RooExtendPdf.cxx b/roofit/roofitcore/src/RooExtendPdf.cxx index 62ec65898dd36..209c0ee98305a 100644 --- a/roofit/roofitcore/src/RooExtendPdf.cxx +++ b/roofit/roofitcore/src/RooExtendPdf.cxx @@ -42,6 +42,9 @@ the nominal integration range \f$ \mathrm{normRegion}[x] \f$. #include "RooRealVar.h" #include "RooFormulaVar.h" #include "RooNameReg.h" +#include "RooConstVar.h" +#include "RooProduct.h" +#include "RooRatio.h" #include "RooMsgService.h" @@ -49,13 +52,10 @@ the nominal integration range \f$ \mathrm{normRegion}[x] \f$. using namespace std; ClassImp(RooExtendPdf); -; - -RooExtendPdf::RooExtendPdf() : _rangeName(0) -{ - // Default constructor -} +RooExtendPdf::RooExtendPdf(const char *name, const char *title, RooAbsPdf& pdf, + RooAbsReal& norm, const char* rangeName) + : RooExtendPdf{name, title, pdf, RooAbsReal::Ref{norm}, rangeName} {} /// Constructor. The ExtendPdf behaves identical to the supplied input pdf, /// but adds an extended likelihood term. expectedEvents() will return @@ -69,7 +69,7 @@ RooExtendPdf::RooExtendPdf() : _rangeName(0) /// \param[in] rangeName If given, the number of events denoted by `norm` is interpreted as /// the number of events in this range only RooExtendPdf::RooExtendPdf(const char *name, const char *title, RooAbsPdf& pdf, - RooAbsReal& norm, const char* rangeName) : + RooAbsReal::Ref norm, const char* rangeName) : RooAbsPdf(name,title), _pdf("pdf", "PDF", this, pdf), _n("n","Normalization",this,norm), @@ -93,13 +93,6 @@ RooExtendPdf::RooExtendPdf(const RooExtendPdf& other, const char* name) : } -RooExtendPdf::~RooExtendPdf() -{ - // Destructor - -} - - /// Return the number of expected events over the full range of all variables. /// `norm`, the variable set as normalisation constant in the constructor, /// will yield the number of events in the range set in the constructor. That is, the function returns @@ -126,11 +119,7 @@ double RooExtendPdf::expectedEvents(const RooArgSet* nset) const // Optionally multiply with fractional normalization if (_rangeName) { - double fracInt; - { - GlobalSelectComponentRAII globalSelComp(true); - fracInt = pdf.getNormObj(nset,nset,_rangeName)->getVal(); - } + double fracInt = pdf.getNormObj(nset,nset,_rangeName)->getVal(); if ( fracInt == 0. || _n == 0.) { @@ -139,10 +128,6 @@ double RooExtendPdf::expectedEvents(const RooArgSet* nset) const } nExp /= fracInt ; - - - // cout << "RooExtendPdf::expectedEvents(" << GetName() << ") fracInt = " << fracInt << " _n = " << _n << " nExpect = " << nExp << endl ; - } // Multiply with original Nexpected, if defined @@ -152,4 +137,45 @@ double RooExtendPdf::expectedEvents(const RooArgSet* nset) const } +std::unique_ptr RooExtendPdf::createExpectedEventsFunc(const RooArgSet *nset) const +{ + const RooAbsPdf& pdf = *_pdf; + + RooArgList prodList; + prodList.add(*_n); + + // Optionally multiply with fractional normalization + std::unique_ptr rangeFactor; + if (_rangeName) { + std::unique_ptr fracInteg{pdf.createIntegral(*nset, *nset, RooNameReg::str(_rangeName))}; + // Create one over integral term + auto rangeFactorName = std::string("one_over_") + fracInteg->GetName(); + rangeFactor = std::make_unique(rangeFactorName.c_str(), rangeFactorName.c_str(), RooFit::RooConst(1.0), *fracInteg); + rangeFactor->addOwnedComponents(std::move(fracInteg)); + prodList.add(*rangeFactor); + } + + // Multiply with original Nexpected, if defined + std::unique_ptr pdfExpectedEvents; + if (pdf.canBeExtended()) { + pdfExpectedEvents = pdf.createExpectedEventsFunc(nset); + prodList.add(*pdfExpectedEvents); + } + + auto name = std::string(GetName()) + "_expectedEvents"; + auto out = std::make_unique(name.c_str(), name.c_str(), prodList); + if(rangeFactor) { + out->addOwnedComponents(std::move(rangeFactor)); + } + if(pdfExpectedEvents) { + out->addOwnedComponents(std::move(pdfExpectedEvents)); + } + return out; +} + +void RooExtendPdf::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // Use the result of the underlying pdf. + ctx.addResult(this, ctx.getResult(_pdf)); +} diff --git a/roofit/roofitcore/src/RooExtendedBinding.cxx b/roofit/roofitcore/src/RooExtendedBinding.cxx index d0b675b387a48..a65507aa0baa3 100644 --- a/roofit/roofitcore/src/RooExtendedBinding.cxx +++ b/roofit/roofitcore/src/RooExtendedBinding.cxx @@ -33,7 +33,7 @@ ClassImp(RooExtendedBinding); double RooExtendedBinding::evaluate() const { // ENTER EXPRESSION IN TERMS OF VARIABLE ARGUMENTS HERE - return ((RooAbsPdf&)pdf.arg()).expectedEvents(0) ; + return ((RooAbsPdf&)pdf.arg()).expectedEvents(nullptr) ; } diff --git a/roofit/roofitcore/src/RooExtendedTerm.cxx b/roofit/roofitcore/src/RooExtendedTerm.cxx index e43933677144a..fb498354b1aa1 100644 --- a/roofit/roofitcore/src/RooExtendedTerm.cxx +++ b/roofit/roofitcore/src/RooExtendedTerm.cxx @@ -24,21 +24,10 @@ an extended ML term for a given number of expected events term when an extended is constructed. **/ -#include "RooExtendedTerm.h" - -using namespace std; +#include +#include ClassImp(RooExtendedTerm); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -RooExtendedTerm::RooExtendedTerm() -{ -} - //////////////////////////////////////////////////////////////////////////////// @@ -63,16 +52,6 @@ RooExtendedTerm::RooExtendedTerm(const RooExtendedTerm& other, const char* name) { } - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooExtendedTerm::~RooExtendedTerm() -{ -} - - //////////////////////////////////////////////////////////////////////////////// /// Return number of expected events from associated event count variable @@ -81,5 +60,8 @@ double RooExtendedTerm::expectedEvents(const RooArgSet* /*nset*/) const return _n ; } - - +std::unique_ptr RooExtendedTerm::createExpectedEventsFunc(const RooArgSet * /*nset*/) const +{ + auto name = std::string(GetName()) + "_expectedEvents"; + return std::make_unique(name.c_str(), name.c_str(), *_n); +} diff --git a/roofit/roofitcore/src/RooFFTConvPdf.cxx b/roofit/roofitcore/src/RooFFTConvPdf.cxx index 8326d0b667aab..7599762e748e9 100644 --- a/roofit/roofitcore/src/RooFFTConvPdf.cxx +++ b/roofit/roofitcore/src/RooFFTConvPdf.cxx @@ -150,7 +150,7 @@ ClassImp(RooFFTConvPdf); RooFFTConvPdf::RooFFTConvPdf(const char *name, const char *title, RooRealVar& convVar, RooAbsPdf& pdf1, RooAbsPdf& pdf2, Int_t ipOrder) : RooAbsCachedPdf(name,title,ipOrder), _x("!x","Convolution Variable",this,convVar), - _xprime("!xprime","External Convolution Variable",this,0), + _xprime("!xprime","External Convolution Variable",this,false), _pdf1("!pdf1","pdf1",this,pdf1,false), _pdf2("!pdf2","pdf2",this,pdf2,false), _params("!params","effective parameters",this), @@ -686,7 +686,7 @@ std::vector RooFFTConvPdf::scanPdf(RooRealVar& obs, RooAbsPdf& pdf, con /// - all member of nset that are observables of this p.d.f. /// -RooArgSet* RooFFTConvPdf::actualObservables(const RooArgSet& nset) const +RooFit::OwningPtr RooFFTConvPdf::actualObservables(const RooArgSet& nset) const { // Get complete list of observables auto obs1 = new RooArgSet{}; @@ -731,7 +731,7 @@ RooArgSet* RooFFTConvPdf::actualObservables(const RooArgSet& nset) const } - return obs1 ; + return RooFit::OwningPtr{obs1}; } @@ -741,12 +741,12 @@ RooArgSet* RooFFTConvPdf::actualObservables(const RooArgSet& nset) const /// set nset. For this p.d.f these are the parameters of the input p.d.f. /// but never the convolution variable, in case it is not part of nset. -RooArgSet* RooFFTConvPdf::actualParameters(const RooArgSet& nset) const +RooFit::OwningPtr RooFFTConvPdf::actualParameters(const RooArgSet& nset) const { - RooArgSet* vars = getVariables() ; + auto vars = getVariables() ; vars->remove(*std::unique_ptr{actualObservables(nset)}); - return vars ; + return RooFit::OwningPtr{std::move(vars)}; } diff --git a/roofit/roofitcore/src/RooFactoryWSTool.cxx b/roofit/roofitcore/src/RooFactoryWSTool.cxx index aea971f1ec54d..d7b30213a11e8 100644 --- a/roofit/roofitcore/src/RooFactoryWSTool.cxx +++ b/roofit/roofitcore/src/RooFactoryWSTool.cxx @@ -71,8 +71,8 @@ using namespace std ; ClassImp(RooFactoryWSTool); ; -RooFactoryWSTool* RooFactoryWSTool::_of = 0 ; -map* RooFactoryWSTool::_hooks=0 ; +RooFactoryWSTool* RooFactoryWSTool::_of = nullptr ; +map* RooFactoryWSTool::_hooks=nullptr ; namespace { @@ -157,7 +157,7 @@ RooRealVar* RooFactoryWSTool::createVariable(const char* name, double xmin, doub if (_ws->var(name)) { coutE(ObjectHandling) << "RooFactoryWSTool::createFactory() ERROR: variable with name '" << name << "' already exists" << endl ; logError() ; - return 0 ; + return nullptr ; } // Create variable @@ -197,7 +197,7 @@ RooCategory* RooFactoryWSTool::createCategory(const char* name, const char* stat } else { cat.defineType(tok) ; } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } } @@ -312,7 +312,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam if (!tc) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR class " << className << " not found in factory alias table, nor in ROOT class table" << endl; logError(); - return 0; + return nullptr; } className = tc->GetName(); @@ -321,7 +321,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam if (!tc->InheritsFrom(RooAbsArg::Class())) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR class " << className << " does not inherit from RooAbsArg" << endl; logError(); - return 0; + return nullptr; } _args.clear(); @@ -351,11 +351,11 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam if (ca.first.empty()) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR no suitable constructor found for class " << className << endl ; logError() ; - return 0 ; + return nullptr ; } - // Check if number of provided args is in valid range (add two to accomodate name and title strings) + // Check if number of provided args is in valid range (add two to accomomdate name and title strings) if (_args.size()+2ca.first.size()) { if (ca.second==ca.first.size()) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR number of arguments provided (" << _args.size() << ") for class is invalid, " << className @@ -366,7 +366,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam << " expect number between " << ca.second-2 << " and " << ca.first.size()-2 << endl ; logError() ; } - return 0 ; + return nullptr ; } // Now construct CINT constructor spec, start with mandatory name and title args @@ -380,7 +380,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam Int_t i(0) ; list::iterator ti = ca.first.begin() ; ++ti ; ++ti ; for (vector::iterator ai = _args.begin() ; ai != _args.end() ; ++ai,++ti,++i) { - if ((*ti)=="RooAbsReal&" || (*ti)=="const RooAbsReal&") { + if ((*ti)=="RooAbsReal&" || (*ti)=="const RooAbsReal&" || (*ti)=="RooAbsReal::Ref") { RooFactoryWSTool::as_FUNC(i) ; cintExpr += Form(",RooFactoryWSTool::as_FUNC(%d)",i) ; } else if ((*ti)=="RooAbsArg&" || (*ti)=="const RooAbsArg&") { @@ -435,7 +435,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam string qualvalue ; if (_args[i].find(Form("%s::",className)) != string::npos) { - qualvalue = _args[i].c_str() ; + qualvalue = _args[i] ; } else { qualvalue = Form("%s::%s",className,_args[i].c_str()) ; } @@ -455,7 +455,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam } else { btype = *ti ; } - if (btype.find("&")) { + if (btype.find('&')) { btype.erase(btype.size()-1,btype.size()) ; } @@ -473,7 +473,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam } catch (const string &err) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR constructing " << className << "::" << objName << ": " << err << endl ; logError() ; - return 0 ; + return nullptr ; } cxcoutD(ObjectHandling) << "RooFactoryWSTool::createArg() Construct expression is " << cintExpr << endl ; @@ -493,7 +493,7 @@ RooAbsArg* RooFactoryWSTool::createArg(const char* className, const char* objNam } else { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR in CINT constructor call to create object" << endl ; logError() ; - return 0 ; + return nullptr ; } } @@ -522,7 +522,7 @@ RooAddPdf* RooFactoryWSTool::add(const char *objName, const char* specList, bool } else { pdfList2.add(asPDF(tok)) ; } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } pdfList.add(pdfList2) ; @@ -564,7 +564,7 @@ RooRealSumPdf* RooFactoryWSTool::amplAdd(const char *objName, const char* specLi } else { amplList2.add(asFUNC(tok)) ; } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } amplList.add(amplList2) ; @@ -613,7 +613,7 @@ RooProdPdf* RooFactoryWSTool::prod(const char *objName, const char* pdfList) } catch (const string &err) { coutE(ObjectHandling) << "RooFactoryWSTool::prod(" << objName << ") ERROR creating RooProdPdf Conditional argument: " << err << endl ; logError() ; - return 0 ; + return nullptr ; } } else { @@ -623,7 +623,7 @@ RooProdPdf* RooFactoryWSTool::prod(const char *objName, const char* pdfList) } regPdfList += tok ; } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } regPdfList += "}" ; @@ -663,7 +663,7 @@ RooSimultaneous* RooFactoryWSTool::simul(const char* objName, const char* indexC coutE(ObjectHandling) << "RooFactoryWSTool::simul(" << objName << ") ERROR creating RooSimultaneous::" << objName << " expect mapping token of form 'state=pdfName', but found '" << tok << "'" << endl ; logError() ; - return 0 ; + return nullptr ; } else { *eq = 0 ; @@ -674,7 +674,7 @@ RooSimultaneous* RooFactoryWSTool::simul(const char* objName, const char* indexC logError() ; } } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } @@ -719,19 +719,19 @@ RooAddition* RooFactoryWSTool::addfunc(const char *objName, const char* specList } else { sumlist1.add(asFUNC(tok)) ; } - tok = R__STRTOK_R(0,",",&save) ; + tok = R__STRTOK_R(nullptr,",",&save) ; } } catch (const string &err) { coutE(ObjectHandling) << "RooFactoryWSTool::addfunc(" << objName << ") ERROR creating RooAddition: " << err << endl ; logError() ; - return 0 ; + return nullptr ; } if (sumlist2.getSize()>0 && (sumlist1.getSize()!=sumlist2.getSize())) { coutE(ObjectHandling) << "RooFactoryWSTool::addfunc(" << objName << ") ERROR creating RooAddition: syntax error: either all sum terms must be products or none" << endl ; logError() ; - return 0 ; + return nullptr ; } @@ -794,7 +794,7 @@ RooProduct* RooFactoryWSTool::prodfunc(const char *objName, const char* pdfList) /// creates the sum of a Gaussian and a Chebychev and all its variables. /// /// -/// A seperate series of operator meta-type exists to simplify the construction of composite expressions +/// A separate series of operator meta-type exists to simplify the construction of composite expressions /// meta-types in all capitals (SUM) create pdfs, meta types in lower case (sum) create /// functions. /// @@ -851,7 +851,7 @@ RooAbsArg* RooFactoryWSTool::process(const char* expr) // First perform basic syntax check if (checkSyntax(expr)) { - return 0 ; + return nullptr ; } // Allocate work buffer @@ -890,7 +890,7 @@ RooAbsArg* RooFactoryWSTool::process(const char* expr) ws().commitTransaction() ; } - return out.size() ? ws().arg(out.c_str()) : 0 ; + return !out.empty() ? ws().arg(out) : nullptr ; } @@ -1020,7 +1020,7 @@ std::string RooFactoryWSTool::processSingleExpression(const char* arg) char* save ; char* tmpx = R__STRTOK_R(buf.data(),"([",&save) ; func = tmpx ? tmpx : "" ; - char* p = R__STRTOK_R(0,"",&save) ; + char* p = R__STRTOK_R(nullptr,"",&save) ; // Return here if token is fundamental if (!p) { @@ -1064,7 +1064,7 @@ std::string RooFactoryWSTool::processSingleExpression(const char* arg) // If there is a suffix left in the work buffer attach it to // this argument - p = R__STRTOK_R(0,"",&save) ; + p = R__STRTOK_R(nullptr,"",&save) ; if (p) tmp += p ; args.push_back(tmp) ; @@ -1107,7 +1107,7 @@ std::string RooFactoryWSTool::processSingleExpression(const char* arg) while(true) { autoname = Form("gobj%d",globCounter) ; globCounter++ ; - if (!ws().arg(autoname.c_str())) { + if (!ws().arg(autoname)) { break ; } } @@ -1250,7 +1250,7 @@ TClass* RooFactoryWSTool::resolveClassName(const char* className) if (!tc) { coutE(ObjectHandling) << "RooFactoryWSTool::createArg() ERROR class " << className << " not defined in ROOT class table" << endl ; logError() ; - return 0 ; + return nullptr ; } } return tc ; @@ -1339,7 +1339,7 @@ string RooFactoryWSTool::processCreateVar(string& func, vector& args) // Create a RooAbsCategory string allStates ; for (vector::iterator ai = args.begin() ; ai!=args.end() ; ++ai) { - if (allStates.size()>0) { + if (!allStates.empty()) { allStates += "," ; } allStates += *ai ; @@ -1368,7 +1368,7 @@ string RooFactoryWSTool::processCreateArg(string& func, vector& args) // Split function part in class name and instance name char* save ; const char *className = R__STRTOK_R(buf,":",&save) ; - const char *instName = R__STRTOK_R(0,":",&save) ; + const char *instName = R__STRTOK_R(nullptr,":",&save) ; if (!className) className = ""; if (!instName) instName = "" ; @@ -1445,7 +1445,7 @@ vector RooFactoryWSTool::splitFunctionArgs(const char* funcExpr) char* save ; char* tmpx = R__STRTOK_R(buf.data(),"(",&save) ; func = tmpx ? tmpx : "" ; - char* p = R__STRTOK_R(0,"",&save) ; + char* p = R__STRTOK_R(nullptr,"",&save) ; // Return here if token is fundamental if (!p) { @@ -1488,7 +1488,7 @@ vector RooFactoryWSTool::splitFunctionArgs(const char* funcExpr) // If there is a suffix left in the work buffer attach it to // this argument - p = R__STRTOK_R(0,"",&save) ; + p = R__STRTOK_R(nullptr,"",&save) ; if (p) tmp += p ; args.push_back(tmp) ; @@ -1754,7 +1754,7 @@ RooArgSet RooFactoryWSTool::asSET(const char* arg) throw string(Form("RooAbsArg named %s not found",tok)) ; } } - tok = R__STRTOK_R(0,",{}",&save) ; + tok = R__STRTOK_R(nullptr,",{}",&save) ; } return s ; @@ -1790,7 +1790,7 @@ RooArgList RooFactoryWSTool::asLIST(const char* arg) throw string(Form("RooAbsArg named %s not found",tok)) ; } } - tok = R__STRTOK_R(0,",{}",&save) ; + tok = R__STRTOK_R(nullptr,",{}",&save) ; } return l ; @@ -1869,8 +1869,8 @@ const char* RooFactoryWSTool::asSTRING(const char* arg) static unsigned int cbuf_idx = 0 ; // Handle empty string case: return null pointer - if (arg==0 || strlen(arg)==0) { - return 0 ; + if (arg==nullptr || strlen(arg)==0) { + return nullptr ; } // Fill cyclical buffer entry with quotation marked stripped version of string literal @@ -2046,7 +2046,7 @@ std::string RooFactoryWSTool::SpecialsIFace::create(RooFactoryWSTool& ft, const if (pargv.size() > 3) order = atoi(pargv[3].c_str()); if (pargv.size() > 2) { - if (pargv[2].find(",") != string::npos) + if (pargv[2].find(',') != string::npos) throw string(Form("taylorexpand::%s, factory syntax supports expansion only around same value for all observables", instName)); else observablesValue = atof(pargv[2].c_str()); } @@ -2062,7 +2062,7 @@ std::string RooFactoryWSTool::SpecialsIFace::create(RooFactoryWSTool& ft, const throw string( Form("taylorexpand::%s, requires max. 6 arguments, has %d arguments", instName, (Int_t)pargv.size())); - auto taylor = RooPolyFunc::taylorExpand(instName, instName, func, observables, observablesValue, order, eps1, eps2); + auto taylor = RooPolyFunc::taylorExpand(instName, instName, func, observables, order, {observablesValue}, eps1, eps2); if (ft.ws().import(*taylor, Silence())) ft.logError(); } else if (cl=="nconv") { @@ -2115,21 +2115,21 @@ std::string RooFactoryWSTool::SpecialsIFace::create(RooFactoryWSTool& ft, const const char* intobs = R__STRTOK_R(buf,"|",&save) ; if (!intobs) intobs="" ; - const char* range = R__STRTOK_R(0,"",&save) ; + const char* range = R__STRTOK_R(nullptr,"",&save) ; if (!range) range="" ; std::unique_ptr integral; if (pargv.size()==2) { if (range && strlen(range)) { - integral.reset(func.createIntegral(ft.asSET(intobs),Range(range))); + integral = std::unique_ptr{func.createIntegral(ft.asSET(intobs),Range(range))}; } else { - integral.reset(func.createIntegral(ft.asSET(intobs))); + integral = std::unique_ptr{func.createIntegral(ft.asSET(intobs))}; } } else { if (range && strlen(range)) { - integral.reset(func.createIntegral(ft.asSET(intobs),Range(range),NormSet(ft.asSET(pargv[2].c_str())))); + integral = std::unique_ptr{func.createIntegral(ft.asSET(intobs),Range(range),NormSet(ft.asSET(pargv[2].c_str())))}; } else { - integral.reset(func.createIntegral(ft.asSET(intobs),NormSet(ft.asSET(pargv[2].c_str())))); + integral = std::unique_ptr{func.createIntegral(ft.asSET(intobs),NormSet(ft.asSET(pargv[2].c_str())))}; } } @@ -2168,9 +2168,9 @@ std::string RooFactoryWSTool::SpecialsIFace::create(RooFactoryWSTool& ft, const std::unique_ptr cdf; if (pargv.size()==2) { - cdf.reset(pdf.createCdf(ft.asSET(pargv[1].c_str()))); + cdf = std::unique_ptr{pdf.createCdf(ft.asSET(pargv[1].c_str()))}; } else { - cdf.reset(pdf.createCdf(ft.asSET(pargv[1].c_str()),ft.asSET(pargv[2].c_str()))); + cdf = std::unique_ptr{pdf.createCdf(ft.asSET(pargv[1].c_str()),ft.asSET(pargv[2].c_str()))}; } cdf->SetName(instName) ; diff --git a/roofit/roofitcore/src/RooFirstMoment.cxx b/roofit/roofitcore/src/RooFirstMoment.cxx index 2922bd7cd88d0..dfc22cecdef95 100644 --- a/roofit/roofitcore/src/RooFirstMoment.cxx +++ b/roofit/roofitcore/src/RooFirstMoment.cxx @@ -26,7 +26,7 @@ derivator class. #include "Riostream.h" -#include +#include #include "RooFirstMoment.h" #include "RooAbsReal.h" @@ -68,24 +68,26 @@ RooFirstMoment::RooFirstMoment(const char* name, const char* title, RooAbsReal& { setExpensiveObjectCache(func.expensiveObjectCache()) ; - string pname=Form("%s_product",name) ; + std::string pname = std::string(name) + "_product"; - RooProduct* XF = new RooProduct(pname.c_str(),pname.c_str(),RooArgSet(x,func)) ; + auto XF = std::make_unique(pname.c_str(),pname.c_str(),RooArgSet(x,func)); XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; if (func.isBinnedDistribution(x)) { XF->specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator"); } - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(x) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(x) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(x)}; + std::unique_ptr intF{func.createIntegral(x)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } //////////////////////////////////////////////////////////////////////////////// @@ -100,9 +102,9 @@ RooFirstMoment::RooFirstMoment(const char* name, const char* title, RooAbsReal& _nset.add(nset) ; - string pname=Form("%s_product",name) ; + std::string pname = std::string(name) + "_product"; - RooProduct* XF = new RooProduct(pname.c_str(),pname.c_str(),RooArgSet(x,func)) ; + auto XF = std::make_unique(pname.c_str(),pname.c_str(),RooArgSet(x,func)) ; XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; if (func.isBinnedDistribution(x)) { @@ -116,15 +118,17 @@ RooFirstMoment::RooFirstMoment(const char* name, const char* title, RooAbsReal& RooArgSet intSet(x) ; if (intNSet) intSet.add(_nset,true) ; - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(intSet,&_nset) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(intSet,&_nset) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(intSet, &_nset)}; + std::unique_ptr intF{func.createIntegral(intSet, &_nset)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } diff --git a/roofit/roofitcore/src/RooFit/BatchModeDataHelpers.h b/roofit/roofitcore/src/RooFit/BatchModeDataHelpers.h index 955392268f2e4..a36d0534b50d2 100644 --- a/roofit/roofitcore/src/RooFit/BatchModeDataHelpers.h +++ b/roofit/roofitcore/src/RooFit/BatchModeDataHelpers.h @@ -13,11 +13,12 @@ #ifndef RooFit_BatchModeDataHelpers_h #define RooFit_BatchModeDataHelpers_h -#include #include +#include #include +#include #include #include #include @@ -25,14 +26,20 @@ class RooAbsCategory; class RooAbsData; +class RooSimultaneous; + class TNamed; namespace RooFit { namespace BatchModeDataHelpers { -std::map> -getDataSpans(RooAbsData const &data, std::string_view rangeName, std::string const &prefix, - std::stack> &buffers, bool skipZeroWeights); +std::map> +getDataSpans(RooAbsData const &data, std::string const &rangeName, RooSimultaneous const *simPdf, bool skipZeroWeights, + bool takeGlobalObservablesFromData, std::stack> &buffers); + +std::map +determineOutputSizes(RooAbsArg const &topNode, + std::function const &inputSizeFunc); } // namespace BatchModeDataHelpers } // namespace RooFit diff --git a/roofit/roofitcore/src/RooFit/BatchModeHelpers.h b/roofit/roofitcore/src/RooFit/BatchModeHelpers.h index 7ee055225e113..f592687af9d82 100644 --- a/roofit/roofitcore/src/RooFit/BatchModeHelpers.h +++ b/roofit/roofitcore/src/RooFit/BatchModeHelpers.h @@ -23,22 +23,12 @@ class RooAbsPdf; class RooAbsReal; class RooArgSet; -namespace ROOT { -namespace Experimental { -class RooFitDriver; -} -} // namespace ROOT - namespace RooFit { namespace BatchModeHelpers { -std::unique_ptr createNLL(std::unique_ptr &&pdf, RooAbsData &data, - std::unique_ptr &&constraints, std::string const &rangeName, - RooArgSet const &projDeps, bool isExtended, double integrateOverBinsPrecision, - RooFit::BatchModeOption batchMode, RooFit::OffsetMode offset, bool splitRange, - bool takeGlobalObservablesFromData); - -void logArchitectureInfo(RooFit::BatchModeOption batchMode); +std::unique_ptr createNLL(RooAbsPdf &pdf, RooAbsData &data, std::unique_ptr &&constraints, + std::string const &rangeName, RooArgSet const &projDeps, bool isExtended, + double integrateOverBinsPrecision, RooFit::OffsetMode offset); } // namespace BatchModeHelpers } // namespace RooFit diff --git a/roofit/roofitcore/src/RooFit/Detail/Buffers.h b/roofit/roofitcore/src/RooFit/Detail/Buffers.h index d4e1a6b3175c9..0ad9e4c4d6a04 100644 --- a/roofit/roofitcore/src/RooFit/Detail/Buffers.h +++ b/roofit/roofitcore/src/RooFit/Detail/Buffers.h @@ -13,10 +13,18 @@ #ifndef RooFit_Detail_Buffers_h #define RooFit_Detail_Buffers_h -#include +#include -namespace ROOT { -namespace Experimental { +#ifdef R__HAS_CUDA +#include +#endif + +#include +#include + +#include + +namespace RooFit { namespace Detail { class AbsBuffer { @@ -38,17 +46,19 @@ class BufferManager { BufferManager(); ~BufferManager(); - AbsBuffer *makeScalarBuffer(); - AbsBuffer *makeCpuBuffer(std::size_t size); - AbsBuffer *makeGpuBuffer(std::size_t size); - AbsBuffer *makePinnedBuffer(std::size_t size, cudaStream_t *stream = nullptr); + std::unique_ptr makeScalarBuffer(); + std::unique_ptr makeCpuBuffer(std::size_t size); +#ifdef R__HAS_CUDA + std::unique_ptr makeGpuBuffer(std::size_t size); + std::unique_ptr + makePinnedBuffer(std::size_t size, RooFit::Detail::CudaInterface::CudaStream *stream = nullptr); +#endif private: - BufferQueuesMaps *_queuesMaps; + std::unique_ptr _queuesMaps; }; } // end namespace Detail -} // end namespace Experimental -} // end namespace ROOT +} // end namespace RooFit #endif diff --git a/roofit/roofitcore/src/RooFit/Detail/CodeSquashContext.cxx b/roofit/roofitcore/src/RooFit/Detail/CodeSquashContext.cxx new file mode 100644 index 0000000000000..0b49af3d1c9e2 --- /dev/null +++ b/roofit/roofitcore/src/RooFit/Detail/CodeSquashContext.cxx @@ -0,0 +1,275 @@ +/* + * Project: RooFit + * Authors: + * Garima Singh, CERN 2023 + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include + +#include + +namespace RooFit { + +namespace Detail { + +/// Transform a string into a valid C++ variable name by replacing forbidden. +/// \note The implementation was copy-pasted from `TSystem.cxx`. +/// characters with underscores. +/// @param in The input string. +/// @return A new string valid variable name. +std::string CodeSquashContext::makeValidVarName(TString in) const +{ + + static const int nForbidden = 27; + static const char *forbiddenChars[nForbidden] = {"+", "-", "*", "/", "&", "%", "|", "^", ">", + "<", "=", "~", ".", "(", ")", "[", "]", "!", + ",", "$", " ", ":", "'", "#", "@", "\\", "\""}; + for (int ic = 0; ic < nForbidden; ic++) { + in.ReplaceAll(forbiddenChars[ic], "_"); + } + + return in.Data(); +} + +/// @brief Adds (or overwrites) the string representing the result of a node. +/// @param key The name of the node to add the result for. +/// @param value The new name to assign/overwrite. +void CodeSquashContext::addResult(const char *key, std::string const &value) +{ + const TNamed *namePtr = RooNameReg::known(key); + if (namePtr) + addResult(namePtr, value); +} + +void CodeSquashContext::addResult(TNamed const *key, std::string const &value) +{ + _nodeNames[key] = value; +} + +/// @brief Gets the result for the given node using the node name. This node also performs the necessary +/// code generation through recursive calls to 'translate'. A call to this function modifies the already +/// existing code body. +/// @param key The node to get the result string for. +/// @return String representing the result of this node. +std::string const &CodeSquashContext::getResult(RooAbsArg const &arg) +{ + // If the result has already been recorded, just return the result. + // It is usually the responsibility of each translate function to assign + // the proper result to its class. Hence, if a result has already been recorded + // for a particular node, it means the node has already been 'translate'd and we + // dont need to visit it again. + auto found = _nodeNames.find(arg.namePtr()); + if (found != _nodeNames.end()) + return found->second; + + // The result for vector observables should already be in the map if you + // opened the loop scope. This is just to check if we did not request the + // result of a vector-valued observable outside of the scope of a loop. + auto foundVecObs = _vecObsIndices.find(arg.namePtr()); + if (foundVecObs != _vecObsIndices.end()) { + throw std::runtime_error("You requested the result of a vector observable outside a loop scope for it!"); + } + + // Now, recursively call translate into the current argument to load the correct result. + arg.translate(*this); + + return _nodeNames.at(arg.namePtr()); +} + +/// @brief Adds the given string to the string block that will be emitted at the top of the squashed function. Useful +/// for variable declarations. +/// @param str The string to add to the global scope. +void CodeSquashContext::addToGlobalScope(std::string const &str) +{ + _globalScope += str; +} + +/// @brief Assemble and return the final code with the return expression and global statements. +/// @param returnExpr The string representation of what the squashed function should return, usually the head node. +/// @return The final body of the function. +std::string CodeSquashContext::assembleCode(std::string const &returnExpr) +{ + return _globalScope + _code + "\n return " + returnExpr + ";\n"; +} + +/// @brief Since the squashed code represents all observables as a single flattened array, it is important +/// to keep track of the start index for a vector valued observable which can later be expanded to access the correct +/// element. For example, a vector valued variable x with 10 entries will be squashed to obs[start_idx + i]. +/// @param key The name of the node representing the vector valued observable. +/// @param idx The start index (or relative position of the observable in the set of all observables). +void CodeSquashContext::addVecObs(const char *key, int idx) +{ + const TNamed *namePtr = RooNameReg::known(key); + if (namePtr) + _vecObsIndices[namePtr] = idx; +} + +/// @brief Adds the input string to the squashed code body. If a class implements a translate function that wants to +/// emit something to the squashed code body, it must call this function with the code it wants to emit. In case of +/// loops, automatically determines if code needs to be stored inside or outside loop scope. +/// @param klass The class requesting this addition, usually 'this'. +/// @param in String to add to the squashed code. +void CodeSquashContext::addToCodeBody(RooAbsArg const *klass, std::string const &in) +{ + // If we are in a loop and the value is scope independent, save it at the top of the loop. + // else, just save it in the current scope. + addToCodeBody(in, isScopeIndependent(klass)); +} + +/// @brief A variation of the previous addToCodeBody that takes in a bool value that determines +/// if input is independent. This overload exists because there might other ways to determine if +/// a value/collection of values is scope independent. +/// @param in String to add to the squashed code. +/// @param isScopeIndep The value determining if the input is scope dependent. +void CodeSquashContext::addToCodeBody(std::string const &in, bool isScopeIndep /* = false */) +{ + // If we are in a loop and the value is scope independent, save it at the top of the loop. + // else, just save it in the current scope. + if (_scopePtr != -1 && isScopeIndep) + _tempScope += in; + else + _code += in; +} + +/// @brief Create a RAII scope for iterating over vector observables. You can't use the result of vector observables +/// outside these loop scopes. +/// @param in A pointer to the calling class, used to determine the loop dependent variables. +std::unique_ptr CodeSquashContext::beginLoop(RooAbsArg const *in) +{ + std::string idx = "loopIdx" + std::to_string(_loopLevel); + + std::vector vars; + // set the results of the vector observables + for (auto const &it : _vecObsIndices) { + if (!in->dependsOn(it.first)) + continue; + + vars.push_back(it.first); + _nodeNames[it.first] = "obs[" + std::to_string(it.second) + " + " + idx + "]"; + } + + // TODO: we are using the size of the first loop variable to the the number + // of iterations, but it should be made sure that all loop vars are either + // scalar or have the same size. + std::size_t numEntries = 1; + for (auto &it : vars) { + std::size_t n = outputSize(it); + if (n > 1 && numEntries > 1 && n != numEntries) { + throw std::runtime_error("Trying to loop over variables with different sizes!"); + } + numEntries = std::max(n, numEntries); + } + + // Save the current size of the code array so that we can insert the code at the right position. + _scopePtr = _code.size(); + + // Make sure that the name of this variable doesn't clash with other stuff + addToCodeBody(in, "for(int " + idx + " = 0; " + idx + " < " + std::to_string(numEntries) + "; " + idx + "++) {\n"); + + ++_loopLevel; + return std::make_unique(*this, std::move(vars)); +} + +void CodeSquashContext::endLoop(LoopScope const &scope) +{ + _code += "}\n"; + + // Insert the temporary code into the correct code position. + _code.insert(_scopePtr, _tempScope); + _tempScope.erase(); + _scopePtr = -1; + + // clear the results of the loop variables if they were vector observables + for (auto const &ptr : scope.vars()) { + if (_vecObsIndices.find(ptr) != _vecObsIndices.end()) + _nodeNames.erase(ptr); + } + --_loopLevel; +} + +/// @brief Get a unique variable name to be used in the generated code. +std::string CodeSquashContext::getTmpVarName() +{ + return "tmpVar" + std::to_string(_tmpVarIdx++); +} + +/// @brief A function to save an expression that includes/depends on the result of the input node. +/// @param in The node on which the valueToSave depends on/belongs to. +/// @param valueToSave The actual string value to save as a temporary. +void CodeSquashContext::addResult(RooAbsArg const *in, std::string const &valueToSave) +{ + std::string savedName = makeValidVarName(in->GetName()); + + // Only save values if they contain operations. + bool hasOperations = valueToSave.find_first_of(":-+/*") != std::string::npos; + + // If the name is not empty and this value is worth saving, save it to the correct scope. + // otherwise, just return the actual value itself + if (hasOperations) { + // If this is a scalar result, it will go just outside the loop because + // it doesn't need to be recomputed inside loops. + std::string outVarDecl = "const double " + savedName + " = " + valueToSave + ";\n"; + addToCodeBody(in, outVarDecl); + } else { + savedName = valueToSave; + } + + addResult(in->namePtr(), savedName); +} + +/// @brief Function to save a RooListProxy as an array in the squashed code. +/// @param in The list to convert to array. +/// @return Name of the array that stores the input list in the squashed code. +std::string CodeSquashContext::buildArg(RooAbsCollection const &in) +{ + auto it = listNames.find(in.uniqueId().value()); + if (it != listNames.end()) + return it->second; + + std::string savedName = getTmpVarName(); + bool canSaveOutside = true; + + std::stringstream declStrm; + declStrm << "double " << savedName << "[] = {"; + for (const auto arg : in) { + declStrm << getResult(*arg) << ","; + canSaveOutside = canSaveOutside && isScopeIndependent(arg); + } + declStrm.seekp(-1, declStrm.cur); + declStrm << "};\n"; + + addToCodeBody(declStrm.str(), canSaveOutside); + + listNames.insert({in.uniqueId().value(), savedName}); + return savedName; +} + +std::string CodeSquashContext::buildArg(std::span arr) +{ + unsigned int n = arr.size(); + std::string arrName = getTmpVarName(); + std::string arrDecl = "double " + arrName + "[" + std::to_string(n) + "] = {"; + for (unsigned int i = 0; i < n; i++) { + arrDecl += " " + std::to_string(arr[i]) + ","; + } + arrDecl.back() = '}'; + arrDecl += ";\n"; + addToCodeBody(arrDecl, true); + + return arrName; +} + +bool CodeSquashContext::isScopeIndependent(RooAbsArg const *in) const +{ + return !in->isReducerNode() && outputSize(in->namePtr()) == 1; +} + +} // namespace Detail +} // namespace RooFit diff --git a/roofit/roofitcore/src/RooFit/Detail/DataMap.cxx b/roofit/roofitcore/src/RooFit/Detail/DataMap.cxx new file mode 100644 index 0000000000000..b73f767d465bf --- /dev/null +++ b/roofit/roofitcore/src/RooFit/Detail/DataMap.cxx @@ -0,0 +1,56 @@ +/* + * Project: RooFit + * Authors: + * Garima Singh, CERN 2023 + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include + +#include +#include + +namespace RooFit { +namespace Detail { + +std::span DataMap::at(RooAbsArg const *arg, RooAbsArg const * /*caller*/) +{ + if (!arg->hasDataToken()) { + auto var = static_cast(arg); + return {&var->_value, 1}; + } + std::size_t idx = arg->dataToken(); + return _dataMap[idx]; +} + +void DataMap::setConfig(RooAbsArg const *arg, RooBatchCompute::Config const &config) +{ + if (!arg->hasDataToken()) + return; + std::size_t idx = arg->dataToken(); + _cfgs[idx] = config; +} + +RooBatchCompute::Config DataMap::config(RooAbsArg const *arg) const +{ + if (!arg->hasDataToken()) { + return {}; + } + std::size_t idx = arg->dataToken(); + return _cfgs[idx]; +} + +void DataMap::resize(std::size_t n) +{ + _cfgs.resize(n); + _dataMap.resize(n); +} + +} // namespace Detail +} // namespace RooFit diff --git a/roofit/roofitcore/src/RooFit/Evaluator.cxx b/roofit/roofitcore/src/RooFit/Evaluator.cxx new file mode 100644 index 0000000000000..58301a447b467 --- /dev/null +++ b/roofit/roofitcore/src/RooFit/Evaluator.cxx @@ -0,0 +1,671 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2021 + * Emmanouil Michalainas, CERN 2021 + * + * Copyright (c) 2021, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +/** +\file Evaluator.cxx +\class Evaluator +\ingroup Roofitcore + +This class can evaluate a RooAbsReal object in other ways than recursive graph +traversal. Currently, it is being used for evaluating a RooAbsReal object and +supplying the value to the minimizer, during a fit. The class scans the +dependencies and schedules the computations in a secure and efficient way. The +computations take place in the RooBatchCompute library and can be carried off +by either the CPU or a CUDA-supporting GPU. The Evaluator class takes care +of data transfers. An instance of this class is created every time +RooAbsPdf::fitTo() is called and gets destroyed when the fitting ends. +**/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "BatchModeDataHelpers.h" +#include "BatchModeHelpers.h" +#include "Detail/Buffers.h" + +#include +#include +#include +#include + +#ifdef R__HAS_CUDA + +#include + +namespace CudaInterface = RooFit::Detail::CudaInterface; + +#endif + +namespace RooFit { + +namespace { + +void logArchitectureInfo(bool useGPU) +{ + // We have to exit early if the message stream is not active. Otherwise it's + // possible that this function skips logging because it thinks it has + // already logged, but actually it didn't. + if (!RooMsgService::instance().isActive(static_cast(nullptr), RooFit::Fitting, RooFit::INFO)) { + return; + } + + // Don't repeat logging architecture info if the useGPU option didn't change + { + // Second element of pair tracks whether this function has already been called + static std::pair lastUseGPU; + if (lastUseGPU.second && lastUseGPU.first == useGPU) + return; + lastUseGPU = {useGPU, true}; + } + + auto log = [](std::string_view message) { + oocxcoutI(static_cast(nullptr), Fitting) << message << std::endl; + }; + + if (useGPU && !RooBatchCompute::hasCuda()) { + throw std::runtime_error(std::string("In: ") + __func__ + "(), " + __FILE__ + ":" + __LINE__ + + ": Cuda implementation of the computing library is not available\n"); + } + if (RooBatchCompute::cpuArchitecture() == RooBatchCompute::Architecture::GENERIC) { + log("using generic CPU library compiled with no vectorizations"); + } else { + log(std::string("using CPU computation library compiled with -m") + RooBatchCompute::cpuArchitectureName()); + } + if (useGPU) { + log("using CUDA computation library"); + } +} + +} // namespace + +/// A struct used by the Evaluator to store information on the RooAbsArgs in +/// the computation graph. +struct NodeInfo { + + bool isScalar() const { return outputSize == 1; } + +#ifdef R__HAS_CUDA + bool computeInGPU() const { return (absArg->isReducerNode() || !isScalar()) && absArg->canComputeBatchWithCuda(); } +#endif + + RooAbsArg *absArg = nullptr; + RooAbsArg::OperMode originalOperMode; + + std::shared_ptr buffer; + std::size_t iNode = 0; + int remClients = 0; + int remServers = 0; +#ifdef R__HAS_CUDA + bool copyAfterEvaluation = false; +#endif + bool fromArrayInput = false; + bool isVariable = false; + bool isDirty = true; + bool isCategory = false; + bool hasLogged = false; + std::size_t outputSize = 1; + std::size_t lastSetValCount = std::numeric_limits::max(); + double scalarBuffer = 0.0; + std::vector serverInfos; + std::vector clientInfos; + +#ifdef R__HAS_CUDA + std::unique_ptr event; + std::unique_ptr stream; + + /// Check the servers of a node that has been computed and release it's resources + /// if they are no longer needed. + void decrementRemainingClients() + { + if (--remClients == 0 && !fromArrayInput) { + buffer.reset(); + } + } +#endif // R__HAS_CUDA +}; + +/// Construct a new Evaluator. The constructor analyzes and saves metadata about the graph, +/// useful for the evaluation of it that will be done later. In case the CUDA mode is selected, +/// there's also some CUDA-related initialization. +/// +/// \param[in] absReal The RooAbsReal object that sits on top of the +/// computation graph that we want to evaluate. +/// \param[in] useGPU Whether the evaluation should be preferably done on the GPU. +Evaluator::Evaluator(const RooAbsReal &absReal, bool useGPU) + : _bufferManager{std::make_unique()}, + _topNode{const_cast(absReal)}, + _useGPU{useGPU} +{ +#ifndef R__HAS_CUDA + if (useGPU) { + throw std::runtime_error("Can't create Evaluator in CUDA mode because ROOT was compiled without CUDA support!"); + } +#endif + // Some checks and logging of used architectures + logArchitectureInfo(_useGPU); + + RooArgSet serverSet; + RooHelpers::getSortedComputationGraph(_topNode, serverSet); + + _dataMapCPU.resize(serverSet.size()); +#ifdef R__HAS_CUDA + _dataMapCUDA.resize(serverSet.size()); +#endif + + std::map nodeInfos; + + // Fill the ordered nodes list and initialize the node info structs. + _nodes.reserve(serverSet.size()); + std::size_t iNode = 0; + for (RooAbsArg *arg : serverSet) { + + _nodes.emplace_back(); + auto &nodeInfo = _nodes.back(); + nodeInfo.absArg = arg; + nodeInfo.originalOperMode = arg->operMode(); + nodeInfo.iNode = iNode; + nodeInfos[arg] = &nodeInfo; + + if (dynamic_cast(arg)) { + nodeInfo.isVariable = true; + } else { + arg->setDataToken(iNode); + } + if (dynamic_cast(arg)) { + nodeInfo.isCategory = true; + } + + ++iNode; + } + + for (NodeInfo &info : _nodes) { + info.serverInfos.reserve(info.absArg->servers().size()); + for (RooAbsArg *server : info.absArg->servers()) { + if (server->isValueServer(*info.absArg)) { + auto *serverInfo = nodeInfos.at(server); + info.serverInfos.emplace_back(serverInfo); + serverInfo->clientInfos.emplace_back(&info); + } + } + } + + syncDataTokens(); + +#ifdef R__HAS_CUDA + if (_useGPU) { + // create events and streams for every node + for (auto &info : _nodes) { + info.event = std::make_unique(false); + info.stream = std::make_unique(); + RooBatchCompute::Config cfg; + cfg.setCudaStream(info.stream.get()); + _dataMapCUDA.setConfig(info.absArg, cfg); + } + } +#endif +} + +/// If there are servers with the same name that got de-duplicated in the +/// `_nodes` list, we need to set their data tokens too. We find such nodes by +/// visiting the servers of every known node. +void Evaluator::syncDataTokens() +{ + for (NodeInfo &info : _nodes) { + std::size_t iValueServer = 0; + for (RooAbsArg *server : info.absArg->servers()) { + if (server->isValueServer(*info.absArg)) { + auto *knownServer = info.serverInfos[iValueServer]->absArg; + if (knownServer->hasDataToken()) { + server->setDataToken(knownServer->dataToken()); + } + ++iValueServer; + } + } + } +} + +void Evaluator::setInput(std::string const &name, std::span inputArray, bool isOnDevice) +{ + if (isOnDevice && !_useGPU) { + throw std::runtime_error("Evaluator can only take device array as input in CUDA mode!"); + } + + auto namePtr = RooNameReg::ptr(name.c_str()); + + // Iterate over the given data spans and add them to the data map. Check if + // they are used in the computation graph. If yes, add the span to the data + // map and set the node info accordingly. + std::size_t iNode = 0; + for (auto &info : _nodes) { + const bool fromArrayInput = info.absArg->namePtr() == namePtr; + if (fromArrayInput) { + info.fromArrayInput = true; + info.absArg->setDataToken(iNode); + info.outputSize = inputArray.size(); + if (_useGPU) { +#ifdef R__HAS_CUDA + if (info.outputSize == 1) { + // Scalar observables from the data don't need to be copied to the GPU + _dataMapCPU.set(info.absArg, inputArray); + _dataMapCUDA.set(info.absArg, inputArray); + } else { + if (_useGPU) { + // For simplicity, we put the data on both host and device for + // now. This could be optimized by inspecting the clients of the + // variable. + if (isOnDevice) { + _dataMapCUDA.set(info.absArg, inputArray); + auto gpuSpan = _dataMapCUDA.at(info.absArg); + info.buffer = _bufferManager->makeCpuBuffer(gpuSpan.size()); + CudaInterface::copyDeviceToHost(gpuSpan.data(), info.buffer->cpuWritePtr(), gpuSpan.size()); + _dataMapCPU.set(info.absArg, {info.buffer->cpuReadPtr(), gpuSpan.size()}); + } else { + _dataMapCPU.set(info.absArg, inputArray); + auto cpuSpan = _dataMapCPU.at(info.absArg); + info.buffer = _bufferManager->makeGpuBuffer(cpuSpan.size()); + CudaInterface::copyHostToDevice(cpuSpan.data(), info.buffer->gpuWritePtr(), cpuSpan.size()); + _dataMapCUDA.set(info.absArg, {info.buffer->gpuReadPtr(), cpuSpan.size()}); + } + } else { + _dataMapCPU.set(info.absArg, inputArray); + } + } +#endif + } else { + _dataMapCPU.set(info.absArg, inputArray); + } + } + info.isDirty = !info.fromArrayInput; + ++iNode; + } + + _needToUpdateOutputSizes = true; +} + +void Evaluator::updateOutputSizes() +{ + std::map sizeMap; + for (auto &info : _nodes) { + if (info.fromArrayInput) { + sizeMap[info.absArg] = info.outputSize; + } else { + // any buffer for temporary results is invalidated by resetting the output sizes + info.buffer.reset(); + } + } + + auto outputSizeMap = RooFit::BatchModeDataHelpers::determineOutputSizes(_topNode, [&](RooFit::Detail::DataKey key) { + auto found = sizeMap.find(key); + return found != sizeMap.end() ? found->second : 0; + }); + + for (auto &info : _nodes) { + info.outputSize = outputSizeMap.at(info.absArg); + + // In principle we don't need dirty flag propagation because the driver + // takes care of deciding which node needs to be re-evaluated. However, + // disabling it also for scalar mode results in very long fitting times + // for specific models (test 14 in stressRooFit), which still needs to be + // understood. TODO. + if (!info.isScalar()) { + setOperMode(info.absArg, RooAbsArg::ADirty); + } else { + setOperMode(info.absArg, info.originalOperMode); + } + } + +#ifdef R__HAS_CUDA + if (_useGPU) { + markGPUNodes(); + } +#endif + + _needToUpdateOutputSizes = false; +} + +Evaluator::~Evaluator() +{ + for (auto &info : _nodes) { + info.absArg->resetDataToken(); + } +} + +void Evaluator::computeCPUNode(const RooAbsArg *node, NodeInfo &info) +{ + using namespace Detail; + + auto nodeAbsReal = static_cast(node); + + const std::size_t nOut = info.outputSize; + + double *buffer = nullptr; + if (nOut == 1) { + buffer = &info.scalarBuffer; +#ifdef R__HAS_CUDA + if (_useGPU) { + _dataMapCUDA.set(node, {buffer, nOut}); + } +#endif + } else { +#ifdef R__HAS_CUDA + if (!info.hasLogged && _useGPU) { + RooAbsArg const &arg = *info.absArg; + oocoutI(&arg, FastEvaluations) << "The argument " << arg.ClassName() << "::" << arg.GetName() + << " could not be evaluated on the GPU because the class doesn't support it. " + "Consider requesting or implementing it to benefit from a speed up." + << std::endl; + info.hasLogged = true; + } +#endif + if (!info.buffer) { +#ifdef R__HAS_CUDA + info.buffer = info.copyAfterEvaluation ? _bufferManager->makePinnedBuffer(nOut, info.stream.get()) + : _bufferManager->makeCpuBuffer(nOut); +#else + info.buffer = _bufferManager->makeCpuBuffer(nOut); +#endif + } + buffer = info.buffer->cpuWritePtr(); + } + _dataMapCPU.set(node, {buffer, nOut}); + nodeAbsReal->computeBatch(buffer, nOut, _dataMapCPU); +#ifdef R__HAS_CUDA + if (info.copyAfterEvaluation) { + _dataMapCUDA.set(node, {info.buffer->gpuReadPtr(), nOut}); + if (info.event) { + CudaInterface::cudaEventRecord(*info.event, *info.stream); + } + } +#endif +} + +/// Process a variable in the computation graph. This is a separate non-inlined +/// function such that we can see in performance profiles how long this takes. +void Evaluator::processVariable(NodeInfo &nodeInfo) +{ + RooAbsArg *node = nodeInfo.absArg; + auto *var = static_cast(node); + if (nodeInfo.lastSetValCount != var->valueResetCounter()) { + nodeInfo.lastSetValCount = var->valueResetCounter(); + for (NodeInfo *clientInfo : nodeInfo.clientInfos) { + clientInfo->isDirty = true; + } + computeCPUNode(node, nodeInfo); + nodeInfo.isDirty = false; + } +} + +/// Flags all the clients of a given node dirty. This is a separate non-inlined +/// function such that we can see in performance profiles how long this takes. +void Evaluator::setClientsDirty(NodeInfo &nodeInfo) +{ + for (NodeInfo *clientInfo : nodeInfo.clientInfos) { + clientInfo->isDirty = true; + } +} + +/// Returns the value of the top node in the computation graph +std::span Evaluator::run() +{ + if (_needToUpdateOutputSizes) + updateOutputSizes(); + + ++_nEvaluations; + +#ifdef R__HAS_CUDA + if (_useGPU) { + return getValHeterogeneous(); + } +#endif + + for (auto &nodeInfo : _nodes) { + if (!nodeInfo.fromArrayInput) { + if (nodeInfo.isVariable) { + processVariable(nodeInfo); + } else { + if (nodeInfo.isDirty) { + setClientsDirty(nodeInfo); + computeCPUNode(nodeInfo.absArg, nodeInfo); + nodeInfo.isDirty = false; + } + } + } + } + + // return the final output + return _dataMapCPU.at(&_topNode); +} + +#ifdef R__HAS_CUDA + +/// Returns the value of the top node in the computation graph +std::span Evaluator::getValHeterogeneous() +{ + for (auto &info : _nodes) { + info.remClients = info.clientInfos.size(); + info.remServers = info.serverInfos.size(); + if (info.buffer && !info.fromArrayInput) { + info.buffer.reset(); + } + } + + // find initial GPU nodes and assign them to GPU + for (auto &info : _nodes) { + if (info.remServers == 0 && info.computeInGPU()) { + assignToGPU(info); + } + } + + NodeInfo const &topNodeInfo = _nodes.back(); + while (topNodeInfo.remServers != -2) { + // find finished GPU nodes + for (auto &info : _nodes) { + if (info.remServers == -1 && !info.stream->isActive()) { + info.remServers = -2; + // Decrement number of remaining servers for clients and start GPU computations + for (auto *infoClient : info.clientInfos) { + --infoClient->remServers; + if (infoClient->computeInGPU() && infoClient->remServers == 0) { + assignToGPU(*infoClient); + } + } + for (auto *serverInfo : info.serverInfos) { + serverInfo->decrementRemainingClients(); + } + } + } + + // find next CPU node + auto it = _nodes.begin(); + for (; it != _nodes.end(); it++) { + if (it->remServers == 0 && !it->computeInGPU()) + break; + } + + // if no CPU node available sleep for a while to save CPU usage + if (it == _nodes.end()) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + continue; + } + + // compute next CPU node + NodeInfo &info = *it; + RooAbsArg const *node = info.absArg; + info.remServers = -2; // so that it doesn't get picked again + + if (!info.fromArrayInput) { + computeCPUNode(node, info); + } + + // Assign the clients that are computed on the GPU + for (auto *infoClient : info.clientInfos) { + if (--infoClient->remServers == 0 && infoClient->computeInGPU()) { + assignToGPU(*infoClient); + } + } + for (auto *serverInfo : info.serverInfos) { + serverInfo->decrementRemainingClients(); + } + } + + // return the final value + return _dataMapCUDA.at(&_topNode); +} + +/// Assign a node to be computed in the GPU. Scan it's clients and also assign them +/// in case they only depend on GPU nodes. +void Evaluator::assignToGPU(NodeInfo &info) +{ + using namespace Detail; + + auto node = static_cast(info.absArg); + + info.remServers = -1; + // wait for every server to finish + for (auto *infoServer : info.serverInfos) { + if (infoServer->event) + info.stream->waitForEvent(*infoServer->event); + } + + const std::size_t nOut = info.outputSize; + + double *buffer = nullptr; + if (nOut == 1) { + buffer = &info.scalarBuffer; + _dataMapCPU.set(node, {buffer, nOut}); + } else { + info.buffer = info.copyAfterEvaluation ? _bufferManager->makePinnedBuffer(nOut, info.stream.get()) + : _bufferManager->makeGpuBuffer(nOut); + buffer = info.buffer->gpuWritePtr(); + } + _dataMapCUDA.set(node, {buffer, nOut}); + node->computeBatch(buffer, nOut, _dataMapCUDA); + CudaInterface::cudaEventRecord(*info.event, *info.stream); + if (info.copyAfterEvaluation) { + _dataMapCPU.set(node, {info.buffer->cpuReadPtr(), nOut}); + } +} + +/// Decides which nodes are assigned to the GPU in a CUDA fit. +void Evaluator::markGPUNodes() +{ + for (auto &info : _nodes) { + info.copyAfterEvaluation = false; + // scalar nodes don't need copying + if (!info.isScalar()) { + for (auto *clientInfo : info.clientInfos) { + if (info.computeInGPU() != clientInfo->computeInGPU()) { + info.copyAfterEvaluation = true; + break; + } + } + } + } +} + +#endif // R__HAS_CUDA + +/// Temporarily change the operation mode of a RooAbsArg until the +/// Evaluator gets deleted. +void Evaluator::setOperMode(RooAbsArg *arg, RooAbsArg::OperMode opMode) +{ + if (opMode != arg->operMode()) { + _changeOperModeRAIIs.emplace(arg, opMode); + } +} + +void Evaluator::print(std::ostream &os) const +{ + std::cout << "--- RooFit BatchMode evaluation ---\n"; + + std::vector widths{9, 37, 20, 9, 10, 20}; + + auto printElement = [&](int iCol, auto const &t) { + const char separator = ' '; + os << separator << std::left << std::setw(widths[iCol]) << std::setfill(separator) << t; + os << "|"; + }; + + auto printHorizontalRow = [&]() { + int n = 0; + for (int w : widths) { + n += w + 2; + } + for (int i = 0; i < n; i++) { + os << '-'; + } + os << "|\n"; + }; + + printHorizontalRow(); + + os << "|"; + printElement(0, "Index"); + printElement(1, "Name"); + printElement(2, "Class"); + printElement(3, "Size"); + printElement(4, "From Data"); + printElement(5, "1st value"); + std::cout << "\n"; + + printHorizontalRow(); + + for (std::size_t iNode = 0; iNode < _nodes.size(); ++iNode) { + auto &nodeInfo = _nodes[iNode]; + RooAbsArg *node = nodeInfo.absArg; + + auto span = _dataMapCPU.at(node); + + os << "|"; + printElement(0, iNode); + printElement(1, node->GetName()); + printElement(2, node->ClassName()); + printElement(3, nodeInfo.outputSize); + printElement(4, nodeInfo.fromArrayInput); + printElement(5, span[0]); + + std::cout << "\n"; + } + + printHorizontalRow(); +} + +/// Gets all the parameters of the RooAbsReal. This is in principle not +/// necessary, because we can always ask the RooAbsReal itself, but the +/// Evaluator has the cached information to get the answer quicker. +/// Therefore, this is not meant to be used in general, just where it matters. +/// \warning If we find another solution to get the parameters efficiently, +/// this function might be removed without notice. +RooArgSet Evaluator::getParameters() const +{ + RooArgSet parameters; + for (auto &nodeInfo : _nodes) { + if (!nodeInfo.fromArrayInput && nodeInfo.isVariable) { + parameters.add(*nodeInfo.absArg); + } + } + // Just like in RooAbsArg::getParameters(), we sort the parameters alphabetically. + parameters.sort(); + return parameters; +} + +} // namespace RooFit diff --git a/roofit/roofitcore/src/RooFitDriver.cxx b/roofit/roofitcore/src/RooFitDriver.cxx deleted file mode 100644 index 1969ade05dc58..0000000000000 --- a/roofit/roofitcore/src/RooFitDriver.cxx +++ /dev/null @@ -1,864 +0,0 @@ -/* - * Project: RooFit - * Authors: - * Jonas Rembser, CERN 2021 - * Emmanouil Michalainas, CERN 2021 - * - * Copyright (c) 2021, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -/** -\file RooFitDriver.cxx -\class RooFitDriver -\ingroup Roofitcore - -This class can evaluate a RooAbsReal object in other ways than recursive graph -traversal. Currently, it is being used for evaluating a RooAbsReal object and -supplying the value to the minimizer, during a fit. The class scans the -dependencies and schedules the computations in a secure and efficient way. The -computations take place in the RooBatchCompute library and can be carried off -by either the CPU or a CUDA-supporting GPU. The RooFitDriver class takes care -of data transfers. An instance of this class is created every time -RooAbsPdf::fitTo() is called and gets destroyed when the fitting ends. -**/ - -#include "RooFitDriver.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "RooFit/BatchModeDataHelpers.h" -#include "RooFit/BatchModeHelpers.h" -#include "RooFit/CUDAHelpers.h" -#include - -#include "NormalizationHelpers.h" - -#include - -#include -#include -#include - -#define COUT_DEBUG ooccoutD(nullptr, FastEvaluations) - -namespace { - -enum HeterogeneosIterations { CPUOnly = 2, GPUOnly = 1, Both = 3 }; - -} - -namespace ROOT { -namespace Experimental { - -/// A struct used by the RooFitDriver to store information on the RooAbsArgs in -/// the computation graph. -struct NodeInfo { - /// Check the servers of a node that has been computed and release it's resources - /// if they are no longer needed. - void decrementRemainingClients() - { - if (--remClients == 0) { - delete buffer; - buffer = nullptr; - } - } - - RooAbsArg *absArg = nullptr; - - Detail::AbsBuffer *buffer = nullptr; - std::size_t iNode = 0; - cudaEvent_t *event = nullptr; - cudaEvent_t *eventStart = nullptr; - cudaStream_t *stream = nullptr; - std::chrono::microseconds cpuTime{0}; - std::chrono::microseconds cudaTime{std::chrono::microseconds::max()}; - int remClients = 0; - int remServers = 0; - bool isScalar = false; - bool computeInGPU = false; - bool copyAfterEvaluation = false; - bool fromDataset = false; - bool isVariable = false; - bool isDirty = true; - bool isCategory = false; - std::size_t outputSize = 1; - std::size_t lastSetValCount = std::numeric_limits::max(); - std::size_t originalDataToken = 0; - double scalarBuffer = 0.0; - std::vector serverInfos; - std::vector clientInfos; - - ~NodeInfo() - { - if (event) - RooBatchCompute::dispatchCUDA->deleteCudaEvent(event); - if (eventStart) - RooBatchCompute::dispatchCUDA->deleteCudaEvent(eventStart); - if (stream) - RooBatchCompute::dispatchCUDA->deleteCudaStream(stream); - } -}; - -/// Construct a new RooFitDriver. The constructor analyzes and saves metadata about the graph, -/// useful for the evaluation of it that will be done later. In case the CUDA mode is selected, -/// there's also some CUDA-related initialization. -/// -/// \param[in] absReal The RooAbsReal object that sits on top of the -/// computation graph that we want to evaluate. -/// \param[in] normSet Normalization set for the evaluation -/// \param[in] batchMode The computation mode, accepted values are -/// `RooBatchCompute::Cpu` and `RooBatchCompute::Cuda`. -RooFitDriver::RooFitDriver(const RooAbsReal &absReal, RooArgSet const &normSet, RooFit::BatchModeOption batchMode) - : _batchMode{batchMode} -{ - _integralUnfolder = std::make_unique(absReal, normSet); - - // Initialize RooBatchCompute - RooBatchCompute::init(); - - // Some checks and logging of used architectures - RooFit::BatchModeHelpers::logArchitectureInfo(_batchMode); - - // Get the set of nodes in the computation graph. Do the detour via - // RooArgList to avoid deduplication done after adding each element. - RooArgList serverList; - topNode().treeNodeServerList(&serverList, nullptr, true, true, false, true); - // If we fill the servers in reverse order, they are approximately in - // topological order so we save a bit of work in sortTopologically(). - RooArgSet serverSet; - serverSet.add(serverList.rbegin(), serverList.rend(), /*silent=*/true); - // Sort nodes topologically: the servers of any node will be before that - // node in the collection. - serverSet.sortTopologically(); - - _dataMapCPU.resize(serverSet.size()); - _dataMapCUDA.resize(serverSet.size()); - - std::unordered_map tokens; - std::map nodeInfos; - - // Fill the ordered nodes list and initialize the node info structs. - _nodes.resize(serverSet.size()); - std::size_t iNode = 0; - for (RooAbsArg *arg : serverSet) { - - tokens[arg->namePtr()] = iNode; - - auto &nodeInfo = _nodes[iNode]; - nodeInfo.absArg = arg; - nodeInfo.iNode = iNode; - nodeInfos[arg] = &nodeInfo; - - nodeInfo.originalDataToken = arg->dataToken(); - arg->setDataToken(iNode); - - if (dynamic_cast(arg)) { - nodeInfo.isVariable = true; - } - if (dynamic_cast(arg)) { - nodeInfo.isCategory = true; - } - - ++iNode; - } - - for (NodeInfo &info : _nodes) { - info.serverInfos.reserve(info.absArg->servers().size()); - for (RooAbsArg *server : info.absArg->servers()) { - if (server->isValueServer(*info.absArg)) { - auto *serverInfo = nodeInfos.at(server); - info.serverInfos.emplace_back(serverInfo); - serverInfo->clientInfos.emplace_back(&info); - } - server->setDataToken(tokens.at(server->namePtr())); - } - } - - if (_batchMode == RooFit::BatchModeOption::Cuda) { - // create events and streams for every node - for (auto &info : _nodes) { - info.event = RooBatchCompute::dispatchCUDA->newCudaEvent(true); - info.eventStart = RooBatchCompute::dispatchCUDA->newCudaEvent(true); - info.stream = RooBatchCompute::dispatchCUDA->newCudaStream(); - } - } -} - -void RooFitDriver::setData(RooAbsData const &data, std::string const &rangeName, RooSimultaneous const *simPdf, - bool splitRange, bool skipZeroWeights, bool takeGlobalObservablesFromData) -{ - std::vector> datas; - std::vector isBinnedL; - - if (simPdf) { - _splittedDataSets.clear(); - std::unique_ptr splits{data.split(*simPdf, true)}; - for (auto *d : static_range_cast(*splits)) { - RooAbsPdf *simComponent = simPdf->getPdf(d->GetName()); - // If there is no PDF for that component, we also don't need to fill the data - if (!simComponent) { - continue; - } - datas.emplace_back(std::string("_") + d->GetName() + "_", d); - isBinnedL.emplace_back(RooHelpers::getBinnedL(*simComponent).isBinnedL); - // The dataset need to be kept alive because the datamap points to their content - _splittedDataSets.emplace_back(d); - } - } else { - datas.emplace_back("", &data); - isBinnedL.emplace_back(false); - } - - DataSpansMap dataSpans; - - std::stack>{}.swap(_vectorBuffers); - - for (std::size_t iData = 0; iData < datas.size(); ++iData) { - auto const &toAdd = datas[iData]; - DataSpansMap spans = RooFit::BatchModeDataHelpers::getDataSpans( - *toAdd.second, RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, toAdd.second->GetName()), - toAdd.first, _vectorBuffers, skipZeroWeights && !isBinnedL[iData]); - for (auto const &item : spans) { - dataSpans.insert(item); - } - } - - if (takeGlobalObservablesFromData && data.getGlobalObservables()) { - _vectorBuffers.emplace(); - auto &buffer = _vectorBuffers.top(); - buffer.reserve(data.getGlobalObservables()->size()); - for (auto *arg : static_range_cast(*data.getGlobalObservables())) { - buffer.push_back(arg->getVal()); - dataSpans[arg] = RooSpan{&buffer.back(), 1}; - } - } - setData(dataSpans); -} - -void RooFitDriver::setData(DataSpansMap const &dataSpans) -{ - // Iterate over the given data spans and add them to the data map. Check if - // they are used in the computation graph. If yes, add the span to the data - // map and set the node info accordingly. - std::size_t totalSize = 0; - for (auto &info : _nodes) { - if (info.buffer) { - delete info.buffer; - info.buffer = nullptr; - } - auto found = dataSpans.find(info.absArg->namePtr()); - if (found != dataSpans.end()) { - _dataMapCPU.at(info.absArg) = found->second; - info.outputSize = found->second.size(); - info.fromDataset = true; - info.isDirty = false; - totalSize += info.outputSize; - } else { - info.outputSize = 1; - info.fromDataset = false; - info.isDirty = true; - } - } - - determineOutputSizes(); - - for (auto &info : _nodes) { - // If the node has an output of size 1 - info.isScalar = info.outputSize == 1; - - // In principle we don't need dirty flag propagation because the driver - // takes care of deciding which node needs to be re-evaluated. However, - // disabling it also for scalar mode results in very long fitting times - // for specific models (test 14 in stressRooFit), which still needs to be - // understood. TODO. - if (!info.isScalar) { - setOperMode(info.absArg, RooAbsArg::ADirty); - } - } - - // Extra steps for initializing in cuda mode - if (_batchMode != RooFit::BatchModeOption::Cuda) - return; - - // copy observable data to the GPU - // TODO: use separate buffers here - _cudaMemDataset = static_cast(RooBatchCompute::dispatchCUDA->cudaMalloc(totalSize * sizeof(double))); - size_t idx = 0; - for (auto &info : _nodes) { - if (!info.fromDataset) - continue; - std::size_t size = info.outputSize; - _dataMapCUDA.at(info.absArg) = RooSpan(_cudaMemDataset + idx, size); - RooBatchCompute::dispatchCUDA->memcpyToCUDA(_cudaMemDataset + idx, _dataMapCPU.at(info.absArg).data(), - size * sizeof(double)); - idx += size; - } -} - -RooFitDriver::~RooFitDriver() -{ - for (auto &info : _nodes) { - info.absArg->setDataToken(info.originalDataToken); - } - - if (_batchMode == RooFit::BatchModeOption::Cuda) { - RooBatchCompute::dispatchCUDA->cudaFree(_cudaMemDataset); - } -} - -std::vector RooFitDriver::getValues() -{ - getVal(); - NodeInfo const &nodeInfo = _nodes.back(); - if (nodeInfo.computeInGPU) { - std::size_t nOut = nodeInfo.outputSize; - std::vector out(nOut); - RooBatchCompute::dispatchCUDA->memcpyToCPU(out.data(), _dataMapCPU.at(&topNode()).data(), nOut * sizeof(double)); - _dataMapCPU.at(&topNode()) = RooSpan(out.data(), nOut); - return out; - } - // We copy the data to the output vector - auto dataSpan = _dataMapCPU.at(&topNode()); - std::vector out; - out.reserve(dataSpan.size()); - for (auto const &x : dataSpan) { - out.push_back(x); - } - return out; -} - -void RooFitDriver::computeCPUNode(const RooAbsArg *node, NodeInfo &info) -{ - using namespace Detail; - - auto nodeAbsReal = static_cast(node); - - const std::size_t nOut = info.outputSize; - - if (nOut == 1) { - _dataMapCPU.at(node) = RooSpan(&info.scalarBuffer, nOut); - if (_batchMode == RooFit::BatchModeOption::Cuda) { - _dataMapCUDA.at(node) = RooSpan(&info.scalarBuffer, nOut); - } - nodeAbsReal->computeBatch(nullptr, &info.scalarBuffer, nOut, _dataMapCPU); - } else { - if (!info.buffer) { - info.buffer = info.copyAfterEvaluation ? _bufferManager.makePinnedBuffer(nOut, info.stream) - : _bufferManager.makeCpuBuffer(nOut); - } - double *buffer = info.buffer->cpuWritePtr(); - _dataMapCPU.at(node) = RooSpan(buffer, nOut); - // compute node and measure the time the first time - if (_getValInvocations == CPUOnly) { - using namespace std::chrono; - auto start = steady_clock::now(); - nodeAbsReal->computeBatch(nullptr, buffer, nOut, _dataMapCPU); - info.cpuTime = duration_cast(steady_clock::now() - start); - } else { - nodeAbsReal->computeBatch(nullptr, buffer, nOut, _dataMapCPU); - } - if (info.copyAfterEvaluation) { - _dataMapCUDA.at(node) = RooSpan(info.buffer->gpuReadPtr(), nOut); - if (info.event) { - RooBatchCompute::dispatchCUDA->cudaEventRecord(info.event, info.stream); - } - } - } -} - -/// Returns the value of the top node in the computation graph -double RooFitDriver::getVal() -{ - ++_getValInvocations; - - if (_batchMode == RooFit::BatchModeOption::Cuda) { - return getValHeterogeneous(); - } - - for (auto &nodeInfo : _nodes) { - RooAbsArg *node = nodeInfo.absArg; - if (!nodeInfo.fromDataset) { - if (nodeInfo.isVariable) { - auto *var = static_cast(node); - if (nodeInfo.lastSetValCount != var->valueResetCounter()) { - nodeInfo.lastSetValCount = var->valueResetCounter(); - for (NodeInfo *clientInfo : nodeInfo.clientInfos) { - clientInfo->isDirty = true; - } - computeCPUNode(node, nodeInfo); - nodeInfo.isDirty = false; - } - } else { - if (nodeInfo.isDirty) { - for (NodeInfo *clientInfo : nodeInfo.clientInfos) { - clientInfo->isDirty = true; - } - computeCPUNode(node, nodeInfo); - nodeInfo.isDirty = false; - } - } - } - } - - // return the final value - return _dataMapCPU.at(&topNode())[0]; -} - -/// Returns the value of the top node in the computation graph -double RooFitDriver::getValHeterogeneous() -{ - for (auto &info : _nodes) { - info.remClients = info.clientInfos.size(); - info.remServers = info.serverInfos.size(); - if (info.buffer) - delete info.buffer; - info.buffer = nullptr; - } - - // In a cuda fit, use first 3 fits to determine the execution times - // and the hardware that computes each part of the graph - if (_getValInvocations <= Both) { - // leave everything to be computed (and timed) in CPU in the 1st - // invocation, and after the 3rd the GPU nodes are already marked. - markGPUNodes(); - } - - // find initial GPU nodes and assign them to GPU - for (auto &info : _nodes) { - if (info.remServers == 0 && info.computeInGPU) { - assignToGPU(info); - } - } - - NodeInfo const &topNodeInfo = _nodes.back(); - while (topNodeInfo.remServers != -2) { - // find finished GPU nodes - for (auto &info : _nodes) { - if (info.remServers == -1 && !RooBatchCompute::dispatchCUDA->streamIsActive(info.stream)) { - if (_getValInvocations == GPUOnly) { - float ms = RooBatchCompute::dispatchCUDA->cudaEventElapsedTime(info.eventStart, info.event); - info.cudaTime += std::chrono::microseconds{int(1000.0 * ms)}; - } - info.remServers = -2; - // Decrement number of remaining servers for clients and start GPU computations - for (auto *infoClient : info.clientInfos) { - --infoClient->remServers; - if (infoClient->computeInGPU && infoClient->remServers == 0) { - assignToGPU(*infoClient); - } - } - for (auto *serverInfo : info.serverInfos) { - serverInfo->decrementRemainingClients(); - } - } - } - - // find next CPU node - auto it = _nodes.begin(); - for (; it != _nodes.end(); it++) { - if (it->remServers == 0 && !it->computeInGPU) - break; - } - - // if no CPU node available sleep for a while to save CPU usage - if (it == _nodes.end()) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - continue; - } - - // compute next CPU node - NodeInfo &info = *it; - RooAbsArg const *node = info.absArg; - info.remServers = -2; // so that it doesn't get picked again - - if (!info.fromDataset) { - computeCPUNode(node, info); - } - - // Assign the clients that are computed on the GPU - for (auto *infoClient : info.clientInfos) { - if (--infoClient->remServers == 0 && infoClient->computeInGPU) { - assignToGPU(*infoClient); - } - } - for (auto *serverInfo : info.serverInfos) { - serverInfo->decrementRemainingClients(); - } - } - - // return the final value - return _dataMapCPU.at(&topNode())[0]; -} - -/// Assign a node to be computed in the GPU. Scan it's clients and also assign them -/// in case they only depend on GPU nodes. -void RooFitDriver::assignToGPU(NodeInfo &info) -{ - using namespace Detail; - - auto node = static_cast(info.absArg); - - const std::size_t nOut = info.outputSize; - - info.remServers = -1; - // wait for every server to finish - for (auto *infoServer : info.serverInfos) { - if (infoServer->event) - RooBatchCompute::dispatchCUDA->cudaStreamWaitEvent(info.stream, infoServer->event); - } - - info.buffer = info.copyAfterEvaluation ? _bufferManager.makePinnedBuffer(nOut, info.stream) - : _bufferManager.makeGpuBuffer(nOut); - double *buffer = info.buffer->gpuWritePtr(); - _dataMapCUDA.at(node) = RooSpan(buffer, nOut); - // measure launching overhead (add computation time later) - if (_getValInvocations == GPUOnly) { - using namespace std::chrono; - RooBatchCompute::dispatchCUDA->cudaEventRecord(info.eventStart, info.stream); - auto start = steady_clock::now(); - node->computeBatch(info.stream, buffer, nOut, _dataMapCUDA); - info.cudaTime = duration_cast(steady_clock::now() - start); - } else { - node->computeBatch(info.stream, buffer, nOut, _dataMapCUDA); - } - RooBatchCompute::dispatchCUDA->cudaEventRecord(info.event, info.stream); - if (info.copyAfterEvaluation) { - _dataMapCPU.at(node) = RooSpan(info.buffer->cpuReadPtr(), nOut); - } -} - -} // namespace Experimental -} // namespace ROOT - -namespace { - -/// This methods simulates the computation of the whole graph and the time it takes -/// and decides what to compute in GPU. The decision is made on the basis of avoiding -/// leaving either the GPU or the CPU idle at any time, if possible, and on assigning -/// to each piece of hardware a computation that is significantly slower on the other part. -/// The nodes may be assigned to the non-efficient side (CPU or GPU) to prevent idleness -/// only if the absolute difference cpuTime-cudaTime does not exceed the diffThreshold. -std::chrono::microseconds simulateFit(std::vector &computeInGPU, - std::vector const &nodes, - std::chrono::microseconds h2dTime, std::chrono::microseconds d2hTime, - std::chrono::microseconds diffThreshold) -{ - using namespace std::chrono; - using ROOT::Experimental::NodeInfo; - - for (std::size_t iNode = 0; iNode < nodes.size(); ++iNode) { - auto const &info = nodes[iNode]; - computeInGPU[iNode] = !info.isScalar && info.absArg->canComputeBatchWithCuda(); - } - - std::vector timeLaunched; - timeLaunched.reserve(nodes.size()); - - std::size_t nNodes = nodes.size(); - // launch scalar nodes (assume they are computed in 0 time) - for (auto &info : nodes) { - if (info.isScalar) { - nNodes--; - timeLaunched.emplace_back(0); - } else - timeLaunched.emplace_back(-1); - } - - NodeInfo const *cpuNode = nullptr; - NodeInfo const *cudaNode = nullptr; - microseconds simulatedTime{0}; - while (nNodes) { - microseconds minDiff = microseconds::max(), maxDiff = -minDiff; // diff = cpuTime - cudaTime - NodeInfo const *cpuCandidate = nullptr; - NodeInfo const *cudaCandidate = nullptr; - microseconds cpuDelay{}; - microseconds cudaDelay{}; - for (std::size_t iNode = 0; iNode < nodes.size(); ++iNode) { - auto &info = nodes[iNode]; - if (timeLaunched[iNode] >= microseconds{0}) { - // already launched - continue; - } - microseconds diff{info.cpuTime - info.cudaTime}, cpuWait{0}, cudaWait{0}; - - bool goToNextCandidate = false; - - for (auto *serverInfo : info.serverInfos) { - if (serverInfo->isScalar) - continue; - - // dependencies not computed yet - if (timeLaunched[serverInfo->iNode] < microseconds{0}) { - goToNextCandidate = true; - break; - } - if (computeInGPU[serverInfo->iNode]) { - cpuWait = - std::max(cpuWait, timeLaunched[serverInfo->iNode] + serverInfo->cudaTime + d2hTime - simulatedTime); - } else { - cudaWait = - std::max(cudaWait, timeLaunched[serverInfo->iNode] + serverInfo->cpuTime + h2dTime - simulatedTime); - } - } - - if (goToNextCandidate) { - continue; - } - - diff += cpuWait - cudaWait; - if (diff < minDiff) { - minDiff = diff; - cpuDelay = cpuWait; - cpuCandidate = &info; - } - if (diff > maxDiff && info.absArg->canComputeBatchWithCuda()) { - maxDiff = diff; - cudaDelay = cudaWait; - cudaCandidate = &info; - } - } - - auto calcDiff = [](const NodeInfo *nodeInfo) { return nodeInfo->cpuTime - nodeInfo->cudaTime; }; - if (cpuCandidate && calcDiff(cpuCandidate) > diffThreshold) - cpuCandidate = nullptr; - if (cudaCandidate && -calcDiff(cudaCandidate) > diffThreshold) - cudaCandidate = nullptr; - // don't compute same node twice - if (cpuCandidate == cudaCandidate && !cpuNode && !cudaNode) { - if (minDiff < microseconds{0}) - cudaCandidate = nullptr; - else - cpuCandidate = nullptr; - } - if (cpuCandidate && !cpuNode) { - cpuNode = cpuCandidate; - timeLaunched[cpuNode->iNode] = simulatedTime + cpuDelay; - computeInGPU[cpuNode->iNode] = false; - nNodes--; - } - if (cudaCandidate && !cudaNode) { - cudaNode = cudaCandidate; - timeLaunched[cudaNode->iNode] = simulatedTime + cudaDelay; - computeInGPU[cudaNode->iNode] = true; - nNodes--; - } - - microseconds etaCPU{microseconds::max()}, etaCUDA{microseconds::max()}; - if (cpuNode) { - etaCPU = timeLaunched[cpuNode->iNode] + cpuNode->cpuTime; - } - if (cudaNode) { - etaCUDA = timeLaunched[cudaNode->iNode] + cudaNode->cudaTime; - } - simulatedTime = std::min(etaCPU, etaCUDA); - if (etaCPU < etaCUDA) - cpuNode = nullptr; - else - cudaNode = nullptr; - } // while(nNodes) - return simulatedTime; -} - -std::vector selectNodesForGPU(std::vector const &nodes) -{ - using namespace std::chrono; - - // Assign nodes to GPU using a greedy algorithm: for the number of bytes - // in this benchmark we take the maximum size of spans in the dataset. - std::size_t nEvents = 1; - for (auto const &node : nodes) { - nEvents = std::max(nEvents, node.outputSize); - } - - auto transferTimes = RooFit::CUDAHelpers::memcpyBenchmark(nEvents * sizeof(double)); - - microseconds h2dTime = transferTimes.first; - microseconds d2hTime = transferTimes.second; - COUT_DEBUG << "------Copying times------\n"; - COUT_DEBUG << "h2dTime=" << h2dTime.count() << "us\td2hTime=" << d2hTime.count() << "us\n"; - - std::vector diffTimes; - for (auto &info : nodes) { - if (!info.isScalar) - diffTimes.push_back(info.cpuTime - info.cudaTime); - } - microseconds bestTime = microseconds::max(); - microseconds bestThreshold{}; - microseconds ret; - std::vector computeInGPU(nodes.size()); - for (auto &threshold : diffTimes) { - if ((ret = simulateFit(computeInGPU, nodes, h2dTime, d2hTime, microseconds{std::abs(threshold.count())})) < - bestTime) { - bestTime = ret; - bestThreshold = threshold; - } - } - // finalize the marking of the best configuration - simulateFit(computeInGPU, nodes, h2dTime, d2hTime, microseconds{std::abs(bestThreshold.count())}); - - COUT_DEBUG << "Best threshold = " << bestThreshold.count() << " us" << std::endl; - - return computeInGPU; -} - -} // namespace - -namespace ROOT { -namespace Experimental { - -/// Decides which nodes are assigned to the GPU in a cuda fit. In the 1st iteration, -/// everything is computed in CPU for measuring the CPU time. In the 2nd iteration, -/// everything is computed in GPU (if possible) to measure the GPU time. -/// In the 3rd iteration, simulate the computation of the graph by calling simulateFit -/// with every distinct threshold found as timeDiff within the nodes of the graph and select -/// the best configuration. In the end, mark the nodes and handle the details accordingly. -void RooFitDriver::markGPUNodes() -{ - if (_getValInvocations == CPUOnly) { - for (auto &info : _nodes) { - info.copyAfterEvaluation = false; - info.computeInGPU = false; - } - } else if (_getValInvocations == Both) { - auto computeInGPU = selectNodesForGPU(_nodes); - for (std::size_t iNode = 0; iNode < _nodes.size(); ++iNode) { - _nodes[iNode].copyAfterEvaluation = false; - _nodes[iNode].computeInGPU = computeInGPU[iNode]; - } - - // deletion of the timing events (to be replaced later by non-timing events) - for (auto &info : _nodes) { - RooBatchCompute::dispatchCUDA->deleteCudaEvent(info.event); - RooBatchCompute::dispatchCUDA->deleteCudaEvent(info.eventStart); - info.event = info.eventStart = nullptr; - } - } else { - // compute (and time) as much as possible in GPU - for (auto &info : _nodes) { - info.copyAfterEvaluation = false; - info.computeInGPU = !info.isScalar && info.absArg->canComputeBatchWithCuda(); - } - } - - for (auto &info : _nodes) { - // scalar nodes don't need copying - if (!info.isScalar) { - for (auto *clientInfo : info.clientInfos) { - if (info.computeInGPU != clientInfo->computeInGPU) { - info.copyAfterEvaluation = true; - break; - } - } - } - } - - // restore a cudaEventDisableTiming event when necessary - if (_getValInvocations == Both) { - for (auto &info : _nodes) { - if (info.computeInGPU || info.copyAfterEvaluation) - info.event = RooBatchCompute::dispatchCUDA->newCudaEvent(false); - } - - COUT_DEBUG << "------Nodes------\t\t\t\tCpu time: \t Cuda time\n"; - for (auto &info : _nodes) { - COUT_DEBUG << std::setw(20) << info.absArg->GetName() << "\t" << info.absArg << "\t" - << (info.computeInGPU ? "CUDA" : "CPU") << "\t" << info.cpuTime.count() << "us\t" - << info.cudaTime.count() << "us\n"; - } - } -} - -void RooFitDriver::determineOutputSizes() -{ - for (auto &argInfo : _nodes) { - for (auto *serverInfo : argInfo.serverInfos) { - if (!argInfo.absArg->isReducerNode()) { - argInfo.outputSize = std::max(serverInfo->outputSize, argInfo.outputSize); - } - } - } -} - -/// Temporarily change the operation mode of a RooAbsArg until the -/// RooFitDriver gets deleted. -void RooFitDriver::setOperMode(RooAbsArg *arg, RooAbsArg::OperMode opMode) -{ - if (opMode != arg->operMode()) { - _changeOperModeRAIIs.emplace(arg, opMode); - } -} - -RooAbsReal &RooFitDriver::topNode() const -{ - return static_cast(_integralUnfolder->arg()); -} - -void RooFitDriver::print(std::ostream &os) const -{ - std::cout << "--- RooFit BatchMode evaluation ---\n"; - - std::vector widths{9, 37, 20, 9, 10, 20}; - - auto printElement = [&](int iCol, auto const &t) { - const char separator = ' '; - os << separator << std::left << std::setw(widths[iCol]) << std::setfill(separator) << t; - os << "|"; - }; - - auto printHorizontalRow = [&]() { - int n = 0; - for (int w : widths) { - n += w + 2; - } - for (int i = 0; i < n; i++) { - os << '-'; - } - os << "|\n"; - }; - - printHorizontalRow(); - - os << "|"; - printElement(0, "Index"); - printElement(1, "Name"); - printElement(2, "Class"); - printElement(3, "Size"); - printElement(4, "From Data"); - printElement(5, "1st value"); - std::cout << "\n"; - - printHorizontalRow(); - - for (std::size_t iNode = 0; iNode < _nodes.size(); ++iNode) { - auto &nodeInfo = _nodes[iNode]; - RooAbsArg *node = nodeInfo.absArg; - - auto span = _dataMapCPU.at(node); - - os << "|"; - printElement(0, iNode); - printElement(1, node->GetName()); - printElement(2, node->ClassName()); - printElement(3, nodeInfo.outputSize); - printElement(4, nodeInfo.fromDataset); - printElement(5, span[0]); - - std::cout << "\n"; - } - - printHorizontalRow(); -} - -} // namespace Experimental -} // namespace ROOT diff --git a/roofit/roofitcore/src/RooFitDriver.h b/roofit/roofitcore/src/RooFitDriver.h deleted file mode 100644 index 10a2225320443..0000000000000 --- a/roofit/roofitcore/src/RooFitDriver.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Project: RooFit - * Authors: - * Jonas Rembser, CERN 2021 - * Emmanouil Michalainas, CERN 2021 - * - * Copyright (c) 2021, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#ifndef RooFit_RooFitDriver_h -#define RooFit_RooFitDriver_h - -#include "RooFit/Detail/DataMap.h" -#include -#include -#include "RooFit/Detail/Buffers.h" - -#include -#include -#include - -class RooAbsArg; -class RooAbsReal; -class RooAbsCategory; -class RooAbsData; -namespace RooFit { -class NormalizationIntegralUnfolder; -} -class RooSimultaneous; - -namespace ROOT { -namespace Experimental { - -struct NodeInfo; - -class RooFitDriver { -public: - //////////////////// - // Enums and aliases - - using DataSpansMap = std::map>; - - ////////////////////////// - // Public member functions - - RooFitDriver(const RooAbsReal &absReal, RooArgSet const &normSet, - RooFit::BatchModeOption batchMode = RooFit::BatchModeOption::Cpu); - - void setData(RooAbsData const &data, std::string const &rangeName = "", RooSimultaneous const *simPdf = nullptr, - bool splitRange = false, bool skipZeroWeights = false, bool takeGlobalObservablesFromData = true); - void setData(DataSpansMap const &dataSpans); - - ~RooFitDriver(); - std::vector getValues(); - double getVal(); - RooAbsReal &topNode() const; - - void print(std::ostream &os) const; - -private: - /////////////////////////// - // Private member functions - - double getValHeterogeneous(); - void markGPUNodes(); - void assignToGPU(NodeInfo &info); - void computeCPUNode(const RooAbsArg *node, NodeInfo &info); - void setOperMode(RooAbsArg *arg, RooAbsArg::OperMode opMode); - void determineOutputSizes(); - - /////////////////////////// - // Private member variables - - Detail::BufferManager _bufferManager; // The object managing the different buffers for the intermediate results - - const RooFit::BatchModeOption _batchMode = RooFit::BatchModeOption::Off; - int _getValInvocations = 0; - double *_cudaMemDataset = nullptr; - - // used for preserving static info about the computation graph - RooFit::Detail::DataMap _dataMapCPU; - RooFit::Detail::DataMap _dataMapCUDA; - - // the ordered computation graph - std::vector _nodes; - - // used for preserving resources - std::stack> _vectorBuffers; - std::unique_ptr _integralUnfolder; - - // RAII structures to reset state of computation graph after driver destruction - std::stack _changeOperModeRAIIs; - - std::vector> _splittedDataSets; -}; - -} // end namespace Experimental -} // end namespace ROOT - -#endif diff --git a/roofit/roofitcore/src/RooFitLegacy/RooCatTypeLegacy.cxx b/roofit/roofitcore/src/RooFitLegacy/RooCatTypeLegacy.cxx index c90282fb7aeb8..83f6671a056b4 100644 --- a/roofit/roofitcore/src/RooFitLegacy/RooCatTypeLegacy.cxx +++ b/roofit/roofitcore/src/RooFitLegacy/RooCatTypeLegacy.cxx @@ -18,7 +18,7 @@ \class RooCatType \ingroup Roofitlegacy -RooCatType is an auxilary class for RooAbsCategory and defines a +RooCatType is an auxiliary class for RooAbsCategory and defines a a single category state. The class holds a string label and an integer index value which define the state **/ @@ -28,12 +28,9 @@ index value which define the state #include - using namespace std; ClassImp(RooCatType); -; - //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofitcore/src/RooFitLegacy/RooMinuit.cxx b/roofit/roofitcore/src/RooFitLegacy/RooMinuit.cxx deleted file mode 100644 index b69d0a48d3312..0000000000000 --- a/roofit/roofitcore/src/RooFitLegacy/RooMinuit.cxx +++ /dev/null @@ -1,1253 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooMinuit.cxx -\class RooMinuit -\ingroup Roofitlegacy - -RooMinuit is a wrapper class around TFitter/TMinuit that -provides a seamless interface between the MINUIT functionality -and the native RooFit interface. -RooMinuit can minimize any RooAbsReal function with respect to -its parameters. Usual choices for minimization are RooNLLVar -and RooChi2Var -RooMinuit has methods corresponding to MINUIT functions like -hesse(), migrad(), minos() etc. In each of these function calls -the state of the MINUIT engine is synchronized with the state -of the RooFit variables: any change in variables, change -in the constant status etc is forwarded to MINUIT prior to -execution of the MINUIT call. Afterwards the RooFit objects -are resynchronized with the output state of MINUIT: changes -parameter values, errors are propagated. -Various methods are available to control verbosity, profiling, -automatic PDF optimization. -**/ - -// At least for building the implementation we have to suppress the deprecation warning -#define __ROOFIT_SUPPRESS_ROOMINIMIZER_DEPRECATION_WARNING -#include "RooFitLegacy/RooMinuit.h" -#undef __ROOFIT_SUPPRESS_ROOMINIMIZER_DEPRECATION_WARNING - -#include "TClass.h" - -#include -#include -#include -#include "TMarker.h" -#include "TGraph.h" -#include "TStopwatch.h" -#include "TFitter.h" -#include "TMinuit.h" -#include "TMatrixDSym.h" -#include "RooArgSet.h" -#include "RooArgList.h" -#include "RooAbsReal.h" -#include "RooAbsRealLValue.h" -#include "RooRealVar.h" -#include "RooFitResult.h" -#include "RooAbsPdf.h" -#include "../RooSentinel.h" -#include "RooMsgService.h" -#include "RooPlot.h" - - -#if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3) -char* operator+( streampos&, char* ); -#endif - -using namespace std; - - -TVirtualFitter *RooMinuit::_theFitter = nullptr; - - - -//////////////////////////////////////////////////////////////////////////////// -/// Cleanup method called by atexit handler installed by RooSentinel -/// to delete all global heap objects when the program is terminated - -void RooMinuit::cleanup() -{ - if (_theFitter) { - delete _theFitter ; - _theFitter =0 ; - } -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct MINUIT interface to given function. Function can be anything, -/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2 -/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition -/// of a RooNLLVar plus a penalty or constraint term. This class propagates -/// all RooFit information (floating parameters, their values and errors) -/// to MINUIT before each MINUIT call and propagates all MINUIT information -/// back to the RooFit object at the end of each call (updated parameter -/// values, their (asymmetric errors) etc. The default MINUIT error level -/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel() -/// value of the input function. - -RooMinuit::RooMinuit(RooAbsReal& function) -{ - RooSentinel::activate() ; - - // Store function reference - _evalCounter = 0 ; - _extV = 0 ; - _func = &function ; - _logfile = 0 ; - _optConst = false ; - _verbose = false ; - _profile = false ; - _handleLocalErrors = true ; - _printLevel = 1 ; - _printEvalErrors = 10 ; - _warnLevel = -999 ; - _maxEvalMult = 500 ; - _doEvalErrorWall = true ; - - // Examine parameter list - RooArgSet* paramSet = function.getParameters(RooArgSet()) ; - RooArgList paramList(*paramSet) ; - delete paramSet ; - - _floatParamList = (RooArgList*) paramList.selectByAttrib("Constant",false) ; - if (_floatParamList->getSize()>1) { - _floatParamList->sort() ; - } - _floatParamList->setName("floatParamList") ; - - _constParamList = (RooArgList*) paramList.selectByAttrib("Constant",true) ; - if (_constParamList->getSize()>1) { - _constParamList->sort() ; - } - _constParamList->setName("constParamList") ; - - // Remove all non-RooRealVar parameters from list (MINUIT cannot handle them) - for (RooAbsArg * arg : *_floatParamList) { - if (!arg->IsA()->InheritsFrom(RooAbsRealLValue::Class())) { - coutW(Minimization) << "RooMinuit::RooMinuit: removing parameter " << arg->GetName() - << " from list because it is not of type RooRealVar" << endl ; - _floatParamList->remove(*arg) ; - } - } - _nPar = _floatParamList->getSize() ; - - updateFloatVec() ; - - // Save snapshot of initial lists - _initFloatParamList = (RooArgList*) _floatParamList->snapshot(false) ; - _initConstParamList = (RooArgList*) _constParamList->snapshot(false) ; - - // Initialize MINUIT - Int_t nPar= _floatParamList->getSize() + _constParamList->getSize() ; - if (_theFitter) delete _theFitter ; - _theFitter = new TFitter(nPar*2+1) ; //WVE Kludge, nPar*2 works around TMinuit memory allocation bug - _theFitter->SetObjectFit(this) ; - - // Shut up for now - setPrintLevel(-1) ; - _theFitter->Clear(); - - // Tell MINUIT to use our global glue function - _theFitter->SetFCN(RooMinuitGlue); - - // Use +0.5 for 1-sigma errors - setErrorLevel(function.defaultErrorLevel()) ; - - // Declare our parameters to MINUIT - synchronize(false) ; - - // Reset the *largest* negative log-likelihood value we have seen so far - _maxFCN= -1e30 ; - _numBadNLL = 0 ; - - // Now set default verbosity - if (RooMsgService::instance().silentMode()) { - setWarnLevel(-1) ; - setPrintLevel(-1) ; - } else { - setWarnLevel(1) ; - setPrintLevel(1) ; - } -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooMinuit::~RooMinuit() -{ - delete _floatParamList ; - delete _initFloatParamList ; - delete _constParamList ; - delete _initConstParamList ; - if (_extV) { - delete _extV ; - } -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Change MINUIT strategy to istrat. Accepted codes -/// are 0,1,2 and represent MINUIT strategies for dealing -/// most efficiently with fast FCNs (0), expensive FCNs (2) -/// and 'intermediate' FCNs (1) - -void RooMinuit::setStrategy(Int_t istrat) -{ - double stratArg(istrat) ; - _theFitter->ExecuteCommand("SET STR",&stratArg,1) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Set the level for MINUIT error analysis to the given -/// value. This function overrides the default value -/// that is taken in the RooMinuit constructor from -/// the defaultErrorLevel() method of the input function - -void RooMinuit::setErrorLevel(double level) -{ - _theFitter->ExecuteCommand("SET ERR",&level,1); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Change MINUIT epsilon - -void RooMinuit::setEps(double eps) -{ - _theFitter->ExecuteCommand("SET EPS",&eps,1) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Enable internal likelihood offsetting for enhanced numeric precision - -void RooMinuit::setOffsetting(bool flag) -{ - _func->enableOffsetting(flag) ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Parse traditional RooAbsPdf::fitTo driver options -/// -/// s - Run Hesse first to estimate initial step size -/// m - Run Migrad only -/// h - Run Hesse to estimate errors -/// v - Verbose mode -/// l - Log parameters after each Minuit steps to file -/// t - Activate profile timer -/// r - Save fit result -/// 0 - Run Migrad with strategy 0 - -RooFitResult* RooMinuit::fit(const char* options) -{ - if (_floatParamList->empty()) { - return 0 ; - } - - _theFitter->SetObjectFit(this) ; - - TString opts(options) ; - opts.ToLower() ; - - // Initial configuration - if (opts.Contains("v")) setVerbose(1) ; - if (opts.Contains("t")) setProfile(1) ; - if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ; - if (opts.Contains("c")) optimizeConst(1) ; - - // Fitting steps - if (opts.Contains("s")) hesse() ; - if (opts.Contains("0")) setStrategy(0) ; - migrad() ; - if (opts.Contains("0")) setStrategy(1) ; - if (opts.Contains("h")||!opts.Contains("m")) hesse() ; - if (!opts.Contains("m")) minos() ; - - return (opts.Contains("r")) ? save() : 0 ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute MIGRAD. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::migrad() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - arglist[1]= 1.0; // tolerance - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("MIGRAD",arglist,2); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("MIGRAD",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute HESSE. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::hesse() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("HESSE",arglist,1); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("HESSE",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute MINOS. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::minos() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("MINOS",arglist,1); - // check also the status of Minos looking at fCstatu - if (_status == 0 && gMinuit->fCstatu != "SUCCESSFUL") { - if (gMinuit->fCstatu == "FAILURE" || - gMinuit->fCstatu == "PROBLEMS") _status = 5; - _status = 6; - } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("MINOS",_status) ; - return _status ; -} - - -// added FMV, 08/18/03 - -//////////////////////////////////////////////////////////////////////////////// -/// Execute MINOS for given list of parameters. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::minos(const RooArgSet& minosParamList) -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - Int_t nMinosPar(0) ; - double* arglist = new double[_nPar+1]; - - if (minosParamList.getSize()>0) { - for(RooAbsArg * arg : minosParamList) { - RooAbsArg* par = _floatParamList->find(arg->GetName()); - if (par && !par->isConstant()) { - Int_t index = _floatParamList->index(par); - nMinosPar++; - arglist[nMinosPar]=index+1; - } - } - } - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("MINOS",arglist,1+nMinosPar); - // check also the status of Minos looking at fCstatu - if (_status == 0 && gMinuit->fCstatu != "SUCCESSFUL") { - if (gMinuit->fCstatu == "FAILURE" || - gMinuit->fCstatu == "PROBLEMS") _status = 5; - _status = 6; - } - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - delete[] arglist ; - - saveStatus("MINOS",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute SEEK. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::seek() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("SEEK",arglist,1); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("SEEK",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute SIMPLEX. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::simplex() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - arglist[1]= 1.0; // tolerance - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("SIMPLEX",arglist,2); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("SIMPLEX",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Execute IMPROVE. Changes in parameter values -/// and calculated errors are automatically -/// propagated back the RooRealVars representing -/// the floating parameters in the MINUIT operation - -Int_t RooMinuit::improve() -{ - if (_floatParamList->empty()) { - return -1 ; - } - - _theFitter->SetObjectFit(this) ; - - double arglist[2]; - arglist[0]= _maxEvalMult*_nPar; // maximum iterations - - synchronize(_verbose) ; - profileStart() ; - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - RooAbsReal::clearEvalErrorLog() ; - _status= _theFitter->ExecuteCommand("IMPROVE",arglist,1); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - profileStop() ; - backProp() ; - - saveStatus("IMPROVE",_status) ; - - return _status ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Change the MINUIT internal printing level - -Int_t RooMinuit::setPrintLevel(Int_t newLevel) -{ - Int_t ret = _printLevel ; - double arg(newLevel) ; - _theFitter->ExecuteCommand("SET PRINT",&arg,1); - _printLevel = newLevel ; - return ret ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Instruct MINUIT to suppress warnings - -void RooMinuit::setNoWarn() -{ - double arg(0) ; - _theFitter->ExecuteCommand("SET NOWARNINGS",&arg,1); - _warnLevel = -1 ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Set MINUIT warning level to given level - -Int_t RooMinuit::setWarnLevel(Int_t newLevel) -{ - if (newLevel==_warnLevel) { - return _warnLevel ; - } - - Int_t ret = _warnLevel ; - double arg(newLevel) ; - - if (newLevel>=0) { - _theFitter->ExecuteCommand("SET WARNINGS",&arg,1); - } else { - double arg2(0) ; - _theFitter->ExecuteCommand("SET NOWARNINGS",&arg2,1); - } - _warnLevel = newLevel ; - - return ret ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Internal function to synchronize TMinuit with current -/// information in RooAbsReal function parameters - -bool RooMinuit::synchronize(bool verbose) -{ - Int_t oldPrint = setPrintLevel(-1) ; - gMinuit->fNwrmes[0] = 0; // to clear buffer - Int_t oldWarn = setWarnLevel(-1) ; - - bool constValChange(false) ; - bool constStatChange(false) ; - - Int_t index(0) ; - - // Handle eventual migrations from constParamList -> floatParamList - for(index= 0; index < _constParamList->getSize() ; index++) { - RooRealVar *par= dynamic_cast(_constParamList->at(index)) ; - if (!par) continue ; - - RooRealVar *oldpar= dynamic_cast(_initConstParamList->at(index)) ; - if (!oldpar) continue ; - - // Test if constness changed - if (!par->isConstant()) { - - // Remove from constList, add to floatList - _constParamList->remove(*par) ; - _floatParamList->add(*par) ; - _initFloatParamList->addClone(*oldpar) ; - _initConstParamList->remove(*oldpar) ; - constStatChange=true ; - _nPar++ ; - - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now floating." << endl ; - } - } - - // Test if value changed - if (par->getVal()!= oldpar->getVal()) { - constValChange=true ; - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: value of constant parameter " << par->GetName() - << " changed from " << oldpar->getVal() << " to " << par->getVal() << endl ; - } - } - - } - - // Update reference list - _initConstParamList->assign(*_constParamList) ; - - - // Synchronize MINUIT with function state - for(index= 0; index < _nPar; index++) { - RooRealVar *par= dynamic_cast(_floatParamList->at(index)) ; - if (!par) continue ; - - double pstep(0) ; - double pmin(0) ; - double pmax(0) ; - - if(!par->isConstant()) { - - // Verify that floating parameter is indeed of type RooRealVar - if (!par->IsA()->InheritsFrom(RooRealVar::Class())) { - coutW(Minimization) << "RooMinuit::fit: Error, non-constant parameter " << par->GetName() - << " is not of type RooRealVar, skipping" << endl ; - continue ; - } - - // Set the limits, if not infinite - if (par->hasMin() && par->hasMax()) { - pmin = par->getMin(); - pmax = par->getMax(); - } - - // Calculate step size - pstep= par->getError(); - if(pstep <= 0) { - // Floating parameter without error estitimate - if (par->hasMin() && par->hasMax()) { - pstep= 0.1*(pmax-pmin); - - // Trim default choice of error if within 2 sigma of limit - if (pmax - par->getVal() < 2*pstep) { - pstep = (pmax - par->getVal())/2 ; - } else if (par->getVal() - pmin < 2*pstep) { - pstep = (par->getVal() - pmin )/2 ; - } - - // If trimming results in zero error, restore default - if (pstep==0) { - pstep= 0.1*(pmax-pmin); - } - - } else { - pstep=1 ; - } - if(_verbose) { - coutW(Minimization) << "RooMinuit::synchronize: WARNING: no initial error estimate available for " - << par->GetName() << ": using " << pstep << endl; - } - } - } else { - pmin = par->getVal() ; - pmax = par->getVal() ; - } - - // Extract previous information - double oldVar,oldVerr,oldVlo,oldVhi ; - char oldParname[100] ; - Int_t ierr = _theFitter->GetParameter(index,oldParname,oldVar,oldVerr,oldVlo,oldVhi) ; - - // Determine if parameters is currently fixed in MINUIT - - Int_t ix ; - bool oldFixed(false) ; - if (ierr>=0) { - for (ix = 1; ix <= gMinuit->fNpfix; ++ix) { - if (gMinuit->fIpfix[ix-1] == index+1) oldFixed=true ; - } - } - - if (par->isConstant() && !oldFixed) { - - // Parameter changes floating -> constant : update only value if necessary - if (oldVar!=par->getVal()) { - double arglist[2] ; - arglist[0] = index+1 ; - arglist[1] = par->getVal() ; - _theFitter->ExecuteCommand("SET PAR",arglist,2) ; - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: value of parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ; - } - } - - _theFitter->FixParameter(index) ; - constStatChange=true ; - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now fixed." << endl ; - } - - } else if (par->isConstant() && oldFixed) { - - // Parameter changes constant -> constant : update only value if necessary - if (oldVar!=par->getVal()) { - double arglist[2] ; - arglist[0] = index+1 ; - arglist[1] = par->getVal() ; - _theFitter->ExecuteCommand("SET PAR",arglist,2) ; - constValChange=true ; - - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: value of fixed parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ; - } - } - - } else { - - if (!par->isConstant() && oldFixed) { - _theFitter->ReleaseParameter(index) ; - constStatChange=true ; - - if (verbose) { - coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now floating." << endl ; - } - } - - // Parameter changes constant -> floating : update all if necessary - if (oldVar!=par->getVal() || oldVlo!=pmin || oldVhi != pmax || oldVerr!=pstep) { - _theFitter->SetParameter(index, par->GetName(), par->getVal(), pstep, pmin, pmax); - } - - // Inform user about changes in verbose mode - if (verbose && ierr>=0) { - // if ierr<0, par was moved from the const list and a message was already printed - - if (oldVar!=par->getVal()) { - coutI(Minimization) << "RooMinuit::synchronize: value of parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ; - } - if (oldVlo!=pmin || oldVhi!=pmax) { - coutI(Minimization) << "RooMinuit::synchronize: limits of parameter " << par->GetName() << " changed from [" << oldVlo << "," << oldVhi - << "] to [" << pmin << "," << pmax << "]" << endl ; - } - - // If oldVerr=0, then parameter was previously fixed - if (oldVerr!=pstep && oldVerr!=0) { - coutI(Minimization) << "RooMinuit::synchronize: error/step size of parameter " << par->GetName() << " changed from " << oldVerr << " to " << pstep << endl ; - } - } - } - } - - - gMinuit->fNwrmes[0] = 0; // to clear buffer - oldWarn = setWarnLevel(oldWarn) ; - oldPrint = setPrintLevel(oldPrint) ; - - if (_optConst) { - if (constStatChange) { - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - - coutI(Minimization) << "RooMinuit::synchronize: set of constant parameters changed, rerunning const optimizer" << endl ; - _func->constOptimizeTestStatistic(RooAbsArg::ConfigChange) ; - } else if (constValChange) { - coutI(Minimization) << "RooMinuit::synchronize: constant parameter values changed, rerunning const optimizer" << endl ; - _func->constOptimizeTestStatistic(RooAbsArg::ValueChange) ; - } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - - } - - updateFloatVec() ; - - return 0 ; -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// If flag is true, perform constant term optimization on -/// function being minimized. - -void RooMinuit::optimizeConst(Int_t flag) -{ - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ; - - if (_optConst && !flag){ - if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: deactivating const optimization" << endl ; - _func->constOptimizeTestStatistic(RooAbsArg::DeActivate,flag>1) ; - _optConst = flag ; - } else if (!_optConst && flag) { - if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: activating const optimization" << endl ; - _func->constOptimizeTestStatistic(RooAbsArg::Activate,flag>1) ; - _optConst = flag ; - } else if (_optConst && flag) { - if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: const optimization already active" << endl ; - } else { - if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: const optimization wasn't active" << endl ; - } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ; - -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Save and return a RooFitResult snaphot of current minimizer status. -/// This snapshot contains the values of all constant parameters, -/// the value of all floating parameters at RooMinuit construction and -/// after the last MINUIT operation, the MINUIT status, variance quality, -/// EDM setting, number of calls with evaluation problems, the minimized -/// function value and the full correlation matrix - -RooFitResult* RooMinuit::save(const char* userName, const char* userTitle) -{ - TString name,title ; - name = userName ? userName : Form("%s", _func->GetName()) ; - title = userTitle ? userTitle : Form("%s", _func->GetTitle()) ; - - if (_floatParamList->empty()) { - RooFitResult* fitRes = new RooFitResult(name,title) ; - fitRes->setConstParList(*_constParamList) ; - fitRes->setInitParList(RooArgList()) ; - fitRes->setFinalParList(RooArgList()) ; - fitRes->setStatus(-999) ; - fitRes->setCovQual(-999) ; - fitRes->setMinNLL(_func->getVal()) ; - fitRes->setNumInvalidNLL(0) ; - fitRes->setEDM(-999) ; - return fitRes ; - } - - RooFitResult* fitRes = new RooFitResult(name,title) ; - - // Move eventual fixed parameters in floatList to constList - Int_t i ; - RooArgList saveConstList(*_constParamList) ; - RooArgList saveFloatInitList(*_initFloatParamList) ; - RooArgList saveFloatFinalList(*_floatParamList) ; - for (i=0 ; i<_floatParamList->getSize() ; i++) { - RooAbsArg* par = _floatParamList->at(i) ; - if (par->isConstant()) { - saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),true) ; - saveFloatFinalList.remove(*par) ; - saveConstList.add(*par) ; - } - } - saveConstList.sort() ; - - fitRes->setConstParList(saveConstList) ; - fitRes->setInitParList(saveFloatInitList) ; - - double edm, errdef, minVal; - Int_t nvpar, nparx; - Int_t icode = _theFitter->GetStats(minVal, edm, errdef, nvpar, nparx); - fitRes->setStatus(_status) ; - fitRes->setCovQual(icode) ; - fitRes->setMinNLL(minVal) ; - fitRes->setNumInvalidNLL(_numBadNLL) ; - fitRes->setEDM(edm) ; - fitRes->setFinalParList(saveFloatFinalList) ; - if (!_extV) { - fitRes->fillCorrMatrix() ; - } else { - fitRes->setCovarianceMatrix(*_extV) ; - } - - fitRes->setStatusHistory(_statusHistory) ; - - return fitRes ; -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Create and draw a TH2 with the error contours in parameters var1 and v2 at up to 6 'sigma' settings -/// where 'sigma' is calculated as n*n*errorLevel - -RooPlot* RooMinuit::contour(RooRealVar& var1, RooRealVar& var2, double n1, double n2, double n3, double n4, double n5, double n6) -{ - - _theFitter->SetObjectFit(this) ; - - RooArgList* paramSave = (RooArgList*) _floatParamList->snapshot() ; - - // Verify that both variables are floating parameters of PDF - Int_t index1= _floatParamList->index(&var1); - if(index1 < 0) { - coutE(Minimization) << "RooMinuit::contour(" << GetName() - << ") ERROR: " << var1.GetName() << " is not a floating parameter of " << _func->GetName() << endl ; - return 0; - } - - Int_t index2= _floatParamList->index(&var2); - if(index2 < 0) { - coutE(Minimization) << "RooMinuit::contour(" << GetName() - << ") ERROR: " << var2.GetName() << " is not a floating parameter of PDF " << _func->GetName() << endl ; - return 0; - } - - // create and draw a frame - RooPlot* frame = new RooPlot(var1,var2) ; - - // draw a point at the current parameter values - TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8); - frame->addObject(point) ; - - // remember our original value of ERRDEF - double errdef= gMinuit->fUp; - - double n[6] ; - n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ; - - - for (Int_t ic = 0 ; ic<6 ; ic++) { - if(n[ic] > 0) { - // set the value corresponding to an n1-sigma contour - gMinuit->SetErrorDef(n[ic]*n[ic]*errdef); - // calculate and draw the contour - TGraph* graph= (TGraph*)gMinuit->Contour(50, index1, index2); - if (!graph) { - coutE(Minimization) << "RooMinuit::contour(" << GetName() << ") ERROR: MINUIT did not return a contour graph for n=" << n[ic] << endl ; - } else { - graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ; - graph->SetLineStyle(ic+1) ; - graph->SetLineWidth(2) ; - graph->SetLineColor(kBlue) ; - frame->addObject(graph,"L") ; - } - } - } - - // restore the original ERRDEF - gMinuit->SetErrorDef(errdef); - - // restore parameter values - _floatParamList->assign(*paramSave) ; - delete paramSave ; - - - return frame ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Change the file name for logging of a RooMinuit of all MINUIT steppings -/// through the parameter space. If inLogfile is null, the current log file -/// is closed and logging is stopped. - -bool RooMinuit::setLogFile(const char* inLogfile) -{ - if (_logfile) { - coutI(Minimization) << "RooMinuit::setLogFile: closing previous log file" << endl ; - _logfile->close() ; - delete _logfile ; - _logfile = 0 ; - } - _logfile = new ofstream(inLogfile) ; - if (!_logfile->good()) { - coutI(Minimization) << "RooMinuit::setLogFile: cannot open file " << inLogfile << endl ; - _logfile->close() ; - delete _logfile ; - _logfile= 0; - } - return false ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Access PDF parameter value by ordinal index (needed by MINUIT) - -double RooMinuit::getPdfParamVal(Int_t index) -{ - return ((RooRealVar*)_floatParamList->at(index))->getVal() ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Access PDF parameter error by ordinal index (needed by MINUIT) - -double RooMinuit::getPdfParamErr(Int_t index) -{ - return ((RooRealVar*)_floatParamList->at(index))->getError() ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Modify PDF parameter value by ordinal index (needed by MINUIT) - -bool RooMinuit::setPdfParamVal(Int_t index, double value, bool verbose) -{ - //RooRealVar* par = (RooRealVar*)_floatParamList->at(index) ; - RooRealVar* par = (RooRealVar*)_floatParamVec[index] ; - - if (par->getVal()!=value) { - if (verbose) cout << par->GetName() << "=" << value << ", " ; - par->setVal(value) ; - return true ; - } - - return false ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Modify PDF parameter error by ordinal index (needed by MINUIT) - -void RooMinuit::setPdfParamErr(Int_t index, double value) -{ - ((RooRealVar*)_floatParamList->at(index))->setError(value) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Modify PDF parameter error by ordinal index (needed by MINUIT) - -void RooMinuit::clearPdfParamAsymErr(Int_t index) -{ - ((RooRealVar*)_floatParamList->at(index))->removeAsymError() ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Modify PDF parameter error by ordinal index (needed by MINUIT) - -void RooMinuit::setPdfParamErr(Int_t index, double loVal, double hiVal) -{ - ((RooRealVar*)_floatParamList->at(index))->setAsymError(loVal,hiVal) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Start profiling timer - -void RooMinuit::profileStart() -{ - if (_profile) { - _timer.Start() ; - _cumulTimer.Start(false) ; - } -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Stop profiling timer and report results of last session - -void RooMinuit::profileStop() -{ - if (_profile) { - _timer.Stop() ; - _cumulTimer.Stop() ; - coutI(Minimization) << "Command timer: " ; _timer.Print() ; - coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ; - } -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Transfer MINUIT fit results back into RooFit objects - -void RooMinuit::backProp() -{ - double val,err,vlo,vhi, eplus, eminus, eparab, globcc; - char buffer[64000]; - Int_t index ; - for(index= 0; index < _nPar; index++) { - _theFitter->GetParameter(index, buffer, val, err, vlo, vhi); - setPdfParamVal(index, val); - _theFitter->GetErrors(index, eplus, eminus, eparab, globcc); - - // Set the parabolic error - setPdfParamErr(index, err); - - if(eplus > 0 || eminus < 0) { - // Store the asymmetric error, if it is available - setPdfParamErr(index, eminus,eplus); - } else { - // Clear the asymmetric error - clearPdfParamAsymErr(index) ; - } - } -} - - -//////////////////////////////////////////////////////////////////////////////// - -void RooMinuit::updateFloatVec() -{ - _floatParamVec.clear() ; - _floatParamVec.resize(_floatParamList->getSize()) ; - Int_t i(0) ; - for (auto* arg : *_floatParamList) { - _floatParamVec[i++] = arg ; - } -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Apply results of given external covariance matrix. i.e. propagate its errors -/// to all RRV parameter representations and give this matrix instead of the -/// HESSE matrix at the next save() call - -void RooMinuit::applyCovarianceMatrix(TMatrixDSym& V) -{ - _extV = (TMatrixDSym*) V.Clone() ; - - for (Int_t i=0 ; iat(i)->isConstant()) { - continue ; - } - RooMinuit* context = (RooMinuit*) RooMinuit::_theFitter->GetObjectFit() ; - if (context && context->_verbose) - cout << "setting parameter " << i << " error to " << sqrt((*_extV)(i,i)) << endl ; - setPdfParamErr(i, sqrt((*_extV)(i,i))) ; - } - -} - - - - -void RooMinuitGlue(Int_t& /*np*/, double* /*gin*/, - double &f, double *par, Int_t /*flag*/) -{ - // Static function that interfaces minuit with RooMinuit - - // Retrieve fit context and its components - RooMinuit* context = (RooMinuit*) RooMinuit::_theFitter->GetObjectFit() ; - ofstream* logf = context->logfile() ; - double& maxFCN = context->maxFCN() ; - bool verbose = context->_verbose ; - - // Set the parameter values for this iteration - Int_t nPar= context->getNPar(); - for(Int_t index= 0; index < nPar; index++) { - if (logf) (*logf) << par[index] << " " ; - context->setPdfParamVal(index, par[index],verbose); - } - - // Calculate the function for these parameters - RooAbsReal::setHideOffset(false) ; - f= context->_func->getVal() ; - RooAbsReal::setHideOffset(true) ; - context->_evalCounter++ ; - if (RooAbsReal::numEvalErrors()>0 || f>1e30) { - - if (context->_printEvalErrors>=0) { - - if (context->_doEvalErrorWall) { - oocoutW(context,Minimization) << "RooMinuitGlue: Minimized function has error status." << endl - << "Returning maximum FCN so far (" << maxFCN - << ") to force MIGRAD to back out of this region. Error log follows" << endl ; - } else { - oocoutW(context,Minimization) << "RooMinuitGlue: Minimized function has error status but is ignored" << endl ; - } - - bool first(true) ; - ooccoutW(context,Minimization) << "Parameter values: " ; - for(auto * var : static_range_cast(*context->_floatParamList)) { - if (first) { first = false ; } else ooccoutW(context,Minimization) << ", " ; - ooccoutW(context,Minimization) << var->GetName() << "=" << var->getVal() ; - } - ooccoutW(context,Minimization) << endl ; - - RooAbsReal::printEvalErrors(ooccoutW(context,Minimization),context->_printEvalErrors) ; - ooccoutW(context,Minimization) << endl ; - } - - if (context->_doEvalErrorWall) { - f = maxFCN+1 ; - } - - RooAbsReal::clearEvalErrorLog() ; - context->_numBadNLL++ ; - } else if (f>maxFCN) { - maxFCN = f ; - } - - // Optional logging - if (logf) (*logf) << setprecision(15) << f << setprecision(4) << endl; - if (verbose) { - cout << "\nprevFCN" << (context->_func->isOffsetting()?"-offset":"") << " = " << setprecision(10) << f << setprecision(4) << " " ; - cout.flush() ; - } -} diff --git a/roofit/roofitcore/src/RooFitResult.cxx b/roofit/roofitcore/src/RooFitResult.cxx index 95add747017bf..2c2faf6d75272 100644 --- a/roofit/roofitcore/src/RooFitResult.cxx +++ b/roofit/roofitcore/src/RooFitResult.cxx @@ -22,7 +22,7 @@ /// * Values of all constant parameters /// * Initial and final values of floating parameters with error /// * Correlation matrix and global correlation coefficients -/// * NLL and EDM at mininum +/// * NLL and EDM at minimum /// /// No references to the fitted PDF and dataset are stored /// @@ -64,8 +64,8 @@ ClassImp(RooFitResult); /// Constructor with name and title RooFitResult::RooFitResult(const char* name, const char* title) : - TNamed(name,title), _constPars(0), _initPars(0), _finalPars(0), _globalCorr(0), _randomPars(0), _Lt(0), - _CM(0), _VM(0), _GC(0) + TNamed(name,title), _constPars(nullptr), _initPars(nullptr), _finalPars(nullptr), _globalCorr(nullptr), _randomPars(nullptr), _Lt(nullptr), + _CM(nullptr), _VM(nullptr), _GC(nullptr) { if (name) appendToDir(this,true) ; } @@ -83,18 +83,24 @@ RooFitResult::RooFitResult(const RooFitResult& other) : _numBadNLL(other._numBadNLL), _minNLL(other._minNLL), _edm(other._edm), - _globalCorr(0), - _randomPars(0), - _Lt(0), - _CM(0), - _VM(0), - _GC(0), + _globalCorr(nullptr), + _randomPars(nullptr), + _Lt(nullptr), + _CM(nullptr), + _VM(nullptr), + _GC(nullptr), _statusHistory(other._statusHistory) { - _constPars = (RooArgList*) other._constPars->snapshot() ; - _initPars = (RooArgList*) other._initPars->snapshot() ; - _finalPars = (RooArgList*) other._finalPars->snapshot() ; - if (other._randomPars) _randomPars = (RooArgList*) other._randomPars->snapshot() ; + _constPars = new RooArgList; + other._constPars->snapshot(*_constPars); + _initPars = new RooArgList; + other._initPars->snapshot(*_initPars); + _finalPars = new RooArgList; + other._finalPars->snapshot(*_finalPars); + if (other._randomPars) { + _randomPars = new RooArgList; + other._randomPars->snapshot(*_randomPars); + } if (other._Lt) _Lt = new TMatrix(*other._Lt); if (other._VM) _VM = new TMatrixDSym(*other._VM) ; if (other._CM) _CM = new TMatrixDSym(*other._CM) ; @@ -134,7 +140,8 @@ RooFitResult::~RooFitResult() void RooFitResult::setConstParList(const RooArgList& list) { if (_constPars) delete _constPars ; - _constPars = (RooArgList*) list.snapshot() ; + _constPars = new RooArgList; + list.snapshot(*_constPars); for(auto* rrv : dynamic_range_cast(*_constPars)) { if (rrv) { rrv->deleteSharedProperties() ; @@ -150,7 +157,8 @@ void RooFitResult::setConstParList(const RooArgList& list) void RooFitResult::setInitParList(const RooArgList& list) { if (_initPars) delete _initPars ; - _initPars = (RooArgList*) list.snapshot() ; + _initPars = new RooArgList; + list.snapshot(*_initPars); for(auto* rrv : dynamic_range_cast(*_initPars)) { if (rrv) { rrv->deleteSharedProperties() ; @@ -166,7 +174,8 @@ void RooFitResult::setInitParList(const RooArgList& list) void RooFitResult::setFinalParList(const RooArgList& list) { if (_finalPars) delete _finalPars ; - _finalPars = (RooArgList*) list.snapshot() ; + _finalPars = new RooArgList; + list.snapshot(*_finalPars); for(auto* rrv : dynamic_range_cast(*_finalPars)) { if (rrv) { @@ -235,14 +244,14 @@ RooPlot *RooFitResult::plotOn(RooPlot *frame, const char *parName1, const char * { // lookup the input parameters by name: we require that they were floated in our fit const RooRealVar *par1= dynamic_cast(floatParsFinal().find(parName1)); - if(0 == par1) { + if(nullptr == par1) { coutE(InputArguments) << "RooFitResult::correlationPlot: parameter not floated in fit: " << parName1 << endl; - return 0; + return nullptr; } const RooRealVar *par2= dynamic_cast(floatParsFinal().find(parName2)); - if(0 == par2) { + if(nullptr == par2) { coutE(InputArguments) << "RooFitResult::correlationPlot: parameter not floated in fit: " << parName2 << endl; - return 0; + return nullptr; } // options are not case sensitive @@ -331,10 +340,11 @@ RooPlot *RooFitResult::plotOn(RooPlot *frame, const char *parName1, const char * const RooArgList& RooFitResult::randomizePars() const { Int_t nPar= _finalPars->getSize(); - if(0 == _randomPars) { // first-time initialization - assert(0 != _finalPars); + if(nullptr == _randomPars) { // first-time initialization + assert(nullptr != _finalPars); // create the list of random values to fill - _randomPars= (RooArgList*)_finalPars->snapshot(); + _randomPars = new RooArgList; + _finalPars->snapshot(*_randomPars); // calculate the elements of the upper-triangular matrix L that gives Lt*L = C // where Lt is the transpose of L (the "square-root method") TMatrix L(nPar,nPar); @@ -404,14 +414,14 @@ double RooFitResult::correlation(const char* parname1, const char* parname2) con const RooArgList* RooFitResult::correlation(const char* parname) const { - if (_globalCorr==0) { + if (_globalCorr==nullptr) { fillLegacyCorrMatrix() ; } RooAbsArg* arg = _initPars->find(parname) ; if (!arg) { coutE(InputArguments) << "RooFitResult::correlation: variable " << parname << " not a floating parameter in fit" << endl ; - return 0 ; + return nullptr ; } return (RooArgList*)_corrMatrix.At(_initPars->index(arg)) ; } @@ -423,7 +433,7 @@ const RooArgList* RooFitResult::correlation(const char* parname) const double RooFitResult::globalCorr(const char* parname) { - if (_globalCorr==0) { + if (_globalCorr==nullptr) { fillLegacyCorrMatrix() ; } @@ -447,7 +457,7 @@ double RooFitResult::globalCorr(const char* parname) const RooArgList* RooFitResult::globalCorr() { - if (_globalCorr==0) { + if (_globalCorr==nullptr) { fillLegacyCorrMatrix() ; } @@ -507,9 +517,13 @@ void RooFitResult::printMultiline(ostream& os, Int_t /*contents*/, bool verbose, << indent << " -------------------- ------------" << endl ; for (i=0 ; i<_constPars->getSize() ; i++) { - os << indent << " " << setw(20) << ((RooAbsArg*)_constPars->at(i))->GetName() - << " " << setw(12) << Form("%12.4e",((RooRealVar*)_constPars->at(i))->getVal()) - << endl ; + os << indent << " " << setw(20) << _constPars->at(i)->GetName() << " " << setw(12); + if(RooRealVar* v = dynamic_cast(_constPars->at(i))) { + os << TString::Format("%12.4e",v->getVal()); + } else { + _constPars->at(i)->printValue(os); // for anything other than RooRealVar use printValue method to print + } + os << endl ; } os << endl ; @@ -588,7 +602,7 @@ void RooFitResult::fillCorrMatrix(const std::vector& globalCC, const TMa return ; } - // Delete eventual prevous correlation data holders + // Delete eventual previous correlation data holders if (_CM) delete _CM ; if (_VM) delete _VM ; if (_GC) delete _GC ; @@ -614,7 +628,7 @@ void RooFitResult::fillLegacyCorrMatrix() const { if (!_CM) return ; - // Delete eventual prevous correlation data holders + // Delete eventual previous correlation data holders if (_globalCorr) delete _globalCorr ; _corrMatrix.Delete(); @@ -628,7 +642,7 @@ void RooFitResult::fillLegacyCorrMatrix() const gcName.Append("]") ; TString gcTitle(arg->GetTitle()) ; gcTitle.Append(" Global Correlation") ; - _globalCorr->addOwned(*(new RooRealVar(gcName.Data(),gcTitle.Data(),0.))) ; + _globalCorr->addOwned(std::make_unique(gcName.Data(),gcTitle.Data(),0.)); // Create array with correlation holders for this parameter TString name("C[") ; @@ -647,7 +661,7 @@ void RooFitResult::fillLegacyCorrMatrix() const cTitle.Append(arg->GetName()) ; cTitle.Append(" and ") ; cTitle.Append(arg2->GetName()) ; - corrMatrixRow->addOwned(*(new RooRealVar(cName.Data(),cTitle.Data(),0.))) ; + corrMatrixRow->addOwned(std::make_unique(cName.Data(),cTitle.Data(),0.)); } } @@ -690,7 +704,7 @@ void RooFitResult::fillCorrMatrix() return ; } - // Delete eventual prevous correlation data holders + // Delete eventual previous correlation data holders if (_CM) delete _CM ; if (_VM) delete _VM ; if (_GC) delete _GC ; @@ -736,7 +750,7 @@ void RooFitResult::fillCorrMatrix() void RooFitResult::fillPrefitCorrMatrix() { - // Delete eventual prevous correlation data holders + // Delete eventual previous correlation data holders if (_CM) delete _CM; if (_VM) @@ -781,7 +795,7 @@ void isErrorIdenticalErrMsg(std::string const& msgHead, const RooRealVar* tv, co /// \param[in] other Fit result to test against. /// \param[in] tol **Relative** tolerance for parameters and NLL. /// \param[in] tolErr **Relative** tolerance for parameter errors. -/// \param[in] verbose If this function will log to the standard output when comparisions fail. +/// \param[in] verbose If this function will log to the standard output when comparisons fail. bool RooFitResult::isIdenticalNoCov(const RooFitResult& other, double tol, double tolErr, bool verbose) const { @@ -840,7 +854,7 @@ bool RooFitResult::isIdenticalNoCov(const RooFitResult& other, double tol, doubl /// \param[in] other Fit result to test against. /// \param[in] tol **Relative** tolerance for parameters and NLL. /// \param[in] tolCorr **absolute** tolerance for correlation coefficients. -/// \param[in] verbose If this function will log to the standard output when comparisions fail. +/// \param[in] verbose If this function will log to the standard output when comparisons fail. /// /// As the relative tolerance for the parameter errors, the default value of /// `1e-3` will be used. @@ -850,7 +864,7 @@ bool RooFitResult::isIdentical(const RooFitResult& other, double tol, double tol bool ret = isIdenticalNoCov(other, tol, 1e-3 /* synced with default parameter*/, verbose); auto deviationCorr = [tolCorr](const double left, const double right){ - return fabs(left - right) >= tolCorr; + return std::abs(left - right) >= tolCorr; }; // Only examine correlations for cases with >1 floating parameter @@ -935,18 +949,18 @@ RooFitResult* RooFitResult::lastMinuitFit(const RooArgList& varList) double xerr = gMinuit->fWerr[l-1]; double xval = gMinuit->fU[i-1] ; - RooRealVar* var ; + std::unique_ptr var; if (varList.empty()) { if ((xlo(varName,varName,xval,xlo,xhi) ; } else { - var = new RooRealVar(varName,varName,xval) ; + var = std::make_unique(varName,varName,xval) ; } var->setConstant(isConst) ; } else { - var = (RooRealVar*) varList.at(i-1)->Clone() ; + var = std::unique_ptr{static_cast(varList.at(i-1)->Clone())}; var->setConstant(isConst) ; var->setVal(xval) ; if (xlosetError(xerr) ; - floatPars.addOwned(*var) ; + floatPars.addOwned(std::move(var)); } } @@ -1243,7 +1257,7 @@ RooAbsPdf* RooFitResult::createHessePdf(const RooArgSet& params) const if (det<=0) { coutE(Eval) << "RooFitResult::createHessePdf(" << GetName() << ") ERROR: covariance matrix is not positive definite (|V|=" << det << ") cannot construct p.d.f" << endl ; - return 0 ; + return nullptr ; } // Make sure that all given params were floating parameters in the represented fit diff --git a/roofit/roofitcore/src/RooFoamGenerator.cxx b/roofit/roofitcore/src/RooFoamGenerator.cxx index 2d1eae9654ecc..eea380afbecde 100644 --- a/roofit/roofitcore/src/RooFoamGenerator.cxx +++ b/roofit/roofitcore/src/RooFoamGenerator.cxx @@ -51,7 +51,7 @@ Access those using: #include "RooNumGenFactory.h" #include "RooNumGenConfig.h" -#include +#include using namespace std; diff --git a/roofit/roofitcore/src/RooFormula.cxx b/roofit/roofitcore/src/RooFormula.cxx index e148d18828975..e5607c26af6c9 100644 --- a/roofit/roofitcore/src/RooFormula.cxx +++ b/roofit/roofitcore/src/RooFormula.cxx @@ -54,12 +54,10 @@ Check the tutorial rf506_msgservice.C for details. **/ #include "RooFormula.h" -#include "BracketAdapters.h" #include "RooAbsReal.h" #include "RooAbsCategory.h" #include "RooArgList.h" #include "RooMsgService.h" -#include "RunContext.h" #include "RooBatchCompute.h" #include "TObjString.h" @@ -71,8 +69,6 @@ Check the tutorial rf506_msgservice.C for details. using namespace std; -ClassImp(RooFormula); - namespace { //////////////////////////////////////////////////////////////////////////////// @@ -109,12 +105,12 @@ void convertArobaseReferences(std::string &formula) formula += ']'; } -/// Replace all occurences of `what` with `with` inside of `inout`. -void replaceAll(std::string &inout, std::string_view what, std::string_view with) +/// Replace all occurrences of `what` with `with` inside of `inOut`. +void replaceAll(std::string &inOut, std::string_view what, std::string_view with) { - for (std::string::size_type pos{}; inout.npos != (pos = inout.find(what.data(), pos, what.length())); + for (std::string::size_type pos{}; inOut.npos != (pos = inOut.find(what.data(), pos, what.length())); pos += with.length()) { - inout.replace(pos, what.length(), with.data(), with.length()); + inOut.replace(pos, what.length(), with.data(), with.length()); } } @@ -176,26 +172,18 @@ void replaceVarNamesWithIndexStyle(std::string &formula, RooArgList const &varLi else if (nNew < nOld) isWordBoundary.erase(wbIter + nNew, wbIter + nOld); - // Do the actual replacment + // Do the actual replacement formula.replace(pos, varName.length(), replacement); } oocxcoutD(static_cast(nullptr), InputArguments) << "Preprocessing formula: replace named references: " << varName << " --> " << replacement << "\n\t" - << formula << endl; + << formula << std::endl; } } } -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor -/// coverity[UNINIT_CTOR] - -RooFormula::RooFormula() : TNamed() -{ -} - //////////////////////////////////////////////////////////////////////////////// /// Construct a new formula. @@ -232,23 +220,16 @@ RooFormula::RooFormula(const RooFormula& other, const char* name) : _origList.add(other._origList); _isCategory = findCategoryServers(_origList); - TFormula* newTF = nullptr; + std::unique_ptr newTF; if (other._tFormula) { - newTF = new TFormula(*other._tFormula); + newTF = std::make_unique(*other._tFormula); newTF->SetName(GetName()); } - _tFormula.reset(newTF); + _tFormula = std::move(newTF); } -#ifndef _MSC_VER -#if !defined(__GNUC__) || defined(__clang__) || (__GNUC__ > 4) || ( __GNUC__ == 4 && __GNUC_MINOR__ > 8) -#define ROOFORMULA_HAVE_STD_REGEX -#endif //GCC < 4.9 Check -#endif //_MSC_VER - -#ifdef ROOFORMULA_HAVE_STD_REGEX //////////////////////////////////////////////////////////////////////////////// /// Process given formula by replacing all ordinal and name references by /// `x[i]`, where `i` matches the position of the argument in `_origList`. @@ -262,7 +243,7 @@ std::string RooFormula::processFormula(std::string formula) const { // compilation. cxcoutD(InputArguments) << "Preprocessing formula step 1: find category tags (catName::catState) in " - << formula << endl; + << formula << std::endl; // Step 1: Find all category tags and the corresponding index numbers static const std::regex categoryReg("(\\w+)::(\\w+)"); @@ -277,13 +258,13 @@ std::string RooFormula::processFormula(std::string formula) const { const auto catVariable = dynamic_cast(_origList.find(catName.c_str())); if (!catVariable) { cxcoutD(InputArguments) << "Formula " << GetName() << " uses '::' to reference a category state as '" << fullMatch - << "' but a category '" << catName << "' cannot be found in the input variables." << endl; + << "' but a category '" << catName << "' cannot be found in the input variables." << std::endl; continue; } if (!catVariable->hasLabel(catState)) { coutE(InputArguments) << "Formula " << GetName() << " uses '::' to reference a category state as '" << fullMatch - << "' but the category '" << catName << "' does not seem to have the state '" << catState << "'." << endl; + << "' but the category '" << catName << "' does not seem to have the state '" << catState << "'." << std::endl; throw std::invalid_argument(formula); } const int catNum = catVariable->lookupIndex(catState); @@ -291,24 +272,24 @@ std::string RooFormula::processFormula(std::string formula) const { categoryStates[fullMatch] = catNum; cxcoutD(InputArguments) << "\n\t" << fullMatch << "\tname=" << catName << "\tstate=" << catState << "=" << catNum; } - cxcoutD(InputArguments) << "-- End of category tags --"<< endl; + cxcoutD(InputArguments) << "-- End of category tags --"<< std::endl; // Step 2: Replace all category tags for (const auto& catState : categoryStates) { replaceAll(formula, catState.first, std::to_string(catState.second)); } - cxcoutD(InputArguments) << "Preprocessing formula step 2: replace category tags\n\t" << formula << endl; + cxcoutD(InputArguments) << "Preprocessing formula step 2: replace category tags\n\t" << formula << std::endl; // Step 3: Convert `@i`-style references to `x[i]` convertArobaseReferences(formula); - cxcoutD(InputArguments) << "Preprocessing formula step 3: replace '@'-references\n\t" << formula << endl; + cxcoutD(InputArguments) << "Preprocessing formula step 3: replace '@'-references\n\t" << formula << std::endl; // Step 4: Replace all named references with "x[i]"-style replaceVarNamesWithIndexStyle(formula, _origList); - cxcoutD(InputArguments) << "Final formula:\n\t" << formula << endl; + cxcoutD(InputArguments) << "Final formula:\n\t" << formula << std::endl; return formula; } @@ -359,28 +340,8 @@ std::string RooFormula::reconstructFormula(std::string internalRepr) const { return internalRepr; } -#endif //ROOFORMULA_HAVE_STD_REGEX - - -//////////////////////////////////////////////////////////////////////////////// -/// Recompile formula with new expression. In case of error, the old formula is -/// retained. -bool RooFormula::reCompile(const char* newFormula) -{ - try { - installFormulaOrThrow(newFormula); - } catch (std::runtime_error& e) { - coutE(InputArguments) << __func__ << ": new equation doesn't compile, formula unchanged." - << "\n" << e.what() << endl; - return true; - } - - SetTitle(newFormula); - return false; -} - void RooFormula::dump() const { printMultiline(std::cout, 0); @@ -397,7 +358,9 @@ bool RooFormula::changeDependents(const RooAbsCollection& newDeps, bool mustRepl //Change current servers to new servers with the same name given in list bool errorStat = false; - for (const auto arg : _origList) { + // We only consider the usedVariables() for replacement, because only these + // are registered as servers. + for (const auto arg : usedVariables()) { RooAbsReal* replace = (RooAbsReal*) arg->findNewServer(newDeps,nameChange) ; if (replace) { _origList.replace(*arg, *replace); @@ -409,7 +372,7 @@ bool RooFormula::changeDependents(const RooAbsCollection& newDeps, bool mustRepl } } else if (mustReplaceAll) { - coutE(LinkStateMgmt) << __func__ << ": cannot find replacement for " << arg->GetName() << endl; + coutE(LinkStateMgmt) << __func__ << ": cannot find replacement for " << arg->GetName() << std::endl; errorStat = true; } } @@ -431,7 +394,7 @@ bool RooFormula::changeDependents(const RooAbsCollection& newDeps, bool mustRepl double RooFormula::eval(const RooArgSet* nset) const { if (!_tFormula) { - coutF(Eval) << __func__ << " (" << GetName() << "): Formula didn't compile: " << GetTitle() << endl; + coutF(Eval) << __func__ << " (" << GetName() << "): Formula didn't compile: " << GetTitle() << std::endl; std::string what = "Formula "; what += GetTitle(); what += " didn't compile."; @@ -453,56 +416,14 @@ double RooFormula::eval(const RooArgSet* nset) const return _tFormula->EvalPar(pars.data()); } - -RooSpan RooFormula::evaluateSpan(const RooAbsReal* dataOwner, RooBatchCompute::RunContext& inputData, const RooArgSet* nset) const { - if (!_tFormula) { - coutF(Eval) << __func__ << " (" << GetName() << "): Formula didn't compile: " << GetTitle() << endl; - std::string what = "Formula "; - what += GetTitle(); - what += " didn't compile."; - throw std::runtime_error(what); - } - - std::vector valueAdapters; - std::vector> inputSpans; - size_t nData=1; - for (const auto arg : _origList) { - auto realArg = static_cast(arg); - auto batch = realArg->getValues(inputData, nset); - assert(!batch.empty()); - nData = std::max(nData, batch.size()); - valueAdapters.emplace_back(batch[0], batch); - inputSpans.push_back(std::move(batch)); - } - - auto output = inputData.makeBatch(dataOwner, nData); - std::vector pars(_origList.size()); - - - for (std::size_t i=0; i < nData; ++i) { - for (unsigned int j=0; j < _origList.size(); ++j) { - if (_isCategory[j]) { - // TODO: As long as category states cannot be passed in the RunContext, - // the current state has to be used. - const auto& cat = static_cast(_origList[j]); - pars[j] = cat.getCurrentIndex(); - } else { - pars[j] = valueAdapters[j][i]; - } - } - - output[i] = _tFormula->EvalPar(pars.data()); - } - - return output; -} - -void RooFormula::computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooFormula::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { const int nPars=_origList.size(); - std::vector> inputSpans(nPars); - for (int i=0; i(&_origList[i]) ); + std::vector> inputSpans(nPars); + for (int i=0; i rhs = dataMap.at( static_cast(&_origList[i]) ); + inputSpans[i] = rhs; + } std::vector pars(nPars); for (size_t i=0; i(this)->eval(0) ; + os << const_cast(this)->eval(nullptr) ; } @@ -585,7 +506,7 @@ void RooFormula::installFormulaOrThrow(const std::string& formula) { << "\n\t" << processedFormula << "\n and used as" << "\n\t" << reconstructFormula(processedFormula) - << "\n with the parameters " << _origList << endl; + << "\n with the parameters " << _origList << std::endl; auto theFormula = std::make_unique(GetName(), processedFormula.c_str(), false); @@ -622,158 +543,3 @@ void RooFormula::installFormulaOrThrow(const std::string& formula) { _tFormula = std::move(theFormula); } - - -#ifndef ROOFORMULA_HAVE_STD_REGEX -/* - * g++ 4.8 doesn't support the std::regex. It has headers, but no implementations of the standard, leading to linker - * errors. As long as centos 7 needs to be supported, this forces us to have a legacy implementation. - */ - -#include "TPRegexp.h" - -//////////////////////////////////////////////////////////////////////////////// -/// Process given formula by replacing all ordinal and name references by -/// `x[i]`, where `i` matches the position of the argument in `_origList`. -/// Further, references to category states such as `leptonMulti:one` are replaced -/// by the category index. -std::string RooFormula::processFormula(std::string formula) const { - TString formulaTString = formula.c_str(); - - cxcoutD(InputArguments) << "Preprocessing formula step 1: find category tags (catName::catState) in " - << formulaTString.Data() << endl; - - // Step 1: Find all category tags and the corresponding index numbers - TPRegexp categoryReg("(\\w+)::(\\w+)"); - std::map categoryStates; - int offset = 0; - do { - std::unique_ptr matches(categoryReg.MatchS(formulaTString, "", offset, 3)); - if (matches->GetEntries() == 0) - break; - - std::string fullMatch = static_cast(matches->At(0))->GetString().Data(); - std::string catName = static_cast(matches->At(1))->GetString().Data(); - std::string catState = static_cast(matches->At(2))->GetString().Data(); - offset = formulaTString.Index(categoryReg, offset) + fullMatch.size(); - - const auto catVariable = dynamic_cast(_origList.find(catName.c_str())); - if (!catVariable) { - cxcoutD(InputArguments) << "Formula " << GetName() << " uses '::' to reference a category state as '" << fullMatch - << "' but a category '" << catName << "' cannot be found in the input variables." << endl; - continue; - } - - const RooCatType* catType = catVariable->lookupType(catState.c_str(), false); - if (!catType) { - coutE(InputArguments) << "Formula " << GetName() << " uses '::' to reference a category state as '" << fullMatch - << "' but the category '" << catName << "' does not seem to have the state '" << catState << "'." << endl; - throw std::invalid_argument(formula); - } - const int catNum = catType->getVal(); - - categoryStates[fullMatch] = catNum; - cxcoutD(InputArguments) << "\n\t" << fullMatch << "\tname=" << catName << "\tstate=" << catState << "=" << catNum; - } while (offset != -1); - cxcoutD(InputArguments) << "-- End of category tags --"<< endl; - - // Step 2: Replace all category tags - for (const auto& catState : categoryStates) { - std::stringstream replacement; - replacement << catState.second; - formulaTString.ReplaceAll(catState.first.c_str(), replacement.str().c_str()); - } - - cxcoutD(InputArguments) << "Preprocessing formula step 2: replace category tags\n\t" << formulaTString.Data() << endl; - - // Step 3: Convert `@i`-style references to `x[i]` - TPRegexp ordinalRegex("@([0-9]+)"); - int nsub = 0; - do { - nsub = ordinalRegex.Substitute(formulaTString, "x[$1]"); - } while (nsub > 0); - - cxcoutD(InputArguments) << "Preprocessing formula step 3: replace '@'-references\n\t" << formulaTString.Data() << endl; - - // Step 4: Replace all named references with "x[i]"-style - for (unsigned int i = 0; i < _origList.size(); ++i) { - const auto& var = _origList[i]; - TString regex = "\\b"; - regex += var.GetName(); - regex += "\\b([^\\[\\]]|$)"; //Negative lookahead. If the variable is called `x` or `0`, this might otherwise replace `x[0]`. - TPRegexp findParameterRegex(regex); - - std::stringstream replacement; - replacement << "x[" << i << "]$1"; - int nsub2 = 0; - do { - nsub2 = findParameterRegex.Substitute(formulaTString, replacement.str().c_str()); - } while (nsub2 > 0); - - cxcoutD(InputArguments) << "Preprocessing formula step 4: replace named references: " - << var.GetName() << " --> " << replacement.str() - << "\n\t" << formulaTString.Data() << endl; - } - - cxcoutD(InputArguments) << "Final formula:\n\t" << formulaTString << endl; - - return formulaTString.Data(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Analyse internal formula to find out which variables are actually in use. -RooArgList RooFormula::usedVariables() const { - RooArgList useList; - if (_tFormula == nullptr) - return useList; - - const TString formulaTString = _tFormula->GetTitle(); - - std::set matchedOrdinals; - TPRegexp newOrdinalRegex("\\bx\\[([0-9]+)\\]"); - int offset = 0; - do { - std::unique_ptr matches(newOrdinalRegex.MatchS(formulaTString, "", offset, 2)); - if (matches->GetEntries() == 0) - break; - - std::string fullMatch = static_cast(matches->At(0))->GetString().Data(); - std::string ordinal = static_cast(matches->At(1))->GetString().Data(); - offset = formulaTString.Index(newOrdinalRegex, offset) + fullMatch.size(); - - std::stringstream matchString(ordinal.c_str()); - unsigned int i; - matchString >> i; - - matchedOrdinals.insert(i); - } while (offset != -1); - - for (unsigned int i : matchedOrdinals) { - useList.add(_origList[i]); - } - - return useList; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// From the internal representation, construct a formula by replacing all index place holders -/// with the names of the variables that are being used to evaluate it. -std::string RooFormula::reconstructFormula(std::string internalRepr) const { - TString internalReprT = internalRepr.c_str(); - - for (unsigned int i = 0; i < _origList.size(); ++i) { - const auto& var = _origList[i]; - std::stringstream regexStr; - regexStr << "x\\[" << i << "\\]|@" << i; - TPRegexp regex(regexStr.str().c_str()); - - std::string replacement = std::string("[") + var.GetName() + "]"; - regex.Substitute(internalReprT, replacement.c_str()); - } - - return internalReprT.Data(); -} -#endif //ROOFORMULA_HAVE_STD_REGEX diff --git a/roofit/roofitcore/src/RooFormula.h b/roofit/roofitcore/src/RooFormula.h new file mode 100644 index 0000000000000..a7039909d4bff --- /dev/null +++ b/roofit/roofitcore/src/RooFormula.h @@ -0,0 +1,84 @@ +/* + * Project: RooFit + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef ROO_FORMULA +#define ROO_FORMULA + +#include "RooPrintable.h" +#include "RooArgList.h" +#include "RooArgSet.h" +#include "RooFit/Detail/DataMap.h" + +#include "TFormula.h" + +#include +#include +#include + +class RooAbsReal; + +class RooFormula : public TNamed, public RooPrintable { +public: + // Constructors etc. + RooFormula(const char *name, const char *formula, const RooArgList &varList, bool checkVariables = true); + RooFormula(const RooFormula &other, const char *name = nullptr); + TObject *Clone(const char *newName = nullptr) const override { return new RooFormula(*this, newName); } + + RooFormula &operator=(const RooFormula &other) = delete; + RooFormula &operator=(RooFormula &&other) = delete; + + //////////////////////////////////////////////////////////////////////////////// + /// Return list of arguments which are used in the formula. + RooArgSet actualDependents() const { return usedVariables(); } + bool changeDependents(const RooAbsCollection &newDeps, bool mustReplaceAll, bool nameChange); + + /// Return pointer to the parameter with given name. + /// \return Parameter if in use, nullptr if not in use. + RooAbsArg *getParameter(const char *name) const { return usedVariables().find(name); } + + /// Return pointer to parameter at given index. This returns + /// irrespective of whether the parameter is in use. + RooAbsArg *getParameter(Int_t index) const { return _origList.at(index); } + + bool ok() const { return _tFormula != nullptr; } + /// Evaluate all parameters/observables, and then evaluate formula. + double eval(const RooArgSet *nset = nullptr) const; + void computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &) const; + + /// DEBUG: Dump state information + void dump() const; + + void printValue(std::ostream &os) const override; + void printName(std::ostream &os) const override; + void printTitle(std::ostream &os) const override; + void printClassName(std::ostream &os) const override; + void printArgs(std::ostream &os) const override; + void printMultiline(std::ostream &os, Int_t contents, bool verbose = false, TString indent = "") const override; + + void Print(Option_t *options = nullptr) const override + { + // Printing interface (human readable) + printStream(defaultPrintStream(), defaultPrintContents(options), defaultPrintStyle(options)); + } + + std::string formulaString() const { return _tFormula ? _tFormula->GetTitle() : ""; } + +private: + std::string processFormula(std::string origFormula) const; + RooArgList usedVariables() const; + std::string reconstructFormula(std::string internalRepr) const; + void installFormulaOrThrow(const std::string &formulaa); + + RooArgList _origList; /// _isCategory; /// _tFormula; ///formulaString().c_str(); + _actualVars.add(_formula->actualDependents()); } } @@ -98,13 +103,12 @@ RooFormulaVar::RooFormulaVar(const char *name, const char *title, const RooArgLi _actualVars("actualVars","Variables used by formula expression",this), _formExpr(title) { - _actualVars.add(dependents) ; - - if (_actualVars.empty()) { - _value = traceEval(0); + if (dependents.empty()) { + _value = traceEval(nullptr); } else { - _formula.reset(new RooFormula(GetName(), _formExpr, _actualVars, checkVariables)); + _formula = new RooFormula(GetName(), _formExpr, dependents, checkVariables); _formExpr = _formula->formulaString().c_str(); + _actualVars.add(_formula->actualDependents()); } } @@ -119,7 +123,7 @@ RooFormulaVar::RooFormulaVar(const RooFormulaVar& other, const char* name) : _formExpr(other._formExpr) { if (other._formula && other._formula->ok()) { - _formula = std::make_unique(*other._formula); + _formula = new RooFormula(*other._formula); _formExpr = _formula->formulaString().c_str(); } } @@ -132,8 +136,7 @@ RooFormula& RooFormulaVar::getFormula() const { if (!_formula) { // After being read from file, the formula object might not exist, yet: - auto theFormula = new RooFormula(GetName(), _formExpr, _actualVars); - const_cast&>(_formula).reset(theFormula); + _formula = new RooFormula(GetName(), _formExpr, _actualVars); const_cast(_formExpr) = _formula->formulaString().c_str(); } @@ -141,6 +144,11 @@ RooFormula& RooFormulaVar::getFormula() const } +bool RooFormulaVar::ok() const { return getFormula().ok() ; } + + +void RooFormulaVar::dumpFormula() { getFormula().dump() ; } + //////////////////////////////////////////////////////////////////////////////// /// Calculate current value of object from internal formula @@ -151,21 +159,9 @@ double RooFormulaVar::evaluate() const } -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate the formula for all entries of our servers found in `inputData`. -RooSpan RooFormulaVar::evaluateSpan(RooBatchCompute::RunContext& inputData, const RooArgSet* normSet) const { - if (normSet != _lastNSet) { - // TODO: Remove dependence on _lastNSet - // See also comment in RooAbsReal::getValBatch(). - std::cerr << "Formula " << GetName() << " " << GetTitle() << "\n\tBeing evaluated with normSet " << normSet << "\n"; - normSet->Print("V"); - std::cerr << "\tHowever, _lastNSet = " << _lastNSet << "\n"; - if (_lastNSet) _lastNSet->Print("V"); - - throw std::logic_error("Got conflicting norm sets. This shouldn't happen."); - } - - return formula().evaluateSpan(this, inputData, normSet); +void RooFormulaVar::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +{ + getFormula().computeBatch(output, nEvents, dataMap); } @@ -282,8 +278,8 @@ std::list* RooFormulaVar::plotSamplingHint(RooAbsRealLValue& obs, double double RooFormulaVar::defaultErrorLevel() const { - RooAbsReal* nllArg(0) ; - RooAbsReal* chi2Arg(0) ; + RooAbsReal* nllArg(nullptr) ; + RooAbsReal* chi2Arg(nullptr) ; for (const auto arg : _actualVars) { if (dynamic_cast(arg)) { diff --git a/roofit/roofitcore/src/RooFracRemainder.cxx b/roofit/roofitcore/src/RooFracRemainder.cxx index 396abddc1c59b..cba41f949dc94 100644 --- a/roofit/roofitcore/src/RooFracRemainder.cxx +++ b/roofit/roofitcore/src/RooFracRemainder.cxx @@ -28,7 +28,7 @@ a constrained split #include "Riostream.h" -#include +#include #include "RooFracRemainder.h" #include "RooAbsReal.h" diff --git a/roofit/roofitcore/src/RooFuncWrapper.cxx b/roofit/roofitcore/src/RooFuncWrapper.cxx new file mode 100644 index 0000000000000..056309063e3de --- /dev/null +++ b/roofit/roofitcore/src/RooFuncWrapper.cxx @@ -0,0 +1,243 @@ +/* + * Project: RooFit + * Authors: + * Garima Singh, CERN 2022 + * + * Copyright (c) 2022, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include + +#include +#include +#include +#include +#include +#include +#include "RooFit/BatchModeDataHelpers.h" + +#include +#include + +RooFuncWrapper::RooFuncWrapper(const char *name, const char *title, std::string const &funcBody, + RooArgSet const ¶mSet, const RooAbsData *data, RooSimultaneous const *simPdf, + bool createGradient) + : RooAbsReal{name, title}, _params{"!params", "List of parameters", this}, _hasGradient{createGradient} +{ + // Declare the function and create its derivative. + declareAndDiffFunction(name, funcBody, createGradient); + + // Load the parameters and observables. + loadParamsAndData(name, nullptr, paramSet, data, simPdf); +} + +RooFuncWrapper::RooFuncWrapper(const char *name, const char *title, RooAbsReal const &obj, RooArgSet const &normSet, + const RooAbsData *data, RooSimultaneous const *simPdf, bool createGradient) + : RooAbsReal{name, title}, _params{"!params", "List of parameters", this}, _hasGradient{createGradient} +{ + std::string func; + + // Compile the computation graph for the norm set, such that we also get the + // integrals explicitly in the graph. + std::unique_ptr pdf{RooFit::Detail::compileForNormSet(obj, normSet)}; + // Get the parameters. + RooArgSet paramSet; + obj.getParameters(data ? data->get() : nullptr, paramSet); + RooArgSet floatingParamSet; + for (RooAbsArg *param : paramSet) { + if (!param->isConstant()) { + floatingParamSet.add(*param); + } + } + + // Load the parameters and observables. + loadParamsAndData(name, pdf.get(), floatingParamSet, data, simPdf); + + func = buildCode(*pdf); + + // Declare the function and create its derivative. + declareAndDiffFunction(name, func, createGradient); +} + +RooFuncWrapper::RooFuncWrapper(const RooFuncWrapper &other, const char *name) + : RooAbsReal(other, name), + _params("!params", this, other._params), + _func(other._func), + _grad(other._grad), + _hasGradient(other._hasGradient), + _gradientVarBuffer(other._gradientVarBuffer), + _observables(other._observables) +{ +} + +void RooFuncWrapper::loadParamsAndData(std::string funcName, RooAbsArg const *head, RooArgSet const ¶mSet, + const RooAbsData *data, RooSimultaneous const *simPdf) +{ + // Extract observables + std::stack> vectorBuffers; // for data loading + std::map> spans; + + if (data) { + spans = RooFit::BatchModeDataHelpers::getDataSpans(*data, "", simPdf, true, false, vectorBuffers); + } + + std::size_t idx = 0; + for (auto const &item : spans) { + std::size_t n = item.second.size(); + _obsInfos.emplace(item.first, ObsInfo{idx, n}); + _observables.reserve(_observables.size() + n); + for (std::size_t i = 0; i < n; ++i) { + _observables.push_back(item.second[i]); + } + idx += n; + } + + // Extract parameters + for (auto *param : paramSet) { + if (!dynamic_cast(param)) { + std::stringstream errorMsg; + errorMsg << "In creation of function " << funcName + << " wrapper: input param expected to be of type RooAbsReal."; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); + } + if (spans.find(param) == spans.end()) { + _params.add(*param); + } + } + _gradientVarBuffer.resize(_params.size()); + + if (head) { + _nodeOutputSizes = + RooFit::BatchModeDataHelpers::determineOutputSizes(*head, [&spans](RooFit::Detail::DataKey key) { + auto found = spans.find(key); + return found != spans.end() ? found->second.size() : 0; + }); + } +} + +void RooFuncWrapper::declareAndDiffFunction(std::string funcName, std::string const &funcBody, bool createGradient) +{ + std::string gradName = funcName + "_grad_0"; + std::string requestName = funcName + "_req"; + std::string wrapperName = funcName + "_derivativeWrapper"; + + gInterpreter->Declare("#pragma cling optimize(2)"); + + // Declare the function + std::stringstream bodyWithSigStrm; + bodyWithSigStrm << "double " << funcName << "(double* params, double const* obs) {\n" << funcBody << "\n}"; + bool comp = gInterpreter->Declare(bodyWithSigStrm.str().c_str()); + if (!comp) { + std::stringstream errorMsg; + errorMsg << "Function " << funcName << " could not be compiled. See above for details."; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); + } + _func = reinterpret_cast(gInterpreter->ProcessLine((funcName + ";").c_str())); + + if (!createGradient) + return; + + // Calculate gradient + gInterpreter->ProcessLine("#include "); + // disable clang-format for making the following code unreadable. + // clang-format off + std::stringstream requestFuncStrm; + requestFuncStrm << "#pragma clad ON\n" + "void " << requestName << "() {\n" + " clad::gradient(" << funcName << ", \"params\");\n" + "}\n" + "#pragma clad OFF"; + // clang-format on + comp = gInterpreter->Declare(requestFuncStrm.str().c_str()); + if (!comp) { + std::stringstream errorMsg; + errorMsg << "Function " << funcName << " could not be differentiated. See above for details."; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); + } + + // Build a wrapper over the derivative to hide clad specific types such as 'array_ref'. + // disable clang-format for making the following code unreadable. + // clang-format off + std::stringstream dWrapperStrm; + dWrapperStrm << "void " << wrapperName << "(double* params, double const* obs, double* out) {\n" + " clad::array_ref cladOut(out, " << _params.size() << ");\n" + " " << gradName << "(params, obs, cladOut);\n" + "}"; + // clang-format on + gInterpreter->Declare(dWrapperStrm.str().c_str()); + _grad = reinterpret_cast(gInterpreter->ProcessLine((wrapperName + ";").c_str())); +} + +void RooFuncWrapper::gradient(double *out) const +{ + updateGradientVarBuffer(); + std::fill(out, out + _params.size(), 0.0); + + _grad(_gradientVarBuffer.data(), _observables.data(), out); +} + +void RooFuncWrapper::updateGradientVarBuffer() const +{ + std::transform(_params.begin(), _params.end(), _gradientVarBuffer.begin(), + [](RooAbsArg *obj) { return static_cast(obj)->getVal(); }); +} + +double RooFuncWrapper::evaluate() const +{ + updateGradientVarBuffer(); + + return _func(_gradientVarBuffer.data(), _observables.data()); +} + +void RooFuncWrapper::gradient(const double *x, double *g) const +{ + std::fill(g, g + _params.size(), 0.0); + + _grad(const_cast(x), _observables.data(), g); +} + +std::string RooFuncWrapper::buildCode(RooAbsReal const &head) +{ + RooFit::Detail::CodeSquashContext ctx(_nodeOutputSizes); + + // First update the result variable of params in the compute graph to in[]. + int idx = 0; + for (RooAbsArg *param : _params) { + ctx.addResult(param, "params[" + std::to_string(idx) + "]"); + idx++; + } + + for (auto const &item : _obsInfos) { + const char *name = item.first->GetName(); + // If the observable is scalar, set name to the start idx. else, store + // the start idx and later set the the name to obs[start_idx + curr_idx], + // here curr_idx is defined by a loop producing parent node. + if (item.second.size == 1) { + ctx.addResult(name, "obs[" + std::to_string(item.second.idx) + "]"); + } else { + ctx.addResult(name, "obs"); + ctx.addVecObs(name, item.second.idx); + } + } + + return ctx.assembleCode(ctx.getResult(head)); +} + +/// @brief Prints the squashed code body to console. +void RooFuncWrapper::dumpCode() +{ + gInterpreter->ProcessLine(fName); +} + +/// @brief Prints the derivative code body to console. +void RooFuncWrapper::dumpGradient() +{ + gInterpreter->ProcessLine(fName + "_grad_0"); +} diff --git a/roofit/roofitcore/src/RooFunctor.cxx b/roofit/roofitcore/src/RooFunctor.cxx index dccb11d23dc6e..e93651a16dca3 100644 --- a/roofit/roofitcore/src/RooFunctor.cxx +++ b/roofit/roofitcore/src/RooFunctor.cxx @@ -31,7 +31,7 @@ Lightweight interface adaptor that exports a RooAbsPdf as a functor. #include "RooAbsPdf.h" #include "RooArgSet.h" -#include +#include @@ -68,7 +68,7 @@ RooFunctor::RooFunctor(const RooAbsReal& func, const RooArgList& observables, co allVars.add(parameters) ; // Create RooFit function binding - _binding = new RooRealBinding(func,allVars,&_nset,false,0) ; + _binding = new RooRealBinding(func,allVars,&_nset,false,nullptr) ; _ownBinding = true ; // Allocate transfer array @@ -90,7 +90,7 @@ RooFunctor::RooFunctor(const RooAbsReal& func, const RooArgList& observables, co allVars.add(parameters) ; // Create RooFit function binding - _binding = new RooRealBinding(func,allVars,&_nset,false,0) ; + _binding = new RooRealBinding(func,allVars,&_nset,false,nullptr) ; _ownBinding = true ; // Allocate transfer array @@ -106,7 +106,7 @@ RooFunctor::RooFunctor(const RooAbsReal& func, const RooArgList& observables, co RooFunctor::RooFunctor(const RooFunctor& other) : _ownBinding(other._ownBinding), _nset(other._nset), - _binding(0), + _binding(nullptr), _npar(other._npar), _nobs(other._nobs) { diff --git a/roofit/roofitcore/src/RooGenContext.cxx b/roofit/roofitcore/src/RooGenContext.cxx index fea096d0245c6..0858caac622ca 100644 --- a/roofit/roofitcore/src/RooGenContext.cxx +++ b/roofit/roofitcore/src/RooGenContext.cxx @@ -65,8 +65,8 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, bool verbose, const RooArgSet* forceDirect) : RooAbsGenContext(model,vars,prototype,auxProto,verbose), - _pdfClone(0), _acceptRejectFunc(0), _generator(0), - _maxVar(0), _updateFMaxPerEvent(0) + _pdfClone(nullptr), _generator(nullptr), + _maxVar(nullptr), _updateFMaxPerEvent(0) { cxcoutI(Generation) << "RooGenContext::ctor() setting up event generator context for p.d.f. " << model.GetName() << " for generation of observable(s) " << vars ; @@ -97,7 +97,7 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, // Analyze the list of variables to generate... _isValid= true; - const RooAbsArg *arg = 0; + const RooAbsArg *arg = nullptr; for(RooAbsArg * tmp : vars) { if(!_isValid) break; @@ -109,7 +109,7 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, } // lookup this argument in the cloned set of PDF dependents arg= static_cast(_cloneSet.find(tmp->GetName())); - if(0 == arg) { + if(nullptr == arg) { coutI(Generation) << "RooGenContext::ctor() WARNING model does not depend on \"" << tmp->GetName() << "\" which will have uniform distribution" << endl; _uniformVars.add(*tmp); @@ -119,10 +119,10 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, // does the model depend on this variable directly, ie, like "x" in // f(x) or f(x,g(x,y)) or even f(x,x) ? const RooAbsArg *direct= arg ; - if (forceDirect==0 || !forceDirect->find(direct->GetName())) { + if (forceDirect==nullptr || !forceDirect->find(direct->GetName())) { if (!_pdfClone->isDirectGenSafe(*arg)) { cxcoutD(Generation) << "RooGenContext::ctor() observable " << arg->GetName() << " has been determined to be unsafe for internal generation" << endl; - direct=0 ; + direct=nullptr ; } } @@ -218,17 +218,17 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, if (_otherVars.getSize()>0) { _pdfClone->getVal(&vars) ; // WVE debug - _acceptRejectFunc= new RooRealIntegral(nname,ntitle,*_pdfClone,depList,&vars); + _acceptRejectFunc= std::make_unique(nname,ntitle,*_pdfClone,depList,&vars); cxcoutI(Generation) << "RooGenContext::ctor() accept/reject sampling function is " << _acceptRejectFunc->GetName() << endl ; } else { - _acceptRejectFunc = 0 ; + _acceptRejectFunc = nullptr; } } else { // Generation _with_ prototype variable depList.remove(_protoVars,true,true); - _acceptRejectFunc= (RooRealIntegral*) _pdfClone->createIntegral(depList,vars) ; + _acceptRejectFunc= std::unique_ptr{_pdfClone->createIntegral(depList,vars)}; cxcoutI(Generation) << "RooGenContext::ctor() accept/reject sampling function is " << _acceptRejectFunc->GetName() << endl ; // Check if PDF supports maximum finding for the entire phase space @@ -240,7 +240,8 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, coutI(Generation) << "RooGenContext::ctor() prototype data provided, and " << "model supports analytical maximum finding in the full phase space: " << "can provide analytical pdf maximum to numeric generator" << endl ; - _maxVar = new RooRealVar("funcMax","function maximum",_pdfClone->maxVal(maxFindCode)) ; + double maxVal = _pdfClone->maxVal(maxFindCode) / _pdfClone->getNorm(&allVars); + _maxVar = new RooRealVar("funcMax", "function maximum", maxVal); } else { maxFindCode = _pdfClone->getMaxVal(_otherVars) ; if (maxFindCode != 0) { @@ -264,7 +265,7 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, if (_otherVars.getSize()>0) { - cxcoutD(Generation) << "RooGenContext::ctor() prototype data provided, observables are generated numericaly no " + cxcoutD(Generation) << "RooGenContext::ctor() prototype data provided, observables are generated numerically no " << "analytical estimate of maximum function value provided by model, must determine maximum value through initial sampling space " << "of accept/reject observables plus prototype observables: " << otherAndProto << endl ; @@ -295,7 +296,7 @@ RooGenContext::RooGenContext(const RooAbsPdf &model, const RooArgSet &vars, cxcoutD(Generation) << "RooGenContext::ctor() creating MC sampling generator " << _generator->generatorName() << " from function for observables " << _otherVars << endl ; //_generator= new RooAcceptReject(*_acceptRejectFunc,_otherVars,RooNumGenConfig::defaultConfig(),_verbose,_maxVar); } else { - _generator = 0 ; + _generator = nullptr ; } _otherVars.add(_uniformVars); @@ -309,7 +310,6 @@ RooGenContext::~RooGenContext() { // Clean up our accept/reject generator if (_generator) delete _generator; - if (_acceptRejectFunc) delete _acceptRejectFunc; if (_maxVar) delete _maxVar ; } @@ -379,7 +379,7 @@ void RooGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) << resampleRatio << " due to increased maximum weight" << endl ; resampleData(resampleRatio) ; } - if(0 == subEvent) { + if(nullptr == subEvent) { coutE(Generation) << "RooGenContext::generateEvent ERROR accept/reject generator failed" << endl ; return; } diff --git a/roofit/roofitcore/src/RooGenFitStudy.cxx b/roofit/roofitcore/src/RooGenFitStudy.cxx index e9762d76717d7..2a1149cc29190 100644 --- a/roofit/roofitcore/src/RooGenFitStudy.cxx +++ b/roofit/roofitcore/src/RooGenFitStudy.cxx @@ -46,13 +46,12 @@ ClassImp(RooGenFitStudy); RooGenFitStudy::RooGenFitStudy(const char* name, const char* title) : RooAbsStudy(name?name:"RooGenFitStudy",title?title:"RooGenFitStudy"), - _genPdf(0), - _fitPdf(0), - _genSpec(0), - _nllVar(0), - _ngenVar(0), - _params(0), - _initParams(0) + _genPdf(nullptr), + _fitPdf(nullptr), + _genSpec(nullptr), + _nllVar(nullptr), + _ngenVar(nullptr), + _initParams(nullptr) { } @@ -67,13 +66,12 @@ RooGenFitStudy::RooGenFitStudy(const RooGenFitStudy& other) : _genObsName(other._genObsName), _fitPdfName(other._fitPdfName), _fitObsName(other._fitObsName), - _genPdf(0), - _fitPdf(0), - _genSpec(0), - _nllVar(0), - _ngenVar(0), - _params(0), - _initParams(0) + _genPdf(nullptr), + _fitPdf(nullptr), + _genSpec(nullptr), + _nllVar(nullptr), + _ngenVar(nullptr), + _initParams(nullptr) { for(TObject * o : other._genOpts) _genOpts.Add(o->Clone()); for(TObject * o : other._fitOpts) _fitOpts.Add(o->Clone()); @@ -85,7 +83,6 @@ RooGenFitStudy::RooGenFitStudy(const RooGenFitStudy& other) : RooGenFitStudy::~RooGenFitStudy() { - if (_params) delete _params ; } @@ -97,7 +94,7 @@ bool RooGenFitStudy::attach(RooWorkspace& w) { bool ret = false ; - RooAbsPdf* pdf = w.pdf(_genPdfName.c_str()) ; + RooAbsPdf* pdf = w.pdf(_genPdfName) ; if (pdf) { _genPdf = pdf ; } else { @@ -111,7 +108,7 @@ bool RooGenFitStudy::attach(RooWorkspace& w) ret = true ; } - pdf = w.pdf(_fitPdfName.c_str()) ; + pdf = w.pdf(_fitPdfName) ; if (pdf) { _fitPdf = pdf ; } else { @@ -164,9 +161,10 @@ bool RooGenFitStudy::initialize() _nllVar = new RooRealVar("NLL","-log(Likelihood)",0) ; _ngenVar = new RooRealVar("ngen","number of generated events",0) ; - _params = _fitPdf->getParameters(_genObs) ; + _params = std::unique_ptr{_fitPdf->getParameters(_genObs)}; RooArgSet modelParams(*_params) ; - _initParams = (RooArgSet*) _params->snapshot() ; + _initParams = new RooArgSet; + _params->snapshot(*_initParams); _params->add(*_nllVar) ; _params->add(*_ngenVar) ; @@ -184,17 +182,16 @@ bool RooGenFitStudy::initialize() bool RooGenFitStudy::execute() { _params->assign(*_initParams) ; - RooDataSet* data = _genPdf->generate(*_genSpec) ; - RooFitResult* fr = _fitPdf->fitTo(*data,RooFit::Save(true),(RooCmdArg&)*_fitOpts.At(0),(RooCmdArg&)*_fitOpts.At(1),(RooCmdArg&)*_fitOpts.At(2)) ; + std::unique_ptr data{_genPdf->generate(*_genSpec)}; + std::unique_ptr fr{_fitPdf->fitTo(*data,RooFit::Save(true),(RooCmdArg&)*_fitOpts.At(0),(RooCmdArg&)*_fitOpts.At(1),(RooCmdArg&)*_fitOpts.At(2))}; if (fr->status()==0) { _ngenVar->setVal(data->sumEntries()) ; _nllVar->setVal(fr->minNll()) ; storeSummaryOutput(*_params) ; - storeDetailedOutput(*fr) ; + storeDetailedOutput(std::move(fr)) ; } - delete data ; return false ; } @@ -205,16 +202,15 @@ bool RooGenFitStudy::execute() bool RooGenFitStudy::finalize() { - delete _params ; delete _nllVar ; delete _ngenVar ; delete _initParams ; delete _genSpec ; - _params = 0 ; - _nllVar = 0 ; - _ngenVar = 0 ; - _initParams = 0 ; - _genSpec = 0 ; + _params.reset(); + _nllVar = nullptr ; + _ngenVar = nullptr ; + _initParams = nullptr ; + _genSpec = nullptr ; return false ; diff --git a/roofit/roofitcore/src/RooGenFunction.cxx b/roofit/roofitcore/src/RooGenFunction.cxx deleted file mode 100644 index 1727f02b65ff2..0000000000000 --- a/roofit/roofitcore/src/RooGenFunction.cxx +++ /dev/null @@ -1,82 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - - -/** -\file RooGenFunction.cxx -\class RooGenFunction -\ingroup Roofitcore - -Lightweight interface adaptor that exports a RooAbsReal as a ROOT::Math::IGenFunction -**/ - - -#include "Riostream.h" - -#include "RooGenFunction.h" -#include "RooRealBinding.h" -#include "RooAbsReal.h" -#include "RooAbsPdf.h" -#include "RooArgSet.h" - -#include - - - -using namespace std; - -ClassImp(RooGenFunction); -; - -//////////////////////////////////////////////////////////////////////////////// - -RooGenFunction::RooGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters) : - _ftor(func,observables,parameters,observables) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooGenFunction::RooGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters, const RooArgSet& nset) : - _ftor(func,observables,parameters,nset) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooGenFunction::RooGenFunction(const RooGenFunction& other) : - ROOT::Math::IGenFunction(other), _ftor(other._ftor) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooGenFunction::~RooGenFunction() -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -double RooGenFunction::DoEval(double x) const -{ - return _ftor(x) ; -} - - diff --git a/roofit/roofitcore/src/RooGenProdProj.cxx b/roofit/roofitcore/src/RooGenProdProj.cxx index 4139fe89ab2ca..0d617dfddb41f 100644 --- a/roofit/roofitcore/src/RooGenProdProj.cxx +++ b/roofit/roofitcore/src/RooGenProdProj.cxx @@ -32,7 +32,7 @@ analytically. Remaining non-factorising observables are integrated numerically. #include "Riostream.h" -#include +#include #include "RooGenProdProj.h" #include "RooAbsReal.h" @@ -40,22 +40,6 @@ analytically. Remaining non-factorising observables are integrated numerically. #include "RooErrorHandler.h" #include "RooProduct.h" -using namespace std; - -ClassImp(RooGenProdProj); - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooGenProdProj::RooGenProdProj() : - _compSetOwnedN(0), - _compSetOwnedD(0), - _haveD(false) -{ -} - //////////////////////////////////////////////////////////////////////////////// /// Constructor for a normalization projection of the product of p.d.f.s _prodSet @@ -64,19 +48,16 @@ RooGenProdProj::RooGenProdProj() : RooGenProdProj::RooGenProdProj(const char *name, const char *title, const RooArgSet& _prodSet, const RooArgSet& _intSet, const RooArgSet& _normSet, const char* isetRangeName, const char* normRangeName, bool doFactorize) : RooAbsReal(name, title), - _compSetOwnedN(0), - _compSetOwnedD(0), _compSetN("compSetN","Set of integral components owned by numerator",this,false), _compSetD("compSetD","Set of integral components owned by denominator",this,false), - _intList("intList","List of integrals",this,true), - _haveD(false) + _intList("intList","List of integrals",this,true) { // Set expensive object cache to that of first item in prodSet setExpensiveObjectCache(_prodSet.first()->expensiveObjectCache()) ; // Create owners of components created in ctor - _compSetOwnedN = new RooArgSet ; - _compSetOwnedD = new RooArgSet ; + _compSetOwnedN = std::make_unique(); + _compSetOwnedD = std::make_unique(); RooAbsReal* numerator = makeIntegral("numerator",_prodSet,_intSet,*_compSetOwnedN,isetRangeName,doFactorize) ; RooAbsReal* denominator = makeIntegral("denominator",_prodSet,_normSet,*_compSetOwnedD,normRangeName,doFactorize) ; @@ -104,22 +85,17 @@ RooGenProdProj::RooGenProdProj(const char *name, const char *title, const RooArg RooGenProdProj::RooGenProdProj(const RooGenProdProj& other, const char* name) : RooAbsReal(other, name), - _compSetOwnedN(0), - _compSetOwnedD(0), _compSetN("compSetN","Set of integral components owned by numerator",this), _compSetD("compSetD","Set of integral components owned by denominator",this), _intList("intList","List of integrals",this) { - // Explicitly remove all server links at this point - for(RooAbsArg * server : servers()) { - removeServer(*server,true) ; - } - // Copy constructor - _compSetOwnedN = (RooArgSet*) other._compSetN.snapshot() ; + _compSetOwnedN = std::make_unique(); + other._compSetN.snapshot(*_compSetOwnedN); _compSetN.add(*_compSetOwnedN) ; - _compSetOwnedD = (RooArgSet*) other._compSetD.snapshot() ; + _compSetOwnedD = std::make_unique(); + other._compSetD.snapshot(*_compSetOwnedD); _compSetD.add(*_compSetOwnedD) ; for (RooAbsArg * arg : *_compSetOwnedN) { @@ -138,18 +114,6 @@ RooGenProdProj::RooGenProdProj(const RooGenProdProj& other, const char* name) : } - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooGenProdProj::~RooGenProdProj() -{ - if (_compSetOwnedN) delete _compSetOwnedN ; - if (_compSetOwnedD) delete _compSetOwnedD ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Utility function to create integral for product over certain observables. /// \param[in] name Name of integral to be created. @@ -184,15 +148,31 @@ RooAbsReal* RooGenProdProj::makeIntegral(const char* name, const RooArgSet& comp RooArgSet prodSet ; numIntSet.add(intSet) ; + // The idea of the RooGenProdProj is that we divide two integral objects each + // created with this makeIntegral() function to get the normalized integral of + // a product. Therefore, we don't need to normalize the numerater and + // denominator integrals themselves. Doing the normalization would be + // expensive and it would cancel out anyway. However, if we don't specify an + // explicit normalization integral in createIntegral(), the last-used + // normalization set might be used to normalize the pdf, resulting in + // redundant computations. + // + // For this reason, the normalization set of the integrated pdfs is fixed to + // an empty set in this case. Note that in RooFit, a nullptr normalization + // set and an empty normalization set is not equivalent. The former implies + // taking the last-used normalization set, and the latter means explicitly no + // normalization. + RooArgSet emptyNormSet{}; + for (const auto pdfAsArg : compSet) { auto pdf = static_cast(pdfAsArg); if (doFactorize && pdf->dependsOn(anaIntSet)) { RooArgSet anaSet ; - Int_t code = pdf->getAnalyticalIntegralWN(anaIntSet,anaSet,0,isetRangeName) ; + Int_t code = pdf->getAnalyticalIntegralWN(anaIntSet,anaSet,nullptr,isetRangeName) ; if (code!=0) { // Analytical integral, create integral object - RooAbsReal* pai = pdf->createIntegral(anaSet,isetRangeName) ; + std::unique_ptr pai{pdf->createIntegral(anaSet,emptyNormSet,isetRangeName)}; pai->setOperMode(_operMode) ; // Add to integral to product @@ -202,7 +182,7 @@ RooAbsReal* RooGenProdProj::makeIntegral(const char* name, const RooArgSet& comp numIntSet.remove(anaSet) ; // Declare ownership of integral - saveSet.addOwned(*pai) ; + saveSet.addOwned(std::move(pai)); } else { // Analytic integration of factorizable observable not possible, add straight pdf to product prodSet.add(*pdf) ; @@ -235,7 +215,7 @@ RooAbsReal* RooGenProdProj::makeIntegral(const char* name, const RooArgSet& comp prod->setOperMode(_operMode) ; // Create integral performing remaining numeric integration over (partial) analytic product - std::unique_ptr integral{prod->createIntegral(numIntSet,isetRangeName)}; + std::unique_ptr integral{prod->createIntegral(numIntSet,emptyNormSet,isetRangeName)}; integral->setOperMode(_operMode) ; auto ret = integral.get(); @@ -289,10 +269,3 @@ void RooGenProdProj::operModeHook() _intList.at(0)->setOperMode(_operMode) ; if (_haveD) _intList.at(1)->setOperMode(Auto) ; // Denominator always stays in Auto mode (normalization integral) } - - - - - - - diff --git a/roofit/roofitcore/src/RooGenProdProj.h b/roofit/roofitcore/src/RooGenProdProj.h new file mode 100644 index 0000000000000..0206fcbbfd122 --- /dev/null +++ b/roofit/roofitcore/src/RooGenProdProj.h @@ -0,0 +1,43 @@ +/* + * Project: RooFit + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef ROO_GEN_PROD_PROJ +#define ROO_GEN_PROD_PROJ + +#include +#include +#include + +/// General form of projected integral of product of PDFs, utility class for RooProdPdf. +class RooGenProdProj : public RooAbsReal { +public: + RooGenProdProj(const char *name, const char *title, const RooArgSet &_prodSet, const RooArgSet &_intSet, + const RooArgSet &_normSet, const char *isetRangeName, const char *normRangeName = nullptr, + bool doFactorize = true); + + RooGenProdProj(const RooGenProdProj &other, const char *name = nullptr); + TObject *clone(const char *newname) const override { return new RooGenProdProj(*this, newname); } + +private: + RooAbsReal *makeIntegral(const char *name, const RooArgSet &compSet, const RooArgSet &intSet, RooArgSet &saveSet, + const char *isetRangeName, bool doFactorize); + + void operModeHook() override; + + double evaluate() const override; + std::unique_ptr _compSetOwnedN; ///< Owner of numerator components + std::unique_ptr _compSetOwnedD; ///< Owner of denominator components + RooSetProxy _compSetN; ///< Set proxy for numerator components + RooSetProxy _compSetD; ///< Set proxy for denominator components + RooListProxy _intList; ///< Master integrals representing numerator and denominator + bool _haveD = false; ///< Do we have a denominator term? +}; + +#endif diff --git a/roofit/roofitcore/src/RooGenericPdf.cxx b/roofit/roofitcore/src/RooGenericPdf.cxx index 626380f98e67b..0fad587ac3b6d 100644 --- a/roofit/roofitcore/src/RooGenericPdf.cxx +++ b/roofit/roofitcore/src/RooGenericPdf.cxx @@ -47,12 +47,18 @@ the names of the arguments are not hard coded. #include "RooStreamParser.h" #include "RooMsgService.h" #include "RooArgList.h" -#include "RunContext.h" +#include "RooFormula.h" using namespace std; ClassImp(RooGenericPdf); +RooGenericPdf::RooGenericPdf() {} + +RooGenericPdf::~RooGenericPdf() +{ + if(_formula) delete _formula; +} //////////////////////////////////////////////////////////////////////////////// @@ -63,10 +69,13 @@ RooGenericPdf::RooGenericPdf(const char *name, const char *title, const RooArgLi _actualVars("actualVars","Variables used by PDF expression",this), _formExpr(title) { - _actualVars.add(dependents) ; - formula(); - - if (_actualVars.empty()) _value = traceEval(0) ; + if (dependents.empty()) { + _value = traceEval(nullptr); + } else { + _formula = new RooFormula(GetName(), _formExpr, dependents); + _formExpr = _formula->formulaString().c_str(); + _actualVars.add(_formula->actualDependents()); + } } @@ -80,10 +89,13 @@ RooGenericPdf::RooGenericPdf(const char *name, const char *title, _actualVars("actualVars","Variables used by PDF expression",this), _formExpr(inFormula) { - _actualVars.add(dependents) ; - formula(); - - if (_actualVars.empty()) _value = traceEval(0) ; + if (dependents.empty()) { + _value = traceEval(nullptr); + } else { + _formula = new RooFormula(GetName(), _formExpr, dependents); + _formExpr = _formula->formulaString().c_str(); + _actualVars.add(_formula->actualDependents()); + } } @@ -105,8 +117,7 @@ RooGenericPdf::RooGenericPdf(const RooGenericPdf& other, const char* name) : RooFormula& RooGenericPdf::formula() const { if (!_formula) { - const_cast&>(_formula).reset( - new RooFormula(GetName(),_formExpr.Data(),_actualVars)); + _formula = new RooFormula(GetName(),_formExpr.Data(),_actualVars); const_cast(_formExpr) = _formula->formulaString().c_str(); } return *_formula ; @@ -124,48 +135,12 @@ double RooGenericPdf::evaluate() const //////////////////////////////////////////////////////////////////////////////// -/// Evaluate this formula for values found in inputData. -RooSpan RooGenericPdf::evaluateSpan(RooBatchCompute::RunContext& inputData, const RooArgSet* normSet) const { - if (normSet != nullptr && normSet != _normSet) - throw std::logic_error("Got conflicting normSets"); - - auto results = formula().evaluateSpan(this, inputData, _normSet); - inputData.spans[this] = results; - - return results; -} - -//////////////////////////////////////////////////////////////////////////////// -void RooGenericPdf::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const -{ - formula().computeBatch(stream, output, nEvents, dataMap); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Change formula expression to given expression - -bool RooGenericPdf::setFormula(const char* inFormula) +void RooGenericPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - if (formula().reCompile(inFormula)) return true ; - - _formExpr = inFormula ; - setValueDirty() ; - return false ; + formula().computeBatch(output, nEvents, dataMap); } - -//////////////////////////////////////////////////////////////////////////////// -/// Check if given value is valid - -bool RooGenericPdf::isValidReal(double /*value*/, bool /*printError*/) const -{ - return true ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Propagate server changes to embedded formula object @@ -202,19 +177,16 @@ void RooGenericPdf::printMetaArgs(ostream& os) const } +void RooGenericPdf::dumpFormula() { formula().dump() ; } + //////////////////////////////////////////////////////////////////////////////// /// Read object contents from given stream -bool RooGenericPdf::readFromStream(istream& is, bool compact, bool /*verbose*/) +bool RooGenericPdf::readFromStream(istream& /*is*/, bool /*compact*/, bool /*verbose*/) { - if (compact) { - coutE(InputArguments) << "RooGenericPdf::readFromStream(" << GetName() << "): can't read in compact mode" << endl ; - return true ; - } else { - RooStreamParser parser(is) ; - return setFormula(parser.readLine()) ; - } + coutE(InputArguments) << "RooGenericPdf::readFromStream(" << GetName() << "): can't read" << std::endl; + return true; } @@ -229,6 +201,3 @@ void RooGenericPdf::writeToStream(ostream& os, bool compact) const os << GetTitle() ; } } - - - diff --git a/roofit/roofitcore/src/RooGlobalFunc.cxx b/roofit/roofitcore/src/RooGlobalFunc.cxx index 0c8755ecda2f3..c26e69bf0be0f 100644 --- a/roofit/roofitcore/src/RooGlobalFunc.cxx +++ b/roofit/roofitcore/src/RooGlobalFunc.cxx @@ -37,403 +37,1023 @@ using namespace std; namespace RooFit { - // anonymous namespace for helper functions for the implementation of the global functions - namespace { - - template - RooCmdArg processImportItem(std::pair const& item) { - return Import(item.first.c_str(), *item.second) ; - } - - template - RooCmdArg processLinkItem(std::pair const& item) { - return Link(item.first.c_str(), *item.second) ; - } - - RooCmdArg processSliceItem(std::pair const& item) { - return Slice(*item.first, item.second.c_str()); - } - - template - RooCmdArg processMap(const char* name, Func_t func, Map_t const& map) { - RooCmdArg container(name,0,0,0,0,0,0,0,0) ; - for (auto const& item : map) { - container.addArg(func(item)) ; - } - container.setProcessRecArgs(true,false) ; - return container ; - } - - } // namespace - - namespace Experimental { - - std::string& defaultBatchMode() { - static std::string batchMode = "off"; - return batchMode; - } - - RooCmdArg ParallelGradientOptions(bool enable, int orderStrategy, int chainFactor) { - return RooCmdArg("ParallelGradientOptions",enable,chainFactor,orderStrategy,0,0,0,0,0) ;} - RooCmdArg ParallelDescentOptions(bool enable, int splitStrategy, int numSplits) { - return RooCmdArg("ParallelDescentOptions",enable,numSplits,splitStrategy,0,0,0,0,0) ;} - - } - - // RooAbsReal::plotOn arguments - RooCmdArg DrawOption(const char* opt) { return RooCmdArg("DrawOption",0,0,0,0,opt,0,0,0) ; } - RooCmdArg Slice(const RooArgSet& sliceSet) { - RooCmdArg out{"SliceVars",0}; - out.setSet(0, sliceSet); - return out; - } - RooCmdArg Slice(RooCategory& cat, const char* label) { return RooCmdArg("SliceCat",0,0,0,0,label,0,&cat,0) ; } - RooCmdArg Slice(std::map const& arg) { - return processMap("SliceCatMany", processSliceItem, arg); - } - - RooCmdArg Project(const RooArgSet& projSet) { - RooCmdArg out{"Project",0}; - out.setSet(0, projSet); - return out; - } - RooCmdArg ProjWData(const RooArgSet& projSet, - const RooAbsData& projData, - bool binData) { - RooCmdArg out{"ProjData",binData,0,0,0,0,0,nullptr,&projData}; - out.setSet(0, projSet); - return out; - } - RooCmdArg ProjWData(const RooAbsData& projData, - bool binData) { return RooCmdArg("ProjData",binData,0,0,0,0,0,0,&projData) ; } - RooCmdArg Asymmetry(const RooCategory& cat) { return RooCmdArg("Asymmetry",0,0,0,0,0,0,&cat,0) ; } - RooCmdArg Precision(double prec) { return RooCmdArg("Precision",0,0,prec,0,0,0,0,0) ; } - RooCmdArg ShiftToZero() { return RooCmdArg("ShiftToZero",1) ; } - RooCmdArg Normalization(double scaleFactor) { return RooCmdArg("Normalization",RooAbsReal::Relative,0,scaleFactor,0,0,0,0,0) ; } - RooCmdArg Range(const char* rangeName, bool adjustNorm) { return RooCmdArg("RangeWithName",adjustNorm,0,0,0,rangeName,0,0,0) ; } - RooCmdArg Range(double lo, double hi, bool adjustNorm){ return RooCmdArg("Range",adjustNorm,0,lo,hi,0,0,0,0) ; } - RooCmdArg NormRange(const char* rangeNameList) { return RooCmdArg("NormRange",0,0,0,0,rangeNameList,0,0,0) ; } - RooCmdArg VLines() { return RooCmdArg("VLines",1,0,0,0,0,0,0,0) ; } - RooCmdArg LineColor(Color_t color) { return RooCmdArg("LineColor",color) ; } - RooCmdArg LineStyle(Style_t style) { return RooCmdArg("LineStyle",style) ; } - RooCmdArg LineWidth(Width_t width) { return RooCmdArg("LineWidth",width) ; } - RooCmdArg FillColor(Color_t color) { return RooCmdArg("FillColor",color) ; } - RooCmdArg FillStyle(Style_t style) { return RooCmdArg("FillStyle",style) ; } - RooCmdArg ProjectionRange(const char* rangeName) { return RooCmdArg("ProjectionRange",0,0,0,0,rangeName,0,0,0) ; } - RooCmdArg Name(const char* name) { return RooCmdArg("Name",0,0,0,0,name,0,0,0) ; } - RooCmdArg Invisible(bool inv) { return RooCmdArg("Invisible",inv,0,0,0,0,0,0,0) ; } - RooCmdArg AddTo(const char* name, double wgtSel, double wgtOther) { return RooCmdArg("AddTo",0,0,wgtSel,wgtOther,name,0,0,0) ; } - RooCmdArg EvalErrorValue(double val) { return RooCmdArg("EvalErrorValue",1,0,val,0,0,0,0,0) ; } - RooCmdArg MoveToBack() { return RooCmdArg("MoveToBack",1,0,0,0,0,0,0,0) ; } - RooCmdArg VisualizeError(const RooFitResult& fitres, double Z, bool EVmethod) { return RooCmdArg("VisualizeError",EVmethod,0,Z,0,0,0,&fitres,0) ; } - RooCmdArg VisualizeError(const RooFitResult& fitres, const RooArgSet& param, double Z, bool EVmethod) - { return RooCmdArg("VisualizeError",EVmethod,0,Z,0,0,0,&fitres,0,0,0,¶m) ; } - RooCmdArg VisualizeError(const RooDataSet& paramData, double Z) { return RooCmdArg("VisualizeErrorData",0,0,Z,0,0,0,¶mData,0) ; } - RooCmdArg ShowProgress() { return RooCmdArg("ShowProgress",1,0,0,0,0,0,0,0) ; } - - // RooAbsPdf::plotOn arguments - RooCmdArg Components(const char* compSpec) { return RooCmdArg("SelectCompSpec",0,0,0,0,compSpec,0,0,0) ; } - RooCmdArg Normalization(double scaleFactor, Int_t scaleType) - { return RooCmdArg("Normalization",scaleType,0,scaleFactor,0,0,0,0,0) ; } - - // RooAbsData::plotOn arguments - RooCmdArg Cut(const char* cutSpec) { return RooCmdArg("CutSpec",0,0,0,0,cutSpec,0,0,0) ; } - RooCmdArg Cut(const RooFormulaVar& cutVar) { return RooCmdArg("CutVar",0,0,0,0,0,0,&cutVar,0) ; } - RooCmdArg Binning(const RooAbsBinning& binning) { return RooCmdArg("Binning",0,0,0,0,0,0,&binning,0) ;} - RooCmdArg Binning(const char* binningName) { return RooCmdArg("BinningName",0,0,0,0,binningName,0,0,0) ;} - RooCmdArg Binning(int nBins, double xlo, double xhi) { return RooCmdArg("BinningSpec",nBins,0,xlo,xhi,0,0,0,0) ;} - RooCmdArg MarkerStyle(Style_t style) { return RooCmdArg("MarkerStyle",style,0,0,0,0,0,0,0) ; } - RooCmdArg MarkerSize(Size_t size) { return RooCmdArg("MarkerSize",0,0,size,0,0,0,0,0) ; } - RooCmdArg MarkerColor(Color_t color) { return RooCmdArg("MarkerColor",color,0,0,0,0,0,0,0) ; } - RooCmdArg CutRange(const char* rangeName) { return RooCmdArg("CutRange",0,0,0,0,rangeName,0,0,0) ; } - RooCmdArg XErrorSize(double width) { return RooCmdArg("XErrorSize",0,0,width,0,0,0,0,0) ; } - RooCmdArg RefreshNorm() { return RooCmdArg("RefreshNorm",1,0,0,0,0,0,0,0) ; } - RooCmdArg Efficiency(const RooCategory& cat) { return RooCmdArg("Efficiency",0,0,0,0,0,0,&cat,0) ; } - RooCmdArg Rescale(double factor) { return RooCmdArg("Rescale",0,0,factor,0,0,0,0,0) ; } - - // RooDataHist::ctor arguments - RooCmdArg Weight(double wgt) { return RooCmdArg("Weight",0,0,wgt,0,0,0,0,0) ; } - RooCmdArg Index(RooCategory& icat) { return RooCmdArg("IndexCat",0,0,0,0,0,0,&icat,0) ; } - RooCmdArg Import(const char* state, TH1& histo) { return RooCmdArg("ImportHistoSlice",0,0,0,0,state,0,&histo,0) ; } - RooCmdArg Import(const char* state, RooDataHist& dhist) { return RooCmdArg("ImportDataHistSlice",0,0,0,0,state,0,&dhist,0) ; } - RooCmdArg Import(TH1& histo, bool importDensity) { return RooCmdArg("ImportHisto",importDensity,0,0,0,0,0,&histo,0) ; } - - RooCmdArg Import(const std::map& arg) { - return processMap("ImportDataHistSliceMany", processImportItem, arg); - } - RooCmdArg Import(const std::map& arg) { - return processMap("ImportHistoSliceMany", processImportItem, arg); - } - - - // RooDataSet::ctor arguments - RooCmdArg WeightVar(const char* name, bool reinterpretAsWeight) { return RooCmdArg("WeightVarName",reinterpretAsWeight,0,0,0,name,0,0,0) ; } - RooCmdArg WeightVar(const RooRealVar& arg, bool reinterpretAsWeight) { return RooCmdArg("WeightVar",reinterpretAsWeight,0,0,0,0,0,&arg,0) ; } - RooCmdArg Link(const char* state, RooAbsData& data) { return RooCmdArg("LinkDataSlice",0,0,0,0,state,0,&data,0) ;} - RooCmdArg Import(const char* state, RooDataSet& data) { return RooCmdArg("ImportDataSlice",0,0,0,0,state,0,&data,0) ; } - RooCmdArg Import(RooDataSet& data) { return RooCmdArg("ImportData",0,0,0,0,0,0,&data,0) ; } - RooCmdArg Import(TTree& tree) { return RooCmdArg("ImportTree",0,0,0,0,0,0,reinterpret_cast(&tree),0) ; } - RooCmdArg ImportFromFile(const char* fname, const char* tname){ return RooCmdArg("ImportFromFile",0,0,0,0,fname,tname,0,0) ; } - RooCmdArg StoreError(const RooArgSet& aset) { return RooCmdArg("StoreError",0,0,0,0,0,0,0,0,0,0,&aset) ; } - RooCmdArg StoreAsymError(const RooArgSet& aset) { return RooCmdArg("StoreAsymError",0,0,0,0,0,0,0,0,0,0,&aset) ; } - RooCmdArg OwnLinked() { return RooCmdArg("OwnLinked",1,0,0,0,0,0,0,0,0,0,0) ; } - - RooCmdArg Import(const std::map& arg) { - return processMap("ImportDataSliceMany", processImportItem, arg); - } - RooCmdArg Link(const std::map& arg) { - return processMap("LinkDataSliceMany", processLinkItem, arg); - } - - - // RooChi2Var::ctor / RooNLLVar arguments - RooCmdArg Extended(bool flag) { return RooCmdArg("Extended",flag,0,0,0,0,0,0,0) ; } - RooCmdArg DataError(Int_t etype) { return RooCmdArg("DataError",(Int_t)etype,0,0,0,0,0,0,0) ; } - RooCmdArg NumCPU(Int_t nCPU, Int_t interleave) { return RooCmdArg("NumCPU",nCPU,interleave,0,0,0,0,0,0) ; } - RooCmdArg ModularL(bool flag) { return RooCmdArg("ModularL",flag,0,0,0,0,0,0) ; } - RooCmdArg Parallelize(Int_t nWorkers) { return RooCmdArg("Parallelize",nWorkers,0,0,0,0,0,0,0) ; } - RooCmdArg TimingAnalysis(bool flag) { return RooCmdArg("TimingAnalysis",flag,0,0,0,0,0,0) ; } - RooCmdArg BatchMode(std::string const& batchMode) { - std::string lower = batchMode; - std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c){ return std::tolower(c); }); - BatchModeOption mode; - if(lower == "off") mode = BatchModeOption::Off; - else if(lower == "cpu") mode = BatchModeOption::Cpu; - else if(lower == "cuda") mode = BatchModeOption::Cuda; - else if(lower == "old") mode = BatchModeOption::Old; - // Note that the "old" argument is undocumented, because accessing the - // old batch mode is an advanced developer feature. - else throw std::runtime_error("Only supported string values for BatchMode() are \"off\", \"cpu\", or \"cuda\"."); - return RooCmdArg("BatchMode", static_cast(mode)); - } - /// Integrate the PDF over bins. Improves accuracy for binned fits. Switch off using `0.` as argument. \see RooAbsPdf::fitTo(). - RooCmdArg IntegrateBins(double precision) { return RooCmdArg("IntegrateBins", 0, 0, precision); } - - // RooAbsCollection::printLatex arguments - RooCmdArg Columns(Int_t ncol) { return RooCmdArg("Columns",ncol,0,0,0,0,0,0,0) ; } - RooCmdArg OutputFile(const char* fileName) { return RooCmdArg("OutputFile",0,0,0,0,fileName,0,0,0) ; } - RooCmdArg Sibling(const RooAbsCollection& sibling) { return RooCmdArg("Sibling",0,0,0,0,0,0,&sibling,0) ; } - RooCmdArg Format(const char* format, Int_t sigDigit) { return RooCmdArg("Format",sigDigit,0,0,0,format,0,0,0) ; } - RooCmdArg Format(const char* what, const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, - const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) { - RooCmdArg ret("FormatArgs",0,0,0,0,what,0,0,0) ; ret.addArg(arg1) ; ret.addArg(arg2) ; - ret.addArg(arg3) ; ret.addArg(arg4) ; ret.addArg(arg5) ; ret.addArg(arg6) ; ret.addArg(arg7) ; ret.addArg(arg8) ; - ret.setProcessRecArgs(false) ; return ret ; - } - - // RooAbsRealLValue::frame arguments - RooCmdArg Title(const char* name) { return RooCmdArg("Title",0,0,0,0,name,0,0,0) ; } - RooCmdArg Bins(Int_t nbin) { return RooCmdArg("Bins",nbin,0,0,0,0,0,0,0) ; } - RooCmdArg AutoSymRange(const RooAbsData& data, double marginFactor) { return RooCmdArg("AutoRange",1,0,marginFactor,0,0,0,&data,0) ; } - RooCmdArg AutoRange(const RooAbsData& data, double marginFactor) { return RooCmdArg("AutoRange",0,0,marginFactor,0,0,0,&data,0) ; } - - // RooAbsData::reduce arguments - RooCmdArg SelectVars(const RooArgSet& vars) { - RooCmdArg out{"SelectVars",0}; - out.setSet(0, vars); - return out; - } - RooCmdArg EventRange(Int_t nStart, Int_t nStop) { return RooCmdArg("EventRange",nStart,nStop,0,0,0,0,0,0) ; } - - // RooAbsPdf::fitTo arguments - RooCmdArg PrefitDataFraction(double data_ratio) { return RooCmdArg("Prefit",0,0,data_ratio,0,nullptr,nullptr,nullptr,nullptr) ; } - RooCmdArg Optimize(Int_t flag) { return RooCmdArg("Optimize",flag) ; } - RooCmdArg Verbose(bool flag) { return RooCmdArg("Verbose",flag) ; } - RooCmdArg Save(bool flag) { return RooCmdArg("Save",flag) ; } - RooCmdArg Timer(bool flag) { return RooCmdArg("Timer",flag) ; } - RooCmdArg PrintLevel(Int_t level) { return RooCmdArg("PrintLevel",level) ; } - RooCmdArg MaxCalls(int n) { return RooCmdArg("MaxCalls",n) ; } - RooCmdArg Warnings(bool flag) { return RooCmdArg("Warnings",flag) ; } - RooCmdArg Strategy(Int_t code) { return RooCmdArg("Strategy",code) ; } - RooCmdArg InitialHesse(bool flag) { return RooCmdArg("InitialHesse",flag) ; } - RooCmdArg Hesse(bool flag) { return RooCmdArg("Hesse",flag) ; } - RooCmdArg Minos(bool flag) { return RooCmdArg("Minos",flag) ; } - RooCmdArg Minos(const RooArgSet& minosArgs) { - RooCmdArg out{"Minos",1}; - out.setSet(0, minosArgs); - return out; - } - RooCmdArg SplitRange(bool flag) { return RooCmdArg("SplitRange",flag,0,0,0,0,0,0,0) ; } - RooCmdArg SumCoefRange(const char* rangeName) { return RooCmdArg("SumCoefRange",0,0,0,0,rangeName,0,0,0) ; } - RooCmdArg Constrain(const RooArgSet& params) { - for(RooAbsArg * param : params) { - if(!dynamic_cast(param)) { - std::stringstream errorMsg; - errorMsg << "RooFit::Constrain(): you passed the argument \"" << param->GetName() - << "\", but it's not a RooRealVar!" - << " You can only constrain parameters, which must be RooRealVars."; - oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl; - throw std::invalid_argument(errorMsg.str().c_str()); +// anonymous namespace for helper functions for the implementation of the global functions +namespace { + +template +RooCmdArg processImportItem(std::pair const &item) +{ + return Import(item.first.c_str(), *item.second); +} + +template +RooCmdArg processLinkItem(std::pair const &item) +{ + return Link(item.first.c_str(), *item.second); +} + +RooCmdArg processSliceItem(std::pair const &item) +{ + return Slice(*item.first, item.second.c_str()); +} + +template +RooCmdArg processMap(const char *name, Func_t func, Map_t const &map) +{ + RooCmdArg container(name, 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); + for (auto const &item : map) { + container.addArg(func(item)); + } + container.setProcessRecArgs(true, false); + return container; +} + +} // namespace + +namespace Experimental { + +RooCmdArg ParallelGradientOptions(bool enable, int orderStrategy, int chainFactor) +{ + return RooCmdArg("ParallelGradientOptions", enable, chainFactor, orderStrategy, 0, nullptr, nullptr, nullptr, + nullptr); +} +RooCmdArg ParallelDescentOptions(bool enable, int splitStrategy, int numSplits) +{ + return RooCmdArg("ParallelDescentOptions", enable, numSplits, splitStrategy, 0, nullptr, nullptr, nullptr, nullptr); +} + +} // namespace Experimental + +// RooAbsReal::plotOn arguments +RooCmdArg DrawOption(const char *opt) +{ + return RooCmdArg("DrawOption", 0, 0, 0, 0, opt, nullptr, nullptr, nullptr); +} +RooCmdArg Slice(const RooArgSet &sliceSet) +{ + RooCmdArg out{"SliceVars", 0}; + out.setSet(0, sliceSet); + return out; +} +RooCmdArg Slice(RooCategory &cat, const char *label) +{ + // We don't support adding multiple slices for a single category by + // concatenating labels with a comma. Users were trying to do that, and were + // surprised it did not work. So we explicitly check if there is a comma, + // and if there is, we will give some helpful advice on how to get to the + // desired plot. + std::string lbl{label}; + if (lbl.find(',') != std::string::npos) { + std::stringstream errorMsg; + errorMsg << "RooFit::Slice(): you tried to pass a comma-separated list of state labels \"" << label + << "\" for a given category, but selecting multiple slices like this is not supported!" + << " If you want to make a plot of multiple slices, use the ProjWData() command where you pass a " + "dataset that includes " + "the desired slices. If the slices are a subset of all slices, then you can create such a dataset " + "with RooAbsData::reduce(RooFit::Cut(\"cat==cat::label_1 || cat==cat::label_2 || ...\")). You can " + "find some examples in the rf501_simultaneouspdf tutorial."; + oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl; + throw std::invalid_argument(errorMsg.str().c_str()); + } + return RooCmdArg("SliceCat", 0, 0, 0, 0, label, nullptr, &cat, nullptr); +} +RooCmdArg Slice(std::map const &arg) +{ + return processMap("SliceCatMany", processSliceItem, arg); +} + +RooCmdArg Project(const RooArgSet &projSet) +{ + RooCmdArg out{"Project", 0}; + out.setSet(0, projSet); + return out; +} +RooCmdArg ProjWData(const RooArgSet &projSet, const RooAbsData &projData, bool binData) +{ + RooCmdArg out{"ProjData", binData, 0, 0, 0, nullptr, nullptr, nullptr, &projData}; + out.setSet(0, projSet); + return out; +} +RooCmdArg ProjWData(const RooAbsData &projData, bool binData) +{ + return RooCmdArg("ProjData", binData, 0, 0, 0, nullptr, nullptr, nullptr, &projData); +} +RooCmdArg Asymmetry(const RooCategory &cat) +{ + return RooCmdArg("Asymmetry", 0, 0, 0, 0, nullptr, nullptr, &cat, nullptr); +} +RooCmdArg Precision(double prec) +{ + return RooCmdArg("Precision", 0, 0, prec, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ShiftToZero() +{ + return RooCmdArg("ShiftToZero", 1); +} +RooCmdArg Normalization(double scaleFactor) +{ + return RooCmdArg("Normalization", RooAbsReal::Relative, 0, scaleFactor, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Range(const char *rangeName, bool adjustNorm) +{ + return RooCmdArg("RangeWithName", adjustNorm, 0, 0, 0, rangeName, nullptr, nullptr, nullptr); +} +RooCmdArg Range(double lo, double hi, bool adjustNorm) +{ + return RooCmdArg("Range", adjustNorm, 0, lo, hi, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg NormRange(const char *rangeNameList) +{ + return RooCmdArg("NormRange", 0, 0, 0, 0, rangeNameList, nullptr, nullptr, nullptr); +} +RooCmdArg VLines() +{ + return RooCmdArg("VLines", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg LineColor(Color_t color) +{ + return RooCmdArg("LineColor", color); +} +RooCmdArg LineStyle(Style_t style) +{ + return RooCmdArg("LineStyle", style); +} +RooCmdArg LineWidth(Width_t width) +{ + return RooCmdArg("LineWidth", width); +} +RooCmdArg FillColor(Color_t color) +{ + return RooCmdArg("FillColor", color); +} +RooCmdArg FillStyle(Style_t style) +{ + return RooCmdArg("FillStyle", style); +} +RooCmdArg ProjectionRange(const char *rangeName) +{ + return RooCmdArg("ProjectionRange", 0, 0, 0, 0, rangeName, nullptr, nullptr, nullptr); +} +RooCmdArg Name(const char *name) +{ + return RooCmdArg("Name", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg Invisible(bool inv) +{ + return RooCmdArg("Invisible", inv, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg AddTo(const char *name, double wgtSel, double wgtOther) +{ + return RooCmdArg("AddTo", 0, 0, wgtSel, wgtOther, name, nullptr, nullptr, nullptr); +} +RooCmdArg EvalErrorValue(double val) +{ + return RooCmdArg("EvalErrorValue", 1, 0, val, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg MoveToBack() +{ + return RooCmdArg("MoveToBack", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg VisualizeError(const RooFitResult &fitres, double Z, bool EVmethod) +{ + return RooCmdArg("VisualizeError", EVmethod, 0, Z, 0, nullptr, nullptr, &fitres, nullptr); +} +RooCmdArg VisualizeError(const RooFitResult &fitres, const RooArgSet ¶m, double Z, bool EVmethod) +{ + return RooCmdArg("VisualizeError", EVmethod, 0, Z, 0, nullptr, nullptr, &fitres, nullptr, nullptr, nullptr, ¶m); +} +RooCmdArg VisualizeError(const RooDataSet ¶mData, double Z) +{ + return RooCmdArg("VisualizeErrorData", 0, 0, Z, 0, nullptr, nullptr, ¶mData, nullptr); +} +RooCmdArg ShowProgress() +{ + return RooCmdArg("ShowProgress", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsPdf::plotOn arguments +RooCmdArg Components(const char *compSpec) +{ + return RooCmdArg("SelectCompSpec", 0, 0, 0, 0, compSpec, nullptr, nullptr, nullptr); +} +RooCmdArg Normalization(double scaleFactor, Int_t scaleType) +{ + return RooCmdArg("Normalization", scaleType, 0, scaleFactor, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsData::plotOn arguments +RooCmdArg Cut(const char *cutSpec) +{ + return RooCmdArg("CutSpec", 0, 0, 0, 0, cutSpec, nullptr, nullptr, nullptr); +} +RooCmdArg Cut(const RooFormulaVar &cutVar) +{ + return RooCmdArg("CutVar", 0, 0, 0, 0, nullptr, nullptr, &cutVar, nullptr); +} +RooCmdArg Binning(const RooAbsBinning &binning) +{ + return RooCmdArg("Binning", 0, 0, 0, 0, nullptr, nullptr, &binning, nullptr); +} +RooCmdArg Binning(const char *binningName) +{ + return RooCmdArg("BinningName", 0, 0, 0, 0, binningName, nullptr, nullptr, nullptr); +} +RooCmdArg Binning(int nBins, double xlo, double xhi) +{ + return RooCmdArg("BinningSpec", nBins, 0, xlo, xhi, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg MarkerStyle(Style_t style) +{ + return RooCmdArg("MarkerStyle", style, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg MarkerSize(Size_t size) +{ + return RooCmdArg("MarkerSize", 0, 0, size, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg MarkerColor(Color_t color) +{ + return RooCmdArg("MarkerColor", color, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg CutRange(const char *rangeName) +{ + return RooCmdArg("CutRange", 0, 0, 0, 0, rangeName, nullptr, nullptr, nullptr); +} +RooCmdArg XErrorSize(double width) +{ + return RooCmdArg("XErrorSize", 0, 0, width, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg RefreshNorm() +{ + return RooCmdArg("RefreshNorm", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Efficiency(const RooCategory &cat) +{ + return RooCmdArg("Efficiency", 0, 0, 0, 0, nullptr, nullptr, &cat, nullptr); +} +RooCmdArg Rescale(double factor) +{ + return RooCmdArg("Rescale", 0, 0, factor, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooDataHist::ctor arguments +RooCmdArg Weight(double wgt) +{ + return RooCmdArg("Weight", 0, 0, wgt, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Index(RooCategory &icat) +{ + return RooCmdArg("IndexCat", 0, 0, 0, 0, nullptr, nullptr, &icat, nullptr); +} +RooCmdArg Import(const char *state, TH1 &histo) +{ + return RooCmdArg("ImportDataSlice", 0, 0, 0, 0, state, nullptr, &histo, nullptr); +} +RooCmdArg Import(const char *state, RooDataHist &dhist) +{ + return RooCmdArg("ImportDataSlice", 0, 0, 0, 0, state, nullptr, &dhist, nullptr); +} +RooCmdArg Import(TH1 &histo, bool importDensity) +{ + return RooCmdArg("ImportHisto", importDensity, 0, 0, 0, nullptr, nullptr, &histo, nullptr); +} + +RooCmdArg Import(const std::map &arg) +{ + return processMap("ImportDataSliceMany", processImportItem, arg); +} +RooCmdArg Import(const std::map &arg) +{ + return processMap("ImportDataSliceMany", processImportItem, arg); +} + +// RooDataSet::ctor arguments +RooCmdArg WeightVar(const char *name, bool reinterpretAsWeight) +{ + if (name == nullptr) + return RooCmdArg::none(); // Passing a nullptr name means no weight variable + return RooCmdArg("WeightVarName", reinterpretAsWeight, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg WeightVar(const RooRealVar &arg, bool reinterpretAsWeight) +{ + return RooCmdArg("WeightVar", reinterpretAsWeight, 0, 0, 0, nullptr, nullptr, &arg, nullptr); +} +RooCmdArg Link(const char *state, RooAbsData &data) +{ + return RooCmdArg("LinkDataSlice", 0, 0, 0, 0, state, nullptr, &data, nullptr); +} +RooCmdArg Import(const char *state, RooAbsData &data) +{ + return RooCmdArg("ImportDataSlice", 0, 0, 0, 0, state, nullptr, &data, nullptr); +} +RooCmdArg Import(RooAbsData &data) +{ + return RooCmdArg("ImportData", 0, 0, 0, 0, nullptr, nullptr, &data, nullptr); +} +RooCmdArg Import(TTree &tree) +{ + return RooCmdArg("ImportTree", 0, 0, 0, 0, nullptr, nullptr, reinterpret_cast(&tree), nullptr); +} +RooCmdArg ImportFromFile(const char *fname, const char *tname) +{ + return RooCmdArg("ImportFromFile", 0, 0, 0, 0, fname, tname, nullptr, nullptr); +} +RooCmdArg StoreError(const RooArgSet &aset) +{ + return RooCmdArg("StoreError", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &aset); +} +RooCmdArg StoreAsymError(const RooArgSet &aset) +{ + return RooCmdArg("StoreAsymError", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &aset); +} +RooCmdArg OwnLinked() +{ + return RooCmdArg("OwnLinked", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); +} + +RooCmdArg Import(const std::map &arg) +{ + return processMap("ImportDataSliceMany", processImportItem, arg); +} +RooCmdArg Link(const std::map &arg) +{ + return processMap("LinkDataSliceMany", processLinkItem, arg); +} + +// RooChi2Var::ctor / RooNLLVar arguments +RooCmdArg Extended(bool flag) +{ + return RooCmdArg("Extended", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg DataError(Int_t etype) +{ + return RooCmdArg("DataError", (Int_t)etype, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg NumCPU(Int_t nCPU, Int_t interleave) +{ + return RooCmdArg("NumCPU", nCPU, interleave, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ModularL(bool flag) +{ + return RooCmdArg("ModularL", flag, 0, 0, 0, nullptr, nullptr, nullptr); +} +RooCmdArg Parallelize(Int_t nWorkers) +{ + return RooCmdArg("Parallelize", nWorkers, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg TimingAnalysis(bool flag) +{ + return RooCmdArg("TimingAnalysis", flag, 0, 0, 0, nullptr, nullptr, nullptr); +} +RooCmdArg BatchMode(std::string const &batchMode) +{ + oocoutW(nullptr, InputArguments) << "The BatchMode() command argument is deprecated. Please use EvalBackend() instead." << std::endl; + std::string lower = batchMode; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); }); + if (lower == "off") + return EvalBackend::Legacy(); + else if (lower == "cpu") + return EvalBackend::Cpu(); + else if (lower == "cuda") + return EvalBackend::Cuda(); + throw std::runtime_error("Only supported string values for BatchMode() are \"off\", \"cpu\", or \"cuda\"."); +} +/// Integrate the PDF over bins. Improves accuracy for binned fits. Switch off using `0.` as argument. \see +/// RooAbsPdf::fitTo(). +RooCmdArg IntegrateBins(double precision) +{ + return RooCmdArg("IntegrateBins", 0, 0, precision); +} + +// RooAbsCollection::printLatex arguments +RooCmdArg Columns(Int_t ncol) +{ + return RooCmdArg("Columns", ncol, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg OutputFile(const char *fileName) +{ + return RooCmdArg("OutputFile", 0, 0, 0, 0, fileName, nullptr, nullptr, nullptr); +} +RooCmdArg Sibling(const RooAbsCollection &sibling) +{ + return RooCmdArg("Sibling", 0, 0, 0, 0, nullptr, nullptr, &sibling, nullptr); +} +RooCmdArg Format(const char *what, const RooCmdArg &arg1, const RooCmdArg &arg2, const RooCmdArg &arg3, + const RooCmdArg &arg4, const RooCmdArg &arg5, const RooCmdArg &arg6, const RooCmdArg &arg7, + const RooCmdArg &arg8) +{ + RooCmdArg ret("FormatArgs", 0, 0, 0, 0, what, nullptr, nullptr, nullptr); + ret.addArg(arg1); + ret.addArg(arg2); + ret.addArg(arg3); + ret.addArg(arg4); + ret.addArg(arg5); + ret.addArg(arg6); + ret.addArg(arg7); + ret.addArg(arg8); + ret.setProcessRecArgs(false); + return ret; +} + +// RooAbsRealLValue::frame arguments +RooCmdArg Title(const char *name) +{ + return RooCmdArg("Title", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg Bins(Int_t nbin) +{ + return RooCmdArg("Bins", nbin, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg AutoSymRange(const RooAbsData &data, double marginFactor) +{ + return RooCmdArg("AutoRange", 1, 0, marginFactor, 0, nullptr, nullptr, &data, nullptr); +} +RooCmdArg AutoRange(const RooAbsData &data, double marginFactor) +{ + return RooCmdArg("AutoRange", 0, 0, marginFactor, 0, nullptr, nullptr, &data, nullptr); +} + +// RooAbsData::reduce arguments +RooCmdArg SelectVars(const RooArgSet &vars) +{ + RooCmdArg out{"SelectVars", 0}; + out.setSet(0, vars); + return out; +} +RooCmdArg EventRange(Int_t nStart, Int_t nStop) +{ + return RooCmdArg("EventRange", nStart, nStop, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsPdf::fitTo arguments + +EvalBackend::EvalBackend(EvalBackend::Value value) : RooCmdArg{"EvalBackend", static_cast(value)} {} +EvalBackend::EvalBackend(std::string const &name) : EvalBackend{toValue(name)} {} +EvalBackend::Value EvalBackend::toValue(std::string const &name) +{ + std::string lower = name; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); }); + if (lower == toName(Value::Legacy)) + return Value::Legacy; + if (lower == toName(Value::Cpu)) + return Value::Cpu; + if (lower == toName(Value::Cuda)) + return Value::Cuda; + if (lower == toName(Value::Codegen)) + return Value::Codegen; + if (lower == toName(Value::CodegenNoGrad)) + return Value::CodegenNoGrad; + throw std::runtime_error("Only supported string values for EvalBackend() are \"legacy\", \"cpu\", \"cuda\", " + "\"codegen\", or \"codegen_no_grad\"."); +} +EvalBackend EvalBackend::Legacy() +{ + return EvalBackend(Value::Legacy); +} +EvalBackend EvalBackend::Cpu() +{ + return EvalBackend(Value::Cpu); +} +EvalBackend EvalBackend::Cuda() +{ + return EvalBackend(Value::Cpu); +} +EvalBackend EvalBackend::Codegen() +{ + return EvalBackend(Value::Codegen); +} +EvalBackend EvalBackend::CodegenNoGrad() +{ + return EvalBackend(Value::CodegenNoGrad); +} +std::string EvalBackend::name() const +{ + return toName(value()); +} +std::string EvalBackend::toName(EvalBackend::Value value) +{ + if (value == Value::Legacy) + return "legacy"; + if (value == Value::Cpu) + return "cpu"; + if (value == Value::Cuda) + return "cuda"; + if (value == Value::Codegen) + return "codegen"; + if (value == Value::CodegenNoGrad) + return "codegen_no_grad"; + return ""; +} +EvalBackend::Value &EvalBackend::defaultValue() +{ + static Value value = Value::Legacy; + return value; +} + +RooCmdArg PrefitDataFraction(double data_ratio) +{ + return RooCmdArg("Prefit", 0, 0, data_ratio, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Optimize(Int_t flag) +{ + return RooCmdArg("Optimize", flag); +} +RooCmdArg Verbose(bool flag) +{ + return RooCmdArg("Verbose", flag); +} +RooCmdArg Save(bool flag) +{ + return RooCmdArg("Save", flag); +} +RooCmdArg Timer(bool flag) +{ + return RooCmdArg("Timer", flag); +} +RooCmdArg PrintLevel(Int_t level) +{ + return RooCmdArg("PrintLevel", level); +} +RooCmdArg MaxCalls(int n) +{ + return RooCmdArg("MaxCalls", n); +} +RooCmdArg Warnings(bool flag) +{ + return RooCmdArg("Warnings", flag); +} +RooCmdArg Strategy(Int_t code) +{ + return RooCmdArg("Strategy", code); +} +RooCmdArg InitialHesse(bool flag) +{ + return RooCmdArg("InitialHesse", flag); +} +RooCmdArg Hesse(bool flag) +{ + return RooCmdArg("Hesse", flag); +} +RooCmdArg Minos(bool flag) +{ + return RooCmdArg("Minos", flag); +} +RooCmdArg Minos(const RooArgSet &minosArgs) +{ + RooCmdArg out{"Minos", 1}; + out.setSet(0, minosArgs); + return out; +} +RooCmdArg SplitRange(bool flag) +{ + return RooCmdArg("SplitRange", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg SumCoefRange(const char *rangeName) +{ + return RooCmdArg("SumCoefRange", 0, 0, 0, 0, rangeName, nullptr, nullptr, nullptr); +} +RooCmdArg Constrain(const RooArgSet ¶ms) +{ + for (RooAbsArg *param : params) { + if (!dynamic_cast(param)) { + std::stringstream errorMsg; + errorMsg << "RooFit::Constrain(): you passed the argument \"" << param->GetName() + << "\", but it's not a RooRealVar!" + << " You can only constrain parameters, which must be RooRealVars."; + oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl; + throw std::invalid_argument(errorMsg.str().c_str()); } - } - return RooCmdArg("Constrain",0,0,0,0,0,0,0,0,0,0,¶ms); - } - RooCmdArg GlobalObservablesSource(const char* sourceName) { return {"GlobalObservablesSource",0,0,0,0,sourceName,0,0,0}; } - RooCmdArg GlobalObservablesTag(const char* tagName) { return RooCmdArg("GlobalObservablesTag",0,0,0,0,tagName,0,0,0) ; } - RooCmdArg ExternalConstraints(const RooArgSet& cpdfs) { return RooCmdArg("ExternalConstraints",0,0,0,0,0,0,nullptr,nullptr,0,0,&cpdfs) ; } - RooCmdArg PrintEvalErrors(Int_t numErrors) { return RooCmdArg("PrintEvalErrors",numErrors,0,0,0,0,0,0,0) ; } - RooCmdArg EvalErrorWall(bool flag) { return RooCmdArg("EvalErrorWall",flag,0,0,0,0,0,0,0) ; } - RooCmdArg SumW2Error(bool flag) { return RooCmdArg("SumW2Error",flag,0,0,0,0,0,0,0) ; } - RooCmdArg AsymptoticError(bool flag) { return RooCmdArg("AsymptoticError",flag,0,0,0,0,0,0,0) ; } - RooCmdArg CloneData(bool flag) { return RooCmdArg("CloneData",flag,0,0,0,0,0,0,0) ; } - RooCmdArg Integrate(bool flag) { return RooCmdArg("Integrate",flag,0,0,0,0,0,0,0) ; } - RooCmdArg Minimizer(const char* type, const char* alg) { return RooCmdArg("Minimizer",0,0,0,0,type,alg,0,0) ; } - - RooCmdArg Offset(std::string const& mode) { - std::string lower = mode; - std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c){ return std::tolower(c); }); - OffsetMode modeVal = OffsetMode::Off; - if(lower == "off") modeVal = OffsetMode::Off; - else if(lower == "initial") modeVal = OffsetMode::Initial; - else if(lower == "bin") modeVal = OffsetMode::Bin; - return RooCmdArg("OffsetLikelihood", static_cast(modeVal)); - } - - /// When parameters are chosen such that a PDF is undefined, try to indicate to the minimiser how to leave this region. - /// \param strength Strength of hints for minimiser. Set to zero to switch off. - RooCmdArg RecoverFromUndefinedRegions(double strength) { return RooCmdArg("RecoverFromUndefinedRegions",0,0,strength,0,0,0,0,0) ; } - - - // RooAbsPdf::paramOn arguments - RooCmdArg Label(const char* str) { return RooCmdArg("Label",0,0,0,0,str,0,0,0) ; } - RooCmdArg Layout(double xmin, double xmax, double ymin) { return RooCmdArg("Layout",Int_t(ymin*10000),0,xmin,xmax,0,0,0,0) ; } - RooCmdArg Parameters(const RooArgSet& params) { - RooCmdArg out{"Parameters",0}; - out.setSet(0, params); - return out; - } - RooCmdArg ShowConstants(bool flag) { return RooCmdArg("ShowConstants",flag,0,0,0,0,0,0,0) ; } - - // RooTreeData::statOn arguments - RooCmdArg What(const char* str) { return RooCmdArg("What",0,0,0,0,str,0,0,0) ; } - - // RooProdPdf::ctor arguments - RooCmdArg Conditional(const RooArgSet& pdfSet, const RooArgSet& depSet, bool depsAreCond) { return RooCmdArg("Conditional",depsAreCond,0,0,0,0,0,0,0,0,0,&pdfSet,&depSet) ; } ; - - // RooAbsPdf::generate arguments - RooCmdArg ProtoData(const RooDataSet& protoData, bool randomizeOrder, bool resample) - { return RooCmdArg("PrototypeData",randomizeOrder,resample,0,0,0,0,&protoData,0) ; } - RooCmdArg NumEvents(Int_t numEvents) { return RooCmdArg("NumEvents",numEvents,0,0,0,0,0,0,0) ; } - RooCmdArg NumEvents(double numEvents) { return RooCmdArg("NumEventsD",0,0,numEvents,0,0,0,0,0) ; } - RooCmdArg ExpectedData(bool flag) { return RooCmdArg("ExpectedData",flag,0,0,0,0,0,0,0) ; } - RooCmdArg Asimov(bool flag) { return ExpectedData(flag) ; } - RooCmdArg AutoBinned(bool flag) { return RooCmdArg("AutoBinned",flag,0,0,0,0,0,0,0) ; } - RooCmdArg GenBinned(const char* tag) { return RooCmdArg("GenBinned",0,0,0,0,tag,0,0,0) ; } - RooCmdArg AllBinned() { return RooCmdArg("GenBinned",0,0,0,0,"*",0,0,0) ; } - - - // RooAbsRealLValue::createHistogram arguments - RooCmdArg YVar(const RooAbsRealLValue& var, const RooCmdArg& arg) { return RooCmdArg("YVar",0,0,0,0,0,0,&var,0,&arg) ; } - RooCmdArg ZVar(const RooAbsRealLValue& var, const RooCmdArg& arg) { return RooCmdArg("ZVar",0,0,0,0,0,0,&var,0,&arg) ; } - RooCmdArg AxisLabel(const char* name) { return RooCmdArg("AxisLabel",0,0,0,0,name,0,0,0) ; } - RooCmdArg Scaling(bool flag) { return RooCmdArg("Scaling",flag,0,0,0,0,0,0,0) ; } - - // RooAbsReal::createHistogram arguments - RooCmdArg IntrinsicBinning(bool flag) { return RooCmdArg("IntrinsicBinning",flag,0,0,0,0,0,0,0) ; } - - // RooAbsData::createHistogram arguments - RooCmdArg AutoSymBinning(Int_t nbins, double marginFactor) { return RooCmdArg("AutoRangeData",1,nbins,marginFactor,0,0,0,0,0) ; } - RooCmdArg AutoBinning(Int_t nbins, double marginFactor) { return RooCmdArg("AutoRangeData",0,nbins,marginFactor,0,0,0,0,0) ; } - - // RooAbsReal::fillHistogram arguments - RooCmdArg IntegratedObservables(const RooArgSet& intObs) { return RooCmdArg("IntObs",0,0,0,0,0,0,0,0,0,0,&intObs,0) ; } ; - - // RooAbsReal::createIntegral arguments - RooCmdArg NumIntConfig(const RooNumIntConfig& cfg) { return RooCmdArg("NumIntConfig",0,0,0,0,0,0,&cfg,0) ; } - - // RooMCStudy::ctor arguments - RooCmdArg Silence(bool flag) { return RooCmdArg("Silence",flag,0,0,0,0,0,0,0) ; } - RooCmdArg FitModel(RooAbsPdf& pdf) { return RooCmdArg("FitModel",0,0,0,0,0,0,&pdf,0) ; } - RooCmdArg FitOptions(const RooCmdArg& arg1 ,const RooCmdArg& arg2, const RooCmdArg& arg3, - const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6) { - RooCmdArg ret("FitOptArgs",0,0,0,0,0,0,0,0) ; ret.addArg(arg1) ; ret.addArg(arg2) ; - ret.addArg(arg3) ; ret.addArg(arg4) ; ret.addArg(arg5) ; ret.addArg(arg6) ; - ret.setProcessRecArgs(false) ; return ret ; - } - RooCmdArg Binned(bool flag) { return RooCmdArg("Binned",flag,0,0,0,0,0,0,0) ; } - RooCmdArg BootStrapData(const RooDataSet& dset) { return RooCmdArg("BootStrapData",0,0,0,0,0,0,&dset,0) ; } - - - // RooMCStudy::plot* arguments - RooCmdArg Frame(const RooCmdArg& arg1,const RooCmdArg& arg2, - const RooCmdArg& arg3,const RooCmdArg& arg4, - const RooCmdArg& arg5,const RooCmdArg& arg6) { - RooCmdArg ret("FrameArgs",0,0,0,0,0,0,0,0) ; ret.addArg(arg1) ; ret.addArg(arg2) ; - ret.addArg(arg3) ; ret.addArg(arg4) ; ret.addArg(arg5) ; ret.addArg(arg6) ; - ret.setProcessRecArgs(false) ; return ret ; - } - RooCmdArg FrameBins(Int_t nbins) { return RooCmdArg("Bins",nbins,0,0,0,0,0,0,0) ; } - RooCmdArg FrameRange(double xlo, double xhi) { return RooCmdArg("Range",0,0,xlo,xhi,0,0,0,0) ; } - RooCmdArg FitGauss(bool flag) { return RooCmdArg("FitGauss",flag,0,0,0,0,0,0,0) ; } - - // RooRealVar::format arguments - RooCmdArg ShowName(bool flag) { return RooCmdArg("ShowName",flag,0,0,0,0,0,0,0) ; } - RooCmdArg ShowValue(bool flag) { return RooCmdArg("ShowValue",flag,0,0,0,0,0,0,0) ; } - RooCmdArg ShowError(bool flag) { return RooCmdArg("ShowError",flag,0,0,0,0,0,0,0) ; } - RooCmdArg ShowAsymError(bool flag) { return RooCmdArg("ShowAsymError",flag,0,0,0,0,0,0,0) ; } - RooCmdArg ShowUnit(bool flag) { return RooCmdArg("ShowUnit",flag,0,0,0,0,0,0,0) ; } - RooCmdArg AutoPrecision(Int_t ndigit) { return RooCmdArg("AutoPrecision",ndigit,0,0,0,0,0,0,0) ; } - RooCmdArg FixedPrecision(Int_t ndigit) { return RooCmdArg("FixedPrecision",ndigit,0,0,0,0,0,0,0) ; } - RooCmdArg TLatexStyle(bool flag) { return RooCmdArg("TLatexStyle",flag,0,0,0,0,0,0,0) ; } - RooCmdArg LatexStyle(bool flag) { return RooCmdArg("LatexStyle",flag,0,0,0,0,0,0,0) ; } - RooCmdArg LatexTableStyle(bool flag) { return RooCmdArg("LatexTableStyle",flag,0,0,0,0,0,0,0) ; } - RooCmdArg VerbatimName(bool flag) { return RooCmdArg("VerbatimName",flag,0,0,0,0,0,0,0) ; } - - // RooMsgService::addReportingStream arguments - RooCmdArg Topic(Int_t topic) { return RooCmdArg("Topic",topic,0,0,0,0,0,0,0) ; } - RooCmdArg ObjectName(const char* name) { return RooCmdArg("ObjectName",0,0,0,0,name,0,0,0) ; } - RooCmdArg ClassName(const char* name) { return RooCmdArg("ClassName",0,0,0,0,name,0,0,0) ; } - RooCmdArg BaseClassName(const char* name) { return RooCmdArg("BaseClassName",0,0,0,0,name,0,0,0) ; } - RooCmdArg TagName(const char* name) { return RooCmdArg("LabelName",0,0,0,0,name,0,0,0) ; } - RooCmdArg OutputStream(ostream& os) { return RooCmdArg("OutputStream",0,0,0,0,0,0,new RooHelpers::WrapIntoTObject(os),0) ; } - RooCmdArg Prefix(bool flag) { return RooCmdArg("Prefix",flag,0,0,0,0,0,0,0) ; } - RooCmdArg Color(Color_t color) { return RooCmdArg("Color",color,0,0,0,0,0,0,0) ; } - - - // RooWorkspace::import() arguments - RooCmdArg RenameConflictNodes(const char* suffix, bool ro) { return RooCmdArg("RenameConflictNodes",ro,0,0,0,suffix,0,0,0) ; } - RooCmdArg RecycleConflictNodes(bool flag) { return RooCmdArg("RecycleConflictNodes",flag,0,0,0,0,0,0,0) ; } - RooCmdArg RenameAllNodes(const char* suffix) { return RooCmdArg("RenameAllNodes",0,0,0,0,suffix,0,0,0) ; } - RooCmdArg RenameAllVariables(const char* suffix) { return RooCmdArg("RenameAllVariables",0,0,0,0,suffix,0,0,0) ; } - RooCmdArg RenameAllVariablesExcept(const char* suffix, const char* except) { return RooCmdArg("RenameAllVariables",0,0,0,0,suffix,except,0,0) ; } - RooCmdArg RenameVariable(const char* in, const char* out) { return RooCmdArg("RenameVar",0,0,0,0,in,out,0,0) ; } - RooCmdArg Rename(const char* suffix) { return RooCmdArg("Rename",0,0,0,0,suffix,0,0,0) ; } - RooCmdArg Embedded(bool flag) { return RooCmdArg("Embedded",flag,0,0,0,0,0,0,0) ; } - RooCmdArg NoRecursion(bool flag) { return RooCmdArg("NoRecursion",flag,0,0,0,0,0,0,0) ; } - - // RooSimCloneTool::build() arguments - RooCmdArg SplitParam(const char* varname, const char* catname) { return RooCmdArg("SplitParam",0,0,0,0,varname,catname,0,0) ; } - RooCmdArg SplitParam(const RooRealVar& var, const RooAbsCategory& cat) { return RooCmdArg("SplitParam",0,0,0,0,var.GetName(),cat.GetName(),0,0) ; } - RooCmdArg SplitParamConstrained(const char* varname, const char* catname, const char* rsname) { return RooCmdArg("SplitParamConstrained",0,0,0,0,varname,catname,0,0,0,rsname) ; } - RooCmdArg SplitParamConstrained(const RooRealVar& var, const RooAbsCategory& cat, const char* rsname) { return RooCmdArg("SplitParamConstrained",0,0,0,0,var.GetName(),cat.GetName(),0,0,0,rsname) ; } - RooCmdArg Restrict(const char* catName, const char* stateNameList) { return RooCmdArg("Restrict",0,0,0,0,catName,stateNameList,0,0) ; } - - // RooAbsPdf::createCdf() arguments - RooCmdArg SupNormSet(const RooArgSet& nset) { - RooCmdArg out{"SupNormSet",0}; - out.setSet(0, nset); - return out; - } - RooCmdArg ScanParameters(Int_t nbins,Int_t intOrder) { return RooCmdArg("ScanParameters",nbins,intOrder,0,0,0,0,0,0) ; } - RooCmdArg ScanNumCdf() { return RooCmdArg("ScanNumCdf",1,0,0,0,0,0,0,0) ; } - RooCmdArg ScanAllCdf() { return RooCmdArg("ScanAllCdf",1,0,0,0,0,0,0,0) ; } - RooCmdArg ScanNoCdf() { return RooCmdArg("ScanNoCdf",1,0,0,0,0,0,0,0) ; } - - - RooCmdArg MultiArg(const RooCmdArg& arg1,const RooCmdArg& arg2,const RooCmdArg& arg3,const RooCmdArg& arg4, - const RooCmdArg& arg5,const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) { - RooCmdArg ret("MultiArg",0,0,0,0,0,0,0,0) ; ret.addArg(arg1) ; ret.addArg(arg2) ; - ret.addArg(arg3) ; ret.addArg(arg4) ; ret.addArg(arg5) ; ret.addArg(arg6) ; ret.addArg(arg7) ; ret.addArg(arg8) ; - ret.setProcessRecArgs(true,false) ; return ret ; - } - - RooConstVar& RooConst(double val) { return RooRealConstant::value(val) ; } + } + return RooCmdArg("Constrain", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, ¶ms); +} +RooCmdArg GlobalObservablesSource(const char *sourceName) +{ + return {"GlobalObservablesSource", 0, 0, 0, 0, sourceName, nullptr, nullptr, nullptr}; +} +RooCmdArg GlobalObservablesTag(const char *tagName) +{ + return RooCmdArg("GlobalObservablesTag", 0, 0, 0, 0, tagName, nullptr, nullptr, nullptr); +} +RooCmdArg ExternalConstraints(const RooArgSet &cpdfs) +{ + return RooCmdArg("ExternalConstraints", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &cpdfs); +} +RooCmdArg PrintEvalErrors(Int_t numErrors) +{ + return RooCmdArg("PrintEvalErrors", numErrors, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg EvalErrorWall(bool flag) +{ + return RooCmdArg("EvalErrorWall", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg SumW2Error(bool flag) +{ + return RooCmdArg("SumW2Error", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg AsymptoticError(bool flag) +{ + return RooCmdArg("AsymptoticError", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg CloneData(bool flag) +{ + oocoutI(nullptr, InputArguments) << "The deprecated RooFit::CloneData(" << flag + << ") option passed to createNLL() is ignored." << std::endl; + return RooCmdArg("CloneData", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Integrate(bool flag) +{ + return RooCmdArg("Integrate", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Minimizer(const char *type, const char *alg) +{ + return RooCmdArg("Minimizer", 0, 0, 0, 0, type, alg, nullptr, nullptr); +} + +RooCmdArg Offset(std::string const &mode) +{ + std::string lower = mode; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); }); + OffsetMode modeVal = OffsetMode::None; + if (lower == "none") + modeVal = OffsetMode::None; + else if (lower == "initial") + modeVal = OffsetMode::Initial; + else if (lower == "bin") + modeVal = OffsetMode::Bin; + return RooCmdArg("OffsetLikelihood", static_cast(modeVal)); +} + +/// When parameters are chosen such that a PDF is undefined, try to indicate to the minimiser how to leave this region. +/// \param strength Strength of hints for minimiser. Set to zero to switch off. +RooCmdArg RecoverFromUndefinedRegions(double strength) +{ + return RooCmdArg("RecoverFromUndefinedRegions", 0, 0, strength, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsPdf::paramOn arguments +RooCmdArg Label(const char *str) +{ + return RooCmdArg("Label", 0, 0, 0, 0, str, nullptr, nullptr, nullptr); +} +RooCmdArg Layout(double xmin, double xmax, double ymin) +{ + return RooCmdArg("Layout", Int_t(ymin * 10000), 0, xmin, xmax, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Parameters(const RooArgSet ¶ms) +{ + RooCmdArg out{"Parameters", 0}; + out.setSet(0, params); + return out; +} +RooCmdArg ShowConstants(bool flag) +{ + return RooCmdArg("ShowConstants", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooTreeData::statOn arguments +RooCmdArg What(const char *str) +{ + return RooCmdArg("What", 0, 0, 0, 0, str, nullptr, nullptr, nullptr); +} + +// RooProdPdf::ctor arguments +RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond) +{ + return RooCmdArg("Conditional", depsAreCond, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &pdfSet, + &depSet); +}; + +// RooAbsPdf::generate arguments +RooCmdArg ProtoData(const RooDataSet &protoData, bool randomizeOrder, bool resample) +{ + return RooCmdArg("PrototypeData", randomizeOrder, resample, 0, 0, nullptr, nullptr, &protoData, nullptr); +} +RooCmdArg NumEvents(Int_t numEvents) +{ + return RooCmdArg("NumEvents", numEvents, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg NumEvents(double numEvents) +{ + return RooCmdArg("NumEventsD", 0, 0, numEvents, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ExpectedData(bool flag) +{ + return RooCmdArg("ExpectedData", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Asimov(bool flag) +{ + return ExpectedData(flag); +} +RooCmdArg AutoBinned(bool flag) +{ + return RooCmdArg("AutoBinned", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg GenBinned(const char *tag) +{ + return RooCmdArg("GenBinned", 0, 0, 0, 0, tag, nullptr, nullptr, nullptr); +} +RooCmdArg AllBinned() +{ + return RooCmdArg("GenBinned", 0, 0, 0, 0, "*", nullptr, nullptr, nullptr); +} + +// RooAbsRealLValue::createHistogram arguments +RooCmdArg YVar(const RooAbsRealLValue &var, const RooCmdArg &arg) +{ + return RooCmdArg("YVar", 0, 0, 0, 0, nullptr, nullptr, &var, nullptr, &arg); +} +RooCmdArg ZVar(const RooAbsRealLValue &var, const RooCmdArg &arg) +{ + return RooCmdArg("ZVar", 0, 0, 0, 0, nullptr, nullptr, &var, nullptr, &arg); +} +RooCmdArg AxisLabel(const char *name) +{ + return RooCmdArg("AxisLabel", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg Scaling(bool flag) +{ + return RooCmdArg("Scaling", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsReal::createHistogram arguments +RooCmdArg IntrinsicBinning(bool flag) +{ + return RooCmdArg("IntrinsicBinning", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsData::createHistogram arguments +RooCmdArg AutoSymBinning(Int_t nbins, double marginFactor) +{ + return RooCmdArg("AutoRangeData", 1, nbins, marginFactor, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg AutoBinning(Int_t nbins, double marginFactor) +{ + return RooCmdArg("AutoRangeData", 0, nbins, marginFactor, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooAbsReal::fillHistogram arguments +RooCmdArg IntegratedObservables(const RooArgSet &intObs) +{ + return RooCmdArg("IntObs", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &intObs, nullptr); +}; + +// RooAbsReal::createIntegral arguments +RooCmdArg NumIntConfig(const RooNumIntConfig &cfg) +{ + return RooCmdArg("NumIntConfig", 0, 0, 0, 0, nullptr, nullptr, &cfg, nullptr); +} + +// RooMCStudy::ctor arguments +RooCmdArg Silence(bool flag) +{ + return RooCmdArg("Silence", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg FitModel(RooAbsPdf &pdf) +{ + return RooCmdArg("FitModel", 0, 0, 0, 0, nullptr, nullptr, &pdf, nullptr); +} +RooCmdArg FitOptions(const RooCmdArg &arg1, const RooCmdArg &arg2, const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6) +{ + RooCmdArg ret("FitOptArgs", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); + ret.addArg(arg1); + ret.addArg(arg2); + ret.addArg(arg3); + ret.addArg(arg4); + ret.addArg(arg5); + ret.addArg(arg6); + ret.setProcessRecArgs(false); + return ret; +} +RooCmdArg Binned(bool flag) +{ + return RooCmdArg("Binned", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg BootStrapData(const RooDataSet &dset) +{ + return RooCmdArg("BootStrapData", 0, 0, 0, 0, nullptr, nullptr, &dset, nullptr); +} + +// RooMCStudy::plot* arguments +RooCmdArg Frame(const RooCmdArg &arg1, const RooCmdArg &arg2, const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6) +{ + RooCmdArg ret("FrameArgs", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); + ret.addArg(arg1); + ret.addArg(arg2); + ret.addArg(arg3); + ret.addArg(arg4); + ret.addArg(arg5); + ret.addArg(arg6); + ret.setProcessRecArgs(false); + return ret; +} +RooCmdArg FrameBins(Int_t nbins) +{ + return RooCmdArg("Bins", nbins, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg FrameRange(double xlo, double xhi) +{ + return RooCmdArg("Range", 0, 0, xlo, xhi, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg FitGauss(bool flag) +{ + return RooCmdArg("FitGauss", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooRealVar::format arguments +RooCmdArg ShowName(bool flag) +{ + return RooCmdArg("ShowName", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ShowValue(bool flag) +{ + return RooCmdArg("ShowValue", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ShowError(bool flag) +{ + return RooCmdArg("ShowError", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ShowAsymError(bool flag) +{ + return RooCmdArg("ShowAsymError", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ShowUnit(bool flag) +{ + return RooCmdArg("ShowUnit", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg AutoPrecision(Int_t ndigit) +{ + return RooCmdArg("AutoPrecision", ndigit, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg FixedPrecision(Int_t ndigit) +{ + return RooCmdArg("FixedPrecision", ndigit, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg TLatexStyle(bool flag) +{ + return RooCmdArg("TLatexStyle", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg LatexStyle(bool flag) +{ + return RooCmdArg("LatexStyle", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg LatexTableStyle(bool flag) +{ + return RooCmdArg("LatexTableStyle", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg VerbatimName(bool flag) +{ + return RooCmdArg("VerbatimName", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooMsgService::addReportingStream arguments +RooCmdArg Topic(Int_t topic) +{ + return RooCmdArg("Topic", topic, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ObjectName(const char *name) +{ + return RooCmdArg("ObjectName", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg ClassName(const char *name) +{ + return RooCmdArg("ClassName", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg BaseClassName(const char *name) +{ + return RooCmdArg("BaseClassName", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg TagName(const char *name) +{ + return RooCmdArg("LabelName", 0, 0, 0, 0, name, nullptr, nullptr, nullptr); +} +RooCmdArg OutputStream(ostream &os) +{ + return RooCmdArg("OutputStream", 0, 0, 0, 0, nullptr, nullptr, new RooHelpers::WrapIntoTObject(os), + nullptr); +} +RooCmdArg Prefix(bool flag) +{ + return RooCmdArg("Prefix", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg Color(Color_t color) +{ + return RooCmdArg("Color", color, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooWorkspace::import() arguments +RooCmdArg RenameConflictNodes(const char *suffix, bool ro) +{ + return RooCmdArg("RenameConflictNodes", ro, 0, 0, 0, suffix, nullptr, nullptr, nullptr); +} +RooCmdArg RecycleConflictNodes(bool flag) +{ + return RooCmdArg("RecycleConflictNodes", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg RenameAllNodes(const char *suffix) +{ + return RooCmdArg("RenameAllNodes", 0, 0, 0, 0, suffix, nullptr, nullptr, nullptr); +} +RooCmdArg RenameAllVariables(const char *suffix) +{ + return RooCmdArg("RenameAllVariables", 0, 0, 0, 0, suffix, nullptr, nullptr, nullptr); +} +RooCmdArg RenameAllVariablesExcept(const char *suffix, const char *except) +{ + return RooCmdArg("RenameAllVariables", 0, 0, 0, 0, suffix, except, nullptr, nullptr); +} +RooCmdArg RenameVariable(const char *in, const char *out) +{ + return RooCmdArg("RenameVar", 0, 0, 0, 0, in, out, nullptr, nullptr); +} +RooCmdArg Rename(const char *suffix) +{ + return RooCmdArg("Rename", 0, 0, 0, 0, suffix, nullptr, nullptr, nullptr); +} +RooCmdArg Embedded(bool flag) +{ + return RooCmdArg("Embedded", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg NoRecursion(bool flag) +{ + return RooCmdArg("NoRecursion", flag, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +// RooSimCloneTool::build() arguments +RooCmdArg SplitParam(const char *varname, const char *catname) +{ + return RooCmdArg("SplitParam", 0, 0, 0, 0, varname, catname, nullptr, nullptr); +} +RooCmdArg SplitParam(const RooRealVar &var, const RooAbsCategory &cat) +{ + return RooCmdArg("SplitParam", 0, 0, 0, 0, var.GetName(), cat.GetName(), nullptr, nullptr); +} +RooCmdArg SplitParamConstrained(const char *varname, const char *catname, const char *rsname) +{ + return RooCmdArg("SplitParamConstrained", 0, 0, 0, 0, varname, catname, nullptr, nullptr, nullptr, rsname); +} +RooCmdArg SplitParamConstrained(const RooRealVar &var, const RooAbsCategory &cat, const char *rsname) +{ + return RooCmdArg("SplitParamConstrained", 0, 0, 0, 0, var.GetName(), cat.GetName(), nullptr, nullptr, nullptr, + rsname); +} +RooCmdArg Restrict(const char *catName, const char *stateNameList) +{ + return RooCmdArg("Restrict", 0, 0, 0, 0, catName, stateNameList, nullptr, nullptr); +} + +// RooAbsPdf::createCdf() arguments +RooCmdArg SupNormSet(const RooArgSet &nset) +{ + RooCmdArg out{"SupNormSet", 0}; + out.setSet(0, nset); + return out; +} +RooCmdArg ScanParameters(Int_t nbins, Int_t intOrder) +{ + return RooCmdArg("ScanParameters", nbins, intOrder, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ScanNumCdf() +{ + return RooCmdArg("ScanNumCdf", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ScanAllCdf() +{ + return RooCmdArg("ScanAllCdf", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} +RooCmdArg ScanNoCdf() +{ + return RooCmdArg("ScanNoCdf", 1, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); +} + +RooCmdArg MultiArg(const RooCmdArg &arg1, const RooCmdArg &arg2, const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6, const RooCmdArg &arg7, const RooCmdArg &arg8) +{ + RooCmdArg ret("MultiArg", 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); + ret.addArg(arg1); + ret.addArg(arg2); + ret.addArg(arg3); + ret.addArg(arg4); + ret.addArg(arg5); + ret.addArg(arg6); + ret.addArg(arg7); + ret.addArg(arg8); + ret.setProcessRecArgs(true, false); + return ret; +} +RooConstVar &RooConst(double val) +{ + return RooRealConstant::value(val); +} } // End namespace RooFit namespace RooFitShortHand { -RooConstVar& C(double value) { return RooFit::RooConst(value) ; } +RooConstVar &C(double value) +{ + return RooFit::RooConst(value); +} } // namespace RooFitShortHand diff --git a/roofit/roofitcore/src/RooGrid.cxx b/roofit/roofitcore/src/RooGrid.cxx index 9b3aaceb69a66..41353318f2975 100644 --- a/roofit/roofitcore/src/RooGrid.cxx +++ b/roofit/roofitcore/src/RooGrid.cxx @@ -30,15 +30,11 @@ integration, following the VEGAS algorithm. #include "RooRandom.h" #include "TMath.h" #include "RooMsgService.h" -#include "TClass.h" -#include +#include #include "Riostream.h" #include -using namespace std; - -ClassImp(RooGrid); //////////////////////////////////////////////////////////////////////////////// @@ -49,7 +45,7 @@ RooGrid::RooGrid(const RooAbsFunc &function) { // check that the input function is valid if(!(_valid= function.isValid())) { - oocoutE(nullptr,InputArguments) << ClassName() << ": cannot initialize using an invalid function" << endl; + oocoutE(nullptr,InputArguments) << "RooGrid: cannot initialize using an invalid function" << std::endl; return; } @@ -80,18 +76,18 @@ bool RooGrid::initialize(const RooAbsFunc &function) for(UInt_t index= 0; index < _dim; index++) { _xl[index]= function.getMinLimit(index); if(RooNumber::isInfinite(_xl[index])) { - oocoutE(nullptr,Integration) << ClassName() << ": lower limit of dimension " << index << " is infinite" << endl; + oocoutE(nullptr,Integration) << "RooGrid: lower limit of dimension " << index << " is infinite" << std::endl; return false; } _xu[index]= function.getMaxLimit(index); if(RooNumber::isInfinite(_xl[index])) { - oocoutE(nullptr,Integration) << ClassName() << ": upper limit of dimension " << index << " is infinite" << endl; + oocoutE(nullptr,Integration) << "RooGrid: upper limit of dimension " << index << " is infinite" << std::endl; return false; } double dx= _xu[index] - _xl[index]; if(dx <= 0) { - oocoutE(nullptr,Integration) << ClassName() << ": bad range for dimension " << index << ": [" << _xl[index] - << "," << _xu[index] << "]" << endl; + oocoutE(nullptr,Integration) << "RooGrid: bad range for dimension " << index << ": [" << _xl[index] + << "," << _xu[index] << "]" << std::endl; return false; } _delx[index]= dx; @@ -157,7 +153,7 @@ void RooGrid::resetValues() //////////////////////////////////////////////////////////////////////////////// -/// Generate a random vector in the specified box and and store its +/// Generate a random vector in the specified box and store its /// coordinates in the x[] array provided, the corresponding bin /// indices in the bin[] array, and the volume of this bin in vol. /// The box is specified by the array box[] of box integer indices @@ -186,7 +182,7 @@ void RooGrid::generatePoint(const UInt_t box[], double x[], UInt_t bin[], double // store the bin in which this point lies along the j-th // coordinate axis and calculate its width and position y // in normalized bin coordinates. - Int_t k= (Int_t)z; + Int_t k= static_cast(z); bin[j] = k; double y, bin_width; if(k == 0) { @@ -242,51 +238,23 @@ bool RooGrid::nextBox(UInt_t box[]) const //////////////////////////////////////////////////////////////////////////////// /// Print info about this object to the specified stream. -void RooGrid::printMultiline(ostream& os, Int_t /*contents*/, bool verbose, TString indent) const +void RooGrid::print(std::ostream& os, bool verbose, std::string const& indent) const { - os << ClassName() << ": volume = " << getVolume() << endl; + os << "RooGrid: volume = " << getVolume() << std::endl; os << indent << " Has " << getDimension() << " dimension(s) each subdivided into " - << getNBins() << " bin(s) and sampled with " << _boxes << " box(es)" << endl; - for(UInt_t index= 0; index < getDimension(); index++) { + << getNBins() << " bin(s) and sampled with " << _boxes << " box(es)" << std::endl; + for(std::size_t index= 0; index < getDimension(); index++) { os << indent << " (" << index << ") [" - << setw(10) << _xl[index] << "," << setw(10) << _xu[index] << "]" << endl; + << std::setw(10) << _xl[index] << "," << std::setw(10) << _xu[index] << "]" << std::endl; if(!verbose) continue; - for(UInt_t bin= 0; bin < _bins; bin++) { + for(std::size_t bin= 0; bin < _bins; bin++) { os << indent << " bin-" << bin << " : x = " << coord(bin,index) << " , y = " - << value(bin,index) << endl; + << value(bin,index) << std::endl; } } } -//////////////////////////////////////////////////////////////////////////////// -/// Print name of grid object - -void RooGrid::printName(ostream& os) const -{ - os << GetName() ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Print title of grid object - -void RooGrid::printTitle(ostream& os) const -{ - os << GetTitle() ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Print class name of grid object - -void RooGrid::printClassName(ostream& os) const -{ - os << ClassName() ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Add the specified amount to bin[j] of the 1D histograms associated /// with each axis j. @@ -345,9 +313,8 @@ void RooGrid::refine(double alpha) double xnew = 0; double dw = 0; - UInt_t k; i = 1; - for (k = 0; k < _bins; k++) { + for (UInt_t k = 0; k < _bins; k++) { dw += _weight[k]; xold = xnew; xnew = coord(k+1,j); @@ -358,7 +325,7 @@ void RooGrid::refine(double alpha) } } - for (k = 1 ; k < _bins ; k++) { + for (UInt_t k = 1 ; k < _bins ; k++) { coord( k, j) = newCoord(k); } diff --git a/roofit/roofitcore/src/RooHelpers.cxx b/roofit/roofitcore/src/RooHelpers.cxx index b3e0bc670c993..f5181f6f20e5c 100644 --- a/roofit/roofitcore/src/RooHelpers.cxx +++ b/roofit/roofitcore/src/RooHelpers.cxx @@ -30,6 +30,8 @@ #include #include +#include + namespace RooHelpers { LocalChangeMsgLevel::LocalChangeMsgLevel(RooFit::MsgLevel lvl, @@ -165,7 +167,7 @@ namespace { /// Get the lower and upper bound of parameter range if arg can be casted to RooAbsRealLValue. /// If no range with rangeName is defined for the argument, this will check if a binning of the /// same name exists and return the interval covered by the binning. -/// Returns `{-infinity, infinity}` if agument can't be casted to RooAbsRealLValue* or if no +/// Returns `{-infinity, infinity}` if argument can't be casted to RooAbsRealLValue* or if no /// range or binning with the requested name exists. /// \param[in] arg RooAbsArg for which to get the range. /// \param[in] rangeName The name of the range. @@ -184,32 +186,9 @@ std::pair getRangeOrBinningInterval(RooAbsArg const* arg, const /// Check if there is any overlap when a list of ranges is applied to a set of observables. /// \param[in] observables The observables to check for overlap -/// \param[in] data RooAbsCollection with the observables to check for overlap. /// \param[in] rangeNames The names of the ranges. -bool checkIfRangesOverlap(RooArgSet const& observables, - RooAbsData const& data, - std::vector const& rangeNames) +bool checkIfRangesOverlap(RooArgSet const& observables, std::vector const& rangeNames) { - auto getLimits = [&](RooAbsRealLValue const& rlv, const char* rangeName) { - - // RooDataHistCase - if(dynamic_cast(&data)) { - if (auto binning = rlv.getBinningPtr(rangeName)) { - return getBinningInterval(*binning); - } else { - // default binning if range is not defined - return getBinningInterval(*rlv.getBinningPtr(nullptr)); - } - } - - // RooDataSet and other cases - if (rlv.hasRange(rangeName)) { - return std::pair{rlv.getMin(rangeName), rlv.getMax(rangeName)}; - } - // default range if range with given name is not defined - return std::pair{rlv.getMin(), rlv.getMax()}; - }; - // cache the range limits in a flat vector std::vector> limits; limits.reserve(rangeNames.size() * observables.size()); @@ -219,7 +198,7 @@ bool checkIfRangesOverlap(RooArgSet const& observables, if(dynamic_cast(obs)) { // Nothing to be done for category observables } else if(auto * rlv = dynamic_cast(obs)) { - limits.push_back(getLimits(*rlv, range.c_str())); + limits.emplace_back(rlv->getMin(range.c_str()), rlv->getMax(range.c_str())); } else { throw std::logic_error("Classes that represent observables are expected to inherit from RooAbsRealLValue or RooAbsCategory!"); } @@ -251,9 +230,9 @@ bool checkIfRangesOverlap(RooArgSet const& observables, } -/// Create a string with all sorted names of RooArgSet elements separated by colons. +/// Create a string with all sorted names of RooArgSet elements separated by delimiters. /// \param[in] argSet The input RooArgSet. -std::string getColonSeparatedNameString(RooArgSet const& argSet) { +std::string getColonSeparatedNameString(RooArgSet const& argSet, char delim) { RooArgList tmp(argSet); tmp.sort(); @@ -261,7 +240,7 @@ std::string getColonSeparatedNameString(RooArgSet const& argSet) { std::string content; for(auto const& arg : tmp) { content += arg->GetName(); - content += ":"; + content += delim; } if(!content.empty()) { content.pop_back(); @@ -298,24 +277,132 @@ std::string getRangeNameForSimComponent(std::string const& rangeName, bool split return rangeName; } -BinnedLOutput getBinnedL(RooAbsPdf &pdf) +BinnedLOutput getBinnedL(RooAbsPdf const &pdf) { if (pdf.getAttribute("BinnedLikelihood") && pdf.IsA()->InheritsFrom(RooRealSumPdf::Class())) { // Simplest case: top-level of component is a RooRealSumPdf - return {&pdf, true}; + return {const_cast(&pdf), true}; } else if (pdf.IsA()->InheritsFrom(RooProdPdf::Class())) { // Default case: top-level pdf is a product of RooRealSumPdf and other pdfs - for (RooAbsArg *component : static_cast(pdf).pdfList()) { + for (RooAbsArg *component : static_cast(pdf).pdfList()) { if (component->getAttribute("BinnedLikelihood") && component->IsA()->InheritsFrom(RooRealSumPdf::Class())) { return {static_cast(component), true}; } if (component->getAttribute("MAIN_MEASUREMENT")) { - // not really a binned pdf, but this prevents a (potentially) long list of subsidiary measurements to be passed to the slave calculator - return {static_cast(component), false}; + // not really a binned pdf, but this prevents a (potentially) long list of subsidiary measurements to be + // passed to the slave calculator + return {static_cast(component), false}; } } } return {nullptr, false}; } +/// Get the topologically-sorted list of all nodes in the computation graph. +void getSortedComputationGraph(RooAbsArg const &func, RooArgSet &out) +{ + // Get the set of nodes in the computation graph. Do the detour via + // RooArgList to avoid deduplication done after adding each element. + RooArgList serverList; + func.treeNodeServerList(&serverList, nullptr, true, true, false, true); + // If we fill the servers in reverse order, they are approximately in + // topological order so we save a bit of work in sortTopologically(). + out.add(serverList.rbegin(), serverList.rend(), /*silent=*/true); + // Sort nodes topologically: the servers of any node will be before that + // node in the collection. + out.sortTopologically(); +} + +namespace Detail { + +namespace { + +using ToCloneList = std::vector; +using ToCloneMap = std::unordered_map; + +// Add clones of servers of given argument to end of list +void addServerClonesToList(const RooAbsArg &var, ToCloneList &outlist, ToCloneMap &outmap, bool deepCopy, + RooArgSet const *observables) +{ + if (outmap.find(var.namePtr()) != outmap.end()) { + return; + } + + if (observables && var.isFundamental() && !observables->find(var)) { + return; + } + + outmap[var.namePtr()] = &var; + outlist.push_back(&var); + + if (deepCopy) { + for (const auto server : var.servers()) { + addServerClonesToList(*server, outlist, outmap, deepCopy, observables); + } + } +} + +} // namespace + +/// Implementation of RooAbsCollection::snapshot() with some extra parameters. +/// to be used in other RooHelpers functions. +/// param[in] input The input collection. +/// param[in] output The output collection. +/// param[in] deepCopy If the whole computation graph should be cloned recursively. +/// param[in] observables If this is not a nullptr, only the fundamental +/// variables that are in observables are deep cloned. +bool snapshotImpl(RooAbsCollection const &input, RooAbsCollection &output, bool deepCopy, RooArgSet const *observables) +{ + // Figure out what needs to be cloned + ToCloneList toCloneList; + ToCloneMap toCloneMap; + for (RooAbsArg *orig : input) { + addServerClonesToList(*orig, toCloneList, toCloneMap, deepCopy, observables); + } + + // Actually do the cloning + output.reserve(toCloneList.size()); + for (RooAbsArg const *arg : toCloneList) { + std::unique_ptr serverClone{static_cast(arg->Clone())}; + serverClone->setAttribute("SnapShot_ExtRefClone"); + output.addOwned(std::move(serverClone)); + } + + // Redirect all server connections to internal list members + for (RooAbsArg *var : output) { + var->redirectServers(output, deepCopy && !observables); + } + + return false; +} + +RooAbsArg *cloneTreeWithSameParametersImpl(RooAbsArg const &arg, RooArgSet const *observables) +{ + // Clone tree using snapshot + RooArgSet clonedNodes; + snapshotImpl(RooArgSet(arg), clonedNodes, true, observables); + + // Find the head node in the cloneSet + RooAbsArg *head = clonedNodes.find(arg); + assert(head); + + // We better to release the ownership before removing the "head". Otherwise, + // "head" might also be deleted as the clonedNodes collection owns it. + // (Actually this does not happen because even an owning collection doesn't + // delete the element when removed by pointer lookup, but it's better not to + // rely on this unexpected fact). + clonedNodes.releaseOwnership(); + + // Remove the head node from the cloneSet + // To release it from the set ownership + clonedNodes.remove(*head); + + // Add the set as owned component of the head + head->addOwnedComponents(std::move(clonedNodes)); + + return head; +} + +} // namespace Detail + } diff --git a/roofit/roofitcore/src/RooHist.cxx b/roofit/roofitcore/src/RooHist.cxx index ee490c3f0e98d..4cb9867d3b308 100644 --- a/roofit/roofitcore/src/RooHist.cxx +++ b/roofit/roofitcore/src/RooHist.cxx @@ -30,8 +30,9 @@ a RooPlot. #include "RooAbsRealLValue.h" #include "RooHistError.h" #include "RooCurve.h" -#include "RooScaledFunc.h" #include "RooMsgService.h" +#include "RooProduct.h" +#include "RooConstVar.h" #include "TH1.h" #include "Riostream.h" @@ -259,7 +260,7 @@ RooHist::RooHist(const RooHist& hist1, const RooHist& hist2, double wgt1, double /// More details. /// \param[in] f The function to be plotted. /// \param[in] x The variable on the x-axis -/// \param[in] xErrorFrac Size of the errror in x as a fraction of the bin width +/// \param[in] xErrorFrac Size of the error in x as a fraction of the bin width /// \param[in] scaleFactor arbitrary scaling of the y-values /// \param[in] normVars variables over which to normalize /// \param[in] fr fit result @@ -286,17 +287,8 @@ RooHist::RooHist(const RooAbsReal &f, RooAbsRealLValue &x, double xErrorFrac, do } setYAxisLabel(title.c_str()); - std::unique_ptr rawPtr; - std::unique_ptr funcPtr{f.bindVars(x,normVars,true)}; - - // apply a scale factor if necessary - if(scaleFactor != 1) { - rawPtr= std::move(funcPtr); - funcPtr = std::make_unique(*rawPtr,scaleFactor); - } - - // apply a scale factor if necessary - assert(funcPtr); + RooProduct scaledFunc{"scaled_func", "scaled_func", {f, RooFit::RooConst(scaleFactor)}}; + std::unique_ptr funcPtr{scaledFunc.bindVars(x, normVars, true)}; // calculate the points to add to our curve int xbins = x.numBins(); diff --git a/roofit/roofitcore/src/RooHistError.cxx b/roofit/roofitcore/src/RooHistError.cxx index 29020c24e9345..cb89c4602b897 100644 --- a/roofit/roofitcore/src/RooHistError.cxx +++ b/roofit/roofitcore/src/RooHistError.cxx @@ -30,14 +30,10 @@ a specified area of a Poisson or Binomail error distribution. #include "TMath.h" #include "Riostream.h" -#include +#include using namespace std; -ClassImp(RooHistError); - ; - - //////////////////////////////////////////////////////////////////////////////// /// Return a reference to a singleton object that is created the @@ -105,7 +101,7 @@ bool RooHistError::getPoissonIntervalCalc(Int_t n, double &mu1, double &mu2, dou return false; } - // use assymptotic error if possible + // use asymptotic error if possible if(n > 100) { mu1= n - sqrt(n+0.25) + 0.5; mu2= n + sqrt(n+0.25) + 0.5; @@ -120,7 +116,7 @@ bool RooHistError::getPoissonIntervalCalc(Int_t n, double &mu1, double &mu2, dou } // Backup solution for negative numbers - return getInterval(&upper,0,(double)n,1.0,mu1,mu2,nSigma); + return getInterval(&upper,nullptr,(double)n,1.0,mu1,mu2,nSigma); } @@ -173,7 +169,7 @@ bool RooHistError::getBinomialIntervalAsym(Int_t n, Int_t m, status= getInterval(&upper,&lower,(double)(n-m)/(n+m),0.1,asym1,asym2,nSigma); } else { - status= getInterval(&upper,0,(double)(n-m)/(n+m),0.1,asym1,asym2,nSigma); + status= getInterval(&upper,nullptr,(double)(n-m)/(n+m),0.1,asym1,asym2,nSigma); } // undo the swap here @@ -237,7 +233,7 @@ bool RooHistError::getBinomialIntervalEff(Int_t n, Int_t m, status= getInterval(&upper,&lower,eff,0.1,asym1,asym2,nSigma*0.5); } else { - status= getInterval(&upper,0,eff,0.1,asym1,asym2,nSigma*0.5); + status= getInterval(&upper,nullptr,eff,0.1,asym1,asym2,nSigma*0.5); } // undo the swap here @@ -262,7 +258,7 @@ bool RooHistError::getInterval(const RooAbsFunc *Qu, const RooAbsFunc *Ql, doubl double stepSize, double &lo, double &hi, double nSigma) const { // sanity checks - assert(0 != Qu || 0 != Ql); + assert(nullptr != Qu || nullptr != Ql); // convert number of sigma into a confidence level double beta= TMath::Erf(nSigma/sqrt(2.)); @@ -271,10 +267,10 @@ bool RooHistError::getInterval(const RooAbsFunc *Qu, const RooAbsFunc *Ql, doubl // Does the central interval contain the point estimate? bool ok(true); double loProb(1),hiProb(0); - if(0 != Ql) loProb= (*Ql)(&pointEstimate); - if(0 != Qu) hiProb= (*Qu)(&pointEstimate); + if(nullptr != Ql) loProb= (*Ql)(&pointEstimate); + if(nullptr != Qu) hiProb= (*Qu)(&pointEstimate); - if (Qu && (0 == Ql || loProb > alpha + beta)) { + if (Qu && (nullptr == Ql || loProb > alpha + beta)) { // Force the low edge to be at the pointEstimate lo= pointEstimate; double target= loProb - beta; @@ -282,7 +278,7 @@ bool RooHistError::getInterval(const RooAbsFunc *Qu, const RooAbsFunc *Ql, doubl RooBrentRootFinder uFinder(*Qu); ok= uFinder.findRoot(hi,hi-stepSize,hi,target); } - else if(Ql && (0 == Qu || hiProb < alpha)) { + else if(Ql && (nullptr == Qu || hiProb < alpha)) { // Force the high edge to be at pointEstimate hi= pointEstimate; double target= hiProb + beta; diff --git a/roofit/roofitcore/src/RooHistFunc.cxx b/roofit/roofitcore/src/RooHistFunc.cxx index c86bfd45f9cc8..09c89e54848f6 100644 --- a/roofit/roofitcore/src/RooHistFunc.cxx +++ b/roofit/roofitcore/src/RooHistFunc.cxx @@ -183,7 +183,7 @@ double RooHistFunc::evaluate() const if (harg != parg) { parg->syncCache() ; harg->copyCache(parg,true) ; - if (!harg->inRange(0)) { + if (!harg->inRange(nullptr)) { return 0 ; } } @@ -194,15 +194,19 @@ double RooHistFunc::evaluate() const return ret ; } +void RooHistFunc::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + RooHistPdf::rooHistTranslateImpl(this, ctx, _intOrder, _dataHist, _depList, false); +} -void RooHistFunc::computeBatch(cudaStream_t*, double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const { +void RooHistFunc::computeBatch(double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const { if (_depList.size() == 1) { auto xVals = dataMap.at(_depList[0]); _dataHist->weights(output, xVals, _intOrder, false, _cdfBoundaries); return; } - std::vector> inputValues; + std::vector> inputValues; for (const auto& obs : _depList) { auto realObs = dynamic_cast(obs); if (realObs) { @@ -238,13 +242,8 @@ void RooHistFunc::computeBatch(cudaStream_t*, double* output, size_t size, RooFi Int_t RooHistFunc::getMaxVal(const RooArgSet& vars) const { - RooAbsCollection* common = _depList.selectCommon(vars) ; - if (common->size()==_depList.size()) { - delete common ; - return 1; - } - delete common ; - return 0 ; + std::unique_ptr common{_depList.selectCommon(vars)}; + return common->size() == _depList.size() ? 1 : 0; } //////////////////////////////////////////////////////////////////////////////// @@ -263,6 +262,13 @@ double RooHistFunc::maxVal(Int_t code) const return max*1.05 ; } +RooDataHist* RooHistFunc::cloneAndOwnDataHist(const char* newname) { + if (_ownedDataHist) return _ownedDataHist.get(); + _ownedDataHist.reset(static_cast(_dataHist->Clone(newname))); + _dataHist = _ownedDataHist.get(); + return _dataHist; +} + //////////////////////////////////////////////////////////////////////////////// /// Return the total volume spanned by the observables of the RooDataHist @@ -312,6 +318,16 @@ double RooHistFunc::analyticalIntegral(Int_t code, const char* rangeName) const return RooHistPdf::analyticalIntegral(code, rangeName, _histObsList, _depList, *_dataHist, true); } +bool RooHistFunc::forceAnalyticalInt(const RooAbsArg& dep) const +{ + return RooHistPdf::forceAnalyticalInt(_depList, dep); +} + +std::string RooHistFunc::buildCallToAnalyticIntegral(int code, const char * /* rangeName */, + RooFit::Detail::CodeSquashContext & /* ctx */) const +{ + return RooHistPdf::rooHistIntegralTranslateImpl(code, this, _dataHist, _depList, true); +} //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function @@ -333,11 +349,11 @@ std::list* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, double xlo, { // No hints are required when interpolation is used if (_intOrder>1) { - return 0 ; + return nullptr ; } // Find histogram observable corresponding to pdf observable - RooAbsArg* hobs(0) ; + RooAbsArg* hobs(nullptr) ; for (auto i = 0u; i < _histObsList.size(); ++i) { const auto harg = _histObsList[i]; const auto parg = _depList[i]; @@ -366,7 +382,7 @@ std::list* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, double xlo, // Not found, or check that matching pdf observable is an l-value dependent on histogram observable fails if (!hobs || !(pobs->dependsOn(obs) && dynamic_cast(pobs))) { std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") obs = " << obs.GetName() << " hobs is not found, returning null" << std::endl ; - return 0 ; + return nullptr ; } // Now we are in business - we are in a situation where the pdf observable LV(x), mapping to a histogram observable x @@ -383,16 +399,16 @@ std::list* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, double xlo, if (!xtmp) { std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") hobs = " << hobs->GetName() << " is not found in dataset?" << std::endl ; _dataHist->get()->Print("v") ; - return 0 ; + return nullptr ; } RooAbsLValue* lvarg = dynamic_cast(_dataHist->get()->find(hobs->GetName())) ; if (!lvarg) { std::cout << "RooHistFunc::binBoundaries(" << GetName() << ") hobs = " << hobs->GetName() << " but is not an LV, returning null" << std::endl ; - return 0 ; + return nullptr ; } // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; auto hint = new std::list ; @@ -450,7 +466,7 @@ bool RooHistFunc::importWorkspaceHook(RooWorkspace& ws) coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ; return true ; } - _dataHist = (RooDataHist*) ws.embeddedData(uniqueName.c_str()) ; + _dataHist = (RooDataHist*) ws.embeddedData(uniqueName) ; } } else { @@ -462,7 +478,7 @@ bool RooHistFunc::importWorkspaceHook(RooWorkspace& ws) coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ; return true ; } - _dataHist = static_cast(ws.embeddedData(uniqueName.c_str())); + _dataHist = static_cast(ws.embeddedData(uniqueName)); } return false ; @@ -481,12 +497,12 @@ bool RooHistFunc::importWorkspaceHook(RooWorkspace& ws) bool RooHistFunc::areIdentical(const RooDataHist& dh1, const RooDataHist& dh2) { - if (fabs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ; + if (std::abs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ; if (dh1.numEntries() != dh2.numEntries()) return false ; for (int i=0 ; i < dh1.numEntries() ; i++) { dh1.get(i) ; dh2.get(i) ; - if (fabs(dh1.weight()-dh2.weight())>1e-8) return false ; + if (std::abs(dh1.weight()-dh2.weight())>1e-8) return false ; } using RooHelpers::getColonSeparatedNameString; if (getColonSeparatedNameString(*dh1.get()) != getColonSeparatedNameString(*dh2.get())) return false ; @@ -553,18 +569,18 @@ Int_t RooHistFunc::getBin() const { /// Compute bin numbers corresponding to all coordinates in `evalData`. /// \return Vector of bin numbers. If a bin is not in the current range of the observables, return -1. std::vector RooHistFunc::getBins(RooFit::Detail::DataMap const& dataMap) const { - std::vector> depData; + std::vector> depData; for (const auto dep : _depList) { auto real = dynamic_cast(dep); if (real) { depData.push_back(dataMap.at(real)); } else { - depData.emplace_back(nullptr, 0); + depData.emplace_back(); } } const auto batchSize = std::max_element(depData.begin(), depData.end(), - [](const RooSpan& a, const RooSpan& b){ return a.size() < b.size(); })->size(); + [](const std::span& a, const std::span& b){ return a.size() < b.size(); })->size(); std::vector results; for (std::size_t evt = 0; evt < batchSize; ++evt) { diff --git a/roofit/roofitcore/src/RooHistPdf.cxx b/roofit/roofitcore/src/RooHistPdf.cxx index d913e4d610b82..aa85b7bea2bd9 100644 --- a/roofit/roofitcore/src/RooHistPdf.cxx +++ b/roofit/roofitcore/src/RooHistPdf.cxx @@ -19,7 +19,7 @@ \class RooHistPdf \ingroup Roofitcore -RooHistPdf implements a probablity density function sampled from a +RooHistPdf implements a propability density function sampled from a multidimensional histogram. The histogram distribution is explicitly normalized by RooHistPdf and can have an arbitrary number of real or discrete dimensions. @@ -28,6 +28,7 @@ discrete dimensions. #include "Riostream.h" #include "RooHistPdf.h" +#include "RooCurve.h" #include "RooDataHist.h" #include "RooMsgService.h" #include "RooRealVar.h" @@ -35,6 +36,7 @@ discrete dimensions. #include "RooWorkspace.h" #include "RooGlobalFunc.h" #include "RooHelpers.h" +#include "RooUniformBinning.h" #include "TError.h" #include "TBuffer.h" @@ -187,12 +189,18 @@ RooHistPdf::~RooHistPdf() } +RooDataHist* RooHistPdf::cloneAndOwnDataHist(const char* newname) { + if (_ownedDataHist) return _ownedDataHist.get(); + _ownedDataHist.reset(static_cast(_dataHist->Clone(newname))); + _dataHist = _ownedDataHist.get(); + return _dataHist; +} -void RooHistPdf::computeBatch(cudaStream_t*, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { +void RooHistPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { // For interpolation and histograms of higher dimension, use base function if(_pdfObsList.size() > 1) { - RooAbsReal::computeBatch(nullptr, output, nEvents, dataMap); + RooAbsReal::computeBatch(output, nEvents, dataMap); return; } @@ -216,7 +224,7 @@ double RooHistPdf::evaluate() const if (harg != parg) { parg->syncCache() ; harg->copyCache(parg,true) ; - if (!harg->inRange(0)) { + if (!harg->inRange(nullptr)) { return 0 ; } } @@ -227,6 +235,25 @@ double RooHistPdf::evaluate() const return std::max(ret, 0.0); } +void RooHistPdf::rooHistTranslateImpl(RooAbsArg const *klass, RooFit::Detail::CodeSquashContext &ctx, int intOrder, + RooDataHist const *dataHist, const RooArgSet &obs, bool correctForBinSize) +{ + if (intOrder != 0) { + ooccoutE(klass, InputArguments) << "RooHistPdf::weight(" << klass->GetName() + << ") ERROR: Code Squashing currently only supports non-interpolation cases." + << std::endl; + return; + } + + std::string const &idxName = dataHist->calculateTreeIndexForCodeSquash(klass, ctx, obs); + std::string const &weightName = dataHist->declWeightArrayForCodeSquash(klass, ctx, correctForBinSize); + ctx.addResult(klass, weightName + "[" + idxName + "]"); +} + +void RooHistPdf::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + rooHistTranslateImpl(this, ctx, _intOrder, _dataHist, _pdfObsList, !_unitNorm); +} //////////////////////////////////////////////////////////////////////////////// /// Return the total volume spanned by the observables of the RooHistPdf @@ -255,6 +282,7 @@ double RooHistPdf::totVolume() const } namespace { + bool fullRange(const RooAbsArg& x, const RooAbsArg& y ,const char* range) { const RooAbsRealLValue *_x = dynamic_cast(&x); @@ -270,15 +298,34 @@ bool fullRange(const RooAbsArg& x, const RooAbsArg& y ,const char* range) } return (_x->getMin(range) == _y->getMin() && _x->getMax(range) == _y->getMax()); } + +bool okayForAnalytical(RooAbsArg const& obs, RooArgSet const& allVars) +{ + auto lobs = dynamic_cast(&obs); + if(lobs == nullptr) return false; + + bool isOkayForAnalyticalInt = false; + + for(RooAbsArg *var : allVars) { + if(obs.dependsOn(*var)) { + if(!lobs->isJacobianOK(*var)) return false; + isOkayForAnalyticalInt = true; + } + } + + return isOkayForAnalyticalInt; } +} // namespace + Int_t RooHistPdf::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName, RooArgSet const& histObsList, - RooSetProxy const& pdfObsList, - Int_t intOrder) { + RooArgSet const& pdfObsList, + Int_t intOrder) +{ // First make list of pdf observables to histogram observables // and select only those for which the integral is over the full range @@ -288,7 +335,7 @@ Int_t RooHistPdf::getAnalyticalIntegral(RooArgSet& allVars, const auto pa = pdfObsList[n]; const auto ha = histObsList[n]; - if (allVars.find(*pa)) { + if (okayForAnalytical(*pa, allVars)) { code |= 2 << n; analVars.add(*pa); if (fullRange(*pa, *ha, rangeName)) { @@ -317,7 +364,7 @@ Int_t RooHistPdf::getAnalyticalIntegral(RooArgSet& allVars, double RooHistPdf::analyticalIntegral(Int_t code, const char* rangeName, RooArgSet const& histObsList, - RooSetProxy const& pdfObsList, + RooArgSet const& pdfObsList, RooDataHist& dataHist, bool histFuncMode) { // Simplest scenario, full-range integration over all dependents @@ -353,6 +400,24 @@ double RooHistPdf::analyticalIntegral(Int_t code, return ret ; } +std::string RooHistPdf::rooHistIntegralTranslateImpl(int code, RooAbsArg const *klass, RooDataHist const *dataHist, + const RooArgSet &obs, bool histFuncMode) +{ + if (((2 << obs.size()) - 1) != code) { + oocoutE(klass, InputArguments) + << "RooHistPdf::integral(" << klass->GetName() + << ") ERROR: AD currently only supports integrating over all histogram observables." << std::endl; + return ""; + } + return std::to_string(dataHist->sum(histFuncMode)); +} + +std::string RooHistPdf::buildCallToAnalyticIntegral(int code, const char * /*rangeName */, + RooFit::Detail::CodeSquashContext & /* ctx */) const +{ + return rooHistIntegralTranslateImpl(code, this, _dataHist, _pdfObsList, false); +} + //////////////////////////////////////////////////////////////////////////////// /// Determine integration scenario. If no interpolation is used, /// RooHistPdf can perform all integrals over its dependents @@ -377,6 +442,30 @@ double RooHistPdf::analyticalIntegral(Int_t code, const char* rangeName) const } +bool RooHistPdf::forceAnalyticalInt(RooArgSet const& pdfObsList, const RooAbsArg& dep) +{ + bool isOkayForAnalyticalInt = false; + + for (RooAbsArg * obs : pdfObsList) { + if(obs->dependsOn(dep)) { + // If the observable doesn't depend linearly on the integration + // variable we will not do analytical integration. + auto lvalue = dynamic_cast(obs); + if(!(lvalue && lvalue->isJacobianOK(dep))) return false; + isOkayForAnalyticalInt = true; + } + } + + return isOkayForAnalyticalInt; +} + + +bool RooHistPdf::forceAnalyticalInt(const RooAbsArg& dep) const +{ + return forceAnalyticalInt(_pdfObsList, dep); +} + + //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function /// as the recursive division strategy of RooCurve cannot deal efficiently @@ -423,26 +512,11 @@ std::list* RooHistPdf::plotSamplingHint(RooDataHist const& dataHist, // Retrieve position of all bin boundaries const RooAbsBinning* binning = lval->getBinningPtr(nullptr); - std::span boundaries{binning->array(), static_cast(binning->numBoundaries())}; - - auto hint = new std::list ; - - const double delta = (xhi-xlo)*1e-8 ; - - // Sample points right next to the plot limits - hint->push_back(xlo + delta); - hint->push_back(xhi - delta); + std::span boundaries{binning->array(), static_cast(binning->numBoundaries())}; - // Sample points very close to the left and right of the bin boundaries that - // are strictly in between the plot limits. - for (const double x : boundaries) { - if (x - xlo > delta && xhi - x > delta) { - hint->push_back(x - delta); - hint->push_back(x + delta); - } - } - - return hint ; + // Use the helper function from RooCurve to make sure to get sampling hints + // that work with the RooFitPlotting. + return RooCurve::plotSamplingHintForBinBoundaries(boundaries, xlo, xhi); } @@ -461,11 +535,11 @@ std::list* RooHistPdf::binBoundaries(RooAbsRealLValue& obs, double xlo, // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast(_dataHist->get()->find(obs.GetName())) ; if (!lvarg) { - return 0 ; + return nullptr ; } // Retrieve position of all bin boundaries - const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; + const RooAbsBinning* binning = lvarg->getBinningPtr(nullptr); double* boundaries = binning->array() ; auto hint = new std::list ; @@ -520,12 +594,12 @@ double RooHistPdf::maxVal(Int_t code) const bool RooHistPdf::areIdentical(const RooDataHist& dh1, const RooDataHist& dh2) { - if (fabs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ; + if (std::abs(dh1.sumEntries()-dh2.sumEntries())>1e-8) return false ; if (dh1.numEntries() != dh2.numEntries()) return false ; for (int i=0 ; i < dh1.numEntries() ; i++) { dh1.get(i) ; dh2.get(i) ; - if (fabs(dh1.weight()-dh2.weight())>1e-8) return false ; + if (std::abs(dh1.weight()-dh2.weight())>1e-8) return false ; } return true ; } @@ -564,7 +638,7 @@ bool RooHistPdf::importWorkspaceHook(RooWorkspace& ws) coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ; return true ; } - _dataHist = (RooDataHist*) ws.embeddedData(uniqueName.c_str()) ; + _dataHist = (RooDataHist*) ws.embeddedData(uniqueName) ; } } else { @@ -576,7 +650,7 @@ bool RooHistPdf::importWorkspaceHook(RooWorkspace& ws) coutE(ObjectHandling) << " RooHistPdf::importWorkspaceHook(" << GetName() << ") unable to import clone of underlying RooDataHist with unique name " << uniqueName << ", abort" << std::endl ; return true ; } - _dataHist = static_cast(ws.embeddedData(uniqueName.c_str())); + _dataHist = static_cast(ws.embeddedData(uniqueName)); } return false ; @@ -605,4 +679,3 @@ void RooHistPdf::Streamer(TBuffer &R__b) R__b.WriteClassBuffer(RooHistPdf::Class(),this); } } - diff --git a/roofit/roofitcore/src/RooImproperIntegrator1D.cxx b/roofit/roofitcore/src/RooImproperIntegrator1D.cxx index cc63659de005c..e91d9bc78de51 100644 --- a/roofit/roofitcore/src/RooImproperIntegrator1D.cxx +++ b/roofit/roofitcore/src/RooImproperIntegrator1D.cxx @@ -25,7 +25,7 @@ and the outer two pieces, if required are calculated using a 1/x transform **/ #include "RooImproperIntegrator1D.h" -#include "RooIntegrator1D.h" +#include "RooRombergIntegrator.h" #include "RooInvTransform.h" #include "RooNumber.h" #include "RooNumIntFactory.h" @@ -33,7 +33,7 @@ and the outer two pieces, if required are calculated using a 1/x transform #include "RooMsgService.h" #include "Riostream.h" -#include +#include #include "TClass.h" @@ -44,20 +44,18 @@ ClassImp(RooImproperIntegrator1D); //////////////////////////////////////////////////////////////////////////////// /// Register RooImproperIntegrator1D, its parameters and capabilities with RooNumIntFactory -void RooImproperIntegrator1D::registerIntegrator(RooNumIntFactory& fact) -{ - RooImproperIntegrator1D* proto = new RooImproperIntegrator1D() ; - fact.storeProtoIntegrator(proto,RooArgSet(),RooIntegrator1D::Class()->GetName()) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooImproperIntegrator1D::RooImproperIntegrator1D() : - _case(ClosedBothEnds), _xmin(-10), _xmax(10), _useIntegrandLimits(true) +void RooImproperIntegrator1D::registerIntegrator(RooNumIntFactory &fact) { + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config); + }; + + fact.registerPlugin("RooImproperIntegrator1D", creator, {}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/false, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/true, + /*depName=*/"RooIntegrator1D"); } @@ -106,16 +104,6 @@ RooImproperIntegrator1D::RooImproperIntegrator1D(const RooAbsFunc& function, dou -//////////////////////////////////////////////////////////////////////////////// -/// Return clone of integrator with given function and configuration. Needed by RooNumIntFactory. - -RooAbsIntegrator* RooImproperIntegrator1D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooImproperIntegrator1D(function,config) ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Initialize the integrator, construct and initialize subintegrators @@ -139,10 +127,10 @@ void RooImproperIntegrator1D::initialize(const RooAbsFunc* function) // associated to this integrator, but with a different summation rule. auto makeIntegrator1D = [&](RooAbsFunc const& func, double xmin, double xmax, - RooIntegrator1D::SummationRule rule) { + RooRombergIntegrator::SummationRule rule) { RooNumIntConfig newConfig{_config}; // copy default configuration newConfig.getConfigSection("RooIntegrator1D").setCatIndex("sumRule", rule); - return std::make_unique(func, xmin, xmax, newConfig); + return std::make_unique(func, xmin, xmax, newConfig); }; // partition the integration range into subranges that can each be @@ -150,33 +138,33 @@ void RooImproperIntegrator1D::initialize(const RooAbsFunc* function) switch(_case= limitsCase()) { case ClosedBothEnds: // both limits are finite: use the plain trapezoid integrator - _integrator1 = std::make_unique(*function,_xmin,_xmax,_config); + _integrator1 = std::make_unique(*function,_xmin,_xmax,_config); break; case OpenBothEnds: // both limits are infinite: integrate over (-1,+1) using // the plain trapezoid integrator... - _integrator1 = makeIntegrator1D(*function,-1,+1,RooIntegrator1D::Trapezoid); + _integrator1 = makeIntegrator1D(*function,-1,+1,RooRombergIntegrator::Trapezoid); // ...and integrate the infinite tails using the midpoint integrator - _integrator2 = makeIntegrator1D(*_function,-1,0,RooIntegrator1D::Midpoint); - _integrator3 = makeIntegrator1D(*_function,0,+1,RooIntegrator1D::Midpoint); + _integrator2 = makeIntegrator1D(*_function,-1,0,RooRombergIntegrator::Midpoint); + _integrator3 = makeIntegrator1D(*_function,0,+1,RooRombergIntegrator::Midpoint); break; case OpenBelowSpansZero: // xmax >= 0 so integrate from (-inf,-1) and (-1,xmax) - _integrator1 = makeIntegrator1D(*_function,-1,0,RooIntegrator1D::Midpoint); - _integrator2 = makeIntegrator1D(*function,-1,_xmax,RooIntegrator1D::Trapezoid); + _integrator1 = makeIntegrator1D(*_function,-1,0,RooRombergIntegrator::Midpoint); + _integrator2 = makeIntegrator1D(*function,-1,_xmax,RooRombergIntegrator::Trapezoid); break; case OpenBelow: // xmax < 0 so integrate from (-inf,xmax) - _integrator1 = makeIntegrator1D(*_function,1/_xmax,0,RooIntegrator1D::Midpoint); + _integrator1 = makeIntegrator1D(*_function,1/_xmax,0,RooRombergIntegrator::Midpoint); break; case OpenAboveSpansZero: // xmin <= 0 so integrate from (xmin,+1) and (+1,+inf) - _integrator1 = makeIntegrator1D(*_function,0,+1,RooIntegrator1D::Midpoint); - _integrator2 = makeIntegrator1D(*function,_xmin,+1,RooIntegrator1D::Trapezoid); + _integrator1 = makeIntegrator1D(*_function,0,+1,RooRombergIntegrator::Midpoint); + _integrator2 = makeIntegrator1D(*function,_xmin,+1,RooRombergIntegrator::Trapezoid); break; case OpenAbove: // xmin > 0 so integrate from (xmin,+inf) - _integrator1 = makeIntegrator1D(*_function,0,1/_xmin,RooIntegrator1D::Midpoint); + _integrator1 = makeIntegrator1D(*_function,0,1/_xmin,RooRombergIntegrator::Midpoint); break; case Invalid: default: @@ -193,7 +181,7 @@ void RooImproperIntegrator1D::initialize(const RooAbsFunc* function) bool RooImproperIntegrator1D::setLimits(double *xmin, double *xmax) { if(_useIntegrandLimits) { - oocoutE(nullptr,Integration) << "RooIntegrator1D::setLimits: cannot override integrand's limits" << std::endl; + oocoutE(nullptr,Integration) << "RooImproperIntegrator1D::setLimits: cannot override integrand's limits" << std::endl; return false; } @@ -258,7 +246,7 @@ bool RooImproperIntegrator1D::checkLimits() const RooImproperIntegrator1D::LimitsCase RooImproperIntegrator1D::limitsCase() const { // Analyze the specified limits to determine which case applies. - if(0 == integrand() || !integrand()->isValid()) return Invalid; + if(nullptr == integrand() || !integrand()->isValid()) return Invalid; if (_useIntegrandLimits) { _xmin= integrand()->getMinLimit(0); diff --git a/roofit/roofitcore/src/RooInt.cxx b/roofit/roofitcore/src/RooInt.cxx deleted file mode 100644 index 1697c88f3cffa..0000000000000 --- a/roofit/roofitcore/src/RooInt.cxx +++ /dev/null @@ -1,46 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooInt.cxx -\class RooInt -\ingroup Roofitcore - -RooInt is a minimal implementation of a TObject holding a Int_t -value. -**/ - -#include "RooInt.h" - -using namespace std; - -ClassImp(RooInt); -; - - - -//////////////////////////////////////////////////////////////////////////////// -/// Facilitate sorting of RooInts in ROOT container classes -/// Return -1 or +1 if 'other' is a RooInt with value -/// greater or lesser than self. Return zero if other -/// object is not a RooInt - -Int_t RooInt::Compare(const TObject* other) const -{ - const RooInt* otherD = dynamic_cast(other) ; - if (!otherD) return 0 ; - return (_value>otherD->_value) ? 1 : -1 ; -} diff --git a/roofit/roofitcore/src/RooIntegrator1D.cxx b/roofit/roofitcore/src/RooIntegrator1D.cxx deleted file mode 100644 index cbcac74d753c6..0000000000000 --- a/roofit/roofitcore/src/RooIntegrator1D.cxx +++ /dev/null @@ -1,422 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooIntegrator1D.cxx -\class RooIntegrator1D -\ingroup Roofitcore - -RooIntegrator1D implements an adaptive one-dimensional -numerical integration algorithm. -**/ - - -#include "Riostream.h" - -#include "TClass.h" -#include "RooIntegrator1D.h" -#include "RooArgSet.h" -#include "RooRealVar.h" -#include "RooNumber.h" -#include "RooIntegratorBinding.h" -#include "RooNumIntConfig.h" -#include "RooNumIntFactory.h" -#include "RooMsgService.h" - -#include - - - -using namespace std; - -ClassImp(RooIntegrator1D); -; - -// Register this class with RooNumIntConfig - -//////////////////////////////////////////////////////////////////////////////// -/// Register RooIntegrator1D, is parameters and capabilities with RooNumIntFactory - -void RooIntegrator1D::registerIntegrator(RooNumIntFactory& fact) -{ - RooCategory sumRule("sumRule","Summation Rule") ; - sumRule.defineType("Trapezoid",RooIntegrator1D::Trapezoid) ; - sumRule.defineType("Midpoint",RooIntegrator1D::Midpoint) ; - sumRule.setLabel("Trapezoid") ; - RooCategory extrap("extrapolation","Extrapolation procedure") ; - extrap.defineType("None",0) ; - extrap.defineType("Wynn-Epsilon",1) ; - extrap.setLabel("Wynn-Epsilon") ; - RooRealVar maxSteps("maxSteps","Maximum number of steps",20) ; - RooRealVar minSteps("minSteps","Minimum number of steps",999) ; - RooRealVar fixSteps("fixSteps","Fixed number of steps",0) ; - - RooIntegrator1D* proto = new RooIntegrator1D() ; - fact.storeProtoIntegrator(proto,RooArgSet(sumRule,extrap,maxSteps,minSteps,fixSteps)) ; - RooNumIntConfig::defaultConfig().method1D().setLabel(proto->ClassName()) ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct integrator on given function binding, using specified summation -/// rule, maximum number of steps and conversion tolerance. The integration -/// limits are taken from the function binding - -RooIntegrator1D::RooIntegrator1D(const RooAbsFunc& function, SummationRule rule, - Int_t maxSteps, double eps) : - RooAbsIntegrator(function), _rule(rule), _maxSteps(maxSteps), _minStepsZero(999), _fixSteps(0), _epsAbs(eps), _epsRel(eps), _doExtrap(true) -{ - _useIntegrandLimits= true; - _valid= initialize(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct integrator on given function binding for given range, -/// using specified summation rule, maximum number of steps and -/// conversion tolerance. The integration limits are taken from the -/// function binding - -RooIntegrator1D::RooIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, - SummationRule rule, Int_t maxSteps, double eps) : - RooAbsIntegrator(function), - _rule(rule), - _maxSteps(maxSteps), - _minStepsZero(999), - _fixSteps(0), - _epsAbs(eps), - _epsRel(eps), - _doExtrap(true) -{ - _useIntegrandLimits= false; - _xmin= xmin; - _xmax= xmax; - _valid= initialize(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct integrator on given function binding, using specified -/// configuration object. The integration limits are taken from the -/// function binding - -RooIntegrator1D::RooIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) : - RooAbsIntegrator(function,config.printEvalCounter()), - _epsAbs(config.epsAbs()), - _epsRel(config.epsRel()) -{ - // Extract parameters from config object - const RooArgSet& configSet = config.getConfigSection(ClassName()) ; - _rule = (SummationRule) configSet.getCatIndex("sumRule",Trapezoid) ; - _maxSteps = (Int_t) configSet.getRealValue("maxSteps",20) ; - _minStepsZero = (Int_t) configSet.getRealValue("minSteps",999) ; - _fixSteps = (Int_t) configSet.getRealValue("fixSteps",0) ; - _doExtrap = (bool) configSet.getCatIndex("extrapolation",1) ; - - if (_fixSteps>_maxSteps) { - oocoutE(nullptr,Integration) << "RooIntegrator1D::ctor() ERROR: fixSteps>maxSteps, fixSteps set to maxSteps" << endl ; - _fixSteps = _maxSteps ; - } - - _useIntegrandLimits= true; - _valid= initialize(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Construct integrator on given function binding, using specified -/// configuration object and integration range - -RooIntegrator1D::RooIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, - const RooNumIntConfig& config) : - RooAbsIntegrator(function,config.printEvalCounter()), - _epsAbs(config.epsAbs()), - _epsRel(config.epsRel()) -{ - // Extract parameters from config object - const RooArgSet& configSet = config.getConfigSection(ClassName()) ; - _rule = (SummationRule) configSet.getCatIndex("sumRule",Trapezoid) ; - _maxSteps = (Int_t) configSet.getRealValue("maxSteps",20) ; - _minStepsZero = (Int_t) configSet.getRealValue("minSteps",999) ; - _fixSteps = (Int_t) configSet.getRealValue("fixSteps",0) ; - _doExtrap = (bool) configSet.getCatIndex("extrapolation",1) ; - - _useIntegrandLimits= false; - _xmin= xmin; - _xmax= xmax; - _valid= initialize(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Clone integrator with new function binding and configuration. Needed by RooNumIntFactory - -RooAbsIntegrator* RooIntegrator1D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooIntegrator1D(function,config) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Initialize the integrator - -bool RooIntegrator1D::initialize() -{ - // apply defaults if necessary - if(_maxSteps <= 0) { - _maxSteps= (_rule == Trapezoid) ? 20 : 14; - } - - if(_epsRel <= 0) _epsRel= 1e-6; - if(_epsAbs <= 0) _epsAbs= 1e-6; - - // check that the integrand is a valid function - if(!isValid()) { - oocoutE(nullptr,Integration) << "RooIntegrator1D::initialize: cannot integrate invalid function" << endl; - return false; - } - - // Allocate coordinate buffer size after number of function dimensions - _x.resize(_function->getDimension()); - - - // Allocate workspace for numerical integration engine - _h.resize(_maxSteps + 2); - _s.resize(_maxSteps + 2); - _c.resize(_nPoints + 1); - _d.resize(_nPoints + 1); - - return checkLimits(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Change our integration limits. Return true if the new limits are -/// ok, or otherwise false. Always returns false and does nothing -/// if this object was constructed to always use our integrand's limits. - -bool RooIntegrator1D::setLimits(double *xmin, double *xmax) -{ - if(_useIntegrandLimits) { - oocoutE(nullptr,Integration) << "RooIntegrator1D::setLimits: cannot override integrand's limits" << endl; - return false; - } - _xmin= *xmin; - _xmax= *xmax; - return checkLimits(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Check that our integration range is finite and otherwise return false. -/// Update the limits from the integrand if requested. - -bool RooIntegrator1D::checkLimits() const -{ - if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); - const_cast(_xmin) = integrand()->getMinLimit(0); - const_cast(_xmax) = integrand()->getMaxLimit(0); - } - const_cast(_range) = _xmax - _xmin; - if (_range < 0.) { - oocoutE(nullptr,Integration) << "RooIntegrator1D::checkLimits: bad range with min > max (_xmin = " << _xmin << " _xmax = " << _xmax << ")" << endl; - return false; - } - return (RooNumber::isInfinite(_xmin) || RooNumber::isInfinite(_xmax)) ? false : true; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Calculate numeric integral at given set of function binding parameters - -double RooIntegrator1D::integral(const double *yvec) -{ - assert(isValid()); - - if (_range == 0.) - return 0.; - - // Copy yvec to xvec if provided - if (yvec) { - for (UInt_t i = 0 ; i<_function->getDimension()-1 ; i++) { - _x[i+1] = yvec[i] ; - } - } - - - _h[1]=1.0; - double zeroThresh = _epsAbs/_range ; - for(Int_t j = 1; j <= _maxSteps; ++j) { - // refine our estimate using the appropriate summation rule - _s[j]= (_rule == Trapezoid) ? addTrapezoids(j) : addMidpoints(j); - - if (j >= _minStepsZero) { - bool allZero(true) ; - for (int jj=0 ; jj<=j ; jj++) { - if (_s[j]>=zeroThresh) { - allZero=false ; - } - } - if (allZero) { - //cout << "Roo1DIntegrator(" << this << "): zero convergence at step " << j << ", value = " << 0 << endl ; - return 0; - } - } - - if (_fixSteps>0) { - - // Fixed step mode, return result after fixed number of steps - if (j==_fixSteps) { - //cout << "returning result at fixed step " << j << endl ; - return _s[j]; - } - - } else if(j >= _nPoints) { - - // extrapolate the results of recent refinements and check for a stable result - if (_doExtrap) { - extrapolate(j); - } else { - _extrapValue = _s[j] ; - _extrapError = _s[j]-_s[j-1] ; - } - - if(fabs(_extrapError) <= _epsRel*fabs(_extrapValue)) { - return _extrapValue; - } - if(fabs(_extrapError) <= _epsAbs) { - return _extrapValue ; - } - - } - // update the step size for the next refinement of the summation - _h[j+1]= (_rule == Trapezoid) ? _h[j]/4. : _h[j]/9.; - } - - oocoutW(nullptr,Integration) << "RooIntegrator1D::integral: integral of " << _function->getName() << " over range (" << _xmin << "," << _xmax << ") did not converge after " - << _maxSteps << " steps" << endl; - for(Int_t j = 1; j <= _maxSteps; ++j) { - ooccoutW(nullptr,Integration) << " [" << j << "] h = " << _h[j] << " , s = " << _s[j] << endl; - } - - return _s[_maxSteps] ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Calculate the n-th stage of refinement of the Second Euler-Maclaurin -/// summation rule which has the useful property of not evaluating the -/// integrand at either of its endpoints but requires more function -/// evaluations than the trapezoidal rule. This rule can be used with -/// a suitable change of variables to estimate improper integrals. - -double RooIntegrator1D::addMidpoints(Int_t n) -{ - double x,tnm,sum,del,ddel; - Int_t it,j; - - if(n == 1) { - double xmid= 0.5*(_xmin + _xmax); - return (_savedResult= _range*integrand(xvec(xmid))); - } - else { - for(it=1, j=1; j < n-1; j++) it*= 3; - tnm= it; - del= _range/(3.*tnm); - ddel= del+del; - x= _xmin + 0.5*del; - for(sum= 0, j= 1; j <= it; j++) { - sum+= integrand(xvec(x)); - x+= ddel; - sum+= integrand(xvec(x)); - x+= del; - } - return (_savedResult= (_savedResult + _range*sum/tnm)/3.); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Calculate the n-th stage of refinement of the extended trapezoidal -/// summation rule. This is the most efficient rule for a well behaved -/// integrands that can be evaluated over its entire range, including the -/// endpoints. - -double RooIntegrator1D::addTrapezoids(Int_t n) -{ - if (n == 1) { - // use a single trapezoid to cover the full range - return (_savedResult= 0.5*_range*(integrand(xvec(_xmin)) + integrand(xvec(_xmax)))); - } - else { - // break the range down into several trapezoids using 2**(n-2) - // equally-spaced interior points - const int nInt = 1 << (n-2); - const double del = _range/nInt; - const double xmin = _xmin; - - double sum = 0.; - // TODO Replace by batch computation - for (int j=0; j - -using namespace std; - -ClassImp(RooIntegrator2D); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Register RooIntegrator2D, is parameters and capabilities with RooNumIntFactory - -void RooIntegrator2D::registerIntegrator(RooNumIntFactory& fact) -{ - RooIntegrator2D* proto = new RooIntegrator2D() ; - fact.storeProtoIntegrator(proto,RooArgSet(),RooIntegrator1D::Class()->GetName()) ; - RooNumIntConfig::defaultConfig().method2D().setLabel(proto->ClassName()) ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooIntegrator2D::RooIntegrator2D() : - _xIntegrator(0), _xint(0) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor with a given function binding, summation rule, -/// maximum number of steps and conversion tolerance. The integration -/// limits are taken from the definition in the function binding. - -RooIntegrator2D::RooIntegrator2D(const RooAbsFunc& function, RooIntegrator1D::SummationRule rule, - Int_t maxSteps, double eps) : - RooIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooIntegrator1D(function,rule,maxSteps,eps)))),rule,maxSteps,eps) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor with a given function binding, summation rule, -/// maximum number of steps, conversion tolerance and an explicit -/// choice of integration limits on both dimensions. - -RooIntegrator2D::RooIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, - double ymin, double ymax, - SummationRule rule, Int_t maxSteps, double eps) : - RooIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooIntegrator1D(function,ymin,ymax,rule,maxSteps,eps)))),xmin,xmax,rule,maxSteps,eps) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor with a function binding and a configuration object. -/// The integration limits are taken from the definition in the function -/// binding - -RooIntegrator2D::RooIntegrator2D(const RooAbsFunc& function, const RooNumIntConfig& config) : - RooIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooIntegrator1D(function,config)))),config) -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor with a function binding, a configuration object and -/// an explicit definition of the integration limits. - -RooIntegrator2D::RooIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, - double ymin, double ymax, - const RooNumIntConfig& config) : - RooIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooIntegrator1D(function,ymin,ymax,config)))),xmin,xmax,config) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Clone integrator with new function and configuration. Needed to support RooNumIntFactory - -RooAbsIntegrator* RooIntegrator2D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooIntegrator2D(function,config) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooIntegrator2D::~RooIntegrator2D() -{ - delete _xint ; - delete _xIntegrator ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Verify that the limits are OK for this integrator (i.e. no open-ended ranges) - -bool RooIntegrator2D::checkLimits() const -{ - bool ret = RooIntegrator1D::checkLimits() ; - ret &= _xIntegrator->checkLimits() ; - return ret ; -} diff --git a/roofit/roofitcore/src/RooIntegratorBinding.cxx b/roofit/roofitcore/src/RooIntegratorBinding.cxx deleted file mode 100644 index 2a8c1bbdabebd..0000000000000 --- a/roofit/roofitcore/src/RooIntegratorBinding.cxx +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooIntegratorBinding.cxx -\class RooIntegratorBinding -\ingroup Roofitcore - -Function binding representing the output of a RooAbsIntegrator -**/ - -#include "RooIntegratorBinding.h" - -using namespace std; - -ClassImp(RooIntegratorBinding); -; - diff --git a/roofit/roofitcore/src/RooInvTransform.cxx b/roofit/roofitcore/src/RooInvTransform.cxx index e1e91132da62a..f6996496cf51e 100644 --- a/roofit/roofitcore/src/RooInvTransform.cxx +++ b/roofit/roofitcore/src/RooInvTransform.cxx @@ -29,7 +29,7 @@ range cannot include zero. #include "RooInvTransform.h" #include "Riostream.h" -#include +#include using namespace std; diff --git a/roofit/roofitcore/src/RooLinearCombination.cxx b/roofit/roofitcore/src/RooLinearCombination.cxx index e6a758d846a20..faf22ed3671fc 100644 --- a/roofit/roofitcore/src/RooLinearCombination.cxx +++ b/roofit/roofitcore/src/RooLinearCombination.cxx @@ -37,14 +37,14 @@ namespace { RooLinearCombination::RooLinearCombination() : _actualVars("actualVars", "Variables used by formula expression", this), - _nset(0) { + _nset(nullptr) { // constructor } RooLinearCombination::RooLinearCombination(const char *name) : RooAbsReal(name, name), _actualVars("actualVars", "Variables used by formula expression", this), - _nset(0) { + _nset(nullptr) { // constructor } @@ -52,7 +52,7 @@ RooLinearCombination::RooLinearCombination(const RooLinearCombination &other, const char *name) : RooAbsReal(other, name), _actualVars("actualVars", this, other._actualVars), - _coefficients(other._coefficients), _nset(0) { + _coefficients(other._coefficients), _nset(nullptr) { // copy constructor } @@ -140,7 +140,7 @@ std::list *RooLinearCombination::binBoundaries(RooAbsRealLValue &obs, return binb; } } - return 0; + return nullptr; } std::list *RooLinearCombination::plotSamplingHint(RooAbsRealLValue &obs, @@ -154,5 +154,5 @@ std::list *RooLinearCombination::plotSamplingHint(RooAbsRealLValue &obs, return hint; } } - return 0; + return nullptr; } diff --git a/roofit/roofitcore/src/RooLinearVar.cxx b/roofit/roofitcore/src/RooLinearVar.cxx index 63fdb5b88b6d1..286b99b456dab 100644 --- a/roofit/roofitcore/src/RooLinearVar.cxx +++ b/roofit/roofitcore/src/RooLinearVar.cxx @@ -206,7 +206,7 @@ void RooLinearVar::writeToStream(std::ostream& os, bool compact) const RooAbsBinning& RooLinearVar::getBinning(const char* name, bool verbose, bool createOnTheFly) { // Normalization binning - if (name==0) { + if (name==nullptr) { _binning.updateInput(_var->getBinning(),_slope,_offset) ; return _binning ; } diff --git a/roofit/roofitcore/src/RooLinkedList.cxx b/roofit/roofitcore/src/RooLinkedList.cxx index d239dc5d48160..3ddda7384e8cd 100644 --- a/roofit/roofitcore/src/RooLinkedList.cxx +++ b/roofit/roofitcore/src/RooLinkedList.cxx @@ -46,7 +46,9 @@ Use RooAbsCollection derived objects for public use using namespace std; ClassImp(RooLinkedList); -; + +/// \cond ROOFIT_INTERNAL + namespace RooLinkedListImplDetails { /// a chunk of memory in a pool for quick allocation of RooLinkedListElems class Chunk { @@ -59,7 +61,7 @@ namespace RooLinkedListImplDetails { //cout << "RLLID::Chunk ctor(" << this << ") of size " << _free << " list elements" << endl ; // initialise free list for (Int_t i = 0; i < _free; ++i) - _chunk[i]._next = (i + 1 < _free) ? &_chunk[i + 1] : 0; + _chunk[i]._next = (i + 1 < _free) ? &_chunk[i + 1] : nullptr; } /// destructor ~Chunk() { delete[] _chunk; } @@ -84,11 +86,11 @@ namespace RooLinkedListImplDetails { /// pop a free element off the free list RooLinkedListElem* pop_free_elem() { - if (!_freelist) return 0; + if (!_freelist) return nullptr; RooLinkedListElem* retVal = _freelist; _freelist = retVal->_next; - retVal->_arg = 0; retVal->_refCount = 0; - retVal->_prev = retVal->_next = 0; + retVal->_arg = nullptr; retVal->_refCount = 0; + retVal->_prev = retVal->_next = nullptr; --_free; return retVal; } @@ -256,12 +258,14 @@ namespace RooLinkedListImplDetails { } } -RooLinkedList::Pool* RooLinkedList::_pool = 0; +/// \endcond + +RooLinkedList::Pool* RooLinkedList::_pool = nullptr; //////////////////////////////////////////////////////////////////////////////// RooLinkedList::RooLinkedList(Int_t htsize) : - _hashThresh(htsize), _size(0), _first(0), _last(0), _htableName(nullptr), _htableLink(nullptr), _useNptr(true) + _hashThresh(htsize), _size(0), _first(nullptr), _last(nullptr), _htableName(nullptr), _htableLink(nullptr), _useNptr(true) { if (!_pool) _pool = new Pool; _pool->acquire(); @@ -271,7 +275,7 @@ RooLinkedList::RooLinkedList(Int_t htsize) : /// Copy constructor RooLinkedList::RooLinkedList(const RooLinkedList& other) : - TObject(other), _hashThresh(other._hashThresh), _size(0), _first(0), _last(0), _htableName(nullptr), _htableLink(nullptr), + TObject(other), _hashThresh(other._hashThresh), _size(0), _first(nullptr), _last(nullptr), _htableName(nullptr), _htableLink(nullptr), _name(other._name), _useNptr(other._useNptr) { @@ -370,7 +374,7 @@ RooLinkedList::~RooLinkedList() Clear() ; if (_pool->release()) { delete _pool; - _pool = 0; + _pool = nullptr; } } @@ -392,7 +396,7 @@ RooLinkedListElem* RooLinkedList::findLink(const TObject* arg) const } ptr = ptr->_next ; } - return 0 ; + return nullptr ; } @@ -487,7 +491,7 @@ void RooLinkedList::RecursiveRemove(TObject *obj) TObject* RooLinkedList::At(Int_t index) const { // Check range - if (index<0 || index>=_size) return 0 ; + if (index<0 || index>=_size) return nullptr ; return _at[index]->_arg; // @@ -525,8 +529,8 @@ bool RooLinkedList::Replace(const TObject* oldArg, const TObject* newArg) } //////////////////////////////////////////////////////////////////////////////// -/// Return pointer to obejct with given name. If no such object -/// is found return a null pointer +/// Return pointer to object with given name. If no such object +/// is found return a null pointer. TObject* RooLinkedList::FindObject(const char* name) const { @@ -540,7 +544,7 @@ TObject* RooLinkedList::FindObject(const char* name) const TObject* RooLinkedList::FindObject(const TObject* obj) const { RooLinkedListElem *elem = findLink((TObject*)obj) ; - return elem ? elem->_arg : 0 ; + return elem ? elem->_arg : nullptr ; } //////////////////////////////////////////////////////////////////////////////// @@ -552,8 +556,8 @@ void RooLinkedList::Clear(Option_t *) next = elem->_next ; deleteElement(elem) ; } - _first = 0 ; - _last = 0 ; + _first = nullptr ; + _last = nullptr ; _size = 0 ; if (_htableName) { @@ -581,8 +585,8 @@ void RooLinkedList::Delete(Option_t *) deleteElement(elem) ; elem = next ; } - _first = 0 ; - _last = 0 ; + _first = nullptr ; + _last = nullptr ; _size = 0 ; if (_htableName) { @@ -666,7 +670,7 @@ RooAbsArg* RooLinkedList::findArg(const RooAbsArg* arg) const if (a) return a; //cout << "RooLinkedList::findArg: possibly renamed '" << arg->GetName() << "', kRenamedArg=" << arg->namePtr()->TestBit(RooNameReg::kRenamedArg) << endl; // See if it might have been renamed - if (!arg->namePtr()->TestBit(RooNameReg::kRenamedArg)) return 0; + if (!arg->namePtr()->TestBit(RooNameReg::kRenamedArg)) return nullptr; } RooLinkedListElem* ptr = _first ; @@ -677,7 +681,7 @@ RooAbsArg* RooLinkedList::findArg(const RooAbsArg* arg) const } ptr = ptr->_next ; } - return 0 ; + return nullptr ; } //////////////////////////////////////////////////////////////////////////////// @@ -820,7 +824,7 @@ RooLinkedListElem* RooLinkedList::mergesort_impl( } while (int(sz) != i); } // link elements in array - arr[0]->_prev = arr[sz - 1]->_next = 0; + arr[0]->_prev = arr[sz - 1]->_next = nullptr; for (int i = 0; i < int(sz - 1); ++i) { arr[i]->_next = arr[i + 1]; arr[i + 1]->_prev = arr[i]; @@ -836,8 +840,8 @@ RooLinkedListElem* RooLinkedList::mergesort_impl( if (!end->_next) break; } // disconnect the two sublists - l2->_prev->_next = 0; - l2->_prev = 0; + l2->_prev->_next = nullptr; + l2->_prev = nullptr; // sort the two sublists (only recurse if we have to) if (l1->_next) l1 = mergesort_impl(l1, sz / 2); if (l2->_next) l2 = mergesort_impl(l2, sz - sz / 2); diff --git a/roofit/roofitcore/src/RooMCIntegrator.cxx b/roofit/roofitcore/src/RooMCIntegrator.cxx index 258d5ea7ab292..8317b3c530d92 100644 --- a/roofit/roofitcore/src/RooMCIntegrator.cxx +++ b/roofit/roofitcore/src/RooMCIntegrator.cxx @@ -36,7 +36,7 @@ based on a C version from the 0.9 beta release of the GNU scientific library. #include "RooCategory.h" #include "RooMsgService.h" -#include +#include @@ -76,28 +76,23 @@ void RooMCIntegrator::registerIntegrator(RooNumIntFactory& fact) RooRealVar nIntPerDim("nIntPerDim","Number of integration samples (per dimension)",5000) ; // Create prototype integrator - RooMCIntegrator* proto = new RooMCIntegrator() ; + auto creator = [](const RooAbsFunc& function, const RooNumIntConfig& config) { + return std::make_unique(function,config); + }; // Register prototype and default config with factory - fact.storeProtoIntegrator(proto,RooArgSet(samplingMode,genType,verbose,alpha,nRefineIter,nRefinePerDim,nIntPerDim)) ; + std::string name = "RooMCIntegrator"; + fact.registerPlugin(name, creator, {samplingMode,genType,verbose,alpha,nRefineIter,nRefinePerDim,nIntPerDim}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/true, + /*canIntegrateND=*/true, + /*canIntegrateOpenEnded=*/false); // Make this method the default for all N>2-dim integrals - RooNumIntConfig::defaultConfig().methodND().setLabel(proto->ClassName()) ; + RooNumIntConfig::defaultConfig().methodND().setLabel(name) ; } - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor -/// -/// coverity[UNINIT_CTOR] - - RooMCIntegrator::RooMCIntegrator() -{ -} - - - //////////////////////////////////////////////////////////////////////////////// /// Construct an integrator over 'function' with given sampling mode /// and generator type. The sampling mode can be 'Importance' @@ -113,7 +108,7 @@ RooMCIntegrator::RooMCIntegrator(const RooAbsFunc& function, SamplingMode mode, { // coverity[UNINIT_CTOR] if(!(_valid= _grid.isValid())) return; - if(_verbose) _grid.Print(); + if(_verbose) _grid.print(std::cout); } @@ -136,22 +131,10 @@ RooMCIntegrator::RooMCIntegrator(const RooAbsFunc& function, const RooNumIntConf // check that our grid initialized without errors if(!(_valid= _grid.isValid())) return; - if(_verbose) _grid.Print(); + if(_verbose) _grid.print(std::cout); } - -//////////////////////////////////////////////////////////////////////////////// -/// Return clone of this generator operating on given function with given configuration -/// Needed to support RooNumIntFactory - -RooAbsIntegrator* RooMCIntegrator::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooMCIntegrator(function,config) ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Destructor @@ -233,11 +216,11 @@ double RooMCIntegrator::vegas(Stage stage, UInt_t calls, UInt_t iterations, doub bins= boxes/box_per_bin; if(bins > RooGrid::maxBins) bins= RooGrid::maxBins; boxes = box_per_bin * bins; - oocxcoutD((TObject*)0,Integration) << "RooMCIntegrator: using stratified sampling with " << bins << " bins and " + oocxcoutD((TObject*)nullptr,Integration) << "RooMCIntegrator: using stratified sampling with " << bins << " bins and " << box_per_bin << " boxes/bin" << endl; } else { - oocxcoutD((TObject*)0,Integration) << "RooMCIntegrator: using importance sampling with " << bins << " bins and " + oocxcoutD((TObject*)nullptr,Integration) << "RooMCIntegrator: using importance sampling with " << bins << " bins and " << boxes << " boxes" << endl; } } @@ -353,12 +336,12 @@ double RooMCIntegrator::vegas(Stage stage, UInt_t calls, UInt_t iterations, doub cum_int += (intgrl - cum_int) / (it + 1.0); cum_sig = 0.0; } - oocxcoutD((TObject*)0,Integration) << "=== Iteration " << _it_num << " : I = " << intgrl << " +/- " << sqrt(sig) << endl + oocxcoutD((TObject*)nullptr,Integration) << "=== Iteration " << _it_num << " : I = " << intgrl << " +/- " << sqrt(sig) << endl << " Cumulative : I = " << cum_int << " +/- " << cum_sig << "( chi2 = " << _chisq << ")" << endl; // print the grid after the final iteration - if (oodologD((TObject*)0,Integration)) { - if(it + 1 == iterations) _grid.Print("V"); + if (oodologD((TObject*)nullptr,Integration)) { + if(it + 1 == iterations) _grid.print(std::cout, true); } _grid.refine(_alpha); } diff --git a/roofit/roofitcore/src/RooMCStudy.cxx b/roofit/roofitcore/src/RooMCStudy.cxx index 527df60800237..984db23e146c8 100644 --- a/roofit/roofitcore/src/RooMCStudy.cxx +++ b/roofit/roofitcore/src/RooMCStudy.cxx @@ -120,13 +120,13 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, cmdList.Add(const_cast(&arg7)) ; cmdList.Add(const_cast(&arg8)) ; // Select the pdf-specific commands - RooCmdConfig pc(Form("RooMCStudy::RooMCStudy(%s)",model.GetName())) ; + RooCmdConfig pc("RooMCStudy::RooMCStudy(" + std::string(model.GetName()) + ")"); - pc.defineObject("fitModel","FitModel",0,0) ; - pc.defineSet("condObs","ProjectedObservables",0,0) ; - pc.defineObject("protoData","PrototypeData",0,0) ; - pc.defineSet("cPars","Constrain",0,0) ; - pc.defineSet("extCons","ExternalConstraints",0,0) ; + pc.defineObject("fitModel","FitModel",0,nullptr) ; + pc.defineSet("condObs","ProjectedObservables",0,nullptr) ; + pc.defineObject("protoData","PrototypeData",0,nullptr) ; + pc.defineSet("cPars","Constrain",0,nullptr) ; + pc.defineSet("extCons","ExternalConstraints",0,nullptr) ; pc.defineInt("silence","Silence",0,0) ; pc.defineInt("randProtoData","PrototypeData",0,0) ; pc.defineInt("verboseGen","Verbose",0,0) ; @@ -138,7 +138,7 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, pc.process(cmdList) ; if (!pc.ok(true)) { // WVE do something here - throw std::string("RooMCStudy::RooMCStudy() Error in parsing arguments passed to contructor") ; + throw std::string("RooMCStudy::RooMCStudy() Error in parsing arguments passed to constructor") ; return ; } @@ -196,7 +196,7 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, _constrPdf->getObservables(¶ms, cparams); consPars.add(cparams) ; } - _constrGenContext.reset(_constrPdf->genContext(consPars,0,0,_verboseGen)); + _constrGenContext.reset(_constrPdf->genContext(consPars,nullptr,nullptr,_verboseGen)); _perExptGenParams = true ; @@ -206,13 +206,13 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, // Extract generator and fit models _genModel = const_cast(&model) ; - _genSample = 0 ; - RooAbsPdf* fitModel = static_cast(pc.getObject("fitModel",0)) ; + _genSample = nullptr ; + RooAbsPdf* fitModel = static_cast(pc.getObject("fitModel",nullptr)) ; _fitModel = fitModel ? fitModel : _genModel ; // Extract conditional observables and prototype data - _genProtoData = static_cast(pc.getObject("protoData",0)) ; - if (auto condObs = pc.getSet("condObs",0)) { + _genProtoData = static_cast(pc.getObject("protoData",nullptr)) ; + if (auto condObs = pc.getSet("condObs",nullptr)) { _projDeps.add(*condObs); } @@ -230,7 +230,7 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, _genModel->getParameters(&_dependents, _genParams); if (!_binGenData) { - _genContext.reset(_genModel->genContext(_dependents,_genProtoData,0,_verboseGen)); + _genContext.reset(_genModel->genContext(_dependents,_genProtoData,nullptr,_verboseGen)); _genContext->attach(_genParams) ; } @@ -256,14 +256,14 @@ RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables, // Mark all variable to store their errors in the dataset tmp2.setAttribAll("StoreError",true) ; tmp2.setAttribAll("StoreAsymError",true) ; - TString fpdName ; + std::string fpdName; if (_fitModel==_genModel) { - fpdName = Form("fitParData_%s",_fitModel->GetName()) ; + fpdName = "fitParData_" + std::string(_fitModel->GetName()); } else { - fpdName= Form("fitParData_%s_%s",_fitModel->GetName(),_genModel->GetName()) ; + fpdName= "fitParData_" + std::string(_fitModel->GetName()) + "_" + std::string(_genModel->GetName()); } - _fitParData = std::make_unique(fpdName.Data(),"Fit Parameters DataSet",tmp2); + _fitParData = std::make_unique(fpdName,"Fit Parameters DataSet",tmp2); tmp2.setAttribAll("StoreError",false) ; tmp2.setAttribAll("StoreAsymError",false) ; @@ -349,7 +349,7 @@ bool RooMCStudy::run(bool doGenerate, bool DoFit, Int_t nSamples, Int_t nEvtPerS ooccoutP(_fitModel,Generation) << "sample " << nSamples << endl ; } - _genSample = 0; + _genSample = nullptr; bool existingData = false ; if (doGenerate) { // Generate sample @@ -383,7 +383,7 @@ bool RooMCStudy::run(bool doGenerate, bool DoFit, Int_t nSamples, Int_t nEvtPerS } // Binned generation - _genSample = _genModel->generateBinned(_dependents,nEvt) ; + _genSample = std::unique_ptr{_genModel->generateBinned(_dependents,nEvt)}.release(); } else { @@ -481,7 +481,7 @@ bool RooMCStudy::run(bool doGenerate, bool DoFit, Int_t nSamples, Int_t nEvtPerS if (_genParData) { for(RooAbsArg * arg : *_genParData->get()) { - _genParData->changeObservableName(arg->GetName(),Form("%s_gen",arg->GetName())) ; + _genParData->changeObservableName(arg->GetName(),(std::string(arg->GetName()) + "_gen").c_str()); } _fitParData->merge(_genParData.get()); @@ -577,7 +577,7 @@ bool RooMCStudy::fit(Int_t nSamples, TList& dataSetList) _genDataList.Add(gset) ; } - return run(false,true,nSamples,0,true,0) ; + return run(false,true,nSamples,0,true,nullptr) ; } @@ -596,7 +596,7 @@ void RooMCStudy::resetFitParams() //////////////////////////////////////////////////////////////////////////////// /// Internal function. Performs actual fit according to specifications -RooFitResult* RooMCStudy::doFit(RooAbsData* genSample) +RooFit::OwningPtr RooMCStudy::doFit(RooAbsData* genSample) { // Optionally bin dataset before fitting std::unique_ptr ownedDataHist; @@ -620,9 +620,7 @@ RooFitResult* RooMCStudy::doFit(RooAbsData* genSample) fitOptList.Add(&condo) ; } fitOptList.Add(&plevel) ; - RooFitResult* fr = _fitModel->fitTo(*data,fitOptList) ; - - return fr ; + return _fitModel->fitTo(*data,fitOptList); } @@ -631,18 +629,18 @@ RooFitResult* RooMCStudy::doFit(RooAbsData* genSample) /// Redo fit on 'current' toy sample, or if genSample is not nullptr /// do fit on given sample instead -RooFitResult* RooMCStudy::refit(RooAbsData* genSample) +RooFit::OwningPtr RooMCStudy::refit(RooAbsData* genSample) { if (!genSample) { genSample = _genSample ; } - RooFitResult* fr(0) ; + std::unique_ptr fr; if (genSample->sumEntries()>0) { - fr = doFit(genSample) ; + fr = std::unique_ptr{doFit(genSample)}; } - return fr ; + return RooFit::Detail::owningPtr(std::move(fr)); } @@ -667,7 +665,7 @@ bool RooMCStudy::fitSample(RooAbsData* genSample) bool ok ; std::unique_ptr fr; if (genSample->sumEntries()>0) { - fr.reset(doFit(genSample)); + fr = std::unique_ptr{doFit(genSample)}; ok = (fr->status()==0) ; } else { ok = false ; @@ -817,9 +815,9 @@ const RooDataSet& RooMCStudy::fitParDataSet() //////////////////////////////////////////////////////////////////////////////// /// Return an argset with the fit parameters for the given sample number /// -/// NB: The fit parameters are only stored for successfull fits, +/// NB: The fit parameters are only stored for successful fits, /// thus the maximum sampleNum can be less that the number -/// of generated samples and if so, the indeces will +/// of generated samples and if so, the indices will /// be out of synch with genData() and fitResult() const RooArgSet* RooMCStudy::fitParams(Int_t sampleNum) const @@ -827,7 +825,7 @@ const RooArgSet* RooMCStudy::fitParams(Int_t sampleNum) const // Check if sampleNum is in range if (sampleNum<0 || sampleNum>=_fitParData->numEntries()) { oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitParams: ERROR, invalid sample number: " << sampleNum << endl ; - return 0 ; + return nullptr ; } return _fitParData->get(sampleNum) ; @@ -845,7 +843,7 @@ const RooFitResult* RooMCStudy::fitResult(Int_t sampleNum) const // Check if sampleNum is in range if (sampleNum<0 || sampleNum>=_fitResList.GetSize()) { oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, invalid sample number: " << sampleNum << endl ; - return 0 ; + return nullptr ; } // Retrieve fit result object @@ -856,7 +854,7 @@ const RooFitResult* RooMCStudy::fitResult(Int_t sampleNum) const oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, no fit result saved for sample " << sampleNum << ", did you use the 'r; fit option?" << endl ; } - return 0 ; + return nullptr ; } @@ -870,13 +868,13 @@ RooAbsData* RooMCStudy::genData(Int_t sampleNum) const // Check that generated data was saved if (_genDataList.GetSize()==0) { oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, generated data was not saved" << endl ; - return 0 ; + return nullptr ; } // Check if sampleNum is in range if (sampleNum<0 || sampleNum>=_genDataList.GetSize()) { oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, invalid sample number: " << sampleNum << endl ; - return 0 ; + return nullptr ; } return (RooAbsData*) _genDataList.At(sampleNum) ; @@ -923,7 +921,7 @@ RooPlot* RooMCStudy::plotParam(const char* paramName, const RooCmdArg& arg1, con RooRealVar* param = static_cast(_fitParData->get()->find(paramName)) ; if (!param) { oocoutE(_fitModel,InputArguments) << "RooMCStudy::plotParam: ERROR: no parameter defined with name " << paramName << endl ; - return 0 ; + return nullptr ; } // Forward to implementation below @@ -1006,8 +1004,13 @@ RooPlot* RooMCStudy::plotError(const RooRealVar& param, const RooCmdArg& arg1, c } std::unique_ptr evar{param.errorVar()}; - std::unique_ptr evar_rrv{static_cast(evar->createFundamental())}; - return plotParam(*evar_rrv,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); + std::unique_ptr evar_rrv{evar->createFundamental()}; + RooPlot* frame = plotParam(static_cast(*evar_rrv),arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ; + + // To make sure the frame has no dangling pointer to evar_rrv. + frame->createInternalPlotVarClone(); + + return frame ; } namespace { @@ -1029,7 +1032,7 @@ void fitGaussToPulls(RooPlot& frame, RooDataSet& fitParData) RooRealVar& pullSigma = *ws.var("pullSigma"); RooAbsPdf& pullGauss = *ws.pdf("pullGauss"); - pullGauss.fitTo(fitParData, RooFit::Minos(0), RooFit::PrintLevel(-1)) ; + pullGauss.fitTo(fitParData, RooFit::Minos(false), RooFit::PrintLevel(-1)) ; pullGauss.plotOn(&frame) ; // Instead of using paramOn() without command arguments to plot the fit @@ -1112,8 +1115,8 @@ RooPlot* RooMCStudy::plotPull(const RooRealVar& param, const RooCmdArg& arg1, co RooPlot* frame = makeFrameAndPlotCmd(pvar, cmdList, true) ; if (frame) { - // Pick up optonal FitGauss command from list - RooCmdConfig pc(Form("RooMCStudy::plotPull(%s)",_genModel->GetName())) ; + // Pick up optional FitGauss command from list + RooCmdConfig pc("RooMCStudy::plotPull(" + std::string(_genModel->GetName()) + ")"); pc.defineInt("fitGauss","FitGauss",0,0) ; pc.allowUndefined() ; pc.process(cmdList) ; @@ -1132,6 +1135,9 @@ RooPlot* RooMCStudy::plotPull(const RooRealVar& param, const RooCmdArg& arg1, co if (fitGauss) { fitGaussToPulls(*frame, *_fitParData); } + + // To make sure the frame has no dangling pointer to pvar. + frame->createInternalPlotVarClone(); } return frame; } @@ -1146,7 +1152,7 @@ RooPlot* RooMCStudy::plotPull(const RooRealVar& param, const RooCmdArg& arg1, co RooPlot* RooMCStudy::makeFrameAndPlotCmd(const RooRealVar& param, RooLinkedList& cmdList, bool symRange) const { // Select the frame-specific commands - RooCmdConfig pc(Form("RooMCStudy::plotParam(%s)",_genModel->GetName())) ; + RooCmdConfig pc("RooMCStudy::plotParam(" + std::string(_genModel->GetName()) + ")"); pc.defineInt("nbins","Bins",0,0) ; pc.defineDouble("xlo","Range",0,0) ; pc.defineDouble("xhi","Range",1,0) ; @@ -1158,7 +1164,7 @@ RooPlot* RooMCStudy::makeFrameAndPlotCmd(const RooRealVar& param, RooLinkedList& pc.allowUndefined() ; pc.process(cmdList) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } // Make frame according to specs @@ -1175,14 +1181,14 @@ RooPlot* RooMCStudy::makeFrameAndPlotCmd(const RooRealVar& param, RooLinkedList& // FrameBins, FrameRange or none are given, build custom frame command list RooCmdArg bins = RooFit::Bins(nbins) ; RooCmdArg range = RooFit::Range(xlo,xhi) ; - RooCmdArg autor = symRange ? RooFit::AutoSymRange(*_fitParData,0.2) : RooFit::AutoRange(*_fitParData,0.2) ; + RooCmdArg autoRange = symRange ? RooFit::AutoSymRange(*_fitParData,0.2) : RooFit::AutoRange(*_fitParData,0.2) ; RooLinkedList frameCmdList ; if (pc.hasProcessed("Bins")) frameCmdList.Add(&bins) ; if (pc.hasProcessed("Range")) { frameCmdList.Add(&range) ; } else { - frameCmdList.Add(&autor) ; + frameCmdList.Add(&autoRange) ; } frame = param.frame(frameCmdList) ; } diff --git a/roofit/roofitcore/src/RooMappedCategory.cxx b/roofit/roofitcore/src/RooMappedCategory.cxx index 815d3ca38a343..3f028de799538 100644 --- a/roofit/roofitcore/src/RooMappedCategory.cxx +++ b/roofit/roofitcore/src/RooMappedCategory.cxx @@ -81,7 +81,7 @@ class RooMappedCategoryCache : public RooAbsCache { RooMappedCategory::RooMappedCategory(const char *name, const char *title, RooAbsCategory& inputCat, const char* defOut, Int_t defOutIdx) : RooAbsCategory(name, title), _inputCat("input","Input category",this,inputCat), - _mapcache(0) + _mapcache(nullptr) { // Constructor with input category and name of default output state, which is assigned // to all input category states that do not follow any mapping rule. @@ -95,7 +95,7 @@ RooMappedCategory::RooMappedCategory(const char *name, const char *title, RooAbs RooMappedCategory::RooMappedCategory(const RooMappedCategory& other, const char *name) : RooAbsCategory(other,name), _inputCat("input",this,other._inputCat), _mapArray(other._mapArray), - _mapcache(0) + _mapcache(nullptr) { _defCat = lookupIndex(other.lookupName(other._defCat)); } @@ -208,7 +208,7 @@ bool RooMappedCategory::readFromStream(std::istream& is, bool compact, bool /*ve TString defCatName(lookupName(_defCat)); _mapArray.clear() ; delete _mapcache; - _mapcache = 0; + _mapcache = nullptr; clearTypes() ; _defCat = defineState(defCatName.Data()).second; @@ -222,7 +222,7 @@ bool RooMappedCategory::readFromStream(std::istream& is, bool compact, bool /*ve bool readToken(true) ; // Loop over definition sequences - while(1) { + while(true) { if (readToken) token=parser.readToken() ; if (token.IsNull()) break ; readToken=true ; @@ -231,7 +231,7 @@ bool RooMappedCategory::readFromStream(std::istream& is, bool compact, bool /*ve if (parser.expectToken(":",true)) return true ; // Loop over list of sources for this destination - while(1) { + while(true) { srcKey = parser.readToken() ; token = parser.readToken() ; diff --git a/roofit/roofitcore/src/RooMath.cxx b/roofit/roofitcore/src/RooMath.cxx index 216983988f230..91b006e479b22 100644 --- a/roofit/roofitcore/src/RooMath.cxx +++ b/roofit/roofitcore/src/RooMath.cxx @@ -18,10 +18,9 @@ // RooMath is a singleton class implementing various mathematical // functions not found in TMath, mostly involving complex algebra - #include -#include +#include #include #include @@ -30,19 +29,19 @@ std::complex RooMath::faddeeva(std::complex z) { - return faddeeva_impl::faddeeva(z); + return RooHeterogeneousMath::faddeeva(z); } std::complex RooMath::faddeeva_fast(std::complex z) { - return faddeeva_impl::faddeeva_fast(z); + return RooHeterogeneousMath::faddeeva_fast(z); } std::complex RooMath::erfc(const std::complex z) { double re = -z.real() * z.real() + z.imag() * z.imag(); double im = -2. * z.real() * z.imag(); - faddeeva_impl::cexp(re, im); + RooHeterogeneousMath::cexp(re, im); return (z.real() >= 0.) ? (std::complex(re, im) * faddeeva(std::complex(-z.imag(), z.real()))) : (2. - std::complex(re, im) * faddeeva(std::complex(z.imag(), -z.real()))); } @@ -51,7 +50,7 @@ std::complex RooMath::erfc_fast(const std::complex z) { double re = -z.real() * z.real() + z.imag() * z.imag(); double im = -2. * z.real() * z.imag(); - faddeeva_impl::cexp(re, im); + RooHeterogeneousMath::cexp(re, im); return (z.real() >= 0.) ? (std::complex(re, im) * faddeeva_fast(std::complex(-z.imag(), z.real()))) : (2. - std::complex(re, im) * faddeeva_fast(std::complex(z.imag(), -z.real()))); @@ -61,7 +60,7 @@ std::complex RooMath::erf(const std::complex z) { double re = -z.real() * z.real() + z.imag() * z.imag(); double im = -2. * z.real() * z.imag(); - faddeeva_impl::cexp(re, im); + RooHeterogeneousMath::cexp(re, im); return (z.real() >= 0.) ? (1. - std::complex(re, im) * faddeeva(std::complex(-z.imag(), z.real()))) : (std::complex(re, im) * faddeeva(std::complex(z.imag(), -z.real())) - 1.); } @@ -70,7 +69,7 @@ std::complex RooMath::erf_fast(const std::complex z) { double re = -z.real() * z.real() + z.imag() * z.imag(); double im = -2. * z.real() * z.imag(); - faddeeva_impl::cexp(re, im); + RooHeterogeneousMath::cexp(re, im); return (z.real() >= 0.) ? (1. - std::complex(re, im) * faddeeva_fast(std::complex(-z.imag(), z.real()))) : (std::complex(re, im) * faddeeva_fast(std::complex(z.imag(), -z.real())) - 1.); @@ -82,14 +81,14 @@ double RooMath::interpolate(double ya[], Int_t n, double x) // Int to Double conversion is faster via array lookup than type conversion! static double itod[20] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, - 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0}; + 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0}; int i, m, ns = 1; double den, dif, dift /*,ho,hp,w*/, y, dy; double c[20], d[20]; - dif = fabs(x); + dif = std::abs(x); for (i = 1; i <= n; i++) { - if ((dift = fabs(x - itod[i - 1])) < dif) { + if ((dift = std::abs(x - itod[i - 1])) < dif) { ns = i; dif = dift; } @@ -121,9 +120,9 @@ double RooMath::interpolate(double xa[], double ya[], Int_t n, double x) double den, dif, dift, ho, hp, w, y, dy; double c[20], d[20]; - dif = fabs(x - xa[0]); + dif = std::abs(x - xa[0]); for (i = 1; i <= n; i++) { - if ((dift = fabs(x - xa[i - 1])) < dif) { + if ((dift = std::abs(x - xa[i - 1])) < dif) { ns = i; dif = dift; } diff --git a/roofit/roofitcore/src/RooMinimizer.cxx b/roofit/roofitcore/src/RooMinimizer.cxx index fd9db220f427a..c9d942e703a16 100644 --- a/roofit/roofitcore/src/RooMinimizer.cxx +++ b/roofit/roofitcore/src/RooMinimizer.cxx @@ -115,9 +115,10 @@ RooMinimizer::RooMinimizer(RooAbsReal &function, Config const &cfg) : _cfg(cfg) << "also setting parallel gradient calculation mode." << std::endl; _cfg.enableParallelGradient = 1; } - // If _cfg.parallelize is larger than zero set the number of workers to that value. Otherwise do not do anything and let - // RooFit::MultiProcess handle the number of workers - if (_cfg.parallelize > 0) RooFit::MultiProcess::Config::setDefaultNWorkers(_cfg.parallelize); + // If _cfg.parallelize is larger than zero set the number of workers to that value. Otherwise do not do + // anything and let RooFit::MultiProcess handle the number of workers + if (_cfg.parallelize > 0) + RooFit::MultiProcess::Config::setDefaultNWorkers(_cfg.parallelize); RooFit::MultiProcess::Config::setTimingAnalysis(_cfg.timingAnalysis); _fcn = std::make_unique( @@ -131,14 +132,14 @@ RooMinimizer::RooMinimizer(RooAbsReal &function, Config const &cfg) : _cfg(cfg) "please recompile with -Droofit_multiprocess=ON for parallel evaluation"); #endif } else { // modular test statistic non parallel - coutW(InputArguments) << "Requested modular likelihood without gradient parallelization, some features such as offsetting " - << "may not work yet. Non-modular likelihoods are more reliable without parallelization." - << std::endl; - // The RooRealL that is used in the case where the modular likelihood is being passed to a RooMinimizerFcn does not have - // offsetting implemented. Therefore, offsetting will not work in this case. Other features might also not work since the - // RooRealL was not intended for minimization. Further development is required to make the MinuitFcnGrad also handle serial gradient - // minimization. The MinuitFcnGrad accepts a RooAbsL and has offsetting implemented, thus omitting the need for RooRealL - // minimization altogether. + coutW(InputArguments) + << "Requested modular likelihood without gradient parallelization, some features such as offsetting " + << "may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl; + // The RooRealL that is used in the case where the modular likelihood is being passed to a RooMinimizerFcn does + // not have offsetting implemented. Therefore, offsetting will not work in this case. Other features might also + // not work since the RooRealL was not intended for minimization. Further development is required to make the + // MinuitFcnGrad also handle serial gradient minimization. The MinuitFcnGrad accepts a RooAbsL and has + // offsetting implemented, thus omitting the need for RooRealL minimization altogether. _fcn = std::make_unique(&function, this); } } else { @@ -222,7 +223,7 @@ void RooMinimizer::setMaxIterations(int n) } //////////////////////////////////////////////////////////////////////////////// -/// Change maximum number of likelihood function calss from MINUIT +/// Change maximum number of likelihood function class from MINUIT /// (RooMinimizer default 500 * #%parameters) void RooMinimizer::setMaxFunctionCalls(int n) @@ -297,7 +298,7 @@ ROOT::Fit::Fitter const *RooMinimizer::fitter() const bool RooMinimizer::fitFcn() const { - return _fcn->fit(*_theFitter); + return _theFitter->FitFCN(*_fcn->getMultiGenFcn()); } //////////////////////////////////////////////////////////////////////////////// @@ -310,28 +311,27 @@ bool RooMinimizer::fitFcn() const /// \param[in] alg Fit algorithm to use. (Optional) int RooMinimizer::minimize(const char *type, const char *alg) { - if (_cfg.timingAnalysis) + if (_cfg.timingAnalysis) { #ifdef R__HAS_ROOFIT_MULTIPROCESS addParamsToProcessTimer(); #else - throw std::logic_error( - "ProcessTimer, but ROOT was not compiled with multiprocessing enabled, " - "please recompile with -Droofit_multiprocess=ON for logging with the " - "ProcessTimer."); + throw std::logic_error("ProcessTimer, but ROOT was not compiled with multiprocessing enabled, " + "please recompile with -Droofit_multiprocess=ON for logging with the " + "ProcessTimer."); #endif + } _fcn->Synchronize(_theFitter->Config().ParamsSettings()); setMinimizerType(type); - _theFitter->Config().SetMinimizer(type, alg); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), alg); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - bool ret = fitFcn(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + { + auto ctx = makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + bool ret = fitFcn(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -350,14 +350,13 @@ int RooMinimizer::migrad() { _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); + { + auto ctx = makeEvalErrorContext(); - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "migrad"); - bool ret = fitFcn(); - _status = ((ret) ? _theFitter->Result().Status() : -1); - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "migrad"); + bool ret = fitFcn(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -381,14 +380,13 @@ int RooMinimizer::hesse() _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); - bool ret = _theFitter->CalculateHessErrors(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + { + auto ctx = makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); + bool ret = _theFitter->CalculateHessErrors(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -413,14 +411,14 @@ int RooMinimizer::minos() _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); + { + auto ctx = makeEvalErrorContext(); - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); - bool ret = _theFitter->CalculateMinosErrors(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); + bool ret = _theFitter->CalculateMinosErrors(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -445,31 +443,30 @@ int RooMinimizer::minos(const RooArgSet &minosParamList) _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - // get list of parameters for Minos - std::vector paramInd; - for (RooAbsArg *arg : minosParamList) { - RooAbsArg *par = _fcn->GetFloatParamList()->find(arg->GetName()); - if (par && !par->isConstant()) { - int index = _fcn->GetFloatParamList()->index(par); - paramInd.push_back(index); + { + auto ctx = makeEvalErrorContext(); + + // get list of parameters for Minos + std::vector paramInd; + for (RooAbsArg *arg : minosParamList) { + RooAbsArg *par = _fcn->GetFloatParamList()->find(arg->GetName()); + if (par && !par->isConstant()) { + int index = _fcn->GetFloatParamList()->index(par); + paramInd.push_back(index); + } } - } - if (paramInd.size()) { - // set the parameter indeces - _theFitter->Config().SetMinosErrors(paramInd); + if (paramInd.size()) { + // set the parameter indices + _theFitter->Config().SetMinosErrors(paramInd); - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); - bool ret = _theFitter->CalculateMinosErrors(); - _status = ((ret) ? _theFitter->Result().Status() : -1); - // to avoid that following minimization computes automatically the Minos errors - _theFitter->Config().SetMinosErrors(false); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str()); + bool ret = _theFitter->CalculateMinosErrors(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + // to avoid that following minimization computes automatically the Minos errors + _theFitter->Config().SetMinosErrors(false); + } } - - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -489,14 +486,13 @@ int RooMinimizer::seek() { _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "seek"); - bool ret = fitFcn(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + { + auto ctx = makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "seek"); + bool ret = fitFcn(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -515,14 +511,13 @@ int RooMinimizer::simplex() { _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "simplex"); - bool ret = fitFcn(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + { + auto ctx = makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "simplex"); + bool ret = fitFcn(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -541,14 +536,13 @@ int RooMinimizer::improve() { _fcn->Synchronize(_theFitter->Config().ParamsSettings()); profileStart(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors); - RooAbsReal::clearEvalErrorLog(); - - _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "migradimproved"); - bool ret = fitFcn(); - _status = ((ret) ? _theFitter->Result().Status() : -1); + { + auto ctx = makeEvalErrorContext(); - RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors); + _theFitter->Config().SetMinimizer(_cfg.minimizerType.c_str(), "migradimproved"); + bool ret = fitFcn(); + _status = ((ret) ? _theFitter->Result().Status() : -1); + } profileStop(); _fcn->BackProp(_theFitter->Result()); @@ -590,7 +584,7 @@ void RooMinimizer::optimizeConst(int flag) /// EDM setting, number of calls with evaluation problems, the minimized /// function value and the full correlation matrix. -RooFitResult *RooMinimizer::save(const char *userName, const char *userTitle) +RooFit::OwningPtr RooMinimizer::save(const char *userName, const char *userTitle) { if (_theFitter->GetMinimizer() == 0) { coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!" << endl; @@ -600,7 +594,7 @@ RooFitResult *RooMinimizer::save(const char *userName, const char *userTitle) TString name, title; name = userName ? userName : Form("%s", _fcn->getFunctionName().c_str()); title = userTitle ? userTitle : Form("%s", _fcn->getFunctionTitle().c_str()); - RooFitResult *fitRes = new RooFitResult(name, title); + auto fitRes = std::make_unique(name, title); // Move eventual fixed parameters in floatList to constList RooArgList saveConstList(*(_fcn->GetConstParamList())); @@ -619,13 +613,9 @@ RooFitResult *RooMinimizer::save(const char *userName, const char *userTitle) fitRes->setConstParList(saveConstList); fitRes->setInitParList(saveFloatInitList); - // The fitter often clones the function. We therefore have to ask it for its copy. - const auto fitFcn = dynamic_cast(_theFitter->GetFCN()); double removeOffset = 0.; - if (fitFcn) { - fitRes->setNumInvalidNLL(fitFcn->GetNumInvalidNLL()); - removeOffset = -fitFcn->getOffset(); - } + fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL()); + removeOffset = -_fcn->getOffset(); fitRes->setStatus(_status); fitRes->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()); @@ -650,7 +640,7 @@ RooFitResult *RooMinimizer::save(const char *userName, const char *userTitle) fitRes->setStatusHistory(_statusHistory); - return fitRes; + return RooFit::Detail::owningPtr(std::move(fitRes)); } //////////////////////////////////////////////////////////////////////////////// @@ -673,7 +663,8 @@ RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, do double n5, double n6, unsigned int npoints) { RooArgList *params = _fcn->GetFloatParamList(); - std::unique_ptr paramSave{static_cast(params->snapshot())}; + RooArgList paramSave; + params->snapshot(paramSave); // Verify that both variables are floating parameters of PDF int index1 = _fcn->GetFloatParamList()->index(&var1); @@ -747,7 +738,7 @@ RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, do _theFitter->GetMinimizer()->SetErrorDef(errdef); // restore parameter values - params->assign(*paramSave); + params->assign(paramSave); return frame; } @@ -758,15 +749,15 @@ RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, do void RooMinimizer::addParamsToProcessTimer() { #ifdef R__HAS_ROOFIT_MULTIPROCESS - // parameter indices for use in timing heat matrix - std::vector parameter_names; - for (auto && parameter : *_fcn->GetFloatParamList()) { - parameter_names.push_back(parameter->GetName()); - if (_cfg.verbose) { - coutI(Minimization) << "parameter name: " << parameter_names.back() << std::endl; - } - } - RooFit::MultiProcess::ProcessTimer::add_metadata(parameter_names); + // parameter indices for use in timing heat matrix + std::vector parameter_names; + for (auto &¶meter : *_fcn->GetFloatParamList()) { + parameter_names.push_back(parameter->GetName()); + if (_cfg.verbose) { + coutI(Minimization) << "parameter name: " << parameter_names.back() << std::endl; + } + } + RooFit::MultiProcess::ProcessTimer::add_metadata(parameter_names); #else coutI(Minimization) << "Not adding parameters to processtimer because multiprocessing " << "is not enabled." << std::endl; @@ -817,12 +808,12 @@ void RooMinimizer::applyCovarianceMatrix(TMatrixDSym const &V) _fcn->ApplyCovarianceMatrix(*_extV); } -RooFitResult *RooMinimizer::lastMinuitFit() +RooFit::OwningPtr RooMinimizer::lastMinuitFit() { return RooMinimizer::lastMinuitFit({}); } -RooFitResult *RooMinimizer::lastMinuitFit(const RooArgList &varList) +RooFit::OwningPtr RooMinimizer::lastMinuitFit(const RooArgList &varList) { // Import the results of the last fit performed, interpreting // the fit parameters as the given varList of parameters. @@ -850,7 +841,7 @@ RooFitResult *RooMinimizer::lastMinuitFit(const RooArgList &varList) } } - RooFitResult *res = new RooFitResult("lastMinuitFit", "Last MINUIT fit"); + auto res = std::make_unique("lastMinuitFit", "Last MINUIT fit"); // Extract names of fit parameters // and construct corresponding RooRealVars @@ -919,7 +910,7 @@ RooFitResult *RooMinimizer::lastMinuitFit(const RooArgList &varList) } res->fillCorrMatrix(globalCC, corrs, covs); - return res; + return RooFit::Detail::owningPtr(std::move(res)); } /// Try to recover from invalid function values. When invalid function values @@ -973,3 +964,13 @@ int RooMinimizer::Config::getDefaultWorkers() return 0; #endif } + +std::unique_ptr RooMinimizer::makeEvalErrorContext() const +{ + RooAbsReal::clearEvalErrorLog(); + // If evaluation error printing is disabled, we don't need to collect the + // errors and only need to count them. This significantly reduces the + // performance overhead when having evaluation errors. + auto m = _cfg.printEvalErrors < 0 ? RooAbsReal::CountErrors : RooAbsReal::CollectErrors; + return std::make_unique(m); +} diff --git a/roofit/roofitcore/src/RooMinimizerFcn.cxx b/roofit/roofitcore/src/RooMinimizerFcn.cxx index 8b89cf31b7f4e..8b0b98561e2ee 100644 --- a/roofit/roofitcore/src/RooMinimizerFcn.cxx +++ b/roofit/roofitcore/src/RooMinimizerFcn.cxx @@ -28,6 +28,7 @@ #include "RooMinimizer.h" #include "RooNaNPacker.h" +#include "Math/Functor.h" #include "TMatrixDSym.h" #include @@ -49,21 +50,16 @@ RooArgSet getParameters(RooAbsReal const &funct) } // namespace +// use reference wrapper for the Functor, such that the functor points to this RooMinimizerFcn by reference. RooMinimizerFcn::RooMinimizerFcn(RooAbsReal *funct, RooMinimizer *context) : RooAbsMinimizerFcn(getParameters(*funct), context), _funct(funct) { -} - -RooMinimizerFcn::RooMinimizerFcn(const RooMinimizerFcn &other) - : RooAbsMinimizerFcn(other), ROOT::Math::IBaseFunctionMultiDim(other), _funct(other._funct) -{ -} - -RooMinimizerFcn::~RooMinimizerFcn() {} - -ROOT::Math::IBaseFunctionMultiDim *RooMinimizerFcn::Clone() const -{ - return new RooMinimizerFcn(*this); + if (context->_cfg.useGradient && funct->hasGradient()) { + _multiGenFcn = std::make_unique(this, &RooMinimizerFcn::operator(), + &RooMinimizerFcn::evaluateGradient, getNDim()); + } else { + _multiGenFcn = std::make_unique(std::cref(*this), getNDim()); + } } void RooMinimizerFcn::setOptimizeConstOnFunction(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) @@ -72,9 +68,8 @@ void RooMinimizerFcn::setOptimizeConstOnFunction(RooAbsArg::ConstOpCode opcode, } /// Evaluate function given the parameters in `x`. -double RooMinimizerFcn::DoEval(const double *x) const +double RooMinimizerFcn::operator()(const double *x) const { - // Set the parameter values for this iteration for (unsigned index = 0; index < _nDim; index++) { if (_logfile) @@ -121,6 +116,26 @@ double RooMinimizerFcn::DoEval(const double *x) const return fvalue; } +void RooMinimizerFcn::evaluateGradient(const double *x, double *out) const +{ + // Set the parameter values for this iteration + for (unsigned index = 0; index < _nDim; index++) { + if (_logfile) + (*_logfile) << x[index] << " "; + SetPdfParamVal(index, x[index]); + } + + _funct->gradient(out); + + // Optional logging + if (cfg().verbose) { + std::cout << "\n gradient = "; + for (std::size_t i = 0; i < getNDim(); ++i) { + std::cout << out[i] << ", "; + } + } +} + std::string RooMinimizerFcn::getFunctionName() const { return _funct->GetName(); diff --git a/roofit/roofitcore/src/RooMinimizerFcn.h b/roofit/roofitcore/src/RooMinimizerFcn.h index 35dd2d77fe969..961eb100a1f1c 100644 --- a/roofit/roofitcore/src/RooMinimizerFcn.h +++ b/roofit/roofitcore/src/RooMinimizerFcn.h @@ -34,15 +34,10 @@ using TMatrixDSym = TMatrixTSym; // forward declaration class RooMinimizer; -class RooMinimizerFcn : public RooAbsMinimizerFcn, public ROOT::Math::IBaseFunctionMultiDim { +class RooMinimizerFcn : public RooAbsMinimizerFcn { public: RooMinimizerFcn(RooAbsReal *funct, RooMinimizer *context); - RooMinimizerFcn(const RooMinimizerFcn &other); - ~RooMinimizerFcn() override; - - ROOT::Math::IBaseFunctionMultiDim *Clone() const override; - unsigned int NDim() const override { return getNDim(); } std::string getFunctionName() const override; std::string getFunctionTitle() const override; @@ -50,13 +45,14 @@ class RooMinimizerFcn : public RooAbsMinimizerFcn, public ROOT::Math::IBaseFunct void setOptimizeConstOnFunction(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) override; void setOffsetting(bool flag) override; - bool fit(ROOT::Fit::Fitter &fitter) const override { return fitter.FitFCN(*this); }; - ROOT::Math::IMultiGenFunction *getMultiGenFcn() override { return this; }; + ROOT::Math::IMultiGenFunction *getMultiGenFcn() override { return _multiGenFcn.get(); } -private: - double DoEval(const double *x) const override; + double operator()(const double *x) const; + void evaluateGradient(const double *x, double *out) const; +private: RooAbsReal *_funct; + std::unique_ptr _multiGenFcn; }; #endif diff --git a/roofit/roofitcore/src/RooMoment.cxx b/roofit/roofitcore/src/RooMoment.cxx index 9e7539feed0d3..dd8334b4ce612 100644 --- a/roofit/roofitcore/src/RooMoment.cxx +++ b/roofit/roofitcore/src/RooMoment.cxx @@ -26,7 +26,7 @@ derivator class. #include "Riostream.h" -#include +#include #include "RooMoment.h" #include "RooAbsReal.h" @@ -70,18 +70,18 @@ RooMoment::RooMoment(const char* name, const char* title, RooAbsReal& func, RooR string pname=Form("%s_product",name) ; - RooFormulaVar* XF ; + std::unique_ptr XF; if (centr) { string formula=Form("pow((@0-@1),%d)*@2",_order) ; string m1name=Form("%s_moment1",GetName()) ; RooAbsReal* mom1 = func.mean(x) ; - XF = new RooFormulaVar(pname.c_str(),formula.c_str(),RooArgList(x,*mom1,func)) ; + XF = std::make_unique(pname.c_str(),formula.c_str(),RooArgList(x,*mom1,func)) ; XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; addOwnedComponents(*mom1) ; _mean.setArg(*mom1) ; } else { string formula=Form("pow(@0,%d)*@1",_order) ; - XF = new RooFormulaVar(pname.c_str(),formula.c_str(),RooArgSet(x,func)) ; + XF = std::make_unique(pname.c_str(),formula.c_str(),RooArgSet(x,func)) ; XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; } @@ -89,15 +89,17 @@ RooMoment::RooMoment(const char* name, const char* title, RooAbsReal& func, RooR XF->specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator"); } - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(x) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(x) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(x)}; + std::unique_ptr intF{func.createIntegral(x)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } //////////////////////////////////////////////////////////////////////////////// @@ -114,18 +116,18 @@ RooMoment::RooMoment(const char* name, const char* title, RooAbsReal& func, RooR _nset.add(nset) ; string pname=Form("%s_product",name) ; - RooFormulaVar* XF ; + std::unique_ptr XF; if (centr) { string formula=Form("pow((@0-@1),%d)*@2",_order) ; string m1name=Form("%s_moment1",GetName()) ; RooAbsReal* mom1 = func.mean(x,nset) ; - XF = new RooFormulaVar(pname.c_str(),formula.c_str(),RooArgList(x,*mom1,func)) ; + XF = std::make_unique(pname.c_str(),formula.c_str(),RooArgList(x,*mom1,func)) ; XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; addOwnedComponents(*mom1) ; _mean.setArg(*mom1) ; } else { string formula=Form("pow(@0,%d)*@1",_order) ; - XF = new RooFormulaVar(pname.c_str(),formula.c_str(),RooArgSet(x,func)) ; + XF = std::make_unique(pname.c_str(),formula.c_str(),RooArgSet(x,func)) ; XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; } @@ -136,15 +138,17 @@ RooMoment::RooMoment(const char* name, const char* title, RooAbsReal& func, RooR RooArgSet intSet(x) ; if (intNSet) intSet.add(_nset,true) ; - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(intSet,&_nset) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(intSet,&_nset) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(intSet, &_nset)}; + std::unique_ptr intF{func.createIntegral(intSet, &_nset)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } diff --git a/roofit/roofitcore/src/RooMsgService.cxx b/roofit/roofitcore/src/RooMsgService.cxx index 9044503320423..d75d3b4dd4d76 100644 --- a/roofit/roofitcore/src/RooMsgService.cxx +++ b/roofit/roofitcore/src/RooMsgService.cxx @@ -79,7 +79,7 @@ Int_t RooMsgService::_debugCount = 0; RooMsgService::RooMsgService() { - _devnull = new ofstream("/dev/null") ; + _devnull = std::make_unique("/dev/null") ; _levelNames[DEBUG]="DEBUG" ; _levelNames[INFO]="INFO" ; @@ -116,13 +116,9 @@ void RooMsgService::reset() { _globMinLevel = DEBUG ; _lastMsgLevel = DEBUG ; - delete _debugWorkspace; _debugWorkspace = nullptr; _debugCode = 0 ; - for (auto &item : _files) { - delete item.second; - } _files.clear(); // Old-style streams @@ -133,24 +129,7 @@ void RooMsgService::reset() { } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooMsgService::~RooMsgService() -{ - // Delete all ostreams we own ; - map::iterator iter = _files.begin() ; - for (; iter != _files.end() ; ++iter) { - delete iter->second ; - } - - if (_debugWorkspace) { - delete _debugWorkspace ; - } - - delete _devnull ; -} - +RooMsgService::~RooMsgService() = default; //////////////////////////////////////////////////////////////////////////////// @@ -168,9 +147,9 @@ bool RooMsgService::anyDebug() RooWorkspace* RooMsgService::debugWorkspace() { if (!_debugWorkspace) { - _debugWorkspace = new RooWorkspace("wdebug") ; + _debugWorkspace = std::make_unique("wdebug") ; } - return _debugWorkspace ; + return _debugWorkspace.get(); } @@ -188,7 +167,7 @@ RooWorkspace* RooMsgService::debugWorkspace() ///
    ObjectName(const char*) Restrict stream to messages from object with given name ///
    ClassName(const char*) Restrict stream to messages from objects with given class name ///
    BaseClassName(const char*) Restrict stream to messages from objects with given base class name -///
    LabelName(const chat*) Restrict stream to messages from objects setAtrribute(const char*) tag with given name +///
    LabelName(const chat*) Restrict stream to messages from objects setAttribute(const char*) tag with given name ///
    Output redirection options ///
    OutputFile(const char*) Send output to file with given name. Multiple streams can write to same file. ///
    OutputStream(ostream&) Send output to given C++ stream. Multiple message streams can write to same c++ stream @@ -206,7 +185,7 @@ Int_t RooMsgService::addStream(RooFit::MsgLevel level, const RooCmdArg& arg1, co l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ; // Define configuration for this method - RooCmdConfig pc(Form("RooMsgService::addReportingStream(%s)",GetName())) ; + RooCmdConfig pc("RooMsgService::addReportingStream(" + std::string(GetName()) + ")") ; pc.defineInt("prefix","Prefix",0,true) ; pc.defineInt("color","Color",0,static_cast(kBlack)) ; pc.defineInt("topic","Topic",0,0xFFFFF) ; @@ -215,7 +194,7 @@ Int_t RooMsgService::addStream(RooFit::MsgLevel level, const RooCmdArg& arg1, co pc.defineString("baseClassName","BaseClassName",0,"") ; pc.defineString("tagName","LabelName",0,"") ; pc.defineString("outFile","OutputFile",0,"") ; - pc.defineObject("outStream","OutputStream",0,0) ; + pc.defineObject("outStream","OutputStream",0,nullptr) ; pc.defineMutex("OutputFile","OutputStream") ; // Process & check varargs @@ -254,7 +233,7 @@ Int_t RooMsgService::addStream(RooFit::MsgLevel level, const RooCmdArg& arg1, co newStream.tagName = (tagName ? tagName : "" ) ; newStream.color = color ; newStream.prefix = prefix ; - newStream.universal = (newStream.objectName=="" && newStream.className=="" && newStream.baseClassName=="" && newStream.tagName=="") ; + newStream.universal = (newStream.objectName.empty() && newStream.className.empty() && newStream.baseClassName.empty() && newStream.tagName.empty()) ; // Update debug stream count if (level==DEBUG) { @@ -267,10 +246,10 @@ Int_t RooMsgService::addStream(RooFit::MsgLevel level, const RooCmdArg& arg1, co // To given non-owned stream newStream.os = os ; - } else if (string(outFile).size()>0) { + } else if (!string(outFile).empty()) { // See if we already opened the file - ostream* os2 = _files["outFile"] ; + ostream* os2 = _files["outFile"].get(); if (!os2) { @@ -286,8 +265,8 @@ Int_t RooMsgService::addStream(RooFit::MsgLevel level, const RooCmdArg& arg1, co } } else { - _files["outFile"] = os2 ; newStream.os = os2 ; + _files["outFile"] = std::unique_ptr{os2}; } @@ -452,10 +431,10 @@ bool RooMsgService::StreamConfig::match(RooFit::MsgLevel level, RooFit::MsgTopic if (universal) return true ; if (!obj) return false; - if (objectName.size()>0 && objectName != obj->GetName()) return false ; - if (className.size()>0 && className != obj->ClassName()) return false ; - if (baseClassName.size()>0 && !obj->IsA()->InheritsFrom(baseClassName.c_str())) return false ; - if (tagName.size()>0 && !obj->getAttribute(tagName.c_str())) return false ; + if (!objectName.empty() && objectName != obj->GetName()) return false ; + if (!className.empty() && className != obj->ClassName()) return false ; + if (!baseClassName.empty() && !obj->IsA()->InheritsFrom(baseClassName.c_str())) return false ; + if (!tagName.empty() && !obj->getAttribute(tagName.c_str())) return false ; return true ; } @@ -473,9 +452,9 @@ bool RooMsgService::StreamConfig::match(RooFit::MsgLevel level, RooFit::MsgTopic if (universal) return true ; if (!obj) return false; - if (objectName.size()>0 && objectName != obj->GetName()) return false ; - if (className.size()>0 && className != obj->ClassName()) return false ; - if (baseClassName.size()>0 && !obj->IsA()->InheritsFrom(baseClassName.c_str())) return false ; + if (!objectName.empty() && objectName != obj->GetName()) return false ; + if (!className.empty() && className != obj->ClassName()) return false ; + if (!baseClassName.empty() && !obj->IsA()->InheritsFrom(baseClassName.c_str())) return false ; return true ; } @@ -586,16 +565,16 @@ void RooMsgService::Print(Option_t *options) const } - if (_streams[i].objectName.size()>0) { + if (!_streams[i].objectName.empty()) { cout << " ObjectName = " << _streams[i].objectName ; } - if (_streams[i].className.size()>0) { + if (!_streams[i].className.empty()) { cout << " ClassName = " << _streams[i].className ; } - if (_streams[i].baseClassName.size()>0) { + if (!_streams[i].baseClassName.empty()) { cout << " BaseClassName = " << _streams[i].baseClassName ; } - if (_streams[i].tagName.size()>0) { + if (!_streams[i].tagName.empty()) { cout << " TagLabel = " << _streams[i].tagName ; } diff --git a/roofit/roofitcore/src/RooMultiGenFunction.cxx b/roofit/roofitcore/src/RooMultiGenFunction.cxx deleted file mode 100644 index 69ceb1ee6965a..0000000000000 --- a/roofit/roofitcore/src/RooMultiGenFunction.cxx +++ /dev/null @@ -1,92 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - - -/** -\file RooMultiGenFunction.cxx -\class RooMultiGenFunction -\ingroup Roofitcore - -Lightweight interface adaptor that exports a RooAbsReal as a ROOT::Math::IMultiGenFunction -**/ - -#include "Riostream.h" - -#include "RooMultiGenFunction.h" -#include "RooRealBinding.h" -#include "RooAbsReal.h" -#include "RooAbsPdf.h" -#include "RooArgSet.h" - -#include - - - -using namespace std; - -ClassImp(RooMultiGenFunction); -; - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction::RooMultiGenFunction(const RooAbsFunc& func) : - _ftor(func) -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction::RooMultiGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters) : - _ftor(func,observables,parameters) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction::RooMultiGenFunction(const RooAbsReal& func, const RooArgList& observables, const RooArgList& parameters, const RooArgSet& nset) : - _ftor(func,observables,parameters,nset) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction::RooMultiGenFunction(const RooMultiGenFunction& other) : - ROOT::Math::IMultiGenFunction(other), _ftor(other._ftor) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -RooMultiGenFunction::~RooMultiGenFunction() -{ -} - - -//////////////////////////////////////////////////////////////////////////////// - -double RooMultiGenFunction::DoEval(const double* x) const -{ - return _ftor(x) ; -} - - - diff --git a/roofit/roofitcore/src/RooMultiVarGaussian.cxx b/roofit/roofitcore/src/RooMultiVarGaussian.cxx index b56a07fec755e..02b026eb4e40e 100644 --- a/roofit/roofitcore/src/RooMultiVarGaussian.cxx +++ b/roofit/roofitcore/src/RooMultiVarGaussian.cxx @@ -23,7 +23,7 @@ Multivariate Gaussian p.d.f. with correlations **/ #include "Riostream.h" -#include +#include #include "RooMultiVarGaussian.h" #include "RooAbsReal.h" @@ -38,19 +38,29 @@ Multivariate Gaussian p.d.f. with correlations using namespace std; ClassImp(RooMultiVarGaussian); - ; //////////////////////////////////////////////////////////////////////////////// RooMultiVarGaussian::RooMultiVarGaussian(const char *name, const char *title, - const RooArgList& xvec, const RooArgList& mu, const TMatrixDSym& cov) : + const RooArgList& xvec, const RooArgList& mu, const TMatrixDBase& cov) : RooAbsPdf(name,title), _x("x","Observables",this,true,false), _mu("mu","Offset vector",this,true,false), - _cov(cov), - _covI(cov), + _cov{cov.GetNrows()}, + _covI{cov.GetNrows()}, _z(4) { + if(!cov.IsSymmetric()) { + std::stringstream errorMsg; + errorMsg << "RooMultiVarGaussian::RooMultiVarGaussian(" << GetName() + << ") input covariance matrix is not symmetric!"; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::invalid_argument(errorMsg.str().c_str()); + } + + _cov.SetSub(0, cov); + _covI.SetSub(0, cov); + _x.add(xvec) ; _mu.add(mu) ; @@ -80,9 +90,9 @@ RooMultiVarGaussian::RooMultiVarGaussian(const char *name, const char *title, const RooArgList& fpf = fr.floatParsFinal() ; for (Int_t i=0 ; iGetName())) { - RooRealVar* parclone = (RooRealVar*) fpf.at(i)->Clone(Form("%s_centralvalue",fpf.at(i)->GetName())) ; + std::unique_ptr parclone{static_cast(fpf.at(i)->Clone(Form("%s_centralvalue",fpf.at(i)->GetName())))}; parclone->setConstant(true) ; - _mu.addOwned(*parclone) ; + _mu.addOwned(std::move(parclone)); munames.push_back(fpf.at(i)->GetName()) ; } } @@ -98,55 +108,46 @@ RooMultiVarGaussian::RooMultiVarGaussian(const char *name, const char *title, } +namespace { -//////////////////////////////////////////////////////////////////////////////// - -RooMultiVarGaussian::RooMultiVarGaussian(const char *name, const char *title, - const RooArgList& xvec, const TVectorD& mu, const TMatrixDSym& cov) : - RooAbsPdf(name,title), - _x("x","Observables",this,true,false), - _mu("mu","Offset vector",this,true,false), - _cov(cov), - _covI(cov), - _z(4) +RooArgList muFromVector(TVectorD const &mu) { - _x.add(xvec) ; + RooArgList out; + for (int i = 0; i < mu.GetNrows(); i++) { + out.add(RooFit::RooConst(mu(i))); + } + return out; +} - for (Int_t i=0 ; i& omap = gd.omap ; - while(1) { + while(true) { // Create unit Gaussian vector TVectorD xgen(nobs); @@ -654,16 +655,15 @@ bool RooMultiVarGaussian::BitBlock::getBit(Int_t ibit) return false ; } -bool RooMultiVarGaussian::BitBlock::operator==(const BitBlock& other) +bool operator==(RooMultiVarGaussian::BitBlock const &lhs, RooMultiVarGaussian::BitBlock const &rhs) { - if (b0 != other.b0) return false ; - if (b1 != other.b1) return false ; - if (b2 != other.b2) return false ; - if (b3 != other.b3) return false ; - return true ; + if (lhs.b0 != rhs.b0) + return false; + if (lhs.b1 != rhs.b1) + return false; + if (lhs.b2 != rhs.b2) + return false; + if (lhs.b3 != rhs.b3) + return false; + return true; } - - - - - diff --git a/roofit/roofitcore/src/RooNLLVar.cxx b/roofit/roofitcore/src/RooNLLVar.cxx index dc31ad1a25384..f377a1b43c704 100644 --- a/roofit/roofitcore/src/RooNLLVar.cxx +++ b/roofit/roofitcore/src/RooNLLVar.cxx @@ -28,20 +28,20 @@ In extended mode, a \f$ N_\mathrm{expect} - N_\mathrm{observed}*log(N_\mathrm{expect}) \f$ term is added. **/ -#include "RooNLLVar.h" - -#include "RooAbsData.h" -#include "RooAbsPdf.h" -#include "RooCmdConfig.h" -#include "RooMsgService.h" -#include "RooAbsDataStore.h" -#include "RooRealMPFE.h" -#include "RooRealSumPdf.h" -#include "RooRealVar.h" -#include "RooProdPdf.h" -#include "RooNaNPacker.h" -#include "RunContext.h" -#include "RooDataHist.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef ROOFIT_CHECK_CACHED_VALUES #include @@ -70,7 +70,6 @@ namespace { ClassImp(RooNLLVar) -RooNLLVar::RooNLLVar() {} RooNLLVar::~RooNLLVar() {} RooArgSet RooNLLVar::_emptySet ; @@ -110,7 +109,7 @@ RooNLLVar::RooNLLVar(const char *name, const char* title, RooAbsPdf& pdf, RooAbs pc.process(arg7) ; pc.process(arg8) ; pc.process(arg9) ; _extended = pc.getInt("extended") ; - _batchEvaluations = pc.getInt("BatchMode"); + _skipZeroWeights = true; } @@ -160,6 +159,10 @@ RooNLLVar::RooNLLVar(const char *name, const char *title, RooAbsPdf& pdf, RooAbs ++biter ; } } + + _skipZeroWeights = false; + } else { + _skipZeroWeights = true; } } @@ -171,7 +174,6 @@ RooNLLVar::RooNLLVar(const char *name, const char *title, RooAbsPdf& pdf, RooAbs RooNLLVar::RooNLLVar(const RooNLLVar& other, const char* name) : RooAbsOptTestStatistic(other,name), _extended(other._extended), - _batchEvaluations(other._batchEvaluations), _weightSq(other._weightSq), _offsetSaveW2(other._offsetSaveW2), _binw(other._binw), @@ -190,7 +192,6 @@ RooAbsTestStatistic* RooNLLVar::create(const char *name, const char *title, RooA bool extendedPdf = _extended && thePdf.canBeExtended(); auto testStat = new RooNLLVar(name, title, thePdf, adata, projDeps, extendedPdf, cfg); - testStat->batchMode(_batchEvaluations); return testStat; } @@ -236,11 +237,6 @@ double RooNLLVar::evaluatePartition(std::size_t firstEvent, std::size_t lastEven auto * pdfClone = static_cast(_funcClone); - // cout << "RooNLLVar::evaluatePartition(" << GetName() << ") projDeps = " << (_projDeps?*_projDeps:RooArgSet()) << endl ; - - _dataClone->store()->recalculateCache( _projDeps, firstEvent, lastEvent, stepSize, (_binnedPdf?false:true) ) ; - - // If pdf is marked as binned - do a binned likelihood calculation here (sum of log-Poisson for each bin) if (_binnedPdf) { @@ -279,39 +275,11 @@ double RooNLLVar::evaluatePartition(std::size_t firstEvent, std::size_t lastEven } else { //unbinned PDF - if (_batchEvaluations) { - std::tie(result, sumWeight) = computeBatched(stepSize, firstEvent, lastEvent); -#ifdef ROOFIT_CHECK_CACHED_VALUES - - ROOT::Math::KahanSum resultScalar, sumWeightScalar; - std::tie(resultScalar, sumWeightScalar) = computeScalar(stepSize, firstEvent, lastEvent); - double carryScalar = resultScalar.Carry(); - - constexpr bool alwaysPrint = false; - - if (alwaysPrint || std::abs(result - resultScalar)/resultScalar > 5.E-15) { - std::cerr << "RooNLLVar: result is off\n\t" << std::setprecision(15) << result - << "\n\t" << resultScalar << std::endl; - } - - if (alwaysPrint || std::abs(carry - carryScalar)/carryScalar > 500.) { - std::cerr << "RooNLLVar: carry is far off\n\t" << std::setprecision(15) << carry - << "\n\t" << carryScalar << std::endl; - } - - if (alwaysPrint || std::abs(sumWeight - sumWeightScalar)/sumWeightScalar > 1.E-15) { - std::cerr << "RooNLLVar: sumWeight is off\n\t" << std::setprecision(15) << sumWeight - << "\n\t" << sumWeightScalar << std::endl; - } - -#endif - } else { //scalar mode - std::tie(result, sumWeight) = computeScalar(stepSize, firstEvent, lastEvent); - } + std::tie(result, sumWeight) = computeScalar(stepSize, firstEvent, lastEvent); // include the extended maximum likelihood term, if requested if(_extended && _setNum==_extSet) { - result += pdfClone->extendedTerm(*_dataClone, _weightSq); + result += pdfClone->extendedTerm(*_dataClone, _weightSq, _doBinOffset); } } //unbinned PDF @@ -334,8 +302,8 @@ double RooNLLVar::evaluatePartition(std::size_t firstEvent, std::size_t lastEven if (_doOffset) { // If no offset is stored enable this feature now - if (_offset==0 && result !=0 ) { - coutI(Minimization) << "RooNLLVar::evaluatePartition(" << GetName() << ") first = "<< firstEvent << " last = " << lastEvent << " Likelihood offset now set to " << result << std::endl ; + if (_offset.Sum() == 0 && _offset.Carry() == 0 && (result.Sum() != 0 || result.Carry() != 0)) { + coutI(Minimization) << "RooNLLVar::evaluatePartition(" << GetName() << ") first = "<< firstEvent << " last = " << lastEvent << " Likelihood offset now set to " << result.Sum() << std::endl ; _offset = result ; } @@ -347,153 +315,32 @@ double RooNLLVar::evaluatePartition(std::size_t firstEvent, std::size_t lastEven return result.Sum() ; } - -//////////////////////////////////////////////////////////////////////////////// -/// Compute probabilites of all data events. Use faster batch interface. -/// \param[in] stepSize Stride when moving through the dataset. -/// \note For batch computations, the step size **must** be one. -/// \param[in] firstEvent First event to be processed. -/// \param[in] lastEvent First event not to be processed. -/// \return Tuple with (Kahan sum of probabilities, carry of kahan sum, sum of weights) -RooNLLVar::ComputeResult RooNLLVar::computeBatched(std::size_t stepSize, std::size_t firstEvent, std::size_t lastEvent) const -{ - auto pdfClone = static_cast(_funcClone); - return computeBatchedFunc(pdfClone, _dataClone, _evalData, _normSet, _weightSq, stepSize, firstEvent, lastEvent); -} - -// static function, also used from TestStatistics::RooUnbinnedL -RooNLLVar::ComputeResult RooNLLVar::computeBatchedFunc(const RooAbsPdf *pdfClone, RooAbsData *dataClone, - std::unique_ptr &evalData, - RooArgSet *normSet, bool weightSq, std::size_t stepSize, - std::size_t firstEvent, std::size_t lastEvent) -{ - const auto nEvents = lastEvent - firstEvent; - - if (stepSize != 1) { - throw std::invalid_argument(std::string("Error in ") + __FILE__ + ": Step size for batch computations can only be 1."); - } - - // Create a RunContext that will own the memory where computation results are stored. - // Holding on to this struct in between function calls will make sure that the memory - // is only allocated once. - if (!evalData) { - evalData.reset(new RooBatchCompute::RunContext); - } - evalData->clear(); - evalData->spans = dataClone->getBatches(firstEvent, nEvents); - - auto results = pdfClone->getLogProbabilities(*evalData, normSet); - -#ifdef ROOFIT_CHECK_CACHED_VALUES - - for (std::size_t evtNo = firstEvent; evtNo < std::min(lastEvent, firstEvent + 10); ++evtNo) { - dataClone->get(evtNo); - if (dataClone->weight() == 0.) // 0-weight events are not cached, so cannot compare against them. - continue; - - try { - // Cross check results with strict tolerance and complain - BatchInterfaceAccessor::checkBatchComputation(*pdfClone, *evalData, evtNo-firstEvent, normSet, 1.E-13); - } catch (std::exception& e) { - std::cerr << __FILE__ << ":" << __LINE__ << " ERROR when checking batch computation for event " << evtNo << ":\n" - << e.what() << std::endl; - - // It becomes a real problem if it's very wrong. We fail in this case: - try { - BatchInterfaceAccessor::checkBatchComputation(*pdfClone, *evalData, evtNo-firstEvent, normSet, 1.E-9); - } catch (std::exception& e2) { - assert(false); - } - } - } - -#endif - - - // Compute sum of event weights. First check if we need squared weights - const RooSpan eventWeights = dataClone->getWeightBatch(firstEvent, nEvents, weightSq); - - //Sum the event weights and probabilities - ROOT::Math::KahanSum kahanProb; - double uniformSingleEventWeight{0.0}; - double sumOfWeights; - if (eventWeights.empty()) { - uniformSingleEventWeight = weightSq ? dataClone->weightSquared() : dataClone->weight(); - sumOfWeights = nEvents * uniformSingleEventWeight; - for (std::size_t i = 0; i < results.size(); ++i) { //CHECK_VECTORISE - kahanProb.AddIndexed(-uniformSingleEventWeight * results[i], i); - } - } else { - assert(results.size() == eventWeights.size()); - ROOT::Math::KahanSum kahanWeight; - for (std::size_t i = 0; i < results.size(); ++i) { //CHECK_VECTORISE - const double weight = eventWeights[i]; - kahanProb.AddIndexed(-weight * results[i], i); - kahanWeight.AddIndexed(weight, i); - } - sumOfWeights = kahanWeight.Sum(); - } - - if (std::isnan(kahanProb.Sum())) { - // Special handling of evaluation errors. - // We can recover if the bin/event that results in NaN has a weight of zero: - ROOT::Math::KahanSum kahanSanitised; - RooNaNPacker nanPacker; - for (std::size_t i = 0; i < results.size(); ++i) { - double weight = eventWeights.empty() ? uniformSingleEventWeight : eventWeights[i]; - - if (weight == 0.) - continue; - - if (std::isnan(results[i])) { - nanPacker.accumulate(results[i]); - } else { - kahanSanitised += -weight * results[i]; - } - } - - // Some events with evaluation errors. Return "badness" of errors. - if (nanPacker.getPayload() > 0.) { - return {{nanPacker.getNaNWithPayload()}, sumOfWeights}; - } else { - return {kahanSanitised, sumOfWeights}; - } - } - - return {kahanProb, sumOfWeights}; -} - - RooNLLVar::ComputeResult RooNLLVar::computeScalar(std::size_t stepSize, std::size_t firstEvent, std::size_t lastEvent) const { auto pdfClone = static_cast(_funcClone); - return computeScalarFunc(pdfClone, _dataClone, _normSet, _weightSq, stepSize, firstEvent, lastEvent, _templateRatioOffset); + return computeScalarFunc(pdfClone, _dataClone, _normSet, _weightSq, stepSize, firstEvent, lastEvent, _offsetPdf.get()); } // static function, also used from TestStatistics::RooUnbinnedL RooNLLVar::ComputeResult RooNLLVar::computeScalarFunc(const RooAbsPdf *pdfClone, RooAbsData *dataClone, RooArgSet *normSet, bool weightSq, std::size_t stepSize, - std::size_t firstEvent, std::size_t lastEvent, bool templateRatioOffset) + std::size_t firstEvent, std::size_t lastEvent, RooAbsPdf const* offsetPdf) { ROOT::Math::KahanSum kahanWeight; ROOT::Math::KahanSum kahanProb; RooNaNPacker packedNaN(0.f); - const double logSumW = std::log(dataClone->sumEntries()); - - auto* dataHist = templateRatioOffset ? dynamic_cast(dataClone) : nullptr; for (auto i=firstEvent; iget(i) ; double weight = dataClone->weight(); //FIXME - const double ni = weight; if (0. == weight * weight) continue ; if (weightSq) weight = dataClone->weightSquared() ; double logProba = pdfClone->getLogVal(normSet); - if(templateRatioOffset && dataHist) { - logProba -= std::log(ni) - std::log(dataHist->binVolume(i)) - logSumW; + if(offsetPdf) { + logProba -= offsetPdf->getLogVal(normSet); } const double term = -weight * logProba; @@ -505,8 +352,33 @@ RooNLLVar::ComputeResult RooNLLVar::computeScalarFunc(const RooAbsPdf *pdfClone, if (packedNaN.getPayload() != 0.) { // Some events with evaluation errors. Return "badness" of errors. - return {{packedNaN.getNaNWithPayload()}, kahanWeight.Sum()}; + return {ROOT::Math::KahanSum{packedNaN.getNaNWithPayload()}, kahanWeight.Sum()}; } return {kahanProb, kahanWeight.Sum()}; } + +bool RooNLLVar::setData(RooAbsData &data, bool cloneData) +{ + bool ret = RooAbsOptTestStatistic::setData(data, cloneData); + // To re-create the data template pdf if necessary + _offsetPdf.reset(); + enableBinOffsetting(_doBinOffset); + return ret; +} + +void RooNLLVar::enableBinOffsetting(bool on) +{ + if (on && !_offsetPdf) { + std::string name = std::string{GetName()} + "_offsetPdf"; + std::unique_ptr dataTemplate; + if (auto dh = dynamic_cast(_dataClone)) { + dataTemplate = std::make_unique(*dh); + } else { + dataTemplate = std::unique_ptr(static_cast(*_dataClone).binnedClone()); + } + _offsetPdf = std::make_unique(name.c_str(), name.c_str(), *_funcObsSet, std::move(dataTemplate)); + _offsetPdf->setOperMode(ADirty); + } + _doBinOffset = on; +} diff --git a/roofit/roofitcore/src/RooNLLVarNew.cxx b/roofit/roofitcore/src/RooNLLVarNew.cxx index 1c1d452f78ade..2052d22f63040 100644 --- a/roofit/roofitcore/src/RooNLLVarNew.cxx +++ b/roofit/roofitcore/src/RooNLLVarNew.cxx @@ -17,17 +17,19 @@ \ingroup Roofitcore This is a simple class designed to produce the nll values needed by the fitter. -In contrast to the `RooNLLVar` class, any logic except the bare minimum has been -transfered away to other classes, like the `RooFitDriver`. This class also calls -functions from `RooBatchCompute` library to provide faster computation times. +This class calls functions from `RooBatchCompute` library to provide faster +computation times. **/ #include "RooNLLVarNew.h" -#include -#include +#include +#include +#include #include +#include #include +#include #include "RooFit/Detail/Buffers.h" #include @@ -35,26 +37,17 @@ functions from `RooBatchCompute` library to provide faster computation times. #include #include #include -#include #include #include #include -using namespace ROOT::Experimental; - // Declare constexpr static members to make them available if odr-used in C++14. constexpr const char *RooNLLVarNew::weightVarName; constexpr const char *RooNLLVarNew::weightVarNameSumW2; namespace { -template -double kahanSum(Input const &input) -{ - return ROOT::Math::KahanSum::Accumulate(input.begin(), input.end()).Sum(); -} - RooArgSet getObs(RooAbsArg const &arg, RooArgSet const &observables) { RooArgSet out; @@ -62,6 +55,66 @@ RooArgSet getObs(RooAbsArg const &arg, RooArgSet const &observables) return out; } +// Use RooConstVar for dummies such that they don't get included in getParameters(). +RooConstVar *dummyVar(const char *name) +{ + return new RooConstVar(name, name, 1.0); +} + +// Helper class to represent a template pdf based on the fit dataset. +class RooOffsetPdf : public RooAbsPdf { +public: + RooOffsetPdf(const char *name, const char *title, RooArgSet const &observables, RooAbsReal &weightVar) + : RooAbsPdf(name, title), + _observables("!observables", "List of observables", this), + _weightVar{"!weightVar", "weightVar", this, weightVar, true, false} + { + for (RooAbsArg *obs : observables) { + _observables.add(*obs); + } + } + RooOffsetPdf(const RooOffsetPdf &other, const char *name = nullptr) + : RooAbsPdf(other, name), + _observables("!servers", this, other._observables), + _weightVar{"!weightVar", this, other._weightVar} + { + } + TObject *clone(const char *newname) const override { return new RooOffsetPdf(*this, newname); } + + void computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const override + { + std::span weights = dataMap.at(_weightVar); + + // Create the template histogram from the data. This operation is very + // expensive, but since the offset only depends on the observables it + // only has to be done once. + + RooDataHist dataHist{"data", "data", _observables}; + // Loop over events to fill the histogram + for (std::size_t i = 0; i < nEvents; ++i) { + for (auto *var : static_range_cast(_observables)) { + var->setVal(dataMap.at(var)[i]); + } + dataHist.add(_observables, weights[weights.size() == 1 ? 0 : i]); + } + + // Lookup bin weights via RooHistPdf + RooHistPdf pdf{"offsetPdf", "offsetPdf", _observables, dataHist}; + for (std::size_t i = 0; i < nEvents; ++i) { + for (auto *var : static_range_cast(_observables)) { + var->setVal(dataMap.at(var)[i]); + } + output[i] = pdf.getVal(_observables); + } + } + +private: + double evaluate() const override { return 0.0; } // should never be called + + RooSetProxy _observables; + RooTemplateProxy _weightVar; +}; + } // namespace /** Construct a RooNLLVarNew @@ -72,192 +125,197 @@ RooArgSet getObs(RooAbsArg const &arg, RooArgSet const &observables) \param isExtended Set to true if this is an extended fit **/ RooNLLVarNew::RooNLLVarNew(const char *name, const char *title, RooAbsPdf &pdf, RooArgSet const &observables, - bool isExtended, RooFit::OffsetMode offsetMode, bool binnedL) - : RooAbsReal(name, title), _pdf{"pdf", "pdf", this, pdf}, _observables{getObs(pdf, observables)}, - _isExtended{isExtended}, _binnedL{binnedL}, - _weightVar{"weightVar", "weightVar", this, *new RooRealVar(weightVarName, weightVarName, 1.0), true, false, true}, - _weightSquaredVar{weightVarNameSumW2, - weightVarNameSumW2, - this, - *new RooRealVar("weightSquardVar", "weightSquaredVar", 1.0), - true, - false, - true} + bool isExtended, RooFit::OffsetMode offsetMode) + : RooAbsReal(name, title), + _pdf{"pdf", "pdf", this, pdf}, + _weightVar{"weightVar", "weightVar", this, *dummyVar(weightVarName), true, false, true}, + _weightSquaredVar{weightVarNameSumW2, weightVarNameSumW2, this, *dummyVar("weightSquardVar"), true, false, true}, + _binnedL{pdf.getAttribute("BinnedLikelihoodActive")} { - if (_binnedL) { - if (_observables.size() != 1) { - throw std::runtime_error("BinnedPdf optimization only works with a 1D pdf."); - } else { - auto *var = static_cast(_observables.first()); - std::list *boundaries = pdf.binBoundaries(*var, var->getMin(), var->getMax()); - std::list::iterator biter = boundaries->begin(); - _binw.resize(boundaries->size() - 1); - double lastBound = (*biter); - ++biter; - int ibin = 0; - while (biter != boundaries->end()) { - _binw[ibin] = (*biter) - lastBound; - lastBound = (*biter); - ibin++; - ++biter; - } + RooArgSet obs{getObs(pdf, observables)}; + + // In the "BinnedLikelihoodActiveYields" mode, the pdf values can directly + // be interpreted as yields and don't need to be multiplied by the bin + // widths. That's why we don't need to even fill them in this case. + if (_binnedL && !pdf.getAttribute("BinnedLikelihoodActiveYields")) { + fillBinWidthsFromPdfBoundaries(pdf, obs); + } + + if (isExtended && !_binnedL) { + std::unique_ptr expectedEvents = pdf.createExpectedEventsFunc(&obs); + if (expectedEvents) { + _expectedEvents = + std::make_unique>("expectedEvents", "expectedEvents", this, *expectedEvents); + addOwnedComponents(std::move(expectedEvents)); } } resetWeightVarNames(); enableOffsetting(offsetMode == RooFit::OffsetMode::Initial); - // TODO: implement template offsetting mode as well + enableBinOffsetting(offsetMode == RooFit::OffsetMode::Bin); + + if (_doBinOffset) { + auto offsetPdf = std::make_unique("_offset_pdf", "_offset_pdf", observables, *_weightVar); + _offsetPdf = std::make_unique>("offsetPdf", "offsetPdf", this, *offsetPdf); + addOwnedComponents(std::move(offsetPdf)); + } } RooNLLVarNew::RooNLLVarNew(const RooNLLVarNew &other, const char *name) - : RooAbsReal(other, name), _pdf{"pdf", this, other._pdf}, _observables{other._observables}, - _isExtended{other._isExtended}, _weightSquared{other._weightSquared}, _binnedL{other._binnedL}, - _doOffset{other._doOffset}, _simCount{other._simCount}, _prefix{other._prefix}, - _weightVar{"weightVar", this, other._weightVar}, _weightSquaredVar{"weightSquaredVar", this, - other._weightSquaredVar} + : RooAbsReal(other, name), + _pdf{"pdf", this, other._pdf}, + _weightVar{"weightVar", this, other._weightVar}, + _weightSquaredVar{"weightSquaredVar", this, other._weightSquaredVar}, + _weightSquared{other._weightSquared}, + _binnedL{other._binnedL}, + _doOffset{other._doOffset}, + _simCount{other._simCount}, + _prefix{other._prefix}, + _binw{other._binw} { + if (other._expectedEvents) { + _expectedEvents = std::make_unique>("expectedEvents", this, *other._expectedEvents); + } } -/** Compute multiple negative logs of propabilities - -\param output An array of doubles where the computation results will be stored -\param nOut not used -\note nEvents is the number of events to be processed (the dataMap size) -\param dataMap A map containing spans with the input data for the computation -**/ -void RooNLLVarNew::computeBatch(cudaStream_t * /*stream*/, double *output, size_t /*nOut*/, - RooFit::Detail::DataMap const &dataMap) const +void RooNLLVarNew::fillBinWidthsFromPdfBoundaries(RooAbsReal const &pdf, RooArgSet const &observables) { - std::size_t nEvents = dataMap.at(_pdf).size(); - - auto weights = dataMap.at(_weightVar); - auto weightsSumW2 = dataMap.at(_weightSquaredVar); - auto weightSpan = _weightSquared ? weightsSumW2 : weights; + // Check if the bin widths were already filled + if (!_binw.empty()) { + return; + } - if (_binnedL) { - ROOT::Math::KahanSum result{0.0}; - ROOT::Math::KahanSum sumWeightKahanSum{0.0}; - auto preds = dataMap.at(&*_pdf); + if (observables.size() != 1) { + throw std::runtime_error("BinnedPdf optimization only works with a 1D pdf."); + } else { + auto *var = static_cast(observables.first()); + std::list *boundaries = pdf.binBoundaries(*var, var->getMin(), var->getMax()); + std::list::iterator biter = boundaries->begin(); + _binw.resize(boundaries->size() - 1); + double lastBound = (*biter); + ++biter; + int ibin = 0; + while (biter != boundaries->end()) { + _binw[ibin] = (*biter) - lastBound; + lastBound = (*biter); + ibin++; + ++biter; + } + } +} - for (std::size_t i = 0; i < nEvents; ++i) { +double RooNLLVarNew::computeBatchBinnedL(std::span preds, std::span weights) const +{ + ROOT::Math::KahanSum result{0.0}; + ROOT::Math::KahanSum sumWeightKahanSum{0.0}; - double eventWeight = weightSpan[i]; + const bool predsAreYields = _binw.empty(); - // Calculate log(Poisson(N|mu) for this bin - double N = eventWeight; - double mu = preds[i] * _binw[i]; + for (std::size_t i = 0; i < preds.size(); ++i) { - if (mu <= 0 && N > 0) { + double eventWeight = weights[i]; - // Catch error condition: data present where zero events are predicted - logEvalError(Form("Observed %f events in bin %lu with zero event yield", N, (unsigned long)i)); + // Calculate log(Poisson(N|mu) for this bin + double N = eventWeight; + double mu = preds[i]; + if (!predsAreYields) { + mu *= _binw[i]; + } - } else if (std::abs(mu) < 1e-10 && std::abs(N) < 1e-10) { + if (mu <= 0 && N > 0) { - // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula - // since log(mu)=0. No update of result is required since term=0. + // Catch error condition: data present where zero events are predicted + logEvalError(Form("Observed %f events in bin %lu with zero event yield", N, (unsigned long)i)); - } else { + } else if (std::abs(mu) < 1e-10 && std::abs(N) < 1e-10) { - result += -1 * (-mu + N * log(mu) - TMath::LnGamma(N + 1)); - sumWeightKahanSum += eventWeight; - } - } + // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula + // since log(mu)=0. No update of result is required since term=0. - output[0] = finalizeResult(std::move(result), sumWeightKahanSum.Sum()); + } else { - return; + result += -1 * (-mu + N * log(mu) - TMath::LnGamma(N + 1)); + sumWeightKahanSum += eventWeight; + } } - auto probas = dataMap.at(_pdf); + return finalizeResult(result, sumWeightKahanSum.Sum()); +} - _logProbasBuffer.resize(nEvents); - (*_pdf).getLogProbabilities(probas, _logProbasBuffer.data()); +/** Compute multiple negative logs of probabilities. - _sumWeight = weights.size() == 1 ? weights[0] * nEvents : kahanSum(weights); +\param output An array of doubles where the computation results will be stored +\param nOut not used +\note nEvents is the number of events to be processed (the dataMap size) +\param dataMap A map containing spans with the input data for the computation +**/ +void RooNLLVarNew::computeBatch(double *output, size_t /*nOut*/, RooFit::Detail::DataMap const &dataMap) const +{ + std::span weights = dataMap.at(_weightVar); + std::span weightsSumW2 = dataMap.at(_weightSquaredVar); - if (_isExtended && _weightSquared && _sumWeight2 == 0.0) { - _sumWeight2 = weights.size() == 1 ? weightsSumW2[0] * nEvents : kahanSum(weightsSumW2); + if (_binnedL) { + output[0] = computeBatchBinnedL(dataMap.at(&*_pdf), _weightSquared ? weightsSumW2 : weights); + return; } - ROOT::Math::KahanSum kahanProb; - RooNaNPacker packedNaN(0.f); + auto config = dataMap.config(this); - for (std::size_t i = 0; i < nEvents; ++i) { + auto probas = dataMap.at(_pdf); - double eventWeight = weightSpan.size() > 1 ? weightSpan[i] : weightSpan[0]; - if (0. == eventWeight * eventWeight) - continue; + _sumWeight = weights.size() == 1 ? weights[0] * probas.size() + : RooBatchCompute::reduceSum(config, weights.data(), weights.size()); + if (_expectedEvents && _weightSquared && _sumWeight2 == 0.0) { + _sumWeight2 = weights.size() == 1 ? weightsSumW2[0] * probas.size() + : RooBatchCompute::reduceSum(config, weightsSumW2.data(), weightsSumW2.size()); + } - const double term = -eventWeight * _logProbasBuffer[i]; + auto nllOut = RooBatchCompute::reduceNLL(config, probas, _weightSquared ? weightsSumW2 : weights, + _doBinOffset ? dataMap.at(*_offsetPdf) : std::span{}); - kahanProb.Add(term); - packedNaN.accumulate(term); + if (nllOut.nLargeValues > 0) { + oocoutW(&*_pdf, Eval) << "RooAbsPdf::getLogVal(" << _pdf->GetName() + << ") WARNING: top-level pdf has unexpectedly large values" << std::endl; } - - if (packedNaN.getPayload() != 0.) { - // Some events with evaluation errors. Return "badness" of errors. - kahanProb = packedNaN.getNaNWithPayload(); + for (std::size_t i = 0; i < nllOut.nNonPositiveValues; ++i) { + _pdf->logEvalError("getLogVal() top-level p.d.f not greater than zero"); + } + for (std::size_t i = 0; i < nllOut.nNaNValues; ++i) { + _pdf->logEvalError("getLogVal() top-level p.d.f evaluates to NaN"); } - if (_isExtended) { - double expected = _pdf->expectedEvents(&_observables); - kahanProb += _pdf->extendedTerm(_sumWeight, expected, _weightSquared ? _sumWeight2 : 0.0); + if (_expectedEvents) { + std::span expected = dataMap.at(*_expectedEvents); + nllOut.nllSum += _pdf->extendedTerm(_sumWeight, expected[0], _weightSquared ? _sumWeight2 : 0.0, _doBinOffset); } - output[0] = finalizeResult(std::move(kahanProb), _sumWeight); + output[0] = finalizeResult(nllOut.nllSum, _sumWeight); } void RooNLLVarNew::getParametersHook(const RooArgSet * /*nset*/, RooArgSet *params, bool /*stripDisconnected*/) const { - // strip away the observables and weights - params->remove(_observables, true, true); + // strip away the special variables params->remove(RooArgList{*_weightVar, *_weightSquaredVar}, true, true); } //////////////////////////////////////////////////////////////////////////////// -/// Clones the PDF recursively and prefixes the names of all nodes, except for -/// parameter nodes. Used for simultaneous fits. -/// \return A RooArgSet with the new observable args. +/// Sets the prefix for the special variables of this NLL, like weights or bin +/// volumes. /// \param[in] prefix The prefix to add to the observables and weight names. -RooArgSet RooNLLVarNew::prefixArgNames(std::string const &prefix) +void RooNLLVarNew::setPrefix(std::string const &prefix) { _prefix = prefix; - std::unique_ptr pdfClone = RooHelpers::cloneTreeWithSameParameters(*_pdf, &_observables); - - redirectServers(RooArgList{*pdfClone}); - - RooArgSet parameters; - pdfClone->getParameters(&_observables, parameters); - - _observables.clear(); - - RooArgSet nodes; - pdfClone->treeNodeServerList(&nodes); - for (RooAbsArg *arg : nodes) { - if (!parameters.find(*arg)) { - arg->SetName((prefix + arg->GetName()).c_str()); - if (dynamic_cast(arg)) { - // It's an observable - static_cast(arg)->setConstant(); - _observables.add(*arg); - arg->setAttribute("__obs__"); - } - } - } - - addOwnedComponents(std::move(pdfClone)); - resetWeightVarNames(); - - return _observables; } void RooNLLVarNew::resetWeightVarNames() { _weightVar->SetName((_prefix + weightVarName).c_str()); _weightSquaredVar->SetName((_prefix + weightVarNameSumW2).c_str()); + if (_offsetPdf) { + _offsetPdf->SetName((_prefix + "_offset_pdf").c_str()); + } } //////////////////////////////////////////////////////////////////////////////// @@ -267,22 +325,13 @@ void RooNLLVarNew::applyWeightSquared(bool flag) _weightSquared = flag; } -std::unique_ptr -RooNLLVarNew::fillNormSetForServer(RooArgSet const & /*normSet*/, RooAbsArg const & /*server*/) const -{ - if (_binnedL) { - return std::make_unique(); - } - return nullptr; -} - void RooNLLVarNew::enableOffsetting(bool flag) { _doOffset = flag; - _offset = {}; + _offset = ROOT::Math::KahanSum{}; } -double RooNLLVarNew::finalizeResult(ROOT::Math::KahanSum &&result, double weightSum) const +double RooNLLVarNew::finalizeResult(ROOT::Math::KahanSum result, double weightSum) const { // If part of simultaneous PDF normalize probability over // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n) @@ -291,10 +340,10 @@ double RooNLLVarNew::finalizeResult(ROOT::Math::KahanSum &&result, doubl } // Check if value offset flag is set. - if (_offset) { + if (_doOffset) { // If no offset is stored enable this feature now - if (_offset == 0 && result != 0) { + if (_offset.Sum() == 0 && _offset.Carry() == 0 && (result.Sum() != 0 || result.Carry() != 0)) { _offset = result; } @@ -305,3 +354,53 @@ double RooNLLVarNew::finalizeResult(ROOT::Math::KahanSum &&result, doubl } return result.Sum(); } + +void RooNLLVarNew::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string weightSumName = ctx.makeValidVarName(GetName()) + "WeightSum"; + std::string resName = ctx.makeValidVarName(GetName()) + "Result"; + ctx.addResult(this, resName); + ctx.addToGlobalScope("double " + weightSumName + " = 0.0;\n"); + ctx.addToGlobalScope("double " + resName + " = 0.0;\n"); + + const bool needWeightSum = _expectedEvents || _simCount > 1; + + if (needWeightSum) { + auto scope = ctx.beginLoop(this); + ctx.addToCodeBody(weightSumName + " += " + ctx.getResult(*_weightVar) + ";\n"); + } + if (_simCount > 1) { + std::string simCountStr = std::to_string(static_cast(_simCount)); + ctx.addToCodeBody(resName + " += " + weightSumName + " * std::log(" + simCountStr + ");\n"); + } + + // Begin loop scope for the observables and weight variable. If the weight + // is a scalar, the context will ignore it for the loop scope. The closing + // brackets of the loop is written at the end of the scopes lifetime. + { + auto scope = ctx.beginLoop(this); + std::string const &weight = ctx.getResult(_weightVar.arg()); + std::string const &pdfName = ctx.getResult(_pdf.arg()); + + if (_binnedL) { + // Since we only support uniform binning, bin width is the same for all. + if (!_pdf->getAttribute("BinnedLikelihoodActiveYields")) { + std::stringstream errorMsg; + errorMsg << "RooNLLVarNew::translate(): binned likelihood optimization is only supported when raw pdf " + "values can be interpreted as yields." + << " This is not the case for HistFactory models written with ROOT versions before 6.26.00"; + coutE(InputArguments) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str()); + } + std::string muName = pdfName; + ctx.addToCodeBody(this, resName + " += -1 * (-" + muName + " + " + weight + " * std::log(" + muName + + ") - TMath::LnGamma(" + weight + "+ 1));\n"); + } else { + ctx.addToCodeBody(this, resName + " -= " + weight + " * std::log(" + pdfName + ");\n"); + } + } + if (_expectedEvents) { + std::string expected = ctx.getResult(**_expectedEvents); + ctx.addToCodeBody(resName + " += " + expected + " - " + weightSumName + " * std::log(" + expected + ");\n"); + } +} diff --git a/roofit/roofitcore/src/RooNLLVarNew.h b/roofit/roofitcore/src/RooNLLVarNew.h index c3afb212e684a..3bd072c1e604f 100644 --- a/roofit/roofitcore/src/RooNLLVarNew.h +++ b/roofit/roofitcore/src/RooNLLVarNew.h @@ -21,11 +21,6 @@ #include -#include "RooBatchComputeTypes.h" - -namespace ROOT { -namespace Experimental { - class RooNLLVarNew : public RooAbsReal { public: @@ -33,9 +28,8 @@ class RooNLLVarNew : public RooAbsReal { static constexpr const char *weightVarName = "_weight"; static constexpr const char *weightVarNameSumW2 = "_weight_sumW2"; - RooNLLVarNew(){}; RooNLLVarNew(const char *name, const char *title, RooAbsPdf &pdf, RooArgSet const &observables, bool isExtended, - RooFit::OffsetMode offsetMode, bool binnedL = false); + RooFit::OffsetMode offsetMode); RooNLLVarNew(const RooNLLVarNew &other, const char *name = nullptr); TObject *clone(const char *newname) const override { return new RooNLLVarNew(*this, newname); } @@ -44,44 +38,45 @@ class RooNLLVarNew : public RooAbsReal { /// Return default level for MINUIT error analysis. double defaultErrorLevel() const override { return 0.5; } - inline RooAbsPdf *getPdf() const { return &*_pdf; } - void computeBatch(cudaStream_t *, double *output, size_t nOut, RooFit::Detail::DataMap const &) const override; - inline bool isReducerNode() const override { return true; } + void computeBatch(double *output, size_t nOut, RooFit::Detail::DataMap const &) const override; + bool canComputeBatchWithCuda() const override { return !_binnedL; } + bool isReducerNode() const override { return true; } - RooArgSet prefixArgNames(std::string const &prefix); + void setPrefix(std::string const &prefix); void applyWeightSquared(bool flag) override; - std::unique_ptr fillNormSetForServer(RooArgSet const &normSet, RooAbsArg const &server) const override; - void enableOffsetting(bool) override; + void enableBinOffsetting(bool on = true) { _doBinOffset = on; } + void setSimCount(int simCount) { _simCount = simCount; } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + private: double evaluate() const override { return _value; } void resetWeightVarNames(); - double finalizeResult(ROOT::Math::KahanSum &&result, double weightSum) const; + double finalizeResult(ROOT::Math::KahanSum result, double weightSum) const; + void fillBinWidthsFromPdfBoundaries(RooAbsReal const &pdf, RooArgSet const &observables); + double computeBatchBinnedL(std::span preds, std::span weights) const; RooTemplateProxy _pdf; - RooArgSet _observables; + RooTemplateProxy _weightVar; + RooTemplateProxy _weightSquaredVar; + std::unique_ptr> _expectedEvents; + std::unique_ptr> _offsetPdf; mutable double _sumWeight = 0.0; //! mutable double _sumWeight2 = 0.0; //! - bool _isExtended; bool _weightSquared = false; bool _binnedL = false; bool _doOffset = false; + bool _doBinOffset = false; int _simCount = 1; std::string _prefix; - RooTemplateProxy _weightVar; - RooTemplateProxy _weightSquaredVar; - mutable std::vector _binw; /// _logProbasBuffer; /// _offset = 0.0; /// _binw; + mutable ROOT::Math::KahanSum _offset{0.}; ///second.get() : nullptr; diff --git a/roofit/roofitcore/src/RooNormSetCache.cxx b/roofit/roofitcore/src/RooNormSetCache.cxx index db122f02ccda0..4275fd82185bc 100644 --- a/roofit/roofitcore/src/RooNormSetCache.cxx +++ b/roofit/roofitcore/src/RooNormSetCache.cxx @@ -26,7 +26,7 @@ RooArgSets with the same contents may be passed to an object that caches intermediate results dependent on the normalization/integration set To avoid unnecessary cache faulting, This class tracks all instances with the same contents and reports to the owner if the present nset/iset -is truely different from the current reference. Class RooNormSet only +is truly different from the current reference. Class RooNormSet only evaluates each RooArgSet pointer once, it therefore assumes that RooArgSets with normalization and/or integration sets are not changes during their lifetime. @@ -40,15 +40,8 @@ during their lifetime. void RooNormSetCache::clear() { - { - PairIdxMapType tmpmap; - tmpmap.swap(_pairToIdx); - } - { - PairVectType tmppairvect; - tmppairvect.swap(_pairs); - } - _next = 0; + _pairSet.clear(); + _pairs.clear(); } //////////////////////////////////////////////////////////////////////////////// @@ -56,28 +49,20 @@ void RooNormSetCache::clear() void RooNormSetCache::add(const RooArgSet* set1, const RooArgSet* set2) { - const Pair pair(set1, set2); - PairIdxMapType::iterator it = _pairToIdx.lower_bound(pair); - if (_pairToIdx.end() != it && it->first == pair) { + const Pair_t pair{RooFit::getUniqueId(set1), RooFit::getUniqueId(set2)}; + auto it = _pairSet.find(pair); + if (it != _pairSet.end()) { // not empty, and keys match - nothing to do return; } // register pair -> index mapping - _pairToIdx.insert(it, std::make_pair(pair, _pairs.size())); + _pairSet.emplace(pair); // save pair at that index - _pairs.push_back(pair); + _pairs.emplace_back(pair); // if the cache grew too large, start replacing in a round-robin fashion while (_pairs.size() > _max) { - // new index of the pair: replace slot _next - it->second = _next; - // find and erase mapping of old pair in that slot - _pairToIdx.erase(_pairs[_next]); - // put new pair into new slot - _pairs[_next] = _pairs.back(); - // and erase the copy we no longer need - _pairs.erase(_pairs.end() - 1); - ++_next; - _next %= _max; + _pairSet.erase(_pairs.front()); + _pairs.pop_front(); } } diff --git a/roofit/roofitcore/src/RooNormalizedPdf.cxx b/roofit/roofitcore/src/RooNormalizedPdf.cxx index 8c55d195844e5..6138f5ec06d6d 100644 --- a/roofit/roofitcore/src/RooNormalizedPdf.cxx +++ b/roofit/roofitcore/src/RooNormalizedPdf.cxx @@ -11,6 +11,7 @@ */ #include "RooNormalizedPdf.h" +#include "RooBatchCompute.h" /** * \class RooNormalizedPdf @@ -19,20 +20,34 @@ * normalization set into a new self-normalized pdf. */ -void RooNormalizedPdf::computeBatch(cudaStream_t * /*stream*/, double *output, size_t nEvents, - RooFit::Detail::DataMap const& dataMap) const +void RooNormalizedPdf::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { auto nums = dataMap.at(_pdf); auto integralSpan = dataMap.at(_normIntegral); - if (integralSpan.size() == 1) { - for (std::size_t i = 0; i < nEvents; ++i) { - output[i] = normalizeWithNaNPacking(nums[i], integralSpan[0]); - } - } else { - assert(integralSpan.size() == nEvents); - for (std::size_t i = 0; i < nEvents; ++i) { - output[i] = normalizeWithNaNPacking(nums[i], integralSpan[i]); - } + // We use the extraArgs as output parameter to count evaluation errors. + RooBatchCompute::ArgVector extraArgs{0.0, 0.0, 0.0}; + + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::NormalizedPdf, output, nEvents, {nums, integralSpan}, + extraArgs); + + std::size_t nEvalErrorsType0 = extraArgs[0]; + std::size_t nEvalErrorsType1 = extraArgs[1]; + std::size_t nEvalErrorsType2 = extraArgs[2]; + + for (std::size_t i = 0; i < nEvalErrorsType0; ++i) { + logEvalError("p.d.f normalization integral is zero or negative"); + } + for (std::size_t i = 0; i < nEvalErrorsType1; ++i) { + logEvalError("p.d.f value is less than zero, trying to recover"); } + for (std::size_t i = 0; i < nEvalErrorsType2; ++i) { + logEvalError("p.d.f value is Not-a-Number"); + } +} + +void RooNormalizedPdf::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + // For now just return function/normalization integral. + ctx.addResult(this, ctx.getResult(_pdf) + "/" + ctx.getResult(_normIntegral)); } diff --git a/roofit/roofitcore/src/RooNormalizedPdf.h b/roofit/roofitcore/src/RooNormalizedPdf.h index 764d930b319dc..36daeead4ff99 100644 --- a/roofit/roofitcore/src/RooNormalizedPdf.h +++ b/roofit/roofitcore/src/RooNormalizedPdf.h @@ -20,8 +20,11 @@ class RooNormalizedPdf : public RooAbsPdf { public: RooNormalizedPdf(RooAbsPdf &pdf, RooArgSet const &normSet) : _pdf("numerator", "numerator", this, pdf), - _normIntegral("denominator", "denominator", this, - *pdf.createIntegral(normSet, *pdf.getIntegratorConfig(), pdf.normRange()), true, false, true), + _normIntegral( + "denominator", "denominator", this, + *std::unique_ptr{pdf.createIntegral(normSet, *pdf.getIntegratorConfig(), pdf.normRange())} + .release(), + true, false, true), _normSet{normSet} { auto name = std::string(pdf.GetName()) + "_over_" + _normIntegral->GetName(); @@ -30,8 +33,10 @@ class RooNormalizedPdf : public RooAbsPdf { } RooNormalizedPdf(const RooNormalizedPdf &other, const char *name) - : RooAbsPdf(other, name), _pdf("numerator", this, other._pdf), - _normIntegral("denominator", this, other._normIntegral), _normSet{other._normSet} + : RooAbsPdf(other, name), + _pdf("numerator", this, other._pdf), + _normIntegral("denominator", this, other._normIntegral), + _normSet{other._normSet} { } @@ -47,19 +52,25 @@ class RooNormalizedPdf : public RooAbsPdf { return _pdf->getAnalyticalIntegralWN(allVars, analVars, &_normSet, rangeName); } /// Forward calculation of analytical integrals to input p.d.f - double analyticalIntegralWN(Int_t code, const RooArgSet * /*normSet*/, const char *rangeName = 0) const override + double analyticalIntegralWN(Int_t code, const RooArgSet * /*normSet*/, const char *rangeName = nullptr) const override { return _pdf->analyticalIntegralWN(code, &_normSet, rangeName); } ExtendMode extendMode() const override { return static_cast(*_pdf).extendMode(); } - double expectedEvents(const RooArgSet *nset) const override + double expectedEvents(const RooArgSet * /*nset*/) const override { return _pdf->expectedEvents(&_normSet); } + + std::unique_ptr createExpectedEventsFunc(const RooArgSet * /*nset*/) const override { - return static_cast(*_pdf).expectedEvents(nset); + return _pdf->createExpectedEventsFunc(&_normSet); } + void translate(RooFit::Detail::CodeSquashContext &ctx) const override; + + bool canComputeBatchWithCuda() const override { return true; } + protected: - void computeBatch(cudaStream_t *, double *output, size_t size, RooFit::Detail::DataMap const &) const override; + void computeBatch(double *output, size_t size, RooFit::Detail::DataMap const &) const override; double evaluate() const override { // Evaluate() should not be called in the BatchMode, but we still need it @@ -72,9 +83,9 @@ class RooNormalizedPdf : public RooAbsPdf { }; private: - RooRealProxy _pdf; + RooTemplateProxy _pdf; RooRealProxy _normIntegral; - RooArgSet const &_normSet; + RooArgSet _normSet; }; #endif diff --git a/roofit/roofitcore/src/RooNumConvPdf.cxx b/roofit/roofitcore/src/RooNumConvPdf.cxx index dfeca811764b5..76bd3f00ece6d 100644 --- a/roofit/roofitcore/src/RooNumConvPdf.cxx +++ b/roofit/roofitcore/src/RooNumConvPdf.cxx @@ -80,11 +80,7 @@ ClassImp(RooNumConvPdf); //////////////////////////////////////////////////////////////////////////////// -RooNumConvPdf::RooNumConvPdf() : - _init(false), - _conv(0) -{ -} +RooNumConvPdf::RooNumConvPdf() {} @@ -92,8 +88,6 @@ RooNumConvPdf::RooNumConvPdf() : //_____________________________________________________________________________R RooNumConvPdf::RooNumConvPdf(const char *name, const char *title, RooRealVar& convVar, RooAbsPdf& inPdf, RooAbsPdf& resmodel) : RooAbsPdf(name,title), - _init(false), - _conv(0), _origVar("!origVar","Original Convolution variable",this,convVar), _origPdf("!origPdf","Original Input PDF",this,inPdf), _origModel("!origModel","Original Resolution model",this,resmodel) @@ -102,7 +96,7 @@ RooNumConvPdf::RooNumConvPdf(const char *name, const char *title, RooRealVar& co // // convVar : convolution variable (on which both pdf and resmodel should depend) // pdf : input 'physics' pdf - // resmodel : input 'resultion' pdf + // resmodel : input 'resolution' pdf // // output is pdf(x) (X) resmodel(x) = Int [ pdf(x') resmodel (x-x') ] dx' // @@ -115,7 +109,6 @@ RooNumConvPdf::RooNumConvPdf(const char *name, const char *title, RooRealVar& co RooNumConvPdf::RooNumConvPdf(const RooNumConvPdf& other, const char* name) : RooAbsPdf(other,name), - _init(false), _origVar("!origVar",this,other._origVar), _origPdf("!origPdf",this,other._origPdf), _origModel("!origModel",this,other._origModel) @@ -124,9 +117,7 @@ RooNumConvPdf::RooNumConvPdf(const RooNumConvPdf& other, const char* name) : // This information will be propagated to a newly create convolution in a subsequent // call to initialize() if (other._conv) { - _conv = new RooNumConvolution(*other._conv,Form("%s_CONV",name?name:GetName())) ; - } else { - _conv = 0 ; + _conv = std::make_unique(*other._conv,Form("%s_CONV",name?name:GetName())) ; } } @@ -135,12 +126,7 @@ RooNumConvPdf::RooNumConvPdf(const RooNumConvPdf& other, const char* name) : //////////////////////////////////////////////////////////////////////////////// /// Destructor -RooNumConvPdf::~RooNumConvPdf() -{ - if (_init) { - delete _conv ; - } -} +RooNumConvPdf::~RooNumConvPdf() {} @@ -163,15 +149,10 @@ void RooNumConvPdf::initialize() const { // Save pointer to any prototype convolution object (only present if this object is made through // a copy constructor) - RooNumConvolution* protoConv = _conv ; + RooNumConvolution* protoConv = _conv.get(); // Optionally pass along configuration data from prototype object - _conv = new RooNumConvolution(Form("%s_CONV",GetName()),GetTitle(),var(),pdf(),model(),protoConv) ; - - // Delete prototype object now - if (protoConv) { - delete protoConv ; - } + _conv = std::make_unique(Form("%s_CONV",GetName()),GetTitle(),var(),pdf(),model(),protoConv) ; _init = true ; } @@ -190,10 +171,10 @@ RooAbsGenContext* RooNumConvPdf::genContext(const RooArgSet &vars, const RooData if (!_init) initialize() ; // Check if physics PDF and resolution model can both directly generate the convolution variable - RooArgSet* modelDep = _conv->model().getObservables(&vars) ; - modelDep->remove(_conv->var(),true,true) ; - Int_t numAddDep = modelDep->getSize() ; - delete modelDep ; + RooArgSet modelDep; + _conv->model().getObservables(&vars, modelDep); + modelDep.remove(_conv->var(),true,true) ; + Int_t numAddDep = modelDep.getSize() ; RooArgSet dummy ; bool pdfCanDir = (((RooAbsPdf&)_conv->pdf()).getGenerator(_conv->var(),dummy) != 0 && \ diff --git a/roofit/roofitcore/src/RooNumConvolution.cxx b/roofit/roofitcore/src/RooNumConvolution.cxx index 7c120e0001fbf..57ae316585e2b 100644 --- a/roofit/roofitcore/src/RooNumConvolution.cxx +++ b/roofit/roofitcore/src/RooNumConvolution.cxx @@ -79,16 +79,15 @@ ClassImp(RooNumConvolution); RooNumConvolution::RooNumConvolution() : _init(false), - _integrand(0), - _integrator(0), - _cloneVar(0), - _clonePdf(0), - _cloneModel(0), + _integrand(nullptr), + _cloneVar(nullptr), + _clonePdf(nullptr), + _cloneModel(nullptr), _useWindow(false), _windowScale(1), _verboseThresh(2000), _doProf(false), - _callHist(0) + _callHist(nullptr) { } @@ -99,7 +98,7 @@ RooNumConvolution::RooNumConvolution() : /// /// convVar : convolution variable (on which both pdf and resmodel should depend) /// pdf : input 'physics' pdf -/// resmodel : input 'resultion' pdf +/// resmodel : input 'resolution' pdf /// /// output is pdf(x) (X) resmodel(x) = Int [ pdf(x') resmodel (x-x') ] dx' /// @@ -108,22 +107,21 @@ RooNumConvolution::RooNumConvolution(const char *name, const char *title, RooRea RooAbsReal(name,title), _init(false), _convIntConfig(RooNumIntConfig::defaultConfig()), - _integrand(0), - _integrator(0), + _integrand(nullptr), _origVar("origVar","Original Convolution variable",this,convVar), _origPdf("origPdf","Original Input PDF",this,inPdf), _origModel("origModel","Original Resolution model",this,resmodel), _ownedClonedPdfSet("ownedClonePdfSet"), _ownedClonedModelSet("ownedCloneModelSet"), - _cloneVar(0), - _clonePdf(0), - _cloneModel(0), + _cloneVar(nullptr), + _clonePdf(nullptr), + _cloneModel(nullptr), _useWindow(false), _windowScale(1), _windowParam("windowParam","Convolution window parameter",this,false), _verboseThresh(2000), _doProf(false), - _callHist(0) + _callHist(nullptr) { // Use Adaptive Gauss-Kronrod integration by default for the convolution integral _convIntConfig.method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D") ; @@ -146,16 +144,15 @@ RooNumConvolution::RooNumConvolution(const RooNumConvolution& other, const char* RooAbsReal(other,name), _init(false), _convIntConfig(other._convIntConfig), - _integrand(0), - _integrator(0), + _integrand(nullptr), _origVar("origVar",this,other._origVar), _origPdf("origPdf",this,other._origPdf), _origModel("origModel",this,other._origModel), _ownedClonedPdfSet("ownedClonePdfSet"), _ownedClonedModelSet("ownedCloneModelSet"), - _cloneVar(0), - _clonePdf(0), - _cloneModel(0), + _cloneVar(nullptr), + _clonePdf(nullptr), + _cloneModel(nullptr), _useWindow(other._useWindow), _windowScale(other._windowScale), _windowParam("windowParam",this,other._windowParam), @@ -199,10 +196,10 @@ void RooNumConvolution::initialize() const _cloneVar->SetName(var().GetName()) ; // Create Convolution integrand - _integrand = new RooConvIntegrandBinding(*_clonePdf,*_cloneModel,*_cloneVar,var(),0) ; + _integrand = new RooConvIntegrandBinding(*_clonePdf,*_cloneModel,*_cloneVar,var(),nullptr) ; // Instantiate integrator for convolution integrand - _integrator = RooNumIntFactory::instance().createIntegrator(*_integrand,_convIntConfig,1) ; + _integrator = RooNumIntFactory::instance().createIntegrator(*_integrand,_convIntConfig,1); _integrator->setUseIntegrandLimits(false) ; _init = true ; @@ -249,7 +246,7 @@ double RooNumConvolution::evaluate() const if (_doProf) { _callHist->Fill(x,_integrand->numCall()) ; if (_integrand->numCall()>_verboseThresh) { - coutW(Integration) << "RooNumConvolution::eveluate(" << GetName() << ") WARNING convolution integral at x=" << x + coutW(Integration) << "RooNumConvolution::evaluate(" << GetName() << ") WARNING convolution integral at x=" << x << " required " << _integrand->numCall() << " function evaluations" << endl ; } } @@ -338,7 +335,7 @@ void RooNumConvolution::setCallProfiling(bool flag, Int_t nbinX, Int_t nbinCall, } else if (_doProf) { delete _callHist ; - _callHist = 0 ; + _callHist = nullptr ; _doProf = false ; } diff --git a/roofit/roofitcore/src/RooNumGenConfig.cxx b/roofit/roofitcore/src/RooNumGenConfig.cxx index 1a6d35d3f2ddf..668020a3c44cd 100644 --- a/roofit/roofitcore/src/RooNumGenConfig.cxx +++ b/roofit/roofitcore/src/RooNumGenConfig.cxx @@ -116,7 +116,8 @@ RooNumGenConfig::RooNumGenConfig(const RooNumGenConfig& other) : { // Clone all configuration dat for (auto * set : static_range_cast(other._configSets)) { - RooArgSet* setCopy = (RooArgSet*) set->snapshot() ; + RooArgSet* setCopy = new RooArgSet; + set->snapshot(*setCopy) ; setCopy->setName(set->GetName()) ; _configSets.Add(setCopy); } @@ -154,7 +155,8 @@ RooNumGenConfig& RooNumGenConfig::operator=(const RooNumGenConfig& other) // Copy new integrator-specific data for(auto * set : static_range_cast(other._configSets)) { - RooArgSet* setCopy = (RooArgSet*) set->snapshot() ; + RooArgSet* setCopy = new RooArgSet; + set->snapshot(*setCopy); setCopy->setName(set->GetName()) ; _configSets.Add(setCopy); } @@ -261,7 +263,8 @@ bool RooNumGenConfig::addConfigSection(const RooAbsNumGenerator* proto, const Ro } // Store default configuration parameters - RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ; + RooArgSet* config = new RooArgSet; + inDefaultConfig.snapshot(*config); config->setName(name.c_str()); _configSets.Add(config) ; diff --git a/roofit/roofitcore/src/RooNumGenFactory.cxx b/roofit/roofitcore/src/RooNumGenFactory.cxx index 7e661cb4e001d..222cff49ebc3c 100644 --- a/roofit/roofitcore/src/RooNumGenFactory.cxx +++ b/roofit/roofitcore/src/RooNumGenFactory.cxx @@ -138,7 +138,7 @@ bool RooNumGenFactory::storeProtoSampler(RooAbsNumGenerator* proto, const RooArg const RooAbsNumGenerator* RooNumGenFactory::getProtoSampler(const char* name) { if (_map.count(name)==0) { - return 0 ; + return nullptr ; } return _map[name] ; @@ -189,7 +189,7 @@ RooAbsNumGenerator* RooNumGenFactory::createSampler(RooAbsReal& func, const RooA if (!method.CompareTo("N/A")) { oocoutE(nullptr,Integration) << "RooNumGenFactory::createSampler: No sampler method has been defined for " << (cond?"a conditional ":"a ") << ndim << "-dimensional p.d.f" << endl ; - return 0 ; + return nullptr ; } // Retrieve proto integrator and return clone configured for the requested integration task diff --git a/roofit/roofitcore/src/RooNumIntConfig.cxx b/roofit/roofitcore/src/RooNumIntConfig.cxx index 67f55a22f0037..88e1ad67bf46b 100644 --- a/roofit/roofitcore/src/RooNumIntConfig.cxx +++ b/roofit/roofitcore/src/RooNumIntConfig.cxx @@ -114,7 +114,8 @@ RooNumIntConfig::RooNumIntConfig(const RooNumIntConfig& other) : { // Clone all configuration dat for(auto * set : static_range_cast(other._configSets)) { - RooArgSet* setCopy = (RooArgSet*) set->snapshot() ; + RooArgSet* setCopy = new RooArgSet; + set->snapshot(*setCopy); setCopy->setName(set->GetName()) ; _configSets.Add(setCopy); } @@ -146,7 +147,8 @@ RooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other) // Copy new integrator-specific data for(auto * set : static_range_cast(other._configSets)) { - RooArgSet* setCopy = (RooArgSet*) set->snapshot() ; + RooArgSet* setCopy = new RooArgSet; + set->snapshot(*setCopy); setCopy->setName(set->GetName()) ; _configSets.Add(setCopy); } @@ -161,34 +163,34 @@ RooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other) /// automatically determined from instance passed as 'proto'. The defaultConfig object is associated /// as the default configuration for the integrator. -bool RooNumIntConfig::addConfigSection(const RooAbsIntegrator* proto, const RooArgSet& inDefaultConfig) +bool RooNumIntConfig::addConfigSection(std::string const &name, const RooArgSet &inDefaultConfig, bool canIntegrate1D, + bool canIntegrate2D, bool canIntegrateND, bool canIntegrateOpenEnded) { - std::string name = proto->ClassName() ; - // Register integrator for appropriate dimensionalities - if (proto->canIntegrate1D()) { + if (canIntegrate1D) { _method1D.defineType(name) ; - if (proto->canIntegrateOpenEnded()) { + if (canIntegrateOpenEnded) { _method1DOpen.defineType(name) ; } } - if (proto->canIntegrate2D()) { + if (canIntegrate2D) { _method2D.defineType(name) ; - if (proto->canIntegrateOpenEnded()) { + if (canIntegrateOpenEnded) { _method2DOpen.defineType(name) ; } } - if (proto->canIntegrateND()) { + if (canIntegrateND) { _methodND.defineType(name) ; - if (proto->canIntegrateOpenEnded()) { + if (canIntegrateOpenEnded) { _methodNDOpen.defineType(name) ; } } // Store default configuration parameters - RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ; + RooArgSet* config = new RooArgSet; + inDefaultConfig.snapshot(*config); config->setName(name.c_str()); _configSets.Add(config) ; @@ -223,7 +225,7 @@ const RooArgSet& RooNumIntConfig::getConfigSection(const char* name) const //////////////////////////////////////////////////////////////////////////////// -/// Set absolute convergence criteria (convergence if abs(Err)(_configSets)) { + auto const& info = *RooNumIntFactory::instance().getPluginInfo(configSet->GetName()); + os << indent << "*** " << configSet->GetName() << " ***" << endl ; os << indent << "Capabilities: " ; - const RooAbsIntegrator* proto = RooNumIntFactory::instance().getProtoIntegrator(configSet->GetName()) ; - if (proto->canIntegrate1D()) os << "[1-D] " ; - if (proto->canIntegrate2D()) os << "[2-D] " ; - if (proto->canIntegrateND()) os << "[N-D] " ; - if (proto->canIntegrateOpenEnded()) os << "[OpenEnded] " ; + if (info.canIntegrate1D) os << "[1-D] " ; + if (info.canIntegrate2D) os << "[2-D] " ; + if (info.canIntegrateND) os << "[N-D] " ; + if (info.canIntegrateOpenEnded) os << "[OpenEnded] " ; os << endl ; os << "Configuration: " << endl ; configSet->printMultiline(os,kName|kValue) ; //configSet->writeToStream(os,false) ; - const char* depName = RooNumIntFactory::instance().getDepIntegratorName(configSet->GetName()) ; - if (strlen(depName)>0) { - os << indent << "(Depends on '" << depName << "')" << endl ; + if (!info.depName.empty()) { + os << indent << "(Depends on '" << info.depName << "')" << endl ; } os << endl ; diff --git a/roofit/roofitcore/src/RooNumIntFactory.cxx b/roofit/roofitcore/src/RooNumIntFactory.cxx index d2769abc12d09..84e2f612f3543 100644 --- a/roofit/roofitcore/src/RooNumIntFactory.cxx +++ b/roofit/roofitcore/src/RooNumIntFactory.cxx @@ -38,11 +38,8 @@ the preference of the caller as encoded in the configuration object. #include "RooNumIntConfig.h" #include "RooNumber.h" -#include "RooIntegrator1D.h" +#include "RooRombergIntegrator.h" #include "RooBinIntegrator.h" -#include "RooIntegrator2D.h" -#include "RooSegmentedIntegrator1D.h" -#include "RooSegmentedIntegrator2D.h" #include "RooImproperIntegrator1D.h" #include "RooMCIntegrator.h" #include "RooAdaptiveIntegratorND.h" @@ -60,10 +57,7 @@ ClassImp(RooNumIntFactory) /// their static registration functions void RooNumIntFactory::init() { RooBinIntegrator::registerIntegrator(*this) ; - RooIntegrator1D::registerIntegrator(*this) ; - RooIntegrator2D::registerIntegrator(*this) ; - RooSegmentedIntegrator1D::registerIntegrator(*this) ; - RooSegmentedIntegrator2D::registerIntegrator(*this) ; + RooRombergIntegrator::registerIntegrator(*this) ; RooImproperIntegrator1D::registerIntegrator(*this) ; RooMCIntegrator::registerIntegrator(*this) ; // GSL integrator is now in RooFitMore and it register itself @@ -112,50 +106,31 @@ RooNumIntFactory& RooNumIntFactory::instance() /// default configuration options and an optional list of names of other numeric integrators /// on which this integrator depends. Returns true if integrator was previously registered -bool RooNumIntFactory::storeProtoIntegrator(RooAbsIntegrator* proto, const RooArgSet& defConfig, const char* depName) +bool RooNumIntFactory::registerPlugin(std::string const &name, Creator const &creator, const RooArgSet &defConfig, + bool canIntegrate1D, bool canIntegrate2D, bool canIntegrateND, + bool canIntegrateOpenEnded, const char *depName) { - TString name = proto->ClassName() ; - - if (getProtoIntegrator(name)) { + if (_map.find(name) != _map.end()) { //cout << "RooNumIntFactory::storeIntegrator() ERROR: integrator '" << name << "' already registered" << endl ; return true ; } // Add to factory - _map[name.Data()] = std::make_pair(unique_ptr(proto), std::string(depName)); + auto& info = _map[name]; + info.creator = creator; + info.canIntegrate1D = canIntegrate1D; + info.canIntegrate2D = canIntegrate2D; + info.canIntegrateND = canIntegrateND; + info.canIntegrateOpenEnded = canIntegrateOpenEnded; + info.depName = depName; // Add default config to master config - RooNumIntConfig::defaultConfig().addConfigSection(proto,defConfig) ; + RooNumIntConfig::defaultConfig().addConfigSection(name,defConfig, canIntegrate1D, canIntegrate2D, canIntegrateND, canIntegrateOpenEnded) ; return false ; } - -//////////////////////////////////////////////////////////////////////////////// -/// Return prototype integrator with given (class) name - -const RooAbsIntegrator* RooNumIntFactory::getProtoIntegrator(const char* name) const -{ - auto item = _map.find(name); - - return item == _map.end() ? nullptr : item->second.first.get(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Get list of class names of integrators needed by integrator named 'name' - -const char* RooNumIntFactory::getDepIntegratorName(const char* name) const -{ - auto item = _map.find(name); - - return item == _map.end() ? nullptr : item->second.second.c_str(); -} - - - //////////////////////////////////////////////////////////////////////////////// /// Construct a numeric integrator instance that operates on function 'func' and is configured /// with 'config'. If ndimPreset is greater than zero that number is taken as the dimensionality @@ -165,7 +140,7 @@ const char* RooNumIntFactory::getDepIntegratorName(const char* name) const /// the number of dimensions, the nature of the limits (open ended vs closed) and the user /// preference stated in 'config' -RooAbsIntegrator* RooNumIntFactory::createIntegrator(RooAbsFunc& func, const RooNumIntConfig& config, Int_t ndimPreset, bool isBinned) const +std::unique_ptr RooNumIntFactory::createIntegrator(RooAbsFunc& func, const RooNumIntConfig& config, Int_t ndimPreset, bool isBinned) const { // First determine dimensionality and domain of integrand Int_t ndim = ndimPreset>0 ? ndimPreset : ((Int_t)func.getDimension()) ; @@ -204,12 +179,11 @@ RooAbsIntegrator* RooNumIntFactory::createIntegrator(RooAbsFunc& func, const Roo if (!method.CompareTo("N/A")) { oocoutE(nullptr,Integration) << "RooNumIntFactory::createIntegrator: No integration method has been defined for " << (openEnded?"an open ended ":"a ") << ndim << "-dimensional integral" << endl ; - return 0 ; + return nullptr ; } // Retrieve proto integrator and return clone configured for the requested integration task - const RooAbsIntegrator* proto = getProtoIntegrator(method) ; - RooAbsIntegrator* engine = proto->clone(func,config) ; + std::unique_ptr engine = getPluginInfo(method)->creator(func,config) ; if (config.printEvalCounter()) { engine->setPrintEvalCounter(true) ; } diff --git a/roofit/roofitcore/src/RooNumRunningInt.cxx b/roofit/roofitcore/src/RooNumRunningInt.cxx index 1287c5c9eaa6e..14072700fb817 100644 --- a/roofit/roofitcore/src/RooNumRunningInt.cxx +++ b/roofit/roofitcore/src/RooNumRunningInt.cxx @@ -213,7 +213,7 @@ void RooNumRunningInt::RICacheElem::addRange(Int_t ixlo, Int_t ixhi, Int_t nbins double yInt = _ay[ixlo] + (_ay[ixhi]-_ay[ixlo])*(ixmid-ixlo)/(ixhi-ixlo) ; // If relative deviation is greater than tolerance divide and iterate - if (fabs(yInt-_ay[ixmid])*(_ax[nbins-1]-_ax[0])>1e-6) { + if (std::abs(yInt-_ay[ixmid])*(_ax[nbins-1]-_ax[0])>1e-6) { addRange(ixlo,ixmid,nbins) ; addRange(ixmid,ixhi,nbins) ; } else { @@ -256,11 +256,11 @@ void RooNumRunningInt::fillCacheObject(RooAbsCachedReal::FuncCacheElem& cache) c /// Return observable in nset to be cached by RooAbsCachedPdf /// this is always the x observable that is integrated -RooArgSet* RooNumRunningInt::actualObservables(const RooArgSet& /*nset*/) const +RooFit::OwningPtr RooNumRunningInt::actualObservables(const RooArgSet& /*nset*/) const { RooArgSet* ret = new RooArgSet ; ret->add(x.arg()) ; - return ret ; + return RooFit::OwningPtr{ret}; } @@ -270,11 +270,11 @@ RooArgSet* RooNumRunningInt::actualObservables(const RooArgSet& /*nset*/) const /// These are always the input functions parameter, but never the /// integrated variable x. -RooArgSet* RooNumRunningInt::actualParameters(const RooArgSet& /*nset*/) const +RooFit::OwningPtr RooNumRunningInt::actualParameters(const RooArgSet& /*nset*/) const { - RooArgSet* ret = func.arg().getParameters(RooArgSet()) ; + auto ret = func->getParameters(RooArgSet()) ; ret->remove(x.arg(),true,true) ; - return ret ; + return ret; } diff --git a/roofit/roofitcore/src/RooNumber.cxx b/roofit/roofitcore/src/RooNumber.cxx index 83c493d9ade70..c4e652d81a338 100644 --- a/roofit/roofitcore/src/RooNumber.cxx +++ b/roofit/roofitcore/src/RooNumber.cxx @@ -22,40 +22,29 @@ Class RooNumber implements numeric constants used by RooFit **/ -#include "RooNumber.h" +#include -using namespace std; - -ClassImp(RooNumber); -; - -#ifdef HAS_NUMERIC_LIMITS - -#include -double RooNumber::_Infinity= numeric_limits::infinity(); -#else - -// This assumes a well behaved IEEE-754 floating point implementation. -// The next line may generate a compiler warning that can be ignored. -double RooNumber::_Infinity= 1.0e30 ; //1./0.; - -#endif - - -//////////////////////////////////////////////////////////////////////////////// -/// Return internal infinity representation - -double RooNumber::infinity() +/// @brief Returns an std::to_string compatible number (i.e. rounds infinities back to the nearest representable +/// value). This function is primarily used in the code-squashing for AD and as such encodes infinities to double's +/// maximum value. We do this because 1, std::to_string cannot handle infinities correctly on some platforms +/// (e.g. 32 bit debian) and 2, Clad (the AD tool) cannot handle differentiating std::numeric_limits::infinity directly. +std::string RooNumber::toString(double x) { - return _Infinity ; + int sign = isInfinite(x); + double out = x; + if (sign) + out = sign == 1 ? std::numeric_limits::max() : std::numeric_limits::min(); + return std::to_string(out); } - -//////////////////////////////////////////////////////////////////////////////// -/// Return true if x is infinite by RooNumBer internal specification - -Int_t RooNumber::isInfinite(double x) +double &RooNumber::staticRangeEpsRel() { - return (x >= +_Infinity) ? +1 : ((x <= -_Infinity) ? -1 : 0); + static double epsRel = 0.0; + return epsRel; } +double &RooNumber::staticRangeEpsAbs() +{ + static double epsAbs = 0.0; + return epsAbs; +} diff --git a/roofit/roofitcore/src/RooObjCacheManager.cxx b/roofit/roofitcore/src/RooObjCacheManager.cxx index aaa2ca6808f72..9c7a1d925691f 100644 --- a/roofit/roofitcore/src/RooObjCacheManager.cxx +++ b/roofit/roofitcore/src/RooObjCacheManager.cxx @@ -53,7 +53,7 @@ RooObjCacheManager::RooObjCacheManager(RooAbsArg* owner, Int_t maxSize, bool cle _clearOnRedirect(clearCacheOnServerRedirect), _allowOptimize(allowOptimize), _optCacheModeSeen(false), - _optCacheObservables(0) + _optCacheObservables(nullptr) { } @@ -66,7 +66,7 @@ RooObjCacheManager::RooObjCacheManager(const RooObjCacheManager& other, RooAbsAr _clearOnRedirect(other._clearOnRedirect), _allowOptimize(other._allowOptimize), _optCacheModeSeen(false), // cache mode properties are not transferred in copy ctor - _optCacheObservables(0) + _optCacheObservables(nullptr) { } @@ -165,7 +165,7 @@ void RooObjCacheManager::sterilize() if (_optCacheObservables && _clearObsList) { delete _optCacheObservables ; - _optCacheObservables = 0 ; + _optCacheObservables = nullptr ; _optCacheModeSeen = false ; } diff --git a/roofit/roofitcore/src/RooParamBinning.cxx b/roofit/roofitcore/src/RooParamBinning.cxx index 9f68109f5dd25..9b766b30c1e26 100644 --- a/roofit/roofitcore/src/RooParamBinning.cxx +++ b/roofit/roofitcore/src/RooParamBinning.cxx @@ -44,9 +44,9 @@ ClassImp(RooParamBinning); /// cout << "RooParamBinning(" << this << ") default ctor" << endl ; RooParamBinning::RooParamBinning(const char* name) : - RooAbsBinning(name), _xlo(0), _xhi(0), _nbins(100), _binw(0), _lp(0), _owner(0) + RooAbsBinning(name), _xlo(nullptr), _xhi(nullptr), _nbins(100), _binw(0), _lp(nullptr), _owner(nullptr) { - _array = 0 ; + _array = nullptr ; } @@ -56,13 +56,13 @@ RooParamBinning::RooParamBinning(const char* name) : RooParamBinning::RooParamBinning(RooAbsReal& xloIn, RooAbsReal& xhiIn, Int_t nBins, const char* name) : RooAbsBinning(name), - _array(0), + _array(nullptr), _xlo(&xloIn), _xhi(&xhiIn), _nbins(nBins), _binw(0), - _lp(0), - _owner(0) + _lp(nullptr), + _owner(nullptr) { } @@ -84,9 +84,9 @@ RooParamBinning::~RooParamBinning() /// cout << "RooParamBinning::cctor(" << this << ") orig = " << &other << endl ; RooParamBinning::RooParamBinning(const RooParamBinning& other, const char* name) : - RooAbsBinning(name), _binw(0), _owner(0) + RooAbsBinning(name), _binw(0), _owner(nullptr) { - _array = 0 ; + _array = nullptr ; if (other._lp) { // cout << "RooParamBinning::cctor(this = " << this << ") taking addresses from orig ListProxy" << endl ; @@ -102,7 +102,7 @@ RooParamBinning::RooParamBinning(const RooParamBinning& other, const char* name) } _nbins = other._nbins ; - _lp = 0 ; + _lp = nullptr ; //cout << "RooParamBinning::cctor(this = " << this << " xlo = " << &_xlo << " xhi = " << &_xhi << " _lp = " << _lp << " owner = " << _owner << ")" << endl ; } @@ -133,8 +133,8 @@ void RooParamBinning::insertHook(RooAbsRealLValue& owner) const _lp = new RooListProxy(Form("range::%s",GetName()),"lp",&owner,false,true) ; _lp->add(*_xlo) ; _lp->add(*_xhi) ; - _xlo = 0 ; - _xhi = 0 ; + _xlo = nullptr ; + _xhi = nullptr ; } @@ -147,14 +147,14 @@ void RooParamBinning::insertHook(RooAbsRealLValue& owner) const void RooParamBinning::removeHook(RooAbsRealLValue& /*owner*/) const { - _owner = 0 ; + _owner = nullptr ; // Remove list proxy from owner if (_lp) { _xlo = xlo() ; _xhi = xhi() ; delete _lp ; - _lp = 0 ; + _lp = nullptr ; } } diff --git a/roofit/roofitcore/src/RooPlot.cxx b/roofit/roofitcore/src/RooPlot.cxx index b0f7b9f09e788..74c808732f0a6 100644 --- a/roofit/roofitcore/src/RooPlot.cxx +++ b/roofit/roofitcore/src/RooPlot.cxx @@ -367,7 +367,10 @@ void RooPlot::SetDirectory(TDirectory *dir) { void RooPlot::updateNormVars(const RooArgSet &vars) { - if(0 == _normVars) _normVars= (RooArgSet*) vars.snapshot(true); + if(_normVars == nullptr) { + _normVars = new RooArgSet; + vars.snapshot(*_normVars, true); + } } @@ -379,7 +382,7 @@ void RooPlot::updateNormVars(const RooArgSet &vars) void RooPlot::addObject(TObject *obj, Option_t *drawOptions, bool invisible) { - if(0 == obj) { + if(nullptr == obj) { coutE(InputArguments) << fName << "::addObject: called with a null pointer" << endl; return; } @@ -398,7 +401,7 @@ void RooPlot::addObject(TObject *obj, Option_t *drawOptions, bool invisible) void RooPlot::addTH1(TH1 *hist, Option_t *drawOptions, bool invisible) { - if(0 == hist) { + if(nullptr == hist) { coutE(InputArguments) << fName << "::addTH1: called with a null pointer" << endl; return; } @@ -535,7 +538,7 @@ void RooPlot::addPlotable(RooPlotable *plotable, Option_t *drawOptions, bool inv // add this element to our list and remember its drawing option TObject *obj= plotable->crossCast(); - if(0 == obj) { + if(nullptr == obj) { coutE(InputArguments) << fName << "::add: cross-cast to TObject failed (nothing added)" << endl; } else { @@ -582,9 +585,9 @@ void RooPlot::updateFitRangeNorm(const RooPlotable* rp, bool refreshNorm) if (dynamic_cast(rp)) corFac = _normBinWidth/rp->getFitRangeBinW() ; - if (fabs(rp->getFitRangeNEvt()/corFac-_normNumEvts)>1e-6) { + if (std::abs(rp->getFitRangeNEvt()/corFac-_normNumEvts)>1e-6) { coutI(Plotting) << "RooPlot::updateFitRangeNorm: New event count of " << rp->getFitRangeNEvt()/corFac - << " will supercede previous event count of " << _normNumEvts << " for normalization of PDF projections" << endl ; + << " will supersede previous event count of " << _normNumEvts << " for normalization of PDF projections" << endl ; } // Nominal bin width (i.e event density) is already locked in by previously drawn histogram @@ -610,7 +613,7 @@ void RooPlot::updateFitRangeNorm(const RooPlotable* rp, bool refreshNorm) //////////////////////////////////////////////////////////////////////////////// -/// Update our y-axis limits to accomodate an object whose spread +/// Update our y-axis limits to accommodate an object whose spread /// in y is (ymin,ymax). Use the specified y-axis label if we don't /// have one assigned already. @@ -751,7 +754,7 @@ void RooPlot::printMultiline(ostream& os, Int_t /*content*/, bool verbose, TStri { TString deeper(indent); deeper.Append(" "); - if(0 != _plotVar) { + if(nullptr != _plotVar) { os << indent << "RooPlot " << GetName() << " (" << GetTitle() << ") plots variable "; _plotVar->printStream(os,kName|kTitle,kSingleLine,""); } @@ -789,7 +792,7 @@ const char* RooPlot::nameOf(Int_t idx) const TObject* obj = _items.at(idx).first; if (!obj) { coutE(InputArguments) << "RooPlot::nameOf(" << GetName() << ") index " << idx << " out of range" << endl ; - return 0 ; + return nullptr ; } return obj->GetName() ; } @@ -805,7 +808,7 @@ TObject* RooPlot::getObject(Int_t idx) const TObject* obj = _items.at(idx).first; if (!obj) { coutE(InputArguments) << "RooPlot::getObject(" << GetName() << ") index " << idx << " out of range" << endl ; - return 0 ; + return nullptr ; } return obj ; } @@ -951,14 +954,14 @@ bool RooPlot::drawAfter(const char *after, const char *target) /// methods to change the drawing style attributes of a contained /// object directly. -TObject *RooPlot::findObject(const char *name, const TClass* clas) const +TObject *RooPlot::findObject(const char *name, const TClass* tClass) const { TObject *ret = nullptr; for(auto const& item : _items) { TObject &obj = *item.first; if ((!name || name[0] == '\0' || !TString(name).CompareTo(obj.GetName())) - && (!clas || (obj.IsA()==clas))) { + && (!tClass || (obj.IsA()==tClass))) { ret = &obj ; } } @@ -1076,7 +1079,7 @@ void RooPlot::SetMinimum(double minimum) /// /// \note The \f$ \chi^2 \f$ is calculated between a *plot of the original distribution* and the data. /// It therefore has more rounding errors than directly calculating the \f$ \chi^2 \f$ from a PDF or -/// function. To do this, use RooChi2Var. +/// function. To do this, use RooAbsReal::createChi2(RooDataHist&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&). double RooPlot::chiSquare(const char* curvename, const char* histname, int nFitParam) const { @@ -1184,7 +1187,7 @@ void RooPlot::DrawOpt::initialize(const char* inRawOpt) } strlcpy(drawOptions,inRawOpt,128) ; strtok(drawOptions,":") ; - const char* extraOpt = strtok(0,":") ; + const char* extraOpt = strtok(nullptr,":") ; if (extraOpt) { invisible = (extraOpt[0]=='I') ; } @@ -1437,3 +1440,17 @@ void RooPlot::fillItemsFromTList(RooPlot::Items & items, TList const& tlist) { items.emplace_back(obj, obj->GetOption()); } } + +/// Replaces the pointer to the plot variable with a pointer to a clone of the +/// plot variable that is owned by this RooPlot. The RooPlot references the +/// plotted variable by non-owning pointer by default since ROOT 6.28, which +/// resulted in a big speedup when plotting complicated pdfs that are expensive +/// to clone. However, going back to an owned clone is useful in rare cases. +/// For example in the RooUnitTest, where the registered plots need to live +/// longer than the scope of the unit test. +void RooPlot::createInternalPlotVarClone() { + // If the plot variable is already cloned, we don't need to do anything. + if(_plotVarSet) return; + _plotVarSet = static_cast(RooArgSet(*_plotVar).snapshot()); + _plotVar = static_cast(_plotVarSet->find(_plotVar->GetName())); +} diff --git a/roofit/roofitcore/src/RooPolyFunc.cxx b/roofit/roofitcore/src/RooPolyFunc.cxx old mode 100755 new mode 100644 index afcc9efa83b10..fd3689c680acf --- a/roofit/roofitcore/src/RooPolyFunc.cxx +++ b/roofit/roofitcore/src/RooPolyFunc.cxx @@ -47,17 +47,17 @@ void RooPolyFunc::addTerm(double coefficient) std::string coeff_name = Form("%s_c%d", GetName(), n_terms); std::string term_name = Form("%s_t%d", GetName(), n_terms); auto termList = std::make_unique(term_name.c_str(), term_name.c_str(), this); - auto coeff = new RooRealVar(coeff_name.c_str(), coeff_name.c_str(), coefficient); - auto exponents = new RooArgList(); + auto coeff = std::make_unique(coeff_name.c_str(), coeff_name.c_str(), coefficient); + RooArgList exponents{}; for (const auto &var : _vars) { std::string exponent_name = Form("%s_%s^%d", GetName(), var->GetName(), 0); - auto exponent = new RooRealVar(exponent_name.c_str(), exponent_name.c_str(), 0); - exponents->add(*exponent); + auto exponent = std::make_unique(exponent_name.c_str(), exponent_name.c_str(), 0); + exponents.addOwned(std::move(exponent)); } - termList->addOwned(*exponents); - termList->addOwned(*coeff); + termList->addOwned(std::move(exponents)); + termList->addOwned(std::move(coeff)); _terms.push_back(std::move(termList)); } @@ -67,8 +67,8 @@ void RooPolyFunc::addTerm(double coefficient, const RooAbsReal &var1, int exp1) std::string coeff_name = Form("%s_c%d", GetName(), n_terms); std::string term_name = Form("%s_t%d", GetName(), n_terms); auto termList = std::make_unique(term_name.c_str(), term_name.c_str(), this); - auto coeff = new RooRealVar(coeff_name.c_str(), coeff_name.c_str(), coefficient); - auto exponents = new RooArgList(); + auto coeff = std::make_unique(coeff_name.c_str(), coeff_name.c_str(), coefficient); + RooArgList exponents{}; // linear iterate over all the variables, create var1^exp1 ..vark^0 for (const auto &var : _vars) { @@ -76,12 +76,12 @@ void RooPolyFunc::addTerm(double coefficient, const RooAbsReal &var1, int exp1) if (strcmp(var1.GetName(), var->GetName()) == 0) exp += exp1; std::string exponent_name = Form("%s_%s^%d", GetName(), var->GetName(), exp); - auto exponent = new RooRealVar(exponent_name.c_str(), exponent_name.c_str(), exp); - exponents->add(*exponent); + auto exponent = std::make_unique(exponent_name.c_str(), exponent_name.c_str(), exp); + exponents.addOwned(std::move(exponent)); } - termList->addOwned(*exponents); - termList->addOwned(*coeff); + termList->addOwned(std::move(exponents)); + termList->addOwned(std::move(coeff)); _terms.push_back(std::move(termList)); } @@ -92,8 +92,8 @@ void RooPolyFunc::addTerm(double coefficient, const RooAbsReal &var1, int exp1, std::string coeff_name = Form("%s_c%d", GetName(), n_terms); std::string term_name = Form("%s_t%d", GetName(), n_terms); auto termList = std::make_unique(term_name.c_str(), term_name.c_str(), this); - auto coeff = new RooRealVar(coeff_name.c_str(), coeff_name.c_str(), coefficient); - auto exponents = new RooArgList(); + auto coeff = std::make_unique(coeff_name.c_str(), coeff_name.c_str(), coefficient); + RooArgList exponents{}; for (const auto &var : _vars) { int exp = 0; @@ -102,11 +102,11 @@ void RooPolyFunc::addTerm(double coefficient, const RooAbsReal &var1, int exp1, if (strcmp(var2.GetName(), var->GetName()) == 0) exp += exp2; std::string exponent_name = Form("%s_%s^%d", GetName(), var->GetName(), exp); - auto exponent = new RooRealVar(exponent_name.c_str(), exponent_name.c_str(), exp); - exponents->add(*exponent); + auto exponent = std::make_unique(exponent_name.c_str(), exponent_name.c_str(), exp); + exponents.addOwned(std::move(exponent)); } - termList->addOwned(*exponents); - termList->addOwned(*coeff); + termList->addOwned(std::move(exponents)); + termList->addOwned(std::move(coeff)); _terms.push_back(std::move(termList)); } @@ -121,9 +121,9 @@ void RooPolyFunc::addTerm(double coefficient, const RooAbsCollection &exponents) std::string coeff_name = Form("%s_c%d", GetName(), n_terms); std::string term_name = Form("%s_t%d", GetName(), n_terms); auto termList = std::make_unique(term_name.c_str(), term_name.c_str(), this); - auto coeff = new RooRealVar(coeff_name.c_str(), coeff_name.c_str(), coefficient); + auto coeff = std::make_unique(coeff_name.c_str(), coeff_name.c_str(), coefficient); termList->addOwned(exponents); - termList->addOwned(*coeff); + termList->addOwned(std::move(coeff)); _terms.push_back(std::move(termList)); } @@ -174,17 +174,22 @@ std::string RooPolyFunc::asString() const auto coef = dynamic_cast(term->at(n_vars)); if (coef->getVal() > 0 && !first) ss << "+"; - ss << coef->getVal() << " * ("; + ss << coef->getVal(); first = true; for (size_t i_var = 0; i_var < n_vars; ++i_var) { auto var = dynamic_cast(_vars.at(i_var)); auto exp = dynamic_cast(term->at(i_var)); - if (!first) - ss << "+"; + if (exp->getVal() == 0) + continue; + if (first) + ss << " * ("; + else + ss << "*"; ss << "pow(" << var->GetName() << "," << exp->getVal() << ")"; first = false; } - ss << ")"; + if (!first) + ss << ")"; } return ss.str(); } @@ -224,32 +229,77 @@ void fixObservables(const RooAbsCollection &observables) var->setConstant(true); } } -//////////////////////////////////////////////////////////////////////////////// -///// Taylor expanding given function in terms of observables around -///// observableValues. Supports expansions upto order 2. -///// \param[in] function of variables that is taylor expanded. -///// \param[in] observables set of variables to perform the expansion. -///// \param[in] observableValues co-ordinates around which expansion is performed. -///// \param[in] order order of the expansion (0,1,2 supported). -///// \param[in] eps1 precision for first derivative and second derivative. -///// \param[in] eps2 precision for second partial derivative of cross-derivative. + +////////////////////////////////////////////////////////////////////////////// +/// Taylor expanding given function in terms of observables around +/// observableValues. Supports expansions upto order 2. +/// \param[in] func Function of variables that is taylor expanded. +/// \param[in] observables Set of variables to perform the expansion. +/// It's type is RooArgList to ensure that it is always ordered the +/// same as the observableValues vector. However, duplicate +/// observables are still not allowed. +/// \param[in] order Order of the expansion (0,1,2 supported). +/// \param[in] observableValues Coordinates around which expansion is +/// performed. If empty, the nominal observable values are taken, if +/// the size matches the size of the observables RooArgSet, the +/// values are mapped to the observables in matching order. If it +/// contains only one element, the same single value is used for all +/// observables. +/// \param[in] eps1 Precision for first derivative and second derivative. +/// \param[in] eps2 Precision for second partial derivative of cross-derivative. std::unique_ptr -RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, const RooAbsCollection &observables, - std::vector const &observableValues, int order, double eps1, double eps2) +RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, const RooArgList &observables, + int order, std::vector const &observableValues, double eps1, double eps2) { - // create the taylor expansion polynomial - auto taylor_poly = std::make_unique(name, title, observables); + // Create the taylor expansion polynomial + auto taylorPoly = std::make_unique(name, title, observables); + + // Verify that there are no duplicate observables + { + RooArgSet obsSet; + for (RooAbsArg *obs : observables) { + obsSet.add(*obs, /*silent*/ true); // we can be silent now, the error will come later + } + if (obsSet.size() != observables.size()) { + std::stringstream errorMsgStream; + errorMsgStream << "RooPolyFunc::taylorExpand(" << name << ") ERROR: duplicate input observables!"; + const auto errorMsg = errorMsgStream.str(); + oocoutE(taylorPoly.get(), InputArguments) << errorMsg << std::endl; + throw std::invalid_argument(errorMsg); + } + } + + // Figure out the observable values around which to exapnd + std::vector obsValues; + if (observableValues.empty()) { + obsValues.reserve(observables.size()); + for (auto *var : static_range_cast(observables)) { + obsValues.push_back(var->getVal()); + } + } else if (observableValues.size() == 1) { + obsValues.resize(observables.size()); + std::fill(obsValues.begin(), obsValues.end(), observableValues[0]); + } else if (observableValues.size() == observables.size()) { + obsValues = observableValues; + } else { + std::stringstream errorMsgStream; + errorMsgStream << "RooPolyFunc::taylorExpand(" << name + << ") ERROR: observableValues must be empty, contain one element, or match observables.size()!"; + const auto errorMsg = errorMsgStream.str(); + oocoutE(taylorPoly.get(), InputArguments) << errorMsg << std::endl; + throw std::invalid_argument(errorMsg); + } // taylor expansion can be performed only for order 0, 1, 2 currently if (order >= 3 || order <= 0) { std::stringstream errorMsgStream; errorMsgStream << "RooPolyFunc::taylorExpand(" << name << ") ERROR: order must be 0, 1, or 2"; const auto errorMsg = errorMsgStream.str(); - oocoutE(taylor_poly.get(), InputArguments) << errorMsg << std::endl; + oocoutE(taylorPoly.get(), InputArguments) << errorMsg << std::endl; throw std::invalid_argument(errorMsg); } - setCoordinates(observables, observableValues); + setCoordinates(observables, obsValues); // estimate taylor expansion polynomial for different orders // f(x) = f(x=x0) @@ -260,7 +310,7 @@ RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, for (int i_order = 0; i_order <= order; ++i_order) { switch (i_order) { case 0: { - taylor_poly->addTerm(func.getVal()); + taylorPoly->addTerm(func.getVal()); break; } case 1: { @@ -268,10 +318,10 @@ RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, double var1_val = var->getVal(); auto deriv = func.derivative(*var, 1, eps2); double deriv_val = deriv->getVal(); - setCoordinates(observables, observableValues); - taylor_poly->addTerm(deriv_val, *var, 1); + setCoordinates(observables, obsValues); + taylorPoly->addTerm(deriv_val, *var, 1); if (var1_val != 0.0) { - taylor_poly->addTerm(deriv_val * var1_val * -1.0); + taylorPoly->addTerm(deriv_val * var1_val * -1.0); } } break; @@ -286,17 +336,17 @@ RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, if (strcmp(var1->GetName(), var2->GetName()) == 0) { auto deriv2 = func.derivative(*var2, 2, eps2); deriv_val = 0.5 * deriv2->getVal(); - setCoordinates(observables, observableValues); + setCoordinates(observables, obsValues); } else { auto deriv2 = deriv1->derivative(*var2, 1, eps2); deriv_val = 0.5 * deriv2->getVal(); - setCoordinates(observables, observableValues); + setCoordinates(observables, obsValues); } - taylor_poly->addTerm(deriv_val, *var1, 1, *var2, 1); + taylorPoly->addTerm(deriv_val, *var1, 1, *var2, 1); if (var1_val != 0.0 || var2_val != 0.0) { - taylor_poly->addTerm(deriv_val * var1_val * var2_val); - taylor_poly->addTerm(deriv_val * var2_val * -1.0, *var1, 1); - taylor_poly->addTerm(deriv_val * var1_val * -1.0, *var2, 1); + taylorPoly->addTerm(deriv_val * var1_val * var2_val); + taylorPoly->addTerm(deriv_val * var2_val * -1.0, *var1, 1); + taylorPoly->addTerm(deriv_val * var1_val * -1.0, *var2, 1); } } } @@ -304,16 +354,5 @@ RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, } } } - return taylor_poly; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Taylor expanding given function in terms of observables around -/// defaultValue for all observables. -std::unique_ptr RooPolyFunc::taylorExpand(const char *name, const char *title, RooAbsReal &func, - const RooAbsCollection &observables, double observablesValue, - int order, double eps1, double eps2) -{ - return RooPolyFunc::taylorExpand(name, title, func, observables, - std::vector(observables.size(), observablesValue), order, eps1, eps2); + return taylorPoly; } diff --git a/roofit/roofitcore/src/RooPolyVar.cxx b/roofit/roofitcore/src/RooPolyVar.cxx index 4844b622fa184..8f4f210ac85c4 100644 --- a/roofit/roofitcore/src/RooPolyVar.cxx +++ b/roofit/roofitcore/src/RooPolyVar.cxx @@ -31,147 +31,176 @@ it can define. #include "RooPolyVar.h" #include "RooArgList.h" #include "RooMsgService.h" -//#include "Riostream.h" +#include "RooBatchCompute.h" -#include "TError.h" +#include +#include -using namespace std; +#include "TError.h" ClassImp(RooPolyVar); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooPolyVar::RooPolyVar() : _lowestOrder(0) -{ } - //////////////////////////////////////////////////////////////////////////////// /// Construct polynomial in x with coefficients in coefList. If /// lowestOrder is not zero, then the first element in coefList is /// interpreted as as the 'lowestOrder' coefficients and all -/// subsequent coeffient elements are shifted by a similar amount. -RooPolyVar::RooPolyVar(const char* name, const char* title, - RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) : - RooAbsReal(name, title), - _x("x", "Dependent", this, x), - _coefList("coefList","List of coefficients",this), - _lowestOrder(lowestOrder) +/// subsequent coefficient elements are shifted by a similar amount. +RooPolyVar::RooPolyVar(const char *name, const char *title, RooAbsReal &x, const RooArgList &coefList, + Int_t lowestOrder) + : RooAbsReal(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), + _lowestOrder(lowestOrder) { - // Check lowest order - if (_lowestOrder<0) { - coutE(InputArguments) << "RooPolyVar::ctor(" << GetName() - << ") WARNING: lowestOrder must be >=0, setting value to 0" << endl ; - _lowestOrder=0 ; - } - - for(RooAbsArg * coef : coefList) { - if (!dynamic_cast(coef)) { - coutE(InputArguments) << "RooPolyVar::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() - << " is not of type RooAbsReal" << endl ; - R__ASSERT(0) ; - } - _coefList.add(*coef) ; - } + // Check lowest order + if (_lowestOrder < 0) { + coutE(InputArguments) << "RooPolyVar::ctor(" << GetName() + << ") WARNING: lowestOrder must be >=0, setting value to 0" << std::endl; + _lowestOrder = 0; + } + + for (RooAbsArg *coef : coefList) { + if (!dynamic_cast(coef)) { + coutE(InputArguments) << "RooPolyVar::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() + << " is not of type RooAbsReal" << std::endl; + R__ASSERT(0); + } + _coefList.add(*coef); + } } - //////////////////////////////////////////////////////////////////////////////// /// Constructor of flat polynomial function -RooPolyVar::RooPolyVar(const char* name, const char* title, - RooAbsReal& x) : - RooAbsReal(name, title), - _x("x", "Dependent", this, x), - _coefList("coefList","List of coefficients",this), - _lowestOrder(1) -{ } - - +RooPolyVar::RooPolyVar(const char *name, const char *title, RooAbsReal &x) + : RooAbsReal(name, title), + _x("x", "Dependent", this, x), + _coefList("coefList", "List of coefficients", this), + _lowestOrder(1) +{ +} //////////////////////////////////////////////////////////////////////////////// /// Copy constructor -RooPolyVar::RooPolyVar(const RooPolyVar& other, const char* name) : - RooAbsReal(other, name), - _x("x", this, other._x), - _coefList("coefList",this,other._coefList), - _lowestOrder(other._lowestOrder) -{ } - - +RooPolyVar::RooPolyVar(const RooPolyVar &other, const char *name) + : RooAbsReal(other, name), + _x("x", this, other._x), + _coefList("coefList", this, other._coefList), + _lowestOrder(other._lowestOrder) +{ +} +void RooPolyVar::fillCoeffValues(std::vector &wksp, RooListProxy const &coefList) +{ + wksp.clear(); + wksp.reserve(coefList.size()); + { + const RooArgSet *nset = coefList.nset(); + for (const auto arg : coefList) { + const auto c = static_cast(arg); + wksp.push_back(c->getVal(nset)); + } + } +} //////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooPolyVar::~RooPolyVar() -{ } - +/// Calculate and return value of polynomial +double RooPolyVar::evaluate() const +{ + const unsigned sz = _coefList.getSize(); + if (!sz) + return _lowestOrder ? 1. : 0.; + fillCoeffValues(_wksp, _coefList); -//////////////////////////////////////////////////////////////////////////////// -/// Calculate and return value of polynomial + return RooFit::Detail::EvaluateFuncs::polynomialEvaluate(_wksp.data(), sz, _lowestOrder, _x); +} -double RooPolyVar::evaluate() const +void RooPolyVar::translate(RooFit::Detail::CodeSquashContext &ctx) const { - const unsigned sz = _coefList.getSize(); - const int lowestOrder = _lowestOrder; - if (!sz) return lowestOrder ? 1. : 0.; - _wksp.clear(); - _wksp.reserve(sz); - { - const RooArgSet* nset = _coefList.nset(); - for (const auto arg : _coefList) { - const auto c = static_cast(arg); - _wksp.push_back(c->getVal(nset)); - } - } - const double x = _x; - double retVal = _wksp[sz - 1]; - for (unsigned i = sz - 1; i--; ) retVal = _wksp[i] + x * retVal; - return retVal * std::pow(x, lowestOrder); + const unsigned sz = _coefList.size(); + if (!sz) { + ctx.addResult(this, std::to_string((_lowestOrder ? 1. : 0.))); + return; + } + + ctx.addResult(this, + ctx.buildCall("RooFit::Detail::EvaluateFuncs::polynomialEvaluate", _coefList, sz, _lowestOrder, _x)); } +void RooPolyVar::computeBatchImpl(RooAbsArg const* caller, double *output, size_t nEvents, + RooFit::Detail::DataMap const &dataMap, RooAbsReal const &x, RooArgList const &coefs, + int lowestOrder) +{ + if (coefs.empty()) { + output[0] = lowestOrder ? 1.0 : 0.0; + return; + } + + RooBatchCompute::VarVector vars; + vars.reserve(coefs.size() + 2); + + // Fill the coefficients for the skipped orders. By a conventions started in + // RooPolynomial, if the zero-th order is skipped, it implies a coefficient + // for the constant term of one. + const double zero = 1.0; + const double one = 1.0; + for (int i = lowestOrder - 1; i >= 0; --i) { + vars.push_back(i == 0 ? std::span{&one, 1} : std::span{&zero, 1}); + } + + for (RooAbsArg *coef : coefs) { + vars.push_back(dataMap.at(coef)); + } + vars.push_back(dataMap.at(&x)); + RooBatchCompute::ArgVector extraArgs{double(vars.size() - 1)}; + RooBatchCompute::compute(dataMap.config(caller), RooBatchCompute::Polynomial, output, nEvents, vars, extraArgs); +} +/// Compute multiple values of Polynomial. +void RooPolyVar::computeBatch(double *output, size_t nEvents, + RooFit::Detail::DataMap const &dataMap) const +{ + computeBatchImpl(this, output, nEvents, dataMap, _x.arg(), _coefList, _lowestOrder); +} //////////////////////////////////////////////////////////////////////////////// /// Advertise that we can internally integrate over x -Int_t RooPolyVar::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const +Int_t RooPolyVar::getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char * /*rangeName*/) const { - if (matchArgs(allVars, analVars, _x)) return 1; - return 0; + if (matchArgs(allVars, analVars, _x)) + return 1; + return 0; } - - //////////////////////////////////////////////////////////////////////////////// /// Calculate and return analytical integral over x -double RooPolyVar::analyticalIntegral(Int_t code, const char* rangeName) const +double RooPolyVar::analyticalIntegral(Int_t code, const char *rangeName) const +{ + R__ASSERT(code == 1); + + const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); + const unsigned sz = _coefList.getSize(); + if (!sz) + return _lowestOrder ? xmax - xmin : 0.0; + + fillCoeffValues(_wksp, _coefList); + + return RooFit::Detail::AnalyticalIntegrals::polynomialIntegral(_wksp.data(), sz, _lowestOrder, xmin, xmax); +} + +std::string RooPolyVar::buildCallToAnalyticIntegral(Int_t /* code */, const char *rangeName, + RooFit::Detail::CodeSquashContext &ctx) const { - R__ASSERT(code==1) ; - - const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); - const int lowestOrder = _lowestOrder; - const unsigned sz = _coefList.getSize(); - if (!sz) return xmax - xmin; - _wksp.clear(); - _wksp.reserve(sz); - { - const RooArgSet* nset = _coefList.nset(); - unsigned i = 1 + lowestOrder; - for(auto * c : static_range_cast(_coefList)) { - _wksp.push_back(c->getVal(nset) / double(i)); - ++i; - } - } - double min = _wksp[sz - 1], max = _wksp[sz - 1]; - for (unsigned i = sz - 1; i--; ) - min = _wksp[i] + xmin * min, max = _wksp[i] + xmax * max; - return max * std::pow(xmax, 1 + lowestOrder) - min * std::pow(xmin, 1 + lowestOrder); + const double xmin = _x.min(rangeName), xmax = _x.max(rangeName); + const unsigned sz = _coefList.getSize(); + if (!sz) + return std::to_string(_lowestOrder ? xmax - xmin : 0.0); + + return ctx.buildCall("RooFit::Detail::AnalyticalIntegrals::polynomialIntegral", _coefList, sz, _lowestOrder, xmin, + xmax); } diff --git a/roofit/roofitcore/src/RooPrintable.cxx b/roofit/roofitcore/src/RooPrintable.cxx index 9c40a5ba75163..0945382e3c81a 100644 --- a/roofit/roofitcore/src/RooPrintable.cxx +++ b/roofit/roofitcore/src/RooPrintable.cxx @@ -272,6 +272,6 @@ ostream &RooPrintable::defaultPrintStream(ostream *os) static ostream *_defaultPrintStream = &cout; ostream& _oldDefault= *_defaultPrintStream; - if(0 != os) _defaultPrintStream= os; + if(nullptr != os) _defaultPrintStream= os; return _oldDefault; } diff --git a/roofit/roofitcore/src/RooProdGenContext.cxx b/roofit/roofitcore/src/RooProdGenContext.cxx index 3b28247a5e540..9a9855e945d64 100644 --- a/roofit/roofitcore/src/RooProdGenContext.cxx +++ b/roofit/roofitcore/src/RooProdGenContext.cxx @@ -60,9 +60,7 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v // Make full list of dependents (generated & proto) RooArgSet deps(vars) ; if (prototype) { - RooArgSet* protoDeps = model.getObservables(*prototype->get()) ; - deps.remove(*protoDeps,true,true) ; - delete protoDeps ; + deps.remove(*std::unique_ptr{model.getObservables(*prototype->get())},true,true) ; } // Factorize product in irreducible terms @@ -156,7 +154,7 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v if (!pdfDep->empty()) { coutI(Generation) << "RooProdGenContext::ctor() creating subcontext for generation of observables " << *pdfDep << " from model " << pdf->GetName() << endl ; std::unique_ptr auxProto2{pdf->getObservables(impDeps)}; - _gcList.push_back(pdf->genContext(*pdfDep,prototype,auxProto2.get(),verbose)) ; + _gcList.emplace_back(pdf->genContext(*pdfDep,prototype,auxProto2.get(),verbose)) ; } // cout << "adding following dependents to list of generated observables: " ; pdfDep->Print("1") ; @@ -166,7 +164,7 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v // Composite term if (!termDeps->empty()) { - const std::string name = model.makeRGPPName("PRODGEN_",*term,RooArgSet(),RooArgSet(),0) ; + const std::string name = model.makeRGPPName("PRODGEN_",*term,RooArgSet(),RooArgSet(),nullptr) ; // Construct auxiliary PDF expressing product of composite terms, // following Conditional component specification of input model @@ -188,18 +186,17 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v } } - RooProdPdf* multiPdf = new RooProdPdf(name.c_str(),name.c_str(),fullPdfSet,cmdList) ; + auto multiPdf = std::make_unique(name.c_str(),name.c_str(),fullPdfSet,cmdList) ; cmdList.Delete() ; pdfSetList.Delete() ; multiPdf->setOperMode(RooAbsArg::ADirty,true) ; multiPdf->useDefaultGen(true) ; - _ownedMultiProds.addOwned(*multiPdf) ; coutI(Generation) << "RooProdGenContext()::ctor creating subcontext for generation of observables " << *termDeps << "for irriducuble composite term using sub-product object " << multiPdf->GetName() ; - RooAbsGenContext* cx = multiPdf->genContext(*termDeps,prototype,auxProto,verbose) ; - _gcList.push_back(cx) ; + _gcList.emplace_back(multiPdf->genContext(*termDeps,prototype,auxProto,verbose)); + _ownedMultiProds.addOwned(std::move(multiPdf)); genDeps.add(*termDeps) ; @@ -238,7 +235,7 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v ++normIter; } - const std::string name = model.makeRGPPName("PRODGEN_",trailerTerm,RooArgSet(),RooArgSet(),0) ; + const std::string name = model.makeRGPPName("PRODGEN_",trailerTerm,RooArgSet(),RooArgSet(),nullptr) ; // Construct auxiliary PDF expressing product of composite terms, // following Partial/Full component specification of input model @@ -261,18 +258,18 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v } // cmdList.Print("v") ; - RooProdPdf* multiPdf = new RooProdPdf(name.c_str(),name.c_str(),fullPdfSet,cmdList) ; + auto multiPdf = std::make_unique(name.c_str(),name.c_str(),fullPdfSet,cmdList); cmdList.Delete() ; pdfSetList.Delete() ; multiPdf->setOperMode(RooAbsArg::ADirty,true) ; multiPdf->useDefaultGen(true) ; - _ownedMultiProds.addOwned(*multiPdf) ; cxcoutD(Generation) << "RooProdGenContext(" << model.GetName() << "): creating context for irreducible composite trailer term " << multiPdf->GetName() << " that generates observables " << trailerTermDeps << endl ; - RooAbsGenContext* cx = multiPdf->genContext(trailerTermDeps,prototype,auxProto,verbose) ; - _gcList.push_back(cx) ; + _gcList.emplace_back(multiPdf->genContext(trailerTermDeps,prototype,auxProto,verbose)); + + _ownedMultiProds.addOwned(std::move(multiPdf)); } // Now check if the are observables in vars that are not generated by any of the above p.d.f.s @@ -298,12 +295,7 @@ RooProdGenContext::RooProdGenContext(const RooProdPdf &model, const RooArgSet &v //////////////////////////////////////////////////////////////////////////////// /// Destructor. Delete all owned subgenerator contexts -RooProdGenContext::~RooProdGenContext() -{ - for (list::iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - delete (*iter) ; - } -} +RooProdGenContext::~RooProdGenContext() {} //////////////////////////////////////////////////////////////////////////////// @@ -312,8 +304,8 @@ RooProdGenContext::~RooProdGenContext() void RooProdGenContext::attach(const RooArgSet& args) { //Forward initGenerator call to all components - for (list::iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - (*iter)->attach(args) ; + for (auto const& elem : _gcList) { + elem->attach(args) ; } } @@ -324,8 +316,8 @@ void RooProdGenContext::attach(const RooArgSet& args) void RooProdGenContext::initGenerator(const RooArgSet &theEvent) { // Forward initGenerator call to all components - for (list::iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - (*iter)->initGenerator(theEvent) ; + for (auto const& elem : _gcList) { + elem->initGenerator(theEvent) ; } } @@ -341,8 +333,8 @@ void RooProdGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) { // Loop over the component generators - for (list::iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - (*iter)->generateEvent(theEvent,remaining) ; + for (auto const& elem : _gcList) { + elem->generateEvent(theEvent,remaining) ; } // Generate uniform variables (non-dependents) @@ -354,7 +346,6 @@ void RooProdGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining) } theEvent.assign(_uniObs) ; } - } @@ -368,10 +359,9 @@ void RooProdGenContext::setProtoDataOrder(Int_t* lut) // Forward call to component generators RooAbsGenContext::setProtoDataOrder(lut) ; - for (list::iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - (*iter)->setProtoDataOrder(lut) ; + for (auto const& elem : _gcList) { + elem->setProtoDataOrder(lut) ; } - } @@ -390,7 +380,7 @@ void RooProdGenContext::printMultiline(ostream &os, Int_t content, bool verbose, TString indent2(indent) ; indent2.Append(" ") ; - for (list::const_iterator iter=_gcList.begin() ; iter!=_gcList.end() ; ++iter) { - (*iter)->printMultiline(os,content,verbose,indent2) ; + for (auto const& elem : _gcList) { + elem->printMultiline(os,content,verbose,indent2) ; } } diff --git a/roofit/roofitcore/src/RooProdPdf.cxx b/roofit/roofitcore/src/RooProdPdf.cxx index 84a6ca0231af6..272abfc65f239 100644 --- a/roofit/roofitcore/src/RooProdPdf.cxx +++ b/roofit/roofitcore/src/RooProdPdf.cxx @@ -160,32 +160,7 @@ RooProdPdf::RooProdPdf(const char* name, const char* title, const RooArgList& in _cutOff(cutOff), _pdfList("!pdfs","List of PDFs",this) { - Int_t numExtended(0) ; - for(RooAbsArg * arg : inPdfList) { - RooAbsPdf* pdf = dynamic_cast(arg) ; - if (!pdf) { - coutW(InputArguments) << "RooProdPdf::RooProdPdf(" << GetName() << ") list arg " - << arg->GetName() << " is not a PDF, ignored" << endl ; - continue ; - } - _pdfList.add(*pdf) ; - - _pdfNSetList.emplace_back(std::make_unique("nset")) ; - - if (pdf->canBeExtended()) { - _extendedIndex = _pdfList.index(pdf) ; - numExtended++ ; - } - } - - // Protect against multiple extended terms - if (numExtended>1) { - coutW(InputArguments) << "RooProdPdf::RooProdPdf(" << GetName() - << ") WARNING: multiple components with extended terms detected," - << " product will not be extendible." << endl ; - _extendedIndex = -1 ; - } - + addPdfs(inPdfList); TRACE_CREATE } @@ -221,7 +196,7 @@ RooProdPdf::RooProdPdf(const char* name, const char* title, const RooArgList& in /// \f$ F \f$ only is used to determine the correlation between \f$ X \f$ and \f$ Y \f$. In the latter /// case, the \f$ Y \f$ distribution is defined by the product of \f$ F \f$ and \f$ G \f$. /// -/// This \f$ P(x,y) \f$ construction is analoguous to generating events from \f$ F(x,y) \f$ with +/// This \f$ P(x,y) \f$ construction is analogous to generating events from \f$ F(x,y) \f$ with /// a prototype dataset sampled from \f$ G(y) \f$. RooProdPdf::RooProdPdf(const char* name, const char* title, const RooArgSet& fullPdfSet, @@ -334,8 +309,8 @@ void RooProdPdf::initializeFromCmdArgList(const RooArgSet& fullPdfSet, const Roo if (0 == strcmp(carg->GetName(), "Conditional")) { Int_t argType = carg->getInt(0) ; - RooArgSet* pdfSet = (RooArgSet*) carg->getSet(0) ; - RooArgSet* normSet = (RooArgSet*) carg->getSet(1) ; + auto pdfSet = static_cast(carg->getSet(0)); + auto normSet = static_cast(carg->getSet(1)); for(auto * thePdf : static_range_cast(*pdfSet)) { _pdfList.add(*thePdf) ; @@ -379,12 +354,12 @@ RooProdPdf::~RooProdPdf() RooProdPdf::CacheElem* RooProdPdf::getCacheElem(RooArgSet const* nset) const { int code ; - auto cache = static_cast(_cacheMgr.getObj(nset, 0, &code)) ; + auto cache = static_cast(_cacheMgr.getObj(nset, nullptr, &code)) ; // If cache doesn't have our configuration, recalculate here if (!cache) { code = getPartIntList(nset, nullptr) ; - cache = static_cast(_cacheMgr.getObj(nset, 0, &code)) ; + cache = static_cast(_cacheMgr.getObj(nset, nullptr, &code)) ; } return cache; } @@ -435,24 +410,24 @@ double RooProdPdf::calculate(const RooProdPdf::CacheElem& cache, bool /*verbose* //////////////////////////////////////////////////////////////////////////////// /// Evaluate product of PDFs in batch mode. -void RooProdPdf::calculateBatch(const RooProdPdf::CacheElem& cache, cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooProdPdf::calculateBatch(RooAbsArg const *caller, const RooProdPdf::CacheElem &cache, double *output, + size_t nEvents, RooFit::Detail::DataMap const &dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - - if (cache._isRearranged) { - auto numerator = dataMap.at(cache._rearrangedNum.get()); - auto denominator = dataMap.at(cache._rearrangedDen.get()); - dispatch->compute(stream, RooBatchCompute::Ratio, output, nEvents, {numerator, denominator}); - } else { - RooBatchCompute::VarVector factors; - factors.reserve(cache._partList.size()); - for (const RooAbsArg *i : cache._partList) { - auto span = dataMap.at(i); - factors.push_back(span); - } - RooBatchCompute::ArgVector special{static_cast(factors.size())}; - dispatch->compute(stream, RooBatchCompute::ProdPdf, output, nEvents, factors, special); - } + if (cache._isRearranged) { + auto numerator = dataMap.at(cache._rearrangedNum.get()); + auto denominator = dataMap.at(cache._rearrangedDen.get()); + RooBatchCompute::compute(dataMap.config(caller), RooBatchCompute::Ratio, output, nEvents, + {numerator, denominator}); + } else { + RooBatchCompute::VarVector factors; + factors.reserve(cache._partList.size()); + for (const RooAbsArg *i : cache._partList) { + auto span = dataMap.at(i); + factors.push_back(span); + } + RooBatchCompute::ArgVector special{static_cast(factors.size())}; + RooBatchCompute::compute(dataMap.config(caller), RooBatchCompute::ProdPdf, output, nEvents, factors, special); + } } namespace { @@ -506,10 +481,10 @@ void RooProdPdf::factorizeProduct(const RooArgSet& normSet, const RooArgSet& int std::vector depIntNoNormList; // Setup lists for factorization terms and their dependents - RooArgSet* term(0); - RooArgSet* termNormDeps(0); - RooArgSet* termIntDeps(0); - RooArgSet* termIntNoNormDeps(0); + RooArgSet* term(nullptr); + RooArgSet* termNormDeps(nullptr); + RooArgSet* termIntDeps(nullptr); + RooArgSet* termIntNoNormDeps(nullptr); std::vector pdfIntNoNormDeps; std::vector pdfIntSet; @@ -527,11 +502,11 @@ void RooProdPdf::factorizeProduct(const RooArgSet& normSet, const RooArgSet& int pdfCSet.clear(); // Make iterator over tree leaf node list to get the observables. - // This code is borrowed from RooAgsPdf::getObservables. + // This code is borrowed from RooAbsPdf::getObservables(). // RooAbsArg::treeNodeServer list is relatively expensive, so we only do it // once and use it in a lambda function. RooArgSet pdfLeafList("leafNodeServerList") ; - pdf.treeNodeServerList(&pdfLeafList,0,false,true,true) ; + pdf.treeNodeServerList(&pdfLeafList,nullptr,false,true,true) ; auto getObservablesOfCurrentPdf = [&pdfLeafList]( std::vector & out, const RooArgSet& dataList) { @@ -626,7 +601,6 @@ void RooProdPdf::factorizeProduct(const RooArgSet& normSet, const RooArgSet& int if (!done) { if (!(pdfNormDeps.empty() && pdfAllDeps.empty() && pdfIntSet.empty()) || normSet.empty()) { -// cout << GetName() << ": creating new term" << endl; term = new RooArgSet("term"); termNormDeps = new RooArgSet("termNormDeps"); depAllList.emplace_back(pdfAllDeps.begin(), pdfAllDeps.end(), "termAllDeps"); @@ -656,13 +630,17 @@ void RooProdPdf::factorizeProduct(const RooArgSet& normSet, const RooArgSet& int // Make list of wholly imported dependents RooArgSet impDeps(depAllList[i]); impDeps.remove(*normDeps, true, true); - impDepList.Add(impDeps.snapshot()); + auto snap = new RooArgSet; + impDeps.snapshot(*snap); + impDepList.Add(snap); // cout << GetName() << ": list of imported dependents for term " << (*term) << " set to " << impDeps << endl ; // Make list of cross dependents (term is self contained for these dependents, // but components import dependents from other components) auto crossDeps = std::unique_ptr{depIntNoNormList[i].selectCommon(*normDeps)}; - crossDepList.Add(crossDeps->snapshot()); + snap = new RooArgSet; + crossDeps->snapshot(*snap); + crossDepList.Add(snap); // cout << GetName() << ": list of cross dependents for term " << (*term) << " set to " << *crossDeps << endl ; } @@ -744,7 +722,7 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS // cout<<"FK: termImpSet.getSize() = "< RooProdPdf::createCacheElem(const RooArgS } else { // cout<<"FK: Starting Composite Term"< RooProdPdf::createCacheElem(const RooArgS imps=(RooArgSet*)imp.At(termIdx); RooArgSet termNSet(*norm), termImpSet(*imps); - if (!termImpSet.empty() && 0 != _refRangeName) { + if (!termImpSet.empty() && nullptr != _refRangeName) { // WVE we can skip this if the ref range is equal to the normalization range bool rangeIdentical(true); @@ -817,22 +794,6 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS // Find groups with y as termNSet // Replace G(y) with (G(y),ratio) for (auto const& group : groupedList) { - if (1 == group.size()) { - RooArgSet* term = group[0]; - - Int_t termIdx = terms.IndexOf(term); - norm = (RooArgSet*) norms.At(termIdx); - imps = (RooArgSet*) imp.At(termIdx); - RooArgSet termNSet(*norm), termImpSet(*imps); - - // If termNset matches index of ratioTerms, insert ratio here - std::ostringstream str; termNSet.printValue(str); - if (!ratioTerms[str.str()].empty()) { -// cout << "MUST INSERT RATIO OBJECT IN TERM (SINGLE) " << *term << endl; - term->addOwned(std::move(ratioTerms[str.str()])); - } - } else { - RooArgSet compTermSet, compTermNorm; for (auto const& term : group) { Int_t termIdx = terms.IndexOf(term); norm = (RooArgSet*) norms.At(termIdx); @@ -843,10 +804,10 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS ostringstream str; termNSet.printValue(str); if (!ratioTerms[str.str()].empty()) { // cout << "MUST INSERT RATIO OBJECT IN TERM (COMPOSITE)" << *term << endl; - term->addOwned(std::move(ratioTerms[str.str()])); + term->add(ratioTerms[str.str()]); + cache->_ownedList.addOwned(std::move(ratioTerms[str.str()])); } } - } } for (auto const& group : groupedList) { @@ -873,25 +834,18 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS termXSet.add(*xdeps); termImpSet.add(*imps); -// cout << GetName() << ": termISet = " << termISet << endl; -// cout << GetName() << ": termNSet = " << termNSet << endl; -// cout << GetName() << ": termXSet = " << termXSet << endl; -// cout << GetName() << ": termImpSet = " << termImpSet << endl; - // Add prefab term to partIntList. bool isOwned(false); vector func = processProductTerm(nset, iset, isetRangeName, term, termNSet, termISet, isOwned); if (func[0]) { cache->_partList.add(*func[0]); - if (isOwned) cache->_ownedList.addOwned(*func[0]); + if (isOwned) cache->_ownedList.addOwned(std::unique_ptr{func[0]}); - cache->_normList.emplace_back(norm->snapshot(false)); + cache->_normList.emplace_back(std::make_unique()); + norm->snapshot(*cache->_normList.back(), false); - cache->_numList.addOwned(*func[1]); - cache->_denList.addOwned(*func[2]); -// cout << "func[0]=" << func[0]->ClassName() << "::" << func[0]->GetName() << endl; -// cout << "func[1]=" << func[1]->ClassName() << "::" << func[1]->GetName() << endl; -// cout << "func[2]=" << func[2]->ClassName() << "::" << func[2]->GetName() << endl; + cache->_numList.addOwned(std::unique_ptr{func[1]}); + cache->_denList.addOwned(std::unique_ptr{func[2]}); } } else { // cout << "processing composite item" << endl; @@ -912,19 +866,13 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS // Remove outer integration dependents from termISet termISet.remove(outerIntDeps, true, true); -// cout << "termISet = "; termISet.Print("1"); - -// cout << GetName() << ": termISet = " << termISet << endl; -// cout << GetName() << ": termNSet = " << termNSet << endl; -// cout << GetName() << ": termXSet = " << termXSet << endl; -// cout << GetName() << ": termImpSet = " << termImpSet << endl; bool isOwned = false; vector func = processProductTerm(nset, iset, isetRangeName, term, termNSet, termISet, isOwned, true); // cout << GetName() << ": created composite term component " << func[0]->GetName() << endl; if (func[0]) { compTermSet.add(*func[0]); - if (isOwned) cache->_ownedList.addOwned(*func[0]); + if (isOwned) cache->_ownedList.addOwned(std::unique_ptr{func[0]}); compTermNorm.add(*norm, false); compTermNum.add(*func[1]); @@ -932,9 +880,6 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS //cache->_numList.add(*func[1]); //cache->_denList.add(*func[2]); -// cout << "func[0]=" << func[0]->ClassName() << "::" << func[0]->GetName() << endl; -// cout << "func[1]=" << func[1]->ClassName() << "::" << func[1]->GetName() << endl; -// cout << "func[2]=" << func[2]->ClassName() << "::" << func[2]->GetName() << endl; } } @@ -957,12 +902,12 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS cache->_partList.add(*inttmp); // Product of numerator terms - const string prodname_num = makeRGPPName("SPECPROD_NUM", compTermNum, RooArgSet(), RooArgSet(), 0); + const string prodname_num = makeRGPPName("SPECPROD_NUM", compTermNum, RooArgSet(), RooArgSet(), nullptr); auto prodtmp_num = std::make_unique(prodname_num.c_str(), prodname_num.c_str(), compTermNum); prodtmp_num->addOwnedComponents(compTermNum); // Product of denominator terms - const string prodname_den = makeRGPPName("SPECPROD_DEN", compTermDen, RooArgSet(), RooArgSet(), 0); + const string prodname_den = makeRGPPName("SPECPROD_DEN", compTermDen, RooArgSet(), RooArgSet(), nullptr); auto prodtmp_den = std::make_unique(prodname_den.c_str(), prodname_den.c_str(), compTermDen); prodtmp_den->addOwnedComponents(compTermDen); @@ -979,31 +924,12 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS cache->_ownedList.addOwned(std::move(prodtmp_num)); cache->_ownedList.addOwned(std::move(prodtmp_den)); cache->_numList.addOwned(std::move(numtmp)); - cache->_denList.addOwned(*(RooAbsArg*)RooFit::RooConst(1).clone("1")); - cache->_normList.emplace_back(compTermNorm.snapshot(false)); + cache->_denList.addOwned(std::unique_ptr{static_cast(RooFit::RooConst(1).clone("1"))}); + cache->_normList.emplace_back(std::make_unique()); + compTermNorm.snapshot(*cache->_normList.back(), false); } } - // WVE DEBUG PRINTING -// cout << "RooProdPdf::getPartIntList(" << GetName() << ") made cache " << cache << " with the following nset pointers "; -// TIterator* nliter = nsetList->MakeIterator(); -// RooArgSet* ns; -// while((ns=(RooArgSet*)nliter->Next())) { -// cout << ns << " "; -// } -// cout << endl; -// delete nliter; - -// cout << " FOLKERT::RooProdPdf::getPartIntList END(" << GetName() <<") nset = " << (nset?*nset:RooArgSet()) << endl -// << " _normRange = " << _normRange << endl -// << " iset = " << (iset?*iset:RooArgSet()) << endl -// << " partList = "; -// if(partListPointer) partListPointer->Print(); -// cout << " nsetList = "; -// if(nsetListPointer) nsetListPointer->Print(""); -// cout << " code = " << returnCode << endl -// << " isetRangeName = " << (isetRangeName?isetRangeName:"") << endl; - // Need to rearrange product in case of multiple ranges if (_normRange.Contains(",")) { rearrangeProduct(*cache); @@ -1026,12 +952,13 @@ std::unique_ptr RooProdPdf::createCacheElem(const RooArgS std::unique_ptr RooProdPdf::makeCondPdfRatioCorr(RooAbsReal& pdf, const RooArgSet& termNset, const RooArgSet& /*termImpSet*/, const char* normRangeTmp, const char* refRange) const { - RooAbsReal* ratio_num = pdf.createIntegral(termNset,normRangeTmp) ; - RooAbsReal* ratio_den = pdf.createIntegral(termNset,refRange) ; + std::unique_ptr ratio_num{pdf.createIntegral(termNset,normRangeTmp)}; + std::unique_ptr ratio_den{pdf.createIntegral(termNset,refRange)}; auto ratio = std::make_unique(Form("ratio(%s,%s)",ratio_num->GetName(),ratio_den->GetName()),"@0/@1", RooArgList(*ratio_num,*ratio_den)) ; - ratio->addOwnedComponents(RooArgSet(*ratio_num,*ratio_den)) ; + ratio->addOwnedComponents(std::move(ratio_num)); + ratio->addOwnedComponents(std::move(ratio_den)); ratio->setAttribute("RATIO_TERM") ; return ratio ; } @@ -1050,16 +977,16 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const { std::vector buf(strlen(_normRange.Data()) + 1); strcpy(buf.data(),_normRange.Data()) ; - char* save(0) ; + char* save(nullptr) ; char* token = R__STRTOK_R(buf.data(),",",&save) ; while(token) { rangeComps.push_back(token) ; - token = R__STRTOK_R(0,",",&save) ; + token = R__STRTOK_R(nullptr,",",&save) ; } } - map denListList ; + std::map denListList ; RooArgSet specIntDeps ; string specIntRange ; @@ -1077,7 +1004,7 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const // cout << "corresponding denominator = " << den->GetName() << endl ; - RooFormulaVar* ratio(0) ; + RooFormulaVar* ratio(nullptr) ; RooArgSet origNumTerm ; if (string("SPECINT")==part->getStringAttribute("PROD_TERM_TYPE")) { @@ -1163,13 +1090,13 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const // cout << "depends in value of ratio" << endl ; // Make specialize ratio instance - RooAbsReal* specializedRatio = specializeRatio(*(RooFormulaVar*)ratio,iter->c_str()) ; + std::unique_ptr specializedRatio{specializeRatio(*(RooFormulaVar*)ratio,iter->c_str())}; // cout << "specRatio = " << endl ; // specializedRatio->printComponentTree() ; // Replace generic ratio with specialized ratio - RooAbsArg *partCust(0) ; + RooAbsArg *partCust(nullptr) ; if (parg->InheritsFrom(RooAddition::Class())) { @@ -1190,19 +1117,21 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const // cout << "customized function = " << endl ; // partCust->printComponentTree() ; - RooAbsReal* specializedPartCust = specializeIntegral(*(RooAbsReal*)partCust,iter->c_str()) ; + std::unique_ptr specializedPartCust{specializeIntegral(*(RooAbsReal*)partCust,iter->c_str())}; // Finally divide again by ratio string name = Form("%s_divided_by_ratio",specializedPartCust->GetName()) ; - RooFormulaVar* specIntFinal = new RooFormulaVar(name.c_str(),"@0/@1",RooArgList(*specializedPartCust,*specializedRatio)) ; + auto specIntFinal = std::make_unique(name.c_str(),"@0/@1",RooArgList(*specializedPartCust,*specializedRatio)) ; + specIntFinal->addOwnedComponents(std::move(specializedPartCust)); + specIntFinal->addOwnedComponents(std::move(specializedRatio)); - denListList[*iter].add(*specIntFinal) ; + denListList[*iter].addOwned(std::move(specIntFinal)); } else { // cout << "does NOT depend on value of ratio" << endl ; // parg->Print("t") ; - denListList[*iter].add(*specializeIntegral(*parg,iter->c_str())) ; + denListList[*iter].addOwned(specializeIntegral(*parg,iter->c_str())); } } @@ -1211,33 +1140,37 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const if (ratio) { - RooAbsReal* specRatio = specializeRatio(*(RooFormulaVar*)ratio,iter->c_str()) ; + std::unique_ptr specRatio{specializeRatio(*(RooFormulaVar*)ratio,iter->c_str())}; // If integral is 'Int r(y)*g(y) dy ' then divide a posteriori by r(y) // cout << "have ratio, orig den = " << den->GetName() << endl ; RooArgSet tmp(origNumTerm) ; tmp.add(*specRatio) ; - const string pname = makeRGPPName("PROD",tmp,RooArgSet(),RooArgSet(),0) ; - RooProduct* specDenProd = new RooProduct(pname.c_str(),pname.c_str(),tmp) ; - RooAbsReal* specInt(0) ; + const string pname = makeRGPPName("PROD",tmp,RooArgSet(),RooArgSet(),nullptr) ; + auto specDenProd = std::make_unique(pname.c_str(),pname.c_str(),tmp) ; + std::unique_ptr specInt; if (den->InheritsFrom(RooRealIntegral::Class())) { - specInt = specDenProd->createIntegral(((RooRealIntegral*)den)->intVars(),iter->c_str()) ; + specInt = std::unique_ptr{specDenProd->createIntegral(((RooRealIntegral*)den)->intVars(),iter->c_str())}; + specInt->addOwnedComponents(std::move(specDenProd)); } else if (den->InheritsFrom(RooAddition::Class())) { RooAddition* orig = (RooAddition*)den ; RooRealIntegral* origInt = (RooRealIntegral*) orig->list1().first() ; - specInt = specDenProd->createIntegral(origInt->intVars(),iter->c_str()) ; + specInt = std::unique_ptr{specDenProd->createIntegral(origInt->intVars(),iter->c_str())}; + specInt->addOwnedComponents(std::move(specDenProd)); } else { throw string("this should not happen") ; } //RooAbsReal* specInt = specializeIntegral(*den,iter->c_str()) ; string name = Form("%s_divided_by_ratio",specInt->GetName()) ; - RooFormulaVar* specIntFinal = new RooFormulaVar(name.c_str(),"@0/@1",RooArgList(*specInt,*specRatio)) ; - denListList[*iter].add(*specIntFinal) ; + auto specIntFinal = std::make_unique(name.c_str(),"@0/@1",RooArgList(*specInt,*specRatio)) ; + specIntFinal->addOwnedComponents(std::move(specInt)); + specIntFinal->addOwnedComponents(std::move(specRatio)); + denListList[*iter].addOwned(std::move(specIntFinal)); } else { - denListList[*iter].add(*specializeIntegral(*den,iter->c_str())) ; + denListList[*iter].addOwned(specializeIntegral(*den,iter->c_str())); } } @@ -1253,7 +1186,7 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const string name = Form("%s_numerator",GetName()) ; // WVE FIX THIS (2) - RooAbsReal* numerator = new RooProduct(name.c_str(),name.c_str(),nomList) ; + std::unique_ptr numerator = std::make_unique(name.c_str(),name.c_str(),nomList) ; RooArgSet products ; // cout << "nomList = " << nomList << endl ; @@ -1262,22 +1195,23 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const name = Form("%s_denominator_comp_%s",GetName(),iter->first.c_str()) ; // WVE FIX THIS (2) RooProduct* prod_comp = new RooProduct(name.c_str(),name.c_str(),iter->second) ; + prod_comp->addOwnedComponents(std::move(iter->second)); products.add(*prod_comp) ; } name = Form("%s_denominator_sum",GetName()) ; RooAbsReal* norm = new RooAddition(name.c_str(),name.c_str(),products) ; norm->addOwnedComponents(products) ; - if (specIntDeps.getSize()>0) { + if (!specIntDeps.empty()) { // Apply posterior integration required for SPECINT case string namesr = Form("SPEC_RATIO(%s,%s)",numerator->GetName(),norm->GetName()) ; RooFormulaVar* ndr = new RooFormulaVar(namesr.c_str(),"@0/@1",RooArgList(*numerator,*norm)) ; + ndr->addOwnedComponents(std::move(numerator)); // Integral of ratio - RooAbsReal* numtmp = ndr->createIntegral(specIntDeps,specIntRange.c_str()) ; + numerator = std::unique_ptr{ndr->createIntegral(specIntDeps,specIntRange.c_str())}; - numerator = numtmp ; norm = (RooAbsReal*) RooFit::RooConst(1).Clone() ; } @@ -1291,7 +1225,7 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const // WVE DEBUG //RooMsgService::instance().debugWorkspace()->import(RooArgSet(*numerator,*norm)) ; - cache._rearrangedNum.reset(numerator); + cache._rearrangedNum = std::move(numerator); cache._rearrangedDen.reset(norm); cache._isRearranged = true ; @@ -1300,31 +1234,31 @@ void RooProdPdf::rearrangeProduct(RooProdPdf::CacheElem& cache) const //////////////////////////////////////////////////////////////////////////////// -RooAbsReal* RooProdPdf::specializeRatio(RooFormulaVar& input, const char* targetRangeName) const +std::unique_ptr RooProdPdf::specializeRatio(RooFormulaVar& input, const char* targetRangeName) const { RooRealIntegral* numint = (RooRealIntegral*) input.getParameter(0) ; RooRealIntegral* denint = (RooRealIntegral*) input.getParameter(1) ; - RooAbsReal* numint_spec = specializeIntegral(*numint,targetRangeName) ; + std::unique_ptr numint_spec{specializeIntegral(*numint,targetRangeName)}; - RooAbsReal* ret = new RooFormulaVar(Form("ratio(%s,%s)",numint_spec->GetName(),denint->GetName()),"@0/@1",RooArgList(*numint_spec,*denint)) ; - ret->addOwnedComponents(*numint_spec) ; + std::unique_ptr ret = std::make_unique(Form("ratio(%s,%s)",numint_spec->GetName(),denint->GetName()),"@0/@1",RooArgList(*numint_spec,*denint)) ; + ret->addOwnedComponents(std::move(numint_spec)); - return ret ; + return ret; } //////////////////////////////////////////////////////////////////////////////// -RooAbsReal* RooProdPdf::specializeIntegral(RooAbsReal& input, const char* targetRangeName) const +std::unique_ptr RooProdPdf::specializeIntegral(RooAbsReal& input, const char* targetRangeName) const { if (input.InheritsFrom(RooRealIntegral::Class())) { // If input is integral, recreate integral but override integration range to be targetRangeName RooRealIntegral* orig = (RooRealIntegral*)&input ; // cout << "creating integral: integrand = " << orig->integrand().GetName() << " vars = " << orig->intVars() << " range = " << targetRangeName << endl ; - return orig->integrand().createIntegral(orig->intVars(),targetRangeName) ; + return std::unique_ptr{orig->integrand().createIntegral(orig->intVars(),targetRangeName)}; } else if (input.InheritsFrom(RooAddition::Class())) { @@ -1332,14 +1266,12 @@ RooAbsReal* RooProdPdf::specializeIntegral(RooAbsReal& input, const char* target RooAddition* orig = (RooAddition*)&input ; RooRealIntegral* origInt = (RooRealIntegral*) orig->list1().first() ; // cout << "creating integral from addition: integrand = " << origInt->integrand().GetName() << " vars = " << origInt->intVars() << " range = " << targetRangeName << endl ; - return origInt->integrand().createIntegral(origInt->intVars(),targetRangeName) ; - - } else { - -// cout << "specializeIntegral: unknown input type " << input.ClassName() << "::" << input.GetName() << endl ; + return std::unique_ptr{origInt->integrand().createIntegral(origInt->intVars(),targetRangeName)}; } - return &input ; + std::stringstream errMsg; + errMsg << "specializeIntegral: unknown input type " << input.ClassName() << "::" << input.GetName(); + throw std::runtime_error(errMsg.str()); } @@ -1411,7 +1343,7 @@ void RooProdPdf::groupProductTerms(std::list>& groupedTe newGroup->emplace_back(term2) ; } - // Remove this group from list and delete it (but not its contents) + // Remove this non-owning group from list group = groupedTerms.erase(group); } else { ++group; @@ -1431,22 +1363,12 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c const RooArgSet* term,const RooArgSet& termNSet, const RooArgSet& termISet, bool& isOwned, bool forceWrap) const { -// cout << " FOLKERT::RooProdPdf(" << GetName() <<") processProductTerm nset = " << (nset?*nset:RooArgSet()) << endl -// << " _normRange = " << _normRange << endl -// << " iset = " << (iset?*iset:RooArgSet()) << endl -// << " isetRangeName = " << (isetRangeName?isetRangeName:"") << endl -// << " term = " << (term?*term:RooArgSet()) << endl -// << " termNSet = " << termNSet << endl -// << " termISet = " << termISet << endl -// << " isOwned = " << isOwned << endl -// << " forceWrap = " << forceWrap << endl ; - - vector ret(3) ; ret[0] = 0 ; ret[1] = 0 ; ret[2] = 0 ; + vector ret(3) ; ret[0] = nullptr ; ret[1] = nullptr ; ret[2] = nullptr ; // CASE I: factorizing term: term is integrated over all normalizing observables // ----------------------------------------------------------------------------- // Check if all observbales of this term are integrated. If so the term cancels - if (termNSet.getSize()>0 && termNSet.getSize()==termISet.getSize() && isetRangeName==0) { + if (termNSet.getSize()>0 && termNSet.getSize()==termISet.getSize() && isetRangeName==nullptr) { //cout << "processProductTerm(" << GetName() << ") case I " << endl ; @@ -1473,7 +1395,7 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c RooAbsPdf* pdf = (RooAbsPdf*) term->first() ; - RooAbsReal* partInt = pdf->createIntegral(termISet,termNSet,isetRangeName) ; + RooAbsReal* partInt = std::unique_ptr{pdf->createIntegral(termISet,termNSet,isetRangeName)}.release(); partInt->setOperMode(operMode()) ; partInt->setStringAttribute("PROD_TERM_TYPE","IIIa") ; @@ -1484,8 +1406,8 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c ret[0] = partInt ; // Split mode results - ret[1] = pdf->createIntegral(termISet,isetRangeName) ; - ret[2] = pdf->createIntegral(termNSet,normRange()) ; + ret[1] = std::unique_ptr{pdf->createIntegral(termISet,isetRangeName)}.release(); + ret[2] = std::unique_ptr{pdf->createIntegral(termNSet,normRange())}.release(); return ret ; @@ -1506,13 +1428,13 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c isOwned=true ; ret[0] = partInt ; - const std::string name1 = makeRGPPName("PROD",*term,RooArgSet(),RooArgSet(),0) ; + const std::string name1 = makeRGPPName("PROD",*term,RooArgSet(),RooArgSet(),nullptr) ; // WVE FIX THIS RooProduct* tmp_prod = new RooProduct(name1.c_str(),name1.c_str(),*term) ; - ret[1] = tmp_prod->createIntegral(termISet,isetRangeName) ; - ret[2] = tmp_prod->createIntegral(termNSet,normRange()) ; + ret[1] = std::unique_ptr{tmp_prod->createIntegral(termISet,isetRangeName)}.release(); + ret[2] = std::unique_ptr{tmp_prod->createIntegral(termNSet,normRange())}.release(); return ret ; } @@ -1535,13 +1457,13 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c isOwned=true ; ret[0] = partInt ; - const std::string name1 = makeRGPPName("PROD",*term,RooArgSet(),RooArgSet(),0) ; + const std::string name1 = makeRGPPName("PROD",*term,RooArgSet(),RooArgSet(),nullptr) ; // WVE FIX THIS RooProduct* tmp_prod = new RooProduct(name1.c_str(),name1.c_str(),*term) ; - ret[1] = tmp_prod->createIntegral(termISet,isetRangeName) ; - ret[2] = tmp_prod->createIntegral(termNSet,normRange()) ; + ret[1] = std::unique_ptr{tmp_prod->createIntegral(termISet,isetRangeName)}.release(); + ret[2] = std::unique_ptr{tmp_prod->createIntegral(termNSet,normRange())}.release(); return ret ; } @@ -1578,8 +1500,8 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c ret[0] = partInt ; - ret[1] = pdf->createIntegral(RooArgSet()) ; - ret[2] = pdf->createIntegral(termNSet,normRange()) ; + ret[1] = std::unique_ptr{pdf->createIntegral(RooArgSet())}.release(); + ret[2] = std::unique_ptr{pdf->createIntegral(termNSet,normRange())}.release(); return ret ; @@ -1593,8 +1515,9 @@ std::vector RooProdPdf::processProductTerm(const RooArgSet* nset, c pdf->setStringAttribute("PROD_TERM_TYPE","IVb") ; ret[0] = pdf ; - ret[1] = pdf->createIntegral(RooArgSet()) ; - ret[2] = termNSet.getSize()>0 ? pdf->createIntegral(termNSet,normRange()) : ((RooAbsReal*)RooFit::RooConst(1).clone("1")) ; + ret[1] = std::unique_ptr{pdf->createIntegral(RooArgSet())}.release(); + ret[2] = !termNSet.empty() ? std::unique_ptr{pdf->createIntegral(termNSet,normRange())}.release() + : ((RooAbsReal*)RooFit::RooConst(1).clone("1")); return ret ; } } @@ -1690,7 +1613,7 @@ double RooProdPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, co CacheElem* cache = (CacheElem*) _cacheMgr.getObjByIndex(code-1) ; // If cache has been sterilized, revive this slot - if (cache==0) { + if (cache==nullptr) { std::unique_ptr vars{getParameters(RooArgSet())} ; RooArgSet nset = _cacheMgr.selectFromSet1(*vars, code-1) ; RooArgSet iset = _cacheMgr.selectFromSet2(*vars, code-1) ; @@ -1732,9 +1655,18 @@ double RooProdPdf::expectedEvents(const RooArgSet* nset) const throw std::logic_error(std::string("RooProdPdf ") + GetName() + " could not be extended."); } - return ((RooAbsPdf*)_pdfList.at(_extendedIndex))->expectedEvents(nset) ; + return static_cast(_pdfList.at(_extendedIndex))->expectedEvents(nset) ; } +std::unique_ptr RooProdPdf::createExpectedEventsFunc(const RooArgSet* nset) const +{ + if (_extendedIndex<0) { + coutF(Generation) << "Requesting expected number of events from a RooProdPdf that does not contain an extended p.d.f" << endl ; + throw std::logic_error(std::string("RooProdPdf ") + GetName() + " could not be extended."); + } + + return static_cast(_pdfList.at(_extendedIndex))->createExpectedEventsFunc(nset); +} //////////////////////////////////////////////////////////////////////////////// @@ -1876,7 +1808,7 @@ bool RooProdPdf::isDirectGenSafe(const RooAbsArg& arg) const if (!_useDefaultGen) return RooAbsPdf::isDirectGenSafe(arg) ; // Argument may appear in only one PDF component - RooAbsPdf* thePdf(0) ; + RooAbsPdf* thePdf(nullptr) ; for (auto* pdf : static_range_cast(_pdfList)) { if (pdf->dependsOn(arg)) { @@ -1905,15 +1837,57 @@ RooArgSet* RooProdPdf::findPdfNSet(RooAbsPdf const& pdf) const } + +/// Add some full PDFs to the factors of this RooProdPdf. +void RooProdPdf::addPdfs(RooAbsCollection const& pdfs) +{ + size_t numExtended = (_extendedIndex==-1) ? 0 : 1; + + for(auto arg : pdfs) { + RooAbsPdf* pdf = dynamic_cast(arg); + if (!pdf) { + coutW(InputArguments) << "RooProdPdf::addPdfs(" << GetName() << ") list arg " + << arg->GetName() << " is not a PDF, ignored" << endl ; + continue; + } + if(pdf->canBeExtended()) { + if (_extendedIndex == -1) { + _extendedIndex = _pdfList.size(); + } else { + numExtended++; + } + } + _pdfList.add(*pdf); + _pdfNSetList.emplace_back(std::make_unique("nset")); + } + + // Protect against multiple extended terms + if (numExtended>1) { + coutW(InputArguments) << "RooProdPdf::addPdfs(" << GetName() + << ") WARNING: multiple components with extended terms detected," + << " product will not be extendible." << endl ; + _extendedIndex = -1 ; + } + + // Reset cache + _cacheMgr.reset() ; + +} + /// Remove some PDFs from the factors of this RooProdPdf. -/// Private implementation detail. -void RooProdPdf::removePdfs(RooArgSet const& pdfs) +void RooProdPdf::removePdfs(RooAbsCollection const& pdfs) { // Remember what the extended PDF is RooAbsArg const* extPdf = _extendedIndex >= 0 ? &_pdfList[_extendedIndex] : nullptr; - // Actually remove the PDFs - _pdfList.remove(pdfs); + // Actually remove the PDFs and associated nsets + for(size_t i=0;i < _pdfList.size(); i++) { + if(pdfs.contains(_pdfList[i])) { + _pdfList.remove(_pdfList[i]); + _pdfNSetList.erase(_pdfNSetList.begin()+i); + i--; + } + } // Since we may have removed PDFs from the list, the index of the extended // PDF in the list needs to be updated. The new index might also be -1 if the @@ -1927,6 +1901,38 @@ void RooProdPdf::removePdfs(RooArgSet const& pdfs) } +namespace { + +std::vector sortedNamePtrs(RooAbsCollection const& col) +{ + std::vector ptrs; + ptrs.reserve(col.size()); + for(RooAbsArg* arg : col) { + ptrs.push_back(arg->namePtr()); + } + std::sort(ptrs.begin(), ptrs.end()); + return ptrs; +} + +bool sortedNamePtrsOverlap(std::vector const& ptrsA, std::vector const& ptrsB) +{ + auto pA = ptrsA.begin(); + auto pB = ptrsB.begin(); + while (pA != ptrsA.end() && pB != ptrsB.end()) { + if (*pA < *pB) { + ++pA; + } else if (*pB < *pA) { + ++pB; + } else { + return true; + } + } + return false; +} + +} // namespace + + //////////////////////////////////////////////////////////////////////////////// /// Return all parameter constraint p.d.f.s on parameters listed in constrainedParams. /// The observables set is required to distinguish unambiguously p.d.f in terms @@ -1939,18 +1945,39 @@ RooArgSet* RooProdPdf::getConstraints(const RooArgSet& observables, RooArgSet& c RooArgSet constraints ; RooArgSet pdfParams, conParams ; + // For the optimized implementation of checking if two collections overlap by name. + auto observablesNamePtrs = sortedNamePtrs(observables); + auto constrainedParamsNamePtrs = sortedNamePtrs(constrainedParams); + // Loop over PDF components - for(auto * pdf : static_range_cast(_pdfList)) { - // A constraint term is a p.d.f that does not depend on any of the listed observables - // but does depends on any of the parameters that should be constrained + for (std::size_t iPdf = 0; iPdf < _pdfList.size(); ++iPdf) { + auto * pdf = static_cast(&_pdfList[iPdf]); + RooArgSet tmp; pdf->getParameters(nullptr, tmp); - // Before, there were calls to `pdf->dependsOn()` here, but they were very - // expensive for large computation graphs! Given that we have to traverse - // the computation graph with a call to `pdf->getParameters()` anyway, we - // can just check if the set of all variables operlaps with the observables - // or constraind parameters. - if (!tmp.overlaps(observables) && tmp.overlaps(constrainedParams)) { + + // A constraint term is a p.d.f that doesn't contribute to the + // expectedEvents() and does not depend on any of the listed observables + // but does depends on any of the parameters that should be constrained + bool isConstraint = false; + + if(static_cast(iPdf) != _extendedIndex) { + auto tmpNamePtrs = sortedNamePtrs(tmp); + // Before, there were calls to `pdf->dependsOn()` here, but they were very + // expensive for large computation graphs! Given that we have to traverse + // the computation graph with a call to `pdf->getParameters()` anyway, we + // can just check if the set of all variables operlaps with the observables + // or constraind parameters. + // + // We are using an optimized implementation of overlap checking. Because + // the overlap is checked by name, we can check overlap of the + // corresponding name pointers. The optimization can't be in + // RooAbsCollection itself, because it is crucial that the memory for the + // non-tmp name pointers is not reallocated for each pdf. + isConstraint = !sortedNamePtrsOverlap(tmpNamePtrs, observablesNamePtrs) && + sortedNamePtrsOverlap(tmpNamePtrs, constrainedParamsNamePtrs); + } + if (isConstraint) { constraints.add(*pdf) ; conParams.add(tmp,true) ; } else { @@ -2003,11 +2030,14 @@ RooArgSet* RooProdPdf::getConstraints(const RooArgSet& observables, RooArgSet& c RooArgSet* RooProdPdf::getConnectedParameters(const RooArgSet& observables) const { RooArgSet* connectedPars = new RooArgSet("connectedPars") ; - for (const auto arg : _pdfList) { - // Check if term is relevant - if (arg->dependsOn(observables)) { + for (std::size_t iPdf = 0; iPdf < _pdfList.size(); ++iPdf) { + auto * pdf = static_cast(&_pdfList[iPdf]); + // Check if term is relevant, either because it provides a propablity + // density in the observables or because it is used for the expected + // events. + if (static_cast(iPdf) == _extendedIndex || pdf->dependsOn(observables)) { RooArgSet tmp; - arg->getParameters(&observables, tmp); + pdf->getParameters(&observables, tmp); connectedPars->add(tmp) ; } } @@ -2217,9 +2247,8 @@ bool RooProdPdf::redirectServersHook(const RooAbsCollection& newServerList, bool // Need to do some tricks here because it's not possible to replace in // an owning RooAbsCollection. normSet->releaseOwnership(); - normSet->replace(*arg, *newArg->cloneTree()); + normSet->replace(*std::unique_ptr{arg}, *newArg->cloneTree()); normSet->takeOwnership(); - delete arg; } } } @@ -2257,27 +2286,148 @@ void RooProdPdf::CacheElem::writeToStream(std::ostream& os) const { } } -void RooProdPdf::writeCacheToStream(std::ostream& os, RooArgSet const* nset) const { - getCacheElem(nset)->writeToStream(os); +std::unique_ptr RooProdPdf::fillNormSetForServer(RooArgSet const &normSet, RooAbsArg const &server) const +{ + if (normSet.empty()) + return nullptr; + auto *pdfNset = findPdfNSet(static_cast(server)); + if (pdfNset && !pdfNset->empty()) { + std::unique_ptr out; + if (0 == strcmp("cset", pdfNset->GetName())) { + // If the name of the normalization set is "cset", it doesn't contain the + // normalization set but the conditional observables that should *not* be + // normalized over. + out = std::make_unique(normSet); + RooArgSet common; + out->selectCommon(*pdfNset, common); + out->remove(common); + } else { + out = std::make_unique(*pdfNset); + } + // prefix also the arguments in the normSets if they have not already been + if (auto prefix = getStringAttribute("__prefix__")) { + for (RooAbsArg *arg : *out) { + if (!arg->getStringAttribute("__prefix__")) { + arg->SetName((std::string(prefix) + arg->GetName()).c_str()); + arg->setStringAttribute("__prefix__", prefix); + } + } + } + return out; + } else { + return nullptr; + } } -std::unique_ptr RooProdPdf::fillNormSetForServer(RooArgSet const& normSet, RooAbsArg const& server) const { - if(normSet.empty()) return nullptr; - auto * pdfNset = findPdfNSet(static_cast(server)); - if (pdfNset && !pdfNset->empty()) { - if (0 == strcmp("cset", pdfNset->GetName())) { - // If the name of the normalization set is "cset", it doesn't contain the - // normalization set but the conditional observables that should *not* be - // normalized over. - auto out = std::make_unique(normSet); - RooArgSet common; - out->selectCommon(*pdfNset, common); - out->remove(common); - return out; - } else { - return std::make_unique(*pdfNset); - } - } else { - return nullptr; - } +/// A RooProdPdf with a fixed normalization set can be replaced by this class. +/// Its purpose is to provide the right client-server interface for the +/// evaluation of RooProdPdf cache elements that were created for a given +/// normalization set. +class RooFixedProdPdf : public RooAbsPdf { +public: + RooFixedProdPdf(std::unique_ptr &&prodPdf, RooArgSet const &normSet) + : RooAbsPdf(prodPdf->GetName(), prodPdf->GetTitle()), _normSet{normSet}, + _servers("!servers", "List of servers", this), _prodPdf{std::move(prodPdf)} + { + initialize(); + } + RooFixedProdPdf(const RooFixedProdPdf &other, const char *name = nullptr) + : RooAbsPdf(other, name), _normSet{other._normSet}, + _servers("!servers", "List of servers", this), _prodPdf{static_cast(other._prodPdf->Clone())} + { + initialize(); + } + TObject *clone(const char *newname) const override { return new RooFixedProdPdf(*this, newname); } + + bool selfNormalized() const override { return true; } + + inline bool canComputeBatchWithCuda() const override { return true; } + + void computeBatch(double *output, size_t nEvents, + RooFit::Detail::DataMap const &dataMap) const override + { + _prodPdf->calculateBatch(this, *_cache, output, nEvents, dataMap); + } + + ExtendMode extendMode() const override { return _prodPdf->extendMode(); } + double expectedEvents(const RooArgSet * /*nset*/) const override { return _prodPdf->expectedEvents(&_normSet); } + std::unique_ptr createExpectedEventsFunc(const RooArgSet * /*nset*/) const override + { + return _prodPdf->createExpectedEventsFunc(&_normSet); + } + + // Analytical Integration handling + bool forceAnalyticalInt(const RooAbsArg &dep) const override { return _prodPdf->forceAnalyticalInt(dep); } + Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, + const char *rangeName = nullptr) const override + { + return _prodPdf->getAnalyticalIntegralWN(allVars, analVars, normSet, rangeName); + } + Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &numVars, const char *rangeName = nullptr) const override + { + return _prodPdf->getAnalyticalIntegral(allVars, numVars, rangeName); + } + double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName) const override + { + return _prodPdf->analyticalIntegralWN(code, normSet, rangeName); + } + double analyticalIntegral(Int_t code, const char *rangeName = nullptr) const override + { + return _prodPdf->analyticalIntegral(code, rangeName); + } + +private: + void initialize() + { + _cache = _prodPdf->createCacheElem(&_normSet, nullptr); + auto &cache = *_cache; + + // The actual servers for a given normalization set depend on whether the + // cache is rearranged or not. See RooProdPdf::calculateBatch to see + // which args in the cache are used directly. + if (cache._isRearranged) { + _servers.add(*cache._rearrangedNum); + _servers.add(*cache._rearrangedDen); + } else { + for (std::size_t i = 0; i < cache._partList.size(); ++i) { + _servers.add(cache._partList[i]); + } + } + } + + double evaluate() const override { return _prodPdf->calculate(*_cache); } + + RooArgSet _normSet; + std::unique_ptr _cache; + RooSetProxy _servers; + std::unique_ptr _prodPdf; +}; + +std::unique_ptr +RooProdPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + if (ctx.likelihoodMode()) { + auto binnedInfo = RooHelpers::getBinnedL(*this); + if (binnedInfo.binnedPdf && binnedInfo.binnedPdf != this) { + return binnedInfo.binnedPdf->compileForNormSet(normSet, ctx); + } + } + + std::unique_ptr prodPdfClone{static_cast(this->Clone())}; + ctx.markAsCompiled(*prodPdfClone); + + for (const auto server : prodPdfClone->servers()) { + auto nsetForServer = fillNormSetForServer(normSet, *server); + RooArgSet const &nset = nsetForServer ? *nsetForServer : normSet; + + RooArgSet depList; + server->getObservables(&nset, depList); + + ctx.compileServer(*server, *prodPdfClone, depList); + } + + auto fixedProdPdf = std::make_unique(std::move(prodPdfClone), normSet); + ctx.markAsCompiled(*fixedProdPdf); + + return fixedProdPdf; } diff --git a/roofit/roofitcore/src/RooProduct.cxx b/roofit/roofitcore/src/RooProduct.cxx index 9b807e194b371..743460fe12b7d 100644 --- a/roofit/roofitcore/src/RooProduct.cxx +++ b/roofit/roofitcore/src/RooProduct.cxx @@ -216,12 +216,12 @@ Int_t RooProduct::getPartIntList(const RooArgSet* iset, const char *isetRange) c // check if we already have integrals for this combination of factors Int_t sterileIndex(-1); CacheElem* cache = (CacheElem*) _cacheMgr.getObj(iset,iset,&sterileIndex,RooNameReg::ptr(isetRange)); - if (cache!=0) { + if (cache!=nullptr) { Int_t code = _cacheMgr.lastIndex(); return code; } - ProdMap* map = groupProductTerms(*iset); + std::unique_ptr map{groupProductTerms(*iset)}; cxcoutD(Integration) << "RooProduct::getPartIntList(" << GetName() << ") groupProductTerms returned map" ; if (dologD(Integration)) { @@ -237,31 +237,31 @@ Int_t RooProduct::getPartIntList(const RooArgSet* iset, const char *isetRange) c delete iter->second ; } - delete map ; return -1; // RRI caller will zero analVars if return code = 0.... } cache = new CacheElem(); for (ProdMap::const_iterator i = map->begin();i!=map->end();++i) { - RooAbsReal *term(0); + RooAbsReal *term(nullptr); if (i->second->getSize()>1) { // create a RooProd for this subexpression const char *name = makeFPName("SUBPROD_",*i->second); - term = new RooProduct(name,name,*i->second); - cache->_ownedList.addOwned(*term); + auto ownedTerm = std::make_unique(name,name,*i->second); + term = ownedTerm.get(); + cache->_ownedList.addOwned(std::move(ownedTerm)); cxcoutD(Integration) << "RooProduct::getPartIntList(" << GetName() << ") created subexpression " << term->GetName() << endl; } else { assert(i->second->getSize()==1); term = static_cast(i->second->at(0)); } - assert(term!=0); + assert(term!=nullptr); if (i->first->empty()) { // check whether we need to integrate over this term or not... cache->_prodList.add(*term); cxcoutD(Integration) << "RooProduct::getPartIntList(" << GetName() << ") adding simple factor " << term->GetName() << endl; } else { - RooAbsReal *integral = term->createIntegral(*i->first,isetRange); + std::unique_ptr integral{term->createIntegral(*i->first,isetRange)}; cache->_prodList.add(*integral); - cache->_ownedList.addOwned(*integral); cxcoutD(Integration) << "RooProduct::getPartIntList(" << GetName() << ") adding integral for " << term->GetName() << " : " << integral->GetName() << endl; + cache->_ownedList.addOwned(std::move(integral)); } } // add current set-up to cache, and return index.. @@ -274,7 +274,6 @@ Int_t RooProduct::getPartIntList(const RooArgSet* iset, const char *isetRange) c delete iter->first ; delete iter->second ; } - delete map ; return code; } @@ -305,7 +304,7 @@ double RooProduct::analyticalIntegral(Int_t code, const char* rangeName) const { // note: rangeName implicit encoded in code: see _cacheMgr.setObj in getPartIntList... CacheElem *cache = (CacheElem*) _cacheMgr.getObjByIndex(code-1); - if (cache==0) { + if (cache==nullptr) { // cache got sterilized, trigger repopulation of this slot, then try again... std::unique_ptr vars( getParameters(RooArgSet()) ); RooArgSet iset = _cacheMgr.selectFromSet2(*vars, code-1); @@ -313,7 +312,7 @@ double RooProduct::analyticalIntegral(Int_t code, const char* rangeName) const assert(code==code2); // must have revived the right (sterilized) slot... return analyticalIntegral(code2,rangeName); } - assert(cache!=0); + assert(cache!=nullptr); return calculate(cache->_prodList); } @@ -376,7 +375,7 @@ double RooProduct::evaluate() const } -void RooProduct::computeBatch(cudaStream_t* /*stream*/, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooProduct::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { for (unsigned int i = 0; i < nEvents; ++i) { output[i] = 1.; @@ -416,7 +415,7 @@ std::list* RooProduct::binBoundaries(RooAbsRealLValue& obs, double xlo, } } - return 0 ; + return nullptr ; } @@ -452,7 +451,7 @@ std::list* RooProduct::plotSamplingHint(RooAbsRealLValue& obs, double xl } } - return 0 ; + return nullptr ; } @@ -493,9 +492,19 @@ void RooProduct::setCacheAndTrackHints(RooArgSet& trackNodes) } } +//////////////////////////////////////////////////////////////////////////////// - - +void RooProduct::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + std::string result; + // Build a (node1 * node2 * node3 * ...) like expression. + result = '('; + for (RooAbsArg* item : _compRSet) { + result += ctx.getResult(*item) + "*"; + } + result.back() = ')'; + ctx.addResult(this, result); +} //////////////////////////////////////////////////////////////////////////////// /// Customized printing of arguments of a RooProduct to more intuitively reflect the contents of the @@ -525,29 +534,50 @@ void RooProduct::ioStreamerPass2() { RooAbsReal::ioStreamerPass2(); // call the baseclass method if(numProxies() < 2) { - throw std::runtime_error("RooProduct::ioStreamerPass2(): the number of proxies in the proxy list should be at leat 2!"); + throw std::runtime_error("RooProduct::ioStreamerPass2(): the number of proxies in the proxy list should be at least 2!"); } // If the proxy data members are evolved by schema evolution, the proxy list // that references them will contain null pointers because the evolved // members are only created after the proxy list. That's why we have to set - // them manually in that case. But to make sure we don't overwrite valid - // proxies, an exception will be thrown if the proxy list constains - // unexpected values. + // them manually in that case. RooAbsProxy * p0 = getProxy(0); - if(p0 != &_compRSet) { - if(p0) { - throw std::runtime_error("RooProduct::ioStreamerPass2(): the first proxy unexpectedly wasn't the compRSet!"); - } + if(p0 == nullptr) { _proxyList.AddAt(&_compRSet, 0); + p0 = &_compRSet; } RooAbsProxy * p1 = getProxy(1); - if(p1 != &_compCSet) { - if(p1) { - throw std::runtime_error("RooProduct::ioStreamerPass2(): the second proxy unexpectedly wasn't the compCSet!"); - } + if(p1 == nullptr) { _proxyList.AddAt(&_compCSet, 1); + p1 = &_compCSet; } + + // If the proxies in the proxy list still don't correspond to _compRSet and + // _compCSet, it's time to print errors. And try to recover. + auto expectProxyIs = [this](std::size_t idx, RooAbsProxy * proxyInArg, RooListProxy * ourProxy, const char* memberName) { + if(proxyInArg != ourProxy) { + // From experience, it's rather the members of the RooProduct that is + // still correct in these inconsistent cases. That's why we try to + // recover by setting the proxy in the _proxyList to be equal to the + // member proxy. But that might be wrong, so it's important to warn the + // user anyway. + _proxyList.RemoveAt(idx); + _proxyList.AddAt(ourProxy, idx); + std::stringstream ss; + ss << "Problem when reading RooProduct instance \"" << GetName() << "\"!\n" + << " _proxyList[" << idx << "] was expected to be equal to " << memberName << ", but it's not.\n" + << " - proxyList[" << idx << "] : "; + proxyInArg->print(ss, true); + ss << "\n - " << memberName << " : " ; + ourProxy->print(ss, true); + ss << "\n RooFit will resolve this inconsistency by making _proxyList[" << idx << "] point to " << memberName + << "."; + coutW(LinkStateMgmt) << ss.str() << std::endl; + } + }; + + expectProxyIs(0, p0, &_compRSet, "_compRSet"); + expectProxyIs(1, p1, &_compCSet, "_compCSet"); } diff --git a/roofit/roofitcore/src/RooProfileLL.cxx b/roofit/roofitcore/src/RooProfileLL.cxx index 8c91430614c8d..660867d6628d4 100644 --- a/roofit/roofitcore/src/RooProfileLL.cxx +++ b/roofit/roofitcore/src/RooProfileLL.cxx @@ -43,11 +43,7 @@ ClassImp(RooProfileLL); RooAbsReal("RooProfileLL","RooProfileLL"), _nll(), _obs("paramOfInterest","Parameters of interest",this), - _par("nuisanceParam","Nuisance parameters",this,false,false), - _startFromMin(true), - _absMinValid(false), - _absMin(0), - _neval(0) + _par("nuisanceParam","Nuisance parameters",this,false,false) { } @@ -63,11 +59,7 @@ RooProfileLL::RooProfileLL(const char *name, const char *title, RooAbsReal(name,title), _nll("input","-log(L) function",this,nllIn), _obs("paramOfInterest","Parameters of interest",this), - _par("nuisanceParam","Nuisance parameters",this,false,false), - _startFromMin(true), - _absMinValid(false), - _absMin(0), - _neval(0) + _par("nuisanceParam","Nuisance parameters",this,false,false) { // Determine actual parameters and observables nllIn.getObservables(&observables, _obs) ; @@ -121,7 +113,7 @@ const RooArgSet& RooProfileLL::bestFitObs() const /// Return profile of original function in terms of stated parameters /// of interest rather than profiling recursively. -RooAbsReal* RooProfileLL::createProfile(const RooArgSet& paramsOfInterest) +RooFit::OwningPtr RooProfileLL::createProfile(const RooArgSet& paramsOfInterest) { return nll().createProfile(paramsOfInterest) ; } diff --git a/roofit/roofitcore/src/RooProjectedPdf.cxx b/roofit/roofitcore/src/RooProjectedPdf.cxx index 6452b12f557b2..92953b171c0ad 100644 --- a/roofit/roofitcore/src/RooProjectedPdf.cxx +++ b/roofit/roofitcore/src/RooProjectedPdf.cxx @@ -62,7 +62,7 @@ RooProjectedPdf::RooProjectedPdf() : _cacheMgr(this,10) // servers are. Integration observables will be shape servers, the other // servers are value servers. int code; - auto proj = getProjection(&intObs, nullptr, 0, code); + auto proj = getProjection(&intObs, nullptr, nullptr, code); for(RooAbsArg* server : proj->servers()) { if(server->isShapeServer(*proj)) { intobs.add(*server); @@ -95,7 +95,7 @@ double RooProjectedPdf::evaluate() const { // Calculate current unnormalized value of object int code ; - return getProjection(&intobs, _normSet, 0, code)->getVal() ; + return getProjection(&intobs, _normSet, normRange(), code)->getVal() ; } @@ -124,7 +124,7 @@ const RooAbsReal* RooProjectedPdf::getProjection(const RooArgSet* iset, const Ro } auto cache = new CacheElem ; - cache->_projection = std::unique_ptr{intpdf.arg().createIntegral(iset?*iset:RooArgSet(),&nset2,0,rangeName)}; + cache->_projection = std::unique_ptr{intpdf.arg().createIntegral(iset?*iset:RooArgSet(),&nset2,nullptr,rangeName)}; code = _cacheMgr.setObj(iset, nset, cache, RooNameReg::ptr(rangeName)) ; @@ -277,3 +277,16 @@ void RooProjectedPdf::CacheElem::printCompactTreeHook(std::ostream& os, const ch os << indent << "RooProjectedPdf end projection cache" << std::endl ; } } + + +std::unique_ptr +RooProjectedPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + RooArgSet nset2; + intpdf->getObservables(&normSet, nset2); + nset2.add(intobs); + + auto newArg = std::unique_ptr{intpdf->createIntegral(intobs, &nset2)}; + ctx.markAsCompiled(*newArg); + return newArg; +} diff --git a/roofit/roofitcore/src/RooProofDriverSelector.cxx b/roofit/roofitcore/src/RooProofDriverSelector.cxx index e33a487d7bc0f..ee832672defc0 100644 --- a/roofit/roofitcore/src/RooProofDriverSelector.cxx +++ b/roofit/roofitcore/src/RooProofDriverSelector.cxx @@ -41,7 +41,7 @@ using namespace std; void RooProofDriverSelector::SlaveBegin(TTree * /*tree*/) { // Retrieve study pack - _pkg=0 ; + _pkg=nullptr ; if (fInput) { for (auto * tmp : dynamic_range_cast(*fInput)) { if (tmp) { @@ -49,7 +49,7 @@ void RooProofDriverSelector::SlaveBegin(TTree * /*tree*/) } } } - if (_pkg==0) { + if (_pkg==nullptr) { cout << "RooProofDriverSelector::SlaveBegin() no RooStudyPackage found, aborting process" << endl ; fStatus = kAbortProcess ; } else { diff --git a/roofit/roofitcore/src/RooQuasiRandomGenerator.cxx b/roofit/roofitcore/src/RooQuasiRandomGenerator.cxx index 5cd45fb3c1149..48dddaa5525e3 100644 --- a/roofit/roofitcore/src/RooQuasiRandomGenerator.cxx +++ b/roofit/roofitcore/src/RooQuasiRandomGenerator.cxx @@ -93,7 +93,7 @@ bool RooQuasiRandomGenerator::generate(UInt_t dimension, double vector[]) * the count is advanced. */ Int_t r(0),c(_sequenceCount); - while(1) { + while(true) { if((c % 2) == 1) { ++r; c /= 2; @@ -200,7 +200,7 @@ void RooQuasiRandomGenerator::calculateV(const int px[], int px_degree, int pb[], int * pb_degree, int v[], int maxv) { const int nonzero_element = 1; /* nonzero element of Z_2 */ - const int arbitrary_element = 1; /* arbitray element of Z_2 */ + const int arbitrary_element = 1; /* arbitrary element of Z_2 */ /* The polynomial ph is px**(J-1), which is the value of B on arrival. * In section 3.3, the values of Hi are defined with a minus sign: diff --git a/roofit/roofitcore/src/RooRandom.cxx b/roofit/roofitcore/src/RooRandom.cxx index ccbba1be2b211..1d4f98b969142 100644 --- a/roofit/roofitcore/src/RooRandom.cxx +++ b/roofit/roofitcore/src/RooRandom.cxx @@ -35,8 +35,8 @@ ClassImp(RooRandom); ; -TRandom* RooRandom::_theGenerator = 0; -RooQuasiRandomGenerator* RooRandom::_theQuasiGenerator = 0; +TRandom* RooRandom::_theGenerator = nullptr; +RooQuasiRandomGenerator* RooRandom::_theQuasiGenerator = nullptr; RooRandom::Guard RooRandom::guard; //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roofitcore/src/RooRandomizeParamMCSModule.cxx b/roofit/roofitcore/src/RooRandomizeParamMCSModule.cxx index 7384dfbee0ce2..046e3f5c94931 100644 --- a/roofit/roofitcore/src/RooRandomizeParamMCSModule.cxx +++ b/roofit/roofitcore/src/RooRandomizeParamMCSModule.cxx @@ -55,7 +55,7 @@ ClassImp(RooRandomizeParamMCSModule); /// Constructor RooRandomizeParamMCSModule::RooRandomizeParamMCSModule() : - RooAbsMCStudyModule("RooRandomizeParamMCSModule","RooRandomizeParamMCSModule"), _data(0) + RooAbsMCStudyModule("RooRandomizeParamMCSModule","RooRandomizeParamMCSModule"), _data(nullptr) { } @@ -68,7 +68,7 @@ RooRandomizeParamMCSModule::RooRandomizeParamMCSModule(const RooRandomizeParamMC RooAbsMCStudyModule(other), _unifParams(other._unifParams), _gausParams(other._gausParams), - _data(0) + _data(nullptr) { } @@ -244,10 +244,9 @@ bool RooRandomizeParamMCSModule::initializeInstance() uiter->_param = actualPar ; // Add variable to summary dataset to hold generator value - TString parName = Form("%s_gen",uiter->_param->GetName()) ; - TString parTitle = Form("%s as generated",uiter->_param->GetTitle()) ; - RooRealVar* par_gen = new RooRealVar(parName.Data(),parTitle.Data(),0) ; - _genParSet.addOwned(*par_gen) ; + std::string parName = std::string(uiter->_param->GetName()) + "_gen"; + std::string parTitle = std::string(uiter->_param->GetTitle()) + " as generated"; + _genParSet.addOwned(std::make_unique(parName.c_str(),parTitle.c_str(),0)); } // Loop over all gaussian smearing parameters @@ -264,10 +263,9 @@ bool RooRandomizeParamMCSModule::initializeInstance() giter->_param = actualPar ; // Add variable to summary dataset to hold generator value - TString parName = Form("%s_gen",giter->_param->GetName()) ; - TString parTitle = Form("%s as generated",giter->_param->GetTitle()) ; - RooRealVar* par_gen = new RooRealVar(parName.Data(),parTitle.Data(),0) ; - _genParSet.addOwned(*par_gen) ; + std::string parName = std::string(giter->_param->GetName()) + "_gen"; + std::string parTitle = std::string(giter->_param->GetTitle()) + " as generated"; + _genParSet.addOwned(std::make_unique(parName.c_str(),parTitle.c_str(),0)); } @@ -290,10 +288,9 @@ bool RooRandomizeParamMCSModule::initializeInstance() // Add variables to summary dataset to hold generator values for(auto * param : static_range_cast(usiter->_pset)) { - TString parName = Form("%s_gen",param->GetName()) ; - TString parTitle = Form("%s as generated",param->GetTitle()) ; - RooRealVar* par_gen = new RooRealVar(parName.Data(),parTitle.Data(),0) ; - _genParSet.addOwned(*par_gen) ; + std::string parName = std::string(param->GetName()) + "_gen"; + std::string parTitle = std::string(param->GetTitle()) + " as generated"; + _genParSet.addOwned(std::make_unique(parName.c_str(),parTitle.c_str(),0)); } } @@ -317,10 +314,9 @@ bool RooRandomizeParamMCSModule::initializeInstance() // Add variables to summary dataset to hold generator values for(auto * param : static_range_cast(ugiter->_pset)) { - TString parName = Form("%s_gen",param->GetName()) ; - TString parTitle = Form("%s as generated",param->GetTitle()) ; - RooRealVar* par_gen = new RooRealVar(parName.Data(),parTitle.Data(),0) ; - _genParSet.addOwned(*par_gen) ; + std::string parName = std::string(param->GetName()) + "_gen"; + std::string parTitle = std::string(param->GetTitle()) + " as generated"; + _genParSet.addOwned(std::make_unique(parName.c_str(),parTitle.c_str(),0)); } } @@ -383,7 +379,7 @@ bool RooRandomizeParamMCSModule::processBeforeGen(Int_t /*sampleNum*/) << usiter->_pset << " in range [" << usiter->_lo << "," << usiter->_hi << "], chosen sum value for this sample is " << newVal << endl ; - // Determine original value of sum and calculate per-component scale factor to obtain new valye for sum + // Determine original value of sum and calculate per-component scale factor to obtain new value for sum RooAddition sumVal("sumVal","sumVal",usiter->_pset) ; double compScaleFactor = newVal/sumVal.getVal() ; @@ -406,7 +402,7 @@ bool RooRandomizeParamMCSModule::processBeforeGen(Int_t /*sampleNum*/) << " with a mean of " << gsiter->_mean << " and a width of " << gsiter->_sigma << ", chosen value for this sample is " << newVal << endl ; - // Determine original value of sum and calculate per-component scale factor to obtain new valye for sum + // Determine original value of sum and calculate per-component scale factor to obtain new value for sum RooAddition sumVal("sumVal","sumVal",gsiter->_pset) ; double compScaleFactor = newVal/sumVal.getVal() ; diff --git a/roofit/roofitcore/src/RooRangeBoolean.cxx b/roofit/roofitcore/src/RooRangeBoolean.cxx index 5ab18ff2d01f2..5e45ec33f8437 100644 --- a/roofit/roofitcore/src/RooRangeBoolean.cxx +++ b/roofit/roofitcore/src/RooRangeBoolean.cxx @@ -23,7 +23,7 @@ RooRangeBoolean **/ #include "Riostream.h" -#include +#include #include "RooRangeBoolean.h" #include "RooAbsReal.h" @@ -79,7 +79,7 @@ RooRangeBoolean::~RooRangeBoolean() //////////////////////////////////////////////////////////////////////////////// -/// Return 1 if x is in range, zero otherwis +/// Return 1 if x is in range, zero otherwise. double RooRangeBoolean::evaluate() const { @@ -97,7 +97,7 @@ double RooRangeBoolean::evaluate() const std::list* RooRangeBoolean::plotSamplingHint(RooAbsRealLValue& obs, double /*xlo*/, double /*xhi*/) const { if (string(obs.GetName())!=_x.arg().GetName()) { - return 0 ; + return nullptr ; } list* hint = new list ; diff --git a/roofit/roofitcore/src/RooRatio.cxx b/roofit/roofitcore/src/RooRatio.cxx index 6cacf6378dfc0..01e5ae7c7aa0d 100644 --- a/roofit/roofitcore/src/RooRatio.cxx +++ b/roofit/roofitcore/src/RooRatio.cxx @@ -32,7 +32,7 @@ A RooRatio represents the ratio of two given RooAbsReal objects. #include "TMath.h" -#include +#include ClassImp(RooRatio); @@ -109,8 +109,7 @@ RooRatio::RooRatio(const RooRatio &other, const char *name) //////////////////////////////////////////////////////////////////////////////// /// Evaluate in batch mode. -void RooRatio::computeBatch(cudaStream_t* stream, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const +void RooRatio::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { - auto dispatch = stream ? RooBatchCompute::dispatchCUDA : RooBatchCompute::dispatchCPU; - dispatch->compute(stream, RooBatchCompute::Ratio, output, nEvents, {dataMap.at(_numerator), dataMap.at(_denominator)}); + RooBatchCompute::compute(dataMap.config(this), RooBatchCompute::Ratio, output, nEvents, {dataMap.at(_numerator), dataMap.at(_denominator)}); } diff --git a/roofit/roofitcore/src/RooRealAnalytic.cxx b/roofit/roofitcore/src/RooRealAnalytic.cxx deleted file mode 100644 index 1f78c256db816..0000000000000 --- a/roofit/roofitcore/src/RooRealAnalytic.cxx +++ /dev/null @@ -1,74 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooRealAnalytic.cxx -\class RooRealAnalytic -\ingroup Roofitcore - -Lightweight RooAbsFunc interface adaptor that binds an analytic integral of a -RooAbsReal object (specified by a code) to a set of dependent variables. -**/ - -#include "RooRealAnalytic.h" -#include "RooAbsRealLValue.h" - -#include - -using namespace std; - -ClassImp(RooRealAnalytic); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate our analytic integral at the specified values of the dependents. - -double RooRealAnalytic::operator()(const double xvector[]) const -{ - assert(isValid()); - loadValues(xvector); - _ncall++ ; - return _code ? _func->analyticalIntegralWN(_code,_nset,_rangeName?_rangeName->GetName():0):_func->getVal(_nset) ; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate the analytic integral of the function at the specified values of the dependents. -RooSpan RooRealAnalytic::getValues(std::vector> coordinates) const { - assert(isValid()); - _ncall += coordinates.front().size(); - - if (!_batchBuffer) - _batchBuffer.reset(new std::vector()); - _batchBuffer->resize(coordinates.front().size()); - RooSpan results(*_batchBuffer); - - for (std::size_t i=0; i < coordinates.front().size(); ++i) { - for (unsigned int dim=0; dim < coordinates.size(); ++dim) { - _vars[dim]->setVal(coordinates[dim][i]); - } - - if (_code == 0) { - results[i] = _func->getVal(_nset); - } else { - results[i] = _func->analyticalIntegralWN(_code,_nset,_rangeName?_rangeName->GetName():0); - } - } - - return results; -} - diff --git a/roofit/roofitcore/src/RooRealBinding.cxx b/roofit/roofitcore/src/RooRealBinding.cxx index ed46048997181..0631781a644e0 100644 --- a/roofit/roofitcore/src/RooRealBinding.cxx +++ b/roofit/roofitcore/src/RooRealBinding.cxx @@ -30,7 +30,6 @@ of its servers and present it as a simple array oriented interface. #include "RooAbsRealLValue.h" #include "RooNameReg.h" #include "RooMsgService.h" -#include "RunContext.h" #include @@ -53,7 +52,7 @@ ClassImp(RooRealBinding); /// range. RooRealBinding::RooRealBinding(const RooAbsReal& func, const RooArgSet &vars, const RooArgSet* nset, bool clipInvalid, const TNamed* rangeName) : - RooAbsFunc(vars.getSize()), _func(&func), _vars(), _nset(nset), _clipInvalid(clipInvalid), _xsave(0), _rangeName(rangeName), _funcSave(0) + RooAbsFunc(vars.getSize()), _func(&func), _vars(), _nset(nset), _clipInvalid(clipInvalid), _rangeName(rangeName), _funcSave(0) { // check that all of the arguments are real valued and store them for (unsigned int index=0; index < vars.size(); ++index) { @@ -86,20 +85,13 @@ RooRealBinding::RooRealBinding(const RooAbsReal& func, const RooArgSet &vars, co RooRealBinding::RooRealBinding(const RooRealBinding& other, const RooArgSet* nset) : RooAbsFunc(other), _func(other._func), _vars(other._vars), _nset(nset?nset:other._nset), _xvecValid(other._xvecValid), - _clipInvalid(other._clipInvalid), _xsave(0), _rangeName(other._rangeName), _funcSave(other._funcSave) + _clipInvalid(other._clipInvalid), _rangeName(other._rangeName), _funcSave(other._funcSave) { } -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooRealBinding::~RooRealBinding() -{ - if (_xsave) delete[] _xsave ; -} - +RooRealBinding::~RooRealBinding() = default; //////////////////////////////////////////////////////////////////////////////// @@ -107,16 +99,15 @@ RooRealBinding::~RooRealBinding() void RooRealBinding::saveXVec() const { - if (!_xsave) { - _xsave = new double[getDimension()] ; - RooArgSet* comps = _func->getComponents() ; + if (_xsave.empty()) { + _xsave.resize(getDimension()); + std::unique_ptr comps{_func->getComponents()}; for (auto* arg : dynamic_range_cast(*comps)) { if (arg) { _compList.push_back(static_cast(arg)) ; - _compSave.push_back(0) ; + _compSave.push_back(0.0) ; } } - delete comps ; } _funcSave = _func->_value ; @@ -140,7 +131,7 @@ void RooRealBinding::saveXVec() const void RooRealBinding::restoreXVec() const { - if (!_xsave) { + if (_xsave.empty()) { return ; } _func->_value = _funcSave ; @@ -193,81 +184,6 @@ double RooRealBinding::operator()(const double xvector[]) const } -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate the bound object at all locations indicated by the data in `coordinates`. -/// If `_clipInvalid` is set, the function is set to zero at all points in the arguments -/// that are not within the range of the observables. -/// \param coordinates Vector of spans that contain the points where the function should be evaluated. -/// The ordinal position in the vector corresponds to the ordinal position in the set of -/// {observables, parameters} that were passed to the constructor. -/// The spans can either have a size of `n`, in which case a batch of `n` results is returned, or they can have -/// a size of 1. In the latter case, the value in the span is broadcast to all `n` events. -/// \return Batch of function values for each coordinate given in the input spans. If a parameter is invalid, i.e., -/// out of its range, an empty span is returned. If an observable is invalid, the function value is 0. -RooSpan RooRealBinding::getValues(std::vector> coordinates) const { - assert(isValid()); - _ncall += coordinates.front().size(); - - bool parametersValid = true; - - // Use _evalData to hold on to memory between integration calls - if (!_evalData) { - _evalData.reset(new RooBatchCompute::RunContext()); - } else { - _evalData->clear(); - } - _evalData->rangeName = RooNameReg::str(_rangeName); - - for (unsigned int dim=0; dim < coordinates.size(); ++dim) { - const RooSpan& values = coordinates[dim]; - RooAbsRealLValue& var = *_vars[dim]; - _evalData->spans[&var] = values; - if (_clipInvalid && values.size() == 1) { - // The argument is a parameter of the function. Check it - // here, so we can do early stopping if it's invalid. - parametersValid &= var.isValidReal(values[0]); - assert(values.size() == 1); - } - } - - if (!parametersValid) - return {}; - - auto results = getValuesOfBoundFunction(*_evalData); - - if (_clipInvalid) { - RooSpan resultsWritable(_evalData->getWritableBatch(_func)); - assert(results.data() == resultsWritable.data()); - assert(results.size() == resultsWritable.size()); - - // Run through all events, and check if the given coordinates are valid: - for (std::size_t coord=0; coord < coordinates.size(); ++coord) { - if (coordinates[coord].size() == 1) - continue; // We checked all parameters above - - for (std::size_t evt=0; evt < coordinates[coord].size(); ++evt) { - if (!_vars[coord]->isValidReal(coordinates[coord][evt])) - resultsWritable[evt] = 0.; - } - } - } - - return results; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate the bound object at all locations indicated by the data in `evalData`. -/// \see RooAbsReal::getValues(). -/// \param[in,out] evalData Struct with spans pointing to the data to be used for evaluation. -/// The spans can either have a size of `n`, in which case a batch of `n` results is returned, or they can have -/// a size of 1. In the latter case, the value in the span is broadcast to all `n` events. -/// \return Batch of function values for each coordinate given in the input spans. -RooSpan RooRealBinding::getValuesOfBoundFunction(RooBatchCompute::RunContext& evalData) const { - return _func->getValues(evalData, _nset); -} - - //////////////////////////////////////////////////////////////////////////////// /// Return lower limit on i-th variable diff --git a/roofit/roofitcore/src/RooRealConstant.cxx b/roofit/roofitcore/src/RooRealConstant.cxx index f95c675b1e789..3a7b07b5e329b 100644 --- a/roofit/roofitcore/src/RooRealConstant.cxx +++ b/roofit/roofitcore/src/RooRealConstant.cxx @@ -30,7 +30,7 @@ RooRealConstant keeps an internal database of previously created RooRealVar objects and will recycle them as appropriate. **/ -#include +#include #include #include "RooRealConstant.h" #include "RooConstVar.h" @@ -59,11 +59,12 @@ RooConstVar& RooRealConstant::value(double value) std::ostringstream s ; s << value ; - auto var = new RooConstVar(s.str().c_str(),s.str().c_str(),value) ; + auto var = std::make_unique(s.str().c_str(),s.str().c_str(),value); var->setAttribute("RooRealConstant_Factory_Object",true) ; - constDB().addOwned(*var) ; + RooConstVar &varRef = *var; + constDB().addOwned(std::move(var)); - return *var ; + return varRef; } @@ -72,12 +73,13 @@ RooConstVar& RooRealConstant::value(double value) RooConstVar& RooRealConstant::removalDummy() { - RooConstVar* var = new RooConstVar("REMOVAL_DUMMY","REMOVAL_DUMMY",1) ; + auto var = std::make_unique("REMOVAL_DUMMY","REMOVAL_DUMMY",1) ; var->setAttribute("RooRealConstant_Factory_Object",true) ; var->setAttribute("REMOVAL_DUMMY") ; - constDB().addOwned(*var) ; + RooConstVar &varRef = *var; + constDB().addOwned(std::move(var)); - return *var ; + return varRef; } diff --git a/roofit/roofitcore/src/RooRealIntegral.cxx b/roofit/roofitcore/src/RooRealIntegral.cxx index c29ad9e62a5ae..93e533316b065 100644 --- a/roofit/roofitcore/src/RooRealIntegral.cxx +++ b/roofit/roofitcore/src/RooRealIntegral.cxx @@ -35,7 +35,6 @@ integration is performed in the various implementations of the RooAbsIntegrator #include "RooAbsRealLValue.h" #include "RooAbsCategoryLValue.h" #include "RooRealBinding.h" -#include "RooRealAnalytic.h" #include "RooInvTransform.h" #include "RooSuperCategory.h" #include "RooNumIntFactory.h" @@ -227,7 +226,7 @@ Int_t RooRealIntegral::_cacheAllNDim(2) ; RooRealIntegral::RooRealIntegral() { - TRACE_CREATE + TRACE_CREATE; } @@ -240,13 +239,18 @@ RooRealIntegral::RooRealIntegral() /// The other integrations are performed numerically. The optional /// config object prescribes how these numeric integrations are configured. /// - +/// \Note If pdf component selection was globally overridden to always include +/// all components (either with RooAbsReal::globalSelectComp(bool) or a +/// RooAbsReal::GlobalSelectComponentRAII), then any created integral will +/// ignore component selections during its lifetime. This is especially useful +/// when creating normalization or projection integrals. RooRealIntegral::RooRealIntegral(const char *name, const char *title, const RooAbsReal& function, const RooArgSet& depList, const RooArgSet* funcNormSet, const RooNumIntConfig* config, const char* rangeName) : RooAbsReal(name,title), _valid(true), + _respectCompSelect{!_globalSelectComp}, _sumList("!sumList","Categories to be summed numerically",this,false,false), _intList("!intList","Variables to be integrated numerically",this,false,false), _anaList("!anaList","Variables to be integrated analytically",this,false,false), @@ -263,7 +267,7 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, // lvalues that are higher in the expression tree // // C) Check for dependents that the PDF insists on integrating - // analytically iself + // analytically itself // // D) Make list of servers that can be integrated analytically // Add all parameters/dependents as value/shape servers @@ -318,10 +322,10 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, _valid= false; } if (!function.dependsOn(*arg)) { - RooAbsArg* argClone = (RooAbsArg*) arg->Clone() ; - _facListOwned.addOwned(*argClone) ; + std::unique_ptr argClone{static_cast(arg->Clone())}; _facList.add(*argClone) ; addServer(*argClone,false,true) ; + _facListOwned.addOwned(std::move(argClone)); } } @@ -357,9 +361,10 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, } exclLVBranches.remove(depList,true,true) ; - // Initial fill of list of LValue leaf servers (put in intDepList) + // Initial fill of list of LValue leaf servers (put in intDepList, but the + // instances that are in the actual computation graph of the function) RooArgSet exclLVServers("exclLVServers") ; - exclLVServers.add(intDepList) ; + function.getObservables(&intDepList, exclLVServers); // Obtain mutual exclusive dependence by iterative reduction bool converged(false) ; @@ -417,7 +422,7 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * C) Check for dependents that the PDF insists on integrating * - // analytically iself * + // analytically itself * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * RooArgSet anIntOKDepList ; @@ -447,14 +452,9 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, // * E) interact with function to make list of objects actually integrated analytically * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - RooArgSet anIntDepList ; - - RooArgSet anaSet{ _anaList, Form("UniqueCloneOf_%s",_anaList.GetName())}; - _mode = function.getAnalyticalIntegralWN(anIntOKDepList,anaSet,_funcNormSet.get(),RooNameReg::str(_rangeName)) ; - _anaList.removeAll() ; - _anaList.add(anaSet); + _mode = function.getAnalyticalIntegralWN(anIntOKDepList,_anaList,_funcNormSet.get(),RooNameReg::str(_rangeName)) ; - // Avoid confusion -- if mode is zero no analytical integral is defined regardless of contents of _anaListx + // Avoid confusion -- if mode is zero no analytical integral is defined regardless of contents of _anaList if (_mode==0) { _anaList.removeAll() ; } @@ -600,7 +600,7 @@ RooRealIntegral::RooRealIntegral(const char *name, const char *title, } } - TRACE_CREATE + TRACE_CREATE; } @@ -690,22 +690,24 @@ bool RooRealIntegral::initNumIntegrator() const // All done if there are no arguments to integrate numerically if(_intList.empty()) return true; - // Bind the appropriate analytic integral (specified by _mode) of our RooRealVar object to + // Bind the appropriate analytic integral of our RooRealVar object to // those of its arguments that will be integrated out numerically. if(_mode != 0) { - _numIntegrand = std::make_unique(*_function,_intList,_mode,funcNormSet(),_rangeName); + std::unique_ptr analyticalPart{_function->createIntegral(_anaList, *funcNormSet(), RooNameReg::str(_rangeName))}; + _numIntegrand = std::make_unique(*analyticalPart,_intList,nullptr,false,_rangeName); + const_cast(this)->addOwnedComponents(std::move(analyticalPart)); } else { _numIntegrand = std::make_unique(*_function,_intList,funcNormSet(),false,_rangeName); } - if(0 == _numIntegrand || !_numIntegrand->isValid()) { + if(nullptr == _numIntegrand || !_numIntegrand->isValid()) { coutE(Integration) << ClassName() << "::" << GetName() << ": failed to create valid integrand." << std::endl; return false; } // Create appropriate numeric integrator using factory bool isBinned = _function->isBinnedDistribution(_intList) ; - _numIntEngine.reset(RooNumIntFactory::instance().createIntegrator(*_numIntegrand,*_iconfig,0,isBinned)); + _numIntEngine = RooNumIntFactory::instance().createIntegrator(*_numIntegrand,*_iconfig,0,isBinned); if(_numIntEngine == nullptr || !_numIntEngine->isValid()) { coutE(Integration) << ClassName() << "::" << GetName() << ": failed to create valid integrator." << std::endl; @@ -746,19 +748,22 @@ RooRealIntegral::RooRealIntegral(const RooRealIntegral& other, const char* name) _rangeName(other._rangeName), _cacheNum(false) { - _funcNormSet.reset(other._funcNormSet ? static_cast(other._funcNormSet->snapshot(false)) : nullptr); + if(other._funcNormSet) { + _funcNormSet = std::make_unique(); + other._funcNormSet->snapshot(*_funcNormSet, false); + } for (const auto arg : other._facList) { - RooAbsArg* argClone = (RooAbsArg*) arg->Clone() ; - _facListOwned.addOwned(*argClone) ; + std::unique_ptr argClone{static_cast(arg->Clone())}; _facList.add(*argClone) ; addServer(*argClone,false,true) ; + _facListOwned.addOwned(std::move(argClone)); } other._intList.snapshot(_saveInt) ; other._sumList.snapshot(_saveSum) ; - TRACE_CREATE + TRACE_CREATE; } @@ -766,13 +771,13 @@ RooRealIntegral::RooRealIntegral(const RooRealIntegral& other, const char* name) RooRealIntegral::~RooRealIntegral() { - TRACE_DESTROY + TRACE_DESTROY; } //////////////////////////////////////////////////////////////////////////////// -RooAbsReal* RooRealIntegral::createIntegral(const RooArgSet& iset, const RooArgSet* nset, const RooNumIntConfig* cfg, const char* rangeName) const +RooFit::OwningPtr RooRealIntegral::createIntegral(const RooArgSet& iset, const RooArgSet* nset, const RooNumIntConfig* cfg, const char* rangeName) const { // Handle special case of no integration with default algorithm if (iset.empty()) { @@ -786,7 +791,7 @@ RooAbsReal* RooRealIntegral::createIntegral(const RooArgSet& iset, const RooArgS isetAll.add(_anaList) ; isetAll.add(_facList) ; - const RooArgSet* newNormSet(0) ; + const RooArgSet* newNormSet(nullptr) ; std::unique_ptr tmp; if (nset && !_funcNormSet) { newNormSet = nset ; @@ -798,9 +803,7 @@ RooAbsReal* RooRealIntegral::createIntegral(const RooArgSet& iset, const RooArgS tmp->add(*_funcNormSet,true) ; newNormSet = tmp.get(); } - RooAbsReal* ret = _function->createIntegral(isetAll,newNormSet,cfg,rangeName) ; - - return ret ; + return _function->createIntegral(isetAll,newNormSet,cfg,rangeName); } @@ -817,9 +820,9 @@ double RooRealIntegral::getValV(const RooArgSet* nset) const // return _value ; // } - if (nset && nset!=_lastNSet) { - ((RooAbsReal*) this)->setProxyNormSet(nset) ; - _lastNSet = (RooArgSet*) nset ; + if (nset && nset->uniqueId().value() != _lastNormSetId) { + const_cast(this)->setProxyNormSet(nset); + _lastNormSetId = nset->uniqueId().value(); } if (isValueOrShapeDirtyAndClear()) { @@ -838,7 +841,7 @@ double RooRealIntegral::getValV(const RooArgSet* nset) const double RooRealIntegral::evaluate() const { - GlobalSelectComponentRAII selCompRAII(_globalSelectComp || !_respectCompSelect); + GlobalSelectComponentRAII selCompRAII(!_respectCompSelect); double retVal(0) ; switch (_intOperMode) { @@ -846,7 +849,7 @@ double RooRealIntegral::evaluate() const case Hybrid: { // Cache numeric integrals in >1d expensive object cache - RooDouble* cacheVal(0) ; + RooDouble* cacheVal(nullptr) ; if ((_cacheNum && !_intList.empty()) || _intList.getSize()>=_cacheAllNDim) { cacheVal = (RooDouble*) expensiveObjectCache().retrieveObject(GetName(),RooDouble::Class(),parameters()) ; } @@ -929,7 +932,7 @@ double RooRealIntegral::evaluate() const // Multiply by fit range for 'real' dependents if (arg->IsA()->InheritsFrom(RooAbsRealLValue::Class())) { RooAbsRealLValue* argLV = (RooAbsRealLValue*)arg ; - retVal *= (argLV->getMax() - argLV->getMin()) ; + retVal *= (argLV->getMax(intRange()) - argLV->getMin(intRange())) ; } // Multiply by number of states for category dependents if (arg->IsA()->InheritsFrom(RooAbsCategoryLValue::Class())) { @@ -942,7 +945,7 @@ double RooRealIntegral::evaluate() const if (dologD(Tracing)) { cxcoutD(Tracing) << "RooRealIntegral::evaluate(" << GetName() << ") anaInt = " << _anaList << " numInt = " << _intList << _sumList << " mode = " ; - switch(_mode) { + switch(_intOperMode) { case Hybrid: ccoutD(Tracing) << "Hybrid" ; break ; case Analytic: ccoutD(Tracing) << "Analytic" ; break ; case PassThrough: ccoutD(Tracing) << "PassThrough" ; break ; @@ -971,9 +974,9 @@ double RooRealIntegral::jacobianProduct() const jacProd *= arg->jacobian() ; } - // Take fabs() here: if jacobian is negative, min and max are swapped and analytical integral + // Take std::abs() here: if jacobian is negative, min and max are swapped and analytical integral // will be positive, so must multiply with positive jacobian. - return fabs(jacProd) ; + return std::abs(jacProd) ; } @@ -1083,6 +1086,18 @@ void RooRealIntegral::setAllowComponentSelection(bool allow){ _respectCompSelect = allow; } +void RooRealIntegral::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + if (!_sumList.empty() || !_intList.empty()) { + std::stringstream errorMsg; + errorMsg << "Only analytical integrals are supported for AD for class" << _function.GetName(); + coutE(Minimization) << errorMsg.str() << std::endl; + throw std::runtime_error(errorMsg.str().c_str()); + } + + ctx.addResult(this, _function.arg().buildCallToAnalyticIntegral(_mode, RooNameReg::str(_rangeName), ctx)); +} + //////////////////////////////////////////////////////////////////////////////// /// Customized printing of arguments of a RooRealIntegral to more intuitively reflect the contents of the /// integration operation @@ -1161,7 +1176,8 @@ Int_t RooRealIntegral::getCacheAllNumeric() } -std::unique_ptr RooRealIntegral::fillNormSetForServer(RooArgSet const& /*normSet*/, - RooAbsArg const& /*server*/) const { - return _funcNormSet ? std::make_unique(*_funcNormSet) : nullptr; +std::unique_ptr +RooRealIntegral::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + return RooAbsReal::compileForNormSet(_funcNormSet ? *_funcNormSet : normSet, ctx); } diff --git a/roofit/roofitcore/src/RooRealMPFE.cxx b/roofit/roofitcore/src/RooRealMPFE.cxx index fe434d97b4853..ca7e0b6ddf313 100644 --- a/roofit/roofitcore/src/RooRealMPFE.cxx +++ b/roofit/roofitcore/src/RooRealMPFE.cxx @@ -68,7 +68,7 @@ For general multiprocessing in ROOT, please refer to the TProcessExecutor class. class RooRealMPFE ; // RooMPSentinel is a singleton class that keeps track of all -// parellel execution processes for goodness-of-fit calculations. +// parallel execution processes for goodness-of-fit calculations. // The primary task of RooMPSentinel is to terminate all server processes // when the main ROOT process is exiting. struct RooMPSentinel { @@ -110,8 +110,8 @@ RooRealMPFE::RooRealMPFE(const char *name, const char *title, RooAbsReal& arg, b _verboseServer(false), _inlineMode(calcInline), _remoteEvalErrorLoggingState(RooAbsReal::PrintErrors), - _pipe(0), - _updateMaster(0), + _pipe(nullptr), + _updateMaster(nullptr), _retrieveDispatched(false), _evalCarry(0.) { #ifdef _WIN32 @@ -139,8 +139,8 @@ RooRealMPFE::RooRealMPFE(const RooRealMPFE& other, const char* name) : _inlineMode(other._inlineMode), _forceCalc(other._forceCalc), _remoteEvalErrorLoggingState(other._remoteEvalErrorLoggingState), - _pipe(0), - _updateMaster(0), + _pipe(nullptr), + _updateMaster(nullptr), _retrieveDispatched(false), _evalCarry(other._evalCarry) { initVars() ; @@ -170,7 +170,7 @@ void RooRealMPFE::initVars() _saveVars.removeAll() ; // Retrieve non-constant parameters - RooArgSet* vars = _arg.arg().getParameters(RooArgSet()) ; + auto vars = _arg->getParameters(RooArgSet()); //RooArgSet* ncVars = (RooArgSet*) vars->selectByAttrib("Constant",false) ; RooArgList varList(*vars) ; @@ -182,9 +182,6 @@ void RooRealMPFE::initVars() // Force next calculation _forceCalc = true ; - - delete vars ; - //delete ncVars ; } double RooRealMPFE::getCarry() const @@ -231,7 +228,7 @@ void RooRealMPFE::initialize() delete _pipe; _exit(0) ; } else { - // Client process - fork successul + // Client process - fork successful if (_verboseClient) ccoutD(Minimization) << "RooRealMPFE::initialize(" << GetName() << ") successfully forked server process " << _pipe->pidOtherEnd() << endl ; @@ -328,7 +325,7 @@ void RooRealMPFE::serverLoop() objidstr = oss2.str(); } std::map > >::const_iterator iter = evalErrorIter(); - const RooAbsArg* ptr = 0; + const RooAbsArg* ptr = nullptr; for (int i = 0; i < numEvalErrorItems(); ++i) { list::const_iterator iter2 = iter->second.second.begin(); for (; iter->second.second.end() != iter2; ++iter2) { @@ -339,7 +336,7 @@ void RooRealMPFE::serverLoop() } } // let other end know that we're done with the list of errors - ptr = 0; + ptr = nullptr; *_pipe << ptr; // Clear error list on local side clearEvalErrorLog(); @@ -522,7 +519,7 @@ void RooRealMPFE::calculate() const //////////////////////////////////////////////////////////////////////////////// -/// If value needs recalculation and calculation has not beed started +/// If value needs recalculation and calculation has not been started /// with a call to calculate() start it now. This function blocks /// until remote process has finished calculation and returns /// remote value @@ -532,7 +529,7 @@ double RooRealMPFE::getValV(const RooArgSet* /*nset*/) const if (isValueDirty()) { // Cache is dirty, no calculation has been started yet - //cout << "RooRealMPFE::getValF(" << GetName() << ") cache is dirty, caling calculate and evaluate" << endl ; + //cout << "RooRealMPFE::getValF(" << GetName() << ") cache is dirty, calling calculate and evaluate" << endl ; calculate() ; _value = evaluate() ; } else if (_calcInProgress) { @@ -567,7 +564,7 @@ double RooRealMPFE::evaluate() const int msg; double value; - // If current error loggin state is not the same as remote state + // If current error logging state is not the same as remote state // update the remote state if (evalErrorLoggingMode() != _remoteEvalErrorLoggingState) { msg = LogEvalError ; @@ -604,8 +601,8 @@ double RooRealMPFE::evaluate() const << ") IPC fromServer> NumErrors " << numError << endl ; if (numError) { // Retrieve remote errors and feed into local error queue - char *msgbuf1 = 0, *msgbuf2 = 0, *msgbuf3 = 0; - RooAbsArg *ptr = 0; + char *msgbuf1 = nullptr, *msgbuf2 = nullptr, *msgbuf3 = nullptr; + RooAbsArg *ptr = nullptr; while (true) { *_pipe >> ptr; if (!ptr) break; @@ -662,7 +659,7 @@ void RooRealMPFE::standby() } // Close pipes delete _pipe; - _pipe = 0; + _pipe = nullptr; // Revert to initialize state _state = Initialize; diff --git a/roofit/roofitcore/src/RooRealSumFunc.cxx b/roofit/roofitcore/src/RooRealSumFunc.cxx index 5205f3f8c2cb8..02ede30c0247d 100644 --- a/roofit/roofitcore/src/RooRealSumFunc.cxx +++ b/roofit/roofitcore/src/RooRealSumFunc.cxx @@ -114,6 +114,10 @@ double RooRealSumFunc::evaluate() const return RooRealSumPdf::evaluate(*this, _funcList, _coefList, _doFloor || _doFloorGlobal, _haveWarned); } +void RooRealSumFunc::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + RooRealSumPdf::translateImpl(ctx, this, _funcList, _coefList); +} //_____________________________________________________________________________ bool RooRealSumFunc::checkObservables(const RooArgSet *nset) const @@ -165,3 +169,11 @@ void RooRealSumFunc::printMetaArgs(std::ostream &os) const { RooRealSumPdf::printMetaArgs(_funcList, _coefList, os); } + +std::unique_ptr RooRealSumFunc::compileForNormSet(RooArgSet const &/*normSet*/, RooFit::Detail::CompileContext & ctx) const +{ + auto newArg = std::unique_ptr{static_cast(Clone())}; + ctx.markAsCompiled(*newArg); + ctx.compileServers(*newArg, {}); + return newArg; +} diff --git a/roofit/roofitcore/src/RooRealSumPdf.cxx b/roofit/roofitcore/src/RooRealSumPdf.cxx index e766b33beecd7..3e2ae33536ff9 100644 --- a/roofit/roofitcore/src/RooRealSumPdf.cxx +++ b/roofit/roofitcore/src/RooRealSumPdf.cxx @@ -46,12 +46,12 @@ to the fractions of the various functions. **This requires setting the last argu #include "RooRealSumPdf.h" +#include "RooNormalizedPdf.h" #include "RooRealIntegral.h" #include "RooRealProxy.h" #include "RooRealVar.h" #include "RooMsgService.h" #include "RooNaNPacker.h" -#include "RunContext.h" #include @@ -262,7 +262,6 @@ double RooRealSumPdf::evaluate(RooAbsReal const& caller, return value < 0 && doFloor ? 0.0 : value; } - //////////////////////////////////////////////////////////////////////////////// /// Calculate the current value @@ -272,7 +271,7 @@ double RooRealSumPdf::evaluate() const } -void RooRealSumPdf::computeBatch(cudaStream_t* /*stream*/, double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { +void RooRealSumPdf::computeBatch(double* output, size_t nEvents, RooFit::Detail::DataMap const& dataMap) const { // Do running sum of coef/func pairs, calculate lastCoef. for (unsigned int j = 0; j < nEvents; ++j) { output[j] = 0.0; @@ -300,7 +299,7 @@ void RooRealSumPdf::computeBatch(cudaStream_t* /*stream*/, double* output, size_ // Warn about degeneration of last coefficient if (coef == nullptr && (coefVal < 0 || coefVal > 1.)) { if (!_haveWarned) { - coutW(Eval) << "RooRealSumPdf::evaluateSpan(" << GetName() + coutW(Eval) << "RooRealSumPdf::computeBatch(" << GetName() << ") WARNING: sum of FUNC coefficients not in range [0-1], value=" << sumCoeff << ". This means that the PDF is not properly normalised. If the PDF was meant to be extended, provide as many coefficients as functions." << endl ; _haveWarned = true; @@ -320,6 +319,62 @@ void RooRealSumPdf::computeBatch(cudaStream_t* /*stream*/, double* output, size_ } } +void RooRealSumPdf::translateImpl(RooFit::Detail::CodeSquashContext &ctx, RooAbsArg const *klass, + RooArgList const &funcList, RooArgList const &coefList) +{ + bool noLastCoeff = funcList.size() != coefList.size(); + std::string sum; + std::string lastCoeff; + + if (funcList.size() < 3) { + lastCoeff = "(1"; + + std::size_t i; + for (i = 0; i < coefList.size(); ++i) { + auto coeff = ctx.getResult(coefList[i]); + sum += "(" + ctx.getResult(funcList[i]) + " * " + coeff + ") +"; + if (noLastCoeff) + lastCoeff += " - " + coeff; + } + lastCoeff += ")"; + + if (noLastCoeff) { + sum += "(" + ctx.getResult(funcList[i]) + " * " + lastCoeff + ")"; + } else { + sum.pop_back(); + } + + } else { + std::string const &funcName = ctx.buildArg(funcList); + std::string const &coeffName = ctx.buildArg(coefList); + std::string const &coeffSize = std::to_string(coefList.size()); + std::string const &className = klass->GetName(); + + sum = ctx.getTmpVarName(); + lastCoeff = ctx.getTmpVarName(); + ctx.addToCodeBody(klass, "double " + sum + " = 0, " + lastCoeff + "= 0;\n"); + + std::string iterator = "i_" + className; + std::string subscriptExpr = "[" + iterator + "]"; + + std::string code = "for(int " + iterator + " = 0; " + iterator + " < " + coeffSize + "; " + iterator + "++) {\n" + + sum + " += " + funcName + subscriptExpr + " * " + coeffName + subscriptExpr + ";\n"; + if (noLastCoeff) + code += lastCoeff + " += " + coeffName + subscriptExpr + ";\n"; + code += "}\n"; + + if (noLastCoeff) + code += sum + " += " + funcName + "[" + coeffSize + "]" + " * (1 - " + lastCoeff + ");\n"; + ctx.addToCodeBody(klass, code); + } + + ctx.addResult(klass, sum); +} + +void RooRealSumPdf::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + translateImpl(ctx, this, _funcList, _coefList); +} bool RooRealSumPdf::checkObservables(RooAbsReal const& caller, RooArgSet const* nset, RooArgList const& funcList, RooArgList const& coefList) @@ -383,12 +438,16 @@ Int_t RooRealSumPdf::getAnalyticalIntegralWN(RooAbsReal const& caller, RooObjCac // Select subset of allVars that are actual dependents analVars.add(allVars) ; - RooArgSet* normSet = normSet2 ? caller.getObservables(normSet2) : 0 ; + std::unique_ptr normSet; + if(normSet2) { + normSet = std::make_unique(); + caller.getObservables(normSet2, *normSet); + } // Check if this configuration was created before Int_t sterileIdx(-1) ; - auto* cache = static_cast(normIntMgr.getObj(normSet,&analVars,&sterileIdx,RooNameReg::ptr(rangeName))); + auto* cache = static_cast(normIntMgr.getObj(normSet.get(),&analVars,&sterileIdx,RooNameReg::ptr(rangeName))); if (cache) { //cout << "RooRealSumPdf("<") << " -> " << _normIntMgr.lastIndex()+1 << " (cached)" << endl; return normIntMgr.lastIndex()+1 ; @@ -401,21 +460,16 @@ Int_t RooRealSumPdf::getAnalyticalIntegralWN(RooAbsReal const& caller, RooObjCac for (const auto elm : funcList) { const auto func = static_cast(elm); - RooAbsReal* funcInt = func->createIntegral(analVars,rangeName) ; - if(funcInt->InheritsFrom(RooRealIntegral::Class())) ((RooRealIntegral*)funcInt)->setAllowComponentSelection(true); - cache->_funcIntList.addOwned(*funcInt) ; - if (normSet && normSet->getSize()>0) { - RooAbsReal* funcNorm = func->createIntegral(*normSet) ; - cache->_funcNormList.addOwned(*funcNorm) ; + std::unique_ptr funcInt{func->createIntegral(analVars,rangeName)}; + if(auto funcRealInt = dynamic_cast(funcInt.get())) funcRealInt->setAllowComponentSelection(true); + cache->_funcIntList.addOwned(std::move(funcInt)); + if (normSet && !normSet->empty()) { + cache->_funcNormList.addOwned(std::unique_ptr{func->createIntegral(*normSet)}); } } // Store cache element - Int_t code = normIntMgr.setObj(normSet,&analVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)) ; - - if (normSet) { - delete normSet ; - } + Int_t code = normIntMgr.setObj(normSet.get(),&analVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)) ; //cout << "RooRealSumPdf("<") << " -> " << code+1 << endl; return code+1 ; @@ -643,6 +697,9 @@ std::list* RooRealSumPdf::plotSamplingHint(RooArgList const& funcList, R auto* newSumHint = new std::list(sumHint->size()+funcHint->size()) ; + // the lists must be sorted before merging them + funcHint->sort(); + sumHint->sort(); // Merge hints into temporary array merge(funcHint->begin(),funcHint->end(),sumHint->begin(),sumHint->end(),newSumHint->begin()) ; @@ -730,3 +787,60 @@ void RooRealSumPdf::printMetaArgs(RooArgList const& funcList, RooArgList const& os << " " ; } + +std::unique_ptr +RooRealSumPdf::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + if (normSet.empty() || selfNormalized()) { + return RooAbsPdf::compileForNormSet({}, ctx); + } + std::unique_ptr pdfClone(static_cast(this->Clone())); + + if (ctx.likelihoodMode() && pdfClone->getAttribute("BinnedLikelihood")) { + + // This has to be done before compiling the servers, such that the + // RooBinWidthFunctions know to disable themselves. + ctx.setBinnedLikelihoodMode(true); + + ctx.markAsCompiled(*pdfClone); + ctx.compileServers(*pdfClone, {}); + + pdfClone->setAttribute("BinnedLikelihoodActive"); + // If this is a binned likelihood, we're flagging it in the context. + // Then, the RooBinWidthFunctions know that they should not put + // themselves in the computation graph. Like this, the pdf values can + // directly be interpreted as yields, without multiplying them with the + // bin widths again in the NLL. However, the NLL class has to be careful + // to only skip the bin with multiplication when there actually were + // RooBinWidthFunctions! This is not the case for old workspace before + // ROOT 6.26. Therefore, we use the "BinnedLikelihoodActiveYields" + // attribute to let the NLL know what it should do. + if (ctx.binWidthFuncFlag()) { + pdfClone->setAttribute("BinnedLikelihoodActiveYields"); + } + return pdfClone; + } + + ctx.compileServers(*pdfClone, {}); + + RooArgSet depList; + pdfClone->getObservables(&normSet, depList); + + auto newArg = std::make_unique(*pdfClone, depList); + + // The direct servers are this pdf and the normalization integral, which + // don't need to be compiled further. + for (RooAbsArg *server : newArg->servers()) { + ctx.markAsCompiled(*server); + } + ctx.markAsCompiled(*newArg); + newArg->addOwnedComponents(std::move(pdfClone)); + return newArg; +} + +std::unique_ptr RooRealSumPdf::createExpectedEventsFunc(const RooArgSet *nset) const +{ + if (nset == nullptr) + return nullptr; + return std::unique_ptr{createIntegral(*nset, *getIntegratorConfig(), normRange())}; +} diff --git a/roofit/roofitcore/src/RooRealVar.cxx b/roofit/roofitcore/src/RooRealVar.cxx index bc813271f47c9..81947ea3df766 100644 --- a/roofit/roofitcore/src/RooRealVar.cxx +++ b/roofit/roofitcore/src/RooRealVar.cxx @@ -39,7 +39,6 @@ or integrals to sub ranges. The range without any name is used as default range. #include "RooTrace.h" #include "RooRealVarSharedProperties.h" #include "RooUniformBinning.h" -#include "RunContext.h" #include "RooSentinel.h" #include "TTree.h" @@ -69,7 +68,7 @@ RooRealVar::SharedPropertiesMap* RooRealVar::sharedPropList() } //////////////////////////////////////////////////////////////////////////////// -/// Explicitely deletes the shared properties list on exit to avoid problems +/// Explicitly deletes the shared properties list on exit to avoid problems /// with the initialization order. Meant to be only used internally in RooFit /// by RooSentinel. @@ -81,6 +80,24 @@ void RooRealVar::cleanup() } } +//////////////////////////////////////////////////////////////////////////////// + +void RooRealVar::translate(RooFit::Detail::CodeSquashContext &ctx) const +{ + if(!isConstant()) { + ctx.addResult(this, GetName()); + } + // Just return a formatted version of the const value. + // Formats to the maximum precision. + constexpr auto max_precision{std::numeric_limits::digits10 + 1}; + std::stringstream ss; + ss.precision(max_precision); + // Just use toString to make sure we do not output 'inf'. + // This is really ugly for large numbers... + ss << std::fixed << RooNumber::toString(_value); + ctx.addResult(this, ss.str()); +} + /// Return a dummy object to use when properties are not initialised. RooRealVarSharedProperties& RooRealVar::_nullProp() { @@ -161,7 +178,7 @@ RooRealVar::RooRealVar(const char *name, const char *title, setRange(minValue,maxValue) ; double clipValue ; - inRange(value,0,&clipValue) ; + inRange(value,nullptr,&clipValue) ; _value = clipValue ; TRACE_CREATE @@ -200,7 +217,7 @@ RooRealVar::RooRealVar(const RooRealVar& other, const char* name) : RooRealVar::~RooRealVar() { - // We should not forget to explicitely call deleteSharedProperties() in the + // We should not forget to explicitly call deleteSharedProperties() in the // destructor, because this is where the expired weak_ptrs in the // _sharedPropList get erased. deleteSharedProperties(); @@ -218,35 +235,6 @@ double RooRealVar::getValV(const RooArgSet*) const } -//////////////////////////////////////////////////////////////////////////////// -/// Retrieve data column of this variable. -/// \param inputData Struct with data arrays. -/// 1. Check if `inputData` has a column of data registered for this variable (checks the pointer). -/// 2. If not, check if there's an object with the same name, and use this object's values. -/// 3. If there is no such object, return a batch of size one with the current value of the variable. -/// For cases 2. and 3., the data column in `inputData` is associated to this object, so the next call can return it immediately. -RooSpan RooRealVar::getValues(RooBatchCompute::RunContext& inputData, const RooArgSet*) const { - auto item = inputData.spans.find(this); - if (item != inputData.spans.end()) { - return item->second; - } - - for (const auto& var_span : inputData.spans) { - auto var = var_span.first; - if (var == RooFit::Detail::DataKey{this}) { - // A variable with the same name exists in the input data. Use their values as ours. - inputData.spans[this] = var_span.second; - return var_span.second; - } - } - - auto output = inputData.makeBatch(this, 1); - output[0] = _value; - - return output; -} - - //////////////////////////////////////////////////////////////////////////////// /// Set value of variable to 'value'. If 'value' is outside /// range of object, clip value into range @@ -254,7 +242,7 @@ RooSpan RooRealVar::getValues(RooBatchCompute::RunContext& inputDa void RooRealVar::setVal(double value) { double clipValue ; - inRange(value,0,&clipValue) ; + inRange(value,nullptr,&clipValue) ; if (clipValue != _value) { setValueDirty() ; @@ -330,7 +318,7 @@ const RooAbsBinning& RooRealVar::getBinning(const char* name, bool verbose, bool RooAbsBinning& RooRealVar::getBinning(const char* name, bool verbose, bool createOnTheFly) { // Return default (normalization) binning and range if no name is specified - if (name==0) { + if (name==nullptr) { return *_binning ; } @@ -474,7 +462,7 @@ void RooRealVar::setMin(const char* name, double value) // Clip current value in window if it fell out if (!name) { double clipValue ; - if (!inRange(_value,0,&clipValue)) { + if (!inRange(_value,nullptr,&clipValue)) { setVal(clipValue) ; } } @@ -504,7 +492,7 @@ void RooRealVar::setMax(const char* name, double value) // Clip current value in window if it fell out if (!name) { double clipValue ; - if (!inRange(_value,0,&clipValue)) { + if (!inRange(_value,nullptr,&clipValue)) { setVal(clipValue) ; } } @@ -590,7 +578,7 @@ bool RooRealVar::readFromStream(istream& is, bool compact, bool verbose) removeAsymError() ; bool reprocessToken = false ; - while(1) { + while(true) { if (parser.atEOL() || parser.atEOF()) break ; if (!reprocessToken) { @@ -644,7 +632,7 @@ bool RooRealVar::readFromStream(istream& is, bool compact, bool verbose) parser.readInteger(plotBins,true) || parser.expectToken(")",true)) break ; // setPlotRange(plotMin,plotMax) ; - coutW(Eval) << "RooRealVar::readFromStrem(" << GetName() + coutW(Eval) << "RooRealVar::readFromStream(" << GetName() << ") WARNING: plot range deprecated, removed P(...) token" << endl ; } else if (!token.CompareTo("F")) { @@ -727,9 +715,7 @@ void RooRealVar::writeToStream(ostream& os, bool compact) const os << " " ; } else { - TString* tmp = format(_printSigDigits,"EFA") ; - os << tmp->Data() << " " ; - delete tmp ; + os << std::unique_ptr{format(_printSigDigits,"EFA")}->Data() << " " ; } // Append limits if not constants @@ -858,7 +844,7 @@ TString* RooRealVar::format(const RooCmdArg& formatArg) const RooCmdArg tmp(formatArg) ; tmp.setProcessRecArgs(true) ; - RooCmdConfig pc(Form("RooRealVar::format(%s)",GetName())) ; + RooCmdConfig pc("RooRealVar::format(" + std::string(GetName()) + ")"); pc.defineString("what","FormatArgs",0,"") ; pc.defineInt("autop","FormatArgs::AutoPrecision",0,2) ; pc.defineInt("fixedp","FormatArgs::FixedPrecision",0,2) ; @@ -872,7 +858,7 @@ TString* RooRealVar::format(const RooCmdArg& formatArg) const // Process & check varargs pc.process(tmp) ; if (!pc.ok(true)) { - return 0 ; + return nullptr ; } // Extract values from named arguments @@ -908,6 +894,7 @@ TString* RooRealVar::format(const RooCmdArg& formatArg) const /// /// To control what is shown use the following options /// N = show name +/// T = show title (takes precedent over `N`, falls back to `N` if title is empty) /// H = hide value /// E = show error /// A = show asymmetric error instead of parabolic error (if available) @@ -924,12 +911,12 @@ TString* RooRealVar::format(const RooCmdArg& formatArg) const TString *RooRealVar::format(Int_t sigDigits, const char *options) const { - //cout << "format = " << options << endl ; - // parse the options string TString opts(options); opts.ToLower(); + bool showName= opts.Contains("n"); + bool showTitle = opts.Contains("t"); bool hideValue= opts.Contains("h"); bool showError= opts.Contains("e"); bool showUnit= opts.Contains("u"); @@ -938,6 +925,12 @@ TString *RooRealVar::format(Int_t sigDigits, const char *options) const bool latexTableMode = opts.Contains("y") ; bool latexVerbatimName = opts.Contains("v") ; + std::string label = showName ? getPlotLabel() : ""; + if(showTitle) { + label = GetTitle(); + if(label.empty()) label = getPlotLabel(); + } + if (latexTableMode) latexMode = true ; bool asymError= opts.Contains("a") ; bool useErrorForPrecision= (((showError && hasError(false) && !isConstant()) || opts.Contains("p")) && !opts.Contains("f")) ; @@ -945,13 +938,13 @@ TString *RooRealVar::format(Int_t sigDigits, const char *options) const if(sigDigits < 1) sigDigits= 1; Int_t leadingDigitVal = 0; if (useErrorForPrecision) { - leadingDigitVal = (Int_t)floor(log10(fabs(_error+1e-10))); + leadingDigitVal = (Int_t)floor(log10(std::abs(_error+1e-10))); if (_value==0&&_error==0) leadingDigitVal=0 ; } else { - leadingDigitVal = (Int_t)floor(log10(fabs(_value+1e-10))); + leadingDigitVal = (Int_t)floor(log10(std::abs(_value+1e-10))); if (_value==0) leadingDigitVal=0 ; } - Int_t leadingDigitErr= (Int_t)floor(log10(fabs(_error+1e-10))); + Int_t leadingDigitErr= (Int_t)floor(log10(std::abs(_error+1e-10))); Int_t whereVal= leadingDigitVal - sigDigits + 1; Int_t whereErr= leadingDigitErr - sigDigits + 1; char fmtVal[16], fmtErr[16]; @@ -962,11 +955,11 @@ TString *RooRealVar::format(Int_t sigDigits, const char *options) const TString *text= new TString(); if(latexMode) text->Append("$"); // begin the string with " = " if requested - if(showName) { + if(showName || showTitle) { if (latexTableMode && latexVerbatimName) { text->Append("\\verb+") ; } - text->Append(getPlotLabel()); + text->Append(label); if (latexVerbatimName) text->Append("+") ; if (!latexTableMode) { @@ -1229,7 +1222,7 @@ void RooRealVar::Streamer(TBuffer &R__b) R__b >> fitMin; R__b >> fitMax; R__b >> fitBins; - _binning.reset(new RooUniformBinning(fitMin,fitMax,fitBins)); + _binning = std::make_unique(fitMin,fitMax,fitBins); } R__b >> _error; R__b >> _asymErrLo; diff --git a/roofit/roofitcore/src/RooRecursiveFraction.cxx b/roofit/roofitcore/src/RooRecursiveFraction.cxx index 3737febe3ef62..3f784cd1bbbb4 100644 --- a/roofit/roofitcore/src/RooRecursiveFraction.cxx +++ b/roofit/roofitcore/src/RooRecursiveFraction.cxx @@ -26,7 +26,7 @@ from a set of recursive fractions: for a given set of input fractions **/ #include "Riostream.h" -#include +#include #include "RooRecursiveFraction.h" #include "RooAbsReal.h" diff --git a/roofit/roofitcore/src/RooRefCountList.cxx b/roofit/roofitcore/src/RooRefCountList.cxx deleted file mode 100644 index 51ab576428b77..0000000000000 --- a/roofit/roofitcore/src/RooRefCountList.cxx +++ /dev/null @@ -1,117 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooRefCountList.cxx -\class RooRefCountList -\ingroup Roofitcore - -A RooRefCountList is a RooLinkedList that keeps a reference counter -with each added node. Multiple Add()s of the same object will increase -the counter instead of adding multiple copies. Remove() decrements the -reference count until zero, when the object is actually removed. -**/ - -#include "RooRefCountList.h" - -#include "Riostream.h" -#include - -using namespace std; - -ClassImp(RooRefCountList); - ; - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor construct lists with initial hash table size of 17 - -RooRefCountList::RooRefCountList() - : RooLinkedList(0) -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Add object to list with given reference count increment -/// List takes ownership of object. - -void RooRefCountList::Add(TObject* obj, Int_t count) -{ - // Check if we already have it - TObject* listObj = FindObject(obj) ; - if (!listObj) { - // Add to list with reference count - RooLinkedList::Add(obj, count) ; - //cout << "RooRefCountList::AddLast(" << obj << ") adding object" << endl ; - } else { - RooLinkedListElem* link = findLink(obj) ; - if(link) { - while(count--) link->incRefCount() ; - } - //cout << "RooRefCountList::AddLast(" << obj << ") incremented reference count to " << link->refCount() << endl ; - } - -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Remove object from list and if reference count -/// reaches zero delete object itself as well. - -bool RooRefCountList::Remove(TObject* obj) -{ - RooLinkedListElem* link = findLink(obj) ; - if (!link) { - return 0 ; - } else { - if (link->decRefCount()==0) { - //cout << "RooRefCountList::AddLast(" << obj << ") removed object" << endl ; - return RooLinkedList::Remove(obj) ; - } - //cout << "RooRefCountList::AddLast(" << obj << ") decremented reference count to " << link->refCount() << endl ; - } - return 0 ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Remove object from list and delete object itself -/// regardless of reference count - -bool RooRefCountList::RemoveAll(TObject* obj) -{ - return RooLinkedList::Remove(obj) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Return reference count associated with 'obj' - -Int_t RooRefCountList::refCount(TObject* obj) const -{ - RooLinkedListElem* link = findLink(obj) ; - if (!link) { - return 0 ; - } else { - return link->refCount() ; - } -} diff --git a/roofit/roofitcore/src/RooResolutionModel.cxx b/roofit/roofitcore/src/RooResolutionModel.cxx index b8aee50d4366a..6c50f21f146c8 100644 --- a/roofit/roofitcore/src/RooResolutionModel.cxx +++ b/roofit/roofitcore/src/RooResolutionModel.cxx @@ -75,13 +75,13 @@ ClassImp(RooResolutionModel); //////////////////////////////////////////////////////////////////////////////// /// Constructor with convolution variable 'x'. -/// The convolution variable needs to be convertable to real values, and be able +/// The convolution variable needs to be convertible to real values, and be able /// to give information about its range. This is supported by e.g. RooRealVar or RooLinearVar, which /// accepts offsetting and scaling an observable. RooResolutionModel::RooResolutionModel(const char *name, const char *title, RooAbsRealLValue& _x) : RooAbsPdf(name,title), x("x","Dependent or convolution variable",this,_x), - _basisCode(0), _basis(0), + _basisCode(0), _basis(nullptr), _ownBasis(false) { @@ -95,7 +95,7 @@ RooResolutionModel::RooResolutionModel(const char *name, const char *title, RooA RooResolutionModel::RooResolutionModel(const RooResolutionModel& other, const char* name) : RooAbsPdf(other,name), x("x",this,other.x), - _basisCode(other._basisCode), _basis(0), + _basisCode(other._basisCode), _basis(nullptr), _ownBasis(false) { if (other._basis) { @@ -154,13 +154,13 @@ RooResolutionModel* RooResolutionModel::convolution(RooFormulaVar* inBasis, RooA << ") convolution parameter of basis function and PDF don't match" << endl << "basis->findServer(0) = " << inBasis->findServer(0) << endl << "x.absArg() = " << x.absArg() << endl ; - return 0 ; + return nullptr ; } if (basisCode(inBasis->GetTitle())==0) { coutE(InputArguments) << "RooResolutionModel::convolution(" << GetName() << "," << this << ") basis function '" << inBasis->GetTitle() << "' is not supported." << endl ; - return 0 ; + return nullptr ; } TString newName(GetName()) ; @@ -258,7 +258,7 @@ double RooResolutionModel::getValV(const RooArgSet* nset) const bool RooResolutionModel::redirectServersHook(const RooAbsCollection& newServerList, bool mustReplaceAll, bool nameChange, bool isRecursive) { if (!_basis) { - _norm = 0 ; + _norm = nullptr ; return false ; } diff --git a/roofit/roofitcore/src/RooRombergIntegrator.cxx b/roofit/roofitcore/src/RooRombergIntegrator.cxx new file mode 100644 index 0000000000000..0a7adc26ced2a --- /dev/null +++ b/roofit/roofitcore/src/RooRombergIntegrator.cxx @@ -0,0 +1,550 @@ +/***************************************************************************** + * Project: RooFit * + * Package: RooFitCore * + * @(#)root/roofitcore:$Id$ + * Authors: * + * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * + * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * + * * + * Copyright (c) 2000-2005, Regents of the University of California * + * and Stanford University. All rights reserved. * + * * + * Redistribution and use in source and binary forms, * + * with or without modification, are permitted according to the terms * + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * + *****************************************************************************/ + +/** +\file RooRombergIntegrator.cxx +\class RooRombergIntegrator +\ingroup Roofitcore + +RooRombergIntegrator implements an adaptive numerical integration algorithm. + +It uses Romberg's method with trapezoids or midpoints. +The integrand is approximated by \f$ 1, 2, 4, 8, \ldots, 2^n \f$ trapezoids, and +Richardson series acceleration is applied to the series. For refinement step \f$ n \f$, that is +\f[ + R(n,m) = \frac{1}{4^m - 1} \left( 4^m R(n, m-1) - R(n-1, m-1) \right) +\f] +The integrator will evaluate the first six refinements (i.e. 64 points) in one go, +apply a five-point series acceleration, and successively add more steps until the +desired precision is reached. +**/ + +#include "Riostream.h" + +#include "TClass.h" +#include "RooRombergIntegrator.h" +#include "RooArgSet.h" +#include "RooRealVar.h" +#include "RooNumber.h" +#include "RooNumIntConfig.h" +#include "RooNumIntFactory.h" +#include "RooMsgService.h" + +#include + +namespace { + +constexpr static int nPoints = 5; + +//////////////////////////////////////////////////////////////////////////////// +/// Calculate the n-th stage of refinement of the Second Euler-Maclaurin +/// summation rule which has the useful property of not evaluating the +/// integrand at either of its endpoints but requires more function +/// evaluations than the trapezoidal rule. This rule can be used with +/// a suitable change of variables to estimate improper integrals. + +double addMidpoints(std::function const &func, double savedResult, int n, double xmin, double xmax) +{ + const double range = xmax - xmin; + + if (n == 1) { + double xmid = 0.5 * (xmin + xmax); + return range * func(xmid); + } + + int it = 1; + for (int j = 1; j < n - 1; j++) { + it *= 3; + } + double tnm = it; + double del = range / (3. * tnm); + double ddel = del + del; + double x = xmin + 0.5 * del; + double sum = 0; + for (int j = 1; j <= it; j++) { + sum += func(x); + x += ddel; + sum += func(x); + x += del; + } + return (savedResult + range * sum / tnm) / 3.; +} + +//////////////////////////////////////////////////////////////////////////////// +/// Calculate the n-th stage of refinement of the extended trapezoidal +/// summation rule. This is the most efficient rule for a well behaved +/// integrands that can be evaluated over its entire range, including the +/// endpoints. + +double addTrapezoids(std::function const &func, double savedResult, int n, double xmin, double xmax) +{ + const double range = xmax - xmin; + + if (n == 1) { + // use a single trapezoid to cover the full range + return 0.5 * range * (func(xmin) + func(xmax)); + } + + // break the range down into several trapezoids using 2**(n-2) + // equally-spaced interior points + const int nInt = 1 << (n - 2); + const double del = range / nInt; + + double sum = 0.; + // TODO Replace by batch computation + for (int j = 0; j < nInt; ++j) { + double x = xmin + (0.5 + j) * del; + sum += func(x); + } + + return 0.5 * (savedResult + range * sum / nInt); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Extrapolate result to final value. + +std::pair extrapolate(int n, double const *h, double const *s, double *c, double *d) +{ + double const *xa = &h[n - nPoints]; + double const *ya = &s[n - nPoints]; + int ns = 1; + + double dif = std::abs(xa[1]); + for (int i = 1; i <= nPoints; i++) { + double dift = std::abs(xa[i]); + if (dift < dif) { + ns = i; + dif = dift; + } + c[i] = ya[i]; + d[i] = ya[i]; + } + double extrapError = 0.0; + double extrapValue = ya[ns--]; + for (int m = 1; m < nPoints; m++) { + for (int i = 1; i <= nPoints - m; i++) { + double ho = xa[i]; + double hp = xa[i + m]; + double w = c[i + 1] - d[i]; + double den = ho - hp; + if (den == 0.0) { + throw std::runtime_error("RooRombergIntegrator::extrapolate: internal error"); + } + den = w / den; + d[i] = hp * den; + c[i] = ho * den; + } + extrapError = 2 * ns < (nPoints - m) ? c[ns + 1] : d[ns--]; + extrapValue += extrapError; + } + return {extrapValue, extrapError}; +} + +} // namespace + +namespace RooFit { +namespace Detail { + +std::pair integrate1d(std::function func, bool doTrapezoid, int maxSteps, int minStepsZero, + int fixSteps, double epsAbs, double epsRel, bool doExtrap, double xmin, double xmax, + std::span hArr, std::span sArr) +{ + assert(int(hArr.size()) == maxSteps + 2); + assert(int(sArr.size()) == maxSteps + 2); + + const double range = xmax - xmin; + + // Small working arrays can be on the stack + std::array cArr = {}; + std::array dArr = {}; + + hArr[1] = 1.0; + double zeroThresh = epsAbs / range; + for (int j = 1; j <= maxSteps; ++j) { + // refine our estimate using the appropriate summation rule + sArr[j] = + doTrapezoid ? addTrapezoids(func, sArr[j - 1], j, xmin, xmax) : addMidpoints(func, sArr[j - 1], j, xmin, xmax); + + if (j >= minStepsZero) { + bool allZero(true); + for (int jj = 0; jj <= j; jj++) { + if (sArr[j] >= zeroThresh) { + allZero = false; + } + } + if (allZero) { + // cout << "Roo1DIntegrator(" << this << "): zero convergence at step " << j << ", value = " << 0 << + // std::endl ; + return {0, j}; + } + } + + if (fixSteps > 0) { + + // Fixed step mode, return result after fixed number of steps + if (j == fixSteps) { + // cout << "returning result at fixed step " << j << std::endl ; + return {sArr[j], j}; + } + + } else if (j >= nPoints) { + + double extrapValue = 0.0; + double extrapError = 0.0; + + // extrapolate the results of recent refinements and check for a stable result + if (doExtrap) { + std::tie(extrapValue, extrapError) = extrapolate(j, hArr.data(), sArr.data(), cArr.data(), dArr.data()); + } else { + extrapValue = sArr[j]; + extrapError = sArr[j] - sArr[j - 1]; + } + + if (std::abs(extrapError) <= epsRel * std::abs(extrapValue)) { + return {extrapValue, j}; + } + if (std::abs(extrapError) <= epsAbs) { + return {extrapValue, j}; + } + } + // update the step size for the next refinement of the summation + hArr[j + 1] = doTrapezoid ? hArr[j] / 4. : hArr[j] / 9.; + } + + return {sArr[maxSteps], maxSteps}; +} + +} // namespace Detail +} // namespace RooFit + +ClassImp(RooRombergIntegrator); + +// Register this class with RooNumIntConfig + +//////////////////////////////////////////////////////////////////////////////// +/// Register integrator plugins, their parameters and capabilities with RooNumIntFactory. + +void RooRombergIntegrator::registerIntegrator(RooNumIntFactory &fact) +{ + RooCategory sumRule("sumRule", "Summation Rule"); + sumRule.defineType("Trapezoid", RooRombergIntegrator::Trapezoid); + sumRule.defineType("Midpoint", RooRombergIntegrator::Midpoint); + sumRule.setLabel("Trapezoid"); + RooCategory extrap("extrapolation", "Extrapolation procedure"); + extrap.defineType("None", 0); + extrap.defineType("Wynn-Epsilon", 1); + extrap.setLabel("Wynn-Epsilon"); + RooRealVar maxSteps("maxSteps", "Maximum number of steps", 20); + RooRealVar minSteps("minSteps", "Minimum number of steps", 999); + RooRealVar fixSteps("fixSteps", "Fixed number of steps", 0); + RooRealVar numSeg("numSeg", "Number of segments", 3); // only for the segmented integrators + + std::string name = "RooIntegrator1D"; + + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config, 1, /*doSegmentation=*/false); + }; + + fact.registerPlugin(name, creator, {sumRule, extrap, maxSteps, minSteps, fixSteps}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/false, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/false); + + RooNumIntConfig::defaultConfig().method1D().setLabel(name); + + auto creator2d = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config, 2, /*doSegmentation=*/false); + }; + std::string name2d = "RooIntegrator2D"; + fact.registerPlugin(name2d, creator2d, {}, + /*canIntegrate1D=*/false, + /*canIntegrate2D=*/true, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/false, + /*depName=*/"RooIntegrator1D"); + RooNumIntConfig::defaultConfig().method2D().setLabel(name2d); + + auto creatorSeg = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config, 1, /*doSegmentation=*/true); + }; + + fact.registerPlugin("RooSegmentedIntegrator1D", creatorSeg, {numSeg}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/false, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/false, + /*depName=*/"RooIntegrator1D"); + + auto creatorSeg2d = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config, 2, /*doSegmentation=*/true); + }; + + fact.registerPlugin("RooSegmentedIntegrator2D", creatorSeg2d, {}, + /*canIntegrate1D=*/false, + /*canIntegrate2D=*/true, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/false, + /*depName=*/"RooSegmentedIntegrator1D"); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Construct integrator on given function binding, using specified summation +/// rule, maximum number of steps and conversion tolerance. The integration +/// limits are taken from the function binding. + +RooRombergIntegrator::RooRombergIntegrator(const RooAbsFunc &function, SummationRule rule, int maxSteps, double eps) + : RooAbsIntegrator(function), _rule(rule), _maxSteps(maxSteps), _epsAbs(eps), _epsRel(eps) +{ + _useIntegrandLimits = true; + _valid = initialize(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Construct integrator on given function binding for given range, +/// using specified summation rule, maximum number of steps and +/// conversion tolerance. The integration limits are taken from the +/// function binding. + +RooRombergIntegrator::RooRombergIntegrator(const RooAbsFunc &function, double xmin, double xmax, SummationRule rule, + int maxSteps, double eps) + : RooAbsIntegrator(function), _rule(rule), _maxSteps(maxSteps), _epsAbs(eps), _epsRel(eps) +{ + _useIntegrandLimits = false; + _xmin.push_back(xmin); + _xmax.push_back(xmax); + _valid = initialize(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Construct integrator on given function binding, using specified +/// configuration object. The integration limits are taken from the +/// function binding + +RooRombergIntegrator::RooRombergIntegrator(const RooAbsFunc &function, const RooNumIntConfig &config, int nDim, + bool doSegmentation) + : RooAbsIntegrator(function, config.printEvalCounter()), + _nDim{nDim}, + _epsAbs(config.epsAbs()), + _epsRel(config.epsRel()) +{ + // Extract parameters from config object + const RooArgSet &configSet = config.getConfigSection("RooIntegrator1D"); + _rule = (SummationRule)configSet.getCatIndex("sumRule", Trapezoid); + _maxSteps = (int)configSet.getRealValue("maxSteps", 20); + _minStepsZero = (int)configSet.getRealValue("minSteps", 999); + _fixSteps = (int)configSet.getRealValue("fixSteps", 0); + _doExtrap = (bool)configSet.getCatIndex("extrapolation", 1); + if (doSegmentation) { + _nSeg = (int)config.getConfigSection("RooSegmentedIntegrator1D").getRealValue("numSeg", 3); + _epsAbs /= std::sqrt(_nSeg); + _epsRel /= std::sqrt(_nSeg); + } + + if (_fixSteps > _maxSteps) { + oocoutE(nullptr, Integration) << "RooRombergIntegrator::ctor() ERROR: fixSteps>maxSteps, fixSteps set to maxSteps" + << std::endl; + _fixSteps = _maxSteps; + } + + _useIntegrandLimits = true; + _valid = initialize(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Construct integrator on given function binding, using specified +/// configuration object and integration range + +RooRombergIntegrator::RooRombergIntegrator(const RooAbsFunc &function, double xmin, double xmax, + const RooNumIntConfig &config, int nDim) + : RooAbsIntegrator(function, config.printEvalCounter()), + _nDim{nDim}, + _epsAbs(config.epsAbs()), + _epsRel(config.epsRel()) +{ + // Extract parameters from config object + const RooArgSet &configSet = config.getConfigSection("RooIntegrator1D"); + _rule = (SummationRule)configSet.getCatIndex("sumRule", Trapezoid); + _maxSteps = (int)configSet.getRealValue("maxSteps", 20); + _minStepsZero = (int)configSet.getRealValue("minSteps", 999); + _fixSteps = (int)configSet.getRealValue("fixSteps", 0); + _doExtrap = (bool)configSet.getCatIndex("extrapolation", 1); + + _useIntegrandLimits = false; + _xmin.push_back(xmin); + _xmax.push_back(xmax); + _valid = initialize(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Initialize the integrator + +bool RooRombergIntegrator::initialize() +{ + // apply defaults if necessary + if (_maxSteps <= 0) { + _maxSteps = (_rule == Trapezoid) ? 20 : 14; + } + + if (_epsRel <= 0) + _epsRel = 1e-6; + if (_epsAbs <= 0) + _epsAbs = 1e-6; + + // check that the integrand is a valid function + if (!isValid()) { + oocoutE(nullptr, Integration) << "RooRombergIntegrator::initialize: cannot integrate invalid function" + << std::endl; + return false; + } + + // Allocate coordinate buffer size after number of function dimensions + _x.resize(_function->getDimension()); + + // Allocate workspace for numerical integration engine + _wksp.resize(_nDim * 2 * _maxSteps + 4); + + return checkLimits(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Change our integration limits. Return true if the new limits are +/// ok, or otherwise false. Always returns false and does nothing +/// if this object was constructed to always use our integrand's limits. + +bool RooRombergIntegrator::setLimits(double *xmin, double *xmax) +{ + if (_useIntegrandLimits) { + oocoutE(nullptr, Integration) << "RooRombergIntegrator::setLimits: cannot override integrand's limits" + << std::endl; + return false; + } + _xmin.resize(_nDim); + _xmax.resize(_nDim); + for (int iDim = 0; iDim < _nDim; ++iDim) { + _xmin[iDim] = xmin[iDim]; + _xmax[iDim] = xmax[iDim]; + } + return checkLimits(); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Check that our integration range is finite and otherwise return false. +/// Update the limits from the integrand if requested. + +bool RooRombergIntegrator::checkLimits() const +{ + if (_useIntegrandLimits) { + assert(nullptr != integrand() && integrand()->isValid()); + const_cast &>(_xmin).resize(_nDim); + const_cast &>(_xmax).resize(_nDim); + for (int iDim = 0; iDim < _nDim; ++iDim) { + const_cast(_xmin[iDim]) = integrand()->getMinLimit(iDim); + const_cast(_xmax[iDim]) = integrand()->getMaxLimit(iDim); + } + } + for (int iDim = 0; iDim < _nDim; ++iDim) { + const double xmin = _xmin[iDim]; + const double xmax = _xmax[iDim]; + const double range = xmax - xmin; + if (range < 0.) { + oocoutE(nullptr, Integration) << "RooRombergIntegrator::checkLimits: bad range with min > max (_xmin[" << iDim + << "] = " << xmin << " _xmax[" << iDim << "] = " << xmax << ")" << std::endl; + return false; + } + if (RooNumber::isInfinite(xmin) || RooNumber::isInfinite(xmax)) { + return false; + } + } + return true; +} + +double RooRombergIntegrator::integral(const double *yvec) +{ + // Copy yvec to xvec if provided + if (yvec) { + for (unsigned int i = 0; i < _function->getDimension() - 1; i++) { + _x[i + _nDim] = yvec[i]; + } + } + + return integral(_nDim - 1, _nSeg, _wksp); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Calculate numeric integral at given set of function binding parameters. + +double RooRombergIntegrator::integral(int iDim, int nSeg, std::span wksp) +{ + assert(isValid()); + + const double xmin = _xmin[iDim]; + const double xmax = _xmax[iDim]; + const double range = xmax - xmin; + + if (range == 0.) + return 0.; + + // In case of segmentation, split this integral up in a loop. + if (nSeg > 1) { + const double segSize = (xmax - xmin) / nSeg; + double result = 0.0; + for (int iSeg = 0; iSeg < nSeg; iSeg++) { + _xmin[iDim] = xmin + iSeg * segSize; + _xmax[iDim] = xmin + (iSeg + 1) * segSize; + double part = integral(iDim, 1, wksp); + result += part; + } + + // reset limits + _xmin[iDim] = xmin; + _xmax[iDim] = xmax; + + return result; + } + + // From the working array + std::size_t nWorkingArr = _maxSteps + 2; + double *hArr = wksp.data(); + double *sArr = wksp.data() + nWorkingArr; + + double output = 0.0; + int steps = 0; + + std::span nextWksp{wksp.data() + 2 * _maxSteps + 4, wksp.data() + wksp.size()}; + + auto func = [&](double x) { + _x[iDim] = x; + + return iDim == 0 ? integrand(_x.data()) : integral(iDim - 1, _nSeg, nextWksp); + }; + + std::tie(output, steps) = + RooFit::Detail::integrate1d(func, _rule == Trapezoid, _maxSteps, _minStepsZero, _fixSteps, _epsAbs, _epsRel, + _doExtrap, xmin, xmax, {hArr, nWorkingArr}, {sArr, nWorkingArr}); + + if (steps == _maxSteps) { + + oocoutW(nullptr, Integration) << "RooRombergIntegrator::integral: integral of " << _function->getName() + << " over range (" << xmin << "," << xmax << ") did not converge after " + << _maxSteps << " steps" << std::endl; + for (int j = 1; j <= _maxSteps; ++j) { + ooccoutW(nullptr, Integration) << " [" << j << "] h = " << hArr[j] << " , s = " << sArr[j] << std::endl; + } + } + + return output; +} diff --git a/roofit/roofitcore/src/RooSTLRefCountList.cxx b/roofit/roofitcore/src/RooSTLRefCountList.cxx index e4624f58d8708..5fb0acc4c6608 100644 --- a/roofit/roofitcore/src/RooSTLRefCountList.cxx +++ b/roofit/roofitcore/src/RooSTLRefCountList.cxx @@ -13,31 +13,30 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ +/// \cond ROOFIT_INTERNAL + #include "RooSTLRefCountList.h" -#include "RooRefCountList.h" +#include "RooLinkedList.h" #include "RooLinkedListIter.h" #include "RooAbsArg.h" -#include // Template specialisation used in RooAbsArg: ClassImp(RooSTLRefCountList); -namespace RooFit { -namespace STLRefCountListHelpers { -/// Converts RooRefCountList to RooSTLRefCountList. +/// Converts RooLinkedList to RooSTLRefCountList. /// This converter only yields lists with T=RooAbsArg. This is ok because this /// the old RefCountList was only holding these. -RooSTLRefCountList convert(const RooRefCountList& old) { +template <> +RooSTLRefCountList RooSTLRefCountList::convert(const RooLinkedList& old) { RooSTLRefCountList newList; newList.reserve(old.GetSize()); for(TObject * elm : old) { - newList.Add(static_cast(elm), old.refCount(elm)); + newList.Add(static_cast(elm), old.findLink(elm)->refCount()); } return newList; } -} -} +/// \endcond diff --git a/roofit/roofitcore/src/RooScaledFunc.cxx b/roofit/roofitcore/src/RooScaledFunc.cxx deleted file mode 100644 index aafb929b18cf8..0000000000000 --- a/roofit/roofitcore/src/RooScaledFunc.cxx +++ /dev/null @@ -1,33 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooScaledFunc.cxx -\class RooScaledFunc -\ingroup Roofitcore - -Lightweight RooAbsFunction implementation that applies a constant scale -factor to another RooAbsFunc. -**/ - - -#include "RooScaledFunc.h" - -using namespace std; - -ClassImp(RooScaledFunc); -; - diff --git a/roofit/roofitcore/src/RooSecondMoment.cxx b/roofit/roofitcore/src/RooSecondMoment.cxx index ff85fa2518db9..35cfb7b7df9ba 100644 --- a/roofit/roofitcore/src/RooSecondMoment.cxx +++ b/roofit/roofitcore/src/RooSecondMoment.cxx @@ -25,7 +25,7 @@ derivator class. **/ #include "Riostream.h" -#include +#include #include "RooSecondMoment.h" #include "RooAbsReal.h" @@ -70,7 +70,7 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal { setExpensiveObjectCache(func.expensiveObjectCache()) ; - RooAbsReal* XF(0) ; + std::unique_ptr XF; if (centr) { string m1name=Form("%s_moment1",GetName()) ; @@ -78,12 +78,12 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal string pname=Form("%s_product",name) ; _xfOffset = _mean->getVal() ; - XF = new RooFormulaVar(pname.c_str(),Form("pow((@0-%f),2)*@1",_xfOffset),RooArgList(x,func)) ; + XF = std::make_unique(pname.c_str(),Form("pow((@0-%f),2)*@1",_xfOffset),RooArgList(x,func)) ; } else { string pname=Form("%s_product",name) ; - XF = new RooProduct(pname.c_str(),pname.c_str(),RooArgList(x,x,func)) ; + XF = std::make_unique(pname.c_str(),pname.c_str(),RooArgList(x,x,func)) ; } XF->setExpensiveObjectCache(func.expensiveObjectCache()) ; @@ -92,15 +92,17 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal XF->specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator"); } - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(x) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(x) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(x)}; + std::unique_ptr intF{func.createIntegral(x)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } //////////////////////////////////////////////////////////////////////////////// @@ -117,7 +119,7 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal _nset.add(nset) ; - RooAbsReal* XF(0) ; + std::unique_ptr XF; if (centr) { string m1name=Form("%s_moment1",GetName()) ; @@ -125,13 +127,13 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal string pname=Form("%s_product",name) ; _xfOffset = _mean->getVal() ; - XF = new RooFormulaVar(pname.c_str(),Form("pow((@0-%f),2)*@1",_xfOffset),RooArgList(x,func)) ; + XF = std::make_unique(pname.c_str(),Form("pow((@0-%f),2)*@1",_xfOffset),RooArgList(x,func)) ; } else { string pname=Form("%s_product",name) ; - XF = new RooProduct(pname.c_str(),pname.c_str(),RooArgList(x,x,func)) ; + XF = std::make_unique(pname.c_str(),pname.c_str(),RooArgList(x,x,func)) ; } @@ -147,15 +149,17 @@ RooSecondMoment::RooSecondMoment(const char* name, const char* title, RooAbsReal RooArgSet intSet(x) ; if (intNSet) intSet.add(_nset,true) ; - RooRealIntegral* intXF = (RooRealIntegral*) XF->createIntegral(intSet,&_nset) ; - RooRealIntegral* intF = (RooRealIntegral*) func.createIntegral(intSet,&_nset) ; - intXF->setCacheNumeric(true) ; - intF->setCacheNumeric(true) ; + std::unique_ptr intXF{XF->createIntegral(intSet, &_nset)}; + std::unique_ptr intF{func.createIntegral(intSet, &_nset)}; + static_cast(*intXF).setCacheNumeric(true) ; + static_cast(*intF).setCacheNumeric(true) ; _xf.setArg(*XF) ; _ixf.setArg(*intXF) ; _if.setArg(*intF) ; - addOwnedComponents(RooArgSet(*XF,*intXF,*intF)) ; + addOwnedComponents(std::move(XF)) ; + addOwnedComponents(std::move(intXF)); + addOwnedComponents(std::move(intF)); } diff --git a/roofit/roofitcore/src/RooSegmentedIntegrator1D.cxx b/roofit/roofitcore/src/RooSegmentedIntegrator1D.cxx deleted file mode 100644 index 419994051507d..0000000000000 --- a/roofit/roofitcore/src/RooSegmentedIntegrator1D.cxx +++ /dev/null @@ -1,225 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooSegmentedIntegrator1D.cxx -\class RooSegmentedIntegrator1D -\ingroup Roofitcore - -RooSegmentedIntegrator1D implements an adaptive one-dimensional -numerical integration algorithm. -**/ - -#include "Riostream.h" - -#include "TClass.h" -#include "RooSegmentedIntegrator1D.h" -#include "RooArgSet.h" -#include "RooRealVar.h" -#include "RooNumber.h" -#include "RooMsgService.h" -#include "RooNumIntFactory.h" - -#include - - - -using namespace std; - -ClassImp(RooSegmentedIntegrator1D); -; - -// Register this class with RooNumIntConfig - -//////////////////////////////////////////////////////////////////////////////// -/// Register RooSegmentedIntegrator1D, its parameters, dependencies and capabilities with RooNumIntFactory - -void RooSegmentedIntegrator1D::registerIntegrator(RooNumIntFactory& fact) -{ - RooRealVar numSeg("numSeg","Number of segments",3) ; - fact.storeProtoIntegrator(new RooSegmentedIntegrator1D(),numSeg,RooIntegrator1D::Class()->GetName()) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor -/// -/// coverity[UNINIT_CTOR] - -RooSegmentedIntegrator1D::RooSegmentedIntegrator1D() : _array(0) -{ -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor of integral on given function binding and with given configuration. The -/// integration limits are taken from the definition in the function binding - -RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) : - RooAbsIntegrator(function), _config(config) -{ - _nseg = (Int_t) config.getConfigSection(ClassName()).getRealValue("numSeg",3) ; - _useIntegrandLimits= true; - - _valid= initialize(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor integral on given function binding, with given configuration and -/// explicit definition of integration range - -RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, - const RooNumIntConfig& config) : - RooAbsIntegrator(function), _config(config) -{ - _nseg = (Int_t) config.getConfigSection(ClassName()).getRealValue("numSeg",3) ; - _useIntegrandLimits= false; - _xmin= xmin; - _xmax= xmax; - - _valid= initialize(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Virtual constructor with given function and configuration. Needed by RooNumIntFactory - -RooAbsIntegrator* RooSegmentedIntegrator1D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooSegmentedIntegrator1D(function,config) ; -} - - - -typedef RooIntegrator1D* pRooIntegrator1D ; - -//////////////////////////////////////////////////////////////////////////////// -/// One-time integrator initialization - -bool RooSegmentedIntegrator1D::initialize() -{ - _array = 0 ; - - bool limitsOK = checkLimits(); - if (!limitsOK) return false ; - - // Make array of integrators for each segment - _array = new pRooIntegrator1D[_nseg] ; - - Int_t i ; - - double segSize = (_xmax - _xmin) / _nseg ; - - // Adjust integrator configurations for reduced intervals - _config.setEpsRel(_config.epsRel()/sqrt(1.*_nseg)) ; - _config.setEpsAbs(_config.epsAbs()/sqrt(1.*_nseg)) ; - - for (i=0 ; i<_nseg ; i++) { - _array[i] = new RooIntegrator1D(*_function,_xmin+i*segSize,_xmin+(i+1)*segSize,_config) ; - } - - return true ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooSegmentedIntegrator1D::~RooSegmentedIntegrator1D() -{ - if (_array) { - for (Int_t i=0 ; i<_nseg ; i++) { - delete _array[i] ; - } - delete [] _array ; - } -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Change our integration limits. Return true if the new limits are -/// ok, or otherwise false. Always returns false and does nothing -/// if this object was constructed to always use our integrand's limits. - -bool RooSegmentedIntegrator1D::setLimits(double* xmin, double* xmax) -{ - if(_useIntegrandLimits) { - oocoutE(nullptr,InputArguments) << "RooSegmentedIntegrator1D::setLimits: cannot override integrand's limits" << endl; - return false; - } - _xmin= *xmin; - _xmax= *xmax; - return checkLimits(); -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Check that our integration range is finite and otherwise return false. -/// Update the limits from the integrand if requested. - -bool RooSegmentedIntegrator1D::checkLimits() const -{ - if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); - _xmin= integrand()->getMinLimit(0); - _xmax= integrand()->getMaxLimit(0); - } - _range= _xmax - _xmin; - if(_range <= 0) { - oocoutE(nullptr,InputArguments) << "RooIntegrator1D::checkLimits: bad range with min >= max" << endl; - return false; - } - bool ret = (RooNumber::isInfinite(_xmin) || RooNumber::isInfinite(_xmax)) ? false : true; - - // Adjust component integrators, if already created - if (_array && ret) { - double segSize = (_xmax - _xmin) / _nseg ; - Int_t i ; - for (i=0 ; i<_nseg ; i++) { - _array[i]->setLimits(_xmin+i*segSize,_xmin+(i+1)*segSize) ; - } - } - - return ret ; -} - - - - -//////////////////////////////////////////////////////////////////////////////// -/// Evaluate integral at given function binding parameter values - -double RooSegmentedIntegrator1D::integral(const double *yvec) -{ - assert(isValid()); - - Int_t i ; - double result(0) ; - for (i=0 ; i<_nseg ; i++) { - result += _array[i]->integral(yvec) ; - } - - return result; -} - diff --git a/roofit/roofitcore/src/RooSegmentedIntegrator2D.cxx b/roofit/roofitcore/src/RooSegmentedIntegrator2D.cxx deleted file mode 100644 index df6ea70662853..0000000000000 --- a/roofit/roofitcore/src/RooSegmentedIntegrator2D.cxx +++ /dev/null @@ -1,141 +0,0 @@ -/***************************************************************************** - * Project: RooFit * - * Package: RooFitCore * - * @(#)root/roofitcore:$Id$ - * Authors: * - * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * - * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * - * * - * Copyright (c) 2000-2005, Regents of the University of California * - * and Stanford University. All rights reserved. * - * * - * Redistribution and use in source and binary forms, * - * with or without modification, are permitted according to the terms * - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * - *****************************************************************************/ - -/** -\file RooSegmentedIntegrator2D.cxx -\class RooSegmentedIntegrator2D -\ingroup Roofitcore - -RooSegmentedIntegrator2D implements an adaptive one-dimensional -numerical integration algorithm. -**/ - - -#include "Riostream.h" - -#include "TClass.h" -#include "RooSegmentedIntegrator2D.h" -#include "RooArgSet.h" -#include "RooIntegratorBinding.h" -#include "RooRealVar.h" -#include "RooNumber.h" -#include "RooNumIntFactory.h" -#include "RooMsgService.h" - -#include - - - -using namespace std; - -ClassImp(RooSegmentedIntegrator2D); -; - - -//////////////////////////////////////////////////////////////////////////////// -/// Register RooSegmentedIntegrator2D, its parameters, dependencies and capabilities with RooNumIntFactory - -void RooSegmentedIntegrator2D::registerIntegrator(RooNumIntFactory& fact) -{ - fact.storeProtoIntegrator(new RooSegmentedIntegrator2D(),RooArgSet(),RooSegmentedIntegrator1D::Class()->GetName()) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor - -RooSegmentedIntegrator2D::RooSegmentedIntegrator2D() : - _xIntegrator(0), _xint(0) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor of integral on given function binding and with given configuration. The -/// integration limits are taken from the definition in the function binding - -RooSegmentedIntegrator2D::RooSegmentedIntegrator2D(const RooAbsFunc& function, const RooNumIntConfig& config) : - RooSegmentedIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooSegmentedIntegrator1D(function,config)))),config) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor integral on given function binding, with given configuration and -/// explicit definition of integration range - -RooSegmentedIntegrator2D::RooSegmentedIntegrator2D(const RooAbsFunc& function, double xmin, double xmax, - double ymin, double ymax, - const RooNumIntConfig& config) : - RooSegmentedIntegrator1D(*(_xint=new RooIntegratorBinding(*(_xIntegrator=new RooSegmentedIntegrator1D(function,ymin,ymax,config)))),xmin,xmax,config) -{ -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Virtual constructor with given function and configuration. Needed by RooNumIntFactory - -RooAbsIntegrator* RooSegmentedIntegrator2D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooSegmentedIntegrator2D(function,config) ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooSegmentedIntegrator2D::~RooSegmentedIntegrator2D() -{ - delete _xint ; - delete _xIntegrator ; -} - - - -//////////////////////////////////////////////////////////////////////////////// -/// Check that our integration range is finite and otherwise return false. -/// Update the limits from the integrand if requested. - -bool RooSegmentedIntegrator2D::checkLimits() const -{ - if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); - _xmin= integrand()->getMinLimit(0); - _xmax= integrand()->getMaxLimit(0); - } - _range= _xmax - _xmin; - if(_range <= 0) { - oocoutE(nullptr,InputArguments) << "RooIntegrator1D::checkLimits: bad range with min >= max" << endl; - return false; - } - bool ret = (RooNumber::isInfinite(_xmin) || RooNumber::isInfinite(_xmax)) ? false : true; - - // Adjust component integrators, if already created - if (_array && ret) { - double segSize = (_xmax - _xmin) / _nseg ; - Int_t i ; - for (i=0 ; i<_nseg ; i++) { - _array[i]->setLimits(_xmin+i*segSize,_xmin+(i+1)*segSize) ; - } - } - - return ret ; -} - - - diff --git a/roofit/roofitcore/src/RooSentinel.cxx b/roofit/roofitcore/src/RooSentinel.cxx index 7943e7914979f..b39c366de0969 100644 --- a/roofit/roofitcore/src/RooSentinel.cxx +++ b/roofit/roofitcore/src/RooSentinel.cxx @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + /***************************************************************************** * Project: RooFit * * Package: RooFitCore * @@ -59,5 +61,4 @@ void RooSentinel::activate() } } - - +/// \endcond diff --git a/roofit/roofitcore/src/RooSentinel.h b/roofit/roofitcore/src/RooSentinel.h index d5abf64a1e2a5..76f60a4dc6a05 100644 --- a/roofit/roofitcore/src/RooSentinel.h +++ b/roofit/roofitcore/src/RooSentinel.h @@ -1,3 +1,5 @@ +/// \cond ROOFIT_INTERNAL + /***************************************************************************** * Project: RooFit * * Package: RooFitCore * @@ -13,6 +15,7 @@ * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ + #ifndef ROO_SENTINEL #define ROO_SENTINEL @@ -33,3 +36,5 @@ class RooSentinel { }; #endif + +/// \endcond diff --git a/roofit/roofitcore/src/RooSimGenContext.cxx b/roofit/roofitcore/src/RooSimGenContext.cxx index 736bff9c7ecc4..825d5f14f59cb 100644 --- a/roofit/roofitcore/src/RooSimGenContext.cxx +++ b/roofit/roofitcore/src/RooSimGenContext.cxx @@ -58,52 +58,31 @@ ClassImp(RooSimGenContext); RooSimGenContext::RooSimGenContext(const RooSimultaneous &model, const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, bool verbose) : - RooAbsGenContext(model,vars,prototype,auxProto,verbose), _pdf(&model), _protoData(0) + RooAbsGenContext(model,vars,prototype,auxProto,verbose), _pdf(&model), _protoData(nullptr) { // Determine if we are requested to generate the index category - RooAbsCategory *idxCat = (RooAbsCategory*) model._indexCat.absArg() ; + RooAbsCategoryLValue const& idxCat = model.indexCat(); RooArgSet pdfVars(vars) ; RooArgSet allPdfVars(pdfVars) ; if (prototype) allPdfVars.add(*prototype->get(),true) ; - if (!idxCat->isDerived()) { - pdfVars.remove(*idxCat,true,true) ; - bool doGenIdx = allPdfVars.find(idxCat->GetName())?true:false ; + RooArgSet catsAmongAllVars; + allPdfVars.selectCommon(model.flattenedCatList(), catsAmongAllVars); - if (!doGenIdx) { + if(catsAmongAllVars.size() != model.flattenedCatList().size()) { oocoutE(_pdf,Generation) << "RooSimGenContext::ctor(" << GetName() << ") ERROR: This context must" - << " generate the index category" << endl ; + << " generate all components of the index category" << endl ; _isValid = false ; _numPdf = 0 ; _haveIdxProto = false ; return ; - } - } else { - bool anyServer(false), allServers(true) ; - for(RooAbsArg* server : idxCat->servers()) { - if (vars.find(server->GetName())) { - anyServer=true ; - pdfVars.remove(*server,true,true) ; - } else { - allServers=false ; - } - } - - if (anyServer && !allServers) { - oocoutE(_pdf,Generation) << "RooSimGenContext::ctor(" << GetName() << ") ERROR: This context must" - << " generate all components of a derived index category" << endl ; - _isValid = false ; - _numPdf = 0 ; - _haveIdxProto = false ; - return ; - } } // We must either have the prototype or extended likelihood to determined // the relative fractions of the components _haveIdxProto = prototype ? true : false ; - _idxCatName = idxCat->GetName() ; + _idxCatName = idxCat.GetName() ; if (!_haveIdxProto && !model.canBeExtended()) { oocoutE(_pdf,Generation) << "RooSimGenContext::ctor(" << GetName() << ") ERROR: Need either extended mode" << " or prototype data to calculate number of events per category" << endl ; @@ -129,7 +108,7 @@ RooSimGenContext::RooSimGenContext(const RooSimultaneous &model, const RooArgSet // Name the context after the associated state and add to list cx->SetName(proxy->name()) ; _gcList.push_back(cx) ; - _gcIndex.push_back(idxCat->lookupIndex(proxy->name())); + _gcIndex.push_back(idxCat.lookupIndex(proxy->name())); // Fill fraction threshold array _fracThresh[i] = _fracThresh[i-1] + (_haveIdxProto?0:pdf->expectedEvents(&allPdfVars)) ; @@ -144,13 +123,14 @@ RooSimGenContext::RooSimGenContext(const RooSimultaneous &model, const RooArgSet // Clone the index category - _idxCatSet = (RooArgSet*) RooArgSet(model._indexCat.arg()).snapshot(true) ; + _idxCatSet = new RooArgSet; + RooArgSet(model.indexCat()).snapshot(*_idxCatSet, true); if (!_idxCatSet) { oocoutE(_pdf,Generation) << "RooSimGenContext::RooSimGenContext(" << GetName() << ") Couldn't deep-clone index category, abort," << endl ; throw std::string("RooSimGenContext::RooSimGenContext() Couldn't deep-clone index category, abort") ; } - _idxCat = (RooAbsCategoryLValue*) _idxCatSet->find(model._indexCat.arg().GetName()) ; + _idxCat = static_cast(_idxCatSet->find(model.indexCat().GetName())); } @@ -176,7 +156,7 @@ RooSimGenContext::~RooSimGenContext() void RooSimGenContext::attach(const RooArgSet& args) { if (_idxCat->isDerived()) { - _idxCat->recursiveRedirectServers(args,true) ; + _idxCat->recursiveRedirectServers(args) ; } // Forward initGenerator call to all components @@ -194,7 +174,7 @@ void RooSimGenContext::initGenerator(const RooArgSet &theEvent) { // Attach the index category clone to the event if (_idxCat->isDerived()) { - _idxCat->recursiveRedirectServers(theEvent,true) ; + _idxCat->recursiveRedirectServers(theEvent) ; } else { _idxCat = (RooAbsCategoryLValue*) theEvent.find(_idxCat->GetName()) ; } @@ -225,12 +205,10 @@ RooDataSet* RooSimGenContext::createDataSet(const char* name, const char* title, map dmap ; for (const auto& nameIdx : *_idxCat) { RooAbsPdf* slicePdf = _pdf->getPdf(nameIdx.first.c_str()); - RooArgSet* sliceObs = slicePdf->getObservables(obs) ; + std::unique_ptr sliceObs{slicePdf->getObservables(obs)}; std::string sliceName = Form("%s_slice_%s", name, nameIdx.first.c_str()); std::string sliceTitle = Form("%s (index slice %s)", title, nameIdx.first.c_str()); - RooDataSet* dset = new RooDataSet(sliceName.c_str(),sliceTitle.c_str(),*sliceObs) ; - dmap[nameIdx.first] = dset ; - delete sliceObs ; + dmap[nameIdx.first] = new RooDataSet(sliceName,sliceTitle,*sliceObs); } _protoData = new RooDataSet(name, title, obs, Index((RooCategory&)*_idxCat), Link(dmap), OwnLinked()) ; } diff --git a/roofit/roofitcore/src/RooSimSplitGenContext.cxx b/roofit/roofitcore/src/RooSimSplitGenContext.cxx index 457314daad7c9..dbe8b668207fd 100644 --- a/roofit/roofitcore/src/RooSimSplitGenContext.cxx +++ b/roofit/roofitcore/src/RooSimSplitGenContext.cxx @@ -50,49 +50,28 @@ ClassImp(RooSimSplitGenContext); /// generation of events to the appropriate component generator context RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const RooArgSet &vars, bool verbose, bool autoBinned, const char* binnedTag) : - RooAbsGenContext(model,vars,0,0,verbose), _pdf(&model) + RooAbsGenContext(model,vars,nullptr,nullptr,verbose), _pdf(&model) { // Determine if we are requested to generate the index category - RooAbsCategory *idxCat = (RooAbsCategory*) model._indexCat.absArg() ; + RooAbsCategoryLValue const& idxCat = model.indexCat(); RooArgSet pdfVars(vars) ; RooArgSet allPdfVars(pdfVars) ; - if (!idxCat->isDerived()) { - pdfVars.remove(*idxCat,true,true) ; - bool doGenIdx = allPdfVars.find(idxCat->GetName())?true:false ; + RooArgSet catsAmongAllVars; + allPdfVars.selectCommon(model.flattenedCatList(), catsAmongAllVars); - if (!doGenIdx) { + if(catsAmongAllVars.size() != model.flattenedCatList().size()) { oocoutE(_pdf,Generation) << "RooSimSplitGenContext::ctor(" << GetName() << ") ERROR: This context must" - << " generate the index category" << endl ; + << " generate all components of the index category" << endl ; _isValid = false ; _numPdf = 0 ; // coverity[UNINIT_CTOR] return ; - } - } else { - bool anyServer(false), allServers(true) ; - for(RooAbsArg* server : idxCat->servers()) { - if (vars.find(server->GetName())) { - anyServer=true ; - pdfVars.remove(*server,true,true) ; - } else { - allServers=false ; - } - } - - if (anyServer && !allServers) { - oocoutE(_pdf,Generation) << "RooSimSplitGenContext::ctor(" << GetName() << ") ERROR: This context must" - << " generate all components of a derived index category" << endl ; - _isValid = false ; - _numPdf = 0 ; - // coverity[UNINIT_CTOR] - return ; - } } // We must extended likelihood to determine the relative fractions of the components - _idxCatName = idxCat->GetName() ; + _idxCatName = idxCat.GetName() ; if (!model.canBeExtended()) { oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << "): All components of the simultaneous PDF " << "must be extended PDFs. Otherwise, it is impossible to calculate the number of events to be generated per component." << endl ; @@ -114,11 +93,10 @@ RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const auto pdf = static_cast(proxy->absArg()); // Create generator context for this PDF - RooArgSet* compVars = pdf->getObservables(pdfVars) ; - RooAbsGenContext* cx = pdf->autoGenContext(*compVars,0,0,verbose,autoBinned,binnedTag) ; - delete compVars ; + std::unique_ptr compVars{pdf->getObservables(pdfVars)}; + RooAbsGenContext* cx = pdf->autoGenContext(*compVars,nullptr,nullptr,verbose,autoBinned,binnedTag) ; - const auto state = idxCat->lookupIndex(proxy->name()); + const auto state = idxCat.lookupIndex(proxy->name()); cx->SetName(proxy->name()) ; _gcList.push_back(cx) ; @@ -134,13 +112,11 @@ RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const } // Clone the index category - _idxCatSet = (RooArgSet*) RooArgSet(model._indexCat.arg()).snapshot(true) ; - if (!_idxCatSet) { + if(RooArgSet(model.indexCat()).snapshot(_idxCatSet, true)) { oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << ") Couldn't deep-clone index category, abort," << endl ; throw std::string("RooSimSplitGenContext::RooSimSplitGenContext() Couldn't deep-clone index category, abort") ; } - - _idxCat = (RooAbsCategoryLValue*) _idxCatSet->find(model._indexCat.arg().GetName()) ; + _idxCat = static_cast(_idxCatSet.find(model.indexCat().GetName())); } @@ -151,7 +127,6 @@ RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const RooSimSplitGenContext::~RooSimSplitGenContext() { delete[] _fracThresh ; - delete _idxCatSet ; for (vector::iterator iter = _gcList.begin() ; iter!=_gcList.end() ; ++iter) { delete (*iter) ; } @@ -165,7 +140,7 @@ RooSimSplitGenContext::~RooSimSplitGenContext() void RooSimSplitGenContext::attach(const RooArgSet& args) { if (_idxCat->isDerived()) { - _idxCat->recursiveRedirectServers(args,true) ; + _idxCat->recursiveRedirectServers(args) ; } // Forward initGenerator call to all components @@ -183,7 +158,7 @@ void RooSimSplitGenContext::initGenerator(const RooArgSet &theEvent) { // Attach the index category clone to the event if (_idxCat->isDerived()) { - _idxCat->recursiveRedirectServers(theEvent,true) ; + _idxCat->recursiveRedirectServers(theEvent) ; } else { _idxCat = (RooAbsCategoryLValue*) theEvent.find(_idxCat->GetName()) ; } @@ -203,7 +178,7 @@ RooDataSet* RooSimSplitGenContext::generate(double nEvents, bool skipInit, bool { if(!isValid()) { coutE(Generation) << ClassName() << "::" << GetName() << ": context is not valid" << endl; - return 0; + return nullptr; } diff --git a/roofit/roofitcore/src/RooSimWSTool.cxx b/roofit/roofitcore/src/RooSimWSTool.cxx index 8ae4c5ba61b0f..dcc1b457b05fc 100644 --- a/roofit/roofitcore/src/RooSimWSTool.cxx +++ b/roofit/roofitcore/src/RooSimWSTool.cxx @@ -18,7 +18,7 @@ /// \class RooSimWSTool /// The RooSimWSTool is a tool operating on RooWorkspace objects that /// can clone PDFs into a series of variations that are joined together -/// into a RooSimultanous PDF. +/// into a RooSimultaneous PDF. /// /// ## Splitting a single PDF /// The simplest use case is to take a workspace PDF as prototype and @@ -164,7 +164,7 @@ RooSimWSTool::~RooSimWSTool() ///
    ///
    Optional Arguments Effect ///
    SplitParam(varname, catname) Split parameter(s) with given name(s) in category(s) with given names -///
    SplitParam(var, cat) Split given parameter(s) in givem category(s) +///
    SplitParam(var, cat) Split given parameter(s) in given category(s) ///
    SplitParamConstrained(vname, cname, remainder) Make constrained split in parameter(s) with given name(s) in category(s) with given names /// putting remainder fraction formula in state with name "remainder" ///
    SplitParamConstrained(var,cat,remainder) Make constrained split in parameter(s) with given name(s) in category(s) with given names @@ -218,7 +218,7 @@ std::unique_ptr RooSimWSTool::validateConfig(Build return nullptr; } } else { - obc->_masterCat = 0 ; + obc->_masterCat = nullptr ; } map::iterator pdfiter ; @@ -262,7 +262,7 @@ std::unique_ptr RooSimWSTool::validateConfig(Build RooArgSet splitCatSet ; list::iterator catiter ; for (catiter = pariter->second.first.begin() ; catiter!=pariter->second.first.end() ; ++catiter) { - RooAbsCategory* cat = _ws->catfunc(catiter->c_str()) ; + RooAbsCategory* cat = _ws->catfunc(*catiter) ; if (!cat) { oocoutE(nullptr, ObjectHandling) << "RooSimWSTool::build() ERROR: associated workspace " << _ws->GetName() << " does not contain a category named " << catiter->c_str() @@ -301,7 +301,7 @@ std::unique_ptr RooSimWSTool::validateConfig(Build list::iterator misi ; for (misi=sr._miStateNameList.begin() ; misi!=sr._miStateNameList.end() ; ++misi) { const RooCatType* ctype = obc->_masterCat->lookupType(misi->c_str(),false) ; - if (ctype==0) { + if (ctype==nullptr) { oocoutE(nullptr, ObjectHandling) << "RooSimWSTool::build() ERROR: master index category " << obc->_masterCat->GetName() << " does not have a state named " << *misi << " which was specified as state associated with p.d.f " << sr.GetName() << endl ; @@ -322,7 +322,7 @@ std::unique_ptr RooSimWSTool::validateConfig(Build list::iterator misi ; for (misi=sr._miStateNameList.begin() ; misi!=sr._miStateNameList.end() ; ++misi) { const RooCatType* ctype = obc->_masterCat->lookupType(misi->c_str(),false) ; - if (ctype==0) { + if (ctype==nullptr) { oocoutE(nullptr, ObjectHandling) << "RooSimWSTool::build() ERROR: master index category " << obc->_masterCat->GetName() << " does not have a state named " << *misi << " which was specified as state associated with p.d.f " << sr.GetName() << endl ; @@ -361,7 +361,7 @@ std::unique_ptr RooSimWSTool::validateConfig(Build return nullptr; } rlist.push_back(ctype) ; - tok = strtok(0,"{,}") ; + tok = strtok(nullptr,"{,}") ; } obc->_restr[cat] = rlist ; @@ -453,7 +453,7 @@ RooSimultaneous* RooSimWSTool::executeBuild(const char* simPdfName, ObjBuildConf string splitName = makeSplitName(splitCatSetTmp) ; // If composite split object does not exist yet, create it now - RooAbsCategory* splitCat = _ws->catfunc(splitName.c_str()) ; + RooAbsCategory* splitCat = _ws->catfunc(splitName) ; if (!splitCat) { auto splitCatOwner = std::make_unique(splitName.c_str(),splitName.c_str(),splitCatSetTmp); splitCat = splitCatOwner.get(); @@ -481,15 +481,13 @@ RooSimultaneous* RooSimWSTool::executeBuild(const char* simPdfName, ObjBuildConf if (splitIter->second.second == typeName) continue ; // Construct name of split leaf - TString splitLeafName(splitIter->first->GetName()) ; - splitLeafName.Append("_") ; - splitLeafName.Append(typeName) ; + std::string splitLeafName = std::string{splitIter->first->GetName()} + "_" + typeName; // Check if split leaf already exists RooAbsArg* splitLeaf = _ws->fundArg(splitLeafName) ; if (!splitLeaf) { // If not create it now - splitLeaf = (RooAbsArg*) splitIter->first->clone(splitLeafName) ; + splitLeaf = (RooAbsArg*) splitIter->first->clone(splitLeafName.c_str()); _ws->import(*splitLeaf,RooFit::Silence(!verbose)) ; } fracLeafList.add(*splitLeaf) ; @@ -580,7 +578,7 @@ RooSimultaneous* RooSimWSTool::executeBuild(const char* simPdfName, ObjBuildConf RooCustomizer* physCustomizer ; if (physCat) { RooAbsPdf* pdf = stateMap[physCat->getCurrentLabel()] ; - if (pdf==0) { + if (pdf==nullptr) { continue ; } const std::string pdfName = pdf->GetName(); @@ -648,14 +646,14 @@ void RooSimWSTool::SplitRule::splitParameter(const char* paramNameList, const ch char* cat = strtok(catBuf,"{,}") ; while(cat) { catList.push_back(cat) ; - cat = strtok(0,"{,}") ; + cat = strtok(nullptr,"{,}") ; } // Now parse parameter list char* param = strtok(paramBuf,"{,}") ; while(param) { _paramSplitMap[param] = pair,string>(catList,"") ; - param = strtok(0,"{,}") ; + param = strtok(nullptr,"{,}") ; } } @@ -676,14 +674,14 @@ void RooSimWSTool::SplitRule::splitParameterConstrained(const char* paramNameLis char* cat = strtok(catBuf,"{,}") ; while(cat) { catList.push_back(cat) ; - cat = strtok(0,"{,}") ; + cat = strtok(nullptr,"{,}") ; } // Now parse parameter list char* param = strtok(paramBuf,"{,}") ; while(param) { _paramSplitMap[param] = pair,string>(catList,remainderStateName) ; - param = strtok(0,"{,}") ; + param = strtok(nullptr,"{,}") ; } } @@ -703,7 +701,7 @@ void RooSimWSTool::SplitRule::configure(const RooCmdArg& arg1,const RooCmdArg& a list::iterator iter ; for (iter=cmdList.begin() ; iter!=cmdList.end() ; ++iter) { - if ((*iter)->opcode()==0) continue ; + if ((*iter)->opcode()==nullptr) continue ; string name = (*iter)->opcode() ; @@ -747,7 +745,7 @@ RooSimWSTool::BuildConfig::BuildConfig(const char* pdfName, const RooCmdArg& arg list::iterator iter ; for (iter=cmdList.begin() ; iter!=cmdList.end() ; ++iter) { - if ((*iter)->opcode()==0) continue ; + if ((*iter)->opcode()==nullptr) continue ; string name = (*iter)->opcode() ; if (name=="Restrict") { restrictBuild((*iter)->getString(0),(*iter)->getString(1)) ; @@ -780,7 +778,7 @@ void RooSimWSTool::BuildConfig::internalAddPdf(const char* pdfName, const char* char* tok = strtok(buf,",") ; while(tok) { sr._miStateNameList.push_back(tok) ; - tok = strtok(0,",") ; + tok = strtok(nullptr,",") ; } _pdfmap[pdfName] = sr ; @@ -811,7 +809,7 @@ RooSimWSTool::MultiBuildConfig::MultiBuildConfig(const char* masterIndexCat) //////////////////////////////////////////////////////////////////////////////// -/// Add protytpe p.d.f 'pdfName' to MultiBuildConfig associated with master indes states 'miStateList'. This +/// Add protytpe p.d.f 'pdfName' to MultiBuildConfig associated with master index states 'miStateList'. This /// method parses the SplitParam() and SplitParamConstrained() arguments void RooSimWSTool::MultiBuildConfig::addPdf(const char* miStateList, const char* pdfName, const RooCmdArg& arg1,const RooCmdArg& arg2, @@ -825,7 +823,7 @@ void RooSimWSTool::MultiBuildConfig::addPdf(const char* miStateList, const char* //////////////////////////////////////////////////////////////////////////////// -/// Add protytpe p.d.f 'pdfName' to MultiBuildConfig associated with master indes states 'miStateList'. +/// Add protytpe p.d.f 'pdfName' to MultiBuildConfig associated with master index states 'miStateList'. void RooSimWSTool::MultiBuildConfig::addPdf(const char* miStateList, const char* pdfName, SplitRule& sr) { diff --git a/roofit/roofitcore/src/RooSimultaneous.cxx b/roofit/roofitcore/src/RooSimultaneous.cxx index e58c7c9b47cc3..1cd9f5b5fe547 100644 --- a/roofit/roofitcore/src/RooSimultaneous.cxx +++ b/roofit/roofitcore/src/RooSimultaneous.cxx @@ -49,7 +49,6 @@ in each category. #include "RooSimultaneous.h" #include "RooAbsCategoryLValue.h" #include "RooPlot.h" -#include "RooCurve.h" #include "RooRealVar.h" #include "RooAddPdf.h" #include "RooAbsData.h" @@ -72,6 +71,30 @@ in each category. #include +namespace { + +std::map createPdfMap(const RooArgList &inPdfList, RooAbsCategoryLValue &inIndexCat) +{ + std::map pdfMap; + auto indexCatIt = inIndexCat.begin(); + for (unsigned int i = 0; i < inPdfList.size(); ++i) { + auto pdf = static_cast(&inPdfList[i]); + const auto &nameIdx = (*indexCatIt++); + pdfMap[nameIdx.first] = pdf; + } + return pdfMap; +} + +} // namespace + +RooSimultaneous::InitializationOutput::~InitializationOutput() = default; + +void RooSimultaneous::InitializationOutput::addPdf(const RooAbsPdf &pdf, std::string const &catLabel) +{ + finalPdfs.push_back(&pdf); + finalCatLabels.emplace_back(catLabel); +} + using namespace std; ClassImp(RooSimultaneous); @@ -89,17 +112,11 @@ ClassImp(RooSimultaneous); RooSimultaneous::RooSimultaneous(const char *name, const char *title, RooAbsCategoryLValue& inIndexCat) : - RooAbsPdf(name,title), - _plotCoefNormSet("!plotCoefNormSet","plotCoefNormSet",this,false,false), - _plotCoefNormRange(0), - _partIntMgr(this,10), - _indexCat("indexCat","Index category",this,inIndexCat), - _numPdf(0) + RooSimultaneous{name, title, std::map{}, inIndexCat} { } - //////////////////////////////////////////////////////////////////////////////// /// Constructor from index category and full list of PDFs. /// In this constructor form, a PDF must be supplied for each indexCat state @@ -112,47 +129,43 @@ RooSimultaneous::RooSimultaneous(const char *name, const char *title, RooSimultaneous::RooSimultaneous(const char *name, const char *title, const RooArgList& inPdfList, RooAbsCategoryLValue& inIndexCat) : - RooAbsPdf(name,title), - _plotCoefNormSet("!plotCoefNormSet","plotCoefNormSet",this,false,false), - _plotCoefNormRange(0), - _partIntMgr(this,10), - _indexCat("indexCat","Index category",this,inIndexCat), - _numPdf(0) + RooSimultaneous{name, title, createPdfMap(inPdfList, inIndexCat), inIndexCat} { if (inPdfList.size() != inIndexCat.size()) { - coutE(InputArguments) << "RooSimultaneous::ctor(" << GetName() - << " ERROR: Number PDF list entries must match number of index category states, no PDFs added" << endl ; - return ; + std::stringstream errMsg; + errMsg << "RooSimultaneous::ctor(" << GetName() + << " ERROR: Number PDF list entries must match number of index category states, no PDFs added"; + coutE(InputArguments) << errMsg.str() << std::endl; + throw std::invalid_argument(errMsg.str()); } - - map pdfMap ; - auto indexCatIt = inIndexCat.begin(); - for (unsigned int i=0; i < inPdfList.size(); ++i) { - auto pdf = static_cast(&inPdfList[i]); - const auto& nameIdx = (*indexCatIt++); - pdfMap[nameIdx.first] = pdf; - } - - initialize(inIndexCat,pdfMap) ; } //////////////////////////////////////////////////////////////////////////////// -RooSimultaneous::RooSimultaneous(const char *name, const char *title, - map pdfMap, RooAbsCategoryLValue& inIndexCat) : - RooAbsPdf(name,title), - _plotCoefNormSet("!plotCoefNormSet","plotCoefNormSet",this,false,false), - _plotCoefNormRange(0), - _partIntMgr(this,10), - _indexCat("indexCat","Index category",this,inIndexCat), - _numPdf(0) +RooSimultaneous::RooSimultaneous(const char *name, const char *title, std::map pdfMap, + RooAbsCategoryLValue &inIndexCat) + : RooSimultaneous(name, title, std::move(*initialize(name ? name : "", inIndexCat, pdfMap))) { - initialize(inIndexCat,pdfMap) ; } +RooSimultaneous::RooSimultaneous(const char *name, const char *title, RooSimultaneous::InitializationOutput &&initInfo) + : RooAbsPdf(name, title), + _plotCoefNormSet("!plotCoefNormSet", "plotCoefNormSet", this, false, false), + _partIntMgr(this, 10), + _indexCat("indexCat", "Index category", this, *initInfo.indexCat) +{ + for (std::size_t i = 0; i < initInfo.finalPdfs.size(); ++i) { + addPdf(*initInfo.finalPdfs[i], initInfo.finalCatLabels[i].c_str()); + } + // Take ownership of eventual super category + if (initInfo.superIndex) { + addOwnedComponents(std::move(initInfo.superIndex)); + } +} +/// \cond ROOFIT_INTERNAL // This class cannot be locally defined in initialize as it cannot be // used as a template argument in that case @@ -161,16 +174,24 @@ namespace RooSimultaneousAux { RooAbsPdf* pdf ; RooSimultaneous* simPdf ; const RooAbsCategoryLValue* subIndex ; - RooArgSet* subIndexComps ; + std::unique_ptr subIndexComps; } ; } -void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::map pdfMap) +/// \endcond + +std::unique_ptr +RooSimultaneous::initialize(std::string const& name, RooAbsCategoryLValue &inIndexCat, + std::map const& pdfMap) + { + auto out = std::make_unique(); + out->indexCat = &inIndexCat; + // First see if there are any RooSimultaneous input components bool simComps(false) ; - for (map::iterator iter=pdfMap.begin() ; iter!=pdfMap.end() ; ++iter) { - if (dynamic_cast(iter->second)) { + for (auto const& item : pdfMap) { + if (dynamic_cast(item.second)) { simComps = true ; break ; } @@ -178,61 +199,58 @@ void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::map::iterator iter=pdfMap.begin() ; iter!=pdfMap.end() ; ++iter) { - failure |= addPdf(*iter->second,iter->first.c_str()) ; + for (auto const& item : pdfMap) { + out->addPdf(*item.second,item.first); } - - if (failure) { - throw std::invalid_argument(std::string("At least one of the PDFs of the RooSimultaneous ") - + GetName() + " is invalid."); - } - return ; + return out; } - // Issue info message that we are about to do some rearraning - coutI(InputArguments) << "RooSimultaneous::initialize(" << GetName() << ") INFO: one or more input component of simultaneous p.d.f.s are" + std::string msgPrefix = "RooSimultaneous::initialize(" + name + ") "; + + // Issue info message that we are about to do some rearranging + oocoutI(nullptr, InputArguments) << msgPrefix << "INFO: one or more input component of simultaneous p.d.f.s are" << " simultaneous p.d.f.s themselves, rewriting composite expressions as one-level simultaneous p.d.f. in terms of" - << " final constituents and extended index category" << endl ; + << " final constituents and extended index category" << std::endl; RooArgSet allAuxCats ; - map compMap ; - for (map::iterator iter=pdfMap.begin() ; iter!=pdfMap.end() ; ++iter) { + std::map compMap ; + for (auto const& item : pdfMap) { RooSimultaneousAux::CompInfo ci ; - ci.pdf = iter->second ; - RooSimultaneous* simComp = dynamic_cast(iter->second) ; + ci.pdf = item.second ; + RooSimultaneous* simComp = dynamic_cast(item.second) ; if (simComp) { ci.simPdf = simComp ; ci.subIndex = &simComp->indexCat() ; - ci.subIndexComps = simComp->indexCat().isFundamental() ? new RooArgSet(simComp->indexCat()) : simComp->indexCat().getVariables() ; - allAuxCats.add(*(ci.subIndexComps),true) ; + ci.subIndexComps = simComp->indexCat().isFundamental() + ? std::make_unique(simComp->indexCat()) + : std::unique_ptr(simComp->indexCat().getVariables()); + allAuxCats.add(*ci.subIndexComps,true) ; } else { - ci.simPdf = 0 ; - ci.subIndex = 0 ; - ci.subIndexComps = 0 ; + ci.simPdf = nullptr; + ci.subIndex = nullptr; } - compMap[iter->first] = ci ; + compMap[item.first] = std::move(ci); } // Construct the 'superIndex' from the nominal index category and all auxiliary components RooArgSet allCats(inIndexCat) ; allCats.add(allAuxCats) ; - string siname = Form("%s_index",GetName()) ; - RooSuperCategory* superIndex = new RooSuperCategory(siname.c_str(),siname.c_str(),allCats) ; - bool failure = false; + std::string siname = name + "_index"; + out->superIndex = std::make_unique(siname.c_str(),siname.c_str(),allCats) ; + auto *superIndex = out->superIndex.get(); + out->indexCat = superIndex; // Now process each of original pdf/state map entries - for (map::iterator citer = compMap.begin() ; citer != compMap.end() ; ++citer) { + for (auto const& citem : compMap) { RooArgSet repliCats(allAuxCats) ; - if (citer->second.subIndexComps) { - repliCats.remove(*citer->second.subIndexComps) ; - delete citer->second.subIndexComps ; + if (citem.second.subIndexComps) { + repliCats.remove(*citem.second.subIndexComps) ; } - inIndexCat.setLabel(citer->first.c_str()) ; + inIndexCat.setLabel(citem.first.c_str()) ; - if (!citer->second.simPdf) { + if (!citem.second.simPdf) { // Entry is a plain p.d.f. assign it to every state permutation of the repliCats set RooSuperCategory repliSuperCat("tmp","tmp",repliCats) ; @@ -243,9 +261,9 @@ void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::mapgetCurrentLabel() ; - failure |= addPdf(*citer->second.pdf,superLabel.c_str()) ; - cxcoutD(InputArguments) << "RooSimultaneous::initialize(" << GetName() - << ") assigning pdf " << citer->second.pdf->GetName() << " to super label " << superLabel << endl ; + out->addPdf(*citem.second.pdf,superLabel); + oocxcoutD(static_cast(nullptr), InputArguments) << msgPrefix + << "assigning pdf " << citem.second.pdf->GetName() << " to super label " << superLabel << endl ; } } else { @@ -255,19 +273,19 @@ void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::mapsecond.subIndex) { - const_cast(citer->second.subIndex)->setLabel(type.first.c_str()); + for (const auto& type : *citem.second.subIndex) { + const_cast(citem.second.subIndex)->setLabel(type.first.c_str()); string superLabel = superIndex->getCurrentLabel() ; - RooAbsPdf* compPdf = citer->second.simPdf->getPdf(type.first.c_str()); + RooAbsPdf* compPdf = citem.second.simPdf->getPdf(type.first); if (compPdf) { - failure |= addPdf(*compPdf,superLabel.c_str()) ; - cxcoutD(InputArguments) << "RooSimultaneous::initialize(" << GetName() - << ") assigning pdf " << compPdf->GetName() << "(member of " << citer->second.pdf->GetName() + out->addPdf(*compPdf,superLabel); + oocxcoutD(static_cast(nullptr), InputArguments) << msgPrefix + << "assigning pdf " << compPdf->GetName() << "(member of " << citem.second.pdf->GetName() << ") to super label " << superLabel << endl ; } else { - coutW(InputArguments) << "RooSimultaneous::initialize(" << GetName() << ") WARNING: No p.d.f. associated with label " - << type.second << " for component RooSimultaneous p.d.f " << citer->second.pdf->GetName() - << "which is associated with master index label " << citer->first << endl ; + oocoutW(nullptr, InputArguments) << msgPrefix << "WARNING: No p.d.f. associated with label " + << type.second << " for component RooSimultaneous p.d.f " << citem.second.pdf->GetName() + << "which is associated with master index label " << citem.first << endl ; } } @@ -278,22 +296,22 @@ void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::mapsecond.subIndex) { - const_cast(citer->second.subIndex)->setLabel(stype.first.c_str()); + for (const auto& stype : *citem.second.subIndex) { + const_cast(citem.second.subIndex)->setLabel(stype.first.c_str()); for (const auto& nameIdx : repliSuperCat) { repliSuperCat.setLabel(nameIdx.first) ; const string superLabel = superIndex->getCurrentLabel() ; - RooAbsPdf* compPdf = citer->second.simPdf->getPdf(stype.first.c_str()); + RooAbsPdf* compPdf = citem.second.simPdf->getPdf(stype.first); if (compPdf) { - failure |= addPdf(*compPdf,superLabel.c_str()) ; - cxcoutD(InputArguments) << "RooSimultaneous::initialize(" << GetName() - << ") assigning pdf " << compPdf->GetName() << "(member of " << citer->second.pdf->GetName() + out->addPdf(*compPdf,superLabel); + oocxcoutD(static_cast(nullptr), InputArguments) << msgPrefix + << "assigning pdf " << compPdf->GetName() << "(member of " << citem.second.pdf->GetName() << ") to super label " << superLabel << endl ; } else { - coutW(InputArguments) << "RooSimultaneous::initialize(" << GetName() << ") WARNING: No p.d.f. associated with label " - << stype.second << " for component RooSimultaneous p.d.f " << citer->second.pdf->GetName() - << "which is associated with master index label " << citer->first << endl ; + oocoutW(nullptr, InputArguments) << msgPrefix << "WARNING: No p.d.f. associated with label " + << stype.second << " for component RooSimultaneous p.d.f " << citem.second.pdf->GetName() + << "which is associated with master index label " << citem.first << endl ; } } } @@ -301,18 +319,10 @@ void RooSimultaneous::initialize(RooAbsCategoryLValue& inIndexCat, std::mapabsArg()) : 0 ; + RooRealProxy* proxy = static_cast(_pdfProxyList.FindObject(catName.c_str())); + return proxy ? static_cast(proxy->absArg()) : nullptr; } @@ -394,7 +404,7 @@ bool RooSimultaneous::addPdf(const RooAbsPdf& pdf, const char* catLabel) } else { // Create a proxy named after the associated index state - TObject* proxy = new RooRealProxy(catLabel,catLabel,this,(RooAbsPdf&)pdf) ; + TObject* proxy = new RooRealProxy(catLabel,catLabel,this,const_cast(pdf)); _pdfProxyList.Add(proxy) ; _numPdf += 1 ; } @@ -407,9 +417,9 @@ bool RooSimultaneous::addPdf(const RooAbsPdf& pdf, const char* catLabel) //////////////////////////////////////////////////////////////////////////////// -/// Examine the pdf components and check if one of them can be extended or must be extended -/// It is enough to have one component that can be exteded or must be extended to return the flag in -/// the total simultaneous pdf +/// Examine the pdf components and check if one of them can be extended or must be extended. +/// It is enough to have one component that can be extended or must be extended to return the flag in +/// the total simultaneous pdf. RooAbsPdf::ExtendMode RooSimultaneous::extendMode() const { @@ -457,7 +467,7 @@ double RooSimultaneous::evaluate() const RooRealProxy* proxy = (RooRealProxy*) _pdfProxyList.FindObject(_indexCat.label()) ; //assert(proxy!=0) ; - if (proxy==0) return 0 ; + if (proxy==nullptr) return 0 ; // Calculate relative weighting factor for sim-pdfs of all extendable components double catFrac(1) ; @@ -501,7 +511,7 @@ double RooSimultaneous::expectedEvents(const RooArgSet* nset) const RooRealProxy* proxy = (RooRealProxy*) _pdfProxyList.FindObject(_indexCat.label()) ; //assert(proxy!=0) ; - if (proxy==0) return 0 ; + if (proxy==nullptr) return 0 ; // Return the selected PDF value, normalized by the number of index states return ((RooAbsPdf*)(proxy->absArg()))->expectedEvents(nset); @@ -525,7 +535,7 @@ Int_t RooSimultaneous::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& an Int_t code ; // Check if this configuration was created before - CacheElem* cache = (CacheElem*) _partIntMgr.getObj(normSet,&analVars,0,RooNameReg::ptr(rangeName)) ; + CacheElem* cache = (CacheElem*) _partIntMgr.getObj(normSet,&analVars,nullptr,RooNameReg::ptr(rangeName)) ; if (cache) { code = _partIntMgr.lastIndex() ; return code+1 ; @@ -534,8 +544,7 @@ Int_t RooSimultaneous::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& an // Create the partial integral set for this request for(auto * proxy : static_range_cast(_pdfProxyList)) { - RooAbsReal* pdfInt = proxy->arg().createIntegral(analVars,normSet,0,rangeName) ; - cache->_partIntList.addOwned(*pdfInt) ; + cache->_partIntList.addOwned(std::unique_ptr{proxy->arg().createIntegral(analVars,normSet,nullptr,rangeName)}); } // Store the partial integral list and return the assigned code ; @@ -581,11 +590,11 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const if (plotSanityChecks(frame)) return frame ; // Extract projection configuration from command list - RooCmdConfig pc(Form("RooSimultaneous::plotOn(%s)",GetName())) ; + RooCmdConfig pc("RooSimultaneous::plotOn(" + std::string(GetName()) + ")"); pc.defineString("sliceCatState","SliceCat",0,"",true) ; pc.defineDouble("scaleFactor","Normalization",0,1.0) ; pc.defineInt("scaleType","Normalization",0,RooAbsPdf::Relative) ; - pc.defineObject("sliceCatList","SliceCat",0,0,true) ; + pc.defineObject("sliceCatList","SliceCat",0,nullptr,true) ; // This dummy is needed for plotOn to recognize the "SliceCatMany" command. // It is not used directly, but the "SliceCat" commands are nested in it. // Removing this dummy definition results in "ERROR: unrecognized command: SliceCatMany". @@ -613,13 +622,13 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const // Look for category slice arguments and add them to the master slice list if found - const char* sliceCatState = pc.getString("sliceCatState",0,true) ; + const char* sliceCatState = pc.getString("sliceCatState",nullptr,true) ; const RooLinkedList& sliceCatList = pc.getObjectList("sliceCatList") ; if (sliceCatState) { // Make the master slice set if it doesnt exist if (!sliceSet) { - sliceSet.reset(new RooArgSet); + sliceSet = std::make_unique(); } // Prepare comma separated label list for parsing @@ -689,7 +698,7 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const // Determine if any servers of the index category are in the projectedVars RooArgSet projIdxServers ; bool anyServers(false) ; - for (const auto server : _indexCat->servers()) { + for (const auto server : flattenedCatList()) { if (projectedVars.find(server->GetName())) { anyServers=true ; projIdxServers.add(*server) ; @@ -726,8 +735,9 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const // Clone the index category to be able to cycle through the category states for plotting without // affecting the category state of our instance - std::unique_ptr idxCloneSet( RooArgSet(*_indexCat).snapshot(true) ); - auto idxCatClone = static_cast( idxCloneSet->find(_indexCat->GetName()) ); + RooArgSet idxCloneSet; + RooArgSet(*_indexCat).snapshot(idxCloneSet, true); + auto idxCatClone = static_cast( idxCloneSet.find(_indexCat->GetName()) ); assert(idxCatClone); // Make list of category columns to exclude from projection data @@ -802,7 +812,7 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const bool skip(false) ; for (const auto idxSliceCompArg : *idxCompSliceSet) { const auto idxSliceComp = static_cast(idxSliceCompArg); - RooAbsCategory* idxComp = (RooAbsCategory*) idxCloneSet->find(idxSliceComp->GetName()) ; + RooAbsCategory* idxComp = (RooAbsCategory*) idxCloneSet.find(idxSliceComp->GetName()) ; if (idxComp->getCurrentIndex()!=idxSliceComp->getCurrentIndex()) { skip=true ; break ; @@ -811,8 +821,7 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const if (skip) continue ; // Instantiate a RRV holding this pdfs weight fraction - RooRealVar *wgtVar = new RooRealVar(proxy->name(),"coef",wTable->getFrac(proxy->name())) ; - wgtCompList.addOwned(*wgtVar) ; + wgtCompList.addOwned(std::make_unique(proxy->name(),"coef",wTable->getFrac(proxy->name()))); sumWeight += wTable->getFrac(proxy->name()) ; // Add the PDF to list list @@ -820,11 +829,11 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const } TString plotVarName(GetName()) ; - RooAddPdf *plotVar = new RooAddPdf(plotVarName,"weighted sum of RS components",pdfCompList,wgtCompList) ; + RooAddPdf plotVar{plotVarName,"weighted sum of RS components",pdfCompList,wgtCompList}; // Fix appropriate coefficient normalization in plot function - if (_plotCoefNormSet.getSize()>0) { - plotVar->fixAddCoefNormalization(_plotCoefNormSet) ; + if (!_plotCoefNormSet.empty()) { + plotVar.fixAddCoefNormalization(_plotCoefNormSet) ; } std::unique_ptr projDataTmp; @@ -833,7 +842,7 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const // Construct cut string to only select projection data event that match the current slice TString cutString ; - if (idxCompSliceSet->getSize()>0) { + if (!idxCompSliceSet->empty()) { bool first(true) ; for (const auto idxSliceCompArg : *idxCompSliceSet) { const auto idxSliceComp = static_cast(idxSliceCompArg); @@ -848,39 +857,37 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const // Make temporary projData without RooSim index category components RooArgSet projDataVars(*projData->get()) ; - RooArgSet* idxCatServers = _indexCat.arg().getObservables(frame->getNormVars()) ; + RooArgSet idxCatServers; + _indexCat.arg().getObservables(frame->getNormVars(), idxCatServers) ; - projDataVars.remove(*idxCatServers,true,true) ; + projDataVars.remove(idxCatServers,true,true) ; - if (idxCompSliceSet->getSize()>0) { - projDataTmp.reset( const_cast(projData)->reduce(projDataVars,cutString) ); + if (!idxCompSliceSet->empty()) { + projDataTmp = std::unique_ptr{const_cast(projData)->reduce(projDataVars,cutString)}; } else { - projDataTmp.reset( const_cast(projData)->reduce(projDataVars) ); + projDataTmp = std::unique_ptr{const_cast(projData)->reduce(projDataVars)}; } if (projSet) { projSetTmp.add(*projSet) ; - projSetTmp.remove(*idxCatServers,true,true); + projSetTmp.remove(idxCatServers,true,true); } - - - delete idxCatServers ; } - if (_indexCat.arg().isDerived() && idxCompSliceSet->getSize()>0) { + if (_indexCat.arg().isDerived() && !idxCompSliceSet->empty()) { coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName() << " represents a slice in index category components " << *idxCompSliceSet << endl ; - RooArgSet* idxCompProjSet = _indexCat.arg().getObservables(frame->getNormVars()) ; - idxCompProjSet->remove(*idxCompSliceSet,true,true) ; - if (idxCompProjSet->getSize()>0) { + RooArgSet idxCompProjSet; + _indexCat.arg().getObservables(frame->getNormVars(), idxCompProjSet) ; + idxCompProjSet.remove(*idxCompSliceSet,true,true) ; + if (!idxCompProjSet.empty()) { coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName() - << " averages with data index category components " << *idxCompProjSet << endl ; + << " averages with data index category components " << idxCompProjSet << endl ; } - delete idxCompProjSet ; } else { coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName() << " averages with data index category (" << _indexCat.arg().GetName() << ")" << endl ; @@ -899,49 +906,20 @@ RooPlot* RooSimultaneous::plotOn(RooPlot *frame, RooLinkedList& cmdList) const cmdList2.Add(&tmp2) ; RooPlot* frame2 ; - if (projSetTmp.getSize()>0) { + if (!projSetTmp.empty()) { // Plot temporary function RooCmdArg tmp3 = RooFit::Project(projSetTmp) ; cmdList2.Add(&tmp3) ; - frame2 = plotVar->plotOn(frame,cmdList2) ; + frame2 = plotVar.plotOn(frame,cmdList2) ; } else { // Plot temporary function - frame2 = plotVar->plotOn(frame,cmdList2) ; + frame2 = plotVar.plotOn(frame,cmdList2) ; } - // Cleanup - delete plotVar ; - return frame2 ; } - -//////////////////////////////////////////////////////////////////////////////// -/// OBSOLETE -- Retained for backward compatibility - -RooPlot* RooSimultaneous::plotOn(RooPlot *frame, Option_t* drawOptions, double scaleFactor, - ScaleType stype, const RooAbsData* projData, const RooArgSet* projSet, - double /*precision*/, bool /*shiftToZero*/, const RooArgSet* /*projDataSet*/, - double /*rangeLo*/, double /*rangeHi*/, RooCurve::WingMode /*wmode*/) const -{ - // Make command list - RooLinkedList cmdList ; - cmdList.Add(new RooCmdArg(RooFit::DrawOption(drawOptions))) ; - cmdList.Add(new RooCmdArg(RooFit::Normalization(scaleFactor,stype))) ; - if (projData) cmdList.Add(new RooCmdArg(RooFit::ProjWData(*projData))) ; - if (projSet) cmdList.Add(new RooCmdArg(RooFit::Project(*projSet))) ; - - // Call new method - RooPlot* ret = plotOn(frame,cmdList) ; - - // Cleanup - cmdList.Delete() ; - return ret ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Interface function used by test statistics to freeze choice of observables /// for interpretation of fraction coefficients. Needed here because a RooSimultaneous @@ -974,8 +952,8 @@ RooAbsGenContext* RooSimultaneous::autoGenContext(const RooArgSet &vars, const R { const char* idxCatName = _indexCat.arg().GetName() ; - if (vars.find(idxCatName) && prototype==0 - && (auxProto==0 || auxProto->empty()) + if (vars.find(idxCatName) && prototype==nullptr + && (auxProto==nullptr || auxProto->empty()) && (autoBinned || (binnedTag && strlen(binnedTag)))) { // Return special generator config that can also do binned generation for selected states @@ -996,53 +974,37 @@ RooAbsGenContext* RooSimultaneous::autoGenContext(const RooArgSet &vars, const R RooAbsGenContext* RooSimultaneous::genContext(const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, bool verbose) const { - const char* idxCatName = _indexCat.arg().GetName() ; - const RooArgSet* protoVars = prototype ? prototype->get() : 0 ; - - if (vars.find(idxCatName) || (protoVars && protoVars->find(idxCatName))) { - - // Generating index category: return special sim-context - return new RooSimGenContext(*this,vars,prototype,auxProto,verbose) ; + RooArgSet allVars{vars}; + if(prototype) allVars.add(*prototype->get()); - } else if (_indexCat.arg().isDerived()) { - // Generating dependents of a derived index category + RooArgSet catsAmongAllVars; + allVars.selectCommon(flattenedCatList(), catsAmongAllVars); - // Determine if we none,any or all servers - bool anyServer(false), allServers(true) ; - if (prototype) { - for(RooAbsArg * server : _indexCat.arg().servers()) { - if (prototype->get()->find(server->GetName())) { - anyServer=true ; - } else { - allServers=false ; - } - } - } else { - allServers=true ; + // Not generating index cat: return context for pdf associated with present index state + if(catsAmongAllVars.empty()) { + auto* proxy = static_cast(_pdfProxyList.FindObject(_indexCat->getCurrentLabel())); + if (!proxy) { + coutE(InputArguments) << "RooSimultaneous::genContext(" << GetName() + << ") ERROR: no PDF associated with current state (" + << _indexCat.arg().GetName() << "=" << _indexCat.arg().getCurrentLabel() << ")" << endl ; + return nullptr; } + return static_cast(proxy->absArg())->genContext(vars,prototype,auxProto,verbose) ; + } - if (allServers) { - // Use simcontext if we have all servers + RooArgSet catsAmongProtoVars; + if(prototype) { + prototype->get()->selectCommon(flattenedCatList(), catsAmongProtoVars); - return new RooSimGenContext(*this,vars,prototype,auxProto,verbose) ; - } else if (!allServers && anyServer) { + if(!catsAmongProtoVars.empty() && catsAmongProtoVars.size() != flattenedCatList().size()) { // Abort if we have only part of the servers coutE(Plotting) << "RooSimultaneous::genContext: ERROR: prototype must include either all " - << " components of the RooSimultaneous index category or none " << endl ; - return 0 ; + << " components of the RooSimultaneous index category or none " << std::endl; + return nullptr; } - // Otherwise make single gencontext for current state } - // Not generating index cat: return context for pdf associated with present index state - RooRealProxy* proxy = (RooRealProxy*) _pdfProxyList.FindObject(_indexCat.arg().getCurrentLabel()) ; - if (!proxy) { - coutE(InputArguments) << "RooSimultaneous::genContext(" << GetName() - << ") ERROR: no PDF associated with current state (" - << _indexCat.arg().GetName() << "=" << _indexCat.arg().getCurrentLabel() << ")" << endl ; - return 0 ; - } - return ((RooAbsPdf*)proxy->absArg())->genContext(vars,prototype,auxProto,verbose) ; + return new RooSimGenContext(*this,vars,prototype,auxProto,verbose) ; } @@ -1057,8 +1019,8 @@ RooDataHist* RooSimultaneous::fillDataHist(RooDataHist *hist, bool showProgress) const { if (RooAbsReal::fillDataHist (hist, nset, scaleFactor, - correctForBinVolume, showProgress) == 0) - return 0; + correctForBinVolume, showProgress) == nullptr) + return nullptr; const double sum = hist->sumEntries(); if (sum != 0) { @@ -1076,35 +1038,32 @@ RooDataHist* RooSimultaneous::fillDataHist(RooDataHist *hist, //////////////////////////////////////////////////////////////////////////////// /// Special generator interface for generation of 'global observables' -- for RooStats tools -RooDataSet* RooSimultaneous::generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) +RooFit::OwningPtr RooSimultaneous::generateSimGlobal(const RooArgSet& whatVars, Int_t nEvents) { // Make set with clone of variables (placeholder for output) - RooArgSet* globClone = (RooArgSet*) whatVars.snapshot() ; + RooArgSet globClone; + whatVars.snapshot(globClone); - RooDataSet* data = new RooDataSet("gensimglobal","gensimglobal",whatVars) ; + auto data = std::make_unique("gensimglobal","gensimglobal",whatVars); for (Int_t i=0 ; igetObservables(whatVars) ; - RooDataSet* tmp = pdftmp->generate(*globtmp,1) ; + RooArgSet globtmp; + pdftmp->getObservables(&whatVars, globtmp) ; + std::unique_ptr tmp{pdftmp->generate(globtmp,1)}; // Transfer values to output placeholder - globClone->assign(*tmp->get(0)) ; - - // Cleanup - delete globtmp ; - delete tmp ; + globClone.assign(*tmp->get(0)) ; } - data->add(*globClone) ; + data->add(globClone) ; } - delete globClone ; - return data ; + return RooFit::Detail::owningPtr(std::move(data)); } @@ -1121,11 +1080,11 @@ void RooSimultaneous::wrapPdfsInBinSamplingPdfs(RooAbsData const &data, double p for (auto const &item : this->indexCat()) { auto const &catName = item.first; - auto &pdf = *this->getPdf(catName.c_str()); + auto &pdf = *this->getPdf(catName); if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) { // Set the "ORIGNAME" attribute the indicate to - // RooAbsArg::redirectServers() wich pdf should be replaced by this + // RooAbsArg::redirectServers() which pdf should be replaced by this // RooBinSamplingPdf in the RooSimultaneous. newSamplingPdf->setAttribute( (std::string("ORIGNAME:") + pdf.GetName()).c_str()); @@ -1161,7 +1120,7 @@ void RooSimultaneous::wrapPdfsInBinSamplingPdfs(RooAbsData const &data, for (auto const &item : this->indexCat()) { auto const &catName = item.first; - auto &pdf = *this->getPdf(catName.c_str()); + auto &pdf = *this->getPdf(catName); std::string pdfName = pdf.GetName(); auto found = precisions.find(useCategoryNames ? catName : pdfName); @@ -1172,7 +1131,7 @@ void RooSimultaneous::wrapPdfsInBinSamplingPdfs(RooAbsData const &data, if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) { // Set the "ORIGNAME" attribute the indicate to - // RooAbsArg::redirectServers() wich pdf should be replaced by this + // RooAbsArg::redirectServers() which pdf should be replaced by this // RooBinSamplingPdf in the RooSimultaneous. newSamplingPdf->setAttribute( (std::string("ORIGNAME:") + pdf.GetName()).c_str()); @@ -1183,3 +1142,107 @@ void RooSimultaneous::wrapPdfsInBinSamplingPdfs(RooAbsData const &data, this->redirectServers(newSamplingPdfs, false, true); this->addOwnedComponents(std::move(newSamplingPdfs)); } + +/// Internal utility function to get a list of all category components for this +/// RooSimultaneous. The output contains only the index category if it is a +/// RooCategory, or the list of all category components if it is a +/// RooSuperCategory. +RooArgSet const& RooSimultaneous::flattenedCatList() const +{ + // Note that the index category of a RooSimultaneous can only be of type + // RooCategory or RooSuperCategory, because these are the only classes that + // inherit from RooAbsCategoryLValue. + if (auto superCat = dynamic_cast(&_indexCat.arg())) { + return superCat->inputCatList(); + } + + if(!_indexCatSet) { + _indexCatSet = std::make_unique(_indexCat.arg()); + } + return *_indexCatSet; +} + +namespace { + +void prefixArgs(RooAbsArg *arg, std::string const &prefix, RooArgSet const &normSet) +{ + if (!arg->getStringAttribute("__prefix__")) { + arg->SetName((prefix + arg->GetName()).c_str()); + arg->setStringAttribute("__prefix__", prefix.c_str()); + } + for (RooAbsArg *server : arg->servers()) { + if (server->isFundamental() && normSet.find(*server)) { + prefixArgs(server, prefix, normSet); + server->setAttribute("__obs__"); + } else if (!server->isFundamental()) { + prefixArgs(server, prefix, normSet); + } + } +} + +} // namespace + +std::unique_ptr +RooSimultaneous::compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const +{ + std::unique_ptr newSimPdf{static_cast(this->Clone())}; + + const char *rangeName = this->getStringAttribute("RangeName"); + bool splitRange = this->getAttribute("SplitRange"); + + RooArgSet newPdfs; + std::vector catNames; + + for (auto *proxy : static_range_cast(newSimPdf->_pdfProxyList)) { + catNames.emplace_back(proxy->GetName()); + std::string const &catName = catNames.back(); + const std::string prefix = "_" + catName + "_"; + + const std::string origname = proxy->arg().GetName(); + + auto pdfClone = RooHelpers::cloneTreeWithSameParameters(static_cast(proxy->arg()), &normSet); + + prefixArgs(pdfClone.get(), prefix, normSet); + + std::unique_ptr pdfNormSet( + static_cast(std::unique_ptr(pdfClone->getVariables())->selectByAttrib("__obs__", true))); + + if (rangeName) { + pdfClone->setNormRange(RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, catName).c_str()); + } + + RooFit::Detail::CompileContext pdfContext{*pdfNormSet}; + pdfContext.setLikelihoodMode(ctx.likelihoodMode()); + auto *pdfFinal = pdfContext.compile(*pdfClone, *newSimPdf, *pdfNormSet); + + pdfFinal->fixAddCoefNormalization(*pdfNormSet, false); + + pdfClone->SetName((std::string("_") + pdfClone->GetName()).c_str()); + pdfFinal->addOwnedComponents(std::move(pdfClone)); + + pdfFinal->setAttribute(("ORIGNAME:" + origname).c_str()); + newPdfs.add(*pdfFinal); + + // We will remove the old pdf server because we will fill the new ones by + // hand via the creation of new proxies. + newSimPdf->removeServer(const_cast(proxy->arg()), true); + } + + // Replace pdfs with compiled pdfs. Don't use RooAbsArg::redirectServers() + // here, because it doesn't support replacing two servers with the same name + // (it can happen in a RooSimultaneous that two pdfs have the same name). + + // First delete old proxies (we have already removed the servers before). + newSimPdf->_pdfProxyList.Delete(); + + // Recreate the _pdfProxyList with the compiled pdfs + for (std::size_t i = 0; i < newPdfs.size(); ++i) { + const char *label = catNames[i].c_str(); + newSimPdf->_pdfProxyList.Add( + new RooRealProxy(label, label, newSimPdf.get(), *static_cast(newPdfs[i]))); + } + + ctx.compileServers(*newSimPdf, normSet); // to trigger compiling also the index category + + return newSimPdf; +} diff --git a/roofit/roofitcore/src/RooStreamParser.cxx b/roofit/roofitcore/src/RooStreamParser.cxx index 066d544a4b036..231073b4c6272 100644 --- a/roofit/roofitcore/src/RooStreamParser.cxx +++ b/roofit/roofitcore/src/RooStreamParser.cxx @@ -35,7 +35,7 @@ #include "Riostream.h" -#include +#include #ifndef _WIN32 #include @@ -149,7 +149,7 @@ TString RooStreamParser::readToken() } } - while(1) { + while(true) { // Buffer overflow protection if (bufptr >= 63999) { oocoutW(nullptr, InputArguments) @@ -426,7 +426,7 @@ bool RooStreamParser::readDouble(double& value, bool /*zapOnError*/) bool RooStreamParser::convertToDouble(const TString& token, double& value) { - char* endptr = 0; + char* endptr = nullptr; const char* data=token.Data() ; // Handle +/- infinity cases, (token is guaranteed to be >1 char long) @@ -466,7 +466,7 @@ bool RooStreamParser::readInteger(Int_t& value, bool /*zapOnError*/) bool RooStreamParser::convertToInteger(const TString& token, Int_t& value) { - char* endptr = 0; + char* endptr = nullptr; const char* data=token.Data() ; value = strtol(data,&endptr,10) ; bool error = (endptr-data!=token.Length()) ; diff --git a/roofit/roofitcore/src/RooStringVar.cxx b/roofit/roofitcore/src/RooStringVar.cxx index fac87a57b8dd4..480dd4bce9cc5 100644 --- a/roofit/roofitcore/src/RooStringVar.cxx +++ b/roofit/roofitcore/src/RooStringVar.cxx @@ -35,7 +35,7 @@ RooStringVar is a RooAbsArg implementing string values. /// Constructor with initial value. The size argument is ignored. RooStringVar::RooStringVar(const char *name, const char *title, const char* value, Int_t) : RooAbsArg(name, title), - _string(value) + _string(value), _stringAddr(&_string) { setValueDirty(); } @@ -47,7 +47,7 @@ RooStringVar::RooStringVar(const char *name, const char *title, const char* valu RooStringVar::RooStringVar(const RooStringVar& other, const char* name) : RooAbsArg(other, name), - _string(other._string) + _string(other._string), _stringAddr(&_string) { setValueDirty(); } @@ -105,7 +105,7 @@ void RooStringVar::attachToTree(TTree& t, Int_t) // First determine if branch is taken TBranch* branch ; if ((branch = t.GetBranch(GetName()))) { - t.SetBranchAddress(GetName(), &_string); + t.SetBranchAddress(GetName(), &_stringAddr); } else { t.Branch(GetName(), &_string); } @@ -137,7 +137,7 @@ void RooStringVar::setTreeBranchStatus(TTree& t, bool active) { TBranch* branch = t.GetBranch(GetName()) ; if (branch) { - t.SetBranchStatus(GetName(),active?1:0) ; + t.SetBranchStatus(GetName(),active?true:false) ; } } diff --git a/roofit/roofitcore/src/RooStudyManager.cxx b/roofit/roofitcore/src/RooStudyManager.cxx index aa95d107d85f9..a7658fe1951ff 100644 --- a/roofit/roofitcore/src/RooStudyManager.cxx +++ b/roofit/roofitcore/src/RooStudyManager.cxx @@ -103,8 +103,8 @@ void RooStudyManager::runProof(Int_t nExperiments, const char* proofHost, bool s coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") opening PROOF session" << endl ; void* p = (void*) gROOT->ProcessLineFast(Form("TProof::Open(\"%s\")",proofHost)) ; - // Check that PROOF initialization actually succeeeded - if (p==0) { + // Check that PROOF initialization actually succeeded + if (p==nullptr) { coutE(Generation) << "RooStudyManager::runProof(" << GetName() << ") ERROR initializing proof, aborting" << endl ; return ; } @@ -181,7 +181,7 @@ void RooStudyManager::prepareBatchInput(const char* studyName, Int_t nExpPerJob, // Write uuencoded ROOT file (base64) in driver script gSystem->Exec(Form("cat study_data_%s.root | uuencode -m study_data_%s.root >> study_driver_%s.sh",studyName,studyName,studyName)) ; - // Write remainder of deriver script + // Write remainder of driver script ofstream bdr2 (Form("study_driver_%s.sh",studyName),ios::app) ; bdr2 << "EOR" << endl << "fi" << endl diff --git a/roofit/roofitcore/src/RooStudyPackage.cxx b/roofit/roofitcore/src/RooStudyPackage.cxx index 4351e47687925..f6d3527fd46ce 100644 --- a/roofit/roofitcore/src/RooStudyPackage.cxx +++ b/roofit/roofitcore/src/RooStudyPackage.cxx @@ -48,7 +48,7 @@ ClassImp(RooStudyPackage); //////////////////////////////////////////////////////////////////////////////// -RooStudyPackage::RooStudyPackage() : _ws(0) +RooStudyPackage::RooStudyPackage() : _ws(nullptr) { } diff --git a/roofit/roofitcore/src/RooTFoamBinding.cxx b/roofit/roofitcore/src/RooTFoamBinding.cxx index 4b51f1b22b4be..d67eaf0c309ad 100644 --- a/roofit/roofitcore/src/RooTFoamBinding.cxx +++ b/roofit/roofitcore/src/RooTFoamBinding.cxx @@ -14,6 +14,8 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ +/// \cond ROOFIT_INTERNAL + /** \file RooTFoamBinding.cxx \class RooTFoamBinding @@ -31,22 +33,19 @@ Lightweight interface adaptor that binds a RooAbsPdf to TFOAM #include "RooAbsPdf.h" #include "RooArgSet.h" -#include +#include using namespace std; -ClassImp(RooTFoamBinding); -; - //////////////////////////////////////////////////////////////////////////////// RooTFoamBinding::RooTFoamBinding(const RooAbsReal& pdf, const RooArgSet& observables) { _nset.add(observables) ; - _binding = new RooRealBinding(pdf,observables,&_nset,false,0) ; + _binding = new RooRealBinding(pdf,observables,&_nset,false,nullptr) ; } @@ -72,3 +71,5 @@ double RooTFoamBinding::Density(Int_t ndim, double *xvec) double ret = (*_binding)(x) ; return ret<0?0:ret ; } + +/// \endcond diff --git a/roofit/roofitcore/inc/RooTFoamBinding.h b/roofit/roofitcore/src/RooTFoamBinding.h similarity index 78% rename from roofit/roofitcore/inc/RooTFoamBinding.h rename to roofit/roofitcore/src/RooTFoamBinding.h index 9e2abc865fb09..62161fc437c5e 100644 --- a/roofit/roofitcore/inc/RooTFoamBinding.h +++ b/roofit/roofitcore/src/RooTFoamBinding.h @@ -13,30 +13,32 @@ * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ + +/// \cond ROOFIT_INTERNAL + #ifndef ROO_TFOAM_BINDING #define ROO_TFOAM_BINDING #include "TFoamIntegrand.h" #include "RooArgSet.h" #include "RooRealBinding.h" -class RooAbsPdf ; +class RooAbsPdf; +// Function binding to RooAbsReal object class RooTFoamBinding : public TFoamIntegrand { public: - RooTFoamBinding(const RooAbsReal& pdf, const RooArgSet& observables) ; - ~RooTFoamBinding() override; + RooTFoamBinding(const RooAbsReal &pdf, const RooArgSet &observables); + ~RooTFoamBinding() override; - double Density(Int_t ndim, double *) override ; + double Density(Int_t ndim, double *) override; - RooRealBinding& binding() { return *_binding ; } + RooRealBinding &binding() { return *_binding; } protected: - - RooArgSet _nset ; - RooRealBinding* _binding ; - - ClassDefOverride(RooTFoamBinding,0) // Function binding to RooAbsReal object + RooArgSet _nset; + RooRealBinding *_binding; }; #endif +/// \endcond diff --git a/roofit/roofitcore/src/RooTObjWrap.cxx b/roofit/roofitcore/src/RooTObjWrap.cxx index 26c40aaedad47..37340a1c2ac95 100644 --- a/roofit/roofitcore/src/RooTObjWrap.cxx +++ b/roofit/roofitcore/src/RooTObjWrap.cxx @@ -14,12 +14,14 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ +/// \cond ROOFIT_INTERNAL + /** \file RooTObjWrap.cxx \class RooTObjWrap \ingroup Roofitcore -RooInt is a minimal implementation of a TNamed holding a TObject +RooTObjWrap is a minimal implementation of a TNamed holding a TObject **/ #include "RooTObjWrap.h" @@ -29,3 +31,4 @@ using namespace std; ClassImp(RooTObjWrap); ; +/// \endcond diff --git a/roofit/roofitcore/src/RooTrace.cxx b/roofit/roofitcore/src/RooTrace.cxx index 8f0a56b8a5ac1..ca18d2c6c606d 100644 --- a/roofit/roofitcore/src/RooTrace.cxx +++ b/roofit/roofitcore/src/RooTrace.cxx @@ -24,6 +24,64 @@ objects. When tracing is active, a table of live RooFit objects is kept that can be queried at any time. In verbose mode, messages are printed in addition at the construction and destruction of each object. + +Usage example: +\code{.cpp} +void exampleRooTrace() +{ + using namespace RooFit; + + // Activate RooFit memory tracing + RooTrace::active(true); + + // Construct gauss(x,m,s) + RooRealVar x("x", "x", -10, 10); + RooRealVar m("m", "m", 0, -10, 10); + RooRealVar s("s", "s", 1, -10, 10); + RooGaussian gauss("g", "g", x, m, s); + + // Show dump of all RooFit object in memory + RooTrace::dump(); + + // Activate verbose mode + RooTrace::verbose(true); + + // Construct poly(x,p0) + RooRealVar p0("p0", "p0", 0.01, 0., 1.); + RooPolynomial poly("p", "p", x, p0); + + // Put marker in trace list for future reference + RooTrace::mark(); + + // Construct model = f*gauss(x) + (1-f)*poly(x) + RooRealVar f("f", "f", 0.5, 0., 1.); + RooAddPdf model("model", "model", RooArgSet(gauss, poly), f); + + // Show object added to memory since marker + RooTrace::printObjectCounts(); + + // Since verbose mode is still on, you will see messages + // pertaining to destructor calls of all RooFit objects + // made in this macro + // + // A call to RooTrace::dump() at the end of this macro + // should show that there a no RooFit object left in memory +} +\endcode + +\note In the ROOT releases, the RooTrace is disabled at compile time and the +example above will not print any objects. If you are an advanced developer who +wants to use the RooTrace, you need to recompile ROOT after changing the +`TRACE_CREATE` and `TRACE_DESTROY` macros in RooTrace.h to call the RooTrace +functions: + +\code{.cpp} +#define TRACE_CREATE RooTrace::create(this); +#define TRACE_DESTROY RooTrace::destroy(this); +\endcode + +However, as ROOT is not build with this by default, the RooTrace is not tested +and there is no guarantee that this works. **/ #include "RooTrace.h" @@ -40,14 +98,14 @@ using namespace std; ClassImp(RooTrace); ; -RooTrace* RooTrace::_instance=0 ; +RooTrace* RooTrace::_instance=nullptr ; //////////////////////////////////////////////////////////////////////////////// RooTrace& RooTrace::instance() { - if (_instance==0) _instance = new RooTrace() ; + if (_instance==nullptr) _instance = new RooTrace() ; return *_instance ; } @@ -295,7 +353,7 @@ void RooTrace::printObjectCounts3() void RooTrace::callgrind_zero() { - ooccoutD((TObject*)0,Tracing) << "RooTrace::callgrind_zero()" << endl ; + ooccoutD((TObject*)nullptr,Tracing) << "RooTrace::callgrind_zero()" << endl ; } //////////////////////////////////////////////////////////////////////////////// @@ -307,5 +365,5 @@ void RooTrace::callgrind_zero() void RooTrace::callgrind_dump() { - ooccoutD((TObject*)0,Tracing) << "RooTrace::callgrind_dump()" << endl ; + ooccoutD((TObject*)nullptr,Tracing) << "RooTrace::callgrind_dump()" << endl ; } diff --git a/roofit/roofitcore/src/RooTreeDataStore.cxx b/roofit/roofitcore/src/RooTreeDataStore.cxx index 75f9c02b3a2a8..37a664aa01e93 100644 --- a/roofit/roofitcore/src/RooTreeDataStore.cxx +++ b/roofit/roofitcore/src/RooTreeDataStore.cxx @@ -153,8 +153,8 @@ RooTreeDataStore::RooTreeDataStore(RooStringView name, RooStringView title, RooA // WVE NEED TO ADJUST THIS FOR WEIGHTS // Protected constructor for internal use only - _tree = 0 ; - _cacheTree = 0 ; + _tree = nullptr ; + _cacheTree = nullptr ; createTree(makeTreeName(), title); // Deep clone cutVar and attach clone to this dataset @@ -167,11 +167,11 @@ RooTreeDataStore::RooTreeDataStore(RooStringView name, RooStringView title, RooA // Constructor from existing data set with list of variables that preserves the cache initialize(); - attachCache(0,((RooTreeDataStore&)tds)._cachedVars) ; + attachCache(nullptr,((RooTreeDataStore&)tds)._cachedVars) ; // WVE copy values of cached variables here!!! _cacheTree->CopyEntries(((RooTreeDataStore&)tds)._cacheTree) ; - _cacheOwner = 0 ; + _cacheOwner = nullptr ; loadValues(&tds,cloneVar.get(),cutRange,nStart,nStop); } @@ -217,7 +217,7 @@ RooRealVar* RooTreeDataStore::weightVar(const RooArgSet& allVars, const char* wg RooRealVar* wgt = dynamic_cast(allVars.find(wgtName)) ; return wgt ; } - return 0 ; + return nullptr ; } @@ -267,9 +267,9 @@ RooTreeDataStore::RooTreeDataStore(const RooTreeDataStore& other, const char* ne //////////////////////////////////////////////////////////////////////////////// RooTreeDataStore::RooTreeDataStore(const RooTreeDataStore& other, const RooArgSet& vars, const char* newname) : - RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():0),newname), + RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():nullptr),newname), _varsww(vars), - _wgtVar(other._wgtVar?weightVar(vars,other._wgtVar->GetName()):0), + _wgtVar(other._wgtVar?weightVar(vars,other._wgtVar->GetName()):nullptr), _extWgtArray(other._extWgtArray), _extWgtErrLoArray(other._extWgtErrLoArray), _extWgtErrHiArray(other._extWgtErrHiArray), @@ -327,7 +327,7 @@ void RooTreeDataStore::initialize() void RooTreeDataStore::createTree(RooStringView name, RooStringView title) { if (!_tree) { - _tree = new TTree(name,title); + _tree = new TTree(name.c_str(),title.c_str()); _tree->ResetBit(kCanDelete); _tree->ResetBit(kMustCleanup); _tree->SetDirectory(nullptr); @@ -345,8 +345,8 @@ void RooTreeDataStore::createTree(RooStringView name, RooStringView title) } if (!_cacheTree) { - _cacheTree = new TTree(TString{static_cast(name)} + "_cacheTree", TString{static_cast(title)}); - _cacheTree->SetDirectory(0) ; + _cacheTree = new TTree(TString{name.c_str()} + "_cacheTree", TString{title.c_str()}); + _cacheTree->SetDirectory(nullptr) ; gDirectory->RecursiveRemove(_cacheTree) ; } @@ -375,11 +375,12 @@ void RooTreeDataStore::loadValues(const TTree *t, const RooFormulaVar* select, c tClone->SetDirectory(t->GetDirectory()); // Clone list of variables - std::unique_ptr sourceArgSet( _varsww.snapshot(false) ); + RooArgSet sourceArgSet; + _varsww.snapshot(sourceArgSet, false); // Check that we have the branches: bool missingBranches = false; - for (const auto var : *sourceArgSet) { + for (const auto var : sourceArgSet) { if (!tClone->GetBranch(var->GetName())) { missingBranches = true; coutE(InputArguments) << "Didn't find a branch in Tree '" << tClone->GetName() << "' to read variable '" @@ -394,7 +395,7 @@ void RooTreeDataStore::loadValues(const TTree *t, const RooFormulaVar* select, c } // Attach args in cloned list to cloned source tree - for (const auto sourceArg : *sourceArgSet) { + for (const auto sourceArg : sourceArgSet) { sourceArg->attachToTree(*tClone,_defTreeBufSize) ; } @@ -402,7 +403,7 @@ void RooTreeDataStore::loadValues(const TTree *t, const RooFormulaVar* select, c std::unique_ptr selectClone; if (select) { selectClone.reset( static_cast(select->cloneTree()) ); - selectClone->recursiveRedirectServers(*sourceArgSet) ; + selectClone->recursiveRedirectServers(sourceArgSet) ; selectClone->setOperMode(RooAbsArg::ADirty,true) ; } @@ -416,9 +417,9 @@ void RooTreeDataStore::loadValues(const TTree *t, const RooFormulaVar* select, c // Copy from source to destination bool allOK(true) ; - for (unsigned int j=0; j < sourceArgSet->size(); ++j) { + for (unsigned int j=0; j < sourceArgSet.size(); ++j) { auto destArg = _varsww[j]; - const auto sourceArg = (*sourceArgSet)[j]; + const auto sourceArg = sourceArgSet[j]; destArg->copyCache(sourceArg) ; sourceArg->copyCache(destArg) ; @@ -556,7 +557,7 @@ const RooArgSet* RooTreeDataStore::get(Int_t index) const Int_t ret = ((RooTreeDataStore*)this)->GetEntry(index, 1) ; - if(!ret) return 0; + if(!ret) return nullptr; if (_doDirtyProp) { // Raise all dirty flags @@ -784,12 +785,12 @@ RooAbsArg* RooTreeDataStore::addColumn(RooAbsArg& newVar, bool adjustRange) checkInit() ; // Create a fundamental object of the right type to hold newVar values - RooAbsArg* valHolder= newVar.createFundamental(); + auto valHolder = std::unique_ptr{newVar.createFundamental()}.release(); // Sanity check that the holder really is fundamental if(!valHolder->isFundamental()) { coutE(InputArguments) << GetName() << "::addColumn: holder argument is not fundamental: \"" << valHolder->GetName() << "\"" << endl; - return 0; + return nullptr; } // WVE need to reset TTRee buffers to original datamembers here @@ -805,7 +806,7 @@ RooAbsArg* RooTreeDataStore::addColumn(RooAbsArg& newVar, bool adjustRange) _varsww.add(*valHolder) ; - // Fill values of of placeholder + // Fill values of placeholder for (int i=0 ; i RooTreeDataStore::getWeightBatch(std::size_t first, std::size_t len) const { +std::span RooTreeDataStore::getWeightBatch(std::size_t first, std::size_t len) const { if (_extWgtArray) { return {_extWgtArray + first, len}; } if (!_weightBuffer) { - _weightBuffer.reset(new std::vector()); + _weightBuffer = std::make_unique>(); _weightBuffer->reserve(len); for (std::size_t i = 0; i < GetEntries(); ++i) { diff --git a/roofit/roofitcore/src/RooTruthModel.cxx b/roofit/roofitcore/src/RooTruthModel.cxx index e3f8e1fce2afc..17bab9d7c307b 100644 --- a/roofit/roofitcore/src/RooTruthModel.cxx +++ b/roofit/roofitcore/src/RooTruthModel.cxx @@ -27,6 +27,7 @@ functions used in D mixing have been hand coded for increased execution speed. **/ #include "Riostream.h" +#include "RooBatchCompute.h" #include "RooTruthModel.h" #include "RooGenContext.h" #include "RooAbsAnaConvPdf.h" @@ -78,60 +79,79 @@ RooTruthModel::~RooTruthModel() Int_t RooTruthModel::basisCode(const char* name) const { - // Check for optimized basis functions - if (!TString("exp(-@0/@1)").CompareTo(name)) return expBasisPlus ; - if (!TString("exp(@0/@1)").CompareTo(name)) return expBasisMinus ; - if (!TString("exp(-abs(@0)/@1)").CompareTo(name)) return expBasisSum ; - if (!TString("exp(-@0/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisPlus ; - if (!TString("exp(@0/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisMinus ; - if (!TString("exp(-abs(@0)/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisSum ; - if (!TString("exp(-@0/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisPlus ; - if (!TString("exp(@0/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisMinus ; - if (!TString("exp(-abs(@0)/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisSum ; - if (!TString("(@0/@1)*exp(-@0/@1)").CompareTo(name)) return linBasisPlus ; - if (!TString("(@0/@1)*(@0/@1)*exp(-@0/@1)").CompareTo(name)) return quadBasisPlus ; - if (!TString("exp(-@0/@1)*cosh(@0*@2/2)").CompareTo(name)) return coshBasisPlus; - if (!TString("exp(@0/@1)*cosh(@0*@2/2)").CompareTo(name)) return coshBasisMinus; - if (!TString("exp(-abs(@0)/@1)*cosh(@0*@2/2)").CompareTo(name)) return coshBasisSum; - if (!TString("exp(-@0/@1)*sinh(@0*@2/2)").CompareTo(name)) return sinhBasisPlus; - if (!TString("exp(@0/@1)*sinh(@0*@2/2)").CompareTo(name)) return sinhBasisMinus; - if (!TString("exp(-abs(@0)/@1)*sinh(@0*@2/2)").CompareTo(name)) return sinhBasisSum; - - // Truth model is delta function, i.e. convolution integral - // is basis function, therefore we can handle any basis function - return genericBasis ; + std::string str = name; + + // Remove whitespaces from the input string + str.erase(remove(str.begin(),str.end(),' '),str.end()); + + // Check for optimized basis functions + if (str == "exp(-@0/@1)") return expBasisPlus ; + if (str == "exp(@0/@1)") return expBasisMinus ; + if (str == "exp(-abs(@0)/@1)") return expBasisSum ; + if (str == "exp(-@0/@1)*sin(@0*@2)") return sinBasisPlus ; + if (str == "exp(@0/@1)*sin(@0*@2)") return sinBasisMinus ; + if (str == "exp(-abs(@0)/@1)*sin(@0*@2)") return sinBasisSum ; + if (str == "exp(-@0/@1)*cos(@0*@2)") return cosBasisPlus ; + if (str == "exp(@0/@1)*cos(@0*@2)") return cosBasisMinus ; + if (str == "exp(-abs(@0)/@1)*cos(@0*@2)") return cosBasisSum ; + if (str == "(@0/@1)*exp(-@0/@1)") return linBasisPlus ; + if (str == "(@0/@1)*(@0/@1)*exp(-@0/@1)") return quadBasisPlus ; + if (str == "exp(-@0/@1)*cosh(@0*@2/2)") return coshBasisPlus; + if (str == "exp(@0/@1)*cosh(@0*@2/2)") return coshBasisMinus; + if (str == "exp(-abs(@0)/@1)*cosh(@0*@2/2)") return coshBasisSum; + if (str == "exp(-@0/@1)*sinh(@0*@2/2)") return sinhBasisPlus; + if (str == "exp(@0/@1)*sinh(@0*@2/2)") return sinhBasisMinus; + if (str == "exp(-abs(@0)/@1)*sinh(@0*@2/2)") return sinhBasisSum; + + // Truth model is delta function, i.e. convolution integral is basis + // function, therefore we can handle any basis function + return genericBasis ; } - //////////////////////////////////////////////////////////////////////////////// /// Changes associated bases function to 'inBasis' void RooTruthModel::changeBasis(RooFormulaVar* inBasis) { - // Process change basis function. Since we actually - // evaluate the basis function object, we need to - // adjust our client-server links to the basis function here - - // Remove client-server link to old basis - if (_basis) { - removeServer(*_basis) ; - } - - // Change basis pointer and update client-server link - _basis = inBasis ; - if (_basis) { - addServer(*_basis,true,false) ; - } + // Remove client-server link to old basis + if (_basis) { + if (_basisCode == genericBasis) { + // In the case of a generic basis, we evaluate it directly, so the + // basis was a direct server. + removeServer(*_basis); + } else { + for (RooAbsArg *basisServer : _basis->servers()) { + removeServer(*basisServer); + } + } - _basisCode = inBasis?basisCode(inBasis->GetTitle()):0 ; + if (_ownBasis) { + delete _basis; + } + } + _ownBasis = false; + + _basisCode = inBasis ? basisCode(inBasis->GetTitle()) : 0; + + // Change basis pointer and update client-server link + _basis = inBasis; + if (_basis) { + if (_basisCode == genericBasis) { + // Since we actually evaluate the basis function object, we need to + // adjust our client-server links to the basis function here + addServer(*_basis, true, false); + } else { + for (RooAbsArg *basisServer : _basis->servers()) { + addServer(*basisServer, true, false); + } + } + } } - - //////////////////////////////////////////////////////////////////////////////// /// Evaluate the truth model: a delta function when used as PDF, /// the basis function itself, when convoluted with a basis function. @@ -162,32 +182,32 @@ double RooTruthModel::evaluate() const // Return desired basis function switch(basisType) { case expBasis: { - //cout << " RooTruthModel::eval(" << GetName() << ") expBasis mode ret = " << exp(-fabs((double)x)/tau) << " tau = " << tau << endl ; - return exp(-fabs((double)x)/tau) ; + //cout << " RooTruthModel::eval(" << GetName() << ") expBasis mode ret = " << exp(-std::abs((double)x)/tau) << " tau = " << tau << endl ; + return exp(-std::abs((double)x)/tau) ; } case sinBasis: { double dm = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - return exp(-fabs((double)x)/tau)*sin(x*dm) ; + return exp(-std::abs((double)x)/tau)*sin(x*dm) ; } case cosBasis: { double dm = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - return exp(-fabs((double)x)/tau)*cos(x*dm) ; + return exp(-std::abs((double)x)/tau)*cos(x*dm) ; } case linBasis: { - double tscaled = fabs((double)x)/tau; + double tscaled = std::abs((double)x)/tau; return exp(-tscaled)*tscaled ; } case quadBasis: { - double tscaled = fabs((double)x)/tau; + double tscaled = std::abs((double)x)/tau; return exp(-tscaled)*tscaled*tscaled; } case sinhBasis: { double dg = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - return exp(-fabs((double)x)/tau)*sinh(x*dg/2) ; + return exp(-std::abs((double)x)/tau)*sinh(x*dg/2) ; } case coshBasis: { double dg = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - return exp(-fabs((double)x)/tau)*cosh(x*dg/2) ; + return exp(-std::abs((double)x)/tau)*cosh(x*dg/2) ; } default: R__ASSERT(0) ; @@ -197,6 +217,77 @@ double RooTruthModel::evaluate() const } +void RooTruthModel::computeBatch(double *output, size_t nEvents, RooFit::Detail::DataMap const &dataMap) const +{ + auto config = dataMap.config(this); + auto xVals = dataMap.at(x); + + // No basis: delta function + if (_basisCode == noBasis) { + RooBatchCompute::compute(config, RooBatchCompute::DeltaFunction, output, nEvents, {xVals}); + return; + } + + // Generic basis: evaluate basis function object + if (_basisCode == genericBasis) { + RooBatchCompute::compute(config, RooBatchCompute::Identity, output, nEvents, {dataMap.at(&basis())}); + return; + } + + // Precompiled basis functions + const BasisType basisType = static_cast((_basisCode == 0) ? 0 : (_basisCode / 10) + 1); + + // Cast the int from the enum to double because we can only pass doubles to + // RooBatchCompute at this point. + const double basisSign = static_cast((BasisSign)(_basisCode - 10 * (basisType - 1) - 2)); + + auto param1 = static_cast(basis().getParameter(1)); + auto param2 = static_cast(basis().getParameter(2)); + auto param1Vals = param1 ? dataMap.at(param1) : std::span{}; + auto param2Vals = param2 ? dataMap.at(param2) : std::span{}; + + // Return desired basis function + RooBatchCompute::ArgVector extraArgs{basisSign}; + switch (basisType) { + case expBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelExpBasis, output, nEvents, {xVals, param1Vals}, + extraArgs); + break; + } + case sinBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelSinBasis, output, nEvents, + {xVals, param1Vals, param2Vals}, extraArgs); + break; + } + case cosBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelCosBasis, output, nEvents, + {xVals, param1Vals, param2Vals}, extraArgs); + break; + } + case linBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelLinBasis, output, nEvents, {xVals, param1Vals}, + extraArgs); + break; + } + case quadBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelQuadBasis, output, nEvents, {xVals, param1Vals}, + extraArgs); + break; + } + case sinhBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelSinhBasis, output, nEvents, + {xVals, param1Vals, param2Vals}, extraArgs); + break; + } + case coshBasis: { + RooBatchCompute::compute(config, RooBatchCompute::TruthModelCoshBasis, output, nEvents, + {xVals, param1Vals, param2Vals}, extraArgs); + break; + } + default: R__ASSERT(0); + } +} + //////////////////////////////////////////////////////////////////////////////// /// Advertise analytical integrals for compiled basis functions and when used @@ -257,17 +348,21 @@ double RooTruthModel::analyticalIntegral(Int_t code, const char* rangeName) cons //cout << " calling RooTruthModel::analyticalIntegral with basisType " << basisType << endl; double tau = ((RooAbsReal*)basis().getParameter(1))->getVal() ; + + const double xmin = x.min(rangeName); + const double xmax = x.max(rangeName); + switch (basisType) { case expBasis: { // WVE fixed for ranges double result(0) ; if (tau==0) return 1 ; - if ((basisSign != Minus) && (x.max(rangeName)>0)) { - result += tau*(-exp(-x.max(rangeName)/tau) - -exp(-max(0.,x.min(rangeName))/tau) ) ; // plus and both + if ((basisSign != Minus) && (xmax>0)) { + result += tau*(-exp(-xmax/tau) - -exp(-max(0.,xmin)/tau) ) ; // plus and both } - if ((basisSign != Plus) && (x.min(rangeName)<0)) { - result -= tau*(-exp(-max(0.,x.min(rangeName))/tau)) - -tau*exp(-x.max(rangeName)/tau) ; // minus and both + if ((basisSign != Plus) && (xmin<0)) { + result -= tau*(-exp(-max(0.,xmin)/tau)) - -tau*exp(-xmax/tau) ; // minus and both } return result ; @@ -277,8 +372,22 @@ double RooTruthModel::analyticalIntegral(Int_t code, const char* rangeName) cons double result(0) ; if (tau==0) return 0 ; double dm = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - if (basisSign != Minus) result += exp(-x.max(rangeName)/tau)*(-1/tau*sin(dm*x.max(rangeName)) - dm*cos(dm*x.max(rangeName))) + dm; // fixed FMV 08/29/03 - if (basisSign != Plus) result -= exp( x.min(rangeName)/tau)*(-1/tau*sin(dm*(-x.min(rangeName))) - dm*cos(dm*(-x.min(rangeName)))) + dm ; // fixed FMV 08/29/03 + if (basisSign != Minus) { + double term = exp(-xmax/tau); + // We only multiply with the sine term if the coefficient is non zero, + // i.e. if xmax was not infinity. Otherwise, we are evaluating the + // sine of infinity, which is NAN! Same applies to the other terms + // below. + if(term > 0.0) term *= -1/tau*sin(dm*xmax) - dm*cos(dm*xmax); + term += dm; + result += term; + } + if (basisSign != Plus) { + double term = exp(xmin/tau); + if (term > 0.0) term *= -1/tau*sin(dm*(-xmin)) - dm*cos(dm*(-xmin)); + term += dm; + result -= term; + } return result / (1/(tau*tau) + dm*dm) ; } case cosBasis: @@ -286,20 +395,30 @@ double RooTruthModel::analyticalIntegral(Int_t code, const char* rangeName) cons double result(0) ; if (tau==0) return 1 ; double dm = ((RooAbsReal*)basis().getParameter(2))->getVal() ; - if (basisSign != Minus) result += exp(-x.max(rangeName)/tau)*(-1/tau*cos(dm*x.max(rangeName)) + dm*sin(dm*x.max(rangeName))) + 1/tau ; - if (basisSign != Plus) result += exp( x.min(rangeName)/tau)*(-1/tau*cos(dm*(-x.min(rangeName))) + dm*sin(dm*(-x.min(rangeName)))) + 1/tau ; // fixed FMV 08/29/03 + if (basisSign != Minus) { + double term = exp(-xmax/tau); + if(term > 0.0) term *= -1/tau*cos(dm*xmax) + dm*sin(dm*xmax); + term += 1/tau; + result += term; + } + if (basisSign != Plus) { + double term = exp( xmin/tau); + if(term > 0.0) term *= -1/tau*cos(dm*(-xmin)) + dm*sin(dm*(-xmin)); + term += 1/tau; + result += term; + } return result / (1/(tau*tau) + dm*dm) ; } case linBasis: { if (tau==0) return 0 ; - double t_max = x.max(rangeName)/tau ; + double t_max = xmax/tau ; return tau*( 1 - (1 + t_max)*exp(-t_max) ) ; } case quadBasis: { if (tau==0) return 0 ; - double t_max = x.max(rangeName)/tau ; + double t_max = xmax/tau ; return tau*( 2 - (2 + (2 + t_max)*t_max)*exp(-t_max) ) ; } case sinhBasis: @@ -309,8 +428,8 @@ double RooTruthModel::analyticalIntegral(Int_t code, const char* rangeName) cons double dg = ((RooAbsReal*)basis().getParameter(2))->getVal() ; double taup = 2*tau/(2-tau*dg); double taum = 2*tau/(2+tau*dg); - if (basisSign != Minus) result += 0.5*( taup*(1-exp(-x.max(rangeName)/taup)) - taum*(1-exp(-x.max(rangeName)/taum)) ) ; - if (basisSign != Plus) result -= 0.5*( taup*(1-exp( x.min(rangeName)/taup)) - taum*(1-exp( x.min(rangeName)/taum)) ) ; + if (basisSign != Minus) result += 0.5*( taup*(1-exp(-xmax/taup)) - taum*(1-exp(-xmax/taum)) ) ; + if (basisSign != Plus) result -= 0.5*( taup*(1-exp( xmin/taup)) - taum*(1-exp( xmin/taum)) ) ; return result ; } case coshBasis: @@ -320,8 +439,8 @@ double RooTruthModel::analyticalIntegral(Int_t code, const char* rangeName) cons double dg = ((RooAbsReal*)basis().getParameter(2))->getVal() ; double taup = 2*tau/(2-tau*dg); double taum = 2*tau/(2+tau*dg); - if (basisSign != Minus) result += 0.5*( taup*(1-exp(-x.max(rangeName)/taup)) + taum*(1-exp(-x.max(rangeName)/taum)) ) ; - if (basisSign != Plus) result += 0.5*( taup*(1-exp( x.min(rangeName)/taup)) + taum*(1-exp( x.min(rangeName)/taum)) ) ; + if (basisSign != Minus) result += 0.5*( taup*(1-exp(-xmax/taup)) + taum*(1-exp(-xmax/taum)) ) ; + if (basisSign != Plus) result += 0.5*( taup*(1-exp( xmin/taup)) + taum*(1-exp( xmin/taum)) ) ; return result ; } default: @@ -339,9 +458,8 @@ RooAbsGenContext* RooTruthModel::modelGenContext (const RooAbsAnaConvPdf& convPdf, const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, bool verbose) const { - RooArgSet forceDirect(convVar()) ; - return new RooGenContext(dynamic_cast(convPdf), vars, prototype, - auxProto, verbose, &forceDirect) ; + RooArgSet forceDirect(convVar()) ; + return new RooGenContext(convPdf, vars, prototype, auxProto, verbose, &forceDirect); } diff --git a/roofit/roofitcore/src/RooUniformBinning.cxx b/roofit/roofitcore/src/RooUniformBinning.cxx index a6b1390b5c77c..282a46cbd924c 100644 --- a/roofit/roofitcore/src/RooUniformBinning.cxx +++ b/roofit/roofitcore/src/RooUniformBinning.cxx @@ -45,7 +45,7 @@ ClassImp(RooUniformBinning); RooUniformBinning::RooUniformBinning(const char* name) : RooAbsBinning(name) { - _array = 0 ; + _array = nullptr ; } @@ -54,7 +54,7 @@ RooUniformBinning::RooUniformBinning(const char* name) : RooUniformBinning::RooUniformBinning(double xlo, double xhi, Int_t nBins, const char* name) : RooAbsBinning(name), - _array(0), + _array(nullptr), _nbins(nBins) { setRange(xlo,xhi) ; @@ -78,7 +78,7 @@ RooUniformBinning::~RooUniformBinning() RooUniformBinning::RooUniformBinning(const RooUniformBinning& other, const char* name) : RooAbsBinning(name) { - _array = 0 ; + _array = nullptr ; _xlo = other._xlo ; _xhi = other._xhi ; _nbins = other._nbins ; @@ -105,7 +105,7 @@ void RooUniformBinning::setRange(double xlo, double xhi) // Delete any out-of-date boundary arrays at this point if (_array) { delete[] _array ; - _array = 0 ; + _array = nullptr ; } } diff --git a/roofit/roofitcore/src/RooUnitTest.cxx b/roofit/roofitcore/src/RooUnitTest.cxx index 665465378d7d4..e2475eab9ed69 100644 --- a/roofit/roofitcore/src/RooUnitTest.cxx +++ b/roofit/roofitcore/src/RooUnitTest.cxx @@ -28,7 +28,7 @@ Object | function ----------------|------------ RooPlot | regPlot() RooFitResult | regResult() - double | regValue() + double | regValue() RooTable | regTable() TH1/2/3 | regTH() RooWorkspace | regWS() @@ -58,8 +58,8 @@ TDirectory* RooUnitTest::gMemDir = nullptr; //////////////////////////////////////////////////////////////////////////////// -RooUnitTest::RooUnitTest(const char* name, TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : TNamed(name,name), - _refFile(refFile), _debug(false), _write(writeRef), _verb(verbose), _batchMode(batchMode) +RooUnitTest::RooUnitTest(const char* name, TFile* refFile, bool writeRef, Int_t verbose) : TNamed(name,name), + _refFile(refFile), _debug(false), _write(writeRef), _verb(verbose) { } @@ -79,7 +79,13 @@ void RooUnitTest::regPlot(RooPlot* frame, const char* refName) if (_refFile) { string refNameStr(refName) ; frame->SetName(refName) ; - _regPlots.push_back(make_pair(frame,refNameStr)) ; + // Since ROOT 6.28, the RooPlot doesn't clone the plot variable by default + // anymore. This is a problem for registering the RooPlots, because they + // need to survive without dangling pointers even after the RooUnitTest is + // done. For that reason, we ask the RooPlot to create an internal plot + // variable clone for itself. + frame->createInternalPlotVarClone(); + _regPlots.emplace_back(frame,refNameStr); } else { delete frame ; } @@ -88,13 +94,11 @@ void RooUnitTest::regPlot(RooPlot* frame, const char* refName) //////////////////////////////////////////////////////////////////////////////// -void RooUnitTest::regResult(RooFitResult* r, const char* refName) +void RooUnitTest::regResult(std::unique_ptr r, const char* refName) { if (_refFile) { string refNameStr(refName) ; - _regResults.push_back(make_pair(r,refNameStr)) ; - } else { - delete r ; + _regResults.push_back(make_pair(r.release(),refNameStr)) ; } } @@ -157,7 +161,7 @@ RooWorkspace* RooUnitTest::getWS(const char* refName) if (!ws) { if(_verb >= 0) std::cout << "RooUnitTest ERROR: cannot retrieve RooWorkspace " << refName << " from reference file, skipping " << endl ; - return 0 ; + return nullptr ; } return ws ; @@ -197,7 +201,7 @@ bool RooUnitTest::areTHidentical(TH1* htest, TH1* href) } for (Int_t i=0 ; iGetBinContent(i)-href->GetBinContent(i))>htol()) { + if (std::abs(htest->GetBinContent(i)-href->GetBinContent(i))>htol()) { if(_verb >= 0) std::cout << "htest[" << i << "] = " << htest->GetBinContent(i) << " href[" << i << "] = " << href->GetBinContent(i) << endl; } } @@ -239,7 +243,7 @@ bool RooUnitTest::runCompTests() cout << "benchmark: " ; bmark->Print() ; } - RooPlot* compPlot = _debug ? iter->first->emptyClone(Form("%s_comparison",iter->first->GetName())) : 0 ; + RooPlot* compPlot = _debug ? iter->first->emptyClone(Form("%s_comparison",iter->first->GetName())) : nullptr ; bool anyFail=false ; Stat_t nItems = iter->first->numItems() ; @@ -398,7 +402,7 @@ bool RooUnitTest::runCompTests() cout << "comparing value " << iter3->first << " to benchmark " << iter3->second << " = " << (double)(*ref) << endl ; } - if (fabs(iter3->first - (double)(*ref))>vtol() ) { + if (std::abs(iter3->first - (double)(*ref))>vtol() ) { if(_verb >= 0) cout << "RooUnitTest ERROR: comparison of value " << iter3->first << " fails comparison with reference " << ref->GetName() << endl ; ret = false ; } diff --git a/roofit/roofitcore/src/RooVectorDataStore.cxx b/roofit/roofitcore/src/RooVectorDataStore.cxx index 7c12f72b9f118..615594aa422cc 100644 --- a/roofit/roofitcore/src/RooVectorDataStore.cxx +++ b/roofit/roofitcore/src/RooVectorDataStore.cxx @@ -51,6 +51,7 @@ using namespace std; ClassImp(RooVectorDataStore); ClassImp(RooVectorDataStore::RealVector); +ClassImp(RooVectorDataStore::RealFullVector); //////////////////////////////////////////////////////////////////////////////// @@ -127,7 +128,7 @@ RooRealVar* RooVectorDataStore::weightVar(const RooArgSet& allVars, const char* RooRealVar* wgt = dynamic_cast(allVars.find(wgtName)) ; return wgt ; } - return 0 ; + return nullptr ; } @@ -169,9 +170,9 @@ RooVectorDataStore::RooVectorDataStore(const RooVectorDataStore& other, const ch //////////////////////////////////////////////////////////////////////////////// RooVectorDataStore::RooVectorDataStore(const RooTreeDataStore& other, const RooArgSet& vars, const char* newname) : - RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():0),newname), + RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():nullptr),newname), _varsww(vars), - _wgtVar(weightVar(vars,other._wgtVar?other._wgtVar->GetName():0)) + _wgtVar(weightVar(vars,other._wgtVar?other._wgtVar->GetName():nullptr)) { for (const auto arg : _varsww) { arg->attachToVStore(*this) ; @@ -195,9 +196,9 @@ RooVectorDataStore::RooVectorDataStore(const RooTreeDataStore& other, const RooA /// Clone ctor, must connect internal storage to given new external set of vars RooVectorDataStore::RooVectorDataStore(const RooVectorDataStore& other, const RooArgSet& vars, const char* newname) : - RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():0),newname), + RooAbsDataStore(other,varsNoWeight(vars,other._wgtVar?other._wgtVar->GetName():nullptr),newname), _varsww(vars), - _wgtVar(other._wgtVar?weightVar(vars,other._wgtVar->GetName()):0), + _wgtVar(other._wgtVar?weightVar(vars,other._wgtVar->GetName()):nullptr), _sumWeight(other._sumWeight), _sumWeightCarry(other._sumWeightCarry), _extWgtArray(other._extWgtArray), @@ -216,12 +217,12 @@ RooVectorDataStore::RooVectorDataStore(const RooVectorDataStore& other, const Ro } } - vector::const_iterator fiter = other._realfStoreList.begin() ; - for (; fiter!=other._realfStoreList.end() ; ++fiter) { - RooAbsReal* real = (RooAbsReal*) vars.find((*fiter)->bufArg()->GetName()) ; + auto forwardIter = other._realfStoreList.begin() ; + for (; forwardIter!=other._realfStoreList.end() ; ++forwardIter) { + RooAbsReal* real = (RooAbsReal*) vars.find((*forwardIter)->bufArg()->GetName()) ; if (real) { // Clone vector - _realfStoreList.push_back(new RealFullVector(**fiter,real)) ; + _realfStoreList.push_back(new RealFullVector(**forwardIter,real)) ; // Adjust buffer pointer real->attachToVStore(*this) ; } @@ -350,7 +351,7 @@ Int_t RooVectorDataStore::fill() /// and return a pointer to the RooArgSet that holds them. const RooArgSet* RooVectorDataStore::get(Int_t index) const { - if (index < 0 || static_cast(index) >= size()) return 0; + if (index < 0 || static_cast(index) >= size()) return nullptr; for (const auto realV : _realStoreList) { realV->load(index); @@ -575,7 +576,7 @@ void RooVectorDataStore::loadValues(const RooAbsDataStore *ads, const RooFormula continue ; } - _varsww.assignValueOnly(*otherVarsww) ; + _varsww.assign(*otherVarsww) ; fill() ; } @@ -620,19 +621,19 @@ bool RooVectorDataStore::changeObservableName(const char* /*from*/, const char* RooAbsArg* RooVectorDataStore::addColumn(RooAbsArg& newVar, bool /*adjustRange*/) { // Create a fundamental object of the right type to hold newVar values - RooAbsArg* valHolder= newVar.createFundamental(); + auto valHolder = std::unique_ptr{newVar.createFundamental()}.release(); // Sanity check that the holder really is fundamental if(!valHolder->isFundamental()) { coutE(InputArguments) << GetName() << "::addColumn: holder argument is not fundamental: \"" << valHolder->GetName() << "\"" << endl; - return 0; + return nullptr; } // Attention: need to do this now, as adding an empty column might give 0 as size const std::size_t numEvt = size(); // Clone variable and attach to cloned tree - RooAbsArg* newVarClone = newVar.cloneTree() ; + std::unique_ptr newVarClone{newVar.cloneTree()}; newVarClone->recursiveRedirectServers(_vars,false) ; // Attach value place holder to this tree @@ -641,8 +642,8 @@ RooAbsArg* RooVectorDataStore::addColumn(RooAbsArg& newVar, bool /*adjustRange*/ _varsww.add(*valHolder) ; // Fill values of placeholder - RealVector* rv(0) ; - CatVector* cv(0) ; + RealVector* rv(nullptr) ; + CatVector* cv(nullptr) ; assert(numEvt != 0); if (dynamic_cast(valHolder)) { rv = addReal((RooAbsReal*)valHolder); @@ -656,15 +657,13 @@ RooAbsArg* RooVectorDataStore::addColumn(RooAbsArg& newVar, bool /*adjustRange*/ get(i) ; newVarClone->syncCache(&_vars) ; - valHolder->copyCache(newVarClone) ; + valHolder->copyCache(newVarClone.get()) ; if (rv) rv->write(i) ; if (cv) cv->write(i) ; } - delete newVarClone ; return valHolder ; - } @@ -764,7 +763,7 @@ void RooVectorDataStore::cacheArgs(const RooAbsArg* owner, RooArgSet& newVarSet, { // Delete previous cache, if any delete _cache ; - _cache = 0 ; + _cache = nullptr ; // Reorder cached elements. First constant nodes, then tracked nodes in order of dependence @@ -808,17 +807,18 @@ void RooVectorDataStore::cacheArgs(const RooAbsArg* owner, RooArgSet& newVarSet, checkInit() ; - std::vector vlist; + std::vector> vlist; RooArgList cloneSet; for (const auto var : orderedArgs) { // Clone variable and attach to cloned tree - RooArgSet* newVarCloneList = (RooArgSet*) RooArgSet(*var).snapshot() ; + auto newVarCloneList = std::make_unique(); + RooArgSet(*var).snapshot(*newVarCloneList); RooAbsArg* newVarClone = newVarCloneList->find(var->GetName()) ; newVarClone->recursiveRedirectServers(_vars,false) ; - vlist.push_back(newVarCloneList) ; + vlist.emplace_back(std::move(newVarCloneList)); cloneSet.add(*newVarClone) ; } @@ -829,16 +829,17 @@ void RooVectorDataStore::cacheArgs(const RooAbsArg* owner, RooArgSet& newVarSet, RooAbsArg::setDirtyInhibit(true) ; std::vector nsetList ; - std::vector argObsList ; + std::vector> argObsList ; // Now need to attach branch buffers of clones for (const auto arg : cloneSet) { arg->attachToVStore(*newCache) ; - RooArgSet* argObs = nset ? arg->getObservables(*nset) : arg->getVariables() ; - argObsList.push_back(argObs) ; + if(nset) argObsList.emplace_back(arg->getObservables(*nset)); + else argObsList.emplace_back(arg->getVariables()); + RooArgSet* argObs = argObsList.back().get(); - RooArgSet* normSet(0) ; + RooArgSet* normSet(nullptr) ; const char* catNset = arg->getStringAttribute("CATNormSet") ; if (catNset) { // cout << "RooVectorDataStore::cacheArgs() cached node " << arg->GetName() << " has a normalization set specification CATNormSet = " << catNset << endl ; @@ -864,7 +865,7 @@ void RooVectorDataStore::cacheArgs(const RooAbsArg* owner, RooArgSet& newVarSet, } - // Fill values of of placeholder + // Fill values of placeholder const std::size_t numEvt = size(); newCache->reserve(numEvt); for (std::size_t i=0; i < numEvt; i++) { @@ -890,28 +891,20 @@ void RooVectorDataStore::cacheArgs(const RooAbsArg* owner, RooArgSet& newVarSet, // Activate change tracking mode, if requested if (!arg->getAttribute("ConstantExpression") && dynamic_cast(arg)) { RealVector* rv = newCache->addReal((RooAbsReal*)arg) ; - RooArgSet* deps = arg->getParameters(_vars) ; - rv->setDependents(*deps) ; + RooArgSet deps; + arg->getParameters(&_vars, deps); + rv->setDependents(deps) ; // WV lookup normalization set and associate with RealVector // find ordinal number of arg in original list Int_t idx = cloneSet.index(arg->GetName()) ; - coutI(Optimization) << "RooVectorDataStore::cacheArg() element " << arg->GetName() << " has change tracking enabled on parameters " << *deps << endl ; + coutI(Optimization) << "RooVectorDataStore::cacheArg() element " << arg->GetName() << " has change tracking enabled on parameters " << deps << endl ; rv->setNset(nsetList[idx]) ; - delete deps ; } } - - for (auto set : vlist) { - delete set; - } - for (auto set : argObsList) { - delete set; - } - _cache = newCache ; _cache->setDirtyProp(_doDirtyProp) ; } @@ -950,12 +943,13 @@ void RooVectorDataStore::recalculateCache( const RooArgSet *projectedArgs, Int_t // Refill caches of elements that require recalculation - RooArgSet* ownedNset = 0 ; - RooArgSet* usedNset = 0 ; - if (projectedArgs && projectedArgs->getSize()>0) { - ownedNset = (RooArgSet*) _vars.snapshot(false) ; + std::unique_ptr ownedNset; + RooArgSet* usedNset = nullptr; + if (projectedArgs && !projectedArgs->empty()) { + ownedNset = std::make_unique(); + _vars.snapshot(*ownedNset, false) ; ownedNset->remove(*projectedArgs,false,true); - usedNset = ownedNset ; + usedNset = ownedNset.get(); } else { usedNset = &_vars ; } @@ -976,9 +970,6 @@ void RooVectorDataStore::recalculateCache( const RooArgSet *projectedArgs, Int_t for (auto realVector : tv) { realVector->_nativeReal->setOperMode(RooAbsArg::AClean); } - - delete ownedNset ; - } @@ -1089,7 +1080,7 @@ void RooVectorDataStore::dump() for (const auto elm : _realfStoreList) { cout << "RealFullVector " << elm << " _nativeReal = " << elm->_nativeReal << " = " << elm->_nativeReal->GetName() - << " bufptr = " << elm->_buf << " errbufptr = " << elm->_bufE << endl ; + << " bufptr = " << elm->_buf << " errbufptr = " << elm->bufE() << endl ; cout << " values : " ; Int_t imax = elm->_vec.size()>10 ? 10 : elm->_vec.size() ; @@ -1097,10 +1088,10 @@ void RooVectorDataStore::dump() cout << elm->_vec[i] << " " ; } cout << endl ; - if (elm->_vecE) { + if (elm->bufE()) { cout << " errors : " ; for (Int_t i=0 ; i_vecE)[i] << " " ; + cout << elm->dataE()[i] << " " ; } cout << endl ; @@ -1136,26 +1127,6 @@ void RooVectorDataStore::Streamer(TBuffer &R__b) } -//////////////////////////////////////////////////////////////////////////////// -/// Stream an object of class RooVectorDataStore::RealFullVector. - -void RooVectorDataStore::RealFullVector::Streamer(TBuffer &R__b) -{ - if (R__b.IsReading()) { - R__b.ReadClassBuffer(RooVectorDataStore::RealFullVector::Class(),this); - - // WVE - It seems that ROOT persistence turns null pointers to vectors into pointers to null-sized vectors - // Intervene here to remove those null-sized vectors and replace with null pointers to not break - // assumptions made elsewhere in this class - if (_vecE && _vecE->empty()) { delete _vecE ; _vecE = 0 ; } - if (_vecEL && _vecEL->empty()) { delete _vecEL ; _vecEL = 0 ; } - if (_vecEH && _vecEH->empty()) { delete _vecEH ; _vecEH = 0 ; } - } else { - R__b.WriteClassBuffer(RooVectorDataStore::RealFullVector::Class(),this); - } -} - - //////////////////////////////////////////////////////////////////////////////// /// Return batches of the data columns for the requested events. /// \param[in] first First event in the batches. @@ -1227,10 +1198,10 @@ RooAbsData::CategorySpans RooVectorDataStore::getCategoryBatches(std::size_t fir /// If an array with weights is stored, a batch with these weights will be returned. If /// no weights are stored, an empty batch is returned. Use weight() to check if there's /// a constant weight. -RooSpan RooVectorDataStore::getWeightBatch(std::size_t first, std::size_t len) const +std::span RooVectorDataStore::getWeightBatch(std::size_t first, std::size_t len) const { if (_extWgtArray) { - return RooSpan(_extWgtArray + first, _extWgtArray + first + len); + return std::span(_extWgtArray + first, _extWgtArray + first + len); } if (_wgtVar) { @@ -1309,7 +1280,7 @@ bool RooVectorDataStore::hasError(RooAbsReal* real) { // First try a match by name for (auto fullVec : _realfStoreList) { if (std::string(fullVec->bufArg()->GetName())==real->GetName()) { - return fullVec->_vecE ? true : false ; + return fullVec->bufE(); } } return false ; @@ -1321,7 +1292,7 @@ bool RooVectorDataStore::hasAsymError(RooAbsReal* real) { // First try a match by name for (auto fullVec : _realfStoreList) { if (std::string(fullVec->bufArg()->GetName())==real->GetName()) { - return fullVec->_vecEL ? true : false ; + return fullVec->bufEL(); } } return false ; @@ -1400,9 +1371,9 @@ RooVectorDataStore::ArraysStruct RooVectorDataStore::getArrays() const { for(auto const* realf : _realfStoreList) { std::string name = realf->_nativeReal->GetName(); out.reals.emplace_back(name, realf->_vec.data()); - if(realf->_vecE) out.reals.emplace_back(name + "Err", realf->_vecE->data()); - if(realf->_vecEL) out.reals.emplace_back(name + "ErrLo", realf->_vecEL->data()); - if(realf->_vecEH) out.reals.emplace_back(name + "ErrHi", realf->_vecEH->data()); + if(realf->bufE()) out.reals.emplace_back(name + "Err", realf->dataE().data()); + if(realf->bufEL()) out.reals.emplace_back(name + "ErrLo", realf->dataEL().data()); + if(realf->bufEH()) out.reals.emplace_back(name + "ErrHi", realf->dataEH().data()); } for(auto const* cat : _catStoreList) { out.cats.emplace_back(cat->_cat->GetName(), cat->_vec.data()); diff --git a/roofit/roofitcore/src/RooWorkspace.cxx b/roofit/roofitcore/src/RooWorkspace.cxx index 6b79fdfa73ec6..6906c079f937a 100644 --- a/roofit/roofitcore/src/RooWorkspace.cxx +++ b/roofit/roofitcore/src/RooWorkspace.cxx @@ -197,7 +197,8 @@ RooWorkspace::RooWorkspace(const RooWorkspace& other) : // Copy snapshots for(auto * snap : static_range_cast(other._snapshots)) { - auto snapClone = static_cast(snap->snapshot()); + auto snapClone = new RooArgSet; + snap->snapshot(*snapClone); snapClone->setName(snap->GetName()) ; _snapshots.Add(snapClone) ; } @@ -223,6 +224,16 @@ RooWorkspace::RooWorkspace(const RooWorkspace& other) : } +/// TObject::Clone() needs to be overridden. +TObject *RooWorkspace::Clone(const char *newname) const +{ + auto out = new RooWorkspace{*this}; + if(newname && std::string(newname) != GetName()) { + out->SetName(newname); + } + return out; +} + //////////////////////////////////////////////////////////////////////////////// /// Workspace destructor @@ -276,14 +287,14 @@ bool RooWorkspace::import(const char* fileSpec, // Check that file can be opened std::unique_ptr f{TFile::Open(filename.c_str())}; - if (f==0) { + if (f==nullptr) { coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR opening file " << filename << endl ; return false; } // That that file contains workspace RooWorkspace* w = dynamic_cast(f->Get(wsname.c_str())) ; - if (w==0) { + if (w==nullptr) { coutE(InputArguments) << "RooWorkspace(" << GetName() << ") ERROR: No object named " << wsname << " in file " << filename << " or object is not a RooWorkspace" << endl ; return false; @@ -368,7 +379,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, args.Add((TObject*)&arg9) ; // Select the pdf-specific commands - RooCmdConfig pc(Form("RooWorkspace::import(%s)",GetName())) ; + RooCmdConfig pc("RooWorkspace::import(" + std::string(GetName()) + ")"); pc.defineString("conflictSuffix","RenameConflictNodes",0) ; pc.defineInt("renameConflictOrig","RenameConflictNodes",0,0) ; @@ -406,8 +417,8 @@ bool RooWorkspace::import(const RooAbsArg& inArg, // Turn zero length strings into null pointers - if (suffixC && strlen(suffixC)==0) suffixC = 0 ; - if (suffixA && strlen(suffixA)==0) suffixA = 0 ; + if (suffixC && strlen(suffixC)==0) suffixC = nullptr ; + if (suffixA && strlen(suffixA)==0) suffixA = nullptr ; bool conflictOnly = suffixA ? false : true ; const char* suffix = suffixA ? suffixA : suffixC ; @@ -434,7 +445,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, exceptVarNames.insert(toks.begin(), toks.end()); } - if (suffixV != 0 && strlen(suffixV)>0) { + if (suffixV != nullptr && strlen(suffixV)>0) { std::unique_ptr vars{inArg.getVariables()}; for (const auto v : *vars) { if (exceptVarNames.find(v->GetName())==exceptVarNames.end()) { @@ -448,13 +459,13 @@ bool RooWorkspace::import(const RooAbsArg& inArg, // Check for factory specification match const char* tagIn = inArg.getStringAttribute("factory_tag") ; - const char* tagWs = wsarg ? wsarg->getStringAttribute("factory_tag") : 0 ; + const char* tagWs = wsarg ? wsarg->getStringAttribute("factory_tag") : nullptr ; bool factoryMatch = (tagIn && tagWs && !strcmp(tagIn,tagWs)) ; if (factoryMatch) { ((RooAbsArg&)inArg).setAttribute("RooWorkspace::Recycle") ; } - if (!suffix && wsarg && !useExistingNodes && !(inArg.isFundamental() && varMap[inArg.GetName()]!="")) { + if (!suffix && wsarg && !useExistingNodes && !(inArg.isFundamental() && !varMap[inArg.GetName()].empty())) { if (!factoryMatch) { if (wsarg!=&inArg) { coutE(ObjectHandling) << "RooWorkSpace::import(" << GetName() << ") ERROR importing object named " << inArg.GetName() @@ -520,8 +531,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, string tag = Form("ORIGNAME:%s",origName.c_str()) ; cnode2->setAttribute(tag.c_str()) ; if (!cnode2->getStringAttribute("origName")) { - string tag2 = Form("%s",origName.c_str()) ; - cnode2->setStringAttribute("origName",tag2.c_str()) ; + cnode2->setStringAttribute("origName",origName.c_str()); } // Save name of new top level node for later use @@ -568,7 +578,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, << origName << " to " << wsnode->GetName() << endl ; } } else { - coutW(ObjectHandling) << "RooWorkspce::import(" << GetName() << ") Internal error: expected to find existing node " + coutW(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") Internal error: expected to find existing node " << origName << " to be renamed, but didn't find it..." << endl ; } @@ -587,8 +597,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, string tag = Form("ORIGNAME:%s",origName.c_str()) ; cnode->setAttribute(tag.c_str()) ; if (!cnode->getStringAttribute("origName")) { - string tag2 = Form("%s",origName.c_str()) ; - cnode->setStringAttribute("origName",tag2.c_str()) ; + cnode->setStringAttribute("origName",origName.c_str()) ; } if (!silence) { @@ -663,7 +672,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, recycledNodes.add(*_allOwnedNodes.find(node->GetName())) ; // Delete clone of incoming node - nodesToBeDeleted.addOwned(*node) ; + nodesToBeDeleted.addOwned(std::unique_ptr{node}); //cout << "WV: recycling existing node " << existingNode << " = " << existingNode->GetName() << " for imported node " << node << endl ; @@ -673,7 +682,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") importing " << node->ClassName() << "::" << node->GetName() << endl ; } - _allOwnedNodes.addOwned(*node) ; + _allOwnedNodes.addOwned(std::unique_ptr{node}); if (_openTrans) { _sandboxNodes.add(*node) ; } else { @@ -708,7 +717,7 @@ bool RooWorkspace::import(const RooAbsArg& inArg, ///
    `RenameVariable(const char* inputName, const char* outputName)` Change names of observables in dataset upon insertion ///
    `Silence` Be quiet, except in case of errors /// \note From python, use `Import()`, since `import` is a reserved keyword. -bool RooWorkspace::import(RooAbsData& inData, +bool RooWorkspace::import(RooAbsData const& inData, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8, const RooCmdArg& arg9) @@ -751,9 +760,9 @@ bool RooWorkspace::import(RooAbsData& inData, if (!silence) coutI(ObjectHandling) << "RooWorkspace::import(" << GetName() << ") importing dataset " << inData.GetName() << endl ; - // Transform emtpy string into null pointer + // Transform empty string into null pointer if (dsetName && strlen(dsetName)==0) { - dsetName=0 ; + dsetName=nullptr ; } RooLinkedList& dataList = embedded ? _embeddedDataList : _dataList ; @@ -946,10 +955,10 @@ bool RooWorkspace::extendSet(const char* name, const char* newContents) /// Return pointer to previously defined named set with given nmame /// If no such set is found a null pointer is returned -const RooArgSet* RooWorkspace::set(const char* name) +const RooArgSet* RooWorkspace::set(RooStringView name) { - map::iterator i = _namedSets.find(name) ; - return (i!=_namedSets.end()) ? &(i->second) : 0 ; + std::map::iterator i = _namedSets.find(name.c_str()); + return (i!=_namedSets.end()) ? &(i->second) : nullptr; } @@ -1089,7 +1098,7 @@ bool RooWorkspace::importClassCode(TClass* theClass, bool doReplace) //////////////////////////////////////////////////////////////////////////////// -/// Inport code of all classes in the workspace that have a class name +/// Import code of all classes in the workspace that have a class name /// that matches pattern 'pat' and which are not found to be part of /// the standard ROOT distribution. If doReplace is true any existing /// class code saved in the workspace is replaced @@ -1119,7 +1128,7 @@ bool RooWorkspace::importClassCode(const char* pat, bool doReplace) /// Save snapshot of values and attributes (including "Constant") of given parameters. /// \param[in] name Name of the snapshot. /// \param[in] paramNames Comma-separated list of parameter names to be snapshot. -bool RooWorkspace::saveSnapshot(const char* name, const char* paramNames) +bool RooWorkspace::saveSnapshot(RooStringView name, const char* paramNames) { return saveSnapshot(name,argSet(paramNames),false) ; } @@ -1134,20 +1143,21 @@ bool RooWorkspace::saveSnapshot(const char* name, const char* paramNames) /// saved. If importValues is TRUE, the values of the objects passed in the 'params' /// argument are saved -bool RooWorkspace::saveSnapshot(const char* name, const RooArgSet& params, bool importValues) +bool RooWorkspace::saveSnapshot(RooStringView name, const RooArgSet& params, bool importValues) { RooArgSet actualParams; _allOwnedNodes.selectCommon(params, actualParams); - auto snapshot = static_cast(actualParams.snapshot()); + auto snapshot = new RooArgSet; + actualParams.snapshot(*snapshot); - snapshot->setName(name) ; + snapshot->setName(name.c_str()) ; if (importValues) { snapshot->assign(params) ; } - if (std::unique_ptr oldSnap{static_cast(_snapshots.FindObject(name))}) { - coutI(ObjectHandling) << "RooWorkspace::saveSnaphot(" << GetName() << ") replacing previous snapshot with name " << name << endl ; + if (std::unique_ptr oldSnap{static_cast(_snapshots.FindObject(name.c_str()))}) { + coutI(ObjectHandling) << "RooWorkspace::saveSnapshot(" << GetName() << ") replacing previous snapshot with name " << name << endl ; _snapshots.Remove(oldSnap.get()) ; } @@ -1197,7 +1207,7 @@ const RooArgSet* RooWorkspace::getSnapshot(const char* name) const RooAbsPdf* RooWorkspace::pdf(RooStringView name) const { - return dynamic_cast(_allOwnedNodes.find(name)) ; + return dynamic_cast(_allOwnedNodes.find(name.c_str())) ; } @@ -1206,7 +1216,7 @@ RooAbsPdf* RooWorkspace::pdf(RooStringView name) const RooAbsReal* RooWorkspace::function(RooStringView name) const { - return dynamic_cast(_allOwnedNodes.find(name)) ; + return dynamic_cast(_allOwnedNodes.find(name.c_str())) ; } @@ -1215,7 +1225,7 @@ RooAbsReal* RooWorkspace::function(RooStringView name) const RooRealVar* RooWorkspace::var(RooStringView name) const { - return dynamic_cast(_allOwnedNodes.find(name)) ; + return dynamic_cast(_allOwnedNodes.find(name.c_str())) ; } @@ -1224,7 +1234,7 @@ RooRealVar* RooWorkspace::var(RooStringView name) const RooCategory* RooWorkspace::cat(RooStringView name) const { - return dynamic_cast(_allOwnedNodes.find(name)) ; + return dynamic_cast(_allOwnedNodes.find(name.c_str())) ; } @@ -1233,7 +1243,7 @@ RooCategory* RooWorkspace::cat(RooStringView name) const RooAbsCategory* RooWorkspace::catfunc(RooStringView name) const { - return dynamic_cast(_allOwnedNodes.find(name)) ; + return dynamic_cast(_allOwnedNodes.find(name.c_str())) ; } @@ -1243,7 +1253,7 @@ RooAbsCategory* RooWorkspace::catfunc(RooStringView name) const RooAbsArg* RooWorkspace::arg(RooStringView name) const { - return _allOwnedNodes.find(name) ; + return _allOwnedNodes.find(name.c_str()) ; } @@ -1260,7 +1270,11 @@ RooArgSet RooWorkspace::argSet(RooStringView nameList) const if (oneArg) { ret.add(*oneArg) ; } else { - coutE(InputArguments) << " RooWorkspace::argSet(" << GetName() << ") no RooAbsArg named \"" << token << "\" in workspace" << endl ; + std::stringstream ss; + ss << " RooWorkspace::argSet(" << GetName() << ") no RooAbsArg named \"" << token << "\" in workspace" ; + const std::string errorMsg = ss.str(); + coutE(InputArguments) << errorMsg << std::endl; + throw std::runtime_error(errorMsg); } } return ret ; @@ -1288,7 +1302,7 @@ RooAbsArg* RooWorkspace::fundArg(RooStringView name) const RooAbsData* RooWorkspace::data(RooStringView name) const { - return (RooAbsData*)_dataList.FindObject(name) ; + return (RooAbsData*)_dataList.FindObject(name.c_str()) ; } @@ -1297,7 +1311,7 @@ RooAbsData* RooWorkspace::data(RooStringView name) const RooAbsData* RooWorkspace::embeddedData(RooStringView name) const { - return (RooAbsData*)_embeddedDataList.FindObject(name) ; + return (RooAbsData*)_embeddedDataList.FindObject(name.c_str()) ; } @@ -1487,7 +1501,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) return true ; } - // Check if class is listed in a ROOTMAP file - if so we can skip it because it is in the root distribtion + // Check if class is listed in a ROOTMAP file - if so we can skip it because it is in the root distribution const char* mapEntry = gInterpreter->GetClassSharedLibs(tc->GetName()) ; if (mapEntry && strlen(mapEntry)>0) { oocxcoutD(_wspace,ObjectHandling) << "RooWorkspace::CodeRepo(" << _wspace->GetName() << ") code of class " << tc->GetName() << " is in ROOT distribution, skipping " << endl ; @@ -1551,7 +1565,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) if (declpath.empty()) { oocoutW(_wspace,ObjectHandling) << "RooWorkspace::autoImportClass(" << _wspace->GetName() << ") WARNING Cannot access code of class " << tc->GetName() << " because header file " << declfile << " is not found in current directory nor in $ROOTSYS" ; - if (_classDeclDirList.size()>0) { + if (!_classDeclDirList.empty()) { ooccoutW(_wspace,ObjectHandling) << ", nor in the search path " ; diter = RooWorkspace::_classDeclDirList.begin() ; @@ -1596,7 +1610,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) if (implpath.empty()) { oocoutW(_wspace,ObjectHandling) << "RooWorkspace::autoImportClass(" << _wspace->GetName() << ") WARNING Cannot access code of class " << tc->GetName() << " because implementation file " << implfile << " is not found in current directory nor in $ROOTSYS" ; - if (_classDeclDirList.size()>0) { + if (!_classDeclDirList.empty()) { ooccoutW(_wspace,ObjectHandling) << ", nor in the search path " ; iiter = RooWorkspace::_classImplDirList.begin() ; @@ -1638,7 +1652,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) list extraHeaders ; - // If file has not beed stored yet, enter stl strings with implementation and declaration in file map + // If file has not been stored yet, enter stl strings with implementation and declaration in file map if (_fmap.find(declfilebase) == _fmap.end()) { // Open declaration file @@ -1663,7 +1677,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) // Look for include state of self bool processedInclude = false ; - char* extincfile = 0 ; + char* extincfile = nullptr ; // Look for include of declaration file corresponding to this implementation file if (strstr(buf,"#include")) { @@ -1672,7 +1686,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) strlcpy(tmp, buf, 64000); bool stdinclude = strchr(buf, '<'); strtok(tmp, " <\""); - char *incfile = strtok(0, " <>\""); + char *incfile = strtok(nullptr, " <>\""); if (!stdinclude) { // check if it lives in $ROOTSYS/include @@ -1709,7 +1723,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) } - // Import entire implentation file into stl string + // Import entire implementation file into stl string string impl ; while(fimpl.getline(buf,1023)) { // Process #include statements here @@ -1717,7 +1731,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) // Look for include state of self bool foundSelfInclude=false ; bool processedInclude = false ; - char* extincfile = 0 ; + char* extincfile = nullptr ; // Look for include of declaration file corresponding to this implementation file if (strstr(buf,"#include")) { @@ -1726,7 +1740,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) strlcpy(tmp, buf, 64000); bool stdinclude = strchr(buf, '<'); strtok(tmp, " <\""); - char *incfile = strtok(0, " <>\""); + char *incfile = strtok(nullptr, " <>\""); if (strstr(incfile, declfilename.c_str())) { foundSelfInclude = true; @@ -1787,7 +1801,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) strlcpy(tmp, buf2, 64000); bool stdinclude = strchr(buf, '<'); strtok(tmp, " <\""); - char *incfile = strtok(0, " <>\""); + char *incfile = strtok(nullptr, " <>\""); if (!stdinclude) { // check if it lives in $ROOTSYS/include @@ -1817,7 +1831,7 @@ bool RooWorkspace::CodeRepo::autoImportClass(TClass* tc, bool doReplace) // Inform that existing file entry is being recycled because it already contained class code oocoutI(_wspace,ObjectHandling) << "RooWorkspace::autoImportClass(" << _wspace->GetName() << ") code of class " << tc->GetName() - << " was already imported from " << (!implpath.empty() ? implpath : implfile.c_str()) + << " was already imported from " << (!implpath.empty() ? implpath : implfile) << " and " << (!declpath.empty() ? declpath.c_str() : declfile.c_str()) << std::endl; } @@ -1868,8 +1882,8 @@ bool RooWorkspace::makeDir() { if (_dir) return true ; - TString title= Form("TDirectory representation of RooWorkspace %s",GetName()) ; - _dir = new WSDir(GetName(),title.Data(),this) ; + std::string title= "TDirectory representation of RooWorkspace " + std::string(GetName()); + _dir = new WSDir(GetName(),title.c_str(),this) ; for (RooAbsArg * darg : _allOwnedNodes) { if (darg->IsA() != RooConstVar::Class()) { @@ -1889,7 +1903,7 @@ bool RooWorkspace::makeDir() /// /// Returns true if an error has occurred. -bool RooWorkspace::import(TObject& object, bool replaceExisting) +bool RooWorkspace::import(TObject const& object, bool replaceExisting) { // First check if object with given name already exists std::unique_ptr oldObj{_genObjects.FindObject(object.GetName())}; @@ -1901,7 +1915,7 @@ bool RooWorkspace::import(TObject& object, bool replaceExisting) // Grab the current state of the directory Auto-Add ROOT::DirAutoAdd_t func = object.IsA()->GetDirectoryAutoAdd(); - object.IsA()->SetDirectoryAutoAdd(0); + object.IsA()->SetDirectoryAutoAdd(nullptr); bool tmp = RooPlot::setAddDirectoryStatus(false) ; if (oldObj) { @@ -1929,13 +1943,13 @@ bool RooWorkspace::import(TObject& object, bool replaceExisting) /// /// Returns true if an error has occurred. -bool RooWorkspace::import(TObject& object, const char* aliasName, bool replaceExisting) +bool RooWorkspace::import(TObject const& object, const char* aliasName, bool replaceExisting) { // First check if object with given name already exists - std::unique_ptr oldObj{_genObjects.FindObject(object.GetName())}; + std::unique_ptr oldObj{_genObjects.FindObject(aliasName)}; if (oldObj && !replaceExisting) { coutE(InputArguments) << "RooWorkspace::import(" << GetName() << ") generic object with name " - << object.GetName() << " is already in workspace and replaceExisting flag is set to false" << endl ; + << aliasName << " is already in workspace and replaceExisting flag is set to false" << endl ; return true ; } @@ -2006,7 +2020,7 @@ TObject* RooWorkspace::obj(RooStringView name) const TObject* RooWorkspace::genobj(RooStringView name) const { // Find object by name - TObject* gobj = _genObjects.FindObject(name) ; + TObject* gobj = _genObjects.FindObject(name.c_str()) ; // Exit here if not found if (!gobj) return nullptr; @@ -2063,7 +2077,7 @@ RooFactoryWSTool& RooWorkspace::factory() /// \copydoc RooFactoryWSTool::process(const char*) RooAbsArg* RooWorkspace::factory(RooStringView expr) { - return factory().process(expr) ; + return factory().process(expr.c_str()) ; } @@ -2267,7 +2281,7 @@ void RooWorkspace::Print(Option_t* opts) const } - if (_namedSets.size()>0) { + if (!_namedSets.empty()) { cout << "named sets" << endl ; cout << "----------" << endl ; for (map::const_iterator it = _namedSets.begin() ; it != _namedSets.end() ; ++it) { @@ -2550,7 +2564,7 @@ std::string RooWorkspace::CodeRepo::listOfClassNames() const string ret ; map::const_iterator iter = _c2fmap.begin() ; while(iter!=_c2fmap.end()) { - if (ret.size()>0) { + if (!ret.empty()) { ret += ", " ; } ret += iter->first ; @@ -2706,12 +2720,12 @@ bool RooWorkspace::CodeRepo::compileClasses() if (!writeExtraHeaders) { writeExtraHeaders = true ; - map::iterator eiter = _ehmap.begin() ; - while(eiter!=_ehmap.end()) { + map::iterator extraIter = _ehmap.begin() ; + while(extraIter!=_ehmap.end()) { // Check if identical declaration file (header) is already written bool needEHWrite=true ; - string fdname = Form("%s/%s",dirName.c_str(),eiter->second._hname.Data()) ; + string fdname = Form("%s/%s",dirName.c_str(),extraIter->second._hname.Data()) ; ifstream ifdecl(fdname.c_str()) ; if (ifdecl) { TString contents ; @@ -2721,7 +2735,7 @@ bool RooWorkspace::CodeRepo::compileClasses() contents += "\n"; } UInt_t crcFile = crc32(contents.Data()); - UInt_t crcWS = crc32(eiter->second._hfile.Data()); + UInt_t crcWS = crc32(extraIter->second._hfile.Data()); needEHWrite = (crcFile != crcWS); } @@ -2739,10 +2753,10 @@ bool RooWorkspace::CodeRepo::compileClasses() << " for writing" << endl; return false; } - fdecl << eiter->second._hfile.Data(); + fdecl << extraIter->second._hfile.Data(); fdecl.close(); } - ++eiter; + ++extraIter; } } diff --git a/roofit/roofitcore/src/RooXYChi2Var.cxx b/roofit/roofitcore/src/RooXYChi2Var.cxx index a9e0262f5cbfd..0b62812fe6aeb 100644 --- a/roofit/roofitcore/src/RooXYChi2Var.cxx +++ b/roofit/roofitcore/src/RooXYChi2Var.cxx @@ -47,7 +47,7 @@ using namespace std; ClassImp(RooXYChi2Var); -; + namespace { RooAbsTestStatistic::Configuration makeRooAbsTestStatisticCfg() { @@ -59,16 +59,12 @@ namespace { //////////////////////////////////////////////////////////////////////////////// -/// coverity[UNINIT_CTOR] - -RooXYChi2Var::RooXYChi2Var() -{ -} - - -//////////////////////////////////////////////////////////////////////////////// /// -/// RooXYChi2Var constructor with function and X-Y values dataset +/// RooXYChi2Var constructor with function and X-Y values dataset +/// +/// If the function is a pdf, it must be extendable. in this case, hhe value of +/// the function that defines the chi^2 in this form is takes as the p.d.f. +/// times the expected number of events /// /// An X-Y dataset is a weighted dataset with one or more observables X where the weight is interpreted /// as the Y value and the weight error is interpreted as the Y value error. The weight must have an @@ -81,22 +77,18 @@ RooXYChi2Var::RooXYChi2Var() /// are the double values that correspond to the Y and its error /// -RooXYChi2Var::RooXYChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataSet& xydata, bool integrate) : - RooAbsOptTestStatistic(name,title,func,xydata,RooArgSet(),makeRooAbsTestStatisticCfg()), - _extended(false), - _integrate(integrate), - _intConfig(*defaultIntegratorConfig()) +RooXYChi2Var::RooXYChi2Var(const char *name, const char *title, RooAbsReal &func, RooDataSet &xydata, bool integrate) + : RooXYChi2Var{name, title, func, xydata, nullptr, integrate, makeRooAbsTestStatisticCfg()} { - _extended = false ; - _yvar = 0 ; - - initialize() ; } - //////////////////////////////////////////////////////////////////////////////// /// -/// RooXYChi2Var constructor with function and X-Y values dataset +/// RooXYChi2Var constructor with function and X-Y values dataset. +/// +/// If the function is a pdf, it must be extendable. in this case, hhe value of +/// the function that defines the chi^2 in this form is takes as the p.d.f. +/// times the expected number of events /// /// An X-Y dataset is a weighted dataset with one or more observables X where given yvar is interpreted /// as the Y value. The Y variable must have a non-zero error defined at each point for the chi^2 calculation to be meaningful. @@ -108,83 +100,37 @@ RooXYChi2Var::RooXYChi2Var(const char *name, const char* title, RooAbsReal& func /// are the double values that correspond to the Y and its error /// -RooXYChi2Var::RooXYChi2Var(const char *name, const char* title, RooAbsReal& func, RooDataSet& xydata, RooRealVar& yvar, bool integrate) : - RooAbsOptTestStatistic(name,title,func,xydata,RooArgSet(),makeRooAbsTestStatisticCfg()), - _extended(false), - _integrate(integrate), - _intConfig(*defaultIntegratorConfig()) +RooXYChi2Var::RooXYChi2Var(const char *name, const char *title, RooAbsReal &func, RooDataSet &xydata, RooRealVar &yvar, + bool integrate) + : RooXYChi2Var{name, title, func, xydata, &yvar, integrate, makeRooAbsTestStatisticCfg()} { - _extended = false ; - _yvar = (RooRealVar*) _dataClone->get()->find(yvar.GetName()) ; - - initialize() ; } -//////////////////////////////////////////////////////////////////////////////// -/// -/// RooXYChi2Var constructor with an extended p.d.f. and X-Y values dataset -/// The value of the function that defines the chi^2 in this form is takes as -/// the p.d.f. times the expected number of events -/// -/// An X-Y dataset is a weighted dataset with one or more observables X where the weight is interpreted -/// as the Y value and the weight error is interpreted as the Y value error. The weight must have an -/// non-zero error defined at each point for the chi^2 calculation to be meaningful. -/// -/// To store errors associated with the x and y values in a RooDataSet, call RooRealVar::setAttribute("StoreError") -/// on each X-type observable for which the error should be stored and add datapoints to the dataset as follows -/// -/// RooDataSet::add(xset,yval,yerr) where xset is the RooArgSet of x observables (with or without errors) and yval and yerr -/// are the double values that correspond to the Y and its error -/// - -RooXYChi2Var::RooXYChi2Var(const char *name, const char* title, RooAbsPdf& extPdf, RooDataSet& xydata, bool integrate) : - RooAbsOptTestStatistic(name,title,extPdf,xydata,RooArgSet(),makeRooAbsTestStatisticCfg()), - _extended(true), - _integrate(integrate), - _intConfig(*defaultIntegratorConfig()) +/// \cond ROOFIT_INTERNAL +// For internal use in RooAbsReal::createChi2(). +RooXYChi2Var::RooXYChi2Var(const char *name, const char *title, RooAbsReal &func, RooAbsData &data, RooRealVar *yvar, + bool integrate, RooAbsTestStatistic::Configuration const &cfg) + : RooAbsOptTestStatistic(name, title, func, data, RooArgSet(), cfg), + _integrate(integrate), + _intConfig(*defaultIntegratorConfig()) { - if (!extPdf.canBeExtended()) { - throw std::runtime_error(Form("RooXYChi2Var::RooXYChi2Var(%s) ERROR: Input p.d.f. must be extendible",GetName())); - } - _yvar = 0 ; - initialize() ; -} - - + bool isPdf = dynamic_cast(&func) != nullptr; + if (isPdf) { + auto &extPdf = static_cast(func); + if (!extPdf.canBeExtended()) { + throw std::runtime_error( + Form("RooXYChi2Var::RooXYChi2Var(%s) ERROR: Input p.d.f. must be extendible", GetName())); + } + } -//////////////////////////////////////////////////////////////////////////////// -/// -/// RooXYChi2Var constructor with an extended p.d.f. and X-Y values dataset -/// The value of the function that defines the chi^2 in this form is takes as -/// the p.d.f. times the expected number of events -/// -/// An X-Y dataset is a weighted dataset with one or more observables X where the weight is interpreted -/// as the Y value and the weight error is interpreted as the Y value error. The weight must have an -/// non-zero error defined at each point for the chi^2 calculation to be meaningful. -/// -/// To store errors associated with the x and y values in a RooDataSet, call RooRealVar::setAttribute("StoreError") -/// on each X-type observable for which the error should be stored and add datapoints to the dataset as follows -/// -/// RooDataSet::add(xset,yval,yerr) where xset is the RooArgSet of x observables (with or without errors) and yval and yerr -/// are the double values that correspond to the Y and its error -/// + _extended = isPdf; + _yvar = yvar ? static_cast(_dataClone->get()->find(yvar->GetName())) : nullptr; -RooXYChi2Var::RooXYChi2Var(const char *name, const char* title, RooAbsPdf& extPdf, RooDataSet& xydata, RooRealVar& yvar, bool integrate) : - RooAbsOptTestStatistic(name,title,extPdf,xydata,RooArgSet(),makeRooAbsTestStatisticCfg()), - _extended(true), - _integrate(integrate), - _intConfig(*defaultIntegratorConfig()) -{ - if (!extPdf.canBeExtended()) { - throw std::runtime_error(Form("RooXYChi2Var::ctor(%s) ERROR: Input p.d.f. must be an extendible",GetName())); - } - _yvar = (RooRealVar*) _dataClone->get()->find(yvar.GetName()) ; - initialize() ; + initialize(); } - - +/// \endcond ROOFIT_INTERNAL //////////////////////////////////////////////////////////////////////////////// @@ -196,14 +142,12 @@ RooXYChi2Var::RooXYChi2Var(const RooXYChi2Var& other, const char* name) : _integrate(other._integrate), _intConfig(other._intConfig) { - _yvar = other._yvar ? (RooRealVar*) _dataClone->get()->find(other._yvar->GetName()) : 0 ; + _yvar = other._yvar ? (RooRealVar*) _dataClone->get()->find(other._yvar->GetName()) : nullptr ; initialize() ; } - - //////////////////////////////////////////////////////////////////////////////// /// Common constructor initialization @@ -245,7 +189,7 @@ void RooXYChi2Var::initialize() void RooXYChi2Var::initIntegrator() { if (!_funcInt) { - _funcInt = _funcClone->createIntegral(_rrvArgs,_rrvArgs,_intConfig,"bin") ; + _funcInt = std::unique_ptr{_funcClone->createIntegral(_rrvArgs,_rrvArgs,_intConfig,"bin")}; for(auto * x : static_range_cast(_rrvArgs)) { _binList.push_back(&x->getBinning("bin",false,true)) ; } @@ -254,16 +198,7 @@ void RooXYChi2Var::initIntegrator() } - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor - -RooXYChi2Var::~RooXYChi2Var() -{ - if (_funcInt) delete _funcInt ; -} - - +RooXYChi2Var::~RooXYChi2Var() = default; //////////////////////////////////////////////////////////////////////////////// @@ -390,8 +325,6 @@ double RooXYChi2Var::evaluatePartition(std::size_t firstEvent, std::size_t lastE // Loop over bins of dataset RooDataSet* xydata = (RooDataSet*) _dataClone ; - _dataClone->store()->recalculateCache( _projDeps, firstEvent, lastEvent, stepSize,false ) ; - for (auto i=firstEvent ; i -#include - -class RooAbsArg; - -namespace RooBatchCompute { - -/// Check if there is a span of data corresponding to the object passed as owner. -RooSpan RunContext::getBatch(const RooAbsArg* owner) const { - const auto item = spans.find(owner); - if (item != spans.end()) - return item->second; - - return {}; -} - - -/// Check if there is a writable span of data corresponding to the object passed as owner. -/// The span can be used both for reading and writing. -RooSpan RunContext::getWritableBatch(const RooAbsArg* owner) { - auto item = ownedMemory.find(owner); - if (item != ownedMemory.end()) { - assert(spans.count(owner) > 0); // If we can write, the span must also be registered for reading - return RooSpan(item->second); - } - - return {}; -} - - -/// Create a writable batch. If the RunContext already owns memory for the object -/// `owner`, just resize the memory. If it doesn't exist yet, allocate it. -/// \warning The memory will be uninitialised, so every entry **must** be overwritten. -/// On first use, all values are initialised to `NaN` to help detect such errors. -/// -/// A read-only reference to the memory will be stored in `spans`. -/// \param owner RooFit object whose value should be written into the memory. -/// \param size Requested size of the span. -/// \return A writeable RooSpan of the requested size, whose memory is owned by -/// the RunContext. -RooSpan RunContext::makeBatch(const RooAbsArg* owner, std::size_t size) { - auto item = ownedMemory.find(owner); - if (item == ownedMemory.end() || item->second.size() != size) { - std::vector& data = ownedMemory[owner]; - data.resize(size, std::numeric_limits::quiet_NaN()); -#ifndef NDEBUG - data.assign(size, std::numeric_limits::quiet_NaN()); -#endif - spans[owner] = RooSpan(data); - return {data}; - } - - spans[owner] = RooSpan(item->second); - return {item->second}; -} - -void RunContext::clear() { - spans.clear(); - rangeName = nullptr; -} - -} diff --git a/roofit/roofitcore/src/TestStatistics/LikelihoodJob.cxx b/roofit/roofitcore/src/TestStatistics/LikelihoodJob.cxx index 297012c8277ec..e0b92eec25dda 100644 --- a/roofit/roofitcore/src/TestStatistics/LikelihoodJob.cxx +++ b/roofit/roofitcore/src/TestStatistics/LikelihoodJob.cxx @@ -70,9 +70,10 @@ void LikelihoodJob::init_vars() save_vars_.removeAll(); // Retrieve non-constant parameters - auto vars = std::make_unique( - *likelihood_->getParameters()); // TODO: make sure this is the right list of parameters, compare to original - // implementation in RooRealMPFE.cxx + std::unique_ptr vars{likelihood_->getParameters()}; + // TODO: make sure this is the right list of parameters, compare to original + // implementation in RooRealMPFE.cxx + RooArgList varList(*vars); // Save in lists @@ -193,7 +194,8 @@ void LikelihoodJob::evaluate() // wait for task results back from workers to master gather_worker_results(); - result_ = 0; + result_ = ROOT::Math::KahanSum{0.}; +// printf("Master evaluate: "); for (auto const &item : results_) { result_ += item; } diff --git a/roofit/roofitcore/src/TestStatistics/LikelihoodSerial.cxx b/roofit/roofitcore/src/TestStatistics/LikelihoodSerial.cxx index 44c8f6f77fbec..a36c1c1474ad4 100644 --- a/roofit/roofitcore/src/TestStatistics/LikelihoodSerial.cxx +++ b/roofit/roofitcore/src/TestStatistics/LikelihoodSerial.cxx @@ -53,7 +53,7 @@ LikelihoodSerial::LikelihoodSerial(std::shared_ptr likelihood, std::sha // should also somehow be updated in this class. } -/// \brief Helper function for the constuctor. +/// \brief Helper function for the constructor. /// /// This is a separate function (instead of just in ctor) for historical reasons. /// Its predecessor RooRealMPFE::initVars() was used from multiple ctors, but also @@ -67,7 +67,7 @@ void LikelihoodSerial::initVars() _saveVars.removeAll(); // Retrieve non-constant parameters - auto vars = std::make_unique(*likelihood_->getParameters()); + std::unique_ptr vars{likelihood_->getParameters()}; RooArgList varList(*vars); diff --git a/roofit/roofitcore/src/TestStatistics/LikelihoodWrapper.cxx b/roofit/roofitcore/src/TestStatistics/LikelihoodWrapper.cxx index e69a878c57a4b..3b959be3575fa 100644 --- a/roofit/roofitcore/src/TestStatistics/LikelihoodWrapper.cxx +++ b/roofit/roofitcore/src/TestStatistics/LikelihoodWrapper.cxx @@ -86,7 +86,7 @@ void LikelihoodWrapper::enableOffsetting(bool flag) do_offset_ = flag; // Clear offset if feature is disabled so that it is recalculated next time it is enabled if (!do_offset_) { - offset_ = {}; + offset_ = ROOT::Math::KahanSum(); } } @@ -97,7 +97,7 @@ void LikelihoodWrapper::setOffsettingMode(OffsettingMode mode) oocoutI(nullptr, Minimization) << "LikelihoodWrapper::setOffsettingMode(" << GetName() << "): changed offsetting mode while offsetting was enabled; resetting offset values" << std::endl; - offset_ = {}; + offset_ = ROOT::Math::KahanSum(); } } @@ -106,7 +106,7 @@ ROOT::Math::KahanSum LikelihoodWrapper::applyOffsetting(ROOT::Math::Kaha if (do_offset_) { // If no offset is stored enable this feature now - if (offset_ == 0 && current_value != 0) { + if (offset_.Sum() == 0 && offset_.Carry() == 0 && (current_value.Sum() != 0 || current_value.Carry() != 0)) { offset_ = current_value; if (offsetting_mode_ == OffsettingMode::legacy) { auto sum_likelihood = dynamic_cast(likelihood_.get()); @@ -115,11 +115,11 @@ ROOT::Math::KahanSum LikelihoodWrapper::applyOffsetting(ROOT::Math::Kaha // "undo" the addition of the subsidiary value to emulate legacy behavior offset_ -= subsidiary_value; // manually calculate result with zero carry, again to emulate legacy behavior - return {current_value.Result() - offset_.Result()}; + return ROOT::Math::KahanSum{current_value.Result() - offset_.Result()}; } } oocoutI(nullptr, Minimization) - << "LikelihoodWrapper::applyOffsetting(" << GetName() << "): Likelihood offset now set to " << offset_ + << "LikelihoodWrapper::applyOffsetting(" << GetName() << "): Likelihood offset now set to " << offset_.Sum() << std::endl; } diff --git a/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.cxx b/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.cxx index cb305ada6a62c..eb5e4751f23c8 100644 --- a/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.cxx +++ b/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.cxx @@ -21,6 +21,40 @@ namespace RooFit { namespace TestStatistics { +namespace { + +class MinuitGradFunctor : public ROOT::Math::IMultiGradFunction { + +public: + MinuitGradFunctor(MinuitFcnGrad const &fcn) : _fcn{fcn} {} + + ROOT::Math::IMultiGradFunction *Clone() const override { return new MinuitGradFunctor(_fcn); } + + unsigned int NDim() const override { return _fcn.NDim(); } + + void Gradient(const double *x, double *grad) const override { return _fcn.Gradient(x, grad); } + + void GradientWithPrevResult(const double *x, double *grad, double *previous_grad, double *previous_g2, + double *previous_gstep) const override + { + return _fcn.GradientWithPrevResult(x, grad, previous_grad, previous_g2, previous_gstep); + } + + bool returnsInMinuit2ParameterSpace() const override { return _fcn.returnsInMinuit2ParameterSpace(); } + +private: + double DoEval(const double *x) const override { return _fcn(x); } + + double DoDerivative(double const * /*x*/, unsigned int /*icoord*/) const override + { + throw std::runtime_error("MinuitFcnGrad::DoDerivative is not implemented, please use Gradient instead."); + } + + MinuitFcnGrad const &_fcn; +}; + +} // namespace + /** \class MinuitFcnGrad * * \brief Minuit-RooMinimizer interface which synchronizes parameter data and coordinates evaluation of likelihood @@ -37,7 +71,7 @@ namespace TestStatistics { * likelihood object, or to use a higher level entry point like RooAbsPdf::fitTo() or RooAbsPdf::createNLL(). */ -/// \param[in] _likelihood L +/// \param[in] absL The input likelihood. /// \param[in] context RooMinimizer that creates and owns this class. /// \param[in] parameters The vector of ParameterSettings objects that describe the parameters used in the Minuit /// \param[in] likelihoodMode Lmode @@ -45,50 +79,45 @@ namespace TestStatistics { /// \param[in] verbose true for verbose output /// Fitter. Note that these must match the set used in the Fitter used by \p context! It can be passed in from /// RooMinimizer with fitter()->Config().ParamsSettings(). -MinuitFcnGrad::MinuitFcnGrad(const std::shared_ptr &_likelihood, RooMinimizer *context, +MinuitFcnGrad::MinuitFcnGrad(const std::shared_ptr &absL, RooMinimizer *context, std::vector ¶meters, LikelihoodMode likelihoodMode, LikelihoodGradientMode likelihoodGradientMode) - : RooAbsMinimizerFcn(RooArgList(*_likelihood->getParameters()), context), minuit_internal_x_(NDim(), 0), - minuit_external_x_(NDim(), 0) + : RooAbsMinimizerFcn(*absL->getParameters(), context), + _minuitInternalX(NDim(), 0), + _minuitExternalX(NDim(), 0), + _multiGenFcn{std::make_unique(*this)} { synchronizeParameterSettings(parameters, true); - calculation_is_clean = std::make_shared(); + _calculationIsClean = std::make_unique(); - likelihood = LikelihoodWrapper::create(likelihoodMode, _likelihood, calculation_is_clean); - if (likelihoodMode == LikelihoodMode::multiprocess && likelihoodGradientMode == LikelihoodGradientMode::multiprocess) { - likelihood_in_gradient = LikelihoodWrapper::create(LikelihoodMode::serial, _likelihood, calculation_is_clean); - } else { - likelihood_in_gradient = likelihood; + _likelihood = LikelihoodWrapper::create(likelihoodMode, absL, _calculationIsClean); + if (likelihoodMode == LikelihoodMode::multiprocess && + likelihoodGradientMode == LikelihoodGradientMode::multiprocess) { + _likelihoodInGradient = LikelihoodWrapper::create(LikelihoodMode::serial, absL, _calculationIsClean); } - gradient = - LikelihoodGradientWrapper::create(likelihoodGradientMode, _likelihood, calculation_is_clean, getNDim(), _context); + _gradient = + LikelihoodGradientWrapper::create(likelihoodGradientMode, absL, _calculationIsClean, getNDim(), _context); - likelihood->synchronizeParameterSettings(parameters); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->synchronizeParameterSettings(parameters); - } - gradient->synchronizeParameterSettings(this, parameters); + applyToLikelihood([&](auto &l) { l.synchronizeParameterSettings(parameters); }); + _gradient->synchronizeParameterSettings(getMultiGenFcn(), parameters); // Note: can be different than RooGradMinimizerFcn/LikelihoodGradientSerial, where default options are passed // (ROOT::Math::MinimizerOptions::DefaultStrategy() and ROOT::Math::MinimizerOptions::DefaultErrorDef()) - likelihood->synchronizeWithMinimizer(ROOT::Math::MinimizerOptions()); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->synchronizeWithMinimizer(ROOT::Math::MinimizerOptions()); - } - gradient->synchronizeWithMinimizer(ROOT::Math::MinimizerOptions()); + applyToLikelihood([&](auto &l) { l.synchronizeWithMinimizer(ROOT::Math::MinimizerOptions()); }); + _gradient->synchronizeWithMinimizer(ROOT::Math::MinimizerOptions()); } -double MinuitFcnGrad::DoEval(const double *x) const +double MinuitFcnGrad::operator()(const double *x) const { bool parameters_changed = syncParameterValuesFromMinuitCalls(x, false); // Calculate the function for these parameters // RooAbsReal::setHideOffset(false); - auto likelihood_here(gradient->isCalculating() ? likelihood_in_gradient : likelihood); - likelihood_here->evaluate(); - double fvalue = likelihood_here->getResult().Sum(); - calculation_is_clean->likelihood = true; + auto &likelihoodHere(_likelihoodInGradient && _gradient->isCalculating() ? *_likelihoodInGradient : *_likelihood); + likelihoodHere.evaluate(); + double fvalue = likelihoodHere.getResult().Sum(); + _calculationIsClean->likelihood = true; // RooAbsReal::setHideOffset(true); if (!parameters_changed) { @@ -104,25 +133,23 @@ double MinuitFcnGrad::DoEval(const double *x) const << "Returning maximum FCN so far (" << _maxFCN << ") to force MIGRAD to back out of this region. Error log follows" << std::endl; } else { - oocoutW(nullptr, Eval) << "MinuitFcnGrad: Minimized function has error status but is ignored" - << std::endl; + oocoutW(nullptr, Eval) << "MinuitFcnGrad: Minimized function has error status but is ignored" << std::endl; } bool first(true); - ooccoutW(static_cast(nullptr), Eval) << "Parameter values: "; - for (const auto rooAbsArg : *_floatParamList) { - auto var = static_cast(rooAbsArg); + ooccoutW(nullptr, Eval) << "Parameter values: "; + for (auto *var : static_range_cast(*_floatParamList)) { if (first) { first = false; } else { - ooccoutW(static_cast(nullptr), Eval) << ", "; + ooccoutW(nullptr, Eval) << ", "; } - ooccoutW(static_cast(nullptr), Eval) << var->GetName() << "=" << var->getVal(); + ooccoutW(nullptr, Eval) << var->GetName() << "=" << var->getVal(); } - ooccoutW(static_cast(nullptr), Eval) << std::endl; + ooccoutW(nullptr, Eval) << std::endl; - RooAbsReal::printEvalErrors(ooccoutW(static_cast(nullptr), Eval), cfg().printEvalErrors); - ooccoutW(static_cast(nullptr), Eval) << std::endl; + RooAbsReal::printEvalErrors(ooccoutW(nullptr, Eval), cfg().printEvalErrors); + ooccoutW(nullptr, Eval) << std::endl; } if (cfg().doEEWall) { @@ -137,7 +164,7 @@ double MinuitFcnGrad::DoEval(const double *x) const // Optional logging if (cfg().verbose) { - std::cout << "\nprevFCN" << (likelihood_here->isOffsetting() ? "-offset" : "") << " = " << std::setprecision(10) + std::cout << "\nprevFCN" << (likelihoodHere.isOffsetting() ? "-offset" : "") << " = " << std::setprecision(10) << fvalue << std::setprecision(4) << " "; std::cout.flush(); } @@ -179,13 +206,13 @@ double MinuitFcnGrad::DoEval(const double *x) const /// happens when Minuit tries out values that lay outside the RooFit parameter's range(s). RooFit's setVal (called /// inside SetPdfParamVal) then clips the RooAbsArg's value to one of the range limits, instead of setting it to the /// value Minuit intended. When this happens, i.e. syncParameterValuesFromMinuitCalls is called with -/// minuit_internal = false and the values do not match the previous values stored in minuit_internal_x_ *but* the -/// values after SetPdfParamVal did not get set to the intended value, the minuit_internal_roofit_x_mismatch_ flag is +/// minuit_internal = false and the values do not match the previous values stored in _minuitInternalX *but* the +/// values after SetPdfParamVal did not get set to the intended value, the _minuitInternalRooFitXMismatch flag is /// set. This information can be used by calculators, if desired, for instance when a calculator does not want to make /// use of the range information in the RooAbsArg parameters. bool MinuitFcnGrad::syncParameterValuesFromMinuitCalls(const double *x, bool minuit_internal) const { - bool a_parameter_has_been_updated = false; + bool aParamWasUpdated = false; if (minuit_internal) { if (!returnsInMinuit2ParameterSpace()) { throw std::logic_error("Updating Minuit-internal parameters only makes sense for (gradient) calculators that " @@ -193,88 +220,72 @@ bool MinuitFcnGrad::syncParameterValuesFromMinuitCalls(const double *x, bool min } for (std::size_t ix = 0; ix < NDim(); ++ix) { - bool parameter_changed = (x[ix] != minuit_internal_x_[ix]); + bool parameter_changed = (x[ix] != _minuitInternalX[ix]); if (parameter_changed) { - minuit_internal_x_[ix] = x[ix]; + _minuitInternalX[ix] = x[ix]; } - a_parameter_has_been_updated |= parameter_changed; + aParamWasUpdated |= parameter_changed; } - if (a_parameter_has_been_updated) { - calculation_is_clean->set_all(false); - likelihood->updateMinuitInternalParameterValues(minuit_internal_x_); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->updateMinuitInternalParameterValues(minuit_internal_x_); - } - gradient->updateMinuitInternalParameterValues(minuit_internal_x_); + if (aParamWasUpdated) { + _calculationIsClean->set_all(false); + applyToLikelihood([&](auto &l) { l.updateMinuitInternalParameterValues(_minuitInternalX); }); + _gradient->updateMinuitInternalParameterValues(_minuitInternalX); } } else { - bool a_parameter_is_mismatched = false; + bool aParamIsMismatched = false; for (std::size_t ix = 0; ix < NDim(); ++ix) { // Note: the return value of SetPdfParamVal does not always mean that the parameter's value in the RooAbsReal // changed since last time! If the value was out of range bin, setVal was still called, but the value was not // updated. SetPdfParamVal(ix, x[ix]); - minuit_external_x_[ix] = x[ix]; - // The above is why we need minuit_external_x_. The minuit_external_x_ vector can also be passed to + _minuitExternalX[ix] = x[ix]; + // The above is why we need _minuitExternalX. The _minuitExternalX vector can also be passed to // LikelihoodWrappers, if needed, but typically they will make use of the RooFit parameters directly. However, // we log in the flag below whether they are different so that calculators can use this information. - bool parameter_changed = (x[ix] != minuit_external_x_[ix]); - a_parameter_has_been_updated |= parameter_changed; - a_parameter_is_mismatched |= (((RooRealVar *)_floatParamList->at(ix))->getVal() != minuit_external_x_[ix]); + bool parameter_changed = (x[ix] != _minuitExternalX[ix]); + aParamWasUpdated |= parameter_changed; + aParamIsMismatched |= + (static_cast(_floatParamList->at(ix))->getVal() != _minuitExternalX[ix]); } - minuit_internal_roofit_x_mismatch_ = a_parameter_is_mismatched; + _minuitInternalRooFitXMismatch = aParamIsMismatched; - if (a_parameter_has_been_updated) { - calculation_is_clean->set_all(false); - likelihood->updateMinuitExternalParameterValues(minuit_external_x_); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->updateMinuitExternalParameterValues(minuit_external_x_); - } - gradient->updateMinuitExternalParameterValues(minuit_external_x_); + if (aParamWasUpdated) { + _calculationIsClean->set_all(false); + applyToLikelihood([&](auto &l) { l.updateMinuitExternalParameterValues(_minuitExternalX); }); + _gradient->updateMinuitExternalParameterValues(_minuitExternalX); } } - return a_parameter_has_been_updated; + return aParamWasUpdated; } void MinuitFcnGrad::Gradient(const double *x, double *grad) const { - calculating_gradient_ = true; + _calculatingGradient = true; syncParameterValuesFromMinuitCalls(x, returnsInMinuit2ParameterSpace()); - gradient->fillGradient(grad); - calculating_gradient_ = false; + _gradient->fillGradient(grad); + _calculatingGradient = false; } void MinuitFcnGrad::GradientWithPrevResult(const double *x, double *grad, double *previous_grad, double *previous_g2, double *previous_gstep) const { - calculating_gradient_ = true; + _calculatingGradient = true; syncParameterValuesFromMinuitCalls(x, returnsInMinuit2ParameterSpace()); - gradient->fillGradientWithPrevResult(grad, previous_grad, previous_g2, previous_gstep); - calculating_gradient_ = false; -} - -double MinuitFcnGrad::DoDerivative(const double * /*x*/, unsigned int /*icoord*/) const -{ - throw std::runtime_error("MinuitFcnGrad::DoDerivative is not implemented, please use Gradient instead."); + _gradient->fillGradientWithPrevResult(grad, previous_grad, previous_g2, previous_gstep); + _calculatingGradient = false; } bool MinuitFcnGrad::Synchronize(std::vector ¶meters) { bool returnee = synchronizeParameterSettings(parameters, _optConst); - likelihood->synchronizeParameterSettings(parameters); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->synchronizeParameterSettings(parameters); - } - gradient->synchronizeParameterSettings(parameters); + applyToLikelihood([&](auto &l) { l.synchronizeParameterSettings(parameters); }); + _gradient->synchronizeParameterSettings(parameters); - likelihood->synchronizeWithMinimizer(_context->fitter()->Config().MinimizerOptions()); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->synchronizeWithMinimizer(_context->fitter()->Config().MinimizerOptions()); - } - gradient->synchronizeWithMinimizer(_context->fitter()->Config().MinimizerOptions()); + applyToLikelihood([&](auto &l) { l.synchronizeWithMinimizer(_context->fitter()->Config().MinimizerOptions()); }); + _gradient->synchronizeWithMinimizer(_context->fitter()->Config().MinimizerOptions()); return returnee; } diff --git a/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.h b/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.h index 5667c1b6cbddd..a60ea03564565 100644 --- a/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.h +++ b/roofit/roofitcore/src/TestStatistics/MinuitFcnGrad.h @@ -23,84 +23,72 @@ #include #include "Math/IFunction.h" // ROOT::Math::IMultiGradFunction -// forward declaration -class RooAbsReal; class RooMinimizer; namespace RooFit { namespace TestStatistics { -class MinuitFcnGrad : public ROOT::Math::IMultiGradFunction, public RooAbsMinimizerFcn { +class MinuitFcnGrad : public RooAbsMinimizerFcn { public: - MinuitFcnGrad(const std::shared_ptr &_likelihood, RooMinimizer *context, + MinuitFcnGrad(const std::shared_ptr &absL, RooMinimizer *context, std::vector ¶meters, LikelihoodMode likelihoodMode, LikelihoodGradientMode likelihoodGradientMode); - inline ROOT::Math::IMultiGradFunction *Clone() const override { return new MinuitFcnGrad(*this); } - /// Overridden from RooAbsMinimizerFcn to include gradient strategy synchronization. bool Synchronize(std::vector ¶meter_settings) override; // used inside Minuit: - inline bool returnsInMinuit2ParameterSpace() const override { return gradient->usesMinuitInternalValues(); } + inline bool returnsInMinuit2ParameterSpace() const { return _gradient->usesMinuitInternalValues(); } inline void setOptimizeConstOnFunction(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) override { - likelihood->constOptimizeTestStatistic(opcode, doAlsoTrackingOpt); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->constOptimizeTestStatistic(opcode, doAlsoTrackingOpt); - } + applyToLikelihood([&](auto &l) { l.constOptimizeTestStatistic(opcode, doAlsoTrackingOpt); }); } - bool fit(ROOT::Fit::Fitter &fitter) const override { return fitter.FitFCN(*this); }; - ROOT::Math::IMultiGenFunction *getMultiGenFcn() override { return this; }; + ROOT::Math::IMultiGenFunction *getMultiGenFcn() override { return _multiGenFcn.get(); } -private: - /// IMultiGradFunction override necessary for Minuit - double DoEval(const double *x) const override; + double operator()(const double *x) const; -public: /// IMultiGradFunction overrides necessary for Minuit - void Gradient(const double *x, double *grad) const override; + void Gradient(const double *x, double *grad) const; void GradientWithPrevResult(const double *x, double *grad, double *previous_grad, double *previous_g2, - double *previous_gstep) const override; + double *previous_gstep) const; - /// Part of IMultiGradFunction interface, used widely both in Minuit and in RooFit. - inline unsigned int NDim() const override { return _nDim; } + inline std::string getFunctionName() const override { return _likelihood->GetName(); } - inline std::string getFunctionName() const override { return likelihood->GetName(); } - - inline std::string getFunctionTitle() const override { return likelihood->GetTitle(); } + inline std::string getFunctionTitle() const override { return _likelihood->GetTitle(); } inline void setOffsetting(bool flag) override { - likelihood->enableOffsetting(flag); - if (likelihood != likelihood_in_gradient) { - likelihood_in_gradient->enableOffsetting(flag); - } + applyToLikelihood([&](auto &l) { l.enableOffsetting(flag); }); } private: - /// This override should not be used in this class, so it throws. - double DoDerivative(const double *x, unsigned int icoord) const override; - bool syncParameterValuesFromMinuitCalls(const double *x, bool minuit_internal) const; + template + void applyToLikelihood(Func &&func) const + { + func(*_likelihood); + if (_likelihoodInGradient && _likelihood != _likelihoodInGradient) { + func(*_likelihoodInGradient); + } + } + // members - std::shared_ptr likelihood; - std::shared_ptr likelihood_in_gradient; - std::shared_ptr gradient; - mutable bool calculating_gradient_ = false; + std::unique_ptr _likelihood; + std::unique_ptr _likelihoodInGradient; + std::unique_ptr _gradient; + mutable bool _calculatingGradient = false; -public: - mutable std::shared_ptr calculation_is_clean; + mutable std::shared_ptr _calculationIsClean; -private: - mutable std::vector minuit_internal_x_; - mutable std::vector minuit_external_x_; + mutable std::vector _minuitInternalX; + mutable std::vector _minuitExternalX; -public: - mutable bool minuit_internal_roofit_x_mismatch_ = false; + std::unique_ptr _multiGenFcn; + + mutable bool _minuitInternalRooFitXMismatch = false; }; } // namespace TestStatistics diff --git a/roofit/roofitcore/src/TestStatistics/README.md b/roofit/roofitcore/src/TestStatistics/README.md index 30dfe07c34c2a..4a46f79066e69 100644 --- a/roofit/roofitcore/src/TestStatistics/README.md +++ b/roofit/roofitcore/src/TestStatistics/README.md @@ -132,7 +132,7 @@ This applies constant term optimization to the cloned pdf and dataset inside the It will not modify anything outside of the likelihood. Optimization can also be activated through the minimizer, which may be more familiar to most users. -Given the `RooMinimizer` object `m` as definied in the example above, we can do: +Given the `RooMinimizer` object `m` as defined in the example above, we can do: ```c++ m.optimizeConst(2); ``` diff --git a/roofit/roofitcore/src/TestStatistics/RooAbsL.cxx b/roofit/roofitcore/src/TestStatistics/RooAbsL.cxx index 63f4628b13b95..5c474aed5f95d 100644 --- a/roofit/roofitcore/src/TestStatistics/RooAbsL.cxx +++ b/roofit/roofitcore/src/TestStatistics/RooAbsL.cxx @@ -31,7 +31,7 @@ namespace RooFit { namespace TestStatistics { // static function -bool RooAbsL::isExtendedHelper(RooAbsPdf* pdf, Extended extended) +bool RooAbsL::isExtendedHelper(RooAbsPdf *pdf, Extended extended) { switch (extended) { case RooAbsL::Extended::No: { @@ -49,9 +49,10 @@ bool RooAbsL::isExtendedHelper(RooAbsPdf* pdf, Extended extended) } } -/// After handling cloning (or not) of the pdf and dataset, the public constructors call this private constructor to handle common tasks. -RooAbsL::RooAbsL(std::shared_ptr pdf, std::shared_ptr data, - std::size_t N_events, std::size_t N_components, Extended extended) +/// After handling cloning (or not) of the pdf and dataset, the public constructors call this private constructor to +/// handle common tasks. +RooAbsL::RooAbsL(std::shared_ptr pdf, std::shared_ptr data, std::size_t N_events, + std::size_t N_components, Extended extended) : pdf_(std::move(pdf)), data_(std::move(data)), N_events_(N_events), N_components_(N_components) { extended_ = isExtendedHelper(pdf_.get(), extended); @@ -71,33 +72,44 @@ RooAbsL::RooAbsL(std::shared_ptr pdf, std::shared_ptr dat /// \param in Struct containing raw pointers to the pdf and dataset that are to be cloned. /// \param N_events The number of events in this likelihood's dataset. /// \param N_components The number of components in the likelihood. -/// \param extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on the pdf whether to activate or not. +/// \param extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on the +/// pdf whether to activate or not. RooAbsL::RooAbsL(RooAbsL::ClonePdfData in, std::size_t N_events, std::size_t N_components, Extended extended) - : RooAbsL(std::shared_ptr(static_cast(in.pdf->cloneTree())), - std::shared_ptr(static_cast(in.data->Clone())), N_events, N_components, extended) + : RooAbsL(in.ownedPdf ? std::move(in.ownedPdf) + : std::unique_ptr(static_cast(in.pdf->cloneTree())), + std::shared_ptr(static_cast(in.data->Clone())), N_events, N_components, extended) { initClones(*in.pdf, *in.data); } /// Constructor that does not clone pdf/data and uses the shared_ptr aliasing constructor to make it non-owning. /// -/// This constructor is used for classes where a reference to the external pdf/dataset is good enough (RooSumL and RooSubsidiaryL). +/// This constructor is used for classes where a reference to the external pdf/dataset is good enough (RooSumL and +/// RooSubsidiaryL). /// /// \param inpdf Raw pointer to the pdf. /// \param indata Raw pointer to the dataset. /// \param N_events The number of events in this likelihood's dataset. /// \param N_components The number of components in the likelihood. -/// \param extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on the pdf whether to activate or not. +/// \param extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on the +/// pdf whether to activate or not. RooAbsL::RooAbsL(RooAbsPdf *inpdf, RooAbsData *indata, std::size_t N_events, std::size_t N_components, Extended extended) - : RooAbsL({std::shared_ptr(nullptr), inpdf}, {std::shared_ptr(nullptr), indata}, N_events, N_components, extended) -{} - + : RooAbsL({std::shared_ptr(nullptr), inpdf}, {std::shared_ptr(nullptr), indata}, N_events, + N_components, extended) +{ +} RooAbsL::RooAbsL(const RooAbsL &other) - : pdf_(other.pdf_), data_(other.data_), N_events_(other.N_events_), N_components_(other.N_components_), extended_(other.extended_), sim_count_(other.sim_count_) + : pdf_(other.pdf_), + data_(other.data_), + N_events_(other.N_events_), + N_components_(other.N_components_), + extended_(other.extended_), + sim_count_(other.sim_count_) { - // it can never be one, since we just copied the shared_ptr; if it is, something really weird is going on; also they must be equal (usually either zero or two) + // it can never be one, since we just copied the shared_ptr; if it is, something really weird is going on; also they + // must be equal (usually either zero or two) assert((pdf_.use_count() != 1) && (data_.use_count() != 1) && (pdf_.use_count() == data_.use_count())); if ((pdf_.use_count() > 1) && (data_.use_count() > 1)) { pdf_.reset(static_cast(other.pdf_->cloneTree())); @@ -124,14 +136,15 @@ void RooAbsL::initClones(RooAbsPdf &inpdf, RooAbsData &indata) pdf_->recursiveRedirectServers(*origParams); // Store normalization set - normSet_.reset((RooArgSet *)indata.get()->snapshot(false)); + normSet_ = std::make_unique(); + indata.get()->snapshot(*normSet_, false); // Expand list of observables with any observables used in parameterized ranges for (const auto realDep : *_funcObsSet) { auto realDepRLV = dynamic_cast(realDep); if (realDepRLV && realDepRLV->isDerived()) { RooArgSet tmp2; - realDepRLV->leafNodeServerList(&tmp2, 0, true); + realDepRLV->leafNodeServerList(&tmp2, nullptr, true); _funcObsSet->add(tmp2, true); } } @@ -158,8 +171,8 @@ void RooAbsL::initClones(RooAbsPdf &inpdf, RooAbsData &indata) if (!realReal->getBinning().lowBoundFunc() && realReal->getMin() < (datReal->getMin() - 1e-6)) { oocoutE(nullptr, InputArguments) << "RooAbsL: ERROR minimum of FUNC observable " << arg->GetName() << "(" - << realReal->getMin() << ") is smaller than that of " << arg->GetName() - << " in the dataset (" << datReal->getMin() << ")" << std::endl; + << realReal->getMin() << ") is smaller than that of " << arg->GetName() + << " in the dataset (" << datReal->getMin() << ")" << std::endl; RooErrorHandler::softAbort(); return; } @@ -180,16 +193,16 @@ void RooAbsL::initClones(RooAbsPdf &inpdf, RooAbsData &indata) // TODO // Jonas R.: The following code is commented out, because the functionality - // to mask out-ot-range entries with `RooDataHist::cacheValidEntries` has + // to mask out-of-range entries with `RooDataHist::cacheValidEntries` has // been removed from the RooDataHist. If you want to implement ranged fits // properly, please create a RooDataHist for the requested range with // `RooDataHist::reduce`. //// If dataset is binned, activate caching of bins that are invalid because they're outside the //// updated range definition (WVE need to add virtual interface here) - //RooDataHist *tmph = dynamic_cast(data_.get()); - //if (tmph) { - //tmph->cacheValidEntries(); + // RooDataHist *tmph = dynamic_cast(data_.get()); + // if (tmph) { + // tmph->cacheValidEntries(); //} // This is deferred from part 2 - but must happen after part 3 - otherwise invalid bins cannot be properly marked in @@ -218,17 +231,17 @@ void RooAbsL::initClones(RooAbsPdf &inpdf, RooAbsData &indata) data_->optimizeReadingWithCaching(*pdf_, RooArgSet(), RooArgSet()); } -RooArgSet *RooAbsL::getParameters() +std::unique_ptr RooAbsL::getParameters() { - auto ding = pdf_->getParameters(*data_); - return ding; + return std::unique_ptr{pdf_->getParameters(*data_)}; } void RooAbsL::constOptimizeTestStatistic(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) { // to be further implemented, this is just a first test implementation if (opcode == RooAbsArg::Activate) { - ConstantTermsOptimizer::enableConstantTermsOptimization(pdf_.get(), normSet_.get(), data_.get(), doAlsoTrackingOpt); + ConstantTermsOptimizer::enableConstantTermsOptimization(pdf_.get(), normSet_.get(), data_.get(), + doAlsoTrackingOpt); } } diff --git a/roofit/roofitcore/src/TestStatistics/RooBinnedL.cxx b/roofit/roofitcore/src/TestStatistics/RooBinnedL.cxx index 94cf84810978b..7336355833341 100644 --- a/roofit/roofitcore/src/TestStatistics/RooBinnedL.cxx +++ b/roofit/roofitcore/src/TestStatistics/RooBinnedL.cxx @@ -94,7 +94,7 @@ RooBinnedL::evaluatePartition(Section bins, std::size_t /*components_begin*/, st ROOT::Math::KahanSum result; // Do not reevaluate likelihood if parameters nor event range have changed - if (!paramTracker_->hasChanged(true) && bins == lastSection_ && (cachedResult_ != 0)) return cachedResult_; + if (!paramTracker_->hasChanged(true) && bins == lastSection_ && (cachedResult_.Sum() != 0 || cachedResult_.Carry() != 0)) return cachedResult_; // data->store()->recalculateCache(_projDeps, firstEvent, lastEvent, stepSize, (_binnedPdf?false:true)); // TODO: check when we might need _projDeps (it seems to be mostly empty); ties in with TODO below @@ -120,7 +120,7 @@ RooBinnedL::evaluatePartition(Section bins, std::size_t /*components_begin*/, st oocoutI(nullptr, Minimization) << "Observed " << N << " events in bin " << i << " with zero event yield" << std::endl; - } else if (fabs(mu) < 1e-10 && fabs(N) < 1e-10) { + } else if (std::abs(mu) < 1e-10 && std::abs(N) < 1e-10) { // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula // since log(mu)=0. No update of result is required since term=0. @@ -137,7 +137,7 @@ RooBinnedL::evaluatePartition(Section bins, std::size_t /*components_begin*/, st // If part of simultaneous PDF normalize probability over // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n) if (sim_count_ > 1) { - result += sumWeight * log(1.0 * sim_count_); + result += sumWeight.Sum() * log(1.0 * sim_count_); } // At the end of the first full calculation, wire the caches diff --git a/roofit/roofitcore/src/TestStatistics/RooRealL.cxx b/roofit/roofitcore/src/TestStatistics/RooRealL.cxx index ac9d22314e27a..4aa0499d1dab4 100644 --- a/roofit/roofitcore/src/TestStatistics/RooRealL.cxx +++ b/roofit/roofitcore/src/TestStatistics/RooRealL.cxx @@ -31,8 +31,9 @@ RooRealL::RooRealL(const char *name, const char *title, std::shared_ptr : RooAbsReal(name, title), likelihood_(std::move(likelihood)), vars_proxy_("varsProxy", "proxy set of parameters", this) { - vars_obs_.add(*likelihood_->getParameters()); - vars_proxy_.add(*likelihood_->getParameters()); + std::unique_ptr params{likelihood_->getParameters()}; + vars_obs_.add(*params); + vars_proxy_.add(*params); } RooRealL::RooRealL(const RooRealL &other, const char *name) diff --git a/roofit/roofitcore/src/TestStatistics/RooSumL.cxx b/roofit/roofitcore/src/TestStatistics/RooSumL.cxx index 8f7be9581c76a..a72880a71efbd 100644 --- a/roofit/roofitcore/src/TestStatistics/RooSumL.cxx +++ b/roofit/roofitcore/src/TestStatistics/RooSumL.cxx @@ -117,7 +117,7 @@ ROOT::Math::KahanSum RooSumL::getSubsidiaryValue() return (*component)->evaluatePartition({0, 1}, 0, 0); } } - return {}; + return ROOT::Math::KahanSum{}; } void RooSumL::constOptimizeTestStatistic(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt) diff --git a/roofit/roofitcore/src/TestStatistics/RooUnbinnedL.cxx b/roofit/roofitcore/src/TestStatistics/RooUnbinnedL.cxx index 973abac4da559..f58db72c35885 100644 --- a/roofit/roofitcore/src/TestStatistics/RooUnbinnedL.cxx +++ b/roofit/roofitcore/src/TestStatistics/RooUnbinnedL.cxx @@ -26,29 +26,59 @@ In extended mode, a #include -#include "RooAbsData.h" -#include "RooAbsPdf.h" -#include "RooAbsDataStore.h" -#include "RooNLLVar.h" // RooNLLVar::ComputeScalar -#include "RunContext.h" -#include "RooChangeTracker.h" +#include +#include +#include +#include // RooNLLVar::ComputeScalar +#include +#include +#include + +#include "../RooFit/BatchModeDataHelpers.h" namespace RooFit { namespace TestStatistics { +namespace { + +RooAbsL::ClonePdfData clonePdfData(RooAbsPdf &pdf, RooAbsData &data, RooFit::EvalBackend evalBackend) +{ + if (evalBackend.value() == RooFit::EvalBackend::Value::Legacy) { + return {&pdf, &data}; + } + // For the evaluation with the BatchMode, the pdf needs to be "compiled" for + // a given normalization set. + return {RooFit::Detail::compileForNormSet(pdf, *data.get()), &data}; +} + +} // namespace + RooUnbinnedL::RooUnbinnedL(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended extended, - bool useBatchedEvaluations) - : RooAbsL(RooAbsL::ClonePdfData{pdf, data}, data->numEntries(), 1, extended), - useBatchedEvaluations_(useBatchedEvaluations) + RooFit::EvalBackend evalBackend) + : RooAbsL(clonePdfData(*pdf, *data, evalBackend), data->numEntries(), 1, extended) { std::unique_ptr params(pdf->getParameters(data)); - paramTracker_ = std::make_unique("chtracker","change tracker",*params,true); + paramTracker_ = std::make_unique("chtracker", "change tracker", *params, true); + + if (evalBackend.value() != RooFit::EvalBackend::Value::Legacy) { + evaluator_ = std::make_unique(*pdf_, evalBackend.value() == RooFit::EvalBackend::Value::Cuda); + std::stack>{}.swap(_vectorBuffers); + auto dataSpans = + RooFit::BatchModeDataHelpers::getDataSpans(*data, "", nullptr, /*skipZeroWeights=*/true, + /*takeGlobalObservablesFromData=*/false, _vectorBuffers); + for (auto const &item : dataSpans) { + evaluator_->setInput(item.first->GetName(), item.second, false); + } + } } RooUnbinnedL::RooUnbinnedL(const RooUnbinnedL &other) - : RooAbsL(other), apply_weight_squared(other.apply_weight_squared), _first(other._first), - useBatchedEvaluations_(other.useBatchedEvaluations_), lastSection_(other.lastSection_), - cachedResult_(other.cachedResult_) + : RooAbsL(other), + apply_weight_squared(other.apply_weight_squared), + _first(other._first), + lastSection_(other.lastSection_), + cachedResult_(other.cachedResult_), + evaluator_(other.evaluator_) { paramTracker_ = std::make_unique(*other.paramTracker_); } @@ -68,10 +98,44 @@ bool RooUnbinnedL::setApplyWeightSquared(bool flag) return false; } -void RooUnbinnedL::setUseBatchedEvaluations(bool flag) { - useBatchedEvaluations_ = flag; +namespace { + +// For now, almost exact copy of RooNLLVar::computeScalarFunc. +RooNLLVar::ComputeResult computeBatchFunc(std::span probas, RooAbsData *dataClone, bool weightSq, + std::size_t stepSize, std::size_t firstEvent, std::size_t lastEvent) +{ + ROOT::Math::KahanSum kahanWeight; + ROOT::Math::KahanSum kahanProb; + RooNaNPacker packedNaN(0.f); + + for (auto i = firstEvent; i < lastEvent; i += stepSize) { + dataClone->get(i); + + double weight = dataClone->weight(); + + if (0. == weight * weight) + continue; + if (weightSq) + weight = dataClone->weightSquared(); + + double logProba = std::log(probas[i]); + const double term = -weight * logProba; + + kahanWeight.Add(weight); + kahanProb.Add(term); + packedNaN.accumulate(term); + } + + if (packedNaN.getPayload() != 0.) { + // Some events with evaluation errors. Return "badness" of errors. + return {ROOT::Math::KahanSum{packedNaN.getNaNWithPayload()}, kahanWeight.Sum()}; + } + + return {kahanProb, kahanWeight.Sum()}; } +} // namespace + ////////////////////////////////////////////////////////////////////////////////// /// Calculate and return likelihood on subset of data from firstEvent to lastEvent /// processed with a step size of 'stepSize'. If this an extended likelihood and @@ -89,17 +153,21 @@ RooUnbinnedL::evaluatePartition(Section events, std::size_t /*components_begin*/ double sumWeight; // Do not reevaluate likelihood if parameters nor event range have changed - if (!paramTracker_->hasChanged(true) && events == lastSection_ && (cachedResult_ != 0)) return cachedResult_; - - data_->store()->recalculateCache(nullptr, events.begin(N_events_), events.end(N_events_), 1, true); - - if (useBatchedEvaluations_) { - std::unique_ptr evalData; - std::tie(result, sumWeight) = RooNLLVar::computeBatchedFunc(pdf_.get(), data_.get(), evalData, normSet_.get(), apply_weight_squared, - 1, events.begin(N_events_), events.end(N_events_)); + if (!paramTracker_->hasChanged(true) && events == lastSection_ && + (cachedResult_.Sum() != 0 || cachedResult_.Carry() != 0)) + return cachedResult_; + + if (evaluator_) { + // Here, we have a memory allocation that should be avoided when this + // code needs to be optimized. + std::span probas = evaluator_->run(); + std::tie(result, sumWeight) = + computeBatchFunc(probas, data_.get(), apply_weight_squared, 1, events.begin(N_events_), events.end(N_events_)); } else { - std::tie(result, sumWeight) = RooNLLVar::computeScalarFunc(pdf_.get(), data_.get(), normSet_.get(), apply_weight_squared, - 1, events.begin(N_events_), events.end(N_events_)); + data_->store()->recalculateCache(nullptr, events.begin(N_events_), events.end(N_events_), 1, true); + std::tie(result, sumWeight) = + RooNLLVar::computeScalarFunc(pdf_.get(), data_.get(), normSet_.get(), apply_weight_squared, 1, + events.begin(N_events_), events.end(N_events_)); } // include the extended maximum likelihood term, if requested @@ -113,8 +181,9 @@ RooUnbinnedL::evaluatePartition(Section events, std::size_t /*components_begin*/ result += sumWeight * log(1.0 * sim_count_); } - // At the end of the first full calculation, wire the caches - if (_first) { + // At the end of the first full calculation, wire the caches. This doesn't + // need to be done in BatchMode with the RooFit driver. + if (_first && !evaluator_) { _first = false; pdf_->wireAllCaches(); } diff --git a/roofit/roofitcore/src/TestStatistics/buildLikelihood.cxx b/roofit/roofitcore/src/TestStatistics/buildLikelihood.cxx index 161483422d0a5..2524e5f7e6ef8 100644 --- a/roofit/roofitcore/src/TestStatistics/buildLikelihood.cxx +++ b/roofit/roofitcore/src/TestStatistics/buildLikelihood.cxx @@ -53,11 +53,11 @@ namespace RooFit { */ namespace TestStatistics { -namespace { // private implementation details +namespace { // private implementation details -RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constrained_parameters, - ExternalConstraints external_constraints, GlobalObservables global_observables, - std::string global_observables_tag) +RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, RooArgSet constrained_parameters, + RooArgSet const &external_constraints, RooArgSet global_observables, + std::string const &global_observables_tag) { // BEGIN CONSTRAINT COLLECTION; copied from RooAbsPdf::createNLL @@ -69,9 +69,9 @@ RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParamet bool did_default_constraint_algo = false; std::size_t N_default_constraints = 0; #endif - if (constrained_parameters.set.empty()) { + if (constrained_parameters.empty()) { std::unique_ptr default_constraints{pdf->getParameters(*data, false)}; - constrained_parameters.set.add(*default_constraints); + constrained_parameters.add(*default_constraints); doStripDisconnected = true; #ifndef NDEBUG did_default_constraint_algo = true; @@ -80,7 +80,7 @@ RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParamet } #ifndef NDEBUG if (did_default_constraint_algo) { - assert(N_default_constraints == static_cast(constrained_parameters.set.getSize())); + assert(N_default_constraints == static_cast(constrained_parameters.getSize())); } #endif @@ -88,16 +88,14 @@ RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParamet RooArgSet allConstraints; if (!global_observables_tag.empty()) { - if (!global_observables.set.empty()) { - global_observables.set.removeAll(); + if (!global_observables.empty()) { + global_observables.removeAll(); } std::unique_ptr allVars{pdf->getVariables()}; - global_observables.set.add( - *dynamic_cast(allVars->selectByAttrib(global_observables_tag.c_str(), true))); - oocoutI(nullptr, Minimization) - << "User-defined specification of global observables definition with tag named '" << global_observables_tag - << "'" << std::endl; - } else if (global_observables.set.empty()) { + global_observables.add(*dynamic_cast(allVars->selectByAttrib(global_observables_tag.c_str(), true))); + oocoutI(nullptr, Minimization) << "User-defined specification of global observables definition with tag named '" + << global_observables_tag << "'" << std::endl; + } else if (global_observables.empty()) { // neither global_observables nor global_observables_tag was given - try if a default tag is defined in the head // node const char *defGlobObsTag = pdf->getStringAttribute("DefaultGlobalObservablesTag"); @@ -106,19 +104,19 @@ RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParamet << "p.d.f. provides built-in specification of global observables definition with tag named '" << defGlobObsTag << "'" << std::endl; std::unique_ptr allVars{pdf->getVariables()}; - global_observables.set.add(*dynamic_cast(allVars->selectByAttrib(defGlobObsTag, true))); + global_observables.add(*dynamic_cast(allVars->selectByAttrib(defGlobObsTag, true))); } } // EGP: removed workspace (RooAbsPdf::_myws) based stuff for now; TODO: reconnect this class to workspaces - if (!constrained_parameters.set.empty()) { + if (!constrained_parameters.empty()) { std::unique_ptr constraints{ - pdf->getAllConstraints(*data->get(), constrained_parameters.set, doStripDisconnected)}; + pdf->getAllConstraints(*data->get(), constrained_parameters, doStripDisconnected)}; allConstraints.add(*constraints); } - if (!external_constraints.set.empty()) { - allConstraints.add(external_constraints.set); + if (!external_constraints.empty()) { + allConstraints.add(external_constraints); } return allConstraints; @@ -143,10 +141,9 @@ RooArgSet getConstraintsSet(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParamet * \return A unique pointer to a RooSubsidiaryL that contains all terms in the pdf that can be * calculated separately from the other components in the full likelihood. */ -std::unique_ptr -buildSubsidiaryL(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constrained_parameters, - ExternalConstraints external_constraints, GlobalObservables global_observables, - std::string global_observables_tag) +std::unique_ptr buildSubsidiaryL(RooAbsPdf *pdf, RooAbsData *data, RooArgSet constrained_parameters, + RooArgSet const &external_constraints, RooArgSet global_observables, + std::string const &global_observables_tag) { auto allConstraints = getConstraintsSet(pdf, data, constrained_parameters, external_constraints, global_observables, global_observables_tag); @@ -155,28 +152,21 @@ buildSubsidiaryL(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constra // Include constraints, if any, in likelihood if (!allConstraints.empty()) { - oocoutI(nullptr, Minimization) - << " Including the following contraint terms in minimization: " << allConstraints << std::endl; - if (!global_observables.set.empty()) { - oocoutI(nullptr, Minimization) - << "The following global observables have been defined: " << global_observables.set << std::endl; + oocoutI(nullptr, Minimization) << " Including the following constraint terms in minimization: " << allConstraints + << std::endl; + if (!global_observables.empty()) { + oocoutI(nullptr, Minimization) << "The following global observables have been defined: " << global_observables + << std::endl; } std::string name("likelihood for pdf "); name += pdf->GetName(); subsidiary_likelihood = std::make_unique( - name, allConstraints, - (!global_observables.set.empty()) ? global_observables.set : constrained_parameters.set); + name, allConstraints, (!global_observables.empty()) ? global_observables : constrained_parameters); } return subsidiary_likelihood; } -bool isSimultaneous(RooAbsPdf *pdf) -{ - auto sim_pdf = dynamic_cast(pdf); - return sim_pdf != nullptr; -} - /// Get the binned part of a pdf /// /// \param pdf Raw pointer to the pdf @@ -203,34 +193,31 @@ RooAbsPdf *getBinnedPdf(RooAbsPdf *pdf) return binnedPdf; } +} // namespace + /* - * \brief Build a set of likelihood components to build a likelihood from a simultaneous pdf + * \brief Build a set of likelihood components to build a likelihood from a simultaneous pdf. * - * \param[in] pdf Raw pointer to the pdf - * \param[in] data Raw pointer to the dataset - * \param[in] extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on - * the pdf whether to activate or not. * \return A vector to RooAbsL unique_ptrs that contain all component binned and/or * unbinned likelihoods. Note: subsidiary components are not included; use getConstraintsSet and/or * buildSubsidiaryLikelihood to add those. */ -std::vector> -getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended extended) +std::vector> NLLFactory::getSimultaneousComponents() { - auto sim_pdf = dynamic_cast(pdf); + auto sim_pdf = dynamic_cast(&_pdf); // the rest of this function is an adaptation of RooAbsTestStatistic::initSimMode: - RooAbsCategoryLValue &simCat = (RooAbsCategoryLValue &)sim_pdf->indexCat(); + auto &simCat = const_cast(sim_pdf->indexCat()); // note: this is valid for simultaneous likelihoods, not for other test statistic types (e.g. chi2) for which this // should return true. - bool process_empty_data_sets = RooAbsL::isExtendedHelper(pdf, extended); + bool process_empty_data_sets = RooAbsL::isExtendedHelper(&_pdf, _extended); TString simCatName(simCat.GetName()); // Note: important not to use cloned dataset here (possible when this code is run in Roo[...]L ctor), use the // original one (which is data_ in Roo[...]L ctors, but data here) - std::unique_ptr dsetList{data->split(*sim_pdf, process_empty_data_sets)}; + std::unique_ptr dsetList{_data.split(*sim_pdf, process_empty_data_sets)}; if (!dsetList) { throw std::logic_error( "getSimultaneousComponents ERROR, index category of simultaneous pdf is missing in dataset, aborting"); @@ -242,7 +229,7 @@ getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended ex for (const auto &catState : simCat) { // Retrieve the PDF for this simCat state RooAbsPdf *component_pdf = sim_pdf->getPdf(catState.first.c_str()); - auto dset = (RooAbsData *)dsetList->FindObject(catState.first.c_str()); + auto *dset = static_cast(dsetList->FindObject(catState.first.c_str())); if (component_pdf && dset && (0. != dset->sumEntries() || process_empty_data_sets)) { ++N_components; @@ -260,12 +247,11 @@ getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended ex const std::string &catName = catState.first; // Retrieve the PDF for this simCat state RooAbsPdf *component_pdf = sim_pdf->getPdf(catName.c_str()); - auto dset = (RooAbsData *)dsetList->FindObject(catName.c_str()); + auto *dset = static_cast(dsetList->FindObject(catName.c_str())); if (component_pdf && dset && (0. != dset->sumEntries() || process_empty_data_sets)) { - ooccoutI((TObject *)nullptr, Fitting) - << "getSimultaneousComponents: creating slave calculator #" << n << " for state " << catName << " (" - << dset->numEntries() << " dataset entries)" << std::endl; + ooccoutI(nullptr, Fitting) << "getSimultaneousComponents: creating slave calculator #" << n << " for state " + << catName << " (" << dset->numEntries() << " dataset entries)" << std::endl; RooAbsPdf *binnedPdf = getBinnedPdf(component_pdf); bool binnedL = (binnedPdf != nullptr); @@ -285,7 +271,8 @@ getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended ex if (binnedL) { components.push_back(std::make_unique((binnedPdf ? binnedPdf : component_pdf), dset)); } else { - components.push_back(std::make_unique((binnedPdf ? binnedPdf : component_pdf), dset)); + components.push_back( + std::make_unique((binnedPdf ? binnedPdf : component_pdf), dset, _extended, _evalBackend)); } // } components.back()->setSimCount(N_components); @@ -294,30 +281,33 @@ getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended ex std::unique_ptr actualParams{binnedPdf ? binnedPdf->getParameters(dset) : component_pdf->getParameters(dset)}; - std::unique_ptr selTargetParams{ - (RooArgSet *)pdf->getParameters(*data)->selectCommon(*actualParams)}; + RooArgSet params; + _pdf.getParameters(_data.get(), params); + RooArgSet selTargetParams; + params.selectCommon(*actualParams, selTargetParams); - assert(selTargetParams->equals(*components.back()->getParameters())); + assert(selTargetParams.equals(*components.back()->getParameters())); ++n; } else { if ((!dset || (0. != dset->sumEntries() && !process_empty_data_sets)) && component_pdf) { - ooccoutD((TObject *)nullptr, Fitting) << "getSimultaneousComponents: state " << catName - << " has no data entries, no slave calculator created" << std::endl; + ooccoutD(nullptr, Fitting) << "getSimultaneousComponents: state " << catName + << " has no data entries, no slave calculator created" << std::endl; } } } - oocoutI(nullptr, Fitting) << "getSimultaneousComponents: created " << n << " slave calculators." - << std::endl; + oocoutI(nullptr, Fitting) << "getSimultaneousComponents: created " << n << " slave calculators." << std::endl; return components; } -} // anonymous namespace with private implementation details - +/// Create a likelihood builder for a given pdf and dataset. +/// \param[in] pdf Raw pointer to the pdf +/// \param[in] data Raw pointer to the dataset +NLLFactory::NLLFactory(RooAbsPdf &pdf, RooAbsData &data) : _pdf{pdf}, _data{data} {} /* - * \brief Build a likelihood from a pdf + dataset, optionally with a subsidiary likelihood component + * \brief Build a likelihood from a pdf + dataset, optionally with a subsidiary likelihood component. * * This function analyzes the pdf and automatically constructs the proper likelihood, built up from the available * RooAbsL subclasses. In essence, this can give 8 conceptually different combinations, based on three questions: @@ -328,80 +318,89 @@ getSimultaneousComponents(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended ex * other cases it returns a RooSumL, which will contain RooBinnedL and/or RooUnbinnedL component(s) and possibly a * RooSubsidiaryL component with constraint terms. * - * \param[in] pdf Raw pointer to the pdf - * \param[in] data Raw pointer to the dataset - * \param[in] extended Set extended term calculation on, off or use Extended::Auto to determine automatically based on - * the pdf whether to activate or not. - * \param[in] constrained_parameters Set of parameters that are constrained. Pdf components dependent on these alone are - * added to the subsidiary likelihood. - * \param[in] external_constraints Set of external constraint pdfs, i.e. constraints - * not necessarily in the pdf itself. These are always added to the subsidiary likelihood. - * \param[in] global_observables - * Observables that have a constant value, independent of the dataset events. Pdf components dependent on these alone - * are added to the subsidiary likelihood. \note Overrides all other likelihood parameters (like those in \p - * constrained_parameters) if present. - * \param[in] global_observables_tag String that can be set as attribute in pdf - * components to indicate that it is a global observable. Can be used instead of or in addition to \p - * global_observables. * \return A unique pointer to a RooSubsidiaryL that contains all terms in * the pdf that can be calculated separately from the other components in the full likelihood. */ -std::unique_ptr buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, RooAbsL::Extended extended, - ConstrainedParameters constrained_parameters, - ExternalConstraints external_constraints, GlobalObservables global_observables, - std::string global_observables_tag) +std::unique_ptr NLLFactory::build() { std::unique_ptr likelihood; std::vector> components; - if (isSimultaneous(pdf)) { - components = getSimultaneousComponents(pdf, data, extended); - } else if (auto binnedPdf = getBinnedPdf(pdf)) { - likelihood = std::make_unique(binnedPdf, data); + if (dynamic_cast(&_pdf)) { + components = getSimultaneousComponents(); + } else if (auto binnedPdf = getBinnedPdf(&_pdf)) { + likelihood = std::make_unique(binnedPdf, &_data); } else { // unbinned - likelihood = std::make_unique(pdf, data, extended); + likelihood = std::make_unique(&_pdf, &_data, _extended, _evalBackend); } - auto subsidiary = buildSubsidiaryL(pdf, data, constrained_parameters, external_constraints, global_observables, global_observables_tag); + auto subsidiary = buildSubsidiaryL(&_pdf, &_data, _constrainedParameters, _externalConstraints, _globalObservables, + _globalObservablesTag); if (subsidiary) { if (likelihood) { components.push_back(std::move(likelihood)); } components.push_back(std::move(subsidiary)); } - if (components.size() > 0) { - likelihood = std::make_unique(pdf, data, std::move(components), extended); + if (!components.empty()) { + likelihood = std::make_unique(&_pdf, &_data, std::move(components), _extended); } return likelihood; } -// delegating convenience overloads -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constrained_parameters) +/// \param[in] extended Set extended term calculation on, off or use +/// RooAbsL::Extended::Auto to determine automatically based on the +/// pdf whether to activate or not. +NLLFactory &NLLFactory::Extended(RooAbsL::Extended extended) { - return buildLikelihood(pdf, data, RooAbsL::Extended::Auto, constrained_parameters); + _extended = extended; + return *this; } -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, ExternalConstraints external_constraints) + +/// \param[in] constrainedParameters Set of parameters that are constrained. +/// Pdf components dependent on these alone are added to the +/// subsidiary likelihood. +NLLFactory &NLLFactory::ConstrainedParameters(const RooArgSet &constrainedParameters) { - return buildLikelihood(pdf, data, RooAbsL::Extended::Auto, {}, external_constraints); + _constrainedParameters.add(constrainedParameters); + return *this; } -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, GlobalObservables global_observables) + +/// \param[in] externalConstraints Set of external constraint pdfs, i.e. +/// constraints not necessarily in the pdf itself. These are always +/// added to the subsidiary likelihood. +NLLFactory &NLLFactory::ExternalConstraints(const RooArgSet &externalConstraints) { - return buildLikelihood(pdf, data, RooAbsL::Extended::Auto, {}, {}, global_observables); + _externalConstraints.add(externalConstraints); + return *this; } -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, std::string global_observables_tag) + +/// \param[in] globalObservables Observables that have a constant value, +/// independent of the dataset events. Pdf components dependent on +/// these alone are added to the subsidiary likelihood. +/// \note Overrides all other likelihood parameters (like those in +/// NLLFactory::ConstrainedParameters()) if present. +NLLFactory &NLLFactory::GlobalObservables(const RooArgSet &globalObservables) { - return buildLikelihood(pdf, data, RooAbsL::Extended::Auto, {}, {}, {}, global_observables_tag); + _globalObservables.add(globalObservables); + return *this; } -std::unique_ptr -buildLikelihood(RooAbsPdf *pdf, RooAbsData *data, ConstrainedParameters constrained_parameters, GlobalObservables global_observables) + +/// \param[in] globalObservablesTag String that can be set as attribute in +/// pdf components to indicate that it is a global observable. Can +/// be used instead of or in addition to +/// NLLFactory::GlobalObservables(). +NLLFactory &NLLFactory::GlobalObservablesTag(const char *globalObservablesTag) { - return buildLikelihood(pdf, data, RooAbsL::Extended::Auto, constrained_parameters, {}, global_observables); + _globalObservablesTag = globalObservablesTag; + return *this; } +NLLFactory &NLLFactory::EvalBackend(RooFit::EvalBackend evalBackend) +{ + _evalBackend = evalBackend; + return *this; +} } // namespace TestStatistics } // namespace RooFit diff --git a/roofit/roofitcore/src/TestStatistics/optional_parameter_types.cxx b/roofit/roofitcore/src/TestStatistics/optional_parameter_types.cxx deleted file mode 100644 index 7e3dc0a362012..0000000000000 --- a/roofit/roofitcore/src/TestStatistics/optional_parameter_types.cxx +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Project: RooFit - * Authors: - * PB, Patrick Bos, Netherlands eScience Center, p.bos@esciencecenter.nl - * - * Copyright (c) 2021, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#include - -namespace RooFit { -namespace TestStatistics { - -ConstrainedParameters::ConstrainedParameters(const RooArgSet ¶meters) : set(parameters) {} -// N.B.: the default constructor must be _user-provided_ defaulted, otherwise aggregate initialization will be possible, -// which bypasses the explicit constructor and even leads to errors in some compilers; when initializing as -// ConstrainedParameters({someRooArgSet}) -// compilers can respond with -// call of overloaded ‘GlobalObservables()’ is ambiguous -// This problem is well documented in http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1008r0.pdf. The solution -// used here is detailed in section 1.4 of that paper. Note that in C++17, the workaround is no longer necessary and -// the constructor can be _user-declared_ default (i.e. directly in the declaration above). -ConstrainedParameters::ConstrainedParameters() = default; - -ExternalConstraints::ExternalConstraints(const RooArgSet &constraints) : set(constraints) {} -ExternalConstraints::ExternalConstraints() = default; - -GlobalObservables::GlobalObservables(const RooArgSet &observables) : set(observables) {} -GlobalObservables::GlobalObservables() = default; - -} -} diff --git a/roofit/roofitcore/test/CMakeLists.txt b/roofit/roofitcore/test/CMakeLists.txt index 3f5de541e8847..05589d450975f 100644 --- a/roofit/roofitcore/test/CMakeLists.txt +++ b/roofit/roofitcore/test/CMakeLists.txt @@ -7,7 +7,7 @@ # @author Danilo Piparo CERN, 2018 # @author Patrick Bos, NL eScience Center, 2018 -ROOT_ADD_GTEST(simple simple.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testSimple testSimple.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooAddPdf testRooAddPdf.cxx LIBRARIES RooFitCore RooStats) ROOT_ADD_GTEST(testRooCacheManager testRooCacheManager.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooCategory testRooCategory.cxx LIBRARIES RooFitCore) @@ -19,9 +19,10 @@ ROOT_ADD_GTEST(testRooDataHist testRooDataHist.cxx LIBRARIES RooFitCore ROOT_ADD_GTEST(testRooBinSamplingPdf testRooBinSamplingPdf.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooWrapperPdf testRooWrapperPdf.cxx LIBRARIES Gpad RooFitCore) ROOT_ADD_GTEST(testGenericPdf testGenericPdf.cxx LIBRARIES RooFitCore) -ROOT_ADD_GTEST(testRooAbsPdf testRooAbsPdf.cxx LIBRARIES RooFitCore RooFit) +ROOT_ADD_GTEST(testRooAbsPdf testRooAbsPdf.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooAbsCollection testRooAbsCollection.cxx LIBRARIES RooFitCore) -ROOT_ADD_GTEST(testRooDataSet testRooDataSet.cxx LIBRARIES Tree RooFitCore) +ROOT_ADD_GTEST(testRooDataSet testRooDataSet.cxx LIBRARIES Tree RooFitCore + COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/dataSet_with_errors_6_26_10.root) ROOT_ADD_GTEST(testRooFormula testRooFormula.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooProdPdf testRooProdPdf.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testProxiesAndCategories testProxiesAndCategories.cxx @@ -41,29 +42,34 @@ ROOT_ADD_GTEST(testRooRealVar testRooRealVar.cxx LIBRARIES RooFitCore LIBRARIES RooFitCore COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/testRooAbsReal_1.root ${CMAKE_CURRENT_SOURCE_DIR}/testRooAbsReal_2.root) if(NOT MSVC OR win_broken_tests) - # Dsiabled on Windows because it causes the following error: + # Disabled on Windows because it causes the following error: # unknown file: error: SEH exception with code 0xc0000005 thrown in the test body. # According to the internet, this has to do with gtest, so it's not a RooFit problem ROOT_ADD_GTEST(testRooRealIntegral testRooRealIntegral.cxx LIBRARIES RooFitCore) - - ROOT_ADD_GTEST(testTestStatistics testTestStatistics.cxx LIBRARIES RooFitCore RooFit) + if(clad) + # Test disabled on windows due to an issue with cling symbols. + ROOT_ADD_GTEST(testRooFuncWrapper testRooFuncWrapper.cxx LIBRARIES RooFitCore RooFit HistFactory) + endif() + ROOT_ADD_GTEST(testTestStatistics testTestStatistics.cxx LIBRARIES RooFitCore) endif() ROOT_ADD_GTEST(testNaNPacker testNaNPacker.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooSimultaneous testRooSimultaneous.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooSTLRefCountList testRooSTLRefCountList.cxx LIBRARIES RooFitCore) -ROOT_ADD_GTEST(testLikelihoodSerial TestStatistics/testLikelihoodSerial.cxx LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testRooAbsL TestStatistics/testRooAbsL.cxx LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testRooRealL TestStatistics/RooRealL.cpp LIBRARIES RooFitCore RooFit) -ROOT_ADD_GTEST(testInterface TestStatistics/testInterface.cpp LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testLikelihoodSerial TestStatistics/testLikelihoodSerial.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testRooAbsL TestStatistics/testRooAbsL.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testRooRealL TestStatistics/testRooRealL.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testInterface TestStatistics/testInterface.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testGlobalObservables testGlobalObservables.cxx LIBRARIES RooFitCore) ROOT_ADD_GTEST(testRooPolyFunc testRooPolyFunc.cxx LIBRARIES Gpad RooFitCore) ROOT_ADD_GTEST(testSumW2Error testSumW2Error.cxx LIBRARIES Gpad RooFitCore) ROOT_ADD_GTEST(testRooHist testRooHist.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testRooHistPdf testRooHistPdf.cxx LIBRARIES RooFitCore) +ROOT_ADD_GTEST(testRooRombergIntegrator testRooRombergIntegrator.cxx LIBRARIES MathCore RooFitCore) if (roofit_multiprocess) - ROOT_ADD_GTEST(testTestStatisticsPlot TestStatistics/testPlot.cpp LIBRARIES RooFitMultiProcess RooFitCore RooFit + ROOT_ADD_GTEST(testTestStatisticsPlot TestStatistics/testPlot.cxx LIBRARIES RooFitMultiProcess RooFitCore RooFit COPY_TO_BUILDDIR ${CMAKE_CURRENT_SOURCE_DIR}/TestStatistics/TestStatistics_ref.root) - ROOT_ADD_GTEST(testLikelihoodGradientJob TestStatistics/testLikelihoodGradientJob.cpp LIBRARIES RooFitMultiProcess RooFitCore RooFit RooStats m) + ROOT_ADD_GTEST(testLikelihoodGradientJob TestStatistics/testLikelihoodGradientJob.cxx LIBRARIES RooFitMultiProcess RooFitCore m) target_include_directories(testLikelihoodGradientJob PRIVATE ${RooFitCore_MultiProcess_TestStatistics_INCLUDE_DIR}) - ROOT_ADD_GTEST(testLikelihoodJob TestStatistics/testLikelihoodJob.cxx LIBRARIES RooFitMultiProcess RooFitCore RooFit RooStats m) + ROOT_ADD_GTEST(testLikelihoodJob TestStatistics/testLikelihoodJob.cxx LIBRARIES RooFitMultiProcess RooFitCore m) target_include_directories(testLikelihoodJob PRIVATE ${RooFitCore_MultiProcess_TestStatistics_INCLUDE_DIR}) endif() diff --git a/roofit/roofitcore/test/TestStatistics/testInterface.cpp b/roofit/roofitcore/test/TestStatistics/testInterface.cpp deleted file mode 100644 index a4bc0a8ed8e30..0000000000000 --- a/roofit/roofitcore/test/TestStatistics/testInterface.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Project: RooFit - * Authors: - * ZW, Zef Wolffs, Nikhef, zefwolffs@gmail.com - * - * Copyright (c) 2021, CERN - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted according to the terms - * listed in LICENSE (http://roofit.sourceforge.net/license.txt) - */ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Math/Minimizer.h" - -#include "gtest/gtest.h" - -class Interface : public ::testing::Test {}; - -// Verifies that RooAbsPdf::createNLL() can create a valid RooAbsL wrapped in RooRealL -TEST(Interface, createNLLRooAbsL) -{ - using namespace RooFit; - - RooRandom::randomGenerator()->SetSeed(42); - RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); - auto x = w.var("x"); - RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; - RooAbsReal *nll = pdf->createNLL(*data, RooFit::ModularL(true)); - - RooFit::TestStatistics::RooRealL *nll_real = dynamic_cast(nll); - - EXPECT_TRUE(nll_real != nullptr); - - RooFit::TestStatistics::RooAbsL *nll_absL = - dynamic_cast(nll_real->getRooAbsL().get()); - - EXPECT_TRUE(nll_absL != nullptr); -} - -// New Style likelihoods cannot be initialized with offsetting -TEST(Interface, createNLLModularLAndOffset) -{ - using namespace RooFit; - - RooRandom::randomGenerator()->SetSeed(42); - RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); - auto x = w.var("x"); - RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; - RooAbsReal *nll = pdf->createNLL(*data, RooFit::Offset(true), RooFit::ModularL(true)); - - EXPECT_TRUE(nll == nullptr); -} - -// Verifies that the fitTo parallelize interface creates a valid minimization -TEST(Interface, DISABLED_fitTo) -{ - ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); - - RooRandom::randomGenerator()->SetSeed(42); - RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); - auto x = w.var("x"); - RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; - - RooArgSet *values = pdf->getParameters(data.get()); - - values->add(*pdf); - - RooArgSet *savedValues = dynamic_cast(values->snapshot()); - if (savedValues == nullptr) { - throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!"); - } - - std::unique_ptr result1{pdf->fitTo(*data, RooFit::Save())}; - - double minNll_nominal = result1->minNll(); - double edm_nominal = result1->edm(); - - *values = *savedValues; - - std::unique_ptr result2{pdf->fitTo(*data, RooFit::Save(), RooFit::Parallelize(4), RooFit::Experimental::ParallelGradientOptions(true), RooFit::Experimental::ParallelDescentOptions(true))}; - - double minNll_GradientJob = result2->minNll(); - double edm_GradientJob = result2->edm(); - - EXPECT_NEAR(minNll_nominal, minNll_GradientJob, 1e-4); - EXPECT_NEAR(edm_nominal, edm_GradientJob, 1e-4); -} diff --git a/roofit/roofitcore/test/TestStatistics/testInterface.cxx b/roofit/roofitcore/test/TestStatistics/testInterface.cxx new file mode 100644 index 0000000000000..5613248d8bfc9 --- /dev/null +++ b/roofit/roofitcore/test/TestStatistics/testInterface.cxx @@ -0,0 +1,126 @@ +/* + * Project: RooFit + * Authors: + * ZW, Zef Wolffs, Nikhef, zefwolffs@gmail.com + * + * Copyright (c) 2021, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Math/Minimizer.h" + +#include "gtest/gtest.h" + +class Interface : public ::testing::Test {}; + +// Verifies that RooAbsPdf::createNLL() can create a valid RooAbsL wrapped in RooRealL +TEST(Interface, createNLLRooAbsL) +{ + using namespace RooFit; + + RooRandom::randomGenerator()->SetSeed(42); + RooWorkspace w; + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1, 0.01, 3])"); + RooRealVar *x = w.var("x"); + RooRealVar *sigma = w.var("sigma"); + sigma->setConstant(true); + RooAbsPdf *pdf = w.pdf("g"); + std::unique_ptr data{pdf->generate(*x, 10000)}; + std::unique_ptr nll{pdf->createNLL(*data, RooFit::ModularL(true))}; + + auto *nll_real = dynamic_cast(&*nll); + + EXPECT_TRUE(nll_real != nullptr); + + auto *nll_absL = dynamic_cast(nll_real->getRooAbsL().get()); + + EXPECT_TRUE(nll_absL != nullptr); +} + +// New Style likelihoods cannot be initialized with offsetting +TEST(Interface, createNLLModularLAndOffset) +{ + using namespace RooFit; + + RooRandom::randomGenerator()->SetSeed(42); + RooWorkspace w; + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1, 0.01, 3])"); + RooRealVar *x = w.var("x"); + RooRealVar *sigma = w.var("sigma"); + sigma->setConstant(true); + RooAbsPdf *pdf = w.pdf("g"); + std::unique_ptr data{pdf->generate(*x, 10000)}; + + RooHelpers::HijackMessageStream hijack(RooFit::ERROR, RooFit::InputArguments); + + std::unique_ptr nll{pdf->createNLL(*data, RooFit::Offset(true), RooFit::ModularL(true))}; + + EXPECT_NE(hijack.str().find("ERROR"), std::string::npos) << "Stream contents: " << hijack.str(); + + EXPECT_TRUE(nll == nullptr); +} + +// Verifies that the fitTo parallelize interface creates a valid minimization +#ifdef R__HAS_ROOFIT_MULTIPROCESS +TEST(Interface, fitTo) +#else +TEST(Interface, DISABLED_fitTo) +#endif +{ + using namespace RooFit; + + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); + + RooRandom::randomGenerator()->SetSeed(42); + RooWorkspace w; + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1, 0.01, 3])"); + auto x = w.var("x"); + RooRealVar *sigma = w.var("sigma"); + sigma->setConstant(true); + RooAbsPdf *pdf = w.pdf("g"); + std::unique_ptr data{pdf->generate({*x}, 10000)}; + + RooArgSet values; + pdf->getParameters(data->get(), values); + + values.add(*pdf); + + RooArgSet savedValues; + values.snapshot(savedValues); + + std::unique_ptr result1{pdf->fitTo(*data, Save(), PrintLevel(-1))}; + + double minNll_nominal = result1->minNll(); + double edm_nominal = result1->edm(); + + values.assign(savedValues); + + std::unique_ptr result2{pdf->fitTo(*data, Save(), PrintLevel(-1), Parallelize(4), + Experimental::ParallelGradientOptions(true), + Experimental::ParallelDescentOptions(true))}; + + double minNll_GradientJob = result2->minNll(); + double edm_GradientJob = result2->edm(); + + EXPECT_NEAR(minNll_nominal, minNll_GradientJob, 1e-4); + EXPECT_NEAR(edm_nominal, edm_GradientJob, 1e-4); +} diff --git a/roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cpp b/roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cxx similarity index 91% rename from roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cpp rename to roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cxx index ae9c6ec0b3fa7..d9e50b2395ad8 100644 --- a/roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cpp +++ b/roofit/roofitcore/test/TestStatistics/testLikelihoodGradientJob.cxx @@ -18,6 +18,7 @@ #include "RooWorkspace.h" #include "RooDataHist.h" // complete type in Binned test #include "RooCategory.h" // complete type in MultiBinnedConstraint test +#include "RooHelpers.h" #include "RooMinimizer.h" #include "RooFitResult.h" #include "RooFit/TestStatistics/LikelihoodWrapper.h" @@ -26,18 +27,12 @@ #include "RooFit/TestStatistics/buildLikelihood.h" #include "RooFit/MultiProcess/JobManager.h" #include "RooFit/MultiProcess/Config.h" -#include "RooStats/ModelConfig.h" #include "Math/Minimizer.h" #include // runtime_error -#include "gtest/gtest.h" - -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif +#include "../gtest_wrapper.h" #include "../test_lib.h" // generate_1D_gaussian_pdf_nll @@ -63,9 +58,13 @@ class Environment : public testing::Environment { public: void SetUp() override { - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + _changeMsgLvl = std::make_unique(RooFit::ERROR); ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); } + void TearDown() override { _changeMsgLvl.reset(); } + +private: + std::unique_ptr _changeMsgLvl; }; // Previously, we just called AddGlobalTestEnvironment in global namespace, but this caused either a warning about an @@ -96,7 +95,7 @@ TEST_P(LikelihoodGradientJobTest, Gaussian1D) std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooDataSet *data; + std::unique_ptr data; std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); RooRealVar *mu = w.var("mu"); @@ -121,8 +120,8 @@ TEST_P(LikelihoodGradientJobTest, Gaussian1D) values->assign(savedValues); RooFit::MultiProcess::Config::setDefaultNWorkers(NWorkers); - auto unbinned_l = std::make_shared(pdf, data); - RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", unbinned_l); + RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", + std::make_unique(pdf, data.get())); // Convert to RooRealL to enter into minimizer RooMinimizer::Config cfg1; @@ -162,7 +161,7 @@ TEST(LikelihoodGradientJob, RepeatMigrad) std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooDataSet *data; + std::unique_ptr data; std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); RooArgSet savedValues; @@ -171,8 +170,8 @@ TEST(LikelihoodGradientJob, RepeatMigrad) // -------- RooFit::MultiProcess::Config::setDefaultNWorkers(NWorkers); - auto unbinned_l = std::make_shared(pdf, data); - RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", unbinned_l); + RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", + std::make_unique(pdf, data.get())); RooMinimizer::Config cfg; cfg.parallelize = -1; RooMinimizer m1(likelihood, cfg); @@ -208,8 +207,8 @@ TEST_P(LikelihoodGradientJobTest, GaussianND) std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooDataSet *data; - std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000); + std::unique_ptr data; + std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, RooFit::EvalBackend::Legacy()); RooArgSet savedValues; values->snapshot(savedValues); @@ -248,8 +247,8 @@ TEST_P(LikelihoodGradientJobTest, GaussianND) // -------- RooFit::MultiProcess::Config::setDefaultNWorkers(NWorkers); - auto unbinned_l = std::make_shared(pdf, data); - RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", unbinned_l); + RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", + std::make_unique(pdf, data.get())); RooMinimizer::Config cfg1; cfg1.parallelize = -1; RooMinimizer m1(likelihood, cfg1); @@ -331,7 +330,7 @@ std::unique_ptr makeSimBinnedConstrainedWorkspace() w.factory("PROD::model_A(model_phys_A,model_subs_A)"); w.factory("PROD::model_B(model_phys_B,model_subs_B)"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); // Construct dataset from physics pdf @@ -358,15 +357,16 @@ TEST(SimBinnedConstrainedTestBasic, BasicParameters) const double nll0 = nll->getVal(); - std::shared_ptr likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); - auto clean_flags = std::make_shared(); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); + auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, + RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(), + std::make_unique()); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_DOUBLE_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } class SimBinnedConstrainedTest : public ::testing::TestWithParam> {}; @@ -417,9 +417,8 @@ TEST_P(SimBinnedConstrainedTest, ConstrainedAndOffset) RooFit::MultiProcess::Config::setDefaultNWorkers(NWorkers); - std::unique_ptr likelihoodAbsReal{pdf->createNLL(*data, Constrain(*w.var("alpha_bkg_obs_A")), - GlobalObservables(*w.var("alpha_bkg_obs_B")), - ModularL(true))}; + std::unique_ptr likelihoodAbsReal{pdf->createNLL( + *data, Constrain(*w.var("alpha_bkg_obs_A")), GlobalObservables(*w.var("alpha_bkg_obs_B")), ModularL(true))}; RooMinimizer::Config cfg1; cfg1.parallelize = -1; @@ -490,7 +489,7 @@ TEST_P(LikelihoodGradientJobTest, Gaussian1DAlsoWithLikelihoodJob) std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooDataSet *data; + std::unique_ptr data; std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); RooRealVar *mu = w.var("mu"); @@ -516,8 +515,8 @@ TEST_P(LikelihoodGradientJobTest, Gaussian1DAlsoWithLikelihoodJob) values->assign(savedValues); RooFit::MultiProcess::Config::setDefaultNWorkers(NWorkers); - auto unbinned_l = std::make_shared(pdf, data); - RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", unbinned_l); + RooFit::TestStatistics::RooRealL likelihood("likelihood", "likelihood", + std::make_unique(pdf, data.get())); RooMinimizer::Config cfg; cfg.parallelize = -1; cfg.enableParallelDescent = true; diff --git a/roofit/roofitcore/test/TestStatistics/testLikelihoodJob.cxx b/roofit/roofitcore/test/TestStatistics/testLikelihoodJob.cxx index 17b2524b7be5c..f6a96c10e53ea 100644 --- a/roofit/roofitcore/test/TestStatistics/testLikelihoodJob.cxx +++ b/roofit/roofitcore/test/TestStatistics/testLikelihoodJob.cxx @@ -16,12 +16,10 @@ #include "RooWorkspace.h" #include "RooMinimizer.h" #include "RooFitResult.h" -#include "RooNLLVar.h" #include "RooDataHist.h" // complete type in Binned test #include "RooCategory.h" // complete type in MultiBinnedConstraint test #include "RooFit/TestStatistics/RooUnbinnedL.h" #include "RooFit/TestStatistics/RooBinnedL.h" -#include "RooFit/TestStatistics/optional_parameter_types.h" #include "RooFit/TestStatistics/buildLikelihood.h" #include "RooFit/TestStatistics/RooRealL.h" #include "RooFit/MultiProcess/Config.h" @@ -30,12 +28,7 @@ #include // runtime_error -#include "gtest/gtest.h" - -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif +#include "../gtest_wrapper.h" #include "../test_lib.h" // generate_1D_gaussian_pdf_nll @@ -45,9 +38,13 @@ class Environment : public testing::Environment { public: void SetUp() override { - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + _changeMsgLvl = std::make_unique(RooFit::ERROR); RooFit::MultiProcess::Config::setDefaultNWorkers(2); } + void TearDown() override { _changeMsgLvl.reset(); } + +private: + std::unique_ptr _changeMsgLvl; }; // Previously, we just called AddGlobalTestEnvironment in global namespace, but this caused either a warning about an @@ -66,7 +63,7 @@ class LikelihoodJobTest : public ::testing::Test { void SetUp() override { RooRandom::randomGenerator()->SetSeed(seed); - clean_flags = std::make_shared(); + clean_flags = std::make_unique(); } std::size_t seed = 23; @@ -74,7 +71,7 @@ class LikelihoodJobTest : public ::testing::Test { std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooAbsData *data; + std::unique_ptr data; std::shared_ptr likelihood; std::shared_ptr clean_flags; }; @@ -90,8 +87,8 @@ class LikelihoodJobBinnedDatasetTest : public LikelihoodJobTest { w.factory("Uniform::u(x)"); // Generate template histograms - RooDataHist *h_sig = w.pdf("g")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sig{w.pdf("g")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sig, RooFit::Rename("h_sig")); w.import(*h_bkg, RooFit::Rename("h_bkg")); @@ -108,22 +105,24 @@ class LikelihoodJobBinnedDatasetTest : public LikelihoodJobTest { TEST_F(LikelihoodJobTest, UnbinnedGaussian1D) { std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, UnbinnedGaussian1DTwice) { std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -132,65 +131,62 @@ TEST_F(LikelihoodJobTest, UnbinnedGaussian1DTwice) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, UnbinnedGaussianND) { + using namespace RooFit; unsigned int N = 4; - std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, EvalBackend::Legacy()); + likelihood = TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = LikelihoodWrapper::create(TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); + // printf("%a =?= %a\n", nll0, nll1.Sum()); } TEST_F(LikelihoodJobBinnedDatasetTest, UnbinnedPdf) { - data = pdf->generateBinned(*w.var("x")); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } -TEST_F(LikelihoodJobBinnedDatasetTest, BinnedManualNLL) +TEST_F(LikelihoodJobBinnedDatasetTest, BinnedNLL) { pdf->setAttribute("BinnedLikelihood"); - data = pdf->generateBinned(*w.var("x")); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; - // manually create NLL, ripping all relevant parts from RooAbsPdf::createNLL, except here we also set binnedL = true - RooArgSet projDeps; - RooAbsTestStatistic::Configuration nll_config; - nll_config.verbose = false; - nll_config.cloneInputData = false; - nll_config.binnedL = true; - int extended = 2; - RooNLLVar nll_manual("nlletje", "-log(likelihood)", *pdf, *data, projDeps, extended, nll_config); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); - auto nll0 = nll_manual.getVal(); + auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, SimBinned) @@ -201,9 +197,9 @@ TEST_F(LikelihoodJobTest, SimBinned) w.factory("Uniform::u(x)"); // Generate template histograms - RooDataHist *h_sigA = w.pdf("gA")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_sigB = w.pdf("gB")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sigA{w.pdf("gA")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_sigB{w.pdf("gB")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sigA, RooFit::Rename("h_sigA")); w.import(*h_sigB, RooFit::Rename("h_sigB")); @@ -220,24 +216,25 @@ TEST_F(LikelihoodJobTest, SimBinned) w.pdf("model_A")->setAttribute("BinnedLikelihood"); w.pdf("model_B")->setAttribute("BinnedLikelihood"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); // Construct dataset pdf = w.pdf("model"); - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index")), RooFit::AllBinned()); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")}, RooFit::AllBinned())}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, BinnedConstrained) @@ -249,8 +246,8 @@ TEST_F(LikelihoodJobTest, BinnedConstrained) // Generate template histograms - RooDataHist *h_sig = w.pdf("g")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sig{w.pdf("g")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sig, RooFit::Rename("h_sig")); w.import(*h_bkg, RooFit::Rename("h_bkg")); @@ -268,22 +265,22 @@ TEST_F(LikelihoodJobTest, BinnedConstrained) pdf = w.pdf("model"); // Construct dataset from physics pdf - data = w.pdf("model_phys")->generateBinned(*w.var("x")); + data = std::unique_ptr{w.pdf("model_phys")->generateBinned(*w.var("x"))}; - nll.reset(pdf->createNLL(*data, RooFit::GlobalObservables(*w.var("alpha_bkg_obs")))); + nll = std::unique_ptr{pdf->createNLL(*data, RooFit::GlobalObservables(*w.var("alpha_bkg_obs")))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs")))); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data}.GlobalObservables(*w.var("alpha_bkg_obs")).build(); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_DOUBLE_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, SimUnbinned) @@ -296,21 +293,22 @@ TEST_F(LikelihoodJobTest, SimUnbinned) pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index"))); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")})}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_DOUBLE_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobTest, SimUnbinnedNonExtended) @@ -328,22 +326,23 @@ TEST_F(LikelihoodJobTest, SimUnbinnedNonExtended) w.cat("index")->setLabel("B"); dB->addColumn(*w.cat("index")); - data = (RooDataSet *)dA->Clone(); - dynamic_cast(data)->append(*dB); + data = std::unique_ptr{static_cast(dA->Clone())}; + static_cast(*data).append(*dB); pdf = w.pdf("model"); - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); auto nll0 = nll->getVal(); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } class LikelihoodJobSimBinnedConstrainedTest : public LikelihoodJobTest { @@ -384,49 +383,54 @@ class LikelihoodJobSimBinnedConstrainedTest : public LikelihoodJobTest { w.factory("PROD::model_A(model_phys_A,model_subs_A)"); w.factory("PROD::model_B(model_phys_B,model_subs_B)"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index")), RooFit::AllBinned()); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")}, RooFit::AllBinned())}; } }; TEST_F(LikelihoodJobSimBinnedConstrainedTest, BasicParameters) { // original test: - nll.reset(pdf->createNLL( - *data, RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B"))))); + nll = std::unique_ptr{ + pdf->createNLL(*data, RooFit::GlobalObservables(*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_DOUBLE_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodJobSimBinnedConstrainedTest, ConstrainedAndOffset) { // a variation to test some additional parameters (ConstrainedParameters and offsetting) - nll.reset(pdf->createNLL(*data, RooFit::Constrain(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B"))), RooFit::Offset(true))); + nll = std::unique_ptr{pdf->createNLL(*data, RooFit::Constrain(*w.var("alpha_bkg_obs_A")), + RooFit::GlobalObservables(*w.var("alpha_bkg_obs_B")), + RooFit::Offset(true))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::ConstrainedParameters(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::TestStatistics::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B")))); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .ConstrainedParameters(*w.var("alpha_bkg_obs_A")) + .GlobalObservables(*w.var("alpha_bkg_obs_B")) + .build(); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); nll_ts->enableOffsetting(true); nll_ts->evaluate(); @@ -437,8 +441,8 @@ TEST_F(LikelihoodJobSimBinnedConstrainedTest, ConstrainedAndOffset) // manually add the offset. ROOT::Math::KahanSum nll1 = nll_ts->getResult() + nll_ts->offset(); - EXPECT_DOUBLE_EQ(nll0, nll1); - EXPECT_FALSE(nll_ts->offset() == 0); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); + EXPECT_FALSE(nll_ts->offset().Sum() == 0); // also check against RooRealL value RooFit::TestStatistics::RooRealL nll_real("real_nll", "RooRealL version", likelihood); @@ -446,55 +450,52 @@ TEST_F(LikelihoodJobSimBinnedConstrainedTest, ConstrainedAndOffset) auto nll2 = nll_real.getVal(); EXPECT_EQ(nll0, nll2); - EXPECT_DOUBLE_EQ(nll1, nll2); + EXPECT_DOUBLE_EQ(nll1.Sum(), nll2); } TEST_F(LikelihoodJobTest, BatchedUnbinnedGaussianND) { unsigned int N = 4; - bool batch_mode = true; - - std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, batch_mode); - - // TODO: the result from the new test statistics is not correct unless the - // coefficient normalization set is fixed manually. Probably this works - // better when the new test statistics are migrated to the new BatchMode, - // and then this line can be deleted. - pdf->fixAddCoefNormalization(*data->get(), false); - - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - dynamic_cast(likelihood.get())->setUseBatchedEvaluations(true); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + auto backend = RooFit::EvalBackend::Cpu(); + std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, backend); auto nll0 = nll->getVal(); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data}.EvalBackend(backend).build(); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_NEAR(nll0, nll1, 1e-14 * nll0); + EXPECT_NEAR(nll0, nll1.Sum(), 1e-14 * nll0); } -class LikelihoodJobSplitStrategies : public LikelihoodJobSimBinnedConstrainedTest, public testing::WithParamInterface> {}; +class LikelihoodJobSplitStrategies : public LikelihoodJobSimBinnedConstrainedTest, + public testing::WithParamInterface> {}; TEST_P(LikelihoodJobSplitStrategies, SimBinnedConstrainedAndOffset) { // based on ConstrainedAndOffset, this test tests different parallelization strategies - nll.reset(pdf->createNLL(*data, RooFit::Constrain(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B"))), RooFit::Offset(true))); + nll = std::unique_ptr{pdf->createNLL(*data, RooFit::Constrain(*w.var("alpha_bkg_obs_A")), + RooFit::GlobalObservables(*w.var("alpha_bkg_obs_B")), + RooFit::Offset(true))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::ConstrainedParameters(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::TestStatistics::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B")))); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .ConstrainedParameters(*w.var("alpha_bkg_obs_A")) + .GlobalObservables(*w.var("alpha_bkg_obs_B")) + .build(); RooFit::MultiProcess::Config::LikelihoodJob::defaultNEventTasks = std::get<0>(GetParam()); RooFit::MultiProcess::Config::LikelihoodJob::defaultNComponentTasks = std::get<1>(GetParam()); - auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); + auto nll_ts = + LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::multiprocess, likelihood, clean_flags); nll_ts->enableOffsetting(true); nll_ts->evaluate(); @@ -505,8 +506,8 @@ TEST_P(LikelihoodJobSplitStrategies, SimBinnedConstrainedAndOffset) // manually add the offset. ROOT::Math::KahanSum nll1 = nll_ts->getResult() + nll_ts->offset(); - EXPECT_DOUBLE_EQ(nll0, nll1); - EXPECT_FALSE(nll_ts->offset() == 0); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); + EXPECT_FALSE(nll_ts->offset().Sum() == 0); // also check against RooRealL value RooFit::TestStatistics::RooRealL nll_real("real_nll", "RooRealL version", likelihood); @@ -514,15 +515,14 @@ TEST_P(LikelihoodJobSplitStrategies, SimBinnedConstrainedAndOffset) auto nll2 = nll_real.getVal(); EXPECT_EQ(nll0, nll2); - EXPECT_DOUBLE_EQ(nll1, nll2); + EXPECT_DOUBLE_EQ(nll1.Sum(), nll2); } -INSTANTIATE_TEST_SUITE_P( - SplitStrategies, LikelihoodJobSplitStrategies, - testing::Combine( - // number of event tasks: - testing::Values(0, 1, 2, 50, 100, 101, 102, 100000), // the last value is larger than number of events to test that - // number of component tasks: - testing::Values(0, 1, 2, 4) // the last value is larger than number of components - ) -); +INSTANTIATE_TEST_SUITE_P(SplitStrategies, LikelihoodJobSplitStrategies, + testing::Combine( + // number of event tasks: + testing::Values(0, 1, 2, 50, 100, 101, 102, + 100000), // the last value is larger than number of events to test that + // number of component tasks: + testing::Values(0, 1, 2, 4) // the last value is larger than number of components + )); diff --git a/roofit/roofitcore/test/TestStatistics/testLikelihoodSerial.cxx b/roofit/roofitcore/test/TestStatistics/testLikelihoodSerial.cxx index 3ac2c884b927b..6e84710ac5606 100644 --- a/roofit/roofitcore/test/TestStatistics/testLikelihoodSerial.cxx +++ b/roofit/roofitcore/test/TestStatistics/testLikelihoodSerial.cxx @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -37,7 +36,11 @@ using RooFit::TestStatistics::LikelihoodWrapper; class Environment : public testing::Environment { public: - void SetUp() override { RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); } + void SetUp() override { _changeMsgLvl = std::make_unique(RooFit::ERROR); } + void TearDown() override { _changeMsgLvl.reset(); } + +private: + std::unique_ptr _changeMsgLvl; }; // Previously, we just called AddGlobalTestEnvironment in global namespace, but this caused either a warning about an @@ -56,7 +59,7 @@ class LikelihoodSerialTest : public ::testing::Test { void SetUp() override { RooRandom::randomGenerator()->SetSeed(seed); - clean_flags = std::make_shared(); + clean_flags = std::make_unique(); } std::size_t seed = 23; @@ -64,7 +67,7 @@ class LikelihoodSerialTest : public ::testing::Test { std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooAbsData *data; + std::unique_ptr data; std::shared_ptr likelihood; std::shared_ptr clean_flags; }; @@ -80,8 +83,8 @@ class LikelihoodSerialBinnedDatasetTest : public LikelihoodSerialTest { w.factory("Uniform::u(x)"); // Generate template histograms - RooDataHist *h_sig = w.pdf("g")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sig{w.pdf("g")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sig, RooFit::Rename("h_sig")); w.import(*h_bkg, RooFit::Rename("h_bkg")); @@ -98,7 +101,7 @@ class LikelihoodSerialBinnedDatasetTest : public LikelihoodSerialTest { TEST_F(LikelihoodSerialTest, UnbinnedGaussian1D) { std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -106,15 +109,15 @@ TEST_F(LikelihoodSerialTest, UnbinnedGaussian1D) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialTest, UnbinnedGaussianND) { unsigned int N = 4; - std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, RooFit::EvalBackend::Legacy()); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -122,16 +125,16 @@ TEST_F(LikelihoodSerialTest, UnbinnedGaussianND) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialBinnedDatasetTest, UnbinnedPdf) { - data = pdf->generateBinned(*w.var("x")); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -139,13 +142,13 @@ TEST_F(LikelihoodSerialBinnedDatasetTest, UnbinnedPdf) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialBinnedDatasetTest, BinnedManualNLL) { pdf->setAttribute("BinnedLikelihood"); - data = pdf->generateBinned(*w.var("x")); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; // manually create NLL, ripping all relevant parts from RooAbsPdf::createNLL, except here we also set binnedL = true RooArgSet projDeps; @@ -156,7 +159,7 @@ TEST_F(LikelihoodSerialBinnedDatasetTest, BinnedManualNLL) int extended = 2; RooNLLVar nll_manual("nlletje", "-log(likelihood)", *pdf, *data, projDeps, extended, nll_config); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll_manual.getVal(); @@ -164,7 +167,7 @@ TEST_F(LikelihoodSerialBinnedDatasetTest, BinnedManualNLL) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialTest, SimBinned) @@ -175,9 +178,9 @@ TEST_F(LikelihoodSerialTest, SimBinned) w.factory("Uniform::u(x)"); // Generate template histograms - RooDataHist *h_sigA = w.pdf("gA")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_sigB = w.pdf("gB")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sigA{w.pdf("gA")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_sigB{w.pdf("gB")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sigA, RooFit::Rename("h_sigA")); w.import(*h_sigB, RooFit::Rename("h_sigB")); @@ -194,16 +197,16 @@ TEST_F(LikelihoodSerialTest, SimBinned) w.pdf("model_A")->setAttribute("BinnedLikelihood"); w.pdf("model_B")->setAttribute("BinnedLikelihood"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); // Construct dataset pdf = w.pdf("model"); - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index")), RooFit::AllBinned()); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")}, RooFit::AllBinned())}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -211,7 +214,7 @@ TEST_F(LikelihoodSerialTest, SimBinned) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialTest, BinnedConstrained) @@ -223,8 +226,8 @@ TEST_F(LikelihoodSerialTest, BinnedConstrained) // Generate template histograms - RooDataHist *h_sig = w.pdf("g")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sig{w.pdf("g")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sig, RooFit::Rename("h_sig")); w.import(*h_bkg, RooFit::Rename("h_bkg")); @@ -242,22 +245,21 @@ TEST_F(LikelihoodSerialTest, BinnedConstrained) pdf = w.pdf("model"); // Construct dataset from physics pdf - data = w.pdf("model_phys")->generateBinned(*w.var("x")); + data = std::unique_ptr{w.pdf("model_phys")->generateBinned(*w.var("x"))}; - nll.reset(pdf->createNLL(*data, RooFit::GlobalObservables(*w.var("alpha_bkg_obs")))); + nll = std::unique_ptr{pdf->createNLL(*data, RooFit::GlobalObservables(*w.var("alpha_bkg_obs")))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs")))); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data}.GlobalObservables(*w.var("alpha_bkg_obs")).build(); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialTest, SimUnbinned) @@ -270,21 +272,21 @@ TEST_F(LikelihoodSerialTest, SimUnbinned) pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index"))); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")})}; - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialTest, SimUnbinnedNonExtended) @@ -302,14 +304,14 @@ TEST_F(LikelihoodSerialTest, SimUnbinnedNonExtended) w.cat("index")->setLabel("B"); dB->addColumn(*w.cat("index")); - data = (RooDataSet *)dA->Clone(); - dynamic_cast(data)->append(*dB); + data = std::unique_ptr{static_cast(dA->Clone())}; + static_cast(*data).append(*dB); pdf = w.pdf("model"); - nll.reset(pdf->createNLL(*data)); + nll = std::unique_ptr{pdf->createNLL(*data)}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); auto nll0 = nll->getVal(); @@ -317,7 +319,7 @@ TEST_F(LikelihoodSerialTest, SimUnbinnedNonExtended) nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_EQ(nll0, nll1); + EXPECT_EQ(nll0, nll1.Sum()); } class LikelihoodSerialSimBinnedConstrainedTest : public LikelihoodSerialTest { @@ -358,48 +360,51 @@ class LikelihoodSerialSimBinnedConstrainedTest : public LikelihoodSerialTest { w.factory("PROD::model_A(model_phys_A,model_subs_A)"); w.factory("PROD::model_B(model_phys_B,model_subs_B)"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index")), RooFit::AllBinned()); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")}, RooFit::AllBinned())}; } }; TEST_F(LikelihoodSerialSimBinnedConstrainedTest, BasicParameters) { // original test: - nll.reset(pdf->createNLL( - *data, RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B"))))); + nll = std::unique_ptr{pdf->createNLL( + *data, RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B"))))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_DOUBLE_EQ(nll0, nll1); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); } TEST_F(LikelihoodSerialSimBinnedConstrainedTest, ConstrainedAndOffset) { // a variation to test some additional parameters (ConstrainedParameters and offsetting) - nll.reset(pdf->createNLL(*data, RooFit::Constrain(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B"))), RooFit::Offset(true))); + nll = std::unique_ptr{pdf->createNLL(*data, RooFit::Constrain(RooArgSet(*w.var("alpha_bkg_obs_A"))), + RooFit::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B"))), + RooFit::Offset(true))}; // -------- auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::ConstrainedParameters(RooArgSet(*w.var("alpha_bkg_obs_A"))), - RooFit::TestStatistics::GlobalObservables(RooArgSet(*w.var("alpha_bkg_obs_B")))); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .ConstrainedParameters(*w.var("alpha_bkg_obs_A")) + .GlobalObservables(*w.var("alpha_bkg_obs_B")) + .build(); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); nll_ts->enableOffsetting(true); @@ -411,8 +416,8 @@ TEST_F(LikelihoodSerialSimBinnedConstrainedTest, ConstrainedAndOffset) // manually add the offset. ROOT::Math::KahanSum nll1 = nll_ts->getResult() + nll_ts->offset(); - EXPECT_DOUBLE_EQ(nll0, nll1); - EXPECT_FALSE(nll_ts->offset() == 0); + EXPECT_DOUBLE_EQ(nll0, nll1.Sum()); + EXPECT_FALSE(nll_ts->offset().Sum() == 0); // also check against RooRealL value RooFit::TestStatistics::RooRealL nll_real("real_nll", "RooRealL version", likelihood); @@ -420,31 +425,23 @@ TEST_F(LikelihoodSerialSimBinnedConstrainedTest, ConstrainedAndOffset) auto nll2 = nll_real.getVal(); EXPECT_EQ(nll0, nll2); - EXPECT_DOUBLE_EQ(nll1, nll2); + EXPECT_DOUBLE_EQ(nll1.Sum(), nll2); } TEST_F(LikelihoodSerialTest, BatchedUnbinnedGaussianND) { unsigned int N = 4; - bool batch_mode = true; - - std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, batch_mode); + auto backend = RooFit::EvalBackend::Cpu(); - // TODO: the result from the new test statistics is not correct unless the - // coefficient normalization set is fixed manually. Probably this works - // better when the new test statistics are migrated to the new BatchMode, - // and then this line can be deleted. - pdf->fixAddCoefNormalization(*data->get(), false); + std::tie(nll, pdf, data, values) = generate_ND_gaussian_pdf_nll(w, N, 1000, backend); + auto nll0 = nll->getVal(); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); - dynamic_cast(likelihood.get())->setUseBatchedEvaluations(true); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data}.EvalBackend(backend).build(); auto nll_ts = LikelihoodWrapper::create(RooFit::TestStatistics::LikelihoodMode::serial, likelihood, clean_flags); - auto nll0 = nll->getVal(); - nll_ts->evaluate(); auto nll1 = nll_ts->getResult(); - EXPECT_NEAR(nll0, nll1, 1e-14 * nll0); + EXPECT_NEAR(nll0, nll1.Sum(), 1e-14 * nll0); } diff --git a/roofit/roofitcore/test/TestStatistics/testPlot.cpp b/roofit/roofitcore/test/TestStatistics/testPlot.cxx similarity index 85% rename from roofit/roofitcore/test/TestStatistics/testPlot.cpp rename to roofit/roofitcore/test/TestStatistics/testPlot.cxx index fc496ed8e9dd5..c3bf88f1b275f 100644 --- a/roofit/roofitcore/test/TestStatistics/testPlot.cpp +++ b/roofit/roofitcore/test/TestStatistics/testPlot.cxx @@ -33,9 +33,13 @@ class Environment : public testing::Environment { public: void SetUp() override { - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + _changeMsgLvl = std::make_unique(RooFit::ERROR); ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); } + void TearDown() override { _changeMsgLvl.reset(); } + +private: + std::unique_ptr _changeMsgLvl; }; int main(int argc, char **argv) @@ -47,8 +51,8 @@ int main(int argc, char **argv) class TestRooRealLPlot : public RooUnitTest { public: - TestRooRealLPlot(TFile &refFile, bool writeRef, int verbose, std::string const &batchMode) - : RooUnitTest("Plotting and minimization with RooFit::TestStatistics", &refFile, writeRef, verbose, batchMode){}; + TestRooRealLPlot(TFile &refFile, bool writeRef, int verbose) + : RooUnitTest("Plotting and minimization with RooFit::TestStatistics", &refFile, writeRef, verbose){}; bool testCode() override { @@ -67,7 +71,7 @@ class TestRooRealLPlot : public RooUnitTest { // -------------------------------------------------------------------------------- // Creating a RooAbsL likelihood - RooAbsReal *likelihood = w.pdf("model")->createNLL(d, ModularL(true)); + std::unique_ptr likelihood{w.pdf("model")->createNLL(d, ModularL(true))}; // Creating a minimizer and explicitly setting type of parallelization std::size_t nWorkers = 1; @@ -99,9 +103,11 @@ TEST(TestStatisticsPlot, RooRealL) RooUnitTest::setMemDir(gDirectory); + gErrorIgnoreLevel = kWarning; + TFile fref("TestStatistics_ref.root"); - TestRooRealLPlot plotTest{fref, false, 0, "off"}; + TestRooRealLPlot plotTest{fref, false, 0}; bool result = plotTest.runTest(); ASSERT_TRUE(result); } diff --git a/roofit/roofitcore/test/TestStatistics/testRooAbsL.cxx b/roofit/roofitcore/test/TestStatistics/testRooAbsL.cxx index 458baa63a8cdc..4a741e49546ad 100644 --- a/roofit/roofitcore/test/TestStatistics/testRooAbsL.cxx +++ b/roofit/roofitcore/test/TestStatistics/testRooAbsL.cxx @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -37,7 +36,11 @@ using RooFit::TestStatistics::LikelihoodWrapper; class Environment : public testing::Environment { public: - void SetUp() override { RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); } + void SetUp() override { _changeMsgLvl = std::make_unique(RooFit::ERROR); } + void TearDown() override { _changeMsgLvl.reset(); } + +private: + std::unique_ptr _changeMsgLvl; }; // Previously, we just called AddGlobalTestEnvironment in global namespace, but this caused either a warning about an @@ -56,7 +59,7 @@ class RooAbsLTest : public ::testing::Test { void SetUp() override { RooRandom::randomGenerator()->SetSeed(seed); - clean_flags = std::make_shared(); + clean_flags = std::make_unique(); } std::size_t seed = 23; @@ -64,7 +67,7 @@ class RooAbsLTest : public ::testing::Test { std::unique_ptr nll; std::unique_ptr values; RooAbsPdf *pdf; - RooAbsData *data; + std::unique_ptr data; std::shared_ptr likelihood; std::shared_ptr clean_flags; }; @@ -80,8 +83,8 @@ class BinnedDatasetTest : public RooAbsLTest { w.factory("Uniform::u(x)"); // Generate template histograms - RooDataHist *h_sig = w.pdf("g")->generateBinned(*w.var("x"), 1000); - RooDataHist *h_bkg = w.pdf("u")->generateBinned(*w.var("x"), 1000); + std::unique_ptr h_sig{w.pdf("g")->generateBinned(*w.var("x"), 1000)}; + std::unique_ptr h_bkg{w.pdf("u")->generateBinned(*w.var("x"), 1000)}; w.import(*h_sig, RooFit::Rename("h_sig")); w.import(*h_bkg, RooFit::Rename("h_bkg")); @@ -133,12 +136,12 @@ class SimBinnedConstrainedTest : public RooAbsLTest { w.factory("PROD::model_A(model_phys_A,model_subs_A)"); w.factory("PROD::model_B(model_phys_B,model_subs_B)"); - // Construct simulatenous pdf + // Construct simultaneous pdf w.factory("SIMUL::model(index[A,B],A=model_A,B=model_B)"); pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index")), RooFit::AllBinned()); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")}, RooFit::AllBinned())}; } }; @@ -149,7 +152,7 @@ class SimBinnedConstrainedTest : public RooAbsLTest { TEST_F(RooAbsLTest, UnbinnedLikelihoodIntrospection) { std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10000); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); EXPECT_STREQ("RooUnbinnedL", (likelihood->GetClassName()).c_str()); EXPECT_STREQ("RooUnbinnedL::g", (likelihood->GetInfo()).c_str()); @@ -158,8 +161,8 @@ TEST_F(RooAbsLTest, UnbinnedLikelihoodIntrospection) TEST_F(BinnedDatasetTest, BinnedLikelihoodIntrospection) { pdf->setAttribute("BinnedLikelihood"); - data = pdf->generateBinned(*w.var("x")); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); EXPECT_STREQ("RooBinnedL", (likelihood->GetClassName()).c_str()); EXPECT_STREQ("RooBinnedL::model", (likelihood->GetInfo()).c_str()); @@ -173,27 +176,26 @@ TEST_F(RooAbsLTest, SumLikelihoodIntrospection) pdf = w.pdf("model"); // Construct dataset from physics pdf - data = pdf->generate(RooArgSet(*w.var("x"), *w.cat("index"))); + data = std::unique_ptr{pdf->generate({*w.var("x"), *w.cat("index")})}; - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); EXPECT_STREQ("RooSumL", (likelihood->GetClassName()).c_str()); EXPECT_STREQ("RooSumL::model", (likelihood->GetInfo()).c_str()); } - TEST_F(SimBinnedConstrainedTest, SumSubsidiaryLikelihoodIntrospection) { - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(); EXPECT_STREQ("RooSumL", (likelihood->GetClassName()).c_str()); EXPECT_STREQ("RooSumL::model", (likelihood->GetInfo()).c_str()); - // Is RooSumL so we can cast to this type to use its further functionality - RooFit::TestStatistics::RooSumL* sum_likelihood = dynamic_cast(likelihood.get()); + auto sum_likelihood = static_cast(likelihood.get()); EXPECT_STREQ("RooUnbinnedL", (sum_likelihood->GetComponents()[0]->GetClassName()).c_str()); EXPECT_STREQ("RooUnbinnedL::model_A", (sum_likelihood->GetComponents()[0]->GetInfo()).c_str()); @@ -203,38 +205,47 @@ TEST_F(SimBinnedConstrainedTest, SumSubsidiaryLikelihoodIntrospection) EXPECT_STREQ("RooSubsidiaryL::likelihood for pdf model", (sum_likelihood->GetComponents()[2]->GetInfo()).c_str()); } - TEST_F(BinnedDatasetTest, EventSections) { // Test whether the summed total of multiple sections gives the same result // as an evaluation with a single section over the whole event range. pdf->setAttribute("BinnedLikelihood"); - data = pdf->generateBinned(*w.var("x")); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + data = std::unique_ptr{pdf->generateBinned(*w.var("x"))}; + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto whole = likelihood->evaluatePartition({0, 1}, 0, 0); auto part1 = likelihood->evaluatePartition({0, 0.5}, 0, 0); auto part2 = likelihood->evaluatePartition({0.5, 1}, 0, 0); - EXPECT_EQ(whole, part1 + part2); + + // We cannot EXPECT_EQ in this test, because we compare actually different + // calculations. The multiple additions and FMA operations involved in the + // calculation of the multiple parts introduces different rounding errors + // on the CPU level than the single calculation over all events at once. + EXPECT_DOUBLE_EQ(whole.Sum(), (part1 + part2).Sum()); } TEST_F(SimBinnedConstrainedTest, EventSections) { // Test whether the summed total of multiple sections gives the same result // as an evaluation with a single section over the whole event range. - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(); auto whole = likelihood->evaluatePartition({0, 1}, 0, likelihood->getNComponents()); auto part1 = likelihood->evaluatePartition({0, 0.5}, 0, likelihood->getNComponents()); auto part2 = likelihood->evaluatePartition({0.5, 1}, 0, likelihood->getNComponents()); - EXPECT_EQ(whole, part1 + part2); + + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), (part1 + part2).Sum()); auto part1of4 = likelihood->evaluatePartition({0, 0.25}, 0, likelihood->getNComponents()); auto part2of4 = likelihood->evaluatePartition({0.25, 0.5}, 0, likelihood->getNComponents()); auto part3of4 = likelihood->evaluatePartition({0.5, 0.75}, 0, likelihood->getNComponents()); auto part4of4 = likelihood->evaluatePartition({0.75, 1}, 0, likelihood->getNComponents()); - EXPECT_EQ(whole, part1of4 + part2of4 + part3of4 + part4of4); + + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), (part1of4 + part2of4 + part3of4 + part4of4).Sum()); } TEST_F(RooAbsLTest, SubEventSections) @@ -245,25 +256,31 @@ TEST_F(RooAbsLTest, SubEventSections) // must contain two events, but which section?), or 11 (one must be empty, // but which one?). std::tie(nll, pdf, data, values) = generate_1D_gaussian_pdf_nll(w, 10); - likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data); + likelihood = RooFit::TestStatistics::buildLikelihood(pdf, data.get()); auto whole = likelihood->evaluatePartition({0, 1}, 0, likelihood->getNComponents()); ROOT::Math::KahanSum nine_parts, eleven_parts, twenty_parts; for (std::size_t ix = 0; ix < 9; ++ix) { - nine_parts += likelihood->evaluatePartition({static_cast(ix)/9, static_cast(ix+1)/9}, 0, likelihood->getNComponents()); + nine_parts += likelihood->evaluatePartition({static_cast(ix) / 9, static_cast(ix + 1) / 9}, 0, + likelihood->getNComponents()); } - EXPECT_EQ(whole, nine_parts); + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), nine_parts.Sum()); for (std::size_t ix = 0; ix < 11; ++ix) { - eleven_parts += likelihood->evaluatePartition({static_cast(ix)/11, static_cast(ix+1)/11}, 0, likelihood->getNComponents()); + eleven_parts += likelihood->evaluatePartition({static_cast(ix) / 11, static_cast(ix + 1) / 11}, 0, + likelihood->getNComponents()); } - EXPECT_EQ(whole, eleven_parts); + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), eleven_parts.Sum()); for (std::size_t ix = 0; ix < 20; ++ix) { - twenty_parts += likelihood->evaluatePartition({static_cast(ix)/20, static_cast(ix+1)/20}, 0, likelihood->getNComponents()); + twenty_parts += likelihood->evaluatePartition({static_cast(ix) / 20, static_cast(ix + 1) / 20}, 0, + likelihood->getNComponents()); } - EXPECT_EQ(whole, twenty_parts); + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), twenty_parts.Sum()); } TEST_F(SimBinnedConstrainedTest, SubEventSections) @@ -273,8 +290,9 @@ TEST_F(SimBinnedConstrainedTest, SubEventSections) // number (less) of events than the RooSumL itself. Moreover, this more // complex likelihood has an extended term and a subsidiary component // which also depend on section so will also be checked here. - likelihood = RooFit::TestStatistics::buildLikelihood( - pdf, data, RooFit::TestStatistics::GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")})); + likelihood = RooFit::TestStatistics::NLLFactory{*pdf, *data} + .GlobalObservables({*w.var("alpha_bkg_obs_A"), *w.var("alpha_bkg_obs_B")}) + .build(); auto whole = likelihood->evaluatePartition({0, 1}, 0, likelihood->getNComponents()); @@ -282,15 +300,21 @@ TEST_F(SimBinnedConstrainedTest, SubEventSections) auto N_events_total = likelihood->getNEvents(); for (std::size_t ix = 0; ix < N_events_total; ++ix) { - N_events_total_parts += likelihood->evaluatePartition({static_cast(ix)/N_events_total, static_cast(ix+1)/N_events_total}, 0, likelihood->getNComponents()); + N_events_total_parts += likelihood->evaluatePartition( + {static_cast(ix) / N_events_total, static_cast(ix + 1) / N_events_total}, 0, + likelihood->getNComponents()); } - EXPECT_EQ(whole, N_events_total_parts); + // See comment in first EventSections test for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), N_events_total_parts.Sum()); // now let's do it again over a number of sections 3 times the number of events ROOT::Math::KahanSum thrice_N_events_total_parts; for (std::size_t ix = 0; ix < 3 * N_events_total; ++ix) { - thrice_N_events_total_parts += likelihood->evaluatePartition({static_cast(ix)/(3 * N_events_total), static_cast(ix+1)/(3 * N_events_total)}, 0, likelihood->getNComponents()); + thrice_N_events_total_parts += likelihood->evaluatePartition( + {static_cast(ix) / (3 * N_events_total), static_cast(ix + 1) / (3 * N_events_total)}, 0, + likelihood->getNComponents()); } - EXPECT_EQ(whole, thrice_N_events_total_parts); + // See comment in BinnedDatasetTest.EventSections for explanation on why no EXPECT_EQ. + EXPECT_DOUBLE_EQ(whole.Sum(), thrice_N_events_total_parts.Sum()); } diff --git a/roofit/roofitcore/test/TestStatistics/RooRealL.cpp b/roofit/roofitcore/test/TestStatistics/testRooRealL.cxx similarity index 56% rename from roofit/roofitcore/test/TestStatistics/RooRealL.cpp rename to roofit/roofitcore/test/TestStatistics/testRooRealL.cxx index 43e285735ee91..bc0cc59efe93a 100644 --- a/roofit/roofitcore/test/TestStatistics/RooRealL.cpp +++ b/roofit/roofitcore/test/TestStatistics/testRooRealL.cxx @@ -20,29 +20,22 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include #include -#include // count_if +#include // count_if -#include "gtest/gtest.h" +#include "../gtest_wrapper.h" -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif - -class RooRealL - : public ::testing::TestWithParam> { -}; +class RooRealL : public ::testing::TestWithParam> {}; TEST_P(RooRealL, getVal) { @@ -50,30 +43,35 @@ TEST_P(RooRealL, getVal) // should replicate RooRealMPFE results. RooRandom::randomGenerator()->SetSeed(std::get<0>(GetParam())); RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1,0.01,5.0])"); auto x = w.var("x"); RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data {pdf->generate(RooArgSet(*x), 10000)}; - std::unique_ptr nll {pdf->createNLL(*data)}; + std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; + std::unique_ptr nll{pdf->createNLL(*data)}; auto nominal_result = nll->getVal(); - RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", std::make_shared(pdf, data.get())); + RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", + std::make_unique(pdf, data.get())); auto mp_result = nll_new.getVal(); EXPECT_DOUBLE_EQ(nominal_result, mp_result); } -void check_NLL_type(RooAbsReal *nll) +void check_NLL_type(RooAbsReal *nll, bool verbose = false) { if (dynamic_cast(nll) != nullptr) { - std::cout << "the NLL object is a RooAddition*..." << std::endl; + if (verbose) { + std::cout << "the NLL object is a RooAddition*..." << std::endl; + } bool has_rooconstraintsum = false; for (const auto nll_component : static_cast(nll)->list()) { if (nll_component->IsA() == RooConstraintSum::Class()) { has_rooconstraintsum = true; - std::cout << "...containing a RooConstraintSum component: " << nll_component->GetName() << std::endl; + if (verbose) { + std::cout << "...containing a RooConstraintSum component: " << nll_component->GetName() << std::endl; + } break; } else if (nll_component->IsA() != RooNLLVar::Class() && nll_component->IsA() != RooAddition::Class()) { std::cerr << "... containing an unexpected component class: " << nll_component->ClassName() << std::endl; @@ -81,52 +79,61 @@ void check_NLL_type(RooAbsReal *nll) } } if (!has_rooconstraintsum) { - std::cout << "...containing only RooNLLVar components." << std::endl; + if (verbose) { + std::cout << "...containing only RooNLLVar components." << std::endl; + } } } else if (dynamic_cast(nll) != nullptr) { - std::cout << "the NLL object is a RooNLLVar*" << std::endl; + if (verbose) { + std::cout << "the NLL object is a RooNLLVar*" << std::endl; + } } } -void count_NLL_components(RooAbsReal *nll) +void count_NLL_components(RooAbsReal *nll, bool verbose = false) { if (dynamic_cast(nll) != nullptr) { - std::cout << "the NLL object is a RooAddition*..." << std::endl; + if (verbose) { + std::cout << "the NLL object is a RooAddition*..." << std::endl; + } std::size_t nll_component_count = 0; - for (const auto& component : *nll->getComponents()) { + std::unique_ptr components{nll->getComponents()}; + for (const auto &component : *components) { if (component->IsA() == RooNLLVar::Class()) { ++nll_component_count; } } - std::cout << "...containing " << nll_component_count << " RooNLLVar components." << std::endl; + if (verbose) { + std::cout << "...containing " << nll_component_count << " RooNLLVar components." << std::endl; + } } else if (dynamic_cast(nll) != nullptr) { - std::cout << "the NLL object is a RooNLLVar*" << std::endl; + if (verbose) { + std::cout << "the NLL object is a RooNLLVar*" << std::endl; + } } } TEST_P(RooRealL, getValRooAddition) { - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::ERROR); RooRandom::randomGenerator()->SetSeed(std::get<0>(GetParam())); RooWorkspace w; - w.factory("Gaussian::g(x[-10,10],mu[0,-3,3],sigma[1])"); + w.factory("Gaussian::g(x[-10,10],mu[0,-3,3],sigma[1,0.01,5.0])"); RooRealVar *x = w.var("x"); x->setRange("x_range", -3, 0); x->setRange("another_range", 1, 7); RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data {pdf->generate(RooArgSet(*x), 10000)}; - - RooAbsReal *nll = - pdf->createNLL(*data, RooFit::Range("x_range"), RooFit::Range("another_range")); + std::unique_ptr data{pdf->generate(*x, 10000)}; - check_NLL_type(nll); - count_NLL_components(nll); + using namespace RooFit; + std::unique_ptr nll{pdf->createNLL(*data, Range("x_range,another_range"))}; - delete nll; + check_NLL_type(nll.get()); + count_NLL_components(nll.get()); } #if !defined(_MSC_VER) || defined(R__ENABLE_BROKEN_WIN_TESTS) @@ -135,30 +142,30 @@ TEST_P(RooRealL, getValRooConstraintSumAddition) // modified from // https://github.com/roofit-dev/rootbench/blob/43d12f33e8dac7af7d587b53a2804ddf6717e92f/root/roofit/roofit/RooFitASUM.cxx#L417 - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::ERROR); - int bins = 10000; + RooWorkspace ws; + ws.factory("Polynomial::p0(x[0, 10000])"); + ws.factory("Polynomial::p1(x, {a0[0], a1[1., 0., 2.], a2[0]}, 0)"); - RooRealVar x("x", "x", 0, bins); - x.setBins(bins); - // Parameters - RooRealVar a0("a0", "a0", 0); - RooRealVar a1("a1", "a1", 1, 0, 2); - RooRealVar a2("a2", "a2", 0); + RooRealVar &x = *ws.var("x"); + RooRealVar &a1 = *ws.var("a1"); - RooPolynomial p0("p0", "p0", x); - RooPolynomial p1("p1", "p1", x, RooArgList(a0, a1, a2), 0); + RooAbsPdf &p0 = *ws.pdf("p0"); + RooAbsPdf &p1 = *ws.pdf("p1"); - std::unique_ptr dh_bkg {p0.generateBinned(x, 1000000000)}; - std::unique_ptr dh_sig {p1.generateBinned(x, 100000000)}; + x.setBins(x.getMax()); + + std::unique_ptr dh_bkg{p0.generateBinned(x, 1000000000)}; + std::unique_ptr dh_sig{p1.generateBinned(x, 100000000)}; dh_bkg->SetName("dh_bkg"); dh_sig->SetName("dh_sig"); a1.setVal(2); - std::unique_ptr dh_sig_up {p1.generateBinned(x, 1100000000)}; + std::unique_ptr dh_sig_up{p1.generateBinned(x, 1100000000)}; dh_sig_up->SetName("dh_sig_up"); a1.setVal(.5); - std::unique_ptr dh_sig_down {p1.generateBinned(x, 900000000)}; + std::unique_ptr dh_sig_down{p1.generateBinned(x, 900000000)}; dh_sig_down->SetName("dh_sig_down"); RooWorkspace w = RooWorkspace("w"); @@ -179,35 +186,37 @@ TEST_P(RooRealL, getValRooConstraintSumAddition) RooAbsPdf *pdf = w.pdf("model2"); - std::unique_ptr data {pdf->generateBinned(x, 1100000)}; - RooAbsReal *nll = pdf->createNLL(*data); - - check_NLL_type(nll); - count_NLL_components(nll); + std::unique_ptr data{pdf->generateBinned(x, 1100000)}; + std::unique_ptr nll{pdf->createNLL(*data)}; - delete nll; + check_NLL_type(nll.get()); + count_NLL_components(nll.get()); } -#endif // !defined(_MSC_VER) || defined(R__ENABLE_BROKEN_WIN_TESTS) +#endif // !defined(_MSC_VER) || defined(R__ENABLE_BROKEN_WIN_TESTS) TEST_P(RooRealL, setVal) { // calculate the NLL twice with different parameters + const bool verbose = false; RooRandom::randomGenerator()->SetSeed(std::get<0>(GetParam())); RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1,0.01,5.0])"); auto x = w.var("x"); RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data {pdf->generate(RooArgSet(*x), 10000)}; - std::unique_ptr nll {pdf->createNLL(*data)}; + std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; + std::unique_ptr nll{pdf->createNLL(*data)}; - RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", std::make_shared(pdf, data.get())); + RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", + std::make_unique(pdf, data.get())); // calculate first results auto nominal_result1 = nll->getVal(); auto mp_result1 = nll_new.getVal(); - std::cout << "nominal_result1 = " << nominal_result1 << ", mp_result1 = " << mp_result1 << std::endl; + if (verbose) { + std::cout << "nominal_result1 = " << nominal_result1 << ", mp_result1 = " << mp_result1 << std::endl; + } EXPECT_EQ(nominal_result1, mp_result1); @@ -217,7 +226,9 @@ TEST_P(RooRealL, setVal) auto nominal_result2 = nll->getVal(); auto mp_result2 = nll_new.getVal(); - std::cout << "nominal_result2 = " << nominal_result2 << ", mp_result2 = " << mp_result2 << std::endl; + if (verbose) { + std::cout << "nominal_result2 = " << nominal_result2 << ", mp_result2 = " << mp_result2 << std::endl; + } EXPECT_EQ(nominal_result2, mp_result2); if (HasFailure()) { @@ -225,18 +236,15 @@ TEST_P(RooRealL, setVal) } } -INSTANTIATE_TEST_SUITE_P(NworkersModeSeed, RooRealL, - ::testing::Values(2, 3)); // random seed +INSTANTIATE_TEST_SUITE_P(NworkersModeSeed, RooRealL, ::testing::Values(2, 3)); // random seed -class RealLVsMPFE - : public ::testing::TestWithParam> { -}; +class RealLVsMPFE : public ::testing::TestWithParam> {}; TEST_P(RealLVsMPFE, getVal) { // Compare our MP NLL to actual RooRealMPFE results using the same strategies. - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::ERROR); // parameters std::size_t seed = std::get<0>(GetParam()); @@ -244,16 +252,17 @@ TEST_P(RealLVsMPFE, getVal) RooRandom::randomGenerator()->SetSeed(seed); RooWorkspace w; - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1,0.01,5.0])"); auto x = w.var("x"); RooAbsPdf *pdf = w.pdf("g"); - std::unique_ptr data {pdf->generate(RooArgSet(*x), 10000)}; + std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; - std::unique_ptr nll_mpfe {pdf->createNLL(*data)}; + std::unique_ptr nll_mpfe{pdf->createNLL(*data)}; auto mpfe_result = nll_mpfe->getVal(); - RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", std::make_shared(pdf, data.get())); + RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", + std::make_unique(pdf, data.get())); auto mp_result = nll_new.getVal(); @@ -267,7 +276,7 @@ TEST_P(RealLVsMPFE, minimize) { // do a minimization (e.g. like in GradMinimizer_Gaussian1D test) - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::ERROR); // parameters std::size_t seed = std::get<0>(GetParam()); @@ -276,24 +285,28 @@ TEST_P(RealLVsMPFE, minimize) RooWorkspace w = RooWorkspace(); - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); + w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1,0.01,5.0])"); auto x = w.var("x"); RooAbsPdf *pdf = w.pdf("g"); RooRealVar *mu = w.var("mu"); + RooRealVar *sigma = w.var("sigma"); - std::unique_ptr data {pdf->generate(RooArgSet(*x), 10000)}; + std::unique_ptr data{pdf->generate(RooArgSet(*x), 10000)}; mu->setVal(-2.9); - std::unique_ptr nll_mpfe {pdf->createNLL(*data)}; - RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", std::make_shared(pdf, data.get())); + // If we don't set sigma constant, the fit is not stable as we start with mu + // so close to the boundary + sigma->setConstant(true); + + std::unique_ptr nll_mpfe{pdf->createNLL(*data)}; + RooFit::TestStatistics::RooRealL nll_new("nll_new", "new style NLL", + std::make_unique(pdf, data.get())); // save initial values for the start of all minimizations - RooArgSet values = RooArgSet(*mu, *pdf); + RooArgSet values{*mu, *pdf}; - auto savedValues = dynamic_cast(values.snapshot()); - if (savedValues == nullptr) { - throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!"); - } + RooArgSet savedValues; + values.snapshot(savedValues); // -------- @@ -305,13 +318,13 @@ TEST_P(RealLVsMPFE, minimize) m0.migrad(); - std::unique_ptr m0result {m0.lastMinuitFit()}; + std::unique_ptr m0result{m0.lastMinuitFit()}; double minNll0 = m0result->minNll(); double edm0 = m0result->edm(); double mu0 = mu->getVal(); double muerr0 = mu->getError(); - values = *savedValues; + values.assign(savedValues); RooMinimizer m1(nll_new); m1.setMinimizerType("Minuit2"); @@ -321,7 +334,7 @@ TEST_P(RealLVsMPFE, minimize) m1.migrad(); - std::unique_ptr m1result {m1.lastMinuitFit()}; + std::unique_ptr m1result{m1.lastMinuitFit()}; double minNll1 = m1result->minNll(); double edm1 = m1result->edm(); double mu1 = mu->getVal(); @@ -331,9 +344,6 @@ TEST_P(RealLVsMPFE, minimize) EXPECT_EQ(mu0, mu1); EXPECT_EQ(muerr0, muerr1); EXPECT_EQ(edm0, edm1); - - delete savedValues; } -INSTANTIATE_TEST_SUITE_P(NworkersModeSeed, RealLVsMPFE, - ::testing::Values(2, 3)); // random seed +INSTANTIATE_TEST_SUITE_P(NworkersModeSeed, RealLVsMPFE, ::testing::Values(2, 3)); // random seed diff --git a/roofit/roofitcore/test/dataSet_with_errors_6_26_10.root b/roofit/roofitcore/test/dataSet_with_errors_6_26_10.root new file mode 100644 index 0000000000000..ea98f26a665de Binary files /dev/null and b/roofit/roofitcore/test/dataSet_with_errors_6_26_10.root differ diff --git a/roofit/roofitcore/test/gtest_wrapper.h b/roofit/roofitcore/test/gtest_wrapper.h new file mode 100644 index 0000000000000..8acbd1a96c05f --- /dev/null +++ b/roofit/roofitcore/test/gtest_wrapper.h @@ -0,0 +1,6 @@ +#include + +// Backward compatibility for gtest version < 1.10.0 +#ifndef INSTANTIATE_TEST_SUITE_P +#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P +#endif diff --git a/roofit/roofitcore/test/testGenericPdf.cxx b/roofit/roofitcore/test/testGenericPdf.cxx index 54bf864f480ed..d8f2244c064a8 100644 --- a/roofit/roofitcore/test/testGenericPdf.cxx +++ b/roofit/roofitcore/test/testGenericPdf.cxx @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -35,7 +36,10 @@ TEST(GenericPdf, CrashWhenRunningJohnson) } // ROOT-10411 -TEST(GenericPdf, CrashWhenRenamingArguments) { +TEST(GenericPdf, CrashWhenRenamingArguments) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooRealVar var("var", "var", 0.1, 0, 1); RooRealVar par("par", "par", 0.5, 0, 1); RooGenericPdf genPdf("genPdf", "var*(par + 1)", RooArgSet(var, par)); @@ -56,7 +60,10 @@ TEST(GenericPdf, CrashWhenRenamingArguments) { } // ROOT-5101: Identity PDF affects normalization -TEST(GenericPdf, IdentidyPdfNormalization) { +TEST(GenericPdf, IdentidyPdfNormalization) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooWorkspace ws; ws.factory("Exponential::exp(x[0.0, 100.0], s[-0.5, -10.0, 0.0])"); diff --git a/roofit/roofitcore/test/testGlobalObservables.cxx b/roofit/roofitcore/test/testGlobalObservables.cxx index b1342d9e31543..cc5b2bf2279eb 100644 --- a/roofit/roofitcore/test/testGlobalObservables.cxx +++ b/roofit/roofitcore/test/testGlobalObservables.cxx @@ -2,17 +2,23 @@ // Authors: Jonas Rembser, CERN 08/2021 #include +#include #include #include -#include +#include +#include #include #include +#include "../src/FitHelpers.h" + #include #include #include +using RooFit::FitHelpers::minimize; + namespace { // Helper function to check if two RooFitResults are not identical. @@ -42,7 +48,7 @@ class TestGlobalObservables : public ::testing::Test { void SetUp() override { // silence log output - RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); + _changeMsgLvl = std::make_unique(RooFit::WARNING); // We use the global observable also in the model for the event // observables. It's unusual, but let's better do this to also cover the @@ -68,7 +74,7 @@ class TestGlobalObservables : public ::testing::Test { // generate small dataset for use in fitting below, also cloned versions // with one or two global observables attached - _data.reset(_ws.pdf("model")->generate(*_ws.var("x"), 50)); + _data = std::unique_ptr{_ws.pdf("model")->generate(*_ws.var("x"), 50)}; _dataWithMeanSigmaGlobs.reset(static_cast(_data->Clone())); _dataWithMeanSigmaGlobs->SetName((std::string(_data->GetName()) + "_gm_gs").c_str()); @@ -97,10 +103,9 @@ class TestGlobalObservables : public ::testing::Test { RooAbsPdf &model() { return *ws().pdf("model"); } RooAbsPdf &modelc() { return *ws().pdf("modelc"); } - std::unique_ptr doFit(RooAbsPdf &model, RooAbsData &data, RooCmdArg const &arg1 = RooCmdArg::none(), - RooCmdArg const &arg2 = RooCmdArg::none(), - RooCmdArg const &arg3 = RooCmdArg::none(), - RooCmdArg const &arg4 = RooCmdArg::none()) + std::unique_ptr doFit(RooAbsPdf &model, RooAbsData &data, RooCmdArg const &arg1 = {}, + RooCmdArg const &arg2 = {}, RooCmdArg const &arg3 = {}, + RooCmdArg const &arg4 = {}) { using namespace RooFit; return std::unique_ptr( @@ -112,6 +117,7 @@ class TestGlobalObservables : public ::testing::Test { _data.reset(); _dataWithMeanSigmaGlobs.reset(); _data.reset(); + _changeMsgLvl.reset(); } private: @@ -119,6 +125,7 @@ class TestGlobalObservables : public ::testing::Test { std::unique_ptr _data; std::unique_ptr _dataWithMeanSigmaGlobs; std::unique_ptr _dataWithMeanGlob; + std::unique_ptr _changeMsgLvl; }; TEST_F(TestGlobalObservables, NoConstraints) @@ -265,6 +272,29 @@ TEST_F(TestGlobalObservables, SubsetOfConstraintsFromData) } } +namespace { + +RooCmdConfig minimizerCfg() +{ + + RooCmdConfig pc("minimizerCfg"); + + RooFit::FitHelpers::defineMinimizationOptions(pc); + + std::vector cmdArgs{RooFit::Save(), RooFit::PrintLevel(-1)}; + + RooLinkedList cmdList; + for (auto &arg : cmdArgs) { + cmdList.Add(&arg); + } + + pc.process(cmdList); + + return pc; +} + +} // namespace + TEST_F(TestGlobalObservables, ResetDataToWrongData) { using namespace RooFit; @@ -286,17 +316,14 @@ TEST_F(TestGlobalObservables, ResetDataToWrongData) // check that the fit works when using the dataset with the correct values std::unique_ptr nll{model.createNLL(dataWithMeanSigmaGlobs())}; - RooAbsPdf::MinimizerConfig minimizerCfg; - minimizerCfg.doSave = true; - minimizerCfg.printLevel = -1; - auto res2 = model.minimizeNLL(*nll, dataWithMeanSigmaGlobs(), minimizerCfg); + auto res2 = minimize(model, *nll, dataWithMeanSigmaGlobs(), minimizerCfg()); EXPECT_TRUE(res1->isIdentical(*res2)) << "fitting an model with internal " "constraints in a RooPrdPdf gave a different result when global " "observables were stored in the dataset"; nll->setData(*wrongData); resetParameters(); - auto res3 = model.minimizeNLL(*nll, *wrongData, minimizerCfg); + auto res3 = minimize(model, *nll, *wrongData, minimizerCfg()); // If resetting the dataset used for the nll worked correctly also for // global observables, the fit will now give the wrong result. @@ -328,17 +355,14 @@ TEST_F(TestGlobalObservables, ResetDataToCorrectData) // check that the fit doesn't work when using the dataset with the wrong values std::unique_ptr nll{model.createNLL(*wrongData)}; - RooAbsPdf::MinimizerConfig minimizerCfg; - minimizerCfg.doSave = true; - minimizerCfg.printLevel = -1; - auto res2 = model.minimizeNLL(*nll, *wrongData, minimizerCfg); + auto res2 = minimize(model, *nll, *wrongData, minimizerCfg()); EXPECT_TRUE(isNotIdentical(*res1, *res2)) << "fitting an model with internal " "constraints in a RooPrdPdf ignored the global " "observables stored in the dataset"; nll->setData(dataWithMeanSigmaGlobs()); resetParameters(); - auto res3 = model.minimizeNLL(*nll, dataWithMeanSigmaGlobs(), minimizerCfg); + auto res3 = minimize(model, *nll, dataWithMeanSigmaGlobs(), minimizerCfg()); EXPECT_TRUE(res1->isIdentical(*res3)) << "resetting the dataset " "underlying a RooNLLVar didn't change the global observable value, but it " "should have"; @@ -396,15 +420,12 @@ TEST_F(TestGlobalObservables, ResetDataButSourceFromModel) // check that the fit works when using the dataset with the correct values std::unique_ptr nll{ model.createNLL(dataWithMeanSigmaGlobs(), GlobalObservablesSource("model"), GlobalObservables(gm, gs))}; - RooAbsPdf::MinimizerConfig minimizerCfg; - minimizerCfg.doSave = true; - minimizerCfg.printLevel = -1; - auto res2 = model.minimizeNLL(*nll, dataWithMeanSigmaGlobs(), minimizerCfg); + auto res2 = minimize(model, *nll, dataWithMeanSigmaGlobs(), minimizerCfg()); EXPECT_TRUE(res1->isIdentical(*res2)); nll->setData(*wrongData); resetParameters(); - auto res3 = model.minimizeNLL(*nll, *wrongData, minimizerCfg); + auto res3 = minimize(model, *nll, *wrongData, minimizerCfg()); // this time it should still be identical because even though we reset to // the wrong data, we set the global observables source to "model" diff --git a/roofit/roofitcore/test/testNaNPacker.cxx b/roofit/roofitcore/test/testNaNPacker.cxx index 86fa628b8eb0b..0ee1a8d4e0329 100644 --- a/roofit/roofitcore/test/testNaNPacker.cxx +++ b/roofit/roofitcore/test/testNaNPacker.cxx @@ -1,305 +1,368 @@ // Tests for the RooNaNPacker // Authors: Stephan Hageboeck, CERN 04/2020 -#include "RooNaNPacker.h" -#include "RooRealVar.h" -#include "RooGenericPdf.h" -#include "RooMinimizer.h" -#include "RooFitResult.h" -#include "RooDataSet.h" -#include "RooAddPdf.h" -#include "RooRealSumPdf.h" -#include "RooRandom.h" - -#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtest_wrapper.h" #include -#include #include +#include -void dumpFloats(double val) { - float tmp[2]; - std::memcpy(tmp, &val, sizeof(double)); - - for (int i = 1; i >= 0; --i) { - unsigned long long ull = 0ull; - std::memcpy(&ull, &tmp[i], 4); - std::bitset<32> bits(ull); - std::cout << bits << " " << std::flush; - } - std::cout << std::endl; +void dumpFloats(double val) +{ + float tmp[2]; + std::memcpy(tmp, &val, sizeof(double)); + + for (int i = 1; i >= 0; --i) { + unsigned long long ull = 0ull; + std::memcpy(&ull, &tmp[i], 4); + std::bitset<32> bits(ull); + std::cout << bits << " " << std::flush; + } + std::cout << std::endl; } // Test if we can pack floats into NaNs, and recover them. TEST(RooNaNPacker, CanPackStuffIntoNaNs) { - static_assert((RooNaNPacker::magicTag & RooNaNPacker::magicTagMask) == RooNaNPacker::magicTag, "Bit mask wrong."); - constexpr bool dump = false; - - // Create a NaN that has 1.337f as payload - RooNaNPacker rnp; - rnp.setPayload(1.337f); - EXPECT_TRUE(std::isnan(rnp._payload)); - EXPECT_TRUE(rnp.isNaNWithPayload()); - EXPECT_FLOAT_EQ(rnp.getPayload(), 1.337f); - if (dump) dumpFloats(rnp._payload); - - // Create a normal double - rnp._payload = 1.337; - EXPECT_FALSE(std::isnan(rnp._payload)); - EXPECT_FALSE(rnp.isNaNWithPayload()); - EXPECT_DOUBLE_EQ(rnp._payload, 1.337); - EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); - if (dump) dumpFloats(rnp._payload); - - // Create a normal double - rnp._payload = 4.; - EXPECT_FALSE(std::isnan(rnp._payload)); - EXPECT_FALSE(rnp.isNaNWithPayload()); - EXPECT_DOUBLE_EQ(rnp._payload, 4.); - EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); - if (dump) dumpFloats(rnp._payload); - - // Create a simple payload - rnp.setPayload(0.); - EXPECT_TRUE(std::isnan(rnp._payload)); - EXPECT_TRUE(rnp.isNaNWithPayload()); - EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); - if (dump) dumpFloats(rnp._payload); - - // Create a simple payload - rnp.setPayload(2.); - EXPECT_TRUE(std::isnan(rnp._payload)); - EXPECT_TRUE(rnp.isNaNWithPayload()); - EXPECT_FLOAT_EQ(rnp.getPayload(), 2.f); - if (dump) dumpFloats(rnp._payload); - - // Create a simple payload - rnp.setPayload(4.); - EXPECT_TRUE(std::isnan(rnp._payload)); - EXPECT_TRUE(rnp.isNaNWithPayload()); - EXPECT_FLOAT_EQ(rnp.getPayload(), 4.f); - if (dump) dumpFloats(rnp._payload); - - // Create a NaN that doesn't have the magic tag, - // so no information encoded - rnp._payload = std::numeric_limits::quiet_NaN(); - const float tmp = 1234.5f; - std::memcpy(&rnp._payload, &tmp, sizeof(float)); - EXPECT_TRUE(std::isnan(rnp._payload)); - EXPECT_FALSE(rnp.isNaNWithPayload()); - EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); - if (dump) dumpFloats(rnp._payload); - + static_assert((RooNaNPacker::magicTag & RooNaNPacker::magicTagMask) == RooNaNPacker::magicTag, "Bit mask wrong."); + constexpr bool dump = false; + + // Create a NaN that has 1.337f as payload + RooNaNPacker rnp; + rnp.setPayload(1.337f); + EXPECT_TRUE(std::isnan(rnp._payload)); + EXPECT_TRUE(rnp.isNaNWithPayload()); + EXPECT_FLOAT_EQ(rnp.getPayload(), 1.337f); + if (dump) + dumpFloats(rnp._payload); + + // Create a normal double + rnp._payload = 1.337; + EXPECT_FALSE(std::isnan(rnp._payload)); + EXPECT_FALSE(rnp.isNaNWithPayload()); + EXPECT_DOUBLE_EQ(rnp._payload, 1.337); + EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); + if (dump) + dumpFloats(rnp._payload); + + // Create a normal double + rnp._payload = 4.; + EXPECT_FALSE(std::isnan(rnp._payload)); + EXPECT_FALSE(rnp.isNaNWithPayload()); + EXPECT_DOUBLE_EQ(rnp._payload, 4.); + EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); + if (dump) + dumpFloats(rnp._payload); + + // Create a simple payload + rnp.setPayload(0.); + EXPECT_TRUE(std::isnan(rnp._payload)); + EXPECT_TRUE(rnp.isNaNWithPayload()); + EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); + if (dump) + dumpFloats(rnp._payload); + + // Create a simple payload + rnp.setPayload(2.); + EXPECT_TRUE(std::isnan(rnp._payload)); + EXPECT_TRUE(rnp.isNaNWithPayload()); + EXPECT_FLOAT_EQ(rnp.getPayload(), 2.f); + if (dump) + dumpFloats(rnp._payload); + + // Create a simple payload + rnp.setPayload(4.); + EXPECT_TRUE(std::isnan(rnp._payload)); + EXPECT_TRUE(rnp.isNaNWithPayload()); + EXPECT_FLOAT_EQ(rnp.getPayload(), 4.f); + if (dump) + dumpFloats(rnp._payload); + + // Create a NaN that doesn't have the magic tag, + // so no information encoded + rnp._payload = std::numeric_limits::quiet_NaN(); + const float tmp = 1234.5f; + std::memcpy(&rnp._payload, &tmp, sizeof(float)); + EXPECT_TRUE(std::isnan(rnp._payload)); + EXPECT_FALSE(rnp.isNaNWithPayload()); + EXPECT_FLOAT_EQ(rnp.getPayload(), 0.f); + if (dump) + dumpFloats(rnp._payload); } /// Fit a simple linear function, that starts in the negative. -TEST(RooNaNPacker, FitSimpleLinear) { - RooRealVar x("x", "x", -10, 10); - RooRealVar a1("a1", "a1", 12., -5., 15.); - RooGenericPdf pdf("pdf", "a1 + x", RooArgSet(x, a1)); - std::unique_ptr data(pdf.generate(x, 1000)); - std::unique_ptr nll(pdf.createNLL(*data)); - - RooArgSet normSet{x}; - ASSERT_FALSE(std::isnan(pdf.getVal(normSet))); - a1.setVal(-9.); - ASSERT_TRUE(std::isnan(pdf.getVal(normSet))); - - RooMinimizer minim(*nll); - minim.setPrintLevel(-1); - minim.setPrintEvalErrors(-1); - minim.migrad(); - minim.hesse(); - auto fitResult = minim.save(); - - EXPECT_EQ(fitResult->status(), 0); - EXPECT_NEAR(a1.getVal(), 12., a1.getError()); +TEST(RooNaNPacker, FitSimpleLinear) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + RooRealVar x("x", "x", -10, 10); + RooRealVar a1("a1", "a1", 12., -5., 15.); + RooGenericPdf pdf("pdf", "a1 + x", {x, a1}); + std::unique_ptr data(pdf.generate(x, 1000)); + std::unique_ptr nll(pdf.createNLL(*data)); + + RooArgSet normSet{x}; + ASSERT_FALSE(std::isnan(pdf.getVal(normSet))); + a1.setVal(-9.); + ASSERT_TRUE(std::isnan(pdf.getVal(normSet))); + + RooMinimizer minim(*nll); + minim.setPrintLevel(-1); + minim.setPrintEvalErrors(-1); + minim.migrad(); + minim.hesse(); + std::unique_ptr fitResult{minim.save()}; + + EXPECT_EQ(fitResult->status(), 0); + EXPECT_NEAR(a1.getVal(), 12., a1.getError()); } +class TestForDifferentBackends : public testing::TestWithParam> { +public: + TestForDifferentBackends() : _evalBackend{RooFit::EvalBackend::Legacy()} {} + +private: + void SetUp() override + { + RooRandom::randomGenerator()->SetSeed(1337ul); + _evalBackend = std::get<0>(GetParam()); + _changeMsgLvl = std::make_unique(RooFit::WARNING); + } + + void TearDown() override { _changeMsgLvl.reset(); } + +protected: + RooFit::EvalBackend _evalBackend; + +private: + std::unique_ptr _changeMsgLvl; +}; /// Fit a parabola, where parameters are set up such that negative function values are obtained. /// The minimiser needs to recover from that. /// Test also that when recovery with NaN packing is switched off, the minimiser fails to recover. -TEST(RooNaNPacker, FitParabola) { - RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); // We don't need integration messages - - RooRealVar x("x", "x", -10, 10); - RooRealVar a1("a1", "a1", 12., -10., 20.); - RooRealVar a2("a2", "a2", 1.1, -10., 20.); - RooGenericPdf pdf("pdf", "a1 + x + a2 *x*x", RooArgSet(x, a1, a2)); - std::unique_ptr data(pdf.generate(x, 10000)); - - RooArgSet params(a1, a2); - RooArgSet paramsInit; - params.snapshot(paramsInit); - RooArgSet evilValues; - a1.setVal(-9.); - a2.setVal(-1.); - params.snapshot(evilValues); - - for (bool batchMode : std::initializer_list{true, false}) { - SCOPED_TRACE(batchMode ? "in batch mode" : "in single-value mode"); - - params.assign(evilValues); - std::unique_ptr fitResultOld( pdf.fitTo(*data, - RooFit::RecoverFromUndefinedRegions(0.), - RooFit::Save(), - RooFit::PrintLevel(-1), // Don't need fit status printed - RooFit::PrintEvalErrors(-1), // We provoke a lot of evaluation errors in this test. Don't print those. - RooFit::BatchMode(batchMode), - RooFit::Minos())); - - params.assign(evilValues); - std::unique_ptr fitResultNew( pdf.fitTo(*data, - RooFit::Save(), - RooFit::PrintLevel(-1), - RooFit::PrintEvalErrors(-1), - RooFit::BatchMode(batchMode), - RooFit::Minos())); - - ASSERT_NE(fitResultOld, nullptr); - ASSERT_NE(fitResultNew, nullptr); - - const auto& a1Old = static_cast(fitResultOld->floatParsFinal()[0]); - const auto& a2Old = static_cast(fitResultOld->floatParsFinal()[1]); - - const auto& a1Recover = static_cast(fitResultNew->floatParsFinal()[0]); - const auto& a2Recover = static_cast(fitResultNew->floatParsFinal()[1]); - - EXPECT_EQ(fitResultNew->status(), 0); - EXPECT_NEAR(a1Recover.getVal(), static_cast(paramsInit["a1"]).getVal(), a1Recover.getError()); - EXPECT_NEAR(a2Recover.getVal(), static_cast(paramsInit["a2"]).getVal(), a2Recover.getError()); - - EXPECT_LT(a1Old.getVal(), 0.); - EXPECT_LT(a2Old.getVal(), 0.); - - EXPECT_LT(fitResultNew->numInvalidNLL(), fitResultOld->numInvalidNLL()); - } +TEST_P(TestForDifferentBackends, FitParabola) +{ + RooRealVar x("x", "x", -10, 10); + RooRealVar a1("a1", "a1", 12., -10., 20.); + RooRealVar a2("a2", "a2", 1.1, -10., 20.); + RooGenericPdf pdf("pdf", "a1 + x + a2 *x*x", {x, a1, a2}); + std::unique_ptr data(pdf.generate(x, 10000)); + + RooArgSet params(a1, a2); + RooArgSet paramsInit; + params.snapshot(paramsInit); + RooArgSet evilValues; + a1.setVal(-9.); + a2.setVal(-1.); + params.snapshot(evilValues); + + using namespace RooFit; + params.assign(evilValues); + // Note: we can't use Hesse or Minos. Without the error recovery, Minuit2 + // would print errors that would cause the unit test to fail. + std::unique_ptr fitResultOld( + pdf.fitTo(*data, RecoverFromUndefinedRegions(0.), Save(), + PrintLevel(-1), // Don't need fit status printed + PrintEvalErrors(-1), // We provoke a lot of evaluation errors in this test. Don't print those. + _evalBackend, Hesse(false), Minos(false))); + + params.assign(evilValues); + std::unique_ptr fitResultNew( + pdf.fitTo(*data, Save(), PrintLevel(-1), PrintEvalErrors(-1), _evalBackend)); + + ASSERT_NE(fitResultOld, nullptr); + ASSERT_NE(fitResultNew, nullptr); + + const auto &a1Old = static_cast(fitResultOld->floatParsFinal()[0]); + const auto &a2Old = static_cast(fitResultOld->floatParsFinal()[1]); + + const auto &a1Recover = static_cast(fitResultNew->floatParsFinal()[0]); + const auto &a2Recover = static_cast(fitResultNew->floatParsFinal()[1]); + + EXPECT_NE(fitResultOld->status(), 0); + EXPECT_EQ(fitResultNew->status(), 0); + EXPECT_NEAR(a1Recover.getVal(), static_cast(paramsInit["a1"]).getVal(), a1Recover.getError()); + EXPECT_NEAR(a2Recover.getVal(), static_cast(paramsInit["a2"]).getVal(), a2Recover.getError()); + + EXPECT_LT(a1Old.getVal(), 0.); + EXPECT_LT(a2Old.getVal(), 0.); + + // In the past, when Minuit2 was not the default minimizer yet, there was + // also a check that the number of invalid NLL evaluations was reduced with + // the error recovery: + // + // EXPECT_LT(fitResultNew->numInvalidNLL(), fitResultOld->numInvalidNLL()); + // + // However, Minuit2 takes less evaluations to realize that the minimization + // without error recovery is hopeless, resulting in less invalid NLL + // evaluations when the error recovery is off. Hence, the comparison is not + // meaningful and was commended out. } +#ifdef R__HAS_CUDA +#define EVAL_BACKENDS RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu(), RooFit::EvalBackend::Cuda() +#else +#define EVAL_BACKENDS RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu() +#endif + +INSTANTIATE_TEST_SUITE_P(RooNaNPacker, TestForDifferentBackends, testing::Values(EVAL_BACKENDS), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "EvalBackend" << std::get<0>(paramInfo.param).name(); + return ss.str(); + }); + +#undef BATCH_MODE_VALS + /// Make coefficients of RooAddPdf sum to more than 1. Fitter should recover from this. -TEST(RooNaNPacker, FitAddPdf_DegenerateCoeff) { - constexpr bool verbose = false; - RooRandom::randomGenerator()->SetSeed(100); - - RooRealVar x("x", "x", 0., 10); - RooRealVar a1("a1", "a1", 0.4, -10., 10.); - RooRealVar a2("a2", "a2", 0.4, -10., 10.); - RooGenericPdf pdf1("gen1", "exp(-2.*x)", RooArgSet(x)); - RooGenericPdf pdf2("gen2", "TMath::Gaus(x, 3, 2)", RooArgSet(x)); - RooGenericPdf pdf3("gen3", "x*x*x+1", RooArgSet(x)); - RooAddPdf pdf("sum", "a1*gen1 + a2*gen2 + (1-a1-a2)*gen3", RooArgList(pdf1, pdf2, pdf3), RooArgList(a1, a2)); - std::unique_ptr data(pdf.generate(x, 2000)); - std::unique_ptr nll{pdf.createNLL(*data)}; - - RooArgSet params(a1, a2); - RooArgSet paramsInit; - params.snapshot(paramsInit); - - RooArgSet evilValues; - a1.setVal(0.6); - a2.setVal(0.7); - params.snapshot(evilValues); - - params.assign(evilValues); - - RooFitResult *fitResult1 = nullptr, *fitResult2 = nullptr; - for (auto tryRecover : std::initializer_list{0., 10.}) { - params.assign(evilValues); - - RooMinimizer::cleanup(); - RooMinimizer minim(*nll); - minim.setRecoverFromNaNStrength(tryRecover); - minim.setPrintLevel(-1); - minim.setPrintEvalErrors(-1); - minim.migrad(); - minim.hesse(); - auto fitResult = minim.save(); - (tryRecover != 0. ? fitResult1 : fitResult2) = fitResult; - - const auto& a1Final = static_cast(fitResult->floatParsFinal()[0]); - const auto& a2Final = static_cast(fitResult->floatParsFinal()[1]); - - if (tryRecover != 0.) { - EXPECT_EQ(fitResult->status(), 0) << "Recovery strength=" << tryRecover; - EXPECT_NEAR(a1Final.getVal(), static_cast(paramsInit["a1"]).getVal(), a1Final.getError()) << "Recovery strength=" << tryRecover; - EXPECT_NEAR(a2Final.getVal(), static_cast(paramsInit["a2"]).getVal(), a2Final.getError()) << "Recovery strength=" << tryRecover; - EXPECT_NEAR(a1Final.getVal() + a2Final.getVal(), 0.8, 0.02) << "Check that coefficients sum to 1. " << "Recovery strength=" << tryRecover; - } else { - EXPECT_TRUE(a1Final.getVal() < 0. || a1Final.getVal() > 1. || a2Final.getVal() < 0. || a2Final.getVal() > 1.) << "Recovery strength=" << tryRecover; - } - - if (verbose) { - std::cout << "Recovery strength:" << tryRecover << "\n"; - fitResult->Print(); - } - } - - // This makes clang-tidy happy: - ASSERT_NE(fitResult1, nullptr); - ASSERT_NE(fitResult2, nullptr); - if (fitResult1 && fitResult2) { // makes clang-tidy happy - EXPECT_LT(fitResult1->numInvalidNLL(), fitResult2->numInvalidNLL()); - } +TEST(RooNaNPacker, FitAddPdf_DegenerateCoeff) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + constexpr bool verbose = false; + RooRandom::randomGenerator()->SetSeed(100); + + RooRealVar x("x", "x", 0., 10); + RooRealVar a1("a1", "a1", 0.4, -10., 10.); + RooRealVar a2("a2", "a2", 0.4, -10., 10.); + RooGenericPdf pdf1("gen1", "exp(-2.*x)", {x}); + RooGenericPdf pdf2("gen2", "TMath::Gaus(x, 3, 2)", {x}); + RooGenericPdf pdf3("gen3", "x*x*x+1", {x}); + RooAddPdf pdf("sum", "a1*gen1 + a2*gen2 + (1-a1-a2)*gen3", {pdf1, pdf2, pdf3}, {a1, a2}); + std::unique_ptr data(pdf.generate(x, 2000)); + std::unique_ptr nll{pdf.createNLL(*data)}; + + RooArgSet params(a1, a2); + RooArgSet paramsInit; + params.snapshot(paramsInit); + + RooArgSet evilValues; + a1.setVal(0.6); + a2.setVal(0.7); + params.snapshot(evilValues); + + params.assign(evilValues); + + std::unique_ptr fitResult1; + std::unique_ptr fitResult2; + for (auto tryRecover : std::initializer_list{0., 10.}) { + params.assign(evilValues); + + RooMinimizer::cleanup(); + RooMinimizer minim(*nll); + minim.setRecoverFromNaNStrength(tryRecover); + minim.setPrintLevel(-1); + minim.setPrintEvalErrors(-1); + minim.migrad(); + std::unique_ptr fitResult{minim.save()}; + + const auto &a1Final = static_cast(fitResult->floatParsFinal()[0]); + const auto &a2Final = static_cast(fitResult->floatParsFinal()[1]); + + // Only the fit with error recovery should have status zero. + EXPECT_EQ(fitResult->status() == 0, tryRecover != 0.0); + + if (tryRecover != 0.) { + EXPECT_EQ(fitResult->status(), 0) << "Recovery strength=" << tryRecover; + EXPECT_NEAR(a1Final.getVal(), static_cast(paramsInit["a1"]).getVal(), a1Final.getError()) + << "Recovery strength=" << tryRecover; + EXPECT_NEAR(a2Final.getVal(), static_cast(paramsInit["a2"]).getVal(), a2Final.getError()) + << "Recovery strength=" << tryRecover; + EXPECT_NEAR(a1Final.getVal() + a2Final.getVal(), 0.8, 0.02) << "Check that coefficients sum to 1. " + << "Recovery strength=" << tryRecover; + } + + if (verbose) { + std::cout << "Recovery strength:" << tryRecover << "\n"; + fitResult->Print(); + } + + (tryRecover != 0. ? fitResult1 : fitResult2) = std::move(fitResult); + } + + // This makes clang-tidy happy: + ASSERT_NE(fitResult1, nullptr); + ASSERT_NE(fitResult2, nullptr); } /// Make coefficients of RooRealSumPdf sum to more than 1. Fitter should recover from this. -TEST(RooNaNPacker, Interface_RooAbsPdf_fitTo_RooRealSumPdf_DegenerateCoeff) { - constexpr bool verbose = false; - RooRandom::randomGenerator()->SetSeed(100); - - RooRealVar x("x", "x", 0., 10); - RooRealVar a1("a1", "a1", 0.3, -10., 10.); - RooRealVar a2("a2", "a2", 0.4, -10., 10.); - RooGenericPdf pdf1("gen1", "exp(-0.5*x)", RooArgSet(x)); - RooGenericPdf pdf2("gen2", "TMath::Gaus(x, 5, 0.7)", RooArgSet(x)); - RooGenericPdf pdf3("gen3", "TMath::Gaus(x, 8, 0.8)", RooArgSet(x)); - RooRealSumPdf pdf("sum", "a1*gen1 + a2*gen2 + (1-a1-a2)*gen3", RooArgList(pdf1, pdf2, pdf3), RooArgList(a1, a2)); - std::unique_ptr data(pdf.generate(x, 5000)); - - RooArgSet params(a1, a2); - RooArgSet paramsInit; - params.snapshot(paramsInit); - - RooArgSet evilValues; - a1.setVal(0.6); - a2.setVal(0.7); - params.snapshot(evilValues); - - params.assign(evilValues); - - RooFitResult *fitResult1 = nullptr, *fitResult2 = nullptr; - for (auto tryRecover : std::initializer_list{0., 10.}) { - params.assign(evilValues); - - auto fitResult = pdf.fitTo(*data, RooFit::PrintLevel(-1), RooFit::PrintEvalErrors(-1), RooFit::Save(), RooFit::RecoverFromUndefinedRegions(tryRecover)); - (tryRecover != 0. ? fitResult1 : fitResult2) = fitResult; - - const auto& a1Final = static_cast(fitResult->floatParsFinal()[0]); - const auto& a2Final = static_cast(fitResult->floatParsFinal()[1]); - - if (tryRecover != 0.) { - EXPECT_EQ(fitResult->status(), 0) << "Recovery strength=" << tryRecover; - EXPECT_NEAR(a1Final.getVal(), static_cast(paramsInit["a1"]).getVal(), 3.*a1Final.getError()) << "Recovery strength=" << tryRecover; - EXPECT_NEAR(a2Final.getVal(), static_cast(paramsInit["a2"]).getVal(), 3.*a2Final.getError()) << "Recovery strength=" << tryRecover; - EXPECT_GE(a1Final.getVal() + a2Final.getVal(), 0.) << "Check that coefficients are in [0, 1]. " << "Recovery strength=" << tryRecover; - EXPECT_LE(a1Final.getVal() + a2Final.getVal(), 1.) << "Check that coefficients sum to [0, 1]. " << "Recovery strength=" << tryRecover; - } else { - EXPECT_TRUE(a1Final.getVal() < 0. || a1Final.getVal() > 1. || a2Final.getVal() < 0. || a2Final.getVal() > 1.) << "Recovery strength=" << tryRecover; - } - - if (verbose) { - std::cout << "Recovery strength:" << tryRecover << "\n"; - fitResult->Print(); - } - } - - // This makes clang-tidy happy: - ASSERT_NE(fitResult1, nullptr); - ASSERT_NE(fitResult2, nullptr); - - if (fitResult1 && fitResult2) { // makes clang-tidy happy - EXPECT_LT(fitResult1->numInvalidNLL(), fitResult2->numInvalidNLL()); - } +TEST(RooNaNPacker, Interface_RooAbsPdf_fitTo_RooRealSumPdf_DegenerateCoeff) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + constexpr bool verbose = false; + RooRandom::randomGenerator()->SetSeed(100); + + RooRealVar x("x", "x", 0., 10); + RooRealVar a1("a1", "a1", 0.3, -10., 10.); + RooRealVar a2("a2", "a2", 0.4, -10., 10.); + RooGenericPdf pdf1("gen1", "exp(-0.5*x)", {x}); + RooGenericPdf pdf2("gen2", "TMath::Gaus(x, 5, 0.7)", {x}); + RooGenericPdf pdf3("gen3", "TMath::Gaus(x, 8, 0.8)", {x}); + RooRealSumPdf pdf("sum", "a1*gen1 + a2*gen2 + (1-a1-a2)*gen3", {pdf1, pdf2, pdf3}, {a1, a2}); + std::unique_ptr data(pdf.generate(x, 5000)); + + RooArgSet params(a1, a2); + RooArgSet paramsInit; + params.snapshot(paramsInit); + + RooArgSet evilValues; + a1.setVal(0.6); + a2.setVal(0.7); + params.snapshot(evilValues); + + params.assign(evilValues); + + std::unique_ptr fitResult1; + std::unique_ptr fitResult2; + for (auto tryRecover : std::initializer_list{0., 10.}) { + params.assign(evilValues); + + using namespace RooFit; + // Note: we can't do Hesse here. Without the error recovery, Minuit2 + // would print errors that would cause the unit test to fail. + std::unique_ptr fitResult{pdf.fitTo(*data, PrintLevel(-1), PrintEvalErrors(-1), Save(), + RecoverFromUndefinedRegions(tryRecover), Hesse(false))}; + + const auto &a1Final = static_cast(fitResult->floatParsFinal()[0]); + const auto &a2Final = static_cast(fitResult->floatParsFinal()[1]); + + // Only the fit with error recovery should have status zero. + EXPECT_EQ(fitResult->status() == 0, tryRecover != 0.0); + + if (tryRecover != 0.) { + EXPECT_EQ(fitResult->status(), 0) << "Recovery strength=" << tryRecover; + EXPECT_NEAR(a1Final.getVal(), static_cast(paramsInit["a1"]).getVal(), 3. * a1Final.getError()) + << "Recovery strength=" << tryRecover; + EXPECT_NEAR(a2Final.getVal(), static_cast(paramsInit["a2"]).getVal(), 3. * a2Final.getError()) + << "Recovery strength=" << tryRecover; + EXPECT_GE(a1Final.getVal() + a2Final.getVal(), 0.) << "Check that coefficients are in [0, 1]. " + << "Recovery strength=" << tryRecover; + EXPECT_LE(a1Final.getVal() + a2Final.getVal(), 1.) << "Check that coefficients sum to [0, 1]. " + << "Recovery strength=" << tryRecover; + } + + if (verbose) { + std::cout << "Recovery strength:" << tryRecover << "\n"; + fitResult->Print(); + } + + (tryRecover != 0. ? fitResult1 : fitResult2) = std::move(fitResult); + } + + // This makes clang-tidy happy: + ASSERT_NE(fitResult1, nullptr); + ASSERT_NE(fitResult2, nullptr); } - diff --git a/roofit/roofitcore/test/testProxiesAndCategories.cxx b/roofit/roofitcore/test/testProxiesAndCategories.cxx index f20f50bee6b7b..6c710e3059e9d 100644 --- a/roofit/roofitcore/test/testProxiesAndCategories.cxx +++ b/roofit/roofitcore/test/testProxiesAndCategories.cxx @@ -14,12 +14,7 @@ #include "TFile.h" #include "TMemFile.h" -#include "gtest/gtest.h" - -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif +#include "gtest_wrapper.h" TEST(RooCategory, CategoryDefineMultiState) { RooCategory myCat("myCat", "A category", { {"0Lep", 0}, {"1Lep", 1}, {"2Lep", 2}, {"3Lep", 3} }); @@ -212,7 +207,7 @@ TEST(RooTemplateProxy, CategoryProxy) { EXPECT_TRUE(dummy.cat == 2); EXPECT_STREQ(dummy.cat.label(), "B"); - dummy.cat = longStr.c_str(); + dummy.cat = longStr; EXPECT_TRUE(dummy.isValueDirty()); dummy.clear(); EXPECT_TRUE(dummy.cat == 500); diff --git a/roofit/roofitcore/test/testRooAbsCollection.cxx b/roofit/roofitcore/test/testRooAbsCollection.cxx index adc5f6134937a..504d7af594335 100644 --- a/roofit/roofitcore/test/testRooAbsCollection.cxx +++ b/roofit/roofitcore/test/testRooAbsCollection.cxx @@ -80,13 +80,13 @@ TEST(RooArgSet, InsertAndDeduplicate) { RooArgList list2; for (unsigned int i = 0; i < 4; ++i) { char name[] = {char('a'+i), '\0'}; - list.addOwned(*(new RooRealVar(name, name, 0.))); + list.addOwned(std::make_unique(name, name, 0.)); } for (unsigned int i = 0; i < 5; ++i) { char name[] = {char('a'+i), '\0'}; - list2.addOwned(*(new RooRealVar(name, name, 0.))); + list2.addOwned(std::make_unique(name, name, 0.)); name[0] = char('a'+ 4 - i); - list2.addOwned(*(new RooRealVar(name, name, 0.))); + list2.addOwned(std::make_unique(name, name, 0.)); } // Silence deduplication error messages @@ -112,13 +112,13 @@ TEST(RooArgSet, HashAssistedFind) { RooArgList list2; for (unsigned int i = 0; i < 4; ++i) { char name[] = {char('a'+i), '\0'}; - list.addOwned(*(new RooRealVar(name, name, 0.))); + list.addOwned(std::make_unique(name, name, 0.)); } for (unsigned int i = 0; i < 5; ++i) { char name[] = {char('a'+i), '\0'}; - list2.addOwned(*(new RooRealVar(name, name, 0.))); + list2.addOwned(std::make_unique(name, name, 0.)); name[0] = char('a'+ 4 - i); - list2.addOwned(*(new RooRealVar(name, name, 0.))); + list2.addOwned(std::make_unique(name, name, 0.)); } // Silence deduplication error messages diff --git a/roofit/roofitcore/test/testRooAbsPdf.cxx b/roofit/roofitcore/test/testRooAbsPdf.cxx index c913bf530939a..64a1f3976110c 100644 --- a/roofit/roofitcore/test/testRooAbsPdf.cxx +++ b/roofit/roofitcore/test/testRooAbsPdf.cxx @@ -10,32 +10,48 @@ #include #include #include -#include #include #include -#include #include #include #include #include -#include #include +#include #include #include -#include +#include "gtest_wrapper.h" #include +class FitTest : public testing::TestWithParam> { +public: + FitTest() : _evalBackend{RooFit::EvalBackend::Legacy()} {} + +private: + void SetUp() override + { + RooRandom::randomGenerator()->SetSeed(1337ul); + _evalBackend = std::get<0>(GetParam()); + _changeMsgLvl = std::make_unique(RooFit::WARNING); + } + + void TearDown() override { _changeMsgLvl.reset(); } + +protected: + RooFit::EvalBackend _evalBackend; + +private: + std::unique_ptr _changeMsgLvl; +}; + // ROOT-10668: Asympt. correct errors don't work when title and name differ -TEST(RooAbsPdf, AsymptoticallyCorrectErrors) +TEST_P(FitTest, AsymptoticallyCorrectErrors) { using namespace RooFit; - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); - RooRealVar x("x", "xxx", 0, 0, 10); RooRealVar a("a", "aaa", 2, 0, 10); // Cannot play with RooAbsPdf, since abstract. @@ -45,17 +61,16 @@ TEST(RooAbsPdf, AsymptoticallyCorrectErrors) std::unique_ptr data(pdf.generate(x, 5000)); data->addColumn(formula); RooRealVar w("w", "weight", 1, 0, 20); - RooDataSet weightedData("weightedData", "weightedData", {x, w}, Import(*data), - WeightVar(w)); + RooDataSet weightedData("weightedData", "weightedData", {x, w}, Import(*data), WeightVar(w)); ASSERT_TRUE(weightedData.isWeighted()); weightedData.get(0); ASSERT_NE(weightedData.weight(), 1); a = 1.2; - auto result = pdf.fitTo(weightedData, Save(), AsymptoticError(true), PrintLevel(-1)); + auto result = pdf.fitTo(weightedData, Save(), AsymptoticError(true), PrintLevel(-1), _evalBackend); a = 1.2; - auto result2 = pdf.fitTo(weightedData, Save(), SumW2Error(false), PrintLevel(-1)); + auto result2 = pdf.fitTo(weightedData, Save(), SumW2Error(false), PrintLevel(-1), _evalBackend); // Set relative tolerance for errors to large value to only check for values EXPECT_TRUE(result->isIdenticalNoCov(*result2, 1e-6, 10.0)) << "Fit results should be very similar."; @@ -98,7 +113,7 @@ TEST(RooAbsPdf, ConditionalFitBatchMode) for (int i = 0; i < 10000; i++) { double tmpy = gRandom->Gaus(3, 2); double tmpx = gRandom->Poisson(tmpy); - if (fabs(tmpy) > 1 && fabs(tmpy) < 5 && fabs(tmpx) < 10) { + if (std::abs(tmpy) > 1 && std::abs(tmpy) < 5 && std::abs(tmpx) < 10) { x = tmpx; y = tmpy; d->add(coord); @@ -110,30 +125,31 @@ TEST(RooAbsPdf, ConditionalFitBatchMode) auto data = makeFakeDataXY(); - RooRealVar x("x", "x", 0, 10); - RooRealVar y("y", "y", 1.0, 5); + RooWorkspace ws; + ws.factory("Product::mean1({factor[1.0, 0.0, 10.0], y[1.0, 5]})"); + ws.factory("Product::mean2({factor})"); + ws.factory("Poisson::model1(x[0, 10], mean1)"); + ws.factory("Poisson::model2(x, mean2)"); - RooRealVar factor("factor", "factor", 1.0, 0.0, 10.0); + RooRealVar &factor = *ws.var("factor"); + RooRealVar &y = *ws.var("y"); - std::vector means{{"mean", "mean", {factor, y}}, {"mean", "mean", {factor}}}; std::vector expectFastEvaluationsWarnings{true, false}; int iMean = 0; - for (auto &mean : means) { - - RooPoisson model("model", "model", x, mean); + for (RooAbsPdf *model : {ws.pdf("model1"), ws.pdf("model2")}) { std::vector> fitResults; RooHelpers::HijackMessageStream hijack(RooFit::INFO, RooFit::FastEvaluations); - for (bool batchMode : {false, true}) { + for (auto evalBackend : {EvalBackend::Legacy(), EvalBackend::Cpu()}) { factor.setVal(1.0); factor.setError(0.0); - fitResults.emplace_back( - model.fitTo(*data, ConditionalObservables(y), Save(), PrintLevel(-1), BatchMode(batchMode))); - if (verbose) + fitResults.emplace_back(model->fitTo(*data, ConditionalObservables(y), Save(), PrintLevel(-1), evalBackend)); + if (verbose) { fitResults.back()->Print(); + } } EXPECT_TRUE(fitResults[1]->isIdentical(*fitResults[0])); @@ -145,28 +161,30 @@ TEST(RooAbsPdf, ConditionalFitBatchMode) } // ROOT-9530: RooFit side-band fit inconsistent with fit to full range -TEST(RooAbsPdf, MultiRangeFit) +TEST_P(FitTest, MultiRangeFit) { using namespace RooFit; - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); - RooRealVar x("x", "x", -10, 10); + RooWorkspace ws; + + ws.factory("Gaussian::model_simple(x[-10., 10.], mean[-1, -10, 10], width[3, 0.1, 10])"); + // model for extended fit + ws.factory("AddPdf::model_extended({model_simple}, {nsig[100, 0, 2000]})"); + + auto &x = *ws.var("x"); + auto &mean = *ws.var("mean"); + auto &width = *ws.var("width"); + auto &nsig = *ws.var("nsig"); + + RooAbsPdf &modelSimple = *ws.pdf("model_simple"); + RooAbsPdf &modelExtended = *ws.pdf("model_extended"); - double cut = -5; + const double cut = -5; x.setRange("full", -10, 10); x.setRange("low", -10, cut); x.setRange("high", cut, 10); - RooRealVar mean("mean", "mean", -1, -10, 10); - RooRealVar width("width", "width", 3., 0.1, 10); - RooGaussian modelSimple("model_simple", "model_simple", x, mean, width); - - std::size_t nEvents = 100; - - // model for extended fit - RooRealVar nsig("nsig", "nsig", nEvents, 0., 2000); - RooAddPdf modelExtended("model_extended", "model_simple+a", RooArgList(modelSimple), RooArgList(nsig)); + const std::size_t nEvents = nsig.getVal(); auto resetValues = [&]() { mean.setVal(-1); @@ -177,34 +195,57 @@ TEST(RooAbsPdf, MultiRangeFit) nsig.setError(0.0); }; - // loop over non-extended and extended fit - for (auto *model : {static_cast(&modelSimple), static_cast(&modelExtended)}) { + std::unique_ptr dataSet{modelSimple.generate(x, nEvents)}; + std::unique_ptr dataHist{static_cast(*dataSet).binnedClone()}; - std::unique_ptr dataSet{model->generate(x, nEvents)}; - std::unique_ptr dataHist{dataSet->binnedClone()}; + // loop over non-extended and extended fit + for (auto *model : {&modelSimple, &modelExtended}) { // loop over binned fit and unbinned fit - for (auto *data : {static_cast(dataSet.get()), static_cast(dataHist.get())}) { + for (auto *data : {dataSet.get(), dataHist.get()}) { // full range resetValues(); - std::unique_ptr fitResultFull{model->fitTo(*data, Range("full"), Save(), PrintLevel(-1))}; + std::unique_ptr fitResultFull{ + model->fitTo(*data, Range("full"), Save(), PrintLevel(-1), _evalBackend)}; // part (side band fit, but the union of the side bands is the full range) resetValues(); - std::unique_ptr fitResultPart{model->fitTo(*data, Range("low,high"), Save(), PrintLevel(-1))}; + std::unique_ptr fitResultPart{ + model->fitTo(*data, Range("low,high"), Save(), PrintLevel(-1), _evalBackend)}; EXPECT_TRUE(fitResultPart->isIdentical(*fitResultFull)) << "Results of fitting " << model->GetName() << " to a " << data->ClassName() << " should be very similar."; } } + + // If the BatchMode is off, we are doing the same cross-check also with the + // chi-square fit on the RooDataHist. + if (_evalBackend == EvalBackend::Legacy()) { + + auto &dh = static_cast(*dataHist); + + // loop over non-extended and extended fit + for (auto *model : {&modelSimple, &modelExtended}) { + + // full range + resetValues(); + std::unique_ptr fitResultFull{model->chi2FitTo(dh, Range("full"), Save(), PrintLevel(-1))}; + + // part (side band fit, but the union of the side bands is the full range) + resetValues(); + std::unique_ptr fitResultPart{model->chi2FitTo(dh, Range("low,high"), Save(), PrintLevel(-1))}; + + EXPECT_TRUE(fitResultPart->isIdentical(*fitResultFull)) + << "Results of fitting " << model->GetName() + << " to a RooDataHist should be very similar also for chi2FitTo()."; + } + } } // ROOT-9530: RooFit side-band fit inconsistent with fit to full range (2D case) -TEST(RooAbsPdf, MultiRangeFit2D) +TEST_P(FitTest, MultiRangeFit2D) { using namespace RooFit; - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); // model taken from the rf312_multirangefit.C tutorial RooWorkspace ws; @@ -261,61 +302,72 @@ TEST(RooAbsPdf, MultiRangeFit2D) for (auto *data : {static_cast(dataSet.get()), static_cast(dataHist.get())}) { // full range resetValues(); - std::unique_ptr fitResultFull{model.fitTo(*data, Range("FULL"), Save(), PrintLevel(-1))}; + std::unique_ptr fitResultFull{ + model.fitTo(*data, Range("FULL"), Save(), PrintLevel(-1), _evalBackend)}; // part (side band fit, but the union of the side bands is the full range) resetValues(); - std::unique_ptr fitResultPart{model.fitTo(*data, Range("SB1,SB2,SIG"), Save(), PrintLevel(-1))}; + std::unique_ptr fitResultPart{ + model.fitTo(*data, Range("SB1,SB2,SIG"), Save(), PrintLevel(-1), _evalBackend)}; EXPECT_TRUE(fitResultPart->isIdentical(*fitResultFull)) << "Results of fitting " << model.GetName() << " to a " << data->ClassName() << " should be very similar."; } + + // If the BatchMode is off, we are doing the same cross-check also with the + // chi-square fit on the RooDataHist. + if (_evalBackend.name() == EvalBackend::Legacy().name()) { + + // full range + resetValues(); + std::unique_ptr fitResultFull{ + model.fitTo(*dataHist, Range("FULL"), Save(), PrintLevel(-1), _evalBackend)}; + + // part (side band fit, but the union of the side bands is the full range) + resetValues(); + std::unique_ptr fitResultPart{ + model.fitTo(*dataHist, Range("SB1,SB2,SIG"), Save(), PrintLevel(-1), _evalBackend)}; + + EXPECT_TRUE(fitResultPart->isIdentical(*fitResultFull)) + << "Results of fitting " << model.GetName() + << " to a RooDataHist should be very similar also for chi2FitTo()."; + } } // This test will crash if the cached normalization sets are not reset // correctly after servers are redirected. This is a reduced version of a code // provided in the ROOT forum that originally unveiled this problem: // https://root-forum.cern.ch/t/problems-with-2d-simultaneous-fit/48249/4 -TEST(RooAbsPdf, ProblemsWith2DSimultaneousFit) +TEST_P(FitTest, ProblemsWith2DSimultaneousFit) { using namespace RooFit; - RooRealVar x("x", "y", 1.0, 2.); - RooRealVar y("y", "y", 1.0, 2.); - - RooRealVar mu1("mu1", "mu1", 2., 0, 5); - - RooUniform uniform1("uniform1", "uniform1", {x, y}); - RooUniform uniform2("uniform2", "uniform2", {x, y}); - - RooGaussian gauss1("gauss1", "gauss1", x, mu1, RooConst(0.1)); - RooGaussian gauss2("gauss2", "gauss2", x, mu1, RooConst(0.1)); - RooGaussian gauss3("gauss3", "gauss3", x, mu1, RooConst(0.1)); - - RooAddPdf gauss12("gauss12", "gauss12", gauss1, gauss2, RooConst(0.1)); - - RooAddPdf sig_x("sig_x", "sig_x", gauss3, gauss12, RooConst(0.1)); - - RooUniform sig_y("sig_y", "sig_y", y); - RooProdPdf sig("sig", "sig", sig_y, sig_x); - - RooRealVar yield{"yield", "yield", 100}; + RooWorkspace ws; + ws.factory("Uniform::uniform1({x[1.0, 2.], y[1.0, 2.]})"); + ws.factory("Uniform::uniform2({x, y})"); + ws.factory("Gaussian::gauss1(x, mu1[2., 0., 5.], 0.1)"); + ws.factory("Gaussian::gauss2(x, mu1[2., 0., 5.], 0.1)"); + ws.factory("Gaussian::gauss3(x, mu1[2., 0., 5.], 0.1)"); + ws.factory("AddPdf::gauss12(gauss1, gauss2, 0.1)"); + ws.factory("AddPdf::sig_x(gauss3, gauss12, 0.1)"); + ws.factory("Uniform::sig_y(y)"); + ws.factory("ProdPdf::sig(sig_y, sig_x)"); // Complete model - RooAddPdf model("model", "model", {sig, sig_y, uniform2, uniform1}, {yield, yield, yield, yield}); + ws.factory("AddPdf::model({sig, sig_y, uniform2, uniform1}, {yield[100], yield, yield, yield})"); // Define category to distinguish d0 and d0bar samples events RooCategory sample("sample", "sample", {{"cat0", 0}, {"cat1", 1}}); - // Construct a dummy dataset - RooDataSet data("data", "data", RooArgSet(sample, x, y)); - // Construct a simultaneous pdf using category sample as index RooSimultaneous simPdf("simPdf", "simultaneous pdf", sample); - simPdf.addPdf(model, "cat0"); - simPdf.addPdf(model, "cat1"); + simPdf.addPdf(*ws.pdf("model"), "cat0"); + simPdf.addPdf(*ws.pdf("model"), "cat1"); - simPdf.fitTo(data, PrintLevel(-1)); + // Construct a dummy dataset + std::unique_ptr data{simPdf.generate({sample, *ws.var("x"), *ws.var("y")})}; + + simPdf.fitTo(*data, PrintLevel(-1), _evalBackend); } // Verifies that a server pdf gets correctly reevaluated when the normalization @@ -324,8 +376,12 @@ TEST(RooAbsPdf, NormSetChange) { using namespace RooFit; - RooRealVar x("x", "x", 0, -10, 10); - RooGaussian gauss("gauss", "gauss", x, RooConst(0), RooConst(2)); + RooWorkspace ws; + ws.factory("Gaussian::gauss(x[0, -10, 10], 0., 2.)"); + + RooRealVar &x = *ws.var("x"); + RooAbsPdf &gauss = *ws.pdf("gauss"); + RooAddition add("add", "add", {gauss}); double v1 = add.getVal(); @@ -335,3 +391,10 @@ TEST(RooAbsPdf, NormSetChange) // value, so val2 should be different from val1. } EXPECT_NE(v1, v2); } + +INSTANTIATE_TEST_SUITE_P(RooAbsPdf, FitTest, testing::Values(RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu()), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "EvalBackend" << std::get<0>(paramInfo.param).name(); + return ss.str(); + }); diff --git a/roofit/roofitcore/test/testRooAddPdf.cxx b/roofit/roofitcore/test/testRooAddPdf.cxx index 4de3c9f33ac3f..ba1897c22082a 100644 --- a/roofit/roofitcore/test/testRooAddPdf.cxx +++ b/roofit/roofitcore/test/testRooAddPdf.cxx @@ -4,8 +4,9 @@ #include #include #include -#include -#include +#include +#include +#include #include #include #include @@ -13,12 +14,7 @@ #include -#include - -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif +#include "gtest_wrapper.h" #include @@ -28,90 +24,62 @@ /// is taken from the GitHub issue thread, with the plotting part removed. TEST(RooAddPdf, TestSPlot) { - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); - double lowRange = 0.; - double highRange = 200.; - RooRealVar invMass("invMass", "M_{inv}", lowRange, highRange, "GeV"); - RooRealVar isolation("isolation", "isolation", 0., 20., "GeV"); + RooWorkspace ws; // mass model: linear combination of two Gaussians of different widths - RooRealVar mZ("mZ", "Z Mass", 91.2, lowRange, highRange); - RooRealVar sigmaZ("sigmaZ", "Width of Gaussian", 2, 0.1, 10, "GeV"); - RooGaussian mZModel1("mZModel1", "Z+jets Model", invMass, mZ, sigmaZ); - - RooRealVar sigmaZ2("sigmaZ2", "Width of Gaussian", 1.5, 0.01, 10, "GeV"); - RooGaussian mZModel2("mZModel2", "Z+jets Model", invMass, mZ, sigmaZ2); - - RooRealVar frac_1a("frac_1a", "frac_1a", 0.5); // fraction of the first Gaussian - - RooArgList shapes_DCB; - shapes_DCB.add(mZModel1); - shapes_DCB.add(mZModel2); - - RooArgList yields_DCB; - yields_DCB.add(frac_1a); - - RooArgSet normSet(invMass); - - RooAddPdf mZModel("mZModel", "mZModel", shapes_DCB, yields_DCB); + ws.factory("Gaussian::mZModel1(invMass[0., 200.], mZ[91.2, 0., 200.], sigmaZ[2, 0.1, 10])"); + ws.factory("Gaussian::mZModel2(invMass[0., 200.], mZ[91.2, 0., 200.], sigmaZ2[1.5, 0.01, 10])"); + ws.factory("SUM::mZModel(frac_1a[0.5] * mZModel1, mZModel2)"); // isolation model for Z-boson. Only used to generate toy MC. - - RooConstVar zIsolDecayConst("zIsolDecayConst", "z isolation decay constant", -1); - RooExponential zIsolationModel("zIsolationModel", "z isolation model", isolation, zIsolDecayConst); + ws.factory("Exponential::zIsolationModel(isolation[0., 20.], zIsolDecayConst[-1])"); // make the combined Z model - RooProdPdf zModel("zModel", "2-d model for Z", {mZModel, zIsolationModel}); - - // make the QCD model + ws.factory("PROD::zModel(mZModel, zIsolationModel)"); // mass model for QCD. - - RooRealVar qcdMassDecayConst("qcdMassDecayConst", "Decay const for QCD mass spectrum", -0.01, -100, 100, "1/GeV"); - RooExponential qcdMassModel("qcdMassModel", "qcd Mass Model", invMass, qcdMassDecayConst); + ws.factory("Exponential::qcdMassModel(invMass, qcdMassDecayConst[-0.01, -100, 100])"); // isolation model for QCD. - RooConstVar qcdIsolDecayConst("qcdIsolDecayConst", "Et resolution constant", -.1); - RooExponential qcdIsolationModel("qcdIsolationModel", "QCD isolation model", isolation, qcdIsolDecayConst); - - // make the 2D model - RooProdPdf qcdModel("qcdModel", "2-d model for QCD", {qcdMassModel, qcdIsolationModel}); + ws.factory("Exponential::qcdIsolationModel(isolation, qcdIsolDecayConst[-0.1])"); - // -------------------------------------- - // combined model - - // These variables represent the number of Z or QCD events - // They will be fitted. - RooRealVar zYield("zYield", "fitted yield for Z", 300, 0., 10000); - RooRealVar qcdYield("qcdYield", "fitted yield for QCD", 2700, 0., 10000); + // make the 2D QCD model + ws.factory("PROD::qcdModel(qcdMassModel, qcdIsolationModel)"); // now make the combined model // this is the 2D model for generation only - RooAddPdf model_gen("model_gen", "mygreatmodel_gen", {zModel, qcdModel}, {zYield, qcdYield}); + ws.factory("SUM::model_gen(zYield[300, 0., 10000] * zModel, qcdYield[2700, 0., 10000] * qcdModel)"); // this is the mass model for the fit only - RooAddPdf model("model", "mygreatmodel", {mZModel, qcdMassModel}, {zYield, qcdYield}); + ws.factory("SUM::model(zYield[300, 0., 10000] * mZModel, qcdYield[2700, 0., 10000] * qcdMassModel)"); + + RooRealVar &invMass = *ws.var("invMass"); + RooRealVar &isolation = *ws.var("isolation"); + RooRealVar &zYield = *ws.var("zYield"); + RooRealVar &qcdYield = *ws.var("qcdYield"); + RooAbsPdf &model_gen = *ws.pdf("model_gen"); + RooAbsPdf &model = *ws.pdf("model"); - int nEvents = zYield.getVal() + qcdYield.getVal(); + RooArgSet normSet{invMass}; // make the toy data - std::unique_ptr data{model_gen.generate({invMass, isolation}, nEvents, RooFit::Name("mygendataset"))}; + std::unique_ptr data{model_gen.generate({invMass, isolation}, RooFit::Name("mygendataset"))}; // fit the model to the data. model.fitTo(*data, RooFit::Extended(), RooFit::PrintLevel(-1)); - double valYieldBefore = zYield.getVal(); + const double valYieldBefore = zYield.getVal(); // fix the parameters that are not yields before doing the sPlot - qcdMassDecayConst.setConstant(true); - sigmaZ.setConstant(true); - sigmaZ2.setConstant(true); - mZ.setConstant(true); + ws.var("qcdMassDecayConst")->setConstant(true); + ws.var("sigmaZ")->setConstant(true); + ws.var("sigmaZ2")->setConstant(true); + ws.var("mZ")->setConstant(true); RooStats::SPlot("sData", "An SPlot", *data, &model, {zYield, qcdYield}); - double valYieldAfter = zYield.getVal(); + const double valYieldAfter = zYield.getVal(); EXPECT_NEAR(valYieldAfter, valYieldBefore, 1e-1) << "Doing the SPlot should not change parameter values by orders of magnitudes!"; @@ -121,8 +89,7 @@ TEST(RooAddPdf, TestSPlot) /// issues of RooAddPdf integrals. TEST(RooAddPdf, Issue10988) { - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); using namespace RooFit; @@ -139,7 +106,7 @@ TEST(RooAddPdf, Issue10988) auto &x2 = *w2.var("x"); // Call createIntegral on workspace w1 only. It's important that this - // integral lives longer than "interal1" to reproduce the problem. + // integral lives longer than "integral1" to reproduce the problem. std::unique_ptr integral0{pdf1.createIntegral(x1, NormSet(x1), Range("range_int"))}; double val0 = integral0->getVal(); @@ -153,7 +120,7 @@ TEST(RooAddPdf, Issue10988) std::unique_ptr integral2{pdf2.createIntegral(x2, NormSet(x2), Range("range_int"))}; double val2 = integral2->getVal(); - // Check that the integrals have differnt values, now that the coefficient + // Check that the integrals have different values, now that the coefficient // range was fixed to a different one. EXPECT_NE(val0, val1); EXPECT_EQ(val1, val2); @@ -193,12 +160,19 @@ TEST(RooAddPdf, RecursiveCoefficients) } class ProjCacheTest : public testing::TestWithParam> { - void SetUp() override { _fixCoefNormalization = std::get<0>(GetParam()); } + void SetUp() override + { + _fixCoefNormalization = std::get<0>(GetParam()); + _changeMsgLvl = std::make_unique(RooFit::WARNING); + } - void TearDown() override {} + void TearDown() override { _changeMsgLvl.reset(); } protected: bool _fixCoefNormalization = false; + +private: + std::unique_ptr _changeMsgLvl; }; /// Verify that the coefficient projection works for different configurations @@ -254,6 +228,8 @@ TEST(RooAddPdf, ResetServerNormRange) { using namespace RooFit; + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooWorkspace ws; ws.factory("PROD::sig(Polynomial(x[-10, 10], {0.0, 0.0, 1.0}, 0), Polynomial(y[-10, 10], {}))"); ws.factory("PROD::bkg(Polynomial(x, {}), Polynomial(y, {}))"); @@ -298,7 +274,7 @@ TEST(RooAddPdf, ResetServerNormRange) } // We first use the same normalization set to re-evaluate, then a different - // one to confuse to first trigger the chache and then have a another + // one to confuse to first trigger the cache and then have a another // reference. const double val2 = model.getVal(normSet1); const double val3 = model.getVal(normSet2); @@ -320,6 +296,8 @@ TEST(RooAddPdf, ResetServerNormRange) /// https://sft.its.cern.ch/jira/browse/ROOT-10483. TEST(RooAddPdf, ROOT10483) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooWorkspace ws; // Create model @@ -365,3 +343,42 @@ TEST(RooAddPdf, ROOT10483) // sampled from the model. EXPECT_LE(frame->chiSquare(), 1.0); } + +/// If you add components where each component only depends on a subset of the +/// union set of the observables, the RooAddPdf should understand that the +/// component is uniform in the missing observables. This is validated in the +/// following test for both the getVal() interface and evaluation with the +/// RooFit::Evaluator. +TEST(RooAddPdf, ImplicitDimensions) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + using namespace RooFit; + + RooRealVar x{"x", "x", 5, 0, 10}; + RooRealVar y{"y", "y", 5, 0, 10}; + + // Define the PDFs such that they explicitly depend on only one of the + // observables each. This means the RooAddPdf needs to figure out itself + // that in the other dimensions (y for uniformX and x for uniformY), the + // distribution is implicitly uniform. + RooGenericPdf uniformX{"uniform_x", "x - x + 1.0", x}; + RooGenericPdf uniformY{"uniform_y", "y - y + 1.0", y}; + + RooAddPdf pdf{"pdf", "pdf", {uniformX, uniformY}, {RooConst(0.5)}}; + + RooArgSet normSet{x, y}; + + std::unique_ptr pdfCompiled{RooFit::Detail::compileForNormSet(pdf, normSet)}; + RooFit::Evaluator evaluator{*pdfCompiled}; + + pdf.fixAddCoefNormalization(normSet); + pdfCompiled->fixAddCoefNormalization(normSet); + + // A uniform distribution in x and y should have this value everywhere, + // given our limits for x and y. + const double refVal = 0.01; + + EXPECT_DOUBLE_EQ(pdf.getVal(normSet), refVal); + EXPECT_DOUBLE_EQ(evaluator.run()[0], refVal); +} diff --git a/roofit/roofitcore/test/testRooBinSamplingPdf.cxx b/roofit/roofitcore/test/testRooBinSamplingPdf.cxx index 0999a2cc727b3..479ee82b8e4a8 100644 --- a/roofit/roofitcore/test/testRooBinSamplingPdf.cxx +++ b/roofit/roofitcore/test/testRooBinSamplingPdf.cxx @@ -1,41 +1,53 @@ // Tests for the RooBinSamplingPdf // Authors: Jonas Rembser, CERN 03/2022 + +#include #include #include +#include +#include #include -#include +#include #include -#include -#include #include -#include -#include +#include "gtest_wrapper.h" #include +class ParamTest : public testing::TestWithParam> { + void SetUp() override + { + RooRandom::randomGenerator()->SetSeed(1337ul); + _batchMode = std::get<0>(GetParam()); + _changeMsgLvl = std::make_unique(RooFit::WARNING); + } + + void TearDown() override { _changeMsgLvl.reset(); } + +protected: + std::string _batchMode; + +private: + std::unique_ptr _changeMsgLvl; +}; + // For a linear pdf, doing the bin sampling should make no difference because // the integral of a linear function is the same as the central point. -TEST(RooBinSamplingPdf, LinearPdfCrossCheck) +TEST_P(ParamTest, LinearPdfCrossCheck) { using namespace RooFit; - auto& msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); RooRandom::randomGenerator()->SetSeed(1337ul); RooRealVar x("x", "x", 0.1, 5.1); x.setBins(10); - RooGenericPdf pdf("lin", "x", RooArgSet(x)); + RooGenericPdf pdf("lin", "x", {x}); std::unique_ptr dataH(pdf.generateBinned(x, 10000)); - RooRealVar w("w", "weight", 0., 0., 10000.); - RooDataSet data("data", "data", RooArgSet(x, w), RooFit::WeightVar(w)); - for (int i = 0; i < dataH->numEntries(); ++i) { - auto coords = dataH->get(i); - data.add(*coords, dataH->weight()); - } + RooDataSet data("data", "data", x, RooFit::Import(*dataH)); std::unique_ptr nll1(pdf.createNLL(data)); std::unique_ptr nll2(pdf.createNLL(data, IntegrateBins(1.E-3))); @@ -46,12 +58,11 @@ TEST(RooBinSamplingPdf, LinearPdfCrossCheck) // For a linear pdf, doing the bin sampling should make no difference because // the integral of a linear function is the same as the central point. // Similar to "LinearPdfCrossCheck", but this time for a subrange fit. -TEST(RooBinSamplingPdf, LinearPdfSubRangeCrossCheck) +TEST_P(ParamTest, LinearPdfSubRangeCrossCheck) { using namespace RooFit; - auto& msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); RooRandom::randomGenerator()->SetSeed(1337ul); @@ -60,14 +71,9 @@ TEST(RooBinSamplingPdf, LinearPdfSubRangeCrossCheck) x.setRange("range", 0.1, 4.1); x.setBins(8, "range"); // consistent binning - RooGenericPdf pdf("lin", "x", RooArgSet(x)); + RooGenericPdf pdf("lin", "x", {x}); std::unique_ptr dataH(pdf.generateBinned(x, 10000)); - RooRealVar w("w", "weight", 0., 0., 10000.); - RooDataSet data("data", "data", RooArgSet(x, w), RooFit::WeightVar(w)); - for (int i = 0; i < dataH->numEntries(); ++i) { - auto coords = dataH->get(i); - data.add(*coords, dataH->weight()); - } + RooDataSet data("data", "data", x, RooFit::Import(*dataH)); std::unique_ptr nll1(pdf.createNLL(data, Range("range"))); std::unique_ptr nll2(pdf.createNLL(data, Range("range"), IntegrateBins(1.E-3))); @@ -77,6 +83,8 @@ TEST(RooBinSamplingPdf, LinearPdfSubRangeCrossCheck) TEST(RooBinSamplingPdf, CheckConsistentNormalization) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooRealVar x("x", "x", 0, 10); RooRealVar mean1("mean1", "mean1", 4., 0, 10); RooRealVar mean2("mean2", "mean2", 6., 0, 10); @@ -85,8 +93,8 @@ TEST(RooBinSamplingPdf, CheckConsistentNormalization) RooArgSet normSet{x}; - RooGenericPdf gaus1("guas1", "gaus1", "std::exp(-0.5*(x - mean1)^2/width^2)", {x, mean1, width}); - RooGenericPdf gaus2("guas2", "gaus2", "std::exp(-0.5*(x - mean2)^2/width^2)", {x, mean2, width}); + RooGenericPdf gaus1("gauss1", "gauss1", "std::exp(-0.5*(x - mean1)^2/width^2)", {x, mean1, width}); + RooGenericPdf gaus2("gauss2", "gauss2", "std::exp(-0.5*(x - mean2)^2/width^2)", {x, mean2, width}); RooAddPdf pdf{"pdf", "pdf", {gaus1, gaus2}, {f}}; pdf.fixCoefNormalization(normSet); @@ -104,3 +112,10 @@ TEST(RooBinSamplingPdf, CheckConsistentNormalization) std::unique_ptr int3{binSamplingPdf.createIntegral(normSet)}; EXPECT_FLOAT_EQ(int2->getVal(), int3->getVal()); } + +INSTANTIATE_TEST_SUITE_P(RooBinSamplingPdf, ParamTest, testing::Values("Off", "Cpu"), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "BatchMode" << std::get<0>(paramInfo.param); + return ss.str(); + }); diff --git a/roofit/roofitcore/test/testRooDataHist.cxx b/roofit/roofitcore/test/testRooDataHist.cxx index b9767db8c8eb2..974d53547b5a5 100644 --- a/roofit/roofitcore/test/testRooDataHist.cxx +++ b/roofit/roofitcore/test/testRooDataHist.cxx @@ -12,18 +12,15 @@ #include "RooAbsArg.h" #include "RooDataSet.h" #include "RooRandom.h" +#include "RooFit/Detail/NormalizationHelpers.h" +#include "RooFit/Evaluator.h" #include "TH1D.h" #include "TH2D.h" #include "TMath.h" #include "TFile.h" -#include "gtest/gtest.h" - -// Backward compatibility for gtest version < 1.10.0 -#ifndef INSTANTIATE_TEST_SUITE_P -#define INSTANTIATE_TEST_SUITE_P INSTANTIATE_TEST_CASE_P -#endif +#include "gtest_wrapper.h" #include #include @@ -33,389 +30,389 @@ /// although the boundaries match perfectly. TEST(RooDataHist, BinningRangeCheck_8163) { - RooHelpers::HijackMessageStream hijack(RooFit::INFO, RooFit::DataHandling, "dataHist"); + RooHelpers::HijackMessageStream hijack(RooFit::INFO, RooFit::DataHandling, "dataHist"); - RooRealVar x("x", "x", 0., 1.); - TH1D hist("hist", "", 10, 0., 1.); + RooRealVar x("x", "x", 0., 1.); + TH1D hist("hist", "", 10, 0., 1.); - RooDataHist dataHist("dataHist", "", RooArgList(x), &hist); - EXPECT_TRUE(hijack.str().empty()) << "Messages issued were: " << hijack.str(); + RooDataHist dataHist("dataHist", "", RooArgList(x), &hist); + EXPECT_TRUE(hijack.str().empty()) << "Messages issued were: " << hijack.str(); } +double computePoissonUpper(double weight) +{ + double upperLimit = weight; + double CL; + do { + upperLimit += 0.001; + CL = 0.; + for (unsigned int i = 0; i <= (unsigned int)weight; ++i) { + CL += TMath::PoissonI(i, upperLimit); + } + // std::cout << "Upper=" << upperLimit << "\tCL=" << CL << std::endl; + } while (CL > 0.16); - -double computePoissonUpper(double weight) { - double upperLimit = weight; - double CL; - do { - upperLimit += 0.001; - CL = 0.; - for (unsigned int i = 0; i <= (unsigned int)weight; ++i) { - CL += TMath::PoissonI(i, upperLimit); - } -// std::cout << "Upper=" << upperLimit << "\tCL=" << CL << std::endl; - } while (CL > 0.16); - - return upperLimit; + return upperLimit; } -double computePoissonLower(double weight) { - double lowerLimit = weight; - double CL; - do { - CL = 0.; - lowerLimit -= 0.001; - for (unsigned int i = 0; i < (unsigned int)weight; ++i) { - CL += TMath::PoissonI(i, lowerLimit); - } - } while (CL < 1. - 0.16); - - return lowerLimit; +double computePoissonLower(double weight) +{ + double lowerLimit = weight; + double CL; + do { + CL = 0.; + lowerLimit -= 0.001; + for (unsigned int i = 0; i < (unsigned int)weight; ++i) { + CL += TMath::PoissonI(i, lowerLimit); + } + } while (CL < 1. - 0.16); + + return lowerLimit; } TEST(RooDataHist, UnWeightedEntries) { - RooRealVar x("x", "x", -10., 10.); - x.setBins(20); - RooRealVar w("w", "w", 0., 10.); - RooArgSet coordinates(x); - - constexpr double targetBinContent = 10.; - RooDataHist dataHist("dataHist", "", RooArgList(x)); - for (unsigned int i=0; i < 200; ++i) { - x.setVal(-10. + 20./200. * i); - dataHist.add(coordinates); - } - - EXPECT_EQ(dataHist.numEntries(), 20); - ASSERT_EQ(dataHist.sumEntries(), 20 * targetBinContent); - - x.setVal(0.); - RooArgSet* coordsAtZero = dataHist.get(coordinates)->snapshot(); - x.setVal(0.9); - RooArgSet* coordsAtPoint9 = dataHist.get(coordinates)->snapshot(); - EXPECT_EQ(static_cast(coordsAtZero->find(x))->getVal(), - static_cast(coordsAtPoint9->find(x))->getVal()); - - const double weight = dataHist.weight(); - EXPECT_EQ(weight, targetBinContent); - - EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), - sqrt(targetBinContent), 0.7); // TODO What is the actual value? - - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::Poisson); - EXPECT_LT(lo, hi); - EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); - EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); - } - - EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), - sqrt(targetBinContent), 1.E-14); - - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::SumW2); - EXPECT_NEAR(lo, sqrt(targetBinContent), 1.E-14); - EXPECT_NEAR(lo, sqrt(targetBinContent), 1.E-14); - EXPECT_EQ(lo, hi); - } - - - RooArgSet* coordsAt10 = dataHist.get(10)->snapshot(); - const double weightBin10 = dataHist.weight(); - - EXPECT_NEAR(static_cast(coordsAt10->find(x))->getVal(), 0.5, 1.E-1); - EXPECT_EQ(weight, weightBin10); -} + RooRealVar x("x", "x", -10., 10.); + x.setBins(20); + RooRealVar w("w", "w", 0., 10.); + RooArgSet coordinates(x); + + constexpr double targetBinContent = 10.; + RooDataHist dataHist("dataHist", "", RooArgList(x)); + for (unsigned int i = 0; i < 200; ++i) { + x.setVal(-10. + 20. / 200. * i); + dataHist.add(coordinates); + } + EXPECT_EQ(dataHist.numEntries(), 20); + ASSERT_EQ(dataHist.sumEntries(), 20 * targetBinContent); -TEST(RooDataHist, WeightedEntries) -{ - RooRealVar x("x", "x", -10., 10.); - x.setBins(20); - RooRealVar w("w", "w", 0., 10.); - RooArgSet coordinates(x); + x.setVal(0.); + RooArgSet coordsAtZero; + dataHist.get(coordinates)->snapshot(coordsAtZero); + x.setVal(0.9); + RooArgSet coordsAtPoint9; + dataHist.get(coordinates)->snapshot(coordsAtPoint9); + EXPECT_EQ(static_cast(coordsAtZero.find(x))->getVal(), + static_cast(coordsAtPoint9.find(x))->getVal()); - constexpr double targetBinContent = 20.; - RooDataHist dataHist("dataHist", "", RooArgList(x)); - for (unsigned int i=0; i < 200; ++i) { - x.setVal(-10. + 20./200. * i); - dataHist.add(coordinates, 2.); - } + const double weight = dataHist.weight(); + EXPECT_EQ(weight, targetBinContent); + EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), sqrt(targetBinContent), + 0.7); // TODO What is the actual value? - EXPECT_EQ(dataHist.numEntries(), 20); - EXPECT_EQ(dataHist.sumEntries(), 20 * targetBinContent); + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::Poisson); + EXPECT_LT(lo, hi); + EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); + EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); + } - x.setVal(0.); - dataHist.get(coordinates)->snapshot(); - const double weight = dataHist.weight(); - ASSERT_EQ(weight, targetBinContent); + EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), sqrt(targetBinContent), 1.E-14); + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::SumW2); + EXPECT_NEAR(lo, sqrt(targetBinContent), 1.E-14); + EXPECT_NEAR(lo, sqrt(targetBinContent), 1.E-14); + EXPECT_EQ(lo, hi); + } - const double targetError = sqrt(10*4.); + RooArgSet coordsAt10; + dataHist.get(10)->snapshot(coordsAt10); + const double weightBin10 = dataHist.weight(); - EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), - targetError, 1.5); // TODO What is the actual value? + EXPECT_NEAR(static_cast(coordsAt10.find(x))->getVal(), 0.5, 1.E-1); + EXPECT_EQ(weight, weightBin10); +} - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::Poisson); - EXPECT_LT(lo, hi); - EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); - EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); - } +TEST(RooDataHist, WeightedEntries) +{ + RooRealVar x("x", "x", -10., 10.); + x.setBins(20); + RooRealVar w("w", "w", 0., 10.); + RooArgSet coordinates(x); + + constexpr double targetBinContent = 20.; + RooDataHist dataHist("dataHist", "", RooArgList(x)); + for (unsigned int i = 0; i < 200; ++i) { + x.setVal(-10. + 20. / 200. * i); + dataHist.add(coordinates, 2.); + } - EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), - targetError, 1.E-14); + EXPECT_EQ(dataHist.numEntries(), 20); + EXPECT_EQ(dataHist.sumEntries(), 20 * targetBinContent); - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::SumW2); - EXPECT_NEAR(lo, targetError, 1.E-14); - EXPECT_NEAR(lo, targetError, 1.E-14); - EXPECT_EQ(lo, hi); - } + x.setVal(0.); + dataHist.get(coordinates); + const double weight = dataHist.weight(); + ASSERT_EQ(weight, targetBinContent); + const double targetError = sqrt(10 * 4.); - RooArgSet* coordsAt10 = dataHist.get(10)->snapshot(); - const double weightBin10 = dataHist.weight(); + EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), targetError, 1.5); // TODO What is the actual value? - EXPECT_NEAR(static_cast(coordsAt10->find(x))->getVal(), 0.5, 1.E-1); - EXPECT_EQ(weight, weightBin10); + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::Poisson); + EXPECT_LT(lo, hi); + EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); + EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); + } + + EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), targetError, 1.E-14); + + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::SumW2); + EXPECT_NEAR(lo, targetError, 1.E-14); + EXPECT_NEAR(lo, targetError, 1.E-14); + EXPECT_EQ(lo, hi); + } + + RooArgSet coordsAt10; + dataHist.get(10)->snapshot(coordsAt10); + const double weightBin10 = dataHist.weight(); + + EXPECT_NEAR(static_cast(coordsAt10.find(x))->getVal(), 0.5, 1.E-1); + EXPECT_EQ(weight, weightBin10); } -class RooDataHistIO : public testing::TestWithParam { +class RooDataHistIO : public testing::TestWithParam { public: - void SetUp() override { - TFile file(GetParam(), "READ"); - ASSERT_TRUE(file.IsOpen()); + void SetUp() override + { + TFile file(GetParam(), "READ"); + ASSERT_TRUE(file.IsOpen()); - file.GetObject("dataHist", legacy); - ASSERT_NE(legacy, nullptr); - } + legacy = std::unique_ptr{file.Get("dataHist")}; + ASSERT_NE(legacy, nullptr); + } - void TearDown() override { - delete legacy; - } + void TearDown() override { legacy.reset(); } protected: - RooDataHist* legacy{nullptr}; + std::unique_ptr legacy; }; -TEST_P(RooDataHistIO, ReadLegacy) { - - RooDataHist& dataHist = *legacy; - - constexpr double targetBinContent = 20.; - - RooArgSet* legacyVals = dataHist.get(10)->snapshot(); - EXPECT_EQ(static_cast(legacyVals->find("x"))->getVal(), - static_cast(dataHist.get(10)->find("x"))->getVal()); +TEST_P(RooDataHistIO, ReadLegacy) +{ + RooDataHist &dataHist = *legacy; - EXPECT_EQ(dataHist.numEntries(), 20); - EXPECT_EQ(dataHist.sumEntries(), 20 * targetBinContent); + constexpr double targetBinContent = 20.; - static_cast(legacyVals->find("x"))->setVal(0.); - dataHist.get(*legacyVals); // trigger side effect for weight below. - const double weight = dataHist.weight(); - ASSERT_EQ(weight, targetBinContent); + RooArgSet legacyVals; + dataHist.get(10)->snapshot(legacyVals); + EXPECT_EQ(static_cast(legacyVals.find("x"))->getVal(), + static_cast(dataHist.get(10)->find("x"))->getVal()); + EXPECT_EQ(dataHist.numEntries(), 20); + EXPECT_EQ(dataHist.sumEntries(), 20 * targetBinContent); - const double targetError = sqrt(10*4.); + static_cast(legacyVals.find("x"))->setVal(0.); + dataHist.get(legacyVals); // trigger side effect for weight below. + const double weight = dataHist.weight(); + ASSERT_EQ(weight, targetBinContent); - EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), targetError, 1.5); // TODO What is the actual value? + const double targetError = sqrt(10 * 4.); - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::Poisson); - EXPECT_LT(lo, hi); - EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); - EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); - } + EXPECT_NEAR(dataHist.weightError(RooAbsData::Poisson), targetError, 1.5); // TODO What is the actual value? - EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), - targetError, 1.E-14); + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::Poisson); + EXPECT_LT(lo, hi); + EXPECT_NEAR(lo, weight - computePoissonLower(weight), 3.E-2); + EXPECT_NEAR(hi, computePoissonUpper(weight) - weight, 3.E-2); + } - { - double lo, hi; - dataHist.weightError(lo, hi, RooAbsData::SumW2); - EXPECT_NEAR(lo, targetError, 1.E-14); - EXPECT_NEAR(lo, targetError, 1.E-14); - EXPECT_EQ(lo, hi); - } + EXPECT_NEAR(dataHist.weightError(RooAbsData::SumW2), targetError, 1.E-14); + { + double lo, hi; + dataHist.weightError(lo, hi, RooAbsData::SumW2); + EXPECT_NEAR(lo, targetError, 1.E-14); + EXPECT_NEAR(lo, targetError, 1.E-14); + EXPECT_EQ(lo, hi); + } - RooArgSet* coordsAt10 = dataHist.get(10)->snapshot(); - const double weightBin10 = dataHist.weight(); + RooArgSet coordsAt10; + dataHist.get(10)->snapshot(coordsAt10); + const double weightBin10 = dataHist.weight(); - EXPECT_NEAR(static_cast(coordsAt10->find("x"))->getVal(), 0.5, 1.E-1); - EXPECT_EQ(weight, weightBin10); + EXPECT_NEAR(static_cast(coordsAt10.find("x"))->getVal(), 0.5, 1.E-1); + EXPECT_EQ(weight, weightBin10); } - INSTANTIATE_TEST_SUITE_P(IO_SchemaEvol, RooDataHistIO, - testing::Values("dataHistv4_ref.root", "dataHistv5_ref.root", "dataHistv6_ref.root")); - + testing::Values("dataHistv4_ref.root", "dataHistv5_ref.root", "dataHistv6_ref.root")); -void fillHist(TH2D* histo, double content) { - for (int i=0; i < histo->GetNbinsX()+2; ++i) { - for (int j=0; j < histo->GetNbinsY()+2; ++j) { - histo->SetBinContent(i, j, content + (i-1)*100 + (j-1)); - } - } +void fillHist(TH2D *histo, double content) +{ + for (int i = 0; i < histo->GetNbinsX() + 2; ++i) { + for (int j = 0; j < histo->GetNbinsY() + 2; ++j) { + histo->SetBinContent(i, j, content + (i - 1) * 100 + (j - 1)); + } + } } -TEST(RooDataHist, BatchDataAccess) { - RooRealVar x("x", "x", 0, -10, 10); - RooRealVar y("y", "y", 1, 0, 20); +TEST(RooDataHist, BatchDataAccess) +{ + RooRealVar x("x", "x", 0, -10, 10); + RooRealVar y("y", "y", 1, 0, 20); - auto histo = std::make_unique("xyHist", "xyHist", 20, -10, 10, 10, 0, 10); - fillHist(histo.get(), 0.1); + auto histo = std::make_unique("xyHist", "xyHist", 20, -10, 10, 10, 0, 10); + fillHist(histo.get(), 0.1); - RooDataHist dataHist("dataHist", "Data histogram with batch access", - RooArgSet(x, y), RooFit::Import(*histo)); + RooDataHist dataHist("dataHist", "Data histogram with batch access", RooArgSet(x, y), RooFit::Import(*histo)); - const std::size_t numEntries = static_cast(dataHist.numEntries()); - ASSERT_EQ(numEntries, 200ul); + const std::size_t numEntries = static_cast(dataHist.numEntries()); + ASSERT_EQ(numEntries, 200ul); - const RooArgSet& vars = *dataHist.get(); - auto xp = dynamic_cast(vars[0ul]); - auto yp = dynamic_cast(vars[1]); - ASSERT_STREQ(xp->GetName(), "x"); - ASSERT_STREQ(yp->GetName(), "y"); + const RooArgSet &vars = *dataHist.get(); + auto xp = dynamic_cast(vars[0ul]); + auto yp = dynamic_cast(vars[1]); + ASSERT_STREQ(xp->GetName(), "x"); + ASSERT_STREQ(yp->GetName(), "y"); - auto evalData = dataHist.getBatches(0, numEntries); + auto evalData = dataHist.getBatches(0, numEntries); - auto xBatchShort = dataHist.getBatches(0, 100)[xp]; - auto xBatch = evalData[xp]; - auto yBatch = evalData[yp]; + auto xBatchShort = dataHist.getBatches(0, 100)[xp]; + auto xBatch = evalData[xp]; + auto yBatch = evalData[yp]; - ASSERT_FALSE(xBatchShort.empty()); - ASSERT_FALSE(xBatch.empty()); - ASSERT_FALSE(yBatch.empty()); + ASSERT_FALSE(xBatchShort.empty()); + ASSERT_FALSE(xBatch.empty()); + ASSERT_FALSE(yBatch.empty()); - EXPECT_EQ(xBatchShort.size(), 100ul); - EXPECT_EQ(xBatch.size(), numEntries); - EXPECT_EQ(yBatch.size(), numEntries); + EXPECT_EQ(xBatchShort.size(), 100ul); + EXPECT_EQ(xBatch.size(), numEntries); + EXPECT_EQ(yBatch.size(), numEntries); - EXPECT_EQ(xBatch[5 * 10], histo->GetXaxis()->GetBinCenter(5+1)); - EXPECT_EQ(yBatch[5], histo->GetYaxis()->GetBinCenter(5+1)); + EXPECT_EQ(xBatch[5 * 10], histo->GetXaxis()->GetBinCenter(5 + 1)); + EXPECT_EQ(yBatch[5], histo->GetYaxis()->GetBinCenter(5 + 1)); - auto weights = dataHist.getWeightBatch(0, numEntries); - ASSERT_FALSE(weights.empty()); - ASSERT_EQ(weights.size(), numEntries); - EXPECT_EQ(weights[2], 0.1 + 2.); - EXPECT_EQ(weights[4*10 + 7], 0.1 + 400. + 7.); + auto weights = dataHist.getWeightBatch(0, numEntries); + ASSERT_FALSE(weights.empty()); + ASSERT_EQ(weights.size(), numEntries); + EXPECT_EQ(weights[2], 0.1 + 2.); + EXPECT_EQ(weights[4 * 10 + 7], 0.1 + 400. + 7.); } - -void fillHist(TH1D* histo, double content) { - for (int i=0; i < histo->GetNbinsX()+2; ++i) { - histo->SetBinContent(i, content + i-1); - } +void fillHist(TH1D *histo, double content) +{ + for (int i = 0; i < histo->GetNbinsX() + 2; ++i) { + histo->SetBinContent(i, content + i - 1); + } } -TEST(RooDataHist, BatchDataAccessWithCategories) { - RooRealVar x("x", "x", 0, -10, 10); - RooCategory cat("cat", "category"); +TEST(RooDataHist, BatchDataAccessWithCategories) +{ + RooRealVar x("x", "x", 0, -10, 10); + RooCategory cat("cat", "category"); - auto histoX = std::make_unique("xHist", "xHist", 20, -10., 10.); - auto histoY = std::make_unique("yHist", "yHist", 20, -10., 10.); - fillHist(histoX.get(), 0.2); - fillHist(histoY.get(), 0.3); + auto histoX = std::make_unique("xHist", "xHist", 20, -10., 10.); + auto histoY = std::make_unique("yHist", "yHist", 20, -10., 10.); + fillHist(histoX.get(), 0.2); + fillHist(histoY.get(), 0.3); - RooDataHist dataHist("dataHist", "Data histogram with batch access", - RooArgSet(x), RooFit::Index(cat), RooFit::Import("catX", *histoX), RooFit::Import("catY", *histoY)); + RooDataHist dataHist("dataHist", "Data histogram with batch access", RooArgSet(x), RooFit::Index(cat), + RooFit::Import("catX", *histoX), RooFit::Import("catY", *histoY)); - const std::size_t numEntries = (std::size_t)dataHist.numEntries(); - ASSERT_EQ(numEntries, 40ul); + const std::size_t numEntries = (std::size_t)dataHist.numEntries(); + ASSERT_EQ(numEntries, 40ul); - const RooArgSet& vars = *dataHist.get(); - auto catp = dynamic_cast(vars[0ul]); - auto xp = dynamic_cast(vars[1]); - ASSERT_NE(catp, nullptr); - ASSERT_NE(xp, nullptr); - ASSERT_STREQ(catp->GetName(), "cat"); - ASSERT_STREQ(xp->GetName(), "x"); + const RooArgSet &vars = *dataHist.get(); + auto catp = dynamic_cast(vars[0ul]); + auto xp = dynamic_cast(vars[1]); + ASSERT_NE(catp, nullptr); + ASSERT_NE(xp, nullptr); + ASSERT_STREQ(catp->GetName(), "cat"); + ASSERT_STREQ(xp->GetName(), "x"); - auto xBatchShort = dataHist.getBatches(0, 10)[xp]; - auto xBatch = dataHist.getBatches(0, numEntries)[xp]; + auto xBatchShort = dataHist.getBatches(0, 10)[xp]; + auto xBatch = dataHist.getBatches(0, numEntries)[xp]; - ASSERT_FALSE(xBatchShort.empty()); - ASSERT_FALSE(xBatch.empty()); + ASSERT_FALSE(xBatchShort.empty()); + ASSERT_FALSE(xBatch.empty()); - EXPECT_EQ(xBatchShort.size(), 10ul); - EXPECT_EQ(xBatch.size(), numEntries); + EXPECT_EQ(xBatchShort.size(), 10ul); + EXPECT_EQ(xBatch.size(), numEntries); - EXPECT_EQ(xBatch[15], histoX->GetXaxis()->GetBinCenter(15+1)); - EXPECT_EQ(xBatch[35], histoX->GetXaxis()->GetBinCenter(15+1)); + EXPECT_EQ(xBatch[15], histoX->GetXaxis()->GetBinCenter(15 + 1)); + EXPECT_EQ(xBatch[35], histoX->GetXaxis()->GetBinCenter(15 + 1)); - auto weights = dataHist.getWeightBatch(0, numEntries); - ASSERT_FALSE(weights.empty()); - ASSERT_EQ(weights.size(), numEntries); - EXPECT_EQ(weights[2], 0.2 + 2.); - EXPECT_EQ(weights[23], 0.3 + 3.); + auto weights = dataHist.getWeightBatch(0, numEntries); + ASSERT_FALSE(weights.empty()); + ASSERT_EQ(weights.size(), numEntries); + EXPECT_EQ(weights[2], 0.2 + 2.); + EXPECT_EQ(weights[23], 0.3 + 3.); } +TEST(RooDataHist, BatchDataAccessWithCategoriesAndFitRange) +{ + RooRealVar x("x", "x", 0, -10, 10); + RooCategory cat("cat", "category"); + x.setRange(-8., 5); -TEST(RooDataHist, BatchDataAccessWithCategoriesAndFitRange) { - RooRealVar x("x", "x", 0, -10, 10); - RooCategory cat("cat", "category"); - x.setRange(-8., 5); - - auto histoX = std::make_unique("xHist", "xHist", 20, -10., 10.); - auto histoY = std::make_unique("yHist", "yHist", 20, -10., 10.); - fillHist(histoX.get(), 0.2); - fillHist(histoY.get(), 0.3); + auto histoX = std::make_unique("xHist", "xHist", 20, -10., 10.); + auto histoY = std::make_unique("yHist", "yHist", 20, -10., 10.); + fillHist(histoX.get(), 0.2); + fillHist(histoY.get(), 0.3); - RooDataHist dataHist("dataHist", "Data histogram with batch access", - RooArgSet(x), RooFit::Index(cat), RooFit::Import("catX", *histoX), RooFit::Import("catY", *histoY)); + RooDataHist dataHist("dataHist", "Data histogram with batch access", RooArgSet(x), RooFit::Index(cat), + RooFit::Import("catX", *histoX), RooFit::Import("catY", *histoY)); - const std::size_t numEntries = (std::size_t)dataHist.numEntries(); - ASSERT_EQ(numEntries, 26ul); + const std::size_t numEntries = (std::size_t)dataHist.numEntries(); + ASSERT_EQ(numEntries, 26ul); - const RooArgSet& vars = *dataHist.get(); - auto catp = dynamic_cast(vars[0ul]); - auto xp = dynamic_cast(vars[1]); - ASSERT_NE(catp, nullptr); - ASSERT_NE(xp, nullptr); - ASSERT_STREQ(catp->GetName(), "cat"); - ASSERT_STREQ(xp->GetName(), "x"); + const RooArgSet &vars = *dataHist.get(); + auto catp = dynamic_cast(vars[0ul]); + auto xp = dynamic_cast(vars[1]); + ASSERT_NE(catp, nullptr); + ASSERT_NE(xp, nullptr); + ASSERT_STREQ(catp->GetName(), "cat"); + ASSERT_STREQ(xp->GetName(), "x"); - auto xBatchShort = dataHist.getBatches(0, 10)[xp]; - auto xBatch = dataHist.getBatches(0, numEntries)[xp]; + auto xBatchShort = dataHist.getBatches(0, 10)[xp]; + auto xBatch = dataHist.getBatches(0, numEntries)[xp]; - ASSERT_FALSE(xBatchShort.empty()); - ASSERT_FALSE(xBatch.empty()); + ASSERT_FALSE(xBatchShort.empty()); + ASSERT_FALSE(xBatch.empty()); - EXPECT_EQ(xBatchShort.size(), 10ul); - EXPECT_EQ(xBatch.size(), numEntries); + EXPECT_EQ(xBatchShort.size(), 10ul); + EXPECT_EQ(xBatch.size(), numEntries); - EXPECT_TRUE(std::all_of(xBatch.begin(), xBatch.end(), [](double arg){return -8. < arg && arg < 5.;})); + EXPECT_TRUE(std::all_of(xBatch.begin(), xBatch.end(), [](double arg) { return -8. < arg && arg < 5.; })); - EXPECT_EQ(xBatch[ 0], -7.5); - EXPECT_EQ(xBatch[12], 4.5); - EXPECT_EQ(xBatch[13], -7.5); - EXPECT_EQ(xBatch[25], 4.5); + EXPECT_EQ(xBatch[0], -7.5); + EXPECT_EQ(xBatch[12], 4.5); + EXPECT_EQ(xBatch[13], -7.5); + EXPECT_EQ(xBatch[25], 4.5); - auto weights = dataHist.getWeightBatch(0, numEntries); - ASSERT_FALSE(weights.empty()); - ASSERT_EQ(weights.size(), numEntries); - EXPECT_TRUE(std::none_of(weights.begin(), weights.end(), [](double arg){return arg == 0.;})); + auto weights = dataHist.getWeightBatch(0, numEntries); + ASSERT_FALSE(weights.empty()); + ASSERT_EQ(weights.size(), numEntries); + EXPECT_TRUE(std::none_of(weights.begin(), weights.end(), [](double arg) { return arg == 0.; })); } -double integrate(RooAbsReal &absReal, const RooArgSet &iset, const RooArgSet &nset, const char *rangeName = 0) +double integrate(RooAbsReal &absReal, const RooArgSet &iset, const RooArgSet &nset, const char *rangeName = nullptr) { - return absReal.createIntegral(iset, nset, rangeName)->getVal(); + return std::unique_ptr + { + absReal.createIntegral(iset, nset, rangeName) + } -> getVal(); } -double integrate(RooAbsReal &absReal, const RooArgSet &iset, const char *rangeName = 0) +double integrate(RooAbsReal &absReal, const RooArgSet &iset, const char *rangeName = nullptr) { - return absReal.createIntegral(iset, rangeName)->getVal(); + return std::unique_ptr + { + absReal.createIntegral(iset, rangeName) + } -> getVal(); } double integrateTH1DAsFunction(TH1D &hist) @@ -448,11 +445,11 @@ TEST(RooDataHist, AnalyticalIntegration) RooRealVar x("x", "x", 0, 3.5); x.setRange("R1", 1.0, 3.0); // subrange that respects the bin edges - x.setRange("R2", 0.5, 3.25); // subrange that slices throught the bins + x.setRange("R2", 0.5, 3.25); // subrange that slices through the bins RooRealVar y("y", "y", 0.5, 0, 3.5); y.setRange("R1", 0, 2.5); // subrange that respects the bin edges - y.setRange("R2", 0, 3.3); // subrange that slices throught the bins + y.setRange("R2", 0, 3.3); // subrange that slices through the bins RooArgSet bothXandY{x, y}; @@ -585,7 +582,6 @@ TEST(RooDataHist, AnalyticalIntegration) EXPECT_FLOAT_EQ(integrate(hpdf2, y, bothXandY, "R2"), 3.8 / 4. * normYoverXY); } - TEST(RooDataHist, Interpolation2DSimple) { TH2D hist{"hist", "hist", 2, 0, 2, 2, 0, 2}; @@ -595,16 +591,16 @@ TEST(RooDataHist, Interpolation2DSimple) double a1 = 3; double b1 = 4; - for(int i = 0; i < a0; ++i) { + for (int i = 0; i < a0; ++i) { hist.Fill(0.5, 0.5); } - for(int i = 0; i < b0; ++i) { + for (int i = 0; i < b0; ++i) { hist.Fill(1.5, 0.5); } - for(int i = 0; i < a1; ++i) { + for (int i = 0; i < a1; ++i) { hist.Fill(0.5, 1.5); } - for(int i = 0; i < b1; ++i) { + for (int i = 0; i < b1; ++i) { hist.Fill(1.5, 1.5); } @@ -619,9 +615,7 @@ TEST(RooDataHist, Interpolation2DSimple) values.push_back((i * 2.0) / n); } - auto clamp = [](double v, double a, double b) { - return std::min(std::max(v, a), b); - }; + auto clamp = [](double v, double a, double b) { return std::min(std::max(v, a), b); }; auto getTrueWeight = [&]() { double xVal = x.getVal(); @@ -642,7 +636,6 @@ TEST(RooDataHist, Interpolation2DSimple) } } - /// GitHub issue #8015 /// Take binning from input RooDataHists when building a combined RooDataHist. TEST(RooDataHist, CombinedRooDataHistBinning) @@ -664,20 +657,16 @@ TEST(RooDataHist, CombinedRooDataHistBinning) RooDataHist dh2("dh2", "dh1", x, &hh2); // Create combined RooDataHist via intermediate RooDataHists - RooDataHist dhComb1("dhComb1", "dhComb1", x, Index(c), Import("SampleA", dh1), - Import("SampleB", dh2)); + RooDataHist dhComb1("dhComb1", "dhComb1", x, Index(c), Import("SampleA", dh1), Import("SampleB", dh2)); // Create combined RooDataHist directly from the TH1Ds - RooDataHist dhComb2{"dhComb2", "dhComb2", x, Index(c), Import("SampleA", hh1), - Import("SampleB", hh2)}; + RooDataHist dhComb2{"dhComb2", "dhComb2", x, Index(c), Import("SampleA", hh1), Import("SampleB", hh2)}; // In both cases the number of bins should be 40 + 40 = 80 EXPECT_EQ(dhComb1.numEntries(), 80); EXPECT_EQ(dhComb2.numEntries(), 80); } - - class WeightsTest : public testing::TestWithParam> { void SetUp() override { @@ -698,92 +687,75 @@ class WeightsTest : public testing::TestWithParam boundaries(nBins + 1); - for(std::size_t i = 0; i < boundaries.size(); ++i) { - boundaries[i] = ((xMax - xMin) / nBins) * i + xMin; - } - h1 = TH1D("h1", "h1", nBins, boundaries.data()); - } - - h1.FillRandom("gaus"); - - RooRealVar x("x", "x", 0, xMin, xMax); - RooDataHist dh{"dh", "dh", x, &h1}; - - std::unique_ptr absReal; - if (_correctForBinSize) { - auto histPdf = std::make_unique("histPdf", "histPdf", x, dh, _interpolationOrder); - histPdf->setCdfBoundaries(_cdfBoundaries); - absReal = std::move(histPdf); - } else { - auto histFunc = std::make_unique("histPdf", "histPdf", x, dh, _interpolationOrder); - histFunc->setCdfBoundaries(_cdfBoundaries); - absReal = std::move(histFunc); - } - - // Fill 10 000 random x values - std::size_t nVals = 10000; - std::vector xVals(nVals); - RooDataSet data{"data", "data", x}; - - for (std::size_t i = 0; i < nVals; ++i) { - xVals[i] = xMin + RooRandom::uniform() * (xMax - xMin); - x.setVal(xVals[i]); - data.add(x); - } - - std::vector weightsGetVal(nVals); - for (std::size_t i = 0; i < nVals; ++i) { - x.setVal(xVals[i]); - weightsGetVal[i] = absReal->getVal(x); - } - x.setVal(0.0); - - auto weightsGetValues = absReal->getValues(data); - - for (std::size_t i = 0; i < nVals; ++i) { - EXPECT_NEAR(weightsGetVal[i], weightsGetValues[i], 1e-6); - } + // Change local message level to suppress unnecessary info + RooHelpers::LocalChangeMsgLevel chmsglvl1{RooFit::WARNING, 0u, RooFit::DataHandling, true}; + RooHelpers::LocalChangeMsgLevel chmsglvl2{RooFit::WARNING, 0u, RooFit::Fitting, true}; + + const double xMin = -1; + const double xMax = 1; + const std::size_t nBins = 100; + + TH1D h1; + if (_isUniform) { + h1 = TH1D("h1", "h1", nBins, xMin, xMax); + } else { + std::vector boundaries(nBins + 1); + for (std::size_t i = 0; i < boundaries.size(); ++i) { + boundaries[i] = ((xMax - xMin) / nBins) * i + xMin; + } + h1 = TH1D("h1", "h1", nBins, boundaries.data()); + } + + h1.FillRandom("gaus"); + + RooRealVar x("x", "x", 0, xMin, xMax); + RooDataHist dh{"dh", "dh", x, &h1}; + + std::unique_ptr absReal; + if (_correctForBinSize) { + auto histPdf = std::make_unique("histPdf", "histPdf", x, dh, _interpolationOrder); + histPdf->setCdfBoundaries(_cdfBoundaries); + absReal = std::move(histPdf); + } else { + auto histFunc = std::make_unique("histPdf", "histPdf", x, dh, _interpolationOrder); + histFunc->setCdfBoundaries(_cdfBoundaries); + absReal = std::move(histFunc); + } + + // Fill 10 000 random x values + std::size_t nVals = 10000; + std::vector xVals(nVals); + RooDataSet data{"data", "data", x}; + + for (std::size_t i = 0; i < nVals; ++i) { + xVals[i] = xMin + RooRandom::uniform() * (xMax - xMin); + x.setVal(xVals[i]); + data.add(x); + } + + std::vector weightsGetVal(nVals); + for (std::size_t i = 0; i < nVals; ++i) { + x.setVal(xVals[i]); + weightsGetVal[i] = absReal->getVal(x); + } + x.setVal(0.0); + + std::unique_ptr clone = RooFit::Detail::compileForNormSet(*absReal, *data.get()); + RooFit::Evaluator evaluator(*clone); + evaluator.setInput(x.GetName(), xVals, false); + std::span weightsGetValues = evaluator.run(); + + for (std::size_t i = 0; i < nVals; ++i) { + EXPECT_NEAR(weightsGetVal[i], weightsGetValues[i], 1e-6); + } } INSTANTIATE_TEST_SUITE_P(RooDataHist, WeightsTest, - testing::Values(WeightsTest::ParamType{0, false, false, false}, - WeightsTest::ParamType{1, false, false, false}, - WeightsTest::ParamType{2, false, false, false}, - WeightsTest::ParamType{0, false, true, false}, - WeightsTest::ParamType{1, false, true, false}, - WeightsTest::ParamType{2, false, true, false}, - WeightsTest::ParamType{0, true, false, false}, - WeightsTest::ParamType{1, true, false, false}, - WeightsTest::ParamType{2, true, false, false}, - WeightsTest::ParamType{0, true, true, false}, - WeightsTest::ParamType{1, true, true, false}, - WeightsTest::ParamType{2, true, true, false}, - WeightsTest::ParamType{0, false, false, true}, - WeightsTest::ParamType{1, false, false, true}, - WeightsTest::ParamType{2, false, false, true}, - WeightsTest::ParamType{0, false, true, true}, - WeightsTest::ParamType{1, false, true, true}, - WeightsTest::ParamType{2, false, true, true}, - WeightsTest::ParamType{0, true, false, true}, - WeightsTest::ParamType{1, true, false, true}, - WeightsTest::ParamType{2, true, false, true}, - WeightsTest::ParamType{0, true, true, true}, - WeightsTest::ParamType{1, true, true, true}, - WeightsTest::ParamType{2, true, true, true}), + testing::Combine(testing::Values(0, 1, 2), // interpolation order + testing::Values(false, true), // RooHistPdf or RooHistFunc? + testing::Values(false, true), // CDF boundary mode + testing::Values(false, true) // uniform bins or not + ), [](testing::TestParamInfo const ¶mInfo) { std::stringstream ss; ss << (std::get<1>(paramInfo.param) ? "RooHistFunc" : "RooHistPdf"); @@ -791,4 +763,32 @@ INSTANTIATE_TEST_SUITE_P(RooDataHist, WeightsTest, ss << (std::get<2>(paramInfo.param) ? "CDF" : ""); ss << (std::get<3>(paramInfo.param) ? "UniformBins" : ""); return ss.str(); - }); \ No newline at end of file + }); + +// Test that splitting a RooDataSet by index category does preserve the sum of +// weights squared and weight errors. +TEST(RooDataHist, SplitDataHistWithSumW2) +{ + using namespace RooFit; + + RooRealVar x{"x", "x", 0, 0, 10}; + RooCategory cat{"cat", "cat", {{"sample_0", 0}}}; + RooRealVar weight{"weight", "weight", 1.0}; + + RooDataHist data1{"data", "data", {x, cat}}; + + data1.add({x, cat}, 2.0, 0.3); + + std::unique_ptr dataList{data1.split(cat, true)}; + auto &data2 = static_cast(*dataList->At(0)); + + data1.get(0); + data2.get(0); + EXPECT_DOUBLE_EQ(data2.weightSquared(), data1.weightSquared()); + EXPECT_DOUBLE_EQ(data2.weightError(), data1.weightError()); + + data1.get(1); + data2.get(1); + EXPECT_DOUBLE_EQ(data2.weightSquared(), data1.weightSquared()); + EXPECT_DOUBLE_EQ(data2.weightError(), data1.weightError()); +} diff --git a/roofit/roofitcore/test/testRooDataSet.cxx b/roofit/roofitcore/test/testRooDataSet.cxx index fe4d33b74b661..c633695cb223a 100644 --- a/roofit/roofitcore/test/testRooDataSet.cxx +++ b/roofit/roofitcore/test/testRooDataSet.cxx @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include @@ -37,20 +39,21 @@ TEST(RooDataSet, ImportFromTreeWithCut) RooHelpers::HijackMessageStream hijack(RooFit::INFO, RooFit::InputArguments); TTree tree("tree", "tree"); - double thex, they; - tree.Branch("x", &thex); - tree.Branch("y", &they); - tree.Branch("z", &they); - thex = -0.337; - they = 1.; + double theXVal; + double theYVal; + tree.Branch("x", &theXVal); + tree.Branch("y", &theYVal); + tree.Branch("z", &theYVal); + theXVal = -0.337; + theYVal = 1.; tree.Fill(); - thex = 0.337; - they = 1.; + theXVal = 0.337; + theYVal = 1.; tree.Fill(); - thex = 1.337; - they = 1.; + theXVal = 1.337; + theYVal = 1.; tree.Fill(); RooRealVar x("x", "x", 0); @@ -72,11 +75,11 @@ TEST(RooDataSet, ImportLongBranchNames) { TTree tree("theTree", "theTree"); - double doub = 0.; - tree.Branch("HLT_mu6_mu4_bBmumux_BsmumuPhi_delayed_L1BPH_2M8_MU6MU4_BPH_0DR15_MU6MU4", &doub); - doub = 2.; + double myDouble = 0.; + tree.Branch("HLT_mu6_mu4_bBmumux_BsmumuPhi_delayed_L1BPH_2M8_MU6MU4_BPH_0DR15_MU6MU4", &myDouble); + myDouble = 2.; tree.Fill(); - doub = 4.; + myDouble = 4.; tree.Fill(); RooRealVar *v = @@ -120,13 +123,15 @@ TEST(RooDataSet, BinnedClone) RooRealVar mes("Mes", "Mes", 5.28, 5.24, 5.29); mes.setBin(40); RooRealVar weight("weight", "weight", 1, 0, 100); - RooDataSet *data = new RooDataSet("dataset", "dataset", &chain, RooArgSet(mes, weight), 0, weight.GetName()); - RooDataHist *hist = data->binnedClone(); - EXPECT_DOUBLE_EQ(hist->sumEntries(), sumW); + { + RooDataSet data{"dataset", "dataset", &chain, RooArgSet(mes, weight), nullptr, weight.GetName()}; + std::unique_ptr hist{data.binnedClone()}; - delete hist; // invalid read here - delete data; // and here too + EXPECT_DOUBLE_EQ(hist->sumEntries(), sumW); + + // the original crash happened when "hist" and "data" got destructed + } gSystem->Unlink(filename[0]); gSystem->Unlink(filename[1]); @@ -176,16 +181,14 @@ TEST(RooDataSet, ReducingData) ASSERT_EQ(test_hist.Integral(), drawnEvents); // For unbinned data, reducing should be equivalent to the tree. - std::unique_ptr data_unbinned_reduced( - static_cast(data_unbinned->reduce(RooFit::Cut(chi2_test_cut)))); + std::unique_ptr data_unbinned_reduced{data_unbinned->reduce(RooFit::Cut(chi2_test_cut))}; EXPECT_DOUBLE_EQ(data_unbinned_reduced->sumEntries(), test_hist.Integral()); EXPECT_EQ(data_unbinned_reduced->numEntries(), test_hist.Integral()); // When using binned data, reducing and expecting the ame number of entries as in the unbinned case is not // possible, since information is lost if entries to the left and right of the cut end up in the same bin. // Therefore, can only test <= - std::unique_ptr reduced_binned_data( - static_cast(data->reduce(RooFit::Cut(chi2_test_cut)))); + std::unique_ptr reduced_binned_data{data->reduce(RooFit::Cut(chi2_test_cut))}; if (floor(chi2cutval) == chi2cutval) EXPECT_FLOAT_EQ(reduced_binned_data->sumEntries(), test_hist.Integral()); else @@ -277,11 +280,10 @@ TEST(RooDataSet, CrashAfterImportFromTree) // root-project/root#6951: Broken weights after reducing RooDataSet created with RooAbsPdf::generate() TEST(RooDataSet, ReduceWithCompositeDataStore) { - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); RooWorkspace ws{}; - ws.factory("Gaussian::gauss(x[-10,10], mean[3,-10,10], sig ma[1,0.1,10])"); + ws.factory("Gaussian::gauss(x[-10,10], mean[3,-10,10], sigma[1,0.1,10])"); auto &gauss = *ws.pdf("gauss"); auto &x = *ws.var("x"); @@ -292,8 +294,7 @@ TEST(RooDataSet, ReduceWithCompositeDataStore) auto &dataSet = *dataSetPtr; // Generate a new dataset with weight column - RooRealVar weight("weight", "weight", 0.5, 0.0, 1.0); - RooDataSet dataSetWeighted("dataSetWeighted", "dataSetWeighted", {x, weight}, "weight"); + RooDataSet dataSetWeighted("dataSetWeighted", "dataSetWeighted", x, RooFit::WeightVar()); for (std::size_t i = 0; i < nEvents; ++i) { dataSetWeighted.add(*dataSet.get(), 0.5); } @@ -302,7 +303,7 @@ TEST(RooDataSet, ReduceWithCompositeDataStore) RooCategory sample("sample", "sample"); sample.defineType("physics"); RooDataSet dataSetComposite("hmaster", "hmaster", x, RooFit::Index(sample), - RooFit::Link({{"physic s", &dataSetWeighted}})); + RooFit::Link({{"physics", &dataSetWeighted}})); // Reduce the dataset with the RooCompositeDataStore std::unique_ptr dataSetReducedPtr{dataSetComposite.reduce("true")}; @@ -353,3 +354,135 @@ TEST(RooDataSet, ReduceWithSelectVarsAndCutRange) EXPECT_EQ(reduced->numEntries(), 1); } + +// Test that importing a RooDataHist to a RooDataSet works and that it gives +// the right weight() and weightSquared(). +TEST(RooDataSet, ImportDataHist) +{ + RooRealVar x{"x", "x", 0, 3}; + x.setBins(3); + + RooDataHist dh{"dh", "dh", x}; + + dh.set(0, 10, 5); + dh.set(1, 20, 15); + dh.set(2, 30, 20); + + RooDataSet ds{"ds", "ds", x, RooFit::Import(dh)}; + + for (int i = 0; i < x.numBins(); ++i) { + dh.get(i); + ds.get(i); + EXPECT_FLOAT_EQ(ds.weight(), dh.weight()) << "weight() is off in bin " << i; + EXPECT_FLOAT_EQ(ds.weightSquared(), dh.weightSquared()) << "weightSquared() is off in bin " << i; + } +} + +// Test that splitting a RooDataSet by index category does preserve the weight +// errors. Covers GitHub issue #12453. +TEST(RooDataSet, SplitDataSetWithWeightErrors) +{ + using namespace RooFit; + + RooRealVar x{"x", "x", 0, 10}; + RooCategory cat{"cat", "cat", {{"sample_0", 0}}}; + RooRealVar weight{"weight", "weight", 1.0}; + + RooDataSet data1{"data", "data", {x, cat, weight}, WeightVar(weight), StoreError(weight)}; + + data1.add({x, cat}, 2.0, 0.3); + + std::unique_ptr dataList{data1.split(cat, true)}; + auto &data2 = static_cast(*dataList->At(0)); + + data1.Print(); + + data1.get(0); + data2.get(0); + EXPECT_DOUBLE_EQ(data2.weightError(), data1.weightError()); +} + +// The version number of the RooVectorDataStore::RealFullVector was increased +// in the 6.30 development cycle. The RealFullVector is used to store columns +// with errors, both symmetric and asymmetric. +// +// The reference file was created with the following code with ROOT 6.26.10: +// +// ```c++ +// using namespace RooFit; +// +// RooRealVar x{"x", "x", 0, 10}; +// RooRealVar y{"y", "y", 0, 10}; +// +// RooDataSet data{"data", "data", {x, y}, StoreError(x), StoreAsymError(y)}; +// +// x.setVal(5.0); +// x.setError(2.0); +// y.setVal(9.0); +// y.setAsymError(-4.0, 3.0); +// +// data.add({x, y}); +// +// x.setVal(7.0); +// x.setError(3.0); +// y.setVal(4.0); +// y.setAsymError(-2.0, 1.0); +// +// data.add({x, y}); +// +// std::unique_ptr file{TFile::Open("dataSet_with_errors_6_26_10.root", "RECREATE")}; +// +// file->WriteObject(&data, data.GetName()); +// ``` +TEST(RooDataSet, ReadDataSetWithErrors626) +{ + std::unique_ptr file{TFile::Open("dataSet_with_errors_6_26_10.root", "READ")}; + + auto data = file->Get("data"); + + auto &x = static_cast((*data->get())["x"]); + auto &y = static_cast((*data->get())["y"]); + + // Make sure the dataset is really using a RooVectorDataStore + EXPECT_TRUE(dynamic_cast(data->store())); + + data->get(0); + + EXPECT_DOUBLE_EQ(x.getVal(), 5.0); + EXPECT_DOUBLE_EQ(x.getError(), 2.0); + + EXPECT_DOUBLE_EQ(y.getVal(), 9.0); + EXPECT_DOUBLE_EQ(y.getAsymErrorLo(), -4.0); + EXPECT_DOUBLE_EQ(y.getAsymErrorHi(), 3.0); + + data->get(1); + + EXPECT_DOUBLE_EQ(x.getVal(), 7.0); + EXPECT_DOUBLE_EQ(x.getError(), 3.0); + + EXPECT_DOUBLE_EQ(y.getVal(), 4.0); + EXPECT_DOUBLE_EQ(y.getAsymErrorLo(), -2.0); + EXPECT_DOUBLE_EQ(y.getAsymErrorHi(), 1.0); +} + +TEST(RooDataSet,RooStringVarStorage) { + /* RooDataSet should be able to store strings + * although this currently will only work for tree storage + * */ + + RooStringVar str("str","test string",""); + RooDataSet data("data","data",str); + data.convertToTreeStore(); // necessary until VectorStore supports strings + data.add(str="str1"); + data.add(str="str2"); + + ASSERT_STREQ(data.get(0)->getStringValue("str"),"str1"); + ASSERT_STREQ(data.get(1)->getStringValue("str"),"str2"); + + // ensure dataset is cloneable + RooDataSet dataClone(data); + + ASSERT_STREQ(dataClone.get(0)->getStringValue("str"),"str1"); + ASSERT_STREQ(dataClone.get(1)->getStringValue("str"),"str2"); + +} diff --git a/roofit/roofitcore/test/testRooFormula.cxx b/roofit/roofitcore/test/testRooFormula.cxx index 827e639b264db..ca02e6b4d8aa9 100644 --- a/roofit/roofitcore/test/testRooFormula.cxx +++ b/roofit/roofitcore/test/testRooFormula.cxx @@ -1,12 +1,14 @@ // Tests for the RooFormula -// Author: Stephan Hageboeck, CERN 2020 +// Authors: Stephan Hageboeck, CERN 2020 +// Jonas Rembser, CERN 2023 -#include "RooFormula.h" -#include "RooRealVar.h" +#include "../src/RooFormula.h" +#include +#include -#include "ROOT/TestSupport.hxx" +#include -#include "gtest/gtest.h" +#include /// Since TFormula does very surprising things, /// RooFit needs to do safety checks. @@ -16,29 +18,31 @@ /// ``` /// is, for example, legal, and silently uses an undefined /// value for y. RooFit needs to detect this. -TEST(RooFormula, TestInvalidFormulae) { - ROOT::TestSupport::CheckDiagsRAII checkDiag; - checkDiag.requiredDiag(kError, "prepareMethod", "Can't compile function TFormula", false); - checkDiag.requiredDiag(kError, "TFormula::InputFormulaIntoCling", "Error compiling formula expression in Cling", true); - checkDiag.requiredDiag(kError, "TFormula::ProcessFormula", " is invalid", false); - checkDiag.requiredDiag(kError, "TFormula::ProcessFormula", "has not been matched in the formula expression", false); - checkDiag.requiredDiag(kError, "cling", "undeclared identifier", false); - - RooRealVar x("x", "x", 1.337); - RooRealVar y("y", "y", -1.); - RooFormula form("form", "x+10", x); - EXPECT_FLOAT_EQ(form.eval(nullptr), 11.337); - - ASSERT_ANY_THROW(RooFormula("form", "x+y", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; - ASSERT_ANY_THROW(RooFormula("form", "x+z", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; - ASSERT_ANY_THROW(RooFormula("form", "x+t", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; - ASSERT_ANY_THROW(RooFormula("form", "x+a", x)) << "Formulae with unknown variable cannot work."; - - RooFormula* form6 = nullptr; - ASSERT_NO_THROW( form6 = new RooFormula("form", "x+y", RooArgSet(x,y))) << "Formula with x,y must work."; - ASSERT_NE(form6, nullptr); - EXPECT_FLOAT_EQ(form6->eval(nullptr), 1.337 - 1.); - delete form6; +TEST(RooFormula, TestInvalidFormulae) +{ + ROOT::TestSupport::CheckDiagsRAII checkDiag; + checkDiag.requiredDiag(kError, "prepareMethod", "Can't compile function TFormula", false); + checkDiag.requiredDiag(kError, "TFormula::InputFormulaIntoCling", "Error compiling formula expression in Cling", + true); + checkDiag.requiredDiag(kError, "TFormula::ProcessFormula", " is invalid", false); + checkDiag.requiredDiag(kError, "TFormula::ProcessFormula", "has not been matched in the formula expression", false); + checkDiag.requiredDiag(kError, "cling", "undeclared identifier", false); + + RooRealVar x("x", "x", 1.337); + RooRealVar y("y", "y", -1.); + RooFormula form("form", "x+10", x); + EXPECT_FLOAT_EQ(form.eval(nullptr), 11.337); + + ASSERT_ANY_THROW(RooFormula("form", "x+y", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; + ASSERT_ANY_THROW(RooFormula("form", "x+z", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; + ASSERT_ANY_THROW(RooFormula("form", "x+t", x)) << "Formulae with y,z,t and no RooFit variable cannot work."; + ASSERT_ANY_THROW(RooFormula("form", "x+a", x)) << "Formulae with unknown variable cannot work."; + + std::unique_ptr form6; + ASSERT_NO_THROW(form6 = std::make_unique("form", "x+y", RooArgList{x, y})) + << "Formula with x,y must work."; + ASSERT_NE(form6, nullptr); + EXPECT_FLOAT_EQ(form6->eval(nullptr), 1.337 - 1.); } // In case of named arguments, the RooFormula will replace the argument names @@ -48,12 +52,28 @@ TEST(RooFormula, TestInvalidFormulae) { // replace existing x[i]. Second, variables with integer names like "0" should // only be substituted if the match is not followed by a "]", again to avoid // replacing x[i]. This test checks that these cases are handled correctly. -TEST(RooFormula, TestDangerousVariableNames) { - RooRealVar dt("dt", "dt", -10, 10); - RooRealVar x("x", "x", 1.547); - RooRealVar zero("0", "0", 0); - - // Create the formula, triggers an error if the formula doesn't compile - // correctly because the dangerous variable names haven't been treated right. - RooFormula formula("formula", "exp(-abs(@0)/@1)*cos(@0*@2)", {dt, x, zero}); +TEST(RooFormula, TestDangerousVariableNames) +{ + RooRealVar dt("dt", "dt", -10, 10); + RooRealVar x("x", "x", 1.547); + RooRealVar zero("0", "0", 0); + + // Create the formula, triggers an error if the formula doesn't compile + // correctly because the dangerous variable names haven't been treated right. + RooFormula formula("formula", "exp(-abs(@0)/@1)*cos(@0*@2)", {dt, x, zero}); +} + +/// Check that the RooFormulaVar has the right number of servers when some +/// variables are unused. +TEST(RooFormula, UnusedVariables) +{ + RooRealVar x{"x", "x", 1}; + RooRealVar y{"y", "y", 2}; + RooRealVar z{"z", "z", 3}; + + RooFormulaVar func{"func", "x * y", {x, y, z}}; + + // There are expected to be two servers only because "z" is not used in the + // formula. + EXPECT_EQ(func.servers().size(), 2); } diff --git a/roofit/roofitcore/test/testRooFuncWrapper.cxx b/roofit/roofitcore/test/testRooFuncWrapper.cxx new file mode 100644 index 0000000000000..334b2f886aa04 --- /dev/null +++ b/roofit/roofitcore/test/testRooFuncWrapper.cxx @@ -0,0 +1,581 @@ +/* + * Project: RooFit + * Authors: + * Garima Singh, CERN 2023 + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "gtest_wrapper.h" + +namespace { + +// Function to get the derivative of pdf wrt var. +double getNumDerivative(const RooAbsReal &pdf, RooRealVar &var, const RooArgSet &normSet, double eps = 1e-8) +{ + double orig = var.getVal(); + if (!var.inRange(orig + eps, nullptr)) { + throw std::runtime_error("getNumDerivative(): positive variation outside of range!"); + } + if (!var.inRange(orig - eps, nullptr)) { + throw std::runtime_error("getNumDerivative(): negative variation outside of range!"); + } + var.setVal(orig + eps); + double plus = pdf.getVal(normSet); + var.setVal(orig - eps); + double minus = pdf.getVal(normSet); + var.setVal(orig); + + return (plus - minus) / (2 * eps); +} + +void randomizeParameters(const RooArgSet ¶meters) +{ + double lowerBound = -0.1; + double upperBound = 0.1; + std::uniform_real_distribution unif(lowerBound, upperBound); + std::default_random_engine re; + + for (auto *param : parameters) { + double mul = unif(re); + + auto par = dynamic_cast(param); + if (!par) + continue; + double val = par->getVal(); + val = val + mul * (mul > 0 ? (par->getMax() - val) : (val - par->getMin())); + + par->setVal(val); + } +} + +} // namespace + +TEST(RooFuncWrapper, GaussianNormalizedHardcoded) +{ + using namespace RooFit; + auto inf = std::numeric_limits::infinity(); + + RooWorkspace ws; + ws.import(RooRealVar{"x", "x", 0, -inf, inf}); + ws.factory("Gaussian::gauss(x, mu[0, -10, 10], sigma[2.0, 0.01, 10])"); + + RooAbsPdf &gauss = *ws.pdf("gauss"); + RooRealVar &x = *ws.var("x"); + RooRealVar &mu = *ws.var("mu"); + RooRealVar &sigma = *ws.var("sigma"); + + RooArgSet normSet{x}; + RooArgSet paramsGauss; + RooArgSet paramsMyGauss; + + std::string func = "const double arg = params[0] - params[1];" + "const double sig = params[2];" + "double out = std::exp(-0.5 * arg * arg / (sig * sig));" + "return 1. / (std::sqrt(TMath::TwoPi()) * sig) * out;"; + RooFuncWrapper gaussFunc("myGauss1", "myGauss1", func, {x, mu, sigma}, nullptr, nullptr, true); + + // Check if functions results are the same even after changing parameters. + EXPECT_NEAR(gauss.getVal(normSet), gaussFunc.getVal(), 1e-8); + + mu.setVal(1); + EXPECT_NEAR(gauss.getVal(normSet), gaussFunc.getVal(), 1e-8); + + // Check if the parameter layout and size is the same. + gauss.getParameters(&normSet, paramsGauss); + gaussFunc.getParameters(&normSet, paramsMyGauss); + + EXPECT_TRUE(paramsMyGauss.hasSameLayout(paramsGauss)); + EXPECT_EQ(paramsMyGauss.size(), paramsGauss.size()); + + // Get AD based derivative + // Get number of actual parameters directly from the wrapper as not always will they be the same as paramsMyGauss. + std::vector dMyGauss(gaussFunc.getNumParams(), 0); + gaussFunc.gradient(dMyGauss.data()); + + // Check if derivatives are equal + EXPECT_NEAR(getNumDerivative(gauss, x, normSet), dMyGauss[0], 1e-8); + EXPECT_NEAR(getNumDerivative(gauss, mu, normSet), dMyGauss[1], 1e-8); + EXPECT_NEAR(getNumDerivative(gauss, sigma, normSet), dMyGauss[2], 1e-8); +} + +TEST(RooFuncWrapper, GaussianNormalized) +{ + RooWorkspace ws; + ws.import(RooRealVar{"x", "x", 0, -10, std::numeric_limits::infinity()}); + ws.factory("sum::mu_shifted(mu[0, -10, 10], shift[1.0, -10, 10])"); + ws.factory("prod::sigma_scaled(sigma[2.0, 0.01, 10], 1.5)"); + ws.factory("Gaussian::gauss(x, mu_shifted, sigma_scaled)"); + + RooAbsPdf &gauss = *ws.pdf("gauss"); + RooRealVar &x = *ws.var("x"); + RooRealVar &mu = *ws.var("mu"); + + RooArgSet normSet{x}; + + RooFuncWrapper gaussFunc("myGauss3", "myGauss3", gauss, normSet, nullptr, nullptr, true); + + RooArgSet paramsGauss; + gauss.getParameters(nullptr, paramsGauss); + + // Check if functions results are the same even after changing parameters. + EXPECT_NEAR(gauss.getVal(normSet), gaussFunc.getVal(), 1e-8); + + mu.setVal(1); + EXPECT_NEAR(gauss.getVal(normSet), gaussFunc.getVal(), 1e-8); + + // Get AD based derivative + std::vector dMyGauss(gaussFunc.getNumParams(), 0); + gaussFunc.gradient(dMyGauss.data()); + + // Check if derivatives are equal + for (std::size_t i = 0; i < paramsGauss.size(); ++i) { + EXPECT_NEAR(getNumDerivative(gauss, static_cast(*paramsGauss[i]), normSet), dMyGauss[i], 1e-8); + } +} + +TEST(RooFuncWrapper, Exponential) +{ + + for (auto negateCoefficient : {false, true}) { + + RooWorkspace ws; + if (negateCoefficient) { + ws.factory("Exponential::expo_2(x[1.0, 0, 10], c[0.1, 0, 10], true)"); + } else { + ws.factory("Exponential::expo_1(x[1.0, 0, 10], c[0.1, 0, 10], false)"); + } + + std::string name = negateCoefficient ? "expo_2" : "expo_1"; + + RooAbsPdf &expo = *ws.pdf(name); + RooRealVar &x = *ws.var("x"); + + RooArgSet normSet{x}; + + RooFuncWrapper expoFunc(name.c_str(), name.c_str(), expo, normSet, nullptr, nullptr, true); + + RooArgSet params; + expo.getParameters(nullptr, params); + + EXPECT_NEAR(expo.getVal(normSet), expoFunc.getVal(), 1e-8); + + // Get AD based derivative + std::vector dExpo(expoFunc.getNumParams(), 0); + expoFunc.gradient(dExpo.data()); + + // Check if derivatives are equal + for (std::size_t i = 0; i < params.size(); ++i) { + EXPECT_NEAR(getNumDerivative(expo, static_cast(*params[i]), normSet), dExpo[i], 1e-8) + << params[i]->GetName(); + } + } +} + +using CreateNLLFunc = + std::function(RooAbsPdf &, RooAbsData &, RooWorkspace &, RooFit::EvalBackend)>; +using WorkspaceSetupFunc = std::function; + +class FactoryTestParams { +public: + FactoryTestParams() = default; + FactoryTestParams(std::string const &name, WorkspaceSetupFunc setupWorkspace, CreateNLLFunc createNLL, + double fitResultTolerance, bool randomizeParameters) + : _name{name}, + _setupWorkspace{setupWorkspace}, + _createNLL{createNLL}, + _fitResultTolerance{fitResultTolerance}, + _randomizeParameters{randomizeParameters} + { + } + + std::string _name; + WorkspaceSetupFunc _setupWorkspace; + CreateNLLFunc _createNLL; + double _fitResultTolerance = 1e-4; + bool _randomizeParameters = true; +}; + +class FactoryTest : public testing::TestWithParam { + void SetUp() override + { + _changeMsgLvl = std::make_unique(RooFit::WARNING); + _params = GetParam(); + } + + void TearDown() override { _changeMsgLvl.reset(); } + +protected: + FactoryTestParams _params; + +private: + std::unique_ptr _changeMsgLvl; +}; + +std::unique_ptr runMinimizer(RooAbsReal &absReal, bool useGradient = true) +{ + RooMinimizer::Config cfg; + cfg.useGradient = useGradient; + RooMinimizer m{absReal, cfg}; + m.setPrintLevel(-1); + m.setStrategy(0); + m.minimize("Minuit2"); + return std::unique_ptr{m.save()}; +} + +TEST_P(FactoryTest, NLLFit) +{ + + RooWorkspace ws; + + std::unique_ptr ownedData; + _params._setupWorkspace(ws); + RooArgSet const &observables = *ws.set("observables"); + RooAbsData *data = ws.data("data"); + RooAbsPdf &model = *ws.pdf("model"); + + std::size_t nEvents = 100; + if (!data) { + std::unique_ptr data0{model.generate(observables, nEvents)}; + ownedData = std::unique_ptr{data0->binnedClone()}; + data = ownedData.get(); + } + + std::unique_ptr nllRef = _params._createNLL(model, *data, ws, RooFit::EvalBackend::Cpu()); + std::unique_ptr nllFunc = _params._createNLL(model, *data, ws, RooFit::EvalBackend::Codegen()); + + EXPECT_NEAR(nllRef->getVal(observables), nllFunc->getVal(), 1e-8); + + // Check if the parameter layout and size is the same. + RooArgSet paramsRefNll; + nllRef->getParameters(nullptr, paramsRefNll); + RooArgSet paramsMyNLL; + nllFunc->getParameters(&observables, paramsMyNLL); + + if (_params._randomizeParameters) { + randomizeParameters(paramsMyNLL); + // Check if functions results are the same even after changing parameters. + EXPECT_NEAR(nllRef->getVal(observables), nllFunc->getVal(), 1e-8); + } + + EXPECT_TRUE(paramsMyNLL.hasSameLayout(paramsRefNll)); + EXPECT_EQ(paramsMyNLL.size(), paramsRefNll.size()); + + // Get AD based derivative + std::vector dMyNLL(paramsMyNLL.size(), 0); + nllFunc->gradient(dMyNLL.data()); + + // Check if derivatives are equal + for (std::size_t i = 0; i < paramsMyNLL.size(); ++i) { + EXPECT_NEAR(getNumDerivative(*nllRef, static_cast(*paramsMyNLL[i]), observables), dMyNLL[i], 1e-4); + } + + // Remember parameter state before minimization + RooArgSet parametersOrig; + paramsRefNll.snapshot(parametersOrig); + + // Minimize the RooFuncWrapper Implementation + auto result = runMinimizer(*nllFunc, false); + paramsRefNll.assign(parametersOrig); + + // Minimize the RooFuncWrapper Implementation with AD + auto resultAd = runMinimizer(*nllFunc); + paramsRefNll.assign(parametersOrig); + + // Minimize the reference NLL + auto resultRef = runMinimizer(*nllRef); + paramsRefNll.assign(parametersOrig); + + // Compare minimization results + double tol = _params._fitResultTolerance; + // Same tolerance for parameter values and error, don't compare correlations + // because for very small correlations it's usually not the same within the + // relative tolerance because you would compare two small values that are + // only different from zero because of noise. + EXPECT_TRUE(result->isIdenticalNoCov(*resultRef, tol, tol)); + EXPECT_TRUE(resultAd->isIdenticalNoCov(*resultRef, tol, tol)); +} + +/// Initial minimization that was not based on any other tutorial/test. +FactoryTestParams param1{"Gaussian", + [](RooWorkspace &ws) { + ws.factory("sum::mu_shifted(mu[0, -10, 10], shift[1.0, -10, 10])"); + ws.factory("prod::sigma_scaled(sigma[3.0, 0.01, 10], 1.5)"); + ws.factory("Gaussian::model(x[0, -10, 10], mu_shifted, sigma_scaled)"); + + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + using namespace RooFit; + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/false}; + +/// Test based on the rf301 tutorial. +FactoryTestParams param2{"PolyVar", + [](RooWorkspace &ws) { + ws.factory("PolyVar::fy(y[-5, 5], {a0[-0.5, -5, 5], a1[-0.5, -1, 1], y})"); + ws.factory("Gaussian::model(x[-5, 5], fy, sigma[0.5, 0.01, 10])"); + + ws.defineSet("observables", "x,y"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &ws, RooFit::EvalBackend backend) { + using namespace RooFit; + RooRealVar &y = *ws.var("y"); + return std::unique_ptr{pdf.createNLL(data, ConditionalObservables(y), backend)}; + }, + 1e-4, + /*randomizeParameters=*/false}; + +/// Test based on the rf201 tutorial. +FactoryTestParams param3{"AddPdf", + [](RooWorkspace &ws) { + ws.factory("Gaussian::sig1(x[0, 10], mean[5, -10, 10], sigma1[0.50, .01, 10])"); + ws.factory("Gaussian::sig2(x, mean, sigma2[1.0, .01, 10])"); + ws.factory("Chebychev::bkg(x, {a0[0.3, 0., 0.5], a1[0.2, 0., 0.5]})"); + ws.factory("SUM::sig(sig1frac[0.8, 0.0, 1.0] * sig1, sig2)"); + ws.factory("SUM::model(bkgfrac[0.5, 0.0, 1.0] * bkg, sig)"); + + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + using namespace RooFit; + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 5e-3, + /*randomizeParameters=*/true}; + +/// Test based on the rf604 tutorial. +FactoryTestParams param4{"ConstraintSum", + [](RooWorkspace &ws) { + ws.factory("RealSumFunc::mu_func({mu[-1, -10, 10], 4.0, 5.0}, {1.1, 0.3, 0.2})"); + ws.factory("Gaussian::gauss(x[-10, 10], mu_func, sigma[2, 0.1, 10])"); + ws.factory("Polynomial::poly(x)"); + ws.factory("SUM::model(f[0.5, 0.0, 1.0] * gauss, poly)"); + ws.factory("Gaussian::fconstext(f, 0.2, 0.1)"); + + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &ws, RooFit::EvalBackend backend) { + using namespace RooFit; + return std::unique_ptr{ + pdf.createNLL(data, ExternalConstraints(*ws.pdf("fconstext")), backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +namespace { + +std::unique_ptr createSimPdfModel(RooRealVar &x, std::string const &channelName) +{ + auto prefix = [&](const char *name) { return name + std::string("_") + channelName; }; + + RooRealVar c(prefix("c").c_str(), "c", -0.5, -0.8, 0.2); + + RooExponential expo(prefix("expo").c_str(), "expo", x, c); + + // Create two Gaussian PDFs g1(x,mean1,sigma) anf g2(x,mean2,sigma) and their parameters + RooRealVar mean1(prefix("mean1").c_str(), "mean of gaussians", 3, 0, 5); + RooRealVar sigma1(prefix("sigma1").c_str(), "width of gaussians", 0.8, .01, 3.0); + RooRealVar mean2(prefix("mean2").c_str(), "mean of gaussians", 6, 5, 10); + RooRealVar sigma2(prefix("sigma2").c_str(), "width of gaussians", 1.0, .01, 3.0); + + RooGaussian sig1(prefix("sig1").c_str(), "Signal component 1", x, mean1, sigma1); + RooGaussian sig2(prefix("sig2").c_str(), "Signal component 2", x, mean2, sigma2); + + // Sum the signal components + RooRealVar sig1frac(prefix("sig1frac").c_str(), "fraction of signal 1", 0.5, 0.0, 1.0); + RooAddPdf sig(prefix("sig").c_str(), "g1+g2", {sig1, sig2}, {sig1frac}); + + // Sum the composite signal and background + RooRealVar sigfrac(prefix("sigfrac").c_str(), "fraction of signal", 0.4, 0.0, 1.0); + RooAddPdf model(prefix("model").c_str(), "g1+g2+a", {sig, expo}, {sigfrac}); + + return std::unique_ptr{static_cast(model.cloneTree())}; +} + +void getSimPdfModel(RooWorkspace &ws) +{ + using namespace RooFit; + RooCategory channelCat{"channel_cat", ""}; + + std::map pdfMap; + std::map> dataMap; + + RooArgSet models; + RooArgSet observables; + + auto nChannels = 2; + auto nEvents = 1000; + + for (int i = 0; i < nChannels; ++i) { + std::string suffix = "_" + std::to_string(i + 1); + auto obsName = "x" + suffix; + auto x = std::make_unique(obsName.c_str(), obsName.c_str(), 0, 10.); + x->setBins(20); + + std::unique_ptr model{createSimPdfModel(*x, std::to_string(i + 1))}; + + pdfMap.insert({"channel" + suffix, model.get()}); + channelCat.defineType("channel" + suffix, i); + dataMap.insert({"channel" + suffix, std::unique_ptr{model->generateBinned(*x, nEvents)}}); + + observables.addOwned(std::move(x)); + models.addOwned(std::move(model)); + } + + RooSimultaneous model{"model", "model", pdfMap, channelCat}; + + ws.import(RooDataSet("data", "data", {observables, channelCat}, Index(channelCat), Import(dataMap))); + + ws.import(model); + ws.defineSet("observables", observables); +} +} // namespace + +/// Test based on the simultaneous fit shown in CHEP'23 results +FactoryTestParams param5{"SimPdf", getSimPdfModel, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 5e-3, + /*randomizeParameters=*/true}; + +FactoryTestParams param6{"GaussianExtended", + [](RooWorkspace &ws) { + ws.factory("Gaussian::gauss(x[0, -10, 10], mu[0, -10, 10], sigma[3.0, 0.01, 10])"); + ws.factory("ExtendPdf::model(gauss, n[100, 0, 10000])"); + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/false}; +namespace { +void getDataHistModel(RooWorkspace &ws) +{ + RooRealVar x("x", "x", 6, 0, 20); + RooPolynomial p("p", "p", x, RooArgList(0.01, -0.01, 0.0004)); + + // Sample 500 events from p + x.setBins(10); + std::unique_ptr data1{p.generate(x, 500)}; + + // Create a binned dataset with 10 bins and 500 events + std::unique_ptr hist1{p.generateBinned(x, 500)}; + + // Represent data in dh as pdf in x + RooHistPdf histpdf("histpdf", "histpdf", x, *hist1, 0); + + RooRealVar mean("mean", "mean of gaussian", 6, 5, 10); + RooRealVar sigma("sigma", "width of gaussian", 1.0, .01, 3.0); + + RooGaussian gauss("gauss", "gauss", x, mean, sigma); + RooRealVar frac("frac", "faction of histpdf", 0.5, 0, 1); + RooAddPdf model("model", "model", {histpdf, gauss}, frac); + + ws.import(model); + ws.defineSet("observables", {x}); +} +} // namespace + +/// Test based on rf706 tutorial +FactoryTestParams param7{"HistPdf", getDataHistModel, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +FactoryTestParams param8{"Lognormal", + [](RooWorkspace &ws) { + ws.factory("Lognormal::model(x[1.0, 1.1, 10], mu[2.0, 1.1, 10], k[2.0, 1.1, 5.0])"); + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +FactoryTestParams param8p1{"LognormalStandard", + [](RooWorkspace &ws) { + ws.factory( + "Lognormal::model(x[1.0, 1.1, 10], mu[0.7, 0.1, 2.3], k[0.7, 0.1, 1.6], true)"); + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +FactoryTestParams param9{"Poisson", + [](RooWorkspace &ws) { + ws.factory("Poisson::model(x[5, 0, 10], mu[5, 0, 10])"); + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +// A RooPoisson where x is not rounded, like it is used in HistFactory +FactoryTestParams param10{"PoissonNoRounding", + [](RooWorkspace &ws) { + ws.factory("Poisson::model(x[5, 0, 10], mu[5, 0, 10])"); + auto poisson = static_cast(ws.pdf("model")); + poisson->setNoRounding(true); + ws.defineSet("observables", "x"); + }, + [](RooAbsPdf &pdf, RooAbsData &data, RooWorkspace &, RooFit::EvalBackend backend) { + return std::unique_ptr{pdf.createNLL(data, backend)}; + }, + 1e-4, + /*randomizeParameters=*/true}; + +INSTANTIATE_TEST_SUITE_P(RooFuncWrapper, FactoryTest, + testing::Values(param1, param2, param3, param4, param5, param6, param7, param8, param8p1, + param9, param10), + [](testing::TestParamInfo const ¶mInfo) { + return paramInfo.param._name; + }); diff --git a/roofit/roofitcore/test/testRooHistPdf.cxx b/roofit/roofitcore/test/testRooHistPdf.cxx new file mode 100644 index 0000000000000..6b6cf3e5ed9af --- /dev/null +++ b/roofit/roofitcore/test/testRooHistPdf.cxx @@ -0,0 +1,34 @@ +// Tests for the RooHistPdf +// Authors: Jonas Rembser, CERN 03/2023 + +#include +#include +#include +#include +#include + +#include + +// Verify that RooFit correctly uses analytic integration when having a +// RooLinearVar as the observable of a RooHistPdf. +TEST(RooHistPdf, AnalyticIntWithRooLinearVar) +{ + RooRealVar x{"x", "x", 0, -10, 10}; + x.setBins(10); + + RooDataHist dataHist("dataHist", "dataHist", x); + for(int i = 0; i < x.numBins(); ++i) { + dataHist.set(i, 10.0, 0.0); + } + + RooRealVar shift{"shift", "shift", 2.0, -10, 10}; + RooRealVar slope{"slope", "slope", 1.0}; + RooLinearVar xShifted{"x_shifted", "x_shifted", x, slope, shift}; + + RooHistPdf pdf{"pdf", "pdf", xShifted, x, dataHist}; + + RooRealIntegral integ{"integ", "integ", pdf, x}; + + EXPECT_DOUBLE_EQ(integ.getVal(), 90.); + EXPECT_EQ(integ.anaIntVars().size(), 1); +} diff --git a/roofit/roofitcore/test/testRooPolyFunc.cxx b/roofit/roofitcore/test/testRooPolyFunc.cxx index 172e9f589a3c0..4bce1610f2c8d 100644 --- a/roofit/roofitcore/test/testRooPolyFunc.cxx +++ b/roofit/roofitcore/test/testRooPolyFunc.cxx @@ -80,7 +80,7 @@ TEST(RooPolyFunc, TaylorExpansionClosure1D) { RooRealVar x("x", "x", 0., -10., 10.); auto polyfunc = makePolyFunc1D(x); - auto taylor = RooPolyFunc::taylorExpand("taylor", "taylor expansion", *polyfunc, RooArgSet{x}, 0.0, 2); + auto taylor = RooPolyFunc::taylorExpand("taylor", "taylor expansion", *polyfunc, {x}, 2); for (double theX : Doubles{0., 0.5, 1., 5., 10.}) { x = theX; // Taylor epansion of 2nd degree polynomial from RooPolyFunc @@ -94,7 +94,7 @@ TEST(RooPolyFunc, TaylorExpansionClosure2D) RooRealVar x("x", "x", 0., -10., 10.); RooRealVar y("y", "y", 0., -10., 10.); auto polyfunc = makePolyFunc2D(x, y); - auto taylor = RooPolyFunc::taylorExpand("taylor", "taylor expansion", *polyfunc, RooArgSet{x, y}, 0.0, 2); + auto taylor = RooPolyFunc::taylorExpand("taylor", "taylor expansion", *polyfunc, {x, y}, 2); for (double theX : Doubles{0., 0.5, 1., 5., 10.}) { for (double theY : Doubles{0., 0.5, 1., 5., 10.}) { x = theX; diff --git a/roofit/roofitcore/test/testRooProdPdf.cxx b/roofit/roofitcore/test/testRooProdPdf.cxx index 47c5bad194644..83aa9c8971c1d 100644 --- a/roofit/roofitcore/test/testRooProdPdf.cxx +++ b/roofit/roofitcore/test/testRooProdPdf.cxx @@ -14,23 +14,28 @@ #include #include -#include +#include + +#include "gtest_wrapper.h" #include #include #include -class TestProdPdf : public ::testing::TestWithParam> { +class TestProdPdf : public ::testing::TestWithParam> { +public: + TestProdPdf() : _evalBackend{RooFit::EvalBackend::Legacy()} {} + private: void SetUp() override { RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; - datap.reset(prod.generate(x, 1000)); + datap = std::unique_ptr{prod.generate(x, 1000)}; a.setConstant(true); _optimize = std::get<0>(GetParam()); - _batchMode = std::get<1>(GetParam()); + _evalBackend = std::get<1>(GetParam()); } protected: @@ -46,7 +51,7 @@ class TestProdPdf : public ::testing::TestWithParam std::unique_ptr datap; int _optimize = 0; - std::string _batchMode; + RooFit::EvalBackend _evalBackend; }; TEST_P(TestProdPdf, CachingOpt) @@ -54,91 +59,54 @@ TEST_P(TestProdPdf, CachingOpt) RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; using namespace RooFit; - prod.fitTo(*datap, Optimize(_optimize), PrintLevel(-1), BatchMode(_batchMode)); - EXPECT_LT(fabs(b.getVal() - bTruth), b.getError() * 2.5) // 2.5-sigma compatibility check + prod.fitTo(*datap, Optimize(_optimize), PrintLevel(-1), _evalBackend); + EXPECT_LT(std::abs(b.getVal() - bTruth), b.getError() * 2.5) // 2.5-sigma compatibility check << "b=" << b.getVal() << " +- " << b.getError() << " doesn't match truth value with O" << _optimize << "."; } INSTANTIATE_TEST_SUITE_P(RooProdPdf, TestProdPdf, - testing::Values(TestProdPdf::ParamType{0, "off"}, TestProdPdf::ParamType{0, "cpu"}, - TestProdPdf::ParamType{1, "off"}, TestProdPdf::ParamType{1, "cpu"}, - TestProdPdf::ParamType{2, "off"}, TestProdPdf::ParamType{2, "cpu"}), + testing::Combine(testing::Values(0, 1, 2), + testing::Values(RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu())), [](testing::TestParamInfo const ¶mInfo) { std::stringstream ss; - ss << "opt" << std::get<0>(paramInfo.param) << std::get<1>(paramInfo.param); + ss << "opt" << std::get<0>(paramInfo.param) << std::get<1>(paramInfo.param).name(); return ss.str(); }); -std::vector> allPossibleSubset(RooAbsCollection const &arr) +TEST(RooProdPdf, TestGetPartIntList) { - std::vector> out; - std::size_t n = arr.size(); - - std::size_t count = std::pow(2, n); - for (std::size_t i = 0; i < count; i++) { - out.emplace_back(); - auto &back = out.back(); - for (std::size_t j = 0; j < n; j++) { - if ((i & (1 << j)) != 0) { - back.push_back(arr[j]); - } - } - } - return out; -} + RooHelpers::LocalChangeMsgLevel chmsglvl1{RooFit::ERROR, 0u, RooFit::InputArguments, true}; + RooHelpers::LocalChangeMsgLevel chmsglvl2{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; -// Hash the integral configuration for all possible normalization sets. -unsigned int hashRooProduct(RooProdPdf const &prod) -{ - RooArgSet params; - prod.getParameters(nullptr, params); - auto subsets = allPossibleSubset(params); + // This test checks if RooProdPdf::getPartIntList factorizes the integrals + // as expected, for the example of a three dimensional RooProdPdf. - std::stringstream ss; + RooWorkspace ws; - for (auto const &subset : subsets) { - // this can't be on the stack, otherwise we will always get the same - // address and therefore get wrong cache hits! - auto nset = std::make_unique(subset.begin(), subset.end()); - prod.writeCacheToStream(ss, nset.get()); - } + double a = 10.; + double b = 4.; + double c = 2.5; - std::string s = ss.str(); - return TString::Hash(s.c_str(), s.size()); -} + auto &x = static_cast(*ws.factory("x[0, 0, " + std::to_string(a) + "]")); + auto &y = static_cast(*ws.factory("y[0, 0, " + std::to_string(b) + "]")); + auto &z = static_cast(*ws.factory("z[0, 0, " + std::to_string(c) + "]")); -TEST(RooProdPdf, TestGetPartIntList) -{ - // This test checks if RooProdPdf::getPartIntList factorizes the integrals - // as expected. - // Instead of trying to construct tests for all possible cases by hand, - // this test creates a product where the factors have different patters of - // overlapping parameters. To make sure all possible cases are covered, we - // are using all possible subsets of the parameters one after the other to - // create the reference test result. - - RooRealVar x{"x", "x", 1., 0, 10}; - RooRealVar y{"y", "y", 1., 0, 10}; - RooRealVar z{"z", "z", 1., 0, 10}; - - RooRealVar m1{"m1", "m1", 1., 0, 10}; - RooRealVar m2{"m2", "m2", 1., 0, 10}; - RooRealVar m3{"m3", "m3", 1., 0, 10}; - - RooGenericPdf gauss1{"gauss1", "gauss1", "x+m1", {x, m1}}; - RooGenericPdf gauss2{"gauss2", "gauss2", "x+m2", {x, m2}}; - RooGenericPdf gauss3{"gauss3", "gauss3", "y+m3", {y, m3}}; - RooGenericPdf gauss4{"gauss4", "gauss4", "z+m1", {z, m1}}; - RooGenericPdf gauss5{"gauss5", "gauss5", "x+m1", {x, m1}}; + // Factorize the product in one 1D and one 2D pdf to get a more complicated + // and complete test case. + ws.factory("Uniform::pdf1({x})"); + ws.factory("Uniform::pdf2({y, z})"); // Product of all the pdfs. - RooProdPdf prod{"prod", "prod", RooArgList{gauss1, gauss2, gauss3, gauss4, gauss5}}; - - // We hash the string serializations of caches for all possible - // normalization sets and compare it to the expected hash. - // This value must be updated if the convention for integral names in - // RooProdPdf changes. - EXPECT_EQ(hashRooProduct(prod), 2448666198); + auto &prod = static_cast(*ws.factory("PROD::prod(pdf1, pdf2)")); + + EXPECT_DOUBLE_EQ(prod.getVal({}), 1.0); + EXPECT_DOUBLE_EQ(prod.getVal({x}), 1. / a); + EXPECT_DOUBLE_EQ(prod.getVal({y}), 1. / b); + EXPECT_DOUBLE_EQ(prod.getVal({z}), 1. / c); + EXPECT_DOUBLE_EQ(prod.getVal({x, y}), 1. / a / b); + EXPECT_DOUBLE_EQ(prod.getVal({x, z}), 1. / a / c); + EXPECT_DOUBLE_EQ(prod.getVal({y, z}), 1. / b / c); + EXPECT_DOUBLE_EQ(prod.getVal({x, y, z}), 1. / a / b / c); } TEST(RooProdPdf, TestDepsAreCond) @@ -174,13 +142,13 @@ TEST(RooProdPdf, TestDepsAreCond) using ResultPtr = std::unique_ptr; - ResultPtr result1{pdf1.fitTo(*data, Save(), BatchMode("off"), PrintLevel(-1))}; + ResultPtr result1{pdf1.fitTo(*data, Save(), EvalBackend::Legacy(), PrintLevel(-1))}; resetParameters(); - ResultPtr result2{pdf1.fitTo(*data, Save(), BatchMode("cpu"), PrintLevel(-1))}; + ResultPtr result2{pdf1.fitTo(*data, Save(), EvalBackend::Cpu(), PrintLevel(-1))}; resetParameters(); - ResultPtr result3{pdf2.fitTo(*data, Save(), BatchMode("off"), PrintLevel(-1))}; + ResultPtr result3{pdf2.fitTo(*data, Save(), EvalBackend::Legacy(), PrintLevel(-1))}; resetParameters(); - ResultPtr result4{pdf2.fitTo(*data, Save(), BatchMode("cpu"), PrintLevel(-1))}; + ResultPtr result4{pdf2.fitTo(*data, Save(), EvalBackend::Cpu(), PrintLevel(-1))}; EXPECT_TRUE(result2->isIdentical(*result1)) << "batchmode fit is inconsistent!"; EXPECT_TRUE(result3->isIdentical(*result1)) << "alternative model fit is inconsistent!"; @@ -219,7 +187,7 @@ TEST(RooProdPdf, DISABLED_ChangeServerNormSetForProdPdfInAddPdf) x.setRange("FULL", -10, +10); y.setRange("FULL", -10, +10); - // Try different normalization sets to check if there is a false chache hit + // Try different normalization sets to check if there is a false cache hit // after changing the normalization range of the servers. RooArgSet normSet1{x, y}; RooArgSet normSet2{x, y}; @@ -244,3 +212,25 @@ TEST(RooProdPdf, DISABLED_ChangeServerNormSetForProdPdfInAddPdf) EXPECT_FLOAT_EQ(val2, val1); EXPECT_FLOAT_EQ(val3, val1); } + +// Make sure that the pdf that provides the expected number of events in a +// RooProdPdf is not considered as a constraint. Covers JIRA issue ROOT-7604. +TEST(RooProdPdf, RooProdPdfWithExtendedTerm) +{ + RooHelpers::LocalChangeMsgLevel locmsg(RooFit::WARNING, 0u, RooFit::Minimization, false); + + RooWorkspace ws; + ws.factory("Gaussian::L_constraint(L_nom[10],L[10,0,20],0.2)"); + ws.factory("PROD::full_model( RooExtendedTerm::model( L ) , L_constraint )"); + + ws.factory("weightVar[10,0,100]"); + ws.factory("dummy_obs[1,0,1]"); + ws.defineSet("obs", "dummy_obs,weightVar"); + RooDataSet data("data", "data", *ws.set("obs"), RooFit::WeightVar("weightVar")); + data.add(*ws.set("obs"), 5); + + std::unique_ptr nll1{ws.pdf("full_model")->createNLL(data)}; + double refVal = -std::log(ROOT::Math::gaussian_pdf(10, 0.2, 10)) + (10. - 5 * std::log(10.)); + double nll1Val = nll1->getVal(); + EXPECT_FLOAT_EQ(nll1Val, refVal); +} diff --git a/roofit/roofitcore/test/testRooRealIntegral.cxx b/roofit/roofitcore/test/testRooRealIntegral.cxx index d4bfc2d466bd8..3b900a8e4590c 100644 --- a/roofit/roofitcore/test/testRooRealIntegral.cxx +++ b/roofit/roofitcore/test/testRooRealIntegral.cxx @@ -15,7 +15,11 @@ #include #include -#include +#include + +#include "../src/RooGenProdProj.h" + +#include "gtest_wrapper.h" #include @@ -45,8 +49,8 @@ TEST(RooRealIntegral, ClientServerInterface1) ws.factory("Product::mu_mod({mu[-0.005, -5.0, 5.0], 10.0})"); ws.factory("Gaussian::gauss(x[0, 1], mu_mod, 2.0)"); - RooRealVar& x = *ws.var("x"); - RooAbsPdf& gauss = *ws.pdf("gauss"); + RooRealVar &x = *ws.var("x"); + RooAbsPdf &gauss = *ws.pdf("gauss"); RooGenericPdf pdf{"gaussWrapped", "gauss", gauss}; std::unique_ptr integ1{gauss.createIntegral(x, *pdf.getIntegratorConfig(), nullptr)}; @@ -117,9 +121,9 @@ TEST(RooRealIntegral, IntegrateFuncWithShapeServers) ws.factory("Gaussian::gauss(x[0, 1], mu_mod, sigma[1, 0.5, 2.0])"); RooRealVar &x = *ws.var("x"); - RooAbsReal& muMod = *ws.function("mu_mod"); - RooRealVar& sigma = *ws.var("sigma"); - RooAbsPdf& gauss = *ws.pdf("gauss"); + RooAbsReal &muMod = *ws.function("mu_mod"); + RooRealVar &sigma = *ws.var("sigma"); + RooAbsPdf &gauss = *ws.pdf("gauss"); RooGenericPdf pdf("pdf", "gauss", gauss); // Project over sigma, meaning sigma should now become a shape server @@ -142,7 +146,7 @@ TEST(RooRealIntegral, IntegrateFuncWithShapeServers) EXPECT_FALSE(sigma.isValueServer(*integ1)); EXPECT_TRUE(sigma.isShapeServer(*integ1)); // sigma should still be shape server! - // Also check that that the number of servers is right (should be 3 for x, + // Also check that the number of servers is right (should be 3 for x, // mu, and sigma, and 1 more for the underlying PDF) EXPECT_EQ(gaussProj.servers().size(), 4); EXPECT_EQ(integ1->servers().size(), 4); @@ -220,7 +224,12 @@ TEST(RooRealIntegral, UseCloneAsIntegrationVariable2) /// Make sure that the normalization set for a RooAddPdf is always defined when /// numerically integrating a RooProdPdf where the RooAddPdf is one of the /// factors. Covers GitHub #11476 and JIRA issue ROOT-9436. -TEST(RooRealIntegral, Issue11476) +/// +/// Disabled for now because the fix to the bug that is covered by this unit +/// test caused a severe performance problem and was reverted. The performance +/// regression is covered by another unit test in this file, called +/// "ProjectConditional". +TEST(RooRealIntegral, DISABLED_Issue11476) { // Silence the info about numeric integration because we don't care about it RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::NumIntegration, true}; @@ -243,7 +252,7 @@ TEST(RooRealIntegral, Issue11476) // Check that there were no warnings (covers GitHub issue #11476) const std::string messages = hijack.str(); std::cout << messages; - EXPECT_TRUE(messages.empty()) << "Unexpected warnings were issued!"; + EXPECT_TRUE(messages.empty()) << "Unexpected warnings were issued! Stream contents: " << hijack.str(); // Verify that plot is correctly normalized std::unique_ptr frame{x.frame()}; @@ -255,3 +264,125 @@ TEST(RooRealIntegral, Issue11476) EXPECT_LE(frame->chiSquare(), 1.0) << "The chi-square of the plot is too high, the normalization of the PDF is probably wrong!"; } + +class LevelTest : public testing::TestWithParam { + void SetUp() override { _level = GetParam(); } + +protected: + int _level; + +private: + std::unique_ptr _changeMsgLvl; +}; + +/// Related to GitHub issue #11814. +TEST_P(LevelTest, ProjectConditional) +{ + RooHelpers::HijackMessageStream hijack(RooFit::INFO, RooFit::NumIntegration); + + constexpr bool verbose = false; + + RooWorkspace w; + w.factory("Poisson::px(x[150,0,500],sum::splusb(s[0,0,100],b[100,0,300]))"); + w.factory("Poisson::py(y[100,0,500],prod::taub(tau[1.],b))"); + w.factory("Uniform::prior_b(b)"); + + RooRealVar &x = *w.var("x"); + RooRealVar &b = *w.var("b"); + + std::unique_ptr function; + std::size_t expectedNumInts = 0; + + // The following three code blocks all cover the issue, but generate the + // computation graph using different levels of interacting with RooFit, from low to high level. + switch (_level) { + + case 1: { + // Version 1) Manually reproducing the RooGenProdProj instance that the + // RooProdPdf would create under the hood: + RooAbsPdf &px = *w.pdf("px"); + RooAbsPdf &py = *w.pdf("py"); + RooArgSet iset{b}; + RooArgSet eset{}; + std::unique_ptr pxNormed{px.createIntegral({}, x)}; + auto genProdProj = std::make_unique("genProdProj", "", RooArgSet{py}, eset, iset, nullptr); + auto prod = std::make_unique("prod", "", RooArgList{*genProdProj, *pxNormed}); + function = std::unique_ptr{prod->createIntegral(iset)}; + + function->addOwnedComponents(std::move(pxNormed)); + function->addOwnedComponents(std::move(genProdProj)); + function->addOwnedComponents(std::move(prod)); + + expectedNumInts = 2; + } break; + + case 2: { + // Version 2) Doing the final projection integral manually: + w.factory("PROD::foo(px|b,py,prior_b)"); + function = std::unique_ptr{w.pdf("foo")->createIntegral({b}, {b, x})}; + expectedNumInts = 3; + } break; + + case 3: { + // Version 3) High-level Projection in RooWorkspace factory language, as + // it originally appeared in the RooStats tutorials: + w.factory("PROJ::averagedModel(PROD::foo(px|b,py,prior_b),b)"); + function = std::unique_ptr{static_cast(w.pdf("averagedModel")->Clone())}; + expectedNumInts = 4; + } break; + + default: break; + } + + RooArgSet nset{b, x}; + + for (int i = 0; i < 10; ++i) { + x.setVal(i % 500); + + const double val = function->getVal(nset); + if (verbose) { + std::cout << val << std::endl; + } + } + + EXPECT_LE(ROOT::Split(hijack.str(), "\n", true).size(), expectedNumInts) + << "More numeric integrals than expected! This might be okay, but could also point to a performance regression " + "for the model covered in this unit test. Please investigate, and increase the number of expected numeric " + "integrals in this test if they are not related to performance regressions."; +} + +INSTANTIATE_TEST_SUITE_P(RooRealIntegral, LevelTest, testing::Values(1, 2, 3), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "Level" << paramInfo.param; + return ss.str(); + }); + +// If we integrate a model that uses RooLinearVar and should be able to get +// integrated analytically, this should also work if we integrate over variable +// clones because RooFit considers them identical. Covers GitHub issue #12646. +TEST(RooRealIntegral, RooLinearVarModelIntegratedOverVariableClones) +{ + RooWorkspace ws; + ws.factory("LinearVar::x2(x[0, 1], 1, 0)"); + ws.factory("LinearVar::y2(y[0, 1], 1, 0)"); + + // RooGaussian can integrate over x or mu, but not both still, the issue is + // visible regardless + ws.factory("Gaussian::gauss(x2, y2, 0.2)"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &y = *ws.var("y"); + RooAbsPdf &gauss = *ws.pdf("gauss"); + + // There should be no numeric integration happening + std::unique_ptr integral{gauss.createIntegral({y}, {x, y})}; + EXPECT_TRUE(static_cast(*integral).numIntRealVars().empty()); + + RooRealVar xCopy{x}; + RooRealVar yCopy{y}; + + // Also if we use clones of the observables, it should not make a difference + std::unique_ptr integral2{gauss.createIntegral({yCopy}, {xCopy, yCopy})}; + EXPECT_TRUE(static_cast(*integral2).numIntRealVars().empty()); +} diff --git a/roofit/roofitcore/test/testRooRealVar.cxx b/roofit/roofitcore/test/testRooRealVar.cxx index 95aabbe3b6666..353dd9c65bd3b 100644 --- a/roofit/roofitcore/test/testRooRealVar.cxx +++ b/roofit/roofitcore/test/testRooRealVar.cxx @@ -19,9 +19,10 @@ TEST(RooRealVar, AlternativeBinnings) x.setBinning(RooUniformBinning(-9, 10, 20, "uniform"), "uniform"); RooArgSet xSet(x); - auto clones = xSet.snapshot(true); + RooArgSet clones; + xSet.snapshot(clones, true); - auto& uniform = dynamic_cast((*clones)["x"]).getBinning("uniform"); + auto& uniform = dynamic_cast(clones["x"]).getBinning("uniform"); EXPECT_TRUE(uniform.isUniform()); EXPECT_EQ(uniform.lowBound(), -9.); EXPECT_EQ(uniform.highBound(), 10.); @@ -30,13 +31,11 @@ TEST(RooRealVar, AlternativeBinnings) double boundaries[] = {-5., 5., 10.}; x.setBinning(RooBinning(2, boundaries, "custom"), "uniform"); - auto& overwrittenBinning = dynamic_cast((*clones)["x"]).getBinning("uniform"); + auto& overwrittenBinning = dynamic_cast(clones["x"]).getBinning("uniform"); EXPECT_EQ(overwrittenBinning.lowBound(), -5.); EXPECT_EQ(overwrittenBinning.highBound(), 10.); EXPECT_EQ(overwrittenBinning.binWidth(0), 10.); - delete clones; - auto& uniformFromX = x.getBinning("uniform"); EXPECT_EQ(&uniformFromX, &overwrittenBinning); EXPECT_EQ(uniformFromX.lowBound(), -5.); diff --git a/roofit/roofitcore/test/testRooRombergIntegrator.cxx b/roofit/roofitcore/test/testRooRombergIntegrator.cxx new file mode 100644 index 0000000000000..3fdbf4d5445b8 --- /dev/null +++ b/roofit/roofitcore/test/testRooRombergIntegrator.cxx @@ -0,0 +1,430 @@ +// Tests for the RooRombergIntegrator. +// Authors: Stephan Hageboeck, CERN 05/2020 +// Jonas Rembser, CERN 08/2023 + +#include "RooRealBinding.h" +#include "RooRealVar.h" +#include "RooFormulaVar.h" +#include "RooRombergIntegrator.h" +#include "RooNumIntConfig.h" +#include "RooHelpers.h" +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" + +#include +#include + +TEST(RooIntegrator1D, RunFormulaVar_Trapezoid) +{ + + RooRealVar x("x", "x", -100, 100); + RooRealVar a("a", "a", 0.2, -100, 100); + RooRealVar b("b", "b", 0.3, -100, 100); + RooFormulaVar formula("formula", "0.1 + x*(a + b*x)", {x, a, b}); + auto solution = [&x](double aVal, double bVal) { + auto indefInt = [=](double y) { return y * (0.1 + y * (1. / 2. * aVal + 1. / 3. * bVal * y)); }; + return indefInt(x.getMax()) - indefInt(x.getMin()); + }; + RooRealBinding binding(formula, {x, a, b}); + std::vector yvals{a.getVal(), b.getVal()}; + + // The integrators will warn, since we let them run until maxSteps + RooHelpers::HijackMessageStream hijack(RooFit::WARNING, RooFit::Integration); + + // Test the recursion anchors of the Romberg integration + { + RooRombergIntegrator oneStep(binding, RooRombergIntegrator::Trapezoid, 1, 1.E-15); + EXPECT_DOUBLE_EQ(oneStep.integral(yvals.data()), 0.5 * 200. * (2 * 0.1 + 2. * 0.3 * 10000.)); + x = -100.; + const double left = formula.getVal(); + x = 100.; + const double right = formula.getVal(); + // Run integral again, also to make sure that setting x has no effect: + EXPECT_DOUBLE_EQ(oneStep.integral(yvals.data()), 0.5 * 200. * (left + right)); + + RooRombergIntegrator twoStep(binding, RooRombergIntegrator::Trapezoid, 2, 1.E-15); + x = 0.; + const double middle = formula.getVal(); + EXPECT_DOUBLE_EQ(twoStep.integral(yvals.data()), 0.25 * 200. * (left + right) + 0.5 * 200. * middle); + } + + // Now run many steps + { + constexpr unsigned int nSteps = 25; + constexpr double relEps = 1.E-50; + RooRombergIntegrator integrator(binding, RooRombergIntegrator::Trapezoid, nSteps, relEps); + double inputs[] = {1., 3.123}; + double target = solution(inputs[0], inputs[1]); + EXPECT_LT(std::abs(integrator.integral(inputs) - target) / target, 1.E-14); + + inputs[0] = a.getVal(); + inputs[1] = b.getVal(); + target = solution(inputs[0], inputs[1]); + EXPECT_LT(std::abs(integrator.integral(inputs) - target) / target, 1.E-14); + + inputs[0] = 4.; + inputs[1] = 5.; + target = solution(inputs[0], inputs[1]); + EXPECT_LT(std::abs(integrator.integral(inputs) - target) / target, 1.E-14); + } +} + +TEST(RooIntegrator1D, RunQuarticFormulaVar) +{ + constexpr unsigned int nSteps = 25; + constexpr double relEps = 1.E-16; + RooRealVar x("x", "x", -50, 50); + RooRealVar a("a", "a", 0.2, -100, 100); + RooRealVar b("b", "b", 0.3, -100, 100); + RooRealVar c("c", "c", 0.4, -100, 100); + RooRealVar d("d", "d", 0.5, -100, 100); + RooFormulaVar formula("formula", "0.1 + x*(a + x*(b + x*(c + d * x)))", {x, a, b, c, d}); + auto solution = [&x](double aVal, double bVal, double cVal, double dVal) { + auto indefInt = [=](double yVal) { + return yVal * (0.1 + yVal * (1. / 2. * aVal + + yVal * (1. / 3. * bVal + yVal * (1. / 4. * cVal + 1. / 5. * dVal * yVal)))); + }; + return indefInt(x.getMax()) - indefInt(x.getMin()); + }; + RooRealBinding binding(formula, {x}); + RooRombergIntegrator integrator(binding, RooRombergIntegrator::Trapezoid, nSteps, relEps); + + double target = solution(0.2, 0.3, 0.4, 0.5); + EXPECT_LT(std::abs(integrator.integral() - target) / target, 1.E-13); +} + +/// Run numeric integrations using RooRombergIntegrator and ROOT's adaptive integrator. Ensure that +/// they reach the requested precision. +void testConvergenceSettings(const RooFormulaVar &formula, const RooArgSet &observables, + const RooArgSet &funcParameters, + std::function solution, + const std::string &name) +{ + constexpr unsigned int nSteps = 25; + constexpr bool printDetails = false; + SCOPED_TRACE(std::string("Function to integrate: ") + name + "\t" + formula.GetTitle()); + + for (double relEps : {1.E-3, 1.E-6, 1.E-8}) { + SCOPED_TRACE(std::string("relEps=" + std::to_string(relEps))); + TStopwatch stopNew; + TStopwatch stopRoot; + + RooRealVar &x = dynamic_cast(*observables[0ul]); + RooArgSet variables(observables); + variables.add(funcParameters); + RooRealBinding binding(formula, variables); + RooRombergIntegrator integrator(binding, RooRombergIntegrator::Trapezoid, nSteps, relEps); + + std::vector errors; + std::vector errorsRootInt; + + RooArgSet initialParameters; + funcParameters.snapshot(initialParameters); + + constexpr unsigned int nRun = 10000; + for (unsigned int i = 0; i < nRun; ++i) { + std::vector pars; + for (const auto p : initialParameters) { + auto par = static_cast(p); + pars.push_back(par->getVal() + (par->getMax() - par->getVal()) / nRun * i); + } + + const double target = solution(pars.data(), pars.size()); + + stopNew.Start(false); + const double integral = integrator.integral(pars.data()); + stopNew.Stop(); + errors.push_back(std::abs((integral - target) / target)); + + { + std::vector vars(1); + std::copy(pars.begin(), pars.end(), std::back_inserter(vars)); + auto bindingROOTInt = [&vars, &binding](double xVal) { + vars[0] = xVal; + return binding(vars.data()); + }; + ROOT::Math::IntegratorOneDim rootIntegrator(bindingROOTInt, ROOT::Math::IntegrationOneDim::kADAPTIVE, + 1.E-20, relEps, 100); + + stopRoot.Start(false); + const double rootIntegral = rootIntegrator.Integral(x.getMin(), x.getMax()); + stopRoot.Stop(); + errorsRootInt.push_back(std::abs((rootIntegral - target) / target)); + } + } + + auto mean = [](const std::vector &vec) { return TMath::Mean(vec.begin(), vec.end()); }; + auto median = [&](const std::vector &vec) { return TMath::Median(vec.size(), vec.data()); }; + auto q95_99 = [&](const std::vector &vec) -> std::pair { + std::vector q(2); + std::vector p(1, 0.95); + p.push_back(0.99); + TMath::Quantiles(vec.size(), q.size(), const_cast(vec.data()), q.data(), p.data(), false); + return {q[0], q[1]}; + }; + + const auto q95_99_int1D = q95_99(errors); + const auto q95_99_intROOT = q95_99(errorsRootInt); + + if (printDetails) { + std::cout << "Integrating " << name << ", relEps = " << relEps; + std::cout << "\n\t \t" + << "mean \tmedian \tq95 \tq99 \tmax"; + const std::vector *vec = &errors; + std::cout << "\n\tnew:\t" << mean(*vec) << "\t" << median(*vec) << "\t" << q95_99_int1D.first << "\t" + << q95_99_int1D.second << "\t" + << "\tt=" << stopNew.CpuTime(); + vec = &errorsRootInt; + std::cout << "\n\tROOT:\t" << mean(*vec) << "\t" << median(*vec) << "\t" << q95_99_intROOT.first << "\t" + << q95_99_intROOT.second << "\t" + << "\tt=" << stopRoot.CpuTime(); + std::cout << std::endl; + } + + // Depending on the function, the integrator precision doesn't reach the + // actual precisiosn parameter, so we give it some headroom. + const double mult = 100.0; + + EXPECT_LT(mean(errors), mult * relEps) << "RooRombergIntegrator should reach target precision."; + EXPECT_LT(mean(errorsRootInt), mult * relEps) << "ROOT integrator should reach target precision."; + + EXPECT_LT(q95_99_int1D.first, mult * relEps) << "95% quantile of errors exceeds relEpsilon"; + EXPECT_LT(q95_99_int1D.second, 2. * mult * relEps) << "99% quantile of errors exceeds 2.*relEpsilon"; + + EXPECT_LT(q95_99_intROOT.first, mult * relEps) << "95% quantile of errors exceeds relEpsilon"; + EXPECT_LT(q95_99_intROOT.second, 2. * mult * relEps) << "95% quantile of errors exceeds relEpsilon"; + } +} + +/// Disabled because the integrator doesn't reach the asked precision. If this +/// behavior gets changed, this can be enabled. +TEST(RooIntegrator1D, ConvergenceSettings_log) +{ + RooRealVar x("x", "x", 0.1, 50); + RooRealVar a("a", "a", 0.2, -100, 1.E5); + RooFormulaVar formula("formula", "log(a*x)", {x, a}); + testConvergenceSettings( + formula, {x}, {a}, + [&x](const double *pars, unsigned int nPar) { + const double aVal = pars[0]; + if (nPar != 1) + throw std::logic_error("Need npar == 1"); + + auto indefInt = [=](double y) { return 1. / aVal * (y * log(y) - y); }; + return indefInt(aVal * x.getMax()) - indefInt(aVal * x.getMin()); + }, + "log(a*x)"); +} + +TEST(RooIntegrator1D, ConvergenceSettings_pol4) +{ + RooRealVar x2("x", "x", -10, 10); + RooRealVar a2("a", "a", 0.2, -1., 1); + RooRealVar b2("b", "b", -0.1, -1., 1); + RooRealVar c2("c", "c", 0.02, -0.1, 0.1); + RooRealVar d2("d", "d", -0., -0.01, 0.01); + RooFormulaVar formula("formula", "0.1 + x*(a + x*(b + x*(c + d * x)))", {x2, a2, b2, c2, d2}); + testConvergenceSettings( + formula, {x2}, {a2, b2, c2, d2}, + [&x2](const double *pars, unsigned int nPar) { + const double a = pars[0]; + const double b = pars[1]; + const double c = pars[2]; + const double d = pars[3]; + if (nPar != 4) + throw std::logic_error("Need npar == 4"); + + auto indefInt = [=](double y) { + return y * (0.1 + y * (1. / 2. * a + y * (1. / 3. * b + y * (1. / 4. * c + 1. / 5. * d * y)))); + }; + return indefInt(x2.getMax()) - indefInt(x2.getMin()); + }, + "Polynomial 4th order"); +} + +/// Disabled because the integrator doesn't reach the asked precision. If this +/// behavior gets changed, this can be enabled. +TEST(RooIntegrator1D, ConvergenceSettings_breitWig) +{ + RooRealVar x3("x", "x", 0., 100.); + RooRealVar a3("a", "a", 10., 100.); + RooRealVar b3("b", "b", 3., 10.); + RooFormulaVar formula("breitwigner", "ROOT::Math::breitwigner_pdf(x, b, a)", {x3, a3, b3}); + testConvergenceSettings( + formula, {x3}, {a3, b3}, + [&x3](const double *pars, unsigned int nPar) { + const double a = pars[0]; + const double b = pars[1]; + if (nPar != 2) + throw std::logic_error("Need npar == 2"); + + return ROOT::Math::breitwigner_cdf(x3.getMax(), b, a) - ROOT::Math::breitwigner_cdf(x3.getMin(), b, a); + }, + "Breit-Wigner distribution"); +} + +TEST(RooIntegrator1D, ConvergenceSettings_Erf) +{ + RooRealVar x("x", "x", -10., 10.); + RooRealVar m("m", "m", -5., 5.); + RooRealVar s("s", "s", 0.5, 10.); + const std::string funcStr = "ROOT::Math::gaussian_pdf(x, s, m)"; + RooFormulaVar formula("gaus", funcStr.c_str(), {x, m, s}); + testConvergenceSettings( + formula, {x}, {m, s}, + [&x](const double *pars, unsigned int nPar) { + const double mVal = pars[0]; + const double sVal = pars[1]; + if (nPar != 2) + throw std::logic_error("Need npar == 2"); + + return ROOT::Math::gaussian_cdf(x.getMax(), sVal, mVal) - ROOT::Math::gaussian_cdf(x.getMin(), sVal, mVal); + }, + "Gaussian distribution"); +} + +TEST(RooIntegrator1D, RunErf_NStep) +{ + RooHelpers::HijackMessageStream hijack(RooFit::WARNING, RooFit::Integration); + constexpr double sigma = 1.3; + constexpr double mean = 0.2; + + for (auto limits : std::initializer_list>{{0.1, 1.5}, {-0.3, 2.}, {2.5, 4.5}}) { + const double min = limits.first; + const double max = limits.second; + RooRealVar theX("theX", "x", min, max); + std::string funcStr = + std::string("ROOT::Math::gaussian_pdf(theX, ") + std::to_string(sigma) + ", " + std::to_string(mean) + ")"; + RooFormulaVar gaus("gaus", funcStr.c_str(), theX); + RooRealBinding binding(gaus, theX); + + double targetError = 0.; + for (unsigned int nSteps = 4; nSteps < 24; ++nSteps) { + RooRombergIntegrator integrator(binding, RooRombergIntegrator::Trapezoid, nSteps, 1.E-17); + const double integral = integrator.integral(); + + const double error = std::abs( + integral - (ROOT::Math::gaussian_cdf(max, sigma, mean) - ROOT::Math::gaussian_cdf(min, sigma, mean))); + + if (nSteps == 4) { + targetError = error; + } else { + // Error should go down faster than 0.5^nSteps because the integrator uses series acceleration, + // so test if it goes down faster than 0.333^nSteps + targetError /= 3.; + // But cannot be better than double precision + EXPECT_LT(error, std::max(targetError, 1.E-16)) << "For step " << nSteps << " with integral=" << integral; + } + if (nSteps > 10) { + EXPECT_LT(error / integral, 1.E-4) << "For step " << nSteps << " with integral=" << integral; + } + if (nSteps > 15) { + EXPECT_LT(error / integral, 1.E-6) << "For step " << nSteps << " with integral=" << integral; + } + if (nSteps > 21) { + EXPECT_LT(error / integral, 1.E-8) << "For step " << nSteps << " with integral=" << integral; + } + } + } +} + +TEST(RooIntegrator1D, RunErf_Midpoint) +{ + const double min = 0, max = 1; + RooRealVar theX("theX", "x", min, max); + RooFormulaVar gaus("gaus", "ROOT::Math::gaussian_pdf(theX, 1, 0)", theX); + RooRealBinding binding(gaus, theX); + double targetError = 0.; + + RooHelpers::HijackMessageStream hijack(RooFit::WARNING, RooFit::Integration); + + for (unsigned int nSteps = 4; nSteps < 20; ++nSteps) { + RooRombergIntegrator integrator(binding, RooRombergIntegrator::Midpoint, nSteps, 1.E-16); + const double integral = integrator.integral(); + const double error = + std::abs(integral - (ROOT::Math::gaussian_cdf(max, 1, 0) - ROOT::Math::gaussian_cdf(min, 1, 0))); + if (nSteps == 4) { + targetError = error; + } else { + // Error should go down faster than 2^nSteps because of series acceleration. + targetError /= 3.; + // But cannot be better than double precision + EXPECT_LT(error, std::max(targetError, 1.E-16)) << "For step " << nSteps << " with integral=" << integral; + } + if (nSteps > 10) { + EXPECT_LT(error / integral, 1.E-4) << "For step " << nSteps << " with integral=" << integral; + } + if (nSteps > 15) { + EXPECT_LT(error / integral, 1.E-6) << "For step " << nSteps << " with integral=" << integral; + } + } +} + +double testIntegrationMethod(int ndim, std::string const &label) +{ + constexpr bool verbose = false; + + RooRealVar x{"x", "x", 0, 10}; + RooRealVar y{"y", "y", 0, 10}; + + std::string funcName = std::string("func") + label; + RooFormulaVar func{funcName.c_str(), "x*std::sqrt(x) + y*std::sqrt(y) + x*y", {x, y}}; + + if (verbose) { + std::cout << label << ":" << std::endl; + } + + RooNumIntConfig cfg(*func.getIntegratorConfig()); + + if (ndim == 2) { + cfg.method2D().setLabel(label.c_str()); + } + if (ndim == 1) { + cfg.method1D().setLabel(label.c_str()); + } + + RooArgSet iset{x}; + if (ndim > 1) { + iset.add(y); + } + std::unique_ptr integ{func.createIntegral(iset, RooFit::NumIntConfig(cfg))}; + double val = integ->getVal(); + if (verbose) { + std::cout << std::setprecision(15) << val << std::endl; + std::cout << std::endl; + } + + return val; +} + +TEST(RooRombergIntegrator, CompareToReference) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + std::vector methods1d{"RooIntegrator1D", "RooSegmentedIntegrator1D"}; + std::vector methods2d{"RooAdaptiveIntegratorND", "RooIntegrator2D", "RooSegmentedIntegrator2D"}; + + // These are reference values obtained with ROOT 6.28.04 + // We compare the results exactly to these references to ensure that the + // implementation has not changed accidentally. These values were printed + // out with setprecision(15), but for the comparisons we only use + // EXPECT_FLOAT_EQ because we are not bothered by foating point precision + // problems here. + std::vector references1d{488.294986988088, 488.294680086881}; + std::vector references2d{5029.82213550336, 5029.84276464679, 5029.82506801992}; + + for (std::size_t i = 0; i < methods1d.size(); ++i) { + double res = testIntegrationMethod(1, methods1d[i]); + EXPECT_FLOAT_EQ(res, references1d[i]) << methods1d[i]; + } + + for (std::size_t i = 0; i < methods2d.size(); ++i) { + double res = testIntegrationMethod(2, methods2d[i]); + EXPECT_FLOAT_EQ(res, references2d[i]) << methods2d[i]; + } +} diff --git a/roofit/roofitcore/test/testRooSimultaneous.cxx b/roofit/roofitcore/test/testRooSimultaneous.cxx index 595f2f7eb5253..d505bcdc0bad3 100644 --- a/roofit/roofitcore/test/testRooSimultaneous.cxx +++ b/roofit/roofitcore/test/testRooSimultaneous.cxx @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -25,7 +26,7 @@ TEST(RooSimultaneous, SingleChannelCrossCheck) using namespace RooFit; // silence log output - RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); RooWorkspace ws; ws.factory("Gaussian::gauss1(x[0, 10], mean[1., 0., 10.], width[1, 0.1, 10])"); @@ -47,10 +48,10 @@ TEST(RooSimultaneous, SingleChannelCrossCheck) using AbsRealPtr = std::unique_ptr; - AbsRealPtr nllDirect{modelConstrained.createNLL(combData)}; - AbsRealPtr nllSimWrapped{modelSim.createNLL(combData)}; - AbsRealPtr nllDirectBatch{modelConstrained.createNLL(combData, BatchMode("cpu"))}; - AbsRealPtr nllSimWrappedBatch{modelSim.createNLL(combData, BatchMode("cpu"))}; + AbsRealPtr nllDirect{modelConstrained.createNLL(combData, EvalBackend::Legacy())}; + AbsRealPtr nllSimWrapped{modelSim.createNLL(combData, EvalBackend::Legacy())}; + AbsRealPtr nllDirectBatch{modelConstrained.createNLL(combData, EvalBackend::Cpu())}; + AbsRealPtr nllSimWrappedBatch{modelSim.createNLL(combData, EvalBackend::Cpu())}; EXPECT_FLOAT_EQ(nllDirect->getVal(), nllSimWrapped->getVal()) << "Inconsistency in old RooFit"; EXPECT_FLOAT_EQ(nllDirect->getVal(), nllDirectBatch->getVal()) << "Old RooFit and BatchMode don't agree"; @@ -63,6 +64,8 @@ TEST(RooSimultaneous, SingleChannelCrossCheck) /// of the observables is a category. TEST(RooSimultaneous, MultiRangeNLL) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + using namespace RooFit; RooWorkspace ws{}; @@ -86,9 +89,9 @@ TEST(RooSimultaneous, MultiRangeNLL) simPdf.addPdf(pdfCat2, "cat2"); // Generate datasets - std::map datasetMap{}; - datasetMap["cat1"] = pdfCat1.generate(RooArgSet(x), 11000); - datasetMap["cat2"] = pdfCat2.generate(RooArgSet(x), 11000); + std::map> datasetMap{}; + datasetMap["cat1"] = std::unique_ptr{pdfCat1.generate(RooArgSet(x), 11000)}; + datasetMap["cat2"] = std::unique_ptr{pdfCat2.generate(RooArgSet(x), 11000)}; RooDataSet combData("combData", "", RooArgSet(x), Index(indexCat), Import(datasetMap)); std::unique_ptr nll{simPdf.createNLL(combData, Range("range1,range2"))}; @@ -98,6 +101,8 @@ TEST(RooSimultaneous, MultiRangeNLL) /// Crash when RooSimultaneous does not contain a pdf for each value of the index category. TEST(RooSimultaneous, CategoriesWithNoPdf) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + RooRealVar x("x", "", 0, 1); RooRealVar rnd("rnd", "", 0, 1); RooThresholdCategory catThr("cat", "", rnd, "v2", 2); @@ -111,7 +116,7 @@ TEST(RooSimultaneous, CategoriesWithNoPdf) RooGenericPdf rndPdf("rndPdf", "", "1", {}); RooProdPdf pdf("pdf", "", RooArgSet(g0, rndPdf)); - auto ds = pdf.generate(RooArgSet(x, rnd), RooFit::Name("ds"), RooFit::NumEvents(100)); + std::unique_ptr ds{pdf.generate(RooArgSet(x, rnd), RooFit::Name("ds"), RooFit::NumEvents(100))}; auto cat = dynamic_cast(ds->addColumn(catThr)); RooSimultaneous sim("sim", "", *cat); @@ -120,12 +125,12 @@ TEST(RooSimultaneous, CategoriesWithNoPdf) // We don't care about the fit result, just that it doesn't crash. using namespace RooFit; - sim.fitTo(*ds, BatchMode(false), PrintLevel(-1)); + sim.fitTo(*ds, EvalBackend::Legacy(), PrintLevel(-1)); m0.setVal(0.5); m0.setError(0.0); m1.setVal(0.5); m1.setError(0.0); - sim.fitTo(*ds, BatchMode(true), PrintLevel(-1)); + sim.fitTo(*ds, EvalBackend::Cpu(), PrintLevel(-1)); } /// GitHub issue #11396. @@ -133,6 +138,8 @@ TEST(RooSimultaneous, CategoriesWithNoPdf) /// fits is correctly considered in multi-range fits. TEST(RooSimultaneous, MultiRangeFitWithSplitRange) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + using namespace RooFit; int nEventsInCat = 11000; @@ -168,8 +175,8 @@ TEST(RooSimultaneous, MultiRangeFitWithSplitRange) const char *cutRange1 = "SideBandLo_cat1,SideBandHi_cat1"; const char *cutRange2 = "SideBandLo_cat2,SideBandHi_cat2"; using RealPtr = std::unique_ptr; - RealPtr nllSim{simPdf.createNLL(combData, Range("SideBandLo,SideBandHi"), SplitRange(), BatchMode("off"))}; - RealPtr nllSimBatch{simPdf.createNLL(combData, Range("SideBandLo,SideBandHi"), SplitRange(), BatchMode("cpu"))}; + RealPtr nllSim{simPdf.createNLL(combData, Range("SideBandLo,SideBandHi"), SplitRange(), EvalBackend::Legacy())}; + RealPtr nllSimBatch{simPdf.createNLL(combData, Range("SideBandLo,SideBandHi"), SplitRange(), EvalBackend::Cpu())}; // In simultaneous PDFs, the probability is normalized over the categories, // so we have to do that as well when computing the reference value. Since @@ -195,9 +202,11 @@ TEST(RooSimultaneous, MultiRangeFitWithSplitRange) /// specific components from a RooSimultaneous. Covers GitHub issue #8231. TEST(RooSimultaneous, RangedCategory) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + using namespace RooFit; - // Create the model with the RooWorkspace to not explicitely depend on + // Create the model with the RooWorkspace to not explicitly depend on // non-RooFitCore classes like RooGaussian RooWorkspace ws; ws.factory("Gaussian::pdfA(x[-10, 10], mu[0, -10, 10], sigma[2.0, 0.1, 10.0])"); @@ -240,12 +249,11 @@ TEST(RooSimultaneous, RangedCategory) sigma.setError(0.0); }; - constexpr auto batchMode = "off"; - - // Funciton to do the fit + // Function to do the fit auto doFit = [&](RooAbsPdf &pdf, RooAbsData &dataset, const char *range = nullptr) { resetParameters(); - std::unique_ptr res{pdf.fitTo(dataset, Range(range), Save(), PrintLevel(-1), BatchMode(batchMode))}; + std::unique_ptr res{ + pdf.fitTo(dataset, Range(range), Save(), PrintLevel(-1), EvalBackend::Legacy())}; resetParameters(); return res; }; @@ -263,3 +271,50 @@ TEST(RooSimultaneous, RangedCategory) EXPECT_TRUE(resB->isIdentical(*resBref)) << "Selecting only state B didn't work!"; EXPECT_TRUE(resAB->isIdentical(*res)) << "Result when selecting all states inconsistent with default fit!"; } + +/// Check that the dataset generation from a nested RooSimultaneous with +/// protodata containing the category values works. +/// Covers GitHub issue #12020. +TEST(RooSimultaneous, NestedSimPdfGenContext) +{ + RooHelpers::LocalChangeMsgLevel locmsg(RooFit::WARNING, 0u, RooFit::InputArguments, false); + + RooRealVar x{"x", "", 0, 1}; + + // It's important that there are different values for the first (inner) + // category such that we can test that the different values are correctly + // picked up from the proto dataset. + RooCategory c1{"c1", ""}; + c1.defineType("c11", 1); + c1.defineType("c12", 2); + + RooCategory c2{"c2", ""}; + c2.defineType("c21", 1); + + RooGenericPdf u11{"u11", "1.0", {}}; + RooGenericPdf u12{"u12", "1.0", {}}; + + RooSimultaneous s1("s1", "", {{"c11", &u11}, {"c12", &u12}}, c1); + RooSimultaneous s2("s2", "", {{"c21", &s1}}, c2); + + RooArgSet categories{c1, c2}; + RooDataSet proto{"proto", "", categories}; + + c1.setIndex(1); + proto.add(categories); + + c1.setIndex(2); + proto.add(categories); + + std::unique_ptr data2{s2.generate(x, RooFit::ProtoData(proto))}; + + auto catIndex = [](RooArgSet const *vars, const char *name) { + return static_cast(vars->find(name))->getCurrentIndex(); + }; + + // If all went well, the category values are taken from the proto dataset + EXPECT_EQ(catIndex(data2->get(0), "c1"), catIndex(proto.get(0), "c1")); + EXPECT_EQ(catIndex(data2->get(0), "c2"), catIndex(proto.get(0), "c2")); + EXPECT_EQ(catIndex(data2->get(1), "c1"), catIndex(proto.get(1), "c1")); + EXPECT_EQ(catIndex(data2->get(1), "c2"), catIndex(proto.get(1), "c2")); +} diff --git a/roofit/roofitcore/test/testRooWrapperPdf.cxx b/roofit/roofitcore/test/testRooWrapperPdf.cxx index b4848833409ae..29ff9066fc62e 100644 --- a/roofit/roofitcore/test/testRooWrapperPdf.cxx +++ b/roofit/roofitcore/test/testRooWrapperPdf.cxx @@ -65,7 +65,7 @@ TEST(RooWrapperPdf, GenerateAndFit) { auto result = polPdf.fitTo(*data, RooFit::Save(), RooFit::PrintLevel(-1)); EXPECT_EQ(result->status(), 0) << "Fit converged."; - EXPECT_LT(fabs(a2.getVal()-0.01), a2.getError()); + EXPECT_LT(std::abs(a2.getVal()-0.01), a2.getError()); // auto frame = x.frame(); // data->plotOn(frame); diff --git a/roofit/roofitcore/test/simple.cxx b/roofit/roofitcore/test/testSimple.cxx similarity index 84% rename from roofit/roofitcore/test/simple.cxx rename to roofit/roofitcore/test/testSimple.cxx index 9714ff7529771..c03f1754c905f 100644 --- a/roofit/roofitcore/test/simple.cxx +++ b/roofit/roofitcore/test/testSimple.cxx @@ -4,13 +4,12 @@ #include "gtest/gtest.h" - // Tests ROOT-6378 TEST(RooRealVar, PrintDefaultConstructed) { std::stringstream s; RooRealVar v; - v.printStream(s, v.defaultPrintContents(""),v.defaultPrintStyle("")); + v.printStream(s, v.defaultPrintContents(""), v.defaultPrintStyle("")); auto resString = s.str(); auto separatorPos = resString.find("+/-"); diff --git a/roofit/roofitcore/test/testSumW2Error.cxx b/roofit/roofitcore/test/testSumW2Error.cxx index d203aa4e8701b..41d090dd1d43d 100644 --- a/roofit/roofitcore/test/testSumW2Error.cxx +++ b/roofit/roofitcore/test/testSumW2Error.cxx @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -15,67 +16,55 @@ // GitHub issue 9118: Problem running weighted binned fit in batch mode TEST(SumW2Error, BatchMode) { - auto &msg = RooMsgService::instance(); - msg.setGlobalKillBelow(RooFit::WARNING); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); RooWorkspace ws{"workspace"}; ws.factory("Gaussian::sig(x[0,0,10],mu[3,0,10],s[1, 0.1, 5])"); ws.factory("Exponential::bkg(x,c1[-0.5, -3, -0.1])"); ws.factory("SUM::model(f[0.2, 0.0, 1.0] * sig, bkg)"); - auto &x = *ws.var("x"); - auto &mu = *ws.var("mu"); - auto &s = *ws.var("s"); - auto &c1 = *ws.var("c1"); - auto &f = *ws.var("f"); - auto &model = *ws.pdf("model"); - auto resetParametersToInitialFitValues = [&]() { - mu.setVal(4.0); - mu.setError(0.0); - s.setVal(2.0); - s.setError(0.0); - c1.setVal(-0.4); - c1.setError(0.0); - f.setVal(0.3); - f.setError(0.0); - }; + RooRandom::randomGenerator()->SetSeed(4357); + std::unique_ptr dataSet{model.generate(*ws.var("x"), 1000)}; - std::size_t nEvents = 1000; + RooArgSet params; + RooArgSet initialParams; - RooRandom::randomGenerator()->SetSeed(4357); - std::unique_ptr dataHist{model.generateBinned(x, nEvents)}; - std::unique_ptr dataSet{model.generate(x, nEvents)}; + model.getParameters(dataSet->get(), params); + params.snapshot(initialParams); // these datasets will be filled with a weight that is not unity - RooRealVar weight("weight", "weight", 0.5, 0.0, 1.0); - RooDataHist dataHistWeighted("dataHistWeighted", "dataHistWeighted", x); - RooDataSet dataSetWeighted("dataSetWeighted", "dataSetWeighted", {x, weight}, "weight"); + RooDataSet dataSetWeighted("dataSetWeighted", "dataSetWeighted", *dataSet->get(), RooFit::WeightVar()); - for (std::size_t i = 0; i < nEvents; ++i) { - dataHistWeighted.add(*dataSet->get(), 0.5); // filling the histogram from a dataset is easier - dataSetWeighted.add(*dataSet->get(), 0.5); + for (int i = 0; i < dataSet->numEntries(); ++i) { + dataSetWeighted.add(*dataSet->get(i), 0.5); } - auto fit = [&](RooAbsData &data, bool sumw2, bool batchmode, std::string const &minimizer, int printLevel = -1) { - using namespace RooFit; + std::unique_ptr dataHist{dataSet->binnedClone()}; + std::unique_ptr dataHistWeighted{dataSetWeighted.binnedClone()}; + + using namespace RooFit; - resetParametersToInitialFitValues(); + auto fit = [&](RooAbsData &data, bool sumw2, EvalBackend evalBackend, std::string const &minimizer, + int printLevel = -1) { + params.assign(initialParams); - return std::unique_ptr{model.fitTo(data, Save(), SumW2Error(sumw2), Strategy(1), - BatchMode(batchmode), Minimizer(minimizer.c_str()), - PrintLevel(printLevel))}; + return std::unique_ptr{model.fitTo(data, Save(), SumW2Error(sumw2), Strategy(1), evalBackend, + Minimizer(minimizer.c_str()), PrintLevel(printLevel))}; }; + auto scalar = EvalBackend::Legacy(); + auto batchMode = EvalBackend::Cpu(); + // Compare batch mode vs. scalar mode for non-SumW2 fits on UNWEIGHTED datasets - EXPECT_TRUE(fit(*dataSet, 0, 0, "Minuit")->isIdentical(*fit(*dataSet, 0, 1, "Minuit"))) + EXPECT_TRUE(fit(*dataSet, 0, scalar, "Minuit")->isIdentical(*fit(*dataSet, 0, batchMode, "Minuit"))) << " different results for Minuit fit to RooDataSet without SumW2Error correction."; - EXPECT_TRUE(fit(*dataHist, 0, 0, "Minuit")->isIdentical(*fit(*dataHist, 0, 1, "Minuit"))) + EXPECT_TRUE(fit(*dataHist, 0, scalar, "Minuit")->isIdentical(*fit(*dataHist, 0, batchMode, "Minuit"))) << " different results for Minuit fit to RooDataHist without SumW2Error correction."; - EXPECT_TRUE(fit(*dataSet, 0, 0, "Minuit2")->isIdentical(*fit(*dataSet, 0, 1, "Minuit2"))) + EXPECT_TRUE(fit(*dataSet, 0, scalar, "Minuit2")->isIdentical(*fit(*dataSet, 0, batchMode, "Minuit2"))) << " different results for Minuit2 fit to RooDataSet without SumW2Error correction."; - EXPECT_TRUE(fit(*dataHist, 0, 0, "Minuit2")->isIdentical(*fit(*dataHist, 0, 1, "Minuit2"))) + EXPECT_TRUE(fit(*dataHist, 0, scalar, "Minuit2")->isIdentical(*fit(*dataHist, 0, batchMode, "Minuit2"))) << " different results for Minuit2 fit to RooDataHist without SumW2Error correction."; // We can't compare the covariance matrix in these next cases, because it is @@ -84,28 +73,34 @@ TEST(SumW2Error, BatchMode) // covariance matrix. // Compare batch mode vs. scalar mode for SumW2 fits on UNWEIGHTED datasets - EXPECT_TRUE(fit(*dataSet, 1, 0, "Minuit")->isIdenticalNoCov(*fit(*dataSet, 1, 1, "Minuit"))) + EXPECT_TRUE(fit(*dataSet, 1, scalar, "Minuit")->isIdenticalNoCov(*fit(*dataSet, 1, batchMode, "Minuit"))) << " different results for Minuit fit to RooDataSet with SumW2Error correction."; - EXPECT_TRUE(fit(*dataHist, 1, 0, "Minuit")->isIdenticalNoCov(*fit(*dataHist, 1, 1, "Minuit"))) + EXPECT_TRUE(fit(*dataHist, 1, scalar, "Minuit")->isIdenticalNoCov(*fit(*dataHist, 1, batchMode, "Minuit"))) << " different results for Minuit fit to RooDataHist with SumW2Error correction."; - EXPECT_TRUE(fit(*dataSet, 1, 0, "Minuit2")->isIdenticalNoCov(*fit(*dataSet, 1, 1, "Minuit2"))) + EXPECT_TRUE(fit(*dataSet, 1, scalar, "Minuit2")->isIdenticalNoCov(*fit(*dataSet, 1, batchMode, "Minuit2"))) << " different results for Minuit2 fit to RooDataSet with SumW2Error correction."; - EXPECT_TRUE(fit(*dataHist, 1, 0, "Minuit2")->isIdenticalNoCov(*fit(*dataHist, 1, 1, "Minuit2"))) + EXPECT_TRUE(fit(*dataHist, 1, scalar, "Minuit2")->isIdenticalNoCov(*fit(*dataHist, 1, batchMode, "Minuit2"))) << " different results for Minuit2 fit to RooDataHist with SumW2Error correction."; // Compare batch mode vs. scalar mode for SumW2 fits on WEIGHTED datasets - EXPECT_TRUE(fit(dataSetWeighted, 1, 0, "Minuit")->isIdenticalNoCov(*fit(dataSetWeighted, 1, 1, "Minuit"))) + EXPECT_TRUE( + fit(dataSetWeighted, 1, scalar, "Minuit")->isIdenticalNoCov(*fit(dataSetWeighted, 1, batchMode, "Minuit"))) << " different results for Minuit fit to weighted RooDataSet with SumW2Error correction."; - EXPECT_TRUE(fit(dataHistWeighted, 1, 0, "Minuit")->isIdenticalNoCov(*fit(dataHistWeighted, 1, 1, "Minuit"))) + EXPECT_TRUE( + fit(*dataHistWeighted, 1, scalar, "Minuit")->isIdenticalNoCov(*fit(*dataHistWeighted, 1, batchMode, "Minuit"))) << " different results for Minuit fit to weighted RooDataHist with SumW2Error correction."; - EXPECT_TRUE(fit(dataSetWeighted, 1, 0, "Minuit2")->isIdenticalNoCov(*fit(dataSetWeighted, 1, 1, "Minuit2"))) + EXPECT_TRUE( + fit(dataSetWeighted, 1, scalar, "Minuit2")->isIdenticalNoCov(*fit(dataSetWeighted, 1, batchMode, "Minuit2"))) << " different results for Minuit2 fit to weighted RooDataSet with SumW2Error correction."; - EXPECT_TRUE(fit(dataHistWeighted, 1, 0, "Minuit2")->isIdenticalNoCov(*fit(dataHistWeighted, 1, 1, "Minuit2"))) + EXPECT_TRUE( + fit(*dataHistWeighted, 1, scalar, "Minuit2")->isIdenticalNoCov(*fit(*dataHistWeighted, 1, batchMode, "Minuit2"))) << " different results for Minuit2 fit to weighted RooDataHist with SumW2Error correction."; } TEST(SumW2Error, ExtendedFit) { + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + using namespace RooFit; RooWorkspace ws("workspace"); @@ -138,31 +133,25 @@ TEST(SumW2Error, ExtendedFit) w->GetName()}; RooDataHist datahist{"datahist", "datahist", *data.get(), data}; - std::vector> inVals; - for (auto const *v : ws.allVars()) { - inVals.emplace_back(v->GetName(), static_cast(v)->getVal()); - } + RooArgSet params; + RooArgSet initialParams; - auto resetVals = [&]() { - for (auto const &item : inVals) { - ws.var(item.first)->setError(0.0); - ws.var(item.first)->setVal(item.second); - } - }; + shp->getParameters(dataNoWeights->get(), params); + params.snapshot(initialParams); - auto doFit = [&](bool batchMode, bool sumW2Error, const char *range) { - resetVals(); + auto doFit = [&](RooFit::EvalBackend evalBackend, bool sumW2Error, const char *range) { + params.assign(initialParams); return std::unique_ptr{shp->fitTo(datahist, Extended(), Range(range), Save(), - SumW2Error(sumW2Error), Strategy(1), PrintLevel(-1), - BatchMode(batchMode), Minimizer("Minuit2", "migrad"))}; + SumW2Error(sumW2Error), Strategy(1), PrintLevel(-1), evalBackend, + Minimizer("Minuit2", "migrad"))}; }; // compare batch mode and scalar mode fit results for full range { - auto yy = doFit(true, true, nullptr); - auto yn = doFit(true, false, nullptr); - auto ny = doFit(false, true, nullptr); - auto nn = doFit(false, false, nullptr); + auto yy = doFit(EvalBackend::Cpu(), true, nullptr); + auto yn = doFit(EvalBackend::Cpu(), false, nullptr); + auto ny = doFit(EvalBackend::Legacy(), true, nullptr); + auto nn = doFit(EvalBackend::Legacy(), false, nullptr); EXPECT_TRUE(yy->isIdenticalNoCov(*ny)) << "different results for extended fit with SumW2Error in BatchMode"; EXPECT_TRUE(yn->isIdenticalNoCov(*nn)) << "different results for extended fit without SumW2Error in BatchMode"; @@ -170,10 +159,10 @@ TEST(SumW2Error, ExtendedFit) // compare batch mode and scalar mode fit results for subrange { - auto yy = doFit(true, true, "subrange"); - auto yn = doFit(true, false, "subrange"); - auto ny = doFit(false, true, "subrange"); - auto nn = doFit(false, false, "subrange"); + auto yy = doFit(EvalBackend::Cpu(), true, "subrange"); + auto yn = doFit(EvalBackend::Cpu(), false, "subrange"); + auto ny = doFit(EvalBackend::Legacy(), true, "subrange"); + auto nn = doFit(EvalBackend::Legacy(), false, "subrange"); EXPECT_TRUE(yy->isIdenticalNoCov(*ny)) << "different results for extended fit in subrange with SumW2Error in BatchMode"; diff --git a/roofit/roofitcore/test/testTestStatistics.cxx b/roofit/roofitcore/test/testTestStatistics.cxx index 70541912b963c..59be8763ed6ef 100644 --- a/roofit/roofitcore/test/testTestStatistics.cxx +++ b/roofit/roofitcore/test/testTestStatistics.cxx @@ -3,320 +3,570 @@ // Jonas Rembser, CERN 10/2022 #include +#include #include #include +#include #include -#include -#include +#include +#include +#include #include -#include #include +#include +#include +#include +#include #include +#include -#include +#include "gtest_wrapper.h" #include +#include + +namespace { + +double getVal(const char *name, const RooArgSet &set) +{ + return static_cast(set[name]).getVal(); +} + +double getErr(const char *name, const RooArgSet &set) +{ + return static_cast(set[name]).getError(); +} + +std::unique_ptr generateBinnedAsimov(RooAbsPdf const &pdf, RooRealVar &x, int nEvents) +{ + auto dataH = std::make_unique("dataH", "dataH", RooArgSet{x}); + RooAbsBinning &xBinning = x.getBinning(); + for (int iBin = 0; iBin < x.numBins(); ++iBin) { + x.setRange("bin", xBinning.binLow(iBin), xBinning.binHigh(iBin)); + std::unique_ptr integ{pdf.createIntegral(x, RooFit::NormSet(x), RooFit::Range("bin"))}; + integ->getVal(); + dataH->set(iBin, nEvents * integ->getVal(), -1); + } + return dataH; +} + +} // namespace + +class TestStatisticTest : public testing::TestWithParam> { +public: + TestStatisticTest() : _evalBackend{RooFit::EvalBackend::Legacy()} {} -const bool batchMode = true; +private: + void SetUp() override + { + RooRandom::randomGenerator()->SetSeed(1337ul); + _evalBackend = std::get<0>(GetParam()); + _changeMsgLvl = std::make_unique(RooFit::WARNING); + } -TEST(RooNLLVar, IntegrateBins) { - RooRandom::randomGenerator()->SetSeed(1337ul); + void TearDown() override { _changeMsgLvl.reset(); } - RooRealVar x("x", "x", 0.1, 5.1); - x.setBins(10); +protected: + RooFit::EvalBackend _evalBackend; - RooRealVar a("a", "a", -0.3, -5., 5.); - RooArgSet targetValues; - RooArgSet(a).snapshot(targetValues); +private: + std::unique_ptr _changeMsgLvl; +}; - RooGenericPdf pdf("pow", "std::pow(x, a)", RooArgSet(x, a)); - std::unique_ptr dataH(pdf.generateBinned(x, 10000)); - RooRealVar w("w", "weight", 0., 0., 10000.); - RooDataSet data("data", "data", RooArgSet(x, w), RooFit::WeightVar(w)); - for (int i=0; i < dataH->numEntries(); ++i) { - auto coords = dataH->get(i); - data.add(*coords, dataH->weight()); - } +TEST_P(TestStatisticTest, IntegrateBins) +{ + RooWorkspace ws; + ws.factory("Power::pow(x[0.1, 5.1], {1.0}, {a[-0.3, -5., 5.]})"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &a = *ws.var("a"); + RooAbsPdf &pdf = *ws.pdf("pow"); - std::unique_ptr frame( x.frame() ); - dataH->plotOn(frame.get(), RooFit::MarkerColor(kRed)); - data.plotOn(frame.get(), RooFit::Name("data")); + x.setBins(10); + RooArgSet targetValues; + RooArgSet(a).snapshot(targetValues); - a.setVal(3.); - std::unique_ptr fit1( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::Name("standard")); + using namespace RooFit; - a.setVal(3.); - std::unique_ptr fit2( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(1.E-3)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::Name("highRes")); + std::unique_ptr dataH(generateBinnedAsimov(pdf, x, 10000)); + auto dataS = std::make_unique("data", "data", x, Import(*dataH)); + std::unique_ptr frame(x.frame()); + dataH->plotOn(frame.get(), MarkerColor(kRed)); + dataS->plotOn(frame.get(), Name("data")); - auto getVal = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getVal(); - }; - auto getErr = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getError(); - }; + a.setVal(3.); + std::unique_ptr fit1(pdf.fitTo(*dataS, Save(), PrintLevel(-1), _evalBackend, SumW2Error(false))); + pdf.plotOn(frame.get(), LineColor(kRed), Name("standard")); - EXPECT_GT(fabs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), 1. * getErr("a", fit1->floatParsFinal())) + a.setVal(3.); + std::unique_ptr fit2( + pdf.fitTo(*dataS, Save(), PrintLevel(-1), _evalBackend, SumW2Error(false), IntegrateBins(1.E-3))); + pdf.plotOn(frame.get(), LineColor(kBlue), Name("highRes")); + + EXPECT_GT(std::abs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), + 1. * getErr("a", fit1->floatParsFinal())) << "Expecting a bias when sampling PDF in bin centre."; - EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) + EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) << "Expect reduced bias with high-resolution sampling."; - EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) + EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) << "Expect chi2/ndf at least 10% better."; } - /// Prepare a RooDataSet that looks like the one that HistFactory uses: /// It pretends to be an unbinned dataset, but instead of single events, /// events are aggregated in the bin centres using weights. -TEST(RooNLLVar, IntegrateBins_SubRange) { - RooRandom::randomGenerator()->SetSeed(1337ul); - - RooRealVar x("x", "x", 0.1, 5.1); - x.setBins(10); - x.setRange("range", 0.1, 4.1); - x.setBins(8, "range"); // consistent binning - - RooRealVar a("a", "a", -0.3, -5., 5.); - RooArgSet targetValues; - RooArgSet(a).snapshot(targetValues); - - RooGenericPdf pdf("pow", "std::pow(x, a)", RooArgSet(x, a)); - std::unique_ptr dataH(pdf.generateBinned(x, 10000)); - RooRealVar w("w", "weight", 0., 0., 10000.); - RooDataSet data("data", "data", RooArgSet(x, w), RooFit::WeightVar(w)); - for (int i=0; i < dataH->numEntries(); ++i) { - auto coords = dataH->get(i); - data.add(*coords, dataH->weight()); - } - - std::unique_ptr frame( x.frame() ); - dataH->plotOn(frame.get(), RooFit::MarkerColor(kRed)); - data.plotOn(frame.get(), RooFit::Name("data")); - - - a.setVal(3.); - std::unique_ptr fit1( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::Optimize(0), - RooFit::Range("range"), - RooFit::BatchMode(batchMode)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::Name("standard")); - - a.setVal(3.); - std::unique_ptr fit2( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::Optimize(0), - RooFit::Range("range"), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(1.E-3)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::Name("highRes")); - - - auto getVal = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getVal(); - }; - auto getErr = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getError(); - }; - - EXPECT_GT(fabs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), 1. * getErr("a", fit1->floatParsFinal())) +TEST_P(TestStatisticTest, IntegrateBins_SubRange) +{ + RooWorkspace ws; + ws.factory("Power::pow(x[0.1, 5.1], {1.0}, {a[-0.3, -5., 5.]})"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &a = *ws.var("a"); + RooAbsPdf &pdf = *ws.pdf("pow"); + + x.setBins(10); + x.setRange("range", 0.1, 4.1); + x.setBins(8, "range"); // consistent binning + + RooArgSet targetValues; + RooArgSet(a).snapshot(targetValues); + + using namespace RooFit; + + std::unique_ptr dataH(generateBinnedAsimov(pdf, x, 10000)); + auto dataS = std::make_unique("data", "data", x, Import(*dataH)); + + std::unique_ptr frame(x.frame()); + dataH->plotOn(frame.get(), MarkerColor(kRed)); + dataS->plotOn(frame.get(), Name("data")); + + a.setVal(3.); + std::unique_ptr fit1( + pdf.fitTo(*dataS, Save(), PrintLevel(-1), Optimize(0), Range("range"), _evalBackend, SumW2Error(false))); + pdf.plotOn(frame.get(), LineColor(kRed), Name("standard"), Range("range"), NormRange("range")); + + a.setVal(3.); + std::unique_ptr fit2(pdf.fitTo(*dataS, Save(), PrintLevel(-1), Optimize(0), Range("range"), + _evalBackend, SumW2Error(false), IntegrateBins(1.E-3))); + pdf.plotOn(frame.get(), LineColor(kBlue), Name("highRes"), Range("range"), NormRange("range")); + + EXPECT_GT(std::abs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), + 1. * getErr("a", fit1->floatParsFinal())) << "Expecting a bias when sampling PDF in bin centre."; - EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) + EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) << "Expect reduced bias with high-resolution sampling."; - EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) + EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) << "Expect chi2/ndf at least 10% better."; } /// Prepare a RooDataSet that looks like the one that HistFactory uses: /// It pretends to be an unbinned dataset, but instead of single events, /// events are aggregated in the bin centres using weights. -TEST(RooNLLVar, IntegrateBins_CustomBinning) { - RooRandom::randomGenerator()->SetSeed(1337ul); - - RooRealVar x("x", "x", 1., 5.); - RooBinning binning(1., 5.); - binning.addBoundary(1.5); - binning.addBoundary(2.0); - binning.addBoundary(3.); - binning.addBoundary(4.); - x.setBinning(binning); - - RooRealVar a("a", "a", -0.3, -5., 5.); - RooArgSet targetValues; - RooArgSet(a).snapshot(targetValues); - - RooGenericPdf pdf("pow", "std::pow(x, a)", RooArgSet(x, a)); - std::unique_ptr dataH(pdf.generateBinned(x, 50000)); - RooRealVar w("w", "weight", 0., 0., 1000000.); - RooDataSet data("data", "data", RooArgSet(x, w), RooFit::WeightVar(w)); - for (int i=0; i < dataH->numEntries(); ++i) { - auto coords = dataH->get(i); - data.add(*coords, dataH->weight()); - } - - std::unique_ptr frame( x.frame() ); - dataH->plotOn(frame.get(), RooFit::Name("dataHist"), RooFit::MarkerColor(kRed)); - data.plotOn(frame.get(), RooFit::Name("data")); - - - a.setVal(3.); - std::unique_ptr fit1( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::Optimize(0)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::Name("standard")); - - a.setVal(3.); - std::unique_ptr fit2( pdf.fitTo(data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::Optimize(0), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(1.E-3)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::Name("highRes")); - - - auto getVal = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getVal(); - }; - auto getErr = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getError(); - }; - - EXPECT_GT(fabs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), 1. * getErr("a", fit1->floatParsFinal())) +TEST_P(TestStatisticTest, IntegrateBins_CustomBinning) +{ + RooWorkspace ws; + ws.factory("Power::pow(x[1.0, 5.], {1.0}, {a[-0.3, -5., 5.]})"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &a = *ws.var("a"); + RooAbsPdf &pdf = *ws.pdf("pow"); + + RooBinning binning(1., 5.); + binning.addBoundary(1.5); + binning.addBoundary(2.0); + binning.addBoundary(3.); + binning.addBoundary(4.); + x.setBinning(binning); + + RooArgSet targetValues; + RooArgSet(a).snapshot(targetValues); + + using namespace RooFit; + + std::unique_ptr dataH(generateBinnedAsimov(pdf, x, 50000)); + auto dataS = std::make_unique("data", "data", x, Import(*dataH)); + + std::unique_ptr frame(x.frame()); + dataH->plotOn(frame.get(), Name("dataHist"), MarkerColor(kRed)); + dataS->plotOn(frame.get(), Name("data")); + + a.setVal(3.); + std::unique_ptr fit1( + pdf.fitTo(*dataS, Save(), PrintLevel(-1), _evalBackend, SumW2Error(false), Optimize(0))); + pdf.plotOn(frame.get(), LineColor(kRed), Name("standard")); + + a.setVal(3.); + std::unique_ptr fit2( + pdf.fitTo(*dataS, Save(), PrintLevel(-1), Optimize(0), _evalBackend, SumW2Error(false), IntegrateBins(1.E-3))); + pdf.plotOn(frame.get(), LineColor(kBlue), Name("highRes")); + + EXPECT_GT(std::abs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), + 1. * getErr("a", fit1->floatParsFinal())) << "Expecting a bias when sampling PDF in bin centre."; - EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) + EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) << "Expect reduced bias with high-resolution sampling."; - // Note: We cannot compare with the unbinned dataset here, because when it's plotted, it's filled into a - // histogram with uniform binning. It therefore creates a jumpy distribution. When comparing with the original - // data hist, we don't get those jumps. - EXPECT_GT(frame->chiSquare("standard", "dataHist", 1) * 0.9, frame->chiSquare("highRes", "dataHist", 1)) + // Note: We cannot compare with the unbinned dataset here, because when it's plotted, it's filled into a + // histogram with uniform binning. It therefore creates a jumpy distribution. When comparing with the original + // data hist, we don't get those jumps. + EXPECT_GT(frame->chiSquare("standard", "dataHist", 1) * 0.9, frame->chiSquare("highRes", "dataHist", 1)) << "Expect chi2/ndf at least 10% better."; } - /// Test the same, but now with RooDataHist. Here, the feature should switch on automatically. -TEST(RooNLLVar, IntegrateBins_RooDataHist) { - RooRealVar x("x", "x", 0.1, 5.); - x.setBins(10); +TEST_P(TestStatisticTest, IntegrateBins_RooDataHist) +{ + RooWorkspace ws; + ws.factory("Power::pow(x[0.1, 5.0], {1.0}, {a[-0.3, -5., 5.]})"); - RooRealVar a("a", "a", -0.3, -5., 5.); - RooArgSet targetValues; - RooArgSet(a).snapshot(targetValues); + RooRealVar &x = *ws.var("x"); + RooRealVar &a = *ws.var("a"); + RooAbsPdf &pdf = *ws.pdf("pow"); - RooGenericPdf pdf("pow", "std::pow(x, a)", RooArgSet(x, a)); - std::unique_ptr data(pdf.generateBinned(x, 10000)); + x.setBins(10); - std::unique_ptr frame( x.frame() ); - data->plotOn(frame.get(), RooFit::Name("data")); + RooArgSet targetValues; + RooArgSet(a).snapshot(targetValues); + using namespace RooFit; - a.setVal(3.); - std::unique_ptr fit1( pdf.fitTo(*data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(-1.) // Disable forcefully - ) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::Name("standard")); + std::unique_ptr data(generateBinnedAsimov(pdf, x, 10000)); - a.setVal(3.); - std::unique_ptr fit2( pdf.fitTo(*data, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(0.) // Auto-enable for all RooDataHists. - ) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::Name("highRes")); + std::unique_ptr frame(x.frame()); + data->plotOn(frame.get(), Name("data")); + a.setVal(3.); + // Disable IntegrateBins forcefully + std::unique_ptr fit1( + pdf.fitTo(*data, Save(), PrintLevel(-1), _evalBackend, SumW2Error(false), IntegrateBins(-1.))); + pdf.plotOn(frame.get(), LineColor(kRed), Name("standard")); - auto getVal = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getVal(); - }; - auto getErr = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getError(); - }; + a.setVal(3.); + // Auto-enable IntegrateBins for all RooDataHists. + std::unique_ptr fit2( + pdf.fitTo(*data, Save(), PrintLevel(-1), _evalBackend, SumW2Error(false), IntegrateBins(0.))); + pdf.plotOn(frame.get(), LineColor(kBlue), Name("highRes")); - EXPECT_GT(fabs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), 1. * getErr("a", fit1->floatParsFinal())) + EXPECT_GT(std::abs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), + 1. * getErr("a", fit1->floatParsFinal())) << "Expecting a bias when sampling PDF in bin centre."; - EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) + EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) << "Expect reduced bias with high-resolution sampling."; - EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) + EXPECT_GT(frame->chiSquare("standard", "data", 1) * 0.9, frame->chiSquare("highRes", "data", 1)) << "Expect chi2/ndf at least 10% better."; } +TEST(RooChi2Var, IntegrateBins) +{ + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); -TEST(RooChi2Var, IntegrateBins) { - RooRandom::randomGenerator()->SetSeed(1337ul); + RooRandom::randomGenerator()->SetSeed(1337ul); - RooRealVar x("x", "x", 0.1, 5.1); - x.setBins(10); + RooWorkspace ws; + ws.factory("Power::pow(x[0.1, 5.1], {1.0}, {a[-0.3, -5., 5.]})"); - RooRealVar a("a", "a", -0.3, -5., 5.); - RooArgSet targetValues; - RooArgSet(a).snapshot(targetValues); + RooRealVar &x = *ws.var("x"); + RooRealVar &a = *ws.var("a"); + RooAbsPdf &pdf = *ws.pdf("pow"); - RooGenericPdf pdf("pow", "std::pow(x, a)", RooArgSet(x, a)); - std::unique_ptr dataH(pdf.generateBinned(x, 10000)); + x.setBins(10); - std::unique_ptr frame( x.frame() ); - dataH->plotOn(frame.get(), RooFit::MarkerColor(kRed)); + RooArgSet targetValues; + RooArgSet(a).snapshot(targetValues); + using namespace RooFit; - a.setVal(3.); - std::unique_ptr fit1( pdf.chi2FitTo(*dataH, RooFit::Save(), RooFit::PrintLevel(-1)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kRed), RooFit::Name("standard")); + std::unique_ptr dataH(generateBinnedAsimov(pdf, x, 10000)); - a.setVal(3.); - std::unique_ptr fit2( pdf.chi2FitTo(*dataH, RooFit::Save(), RooFit::PrintLevel(-1), - RooFit::BatchMode(batchMode), - RooFit::IntegrateBins(1.E-3)) ); - pdf.plotOn(frame.get(), RooFit::LineColor(kBlue), RooFit::Name("highRes")); + std::unique_ptr frame(x.frame()); + dataH->plotOn(frame.get(), MarkerColor(kRed)); + a.setVal(3.); + std::unique_ptr fit1(pdf.chi2FitTo(*dataH, Save(), PrintLevel(-1))); + pdf.plotOn(frame.get(), LineColor(kRed), Name("standard")); - auto getVal = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getVal(); - }; - auto getErr = [](const char* name, const RooArgSet& set) { - return dynamic_cast(set[name]).getError(); - }; + a.setVal(3.); + std::unique_ptr fit2(pdf.chi2FitTo(*dataH, Save(), PrintLevel(-1), IntegrateBins(1.E-3))); + pdf.plotOn(frame.get(), LineColor(kBlue), Name("highRes")); - EXPECT_GT(fabs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), 1. * getErr("a", fit1->floatParsFinal())) + EXPECT_GT(std::abs(getVal("a", targetValues) - getVal("a", fit1->floatParsFinal())), + 1. * getErr("a", fit1->floatParsFinal())) << "Expecting a bias when sampling PDF in bin centre."; - EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) + EXPECT_NEAR(getVal("a", targetValues), getVal("a", fit2->floatParsFinal()), 1. * getErr("a", fit2->floatParsFinal())) << "Expect reduced bias with high-resolution sampling."; - EXPECT_GT(frame->chiSquare("standard", nullptr, 1) * 0.9, frame->chiSquare("highRes", nullptr, 1)) + EXPECT_GT(frame->chiSquare("standard", nullptr, 1) * 0.9, frame->chiSquare("highRes", nullptr, 1)) << "Expect chi2/ndf at least 10% better."; } - /// Verifies that a ranged RooNLLVar has still the correct value when copied, /// as it happens when it is plotted Covers JIRA ticket ROOT-9752. TEST(RooNLLVar, CopyRangedNLL) { - RooRealVar x("x", "x", 0, 10); - RooRealVar mean("mean", "mean", 5, 0, 10); - RooRealVar sigma("sigma", "sigma", 0.5, 0.01, 5); - RooGaussian model("model", "model", x, mean, sigma); + RooHelpers::LocalChangeMsgLevel changeMsgLvl(RooFit::WARNING); + + RooWorkspace ws; + ws.factory("Gaussian::model(x[0, 10], mean[5, 0, 10], sigma[0.5, 0.01, 5.0])"); + + RooRealVar &x = *ws.var("x"); + RooAbsPdf &model = *ws.pdf("model"); x.setRange("fitrange", 0, 10); std::unique_ptr ds{model.generate(x, 20)}; - // This bug is related to the implementation details of the old test statistics, so BatchMode is forced to be off + // This bug is related to the implementation details of the old test + // statistics, so the EvalBackend is forced to be Legacy using namespace RooFit; - std::unique_ptr nll{static_cast(model.createNLL(*ds, BatchMode("off")))}; - std::unique_ptr nllrange{static_cast(model.createNLL(*ds, Range("fitrange"), BatchMode("off")))}; + std::unique_ptr nll{model.createNLL(*ds, EvalBackend::Legacy())}; + std::unique_ptr nllrange{model.createNLL(*ds, Range("fitrange"), EvalBackend::Legacy())}; - auto nllClone = std::make_unique(*nll); - auto nllrangeClone = std::make_unique(*nllrange); + auto nllClone = std::make_unique(static_cast(*nll)); + auto nllrangeClone = std::make_unique(static_cast(*nllrange)); EXPECT_FLOAT_EQ(nll->getVal(), nllClone->getVal()); EXPECT_FLOAT_EQ(nll->getVal(), nllrange->getVal()); EXPECT_FLOAT_EQ(nllrange->getVal(), nllrangeClone->getVal()); } + +/// When using the Integrate() command argument in chi2FitTo, the result should +/// be identical to a fit without bin integration if the fit function is +/// linear. This is a good cross check to see if the integration works. +/// Inspired by the rf609_xychi2fit tutorial. +TEST(RooXYChi2Var, IntegrateLinearFunction) +{ + using namespace RooFit; + + // Make weighted XY dataset with asymmetric errors stored The StoreError() + // argument is essential as it makes the dataset store the error in addition + // to the values of the observables. If errors on one or more observables + // are asymmetric, one can store the asymmetric error using the + // StoreAsymError() argument + RooRealVar x("x", "x", -11, 11); + RooRealVar y("y", "y", -10, 200); + RooDataSet dxy("dxy", "dxy", {x, y}, StoreError({x, y})); + + const double aTrue = 0.1; + const double bTrue = 10.0; + + // Fill an example dataset with X,err(X),Y,err(Y) values + for (int i = 0; i <= 10; i++) { + + // Set X value and error + x = -10 + 2 * i; + x.setError(i < 5 ? 0.5 / 1. : 1.0 / 1.); + + // Set Y value and error + y = aTrue * x.getVal() + bTrue; + y.setError(std::sqrt(y.getVal())); + + dxy.add({x, y}); + } + + // Make linear fit function + RooRealVar a("a", "a", 0.0, -10, 10); + RooRealVar b("b", "b", 0.0, -100, 100); + RooArgList coefs{b, a}; + RooPolyVar f("f", "f", x, coefs); + + RooArgSet savedValues; + coefs.snapshot(savedValues); + + // Fit chi^2 using X and Y errors + std::unique_ptr fit1{f.chi2FitTo(dxy, YVar(y), Save(), PrintLevel(-1), Optimize(0))}; + + coefs.assign(savedValues); + // Alternative: fit chi^2 integrating f(x) over ranges defined by X errors, + // rather than taking point at center of bin + std::unique_ptr fit2{f.chi2FitTo(dxy, YVar(y), Integrate(true), Save(), PrintLevel(-1), Optimize(0))}; + + // Verify that the fit result is compatible with true values within the error + EXPECT_NEAR(getVal("a", fit1->floatParsFinal()), aTrue, getErr("a", fit1->floatParsFinal())); + EXPECT_NEAR(getVal("b", fit1->floatParsFinal()), bTrue, getErr("b", fit1->floatParsFinal())); + + EXPECT_NEAR(getVal("a", fit2->floatParsFinal()), aTrue, getErr("a", fit2->floatParsFinal())); + EXPECT_NEAR(getVal("b", fit2->floatParsFinal()), bTrue, getErr("b", fit2->floatParsFinal())); +} + +class OffsetBinTest : public testing::TestWithParam> { +public: + OffsetBinTest() : _evalBackend{RooFit::EvalBackend::Legacy()} {} + +private: + void SetUp() override + { + _changeMsgLvl = std::make_unique(RooFit::WARNING); + _evalBackend = std::get<0>(GetParam()); + _binned = std::get<1>(GetParam()); + _ext = std::get<2>(GetParam()); + _sumw2 = std::get<3>(GetParam()); + } + + void TearDown() override { _changeMsgLvl.reset(); } + +protected: + RooFit::EvalBackend _evalBackend; + bool _binned = false; + bool _ext = false; + bool _sumw2 = false; + +private: + std::unique_ptr _changeMsgLvl; +}; + +// Test the `Offset("bin")` feature of RooAbsPdf::createNLL. Doing the +// bin-by-bin offset is equivalent to calculating the likelihood ratio with the +// NLL of a template histogram that is based of the dataset, so we use this +// relation to do a cross check: if we create a template pdf from the fit data +// and fit this template to the data with the `Offset("bin")` option, the +// resulting NLL should always be zero (within some numerical errors). +TEST_P(OffsetBinTest, CrossCheck) +{ + using namespace RooFit; + using RealPtr = std::unique_ptr; + + // Create extended PDF model + RooWorkspace ws; + ws.factory("Gaussian::gauss(x[-10, 10], mean[0, -10, 10], sigma[4, 0.1, 10])"); + ws.factory("AddPdf::extGauss({gauss}, {nEvents[10000, 100, 100000]})"); + + RooRealVar &x = *ws.var("x"); + RooRealVar &nEvents = *ws.var("nEvents"); + RooAbsPdf &extGauss = *ws.pdf("extGauss"); + + // We have to generate double the number of events because in the next step + // we will weight down each event by a factor of two. + std::unique_ptr data{extGauss.generate(x, 2. * nEvents.getVal())}; + + // Replace dataset with a clone where the weights are different from unity + // such that the effect of the SumW2Error option is not trivial and we test + // it correctly. + { + // Create weighted dataset and hist to test SumW2 feature + auto dataW = std::make_unique("dataW", "dataW", x, RooFit::WeightVar()); + for (int i = 0; i < data->numEntries(); ++i) { + dataW->add(*data->get(i), 0.5); + } + std::swap(dataW, data); + } + + std::unique_ptr hist{data->binnedClone()}; + + // Create template PDF based on data + RooHistPdf histPdf{"histPdf", "histPdf", x, *hist}; + RooExtendPdf extHistPdf("extHistPdf", "extHistPdf", histPdf, nEvents); + + RooAbsData *fitData = _binned ? static_cast(hist.get()) : static_cast(data.get()); + + RealPtr nll0{extHistPdf.createNLL(*fitData, _evalBackend, Extended(_ext))}; + RealPtr nll1{extHistPdf.createNLL(*fitData, Offset("bin"), _evalBackend, Extended(_ext))}; + + if (_sumw2) { + nll0->applyWeightSquared(true); + nll1->applyWeightSquared(true); + } + + double nllVal0 = nll0->getVal(); + double nllVal1 = nll1->getVal(); + + // For all configurations, the bin offset should have the effect of bringing + // the NLL to zero, modulo some numerical imprecisions: + EXPECT_NEAR(nllVal1, 0.0, 1e-8) << "NLL with bin offsetting is " << nllVal1 << ", and " << nllVal0 << " without it."; +} + +// Verify that the binned likelihood optimization works also when fitting a +// single-channel RooRealSumPdf or RooProdPdf. +TEST_P(TestStatisticTest, BinnedLikelihood) +{ + using namespace RooFit; + + int nEvents = 1000; + int numBins = 5; + + RooWorkspace ws; + + ws.factory("x[0, 0, " + std::to_string(numBins) + "]"); + + auto &x = *ws.var("x"); + x.setBins(numBins); + + { + // Uniform RooDataHist + RooDataHist dataHist{"data_hist", "data_hist", x}; + for (int iBin = 0; iBin < numBins; ++iBin) { + dataHist.set(iBin, nEvents / numBins, -1); + } + + RooHistFunc histFunc{"hist_func", "hist_func", x, dataHist}; + RooRealSumPdf pdf{"pdf", "pdf", histFunc, RooArgList{1.0}}; + + // Enable the binned likelihood optimization to avoid integrals + // (like in HistFactory). + pdf.setAttribute("BinnedLikelihood"); + + // Wrap the channel pdf in a RooProdPdf to mimic HistFactory + RooProdPdf prodPdf{"prod_pdf", "prod_pdf", pdf}; + + ws.import(prodPdf); + } + + ws.factory("SIMUL::simPdf( cat[A=0], A=pdf)"); + auto &realSumPdf = *ws.pdf("pdf"); + auto &prodPdf = *ws.pdf("prod_pdf"); + auto &simPdf = *ws.pdf("simPdf"); + auto &cat = *ws.cat("cat"); + + std::unique_ptr data{simPdf.generateBinned({x, cat}, nEvents)}; + + std::unique_ptr realSumNll{realSumPdf.createNLL(*data, _evalBackend)}; + std::unique_ptr prodNll{prodPdf.createNLL(*data, _evalBackend)}; + std::unique_ptr simNll{simPdf.createNLL(*data, _evalBackend)}; + + double realSumNllVal = realSumNll->getVal(); + double prodNllVal = prodNll->getVal(); + double simNllVal = simNll->getVal(); + + // If using the RooRealSumPdf or RooProdPdf directly is successfully hitting + // the binned likelihood code path, the likelihood values will be identical + // with the one of the RooSimultaneous. + EXPECT_DOUBLE_EQ(realSumNllVal, simNllVal); + EXPECT_DOUBLE_EQ(prodNllVal, simNllVal); +} + +#ifdef R__HAS_CUDA +#define EVAL_BACKENDS RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu(), RooFit::EvalBackend::Cuda() +#else +#define EVAL_BACKENDS RooFit::EvalBackend::Legacy(), RooFit::EvalBackend::Cpu() +#endif + +INSTANTIATE_TEST_SUITE_P(RooNLLVar, TestStatisticTest, testing::Values(EVAL_BACKENDS), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "EvalBackend" << std::get<0>(paramInfo.param).name(); + return ss.str(); + }); + +INSTANTIATE_TEST_SUITE_P(RooNLLVar, OffsetBinTest, + testing::Combine(testing::Values(EVAL_BACKENDS), // EvalBackend + testing::Values(false, true), // unbinned or binned + testing::Values(false, true), // extended fit + testing::Values(false, true) // use sumW2 + ), + [](testing::TestParamInfo const ¶mInfo) { + std::stringstream ss; + ss << "EvalBackend" << std::get<0>(paramInfo.param).name(); + ss << (std::get<1>(paramInfo.param) ? "Binned" : "Unbinned"); + ss << (std::get<2>(paramInfo.param) ? "Extended" : ""); + ss << (std::get<3>(paramInfo.param) ? "SumW2" : ""); + return ss.str(); + }); diff --git a/roofit/roofitcore/test/testWorkspace.cxx b/roofit/roofitcore/test/testWorkspace.cxx index 9b569002266b0..c366dbe1bd862 100644 --- a/roofit/roofitcore/test/testWorkspace.cxx +++ b/roofit/roofitcore/test/testWorkspace.cxx @@ -38,26 +38,23 @@ TEST(RooWorkspace, CloneModelConfig_ROOT_9777) TFile outfile(filename, "RECREATE"); // now create the model config for this problem - RooWorkspace* w = new RooWorkspace("ws"); - ModelConfig modelConfig("ModelConfig", w); + RooWorkspace ws{"ws"}; + ModelConfig modelConfig("ModelConfig", &ws); modelConfig.SetPdf(pdf); modelConfig.SetParametersOfInterest(RooArgSet(sigma)); modelConfig.SetGlobalObservables(RooArgSet(mu)); - w->import(modelConfig); + ws.import(modelConfig); - outfile.WriteObject(w, "ws"); - delete w; + outfile.WriteObject(&ws, "ws"); } RooWorkspace *w2; { TFile infile(filename, "READ"); - RooWorkspace *w; - infile.GetObject("ws", w); - ASSERT_TRUE(w) << "Workspace not read from file."; + std::unique_ptr ws{infile.Get("ws")}; + ASSERT_TRUE(ws) << "Workspace not read from file."; - w2 = new RooWorkspace(*w); - delete w; + w2 = new RooWorkspace(*ws); } if(verbose) w2->Print(); @@ -250,7 +247,7 @@ TEST(RooWorkspace, Issue_7965) } /// Covers an issue about the RooProdPdf constructor taking a RooFit collection -/// not working and the RooProduct constuctors behaving inconsistently. +/// not working and the RooProduct constructors behaving inconsistently. TEST(RooWorkspace, Issue_7809) { RooWorkspace ws; diff --git a/roofit/roofitcore/test/test_lib.h b/roofit/roofitcore/test/test_lib.h index 5d6ea41266b11..edb2af6f9620d 100644 --- a/roofit/roofitcore/test/test_lib.h +++ b/roofit/roofitcore/test/test_lib.h @@ -13,155 +13,136 @@ #ifndef ROOT_TEST_LIB_H #define ROOT_TEST_LIB_H -#include "RooWorkspace.h" -#include "RooRandom.h" -#include "RooAddPdf.h" -#include "RooDataSet.h" -#include "RooRealVar.h" // for the dynamic cast to have a complete type +#include +#include +#include +#include +#include // for the dynamic cast to have a complete type +#include #include -#include // make_unique +#include // make_unique #include -RooAbsPdf * generate_1D_gaussian_pdf(RooWorkspace &w) +RooAbsPdf *generate_1D_gaussian_pdf(RooWorkspace &ws) { - w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); - RooAbsPdf *pdf = w.pdf("g"); + ws.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])"); + RooAbsPdf *pdf = ws.pdf("g"); return pdf; } -RooDataSet * generate_1D_dataset(RooWorkspace &w, RooAbsPdf *pdf, unsigned long N_events) +std::unique_ptr generate_1D_dataset(RooWorkspace &ws, RooAbsPdf *pdf, unsigned long nEvents) { - RooDataSet *data = pdf->generate(RooArgSet(*w.var("x")), N_events); - return data; + return std::unique_ptr{pdf->generate(RooArgSet(*ws.var("x")), nEvents)}; } - -std::tuple, RooAbsPdf *, RooDataSet *, std::unique_ptr> -generate_1D_gaussian_pdf_nll(RooWorkspace &w, unsigned long N_events) +std::tuple, RooAbsPdf *, std::unique_ptr, std::unique_ptr> +generate_1D_gaussian_pdf_nll(RooWorkspace &ws, unsigned long nEvents) { - RooAbsPdf *pdf = generate_1D_gaussian_pdf(w); + RooAbsPdf *pdf = generate_1D_gaussian_pdf(ws); - RooDataSet *data = generate_1D_dataset(w, pdf, N_events); + std::unique_ptr data{generate_1D_dataset(ws, pdf, nEvents)}; - RooRealVar *mu = w.var("mu"); + RooRealVar *mu = ws.var("mu"); mu->setVal(-2.9); std::unique_ptr nll{pdf->createNLL(*data)}; // save initial values for the start of all minimizations - std::unique_ptr values = std::make_unique(*mu, *pdf, *nll, "values"); + auto values = std::make_unique(*mu, *pdf, *nll, "values"); - return std::make_tuple(std::move(nll), pdf, data, std::move(values)); + return {std::move(nll), pdf, std::move(data), std::move(values)}; } // return two unique_ptrs, the first because nll is a pointer, // the second because RooArgSet doesn't have a move ctor -std::tuple, RooAbsPdf *, RooDataSet *, std::unique_ptr> -generate_ND_gaussian_pdf_nll(RooWorkspace &w, unsigned int n, unsigned long N_events, bool batch_mode = false) { - RooArgSet obs_set; - - // create gaussian parameters - std::vector mean(n), sigma(n); - for (unsigned ix = 0; ix < n; ++ix) { - mean[ix] = RooRandom::randomGenerator()->Gaus(0, 2); - sigma[ix] = 0.1 + abs(RooRandom::randomGenerator()->Gaus(0, 2)); - } - - // create gaussians and also the observables and parameters they depend on - for (unsigned ix = 0; ix < n; ++ix) { - std::ostringstream os; - os << "Gaussian::g" << ix - << "(x" << ix << "[-10,10]," - << "m" << ix << "[" << mean[ix] << ",-10,10]," - << "s" << ix << "[" << sigma[ix] << ",0.1,10])"; - w.factory(os.str()); - } - - // create uniform background signals on each observable - for (unsigned ix = 0; ix < n; ++ix) { - { - std::ostringstream os; - os << "Uniform::u" << ix << "(x" << ix << ")"; - w.factory(os.str()); - } - - // gather the observables in a list for data generation below - { - std::ostringstream os; - os << "x" << ix; - obs_set.add(*w.arg(os.str().c_str())); - } - } - - RooArgSet pdf_set = w.allPdfs(); - - // create event counts for all pdfs - RooArgSet count_set; - - // ... for the gaussians - for (unsigned ix = 0; ix < n; ++ix) { - std::stringstream os, os2; - os << "Nsig" << ix; - os2 << "#signal events comp " << ix; - RooRealVar a(os.str().c_str(), os2.str().c_str(), N_events/10, 0., 10*N_events); - w.import(a); - // gather in count_set - count_set.add(*w.arg(os.str().c_str())); - } - // ... and for the uniform background components - for (unsigned ix = 0; ix < n; ++ix) { - std::stringstream os, os2; - os << "Nbkg" << ix; - os2 << "#background events comp " << ix; - RooRealVar a(os.str().c_str(), os2.str().c_str(), N_events/10, 0., 10*N_events); - w.import(a); - // gather in count_set - count_set.add(*w.arg(os.str().c_str())); - } - - RooAddPdf* sum = new RooAddPdf("sum", "gaussians+uniforms", pdf_set, count_set); - w.import(*sum); // keep sum around after returning - - // --- Generate a toyMC sample from composite PDF --- - RooDataSet *data = sum->generate(obs_set, N_events); - - std::unique_ptr nll {sum->createNLL(*data, RooFit::BatchMode(batch_mode))}; - - // set values randomly so that they actually need to do some fitting - for (unsigned ix = 0; ix < n; ++ix) { - { - std::ostringstream os; - os << "m" << ix; - dynamic_cast(w.arg(os.str().c_str()))->setVal(RooRandom::randomGenerator()->Gaus(0, 2)); - } - { - std::ostringstream os; - os << "s" << ix; - dynamic_cast(w.arg(os.str().c_str()))->setVal(0.1 + abs(RooRandom::randomGenerator()->Gaus(0, 2))); - } - } - - // gather all values of parameters, pdfs and nll here for easy - // saving and restoring - std::unique_ptr all_values = std::make_unique(pdf_set, count_set, "all_values"); - all_values->add(*nll); - all_values->add(*sum); - for (unsigned ix = 0; ix < n; ++ix) { - { - std::ostringstream os; - os << "m" << ix; - all_values->add(*w.arg(os.str().c_str())); - } - { +std::tuple, RooAbsPdf *, std::unique_ptr, std::unique_ptr> +generate_ND_gaussian_pdf_nll(RooWorkspace &ws, unsigned int n, unsigned long nEvents, RooFit::EvalBackend evalBackend) +{ + RooArgSet obs_set; + + // create gaussian parameters + std::vector mean(n); + std::vector sigma(n); + for (unsigned ix = 0; ix < n; ++ix) { + mean[ix] = RooRandom::randomGenerator()->Gaus(0, 2); + sigma[ix] = 0.1 + std::abs(RooRandom::randomGenerator()->Gaus(0, 2)); + } + + // create gaussians and also the observables and parameters they depend on + RooArgSet signals; + for (unsigned ix = 0; ix < n; ++ix) { std::ostringstream os; - os << "s" << ix; - all_values->add(*w.arg(os.str().c_str())); - } - } - - return std::make_tuple(std::move(nll), sum, data, std::move(all_values)); + os << "Gaussian::g" << ix << "(x" << ix << "[-10,10]," + << "m" << ix << "[" << mean[ix] << ",-10,10]," + << "s" << ix << "[" << sigma[ix] << ",0.1,10])"; + signals.add(*ws.factory(os.str())); + } + + // create uniform background signals on each observable + RooArgSet backgrounds; + for (unsigned ix = 0; ix < n; ++ix) { + { + std::ostringstream os; + os << "Uniform::u" << ix << "(x" << ix << ")"; + backgrounds.add(*ws.factory(os.str())); + } + + // gather the observables in a list for data generation below + { + std::ostringstream os; + os << "x" << ix; + obs_set.add(*ws.arg(os.str())); + } + } + + // The ND signal and background pdfs + RooProdPdf sigPdf{"sig_pdf", "sig_pdf", signals}; + RooProdPdf bkgPdf{"bkg_pdf", "bkg_pdf", backgrounds}; + + // Signal and background yields + RooRealVar nSig{"n_sig", "n_sig", nEvents / 2., 0., 5. * nEvents}; + RooRealVar nBkg{"n_bkg", "n_bkg", nEvents / 2., 0., 5. * nEvents}; + + ws.import(RooAddPdf("sum", "gaussians+uniforms", {sigPdf, bkgPdf}, {nSig, nBkg})); + RooAbsPdf *sum = ws.pdf("sum"); + + // --- Generate a toyMC sample from composite PDF --- + std::unique_ptr data{sum->generate(obs_set)}; + + std::unique_ptr nll{sum->createNLL(*data, evalBackend)}; + + // set values randomly so that they actually need to do some fitting + for (unsigned ix = 0; ix < n; ++ix) { + { + std::ostringstream os; + os << "m" << ix; + dynamic_cast(ws.arg(os.str()))->setVal(RooRandom::randomGenerator()->Gaus(0, 2)); + } + { + std::ostringstream os; + os << "s" << ix; + dynamic_cast(ws.arg(os.str()))->setVal(0.1 + std::abs(RooRandom::randomGenerator()->Gaus(0, 2))); + } + } + + // gather all values of parameters, pdfs and nll here for easy + // saving and restoring + auto all_values = std::make_unique(*ws.arg("n_sig"), *ws.arg("n_bkg"), "all_values"); + for (unsigned ix = 0; ix < n; ++ix) { + { + std::ostringstream os; + os << "m" << ix; + all_values->add(*ws.arg(os.str())); + } + { + std::ostringstream os; + os << "s" << ix; + all_values->add(*ws.arg(os.str())); + } + } + + return {std::move(nll), sum, std::move(data), std::move(all_values)}; } - -#endif //ROOT_TEST_LIB_H +#endif // ROOT_TEST_LIB_H diff --git a/roofit/roofitcuda/CMakeLists.txt b/roofit/roofitcuda/CMakeLists.txt new file mode 100644 index 0000000000000..9f9f0b68a76b1 --- /dev/null +++ b/roofit/roofitcuda/CMakeLists.txt @@ -0,0 +1,12 @@ +# Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. +# All rights reserved. +# +# For the licensing terms see $ROOTSYS/LICENSE. +# For the list of contributors see $ROOTSYS/README/CREDITS. + +# Library for RooFit to interface with CUDA. + +ROOT_LINKER_LIBRARY(RooFitCuda src/CudaInterface.cu src/CudaHelpers.cxx TYPE SHARED) +set_target_properties(RooFitCuda PROPERTIES CUDA_RUNTIME_LIBRARY Shared) + +ROOT_INSTALL_HEADERS() diff --git a/roofit/roofitcuda/doc/index.md b/roofit/roofitcuda/doc/index.md new file mode 100644 index 0000000000000..bf83666c21268 --- /dev/null +++ b/roofit/roofitcuda/doc/index.md @@ -0,0 +1,3 @@ +\defgroup RooFitCuda RooFit CUDA +\brief RooFit CUDA support library. +\ingroup Roofitmain diff --git a/roofit/roofitcuda/inc/RooFit/Detail/CudaInterface.h b/roofit/roofitcuda/inc/RooFit/Detail/CudaInterface.h new file mode 100644 index 0000000000000..de452e9409743 --- /dev/null +++ b/roofit/roofitcuda/inc/RooFit/Detail/CudaInterface.h @@ -0,0 +1,210 @@ +/* + * Project: RooFit + * Author: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_CudaInterface_h +#define RooFit_Detail_CudaInterface_h + +#include +#include + +namespace RooFit { +namespace Detail { +/* + * C++ interface around CUDA functionality. + * + * Generally, if the call to the underlying CUDA function does not return + * `cudaSuccess`, a `std::runtime_error` is thrown. + * + * \ingroup RooFitCuda + */ +namespace CudaInterface { + +/// \cond ROOFIT_INTERNAL + +template +struct Deleter { + void operator()(void *ptr); +}; + +/// \endcond + +/* + * Wrapper around cudaEvent_t. + */ +class CudaEvent { +public: + CudaEvent(bool /*forTiming*/); + +// When compiling with NVCC, we allow setting and getting the actual CUDA objects from the wrapper. +#ifdef __CUDACC__ + inline operator cudaEvent_t() { return *reinterpret_cast(_ptr.get()); } +#endif +private: + std::unique_ptr> _ptr; +}; + +/* + * Wrapper around cudaStream_t. + */ +class CudaStream { +public: + CudaStream(); + + bool isActive(); + void waitForEvent(CudaEvent &); + +// When compiling with NVCC, we allow setting and getting the actual CUDA objects from the wrapper. +#ifdef __CUDACC__ + inline cudaStream_t *get() { return reinterpret_cast(_ptr); } + inline operator cudaStream_t() { return *reinterpret_cast(_ptr.get()); } +#endif +private: + std::unique_ptr> _ptr; +}; + +void cudaEventRecord(CudaEvent &, CudaStream &); +float cudaEventElapsedTime(CudaEvent &, CudaEvent &); + +/// \cond ROOFIT_INTERNAL +void copyHostToDeviceImpl(const void *src, void *dest, std::size_t n, CudaStream * = nullptr); +void copyDeviceToHostImpl(const void *src, void *dest, std::size_t n, CudaStream * = nullptr); +/// \endcond + +/** + * Copies data from the host to the CUDA device. + * + * @param[in] src Pointer to the source memory on the host. + * @param[in] dest Pointer to the destination memory on the device. + * @param[in] nBytes Number of bytes to copy. + * @param[in] stream CudaStream for asynchronous memory transfer (optional). + */ +template +void copyHostToDevice(const T *src, T *dest, std::size_t n, CudaStream * = nullptr) +{ + copyHostToDeviceImpl(src, dest, sizeof(T) * n); +} + +/** + * Copies data from the CUDA device to the host. + * + * @param[in] src Pointer to the source memory on the device. + * @param[in] dest Pointer to the destination memory on the host. + * @param[in] nBytes Number of bytes to copy. + * @param[in] stream CudaStream for asynchronous memory transfer (optional). + */ +template +void copyDeviceToHost(const T *src, T *dest, std::size_t n, CudaStream * = nullptr) +{ + copyDeviceToHostImpl(src, dest, sizeof(T) * n); +} + +/// \cond ROOFIT_INTERNAL + +// The user should not use these "Memory" classes directly, but instead the typed +// "Array" classes. That's why we tell doxygen that this is internal. + +class DeviceMemory { +public: + DeviceMemory(std::size_t n, std::size_t typeSize); + + std::size_t size() const { return _size; } + void *data() { return _data.get(); } + void const *data() const { return _data.get(); } + +private: + std::unique_ptr> _data; + std::size_t _size = 0; +}; + +class PinnedHostMemory { +public: + PinnedHostMemory(std::size_t n, std::size_t typeSize); + + std::size_t size() const { return _size; } + void *data() { return _data.get(); } + void const *data() const { return _data.get(); } + +private: + std::unique_ptr> _data; + std::size_t _size = 0; +}; +/// \endcond + + +/** + * @class Array + * @brief A templated class for managing an array of data using a specified memory type. + * + * The Array class provides a convenient interface for managing an array of + * data using different memory types (e.g., memory on the host or device). + * The memory is automatically freed at the end of the lifetime. + * + * @tparam Data_t The type of data elements to be stored in the array. + * @tparam Memory_t The type of memory that provides storage for the array. + */ +template +class Array : public Memory_t { +public: + /** + * @brief Constructor to create an Array object with a specified size. + * @param n The size of the array (number of elements). + */ + Array(std::size_t n) : Memory_t{n, sizeof(Data_t)} {} + + // Needs to be declared explicitly for doxygen to mention it. + /** + * @brief Get the size of the array. + * @return The size of the array (number of elements). + * + * This function returns the number of elements in the array. + */ + inline std::size_t size() const { return Memory_t::size(); } + + /** + * @brief Get a pointer to the start of the array. + * @return A pointer to the start of the array. + * + * This function returns a pointer to the underlying memory. + * It allows direct manipulation of array elements. + */ + inline Data_t *data() { return static_cast(Memory_t::data()); } + + /** + * @brief Get a const pointer to the start of the array. + * @return A const pointer to the start of the array. + * + * This function returns a const pointer to the underlying memory. + * It allows read-only access to array elements. + */ + inline Data_t const *data() const { return static_cast(Memory_t::data()); } +}; + +/** + * An array of specific type that is allocated on the device with `cudaMalloc` and freed with `cudaFree`. + */ +template +using DeviceArray = Array; + +/** + * A pinned array of specific type that allocated on the host with `cudaMallocHost` and freed with `cudaFreeHost`. + * The memory is "pinned", i.e. page-locked and accessible to the device for fast copying. + * \see The documentation of `cudaMallocHost` on developer.download.nvidia.com. + */ +template +using PinnedHostArray = Array; + +} // namespace CudaInterface +} // namespace Detail +} // namespace RooFit + +#endif diff --git a/roofit/roofitcuda/inc/RooFit/Detail/CudaKernels.cuh b/roofit/roofitcuda/inc/RooFit/Detail/CudaKernels.cuh new file mode 100644 index 0000000000000..c52fa5b7f7860 --- /dev/null +++ b/roofit/roofitcuda/inc/RooFit/Detail/CudaKernels.cuh @@ -0,0 +1,275 @@ +/* + * Project: RooFit + * Author: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#ifndef RooFit_Detail_CudaKernels_cuh +#define RooFit_Detail_CudaKernels_cuh + +namespace RooFit { +namespace Detail { + +/* + * Namespace for templated CUDA kernels. + * \ingroup RooFitCuda + */ +namespace CudaKernels { + +/// The type for array size parameters. +using Size_t = int; + +/// Dedicated namespace for reduction kernels. +namespace Reducers { + +/** + * Performs a multi-block sum reduction on the input array `arr`. The input + * array can either be scalar, or a flattened vector array with inner dimension + * `ElemDim_n`. + * + * The output array is of shape `[ gridDim.x, ElemDim_n ]` (row-major flattened, meaning + * when iterating over the bins, the elements are contiguous). + * + * @tparam ElemDim_n Inner dimension of the flattened input array. Set to + * `1` when summing scalar values. + * @tparam BlockSize_n Needs to be identical to the number of thread blocks. + * Has to be known statically for the size of the shared memory. + * @tparam Elem_t Data type of the input array elements. + * @tparam Sum_t Data type of the output and shared memory array elements. + * @param[in] nElems Number of elements in the input array. + * @param[in] arr Input array containing data to be summed. + * @param[out] output Output array containing partial sums for each block. + * (Each block's sum is stored in 'output[ElemDim_n * blockIdx.x]'). + */ +template +__global__ void SumVectors(Size_t nElems, const Elem_t *__restrict__ arr, Sum_t *__restrict__ output) +{ + int thIdx = threadIdx.x; + int gthIdx = thIdx + blockIdx.x * BlockSize_n; + int arraySize = nElems * ElemDim_n; + const int nThreadsTotal = BlockSize_n * gridDim.x; + // Each thread calculates its partial sum and writes the result to memory + // that is shared by all threads in the block. + Sum_t sum[ElemDim_n]; + // Don't forget the zero-initialization! + for (int i = 0; i < ElemDim_n; i += 1) { + sum[i] = 0; + } + + for (int i = gthIdx; i < arraySize; i += nThreadsTotal) { + sum[i % ElemDim_n] += arr[i]; + } + __shared__ Sum_t shArr[ElemDim_n * BlockSize_n]; + for (int i = 0; i < ElemDim_n; i += 1) { + shArr[i * BlockSize_n + thIdx] = sum[i]; + } + __syncthreads(); + // Sum within the thread blocks + for (int size = BlockSize_n / 2; size > 0; size /= 2) { // uniform + if (thIdx < size) { + for (int i = 0; i < ElemDim_n; i += 1) { + shArr[i * BlockSize_n + thIdx] += shArr[i * BlockSize_n + thIdx + size]; + } + } + __syncthreads(); + } + if (thIdx == 0) + for (int i = 0; i < ElemDim_n; i += 1) { + output[ElemDim_n * blockIdx.x + i] = shArr[i * BlockSize_n]; + } +} + +/** + * Computes bin-wise sum and count of elements from the 'arr' array into separate output arrays + * based on indices provided in 'x1' and 'x2' arrays, using a 2D grid-stride loop approach. + * + * The output arrays are of shape `[ gridDim.x, Bins1_n, Bins2_n ]` (row-major + * flattened, meaning when iterating over the bins, the elements are + * contiguous). + * + * @tparam Bins1_n Number of bins in the first dimension. + * @tparam Bins2_n Number of bins in the second dimension. + * @tparam BlockSize_n Needs to be identical to the number of thread blocks. + * Has to be known statically for the size of the shared memory. + * @tparam Idx_t Data type of index arrays `x1` and `x2`. + * @tparam Elem_t Data type of the input array `arr` elements. + * @tparam Sum_t Data type for bin-wise sum output. + * @tparam Counts_t Data type for bin-wise count output. + * @param[in] arraySize Size of the input arrays `x1`, `x2`, and `arr`. + * @param[in] x1 Input array containing bin indices for the first dimension. + * @param[in] x2 Input array containing bin indices for the second dimension. + * @param[in] arr Input array containing elements to be summed. + * @param[out] outputSum Output array for storing bin-wise sum of elements. + * @param[out] outputCounts Output array for storing bin-wise count of elements. + */ +template +__global__ void +SumBinwise2D(int arraySize, Idx_t const *__restrict__ x1, Idx_t const *__restrict__ x2, const Elem_t *__restrict__ arr, + Sum_t *__restrict__ outputSum, Counts_t *__restrict__ outputCounts) +{ + int thIdx = threadIdx.x; + int gthIdx = thIdx + blockIdx.x * BlockSize_n; + const int nThreadsTotal = BlockSize_n * gridDim.x; + constexpr int nBins = Bins1_n * Bins2_n; + float sum[nBins]; + int cnt[nBins]; + + // We need to do zero-initialization. + for (int i = 0; i < nBins; i += 1) { + sum[i] = 0; + cnt[i] = 0; + } + + for (int i = gthIdx; i < arraySize; i += nThreadsTotal) { + int idx = Bins2_n * x1[i] + x2[i]; + sum[idx] += arr[i]; + cnt[idx] += 1; + } + __shared__ float shArrSum[nBins * BlockSize_n]; + __shared__ int shArrCnt[nBins * BlockSize_n]; + + for (int i = 0; i < nBins; i += 1) { + shArrSum[i * BlockSize_n + thIdx] = sum[i]; + shArrCnt[i * BlockSize_n + thIdx] = cnt[i]; + } + + __syncthreads(); + for (int size = BlockSize_n / 2; size > 0; size /= 2) { // uniform + if (thIdx < size) { + for (int i = 0; i < nBins; i += 1) { + shArrSum[i * BlockSize_n + thIdx] += shArrSum[i * BlockSize_n + thIdx + size]; + shArrCnt[i * BlockSize_n + thIdx] += shArrCnt[i * BlockSize_n + thIdx + size]; + } + } + __syncthreads(); + } + if (thIdx == 0) + for (int i = 0; i < nBins; i += 1) { + outputSum[nBins * blockIdx.x + i] = shArrSum[i * BlockSize_n]; + outputCounts[nBins * blockIdx.x + i] = shArrCnt[i * BlockSize_n]; + } +} + +/** + * Computes the covariance, variance of 'x', and variance of 'y' for a 2D data set. + + * The output array is of shape `[ gridDim.x, 3 ]` (row-major flattened, + * meaning when iterating over the elements of the covariance matrix, the + * elements are contiguous). Only three output elements are needed to store the + * symmetric 2-by-2 covariance matrix. + * + * @tparam BlockSize_n Needs to be identical to the number of thread blocks. + * Has to be known statically for the size of the shared memory. + * @param[in] arraySize Size of the input arrays 'x' and 'y'. + * @param[in] x Input array containing 'x' data. + * @param[in] y Input array containing 'y' data. + * @param[in] xMean Mean of the 'x' data. + * @param[in] yMean Mean of the 'y' data. + * @param[out] output Output array to store computed covariance and variances. + * (Three values are stored per block: variance of 'x', covariance, variance of 'y'.) + */ +template +__global__ void Covariance2D(Size_t arraySize, float const *__restrict__ x, const float *__restrict__ y, double xMean, + double yMean, double *__restrict__ output) +{ + int thIdx = threadIdx.x; + int gthIdx = thIdx + blockIdx.x * BlockSize_n; + const int nThreadsTotal = BlockSize_n * gridDim.x; + double sumX2 = 0; + double sumCov = 0; + double sumY2 = 0; + for (int i = gthIdx; i < arraySize; i += nThreadsTotal) { + const double argx = double(x[i]) - xMean; + const double argy = double(y[i]) - yMean; + sumX2 += argx * argx; + sumCov += argx * argy; + sumY2 += argy * argy; + } + __shared__ double shArrCov[BlockSize_n]; + __shared__ double shArrX2[BlockSize_n]; + __shared__ double shArrY2[BlockSize_n]; + shArrX2[thIdx] = sumX2; + shArrCov[thIdx] = sumCov; + shArrY2[thIdx] = sumY2; + __syncthreads(); + for (int size = BlockSize_n / 2; size > 0; size /= 2) { // uniform + if (thIdx < size) { + shArrX2[thIdx] += shArrX2[thIdx + size]; + shArrCov[thIdx] += shArrCov[thIdx + size]; + shArrY2[thIdx] += shArrY2[thIdx + size]; + } + __syncthreads(); + } + if (thIdx == 0) { + output[3 * blockIdx.x + 0] = shArrX2[0] / arraySize; + output[3 * blockIdx.x + 1] = shArrCov[0] / arraySize; + output[3 * blockIdx.x + 2] = shArrY2[0] / arraySize; + } +} + +} // namespace Reducers + +/** + * Divides elements of the `num` array in-place by corresponding elements of + * the `den` array. + * + * @tparam Num_t Data type of the 'num' array elements. + * @tparam Den_t Data type of the 'den' array elements. + * @param[in] arraySize Size of the input arrays. + * @param[in,out] num Numerator array containing values to be divided. + * @param[in] den Denominator array containing divisor values. + */ +template +__global__ void DivideBy(Size_t arraySize, Den_t *__restrict__ num, Num_t const *__restrict__ den) +{ + int thIdx = threadIdx.x; + int gthIdx = thIdx + blockIdx.x * blockDim.x; + const int nThreadsTotal = blockDim.x * gridDim.x; + + for (int i = gthIdx; i < arraySize; i += nThreadsTotal) { + num[i] = num[i] / den[i]; + } +} + +/** + * Fills an output array 'output' with values from a row-wise flattened + * two-dimensional lookup table `lut` based on input arrays `x1` and `x2`: + * + * `output[ i ] = lut[ n2 * x1[i] + x2[i] ]`. + * + * Each thread processes a portion of the input arrays using grid-stride looping. + * + * @tparam Idx_t Data type of the indices. + * @tparam Elem_t Data type of the lookup table and output array elements. + * @param[in] arraySize Size of the input and output arrays. + * @param[in] n2 Size of the second dimension of the lookup table. + * @param[in] x1 Input array containing indices for the first dimension of the lookup table. + * @param[in] x2 Input array containing indices for the second dimension of the lookup table. + * @param[in] lut Lookup table containing values. + * @param[out] output Output array to be filled with values from the lookup table. + */ +template +__global__ void Lookup2D(Size_t arraySize, Idx_t n2, Idx_t const *__restrict__ x1, Idx_t const *__restrict__ x2, + Elem_t const *__restrict__ lut, Elem_t *__restrict__ output) +{ + int thIdx = threadIdx.x; + int gthIdx = thIdx + blockIdx.x * blockDim.x; + const int nThreadsTotal = blockDim.x * gridDim.x; + + for (int i = gthIdx; i < arraySize; i += nThreadsTotal) { + output[i] = lut[n2 * x1[i] + x2[i]]; + } +} + +} // namespace CudaKernels + +} // namespace Detail +} // namespace RooFit + +#endif diff --git a/roofit/roofitcuda/src/CudaHelpers.cxx b/roofit/roofitcuda/src/CudaHelpers.cxx new file mode 100644 index 0000000000000..641206a280a42 --- /dev/null +++ b/roofit/roofitcuda/src/CudaHelpers.cxx @@ -0,0 +1,57 @@ +/* + * Project: RooFit + * Authors: + * Jonas Rembser, CERN 2022 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include "CudaHelpers.h" + +#include + +/** + * @brief Measure the time taken to perform memory copy operations between host and device memory. + * @param nBytes The number of bytes to be copied between host and device memory. + * @return A pair of durations representing the average time taken for host-to-device and device-to-host copies. + * + * This function measures the time taken to copy data between host and device memory using the CUDA API. + * It performs a series of copy operations and calculates the average time for both directions. + * The input parameter `nBytes` specifies the size of the data to be copied in bytes. + * The function returns a pair of durations, where the first duration represents the average time + * taken for host-to-device copies and the second duration represents the average time taken for + * device-to-host copies. + * + * Example usage: + * @code + * auto copyTimes = RooFit::Detail::CudaHelpers::memcpyBenchmark(1024 * 1024); // Measure copy time for 1 MB of data + * std::cout << "Average Host-to-Device Copy Time: " << copyTimes.first.count() << " microseconds" << std::endl; + * std::cout << "Average Device-to-Host Copy Time: " << copyTimes.second.count() << " microseconds" << std::endl; + * @endcode + */ +std::pair +RooFit::Detail::CudaHelpers::memcpyBenchmark(std::size_t nBytes) +{ + using namespace std::chrono; + namespace CudaInterface = RooFit::Detail::CudaInterface; + + std::pair ret; + CudaInterface::PinnedHostArray hostArr{nBytes}; + CudaInterface::DeviceArray deviArr{nBytes}; + constexpr std::size_t nIterations = 5; + for (std::size_t i = 0; i < nIterations; i++) { + auto start = steady_clock::now(); + CudaInterface::copyHostToDevice(hostArr.data(), deviArr.data(), nBytes); + ret.first += duration_cast(steady_clock::now() - start); + start = steady_clock::now(); + CudaInterface::copyDeviceToHost(deviArr.data(), hostArr.data(), nBytes); + ret.second += duration_cast(steady_clock::now() - start); + } + ret.first /= nIterations; + ret.second /= nIterations; + return ret; +} diff --git a/roofit/roofitcore/src/RooFit/CUDAHelpers.h b/roofit/roofitcuda/src/CudaHelpers.h similarity index 64% rename from roofit/roofitcore/src/RooFit/CUDAHelpers.h rename to roofit/roofitcuda/src/CudaHelpers.h index 71f98c430b240..97e48d6f192fb 100644 --- a/roofit/roofitcore/src/RooFit/CUDAHelpers.h +++ b/roofit/roofitcuda/src/CudaHelpers.h @@ -10,18 +10,25 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ -#ifndef RooFit_CUDAHelpers_h -#define RooFit_CUDAHelpers_h +#ifndef RooFit_CudaHelpers_h +#define RooFit_CudaHelpers_h #include #include namespace RooFit { -namespace CUDAHelpers { +namespace Detail { +/* + * Contains helper functions that might be useful in the context of using a CUDA GPU. + * + * \ingroup RooFitCuda + */ +namespace CudaHelpers { std::pair memcpyBenchmark(std::size_t nBytes); -} // namespace CUDAHelpers +} // namespace CudaHelpers +} // namespace Detail } // namespace RooFit #endif diff --git a/roofit/roofitcuda/src/CudaInterface.cu b/roofit/roofitcuda/src/CudaInterface.cu new file mode 100644 index 0000000000000..f4e7c9952ad4d --- /dev/null +++ b/roofit/roofitcuda/src/CudaInterface.cu @@ -0,0 +1,176 @@ +/* + * Project: RooFit + * Author: + * Jonas Rembser, CERN 2023 + * + * Copyright (c) 2023, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +#include + +#include +#include +#include + +#define ERRCHECK(err) __checkCudaErrors((err), __func__, __FILE__, __LINE__) +inline static void __checkCudaErrors(cudaError_t error, std::string func, std::string file, int line) +{ + if (error != cudaSuccess) { + std::stringstream errMsg; + errMsg << func << "(), " << file + ":" << std::to_string(line) << " : " << cudaGetErrorString(error); + throw std::runtime_error(errMsg.str()); + } +} + +namespace RooFit { +namespace Detail { +namespace CudaInterface { + +DeviceMemory::DeviceMemory(std::size_t n, std::size_t typeSize) : _size{n} +{ + void *ret; + ERRCHECK(::cudaMalloc(&ret, n * typeSize)); + _data.reset(ret); +} +PinnedHostMemory::PinnedHostMemory(std::size_t n, std::size_t typeSize) : _size{n} +{ + void *ret; + ERRCHECK(::cudaMallocHost(&ret, n * typeSize)); + _data.reset(ret); +} + +template <> +void Deleter::operator()(void *ptr) +{ + ERRCHECK(::cudaFree(ptr)); + ptr = nullptr; +} +template <> +void Deleter::operator()(void *ptr) +{ + ERRCHECK(::cudaFreeHost(ptr)); + ptr = nullptr; +} + +/** + * Creates a new CUDA event. + * + * @param[in] forTiming Set to true if the event is intended for timing purposes. + * If `false`, the `cudaEventDisableTiming` is passed to CUDA. + * @return CudaEvent object representing the new event. + */ +CudaEvent::CudaEvent(bool forTiming) +{ + auto event = new cudaEvent_t; + ERRCHECK(cudaEventCreateWithFlags(event, forTiming ? 0 : cudaEventDisableTiming)); + _ptr.reset(event); +} + +template <> +void Deleter::operator()(void *ptr) +{ + auto event = reinterpret_cast(ptr); + ERRCHECK(cudaEventDestroy(*event)); + delete event; + ptr = nullptr; +} + +template <> +void Deleter::operator()(void *ptr) +{ + auto stream = reinterpret_cast(ptr); + ERRCHECK(cudaStreamDestroy(*stream)); + delete stream; + ptr = nullptr; +} + +/** + * Records a CUDA event. + * + * @param[in] event CudaEvent object representing the event to be recorded. + * @param[in] stream CudaStream in which to record the event. + */ +void cudaEventRecord(CudaEvent &event, CudaStream &stream) +{ + ERRCHECK(::cudaEventRecord(event, stream)); +} + +/** + * Creates a new CUDA stream. + * + * @return CudaStream object representing the new stream. + */ +CudaStream::CudaStream() +{ + auto stream = new cudaStream_t; + ERRCHECK(cudaStreamCreate(stream)); + _ptr.reset(stream); +} + +/** + * Checks if a CUDA stream is currently active. + * + * @return True if the stream is active, false otherwise. + */ +bool CudaStream::isActive() +{ + cudaError_t err = cudaStreamQuery(*this); + if (err == cudaErrorNotReady) + return true; + else if (err == cudaSuccess) + return false; + ERRCHECK(err); + return false; +} + +/** + * Makes a CUDA stream wait for a CUDA event. + * + * @param[in] event CudaEvent object representing the event to wait for. + */ +void CudaStream::waitForEvent(CudaEvent &event) +{ + ERRCHECK(::cudaStreamWaitEvent(*this, event, 0)); +} + +/** + * Calculates the elapsed time between two CUDA events. + * + * @param[in] begin CudaEvent representing the start event. + * @param[in] end CudaEvent representing the end event. + * @return Elapsed time in milliseconds. + */ +float cudaEventElapsedTime(CudaEvent &begin, CudaEvent &end) +{ + float ret; + ERRCHECK(::cudaEventElapsedTime(&ret, begin, end)); + return ret; +} + +/// \cond ROOFIT_INTERNAL + +void copyHostToDeviceImpl(const void *src, void *dest, size_t nBytes, CudaStream *stream) +{ + if (stream) + ERRCHECK(cudaMemcpyAsync(dest, src, nBytes, cudaMemcpyHostToDevice, *stream)); + else + ERRCHECK(cudaMemcpy(dest, src, nBytes, cudaMemcpyHostToDevice)); +} + +void copyDeviceToHostImpl(const void *src, void *dest, size_t nBytes, CudaStream *stream) +{ + if (stream) + ERRCHECK(cudaMemcpyAsync(dest, src, nBytes, cudaMemcpyDeviceToHost, *stream)); + else + ERRCHECK(cudaMemcpy(dest, src, nBytes, cudaMemcpyDeviceToHost)); +} + +/// \endcond + +} // namespace CudaInterface +} // namespace Detail +} // namespace RooFit diff --git a/roofit/roofitmore/CMakeLists.txt b/roofit/roofitmore/CMakeLists.txt index e3808baec9770..7962a194de7e9 100644 --- a/roofit/roofitmore/CMakeLists.txt +++ b/roofit/roofitmore/CMakeLists.txt @@ -13,6 +13,11 @@ if(mathmore) set(ROOT_MATHMORE_LIBRARY MathMore) endif() +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(RooFitMore HEADERS RooFitMoreLib.h @@ -50,8 +55,14 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitMore RIO MathCore Foam + BUILTINS + GSL + ${EXTRA_DICT_OPTS} ) +target_include_directories(RooFitMore SYSTEM PRIVATE ${GSL_INCLUDE_DIR}) +target_link_libraries(RooFitMore PRIVATE ${GSL_LIBRARIES}) + # For recent clang, this can facilitate auto-vectorisation. # In RooFit, the errno side effect is not needed, anyway: if(NOT MSVC) diff --git a/roofit/roofitmore/doc/index.md b/roofit/roofitmore/doc/index.md new file mode 100644 index 0000000000000..e67d1d5765e1f --- /dev/null +++ b/roofit/roofitmore/doc/index.md @@ -0,0 +1,3 @@ +\defgroup RooFitMore RooFit More +\brief RooFit components that are only available if ROOT was built with the `mathmore` option. +\ingroup Roofitmain diff --git a/roofit/roofitmore/inc/RooAdaptiveGaussKronrodIntegrator1D.h b/roofit/roofitmore/inc/RooAdaptiveGaussKronrodIntegrator1D.h index 8b2c34e8a82cb..53ac14f0f85d0 100644 --- a/roofit/roofitmore/inc/RooAdaptiveGaussKronrodIntegrator1D.h +++ b/roofit/roofitmore/inc/RooAdaptiveGaussKronrodIntegrator1D.h @@ -25,11 +25,9 @@ class RooAdaptiveGaussKronrodIntegrator1D : public RooAbsIntegrator { public: // Constructors, assignment etc - RooAdaptiveGaussKronrodIntegrator1D() {} RooAdaptiveGaussKronrodIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) ; RooAdaptiveGaussKronrodIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, const RooNumIntConfig& config) ; - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; ~RooAdaptiveGaussKronrodIntegrator1D() override; bool checkLimits() const override; @@ -38,27 +36,10 @@ class RooAdaptiveGaussKronrodIntegrator1D : public RooAbsIntegrator { using RooAbsIntegrator::setLimits ; bool setLimits(double* xmin, double* xmax) override; bool setUseIntegrandLimits(bool flag) override { - // If flag is true, intergration limits are taken from definition in input function binding + // If flag is true, integration limits are taken from definition in input function binding _useIntegrandLimits = flag ; return true ; } - bool canIntegrate1D() const override { - // We can integrate 1-dimensional functions - return true ; - } - bool canIntegrate2D() const override { - // We can not integrate 2-dimensional functions - return false ; - } - bool canIntegrateND() const override { - // We can not integrate >2-dimensional functions - return false ; - } - bool canIntegrateOpenEnded() const override { - // We can integrate over open-ended domains - return true ; - } - protected: friend class RooNumIntFactory ; diff --git a/roofit/roofitmore/inc/RooGaussKronrodIntegrator1D.h b/roofit/roofitmore/inc/RooGaussKronrodIntegrator1D.h index a954d28f60e5a..c6800ff543db4 100644 --- a/roofit/roofitmore/inc/RooGaussKronrodIntegrator1D.h +++ b/roofit/roofitmore/inc/RooGaussKronrodIntegrator1D.h @@ -25,11 +25,8 @@ class RooGaussKronrodIntegrator1D : public RooAbsIntegrator { public: // Constructors, assignment etc - RooGaussKronrodIntegrator1D() {} RooGaussKronrodIntegrator1D(const RooAbsFunc& function, const RooNumIntConfig& config) ; RooGaussKronrodIntegrator1D(const RooAbsFunc& function, double xmin, double xmax, const RooNumIntConfig& config) ; - RooAbsIntegrator* clone(const RooAbsFunc& function, const RooNumIntConfig& config) const override ; - bool checkLimits() const override; double integral(const double *yvec=nullptr) override ; @@ -37,11 +34,6 @@ class RooGaussKronrodIntegrator1D : public RooAbsIntegrator { bool setLimits(double* xmin, double* xmax) override; bool setUseIntegrandLimits(bool flag) override {_useIntegrandLimits = flag ; return true ; } - bool canIntegrate1D() const override { return true ; } - bool canIntegrate2D() const override { return false ; } - bool canIntegrateND() const override { return false ; } - bool canIntegrateOpenEnded() const override { return true ; } - protected: friend class RooNumIntFactory ; diff --git a/roofit/roofitmore/inc/RooHypatia2.h b/roofit/roofitmore/inc/RooHypatia2.h index d63e8c6fd6158..c6b20c7e44fc5 100644 --- a/roofit/roofitmore/inc/RooHypatia2.h +++ b/roofit/roofitmore/inc/RooHypatia2.h @@ -53,7 +53,7 @@ class RooHypatia2 : public RooAbsPdf { RooRealProxy _n2; double evaluate() const override; - RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; /// \cond CLASS_DEF_DOXY ClassDefOverride(RooHypatia2, 1); diff --git a/roofit/roofitmore/inc/RooLegendre.h b/roofit/roofitmore/inc/RooLegendre.h index 2ebda16595893..1d961dfc3bfa3 100644 --- a/roofit/roofitmore/inc/RooLegendre.h +++ b/roofit/roofitmore/inc/RooLegendre.h @@ -42,7 +42,7 @@ class RooLegendre : public RooAbsReal { int _l2,_m2; double evaluate() const override; - RooSpan evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const override; + void computeBatch(double* output, size_t size, RooFit::Detail::DataMap const&) const override; ClassDefOverride(RooLegendre,1) // Legendre polynomial }; diff --git a/roofit/batchcompute/inc/BracketAdapters.h b/roofit/roofitmore/src/BracketAdapters.h similarity index 92% rename from roofit/batchcompute/inc/BracketAdapters.h rename to roofit/roofitmore/src/BracketAdapters.h index 1ea3ba17f5b03..d0952baab6400 100644 --- a/roofit/batchcompute/inc/BracketAdapters.h +++ b/roofit/roofitmore/src/BracketAdapters.h @@ -17,7 +17,7 @@ #ifndef ROOFIT_BATCHCOMPUTE_BRACKETADAPTER_H #define ROOFIT_BATCHCOMPUTE_BRACKETADAPTER_H -#include "RooSpan.h" +#include #include @@ -32,7 +32,7 @@ class BracketAdapter { constexpr BracketAdapter(T payload) noexcept : _payload{payload} { } - constexpr BracketAdapter(RooSpan payload) noexcept : + constexpr BracketAdapter(std::span payload) noexcept : _payload{payload[0]} { } constexpr double operator[](std::size_t) const { @@ -57,7 +57,7 @@ class BracketAdapterWithMask { /// Construct adapter from a fallback value and a batch of values. /// - If `batch.empty()`, always return `payload`. /// - Else, return `batch[i]`. - BracketAdapterWithMask(double payload, const RooSpan& batch) noexcept : + BracketAdapterWithMask(double payload, const std::span& batch) noexcept : _isBatch(!batch.empty()), _payload(payload), _pointer(batch.empty() ? &_payload : batch.data()), @@ -68,7 +68,7 @@ class BracketAdapterWithMask { /// Construct adapter from a batch of values. /// - If `batch.size() == 1`, always return the value at `batch[0]`. /// - Else, return `batch[i]`. - BracketAdapterWithMask(RooSpan batch) : + BracketAdapterWithMask(std::span batch) : _isBatch(batch.size() > 1), _payload(batch[0]), _pointer(batch.data()), diff --git a/roofit/roofitmore/src/RooAdaptiveGaussKronrodIntegrator1D.cxx b/roofit/roofitmore/src/RooAdaptiveGaussKronrodIntegrator1D.cxx index db034942174f9..bb3282c7fe2d6 100644 --- a/roofit/roofitmore/src/RooAdaptiveGaussKronrodIntegrator1D.cxx +++ b/roofit/roofitmore/src/RooAdaptiveGaussKronrodIntegrator1D.cxx @@ -43,8 +43,8 @@ For integrands with integrable singularities the Wynn epsilon rule can be selected to speed up the convergence of these integrals. **/ -#include -#include +#include +#include #include "TClass.h" #include "Riostream.h" #include "RooAdaptiveGaussKronrodIntegrator1D.h" @@ -52,7 +52,6 @@ can be selected to speed up the convergence of these integrals. #include "RooRealVar.h" #include "RooNumber.h" #include "RooNumIntFactory.h" -#include "RooIntegratorBinding.h" #include "TMath.h" #include "RooMsgService.h" @@ -131,6 +130,8 @@ gsl_integration_qagiu (gsl_function * f, //------------------------------------------------------------------- +/// \cond ROOFIT_INTERNAL + // register integrator class // create a derived class in order to call the protected method of the // RoodaptiveGaussKronrodIntegrator1D @@ -148,6 +149,8 @@ struct Roo_reg_AGKInteg1D { Roo_reg_AGKInteg1D() { Roo_internal_AGKInteg1D::registerIntegrator(); } }; +/// \endcond + static Roo_reg_AGKInteg1D instance; } // namespace RooFit_internal //////////////////////////////////////////////////////////////////////////////// @@ -165,7 +168,17 @@ void RooAdaptiveGaussKronrodIntegrator1D::registerIntegrator(RooNumIntFactory& f method.defineType("51Points", 5); method.defineType("61Points", 6); method.setIndex(2); - fact.storeProtoIntegrator(new RooAdaptiveGaussKronrodIntegrator1D(), RooArgSet(maxSeg, method)); + + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config); + }; + + fact.registerPlugin("RooAdaptiveGaussKronrodIntegrator1D", creator, {maxSeg, method}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/false, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/true); + oocoutI(nullptr,Integration) << "RooAdaptiveGaussKronrodIntegrator1D has been registered " << std::endl; } @@ -212,17 +225,6 @@ RooAdaptiveGaussKronrodIntegrator1D::RooAdaptiveGaussKronrodIntegrator1D(const R } - -//////////////////////////////////////////////////////////////////////////////// -/// Virtual constructor - -RooAbsIntegrator* RooAdaptiveGaussKronrodIntegrator1D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooAdaptiveGaussKronrodIntegrator1D(function,config) ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Initialize integrator allocate buffers and setup GSL workspace @@ -275,7 +277,7 @@ bool RooAdaptiveGaussKronrodIntegrator1D::setLimits(double* xmin, double* xmax) bool RooAdaptiveGaussKronrodIntegrator1D::checkLimits() const { if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); + assert(nullptr != integrand() && integrand()->isValid()); _xmin= integrand()->getMinLimit(0); _xmax= integrand()->getMaxLimit(0); } @@ -731,9 +733,9 @@ subinterval_too_small (double a1, double a2, double b2) const double e = GSL_DBL_EPSILON; const double u = GSL_DBL_MIN; - double tmp = (1 + 100 * e) * (fabs (a2) + 1000 * u); + double tmp = (1 + 100 * e) * (std::abs(a2) + 1000 * u); - int status = fabs (a1) <= tmp && fabs (b2) <= tmp; + int status = std::abs(a1) <= tmp && std::abs(b2) <= tmp; return status; } @@ -829,7 +831,7 @@ qag (const gsl_function * f, if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28)) { - GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel", + GSL_ERROR ("tolerance cannot be acheieved with given epsabs and epsrel", GSL_EBADTOL); } @@ -841,7 +843,7 @@ qag (const gsl_function * f, /* Test on accuracy */ - tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0)); + tolerance = GSL_MAX_DBL (epsabs, epsrel * std::abs(result0)); /* need IEEE rounding here to match original quadpack behavior */ @@ -906,7 +908,7 @@ qag (const gsl_function * f, { double delta = r_i - area12; - if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i) + if (std::abs(delta) <= 1.0e-5 * std::abs(area12) && error12 >= 0.99 * e_i) { roundoff_type1++; } @@ -916,7 +918,7 @@ qag (const gsl_function * f, } } - tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area)); + tolerance = GSL_MAX_DBL (epsabs, epsrel * std::abs(area)); if (errsum > tolerance) { @@ -975,7 +977,7 @@ static double rescale_error (double err, const double result_abs, const double r static double rescale_error (double err, const double result_abs, const double result_asc) { - err = fabs(err) ; + err = std::abs(err) ; if (result_asc != 0 && err != 0) { @@ -1015,13 +1017,13 @@ gsl_integration_qk (const int n, const double center = 0.5 * (a + b); const double half_length = 0.5 * (b - a); - const double abs_half_length = fabs (half_length); + const double abs_half_length = std::abs(half_length); const double f_center = GSL_FN_EVAL (f, center); double result_gauss = 0; double result_kronrod = f_center * wgk[n - 1]; - double result_abs = fabs (result_kronrod); + double result_abs = std::abs(result_kronrod); double result_asc = 0; double mean = 0, err = 0; @@ -1043,7 +1045,7 @@ gsl_integration_qk (const int n, fv2[jtw] = fval2; result_gauss += wg[j] * fsum; result_kronrod += wgk[jtw] * fsum; - result_abs += wgk[jtw] * (fabs (fval1) + fabs (fval2)); + result_abs += wgk[jtw] * (std::abs(fval1) + std::abs(fval2)); } for (j = 0; j < n / 2; j++) @@ -1055,16 +1057,16 @@ gsl_integration_qk (const int n, fv1[jtwm1] = fval1; fv2[jtwm1] = fval2; result_kronrod += wgk[jtwm1] * (fval1 + fval2); - result_abs += wgk[jtwm1] * (fabs (fval1) + fabs (fval2)); + result_abs += wgk[jtwm1] * (std::abs(fval1) + std::abs(fval2)); }; mean = result_kronrod * 0.5; - result_asc = wgk[n - 1] * fabs (f_center - mean); + result_asc = wgk[n - 1] * std::abs(f_center - mean); for (j = 0; j < n - 1; j++) { - result_asc += wgk[j] * (fabs (fv1[j] - mean) + fabs (fv2[j] - mean)); + result_asc += wgk[j] * (std::abs(fv1[j] - mean) + std::abs(fv2[j] - mean)); } /* scale by the width of the integration region */ @@ -1548,55 +1550,55 @@ gsl_integration_workspace_alloc (const size_t n) if (n == 0) { GSL_ERROR_VAL ("workspace length n must be positive integer", - GSL_EDOM, 0); + GSL_EDOM, nullptr); } w = (gsl_integration_workspace *) malloc (sizeof (gsl_integration_workspace)); - if (w == 0) + if (w == nullptr) { GSL_ERROR_VAL ("failed to allocate space for workspace struct", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->alist = (double *) malloc (n * sizeof (double)); - if (w->alist == 0) + if (w->alist == nullptr) { free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for alist ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->blist = (double *) malloc (n * sizeof (double)); - if (w->blist == 0) + if (w->blist == nullptr) { free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for blist ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->rlist = (double *) malloc (n * sizeof (double)); - if (w->rlist == 0) + if (w->rlist == nullptr) { free (w->blist); free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for rlist ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->elist = (double *) malloc (n * sizeof (double)); - if (w->elist == 0) + if (w->elist == nullptr) { free (w->rlist); free (w->blist); @@ -1604,12 +1606,12 @@ gsl_integration_workspace_alloc (const size_t n) free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for elist ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->order = (size_t *) malloc (n * sizeof (size_t)); - if (w->order == 0) + if (w->order == nullptr) { free (w->elist); free (w->rlist); @@ -1618,12 +1620,12 @@ gsl_integration_workspace_alloc (const size_t n) free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for order ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->level = (size_t *) malloc (n * sizeof (size_t)); - if (w->level == 0) + if (w->level == nullptr) { free (w->order); free (w->elist); @@ -1633,7 +1635,7 @@ gsl_integration_workspace_alloc (const size_t n) free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for order ranges", - GSL_ENOMEM, 0); + GSL_ENOMEM, nullptr); } w->size = 0 ; @@ -1790,7 +1792,7 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) const double current = epstab[n]; double absolute = GSL_DBL_MAX; - double relative = 5 * GSL_DBL_EPSILON * fabs (current); + double relative = 5 * GSL_DBL_EPSILON * std::abs(current); const size_t newelm = n / 2; const size_t n_orig = n; @@ -1819,13 +1821,13 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) double e1 = epstab[n - 2 * i - 1]; double e2 = res; - double e1abs = fabs (e1); + double e1abs = std::abs(e1); double delta2 = e2 - e1; - double err2 = fabs (delta2); - double tol2 = GSL_MAX_DBL (fabs (e2), e1abs) * GSL_DBL_EPSILON; + double err2 = std::abs(delta2); + double tol2 = GSL_MAX_DBL (std::abs(e2), e1abs) * GSL_DBL_EPSILON; double delta3 = e1 - e0; - double err3 = fabs (delta3); - double tol3 = GSL_MAX_DBL (e1abs, fabs (e0)) * GSL_DBL_EPSILON; + double err3 = std::abs(delta3); + double tol3 = GSL_MAX_DBL (e1abs, std::abs(e0)) * GSL_DBL_EPSILON; double e3, delta1, err1, tol1, ss; @@ -1836,7 +1838,7 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) *result = res; absolute = err2 + err3; - relative = 5 * GSL_DBL_EPSILON * fabs (res); + relative = 5 * GSL_DBL_EPSILON * std::abs(res); *abserr = GSL_MAX_DBL (absolute, relative); return; } @@ -1844,8 +1846,8 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) e3 = epstab[n - 2 * i]; epstab[n - 2 * i] = e1; delta1 = e1 - e3; - err1 = fabs (delta1); - tol1 = GSL_MAX_DBL (e1abs, fabs (e3)) * GSL_DBL_EPSILON; + err1 = std::abs(delta1); + tol1 = GSL_MAX_DBL (e1abs, std::abs(e3)) * GSL_DBL_EPSILON; /* If two elements are very close to each other, omit a part of the table by adjusting the value of n */ @@ -1862,7 +1864,7 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) eventually omit a part of the table by adjusting the value of n. */ - if (fabs (ss * e1) <= 0.0001) + if (std::abs(ss * e1) <= 0.0001) { n_final = 2 * i; break; @@ -1875,7 +1877,7 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) epstab[n - 2 * i] = res; { - const double error = err2 + fabs (res - e2) + err3; + const double error = err2 + std::abs(res - e2) + err3; if (error <= *abserr) { @@ -1928,8 +1930,8 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) } else { /* Compute error estimate */ - *abserr = (fabs (*result - res3la[2]) + fabs (*result - res3la[1]) - + fabs (*result - res3la[0])); + *abserr = (std::abs(*result - res3la[2]) + std::abs(*result - res3la[1]) + + std::abs(*result - res3la[0])); res3la[0] = res3la[1]; res3la[1] = res3la[2]; @@ -1944,7 +1946,7 @@ qelg (struct extrapolation_table *table, double *result, double *abserr) table->nres = nres_orig + 1; - *abserr = GSL_MAX_DBL (*abserr, 5 * GSL_DBL_EPSILON * fabs (*result)); + *abserr = GSL_MAX_DBL (*abserr, 5 * GSL_DBL_EPSILON * std::abs(*result)); return; } @@ -1960,7 +1962,7 @@ test_positivity (double result, double resabs); static inline int test_positivity (double result, double resabs) { - int status = (fabs (result) >= (1 - 50 * GSL_DBL_EPSILON) * resabs); + int status = (std::abs(result) >= (1 - 50 * GSL_DBL_EPSILON) * resabs); return status; } @@ -2170,7 +2172,7 @@ qags (const gsl_function * f, if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28)) { - GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel", + GSL_ERROR ("tolerance cannot be achieved with given epsabs and epsrel", GSL_EBADTOL); } @@ -2180,7 +2182,7 @@ qags (const gsl_function * f, set_initial_result (workspace, result0, abserr0); - tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0)); + tolerance = GSL_MAX_DBL (epsabs, epsrel * std::abs(result0)); if (abserr0 <= 100 * GSL_DBL_EPSILON * resabs0 && abserr0 > tolerance) { @@ -2261,13 +2263,13 @@ qags (const gsl_function * f, errsum = errsum + error12 - e_i; area = area + area12 - r_i; - tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area)); + tolerance = GSL_MAX_DBL (epsabs, epsrel * std::abs(area)); if (resasc1 != error1 && resasc2 != error2) { double delta = r_i - area12; - if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i) + if (std::abs(delta) <= 1.0e-5 * std::abs(area12) && error12 >= 0.99 * e_i) { if (!extrapolate) { @@ -2381,7 +2383,7 @@ qags (const gsl_function * f, err_ext = abseps; res_ext = reseps; correc = error_over_large_intervals; - ertest = GSL_MAX_DBL (epsabs, epsrel * fabs (reseps)); + ertest = GSL_MAX_DBL (epsabs, epsrel * std::abs(reseps)); if (err_ext <= ertest) break; } @@ -2425,7 +2427,7 @@ qags (const gsl_function * f, if (res_ext != 0.0 && area != 0.0) { - if (err_ext / fabs (res_ext) > errsum / fabs (area)) + if (err_ext / std::abs(res_ext) > errsum / std::abs(area)) goto compute_result; } else if (err_ext > errsum) @@ -2441,7 +2443,7 @@ qags (const gsl_function * f, /* Test on divergence. */ { - double max_area = GSL_MAX_DBL (fabs (res_ext), fabs (area)); + double max_area = GSL_MAX_DBL (std::abs(res_ext), std::abs(area)); if (!positive_integrand && max_area < 0.01 * resabs0) goto return_error; @@ -2450,7 +2452,7 @@ qags (const gsl_function * f, { double ratio = res_ext / area; - if (ratio < 0.01 || ratio > 100.0 || errsum > fabs (area)) + if (ratio < 0.01 || ratio > 100.0 || errsum > std::abs(area)) error_type = 6; } diff --git a/roofit/roofitmore/src/RooGaussKronrodIntegrator1D.cxx b/roofit/roofitmore/src/RooGaussKronrodIntegrator1D.cxx index bef69309a34d5..dda3728b21756 100644 --- a/roofit/roofitmore/src/RooGaussKronrodIntegrator1D.cxx +++ b/roofit/roofitmore/src/RooGaussKronrodIntegrator1D.cxx @@ -39,41 +39,29 @@ Scientific Library version 1.5 and applies the 10-, 21-, 43- and reached **/ -#include -#include -#include -#include "Riostream.h" -#include "TMath.h" -#include "RooGaussKronrodIntegrator1D.h" -#include "RooArgSet.h" -#include "RooRealVar.h" -#include "RooNumber.h" -#include "RooNumIntFactory.h" -#include "RooIntegratorBinding.h" -#include "RooMsgService.h" +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +#include +#include +#include using namespace std; ClassImp(RooGaussKronrodIntegrator1D); -; - -// --- From GSL_MATH.h ------------------------------------------- -struct gsl_function_struct -{ - double (* function) (double x, void * params); - void * params; -}; -typedef struct gsl_function_struct gsl_function ; -#define GSL_FN_EVAL(F,x) (*((F)->function))(x,(F)->params) -//----From GSL_INTEGRATION.h --------------------------------------- -int gsl_integration_qng (const gsl_function * f, - double a, double b, - double epsabs, double epsrel, - double *result, double *abserr, - size_t * neval); -//------------------------------------------------------------------- +/// \cond ROOFIT_INTERNAL // register integrator class // create a derived class in order to call the protected method of the @@ -93,16 +81,27 @@ struct Roo_reg_GKInteg1D { }; static Roo_reg_GKInteg1D instance; -} +} // namespace RooFit_internal + +/// \endcond //////////////////////////////////////////////////////////////////////////////// /// Register RooGaussKronrodIntegrator1D, its parameters and capabilities with RooNumIntConfig -void RooGaussKronrodIntegrator1D::registerIntegrator(RooNumIntFactory& fact) +void RooGaussKronrodIntegrator1D::registerIntegrator(RooNumIntFactory &fact) { - fact.storeProtoIntegrator(new RooGaussKronrodIntegrator1D(),RooArgSet()) ; - oocoutI(nullptr,Integration) << "RooGaussKronrodIntegrator1D has been registered" << std::endl; + auto creator = [](const RooAbsFunc &function, const RooNumIntConfig &config) { + return std::make_unique(function, config); + }; + + fact.registerPlugin("RooGaussKronrodIntegrator1D", creator, {}, + /*canIntegrate1D=*/true, + /*canIntegrate2D=*/false, + /*canIntegrateND=*/false, + /*canIntegrateOpenEnded=*/true); + + oocoutI(nullptr, Integration) << "RooGaussKronrodIntegrator1D has been registered" << std::endl; } @@ -138,17 +137,6 @@ RooGaussKronrodIntegrator1D::RooGaussKronrodIntegrator1D(const RooAbsFunc& funct } - -//////////////////////////////////////////////////////////////////////////////// -/// Clone integrator with given function and configuration. Needed for RooNumIntFactory - -RooAbsIntegrator* RooGaussKronrodIntegrator1D::clone(const RooAbsFunc& function, const RooNumIntConfig& config) const -{ - return new RooGaussKronrodIntegrator1D(function,config) ; -} - - - //////////////////////////////////////////////////////////////////////////////// /// Perform one-time initialization of integrator @@ -187,7 +175,7 @@ bool RooGaussKronrodIntegrator1D::setLimits(double* xmin, double* xmax) bool RooGaussKronrodIntegrator1D::checkLimits() const { if(_useIntegrandLimits) { - assert(0 != integrand() && integrand()->isValid()); + assert(nullptr != integrand() && integrand()->isValid()); _xmin= integrand()->getMinLimit(0); _xmax= integrand()->getMaxLimit(0); } @@ -232,419 +220,3 @@ double RooGaussKronrodIntegrator1D::integral(const double *yvec) return result; } - - -// ---------------------------------------------------------------------------- -// ---------- Code below imported from GSL version 1.5 ------------------------ -// ---------------------------------------------------------------------------- - -/* - * - * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or (at - * your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -#define GSL_SUCCESS 0 -#define GSL_EBADTOL 13 /* user specified an invalid tolerance */ -#define GSL_ETOL 14 /* failed to reach the specified tolerance */ -#define GSL_ERROR(a,b) oocoutE(nullptr,Eval) << "RooGaussKronrodIntegrator1D::integral() ERROR: " << a << endl ; return b ; -#define GSL_DBL_MIN 2.2250738585072014e-308 -#define GSL_DBL_EPSILON 2.2204460492503131e-16 - - -// INCLUDED BELOW #include "qng.c" - -int gsl_integration_qng (const gsl_function * f, - double a, double b, - double epsabs, double epsrel, - double *result, double *abserr, - size_t * neval); - - - -// INCLUDED BELOW #include "err.c" -static double rescale_error (double err, const double result_abs, const double result_asc) ; - -static double -rescale_error (double err, const double result_abs, const double result_asc) -{ - err = fabs(err) ; - - if (result_asc != 0 && err != 0) - { - double scale = TMath::Power((200 * err / result_asc), 1.5) ; - - if (scale < 1) - { - err = result_asc * scale ; - } - else - { - err = result_asc ; - } - } - if (result_abs > GSL_DBL_MIN / (50 * GSL_DBL_EPSILON)) - { - double min_err = 50 * GSL_DBL_EPSILON * result_abs ; - - if (min_err > err) - { - err = min_err ; - } - } - - return err ; -} - - -// INCLUDED BELOW #include "qng.h" -/* Gauss-Kronrod-Patterson quadrature coefficients for use in - quadpack routine qng. These coefficients were calculated with - 101 decimal digit arithmetic by L. W. Fullerton, Bell Labs, Nov - 1981. */ - -/* x1, abscissae common to the 10-, 21-, 43- and 87-point rule */ -static const double x1[5] = { - 0.973906528517171720077964012084452, - 0.865063366688984510732096688423493, - 0.679409568299024406234327365114874, - 0.433395394129247190799265943165784, - 0.148874338981631210884826001129720 -} ; - -/* w10, weights of the 10-point formula */ -static const double w10[5] = { - 0.066671344308688137593568809893332, - 0.149451349150580593145776339657697, - 0.219086362515982043995534934228163, - 0.269266719309996355091226921569469, - 0.295524224714752870173892994651338 -} ; - -/* x2, abscissae common to the 21-, 43- and 87-point rule */ -static const double x2[5] = { - 0.995657163025808080735527280689003, - 0.930157491355708226001207180059508, - 0.780817726586416897063717578345042, - 0.562757134668604683339000099272694, - 0.294392862701460198131126603103866 -} ; - -/* w21a, weights of the 21-point formula for abscissae x1 */ -static const double w21a[5] = { - 0.032558162307964727478818972459390, - 0.075039674810919952767043140916190, - 0.109387158802297641899210590325805, - 0.134709217311473325928054001771707, - 0.147739104901338491374841515972068 -} ; - -/* w21b, weights of the 21-point formula for abscissae x2 */ -static const double w21b[6] = { - 0.011694638867371874278064396062192, - 0.054755896574351996031381300244580, - 0.093125454583697605535065465083366, - 0.123491976262065851077958109831074, - 0.142775938577060080797094273138717, - 0.149445554002916905664936468389821 -} ; - -/* x3, abscissae common to the 43- and 87-point rule */ -static const double x3[11] = { - 0.999333360901932081394099323919911, - 0.987433402908088869795961478381209, - 0.954807934814266299257919200290473, - 0.900148695748328293625099494069092, - 0.825198314983114150847066732588520, - 0.732148388989304982612354848755461, - 0.622847970537725238641159120344323, - 0.499479574071056499952214885499755, - 0.364901661346580768043989548502644, - 0.222254919776601296498260928066212, - 0.074650617461383322043914435796506 -} ; - -/* w43a, weights of the 43-point formula for abscissae x1, x3 */ -static const double w43a[10] = { - 0.016296734289666564924281974617663, - 0.037522876120869501461613795898115, - 0.054694902058255442147212685465005, - 0.067355414609478086075553166302174, - 0.073870199632393953432140695251367, - 0.005768556059769796184184327908655, - 0.027371890593248842081276069289151, - 0.046560826910428830743339154433824, - 0.061744995201442564496240336030883, - 0.071387267268693397768559114425516 -} ; - -/* w43b, weights of the 43-point formula for abscissae x3 */ -static const double w43b[12] = { - 0.001844477640212414100389106552965, - 0.010798689585891651740465406741293, - 0.021895363867795428102523123075149, - 0.032597463975345689443882222526137, - 0.042163137935191811847627924327955, - 0.050741939600184577780189020092084, - 0.058379395542619248375475369330206, - 0.064746404951445885544689259517511, - 0.069566197912356484528633315038405, - 0.072824441471833208150939535192842, - 0.074507751014175118273571813842889, - 0.074722147517403005594425168280423 -} ; - -/* x4, abscissae of the 87-point rule */ -static const double x4[22] = { - 0.999902977262729234490529830591582, - 0.997989895986678745427496322365960, - 0.992175497860687222808523352251425, - 0.981358163572712773571916941623894, - 0.965057623858384619128284110607926, - 0.943167613133670596816416634507426, - 0.915806414685507209591826430720050, - 0.883221657771316501372117548744163, - 0.845710748462415666605902011504855, - 0.803557658035230982788739474980964, - 0.757005730685495558328942793432020, - 0.706273209787321819824094274740840, - 0.651589466501177922534422205016736, - 0.593223374057961088875273770349144, - 0.531493605970831932285268948562671, - 0.466763623042022844871966781659270, - 0.399424847859218804732101665817923, - 0.329874877106188288265053371824597, - 0.258503559202161551802280975429025, - 0.185695396568346652015917141167606, - 0.111842213179907468172398359241362, - 0.037352123394619870814998165437704 -} ; - -/* w87a, weights of the 87-point formula for abscissae x1, x2, x3 */ -static const double w87a[21] = { - 0.008148377384149172900002878448190, - 0.018761438201562822243935059003794, - 0.027347451050052286161582829741283, - 0.033677707311637930046581056957588, - 0.036935099820427907614589586742499, - 0.002884872430211530501334156248695, - 0.013685946022712701888950035273128, - 0.023280413502888311123409291030404, - 0.030872497611713358675466394126442, - 0.035693633639418770719351355457044, - 0.000915283345202241360843392549948, - 0.005399280219300471367738743391053, - 0.010947679601118931134327826856808, - 0.016298731696787335262665703223280, - 0.021081568889203835112433060188190, - 0.025370969769253827243467999831710, - 0.029189697756475752501446154084920, - 0.032373202467202789685788194889595, - 0.034783098950365142750781997949596, - 0.036412220731351787562801163687577, - 0.037253875503047708539592001191226 -} ; - -/* w87b, weights of the 87-point formula for abscissae x4 */ -static const double w87b[23] = { - 0.000274145563762072350016527092881, - 0.001807124155057942948341311753254, - 0.004096869282759164864458070683480, - 0.006758290051847378699816577897424, - 0.009549957672201646536053581325377, - 0.012329447652244853694626639963780, - 0.015010447346388952376697286041943, - 0.017548967986243191099665352925900, - 0.019938037786440888202278192730714, - 0.022194935961012286796332102959499, - 0.024339147126000805470360647041454, - 0.026374505414839207241503786552615, - 0.028286910788771200659968002987960, - 0.030052581128092695322521110347341, - 0.031646751371439929404586051078883, - 0.033050413419978503290785944862689, - 0.034255099704226061787082821046821, - 0.035262412660156681033782717998428, - 0.036076989622888701185500318003895, - 0.036698604498456094498018047441094, - 0.037120549269832576114119958413599, - 0.037334228751935040321235449094698, - 0.037361073762679023410321241766599 -} ; - - -int -gsl_integration_qng (const gsl_function *f, - double a, double b, - double epsabs, double epsrel, - double * result, double * abserr, size_t * neval) -{ - double fv1[5], fv2[5], fv3[5], fv4[5]; - double savfun[21]; /* array of function values which have been computed */ - double res10, res21, res43, res87; /* 10, 21, 43 and 87 point results */ - double result_kronrod, err ; - double resabs; /* approximation to the integral of abs(f) */ - double resasc; /* approximation to the integral of abs(f-i/(b-a)) */ - - const double half_length = 0.5 * (b - a); - const double abs_half_length = fabs (half_length); - const double center = 0.5 * (b + a); - const double f_center = GSL_FN_EVAL(f, center); - - int k ; - - if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28)) - { - * result = 0; - * abserr = 0; - * neval = 0; - GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel", - GSL_EBADTOL); - }; - - /* Compute the integral using the 10- and 21-point formula. */ - - res10 = 0; - res21 = w21b[5] * f_center; - resabs = w21b[5] * fabs (f_center); - - for (k = 0; k < 5; k++) - { - const double abscissa = half_length * x1[k]; - const double fval1 = GSL_FN_EVAL(f, center + abscissa); - const double fval2 = GSL_FN_EVAL(f, center - abscissa); - const double fval = fval1 + fval2; - res10 += w10[k] * fval; - res21 += w21a[k] * fval; - resabs += w21a[k] * (fabs (fval1) + fabs (fval2)); - savfun[k] = fval; - fv1[k] = fval1; - fv2[k] = fval2; - } - - for (k = 0; k < 5; k++) - { - const double abscissa = half_length * x2[k]; - const double fval1 = GSL_FN_EVAL(f, center + abscissa); - const double fval2 = GSL_FN_EVAL(f, center - abscissa); - const double fval = fval1 + fval2; - res21 += w21b[k] * fval; - resabs += w21b[k] * (fabs (fval1) + fabs (fval2)); - savfun[k + 5] = fval; - fv3[k] = fval1; - fv4[k] = fval2; - } - - resabs *= abs_half_length ; - - { - const double mean = 0.5 * res21; - - resasc = w21b[5] * fabs (f_center - mean); - - for (k = 0; k < 5; k++) - { - resasc += - (w21a[k] * (fabs (fv1[k] - mean) + fabs (fv2[k] - mean)) - + w21b[k] * (fabs (fv3[k] - mean) + fabs (fv4[k] - mean))); - } - resasc *= abs_half_length ; - } - - result_kronrod = res21 * half_length; - - err = rescale_error ((res21 - res10) * half_length, resabs, resasc) ; - - /* test for convergence. */ - - if (err < epsabs || err < epsrel * fabs (result_kronrod)) - { - * result = result_kronrod ; - * abserr = err ; - * neval = 21; - return GSL_SUCCESS; - } - - /* compute the integral using the 43-point formula. */ - - res43 = w43b[11] * f_center; - - for (k = 0; k < 10; k++) - { - res43 += savfun[k] * w43a[k]; - } - - for (k = 0; k < 11; k++) - { - const double abscissa = half_length * x3[k]; - const double fval = (GSL_FN_EVAL(f, center + abscissa) - + GSL_FN_EVAL(f, center - abscissa)); - res43 += fval * w43b[k]; - savfun[k + 10] = fval; - } - - /* test for convergence */ - - result_kronrod = res43 * half_length; - err = rescale_error ((res43 - res21) * half_length, resabs, resasc); - - if (err < epsabs || err < epsrel * fabs (result_kronrod)) - { - * result = result_kronrod ; - * abserr = err ; - * neval = 43; - return GSL_SUCCESS; - } - - /* compute the integral using the 87-point formula. */ - - res87 = w87b[22] * f_center; - - for (k = 0; k < 21; k++) - { - res87 += savfun[k] * w87a[k]; - } - - for (k = 0; k < 22; k++) - { - const double abscissa = half_length * x4[k]; - res87 += w87b[k] * (GSL_FN_EVAL(f, center + abscissa) - + GSL_FN_EVAL(f, center - abscissa)); - } - - /* test for convergence */ - - result_kronrod = res87 * half_length ; - - err = rescale_error ((res87 - res43) * half_length, resabs, resasc); - - if (err < epsabs || err < epsrel * fabs (result_kronrod)) - { - * result = result_kronrod ; - * abserr = err ; - * neval = 87; - return GSL_SUCCESS; - } - - /* failed to converge */ - - * result = result_kronrod ; - * abserr = err ; - * neval = 87; - - // GSL_ERROR("failed to reach tolerance with highest-order rule", GSL_ETOL) ; - return GSL_ETOL ; -} diff --git a/roofit/roofitmore/src/RooHypatia2.cxx b/roofit/roofitmore/src/RooHypatia2.cxx index cac8d00023729..39b01ce4ce455 100644 --- a/roofit/roofitmore/src/RooHypatia2.cxx +++ b/roofit/roofitmore/src/RooHypatia2.cxx @@ -93,7 +93,6 @@ #include "BracketAdapters.h" #include "RooAbsReal.h" #include "RooHelpers.h" -#include "RunContext.h" #include "TMath.h" #include "Math/SpecFunc.h" @@ -182,7 +181,7 @@ double low_x_LnBK(double nu, double x){ } double besselK(double ni, double x) { - const double nu = std::fabs(ni); + const double nu = std::abs(ni); if ((x < 1.e-06 && nu > 0.) || (x < 1.e-04 && nu > 0. && nu < 55.) || (x < 0.1 && nu >= 55.) ) @@ -197,7 +196,7 @@ double besselK(double ni, double x) { } double LnBesselK(double ni, double x) { - const double nu = std::fabs(ni); + const double nu = std::abs(ni); if ((x < 1.e-06 && nu > 0.) || (x < 1.e-04 && nu > 0. && nu < 55.) || (x < 0.1 && nu >= 55.) ) @@ -219,7 +218,7 @@ double LogEval(double d, double l, double alpha, double beta, double delta) { return std::exp(logno + beta*d + (0.5-l)*(std::log(alpha)-0.5*std::log(thing)) - + LnBesselK(l-0.5, alpha*std::sqrt(thing)) );// + std::log(std::fabs(beta)+0.0001) ); + + LnBesselK(l-0.5, alpha*std::sqrt(thing)) );// + std::log(std::abs(beta)+0.0001) ); } @@ -243,7 +242,7 @@ double diff_eval(double d, double l, double alpha, double beta, double delta){ /* double Gauss2F1(double a, double b, double c, double x){ - if (fabs(x) <= 1.) { + if (std::abs(x) <= 1.) { return ROOT::Math::hyperg(a, b, c, x); } else { return ROOT::Math::hyperg(c-a, b, c, 1-1/(1-x))/std::pow(1-x, b); @@ -336,7 +335,7 @@ namespace { /// This is only needed in the rare case where a parameter is used as an observable. template -void compute(RooSpan output, Tx x, Tl lambda, Tz zeta, Tb beta, Ts sigma, Tm mu, Ta a, Tn n, Ta2 a2, Tn2 n2) { +void compute(std::span output, Tx x, Tl lambda, Tz zeta, Tb beta, Ts sigma, Tm mu, Ta a, Tn n, Ta2 a2, Tn2 n2) { const auto N = output.size(); const bool zetaIsAlwaysLargerZero = !zeta.isBatch() && zeta[0] > 0.; const bool zetaIsAlwaysZero = !zeta.isBatch() && zeta[0] == 0.; @@ -432,7 +431,7 @@ using RooBatchCompute::BracketAdapter; ////////////////////////////////////////////////////////////////////////////////////////// /// A specialised compute function where x is an observable, and all parameters are used as /// parameters. Since many things can be calculated outside of the loop, it is faster. -void compute(RooSpan output, RooSpan x, +void compute(std::span output, std::span x, BracketAdapter lambda, BracketAdapter zeta, BracketAdapter beta, BracketAdapter sigma, BracketAdapter mu, BracketAdapter a, BracketAdapter n, BracketAdapter a2, BracketAdapter n2) { @@ -488,43 +487,42 @@ void compute(RooSpan output, RooSpan x, } -RooSpan RooHypatia2::evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { +void RooHypatia2::computeBatch(double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const +{ using namespace RooBatchCompute; - auto x = _x->getValues(evalData, normSet); - auto lambda = _lambda->getValues(evalData, normSet); - auto zeta = _zeta->getValues(evalData, normSet); - auto beta = _beta->getValues(evalData, normSet); - auto sig = _sigma->getValues(evalData, normSet); - auto mu = _mu->getValues(evalData, normSet); - auto a = _a->getValues(evalData, normSet); - auto n = _n->getValues(evalData, normSet); - auto a2 = _a2->getValues(evalData, normSet); - auto n2 = _n2->getValues(evalData, normSet); - - size_t paramSizeSum=0, batchSize = x.size(); + auto x = dataMap.at(_x); + auto lambda = dataMap.at(_lambda); + auto zeta = dataMap.at(_zeta); + auto beta = dataMap.at(_beta); + auto sig = dataMap.at(_sigma); + auto mu = dataMap.at(_mu); + auto a = dataMap.at(_a); + auto n = dataMap.at(_n); + auto a2 = dataMap.at(_a2); + auto n2 = dataMap.at(_n2); + + size_t paramSizeSum=0; for (const auto& i:{lambda, zeta, beta, sig, mu, a, n, a2, n2}) { paramSizeSum += i.size(); - batchSize = std::max(batchSize, i.size()); } - RooSpan output = evalData.makeBatch(this, batchSize); + std::span outputSpan{output, size}; // Run high performance compute if only x has multiple values if (x.size()>1 && paramSizeSum==9) { - compute(output, x, + compute(outputSpan, x, BracketAdapter(_lambda), BracketAdapter(_zeta), BracketAdapter(_beta), BracketAdapter(_sigma), BracketAdapter(_mu), BracketAdapter(_a), BracketAdapter(_n), BracketAdapter(_a2), BracketAdapter(_n2)); } else { - compute(output, BracketAdapterWithMask(_x, x), + compute(outputSpan, BracketAdapterWithMask(_x, x), BracketAdapterWithMask(_lambda, lambda), BracketAdapterWithMask(_zeta, zeta), BracketAdapterWithMask(_beta, beta), BracketAdapterWithMask(_sigma, sig), BracketAdapterWithMask(_mu, mu), BracketAdapterWithMask(_a, a), BracketAdapterWithMask(_n, n), BracketAdapterWithMask(_a2, a2), BracketAdapterWithMask(_n2, n2)); } - return output; } diff --git a/roofit/roofitmore/src/RooLegendre.cxx b/roofit/roofitmore/src/RooLegendre.cxx index e80cc2a7c1090..3b4673d793ec8 100644 --- a/roofit/roofitmore/src/RooLegendre.cxx +++ b/roofit/roofitmore/src/RooLegendre.cxx @@ -22,7 +22,6 @@ **/ #include "RooLegendre.h" -#include "RunContext.h" #include "RooAbsReal.h" #include "Math/SpecFunc.h" @@ -168,12 +167,9 @@ void compute( size_t batchSize, const int l1, const int m1, const int l2, const } }; -RooSpan RooLegendre::evaluateSpan(RooBatchCompute::RunContext& evalData, const RooArgSet* normSet) const { - RooSpan cthetaData = _ctheta->getValues(evalData, normSet); - size_t batchSize = cthetaData.size(); - auto output = evalData.makeBatch(this, batchSize); - compute(batchSize, _l1, _m1, _l2, _m2, output.data(), cthetaData.data()); - return output; +void RooLegendre::computeBatch(double* output, size_t size, RooFit::Detail::DataMap const& dataMap) const +{ + compute(size, _l1, _m1, _l2, _m2, output, dataMap.at(_ctheta).data()); } @@ -182,9 +178,9 @@ RooSpan RooLegendre::evaluateSpan(RooBatchCompute::RunContext& evalData, namespace { bool fullRange(const RooRealProxy& x ,const char* range) { - return range == 0 || strlen(range) == 0 - ? std::fabs(x.min() + 1.) < 1.e-8 && std::fabs(x.max() - 1.) < 1.e-8 - : std::fabs(x.min(range) + 1.) < 1.e-8 && std::fabs(x.max(range) - 1.) < 1.e-8; + return range == nullptr || strlen(range) == 0 + ? std::abs(x.min() + 1.) < 1.e-8 && std::abs(x.max() - 1.) < 1.e-8 + : std::abs(x.min(range) + 1.) < 1.e-8 && std::abs(x.max(range) - 1.) < 1.e-8; } } diff --git a/roofit/roofitmore/src/RooNonCentralChiSquare.cxx b/roofit/roofitmore/src/RooNonCentralChiSquare.cxx index 540768eb9059a..035f95aa63ba8 100644 --- a/roofit/roofitmore/src/RooNonCentralChiSquare.cxx +++ b/roofit/roofitmore/src/RooNonCentralChiSquare.cxx @@ -43,7 +43,7 @@ This implementation could be improved. BOOST has a nice implementation: #include "RooNonCentralChiSquare.h" #include "RooAbsReal.h" #include "RooAbsCategory.h" -#include +#include #include "TMath.h" //#include "RooNumber.h" #include "Math/DistFunc.h" @@ -231,7 +231,7 @@ double RooNonCentralChiSquare::analyticalIntegral(Int_t code, const char* rangeN double sum = 0; double ithTerm = 0; - double errorTol = fErrorTol; // for nomralization allow slightly larger error + double errorTol = fErrorTol; // for normalization allow slightly larger error int MaxIters = fMaxIters; // for normalization use more terms int iDominant = (int) TMath::Floor(lambda/2); diff --git a/roofit/roofitmore/src/RooSpHarmonic.cxx b/roofit/roofitmore/src/RooSpHarmonic.cxx index 39d03abf10980..49e1201d5abaa 100644 --- a/roofit/roofitmore/src/RooSpHarmonic.cxx +++ b/roofit/roofitmore/src/RooSpHarmonic.cxx @@ -47,7 +47,7 @@ integrals, using the orthogonality properties of \f$Y_l^m\f$... **/ #include "Riostream.h" -#include +#include #include "RooSpHarmonic.h" #include "Math/SpecFunc.h" @@ -124,14 +124,14 @@ namespace { bool fullRange(const RooRealProxy& x, const char* range, bool phi) { if (phi) { - return range == 0 || strlen(range) == 0 - ? std::fabs(x.max() - x.min() - TMath::TwoPi()) < 1.e-8 - : std::fabs(x.max(range) - x.min(range) - TMath::TwoPi()) < 1.e-8; + return range == nullptr || strlen(range) == 0 + ? std::abs(x.max() - x.min() - TMath::TwoPi()) < 1.e-8 + : std::abs(x.max(range) - x.min(range) - TMath::TwoPi()) < 1.e-8; } - return range == 0 || strlen(range) == 0 - ? std::fabs(x.min() + 1.) < 1.e-8 && std::fabs(x.max() - 1.) < 1.e-8 - : std::fabs(x.min(range) + 1.) < 1.e-8 && std::fabs(x.max(range) - 1.) < 1.e-8; + return range == nullptr || strlen(range) == 0 + ? std::abs(x.min() + 1.) < 1.e-8 && std::abs(x.max() - 1.) < 1.e-8 + : std::abs(x.min(range) + 1.) < 1.e-8 && std::abs(x.max(range) - 1.) < 1.e-8; } } diff --git a/roofit/roostats/CMakeLists.txt b/roofit/roostats/CMakeLists.txt index d3e1bf8d80499..692161f9112e3 100644 --- a/roofit/roostats/CMakeLists.txt +++ b/roofit/roostats/CMakeLists.txt @@ -9,6 +9,11 @@ # @author Pere Mato, CERN ############################################################################ +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(RooStats HEADERS RooStats/AsymptoticCalculator.h @@ -98,7 +103,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooStats src/MCMCInterval.cxx src/MCMCIntervalPlot.cxx src/MetropolisHastings.cxx - src/ModelConfig.cxx src/NeymanConstruction.cxx src/NumberCountingPdfFactory.cxx src/NumberCountingUtils.cxx @@ -136,6 +140,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooStats Foam Graf Gpad + ${EXTRA_DICT_OPTS} ) ROOT_ADD_TEST_SUBDIRECTORY(test) diff --git a/roofit/roostats/doc/index.md b/roofit/roostats/doc/index.md index 6fa8092acc47f..6330991455138 100644 --- a/roofit/roostats/doc/index.md +++ b/roofit/roostats/doc/index.md @@ -1,4 +1,4 @@ -\defgroup Roostats Roostats +\defgroup Roostats RooStats \brief RooStats is a toolkit for statistical tests built on top of RooFit. \ingroup Roofitmain diff --git a/roofit/roostats/inc/LinkDef.h b/roofit/roostats/inc/LinkDef.h index f5a08205fcd2a..f9d4466905375 100644 --- a/roofit/roostats/inc/LinkDef.h +++ b/roofit/roostats/inc/LinkDef.h @@ -34,8 +34,6 @@ #pragma link C++ class RooStats::LikelihoodInterval+; #pragma link C++ class RooStats::PointSetInterval+; -#pragma link C++ class RooStats::ModelConfig+; - #pragma link C++ class RooStats::IntervalCalculator+; // interface, not concrete #pragma link C++ class RooStats::HypoTestCalculator+; // interface, not concrete #pragma link C++ class RooStats::CombinedCalculator+; // interface, not concrete @@ -105,25 +103,6 @@ #pragma link C++ class RooStats::UpperLimitMCSModule+; -#pragma link C++ function RooStats::NumberCountingUtils::BinomialExpZ(double , double ,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialWithTauExpZ(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialObsZ(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialWithTauObsZ(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialExpP(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialWithTauExpP(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialObsP(double,double,double); -#pragma link C++ function RooStats::NumberCountingUtils::BinomialWithTauObsP(double,double,double); - -#pragma link C++ function RooStats::PValueToSignificance(double); -#pragma link C++ function RooStats::SignificanceToPValue(double); -#pragma link C++ function RooStats::RemoveConstantParameters(RooArgSet* set); -#pragma link C++ function RooStats::RemoveConstantParameters(RooArgList& set); -#pragma link C++ function RooStats::SetParameters(const RooArgSet* , RooArgSet* ); -#pragma link C++ function RooStats::SetAllConstant(const RooAbsCollection & , bool ); -#pragma link C++ function RooStats::MakeNuisancePdf(RooAbsPdf & , const RooArgSet &, const char * ); -#pragma link C++ function RooStats::MakeNuisancePdf(const RooStats::ModelConfig & , const char * ); -#pragma link C++ function RooStats::GetAsTTree(TString, TString, const RooDataSet&); - // need for unique_ptr object in Likelihoodinterval since they are forwd declared #pragma extra_include "Math/IFunction.h"; diff --git a/roofit/roostats/inc/RooStats/AsymptoticCalculator.h b/roofit/roostats/inc/RooStats/AsymptoticCalculator.h index b94a8f90507b4..c79ef5f45ad27 100644 --- a/roofit/roostats/inc/RooStats/AsymptoticCalculator.h +++ b/roofit/roostats/inc/RooStats/AsymptoticCalculator.h @@ -116,7 +116,7 @@ namespace RooStats { static void FillBins(const RooAbsPdf & pdf, const RooArgList &obs, RooAbsData & data, int &index, double &binVolume, int &ibin); - static double EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, const RooArgSet * condObs, const RooArgSet * globObs, const RooArgSet *poiSet = nullptr ); + static double EvaluateNLL(RooStats::ModelConfig const& modelConfig, RooAbsData& data, const RooArgSet *poiSet = nullptr ); static bool SetObsToExpected(RooAbsPdf &pdf, const RooArgSet &obs); static bool SetObsToExpected(RooProdPdf &prod, const RooArgSet &obs); diff --git a/roofit/roostats/inc/RooStats/BayesianCalculator.h b/roofit/roostats/inc/RooStats/BayesianCalculator.h index 018ecfb36dab5..f0800cb866abf 100644 --- a/roofit/roostats/inc/RooStats/BayesianCalculator.h +++ b/roofit/roostats/inc/RooStats/BayesianCalculator.h @@ -171,7 +171,7 @@ namespace RooStats { RooArgSet fGlobalObs; ///< global observables mutable RooAbsPdf* fProductPdf; ///< internal pointer to model * prior - mutable RooAbsReal* fLogLike; ///< internal pointer to log likelihood function + mutable std::unique_ptr fLogLike; ///< internal pointer to log likelihood function mutable RooAbsReal* fLikelihood; ///< internal pointer to likelihood function mutable RooAbsReal* fIntegratedLikelihood; ///< integrated likelihood function, i.e - unnormalized posterior function mutable RooAbsPdf* fPosteriorPdf; ///< normalized (on the poi) posterior pdf @@ -191,7 +191,7 @@ namespace RooStats { protected: - ClassDefOverride(BayesianCalculator,2) // BayesianCalculator class + ClassDefOverride(BayesianCalculator,3) // BayesianCalculator class }; } diff --git a/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h b/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h index f8cd81958401d..811e81857c900 100644 --- a/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h +++ b/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h @@ -43,7 +43,7 @@ namespace RooStats { const RooArgList* GetAsArgList() const { // Returns this set of detailed output. - // Note that the ownership of the returned list is not transfered + // Note that the ownership of the returned list is not transferred // It is managed by the DetailedOutputAggregator class return fBuiltSet; } diff --git a/roofit/roostats/inc/RooStats/FeldmanCousins.h b/roofit/roostats/inc/RooStats/FeldmanCousins.h index 2748bd7f06079..5a19dcd4f6c95 100644 --- a/roofit/roostats/inc/RooStats/FeldmanCousins.h +++ b/roofit/roostats/inc/RooStats/FeldmanCousins.h @@ -50,20 +50,6 @@ namespace RooStats { void SetData(RooAbsData& /*data*/) override { std::cout << "DEPRECATED, set data in constructor" << std::endl; } - /// Set the Pdf - virtual void SetPdf(RooAbsPdf& /*pdf*/) { - std::cout << "DEPRECATED, use ModelConfig" << std::endl; - } - - /// specify the parameters of interest in the interval - virtual void SetParameters(const RooArgSet& /*set*/) { - std::cout << "DEPRECATED, use ModelConfig" << std::endl; - } - - /// specify the nuisance parameters (eg. the rest of the parameters) - virtual void SetNuisanceParameters(const RooArgSet& /*set*/) { - std::cout << "DEPRECATED, use ModelConfig" << std::endl; - } /// User-defined set of points to test void SetParameterPointsToTest(RooAbsData& pointsToTest) { diff --git a/roofit/roostats/inc/RooStats/HypoTestResult.h b/roofit/roostats/inc/RooStats/HypoTestResult.h index e05dd18f1ce1b..84f8c5a01c537 100644 --- a/roofit/roostats/inc/RooStats/HypoTestResult.h +++ b/roofit/roostats/inc/RooStats/HypoTestResult.h @@ -76,6 +76,10 @@ namespace RooStats { const RooArgList* GetAllTestStatisticsData(void) const { return fAllTestStatisticsData; } bool HasTestStatisticData(void) const; + void SetNullPValue(double pvalue) { fNullPValue = pvalue; } + void SetNullPValueError(double err) { fNullPValueError = err; } + void SetAltPValue(double pvalue) { fAlternatePValue = pvalue; } + void SetAltPValueError(double err) { fAlternatePValueError = err; } void SetAltDistribution(SamplingDistribution *alt); void SetNullDistribution(SamplingDistribution *null); void SetAltDetailedOutput(RooDataSet* d) { fAltDetailedOutput = d; } diff --git a/roofit/roostats/inc/RooStats/LikelihoodIntervalPlot.h b/roofit/roostats/inc/RooStats/LikelihoodIntervalPlot.h index 33d02ad81f360..411b21ed14d63 100644 --- a/roofit/roostats/inc/RooStats/LikelihoodIntervalPlot.h +++ b/roofit/roostats/inc/RooStats/LikelihoodIntervalPlot.h @@ -69,7 +69,7 @@ namespace RooStats { /// for the 1D case a RooPlot is drawn by default of the profiled Log-Likelihood ratio /// if option "TF1" is used the objects are drawn using a TF1 scanning the LL function in a /// grid of the set points (by default - /// the TF1 can be costumized by setting maximum and the number of points to scan + /// the TF1 can be customized by setting maximum and the number of points to scan void Draw(const Option_t *options=nullptr) override; private: diff --git a/roofit/roostats/inc/RooStats/MCMCInterval.h b/roofit/roostats/inc/RooStats/MCMCInterval.h index 43d58cc989cbd..fb1c5124312ed 100644 --- a/roofit/roostats/inc/RooStats/MCMCInterval.h +++ b/roofit/roostats/inc/RooStats/MCMCInterval.h @@ -199,7 +199,7 @@ namespace RooStats { /// Get a clone of the markov chain on which this interval is based /// as a RooDataSet. You own the returned RooDataSet* - virtual RooDataSet* GetChainAsDataSet(RooArgSet* whichVars = nullptr) + virtual RooFit::OwningPtr GetChainAsDataSet(RooArgSet* whichVars = nullptr) { return fChain->GetAsDataSet(whichVars); } /// Get the markov chain on which this interval is based @@ -209,7 +209,7 @@ namespace RooStats { /// Get a clone of the markov chain on which this interval is based /// as a RooDataHist. You own the returned RooDataHist* - virtual RooDataHist* GetChainAsDataHist(RooArgSet* whichVars = nullptr) + virtual RooFit::OwningPtr GetChainAsDataHist(RooArgSet* whichVars = nullptr) { return fChain->GetAsDataHist(whichVars); } /// Get a clone of the markov chain on which this interval is based diff --git a/roofit/roostats/inc/RooStats/MarkovChain.h b/roofit/roostats/inc/RooStats/MarkovChain.h index e23737d600fb0..c43102f0ca572 100644 --- a/roofit/roostats/inc/RooStats/MarkovChain.h +++ b/roofit/roostats/inc/RooStats/MarkovChain.h @@ -64,15 +64,15 @@ namespace RooStats { /// of whichVars. Call with whichVars = nullptr (default) to get values of /// all variables (including NLL value and weight); /// Note: caller owns the returned data set - virtual RooDataSet* GetAsDataSet(RooArgSet* whichVars = nullptr) const; + virtual RooFit::OwningPtr GetAsDataSet(RooArgSet* whichVars = nullptr) const; /// Get a clone of the markov chain on which this interval is based /// as a RooDataSet. You own the returned RooDataSet* - virtual RooDataSet* GetAsDataSet(const RooCmdArg& arg1, - const RooCmdArg& arg2=RooCmdArg::none(), const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), - const RooCmdArg& arg8=RooCmdArg::none() ) const; + virtual RooFit::OwningPtr GetAsDataSet(const RooCmdArg& arg1, + const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, + const RooCmdArg& arg8={} ) const; virtual const RooDataSet* GetAsConstDataSet() const { return fChain; } @@ -80,15 +80,15 @@ namespace RooStats { /// of whichVars. Call with whichVars = nullptr (default) to get values of /// all variables (including NLL value and weight); /// Note: caller owns the returned data hist - virtual RooDataHist* GetAsDataHist(RooArgSet* whichVars = nullptr) const; + virtual RooFit::OwningPtr GetAsDataHist(RooArgSet* whichVars = nullptr) const; /// Get a clone of the markov chain on which this interval is based /// as a RooDataHist. You own the returned RooDataHist* - virtual RooDataHist* GetAsDataHist(const RooCmdArg & arg1, - const RooCmdArg& arg2=RooCmdArg::none(), const RooCmdArg& arg3=RooCmdArg::none(), - const RooCmdArg& arg4=RooCmdArg::none(), const RooCmdArg& arg5=RooCmdArg::none(), - const RooCmdArg& arg6=RooCmdArg::none(), const RooCmdArg& arg7=RooCmdArg::none(), - const RooCmdArg& arg8=RooCmdArg::none() ) const; + virtual RooFit::OwningPtr GetAsDataHist(const RooCmdArg & arg1, + const RooCmdArg& arg2={}, const RooCmdArg& arg3={}, + const RooCmdArg& arg4={}, const RooCmdArg& arg5={}, + const RooCmdArg& arg6={}, const RooCmdArg& arg7={}, + const RooCmdArg& arg8={} ) const; /// Get a clone of the markov chain on which this interval is based /// as a sparse histogram. You own the returned THnSparse* @@ -102,7 +102,7 @@ namespace RooStats { /// get a clone of the weight variable virtual RooRealVar* GetWeightVar() const - { return (RooRealVar*)fWeight->Clone(); } + { return static_cast(fChain->weightVar()->Clone()); } ~MarkovChain() override { @@ -116,9 +116,8 @@ namespace RooStats { RooArgSet * fDataEntry; RooDataSet* fChain; RooRealVar* fNLL; - RooRealVar* fWeight; - ClassDefOverride(MarkovChain,1); + ClassDefOverride(MarkovChain,2); }; } diff --git a/roofit/roostats/inc/RooStats/MaxLikelihoodEstimateTestStat.h b/roofit/roostats/inc/RooStats/MaxLikelihoodEstimateTestStat.h index 323b5f6ee5f28..cf7961fd673b5 100644 --- a/roofit/roostats/inc/RooStats/MaxLikelihoodEstimateTestStat.h +++ b/roofit/roostats/inc/RooStats/MaxLikelihoodEstimateTestStat.h @@ -78,11 +78,11 @@ class MaxLikelihoodEstimateTestStat: public TestStatistic { return ret; */ - RooArgSet* allParams = fPdf->getParameters(data); - RooStats::RemoveConstantParameters(allParams); + std::unique_ptr allParams{fPdf->getParameters(data)}; + RooStats::RemoveConstantParameters(&*allParams); // need to call constrain for RooSimultaneous until stripDisconnected problem fixed - RooAbsReal* nll = fPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams),RooFit::ConditionalObservables(fConditionalObs)); + std::unique_ptr nll{fPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams),RooFit::ConditionalObservables(fConditionalObs))}; //RooAbsReal* nll = fPdf->createNLL(data, RooFit::CloneData(false)); @@ -91,9 +91,6 @@ class MaxLikelihoodEstimateTestStat: public TestStatistic { // RooArgSet* vars = profile->getVariables(); // RooMsgService::instance().setGlobalKillBelow(msglevel); // double ret = vars->getRealValue(fParameter->GetName()); - // delete vars; - // delete nll; - // delete profile; // return ret; @@ -123,7 +120,6 @@ class MaxLikelihoodEstimateTestStat: public TestStatistic { //allParams->Print("V"); RooMsgService::instance().setGlobalKillBelow(msglevel); - delete nll; if (status != 0) return -1; return fParameter->getVal(); diff --git a/roofit/roostats/inc/RooStats/ModelConfig.h b/roofit/roostats/inc/RooStats/ModelConfig.h index 7d48f830e2480..b27c17f9e53b6 100644 --- a/roofit/roostats/inc/RooStats/ModelConfig.h +++ b/roofit/roostats/inc/RooStats/ModelConfig.h @@ -1,312 +1 @@ -// @(#)root/roostats:$Id$ -// Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss -/************************************************************************* - * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOSTATS_ModelConfig -#define ROOSTATS_ModelConfig - - -#include "RooAbsPdf.h" - -#include "RooAbsData.h" - -#include "RooArgSet.h" - -#include "RooWorkspaceHandle.h" - -#include "TRef.h" - -#include - - -namespace RooStats { - -class ModelConfig final : public TNamed, public RooWorkspaceHandle { - -public: - - ModelConfig(RooWorkspace * ws = nullptr) : - TNamed() - { - if(ws) SetWS(*ws); - } - - ModelConfig(const char* name, RooWorkspace *ws = nullptr) : - TNamed(name, name) - { - if(ws) SetWS(*ws); - } - - ModelConfig(const char* name, const char* title, RooWorkspace *ws = nullptr) : - TNamed(name, title) - { - if(ws) SetWS(*ws); - } - - - /// clone - ModelConfig * Clone(const char * name = "") const override { - ModelConfig * mc = new ModelConfig(*this); - if(strcmp(name,"")==0) - mc->SetName(this->GetName()); - else - mc->SetName(name); - return mc; - } - - /// Set a workspace that owns all the necessary components for the analysis. - void SetWS(RooWorkspace & ws) override; - //// alias for SetWS(...) - virtual void SetWorkspace(RooWorkspace & ws) { SetWS(ws); } - - /// Remove the existing reference to a workspace and replace it with this new one. - void ReplaceWS(RooWorkspace *ws) override { - fRefWS = nullptr; - SetWS(*ws); - } - - /// Set the proto DataSet, add to the workspace if not already there - virtual void SetProtoData(RooAbsData & data) { - ImportDataInWS(data); - SetProtoData( data.GetName() ); - } - - /// Set the Pdf, add to the workspace if not already there - virtual void SetPdf(const RooAbsPdf& pdf) { - ImportPdfInWS(pdf); - SetPdf( pdf.GetName() ); - } - - /// Set the Prior Pdf, add to the workspace if not already there - virtual void SetPriorPdf(const RooAbsPdf& pdf) { - ImportPdfInWS(pdf); - SetPriorPdf( pdf.GetName() ); - } - - /// Specify parameters of the PDF. - virtual void SetParameters(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetParameters")) return ; - fPOIName=std::string(GetName()) + "_POI"; - DefineSetInWS(fPOIName.c_str(), set); - } - - /// Specify parameters of interest. - virtual void SetParametersOfInterest(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetParametersOfInterest")) return ; - SetParameters(set); - } - - /// Specify parameters - /// using a list of comma-separated list of arguments already in the workspace. - virtual void SetParameters(const char *argList) { - if(!GetWS()) return; - SetParameters(GetWS()->argSet(argList)); - } - - /// Specify parameters of interest - /// using a comma-separated list of arguments already in the workspace. - virtual void SetParametersOfInterest(const char *argList) { - SetParameters(argList); - } - - /// Specify the nuisance parameters (parameters that are not POI). - virtual void SetNuisanceParameters(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetNuisanceParameters")) return ; - fNuisParamsName=std::string(GetName()) + "_NuisParams"; - DefineSetInWS(fNuisParamsName.c_str(), set); - } - - /// Specify the nuisance parameters - /// using a comma-separated list of arguments already in the workspace. - virtual void SetNuisanceParameters(const char *argList) { - if(!GetWS()) return; - SetNuisanceParameters(GetWS()->argSet(argList)); - } - - /// Specify the constraint parameters - virtual void SetConstraintParameters(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetConstainedParameters")) return ; - fConstrParamsName=std::string(GetName()) + "_ConstrainedParams"; - DefineSetInWS(fConstrParamsName.c_str(), set); - } - /// Specify the constraint parameters - /// through a comma-separated list of arguments already in the workspace. - virtual void SetConstraintParameters(const char *argList) { - if(!GetWS()) return; - SetConstraintParameters(GetWS()->argSet(argList)); - } - - /// Specify the observables. - virtual void SetObservables(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetObservables")) return ; - fObservablesName=std::string(GetName()) + "_Observables"; - DefineSetInWS(fObservablesName.c_str(), set); - } - /// specify the observables - /// through a comma-separated list of arguments already in the workspace. - virtual void SetObservables(const char *argList) { - if(!GetWS()) return; - SetObservables(GetWS()->argSet(argList)); - } - - /// Specify the conditional observables. - virtual void SetConditionalObservables(const RooArgSet& set) { - if (!SetHasOnlyParameters(set,"ModelConfig::SetConditionalObservables")) return ; - fConditionalObsName=std::string(GetName()) + "_ConditionalObservables"; - DefineSetInWS(fConditionalObsName.c_str(), set); - } - /// Specify the conditional observables - /// through a comma-separated list of arguments already in the workspace. - virtual void SetConditionalObservables(const char *argList) { - if(!GetWS()) return; - SetConditionalObservables(GetWS()->argSet(argList)); - } - - /// Specify the global observables. - virtual void SetGlobalObservables(const RooArgSet& set) { - - if (!SetHasOnlyParameters(set,"ModelConfig::SetGlobalObservables")) return ; - - // make global observables constant - for (auto *arg : set){ - arg->setAttribute("Constant", true); - } - - fGlobalObsName=std::string(GetName()) + "_GlobalObservables"; - DefineSetInWS(fGlobalObsName.c_str(), set); - } - /// Specify the global observables - /// through a comma-separated list of arguments already in the workspace. - virtual void SetGlobalObservables(const char *argList) { - if(!GetWS()) return; - SetGlobalObservables(GetWS()->argSet(argList)); - } - - /// Set parameter values for a particular hypothesis if using a common PDF - /// by saving a snapshot in the workspace. - virtual void SetSnapshot(const RooArgSet& set); - - /// Specify the name of the PDF in the workspace to be used. - virtual void SetPdf(const char* name) { - if (! GetWS() ) return; - - if(GetWS()->pdf(name)) - fPdfName = name; - else - coutE(ObjectHandling) << "pdf "<pdf(name)) - fPriorPdfName = name; - else - coutE(ObjectHandling) << "pdf "<data(name)) - fProtoDataName = name; - else - coutE(ObjectHandling) << "dataset "<pdf(fPdfName.c_str()) : nullptr; } - - /// get RooArgSet containing the parameter of interest (return nullptr if not existing) - const RooArgSet * GetParametersOfInterest() const { return (GetWS()) ? GetWS()->set(fPOIName.c_str()) : nullptr; } - - /// get RooArgSet containing the nuisance parameters (return nullptr if not existing) - const RooArgSet * GetNuisanceParameters() const { return (GetWS()) ? GetWS()->set(fNuisParamsName.c_str()) : nullptr; } - - /// get RooArgSet containing the constraint parameters (return nullptr if not existing) - const RooArgSet * GetConstraintParameters() const { return (GetWS()) ? GetWS()->set(fConstrParamsName.c_str()) : nullptr; } - - /// get parameters prior pdf (return nullptr if not existing) - RooAbsPdf * GetPriorPdf() const { return (GetWS()) ? GetWS()->pdf(fPriorPdfName.c_str()) : nullptr; } - - /// get RooArgSet for observables (return nullptr if not existing) - const RooArgSet * GetObservables() const { return (GetWS()) ? GetWS()->set(fObservablesName.c_str()) : nullptr; } - - /// get RooArgSet for conditional observables (return nullptr if not existing) - const RooArgSet * GetConditionalObservables() const { return (GetWS()) ? GetWS()->set(fConditionalObsName.c_str()) : nullptr; } - - /// get RooArgSet for global observables (return nullptr if not existing) - const RooArgSet * GetGlobalObservables() const { return (GetWS()) ? GetWS()->set(fGlobalObsName.c_str()) : nullptr; } - - /// get Proto data set (return nullptr if not existing) - RooAbsData * GetProtoData() const { return (GetWS()) ? GetWS()->data(fProtoDataName.c_str()) : nullptr; } - - /// get RooArgSet for parameters for a particular hypothesis (return nullptr if not existing) - const RooArgSet * GetSnapshot() const; - - void LoadSnapshot() const; - - RooWorkspace * GetWS() const override; - /// alias for GetWS() - RooWorkspace * GetWorkspace() const { return GetWS(); } - - void GuessObsAndNuisance(const RooAbsData& data, bool printModelConfig = true); - - /// overload the print method - void Print(Option_t* option = "") const override; - -protected: - - /// helper function to check that content of a given set is exclusively parameters - bool SetHasOnlyParameters(const RooArgSet& set, const char* errorMsgPrefix=nullptr) ; - - /// helper functions to define a set in the WS - void DefineSetInWS(const char* name, const RooArgSet& set); - - /// internal function to import Pdf in WS - void ImportPdfInWS(const RooAbsPdf & pdf); - - /// internal function to import data in WS - void ImportDataInWS(RooAbsData & data); - - TRef fRefWS; ///< WS reference used in the file - - std::string fWSName; ///< name of the WS - - std::string fPdfName; ///< name of PDF in workspace - std::string fDataName; ///< name of data set in workspace - std::string fPOIName; ///< name for RooArgSet specifying parameters of interest - - std::string fNuisParamsName; ///< name for RooArgSet specifying nuisance parameters - std::string fConstrParamsName; ///< name for RooArgSet specifying constrained parameters - std::string fPriorPdfName; ///< name for RooAbsPdf specifying a prior on the parameters - - std::string fConditionalObsName; ///< name for RooArgSet specifying conditional observables - std::string fGlobalObsName; ///< name for RooArgSet specifying global observables - std::string fProtoDataName; ///< name for RooArgSet specifying dataset that should be used as proto-data - - std::string fSnapshotName; ///< name for RooArgSet that specifies a particular hypothesis - - std::string fObservablesName; ///< name for RooArgSet specifying observable parameters. - - ClassDefOverride(ModelConfig,5) ///< A class that holds configuration information for a model using a workspace as a store - -}; - -} // end namespace RooStats - - -#endif +#include diff --git a/roofit/roostats/inc/RooStats/NeymanConstruction.h b/roofit/roostats/inc/RooStats/NeymanConstruction.h index 2d0b17910df89..9e2ca07762c83 100644 --- a/roofit/roostats/inc/RooStats/NeymanConstruction.h +++ b/roofit/roostats/inc/RooStats/NeymanConstruction.h @@ -77,21 +77,6 @@ namespace RooStats { /// Set the DataSet void SetData(RooAbsData& data) override { fData = data; } - /// Set the Pdf, add to the workspace if not already there - virtual void SetPdf(RooAbsPdf& /*pdf*/) { - std::cout << "DEPRECATED, use ModelConfig"< fCache; /// the cached proposal data set RooArgSet fMaster; /// pointers to master variables needed for updates bool fOwnsPdf; /// whether we own the proposal density function //bool fIsAlwaysSymmetric; // does Q(x1 | x2) == Q(x2 | x1) for all x1, x2 @@ -116,7 +114,7 @@ namespace RooStats { virtual bool Equals(RooArgSet& x1, RooArgSet& x2); /// Interface for tools setting limits (producing confidence intervals) - ClassDefOverride(PdfProposal,1) + ClassDefOverride(PdfProposal,2); }; } diff --git a/roofit/roostats/inc/RooStats/ProfileLikelihoodCalculator.h b/roofit/roostats/inc/RooStats/ProfileLikelihoodCalculator.h index 6ace8c65ee1d6..26fbbf994b346 100644 --- a/roofit/roostats/inc/RooStats/ProfileLikelihoodCalculator.h +++ b/roofit/roostats/inc/RooStats/ProfileLikelihoodCalculator.h @@ -61,17 +61,17 @@ namespace RooStats { void DoReset() const; /// perform a global fit - RooAbsReal * DoGlobalFit() const; + RooFit::OwningPtr DoGlobalFit() const; /// minimize likelihood - static RooFitResult * DoMinimizeNLL(RooAbsReal * nll); + static RooFit::OwningPtr DoMinimizeNLL(RooAbsReal * nll); - mutable RooFitResult * fFitResult; //// internal result of global fit + mutable std::unique_ptr fFitResult; //// internal result of global fit mutable bool fGlobalFitDone; ///< flag to control if a global fit has been done - ClassDefOverride(ProfileLikelihoodCalculator,2) // A concrete implementation of CombinedCalculator that uses the ProfileLikelihood ratio. + ClassDefOverride(ProfileLikelihoodCalculator,3) // A concrete implementation of CombinedCalculator that uses the ProfileLikelihood ratio. }; } diff --git a/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h b/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h index a88a98224f7d2..8d669585c8449 100644 --- a/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h +++ b/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h @@ -35,7 +35,6 @@ namespace RooStats { ProfileLikelihoodTestStat() { // Proof constructor. Do not use. fPdf = nullptr; - fNll = nullptr; fCachedBestFitParams = nullptr; fLastData = nullptr; fLimitType = twoSided; @@ -54,7 +53,6 @@ namespace RooStats { ProfileLikelihoodTestStat(RooAbsPdf& pdf) { fPdf = &pdf; - fNll = nullptr; fCachedBestFitParams = nullptr; fLastData = nullptr; fLimitType = twoSided; @@ -73,7 +71,6 @@ namespace RooStats { } ~ProfileLikelihoodTestStat() override { - if(fNll) delete fNll; if(fCachedBestFitParams) delete fCachedBestFitParams; if(fDetailedOutput) delete fDetailedOutput; } @@ -134,12 +131,12 @@ namespace RooStats { private: - RooFitResult* GetMinNLL(); + std::unique_ptr GetMinNLL(); private: RooAbsPdf* fPdf; - RooAbsReal* fNll; //! + std::unique_ptr fNll; //! const RooArgSet* fCachedBestFitParams; RooAbsData* fLastData; // double fLastMLE; diff --git a/roofit/roostats/inc/RooStats/RooStatsUtils.h b/roofit/roostats/inc/RooStats/RooStatsUtils.h index be38b2e7b8d3f..56df83cac0c86 100644 --- a/roofit/roostats/inc/RooStats/RooStatsUtils.h +++ b/roofit/roostats/inc/RooStats/RooStatsUtils.h @@ -57,7 +57,7 @@ namespace RooStats { /// Compute the Asimov Median significance for a Poisson process /// with s = expected number of signal events, b = expected number of background events - /// and optionally sigma_b = expected uncertainty of backgorund events + /// and optionally sigma_b = expected uncertainty of background events double AsimovSignificance(double s, double b, double sigma_b = 0.0 ); inline void SetParameters(const RooArgSet* desiredVals, RooArgSet* paramsToChange){ @@ -83,7 +83,7 @@ namespace RooStats { /// utility function to set all variable constant in a collection /// (from G. Petrucciani) inline bool SetAllConstant(const RooAbsCollection &coll, bool constant = true) { - bool changed = false; + bool changed = false; for (auto *v : dynamic_range_cast(coll)) { if (v && (v->isConstant() != constant)) { changed = true; diff --git a/roofit/roostats/inc/RooStats/SPlot.h b/roofit/roostats/inc/RooStats/SPlot.h index 87e6c73fd83ec..70a6305e6c3b4 100644 --- a/roofit/roostats/inc/RooStats/SPlot.h +++ b/roofit/roostats/inc/RooStats/SPlot.h @@ -41,10 +41,10 @@ namespace RooStats{ SPlot(const char* name, const char* title,RooDataSet& data, RooAbsPdf* pdf, const RooArgList &yieldsList,const RooArgSet &projDeps=RooArgSet(), bool useWeights=true, bool copyDataSet = false, const char* newName = "", - const RooCmdArg& fitToarg5=RooCmdArg::none(), - const RooCmdArg& fitToarg6=RooCmdArg::none(), - const RooCmdArg& fitToarg7=RooCmdArg::none(), - const RooCmdArg& fitToarg8=RooCmdArg::none()); + const RooCmdArg& fitToarg5={}, + const RooCmdArg& fitToarg6={}, + const RooCmdArg& fitToarg7={}, + const RooCmdArg& fitToarg8={}); RooDataSet* SetSData(RooDataSet* data); @@ -56,10 +56,10 @@ namespace RooStats{ void AddSWeight(RooAbsPdf* pdf, const RooArgList &yieldsTmp, const RooArgSet &projDeps=RooArgSet(), bool includeWeights=true, - const RooCmdArg& fitToarg5=RooCmdArg::none(), - const RooCmdArg& fitToarg6=RooCmdArg::none(), - const RooCmdArg& fitToarg7=RooCmdArg::none(), - const RooCmdArg& fitToarg8=RooCmdArg::none()); + const RooCmdArg& fitToarg5={}, + const RooCmdArg& fitToarg6={}, + const RooCmdArg& fitToarg7={}, + const RooCmdArg& fitToarg8={}); double GetSumOfEventSWeight(Int_t numEvent) const; diff --git a/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h b/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h index 5471136cb4ed3..ecb8e9307bb57 100644 --- a/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h +++ b/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h @@ -34,8 +34,6 @@ namespace RooStats { fNullParameters = nullptr; fAltParameters = nullptr; fReuseNll=false ; - fNllNull=nullptr ; - fNllAlt=nullptr ; } /// Takes null and alternate parameters from PDF. Can be overridden. @@ -48,20 +46,16 @@ namespace RooStats { fNullPdf = &nullPdf; fAltPdf = &altPdf; - RooArgSet * allNullVars = fNullPdf->getVariables(); + std::unique_ptr allNullVars{fNullPdf->getVariables()}; fNullParameters = (RooArgSet*) allNullVars->snapshot(); - delete allNullVars; - RooArgSet * allAltVars = fAltPdf->getVariables(); + std::unique_ptr allAltVars{fAltPdf->getVariables()}; fAltParameters = (RooArgSet*) allAltVars->snapshot(); - delete allAltVars; fDetailedOutputEnabled = false; fDetailedOutput = nullptr; fReuseNll=false ; - fNllNull=nullptr ; - fNllAlt=nullptr ; } /// Takes null and alternate parameters from values in nullParameters @@ -84,15 +78,11 @@ namespace RooStats { fDetailedOutput = nullptr; fReuseNll=false ; - fNllNull=nullptr ; - fNllAlt=nullptr ; } ~SimpleLikelihoodRatioTestStat() override { if (fNullParameters) delete fNullParameters; if (fAltParameters) delete fAltParameters; - if (fNllNull) delete fNllNull ; - if (fNllAlt) delete fNllAlt ; if (fDetailedOutput) delete fDetailedOutput; } @@ -160,8 +150,8 @@ namespace RooStats { bool fDetailedOutputEnabled; RooArgSet* fDetailedOutput; /// fNllNull; /// fNllAlt; ///= 1 ) p = fNullDensities[0]; + if( p == nullptr && !fNullDensities.empty() ) p = fNullDensities[0]; if( s == nullptr ) s = fParametersForTestStat.get(); if( s ) s = (const RooArgSet*)s->snapshot(); fNullDensities.push_back( p ); fNullSnapshots.push_back( s ); - fNullNLLs.push_back( nullptr ); + fNullNLLs.emplace_back( nullptr ); ClearCache(); } /// overwrite from ToyMCSampler @@ -190,8 +190,8 @@ class ToyMCImportanceSampler: public ToyMCSampler { toysStrategies fToysStrategy; - mutable std::vector fNullNLLs; /// fImpNLLs; ///> fNullNLLs; ///> fImpNLLs; ///(); + nullpoi.snapshot(*params); + fParametersForTestStat = std::move(params); } void SetPdf(RooAbsPdf& pdf) override { fPdf = &pdf; ClearCache(); } @@ -233,7 +235,7 @@ class ToyMCSampler: public TestStatSampler { const RooArgList* EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi, DetailedOutputAggregator& detOutAgg); /// helper for GenerateToyData - RooAbsData* Generate(RooAbsPdf &pdf, RooArgSet &observables, const RooDataSet *protoData=nullptr, int forceEvents=0) const; + std::unique_ptr Generate(RooAbsPdf &pdf, RooArgSet &observables, const RooDataSet *protoData=nullptr, int forceEvents=0) const; /// helper method for clearing the cache virtual void ClearCache(); diff --git a/roofit/roostats/src/AsymptoticCalculator.cxx b/roofit/roostats/src/AsymptoticCalculator.cxx index 59fb1819ba540..552093165f9a9 100644 --- a/roofit/roostats/src/AsymptoticCalculator.cxx +++ b/roofit/roostats/src/AsymptoticCalculator.cxx @@ -94,11 +94,11 @@ AsymptoticCalculator::AsymptoticCalculator( RooAbsData &data, const ModelConfig &altModel, const ModelConfig &nullModel, bool nominalAsimov) : - HypoTestCalculatorGeneric(data, altModel, nullModel, 0), + HypoTestCalculatorGeneric(data, altModel, nullModel, nullptr), fOneSided(false), fOneSidedDiscovery(false), fNominalAsimov(nominalAsimov), fUseQTilde(-1), fNLLObs(0), fNLLAsimov(0), - fAsimovData(0) + fAsimovData(nullptr) { if (!Initialize()) return; @@ -176,8 +176,8 @@ bool AsymptoticCalculator::Initialize() const { // keep snapshot for the initial parameter values (need for nominal Asimov) RooArgSet nominalParams; - RooArgSet * allParams = nullPdf->getParameters(data); - RemoveConstantParameters(allParams); + std::unique_ptr allParams{nullPdf->getParameters(data)}; + RemoveConstantParameters(&*allParams); if (fNominalAsimov) { allParams->snapshot(nominalParams); } @@ -188,7 +188,7 @@ bool AsymptoticCalculator::Initialize() const { // evaluate the unconditional nll for the full model on the observed data if (verbose >= 0) oocoutP(nullptr,Eval) << "AsymptoticCalculator::Initialize - Find best unconditional NLL on observed data" << endl; - fNLLObs = EvaluateNLL( *nullPdf, data, GetNullModel()->GetConditionalObservables(),GetNullModel()->GetGlobalObservables()); + fNLLObs = EvaluateNLL(*GetNullModel(), data); // fill also snapshot of best poi poi->snapshot(fBestFitPoi); RooRealVar * muBest = dynamic_cast(fBestFitPoi.first()); @@ -197,7 +197,6 @@ bool AsymptoticCalculator::Initialize() const { oocoutP(nullptr,Eval) << "Best fitted POI value = " << muBest->getVal() << " +/- " << muBest->getError() << std::endl; // keep snapshot of all best fit parameters allParams->snapshot(fBestFitParams); - delete allParams; // compute Asimov data set for the background (alt poi ) value const RooArgSet * altSnapshot = GetAlternateModel()->GetSnapshot(); @@ -215,7 +214,7 @@ bool AsymptoticCalculator::Initialize() const { // This number will be used for making the Asimov data set so it will be more consistent with the // observed data int prevBins = 0; - RooRealVar * xobs = 0; + RooRealVar * xobs = nullptr; if (GetNullModel()->GetObservables() && GetNullModel()->GetObservables()->size() == 1 ) { xobs = (RooRealVar*) (GetNullModel()->GetObservables())->first(); if (data.IsA() == RooDataHist::Class() ) { @@ -270,7 +269,7 @@ bool AsymptoticCalculator::Initialize() const { oocoutP(nullptr,Eval) << "AsymptoticCalculator::Initialize Find best conditional NLL on ASIMOV data set for given alt POI ( " << muAlt->GetName() << " ) = " << muAlt->getVal() << std::endl; - fNLLAsimov = EvaluateNLL( *nullPdf, *fAsimovData, GetNullModel()->GetConditionalObservables(), GetNullModel()->GetGlobalObservables(), &poiAlt ); + fNLLAsimov = EvaluateNLL(*GetNullModel(), *fAsimovData, &poiAlt ); // for unconditional fit //fNLLAsimov = EvaluateNLL( *nullPdf, *fAsimovData); //poi->Print("v"); @@ -287,29 +286,25 @@ bool AsymptoticCalculator::Initialize() const { //////////////////////////////////////////////////////////////////////////////// -double AsymptoticCalculator::EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, const RooArgSet * condObs, const RooArgSet * globObs, const RooArgSet *poiSet) { +double AsymptoticCalculator::EvaluateNLL(RooStats::ModelConfig const& modelConfig, RooAbsData& data, const RooArgSet *poiSet) +{ int verbose = fgPrintLevel; + RooAbsPdf &pdf = *modelConfig.GetPdf(); RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow(); if (verbose < 2) RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL); - RooArgSet* allParams = pdf.getParameters(data); - RooStats::RemoveConstantParameters(allParams); + std::unique_ptr allParams{pdf.getParameters(data)}; + RooStats::RemoveConstantParameters(&*allParams); // add constraint terms for all non-constant parameters - RooArgSet conditionalObs; - if (condObs) conditionalObs.add(*condObs); - RooArgSet globalObs; - if (globObs) globalObs.add(*globObs); - // need to call constrain for RooSimultaneous until stripDisconnected problem fixed auto& config = GetGlobalRooStatsConfig(); - RooAbsReal* nll = pdf.createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams),RooFit::ConditionalObservables(conditionalObs), RooFit::GlobalObservables(globalObs), - RooFit::Offset(config.useLikelihoodOffset)); + std::unique_ptr nll{modelConfig.createNLL(data, RooFit::Constrain(*allParams), RooFit::Offset(config.useLikelihoodOffset))}; - RooArgSet* attachedSet = nll->getVariables(); + std::unique_ptr attachedSet{nll->getVariables()}; // if poi are specified - do a conditional fit RooArgSet paramsSetConstant; @@ -351,7 +346,6 @@ double AsymptoticCalculator::EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, co //check if needed to skip the fit RooArgSet nllParams(*attachedSet); RooStats::RemoveConstantParameters(&nllParams); - delete attachedSet; bool skipFit = (nllParams.empty()); if (skipFit) @@ -408,11 +402,11 @@ double AsymptoticCalculator::EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, co } } - RooFitResult * result = 0; + std::unique_ptr result; // ignore errors in Hesse or in Improve and also when matrix was made pos def (status returned = 1) if (status >= 0) { - result = minim.save(); + result = std::unique_ptr{minim.save()}; } if (result){ if (!RooStats::IsNLLOffset() ) @@ -431,9 +425,6 @@ double AsymptoticCalculator::EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, co } minim.optimizeConst(false); - if (result) delete result; - - } double muTest = 0; @@ -457,9 +448,6 @@ double AsymptoticCalculator::EvaluateNLL(RooAbsPdf & pdf, RooAbsData& data, co if (verbose < 2) RooMsgService::instance().setGlobalKillBelow(msglevel); - delete allParams; - delete nll; - return val; } @@ -479,13 +467,13 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { if (!fIsInitialized) { if (!Initialize() ) { oocoutE(nullptr,InputArguments) << "AsymptoticCalculator::GetHypoTest - Error initializing Asymptotic calculator - return nullptr result " << endl; - return 0; + return nullptr; } } if (!fAsimovData) { oocoutE(nullptr,InputArguments) << "AsymptoticCalculator::GetHypoTest - Asimov data set has not been generated - return nullptr result " << endl; - return 0; + return nullptr; } assert(GetNullModel() ); @@ -507,9 +495,8 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { oocoutW(nullptr,InputArguments) << "AsymptoticCalculator::GetHypoTest: snapshot has more than one POI - assume as POI first parameter " << std::endl; } - RooArgSet * allParams = nullPdf->getParameters(*GetData() ); + std::unique_ptr allParams{nullPdf->getParameters(*GetData() )}; allParams->assign(fBestFitParams); - delete allParams; // set the one-side condition // (this works when we have only one params of interest @@ -527,7 +514,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { } // evaluate the conditional NLL on the observed data for the snapshot value - double condNLL = EvaluateNLL( *nullPdf, const_cast(*GetData()), GetNullModel()->GetConditionalObservables(), GetNullModel()->GetGlobalObservables(), &poiTest); + double condNLL = EvaluateNLL(*GetNullModel(), const_cast(*GetData()), &poiTest); double qmu = 2.*(condNLL - fNLLObs); @@ -549,7 +536,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { << std::endl; - double nll = EvaluateNLL( *nullPdf, const_cast(*GetData()),GetNullModel()->GetConditionalObservables(),GetNullModel()->GetGlobalObservables()); + double nll = EvaluateNLL(*GetNullModel(), const_cast(*GetData())); if (nll < fNLLObs || (TMath::IsNaN(fNLLObs) && !TMath::IsNaN(nll) ) ) { oocoutW(nullptr,Minimization) << "AsymptoticCalculator: Found a better unconditional minimum " @@ -611,7 +598,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { if (verbose > 0) oocoutP(nullptr,Eval) << "AsymptoticCalculator::GetHypoTest -- Find best conditional NLL on ASIMOV data set .... " << std::endl; - double condNLL_A = EvaluateNLL( *nullPdf, *fAsimovData, GetNullModel()->GetConditionalObservables(), GetNullModel()->GetGlobalObservables(), &poiTest); + double condNLL_A = EvaluateNLL(*GetNullModel(), *fAsimovData, &poiTest); double qmu_A = 2.*(condNLL_A - fNLLAsimov ); @@ -629,7 +616,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { << std::endl; - double nll = EvaluateNLL( *nullPdf, *fAsimovData, GetNullModel()->GetConditionalObservables(), GetNullModel()->GetGlobalObservables() ); + double nll = EvaluateNLL(*GetNullModel(), *fAsimovData); if (nll < fNLLAsimov || (TMath::IsNaN(fNLLAsimov) && !TMath::IsNaN(nll) )) { oocoutW(nullptr,Minimization) << "AsymptoticCalculator: Found a better unconditional minimum for Asimov data set" @@ -683,7 +670,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const { RooRealVar * muAlt = dynamic_cast( GetAlternateModel()->GetSnapshot()->first() ); // null snapshot is value for which background is zero (for discovery) //RooRealVar * muNull = dynamic_cast( GetNullModel()->GetSnapshot()->first() ); - assert(muAlt != 0 ); + assert(muAlt != nullptr ); if (muTest->getMin() == muAlt->getVal() ) { fUseQTilde = 1; oocoutI(nullptr,InputArguments) << "Minimum of POI is " << muTest->getMin() << " corresponds to alt snapshot - using qtilde asymptotic formulae " << std::endl; @@ -930,13 +917,13 @@ bool AsymptoticCalculator::SetObsToExpected(RooProdPdf &prod, const RooArgSet &o bool ret = true; for (auto *a : prod.pdfList()) { if (!a->dependsOn(obs)) continue; - RooPoisson *pois = 0; - RooGaussian * gaus = 0; - if ((pois = dynamic_cast(a)) != 0) { + RooPoisson *pois = nullptr; + RooGaussian * gauss = nullptr; + if ((pois = dynamic_cast(a)) != nullptr) { ret &= SetObsToExpected(*pois, obs); pois->setNoRounding(true); //needed since expected value is not an integer - } else if ((gaus = dynamic_cast(a)) != 0) { - ret &= SetObsToExpected(*gaus, obs); + } else if ((gauss = dynamic_cast(a)) != nullptr) { + ret &= SetObsToExpected(*gauss, obs); } else { // should try to add also lognormal case ? RooProdPdf *subprod = dynamic_cast(a); @@ -966,40 +953,40 @@ bool AsymptoticCalculator::SetObsToExpected(RooProdPdf &prod, const RooArgSet &o bool AsymptoticCalculator::SetObsToExpected(RooAbsPdf &pdf, const RooArgSet &obs) { - RooRealVar *myobs = 0; - RooAbsReal *myexp = 0; + RooRealVar *myobs = nullptr; + RooAbsReal *myexp = nullptr; const char * pdfName = pdf.ClassName(); RooFIter iter(pdf.serverMIterator()); - for (RooAbsArg *a = iter.next(); a != 0; a = iter.next()) { + for (RooAbsArg *a = iter.next(); a != nullptr; a = iter.next()) { if (obs.contains(*a)) { - if (myobs != 0) { + if (myobs != nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : Has two observables ?? " << endl; return false; } myobs = dynamic_cast(a); - if (myobs == 0) { + if (myobs == nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : Observable is not a RooRealVar??" << endl; return false; } } else { if (!a->isConstant() ) { - if (myexp != 0) { + if (myexp != nullptr) { oocoutE(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : Has two non-const arguments " << endl; return false; } myexp = dynamic_cast(a); - if (myexp == 0) { + if (myexp == nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : Expected is not a RooAbsReal??" << endl; return false; } } } } - if (myobs == 0) { + if (myobs == nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : No observable?" << endl; return false; } - if (myexp == 0) { + if (myexp == nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::SetObsExpected( " << pdfName << " ) : No observable?" << endl; return false; } @@ -1021,25 +1008,25 @@ bool AsymptoticCalculator::SetObsToExpected(RooAbsPdf &pdf, const RooArgSet &obs RooAbsData * AsymptoticCalculator::GenerateCountingAsimovData(RooAbsPdf & pdf, const RooArgSet & observables, const RooRealVar & , RooCategory * channelCat) { RooArgSet obs(observables); RooProdPdf *prod = dynamic_cast(&pdf); - RooPoisson *pois = 0; - RooGaussian *gaus = 0; + RooPoisson *pois = nullptr; + RooGaussian *gauss = nullptr; if (fgPrintLevel > 1) std::cout << "generate counting Asimov data for pdf of type " << pdf.ClassName() << std::endl; bool r = false; - if (prod != 0) { + if (prod != nullptr) { r = SetObsToExpected(*prod, observables); - } else if ((pois = dynamic_cast(&pdf)) != 0) { + } else if ((pois = dynamic_cast(&pdf)) != nullptr) { r = SetObsToExpected(*pois, observables); // we need in this case to set Poisson to real values pois->setNoRounding(true); - } else if ((gaus = dynamic_cast(&pdf)) != 0) { - r = SetObsToExpected(*gaus, observables); + } else if ((gauss = dynamic_cast(&pdf)) != nullptr) { + r = SetObsToExpected(*gauss, observables); } else { oocoutE(nullptr,InputArguments) << "A counting model pdf must be either a RooProdPdf or a RooPoisson or a RooGaussian" << endl; } - if (!r) return 0; + if (!r) return nullptr; int icat = 0; if (channelCat) { icat = channelCat->getCurrentIndex(); @@ -1071,7 +1058,7 @@ RooAbsData * AsymptoticCalculator::GenerateAsimovDataSinglePdf(const RooAbsPdf & RooArgSet obsAndWeight(*obs); obsAndWeight.add(weightVar); - RooDataSet* asimovData = 0; + RooDataSet* asimovData = nullptr; if (channelCat) { int icat = channelCat->getCurrentIndex(); asimovData = new RooDataSet(std::string("AsimovData") + std::to_string(icat), @@ -1125,7 +1112,7 @@ RooAbsData * AsymptoticCalculator::GenerateAsimovDataSinglePdf(const RooAbsPdf & cout << "sum entries is nan"<(&pdf); if (!simPdf) { // generate data for non sim pdf - return GenerateAsimovDataSinglePdf( pdf, observables, *weightVar, 0); + return GenerateAsimovDataSinglePdf( pdf, observables, *weightVar, nullptr); } std::map asimovDataMap; @@ -1163,7 +1150,7 @@ RooAbsData * AsymptoticCalculator::GenerateAsimovData(const RooAbsPdf & pdf, con //iFrame++; // Get pdf associated with state from simpdf RooAbsPdf* pdftmp = simPdf->getPdf(channelCat.getCurrentLabel()) ; - assert(pdftmp != 0); + assert(pdftmp != nullptr); if (printLevel > 1) { @@ -1175,7 +1162,7 @@ RooAbsData * AsymptoticCalculator::GenerateAsimovData(const RooAbsPdf & pdf, con //cout << "expected events " << pdftmp->expectedEvents(*obstmp) << endl; if (!dataSinglePdf) { oocoutE(nullptr,Generation) << "Error generating an Asimov data set for pdf " << pdftmp->GetName() << endl; - return 0; + return nullptr; } if (asimovDataMap.count(string(channelCat.getCurrentLabel())) != 0) { @@ -1250,7 +1237,7 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(RooAbsData & realData, const M // Do we have free parameters anyway that need fitting? std::unique_ptr params(model.GetPdf()->getParameters(realData)); for (auto const *rrv : dynamic_range_cast(*params)) { - if ( rrv != 0 && rrv->isConstant() == false ) { hasFloatParams = true; break; } + if ( rrv != nullptr && rrv->isConstant() == false ) { hasFloatParams = true; break; } } } if (hasFloatParams) { @@ -1311,8 +1298,8 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(RooAbsData & realData, const M SetAllConstant(paramsSetConstant, false); - RooArgSet * allParams = model.GetPdf()->getParameters(realData); - RooStats::RemoveConstantParameters( allParams ); + std::unique_ptr allParams{model.GetPdf()->getParameters(realData)}; + RooStats::RemoveConstantParameters( &*allParams ); // if a RooArgSet of poi is passed , different poi will be used for generating the Asimov data set if (genPoiValues) { @@ -1321,17 +1308,12 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(RooAbsData & realData, const M // now do the actual generation of the AsimovData Set // no need to pass parameters values since we have set them before - RooAbsData * asimovData = MakeAsimovData(model, *allParams, asimovGlobObs); - - delete allParams; - - return asimovData; - + return MakeAsimovData(model, *allParams, asimovGlobObs); } //////////////////////////////////////////////////////////////////////////////// /// \param model ModelConfig that contains the model pdf and the model parameters -/// \param allParamValues The parameters fo the model will be set to the values given in this set +/// \param allParamValues The parameters of the model will be set to the values given in this set /// \param[out] asimovGlobObs Global observables set to values satisfying the constraints /// \return Asimov data set. The user takes ownership. /// @@ -1348,9 +1330,8 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(const ModelConfig & model, con // set the parameter values (do I need the poi to be constant ? ) // the nuisance parameter values could be set at their fitted value (the MLE) if (!allParamValues.empty()) { - RooArgSet * allVars = model.GetPdf()->getVariables(); + std::unique_ptr allVars{model.GetPdf()->getVariables()}; allVars->assign(allParamValues); - delete allVars; } @@ -1409,7 +1390,7 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(const ModelConfig & model, con // part 1: create the nuisance pdf std::unique_ptr nuispdf(RooStats::MakeNuisancePdf(model,"TempNuisPdf") ); - if (nuispdf.get() == 0) { + if (nuispdf.get() == nullptr) { oocoutF(nullptr,Generation) << "AsymptoticCalculator::MakeAsimovData: model has nuisance parameters and global obs but no nuisance pdf " << std::endl; } @@ -1496,16 +1477,16 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(const ModelConfig & model, con // need to treat the Gamma as a special case // the mode of the Gamma is (k-1)*theta where theta is the inverse of the rate parameter. // we assume that the global observable is defined as ngobs = k-1 and the theta parameter has the name theta otherwise we use other procedure which might be wrong - RooAbsReal * thetaGamma = 0; + RooAbsReal * thetaGamma = nullptr; if ( cClass == RooGamma::Class() ) { RooFIter itc(cterm->serverMIterator() ); - for (RooAbsArg *a2 = itc.next(); a2 != 0; a2 = itc.next()) { + for (RooAbsArg *a2 = itc.next(); a2 != nullptr; a2 = itc.next()) { if (TString(a2->GetName()).Contains("theta") ) { thetaGamma = dynamic_cast(a2); break; } } - if (thetaGamma == 0) { + if (thetaGamma == nullptr) { oocoutI(nullptr, Generation) << "AsymptoticCalculator::MakeAsimovData:constraint term " << cterm->GetName() << " is a Gamma distribution and no server named theta is found. Assume that the Gamma scale is 1 " << std::endl; @@ -1516,7 +1497,7 @@ RooAbsData * AsymptoticCalculator::MakeAsimovData(const ModelConfig & model, con } } RooFIter iter2(cterm->serverMIterator() ); - for (RooAbsArg *a2 = iter2.next(); a2 != 0; a2 = iter2.next()) { + for (RooAbsArg *a2 = iter2.next(); a2 != nullptr; a2 = iter2.next()) { RooAbsReal * rrv2 = dynamic_cast(a2); if (verbose > 2) std::cout << "Loop on constraint server term " << a2->GetName() << std::endl; if (rrv2 && rrv2->dependsOn(nuis) ) { diff --git a/roofit/roostats/src/BayesianCalculator.cxx b/roofit/roostats/src/BayesianCalculator.cxx index a1e80dd0a0642..5dc051b926a2b 100644 --- a/roofit/roostats/src/BayesianCalculator.cxx +++ b/roofit/roostats/src/BayesianCalculator.cxx @@ -28,7 +28,7 @@ computing the posterior. Alternatively, the class can be constructed by passing all the needed information (model pdf, prior pdf, parameter of interest, nuisance parameters, etc..) After configuring the calculator, one only needs to ask GetInterval(), which -will return an SimpleInterval object. By default the extrem of the integral are obtained by inverting directly the +will return an SimpleInterval object. By default the extreme of the integral are obtained by inverting directly the cumulative posterior distribution. By using the method SetScanOfPosterior(nbins) the interval is then obtained by scanning the posterior function in the given number of points. The first method is in general faster but it requires an integration one extra dimension ( in the poi in addition to the nuisance parameters), therefore in some case it can be @@ -105,7 +105,7 @@ namespace RooStats { struct LikelihoodFunction { - LikelihoodFunction(RooFunctor & f, RooFunctor * prior = 0, double offset = 0) : + LikelihoodFunction(RooFunctor & f, RooFunctor * prior = nullptr, double offset = 0) : fFunc(f), fPrior(prior), fOffset(offset), fMaxL(0) { fFunc.binding().resetNumCall(); @@ -164,10 +164,10 @@ class PosteriorCdfFunction : public ROOT::Math::IGenFunction { public: - PosteriorCdfFunction(RooAbsReal & nll, RooArgList & bindParams, RooAbsReal * prior = 0, const char * integType = 0, double nllMinimum = 0) : + PosteriorCdfFunction(RooAbsReal & nll, RooArgList & bindParams, RooAbsReal * prior = nullptr, const char * integType = nullptr, double nllMinimum = 0) : fFunctor(nll, bindParams, RooArgList() ), // functor fPriorFunc(nullptr), - fLikelihood(fFunctor, 0, nllMinimum), // integral of exp(-nll) function + fLikelihood(fFunctor, nullptr, nllMinimum), // integral of exp(-nll) function fIntegrator(ROOT::Math::IntegratorMultiDim::GetType(integType) ), // integrator fXmin(bindParams.getSize() ), // vector of parameters (min values) fXmax(bindParams.getSize() ), // vector of parameter (max values) @@ -349,11 +349,11 @@ class PosteriorFunction : public ROOT::Math::IGenFunction { public: - PosteriorFunction(RooAbsReal & nll, RooRealVar & poi, RooArgList & nuisParams, RooAbsReal * prior = 0, const char * integType = 0, double + PosteriorFunction(RooAbsReal & nll, RooRealVar & poi, RooArgList & nuisParams, RooAbsReal * prior = nullptr, const char * integType = nullptr, double norm = 1.0, double nllOffset = 0, int niter = 0) : fFunctor(nll, nuisParams, RooArgList() ), fPriorFunc(nullptr), - fLikelihood(fFunctor, 0, nllOffset), + fLikelihood(fFunctor, nullptr, nllOffset), fPoi(&poi), fXmin(nuisParams.getSize() ), fXmax(nuisParams.getSize() ), @@ -383,7 +383,7 @@ class PosteriorFunction : public ROOT::Math::IGenFunction { fIntegratorOneDim->Options().Print(ooccoutD(nullptr,NumIntegration) ); } else if (fXmin.size() > 1) { // multiDim case - fIntegratorMultiDim.reset(new ROOT::Math::IntegratorMultiDim(ROOT::Math::IntegratorMultiDim::GetType(integType) ) ); + fIntegratorMultiDim = std::make_unique(ROOT::Math::IntegratorMultiDim::GetType(integType)); fIntegratorMultiDim->SetFunction(fLikelihood, fXmin.size()); ROOT::Math::IntegratorMultiDimOptions opt = fIntegratorMultiDim->Options(); if (niter > 0) { @@ -399,7 +399,7 @@ class PosteriorFunction : public ROOT::Math::IGenFunction { ROOT::Math::IGenFunction * Clone() const override { assert(1); - return 0; // cannot clone this function for integrator + return nullptr; // cannot clone this function for integrator } double Error() const { return fError;} @@ -465,15 +465,14 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { public: - PosteriorFunctionFromToyMC(RooAbsReal & nll, RooAbsPdf & pdf, RooRealVar & poi, RooArgList & nuisParams, RooAbsReal * prior = 0, double + PosteriorFunctionFromToyMC(RooAbsReal & nll, RooAbsPdf & pdf, RooRealVar & poi, RooArgList & nuisParams, RooAbsReal * prior = nullptr, double nllOffset = 0, int niter = 0, bool redoToys = true ) : fFunctor(nll, nuisParams, RooArgList() ), fPriorFunc(nullptr), - fLikelihood(fFunctor, 0, nllOffset), + fLikelihood(fFunctor, nullptr, nllOffset), fPdf(&pdf), fPoi(&poi), fNuisParams(nuisParams), - fGenParams(0), fNumIterations(niter), fError(-1), fRedoToys(redoToys) @@ -489,7 +488,7 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { ooccoutI(nullptr,InputArguments) << "PosteriorFunctionFromToyMC::Pdf used for randomizing the nuisance is " << fPdf->GetName() << std::endl; // check that pdf contains the nuisance - RooArgSet * vars = fPdf->getVariables(); + std::unique_ptr vars{fPdf->getVariables()}; for (int i = 0; i < fNuisParams.getSize(); ++i) { if (!vars->find( fNuisParams[i].GetName() ) ) { ooccoutW(nullptr,InputArguments) << "Nuisance parameter " << fNuisParams[i].GetName() @@ -497,7 +496,6 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { << "they will be treated as constant " << std::endl; } } - delete vars; if (!fRedoToys) { ooccoutI(nullptr,InputArguments) << "PosteriorFunctionFromToyMC::Generate nuisance toys only one time (for all POI points)" << std::endl; @@ -505,13 +503,10 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { } } - ~PosteriorFunctionFromToyMC() override { if (fGenParams) delete fGenParams; } - // generate first n-samples of the nuisance parameters void GenerateToys() const { - if (fGenParams) delete fGenParams; - fGenParams = fPdf->generate(fNuisParams, fNumIterations); - if(fGenParams==0) { + fGenParams = std::unique_ptr{fPdf->generate(fNuisParams, fNumIterations)}; + if(fGenParams==nullptr) { ooccoutE(nullptr,InputArguments) << "PosteriorFunctionFromToyMC - failed to generate nuisance parameters" << std::endl; } } @@ -523,7 +518,7 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { //return new PosteriorFunctionFromToyMC(*this); // clone not implemented assert(1); - return 0; + return nullptr; } private: @@ -554,7 +549,7 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { const RooArgSet* genset=fGenParams->get(iter); RooAbsArg * arg = genset->find( fNuisParams[i].GetName() ); RooRealVar * var = dynamic_cast(arg); - assert(var != 0); + assert(var != nullptr); p[i] = var->getVal(); ((RooRealVar &) fNuisParams[i]).setVal(p[i]); } @@ -626,7 +621,7 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { mutable RooAbsPdf * fPdf; RooRealVar * fPoi; RooArgList fNuisParams; - mutable RooDataSet * fGenParams; + mutable std::unique_ptr fGenParams; int fNumIterations; mutable double fError; bool fRedoToys; // do toys every iteration @@ -641,12 +636,12 @@ class PosteriorFunctionFromToyMC : public ROOT::Math::IGenFunction { /// default constructor BayesianCalculator::BayesianCalculator() : - fData(0), - fPdf(0), - fPriorPdf(0), - fNuisancePdf(0), - fProductPdf (0), fLogLike(0), fLikelihood (0), fIntegratedLikelihood (0), fPosteriorPdf(0), - fPosteriorFunction(0), fApproxPosterior(0), + fData(nullptr), + fPdf(nullptr), + fPriorPdf(nullptr), + fNuisancePdf(nullptr), + fProductPdf (nullptr), fLikelihood (nullptr), fIntegratedLikelihood (nullptr), fPosteriorPdf(nullptr), + fPosteriorFunction(nullptr), fApproxPosterior(nullptr), fLower(0), fUpper(0), fNLLMin(0), fSize(0.05), fLeftSideFraction(0.5), @@ -672,9 +667,9 @@ BayesianCalculator::BayesianCalculator( /* const char* name, const char* title, fPdf(&pdf), fPOI(POI), fPriorPdf(&priorPdf), - fNuisancePdf(0), - fProductPdf (0), fLogLike(0), fLikelihood (0), fIntegratedLikelihood (0), fPosteriorPdf(0), - fPosteriorFunction(0), fApproxPosterior(0), + fNuisancePdf(nullptr), + fProductPdf (nullptr), fLikelihood (nullptr), fIntegratedLikelihood (nullptr), fPosteriorPdf(nullptr), + fPosteriorFunction(nullptr), fApproxPosterior(nullptr), fLower(0), fUpper(0), fNLLMin(0), fSize(0.05), fLeftSideFraction(0.5), @@ -698,9 +693,9 @@ BayesianCalculator::BayesianCalculator( RooAbsData& data, fData(&data), fPdf(model.GetPdf()), fPriorPdf( model.GetPriorPdf()), - fNuisancePdf(0), - fProductPdf (0), fLogLike(0), fLikelihood (0), fIntegratedLikelihood (0), fPosteriorPdf(0), - fPosteriorFunction(0), fApproxPosterior(0), + fNuisancePdf(nullptr), + fProductPdf (nullptr), fLikelihood (nullptr), fIntegratedLikelihood (nullptr), fPosteriorPdf(nullptr), + fPosteriorFunction(nullptr), fApproxPosterior(nullptr), fLower(0), fUpper(0), fNLLMin(0), fSize(0.05), fLeftSideFraction(0.5), @@ -724,18 +719,17 @@ BayesianCalculator::~BayesianCalculator() void BayesianCalculator::ClearAll() const { if (fProductPdf) delete fProductPdf; - if (fLogLike) delete fLogLike; + fLogLike.reset(); if (fLikelihood) delete fLikelihood; if (fIntegratedLikelihood) delete fIntegratedLikelihood; if (fPosteriorPdf) delete fPosteriorPdf; if (fPosteriorFunction) delete fPosteriorFunction; if (fApproxPosterior) delete fApproxPosterior; - fPosteriorPdf = 0; - fPosteriorFunction = 0; - fProductPdf = 0; - fLogLike = 0; - fLikelihood = 0; - fIntegratedLikelihood = 0; + fPosteriorPdf = nullptr; + fPosteriorFunction = nullptr; + fProductPdf = nullptr; + fLikelihood = nullptr; + fIntegratedLikelihood = nullptr; fLower = 0; fUpper = 0; fNLLMin = 0; @@ -787,26 +781,26 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const // run some sanity checks if (!fPdf ) { coutE(InputArguments) << "BayesianCalculator::GetPosteriorPdf - missing pdf model" << std::endl; - return 0; + return nullptr; } if (fPOI.empty()) { coutE(InputArguments) << "BayesianCalculator::GetPosteriorPdf - missing parameter of interest" << std::endl; - return 0; + return nullptr; } if (fPOI.getSize() > 1) { coutE(InputArguments) << "BayesianCalculator::GetPosteriorPdf - current implementation works only on 1D intervals" << std::endl; - return 0; + return nullptr; } - RooArgSet* constrainedParams = fPdf->getParameters(*fData); + std::unique_ptr constrainedParams{fPdf->getParameters(*fData)}; // remove the constant parameters - RemoveConstantParameters(constrainedParams); + RemoveConstantParameters(&*constrainedParams); //constrainedParams->Print("V"); // use RooFit::Constrain() to be sure constraints terms are taken into account - fLogLike = fPdf->createNLL(*fData, RooFit::Constrain(*constrainedParams), RooFit::ConditionalObservables(fConditionalObs), RooFit::GlobalObservables(fGlobalObs) ); + fLogLike = std::unique_ptr{fPdf->createNLL(*fData, RooFit::Constrain(*constrainedParams), RooFit::ConditionalObservables(fConditionalObs), RooFit::GlobalObservables(fGlobalObs) )}; @@ -826,13 +820,13 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const RooArgList p(*constrainedParams); for (int i = 0; i < p.getSize(); ++i) { RooRealVar * v = dynamic_cast(&p[i] ); - if (v!=0) ccoutE(Eval) << v->GetName() << " = " << v->getVal() << " "; + if (v!=nullptr) ccoutE(Eval) << v->GetName() << " = " << v->getVal() << " "; } ccoutE(Eval) << std::endl; ccoutE(Eval) << "-- Perform a full likelihood fit of the model before or set more reasonable parameter values" << std::endl; coutE(Eval) << "BayesianCalculator::GetPosteriorFunction : " << " cannot compute posterior function " << std::endl; - return 0; + return nullptr; } @@ -866,8 +860,6 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const delete nllFunc; - delete constrainedParams; - if ( fNuisanceParameters.empty() || fIntegrationType.Contains("ROOFIT") ) { @@ -883,10 +875,10 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const #else // here use RooProdPdf (not very nice) but working - if (fLogLike) delete fLogLike; + if (fLogLike) fLogLike.reset(); if (fProductPdf) { delete fProductPdf; - fProductPdf = 0; + fProductPdf = nullptr; } // // create a unique name for the product pdf @@ -898,11 +890,10 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const pdfAndPrior = fProductPdf; } - RooArgSet* constrParams = fPdf->getParameters(*fData); + std::unique_ptr constrParams{fPdf->getParameters(*fData)}; // remove the constant parameters - RemoveConstantParameters(constrParams); - fLogLike = pdfAndPrior->createNLL(*fData, RooFit::Constrain(*constrParams),RooFit::ConditionalObservables(fConditionalObs),RooFit::GlobalObservables(fGlobalObs) ); - delete constrParams; + RemoveConstantParameters(&*constrParams); + fLogLike = std::unique_ptr{pdfAndPrior->createNLL(*fData, RooFit::Constrain(*constrParams),RooFit::ConditionalObservables(fConditionalObs),RooFit::GlobalObservables(fGlobalObs) )}; TString likeName = TString("likelihood_times_prior_") + TString(pdfAndPrior->GetName()); TString formula; @@ -914,11 +905,11 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const // if no nuisance parameter we can just return the likelihood function if (fNuisanceParameters.empty()) { fIntegratedLikelihood = fLikelihood; - fLikelihood = 0; + fLikelihood = nullptr; } else // case of using RooFit for the integration - fIntegratedLikelihood = fLikelihood->createIntegral(fNuisanceParameters); + fIntegratedLikelihood = std::unique_ptr{fLikelihood->createIntegral(fNuisanceParameters)}.release(); } @@ -983,7 +974,7 @@ RooAbsPdf* BayesianCalculator::GetPosteriorPdf() const { RooAbsReal * plike = GetPosteriorFunction(); - if (!plike) return 0; + if (!plike) return nullptr; // create a unique name on the posterior from the names of the components @@ -1029,7 +1020,7 @@ RooPlot* BayesianCalculator::GetPosteriorPlot(bool norm, double precision ) cons fPosteriorPdf = GetPosteriorPdf(); posterior = fPosteriorPdf; } - if (!posterior) return 0; + if (!posterior) return nullptr; if (!fValidInterval) GetInterval(); @@ -1038,7 +1029,7 @@ RooPlot* BayesianCalculator::GetPosteriorPlot(bool norm, double precision ) cons RooPlot* plot = poi->frame(); - if (!plot) return 0; + if (!plot) return nullptr; // try to reduce some error messages RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CountErrors); @@ -1116,7 +1107,7 @@ SimpleInterval* BayesianCalculator::GetInterval() const RooRealVar* poi = dynamic_cast( fPOI.first() ); if (!poi) { coutE(Eval) << "BayesianCalculator::GetInterval - no parameter of interest is set " << std::endl; - return 0; + return nullptr; } @@ -1216,10 +1207,10 @@ void BayesianCalculator::ComputeIntervalUsingRooFit(double lowerCutOff, double u if (!fPosteriorPdf) fPosteriorPdf = (RooAbsPdf*) GetPosteriorPdf(); if (!fPosteriorPdf) return; - RooAbsReal* cdf = fPosteriorPdf->createCdf(fPOI,RooFit::ScanNoCdf()); + std::unique_ptr cdf{fPosteriorPdf->createCdf(fPOI,RooFit::ScanNoCdf())}; if (!cdf) return; - RooAbsFunc* cdf_bind = cdf->bindVars(fPOI,&fPOI); + std::unique_ptr cdf_bind{cdf->bindVars(fPOI,&fPOI)}; if (!cdf_bind) return; RooBrentRootFinder brf(*cdf_bind); @@ -1249,9 +1240,6 @@ void BayesianCalculator::ComputeIntervalUsingRooFit(double lowerCutOff, double u poi->setVal(tmpVal); // patch: restore the original value of poi - - delete cdf_bind; - delete cdf; } //////////////////////////////////////////////////////////////////////////////// @@ -1265,7 +1253,7 @@ void BayesianCalculator::ComputeIntervalFromCdf(double lowerCutOff, double upper RooRealVar* poi = dynamic_cast( fPOI.first() ); assert(poi); - if (GetPosteriorFunction() == 0) { + if (GetPosteriorFunction() == nullptr) { coutE(InputArguments) << "BayesianCalculator::GetInterval() cannot make posterior Function " << std::endl; return; } @@ -1340,7 +1328,7 @@ void BayesianCalculator::ApproximatePosterior() const { if (fApproxPosterior->GetNpx() >= fNScanBins) return; // otherwise redo the scan delete fApproxPosterior; - fApproxPosterior = 0; + fApproxPosterior = nullptr; } @@ -1349,7 +1337,7 @@ void BayesianCalculator::ApproximatePosterior() const { TF1 * tmp = posterior->asTF(fPOI); - assert(tmp != 0); + assert(tmp != nullptr); // binned the function in nbins and evaluate at those points if (fNScanBins > 0) tmp->SetNpx(fNScanBins); // if not use default of TF1 (which is 100) @@ -1407,7 +1395,7 @@ void BayesianCalculator::ComputeShortestInterval( ) const { if (!fApproxPosterior) return; TH1D * h1 = dynamic_cast(fApproxPosterior->GetHistogram() ); - assert(h1 != 0); + assert(h1 != nullptr); h1->SetName(fApproxPosterior->GetName()); // get bins and sort them double * bins = h1->GetArray(); diff --git a/roofit/roostats/src/BernsteinCorrection.cxx b/roofit/roostats/src/BernsteinCorrection.cxx index 3b6cfb8854746..9c2403599dba5 100644 --- a/roofit/roostats/src/BernsteinCorrection.cxx +++ b/roofit/roostats/src/BernsteinCorrection.cxx @@ -54,7 +54,7 @@ generating the toys (either via a histogram or via an independent model that is #include "TMath.h" #include #include -#include +#include #include #include @@ -103,7 +103,7 @@ Int_t BernsteinCorrection::ImportCorrectedPdf(RooWorkspace* wks, // initialize alg, by checking how well nominal model fits int printLevel = ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1; - RooFitResult* nominalResult = nominal->fitTo(*data,Save(),Minos(false), Hesse(false),PrintLevel(printLevel)); + std::unique_ptr nominalResult{nominal->fitTo(*data,Save(),Minos(false), Hesse(false),PrintLevel(printLevel))}; double lastNll= nominalResult->minNll(); if (nominalResult->status() != 0 ) { @@ -138,7 +138,7 @@ Int_t BernsteinCorrection::ImportCorrectedPdf(RooWorkspace* wks, // Since pdf is normalized - coefficient for degree 0 is fixed to be 1 if (degree == 0) { newCoef->setVal(1); - newCoef->setConstant(1); + newCoef->setConstant(true); continue; } @@ -149,7 +149,7 @@ Int_t BernsteinCorrection::ImportCorrectedPdf(RooWorkspace* wks, RooEffProd* corrected = new RooEffProd("corrected","",*nominal,*poly); // check to see how well this correction fits - RooFitResult* result = corrected->fitTo(*data,Save(),Minos(false), Hesse(false),PrintLevel(printLevel)); + std::unique_ptr result{corrected->fitTo(*data,Save(),Minos(false), Hesse(false),PrintLevel(printLevel))}; if (result->status() != 0) { std::cout << "BernsteinCorrection::ImportCorrectedPdf - Error fit with corrected model failed" << std::endl; @@ -186,8 +186,6 @@ Int_t BernsteinCorrection::ImportCorrectedPdf(RooWorkspace* wks, // update last result for next iteration in loop lastNll = result->minNll(); - - delete result; } log << "------ End Bernstein Correction Log --------" << endl; @@ -288,20 +286,20 @@ void BernsteinCorrection::CreateQSamplingDist(RooWorkspace* wks, for(int i=0; inumEntries()); + std::unique_ptr tmpData{toyGen.generate(*x,data->numEntries())}; // check to see how well this correction fits - RooFitResult* result - = corrected->fitTo(*tmpData,Save(),Minos(false), - Hesse(false),PrintLevel(printLevel)); + std::unique_ptr result{ + corrected->fitTo(*tmpData,Save(),Minos(false), + Hesse(false),PrintLevel(printLevel))}; - RooFitResult* resultNull - = correctedNull->fitTo(*tmpData,Save(),Minos(false), - Hesse(false),PrintLevel(printLevel)); + std::unique_ptr resultNull{ + correctedNull->fitTo(*tmpData,Save(),Minos(false), + Hesse(false),PrintLevel(printLevel))}; - RooFitResult* resultExtra - = correctedExtra->fitTo(*tmpData,Save(),Minos(false), - Hesse(false),PrintLevel(printLevel)); + std::unique_ptr resultExtra{ + correctedExtra->fitTo(*tmpData,Save(),Minos(false), + Hesse(false),PrintLevel(printLevel))}; // Hypothesis test between previous correction (null) @@ -314,12 +312,6 @@ void BernsteinCorrection::CreateQSamplingDist(RooWorkspace* wks, samplingDistExtra->Fill(qExtra); if (printLevel > 0) cout << "NLL Results: null " << resultNull->minNll() << " ref = " << result->minNll() << " extra" << resultExtra->minNll() << endl; - - - delete tmpData; - delete result; - delete resultNull; - delete resultExtra; } RooMsgService::instance().setGlobalKillBelow(msglevel); diff --git a/roofit/roostats/src/ConfidenceBelt.cxx b/roofit/roostats/src/ConfidenceBelt.cxx index 1e8b9b86a7838..72e9ecf43d291 100644 --- a/roofit/roostats/src/ConfidenceBelt.cxx +++ b/roofit/roostats/src/ConfidenceBelt.cxx @@ -47,7 +47,7 @@ using namespace std; /// Default constructor ConfidenceBelt::ConfidenceBelt() : - TNamed(), fParameterPoints(0) + TNamed(), fParameterPoints(nullptr) { } @@ -55,7 +55,7 @@ ConfidenceBelt::ConfidenceBelt() : /// Alternate constructor ConfidenceBelt::ConfidenceBelt(const char* name) : - TNamed(name,name), fParameterPoints(0) + TNamed(name,name), fParameterPoints(nullptr) { } @@ -63,7 +63,7 @@ ConfidenceBelt::ConfidenceBelt(const char* name) : /// Alternate constructor ConfidenceBelt::ConfidenceBelt(const char* name, const char* title) : - TNamed(name,title), fParameterPoints(0) + TNamed(name,title), fParameterPoints(nullptr) { } @@ -221,7 +221,7 @@ AcceptanceRegion* ConfidenceBelt::GetAcceptanceRegion(RooArgSet ¶meterPoint, if( !this->CheckParameters(parameterPoint) ){ std::cout << "problem with parameters" << std::endl; - return 0; + return nullptr; } if( hist ) { @@ -240,7 +240,7 @@ AcceptanceRegion* ConfidenceBelt::GetAcceptanceRegion(RooArgSet ¶meterPoint, // need a way to get index for given point // RooStats::SetParameters(¶meterPoint, tree->get()); // set tree's parameters to desired values Int_t index = 0; //need something like tree->calcTreeIndex(); - const RooArgSet* thisPoint = 0; + const RooArgSet* thisPoint = nullptr; for(index=0; indexnumEntries(); ++index){ thisPoint = tree->get(index); bool samePoint = true; @@ -263,7 +263,7 @@ AcceptanceRegion* ConfidenceBelt::GetAcceptanceRegion(RooArgSet ¶meterPoint, std::cout << "dataset is not initialized properly" << std::endl; } - return 0; + return nullptr; } diff --git a/roofit/roostats/src/DetailedOutputAggregator.cxx b/roofit/roostats/src/DetailedOutputAggregator.cxx index bd2f29cd7e0b4..65db5598bb10d 100644 --- a/roofit/roostats/src/DetailedOutputAggregator.cxx +++ b/roofit/roostats/src/DetailedOutputAggregator.cxx @@ -99,17 +99,17 @@ namespace RooStats { TString renamed(TString::Format("%s%s", prefix.Data(), v->GetName())); if (fResult == nullptr) { // we never committed, so by default all columns are expected to not exist - RooAbsArg* var = v->createFundamental(); + std::unique_ptr var{v->createFundamental()}; assert(var != nullptr); RooArgSet(*var).assign(RooArgSet(*v)); var->SetName(renamed); - if (RooRealVar* rvar= dynamic_cast(var)) { + if (RooRealVar* rvar= dynamic_cast(var.get())) { if (v->getAttribute("StoreError")) var->setAttribute("StoreError"); else rvar->removeError(); if (v->getAttribute("StoreAsymError")) var->setAttribute("StoreAsymError"); else rvar->removeAsymError(); } - if (fBuiltSet->addOwned(*var)) continue; // OK - can skip past setting value + if (fBuiltSet->addOwned(std::move(var))) continue; // OK - can skip past setting value } if (RooAbsArg* var = fBuiltSet->find(renamed)) { // we already committed an argset once, so we expect all columns to already be in the set @@ -127,8 +127,7 @@ namespace RooStats { void DetailedOutputAggregator::CommitSet(double weight) { if (fResult == nullptr) { // Store dataset as a tree - problem with VectorStore and StoreError (bug #94908) - RooRealVar wgt("weight","weight",1.0); - fResult = new RooDataSet("", "", RooArgSet(*fBuiltSet,wgt), RooFit::WeightVar(wgt)); + fResult = new RooDataSet("", "", *fBuiltSet, RooFit::WeightVar()); } fResult->add(RooArgSet(*fBuiltSet), weight); @@ -153,8 +152,7 @@ namespace RooStats { fResult = nullptr; // we no longer own the dataset temp->SetNameTitle( name.Data(), title.Data() ); }else{ - RooRealVar wgt("weight","weight",1.0); - temp = new RooDataSet(name.Data(), title.Data(), RooArgSet(wgt), RooFit::WeightVar(wgt)); + temp = new RooDataSet(name.Data(), title.Data(), {}, RooFit::WeightVar()); } delete fBuiltSet; fBuiltSet = nullptr; diff --git a/roofit/roostats/src/FeldmanCousins.cxx b/roofit/roostats/src/FeldmanCousins.cxx index f1b221ae8fe5e..6809f12690cc7 100644 --- a/roofit/roostats/src/FeldmanCousins.cxx +++ b/roofit/roostats/src/FeldmanCousins.cxx @@ -66,9 +66,9 @@ FeldmanCousins::FeldmanCousins(RooAbsData& data, ModelConfig& model) : fSize(0.05), fModel(model), fData(data), - fTestStatSampler(0), - fPointsToTest(0), - fPOIToTest(0), + fTestStatSampler(nullptr), + fPointsToTest(nullptr), + fPOIToTest(nullptr), fConfBelt(nullptr), fAdaptiveSampling(false), fAdditionalNToysFactor(1.), @@ -171,8 +171,8 @@ void FeldmanCousins::CreateParameterPoints() const{ // make profile construction RooFit::MsgLevel previous = RooMsgService::instance().globalKillBelow(); RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ; - RooAbsReal* nll = pdf->createNLL(fData,RooFit::CloneData(false)); - RooAbsReal* profile = nll->createProfile(*fModel.GetParametersOfInterest()); + std::unique_ptr nll{pdf->createNLL(fData,RooFit::CloneData(false))}; + std::unique_ptr profile{nll->createProfile(*fModel.GetParametersOfInterest())}; RooDataSet* profileConstructionPoints = new RooDataSet("profileConstruction", "profileConstruction", @@ -186,8 +186,6 @@ void FeldmanCousins::CreateParameterPoints() const{ profileConstructionPoints->add(*parameters); } RooMsgService::instance().setGlobalKillBelow(previous) ; - delete profile; - delete nll; if(!fPOIToTest) delete parameterScan; // done diff --git a/roofit/roostats/src/FrequentistCalculator.cxx b/roofit/roostats/src/FrequentistCalculator.cxx index a9c50d66ecbe3..949471cb9dc53 100644 --- a/roofit/roostats/src/FrequentistCalculator.cxx +++ b/roofit/roostats/src/FrequentistCalculator.cxx @@ -56,8 +56,8 @@ int FrequentistCalculator::PreNullHook(RooArgSet *parameterPoint, double obsTest // ****** any TestStatSampler ******** // create profile keeping everything but nuisance parameters fixed - RooArgSet * allParams = fNullModel->GetPdf()->getParameters(*fData); - RemoveConstantParameters(allParams); + std::unique_ptr allParams{fNullModel->GetPdf()->getParameters(*fData)}; + RemoveConstantParameters(&*allParams); // note: making nll or profile class variables can only be done in the constructor // as all other hooks are const (which has to be because GetHypoTest is const). However, @@ -94,26 +94,23 @@ int FrequentistCalculator::PreNullHook(RooArgSet *parameterPoint, double obsTest if (fNullModel->GetGlobalObservables()) globalObs.add(*fNullModel->GetGlobalObservables()); auto& config = GetGlobalRooStatsConfig(); - RooAbsReal* nll = fNullModel->GetPdf()->createNLL(*const_cast(fData), RooFit::CloneData(false), RooFit::Constrain(*allParams), + std::unique_ptr nll{fNullModel->GetPdf()->createNLL(*const_cast(fData), RooFit::CloneData(false), RooFit::Constrain(*allParams), RooFit::GlobalObservables(globalObs), RooFit::ConditionalObservables(conditionalObs), - RooFit::Offset(config.useLikelihoodOffset)); - RooProfileLL* profile = dynamic_cast(nll->createProfile(allButNuisance)); + RooFit::Offset(config.useLikelihoodOffset))}; + std::unique_ptr profileOwner{nll->createProfile(allButNuisance)}; + auto profile = dynamic_cast(profileOwner.get()); // set minimier options profile->minimizer()->setPrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1); profile->getVal(); // this will do fit and set nuisance parameters to profiled values // Hack to extract a RooFitResult if (fStoreFitInfo) { - RooFitResult *result = profile->minimizer()->save(); - RooArgSet * detOutput = DetailedOutputAggregator::GetAsArgSet(result, "fitNull_"); + std::unique_ptr result {profile->minimizer()->save()}; + std::unique_ptr detOutput {DetailedOutputAggregator::GetAsArgSet(result.get(), "fitNull_")}; fFitInfo->addOwned(*detOutput); - delete detOutput; - delete result; } - delete profile; - delete nll; RooMsgService::instance().setGlobalKillBelow(msglevel); // set in test statistics conditional and global observables @@ -132,8 +129,6 @@ int FrequentistCalculator::PreNullHook(RooArgSet *parameterPoint, double obsTest if(fNullModel->GetNuisanceParameters()) parameterPoint->add(*fNullModel->GetNuisanceParameters()); - delete allParams; - // ***** ToyMCSampler specific ******* @@ -173,8 +168,8 @@ int FrequentistCalculator::PreAltHook(RooArgSet *parameterPoint, double obsTestS // ****** any TestStatSampler ******** // create profile keeping everything but nuisance parameters fixed - RooArgSet * allParams = fAltModel->GetPdf()->getParameters(*fData); - RemoveConstantParameters(allParams); + std::unique_ptr allParams{fAltModel->GetPdf()->getParameters(*fData)}; + RemoveConstantParameters(&*allParams); bool doProfile = true; RooArgSet allButNuisance(*allParams); @@ -205,27 +200,24 @@ int FrequentistCalculator::PreAltHook(RooArgSet *parameterPoint, double obsTestS if (fAltModel->GetGlobalObservables()) globalObs.add(*fAltModel->GetGlobalObservables()); const auto& config = GetGlobalRooStatsConfig(); - RooAbsReal* nll = fAltModel->GetPdf()->createNLL(*const_cast(fData), RooFit::CloneData(false), RooFit::Constrain(*allParams), + std::unique_ptr nll{fAltModel->GetPdf()->createNLL(*const_cast(fData), RooFit::CloneData(false), RooFit::Constrain(*allParams), RooFit::GlobalObservables(globalObs), RooFit::ConditionalObservables(conditionalObs), - RooFit::Offset(config.useLikelihoodOffset)); + RooFit::Offset(config.useLikelihoodOffset))}; - RooProfileLL* profile = dynamic_cast(nll->createProfile(allButNuisance)); + std::unique_ptr profileOwner{nll->createProfile(allButNuisance)}; + auto profile = dynamic_cast(profileOwner.get()); // set minimizer options profile->minimizer()->setPrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1); // use -1 to make more silent profile->getVal(); // this will do fit and set nuisance parameters to profiled values // Hack to extract a RooFitResult if (fStoreFitInfo) { - RooFitResult *result = profile->minimizer()->save(); - RooArgSet * detOutput = DetailedOutputAggregator::GetAsArgSet(result, "fitAlt_"); + std::unique_ptr result {profile->minimizer()->save()}; + std::unique_ptr detOutput {DetailedOutputAggregator::GetAsArgSet(result.get(), "fitAlt_")}; fFitInfo->addOwned(*detOutput); - delete detOutput; - delete result; } - delete profile; - delete nll; RooMsgService::instance().setGlobalKillBelow(msglevel); // set in test statistics conditional and global observables @@ -244,8 +236,6 @@ int FrequentistCalculator::PreAltHook(RooArgSet *parameterPoint, double obsTestS if(fAltModel->GetNuisanceParameters()) parameterPoint->add(*fAltModel->GetNuisanceParameters()); - delete allParams; - // ***** ToyMCSampler specific ******* // check whether TestStatSampler is a ToyMCSampler diff --git a/roofit/roostats/src/HLFactory.cxx b/roofit/roostats/src/HLFactory.cxx index d1eb156458050..d8958a048b048 100644 --- a/roofit/roostats/src/HLFactory.cxx +++ b/roofit/roostats/src/HLFactory.cxx @@ -51,10 +51,10 @@ HLFactory::HLFactory(const char *name, const char *fileName, bool isVerbose): TNamed(name,name), - fComboCat(0), - fComboBkgPdf(0), - fComboSigBkgPdf(0), - fComboDataset(0), + fComboCat(nullptr), + fComboBkgPdf(nullptr), + fComboSigBkgPdf(nullptr), + fComboDataset(nullptr), fCombinationDone(false), fVerbose(isVerbose), fInclusionLevel(0), @@ -78,10 +78,10 @@ HLFactory::HLFactory(const char* name, RooWorkspace* externalWs, bool isVerbose): TNamed(name,name), - fComboCat(0), - fComboBkgPdf(0), - fComboSigBkgPdf(0), - fComboDataset(0), + fComboCat(nullptr), + fComboBkgPdf(nullptr), + fComboSigBkgPdf(nullptr), + fComboDataset(nullptr), fCombinationDone(false), fVerbose(isVerbose), fInclusionLevel(0), @@ -97,10 +97,10 @@ HLFactory::HLFactory(const char* name, HLFactory::HLFactory(): TNamed("hlfactory","hlfactory"), - fComboCat(0), - fComboBkgPdf(0), - fComboSigBkgPdf(0), - fComboDataset(0), + fComboCat(nullptr), + fComboBkgPdf(nullptr), + fComboSigBkgPdf(nullptr), + fComboDataset(nullptr), fCombinationDone(false), fVerbose(false), fInclusionLevel(0), @@ -148,7 +148,7 @@ int HLFactory::AddChannel(const char* label, return -1; } - if (SigBkgPdfName!=0){ + if (SigBkgPdfName!=nullptr){ if (fWs->pdf(SigBkgPdfName)==nullptr){ std::cerr << "Pdf " << SigBkgPdfName << " not found in workspace!\n"; return -1; @@ -157,7 +157,7 @@ int HLFactory::AddChannel(const char* label, fSigBkgPdfNames.Add(name); } - if (BkgPdfName!=0){ + if (BkgPdfName!=nullptr){ if (fWs->pdf(BkgPdfName)==nullptr){ std::cerr << "Pdf " << BkgPdfName << " not found in workspace!\n"; return -1; @@ -166,7 +166,7 @@ int HLFactory::AddChannel(const char* label, fBkgPdfNames.Add(name); } - if (DatasetName!=0){ + if (DatasetName!=nullptr){ if (fWs->data(DatasetName)==nullptr){ std::cerr << "Dataset " << DatasetName << " not found in workspace!\n"; return -1; @@ -175,7 +175,7 @@ int HLFactory::AddChannel(const char* label, fDatasetsNames.Add(name); } - if (label!=0){ + if (label!=nullptr){ TObjString* name = new TObjString(label); fLabelsNames.Add(name); } @@ -189,7 +189,7 @@ int HLFactory::AddChannel(const char* label, RooAbsPdf* HLFactory::GetTotSigBkgPdf(){ if (fSigBkgPdfNames.GetSize()==0) - return 0; + return nullptr; if (fComboSigBkgPdf!=nullptr) return fComboSigBkgPdf; @@ -198,8 +198,7 @@ RooAbsPdf* HLFactory::GetTotSigBkgPdf(){ return nullptr; if (fSigBkgPdfNames.GetSize()==1){ - TString name(((TObjString*)fSigBkgPdfNames.At(0))->String()); - fComboSigBkgPdf=fWs->pdf(name); + fComboSigBkgPdf=fWs->pdf(static_cast(fSigBkgPdfNames.At(0))->String().Data()); return fComboSigBkgPdf; } @@ -209,18 +208,18 @@ RooAbsPdf* HLFactory::GetTotSigBkgPdf(){ RooArgList pdfs("pdfs"); for(auto * ostring : static_range_cast(fSigBkgPdfNames)) { - pdfs.add( *(fWs->pdf(ostring->String())) ); + pdfs.add( *(fWs->pdf(ostring->String().Data())) ); } - TString name(GetName()); + std::string name(GetName()); name+="_sigbkg"; - TString title(GetName()); + std::string title(GetName()); title+="_sigbkg"; fComboSigBkgPdf= - new RooSimultaneous(name, - title, + new RooSimultaneous(name.c_str(), + title.c_str(), pdfs, *fComboCat); @@ -235,7 +234,7 @@ RooAbsPdf* HLFactory::GetTotSigBkgPdf(){ RooAbsPdf* HLFactory::GetTotBkgPdf(){ if (fBkgPdfNames.GetSize()==0) - return 0; + return nullptr; if (fComboBkgPdf!=nullptr) return fComboBkgPdf; @@ -244,7 +243,7 @@ RooAbsPdf* HLFactory::GetTotBkgPdf(){ return nullptr; if (fBkgPdfNames.GetSize()==1){ - fComboBkgPdf=fWs->pdf(((TObjString*)fBkgPdfNames.First())->String()); + fComboBkgPdf=fWs->pdf(static_cast(fBkgPdfNames.First())->String().Data()); return fComboBkgPdf; } @@ -254,7 +253,7 @@ RooAbsPdf* HLFactory::GetTotBkgPdf(){ RooArgList pdfs("pdfs"); for(auto * ostring : static_range_cast(fBkgPdfNames)) { - pdfs.add( *(fWs->pdf(ostring->String())) ); + pdfs.add( *fWs->pdf(ostring->String().Data()) ); } TString name(GetName()); @@ -280,7 +279,7 @@ RooAbsPdf* HLFactory::GetTotBkgPdf(){ RooDataSet* HLFactory::GetTotDataSet(){ if (fDatasetsNames.GetSize()==0) - return 0; + return nullptr; if (fComboDataset!=nullptr) return fComboDataset; @@ -289,7 +288,7 @@ RooDataSet* HLFactory::GetTotDataSet(){ return nullptr; if (fDatasetsNames.GetSize()==1){ - fComboDataset=(RooDataSet*)fWs->data(((TObjString*)fDatasetsNames.First())->String()); + fComboDataset=(RooDataSet*)fWs->data(static_cast(fDatasetsNames.First())->String().Data()); return fComboDataset; } @@ -301,7 +300,7 @@ RooDataSet* HLFactory::GetTotDataSet(){ TObjString* ostring; ostring = static_cast(*it); ++it; - fComboDataset = (RooDataSet*) fWs->data(ostring->String()) ; + fComboDataset = (RooDataSet*) fWs->data(ostring->String().Data()) ; if (!fComboDataset) return nullptr; fComboDataset->Print(); TString dataname(GetName()); @@ -312,7 +311,7 @@ RooDataSet* HLFactory::GetTotDataSet(){ for(; it != fDatasetsNames.end() ; ++it) { ostring = static_cast(*it); catindex++; - RooDataSet * data = (RooDataSet*)fWs->data(ostring->String()); + RooDataSet * data = (RooDataSet*)fWs->data(ostring->String().Data()); if (!data) return nullptr; RooDataSet* dummy = new RooDataSet(*data,""); fComboCat->setIndex(catindex); @@ -348,7 +347,7 @@ RooCategory* HLFactory::GetTotCategory(){ /// Process an additional configuration file int HLFactory::ProcessCard(const char* filename){ - return fReadFile(filename,0); + return fReadFile(filename,false); } //////////////////////////////////////////////////////////////////////////////// @@ -564,7 +563,7 @@ int HLFactory::fParseLine(TString& line){ nequals>0 && // It is a cat like "tag[B0=1,B0bar=-1]" ! line.Contains("(") && ! line.Contains(")"))) { - fWs->factory(line); + fWs->factory(line.Data()); return 0; } @@ -601,7 +600,7 @@ int HLFactory::fParseLine(TString& line){ TString rootfile_name (static_cast(descr_array->At(0))->GetString()); std::unique_ptr ifile{TFile::Open(rootfile_name)}; - if (ifile==0) + if (ifile==nullptr) return 1; if (n_descr_parts==3){// in presence of a Ws @@ -625,13 +624,13 @@ int HLFactory::fParseLine(TString& line){ std::cout << "DEBUG: new_line: " << new_line.Data() << std::endl; } - fWs->factory(new_line); + fWs->factory(new_line.Data()); return 0; } else { // In case we do not know what to do we pipe it.. - fWs->factory(line); + fWs->factory(line.Data()); } return 0; diff --git a/roofit/roostats/src/HybridPlot.cxx b/roofit/roostats/src/HybridPlot.cxx index e17ff332bf8bc..97d2af143cab8 100644 --- a/roofit/roostats/src/HybridPlot.cxx +++ b/roofit/roostats/src/HybridPlot.cxx @@ -12,7 +12,7 @@ An example plot is available here: http://www-ekp.physik.uni-karlsruhe.de/~schott/roostats/hybridplot_example.png */ -#include "assert.h" +#include #include #include #include @@ -51,9 +51,9 @@ HybridPlot::HybridPlot(const char* name, fSb_histo_shaded(nullptr), fB_histo(nullptr), fB_histo_shaded(nullptr), - fData_testStat_line(0), - fLegend(0), - fPad(0), + fData_testStat_line(nullptr), + fLegend(nullptr), + fPad(nullptr), fVerbose(verbosity) { int nToysSB = sb_vals.size(); @@ -96,11 +96,11 @@ HybridPlot::HybridPlot(const char* name, for (int i=0;iFill(b_vals[i]); double histos_max_y = fSb_histo->GetMaximum(); - double line_hight = histos_max_y/nToysSB; + double lineHeight = histos_max_y/nToysSB; if (histos_max_yGetMaximum()) histos_max_y = fB_histo->GetMaximum()/nToysB; // Build the line of the measured -2lnQ - fData_testStat_line = new TLine(testStat_data,0,testStat_data,line_hight); + fData_testStat_line = new TLine(testStat_data,0,testStat_data,lineHeight); fData_testStat_line->SetLineWidth(3); fData_testStat_line->SetLineColor(kBlack); @@ -250,19 +250,19 @@ double HybridPlot::GetHistoCenter(TH1* histo_orig, double n_rms, bool display_re // First fit! - TF1* gaus = new TF1("mygaus", "gaus", x_min, x_max); + TF1* gauss = new TF1("mygauss", "gauss", x_min, x_max); - gaus->SetParameter("Constant",histo->GetEntries()); - gaus->SetParameter("Mean",histo->GetMean()); - gaus->SetParameter("Sigma",histo->GetRMS()); + gauss->SetParameter("Constant",histo->GetEntries()); + gauss->SetParameter("Mean",histo->GetMean()); + gauss->SetParameter("Sigma",histo->GetRMS()); - histo->Fit(gaus,optfit); + histo->Fit(gauss,optfit); // Second fit! - double sigma = gaus->GetParameter("Sigma"); - double mean = gaus->GetParameter("Mean"); + double sigma = gauss->GetParameter("Sigma"); + double mean = gauss->GetParameter("Mean"); - delete gaus; + delete gauss; std::cout << "Center is 1st pass = " << mean << std::endl; @@ -271,24 +271,24 @@ double HybridPlot::GetHistoCenter(TH1* histo_orig, double n_rms, bool display_re x_min = mean - n_rms*sigma - sigma*skewness/2; x_max = mean + n_rms*sigma - sigma*skewness/2;; - TF1* gaus2 = new TF1("mygaus2", "gaus", x_min, x_max); - gaus2->SetParameter("Mean",mean); + TF1* gauss2 = new TF1("mygauss2", "gauss", x_min, x_max); + gauss2->SetParameter("Mean",mean); // second fit : likelihood fit optfit += "L"; - histo->Fit(gaus2,optfit,"", x_min, x_max); + histo->Fit(gauss2,optfit,"", x_min, x_max); - double center = gaus2->GetParameter("Mean"); + double center = gauss2->GetParameter("Mean"); if (display_result) { histo->Draw(); - gaus2->Draw("same"); + gauss2->Draw("same"); } else { delete histo; } - delete gaus2; + delete gauss2; return center; @@ -331,7 +331,7 @@ double* HybridPlot::GetHistoPvals (TH1* histo, double percentage){ for (it = extremes_map.begin();it != extremes_map.end();++it){ a=it->first; b=it->second; - current_diff=std::fabs(histo->GetBinContent(a)-histo->GetBinContent(b)); + current_diff=std::abs(histo->GetBinContent(a)-histo->GetBinContent(b)); if (current_diffSetSnapshot(poi)." << endl; - return 0; + return nullptr; } // CheckHook if(CheckHook() != 0) { oocoutE(nullptr,Generation) << "There was an error in CheckHook(). Stop." << endl; - return 0; + return nullptr; } if (!fTestStatSampler || !fTestStatSampler->GetTestStatistic() ) { oocoutE(nullptr,InputArguments) << "Test Statistic Sampler or Test Statistics not defined. Stop." << endl; - return 0; + return nullptr; } // get a big list of all variables for convenient switching - RooArgSet *nullParams = fNullModel->GetPdf()->getParameters(*fData); - RooArgSet *altParams = fAltModel->GetPdf()->getParameters(*fData); + std::unique_ptr altParams{fAltModel->GetPdf()->getParameters(*fData)}; // save all parameters so we can set them back to what they were - RooArgSet *bothParams = fNullModel->GetPdf()->getParameters(*fData); + std::unique_ptr bothParams{fNullModel->GetPdf()->getParameters(*fData)}; bothParams->add(*altParams,false); - RooArgSet *saveAll = (RooArgSet*) bothParams->snapshot(); + std::unique_ptr saveAll {(RooArgSet*) bothParams->snapshot()}; // check whether we have a ToyMCSampler and if so, keep a pointer to it ToyMCSampler* toymcs = dynamic_cast( fTestStatSampler ); @@ -143,17 +142,16 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const { RooArgSet nullP(*nullSnapshot); double obsTestStat; - RooArgList* allTS = nullptr; + std::unique_ptr allTS; if( toymcs ) { - allTS = toymcs->EvaluateAllTestStatistics(*const_cast(fData), nullP); - if (!allTS) return 0; + allTS = std::unique_ptr{toymcs->EvaluateAllTestStatistics(*const_cast(fData), nullP)}; + if (!allTS) return nullptr; //oocoutP(nullptr,Generation) << "All Test Statistics on data: " << endl; //allTS->Print("v"); RooRealVar* firstTS = (RooRealVar*)allTS->at(0); obsTestStat = firstTS->getVal(); if (allTS->getSize()<=1) { - delete allTS; - allTS= 0; // don't save + allTS = nullptr; // don't save } }else{ obsTestStat = fTestStatSampler->EvaluateTestStatistic(*const_cast(fData), nullP); @@ -181,7 +179,7 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const { samp_null = new SamplingDistribution( detOut_null->GetName(), detOut_null->GetTitle(), *detOut_null ); if (detOut_null->get()->getSize()<=1) { delete detOut_null; - detOut_null= 0; + detOut_null= nullptr; } } }else samp_null = fTestStatSampler->GetSamplingDistribution(paramPointNull); @@ -212,7 +210,7 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const { samp_alt = new SamplingDistribution( detOut_alt->GetName(), detOut_alt->GetTitle(), *detOut_alt ); if (detOut_alt->get()->getSize()<=1) { delete detOut_alt; - detOut_alt= 0; + detOut_alt= nullptr; } } @@ -229,11 +227,11 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const { HypoTestResult* res = new HypoTestResult(resultname.c_str()); res->SetPValueIsRightTail(fTestStatSampler->GetTestStatistic()->PValueIsRightTail()); res->SetTestStatisticData(obsTestStat); - res->SetAltDistribution(samp_alt); - res->SetNullDistribution(samp_null); + res->SetAltDistribution(samp_alt); // takes ownership of samp_alt + res->SetNullDistribution(samp_null); // takes ownership of samp_null res->SetAltDetailedOutput( detOut_alt ); res->SetNullDetailedOutput( detOut_null ); - res->SetAllTestStatisticsData( allTS ); + res->SetAllTestStatisticsData( allTS.get() ); const RooArgSet *aset = GetFitInfo(); if (aset != nullptr) { @@ -243,12 +241,6 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const { } bothParams->assign(*saveAll); - delete allTS; - delete bothParams; - delete saveAll; - delete altParams; - delete nullParams; - delete nullSnapshot; PostHook(); return res; } diff --git a/roofit/roostats/src/HypoTestInverter.cxx b/roofit/roostats/src/HypoTestInverter.cxx index 1d358aa48030c..5f9a6bebade4b 100644 --- a/roofit/roostats/src/HypoTestInverter.cxx +++ b/roofit/roostats/src/HypoTestInverter.cxx @@ -105,7 +105,7 @@ void HypoTestInverter::SetCloseProof(bool flag) { RooRealVar * HypoTestInverter::GetVariableToScan(const HypoTestCalculatorGeneric &hc) { - RooRealVar * varToScan = 0; + RooRealVar * varToScan = nullptr; const ModelConfig * mc = hc.GetNullModel(); if (mc) { const RooArgSet * poi = mc->GetParametersOfInterest(); @@ -144,7 +144,7 @@ void HypoTestInverter::CheckInputModels(const HypoTestCalculatorGeneric &hc,cons oocoutE(nullptr,InputArguments) << "HypoTestInverter - B model has no pdf or observables defined" << std::endl; return; } - RooArgSet * bParams = bPdf->getParameters(*bObs); + std::unique_ptr bParams{bPdf->getParameters(*bObs)}; if (!bParams) { oocoutE(nullptr,InputArguments) << "HypoTestInverter - pdf of B model has no parameters" << std::endl; return; @@ -158,7 +158,6 @@ void HypoTestInverter::CheckInputModels(const HypoTestCalculatorGeneric &hc,cons << " user must check input model configurations " << endl; if (poiB) delete poiB; } - delete bParams; } //////////////////////////////////////////////////////////////////////////////// @@ -167,9 +166,9 @@ void HypoTestInverter::CheckInputModels(const HypoTestCalculatorGeneric &hc,cons HypoTestInverter::HypoTestInverter( ) : fTotalToysRun(0), fMaxToys(0), - fCalculator0(0), - fScannedVariable(0), - fResults(0), + fCalculator0(nullptr), + fScannedVariable(nullptr), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(0), @@ -193,9 +192,9 @@ HypoTestInverter::HypoTestInverter( HypoTestCalculatorGeneric& hc, RooRealVar* scannedVariable, double size ) : fTotalToysRun(0), fMaxToys(0), - fCalculator0(0), + fCalculator0(nullptr), fScannedVariable(scannedVariable), - fResults(0), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(size), @@ -248,7 +247,7 @@ HypoTestInverter::HypoTestInverter( HybridCalculator& hc, fMaxToys(0), fCalculator0(&hc), fScannedVariable(scannedVariable), - fResults(0), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(size), @@ -281,7 +280,7 @@ HypoTestInverter::HypoTestInverter( FrequentistCalculator& hc, fMaxToys(0), fCalculator0(&hc), fScannedVariable(scannedVariable), - fResults(0), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(size), @@ -313,7 +312,7 @@ HypoTestInverter::HypoTestInverter( AsymptoticCalculator& hc, fMaxToys(0), fCalculator0(&hc), fScannedVariable(scannedVariable), - fResults(0), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(size), @@ -344,9 +343,9 @@ HypoTestInverter::HypoTestInverter( RooAbsData& data, ModelConfig &sbModel, Mode RooRealVar * scannedVariable, ECalculatorType type, double size) : fTotalToysRun(0), fMaxToys(0), - fCalculator0(0), + fCalculator0(nullptr), fScannedVariable(scannedVariable), - fResults(0), + fResults(nullptr), fUseCLs(false), fScanLog(false), fSize(size), @@ -355,9 +354,9 @@ HypoTestInverter::HypoTestInverter( RooAbsData& data, ModelConfig &sbModel, Mode fNBins(0), fXmin(1), fXmax(1), fNumErr(0) { - if(fCalcType==kFrequentist) fHC.reset(new FrequentistCalculator(data, bModel, sbModel)); - if(fCalcType==kHybrid) fHC.reset( new HybridCalculator(data, bModel, sbModel)) ; - if(fCalcType==kAsymptotic) fHC.reset( new AsymptoticCalculator(data, bModel, sbModel)); + if(fCalcType==kFrequentist) fHC = std::make_unique(data, bModel, sbModel); + if(fCalcType==kHybrid) fHC = std::make_unique(data, bModel, sbModel); + if(fCalcType==kAsymptotic) fHC = std::make_unique(data, bModel, sbModel); fCalculator0 = fHC.get(); // get scanned variable if (!fScannedVariable) { @@ -379,8 +378,8 @@ HypoTestInverter::HypoTestInverter( RooAbsData& data, ModelConfig &sbModel, Mode HypoTestInverter::HypoTestInverter(const HypoTestInverter & rhs) : IntervalCalculator(), fTotalToysRun(0), - fCalculator0(0), fScannedVariable(0), // add these for Coverity - fResults(0) + fCalculator0(nullptr), fScannedVariable(nullptr), // add these for Coverity + fResults(nullptr) { (*this) = rhs; } @@ -416,7 +415,7 @@ HypoTestInverter & HypoTestInverter::operator= (const HypoTestInverter & rhs) { HypoTestInverter::~HypoTestInverter() { if (fResults) delete fResults; - fCalculator0 = 0; + fCalculator0 = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -428,7 +427,7 @@ TestStatistic * HypoTestInverter::GetTestStatistic( ) const return fCalculator0->GetTestStatSampler()->GetTestStatistic(); } else - return 0; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -448,7 +447,7 @@ bool HypoTestInverter::SetTestStatistic(TestStatistic& stat) void HypoTestInverter::Clear() { if (fResults) delete fResults; - fResults = 0; + fResults = nullptr; fLimitPlot.reset(nullptr); } @@ -456,7 +455,7 @@ void HypoTestInverter::Clear() { /// create a new HypoTestInverterResult to hold all computed results void HypoTestInverter::CreateResults() const { - if (fResults == 0) { + if (fResults == nullptr) { TString results_name = "result_"; results_name += fScannedVariable->GetName(); fResults = new HypoTestInverterResult(results_name,*fScannedVariable,ConfidenceLevel()); @@ -531,7 +530,7 @@ HypoTestResult * HypoTestInverter::Eval(HypoTestCalculatorGeneric &hc, bool adap // run the hypothesis test HypoTestResult * hcResult = hc.GetHypoTest(); - if (hcResult == 0) { + if (hcResult == nullptr) { oocoutE(nullptr,Eval) << "HypoTestInverter::Eval - HypoTest failed" << std::endl; return hcResult; } @@ -560,7 +559,7 @@ HypoTestResult * HypoTestInverter::Eval(HypoTestCalculatorGeneric &hc, bool adap if (fCalcType == kHybrid) HypoTestWrapper::SetToys((HybridCalculator*)&hc, fUseCLs ? fgNToys : 1, 4*fgNToys); if (fCalcType == kFrequentist) HypoTestWrapper::SetToys((FrequentistCalculator*)&hc, fUseCLs ? fgNToys : 1, 4*fgNToys); - while (clsMidErr >= fgCLAccuracy && (clsTarget == -1 || fabs(clsMid-clsTarget) < 3*clsMidErr) ) { + while (clsMidErr >= fgCLAccuracy && (clsTarget == -1 || std::abs(clsMid-clsTarget) < 3*clsMidErr) ) { std::unique_ptr more(hc.GetHypoTest()); // if (flipPValues) @@ -774,7 +773,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur RooRealVar *r = fScannedVariable; - if ((hint != 0) && (*hint > r->getMin())) { + if ((hint != nullptr) && (*hint > r->getMin())) { r->setMax(std::min(3.0 * (*hint), r->getMax())); r->setMin(std::max(0.3 * (*hint), r->getMin())); oocoutI(nullptr,InputArguments) << "HypoTestInverter::RunLimit - Use hint value " << *hint @@ -795,7 +794,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur TF1 expoFit("expoFit","[0]*exp([1]*(x-[2]))", rMin, rMax); - fLimitPlot.reset(new TGraphErrors()); + fLimitPlot = std::make_unique(); if (fVerbose > 0) std::cout << "Search for upper limit to the limit" << std::endl; for (int tries = 0; tries < 6; ++tries) { @@ -805,7 +804,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur continue; } clsMax = std::make_pair( fResults->GetLastYValue(), fResults->GetLastYError() ); - if (clsMax.first == 0 || clsMax.first + 3 * fabs(clsMax.second) < clsTarget ) break; + if (clsMax.first == 0 || clsMax.first + 3 * std::abs(clsMax.second) < clsTarget ) break; rMax += rMax; if (tries == 5) { oocoutE(nullptr,Eval) << "HypoTestInverter::RunLimit - Cannot determine upper limit of scan range. At " << r->GetName() @@ -828,7 +827,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur } clsMin = std::make_pair( fResults->GetLastYValue(), fResults->GetLastYError() ); } - if (clsMin.first != 1 && clsMin.first - 3 * fabs(clsMin.second) < clsTarget) { + if (clsMin.first != 1 && clsMin.first - 3 * std::abs(clsMin.second) < clsTarget) { if (fUseCLs) { rMin = 0; clsMin = CLs_t(1,0); // this is always true for CLs @@ -841,7 +840,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur continue; } clsMin = std::make_pair( fResults->GetLastYValue(), fResults->GetLastYError() ); - if (clsMin.first == 1 || clsMin.first - 3 * fabs(clsMin.second) > clsTarget) break; + if (clsMin.first == 1 || clsMin.first - 3 * std::abs(clsMin.second) > clsTarget) break; rMin += rMin; if (tries == 5) { oocoutE(nullptr,Eval) << "HypoTestInverter::RunLimit - Cannot determine lower limit of scan range. At " << r->GetName() @@ -897,7 +896,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur } // if sufficiently far away, drop one of the points - if (fabs(clsMid.first-clsTarget) >= 2*clsMid.second) { + if (std::abs(clsMid.first-clsTarget) >= 2*clsMid.second) { if ((clsMid.first>clsTarget) == (clsMax.first>clsTarget)) { rMax = limit; clsMax = clsMid; } else { @@ -907,24 +906,24 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur if (fVerbose > 0) std::cout << "Trying to move the interval edges closer" << std::endl; double rMinBound = rMin, rMaxBound = rMax; // try to reduce the size of the interval - while (clsMin.second == 0 || fabs(rMin-limit) > std::max(absAccuracy, relAccuracy * limit)) { + while (clsMin.second == 0 || std::abs(rMin-limit) > std::max(absAccuracy, relAccuracy * limit)) { rMin = 0.5*(rMin+limit); if (!RunOnePoint(rMin,true, clsTarget) ) { oocoutE(nullptr,Eval) << "HypoTestInverter::RunLimit - Hypo test failed at x=" << rMin << " when trying to find limit from below." << std::endl; return false; } clsMin = std::make_pair( fResults->GetLastYValue(), fResults->GetLastYError() ); - if (fabs(clsMin.first-clsTarget) <= 2*clsMin.second) break; + if (std::abs(clsMin.first-clsTarget) <= 2*clsMin.second) break; rMinBound = rMin; } - while (clsMax.second == 0 || fabs(rMax-limit) > std::max(absAccuracy, relAccuracy * limit)) { + while (clsMax.second == 0 || std::abs(rMax-limit) > std::max(absAccuracy, relAccuracy * limit)) { rMax = 0.5*(rMax+limit); if (!RunOnePoint(rMax,true,clsTarget) ) { oocoutE(nullptr,Eval) << "HypoTestInverter::RunLimit - Hypo test failed at x=" << rMin << " when trying to find limit from above." << std::endl; return false; } clsMax = std::make_pair( fResults->GetLastYValue(), fResults->GetLastYError() ); - if (fabs(clsMax.first-clsTarget) <= 2*clsMax.second) break; + if (std::abs(clsMax.first-clsTarget) <= 2*clsMax.second) break; rMaxBound = rMax; } expoFit.SetRange(rMinBound,rMaxBound); @@ -942,7 +941,7 @@ bool HypoTestInverter::RunLimit(double &limit, double &limitErr, double absAccur expoFit.SetParameter(1,log(clsMax.first/clsMin.first)/(rMax-rMin)); expoFit.SetParameter(2,limit); double rMinBound, rMaxBound; expoFit.GetRange(rMinBound, rMaxBound); - limitErr = std::max(fabs(rMinBound-limit), fabs(rMaxBound-limit)); + limitErr = std::max(std::abs(rMinBound-limit), std::abs(rMaxBound-limit)); int npoints = 0; HypoTestInverterPlot plot("plot","plot",fResults); @@ -1025,13 +1024,13 @@ SamplingDistribution * HypoTestInverter::GetLowerLimitDistribution(bool rebuild, if (!rebuild) { if (!fResults) { oocoutE(nullptr,InputArguments) << "HypoTestInverter::GetLowerLimitDistribution(false) - result not existing\n"; - return 0; + return nullptr; } return fResults->GetLowerLimitDistribution(); } - TList * clsDist = 0; - TList * clsbDist = 0; + TList * clsDist = nullptr; + TList * clsbDist = nullptr; if (fUseCLs) clsDist = &fResults->fExpPValues; else clsbDist = &fResults->fExpPValues; @@ -1052,13 +1051,13 @@ SamplingDistribution * HypoTestInverter::GetUpperLimitDistribution(bool rebuild, if (!rebuild) { if (!fResults) { oocoutE(nullptr,InputArguments) << "HypoTestInverter::GetUpperLimitDistribution(false) - result not existing\n"; - return 0; + return nullptr; } return fResults->GetUpperLimitDistribution(); } - TList * clsDist = 0; - TList * clsbDist = 0; + TList * clsDist = nullptr; + TList * clsbDist = nullptr; if (fUseCLs) clsDist = &fResults->fExpPValues; else clsbDist = &fResults->fExpPValues; @@ -1082,13 +1081,13 @@ void HypoTestInverter::SetData(RooAbsData & data) { SamplingDistribution * HypoTestInverter::RebuildDistributions(bool isUpper, int nToys, TList * clsDist, TList * clsbDist, TList * clbDist, const char *outputfile) { - if (!fScannedVariable || !fCalculator0) return 0; + if (!fScannedVariable || !fCalculator0) return nullptr; // get first background snapshot const ModelConfig * bModel = fCalculator0->GetAlternateModel(); const ModelConfig * sbModel = fCalculator0->GetNullModel(); - if (!bModel || ! sbModel) return 0; + if (!bModel || ! sbModel) return nullptr; RooArgSet paramPoint; - if (!sbModel->GetParametersOfInterest()) return 0; + if (!sbModel->GetParametersOfInterest()) return nullptr; paramPoint.add(*sbModel->GetParametersOfInterest()); const RooArgSet * poibkg = bModel->GetSnapshot(); @@ -1105,7 +1104,7 @@ SamplingDistribution * HypoTestInverter::RebuildDistributions(bool isUpper, int ToyMCSampler * toymcSampler = dynamic_cast(fCalculator0->GetTestStatSampler() ); if (!toymcSampler) { oocoutE(nullptr,InputArguments) << "HypoTestInverter::RebuildDistribution - no toy MC sampler existing" << std::endl; - return 0; + return nullptr; } // set up test stat sampler in case of asymptotic calculator if (dynamic_cast(fCalculator0) ) { @@ -1134,7 +1133,7 @@ SamplingDistribution * HypoTestInverter::RebuildDistributions(bool isUpper, int if (nPoints <=0) { oocoutE(nullptr,InputArguments) << "HypoTestInverter - result is not existing and number of point to scan is not set" << std::endl; - return 0; + return nullptr; } } @@ -1167,7 +1166,7 @@ SamplingDistribution * HypoTestInverter::RebuildDistributions(bool isUpper, int // save all parameters to restore them later assert(bModel->GetPdf() ); assert(bModel->GetObservables() ); - RooArgSet * allParams = bModel->GetPdf()->getParameters( *bModel->GetObservables() ); + std::unique_ptr allParams{bModel->GetPdf()->getParameters( *bModel->GetObservables() )}; RooArgSet saveParams; allParams->snapshot(saveParams); @@ -1240,7 +1239,7 @@ SamplingDistribution * HypoTestInverter::RebuildDistributions(bool isUpper, int HypoTestInverterResult * r = inverter.GetInterval(); - if (r == 0) continue; + if (r == nullptr) continue; double value = (isUpper) ? r->UpperLimit() : r->LowerLimit(); limit_values.push_back( value ); diff --git a/roofit/roostats/src/HypoTestInverterPlot.cxx b/roofit/roostats/src/HypoTestInverterPlot.cxx index 39cd9f044efd5..bb46fdbc821ef 100644 --- a/roofit/roostats/src/HypoTestInverterPlot.cxx +++ b/roofit/roostats/src/HypoTestInverterPlot.cxx @@ -126,7 +126,7 @@ TGraphErrors* HypoTestInverterPlot::MakePlot(Option_t * opt) xArray.push_back(fResults->GetXValue(index[i])); } - TGraphErrors* graph = new TGraphErrors(static_cast(xArray.size()),&xArray.front(),&yArray.front(),0,&yErrArray.front()); + TGraphErrors* graph = new TGraphErrors(static_cast(xArray.size()),&xArray.front(),&yArray.front(),nullptr,&yErrArray.front()); TString pValueName = "CLs"; if (type == CLb ) pValueName = "CLb"; if (type == CLsPlusb || (type == Default && !fResults->fUseCLs) ) pValueName = "CLs+b"; @@ -165,8 +165,8 @@ TMultiGraph* HypoTestInverterPlot::MakeExpectedPlot(double nsig1, double nsig2 ) TString pValueName = "CLs"; if (!fResults->fUseCLs) pValueName = "CLs+b"; g0->SetTitle(TString::Format("Expected %s - Median",pValueName.Data()) ); - TGraphAsymmErrors * g1 = 0; - TGraphAsymmErrors * g2 = 0; + TGraphAsymmErrors * g1 = nullptr; + TGraphAsymmErrors * g2 = nullptr; if (doFirstBand) { g1 = new TGraphAsymmErrors; if (nsig1 - int(nsig1) < 0.01) @@ -219,7 +219,7 @@ TMultiGraph* HypoTestInverterPlot::MakeExpectedPlot(double nsig1, double nsig2 ) g0->SetPoint(np, fResults->GetXValue(i), q[2]); if (g1) { g1->SetPoint(np, fResults->GetXValue(i), q[2]); - g1->SetPointEYlow(np, q[2] - q[1]); // -1 sigma errorr + g1->SetPointEYlow(np, q[2] - q[1]); // -1 sigma error g1->SetPointEYhigh(np, q[3] - q[2]);//+1 sigma error } if (g2) { @@ -282,8 +282,8 @@ void HypoTestInverterPlot::Draw(Option_t * opt) { bool drawCLb = option.Contains("CLB"); bool draw2CL = option.Contains("2CL"); - TGraphErrors * gobs = 0; - TGraph * gplot = 0; + TGraphErrors * gobs = nullptr; + TGraph * gplot = nullptr; if (drawObs) { gobs = MakePlot(); // add object to top-level directory to avoid mem leak @@ -296,7 +296,7 @@ void HypoTestInverterPlot::Draw(Option_t * opt) { else gobs->Draw("PL"); } - TMultiGraph * gexp = 0; + TMultiGraph * gexp = nullptr; if (drawExp) { gexp = MakeExpectedPlot(); // add object to current directory to avoid mem leak @@ -326,7 +326,7 @@ void HypoTestInverterPlot::Draw(Option_t * opt) { } - TGraph *gclb = 0; + TGraph *gclb = nullptr; if (drawCLb) { gclb = MakePlot("CLb"); if (gROOT) gROOT->Add(gclb); @@ -335,8 +335,8 @@ void HypoTestInverterPlot::Draw(Option_t * opt) { // draw in red observed cls or clsb if (gobs) gobs->SetMarkerColor(kRed); } - TGraph * gclsb = 0; - TGraph * gcls = 0; + TGraph * gclsb = nullptr; + TGraph * gcls = nullptr; if (draw2CL) { if (fResults->fUseCLs) { gclsb = MakePlot("CLs+b"); @@ -392,7 +392,7 @@ void HypoTestInverterPlot::Draw(Option_t * opt) { /// - type = 2 only alt (B) SamplingDistPlot * HypoTestInverterPlot::MakeTestStatPlot(int index, int type, int nbins) { - SamplingDistPlot * pl = 0; + SamplingDistPlot * pl = nullptr; if (type == 0) { HypoTestResult * result = (HypoTestResult*) fResults->fYObjects.At(index); if (result) @@ -415,5 +415,5 @@ SamplingDistPlot * HypoTestInverterPlot::MakeTestStatPlot(int index, int type, i return pl; } } - return 0; + return nullptr; } diff --git a/roofit/roostats/src/HypoTestInverterResult.cxx b/roofit/roostats/src/HypoTestInverterResult.cxx index c2e8f4a3bdca6..92a5864da3922 100644 --- a/roofit/roostats/src/HypoTestInverterResult.cxx +++ b/roofit/roostats/src/HypoTestInverterResult.cxx @@ -171,8 +171,7 @@ HypoTestInverterResult::HypoTestInverterResult( const char* name, // to avoid I/O problem of the Result class - // make the set owning the cloned copy (use clone instead of Clone to not copying all links) fParameters.removeAll(); - fParameters.takeOwnership(); - fParameters.addOwned(*((RooRealVar *) scannedVariable.clone(scannedVariable.GetName()) )); + fParameters.addOwned(std::unique_ptr{static_cast(scannedVariable.clone(scannedVariable.GetName()))}); } //////////////////////////////////////////////////////////////////////////////// @@ -216,7 +215,7 @@ int HypoTestInverterResult::ExclusionCleanup() bool resultIsAsymptotic(false); if (nEntries>=1) { HypoTestResult* r = dynamic_cast ( GetResult(0) ); - assert(r!=0); + assert(r!=nullptr); if ( !r->GetNullDistribution() && !r->GetAltDistribution() ) { resultIsAsymptotic = true; } @@ -354,7 +353,7 @@ bool HypoTestInverterResult::Add( const HypoTestInverterResult& otherResult ) for (int i = 0; i < nOther; ++i) { double otherVal = otherResult.fXValues[i]; HypoTestResult * otherHTR = (HypoTestResult*) otherResult.fYObjects.At(i); - if (otherHTR == 0) continue; + if (otherHTR == nullptr) continue; bool sameXFound = false; for (int j = 0; j < nThis; ++j) { double thisVal = fXValues[j]; @@ -552,7 +551,7 @@ HypoTestResult* HypoTestInverterResult::GetResult( int index ) const { if ( index >= ArraySize() || index<0 ) { coutE(InputArguments) << "Problem: You are asking for an impossible array index value\n"; - return 0; + return nullptr; } return ((HypoTestResult*) fYObjects.At(index)); @@ -623,7 +622,7 @@ double HypoTestInverterResult::GetGraphX(const TGraph & graph, double y0, bool l if (axmin >= axmax ) { #ifdef DO_DEBUG - std::cout << "No rage given - check if extrapolation is needed " << std::endl; + std::cout << "No range given - check if extrapolation is needed " << std::endl; #endif xmin = graph.GetX()[0]; @@ -827,7 +826,7 @@ double HypoTestInverterResult::FindInterpolatedLimit(double target, bool lowSear std::cout << "finding " << lowSearch << " limit between " << xmin << " " << xmax << endl; #endif - // compute noe the limit using the TGraph interpolations routine + // compute now the limit using the TGraph interpolations routine double limit = GetGraphX(graph, target, lowSearch, xmin, xmax); if (lowSearch) fLowerLimit = limit; else fUpperLimit = limit; @@ -892,7 +891,7 @@ int HypoTestInverterResult::FindClosestPointIndex(double target, int mode, doubl double smallestError = 2; // error must be < 1 double bestValue = 2; for (int i=0; i GetXValue(indx[index2])) ? indx[index1] : indx[index2]; // get smaller point of the two (mode == 1) - if (fabs(GetYValue(indx[index1])-target) <= fabs(GetYValue(indx[index2])-target) ) + if (std::abs(GetYValue(indx[index1])-target) <= std::abs(GetYValue(indx[index2])-target) ) return indx[index1]; return indx[index2]; @@ -1063,7 +1062,7 @@ double HypoTestInverterResult::CalculateEstimatedError(double target, bool lower double errY = GetYError(index); if (errY > 0) { double m = fct.Derivative( GetXValue(index) ); - theError = std::min(fabs( GetYError(index) / m), maxX-minX); + theError = std::min(std::abs( GetYError(index) / m), maxX-minX); } } else { @@ -1109,7 +1108,7 @@ double HypoTestInverterResult::UpperLimitEstimatedError() SamplingDistribution * HypoTestInverterResult::GetBackgroundTestStatDist(int index ) const { HypoTestResult * firstResult = (HypoTestResult*) fYObjects.At(index); - if (!firstResult) return 0; + if (!firstResult) return nullptr; return firstResult->GetBackGroundIsAlt() ? firstResult->GetAltDistribution() : firstResult->GetNullDistribution(); } @@ -1118,7 +1117,7 @@ SamplingDistribution * HypoTestInverterResult::GetBackgroundTestStatDist(int in SamplingDistribution * HypoTestInverterResult::GetSignalAndBackgroundTestStatDist(int index) const { HypoTestResult * result = (HypoTestResult*) fYObjects.At(index); - if (!result) return 0; + if (!result) return nullptr; return !result->GetBackGroundIsAlt() ? result->GetAltDistribution() : result->GetNullDistribution(); } @@ -1127,7 +1126,7 @@ SamplingDistribution * HypoTestInverterResult::GetSignalAndBackgroundTestStatDi SamplingDistribution * HypoTestInverterResult::GetExpectedPValueDist(int index) const { - if (index < 0 || index >= ArraySize() ) return 0; + if (index < 0 || index >= ArraySize() ) return nullptr; if (fExpPValues.GetSize() == ArraySize() ) { return (SamplingDistribution*) fExpPValues.At(index)->Clone(); @@ -1170,7 +1169,7 @@ SamplingDistribution * HypoTestInverterResult::GetExpectedPValueDist(int index) for (int i = 0; i < npoints; ++i) { double nsig = -smax + dsig*i; double pval = AsymptoticCalculator::GetExpectedPValues( result->NullPValue(), result->AlternatePValue(), nsig, fUseCLs, !fIsTwoSided); - if (pval < 0) { return 0;} + if (pval < 0) { return nullptr;} values[i] = pval; } return new SamplingDistribution("Asymptotic expected values","Asymptotic expected values",values); @@ -1185,7 +1184,7 @@ SamplingDistribution * HypoTestInverterResult::GetLimitDistribution(bool lower if (ArraySize()<2) { coutE(Eval) << "HypoTestInverterResult::GetLimitDistribution" << " not enough points - return 0 " << std::endl; - return 0; + return nullptr; } ooccoutD(this,Eval) << "HypoTestInverterResult - computing limit distribution...." << std::endl; @@ -1222,7 +1221,7 @@ SamplingDistribution * HypoTestInverterResult::GetLimitDistribution(bool lower // make quantiles from the sampling distributions of the expected p values std::vector pvalues = distVec[i]->GetSamplingDistribution(); - delete distVec[i]; distVec[i] = 0; + delete distVec[i]; distVec[i] = nullptr; std::sort(pvalues.begin(), pvalues.end()); // find the quantiles of the distribution double p[1] = {0}; @@ -1233,7 +1232,7 @@ SamplingDistribution * HypoTestInverterResult::GetLimitDistribution(bool lower // exclude for a bug in TMath::Quantiles last item p[0] = std::min( (ibin+1) * 1./double(size), 1.0); // use the type 1 which give the point value - TMath::Quantiles(pvalues.size(), 1, &pvalues[0], q, p, true, 0, 1 ); + TMath::Quantiles(pvalues.size(), 1, &pvalues[0], q, p, true, nullptr, 1 ); (quantVec[i])[ibin] = q[0]; } @@ -1253,7 +1252,7 @@ SamplingDistribution * HypoTestInverterResult::GetLimitDistribution(bool lower TGraph g; for (int k = 0; k < npoints ; ++k) { - if (quantVec[index[k]].size() > 0 ) + if (!quantVec[index[k]].empty() ) g.SetPoint(g.GetN(), GetXValue(index[k]), (quantVec[index[k]])[j] ); } @@ -1318,7 +1317,7 @@ double HypoTestInverterResult::GetExpectedLimit(double nsig, bool lower, const if (nEntries <= 0) return (lower) ? 1 : 0; // return 1 for lower, 0 for upper HypoTestResult * r = dynamic_cast (fYObjects.First() ); - assert(r != 0); + assert(r != nullptr); if (!r->GetNullDistribution() && !r->GetAltDistribution() ) { // we are in the asymptotic case // get the limits obtained at the different sigma values diff --git a/roofit/roostats/src/HypoTestResult.cxx b/roofit/roostats/src/HypoTestResult.cxx index 8ccc16d5260d3..980539bb09171 100644 --- a/roofit/roostats/src/HypoTestResult.cxx +++ b/roofit/roostats/src/HypoTestResult.cxx @@ -110,9 +110,9 @@ HypoTestResult::HypoTestResult(const char* name, double nullp, double altp) : HypoTestResult::HypoTestResult(const HypoTestResult& other) : TNamed(other), - fNullPValue(NaN), fAlternatePValue(NaN), - fNullPValueError(0), fAlternatePValueError(0), - fTestStatisticData(NaN), + fNullPValue(other.fNullPValue), fAlternatePValue(other.fAlternatePValue), + fNullPValueError(other.fNullPValueError), fAlternatePValueError(other.fAlternatePValueError), + fTestStatisticData(other.fTestStatisticData), fAllTestStatisticsData(nullptr), fNullDistr(nullptr), fAltDistr(nullptr), fNullDetailedOutput(nullptr), fAltDetailedOutput(nullptr), @@ -197,7 +197,7 @@ void HypoTestResult::Append(const HypoTestResult* other) { if( fFitInfo ) { if( other->GetFitInfo() ) fFitInfo->append( *other->GetFitInfo() ); }else{ - if( other->GetFitInfo() ) fFitInfo.reset(new RooDataSet( *other->GetFitInfo() )); + if( other->GetFitInfo() ) fFitInfo = std::make_unique( *other->GetFitInfo()); } // if no data is present use the other HypoTestResult's data @@ -235,7 +235,7 @@ void HypoTestResult::SetTestStatisticData(const double tsd) { void HypoTestResult::SetAllTestStatisticsData(const RooArgList* tsd) { if (fAllTestStatisticsData) { delete fAllTestStatisticsData; - fAllTestStatisticsData = 0; + fAllTestStatisticsData = nullptr; } if (tsd) fAllTestStatisticsData = (const RooArgList*)tsd->snapshot(); diff --git a/roofit/roostats/src/LikelihoodInterval.cxx b/roofit/roostats/src/LikelihoodInterval.cxx index 468cb1920ca1d..302b0d82960be 100644 --- a/roofit/roostats/src/LikelihoodInterval.cxx +++ b/roofit/roostats/src/LikelihoodInterval.cxx @@ -63,7 +63,7 @@ #include #include #include -#include // need to use c version of toupper defined here +#include // need to use c version of toupper defined here ClassImp(RooStats::LikelihoodInterval); ; @@ -76,7 +76,7 @@ using namespace std; /// Default constructor with name and title LikelihoodInterval::LikelihoodInterval(const char* name) : - ConfInterval(name), fBestFitParams(0), fLikelihoodRatio(0), fConfidenceLevel(0.95) + ConfInterval(name), fBestFitParams(nullptr), fLikelihoodRatio(nullptr), fConfidenceLevel(0.95) { } @@ -129,7 +129,7 @@ bool LikelihoodInterval::IsInInterval(const RooArgSet ¶meterPoint) const // set parameters - SetParameters(¶meterPoint, fLikelihoodRatio->getVariables() ); + SetParameters(¶meterPoint, std::unique_ptr{fLikelihoodRatio->getVariables()}.get()); // evaluate likelihood ratio, see if it's bigger than threshold @@ -227,12 +227,11 @@ bool LikelihoodInterval::CreateMinimizer() { // bind the nll function in the right interface for the Minimizer class // as a function of only the parameters (poi + nuisance parameters) - RooArgSet * partmp = profilell->getVariables(); + std::unique_ptr partmp{profilell->getVariables()}; // need to remove constant parameters - RemoveConstantParameters(partmp); + RemoveConstantParameters(&*partmp); RooArgList params(*partmp); - delete partmp; // need to restore values and errors for POI if (fBestFitParams) { @@ -283,7 +282,7 @@ bool LikelihoodInterval::CreateMinimizer() { } // for finding the contour need to find first global minimum bool iret = fMinimizer->Minimize(); - if (!iret || fMinimizer->X() == 0) { + if (!iret || fMinimizer->X() == nullptr) { ccoutE(Minimization) << "Error: Minimization failed " << std::endl; return false; } @@ -311,10 +310,9 @@ bool LikelihoodInterval::FindLimits(const RooRealVar & param, double &lower, dou } - RooArgSet * partmp = fLikelihoodRatio->getVariables(); - RemoveConstantParameters(partmp); + std::unique_ptr partmp{fLikelihoodRatio->getVariables()}; + RemoveConstantParameters(&*partmp); RooArgList params(*partmp); - delete partmp; int ix = params.index(¶m); if (ix < 0 ) { ccoutE(InputArguments) << "Error - invalid parameter " << param.GetName() << " specified for finding the interval limits " << std::endl; @@ -375,10 +373,9 @@ Int_t LikelihoodInterval::GetContourPoints(const RooRealVar & paramX, const RooR // check the parameters // variable index in minimizer // is index in the RooArgList obtained from the profileLL variables - RooArgSet * partmp = fLikelihoodRatio->getVariables(); - RemoveConstantParameters(partmp); + std::unique_ptr partmp{fLikelihoodRatio->getVariables()}; + RemoveConstantParameters(&*partmp); RooArgList params(*partmp); - delete partmp; int ix = params.index(¶mX); int iy = params.index(¶mY); if (ix < 0 || iy < 0) { diff --git a/roofit/roostats/src/LikelihoodIntervalPlot.cxx b/roofit/roostats/src/LikelihoodIntervalPlot.cxx index c43e8ab0ede4d..3a9d6fa21a2c6 100644 --- a/roofit/roostats/src/LikelihoodIntervalPlot.cxx +++ b/roofit/roostats/src/LikelihoodIntervalPlot.cxx @@ -59,9 +59,9 @@ using namespace RooStats; LikelihoodIntervalPlot::LikelihoodIntervalPlot() { - fInterval = 0; + fInterval = nullptr; fNdimPlot = 0; - fParamsPlot = 0; + fParamsPlot = nullptr; fColor = 0; fFillStyle = 4050; // half transparent fLineColor = 0; @@ -73,7 +73,7 @@ LikelihoodIntervalPlot::LikelihoodIntervalPlot() fYmin = 0; fYmax = -1; fPrecision = -1; // use default - fPlotObject = 0; + fPlotObject = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -95,7 +95,7 @@ LikelihoodIntervalPlot::LikelihoodIntervalPlot(LikelihoodInterval* theInterval) fYmin = 0; fYmax = -1; fPrecision = -1; // use default - fPlotObject = 0; + fPlotObject = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -189,13 +189,15 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) // if the number of parameters to plot is less to the number of parameters of the LikelihoodInterval // we need to re-do the profile likelihood function, otherwise those parameters will not be profiled // when plotting - RooAbsReal* newProfile = 0; + RooAbsReal* newProfile = nullptr; + std::unique_ptr newProfileOwner; RooAbsReal* oldProfile = fInterval->GetLikelihoodRatio(); if (fNdimPlot != intervalParams->getSize() ) { RooProfileLL * profilell = dynamic_cast(oldProfile); if (!profilell) return; RooAbsReal & nll = profilell->nll(); - newProfile = nll.createProfile(*fParamsPlot); + newProfileOwner = std::unique_ptr{nll.createProfile(*fParamsPlot)}; + newProfile = newProfileOwner.get(); } else { newProfile = oldProfile; @@ -242,7 +244,7 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) if (fColor == 0) fColor = kBlue; if (fLineColor == 0) fLineColor = kGreen; - RooPlot * frame = 0; + RooPlot * frame = nullptr; // use TF1 for drawing the function if (!useRooPlot) { @@ -253,7 +255,7 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) if (fXmin < fXmax) { xmin = fXmin; xmax = fXmax; } TF1 * tmp = newProfile->asTF(*myarg); - assert(tmp != 0); + assert(tmp != nullptr); tmp->SetRange(xmin, xmax); tmp->SetNpx(nPoints); @@ -409,7 +411,7 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) TString histName = TString::Format("_hist2D__%s_%s",myparam->GetName(),myparamY->GetName() ); int nBins = int( std::sqrt(double(nPoints)) + 0.5 ); TH2* hist2D = new TH2D(histName, title, nBins, xmin, xmax, nBins, ymin, ymax ); - newProfile->fillHistogram(hist2D, RooArgList(*myparam,*myparamY), 1, 0, false, 0, false); + newProfile->fillHistogram(hist2D, RooArgList(*myparam,*myparamY), 1, nullptr, false, nullptr, false); hist2D->SetTitle(title); hist2D->SetStats(false); @@ -470,7 +472,7 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) // get graphs from the contours TObjArray *contoursOrig = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); // CLONE THE LIST IN CASE IT GETS DELETED - TObjArray *contours = 0; + TObjArray *contours = nullptr; if (contoursOrig) contours = (TObjArray*) contoursOrig->Clone(); delete tmpCanvas; @@ -593,8 +595,5 @@ void LikelihoodIntervalPlot::Draw(const Option_t *options) } - // need to delete if a new profileLL was made - if (newProfile != oldProfile) delete newProfile; - return; } diff --git a/roofit/roostats/src/MCMCCalculator.cxx b/roofit/roostats/src/MCMCCalculator.cxx index 78c78a787a041..e42c2f007ddc5 100644 --- a/roofit/roostats/src/MCMCCalculator.cxx +++ b/roofit/roostats/src/MCMCCalculator.cxx @@ -57,11 +57,11 @@ using namespace std; /// default constructor MCMCCalculator::MCMCCalculator() : - fPropFunc(0), - fPdf(0), - fPriorPdf(0), - fData(0), - fAxes(0) + fPropFunc(nullptr), + fPdf(nullptr), + fPriorPdf(nullptr), + fData(nullptr), + fAxes(nullptr) { fNumIters = 0; fNumBurnInSteps = 0; @@ -80,9 +80,9 @@ MCMCCalculator::MCMCCalculator() : /// by SetupBasicUsage() MCMCCalculator::MCMCCalculator(RooAbsData& data, const ModelConfig & model) : - fPropFunc(0), + fPropFunc(nullptr), fData(&data), - fAxes(0) + fAxes(nullptr) { SetModel(model); SetupBasicUsage(); @@ -115,7 +115,7 @@ void MCMCCalculator::SetModel(const ModelConfig & model) { void MCMCCalculator::SetupBasicUsage() { - fPropFunc = 0; + fPropFunc = nullptr; fNumIters = 10000; fNumBurnInSteps = 40; fNumBins = 50; @@ -149,8 +149,8 @@ void MCMCCalculator::SetLeftSideTailFraction(double a) MCMCInterval* MCMCCalculator::GetInterval() const { - if (!fData || !fPdf ) return 0; - if (fPOI.empty()) return 0; + if (!fData || !fPdf ) return nullptr; + if (fPOI.empty()) return nullptr; if (fSize < 0) { coutE(InputArguments) << "MCMCCalculator::GetInterval: " @@ -159,8 +159,8 @@ MCMCInterval* MCMCCalculator::GetInterval() const } // if a proposal function has not been specified create a default one - bool useDefaultPropFunc = (fPropFunc == 0); - bool usePriorPdf = (fPriorPdf != 0); + bool useDefaultPropFunc = (fPropFunc == nullptr); + bool usePriorPdf = (fPriorPdf != nullptr); if (useDefaultPropFunc) fPropFunc = new UniformProposal(); // if prior is given create product @@ -170,18 +170,17 @@ MCMCInterval* MCMCCalculator::GetInterval() const prodPdf = new RooProdPdf(prodName,prodName,RooArgList(*fPdf,*fPriorPdf) ); } - RooArgSet* constrainedParams = prodPdf->getParameters(*fData); - RooAbsReal* nll = prodPdf->createNLL(*fData, Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),GlobalObservables(fGlobalObs)); - delete constrainedParams; + std::unique_ptr constrainedParams{prodPdf->getParameters(*fData)}; + std::unique_ptr nll{prodPdf->createNLL(*fData, Constrain(*constrainedParams),ConditionalObservables(fConditionalObs),GlobalObservables(fGlobalObs))}; - RooArgSet* params = nll->getParameters(*fData); - RemoveConstantParameters(params); + std::unique_ptr params{nll->getParameters(*fData)}; + RemoveConstantParameters(&*params); if (fNumBins > 0) { SetBins(*params, fNumBins); SetBins(fPOI, fNumBins); if (dynamic_cast(fPropFunc)) { - RooArgSet* proposalVars = ((PdfProposal*)fPropFunc)->GetPdf()-> - getParameters((RooAbsData*)nullptr); + std::unique_ptr proposalVars{((PdfProposal*)fPropFunc)->GetPdf()-> + getParameters((RooAbsData*)nullptr)}; SetBins(*proposalVars, fNumBins); } } @@ -216,8 +215,6 @@ MCMCInterval* MCMCCalculator::GetInterval() const if (useDefaultPropFunc) delete fPropFunc; if (usePriorPdf) delete prodPdf; - delete nll; - delete params; return interval; } diff --git a/roofit/roostats/src/MCMCInterval.cxx b/roofit/roostats/src/MCMCInterval.cxx index ee47902b219c8..e921f3c1d4228 100644 --- a/roofit/roostats/src/MCMCInterval.cxx +++ b/roofit/roostats/src/MCMCInterval.cxx @@ -356,14 +356,12 @@ void MCMCInterval::CreateKeysPdf() return; } - RooDataSet* chain = fChain->GetAsDataSet(SelectVars(fParameters), - EventRange(fNumBurnInSteps, fChain->Size())); + std::unique_ptr chain{fChain->GetAsDataSet(SelectVars(fParameters), + EventRange(fNumBurnInSteps, fChain->Size()))}; RooArgList* paramsList = new RooArgList(); for (Int_t i = 0; i < fDimension; i++) paramsList->add(*fAxes[i]); - // kbelasco: check for memory leaks with chain. who owns it? does - // RooNDKeysPdf take ownership? fKeysPdf = new RooNDKeysPdf("keysPDF", "Keys PDF", *paramsList, *chain, "a"); fCutoffVar = new RooRealVar("cutoff", "cutoff", 0); fHeaviside = new Heaviside("heaviside", "Heaviside", *fKeysPdf, *fCutoffVar); @@ -511,8 +509,8 @@ void MCMCInterval::CreateDataHist() return; } - fDataHist = fChain->GetAsDataHist(SelectVars(fParameters), - EventRange(fNumBurnInSteps, fChain->Size())); + fDataHist = std::unique_ptr{fChain->GetAsDataHist(SelectVars(fParameters), + EventRange(fNumBurnInSteps, fChain->Size()))}.release(); } //////////////////////////////////////////////////////////////////////////////// @@ -724,10 +722,8 @@ void MCMCInterval::DetermineByKeys() double cutoff = 0.0; fCutoffVar->setVal(cutoff); - RooAbsReal* integral = fProduct->createIntegral(fParameters, NormSet(fParameters)); - double full = integral->getVal(fParameters); + double full = std::unique_ptr{fProduct->createIntegral(fParameters, NormSet(fParameters))}->getVal(fParameters); fFull = full; - delete integral; if (full < 0.98) { coutW(Eval) << "Warning: Integral of Keys PDF came out to " << full << " instead of expected value 1. Will continue using this " @@ -1379,14 +1375,10 @@ double MCMCInterval::GetKeysPdfCutoff() double MCMCInterval::CalcConfLevel(double cutoff, double full) { - RooAbsReal* integral; - double confLevel; fCutoffVar->setVal(cutoff); - integral = fProduct->createIntegral(fParameters, NormSet(fParameters)); - confLevel = integral->getVal(fParameters) / full; + std::unique_ptr integral{fProduct->createIntegral(fParameters, NormSet(fParameters))}; + double confLevel = integral->getVal(fParameters) / full; coutI(Eval) << "cutoff = " << cutoff << ", conf = " << confLevel << endl; - //cout << "tmp: cutoff = " << cutoff << ", conf = " << confLevel << endl; - delete integral; return confLevel; } diff --git a/roofit/roostats/src/MCMCIntervalPlot.cxx b/roofit/roostats/src/MCMCIntervalPlot.cxx index a8bfd7a6b756c..42f066413dd89 100644 --- a/roofit/roostats/src/MCMCIntervalPlot.cxx +++ b/roofit/roostats/src/MCMCIntervalPlot.cxx @@ -222,7 +222,7 @@ void* MCMCIntervalPlot::DrawPosteriorKeysPdf(const Option_t* options) return nullptr; } if (isEmpty) - frame->SetTitle(Form("Posterior Keys PDF for %s", v->GetName())); + frame->SetTitle(("Posterior Keys PDF for " + std::string(v->GetName())).c_str()); else frame->SetTitle(GetTitle()); //fPosteriorKeysPdf->plotOn(frame); @@ -305,8 +305,7 @@ void MCMCIntervalPlot::DrawKeysPdfInterval(const Option_t* options) frame->SetTitle(nullptr); else frame->SetTitle(GetTitle()); - frame->GetYaxis()->SetTitle(Form("Posterior for parameter %s", - p->GetName())); + frame->GetYaxis()->SetTitle(("Posterior for parameter " + std::string(p->GetName())).c_str()); fPosteriorKeysPdf->plotOn(frame, RooFit::Normalization(1, RooAbsReal::Raw), RooFit::Range(ll, ul, false), @@ -397,10 +396,9 @@ void MCMCIntervalPlot::DrawHistInterval(const Option_t* options) hist->SetTitle(nullptr); else hist->SetTitle(GetTitle()); - hist->GetYaxis()->SetTitle(Form("Posterior for parameter %s", - p->GetName())); + hist->GetYaxis()->SetTitle(("Posterior for parameter " + std::string(p->GetName())).c_str()); hist->SetStats(false); - TH1F* copy = (TH1F*)hist->Clone(Form("%s_copy", hist->GetTitle())); + TH1F* copy = static_cast(hist->Clone((std::string(hist->GetTitle()) + "_copy").c_str())); double histCutoff = fInterval->GetHistCutoff(); Int_t i; diff --git a/roofit/roostats/src/MarkovChain.cxx b/roofit/roostats/src/MarkovChain.cxx index 3bfe430e6ad28..7b53da965f5ac 100644 --- a/roofit/roostats/src/MarkovChain.cxx +++ b/roofit/roostats/src/MarkovChain.cxx @@ -49,7 +49,6 @@ MarkovChain::MarkovChain() : fDataEntry = nullptr; fChain = nullptr; fNLL = nullptr; - fWeight = nullptr; } MarkovChain::MarkovChain(RooArgSet& parameters) : @@ -59,7 +58,6 @@ MarkovChain::MarkovChain(RooArgSet& parameters) : fDataEntry = nullptr; fChain = nullptr; fNLL = nullptr; - fWeight = nullptr; SetParameters(parameters); } @@ -70,7 +68,6 @@ MarkovChain::MarkovChain(const char* name, const char* title, fDataEntry = nullptr; fChain = nullptr; fNLL = nullptr; - fWeight = nullptr; SetParameters(parameters); } @@ -87,16 +84,13 @@ void MarkovChain::SetParameters(RooArgSet& parameters) // to see if that makes it possible to get values of variables without // doing string comparison RooRealVar nll(NLL_NAME, "-log Likelihood", 0); - RooRealVar weight(WEIGHT_NAME, "weight", 0); fDataEntry = new RooArgSet(); fDataEntry->addClone(parameters); fDataEntry->addClone(nll); - fDataEntry->addClone(weight); fNLL = (RooRealVar*)fDataEntry->find(NLL_NAME); - fWeight = (RooRealVar*)fDataEntry->find(WEIGHT_NAME); - fChain = new RooDataSet(DATASET_NAME, "Markov Chain", *fDataEntry,WEIGHT_NAME); + fChain = new RooDataSet(DATASET_NAME, "Markov Chain", *fDataEntry, RooFit::WeightVar(WEIGHT_NAME)); } void MarkovChain::Add(RooArgSet& entry, double nllValue, double weight) @@ -106,7 +100,6 @@ void MarkovChain::Add(RooArgSet& entry, double nllValue, double weight) RooStats::SetParameters(&entry, fDataEntry); fNLL->setVal(nllValue); //kbelasco: this is stupid, but some things might require it, so be doubly sure - fWeight->setVal(weight); fChain->add(*fDataEntry, weight); //fChain->add(*fDataEntry); } @@ -147,12 +140,11 @@ void MarkovChain::AddFast(RooArgSet& entry, double nllValue, double weight) RooStats::SetParameters(&entry, fDataEntry); fNLL->setVal(nllValue); //kbelasco: this is stupid, but some things might require it, so be doubly sure - fWeight->setVal(weight); fChain->addFast(*fDataEntry, weight); //fChain->addFast(*fDataEntry); } -RooDataSet* MarkovChain::GetAsDataSet(RooArgSet* whichVars) const +RooFit::OwningPtr MarkovChain::GetAsDataSet(RooArgSet* whichVars) const { RooArgSet args; if (whichVars == nullptr) { @@ -163,23 +155,19 @@ RooDataSet* MarkovChain::GetAsDataSet(RooArgSet* whichVars) const args.add(*whichVars); } - RooDataSet* data; - //data = dynamic_cast(fChain->reduce(args)); - data = (RooDataSet*)fChain->reduce(args); - - return data; + return RooFit::Detail::owningPtr(std::unique_ptr{fChain->reduce(args)}); } -RooDataSet* MarkovChain::GetAsDataSet(const RooCmdArg& arg1, const RooCmdArg& arg2, - const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, - const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const +RooFit::OwningPtr MarkovChain::GetAsDataSet(const RooCmdArg &arg1, const RooCmdArg &arg2, + const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6, + const RooCmdArg &arg7, const RooCmdArg &arg8) const { - RooDataSet* data; - data = (RooDataSet*)fChain->reduce(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); - return data; + return RooFit::Detail::owningPtr( + std::unique_ptr{fChain->reduce(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)}); } -RooDataHist* MarkovChain::GetAsDataHist(RooArgSet* whichVars) const +RooFit::OwningPtr MarkovChain::GetAsDataHist(RooArgSet* whichVars) const { RooArgSet args; if (whichVars == nullptr) { @@ -190,24 +178,17 @@ RooDataHist* MarkovChain::GetAsDataHist(RooArgSet* whichVars) const args.add(*whichVars); } - RooDataSet* data = (RooDataSet*)fChain->reduce(args); - RooDataHist* hist = data->binnedClone(); - delete data; - - return hist; + std::unique_ptr data{fChain->reduce(args)}; + return RooFit::Detail::owningPtr(std::unique_ptr{static_cast(*data).binnedClone()}); } -RooDataHist* MarkovChain::GetAsDataHist(const RooCmdArg& arg1, const RooCmdArg& arg2, - const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5, - const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const +RooFit::OwningPtr MarkovChain::GetAsDataHist(const RooCmdArg &arg1, const RooCmdArg &arg2, + const RooCmdArg &arg3, const RooCmdArg &arg4, + const RooCmdArg &arg5, const RooCmdArg &arg6, + const RooCmdArg &arg7, const RooCmdArg &arg8) const { - RooDataSet* data; - RooDataHist* hist; - data = (RooDataSet*)fChain->reduce(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); - hist = data->binnedClone(); - delete data; - - return hist; + std::unique_ptr data{fChain->reduce(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)}; + return RooFit::Detail::owningPtr(std::unique_ptr{static_cast(*data).binnedClone()}); } THnSparse* MarkovChain::GetAsSparseHist(RooAbsCollection* whichVars) const diff --git a/roofit/roostats/src/MetropolisHastings.cxx b/roofit/roostats/src/MetropolisHastings.cxx index 6a94b23061407..8c3af7568d5e2 100644 --- a/roofit/roostats/src/MetropolisHastings.cxx +++ b/roofit/roostats/src/MetropolisHastings.cxx @@ -95,7 +95,7 @@ MetropolisHastings::MetropolisHastings(RooAbsReal& function, const RooArgSet& pa MarkovChain* MetropolisHastings::ConstructChain() { if (fParameters.empty() || !fPropFunc || !fFunction) { - coutE(Eval) << "Critical members unintialized: parameters, proposal " << + coutE(Eval) << "Critical members uninitialized: parameters, proposal " << " function, or (log) likelihood function" << endl; return nullptr; } @@ -175,7 +175,7 @@ MarkovChain* MetropolisHastings::ConstructChain() } - ooccoutP((TObject *)0, Generation) << "Metropolis-Hastings progress: "; + ooccoutP((TObject *)nullptr, Generation) << "Metropolis-Hastings progress: "; // do main loop for (i = 0; i < fNumIters; i++) { @@ -183,7 +183,7 @@ MarkovChain* MetropolisHastings::ConstructChain() hadEvalError = false; // print a dot every 1% of the chain construction - if (i % (fNumIters / 100) == 0) ooccoutP((TObject*)0, Generation) << "."; + if (i % (fNumIters / 100) == 0) ooccoutP((TObject*)nullptr, Generation) << "."; fPropFunc->Propose(xPrime, x); @@ -241,7 +241,7 @@ MarkovChain* MetropolisHastings::ConstructChain() // make sure to add the last point if (weight != 0.0) chain->Add(x, CalcNLL(xL), (double)weight); - ooccoutP((TObject *)0, Generation) << endl; + ooccoutP((TObject *)nullptr, Generation) << endl; RooMsgService::instance().setGlobalKillBelow(oldMsgLevel); diff --git a/roofit/roostats/src/ModelConfig.cxx b/roofit/roostats/src/ModelConfig.cxx deleted file mode 100644 index 46a5f20dcc571..0000000000000 --- a/roofit/roostats/src/ModelConfig.cxx +++ /dev/null @@ -1,325 +0,0 @@ -// @(#)root/roostats:$Id$ -// Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss -/************************************************************************* - * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -/** \class RooStats::ModelConfig - \ingroup Roostats - -ModelConfig is a simple class that holds configuration information specifying how a model -should be used in the context of various RooStats tools. A single model can be used -in different ways, and this class should carry all that is needed to specify how it should be used. -ModelConfig requires a workspace to be set. - -A ModelConfig holds sets of parameters of the likelihood function that have different interpretations: -- **Parameter of interest** Parameters that are measured (*i.e.* fitted). -- **Nuisance parameters** Parameters that are fitted, but their post-fit value is not interesting. Often, -they might be constrained because external knowledge about them exists, *e.g.* from external measurements. -- **Constraint parameters** No direct use in RooFit/RooStats. Can be used by the user for bookkeeping. -- **Observables** Parameters that have been measured externally, *i.e.* they exist in a dataset. These are not fitted, -but read during fitting from the entries of a dataset. -- **Conditional observables** Observables that are not integrated when the normalisation of the PDF is calculated. -See *e.g.* `rf306_condpereventerrors` in the RooFit tutorials. -- **Global observables** Observables that to the fit look like "constant" values, *i.e.* they are not being -fitted and they are not loaded from a dataset, but some knowledge exists that allows to set them to a -specific value. Examples: --- A signal efficiency measured in a Monte Carlo study. --- When constraining a parameter \f$ b \f$, the target value (\f$ b_0 \f$) that this parameter is constrained to: -\f[ - \mathrm{Constraint}_b = \mathrm{Gauss}(b_0 \, | \, b, 0.2) -\f] -*/ - -#include "RooStats/ModelConfig.h" - -#include "RooMsgService.h" - -#include "RooStats/RooStatsUtils.h" - -#include - - -ClassImp(RooStats::ModelConfig); - -using namespace std; - -namespace RooStats { - -//////////////////////////////////////////////////////////////////////////////// -/// Makes sensible guesses of observables, parameters of interest -/// and nuisance parameters if one or multiple have been set by the creator of this ModelConfig. -/// -/// Defaults: -/// - Observables: determined from data, -/// - Global observables: explicit obs - obs from data - constant observables -/// - Parameters of interest: empty, -/// - Nuisance parameters: all parameters except parameters of interest -/// -/// We use nullptr to mean not set, so we don't want to fill -/// with empty RooArgSets. - -void ModelConfig::GuessObsAndNuisance(const RooAbsData& data, bool printModelConfig) { - - // observables - if (!GetObservables()) { - const RooArgSet * obs = GetPdf()->getObservables(data); - SetObservables(*obs); - delete obs; - } - // global observables - if (!GetGlobalObservables()) { - RooArgSet co(*GetObservables()); - const RooArgSet * obs = GetPdf()->getObservables(data); - co.remove(*obs); - RemoveConstantParameters(&co); - if(co.getSize()>0) - SetGlobalObservables(co); - - // TODO BUG This does not work as observables with the same name are already in the workspace. - /* - RooArgSet o(*GetObservables()); - o.remove(co); - SetObservables(o); - */ - delete obs; - } - - // parameters - // if (!GetParametersOfInterest()) { - // SetParametersOfInterest(RooArgSet()); - // } - if (!GetNuisanceParameters()) { - const RooArgSet * params = GetPdf()->getParameters(data); - RooArgSet p(*params); - p.remove(*GetParametersOfInterest()); - RemoveConstantParameters(&p); - if(p.getSize()>0) - SetNuisanceParameters(p); - delete params; - } - - // print Modelconfig as an info message - - if (printModelConfig) { - std::ostream& oldstream = RooPrintable::defaultPrintStream(&ccoutI(InputArguments)); - Print(); - RooPrintable::defaultPrintStream(&oldstream); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// print contents of Model on the default print stream -/// It can be changed using RooPrintable - -void ModelConfig::Print(Option_t*) const { - ostream& os = RooPrintable::defaultPrintStream(); - - os << endl << "=== Using the following for " << GetName() << " ===" << endl; - - - // args - if(GetObservables()){ - os << "Observables: "; - GetObservables()->Print(""); - } - if(GetParametersOfInterest()) { - os << "Parameters of Interest: "; - GetParametersOfInterest()->Print(""); - } - if(GetNuisanceParameters()){ - os << "Nuisance Parameters: "; - GetNuisanceParameters()->Print(""); - } - if(GetGlobalObservables()){ - os << "Global Observables: "; - GetGlobalObservables()->Print(""); - } - if(GetConstraintParameters()){ - os << "Constraint Parameters: "; - GetConstraintParameters()->Print(""); - } - if(GetConditionalObservables()){ - os << "Conditional Observables: "; - GetConditionalObservables()->Print(""); - } - if(GetProtoData()){ - os << "Proto Data: "; - GetProtoData()->Print(""); - } - - // pdfs - if(GetPdf()) { - os << "PDF: "; - GetPdf()->Print(""); - } - if(GetPriorPdf()) { - os << "Prior PDF: "; - GetPriorPdf()->Print(""); - } - - // snapshot - const RooArgSet * snapshot = GetSnapshot(); - if(snapshot) { - os << "Snapshot: " << endl; - snapshot->Print("v"); - delete snapshot; - } - - os << endl; -} - -//////////////////////////////////////////////////////////////////////////////// -/// If a workspace already exists in this ModelConfig, RooWorkspace::merge(ws) will be called -/// on the existing workspace. - -void ModelConfig::SetWS(RooWorkspace & ws) { - if( !fRefWS.GetObject() ) { - fRefWS = &ws; - fWSName = ws.GetName(); - } - else{ - RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ; - GetWS()->merge(ws); - RooMsgService::instance().setGlobalKillBelow(level) ; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// get from TRef - -RooWorkspace * ModelConfig::GetWS() const { - RooWorkspace *ws = dynamic_cast(fRefWS.GetObject() ); - if(!ws) { - coutE(ObjectHandling) << "workspace not set" << endl; - return nullptr; - } - return ws; -} - -//////////////////////////////////////////////////////////////////////////////// -/// save snapshot in the workspace -/// and use values passed with the set - -void ModelConfig::SetSnapshot(const RooArgSet& set) { - if ( !GetWS() ) return; - - fSnapshotName = GetName(); - if (fSnapshotName.size() > 0) fSnapshotName += "_"; - fSnapshotName += set.GetName(); - if (fSnapshotName.size() > 0) fSnapshotName += "_"; - fSnapshotName += "snapshot"; - GetWS()->saveSnapshot(fSnapshotName.c_str(), set, true); // import also the given parameter values - DefineSetInWS(fSnapshotName.c_str(), set); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Load the snapshot from ws and return the corresponding set with the snapshot values. -/// User must delete returned RooArgSet. - -const RooArgSet * ModelConfig::GetSnapshot() const{ - if ( !GetWS() ) return 0; - if (!fSnapshotName.length()) return 0; - // calling loadSnapshot will also copy the current parameter values in the workspaces - // since we do not want to change the model parameters - we restore the previous ones - if (! GetWS()->set(fSnapshotName.c_str() ) )return 0; - RooArgSet snapshotVars(*GetWS()->set(fSnapshotName.c_str() ) ); - if (snapshotVars.empty()) return 0; - // make my snapshot which will contain a copy of the snapshot variables - RooArgSet tempSnapshot; - snapshotVars.snapshot(tempSnapshot); - // load snapshot value from the workspace - if (!(GetWS()->loadSnapshot(fSnapshotName.c_str())) ) return 0; - // by doing this snapshotVars will have the snapshot values - make the snapshot to return - const RooArgSet * modelSnapshot = dynamic_cast( snapshotVars.snapshot()); - // restore now the variables of snapshot in ws to their original values - // need to const cast since assign is not const (but in reality in just assign values and does not change the set) - // and anyway the set is const - snapshotVars.assignFast(tempSnapshot); - return modelSnapshot; -} - -//////////////////////////////////////////////////////////////////////////////// -/// load the snapshot from ws if it exists - -void ModelConfig::LoadSnapshot() const{ - if ( !GetWS() ) return; - GetWS()->loadSnapshot(fSnapshotName.c_str()); -} - -//////////////////////////////////////////////////////////////////////////////// -/// helper functions to avoid code duplication - -void ModelConfig::DefineSetInWS(const char* name, const RooArgSet& set) { - if ( !GetWS() ) return; - - const RooArgSet * prevSet = GetWS()->set(name); - if ( prevSet ) { - //be careful not to remove passed set in case it is the same updated - if (prevSet != &set) - GetWS()->removeSet(name); - } - - // suppress warning when we re-define a previously defined set (when set == prevSet ) - // and set is not removed in that case - RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ; - - - GetWS()->defineSet(name, set,true); - - RooMsgService::instance().setGlobalKillBelow(level) ; - -} - -//////////////////////////////////////////////////////////////////////////////// -/// internal function to import Pdf in WS - -void ModelConfig::ImportPdfInWS(const RooAbsPdf & pdf) { - if ( !GetWS() ) return; - - if (! GetWS()->pdf( pdf.GetName() ) ){ - RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ; - GetWS()->import(pdf, RooFit::RecycleConflictNodes()); - RooMsgService::instance().setGlobalKillBelow(level) ; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// internal function to import data in WS - -void ModelConfig::ImportDataInWS(RooAbsData & data) { - if ( !GetWS() ) return; - - if (! GetWS()->data( data.GetName() ) ){ - RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow(); - RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ; - GetWS()->import(data); - RooMsgService::instance().setGlobalKillBelow(level) ; - } -} - -//////////////////////////////////////////////////////////////////////////////// - -bool ModelConfig::SetHasOnlyParameters(const RooArgSet& set, const char* errorMsgPrefix) { - - RooArgSet nonparams ; - for (auto const *arg : set) { - if (!arg->isFundamental()) { - nonparams.add(*arg) ; - } - } - - if (errorMsgPrefix && nonparams.getSize()>0) { - cout << errorMsgPrefix << " ERROR: specified set contains non-parameters: " << nonparams << endl ; - } - return (nonparams.empty()) ; - } - -} // end namespace RooStats diff --git a/roofit/roostats/src/NeymanConstruction.cxx b/roofit/roostats/src/NeymanConstruction.cxx index 6e931948dc5a9..2edd0e484743a 100644 --- a/roofit/roostats/src/NeymanConstruction.cxx +++ b/roofit/roostats/src/NeymanConstruction.cxx @@ -80,10 +80,10 @@ NeymanConstruction::NeymanConstruction(RooAbsData& data, ModelConfig& model): fSize(0.05), fData(data), fModel(model), - fTestStatSampler(0), - fPointsToTest(0), + fTestStatSampler(nullptr), + fPointsToTest(nullptr), fLeftSideFraction(0), - fConfBelt(0), // constructed with tree data + fConfBelt(nullptr), // constructed with tree data fAdaptiveSampling(false), fAdditionalNToysFactor(1.), fSaveBeltToFile(false), @@ -110,7 +110,7 @@ NeymanConstruction::~NeymanConstruction() { PointSetInterval* NeymanConstruction::GetInterval() const { - TFile* f=0; + TFile* f=nullptr; if(fSaveBeltToFile){ //coverity[FORWARD_NULL] oocoutI(f,Contents) << "NeymanConstruction saving ConfidenceBelt to file SamplingDistributions.root" << endl; @@ -152,7 +152,7 @@ PointSetInterval* NeymanConstruction::GetInterval() const { // find the lower & upper thresholds on the test statistic that // define the acceptance region in the data - SamplingDistribution* samplingDist=0; + SamplingDistribution* samplingDist=nullptr; double sigma; double upperEdgeOfAcceptance, upperEdgeMinusSigma, upperEdgePlusSigma; double lowerEdgeOfAcceptance, lowerEdgeMinusSigma, lowerEdgePlusSigma; @@ -191,7 +191,7 @@ PointSetInterval* NeymanConstruction::GetInterval() const { additionalMC); if (!samplingDist) { oocoutE(nullptr,Eval) << "Neyman Construction: error generating sampling distribution" << endl; - return 0; + return nullptr; } totalMC=samplingDist->GetSize(); @@ -240,7 +240,7 @@ PointSetInterval* NeymanConstruction::GetInterval() const { samplingDist = fTestStatSampler->GetSamplingDistribution(*point); if (!samplingDist) { oocoutE(nullptr,Eval) << "Neyman Construction: error generating sampling distribution" << endl; - return 0; + return nullptr; } lowerEdgeOfAcceptance = diff --git a/roofit/roostats/src/PdfProposal.cxx b/roofit/roostats/src/PdfProposal.cxx index 445c0c2b17bf7..b4d44f069cdab 100644 --- a/roofit/roostats/src/PdfProposal.cxx +++ b/roofit/roostats/src/PdfProposal.cxx @@ -77,7 +77,6 @@ PdfProposal::PdfProposal() : ProposalFunction() fOwnsPdf = false; fCacheSize = 1; fCachePosition = 0; - fCache = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -90,7 +89,6 @@ PdfProposal::PdfProposal(RooAbsPdf& pdf) : ProposalFunction() fOwnsPdf = false; fCacheSize = 1; fCachePosition = 0; - fCache = nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -118,15 +116,15 @@ void PdfProposal::Propose(RooArgSet& xPrime, RooArgSet& x) fLastX.addClone(x); // generate initial cache RooStats::SetParameters(&x, &fMaster); - if (fMap.size() > 0) { + if (!fMap.empty()) { for (fIt = fMap.begin(); fIt != fMap.end(); fIt++) fIt->first->setVal(fIt->second->getVal(&x)); } - fCache = fPdf->generate(xPrime, fCacheSize); + fCache = std::unique_ptr{fPdf->generate(xPrime, fCacheSize)}; } bool moved = false; - if (fMap.size() > 0) { + if (!fMap.empty()) { moved = !Equals(fLastX, x); // if we've moved, set the values of the variables in the PDF to the @@ -147,8 +145,7 @@ void PdfProposal::Propose(RooArgSet& xPrime, RooArgSet& x) // generate new cache if necessary if (moved || fCachePosition >= fCacheSize) { - delete fCache; - fCache = fPdf->generate(xPrime, fCacheSize); + fCache = std::unique_ptr{fPdf->generate(xPrime, fCacheSize)}; fCachePosition = 0; } @@ -159,7 +156,7 @@ void PdfProposal::Propose(RooArgSet& xPrime, RooArgSet& x) //////////////////////////////////////////////////////////////////////////////// /// Determine whether or not the proposal density is symmetric for -/// points x1 and x2 - that is, whether the probabilty of reaching x2 +/// points x1 and x2 - that is, whether the propabilty of reaching x2 /// from x1 is equal to the probability of reaching x1 from x2 bool PdfProposal::IsSymmetric(RooArgSet& /* x1 */, RooArgSet& /* x2 */) @@ -177,9 +174,8 @@ double PdfProposal::GetProposalDensity(RooArgSet& x1, RooArgSet& x2) RooStats::SetParameters(&x2, &fMaster); for (fIt = fMap.begin(); fIt != fMap.end(); fIt++) fIt->first->setVal(fIt->second->getVal(&x2)); - RooArgSet* temp = fPdf->getObservables(x1); - RooStats::SetParameters(&x1, temp); - delete temp; + std::unique_ptr temp{fPdf->getObservables(x1)}; + RooStats::SetParameters(&x1, temp.get()); return fPdf->getVal(&x1); // could just as well use x2 } @@ -197,5 +193,5 @@ void PdfProposal::AddMapping(RooRealVar& proposalParam, RooAbsReal& update) fMaster.add(*update.getParameters(static_cast(nullptr))); if (update.getParameters(static_cast(nullptr))->empty()) fMaster.add(update); - fMap.insert(pair(&proposalParam, &update)); + fMap.insert(std::pair(&proposalParam, &update)); } diff --git a/roofit/roostats/src/PointSetInterval.cxx b/roofit/roostats/src/PointSetInterval.cxx index 2e02ef51b0322..dd708b06b5a5f 100644 --- a/roofit/roostats/src/PointSetInterval.cxx +++ b/roofit/roostats/src/PointSetInterval.cxx @@ -48,7 +48,7 @@ using namespace RooStats; /// Default constructor PointSetInterval::PointSetInterval(const char* name) : - ConfInterval(name), fConfidenceLevel(0.95), fParameterPointsInInterval(0) + ConfInterval(name), fConfidenceLevel(0.95), fParameterPointsInInterval(nullptr) { } @@ -90,7 +90,7 @@ bool PointSetInterval::IsInInterval(const RooArgSet ¶meterPoint) const return false; } else if( tree ){ - const RooArgSet* thisPoint = 0; + const RooArgSet* thisPoint = nullptr; // need to check if the parameter point is the same as any point in tree. for(Int_t i = 0; inumEntries(); ++i){ // This method is not complete diff --git a/roofit/roostats/src/ProfileInspector.cxx b/roofit/roostats/src/ProfileInspector.cxx index bfc3a9211e1bc..31459fca89941 100644 --- a/roofit/roostats/src/ProfileInspector.cxx +++ b/roofit/roostats/src/ProfileInspector.cxx @@ -73,32 +73,32 @@ TList* ProfileInspector::GetListOfProfilePlots( RooAbsData& data, RooStats::Mode if(!poi_set){ cout << "no parameters of interest" << endl; - return 0; + return nullptr; } if(poi_set->getSize()!=1){ cout << "only one parameter of interest is supported currently" << endl; - return 0; + return nullptr; } RooRealVar* poi = (RooRealVar*) poi_set->first(); if(!nuis_params){ cout << "no nuisance parameters" << endl; - return 0; + return nullptr; } if(!pdf){ cout << "pdf not set" << endl; - return 0; + return nullptr; } - RooAbsReal* nll = pdf->createNLL(data); - RooAbsReal* profile = nll->createProfile(*poi); + std::unique_ptr nll{pdf->createNLL(data)}; + std::unique_ptr profile{nll->createProfile(*poi)}; TList * list = new TList; Int_t curve_N=100; - double* curve_x=0; + double* curve_x=nullptr; // if(curve){ // curve_N=curve->GetN(); // curve_x=curve->GetX(); @@ -140,8 +140,5 @@ TList* ProfileInspector::GetListOfProfilePlots( RooAbsData& data, RooStats::Mode delete [] curve_x; - - delete nll; - delete profile; return list; } diff --git a/roofit/roostats/src/ProfileLikelihoodCalculator.cxx b/roofit/roostats/src/ProfileLikelihoodCalculator.cxx index d1a69c8e6c254..e8eb04899d380 100644 --- a/roofit/roostats/src/ProfileLikelihoodCalculator.cxx +++ b/roofit/roostats/src/ProfileLikelihoodCalculator.cxx @@ -80,14 +80,14 @@ using namespace RooStats; /// default constructor ProfileLikelihoodCalculator::ProfileLikelihoodCalculator() : - CombinedCalculator(), fFitResult(0), fGlobalFitDone(false) + CombinedCalculator(), fGlobalFitDone(false) { } ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, RooAbsPdf& pdf, const RooArgSet& paramsOfInterest, double size, const RooArgSet* nullParams ) : CombinedCalculator(data,pdf, paramsOfInterest, size, nullParams ), - fFitResult(0), fGlobalFitDone(false) + fGlobalFitDone(false) { // constructor from pdf and parameters // the pdf must contain eventually the nuisance parameters @@ -95,7 +95,7 @@ ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, RooAb ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, ModelConfig& model, double size) : CombinedCalculator(data, model, size), - fFitResult(0), fGlobalFitDone(false) + fGlobalFitDone(false) { // construct from a ModelConfig. Assume data model.GetPdf() will provide full description of model including // constraint term on the nuisances parameters @@ -109,18 +109,15 @@ ProfileLikelihoodCalculator::ProfileLikelihoodCalculator(RooAbsData& data, Mode /// if (fOwnPdf) delete fPdf; /// fPdf = 0; -ProfileLikelihoodCalculator::~ProfileLikelihoodCalculator(){ - if (fFitResult) delete fFitResult; -} +ProfileLikelihoodCalculator::~ProfileLikelihoodCalculator() = default; void ProfileLikelihoodCalculator::DoReset() const { // reset and clear fit result // to be called when a new model or data are set in the calculator - if (fFitResult) delete fFitResult; - fFitResult = 0; + fFitResult.reset(); } -RooAbsReal * ProfileLikelihoodCalculator::DoGlobalFit() const { +RooFit::OwningPtr ProfileLikelihoodCalculator::DoGlobalFit() const { // perform a global fit of the likelihood letting with all parameter of interest and // nuisance parameters // keep the list of fitted parameters @@ -128,32 +125,30 @@ RooAbsReal * ProfileLikelihoodCalculator::DoGlobalFit() const { DoReset(); RooAbsPdf * pdf = GetPdf(); RooAbsData* data = GetData(); - if (!data || !pdf ) return 0; + if (!data || !pdf ) return nullptr; // get all non-const parameters - RooArgSet* constrainedParams = pdf->getParameters(*data); - if (!constrainedParams) return 0; - RemoveConstantParameters(constrainedParams); + std::unique_ptr constrainedParams{pdf->getParameters(*data)}; + if (!constrainedParams) return nullptr; + RemoveConstantParameters(&*constrainedParams); const auto& config = GetGlobalRooStatsConfig(); - RooAbsReal * nll = pdf->createNLL(*data, CloneData(true), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs), GlobalObservables(fGlobalObs), + auto nll = pdf->createNLL(*data, CloneData(true), Constrain(*constrainedParams),ConditionalObservables(fConditionalObs), GlobalObservables(fGlobalObs), RooFit::Offset(config.useLikelihoodOffset) ); // check if global fit has been already done if (fFitResult && fGlobalFitDone) { - delete constrainedParams; - return nll; + return RooFit::OwningPtr{std::move(nll)}; } // calculate MLE oocoutP(nullptr,Minimization) << "ProfileLikelihoodCalcultor::DoGLobalFit - find MLE " << std::endl; - if (fFitResult) delete fFitResult; - fFitResult = DoMinimizeNLL(nll); + fFitResult = std::unique_ptr{DoMinimizeNLL(&*nll)}; // print fit result if (fFitResult) { - fFitResult->printStream( oocoutI(nullptr,Minimization), fFitResult->defaultPrintContents(0), fFitResult->defaultPrintStyle(0) ); + fFitResult->printStream( oocoutI(nullptr,Minimization), fFitResult->defaultPrintContents(nullptr), fFitResult->defaultPrintStyle(nullptr) ); if (fFitResult->status() != 0) oocoutW(nullptr,Minimization) << "ProfileLikelihoodCalcultor::DoGlobalFit - Global fit failed - status = " << fFitResult->status() << std::endl; @@ -161,11 +156,10 @@ RooAbsReal * ProfileLikelihoodCalculator::DoGlobalFit() const { fGlobalFitDone = true; } - delete constrainedParams; - return nll; + return RooFit::OwningPtr{std::move(nll)}; } -RooFitResult * ProfileLikelihoodCalculator::DoMinimizeNLL(RooAbsReal * nll) { +RooFit::OwningPtr ProfileLikelihoodCalculator::DoMinimizeNLL(RooAbsReal * nll) { // Minimizer the given NLL using the default options const char * minimType = ""; // empty string to select RooMinimizer default @@ -190,7 +184,7 @@ RooFitResult * ProfileLikelihoodCalculator::DoMinimizeNLL(RooAbsReal * nll) { int status = -1; for (int tries = 1, maxtries = 4; tries <= maxtries; ++tries) { status = minim.minimize(minimType,minimAlgo); - if (status%1000 == 0) { // ignore erros from Improve + if (status%1000 == 0) { // ignore errors from Improve break; } else if (tries < maxtries) { cout << " ----> Doing a re-scan first" << endl; @@ -211,10 +205,7 @@ RooFitResult * ProfileLikelihoodCalculator::DoMinimizeNLL(RooAbsReal * nll) { } } - RooFitResult * result = minim.save(); - - - return result; + return minim.save(); } //////////////////////////////////////////////////////////////////////////////// @@ -226,10 +217,10 @@ LikelihoodInterval* ProfileLikelihoodCalculator::GetInterval() const { // RooAbsData* data = fWS->data(fDataName); RooAbsPdf * pdf = GetPdf(); RooAbsData* data = GetData(); - if (!data || !pdf || fPOI.empty()) return 0; + if (!data || !pdf || fPOI.empty()) return nullptr; - RooArgSet* constrainedParams = pdf->getParameters(*data); - RemoveConstantParameters(constrainedParams); + std::unique_ptr constrainedParams{pdf->getParameters(*data)}; + RemoveConstantParameters(&*constrainedParams); /* @@ -239,16 +230,15 @@ LikelihoodInterval* ProfileLikelihoodCalculator::GetInterval() const { */ // do a global fit cloning the data - RooAbsReal * nll = DoGlobalFit(); - if (!nll) return 0; + std::unique_ptr nll{DoGlobalFit()}; + if (!nll) return nullptr; if (!fFitResult) { - delete nll; - return 0; + return nullptr; } - RooAbsReal* profile = nll->createProfile(fPOI); - profile->addOwnedComponents(*nll) ; // to avoid memory leak + std::unique_ptr profile{nll->createProfile(fPOI)}; + profile->addOwnedComponents(std::move(nll)) ; // to avoid memory leak // t.b.f. " RooProfileLL should keep and provide possibility to query on global minimum // set POI to fit value (this will speed up profileLL calculation of global minimum) @@ -282,9 +272,8 @@ LikelihoodInterval* ProfileLikelihoodCalculator::GetInterval() const { } // fPOI contains the parameter of interest of the PL object // and bestPOI contains a snapshot with the best fit values - LikelihoodInterval* interval = new LikelihoodInterval(name, profile, &fPOI, bestPOI); + LikelihoodInterval* interval = new LikelihoodInterval(name, profile.release(), &fPOI, bestPOI); interval->SetConfidenceLevel(1.-fSize); - delete constrainedParams; return interval; } @@ -305,9 +294,9 @@ HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const { RooAbsData* data = GetData(); - if (!data || !pdf) return 0; + if (!data || !pdf) return nullptr; - if (fNullParams.empty()) return 0; + if (fNullParams.empty()) return nullptr; // make a clone and ordered list since a vector will be associated to keep parameter values // clone the list since first fit will changes the fNullParams values @@ -316,16 +305,15 @@ HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const { // do a global fit - RooAbsReal * nll = DoGlobalFit(); - if (!nll) return 0; + std::unique_ptr nll{DoGlobalFit()}; + if (!nll) return nullptr; if (!fFitResult) { - delete nll; - return 0; + return nullptr; } - RooArgSet* constrainedParams = pdf->getParameters(*data); - RemoveConstantParameters(constrainedParams); + std::unique_ptr constrainedParams{pdf->getParameters(*data)}; + RemoveConstantParameters(&*constrainedParams); double nLLatMLE = fFitResult->minNll(); // in case of using offset need to save offset value @@ -365,12 +353,12 @@ HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const { if (existVarParams) { oocoutP(nullptr,Minimization) << "ProfileLikelihoodCalcultor::GetHypoTest - do conditional fit " << std::endl; - RooFitResult * fit2 = DoMinimizeNLL(nll); + std::unique_ptr fit2{DoMinimizeNLL(&*nll)}; // print fit result if (fit2) { nLLatCondMLE = fit2->minNll(); - fit2->printStream( oocoutI(nullptr,Minimization), fit2->defaultPrintContents(0), fit2->defaultPrintStyle(0) ); + fit2->printStream( oocoutI(nullptr,Minimization), fit2->defaultPrintContents(nullptr), fit2->defaultPrintStyle(nullptr) ); if (fit2->status() != 0) oocoutW(nullptr,Minimization) << "ProfileLikelihoodCalcultor::GetHypotest - Conditional fit failed - status = " << fit2->status() << std::endl; @@ -408,8 +396,6 @@ HypoTestResult* ProfileLikelihoodCalculator::GetHypoTest() const { } } - delete constrainedParams; - delete nll; return htr; } diff --git a/roofit/roostats/src/ProfileLikelihoodTestStat.cxx b/roofit/roostats/src/ProfileLikelihoodTestStat.cxx index db673569a7310..acec36cf954a3 100644 --- a/roofit/roostats/src/ProfileLikelihoodTestStat.cxx +++ b/roofit/roostats/src/ProfileLikelihoodTestStat.cxx @@ -56,7 +56,7 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, if( fDetailedOutputEnabled && fDetailedOutput ) { delete fDetailedOutput; - fDetailedOutput = 0; + fDetailedOutput = nullptr; } if( fDetailedOutputEnabled && !fDetailedOutput ) { fDetailedOutput = new RooArgSet(); @@ -83,22 +83,21 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, bool reuse=(fReuseNll || fgAlwaysReuseNll) ; bool created(false) ; - if (!reuse || fNll==0) { - RooArgSet* allParams = fPdf->getParameters(data); - RooStats::RemoveConstantParameters(allParams); + if (!reuse || fNll==nullptr) { + std::unique_ptr allParams{fPdf->getParameters(data)}; + RooStats::RemoveConstantParameters(&*allParams); // need to call constrain for RooSimultaneous until stripDisconnected problem fixed - fNll = fPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams), - RooFit::GlobalObservables(fGlobalObs), RooFit::ConditionalObservables(fConditionalObs), RooFit::Offset(fLOffset)); + fNll = std::unique_ptr{fPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams), + RooFit::GlobalObservables(fGlobalObs), RooFit::ConditionalObservables(fConditionalObs), RooFit::Offset(fLOffset))}; if (fPrintLevel > 0 && fLOffset) cout << "ProfileLikelihoodTestStat::Evaluate - Use Offset in creating NLL " << endl ; created = true ; - delete allParams; - if (fPrintLevel > 1) cout << "creating NLL " << fNll << " with data = " << &data << endl ; + if (fPrintLevel > 1) cout << "creating NLL " << &*fNll << " with data = " << &data << endl ; } if (reuse && !created) { - if (fPrintLevel > 1) cout << "reusing NLL " << fNll << " new data = " << &data << endl ; + if (fPrintLevel > 1) cout << "reusing NLL " << &*fNll << " new data = " << &data << endl ; fNll->setData(data,false) ; } // print data in case of number counting (simple data sets) @@ -109,7 +108,7 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, // make sure we set the variables attached to this nll - RooArgSet* attachedSet = fNll->getVariables(); + std::unique_ptr attachedSet{fNll->getVariables()}; attachedSet->assign(paramsOfInterest); RooArgSet* origAttachedSet = (RooArgSet*) attachedSet->snapshot(); @@ -131,12 +130,12 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, double uncondML = 0; double fit_favored_mu = 0; int statusD = 0; - RooArgSet * detOutput = 0; + RooArgSet * detOutput = nullptr; if (type != 2) { // minimize and count eval errors fNll->clearEvalErrorLog(); if (fPrintLevel>1) std::cout << "Do unconditional fit" << std::endl; - RooFitResult* result = GetMinNLL(); + std::unique_ptr result{GetMinNLL()}; if (result) { uncondML = result->minNll(); statusD = result->status(); @@ -146,11 +145,10 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, // save this snapshot if( fDetailedOutputEnabled ) { - detOutput = DetailedOutputAggregator::GetAsArgSet(result, "fitUncond_", fDetailedOutputWithErrorsAndPulls); + detOutput = DetailedOutputAggregator::GetAsArgSet(result.get(), "fitUncond_", fDetailedOutputWithErrorsAndPulls); fDetailedOutput->addOwned(*detOutput); delete detOutput; } - delete result; } else { return TMath::SignalingNaN(); // this should not really happen @@ -205,16 +203,15 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, } else { fNll->clearEvalErrorLog(); - RooFitResult* result = GetMinNLL(); + std::unique_ptr result{GetMinNLL()}; if (result) { condML = result->minNll(); statusN = result->status(); if( fDetailedOutputEnabled ) { - detOutput = DetailedOutputAggregator::GetAsArgSet(result, "fitCond_", fDetailedOutputWithErrorsAndPulls); + detOutput = DetailedOutputAggregator::GetAsArgSet(result.get(), "fitCond_", fDetailedOutputWithErrorsAndPulls); fDetailedOutput->addOwned(*detOutput); delete detOutput; } - delete result; } else { return TMath::SignalingNaN(); // this should not really happen @@ -272,13 +269,11 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, // need to restore the values ? attachedSet->assign(*origAttachedSet); - delete attachedSet; delete origAttachedSet; delete snap; if (!reuse) { - delete fNll; - fNll = 0; + fNll.reset(); } RooMsgService::instance().setGlobalKillBelow(msglevel); @@ -294,7 +289,7 @@ double RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, //////////////////////////////////////////////////////////////////////////////// /// find minimum of NLL using RooMinimizer -RooFitResult* RooStats::ProfileLikelihoodTestStat::GetMinNLL() { +std::unique_ptr RooStats::ProfileLikelihoodTestStat::GetMinNLL() { const auto& config = GetGlobalRooStatsConfig(); RooMinimizer minim(*fNll); @@ -312,7 +307,7 @@ RooFitResult* RooStats::ProfileLikelihoodTestStat::GetMinNLL() { int status; for (int tries = 1, maxtries = 4; tries <= maxtries; ++tries) { status = minim.minimize(minimizer,algorithm); - if (status%1000 == 0) { // ignore erros from Improve + if (status%1000 == 0) { // ignore errors from Improve break; } else if (tries < maxtries) { cout << " ----> Doing a re-scan first" << endl; @@ -334,6 +329,6 @@ RooFitResult* RooStats::ProfileLikelihoodTestStat::GetMinNLL() { } //how to get cov quality faster? - return minim.save(); + return std::unique_ptr{minim.save()}; //minim.optimizeConst(false); } diff --git a/roofit/roostats/src/ProposalHelper.cxx b/roofit/roostats/src/ProposalHelper.cxx index 87e74c38570c0..43725bdc99bd9 100644 --- a/roofit/roostats/src/ProposalHelper.cxx +++ b/roofit/roostats/src/ProposalHelper.cxx @@ -77,10 +77,8 @@ ProposalFunction* ProposalHelper::GetProposalFunction() { if (fPdf == nullptr) CreatePdf(); - // kbelasco: check here for memory leaks: does RooAddPdf make copies or - // take ownership of components, coeffs - RooArgList* components = new RooArgList(); - RooArgList* coeffs = new RooArgList(); + RooArgList components; + RooArgList coeffs; if (fCluesPdf == nullptr) CreateCluesPdf(); if (fCluesPdf != nullptr) { @@ -88,17 +86,17 @@ ProposalFunction* ProposalHelper::GetProposalFunction() fCluesFrac = DEFAULT_CLUES_FRAC; printf("added clues from dataset %s with fraction %g\n", fClues->GetName(), fCluesFrac); - components->add(*fCluesPdf); - coeffs->add(RooConst(fCluesFrac)); + components.add(*fCluesPdf); + coeffs.add(RooConst(fCluesFrac)); } if (fUniFrac > 0.) { CreateUniformPdf(); - components->add(*fUniformPdf); - coeffs->add(RooConst(fUniFrac)); + components.add(*fUniformPdf); + coeffs.add(RooConst(fUniFrac)); } - components->add(*fPdf); + components.add(*fPdf); RooAddPdf* addPdf = new RooAddPdf("proposalFunction", "Proposal Density", - *components, *coeffs); + components, coeffs); fPdfProp->SetPdf(*addPdf); fPdfProp->SetOwnsPdf(true); if (fCacheSize > 0) @@ -111,31 +109,26 @@ ProposalFunction* ProposalHelper::GetProposalFunction() void ProposalHelper::CreatePdf() { - // kbelasco: check here for memory leaks: - // does RooMultiVarGaussian make copies of xVec and muVec? - // or should we delete them? if (fVars == nullptr) { coutE(InputArguments) << "ProposalHelper::CreatePdf(): " << "Variables to create proposal function for are not set." << endl; return; } - RooArgList* xVec = new RooArgList(); - RooArgList* muVec = new RooArgList(); + RooArgList xVec{}; + RooArgList muVec{}; RooRealVar* clone; for (auto *r : static_range_cast (*fVars)){ - xVec->add(*r); + xVec.add(*r); TString cloneName = TString::Format("%s%s", "mu__", r->GetName()); clone = static_cast(r->clone(cloneName.Data())); - muVec->add(*clone); + muVec.add(*clone); if (fUseUpdates) fPdfProp->AddMapping(*clone, *r); } if (fCovMatrix == nullptr) - CreateCovMatrix(*xVec); - fPdf = new RooMultiVarGaussian("mvg", "MVG Proposal", *xVec, *muVec, + CreateCovMatrix(xVec); + fPdf = new RooMultiVarGaussian("mvg", "MVG Proposal", xVec, muVec, *fCovMatrix); - delete xVec; - delete muVec; } //////////////////////////////////////////////////////////////////////////////// diff --git a/roofit/roostats/src/RatioOfProfiledLikelihoodsTestStat.cxx b/roofit/roostats/src/RatioOfProfiledLikelihoodsTestStat.cxx index 9093578e8448e..a822ad48604ed 100644 --- a/roofit/roostats/src/RatioOfProfiledLikelihoodsTestStat.cxx +++ b/roofit/roostats/src/RatioOfProfiledLikelihoodsTestStat.cxx @@ -103,14 +103,14 @@ double RooStats::RatioOfProfiledLikelihoodsTestStat::Evaluate(RooAbsData& data, if (fDetailedOutputEnabled) { fDetailedOutput = new RooArgSet(); for (auto const *var : static_range_cast(*nullset)) { - RooRealVar* cloneVar = new RooRealVar(TString::Format("nullprof_%s", var->GetName()), + auto cloneVar = std::make_unique(TString::Format("nullprof_%s", var->GetName()), TString::Format("%s for null", var->GetTitle()), var->getVal()); - fDetailedOutput->addOwned(*cloneVar); + fDetailedOutput->addOwned(std::move(cloneVar)); } for (auto const *var : static_range_cast(*altset)) { - RooRealVar* cloneVar = new RooRealVar(TString::Format("altprof_%s", var->GetName()), + auto cloneVar = std::make_unique(TString::Format("altprof_%s", var->GetName()), TString::Format("%s for null", var->GetTitle()), var->getVal()); - fDetailedOutput->addOwned(*cloneVar); + fDetailedOutput->addOwned(std::move(cloneVar)); } } diff --git a/roofit/roostats/src/RooStatsUtils.cxx b/roofit/roostats/src/RooStatsUtils.cxx index 570df057c134f..e0919e10b21eb 100644 --- a/roofit/roostats/src/RooStatsUtils.cxx +++ b/roofit/roostats/src/RooStatsUtils.cxx @@ -104,13 +104,13 @@ namespace RooStats { assert(dynamic_cast(*iter)); FactorizePdf(observables, static_cast(**iter), obsTerms, constraints); } else if (auto sim = dynamic_cast(&pdf)) { //|| dynamic_cast(&pdf)) { - assert(sim != 0); + assert(sim != nullptr); RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().clone(sim->indexCat().GetName()); - for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) { + for (int ic = 0, nc = cat->numBins((const char *)nullptr); ic < nc; ++ic) { cat->setBin(ic); RooAbsPdf* catPdf = sim->getPdf(cat->getCurrentLabel()); // it is possible that a pdf is not defined for every category - if (catPdf != 0) FactorizePdf(observables, *catPdf, obsTerms, constraints); + if (catPdf != nullptr) FactorizePdf(observables, *catPdf, obsTerms, constraints); } delete cat; } else if (pdf.dependsOn(observables)) { @@ -138,7 +138,7 @@ namespace RooStats { FactorizePdf(observables, pdf, obsTerms, constraints); if(constraints.empty()) { oocoutW(nullptr, Eval) << "RooStatsUtils::MakeNuisancePdf - no constraints found on nuisance parameters in the input model" << endl; - return 0; + return nullptr; } return new RooProdPdf(name,"", constraints); } @@ -147,7 +147,7 @@ namespace RooStats { // make a nuisance pdf by factorizing out all constraint terms in a common pdf if (!model.GetPdf() || !model.GetObservables() ) { oocoutE(nullptr, InputArguments) << "RooStatsUtils::MakeNuisancePdf - invalid input model: missing pdf and/or observables" << endl; - return 0; + return nullptr; } return MakeNuisancePdf(*model.GetPdf(), *model.GetObservables(), name); } @@ -239,7 +239,7 @@ namespace RooStats { double fInval; TTree *fTree; - BranchStore(const vector ¶ms = vector (), double _inval = -999.) : fTree(0) { + BranchStore(const vector ¶ms = vector (), double _inval = -999.) : fTree(nullptr) { fInval = _inval; for(unsigned int i = 0;igetSnapshots()) { - RooArgSet *snapClone = static_cast(snap)->snapshot(); - snapClone->setName(snap->GetName()); - newWS->getSnapshots().Add(snapClone); + for (auto* snap : static_range_cast(oldWS->getSnapshots())) { + newWS->saveSnapshot(snap->GetName(), *snap, /*importValuesdf*/true); } } diff --git a/roofit/roostats/src/SPlot.cxx b/roofit/roostats/src/SPlot.cxx index 07f8a3e11eac5..6a7791bcd0c23 100644 --- a/roofit/roostats/src/SPlot.cxx +++ b/roofit/roostats/src/SPlot.cxx @@ -78,7 +78,7 @@ RooRealVar x("x", "observable", 0, 0, 20); RooRealVar m("m", "mean", 5., -10, 10); RooRealVar s("s", "sigma", 2., 0, 10); - RooGaussian gaus("gaus", "gaus", x, m, s); + RooGaussian gauss("gauss", "gauss", x, m, s); RooRealVar a("a", "exp", -0.2, -10., 0.); RooExponential ex("ex", "ex", x, a); @@ -89,7 +89,7 @@ RooLinearVar c1("c1", "c1", r1, common, RooFit::RooConst(0.)); RooLinearVar c2("c2", "c2", r2, common, RooFit::RooConst(0.)); - RooAddPdf sum("sum", "sum", RooArgSet(gaus, ex), RooArgSet(c1, c2)); + RooAddPdf sum("sum", "sum", RooArgSet(gauss, ex), RooArgSet(c1, c2)); auto data = sum.generate(x, 1000); RooStats::SPlot splot("splot", "splot", *data, &sum, RooArgSet(c1, c2)); @@ -367,7 +367,7 @@ double SPlot::GetYieldFromSWeight(const char* sVariable) const //////////////////////////////////////////////////////////////////////////////// -/// Return a RooArgList containing all paramters that have s weights. +/// Return a RooArgList containing all parameters that have s weights. RooArgList SPlot::GetSWeightVars() const { @@ -423,10 +423,10 @@ void SPlot::AddSWeight( RooAbsPdf* pdf, const RooArgList &yieldsTmp, // Find Parameters in the PDF to be considered fixed when calculating the SWeights // and be sure to NOT include the yields in that list - RooArgList* constParameters = (RooArgList*)pdf->getParameters(fSData) ; + std::unique_ptr constParameters{pdf->getParameters(fSData)}; for (unsigned int i=0; i < constParameters->size(); ++i) { // Need a counting loop since collection is being modified - auto& par = (*constParameters)[i]; + auto& par = *(*constParameters)[i]; if (std::any_of(yieldsTmp.begin(), yieldsTmp.end(), [&](const RooAbsArg* yield){ return yield->dependsOn(par); })) { constParameters->remove(par, true, true); --i; @@ -440,7 +440,7 @@ void SPlot::AddSWeight( RooAbsPdf* pdf, const RooArgList &yieldsTmp, for(Int_t i = 0; i < constParameters->getSize(); i++) { - RooAbsRealLValue* varTemp = static_cast( constParameters->at(i) ); + RooAbsRealLValue* varTemp = static_cast( (*constParameters)[i] ); if(varTemp && varTemp->isConstant() == 0 ) { varTemp->setConstant(); @@ -531,7 +531,7 @@ void SPlot::AddSWeight( RooAbsPdf* pdf, const RooArgList &yieldsTmp, // and all others to 0. Evaluate the pdf for each event // and store the values. - RooArgSet * pdfvars = pdf->getVariables(); + std::unique_ptr pdfvars{pdf->getVariables()}; std::vector > pdfvalues(numevents,std::vector(nspec,0)) ; for (Int_t ievt = 0; ievt setVal( 0 ) ; } } - delete pdfvars; // check that the likelihood normalization is fine std::vector norm(nspec,0) ; @@ -684,7 +683,7 @@ void SPlot::AddSWeight( RooAbsPdf* pdf, const RooArgList &yieldsTmp, pdfvec[n]->setVal( pdfvalues[ievt][n] ) ; - if( !(fabs(nsum/dsum)>=0 ) ) + if( !(std::abs(nsum/dsum)>=0 ) ) { coutE(Contents) << "error: " << nsum/dsum << endl ; return; diff --git a/roofit/roostats/src/SamplingDistPlot.cxx b/roofit/roostats/src/SamplingDistPlot.cxx index 391dc56eff9cf..0f88d836a68db 100644 --- a/roofit/roostats/src/SamplingDistPlot.cxx +++ b/roofit/roostats/src/SamplingDistPlot.cxx @@ -46,7 +46,7 @@ using namespace std; /// SamplingDistPlot default constructor with bin size SamplingDistPlot::SamplingDistPlot(Int_t nbins) : - fHist(0), + fHist(nullptr), fLegend(nullptr), fItems(), fOtherItems(), @@ -67,7 +67,7 @@ SamplingDistPlot::SamplingDistPlot(Int_t nbins) : /// SamplingDistPlot constructor with bin size, min and max SamplingDistPlot::SamplingDistPlot(Int_t nbins, double min, double max) : - fHist(0), + fHist(nullptr), fLegend(nullptr), fItems(), fOtherItems(), @@ -137,7 +137,7 @@ double SamplingDistPlot::AddSamplingDistribution(const SamplingDistribution *sam if( !IsNaN(fXMax) ) xup = fXMax; fHist = new TH1F(samplingDist->GetName(), samplingDist->GetTitle(), fBins, xlow, xup); - fHist->SetDirectory(0); // make the object managed by this class + fHist->SetDirectory(nullptr); // make the object managed by this class if( fVarName.Length() == 0 ) fVarName = samplingDist->GetVarName(); fHist->GetXaxis()->SetTitle(fVarName.Data()); @@ -189,7 +189,7 @@ double SamplingDistPlot::AddSamplingDistributionShaded(const SamplingDistributio double scaleFactor = AddSamplingDistribution(samplingDist, drawOptions); TH1F *shaded = (TH1F*)fHist->Clone((string(samplingDist->GetName())+string("_shaded")).c_str()); - shaded->SetDirectory(0); + shaded->SetDirectory(nullptr); shaded->SetFillStyle(fFillStyle++); shaded->SetLineWidth(1); @@ -228,7 +228,7 @@ void SamplingDistPlot::AddLine(double x1, double y1, double x2, double y2, const void SamplingDistPlot::AddTH1(TH1* h, Option_t *drawOptions) { if(fLegend && h->GetTitle()) fLegend->AddEntry(h, h->GetTitle(), "L"); TH1 * hcopy = (TH1*) h->Clone(); - hcopy->SetDirectory(0); + hcopy->SetDirectory(nullptr); addObject(hcopy, drawOptions); } void SamplingDistPlot::AddTF1(TF1* f, const char* title, Option_t *drawOptions) { @@ -260,7 +260,7 @@ void SamplingDistPlot::SetSampleWeights(const SamplingDistribution* samplingDist void SamplingDistPlot::addObject(TObject *obj, Option_t *drawOptions) { - if(0 == obj) { + if(nullptr == obj) { std::cerr << fName << "::addObject: called with a null pointer" << std::endl; return; } @@ -278,7 +278,7 @@ void SamplingDistPlot::addObject(TObject *obj, Option_t *drawOptions) void SamplingDistPlot::addOtherObject(TObject *obj, Option_t *drawOptions) { - if(0 == obj) { + if(nullptr == obj) { coutE(InputArguments) << fName << "::addOtherObject: called with a null pointer" << std::endl; return; } @@ -339,7 +339,7 @@ void SamplingDistPlot::Draw(Option_t * /*options */) { //coutI(InputArguments) << "Setting minimum of TH1 to " << theYMin << endl; cloneObj->SetMinimum(theYMin); } - cloneObj->SetDirectory(0); // transfer ownership of the object + cloneObj->SetDirectory(nullptr); // transfer ownership of the object fRooPlot->addTH1(cloneObj, obj->GetOption()); } @@ -420,7 +420,7 @@ void SamplingDistPlot::GetAbsoluteInterval(double &theMin, double &theMax, doubl /// fill color for the associated shaded TH1F. void SamplingDistPlot::SetLineColor(Color_t color, const SamplingDistribution *samplDist) { - if (samplDist == 0) { + if (samplDist == nullptr) { fHist->SetLineColor(color); TString shadedName(fHist->GetName()); @@ -458,7 +458,7 @@ void SamplingDistPlot::SetLineColor(Color_t color, const SamplingDistribution *s void SamplingDistPlot::SetLineWidth(Width_t lwidth, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->SetLineWidth(lwidth); } else{ @@ -477,7 +477,7 @@ void SamplingDistPlot::SetLineWidth(Width_t lwidth, const SamplingDistribution * void SamplingDistPlot::SetLineStyle(Style_t style, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->SetLineStyle(style); } else{ @@ -496,7 +496,7 @@ void SamplingDistPlot::SetLineStyle(Style_t style, const SamplingDistribution *s void SamplingDistPlot::SetMarkerStyle(Style_t style, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->SetMarkerStyle(style); } else{ @@ -515,7 +515,7 @@ void SamplingDistPlot::SetMarkerStyle(Style_t style, const SamplingDistribution void SamplingDistPlot::SetMarkerColor(Color_t color, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->SetMarkerColor(color); } else{ @@ -534,7 +534,7 @@ void SamplingDistPlot::SetMarkerColor(Color_t color, const SamplingDistribution void SamplingDistPlot::SetMarkerSize(Size_t size, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->SetMarkerSize(size); } else{ @@ -570,7 +570,7 @@ TH1F* SamplingDistPlot::GetTH1F(const SamplingDistribution *samplDist) void SamplingDistPlot::RebinDistribution(Int_t rebinFactor, const SamplingDistribution *samplDist) { - if(samplDist == 0){ + if(samplDist == nullptr){ fHist->Rebin(rebinFactor); } else{ diff --git a/roofit/roostats/src/SimpleInterval.cxx b/roofit/roostats/src/SimpleInterval.cxx index 1df7090eb6ad8..91ab6e44faa32 100644 --- a/roofit/roostats/src/SimpleInterval.cxx +++ b/roofit/roostats/src/SimpleInterval.cxx @@ -108,7 +108,7 @@ bool SimpleInterval::IsInInterval(const RooArgSet ¶meterPoint) const return false; RooAbsReal* point = dynamic_cast (parameterPoint.first()); - if (point == 0) + if (point == nullptr) return false; if ( point->getVal() > fUpperLimit || point->getVal() < fLowerLimit) diff --git a/roofit/roostats/src/SimpleLikelihoodRatioTestStat.cxx b/roofit/roostats/src/SimpleLikelihoodRatioTestStat.cxx index 028db245c9edd..f5b0ba7fdc2cd 100644 --- a/roofit/roostats/src/SimpleLikelihoodRatioTestStat.cxx +++ b/roofit/roostats/src/SimpleLikelihoodRatioTestStat.cxx @@ -50,9 +50,9 @@ double RooStats::SimpleLikelihoodRatioTestStat::Evaluate(RooAbsData& data, RooAr bool created = false ; if (!fNllNull) { - RooArgSet* allParams = fNullPdf->getParameters(data); - fNllNull = fNullPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams),RooFit::GlobalObservables(fGlobalObs),RooFit::ConditionalObservables(fConditionalObs)); - delete allParams; + std::unique_ptr allParams{fNullPdf->getParameters(data)}; + using namespace RooFit; + fNllNull = std::unique_ptr{fNullPdf->createNLL(data, CloneData(false), Constrain(*allParams), GlobalObservables(fGlobalObs), ConditionalObservables(fConditionalObs))}; created = true ; } if (reuse && !created) { @@ -60,7 +60,7 @@ double RooStats::SimpleLikelihoodRatioTestStat::Evaluate(RooAbsData& data, RooAr } // make sure we set the variables attached to this nll - RooArgSet* attachedSet = fNllNull->getVariables(); + std::unique_ptr attachedSet{fNllNull->getVariables()}; attachedSet->assign(*fNullParameters); attachedSet->assign(nullPOI); double nullNLL = fNllNull->getVal(); @@ -70,22 +70,21 @@ double RooStats::SimpleLikelihoodRatioTestStat::Evaluate(RooAbsData& data, RooAr if (!reuse) { - delete fNllNull ; fNllNull = nullptr ; + fNllNull.reset(); } - delete attachedSet; created = false ; if (!fNllAlt) { - RooArgSet* allParams = fAltPdf->getParameters(data); - fNllAlt = fAltPdf->createNLL(data, RooFit::CloneData(false),RooFit::Constrain(*allParams),RooFit::GlobalObservables(fGlobalObs),RooFit::ConditionalObservables(fConditionalObs)); - delete allParams; + std::unique_ptr allParams{fAltPdf->getParameters(data)}; + using namespace RooFit; + fNllAlt = std::unique_ptr{fAltPdf->createNLL(data, CloneData(false), Constrain(*allParams), GlobalObservables(fGlobalObs), ConditionalObservables(fConditionalObs))}; created = true ; } if (reuse && !created) { fNllAlt->setData(data, false) ; } // make sure we set the variables attached to this nll - attachedSet = fNllAlt->getVariables(); + attachedSet = std::unique_ptr{fNllAlt->getVariables()}; attachedSet->assign(*fAltParameters); double altNLL = fNllAlt->getVal(); @@ -97,9 +96,8 @@ double RooStats::SimpleLikelihoodRatioTestStat::Evaluate(RooAbsData& data, RooAr if (!reuse) { - delete fNllAlt ; fNllAlt = nullptr ; + fNllAlt.reset(); } - delete attachedSet; diff --git a/roofit/roostats/src/ToyMCImportanceSampler.cxx b/roofit/roostats/src/ToyMCImportanceSampler.cxx index 76dc3b1b72408..45bc7b19432fb 100644 --- a/roofit/roostats/src/ToyMCImportanceSampler.cxx +++ b/roofit/roostats/src/ToyMCImportanceSampler.cxx @@ -44,8 +44,8 @@ ToyMCImportanceSampler::~ToyMCImportanceSampler() { void ToyMCImportanceSampler::ClearCache(void) { ToyMCSampler::ClearCache(); - for( unsigned int i=0; i < fImpNLLs.size(); i++ ) if(fImpNLLs[i]) { delete fImpNLLs[i]; fImpNLLs[i] = nullptr; } - for( unsigned int i=0; i < fNullNLLs.size(); i++ ) if(fNullNLLs[i]) { delete fNullNLLs[i]; fNullNLLs[i] = nullptr; } + for( unsigned int i=0; i < fImpNLLs.size(); i++ ) { fImpNLLs[i].reset(); } + for( unsigned int i=0; i < fNullNLLs.size(); i++ ) { fNullNLLs[i].reset(); } } //////////////////////////////////////////////////////////////////////////////// @@ -56,7 +56,7 @@ RooDataSet* ToyMCImportanceSampler::GetSamplingDistributionsSingleWorker(RooArgS // remember original #toys, but overwrite it temporarily with the #toys per distribution Int_t allToys = fNToys; - // to keep track of which dataset entry comes form which density, define a roocategory as a label + // to keep track of which dataset entry comes from which density, define a roocategory as a label RooCategory densityLabel( "densityLabel", "densityLabel" ); densityLabel.defineType( "null", -1 ); for( unsigned int i=0; i < fImportanceDensities.size(); i++ ) @@ -104,13 +104,7 @@ RooDataSet* ToyMCImportanceSampler::GetSamplingDistributionsSingleWorker(RooArgS } if( !fullResult ) { - RooArgSet columns( *result->get() ); - RooRealVar weightVar ( "weight", "weight", 1.0 ); - columns.add( weightVar ); -// cout << endl << endl << "Reweighted data columns: " << endl; -// columns.Print("v"); -// cout << endl; - fullResult = new RooDataSet( result->GetName(), result->GetTitle(), columns, "weight" ); + fullResult = new RooDataSet( result->GetName(), result->GetTitle(), *result->get(), RooFit::WeightVar()); } for( int j=0; j < result->numEntries(); j++ ) { @@ -258,10 +252,10 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( } // catch the case when NLLs are not created (e.g. when ToyMCSampler was streamed for Proof) - if( fNullNLLs.empty() && fNullDensities.size() > 0 ) { + if( fNullNLLs.empty() && !fNullDensities.empty() ) { for( unsigned int i = 0; i < fNullDensities.size(); i++ ) fNullNLLs.push_back( nullptr ); } - if( fImpNLLs.empty() && fImportanceDensities.size() > 0 ) { + if( fImpNLLs.empty() && !fImportanceDensities.empty() ) { for( unsigned int i = 0; i < fImportanceDensities.size(); i++ ) fImpNLLs.push_back( nullptr ); } @@ -287,7 +281,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( // assign input paramPoint - RooArgSet* allVars = fPdf->getVariables(); + std::unique_ptr allVars{fPdf->getVariables()}; allVars->assign(paramPoint); @@ -306,9 +300,8 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( // save values to restore later. // but this must remain after(!) generating global observables if( !fGenerateFromNull ) { - RooArgSet* allVarsImpDens = fImportanceDensities[fIndexGenDensity]->getVariables(); + std::unique_ptr allVarsImpDens{fImportanceDensities[fIndexGenDensity]->getVariables()}; allVars->add(*allVarsImpDens); - delete allVarsImpDens; } const RooArgSet* saveVars = (const RooArgSet*)allVars->snapshot(); @@ -335,7 +328,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( if( fGenerateFromNull ) { //cout << "gen from null" << endl; allVars->assign(*fNullSnapshots[fIndexGenDensity]); - data = Generate(*fNullDensities[fIndexGenDensity], observables); + data = Generate(*fNullDensities[fIndexGenDensity], observables).release(); }else{ // need to be careful here not to overwrite the current state of the // nuisance parameters, ie they must not be part of the snapshot @@ -343,7 +336,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( if(fImportanceSnapshots[fIndexGenDensity]) { allVars->assign(*fImportanceSnapshots[fIndexGenDensity]); } - data = Generate(*fImportanceDensities[fIndexGenDensity], observables); + data = Generate(*fImportanceDensities[fIndexGenDensity], observables).release(); } //cout << "data generated: " << data << endl; @@ -364,16 +357,15 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( allVars->assign(*fNullSnapshots[i]); if( !fNullNLLs[i] ) { - RooArgSet* allParams = fNullDensities[i]->getParameters(*data); - fNullNLLs[i] = fNullDensities[i]->createNLL(*data, RooFit::CloneData(false), RooFit::Constrain(*allParams), - RooFit::ConditionalObservables(fConditionalObs)); - delete allParams; + std::unique_ptr allParams{fNullDensities[i]->getParameters(*data)}; + fNullNLLs[i] = std::unique_ptr{fNullDensities[i]->createNLL(*data, RooFit::CloneData(false), RooFit::Constrain(*allParams), + RooFit::ConditionalObservables(fConditionalObs))}; }else{ fNullNLLs[i]->setData( *data, false ); } nullNLLVals[i] = fNullNLLs[i]->getVal(); // FOR DEBuGGING!!!!!!!!!!!!!!!!! - if( !fReuseNLL ) { delete fNullNLLs[i]; fNullNLLs[i] = nullptr; } + if( !fReuseNLL ) { fNullNLLs[i].reset(); } } @@ -390,16 +382,15 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( allVars->assign(*fImportanceSnapshots[i]); } if( !fImpNLLs[i] ) { - RooArgSet* allParams = fImportanceDensities[i]->getParameters(*data); - fImpNLLs[i] = fImportanceDensities[i]->createNLL(*data, RooFit::CloneData(false), RooFit::Constrain(*allParams), - RooFit::ConditionalObservables(fConditionalObs)); - delete allParams; + std::unique_ptr allParams{fImportanceDensities[i]->getParameters(*data)}; + fImpNLLs[i] = std::unique_ptr{fImportanceDensities[i]->createNLL(*data, RooFit::CloneData(false), RooFit::Constrain(*allParams), + RooFit::ConditionalObservables(fConditionalObs))}; }else{ fImpNLLs[i]->setData( *data, false ); } impNLLVals[i] = fImpNLLs[i]->getVal(); // FOR DEBuGGING!!!!!!!!!!!!!!!!! - if( !fReuseNLL ) { delete fImpNLLs[i]; fImpNLLs[i] = nullptr; } + if( !fReuseNLL ) { fImpNLLs[i].reset(); } for( unsigned int j=0; j < nullNLLVals.size(); j++ ) { if( impNLLVals[i] < minNLLVals[j] ) minNLLVals[j] = impNLLVals[i]; @@ -426,7 +417,6 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData( allVars->assign(*saveVars); - delete allVars; delete saveVars; return data; diff --git a/roofit/roostats/src/ToyMCSampler.cxx b/roofit/roostats/src/ToyMCSampler.cxx index 91f0ec58efed2..2e6ba24607bc6 100644 --- a/roofit/roostats/src/ToyMCSampler.cxx +++ b/roofit/roostats/src/ToyMCSampler.cxx @@ -106,12 +106,12 @@ void NuisanceParametersSampler::Refresh() { } - fPoints.reset( fPrior->generate( + fPoints = std::unique_ptr{fPrior->generate( *fParams, AllBinned(), ExpectedData(), NumEvents(1) // for Asimov set, this is only a scale factor - )); + )}; if(fPoints->numEntries() != fNToys) { fNToys = fPoints->numEntries(); oocoutI(nullptr,InputArguments) << @@ -133,7 +133,7 @@ void NuisanceParametersSampler::Refresh() { }else{ oocoutI(nullptr,InputArguments) << "Using randomized nuisance parameters." << endl; - fPoints.reset(fPrior->generate(*fParams, fNToys)); + fPoints = std::unique_ptr{fPrior->generate(*fParams, fNToys)}; } } @@ -244,7 +244,7 @@ bool ToyMCSampler::CheckConfig(void) { RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi) { DetailedOutputAggregator detOutAgg; const RooArgList* allTS = EvaluateAllTestStatistics(data, poi, detOutAgg); - if (!allTS) return 0; + if (!allTS) return nullptr; // no need to delete allTS, it is deleted in destructor of detOutAgg return dynamic_cast(allTS->snapshot()); } @@ -252,13 +252,21 @@ RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, const RooA //////////////////////////////////////////////////////////////////////////////// const RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi, DetailedOutputAggregator& detOutAgg) { - RooArgSet *allVars = fPdf ? fPdf->getVariables() : nullptr; - RooArgSet *saveAll = allVars ? allVars->snapshot() : nullptr; + std::unique_ptr allVars; + std::unique_ptr saveAll; + if(fPdf) { + allVars = std::unique_ptr{fPdf->getVariables()}; + } + if(allVars) { + saveAll = std::make_unique(); + allVars->snapshot(*saveAll); + } for( unsigned int i = 0; i < fTestStatistics.size(); i++ ) { if( fTestStatistics[i] == nullptr ) continue; TString name( TString::Format("%s_TS%u", fSamplingDistName.c_str(), i) ); - std::unique_ptr parForTS(poi.snapshot()); - RooRealVar ts( name, fTestStatistics[i]->GetVarName(), fTestStatistics[i]->Evaluate( data, *parForTS ) ); + RooArgSet parForTS; + poi.snapshot(parForTS); + RooRealVar ts( name, fTestStatistics[i]->GetVarName(), fTestStatistics[i]->Evaluate( data, parForTS ) ); RooArgList tset(ts); detOutAgg.AppendArgSet(&tset); if (const RooArgSet* detOut = fTestStatistics[i]->GetDetailedOutput()) { @@ -270,8 +278,6 @@ const RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, cons allVars->assign(*saveAll); } } - delete saveAll; - delete allVars; return detOutAgg.GetAsArgList(); } @@ -285,15 +291,13 @@ SamplingDistribution* ToyMCSampler::GetSamplingDistribution(RooArgSet& paramPoin } } - RooDataSet* r = GetSamplingDistributions(paramPointIn); + std::unique_ptr r{GetSamplingDistributions(paramPointIn)}; if(r == nullptr || r->numEntries() == 0) { oocoutW(nullptr, Generation) << "no sampling distribution generated" << endl; return nullptr; } - SamplingDistribution* samp = new SamplingDistribution( r->GetName(), r->GetTitle(), *r ); - delete r; - return samp; + return new SamplingDistribution( r->GetName(), r->GetTitle(), *r ); } //////////////////////////////////////////////////////////////////////////////// @@ -372,7 +376,7 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP // important to cache the paramPoint b/c test statistic might // modify it from event to event RooArgSet *paramPoint = (RooArgSet*) paramPointIn.snapshot(); - RooArgSet *allVars = fPdf->getVariables(); + std::unique_ptr allVars{fPdf->getVariables()}; RooArgSet *saveAll = (RooArgSet*) allVars->snapshot(); @@ -440,7 +444,6 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP // clean up allVars->assign(*saveAll); delete saveAll; - delete allVars; delete paramPoint; return detOutAgg.GetAsDataSet(fSamplingDistName, fSamplingDistName); @@ -463,14 +466,13 @@ void ToyMCSampler::GenerateGlobalObservables(RooAbsPdf& pdf) const { // has problem for sim pdfs RooSimultaneous* simPdf = dynamic_cast( &pdf ); if (!simPdf) { - RooDataSet *one = pdf.generate(*fGlobalObservables, 1); + std::unique_ptr one{pdf.generate(*fGlobalObservables, 1)}; const RooArgSet *values = one->get(0); if (!_allVars) { - _allVars.reset(pdf.getVariables()); + _allVars = std::unique_ptr{pdf.getVariables()}; } _allVars->assign(*values); - delete one; } else { @@ -481,10 +483,10 @@ void ToyMCSampler::GenerateGlobalObservables(RooAbsPdf& pdf) const { channelCat.setIndex(i); RooAbsPdf* pdftmp = simPdf->getPdf(channelCat.getCurrentLabel()); assert(pdftmp); - RooArgSet* globtmp = pdftmp->getObservables(*fGlobalObservables); + std::unique_ptr globtmp{pdftmp->getObservables(*fGlobalObservables)}; RooAbsPdf::GenSpec* gs = pdftmp->prepareMultiGen(*globtmp, NumEvents(1)); _pdfList.push_back(pdftmp); - _obsList.emplace_back(globtmp); + _obsList.emplace_back(std::move(globtmp)); _gsList.emplace_back(gs); } } @@ -500,12 +502,10 @@ void ToyMCSampler::GenerateGlobalObservables(RooAbsPdf& pdf) const { } else { // not using multigen for global observables - RooDataSet* one = pdf.generateSimGlobal( *fGlobalObservables, 1 ); + std::unique_ptr one{pdf.generateSimGlobal( *fGlobalObservables, 1 )}; const RooArgSet *values = one->get(0); - RooArgSet* allVars = pdf.getVariables(); + std::unique_ptr allVars{pdf.getVariables()}; allVars->assign(*values); - delete allVars; - delete one; } } @@ -525,7 +525,7 @@ RooAbsData* ToyMCSampler::GenerateToyData(RooArgSet& paramPoint, double& weight, } // assign input paramPoint - RooArgSet* allVars = fPdf->getVariables(); + std::unique_ptr allVars{fPdf->getVariables()}; allVars->assign(paramPoint); @@ -567,12 +567,11 @@ RooAbsData* ToyMCSampler::GenerateToyData(RooArgSet& paramPoint, double& weight, weight = 1.0; } - RooAbsData *data = Generate(pdf, observables); + RooAbsData *data = Generate(pdf, observables).release(); // We generated the data with the randomized nuisance parameter (if hybrid) // but now we are setting the nuisance parameters back to where they were. allVars->assign(*saveVars); - delete allVars; delete saveVars; return data; @@ -585,14 +584,14 @@ RooAbsData* ToyMCSampler::GenerateToyData(RooArgSet& paramPoint, double& weight, /// or whether it should use the expected number of events. It also takes /// into account the option to generate a binned data set (*i.e.* RooDataHist). -RooAbsData* ToyMCSampler::Generate(RooAbsPdf &pdf, RooArgSet &observables, const RooDataSet* protoData, int forceEvents) const { +std::unique_ptr ToyMCSampler::Generate(RooAbsPdf &pdf, RooArgSet &observables, const RooDataSet* protoData, int forceEvents) const { if(fProtoData) { protoData = fProtoData; forceEvents = protoData->numEntries(); } - RooAbsData *data = nullptr; + std::unique_ptr data; int events = forceEvents; if(events == 0) events = fNEvents; @@ -602,22 +601,22 @@ RooAbsData* ToyMCSampler::Generate(RooAbsPdf &pdf, RooArgSet &observables, const if (events == 0) { if (pdf.canBeExtended() && pdf.expectedEvents(observables) > 0) { if(fGenerateBinned) { - if(protoData) data = pdf.generate(observables, AllBinned(), Extended(), ProtoData(*protoData, true, true)); - else data = pdf.generate(observables, AllBinned(), Extended()); + if(protoData) data = std::unique_ptr{pdf.generate(observables, AllBinned(), Extended(), ProtoData(*protoData, true, true))}; + else data = std::unique_ptr{pdf.generate(observables, AllBinned(), Extended())}; } else { if (protoData) { if (useMultiGen) { if (!_gs2) _gs2.reset( pdf.prepareMultiGen(observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true)) ); - data = pdf.generate(*_gs2) ; + data = std::unique_ptr{pdf.generate(*_gs2)}; } else { - data = pdf.generate (observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true)); + data = std::unique_ptr{pdf.generate(observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true))}; } } else { if (useMultiGen) { if (!_gs1) _gs1.reset( pdf.prepareMultiGen(observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag)) ); - data = pdf.generate(*_gs1) ; + data = std::unique_ptr{pdf.generate(*_gs1)}; } else { - data = pdf.generate (observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag) ); + data = std::unique_ptr{pdf.generate(observables, Extended(), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag) )}; } } @@ -629,22 +628,22 @@ RooAbsData* ToyMCSampler::Generate(RooAbsPdf &pdf, RooArgSet &observables, const } } else { if (fGenerateBinned) { - if(protoData) data = pdf.generate(observables, events, AllBinned(), ProtoData(*protoData, true, true)); - else data = pdf.generate(observables, events, AllBinned()); + if(protoData) data = std::unique_ptr{pdf.generate(observables, events, AllBinned(), ProtoData(*protoData, true, true))}; + else data = std::unique_ptr{pdf.generate(observables, events, AllBinned())}; } else { if (protoData) { if (useMultiGen) { if (!_gs3) _gs3.reset( pdf.prepareMultiGen(observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true)) ); - data = pdf.generate(*_gs3) ; + data = std::unique_ptr{pdf.generate(*_gs3)}; } else { - data = pdf.generate (observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true)); + data = std::unique_ptr{pdf.generate(observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag), ProtoData(*protoData, true, true))}; } } else { if (useMultiGen) { if (!_gs4) _gs4.reset( pdf.prepareMultiGen(observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag)) ); - data = pdf.generate(*_gs4) ; + data = std::unique_ptr{pdf.generate(*_gs4)}; } else { - data = pdf.generate (observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag)); + data = std::unique_ptr{pdf.generate(observables, NumEvents(events), AutoBinned(fGenerateAutoBinned), GenBinned(fGenerateBinnedTag))}; } } } @@ -687,7 +686,7 @@ void ToyMCSampler::ClearCache() { _allVars = nullptr; // no need to delete the _pdfList since it is managed by the RooSimultaneous object - if (_pdfList.size() > 0) { + if (!_pdfList.empty()) { _pdfList.clear(); _obsList.clear(); _gsList.clear(); diff --git a/roofit/roostats/src/ToyMCStudy.cxx b/roofit/roostats/src/ToyMCStudy.cxx index 6ea31e37406cc..1c7ecfae2ce69 100644 --- a/roofit/roostats/src/ToyMCStudy.cxx +++ b/roofit/roostats/src/ToyMCStudy.cxx @@ -79,8 +79,7 @@ bool ToyMCStudy::execute(void) { coutP(Generation) << "ToyMCStudy::execute - run with seed " << RooRandom::randomGenerator()->Integer(TMath::Limits::Max() ) << std::endl; RooDataSet* sd = fToyMCSampler->GetSamplingDistributionsSingleWorker(fParamPoint); - ToyMCPayload *sdw = new ToyMCPayload(sd); - storeDetailedOutput(*sdw); + storeDetailedOutput(std::make_unique(sd)); return false; } diff --git a/roofit/roostats/src/UpperLimitMCSModule.cxx b/roofit/roostats/src/UpperLimitMCSModule.cxx index 33f456b740c9f..40e50bac230f1 100644 --- a/roofit/roostats/src/UpperLimitMCSModule.cxx +++ b/roofit/roostats/src/UpperLimitMCSModule.cxx @@ -44,7 +44,7 @@ using namespace RooStats ; UpperLimitMCSModule::UpperLimitMCSModule(const RooArgSet* poi, double CL) : RooAbsMCStudyModule(Form("UpperLimitMCSModule_%s",poi->first()->GetName()),Form("UpperLimitMCSModule_%s",poi->first()->GetName())), _parName(poi->first()->GetName()), - _plc(0),_ul(0),_poi(0), _data(0),_cl(CL), _model(0) + _plc(nullptr),_ul(nullptr),_poi(nullptr), _data(nullptr),_cl(CL), _model(nullptr) { std::cout<<"RooUpperLimitConstructor ParName:"<<_parName<first()->GetName()), - _plc(0),_ul(0),_poi(other._poi), _data(0), _cl(other._cl), _model(other._model) + _plc(nullptr),_ul(nullptr),_poi(other._poi), _data(nullptr), _cl(other._cl), _model(other._model) { } diff --git a/roofit/roostats/test/testHypoTestInvResult.cxx b/roofit/roostats/test/testHypoTestInvResult.cxx index b89eab9b69bb0..c58a415ef5085 100644 --- a/roofit/roostats/test/testHypoTestInvResult.cxx +++ b/roofit/roostats/test/testHypoTestInvResult.cxx @@ -21,7 +21,9 @@ TEST(HypoTestInvResult, ReadFromFile) // This just reads members EXPECT_NEAR(result->UpperLimit(), 2.4613465, 1.E-7); - EXPECT_NEAR(result->UpperLimitEstimatedError(), 0.059684301, 2.E-7); + + // Here, we need to loosen the tolerance because the estimated error is determined on-the-fly with a fit + EXPECT_NEAR(result->UpperLimitEstimatedError(), 0.059684301, 1.E-5); // This accesses the sampling distribution EXPECT_DOUBLE_EQ(result->GetExpectedUpperLimit(0), 1.60988427028569); diff --git a/roofit/roostats/test/testSPlot.cxx b/roofit/roostats/test/testSPlot.cxx index c84c7f7e31bd7..3bb64807f5119 100644 --- a/roofit/roostats/test/testSPlot.cxx +++ b/roofit/roostats/test/testSPlot.cxx @@ -14,7 +14,7 @@ TEST(SPlot, UseWithRooLinearVar) { RooRealVar x("x", "observable", 0, 0, 20); RooRealVar m("m", "mean", 5., -10, 10); RooRealVar s("s", "sigma", 2., 0.1, 10); - RooGaussian gaus("gaus", "gaus", x, m, s); + RooGaussian gauss("gauss", "gauss", x, m, s); RooRealVar a("a", "exp", -0.2, -10., 0.); RooExponential ex("ex", "ex", x, a); @@ -24,7 +24,7 @@ TEST(SPlot, UseWithRooLinearVar) { RooRealVar r2("r2", "ratio 2", 0.5, 0, 10); RooLinearVar c1("c1", "c1", r1, common, RooFit::RooConst(0.)); RooLinearVar c2("c2", "c2", r2, common, RooFit::RooConst(0.)); - RooAddPdf sum("sum", "sum", RooArgSet(gaus, ex), RooArgSet(c1, c2)); + RooAddPdf sum("sum", "sum", RooArgSet(gauss, ex), RooArgSet(c1, c2)); std::unique_ptr data{sum.generate(x, 1000)}; diff --git a/roofit/xroofit/CMakeLists.txt b/roofit/xroofit/CMakeLists.txt index 459b3ce8fbb6a..5bcdb27f3f4bd 100644 --- a/roofit/xroofit/CMakeLists.txt +++ b/roofit/xroofit/CMakeLists.txt @@ -1,10 +1,13 @@ ROOT_STANDARD_LIBRARY_PACKAGE(RooFitXRooFit HEADERS RooBrowser.h + XRooFit.h + RooFit/xRooFit/xRooFit.h RooFit/xRooFit/xRooNode.h + RooFit/xRooFit/xRooNLLVar.h + RooFit/xRooFit/xRooHypoSpace.h RooFit/xRooFit/xRooBrowser.h SOURCES - src/Banner.cxx src/Asymptotics.cxx src/xRooBrowser.cxx src/xRooFit.cxx diff --git a/roofit/xroofit/doc/index.md b/roofit/xroofit/doc/index.md new file mode 100644 index 0000000000000..e43480b4a6865 --- /dev/null +++ b/roofit/xroofit/doc/index.md @@ -0,0 +1,7 @@ +\defgroup xroofit xRooFit +\brief A high-level API for RooFit. +\ingroup Roofitmain + +xRooFit is a high-level API for RooFit. + +A version of the API is included in ROOT as an experimental feature, inside the ROOT::Experimental::XRooFit namespace. diff --git a/roofit/xroofit/inc/LinkDef.h b/roofit/xroofit/inc/LinkDef.h index 60374c717883d..b77031b60ea20 100644 --- a/roofit/xroofit/inc/LinkDef.h +++ b/roofit/xroofit/inc/LinkDef.h @@ -15,8 +15,12 @@ #pragma link off all globals; #pragma link off all classes; -#pragma link C++ class RooFit::Detail::XRooFit::xRooNode + ; -#pragma link C++ class RooFit::Detail::XRooFit::xRooNode::InteractiveObject + ; -#pragma link C++ class RooFit::Detail::XRooFit::xRooBrowser + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooFit + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooNode + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooNode::InteractiveObject + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooNLLVar + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooBrowser + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooHypoSpace + ; +#pragma link C++ class ROOT::Experimental::XRooFit::xRooFit::StoredFitResult + ; #endif diff --git a/roofit/xroofit/inc/RooBrowser.h b/roofit/xroofit/inc/RooBrowser.h index 7f3e2bd00fed4..eca74bc5d19b4 100644 --- a/roofit/xroofit/inc/RooBrowser.h +++ b/roofit/xroofit/inc/RooBrowser.h @@ -10,48 +10,6 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ -/** \class RooBrowser -\ingroup roofit - - \image html RooBrowser.png - -To get started with the RooBrowser, open any ROOT file containing a workspace - and then create an instance of the ROOT::Experimental::RooBrowser just like - creating an instance of a `TBrowser`. A window will be displayed with a navigable - tree structure on the left that lets you explore the content of the workspaces - present in the loaded file. Note that additional files, including json workspace files, - can be loaded through the `Browser --> Open` menu in the top left corner. - -The context menu for each node (access by right clicking on the node) in the tree structure can be used to get more -information about the node. In particular, the `Draw` command can be selected on many of the nodes that are part of a -statistical model, which will visualize that part of the model in the browser window. A number of options are available -for the `Draw` command, including (some options can be combined): - - - "e" : calculate and visualize propagated model uncertainty - - "auxratio" : Draw a ratio auxiliary plot below the main plot - - "auxsignif" : Draw a significance auxiliary plot below the main plot - - "pull" : show panel of current parameter values, which can be dragged in order to change the values and visualize the -effect on the model (very experimental feature). - - Once a node has been drawn, the styling of subsequent draws can be controlled through `TStyle` objects - that will now appear in the `objects` folder in the workspace. - -A model can be fit to a dataset from the workspace using the `fitTo` context menu command and specifying - the name of a dataset in the workspace (if no name is given, an expected dataset corresponding to the - current state of the model will be used). A dialog will display the fit result status code when the - fit completes and then a `fits` folder will be found under the workspace (the workspace may need to - be collapsed and re-expanded to make it appear) where the fit result can be found, selected, and visualized. - In multi-channel models the channels that are included in the fit can be controlled with the checkboxes - in the browser. Clicking the checkbox will cycle through three states: checked, unchecked with - grey-underline, and checked with grey-underline. The grey-underline indicates that channel wont be - included in the fit (and will appear greyed out when the model is visualized) - -Many more features are available in the `RooBrowser`, and further documentation and development can be found at - the xRooFit repository, which is the library where the browser has - been originally developed. The author (Will Buttinger) is also very happy to be contacted with questions or - feedback about this new functionality. - - */ #ifndef RooFit_RooBrowser_h #define RooFit_RooBrowser_h diff --git a/roofit/xroofit/inc/RooFit/xRooFit/Config.h b/roofit/xroofit/inc/RooFit/xRooFit/Config.h index 067059ef4c4e7..759c0677d15bc 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/Config.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/Config.h @@ -14,7 +14,7 @@ #define xRooFit_Config_h // ROOT configuration: all of xRooFit is placed into a detail namespace -#define XROOFIT_NAMESPACE RooFit::Detail::XRooFit +#define XROOFIT_NAMESPACE ROOT::Experimental::XRooFit // Define XROOFIT_USE_PRAGMA_ONCE if you want to use "pragma once" instead of // header guards diff --git a/roofit/xroofit/inc/RooFit/xRooFit/xRooBrowser.h b/roofit/xroofit/inc/RooFit/xRooFit/xRooBrowser.h index 1d0abbc586182..d90e5592acf5d 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/xRooBrowser.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/xRooBrowser.h @@ -23,7 +23,7 @@ #include "TBrowser.h" #include "TQObject.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; class xRooNode; @@ -34,6 +34,8 @@ class xRooBrowser : public TBrowser, public TQObject { xRooNode *GetSelected(); + xRooNode *Open(const char *filename); + void ls(const char *path = nullptr) const override; void cd(const char *path); @@ -47,6 +49,6 @@ class xRooBrowser : public TBrowser, public TQObject { ClassDefOverride(xRooBrowser, 0) }; -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; #endif // include guard diff --git a/roofit/xroofit/inc/RooFit/xRooFit/xRooFit.h b/roofit/xroofit/inc/RooFit/xRooFit/xRooFit.h index 7f25be724c387..153b81f186d39 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/xRooFit.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/xRooFit.h @@ -9,7 +9,6 @@ * with or without modification, are permitted according to the terms * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ - #include "Config.h" // when not using the namespace will use the once pragma. @@ -18,9 +17,17 @@ #ifdef XROOFIT_USE_PRAGMA_ONCE #pragma once #endif -#if !defined(XROOFIT_XROOFIT_H) || defined(XROOFIT_USE_PRAGMA_ONCE) +#if (!defined(XROOFIT_USE_PRAGMA_ONCE) && !defined(XROOFIT_XROOFIT_H)) || \ + (defined(XROOFIT_USE_PRAGMA_ONCE) && !defined(XROOFIT_XROOFIT_H_XROOFIT)) #ifndef XROOFIT_USE_PRAGMA_ONCE #define XROOFIT_XROOFIT_H +#else +#define XROOFIT_XROOFIT_H_XROOFIT +// even with using pragma once, need include guard otherwise cannot include this header +// as part of an interpreted file ... the other headers in xRooFit are similarly affected +// however for now users of xRooFit should only need to include the main xRooFit header to use it all +// in future we should try removing the pragma once altogether (undef XROOFIT_USE_PRAGMA_ONCE) +// and see if it has negative consequences anywhere #endif /** @@ -39,12 +46,13 @@ class RooWorkspace; #include "Fit/FitConfig.h" #include "RooCmdArg.h" +#include "TNamed.h" class TCanvas; #include -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; class xRooNLLVar; @@ -53,6 +61,12 @@ class xRooFit { public: // Extra options for NLL creation: static RooCmdArg ReuseNLL(bool flag); // if should try to reuse the NLL object when it changes dataset + static RooCmdArg Tolerance(double value); + static RooCmdArg StrategySequence(const char *stratSeq); // control minimization strategy sequence + static constexpr double OBS = std::numeric_limits::quiet_NaN(); + + // Helper function for matching precision of a value and its error + static std::pair matchPrecision(const std::pair &in); // Static methods that work with the 'first class' object types: // Pdfs: RooAbsPdf @@ -62,7 +76,7 @@ class xRooFit { // fit result flags in its constPars list which are global observables with the "global" attribute static std::pair, std::shared_ptr> - generateFrom(RooAbsPdf &pdf, const std::shared_ptr &fr, bool expected = false, int seed = 0); + generateFrom(RooAbsPdf &pdf, const RooFitResult &fr, bool expected = false, int seed = 0); static std::shared_ptr fitTo(RooAbsPdf &pdf, const std::pair, std::shared_ptr> &data, const RooLinkedList &nllOpts, const ROOT::Fit::FitConfig &fitConf); @@ -81,12 +95,27 @@ class xRooFit { static std::shared_ptr createFitConfig(); // obtain instance of default fit configuration static std::shared_ptr createNLLOptions(); // obtain instance of default nll options + static std::shared_ptr defaultNLLOptions(); // access default NLL options for modifications + static std::shared_ptr defaultFitConfig(); - static std::shared_ptr - minimize(RooAbsReal &nll, const std::shared_ptr &fitConfig = nullptr); + static std::shared_ptr minimize(RooAbsReal &nll, + const std::shared_ptr &fitConfig = nullptr, + const std::shared_ptr &nllOpts = nullptr); static int minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parName = "", const std::shared_ptr &_fitConfig = nullptr); + // this class is used to store a shared_ptr in a TDirectory's List, so that retrieval of cached fits + // can share the fit result (and avoid re-reading from disk as well) + class StoredFitResult : public TNamed { + public: + StoredFitResult(RooFitResult *_fr); + StoredFitResult(const std::shared_ptr &_fr); + + public: + std::shared_ptr fr; //! + ClassDef(StoredFitResult, 0) + }; + class Asymptotics { public: @@ -129,30 +158,30 @@ class xRooFit { } // inverse of PValue function - static Double_t k(const IncompatFunc &compatRegions, double pValue, double poiVal, double poiPrimeVal, - double sigma_mu = 0, double mu_low = -std::numeric_limits::infinity(), - double mu_high = std::numeric_limits::infinity()); + static double k(const IncompatFunc &compatRegions, double pValue, double poiVal, double poiPrimeVal, + double sigma_mu = 0, double mu_low = -std::numeric_limits::infinity(), + double mu_high = std::numeric_limits::infinity()); - static Double_t k(const PLLType &pllType, double pValue, double mu, double mu_prime, double sigma_mu = 0, - double mu_low = -std::numeric_limits::infinity(), - double mu_high = std::numeric_limits::infinity()) + static double k(const PLLType &pllType, double pValue, double mu, double mu_prime, double sigma_mu = 0, + double mu_low = -std::numeric_limits::infinity(), + double mu_high = std::numeric_limits::infinity()) { return k(IncompatibilityFunction(pllType, mu), pValue, mu, mu_prime, sigma_mu, mu_low, mu_high); } // Recommend sigma_mu = |mu - mu_prime|/sqrt(pll_mu(asimov_mu_prime)) - static Double_t PValue(const IncompatFunc &compatRegions, double k, double mu, double mu_prime, - double sigma_mu = 0, double mu_low = -std::numeric_limits::infinity(), - double mu_high = std::numeric_limits::infinity()); + static double PValue(const IncompatFunc &compatRegions, double k, double mu, double mu_prime, double sigma_mu = 0, + double mu_low = -std::numeric_limits::infinity(), + double mu_high = std::numeric_limits::infinity()); - static Double_t PValue(const PLLType &pllType, double k, double mu, double mu_prime, double sigma_mu = 0, - double mu_low = -std::numeric_limits::infinity(), - double mu_high = std::numeric_limits::infinity()) + static double PValue(const PLLType &pllType, double k, double mu, double mu_prime, double sigma_mu = 0, + double mu_low = -std::numeric_limits::infinity(), + double mu_high = std::numeric_limits::infinity()) { return PValue(IncompatibilityFunction(pllType, mu), k, mu, mu_prime, sigma_mu, mu_low, mu_high); } - static Double_t Phi_m(double mu, double mu_prime, double a, double sigma, const IncompatFunc &compatRegions); + static double Phi_m(double mu, double mu_prime, double a, double sigma, const IncompatFunc &compatRegions); static int CompatFactor(const IncompatFunc &func, double mu_hat); @@ -166,6 +195,9 @@ class xRooFit { // static RooRealVar FindLimit(TGraph *pVals, double target_pVal = 0.05); }; + static std::shared_ptr sDefaultNLLOptions; + static std::shared_ptr sDefaultFitConfig; + // Run hypothesis test(s) on the given pdf // Uses hypoPoint binning on model parameters to determine points to scan // if hypoPoint binning has nBins==0 then will auto-scan (assumes CL=95%, can override with setStringAttribute) @@ -179,7 +211,7 @@ class xRooFit { const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); }; -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; #include "xRooHypoSpace.h" #include "xRooNLLVar.h" diff --git a/roofit/xroofit/inc/RooFit/xRooFit/xRooHypoSpace.h b/roofit/xroofit/inc/RooFit/xRooFit/xRooHypoSpace.h index 352a7dca2de8c..b551170a63a2e 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/xRooHypoSpace.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/xRooHypoSpace.h @@ -22,13 +22,14 @@ #include "xRooNLLVar.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; class xRooHypoSpace : public xRooNLLVar::xRooHypoSpace { - +public: + using xRooNLLVar::xRooHypoSpace::xRooHypoSpace; ClassDef(xRooHypoSpace, 0) }; -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; #endif // include guard diff --git a/roofit/xroofit/inc/RooFit/xRooFit/xRooNLLVar.h b/roofit/xroofit/inc/RooFit/xRooFit/xRooNLLVar.h index 2bfd52ddf1330..fb01c8f89750b 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/xRooNLLVar.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/xRooNLLVar.h @@ -45,19 +45,26 @@ class RooCmdArg; class TGraph; class TGraphErrors; +class TMultiGraph; namespace RooStats { class HypoTestResult; class HypoTestInverterResult; } // namespace RooStats -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; class xRooNode; class xRooNLLVar : public std::shared_ptr { public: + struct xValueWithError : public std::pair { + xValueWithError(const std::pair &in) : std::pair(in) {} + double value() const { return std::pair::first; } + double error() const { return std::pair::second; } + }; + void Print(Option_t *opt = ""); xRooNLLVar(RooAbsPdf &pdf, const std::pair &data, @@ -86,12 +93,60 @@ class xRooNLLVar : public std::shared_ptr { class xRooFitResult : public std::shared_ptr { public: - xRooFitResult(const std::shared_ptr &in); // : fNode(in) { } + xRooFitResult(const std::shared_ptr &in, + const std::shared_ptr &nll = nullptr); // : fNode(in) { } const RooFitResult *operator->() const; // operator std::shared_ptr() const; operator const RooFitResult *() const; void Draw(Option_t *opt = ""); + + xRooNLLVar nll(); + RooArgList poi() + { + return get() + ? RooArgList(*std::unique_ptr(get()->floatParsFinal().selectByAttrib("poi", true))) + : RooArgList(); + } + + // generate a conditional fit using the given poi set to the given values + // alias is used to store the fit result in the map under a different name + xRooFitResult cfit(const char *poiValues, const char *alias = nullptr); + // generate the conditional fit required for an impact calculation + xRooFitResult ifit(const char *np, bool up, bool prefit = false); + // calculate the impact on poi due to np. if approx is true, will use the covariance approximation instead + double impact(const char *poi, const char *np, bool up = true, bool prefit = false, bool approx = false); + double impact(const char *np, bool up = true, bool prefit = false, bool approx = false) + { + auto _poi = poi(); + if (_poi.size() != 1) + throw std::runtime_error("xRooFitResult::impact: not one POI"); + return impact(poi().contentsString().c_str(), np, up, prefit, approx); + } + + // calculate error on poi conditional on the given NPs being held constant at their post-fit values + // The conditional error is often presented as the difference in quadrature to the total error i.e. + // error contribution due to conditional NPs = sqrt( pow(totError,2) - pow(condError,2) ) + double conditionalError(const char *poi, const char *nps, bool up = true, bool approx = false); + + // rank all the np based on impact ... will use the covariance approximation if full impact not available + // the approxThreshold sets the level below which the approximation will be returned + // e.g. set it to 0 to not do approximation + RooArgList ranknp(const char *poi, bool up = true, bool prefit = false, + double approxThreshold = std::numeric_limits::infinity()); + // version that assumes only one parameter is poi + RooArgList + ranknp(bool up = true, bool prefit = false, double approxThreshold = std::numeric_limits::infinity()) + { + auto _poi = poi(); + if (_poi.size() != 1) + throw std::runtime_error("xRooFitResult::ranknp: not one POI"); + return ranknp(poi().contentsString().c_str(), up, prefit, approxThreshold); + } + std::shared_ptr fNode; + std::shared_ptr fNll; + + std::shared_ptr> fCfits; }; xRooFitResult minimize(const std::shared_ptr & = nullptr); @@ -100,11 +155,12 @@ class xRooNLLVar : public std::shared_ptr { std::shared_ptr fitConfig(); // returns fit config, or creates a default one if not existing ROOT::Math::IOptions *fitConfigOptions(); // return pointer to non-const version of the options inside the fit config - class xRooHypoPoint { + class xRooHypoPoint : public TNamed { public: + xRooHypoPoint(std::shared_ptr htr = nullptr, const RooAbsCollection *_coords = nullptr); static std::set allowedStatusCodes; - void Print(); - void Draw(Option_t *opt = ""); + void Print(Option_t *opt = "") const override; + void Draw(Option_t *opt = "") override; // status bitmask of the available fit results // 0 = all ok @@ -115,8 +171,11 @@ class xRooNLLVar : public std::shared_ptr { std::shared_ptr ufit(bool readOnly = false); std::shared_ptr cfit_null(bool readOnly = false); std::shared_ptr cfit_alt(bool readOnly = false); + std::shared_ptr cfit_lbound(bool readOnly = false); // cfit @ the lower bound of mu + std::shared_ptr gfit() { return fGenFit; } // non-zero if data was generated - std::pair, std::shared_ptr> data; + std::pair, std::shared_ptr> fData; + std::pair, std::shared_ptr> data(); std::pair getVal(const char *what); @@ -135,9 +194,17 @@ class xRooNLLVar : public std::shared_ptr { return std::pair(1, 0); // by construction auto null = pNull_toys(nSigma); auto alt = pAlt_toys(nSigma); - double pval = (null.first == 0) ? 0 : null.first / alt.first; - // TODO: should do error calculation like for asymp (calulate up and down separately and then take err) - return std::make_pair(pval, pval * sqrt(pow(null.second / null.first, 2) + pow(alt.second / alt.first, 2))); + double nom = (null.first == 0) ? 0 : null.first / alt.first; + // double up = (null.first + null.second == 0) ? 0 : ((alt.first-alt.second<=0) ? + // std::numeric_limits::infinity() : (null.first + null.second)/(alt.first - alt.second)); double down + // = (null.first - null.second == 0) ? 0 : (null.first - null.second)/(alt.first + alt.second); + // old way ... now doing like in pCLs_asymp by calculating the two variations ... but this is pessimistic + // assumes p-values are anticorrelated! + // so reverting to old + return std::make_pair(nom, (alt.first - alt.second <= 0) + ? std::numeric_limits::infinity() + : (sqrt(pow(null.second, 2) + pow(alt.second * nom, 2)) / alt.first)); + // return std::pair(nom,std::max(std::abs(up - nom), std::abs(down - nom))); } std::pair ts_toys(double nSigma = std::numeric_limits::quiet_NaN()); // test statistic value @@ -148,12 +215,19 @@ class xRooNLLVar : public std::shared_ptr { xRooHypoPoint generateNull(int seed = 0); xRooHypoPoint generateAlt(int seed = 0); - void addNullToys(int nToys = 1, int seed = 0); // if seed=0 will use a random seed - void addAltToys(int nToys = 1, int seed = 0); // if seed=0 will use a random seed + void + addNullToys(int nToys = 1, int seed = 0, double target = std::numeric_limits::quiet_NaN(), + double target_nSigma = std::numeric_limits::quiet_NaN()); // if seed=0 will use a random seed + void + addAltToys(int nToys = 1, int seed = 0, double target = std::numeric_limits::quiet_NaN(), + double target_nSigma = std::numeric_limits::quiet_NaN()); // if seed=0 will use a random seed + void + addCLsToys(int nToys = 1, int seed = 0, double target = std::numeric_limits::quiet_NaN(), + double target_nSigma = std::numeric_limits::quiet_NaN()); // if seed=0 will use a random seed - RooArgList poi(); - RooArgList alt_poi(); // values of the poi in the alt hypothesis (will be nans if not defined) - RooRealVar &mu_hat(); // throws exception if ufit not available + RooArgList poi() const; + RooArgList alt_poi() const; // values of the poi in the alt hypothesis (will be nans if not defined) + RooRealVar &mu_hat(); // throws exception if ufit not available std::shared_ptr asimov(bool readOnly = @@ -168,7 +242,7 @@ class xRooNLLVar : public std::shared_ptr { std::shared_ptr coords; // pars of the nll that will be held const alongside POI - std::shared_ptr fUfit, fNull_cfit, fAlt_cfit; + std::shared_ptr fUfit, fNull_cfit, fAlt_cfit, fLbound_cfit; std::shared_ptr fGenFit; // if the data was generated, this is the fit is was generated from bool isExpected = false; // if genFit, flag says is asimov or not @@ -181,18 +255,24 @@ class xRooNLLVar : public std::shared_ptr { std::vector> altToys; std::shared_ptr nllVar = nullptr; // hypopoints get a copy + std::shared_ptr hypoTestResult = nullptr; + std::shared_ptr retrieveFit(int type); + + TString tsTitle(bool inWords = false) const; private: std::pair pX_toys(bool alt, double nSigma = std::numeric_limits::quiet_NaN()); - void addToys(bool alt, int nToys, int initialSeed = 0); - - TString tsTitle(); + size_t addToys(bool alt, int nToys, int initialSeed = 0, double target = std::numeric_limits::quiet_NaN(), + double target_nSigma = std::numeric_limits::quiet_NaN(), bool targetCLs = false, + double relErrThreshold = 2., size_t maxToys = 10000); }; // use alt_value = nan to skip the asimov calculations xRooHypoPoint hypoPoint(const char *parName, double value, double alt_value = std::numeric_limits::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); + // same as above but specify parNames and values in a string + xRooHypoPoint hypoPoint(const char *parValues, double alt_value, const xRooFit::Asymptotics::PLLType &pllType); // this next method requires poi to be flagged in the model already (with "poi" attribute) .. must be exactly one xRooHypoPoint hypoPoint(double value, double alt_value = std::numeric_limits::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); @@ -205,8 +285,7 @@ class xRooNLLVar : public std::shared_ptr { public: friend class xRooNLLVar; xRooHypoSpace(const char *name = "", const char *title = ""); - - bool AddWorkspace(const char *wsFilename, const char *extraPars = ""); + xRooHypoSpace(const RooStats::HypoTestInverterResult *result); bool AddModel(const xRooNode &pdf, const char *validity = ""); @@ -223,6 +302,7 @@ class xRooNLLVar : public std::shared_ptr { std::shared_ptr pars() const { return fPars; }; RooArgList axes() const; + xRooHypoPoint &AddPoint(double value); // adds by using the first axis var xRooHypoPoint &AddPoint(const char *coords = ""); // adds a new point at given coords or returns existing xRooHypoPoint &point(size_t i) { return at(i); } @@ -233,19 +313,39 @@ class xRooNLLVar : public std::shared_ptr { // expX: do expected, X sigma (use +X or -X for contour, otherwise will return band unless X=0) // toys: pvalues from available toys // readonly: don't compute anything, just return available values - std::shared_ptr BuildGraph(const char *opt); + std::shared_ptr graph(const char *opt) const; - // estimates where corresponding pValues graph becomes equal to 0.05 - // linearly interpolates log(pVal) when obtaining limits. - // returns value and error - static std::pair GetLimit(const TGraph &pValues, double target = 0.05); + // return a TMultiGraph containing the set of graphs for a particular visualization + std::shared_ptr graphs(const char *opt); // will evaluate more points until limit is below given relative uncert - - std::pair FindLimit(const char *opt, double relUncert = std::numeric_limits::infinity()); + xValueWithError findlimit(const char *opt, double relUncert = std::numeric_limits::infinity(), + unsigned int maxTries = 20); + + // get currently available limit, with error. Use nSigma = nan for observed limit + xValueWithError limit(const char *type = "cls", double nSigma = std::numeric_limits::quiet_NaN()) const; + int scan(const char *type, size_t nPoints, double low = std::numeric_limits::quiet_NaN(), + double high = std::numeric_limits::quiet_NaN(), + const std::vector &nSigmas = {0, 1, 2, -1, -2, std::numeric_limits::quiet_NaN()}, + double relUncert = 0.1); + int scan(const char *type = "cls", + const std::vector &nSigmas = {0, 1, 2, -1, -2, std::numeric_limits::quiet_NaN()}, + double relUncert = 0.1) + { + return scan(type, 0, std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), + nSigmas, relUncert); + } + int scan(const char *type, double nSigma, double relUncert = 0.1) + { + return scan(type, std::vector{nSigma}, relUncert); + } // key is nSigma or "obs" for observed - std::map> limits(const char *opt = "cls", double relUncert = 0.1); + // will only do obs if "obs" dataset is not a generated dataset + std::map> + limits(const char *opt = "cls", + const std::vector &nSigmas = {0, 1, 2, -1, -2, std::numeric_limits::quiet_NaN()}, + double relUncert = std::numeric_limits::infinity()); std::shared_ptr pdf(const RooAbsCollection &parValues) const; std::shared_ptr pdf(const char *parValues = "") const; @@ -254,6 +354,12 @@ class xRooNLLVar : public std::shared_ptr { RooStats::HypoTestInverterResult *result(); private: + // estimates where corresponding pValues graph becomes equal to 0.05 + // linearly interpolates log(pVal) when obtaining limits. + // returns value and error + static std::pair + GetLimit(const TGraph &pValues, double target = std::numeric_limits::quiet_NaN()); + static RooArgList toArgs(const char *str); xRooFit::Asymptotics::PLLType fTestStatType = xRooFit::Asymptotics::Unknown; @@ -261,27 +367,59 @@ class xRooNLLVar : public std::shared_ptr { std::map, std::shared_ptr> fNlls; // existing NLL functions of added pdfs; - std::set> fWorkspaces; // added workspaces (kept open) - std::set, std::shared_ptr>> fPdfs; }; xRooHypoSpace hypoSpace(const char *parName, int nPoints, double low, double high, double alt_value = std::numeric_limits::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); - xRooHypoSpace - hypoSpace(const char *parName = "", const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); + xRooHypoSpace hypoSpace(const char *parName = "", + const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown, + double alt_value = std::numeric_limits::quiet_NaN()); xRooHypoSpace hypoSpace(int nPoints, double low, double high, double alt_value = std::numeric_limits::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType = xRooFit::Asymptotics::Unknown); - std::shared_ptr pars(bool stripGlobalObs = true); + std::shared_ptr pars(bool stripGlobalObs = true) const; void Draw(Option_t *opt = ""); + TObject *Scan(const RooArgList &scanPars, const std::vector> &coords, + const RooArgList &profilePars = RooArgList()); + TObject *Scan(const char *scanPars, const std::vector> &coords, + const RooArgList &profilePars = RooArgList()); + TObject *Scan(const char *scanPars, size_t nPoints, double low, double high, size_t nPointsY, double ylow, + double yhigh, const RooArgList &profilePars = RooArgList()) + { + std::vector> coords; + if (nPoints) { + double step = (high - low) / (nPoints); + for (size_t i = 0; i < nPoints; i++) { + std::vector coord({low + step * i}); + if (nPointsY) { + double stepy = (yhigh - ylow) / (nPointsY); + for (size_t j = 0; j < nPointsY; j++) { + coord.push_back({ylow + stepy * j}); + coords.push_back(coord); + coord.resize(1); + } + } else { + coords.push_back(coord); + } + } + } + return Scan(scanPars, coords, profilePars); + } + TObject * + Scan(const char *scanPars, size_t nPoints, double low, double high, const RooArgList &profilePars = RooArgList()) + { + return Scan(scanPars, nPoints, low, high, 0, 0, 0, profilePars); + } + std::shared_ptr func() const; // will assign globs when called std::shared_ptr pdf() const { return fPdf; } RooAbsData *data() const; // returns the data hidden inside the NLLVar if there is some + const RooAbsCollection *globs() const { return fGlobs.get(); } // NLL = nllTerm + constraintTerm // nllTerm = sum( entryVals ) + extendedTerm + simTerm [+ binnedDataTerm if activated binnedL option] @@ -292,18 +430,25 @@ class xRooNLLVar : public std::shared_ptr { RooNLLVar *nllTerm() const; RooConstraintSum *constraintTerm() const; - double getEntryVal(size_t entry); // get the Nll value for a specific entry + double getEntryVal(size_t entry) const; // get the Nll value for a specific entry double extendedTerm() const; double simTerm() const; double binnedDataTerm() const; + double getEntryBinWidth(size_t entry) const; + + double ndof() const; + double saturatedVal() const; + double saturatedConstraintTerm() const; + double saturatedNllTerm() const; + double pgof() const; // a goodness-of-fit pvalue based on profile likelihood of a saturated model // change the dataset - will check globs are the same - Bool_t setData(const std::pair, std::shared_ptr> &_data); - Bool_t setData(const std::shared_ptr &data, const std::shared_ptr &globs) + bool setData(const std::pair, std::shared_ptr> &_data); + bool setData(const std::shared_ptr &data, const std::shared_ptr &globs) { return setData(std::make_pair(data, globs)); } - Bool_t setData(const xRooNode &data); + bool setData(const xRooNode &data); // using shared ptrs everywhere, even for RooLinkedList which needs custom deleter to clear itself // but still work ok for assignment operations @@ -322,6 +467,6 @@ class xRooNLLVar : public std::shared_ptr { bool kReuseNLL = true; }; -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; #endif // include guard diff --git a/roofit/xroofit/inc/RooFit/xRooFit/xRooNode.h b/roofit/xroofit/inc/RooFit/xRooFit/xRooNode.h index 22a4b48e73a1f..7e53bc9cb01f1 100644 --- a/roofit/xroofit/inc/RooFit/xRooFit/xRooNode.h +++ b/roofit/xroofit/inc/RooFit/xRooFit/xRooNode.h @@ -43,7 +43,7 @@ class TStyle; #include "RooCmdArg.h" #include "TQObject.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; class xRooNode; class xRooNLLVar; @@ -116,13 +116,8 @@ class xRooNode : public TNamed, public std::vector> { virtual ~xRooNode(); - void SetName(const char *name) override; // *MENU* - void SetTitle(const char *title) override - { - if (auto o = (get()); o) - o->SetTitle(title); - TNamed::SetTitle(title); - } // *MENU* + void SetName(const char *name) override; // *MENU* + void SetTitle(const char *title) override; // *MENU* const char *GetNodeType() const; @@ -141,22 +136,58 @@ class xRooNode : public TNamed, public std::vector> { RooArgList argList() const; - std::shared_ptr find(const std::string &name) const; + std::shared_ptr + find(const std::string &name, bool browseResult = true) const; // same as at but return nullptr if not found bool contains(const std::string &name) const; // doesn't trigger a browse of the found object, unlike find // most users should use these methods: will do an initial browse and will browse the returned object too std::shared_ptr operator[](size_t idx) { return at(idx); } - std::shared_ptr operator[](const std::string &name); // will create a child node if not existing + std::shared_ptr operator[](const std::string &name); // will create a new node if not existing, unlike 'at' + + // custom iterator to ensure children are auto-browsed as we iterate through + class xRooNodeIterator : public std::vector>::const_iterator { + public: + xRooNodeIterator(std::vector>::const_iterator itr) + : std::vector>::const_iterator(itr) + { + } + std::shared_ptr const &operator*() const + { + auto &&out = std::vector>::const_iterator::operator*(); + if (out->get() && out->empty()) + out->browse(); + return std::move(out); + } + bool operator!=(xRooNodeIterator const &b) const + { + const std::vector>::const_iterator &aa = (*this); + const std::vector>::const_iterator &bb = b; + return aa != bb; + }; + xRooNodeIterator const &operator++() + { + std::vector>::const_iterator::operator++(); + return *this; + } + bool operator==(xRooNodeIterator const &b) const + { + const std::vector>::const_iterator &aa = (*this); + const std::vector>::const_iterator &bb = b; + return aa == bb; + }; + }; + auto begin() const -> xRooNodeIterator { return xRooNodeIterator(std::vector>::begin()); } + auto end() const -> xRooNodeIterator { return xRooNodeIterator(std::vector>::end()); } // needed in pyROOT to avoid it creating iterators that follow the 'get' to death - auto begin() const -> decltype(std::vector>::begin()) - { - return std::vector>::begin(); - } - auto end() const -> decltype(std::vector>::end()) - { - return std::vector>::end(); - } + // auto begin() const -> decltype(std::vector>::begin()) + // { + // return std::vector>::begin(); + // } + // auto end() const -> decltype(std::vector>::end()) + // { + // return std::vector>::end(); + // } void Browse(TBrowser *b = nullptr) override; // will browse the children that aren't "null" nodes bool IsFolder() const override; @@ -178,6 +209,17 @@ class xRooNode : public TNamed, public std::vector> { { return dynamic_cast(get()); } + TObject *xget() const { return xget(); } + template + T *xget() const + { + for (auto &c : fBrowsables) { + if (strcmp(c->GetName(), ".memory") == 0) { + return c->get(); + } + } + return nullptr; + } TObject *operator->() const { return get(); } @@ -190,6 +232,13 @@ class xRooNode : public TNamed, public std::vector> { { return std::dynamic_pointer_cast(acquire(std::make_shared(std::forward(args)...))); } + template + // looser version of above ... first template type says what type to return + // allows returning different type to the one requested in T2 (e.g. ok to get RooConstVar when acquire a RooRealVar) + std::shared_ptr acquire2(Args &&...args) + { + return std::dynamic_pointer_cast(acquire(std::make_shared(std::forward(args)...))); + } template std::shared_ptr acquireNew(Args &&...args) { @@ -206,17 +255,17 @@ class xRooNode : public TNamed, public std::vector> { std::shared_ptr convertForAcquisition(xRooNode &acquirer, const char *opt = "") const; - xRooNode vars() const; // obs,globs,floats,args + xRooNode vars() const; // obs,pars xRooNode obs() const; // robs and globs xRooNode robs() const; // just the regular obs xRooNode globs() const; // just the global obs - xRooNode pars() const; // floats and args/consts - xRooNode floats() const; // just floating pars - xRooNode args() const; // just const pars - xRooNode consts() const { return args(); } + xRooNode pars() const; // poi, np, and pp (prespecified pars) + xRooNode floats() const; // float poi or np + xRooNode consts() const; // just const poi or np xRooNode poi() const; // parameters of interest - xRooNode np() const; // nuisance parameters + xRooNode np() const; // nuisance parameters (non-poi floatables) + xRooNode pp() const; // preset/prespecified parameters xRooNode components() const; // additive children xRooNode factors() const; // multiplicative children @@ -229,6 +278,7 @@ class xRooNode : public TNamed, public std::vector> { xRooNode datasets() const; // datasets corresponding to this pdf (parent nodes that do observable selections automatically applied) + xRooNode Replace(const xRooNode &node); // use to replace a node in the tree at the location of this node xRooNode Remove(const xRooNode &child); xRooNode Add(const xRooNode &child, @@ -240,7 +290,7 @@ class xRooNode : public TNamed, public std::vector> { xRooNode Combine(const xRooNode &rhs); // combine rhs with this node - xRooNode reduced(const std::string &range = "") + xRooNode reduced(const std::string &range = "", bool invert = false) const; // return a node representing reduced version of this node, will use the SetRange to reduce if blank // following versions are for the menu in the GUI @@ -249,19 +299,21 @@ class xRooNode : public TNamed, public std::vector> { void _Vary_(const char *what); // *MENU* xRooNode _Constrain_(const char *what) { return Constrain(what); } // *MENU* - void _ShowVars_(Bool_t set = kTRUE); // *TOGGLE* *GETTER=_IsShowVars_ + void _ShowVars_(bool set = true); // *TOGGLE* *GETTER=_IsShowVars_ bool _IsShowVars_() const; - void SetHidden(Bool_t set = kTRUE); // *TOGGLE* *GETTER=IsHidden + void SetHidden(bool set = true); // *TOGGLE* *GETTER=IsHidden bool IsHidden() const; bool SetContents(const TObject &obj) { operator=(obj); return true; - } // populates the node's comp (creating if necessary) from given object - bool SetContents(double value); // uses a RooConst - bool SetContents(double value, const char *par, double parVal = 1); // shortcut to setting a variation content + } // populates the node's comp (creating if necessary) from given object + bool SetData(const TObject &obj, const char *dataName = "obsData"); + + bool SetContent(double value); // uses a RooConst + bool SetContent(double value, const char *par, double parVal = 1); // shortcut to setting a variation content bool SetContents(const TObject &obj, const char *par, double parVal) { variations()[TString::Format("%s=%g", par, parVal).Data()]->operator=(obj); @@ -271,21 +323,22 @@ class xRooNode : public TNamed, public std::vector> { bool SetBinContent(int bin, double value, const char *par = nullptr, double parVal = 1); bool SetBinData(int bin, double value, const char *dataName = "obsData"); // only valid for pdf nodes - void _SetContents_(double value); // *MENU* + void _SetContent_(double value); // *MENU* void _SetBinContent_(int bin, double value, const char *par = "", double parVal = 1); // *MENU* bool SetXaxis(const RooAbsBinning &binning); + bool SetXaxis(TAxis *ax); bool SetXaxis(const char *name, const char *title, int nbins, double low, double high); - bool SetXaxis(const char *name, const char *title, int nbins, double *bins); + bool SetXaxis(const char *name, const char *title, int nbins, const double *bins); bool SetXaxis(const char *title, int nbins, double low, double high) { return SetXaxis("xaxis", title, nbins, low, high); } - bool SetXaxis(const char *title, int nbins, double *bins) { return SetXaxis("xaxis", title, nbins, bins); } + bool SetXaxis(const char *title, int nbins, const double *bins) { return SetXaxis("xaxis", title, nbins, bins); } bool SetXaxis(int nbins, double low, double high) { return SetXaxis("xaxis", "", nbins, low, high); } - bool SetXaxis(int nbins, double *bins) { return SetXaxis("xaxis", "", nbins, bins); } + bool SetXaxis(int nbins, const double *bins) { return SetXaxis("xaxis", "", nbins, bins); } - std::shared_ptr style(TObject *initObject = nullptr) const; + std::shared_ptr style(TObject *initObject = nullptr, bool autoCreate = true) const; TAxis *GetXaxis() const; @@ -296,6 +349,14 @@ class xRooNode : public TNamed, public std::vector> { std::vector GetBinErrors(int binStart = 1, int binEnd = 0, const xRooNode &fr = "") const; std::pair IntegralAndError(const xRooNode &fr = "", const char *rangeName = nullptr) const; + // methods to access default content and error + double GetContent() const { return GetBinContent(fBinNumber); } + double GetError(const xRooNode &fr = "") const + { + return (fBinNumber == -1) ? IntegralAndError(fr).second : GetBinError(fBinNumber, fr); + } + double GetData(const char *dataName = "obsData") { return GetBinData(fBinNumber, dataName); } + xRooNLLVar nll(const xRooNode &_data, std::initializer_list nllOpts) const; xRooNLLVar nll(const xRooNode &_data, const RooLinkedList &nllOpts) const; xRooNLLVar nll(const xRooNode &_data = "") const; // uses xRooFit::createNLLOption for nllOpts @@ -305,8 +366,15 @@ class xRooNode : public TNamed, public std::vector> { void SetFitResult(const std::shared_ptr &fr) { SetFitResult(fr.get()); } void SetFitResult(const xRooNode &fr); - void _fitTo_(const char *datasetName = "", const char *constParValues = ""); // *MENU* - void _generate_(const char *name = "", bool expected = false); // *MENU* + xRooNode + generate(const xRooNode &fr = "", bool expected = false, + int seed = 0); // generate a dataset from a pdf node using given fr - if none given will use current fit + + void _fit_(const char *constParValues = ""); // *MENU* + void _generate_(const char *name = "", bool expected = false); // *MENU* + void _scan_(const char *what = "plr", double nToys = 0, const char *xvar = "", int nPointsX = 0, double lowX = 0, + double highX = 0 /*, const char* yvar="", int nBinsY=0, double lowY=0, double highY=0*/, + const char *constParValues = ""); // *MENU* // xRooNode fitTo(const char* datasetName) const; // xRooNode fitTo(const xRooNode& _data) const; // xRooNode generate(bool expected=false) const; @@ -326,9 +394,12 @@ class xRooNode : public TNamed, public std::vector> { void Checked(TObject *obj, bool val); void SetChecked(bool val = true) { Checked(this, val); } + xRooNode histo(const xRooNode &vars = "x", const xRooNode &fr = "", bool content = true, bool errors = true) const; + xRooNode filter(const xRooNode &range) const; + TGraph *BuildGraph(RooAbsLValue *v = nullptr, bool includeZeros = false, TVirtualPad *fromPad = nullptr) const; TH1 *BuildHistogram(RooAbsLValue *v = nullptr, bool empty = false, bool errors = false, int binStart = 1, - int binEnd = 0) const; + int binEnd = 0, const xRooNode &fr = "") const; xRooNode mainChild() const; void Draw(Option_t *opt = "") override; // *MENU* @@ -368,14 +439,16 @@ class xRooNode : public TNamed, public std::vector> { std::shared_ptr parentPdf() const; // find first parent that is a pdf - void sterilize(); + void sterilize() const; std::vector> fBrowsables; // will appear in the browser tree but are not actual children std::function fBrowseOperation; // a way to specify a custom browsing operation + std::shared_ptr getBrowsable(const char *name) const; + ClassDefOverride(xRooNode, 0) }; -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; #endif // include guard diff --git a/roofit/xroofit/inc/XRooFit.h b/roofit/xroofit/inc/XRooFit.h new file mode 100644 index 0000000000000..2aa4d9825672f --- /dev/null +++ b/roofit/xroofit/inc/XRooFit.h @@ -0,0 +1,27 @@ +/* + * Project: RooFit + * Author: + * Will Buttinger, RAL 2022 + * + * Copyright (c) 2022, CERN + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted according to the terms + * listed in LICENSE (http://roofit.sourceforge.net/license.txt) + */ + +/** \namespace ROOT::Experimental::XRooFit +\ingroup xroofit + +xRooFit is a high-level API for RooFit. + +A version of the API is included in ROOT as an experimental feature, inside the ROOT::Experimental::XRooFit namespace. + + */ + +#ifndef RooFit_XRooFit_h +#define RooFit_XRooFit_h + +#include "RooFit/xRooFit/xRooFit.h" + +#endif diff --git a/roofit/xroofit/src/Asymptotics.cxx b/roofit/xroofit/src/Asymptotics.cxx index acfc024e5f930..efdff3cf83345 100644 --- a/roofit/xroofit/src/Asymptotics.cxx +++ b/roofit/xroofit/src/Asymptotics.cxx @@ -7,10 +7,10 @@ #include "RooStats/RooStatsUtils.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; -Double_t xRooFit::Asymptotics::k(const IncompatFunc &compatRegions, double pValue, double poiVal, double poiPrimeVal, - double sigma, double low, double high) +double xRooFit::Asymptotics::k(const IncompatFunc &compatRegions, double pValue, double poiVal, double poiPrimeVal, + double sigma, double low, double high) { // determine the pll value corresponding to nSigma expected - i.e. where the altPValue equals e.g. 50% for nSigma=0, @@ -36,7 +36,12 @@ Double_t xRooFit::Asymptotics::k(const IncompatFunc &compatRegions, double pValu struct TailIntegralFunction { TailIntegralFunction(double _poiVal, double _alt_val, double _sigma_mu, double _low, double _high, IncompatFunc _compatibilityFunction, double _target) - : poiVal(_poiVal), alt_val(_alt_val), sigma_mu(_sigma_mu), low(_low), high(_high), target(_target), + : poiVal(_poiVal), + alt_val(_alt_val), + sigma_mu(_sigma_mu), + low(_low), + high(_high), + target(_target), cFunc(_compatibilityFunction) { } @@ -93,8 +98,8 @@ Double_t xRooFit::Asymptotics::k(const IncompatFunc &compatRegions, double pValu return _pll; } -Double_t xRooFit::Asymptotics::PValue(const IncompatFunc &compatRegions, double k, double poiVal, double poi_primeVal, - double sigma, double lowBound, double upBound) +double xRooFit::Asymptotics::PValue(const IncompatFunc &compatRegions, double k, double poiVal, double poi_primeVal, + double sigma, double lowBound, double upBound) { // uncapped test statistic is equal to onesidednegative when k is positive, and equal to 1.0 - difference between // twosided and onesidednegative when k is negative ... @@ -124,17 +129,17 @@ Double_t xRooFit::Asymptotics::PValue(const IncompatFunc &compatRegions, double // get the poi value that defines the test statistic, and the poi_prime hypothesis we are testing // when setting limits, these are often the same value - Double_t Lambda_y = 0; + double Lambda_y = 0; if (std::abs(poiVal - poi_primeVal) > 1e-12) Lambda_y = (poiVal - poi_primeVal) / sigma; if (std::isnan(Lambda_y)) return -1; - Double_t k_low = (lowBound == -std::numeric_limits::infinity()) ? std::numeric_limits::infinity() - : pow((poiVal - lowBound) / sigma, 2); - Double_t k_high = (upBound == std::numeric_limits::infinity()) ? std::numeric_limits::infinity() - : pow((upBound - poiVal) / sigma, 2); + double k_low = (lowBound == -std::numeric_limits::infinity()) ? std::numeric_limits::infinity() + : pow((poiVal - lowBound) / sigma, 2); + double k_high = (upBound == std::numeric_limits::infinity()) ? std::numeric_limits::infinity() + : pow((upBound - poiVal) / sigma, 2); double out = Phi_m(poiVal, poi_primeVal, std::numeric_limits::infinity(), sigma, compatRegions) - 1; @@ -181,7 +186,7 @@ Double_t xRooFit::Asymptotics::PValue(const IncompatFunc &compatRegions, double return 1. - out; } -Double_t +double xRooFit::Asymptotics::Phi_m(double /*mu*/, double mu_prime, double a, double sigma, const IncompatFunc &compatRegions) { @@ -244,4 +249,4 @@ int xRooFit::Asymptotics::CompatFactor(const IncompatFunc &func, double mu_hat) // return RooRealVar("limit","limit",std::numeric_limits::quiet_NaN()); // } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/Banner.cxx b/roofit/xroofit/src/Banner.cxx deleted file mode 100644 index c77ddca62b40d..0000000000000 --- a/roofit/xroofit/src/Banner.cxx +++ /dev/null @@ -1,29 +0,0 @@ -// -// Created by Will Buttinger on 2021-03-22. -// - -#include "RooFit.h" - -#include "Rtypes.h" -#include "Riostream.h" -#include "TEnv.h" - -#include "xRooFitVersion.h" - -using namespace std; - -Int_t doxroofitBanner(); - -static Int_t dummyFMB = doxroofitBanner(); - -Int_t doxroofitBanner() - -{ -#ifndef __xROOFIT_NOBANNER - cout << "\033[1mxRooFit -- Create/Explore/Modify Workspaces -- Development ongoing\033[0m " << endl - << " xRooFit : http://gitlab.cern.ch/will/xroofit" << endl - << " Version: " << GIT_COMMIT_HASH << " [" << GIT_COMMIT_DATE << "]" << endl; -#endif - (void)dummyFMB; - return 0; -} \ No newline at end of file diff --git a/roofit/xroofit/src/coutCapture.h b/roofit/xroofit/src/coutCapture.h index a81a11d517f73..704fb3899347d 100644 --- a/roofit/xroofit/src/coutCapture.h +++ b/roofit/xroofit/src/coutCapture.h @@ -10,25 +10,46 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +#include "TSystem.h" +#include "TUUID.h" +#include + struct cout_redirect { - cout_redirect(std::string &_out, size_t bufSize = 102 * 1024) : out(_out) + cout_redirect(std::string &_out, size_t bufSize = 102 * 1024) : buffer2(nullptr), fp(nullptr), out(_out), fBufSize(bufSize) { + + filename = "xRooFit-logging-"; old = std::cout.rdbuf(buffer.rdbuf()); old2 = std::cerr.rdbuf(buffer.rdbuf()); - old3 = stdout; - buffer2 = (char *)calloc(sizeof(char), bufSize); - fp = fmemopen(buffer2, bufSize, "w"); - stdout = fp; + old3 = stdout; old4 = stderr; + //buffer2 = (char *)calloc(sizeof(char), bufSize);fp = fmemopen(buffer2, bufSize, "w"); + fp = gSystem->TempFileName(filename); + if(fp) { + stdout = fp; + stderr = fp; + } + } ~cout_redirect() { std::cout.rdbuf(old); std::cerr.rdbuf(old2); - std::fclose(fp); stdout = old3; + stderr = old4; + if(fp) { + std::fclose(fp); + { + std::ifstream t(filename); + buffer << t.rdbuf(); + } + gSystem->Unlink(filename); // delete the temp file + } out = buffer.str(); - out += buffer2; - free(buffer2); + if(buffer2) { + out += buffer2; + free(buffer2); + } + if (out.length() > fBufSize) out.resize(fBufSize); } private: @@ -36,6 +57,8 @@ struct cout_redirect { std::stringstream buffer; char *buffer2; FILE *fp; - FILE *old3; + FILE *old3; FILE *old4; std::string &out; + TString filename; + size_t fBufSize; }; \ No newline at end of file diff --git a/roofit/xroofit/src/xRooBrowser.cxx b/roofit/xroofit/src/xRooBrowser.cxx index 70d7a8aa08a4e..676ec6b564139 100644 --- a/roofit/xroofit/src/xRooBrowser.cxx +++ b/roofit/xroofit/src/xRooBrowser.cxx @@ -10,6 +10,54 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +/** \class ROOT::Experimental::XRooFit::xRooBrowser +\ingroup xroofit + + \image html RooBrowser.png width=50% + + \brief A version of the TBrowser that can be used to interact with RooFit models and datasets. + + Also available under the ROOT::Experimental::RooBrowser alias. + +To get started with the xRooBrowser, open any ROOT file containing a workspace + and then create an instance of the xRooBrowser just like + creating an instance of a `TBrowser`. A window will be displayed with a navigable + tree structure on the left that lets you explore the content of the workspaces + present in the loaded file. Note that additional files, including json workspace files, + can be loaded through the `Browser --> Open` menu in the top left corner. + +The context menu for each node (access by right clicking on the node) in the tree structure can be used to get more +information about the node. In particular, the `Draw` command can be selected on many of the nodes that are part of a +statistical model, which will visualize that part of the model in the browser window. A number of options are available +for the `Draw` command, including (some options can be combined): + + - "e" : calculate and visualize propagated model uncertainty + - "auxratio" : Draw a ratio auxiliary plot below the main plot + - "auxsignif" : Draw a significance auxiliary plot below the main plot + - "pull" : show panel of current parameter values, which can be dragged in order to change the values and visualize the +effect on the model (very experimental feature). + + Once a node has been drawn, the styling of subsequent draws can be controlled through `TStyle` objects + that will now appear in the `objects` folder in the workspace. + +A model can be fit to a dataset from the workspace using the `fitTo` context menu command and specifying + the name of a dataset in the workspace (if no name is given, an expected dataset corresponding to the + current state of the model will be used). A dialog will display the fit result status code when the + fit completes and then a `fits` folder will be found under the workspace (the workspace may need to + be collapsed and re-expanded to make it appear) where the fit result can be found, selected, and visualized. + In multi-channel models the channels that are included in the fit can be controlled with the checkboxes + in the browser. Clicking the checkbox will cycle through three states: checked, unchecked with + grey-underline, and checked with grey-underline. The grey-underline indicates that channel wont be + included in the fit (and will appear greyed out when the model is visualized) + +Many more features are available in the xRooBrowser, and further documentation and development can be found at + the xRooFit repository, which is the library where the browser has + been originally developed. The author (Will Buttinger) is also very happy to be contacted with questions or + feedback about this new functionality. + + */ + + #include "xRooFit/xRooBrowser.h" #include "xRooFit/xRooNode.h" @@ -19,14 +67,14 @@ #include "TEnv.h" #include "TFile.h" #include "RooWorkspace.h" -#define protected public #include "TRootBrowser.h" -#undef protected #include "TGMenu.h" #include "TGFileDialog.h" #include "TObjString.h" -BEGIN_XROOFIT_NAMESPACE +#define GETPOPUPMENU(b, m) ((TGPopupMenu *)(*(void **)(((unsigned char *)b) + b->Class()->GetDataMemberOffset(#m)))) + +BEGIN_XROOFIT_NAMESPACE; xRooBrowser::xRooBrowser(xRooNode *o) : TBrowser("RooBrowser", o, "RooFit Browser"), fTopNode(o) { @@ -61,8 +109,8 @@ xRooBrowser::xRooBrowser(xRooNode *o) : TBrowser("RooBrowser", o, "RooFit Browse // override file menu event handling so that can intercept "Open" if (auto rb = dynamic_cast(GetBrowserImp())) { - rb->Disconnect(rb->fMenuFile, "Activated(Int_t)", rb, "HandleMenu(Int_t)"); - rb->fMenuFile->Connect("Activated(Int_t)", ClassName(), this, "HandleMenu(Int_t)"); + rb->Disconnect(GETPOPUPMENU(rb, fMenuFile), "Activated(Int_t)", rb, "HandleMenu(Int_t)"); + GETPOPUPMENU(rb, fMenuFile)->Connect("Activated(Int_t)", ClassName(), this, "HandleMenu(Int_t)"); } } @@ -106,11 +154,21 @@ xRooBrowser::xRooBrowser() gEnv->SetValue("X11.Sync", "no"); gEnv->SetValue("X11.FindBestVisual", "no"); gEnv->SetValue("Browser.Name", "TRootBrowser"); // forces classic root browser (in 6.26 onwards) + gEnv->SetValue("Canvas.Name", "TRootCanvas"); return new xRooNode("!Workspaces"); }()) { } +xRooNode *xRooBrowser::Open(const char *filename) +{ + if (TString(filename).EndsWith(".root")) { + return fTopNode->emplace_back(std::make_shared(std::make_shared(filename))).get(); + } else { + return fTopNode->emplace_back(std::make_shared(filename)).get(); + } +} + void xRooBrowser::ls(const char *path) const { if (!fNode) @@ -134,4 +192,4 @@ xRooNode *xRooBrowser::GetSelected() return dynamic_cast(TBrowser::GetSelected()); } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/xRooFit.cxx b/roofit/xroofit/src/xRooFit.cxx index 1dabe57a574a7..cd2ba9735c779 100644 --- a/roofit/xroofit/src/xRooFit.cxx +++ b/roofit/xroofit/src/xRooFit.cxx @@ -10,9 +10,20 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +#include "RVersion.h" + +// #define private public +// #include "Minuit2/Minuit2Minimizer.h" +// #undef private +// #include "Minuit2/FunctionMinimum.h" + +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) #define protected public +#endif #include "RooFitResult.h" +#ifdef protected #undef protected +#endif #include "xRooFit/xRooFit.h" @@ -33,11 +44,8 @@ #include "RooStats/AsymptoticCalculator.h" #include "Math/GenAlgoOptions.h" - -#define private public +#include "Math/Minimizer.h" #include "RooMinimizer.h" -#undef private - #include "coutCapture.h" #include "TCanvas.h" @@ -49,18 +57,32 @@ #include "RooStringVar.h" #include "RooRealProxy.h" +#include "RooSuperCategory.h" #include "xRooFitVersion.h" #include -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; + +std::shared_ptr xRooFit::sDefaultNLLOptions = nullptr; +std::shared_ptr xRooFit::sDefaultFitConfig = nullptr; RooCmdArg xRooFit::ReuseNLL(bool flag) { return RooCmdArg("ReuseNLL", flag, 0, 0, 0, 0, 0, 0, 0); } +RooCmdArg xRooFit::Tolerance(double val) +{ + return RooCmdArg("Tolerance", 0, 0, val); +} + +RooCmdArg xRooFit::StrategySequence(const char *val) +{ + return RooCmdArg("StrategySequence", 0, 0, 0, 0, val); +} + xRooNLLVar xRooFit::createNLL(const std::shared_ptr pdf, const std::shared_ptr data, const RooLinkedList &nllOpts) { @@ -110,11 +132,12 @@ std::shared_ptr xRooFit::fitTo(RooAbsPdf &pdf, } std::pair, std::shared_ptr> -xRooFit::generateFrom(RooAbsPdf &pdf, const std::shared_ptr &fr, bool expected, int seed) +xRooFit::generateFrom(RooAbsPdf &pdf, const RooFitResult &_fr, bool expected, int seed) { std::pair, std::shared_ptr> out; + auto fr = &_fr; if (!fr) return out; @@ -308,10 +331,10 @@ xRooFit::generateFrom(RooAbsPdf &pdf, const std::shared_ptr auto r = dynamic_cast(o); if (!r) continue; - if (_pdf->isBinnedDistribution(*r)) { + if (auto res = _pdf->binBoundaries(*r, -std::numeric_limits::infinity(), + std::numeric_limits::infinity())) { binnings[r] = std::shared_ptr(r->getBinning().clone(r->getBinning().GetName())); - auto res = _pdf->binBoundaries(*r, -std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + std::vector boundaries; boundaries.reserve(res->size()); for (auto &rr : *res) { @@ -338,7 +361,8 @@ xRooFit::generateFrom(RooAbsPdf &pdf, const std::shared_ptr _out.first->add(_tmp); } else { if (_pdf->canBeExtended()) { - _out.first.reset(_pdf->generate(*_obs, RooFit::Extended(), RooFit::ExpectedData(expected))); + _out.first = + std::unique_ptr{_pdf->generate(*_obs, RooFit::Extended(), RooFit::ExpectedData(expected))}; } else { if (expected) { // use AsymptoticCalculator because generate expected not working correctly on unextended pdf? @@ -346,7 +370,7 @@ xRooFit::generateFrom(RooAbsPdf &pdf, const std::shared_ptr // ObsToExpected? _out.first.reset(RooStats::AsymptoticCalculator::GenerateAsimovData(*_pdf, *_obs)); } else { - _out.first.reset(_pdf->generate(*_obs, RooFit::ExpectedData(expected))); + _out.first = std::unique_ptr{_pdf->generate(*_obs, RooFit::ExpectedData(expected))}; } } } @@ -369,17 +393,50 @@ xRooFit::generateFrom(RooAbsPdf &pdf, const std::shared_ptr }; out = genSubPdf(&pdf); - out.first->SetName(uuid); + out.first->SetName(expected ? (TString(fr->GetName()) + "_asimov") : uuid); + + // from now on we store the globs in the dataset + if (out.second) { + out.first->setGlobalObservables(*out.second); + out.second.reset(); + } #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00) // store fitResult name on the weightVar if (auto w = dynamic_cast(out.first.get())->weightVar()) { w->setStringAttribute("fitResult", fr->GetName()); + w->setAttribute("expected", expected); } #endif *_allVars = *_snap; + // June2023: Added this because found that generation was otherwise getting progressively slower + // the RooAbsPdf::generate does a clone, and it seems that the RooCacheManager of the original pdf + // is getting polluted on each generate call, causing it to grow larger and therefore the clone of it + // to take longer and longer. So sterilize to clear the caches of all components +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + auto _ws = pdf._myws; +#else + auto _ws = pdf.workspace(); +#endif + if (_ws) { + // do explicitly rather than via xRooNode sterilize method because don't want to invoke the constructor + // workspace tweaking features (which sets poi etc etc) + for (auto obj : _ws->components()) { + for (int i = 0; i < obj->numCaches(); i++) { + if (auto cache = dynamic_cast(obj->getCache(i))) { + cache->reset(); + } + } + if (RooAbsPdf *p = dynamic_cast(obj); p) { + p->setNormRange(p->normRange()); + } + obj->setValueDirty(); + } + // xRooNode(pdf.workspace()).sterilize(); + } + return out; } @@ -389,17 +446,38 @@ std::shared_ptr xRooFit::createNLLOptions() l->Delete(); delete l; }); - out->Add(RooFit::Offset().Clone()); - out->Add( - RooFit::Optimize(0) - .Clone()); // disable const-optimization at the construction step ... can happen in the minimization though + for (auto opt : *defaultNLLOptions()) { + out->Add(opt->Clone(nullptr)); // nullptr needed because accessing Clone via TObject base class puts + // "" instead, so doesnt copy names + } return out; } +std::shared_ptr xRooFit::defaultNLLOptions() +{ + if (sDefaultNLLOptions) + return sDefaultNLLOptions; + sDefaultNLLOptions = std::shared_ptr(new RooLinkedList, [](RooLinkedList *l) { + l->Delete(); + delete l; + }); + sDefaultNLLOptions->Add(RooFit::Offset().Clone()); + // disable const-optimization at the construction step ... can happen in the minimization though + sDefaultNLLOptions->Add(RooFit::Optimize(0).Clone()); + return sDefaultNLLOptions; +} + std::shared_ptr xRooFit::createFitConfig() { - auto fFitConfig = std::make_shared(); - auto &fitConfig = *fFitConfig; + return std::make_shared(*defaultFitConfig()); +} + +std::shared_ptr xRooFit::defaultFitConfig() +{ + if (sDefaultFitConfig) + return sDefaultFitConfig; + sDefaultFitConfig = std::make_shared(); + auto &fitConfig = *sDefaultFitConfig; fitConfig.SetParabErrors(true); // will use to run hesse after fit fitConfig.MinimizerOptions().SetMinimizerType("Minuit2"); fitConfig.MinimizerOptions().SetErrorDef(0.5); // ensures errors are +/- 1 sigma ..IMPORTANT @@ -408,7 +486,7 @@ std::shared_ptr xRooFit::createFitConfig() fitConfig.MinimizerOptions().SetMaxFunctionCalls( -1); // calls per iteration. if left as 0 will set automatically to 500*nPars below fitConfig.MinimizerOptions().SetMaxIterations(-1); // if left as 0 will set automatically to 500*nPars - fitConfig.MinimizerOptions().SetStrategy(0); + fitConfig.MinimizerOptions().SetStrategy(-1); // will start at front of StrategySequence (given below) // fitConfig.MinimizerOptions().SetTolerance( // 1); // default is 0.01 (i think) but roominimizer uses 1 as default - use specify with // ROOT::Math::MinimizerOptions::SetDefaultTolerance(..) @@ -418,14 +496,24 @@ std::shared_ptr xRooFit::createFitConfig() auto extraOpts = const_cast(fitConfig.MinimizerOptions().ExtraOptions()); extraOpts->SetValue("OptimizeConst", 2); // if 0 will disable constant term optimization and cache-and-track of the // NLL. 1 = just caching, 2 = cache and track +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00) + extraOpts->SetValue("StrategySequence", "0s01s12s2s3m"); + extraOpts->SetValue("HesseStrategy", 3); // if hesse is run after minimization, will use this strategy +#else extraOpts->SetValue("StrategySequence", "0s01s12s2m"); + extraOpts->SetValue("HesseStrategy", 2); // when hesse is run after minimization, will use this strategy +#endif extraOpts->SetValue("LogSize", 0); // length of log to capture and save extraOpts->SetValue("BoundaryCheck", 0.); // if non-zero, warn if any post-fit value is close to boundary (e.g. 0.01 = within 1%) extraOpts->SetValue("TrackProgress", 30); // seconds between output to log of evaluation progress extraOpts->SetValue("xRooFitVersion", GIT_COMMIT_HASH); // not really options but here for logging purposes // extraOpts->SetValue("ROOTVersion",ROOT_VERSION_CODE); - not needed as should by part of the ROOT TFile definition - return fFitConfig; + + // extraOpts->SetValue("HessianStepTolerance",0.); + // extraOpts->SetValue("HessianG2Tolerance",0.); + + return sDefaultFitConfig; } class ProgressMonitor : public RooAbsReal { @@ -450,6 +538,7 @@ class ProgressMonitor : public RooAbsReal { s.Start(); oldHandlerr = signal(SIGINT, interruptHandler); me = this; + vars.reset(std::unique_ptr(f.getVariables())->selectByAttrib("Constant", false)); } virtual ~ProgressMonitor() { @@ -467,45 +556,100 @@ class ProgressMonitor : public RooAbsReal { double evaluate() const override { - if (fInterrupt) + if (fInterrupt) { + throw std::runtime_error("Keyboard interrupt"); return std::numeric_limits::quiet_NaN(); + } double out = fFunc; - if (prevMin == std::numeric_limits::infinity()) + if (prevMin == std::numeric_limits::infinity()) { prevMin = out; - if (!std::isnan(out)) + prevPars.addClone(*vars); + } + if (!std::isnan(out)) { + if (out < minVal) { + if (minPars.empty()) + minPars.addClone(*vars); + minPars = *vars; + } minVal = std::min(minVal, out); + } counter++; if (s.RealTime() > fInterval) { + double evalRate = (counter - prevCounter) / s.RealTime(); s.Reset(); - std::cerr << (counter) << ") " << TDatime().AsString() << " : " << minVal << " Delta = " << (minVal - prevMin) - << std::endl; + std::cerr << (counter) << ") (" << evalRate << "Hz) " << TDatime().AsString(); + if (!fState.empty()) + std::cerr << " : " << fState; + std::cerr << " : " << minVal << " Delta = " << (minVal - prevMin); + if (minVal < prevMin) { + std::cerr << " : "; + // compare minPars and prevPars, print biggest deltas + std::vector> parDeltas; + parDeltas.reserve(minPars.size()); + for (auto p : minPars) { + parDeltas.emplace_back(std::pair( + dynamic_cast(p)->getVal() - prevPars.getRealValue(p->GetName()), p->GetName())); + } + std::sort(parDeltas.begin(), parDeltas.end(), + [](auto &left, auto &right) { return std::abs(left.first) > std::abs(right.first); }); + int i; + for (i = 0; i < std::min(3, int(parDeltas.size())); i++) { + if (parDeltas.at(i).first == 0) + break; + if (i != 0) + std::cerr << ","; + std::cerr << parDeltas.at(i).second << (parDeltas.at(i).first >= 0 ? "+" : "-") << "=" + << std::abs(parDeltas.at(i).first) << "(" + << minPars.getRealValue(parDeltas.at(i).second.c_str()) << ")"; + } + if (i < int(parDeltas.size()) && parDeltas.at(i).first != 0) + std::cerr << " ..."; + prevPars.assignFast(minPars); + } + std::cerr << std::endl; prevMin = minVal; + prevCounter = counter; } else { s.Continue(); } return out; } + std::string fState; + private: RooRealProxy fFunc; mutable int counter = 0; mutable double minVal = std::numeric_limits::infinity(); mutable double prevMin = std::numeric_limits::infinity(); + mutable RooArgList minPars; + mutable RooArgList prevPars; + mutable int prevCounter = 0; mutable int fInterval = 0; // time in seconds before next report mutable TStopwatch s; + std::shared_ptr vars; }; bool ProgressMonitor::fInterrupt = false; ProgressMonitor *ProgressMonitor::me = nullptr; -std::shared_ptr -xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr &_fitConfig) +xRooFit::StoredFitResult::StoredFitResult(RooFitResult *_fr) : TNamed(*_fr) +{ + fr.reset(_fr); +} + +xRooFit::StoredFitResult::StoredFitResult(const std::shared_ptr &_fr) : TNamed(*_fr) +{ + fr = _fr; +} + +std::shared_ptr xRooFit::minimize(RooAbsReal &nll, + const std::shared_ptr &_fitConfig, + const std::shared_ptr &nllOpts) { auto myFitConfig = _fitConfig ? _fitConfig : createFitConfig(); auto &fitConfig = *myFitConfig; - bool save = true; - auto _nll = &nll; TString resultTitle = nll.getStringAttribute("fitresultTitle"); @@ -529,19 +673,25 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & auto _nllVars = std::unique_ptr(_nll->getVariables()); - std::unique_ptr constPars(_nllVars->selectByAttrib("Constant", kTRUE)); + std::unique_ptr constPars(_nllVars->selectByAttrib("Constant", true)); constPars->add(fUserPars, true); // add here so checked for when loading from cache - std::unique_ptr floatPars(_nllVars->selectByAttrib("Constant", kFALSE)); + std::unique_ptr floatPars(_nllVars->selectByAttrib("Constant", false)); int _progress = 0; double boundaryCheck = 0; std::string s; int logSize = 0; +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00) + int hesseStrategy = 3; // uses most precise hesse settings (step sizes and g2 tolerances) +#else + int hesseStrategy = 2; // uses most precise hesse settings (step sizes and g2 tolerances) +#endif if (fitConfig.MinimizerOptions().ExtraOptions()) { fitConfig.MinimizerOptions().ExtraOptions()->GetNamedValue("StrategySequence", s); fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue("TrackProgress", _progress); fitConfig.MinimizerOptions().ExtraOptions()->GetRealValue("BoundaryCheck", boundaryCheck); fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue("LogSize", logSize); + fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue("HesseStrategy", hesseStrategy); } TString m_strategy = s; @@ -555,7 +705,18 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & for (auto &&k : *keys) { auto cl = TClass::GetClass(((TKey *)k)->GetClassName()); if (cl->InheritsFrom("RooFitResult")) { - if (auto cachedFit = nllDir->Get(k->GetName()); cachedFit) { + StoredFitResult *storedFr = + nllDir->GetList() ? dynamic_cast(nllDir->GetList()->FindObject(k->GetName())) + : nullptr; + if (auto cachedFit = + (storedFr) ? storedFr->fr.get() : dynamic_cast(k)->ReadObject(); + cachedFit) { + if (!storedFr) { + storedFr = new StoredFitResult(cachedFit); + nllDir->Add(storedFr); + // std::cout << "Loaded " << nllDir->GetPath() << "/" << k->GetName() << " : " << k->GetTitle() + // << std::endl; + } bool match = true; if (!cachedFit->floatParsFinal().equals(*floatPars)) { match = false; @@ -569,7 +730,7 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & if (auto _p = dynamic_cast(cachedFit->constPars().find(p->GetName())); _p) { // note: do not need global observable values to match (globals currently added to // constPars list) - if (!_p->getAttribute("global") && abs(_p->getVal() - v->getVal()) > 1e-12) { + if (!_p->getAttribute("global") && std::abs(_p->getVal() - v->getVal()) > 1e-12) { match = false; break; } @@ -577,9 +738,13 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & } } if (match) { - return std::shared_ptr(cachedFit); // return a copy; + return storedFr->fr; + // return std::shared_ptr(cachedFit,[](RooFitResult*){}); // dir owns the + // fitResult - this means dir needs to stay open for fits to be valid return + // std::make_shared(*cachedFit); // return a copy ... dir doesn't need to stay + // open, but fit result isn't shared } else { - delete cachedFit; + // delete cachedFit; } } } @@ -597,7 +762,7 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL); // check how many parameters we have ... if 0 parameters then we wont run a fit, we just evaluate nll and return ... - if (floatPars->getSize() == 0 || fitConfig.MinimizerOptions().MaxFunctionCalls() == 1) { + if (floatPars->empty() || fitConfig.MinimizerOptions().MaxFunctionCalls() == 1) { std::shared_ptr result; RooArgList parsList; parsList.add(*floatPars); @@ -616,11 +781,24 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & result->setEDM(0); result->setStatus(floatPars->getSize() == 0 ? 0 : 1); + std::vector> statusHistory; + statusHistory.emplace_back(std::make_pair("EVAL", result->status())); + result->setStatusHistory(statusHistory); + if (cacheDir && cacheDir->IsWritable()) { // save a copy of fit result to relevant dir if (!cacheDir->GetDirectory(nll.GetName())) cacheDir->mkdir(nll.GetName()); if (auto dir = cacheDir->GetDirectory(nll.GetName()); dir) { + // save NLL opts if was given one, unless already present + if (nllOpts) { + if (strlen(nllOpts->GetName()) == 0) { + nllOpts->SetName(TUUID().AsString()); + } + if (!dir->FindKey(nllOpts->GetName())) { + dir->WriteObject(nllOpts.get(), nllOpts->GetName()); + } + } dir->WriteObject(result.get(), result->GetName()); } } @@ -630,24 +808,75 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & return result; } - int strategy = fitConfig.MinimizerOptions().Strategy(); - // Note: AsymptoticCalculator enforces not less than 1 on tolerance - should we do so too? + std::shared_ptr out; - if (_progress) { - _nll = new ProgressMonitor(*_nll, _progress); - ProgressMonitor::fInterrupt = false; + // check if any floatPars are categorical .. if so, need to a "discrete minimization" over the permutations + RooArgSet floatCats; + for (auto p : *floatPars) { + if (p->isCategory()) { + floatCats.add(*p); + } } + if (!floatCats.empty()) { + RooSuperCategory allCats("floatCats", "Floating categorical parameters", floatCats); + std::unique_ptr _snap(floatCats.snapshot()); + floatCats.setAttribAll("Constant"); + + std::shared_ptr bestFr; + for (auto c : allCats) { + allCats.setIndex(c.second); + Info("minimize", "Minimizing with discrete %s", c.first.c_str()); + auto fr = minimize(nll, _fitConfig, nllOpts); + if (!fr) { + Warning("minimize", "Minimization with discrete %s failed", c.first.c_str()); + continue; + } + if (!bestFr || fr->minNll() < bestFr->minNll()) { + bestFr = fr; + } + } + floatCats.setAttribAll("Constant", false); + + if (!bestFr) + return out; + + // create a copy of the fit result, give it a new uuid, and move the const categories into the float area + out = std::make_shared(*bestFr); + const_cast(out->floatParsFinal()) + .addClone(*std::unique_ptr(out->constPars().selectCommon(floatCats))); + const_cast(out->floatParsInit()).addClone(*_snap); + const_cast(out->constPars()).remove(floatCats); + out->SetName(TUUID().AsString()); + } + + bool restore = !fitConfig.UpdateAfterFit(); std::string logs; - RooFitResult *out = nullptr; - { + if (!out) { + int strategy = fitConfig.MinimizerOptions().Strategy(); + // Note: AsymptoticCalculator enforces not less than 1 on tolerance - should we do so too? + if (_progress) { + _nll = new ProgressMonitor(*_nll, _progress); + ProgressMonitor::fInterrupt = false; + } auto logger = (logSize > 0) ? std::make_unique(logs, logSize) : nullptr; RooMinimizer _minimizer(*_nll); _minimizer.fitter()->Config() = fitConfig; + // if(fitConfig.MinimizerOptions().ExtraOptions()) { + // //for loading hesse options + // double a; + // if(fitConfig.MinimizerOptions().ExtraOptions()->GetValue("HessianStepTolerance",a)) { + // ROOT::Math::MinimizerOptions::Default("Minuit2").SetValue("HessianStepTolerance",a); + // } + // if(fitConfig.MinimizerOptions().ExtraOptions()->GetValue("HessianG2Tolerance",a)) { + // ROOT::Math::MinimizerOptions::Default("Minuit2").SetValue("HessianG2Tolerance",a); + // } + // } bool autoMaxCalls = (_minimizer.fitter()->Config().MinimizerOptions().MaxFunctionCalls() == 0); if (autoMaxCalls) { - _minimizer.fitter()->Config().MinimizerOptions().SetMaxFunctionCalls(500 * floatPars->size()); + _minimizer.fitter()->Config().MinimizerOptions().SetMaxFunctionCalls( + 500 * floatPars->size() * floatPars->size()); // hesse requires O(N^2) function calls } if (_minimizer.fitter()->Config().MinimizerOptions().MaxIterations() == 0) { _minimizer.fitter()->Config().MinimizerOptions().SetMaxIterations(500 * floatPars->size()); @@ -658,10 +887,9 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & false); // turn "off" so can run hesse as a separate step, appearing in status bool minos = _minimizer.fitter()->Config().MinosErrors(); _minimizer.fitter()->Config().SetMinosErrors(false); - bool restore = !_minimizer.fitter()->Config().UpdateAfterFit(); _minimizer.fitter()->Config().SetUpdateAfterFit(true); // note: seems to always take effect - std::vector algNames; + std::vector> statusHistory; // gCurrentSampler = this; // gOldHandlerr = signal(SIGINT,toyInterruptHandlerr); @@ -693,16 +921,42 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & int sIdx = -1; TString minim = _minimizer.fitter()->Config().MinimizerType(); TString algo = _minimizer.fitter()->Config().MinimizerAlgoType(); - if (minim == "Minuit2") - sIdx = m_strategy.Index('0' + strategy); - else if (minim == "Minuit") + if (minim == "Minuit2") { + if (strategy == -1) + sIdx = 0; + else + sIdx = m_strategy.Index('0' + strategy); + if (sIdx == -1) { + Warning("minimize", "Strategy %d not specified in StrategySequence %s ... defaulting to start of sequence", + strategy, m_strategy.Data()); + sIdx = 0; + } + } else if (minim == "Minuit") sIdx = m_strategy.Index('m'); int tries = 0; int maxtries = 4; bool first = true; while (tries < maxtries && sIdx != -1) { - status = _minimizer.minimize(minim, algo); + if (m_strategy(sIdx) == 'm') { + minim = "Minuit"; + algo = "migradImproved"; + } else if (m_strategy(sIdx) == 's') { + algo = "Scan"; + } else { + strategy = int(m_strategy(sIdx) - '0'); + _minimizer.setStrategy(strategy); + minim = "Minuit2"; + algo = "Migrad"; + } + if (auto fff = dynamic_cast(_nll); fff) { + fff->fState = minim + algo + std::to_string(_minimizer.fitter()->Config().MinimizerOptions().Strategy()); + } + try { + status = _minimizer.minimize(minim, algo); + } catch (const std::exception &e) { + std::cerr << "Exception while minimizing: " << e.what() << std::endl; + } if (first && actualFirstMinimizer != _minimizer.fitter()->Config().MinimizerType()) actualFirstMinimizer = _minimizer.fitter()->Config().MinimizerType(); first = false; @@ -717,17 +971,15 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & status = _minimizer.fitter() ->Result() .Status(); // note: Minuit failure is status code 4, minuit2 that is edm above max - _minimizer._statusHistory.back().second = _minimizer.fitter()->Result().Status(); minim = _minimizer.fitter()->Config().MinimizerType(); // may have changed value - if (save) - algNames.push_back(_minimizer.fitter()->Config().MinimizerType() + - _minimizer.fitter()->Config().MinimizerAlgoType() + - std::to_string(_minimizer.fitter()->Config().MinimizerOptions().Strategy())); - // int status = _minimizer->migrad(); + statusHistory.emplace_back(_minimizer.fitter()->Config().MinimizerType() + + _minimizer.fitter()->Config().MinimizerAlgoType() + + std::to_string(_minimizer.fitter()->Config().MinimizerOptions().Strategy()), + status); if (status % 1000 == 0) break; // fit was good - if (_minimizer.fitter()->Result().Status() == 4 && minim != "Minuit") { + if (status == 4 && minim != "Minuit") { if (printLevel >= -1) Warning("fitTo", "%s Hit max function calls of %d", fitName.Data(), _minimizer.fitter()->Config().MinimizerOptions().MaxFunctionCalls()); @@ -746,7 +998,9 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & // specified Also note that if fits are failing because of edm over max, it can be a good idea to activate the // Offset option when building nll if (printLevel >= -1) - Warning("fitTo", "%s Status=%d (edm=%f, tol=%f, strat=%d), tries=#%d...", fitName.Data(), status, + Warning("fitTo", "%s %s%s Status=%d (edm=%f, tol=%f, strat=%d), tries=#%d...", fitName.Data(), + _minimizer.fitter()->Config().MinimizerType().c_str(), + _minimizer.fitter()->Config().MinimizerAlgoType().c_str(), status, _minimizer.fitter()->Result().Edm(), _minimizer.fitter()->Config().MinimizerOptions().Tolerance(), _minimizer.fitter()->Config().MinimizerOptions().Strategy(), tries); @@ -755,17 +1009,6 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & break; // done } - if (m_strategy(sIdx + 1) == 'm') { - minim = "Minuit"; - algo = "migradImproved"; - } else if (m_strategy(sIdx + 1) == 's') { - algo = "Scan"; - } else { - strategy = int(m_strategy(sIdx + 1) - '0'); - _minimizer.setStrategy(strategy); - minim = "Minuit2"; - algo = "Migrad"; - } tries--; sIdx++; } @@ -785,22 +1028,81 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & Warning("fitTo", "%s final status is %d", fitName.Data(), status); } - if (hesse && _minimizer.fitter()->Result().IsValid()) { // only do hesse if was a valid min - - // remove limits on pars before calculation - // interesting note: error on pars before hesse can be significantly - // smaller than after hesse ... what is the pre-hesse error corresponding to? - auto parSettings = _minimizer.fitter()->Config().ParamsSettings(); + // currently dont have a way to access the covariance "dcovar" which is a metric from iterative + // covariance method that is used by minuit2 to say if the covariance is accurate or not + // See MinimumError.h: IsAccurate if Dcovar < 0.1 + // Note that if strategy=2 or strategy=1 and Dcovar>0.05 then hesse will be forced to be run (see + // VariadicMetricBuilder) So only in Strategy=0 can you skip hesse (even if SetParabErrors false). + + double dCovar = std::numeric_limits::quiet_NaN(); + // if(auto _minuit2 = dynamic_cast(_minimizer.fitter()->GetMinimizer()); + // _minuit2 && _minuit2->fMinimum) { + // dCovar = _minuit2->fMinimum->Error().Dcovar(); + // } + + // only do hesse if was a valid min and not strat2 or above (since such strat already ran hesse, albeit with + // allowing for forced pos-def) or if requested hesse strategy is different to the strategy that minimization ran + // at + if (hesse && (strategy < 2 || strategy != hesseStrategy) && _minimizer.fitter()->Result().IsValid()) { + // Note: minima where the covariance was made posdef are deemed 'valid' ... + + // remove limits on pars before calculation - CURRENTLY HAS NO EFFECT, minuit still holds the state as + // transformed interesting note: error on pars before hesse can be significantly smaller than after hesse ... + // what is the pre-hesse error corresponding to? - corresponds to approximation of covariance matrix calculated + // with iterative method + /*auto parSettings = _minimizer.fitter()->Config().ParamsSettings(); for (auto &ss : _minimizer.fitter()->Config().ParamsSettings()) { ss.RemoveLimits(); } + for(auto f : *floatPars) { + auto v = dynamic_cast(f); + if(v->hasRange(nullptr)) v->setRange("backup",v->getMin(),v->getMax()); + v->removeRange(); + }*/ + + // std::cout << "nIterations = " << _minimizer.fitter()->GetMinimizer()->NIterations() << std::endl; + // std::cout << "covQual before hesse = " << _minimizer.fitter()->GetMinimizer()->CovMatrixStatus() << + // std::endl; + + _minimizer.fitter()->Config().MinimizerOptions().SetStrategy(hesseStrategy); + + // const_cast(_minimizer.fitter()->Config().MinimizerOptions().ExtraOptions())->SetValue("HessianStepTolerance",0.1); + // const_cast(_minimizer.fitter()->Config().MinimizerOptions().ExtraOptions())->SetValue("HessianG2Tolerance",0.02); + + if (auto fff = dynamic_cast(_nll); fff) { + fff->fState = TString::Format("Hesse%d", _minimizer.fitter()->Config().MinimizerOptions().Strategy()); + } + //_nll->getVal(); // for reasons I dont understand, if nll evaluated before hesse call the edm is smaller? - // and also becomes WRONG :-S + + // auto _status = (_minimizer.fitter()->CalculateHessErrors()) ? _minimizer.fitter()->Result().Status() : -1; auto _status = _minimizer.hesse(); // note: I have seen that you can get 'full covariance quality' without // running hesse ... is that expected? + // note: hesse status will be -1 if hesse failed (no covariance matrix) + // otherwise the status appears to be whatever was the status before + // note that hesse succeeds even if the cov matrix it calculates is forced pos def. Failure is only + // if it cannot calculate a cov matrix at all. + if (_status != -1) + _status = 0; // mark as hesse succeeded, although need to look at covQual to see if was any good + + /*for(auto f : *floatPars) { + auto v = dynamic_cast(f); + if(v->hasRange("backup")) { + v->setRange(v->getMin(),v->getMax()); + v->removeRange("backup"); + } + } + _minimizer.fitter()->Config().SetParamsSettings(parSettings);*/ + + /*for (auto &ss : _minimizer.fitter()->Config().ParamsSettings()) { + if( ss.HasLowerLimit() || ss.HasUpperLimit() ) std::cout << ss.Name() << " limit restored " << + ss.LowerLimit() << " - " << ss.UpperLimit() << std::endl; + }*/ - _minimizer.fitter()->Config().SetParamsSettings(parSettings); + statusHistory.push_back(std::pair( + TString::Format("Hesse%d", _minimizer.fitter()->Config().MinimizerOptions().Strategy()), _status)); if (auto fff = dynamic_cast(_nll); fff && fff->fInterrupt) { delete _nll; @@ -811,22 +1113,44 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & } } + // call minos if requested on any parameters + if (status == 0 && minos) { + if (std::unique_ptr mpars(floatPars->selectByAttrib("minos", true)); !mpars->empty()) { + if (auto fff = dynamic_cast(_nll); fff) { + fff->fState = "Minos"; + } + auto _status = _minimizer.minos(*mpars); + statusHistory.push_back(std::pair("Minos", _status)); + } + } + // DO NOT DO THIS - seems to mess with the NLL function in a way that breaks the cache - reactivating wont fix // if(constOptimize) { _minimizer.optimizeConst(0); } // doing this because saw happens in RooAbsPdf::minimizeNLL // method // signal(SIGINT,gOldHandlerr); - out = _minimizer.save(fitName, resultTitle); - - if (save) { - // modify the statusHistory to use the algnames instead .. - int i = 0; - for (auto &ss : algNames) { - out->_statusHistory[i++].first = ss; + out = std::unique_ptr{_minimizer.save(fitName, resultTitle)}; + + // if status is 0 (min succeeded) but the covQual isn't fully accurate but requested hesse, reflect that in the + // status + if (out->status() == 0 && out->covQual() != 3 && hesse) { + if (out->covQual() == 2) { // was made posdef + out->setStatus(1); // indicates covariance made pos-def + } else { // anything else indicates either hessian is approximate or something else wrong (e.g. not pos-def + // return from strat3) + out->setStatus(2); // hesse invalid } } - out->_constPars->addClone(fUserPars, true); + out->setStatusHistory(statusHistory); + + // userPars wont have been added to the RooFitResult by RooMinimizer + const_cast(out->constPars()).addClone(fUserPars, true); + + if (!std::isnan(dCovar)) { + const_cast(out->constPars()) + .addClone(RooRealVar(".dCovar", "dCovar from minimization", dCovar), true); + } if (boundaryCheck) { // check if any of the parameters are at their limits (potentially a problem with fit) @@ -849,7 +1173,7 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & v->setVal(v->getMin()); double boundary_nll = _nll->getVal(); if (boundary_nll <= out->minNll()) { - ((RooRealVar *)out->_finalPars->find(v->GetName()))->setVal(v->getMin()); + static_cast(out->floatParsFinal().find(v->GetName()))->setVal(v->getMin()); out->setMinNLL(boundary_nll); // Info("fit","Corrected %s onto minimum @ %g",v->GetName(),v->getMin()); } else { @@ -873,16 +1197,17 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & } if (limit_status == 900) { if (printLevel >= 0) - Warning("miminize", "BOUNDCHK: Parameters within %g%% limit in fit result: %s", boundaryCheck * 100, + Warning("minimize", "BOUNDCHK: Parameters within %g%% limit in fit result: %s", boundaryCheck * 100, listpars.c_str()); } else if (limit_status > 0) { if (printLevel >= 0) - Warning("miminize", "BOUNDCHK: Parameters near limit in fit result"); + Warning("minimize", "BOUNDCHK: Parameters near limit in fit result"); } // store the limit check result - out->_statusHistory.push_back(std::make_pair("BOUNDCHK", limit_status)); - out->_status += limit_status; + statusHistory.emplace_back("BOUNDCHK", limit_status); + out->setStatusHistory(statusHistory); + out->setStatus(out->status() + limit_status); } // // automatic parameter range adjustment based on errors @@ -910,9 +1235,10 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & // value out->setMinNLL(_nll->getVal()); - // ensure no asymm errors on any pars + // ensure no asymm errors on any pars unless had minuitMinos for (auto o : out->floatParsFinal()) { - if (auto v = dynamic_cast(o); v) + if (auto v = dynamic_cast(o); + v && !v->getAttribute("minos") && !v->getAttribute("xminos") && !v->getAttribute("xMinos")) v->removeAsymError(); } @@ -927,28 +1253,46 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & // call minos if requested on any parameters if (status == 0 && minos) { - std::unique_ptr pars(floatPars->selectByAttrib("minos", true)); - for (auto p : *pars) { - xRooFit::minos(nll, *out, p->GetName(), myFitConfig); + for (auto label : {"xminos", "xMinos"}) { + std::unique_ptr pars(floatPars->selectByAttrib(label, true)); + for (auto p : *pars) { + Info("minimize", "Computing xminos error for %s", p->GetName()); + xRooFit::minos(nll, *out, p->GetName(), myFitConfig); + } + if (!pars->empty()) + *floatPars = out->floatParsFinal(); // put values back to best fit } - if (!pars->empty()) - *floatPars = out->floatParsFinal(); // put values back to best fit } + } - if (restore) { - *floatPars = out->floatParsInit(); - } + if (restore) { + *floatPars = out->floatParsInit(); } + if (out && !logs.empty()) { // save logs to StringVar in constPars list - out->_constPars->addClone(RooStringVar(".log", "log", logs.c_str())); +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00) + const_cast(out->constPars()).addOwned(std::make_unique(".log", "log", logs.c_str())); +#else + const_cast(out->constPars()).addOwned(*new RooStringVar(".log", "log", logs.c_str())); +#endif } if (out && cacheDir && cacheDir->IsWritable()) { - // save a copy of fit result to relevant dir + // std::cout << "Saving " << out->GetName() << " " << out->GetTitle() << " to " << nll.GetName() << std::endl; + // save a copy of fit result to relevant dir if (!cacheDir->GetDirectory(nll.GetName())) cacheDir->mkdir(nll.GetName()); if (auto dir = cacheDir->GetDirectory(nll.GetName()); dir) { + // save NLL opts if was given one, unless already present + if (nllOpts) { + if (strlen(nllOpts->GetName()) == 0) { + nllOpts->SetName(TUUID().AsString()); + } + if (!dir->FindKey(nllOpts->GetName())) { + dir->WriteObject(nllOpts.get(), nllOpts->GetName()); + } + } // also save the fitConfig ... unless one with same name already present std::string configName; @@ -961,13 +1305,22 @@ xRooFit::minimize(RooAbsReal &nll, const std::shared_ptr & dir->WriteObject(&fitConfig, configName.data()); } // add the fitConfig name into the fit result before writing, so can retrieve in future - out->_constPars->addClone(RooStringVar(".fitConfigName", "fitConfigName", configName.c_str())); - - dir->WriteObject(out, out->GetName()); +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00) + const_cast(out->constPars()) + .addOwned(std::make_unique(".fitConfigName", "fitConfigName", configName.c_str())); +#else + const_cast(out->constPars()) + .addOwned(*new RooStringVar(".fitConfigName", "fitConfigName", configName.c_str())); +#endif + dir->WriteObject(out.get(), out->GetName()); + auto sfr = new StoredFitResult(out); + dir->Add(sfr); + return sfr->fr; + // return std::shared_ptr(out, [](const RooFitResult*){}); // disowned shared_ptr } } - return std::shared_ptr(out); + return out; } // calculate asymmetric errors, if required, on the named parameter that was floating in the fit @@ -994,6 +1347,7 @@ int xRooFit::minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parNam double val_best = par_hat->getVal(); double val_err = (par_hat->hasError() ? par_hat->getError() : -1); + double orig_err = val_err; double nll_min = ufit.minNll(); int status = 0; @@ -1004,18 +1358,19 @@ int xRooFit::minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parNam auto findValue = [&](double val_guess, double N_sigma = 1, double precision = 0.002, int printLevel = 0) { double tmu; int nrItr = 0; - double sigma_guess = fabs((val_guess - val_best) / N_sigma); + double sigma_guess = std::abs((val_guess - val_best) / N_sigma); double val_pre = val_guess - 10 * precision * sigma_guess; // this is just to set value st. guarantees will do at least one iteration bool lastOverflow = false, lastUnderflow = false; - while (fabs(val_pre - val_guess) > precision * sigma_guess) { + while (std::abs(val_pre - val_guess) > precision * sigma_guess) { val_pre = val_guess; if (val_guess > 0 && par->getMax() < val_guess) par->setMax(2 * val_guess); if (val_guess < 0 && par->getMin() > val_guess) par->setMin(2 * val_guess); par->setVal(val_guess); + // std::cout << "Guessing " << val_guess << std::endl; auto result = xRooFit::minimize(nll, myFitConfig); if (!result) { status = 1; @@ -1024,16 +1379,16 @@ int xRooFit::minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parNam double nll_val = result->minNll(); status += result->status() * 10; tmu = 2 * (nll_val - nll_min); - sigma_guess = fabs(val_guess - val_best) / sqrt(tmu); + sigma_guess = std::abs(val_guess - val_best) / sqrt(tmu); if (tmu <= 0) { // found an alternative or improved minima std::cout << "Warning: Alternative best-fit of " << par->GetName() << " @ " << val_guess << " vs " - << val_best << std::endl; + << val_best << " (delta=" << tmu / 2. << ")" << std::endl; double new_guess = val_guess + (val_guess - val_best); val_best = val_guess; val_guess = new_guess; - sigma_guess = fabs((val_guess - val_best) / N_sigma); + sigma_guess = std::abs((val_guess - val_best) / N_sigma); val_pre = val_guess - 10 * precision * sigma_guess; status = (status / 10) * 10 + 1; continue; @@ -1049,14 +1404,14 @@ int xRooFit::minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parNam // cout << "NLL: " << nll->GetName() << " = " << nll->getVal() << endl; // cout << "delta(NLL): " << nll->getVal()-nll_min << endl; std::cout << "NLL min: " << nll_min << std::endl; - std::cout << "N_sigma*sigma(pre): " << fabs(val_pre - val_best) << std::endl; + std::cout << "N_sigma*sigma(pre): " << std::abs(val_pre - val_best) << std::endl; std::cout << "sigma(guess): " << sigma_guess << std::endl; std::cout << "par(guess): " << val_guess + corr << std::endl; std::cout << "true val: " << val_best << std::endl; std::cout << "tmu: " << tmu << std::endl; std::cout << "Precision: " << sigma_guess * precision << std::endl; std::cout << "Correction: " << (-corr < 0 ? " " : "") << -corr << std::endl; - std::cout << "N_sigma*sigma(guess): " << fabs(val_guess - val_best) << std::endl; + std::cout << "N_sigma*sigma(guess): " << std::abs(val_guess - val_best) << std::endl; std::cout << std::endl; } if (val_guess > par->getMax()) { @@ -1112,21 +1467,29 @@ int xRooFit::minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parNam double lo = par_hat->getErrorLo(); double hi = par_hat->getErrorHi(); if (std::isnan(hi)) { - hi = findValue(val_best + val_err, 1); + hi = findValue(val_best + val_err, 1) + val_best - + par_hat->getVal(); // put error wrt par_hat value, even if found better min + if (hi > val_err) + val_err = hi; // in case val_err was severe underestimate, don't want to waste time being too 'near' min } if (std::isnan(lo)) { - lo = -findValue(val_best - val_err, -1); + lo = -findValue(val_best - val_err, -1) + val_best - + par_hat->getVal(); // put error wrt par_hat value, even if found better min } dynamic_cast(ufit.floatParsFinal().find(parName))->setAsymError(lo, hi); - par_hat->setError(val_err); + par_hat->setError(orig_err); fitConfig.SetParabErrors(pErrs); fitConfig.SetMinosErrors(mErrs); par->setConstant(isConst); - const_cast(ufit)._statusHistory.push_back( - std::make_pair(std::string(TString::Format("xMINOS_%s", parName)), status)); - const_cast(ufit)._status += status; + std::vector> statusHistory; + for (unsigned int i = 0; i < ufit.numStatusHistory(); i++) { + statusHistory.emplace_back(ufit.statusLabelHistory(i), ufit.statusCodeHistory(i)); + } + statusHistory.emplace_back(TString::Format("xMinos:%s", parName), status); + const_cast(ufit).setStatusHistory(statusHistory); + const_cast(ufit).setStatus(ufit.status() + status); return status; } @@ -1248,8 +1611,8 @@ xRooFit::hypoTest(RooWorkspace &w, int nToysNull, int /*nToysAlt*/, const xRooFi Info("hypoTest", "No altVal found - to specify setStringAttribute(\"altVal\",\"\") on POI or set " "the physical range"); } - bool doCLs = - !std::isnan(altVal) && abs(mu->getMin("hypoPoints")) > altVal && abs(mu->getMax("hypoPoints")) > altVal; + bool doCLs = !std::isnan(altVal) && std::abs(mu->getMin("hypoPoints")) > altVal && + std::abs(mu->getMax("hypoPoints")) > altVal; const char *sCL = (doCLs) ? "CLs" : "null"; Info("hypoTest", "%s testing active", sCL); @@ -1320,7 +1683,7 @@ xRooFit::hypoTest(RooWorkspace &w, int nToysNull, int /*nToysAlt*/, const xRooFi testPoint(mu->getMax("hypoPoints")); testPoint((mu->getMax("hypoPoints") + mu->getMin("hypoPoints")) / 2.); - while (abs(obs_pcls->GetPointY(obs_pcls->GetN() - 1) - (1. - CL)) > 0.01) { + while (std::abs(obs_pcls->GetPointY(obs_pcls->GetN() - 1) - (1. - CL)) > 0.01) { obs_pcls->Sort(); double nextTest = getLimit(*obs_pcls); if (std::isnan(nextTest)) @@ -1328,7 +1691,7 @@ xRooFit::hypoTest(RooWorkspace &w, int nToysNull, int /*nToysAlt*/, const xRooFi testPoint(nextTest); } for (auto s : expSig) { - while (abs(exp_pcls[s].GetPointY(exp_pcls[s].GetN() - 1) - (1. - CL)) > 0.01) { + while (std::abs(exp_pcls[s].GetPointY(exp_pcls[s].GetN() - 1) - (1. - CL)) > 0.01) { exp_pcls[s].Sort(); double nextTest = getLimit(exp_pcls[s]); if (std::isnan(nextTest)) @@ -1477,4 +1840,35 @@ xRooFit::hypoTest(RooWorkspace &w, int nToysNull, int /*nToysAlt*/, const xRooFi return out; } -END_XROOFIT_NAMESPACE +double round_to_digits(double value, int digits) +{ + if (value == 0.0) + return 0.0; + double factor = pow(10.0, digits - ceil(log10(std::abs(value)))); + return std::round(value * factor) / factor; +}; +double round_to_decimal(double value, int decimal_places) +{ + const double multiplier = std::pow(10.0, decimal_places); + return std::round(value * multiplier) / multiplier; +} + +// rounds error to 1 or 2 sig fig and round value to match that precision +std::pair xRooFit::matchPrecision(const std::pair &in) +{ + auto out = in; + if (!std::isinf(out.second)) { + auto tmp = out.second; + out.second = round_to_digits(out.second, 2); + int expo = (out.second == 0) ? 0 : (int)std::floor(std::log10(std::abs(out.second))); + if (TString::Format("%e", out.second)(0) != '1') { + out.second = round_to_digits(tmp, 1); + out.first = (expo >= 0) ? round(out.first) : round_to_decimal(out.first, -expo); + } else if (out.second != 0) { + out.first = (expo >= 0) ? round(out.first) : round_to_decimal(out.first, -expo + 1); + } + } + return out; +} + +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/xRooHypoSpace.cxx b/roofit/xroofit/src/xRooHypoSpace.cxx index 45a6df92c7786..c820d74890d00 100644 --- a/roofit/xroofit/src/xRooHypoSpace.cxx +++ b/roofit/xroofit/src/xRooHypoSpace.cxx @@ -24,41 +24,67 @@ #include "TSystem.h" #include "TPRegexp.h" #include "TMemFile.h" +#include "TROOT.h" #include "RooDataSet.h" #include "TKey.h" #include "TFile.h" #include "TGraphErrors.h" +#include "TMultiGraph.h" #include "TH1F.h" #include "TStyle.h" #include "TLegend.h" #include "TLine.h" #include "RooStats/HypoTestInverterResult.h" +#include "TEnv.h" -BEGIN_XROOFIT_NAMESPACE - -// bool xRooNLLVar::xRooHypoSpace::AddWorkspace(const char* wsFilename, const char* extraPars){ -// -// auto ws = std::make_shared(wsFilename); -// -// ws->browse(); -// std::set> models; -// for(auto n : *ws) { -// if (n->fFolder == "!models") models.insert(n); -// } -// if (models.size()!=1) { -// throw std::runtime_error("More than one model in workspace, use AddModel instead"); -// } -// -// auto out = AddModel(*models.begin(),extraPars); -// if (out) { -// fWorkspaces.insert(ws); // keep ws open -// } -// -// } +BEGIN_XROOFIT_NAMESPACE; xRooNLLVar::xRooHypoSpace::xRooHypoSpace(const char *name, const char *title) : TNamed(name, title), fPars(std::make_shared()) { + if (name == nullptr || strlen(name) == 0) { + SetName(TUUID().AsString()); + } +} + +xRooNLLVar::xRooHypoSpace::xRooHypoSpace(const RooStats::HypoTestInverterResult *result) + : TNamed(), fPars(std::make_shared()) +{ + if (!result) + return; + + SetNameTitle(result->GetName(), result->GetTitle()); + + fPars->addClone(*std::unique_ptr(result->GetParameters())); + double spaceSize = 1; + for (auto p : *fPars) { + auto v = dynamic_cast(p); + if (!v) + continue; + spaceSize *= (v->getMax() - v->getMin()); + } + for (int i = 0; i < result->ArraySize(); i++) { + auto point = result->GetResult(i); + double xVal = result->GetXValue(i); + double ssize = spaceSize; + for (auto p : *fPars) { + auto v = dynamic_cast(p); + if (!v) + continue; + ssize /= (v->getMax() - v->getMin()); + double remain = std::fmod(xVal, ssize); + v->setVal((xVal - remain) / ssize); + xVal = remain; + } + emplace_back(xRooHypoPoint(std::make_shared(*point), fPars.get())); + } + // add any pars we might have missed + for (auto &p : *this) { + for (auto a : *p.coords) { + if (!fPars->find(a->GetName())) + fPars->addClone(*a); + } + } } std::shared_ptr xRooNLLVar::xRooHypoSpace::pdf(const char *parValues) const @@ -164,129 +190,267 @@ int xRooNLLVar::xRooHypoSpace::AddPoints(const char *parName, size_t nPoints, do return nPoints; } - double step = (high - low) / nPoints; + double step = (high - low) / (nPoints - 1); if (step <= 0) throw std::runtime_error("Invalid steps"); - for (double v = low + step * 0.5; v <= high; v += step) { - _par->setVal(v); + for (size_t i = 0; i < nPoints; i++) { + _par->setVal((i == nPoints - 1) ? high : (low + step * i)); AddPoint(); } return nPoints; } -double round_to_digits(double value, int digits) -{ - if (value == 0.0) - return 0.0; - double factor = pow(10.0, digits - ceil(log10(fabs(value)))); - return std::round(value * factor) / factor; -}; -double round_to_decimal(double value, int decimal_places) +xRooNLLVar::xRooHypoPoint &xRooNLLVar::xRooHypoSpace::AddPoint(double value) { - const double multiplier = std::pow(10.0, decimal_places); - return std::round(value * multiplier) / multiplier; + if (axes().empty()) { + // set the first poi as the axis variable to scan + if (poi().empty()) { + throw std::runtime_error("No POI to scan"); + } else { + poi().first()->setAttribute("axis"); + } + } + + if (empty()) { + // promote all axes to being poi and demote all non-axes to non-poi + poi().setAttribAll("poi", false); + axes().setAttribAll("poi"); + } + + return AddPoint(TString::Format("%s=%f", axes().first()->GetName(), value)); } -// rounds error to 1 or 2 sig fig and round value to match that precision -std::pair matchPrecision(const std::pair &in) +int xRooNLLVar::xRooHypoSpace::scan(const char *type, size_t nPoints, double low, double high, + const std::vector &nSigmas, double relUncert) { - auto out = in; - if (!std::isinf(out.second)) { - auto tmp = out.second; - out.second = round_to_digits(out.second, 2); - int expo = (out.second == 0) ? 0 : (int)std::floor(std::log10(std::fabs(out.second))); - if (TString::Format("%e", out.second)(0) != '1') { - out.second = round_to_digits(tmp, 1); - out.first = (expo >= 0) ? round(out.first) : round_to_decimal(out.first, -expo); - } else if (out.second != 0) { - out.first = (expo >= 0) ? round(out.first) : round_to_decimal(out.first, -expo + 1); + + TString sType(type); + sType.ToLower(); + if (sType.Contains("cls") && !sType.Contains("pcls")) + sType.ReplaceAll("cls", "pcls"); + if (!sType.Contains("pcls") && !sType.Contains("ts") && !sType.Contains("pnull") && !sType.Contains("plr")) { + throw std::runtime_error("scan type must be equal to one of: plr, cls, ts, pnull"); + } + + // will scan the first axes variable ... if there is none, specify the first poi as the axis var + if (axes().empty()) { + // set the first poi as the axis variable to scan + if (poi().empty()) { + throw std::runtime_error("No POI to scan"); + } else { + poi().first()->setAttribute("axis"); } } - return out; -} -std::map> xRooNLLVar::xRooHypoSpace::limits(const char *opt, double relUncert) -{ - TString sOpt(opt); - if (sOpt.Contains("cls")) { - for (auto p : poi()) { - if (!p->hasRange("physical")) { - Info("limits", "No physical range set for %s, setting to [0,inf]", p->GetName()); - dynamic_cast(p)->setRange("physical", 0, std::numeric_limits::infinity()); + // promote all axes to being poi and demote all non-axes to non-poi + poi().setAttribAll("poi", false); + axes().setAttribAll("poi"); + + auto p = dynamic_cast(axes().first()); + if (!p) { + throw std::runtime_error(TString::Format("%s not scanable", axes().first()->GetName())); + } + + if (sType.Contains("cls")) { + if (empty() && relUncert == std::numeric_limits::infinity()) { + // use default uncertainty precision of 10% + ::Info("xRooHypoSpace::scan", "Using default precision of 10%% for auto-scan"); + relUncert = 0.1; + } + for (auto a : axes()) { + if (!a->hasRange("physical")) { + ::Info("xRooHypoSpace::scan", "No physical range set for %s, setting to [0,inf]", p->GetName()); + dynamic_cast(a)->setRange("physical", 0, std::numeric_limits::infinity()); } - if (!p->getStringAttribute("altVal")) { - Info("limits", "No altVal set for %s, setting to 0", p->GetName()); - p->setStringAttribute("altVal", "0"); + if (!a->getStringAttribute("altVal") || !strlen(p->getStringAttribute("altVal"))) { + ::Info("xRooHypoSpace::scan", "No altVal set for %s, setting to 0", a->GetName()); + a->setStringAttribute("altVal", "0"); } // ensure range straddles altVal - double altVal = TString(p->getStringAttribute("altVal")).Atof(); - auto v = dynamic_cast(p); + double altVal = TString(a->getStringAttribute("altVal")).Atof(); + auto v = dynamic_cast(a); if (v->getMin() >= altVal) { - Info("limits", "range of POI does not straddle alt value, adjusting minimum to %g", altVal - 1e-5); + ::Info("xRooHypoSpace::scan", "range of POI does not straddle alt value, adjusting minimum to %g", + altVal - 1e-5); v->setMin(altVal - 1e-5); } if (v->getMax() <= altVal) { - Info("limits", "range of POI does not straddle alt value, adjusting minimum to %g", altVal + 1e-5); + ::Info("xRooHypoSpace::scan", "range of POI does not straddle alt value, adjusting maximum to %g", + altVal + 1e-5); v->setMax(altVal + 1e-5); } for (auto &[pdf, nll] : fNlls) { - if (auto _v = dynamic_cast(nll->pars()->find(*p))) { + if (auto _v = dynamic_cast(nll->pars()->find(*a))) { _v->setRange(v->getMin(), v->getMax()); } } } + } else if (sType.Contains("plr")) { + // force use of two-sided test statistic for any new points + fTestStatType = xRooFit::Asymptotics::TwoSided; + sType.ReplaceAll("plr", "ts"); } - std::map> out; - std::shared_ptr memFile; - if (!gDirectory->IsWritable()) { - memFile = std::make_shared("memory", "RECREATE"); - } - for (int nSigma : {0, 1, 2, -1, -2}) { - auto lim = FindLimit(TString::Format("%s exp%s%d", opt, nSigma > 0 ? "+" : "", nSigma), relUncert); - if (lim.second < 0) - lim.second = -lim.second; // make errors positive for this method - out[TString::Format("%d", nSigma).Data()] = matchPrecision(lim); + if (p && high <= low) { + // take from parameter + low = p->getMin("scan"); + high = p->getMax("scan"); + ::Info("xRooHypoSpace::scan", "Using %s range: %g - %g", p->GetName(), low, high); } - // don't do the observed limit if all the NLL datas are generated - bool doObs = true; -#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00) - bool allGen = true; - for (auto &[pdf, nll] : fNlls) { - auto _d = dynamic_cast(nll->data()); - if (!_d || !_d->weightVar() || !_d->weightVar()->getStringAttribute("fitResult")) { - allGen = false; + bool doObs = false; + for (auto nSigma : nSigmas) { + if (std::isnan(nSigma)) { + doObs = true; break; } } - if (allGen) - doObs = false; + + if (fNlls.empty()) { + // this happens when loaded hypoSpace from a hypoSpaceInverterResult + // set relUncert to infinity so that we don't test any new points + relUncert = std::numeric_limits::infinity(); // no NLL available so just get whatever limit we can + + // if any of the defined points are 'expected' data don't do obs + // for(auto& hp : *this) { + // if(hp.isExpected) { + // doObs = false; break; + // } + // } + } else { +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00) +// bool allGen = true; +// for (auto &[pdf, nll]: fNlls) { +// auto _d = dynamic_cast(nll->data()); +// if (!_d || !_d->weightVar() || !_d->weightVar()->getStringAttribute("fitResult") || +// !_d->weightVar()->getAttribute("expected")) { +// allGen = false; +// break; +// } +// } +// if (allGen) +// doObs = false; #endif - if (doObs) { - auto lim = FindLimit(TString::Format("%s obs", opt), relUncert); + } + + // create a fitDatabase if required + TDirectory *origDir = gDirectory; + if (!gDirectory || !gDirectory->IsWritable()) { + // locate a TMemFile in the open list of files and move to that + // or create one if cannot find + for (auto file : *gROOT->GetListOfFiles()) { + if (auto f = dynamic_cast(file)) { + f->cd(); + break; + } + } + if (!gDirectory || !gDirectory->IsWritable()) { + new TMemFile("fitDatabase", "RECREATE"); + } + } + + int out = 0; + + if (nPoints == 0) { + // automatic scan + if (sType.Contains("cls")) { + for (double nSigma : nSigmas) { + xValueWithError res(std::make_pair(0., 0.)); + if (std::isnan(nSigma)) { + if (!doObs) + continue; + res = findlimit(TString::Format("%s obs", sType.Data()), relUncert); + } else { + res = + findlimit(TString::Format("%s exp%s%d", sType.Data(), nSigma > 0 ? "+" : "", int(nSigma)), relUncert); + } + if (std::isnan(res.first) || std::isnan(res.second)) + out = 1; + else if (std::isinf(res.second)) + out = 2; + } + } else { + throw std::runtime_error(TString::Format("Automatic scanning not yet supported for %s", type)); + } + } else { + // add the required points and then compute the required value + if (nPoints == 1) { + AddPoint(TString::Format("%s=%g", poi().first()->GetName(), (high + low) / 2.)); + graphs(sType); // triggers computation + } else { + double step = (high - low) / (nPoints - 1); + for (size_t i = 0; i < nPoints; i++) { + AddPoint(TString::Format("%s=%g", poi().first()->GetName(), low + step * i)); + graphs(sType); // triggers computation + } + } + } + + if (origDir) + origDir->cd(); + + return out; +} + +std::map> +xRooNLLVar::xRooHypoSpace::limits(const char *opt, const std::vector &nSigmas, double relUncert) +{ + + if (fNlls.empty()) { + // this happens when loaded hypoSpace from a hypoSpaceInverterResult + // set relUncert to infinity so that we don't test any new points + relUncert = std::numeric_limits::infinity(); // no NLL available so just get whatever limit we can + } + + scan(opt, nSigmas, relUncert); + + std::map> out; + for (auto nSigma : nSigmas) { + auto lim = limit(opt, nSigma); if (lim.second < 0) - lim.second = -lim.second; - out["obs"] = matchPrecision(lim); + lim.second = -lim.second; // make errors positive for this method + out[std::isnan(nSigma) ? "obs" : TString::Format("%d", int(nSigma)).Data()] = xRooFit::matchPrecision(lim); } return out; } xRooNLLVar::xRooHypoPoint &xRooNLLVar::xRooHypoSpace::AddPoint(const char *coords) { - // move to given coords, if any - fPars->assignValueOnly(toArgs(coords)); + // move to given coords, if any ... will mark them const too + std::unique_ptr> _snap(fPars->snapshot(), + [&](RooAbsCollection *c) { + *fPars = *c; + delete c; + }); + TStringToken pattern(coords, ";"); + while (pattern.NextToken()) { + TString s = pattern; + // split by "=" sign + auto _idx = s.Index('='); + if (_idx == -1) + continue; + TString _name = s(0, _idx); + TString _val = s(_idx + 1, s.Length()); + auto _v = dynamic_cast(fPars->find(_name)); + if (!_v) + continue; + + if (_val.IsFloat()) { + _v->setConstant(); + _v->setVal(_val.Atof()); + } + } auto _pdf = pdf(); if (!_pdf) throw std::runtime_error("no model at coordinates"); - if (std::unique_ptr(fPars->selectByAttrib("poi", true))->size() == 0) { - throw std::runtime_error( - "No pars designated as POI - set with pars()->find()->setAttribute(\"poi\",true)"); - } + // if (std::unique_ptr(fPars->selectByAttrib("poi", true))->size() == 0) { + // throw std::runtime_error( + // "No pars designated as POI - set with pars()->find()->setAttribute(\"poi\",true)"); + // } if (fNlls.find(_pdf) == fNlls.end()) { fNlls[_pdf] = std::make_shared(_pdf->nll("" /*TODO:allow change dataset name and nll opts*/, {})); @@ -295,14 +459,22 @@ xRooNLLVar::xRooHypoPoint &xRooNLLVar::xRooHypoSpace::AddPoint(const char *coord xRooHypoPoint out; out.nllVar = fNlls[_pdf]; - out.data = fNlls[_pdf]->getData(); + out.fData = fNlls[_pdf]->getData(); + out.isExpected = dynamic_cast(out.fData.first.get()) && + dynamic_cast(out.fData.first.get())->weightVar()->getAttribute("expected"); + // TODO: need to access the genfit of the data and add that to the point, somehow ... out.coords.reset(fPars->snapshot()); // should already have altVal prop on poi, and poi labelled // ensure all poi are marked const ... required by xRooHypoPoint behaviour out.poi().setAttribAll("Constant"); // and now remove anything that's marked floating + + // do to bug in remove have to ensure not using the hash map otherwise will be doing an invalid read after the + // deletion of the owned pars + const_cast(out.coords.get())->useHashMapForFind(false); const_cast(out.coords.get()) ->remove(*std::unique_ptr(out.coords->selectByAttrib("Constant", false)), true, true); + double value = out.fNullVal(); double alt_value = out.fAltVal(); @@ -319,8 +491,62 @@ xRooNLLVar::xRooHypoPoint &xRooNLLVar::xRooHypoSpace::AddPoint(const char *coord out.fPllType = _type; - // TODO: Check for equivalent point before adding + // look for a matching point + for (auto &p : *this) { + if (p.nllVar != out.nllVar) + continue; + if (p.fData != out.fData) + continue; + if (!p.alt_poi().equals(out.alt_poi())) + continue; + bool match = true; + for (auto c : p.alt_poi()) { + if (auto v = dynamic_cast(c); + v && std::abs(v->getVal() - out.alt_poi().getRealValue(v->GetName())) > 1e-12) { + match = false; + break; + } + } + if (!match) + continue; + if (!p.coords->equals(*out.coords)) + continue; + for (auto c : *p.coords) { + if (c->getAttribute("poi")) { + continue; // check poi below + } + if (auto v = dynamic_cast(c); + v && std::abs(v->getVal() - out.coords->getRealValue(v->GetName())) > 1e-12) { + match = false; + break; + } + } + if (!match) + continue; + // if reached here we can copy over the asimov dataset to save re-generating it + // first copy over cfit_alt (if its there) because that is also the same since coords and alt_poi values same + if (auto cfit = p.cfit_alt(true)) { + out.fAlt_cfit = cfit; + } + if (p.asimov(true) && p.asimov(true)->fData.first && (!out.asimov(true) || !out.asimov(true)->fData.first)) { + out.asimov()->fData = p.asimov(true)->fData; + } + if (!p.poi().equals(out.poi())) + continue; + for (auto c : p.poi()) { + if (auto v = dynamic_cast(c); + v && std::abs(v->getVal() - out.poi().getRealValue(v->GetName())) > 1e-12) { + match = false; + break; + } + } + if (match) { + // found a duplicate point, return that! + return p; + } + } + ::Info("xRooHypoSpace::AddPoint", "Added new point @ %s", coords); return emplace_back(out); } @@ -361,50 +587,64 @@ RooArgList xRooNLLVar::xRooHypoSpace::axes() const RooArgList out; out.setName("axes"); + out.add(*std::unique_ptr( + fPars->selectByAttrib("axis", true))); // start with any pars explicitly designated as axes + bool clash; do { clash = false; - // add next best coordinate - std::map> values; - for (auto &par : *pars()) { - if (out.find(*par)) - continue; - for (auto p : *this) { - values[par->GetName()].insert( - p.coords->getRealValue(par->GetName(), std::numeric_limits::quiet_NaN())); - } - } - - std::string bestVar; - size_t maxDiff = 0; - bool isPOI = false; - for (auto &[k, v] : values) { - if (v.size() > maxDiff || (v.size() == maxDiff && !isPOI && pars()->find(k.c_str())->getAttribute("poi"))) { - bestVar = k; - isPOI = pars()->find(k.c_str())->getAttribute("poi"); - maxDiff = std::max(maxDiff, v.size()); - } - } - - if (bestVar.empty()) { - break; - } - - out.add(*pars()->find(bestVar.c_str())); - std::set> coords; for (auto &p : *this) { std::vector p_coords; for (auto o : out) { - p_coords.push_back(p.coords->getRealValue(o->GetName(), std::numeric_limits::quiet_NaN())); + auto _v = dynamic_cast(p.coords->find(o->GetName())); + p_coords.push_back( + (_v && _v->isConstant()) + ? _v->getVal() + : std::numeric_limits::infinity()); // non-const coords are treating as non-existent + // p_coords.push_back(p.coords->getRealValue(o->GetName(), std::numeric_limits::quiet_NaN())); } if (coords.find(p_coords) != coords.end()) { clash = true; break; } + coords.insert(p_coords); } + if (clash) { + // add next best coordinate + std::map> values; + for (auto &par : *pars()) { + if (out.find(*par)) + continue; + for (auto p : *this) { + auto _v = dynamic_cast(p.coords->find(par->GetName())); + values[par->GetName()].insert( + (_v && _v->isConstant()) + ? _v->getVal() + : std::numeric_limits::infinity()); // non-const coords are treating as non-existent + // values[par->GetName()].insert( + // p.coords->getRealValue(par->GetName(), std::numeric_limits::quiet_NaN())); + } + } + + std::string bestVar; + size_t maxDiff = 0; + bool isPOI = false; + for (auto &[k, v] : values) { + if (v.size() > maxDiff || (v.size() == maxDiff && !isPOI && pars()->find(k.c_str())->getAttribute("poi"))) { + bestVar = k; + isPOI = pars()->find(k.c_str())->getAttribute("poi"); + maxDiff = std::max(maxDiff, v.size()); + } + } + if (bestVar.empty()) { + break; + } + + out.add(*pars()->find(bestVar.c_str())); + } } while (clash); // ensure poi are at the end @@ -572,10 +812,10 @@ void xRooNLLVar::xRooHypoSpace::LoadFits(const char *apath) } }; processDir(dir); - Info("xRooHypoSpace", "%s - Loaded %d fits", apath, nFits); + ::Info("xRooHypoSpace::xRooHypoSpace", "%s - Loaded %d fits", apath, nFits); if (allpois.size() == 1) { - Info("xRooHypoSpace", "Detected POI: %s", allpois.begin()->c_str()); + ::Info("xRooHypoSpace::xRooHypoSpace", "Detected POI: %s", allpois.begin()->c_str()); auto nll = std::make_shared(nullptr, nullptr); auto dummyNll = std::make_shared(apath, "Dummy NLL", std::numeric_limits::quiet_NaN()); @@ -687,13 +927,16 @@ void xRooNLLVar::xRooHypoSpace::Print(Option_t * /*opt*/) const std::cout << "Number of bad fits: " << badFits << std::endl; } -std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char *opt) +std::shared_ptr xRooNLLVar::xRooHypoSpace::graph( + const char *opt /*, const std::function& progress*/) const { TString sOpt(opt); sOpt.ToLower(); bool doCLs = sOpt.Contains("cls"); + bool readOnly = sOpt.Contains("readonly"); + bool visualize = sOpt.Contains("visualize") && !readOnly; double nSigma = (sOpt.Contains("exp")) @@ -710,6 +953,7 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * auto out = std::make_shared(); out->SetName(GetName()); + out->SetEditable(false); const char *sCL = (doCLs) ? "CLs" : "null"; TString title = @@ -725,11 +969,14 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * if (std::isnan(nSigma)) { out->SetNameTitle(TString::Format("obs_p%s", sCL), title); out->SetMarkerStyle(20); + out->SetMarkerSize(0.5); if (sOpt.Contains("ts")) - out->SetNameTitle("obs_ts", TString::Format("Observed;%s;Test Statistic", _axes.at(0)->GetTitle())); + out->SetNameTitle("obs_ts", TString::Format("Observed;%s;%s", _axes.at(0)->GetTitle(), + (empty() ? "" : front().tsTitle(true).Data()))); } else { out->SetNameTitle(TString::Format("exp%d_p%s", int(nSigma), sCL), title); out->SetMarkerStyle(0); + out->SetMarkerSize(0); out->SetLineStyle(2 + int(nSigma)); if (expBand && nSigma) { out->SetFillColor((nSigma == 2) ? kYellow : kGreen); @@ -749,7 +996,7 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * } if (sOpt.Contains("ts")) out->SetNameTitle(TString::Format("exp_ts%d", int(nSigma)), - TString::Format("Expected;%s;Test Statistic", _axes.at(0)->GetTitle())); + TString::Format("Expected;%s;%s", _axes.at(0)->GetTitle(), front().tsTitle(true).Data())); } auto badPoints = [&]() { @@ -759,21 +1006,45 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * badPoints2->SetBit(kCanDelete); badPoints2->SetName("badPoints"); badPoints2->SetMarkerStyle(5); - badPoints2->SetMarkerColor(kRed); - badPoints2->SetMarkerSize(out->GetMarkerSize()); + badPoints2->SetMarkerColor(std::isnan(nSigma) ? kRed : kBlue); + badPoints2->SetMarkerSize(1); out->GetListOfFunctions()->Add(badPoints2, "P"); } return badPoints2; }; int nPointsDown = 0; bool above = true; + TStopwatch s; + s.Start(); + size_t nDone = 0; for (auto &p : *this) { + if (s.RealTime() > 5) { + if (visualize) { + // draw readonly version of the graph + auto gra = graph(sOpt + " readOnly"); + if (gra && gra->GetN()) { + if (!gPad && gROOT->GetSelectedPad()) + gROOT->GetSelectedPad()->cd(); + if (gPad) + gPad->Clear(); + gra->DrawClone(expBand ? "AF" : "ALP")->SetBit(kCanDelete); + gSystem->ProcessEvents(); + } + } else { + ::Info("xRooHypoSpace::graph", "Completed %d/%d points for %s", int(nDone), int(size()), sOpt.Data()); + } + s.Start(); + } else { + s.Continue(); + } double _x = p.coords->getRealValue(_axes.at(0)->GetName(), std::numeric_limits::quiet_NaN()); - auto pval = p.getVal(sOpt); + auto pval = const_cast(p).getVal(sOpt); auto idx = out->GetN() - nPointsDown; if (std::isnan(pval.first)) { - badPoints()->SetPoint(badPoints()->GetN(), _x, 0); + if (p.status() != 0) { // if status is 0 then bad pval is really just absence of fits, not bad fits + badPoints()->SetPoint(badPoints()->GetN(), _x, 0); + } } else { out->InsertPointBefore(idx, _x, pval.first); out->SetPointError(idx, 0, pval.second); @@ -782,9 +1053,11 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * if (expBand && nSigma) { TString sOpt2 = sOpt; sOpt2.ReplaceAll("exp", "exp-"); - pval = p.getVal(sOpt2); + pval = const_cast(p).getVal(sOpt2); if (std::isnan(pval.first)) { - badPoints()->SetPoint(badPoints()->GetN(), _x, 0); + if (p.status() != 0) { // if status is 0 then bad pval is really just absence of fits, not bad fits + badPoints()->SetPoint(badPoints()->GetN(), _x, 0); + } } else { out->InsertPointBefore(idx + 1, _x, pval.first); out->SetPointError(idx + 1, 0, pval.second); @@ -793,6 +1066,7 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * above = false; // the -sigma points are actually above +sigma } } + nDone++; } if (out->GetN() == 0) @@ -800,6 +1074,12 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * if (!expBand) { out->Sort(); + if (out->GetListOfFunctions()->FindObject("badPoints")) { + // try to interpolate the points + for (int i = 0; i < badPoints()->GetN(); i++) { + badPoints()->SetPointY(i, out->Eval(badPoints()->GetPointX(i))); + } + } } else { out->Sort(&TGraph::CompareX, true, 0, out->GetN() - nPointsDown - 1); // sort first half out->Sort(&TGraph::CompareX, false, out->GetN() - nPointsDown, out->GetN() - 1); // reverse sort second half @@ -819,12 +1099,151 @@ std::shared_ptr xRooNLLVar::xRooHypoSpace::BuildGraph(const char * } } + if (visualize) { + // draw result + if (!gPad && gROOT->GetSelectedPad()) + gROOT->GetSelectedPad()->cd(); + if (gPad) + gPad->Clear(); + out->DrawClone(expBand ? "AF" : "ALP")->SetBit(kCanDelete); + gSystem->ProcessEvents(); + } + + return out; +} + +std::shared_ptr xRooNLLVar::xRooHypoSpace::graphs(const char *opt) +{ + TString sOpt(opt); + sOpt.ToLower(); + std::shared_ptr out; + if (sOpt.Contains("pcls") || sOpt.Contains("pnull") || sOpt.Contains("ts")) { + + bool visualize = sOpt.Contains("visualize"); + sOpt.ReplaceAll("visualize", ""); + + auto exp2 = graph(sOpt + " exp2"); + auto exp1 = graph(sOpt + " exp1"); + auto exp = graph(sOpt + " exp"); + bool doObs = true; + // for(auto& hp : *this) { if(hp.isExpected) {doObs=false; break;} } + auto obs = (doObs) ? graph(sOpt) : nullptr; + + out = std::make_shared(GetName(), GetTitle()); + if (exp2 && exp2->GetN() > 1) + out->Add(static_cast(exp2->Clone()), "FP"); + if (exp1 && exp1->GetN() > 1) + out->Add(static_cast(exp1->Clone()), "FP"); + if (exp && exp->GetN() > 1) + out->Add(static_cast(exp->Clone()), "LP"); + if (obs && obs->GetN() > 1) + out->Add(static_cast(obs->Clone()), "LP"); + + if (!out->GetListOfGraphs()) { + return nullptr; + } + + TGraph *testedPoints = nullptr; + if (sOpt.Contains("pcls")) { + TGraph *line = new TGraph; + line->SetName("alpha"); + line->SetLineStyle(2); + line->SetEditable(false); + line->SetPoint(line->GetN(), out->GetHistogram()->GetXaxis()->GetXmin() - 10, 0.05); + testedPoints = new TGraph; + testedPoints->SetName("hypoPoints"); + testedPoints->SetEditable(false); + testedPoints->SetMarkerStyle(24); + testedPoints->SetMarkerSize(0.4); // use line to indicate tested points + if (exp) { + for (int i = 0; i < exp->GetN(); i++) { + testedPoints->SetPoint(testedPoints->GetN(), exp->GetPointX(i), 0.05); + } + } + line->SetPoint(line->GetN(), out->GetHistogram()->GetXaxis()->GetXmax() + 10, 0.05); + line->SetBit(kCanDelete); + out->GetListOfFunctions()->Add(line, "L"); + } + if (exp) { + out->GetHistogram()->GetXaxis()->SetTitle(exp->GetHistogram()->GetXaxis()->GetTitle()); + out->GetHistogram()->GetYaxis()->SetTitle(exp->GetHistogram()->GetYaxis()->GetTitle()); + } + auto leg = new TLegend(1. - gStyle->GetPadRightMargin() - 0.3, 1. - gStyle->GetPadTopMargin() - 0.35, + 1. - gStyle->GetPadRightMargin() - 0.05, 1. - gStyle->GetPadTopMargin() - 0.05); + leg->SetName("legend"); + leg->SetBit(kCanDelete); + + out->GetListOfFunctions()->Add(leg); + // out->GetListOfFunctions()->Add(out->GetHistogram()->Clone(".axis"),"sameaxis"); // redraw axis + + for (auto g : *out->GetListOfGraphs()) { + if (auto o = dynamic_cast(g)->GetListOfFunctions()->FindObject("down")) { + leg->AddEntry(o, "", "F"); + } else { + leg->AddEntry(g, "", "LPE"); + } + } + + if (sOpt.Contains("pcls")) { + // add current limit estimates to legend + if (exp2 && exp2->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*graph(sOpt + "exp-2"))); + leg->AddEntry((TObject *)nullptr, TString::Format("-2#sigma: %g +/- %g", l.first, l.second), ""); + } + if (exp1 && exp1->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*graph(sOpt + "exp-1"))); + leg->AddEntry((TObject *)nullptr, TString::Format("-1#sigma: %g +/- %g", l.first, l.second), ""); + } + if (exp && exp->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*exp)); + leg->AddEntry((TObject *)nullptr, TString::Format("0#sigma: %g +/- %g", l.first, l.second), ""); + } + if (exp1 && exp1->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*graph(sOpt + "exp+1"))); + leg->AddEntry((TObject *)nullptr, TString::Format("+1#sigma: %g +/- %g", l.first, l.second), ""); + } + if (exp2 && exp2->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*graph(sOpt + "exp+2"))); + leg->AddEntry((TObject *)nullptr, TString::Format("+2#sigma: %g +/- %g", l.first, l.second), ""); + } + if (obs && obs->GetN() > 1) { + auto l = xRooFit::matchPrecision(GetLimit(*obs)); + leg->AddEntry((TObject *)nullptr, TString::Format("Observed: %g +/- %g", l.first, l.second), ""); + } + } + if (testedPoints) + out->Add(testedPoints, "P"); + + if (visualize) { + if (!gPad && gROOT->GetSelectedPad()) + gROOT->GetSelectedPad()->cd(); + if (gPad) + gPad->Clear(); + auto gra2 = static_cast(out->DrawClone("A")); + gra2->SetBit(kCanDelete); + if (sOpt.Contains("pcls") || sOpt.Contains("pnull")) { + gra2->GetHistogram()->SetMinimum(1e-6); + } + if (gPad) { + gPad->RedrawAxis(); + gPad->GetCanvas()->Paint(); + gPad->GetCanvas()->Update(); + gSystem->ProcessEvents(); + } + gSystem->ProcessEvents(); + } + } + return out; } std::pair xRooNLLVar::xRooHypoSpace::GetLimit(const TGraph &pValues, double target) { + if (std::isnan(target)) { + target = 1. - gEnv->GetValue("xRooHypoSpace.CL", 95.) / 100.; + } + auto gr = std::make_shared(pValues); // remove any nan points and duplicates int i = 0; @@ -870,11 +1289,15 @@ std::pair xRooNLLVar::xRooHypoSpace::GetLimit(const TGraph &pVal if ((above && gr->GetPointY(gr->GetN() - 1) <= gr->GetPointY(0)) || (!above && gr->GetPointY(gr->GetN() - 1) >= gr->GetPointY(0))) { // extrapolating above based on last two points - double x1 = gr->GetPointX(gr->GetN() - 2); - double y1 = gr->GetPointY(gr->GetN() - 2); + // in fact, if 2nd last point is a p=1 (log(p)=0) then go back + int offset = 2; + while (offset < gr->GetN() && gr->GetPointY(gr->GetN() - offset) == 0) + offset++; + double x1 = gr->GetPointX(gr->GetN() - offset); + double y1 = gr->GetPointY(gr->GetN() - offset); double m = (gr->GetPointY(gr->GetN() - 1) - y1) / (gr->GetPointX(gr->GetN() - 1) - x1); if (m == 0.) - return std::pair(2. * gr->GetPointX(gr->GetN() - 1) - x1, std::numeric_limits::infinity()); + return std::pair(std::numeric_limits::infinity(), std::numeric_limits::infinity()); return std::pair((alpha - y1) / m + x1, std::numeric_limits::infinity()); } else { // extrapolating below based on first two points @@ -882,17 +1305,46 @@ std::pair xRooNLLVar::xRooHypoSpace::GetLimit(const TGraph &pVal double y1 = gr->GetPointY(0); double m = (gr->GetPointY(1) - y1) / (gr->GetPointX(1) - x1); if (m == 0.) - return std::pair(2. * x1 - gr->GetPointX(1), std::numeric_limits::infinity()); - return std::pair((alpha - y1) / m + x1, std::numeric_limits::infinity()); + return std::pair(-std::numeric_limits::infinity(), -std::numeric_limits::infinity()); + return std::pair((alpha - y1) / m + x1, -std::numeric_limits::infinity()); } } -std::pair xRooNLLVar::xRooHypoSpace::FindLimit(const char *opt, double relUncert) +xRooNLLVar::xValueWithError xRooNLLVar::xRooHypoSpace::limit(const char *type, double nSigma) const { - std::shared_ptr gr = BuildGraph(TString(opt) + " readonly"); + TString sOpt = TString::Format("p%s", type); + if (std::isnan(nSigma)) { + sOpt += "obs"; + } else { + sOpt += TString::Format("exp%s%d", nSigma > 0 ? "+" : "", int(nSigma)); + } + return GetLimit(*graph(sOpt + " readonly")); +} + +xRooNLLVar::xValueWithError +xRooNLLVar::xRooHypoSpace::findlimit(const char *opt, double relUncert, unsigned int maxTries) +{ + TString sOpt(opt); + bool visualize = sOpt.Contains("visualize"); + sOpt.ReplaceAll("visualize", ""); + std::shared_ptr gr = graph(sOpt + " readonly"); + if (visualize) { + auto gra = graphs(sOpt.Contains("toys") ? "pcls readonly toys" : "pcls readonly"); + if (gra) { + if (!gPad) + gra->Draw(); // in 6.28 DrawClone wont make the gPad defined :( ... so Draw then clear and Draw Clone + gPad->Clear(); + gra->DrawClone("A")->SetBit(kCanDelete); + gPad->RedrawAxis(); + gra->GetHistogram()->SetMinimum(1e-9); + gra->GetHistogram()->GetYaxis()->SetRangeUser(1e-9, 1); + gPad->Modified(); + gSystem->ProcessEvents(); + } + } // resync parameter boundaries from nlls (may have been modified by fits) - for (auto p : poi()) { + for (auto p : axes()) { for (auto &[pdf, nll] : fNlls) { if (auto _v = dynamic_cast(nll->pars()->find(*p))) { dynamic_cast(p)->setRange(_v->getMin(), _v->getMax()); @@ -901,25 +1353,53 @@ std::pair xRooNLLVar::xRooHypoSpace::FindLimit(const char *opt, } if (!gr || gr->GetN() < 2) { - auto v = (poi().empty()) ? nullptr : dynamic_cast(poi().first()); + auto v = (axes().empty()) ? nullptr : dynamic_cast(*axes().rbegin()); if (!v) - return std::pair(std::numeric_limits::quiet_NaN(), 0); + return std::pair(std::numeric_limits::quiet_NaN(), 0.); double muMax = std::min(v->getMax(), v->getMax("physical")); double muMin = std::max(v->getMin("physical"), v->getMin()); if (!gr || gr->GetN() < 1) { - if (std::isnan(AddPoint(TString::Format("%s=%g", v->GetName(), muMin)).getVal(opt).first)) { + if (maxTries == 0 || std::isnan(AddPoint(TString::Format("%s=%g", v->GetName(), muMin)).getVal(sOpt).first)) { // first point failed ... give up - return std::pair(std::numeric_limits::quiet_NaN(), 0); + return std::pair(std::numeric_limits::quiet_NaN(), 0.); } - return FindLimit(opt, relUncert); // do this to resync parameter limits + gr.reset(); + return findlimit(opt, relUncert, maxTries - 1); // do this to resync parameter limits + } + + // can approximate expected limit using + // mu_hat + sigma_mu*ROOT::Math::gaussian_quantile(1.-alpha/2.,1) for cls + // or mu_hat + sigma_mu*ROOT::Math::gaussian_quantile((1.-alpha),1) for cls+b + // get a very first estimate of sigma_mu from ufit to expected data, take error on mu as sigma_mu + double nextPoint = muMin + (muMax - muMin) / 50; + + // if done an expected limit, assume data is like expected and choose expected limit point as first test point + if (sOpt.Contains("obs")) { + TString sOpt2 = sOpt; + sOpt2.ReplaceAll("obs", "exp"); + auto expLim = findlimit(sOpt2, std::numeric_limits::infinity(), 0); + if (!std::isnan(expLim.first) && expLim.first < nextPoint) + nextPoint = expLim.first; + } + + auto point = + (sOpt.Contains("exp")) ? back().asimov() : std::shared_ptr(&back(), [](xRooHypoPoint *) {}); + point = nullptr; + if (point && point->ufit()) { + double rough_sigma_mu = point->mu_hat().getError(); + double another_estimate = point->mu_hat().getVal() + rough_sigma_mu * ROOT::Math::gaussian_quantile(0.95, 1); + // if (another_estimate < nextPoint) { + nextPoint = another_estimate; + ::Info("xRooHypoSpace::findlimit", "Guessing %g based on rough sigma_mu = %g", nextPoint, rough_sigma_mu); + //} } - if (std::isnan( - AddPoint(TString::Format("%s=%g", v->GetName(), muMin + (muMax - muMin) / 50)).getVal(opt).first)) { + if (maxTries == 0 || std::isnan(AddPoint(TString::Format("%s=%g", v->GetName(), nextPoint)).getVal(sOpt).first)) { // second point failed ... give up - return std::pair(std::numeric_limits::quiet_NaN(), 0); + return std::pair(std::numeric_limits::quiet_NaN(), 0.); } - return FindLimit(opt, relUncert); + gr.reset(); + return findlimit(opt, relUncert, maxTries - 1); } auto lim = GetLimit(*gr); @@ -928,18 +1408,39 @@ std::pair xRooNLLVar::xRooHypoSpace::FindLimit(const char *opt, return lim; } - if (std::abs(lim.second) <= relUncert * std::abs(lim.first)) + auto v = dynamic_cast(*axes().rbegin()); + double maxMu = std::min(v->getMax("physical"), v->getMax()); + double minMu = std::max(v->getMin("physical"), v->getMin()); + + // static double MIN_LIMIT_UNCERT = 1e-4; // stop iterating once uncert gets this small + if (lim.first > -std::numeric_limits::infinity() && lim.first < std::numeric_limits::infinity() && + (std::abs(lim.second) <= relUncert * std::abs(lim.first) /* || std::abs(lim.second)(poi().first()); - double maxMu = std::min(v->getMax("physical"), v->getMax()); - double minMu = std::max(v->getMin("physical"), v->getMin()); + if (lim.second == std::numeric_limits::infinity()) { // limit was found by extrapolating to right nextPoint = lim.first; - if (nextPoint > v->getMax("physical")) + if (nextPoint == std::numeric_limits::infinity() || nextPoint > v->getMax("physical")) { nextPoint = gr->GetPointX(gr->GetN() - 1) + (maxMu - minMu) / 50; + } + + // prefer extrapolation with sigma_mu, if available, if it takes us further + // as shape of p-value curve is usually + auto point = + (sOpt.Contains("exp")) ? back().asimov() : std::shared_ptr(&back(), [](xRooHypoPoint *) {}); + point = nullptr; + if (point && point->ufit()) { + double rough_sigma_mu = point->mu_hat().getError(); + double another_estimate = point->mu_hat().getVal() + rough_sigma_mu * ROOT::Math::gaussian_quantile(0.95, 1); + // if (another_estimate < nextPoint) { + nextPoint = std::max(nextPoint, another_estimate); + ::Info("xRooHypoSpace::findlimit", "Guessing %g based on rough sigma_mu = %g", nextPoint, rough_sigma_mu); + //} + } + nextPoint += nextPoint * relUncert * 0.99; // ensure we step over location + if (nextPoint > v->getMax("physical")) return lim; } else if (lim.second == -std::numeric_limits::infinity()) { @@ -956,12 +1457,13 @@ std::pair xRooNLLVar::xRooHypoSpace::FindLimit(const char *opt, // got here need a new point .... evaluate the estimated lim location +/- the relUncert (signed error takes care of // direction) - Info("FindLimit", "%s -- Testing new point @ %s=%g", opt, v->GetName(), nextPoint); - if (std::isnan(AddPoint(TString::Format("%s=%g", v->GetName(), nextPoint)).getVal(opt).first)) { + ::Info("xRooHypoSpace::findlimit", "%s -- Testing new point @ %s=%g (delta=%g)", sOpt.Data(), v->GetName(), + nextPoint, lim.second); + if (maxTries == 0 || std::isnan(AddPoint(TString::Format("%s=%g", v->GetName(), nextPoint)).getVal(sOpt).first)) { return lim; } - - return FindLimit(opt, relUncert); + gr.reset(); + return findlimit(opt, relUncert, maxTries - 1); } void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) @@ -970,6 +1472,20 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) TString sOpt(opt); sOpt.ToLower(); + if ((sOpt == "" || sOpt == "same") && !empty()) { + if (front().fPllType == xRooFit::Asymptotics::OneSidedPositive) { + sOpt += "pcls"; // default to showing cls p-value scan if drawing a limit + for (auto &hp : *this) { + if (hp.nullToys.size() || hp.altToys.size()) { + sOpt += " toys"; + break; // default to toys if done toys + } + } + } else if (front().fPllType == xRooFit::Asymptotics::TwoSided) { + sOpt += "ts"; + } + } + // split up by ; and call Draw for each (with 'same' appended) auto _axes = axes(); if (_axes.empty()) @@ -1063,7 +1579,7 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) out->SetMarkerStyle(4); out->Draw("AP"); - auto leg = new TLegend(1. - gPad->GetRightMargin() - 0.3, 1. - gPad->GetTopMargin() - 0.3, + auto leg = new TLegend(1. - gPad->GetRightMargin() - 0.3, 1. - gPad->GetTopMargin() - 0.35, 1. - gPad->GetRightMargin() - 0.05, 1. - gPad->GetTopMargin() - 0.05); leg->SetName("legend"); leg->AddEntry(out, "Uncomputed", "P"); @@ -1100,53 +1616,37 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) gPad->SetLogy(false); } + gSystem->ProcessEvents(); + return; } - if (sOpt.Contains("pcls") || sOpt.Contains("pnull")) { - // bool doCLs = (sOpt.Contains("cls")); - // const char* sCL = (doCLs) ? "CLs" : "null"; - - auto exp2 = BuildGraph(sOpt + " exp2"); - auto exp1 = BuildGraph(sOpt + " exp1"); - auto exp = BuildGraph(sOpt + " exp"); - auto obs = BuildGraph(sOpt); - + if (sOpt.Contains("pcls") || sOpt.Contains("pnull") || sOpt.Contains("ts")) { + auto gra = graphs(sOpt + " readonly"); + if (!gPad && gROOT->GetSelectedPad()) + gROOT->GetSelectedPad()->cd(); if (!sOpt.Contains("same") && gPad) { gPad->Clear(); } - auto g = dynamic_cast(exp2->DrawClone("AF")); - g->SetBit(kCanDelete); - g->GetHistogram()->SetName(".axis"); - g->GetHistogram()->SetTitle(""); - g->GetHistogram()->SetBit(TH1::kNoTitle); - exp2->DrawClone("F")->SetBit(kCanDelete); - exp1->DrawClone("F")->SetBit(kCanDelete); - exp->DrawClone("LP")->SetBit(kCanDelete); - obs->DrawClone("LP")->SetBit(kCanDelete); - TLine l; - l.SetLineStyle(2); - l.DrawLine(g->GetHistogram()->GetXaxis()->GetXmin(), 0.05, g->GetHistogram()->GetXaxis()->GetXmax(), 0.05); - // auto l = gPad->BuildLegend(gPad->GetLeftMargin()+0.05, - // gPad->GetBottomMargin()+0.05,gPad->GetLeftMargin()+0.35,gPad->GetBottomMargin()+0.25);l->SetName("legend"); - - auto leg = new TLegend(1. - gPad->GetRightMargin() - 0.3, 1. - gPad->GetTopMargin() - 0.3, - 1. - gPad->GetRightMargin() - 0.05, 1. - gPad->GetTopMargin() - 0.05); - leg->SetName("legend"); - leg->AddEntry(g->GetListOfFunctions()->FindObject("down"), "", "F"); - leg->AddEntry( - dynamic_cast(gPad->GetPrimitive(exp1->GetName()))->GetListOfFunctions()->FindObject("down"), "", - "F"); - leg->AddEntry(gPad->GetPrimitive(exp->GetName()), "", "LPE"); - leg->AddEntry(gPad->GetPrimitive(obs->GetName()), "", "LPE"); - leg->Draw(); - leg->SetBit(kCanDelete); - - g->GetHistogram()->Draw("sameaxis"); // redraw axis - - if (!sOpt.Contains("same")) { - gPad->SetGrid(0, 0); - gPad->SetLogy(1); + if (gra) { + auto gra2 = static_cast(gra->DrawClone(sOpt.Contains("same") ? "" : "A")); + gra2->SetBit(kCanDelete); + if (sOpt.Contains("pcls") || sOpt.Contains("pnull")) { + gra2->GetHistogram()->SetMinimum(1e-6); + } + if (gPad) { + gPad->RedrawAxis(); + gPad->GetCanvas()->Paint(); + gPad->GetCanvas()->Update(); + gSystem->ProcessEvents(); + } + } + if (!sOpt.Contains("same") && gPad) { + // auto mg = static_cast(gPad->GetPrimitive(gra->GetName())); + // mg->GetHistogram()->SetMinimum(1e-9); + // mg->GetHistogram()->GetYaxis()->SetRangeUser(1e-9,1); + // gPad->SetGrid(0, 0); + // gPad->SetLogy(1); } gSystem->ProcessEvents(); @@ -1154,50 +1654,22 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) return; } + // graphs("ts visualize");return; + TGraphErrors *out = new TGraphErrors; out->SetName(GetName()); - TString title = TString::Format(";%s", poi().first()->GetTitle()); + TString title = (!axes().empty()) ? TString::Format(";%s", axes().first()->GetTitle()) : ""; auto pllType = xRooFit::Asymptotics::TwoSided; if (!empty() && axes().size() == 1) { - auto v = dynamic_cast(axes().first()); for (auto &p : *this) { if (p.fPllType != xRooFit::Asymptotics::TwoSided) { pllType = p.fPllType; } } - if (pllType == xRooFit::Asymptotics::OneSidedPositive) { - if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - title += TString::Format(";Lower-Bound One-Sided Limit PLR"); - else if (v) - title += TString::Format(";One-Sided Limit PLR"); - else - title += ";q"; - } else if (pllType == xRooFit::Asymptotics::TwoSided) { - if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - title += TString::Format(";Lower-Bound PLR"); - else if (v) - title += TString::Format(";PLR"); - else - title += ";t"; - } else if (pllType == xRooFit::Asymptotics::OneSidedNegative) { - if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - title += TString::Format(";Lower-Bound One-Sided Discovery PLR"); - else if (v) - title += TString::Format(";One-Sided Discovery PLR"); - else - title += ";r"; - } else if (pllType == xRooFit::Asymptotics::Uncapped) { - if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - title += TString::Format(";Lower-Bound Uncapped PLR"); - else if (v) - title += TString::Format(";Uncapped PLR"); - else - title += ";s"; - } else { - title += ";Test Statistic"; - } + title += ";"; + title += front().tsTitle(true); } out->SetTitle(title); @@ -1208,7 +1680,7 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) if (!gPad) TCanvas::MakeDefCanvas(); - auto basePad = gPad; + TVirtualPad *basePad = gPad; if (!sOpt.Contains("same")) basePad->Clear(); @@ -1239,12 +1711,16 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) for (auto &p : *this) { if (p.fPllType != pllType) continue; // must all have same pll type - auto val = p.pll().first; + auto val = p.pll(true).first; + if (std::isnan(val)) + continue; minMax.first = std::min(minMax.first, val); minMax.second = std::max(minMax.second, val); } - out->GetHistogram()->SetMinimum(minMax.first); - out->GetHistogram()->SetMaximum(minMax.second); + if (minMax.first < std::numeric_limits::infinity()) + out->GetHistogram()->SetMinimum(minMax.first); + if (minMax.second > -std::numeric_limits::infinity()) + out->GetHistogram()->SetMaximum(minMax.second); TGraph *badPoints = nullptr; @@ -1257,6 +1733,13 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) auto val = p.pll().first; if (!ufr) ufr = p.ufit(); + if (out->GetN() == 0 && ufr && ufr->status() == 0) { + out->SetPoint(out->GetN(), + ufr->floatParsFinal().getRealValue(axes().first()->GetName(), + ufr->constPars().getRealValue(axes().first()->GetName())), + 0.); + out->SetPointError(out->GetN() - 1, 0, ufr->edm()); + } if (auto fr = p.fNull_cfit; fr && doFits) { // access member to avoid unnecessarily creating fit result if wasnt needed // create a new subpad and draw fitResult on it @@ -1270,7 +1753,7 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) //_pad->GetListOfPrimitives()->AddFirst(pad); pad->AppendPad(); } - if (std::isnan(val)) { + if (std::isnan(val) && p.status() != 0) { if (!badPoints) { badPoints = new TGraph; badPoints->SetBit(kCanDelete); @@ -1282,8 +1765,8 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) } badPoints->SetPoint(badPoints->GetN(), p.fNullVal(), out->Eval(p.fNullVal())); mainPad->Modified(); - } else { - out->SetPoint(out->GetN(), p.fNullVal(), p.pll().first); + } else if (!std::isnan(val)) { + out->SetPoint(out->GetN(), p.coords->getRealValue(axes().first()->GetName()), p.pll().first); out->SetPointError(out->GetN() - 1, 0, p.pll().second); out->Sort(); @@ -1296,13 +1779,17 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) mainPad->Modified(); } if (s.RealTime() > 3) { // stops the clock - basePad->Update(); + basePad->GetCanvas()->Paint(); + basePad->GetCanvas()->Update(); gSystem->ProcessEvents(); s.Reset(); s.Start(); } s.Continue(); } + basePad->GetCanvas()->Paint(); + basePad->GetCanvas()->Update(); + gSystem->ProcessEvents(); // finish by overlaying ufit if (ufr && doFits) { @@ -1326,11 +1813,13 @@ void xRooNLLVar::xRooHypoSpace::Draw(Option_t *opt) basePad->cd(); } - if (!xRooNode::gIntObj) { - xRooNode::gIntObj = new xRooNode::InteractiveObject; + if (doFits) { + if (!xRooNode::gIntObj) { + xRooNode::gIntObj = new xRooNode::InteractiveObject; + } + gPad->GetCanvas()->Connect("Highlighted(TVirtualPad*,TObject*,Int_t,Int_t)", "xRooNode::InteractiveObject", + xRooNode::gIntObj, "Interactive_PLLPlot(TVirtualPad*,TObject*,Int_t,Int_t)"); } - gPad->GetCanvas()->Connect("Highlighted(TVirtualPad*,TObject*,Int_t,Int_t)", "xRooNode::InteractiveObject", - xRooNode::gIntObj, "Interactive_PLLPlot(TVirtualPad*,TObject*,Int_t,Int_t)"); return; } @@ -1344,7 +1833,8 @@ RooStats::HypoTestInverterResult *xRooNLLVar::xRooHypoSpace::result() if (_axes.empty()) return out; - out = new RooStats::HypoTestInverterResult(GetName(), *dynamic_cast(_axes.at(0)), 0.05); + out = new RooStats::HypoTestInverterResult(GetName(), *dynamic_cast(_axes.at(0)), 0.95); + out->SetTitle(GetTitle()); for (auto &p : *this) { double _x = p.coords->getRealValue(_axes.at(0)->GetName(), std::numeric_limits::quiet_NaN()); @@ -1354,4 +1844,4 @@ RooStats::HypoTestInverterResult *xRooNLLVar::xRooHypoSpace::result() return out; } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/xRooNLLVar.cxx b/roofit/xroofit/src/xRooNLLVar.cxx index a130e939938a8..738f1b7f8e604 100644 --- a/roofit/xroofit/src/xRooNLLVar.cxx +++ b/roofit/xroofit/src/xRooNLLVar.cxx @@ -10,10 +10,24 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +/** \class ROOT::Experimental::XRooFit::xRooNLLVar +\ingroup xroofit + +This xRooNLLVar object has several special methods, e.g. for fitting and toy dataset generation. + + */ + + +#include "RVersion.h" + +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) #define protected public +#endif #include "RooFitResult.h" #include "RooNLLVar.h" +#ifdef protected #undef protected +#endif #include "xRooFit/xRooFit.h" @@ -40,9 +54,26 @@ #include "Math/GenAlgoOptions.h" +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) #define private public +#define GETWS(a) a->_myws +#define GETWSSETS(w) w->_namedSets +#else +#define GETWS(a) a->workspace() +#define GETWSSETS(w) w->sets() +#endif #include "RooWorkspace.h" +#ifdef private #undef private +#endif + +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) +#define protected public +#endif +#include "RooStats/HypoTestResult.h" +#ifdef protected +#undef protected +#endif #include "TMultiGraph.h" #include "TCanvas.h" @@ -52,15 +83,62 @@ #include "TStyle.h" #include "TH1D.h" #include "TLegend.h" +#include "RooCategory.h" +#include "TTree.h" +#include "TGraph2D.h" -#define protected public -#include "RooStats/HypoTestResult.h" -#undef protected +#include "RooGaussian.h" +#include "RooPoisson.h" + +#include "TROOT.h" +#include "TKey.h" +#include "TRegexp.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; std::set xRooNLLVar::xRooHypoPoint::allowedStatusCodes = {0}; +class AutoRestorer { +public: + AutoRestorer(const RooAbsCollection &s, xRooNLLVar *nll = nullptr) : fSnap(s.snapshot()), fNll(nll) + { + fPars.add(s); + if (fNll) { + // if (!fNll->kReuseNLL) fOldNll = *fNll; + fOldData = fNll->getData(); + fOldName = fNll->get()->GetName(); + fOldTitle = fNll->get()->getStringAttribute("fitresultTitle"); + } + } + ~AutoRestorer() + { + ((RooAbsCollection &)fPars) = *fSnap; + if (fNll) { + // commented out code was attempt to speed up things avoid unnecessarily reinitializing things over and over + // if (!fNll->kReuseNLL) { + // // can be faster just by putting back in old nll + // fNll->std::shared_ptr::operator=(fOldNll); + // fNll->fData = fOldData.first; + // fNll->fGlobs = fOldData.second; + // } else { + // fNll->setData(fOldData); + // fNll->get()->SetName(fOldName); + // fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle); + // } + fNll->fGlobs = fOldData.second; // will mean globs matching checks are skipped in setData + fNll->setData(fOldData); + fNll->get()->SetName(fOldName); + fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle); + } + } + RooArgSet fPars; + std::unique_ptr fSnap; + xRooNLLVar *fNll = nullptr; + // std::shared_ptr fOldNll; + std::pair, std::shared_ptr> fOldData; + TString fOldName, fOldTitle; +}; + xRooNLLVar::~xRooNLLVar() {} xRooNLLVar::xRooNLLVar(RooAbsPdf &pdf, const std::pair &data, @@ -87,6 +165,11 @@ xRooNLLVar::xRooNLLVar(const std::shared_ptr &pdf, }); fOpts->SetName(""); + // we *must* take global observables from the model even if they are included in the dataset + // this is because the way xRooNLLVar is coded up it assumes the globs in the funcVars *ARE* + // part of the model + fOpts->Add(RooFit::GlobalObservablesSource("model").Clone(nullptr)); + for (int i = 0; i < opts.GetSize(); i++) { if (strlen(opts.At(i)->GetName()) == 0) continue; // skipping "none" cmds @@ -97,6 +180,16 @@ xRooNLLVar::xRooNLLVar(const std::shared_ptr &pdf, if (!fGlobs || !fGlobs->equals(*gl)) { throw std::runtime_error("GlobalObservables mismatch"); } + } else if (strcmp(opts.At(i)->GetName(), "Hesse") == 0) { + fitConfig()->SetParabErrors(dynamic_cast(opts.At(i))->getInt(0)); // controls hesse + } else if (strcmp(opts.At(i)->GetName(), "Strategy") == 0) { + fitConfig()->MinimizerOptions().SetStrategy(dynamic_cast(opts.At(i))->getInt(0)); + } else if (strcmp(opts.At(i)->GetName(), "StrategySequence") == 0) { + fitConfigOptions()->SetNamedValue("StrategySequence", dynamic_cast(opts.At(i))->getString(0)); + } else if (strcmp(opts.At(i)->GetName(), "Tolerance") == 0) { + fitConfig()->MinimizerOptions().SetTolerance(dynamic_cast(opts.At(i))->getInt(0)); + } else if (strcmp(opts.At(i)->GetName(), "PrintLevel") == 0) { + fitConfig()->MinimizerOptions().SetPrintLevel(dynamic_cast(opts.At(i))->getInt(0)); } else { if (strcmp(opts.At(i)->GetName(), "Optimize") == 0) { // this flag will trigger constOptimizeTestStatistic to be called on the nll in createNLL method @@ -110,6 +203,11 @@ xRooNLLVar::xRooNLLVar(const std::shared_ptr &pdf, if (fGlobs) { // add global observables opt with function obs auto _vars = std::unique_ptr(fPdf->getVariables()); + if (auto extCon = dynamic_cast(fOpts->find("ExternalConstraints"))) { + for (auto con : *extCon->getSet(0)) { + _vars->add(*std::unique_ptr(con->getVariables())); + } + } auto _funcGlobs = std::unique_ptr(dynamic_cast(_vars->selectCommon(*fGlobs))); fOpts->Add(RooFit::GlobalObservables(*_funcGlobs).Clone()); } @@ -256,6 +354,7 @@ void xRooNLLVar::reinitialize() // need to find all RooRealSumPdf nodes and mark them binned or unbinned as required RooArgSet s; fPdf->treeNodeServerList(&s, nullptr, true, false); + s.add(*fPdf.get()); // ensure include self in case fitting a RooRealSumPdf bool isBinned = false; bool hasBinned = false; // if no binned option then 'auto bin' ... if (auto a = dynamic_cast(fOpts->find("Binned")); a) { @@ -273,7 +372,7 @@ void xRooNLLVar::reinitialize() std::unique_ptr obs(a->getObservables(fData->get())); if (obs->size() == 1) { // RooNLLVar requires exactly 1 obs auto *var = static_cast(obs->first()); - std::unique_ptr> boundaries{dynamic_cast(a)->binBoundaries( + std::unique_ptr> boundaries{dynamic_cast(a)->binBoundaries( *var, -std::numeric_limits::infinity(), std::numeric_limits::infinity())}; if (boundaries) { if (!std::shared_ptr::get()) @@ -289,20 +388,22 @@ void xRooNLLVar::reinitialize() } } // before creating, clear away caches if any if pdf is in ws - if (fPdf->_myws) { + if (GETWS(fPdf)) { std::set setNames; - for (auto &a : static_cast(fPdf->_myws)->_namedSets) { + for (auto &a : GETWSSETS(GETWS(fPdf))) { if (TString(a.first.c_str()).BeginsWith("CACHE_")) { setNames.insert(a.first); } } - for (auto &a : setNames) - fPdf->_myws->removeSet(a.c_str()); + for (auto &a : setNames) { + GETWS(fPdf)->removeSet(a.c_str()); + } } std::set attribs; if (std::shared_ptr::get()) attribs = std::shared_ptr::get()->attributes(); - this->reset(fPdf->createNLL(*fData, *fOpts)); + this->reset(std::unique_ptr{fPdf->createNLL(*fData, *fOpts)}.release()); + std::shared_ptr::get()->SetName(TString::Format("nll_%s/%s", fPdf->GetName(), fData->GetName())); // RooFit only swaps in what it calls parameters, this misses out the RooConstVars which we treat as pars as well // so swap those in ... question: is recursiveRedirectServers usage in RooAbsOptTestStatic (and here) a memory // leak?? where do the replaced servers get deleted?? @@ -310,8 +411,8 @@ void xRooNLLVar::reinitialize() for (auto &a : attribs) std::shared_ptr::get()->setAttribute(a.c_str()); // create parent on next line to avoid triggering workspace initialization code in constructor of xRooNode - if (fPdf->_myws) { - xRooNode(*fPdf->_myws, std::make_shared()).sterilize(); + if (GETWS(fPdf)) { + xRooNode(*GETWS(fPdf), std::make_shared()).sterilize(); } // there seems to be a nasty bug somewhere that can make the cache become invalid, so clear it here if (oldName != "") std::shared_ptr::get()->SetName(oldName); @@ -323,7 +424,7 @@ void xRooNLLVar::reinitialize() } } - fFuncVars.reset(std::shared_ptr::get()->getVariables()); + fFuncVars = std::unique_ptr{std::shared_ptr::get()->getVariables()}; if (fGlobs) { fFuncGlobs.reset(fFuncVars->selectCommon(*fGlobs)); fFuncGlobs->setAttribAll("Constant", true); @@ -341,14 +442,17 @@ xRooNLLVar::generate(bool expected, int seed) RooArgList l; l.add((fFuncVars) ? *fFuncVars : *std::unique_ptr(fPdf->getParameters(*fData))); fr->setConstParList(l); - fr->_constPars->setAttribAll("global", false); + const_cast(fr->constPars()).setAttribAll("global", false); if (fGlobs) - std::unique_ptr(fr->_constPars->selectCommon(*fGlobs))->setAttribAll("global", true); - return xRooFit::generateFrom(*fPdf, fr, expected, seed); + std::unique_ptr(fr->constPars().selectCommon(*fGlobs))->setAttribAll("global", true); + return xRooFit::generateFrom(*fPdf, *fr, expected, seed); } -xRooNLLVar::xRooFitResult::xRooFitResult(const std::shared_ptr &in) - : std::shared_ptr(std::dynamic_pointer_cast(in->fComp)), fNode(in) +xRooNLLVar::xRooFitResult::xRooFitResult(const std::shared_ptr &in, const std::shared_ptr &nll) + : std::shared_ptr(std::dynamic_pointer_cast(in->fComp)), + fNode(in), + fNll(nll), + fCfits(std::make_shared>()) { } const RooFitResult *xRooNLLVar::xRooFitResult::operator->() const @@ -366,82 +470,196 @@ void xRooNLLVar::xRooFitResult::Draw(Option_t *opt) fNode->Draw(opt); } +xRooNLLVar::xRooFitResult xRooNLLVar::xRooFitResult::cfit(const char *poiValues, const char *alias) +{ + + // create a hypoPoint with ufit equal to this fit + // and poi equal to given poi + if (!fNll) + throw std::runtime_error("xRooFitResult::cfit: Cannot create cfit without nll"); + + // see if fit already done + if (alias) { + if (auto res = fCfits->find(alias); res != fCfits->end()) { + return res->second; + } + } + if (auto res = fCfits->find(poiValues); res != fCfits->end()) { + return res->second; + } + + AutoRestorer s(*fNll->fFuncVars); + *fNll->fFuncVars = get()->floatParsFinal(); + fNll->fFuncVars->assignValueOnly(get()->constPars()); + std::unique_ptr(fNll->fFuncVars->selectCommon(get()->floatParsFinal())) + ->setAttribAll("Constant", false); + std::unique_ptr(fNll->fFuncVars->selectCommon(get()->constPars()))->setAttribAll("Constant", true); + + auto hp = fNll->hypoPoint(poiValues, std::numeric_limits::quiet_NaN(), xRooFit::Asymptotics::Unknown); + hp.fUfit = *this; + auto out = xRooNLLVar::xRooFitResult(std::make_shared(hp.cfit_null(), fNode->fParent), fNll); + fCfits->insert(std::pair((alias) ? alias : poiValues, out)); + return out; +} +xRooNLLVar::xRooFitResult xRooNLLVar::xRooFitResult::ifit(const char *np, bool up, bool prefit) +{ + RooRealVar *npVar = dynamic_cast((prefit ? get()->floatParsInit() : get()->floatParsFinal()).find(np)); + if (!npVar) + throw std::runtime_error("xRooFitResult::ifit: par not found"); + return cfit(TString::Format("%s=%f", np, npVar->getVal() + (up ? npVar->getErrorHi() : npVar->getErrorLo()))); +} +double xRooNLLVar::xRooFitResult::impact(const char *poi, const char *np, bool up, bool prefit, bool covApprox) +{ + if (!covApprox) { + // get the ifit and get the difference between the postFit poi values + RooRealVar *poiHat = dynamic_cast((get()->floatParsFinal()).find(poi)); + if (!poiHat) + throw std::runtime_error("xRooFitResult::impact: poi not found"); + auto _ifit = ifit(np, up, prefit); + if (!_ifit) + throw std::runtime_error("xRooFitResult::impact: null ifit"); + if (_ifit->status() != 0) + fNode->Warning("impact", "ifit status code is %d", _ifit->status()); + return _ifit->floatParsFinal().getRealValue(poi) - poiHat->getVal(); + } else { + // estimate impact from the covariance matrix .... + int iPoi = get()->floatParsFinal().index(poi); + int iNp = get()->floatParsFinal().index(np); + if (iPoi == -1) + throw std::runtime_error("xRooFitResult::impact: poi not found"); + if (iNp == -1) + throw std::runtime_error("xRooFitResult::impact: np not found"); + RooRealVar *npVar = + dynamic_cast((prefit ? get()->floatParsInit() : get()->floatParsFinal()).find(np)); + return get()->covarianceMatrix()(iPoi, iNp) / (up ? npVar->getErrorHi() : npVar->getErrorLo()); + } + return std::numeric_limits::quiet_NaN(); +} + +double xRooNLLVar::xRooFitResult::conditionalError(const char *poi, const char *nps, bool up, bool covApprox) +{ + // run a fit with given NPs held constant, return quadrature difference + + TString npNames; + RooArgList vars; + RooAbsArg *poiVar = nullptr; + for (auto p : get()->floatParsFinal()) { + if (strcmp(p->GetName(), poi) == 0) { + vars.add(*p); + poiVar = p; + continue; + } + TStringToken pattern(nps, ","); + bool matches = false; + while (pattern.NextToken()) { + TString s(pattern); + if ((p->getStringAttribute("group") && s == p->getStringAttribute("group")) || + TString(p->GetName()).Contains(TRegexp(s, true)) || p->getAttribute(s)) { + matches = true; + break; + } + } + if (matches) { + if (npNames.Length()) + npNames += ","; + npNames += p->GetName(); + } else { + vars.add(*p); // keeping in reduced cov matrix + } + } + if (!poiVar) { + throw std::runtime_error(TString::Format("Could not find poi: %s", poi)); + } + if (npNames == "") { + fNode->Warning("conditionalError", "No parameters selected by: %s", nps); + return (up) ? static_cast(poiVar)->getErrorHi() : static_cast(poiVar)->getErrorLo(); + } + + if (covApprox) { + int idx = vars.index(poi); + return sqrt(get()->conditionalCovarianceMatrix(vars)(idx, idx)); + } + + auto _cfit = cfit(npNames.Data(), nps); + + auto _poi = _cfit->floatParsFinal().find(poi); + + return (up) ? static_cast(_poi)->getErrorHi() : static_cast(_poi)->getErrorLo(); +} + +RooArgList xRooNLLVar::xRooFitResult::ranknp(const char *poi, bool up, bool prefit, double approxThreshold) +{ + + RooRealVar *poiHat = dynamic_cast((get()->floatParsFinal()).find(poi)); + if (!poiHat) + throw std::runtime_error("xRooFitResult::ranknp: poi not found"); + + std::vector> ranks; + // first do with the covariance approximation, since that's always available + for (auto par : get()->floatParsFinal()) { + if (par == poiHat) + continue; + ranks.emplace_back(std::pair(par->GetName(), impact(poi, par->GetName(), up, prefit, true))); + } + + std::sort(ranks.begin(), ranks.end(), [](auto &left, auto &right) { + if (std::isnan(left.second) && !std::isnan(right.second)) + return false; + if (!std::isnan(left.second) && std::isnan(right.second)) + return true; + return fabs(left.second) > fabs(right.second); + }); + + // now redo the ones above the threshold + for (auto &[n, v] : ranks) { + if (v >= approxThreshold) { + try { + v = impact(poi, n.c_str(), up, prefit); + } catch (...) { + v = std::numeric_limits::quiet_NaN(); + }; + } + } + + // resort + std::sort(ranks.begin(), ranks.end(), [](auto &left, auto &right) { + if (std::isnan(left.second) && !std::isnan(right.second)) + return false; + if (!std::isnan(left.second) && std::isnan(right.second)) + return true; + return fabs(left.second) > fabs(right.second); + }); + + RooArgList out; + out.setName("rankings"); + for (auto &[n, v] : ranks) { + out.addClone(*get()->floatParsFinal().find(n.c_str())); + auto vv = static_cast(out.at(out.size() - 1)); + vv->setVal(v); + vv->removeError(); + vv->removeRange(); + } + return out; +} + xRooNLLVar::xRooFitResult xRooNLLVar::minimize(const std::shared_ptr &_config) { auto &nll = *get(); - auto out = xRooFit::minimize(nll, (_config) ? _config : fitConfig()); + auto out = xRooFit::minimize(nll, (_config) ? _config : fitConfig(), fOpts); // add any pars that are const here that aren't in constPars list because they may have been // const-optimized and their values cached with the dataset, so if subsequently floated the // nll wont evaluate correctly // fConstVars.reset( fFuncVars->selectByAttrib("Constant",true) ); - // if saving fits, check the nllOpts have been saved as well ... - - if (out && !nll.getAttribute("readOnly")) { - if (strlen(fOpts->GetName()) == 0) - fOpts->SetName(TUUID().AsString()); - auto cacheDir = gDirectory; - if (cacheDir && cacheDir->IsWritable()) { - // save a copy of fit result to relevant dir - if (!cacheDir->GetDirectory(nll.GetName())) - cacheDir->mkdir(nll.GetName()); - if (auto dir = cacheDir->GetDirectory(nll.GetName()); dir) { - if (!dir->FindKey(fOpts->GetName())) { - dir->WriteObject(fOpts.get(), fOpts->GetName()); - } - } - } - } - // before returning, flag which of the constPars were actually global observables if (out) { - out->_constPars->setAttribAll("global", false); + const_cast(out->constPars()).setAttribAll("global", false); if (fGlobs) - std::unique_ptr(out->_constPars->selectCommon(*fGlobs))->setAttribAll("global", true); + std::unique_ptr(out->constPars().selectCommon(*fGlobs))->setAttribAll("global", true); } - return xRooFitResult(std::make_shared(out, fPdf)); + return xRooFitResult(std::make_shared(out, fPdf), std::make_shared(*this)); } -class AutoRestorer { -public: - AutoRestorer(const RooAbsCollection &s, xRooNLLVar *nll = nullptr) : fSnap(s.snapshot()), fNll(nll) - { - fPars.add(s); - if (fNll) { - // if (!fNll->kReuseNLL) fOldNll = *fNll; - fOldData = fNll->getData(); - fOldName = fNll->get()->GetName(); - fOldTitle = fNll->get()->getStringAttribute("fitresultTitle"); - } - } - ~AutoRestorer() - { - ((RooAbsCollection &)fPars) = *fSnap; - if (fNll) { - // commented out code was attempt to speed up things avoid unnecessarily reinitializing things over and over - // if (!fNll->kReuseNLL) { - // // can be faster just by putting back in old nll - // fNll->std::shared_ptr::operator=(fOldNll); - // fNll->fData = fOldData.first; - // fNll->fGlobs = fOldData.second; - // } else { - // fNll->setData(fOldData); - // fNll->get()->SetName(fOldName); - // fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle); - // } - fNll->setData(fOldData); - fNll->get()->SetName(fOldName); - fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle); - } - } - RooArgSet fPars; - std::unique_ptr fSnap; - xRooNLLVar *fNll = nullptr; - // std::shared_ptr fOldNll; - std::pair, std::shared_ptr> fOldData; - TString fOldName, fOldTitle; -}; - std::shared_ptr xRooNLLVar::fitConfig() { if (!fFitConfig) @@ -456,7 +674,7 @@ ROOT::Math::IOptions *xRooNLLVar::fitConfigOptions() return nullptr; } -double xRooNLLVar::getEntryVal(size_t entry) +double xRooNLLVar::getEntryVal(size_t entry) const { auto _data = data(); if (!_data) @@ -470,7 +688,137 @@ double xRooNLLVar::getEntryVal(size_t entry) return -_data->weight() * _pdf->getLogVal(_data->get()); } -std::shared_ptr xRooNLLVar::pars(bool stripGlobalObs) +double xRooNLLVar::getEntryBinWidth(size_t entry) const +{ + + auto _data = data(); + if (!_data) + return 0; + if (size_t(_data->numEntries()) <= entry) + return 0; + auto _pdf = pdf().get(); + *std::unique_ptr(_pdf->getObservables(_data->get())) = *_data->get(entry); // only set robs + if (auto s = dynamic_cast(_pdf); s) { + _pdf = s->getPdf(s->indexCat().getCurrentLabel()); + } + std::unique_ptr _robs(_pdf->getObservables(_data->get())); + double volume = 1.; + for (auto o : *_robs) { + + if (auto a = dynamic_cast(o); a) { + std::unique_ptr> bins( + _pdf->binBoundaries(*a, -std::numeric_limits::infinity(), std::numeric_limits::infinity())); + if (bins) { + double lowEdge = -std::numeric_limits::infinity(); + for (auto b : *bins) { + if (b > a->getVal()) { + volume *= (b - lowEdge); + break; + } + lowEdge = b; + } + } + } + } + + return volume; +} + +double xRooNLLVar::saturatedConstraintTerm() const +{ + // for each global observable in the dataset, determine which constraint term is associated to it + // and given its type, add the necessary saturated term... + + double out = 0; + + if (!fGlobs) + return 0; + + auto cTerm = constraintTerm(); + if (!cTerm) + return 0; + + for (auto c : cTerm->list()) { + if (auto gaus = dynamic_cast(c)) { + auto v = dynamic_cast(fGlobs->find(gaus->getX().GetName())); + if (!v) { + v = dynamic_cast(fGlobs->find( + gaus->getMean().GetName())); // shouldn't really happen but does for at least ws made by pyhf + } + if (!v) + continue; + out -= std::log(ROOT::Math::gaussian_pdf(v->getVal(), gaus->getSigma().getVal(), v->getVal())); + } else if (auto pois = dynamic_cast(c)) { + auto v = dynamic_cast(fGlobs->find(pois->getX().GetName())); + if (!v) + continue; + out -= std::log(TMath::Poisson(v->getVal(), v->getVal())); + } + } + + return out; +} + +double xRooNLLVar::ndof() const +{ + return data()->numEntries() + (globs() ? globs()->size() : 0) - + std::unique_ptr(pars()->selectByAttrib("Constant", false))->size(); +} + +double xRooNLLVar::pgof() const +{ + // note that if evaluating this for a single channel, until 6.30 is available if you are using Binned mode the pdf + // will need to be part of a Simultaneous + return TMath::Prob(2. * (get()->getVal() - saturatedVal()), ndof()); +} + +double xRooNLLVar::saturatedVal() const +{ + return saturatedNllTerm() + saturatedConstraintTerm(); +} + +double xRooNLLVar::saturatedNllTerm() const +{ + + // Use this term to create a goodness-of-fit metric, which is approx chi2 distributed with numEntries (data) d.o.f: + // prob = TMath::Prob( 2.*(nll.nllTerm()->getVal() - nll.saturatedNllTerm()), nll.data()->numEntries() ) + + // note that need to construct nll with explicit Binned(1 or 0) option otherwise will pick up nll eval + // from attributes in model already, so many get binned nllTerm eval when thinking not binned because didnt specify + // Binned(1) + + auto _data = data(); + if (!_data) + return std::numeric_limits::quiet_NaN(); + + bool isBinned = false; + if (auto a = dynamic_cast(fOpts->find("Binned")); a) { + isBinned = a->getInt(0); + } + + // for binned case each entry is: -(-N + Nlog(N) - TMath::LnGamma(N+1)) + // for unbinned case each entry is: -(N*log(N/(sumN*binW))) = -N*logN + N*log(sumN) + N*log(binW) + // but unbinned gets extendedTerm = sumN - sumN*log(sumN) + // so resulting sum is just sumN - sum[ N*logN - N*log(binW) ] + // which is the same as the binned case without the LnGamma part and with the extra sum[N*log(binW)] part + + double out = _data->sumEntries(); + for (int i = 0; i < _data->numEntries(); i++) { + _data->get(i); + double w = _data->weight(); + out -= w * std::log(w); + if (isBinned) + out += TMath::LnGamma(w + 1); + else + out += w * std::log(getEntryBinWidth(i)); + } + + out += simTerm(); + + return out; +} + +std::shared_ptr xRooNLLVar::pars(bool stripGlobalObs) const { auto out = std::shared_ptr(get()->getVariables()); if (stripGlobalObs && fGlobs) { @@ -479,6 +827,50 @@ std::shared_ptr xRooNLLVar::pars(bool stripGlobalObs) return out; } +TObject * +xRooNLLVar::Scan(const char *scanPars, const std::vector> &coords, const RooArgList &profilePars) +{ + return Scan(*std::unique_ptr(get()->getVariables()->selectByName(scanPars)), coords, profilePars); +} + +TObject *xRooNLLVar::Scan(const RooArgList &scanPars, const std::vector> &coords, + const RooArgList &profilePars) +{ + + if (scanPars.size() > 2 || scanPars.empty()) + return nullptr; + + TGraph2D *out2d = (scanPars.size() == 2) ? new TGraph2D() : nullptr; + TGraph *out1d = (out2d) ? nullptr : new TGraph(); + TNamed *out = (out2d) ? static_cast(out2d) : static_cast(out1d); + out->SetName(get()->GetName()); + out->SetTitle(TString::Format("%s;%s%s%s", get()->GetTitle(), scanPars.first()->GetTitle(), out2d ? ";" : "", + out2d ? scanPars.at(1)->GetTitle() : "")); + + std::unique_ptr funcVars(get()->getVariables()); + AutoRestorer snap(*funcVars); + + for (auto &coord : coords) { + if (coord.size() != scanPars.size()) { + throw std::runtime_error("Invalid coordinate"); + } + for (size_t i = 0; i < coord.size(); i++) { + static_cast(scanPars[i]).setVal(coord[i]); + } + + if (profilePars.empty()) { + // just evaluate + if (out2d) { + out2d->SetPoint(out2d->GetN(), coord[0], coord[1], get()->getVal()); + } else { + out1d->SetPoint(out1d->GetN(), coord[0], get()->getVal()); + } + } + } + + return out; +} + void xRooNLLVar::Draw(Option_t *opt) { TString sOpt(opt); @@ -607,7 +999,7 @@ std::pair, std::shared_ptr> return std::make_pair(fData, fGlobs); } -Bool_t xRooNLLVar::setData(const xRooNode &data) +bool xRooNLLVar::setData(const xRooNode &data) { if (data.fComp && !data.get()) { return false; @@ -616,7 +1008,7 @@ Bool_t xRooNLLVar::setData(const xRooNode &data) std::shared_ptr(data.globs().argList().snapshot())); } -Bool_t xRooNLLVar::setData(const std::pair, std::shared_ptr> &_data) +bool xRooNLLVar::setData(const std::pair, std::shared_ptr> &_data) { if (fData == _data.first && fGlobs == _data.second) @@ -624,17 +1016,22 @@ Bool_t xRooNLLVar::setData(const std::pair, std::sha auto _globs = fGlobs; // done to keep globs alive while NLL might still be alive. - if (fGlobs && !(fGlobs->empty() && !_data.second) && - _data.first) { // second condition allows for no globs being a nullptr, third allow globs to remain if nullifying - // data - if (!_data.second) + auto _dglobs = (_data.second) ? _data.second + : std::shared_ptr(_data.first->getGlobalObservables(), + [](const RooAbsCollection *) {}); + + if (fGlobs && !(fGlobs->empty() && !_dglobs) && _data.first && + fGlobs != + _dglobs) { // second condition allows for no globs being a nullptr, third allow globs to remain if nullifying + // data + if (!_dglobs) throw std::runtime_error("Missing globs"); // ignore 'extra' globs RooArgSet s; s.add(*fGlobs); std::unique_ptr _actualGlobs(fPdf->getObservables(s)); RooArgSet s2; - s2.add(*_data.second); + s2.add(*_dglobs); std::unique_ptr _actualGlobs2(fPdf->getObservables(s2)); if (!_actualGlobs->equals(*_actualGlobs2)) { RooArgSet rC; @@ -647,7 +1044,7 @@ Bool_t xRooNLLVar::setData(const std::pair, std::sha TString l = (!lC.empty()) ? lC.contentsString() : ""; throw std::runtime_error(TString::Format("globs mismatch: adding %s removing %s", r.Data(), l.Data())); } - fGlobs = _data.second; + fGlobs = _dglobs; } if (!std::shared_ptr::get()) { @@ -660,10 +1057,17 @@ Bool_t xRooNLLVar::setData(const std::pair, std::sha throw std::runtime_error("not supported"); } bool out = false; - if (_data.first) - out = nllTerm()->setData(*_data.first, false /* clone data? */); - else + if (_data.first) { + if (_data.first->getGlobalObservables()) { + // replace in all terms + get()->setData(*_data.first, false); + } else { + // replace just in nllTerm ... note to self: why not just replace in all like above? should test! + out = nllTerm()->setData(*_data.first, false /* clone data? */); + } + } else { reset(); + } fData = _data.first; return out; } catch (std::runtime_error &) { @@ -754,11 +1158,15 @@ double xRooNLLVar::simTerm() const double xRooNLLVar::binnedDataTerm() const { // this is only relevant if BinnedLikelihood active + // = sum[ N_i! ] since LnGamma(N_i+1) ~= N_i! + // need to also subtract off sum[ N_i*log(width_i) ] in order to have formula: binnedLL = unbinnedLL + binnedDataTerm + // note this is 0 if all the bin widths are 1 double out = 0; for (int i = 0; i < fData->numEntries(); i++) { fData->get(i); - out += TMath::LnGamma(fData->weight() + 1); + out += TMath::LnGamma(fData->weight() + 1) - fData->weight() * std::log(getEntryBinWidth(i)); } + return out; } @@ -785,9 +1193,9 @@ std::pair xRooNLLVar::xRooHypoPoint::getVal(const char *what) TString sWhat(what); sWhat.ToLower(); bool doTS = sWhat.Contains("ts"); - bool doCLs = sWhat.Contains("cls"); - bool doNull = sWhat.Contains("null"); - bool doAlt = sWhat.Contains("alt"); + bool doCLs = sWhat.Contains("pcls"); + bool doNull = sWhat.Contains("pnull"); + bool doAlt = sWhat.Contains("palt"); double nSigma = (sWhat.Contains("exp")) ? (TString(sWhat(sWhat.Index("exp") + 3, sWhat.Index(" ", sWhat.Index("exp")) == -1 ? sWhat.Length() @@ -796,10 +1204,37 @@ std::pair xRooNLLVar::xRooHypoPoint::getVal(const char *what) : std::numeric_limits::quiet_NaN(); bool toys = sWhat.Contains("toys"); + // bool asymp = sWhat.Contains("asymp"); bool readOnly = sWhat.Contains("readonly"); + if (!readOnly) { + if (toys) { + sigma_mu(); // means we will be able to evaluate the asymptotic values too + } + // only add toys if actually required + if (getVal(sWhat + " readonly").second != 0) { + if (sWhat.Contains("toys=")) { + // extract number of toys required ... format is "nullToys.altToysFraction" if altToysFraction=0 then use + // same for both + size_t nToys = TString(sWhat(sWhat.Index("toys=") + 5, sWhat.Length())).Atoi(); + size_t nToysAlt = (TString(sWhat(sWhat.Index("toys=") + 5, sWhat.Length())).Atof() - nToys) * nToys; + if (nToysAlt == 0) + nToysAlt = nToys; + if (nullToys.size() < nToys) { + addNullToys(nToys - nullToys.size()); + } + if (altToys.size() < nToysAlt) { + addAltToys(nToysAlt - altToys.size()); + } + } else if (doCLs && toys) { + // auto toy-generating for limits .. do in blocks of 100 + addCLsToys(100, 0, 0.05, nSigma); + } + } + } + struct RestoreNll { RestoreNll(std::shared_ptr &v, bool r) : rr(r), var(v) { @@ -836,7 +1271,7 @@ std::pair xRooNLLVar::xRooHypoPoint::getVal(const char *what) throw std::runtime_error(std::string("Unknown: ") + what); } -RooArgList xRooNLLVar::xRooHypoPoint::poi() +RooArgList xRooNLLVar::xRooHypoPoint::poi() const { RooArgList out; out.setName("poi"); @@ -844,7 +1279,7 @@ RooArgList xRooNLLVar::xRooHypoPoint::poi() return out; } -RooArgList xRooNLLVar::xRooHypoPoint::alt_poi() +RooArgList xRooNLLVar::xRooHypoPoint::alt_poi() const { RooArgList out; out.setName("alt_poi"); @@ -877,16 +1312,20 @@ int xRooNLLVar::xRooHypoPoint::status() const return out; } -void xRooNLLVar::xRooHypoPoint::Print() +void xRooNLLVar::xRooHypoPoint::Print(Option_t *) const { - std::cout << "POI: " << poi().contentsString() << " , null: " << dynamic_cast(poi().first())->getVal() - << " , alt: " << dynamic_cast(alt_poi().first())->getVal(); + std::cout << "POI: " << const_cast(this)->poi().contentsString() + << " , null: " << dynamic_cast(const_cast(this)->poi().first())->getVal() + << " , alt: " + << dynamic_cast(const_cast(this)->alt_poi().first())->getVal(); std::cout << " , pllType: " << fPllType << std::endl; std::cout << " - ufit: "; if (fUfit) { - std::cout << fUfit->minNll() << " (status=" << fUfit->status() << ") (" << mu_hat().GetName() - << "_hat: " << mu_hat().getVal() << " +/- " << mu_hat().getError() << ")" << std::endl; + std::cout << fUfit->GetName() << " " << fUfit->minNll() << " (status=" << fUfit->status() << ") (" + << const_cast(this)->mu_hat().GetName() + << "_hat: " << const_cast(this)->mu_hat().getVal() << " +/- " + << const_cast(this)->mu_hat().getError() << ")" << std::endl; } else { std::cout << "Not calculated" << std::endl; } @@ -896,7 +1335,7 @@ void xRooNLLVar::xRooHypoPoint::Print() } else { std::cout << "Not calculated"; } - if (!std::isnan(dynamic_cast(alt_poi().first())->getVal())) { + if (!std::isnan(dynamic_cast(const_cast(this)->alt_poi().first())->getVal())) { std::cout << std::endl << " - alt cfit: "; if (fAlt_cfit) { std::cout << fAlt_cfit->GetName() << " " << fAlt_cfit->minNll() << " (status=" << fAlt_cfit->status() << ")" @@ -905,10 +1344,12 @@ void xRooNLLVar::xRooHypoPoint::Print() std::cout << "Not calculated" << std::endl; } std::cout << " sigma_mu: "; + const_cast(this)->asimov(true); // will trigger construction of fAsimov hypoPoint if possible if (!fAsimov || !fAsimov->fUfit || !fAsimov->fNull_cfit) { std::cout << "Not calculated"; } else { - std::cout << sigma_mu().first << " +/- " << sigma_mu().second; + std::cout << const_cast(this)->sigma_mu().first << " +/- " + << const_cast(this)->sigma_mu().second; } if (fAsimov) { std::cout << std::endl; @@ -961,25 +1402,76 @@ RooRealVar &xRooNLLVar::xRooHypoPoint::mu_hat() throw std::runtime_error("Unconditional fit unavailable"); } +std::pair, std::shared_ptr> xRooNLLVar::xRooHypoPoint::data() +{ + if (fData.first) + return fData; + if (fGenFit && isExpected) { + // std::cout << "Generating asimov" << std::endl;poi().Print("v"); + fData = xRooFit::generateFrom(*nllVar->fPdf, *fGenFit, true); + } + return fData; +} + +xRooNLLVar::xRooHypoPoint::xRooHypoPoint(std::shared_ptr htr, const RooAbsCollection *_coords) + : TNamed(), hypoTestResult(htr) +{ + if (hypoTestResult) { + // load the pllType + fPllType = + xRooFit::Asymptotics::PLLType(hypoTestResult->GetFitInfo()->getGlobalObservables()->getCatIndex("pllType")); + isExpected = hypoTestResult->GetFitInfo()->getGlobalObservables()->getRealValue("isExpected"); + + // load the toys + auto toys = hypoTestResult->GetNullDetailedOutput(); + if (toys) { + // load coords from the nullDist globs list + if (toys->getGlobalObservables()) { + coords = std::shared_ptr(toys->getGlobalObservables()->snapshot()); + } + for (int i = 0; i < toys->numEntries(); i++) { + auto toy = toys->get(i); + nullToys.emplace_back( + std::make_tuple(int(toy->getRealValue("seed")), toy->getRealValue("ts"), toys->weight())); + } + } + toys = hypoTestResult->GetAltDetailedOutput(); + if (toys) { + for (int i = 0; i < toys->numEntries(); i++) { + auto toy = toys->get(i); + altToys.emplace_back( + std::make_tuple(int(toy->getRealValue("seed")), toy->getRealValue("ts"), toys->weight())); + } + } + } + if (!coords && _coords) + coords.reset(_coords->snapshot()); +} + std::shared_ptr xRooNLLVar::xRooHypoPoint::asimov(bool readOnly) { - if (!fAsimov && nllVar) { - if (!nllVar->fFuncVars) - nllVar->reinitialize(); - AutoRestorer snap(*nllVar->fFuncVars); - auto theFit = (!data.first && fGenFit) ? fGenFit : cfit_alt(readOnly); + if (!fAsimov && (nllVar || hypoTestResult)) { + auto theFit = (!fData.first && fGenFit && !isExpected) + ? fGenFit + : cfit_alt(readOnly); // first condition allows genFit to be used as the altFit *if* the data is + // entirely absent, provided not expected data because we postpone data + // creation til later in that case (see below) if (!theFit || allowedStatusCodes.find(theFit->status()) == allowedStatusCodes.end()) return fAsimov; - *nllVar->fFuncVars = theFit->floatParsFinal(); - *nllVar->fFuncVars = theFit->constPars(); - auto asimov = nllVar->generate(true); fAsimov = std::make_shared(*this); + fAsimov->coords.reset(fAsimov->coords->snapshot()); // create a copy so can remove the physical range below + fAsimov->hypoTestResult.reset(); fAsimov->fPllType = xRooFit::Asymptotics::TwoSided; - fAsimov->fUfit.reset(); - fAsimov->fNull_cfit.reset(); + for (auto p : fAsimov->poi()) + dynamic_cast(p)->removeRange("physical"); + fAsimov->nullToys.clear(); + fAsimov->altToys.clear(); + fAsimov->fUfit = retrieveFit(3); + fAsimov->fNull_cfit = retrieveFit(4); fAsimov->fAlt_cfit.reset(); - fAsimov->data = asimov; + fAsimov->fData = + std::make_pair(nullptr, nullptr); // postpone generating expected data until we definitely need it fAsimov->fGenFit = theFit; fAsimov->isExpected = true; } @@ -994,14 +1486,15 @@ std::pair xRooNLLVar::xRooHypoPoint::pNull_asymp(double nSigma) auto first_poi = dynamic_cast(poi().first()); if (!first_poi) return std::pair(std::numeric_limits::quiet_NaN(), 0); - double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fNullVal(), sigma_mu().first, + auto _sigma_mu = sigma_mu(); + double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fNullVal(), _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double up = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fNullVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double down = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fNullVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); return std::pair(nom, std::max(std::abs(up - nom), std::abs(down - nom))); } @@ -1012,15 +1505,15 @@ std::pair xRooNLLVar::xRooHypoPoint::pAlt_asymp(double nSigma) auto first_poi = dynamic_cast(poi().first()); if (!first_poi) return std::pair(std::numeric_limits::quiet_NaN(), 0); - - double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fAltVal(), sigma_mu().first, + auto _sigma_mu = sigma_mu(); + double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fAltVal(), _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double up = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fAltVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double down = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fAltVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); return std::pair(nom, std::max(std::abs(up - nom), std::abs(down - nom))); } @@ -1029,29 +1522,31 @@ std::pair xRooNLLVar::xRooHypoPoint::pCLs_asymp(double nSigma) { if (fNullVal() == fAltVal()) return std::pair(1, 0); // by construction + if (fPllType != xRooFit::Asymptotics::Uncapped && ts_asymp(nSigma).first == 0) return std::pair(1, 0); auto first_poi = dynamic_cast(poi().first()); if (!first_poi) return std::pair(std::numeric_limits::quiet_NaN(), 0); - double nom1 = - xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fNullVal(), sigma_mu().first, - first_poi->getMin("physical"), first_poi->getMax("physical")); + auto _ts_asymp = ts_asymp(nSigma); + auto _sigma_mu = sigma_mu(); + double nom1 = xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first, fNullVal(), fNullVal(), _sigma_mu.first, + first_poi->getMin("physical"), first_poi->getMax("physical")); double up1 = - xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fNullVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first + _ts_asymp.second, fNullVal(), fNullVal(), + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double down1 = - xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fNullVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); - double nom2 = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fAltVal(), sigma_mu().first, + xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first - _ts_asymp.second, fNullVal(), fNullVal(), + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); + double nom2 = xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first, fNullVal(), fAltVal(), _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double up2 = - xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fAltVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first + _ts_asymp.second, fNullVal(), fAltVal(), _sigma_mu.first, + first_poi->getMin("physical"), first_poi->getMax("physical")); double down2 = - xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fAltVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first - _ts_asymp.second, fNullVal(), fAltVal(), _sigma_mu.first, + first_poi->getMin("physical"), first_poi->getMax("physical")); auto nom = (nom1 == 0) ? 0 : nom1 / nom2; auto up = (up1 == 0) ? 0 : up1 / up2; @@ -1062,18 +1557,19 @@ std::pair xRooNLLVar::xRooHypoPoint::pCLs_asymp(double nSigma) std::pair xRooNLLVar::xRooHypoPoint::ts_asymp(double nSigma) { - auto first_poi = dynamic_cast(poi().first()); - if (!first_poi || (!std::isnan(nSigma) && std::isnan(sigma_mu().first))) - return std::pair(std::numeric_limits::quiet_NaN(), 0); if (std::isnan(nSigma)) return pll(); + auto first_poi = dynamic_cast(poi().first()); + auto _sigma_mu = sigma_mu(); + if (!first_poi || (!std::isnan(nSigma) && std::isnan(_sigma_mu.first))) + return std::pair(std::numeric_limits::quiet_NaN(), 0); double nom = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(), - sigma_mu().first, first_poi->getMin("physical"), first_poi->getMax("physical")); + _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical")); double up = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(), - sigma_mu().first + sigma_mu().second, first_poi->getMin("physical"), + _sigma_mu.first + _sigma_mu.second, first_poi->getMin("physical"), first_poi->getMax("physical")); double down = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(), - sigma_mu().first - sigma_mu().second, first_poi->getMin("physical"), + _sigma_mu.first - _sigma_mu.second, first_poi->getMin("physical"), first_poi->getMax("physical")); return std::pair(nom, std::max(std::abs(nom - up), std::abs(nom - down))); } @@ -1098,29 +1594,119 @@ std::pair xRooNLLVar::xRooHypoPoint::ts_toys(double nSigma) std::pair xRooNLLVar::xRooHypoPoint::pll(bool readOnly) { - if (!ufit(readOnly) || allowedStatusCodes.find(ufit(readOnly)->status()) == allowedStatusCodes.end()) + auto _ufit = ufit(readOnly); + if (!_ufit) { + if (hypoTestResult) + return std::make_pair(hypoTestResult->GetTestStatisticData(), 0); + return std::make_pair(std::numeric_limits::quiet_NaN(), 0); + } + if (allowedStatusCodes.find(_ufit->status()) == allowedStatusCodes.end()) { return std::make_pair(std::numeric_limits::quiet_NaN(), 0); - auto cFactor = xRooFit::Asymptotics::CompatFactor(fPllType, fNullVal(), mu_hat().getVal()); + } + if (auto _first_poi = dynamic_cast(poi().first()); + _first_poi && _first_poi->hasMin("physical") && mu_hat().getVal() < _first_poi->getMin("physical")) { + // replace _ufit with fit "boundary" conditional fit + _ufit = cfit_lbound(readOnly); + if (!_ufit) { + return std::make_pair(std::numeric_limits::quiet_NaN(), 0); + } + } + auto cFactor = (fPllType == xRooFit::Asymptotics::TwoSided) + ? 1. + : xRooFit::Asymptotics::CompatFactor(fPllType, fNullVal(), mu_hat().getVal()); if (cFactor == 0) return std::make_pair(0, 0); if (!cfit_null(readOnly) || allowedStatusCodes.find(cfit_null(readOnly)->status()) == allowedStatusCodes.end()) return std::make_pair(std::numeric_limits::quiet_NaN(), 0); // std::cout << cfit->minNll() << ":" << cfit->edm() << " " << ufit->minNll() << ":" << ufit->edm() << std::endl; - return std::make_pair(2. * cFactor * (cfit_null(readOnly)->minNll() - ufit(readOnly)->minNll()), - 2. * cFactor * sqrt(pow(cfit_null(readOnly)->edm(), 2) + pow(ufit(readOnly)->edm(), 2))); + return std::make_pair(2. * cFactor * (cfit_null(readOnly)->minNll() - _ufit->minNll()), + 2. * cFactor * sqrt(pow(cfit_null(readOnly)->edm(), 2) + pow(_ufit->edm(), 2))); // return 2.*cFactor*(cfit->minNll()+cfit->edm() - ufit->minNll()+ufit->edm()); } +std::shared_ptr xRooNLLVar::xRooHypoPoint::retrieveFit(int type) +{ + if (!hypoTestResult) + return nullptr; + // see if can retrieve from that .... + if (auto fits = hypoTestResult->GetFitInfo()) { + for (int i = 0; i < fits->numEntries(); i++) { + auto fit = fits->get(i); + if (fit->getCatIndex("type") != type) + continue; + // found ufit ... construct + std::string _name = + fits->getGlobalObservables()->getStringValue(TString::Format("%s.name", fit->getCatLabel("type"))); + // see if can retrieve from any open file .... + TDirectory *tmp = gDirectory; + for (auto file : *gROOT->GetListOfFiles()) { + if (auto k = static_cast(file)->FindKeyAny(_name.c_str())) { + // use pre-retrieved fits if available + xRooFit::StoredFitResult *storedFr = + k->GetMotherDir()->GetList() + ? dynamic_cast(k->GetMotherDir()->GetList()->FindObject(k->GetName())) + : nullptr; + if (auto cachedFit = (storedFr) ? storedFr->fr.get() : k->ReadObject(); cachedFit) { + if (!storedFr) { + storedFr = new xRooFit::StoredFitResult(cachedFit); + k->GetMotherDir()->Add(storedFr); + } + gDirectory = tmp; // one of the above calls moves to key's directory ... i didn't check which + return storedFr->fr; + } + } + } + auto rfit = std::make_shared(_name.c_str(), TUUID(_name.c_str()).GetTime().AsString()); + rfit->setStatus(fit->getRealValue("status")); + rfit->setMinNLL(fit->getRealValue("minNll")); + rfit->setEDM(fit->getRealValue("edm")); + if (type == 0) { + std::unique_ptr par_hats( + hypoTestResult->GetFitInfo()->getGlobalObservables()->selectByName(coords->contentsString().c_str())); + par_hats->setName("floatParsFinal"); + rfit->setFinalParList(*par_hats); + } else { + rfit->setFinalParList(RooArgList()); + } + rfit->setConstParList(RooArgList()); + rfit->setInitParList(RooArgList()); + TMatrixDSym cov(0); + rfit->setCovarianceMatrix(cov); + return rfit; + } + } + return nullptr; +} + std::shared_ptr xRooNLLVar::xRooHypoPoint::ufit(bool readOnly) { if (fUfit) return fUfit; + if (auto rfit = retrieveFit(0)) { + return fUfit = rfit; + } if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly"))) return nullptr; if (!nllVar->fFuncVars) nllVar->reinitialize(); AutoRestorer snap(*nllVar->fFuncVars, nllVar.get()); - nllVar->setData(data); + if (!fData.first) { + if (!readOnly && isExpected && fGenFit) { + // can try to do a readOnly in case can load from cache + bool tmp = nllVar->get()->getAttribute("readOnly"); + nllVar->get()->setAttribute("readOnly"); + auto out = ufit(true); + nllVar->get()->setAttribute("readOnly", tmp); + if (out) { + // retrieve from cache worked, no need to generate dataset + return out; + } else if (!tmp) { // don't need to setData if doing a readOnly fit + nllVar->setData(data()); + } + } + } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit + nllVar->setData(fData); + } nllVar->fFuncVars->setAttribAll("Constant", false); *nllVar->fFuncVars = *coords; // will reconst the coords if (nllVar->fFuncGlobs) @@ -1134,6 +1720,9 @@ std::shared_ptr xRooNLLVar::xRooHypoPoint::ufit(bool readOnl // rename nll so if caching fit results will cache into subdir nllVar->get()->SetName( TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys")); + if (!isExpected) + nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName())); + } else if (!std::isnan(fAltVal())) { // guess data given is expected to align with alt value nllVar->fFuncVars->setRealValue(fPOIName(), fAltVal()); @@ -1162,12 +1751,31 @@ std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_null(bool re { if (fNull_cfit) return fNull_cfit; + if (auto rfit = retrieveFit(1)) { + return fNull_cfit = rfit; + } if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly"))) return nullptr; if (!nllVar->fFuncVars) nllVar->reinitialize(); AutoRestorer snap(*nllVar->fFuncVars, nllVar.get()); - nllVar->setData(data); + if (!fData.first) { + if (!readOnly && isExpected && fGenFit) { + // can try to do a readOnly in case can load from cache + bool tmp = nllVar->get()->getAttribute("readOnly"); + nllVar->get()->setAttribute("readOnly"); + auto out = cfit_null(true); + nllVar->get()->setAttribute("readOnly", tmp); + if (out) { + // retrieve from cache worked, no need to generate dataset + return out; + } else if (!tmp) { // don't need to setData if doing a readOnly fit + nllVar->setData(data()); + } + } + } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit + nllVar->setData(fData); + } if (fUfit) { // move to ufit coords before evaluating *nllVar->fFuncVars = fUfit->floatParsFinal(); @@ -1176,27 +1784,108 @@ std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_null(bool re *nllVar->fFuncVars = *coords; // will reconst the coords if (nllVar->fFuncGlobs) nllVar->fFuncGlobs->setAttribAll("Constant", true); - nllVar->fFuncVars->find(fPOIName()) - ->setStringAttribute("altVal", (!std::isnan(fAltVal())) ? TString::Format("%g", fAltVal()) : nullptr); - if (fGenFit) + if (fPOIName()) + nllVar->fFuncVars->find(fPOIName()) + ->setStringAttribute("altVal", (!std::isnan(fAltVal())) ? TString::Format("%g", fAltVal()) : nullptr); + if (fGenFit) { nllVar->get()->SetName( TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys")); + if (!isExpected) + nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName())); + } nllVar->get()->setStringAttribute("fitresultTitle", collectionContents(poi()).c_str()); return (fNull_cfit = nllVar->minimize()); } +std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_lbound(bool readOnly) +{ + auto _first_poi = dynamic_cast(poi().first()); + if (!_first_poi) + return nullptr; + if (!_first_poi->hasMin("physical")) + return nullptr; + if (fLbound_cfit) + return fLbound_cfit; + if (auto rfit = retrieveFit(6)) { + return fLbound_cfit = rfit; + } + if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly"))) + return nullptr; + if (!nllVar->fFuncVars) + nllVar->reinitialize(); + AutoRestorer snap(*nllVar->fFuncVars, nllVar.get()); + if (!fData.first) { + if (!readOnly && isExpected && fGenFit) { + // can try to do a readOnly in case can load from cache + bool tmp = nllVar->get()->getAttribute("readOnly"); + nllVar->get()->setAttribute("readOnly"); + auto out = cfit_lbound(true); + nllVar->get()->setAttribute("readOnly", tmp); + if (out) { + // retrieve from cache worked, no need to generate dataset + return out; + } else if (!tmp) { // don't need to setData if doing a readOnly fit + nllVar->setData(data()); + } + } + } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit + nllVar->setData(fData); + } + if (fUfit) { + // move to ufit coords before evaluating + *nllVar->fFuncVars = fUfit->floatParsFinal(); + } + nllVar->fFuncVars->setAttribAll("Constant", false); + *nllVar->fFuncVars = *coords; // will reconst the coords + nllVar->fFuncVars->setRealValue(_first_poi->GetName(), _first_poi->getMin("physical")); + if (nllVar->fFuncGlobs) + nllVar->fFuncGlobs->setAttribAll("Constant", true); + if (fPOIName()) + nllVar->fFuncVars->find(fPOIName()) + ->setStringAttribute("altVal", (!std::isnan(fAltVal())) ? TString::Format("%g", fAltVal()) : nullptr); + if (fGenFit) { + nllVar->get()->SetName( + TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys")); + if (!isExpected) + nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName())); + } + nllVar->get()->setStringAttribute( + "fitresultTitle", + collectionContents(*std::unique_ptr(nllVar->fFuncVars->selectCommon(poi()))).c_str()); + return (fLbound_cfit = nllVar->minimize()); +} + std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_alt(bool readOnly) { if (std::isnan(fAltVal())) return nullptr; if (fAlt_cfit) return fAlt_cfit; + if (auto rfit = retrieveFit(2)) { + return fAlt_cfit = rfit; + } if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly"))) return nullptr; if (!nllVar->fFuncVars) nllVar->reinitialize(); AutoRestorer snap(*nllVar->fFuncVars, nllVar.get()); - nllVar->setData(data); + if (!fData.first) { + if (!readOnly && isExpected && fGenFit) { + // can try to do a readOnly in case can load from cache + bool tmp = nllVar->get()->getAttribute("readOnly"); + nllVar->get()->setAttribute("readOnly"); + auto out = cfit_alt(true); + nllVar->get()->setAttribute("readOnly", tmp); + if (out) { + // retrieve from cache worked, no need to generate dataset + return out; + } else if (!tmp) { // don't need to setData if doing a readOnly fit + nllVar->setData(data()); + } + } + } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit + nllVar->setData(fData); + } if (fUfit) { // move to ufit coords before evaluating *nllVar->fFuncVars = fUfit->floatParsFinal(); @@ -1206,9 +1895,12 @@ std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_alt(bool rea if (nllVar->fFuncGlobs) nllVar->fFuncGlobs->setAttribAll("Constant", true); *nllVar->fFuncVars = alt_poi(); - if (fGenFit) + if (fGenFit) { nllVar->get()->SetName( TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys")); + if (!isExpected) + nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName())); + } nllVar->get()->setStringAttribute("fitresultTitle", collectionContents(alt_poi()).c_str()); return (fAlt_cfit = nllVar->minimize()); } @@ -1216,11 +1908,13 @@ std::shared_ptr xRooNLLVar::xRooHypoPoint::cfit_alt(bool rea std::pair xRooNLLVar::xRooHypoPoint::sigma_mu(bool readOnly) { - if (!asimov(readOnly)) { + auto asi = asimov(readOnly); + + if (!asi) { return std::make_pair(std::numeric_limits::quiet_NaN(), 0); } - auto out = asimov(readOnly)->pll(readOnly); + auto out = asi->pll(readOnly); return std::make_pair(std::abs(fNullVal() - fAltVal()) / sqrt(out.first), out.second * 0.5 * std::abs(fNullVal() - fAltVal()) / (out.first * sqrt(out.first))); } @@ -1230,11 +1924,17 @@ std::pair xRooNLLVar::xRooHypoPoint::pX_toys(bool alt, double nS auto _ts = ts_toys(nSigma); if (std::isnan(_ts.first)) return _ts; + if (fPllType != xRooFit::Asymptotics::Uncapped && _ts.first == 0) + return std::pair(1, 0); // don't need toys to compute this point! TEfficiency eff("", "", 1, 0, 1); auto &_theToys = (alt) ? altToys : nullToys; + if (_theToys.empty()) { + return std::pair(0.5, std::numeric_limits::infinity()); + } + // loop over toys, count how many are > ts value // nans (mean bad ts evaluations) will count towards uncertainty int nans = 0; @@ -1281,6 +1981,9 @@ std::pair xRooNLLVar::xRooHypoPoint::pNull_toys(double nSigma) std::pair xRooNLLVar::xRooHypoPoint::pAlt_toys(double nSigma) { + if (!std::isnan(nSigma)) { + return std::pair(ROOT::Math::gaussian_cdf(nSigma), 0); // by construction + } return pX_toys(true, nSigma); } @@ -1292,14 +1995,15 @@ xRooNLLVar::xRooHypoPoint xRooNLLVar::xRooHypoPoint::generateNull(int seed) out.nllVar = nllVar; if (!nllVar) return out; - if (!cfit_null()) + auto _cfit = cfit_null(); + if (!_cfit) return out; if (!nllVar->fFuncVars) nllVar->reinitialize(); //*nllVar->fFuncVars = cfit_null()->floatParsFinal(); //*nllVar->fFuncVars = cfit_null()->constPars(); - out.data = xRooFit::generateFrom(*nllVar->fPdf, cfit_null(), false, seed); // nllVar->generate(false,seed); - out.fGenFit = cfit_null(); + out.fData = xRooFit::generateFrom(*nllVar->fPdf, *_cfit, false, seed); // nllVar->generate(false,seed); + out.fGenFit = _cfit; return out; } @@ -1317,93 +2021,245 @@ xRooNLLVar::xRooHypoPoint xRooNLLVar::xRooHypoPoint::generateAlt(int seed) nllVar->reinitialize(); //*nllVar->fFuncVars = cfit_alt()->floatParsFinal(); //*nllVar->fFuncVars = cfit_alt()->constPars(); - out.data = xRooFit::generateFrom(*nllVar->fPdf, cfit_alt(), false, seed); // out.data = nllVar->generate(false,seed); + out.fData = + xRooFit::generateFrom(*nllVar->fPdf, *cfit_alt(), false, seed); // out.data = nllVar->generate(false,seed); out.fGenFit = cfit_alt(); return out; } -void xRooNLLVar::xRooHypoPoint::addToys(bool alt, int nToys, int initialSeed) +size_t xRooNLLVar::xRooHypoPoint::addToys(bool alt, int nToys, int initialSeed, double target, double target_nSigma, + bool targetCLs, double relErrThreshold, size_t maxToys) { if ((alt && !cfit_alt()) || (!alt && !cfit_null())) { throw std::runtime_error("Cannot add toys, invalid conditional fit"); } - auto &toys = (alt) ? altToys : nullToys; - int nans = 0; - std::vector times(nToys); + + auto condition = [&]() { // returns true if need more toys + if (std::isnan(target)) + return false; + auto obs = targetCLs ? pCLs_toys(target_nSigma) : (alt ? pAlt_toys(target_nSigma) : pNull_toys(target_nSigma)); + if (!std::isnan(obs.first)) { + double diff = (target < 0) ? obs.first : std::abs(obs.first - target); + double err = obs.second; + if (err > 1e-4 && diff <= relErrThreshold * obs.second) { + // return true; // more toys needed + if (targetCLs) { + // decide which type we'd want to generate and update alt flag + auto pNull = pNull_toys(target_nSigma); + auto pAlt = pAlt_toys(target_nSigma); + // std::cout << obs.first << " +/- " << obs.second << ": " << pNull.first << " +/- " << pNull.second << " + // , " << pAlt.first << " +/- " << pAlt.second << std::endl; + alt = (pAlt.second * pNull.first > pNull.second * pAlt.first); + if ((alt ? pAlt.second : pNull.second) < 1e-4) + return false; // stop if error gets too small + } + return true; + } + } + return false; + }; + + if (!std::isnan(target) && std::isnan(ts_toys(target_nSigma).first)) { + if (std::isnan(target_nSigma)) { + throw std::runtime_error("Cannot target obs p-value because ts value unavailable"); + } + if (targetCLs && pCLs_toys(target_nSigma).second == 0) { + // this happens if the mu_test=mu_alt ... no toys needed + return 0; + } + + // try generating 100 alt toys + Info("addToys", "First generating 100 alt toys in order to determine expected ts value"); + addToys(true, 100, initialSeed); + // if still null then exit + if (std::isnan(ts_toys(target_nSigma).first)) { + throw std::runtime_error("Unable to determine expected ts value"); + } + } + + size_t nans = 0; float lastTime = 0; - int lasti = -1; + int lasti = 0; + auto g = gROOT->Get("toyTime"); + if (!g) { + g = new TGraph; + g->SetNameTitle("toyTime", "Time per toy;Toy;time [s]"); + gROOT->Add(g); + } + g->Set(0); TStopwatch s2; s2.Start(); TStopwatch s; s.Start(); - for (auto i = 0; i < nToys; i++) { - if (i == 0 && initialSeed != 0) - RooRandom::randomGenerator()->SetSeed(initialSeed); - int seed = RooRandom::randomGenerator()->Integer(std::numeric_limits::max()); - toys.push_back(std::make_tuple(seed, ((alt) ? generateAlt(seed) : generateNull(seed)).pll().first, 1.)); - if (std::isnan(std::get<1>(toys.back()))) - nans++; - times[i] = s.RealTime() - lastTime; // stops the clock - lastTime = s.RealTime(); - if (s.RealTime() > 10) { - std::cout << "\r" - << TString::Format("Generated %d/%d %s hypothesis toys [%.2f toys/s]...", i + 1, nToys, - alt ? "alt" : "null", double(i - lasti) / s.RealTime()) - << std::flush; - lasti = i; - s.Reset(); - s.Start(); - // std::cout << "Generated " << i << "/" << nToys << (alt ? " alt " : " null ") << " hypothesis toys " ..." << - // std::endl; - } - s.Continue(); - } - if (lasti) + + size_t toysAdded(0); + size_t altToysAdded(0); + if (initialSeed) { + RooRandom::randomGenerator()->SetSeed(initialSeed); + } + do { + auto &toys = (alt) ? altToys : nullToys; + if (toys.size() >= maxToys) { + // cannot generate more toys, reached limit already + break; + } + // don't generate toys if reached target + if (!std::isnan(target) && !condition()) { + break; + } + auto currVal = std::isnan(target) ? std::pair(0., 0.) + : (targetCLs ? pCLs_toys(target_nSigma) + : (alt ? pAlt_toys(target_nSigma) : pNull_toys(target_nSigma))); + size_t nnToys = std::min(size_t(nToys), (maxToys - toys.size())); + + for (size_t i = 0; i < nnToys; i++) { + int seed = RooRandom::randomGenerator()->Integer(std::numeric_limits::max()); + auto toy = ((alt) ? generateAlt(seed) : generateNull(seed)); + TDirectory *tmp = gDirectory; + gDirectory = nullptr; // disables any saving of fit results for toys + toys.push_back(std::make_tuple(seed, toy.pll().first, 1.)); + gDirectory = tmp; + (alt ? altToysAdded : toysAdded)++; + if (std::isnan(std::get<1>(toys.back()))) + nans++; + g->SetPoint(g->GetN(), g->GetN(), s.RealTime() - lastTime); // stops the clock + lastTime = s.RealTime(); + if (s.RealTime() > 10) { + std::cout << "\r" + << TString::Format("Generated %d/%d %s hypothesis toys [%.2f toys/s]", + int(alt ? altToysAdded : toysAdded), int(nnToys), alt ? "alt" : "null", + double(altToysAdded + toysAdded - lasti) / s.RealTime()); + if (!std::isnan(target)) { + std::cout << " [current=" << currVal.first << "+/-" << currVal.second << " target=" << target + << " nSigma=" << target_nSigma << "]"; + } + std::cout << "..." << std::flush; + lasti = altToysAdded + toysAdded; + s.Reset(); + Draw(); + if (gPad) { + gPad->Update(); + gSystem->ProcessEvents(); + } + s.Start(); + // std::cout << "Generated " << i << "/" << nToys << (alt ? " alt " : " null ") << " hypothesis toys " ..." + // << std::endl; + } + s.Continue(); + } + // sort the toys ... put nans first - do by setting all as negative inf (is that still necessary with the custom + // sort below??) + for (auto &t : toys) { + if (std::isnan(std::get<1>(t))) + std::get<1>(t) = -std::numeric_limits::infinity(); + } + std::sort(toys.begin(), toys.end(), + [](const decltype(nullToys)::value_type &a, const decltype(nullToys)::value_type &b) -> bool { + if (std::isnan(std::get<1>(a))) + return true; + if (std::isnan(std::get<1>(b))) + return false; + return std::get<1>(a) < std::get<1>(b); + }); + for (auto &t : toys) { + if (std::isinf(std::get<1>(t))) + std::get<1>(t) = std::numeric_limits::quiet_NaN(); + } + if (std::isnan(target)) { + break; // no more toys if not doing a target + } + // if(condition()) { + // Info("addToys","Generating more toys to determine p-value ... currently: %f +/- + // %f",pNull_toys(target_nSigma).first,pNull_toys(target_nSigma).second); + // } + } while (condition()); + if (lasti) { std::cout << "\r" - << TString::Format("Generated %d/%d %s hypothesis toys [%.2f toys/s overall]...Done!", nToys, nToys, - alt ? "alt" : "null", double(nToys) / s2.RealTime()) + << "Finished Generating "; + if (toysAdded) { + std::cout << toysAdded << " null "; + } + if (altToysAdded) { + std::cout << altToysAdded << " alt "; + } + std::cout << "toys " << TString::Format("[%.2f toys/s overall]", double(toysAdded + altToysAdded) / s2.RealTime()) << std::endl; - auto g = gDirectory->Get("toyTime"); - if (!g) { - g = new TGraph; - g->SetNameTitle("toyTime", "Time per toy;Toy;time [s]"); - gDirectory->Add(g); - } - g->Set(times.size()); - for (size_t i = 0; i < times.size(); i++) - g->SetPoint(i, i, times[i]); - // sort the toys ... put nans first - do by setting all as negative inf - for (auto &t : toys) { - if (std::isnan(std::get<1>(t))) - std::get<1>(t) = -std::numeric_limits::infinity(); - } - std::sort(toys.begin(), toys.end(), - [](const decltype(nullToys)::value_type &a, const decltype(nullToys)::value_type &b) -> bool { - if (std::isnan(std::get<1>(a))) - return true; - if (std::isnan(std::get<1>(b))) - return false; - return std::get<1>(a) < std::get<1>(b); - }); - for (auto &t : toys) { - if (std::isinf(std::get<1>(t))) - std::get<1>(t) = std::numeric_limits::quiet_NaN(); - } - if (nans > 0) + Draw(); + if (gPad) { + gPad->Update(); + gSystem->ProcessEvents(); + } + } + + if (nans > 0) { std::cout << "Warning: " << nans << " toys were bad" << std::endl; + } + return toysAdded; } -void xRooNLLVar::xRooHypoPoint::addNullToys(int nToys, int seed) +void xRooNLLVar::xRooHypoPoint::addNullToys(int nToys, int seed, double target, double target_nSigma) { - addToys(false, nToys, seed); + addToys(false, nToys, seed, target, target_nSigma); } -void xRooNLLVar::xRooHypoPoint::addAltToys(int nToys, int seed) +void xRooNLLVar::xRooHypoPoint::addAltToys(int nToys, int seed, double target, double target_nSigma) { - addToys(true, nToys, seed); + addToys(true, nToys, seed, target, target_nSigma); +} + +void xRooNLLVar::xRooHypoPoint::addCLsToys(int nToys, int seed, double target, double target_nSigma) +{ + addToys(false, nToys, seed, target, target_nSigma, true); + return; + // + // auto condition = [&](bool doingAlt=false) { // returns true if need more toys + // if(std::isnan(target)) return false; + // auto pval = pCLs_toys(target_nSigma); + // if (!std::isnan(pval.first)) { + // double diff = std::abs(pval.first - target); + // double err = pval.second; + // if (err > 1e-4 && diff <= 2 * pval.second) { + // return true; // more toys needed + // // decide which type we'd want to generate + // // if it matches the type we are generating, then return true + // auto pNull = pNull_toys(target_nSigma); + // auto pAlt = pAlt_toys(target_nSigma); + // if ((doingAlt ? pAlt.second : pNull.second) < 1e-4) return false; // stop if error gets too small + // bool doAlt = (pAlt.second * pNull.first > pNull.second * pAlt.first); + // return doAlt == doingAlt; + // } + // } + // return false; + // }; + // while(condition()) { + // bool doAlt = false; + // double relErrThreshold = 2; + // if(nullToys.size() pNull.second*pAlt.first); + // if( (doAlt ? pAlt.second : pNull.second) < 1e-4 ) break; // stop if error gets too small + // auto pCLs = pCLs_toys(target_nSigma); + // relErrThreshold = (doAlt) ? (pNull.second/pNull.first) : (pAlt.second/pAlt.first); + // relErrThreshold = std::min(2.,std::abs(relErrThreshold)); + // std::cout << "Current pCLs = " << pCLs.first << " +/- " << pCLs.second + // << " (pNull = " << pNull.first << " +/- " << pNull.second + // << " , pAlt = " << pAlt.first << " +/- " << pAlt.second << ") ... generating more " << (doAlt ? + // "alt" : "null") << " toys " << relErrThreshold << std::endl; + // + // } + // if( addToys(doAlt, nToys/*, seed, -1, target_nSigma,relErrThreshold*/) == 0) { + // break; // no toys got added, so stop looping + // } + // } } xRooNLLVar::xRooHypoPoint -xRooNLLVar::hypoPoint(const char *parName, double value, double alt_value, const xRooFit::Asymptotics::PLLType &pllType) +xRooNLLVar::hypoPoint(const char *poiValues, double alt_value, const xRooFit::Asymptotics::PLLType &pllType) { xRooHypoPoint out; // out.fPOIName = parName; out.fNullVal = value; out.fAltVal = alt_value; @@ -1411,22 +2267,58 @@ xRooNLLVar::hypoPoint(const char *parName, double value, double alt_value, const if (!fFuncVars) { reinitialize(); } + AutoRestorer snap(*fFuncVars); out.nllVar = std::make_shared(*this); - out.data = getData(); + out.fData = getData(); - auto poi = dynamic_cast(fFuncVars->find(parName)); - if (!poi) - return out; - AutoRestorer snap((RooArgSet(*poi))); - poi->setVal(value); - poi->setConstant(); + TStringToken pattern(poiValues, ","); + TString poiNames; + while (pattern.NextToken()) { + TString s = pattern.Data(); + TString cName = s; + double val = std::numeric_limits::quiet_NaN(); + auto i = s.Index("="); + if (i != -1) { + cName = s(0, i); + TString cVal = s(i + 1, s.Length()); + if (!cVal.IsFloat()) + throw std::runtime_error("poiValues must contain value"); + val = cVal.Atof(); + } + auto v = dynamic_cast(fFuncVars->find(cName)); + if (!v) + throw std::runtime_error("Cannot find poi"); + if (!std::isnan(val)) + v->setVal(val); + v->setConstant(); // because will select constants as coords + if (poiNames != "") { + poiNames += ","; + } + poiNames += cName; + } + if (poiNames == "") { + throw std::runtime_error("No poi"); + } + if (!std::isnan(alt_value)) { + std::unique_ptr thePoi(fFuncVars->selectByName(poiNames)); + for (auto b : *thePoi) { + if (!static_cast(b)->hasRange("physical")) { + static_cast(b)->setRange("physical", 0, std::numeric_limits::infinity()); + } + } + } auto _snap = std::unique_ptr(fFuncVars->selectByAttrib("Constant", true))->snapshot(); - _snap->find(poi->GetName())->setAttribute("poi", true); - if (std::isnan(alt_value)) - _snap->find(poi->GetName())->setStringAttribute("altVal", nullptr); - else - _snap->find(poi->GetName())->setStringAttribute("altVal", TString::Format("%g", alt_value)); + _snap->setAttribAll("poi", false); + std::unique_ptr _poi(_snap->selectByName(poiNames)); + _poi->setAttribAll("poi", true); + if (std::isnan(alt_value)) { + for (auto a : *_poi) + a->setStringAttribute("altVal", nullptr); + } else { + for (auto a : *_poi) + a->setStringAttribute("altVal", TString::Format("%g", alt_value)); + } if (fGlobs) _snap->remove(*fGlobs, true, true); out.coords.reset(_snap); @@ -1436,7 +2328,7 @@ xRooNLLVar::hypoPoint(const char *parName, double value, double alt_value, const // decide based on values if (std::isnan(alt_value)) _type = xRooFit::Asymptotics::TwoSided; - else if (value >= alt_value) + else if (dynamic_cast(_poi->first())->getVal() >= alt_value) _type = xRooFit::Asymptotics::OneSidedPositive; else _type = xRooFit::Asymptotics::Uncapped; @@ -1462,10 +2354,16 @@ xRooNLLVar::hypoPoint(double value, double alt_value, const xRooFit::Asymptotics return hypoPoint(_poi->first()->GetName(), value, alt_value, pllType); } +xRooNLLVar::xRooHypoPoint +xRooNLLVar::hypoPoint(const char *parName, double value, double alt_value, const xRooFit::Asymptotics::PLLType &pllType) +{ + return hypoPoint(TString::Format("%s=%f", parName, value), alt_value, pllType); +} + void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) { - if (!nllVar) + if (!nllVar && !hypoTestResult) return; TString sOpt(opt); @@ -1495,7 +2393,7 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) clearPad(); } else { // get the histogram representing the axes - hAxis = dynamic_cast(pad->GetPrimitive("axis")); + hAxis = dynamic_cast(pad->GetPrimitive(".axis")); if (!hAxis) { for (auto o : *pad->GetListOfPrimitives()) { if (hAxis = dynamic_cast(o); hAxis) @@ -1527,16 +2425,21 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) auto obs = pll(); if (!std::isnan(obs.first)) { - _min = std::min(obs.first - abs(obs.first) * 0.1, _min); - _max = std::max(obs.first + abs(obs.first) * 0.1, _max); + _min = std::min(obs.first - std::abs(obs.first) * 0.1, _min); + _max = std::max(obs.first + std::abs(obs.first) * 0.1, _max); } - + // these are used down below to add obs p-values to legend, but up here because can trigger fits that create asimov + auto pNull = pNull_toys(); + auto pAlt = pAlt_toys(); + auto pNullA = pNull_asymp(); + auto pAltA = pAlt_asymp(); + sigma_mu(true); auto asi = (fAsimov && fAsimov->fUfit && fAsimov->fNull_cfit) ? fAsimov->pll().first : std::numeric_limits::quiet_NaN(); if (!std::isnan(asi) && asi > 0 && fPllType != xRooFit::Asymptotics::Unknown) { // can calculate asymptotic distributions, - _min = std::min(asi - abs(asi), _min); - _max = std::max(asi + abs(asi), _max); + _min = std::min(asi - std::abs(asi), _min); + _max = std::max(asi + std::abs(asi), _max); } if (_min > 0) _min = 0; @@ -1569,10 +2472,11 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) // } // } // } - title += TString::Format("%s' = %g", fPOIName(), (isAlt) ? fAltVal() : fNullVal()); - title += TString::Format(" , N_{toys}=%lu", (isAlt) ? altToys.size() : nullToys.size()); + if (fPOIName()) + title += TString::Format("%s' = %g", fPOIName(), (isAlt) ? fAltVal() : fNullVal()); + title += TString::Format(" , N_{toys}=%d", int((isAlt) ? altToys.size() : nullToys.size())); if (nBadOrZero > 0) - title += TString::Format(" (N_{bad/0}=%lu)", nBadOrZero); + title += TString::Format(" (N_{bad/0}=%d)", int(nBadOrZero)); title += ";"; title += tsTitle(); title += TString::Format(";Probability Mass"); @@ -1588,16 +2492,19 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) auto altHist = makeHist(true); TLegend *l = nullptr; - auto h = nullHist; + auto h = (nullHist->GetEntries()) ? nullHist : altHist; if (!hasSame) { gPad->SetLogy(); - auto axis = (TH1 *)h->Clone(".axis"); + auto axis = static_cast(h->Clone(".axis")); + axis->SetBit(kCanDelete); + axis->SetStats(false); axis->Reset("ICES"); - axis->SetMinimum(1e-7); - axis->SetMaximum(h->GetMaximum()); - axis->SetTitle(TString::Format("HypoPoint")); + axis->SetTitle(TString::Format("%s HypoPoint", collectionContents(poi()).c_str())); axis->SetLineWidth(0); axis->Draw(""); // h->Draw("axis"); cant use axis option if want title drawn + axis->SetMinimum(1e-7); + axis->GetYaxis()->SetRangeUser(1e-7, 10); + axis->SetMaximum(h->GetMaximum()); hAxis = axis; l = new TLegend(0.4, 0.7, 1. - gPad->GetRightMargin(), 1. - gPad->GetTopMargin()); l->SetName("legend"); @@ -1614,12 +2521,12 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) } if (h->GetEntries() > 0) - h->Draw("histesame"); + h->Draw("esame"); else h->Draw("axissame"); // for unknown reason if second histogram empty it still draws with two weird bars??? h = altHist; if (h->GetEntries() > 0) - h->Draw("histesame"); + h->Draw("esame"); else h->Draw("axissame"); // for unknown reason if second histogram empty it still draws with two weird bars??? @@ -1629,7 +2536,9 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) } if (fAsimov && fAsimov->fUfit && fAsimov->fNull_cfit && !std::isnan(sigma_mu().first) && !std::isnan(fAltVal())) { - auto hh = (TH1 *)nullHist->Clone("null_asymp"); + auto hh = static_cast(nullHist->Clone("null_asymp")); + hh->SetBit(kCanDelete); + hh->SetStats(false); hh->SetLineStyle(2); hh->Reset(); for (int i = 1; i <= hh->GetNbinsX(); i++) { @@ -1640,7 +2549,9 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) sigma_mu().first, _poi->getMin("physical"), _poi->getMax("physical"))); } hh->Draw("lsame"); - hh = (TH1 *)altHist->Clone("alt_asymp"); + hh = static_cast(altHist->Clone("alt_asymp")); + hh->SetBit(kCanDelete); + hh->SetStats(false); hh->SetLineStyle(2); hh->Reset(); for (int i = 1; i <= hh->GetNbinsX(); i++) { @@ -1655,17 +2566,13 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) // draw observed points TLine ll; - ll.SetLineStyle(2); + ll.SetLineStyle(1); + ll.SetLineWidth(3); // for(auto p : fObs) { - auto tl = ll.DrawLine(pll().first, hAxis->GetMinimum(), pll().first, 0.1); - auto label = TString::Format("obs ts = %.4f", pll().first); - if (pll().second) - label += TString::Format(" #pm %.4f", pll().second); - auto pNull = pNull_toys(); - auto pAlt = pAlt_toys(); - - auto pNullA = pNull_asymp(); - auto pAltA = pAlt_asymp(); + auto tl = ll.DrawLine(obs.first, hAxis->GetMinimum(), obs.first, 0.1); + auto label = TString::Format("obs ts = %.4f", obs.first); + if (obs.second) + label += TString::Format(" #pm %.4f", obs.second); l->AddEntry(tl, label, "l"); label = ""; @@ -1674,7 +2581,7 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) label += " p_{toy}=("; label += (std::isnan(pNull.first)) ? "-" : TString::Format("%.4f #pm %.4f", pNull.first, pNull.second); label += (std::isnan(pAlt.first)) ? ",-" : TString::Format(",%.4f #pm %.4f", pAlt.first, pAlt.second); - label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f", pCLs.first, pCLs.second); + label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f)", pCLs.first, pCLs.second); } if (label.Length() > 0) l->AddEntry("", label, ""); @@ -1684,43 +2591,52 @@ void xRooNLLVar::xRooHypoPoint::Draw(Option_t *opt) label += " p_{asymp}=("; label += (std::isnan(pNullA.first)) ? "-" : TString::Format("%.4f #pm %.4f", pNullA.first, pNullA.second); label += (std::isnan(pAltA.first)) ? ",-" : TString::Format(",%.4f #pm %.4f", pAltA.first, pAltA.second); - label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f", pCLs.first, pCLs.second); + label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f)", pCLs.first, pCLs.second); } if (label.Length() > 0) l->AddEntry("", label, ""); - //} + if (auto ax = dynamic_cast(gPad->GetPrimitive(".axis"))) + ax->GetYaxis()->SetRangeUser(1e-7, 1); } -TString xRooNLLVar::xRooHypoPoint::tsTitle() +TString xRooNLLVar::xRooHypoPoint::tsTitle(bool inWords) const { auto v = dynamic_cast(poi().empty() ? nullptr : poi().first()); if (fPllType == xRooFit::Asymptotics::OneSidedPositive) { if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - return TString::Format("#tilde{q}_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("Lower-Bound One-Sided Limit PLR") + : TString::Format("#tilde{q}_{%s=%g}", v->GetTitle(), v->getVal()); else if (v) - return TString::Format("q_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("One-Sided Limit PLR") + : TString::Format("q_{%s=%g}", v->GetTitle(), v->getVal()); else return "q"; } else if (fPllType == xRooFit::Asymptotics::TwoSided) { if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - return TString::Format("#tilde{t}_{%s=%g}", v->GetTitle(), v->getVal()); - else if (v) - return TString::Format("t_{%s=%g}", v->GetTitle(), v->getVal()); - else + return (inWords) ? TString::Format("Lower-Bound PLR") + : TString::Format("#tilde{t}_{%s=%g}", v->GetTitle(), v->getVal()); + else if (v) { + return (inWords) ? TString::Format("-2log[L(%s,#hat{#hat{#theta}})/L(#hat{%s},#hat{#theta})]", v->GetTitle(), + v->GetTitle()) + : TString::Format("t_{%s=%g}", v->GetTitle(), v->getVal()); + } else return "t"; } else if (fPllType == xRooFit::Asymptotics::OneSidedNegative) { if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - return TString::Format("#tilde{r}_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("Lower-Bound One-Sided Discovery PLR") + : TString::Format("#tilde{r}_{%s=%g}", v->GetTitle(), v->getVal()); else if (v) - return TString::Format("r_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("One-Sided Discovery PLR") + : TString::Format("r_{%s=%g}", v->GetTitle(), v->getVal()); else return "r"; } else if (fPllType == xRooFit::Asymptotics::Uncapped) { if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits::infinity()) - return TString::Format("#tilde{s}_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("Lower-Bound Uncapped PLR") + : TString::Format("#tilde{s}_{%s=%g}", v->GetTitle(), v->getVal()); else if (v) - return TString::Format("s_{%s=%g}", v->GetTitle(), v->getVal()); + return (inWords) ? TString::Format("Uncapped PLR") : TString::Format("s_{%s=%g}", v->GetTitle(), v->getVal()); else return "s"; } else { @@ -1730,22 +2646,24 @@ TString xRooNLLVar::xRooHypoPoint::tsTitle() const char *xRooNLLVar::xRooHypoPoint::fPOIName() { - return (poi().first())->GetName(); + return (poi().empty()) ? nullptr : (poi().first())->GetName(); } double xRooNLLVar::xRooHypoPoint::fNullVal() { - return dynamic_cast(poi().first())->getVal(); + auto first_poi = dynamic_cast(poi().first()); + return (first_poi == nullptr) ? std::numeric_limits::quiet_NaN() : first_poi->getVal(); } double xRooNLLVar::xRooHypoPoint::fAltVal() { - return dynamic_cast(alt_poi().first())->getVal(); + auto _alt_poi = alt_poi(); // need to keep alive as alt_poi owns its contents + auto first_poi = dynamic_cast(_alt_poi.first()); + return (first_poi == nullptr) ? std::numeric_limits::quiet_NaN() : first_poi->getVal(); } xRooNLLVar::xRooHypoSpace xRooNLLVar::hypoSpace(const char *parName, int nPoints, double low, double high, double alt_value, const xRooFit::Asymptotics::PLLType &pllType) { - xRooNLLVar::xRooHypoSpace hs = hypoSpace(parName, pllType); - hs.poi().first()->setStringAttribute("altVal", std::isnan(alt_value) ? nullptr : TString::Format("%f", alt_value)); + xRooNLLVar::xRooHypoSpace hs = hypoSpace(parName, pllType, alt_value); if (nPoints > 0) hs.AddPoints(parName, nPoints, low, high); return hs; @@ -1761,29 +2679,40 @@ xRooNLLVar::xRooHypoSpace xRooNLLVar::hypoSpace(int nPoints, double low, double return hypoSpace(_poi->first()->GetName(), nPoints, low, high, alt_value, pllType); } -xRooNLLVar::xRooHypoSpace xRooNLLVar::hypoSpace(const char *parName, const xRooFit::Asymptotics::PLLType &pllType) +xRooNLLVar::xRooHypoSpace +xRooNLLVar::hypoSpace(const char *parName, const xRooFit::Asymptotics::PLLType &pllType, double alt_value) { xRooNLLVar::xRooHypoSpace s(parName, parName); s.AddModel(pdf()); if (strlen(parName)) { - auto poi = s.pars()->find(parName); - if (!poi) + std::unique_ptr axes(s.pars()->selectByName(parName)); + if (axes->empty()) throw std::runtime_error("parameter not found"); - s.pars()->setAttribAll("poi", false); - poi->setAttribute("poi", true); - } else if (std::unique_ptr(s.pars()->selectByAttrib("poi", true))->empty()) { - throw std::runtime_error("You must specify a POI for the hypoSpace"); + axes->setAttribAll("axis", true); } + /*if (std::unique_ptr(s.pars()->selectByAttrib("poi", true))->empty()) { + throw std::runtime_error("You must specify at least one POI for the hypoSpace"); + }*/ s.fNlls[s.fPdfs.begin()->second] = std::make_shared(*this); s.fTestStatType = pllType; + + for (auto poi : s.poi()) { + poi->setStringAttribute("altVal", std::isnan(alt_value) ? nullptr : TString::Format("%f", alt_value)); + } + return s; } RooStats::HypoTestResult xRooNLLVar::xRooHypoPoint::result() { + if (hypoTestResult) { + return *hypoTestResult; + } RooStats::HypoTestResult out; out.SetBackgroundAsAlt(true); + out.SetName(TUUID().AsString()); + out.SetTitle(TString::Format("%s HypoPoint", collectionContents(poi()).c_str())); bool setReadonly = false; if (nllVar && !nllVar->get()->getAttribute("readOnly")) { @@ -1794,55 +2723,142 @@ RooStats::HypoTestResult xRooNLLVar::xRooHypoPoint::result() auto ts_obs = ts_asymp(); out.SetTestStatisticData(ts_obs.first); + + // build a ds to hold all fits ... store coords in the globs list of the nullDist + // also need to store at least mu_hat value(s) + RooArgList fitDetails; + RooArgList fitMeta; + fitMeta.addClone(RooCategory( + "pllType", "test statistic type", + {{"TwoSided", 0}, {"OneSidedPositive", 1}, {"OneSidedNegative", 2}, {"Uncapped", 3}, {"Unknown", 4}})); + if (ufit()) { + fitMeta.addClone(ufit()->floatParsFinal()); + } + fitMeta.setCatIndex("pllType", int(fPllType)); + fitMeta.addClone(RooRealVar("isExpected", "isExpected", int(isExpected))); + fitDetails.addClone(RooCategory("type", "fit type", + {{"ufit", 0}, + {"cfit_null", 1}, + {"cfit_alt", 2}, + {"asimov_ufit", 3}, + {"asimov_cfit_null", 4}, + {"gen", 5}, + {"cfit_lbound", 6}})); + // fitDetails.addClone(RooStringVar("name", "Fit Name", "")); -- not supported properly in ROOT yet + fitDetails.addClone(RooRealVar("status", "status", 0)); + fitDetails.addClone(RooRealVar("minNll", "minNll", 0)); + fitDetails.addClone(RooRealVar("edm", "edm", 0)); + auto fitDS = new RooDataSet("fits", "fit summary data", fitDetails); + fitDS->convertToTreeStore(); // strings not stored properly in vector store, so do convert! + + for (int i = 0; i < 7; i++) { + std::shared_ptr fit; + switch (i) { + case 0: fit = ufit(); break; + case 1: fit = cfit_null(); break; + case 2: fit = cfit_alt(); break; + case 3: fit = asimov() ? asimov()->ufit(true) : nullptr; break; + case 4: fit = asimov() ? asimov()->cfit_null(true) : nullptr; break; + case 5: fit = fGenFit; break; + case 6: fit = cfit_lbound(); break; + } + if (fit) { + fitDetails.setCatIndex("type", i); + fitMeta.addClone(RooStringVar(TString::Format("%s.name", fitDetails.getCatLabel("type")), + fitDetails.getCatLabel("type"), fit->GetName())); + // fitDetails.setStringValue("name",fit->GetName()); + fitDetails.setRealValue("status", fit->status()); + fitDetails.setRealValue("minNll", fit->minNll()); + fitDetails.setRealValue("edm", fit->edm()); + fitDS->add(fitDetails); + } + } + fitDS->setGlobalObservables(fitMeta); + + out.SetFitInfo(fitDS); + RooArgList nullDetails; + RooArgList nullMeta; + nullMeta.addClone(*coords); + nullDetails.addClone(RooRealVar("seed", "Toy Seed", 0)); + nullDetails.addClone(RooRealVar("ts", "test statistic value", 0)); + nullDetails.addClone(RooRealVar("weight", "weight", 1)); + auto nullToyDS = new RooDataSet("nullToys", "nullToys", nullDetails, "weight"); + nullToyDS->setGlobalObservables(nullMeta); if (!nullToys.empty()) { std::vector values; std::vector weights; values.reserve(nullToys.size()); weights.reserve(nullToys.size()); - size_t badToys = 0; + for (auto &t : nullToys) { - if (std::isnan(std::get<1>(t))) { - badToys++; - } else { - values.push_back(std::get<1>(t)); - weights.push_back(std::get<2>(t)); - } + values.push_back(std::get<1>(t)); + weights.push_back(std::get<2>(t)); + nullDetails.setRealValue("seed", std::get<0>(t)); + nullDetails.setRealValue("ts", std::get<1>(t)); + nullToyDS->add(nullDetails, std::get<2>(t)); } - nullDetails.addClone(RooRealVar("badToys", "Number of bad Toys", badToys)); - out.SetNullDistribution(new RooStats::SamplingDistribution("null", "Null dist", values, weights, tsTitle())); - out.SetNullDetailedOutput(new RooDataSet("nullDetails", "nullDetails", nullDetails)); - out.GetNullDetailedOutput()->add(nullDetails); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + out.fNullPValue = pNull_toys().first; // technically set above + out.fNullPValueError = + pNull_toys().second; // overrides binomial error used in SamplingDistribution::IntegralAndError +#else + out.SetNullPValue(pNull_toys().first); // technically set above + out.SetNullPValueError( + pNull_toys().second); // overrides binomial error used in SamplingDistribution::IntegralAndError +#endif } else { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) out.fNullPValue = pNull_asymp().first; out.fNullPValueError = pNull_asymp().second; +#else + out.SetNullPValue(pNull_asymp().first); + out.SetNullPValueError(pNull_asymp().second); +#endif } + out.SetNullDetailedOutput(nullToyDS); - RooArgList altDetails; if (!altToys.empty()) { std::vector values; std::vector weights; - values.reserve(nullToys.size()); - weights.reserve(nullToys.size()); - size_t badToys = 0; - for (auto &t : nullToys) { - if (std::isnan(std::get<1>(t))) { - badToys++; - } else { - values.push_back(std::get<1>(t)); - weights.push_back(std::get<2>(t)); - } + values.reserve(altToys.size()); + weights.reserve(altToys.size()); + RooArgList altDetails; + RooArgList altMeta; + altDetails.addClone(RooRealVar("seed", "Toy Seed", 0)); + altDetails.addClone(RooRealVar("ts", "test statistic value", 0)); + altDetails.addClone(RooRealVar("weight", "weight", 1)); + auto altToyDS = new RooDataSet("altToys", "altToys", altDetails, "weight"); + altToyDS->setGlobalObservables(altMeta); + for (auto &t : altToys) { + values.push_back(std::get<1>(t)); + weights.push_back(std::get<2>(t)); + altDetails.setRealValue("seed", std::get<0>(t)); + altDetails.setRealValue("ts", std::get<1>(t)); + altToyDS->add(altDetails, std::get<2>(t)); } - nullDetails.addClone(RooRealVar("badToys", "Number of bad Toys", badToys)); - out.SetAltDistribution(new RooStats::SamplingDistribution("alt", "Alt dist", values, weights, tsTitle())); - out.SetAltDetailedOutput(new RooDataSet("altDetails", "altDetails", altDetails)); - out.GetAltDetailedOutput()->add(altDetails); + out.SetAltDetailedOutput(altToyDS); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + out.fAlternatePValue = pAlt_toys().first; // technically set above + out.fAlternatePValueError = + pAlt_toys().second; // overrides binomial error used in SamplingDistribution::IntegralAndError +#else + out.SetAltPValue(pAlt_toys().first); // technically set above + out.SetAltPValueError( + pAlt_toys().second); // overrides binomial error used in SamplingDistribution::IntegralAndError +#endif + } else { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) out.fAlternatePValue = pAlt_asymp().first; out.fAlternatePValueError = pAlt_asymp().second; +#else + out.SetAltPValue(pAlt_asymp().first); + out.SetAltPValueError(pAlt_asymp().second); +#endif } if (setReadonly) { @@ -1852,4 +2868,4 @@ RooStats::HypoTestResult xRooNLLVar::xRooHypoPoint::result() return out; } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/xRooNode.cxx b/roofit/xroofit/src/xRooNode.cxx index 6d24a22ceae69..0e8cee95d8e4f 100644 --- a/roofit/xroofit/src/xRooNode.cxx +++ b/roofit/xroofit/src/xRooNode.cxx @@ -10,6 +10,19 @@ * listed in LICENSE (http://roofit.sourceforge.net/license.txt) */ +/** \class ROOT::Experimental::XRooFit::xRooNode +\ingroup xroofit + +The xRooNode class is designed to wrap over a TObject and provide functionality to aid with interacting with that object, + particularly in the case where the object is a RooFit class instance. +It is a smart pointer to the object, so you have access to all the methods of the object too. + */ + + +#include "RVersion.h" + +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + #define protected public #include "TRootBrowser.h" #include "RooStats/HistFactory/ParamHistFunc.h" @@ -31,6 +44,61 @@ #include "RooSimultaneous.h" #undef protected +#define GETWS(a) a->_myws +#define GETWSSETS(w) w->_namedSets +#define GETWSSNAPSHOTS(w) w->_snapshots +#define GETACTBROWSER(b) b->fActBrowser +#define GETROOTDIR(b) b->fRootDir +#define GETLISTTREE(b) b->fListTree +#define GETDMP(o, m) o->m + +#else + +#include "RooAbsArg.h" +#include "RooWorkspace.h" +#include "RooFitResult.h" +#include "RooConstVar.h" +#include "RooHistFunc.h" +#include "RooRealSumPdf.h" +#include "RooSimultaneous.h" +#include "RooAddPdf.h" +#include "RooProduct.h" +#include "TPad.h" +#include "RooStats/HistFactory/PiecewiseInterpolation.h" +#include "RooStats/HistFactory/FlexibleInterpVar.h" +#include "RooStats/HistFactory/ParamHistFunc.h" +#include "RooProdPdf.h" +#include "TRootBrowser.h" +#include "TGFileBrowser.h" + +RooWorkspace *GETWS(RooAbsArg *a) +{ + return a->workspace(); +} +const auto &GETWSSETS(RooWorkspace *w) +{ + return w->sets(); +} +auto &GETWSSNAPSHOTS(RooWorkspace *w) +{ + return w->getSnapshots(); +} +auto GETACTBROWSER(TRootBrowser *b) +{ + return b->GetActBrowser(); +} +auto GETROOTDIR(TGFileBrowser *b) +{ + return b->GetRootDir(); +} +auto GETLISTTREE(TGFileBrowser *b) +{ + return b->GetListTree(); +} +#define GETDMP(o, m) (*(void **)(((unsigned char *)o) + o->Class()->GetDataMemberOffset(#m))) + +#endif + #include "RooAddition.h" #include "RooCategory.h" @@ -56,14 +124,22 @@ #include "TPRegexp.h" #include "TRegexp.h" #include "TExec.h" +#include "TPaveText.h" #include "TGListTree.h" #include "TGMsgBox.h" #include "TGedEditor.h" #include "TGMimeTypes.h" +#include "TH2.h" +#include "RooExtendPdf.h" +#include "RooExtendedBinding.h" + +#include "RooStats/HypoTestInverterResult.h" -//#include "RooFitTrees/RooFitResultTree.h" -//#include "RooFitTrees/RooDataTree.h" +#include "coutCapture.h" + +// #include "RooFitTrees/RooFitResultTree.h" +// #include "RooFitTrees/RooDataTree.h" #include "TFile.h" #include "TSystem.h" #include "TKey.h" @@ -81,6 +157,7 @@ #include "RooPoisson.h" #include "RooGaussian.h" #include "RooFormulaVar.h" +#include "RooGenericPdf.h" #include "TVectorD.h" #include "TStopwatch.h" #include "TTimeStamp.h" @@ -95,8 +172,18 @@ #include "TGraphErrors.h" #include "TMultiGraph.h" #include "TFrame.h" +#include "RooProjectedPdf.h" +#include "TMemFile.h" +#include "TGaxis.h" +#include "TPie.h" +// #include +// #include + +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) +#include "RooNaNPacker.h" +#endif -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; xRooNode::InteractiveObject *xRooNode::gIntObj = nullptr; std::map, bool>> xRooNode::auxFunctions; @@ -119,7 +206,9 @@ xRooNode::xRooNode(const char *classname, const char *name, const char *title) std::shared_ptr( TClass::GetClass(classname) ? (TObject *)TClass::GetClass(classname)->New() : nullptr, [](TObject *o) { if (auto w = dynamic_cast(o); w) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) w->_embeddedDataList.Delete(); +#endif xRooNode(*w, std::make_shared()).sterilize(); } if (o) @@ -135,8 +224,10 @@ xRooNode::xRooNode(const char *name, const std::shared_ptr &comp, const : TNamed(name, ""), fComp(comp), fParent(parent) { - if (!fComp && !fParent) { - TString pathName = TString(gSystem->ExpandPathName(name)); + if (!fComp && !fParent && name && strlen(name) > 0) { + char *_path = gSystem->ExpandPathName(name); + TString pathName = TString(_path); + delete[] _path; if (!gSystem->AccessPathName(pathName)) { // if file is json can try to read if (pathName.EndsWith(".json")) { @@ -168,9 +259,11 @@ xRooNode::xRooNode(const char *name, const std::shared_ptr &comp, const auto cl = TClass::GetClass(((TKey *)k)->GetClassName()); if (cl == RooWorkspace::Class() || cl->InheritsFrom("RooWorkspace")) { fComp.reset(_file->Get(k->GetName()), [](TObject *ws) { - // memory leak in workspace, some RooLinkedLists aren't cleared + // memory leak in workspace, some RooLinkedLists aren't cleared, fixed in ROOT 6.28 if (ws) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) dynamic_cast(ws)->_embeddedDataList.Delete(); +#endif xRooNode(*ws, std::make_shared()).sterilize(); delete ws; } @@ -220,7 +313,7 @@ xRooNode::xRooNode(const char *name, const std::shared_ptr &comp, const if (checkCount == 0 && !_ws->allData().empty()) _ws->allData().back()->SetBit(1 << 20, true); - if (auto _set = dynamic_cast(_ws->_snapshots.find("NominalParamValues")); _set) { + if (auto _set = dynamic_cast(GETWSSNAPSHOTS(_ws).find("NominalParamValues")); _set) { for (auto s : *_set) { if (auto v = dynamic_cast(s); v) { _ws->var(s->GetName())->setStringAttribute("nominal", TString::Format("%f", v->getVal())); @@ -230,7 +323,7 @@ xRooNode::xRooNode(const char *name, const std::shared_ptr &comp, const // also flag global observables ... relies on ModelConfig existences RooArgSet _allGlobs; - for (auto &[k, v] : _ws->_namedSets) { + for (auto &[k, v] : GETWSSETS(_ws)) { if (k == "globalObservables" || TString(k).EndsWith("_GlobalObservables")) { for (auto &s : v) { _allGlobs.add(*s); @@ -244,37 +337,48 @@ xRooNode::xRooNode(const char *name, const std::shared_ptr &comp, const auto _v = dynamic_cast(s); if (!_v) continue; - if (!_v->hasRange("physical")) { - _v->setRange("physical", 0, std::numeric_limits::infinity()); - // ensure range of poi is also straddling 0 - if (_v->getMin() >= 0) - _v->setMin(-1e-5); - } + // if (!_v->hasRange("physical")) { + // _v->setRange("physical", 0, std::numeric_limits::infinity()); + // // ensure range of poi is also straddling 0 + // if (_v->getMin() >= 0) + // _v->setMin(-1e-5); + // } } + } else if (TString(k).EndsWith("_NuisParams")) { + const_cast(v).setAttribAll("np"); } } - if (!_allGlobs.empty() && _ws->_namedSets.count("globalObservables") == 0) { + if (!_allGlobs.empty() && GETWSSETS(_ws).count("globalObservables") == 0) { _ws->defineSet("globalObservables", _allGlobs); } // now check if any pars don't have errors defined (not same as error=0) ... if so, use the first pdf (if there is // one) to try setting values from if (!_ws->allPdfs().empty()) { - std::vector noErrorPars; - for (auto &p : pars()) { + std::set noErrorPars; + std::string parNames; + for (auto &p : np()) { // infer errors on all floating non-poi parameters auto v = p->get(); if (!v) continue; - if (!v->hasError()) - noErrorPars.push_back(v); + if (!v->hasError()) { + noErrorPars.insert(v); + if (!parNames.empty()) + parNames += ","; + parNames += v->GetName(); + } } if (!noErrorPars.empty()) { + Warning( + "xRooNode", + "Inferring initial errors of %d parameters (give all nuisance parameters an error to avoid this msg)", + int(noErrorPars.size())); // get the first top-level pdf browse(); for (auto &a : *this) { if (a->fFolder == "!models") { try { - auto fr = a->fitResult("prefit"); + auto fr = a->floats().reduced(parNames).fitResult("prefit"); if (auto _fr = fr.get(); _fr) { for (auto &v : noErrorPars) { if (auto arg = dynamic_cast(_fr->floatParsFinal().find(v->GetName())); @@ -410,6 +514,7 @@ void xRooNode::Browse(TBrowser *b) gEnv->SetValue("X11.Sync", "no"); gEnv->SetValue("X11.FindBestVisual", "no"); gEnv->SetValue("Browser.Name", "TRootBrowser"); // forces classic root browser (in 6.26 onwards) + gEnv->SetValue("Canvas.Name", "TRootCanvas"); b2 = new TBrowser("nodeBrowser", this, "RooFit Browser"); blockBrowse = false; } else if (strcmp(b2->GetName(), "nodeBrowser") == 0) { @@ -417,7 +522,7 @@ void xRooNode::Browse(TBrowser *b) b2->BrowseObject(this); blockBrowse = false; } else { - auto _b = dynamic_cast(dynamic_cast(b2->GetBrowserImp())->fActBrowser); + auto _b = dynamic_cast(GETACTBROWSER(dynamic_cast(b2->GetBrowserImp()))); if (_b) _b->AddFSDirectory("Workspaces", 0, "SetRootDir"); /*auto l = Node2::Class()->GetMenuList(); @@ -450,18 +555,41 @@ void xRooNode::Browse(TBrowser *b) } browse(); - if (empty()) { + + // for top-level pdfs default to having the .vars browsable too + if (get() && fFolder == "!models" && !_IsShowVars_()) { + fBrowsables.push_back(std::make_shared(vars())); + } + + if (auto _fr = get(); _fr && fBrowsables.empty()) { + // have some common drawing options + fBrowsables.push_back(std::make_shared(".Draw(\"pull\")", nullptr, *this)); + fBrowsables.push_back(std::make_shared(".Draw(\"corrcolztext\")", nullptr, *this)); + if (std::unique_ptr(_fr->floatParsFinal().selectByAttrib("poi", true))->size() == 1) { + fBrowsables.push_back(std::make_shared(".Draw(\"impact\")", nullptr, *this)); + } + } + + if (empty() && fBrowsables.empty()) { try { if (auto s = get()) { s->SetFillAttributes(); if (auto ed = dynamic_cast(TVirtualPadEditor::GetPadEditor())) { ed->SetModel(gPad, s, kButton1Down, true); } - } else + } else if (TString(GetName()).BeginsWith(".Draw(\"") && fParent) { + fParent->Draw(TString(TString(GetName())(7, strlen(GetName()) - 9)) + b->GetDrawOption()); + } else { Draw(b->GetDrawOption()); + } } catch (const std::exception &e) { - new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(), - kMBIconExclamation); // deletes self on dismiss? + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Exception", e.what(), + kMBIconExclamation); // deletes self on dismiss? } } @@ -483,7 +611,7 @@ void xRooNode::Browse(TBrowser *b) } // ensure entry in folders for every folder type ... for (auto &v : *this) { - if (v->fFolder != "" && !_folders->find(v->fFolder)) { + if (v->fFolder != "" && !_folders->find(v->fFolder, false)) { _folders->emplace_back(std::make_shared(v->fFolder.c_str(), nullptr, *this)); } } @@ -501,7 +629,12 @@ void xRooNode::Browse(TBrowser *b) continue; // in the folders if (strcmp(v->GetName(), ".folders") == 0) continue; // never 'browse' the folders property - int _checked = (v->get() || v->get()) ? v->get()->TestBit(1 << 20) : -1; + auto _fr = v->get(); + int _checked = (v->get() || _fr) ? v->get()->TestBit(1 << 20) : -1; + if (_fr && ((_fr->status() == 0 && _fr->numStatusHistory() == 0) || (_fr->floatParsFinal().empty()))) { + // this is a "PARTIAL" fit result ... don't allow it to be selected + _checked = -1; + } if (v->get() && get()) _checked = !v->get()->getAttribute("hidden"); TString _name = v->GetName(); @@ -523,6 +656,19 @@ void xRooNode::Browse(TBrowser *b) else*/ _name += TString::Format(" [%s]", _type); } + if (auto fv = v->get()) { + TString formu = TString::Format(" [%s]", fv->expression()); + for (size_t i = 0; i < fv->dependents().size(); i++) { + formu.ReplaceAll(TString::Format("x[%zu]", i), fv->dependents()[i].GetName()); + } + _name += formu; + } else if (auto gv = v->get()) { + TString formu = TString::Format(" [%s]", gv->expression()); + for (size_t i = 0; i < gv->dependents().size(); i++) { + formu.ReplaceAll(TString::Format("x[%zu]", i), gv->dependents()[i].GetName()); + } + _name += formu; + } // tool tip defaults to displaying name and title, so temporarily set name to obj name if has one // and set title to the object type TString nameSave(v->TNamed::GetName()); @@ -534,12 +680,39 @@ void xRooNode::Browse(TBrowser *b) v->TNamed::SetNameTitle(nameSave, titleSave); if (_checked != -1) { dynamic_cast(b->GetBrowserImp()) - ->Connect("Checked(TObject *, Bool_t)", ClassName(), v.get(), "Checked(TObject *, Bool_t)"); - if (auto _fr = v->get(); _fr && _fr->status()) - v->GetTreeItem(b)->SetColor(kRed); + ->Connect("Checked(TObject *, bool)", ClassName(), v.get(), "Checked(TObject *, bool)"); + } + if (_fr) { + if (_fr->status() || _fr->covQual() != 3) { // snapshots or bad fits + v->GetTreeItem(b)->SetColor((_fr->numStatusHistory() || _fr->floatParsFinal().empty()) ? kRed : kBlue); + } else if (_fr->numStatusHistory() == 0) { // partial fit result .. + v->GetTreeItem(b)->SetColor(kGray); + } } + if ((v->fFolder == "!np" || v->fFolder == "!poi")) { + if (v->get()->getAttribute("Constant")) { + v->GetTreeItem(b)->SetColor(kGray); + } else + v->GetTreeItem(b)->ClearColor(); + } + if (auto _htr = v->get(); _htr) { + // check for fit statuses + if (auto fits = _htr->GetFitInfo()) { + for (int i = 0; i < fits->numEntries(); i++) { + // if any fit (other than a genFit) is bad, flag point as bad + if (fits->get(i)->getCatIndex("type") != 5 && fits->get(i)->getRealValue("status") != 0) { + v->GetTreeItem(b)->SetColor(kRed); + break; + } + } + } else { + v->GetTreeItem(b)->SetColor(kBlue); // unknown fit status + } + } + // v.fBrowsers.insert(b); } + // for pdfs, check for datasets too and add to list /*if (get()) { auto dsets = datasets(); @@ -560,6 +733,8 @@ void xRooNode::Browse(TBrowser *b) // browse the browsables too for (auto &v : fBrowsables) { TString _name = v->GetName(); + if (_name == ".memory") + continue; // hide the memory from browsing, if put in browsables TString nameSave(v->TNamed::GetName()); TString titleSave(v->TNamed::GetTitle()); if (auto o = v->get(); o) @@ -572,7 +747,7 @@ void xRooNode::Browse(TBrowser *b) b->SetSelected(this); } -void xRooNode::_ShowVars_(Bool_t set) +void xRooNode::_ShowVars_(bool set) { if (!set) { // can't remove as causes a crash, need to remove from the browser first @@ -603,7 +778,7 @@ bool xRooNode::IsFolder() const { if (strlen(GetName()) > 0 && GetName()[0] == '!') return true; - if (strlen(GetName()) > 0 && GetName()[0] == '.') + if (strlen(GetName()) > 0 && GetName()[0] == '.' && !(TString(GetName()).BeginsWith(".Draw(\""))) return true; if (empty()) const_cast(this)->browse(); @@ -614,22 +789,23 @@ class Axis2 : public TAxis { public: using TAxis::TAxis; - Double_t GetBinWidth(Int_t bin) const override + double GetBinWidth(Int_t bin) const override { if (auto v = var(); v) return v->getBinWidth(bin - 1, GetName()); return 1; } - Double_t GetBinLowEdge(Int_t bin) const override + double GetBinLowEdge(Int_t bin) const override { if (auto v = rvar(); v) - return v->getBinning(GetName()).binLow(bin - 1); + return (bin == v->getBinning(GetName()).numBins() + 1) ? v->getBinning(GetName()).binHigh(bin - 2) + : v->getBinning(GetName()).binLow(bin - 1); return bin - 1; } - Double_t GetBinUpEdge(Int_t bin) const override + double GetBinUpEdge(Int_t bin) const override { if (auto v = rvar(); v) - return v->getBinning(GetName()).binHigh(bin - 1); + return (bin == 0) ? v->getBinning(GetName()).binLow(bin) : v->getBinning(GetName()).binHigh(bin - 1); return bin; } @@ -645,20 +821,20 @@ class Axis2 : public TAxis { dynamic_cast(GetParent())->SetTitle(title); } - void Set(Int_t nbins, const Double_t *xbins) override + void Set(Int_t nbins, const double *xbins) override { if (auto v = dynamic_cast(rvar())) v->setBinning(RooBinning(nbins, xbins), GetName()); TAxis::Set(nbins, xbins); } - void Set(Int_t nbins, const Float_t *xbins) override + void Set(Int_t nbins, const float *xbins) override { std::vector bins(nbins + 1); for (int i = 0; i <= nbins; i++) bins.at(i) = xbins[i]; return Set(nbins, &bins[0]); } - void Set(Int_t nbins, Double_t xmin, Double_t xmax) override + void Set(Int_t nbins, double xmin, double xmax) override { if (auto v = dynamic_cast(rvar())) v->setBinning(RooUniformBinning(xmin, xmax, nbins), GetName()); @@ -668,7 +844,7 @@ class Axis2 : public TAxis { const RooAbsBinning *binning() const { return var()->getBinningPtr(GetName()); } Int_t FindFixBin(const char *label) const override { return TAxis::FindFixBin(label); } - Int_t FindFixBin(Double_t x) const override { return (binning()) ? (binning()->binNumber(x) + 1) : x; } + Int_t FindFixBin(double x) const override { return (binning()) ? (binning()->binNumber(x) + 1) : x; } private: RooAbsLValue *var() const { return dynamic_cast(GetParent()); } @@ -728,6 +904,13 @@ std::shared_ptr xRooNode::getObject(const std::string &name, const std: if (!out) out = _tmp; } + if (auto arg = GETWSSNAPSHOTS(ws()).find(name.c_str()); arg) { + auto _tmp = std::shared_ptr(arg, [](TObject *) {}); + if (!type.empty() && arg->InheritsFrom(type.c_str())) + return _tmp; + if (!out) + out = _tmp; + } return out; } return nullptr; @@ -736,7 +919,13 @@ std::shared_ptr xRooNode::getObject(const std::string &name, const std: TAxis *xRooNode::GetXaxis() const { if (fXAxis) { - return fXAxis.get(); + // check if num bins needs update or not + if (auto cat = dynamic_cast(fXAxis->GetParent()); + cat && cat->numTypes() != fXAxis->GetNbins()) { + fXAxis.reset(); + } else { + return fXAxis.get(); + } } RooAbsLValue *x = nullptr; if (auto a = get(); a && a->isFundamental()) @@ -755,9 +944,10 @@ TAxis *xRooNode::GetXaxis() const // if xvar has become set equal to an arg and this is a pdf, we will allow a do-over if (!x) { // need to choose from dependent fundamentals, in following order: - // parentX, obs, globs, vars, args + // parentX (if not a glob), robs, globs, vars, args - if (_parentX && (o->dependsOn(*dynamic_cast(_parentX->GetParent())) || vars().size() == 0)) { + if (_parentX && !dynamic_cast(_parentX->GetParent())->getAttribute("global") && + (o->dependsOn(*dynamic_cast(_parentX->GetParent())) || vars().size() == 0)) { x = dynamic_cast(_parentX->GetParent()); } else if (auto _obs = obs(); !_obs.empty()) { for (auto &v : _obs) { @@ -860,13 +1050,14 @@ TAxis *xRooNode::GetXaxis() const } else { fXAxis = std::make_shared(x->numBins(binningName), r->getBinning(binningName).array()); } - } else { + } else if (dynamic_cast(x)) { std::vector bins = {}; for (int i = 0; i <= x->numBins(binningName); i++) bins.push_back(i); fXAxis = std::make_shared(x->numBins(binningName), &bins[0]); // TODO have to load current state of bin labels if was a category (sadly not a virtual method) for (int i = 0; i < x->numBins(binningName); i++) { + fXAxis->SetBinLabel(i + 1, dynamic_cast(x)->lookupName(i).c_str()); } } } @@ -926,8 +1117,29 @@ const char *xRooNode::GetIconName() const return "xRooFitRooConstVar";*/ return "TMethodBrowsable-leaf"; } + if (o->InheritsFrom("RooStats::HypoTestInverterResult")) { + if (!gClient->GetMimeTypeList()->GetIcon("xRooFitScanStyle", true)) { + gClient->GetMimeTypeList()->AddType("xRooFitScanStyle", "xRooFitScanStyle", "f2_s.xpm", "f2_s.xpm", + "->Browse()"); + } + return "xRooFitScanStyle"; + } + if (o->InheritsFrom("RooStats::HypoTestResult")) { + if (!gClient->GetMimeTypeList()->GetIcon("xRooFitTestStyle", true)) { + gClient->GetMimeTypeList()->AddType("xRooFitTestStyle", "xRooFitTestStyle", "diamond.xpm", "diamond.xpm", + "->Browse()"); + } + return "xRooFitTestStyle"; + } if (o->InheritsFrom("RooStats::HistFactory::FlexibleInterpVar")) return "TBranchElement-folder"; + if (o->InheritsFrom("RooAbsPdf")) { + if (!gClient->GetMimeTypeList()->GetIcon("xRooFitPDFStyle", true)) { + gClient->GetMimeTypeList()->AddType("xRooFitPDFStyle", "xRooFitPDFStyle", "pdf.xpm", "pdf.xpm", + "->Browse()"); + } + return "xRooFitPDFStyle"; + } if (auto a = dynamic_cast(o); a) { if (auto _ax = GetXaxis(); _ax && (a->isBinnedDistribution(*dynamic_cast(_ax->GetParent())) || @@ -976,7 +1188,25 @@ xRooNode xRooNode::coords(bool setVals) const while (_p) { TString pName(_p->GetName()); if (auto pos = pName.Index('='); pos != -1) { - if (auto _obs = _p->getObject(pName(0, pos)); _obs) { + if (pos > 0 && pName(pos - 1) == '<') { + // should be a range on a real lvalue, of form low<=namegetObject(pName.Data()); _obs) { + if (setVals) { + _obs->setVal((high + low) / 2.); + static_cast(_obs.get())->setRange("coordRange", low, high); + _obs->setStringAttribute( + "coordRange", "coordRange"); // will need if we allow multi disconnected regions, need comma list + } + out.emplace_back(std::make_shared(_obs->GetName(), _obs, _p)); + } else { + throw std::runtime_error(TString::Format("Unknown observable: %s", pName.Data())); + } + + } else if (auto _obs = _p->getObject(pName(0, pos)); _obs) { if (setVals) { if (auto _cat = dynamic_cast(_obs.get()); _cat) { _cat->setLabel(pName(pos + 1, pName.Length())); @@ -1016,19 +1246,31 @@ void xRooNode::_Vary_(const char *what) xRooNode xRooNode::Remove(const xRooNode &child) { - if (strcmp(GetName(), ".factors") == 0 || strcmp(GetName(), ".constraints") == 0 || - strcmp(GetName(), ".components") == 0) { + if (strcmp(GetName(), ".poi") == 0) { + // demote a parameter from being a poi + auto toRemove = + (child.get() || !find(child.GetName())) ? child : xRooNode(find(child.GetName())->fComp); + if (toRemove) { + if (!toRemove.get()->getAttribute("poi")) { + throw std::runtime_error(TString::Format("%s is not a poi", toRemove.GetName())); + } + toRemove.get()->setAttribute("poi", false); + return toRemove; + } + } else if (strcmp(GetName(), ".factors") == 0 || strcmp(GetName(), ".constraints") == 0 || + strcmp(GetName(), ".components") == 0) { auto toRemove = (child.get() || !find(child.GetName())) ? child : xRooNode(find(child.GetName())->fComp); if (auto p = fParent->get(); p) { auto pdf = toRemove.get(); if (!pdf) - pdf = p->_pdfList.find(child.GetName()); + pdf = p->pdfList().find(child.GetName()); if (!pdf) throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName())); - auto i = p->_pdfList.index(*pdf); + auto i = p->pdfList().index(*pdf); if (i >= 0) { - p->_pdfList.remove(*pdf); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + const_cast(p->pdfList()).remove(*pdf); #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00) p->_pdfNSetList.erase(p->_pdfNSetList.begin() + i); #else @@ -1036,15 +1278,14 @@ xRooNode xRooNode::Remove(const xRooNode &child) p->_pdfNSetList.Remove(nset); delete nset; // I don't think the RooLinkedList owned it so must delete ourself #endif - sterilize(); // next three lines shouldn't be necessary any more - p->_cacheMgr.reset(); - p->setValueDirty(); - p->setNormRange(0); if (p->_extendedIndex == i) p->_extendedIndex = -1; else if (p->_extendedIndex > i) p->_extendedIndex--; - +#else + p->removePdfs(RooArgSet(*pdf)); +#endif + sterilize(); return xRooNode(*pdf); } else { throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName())); @@ -1055,15 +1296,19 @@ xRooNode xRooNode::Remove(const xRooNode &child) arg = p2->components().find(child.GetName()); if (!arg) throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName())); - // remove server ... doesn't seem to trigger removal from proxy + // remove server ... doesn't seem to trigger removal from proxy +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) p2->_compRSet.remove(*arg); +#else + const_cast(p2->realComponents()).remove(*arg); +#endif p2->removeServer(*arg, true); sterilize(); return xRooNode(*arg); } else if (fParent->get()) { // remove from all channels bool removed = false; - for (auto &c : fParent->variations()) { + for (auto &c : fParent->bins()) { try { c->constraints().Remove(toRemove); removed = true; @@ -1077,25 +1322,25 @@ xRooNode xRooNode::Remove(const xRooNode &child) } else if (auto p4 = fParent->get(); p4) { auto arg = toRemove.get(); if (!arg) - arg = p4->_funcList.find(child.GetName()); + arg = p4->funcList().find(child.GetName()); if (!arg) throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName())); // remove, including coef removal .... - auto idx = p4->_funcList.index(arg); + auto idx = p4->funcList().index(arg); if (idx != -1) { - p4->_funcList.remove(*arg); + const_cast(p4->funcList()).remove(*arg); p4->removeServer(*arg, true); // have to be careful removing coef because if shared will end up removing them all!! std::vector _coefs; - for (size_t ii = 0; ii < p4->_coefList.size(); ii++) { + for (size_t ii = 0; ii < const_cast(p4->coefList()).size(); ii++) { if (ii != size_t(idx)) - _coefs.push_back(p4->_coefList.at(ii)); + _coefs.push_back(const_cast(p4->coefList()).at(ii)); } - p4->_coefList.removeAll(); + const_cast(p4->coefList()).removeAll(); for (auto &a : _coefs) - p4->_coefList.add(*a); + const_cast(p4->coefList()).add(*a); sterilize(); } else { @@ -1107,7 +1352,7 @@ xRooNode xRooNode::Remove(const xRooNode &child) if (auto w = get(); w) { xRooNode out(child.GetName()); - auto arg = w->_allOwnedNodes.find(child.GetName()); + auto arg = w->components().find(child.GetName()); if (!arg) arg = operator[](child.GetName())->get(); if (!arg) { @@ -1119,7 +1364,7 @@ xRooNode xRooNode::Remove(const xRooNode &child) TString::Format("Cannot remove %s from workspace %s, because it has dependencies - first remove from those", child.GetName(), GetName())); } - w->_allOwnedNodes.remove(*arg); // deletes arg + const_cast(w->components()).remove(*arg); // deletes arg Info("Remove", "Deleted %s from workspace %s", out.GetName(), GetName()); return out; } else if (get() || get()) { @@ -1171,7 +1416,25 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) } else if (strcmp(GetName(), ".constraints") == 0) { // constrain the parent return fParent->Constrain(child); - } else if (strcmp(GetName(), ".pars") == 0 && fParent->get()) { + } else if (strcmp(GetName(), ".bins") == 0 && fParent->get()) { + // adding a channel (should adding a 'bin' be an 'Extend' operation?) + return fParent->Vary(child); + } else if ((strcmp(GetName(), ".globs") == 0)) { + if (child.get() || (!child.fComp && getObject(child.GetName()))) { + auto out = (child.get()) ? child.get() : getObject(child.GetName()).get(); + out->setAttribute("obs"); + out->setAttribute("global"); + return xRooNode(*out, *this); + } + throw std::runtime_error("Failed to add global observable"); + } else if ((strcmp(GetName(), ".poi") == 0)) { + if (child.get() || (!child.fComp && getObject(child.GetName()))) { + auto out = (child.get()) ? child.get() : getObject(child.GetName()).get(); + out->setAttribute("poi"); + return xRooNode(*out, *this); + } + throw std::runtime_error("Failed to add parameter of interest"); + } else if ((strcmp(GetName(), ".pars") == 0 || strcmp(GetName(), ".vars") == 0) && fParent->get()) { // adding a parameter, interpret as factory string unless no "[" then create RooRealVar TString fac(child.GetName()); if (!fac.Contains("[")) @@ -1191,13 +1454,17 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) auto _fr = std::dynamic_pointer_cast(fParent->fitResult().fComp); if (strlen(_fr->GetName()) == 0) std::const_pointer_cast(_fr)->SetName(TUUID().AsString()); - auto asi = xRooFit::generateFrom(*fParent->get(), _fr, sOpt == "asimov"); + auto asi = xRooFit::generateFrom(*fParent->get(), *_fr, sOpt == "asimov"); if (strlen(child.GetName())) asi.first->SetName(child.GetName()); if (asi.first) { _ws->import(*asi.first); } - if (!_ws->obj(_fr->GetName())) { + if (_fr->numStatusHistory() == 0) { + if (!GETWSSNAPSHOTS(_ws).find(_fr->GetName())) { + const_cast(GETWSSNAPSHOTS(_ws)).Add(_fr->Clone()); + } + } else if (!_ws->obj(_fr->GetName())) { _ws->import(const_cast(*_fr)); } // save fr to workspace, for later retrieval if (asi.second) { @@ -1284,9 +1551,47 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) } if (auto p = get(); p) { + if (auto bb = getBrowsable(".sourceds")) + bb->Add(child, opt); + if (auto _data = child.get()) { + auto ds = dynamic_cast(p); + if (!ds) { + throw std::runtime_error("Can only add datasets to a dataset"); + } + + // append any missing globs, and check any existing globs have matching values + RooArgList globsToAdd; + auto _globs = globs(); + for (auto &glob : child.globs()) { + if (auto g = _globs.find(glob->GetName()); !g) { + globsToAdd.addClone(*glob->get()); + } else if (g->GetContent() != glob->GetContent()) { + Warning("Add", "Global observable %s=%g in dataset mismatches child value %g ... ignoring child", + g->GetName(), g->GetContent(), glob->GetContent()); + } + } + // add any existing globs to list then set the list + if (auto _dglobs = p->getGlobalObservables()) { + globsToAdd.addClone(*_dglobs); + } else { + for (auto g : _globs) + globsToAdd.addClone(*g->get()); + } + p->setGlobalObservables(globsToAdd); + + // append any missing observables to our dataset, then append the dataset + + for (auto col : *_data->get()) { + if (!p->get()->contains(*col)) { + ds->addColumn(*col); + } + } + ds->append(*_data); + return *this; + } auto _h = child.get(); if (!_h) { - throw std::runtime_error("Can only add histogram to data"); + throw std::runtime_error("Can only add histogram or dataset to data"); } auto _pdf = parentPdf(); if (!_pdf) @@ -1312,20 +1617,122 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) } } + // before adding, ensure range is good to cover + for (auto &o : obs) { + if (auto v = dynamic_cast(o); v) { + if (auto dv = dynamic_cast(p->get()->find(v->GetName())); dv) { + if (v->getMin() < dv->getMin()) + dv->setMin(v->getMin()); + if (v->getMax() > dv->getMax()) + dv->setMax(v->getMax()); + } + } else if (auto c = dynamic_cast(o); c) { + if (auto dc = dynamic_cast(p->get()->find(c->GetName())); dc) { + if (!dc->hasLabel(c->getCurrentLabel())) { + dc->defineType(c->getCurrentLabel(), c->getCurrentIndex()); + } + } + } + } + for (int i = 1; i <= _h->GetNbinsX(); i++) { - dynamic_cast(_ax->GetParent())->setVal(_h->GetBinCenter(i)); + if (auto cat = dynamic_cast(_ax->GetParent())) { + if (!_h->GetXaxis()->GetBinLabel(i)) { + throw std::runtime_error( + TString::Format("Categorical observable %s requires bin labels", _ax->GetParent()->GetName())); + } else if (!cat->hasLabel(_h->GetXaxis()->GetBinLabel(i))) { + throw std::runtime_error(TString::Format("Categorical observable %s does not have label %s", + _ax->GetParent()->GetName(), _h->GetXaxis()->GetBinLabel(i))); + } else { + cat->setLabel(_h->GetXaxis()->GetBinLabel(i)); + } + } else { + dynamic_cast(_ax->GetParent())->setVal(_h->GetBinCenter(i)); + } p->add(obs, _h->GetBinContent(i)); } return *this; } - if (auto p = get(); p && child.get()) { - auto out = acquire(child.fComp); - p->_coefList.add(*acquire("1", "1", 1)); - p->_pdfList.add(*std::dynamic_pointer_cast(out)); - sterilize(); - return xRooNode(out, *this); + if (auto p = get(); p) { + if ((child.get() || (!child.fComp && getObject(child.GetName())))) { + auto out = (child.fComp) ? acquire(child.fComp) : getObject(child.GetName()); + // don't add a coef if in 'all-extended' mode and this pdf is extendable + auto _pdf = std::dynamic_pointer_cast(out); + if (!_pdf) { + throw std::runtime_error("Something went wrong with pdf acquisition"); + } + + if (auto _ax = GetXaxis(); _ax && dynamic_cast(_ax->GetParent()) && + _pdf->dependsOn(*static_cast(_ax->GetParent()))) { + auto _p = _pdf; + + if (auto _boundaries = std::unique_ptr>(_p->binBoundaries( + *dynamic_cast(_ax->GetParent()), -std::numeric_limits::infinity(), + std::numeric_limits::infinity())); + !_boundaries && _ax->GetNbins() > 0) { +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00) + Warning("Add", "Adding unbinned pdf %s to binned %s - will wrap with RooBinSamplingPdf(...)", + _p->GetName(), GetName()); + _p = acquireNew(TString::Format("%s_binned", _p->GetName()), _p->GetTitle(), + *dynamic_cast(_ax->GetParent()), *_p); + _p->setStringAttribute("alias", std::dynamic_pointer_cast(out)->getStringAttribute("alias")); + if (!_p->getStringAttribute("alias")) + _p->setStringAttribute("alias", out->GetName()); +#else + throw std::runtime_error( + "unsupported addition of unbinned pdf to binned model - please upgrade to at least ROOT 6.24"); +#endif + _pdf = _p; + } + } + + if (!(_pdf->canBeExtended() && p->coefList().empty())) { + // if extended, use an extended binding as the coef + // otherwise e.g. if adding a RooRealSumPdf the stacked histograms will be above the + // actual pdf histogram because the pdf histogram is just normalized down + if (_pdf->canBeExtended()) { + // FIXME: ExtendedBinding needs the obs list passing to it ... should be fixed in RooFit + // until then, this will return "1" and so the pdf's histograms wont be normalized properly in relation + // to stacks of its comps + const_cast(p->coefList()) + .add(*acquireNew(TString::Format("%s_extBind", _pdf->GetName()), + TString::Format("Expected Events of %s", _pdf->GetTitle()), + *_pdf)); + } else { + const_cast(p->coefList()).add(*acquire2("1", "1", 1)); + } + } + const_cast(p->pdfList()).add(*_pdf); + sterilize(); + return xRooNode(*_pdf, *this); + } else if ((child.get() || child.get() || + (!child.get() && getObject(child.GetName()))) && + !child.get()) { + RooRealSumPdf *_pdf = nullptr; + bool tooMany(false); + for (auto &pp : factors()) { + if (auto _p = pp->get(); _p) { + if (_pdf) { + _pdf = nullptr; + tooMany = true; + break; + } // more than one! + _pdf = _p; + } + } + if (_pdf) { + return xRooNode(*_pdf, *this).Add(child); + } else if (!tooMany) { + // create a RooRealSumPdf to hold the child + auto _sumpdf = Add(*acquireNew(TString::Format("%s_samples", p->GetName()), + TString::Format("%s samples", GetTitle()), RooArgList(), + RooArgList(), true)); + _sumpdf.get()->setStringAttribute("alias", "samples"); + return _sumpdf.Add(child); + } + } } if (auto p = get(); p) { @@ -1343,7 +1750,7 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) std::shared_ptr _func; // a null node .. so create either a new RooProduct or RooHistFunc if has observables (or no deps but has // x-axis) - auto _obs = obs(); + auto _obs = robs(); if (!_obs.empty() || GetXaxis()) { if (_obs.empty()) { // using X axis to construct hist @@ -1376,7 +1783,8 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) TString::Format("%s;%s", dynamic_cast(_x)->GetName(), binningName.Data())); // technically convertForAcquisition has already acquired so no need to re-acquire but should be harmless _func = std::dynamic_pointer_cast(acquire(xRooNode(*h).convertForAcquisition(*this))); - Info("Add", "Created densityhisto factor %s for %s", _func->GetName(), p->GetName()); + Info("Add", "Created densityhisto factor %s (xaxis=%s) for %s", _func->GetName(), _obs.at(0)->GetName(), + p->GetName()); } else { throw std::runtime_error("Unsupported creation of new component in SumPdf for this many obs"); } @@ -1413,23 +1821,68 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) _f->getAttribute("density") ? "densityhisto" : "histo", _f->GetName(), p->GetName()); } + if (auto _p = std::dynamic_pointer_cast(out); _p) { + // adding a pdf to a RooRealSumPdf will replace it with a RooAddPdf and put the RooRealSumPdf inside that + // if pdf is extended will use in the "no coefficients" state, where the expectedEvents are taking from + // the pdf integrals + TString newName(_p->GetName()); + newName.ReplaceAll("_samples", ""); + newName += "_components"; + Warning("Add", "converting samples to components"); + + if (auto _ax = GetXaxis(); _ax && dynamic_cast(_ax->GetParent()) && + _p->dependsOn(*static_cast(_ax->GetParent()))) { + + if (auto _boundaries = std::unique_ptr>(_p->binBoundaries( + *dynamic_cast(_ax->GetParent()), -std::numeric_limits::infinity(), + std::numeric_limits::infinity())); + !_boundaries && _ax->GetNbins() > 0) { +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00) + Warning("Add", "Adding unbinned pdf %s to binned %s - will wrap with RooBinSamplingPdf(...)", + _p->GetName(), GetName()); + _p = acquireNew(TString::Format("%s_binned", _p->GetName()), _p->GetTitle(), + *dynamic_cast(_ax->GetParent()), *_p); + _p->setStringAttribute("alias", std::dynamic_pointer_cast(out)->getStringAttribute("alias")); + if (!_p->getStringAttribute("alias")) + _p->setStringAttribute("alias", out->GetName()); +#else + throw std::runtime_error( + "unsupported addition of unbinned pdf to binned model - please upgrade to at least ROOT 6.24"); +#endif + } + } + + // require to be extended to be in coefficient-free mode ... + // otherwise would lose the integral of the sumPdf (can't think of way to have a coef be the integral) + if (!_p->canBeExtended()) { + _p = acquireNew(TString::Format("%s_extended", _p->GetName()), _p->GetTitle(), *_p, + *acquire2("1", "1", 1)); + } + + return *(Replace(*acquireNew(newName, _p->GetTitle(), RooArgList(*p, *_p))) + .browse()[1]); // returns second node. + } + if (auto _f = std::dynamic_pointer_cast(out); _f) { // todo: if adding a pdf, should actually replace RooRealSumPdf with a RooAddPdf and put // the sumPdf and *this* pdf inside that pdf // only exception is the binSamplingPdf below to integrate unbinned functions across bins - if (auto _ax = GetXaxis(); _ax && dynamic_cast(_ax->GetParent())) { + if (auto _ax = GetXaxis(); _ax && dynamic_cast(_ax->GetParent()) && + _f->dependsOn(*static_cast(_ax->GetParent()))) { if (auto _boundaries = std::unique_ptr>(_f->binBoundaries( *dynamic_cast(_ax->GetParent()), -std::numeric_limits::infinity(), std::numeric_limits::infinity())); !_boundaries && _ax->GetNbins() > 0) { #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00) - Warning("Add", "Adding unbinned function %s to binned %s - will wrap it in a RooBinSamplingPdf", - _f->GetName(), GetName()); + Warning( + "Add", + "Adding unbinned function %s to binned %s - will wrap with RooRealSumPdf(RooBinSamplingPdf(...))", + _f->GetName(), GetName()); auto sumPdf = acquireNew(TString::Format("%s_pdfWrapper", _f->GetName()), _f->GetTitle(), - *_f, *acquire("1", "1", 1), true); + *_f, *acquire2("1", "1", 1), true); sumPdf->setStringAttribute("alias", _f->getStringAttribute("alias")); if (!sumPdf->getStringAttribute("alias")) sumPdf->setStringAttribute("alias", out->GetName()); @@ -1445,8 +1898,8 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) } } - p->_coefList.add(*acquire("1", "1", 1)); - p->_funcList.add(*_f); + const_cast(p->coefList()).add(*acquire2("1", "1", 1)); + const_cast(p->funcList()).add(*_f); // inherit binning if we dont have one yet if (!p->getStringAttribute("binning")) p->setStringAttribute("binning", _f->getStringAttribute("binning")); @@ -1463,18 +1916,23 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) } } sterilize(); + // clear children for reload and update shared axis + clear(); + fXAxis.reset(); + p->setStringAttribute("xvar", nullptr); + browse(); return _out; } } else if (auto p2 = get(); p2) { // can "add" to a RooProdPdf provided trying to add a RooAbsReal not a RooAbsPdf and have a zero or 1 // RooRealSumPdf child.convertForAcquisition(*this); - don't convert here because want generated objects named // after roorealsumpdf - if ((child.get() || child.get() || (!child.get() && getObject(child.GetName()))) && - !child.get()) { - RooRealSumPdf *_pdf = nullptr; + if (child.get() || (!child.get() && getObject(child.GetName()))) { + // can add if 0 or 1 RooAddPdf .... + RooAddPdf *_pdf = nullptr; bool tooMany(false); for (auto &pp : factors()) { - if (auto _p = pp->get(); _p) { + if (auto _p = pp->get(); _p) { if (_pdf) { _pdf = nullptr; tooMany = true; @@ -1486,34 +1944,54 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) if (_pdf) { return xRooNode(*_pdf, *this).Add(child); } else if (!tooMany) { - auto out = this->operator[]("samples")->Add(child); + auto out = this->operator[]("components")->Add(child); return out; } - } else if (child.get()) { - // can add if 0 or 1 RooAddPdf .... - RooAddPdf *_pdf = nullptr; + } else if ((child.get() || child.get() || + (!child.get() && getObject(child.GetName()))) && + !child.get()) { + RooRealSumPdf *_pdf = nullptr; + RooAddPdf *_backup = nullptr; bool tooMany(false); for (auto &pp : factors()) { - if (auto _p = pp->get(); _p) { + if (auto _p = pp->get(); _p) { if (_pdf) { _pdf = nullptr; tooMany = true; break; } // more than one! _pdf = _p; + } else if (auto _p2 = pp->get(); _p2) { + _backup = _p2; + for (auto &_pdfa : pp->components()) { + if (auto _p3 = _pdfa->get(); _p3) { + if (_pdf) { + _pdf = nullptr; + tooMany = true; + break; + } // more than one! + _pdf = _p3; + } + } } } if (_pdf) { return xRooNode(*_pdf, *this).Add(child); + } else if (_backup) { + // added *INSIDE* the addPdf -- will create a RooRealSumPdf to hold it + return xRooNode(*_backup, *this).Add(child); } else if (!tooMany) { - auto out = this->operator[]("components")->Add(child); + auto out = this->operator[]("samples")->Add(child); + // clear our x-axis to re-evaluate + fXAxis.reset(); + p2->setStringAttribute("xvar", nullptr); return out; } } } else if (auto s = get(); s) { - // adding to a simultaneous means adding a variation - return variations().Add(child); + // adding to a simultaneous means adding a bin + return bins().Add(child); // if the child is a RooAbsPdf can just add it as a new channel using name of pdf as the channel name // if child is a histogram, will create a RooProdPdf @@ -1584,7 +2062,9 @@ xRooNode xRooNode::Add(const xRooNode &child, Option_t *opt) if (considerType) { // interpret 'adding' here as dependent on the object type ... - if (get() || TString(child.GetName()).Contains('=')) { + if (get()) { + return bins().Add(child); + } else if (TString(child.GetName()).Contains('=')) { return variations().Add(child); } else if (get() || get()) { return factors().Add(child); @@ -1630,7 +2110,7 @@ xRooNode::~xRooNode() // std::cout << "deleting " << GetPath() << std::endl; } -void xRooNode::SetHidden(Bool_t set) +void xRooNode::SetHidden(bool set) { if (auto a = get()) { a->setAttribute("hidden", set); @@ -1702,7 +2182,7 @@ xRooNode xRooNode::shallowCopy(const std::string &name, std::shared_ptr(); s) { - auto chans = variations(); + auto chans = bins(); if (!chans.empty()) { // create a new RooSimultaneous with shallow copies of each channel @@ -1722,19 +2202,20 @@ xRooNode xRooNode::shallowCopy(const std::string &name, std::shared_ptr(o); p) { // main pdf will be copied too - std::shared_ptr pdf = std::dynamic_pointer_cast( - out.acquire(std::shared_ptr(p->Clone(name.c_str())))); // use clone to copy all attributes etc too + std::shared_ptr pdf = + std::dynamic_pointer_cast(out.acquire(std::shared_ptr(p->Clone(/*name.c_str()*/)), false, + true)); // use clone to copy all attributes etc too auto main = mainChild(); if (main) { - auto newMain = std::dynamic_pointer_cast( - out.acquire(std::shared_ptr(main->Clone((name + "_pdf").c_str())))); - pdf->replaceServer(*pdf->_pdfList.find(main->GetName()), *newMain, true, true); - pdf->_pdfList.replace(*pdf->_pdfList.find(main->GetName()), *newMain); - pdf->_cacheMgr.reset(); - pdf->setValueDirty(); - pdf->setNormRange(0); + auto newMain = + std::dynamic_pointer_cast(out.acquire(std::shared_ptr(main->Clone()), false, true)); + std::cout << newMain << " " << newMain->GetName() << std::endl; + // pdf->replaceServer(*pdf->pdfList().find(main->GetName()), *newMain, true, true); + // const_cast(pdf->pdfList()).replace(*pdf->pdfList().find(main->GetName()), *newMain); + pdf->redirectServers(RooArgList(*newMain)); } out.fComp = pdf; + out.sterilize(); return out; } @@ -1743,6 +2224,14 @@ xRooNode xRooNode::shallowCopy(const std::string &name, std::shared_ptr capture; + std::string captureStr; + bool doCapture = false; + if (!capture && gROOT->FromPopUp()) { // FromPopUp means user executed from the context menu + capture = std::make_unique(captureStr); + doCapture = true; + } + TString sOpt(opt); int depth = 0; if (sOpt.Contains("depth=")) { @@ -1764,9 +2253,8 @@ void xRooNode::Print(Option_t *opt) const std::cout << GetPath(); if (get() && get() != this) { std::cout << ": "; - if (_more || - (get() && (get()->isFundamental() || get() || get())) || - get()) { + if (_more || (get() && get()->isFundamental()) || get() || + get() || get() || get()) { auto _deps = coords(false).argList(); // want to revert coords after print auto _snap = std::unique_ptr(_deps.snapshot()); coords(); // move to coords before printing (in case this matters) @@ -1777,8 +2265,30 @@ void xRooNode::Print(Option_t *opt) const } _deps.assignValueOnly(*_snap); // std::cout << std::endl; - } else - std::cout << get()->ClassName() << "::" << get()->GetName() << std::endl; + } else { + TString _suffix = ""; + if (auto _type = GetNodeType(); strlen(_type)) { + // decided not to show const values until figure out how to update if value changes + /*if (TString(_type)=="Const") _name += TString::Format(" + [%s=%g]",_type,v->get()->getVal()); else*/ + _suffix += TString::Format(" [%s]", _type); + } + if (auto fv = get()) { + TString formu = TString::Format(" [%s]", fv->expression()); + for (size_t i = 0; i < fv->dependents().size(); i++) { + formu.ReplaceAll(TString::Format("x[%zu]", i), fv->dependents()[i].GetName()); + } + _suffix += formu; + } else if (auto gv = get()) { + TString formu = TString::Format(" [%s]", gv->expression()); + for (size_t i = 0; i < gv->dependents().size(); i++) { + formu.ReplaceAll(TString::Format("x[%zu]", i), gv->dependents()[i].GetName()); + } + _suffix += formu; + } + std::cout << get()->ClassName() << "::" << get()->GetName() << _suffix.Data() << std::endl; + } + } else if (!get()) { std::cout << std::endl; } @@ -1808,15 +2318,36 @@ void xRooNode::Print(Option_t *opt) const std::cout << " "; std::cout << i++ << ") " << k->GetName() << " : "; if (k->get()) { - if (_more || (k->get() && (k->get()->isFundamental() || k->get() || - k->get())) /*|| k->get()*/) { + if (_more || (k->get() && k->get()->isFundamental()) || k->get() || + k->get() /*|| k->get()*/) { auto _deps = k->coords(false).argList(); auto _snap = std::unique_ptr(_deps.snapshot()); k->coords(); // move to coords before printing (in case this matters) k->get()->Print(sOpt); // assumes finishes with an endl _deps.assignValueOnly(*_snap); - } else - std::cout << k->get()->ClassName() << "::" << k->get()->GetName() << std::endl; + } else { + TString _suffix = ""; + if (auto _type = k->GetNodeType(); strlen(_type)) { + // decided not to show const values until figure out how to update if value changes + /*if (TString(_type)=="Const") _name += TString::Format(" + [%s=%g]",_type,v->get()->getVal()); else*/ + _suffix += TString::Format(" [%s]", _type); + } + if (auto fv = k->get()) { + TString formu = TString::Format(" [%s]", fv->expression()); + for (size_t j = 0; j < fv->dependents().size(); j++) { + formu.ReplaceAll(TString::Format("x[%zu]", j), fv->dependents()[j].GetName()); + } + _suffix += formu; + } else if (auto gv = k->get()) { + TString formu = TString::Format(" [%s]", gv->expression()); + for (size_t j = 0; j < gv->dependents().size(); j++) { + formu.ReplaceAll(TString::Format("x[%zu]", j), gv->dependents()[j].GetName()); + } + _suffix += formu; + } + std::cout << k->get()->ClassName() << "::" << k->get()->GetName() << _suffix.Data() << std::endl; + } if (depth != 0) { k->Print(sOpt + TString::Format("depth=%dindent=%d", depth - 1, iindent + 1)); } @@ -1824,6 +2355,28 @@ void xRooNode::Print(Option_t *opt) const std::cout << " NULL " << std::endl; } } + if (doCapture) { + capture.reset(); // no captureStr has the string to display + // inject line breaks to avoid msgbox being too wide + size_t lastBreak = 0; + std::string captureStrWithBreaks; + for (size_t i = 0; i < captureStr.size(); i++) { + captureStrWithBreaks += captureStr[i]; + if (captureStr[i] == '\n') { + lastBreak = i; + } + if (i - lastBreak > 150) { + captureStrWithBreaks += '\n'; + lastBreak = i; + } + } + const TGWindow *w = + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(); + new TGMsgBox(gClient->GetRoot(), w, GetName(), + captureStrWithBreaks.c_str()); //,nullptr,kMBDismiss,nullptr,kVerticalFrame,kTextLeft|kTextCenterY); + } } xRooNode xRooNode::Constrain(const xRooNode &child) @@ -2009,20 +2562,25 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) i++; } } - // then scale the relevant bin ... if the relevent bin is a "1" then just drop in our factor (inside a + // then scale the relevant bin ... if the relevant bin is a "1" then just drop in our factor (inside a // RooProduct though, to avoid it getting modified by subsequent multiplies) auto _bin = binFactors->bins().at(fBinNumber - 1); if (auto phf = binFactors->get(); phf && _bin) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + RooArgList &pSet = phf->_paramSet; +#else + RooArgList &pSet = const_cast(phf->paramList()); +#endif if (strcmp(_bin->GetName(), "1") == 0) { RooArgList all; - for (int i = 0; i < phf->_paramSet.getSize(); i++) { + for (int i = 0; i < pSet.getSize(); i++) { if (i != fBinNumber - 1) - all.add(*phf->_paramSet.at(i)); + all.add(*pSet.at(i)); else all.add(*o); } - phf->_paramSet.removeAll(); - phf->_paramSet.add(all); + pSet.removeAll(); + pSet.add(all); } else { _bin->fBinNumber = -1; // to avoid infinite loop return _bin->Multiply(child, opt); @@ -2074,6 +2632,18 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), o->ClassName(), o->GetName()); return out; } else if (sOpt == "norm") { + if (TString(child.GetName()).Contains("[") && ws()) { + // assume factory method wanted + auto arg = ws()->factory(child.GetName()); + if (arg) { + auto out = Multiply(*arg); + if (get()) + Info("Multiply", "Scaled %s by new norm factor %s", + mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName()); + return out; + } + throw std::runtime_error(TString::Format("Failed to create new normFactor %s", child.GetName())); + } auto out = Multiply(RooRealVar(child.GetName(), child.GetTitle(), 1, -1e-5, 100)); if (get()) Info("Multiply", "Scaled %s by new norm factor %s", @@ -2115,11 +2685,6 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName()); return out; } - // auto out = Multiply( - // acquireNew("exprFactor",child.GetName(),child.GetName(),ws()->_allOwnedNodes,false /* don't - // check dependents all feature */) ); Info("Multiply","Scaled %s by new expr factor %s",mainChild().get() ? - // mainChild().get()->GetName() : get()->GetName(),out->GetName()); return out; - // acquire(std::make_shared("expr::%s_%s")) } } if (auto h = child.get(); h && strlen(h->GetOption()) == 0 && strlen(opt) > 0) { @@ -2135,12 +2700,12 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) return out; } - if (strcmp(GetName(), ".coefs") == 0) { + if (strcmp(GetName(), ".coef") == 0) { // covers both .coef and .coefs // need to add this into the relevant coef ... if its not a RooProduct, replace it with one first if (auto p = fParent->fParent->get()) { for (size_t i = 0; i < p->pdfList().size(); i++) { if (p->pdfList().at(i) == fParent->get()) { - auto coefs = p->_coefList.at(i); + auto coefs = p->coefList().at(i); if (!coefs->InheritsFrom("RooProduct")) { RooArgList oldCoef; if (!(strcmp(coefs->GetName(), "1") == 0 || strcmp(coefs->GetName(), "ONE") == 0)) @@ -2149,14 +2714,14 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) TString::Format("coefs_%s", fParent->GetName()), TString::Format("coefficients for %s", fParent->GetName()), oldCoef); RooArgList oldCoefs; - for (size_t j = 0; j < p->_coefList.size(); j++) { + for (size_t j = 0; j < p->coefList().size(); j++) { if (i == j) oldCoefs.add(*newCoefs); else - oldCoefs.add(*p->_coefList.at(j)); + oldCoefs.add(*p->coefList().at(j)); } - p->_coefList.removeAll(); - p->_coefList.add(oldCoefs); + const_cast(p->coefList()).removeAll(); + const_cast(p->coefList()).add(oldCoefs); coefs = newCoefs.get(); } return xRooNode(*coefs, fParent).Multiply(child); @@ -2212,7 +2777,11 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) } if (auto _f = std::dynamic_pointer_cast(out); _f) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) p->_compRSet.add(*_f); +#else + const_cast(p->realComponents()).add(*_f); +#endif p->setValueDirty(); browse(); @@ -2280,7 +2849,8 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) } if (auto _pdf = std::dynamic_pointer_cast(out); _pdf) { - p2->_pdfList.add(*_pdf); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + const_cast(p2->pdfList()).add(*_pdf); #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00) p2->_pdfNSetList.emplace_back(std::make_unique("nset")); #else @@ -2289,11 +2859,10 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) if (!p2->canBeExtended() && _pdf->canBeExtended()) { p2->_extendedIndex = p2->_pdfList.size() - 1; } - // TODO: any more cleanup? +#else + p2->addPdfs(RooArgSet(*_pdf)); +#endif sterilize(); - p2->_cacheMgr.reset(); - p2->setValueDirty(); - p2->setNormRange(0); browse(); return xRooNode(_pdf, *this); } @@ -2368,6 +2937,54 @@ xRooNode xRooNode::Multiply(const xRooNode &child, Option_t *opt) (!child.get() && strlen(opt) == 0) ? " (forgot to specify factor type?)" : "")); } +xRooNode xRooNode::Replace(const xRooNode &node) +{ + + auto p5 = get(); + if (!p5) { + throw std::runtime_error("Only replacement of RooAbsArg is supported"); + } + node.convertForAcquisition(*this, "func"); + + auto new_p = node.get(); + if (!new_p) { + throw std::runtime_error(TString::Format("Cannot replace with %s", node.GetName())); + } + auto out = acquire(node.fComp); + new_p = std::dynamic_pointer_cast(out).get(); + + std::set cl; + for (auto &arg : p5->clients()) { + if (arg == new_p) + continue; // do not replace in self ... although redirectServers will prevent that anyway + cl.insert(arg); + } + + // if multiple clients, see if only one client is in parentage route + // if so, then assume thats the only client we should replace in + if (cl.size() > 1) { + if (fParent && fParent->get() && cl.count(fParent->get()) > 0) { + cl.clear(); + cl.insert(fParent->get()); + } else { + std::stringstream clientList; + for (auto c : cl) + clientList << c->GetName() << ","; + Warning("Replace", "Replacing %s in all clients: %s", p5->GetName(), clientList.str().c_str()); + } + } + + new_p->setAttribute(Form("ORIGNAME:%s", p5->GetName())); // used in redirectServers to say what this replaces + for (auto arg : cl) { + // if RooFormulaVar need to ensure the internal formula has been "constructed" otherwise will try to construct + // it from the original expression that may have old parameter in it. + if (auto p = dynamic_cast(arg)) + p->ok(); // triggers creation of RooFormula + arg->redirectServers(RooArgSet(*new_p), false, true); + } + return node; +} + xRooNode xRooNode::Vary(const xRooNode &child) { @@ -2397,13 +3014,13 @@ xRooNode xRooNode::Vary(const xRooNode &child) return p.Vary(child); } - if (auto s = get(); s) { + if (auto s = get(); s && s->indexCat().IsA() == RooCategory::Class()) { // name is used as cat label std::string label = child.GetName(); if (auto pos = label.find("="); pos != std::string::npos) label = label.substr(pos + 1); if (!s->indexCat().hasLabel(label)) { - const_cast(s->indexCat()).defineType(label.c_str()); + static_cast(const_cast(s->indexCat())).defineType(label.c_str()); } std::shared_ptr out; child.convertForAcquisition(*this); @@ -2418,6 +3035,9 @@ xRooNode xRooNode::Vary(const xRooNode &child) if (auto _pdf = std::dynamic_pointer_cast(out); _pdf) { s->addPdf(*_pdf, label.c_str()); sterilize(); + // clear children for reload and update shared axis + clear(); + fXAxis.reset(); browse(); return xRooNode(TString::Format("%s=%s", s->indexCat().GetName(), label.data()), _pdf, *this); } @@ -2430,7 +3050,13 @@ xRooNode xRooNode::Vary(const xRooNode &child) if (!_c && child.get()) { throw std::runtime_error("Only pure consts can be set as variations of a flexible interpvar"); } +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) double value = (_c ? _c->getVal() : p->_nominal); + double nomVal = p->_nominal; +#else + double value = (_c ? _c->getVal() : p->nominal()); + double nomVal = p->nominal(); +#endif TString cName(child.GetName()); if (cName == "nominal") { @@ -2457,23 +3083,30 @@ xRooNode xRooNode::Vary(const xRooNode &child) v->setError(1); if (!p->findServer(*v)) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) p->_paramList.add(*v); p->_low.push_back(0); p->_high.push_back(0); p->_interpCode.push_back(4); +#else + const_cast(p->variables()).add(*v); + const_cast &>(p->low()).push_back(0); + const_cast &>(p->high()).push_back(0); + const_cast &>(p->interpolationCodes()).push_back(4); +#endif v->setAttribute(Form("SYMMETRIC%s_%s", high ? "+" : "-", GetName())); // flag for symmetrized } if (high) { p->setHigh(*v, value); if (v->getAttribute(Form("SYMMETRIC+_%s", GetName()))) { - p->setLow(*v, 2 * p->_nominal - value); + p->setLow(*v, 2 * nomVal - value); } v->setAttribute(Form("SYMMETRIC-_%s", GetName()), false); } else { p->setLow(*v, value); if (v->getAttribute(Form("SYMMETRIC-_%s", GetName()))) { - p->setHigh(*v, 2 * p->_nominal - value); + p->setHigh(*v, 2 * nomVal - value); } v->setAttribute(Form("SYMMETRIC+_%s", GetName()), false); } @@ -2493,11 +3126,19 @@ xRooNode xRooNode::Vary(const xRooNode &child) if (parVal != 1 && parVal != -1) { throw std::runtime_error("unsupported variation magnitude"); } - +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) RooHistFunc *f = dynamic_cast(p2->_nominal.absArg()); - if (!f) + if (!f) { throw std::runtime_error( TString::Format("Interpolating %s instead of RooHistFunc", p2->_nominal.absArg()->ClassName())); + } +#else + RooHistFunc *f = dynamic_cast(const_cast(p2->nominalHist())); + if (!f) { + throw std::runtime_error( + TString::Format("Interpolating %s instead of RooHistFunc", p2->nominalHist()->ClassName())); + } +#endif RooHistFunc *nomf = f; RooHistFunc *otherf = nullptr; size_t i = 0; @@ -2516,19 +3157,35 @@ xRooNode xRooNode::Vary(const xRooNode &child) if (!v->hasError()) v->setError(1); - auto up = dynamic_cast(f->Clone(Form("%s_%s_up", f->GetName(), parName.Data()))); - auto down = dynamic_cast(f->Clone(Form("%s_%s_down", f->GetName(), parName.Data()))); - // RooHistFunc doesn't clone it's data hist ... do it ourself - auto h1 = up->_dataHist = dynamic_cast(f->dataHist().Clone(Form("hist_%s", up->GetName()))); - auto h2 = down->_dataHist = dynamic_cast(f->dataHist().Clone(Form("hist_%s", down->GetName()))); - - auto ups = std::dynamic_pointer_cast(acquire(std::shared_ptr(up), false, true)); - auto downs = std::dynamic_pointer_cast(acquire(std::shared_ptr(down), false, true)); - + std::shared_ptr up( + static_cast(f->Clone(Form("%s_%s_up", f->GetName(), parName.Data())))); + std::shared_ptr down( + static_cast(f->Clone(Form("%s_%s_down", f->GetName(), parName.Data())))); + // RooHistFunc doesn't clone it's data hist ... do it ourself (will be cloned again if imported into a ws) +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + std::unique_ptr h1( + static_cast(f->dataHist().Clone(Form("hist_%s", up->GetName())))); + std::unique_ptr h2( + static_cast(f->dataHist().Clone(Form("hist_%s", down->GetName())))); + up->_dataHist = dynamic_cast(f->dataHist().Clone(Form("hist_%s", up->GetName()))); + down->_dataHist = dynamic_cast(f->dataHist().Clone(Form("hist_%s", down->GetName()))); +#else + up->cloneAndOwnDataHist(TString::Format("hist_%s", up->GetName())); + down->cloneAndOwnDataHist(TString::Format("hist_%s", down->GetName())); +#endif + auto ups = std::dynamic_pointer_cast(acquire(up, false, true)); + auto downs = std::dynamic_pointer_cast(acquire(down, false, true)); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) p2->_highSet.add(*ups.get()); p2->_lowSet.add(*downs.get()); p2->_interpCode.push_back(4); p2->_paramSet.add(*v); +#else + const_cast(p2->highList()).add(*ups.get()); + const_cast(p2->lowList()).add(*downs.get()); + const_cast &>(p2->interpolationCodes()).push_back(4); + const_cast(p2->paramList()).add(*v); +#endif p2->setValueDirty(); f = ((parVal > 0) ? ups : downs).get(); otherf = ((parVal > 0) ? downs : ups).get(); @@ -2536,8 +3193,6 @@ xRooNode xRooNode::Vary(const xRooNode &child) f->setStringAttribute("symmetrizes", otherf->GetName()); f->setStringAttribute("symmetrize_nominal", nomf->GetName()); otherf->setStringAttribute("symmetrized_by", f->GetName()); - delete h1; - delete h2; // constrain par if required /*if (!unconstrained && fParent->pars()[v->GetName()].constraints().empty()) { @@ -2645,12 +3300,12 @@ xRooNode xRooNode::Vary(const xRooNode &child) throw std::runtime_error(TString::Format("Cannot vary %s with %s", GetName(), child.GetName())); } -bool xRooNode::SetContents(double value) +bool xRooNode::SetContent(double value) { return SetContents(RooConstVar(GetName(), GetTitle(), value)); } -bool xRooNode::SetContents(double value, const char *par, double val) +bool xRooNode::SetContent(double value, const char *par, double val) { return SetContents(RooConstVar(GetName(), GetTitle(), value), par, val); } @@ -2734,6 +3389,9 @@ xRooNode &xRooNode::operator=(const TObject &o) (a && a->isFundamental()) || get() || get()) { SetBinContent(1, _c->getVal()); return *this; + } else if (get()) { // try to do assignment to a dataset (usually setting a bin content) + SetBinContent(0, _c->getVal()); + return *this; } } @@ -2761,7 +3419,7 @@ xRooNode &xRooNode::operator=(const TObject &o) */ } -void xRooNode::_fitTo_(const char *datasetName, const char *constParValues) +void xRooNode::_fit_(const char *constParValues) { try { auto _pars = pars(); @@ -2775,12 +3433,22 @@ void xRooNode::_fitTo_(const char *datasetName, const char *constParValues) for (auto p : _pars.argList()) { if (TString(p->GetName()).Contains(TRegexp(pat, true))) { p->setAttribute("Constant", true); - if (std::isnan(val)) + if (!std::isnan(val)) { dynamic_cast(p)->setVal(val); + } } } } - auto _nll = nll(datasetName); + // use the first selected dataset + auto _dsets = datasets(); + TString dsetName = ""; + for (auto &d : _dsets) { + if (d->get()->TestBit(1 << 20)) { + dsetName = d->get()->GetName(); + break; + } + } + auto _nll = nll(dsetName.Data()); _nll.fitConfigOptions()->SetValue("LogSize", 65536); _nll.fitConfig()->MinimizerOptions().SetPrintLevel(0); auto fr = _nll.minimize(); @@ -2788,15 +3456,36 @@ void xRooNode::_fitTo_(const char *datasetName, const char *constParValues) if (!fr.get()) throw std::runtime_error("Fit Failed"); SetFitResult(fr.get()); - if (fr->status() != 0) - new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Fit Finished", - TString::Format("Fit Status Code = %d", fr->status()), kMBIconExclamation); - else - new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Fit Finished", - TString::Format("Fit Status Code = %d", fr->status())); + TString statusCodes; + for (unsigned int i = 0; i < fr->numStatusHistory(); i++) { + statusCodes += TString::Format("\n%s = %d", fr->statusLabelHistory(i), fr->statusCodeHistory(i)); + } + const TGWindow *w = + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(); + if (fr->status() != 0) { + new TGMsgBox(gClient->GetRoot(), w, "Fit Finished with Bad Status Code", + TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n-------------%s", + fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), statusCodes.Data()), + kMBIconExclamation, kMBOk); + } else if (fr->covQual() != 3 && _nll.fitConfig()->ParabErrors()) { + new TGMsgBox(gClient->GetRoot(), w, "Fit Finished with Bad Covariance Quality", + TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n-------------%s", + fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), statusCodes.Data()), + kMBIconExclamation, kMBOk); + } else { + new TGMsgBox(gClient->GetRoot(), w, "Fit Finished Successfully", + TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n-------------%s", + fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), statusCodes.Data())); + } } catch (const std::exception &e) { - new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(), - kMBIconExclamation); // deletes self on dismiss? + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Exception", e.what(), kMBIconExclamation, kMBOk); // deletes self on dismiss? } } @@ -2805,8 +3494,83 @@ void xRooNode::_generate_(const char *datasetName, bool expected) try { datasets().Add(datasetName, expected ? "asimov" : "toy"); } catch (const std::exception &e) { - new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(), - kMBIconExclamation); // deletes self on dismiss? + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Exception", e.what(), + kMBIconExclamation); // deletes self on dismiss? + } +} + +void xRooNode::_scan_(const char *what, double nToys, const char *xvar, int nBinsX, double lowX, + double highX /*, const char*, int, double, double*/, const char *constParValues) +{ + try { + TString sXvar(xvar); + TString sWhat(what); + + // use the first selected dataset + auto _dsets = datasets(); + TString dsetName = ""; + for (auto &d : _dsets) { + if (d->get()->TestBit(1 << 20)) { + dsetName = d->get()->GetName(); + break; + } + } + auto _pars = pars(); + std::unique_ptr snap(_pars.argList().snapshot()); + TStringToken pattern(constParValues, ","); + while (pattern.NextToken()) { + auto idx = pattern.Index('='); + TString pat = (idx == -1) ? TString(pattern) : TString(pattern(0, idx)); + double val = + (idx == -1) ? std::numeric_limits::quiet_NaN() : TString(pattern(idx + 1, pattern.Length())).Atof(); + for (auto par : _pars.argList()) { + if (TString(par->GetName()).Contains(TRegexp(pat, true))) { + par->setAttribute("Constant", true); + if (!std::isnan(val)) { + dynamic_cast(par)->setVal(val); + } + } + } + } + auto hs = nll(dsetName.Data()).hypoSpace(sXvar); + if (nToys) { + sWhat += " toys"; + if (nToys > 0) { + sWhat += TString::Format("=%g", nToys); + } + } + hs.SetTitle(sWhat + " scan" + ((dsetName != "") ? TString::Format(" [data=%s]", dsetName.Data()) : "")); + int scanStatus = hs.scan(sWhat + " visualize", nBinsX, lowX, highX); + if (scanStatus != 0) { + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Scan Finished with Bad Status Code", + TString::Format("%s\nData = %s\nScan Status Code = %d", hs.GetName(), dsetName.Data(), scanStatus), + kMBIconExclamation, kMBOk); + } + hs.SetName(TUUID().AsString()); + if (ws()) { + if (auto res = hs.result()) + ws()->import(*res); + } + + _pars.argList() = *snap; // restore pars + + } catch (const std::exception &e) { + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Exception", e.what(), kMBIconExclamation); } } @@ -2820,10 +3584,10 @@ void xRooNode::_SetBinContent_(int bin, double value, const char *par, double pa } } -void xRooNode::_SetContents_(double value) +void xRooNode::_SetContent_(double value) { try { - if (!SetContents(value)) + if (!SetContent(value)) throw std::runtime_error("Failed to SetContent"); } catch (const std::exception &e) { new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(), @@ -2864,11 +3628,11 @@ bool xRooNode::SetBinContent(int bin, double value, const char *par, double parV if (get()) { if (auto _data = get(); _data) { - auto _ax = GetXaxis(); - if (!_ax) { + auto _ax = (bin) ? GetXaxis() : nullptr; + if (!_ax && bin) { throw std::runtime_error("Cannot determine binning to fill data"); } - if (_ax->GetNbins() < bin) + if (_ax && _ax->GetNbins() < bin) throw std::out_of_range(TString::Format("%s range %s only has %d bins", _ax->GetParent()->GetName(), _ax->GetName(), _ax->GetNbins())); RooArgSet obs; @@ -2881,6 +3645,14 @@ bool xRooNode::SetBinContent(int bin, double value, const char *par, double parV cut += " && "; cut += TString::Format("%s==%d", _cat->GetName(), _cat->getCurrentIndex()); obs.add(*_cat); // note: if we ever changed coords to return clones, would need to keep coords alive + } else if (auto _rv = _c->get(); _rv) { + // todo: check coordRange is a single range rather than multirange + if (cut != "") + cut += " && "; + cut += + TString::Format("%s>=%f&&%s<%f", _rv->GetName(), _rv->getMin(_rv->getStringAttribute("coordRange")), + _rv->GetName(), _rv->getMax(_rv->getStringAttribute("coordRange"))); + obs.add(*_rv); // note: if we ever changed coords to return clones, would need to keep coords alive } else { throw std::runtime_error("SetBinContent of data: Unsupported coordinate type"); } @@ -2889,10 +3661,14 @@ bool xRooNode::SetBinContent(int bin, double value, const char *par, double parV RooFormulaVar cutFormula("cut1", cut, obs); // doing this to avoid complaints about unused vars RooFormulaVar icutFormula("icut1", TString::Format("!(%s)", cut.Data()), obs); - TString cut2 = TString::Format("%s >= %f && %s < %f", _ax->GetParent()->GetName(), _ax->GetBinLowEdge(bin), - _ax->GetParent()->GetName(), _ax->GetBinUpEdge(bin)); - obs.add(*dynamic_cast(_ax->GetParent())); - + TString cut2; + if (_ax) { + cut2 = TString::Format("%s >= %f && %s < %f", _ax->GetParent()->GetName(), _ax->GetBinLowEdge(bin), + _ax->GetParent()->GetName(), _ax->GetBinUpEdge(bin)); + obs.add(*dynamic_cast(_ax->GetParent())); + } else { + cut2 = "1==1"; + } RooFormulaVar cutFormula2("cut2", cut + " && " + cut2, obs); RooFormulaVar icutFormula2("icut2", TString::Format("!(%s && %s)", cut.Data(), cut2.Data()), obs); @@ -2954,28 +3730,29 @@ bool xRooNode::SetBinContent(int bin, double value, const char *par, double parV // using SetBinContent means dataset must take on a binned form at these coordinates // if number of entries doesnt match number of bins then will 'bin' the data - if (auto _nentries = std::unique_ptr(_data->reduce(cutFormula))->numEntries(); - _nentries != _ax->GetNbins()) { - auto _contents = GetBinContents(1, _ax->GetNbins()); - - if (_nentries > 0) { - Info("SetBinContent", "Binning %s in channel: %s", GetName(), cut.Data()); - auto _reduced = std::unique_ptr(_data->reduce(icutFormula)); - _data->reset(); - for (int j = 0; j < _reduced->numEntries(); j++) { - auto _obs = _reduced->get(j); - _data->add(*_obs, _reduced->weight()); + if (bin) { + if (auto _nentries = std::unique_ptr(_data->reduce(cutFormula))->numEntries(); + _nentries != _ax->GetNbins()) { + auto _contents = GetBinContents(1, _ax->GetNbins()); + + if (_nentries > 0) { + Info("SetBinContent", "Binning %s in channel: %s", GetName(), cut.Data()); + auto _reduced = std::unique_ptr(_data->reduce(icutFormula)); + _data->reset(); + for (int j = 0; j < _reduced->numEntries(); j++) { + auto _obs = _reduced->get(j); + _data->add(*_obs, _reduced->weight()); + } + } + for (int i = 1; i <= _ax->GetNbins(); i++) { + // can skip over the bin we will be setting to save a reduce step below + if (i == bin) + continue; + dynamic_cast(_ax->GetParent())->setBin(i - 1, _ax->GetName()); + _data->add(obs, _contents.at(i - 1)); } - } - for (int i = 1; i <= _ax->GetNbins(); i++) { - // can skip over the bin we will be setting to save a reduce step below - if (i == bin) - continue; - dynamic_cast(_ax->GetParent())->setBin(i - 1, _ax->GetName()); - _data->add(obs, _contents.at(i - 1)); } } - // remove existing entries if (std::unique_ptr(_data->reduce(cutFormula2))->numEntries() > 0) { auto _reduced = std::unique_ptr(_data->reduce(icutFormula2)); @@ -2985,8 +3762,11 @@ bool xRooNode::SetBinContent(int bin, double value, const char *par, double parV _data->add(*_obs, _reduced->weight()); } } - dynamic_cast(_ax->GetParent())->setBin(bin - 1, _ax->GetName()); + if (_ax) + dynamic_cast(_ax->GetParent())->setBin(bin - 1, _ax->GetName()); _data->add(obs, value); + if (auto bb = getBrowsable(".sourceds")) + return bb->SetBinContent(bin, value, par, parVal); // apply to source ds if we have one return true; } else if (get()) { @@ -3075,6 +3855,11 @@ bool xRooNode::SetBinData(int bin, double value, const char *dataName) return datasets()[dataName]->SetBinContent(bin, value); } +bool xRooNode::SetData(const TObject &obj, const char *dataName) +{ + return datasets()[dataName]->SetContents(obj); +} + bool xRooNode::SetBinError(int bin, double value) { @@ -3162,21 +3947,26 @@ bool xRooNode::SetBinError(int bin, double value) auto newVar = (value == 0) ? getObject("1") : acquire(Form("%s_bin%d", prefix.Data(), bin), Form("%s_bin%d", prefix.Data(), bin), 1); - auto var = dynamic_cast(&phf->_paramSet[bin - 1]); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + RooArgList &pSet = phf->_paramSet; +#else + RooArgList &pSet = const_cast(phf->paramList()); +#endif + auto var = dynamic_cast(&pSet[bin - 1]); if (newVar.get() != var) { // need to swap out var for newVar // replace ith element in list with new func, or inject into RooProduct RooArgList all; - for (int i = 0; i < phf->_paramSet.getSize(); i++) { + for (int i = 0; i < pSet.getSize(); i++) { if (i != bin - 1) - all.add(*phf->_paramSet.at(i)); + all.add(*pSet.at(i)); else { all.add(*newVar); } } - phf->_paramSet.removeAll(); - phf->_paramSet.add(all); + pSet.removeAll(); + pSet.add(all); } xRooNode v((value == 0) ? *var : *newVar, *this); @@ -3216,7 +4006,7 @@ bool xRooNode::SetBinError(int bin, double value) double _max = tau * (1. + 5. * sqrt(1. / tau)); _glob->setRange(_min, _max); _glob->setVal(tau); - _constr.at(0)->args().at(0)->SetBinContent(0, tau); + _constr.at(0)->pp().at(0)->SetBinContent(0, tau); rrv->setStringAttribute("boundConstraint", _constr.at(0)->get()->GetName()); } rrv->setRange(std::max((1. - 5. * sqrt(1. / tau)), 1e-15), 1. + 5. * sqrt(1. / tau)); @@ -3238,21 +4028,20 @@ bool xRooNode::SetBinError(int bin, double value) throw std::runtime_error(TString::Format("%s SetBinError failed", GetName())); } -std::shared_ptr xRooNode::find(const std::string &name) const +std::shared_ptr xRooNode::at(const std::string &name, bool browseResult) const { - try { - return at(name); - } catch (std::out_of_range &) { - return nullptr; - } + auto res = find(name, browseResult); + if (res == nullptr) + throw std::out_of_range(name + " does not exist"); + return res; } RooWorkspace *xRooNode::ws() const { if (auto _w = get(); _w) return _w; - if (auto a = get(); a && a->_myws) { - return a->_myws; + if (auto a = get(); a && GETWS(a)) { + return GETWS(a); } if (fParent) return fParent->ws(); @@ -3264,23 +4053,30 @@ xRooNode xRooNode::constraints() const xRooNode out(".constraints", nullptr, *this); - std::function getConstraint; - getConstraint = [&](const xRooNode &n, RooAbsArg &par, RooAbsPdf *ignore) { - // std::cout << "Getting constraint of "<< n.GetName() << std::endl; + std::function ignore)> getConstraint; + getConstraint = [&](const xRooNode &n, RooAbsArg &par, std::set ignore) { + if (auto _pdf = n.get()) { + if (ignore.count(_pdf)) + return (RooAbsPdf *)nullptr; + ignore.insert(_pdf); + } auto o = n.get(); if (!o) { - if (n.get() || (n.get() && n.fParent && n.fParent->get())) { - // if at top-level or is a simultaneous, check all channels for a constraint - for (auto &c : n.variations()) { - if (auto oo = getConstraint(*c.get(), par, nullptr); oo) { + if (n.get()) { + // check all channels for a constraint if is simultaneous + for (auto &c : n.bins()) { + if (auto oo = getConstraint(*c.get(), par, ignore); oo) { return oo; } } return (RooAbsPdf *)nullptr; + } else if (n.get() && n.fParent && n.fParent->get()) { + // reached top-level pdf, which wasn't a simultaneous, so stop here + return (RooAbsPdf *)nullptr; } else if (auto _ws = n.get(); _ws) { // reached a workspace, check for any pdf depending on parameter that isnt the ignore for (auto p : _ws->allPdfs()) { - if (p == ignore) + if (ignore.count(static_cast(p))) continue; if (p->dependsOn(par)) { out.emplace_back(std::make_shared(par.GetName(), *p, *this)); @@ -3289,10 +4085,10 @@ xRooNode xRooNode::constraints() const } if (!n.fParent) return (RooAbsPdf *)nullptr; - return getConstraint(*n.fParent.get(), par, n.get()); + return getConstraint(*n.fParent.get(), par, ignore); } for (auto p : o->pdfList()) { - if (p == ignore) + if (ignore.count(static_cast(p))) continue; if (p->dependsOn(par)) { out.emplace_back(std::make_shared(par.GetName(), *p, *this)); @@ -3305,11 +4101,11 @@ xRooNode xRooNode::constraints() const auto v = dynamic_cast(p->get()); if (!v) continue; - if (v->getAttribute("Constant")) - continue; // skip constants ? + if (v->getAttribute("Constant") && v != get()) + continue; // skip constants unless we are getting the constraints of a parameter itself if (v->getAttribute("obs")) continue; // skip observables ... constraints constrain pars not obs - getConstraint(*this, *v, get()); + getConstraint(*this, *v, {get()}); /*if (auto c = ; c) { out.emplace_back(std::make_shared(p->GetName(), *c, *this)); }*/ @@ -3317,8 +4113,8 @@ xRooNode xRooNode::constraints() const // finish by removing any constraint that contains another constraint for the same par // and consolidate common pars - auto it = out.begin(); - while (it != out.end()) { + auto it = out.std::vector>::begin(); + while (it != out.std::vector>::end()) { bool removeIt = false; for (auto &c : out) { if (c.get() == it->get()) @@ -3458,9 +4254,9 @@ std::shared_ptr xRooNode::convertForAcquisition(xRooNode &acquirer, con } else if (sOpt2.Contains("shape")) { RooArgList list; for (int i = 0; i < x->getBinning(binningName.c_str()).numBins(); i++) { - std::shared_ptr arg; + std::shared_ptr arg; if (sOpt2.Contains("blankshape")) { - arg = acquirer.acquire("1", "1", 1); + arg = acquirer.acquire2("1", "1", 1); } else { if (!h) { arg = acquirer.acquireNew(TString::Format("%s_bin%d", newObjName.Data(), i + 1), "", 1); @@ -3481,8 +4277,13 @@ std::shared_ptr xRooNode::convertForAcquisition(xRooNode &acquirer, con auto tmp = dynamic_cast(x->getBinningPtr(0)->Clone()); x->setBinning(x->getBinning(binningName.c_str())); _f = acquirer.acquireNew(newObjName, h->GetTitle(), *x, list); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) dynamic_cast(_f.get())->_paramSet.setName("paramSet"); // so can see when print - x->setBinning(*tmp); // restore binning +#else + const_cast(dynamic_cast(_f.get())->paramList()) + .setName("paramSet"); // so can see when print +#endif + x->setBinning(*tmp); // restore binning delete tmp; for (auto &[k, v] : stringAttrs) { _f->setStringAttribute(k.c_str(), v.c_str()); @@ -3534,7 +4335,7 @@ std::shared_ptr xRooNode::convertForAcquisition(xRooNode &acquirer, con return fComp; } -std::shared_ptr xRooNode::style(TObject *initObject) const +std::shared_ptr xRooNode::style(TObject *initObject, bool autoCreate) const { auto arg = get(); @@ -3542,14 +4343,21 @@ std::shared_ptr xRooNode::style(TObject *initObject) const return nullptr; } + std::unique_ptr argInitObject; + TString t = GetTitle(); if (initObject) { t = (strlen(initObject->GetTitle())) ? initObject->GetTitle() : initObject->GetName(); } else if (arg) { if (arg->getStringAttribute("style")) t = arg->getStringAttribute("style"); - else + else if (autoCreate) { + // args will default to histo's object styling, whatever that currently may be + argInitObject = std::make_unique(GetName(), GetTitle(), 1, 0, 1); + initObject = argInitObject.get(); + } else { return nullptr; + } } std::shared_ptr style; // use to keep alive for access from GetStyle below, in case getObject has decided to @@ -3559,6 +4367,8 @@ std::shared_ptr xRooNode::style(TObject *initObject) const // loaded style (from workspace?) so put in list and use that gROOT->GetListOfStyles()->Add(style.get()); } else { + if (!autoCreate) + return nullptr; // create new style - gets put in style list automatically so don't have to delete // acquire them so saved to workspaces for auto reload ... style = const_cast(*this).acquireNew(t.Data(), @@ -3613,7 +4423,7 @@ std::shared_ptr xRooNode::acquire(const std::shared_ptr &arg, } } if (!done && _ws->import(*a, RooFit::RecycleConflictNodes())) { - if (a->_myws != _ws) { + if (GETWS(a) != _ws) { Info("acquire", "A copy of %s has been added to workspace %s", a->GetName(), _ws->GetName()); } RooMsgService::instance().setGlobalKillBelow(msglevel); @@ -3621,15 +4431,17 @@ std::shared_ptr xRooNode::acquire(const std::shared_ptr &arg, } // sanitizeWS(); // clears the caches that might exist up to now, as well interfere with getParameters calls std::set setNames; - for (auto &aa : _ws->_namedSets) { + for (auto &aa : GETWSSETS(_ws)) { if (TString(aa.first.c_str()).BeginsWith("CACHE_")) { setNames.insert(aa.first); } } for (auto &aa : setNames) ws()->removeSet(aa.c_str()); - out_arg = _ws->arg(a->GetName()); + if (GETWS(out_arg) != _ws) { // seems that when objects imported their ws isn't set + out_arg->setWorkspace(*_ws); + } } RooMsgService::instance().setGlobalKillBelow(msglevel); return std::shared_ptr(out_arg, [](TObject *) {}); @@ -3641,9 +4453,24 @@ std::shared_ptr xRooNode::acquire(const std::shared_ptr &arg, RooMsgService::instance().setGlobalKillBelow(msglevel); return std::shared_ptr(_ws->embeddedData(arg->GetName()), [](TObject *) {}); } else if (arg->InheritsFrom("RooFitResult") || arg->InheritsFrom("TTree") || arg->IsA() == TStyle::Class()) { - if (_ws->import(*arg.get(), true /*replace existing*/)) { - RooMsgService::instance().setGlobalKillBelow(msglevel); - return nullptr; + // ensure will have a unique name for import if must be new + TNamed *aNamed = dynamic_cast(arg.get()); + TString aName = arg->GetName(); + TObject *out_arg = _ws->genobj(arg->GetName()); + int ii = 1; + while (aNamed && out_arg && mustBeNew) { + aNamed->SetName(TString::Format("%s;%d", aName.Data(), ii++)); + out_arg = _ws->genobj(aNamed->GetName()); + } + if (!out_arg) { + if (aName != arg->GetName()) { + Warning("acquire", "Renaming to %s", arg->GetName()); + } + if (_ws->import(*arg.get(), false /*replace existing*/)) { + RooMsgService::instance().setGlobalKillBelow(msglevel); + return nullptr; + } + out_arg = _ws->genobj(arg->GetName()); } RooMsgService::instance().setGlobalKillBelow(msglevel); /* this doesnt work because caller has its own version of fParent, not the one in the browser @@ -3661,13 +4488,13 @@ std::shared_ptr xRooNode::acquire(const std::shared_ptr &arg, } } }*/ - return std::shared_ptr(_ws->genobj(arg->GetName()), [](TObject *) {}); + return std::shared_ptr(out_arg, [](TObject *) {}); } RooMsgService::instance().setGlobalKillBelow(msglevel); // Warning("acquire","Not implemented acquisition of object %s",arg->GetName()); // return nullptr; } - if (fProvider) { + if (!mustBeNew && fProvider) { auto out = fProvider->getObject(arg->GetName(), arg->ClassName()); if (out) return out; @@ -3678,9 +4505,11 @@ std::shared_ptr xRooNode::acquire(const std::shared_ptr &arg, } // look for exact name, dont use 'find' because doesnt work if trying to find "1" and it doesn't exist, will get back // idx 1 instead - for (auto &r : *_owned) { - if (strcmp(r->GetName(), arg->GetName()) == 0 && strcmp(r->get()->ClassName(), arg->ClassName()) == 0) { - return r->fComp; + if (!mustBeNew) { + for (auto &r : *_owned) { + if (strcmp(r->GetName(), arg->GetName()) == 0 && strcmp(r->get()->ClassName(), arg->ClassName()) == 0) { + return r->fComp; + } } } if (!fProvider) @@ -3697,7 +4526,7 @@ bool xRooNode::SetXaxis(const char *name, const char *title, int nbins, double l return SetXaxis(b); } -bool xRooNode::SetXaxis(const char *name, const char *title, int nbins, double *bins) +bool xRooNode::SetXaxis(const char *name, const char *title, int nbins, const double *bins) { RooBinning b(nbins, bins, name); b.SetTitle(title); @@ -3758,20 +4587,27 @@ bool xRooNode::SetXaxis(const RooAbsBinning &binning) return true; } -bool xRooNode::contains(const std::string &name) const +bool xRooNode::SetXaxis(TAxis *ax) { - try { - return at(name, false) != nullptr; - } catch (std::out_of_range &) { + if (!ax) return false; + if (ax->IsVariableBinSize()) { + return SetXaxis(ax->GetName(), ax->GetTitle(), ax->GetNbins(), ax->GetXbins()->GetArray()); + } else { + return SetXaxis(ax->GetName(), ax->GetTitle(), ax->GetNbins(), ax->GetXmin(), ax->GetXmax()); } } -std::shared_ptr xRooNode::at(const std::string &name, bool browseResult) const +bool xRooNode::contains(const std::string &name) const +{ + return find(name, false) != nullptr; +} + +std::shared_ptr xRooNode::find(const std::string &name, bool browseResult) const { std::string partname = (name.find('/') != std::string::npos) ? name.substr(0, name.find('/')) : name; auto _s = (!get() && fParent) ? fParent->get() - : get(); // makes work if doing simPdf.variations()["blah"] + : get(); // makes work if doing simPdf.bins()["blah"] std::string extra = (_s) ? _s->indexCat().GetName() : ""; for (auto &child : *this) { if (auto _obj = child->get(); name == child->GetName() || partname == child->GetName() || @@ -3808,7 +4644,7 @@ std::shared_ptr xRooNode::at(const std::string &name, bool browseResul } return child2; } - throw std::out_of_range(name + " does not exist"); + return nullptr; } std::shared_ptr xRooNode::operator[](const std::string &name) @@ -3816,8 +4652,9 @@ std::shared_ptr xRooNode::operator[](const std::string &name) std::string partname = (name.find('/') != std::string::npos) ? name.substr(0, name.find('/')) : name; browse(); auto _s = (!get() && fParent) ? fParent->get() - : get(); // makes work if doing simPdf.variations()["blah"] + : get(); // makes work if doing simPdf.bins()["blah"] std::string extra = (_s) ? _s->indexCat().GetName() : ""; + std::shared_ptr folderNode; for (auto &child : *this) { if (name == child->GetName() || partname == child->GetName() || (!extra.empty() && @@ -3840,6 +4677,25 @@ std::shared_ptr xRooNode::operator[](const std::string &name) } } } + if (child->fFolder == (std::string("!") + partname)) { + if (!folderNode) + folderNode = std::make_shared(child->fFolder.c_str(), nullptr, *this); + folderNode->push_back(child); + } + } + if (folderNode) { + if (partname != name) { + return folderNode->operator[](name.substr(partname.length() + 1)); + } + return folderNode; + } + // before giving up see if partName is numeric and indexes within the range + if (TString s(partname); s.IsDec() && size_t(s.Atoi()) < size()) { + auto child2 = at(s.Atoi()); + if (partname != name) { + return child2->operator[](name.substr(partname.length() + 1)); + } + return child2; } auto out = std::make_shared(partname.c_str(), nullptr, *this); // not adding as child yeeet if (partname != name) { @@ -3862,12 +4718,13 @@ TGListTreeItem *xRooNode::GetTreeItem(TBrowser *b) const } if (!b->GetBrowserImp()) return nullptr; - if (auto _b = dynamic_cast(dynamic_cast(b->GetBrowserImp())->fActBrowser); _b) { - auto _root = _b->fRootDir; + if (auto _b = dynamic_cast(GETACTBROWSER(dynamic_cast(b->GetBrowserImp()))); _b) { + auto _root = GETROOTDIR(_b); + ; if (!_root) - _root = _b->fListTree->GetFirstItem(); - _b->fListTree->SetColorMode(TGListTree::EColorMarkupMode(TGListTree::kColorUnderline | TGListTree::kColorBox)); - return _b->fListTree->FindItemByObj(_root, const_cast(this)); + _root = GETLISTTREE(_b)->GetFirstItem(); + GETLISTTREE(_b)->SetColorMode(TGListTree::EColorMarkupMode(TGListTree::kColorUnderline | TGListTree::kColorBox)); + return GETLISTTREE(_b)->FindItemByObj(_root, const_cast(this)); } return nullptr; } @@ -3885,12 +4742,13 @@ TGListTree *xRooNode::GetListTree(TBrowser *b) const return nullptr; } if (b->GetBrowserImp()) { - if (auto _b = dynamic_cast(dynamic_cast(b->GetBrowserImp())->fActBrowser); _b) { - auto _root = _b->fRootDir; + if (auto _b = dynamic_cast(GETACTBROWSER(dynamic_cast(b->GetBrowserImp()))); + _b) { + auto _root = GETROOTDIR(_b); if (!_root) - _root = _b->fListTree->GetFirstItem(); - if (auto item = _b->fListTree->FindItemByObj(_root, const_cast(this)); item) { - return _b->fListTree; + _root = GETLISTTREE(_b)->GetFirstItem(); + if (auto item = GETLISTTREE(_b)->FindItemByObj(_root, const_cast(this)); item) { + return GETLISTTREE(_b); } } } @@ -3911,6 +4769,17 @@ void xRooNode::SetName(const char *name) } } +void xRooNode::SetTitle(const char *title) +{ + if (auto o = (get()); o) { + if (auto c = mainChild(); c.get()) { + c.SetTitle(title); + } + o->SetTitle(title); + } + TNamed::SetTitle(title); +} + xRooNode &xRooNode::browse() { if (get() || (!get() && !(strlen(GetName()) > 0 && (GetName()[0] == '!')) && !fBrowseOperation)) @@ -3918,7 +4787,8 @@ xRooNode &xRooNode::browse() // alternative could have been to mandate that the 'components' of a collection node are the children it has. auto findByObj = [&](const std::shared_ptr &n) { - for (auto &c : *this) { + std::vector> &nn = *this; + for (auto &c : nn) { if (c->get() == n->get() && strcmp(n->GetName(), c->GetName()) == 0) return c; } @@ -3927,20 +4797,22 @@ xRooNode &xRooNode::browse() auto appendChildren = [&](const xRooNode &n) { size_t out = 0; - for (auto &c : n) { + const std::vector> &nn(n); + for (auto &c : nn) { if (auto existing = findByObj(c); existing) { existing->fTimes++; existing->fFolder = c->fFolder; // transfer folder assignment } else { emplace_back(c); } - if (TString(c->GetName()) != ".coef") + if (!TString(c->GetName()).BeginsWith(".coef")) out++; // don't count .coef as a child, as technically part of parent } return out; }; - for (auto &c : *this) { + const std::vector> &nn2(*this); + for (auto &c : nn2) { if (strlen(c->GetName()) > 0 && (c->GetName()[0] == '.')) { c->fTimes = 1; continue; @@ -3978,8 +4850,31 @@ xRooNode &xRooNode::browse() addedChildren += appendChildren(components()); if (!get()) addedChildren += appendChildren(factors()); + // include coefs if any + auto _coefs = coefs(); + if (_coefs.get() && strcmp(_coefs->GetName(), "1") != 0 && strcmp(_coefs->GetName(), "ONE") != 0) { + if (_coefs.size() == 1 && _coefs.get()) { + if (strcmp(_coefs.at(0)->GetName(), "1") != 0 && + strcmp(_coefs.at(0)->GetName(), "ONE") != 0) { // don't add the "1" + auto coef = std::make_shared(".coef", *_coefs.at(0)->get(), *this); + if (auto existing = findByObj(coef); existing) { + existing->fTimes++; + existing->fFolder = _coefs.at(0)->fFolder; // transfer folder assignment + } else { + emplace_back(coef); + } + } + } else { + if (auto existing = find(_coefs.GetName()); existing) { + existing->fTimes++; + existing->fFolder = _coefs.fFolder; // transfer folder assignment + } else { + emplace_back(std::make_shared(_coefs)); + } + } + } addedChildren += appendChildren(variations()); - if (get()) + if (get() || get()) addedChildren += appendChildren(bins()); if (get()) addedChildren += appendChildren(obs()); @@ -3999,7 +4894,9 @@ xRooNode &xRooNode::browse() } else if (auto s = dynamic_cast(_proxy)) { for (auto a2 : *s) { auto c = std::make_shared(*a2, *this); - c->fFolder = std::string("!.") + _proxy->name(); + if (arg->numProxies() != 1) + c->fFolder = std::string("!.") + + _proxy->name(); // don't put in a folder if there's just 1 proxy (the collection) if (auto existing = findByObj(c); existing) { existing->fTimes++; existing->fFolder = c->fFolder; // transfer folder assignment @@ -4018,11 +4915,95 @@ xRooNode &xRooNode::browse() emplace_back(c); } }*/ + } else if (auto ir = get()) { + // check if we already have a hypoSpace in our memory + bool hasHS = false; + for (auto &c : fBrowsables) { + if (strcmp(c->GetName(), ".memory") == 0 && c->get()) { + hasHS = true; + break; + } + } + if (!hasHS) { + // add the HS + auto hs = + fBrowsables.emplace_back(std::make_shared(".memory", std::make_shared(ir), *this)); + // add the hypoPoints first so they appear first + auto _axes = hs->get()->axes(); + + int i = 0; + for (auto &hp : *hs->get()) { + TString coordString; + for (auto a : _axes) { + if (a != _axes.first()) + coordString += ","; + coordString += + TString::Format("%s=%g", a->GetName(), hp.coords->getRealValue(a->GetName(), ir->GetXValue(i))); + } + auto hpn = emplace_back(std::make_shared(coordString, hp.hypoTestResult, hs)); + hpn->fTimes++; + hpn->fBrowsables.emplace_back(std::make_shared( + ".memory", std::shared_ptr(&hp, [](xRooNLLVar::xRooHypoPoint *) {}), hpn)); + i++; + } + } else { + // ensure all hypoTestResults are flagged as keep-alive + std::vector> &nn = *this; + for (auto &c : nn) { + if (c->get()) + c->fTimes++; + } + } + // xRooNode tests; + // for(int i=0;iArraySize();i++) { + // tests.push_back(std::make_shared(TString::Format("%g",ir->GetXValue(i)),*ir->GetResult(i),*this)); + // } + // appendChildren(tests); + } else if (get()) { + + // create the xRooHypoPoint if necessary + xRooNLLVar::xRooHypoPoint *hp = nullptr; + for (auto &c : fBrowsables) { + if (strcmp(c->GetName(), ".memory") == 0 && c->get()) { + hp = c->get(); + c->fTimes++; // keep it alive + break; + } + } + if (!hp) { + auto shp = + std::make_shared(std::dynamic_pointer_cast(fComp)); + fBrowsables.emplace_back(std::make_shared(".memory", shp, *this)); + hp = shp.get(); + } + + xRooNode fits; + + if (auto fit = hp->ufit()) { + fits.emplace_back(std::make_shared(fit, *this))->TNamed::SetName("ufit"); + } + if (auto fit = hp->cfit_null()) { + fits.emplace_back(std::make_shared(fit, *this))->TNamed::SetName("cfit_null"); + } + if (auto fit = hp->cfit_alt()) { + fits.emplace_back(std::make_shared(fit, *this))->TNamed::SetName("cfit_alt"); + } + if (auto fit = hp->gfit()) { + fits.emplace_back(std::make_shared(fit, *this))->TNamed::SetName("gfit"); + } + if (auto asi = hp->asimov()) { + auto asiP = fits.emplace_back(std::make_shared( + asi->hypoTestResult ? asi->hypoTestResult : std::make_shared(asi->result()), + *this)); + asiP->TNamed::SetName("asimov"); + asiP->fBrowsables.emplace_back(std::make_shared(".memory", asi, asiP)); + } + appendChildren(fits); } // clear anything that has fTimes = 0 still - auto it = begin(); - while (it != end()) { + auto it = std::vector>::begin(); + while (it != std::vector>::end()) { if (it->get()->fTimes == 0) { for (auto o : *gROOT->GetListOfBrowsers()) { auto b = dynamic_cast(o); @@ -4030,13 +5011,13 @@ xRooNode &xRooNode::browse() // std::cout << GetPath() << " Removing " << it->get()->GetPath() << std::endl; if (auto _b = - dynamic_cast(dynamic_cast(b->GetBrowserImp())->fActBrowser); + dynamic_cast(GETACTBROWSER(dynamic_cast(b->GetBrowserImp()))); _b) { - auto _root = _b->fRootDir; + auto _root = GETROOTDIR(_b); if (!_root) - _root = _b->fListTree->GetFirstItem(); - if (auto item = _b->fListTree->FindItemByObj(_root, this); item) { - _b->fListTree->OpenItem(item); + _root = GETLISTTREE(_b)->GetFirstItem(); + if (auto item = GETLISTTREE(_b)->FindItemByObj(_root, this); item) { + GETLISTTREE(_b)->OpenItem(item); } } @@ -4120,12 +5101,12 @@ xRooNode xRooNode::pars() const return out; } -xRooNode xRooNode::args() const +xRooNode xRooNode::consts() const { - xRooNode out(".args", std::make_shared(), *this); - out.get()->setName((GetPath() + ".args").c_str()); + xRooNode out(".consts", std::make_shared(), *this); + out.get()->setName((GetPath() + ".consts").c_str()); for (auto o : pars()) { - if (o->get() || o->get()->getAttribute("Constant")) { + if (o->get()->getAttribute("Constant") || o->get()) { out.get()->add(*o->get()); out.emplace_back(o); } @@ -4164,8 +5145,23 @@ xRooNode xRooNode::np() const xRooNode out(".np", std::make_shared(), *this); out.get()->setName((GetPath() + ".np").c_str()); for (auto o : pars()) { - if (!o->get()->getAttribute("Constant") && !o->get()->getAttribute("poi") && - !o->get()) { + if (o->get()->getAttribute("np") || + (!o->get()->getAttribute("Constant") && !o->get()->getAttribute("poi") && + !o->get())) { + out.get()->add(*o->get()); + out.emplace_back(o); + } + } + return out; +} + +xRooNode xRooNode::pp() const +{ + xRooNode out(".pp", std::make_shared(), *this); + out.get()->setName((GetPath() + ".pp").c_str()); + for (auto o : pars()) { + if (!o->get()->getAttribute("np") && !o->get()->getAttribute("poi") && + (o->get()->getAttribute("Constant") || o->get())) { out.get()->add(*o->get()); out.emplace_back(o); } @@ -4177,32 +5173,61 @@ xRooNode xRooNode::vars() const { xRooNode out(".vars", std::make_shared(), *this); out.get()->setName((GetPath() + ".vars").c_str()); + if (auto coll = get(); coll) { + for (auto &x : *this) { + for (auto &y : x->vars()) { + out.push_back(y); + } + } + return out; + } if (auto p = get(); p) { // also need to get all constPars so use leafNodeServerList .. will include self if is fundamental, which is what // we want + // ensure all globs appear after robs, as we rely on this ordering for picking "x" var in "reduced" method + xRooNode _globs; RooArgSet allLeafs; p->leafNodeServerList(&allLeafs); for (auto &c : allLeafs) { if (c->isFundamental() || (dynamic_cast(c) && !TString(c->GetName()).IsFloat())) { - out.get()->add(*c); - out.emplace_back(std::make_shared(*c, *this)); - if (c->getAttribute("global")) - out.back()->fFolder = "!globs"; - else if (c->getAttribute("obs")) - out.back()->fFolder = "!obs"; - else if (dynamic_cast(c)) - out.back()->fFolder = "!consts"; + if (!c->getAttribute("global")) { + out.get()->add(*c); + out.emplace_back(std::make_shared(*c, *this)); + } + if (c->getAttribute("global")) { + _globs.emplace_back(std::make_shared(*c, *this)); + _globs.back()->fFolder = "!globs"; + } else if (c->getAttribute("obs")) + out.back()->fFolder = "!robs"; + else if (c->getAttribute("poi")) + out.back()->fFolder = "!poi"; + else if (c->getAttribute("np") || + (!c->getAttribute("Constant") && !c->getAttribute("poi") && c->IsA() != RooConstVar::Class())) + out.back()->fFolder = "!np"; + else if (!c->getAttribute("Constant") && c->IsA() != RooConstVar::Class()) + out.back()->fFolder = "!floats"; else - out.back()->fFolder = "!pars"; + out.back()->fFolder = "!pp"; } } + for (auto g : _globs) { + out.get()->add(*g->get()); + out.emplace_back(g); + } } else if (auto p2 = get(); p2) { for (auto a : *p2->get()) { a->setAttribute("obs"); out.emplace_back(std::make_shared(*a, *this)); out.get()->add(*a); } - if (auto _globs = find(".globs"); _globs && _globs->get()) { + if (auto _dglobs = p2->getGlobalObservables()) { + for (auto &a : *_dglobs) { + a->setAttribute("obs"); + a->setAttribute("global"); + out.emplace_back(std::make_shared(*a, *this)); + out.get()->add(*a); + } + } else if (auto _globs = find(".globs"); _globs && _globs->get()) { for (auto &a : *_globs->get()) { a->setAttribute("obs"); a->setAttribute("global"); @@ -4210,14 +5235,14 @@ xRooNode xRooNode::vars() const out.get()->add(*a); } } else if (auto _ws = ws(); _ws) { - if (auto _globs2 = dynamic_cast(_ws->_snapshots.find(p2->GetName())); _globs2) { + if (auto _globs2 = dynamic_cast(GETWSSNAPSHOTS(_ws).find(p2->GetName())); _globs2) { for (auto a : *_globs2) { a->setAttribute("obs"); a->setAttribute("global"); out.emplace_back(std::make_shared(*a, *this)); out.get()->add(*a); } - } else if (auto _gl = _ws->_namedSets.find("globalObservables"); _gl != _ws->_namedSets.end()) { + } else if (auto _gl = GETWSSETS(_ws).find("globalObservables"); _gl != GETWSSETS(_ws).end()) { for (auto &_g : _gl->second) { auto _clone = std::shared_ptr(dynamic_cast(_g->Clone(_g->GetName()))); if (auto v = std::dynamic_pointer_cast(_clone); v && _g->getStringAttribute("nominal")) @@ -4227,7 +5252,7 @@ xRooNode xRooNode::vars() const } } else if (fParent) { // note: this is slow in large workspaces ... too many obs to look through? - std::unique_ptr _globs3(fParent->obs().argList().selectByAttrib("global", true)); + std::unique_ptr _globs3(fParent->obs().get()->selectByAttrib("global", true)); // std::unique_ptr _globs(_ws->allVars().selectByAttrib("global",true)); - tried this to // be quicker but it wasn't for (auto &_g : *_globs3) { @@ -4258,8 +5283,13 @@ xRooNode xRooNode::components() const xRooNode out(".components", nullptr, *this); if (auto p = get(); p) { + // only add each pdf once (the coefs will be accumulated in coefs() method) ... + std::set donePdfs; for (auto &o : p->pdfList()) { + if (donePdfs.count(o)) + continue; out.emplace_back(std::make_shared(*o, *this)); + donePdfs.insert(o); } } else if (auto p2 = get(); p2) { // check for common prefixes and suffixes, will use to define aliases to shorten names @@ -4275,96 +5305,28 @@ xRooNode xRooNode::components() const // } // } // } + std::set doneFuncs; for (auto &o : p2->funcList()) { + if (doneFuncs.count(o)) + continue; out.emplace_back(std::make_shared(*o, *this)); + doneFuncs.insert(o); } } else if (auto p3 = get(); p3) { for (auto &o : p3->list()) { out.emplace_back(std::make_shared(*o, *this)); } - } /*else if(auto p = get(); p) { - long _nentries = p->GetEntries(); - - // iterate up through parents until we are out of the tree - int depth = 0; - auto _pdf = fParent; - while(_pdf && _pdf->get()==p) { - _pdf = _pdf->fParent; - depth++; - } - - // first layer is organised by dsid ... - if (depth==0) { - long total = 0; - for (auto &_d : _pdf->datasets()) { // parent of a frt should be the pdf - auto _hash = RooAbsTree::nameToHash(_d->get()->GetName()); - TString _sel = TString::Format("data_hash.first==%d&&data_hash.second==%d", _hash.first, _hash.second); - auto nFits = p->get()->GetEntries(_sel); - if (nFits > 0) { - total += nFits; - out.emplace_back(std::make_shared( _d->GetName(), fComp, *this)); - } - if (total >= _nentries) break; - } - if (total < _nentries) { - out.emplace_back(std::make_shared("otherDatasets", fComp, *this)); - } - } else if(depth==1) { - // get unconditional fit if we can ... - std::string dName = (strcmp(GetName(),"otherDatasets")==0) ? "*" : GetName(); - long total = 0; - if(auto _ufits = p->GetEntrys(p->BuildSelection(dName, std::map{})); !_ufits.empty()) { - for(auto i : _ufits) { - auto _fr = p->GetFit(i); - TUUID uuid(_fr->GetName()); - TString _name = (dName=="*") ? _fr->GetTitle() : ""; - if (_name!="") _name += ";"; - // before adding a copy of fit, see if fit already exists in this and reuse - _name += uuid.GetTime().AsString(); - if (auto _existing = find(_name.Data()); _existing) { - out.emplace_back(std::make_shared(*_existing)); - } else { - out.emplace_back(std::make_shared(_name, _fr, *this)); - out.back()->fFolder = "!unconditional"; - } - - } - total += _ufits.size(); - } - for(auto& _par : *p->GetParameters()) { - if (total >= _nentries) break; - if (_par->getAttribute("Constant")) continue; - //auto _sel = p->BuildSelection(dName,{{_par->GetName(), - {dynamic_cast(_par)->getMin(),dynamic_cast(_par)->getMax()}}}); if (auto n = p->GetEntrys( - p->BuildSelection(dName, {{_par->GetName(), std::numeric_limits::quiet_NaN()}}), - 1).size();n > 0) { - //if (p->get()->GetEntries(_sel) > 0) { - out.emplace_back(std::make_shared(_par->GetName(),fComp,*this)); - total += n; - } - } - } else if(depth==2) { - std::string dName = (strcmp(fParent->GetName(),"otherDatasets")==0) ? "*" : fParent->GetName(); - //std::cout << p->BuildSelection(dName,{{GetName(),std::numeric_limits::quiet_NaN()}}).GetTitle() << - std::endl; for(auto& i : p->GetEntrys( p->BuildSelection(dName, {{GetName(), - std::numeric_limits::quiet_NaN()}}), -1)) { auto _fr = p->GetFit(i); TString _name = - TString::Format("%f;%s",dynamic_cast(_fr->constPars().find(GetName()))->getVal(),TUUID(_fr->GetName()).GetTime().AsString()); - if (auto _existing = find(_name.Data()); _existing) { - out.emplace_back(std::make_shared(*_existing)); - } else { - out.emplace_back(std::make_shared(_name, _fr, *this)); - } - } - } - - }*/ - else if (auto p5 = get(); p5) { + } else if (auto p4 = get(); p4) { + for (auto &a : *p4) { + out.emplace_back(std::make_shared(*a, *this)); + } + } else if (auto p5 = get(); p5) { for (auto &o : p5->components()) { - // only top-level nodes (only clients are integrals) + // only top-level nodes (only clients are integrals or things that aren't part of the workspace) // if (o->hasClients()) continue; bool hasClients = false; for (auto &c : o->clients()) - if (!c->InheritsFrom("RooRealIntegral")) { + if (!c->InheritsFrom("RooRealIntegral") && p5 == GETWS(o)) { hasClients = true; break; } @@ -4385,7 +5347,7 @@ xRooNode xRooNode::components() const // std::cout << " type = " << _pdf->get()->ClassName() << std::endl; out.emplace_back(std::make_shared(fr->GetName(), *fr, _pdf)); // for a while, this node's parent pointed to something of type Node2!! - // how to fix??? - I fxied it with a new constructo to avoid the shared_ptr calling the const + // how to fix??? - I fxied it with a new constructor to avoid the shared_ptr calling the const // Node2& constructor via getting wrapped in a Node2(shared_ptr) call // out.back()->fParent = _pdf; // std::cout << " type2 = " << out.back()->fParent->get()->ClassName() << std::endl; @@ -4393,41 +5355,18 @@ xRooNode xRooNode::components() const out.emplace_back(std::make_shared(fr->GetName(), *fr, *this)); } out.back()->fFolder = "!fits"; - } /*else if(auto t = dynamic_cast(o); t) { - if (!t->GetUserInfo()) continue; - if (t->GetUserInfo()->FindObject("fitConfig")) { - auto frt = getObject(t->GetName()); - if (!frt) { - frt = const_cast(this)->acquire(t); - } - if (frt) { - if (auto _pdf = frt->GetPdf()) { - out.emplace_back(std::make_shared(frt, xRooNode(*_pdf, *this))); - out.back()->fFolder = "!fits"; - } - } - } else if(t->GetUserInfo()->FindObject("rootVersion")) { - // assume its a RooDataTree until we have better way to identify - auto rdt = getObject(t->GetName()); - if (!rdt) { - rdt = const_cast(this)->acquire(t); - } - if (rdt) { - if (auto _pdf = rdt->GetPdf()) { - out.emplace_back(std::make_shared(rdt, xRooNode(*_pdf, *this))); - out.back()->fFolder = "!datasets"; - } - } - } - // TODO: Handle other tree type? - }*/ - else { + } else { out.emplace_back(std::make_shared(*o, *this)); - out.back()->fFolder = "!objects"; + if (strcmp(out.back()->get()->ClassName(), "TStyle") == 0) { + out.back()->fFolder = "!styles"; + } else if (strcmp(out.back()->get()->ClassName(), "RooStats::HypoTestInverterResult") == 0) { + out.back()->fFolder = "!scans"; + } else { + out.back()->fFolder = "!objects"; + } } } - for (auto &[k, v] : - p5->_namedSets) { // warning -- if this is a map, will it invalidate the object addresses on fill? + for (auto &[k, v] : GETWSSETS(p5)) { // skip 'CACHE' sets because they are auto-removed when sanitizing workspaces, which will invalidate these // children if (k.find("CACHE_") == 0) @@ -4436,9 +5375,10 @@ xRooNode xRooNode::components() const out.back()->fFolder = "!sets"; } - std::unique_ptr iter(p5->_snapshots.MakeIterator()); - RooArgSet *snap; - while ((snap = (RooArgSet *)iter->Next())) { + RooLinkedList snaps = GETWSSNAPSHOTS(p5); + std::unique_ptr iter(snaps.MakeIterator()); + TObject *snap; + while ((snap = iter->Next())) { out.emplace_back(std::make_shared(*snap, *this)); out.back()->fFolder = "!snapshots"; } @@ -4466,9 +5406,25 @@ xRooNode xRooNode::bins() const { xRooNode out(".bins", nullptr, *this); - if (auto phf = get(); phf) { + if (auto p = get(); p) { + std::map> cats; // fill into a map to preserve index ordering + for (auto &c : p->indexCat()) { // is alphabetical in labels + auto pp = p->getPdf(c.first.c_str()); + if (!pp) + continue; + cats[c.second] = + std::make_shared(TString::Format("%s=%s", p->indexCat().GetName(), c.first.c_str()), *pp, *this); + } + for (auto &[_, n] : cats) + out.emplace_back(n); + } else if (auto phf = get(); phf) { int i = 1; - for (auto par : phf->_paramSet) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + auto &pSet = phf->_paramSet; +#else + auto &pSet = phf->paramList(); +#endif + for (auto par : pSet) { out.emplace_back(std::make_shared(*par, *this)); out.back()->fBinNumber = i; i++; @@ -4487,13 +5443,18 @@ xRooNode xRooNode::bins() const } } out.emplace_back(std::make_shared( - TString::Format("%s=%g", ax->GetParent()->GetName(), ax->GetBinCenter(i)), + TString::Format("%g<=%s<%g", ax->GetBinLowEdge(i), ax->GetParent()->GetName(), ax->GetBinLowEdge(i + 1)), _factors.empty() ? nullptr : std::make_shared(TString::Format("%s.binFactors.bin%d", GetName(), i), "binFactors", RooArgList()), *this)); - for (auto f : _factors) + for (auto f : _factors) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) out.back()->get()->_compRSet.add(*f); +#else + const_cast(out.back()->get()->realComponents()).add(*f); +#endif + } out.back()->fBinNumber = i; } } @@ -4504,34 +5465,94 @@ xRooNode xRooNode::bins() const xRooNode xRooNode::coefs() const { RooArgList coefs; + bool isResidual = false; // if parent is a sumpdf or addpdf then include the coefs // if func appears multiple times then coefs must be combined into a RooAddition temporary if (fParent) { - if (auto p = fParent->get(); p) { - int i = 0; + // handle case where filters are applied .. need to pass through these + // do this by iterating while fComp is null + auto parent = fParent; + if (!parent->fComp) { + while (!parent->fComp && parent->fParent) { + parent = parent->fParent; + } + // parent should now be node above the filters ... need parent of that + parent = parent->fParent; + if (!parent) + parent = fParent; // revert t original parent in case something went wrong + } + if (auto p = parent->get(); p) { + std::size_t i = 0; for (auto &o : p->funcList()) { if (o == get()) { - coefs.add(*p->coefList().at(i)); + if (i >= p->coefList().size()) { + isResidual = true; + coefs.add(p->coefList()); + } else { + coefs.add(*p->coefList().at(i)); + } } i++; } - } else if (auto p2 = fParent->get(); p2) { - int i = 0; - for (auto &o : p2->pdfList()) { - if (o == get()) { - coefs.add(*p2->coefList().at(i)); + } else if (auto p2 = parent->get(); p2) { + std::size_t i = 0; + if (p2->coefList().empty()) { + // this can happen if all pdfs are extended then the coef is effectively the + // expected number of events + // TODO: test behaviour of xRooNode under this scenario (are histograms correct?) + } else { + for (auto &o : p2->pdfList()) { + if (o == get()) { + if (i >= p2->coefList().size()) { + isResidual = true; + coefs.add(p2->coefList()); + } else { + coefs.add(*p2->coefList().at(i)); + } + } + i++; } - i++; } } } - xRooNode out(".coefs", coefs.empty() ? nullptr : std::make_shared(".coefs", "Coefficients of", coefs), - *this); - if (!coefs.empty()) - out.browse(); + if (isResidual) { + // return a node representing 1.-sumOfCoefs + // involves creating sumOfCoefs unless there is only 1 coef, then just use that + auto coefSum = coefs.empty() + ? nullptr + : (coefs.size() == 1 ? std::shared_ptr(coefs.at(0), [](RooAbsArg *) {}) + : std::make_shared((isResidual) ? ".sumOfCoefs" : ".coefs", + "Coefficients of", coefs)); + xRooNode out(".coef", coefSum ? std::dynamic_pointer_cast(std::make_shared( + ".coef", "1-sum(otherCoefs)", "1. - @0", *coefSum)) + : nullptr /* should we return a "1." instead? */); + if (coefSum && coefs.size() != 1) { + out.emplace_back(std::make_shared(".memory", nullptr, *this)) + ->emplace_back( + std::make_shared(".sumOfCoefs", coefSum, out)); // added to keep the sum alive! with the node + } + if (!coefs.empty()) { + out.browse(); + } + return out; + } else if (coefs.size() == 1) { + xRooNode out(".coef", std::shared_ptr(coefs.at(0), [](RooAbsArg *) {}), *this); + if (!coefs.empty()) { + out.browse(); + } + return out; + } else { + auto coefSum = + coefs.empty() + ? nullptr + : std::make_shared(".coefs", TString::Format("Coefficients of %s", GetName()), coefs); + xRooNode out(".coefs", coefSum, *this); + if (!coefs.empty()) + out.browse(); - return out; + return out; + } } xRooNode xRooNode::factors() const @@ -4581,18 +5602,6 @@ xRooNode xRooNode::factors() const } } - // include coefs if any - auto _coefs = coefs(); - if (!_coefs.empty()) { - if (_coefs.size() == 1) { - if (strcmp(_coefs.at(0)->GetName(), "1") != 0 && - strcmp(_coefs.at(0)->GetName(), "ONE") != 0) { // don't add the "1" - out.emplace_back(std::make_shared(".coef", *_coefs.at(0)->get(), *this)); - } - } else { - out.emplace_back(std::make_shared(_coefs)); - } - } /* // if parent is a sumpdf or addpdf then include the coefs // if func appears multiple times then coefs must be combined into a RooAddition temporary @@ -4635,16 +5644,22 @@ xRooNode xRooNode::variations() const { xRooNode out(".variations", nullptr, *this); - if (auto p = get(); p) { - for (auto &c : p->indexCat()) { - auto pp = p->getPdf(c.first.c_str()); - if (!pp) - continue; - out.emplace_back( - std::make_shared(TString::Format("%s=%s", p->indexCat().GetName(), c.first.c_str()), *pp, *this)); - } - } else if (auto p2 = get(); p2) { + // if (auto p = get(); p) { + // for (auto &c : p->indexCat()) { + // auto pp = p->getPdf(c.first.c_str()); + // if (!pp) + // continue; + // out.emplace_back( + // std::make_shared(TString::Format("%s=%s", p->indexCat().GetName(), c.first.c_str()), *pp, + // *this)); + // } + // } else + if (auto p2 = get(); p2) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) out.emplace_back(std::make_shared("nominal", p2->_nominal.arg(), *this)); +#else + out.emplace_back(std::make_shared("nominal", *(p2->nominalHist()), *this)); +#endif for (size_t i = 0; i < p2->paramList().size(); i++) { // TODO: should we only return one if we find they are symmetrized? out.emplace_back(std::make_shared(TString::Format("%s=1", p2->paramList().at(i)->GetName()), @@ -4653,6 +5668,7 @@ xRooNode xRooNode::variations() const *p2->lowList().at(i), *this)); } } else if (auto p3 = get(); p3) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) out.emplace_back(std::make_shared("nominal", RooFit::RooConst(p3->_nominal), *this)); for (size_t i = 0; i < p3->_paramList.size(); i++) { out.emplace_back(std::make_shared(TString::Format("%s=1", p3->_paramList.at(i)->GetName()), @@ -4660,17 +5676,27 @@ xRooNode xRooNode::variations() const out.emplace_back(std::make_shared(TString::Format("%s=-1", p3->_paramList.at(i)->GetName()), RooFit::RooConst(p3->_low.at(i)), *this)); } +#else + out.emplace_back(std::make_shared("nominal", RooFit::RooConst(p3->nominal()), *this)); + for (size_t i = 0; i < p3->variables().size(); i++) { + out.emplace_back(std::make_shared(TString::Format("%s=1", p3->variables().at(i)->GetName()), + RooFit::RooConst(p3->high().at(i)), *this)); + out.emplace_back(std::make_shared(TString::Format("%s=-1", p3->variables().at(i)->GetName()), + RooFit::RooConst(p3->low().at(i)), *this)); + } +#endif + } else if (auto p4 = get(); p4) { // I *think* I put this here so that can browse into a ParamHistFunc - int i = 0; - for (auto par : p4->_paramSet) { - TString _name = par->GetName(); - // if(auto _v = dynamic_cast(p->_dataSet.get(i)->first()); _v) { - // _name = TString::Format("%s=%g",_v->GetName(),_v->getVal()); - // } - // out.emplace_back(std::make_shared(_name,*par,*this)); -- -removed cos now have bin() method - i++; - } + // int i = 0; + // for (auto par : p4->_paramSet) { + // TString _name = par->GetName(); + // // if(auto _v = dynamic_cast(p->_dataSet.get(i)->first()); _v) { + // // _name = TString::Format("%s=%g",_v->GetName(),_v->getVal()); + // // } + // // out.emplace_back(std::make_shared(_name,*par,*this)); -- -removed cos now have bin() + // method i++; + // } } return out; } @@ -4697,19 +5723,83 @@ xRooNode xRooNode::datasets() const out.back()->fFolder = "!datasets"; } } else if (auto __ws = ws(); __ws) { - if (get()) { + if (get() || + (!get() && fParent && + fParent->get())) { // second condition handles 'bins' nodes of pdf, which have null ptr // only add datasets that have observables that cover all our observables RooArgSet _obs(obs().argList()); - _obs.add(coords(false).argList(), true); // include coord observables too, and current xaxis if there's one - if (auto ax = GetXaxis(); ax && dynamic_cast(ax->GetParent())->getAttribute("obs")) { - auto a = dynamic_cast(ax->GetParent()); - _obs.add(*a, true); - } + //_obs.add(coords(true).argList(), true); // include coord observables too, and current xaxis if there's one - + //added in loop below + + TString cut; + RooArgSet cutobs; + for (auto _c : coords()) { // coords() moves vars to their respective coordinates too + if (auto _cat = _c->get(); _cat) { + if (cut != "") + cut += " && "; + cut += TString::Format("%s==%d", _cat->GetName(), _cat->getCurrentIndex()); + _obs.add(*_cat, + true); // note: if we ever changed coords to return clones, would need to keep coords alive + cutobs.add(*_cat); + } else if (auto _rv = _c->get(); _rv) { + // todo: check coordRange is a single range rather than multirange + if (cut != "") + cut += " && "; + cut += + TString::Format("%s>=%f&&%s<%f", _rv->GetName(), _rv->getMin(_rv->getStringAttribute("coordRange")), + _rv->GetName(), _rv->getMax(_rv->getStringAttribute("coordRange"))); + _obs.add(*_rv, + true); // note: if we ever changed coords to return clones, would need to keep coords alive + cutobs.add(*_rv); + } else { + throw std::runtime_error("datasets(): Unsupported coordinate type"); + } + } + if (auto s = get()) { + // check if we have a pdf for every category ... if not then add to cut + bool hasMissing = false; + TString extraCut = ""; + for (auto cat : s->indexCat()) { + if (!s->getPdf(cat.first.c_str())) { + hasMissing = true; + } else { + if (extraCut != "") + extraCut += " && "; + extraCut += TString::Format("%s==%d", s->indexCat().GetName(), cat.second); + } + } + if (hasMissing) { + if (cut != "") + cut += " && "; + cut += extraCut; + cutobs.add(s->indexCat()); + } + } + + if (auto ax = GetXaxis(); ax && dynamic_cast(ax->GetParent())->getAttribute("obs")) { + auto a = dynamic_cast(ax->GetParent()); + _obs.add(*a, true); + } xRooNode _wsNode(*__ws, *this); for (auto &d : _wsNode.datasets()) { if (std::unique_ptr(d->obs().argList().selectCommon(_obs))->size() == _obs.size()) { // all obs present .. include - out.emplace_back(std::make_shared(d->fComp, *this)); + + if (cut != "") { + RooFormulaVar cutFormula("cut1", cut, cutobs); // doing this to avoid complaints about unused vars + // TODO: Could consider using a 'filter' node (see filter() method) applied to the dataset instead + // of creating and using a reduced dataset here + out.emplace_back(std::make_shared( + std::shared_ptr(d->get()->reduce(cutFormula)), *this)); + // put a subset of the globs in the returned dataset too + out.back()->get()->setGlobalObservables(*globs().get()); + if (d->get()->TestBit(1 << 20)) + out.back()->get()->SetBit(1 << 20); + // need to attach the original dataset so that things like SetBinContent can interact with it + out.back()->fBrowsables.emplace_back(std::make_shared(".sourceds", d->fComp, *this)); + } else { + out.emplace_back(std::make_shared(d->fComp, *this)); + } } } } /*else if(auto p = get(); p) { @@ -4726,6 +5816,14 @@ xRooNode xRooNode::datasets() const return out; } +std::shared_ptr xRooNode::getBrowsable(const char *name) const +{ + for (auto b : fBrowsables) + if (b && strcmp(b->GetName(), name) == 0) + return b; + return nullptr; +} + TGraph *xRooNode::BuildGraph(RooAbsLValue *v, bool includeZeros, TVirtualPad *fromPad) const { @@ -4833,6 +5931,12 @@ TGraph *xRooNode::BuildGraph(RooAbsLValue *v, bool includeZeros, TVirtualPad *fr _skip = true; break; } + } else if (auto rv = _c->get(); rv) { + // must be in range + if (!rv->inRange(theData->get()->getRealValue(rv->GetName()), rv->getStringAttribute("coordRange"))) { + _skip = true; + break; + } } } if (_pos != -1) { @@ -4912,10 +6016,11 @@ TGraph *xRooNode::BuildGraph(RooAbsLValue *v, bool includeZeros, TVirtualPad *fr // } // } auto _style = style(dataGraph); - *dynamic_cast(dataGraph) = *_style; - *dynamic_cast(dataGraph) = *_style; - *dynamic_cast(dataGraph) = *_style; - + if (_style) { + *dynamic_cast(dataGraph) = *_style; + *dynamic_cast(dataGraph) = *_style; + *dynamic_cast(dataGraph) = *_style; + } return dataGraph; } @@ -4982,6 +6087,13 @@ xRooNode xRooNode::fitResult(const char *opt) const // Warning("fitResult","Building prefitResult by examining pdf. Consider setting an explicit prefitResult // (SetFitResult(fr)) where fr name is prefitResult"); + // ensure coefs are included if there are any + auto _coefs = coefs(); + if (_coefs.get()) { + return xRooNode(RooProduct("tmp", "tmp", RooArgList(*get(), *_coefs.get()))) + .fitResult(opt); + } + std::unique_ptr _pars(dynamic_cast(pars().argList().selectByAttrib("Constant", false))); auto fr = std::make_shared("prefitResult", "Prefit"); fr->setFinalParList(*_pars); @@ -4995,8 +6107,21 @@ xRooNode xRooNode::fitResult(const char *opt) const std::shared_ptr pConstr; for (auto &c : _constr) { if (c->get() || c->get()) { - pConstr = c; - break; + // require parameter to be a direct server of the constraint pdf to count + bool isServer = true; + if (c->get()) { + isServer = false; + for (auto s : c->get()->servers()) { + if (strcmp(s->GetName(), p->GetName()) == 0) { + isServer = true; + break; + } + } + } + if (isServer) { + pConstr = c; + break; + } } } if (pConstr) { @@ -5035,7 +6160,8 @@ xRooNode xRooNode::fitResult(const char *opt) const _v->removeError(); } } - auto _args = args().argList(); + auto _args = consts().argList(); + _args.add(pp().argList()); // global obs are added to constPars list too auto _globs = globs(); // keep alive as may own glob _args.add(_globs.argList()); @@ -5051,7 +6177,7 @@ xRooNode xRooNode::fitResult(const char *opt) const // return first checked fit result present in the workspace if (auto _w = ws(); _w) { - for (auto o : _w->allGenericObjects()) { + auto checkFr = [&](TObject *o) { if (auto _fr = dynamic_cast(o); _fr && _fr->TestBit(1 << 20)) { // check all pars match final/const values ... if mismatch need to create a new RooFitResult bool match = true; @@ -5079,15 +6205,21 @@ xRooNode xRooNode::fitResult(const char *opt) const // create new fit result using covariances from this fit result std::unique_ptr _pars( dynamic_cast(pars().argList().selectByAttrib("Constant", false))); - auto fr = std::make_shared(""); + auto fr = std::make_shared(TString::Format("%s-dirty", _fr->GetName())); fr->SetTitle(TString::Format("%s parameter snapshot", GetName())); fr->setFinalParList(*_pars); - if (fr->_VM) { + TMatrixTSym *prevCov = static_cast *>(GETDMP(_fr, _VM)); + if (prevCov) { auto cov = _fr->reducedCovarianceMatrix(*_pars); + // make the diagonals all the current error values + for (size_t i = 0; i < _pars->size(); i++) { + cov(i, i) = pow(dynamic_cast(_pars->at(i))->getError(), 2); + } fr->setCovarianceMatrix(cov); } - auto _args = args().argList(); + auto _args = consts().argList(); + _args.add(pp().argList()); // global obs are added to constPars list too auto _globs = globs(); // keep alive as may own glob _args.add(_globs.argList()); @@ -5102,6 +6234,17 @@ xRooNode xRooNode::fitResult(const char *opt) const } return xRooNode(*_fr, std::make_shared(*_w, std::make_shared())); } + return xRooNode(); + }; + for (auto o : _w->allGenericObjects()) { + auto out = checkFr(o); + if (out) + return out; + } + for (auto o : GETWSSNAPSHOTS(_w)) { + auto out = checkFr(o); + if (out) + return out; } } else { // objects not in workspaces are allowed to have a fitResult set in their memory @@ -5111,13 +6254,21 @@ xRooNode xRooNode::fitResult(const char *opt) const } } + // ensure coefs are included if there are any + auto _coefs = coefs(); + if (_coefs.get()) { + return xRooNode(RooProduct("tmp", "tmp", RooArgList(*get(), *_coefs.get()))) + .fitResult(opt); + } + std::unique_ptr _pars(dynamic_cast(pars().argList().selectByAttrib("Constant", false))); - auto fr = std::make_shared(""); + auto fr = std::make_shared(TUUID().AsString()); fr->SetTitle(TString::Format("%s uncorrelated parameter snapshot", GetName())); fr->setFinalParList(*_pars); + fr->setStatus(-1); TMatrixDSym cov(fr->floatParsFinal().getSize()); - auto prevCov = fr->_VM; + TMatrixTSym *prevCov = static_cast *>(GETDMP(fr.get(), _VM)); if (prevCov) { for (int i = 0; i < prevCov->GetNcols(); i++) { for (int j = 0; j < prevCov->GetNrows(); j++) { @@ -5132,11 +6283,12 @@ xRooNode xRooNode::fitResult(const char *opt) const } i++; } - int covQualBackup = fr->_covQual; + int covQualBackup = fr->covQual(); fr->setCovarianceMatrix(cov); - fr->_covQual = covQualBackup; + fr->setCovQual(covQualBackup); - auto _args = args().argList(); + auto _args = consts().argList(); + _args.add(pp().argList()); // global obs are added to constPars list too auto _globs = globs(); // keep alive as may own glob _args.add(_globs.argList()); @@ -5201,23 +6353,80 @@ xRooNLLVar xRooNode::nll(const xRooNode &_data) const xRooNLLVar xRooNode::nll(const xRooNode &_data, std::initializer_list nllOpts) const { + auto defaultOpts = xRooFit::createNLLOptions(); // smart pointer will cleanup the list + // add user-specified options to list ... if already existing in default list, override and warn RooLinkedList l; - for (auto &i : nllOpts) + for (auto opt : *defaultOpts) { + l.Add(opt); + } + for (auto &i : nllOpts) { + if (auto o = l.FindObject(i.GetName())) { + Info("nll", "Overriding NLL Option: %s", o->GetName()); + l.Remove(o); + } l.Add(const_cast(&i)); + } + return nll(_data, l); } +xRooNode xRooNode::generate(const xRooNode &fr, bool expected, int seed) +{ + if (!get()) { + // before giving up, if this is a workspace we can proceed if we only have one model + if (get()) { + std::shared_ptr mainModel; + for (auto &c : const_cast(this)->browse()) { + if (c->get()) { + if (!mainModel) { + mainModel = c; + } else { + throw std::runtime_error(TString::Format("Workspace has multiple models, you must specify which to " + "generate with (found at least %s and %s)", + mainModel->GetName(), c->GetName())); + } + } + } + if (mainModel) + return mainModel->generate(fr, expected, seed); + } + throw std::runtime_error(TString::Format("%s is not a pdf", GetName())); + } + auto _fr = fr.get(); + return xRooNode( + xRooFit::generateFrom(*get(), (_fr ? *_fr : *(fitResult().get())), expected, seed).first, + *this); +} + xRooNLLVar xRooNode::nll(const xRooNode &_data, const RooLinkedList &opts) const { - if (!get()) + if (!get()) { + // before giving up, if this is a workspace we can proceed if we only have one model + if (get()) { + std::shared_ptr mainModel; + for (auto &c : const_cast(this)->browse()) { + if (c->get()) { + if (!mainModel) { + mainModel = c; + } else { + throw std::runtime_error(TString::Format("Workspace has multiple models, you must specify which to " + "build nll with (found at least %s and %s)", + mainModel->GetName(), c->GetName())); + } + } + } + if (mainModel) + return mainModel->nll(_data, opts); + } throw std::runtime_error(TString::Format("%s is not a pdf", GetName())); + } // if simultaneous and any channels deselected then reduce and return if (get()) { std::string selected; bool hasDeselected = false; - for (auto c : variations()) { + for (auto c : bins()) { if (!c->get()->isSelectedComp()) { hasDeselected = true; } else { @@ -5237,11 +6446,12 @@ xRooNLLVar xRooNode::nll(const xRooNode &_data, const RooLinkedList &opts) const auto _d = strlen(_data.GetName()) ? datasets().find(_data.GetName()) : nullptr; if (strlen(_data.GetName()) == 0) { // create the EXPECTED (asimov) dataset with the observables - auto asi = xRooFit::generateFrom(*get(), - std::dynamic_pointer_cast(fitResult().fComp), true); + auto asi = xRooFit::generateFrom(*get(), *(fitResult().get()), true); _d = std::make_shared(asi.first, *this); - _d->emplace_back( - std::make_shared(".globs", std::const_pointer_cast(asi.second), *_d)); + if (asi.second) { + _d->emplace_back( + std::make_shared(".globs", std::const_pointer_cast(asi.second), *_d)); + } } else if (!_d) { throw std::runtime_error(TString::Format("Cannot find dataset %s", _data.GetName())); } @@ -5371,7 +6581,7 @@ std::shared_ptr xRooNode::parentPdf() const return out; } -xRooNode xRooNode::reduced(const std::string &_range) const +xRooNode xRooNode::reduced(const std::string &_range, bool invert) const { auto rangeName = (_range.empty()) ? GetRange() : _range; if (!rangeName.empty()) { @@ -5385,7 +6595,7 @@ xRooNode xRooNode::reduced(const std::string &_range) const auto &_cat = const_cast(s->indexCat()); auto newPdf = std::make_shared(TString::Format("%s_reduced", GetName()), "Reduced model", _cat); - for (auto &c : variations()) { + for (auto &c : bins()) { TString cName(c->GetName()); cName = cName(cName.Index('=') + 1, cName.Length()); _cat.setLabel(cName); @@ -5400,12 +6610,12 @@ xRooNode xRooNode::reduced(const std::string &_range) const break; } } - if (matchAny) { + if ((matchAny && !invert) || (!matchAny && invert)) { newPdf->addPdf(*c->get(), cName); } } return xRooNode(newPdf, fParent); - } else if (!components().empty()) { + } else if (get() && !get() && !components().empty()) { // create a new obj and remove non-matching components xRooNode out(std::shared_ptr(get()->Clone(TString::Format("%s_reduced", get()->GetName()))), fParent); // go through components and remove any that don't match pattern @@ -5418,11 +6628,17 @@ xRooNode xRooNode::reduced(const std::string &_range) const break; } } - if (!matchAny) + if (!((matchAny && !invert) || (!matchAny && invert))) funcs.push_back(c->get()); } for (auto &c : funcs) out.Remove(*c); + if (!funcs.empty()) { + if (auto _pdf = out.get(); _pdf) { + _pdf->setFloor(false); // remove floor if removed some functions, which allows evaluation of negative + // valued components + } + } out.browse(); return out; } else if (auto fr = get()) { @@ -5439,37 +6655,48 @@ xRooNode xRooNode::reduced(const std::string &_range) const break; } } - if (!matchAny) { + if (!((matchAny && !invert) || (!matchAny && invert))) { _remPars.add(*c); } } _pars.remove(_remPars, true); auto _tmp = fr->reducedCovarianceMatrix(_pars); - int covQualBackup = fr->_covQual; + int covQualBackup = fr->covQual(); fr->setCovarianceMatrix(_tmp); - fr->_covQual = covQualBackup; - fr->_finalPars->remove(_remPars, true); + fr->setCovQual(covQualBackup); + const_cast(fr->floatParsFinal()) + .remove(_remPars, true); // is this a memory leak ... should delete the remPars? return out; - } else if (!get() || get()) { - // filter the children .... - xRooNode out(get() ? std::make_shared() : std::shared_ptr(nullptr), fParent); + } else if (!get() || get()) { + // filter the children .... handle special case of filtering ".vars" with "x" option too + xRooNode out(std::make_shared(), fParent); + size_t nobs = 0; + bool notAllArgs = false; + bool isVars = (strcmp(GetName(), ".vars") == 0); for (auto c : *this) { + nobs += (c->fFolder == "!robs" || c->fFolder == "!globs"); bool matchAny = false; for (auto &p : patterns) { - if (TString(c->GetName()).Contains(TRegexp(p, true))) { + if (TString(c->GetName()).Contains(TRegexp(p, true)) || + (isVars && p == "x" && (c->fFolder == "!robs" || c->fFolder == "!globs") && nobs == 1)) { matchAny = true; break; } } - if (matchAny) { + if ((matchAny && !invert) || (!matchAny && invert)) { out.push_back(c); - if (auto l = out.get()) { - l->add(*c->get()); + if (auto a = c->get()) { + out.get()->add(*a); + } else { + notAllArgs = true; } } } + if (notAllArgs) { + out.fComp.reset(); + } return out; } } @@ -5552,24 +6779,58 @@ xRooNode xRooNode::reduced(const std::string &_range) const // return out; // } +class xRooProjectedPdf : public RooProjectedPdf { +public: + using RooProjectedPdf::RooProjectedPdf; + double expectedEvents(const RooArgSet *nset) const override + { + return static_cast(intpdf.absArg())->expectedEvents(nset); + } + ExtendMode extendMode() const override { return static_cast(intpdf.absArg())->extendMode(); } + virtual TObject *clone(const char *newname) const override { return new xRooProjectedPdf(*this, newname); } + +protected: + double evaluate() const override + { + int code; + return getProjection(&intobs, _normSet, (_normRange.Length() > 0 ? _normRange.Data() : 0), code)->getVal(); + } +}; + class PdfWrapper : public RooAbsPdf { public: - PdfWrapper(RooAbsPdf &f, RooAbsReal *coef, bool expEvMode = false) - : RooAbsPdf(Form("exp_%s", f.GetName())), fFunc("func", "func", this, f), fCoef("coef", "coef", this) + // need expPdf option while RooProjectedPdf doesn't support keeping things extended + PdfWrapper(RooAbsReal &f, RooAbsReal *coef, bool expEvMode = false, RooAbsPdf *expPdf = nullptr) + : RooAbsPdf(Form("exp_%s", f.GetName())), + fFunc("func", "func", this, f), + fCoef("coef", "coef", this), + fExpPdf("expPdf", "expPdf", this) { - if (coef) + // don't treat pdf as extended if it has a coefficient and is RooAddPdf: RooAddPdf doesn't extend them unless no + // coefs for any (and all are extendable) + if (coef) { fCoef.setArg(*coef); + } + if (expPdf && expPdf->canBeExtended() && !(coef && dynamic_cast(expPdf))) { + fExpPdf.setArg(*expPdf); + } else if (auto _p = dynamic_cast(&f); + _p && _p->canBeExtended() && !(coef && dynamic_cast(_p))) { + fExpPdf.setArg(f); // using self for expectation + } fExpectedEventsMode = expEvMode; } virtual ~PdfWrapper(){}; PdfWrapper(const PdfWrapper &other, const char *name = 0) - : RooAbsPdf(other, name), fFunc("func", this, other.fFunc), fCoef("coef", this, other.fCoef), + : RooAbsPdf(other, name), + fFunc("func", this, other.fFunc), + fCoef("coef", this, other.fCoef), + fExpPdf("expPdf", this, other.fExpPdf), fExpectedEventsMode(other.fExpectedEventsMode) { } virtual TObject *clone(const char *newname) const override { return new PdfWrapper(*this, newname); } - Bool_t isBinnedDistribution(const RooArgSet &obs) const override { return fFunc->isBinnedDistribution(obs); } - std::list *binBoundaries(RooAbsRealLValue &obs, Double_t xlo, Double_t xhi) const override + bool isBinnedDistribution(const RooArgSet &obs) const override { return fFunc->isBinnedDistribution(obs); } + std::list *binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const override { return fFunc->binBoundaries(obs, xlo, xhi); } @@ -5577,12 +6838,140 @@ class PdfWrapper : public RooAbsPdf { double evaluate() const override { return (fExpectedEventsMode ? 1. : fFunc) * - (dynamic_cast(fFunc.absArg())->expectedEvents(_normSet)) * (fCoef.absArg() ? fCoef : 1.); + ((fExpPdf.absArg()) ? static_cast(fExpPdf.absArg())->expectedEvents(_normSet) : 1.) * + (fCoef.absArg() ? fCoef : 1.); } + bool selfNormalized() const override + { + return true; + } // so that doesn't try to do an integral because we are passing integration onto fFunc in evaluate + // faster than full evaluation because doesnt make the integral dependent on the full expression - Double_t getSimplePropagatedError(const RooFitResult &fr, const RooArgSet &nset_in) const + double getSimplePropagatedError(const RooFitResult &fr, const RooArgSet &nset_in) const { +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00) + double oo = getPropagatedError(fr, nset_in); // method was improved in 6.28 so use this instead + if (std::isnan(oo)) { + // may be consequence of zero uncerts + // Calling getParameters() might be costly, but necessary to get the right + // parameters in the RooAbsReal. The RooFitResult only stores snapshots. + RooArgSet allParamsInAbsReal; + getParameters(&nset_in, allParamsInAbsReal); + + RooArgList paramList; + for (auto *rrvFitRes : static_range_cast(fr.floatParsFinal())) { + + auto rrvInAbsReal = static_cast(allParamsInAbsReal.find(*rrvFitRes)); + + // If this RooAbsReal is a RooRealVar in the fit result, we don't need to + // propagate anything and can just return the error in the fit result + if (rrvFitRes->namePtr() == namePtr()) + return rrvFitRes->getError(); + + // Strip out parameters with zero error + if (!rrvFitRes->hasError() || + rrvFitRes->getError() <= std::abs(rrvFitRes->getVal()) * std::numeric_limits::epsilon()) + continue; + + // Ignore parameters in the fit result that this RooAbsReal doesn't depend on + if (!rrvInAbsReal) + continue; + + // Checking for float equality is a bad. We check if the values are + // negligibly far away from each other, relative to the uncertainty. + if (std::abs(rrvInAbsReal->getVal() - rrvFitRes->getVal()) > 0.01 * rrvFitRes->getError()) { + std::stringstream errMsg; + errMsg + << "RooAbsReal::getPropagatedError(): the parameters of the RooAbsReal don't have" + << " the same values as in the fit result! The logic of getPropagatedError is broken in this case."; + + throw std::runtime_error(errMsg.str()); + } + + paramList.add(*rrvInAbsReal); + } + if (paramList.empty()) + return 0.; + + std::vector plusVar; + std::vector minusVar; + plusVar.reserve(paramList.size()); + minusVar.reserve(paramList.size()); + + // Create std::vector of plus,minus variations for each parameter + TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ? fr.covarianceMatrix() + : fr.reducedCovarianceMatrix(paramList)); + + for (Int_t ivar = 0; ivar < paramList.getSize(); ivar++) { + + auto &rrv = static_cast(paramList[ivar]); + + double cenVal = rrv.getVal(); + double errVal = sqrt(V(ivar, ivar)); + + // this next thing happens if the par has errors but the covariance matrix is empty + // this only happens if the fit was dodgy, so perhaps best to not even try to recover from this + // screwup ... hence I've commented out this fixup here and will let the errors be nan + // if(errVal==0) { + // Warning("getPropagatedError","Missing variance for %s",rrv.GetName()); + // errVal = rrv.getError(); + // V(ivar,ivar) = errVal*errVal; + // } + + // Make Plus variation + rrv.setVal(cenVal + errVal); + plusVar.push_back(getVal(nset_in)); + + // Make Minus variation + rrv.setVal(cenVal - errVal); + minusVar.push_back(getVal(nset_in)); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + // can try to recover nans ... this stopped being possible in 6.27 onwards because NaNPacker made private + if (std::isnan(plusVar.back()) && RooNaNPacker::isNaNWithPayload(plusVar.back())) { + plusVar.back() = -RooNaNPacker::unpackNaN(plusVar.back()); + } + if (std::isnan(minusVar.back()) && RooNaNPacker::isNaNWithPayload(minusVar.back())) { + minusVar.back() = -RooNaNPacker::unpackNaN(minusVar.back()); + } +#endif + // std::cout << plusVar.back() << " and " << minusVar.back() << std::endl; + + rrv.setVal(cenVal); + } + + // Re-evaluate this RooAbsReal with the central parameters just to be + // extra-safe that a call to `getPropagatedError()` doesn't change any state. + // It should not be necessary because thanks to the dirty flag propagation + // the RooAbsReal is re-evaluated anyway the next time getVal() is called. + // Still there are imaginable corner cases where it would not be triggered, + // for example if the user changes the RooFit operation more after the error + // propagation. + getVal(nset_in); + + TMatrixDSym C(paramList.getSize()); + std::vector errVec(paramList.size()); + for (int i = 0; i < paramList.getSize(); i++) { + errVec[i] = std::sqrt(V(i, i)); + for (int j = i; j < paramList.getSize(); j++) { + C(i, j) = V(i, j) / std::sqrt(V(i, i) * V(j, j)); + C(j, i) = C(i, j); + } + } + + // Make std::vector of variations + TVectorD F(plusVar.size()); + for (unsigned int j = 0; j < plusVar.size(); j++) { + F[j] = (plusVar[j] - minusVar[j]) / 2; + } + + // Calculate error in linear approximation from variations and correlation coefficient + double sum = F * (C * F); + + return sqrt(sum); + } + return oo; +#else // Strip out parameters with zero error RooArgList fpf_stripped; @@ -5595,8 +6984,8 @@ class PdfWrapper : public RooAbsPdf { } // Clone self for internal use - RooAbsReal *cloneFunc = (RooAbsReal *)fFunc.absArg()->cloneTree(); - RooAbsPdf *clonePdf = dynamic_cast(cloneFunc); + RooAbsReal *cloneFunc = const_cast(this); // (RooAbsReal *)fFunc.absArg()->cloneTree(); + // RooAbsPdf *clonePdf = dynamic_cast(cloneFunc); RooArgSet *errorParams = cloneFunc->getObservables(fpf_stripped); RooArgSet *nset = @@ -5614,7 +7003,7 @@ class PdfWrapper : public RooAbsPdf { } } - std::vector plusVar, minusVar; + std::vector plusVar, minusVar; // Create vector of plus,minus variations for each parameter TMatrixDSym V(paramList.getSize() == fr.floatParsFinal().getSize() ? fr.covarianceMatrix() @@ -5624,22 +7013,26 @@ class PdfWrapper : public RooAbsPdf { RooRealVar &rrv = (RooRealVar &)fpf[fpf_idx[ivar]]; - Double_t cenVal = rrv.getVal(); - Double_t errVal = sqrt(V(ivar, ivar)); + double cenVal = rrv.getVal(); + double errVal = sqrt(V(ivar, ivar)); // Make Plus variation ((RooRealVar *)paramList.at(ivar))->setVal(cenVal + errVal); - plusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) * - (clonePdf ? clonePdf->expectedEvents(nset) : 1.)); + // plusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) * + // (clonePdf ? clonePdf->expectedEvents(nset) : 1.)); + plusVar.push_back(cloneFunc->getVal(nset)); // Make Minus variation ((RooRealVar *)paramList.at(ivar))->setVal(cenVal - errVal); - minusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) * - (clonePdf ? clonePdf->expectedEvents(nset) : 1.)); + // minusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) * + // (clonePdf ? clonePdf->expectedEvents(nset) : 1.)); + minusVar.push_back(cloneFunc->getVal(nset)); ((RooRealVar *)paramList.at(ivar))->setVal(cenVal); } + getVal(nset); // reset state + TMatrixDSym C(paramList.getSize()); std::vector errVec(paramList.getSize()); for (int i = 0; i < paramList.getSize(); i++) { @@ -5657,18 +7050,20 @@ class PdfWrapper : public RooAbsPdf { } // Calculate error in linear approximation from variations and correlation coefficient - Double_t sum = F * (C * F); + double sum = F * (C * F); - delete cloneFunc; + // delete cloneFunc; delete errorParams; delete nset; return sqrt(sum); +#endif } private: RooRealProxy fFunc; RooRealProxy fCoef; + RooRealProxy fExpPdf; bool fExpectedEventsMode = false; }; @@ -5687,36 +7082,33 @@ void buildHistogramInterrupt(int signum) } } -void xRooNode::sterilize() +void xRooNode::sterilize() const { auto _doSterilize = [](RooAbsArg *obj) { - if (RooAbsPdf *arg = dynamic_cast(obj); arg) { - arg->_normMgr.reset(); - arg->_normSet = nullptr; - if (RooProdPdf *p = dynamic_cast(arg); p) { - p->_cacheMgr.reset(); - p->setNormRange(0); - } else if (auto p2 = dynamic_cast(arg); p2) { - p2->_normIntMgr.reset(); - } else if (auto p3 = dynamic_cast(arg); p3) { - p3->_partIntMgr.reset(); - } - // std::cout << "cleaned " << arg->GetName() << std::endl; - - } else if (auto p = dynamic_cast(obj); p) { - p->_cacheMgr.reset(); - } else if (auto p2 = dynamic_cast(obj); p2) { - p2->_normIntMgr.reset(); - } else if (auto p3 = dynamic_cast(obj); p3) { - p3->_normIntMgr.reset(); - } - if (obj) { - obj->setValueDirty(); + if (!obj) + return; + for (int i = 0; i < obj->numCaches(); i++) { + if (auto cache = dynamic_cast(obj->getCache(i))) { + cache->reset(); + } + } + if (RooAbsPdf *p = dynamic_cast(obj); p) { + p->setNormRange(p->normRange()); + } +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + if (RooAbsReal *p = dynamic_cast(obj); p) { + // need to forget about any normSet that was passed to getVal(...) + // doesn't seem necessary in 6.28 + + p->setProxyNormSet(nullptr); + p->_lastNSet = nullptr; } +#endif + obj->setValueDirty(); }; if (auto w = get(); w) { // sterilizing all nodes - for (auto &c : w->_allOwnedNodes) { + for (auto &c : w->components()) { _doSterilize(c); } return; @@ -5724,23 +7116,273 @@ void xRooNode::sterilize() // recursive through all clients and sterlize their normalization caches std::function func; func = [&](RooAbsArg *a) { - if (!a) + if (!a) { return; - auto itr = a->clientIterator(); - TObject *obj; - while ((obj = itr->Next())) { - _doSterilize(dynamic_cast(obj)); - if (RooAbsArg *arg = dynamic_cast(obj); arg) { - func(arg); - } } - delete itr; + _doSterilize(a); // sterilize first so that cache elements don't appear in the client list + // safety net in case sterilizing one client deletes another one of our clients + // monitor for change in clients list size + // found this was only case in 6.26 (valgrind shows invalid read), in 6.28 these went away + // might be in 6.28 the client list iterator became able to handle in-loop edits but didn't see + // in test case that client count changed so just resterilizing if that's the case. + size_t nClients; + do { + nClients = a->clients().size(); + for (auto obj : a->clients()) { + func(dynamic_cast(obj)); + if (a->clients().size() != nClients) { + break; // means sterilizing a client changed our clients, so don't trust the client iterator at this + // point + } + } + } while (a->clients().size() != nClients); }; - func(dynamic_cast(get())); - _doSterilize(dynamic_cast(get())); // sterilize self + func(get()); } -TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binStart, int binEnd) const +// observables not in the axisVars are automatically projected over +xRooNode xRooNode::histo(const xRooNode &vars, const xRooNode &fr, bool content, bool errors) const +{ + + if (!vars.fComp && strlen(vars.GetName())) { + return histo(xRooNode::vars().reduced(vars.GetName()), fr, content, errors); + } + + xRooNode out(TString::Format("%s.histo", GetName()), nullptr, *this); + + RooAbsLValue *v = nullptr; + if (vars.empty()) { + out.fComp = std::shared_ptr(BuildHistogram(nullptr, !content, errors, -1, -1, fr)); + } else if (vars.size() == 1) { + v = vars.at(0)->get(); + out.fComp = std::shared_ptr(BuildHistogram(v, !content, errors, 1, 0, fr)); + } else { + throw std::runtime_error("multi-dim histo not yet supported"); + } + + if (auto h = out.get()) { + if (h->GetXaxis()->IsAlphanumeric()) { + // do this to get bin labels + h->GetXaxis()->SetName("xaxis"); // WARNING -- this messes up anywhere we GetXaxis()->GetName() + } + h->SetStats(false); + h->SetName(GetName()); + auto hCopy = static_cast(h->Clone("nominal")); + + if (content && !components().empty()) { + RooAbsReal *sf = nullptr; // TODO - support case of RooExtendPdf drawing (see ::Draw) + // build a stack + THStack *stack = new THStack("stack", ""); + int count = 2; + std::map colorByTitle; // TODO: should fill from any existing legend + std::set allTitles; + bool titleMatchName = true; + std::map histGroups; + std::vector hhs; + + // support for CMS model case where has single component containing many coeffs + // will build stack by setting each coeff equal to 0 in turn, rebuilding the histogram + // the difference from the "full" histogram will be the component + RooArgList cms_coefs; + if (!components().empty()) { + auto comps = components()[0]; + for (auto &c : *comps) { + if (c->fFolder == "!.coeffs") + cms_coefs.add(*c->get()); + } + } + + if (!cms_coefs.empty()) { + RooRealVar zero("zero", "", 0); + std::shared_ptr prevHist((TH1 *)h->Clone()); + for (auto c : cms_coefs) { + // seems I have to remake the function each time, as haven't figured out what cache needs clearing? + std::unique_ptr f(dynamic_cast(components()[0]->get()->Clone("tmpCopy"))); + zero.setAttribute( + Form("ORIGNAME:%s", c->GetName())); // used in redirectServers to say what this replaces + f->redirectServers(RooArgSet(zero), false, true); // each time will replace one additional coef + // zero.setAttribute(Form("ORIGNAME:%s",c->GetName()),false); (commented out so that on next iteration + // will still replace all prev) + auto hh = xRooNode(*f, *this).BuildHistogram(v, false, false, !v ? -1 : 1, !v ? -1 : 0, fr); + if (sf) + hh->Scale(sf->getVal()); + if (strlen(hh->GetTitle()) == 0) + hh->SetTitle(c->GetName()); // ensure all hists has titles + titleMatchName &= (TString(c->GetName()) == hh->GetTitle() || + TString(hh->GetTitle()).BeginsWith(TString(c->GetName()) + "_")); + std::shared_ptr nextHist((TH1 *)hh->Clone()); + hh->Add(prevHist.get(), -1.); + hh->Scale(-1.); + hhs.push_back(hh); + prevHist = nextHist; + } + } else { + for (auto &samp : components()) { + auto hh = samp->BuildHistogram(v, false, false, !v ? -1 : 1, !v ? -1 : 0, fr); + if (sf) + hh->Scale(sf->getVal()); + hhs.push_back(hh); + if (strlen(hh->GetTitle()) == 0) + hh->SetTitle(samp->GetName()); // ensure all hists has titles + titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() || + TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_")); + } + } + for (auto &hh : hhs) { + if (h->GetXaxis()->IsAlphanumeric()) { + // must ensure bin labels match for stack + hh->GetXaxis()->SetName("xaxis"); + for (int i = 1; i <= hh->GetNbinsX(); i++) + hh->GetXaxis()->SetBinLabel(i, h->GetXaxis()->GetBinLabel(i)); + } + // automatically group hists that all have the same title + if (histGroups.find(hh->GetTitle()) == histGroups.end()) { + histGroups[hh->GetTitle()] = hh; + } else { + // add it into this group + histGroups[hh->GetTitle()]->Add(hh); + delete hh; + continue; + } + auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum(); + if (!stack->GetHists() && h->GetMinimum() > hhMin) { + auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin(); + if (hhMin >= 0 && newMin < 0) + newMin = hhMin * 0.99; + h->SetMinimum(newMin); /// adjustYRange(newMin, h->GetMaximum()); + } + if (auto it = colorByTitle.find(hh->GetTitle()); it != colorByTitle.end()) { + hh->SetFillColor(it->second); + } else { + bool used = false; + do { + hh->SetFillColor((count++) % 100); + // check not already used this color + used = false; + for (auto hh2 : hhs) { + if (hh != hh2 && hh2->GetFillColor() == hh->GetFillColor()) { + used = true; + break; + } + } + } while (used); + colorByTitle[hh->GetTitle()] = hh->GetFillColor(); + } + /*if(stack->GetHists() && stack->GetHists()->GetEntries()>0) { + // to remove rounding effects on bin boundaries, see if binnings compatible + auto _h1 = dynamic_cast(stack->GetHists()->At(0)); + if(_h1->GetNbinsX()==hh->GetNbinsX()) TODO ... finish dealing with silly rounding effects + }*/ + TString thisOpt = ""; /// dOpt; + // uncomment next line to blend continuous with discrete components .. get some unpleasant "poke through" + // effects though + // if(auto s = samp->get(); s) thisOpt = s->isBinnedDistribution(*dynamic_cast(v)) ? + // "" : "LF2"; + stack->Add(hh, thisOpt); + allTitles.insert(hh->GetTitle()); + } + + TList *ll = stack->GetHists(); + if (ll && ll->GetEntries()) { + + // get common prefix to strip off only if all titles match names and + // any title is longer than 10 chars + size_t e = std::min(allTitles.begin()->size(), allTitles.rbegin()->size()); + size_t ii = 0; + bool goodPrefix = false; + std::string commonSuffix; + if (titleMatchName && ll->GetEntries() > 1) { + while (ii < e - 1 && allTitles.begin()->at(ii) == allTitles.rbegin()->at(ii)) { + ii++; + if (allTitles.begin()->at(ii) == '_' || allTitles.begin()->at(ii) == ' ') + goodPrefix = true; + } + + // find common suffix if there is one .. must start with a "_" + bool stop = false; + while (!stop && commonSuffix.size() < size_t(e - 1)) { + commonSuffix = allTitles.begin()->substr(allTitles.begin()->length() - commonSuffix.length() - 1); + for (auto &t : allTitles) { + if (!TString(t).EndsWith(commonSuffix.c_str())) { + commonSuffix = commonSuffix.substr(1); + stop = true; + break; + } + } + } + if (commonSuffix.find('_') == std::string::npos) + commonSuffix = ""; + else + commonSuffix = commonSuffix.substr(commonSuffix.find('_')); + } + if (!goodPrefix) + ii = 0; + + // also find how many characters are needed to distinguish all entries (that dont have the same name) + // then carry on up to first space or underscore + size_t jj = 0; + std::map reducedTitles; + while (reducedTitles.size() != allTitles.size()) { + jj++; + std::map titlesMap; + for (auto &s : allTitles) { + if (reducedTitles.count(s)) + continue; + titlesMap[s.substr(0, jj)]++; + } + for (auto &s : allTitles) { + if (titlesMap[s.substr(0, jj)] == 1 && (jj >= s.length() || s.at(jj) == ' ' || s.at(jj) == '_')) { + reducedTitles[s] = s.substr(0, jj); + } + } + } + + // strip common prefix and suffix before adding + for (int i = ll->GetEntries() - 1; i >= 0; i--) { // go in reverse order + auto _title = (ll->GetEntries() > 5) ? reducedTitles[ll->At(i)->GetTitle()] : ll->At(i)->GetTitle(); + _title = _title.substr(ii < _title.size() ? ii : 0); + if (!commonSuffix.empty() && TString(_title).EndsWith(commonSuffix.c_str())) + _title = _title.substr(0, _title.length() - commonSuffix.length()); + + dynamic_cast(ll->At(i))->SetTitle(_title.c_str()); + + // style hists according to available styles ... creating if necessary + auto _style = xRooNode(*ll->At(i), *this).style(ll->At(i)); + if (_style) { + *dynamic_cast(ll->At(i)) = *_style; + *dynamic_cast(ll->At(i)) = *_style; + *dynamic_cast(ll->At(i)) = *_style; + } + } + } + h->GetListOfFunctions()->Add(stack, "noclearsame"); + if (h->GetSumw2() && h->GetSumw2()->GetSum()) { + hCopy->SetFillStyle(3005); + hCopy->SetFillColor(h->GetLineColor()); + hCopy->SetMarkerStyle(0); + h->GetListOfFunctions()->Add(hCopy->Clone(".copy"), "e2same"); + *static_cast(hCopy) = *h; + } + } + + h->GetListOfFunctions()->Add(hCopy, "histsame"); + if (h->GetSumw2() && h->GetSumw2()->GetSum()) { + h->SetFillStyle(3005); + h->SetFillColor(h->GetLineColor()); + h->SetMarkerStyle(0); + } + } + + return out; +} + +xRooNode xRooNode::filter(const xRooNode &range) const +{ + return xRooNode(fComp, xRooNode(range.GetName(), nullptr, *this)); +} + +TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binStart, int binEnd, + const xRooNode &_fr) const { auto rar = get(); if (!rar) @@ -5752,8 +7394,13 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS TH1::AddDirectory(false); TH1 *h = nullptr; if (!v) { - if (auto _ax = GetXaxis()) - v = dynamic_cast(_ax->GetParent()); + if (binStart != -1 || binEnd != -1) { // allow v to stay nullptr if doing integral (binStart=binEnd=-1) + if (auto _ax = GetXaxis()) + v = dynamic_cast(_ax->GetParent()); + } else { + // don't need to integrate if doing a self-histogram + v = dynamic_cast(rar); + } if (v) vv = dynamic_cast(v); else { @@ -5765,6 +7412,7 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS } auto x = dynamic_cast(v); + bool setTitle = false; if (x) { if (x == rar) { // self histogram ... @@ -5775,9 +7423,9 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS if (x->hasError()) h->SetBinError(1, x->getError()); h->SetMaximum(x->hasMax() ? x->getMax() - : (h->GetBinContent(1) + std::max(abs(h->GetBinContent(1) * 0.1), 50.))); + : (h->GetBinContent(1) + std::max(std::abs(h->GetBinContent(1) * 0.1), 50.))); h->SetMinimum(x->hasMin() ? x->getMin() - : (h->GetBinContent(1) - std::max(abs(h->GetBinContent(1) * 0.1), 50.))); + : (h->GetBinContent(1) - std::max(std::abs(h->GetBinContent(1) * 0.1), 50.))); h->GetXaxis()->SetName(dynamic_cast(v)->GetName()); return h; } @@ -5793,6 +7441,7 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS h = new TH1D(rar->GetName(), rar->GetTitle(), x->numBins(binningName), x->getBinning(binningName).array()); } h->GetXaxis()->SetTitle(x->getBinning(binningName).GetTitle()); + setTitle = true; } else if (auto _boundaries = _or_func(/*rar->plotSamplingHint(*x,x->getMin(),x->getMax())*/ (std::list *)(nullptr), rar->binBoundaries(*x, -std::numeric_limits::infinity(), @@ -5814,12 +7463,21 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS } else if (!h) { h = new TH1D(rar->GetName(), rar->GetTitle(), v->numBins(rar->GetName()), 0, v->numBins(rar->GetName())); + if (auto cat = dynamic_cast(v)) { + for (int i = 0; i < cat->numTypes(); i++) { + cat->setBin(i); + h->GetXaxis()->SetBinLabel(i + 1, cat->getLabel()); + } + } + } + if (auto o = dynamic_cast(v); o && !setTitle) { + h->GetXaxis()->SetTitle(o->GetTitle()); } TH1::AddDirectory(t); h->Sumw2(); if (v) h->GetXaxis()->SetName(dynamic_cast(v)->GetName()); // WARNING: messes up display of bin labels - if (auto s = style(); s) { + if (auto s = style(nullptr, false); s) { static_cast(*h) = *s; static_cast(*h) = *s; static_cast(*h) = *s; @@ -5828,11 +7486,35 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS h->GetXaxis()->SetTitle(vv->GetTitle()); auto p = dynamic_cast(rar); + // possible speed improvement: + // if(auto spdf = dynamic_cast(p); spdf && spdf->canBeExtended()) { + // p = nullptr; // faster to evaluate sumpdf as a function not a pdf + // } + + if (empty && !errors) { + return h; + } + + // if (!empty) { + + auto _coefs = coefs(); + RooFitResult *fr = nullptr; if (errors) { - fr = dynamic_cast(fitResult().get()->Clone()); - if (!fr->_finalPars) + // must ensure the fit result we obtain includes pars from coefficients if present + if (_fr.get()) { + fr = static_cast(_fr.get()->Clone()); + } else { + auto frn = + (!_coefs.get() ? *this : xRooNode(RooProduct("tmp", "tmp", RooArgList(*rar, *_coefs.get())))) + .fitResult(); + if (strlen(_fr.GetName())) + frn = frn.reduced(_fr.GetName()); + fr = dynamic_cast(frn->Clone()); + } + if (!GETDMP(fr, _finalPars)) { fr->setFinalParList(RooArgList()); + } /// Oct2022: No longer doing this because want to allow fitResult to be used to get partial error // // need to add any floating parameters not included somewhere already in the fit result ... @@ -5853,9 +7535,10 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS // fr->setFinalParList(l2); // } - if (!fr->_VM || size_t(fr->_VM->GetNcols()) < fr->floatParsFinal().size()) { + TMatrixTSym *prevCov = static_cast *>(GETDMP(fr, _VM)); + + if (!prevCov || size_t(fr->covarianceMatrix().GetNcols()) < fr->floatParsFinal().size()) { TMatrixDSym cov(fr->floatParsFinal().getSize()); - auto prevCov = fr->_VM; if (prevCov) { for (int i = 0; i < prevCov->GetNcols(); i++) { for (int j = 0; j < prevCov->GetNrows(); j++) { @@ -5870,20 +7553,35 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS } i++; } - int covQualBackup = fr->_covQual; + int covQualBackup = fr->covQual(); fr->setCovarianceMatrix(cov); - fr->_covQual = covQualBackup; + fr->setCovQual(covQualBackup); + } + + if (v) { + // need to remove v from result as we are plotting as function of v + if (auto _p = fr->floatParsFinal().find(dynamic_cast(v)->GetName()); _p) { + RooArgList _pars = fr->floatParsFinal(); + _pars.remove(*_p, true); + auto _tmp = fr->reducedCovarianceMatrix(_pars); + int covQualBackup = fr->covQual(); + fr->setCovarianceMatrix(_tmp); + fr->setCovQual(covQualBackup); + const_cast(fr->floatParsFinal()) + .remove(*_p, true); // NOTE: I think this might be a memory leak, should delete _p after removal + } + } + // finally check at least one float has errors defined (might not be cause if in prefit state) + bool hasErrors = false; + for (auto pp : fr->floatParsFinal()) { + if (dynamic_cast(pp)->hasError()) { + hasErrors = true; + break; + } } - - // need to remove v from result as we are plotting as function of v - if (auto _p = fr->floatParsFinal().find(dynamic_cast(v)->GetName()); _p) { - RooArgList _pars = fr->floatParsFinal(); - _pars.remove(*_p, true); - auto _tmp = fr->reducedCovarianceMatrix(_pars); - int covQualBackup = fr->_covQual; - fr->setCovarianceMatrix(_tmp); - fr->_covQual = covQualBackup; - fr->_finalPars->remove(*_p, true); + if (!hasErrors) { + errors = false; + delete fr; } } @@ -5891,101 +7589,217 @@ TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binS if (v) normSet.add(*dynamic_cast(v)); - if (!empty) { - if (binEnd == 0) - binEnd = h->GetNbinsX(); - bool needBinWidth = false; - // may have MULTIPLE coefficients for the same pdf! - auto _coefs = coefs(); - if ((p || !_coefs.empty() || rar->getAttribute("density")) && x) { - // pdfs of samples embedded in a sumpdf (aka have a coef) will convert their density value to a content - needBinWidth = true; - } - std::unique_ptr snap(normSet.snapshot()); - TStopwatch timeIt; - std::vector lapTimes; - bool warned = false; - for (int i = std::max(1, binStart); i <= std::min(h->GetNbinsX(), binEnd); i++) { - timeIt.Start(true); - if (x) - x->setVal(h->GetBinCenter(i)); - else if (v) - v->setBin(i - 1); - double r = /*(p && p->selfNormalized())*/ rar->getVal(normSet); - if (r && !_coefs.empty()) { + if (binEnd == 0) + binEnd = h->GetNbinsX(); + + bool needBinWidth = false; + // may have MULTIPLE coefficients for the same pdf! + + if (x && (p || _coefs.get() || rar->getAttribute("density"))) { + // pdfs of samples embedded in a sumpdf (aka have a coef) will convert their density value to a content + needBinWidth = true; + } + + if (auto spdf = dynamic_cast(p); + spdf && spdf->canBeExtended() && !spdf->getFloor() && !_coefs.get()) { + p = nullptr; // if pdf has no floor, will evaluate it as a function to allow it to be negative - evaluation should + // also be faster (no integral) + // exception is if RooRealSumPdf is embedded in a RooAddPdf (detected by presence of coefs) ... then it must be + // evaluated as a pdf technically should check parent is a RooAddPdf, because if was inside a RooRealSumPdf then + // would be evaluated as a function! + } + + // check if we need to do any projecting of other observables + RooAbsReal *oldrar = nullptr; + auto _obs = obs(); + + for (auto o : _obs) { + if (auto rr = o->get(); rr && rr->hasRange("coordRange")) { + rr->removeRange("coordRange"); + } + } + coords(); // loads current coordinates and populates coordRange, if any + + if (auto a = dynamic_cast(v)) + _obs.get()->remove(*a); + if (!_obs.get()->empty()) { + oldrar = rar; + normSet.add(*_obs.get()); + // check if any obs are restricted range + bool hasRange = false; + for (auto o : normSet) { + if (auto rr = dynamic_cast(o); rr && rr->hasRange("coordRange")) { + hasRange = true; + break; + } + } + if (p) { + // need to handle special case of RooSimultaneous ... each pdf needs individually projecting over just its + // dependent obs + if (auto s = dynamic_cast(p)) { + auto newrar = new RooSimultaneous("projSim", "projSim", const_cast(s->indexCat())); + for (auto pdf : bins()) { + // auto _pdf = + // pdf->get()->createProjection(*pdf->get()->getObservables(*_obs.get())); + auto _pdf = + new xRooProjectedPdf(TString::Format("%s_projection", pdf->GetName()), "", *pdf->get(), + *pdf->get()->getObservables(*_obs.get())); + if (hasRange) { + dynamic_cast(_pdf)->setNormRange("coordRange"); + } + newrar->addPdf(*_pdf, pdf->coords()["channelCat"]->get()->getLabel()); + } + rar = newrar; + } else { + rar = p->createProjection( + *_obs.get()); // TODO should use xRooProjectedPdf here too, because not fixed range and + // extend behaviour of RooProjectedPdf in ROOT yet + if (hasRange) { + dynamic_cast(rar)->setNormRange("coordRange"); + } + } + if (hasRange) + p->setNormRange("coordRange"); // should get cleared when we sterilize + } else { + if (hasRange) { + // commented out passing of normset so that getVal of non-pdf is always a 'raw' value (needed for raw eval + // of RooRealSumPdf) + rar = std::unique_ptr{rar->createIntegral( + *_obs.get(), + /*RooFit::NormSet(normSet),*/ RooFit::Range("coordRange"))} + .release(); + } else { + rar = + std::unique_ptr{rar->createIntegral(*_obs.get() /*, RooFit::NormSet(normSet)*/)} + .release(); + } + } + } + + bool scaleExpected = (p && p->canBeExtended() && !_coefs.get()); + // Note about above: if pdf has coefficients then its embedded in a RooAddPdf that has coefs defined ... + // in this case we should *not* scale by expected, since the coefs become the scaling instead + + std::unique_ptr snap(normSet.snapshot()); + TStopwatch timeIt; + std::vector lapTimes; + bool warned = false; + if (binStart == -1 && binEnd == -1) { + binEnd = 1; + } + for (int i = std::max(1, binStart); i <= std::min(h->GetNbinsX(), binEnd); i++) { + timeIt.Start(true); + if (x) + x->setVal(h->GetBinCenter(i)); + else if (v) + v->setBin(i - 1); + if (x && !x->inRange("coordRange")) + continue; + + double r = 0; + if (!empty) { + r = /*(p && p->selfNormalized())*/ rar->getVal(p ? &normSet : nullptr); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + if (std::isnan(r) && RooNaNPacker::isNaNWithPayload(r)) { + r = -RooNaNPacker::unpackNaN(r); + } +#endif + if (r && _coefs.get()) { r *= _coefs.get()->getVal(normSet); } if (needBinWidth) { r *= h->GetBinWidth(i); } - if (p && p->canBeExtended()) { + if (scaleExpected) { + // std::cout << r << " exp = " << p->expectedEvents(normSet) << " for normRange " << (p->normRange() ? + // p->normRange() : "null") << std::endl; p->Print();rar->Print(); r *= (p->expectedEvents(normSet)); } // do in here in case dependency on var - h->SetBinContent(i, r); - - if (errors) { - double res; - if (p) { - // std::cout << "computing error of :" << h->GetBinCenter(i) << std::endl; - // //fr->floatParsFinal().Print(); fr->covarianceMatrix().Print(); - res = PdfWrapper(*p, _coefs.get()).getSimplePropagatedError(*fr, normSet); - p->_normSet = nullptr; - } else { - res = rar->getPropagatedError(*fr, normSet); - // TODO: What if coef has error? - probably need a FuncWrapper class - if (auto c = _coefs.get(); c) { - res *= c->getVal(normSet); - } - } - if (needBinWidth) { - res *= h->GetBinWidth(i); - } - h->SetBinError(i, res); + } + h->SetBinContent(i, r); + + if (errors) { + double res; + if (p) { + // std::cout << "computing error of :" << h->GetBinCenter(i) << std::endl; + // //fr->floatParsFinal().Print(); fr->covarianceMatrix().Print(); + res = PdfWrapper((oldrar) ? *rar : *p, _coefs.get(), !v, oldrar ? p : nullptr) + .getSimplePropagatedError(*fr, normSet); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards + p->_normSet = nullptr; +#endif + } else { + res = RooProduct("errorEval", "errorEval", + RooArgList(*rar, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get())) + .getPropagatedError(*fr, normSet); } - timeIt.Stop(); - lapTimes.push_back(timeIt.RealTime()); - double time_estimate = - (lapTimes.size() > 1) - ? (h->GetNbinsX() * (std::accumulate(lapTimes.begin() + 1, lapTimes.end(), 0.) / (lapTimes.size() - 1))) - : 0.; - if (!warned && (lapTimes.at(0) > 10 || (lapTimes.size() > 2 && time_estimate > 60.))) { - TTimeStamp t2; - t2.Add(time_estimate); - Warning("BuildHistogram", "Building this histogram will take until %s", t2.AsString()); - if (errors) { - // install interrupt handler - runningNode = this; - gOldHandlerr = signal(SIGINT, buildHistogramInterrupt); - } - warned = true; + if (needBinWidth) { + res *= h->GetBinWidth(i); + } + h->SetBinError(i, res); + } + timeIt.Stop(); + lapTimes.push_back(timeIt.RealTime()); + double time_estimate = + (lapTimes.size() > 1) + ? (h->GetNbinsX() * (std::accumulate(lapTimes.begin() + 1, lapTimes.end(), 0.) / (lapTimes.size() - 1))) + : 0.; + if (!warned && (lapTimes.at(0) > 10 || (lapTimes.size() > 2 && time_estimate > 60.))) { + TTimeStamp t2; + t2.Add(time_estimate); + Warning("BuildHistogram", "Building this histogram will take until %s", t2.AsString()); + if (errors) { + // install interrupt handler + runningNode = this; + gOldHandlerr = signal(SIGINT, buildHistogramInterrupt); } - if (fInterrupted) { - if (errors) { - Warning("BuildHistogram", "Skipping errors for remaining bins"); - errors = false; - } - fInterrupted = false; + warned = true; + } + if (fInterrupted) { + if (errors) { + Warning("BuildHistogram", "Skipping errors for remaining bins"); + errors = false; } + fInterrupted = false; } - if (gOldHandlerr) { - signal(SIGINT, gOldHandlerr); - gOldHandlerr = 0; + } + if (gOldHandlerr) { + signal(SIGINT, gOldHandlerr); + gOldHandlerr = 0; + } + normSet = *snap; + + if (oldrar) { + std::vector extra; + if (auto s = dynamic_cast(rar)) { + // need to delete all the subpdfs we created too + for (auto _pdf : s->servers()) + if (dynamic_cast(_pdf)) + extra.push_back(_pdf); } - normSet = *snap; + extra.push_back(rar); + rar = oldrar; + xRooNode(*rar).sterilize(); // need to clear the cache of the created integral - do this before deleting things! + for (auto a : extra) + delete a; + } else { + sterilize(); // needed to forget about the normSet that was passed to getVal() } - if (!p) { + if (!p && !rar->getAttribute("density") && !needBinWidth) { h->GetYaxis()->SetTitle(rar->getStringAttribute("units")); - } else if (p->canBeExtended()) { + } else if ((p && p->canBeExtended()) || (!p && needBinWidth)) { h->GetYaxis()->SetTitle("Events"); } else { h->GetYaxis()->SetTitle("Probability Mass"); } h->GetYaxis()->SetMaxDigits(3); - if (errors) + if (errors) { delete fr; - + } + //} return h; } @@ -6007,9 +7821,22 @@ std::vector xRooNode::GetBinContents(int binStart, int binEnd) const } std::vector out; if (get()) { - auto g = BuildGraph(nullptr, true /*include points for zeros*/); - if (!g) + auto g = BuildGraph( + nullptr, + (binStart != -1 || + binEnd != -1) /*include points for zeros unless we are asking for a single point with start=end=-1*/); + if (!g) { + return out; + } + if (binStart == binEnd && binStart == -1) { + // integral over all bins if getting bin content -1 + double integral(0); + for (int i = 0; i < g->GetN(); i++) + integral += g->GetPointY(i); + out.push_back(integral); + delete g; return out; + } for (int i = binStart - 1; i < g->GetN() && (binEnd == 0 || i < binEnd); i++) { out.push_back(g->GetPointY(i)); } @@ -6017,14 +7844,29 @@ std::vector xRooNode::GetBinContents(int binStart, int binEnd) const return out; } + bool doIntegral = false; + if (binStart == binEnd && binStart == -1) { + binStart = -1; + binEnd = -1; + doIntegral = true; + } // return integral if request bin -1 auto h = BuildHistogram(nullptr, false, false, binStart, binEnd); if (!h) { throw std::runtime_error(TString::Format("%s has no content", GetName())); } - if (binEnd == 0) + if (binEnd == 0) { binEnd = h->GetNbinsX(); - for (int i = binStart; i <= binEnd; i++) { - out.push_back(h->GetBinContent(i)); + } + if (doIntegral) { + double tot = 0; + for (int i = 1; i <= h->GetNbinsX(); i++) { + tot += h->GetBinContent(i); + } + out.push_back(tot); + } else { + for (int i = binStart; i <= binEnd; i++) { + out.push_back(h->GetBinContent(i)); + } } delete h; return out; @@ -6060,10 +7902,18 @@ void xRooNode::Inspect() const TNamed::Inspect(); } -Bool_t TopRightPlaceBox(TPad *p, TObject *o, Double_t w, Double_t h, Double_t &xl, Double_t &yb) +bool TopRightPlaceBox(TPad *p, TObject *o, double w, double h, double &xl, double &yb) { +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + // reinitialize collide grid because the filling depends on fUxmin and fUxmax (and ymin ymax too) + // and these aren't filled on the first time we do the placement (they init to 0 and 1), but will be filled + // subsequently + for (int i = 0; i < p->fCGnx; i++) { + for (int j = 0; j < p->fCGny; j++) { + p->fCollideGrid[i + j * p->fCGnx] = true; + } + } p->FillCollideGrid(o); - Int_t iw = (int)(p->fCGnx * w); Int_t ih = (int)(p->fCGny * h); @@ -6075,13 +7925,41 @@ Bool_t TopRightPlaceBox(TPad *p, TObject *o, Double_t w, Double_t h, Double_t &x if (p->Collide(i, j, iw, ih)) { continue; } else { - xl = (Double_t)(i) / (Double_t)(p->fCGnx); - yb = (Double_t)(j) / (Double_t)(p->fCGny); - return kTRUE; + xl = (double)(i) / (double)(p->fCGnx); + yb = (double)(j) / (double)(p->fCGny); + return true; } } } - return kFALSE; + return false; +#else + return p->PlaceBox(o, w, h, xl, yb, "trw"); +#endif +} + +TPaveText *getPave(const char *name = "labels", bool create = true, bool doPaint = false) +{ + if (auto p = dynamic_cast(gPad->GetPrimitive(name)); p) { + if (doPaint) + gPad->PaintModified(); //-- slows down x11 so trying to avoid + return p; + } + if (!create) { + return nullptr; + } + auto l = new TPaveText(gPad->GetLeftMargin() + 0.02, 1. - gPad->GetTopMargin() - 0.08, 0.6, + 1. - gPad->GetTopMargin() - 0.08); + l->SetBorderSize(0); + if (l->GetTextSize() == 0) + l->SetTextSize(gStyle->GetTitleYSize()); + + l->SetBit(kCanDelete); + // l->SetMargin(0); + l->SetFillStyle(0); + l->SetName(name); + l->Draw(); + l->ConvertNDCtoPad(); + return l; } TLegend *getLegend(bool create = true, bool doPaint = false) @@ -6093,7 +7971,7 @@ TLegend *getLegend(bool create = true, bool doPaint = false) gPad->PaintModified(); //-- slows down x11 so trying to avoid if (TopRightPlaceBox(dynamic_cast(gPad), p, w, h, x, y)) { // squash inside the frame .. - // std::cout << gPad->GetName() << ":" << x << " , " << y << " , " << h << " , " << w << std::endl; + // std::cout << gPad->GetName() << ":" << x << " , " << y << " , " << w << " , " << h << std::endl; x = std::max(x, (gPad->GetLeftMargin() + 0.02)); y = std::max(y, (gPad->GetBottomMargin() + 0.02)); x = std::min(x, (1. - gPad->GetRightMargin() - 0.02) - w); @@ -6129,9 +8007,10 @@ TLegend *getLegend(bool create = true, bool doPaint = false) } else { if (!create) return nullptr; - l = new TLegend(0.6, 1. - gPad->GetTopMargin() - 0.08, 1. - gPad->GetRightMargin(), - 1. - gPad->GetTopMargin() - 0.08); + l = new TLegend(0.6, 1. - gPad->GetTopMargin() - 0.08, 0.75, 1. - gPad->GetTopMargin() - 0.08); l->SetBorderSize(0); + if (l->GetTextSize() == 0) + l->SetTextSize(gStyle->GetTitleYSize()); } l->SetBit(kCanDelete); // l->SetMargin(0); @@ -6163,9 +8042,9 @@ void addLegendEntry(TObject *o, const char *title, const char *opt) nn *= (nn + 4); if (nObj > 1 && (nObj % nn) == 1) { l->SetNColumns(l->GetNColumns() + 1); - } else if (nObj <= nn && nObj >= l->GetNColumns() * l->GetNColumns()) { - l->SetY1NDC(l->GetY2NDC() - 0.05 * gPad->GetHNDC() * nObj); + l->SetX1NDC(l->GetX2NDC() - 0.15 * l->GetNColumns()); } + l->SetY1NDC(l->GetY2NDC() - 0.05 * gPad->GetHNDC() * std::ceil((double(nObj) / l->GetNColumns()))); } getLegend(); // to mark modified @@ -6180,7 +8059,9 @@ class PadRefresher { { if (fPad) { getLegend(false, true); - fPad->Update(); + fPad->GetCanvas()->Paint(); + fPad->GetCanvas()->Update(); + fPad->cd(); } nExisting--; } @@ -6192,8 +8073,64 @@ int PadRefresher::nExisting = 0; void xRooNode::Draw(Option_t *opt) { - if (!get() && !IsFolder()) + // in order to catch exceptions to prevent crash of GUI, do this: + if (gROOT->FromPopUp()) { + gROOT->SetFromPopUp(false); + try { + Draw(opt); + } catch (const std::exception &e) { + new TGMsgBox( + gClient->GetRoot(), + (gROOT->GetListOfBrowsers()->At(0)) + ? dynamic_cast(static_cast(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp()) + : gClient->GetRoot(), + "Exception", e.what(), + kMBIconExclamation); // deletes self on dismiss? + } + gROOT->SetFromPopUp(true); + return; + } + + TString sOpt2(opt); + sOpt2.ToLower(); + if (!get() && !IsFolder() && !sOpt2.Contains("x=")) + return; + + if (auto ir = get()) { + xRooHypoSpace(ir).Draw(opt); + gSystem->ProcessEvents(); + return; + } else if (get()) { + if (gPad) + gPad->Clear(); + xRooNLLVar::xRooHypoPoint(std::dynamic_pointer_cast(fComp)).Draw(opt); + if (gPad) { + gPad->GetCanvas()->Paint(); + gPad->GetCanvas()->Update(); + } + gSystem->ProcessEvents(); + return; + } + + if (sOpt2 == "pcls" && get() && fParent && fParent->get()) { + // use the first selected dataset + auto _dsets = fParent->datasets(); + // bool _drawn=false; + TString dsetName = ""; + for (auto &d : _dsets) { + if (d->get()->TestBit(1 << 20)) { + dsetName = d->get()->GetName(); + break; + } + } + auto hs = fParent->nll(dsetName.Data()).hypoSpace(get()->GetName()); + hs.limits("cls visualize"); + hs.SetName(TUUID().AsString()); + if (ws()) { + ws()->import(*hs.result()); + } return; + } if (auxFunctions.empty()) { // add the defaults: Ratio and Signif @@ -6229,8 +8166,57 @@ void xRooNode::Draw(Option_t *opt) } TString sOpt(opt); - TString sOpt2(sOpt); - sOpt2.ToLower(); + + RooAbsLValue *v = nullptr; + std::vector xPoints; + if (sOpt2.Contains("x=")) { + // specifying a particular var to scan over ... + int _idx = sOpt2.Index("x="); + int _eidx = sOpt2.Index(';', _idx); + TString varPart = sOpt(_idx + 2, (_eidx < 0 ? sOpt2.Length() : _eidx) - (_idx + 2)); + TString varName = varPart; + // if varName is of form str(num,num,num) then can infer scan points + if (auto _idx2 = varPart.Index("("); _idx2 > 0) { + varName = varPart(0, _idx2); + TStringToken pattern(TString(varPart(_idx2 + 1, varPart.Length() - _idx2 - 2)), ","); + double min(0), max(0); + int nBins = 0; + int ii = 0; + while (pattern.NextToken()) { + TString s = pattern; + if (ii == 0) + nBins = s.Atoi(); + else if (ii == 1) + min = s.Atof(); + else if (ii == 2) + max = s.Atof(); + ii++; + } + if (nBins > 100) + nBins = 100; // limit scanning to 100 points + if (nBins > 1) { + for (double x = min; x <= max; x += (max - min) / (nBins - 1)) { + xPoints.push_back(x); + } + } else if (nBins == 1) + xPoints.push_back((min + max) / 2.); + } + v = getObject(varName.Data()).get(); + if (!v) { + Error("Draw", "Could not find variable %s", varName.Data()); + return; // don't throw because if happens in browser will cause ROOT to exit + } + if (xPoints.empty() && !obs().find(varName.Data())) { // will draw obs as regular (e.g. hist) + double tmp = static_cast(v)->getVal(); + for (int i = 0; i < v->numBins(GetName()); i++) { + v->setBin(i, GetName()); + xPoints.push_back(static_cast(v)->getVal()); + } + static_cast(v)->setVal(tmp); + } + sOpt2 = TString(sOpt2(0, _idx)) + sOpt2(_idx + 2 + varPart.Length() + 1, sOpt2.Length()); + sOpt = TString(sOpt(0, _idx)) + sOpt(_idx + 2 + varPart.Length() + 1, sOpt.Length()); + } TString forceNames = ""; if (sOpt2.Contains("force")) { // force plots show how much NLL changes wrt to a change of variables @@ -6246,7 +8232,8 @@ void xRooNode::Draw(Option_t *opt) sOpt = sOpt(0, sOpt2.Index("force")); sOpt2 = sOpt2(0, sOpt2.Index("force")); } else { - throw std::runtime_error("Can only compute forces with PDFs"); + Error("Draw", "Can only compute forces with PDFs"); + return; // don't throw because will cause browser to exit if done from there } } bool hasOverlay = sOpt2.Contains("overlay"); @@ -6273,11 +8260,13 @@ void xRooNode::Draw(Option_t *opt) sOpt.ToLower(); sOpt.ReplaceAll("ratio", ""); sOpt.ReplaceAll("significance", ""); // remove old option if still given + bool nostack = sOpt.Contains("nostack"); + sOpt.ReplaceAll("nostack", ""); bool hasSame = sOpt.Contains("same"); sOpt.ReplaceAll("same", ""); bool hasGoff = sOpt.Contains("goff"); sOpt.ReplaceAll("goff", ""); - bool hasFR = sOpt.Contains("pull"); + bool hasFR = sOpt.Contains("pull") && !get(); sOpt.ReplaceAll("pull", ""); bool hasText = sOpt.Contains("text"); bool hasErrorOpt = sOpt.Contains("e"); @@ -6292,7 +8281,6 @@ void xRooNode::Draw(Option_t *opt) TVirtualPad *pad = gPad; TH1 *hAxis = nullptr; - RooAbsLValue *v = nullptr; auto clearPad = []() { gPad->Clear(); @@ -6323,7 +8311,7 @@ void xRooNode::Draw(Option_t *opt) break; } } - if (hAxis) { + if (hAxis && !v) { v = getObject(hAxis->GetXaxis()->GetName()).get(); } } @@ -6393,6 +8381,8 @@ void xRooNode::Draw(Option_t *opt) if (hh == hAxis && pad && ymin == 0 && pad->GetLogy()) { ymin = 1e-2; } + if (ymin == 0 && ymax > 10) + ymin = 0.1; // adjust min so if user activates log scale it isn't bad hh->SetMinimum(ymin); hh->SetMaximum(ymax); hh->GetYaxis()->Set(1, ymin, ymax); @@ -6411,6 +8401,30 @@ void xRooNode::Draw(Option_t *opt) return std::make_pair(ymin, ymax); }; + if (!xPoints.empty()) { + // create a graph using GetContent + TGraphAsymmErrors *out = new TGraphAsymmErrors; + out->SetName(GetName()); + out->SetTitle(GetTitle()); + out->SetFillColor(out->GetLineColor()); + out->SetMarkerStyle(0); + out->SetFillStyle(hasErrorOpt ? 3005 : 0); + double tmp = static_cast(v)->getVal(); + for (auto &x : xPoints) { + static_cast(v)->setVal(x); + out->AddPoint(x, GetContent()); + if (hasErrorOpt) { + out->SetPointEYlow(out->GetN() - 1, GetError()); + out->SetPointEYhigh(out->GetN() - 1, out->GetErrorYlow(out->GetN() - 1)); // symmetric error for now + } + } + static_cast(v)->setVal(tmp); + out->GetHistogram()->GetXaxis()->SetTitle(static_cast(v)->GetTitle()); + out->SetBit(kCanDelete); + out->Draw(TString(hasSame ? "L" : "AL") + (hasErrorOpt ? "3" : "")); + return; + } + if (hasFR) { // drawing the fitresult as a pull plot on a subpad, and rest of the draw elsewhere clearPad(); @@ -6433,18 +8447,22 @@ void xRooNode::Draw(Option_t *opt) gPad->SetBottomMargin(0); gPad->SetName("pull"); // split the pull graph into individual points -- for benefit of GUI status bar - auto pullGraph = - dynamic_cast(gPad->GetPrimitive(TString::Format("%s_pull", _fr->GetName()))); + auto pullGraph = dynamic_cast(gPad->GetPrimitive("pulls")); if (!pullGraph) { - throw std::runtime_error("Couldn't find pull graph"); + Error("Draw", "Couldn't find pull graph"); + return; } pullGraph->SetName("nominal"); TMultiGraph *mg = new TMultiGraph; mg->SetName("editables"); + auto scaleHist = static_cast(pullGraph->FindObject("scales")); + if (!scaleHist) + throw std::runtime_error("Could not find scales in fit result"); + for (auto i = 0; i < pullGraph->GetN(); i++) { auto g = new TGraphAsymmErrors; - g->SetName(pullGraph->GetHistogram()->GetXaxis()->GetBinLabel(i + 1)); + g->SetName(scaleHist->GetXaxis()->GetBinLabel(i + 1)); auto _p = dynamic_cast(_fr.get()->floatParsFinal().find(g->GetName())); if (!_p) { Warning("Draw", "Found a non-var in the floatParsFinal list: %s - this shouldn't happen", g->GetName()); @@ -6454,7 +8472,7 @@ void xRooNode::Draw(Option_t *opt) "%s=%g +/- %s [%g,%g]", strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName(), _p->getVal(), _p->hasAsymError() ? TString::Format("(%g,%g)", _p->getAsymErrorHi(), _p->getAsymErrorLo()).Data() : TString::Format("%g", _p->getError()).Data(), - pullGraph->GetHistogram()->GetBinContent(i + 1), pullGraph->GetHistogram()->GetBinError(i + 1))); + scaleHist->GetBinContent(i + 1), scaleHist->GetBinError(i + 1))); g->SetPoint(0, pullGraph->GetPointX(i), pullGraph->GetPointY(i)); g->SetPointEYhigh(0, pullGraph->GetErrorYhigh(i)); g->SetPointEYlow(0, pullGraph->GetErrorYlow(i)); @@ -6472,9 +8490,10 @@ void xRooNode::Draw(Option_t *opt) _thisClone->AppendPad(); // ensure statusbar visible for interactive plot - if (gPad->GetCanvas() && !gPad->GetCanvas()->TestBit(TCanvas::kShowEventStatus)) { - gPad->GetCanvas()->ToggleEventStatus(); - } + // turned this off for now ... as not needed if doing through browser, status bar already there + // if (gPad->GetCanvas() && !gPad->GetCanvas()->TestBit(TCanvas::kShowEventStatus)) { + // gPad->GetCanvas()->ToggleEventStatus(); + // } gPad->AddExec("interactivePull", TString::Format("%s::Interactive_Pull()", ClassName())); pad->cd(); @@ -6483,7 +8502,7 @@ void xRooNode::Draw(Option_t *opt) if (auto _simPdf = get(); _simPdf) { int _size = 0; - auto _channels = variations(); + auto _channels = bins(); for (auto &_v : _channels) { if (!_v->IsHidden()) _size++; @@ -6619,9 +8638,121 @@ void xRooNode::Draw(Option_t *opt) } if (auto fr = get(); fr) { - // auto graph = BuildGraph(); + if (sOpt.Contains("corr")) { + // do correlation matrix + + auto hist = fr->correlationHist(fr->GetName()); + hist->SetTitle(fr->GetTitle()); + hist->SetBit(kCanDelete); + hist->Scale(100); + hist->SetStats(false); + hist->SetDirectory(nullptr); + TString b(gStyle->GetPaintTextFormat()); + gStyle->SetPaintTextFormat(".1f"); + hist->GetXaxis()->SetTickSize(0); + hist->GetYaxis()->SetTickSize(0); + hist->SetMinimum(-100); + hist->Draw(sOpt); + gStyle->SetPaintTextFormat(b); + gPad->SetGrid(1, 1); + gPad->SetLogy(0); + gPad->SetLogx(0); + return; + } + + if (sOpt.Contains("brakdown")) { // e will have been removed above + + // breakdown is quadrature difference between total error and conditional error + // group by 'group' attribute + + std::string poiName; + if (sOpt.Contains("brakdown:")) { + poiName = sOpt(sOpt.Index("brakdown:") + 9, sOpt.Length()); + } else { + std::unique_ptr _poi(fr->floatParsFinal().selectByAttrib("poi", true)); + if (_poi->empty()) { + throw std::runtime_error("No floating poi in the fit"); + } else if (_poi->size() != 1) { + throw std::runtime_error("Multiple poi in the fit"); + } + poiName = _poi->first()->GetName(); + } + RooRealVar *poi = dynamic_cast(fr->floatParsFinal().find(poiName.c_str())); + if (!poi) { + throw std::runtime_error(TString::Format("Cannot find parameter %s", poiName.c_str())); + } + std::set groups; + for (auto p : fr->floatParsFinal()) { + if (p == poi) + continue; + else if (p->getStringAttribute("group")) + groups.insert(p->getStringAttribute("group")); + else + groups.insert(p->GetTitle()); + } + + auto roundedVal = xRooFit::matchPrecision(std::pair(poi->getVal(), poi->getError())); + + TPie *pie = new TPie(TString::Format("breakdown:%s", poi->GetName()), + TString::Format("%s: %g #pm %g", poi->GetTitle(), roundedVal.first, roundedVal.second), + groups.size() + 1); + + // for display of errors will go to one extra dp ... + roundedVal.second *= .1; - // plot pull + // do breakdown by removing parameters in blocks according to groups and seeing impact on variance + // this will give the correct sum but will be order-dependent if there are correlations between + // groups. therefore we will stick with group-by-group + // RooArgList pars(fr->floatParsFinal()); // pars to not condition on + // double variance = pow(dynamic_cast(poi)->getError(),2); + int i = 0; + for (auto group : groups) { + RooArgList pars(fr->floatParsFinal()); // pars to not condition on + double variance = pow(dynamic_cast(poi)->getError(), 2); + for (auto p : fr->floatParsFinal()) { + if (p == poi) + continue; + else if ((p->getStringAttribute("group") && group == p->getStringAttribute("group")) || + (!p->getStringAttribute("group") && group == p->GetTitle())) { + // conditioning on this parameter ... remove from pars list + pars.remove(*p); + } + } + int idx = pars.index(poiName.c_str()); + double reducedVar = fr->conditionalCovarianceMatrix(pars)(idx, idx); + if (reducedVar > variance) { + Warning("Draw", "breakdown group %s variance bigger than preceding?", group.c_str()); + pie->SetEntryVal(i, 0); + pie->SetEntryLabel(i, TString::Format("%s: NaN", group.c_str())); + } else { + pie->SetEntryVal(i, variance - reducedVar); + auto r = xRooFit::matchPrecision( + std::pair(sqrt(variance - reducedVar), roundedVal.second)); // r.first will be the rounded error + if (r.first > 0) { + pie->SetEntryLabel(i, TString::Format("%s: %g", group.c_str(), r.first)); + } else { + pie->SetEntryLabel(i, group.c_str()); // suppress labels for negligible errors. + } + } + pie->SetEntryFillColor(i, TColor::GetColorPalette(TColor::GetNumberOfColors() * i / pie->GetEntries())); + // variance = reducedVar; + i++; + } + // remaining variance is statistical= + double variance = fr->conditionalCovarianceMatrix(*poi)(0, 0); + auto r = + xRooFit::matchPrecision(std::pair(sqrt(variance), roundedVal.second)); // r.first will be the rounded error + pie->SetEntryVal(i, variance); + pie->SetEntryLabel(i, TString::Format("stat: %g", r.first)); + pie->SetEntryFillColor(i, TColor::GetColorPalette(TColor::GetNumberOfColors() * i / pie->GetEntries())); + pie->SetBit(kCanDelete); + pie->SetRadius(0.17); + pie->SetTextSize(gStyle->GetTitleYSize()); + pie->Draw("NOL"); + return; + } + + // plot pull or impact TGraphAsymmErrors *out = new TGraphAsymmErrors; out->SetName(TString::Format("%s_pull", fr->GetName())); out->SetTitle("Fit Result Pulls"); @@ -6636,18 +8767,46 @@ void xRooNode::Draw(Option_t *opt) auto _v = dynamic_cast(p); if (!_v) continue; + + if (std::isnan(_v->getErrorHi()) || std::isnan(_v->getErrorLo())) { + Warning("Draw", "%s error is invalid", _v->GetName()); + } + // need to get constraint mean and error parameters .... // look for normal gaussian and poisson cases - double prefitError = dynamic_cast(fr->floatParsInit().find(p->GetName()))->getError(); - double prefitVal = dynamic_cast(fr->floatParsInit().find(p->GetName()))->getVal(); + double prefitError = 0; + double prefitVal = 0; + double customScale = 0; + if (auto ip = + dynamic_cast(fr->floatParsInit().find(p->GetName()))) { // handles if no prefit available + prefitError = ip->getError(); + prefitVal = ip->getVal(); + }; std::shared_ptr pConstr; if (fParent && fParent->getObject(p->GetName())) { - auto _constr = xRooNode(fParent->getObject(p->GetName()), *this).constraints(); + auto _vv = fParent->getObject(p->GetName()); + if (_vv->hasRange("pullScale")) { + customScale = (_vv->getMax("pullScale") - _vv->getMin("pullScale")) / 2.; + } + auto _constr = xRooNode(_vv, *this).constraints(); for (auto &c : _constr) { if (c->get() || c->get()) { - pConstr = c; - break; + // require parameter to be a direct server of the constraint pdf to count if its a gaussian + bool isServer = true; + if (c->get()) { + isServer = false; + for (auto s : c->get()->servers()) { + if (strcmp(s->GetName(), p->GetName()) == 0) { + isServer = true; + break; + } + } + } + if (isServer) { + pConstr = c; + break; + } } } } @@ -6667,14 +8826,16 @@ void xRooNode::Draw(Option_t *opt) continue; if (xName == _d->get()->GetName()) continue; - prefitError = _d->get()->getVal(); + if (_d->get()->getVal()) + prefitError = _d->get()->getVal(); } // prefitVal will be the global observable value, need to divide that by tau prefitVal /= prefitError; // prefiterror will be tau ... need 1/sqrt(tau) for error prefitError = 1. / sqrt(prefitError); } else if (auto _g = pConstr->get(); _g) { - prefitError = (pConstr->find(".sigma")) ? pConstr->find(".sigma")->get()->getVal() : 0; + prefitError = + (pConstr->find(".sigma")) ? pConstr->find(".sigma")->get()->getVal() : prefitError; prefitVal = (pConstr->find(".x")) ? pConstr->find(".x")->get()->getVal() : 0; // usually the globs if (pConstr->find(".x") && @@ -6684,8 +8845,8 @@ void xRooNode::Draw(Option_t *opt) } } - if (prefitError == 0) - prefitError = dynamic_cast(fr->floatParsInit().find(p->GetName()))->getError(); + if (customScale) + prefitError = customScale; if (prefitError == 0) { Warning("Draw", "failed to determine prefit error of %s, using post-fit error", p->GetName()); prefitError = _v->getError(); @@ -6698,12 +8859,11 @@ void xRooNode::Draw(Option_t *opt) offset[p->GetName()] = prefitVal; } else if (!fParent) { // no parent to determine constraints from ... prefitError=0 will be the unconstrained ones + if (customScale) + prefitError = customScale; if (prefitError == 0) { - // uses range of var if no postfit error either - prefitError = - (_v->getError()) - ? _v->getError() - : (std::max(std::max(_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin()), 4.) / 4); + // uses range of var + prefitError = (std::max({_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin(), 4.}) / 4); ugraph->SetPoint(ugraph->GetN(), ugraph->GetN(), (_v->getVal() - prefitVal) / prefitError); ugraph->SetPointError(ugraph->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError, (_v->getErrorHi()) / prefitError); @@ -6718,13 +8878,11 @@ void xRooNode::Draw(Option_t *opt) offset[p->GetName()] = prefitVal; } else { - // unconstrained (or at least couldn't determine constraint) ... use postfit error if no prefit error + // unconstrained (or at least couldn't determine constraint) ... use par range if no prefit error + if (customScale) + prefitError = customScale; if (prefitError == 0) { - // uses range of var if no postfit error either - prefitError = - (_v->getError()) - ? _v->getError() - : (std::max(std::max(_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin()), 4.) / 4); + prefitError = (std::max({_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin(), 4.}) / 4); } ugraph->SetPoint(ugraph->GetN(), ugraph->GetN(), (_v->getVal() - prefitVal) / prefitError); ugraph->SetPointError(ugraph->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError, @@ -6746,86 +8904,432 @@ void xRooNode::Draw(Option_t *opt) graph->Merge(&tmpList); tmpList.RemoveAll(); delete ugraph; + for (auto &l : ugraphLabels) { + graphLabels.push_back(l); + } graph->SetBit(kCanDelete); graph->SetMarkerStyle(20); graph->SetMarkerSize(0.5); - auto t = TH1::AddDirectoryStatus(); - TH1::AddDirectory(false); - auto hist = new TH1F(TString::Format(".%s_pullFrame", GetName()), fr->GetTitle(), std::max(graph->GetN(), 1), - -0.5, std::max(graph->GetN(), 1) - 0.5); + graph->SetMaximum(4); + graph->SetMinimum(-4); + + bool doHorizontal = + (!sOpt.Contains("impact") && sOpt.Contains("v")) || (sOpt.Contains("impact") && !sOpt.Contains("h")); + + std::vector> covariances; + /*double poiError = 0;*/ std::string poiName; + double maxImpact = 0; + if (sOpt.Contains("impact")) { + if (sOpt.Contains("impact:")) { + poiName = sOpt(sOpt.Index("impact:") + 7, sOpt.Length()); + } else { + std::unique_ptr _poi(fr->floatParsFinal().selectByAttrib("poi", true)); + if (_poi->empty()) { + throw std::runtime_error("No floating poi in the fit"); + } else if (_poi->size() != 1) { + throw std::runtime_error("Multiple poi in the fit"); + } + poiName = _poi->first()->GetName(); + } + RooAbsArg *poi = fr->floatParsFinal().find(poiName.c_str()); + if (!poi) { + throw std::runtime_error(TString::Format("Cannot find parameter %s", poiName.c_str())); + } + size_t poiIdx = fr->floatParsFinal().index(*poi); + // put parameters in order of impact on the poi + + // impact is regression coefficient * npError + // relevant regression coefficient is cov / (npVariance) + // i.e. DeltaX/sigmaX = [cov(X,Y)/(sigmaXsigmaY)]DeltaY/sigmaY + // ... DeltaX = [cov(X,Y)/(sigmaY^2)]DeltaY + // if DeltaY is just sigmaY then DeltaX = cov(X,Y)/sigmaY + + for (auto &label : graphLabels) { + covariances.emplace_back(fr->covarianceMatrix()(poiIdx, fr->floatParsFinal().index(label)) / + dynamic_cast(fr->floatParsFinal().find(label))->getError(), + label); + } + std::sort(covariances.begin(), covariances.end(), + [&](std::pair i, std::pair j) { + return doHorizontal ? (std::abs(i.first) < std::abs(j.first)) + : (std::abs(i.first) > std::abs(j.first)); + }); + + TGraphAsymmErrors sortedGraph; + std::vector sortedLabels; + maxImpact = (doHorizontal) ? covariances.back().first + : covariances.front().first; // note: max impact is likely to be self variance + for (auto &c : covariances) { + if (c.second == poi->GetName()) { + // poiError = sqrt(c.first); + continue; // skip self + } + c.first *= 4. / (maxImpact * 1.2); + sortedLabels.push_back(c.second); + size_t i = 0; + for (; i < graphLabels.size(); i++) { + if (graphLabels[i] == c.second) { + break; + } + } + sortedGraph.AddPoint(sortedGraph.GetN(), graph->GetPointY(i)); + sortedGraph.SetPointError(sortedGraph.GetN() - 1, 0, 0, graph->GetErrorYlow(i), graph->GetErrorYhigh(i)); + } + graph->Set(0); + TList tmpList2; + tmpList2.SetName("tmpList"); + tmpList2.Add(&sortedGraph); + graph->Merge(&tmpList2); + tmpList2.RemoveAll(); + graphLabels = sortedLabels; + graph->SetTitle("Fit Result Impact"); + } + + // create a framing histogram + TH2D *hist; + if (doHorizontal) { + hist = new TH2D(GetName(), fr->GetTitle(), 100, -4, 4, std::max(graph->GetN(), 1), -0.5, + std::max(graph->GetN(), 1) - 0.5); + int i = 1; + for (auto &l : graphLabels) { + hist->GetYaxis()->SetBinLabel(i++, l); + } + if (!graphLabels.empty()) + hist->GetYaxis()->LabelsOption("v"); + hist->GetXaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}"); + } else { + hist = new TH2D(GetName(), fr->GetTitle(), std::max(graph->GetN(), 1), -0.5, std::max(graph->GetN(), 1) - 0.5, + 100, -4, 4); + int i = 1; + for (auto &l : graphLabels) { + hist->GetXaxis()->SetBinLabel(i++, l); + } + if (!graphLabels.empty()) + hist->GetXaxis()->LabelsOption("v"); + hist->GetYaxis()->SetNdivisions(8, 0, 0); + hist->GetYaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}"); + } hist->SetStats(false); - TH1::AddDirectory(t); + hist->SetDirectory(nullptr); hist->SetBit(kCanDelete); - int i = 1; - for (auto &l : graphLabels) { - hist->GetXaxis()->SetBinLabel(i++, l); - } - for (auto &l : ugraphLabels) { - hist->GetXaxis()->SetBinLabel(i++, l); - } - hist->SetMaximum(4); - hist->SetMinimum(-4); - if (graph->GetN()) - hist->GetXaxis()->LabelsOption("v"); - hist->GetYaxis()->SetNdivisions(8, 0, 0); - hist->GetYaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}"); - hAxis = hist; + auto histCopy = dynamic_cast(hist->Clone(".axis")); + histCopy->SetDirectory(0); + histCopy->SetBit(kCanDelete); + auto _axis = (doHorizontal ? histCopy->GetYaxis() : histCopy->GetXaxis()); + + /* + auto t = TH1::AddDirectoryStatus(); + TH1::AddDirectory(false); + auto hist = new TH1F(TString::Format(".%s_pullFrame", GetName()), fr->GetTitle(), std::max(graph->GetN(), + 1), -0.5, std::max(graph->GetN(), 1) - 0.5); hist->SetStats(false); TH1::AddDirectory(t); + hist->SetBit(kCanDelete); + */ + // auto hist = graph->GetHistogram(); + graph->GetHistogram()->GetXaxis()->Set(std::max(graph->GetN(), 1), -0.5, std::max(graph->GetN(), 1) - 0.5); + for (int ii = 1; ii <= _axis->GetNbins(); ii++) { + graph->GetHistogram()->GetXaxis()->SetBinLabel(ii, _axis->GetBinLabel(ii)); + } + // int i = 1; + // for (auto &l : graphLabels) { + // hist->GetXaxis()->SetBinLabel(i++, l); + // } + // hist->SetMaximum(4); + // hist->SetMinimum(-4); + // if (graph->GetN()) + // hist->GetXaxis()->LabelsOption("v"); + // hist->GetYaxis()->SetNdivisions(8, 0, 0); + // hist->GetYaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}"); clearPad(); // create a new pad because adjust the margins ... auto oldPad = gPad; gPad->Divide(1, 1, 1e-9, 1e-9); gPad->cd(1); - gPad->SetBottomMargin(0.4); - auto pNamesHist = dynamic_cast(hist->Clone("pnames")); + if (doHorizontal) { + gPad->SetLeftMargin(0.4); + } else { + gPad->SetBottomMargin(0.4); + } + + auto pNamesHist = dynamic_cast(graph->GetHistogram()->Clone("scales")); // used by interactive "pull" plot pNamesHist->Sumw2(); pNamesHist->SetDirectory(0); for (int ii = 1; ii <= graph->GetN(); ii++) { // use graph->GetN() to protect against the 0 pars case - auto _p = fr->floatParsFinal().find(hist->GetXaxis()->GetBinLabel(ii)); + auto _p = fr->floatParsFinal().find(_axis->GetBinLabel(ii)); pNamesHist->SetBinContent(ii, offset[_p->GetName()]); pNamesHist->SetBinError(ii, scale[_p->GetName()]); - hist->GetXaxis()->SetBinLabel(ii, strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName()); - } - - hist->Draw(); - - for (int ii = 2; ii >= 1; ii--) { - auto pullBox = new TGraphErrors; - pullBox->SetBit(kCanDelete); - pullBox->SetPoint(0, -0.5, 0); - pullBox->SetPoint(1, hist->GetNbinsX() - 0.5 - nUnconstrained, 0); - pullBox->SetPointError(0, 0, ii); - pullBox->SetPointError(1, 0, ii); - pullBox->SetFillColor((ii == 2) ? kYellow : kGreen); - pullBox->Draw("3"); - } - auto pullLine = new TGraph; - pullLine->SetBit(kCanDelete); - pullLine->SetPoint(0, -0.5, 0); - pullLine->SetPoint(1, hist->GetNbinsX() - 0.5 - nUnconstrained, 0); - pullLine->SetLineStyle(2); - pullLine->SetEditable(false); - pullLine->Draw("l"); - if (nUnconstrained > 0) { - pullLine = new TGraph; + _axis->SetBinLabel(ii, strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName()); + } + + // hist->Draw(); -- now just draw the graph + + if (!sOpt.Contains("impact")) { + for (int ii = 2; ii >= 1; ii--) { + auto pullBox = new TGraphErrors; + pullBox->SetName(TString::Format("%dsigmaBand", ii)); + pullBox->SetBit(kCanDelete); + pullBox->SetPoint(0, (doHorizontal) ? -ii : -0.5, (doHorizontal) ? -0.5 : 0); + pullBox->SetPoint(1, (doHorizontal) ? ii : (_axis->GetNbins() - 0.5 - nUnconstrained), + (doHorizontal) ? -0.5 : 0); + pullBox->SetPointError(0, 0, (doHorizontal) ? (_axis->GetNbins() - nUnconstrained) : ii); + pullBox->SetPointError(1, 0, (doHorizontal) ? (_axis->GetNbins() - nUnconstrained) : ii); + pullBox->SetFillColor((ii == 2) ? kYellow : kGreen); + hist->GetListOfFunctions()->Add(pullBox, "3"); // pullBox->Draw("3"); + } + auto pullLine = new TGraph; + pullLine->SetName("0sigmaLine"); pullLine->SetBit(kCanDelete); - pullLine->SetPoint(0, graph->GetN() - 0.5 - nUnconstrained, -100); - pullLine->SetPoint(1, graph->GetN() - 0.5 - nUnconstrained, 100); + pullLine->SetPoint(0, -0.5, 0); + pullLine->SetPoint(1, _axis->GetNbins() - 0.5, 0); pullLine->SetLineStyle(2); pullLine->SetEditable(false); - pullLine->Draw("l"); + hist->GetListOfFunctions()->Add(pullLine, "l"); // pullLine->Draw("l"); + + // also draw vertical line separating constrained from unconstrained, if necessary + if (nUnconstrained > 0) { + pullLine = new TGraph; + pullLine->SetName("dividerLine"); + pullLine->SetBit(kCanDelete); + pullLine->SetPoint(0, graph->GetN() - 0.5 - nUnconstrained, -100); + pullLine->SetPoint(1, graph->GetN() - 0.5 - nUnconstrained, 100); + pullLine->SetLineStyle(2); + pullLine->SetEditable(false); + hist->GetListOfFunctions()->Add(pullLine, "l"); // pullLine->Draw("l"); + } + + // and draw a pave with fr status info + TPaveText *pave = + new TPaveText(gPad->GetLeftMargin(), 1. - gPad->GetTopMargin(), 1. - gPad->GetRightMargin(), 0.98, "NDCNB"); + pave->SetFillStyle(0); + pave->SetBorderSize(0); + pave->SetMargin(0.); + pave->SetName("status"); + pave->SetTextAlign(31); + pave->AddText(TString::Format("minNLL: %g edm: %g", fr->minNll(), fr->edm())); + std::string covQualTxt; + switch (fr->covQual()) { + case -1: covQualTxt = "Unknown"; break; + case 0: covQualTxt = "Not calculated"; break; + case 1: covQualTxt = "Approximate"; break; + case 2: covQualTxt = "Forced Positive-Definite"; break; + case 3: covQualTxt = "Accurate"; break; + } + pave->AddText(TString::Format("Cov. Quality: %d (%s)", fr->covQual(), covQualTxt.c_str())) + ->SetTextColor((fr->covQual() == 3) ? kBlack : kRed); + + std::string statusCodes; + for (unsigned int i = 0; i < fr->numStatusHistory(); i++) { + statusCodes += TString::Format(" %s = %d", fr->statusLabelHistory(i), fr->statusCodeHistory(i)); + } + pave->AddText(statusCodes.c_str())->SetTextColor(fr->status() == 0 ? kBlack : kRed); + + hist->GetListOfFunctions()->Add(pave); + + } else { + gPad->SetTicks(0, 0); // ensure mirrored ticks aren't drawn in this pad + + if (doHorizontal) { + // ensure canvas height big enough + if (int(gPad->GetCanvas()->GetWh()) < pNamesHist->GetNbinsX() * 15) { + gPad->GetCanvas()->SetCanvasSize(gPad->GetCanvas()->GetWw(), pNamesHist->GetNbinsX() * 15); + } + } + + double factor = 475. / gPad->GetCanvas()->GetWh(); // Wh is the full canvas height, not window height + gPad->SetTopMargin(gStyle->GetPadTopMargin() * factor); // fixed margin height + gPad->SetBottomMargin(gStyle->GetPadBottomMargin() * factor); // fixed margin height + + TGaxis *axis = + new TGaxis(_axis->GetXmin(), -4, _axis->GetXmin(), 4, -1.2 * maxImpact, 1.2 * maxImpact, 510, "-S"); + axis->SetTextFont(_axis->GetTitleFont()); + axis->SetLabelFont(_axis->GetLabelFont()); + axis->SetTextSize((axis->GetTextFont() % 10 > 2) ? (10 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / + (gPad->GetY2() - gPad->GetY1()))); + axis->SetTitle(TString::Format("#Delta %s", fr->floatParsFinal().find(poiName.c_str())->GetTitle())); + axis->SetTickSize(axis->GetTickSize() * factor); + + if (doHorizontal) { + axis->SetLabelSize( + (axis->GetLabelFont() % 10 > 2) + ? (10 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / (gPad->GetY2() - gPad->GetY1()))); + // axis->SetTextSize(axis->GetTextSize()*factor); + axis->SetTitleSize( + (axis->GetTextFont() % 10 > 2) + ? (10 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / (gPad->GetY2() - gPad->GetY1()))); + axis->SetTitleOffset(axis->GetTitleOffset() * factor); + // axis->SetLabelOffset(axis->GetLabelOffset()*factor); + _axis->SetLabelSize( + (_axis->GetLabelFont() % 10 > 2) + ? (10 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / (gPad->GetY2() - gPad->GetY1()))); + histCopy->GetXaxis()->SetTickLength(histCopy->GetXaxis()->GetTickLength() * factor); + hist->GetXaxis()->SetTickLength(hist->GetXaxis()->GetTickLength() * factor); + histCopy->GetYaxis()->SetTickLength(histCopy->GetYaxis()->GetTickLength() * factor); + hist->GetYaxis()->SetTickLength(hist->GetYaxis()->GetTickLength() * factor); + histCopy->GetXaxis()->SetTitleOffset(histCopy->GetXaxis()->GetTitleOffset() * factor); + histCopy->GetXaxis()->SetLabelOffset(histCopy->GetXaxis()->GetLabelOffset() * factor); + hist->GetXaxis()->SetTitleOffset(hist->GetXaxis()->GetTitleOffset() * factor); + hist->GetXaxis()->SetLabelOffset(hist->GetXaxis()->GetLabelOffset() * factor); + histCopy->GetXaxis()->SetTitleOffset(histCopy->GetXaxis()->GetTitleOffset() * factor); + histCopy->GetXaxis()->SetLabelOffset(histCopy->GetXaxis()->GetLabelOffset() * factor); + } + + // create impact bar charts + for (int tt = 0; tt < 2; tt++) { + auto impact = static_cast( + graph->GetHistogram()->Clone(TString::Format("%s_impact+", tt == 0 ? "prefit" : "postfit"))); + impact->SetDirectory(0); + impact->GetYaxis()->SetTitle(TString::Format("#Delta%s/#sigma", poiName.c_str())); + impact->SetBarWidth(0.9); + impact->SetBarOffset(0.05); + impact->SetLineColor(kBlack); + impact->SetFillColor(kAzure - 4); + impact->SetFillStyle(tt == 0 ? 3013 : 1001); + auto impact2 = + static_cast(impact->Clone(TString::Format("%s_impact-", tt == 0 ? "prefit" : "postfit"))); + impact2->SetDirectory(0); + impact2->SetFillColor(kCyan); + for (int ii = 1; ii <= pNamesHist->GetNbinsX(); ii++) { + for (auto &c : covariances) { + if (c.second != pNamesHist->GetXaxis()->GetBinLabel(ii)) + continue; + auto vv = dynamic_cast(fr->floatParsFinal().find(c.second.c_str())); + auto vv_init = dynamic_cast(fr->floatParsInit().find(c.second.c_str())); + impact->SetBinContent(ii, ((tt == 0 && !vv_init->hasError()) || !vv->hasError()) + ? 0. + : c.first * vv->getError() / vv->getErrorHi() * + (tt == 0 ? (vv_init->getErrorHi() / vv->getErrorHi()) : 1.)); + impact2->SetBinContent(ii, ((tt == 0 && !vv_init->hasError()) || !vv->hasError()) + ? 0. + : c.first * vv->getError() / vv->getErrorLo() * + (tt == 0 ? (vv_init->getErrorLo() / vv->getErrorLo()) : 1.)); + } + } + hist->GetListOfFunctions()->Add(impact, (doHorizontal) ? "hbarsamemin0" : "bsamey+"); + hist->GetListOfFunctions()->Add(impact2, (doHorizontal) ? "hbarsamemin0" : "bsamey+"); + } + // add three lines + for (int ii = -1; ii <= 1; ii++) { + auto pullLine = new TGraph; + pullLine->SetName(TString::Format("%dsigmaLine", ii)); + pullLine->SetBit(kCanDelete); + pullLine->SetPoint(0, -0.5, ii); + pullLine->SetPoint(1, hist->GetNbinsY() - 0.5, ii); + pullLine->SetLineStyle(2); + pullLine->SetEditable(false); + hist->GetListOfFunctions()->Add(pullLine, "l"); + } + hist->GetListOfFunctions()->Add(axis); // draw axis last + TLegend *leg1 = + new TLegend(0.02, doHorizontal ? (1. - 0.22 * factor) : 0.02, 0.27, (doHorizontal ? 1. : 0.24)); + leg1->SetFillStyle(0); + leg1->SetBorderSize(0); + leg1->SetMargin(0.25); + leg1->SetNColumns(2); + + leg1->SetTextSize((leg1->GetTextFont() % 10 > 2) ? (10 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / + (gPad->GetY2() - gPad->GetY1()))); + // leg1.SetTextFont(gStyle->GetTextFont()); + // leg1.SetTextSize(gStyle->GetTextSize()); + leg1->AddEntry((TObject *)nullptr, "Hessian Pre-fit", ""); + leg1->AddEntry((TObject *)nullptr, "Impact:", ""); + leg1->AddEntry(hist->FindObject("prefit_impact+"), "#theta = #hat{#theta}+#Delta#theta", "f"); + leg1->AddEntry(hist->FindObject("prefit_impact-"), "#theta = #hat{#theta}-#Delta#theta", "f"); + leg1->AddEntry((TObject *)nullptr, "Hessian Post-fit", ""); + leg1->AddEntry((TObject *)nullptr, "Impact:", ""); + leg1->AddEntry(hist->FindObject("postfit_impact+"), "#theta = #hat{#theta}+#Delta#theta", "f"); + leg1->AddEntry(hist->FindObject("postfit_impact-"), "#theta = #hat{#theta}-#Delta#theta", "f"); + + hist->GetListOfFunctions()->Add(leg1); + if (gStyle->GetOptTitle()) { + histCopy->SetBit(TH1::kNoTitle); + TPaveText *title = + new TPaveText(gPad->GetLeftMargin(), 1. - gPad->AbsPixeltoY(14), 1. - gPad->GetRightMargin(), 1., "NDC"); + title->ConvertNDCtoPad(); + title->SetY1NDC(1. - gPad->GetTopMargin() * 0.6); + title->SetY2NDC(1); + title->SetTextSize( + (title->GetTextFont() % 10 > 2) + ? (14 / factor) + : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / (gPad->GetY2() - gPad->GetY1()))); + title->SetFillStyle(0); + title->SetBorderSize(0); + title->AddText(histCopy->GetTitle()); + hist->GetListOfFunctions()->Add(title); + } } - auto minMax = graphMinMax(graph); - adjustYRange(minMax.first, minMax.second); graph->SetEditable(false); - graph->SetHistogram(pNamesHist); - graph->Draw("z0p"); - hist->Draw( - "axissame"); // overlay axis again -- important is last so can remove if don't pad->Update before reclear + pNamesHist->SetLineWidth(0); + pNamesHist->SetMarkerSize(0); + graph->GetListOfFunctions()->Add(pNamesHist, "same"); // graph->SetHistogram(pNamesHist); + if (doHorizontal) { + + // flip the graph and contained graphs + for (int p = 0; p < graph->GetN(); p++) { + graph->SetPoint(p, graph->GetPointY(p), graph->GetPointX(p)); + graph->SetPointError(p, graph->GetErrorYlow(p), graph->GetErrorYhigh(p), graph->GetErrorXlow(p), + graph->GetErrorXhigh(p)); + } + for (auto f : *hist->GetListOfFunctions()) { + if (f->InheritsFrom("TH1")) { + // f->Draw("hbarsamemin0"); + } /*else if (auto g2 = dynamic_cast(f)) { + for (int p = 0; p < g2->GetN(); p++) { + g2->SetPoint(p, g2->GetPointY(p), g2->GetPointX(p)); + g2->SetPointError(p, g2->GetErrorY(p), _axis->GetNbins()); + } + //g2->Draw("3"); + } */ + else if (auto g = dynamic_cast(f)) { + for (int p = 0; p < g->GetN(); p++) { + g->SetPoint(p, g->GetPointY(p), g->GetPointX(p)); + } + // g->Draw("l"); + } else if (auto l = dynamic_cast(f)) { + l->SetX1(l->GetY1()); + l->SetX2(l->GetY2()); + l->SetY1(_axis->GetXmax()); + l->SetY2(_axis->GetXmax()); + // l->Draw(); + } + } + } + + graph->SetName("pulls"); + hist->GetListOfFunctions()->Add(graph, "z0p"); + // hist->GetListOfFunctions()->Add(histCopy->Clone(".axis"),(sOpt.Contains("impact") && + // !doHorizontal)?"axissamey+":"axissame"); // doesn't display right when zoom the axis + if (!hasSame) + histCopy->Draw((sOpt.Contains("impact") && !doHorizontal) + ? "axisy+" + : "axis"); // draws the axis, called ".axis" for easy access + hist->Draw("same"); + // + // if(sOpt.Contains("impact")) { + // // make main object the histogram + // auto h = (TH1*)graph->GetHistogram()->Clone("impact"); + // graph->GetListOfFunctions()->RemoveAll(); + // for(int ii=1;ii<=h->GetNbinsX();ii++) h->SetBinContent(ii,-4); + // h->GetListOfFunctions()->Add(graph,"z0p"); + // h->Draw("hbar"); + // } else { + // graph->Draw(sOpt.Contains("impact") ? "az0py+" : "az0p"); + // } + auto hh = dynamic_cast(histCopy->Clone(".axiscopy")); + hh->SetDirectory(0); + hh->SetBit(kCanDelete); + hh->Draw( + (sOpt.Contains("impact") && !doHorizontal) + ? "axissamey+" + : "axissame"); // overlay axis again -- important is last so can remove if don't pad->Update before reclear gPad->Modified(); oldPad->cd(); // gPad->Update(); @@ -6836,13 +9340,15 @@ void xRooNode::Draw(Option_t *opt) auto s = parentPdf(); if (s && s->get()) { // drawing dataset associated to a simultaneous means must find subpads with variation names - for (auto c : s->variations()) { + for (auto c : s->bins()) { auto _pad = dynamic_cast(gPad->GetPrimitive(c->GetName())); if (!_pad) continue; // channel was hidden? auto ds = c->datasets().find(GetName()); - if (!ds) + if (!ds) { + std::cout << " no ds " << GetName() << std::endl; continue; + } auto tmp = gPad; _pad->cd(); ds->Draw(opt); @@ -6875,7 +9381,16 @@ void xRooNode::Draw(Option_t *opt) if (!dataGraph) return; - dataGraph->SetBit(kCanDelete); // will be be deleted when pad is cleared + dataGraph->SetBit(kCanDelete); // will be be deleted when pad is cleared + dataGraph->SetMarkerSize(dataGraph->GetMarkerSize() * gPad->GetWNDC()); // scale marker sizes to pad size + + if (s && !s->get()->canBeExtended()) { + // normalize dataGraph to 1 + double tot = 0; + for (int i = 0; i < dataGraph->GetN(); i++) + tot += dataGraph->GetPointY(i); + dataGraph->Scale(1. / tot); + } if (!hasSame) { clearPad(); @@ -6912,8 +9427,9 @@ void xRooNode::Draw(Option_t *opt) ratioGraph->SetBit(kCanDelete); for (int i = 0; i < ratioGraph->GetN(); i++) { double val = ratioGraph->GetPointY(i); - double nom = mainHist->GetBinContent(i + 1); - double nomerr = mainHist->GetBinError(i + 1); + int binNum = mainHist->FindFixBin(ratioGraph->GetPointX(i)); + double nom = mainHist->GetBinContent(binNum); + double nomerr = mainHist->GetBinError(binNum); ratioGraph->SetPointY( i, std::get<0>(auxFunctions[h->GetYaxis()->GetTitle()])(ratioGraph->GetPointY(i), nom, nomerr)); ratioGraph->SetPointEYhigh(i, std::get<0>(auxFunctions[h->GetYaxis()->GetTitle()])( @@ -6976,65 +9492,97 @@ void xRooNode::Draw(Option_t *opt) auto initPar = dynamic_cast(_fr.get()->floatParsInit().find(forceNames)); if (!initPar) return; - for (auto &d : _dsets) { - if (!d->get()->TestBit(1 << 20)) - continue; - auto emptyHist = BuildHistogram(v, true); - emptyHist->SetBit(kCanDelete); - auto _obs = d->obs(); - auto x = _obs.find((v) ? dynamic_cast(v)->GetName() : emptyHist->GetXaxis()->GetName()); - auto _nll = nll(d); - auto theData = d->get(); - int nevent = theData->numEntries(); - for (int i = 0; i < nevent; i++) { - theData->get(i); - bool _skip = false; - for (const auto &_c : _coords) { - if (auto cat = _c->get(); cat) { - if (cat->getIndex() != theData->get()->getCatIndex(cat->GetName())) { - _skip = true; - break; + std::vector valuesToDo = {initPar->getVal()}; + if (initPar->hasError() || initPar->hasAsymError()) { + valuesToDo.push_back(initPar->getVal() + initPar->getErrorLo()); + valuesToDo.push_back(initPar->getVal() + initPar->getErrorHi()); + } + int ii = 0; + for (auto valueToDo : valuesToDo) { + ii++; + for (auto &d : _dsets) { + if (!d->get()->TestBit(1 << 20)) + continue; + auto emptyHist = BuildHistogram(v, true); + emptyHist->SetBit(kCanDelete); + auto _obs = d->obs(); + auto x = _obs.find((v) ? dynamic_cast(v)->GetName() : emptyHist->GetXaxis()->GetName()); + auto _nll = nll(d); + auto theData = d->get(); + int nevent = theData->numEntries(); + for (int i = 0; i < nevent; i++) { + theData->get(i); + bool _skip = false; + for (const auto &_c : _coords) { + if (auto cat = _c->get(); cat) { + if (cat->getIndex() != theData->get()->getCatIndex(cat->GetName())) { + _skip = true; + break; + } } } - } - if (_skip) - continue; + if (_skip) + continue; - if (x) { - auto val = _nll.pars()->getRealValue(initPar->GetName()); - auto nllVal = _nll.getEntryVal(i); - _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal()); - auto nllVal2 = _nll.getEntryVal(i); - _nll.pars()->setRealValue(initPar->GetName(), val); - emptyHist->Fill(x->get()->getVal(), (nllVal2 - nllVal)); + if (x) { + auto val = _nll.pars()->getRealValue(initPar->GetName()); + if (ii > 1) + _nll.pars()->setRealValue(initPar->GetName(), valueToDo); + auto nllVal = _nll.getEntryVal(i); + _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal()); + auto nllVal2 = _nll.getEntryVal(i); + _nll.pars()->setRealValue(initPar->GetName(), val); + emptyHist->Fill(x->get()->getVal(), (nllVal2 - nllVal)); + } } + // include the extendedTerm, distributed evenly over the bins + // probably should be somehow dependent on data density though (i.e. bins with more data get more of it?) + auto val = _nll.pars()->getRealValue(initPar->GetName()); + if (ii > 1) + _nll.pars()->setRealValue(initPar->GetName(), valueToDo); + auto _extTerm = _nll.extendedTerm(); + _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal()); + auto _extTerm2 = _nll.extendedTerm(); + _nll.pars()->setRealValue(initPar->GetName(), val); + for (int i = 1; i <= emptyHist->GetNbinsX(); i++) { + emptyHist->SetBinContent(i, + emptyHist->GetBinContent(i) + (_extTerm2 - _extTerm) / emptyHist->GetNbinsX()); + emptyHist->SetBinError(i, 0); + } + emptyHist->GetYaxis()->SetTitle("log (L(#theta)/L(#theta_{0}))"); + emptyHist->SetTitle(TString::Format("#theta = %g", (ii > 1) ? valueToDo : val)); + if (ii == 1) + emptyHist->SetLineColor(kBlack); + if (ii == 2) + emptyHist->SetLineColor(kRed); + else if (ii == 3) + emptyHist->SetLineColor(kBlue); + emptyHist->Draw(_drawn ? "same" : ""); + _drawn = true; } - auto val = _nll.pars()->getRealValue(initPar->GetName()); - auto _extTerm = _nll.extendedTerm(); - _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal()); - auto _extTerm2 = _nll.extendedTerm(); - _nll.pars()->setRealValue(initPar->GetName(), val); - for (int i = 1; i <= emptyHist->GetNbinsX(); i++) { - emptyHist->SetBinContent(i, emptyHist->GetBinContent(i) + (_extTerm2 - _extTerm) / emptyHist->GetNbinsX()); - emptyHist->SetBinError(i, 0); - } - emptyHist->GetYaxis()->SetTitle("log (L(#theta)/L(#theta_{0}))"); - emptyHist->Draw(_drawn ? "same" : ""); - _drawn = true; } return; } auto rar = get(); + const xRooNode *rarNode = this; if (!rar) { get()->Draw(); return; } + RooAbsReal *sf = nullptr; + if (get()->InheritsFrom("RooExtendPdf")) { + browse(); + rarNode = find(".pdf").get(); + // rar = rarNode->get(); + sf = find(".n")->get(); + } auto h = BuildHistogram(v, false, hasErrorOpt); if (!h) return; h->SetBit(kCanDelete); + if (!v) v = getObject(h->GetXaxis()->GetName()).get(); RooAbsArg *vv = (v) ? dynamic_cast(v) : rar; @@ -7042,6 +9590,34 @@ void xRooNode::Draw(Option_t *opt) // do this to get bin labels h->GetXaxis()->SetName("xaxis"); // WARNING -- this messes up anywhere we GetXaxis()->GetName() } + + if (rar->InheritsFrom("RooAbsPdf") && !(rar->InheritsFrom("RooRealSumPdf") || rar->InheritsFrom("RooAddPdf"))) { + // append parameter values to title if has such + RooArgSet s; + rar->leafNodeServerList(&s); + if (v) + s.remove(*dynamic_cast(v)); + if (!s.empty()) { + TString ss = h->GetTitle(); + ss += " ["; + bool first = true; + for (auto _p : s) { + auto _v = dynamic_cast(_p); + if (!_v) + continue; + if (!first) + ss += ","; + first = false; + ss += TString::Format("%s=%g", strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName(), _v->getVal()); + if (_v->hasError()) { + ss += TString::Format("#pm %g", _v->getError()); + } + } + ss += "]"; + h->SetTitle(ss); + } + } + if (!hasSame) { if (obs().find(vv->GetName())) { gPad->SetGrid(0, 0); @@ -7050,13 +9626,16 @@ void xRooNode::Draw(Option_t *opt) } } TString dOpt = (TString(rar->ClassName()).Contains("Hist") || rar->isBinnedDistribution(*vv) || - rar->getAttribute("BinnedLikelihood") || + h->GetNbinsX() == 1 || rar->getAttribute("BinnedLikelihood") || (dynamic_cast(vv) && std::unique_ptr>(rar->binBoundaries(*dynamic_cast(vv), -std::numeric_limits::infinity(), std::numeric_limits::infinity())))) ? "" : "LF2"; + if (auto d = dynamic_cast(rar); d && !d->isBinnedDistribution(*vv) && h->GetNbinsX() != 1) { + dOpt = "LF2"; // hist func is interpolated, so draw it as such + } if (dOpt == "LF2" && !components().empty()) { // check if all components of dOpt are "Hist" type (CMS model support) // if so then dOpt=""; @@ -7070,10 +9649,9 @@ void xRooNode::Draw(Option_t *opt) if (allHist) dOpt = ""; } - if (rar == vv) - dOpt += "TEXT"; if (rar == vv && rar->IsA() == RooRealVar::Class()) { + dOpt += "TEXT"; // add a TExec to the histogram so that when edited it will propagate to var gROOT->SetEditHistograms(true); } else { @@ -7113,6 +9691,8 @@ void xRooNode::Draw(Option_t *opt) h->SetFillColor(h->GetLineColor()); h->SetMarkerStyle(0); errHist = dynamic_cast(h->Clone(Form("%s_err", h->GetName()))); + errHist->SetBit(kCanDelete); + errHist->SetDirectory(0); h->SetFillStyle(0); for (int i = 1; i <= h->GetNbinsX(); i++) { h->SetBinError(i, 0); @@ -7128,18 +9708,22 @@ void xRooNode::Draw(Option_t *opt) dOpt = "TEXT"; auto node = new xRooNode(*this); auto _hist = (errHist) ? errHist : h; - auto hCopy = (errHist) ? nullptr : h->Clone(); + auto hCopy = (errHist) ? nullptr : dynamic_cast(h->Clone()); + if (hCopy) + hCopy->SetDirectory(0); _hist->GetListOfFunctions()->Add(node); _hist->GetListOfFunctions()->Add(new TExec( ".update", TString::Format( - "gROOT->SetEditHistograms(true);auto h = dynamic_cast(gPad->GetPrimitive(\"%s\")); if(h) { if(auto n " + "gROOT->SetEditHistograms(true);auto h = dynamic_cast(gPad->GetPrimitive(\"%s\")); if(h) { double " + "range= h->GetMaximum()-h->GetMinimum(); if(auto n " "= dynamic_cast(h->GetListOfFunctions()->FindObject(\"%s\")); n && " - "n->TestBit(TObject::kNotDeleted) && n->get()->getVal() != h->GetBinContent(1)) {double range " - "= h->GetMaximum()-h->GetMinimum(); h->SetBinContent(1, " - "TString::Format(\"%%.2g\",int(h->GetBinContent(1)/(range*0.01))*range*0.01).Atof());n->SetContents( " + "n->TestBit(TObject::kNotDeleted) && n->get()->getVal() != h->GetBinContent(1)) {" + "h->SetBinContent(1, " + "TString::Format(\"%%.2g\",int(h->GetBinContent(1)/(range*0.01))*range*0.01).Atof());n->SetContent( " "h->GetBinContent(1) ); for(auto pp : *h->GetListOfFunctions()) if(auto hh = " - "dynamic_cast(pp))hh->SetBinContent(1,h->GetBinContent(1));} gPad->Modified();gPad->Update(); }", + "dynamic_cast(pp))hh->SetBinContent(1,h->GetBinContent(1));} if(h->GetBinContent(1)==0.) " + "h->SetBinContent(1,range*0.005); gPad->Modified();gPad->Update(); }", _hist->GetName(), node->GetName()))); if (errHist) { errHist->GetListOfFunctions()->Add(h, "TEXT HIST same"); @@ -7150,6 +9734,7 @@ void xRooNode::Draw(Option_t *opt) _hist->SetBinError(1, 0); } _hist->SetStats(false); + // if (_hist->GetBinContent(1)==0.) _hist->SetBinContent(1,(_hist->GetMaximum()-_hist->GetMinimum())*0.005); _hist->Draw(((errHist) ? "e2" : "")); gPad->Modified(); return; @@ -7165,6 +9750,7 @@ void xRooNode::Draw(Option_t *opt) h = existing; overlayExisted = true; } else { + TString oldStyle = (rar && rar->getStringAttribute("style")) ? rar->getStringAttribute("style") : ""; h->SetTitle(overlayName); // for overlays will take style from current gStyle before overriding with personal style // this ensures initial style will be whatever gStyle is, rather than whatever ours is @@ -7191,10 +9777,12 @@ void xRooNode::Draw(Option_t *opt) // (TAttFill&)(*h) = *(gROOT->GetStyle(h->GetTitle()) ? gROOT->GetStyle(h->GetTitle()) : gStyle); // (TAttMarker&)(*h) = *(gROOT->GetStyle(h->GetTitle()) ? gROOT->GetStyle(h->GetTitle()) : gStyle); auto _style = style(h); - (TAttLine &)(*h) = *_style; - (TAttFill &)(*h) = *_style; - (TAttMarker &)(*h) = *_style; - + rar->setStringAttribute("style", oldStyle == "" ? nullptr : oldStyle.Data()); // restores old style + if (_style) { + (TAttLine &)(*h) = *_style; + (TAttFill &)(*h) = *_style; + (TAttMarker &)(*h) = *_style; + } h->Draw(dOpt); if (errHist) { errHist->SetTitle(overlayName); @@ -7203,41 +9791,57 @@ void xRooNode::Draw(Option_t *opt) } } } else { + auto _style = style(h); + if (_style) { + (TAttLine &)(*h) = *_style; + (TAttFill &)(*h) = *_style; + (TAttMarker &)(*h) = *_style; + if (errHist) { + (TAttLine &)(*errHist) = *h; + errHist->SetFillColor(h->GetLineColor()); + } + } h->Draw(dOpt + sOpt); } - if (!hasOverlay && (rar->InheritsFrom("RooRealSumPdf") || rar->InheritsFrom("RooAddPdf"))) { - // build a stack - THStack *stack = new THStack(TString::Format("%s_stack", rar->GetName()), - TString::Format("%s;%s", rar->GetTitle(), h->GetXaxis()->GetTitle())); - int count = 2; - std::map colorByTitle; // TODO: should fill from any existing legend - std::set allTitles; - bool titleMatchName = true; - std::map histGroups; - std::vector hhs; - if (components().size() == 1) { + if (!hasOverlay && (rarNode->get()->InheritsFrom("RooRealSumPdf") || rarNode->get()->InheritsFrom("RooAddPdf"))) { + // build a stack unless not requested + if (!nostack) { + THStack *stack = new THStack(TString::Format("%s_stack", rar->GetName()), + TString::Format("%s;%s", rar->GetTitle(), h->GetXaxis()->GetTitle())); + int count = 2; + std::map colorByTitle; // TODO: should fill from any existing legend + std::set allTitles; + bool titleMatchName = true; + std::map histGroups; + std::vector hhs; + // support for CMS model case where has single component containing many coeffs // will build stack by setting each coeff equal to 0 in turn, rebuilding the histogram // the difference from the "full" histogram will be the component - auto comps = components()[0]; - RooArgList coefs; - for (auto &c : *comps) { - if (c->fFolder == "!.coeffs") - coefs.add(*c->get()); + RooArgList cms_coefs; + if (!rarNode->components().empty()) { + auto comps = rarNode->components()[0]; + for (auto &c : *comps) { + if (c->fFolder == "!.coeffs") + cms_coefs.add(*c->get()); + } } - if (!coefs.empty()) { + if (!cms_coefs.empty()) { RooRealVar zero("zero", "", 0); std::shared_ptr prevHist((TH1 *)h->Clone()); - for (auto c : coefs) { + for (auto c : cms_coefs) { // seems I have to remake the function each time, as haven't figured out what cache needs clearing? - std::unique_ptr f(dynamic_cast(comps->get()->Clone("tmpCopy"))); + std::unique_ptr f( + dynamic_cast(rarNode->components()[0]->get()->Clone("tmpCopy"))); zero.setAttribute( Form("ORIGNAME:%s", c->GetName())); // used in redirectServers to say what this replaces f->redirectServers(RooArgSet(zero), false, true); // each time will replace one additional coef // zero.setAttribute(Form("ORIGNAME:%s",c->GetName()),false); (commented out so that on next iteration // will still replace all prev) auto hh = xRooNode(*f, *this).BuildHistogram(v); + if (sf) + hh->Scale(sf->getVal()); if (strlen(hh->GetTitle()) == 0) hh->SetTitle(c->GetName()); // ensure all hists has titles titleMatchName &= (TString(c->GetName()) == hh->GetTitle() || @@ -7248,150 +9852,156 @@ void xRooNode::Draw(Option_t *opt) hhs.push_back(hh); prevHist = nextHist; } - } - } else { - for (auto &samp : components()) { - auto hh = samp->BuildHistogram(v); - hhs.push_back(hh); - if (strlen(hh->GetTitle()) == 0) - hh->SetTitle(samp->GetName()); // ensure all hists has titles - titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() || - TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_")); - } - } - for (auto &hh : hhs) { - // automatically group hists that all have the same title - if (histGroups.find(hh->GetTitle()) == histGroups.end()) { - histGroups[hh->GetTitle()] = hh; - } else { - // add it into this group - histGroups[hh->GetTitle()]->Add(hh); - delete hh; - continue; - } - auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum(); - if (!stack->GetHists() && h->GetMinimum() > hhMin) { - auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin(); - if (hhMin >= 0 && newMin < 0) - newMin = hhMin * 0.99; - adjustYRange(newMin, h->GetMaximum()); - } - if (auto it = colorByTitle.find(hh->GetTitle()); it != colorByTitle.end()) { - hh->SetFillColor(it->second); } else { - if (hh->GetFillColor() == 0) { - hh->SetFillColor((count++) % 100); + for (auto &samp : rarNode->components()) { + auto hh = samp->BuildHistogram(v); + if (sf) + hh->Scale(sf->getVal()); + hhs.push_back(hh); + if (strlen(hh->GetTitle()) == 0) + hh->SetTitle(samp->GetName()); // ensure all hists has titles + titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() || + TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_")); } - colorByTitle[hh->GetTitle()] = hh->GetFillColor(); } - /*if(stack->GetHists() && stack->GetHists()->GetEntries()>0) { - // to remove rounding effects on bin boundaries, see if binnings compatible - auto _h1 = dynamic_cast(stack->GetHists()->At(0)); - if(_h1->GetNbinsX()==hh->GetNbinsX()) TODO ... finish dealing with silly rounding effects - }*/ - TString thisOpt = dOpt; - // uncomment next line to blend continuous with discrete components .. get some unpleasant "poke through" - // effects though - // if(auto s = samp->get(); s) thisOpt = s->isBinnedDistribution(*dynamic_cast(v)) ? "" - // : "LF2"; - stack->Add(hh, thisOpt); - allTitles.insert(hh->GetTitle()); - } - stack->SetBit(kCanDelete); // should delete its sub histograms - stack->Draw("noclear same"); - h->Draw("axissame"); // overlay axis again - - TList *ll = stack->GetHists(); - if (ll && ll->GetEntries()) { - - // get common prefix to strip off only if all titles match names and - // any title is longer than 10 chars - size_t e = std::min(allTitles.begin()->size(), allTitles.rbegin()->size()); - size_t ii = 0; - bool goodPrefix = false; - std::string commonSuffix; - if (titleMatchName && ll->GetEntries() > 1) { - while (ii < e - 1 && allTitles.begin()->at(ii) == allTitles.rbegin()->at(ii)) { - ii++; - if (allTitles.begin()->at(ii) == '_' || allTitles.begin()->at(ii) == ' ') - goodPrefix = true; - } - - // find common suffix if there is one .. must start with a "_" - bool stop = false; - while (!stop && commonSuffix.size() < size_t(e - 1)) { - commonSuffix = allTitles.begin()->substr(allTitles.begin()->length() - commonSuffix.length() - 1); - for (auto &t : allTitles) { - if (!TString(t).EndsWith(commonSuffix.c_str())) { - commonSuffix = commonSuffix.substr(1); - stop = true; - break; + for (auto &hh : hhs) { + // automatically group hists that all have the same title + if (histGroups.find(hh->GetTitle()) == histGroups.end()) { + histGroups[hh->GetTitle()] = hh; + } else { + // add it into this group + histGroups[hh->GetTitle()]->Add(hh); + delete hh; + continue; + } + auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum(); + if (!stack->GetHists() && h->GetMinimum() > hhMin) { + auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin(); + if (hhMin >= 0 && newMin < 0) + newMin = hhMin * 0.99; + adjustYRange(newMin, h->GetMaximum()); + } + + /*if(stack->GetHists() && stack->GetHists()->GetEntries()>0) { + // to remove rounding effects on bin boundaries, see if binnings compatible + auto _h1 = dynamic_cast(stack->GetHists()->At(0)); + if(_h1->GetNbinsX()==hh->GetNbinsX()) TODO ... finish dealing with silly rounding effects + }*/ + TString thisOpt = dOpt; + // uncomment next line to blend continuous with discrete components .. get some unpleasant "poke through" + // effects though + // if(auto s = samp->get(); s) thisOpt = s->isBinnedDistribution(*dynamic_cast(v)) ? + // "" : "LF2"; + stack->Add(hh, thisOpt); + allTitles.insert(hh->GetTitle()); + } + stack->SetBit(kCanDelete); // should delete its sub histograms + stack->Draw("noclear same"); + h->Draw( + dOpt + sOpt + + "same"); // overlay again .. if stack would cover original hist (negative components) we still see integral + h->Draw("axissame"); // redraws axis + + TList *ll = stack->GetHists(); + if (ll && ll->GetEntries()) { + + // get common prefix to strip off only if all titles match names and + // any title is longer than 10 chars + size_t e = std::min(allTitles.begin()->size(), allTitles.rbegin()->size()); + size_t ii = 0; + bool goodPrefix = false; + std::string commonSuffix; + if (titleMatchName && ll->GetEntries() > 1) { + while (ii < e - 1 && allTitles.begin()->at(ii) == allTitles.rbegin()->at(ii)) { + ii++; + if (allTitles.begin()->at(ii) == '_' || allTitles.begin()->at(ii) == ' ') + goodPrefix = true; + } + + // find common suffix if there is one .. must start with a "_" + bool stop = false; + while (!stop && commonSuffix.size() < size_t(e - 1)) { + commonSuffix = allTitles.begin()->substr(allTitles.begin()->length() - commonSuffix.length() - 1); + for (auto &t : allTitles) { + if (!TString(t).EndsWith(commonSuffix.c_str())) { + commonSuffix = commonSuffix.substr(1); + stop = true; + break; + } } } - } - if (commonSuffix.find('_') == std::string::npos) - commonSuffix = ""; - else - commonSuffix = commonSuffix.substr(commonSuffix.find('_')); - } - if (!goodPrefix) - ii = 0; - - // also find how many characters are needed to distinguish all entries (that dont have the same name) - // then carry on up to first space or underscore - size_t jj = 0; - std::map reducedTitles; - while (reducedTitles.size() != allTitles.size()) { - jj++; - std::map titlesMap; - for (auto &s : allTitles) { - if (reducedTitles.count(s)) - continue; - titlesMap[s.substr(0, jj)]++; - } - for (auto &s : allTitles) { - if (titlesMap[s.substr(0, jj)] == 1 && (jj >= s.length() || s.at(jj) == ' ' || s.at(jj) == '_')) { - reducedTitles[s] = s.substr(0, jj); + if (commonSuffix.find('_') == std::string::npos) + commonSuffix = ""; + else + commonSuffix = commonSuffix.substr(commonSuffix.find('_')); + } + if (!goodPrefix) + ii = 0; + + // also find how many characters are needed to distinguish all entries (that dont have the same name) + // then carry on up to first space or underscore + size_t jj = 0; + std::map reducedTitles; + while (reducedTitles.size() != allTitles.size()) { + jj++; + std::map titlesMap; + for (auto &s : allTitles) { + if (reducedTitles.count(s)) + continue; + titlesMap[s.substr(0, jj)]++; + } + for (auto &s : allTitles) { + if (titlesMap[s.substr(0, jj)] == 1 && (jj >= s.length() || s.at(jj) == ' ' || s.at(jj) == '_')) { + reducedTitles[s] = s.substr(0, jj); + } } } - } - // strip common prefix and suffix before adding - for (int i = ll->GetEntries() - 1; i >= 0; i--) { // go in reverse order - auto _title = (ll->GetEntries() > 5) ? reducedTitles[ll->At(i)->GetTitle()] : ll->At(i)->GetTitle(); - _title = _title.substr(ii < _title.size() ? ii : 0); - if (!commonSuffix.empty() && TString(_title).EndsWith(commonSuffix.c_str())) - _title = _title.substr(0, _title.length() - commonSuffix.length()); + // strip common prefix and suffix before adding + for (int i = ll->GetEntries() - 1; i >= 0; i--) { // go in reverse order + auto _title = (ll->GetEntries() > 5) ? reducedTitles[ll->At(i)->GetTitle()] : ll->At(i)->GetTitle(); + _title = _title.substr(ii < _title.size() ? ii : 0); + if (!commonSuffix.empty() && TString(_title).EndsWith(commonSuffix.c_str())) + _title = _title.substr(0, _title.length() - commonSuffix.length()); - // style hists according to availble styles ... creating if necessary - // keeping this code here because style() method would be for the stack instead of - // for the components - std::shared_ptr _style; // use to keep alive for access from GetStyle below, in case getObject has - // decided to return the owning ptr (for some reason) - if (!gROOT->GetStyle(_title.c_str())) { - if ((_style = getObject(_title))) { - // loaded style (from workspace?) so put in list and use that - gROOT->GetListOfStyles()->Add(_style.get()); - } else { - // create new style - gets put in style list automatically so don't have to delete - // acquire them so saved to workspaces for auto reload ... - _style = - acquireNew(_title.c_str(), TString::Format("Style for %s component", _title.c_str())); - (TAttLine &)(*_style) = *dynamic_cast(ll->At(i)); - (TAttFill &)(*_style) = *dynamic_cast(ll->At(i)); - (TAttMarker &)(*_style) = *dynamic_cast(ll->At(i)); - gROOT->GetListOfStyles()->Add(_style.get()); - } - } else { - _style = std::shared_ptr(gROOT->GetStyle(_title.c_str()), [](TStyle *) {}); + // style hists according to available styles ... creating if necessary + dynamic_cast(ll->At(i))->SetTitle(_title.c_str()); + addLegendEntry(ll->At(i), _title.c_str(), "f"); } - dynamic_cast(ll->At(i))->SetTitle(_title.c_str()); - // auto _style = style(ll->At(i)); - *dynamic_cast(ll->At(i)) = *_style; - *dynamic_cast(ll->At(i)) = *_style; - *dynamic_cast(ll->At(i)) = *_style; + // finally, ensure all hists are styled + for (auto ho : *ll) { + TH1 *hh = dynamic_cast(ho); + if (!hh) + continue; + bool createdStyle = (xRooNode(*hh, *this).style(nullptr, false) == nullptr); + + if (createdStyle) { + // give hist a color, that isn't the same as any other hists color + bool used = false; + do { + hh->SetFillColor((count++) % 100); + // check not already used this color + used = false; + for (auto ho2 : *ll) { + TH1 *hh2 = dynamic_cast(ho2); + if (!hh2) + continue; + auto _style = xRooNode(*hh2, *this).style(hh2, false); + if (hh != hh2 && _style && _style->GetFillColor() == hh->GetFillColor()) { + used = true; + break; + } + } + } while (used); + } - addLegendEntry(ll->At(i), _title.c_str(), "f"); + auto _style = xRooNode(*hh, *this).style(hh); + if (_style) { + *dynamic_cast(hh) = *_style; + *dynamic_cast(hh) = *_style; + *dynamic_cast(hh) = *_style; + } + } } } } else if (!overlayExisted) { @@ -7399,31 +10009,6 @@ void xRooNode::Draw(Option_t *opt) if (errHist) { addLegendEntry(errHist, strlen(errHist->GetTitle()) ? errHist->GetTitle() : GetName(), "fl"); } else { - if (rar->InheritsFrom("RooAbsPdf") && - !(rar->InheritsFrom("RooRealSumPdf") || rar->InheritsFrom("RooAddPdf"))) { - // append parameter values to title if has such - RooArgSet s; - rar->leafNodeServerList(&s); - if (v) - s.remove(*dynamic_cast(v)); - if (!s.empty()) { - TString ss = h->GetTitle(); - ss += " ["; - bool first = true; - for (auto _p : s) { - auto _v = dynamic_cast(_p); - if (!_v) - continue; - if (!first) - ss += ","; - first = false; - ss += TString::Format("%s=%g", strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName(), _v->getVal()); - } - ss += "]"; - h->SetTitle(ss); - } - } - addLegendEntry(h, strlen(h->GetTitle()) ? h->GetTitle() : GetName(), "l"); } } @@ -7456,6 +10041,7 @@ void xRooNode::Draw(Option_t *opt) ratioPad->SetRightMargin(gPad->GetRightMargin()); ratioPad->cd(); TH1 *ratioHist = dynamic_cast((errHist) ? errHist->Clone("auxHist") : h->Clone("auxHist")); + ratioHist->SetDirectory(0); ratioHist->SetTitle((errHist) ? errHist->GetName() : h->GetName()); // abuse the title string to hold the name of the main hist @@ -7492,12 +10078,22 @@ void xRooNode::Draw(Option_t *opt) ratioHist->SetStats(false); ratioHist->SetBit(TH1::kNoTitle); ratioHist->SetBit(kCanDelete); - ratioHist->Draw((errHist ? "e2" : "")); if (errHist) { auto _h = dynamic_cast(ratioHist->Clone("auxHist_clone")); + _h->SetDirectory(0); _h->SetFillColor(0); - _h->Draw("histsame"); - } + ratioHist->GetListOfFunctions()->Add(_h, "histsame"); + //_h->Draw("histsame"); + } + ratioHist->GetListOfFunctions()->Add(new TExec( + ".updateAxis", + TString::Format("auto h1 = (TH1*)%p; auto h2 = (TH1*)%p; if(h2->GetXaxis()->GetFirst() != " + "h1->GetXaxis()->GetFirst() || h1->GetXaxis()->GetLast()!=h2->GetXaxis()->GetLast()) " + "{h2->GetXaxis()->SetRange(h1->GetXaxis()->GetFirst(),h1->GetXaxis()->GetLast());if(gPad) " + "{gPad->GetCanvas()->Paint();gPad->GetCanvas()->Update();}}", + (void *)ratioHist, (void *)(h)))); + ratioHist->Draw((errHist ? "e2" : "")); + _tmpPad->cd(); ratioPad->Draw(); } else if (auto ratioPad = dynamic_cast(gPad->GetPrimitive("auxPad")); hasSame && ratioPad) { @@ -7512,6 +10108,7 @@ void xRooNode::Draw(Option_t *opt) if (auto hnom = dynamic_cast(gPad->GetPrimitive(histName)); hnom) { h = dynamic_cast(h->Clone(h->GetName())); + h->SetDirectory(0); h->SetBit(kCanDelete); for (int i = 1; i <= hnom->GetNbinsX(); i++) { double val = h->GetBinContent(i); @@ -7570,7 +10167,8 @@ void xRooNode::Draw(Option_t *opt) }*/ // now draw selected datasets on top if this was a pdf - if (!hasSame && get()) { + if (auto _pdf = get(); + !hasSame && _pdf /*&& (_pdf->canBeExtended() || robs().empty())*/ && coefs().empty()) { auto _dsets = datasets(); // bool _drawn=false; for (auto &d : _dsets) { @@ -7610,21 +10208,69 @@ void xRooNode::SaveAs(const char *filename, Option_t *option) const return; } +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) // before saving, clear the eocache of all owned nodes // because causes memory leak when read back in (workspace streamer immediately overwrites the caches) - for (auto &c : w->_allOwnedNodes) { + // fixed in: https://github.com/root-project/root/pull/12024 + for (auto &c : w->components()) { c->_eocache = nullptr; } +#endif // const_cast(this)->sterilize(); - tried this to reduce mem leak on readback but no improve if (!w->writeToFile(filename, sOpt != "update")) { Info("SaveAs", "%s saved to %s", w->GetName(), filename); + // save any fitDatabase that is loaded in memory too + // TODO: We should do this as well for SaveAs on a scan object + if (auto fitDb = dynamic_cast(gROOT->GetListOfFiles()->FindObject("fitDatabase"))) { + + std::function CopyDir; + + CopyDir = [&](TDirectory *source, TDirectory *dest) { + auto dir = dest->GetDirectory(source->GetName()); + if (!dir) { + dir = dest->mkdir(source->GetName()); + } + for (auto k : *source->GetListOfKeys()) { + auto key = dynamic_cast(k); + const char *classname = key->GetClassName(); + TClass *cl = gROOT->GetClass(classname); + // std::cout << "processing " << key->GetName() << " " << classname << std::endl; + if (!cl) { + continue; + } else if (cl->InheritsFrom(TDirectory::Class())) { + CopyDir(source->GetDirectory(key->GetName()), dir); + } else { + // don't write object if it already exists + if (dir->FindKey(key->GetName())) + continue; + // support FitConfigs .... + if (strcmp(classname, "ROOT::Fit::FitConfig") == 0) { + auto fc = key->ReadObject(); + dir->WriteObject(fc, key->GetName()); + delete fc; + } else { + TObject *obj = key->ReadObj(); + if (obj) { + dir->WriteTObject(obj, key->GetName()); + delete obj; + } + } + } + } + }; + CopyDir(fitDb, std::make_unique(filename, "UPDATE").get()); + Info("SaveAs", "Saved fitDatabase to %s", filename); + } + } else { Error("SaveAs", "Unable to save to %s", filename); } +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) // restore the cache to every node - for (auto &c : w->_allOwnedNodes) { + for (auto &c : w->components()) { c->setExpensiveObjectCache(w->expensiveObjectCache()); } +#endif } } @@ -7650,29 +10296,37 @@ std::pair xRooNode::IntegralAndError(const xRooNode &fr, const c _pars = _fr->constPars(); } - auto _obs = obs().argList(); + auto _obs = obs(); auto _coefs = coefs(); // need here to keep alive owned RooProduct if (auto c = _coefs.get(); c) { - out = c->getVal(_obs); // assumes independent of observables! + out = c->getVal(*_obs.get()); // assumes independent of observables! } if (auto p = dynamic_cast(get()); p) { // prefer to use expectedEvents for integrals of RooAbsPdf e.g. for RooProdPdf wont include constraint terms if (rangeName) p->setNormRange(rangeName); - out *= p->expectedEvents(_obs); +#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 27, 00) + RooAbsReal::EvalErrorContext _tmp(RooAbsReal::Ignore); +#endif + out *= p->expectedEvents(*_obs.get()); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards p->_normSet = nullptr; +#endif err = GetBinError(-1, fr); if (rangeName) p->setNormRange(nullptr); } else if (auto p2 = dynamic_cast(get()); p2) { // only integrate over observables we actually depend on - auto f = std::shared_ptr(p2->createIntegral(*std::unique_ptr(p2->getObservables(_obs)), - rangeName)); // did use x here before using obs - double tmp = - out; // coef value ... not included in Error of integral we just created (doesn't have coefs() return) + auto f = std::shared_ptr( + p2->createIntegral(*std::unique_ptr(p2->getObservables(*_obs.get())), + rangeName)); // did use x here before using obs + RooProduct pr("int_x_coef", "int_x_coef", + RooArgList(*f, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get())); out *= f->getVal(); - err = tmp * xRooNode(f, *this).GetBinError(-1, fr); + err = xRooNode(pr, *this).GetBinError(-1, fr); + sterilize(); // needed so that we can forget properly about the integral we just created (and are deleting) } else if (get()) { out = 0; auto vals = GetBinContents(1, 0); // returns all bins @@ -7702,6 +10356,19 @@ std::pair xRooNode::IntegralAndError(const xRooNode &fr, const c std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooNode &_fr) const { + // note: so far this method is inconsistent with the BuildHistogram in ways: + // no projection over other variables + // July2023: made RooRealSumPdf evaluate as a function if doesn't have a floor + // but this method will still evaluate it as a pdf (uses PdfWrapper) + // but can get away with it while added NaN recovery to getSimplePropagatedError to pickup raw values + + if (fBinNumber != -1) { + if (binStart != binEnd || !fParent) { + throw std::runtime_error(TString::Format("%s is a bin - only has one value", GetName())); + } + return fParent->GetBinErrors(fBinNumber, fBinNumber); + } + std::vector out; auto o = dynamic_cast(get()); @@ -7711,13 +10378,20 @@ std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooN std::shared_ptr fr = std::dynamic_pointer_cast(_fr.fComp); //= dynamic_cast( _fr.get() ? _fr->Clone() : fitResult()->Clone()); + auto _coefs = coefs(); + if (!fr) { + // need to ensure coefs, if any, are included in fit result retrieval so all pars are loaded + auto frn = (!_coefs.get() ? *this : xRooNode(RooProduct("tmp", "tmp", RooArgList(*o, *_coefs.get())))) + .fitResult(); + if (strlen(_fr.GetName())) + frn = frn.reduced(_fr.GetName()); + // use name to reduce the fit result, if one given - fr = std::dynamic_pointer_cast(strlen(_fr.GetName()) ? fitResult().reduced(_fr.GetName()).fComp - : fitResult().fComp); + fr = std::dynamic_pointer_cast(frn.fComp); } - if (!fr->_finalPars) { + if (!GETDMP(fr.get(), _finalPars)) { fr->setFinalParList(RooArgList()); } @@ -7739,9 +10413,10 @@ std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooN // fr->setFinalParList(l2); // } - if (!fr->_VM || size_t(fr->_VM->GetNcols()) < fr->floatParsFinal().size()) { + TMatrixTSym *prevCov = static_cast *>(GETDMP(fr.get(), _VM)); + + if (!prevCov || size_t(prevCov->GetNcols()) < fr->floatParsFinal().size()) { TMatrixDSym cov(fr->floatParsFinal().getSize()); - auto prevCov = fr->_VM; if (prevCov) { for (int i = 0; i < prevCov->GetNcols(); i++) { for (int j = 0; j < prevCov->GetNrows(); j++) { @@ -7756,17 +10431,16 @@ std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooN } i++; } - int covQualBackup = fr->_covQual; + int covQualBackup = fr->covQual(); fr->setCovarianceMatrix(cov); - fr->_covQual = covQualBackup; + fr->setCovQual(covQualBackup); } - auto _coefs = coefs(); - bool doBinWidth = false; auto ax = (binStart == -1 && binEnd == -1) ? nullptr : GetXaxis(); - RooArgList normSet = obs().argList(); + auto _obs = obs(); // may own an obs so keep alive here + RooArgList normSet = _obs.argList(); // to give consistency with BuildHistogram method, should be only the axis var if defined if (ax) { normSet.clear(); @@ -7792,13 +10466,19 @@ std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooN if (auto p = dynamic_cast(o); p) { // fr->covarianceMatrix().Print(); res = PdfWrapper(*p, _coefs.get(), !ax).getSimplePropagatedError(*fr, normSet); +#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00) + // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards p->_normSet = nullptr; +#endif } else { - res = o->getPropagatedError(*fr, normSet); - // TODO: What if coef has error? - probably need a FuncWrapper class - if (auto c = _coefs.get(); c) { - res *= c->getVal(normSet); - } + // res = o->getPropagatedError(*fr, normSet); + // // TODO: What if coef has error? - probably need a FuncWrapper class + // if (auto c = _coefs.get(); c) { + // res *= c->getVal(normSet); + // } + res = RooProduct("errorEval", "errorEval", + RooArgList(*o, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get())) + .getPropagatedError(*fr, normSet); } if (doBinWidth) { res *= ax->GetBinWidth(bin); @@ -7809,4 +10489,4 @@ std::vector xRooNode::GetBinErrors(int binStart, int binEnd, const xRooN return out; } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/roofit/xroofit/src/xRooNode_interactive.cxx b/roofit/xroofit/src/xRooNode_interactive.cxx index 2d9684c485e43..a12b6fd4cc5e2 100644 --- a/roofit/xroofit/src/xRooNode_interactive.cxx +++ b/roofit/xroofit/src/xRooNode_interactive.cxx @@ -25,30 +25,34 @@ #include "TMultiGraph.h" #include "TSystem.h" -BEGIN_XROOFIT_NAMESPACE +BEGIN_XROOFIT_NAMESPACE; void xRooNode::Interactive_Pull() { + static bool doRestore = false; auto select = dynamic_cast(gPad->GetSelected()); // if (!select) return; int event = gPad->GetEvent(); if (event == 1) { + doRestore = false; // if this is one of the 'black' points, color it temporarily - } else if (event == 11) { - if (!select) { + } else if (event == 11 || doRestore) { + if (!select || doRestore) { // now need to assemble a snapshot corresponding to the current variation - auto _h = dynamic_cast(gPad->GetPrimitive("nominal"))->GetHistogram(); + auto _h = static_cast(gPad->GetPrimitive("nominal"))->GetHistogram(); for (int i = 1; i <= _h->GetNbinsX(); i++) { std::string parName = _h->GetXaxis()->GetBinLabel(i); // ensure point is back .. sometimes editing mode allows point to drift - auto _gr = dynamic_cast(dynamic_cast(gPad->GetPrimitive("editables")) - ->GetListOfGraphs() - ->FindObject(parName.c_str())); - _gr->SetPoint(0, i - 1, dynamic_cast(gPad->GetPrimitive("nominal"))->GetPointY(i - 1)); + auto _gr = static_cast(static_cast(gPad->GetPrimitive("editables")) + ->GetListOfGraphs() + ->FindObject(parName.c_str())); + _gr->SetPoint(0, i - 1, static_cast(gPad->GetPrimitive("nominal"))->GetPointY(i - 1)); } gPad->GetMother()->GetMother()->cd(); + doRestore = false; return; } + doRestore = true; // mouse up event, if this was an original point it needs snapping back // double _y = select->GetPointY(0); TString _name = select->GetName(); @@ -57,26 +61,28 @@ void xRooNode::Interactive_Pull() _varyName = TString(_name(_name.Index(";") + 1, _name.Length())); _name = _name(0, _name.Index(";")); } - auto _h = dynamic_cast(gPad->GetPrimitive("nominal"))->GetHistogram(); + auto _h = static_cast(gPad->GetPrimitive("nominal")->FindObject("scales")); + if (!_h) + return; for (int i = 1; i <= _h->GetNbinsX(); i++) { if (_name == _h->GetXaxis()->GetBinLabel(i)) { - auto _gr = dynamic_cast(gPad->GetPrimitive("nominal")); + auto _gr = static_cast(gPad->GetPrimitive("nominal")); if (_varyName == "") { int vNum = 1; TGraphAsymmErrors *newPoint = dynamic_cast( gPad->GetPrimitive(TString::Format("%s;variation %d", select->GetName(), vNum))); while (newPoint && newPoint->GetN() > 0) { vNum++; - newPoint = dynamic_cast( + newPoint = static_cast( gPad->GetPrimitive(TString::Format("%s;variation %d", select->GetName(), vNum))); } _varyName = TString::Format("variation %d", vNum); if (!newPoint) - newPoint = dynamic_cast( + newPoint = static_cast( select->Clone(TString::Format("%s;%s", select->GetName(), _varyName.Data()))); newPoint->SetPointX(0, _gr->GetPointX(i - 1)); - newPoint->SetMarkerColor(vNum + 1); - newPoint->SetLineColor(vNum + 1); + newPoint->SetMarkerColor(860 + (vNum - 1) * 20); + newPoint->SetLineColor(newPoint->GetMarkerColor()); newPoint->SetPointEYlow(0, 0); newPoint->SetPointEYhigh(0, 0); // remove errors because currently meaningless! newPoint->Draw("z0p"); @@ -85,6 +91,9 @@ void xRooNode::Interactive_Pull() } else { select->SetPointX(0, _gr->GetPointX(i - 1)); } + static_cast( + static_cast(gPad->GetPrimitive("editables"))->GetListOfGraphs()->FindObject(_name)) + ->SetPoint(0, i - 1, _gr->GetPointY(i - 1)); break; } } @@ -109,13 +118,13 @@ void xRooNode::Interactive_Pull() _pars.setRealValue(parName.c_str(), _val); g->SetTitle(TString::Format("%s=%g", parName.c_str(), _val)); } else { - _pars.setRealValue(parName.c_str(), - dynamic_cast(gPad->GetPrimitive("nominal"))->GetPointY(i - 1) * - _h->GetBinError(i) + - _h->GetBinContent(i)); + _pars.setRealValue(parName.c_str(), static_cast(gPad->GetPrimitive("nominal"))->GetPointY(i - 1) * + _h->GetBinError(i) + + _h->GetBinContent(i)); } } TAttLine bak = *gStyle; + TAttFill bak2 = *gStyle; gStyle->SetLineStyle(5); gStyle->SetLineWidth(2); gStyle->SetLineColor(select->GetMarkerColor()); @@ -123,9 +132,12 @@ void xRooNode::Interactive_Pull() gPad->GetMother()->GetMother()->cd(1); _node->Draw(TString::Format("same overlay%s", _varyName.Data())); // TODO: find the drawn variation and set its title equal to a _pars value string - (TAttLine &)(*gStyle) = bak; + static_cast(*gStyle) = bak; + static_cast(*gStyle) = bak2; _pars = *snap; - _tmpPad->GetMother()->GetMother()->cd(); + _tmpPad->GetCanvas()->cd(); + gPad->GetCanvas()->Paint(); + gPad->GetCanvas()->Update(); } } @@ -135,7 +147,7 @@ void xRooNode::Interactive_PLLPlot() // TObject *select = gPad->GetSelected(); // if(!select) return; // if (!select->InheritsFrom(TGraph::Class())) {gPad->SetUniqueID(0); return;} - // gPad->GetCanvas()->FeedbackMode(kTRUE); + // gPad->GetCanvas()->FeedbackMode(true); auto _pull_pad = gPad->GetPad(1); auto _hidden_pad = gPad->GetPad(2); @@ -154,8 +166,8 @@ void xRooNode::Interactive_PLLPlot() // if(pxold) gVirtualX->DrawLine(pxold,pymin,pxold,pymax); // gVirtualX->DrawLine(px,pymin,px,pymax); gPad->SetUniqueID(px); - Float_t upx = gPad->AbsPixeltoX(px); - Float_t x = gPad->PadtoX(upx); + float upx = gPad->AbsPixeltoX(px); + float x = gPad->PadtoX(upx); // find which graph in the hidden pad best reflects current x value TObject *foundGraph = nullptr; @@ -237,4 +249,4 @@ void xRooNode::InteractiveObject::Interactive_PLLPlot(TVirtualPad *pad, TObject } } -END_XROOFIT_NAMESPACE +END_XROOFIT_NAMESPACE; diff --git a/rootx/CMakeLists.txt b/rootx/CMakeLists.txt index 2427805aa5f3a..242fcd2dc8836 100644 --- a/rootx/CMakeLists.txt +++ b/rootx/CMakeLists.txt @@ -25,6 +25,11 @@ if(x11) ${X11_Xpm_LIB} ${X11_LIBRARIES} ) + +if (CMAKE_SYSTEM_NAME MATCHES FreeBSD) + target_link_libraries(root PRIVATE util procstat) +endif() + elseif(cocoa) if (cxxmodules) # FIXME: Disable modules for ObjC/ObjC++. It has problems when compiling diff --git a/rootx/src/rootcoreteam.h b/rootx/src/rootcoreteam.h deleted file mode 100644 index 233665579065d..0000000000000 --- a/rootx/src/rootcoreteam.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef ROOT_ROOTCoreTeam -#define ROOT_ROOTCoreTeam - -// This file is automatically generated with names from "git shortlog". -// with a terminating 0 - that is what our rootxx.cxx and rootx-cocoa.mm expect. -// Do not modify this file directly but run "make version" or -// "build/unix/coreteam.sh". - -namespace ROOT { -namespace ROOTX { - -const char *gROOTCoreTeam[] = { - "Rene Brun", - "Fons Rademakers", - "Philippe Canal", - "Axel Naumann", - "Olivier Couet", - "Sergey Linev", - "Lorenzo Moneta", - "Vassil Vassilev", - "Danilo Piparo", - "Enrico Guiraud", - "Bertrand Bellenot", - "Gerardo Ganis", - "Guilherme Amadio", - "Jakob Blomer", - "Wouter Verkerke", - "Pere Mato Vila", - "Jonas Rembser", - "Timur Pocheptsov", - "Stephan Hageboeck", - "Matevz Tadel", - 0 }; - -} // namespace ROOTX -} // namespace ROOT - -#endif diff --git a/rootx/src/rootx.cxx b/rootx/src/rootx.cxx index 8971389079317..230d05c1bc704 100644 --- a/rootx/src/rootx.cxx +++ b/rootx/src/rootx.cxx @@ -37,13 +37,13 @@ #include #endif -#ifdef __sun -# ifndef _REENTRANT -# if __SUNPRO_CC > 0x420 -# define GLOBAL_ERRNO -# endif -# endif -#endif +#ifdef R__FBSD +#include +#include +#include +#include +#include +#endif // R__FBSD #if defined(__CYGWIN__) && defined(__GNUC__) #define ROOTBINARY "root_exe.exe" @@ -82,20 +82,12 @@ using ROOT::ROOTX::gChildpid; static int gChildpid; static int GetErrno() { -#ifdef GLOBAL_ERRNO - return ::errno; -#else return errno; -#endif } static void ResetErrno() { -#ifdef GLOBAL_ERRNO - ::errno = 0; -#else errno = 0; -#endif } #endif @@ -120,6 +112,19 @@ static const char *GetExePath() buf[ret] = 0; exepath = buf; } +#endif +#if defined(R__FBSD) + procstat* ps = procstat_open_sysctl(); // + kinfo_proc* kp = kinfo_getproc(getpid()); + + if (kp!=NULL) { + char path_str[PATH_MAX] = ""; + procstat_getpathname(ps, kp, path_str, sizeof(path_str)); + exepath = path_str; + } + + free(kp); + procstat_close(ps); #endif } return exepath.c_str(); @@ -311,7 +316,7 @@ int main(int argc, char **argv) if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) || !strncmp(argv[i], "--help", 6)) { PrintUsage(); - return 1; + return 0; } if (!strcmp(argv[i], "-b")) batch = true; if (!strcmp(argv[i], "-l")) gNoLogo = true; diff --git a/rootx/src/rootxx-cocoa.mm b/rootx/src/rootxx-cocoa.mm index 60bc4ebcac306..870be00ae0e8d 100644 --- a/rootx/src/rootxx-cocoa.mm +++ b/rootx/src/rootxx-cocoa.mm @@ -32,8 +32,6 @@ #include "RConfigure.h" #include "RVersion.h" -#include "rootcoreteam.h" - namespace { #ifdef MAC_OS_X_VERSION_10_12 const NSCompositingOperation kCompositeSourceOver = NSCompositingOperationSourceOver; @@ -867,7 +865,7 @@ void SetSplashscreenPosition() //Aux. "non-GUI" functions. // -//Caption like "Conception"/"Core Developers"/"Contributors" - white and bold. +// Caption like "Conception"/"Contributors" - white and bold. // //_________________________________________________________________ @@ -997,27 +995,6 @@ bool AddDeveloperInfo(NSMutableAttributedString *textToScroll) //TODO: diagnostic. return false; - if (!AddSectionTitle(textToScroll, @"Core Engineering: ")) - //TODO: diagnostic. - return false; - - std::size_t nLines = sizeof ROOT::ROOTX::gROOTCoreTeam / sizeof ROOT::ROOTX::gROOTCoreTeam[0]; - if (nLines > 1) { - nLines -= 1;//There is a "terminating null" in this array, get rid of it. - - NSScopeGuard coreTeam([[NSMutableString alloc] init]); - - for (std::size_t i = 0; i < nLines; ++i) - [coreTeam.Get() appendFormat : (i ? @", %s" : @"%s"), ROOT::ROOTX::gROOTCoreTeam[i]]; - [coreTeam.Get() appendFormat : @".\n\n"]; - - if (!AddSectionBody(textToScroll, coreTeam.Get())) - return false; - } else { - //TODO: diagnostic. - return false; - } - return true; } diff --git a/rootx/src/rootxx.cxx b/rootx/src/rootxx.cxx index d05bc6ee57c85..6ec0b07aaa63a 100644 --- a/rootx/src/rootxx.cxx +++ b/rootx/src/rootxx.cxx @@ -32,8 +32,6 @@ #include "snprintf.h" #include "strlcpy.h" -#include "rootcoreteam.h" - #if defined(R__AIX) || defined(R__SOLARIS) # include #endif @@ -767,8 +765,6 @@ int DrawCredits(bool draw, bool extended) y = DrawCreditItem("Conception: ", gConception, y, draw); y += 2 * lineSpacing; - y = DrawCreditItem("Core Engineering: ", ROOT::ROOTX::gROOTCoreTeam, y, draw); - if (extended && gContributors) { y += 2 * lineSpacing; y = DrawCreditItem("Contributors: ", (const char **)gContributors, y, draw); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 5a6e92ea40181..47bcdfd76c605 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. +# Copyright (C) 1995-2022, Rene Brun and Fons Rademakers. # All rights reserved. # # For the licensing terms see $ROOTSYS/LICENSE. @@ -29,6 +29,7 @@ endif() if(DEFINED ROOT_SOURCE_DIR) # Testing using the binary tree set(ROOT_root_CMD ${ROOT_BINDIR}/root.exe) + include_directories(${ROOT_SOURCE_DIR}/tutorials) else() # Testing using an installation (assuming access to ROOT CMake modules) include_directories(${ROOT_INCLUDE_DIRS}) @@ -58,7 +59,7 @@ if(MSVC) add_custom_command(TARGET Event POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/Event.pcm ${CMAKE_CURRENT_BINARY_DIR}/$/Event.pcm) - endif() + endif() endif() ROOT_EXECUTABLE(eventexe MainEvent.cxx LIBRARIES Event RIO Tree TreePlayer Hist Net) ROOT_ADD_TEST(test-event COMMAND eventexe) @@ -134,7 +135,7 @@ ROOT_ADD_TEST(test-bench COMMAND bench -s LABELS longtest) #--stressShapes------------------------------------------------------------------------------------ ROOT_EXECUTABLE(stressShapes stressShapes.cxx LIBRARIES Geom Tree GenVector Gpad) ROOT_ADD_TEST(test-stressshapes COMMAND stressShapes -b FAILREGEX "FAILED|Error in") -if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) +if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stressshapes-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressShapes.cxx FAILREGEX "FAILED|Error in") endif() @@ -165,7 +166,7 @@ if(ROOT_opengl_FOUND) endif() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/../tutorials/graphics/earth.dat earth.dat COPYONLY) ROOT_ADD_TEST(test-stressgraphics ENVIRONMENT LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/lib:$ENV{LD_LIBRARY_PATH} COMMAND stressGraphics -b -k FAILREGEX "FAILED|Error in" LABELS longtest) - if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) + if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stressgraphics-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressGraphics.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stressgraphics ) endif() @@ -174,7 +175,7 @@ endif() #--stressHistogram------------------------------------------------------------------------------------ ROOT_EXECUTABLE(stressHistogram stressHistogram.cxx LIBRARIES Hist RIO) ROOT_ADD_TEST(test-stresshistogram COMMAND stressHistogram FAILREGEX "FAILED|Error in" LABELS longtest) -if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) +if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stresshistogram-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressHistogram.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stresshistogram ) endif() @@ -245,9 +246,9 @@ if(ROOT_roofit_FOUND) ROOT_EXECUTABLE(stressRooFit stressRooFit.cxx LIBRARIES RooFit RooFitMore) else() ROOT_EXECUTABLE(stressRooFit stressRooFit.cxx LIBRARIES RooFit ) - endif() + endif() configure_file(stressRooFit_ref.root stressRooFit_ref.root COPYONLY) - ROOT_ADD_TEST(test-stressroofit COMMAND stressRooFit -b off FAILREGEX "FAILED|Error in") + ROOT_ADD_TEST(test-stressroofit COMMAND stressRooFit -b legacy FAILREGEX "FAILED|Error in") ROOT_ADD_TEST(test-stressroofit-batchmode-cpu COMMAND stressRooFit -b cpu FAILREGEX "FAILED|Error in") if(CUDA_FOUND) ROOT_ADD_TEST(test-stressroofit-batchmode-cuda COMMAND stressRooFit -b cuda FAILREGEX "FAILED|Error in") @@ -266,29 +267,33 @@ if(ROOT_roofit_FOUND) #--stressRooStats---------------------------------------------------------------------------------- ROOT_EXECUTABLE(stressRooStats stressRooStats.cxx LIBRARIES RooStats) configure_file(stressRooStats_ref.root stressRooStats_ref.root COPYONLY) - ROOT_ADD_TEST(test-stressroostats COMMAND stressRooStats FAILREGEX "FAILED|Error in" LABELS longtest) + ROOT_ADD_TEST(test-stressroostats COMMAND stressRooStats -b legacy FAILREGEX "FAILED|Error in" LABELS longtest) ROOT_ADD_TEST(test-stressroostats-batchmode-cpu COMMAND stressRooStats -b cpu FAILREGEX "FAILED|Error in" LABELS longtest) if(CUDA_FOUND) ROOT_ADD_TEST(test-stressroostats-batchmode-cuda COMMAND stressRooStats -b cuda FAILREGEX "FAILED|Error in" LABELS longtest) endif() - if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) + if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stressroostats-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressRooStats.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stressroostats ) endif() if (ROOT_minuit2_FOUND) - ROOT_ADD_TEST(test-stressroostats-minuit2 COMMAND stressRooStats -minim Minuit2 FAILREGEX "FAILED|Error in" LABELS longtest) + ROOT_ADD_TEST(test-stressroostats-minuit2 COMMAND stressRooStats -minim Minuit2 -b legacy FAILREGEX "FAILED|Error in" LABELS longtest) endif() -endif() -#--stressHistFactory-------------------------------------------------------------------------------- -if(ROOT_roofit_FOUND AND GSL_FOUND AND ROOT_xml_FOUND) - ROOT_EXECUTABLE(stressHistFactory stressHistFactory.cxx LIBRARIES RooStats HistFactory XMLParser) - if(NOT MSVC) - configure_file(HistFactoryTest.tar HistFactoryTest.tar COPYONLY) - configure_file(stressHistFactory_ref.root stressHistFactory_ref.root COPYONLY) - ROOT_ADD_TEST(test-stressHistFactory ENVIRONMENT ROOTSYS=${CMAKE_BINARY_DIR} COMMAND stressHistFactory FAILREGEX "FAILED|Error in" LABELS longtest) - ROOT_ADD_TEST(test-stressHistFactory-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressHistFactory.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stressHistFactory) + #--stressHistFactory-------------------------------------------------------------------------------- + if(GSL_FOUND AND ROOT_xml_FOUND) + ROOT_EXECUTABLE(stressHistFactory stressHistFactory.cxx LIBRARIES RooStats HistFactory XMLParser) + if(NOT MSVC) + configure_file(HistFactoryTest.tar HistFactoryTest.tar COPYONLY) + configure_file(stressHistFactory_ref.root stressHistFactory_ref.root COPYONLY) + ROOT_ADD_TEST(test-stressHistFactory ENVIRONMENT ROOTSYS=${CMAKE_BINARY_DIR} COMMAND stressHistFactory FAILREGEX "FAILED|Error in" LABELS longtest) + if (ROOT_minuit2_FOUND) + ROOT_ADD_TEST(test-stressHistFactory-minuit2 ENVIRONMENT ROOTSYS=${CMAKE_BINARY_DIR} COMMAND stressHistFactory -minim Minui2 FAILREGEX "FAILED|Error in" LABELS longtest) + endif() + ROOT_ADD_TEST(test-stressHistFactory-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressHistFactory.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stressHistFactory) + endif() endif() + endif() #--stressFit--------------------------------------------------------------------------------- @@ -302,7 +307,7 @@ if(ROOT_unuran_FOUND) ROOT_EXECUTABLE(stressHistoFit stressHistoFit.cxx LIBRARIES MathCore Matrix Unuran Tree Gpad) ROOT_ADD_TEST(test-stresshistofit COMMAND stressHistoFit FAILREGEX "FAILED|Error in" LABELS longtest) if(NOT MSVC OR CMAKE_SIZEOF_VOID_P EQUAL 4 OR win_broken_tests) - if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) + if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stresshistofit-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressHistoFit.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stresshistofit ) endif() @@ -312,7 +317,7 @@ endif() #--stressEntryList--------------------------------------------------------------------------- ROOT_EXECUTABLE(stressEntryList stressEntryList.cxx LIBRARIES MathCore Tree Hist) ROOT_ADD_TEST(test-stressentrylist COMMAND stressEntryList -b FAILREGEX "FAILED|Error in") -if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) +if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_TEST(test-stressentrylist-interpreted COMMAND ${ROOT_root_CMD} -b -q -l ${CMAKE_CURRENT_SOURCE_DIR}/stressEntryList.cxx FAILREGEX "FAILED|Error in" DEPENDS test-stressentrylist) endif() @@ -444,6 +449,7 @@ if (NOT cxxmodules) ROOT_ADD_TEST(test-periodic-build COMMAND ${CMAKE_CTEST_COMMAND} ${build_generator_args} --build-and-test ${CMAKE_CURRENT_SOURCE_DIR}/periodic periodic-build + --build-options -DCMAKE_PREFIX_PATH=${CMAKE_BINARY_DIR} ) else() ROOT_ADD_TEST(test-periodic-build @@ -451,6 +457,7 @@ if (NOT cxxmodules) env CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} ${CMAKE_CTEST_COMMAND} --build-generator ${CMAKE_GENERATOR} --build-and-test ${CMAKE_CURRENT_SOURCE_DIR}/periodic periodic-build + --build-options -DCMAKE_PREFIX_PATH=${CMAKE_BINARY_DIR} ) endif() endif() diff --git a/test/RootShower/CMakeLists.txt b/test/RootShower/CMakeLists.txt new file mode 100644 index 0000000000000..e7bf06d114d4b --- /dev/null +++ b/test/RootShower/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. +# All rights reserved. +# +# For the licensing terms see $ROOTSYS/LICENSE. +# For the list of contributors see $ROOTSYS/README/CREDITS. + +cmake_minimum_required(VERSION 3.9 FATAL_ERROR) + +project(RootShower) + +find_package(ROOT REQUIRED) + +set(CMAKE_CXX_FLAGS ${ROOT_CXX_FLAGS}) + +include_directories(${ROOT_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}) + +set(SOURCES + GButtonFrame.cxx + GTitleFrame.cxx + MyDetector.cxx + MyEvent.cxx + MyParticle.cxx + RootShower.cxx + RSAbout.cxx + RSHelpText.cxx + RSMsgBox.cxx + SettingsDlg.cxx +) + +set(HEADERS MyParticle.h MyDetector.h MyEvent.h) + +if(MSVC) + set(RCFILE RootShower.rc) +endif() + +ROOT_GENERATE_DICTIONARY(RootShowerDict ${HEADERS} LINKDEF RSLinkDef.h) +file(COPY ${HEADERS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY ".rootshowerrc" DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) + +add_executable(RootShower ${SOURCES} RootShowerDict.cxx ${RCFILE}) +target_link_libraries(RootShower ROOT::Core ROOT::Rint ROOT::Gui ROOT::RIO ROOT::Hist ROOT::Gpad + ROOT::Graf ROOT::EG ROOT::Html ROOT::Geom ROOT::Tree +) +set_target_properties(RootShower PROPERTIES ENABLE_EXPORTS 1) +if(MSVC) + add_custom_command(TARGET RootShower POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/$/RootShower.exe + ${CMAKE_CURRENT_BINARY_DIR} + ) + set_target_properties(RootShower PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS TRUE) +endif() + +file(COPY anim DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY icons DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) + +install(TARGETS RootShower RUNTIME DESTINATION ${PROJECT_NAME} COMPONENT applications) +install(DIRECTORY anim DESTINATION ${PROJECT_NAME}/anim COMPONENT anim) +install(DIRECTORY icons DESTINATION ${PROJECT_NAME}/icons COMPONENT icons) +install(FILES ${HEADERS} DESTINATION ${PROJECT_NAME} COMPONENT headers) +install(FILES ".rootshowerrc" DESTINATION ${PROJECT_NAME} COMPONENT settings) diff --git a/test/RootShower/MyEvent.h b/test/RootShower/MyEvent.h index 97e5c56660ab2..5bc2410296d95 100644 --- a/test/RootShower/MyEvent.h +++ b/test/RootShower/MyEvent.h @@ -53,7 +53,7 @@ class EventHeader { Int_t GetPrimary() const { return fPrimary; } Double_t GetEnergy() const { return fEnergy; } - ClassDefOverride(EventHeader,1) //Event Header + ClassDef(EventHeader,1) //Event Header }; class MyEvent : public TObject { diff --git a/test/RootShower/RootShower.cxx b/test/RootShower/RootShower.cxx index 748445749bc68..ffc6b7c8d6328 100644 --- a/test/RootShower/RootShower.cxx +++ b/test/RootShower/RootShower.cxx @@ -1306,29 +1306,24 @@ void RootShower::ShowInfos() Window_t wdummy; int ax, ay; TRootHelpDialog *hd; - Char_t str[32]; - Char_t Msg[500]; + std::stringstream Msg; Double_t dimx,dimy,dimz; fEvent->GetDetector()->GetDimensions(&dimx, &dimy, &dimz); - sprintf(Msg, " Some information about the current shower\n"); - sprintf(Msg, "%s Dimensions of the target\n", Msg); - sprintf(Msg, "%s X .................... : %1.2e [cm] \n", Msg, dimx); - sprintf(Msg, "%s Y .................... : %1.2e [cm] \n", Msg, dimy); - sprintf(Msg, "%s Z .................... : %1.2e [cm] \n", Msg, dimz); - sprintf(Msg, "%s Magnetic field ....... : %1.2e [kGauss]\n", Msg, - fEvent->GetB()); - sprintf(Msg, "%s Initial particle ..... : %s \n", Msg, - fEvent->GetParticle(0)->GetName()); - sprintf(Msg, "%s Initial energy ....... : %1.2e [GeV] \n", Msg, - fEvent->GetHeader()->GetEnergy()); - sprintf(Msg, "%s Total Energy loss .... : %1.2e [GeV]", Msg, - fEvent->GetDetector()->GetTotalELoss()); - - sprintf(str, "Infos on current shower"); - hd = new TRootHelpDialog(this, str, 420, 155); - hd->SetText(Msg); + Msg << std::scientific << std::setprecision(2); + Msg << " Some information about the current shower" << std::endl; + Msg << " Dimensions of the target" << std::endl; + Msg << " X .................. : " << dimx << " [cm]" << std::endl; + Msg << " Y .................. : " << dimy << " [cm]" << std::endl; + Msg << " Z .................. : " << dimz << " [cm]" << std::endl; + Msg << " Magnetic field ....... : " << fEvent->GetB() << " [kGauss]" << std::endl; + Msg << " Initial particle ..... : " << fEvent->GetParticle(0)->GetName() << std::endl; + Msg << " Initial energy ....... : " << fEvent->GetHeader()->GetEnergy() << " [GeV]" << std::endl; + Msg << " Total Energy loss .... : " << fEvent->GetDetector()->GetTotalELoss() << " [GeV]" << std::endl; + + hd = new TRootHelpDialog(this, "Infos on current shower", 420, 155); + hd->SetText(Msg.str().c_str()); gVirtualX->TranslateCoordinates( GetId(), GetParent()->GetId(), (Int_t)(GetWidth() - 420) >> 1,(Int_t)(GetHeight() - 155) >> 1, ax, ay, wdummy); @@ -1448,6 +1443,7 @@ void RootShower::Clicked(TGListTreeItem *item, Int_t x, Int_t y) int main(int argc, char **argv) { + TApplication *theApp; Bool_t rint = kFALSE; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i], "-d")) rint = kTRUE; @@ -1458,8 +1454,8 @@ int main(int argc, char **argv) return 0; } } - - TApplication *theApp; + std::string inclCwd = "-I" + gSystem->GetWorkingDirectory(); + TROOT::AddExtraInterpreterArgs({inclCwd}); if (rint) theApp = new TRint("App", &argc, argv); else diff --git a/test/fit/WrapperRooPdf.h b/test/fit/WrapperRooPdf.h index 3a97c4220d67a..f543e372351da 100644 --- a/test/fit/WrapperRooPdf.h +++ b/test/fit/WrapperRooPdf.h @@ -22,23 +22,20 @@ class WrapperRooPdf : public ROOT::Math::IParamMultiFunction { */ WrapperRooPdf(RooAbsPdf * pdf, const std::string xvar = "x", bool norm = true) : fNorm(norm), - fPdf(pdf), - fX(0), - fParams(nullptr) + fPdf(pdf) { assert(fPdf != nullptr); - RooArgSet *vars = fPdf->getVariables(); + std::unique_ptr vars{fPdf->getVariables()}; RooAbsArg * arg = vars->find(xvar.c_str()); // code should abort if not found if (!arg) std::cout <<"Error - observable " << xvar << "is not in the list of pdf variables" << std::endl; assert(arg != nullptr); RooArgSet obsList(*arg); //arg.setDirtyInhibit(true); // do have faster setter of values - fX = fPdf->getObservables(obsList); - fParams = fPdf->getParameters(obsList); + fX = std::unique_ptr{fPdf->getObservables(obsList)}; + fParams = std::unique_ptr{fPdf->getParameters(obsList)}; assert(fX != nullptr); assert(fParams != nullptr); - delete vars; #ifdef DEBUG fX->Print("v"); fParams->Print("v"); @@ -53,14 +50,12 @@ class WrapperRooPdf : public ROOT::Math::IParamMultiFunction { */ WrapperRooPdf(RooAbsPdf * pdf, const RooArgSet & obsList, bool norm = true ) : fNorm(norm), - fPdf(pdf), - fX(nullptr), - fParams(nullptr) + fPdf(pdf) { assert(fPdf != nullptr); - fX = fPdf->getObservables(obsList); - fParams = fPdf->getParameters(obsList); + fX = std::unique_ptr{fPdf->getObservables(obsList)}; + fParams = std::unique_ptr{fPdf->getParameters(obsList)}; assert(fX != nullptr); assert(fParams != nullptr); #ifdef DEBUG @@ -78,12 +73,6 @@ class WrapperRooPdf : public ROOT::Math::IParamMultiFunction { } - ~WrapperRooPdf() override { - // need to delete observables and parameter list - if (fX) delete fX; - if (fParams) delete fParams; - } - /** clone the function */ @@ -181,7 +170,7 @@ class WrapperRooPdf : public ROOT::Math::IParamMultiFunction { //fX->Print("v"); if (fNorm) - return fPdf->getVal(fX); + return fPdf->getVal(fX.get()); else return fPdf->getVal(); // get unnormalized value @@ -203,8 +192,8 @@ class WrapperRooPdf : public ROOT::Math::IParamMultiFunction { bool fNorm; mutable RooAbsPdf * fPdf; - mutable RooArgSet * fX; - mutable RooArgSet * fParams; + mutable std::unique_ptr fX; + mutable std::unique_ptr fParams; mutable std::vector fParamValues; diff --git a/test/fit/testFitPerf.cxx b/test/fit/testFitPerf.cxx index 6c0545439b26b..ad5115c890fb4 100644 --- a/test/fit/testFitPerf.cxx +++ b/test/fit/testFitPerf.cxx @@ -574,11 +574,7 @@ int FitUsingRooFit(TTree * tree, TF1 * func) { bool save = false; #endif -//#ifndef _WIN32 // until a bug 30762 is fixed - RooFitResult * result = pdf.fitTo(data, RooFit::Minos(0), RooFit::Hesse(1) , RooFit::PrintLevel(level), RooFit::Save(save) ); -// #else -// RooFitResult * result = pdf.fitTo(data ); -// #endif + std::unique_ptr result{pdf.fitTo(data, RooFit::Minos(0), RooFit::Hesse(1) , RooFit::PrintLevel(level), RooFit::Save(save) )}; #ifdef DEBUG mean.Print(); @@ -671,11 +667,7 @@ int FitUsingRooFit2(TTree * tree) { #endif -#ifndef _WIN32 // until a bug 30762 is fixed - RooFitResult * result = pdf[N-1]->fitTo(data, RooFit::Minos(0), RooFit::Hesse(1) , RooFit::PrintLevel(level), RooFit::Save(save) ); -#else - RooFitResult * result = pdf[N-1]->fitTo(data); -#endif + std::unique_ptr result{pdf[N-1]->fitTo(data, RooFit::Minos(0), RooFit::Hesse(1) , RooFit::PrintLevel(level), RooFit::Save(save) )}; #ifdef DEBUG assert(result != 0); diff --git a/test/fit/testRooFit.cxx b/test/fit/testRooFit.cxx index 923c6329a436b..13bf2b0c96be6 100644 --- a/test/fit/testRooFit.cxx +++ b/test/fit/testRooFit.cxx @@ -213,18 +213,14 @@ int FitUsingRooFit(TTree & tree, RooAbsPdf & pdf, RooArgSet & xvars) { int level = 2; std::cout << "num entries = " << data.numEntries() << std::endl; bool save = true; - pdf.getVariables()->Print("v"); // print the parameters + std::unique_ptr{pdf.getVariables()}->Print("v"); // print the parameters std::cout << "\n\nDo the fit now \n\n"; #else int level = -1; bool save = false; #endif -#ifndef _WIN32 // until a bug 30762 is fixed - RooFitResult * result = pdf.fitTo(data, RooFit::Minos(0), RooFit::Hesse(0) , RooFit::PrintLevel(level), RooFit::Save(save) ); -#else - RooFitResult * result = pdf.fitTo(data ); -#endif + std::unique_ptr result{pdf.fitTo(data, RooFit::Minos(0), RooFit::Hesse(0) , RooFit::PrintLevel(level), RooFit::Save(save) )}; #ifdef DEBUG assert(result != nullptr); @@ -238,9 +234,8 @@ int FitUsingRooFit(TTree & tree, RooAbsPdf & pdf, RooArgSet & xvars) { w.Stop(); std::cout << "RooFit result " << std::endl; - RooArgSet * params = pdf.getParameters(xvars); + std::unique_ptr params{pdf.getParameters(xvars)}; params->Print("v"); - delete params; std::cout << "\nTime: \t" << w.RealTime() << " , " << w.CpuTime() << std::endl; diff --git a/test/stress.cxx b/test/stress.cxx index 00e02ace1ce2d..de8061a9fc9e1 100644 --- a/test/stress.cxx +++ b/test/stress.cxx @@ -402,9 +402,9 @@ void stress3() Float_t comp = f.GetCompressionFactor(); Bool_t OK = kTRUE; #ifdef R__HAS_CLOUDFLARE_ZLIB - constexpr Long64_t lastgood = 52290; + constexpr Long64_t lastgood = 52264; #else - constexpr Long64_t lastgood = 52116; + constexpr Long64_t lastgood = 52090; #endif constexpr Long64_t tolerance = 150; #ifdef R__HAS_DEFAULT_LZ4 diff --git a/test/stressGraphics.cxx b/test/stressGraphics.cxx index 8b6aa9af9ad03..62d4c5a220d5c 100644 --- a/test/stressGraphics.cxx +++ b/test/stressGraphics.cxx @@ -158,8 +158,6 @@ Int_t gPS1RefNb[60]; Int_t gPS1ErrNb[60]; Int_t gPDFRefNb[60]; Int_t gPDFErrNb[60]; -Int_t gGIFRefNb[60]; -Int_t gGIFErrNb[60]; Int_t gJPGRefNb[60]; Int_t gJPGErrNb[60]; Int_t gPNGRefNb[60]; @@ -303,14 +301,12 @@ void stressGraphics(Int_t verbose = 0) sscanf(&line[18] ,"%d",&gPS1ErrNb[i]); sscanf(&line[28] ,"%d",&gPDFRefNb[i]); sscanf(&line[38] ,"%d",&gPDFErrNb[i]); - sscanf(&line[48] ,"%d",&gGIFRefNb[i]); - sscanf(&line[58] ,"%d",&gGIFErrNb[i]); - sscanf(&line[68] ,"%d",&gJPGRefNb[i]); - sscanf(&line[78] ,"%d",&gJPGErrNb[i]); - sscanf(&line[88] ,"%d",&gPNGRefNb[i]); - sscanf(&line[98] ,"%d",&gPNGErrNb[i]); - sscanf(&line[107],"%d",&gPS2RefNb[i]); - sscanf(&line[118],"%d",&gPS2ErrNb[i]); + sscanf(&line[48] ,"%d",&gJPGRefNb[i]); + sscanf(&line[58] ,"%d",&gJPGErrNb[i]); + sscanf(&line[68] ,"%d",&gPNGRefNb[i]); + sscanf(&line[78] ,"%d",&gPNGErrNb[i]); + sscanf(&line[87] ,"%d",&gPS2RefNb[i]); + sscanf(&line[98] ,"%d",&gPS2ErrNb[i]); } i++; } @@ -319,7 +315,7 @@ void stressGraphics(Int_t verbose = 0) gRandom->SetSeed(65539); if (gOptionR) { - std::cout << "Test# PS1Ref# PS1Err# PDFRef# PDFErr# GIFRef# GIFErr# JPGRef# JPGErr# PNGRef# PNGErr# PS2Ref# PS2Err#" <> line) { - l = line; - if (l.Contains("%!PS-Adobe")) counting = kFALSE; - if (l.Contains("%%EndProlog")) counting = kTRUE; - if (counting) count = count+l.Length(); + if (line.Contains("%!PS-Adobe")) counting = kFALSE; + if (line.Contains("%%EndProlog")) counting = kTRUE; + if (counting) count = count+line.Length(); } if (gVerbose==1) printf(">>>>>>>>> Number of characters found in %s: %d\n",filename.Data(),count); - delete [] line; return count; } @@ -584,14 +577,6 @@ void TestReport1(TCanvas *C, const TString &title, Int_t IPS) gPDFRefNb[gTestNum-1], gPDFErrNb[gTestNum-1]); - snprintf(outfile, outfileSize, "sg%2.2d.gif",gTestNum); - C->cd(0); - C->SaveAs(outfile); - TString giffile = outfile; - StatusPrint(giffile, 0, " GIF output", FileSize(outfile), - gGIFRefNb[gTestNum-1], - gGIFErrNb[gTestNum-1]); - snprintf(outfile, outfileSize, "sg%2.2d.jpg",gTestNum); C->cd(0); C->SaveAs(outfile); @@ -2217,7 +2202,7 @@ void options2d1() C->Divide(2,2); C->SetFillColor(17); C->cd(1); - gH2->Draw(); pl1.DrawPaveLabel(x1,y1,x2,y2,"SCAT","brNDC"); + gH2->Draw("text"); pl1.DrawPaveLabel(x1,y1,x2,y2,"TEXT","brNDC"); C->cd(2); gH2->Draw("box"); pl1.DrawPaveLabel(x1,y1,x2,y2,"BOX","brNDC"); C->cd(3); diff --git a/test/stressGraphics.ref b/test/stressGraphics.ref index 2aecf462e8759..e3676cfff37f0 100644 --- a/test/stressGraphics.ref +++ b/test/stressGraphics.ref @@ -1,52 +1,52 @@ -Test# PS1Ref# PS1Err# PDFRef# PDFErr# GIFRef# GIFErr# JPGRef# JPGErr# PNGRef# PNGErr# PS2Ref# PS2Err# - 1 529 50 12709 50 6351 100 23848 3700 3937 100 569 60 - 2 4627 600 14506 100 7608 1500 13368 7900 9208 3000 4690 600 - 3 452 50 12632 50 4797 350 11232 4200 3796 10700 492 50 - 4 23617 1500 19386 100 43077 12000 143320 123000 45665 11000 24908 1500 - 5 1025 150 12802 200 19715 2900 33468 9900 30846 5000 1072 200 - 6 430 50 12669 50 4041 400 9558 100 5325 700 471 50 - 7 4980 50 13893 50 8215 310 16143 1300 12230 500 5011 70 - 8 5442 80 13473 50 9599 150 18430 700 12398 300 5469 80 - 9 9253 100 14377 50 9664 600 19851 2400 12199 900 9449 100 - 10 8863 70 13539 100 14622 1200 24343 1100 23278 1700 8894 70 - 11 12971 100 14444 50 20508 1300 34063 2000 32033 1200 12864 150 - 12 7674 100 13533 50 27519 2500 83557 3000 38505 4000 7720 150 - 13 5600 400 13242 300 9805 400 16881 400 15063 800 5638 400 - 14 14190539 4000000 12926 100 15663 800 23076 9500 25987 3000 14190704 4000000 - 15 15690 5000 17179 200 12037 800 23076 9500 15202 900 10437 5000 - 16 28072 400 23287 200 25845 2000 44462 11000 30062 5000 38007 400 - 17 20444 400 21520 100 12050 800 27511 11000 16867 600 20721 400 - 18 15894 100 19305 100 12943 550 27187 10300 15925 350 15925 100 - 19 22521 300 42926 150 21207 6800 43868 17000 19232 11000 22729 300 - 20 3664 600 14437 100 9623 900 19824 6300 10396 900 4220 600 - 21 17608 600 13855 100 33543 5500 49440 6300 37586 9000 5938 600 - 22 4866 600 14162 100 14490 2010 30889 10050 21311 1800 4845 600 - 23 4131 40 15272 50 13456 500 34038 2500 12258 1400 4162 40 - 24 7813 300 23739 100 4662 2300 11085 6000 6973 3100 8081 300 - 25 28422 150 29391 100 5187 1400 14104 14800 7386 2800 14493 150 - 26 4545 150 14541 100 11094 1400 27602 14800 13094 2800 4467 150 - 27 6141 200 15967 100 14776 4200 39594 21600 19331 7000 6596 500 - 28 9110 500 16953 200 9738 4200 21346 21600 10645 7000 8869 500 - 29 7419 500 15112 200 8113 4200 18872 21600 7928 7000 7296 500 - 30 17016 5500 18198 100 13764 3400 32434 17400 22157 5000 20823 5500 - 31 30615 8200 27494 150 29010 5900 50520 18200 35724 5400 36690 8200 - 32 3304592 100 712308 500 155478 32000 62688 19000 123056 7000 0 0 - 33 335486 5500 445266 1100 34942 8300 65532 27800 37314 12000 345281 5500 - 34 36514 300 16815 200 25333 2200 47408 12700 33739 3700 36399 300 - 35 207729 750 87126 100 41853 6200 76094 38000 54717 11000 210497 800 - 36 401670 6500 156361 500 38898 10400 62719 34100 45592 14000 410114 6500 - 37 566142 5000 225206 750 43638 6300 65828 31800 53934 6500 573396 5000 - 38 3738751 35000 1292739 8000 84139 3400 60580 9900 133547 3500 3783013 35000 - 39 1456993 9000 853193 50000 54777 8600 38425 13500 91242 18100 1463263 7500 - 40 38312 200 56877 250 47205 3900 36524 11800 119641 8000 38121 200 - 41 15025 3000 29289 500 34091 1500 42525 11300 33336 3900 14787 4000 - 42 254604 5000 383258 7000 34608 5000 55666 30400 46534 6500 259594 7000 - 43 4846 150 14075 150 24281 200 33239 600 25303 300 4877 150 - 44 1435879 150000 12837 100 96029 4000 25972 100 359846 15000 1085792 250000 - 45 5884 500 16577 200 30259 3500 40706 14000 30026 4000 0 0 - 46 5723 700 15720 200 14291 2600 32236 11000 16916 3200 5670 800 - 47 1666331 160000 529473 50000 38603 3000 29519 3000 71404 7000 0 0 - 48 176455 17000 266221 25000 15528 1500 40859 4000 31451 3000 193640 19000 - 49 13592 1300 16669 1600 24300 2400 52678 5200 22353 2200 13291 1300 - 50 153915 10000 545717 50000 10242 1000 17106 1000 11410 1000 173729 10000 +Test# PS1Ref# PS1Err# PDFRef# PDFErr# JPGRef# JPGErr# PNGRef# PNGErr# PS2Ref# PS2Err# + 1 529 50 12767 50 23848 3700 3937 100 569 60 + 2 4627 600 14506 100 13368 7900 9208 3000 4690 600 + 3 452 50 12694 50 11232 4200 3796 10700 492 50 + 4 23617 1500 19386 100 143320 123000 45665 11000 24908 1500 + 5 1025 150 12802 200 33468 9900 30846 5000 1072 200 + 6 430 50 12669 50 9558 100 5325 700 471 50 + 7 4980 50 13893 50 16143 1300 12230 500 5011 70 + 8 5442 80 13473 50 18430 700 12398 300 5469 80 + 9 9253 100 14377 50 19851 2400 12199 900 9449 100 + 10 8863 70 13645 100 24343 1100 23278 1700 8894 70 + 11 12971 100 14444 50 34063 2000 32033 1200 12864 150 + 12 7674 100 13533 50 83557 3000 38505 4000 7720 150 + 13 5600 400 13242 300 16881 400 15063 800 5638 400 + 14 14190539 4000000 12926 100 23076 9500 25987 3000 14190704 4000000 + 15 15690 5000 17179 200 23076 9500 15202 900 10437 5000 + 16 28072 400 23287 200 44462 11000 30062 5000 38007 400 + 17 20444 400 21520 100 27511 11000 16867 600 20721 400 + 18 15894 100 19305 100 27187 10300 15925 350 15925 100 + 19 22521 300 42926 150 43868 17000 19232 11000 22729 300 + 20 3664 600 14437 100 19824 6300 10396 900 4220 600 + 21 17608 600 13900 150 49440 6300 37586 9000 5938 600 + 22 4866 600 14162 100 30889 10050 21311 1800 4845 600 + 23 4131 40 15272 50 34038 2500 12258 1400 4162 40 + 24 7813 300 23739 100 11085 6000 6973 3100 8081 300 + 25 28422 150 29391 300 14104 14800 7386 2800 14493 150 + 26 4545 150 14541 100 27602 14800 13094 2800 4467 150 + 27 6141 200 15967 100 39594 21600 19331 7000 6596 500 + 28 9110 500 16584 200 21346 21600 10645 7000 8869 500 + 29 7419 500 15112 200 18872 21600 7928 7000 7296 500 + 30 17016 5500 18198 100 32434 17400 22157 5000 20823 5500 + 31 30615 8200 27176 150 50520 18200 35724 5400 36690 8200 + 32 3304592 100 712308 500 62688 19000 123056 7000 0 0 + 33 89233 500 47975 300 65532 27800 37314 12000 90600 500 + 34 36514 300 16815 200 47408 12700 33739 3700 36399 300 + 35 207729 750 87126 100 76094 38000 54717 11000 210497 800 + 36 401670 6500 156361 500 62719 34100 45592 14000 410114 6500 + 37 566142 5000 225206 750 65828 31800 53934 6500 573396 5000 + 38 3738751 35000 1292739 8000 60580 9900 133547 3500 3783013 35000 + 39 1466028 9000 853193 50000 38425 13500 91242 18100 1463263 7500 + 40 38312 200 56877 250 36524 11800 119641 8000 38121 200 + 41 15025 3000 29289 500 42525 11300 33336 3900 14787 4000 + 42 254604 5000 383258 7000 55666 30400 46534 6500 259594 7000 + 43 4846 150 14075 150 33239 600 25303 300 4877 150 + 44 1435879 150000 12837 100 25972 100 359846 15000 1085792 250000 + 45 5884 500 16577 200 40706 14000 30026 4000 0 0 + 46 5723 700 15720 200 32236 11000 16916 3200 5670 800 + 47 1666331 160000 529473 50000 29519 3000 71404 7000 0 0 + 48 26983 1700 18807 2500 23765 2000 11196 1000 27409 1900 + 49 13592 1300 16669 1600 52678 5200 22353 2200 13291 1300 + 50 153915 10000 545717 50000 17106 1000 11410 1000 173729 10000 diff --git a/test/stressGraphics_builtinzlib.ref b/test/stressGraphics_builtinzlib.ref index a5929493812ad..7e943403beb94 100644 --- a/test/stressGraphics_builtinzlib.ref +++ b/test/stressGraphics_builtinzlib.ref @@ -1,51 +1,51 @@ -Test# PS1Ref# PS1Err# PDFRef# PDFErr# GIFRef# GIFErr# JPGRef# JPGErr# PNGRef# PNGErr# PS2Ref# PS2Err# - 1 529 50 12710 50 6368 100 23758 3700 3937 100 569 60 - 2 4627 600 14463 100 7566 1500 13359 7900 9227 3000 4690 600 - 3 452 50 12634 50 4840 350 11764 4200 4338 10700 492 50 - 4 23688 1500 19140 100 44192 12000 143676 123000 47075 11000 24979 1500 - 5 1025 150 12806 150 19131 2900 32266 9900 29901 5000 1072 200 - 6 432 50 12627 50 4049 400 9517 150 5306 700 473 50 - 7 5015 50 13822 50 8342 310 16377 1300 12462 500 5046 70 - 8 5488 80 13391 50 9682 150 18439 700 12408 300 5502 80 - 9 9257 100 14261 50 9601 600 20441 2400 12143 900 9377 100 - 10 8831 70 13573 100 13680 1200 24251 1100 23337 1700 8862 70 - 11 12967 100 14386 50 20439 1300 33842 2000 32100 1200 12970 150 - 12 7666 100 13441 50 27523 2500 83044 3000 37165 4100 7713 150 - 13 5600 400 13242 300 9801 400 16868 400 15083 800 5638 400 - 14 14193187 4000000 12924 100 15813 800 27112 9500 25080 3000 14193352 4000000 - 15 16185 5000 17071 200 11803 800 22801 9500 14938 900 11271 5000 - 16 28087 400 23095 200 26368 2000 44898 11000 30209 5000 38047 400 - 17 20424 400 21328 100 12138 800 27719 11000 16806 600 20704 400 - 18 15874 100 19080 100 12980 550 27682 10300 16076 350 15905 100 - 19 22678 300 42680 150 21987 6800 44177 17000 20788 11000 22866 300 - 20 3817 600 14345 100 9762 900 19907 6300 10674 900 4523 600 - 21 17464 600 13840 100 32941 5500 49201 6300 37054 9000 5938 600 - 22 4875 600 14112 100 14915 2010 31268 10050 22053 1800 4849 600 - 23 4130 40 15137 50 13496 500 34790 2500 12156 1400 4161 40 - 24 7825 300 23672 100 4681 2300 11087 6000 7008 3100 8097 300 - 25 28440 150 29127 100 4915 1400 13257 14800 6444 2800 14424 150 - 26 4565 150 14448 100 11126 1400 27798 14800 13315 2800 4452 150 - 27 6299 200 15889 100 14942 4200 34556 21600 19438 7000 6596 500 - 28 9088 500 16889 200 9699 4200 21370 21600 10798 7000 8846 500 - 29 7437 500 15047 200 8074 4200 18767 21600 7971 7000 7314 500 - 30 18751 5500 17967 100 13853 3400 32484 17400 22128 5000 18905 5500 - 31 25492 8200 27143 150 29236 5900 50520 18200 35537 5400 32937 8200 - 32 3304522 100 709947 500 155520 32000 62761 19000 122867 7000 0 0 - 33 335486 5500 443019 1100 38832 8300 71917 27800 44012 12000 345281 5500 - 34 36499 300 16882 200 25181 2200 50206 12700 35399 3700 36389 300 - 35 207704 750 86535 100 42704 6200 73220 38000 56792 11000 210469 800 - 36 402315 6500 154811 500 39474 10400 59500 34100 47446 14000 410778 6500 - 37 566207 5000 223568 750 44610 6300 64725 31800 57072 6500 573456 5000 - 38 3738683 35000 1282525 8000 83056 3400 60908 9900 133160 3500 3782941 35000 - 39 1456916 9000 886840 50000 54759 8600 37221 13500 91830 18100 1460966 7500 - 40 38248 200 56130 250 49911 3900 34988 11800 119591 8000 38089 200 - 41 16675 3000 29481 500 34073 1500 40536 11300 33519 3900 16452 4000 - 42 256544 5000 381654 7000 33659 5000 54446 30400 45002 6500 261593 7000 - 43 4846 150 14074 100 24248 200 32913 600 25421 300 4877 150 - 44 1442666 150000 12840 100 99799 4000 26058 100 374206 15000 1102279 250000 - 45 6130 500 16468 200 31317 3500 49750 14000 29288 4000 0 0 - 46 6200 700 15646 200 14571 2600 31219 11000 18280 3200 6113 800 - 47 1671306 160000 528098 50000 39563 3000 29893 3000 73438 7000 0 0 - 48 177489 17000 264601 25000 15450 1500 40617 4000 31176 3000 194691 19000 - 49 13584 1300 16550 1600 22562 2400 48394 5200 21459 2200 14071 1300 - 50 153915 10000 544813 50000 10229 1000 17104 1000 11960 1000 173729 10000 +Test# PS1Ref# PS1Err# PDFRef# PDFErr# JPGRef# JPGErr# PNGRef# PNGErr# PS2Ref# PS2Err# + 1 529 50 12767 50 23758 3700 3937 100 569 60 + 2 4627 600 14463 100 13359 7900 9227 3000 4690 600 + 3 452 50 12694 50 11764 4200 4338 10700 492 50 + 4 23688 1500 19140 100 143676 123000 47075 11000 24979 1500 + 5 1025 150 12806 150 32266 9900 29901 5000 1072 200 + 6 432 50 12683 50 9517 150 5306 700 473 50 + 7 5015 50 13881 50 16377 1300 12462 500 5046 70 + 8 5488 80 13447 50 18439 700 12408 300 5502 80 + 9 9257 100 14317 50 20441 2400 12143 900 9377 100 + 10 8831 70 13645 100 24251 1100 23337 1700 8862 70 + 11 12967 100 14439 50 33842 2000 32100 1200 12970 150 + 12 7666 100 13497 50 83044 3000 37165 4100 7713 150 + 13 5600 400 13242 300 16868 400 15083 800 5638 400 + 14 14193187 4000000 12924 100 27112 9500 25080 3000 14193352 4000000 + 15 16185 5000 17071 200 22801 9500 14938 900 11271 5000 + 16 28087 400 23095 200 44898 11000 30209 5000 38047 400 + 17 20424 400 21328 100 27719 11000 16806 600 20704 400 + 18 15874 100 19080 100 27682 10300 16076 350 15905 100 + 19 22678 300 42680 150 44177 17000 20788 11000 22866 300 + 20 3817 600 14345 100 19907 6300 10674 900 4523 600 + 21 17464 600 13900 150 49201 6300 37054 9000 5938 600 + 22 4875 600 14112 100 31268 10050 22053 1800 4849 600 + 23 4130 40 15193 50 34790 2500 12156 1400 4161 40 + 24 7825 300 23672 100 11087 6000 7008 3100 8097 300 + 25 28440 150 29127 300 13257 14800 6444 2800 14424 150 + 26 4565 150 14448 100 27798 14800 13315 2800 4452 150 + 27 6299 200 15889 100 34556 21600 19438 7000 6596 500 + 28 9088 500 16789 400 21370 21600 10798 7000 8846 500 + 29 7437 500 15047 200 18767 21600 7971 7000 7314 500 + 30 18751 5500 17967 100 32484 17400 22128 5000 18905 5500 + 31 25492 8200 27143 400 50520 18200 35537 5400 32937 8200 + 32 3304522 100 709947 500 62761 19000 122867 7000 0 0 + 33 89233 500 47975 300 65532 27800 37314 12000 90600 500 + 34 36499 300 16882 200 50206 12700 35399 3700 36389 300 + 35 207704 750 86535 100 73220 38000 56792 11000 210469 800 + 36 402315 6500 154811 500 59500 34100 47446 14000 410778 6500 + 37 566207 5000 223568 750 64725 31800 57072 6500 573456 5000 + 38 3738683 35000 1282525 8000 60908 9900 133160 3500 3782941 35000 + 39 1456916 9000 886840 50000 37221 13500 91830 18100 1460966 7500 + 40 38248 200 56130 250 34988 11800 119591 8000 38089 200 + 41 16675 3000 29481 500 40536 11300 33519 3900 16452 4000 + 42 256544 5000 381654 7000 54446 30400 45002 6500 261593 7000 + 43 4846 150 14074 100 32913 600 25421 300 4877 150 + 44 1442666 150000 12840 100 26058 100 374206 15000 1102279 250000 + 45 6130 500 16468 200 49750 14000 29288 4000 0 0 + 46 6200 700 15646 200 31219 11000 18280 3200 6113 800 + 47 1671306 160000 528098 50000 29893 3000 73438 7000 0 0 + 48 26983 1700 18807 2500 23765 2000 11196 1000 27409 1900 + 49 13584 1300 16550 1600 48394 5200 21459 2200 14071 1300 + 50 153915 10000 544813 50000 17104 1000 11960 1000 173729 10000 diff --git a/test/stressHistFactory.cxx b/test/stressHistFactory.cxx index 626bc37b7be33..84b4bc5f51ca5 100644 --- a/test/stressHistFactory.cxx +++ b/test/stressHistFactory.cxx @@ -6,6 +6,9 @@ #include #include +// Math headers +#include "Math/MinimizerOptions.h" + // ROOT headers #include "TWebFile.h" #include "TSystem.h" @@ -39,7 +42,7 @@ using namespace RooFit ; //////////////////////////////////////////////////////////////////////////////// /// Print test program number and its title -void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth) +void StatusPrint(const int id, const TString &title, const int status, const int lineWidth) { TString header = TString::Format("Test %d : %s ", id, title.Data()); cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl; @@ -48,9 +51,9 @@ void StatusPrint(const Int_t id, const TString &title, const Int_t status, const //////////////////////////////////////////////////////////////////////////////// /// width of lines when printing test results -Int_t stressHistFactory(const char* refFile, bool writeRef, Int_t verbose, bool allTests, bool oneTest, Int_t testNumber, bool dryRun) +int stressHistFactory(const char* refFile, bool writeRef, int verbose, bool allTests, bool oneTest, int testNumber, bool dryRun) { - const Int_t lineWidth = 120; + const int lineWidth = 120; // Save memory directory location RooUnitTest::setMemDir(gDirectory) ; @@ -108,7 +111,7 @@ Int_t stressHistFactory(const char* refFile, bool writeRef, Int_t verbose, bool int nFailed = 0; { - Int_t i; + int i; list::iterator iter; if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) { @@ -181,17 +184,18 @@ Int_t stressHistFactory(const char* refFile, bool writeRef, Int_t verbose, bool int main(int argc, const char *argv[]) { bool doWrite = false; - Int_t verbose = 0; + int verbose = 0; bool allTests = false; bool oneTest = false; - Int_t testNumber = 0; + int testNumber = 0; bool dryRun = false; string refFileName = "stressHistFactory_ref.root" ; + string minimizerName = "Minuit"; // Parse command line arguments - for (Int_t i = 1 ; i < argc ; i++) { + for (int i = 1 ; i < argc ; i++) { string arg = argv[i] ; if (arg == "-f") { @@ -203,6 +207,9 @@ int main(int argc, const char *argv[]) } else if (arg == "-mc") { cout << "stressHistFactory: running in memcheck mode, no regression tests are performed" << endl; dryRun = true; + } else if (arg == "-min" || arg == "-minim") { + cout << "stressHistFactory: running using minimizer " << argv[i +1] << endl; + minimizerName = argv[++i] ; } else if (arg == "-v") { cout << "stressHistFactory: running in verbose mode" << endl; verbose = 1; @@ -219,39 +226,46 @@ int main(int argc, const char *argv[]) } else if (arg == "-d") { cout << "stressHistFactory: setting gDebug to " << argv[i + 1] << endl; gDebug = atoi(argv[++i]); - } else if (arg == "-h") { - cout << "usage: stressHistFactory [ options ] " << endl; - cout << "" << endl; - cout << " -f : use given reference file instead of default (" << refFileName << ")" << endl; - cout << " -w : write reference file, instead of reading file and running comparison tests" << endl; - cout << " -n N : only run test with sequential number N" << endl; - cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl; - cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl; - cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl; - cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; - cout << " -d N : set ROOT gDebug flag to N" << endl ; - cout << " " << endl ; + } else if (arg == "-h" || arg == "--help") { + cout << R"(usage: stressHistFactory [ options ] + + -f : use given reference file instead of default ("stressHistFactory_ref.root") + -w : write reference file, instead of reading file and running comparison tests + -n N : only run test with sequential number N + -a : run full suite of tests (default is basic suite); this overrides the -n single test option + -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind + -min : minimizer name (default is Minuit, not Minuit2) + -vs : use vector-based storage for all datasets (default is tree-based storage) + -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well) + -d N : set ROOT gDebug flag to N +)"; return 0 ; } } + // set minimizer + ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerName.c_str()); + gBenchmark = new TBenchmark(); return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun); } //////////////////////////////////////////////////////////////////////////////// -Int_t stressHistFactory() +int stressHistFactory() { bool doWrite = false; - Int_t verbose = 0; + int verbose = 0; bool allTests = false; bool oneTest = false; - Int_t testNumber = 0; + int testNumber = 0; bool dryRun = false; - string refFileName = "stressHistFactory_ref.root" ; + + // in interpreted mode, the minimizer is hardcoded to Minuit 1 + ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit"); + return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun); } diff --git a/test/stressHistFactory_tests.cxx b/test/stressHistFactory_tests.cxx index 016be27a83142..cdf42e5d95cb8 100644 --- a/test/stressHistFactory_tests.cxx +++ b/test/stressHistFactory_tests.cxx @@ -383,8 +383,8 @@ class PdfComparison : public RooUnitTest { const Int_t iSamplingPoints = 100; // get variables - RooArgSet* pVars1 = rPDF1.getVariables(); - RooArgSet* pVars2 = rPDF2.getVariables(); + std::unique_ptr pVars1{rPDF1.getVariables()}; + std::unique_ptr pVars2{rPDF2.getVariables()}; if(!CompareParameters(*pVars1,*pVars2)) { @@ -392,7 +392,7 @@ class PdfComparison : public RooUnitTest { return false; } - RooDataSet* pSamplingPoints = rPDF1.generate(rAllObservables,NumEvents(iSamplingPoints)); + std::unique_ptr pSamplingPoints{rPDF1.generate(rAllObservables,NumEvents(iSamplingPoints))}; TH1F* h_diff = new TH1F("h_diff","relative difference between both PDF;#Delta;Points / 1e-4",200,-0.01,0.01); float fPDF1value, fPDF2value; @@ -426,7 +426,6 @@ class PdfComparison : public RooUnitTest { } // clean up - delete pSamplingPoints; delete h_diff; if(!bResult) @@ -442,12 +441,12 @@ class PdfComparison : public RooUnitTest { if (gSystem->Load("libMinuit2") < 0) minimizerType = "Minuit"; gErrorIgnoreLevel=prec; - RooFitResult* r1 = rPDF1.fitTo(rTestData,Save(), RooFit::Minimizer(minimizerType.c_str())); + std::unique_ptr r1{rPDF1.fitTo(rTestData,Save(), RooFit::Minimizer(minimizerType.c_str()))}; //L.M: for minuit we need ot rest otherwise fit could fail if (minimizerType == "Minuit") { if (gMinuit) { delete gMinuit; gMinuit=0; } } - RooFitResult* r2 = rPDF2.fitTo(rTestData,Save(), RooFit::Minimizer(minimizerType.c_str())); + std::unique_ptr r2{rPDF2.fitTo(rTestData,Save(), RooFit::Minimizer(minimizerType.c_str()))}; if(_verb > 0) { diff --git a/test/stressHistoFit.cxx b/test/stressHistoFit.cxx index f7883210b768f..d99d6073e5abb 100644 --- a/test/stressHistoFit.cxx +++ b/test/stressHistoFit.cxx @@ -80,6 +80,7 @@ #include "TTree.h" #include "TF1.h" #include "TF2.h" +#include "TFile.h" #include "snprintf.h" #include "Math/IFunction.h" @@ -131,19 +132,35 @@ extern "C" { #include "Riostream.h" using namespace std; -// Next line should not exist. It is now there for testing -// pourpuses. -#undef R__HAS_MATHMORE + unsigned int __DRAW__ = 0; +unsigned int __WRITE__ = 0; // write fitted object in a file int gSelectedTest = 0; +int gSelectedFit = 0; // to select a fit in the test +int gTestIndex = 0; bool gEnableMT = kFALSE; // set a small tolerance for the tests // The default of 10*-2 make sometimes Simplex do not converge -const double gDefaultTolerance = 1.E-4; +//const double gDefaultTolerance = 1.E-4; + +// Options to indicate how the test has to be run +enum testOpt { + testOptPars = 1, // Check parameters + testOptChi = 2, // Check Chi2 Test + testOptErr = 4, // Show the failures + testOptColor = 8, // Show wrong output in color + testOptDebug = 16, // Print out debug version + testOptCheck = 32, // Make the checks + testOptFitDbg = 64, // Make fit debug (normal printout) + testOptFitVer = 128 // Make fit very verbose (option V) +}; + +// Default options that all tests will have +int defaultOptions = testOptCheck;// | testOptDebug; TRandom3 rndm; @@ -155,10 +172,20 @@ enum cmpOpts { cmpErr = 8, }; +int defCmpOpt = cmpPars | cmpChi2; + +//histogram options +const double minX = -5.; +const double maxX = +5.; +const double minY = -5.; +const double maxY = +5.; +const int nbinsX = 30; +const int nbinsY = 30; + // Reference structure to compare the fitting results struct RefValue { const double* pars; - const double chi; + double chi; RefValue(const double* p = 0, const double c = 0.0): pars(p), chi(c) {}; }; @@ -171,23 +198,23 @@ class CompareResult { int opts; double tolPar; double tolChi2; - CompareResult(int _opts = cmpPars, double _tolPar = 3, double _tolChi2 = 0.01): + CompareResult(int _opts = defCmpOpt, double _tolPar = 3, double _tolChi2 = 0.01): refValue(0), opts(_opts), tolPar(_tolPar), tolChi2(_tolChi2) {}; // use default copy-ctor and assignment operator - + void setRefValue(struct RefValue* _refValue) { refValue = _refValue; }; - int parameters(int npar, double val, double ref) const + // test parameters (use interval of tolPar*err), where err is parameter error + int parameters(int npar, double val, double err) const { int ret = 0; if ( refValue && (opts & cmpPars) ) { - ret = compareResult(val, refValue->pars[npar], tolPar*ref); -// printf("[TOL:%f]", ref); + ret = compareResult(val, refValue->pars[npar], tolPar*err); } return ret; }; @@ -196,10 +223,10 @@ class CompareResult { { return ( refValue && (opts & cmpChi2) ) ? compareResult(val, refValue->chi, tolChi2) : 0; }; public: - // Compares two doubles with a given tolerence + // Compares two doubles with a given tolerance int compareResult(double v1, double v2, double tol = 0.01) const { - if (std::abs(v1-v2) > tol ) return 1; - return 0; + if (std::abs(v1-v2) <= tol ) return 0; + return 1; } }; @@ -230,27 +257,19 @@ void FillVariableRange(Double_t v[], Int_t numberOfBins, Double_t minRange, Doub // used. class algoType { public: - const char* type; - const char* algo; - const char* opts; + TString type; + TString algo; + TString opts; CompareResult cmpResult; + bool reference = false; algoType(): type(0), algo(0), opts(0), cmpResult(0) {} algoType(const char* s1, const char* s2, const char* s3, - CompareResult _cmpResult): - type(s1), algo(s2), opts(s3), cmpResult(_cmpResult) {} + CompareResult _cmpResult, bool _ref = false): + type(s1), algo(s2), opts(s3), cmpResult(_cmpResult), reference(_ref) {} }; -// Different vectors containing the list of algorithms to be used. -vector commonAlgos; -vector simplexAlgos; -vector specialAlgos; -vector noGraphAlgos; -vector noGraphErrorAlgos; -vector graphErrorAlgos; -vector histGaus2D; -vector linearAlgos; vector< vector > listTH1DAlgos; vector< vector > listAlgosTGraph; @@ -261,6 +280,7 @@ vector< vector > listLinearAlgos; vector< vector > listTH2DAlgos; vector< vector > listAlgosTGraph2D; vector< vector > listAlgosTGraph2DError; +vector< vector > listTreeAlgos; // Class defining the limits in the parameters of a function. @@ -273,12 +293,11 @@ class ParLimit { }; // Set the limits of a function given a vector of ParLimit -void SetParsLimits(vector& v, TF1* func) +void SetParsLimits(const vector& v, TF1* func) { - for ( vector::iterator it = v.begin(); - it != v.end(); ++it ) { + for ( auto & it : v ) { // printf("Setting parameters: %d, %f, %f\n", (*it)->npar, (*it)->min, (*it)->max); - func->SetParLimits( it->npar, it->min, it->max); + func->SetParLimits( it.npar, it.min, it.max); } } @@ -379,48 +398,10 @@ double gausNd(double *x, double *p) { f *= ROOT::Math::normal_pdf(x[4],p[10],p[9]); f *= ROOT::Math::normal_pdf(x[5],p[12],p[11]); - if (f <= 0) { - std::cout << "invalid f value " << f << " for x "; - for (int i = 0; i < 6; ++i) std::cout << " " << x[i]; - std::cout << "\t P = "; - for (int i = 0; i < 11; ++i) std::cout << " " << p[i]; - std::cout << "\n\n "; - return 1.E-300; - } - else if (f > 0) return f; - - std::cout << " f is a nan " << f << std::endl; - for (int i = 0; i < 6; ++i) std::cout << " " << x[i]; - std::cout << "\t P = "; - for (int i = 0; i < 11; ++i) std::cout << " " << p[i]; - std::cout << "\n\n "; - Error("gausNd","f is a nan"); - assert(1); - return 0; + return f; } -const double minX = -5.; -const double maxX = +5.; -const double minY = -5.; -const double maxY = +5.; -const int nbinsX = 30; -const int nbinsY = 30; - -// Options to indicate how the test has to be run -enum testOpt { - testOptPars = 1, // Check parameters - testOptChi = 2, // Check Chi2 Test - testOptErr = 4, // Show the errors - testOptColor = 8, // Show wrong output in color - testOptDebug = 16, // Print out debug version - testOptCheck = 32, // Make the checkings - testOptFitDbg = 64 // Make fit verbose -}; - -// Default options that all tests will have -int defaultOptions = testOptColor | testOptCheck;// | testOptDebug; - -// Object to manage the fitter depending on the optiones used +// Object to manage the fitter depending on the options used template class ObjectWrapper { public: @@ -429,6 +410,7 @@ class ObjectWrapper { template Int_t Fit(F func, const char* opts) { +#if 0 if ( opts[0] == 'G' ) { ROOT::Fit::BinData d; @@ -457,15 +439,14 @@ class ObjectWrapper { // fitResult.Print(std::cout); return iret; } else { +#endif // printf("Normal FIT\n"); return object->Fit(func, opts); - } }; const char* GetName() { return object->GetName(); } }; // Print the Name of the test -int gTestIndex = 0; template void printTestName(T* object, TF1* func) { @@ -483,18 +464,6 @@ void printTestName(T* object, TF1* func) fflush(stdout); } -// In debug mode, prints the title of the debug table. -void printTitle(TF1* func) -{ - printf("\nMin Type | Min Algo | OPT | PARAMETERS "); - int n = func->GetNpar(); - for ( int i = 1; i < n; ++i ) { - printf(" "); - } - printf(" | CHI2TEST | ERRORS \n"); - fflush(stdout); -} - // In debug mode, separator for the different tests void printSeparator() { @@ -504,6 +473,22 @@ void printSeparator() fflush(stdout); } +// In debug mode, prints the title of the debug table. +void printTitle(TF1* func) +{ + printf(" # | Min Type | Min Algo | OPT | CHI2/Ndf | PARAMETERS "); + int n = func->GetNpar(); + for ( int i = 1; i < n; ++i ) { + printf(" "); + } + printf(" | ERRORS"); + for ( int i = 3; i < n; ++i ) { + printf(" "); + } + printf("| COMPARISONS \n"); + fflush(stdout); +} + // Sets the color of the output to red or normal void setColor(int red = 0) { @@ -525,6 +510,7 @@ void setColor(int red = 0) } // Test a fit once it has been done: +// @itest test number // @str1 Name of the library used // @str2 Name of the algorithm used // @str3 Options used when fitting @@ -532,45 +518,57 @@ void setColor(int red = 0) // @cmpResult Object to compare the result. It contains all the reference // objects as well as the method to compare. It will know whether something has to be tested or not. // @opts Options of the test, to know what has to be printed or tested. -int testFit(const char* str1, const char* str2, const char* str3, - TF1* func, CompareResult const& cmpResult, int opts) +// @isRef flag to indicate if is a reference fit +int testFit(int itest, const char* str1, const char* str2, const char* str3, + TF1* func, CompareResult const& cmpResult, int opts, bool isRef = false) { bool debug = opts & testOptDebug; // so far, status will just count the number of parameters wronly // calculated. There is no other test of the fitters - int status = 0; int diff = 0; + int statusPar = 0; + int statusChi2 = 0; + int statusErrAll = 0; double chi2 = 0; if ( opts & testOptChi || opts & testOptCheck ) chi2 = func->GetChisquare(); fflush(stdout); + + if ( debug ) + printf("%2d | %-11s | %-11s | %-4s | ", itest, str1, str2, str3); + + if ( opts & testOptChi ) + { + diff = cmpResult.chi2(chi2/func->GetNDF()); + statusChi2 += diff; + if ( debug ) + printf(" %8.6g | ", chi2/func->GetNDF()); + } else if (debug) { + printf(" | "); + } + if ( opts & testOptPars ) { int n = func->GetNpar(); double* values = func->GetParameters(); - if ( debug ) - printf("%-11s | %-11s | %-4s | ", str1, str2, str3); for ( int i = 0; i < n; ++i ) { if ( opts & testOptCheck ) + // compare parameter value with reference with tolerance = parameterError * chi2 diff = cmpResult.parameters(i, values[i], std::max(std::sqrt(chi2/func->GetNDF()),1.0)*func->GetParError(i)); - status += diff; + statusPar += diff; if ( opts & testOptColor ) setColor ( diff ); - if ( debug ) - printf("%10.6f +/-(%-6.3f) ", values[i], func->GetParError(i)); + if ( debug ) { + printf("%8.4g +/-(%5.4g) ", values[i], func->GetParError(i)); + if (itest == 0) printf(" "); //additional space for ref values + } fflush(stdout); } - setColor(0); - } - - if ( opts & testOptChi ) - { - if ( debug ) - printf(" | chi2: %9.4f | ", chi2); + if (opts & testOptColor ) setColor(0); } if ( opts & testOptErr ) @@ -580,21 +578,58 @@ int testFit(const char* str1, const char* str2, const char* str3, TBackCompFitter* fitter = dynamic_cast( TVirtualFitter::GetFitter() ); assert(fitter != 0); const ROOT::Fit::FitResult& fitResult = fitter->GetFitResult(); - if ( debug ) - printf("err: "); + if (debug) printf("| "); int n = func->GetNpar(); for ( int i = 0; i < n; ++i ) { - if ( debug ) - printf("%c ", (fitResult.LowerError(i) == fitResult.UpperError(i))?'E':'D'); + int statusErr = 0; + // check that the lower error and upper error are compatible with the parabolic error within 30% + // note that Minos returns lower error as negative + if (fitResult.HasMinosError(i)) { + statusErr += std::abs(fitResult.Error(i)+fitResult.LowerError(i)) > 0.3*fitResult.Error(i); + statusErr += 2*std::abs(fitResult.UpperError(i)-fitResult.Error(i)) > 0.3*fitResult.Error(i); + } + if ( debug ) { + if (statusErr == 0) printf("%c ",'E'); + else if (statusErr == 1) printf("%c ",'L'); + else if (statusErr == 2) printf("%c ",'U'); + else printf("%c ",'D'); + } + statusErrAll += statusErr; } if ( debug ) printf("| "); } + } else if (debug) { + printf("| "); + int n = func->GetNpar(); + for ( int i = 1; i < n; ++i ) + printf(" "); + printf("| "); + } + if (itest> 0 && debug) { + // print summary comparison + if (isRef) + printf("%c ",'R'); + else if (cmpResult.opts & cmpChi2) + printf("%d ",statusChi2); + else + printf("%c ",'-'); + // now for parameters + if (cmpResult.opts & cmpPars) + printf("%d ",statusPar); + else + printf("%c ",'-'); + // now for errors + if (opts & testOptErr ) + printf("%d |",statusErrAll); + else + printf("%c |",'-'); } + int status = statusPar+statusChi2+statusErrAll; if ( opts != 0 ) { - setColor(0); + if ( opts & testOptColor ) setColor(0); if ( debug ) printf("\n"); } @@ -609,76 +644,101 @@ int testFit(const char* str1, const char* str2, const char* str3, // @listAlgos All the algorithms that should be tested // @fitFunction Parameters of the function used to fill the object template -int testFitters(T* object, F* func, vector< vector >& listAlgos, fitFunctions const& fitFunction) +int testFitters(T* object, F* func, vector< vector >& listAlgos, fitFunctions const& fitFunction, bool variableBins = false) { // counts the number of parameters wronly calculated int status = 0; - int numberOfTests = 0; + int numberOfFits = 0; + int numberOfFailedFits = 0; const double* origpars = &(fitFunction.origPars[0]); const double* fitpars = &(fitFunction.fitPars[0]); + std::vector parSteps(func->GetNpar()); // use empty step sizes func->SetParameters(fitpars); + func->SetParErrors(parSteps.data()); + SetParsLimits(fitFunction.parLimits, func); + + // use as reference algorithm the first one in the list + auto & refAlgo = listAlgos[0][0]; printTestName(object, func); - ROOT::Math::MinimizerOptions::SetDefaultMinimizer(commonAlgos[0].type, commonAlgos[0].algo); - ROOT::Math::MinimizerOptions::SetDefaultTolerance(gDefaultTolerance); - - TString opt = ""; - if (! (defaultOptions & testOptFitDbg) ) opt += "Q"; - if (! __DRAW__) opt += "0"; - - object->Fit(func, opt); - if ( defaultOptions & testOptDebug ) printTitle(func); - struct RefValue ref(origpars, func->GetChisquare()); - commonAlgos[0].cmpResult.setRefValue(&ref); - int defMinOptions = testOptPars | testOptChi | testOptErr | defaultOptions; - status += testFit(commonAlgos[0].type, commonAlgos[0].algo - , commonAlgos[0].opts, func - , commonAlgos[0].cmpResult, defMinOptions); - numberOfTests += 1; if ( defaultOptions & testOptDebug ) { + printf("\n"); printSeparator(); func->SetParameters(origpars); - status += testFit("Parameters", "Original", "", func, commonAlgos[0].cmpResult, testOptPars | testOptDebug); + status += testFit(0,"Parameters", "Original", "", func, refAlgo.cmpResult, testOptPars | testOptDebug); func->SetParameters(fitpars); - status += testFit("Parameters", "Initial", "", func, commonAlgos[0].cmpResult, testOptPars | testOptDebug); + status += testFit(0,"Parameters", "Initial", "", func, refAlgo.cmpResult, testOptPars | testOptDebug); + printSeparator(); + printTitle(func); printSeparator(); } + RefValue ref(origpars, -1); // structure with reference values for ( unsigned int j = 0; j < listAlgos.size(); ++j ) { for ( unsigned int i = 0; i < listAlgos[j].size(); ++i ) { - int testFitOptions = testOptPars | testOptChi | testOptErr | defaultOptions; + int testFitOptions = testOptPars | testOptChi | defaultOptions; ROOT::Math::MinimizerOptions::SetDefaultMinimizer(listAlgos[j][i].type, listAlgos[j][i].algo); func->SetParameters(fitpars); + func->SetParErrors(parSteps.data()); fflush(stdout); - object->Fit(func, listAlgos[j][i].opts); - listAlgos[j][i].cmpResult.setRefValue(&ref); - status += testFit(listAlgos[j][i].type, listAlgos[j][i].algo, listAlgos[j][i].opts - , func, listAlgos[j][i].cmpResult, testFitOptions); - numberOfTests += 1; + // perform the fit: if a fit is selected use only that one (order starts from 1) + numberOfFits += 1; + //std::cout << "doing fit " << numberOfFits << std::endl; + if (gSelectedFit <= 0 || numberOfFits == gSelectedFit) { + TString opt = listAlgos[j][i].opts; + if (opt.Contains('E') && !opt.Contains("EX0")) testFitOptions |= testOptErr; + if (! (defaultOptions & testOptFitDbg) && ! (defaultOptions & testOptFitVer)) opt += "Q"; + if (! __DRAW__) opt += "0"; + if (gSelectedFit > 0 && (defaultOptions & testOptFitVer)) opt += "V"; + if (variableBins) opt += " WIDTH"; + //std::cout << "doing selected fit with option " << opt << std::endl; + // perform the fit + object->Fit(func, opt); + // if is a reference set the reference value for chi2 (parameters are compared to original ones) + if (listAlgos[j][i].reference) { + ref.chi = func->GetChisquare()/func->GetNDF(); + } + listAlgos[j][i].cmpResult.setRefValue(&ref); + // test validity of the fit and print result + int ret = testFit(numberOfFits,listAlgos[j][i].type, listAlgos[j][i].algo, listAlgos[j][i].opts, + func, listAlgos[j][i].cmpResult, testFitOptions,listAlgos[j][i].reference); + if (ret > 0) numberOfFailedFits += 1; + status += ret; + } fflush(stdout); } } - double percentageFailure = double( status * 100 ) / double( numberOfTests*func->GetNpar() ); + int totalNumberOfTests = numberOfFits; + if (defaultOptions & testOptPars) + totalNumberOfTests += (func->GetNpar()-1)*numberOfFits; + if (defaultOptions & testOptChi) + totalNumberOfTests += numberOfFits; + if (defaultOptions & testOptErr) + totalNumberOfTests += func->GetNpar()*numberOfFits; + double percentageFailure = double( status * 100 ) / double( numberOfFits*func->GetNpar() ); if ( defaultOptions & testOptDebug ) { printSeparator(); - printf("Number of fails: %d Total Number of tests %d", status, numberOfTests); + printf("Number of failed tests/total: %d / %d - Number of fit failed %d Total Number of fits %d", status, totalNumberOfTests, + numberOfFailedFits, numberOfFits); printf(" Percentage of failure: %f\n", percentageFailure ); } + else + printf("( %d/%d fits) ... ",(numberOfFits-numberOfFailedFits), numberOfFits); // limit in the percentage of failure! return (percentageFailure < 4)?0:1; } -// Test the diferent objects in 1D +// Test the different objects in 1D int test1DObjects(vector< vector >& listH, vector< vector >& listG, vector< vector >& listGE, @@ -700,19 +760,21 @@ int test1DObjects(vector< vector >& listH, { if ( func ) delete func; func = new TF1( listOfFunctions[j].name, listOfFunctions[j].func, minX, maxX, listOfFunctions[j].npars); + // set original parameter values func->SetParameters(&(listOfFunctions[j].origPars[0])); - SetParsLimits(listOfFunctions[j].parLimits, func); - // create here h1 since it is used to make TGrpahs's and THnsparse + // create here h1 since it is used to make TGraphs's and THnsparse if (h1) delete h1; h1 = new TH1D("h1", "Histogram1D Equal Bins", nbinsX, minX, maxX); - for (int i = 0; i <= h1->GetNbinsX() + 1; ++i) + rndm.SetSeed(100+gTestIndex); + + for (int i = 1; i <= h1->GetNbinsX() + 1; ++i) h1->SetBinContent(i, rndm.Poisson(func->Eval(h1->GetBinCenter(i)))); gTestIndex++; if (gSelectedTest == 0 || gSelectedTest == gTestIndex) { // fill equal bin 1D histogram - TString hname = TString::Format("H1D_%d", gTestIndex); + TString hname = "H1D_EqBins"; h1->SetName(hname); if (c1 && !__DRAW__) delete c1; @@ -729,23 +791,31 @@ int test1DObjects(vector< vector >& listH, gTestIndex++; if (gSelectedTest == 0 || gSelectedTest == gTestIndex) { // variable bin test + rndm.SetSeed(100+gTestIndex); + func->SetParameters(&(listOfFunctions[j].origPars[0])); double v[nbinsX + 1]; FillVariableRange(v, nbinsX, minX, maxX); if (h2) delete h2; - TString hname = TString::Format("H1D_%d", gTestIndex); - h2 = new TH1D(hname, "HIstogram1D Variable Bins", nbinsX, v); - for (int i = 0; i <= h2->GetNbinsX() + 1; ++i) - h2->SetBinContent(i, rndm.Poisson(func->Eval(h2->GetBinCenter(i)))); + TString hname = "H1D_VarBins"; + h2 = new TH1D(hname, "Histogram1D Variable Bins", nbinsX, v); + for (int i = 1; i <= h2->GetNbinsX(); ++i) { + double expValue = func->Integral(h2->GetXaxis()->GetBinLowEdge(i), + h2->GetXaxis()->GetBinUpEdge(i)); + h2->SetBinContent(i,rndm.Poisson(expValue)); + } if (c0 && !__DRAW__) delete c0; c0 = new TCanvas(TString::Format("c%d_H1D", gTestIndex), "Histogram1D Variable"); ObjectWrapper owh2(h2); - globalStatus += status = testFitters(&owh2, func, listH, listOfFunctions[j]); + globalStatus += status = testFitters(&owh2, func, listH, listOfFunctions[j], true); // pass flag to set var bin fits printf("%s\n", (status ? "FAILED" : "OK")); if (__DRAW__) { h2->DrawCopy(); func->DrawCopy("SAME"); } + if (__WRITE__) { + h2->Write("h1D_var"); + } } gTestIndex++; @@ -839,8 +909,9 @@ int test2DObjects(vector< vector >& listH, ge1->SetName("Graph2DErrors"); ge1->SetTitle("Graph2D with Errors"); unsigned int counter = 0; - for (int i = 0; i <= h1->GetNbinsX() + 1; ++i) { - for (int j = 0; j <= h1->GetNbinsY() + 1; ++j) { + rndm.SetSeed(100+gTestIndex); + for (int i = 1; i <= h1->GetNbinsX() ; ++i) { + for (int j = 1; j <= h1->GetNbinsY() ; ++j) { double xc = h1->GetXaxis()->GetBinCenter(i); double yc = h1->GetYaxis()->GetBinCenter(j); double content = rndm.Poisson(func->Eval(xc, yc)); @@ -855,7 +926,7 @@ int test2DObjects(vector< vector >& listH, // 2D Equal bins test gTestIndex++; if (gSelectedTest == 0 || gSelectedTest == gTestIndex) { - TString hname = TString::Format("H2D_%d", gTestIndex); + TString hname = "H2D_EqBins"; h1->SetName(hname); if ( c1 && ! __DRAW__) delete c1; c1 = new TCanvas(TString::Format("c%d_H2D", gTestIndex), "Histogram2D"); @@ -866,24 +937,31 @@ int test2DObjects(vector< vector >& listH, h1->DrawCopy("COLZ"); func->DrawCopy("SAME"); } + if (__WRITE__) { + h1->Write("h2D_eq"); + } } // 2D Variable bins test gTestIndex++; if (gSelectedTest == 0 || gSelectedTest == gTestIndex) { // fill and test 2D variable bins histograms + rndm.SetSeed(100+gTestIndex); + func->SetParameters(&(listOfFunctions[h].origPars[0])); if (h2) delete h2; double x[nbinsX + 1]; FillVariableRange(x, nbinsX, minX, maxX); double y[nbinsY + 1]; FillVariableRange(y, nbinsY, minY, maxY); - TString hname = TString::Format("H2D_%d", gTestIndex); + TString hname = "H2D_VarBins"; h2 = new TH2D(hname, "Histogram2D Variable Bins", nbinsX, x, nbinsY, y); - for (int i = 0; i <= h2->GetNbinsX() + 1; ++i) { - for (int j = 0; j <= h2->GetNbinsY() + 1; ++j) { - double xc = h2->GetXaxis()->GetBinCenter(i); - double yc = h2->GetYaxis()->GetBinCenter(j); - double content = rndm.Poisson(func->Eval(xc, yc)); + for (int i = 1; i <= h2->GetNbinsX() ; ++i) { + for (int j = 1; j <= h2->GetNbinsY() ; ++j) { + double xl = h2->GetXaxis()->GetBinLowEdge(i); + double xh = h2->GetXaxis()->GetBinUpEdge(i); + double yl = h2->GetYaxis()->GetBinLowEdge(j); + double yh = h2->GetYaxis()->GetBinUpEdge(j); + double content = rndm.Poisson(func->Integral(xl,xh,yl,yh)); h2->SetBinContent(i, j, content); } } @@ -891,12 +969,15 @@ int test2DObjects(vector< vector >& listH, if (c0 && ! __DRAW__) delete c0; c0 = new TCanvas(TString::Format("c%d_H2D", gTestIndex), "Histogram2D Variable"); ObjectWrapper owh2(h2); - globalStatus += status = testFitters(&owh2, func, listH, listOfFunctions[h]); + globalStatus += status = testFitters(&owh2, func, listH, listOfFunctions[h], true); // flag is a var bins printf("%s\n", (status ? "FAILED" : "OK")); if (__DRAW__) { h2->DrawCopy("COLZ"); func->DrawCopy("SAME"); } + if (__WRITE__) { + h2->Write("h2D_var"); + } } // TGraph 2D test @@ -940,8 +1021,15 @@ int test2DObjects(vector< vector >& listH, if (gSelectedTest == 0 || gSelectedTest == gTestIndex) { delete s1; s1 = THnSparse::CreateSparse("THnSparse2D", "THnSparse 2D", h1); ObjectWrapper ows1(s1); + // mask linear test + if (listH.size() == 1 && listH[0].size() == 1 && listH[0][0].type=="Linear") + listH[0][0].cmpResult = CompareResult(0); globalStatus += status = testFitters(&ows1, func, listH, listOfFunctions[h]); printf("%s\n", (status?"FAILED":"OK")); + if (__WRITE__) { + h1->Write("hns2D_h1"); + s1->Write("hns2D"); + } } } @@ -1003,6 +1091,7 @@ int testUnBinnedFit(int n = 10000) func->SetParameters(origPars); TUnuranMultiContDist dist(func); + rndm.SetSeed(100+gTestIndex); TUnuran unr(&rndm); // sampling with vnrou methods @@ -1019,6 +1108,7 @@ int testUnBinnedFit(int n = 10000) tree->Branch("v",&v,"v/D"); tree->Branch("w",&w,"w/D"); double xx[2]; + rndm.SetSeed(100+gTestIndex); for (Int_t i=0;i > listAlgos(2); - listAlgos[0] = commonAlgos; - listAlgos[1] = simplexAlgos; TreeWrapper tw; TF1 * f1 = 0; @@ -1049,7 +1136,7 @@ int testUnBinnedFit(int n = 10000) f1->SetParameters( &(treeFunctions[0].fitPars[0]) ); f1->FixParameter(2,1); tw.set(tree, "x", ""); - globalStatus += status = testFitters(&tw, f1, listAlgos, treeFunctions[0]); + globalStatus += status = testFitters(&tw, f1, listTreeAlgos, treeFunctions[0]); printf("%s\n", (status?"FAILED":"OK")); } @@ -1058,7 +1145,7 @@ int testUnBinnedFit(int n = 10000) //noCompareInTree.push_back(algoType( "Minuit2", "Simplex", "Q0", CompareResult(0))); vector< vector > listAlgosND(2); - listAlgosND[0] = commonAlgos; + listAlgosND[0] = listTreeAlgos[0]; // commonAlgos listAlgosND[1] = noCompareInTree; gTestIndex++; @@ -1091,117 +1178,171 @@ int testUnBinnedFit(int n = 10000) // fitting functions. void init_structures() { - commonAlgos.push_back( algoType( "Minuit", "Migrad", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "Minuit", "Minimize", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "Minuit", "Scan", "Q0X", CompareResult(0)) ); - commonAlgos.push_back( algoType( "Minuit", "Seek", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "Minuit2", "Migrad", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "Minuit2", "Minimize", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "Minuit2", "Scan", "Q0X", CompareResult(0)) ); - commonAlgos.push_back( algoType( "Minuit2", "Fumili2", "Q0X", CompareResult()) ); -#ifdef R__HAS_MATHMORE - commonAlgos.push_back( algoType( "GSLMultiMin", "conjugatefr", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "GSLMultiMin", "conjugatepr", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "GSLMultiMin", "bfgs2", "Q0X", CompareResult()) ); - commonAlgos.push_back( algoType( "GSLSimAn", "", "Q0X", CompareResult()) ); -#endif -// simplex - simplexAlgos.push_back( algoType( "Minuit", "Simplex", "Q0X", CompareResult()) ); + // Different vectors containing the list of algorithms to be used. + vector commonAlgos; + vector extraAlgos; + vector specialAlgos; + vector noGraphAlgos; + vector noGraphErrorAlgos; + vector graphErrorAlgos; + vector histGaus2D; + vector linearAlgos; + + // common Fits (apply to all) : Quite + no Graphics + chi-square + // use X for chi2 because for THnsparse default is likelihood fit instead of chi2 + commonAlgos.push_back( algoType( "Minuit2", "Migrad", "X", CompareResult(), true) ); //reference + commonAlgos.push_back( algoType( "Minuit", "Migrad", "X", CompareResult()) ); + commonAlgos.push_back( algoType( "Minuit", "Minimize", "X", CompareResult()) ); + commonAlgos.push_back( algoType( "Minuit2", "Minimize", "X", CompareResult()) ); + // extra algorithm + extraAlgos.push_back( algoType( "Minuit", "Scan", "X", CompareResult(0)) ); // mask this + //commonAlgos.push_back( algoType( "Minuit", "Seek", "X", CompareResult(defCmpOpt,5,0.1)) ); + extraAlgos.push_back( algoType( "Minuit", "Seek", "X", CompareResult(0)) ); //mask + extraAlgos.push_back( algoType( "Minuit2", "Scan", "X", CompareResult(0)) ); // mask + + extraAlgos.push_back( algoType( "Minuit", "Simplex", "X", CompareResult(cmpChi2,0,1)) ); //simplex MInuit2 does not work well (needs to be checked) - // simplexAlgos.push_back( algoType( "Minuit2", "Simplex", "Q0", CompareResult()) ); - - specialAlgos.push_back( algoType( "Minuit", "Migrad", "QE0X", CompareResult()) ); - specialAlgos.push_back( algoType( "Minuit", "Migrad", "QW0X", CompareResult()) ); - - noGraphAlgos.push_back( algoType( "Minuit", "Migrad"," Q0IX", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit", "Migrad"," QL0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit", "Migrad"," QLI0", CompareResult()) ); - - // Gradient algorithms - // No Minuit algorithms to use with the 'G' options until some stuff is fixed. - noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "GQ0", CompareResult()) ); -// noGraphAlgos.push_back( algoType( "Minuit", "Minimize", "GQ0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "GQ0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit2", "Minimize", "GQ0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Fumili", "Fumili", "GQ0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit2", "Fumili", "GQ0", CompareResult()) ); -// noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "GQE0", CompareResult()) ); - noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "GQL0", CompareResult()) ); - - noGraphErrorAlgos.push_back(algoType("Minuit2", "Fumili", "Q0", CompareResult())); - //noGraphErrorAlgos.push_back(algoType("Fumili", "Fumili", "Q0", CompareResult())); + // simplexAlgos.push_back( algoType( "Minuit2", "Simplex", "", CompareResult()) ); #ifdef R__HAS_MATHMORE - noGraphErrorAlgos.push_back( algoType( "GSLMultiFit", "", "Q0", CompareResult()) ); // Not in TGraphError + extraAlgos.push_back( algoType( "GSLMultiMin", "conjugatefr", "X", CompareResult(cmpChi2)) ); + extraAlgos.push_back( algoType( "GSLMultiMin", "conjugatepr", "X", CompareResult(cmpChi2)) ); + extraAlgos.push_back( algoType( "GSLMultiMin", "bfgs2", "X", CompareResult(cmpChi2)) ); + extraAlgos.push_back( algoType( "GSLSimAn", "", "X", CompareResult(cmpChi2,0,3.)) ); #endif - // Same as TH1D (but different comparision scheme!): commonAlgos, - histGaus2D.push_back( algoType( "Minuit", "Migrad", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit", "Minimize", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit", "Scan", "Q0", CompareResult(0)) ); - histGaus2D.push_back( algoType( "Minuit", "Seek", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit2", "Migrad", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit2", "Minimize", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit2", "Scan", "Q0", CompareResult(0)) ); - histGaus2D.push_back( algoType( "Minuit2", "Fumili2", "Q0", CompareResult(cmpPars,6)) ); + + specialAlgos.push_back( algoType( "Minuit", "Migrad", "WX", CompareResult(cmpPars)) ); + + // specific fitting options to be used when not fitting a TGraph (e.g. integral, likelihood,...) + noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "EX", CompareResult()) ); + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "EX", CompareResult()) ); + noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "L", CompareResult(defCmpOpt,3,0.1)) ); // normal binned likelihood fit + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "L", CompareResult(defCmpOpt,3,0.1)) ); + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "G", CompareResult()) ); // gradient chi2 fit + //noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "G", CompareResult()) ); // skip TMinuit with G + noGraphAlgos.push_back( algoType( "Minuit2", "Minimize", "G", CompareResult()) ); + //noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "LG", CompareResult()) ); // gradient likelihood fit + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "LG", CompareResult(defCmpOpt,3,0.1)) ); + // new reference for integral bin fits + noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "IX", CompareResult(),true) ); // chi2 fit with bin integral + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "IX", CompareResult()) ); + noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "IL", CompareResult(defCmpOpt,3,0.1)) ); // likelihood fit with bin integral + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "IL", CompareResult(defCmpOpt,3,0.1)) ); + // new reference for Pearson chi2 + noGraphAlgos.push_back( algoType( "Minuit", "Migrad", "P", CompareResult(),true) ); // Pearson chi2 fit + noGraphAlgos.push_back( algoType( "Minuit2", "Migrad", "P", CompareResult()) ); + + //specific algorithm to be used when not fitting TGraphError's + noGraphErrorAlgos.push_back(algoType("Minuit2", "Fumili", "X", CompareResult())); // chi2 fit using Fumili + noGraphErrorAlgos.push_back(algoType("Fumili", "", "X", CompareResult())); + #ifdef R__HAS_MATHMORE + noGraphErrorAlgos.push_back(algoType("GSLMultiFit", "", "X", CompareResult()) ); // Using LM from GSL + #endif + noGraphErrorAlgos.push_back( algoType("Minuit2","Fumili", "G", CompareResult(0)) ); // chi2 fit with gradient + noGraphErrorAlgos.push_back( algoType("Fumili", "", "G", CompareResult(0)) ); + //mask these Likelihood Fumili + noGraphErrorAlgos.push_back(algoType("Minuit2", "Fumili", "L", CompareResult(0)) ); // Binned likelihood fit using Fumili + noGraphErrorAlgos.push_back(algoType("Fumili", "" , "L", CompareResult(0)) ); + noGraphErrorAlgos.push_back(algoType("Minuit2", "Fumili", "LG", CompareResult(0)) ); // Binned likelihood fit using Fumili and gradient + noGraphErrorAlgos.push_back(algoType("Fumili", "" , "LG", CompareResult(0)) ); + + + // Options for TH2 fitting: same as TH1D algos (but different comparision scheme than commonAlgos and others!) + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "X", CompareResult(),true) ); + histGaus2D.push_back( algoType( "Minuit", "Migrad", "X", CompareResult()) ); + histGaus2D.push_back( algoType( "Minuit", "Minimize", "X", CompareResult(cmpPars,6)) ); + histGaus2D.push_back( algoType( "Minuit", "Scan", "X", CompareResult(0)) ); + histGaus2D.push_back( algoType( "Minuit", "Seek", "X", CompareResult(0)) ); + histGaus2D.push_back( algoType( "Minuit2", "Minimize", "X", CompareResult(cmpPars,6)) ); + histGaus2D.push_back( algoType( "Minuit2", "Scan", "X", CompareResult(0)) ); + // specialized algorithms (Fumili) + histGaus2D.push_back( algoType( "Minuit2", "Fumili", "X", CompareResult(cmpPars,6)) ); + histGaus2D.push_back( algoType( "Fumili", "" , "X", CompareResult(cmpPars,6)) ); + #ifdef R__HAS_MATHMORE - histGaus2D.push_back( algoType( "GSLMultiMin", "conjugatefr", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "GSLMultiMin", "conjugatepr", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "GSLMultiMin", "bfgs2", "Q0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "GSLSimAn", "", "Q0", CompareResult(cmpPars,6)) ); -#endif // treeFail - histGaus2D.push_back( algoType( "Minuit", "Simplex", "Q0", CompareResult(cmpPars,6)) ); + // compare only Chi2 value since parameter error is not estimated in GSLMultiMin + histGaus2D.push_back( algoType( "GSLMultiMin", "conjugatefr", "X", CompareResult(cmpChi2)) ); + histGaus2D.push_back( algoType( "GSLMultiMin", "conjugatepr", "X", CompareResult(cmpChi2)) ); + histGaus2D.push_back( algoType( "GSLMultiMin", "bfgs2", "X", CompareResult(cmpChi2)) ); + histGaus2D.push_back( algoType( "GSLSimAn", "", "X", CompareResult(cmpChi2, 0, 1.)) ); + + histGaus2D.push_back( algoType( "GSLMultiFit", "", "X", CompareResult() )); +#endif + histGaus2D.push_back( algoType( "Minuit", "Simplex", "X", CompareResult(cmpPars,6)) ); // minuit2 simplex fails in 2d - //histGaus2D.push_back( algoType( "Minuit2", "Simplex", "Q0", CompareResult(cmpPars,6)) ); + //histGaus2D.push_back( algoType( "Minuit2", "Simplex", "", CompareResult(cmpPars,6)) ); // special algos - histGaus2D.push_back( algoType( "Minuit", "Migrad", "QE0", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit", "Migrad", "QW0", CompareResult()) ); - // noGraphAlgos - histGaus2D.push_back( algoType( "Minuit", "Migrad", " Q0I", CompareResult(cmpPars,6)) ); - histGaus2D.push_back( algoType( "Minuit", "Migrad", "QL0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit", "Migrad", " QLI0", CompareResult()) ); - -// Gradient algorithms - histGaus2D.push_back( algoType( "Minuit", "Migrad", "GQ0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit", "Minimize", "GQ0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit2", "Migrad", "GQ0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit2", "Minimize", "GQ0", CompareResult()) ); - histGaus2D.push_back( algoType( "Fumili", "Fumili", "GQ0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit2", "Fumili", "GQ0", CompareResult()) ); -// histGaus2D.push_back( algoType( "Minuit", "Migrad", "GQE0", CompareResult()) ); - histGaus2D.push_back( algoType( "Minuit", "Migrad", "GQL0", CompareResult()) ); - - // noGraphErrorAlgos - histGaus2D.push_back( algoType( "Fumili", "Fumili", "Q0", CompareResult(cmpPars,6)) ); + histGaus2D.push_back( algoType( "Minuit", "Migrad", "WX", CompareResult(cmpPars)) ); + //gradient + histGaus2D.push_back( algoType( "Minuit", "Migrad", "GX", CompareResult()) ); + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "GX", CompareResult()) ); + histGaus2D.push_back( algoType( "Fumili", "" , "GX", CompareResult(0)) ); + histGaus2D.push_back( algoType( "Minuit2", "Fumili", "GX", CompareResult(0)) ); #ifdef R__HAS_MATHMORE - histGaus2D.push_back( algoType( "GSLMultiFit", "", "Q0", CompareResult(cmpPars,6)) ); + histGaus2D.push_back( algoType( "GSLMultiFit", "", "GX", CompareResult()) ); +#endif + // I - L algos + histGaus2D.push_back( algoType( "Minuit", "Migrad", "L", CompareResult(),true) ); + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "L", CompareResult()) ); + histGaus2D.push_back( algoType( "Minuit", "Migrad", "GL", CompareResult()) ); + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "GL", CompareResult()) ); +#ifdef _HAVE_NEW_FUMILI + histGaus2D.push_back( algoType( "Fumili", "" , "L", CompareResult()) ); // likelihood + histGaus2D.push_back( algoType( "Minuit2", "Fumili", "L", CompareResult()) ); + histGaus2D.push_back( algoType( "Fumili", "" , "GL", CompareResult()) ); // likelihood + histGaus2D.push_back( algoType( "Minuit2", "Fumili", "GL", CompareResult()) ); +#endif + // integral option + histGaus2D.push_back( algoType( "Minuit", "Migrad", "XI", CompareResult(),true) ); + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "XI", CompareResult()) ); + histGaus2D.push_back( algoType( "Minuit", "Migrad", "LI", CompareResult(),true) ); + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "LI", CompareResult()) ); + // P option + histGaus2D.push_back( algoType( "Minuit2", "Migrad", "P", CompareResult(),true) ); + histGaus2D.push_back( algoType( "Minuit", "Migrad", "P", CompareResult()) ); + + + // algorithms only for GraphErrors (excluding error in X) + graphErrorAlgos.push_back( algoType( "Minuit2", "Migrad", "EX0", CompareResult(),true) ); + graphErrorAlgos.push_back( algoType( "Minuit", "Migrad", "EX0", CompareResult()) ); + graphErrorAlgos.push_back( algoType( "Minuit2", "Fumili", "EX0", CompareResult()) ); + graphErrorAlgos.push_back( algoType( "Fumili", "", "EX0", CompareResult()) ); +#ifdef R__HAS_MATHMORE + graphErrorAlgos.push_back( algoType( "GSLMultiFit", "", "EX0", CompareResult(),true )); #endif - - graphErrorAlgos.push_back( algoType( "Minuit", "Migrad", "Q0EX0", CompareResult()) ); - graphErrorAlgos.push_back( algoType( "Minuit2", "Migrad", "Q0EX0", CompareResult()) ); - // For testing the linear fitter we can force the use by setting Linear the default minimizer and use // the G option. In this case the fit is linearized using the gradient as the linear components - // Option "G" has not to be set as first option character to avoid using Fitter class in - // the test program // Use option "X" to force Chi2 calculations - linearAlgos.push_back( algoType( "Linear", "", "Q0XG", CompareResult()) ); + linearAlgos.push_back( algoType( "Linear", "", "XG", CompareResult(cmpPars)) ); + linearAlgos.push_back( algoType( "Minuit2", "", "XF", CompareResult(cmpPars)) ); + + listLinearAlgos.clear(); + listTH1DAlgos.clear(); + listAlgosTGraph.clear(); + listAlgosTGraphError.clear(); + listTH2DAlgos.clear(); + listAlgosTGraph2D.clear(); + listAlgosTGraph2DError.clear(); + listLinearAlgos.push_back( linearAlgos ); + listTH1DAlgos.push_back( commonAlgos ); - listTH1DAlgos.push_back( simplexAlgos ); + listTH1DAlgos.push_back( extraAlgos ); listTH1DAlgos.push_back( specialAlgos ); - listTH1DAlgos.push_back( noGraphAlgos ); listTH1DAlgos.push_back( noGraphErrorAlgos ); + listTH1DAlgos.push_back( noGraphAlgos ); + listAlgosTGraph.push_back( commonAlgos ); - listAlgosTGraph.push_back( simplexAlgos ); + listAlgosTGraph.push_back( extraAlgos ); listAlgosTGraph.push_back( specialAlgos ); listAlgosTGraph.push_back( noGraphErrorAlgos ); listAlgosTGraphError.push_back( commonAlgos ); - listAlgosTGraphError.push_back( simplexAlgos ); + listAlgosTGraphError.push_back( extraAlgos ); listAlgosTGraphError.push_back( specialAlgos ); listAlgosTGraphError.push_back( graphErrorAlgos ); @@ -1215,7 +1356,15 @@ void init_structures() listAlgosTGraph2DError.push_back( specialAlgos ); listAlgosTGraph2DError.push_back( graphErrorAlgos ); + listTreeAlgos.clear(); + listTreeAlgos.push_back(commonAlgos); + vector emptyLimits(0); + l1DFunctions.clear(); + l2DFunctions.clear(); + treeFunctions.clear(); + l1DLinearFunctions.clear(); + l2DLinearFunctions.clear(); double gausOrig[] = { 0., 3., 200.}; double gausFit[] = {0.5, 3.7, 250.}; @@ -1223,12 +1372,13 @@ void init_structures() gaus1DLimits.push_back( ParLimit(1, 0, 5) ); l1DFunctions.push_back( fitFunctions("GAUS", gaus1DImpl, 3, gausOrig, gausFit, gaus1DLimits) ); double poly1DOrig[] = { 2, 3, 4, 200}; - double poly1DFit[] = { 6.4, -2.3, 15.4, 210.5}; + //double poly1DFit[] = { 6.4, -2.3, 15.4, 210.5}; + double poly1DFit[] = {6., -1., 15., 300.}; l1DFunctions.push_back( fitFunctions("Polynomial", poly1DImpl, 4, poly1DOrig, poly1DFit, emptyLimits) ); // range os -5,5 - double gaus2DOrig[] = { 500., +.5, 2.7, -.5, 3.0 }; - double gaus2DFit[] = { 510., .0, 1.8, -1.0, 1.6}; + double gaus2DOrig[] = { 900., +.5, 2.7, -.5, 3.0 }; + double gaus2DFit[] = { 1200., .0, 1.8, -1.0, 1.6}; l2DFunctions.push_back( fitFunctions("gaus2D", gaus2DImpl, 5, gaus2DOrig, gaus2DFit, emptyLimits) ); double gausnOrig[3] = {1,2,1}; @@ -1240,8 +1390,8 @@ void init_structures() l1DLinearFunctions.push_back( fitFunctions("Polynomial", poly1DImpl, 4, poly1DOrig, poly1DFit, emptyLimits) ); - double poly2DOrig[] = { 2, 3, 4, 5, 6, 7, 200, }; - double poly2DFit[] = { 6.4, -2.3, 15.4, 3, 10, -3, 210.5}; + double poly2DOrig[] = { 2, 3, 4, 5, 6, 7, 700, }; + double poly2DFit[] = { 6.4, -2.3, 15.4, 3, 10, -3, 1000}; l2DLinearFunctions.push_back( fitFunctions("Poly2D", poly2DImpl, 7, poly2DOrig, poly2DFit, emptyLimits) ); } @@ -1256,6 +1406,11 @@ int stressHistoFit() init_structures(); int iret = 0; + gTestIndex = 0; + + TFile * fout = nullptr; + if (__WRITE__) + fout = TFile::Open("stressHistoFit.root","RECREATE"); TBenchmark bm; bm.Start("stressHistoFit"); @@ -1285,6 +1440,11 @@ int stressHistoFit() << gROOT->GetGitBranch() << "@" << gROOT->GetGitCommit() << std::endl; std::cout <<"****************************************************************************\n"; + if (__WRITE__) { + fout->Close(); + delete fout; + } + return iret; } @@ -1295,7 +1455,10 @@ int main(int argc, char** argv) Int_t verbose = 0; Int_t testNumber = 0; + Int_t fitNumber = 0; Bool_t doDraw = kFALSE; + Bool_t doWrite = kFALSE; + // Parse command line arguments for (Int_t i = 1 ; i < argc ; i++) { @@ -1308,42 +1471,54 @@ int main(int argc, char** argv) } else if (arg == "-vv") { cout << "stressHistoFit: running in very verbose mode" << endl; verbose = 2; + } else if (arg == "-vvv") { + cout << "stressHistoFit: running in very very verbose mode" << endl; + verbose = 3; } else if (arg == "-a") { cout << "stressHistoFit: deploying full suite of tests" << endl; } else if (arg == "-n") { cout << "stressHistoFit: running single test" << endl; - testNumber = atoi(argv[++i]); + if (argc > i+1) testNumber = atoi(argv[++i]); + if (argc > i+1) fitNumber = atoi(argv[++i]); + if (verbose==0) verbose=1; } else if (arg == "-d") { cout << "stressHistoFit: setting gDebug to " << argv[i + 1] << endl; gDebug = atoi(argv[++i]); } else if (arg == "-g") { cout << "stressHistoFit: running in graphics mode " << endl; doDraw = kTRUE; + } else if (arg == "-s") { + cout << "stressHistoFit: save results in stressHistoFit.root " << endl; + doWrite = kTRUE; } else if (arg == "-t") { cout << "stressHistoFit: running in multi-thread mode " << endl; gEnableMT = kTRUE; } else if (arg == "-h") { cout << "usage: stressHistoFit [ options ] " << endl; cout << "" << endl; - cout << " -n N : only run test with sequential number N" << endl; + cout << " -n N M : only run test with sequential number N and fit M" << endl; cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl; cout << " -g : create a TApplication and produce plots" << endl; - cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; - cout << " -d N : set ROOT gDebug flag to N" << endl ; - cout << " -t : set ROOT to run in Multi-thread mode" << endl; + cout << " -s : save fit results in a output ROOT file" << endl; + cout << " -v/-vv/-vvv: set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; + cout << " -d N : set ROOT gDebug flag to N" << endl ; + cout << " -t : set ROOT to run in Multi-thread mode" << endl; cout << " " << endl ; return 0 ; } } - __DRAW__ = ( doDraw || verbose == 2); + __DRAW__ = ( doDraw || verbose >= 2); + __WRITE__ = (doWrite); if (verbose > 0) { defaultOptions |= testOptDebug; // debug mode (print test results) if (verbose > 1) defaultOptions |= testOptFitDbg; // very debug (print also fit outputs) + if (verbose > 1) defaultOptions |= testOptFitVer; } gSelectedTest = testNumber; // number of selected test + gSelectedFit = fitNumber; if ( __DRAW__ ) theApp = new TApplication("App",&argc,argv); diff --git a/test/stressMathMore.cxx b/test/stressMathMore.cxx index ca4d1e8e5f7d4..8669f08469e3a 100644 --- a/test/stressMathMore.cxx +++ b/test/stressMathMore.cxx @@ -469,10 +469,12 @@ int testGammaFunction(int n = 100) { PrintStatus(ret); iret |= ret; +#if !defined(_MSC_VER) || !defined(__CLING__) || defined(R__ENABLE_BROKEN_WIN_TESTS) PrintTest("\t test inverse with Steffenson algo"); ret = dist.TestInverse2(RootFinder::kGSL_STEFFENSON); PrintStatus(ret); iret |= ret; +#endif PrintTest("\t test inverse with Brent method"); ret = dist.TestInverse1(RootFinder::kBRENT); @@ -534,12 +536,14 @@ int testBetaFunction(int n = 100) { PrintStatus(ret); iret |= ret; +#if !defined(_MSC_VER) || !defined(__CLING__) || defined(R__ENABLE_BROKEN_WIN_TESTS) if (i < 5) { // test failed for k=5 PrintTest("\t test inverse with Steffenson algo"); ret = dist.TestInverse2(RootFinder::kGSL_STEFFENSON); PrintStatus(ret); iret |= ret; } +#endif } return iret; diff --git a/test/stressRooFit.cxx b/test/stressRooFit.cxx index 7fa5505e906f8..056eb2db0168f 100644 --- a/test/stressRooFit.cxx +++ b/test/stressRooFit.cxx @@ -6,6 +6,8 @@ #include "RooRandom.h" #include "RooTrace.h" +#include "Math/MinimizerOptions.h" + #include "TWebFile.h" #include "TSystem.h" #include "TString.h" @@ -31,19 +33,19 @@ using namespace RooFit ; // // //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*_*// -Int_t stressRooFit(const char* refFile, bool writeRef, Int_t doVerbose, Int_t oneTest, bool dryRun) ; +int stressRooFit(const char* refFile, bool writeRef, int doVerbose, int oneTest, bool dryRun) ; //////////////////////////////////////////////////////////////////////////////// /// Print test program number and its title -void StatusPrint(Int_t id,const TString &title,Int_t status) +void StatusPrint(int id,const TString &title,int status) { - const Int_t kMAX = 65; + const int kMAX = 65; Char_t number[4]; snprintf(number, 4, "%2d", id); TString header = TString("Test ")+number+" : "+title; - const Int_t nch = header.Length(); - for (Int_t i = nch; i < kMAX; i++) header += '.'; + const int nch = header.Length(); + for (int i = nch; i < kMAX; i++) header += '.'; cout << header << (status>0 ? "OK" : (status<0 ? "SKIPPED" : "FAILED")) << endl; } @@ -52,9 +54,9 @@ void StatusPrint(Int_t id,const TString &title,Int_t status) //////////////////////////////////////////////////////////////////////////////// -Int_t stressRooFit(const char* refFile, bool writeRef, Int_t doVerbose, Int_t oneTest, bool dryRun, bool doDump, bool doTreeStore, std::string const& batchMode) +int stressRooFit(const char* refFile, bool writeRef, int doVerbose, int oneTest, bool dryRun, bool doDump, bool doTreeStore) { - Int_t retVal = 0; + int retVal = 0; // Save memory directory location RooUnitTest::setMemDir(gDirectory) ; @@ -102,62 +104,62 @@ Int_t stressRooFit(const char* refFile, bool writeRef, Int_t doVerbose, Int_t on timer.Start(); list testList ; - testList.push_back(new TestBasic101(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic102(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic103(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic105(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic108(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic109(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic110(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic111(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic201(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic202(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic203(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic204(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic205(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic208(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic209(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic301(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic302(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic303(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic304(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic305(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic306(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic307(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic308(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic310(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic311(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic312(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic313(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic315(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic314(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic316(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic402(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic403(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic404(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic405(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic406(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic501(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic599(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic601(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic602(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic604(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic605(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic606(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic607(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic609(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic701(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic702(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic703(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic704(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic705(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic706(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic707(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic708(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic801(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic802(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic803(fref,writeRef,doVerbose,batchMode)) ; - testList.push_back(new TestBasic804(fref,writeRef,doVerbose,batchMode)) ; + testList.push_back(new TestBasic101(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic102(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic103(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic105(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic108(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic109(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic110(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic111(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic201(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic202(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic203(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic204(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic205(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic208(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic209(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic301(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic302(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic303(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic304(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic305(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic306(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic307(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic308(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic310(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic311(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic312(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic313(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic315(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic314(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic316(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic402(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic403(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic404(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic405(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic406(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic501(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic599(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic601(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic602(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic604(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic605(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic606(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic607(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic609(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic701(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic702(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic703(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic704(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic705(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic706(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic707(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic708(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic801(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic802(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic803(fref,writeRef,doVerbose)) ; + testList.push_back(new TestBasic804(fref,writeRef,doVerbose)) ; cout << "* Starting S T R E S S basic suite *" <Start("StressRooFit"); - Int_t i(1) ; + int i(1) ; for (list::iterator iter = testList.begin () ; iter != testList.end() ; ++iter) { if (oneTest<0 || oneTest==i) { if (doDump) { (*iter)->setDebug(true) ; } - Int_t status = (*iter)->isTestAvailable()?(*iter)->runTest():-1; + int status = (*iter)->isTestAvailable()?(*iter)->runTest():-1; StatusPrint( i,(*iter)->GetName(), status); // increment retVal for every failed test if (!status) ++retVal; @@ -241,97 +243,81 @@ Int_t stressRooFit(const char* refFile, bool writeRef, Int_t doVerbose, Int_t on int main(int argc,const char *argv[]) { bool doWrite = false ; - Int_t doVerbose = 0 ; - Int_t oneTest = -1 ; - Int_t dryRun = false ; + int doVerbose = 0 ; + int oneTest = -1 ; + int dryRun = false ; bool doDump = false ; bool doTreeStore = false ; - std::string batchMode = "off"; + auto backend = RooFit::EvalBackend::Legacy(); //string refFileName = "http://root.cern.ch/files/stressRooFit_v534_ref.root" ; string refFileName = "stressRooFit_ref.root" ; + string minimizerName = "Minuit"; + + auto verbosityOptionErrorMsg = "Multiple verbosity-related options have been passed to stressRooFit! The options -v, -vv, and -q are mutually exclusive."; // Parse command line arguments - for (Int_t i=1 ; i : Perform every fit in the tests with the BatchMode() command argument, where is a string" << endl ; - cout << " -f : use given reference file instead of default (" << refFileName << ")" << endl ; - cout << " -w : write reference file, instead of reading file and running comparison tests" << endl ; - cout << " " << endl ; - cout << " -n N : Only run test with sequential number N instead of full suite of tests" << endl ; - cout << " -c : dump file stressRooFit_DEBUG.root to which results of both current result and reference for each failed test are written" << endl ; - cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl ; - cout << " -vs : Use vector-based storage for all datasets (default is tree-based storage)" << endl ; - cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl ; - cout << " -q : quiet mode where errors are not logged" << endl ; - cout << " -d N : set ROOT gDebug flag to N" << endl ; - cout << " " << endl ; + cout << R"(usage: stressRooFit [ options ] + + -b : Perform every fit in the tests with the EvalBackend() command argument, where is a string + -f : use given reference file instead of default ("stressRooFit_ref.root") + -w : write reference file, instead of reading file and running comparison tests + + -n N : Only run test with sequential number N instead of full suite of tests + -c : dump file stressRooFit_DEBUG.root to which results of both current result and reference for each failed test are written + -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind + -min : minimizer name (default is Minuit, not Minuit2) + -vs : Use vector-based storage for all datasets (default is tree-based storage) + -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well) + -q : quiet mode where errors are not logged + -d N : set ROOT gDebug flag to N +)"; return 0 ; } @@ -352,26 +338,34 @@ int main(int argc,const char *argv[]) cout << "stressRooFit: WARNING running in write mode, but reference file is web file, writing local file instead: " << refFileName << endl ; } + // set minimizer + ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerName.c_str()); + + // set default BatchMode backend + RooFit::EvalBackend::defaultValue() = backend.value(); + gBenchmark = new TBenchmark(); - Int_t retVal = stressRooFit(refFileName.c_str(),doWrite,doVerbose,oneTest,dryRun,doDump,doTreeStore,batchMode); + int retVal = stressRooFit(refFileName.c_str(),doWrite,doVerbose,oneTest,dryRun,doDump,doTreeStore); return retVal; } //////////////////////////////////////////////////////////////////////////////// -Int_t stressRooFit() +int stressRooFit() { bool doWrite = false ; - Int_t doVerbose = 0 ; - Int_t oneTest = -1 ; - Int_t dryRun = false ; + int doVerbose = 0 ; + int oneTest = -1 ; + int dryRun = false ; bool doDump = false ; bool doTreeStore = false ; - std::string batchMode = "off"; - //string refFileName = "http://root.cern.ch/files/stressRooFit_v534_ref.root" ; string refFileName = "stressRooFit_ref.root" ; - return stressRooFit(refFileName.c_str(),doWrite,doVerbose,oneTest,dryRun,doDump,doTreeStore,batchMode); + + // in interpreted mode, the minimizer is hardcoded to Minuit 1 + ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit"); + + return stressRooFit(refFileName.c_str(),doWrite,doVerbose,oneTest,dryRun,doDump,doTreeStore); } #endif diff --git a/test/stressRooFit_ref.root b/test/stressRooFit_ref.root index 4b8e1e33c24aa..dd99118d06673 100644 Binary files a/test/stressRooFit_ref.root and b/test/stressRooFit_ref.root differ diff --git a/test/stressRooFit_tests.h b/test/stressRooFit_tests.h index 73905d6c6e6c2..b751f1c748889 100644 --- a/test/stressRooFit_tests.h +++ b/test/stressRooFit_tests.h @@ -101,7 +101,7 @@ using namespace RooFit ; class TestBasic101 : public RooUnitTest { public: - TestBasic101(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Fitting,plotting & event generation of basic p.d.f",refFile,writeRef,verbose,batchMode) {} ; + TestBasic101(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Fitting,plotting & event generation of basic p.d.f",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -149,7 +149,7 @@ class TestBasic101 : public RooUnitTest // ----------------------------- // Fit pdf to data - gauss.fitTo(*data,BatchMode(_batchMode)) ; + gauss.fitTo(*data) ; // --- Post processing for stressRooFit --- @@ -177,7 +177,7 @@ class TestBasic101 : public RooUnitTest class TestBasic102 : public RooUnitTest { public: - TestBasic102(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Data import methods",refFile,writeRef,verbose,batchMode) {} ; + TestBasic102(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Data import methods",refFile,writeRef,verbose) {} ; std::unique_ptr makeTH1() { @@ -196,8 +196,8 @@ class TestBasic102 : public RooUnitTest // Create ROOT TTree filled with a Gaussian distribution in x and a uniform distribution in y auto tree = std::make_unique("tree","tree"); - Double_t* px = new Double_t ; - Double_t* py = new Double_t ; + double* px = new double ; + double* py = new double ; tree->Branch("x",px,"x/D") ; tree->Branch("y",py,"y/D") ; for (int i=0 ; i<100 ; i++) { @@ -242,7 +242,7 @@ class TestBasic102 : public RooUnitTest RooRealVar mean("mean","mean",0,-10,10) ; RooRealVar sigma("sigma","sigma",3,0.1,10) ; RooGaussian gauss("gauss","gauss",x,mean,sigma) ; - gauss.fitTo(dh,BatchMode(_batchMode)) ; + gauss.fitTo(dh) ; gauss.plotOn(frame) ; // P l o t a n d f i t a R o o D a t a H i s t w i t h i n t e r n a l e r r o r s @@ -329,7 +329,7 @@ class TestBasic102 : public RooUnitTest class TestBasic103 : public RooUnitTest { public: - TestBasic103(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Interpreted expression p.d.f.",refFile,writeRef,verbose,batchMode) {} ; + TestBasic103(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Interpreted expression p.d.f.",refFile,writeRef,verbose) {} ; bool testCode() { ///////////////////////////////////////////////////////// @@ -356,7 +356,7 @@ class TestBasic103 : public RooUnitTest std::unique_ptr data{genpdf.generate(x,10000)}; // Fit the interpreted p.d.f to the generated data - genpdf.fitTo(*data,BatchMode(_batchMode)) ; + genpdf.fitTo(*data) ; // Make a plot of the data and the p.d.f overlaid RooPlot* xframe = x.frame(Title("Interpreted expression pdf")) ; @@ -390,7 +390,7 @@ class TestBasic103 : public RooUnitTest // --------------------------------- // Construct a separate gaussian g1(x,10,3) to generate a toy Gaussian dataset with mean 10 and width 3 - RooGaussian g1("g1","g1",x,RooConst(10),RooConst(3)) ; + RooGaussian g1("g1","g1",x,10.0,3.0) ; std::unique_ptr data2{g1.generate(x,1000)}; @@ -398,7 +398,7 @@ class TestBasic103 : public RooUnitTest // ------------------------------------------------------------------- // Fit g2 to data from g1 - RooFitResult* r = g2.fitTo(*data2,Save(),BatchMode(_batchMode)) ; + std::unique_ptr r{g2.fitTo(*data2,Save())}; // Plot data on frame and overlay projection of g2 RooPlot* xframe2 = x.frame(Title("Tailored Gaussian pdf")) ; @@ -407,7 +407,7 @@ class TestBasic103 : public RooUnitTest regPlot(xframe,"rf103_plot1") ; regPlot(xframe2,"rf103_plot2") ; - regResult(r,"rf103_fit1") ; + regResult(std::move(r),"rf103_fit1") ; return true ; } @@ -427,7 +427,7 @@ class TestBasic103 : public RooUnitTest class TestBasic105 : public RooUnitTest { public: - TestBasic105(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("C++ function binding operator p.d.f",refFile,writeRef,verbose,batchMode) {} ; + TestBasic105(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("C++ function binding operator p.d.f",refFile,writeRef,verbose) {} ; bool testCode() { // B i n d T M a t h : : E r f C f u n c t i o n @@ -455,7 +455,7 @@ class TestBasic105 : public RooUnitTest // Generate some events and fit std::unique_ptr data{beta->generate(x2,10000)}; - beta->fitTo(*data,BatchMode(_batchMode)) ; + beta->fitTo(*data) ; // Plot data and pdf on frame RooPlot* frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf")) ; @@ -503,7 +503,7 @@ class TestBasic105 : public RooUnitTest class TestBasic108 : public RooUnitTest { public: - TestBasic108(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Non-standard binning in counting and asymmetry plots",refFile,writeRef,verbose,batchMode) {} ; + TestBasic108(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Non-standard binning in counting and asymmetry plots",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -619,7 +619,7 @@ class TestBasic108 : public RooUnitTest class TestBasic109 : public RooUnitTest { public: - TestBasic109(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Calculation of chi^2 and residuals in plots",refFile,writeRef,verbose,batchMode) {} ; + TestBasic109(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Calculation of chi^2 and residuals in plots",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -631,7 +631,7 @@ class TestBasic109 : public RooUnitTest // Create Gaussian RooRealVar sigma("sigma","sigma",3,0.1,10) ; RooRealVar mean("mean","mean",0,-10,10) ; - RooGaussian gauss("gauss","gauss",x,RooConst(0),sigma) ; + RooGaussian gauss("gauss","gauss",x,0.0,sigma) ; // Generate a sample of 1000 events with sigma=3 std::unique_ptr data{gauss.generate(x,10000)}; @@ -704,7 +704,7 @@ class TestBasic109 : public RooUnitTest class TestBasic110 : public RooUnitTest { public: - TestBasic110(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Normalization of p.d.f.s in 1D",refFile,writeRef,verbose,batchMode) {} ; + TestBasic110(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Normalization of p.d.f.s in 1D",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -714,7 +714,7 @@ class TestBasic110 : public RooUnitTest RooRealVar x("x","x",-10,10) ; // Create p.d.f. gaussx(x,-2,3) - RooGaussian gx("gx","gx",x,RooConst(-2),RooConst(3)) ; + RooGaussian gx("gx","gx",x,-2.0,3.0) ; // R e t r i e v e r a w & n o r m a l i z e d v a l u e s o f R o o F i t p . d . f . s @@ -782,7 +782,7 @@ class TestBasic110 : public RooUnitTest class TestBasic111 : public RooUnitTest { public: - TestBasic111(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Numeric integration configuration",refFile,writeRef,verbose,batchMode) {} ; + TestBasic111(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Numeric integration configuration",refFile,writeRef,verbose) {} ; bool testCode() { // A d j u s t g l o b a l 1 D i n t e g r a t i o n p r e c i s i o n @@ -806,14 +806,16 @@ class TestBasic111 : public RooUnitTest // N u m e r i c i n t e g r a t i o n o f l a n d a u p d f // ------------------------------------------------------------------ - // Construct p.d.f without support for analytical integrator for demonstration purposes RooRealVar x("x","x",-10,10) ; - RooLandau landau("landau","landau",x,RooConst(0),RooConst(0.1)) ; + RooLandau landau("landau","landau",x,0.0,0.1) ; + + // Disable analytic integration from demonstration purposes + landau.forceNumInt(true); // Calculate integral over landau with default choice of numeric integrator std::unique_ptr intLandau{landau.createIntegral(x)}; - Double_t val = intLandau->getVal() ; + double val = intLandau->getVal() ; regValue(val,"rf111_val1") ; @@ -830,7 +832,7 @@ class TestBasic111 : public RooUnitTest // Calculate integral over landau with custom integral specification std::unique_ptr intLandau2{landau.createIntegral(x,NumIntConfig(customConfig))}; - Double_t val2 = intLandau2->getVal() ; + double val2 = intLandau2->getVal() ; regValue(val2,"rf111_val2") ; @@ -844,7 +846,7 @@ class TestBasic111 : public RooUnitTest // Calculate integral over landau custom numeric integrator specified as object default std::unique_ptr intLandau3{landau.createIntegral(x)}; - Double_t val3 = intLandau3->getVal() ; + double val3 = intLandau3->getVal() ; regValue(val3,"rf111_val3") ; @@ -868,7 +870,7 @@ class TestBasic111 : public RooUnitTest class TestBasic201 : public RooUnitTest { public: - TestBasic201(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Addition operator p.d.f.",refFile,writeRef,verbose,batchMode) {} ; + TestBasic201(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Addition operator p.d.f.",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o n e n t p d f s @@ -919,7 +921,7 @@ class TestBasic201 : public RooUnitTest std::unique_ptr data{model.generate(x,1000)}; // Fit model to data - model.fitTo(*data,BatchMode(_batchMode)) ; + model.fitTo(*data) ; // Plot data and PDF overlaid RooPlot* xframe = x.frame(Title("Example of composite pdf=(sig1+sig2)+bkg")) ; @@ -981,7 +983,7 @@ class TestBasic201 : public RooUnitTest class TestBasic202 : public RooUnitTest { public: - TestBasic202(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Extended ML fits to addition operator p.d.f.s",refFile,writeRef,verbose,batchMode) {} ; + TestBasic202(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Extended ML fits to addition operator p.d.f.s",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o n e n t p d f s @@ -1030,7 +1032,7 @@ class TestBasic202 : public RooUnitTest std::unique_ptr data{model.generate(x)}; // Fit model to data, extended ML term automatically included - model.fitTo(*data,BatchMode(_batchMode)) ; + model.fitTo(*data) ; // Plot data and PDF overlaid, use expected number of events for p.d.f projection normalization // rather than observed number of events (==data->numEntries()) @@ -1086,7 +1088,7 @@ class TestBasic202 : public RooUnitTest class TestBasic203 : public RooUnitTest { public: - TestBasic203(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Basic fitting and plotting in ranges",refFile,writeRef,verbose,batchMode) {} ; + TestBasic203(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Basic fitting and plotting in ranges",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -1097,7 +1099,7 @@ class TestBasic203 : public RooUnitTest // Construct gaussx(x,mx,1) RooRealVar mx("mx","mx",0,-10,10) ; - RooGaussian gx("gx","gx",x,mx,RooConst(1)) ; + RooGaussian gx("gx","gx",x,mx,1.0) ; // Construct px = 1 (flat in x) RooPolynomial px("px","px",x) ; @@ -1113,7 +1115,7 @@ class TestBasic203 : public RooUnitTest // --------------------------- // Fit p.d.f to all data - RooFitResult* r_full = model.fitTo(*modelData,Save(true),BatchMode(_batchMode)) ; + std::unique_ptr r_full{model.fitTo(*modelData,Save(true))}; // F i t p a r t i a l r a n g e @@ -1123,7 +1125,7 @@ class TestBasic203 : public RooUnitTest x.setRange("signal",-3,3) ; // Fit p.d.f only to data in "signal" range - RooFitResult* r_sig = model.fitTo(*modelData,Save(true),Range("signal"),BatchMode(_batchMode)) ; + std::unique_ptr r_sig{model.fitTo(*modelData,Save(true),Range("signal"))}; // P l o t / p r i n t r e s u l t s @@ -1136,8 +1138,8 @@ class TestBasic203 : public RooUnitTest model.plotOn(frame) ; // By default only fitted range is shown regPlot(frame,"rf203_plot") ; - regResult(r_full,"rf203_r_full") ; - regResult(r_sig,"rf203_r_sig") ; + regResult(std::move(r_full),"rf203_r_full") ; + regResult(std::move(r_sig),"rf203_r_sig") ; return true; } @@ -1159,7 +1161,7 @@ class TestBasic203 : public RooUnitTest class TestBasic204 : public RooUnitTest { public: - TestBasic204(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Extended ML fit in sub range",refFile,writeRef,verbose,batchMode) {} ; + TestBasic204(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Extended ML fit in sub range",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o n e n t p d f s @@ -1214,10 +1216,10 @@ class TestBasic204 : public RooUnitTest // Perform unbinned extended ML fit to data - RooFitResult* r = model.fitTo(*data,Extended(true),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r{model.fitTo(*data,Extended(true),Save())}; - regResult(r,"rf204_result") ; + regResult(std::move(r),"rf204_result") ; return true ; } @@ -1238,7 +1240,7 @@ class TestBasic204 : public RooUnitTest class TestBasic205 : public RooUnitTest { public: - TestBasic205(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Component plotting variations",refFile,writeRef,verbose,batchMode) {} ; + TestBasic205(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Component plotting variations",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o s i t e p d f @@ -1264,16 +1266,16 @@ class TestBasic205 : public RooUnitTest RooChebychev bkg1("bkg1","Background 1",x,RooArgSet(a0,a1)) ; // Build expontential pdf - RooRealVar alpha("alpha","alpha",-1) ; - RooExponential bkg2("bkg2","Background 2",x,alpha) ; + RooRealVar alpha("alpha","alpha", 1) ; + RooExponential bkg2("bkg2","Background 2",x,alpha, true); // Sum the background components into a composite background p.d.f. - RooRealVar bkg1frac("sig1frac","fraction of component 1 in background",0.2,0.,1.) ; - RooAddPdf bkg("bkg","Signal",RooArgList(bkg1,bkg2),sig1frac) ; + RooRealVar bkg1frac("bkg1frac","fraction of component 1 in background",0.8,0.,1.) ; + RooAddPdf bkg("bkg", "Total background", {bkg1,bkg2}, bkg1frac); // Sum the composite signal and background RooRealVar bkgfrac("bkgfrac","fraction of background",0.5,0.,1.) ; - RooAddPdf model("model","g1+g2+a",RooArgList(bkg,sig),bkgfrac) ; + RooAddPdf model("model", "g1+g2+a", {bkg,sig}, bkgfrac); @@ -1350,7 +1352,7 @@ class TestBasic205 : public RooUnitTest class TestBasic208 : public RooUnitTest { public: - TestBasic208(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("FFT Convolution operator p.d.f.",refFile,writeRef,verbose,batchMode) {} ; + TestBasic208(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("FFT Convolution operator p.d.f.",refFile,writeRef,verbose) {} ; bool isTestAvailable() { // only if ROOT was build with fftw3 enabled @@ -1369,7 +1371,7 @@ class TestBasic208 : public RooUnitTest return false ; } - Double_t ctol() { return 1e-2 ; } // Account for difficult shape of Landau distribution + double ctol() { return 1e-2 ; } // Account for difficult shape of Landau distribution bool testCode() { @@ -1410,7 +1412,7 @@ class TestBasic208 : public RooUnitTest { // Get rid of the caching info prints RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::Caching, true}; - lxg.fitTo(*data,BatchMode(_batchMode)) ; + lxg.fitTo(*data) ; } // Plot data, landau pdf, landau (X) gauss pdf @@ -1449,7 +1451,7 @@ class TestBasic208 : public RooUnitTest class TestBasic209 : public RooUnitTest { public: - TestBasic209(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Analytical convolution operator",refFile,writeRef,verbose,batchMode) {} ; + TestBasic209(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Analytical convolution operator",refFile,writeRef,verbose) {} ; bool testCode() { // B - p h y s i c s p d f w i t h t r u t h r e s o l u t i o n @@ -1527,7 +1529,7 @@ class TestBasic209 : public RooUnitTest class TestBasic301 : public RooUnitTest { public: - TestBasic301(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Composition extension of basic p.d.f",refFile,writeRef,verbose,batchMode) {} ; + TestBasic301(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Composition extension of basic p.d.f",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o s e d m o d e l g a u s s ( x , m ( y ) , s ) @@ -1593,7 +1595,7 @@ class TestBasic301 : public RooUnitTest class TestBasic302 : public RooUnitTest { public: - TestBasic302(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Sum and product utility functions",refFile,writeRef,verbose,batchMode) {} ; + TestBasic302(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Sum and product utility functions",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e o b s e r v a b l e s , p a r a m e t e r s @@ -1701,8 +1703,8 @@ RooDataSet* makeFakeDataXY() RooDataSet* d = new RooDataSet("d","d",RooArgSet(x,y)) ; for (int i=0 ; i<10000 ; i++) { - Double_t tmpy = gRandom->Gaus(0,10) ; - Double_t tmpx = gRandom->Gaus(0.5*tmpy,1) ; + double tmpy = gRandom->Gaus(0,10) ; + double tmpx = gRandom->Gaus(0.5*tmpy,1) ; if (fabs(tmpy)<10 && fabs(tmpx)<10) { x = tmpx ; y = tmpy ; @@ -1716,7 +1718,7 @@ RooDataSet* makeFakeDataXY() - TestBasic303(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Conditional use of F(x|y)",refFile,writeRef,verbose,batchMode) {} ; + TestBasic303(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Conditional use of F(x|y)",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p c o m p o s e d m o d e l g a u s s ( x , m ( y ) , s ) @@ -1745,17 +1747,17 @@ RooDataSet* makeFakeDataXY() // --------------------------------------------------------------------------------------------- // Make subset of experimental data with only y values - std::unique_ptr expDataY{static_cast(expDataXY->reduce(y))}; + std::unique_ptr expDataY{expDataXY->reduce(y)}; // Generate 10000 events in x obtained from _conditional_ model(x|y) with y values taken from experimental data - std::unique_ptr data{model.generate(x,ProtoData(*expDataY))}; + std::unique_ptr data{model.generate(x,ProtoData(static_cast(*expDataY)))}; // F i t c o n d i t i o n a l p . d . f m o d e l ( x | y ) t o d a t a // --------------------------------------------------------------------------------------------- - model.fitTo(*expDataXY,ConditionalObservables(y),BatchMode(_batchMode)) ; + model.fitTo(*expDataXY,ConditionalObservables(y)) ; @@ -1769,13 +1771,13 @@ RooDataSet* makeFakeDataXY() // Speed up (and approximate) projection by using binned clone of data for projection - std::unique_ptr binnedDataY{expDataY->binnedClone()}; + std::unique_ptr binnedDataY{static_cast(*expDataY).binnedClone()}; model.plotOn(xframe,ProjWData(*binnedDataY),LineColor(kCyan),LineStyle(kDotted),Name("Alt1")) ; // Show effect of projection with too coarse binning - ((RooRealVar*)expDataY->get()->find("y"))->setBins(5) ; - std::unique_ptr binnedDataY2{expDataY->binnedClone()}; + static_cast(expDataY->get()->find("y"))->setBins(5) ; + std::unique_ptr binnedDataY2{static_cast(*expDataY).binnedClone()}; model.plotOn(xframe,ProjWData(*binnedDataY2),LineColor(kRed),Name("Alt2")) ; @@ -1805,7 +1807,7 @@ RooDataSet* makeFakeDataXY() class TestBasic304 : public RooUnitTest { public: - TestBasic304(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Product operator p.d.f. with uncorrelated terms",refFile,writeRef,verbose,batchMode) {} ; + TestBasic304(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Product operator p.d.f. with uncorrelated terms",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e c o m p o n e n t p d f s i n x a n d y @@ -1875,7 +1877,7 @@ class TestBasic304 : public RooUnitTest class TestBasic305 : public RooUnitTest { public: - TestBasic305(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Product operator p.d.f. with conditional term",refFile,writeRef,verbose,batchMode) {} ; + TestBasic305(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Product operator p.d.f. with conditional term",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e c o n d i t i o n a l p d f g x ( x | y ) @@ -1900,7 +1902,7 @@ class TestBasic305 : public RooUnitTest // ----------------------------------------------------------- // Create gaussy(y,0,5) - RooGaussian gaussy("gaussy","Gaussian in y",y,RooConst(0),RooConst(3)) ; + RooGaussian gaussy("gaussy","Gaussian in y",y,0.0,3.0) ; @@ -1959,7 +1961,7 @@ class TestBasic305 : public RooUnitTest class TestBasic306 : public RooUnitTest { public: - TestBasic306(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Conditional use of per-event error p.d.f. F(t|dt)",refFile,writeRef,verbose,batchMode) {} ; + TestBasic306(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Conditional use of per-event error p.d.f. F(t|dt)",refFile,writeRef,verbose) {} ; bool testCode() { // B - p h y s i c s p d f w i t h p e r - e v e n t G a u s s i a n r e s o l u t i o n @@ -1984,7 +1986,7 @@ class TestBasic306 : public RooUnitTest // ------------------------------------------------------------------------------------------------------ // Use landau p.d.f to get somewhat realistic distribution with long tail - RooLandau pdfDtErr("pdfDtErr","pdfDtErr",dterr,RooConst(1),RooConst(0.25)) ; + RooLandau pdfDtErr("pdfDtErr","pdfDtErr",dterr,1.0,0.25) ; std::unique_ptr expDataDterr{pdfDtErr.generate(dterr,10000)}; @@ -2001,7 +2003,7 @@ class TestBasic306 : public RooUnitTest // --------------------------------------------------------------------- // Specify dterr as conditional observable - decay_gm.fitTo(*data,ConditionalObservables(dterr),BatchMode(_batchMode)) ; + decay_gm.fitTo(*data,ConditionalObservables(dterr)) ; @@ -2016,7 +2018,7 @@ class TestBasic306 : public RooUnitTest // Plot decay_gm(dt|dterr) at various values of dterr RooPlot* frame = dt.frame(Title("Slices of decay(dt|dterr) at various dterr")) ; - for (Int_t ibin=0 ; ibin<100 ; ibin+=20) { + for (int ibin=0 ; ibin<100 ; ibin+=20) { dterr.setBin(ibin) ; decay_gm.plotOn(frame,Normalization(5.),Name(Form("curve_slice_%d",ibin))) ; } @@ -2058,7 +2060,7 @@ class TestBasic306 : public RooUnitTest class TestBasic307 : public RooUnitTest { public: - TestBasic307(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Full per-event error p.d.f. F(t|dt)G(dt)",refFile,writeRef,verbose,batchMode) {} ; + TestBasic307(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Full per-event error p.d.f. F(t|dt)G(dt)",refFile,writeRef,verbose) {} ; bool testCode() { // B - p h y s i c s p d f w i t h p e r - e v e n t G a u s s i a n r e s o l u t i o n @@ -2083,7 +2085,7 @@ class TestBasic307 : public RooUnitTest // ----------------------------------------------------------------- // Use landau p.d.f to get empirical distribution with long tail - RooLandau pdfDtErr("pdfDtErr","pdfDtErr",dterr,RooConst(1),RooConst(0.25)) ; + RooLandau pdfDtErr("pdfDtErr","pdfDtErr",dterr,1.0,0.25) ; std::unique_ptr expDataDterr{pdfDtErr.generate(dterr,10000)}; // Construct a histogram pdf to describe the shape of the dtErr distribution @@ -2114,7 +2116,7 @@ class TestBasic307 : public RooUnitTest // --------------------------------------------------------------------- // Specify dterr as conditional observable - model.fitTo(*data,BatchMode(_batchMode)) ; + model.fitTo(*data) ; @@ -2151,7 +2153,7 @@ class TestBasic307 : public RooUnitTest class TestBasic308 : public RooUnitTest { public: - TestBasic308(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Normalization of p.d.f.s in 2D",refFile,writeRef,verbose,batchMode) {} ; + TestBasic308(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Normalization of p.d.f.s in 2D",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -2162,8 +2164,8 @@ class TestBasic308 : public RooUnitTest RooRealVar y("y","y",-10,10) ; // Create p.d.f. gaussx(x,-2,3), gaussy(y,2,2) - RooGaussian gx("gx","gx",x,RooConst(-2),RooConst(3)) ; - RooGaussian gy("gy","gy",y,RooConst(+2),RooConst(2)) ; + RooGaussian gx("gx","gx",x,-2.0,3.0) ; + RooGaussian gy("gy","gy",y,+2.0,2.0) ; // Create gxy = gx(x)*gy(y) RooProdPdf gxy("gxy","gxy",RooArgSet(gx,gy)) ; @@ -2243,7 +2245,7 @@ class TestBasic308 : public RooUnitTest class TestBasic310 : public RooUnitTest { public: - TestBasic310(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Data and p.d.f projection in category slice",refFile,writeRef,verbose,batchMode) {} ; + TestBasic310(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Data and p.d.f projection in category slice",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e B d e c a y p d f w it h m i x i n g @@ -2332,7 +2334,7 @@ class TestBasic310 : public RooUnitTest class TestBasic311 : public RooUnitTest { public: - TestBasic311(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Data and p.d.f projection in sub range",refFile,writeRef,verbose,batchMode) {} ; + TestBasic311(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Data and p.d.f projection in sub range",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e 3 D p d f a n d d a t a @@ -2344,14 +2346,14 @@ class TestBasic311 : public RooUnitTest RooRealVar z("z","z",-5,5) ; // Create signal pdf gauss(x)*gauss(y)*gauss(z) - RooGaussian gx("gx","gx",x,RooConst(0),RooConst(1)) ; - RooGaussian gy("gy","gy",y,RooConst(0),RooConst(1)) ; - RooGaussian gz("gz","gz",z,RooConst(0),RooConst(1)) ; + RooGaussian gx("gx","gx",x,0.0,1.0) ; + RooGaussian gy("gy","gy",y,0.0,1.0) ; + RooGaussian gz("gz","gz",z,0.0,1.0) ; RooProdPdf sig("sig","sig",RooArgSet(gx,gy,gz)) ; // Create background pdf poly(x)*poly(y)*poly(z) - RooPolynomial px("px","px",x,RooArgSet(RooConst(-0.1),RooConst(0.004))) ; - RooPolynomial py("py","py",y,RooArgSet(RooConst(0.1),RooConst(-0.004))) ; + RooPolynomial px("px","px",x,RooArgSet(-0.1,0.004)) ; + RooPolynomial py("py","py",y,RooArgSet(0.1,-0.004)) ; RooPolynomial pz("pz","pz",z) ; RooProdPdf bkg("bkg","bkg",RooArgSet(px,py,pz)) ; @@ -2414,7 +2416,7 @@ class TestBasic311 : public RooUnitTest class TestBasic312 : public RooUnitTest { public: - TestBasic312(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Fit in multiple rectangular ranges",refFile,writeRef,verbose,batchMode) {} ; + TestBasic312(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Fit in multiple rectangular ranges",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e 2 D p d f a n d d a t a @@ -2428,8 +2430,8 @@ class TestBasic312 : public RooUnitTest RooRealVar mx("mx","mx",1,-10,10) ; RooRealVar my("my","my",1,-10,10) ; - RooGaussian gx("gx","gx",x,mx,RooConst(1)) ; - RooGaussian gy("gy","gy",y,my,RooConst(1)) ; + RooGaussian gx("gx","gx",x,mx,1.0) ; + RooGaussian gy("gy","gy",y,my,1.0) ; RooProdPdf sig("sig","sig",gx,gy) ; @@ -2483,10 +2485,10 @@ class TestBasic312 : public RooUnitTest // ------------------------------------------------------------------------------------- // Perform fit in SideBand1 region (RooAddPdf coefficients will be interpreted in full range) - RooFitResult* r_sb1 = model.fitTo(*modelData,Range("SB1"),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r_sb1{model.fitTo(*modelData,Range("SB1"),Save())}; // Perform fit in SideBand2 region (RooAddPdf coefficients will be interpreted in full range) - RooFitResult* r_sb2 = model.fitTo(*modelData,Range("SB2"),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r_sb2{model.fitTo(*modelData,Range("SB2"),Save())}; @@ -2495,12 +2497,12 @@ class TestBasic312 : public RooUnitTest // Now perform fit to joint 'L-shaped' sideband region 'SB1|SB2' // (RooAddPdf coefficients will be interpreted in full range) - RooFitResult* r_sb12 = model.fitTo(*modelData,Range("SB1,SB2"),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r_sb12{model.fitTo(*modelData,Range("SB1,SB2"),Save())}; - regResult(r_sb1,"rf312_fit_sb1") ; - regResult(r_sb2,"rf312_fit_sb2") ; - regResult(r_sb12,"rf312_fit_sb12") ; + regResult(std::move(r_sb1),"rf312_fit_sb1") ; + regResult(std::move(r_sb2),"rf312_fit_sb2") ; + regResult(std::move(r_sb12),"rf312_fit_sb12") ; return true ; @@ -2523,7 +2525,7 @@ class TestBasic312 : public RooUnitTest class TestBasic313 : public RooUnitTest { public: - TestBasic313(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Integration over non-rectangular regions",refFile,writeRef,verbose,batchMode) {} ; + TestBasic313(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Integration over non-rectangular regions",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e 3 D p d f @@ -2603,7 +2605,7 @@ class TestBasic313 : public RooUnitTest class TestBasic314 : public RooUnitTest { public: - TestBasic314(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Fit with non-rectangular observable boundaries",refFile,writeRef,verbose,batchMode) {} ; + TestBasic314(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Fit with non-rectangular observable boundaries",refFile,writeRef,verbose) {} ; bool testCode() { // D e f i n e o b s e r v a b l e s a n d d e c a y p d f @@ -2629,7 +2631,7 @@ class TestBasic314 : public RooUnitTest std::unique_ptr dall{model.generate(t,10000)}; // Generate a (fake) prototype dataset for acceptance limit values - std::unique_ptr tmp{RooGaussian("gmin","gmin",tmin,RooConst(0),RooConst(0.5)).generate(tmin,5000)}; + std::unique_ptr tmp{RooGaussian("gmin","gmin",tmin,0.0,0.5).generate(tmin,5000)}; // Generate dataset with t values that observe (t>tmin) std::unique_ptr dacc{model.generate(t,ProtoData(*tmp))}; @@ -2639,7 +2641,7 @@ class TestBasic314 : public RooUnitTest // F i t p d f t o d a t a i n a c c e p t a n c e r e g i o n // ----------------------------------------------------------------------- - RooFitResult* r = model.fitTo(*dacc,Save(),BatchMode(_batchMode)) ; + std::unique_ptr r{model.fitTo(*dacc,Save())}; @@ -2653,7 +2655,7 @@ class TestBasic314 : public RooUnitTest dacc->plotOn(frame,Name("dacc")) ; // Print fit results to demonstrate absence of bias - regResult(r,"rf314_fit") ; + regResult(std::move(r),"rf314_fit") ; regPlot(frame,"rf314_plot1") ; return true; @@ -2678,7 +2680,7 @@ class TestBasic314 : public RooUnitTest class TestBasic315 : public RooUnitTest { public: - TestBasic315(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("P.d.f. marginalization through integration",refFile,writeRef,verbose,batchMode) {} ; + TestBasic315(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("P.d.f. marginalization through integration",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e p d f m ( x , y ) = g x ( x | y ) * g ( y ) @@ -2703,7 +2705,7 @@ class TestBasic315 : public RooUnitTest RooGaussian gaussx("gaussx","Gaussian in x with shifting mean in y",x,fy,sigmax) ; // Create gaussy(y,0,2) - RooGaussian gaussy("gaussy","Gaussian in y",y,RooConst(0),RooConst(2)) ; + RooGaussian gaussy("gaussy","Gaussian in y",y,0.0,2.0) ; // Create gaussx(x,sx|y) * gaussy(y) RooProdPdf model("model","gaussx(x|y)*gaussy(y)",gaussy,Conditional(gaussx,x)) ; @@ -2725,7 +2727,7 @@ class TestBasic315 : public RooUnitTest std::unique_ptr data{modelx->generateBinned(x,1000)}; // Fit modelx to toy data - modelx->fitTo(*data,BatchMode(_batchMode)) ; + modelx->fitTo(*data) ; // Plot modelx over data RooPlot* frame = x.frame(40) ; @@ -2759,7 +2761,7 @@ class TestBasic315 : public RooUnitTest class TestBasic316 : public RooUnitTest { public: - TestBasic316(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Likelihood ratio projection plot",refFile,writeRef,verbose,batchMode) {} ; + TestBasic316(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Likelihood ratio projection plot",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e 3 D p d f a n d d a t a @@ -2771,14 +2773,14 @@ class TestBasic316 : public RooUnitTest RooRealVar z("z","z",-5,5) ; // Create signal pdf gauss(x)*gauss(y)*gauss(z) - RooGaussian gx("gx","gx",x,RooConst(0),RooConst(1)) ; - RooGaussian gy("gy","gy",y,RooConst(0),RooConst(1)) ; - RooGaussian gz("gz","gz",z,RooConst(0),RooConst(1)) ; + RooGaussian gx("gx","gx",x,0.0,1.0) ; + RooGaussian gy("gy","gy",y,0.0,1.0) ; + RooGaussian gz("gz","gz",z,0.0,1.0) ; RooProdPdf sig("sig","sig",RooArgSet(gx,gy,gz)) ; // Create background pdf poly(x)*poly(y)*poly(z) - RooPolynomial px("px","px",x,RooArgSet(RooConst(-0.1),RooConst(0.004))) ; - RooPolynomial py("py","py",y,RooArgSet(RooConst(0.1),RooConst(-0.004))) ; + RooPolynomial px("px","px",x,RooArgSet(-0.1,0.004)) ; + RooPolynomial py("py","py",y,RooArgSet(0.1,-0.004)) ; RooPolynomial pz("pz","pz",z) ; RooProdPdf bkg("bkg","bkg",RooArgSet(px,py,pz)) ; @@ -2820,7 +2822,7 @@ class TestBasic316 : public RooUnitTest data->addColumn(llratio_func) ; // Extract the subset of data with large signal likelihood - std::unique_ptr dataSel{static_cast(data->reduce(Cut("llratio>0.7")))}; + std::unique_ptr dataSel{data->reduce(Cut("llratio>0.7"))}; // Make plot frame RooPlot* frame2 = x.frame(Title("Same projection on X with LLratio(y,z)>0.7"),Bins(40)) ; @@ -2838,11 +2840,11 @@ class TestBasic316 : public RooUnitTest // Calculate LL ratio for each generated event and select MC events with llratio)0.7 mcprojData->addColumn(llratio_func) ; - std::unique_ptr mcprojDataSel{static_cast(mcprojData->reduce(Cut("llratio>0.7")))}; + std::unique_ptr mcprojDataSel{mcprojData->reduce(Cut("llratio>0.7"))}; // Project model on x, integrating projected observables (y,z) with Monte Carlo technique // on set of events with the same llratio cut as was applied to data - model.plotOn(frame2,ProjWData(*mcprojDataSel)) ; + model.plotOn(frame2,ProjWData(static_cast(*mcprojDataSel))); regPlot(frame,"rf316_plot1") ; @@ -2867,7 +2869,7 @@ class TestBasic316 : public RooUnitTest class TestBasic402 : public RooUnitTest { public: - TestBasic402(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Basic operations on datasets",refFile,writeRef,verbose,batchMode) {} ; + TestBasic402(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Basic operations on datasets",refFile,writeRef,verbose) {} ; bool testCode() { // Binned (RooDataHist) and unbinned datasets (RooDataSet) share @@ -2894,7 +2896,7 @@ class TestBasic402 : public RooUnitTest // clone of the supplied set of arguments // Fill d with dummy values - Int_t i ; + int i ; for (i=0 ; i<1000 ; i++) { x = i/50 - 10 ; y = sqrt(1.0*i) ; @@ -2910,19 +2912,19 @@ class TestBasic402 : public RooUnitTest // ------------------------------------------------------------- // The reduce() function returns a new dataset which is a subset of the original - std::unique_ptr d1{static_cast(d.reduce(RooArgSet(x,c)))}; - std::unique_ptr d2{static_cast(d.reduce(RooArgSet(y)))}; - std::unique_ptr d3{static_cast(d.reduce("y>5.17"))}; - std::unique_ptr d4{static_cast(d.reduce(RooArgSet(x,c),"y>5.17"))}; + std::unique_ptr d1{d.reduce(RooArgSet(x,c))}; + std::unique_ptr d2{d.reduce(RooArgSet(y))}; + std::unique_ptr d3{d.reduce("y>5.17")}; + std::unique_ptr d4{d.reduce(RooArgSet(x,c),"y>5.17")}; regValue(d3->numEntries(),"rf403_nd3") ; regValue(d4->numEntries(),"rf403_nd4") ; // The merge() function adds two data set column-wise - d1->merge(d2.get()) ; + static_cast(*d1).merge(static_cast(d2.get())); // The append() function addes two datasets row-wise - d1->append(*d3) ; + static_cast(*d1).append(static_cast(*d3)); regValue(d1->numEntries(),"rf403_nd1") ; @@ -2949,7 +2951,7 @@ class TestBasic402 : public RooUnitTest // // All reduce() methods are interfaced in RooAbsData. All reduction techniques // demonstrated on unbinned datasets can be applied to binned datasets as well. - std::unique_ptr dh2{static_cast(dh.reduce(y,"x>0"))}; + std::unique_ptr dh2{dh.reduce(y,"x>0")}; // Add dh2 to yframe and redraw dh2->plotOn(yframe,LineColor(kRed),MarkerColor(kRed),Name("dh2")) ; @@ -2975,7 +2977,7 @@ class TestBasic402 : public RooUnitTest class TestBasic403 : public RooUnitTest { public: - TestBasic403(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Fits with weighted datasets",refFile,writeRef,verbose,batchMode) {} ; + TestBasic403(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Fits with weighted datasets",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e o b s e r v a b l e a n d u n w e i g h t e d d a t a s e t @@ -3023,7 +3025,7 @@ class TestBasic403 : public RooUnitTest // event weights represent Poisson statistics themselves. // In general, parameter error reflect precision of SumOfWeights // events rather than NumEvents events. See comparisons below - RooFitResult* r_ml_wgt = p2.fitTo(dataw,Save(),BatchMode(_batchMode)) ; + std::unique_ptr r_ml_wgt{p2.fitTo(dataw,Save())}; @@ -3054,8 +3056,8 @@ class TestBasic403 : public RooUnitTest std::unique_ptr data3{genPdf.generate(x,43000)}; // Fit the 2nd order polynomial to both unweighted datasets and save the results for comparison - RooFitResult* r_ml_unw10 = p2.fitTo(*data2,Save(),BatchMode(_batchMode)) ; - RooFitResult* r_ml_unw43 = p2.fitTo(*data3,Save(),BatchMode(_batchMode)) ; + std::unique_ptr r_ml_unw10{p2.fitTo(*data2,Save())}; + std::unique_ptr r_ml_unw43{p2.fitTo(*data3,Save())}; // C h i 2 f i t o f p d f t o b i n n e d w e i g h t e d d a t a s e t @@ -3075,7 +3077,7 @@ class TestBasic403 : public RooUnitTest m.hesse() ; // Plot chi^2 fit result on frame as well - RooFitResult* r_chi2_wgt = m.save() ; + std::unique_ptr r_chi2_wgt{m.save()}; p2.plotOn(frame,LineStyle(kDashed),LineColor(kRed),Name("p2_alt")) ; @@ -3087,10 +3089,10 @@ class TestBasic403 : public RooUnitTest // than to 1Kevt of unweighted data, whereas the reference chi^2 fit with SumW2 error gives a result closer to // that of an unbinned ML fit to 1Kevt of unweighted data. - regResult(r_ml_unw10,"rf403_ml_unw10") ; - regResult(r_ml_unw43,"rf403_ml_unw43") ; - regResult(r_ml_wgt ,"rf403_ml_wgt") ; - regResult(r_chi2_wgt ,"rf403_ml_chi2") ; + regResult(std::move(r_ml_unw10),"rf403_ml_unw10") ; + regResult(std::move(r_ml_unw43),"rf403_ml_unw43") ; + regResult(std::move(r_ml_wgt) ,"rf403_ml_wgt") ; + regResult(std::move(r_chi2_wgt) ,"rf403_ml_chi2") ; regPlot(frame,"rf403_plot1") ; return true ; @@ -3112,7 +3114,7 @@ class TestBasic403 : public RooUnitTest class TestBasic404 : public RooUnitTest { public: - TestBasic404(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Categories basic functionality",refFile,writeRef,verbose,batchMode) {} ; + TestBasic404(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Categories basic functionality",refFile,writeRef,verbose) {} ; bool testCode() { // C o n s t r u c t a c a t e g o r y w i t h l a b e l s @@ -3160,11 +3162,11 @@ class TestBasic404 : public RooUnitTest // Retrieve number of events from table // Number can be non-integer if source dataset has weighed events - Double_t nb0 = btable->get("B0") ; + double nb0 = btable->get("B0") ; regValue(nb0,"rf404_nb0") ; // Retrieve fraction of events with "Lepton" tag - Double_t fracLep = ttable->getFrac("Lepton") ; + double fracLep = ttable->getFrac("Lepton") ; regValue(fracLep,"rf404_fracLep") ; @@ -3179,7 +3181,7 @@ class TestBasic404 : public RooUnitTest tagCat.addToRange("soso","NetTagger-2") ; // Use category range in dataset reduction specification - std::unique_ptr goodData{static_cast(data->reduce(CutRange("good")))}; + std::unique_ptr goodData{data->reduce(CutRange("good"))}; Roo1DTable* gtable = goodData->table(tagCat) ; @@ -3210,7 +3212,7 @@ class TestBasic404 : public RooUnitTest class TestBasic405 : public RooUnitTest { public: - TestBasic405(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Real-to-category functions",refFile,writeRef,verbose,batchMode) {} ; + TestBasic405(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Real-to-category functions",refFile,writeRef,verbose) {} ; bool testCode() { @@ -3292,7 +3294,7 @@ class TestBasic405 : public RooUnitTest xb->setRange("alt","x_coarse_bin1,x_coarse_bin3,x_coarse_bin5,x_coarse_bin7,x_coarse_bin9") ; // Construct subset of data matching range "alt" but only for the first 5000 events and plot it on the fram - std::unique_ptr dataSel{static_cast(data->reduce(CutRange("alt"),EventRange(0,5000)))}; + std::unique_ptr dataSel{data->reduce(CutRange("alt"),EventRange(0,5000))}; // dataSel->plotOn(xframe,MarkerColor(kGreen),LineColor(kGreen),Name("data_sel")) ; @@ -3320,7 +3322,7 @@ class TestBasic405 : public RooUnitTest class TestBasic406 : public RooUnitTest { public: - TestBasic406(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Category-to-category functions",refFile,writeRef,verbose,batchMode) {} ; + TestBasic406(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Category-to-category functions",refFile,writeRef,verbose) {} ; bool testCode() { // C o n s t r u c t t w o c a t e g o r i e s @@ -3412,7 +3414,7 @@ class TestBasic406 : public RooUnitTest class TestBasic501 : public RooUnitTest { public: - TestBasic501(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Simultaneous p.d.f. operator",refFile,writeRef,verbose,batchMode) {} ; + TestBasic501(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Simultaneous p.d.f. operator",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l f o r p h y s i c s s a m p l e @@ -3494,7 +3496,7 @@ class TestBasic501 : public RooUnitTest // --------------------------------------------------- // Perform simultaneous fit of model to data and model_ctl to data_ctl - simPdf.fitTo(combData,BatchMode(_batchMode)) ; + simPdf.fitTo(combData) ; @@ -3546,7 +3548,7 @@ class TestBasic501 : public RooUnitTest class TestBasic599 : public RooUnitTest { public: - TestBasic599(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Workspace and p.d.f. persistence",refFile,writeRef,verbose,batchMode) {} ; + TestBasic599(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Workspace and p.d.f. persistence",refFile,writeRef,verbose) {} ; bool testCode() { if (_write) { @@ -3760,7 +3762,7 @@ class TestBasic599 : public RooUnitTest class TestBasic601 : public RooUnitTest { public: - TestBasic601(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Interactive Minuit",refFile,writeRef,verbose,batchMode) {} ; + TestBasic601(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Interactive Minuit",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p p d f a n d l i k e l i h o o d @@ -3784,7 +3786,7 @@ class TestBasic601 : public RooUnitTest std::unique_ptr data{model.generate(x,1000)}; // Construct unbinned likelihood - std::unique_ptr nll{model.createNLL(*data, BatchMode(_batchMode))}; + std::unique_ptr nll{model.createNLL(*data)}; // I n t e r a c t i v e m i n i m i z a t i o n , e r r o r a n a l y s i s @@ -3811,7 +3813,7 @@ class TestBasic601 : public RooUnitTest // matrix, the EDM, the minimized FCN , the last MINUIT status code and // the number of times the RooFit function object has indicated evaluation // problems (e.g. zero probabilities during likelihood evaluation) - RooFitResult* r = m.save() ; + std::unique_ptr r{m.save()}; // C h a n g e p a r a m e t e r v a l u e s , f l o a t i n g @@ -3832,10 +3834,10 @@ class TestBasic601 : public RooUnitTest m.migrad() ; m.hesse() ; - RooFitResult* r2 = m.save() ; + std::unique_ptr r2{m.save()}; - regResult(r,"rf601_r") ; - regResult(r2,"rf601_r2") ; + regResult(std::move(r),"rf601_r") ; + regResult(std::move(r2),"rf601_r2") ; return true ; } @@ -3856,7 +3858,7 @@ class TestBasic601 : public RooUnitTest class TestBasic602 : public RooUnitTest { public: - TestBasic602(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Chi2 minimization",refFile,writeRef,verbose,batchMode) {} ; + TestBasic602(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Chi2 minimization",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p m o d e l @@ -3904,9 +3906,9 @@ class TestBasic602 : public RooUnitTest m.migrad() ; m.hesse() ; - RooFitResult* r = m.save() ; + std::unique_ptr r{ m.save()}; - regResult(r,"rf602_r") ; + regResult(std::move(r),"rf602_r"); return true ; } @@ -3926,7 +3928,7 @@ class TestBasic602 : public RooUnitTest class TestBasic604 : public RooUnitTest { public: - TestBasic604(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Auxiliary observable constraints",refFile,writeRef,verbose,batchMode) {} ; + TestBasic604(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Auxiliary observable constraints",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l a n d d a t a s e t @@ -3955,7 +3957,7 @@ class TestBasic604 : public RooUnitTest // ----------------------------------------- // Construct Gaussian constraint p.d.f on parameter f at 0.8 with resolution of 0.1 - RooGaussian fconstraint("fconstraint","fconstraint",f,RooConst(0.8),RooConst(0.1)) ; + RooGaussian fconstraint("fconstraint","fconstraint",f,0.8,0.1) ; @@ -3969,10 +3971,10 @@ class TestBasic604 : public RooUnitTest RooProdPdf modelc("modelc","model with constraint",RooArgSet(model,fconstraint)) ; // Fit modelc without use of constraint term - RooFitResult* r1 = modelc.fitTo(*d,Save(),BatchMode(_batchMode)) ; + std::unique_ptr r1{modelc.fitTo(*d,Save())}; // Fit modelc with constraint term on parameter f - RooFitResult* r2 = modelc.fitTo(*d,Constrain(f),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r2{modelc.fitTo(*d,Constrain(f),Save())}; @@ -3980,15 +3982,15 @@ class TestBasic604 : public RooUnitTest // ------------------------------------------------------------------------------------------------------- // Construct another Gaussian constraint p.d.f on parameter f at 0.8 with resolution of 0.1 - RooGaussian fconstext("fconstext","fconstext",f,RooConst(0.2),RooConst(0.1)) ; + RooGaussian fconstext("fconstext","fconstext",f,0.2,0.1) ; // Fit with external constraint - RooFitResult* r3 = model.fitTo(*d,ExternalConstraints(fconstext),Save(),BatchMode(_batchMode)) ; + std::unique_ptr r3{model.fitTo(*d,ExternalConstraints(fconstext),Save())}; - regResult(r1,"rf604_r1") ; - regResult(r2,"rf604_r2") ; - regResult(r3,"rf604_r3") ; + regResult(std::move(r1),"rf604_r1") ; + regResult(std::move(r2),"rf604_r2") ; + regResult(std::move(r3),"rf604_r3") ; return true ; } @@ -4009,7 +4011,7 @@ class TestBasic604 : public RooUnitTest class TestBasic605 : public RooUnitTest { public: - TestBasic605(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Profile Likelihood operator",refFile,writeRef,verbose,batchMode) {} ; + TestBasic605(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Profile Likelihood operator",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l a n d d a t a s e t @@ -4038,7 +4040,7 @@ class TestBasic605 : public RooUnitTest // --------------------------------------------------- // Construct unbinned likelihood - std::unique_ptr nll{model.createNLL(*data, BatchMode(_batchMode))}; + std::unique_ptr nll{model.createNLL(*data)}; nll->SetName("nll"); // Minimize likelihood w.r.t all parameters before making plots @@ -4108,7 +4110,7 @@ class TestBasic605 : public RooUnitTest class TestBasic606 : public RooUnitTest { public: - TestBasic606(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("NLL error handling",refFile,writeRef,verbose,batchMode) {} ; + TestBasic606(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("NLL error handling",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l a n d d a t a s e t @@ -4141,9 +4143,9 @@ class TestBasic606 : public RooUnitTest // F i t m o d e l t o d a t a // --------------------------------- - argus.fitTo(*data,PrintEvalErrors(10),Warnings(false),BatchMode(_batchMode)) ; + argus.fitTo(*data,PrintEvalErrors(10),Warnings(false)) ; m0.setError(0.1) ; - argus.fitTo(*data,PrintEvalErrors(0),EvalErrorWall(false),Warnings(false),BatchMode(_batchMode)) ; + argus.fitTo(*data,PrintEvalErrors(0),EvalErrorWall(false),Warnings(false)) ; @@ -4151,7 +4153,7 @@ class TestBasic606 : public RooUnitTest // ------------------------------------------------------------------ // Construct likelihood function of model and data - std::unique_ptr nll{argus.createNLL(*data, BatchMode(_batchMode))}; + std::unique_ptr nll{argus.createNLL(*data)}; nll->SetName("nll"); // Plot likelihood in m0 in range that includes problematic values @@ -4186,7 +4188,7 @@ class TestBasic606 : public RooUnitTest class TestBasic607 : public RooUnitTest { public: - TestBasic607(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Fit Result functionality",refFile,writeRef,verbose,batchMode) {} ; + TestBasic607(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Fit Result functionality",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e p d f , d a t a @@ -4225,7 +4227,7 @@ class TestBasic607 : public RooUnitTest // ------------------------------------------------------------- // Perform fit and save result - std::unique_ptr r{model.fitTo(*data,Save(),BatchMode(_batchMode))}; + std::unique_ptr r{model.fitTo(*data,Save())}; // V i s u a l i z e c o r r e l a t i o n m a t r i x @@ -4240,7 +4242,7 @@ class TestBasic607 : public RooUnitTest // Sample dataset with parameter values according to distribution // of covariance matrix of fit result RooDataSet randPars("randPars","randPars",r->floatParsFinal()) ; - for (Int_t i=0 ; i<10000 ; i++) { + for (int i=0 ; i<10000 ; i++) { randPars.add(r->randomizePars()) ; } @@ -4273,7 +4275,7 @@ class TestBasic607 : public RooUnitTest class TestBasic609 : public RooUnitTest { public: - TestBasic609(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Chi^2 fit to X-Y dataset",refFile,writeRef,verbose,batchMode) {} ; + TestBasic609(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Chi^2 fit to X-Y dataset",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e d a t a s e t w i t h X a n d Y v a l u e s @@ -4312,21 +4314,22 @@ class TestBasic609 : public RooUnitTest // Make fit function RooRealVar a("a","a",0.0,-10,10) ; RooRealVar b("b","b",0.0,-100,100) ; - RooPolyVar f("f","f",x,RooArgList(b,a,RooConst(1))) ; + RooRealVar c("c", "c", 0.0, -100, 100); + RooPolyVar f("f", "f", x, RooArgList(b, a, c)); // Plot dataset in X-Y interpretation RooPlot* frame = x.frame(Title("Chi^2 fit of function set of (X#pmdX,Y#pmdY) values")) ; dxy.plotOnXY(frame,YVar(y)) ; // Fit chi^2 using X and Y errors - f.chi2FitTo(dxy,YVar(y)) ; + std::unique_ptr fit1{f.chi2FitTo(dxy, YVar(y), Save(), PrintLevel(-1))}; // Overlay fitted function f.plotOn(frame) ; // Alternative: fit chi^2 integrating f(x) over ranges defined by X errors, rather // than taking point at center of bin - f.chi2FitTo(dxy,YVar(y),Integrate(true)) ; + std::unique_ptr fit2{f.chi2FitTo(dxy, YVar(y), Save(), PrintLevel(-1), Integrate(true))}; // Overlay alternate fit result f.plotOn(frame,LineStyle(kDashed),LineColor(kRed),Name("alternate")) ; @@ -4355,7 +4358,7 @@ class TestBasic609 : public RooUnitTest class TestBasic701 : public RooUnitTest { public: - TestBasic701(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Efficiency operator p.d.f. 1D",refFile,writeRef,verbose,batchMode) {} ; + TestBasic701(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Efficiency operator p.d.f. 1D",refFile,writeRef,verbose) {} ; bool testCode() { // C o n s t r u c t e f f i c i e n c y f u n c t i o n e ( x ) @@ -4402,7 +4405,7 @@ class TestBasic701 : public RooUnitTest // -------------------------------------------------------------------------- // Fit conditional efficiency p.d.f to data - effPdf.fitTo(*data,ConditionalObservables(x),BatchMode(_batchMode)) ; + effPdf.fitTo(*data,ConditionalObservables(x)) ; @@ -4442,7 +4445,7 @@ class TestBasic701 : public RooUnitTest class TestBasic702 : public RooUnitTest { public: - TestBasic702(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Efficiency operator p.d.f. 2D",refFile,writeRef,verbose,batchMode) {} ; + TestBasic702(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Efficiency operator p.d.f. 2D",refFile,writeRef,verbose) {} ; bool testCode() { bool flat=false ; @@ -4499,7 +4502,7 @@ class TestBasic702 : public RooUnitTest // -------------------------------------------------------------------------- // Fit conditional efficiency p.d.f to data - effPdf.fitTo(*data,ConditionalObservables(RooArgSet(x,y)),BatchMode(_batchMode)) ; + effPdf.fitTo(*data,ConditionalObservables(RooArgSet(x,y))) ; @@ -4541,7 +4544,7 @@ class TestBasic702 : public RooUnitTest class TestBasic703 : public RooUnitTest { public: - TestBasic703(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Efficiency product operator p.d.f",refFile,writeRef,verbose,batchMode) {} ; + TestBasic703(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Efficiency product operator p.d.f",refFile,writeRef,verbose) {} ; bool testCode() { // D e f i n e o b s e r v a b l e s a n d d e c a y p d f @@ -4593,7 +4596,7 @@ class TestBasic703 : public RooUnitTest std::unique_ptr data{modelEff.generate(t,10000)}; // Fit pdf. The normalization integral is calculated numerically. - modelEff.fitTo(*data,BatchMode(_batchMode)) ; + modelEff.fitTo(*data) ; // Plot generated data and overlay fitted pdf RooPlot* frame3 = t.frame(Title("Fitted pdf with efficiency")) ; @@ -4625,7 +4628,7 @@ class TestBasic703 : public RooUnitTest class TestBasic704 : public RooUnitTest { public: - TestBasic704(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Amplitude sum operator p.d.f",refFile,writeRef,verbose,batchMode) {} ; + TestBasic704(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Amplitude sum operator p.d.f",refFile,writeRef,verbose) {} ; bool testCode() { // S e t u p 2 D a m p l i t u d e f u n c t i o n s @@ -4635,22 +4638,18 @@ class TestBasic704 : public RooUnitTest RooRealVar t("t","time",-1.,15.); RooRealVar cosa("cosa","cos(alpha)",-1.,1.); - // Use RooTruthModel to obtain compiled implementation of sinh/cosh modulated decay functions - RooRealVar tau("tau","#tau",1.5); + RooRealVar tau("tau", "#tau", 1.5); RooRealVar deltaGamma("deltaGamma","deltaGamma", 0.3); - RooTruthModel tm("tm","tm",t) ; - RooFormulaVar coshGBasis("coshGBasis","exp(-@0/ @1)*cosh(@0*@2/2)",RooArgList(t,tau,deltaGamma)); - RooFormulaVar sinhGBasis("sinhGBasis","exp(-@0/ @1)*sinh(@0*@2/2)",RooArgList(t,tau,deltaGamma)); - std::unique_ptr coshGConv{tm.convolution(&coshGBasis,&t)}; - std::unique_ptr sinhGConv{tm.convolution(&sinhGBasis,&t)}; + RooFormulaVar coshG("coshGBasis","exp(-@0/ @1)*cosh(@0*@2/2)", {t,tau,deltaGamma}); + RooFormulaVar sinhG("sinhGBasis","exp(-@0/ @1)*sinh(@0*@2/2)", {t,tau,deltaGamma}); // Construct polynomial amplitudes in cos(a) - RooPolyVar poly1("poly1","poly1",cosa,RooArgList(RooConst(0.5),RooConst(0.2),RooConst(0.2)),0); - RooPolyVar poly2("poly2","poly2",cosa,RooArgList(RooConst(1),RooConst(-0.2),RooConst(3)),0); + RooPolyVar poly1("poly1","poly1",cosa,RooArgList(0.5, 0.2, 0.2),0); + RooPolyVar poly2("poly2","poly2",cosa,RooArgList(1.0, -0.2, 3.0),0); // Construct 2D amplitude as uncorrelated product of amp(t)*amp(cosa) - RooProduct ampl1("ampl1","amplitude 1",RooArgSet(poly1,*coshGConv)); - RooProduct ampl2("ampl2","amplitude 2",RooArgSet(poly2,*sinhGConv)); + RooProduct ampl1("ampl1","amplitude 1", {poly1, coshG}); + RooProduct ampl2("ampl2","amplitude 2", {poly2, sinhG}); @@ -4668,7 +4667,7 @@ class TestBasic704 : public RooUnitTest std::unique_ptr data{pdf.generate(RooArgSet(t,cosa),10000)}; // Fit pdf to toy data with only amplitude strength floating - pdf.fitTo(*data,BatchMode(_batchMode)) ; + pdf.fitTo(*data) ; @@ -4724,9 +4723,9 @@ class TestBasic705 : public RooUnitTest { public: - Double_t ctol() { return 5e-2 ; } // very conservative, this is a numerically difficult test + double ctol() { return 5e-2 ; } // very conservative, this is a numerically difficult test - TestBasic705(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Linear morph operator p.d.f.",refFile,writeRef,verbose,batchMode) {} ; + TestBasic705(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Linear morph operator p.d.f.",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e e n d p o i n t p d f s h a p e s @@ -4737,10 +4736,10 @@ class TestBasic705 : public RooUnitTest // Lower end point shape: a Gaussian RooRealVar g1mean("g1mean","g1mean",-10) ; - RooGaussian g1("g1","g1",x,g1mean,RooConst(2)) ; + RooGaussian g1("g1","g1",x,g1mean,2.0) ; // Upper end point shape: a Polynomial - RooPolynomial g2("g2","g2",x,RooArgSet(RooConst(-0.03),RooConst(-0.001))) ; + RooPolynomial g2("g2","g2",x,RooArgSet(-0.03,-0.001)) ; @@ -4808,7 +4807,7 @@ class TestBasic705 : public RooUnitTest { // Get rid of the caching info prints RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::Caching, true}; - lmorph.fitTo(*data,BatchMode(_batchMode)) ; + lmorph.fitTo(*data) ; } // Plot fitted pdf and data overlaid @@ -4827,7 +4826,7 @@ class TestBasic705 : public RooUnitTest { // Get rid of the caching info prints RooHelpers::LocalChangeMsgLevel chmsglvl{RooFit::WARNING, 0u, RooFit::Caching, true}; - std::unique_ptr nll{lmorph.createNLL(*data, BatchMode(_batchMode))}; + std::unique_ptr nll{lmorph.createNLL(*data)}; nll->SetName("nll"); nll->plotOn(frame3,ShiftToZero()) ; } @@ -4859,14 +4858,14 @@ class TestBasic705 : public RooUnitTest class TestBasic706 : public RooUnitTest { public: - TestBasic706(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Histogram based p.d.f.s",refFile,writeRef,verbose,batchMode) {} ; + TestBasic706(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Histogram based p.d.f.s",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e p d f f o r s a m p l i n g // --------------------------------------------- RooRealVar x("x","x",0,20) ; - RooPolynomial p("p","p",x,RooArgList(RooConst(0.01),RooConst(-0.01),RooConst(0.0004))) ; + RooPolynomial p("p","p",x,RooArgList(0.01,-0.01,0.0004)) ; @@ -4930,7 +4929,7 @@ class TestBasic706 : public RooUnitTest class TestBasic707 : public RooUnitTest { public: - TestBasic707(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Kernel estimation p.d.f.s",refFile,writeRef,verbose,batchMode) {} ; + TestBasic707(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Kernel estimation p.d.f.s",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e l o w s t a t s 1 - D d a t a s e t @@ -4938,7 +4937,7 @@ class TestBasic707 : public RooUnitTest // Create a toy pdf for sampling RooRealVar x("x","x",0,20) ; - RooPolynomial p("p","p",x,RooArgList(RooConst(0.01),RooConst(-0.01),RooConst(0.0004))) ; + RooPolynomial p("p","p",x,RooArgList(0.01,-0.01,0.0004)) ; // Sample 500 events from p std::unique_ptr data1{p.generate(x,200)}; @@ -4982,7 +4981,7 @@ class TestBasic707 : public RooUnitTest // Construct a 2D toy pdf for sampleing RooRealVar y("y","y",0,20) ; - RooPolynomial py("py","py",y,RooArgList(RooConst(0.01),RooConst(0.01),RooConst(-0.0004))) ; + RooPolynomial py("py","py",y,RooArgList(0.01,0.01,-0.0004)) ; RooProdPdf pxy("pxy","pxy",RooArgSet(p,py)) ; std::unique_ptr data2{pxy.generate(RooArgSet(x,y),1000)}; @@ -5031,7 +5030,7 @@ class TestBasic707 : public RooUnitTest class TestBasic708 : public RooUnitTest { public: - TestBasic708(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("B Physics p.d.f.s",refFile,writeRef,verbose,batchMode) {} ; + TestBasic708(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("B Physics p.d.f.s",refFile,writeRef,verbose) {} ; bool testCode() { //////////////////////////////////////////////////// @@ -5228,7 +5227,7 @@ class TestBasic708 : public RooUnitTest class TestBasic801 : public RooUnitTest { public: - TestBasic801(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("Automated MC studies",refFile,writeRef,verbose,batchMode) {} ; + TestBasic801(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("Automated MC studies",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l @@ -5281,7 +5280,7 @@ class TestBasic801 : public RooUnitTest // to speed up the study at the expemse of some precision RooMCStudy mcstudy{model,x,Binned(true),Silence(),Extended(), - FitOptions(Save(true),PrintEvalErrors(0),BatchMode(_batchMode))}; + FitOptions(Save(true),PrintEvalErrors(0))}; // G e n e r a t e a n d f i t e v e n t s @@ -5326,7 +5325,7 @@ class TestBasic801 : public RooUnitTest class TestBasic802 : public RooUnitTest { public: - TestBasic802(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("MC Study with chi^2 calculator",refFile,writeRef,verbose,batchMode) {} ; + TestBasic802(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("MC Study with chi^2 calculator",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l @@ -5347,7 +5346,7 @@ class TestBasic802 : public RooUnitTest // ---------------------------------------------------------------------------- // Create study manager for binned likelihood fits of a Gaussian pdf in 10 bins - RooMCStudy mcs{gauss,x,Silence(),Binned(),FitOptions(BatchMode(_batchMode))}; + RooMCStudy mcs{gauss,x,Silence(),Binned()}; // Add chi^2 calculator module to mcs RooChi2MCSModule chi2mod ; @@ -5379,7 +5378,7 @@ class TestBasic802 : public RooUnitTest // Create study manager with separate generation and fit model. This configuration // is set up to generate bad fits as the fit and generator model have different means // and the mean parameter is not floating in the fit - RooMCStudy mcs2{gauss2,x,FitModel(gauss),Silence(),Binned(),FitOptions(BatchMode(_batchMode))}; + RooMCStudy mcs2{gauss2,x,FitModel(gauss),Silence(),Binned()}; // Add chi^2 calculator module to mcs RooChi2MCSModule chi2mod2 ; @@ -5423,7 +5422,7 @@ class TestBasic802 : public RooUnitTest class TestBasic803 : public RooUnitTest { public: - TestBasic803(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("MC Study with param rand. and Z calc",refFile,writeRef,verbose,batchMode) {} ; + TestBasic803(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("MC Study with param rand. and Z calc",refFile,writeRef,verbose) {} ; bool testCode() { // C r e a t e m o d e l @@ -5459,7 +5458,7 @@ class TestBasic803 : public RooUnitTest // Configure manager to perform binned extended likelihood fits (Binned(),Extended()) on data generated // with a Poisson fluctuation on Nobs (Extended()) auto mcs = std::make_unique(model,mjjj,Binned(),Silence(),Extended(true), - FitOptions(Extended(true),PrintEvalErrors(-1),BatchMode(_batchMode))) ; + FitOptions(Extended(true),PrintEvalErrors(-1))) ; @@ -5539,9 +5538,9 @@ class TestBasic803 : public RooUnitTest class TestBasic804 : public RooUnitTest { public: - TestBasic804(TFile* refFile, bool writeRef, Int_t verbose, std::string const& batchMode) : RooUnitTest("MC Studies with aux. obs. constraints",refFile,writeRef,verbose,batchMode) {} ; + TestBasic804(TFile* refFile, bool writeRef, int verbose) : RooUnitTest("MC Studies with aux. obs. constraints",refFile,writeRef,verbose) {} ; - Double_t htol() { return 0.1 ; } // numerically very difficult test + double htol() { return 0.1 ; } // numerically very difficult test bool testCode() { @@ -5564,7 +5563,7 @@ class TestBasic804 : public RooUnitTest RooAddPdf sum("sum","sum",RooArgSet(g,p),f) ; // Construct constraint on parameter f - RooGaussian fconstraint("fconstraint","fconstraint",f,RooConst(0.7),RooConst(0.1)) ; + RooGaussian fconstraint("fconstraint","fconstraint",f,0.7,0.1) ; // Multiply constraint with p.d.f RooProdPdf sumc("sumc","sum with constraint",RooArgSet(sum,fconstraint)) ; @@ -5576,7 +5575,7 @@ class TestBasic804 : public RooUnitTest // Perform toy study with internal constraint on f //RooMCStudy mcs(sumc,x,Constrain(f),Silence(),Binned(),FitOptions(PrintLevel(-1))) ; - RooMCStudy mcs(sumc,x,Constrain(f),Binned(),FitOptions(BatchMode(_batchMode))) ; + RooMCStudy mcs(sumc,x,Constrain(f),Binned()); // Run 50 toys of 2000 events. // Before each toy is generated, a value for the f is sampled from the constraint pdf and diff --git a/test/stressRooStats.cxx b/test/stressRooStats.cxx index eef263e66c0f6..4883fac9d6227 100644 --- a/test/stressRooStats.cxx +++ b/test/stressRooStats.cxx @@ -8,6 +8,9 @@ #include #include +// Math headers +#include "Math/MinimizerOptions.h" + // ROOT headers #include "TWebFile.h" #include "TSystem.h" @@ -46,7 +49,7 @@ using namespace RooFit ; //////////////////////////////////////////////////////////////////////////////// /// Print test program number and its title -void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth) +void StatusPrint(const int id, const TString &title, const int status, const int lineWidth) { TString header = TString::Format("Test %d : %s ", id, title.Data()); cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl; @@ -55,9 +58,9 @@ void StatusPrint(const Int_t id, const TString &title, const Int_t status, const //////////////////////////////////////////////////////////////////////////////// /// width of lines when printing test results -Int_t stressRooStats(const char* refFile, bool writeRef, Int_t verbose, bool allTests, bool oneTest, Int_t testNumber, bool dryRun, bool doDump, bool doTreeStore) +int stressRooStats(const char* refFile, bool writeRef, int verbose, bool allTests, bool oneTest, int testNumber, bool dryRun, bool doDump, bool doTreeStore) { - const Int_t lineWidth = 120; + const int lineWidth = 120; // Save memory directory location auto memDir = gDirectory; @@ -199,7 +202,7 @@ Int_t stressRooStats(const char* refFile, bool writeRef, Int_t verbose, bool all int nFailed = 0; { - Int_t i; + int i; list::iterator iter; if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) { @@ -288,27 +291,27 @@ Int_t stressRooStats(const char* refFile, bool writeRef, Int_t verbose, bool all int main(int argc, const char *argv[]) { bool doWrite = false; - Int_t verbose = 0; + int verbose = 0; bool allTests = false; bool oneTest = false; - Int_t testNumber = 0; + int testNumber = 0; bool dryRun = false; bool doDump = false; bool doTreeStore = false; - std::string batchMode = "off"; + auto backend = RooFit::EvalBackend::Legacy(); //string refFileName = "http://root.cern.ch/files/stressRooStats_v534_ref.root" ; string refFileName = "stressRooStats_ref.root" ; string minimizerName = "Minuit"; // Parse command line arguments - for (Int_t i = 1 ; i < argc ; i++) { + for (int i = 1 ; i < argc ; i++) { string arg = argv[i] ; if (arg=="-b") { - std::string mode = argv[i+1]; - batchMode = mode; - std::cout << "stressRooStats: BatchMode set to " << mode << std::endl; + std::string mode = argv[++i]; + backend = RooFit::EvalBackend(mode); + std::cout << "stressRooStats: NLL evaluation backend set to " << mode << std::endl; } else if (arg == "-f") { cout << "stressRooStats: using reference file " << argv[i + 1] << endl ; refFileName = argv[++i] ; @@ -346,20 +349,21 @@ int main(int argc, const char *argv[]) } else if (arg == "-c") { cout << "stressRooStats: dumping comparison file for failed tests " << endl; doDump = true; - } else if (arg == "-h") { - cout << "usage: stressRooStats [ options ] " << endl; - cout << "" << endl; - cout << " -f : use given reference file instead of default (" << refFileName << ")" << endl; - cout << " -w : write reference file, instead of reading file and running comparison tests" << endl; - cout << " -n N : only run test with sequential number N" << endl; - cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl; - cout << " -c : dump file stressRooStats_DEBUG.root to which results of both current result and reference for each failed test are written" << endl; - cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl; - cout << " -min : minimizer name (default is Minuit2_ if available" << endl; - cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl; - cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; - cout << " -d N : set ROOT gDebug flag to N" << endl ; - cout << " " << endl ; + } else if (arg == "-h" || arg == "--help") { + cout << R"(usage: stressRooStats [ options ] + + -b : Perform every fit in the tests with the EvalBackend() command argument, where is a string + -f : use given reference file instead of default ("stressRooStats_ref.root") + -w : write reference file, instead of reading file and running comparison tests + -n N : only run test with sequential number N + -a : run full suite of tests (default is basic suite); this overrides the -n single test option + -c : dump file stressRooStats_DEBUG.root to which results of both current result and reference for each failed test are written + -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind + -min : minimizer name (default is Minuit, not Minuit2) + -vs : use vector-based storage for all datasets (default is tree-based storage) + -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well) + -d N : set ROOT gDebug flag to N +)"; return 0 ; } @@ -380,18 +384,10 @@ int main(int argc, const char *argv[]) // } // set minimizer - // use Minut2 if available - // check in case of Minuit2 and set Minuit in case we cannot use it - if (minimizerName == "Minuit2") { - int prec = gErrorIgnoreLevel; - gErrorIgnoreLevel = kFatal; - if (gSystem->Load("libMinuit2") < 0) minimizerName = "Minuit"; - gErrorIgnoreLevel=prec; - } ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerName.c_str()); - // set default BatchMode backend - RooFit::Experimental::defaultBatchMode() = batchMode; + // set default NLL backend + RooFit::EvalBackend::defaultValue() = backend.value(); gBenchmark = new TBenchmark(); return stressRooStats(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun, doDump, doTreeStore); @@ -399,18 +395,21 @@ int main(int argc, const char *argv[]) //////////////////////////////////////////////////////////////////////////////// -Int_t stressRooStats() +int stressRooStats() { bool doWrite = false; - Int_t verbose = 0; + int verbose = 0; bool allTests = false; bool oneTest = false; - Int_t testNumber = 0; + int testNumber = 0; bool dryRun = false; bool doDump = false; bool doTreeStore = false; string refFileName = "stressRooStats_ref.root"; + // in interpreted mode, the minimizer is hardcoded to Minuit 1 + ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit"); + return stressRooStats(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun, doDump, doTreeStore); } diff --git a/test/stressRooStats_models.h b/test/stressRooStats_models.h index cae0cdd9b3975..7778f786287c0 100644 --- a/test/stressRooStats_models.h +++ b/test/stressRooStats_models.h @@ -26,22 +26,22 @@ void buildSimultaneousModel(RooWorkspace *w) w->factory("SIMUL::sim_pdf(index[cat1,cat2],cat1=ext_pdf1,cat2=ext_pdf2)"); // create combined signal + background model configuration - ModelConfig *sbModel = new ModelConfig("S+B", w); - sbModel->SetObservables("x1,x2,index"); - sbModel->SetParametersOfInterest("sig"); - sbModel->SetGlobalObservables("gbkg1,gbkg2"); - sbModel->SetNuisanceParameters("bkg1,bkg2"); - sbModel->SetPdf("sim_pdf"); - w->import(*sbModel); + ModelConfig sbModel{"S+B", w}; + sbModel.SetObservables("x1,x2,index"); + sbModel.SetParametersOfInterest("sig"); + sbModel.SetGlobalObservables("gbkg1,gbkg2"); + sbModel.SetNuisanceParameters("bkg1,bkg2"); + sbModel.SetPdf("sim_pdf"); + w->import(sbModel); // create combined background model configuration - ModelConfig *bModel = new ModelConfig(*sbModel); - bModel->SetName("B"); - w->import(*bModel); + ModelConfig bModel{sbModel}; + bModel.SetName("B"); + w->import(bModel); // define data set RooRandom::randomGenerator()->Rndm(); //wast a number to get a better dataset (not too high significance) and closer to expected - RooDataSet *data = w->pdf("sim_pdf")->generate(*sbModel->GetObservables(), Extended(), Name("data")); + std::unique_ptr data{w->pdf("sim_pdf")->generate(*sbModel.GetObservables(), Extended(), Name("data"))}; w->import(*data); } @@ -135,21 +135,20 @@ void buildPoissonEfficiencyModel(RooWorkspace *w) w->factory("PROD::pdf(poiss, constrb, constre)"); // create model configuration - ModelConfig *sbModel = new ModelConfig("S+B", w); - sbModel->SetObservables("x"); - sbModel->SetParametersOfInterest("sig"); - sbModel->SetNuisanceParameters("b1,e1"); - sbModel->SetGlobalObservables("b0,e0"); - sbModel->SetPdf("pdf"); - w->import(*sbModel); - - ModelConfig *bModel = new ModelConfig(*sbModel); - bModel->SetName("B"); - w->import(*bModel); + ModelConfig sbModel{"S+B", w}; + sbModel.SetObservables("x"); + sbModel.SetParametersOfInterest("sig"); + sbModel.SetNuisanceParameters("b1,e1"); + sbModel.SetGlobalObservables("b0,e0"); + sbModel.SetPdf("pdf"); + w->import(sbModel); + + ModelConfig bModel{sbModel}; + bModel.SetName("B"); + w->import(bModel); // define data set and import it into workspace - RooDataSet *data = new RooDataSet("data", "data", *sbModel->GetObservables()); - w->import(*data); + w->import(RooDataSet("data", "data", *sbModel.GetObservables())); } diff --git a/test/stressRooStats_tests.h b/test/stressRooStats_tests.h index 007d18c3f32d8..d16ade4b9a51e 100644 --- a/test/stressRooStats_tests.h +++ b/test/stressRooStats_tests.h @@ -135,16 +135,16 @@ class TestProfileLikelihoodCalculator1 : public RooUnitTest { //TODO: see why it fails for a small number of observations // Create Gaussian model, generate data set and define - RooWorkspace* w = new RooWorkspace("w"); - w->factory("Gaussian::gauss(x[-5,5], mean[0,-5,5], sigma[1])"); - RooDataSet *data = w->pdf("gauss")->generate(*w->var("x"), N); + RooWorkspace ws{"w"}; + ws.factory("Gaussian::gauss(x[-5,5], mean[0,-5,5], sigma[1])"); + std::unique_ptr data{ws.pdf("gauss")->generate(*ws.var("x"), N)}; if (_write == true) { // Calculate likelihood interval from data via analytic methods - Double_t estMean = data->mean(*w->var("x")); + Double_t estMean = data->mean(*ws.var("x")); Double_t intervalHalfWidth = - normal_quantile_c((1.0 - fConfidenceLevel) / 2.0, w->var("sigma")->getValV() / sqrt((double)N)); + normal_quantile_c((1.0 - fConfidenceLevel) / 2.0, ws.var("sigma")->getValV() / sqrt((double)N)); Double_t lowerLimit = estMean - intervalHalfWidth; Double_t upperLimit = estMean + intervalHalfWidth; @@ -155,23 +155,19 @@ class TestProfileLikelihoodCalculator1 : public RooUnitTest { } else { // Calculate likelihood interval using the ProfileLikelihoodCalculator - ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*data, *w->pdf("gauss"), *w->var("mean")); + ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*data, *ws.pdf("gauss"), *ws.var("mean")); plc->SetConfidenceLevel(fConfidenceLevel); LikelihoodInterval *interval = plc->GetInterval(); // Register analytically computed limits in the reference file - regValue(interval->LowerLimit(*w->var("mean")), lowerLimitString); - regValue(interval->UpperLimit(*w->var("mean")), upperLimitString); + regValue(interval->LowerLimit(*ws.var("mean")), lowerLimitString); + regValue(interval->UpperLimit(*ws.var("mean")), upperLimitString); // Cleanup branch objects delete plc; delete interval; } - // Cleanup local objects - delete data; - delete w; - return true ; } }; @@ -256,7 +252,7 @@ class TestProfileLikelihoodCalculator2 : public RooUnitTest { // Create Poisson model and dataset RooWorkspace* w = new RooWorkspace("w"); - w->factory(TString::Format("Poisson::poiss(x[%d,0,1000], mean[0,1000])", fObsValue)); + w->factory(TString::Format("Poisson::poiss(x[%d,0,1000], mean[0,1000])", fObsValue).Data()); RooDataSet *data = new RooDataSet("data", "data", *w->var("x")); data->add(*w->var("x")); @@ -354,9 +350,8 @@ class TestProfileLikelihoodCalculator3 : public RooUnitTest { w->var("y")->setVal(fObsValueY); w->data("data")->add(*model->GetObservables()); - const RooArgSet * initialVariables = model->GetPdf()->getVariables(); + std::unique_ptr initialVariables{model->GetPdf()->getVariables()}; w->saveSnapshot("initialVariables",*initialVariables); - delete initialVariables; // build likelihood interval with ProfileLikelihoodCalculator ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*w->data("data"), *model); @@ -621,7 +616,7 @@ class TestBayesianCalculator1 : public RooUnitTest { w->factory("Uniform::prior(mean)"); w->import(*(new RooCFunction1PdfBinding("priorInv", "priorInv", &priorInv, *w->var("mean")))); w->import(*(new RooCFunction1PdfBinding("priorInvSqrt", "priorInvSqrt", priorInvSqrt, *w->var("mean")))); - w->factory(TString::Format("Gamma::priorGamma(mean, %lf, %lf, 0)", gammaShape, gammaRate)); + w->factory(TString::Format("Gamma::priorGamma(mean, %lf, %lf, 0)", gammaShape, gammaRate).Data()); // build argument sets and data set w->defineSet("obs", "x"); @@ -876,9 +871,8 @@ class TestBayesianCalculator3 : public RooUnitTest { w->var("y")->setVal(fObsValueY); w->data("data")->add(*model->GetObservables()); - const RooArgSet * initialVariables = model->GetPdf()->getVariables(); + std::unique_ptr initialVariables{model->GetPdf()->getVariables()}; w->saveSnapshot("initialVariables",*initialVariables); - delete initialVariables; // NOTE: Roo1DIntegrator is too slow and gives poor results #ifdef R__HAS_MATHMORE @@ -1004,9 +998,8 @@ class TestMCMCCalculator : public RooUnitTest { w->var("y")->setVal(fObsValueY); w->data("data")->add(*model->GetObservables()); - const RooArgSet * initialVariables = model->GetPdf()->getVariables(); + std::unique_ptr initialVariables{model->GetPdf()->getVariables()}; w->saveSnapshot("initialVariables",*initialVariables); - delete initialVariables; // NOTE: Roo1DIntegrator is too slow and gives poor results #ifdef R__HAS_MATHMORE @@ -1487,9 +1480,8 @@ class TestHypoTestInverter1 : public RooUnitTest { w->var("y")->setVal(fObsValueY); w->data("data")->add(*sbModel->GetObservables()); - const RooArgSet * initialVariables = sbModel->GetPdf()->getVariables(); + std::unique_ptr initialVariables{sbModel->GetPdf()->getVariables()}; w->saveSnapshot("initialVariables",*initialVariables); - delete initialVariables; // set snapshots w->var("sig")->setVal(fObsValueX - w->var("bkg1")->getValV()); @@ -1657,9 +1649,8 @@ class TestHypoTestInverter2 : public RooUnitTest { w->var("x")->setVal(fObsValueX); w->data("data")->add(*sbModel->GetObservables()); - const RooArgSet * initialVariables = sbModel->GetPdf()->getVariables(); + std::unique_ptr initialVariables{sbModel->GetPdf()->getVariables()}; w->saveSnapshot("initialVariables",*initialVariables); - delete initialVariables; // set snapshots sbModel->SetSnapshot(*sbModel->GetParametersOfInterest()); @@ -1801,8 +1792,8 @@ class TestHypoTestCalculator : public RooUnitTest { // Make model for prototype on/off problem // Pois(x | s+b) * Pois(y | tau b ) RooWorkspace* w = new RooWorkspace("w"); - w->factory(TString::Format("Poisson::on_pdf(x[%d,0,500],sum::splusb(sig[0,0,100],bkg[100,0,300]))", xValue)); - w->factory(TString::Format("Poisson::off_pdf(y[%d,0,500],prod::taub(tau[%lf],bkg))", yValue, tauValue)); + w->factory(TString::Format("Poisson::on_pdf(x[%d,0,500],sum::splusb(sig[0,0,100],bkg[100,0,300]))", xValue).Data()); + w->factory(TString::Format("Poisson::off_pdf(y[%d,0,500],prod::taub(tau[%lf],bkg))", yValue, tauValue).Data()); w->factory("PROD::prod_pdf(on_pdf, off_pdf)"); w->var("x")->setVal(xValue); diff --git a/test/stressTMVA.cxx b/test/stressTMVA.cxx index 128e8d927a1cf..5047d85e2b0cc 100644 --- a/test/stressTMVA.cxx +++ b/test/stressTMVA.cxx @@ -2246,6 +2246,10 @@ void MethodUnitTestWithROCLimits::run() for (int i=0;i1.e-2) std::cout << \"maxdiff=\"<2.e-4) ok=false;" << std::endl; fout << "testFile->Close();" << std::endl; + fout << "delete testFile;" << std::endl; fout << "if (!ok) {" << std::endl; fout << "std::cout << \"maxdiff=\"<Close(); + delete outputFile; delete dataloader; delete factory; delete input; @@ -2577,6 +2583,7 @@ void RegressionUnitTestWithDeviation::run() test_(stuckCountClose(); + delete testFile; for (int i=0;iClose(); + delete outputFile; + if (input) delete input; delete dataloader; delete factory; } @@ -2840,6 +2849,7 @@ bool MethodUnitTestWithComplexData::create_data(const char* filename, int nmax) dataFile->Write(); dataFile->Close(); + delete dataFile; return true; } diff --git a/test/stressVector.cxx b/test/stressVector.cxx index 83b86fb2b4865..b0ba21e845d2c 100644 --- a/test/stressVector.cxx +++ b/test/stressVector.cxx @@ -540,7 +540,7 @@ int main(int argc,const char *argv[]) { s1=a.testDeltaR (v1, t, t1, "DeltaR TLorentzVector " ); s2=a.testDeltaR (v2, t, t2, "DeltaR XYZTVector " ); s3=a.testDeltaR (v3, t, t3, "DeltaR PtEtaPhiEVector " ); - a.check("DeltaR",s1,s2,s3,15); + a.check("DeltaR",s1,s2,s3,20); int n1, n2, n3; diff --git a/tmva/pymva/inc/TMVA/MethodPyKeras.h b/tmva/pymva/inc/TMVA/MethodPyKeras.h index e956fcd5dcdb6..1e786e9965a2a 100644 --- a/tmva/pymva/inc/TMVA/MethodPyKeras.h +++ b/tmva/pymva/inc/TMVA/MethodPyKeras.h @@ -97,14 +97,17 @@ namespace TMVA { TString fUserCodeName; // filename of an optional user script that will be executed before loading the Keras model TString fKerasString; // string identifying keras or tf.keras - bool fModelIsSetup = false; // flag whether model is loaded, needed for getMvaValue during evaluation - float* fVals = nullptr; // variables array used for GetMvaValue + bool fModelIsSetup = false; // flag whether current model is setup for being used + bool fModelIsSetupForEval = false; // flag to indicate whether model is setup for evaluation + std::vector fVals; // variables array used for GetMvaValue std::vector fOutput; // probability or regression output array used for GetMvaValue UInt_t fNVars {0}; // number of variables UInt_t fNOutputs {0}; // number of outputs (classes or targets) TString fFilenameTrainedModel; // output filename for trained model + void InitKeras(); // initialize Keras (importing the readed modules) void SetupKerasModel(Bool_t loadTrainedModel); // setups the needed variables, loads the model + void SetupKerasModelForEval(); // optimizes model for evaluation UInt_t GetNumValidationSamples(); // get number of validation events according to given option ClassDef(MethodPyKeras, 0); diff --git a/tmva/pymva/inc/TMVA/PyMethodBase.h b/tmva/pymva/inc/TMVA/PyMethodBase.h index 111fabff99f22..6f6acdff1b74b 100644 --- a/tmva/pymva/inc/TMVA/PyMethodBase.h +++ b/tmva/pymva/inc/TMVA/PyMethodBase.h @@ -83,8 +83,6 @@ namespace TMVA { static void PyInitialize(); static int PyIsInitialized(); static void PyFinalize(); - static void PySetProgramName(TString name); - static TString Py_GetProgramName(); PyObject *Eval(TString code); // required to parse booking options from string to pyobjects static void Serialize(TString file,PyObject *classifier); @@ -141,6 +139,7 @@ namespace TMVA { static const char* PyStringAsString(PyObject *string); // Python Utility function for converting a Python String object to const char* static std::vector GetDataFromTuple(PyObject *tupleObject); // Function casts Python Tuple object into vector of size_t static std::vector GetDataFromList(PyObject *listObject); // Function casts Python List object into vector of size_t + static PyObject* GetValueFromDict(PyObject* dict, const char* key); // Function to check for a key in dict and return the associated value if present ClassDef(PyMethodBase, 0) // Virtual base class for all TMVA method }; diff --git a/tmva/pymva/src/MethodPyGTB.cxx b/tmva/pymva/src/MethodPyGTB.cxx index 7b994722e0b35..56b76ba06b6b3 100644 --- a/tmva/pymva/src/MethodPyGTB.cxx +++ b/tmva/pymva/src/MethodPyGTB.cxx @@ -65,7 +65,7 @@ MethodPyGTB::MethodPyGTB(const TString &jobName, DataSetInfo &dsi, const TString &theOption) : PyMethodBase(jobName, Types::kPyGTB, methodTitle, dsi, theOption), - fLoss("deviance"), + fLoss("log_loss"), fLearningRate(0.1), fNestimators(100), fSubsample(1.0), @@ -85,7 +85,7 @@ MethodPyGTB::MethodPyGTB(const TString &jobName, //_______________________________________________________________________ MethodPyGTB::MethodPyGTB(DataSetInfo &theData, const TString &theWeightFile) : PyMethodBase(Types::kPyGTB, theData, theWeightFile), - fLoss("deviance"), + fLoss("log_loss"), fLearningRate(0.1), fNestimators(100), fSubsample(1.0), @@ -122,9 +122,9 @@ void MethodPyGTB::DeclareOptions() { MethodBase::DeclareCompatibilityOptions(); - DeclareOptionRef(fLoss, "Loss", "{'deviance', 'exponential'}, optional (default='deviance')\ - loss function to be optimized. 'deviance' refers to\ - deviance (= logistic regression) for classification\ + DeclareOptionRef(fLoss, "Loss", "{'log_loss', 'exponential'}, optional (default='log_loss')\ + loss function to be optimized. 'log_loss' refers to\ + logistic loss for classification\ with probabilistic outputs. For loss 'exponential' gradient\ boosting recovers the AdaBoost algorithm."); @@ -197,9 +197,9 @@ void MethodPyGTB::DeclareOptions() // Check options and load them to local python namespace void MethodPyGTB::ProcessOptions() { - if (fLoss != "deviance" && fLoss != "exponential") { + if (fLoss != "log_loss" && fLoss != "exponential") { Log() << kFATAL << Form("Loss = %s ... that does not work!", fLoss.Data()) - << " The options are 'deviance' or 'exponential'." << Endl; + << " The options are 'log_loss' or 'exponential'." << Endl; } pLoss = Eval(Form("'%s'", fLoss.Data())); PyDict_SetItemString(fLocalNS, "loss", pLoss); diff --git a/tmva/pymva/src/MethodPyKeras.cxx b/tmva/pymva/src/MethodPyKeras.cxx index 47a087b5b02e9..c915ab70018d4 100644 --- a/tmva/pymva/src/MethodPyKeras.cxx +++ b/tmva/pymva/src/MethodPyKeras.cxx @@ -16,6 +16,7 @@ #include "TMVA/Tools.h" #include "TMVA/Timer.h" #include "TSystem.h" +#include "Math/Util.h" using namespace TMVA; @@ -38,6 +39,7 @@ ClassImp(MethodPyKeras); MethodPyKeras::MethodPyKeras(const TString &jobName, const TString &methodTitle, DataSetInfo &dsi, const TString &theOption) : PyMethodBase(jobName, Types::kPyKeras, methodTitle, dsi, theOption) { fNumEpochs = 10; + fNumThreads = 0; fBatchSize = 100; fVerbose = 1; fContinueTraining = false; @@ -159,7 +161,7 @@ UInt_t TMVA::MethodPyKeras::GetNumValidationSamples() /// Function processing the options /// This is called only when creating the method before training not when -/// readinf from XML file. Called from MethodBase::ProcessSetup +/// reading from XML file. Called from MethodBase::ProcessSetup /// that is called from Factory::BookMethod void MethodPyKeras::ProcessOptions() { @@ -168,14 +170,15 @@ void MethodPyKeras::ProcessOptions() { fFilenameTrainedModel = GetWeightFileDir() + "/TrainedModel_" + GetName() + ".h5"; } + InitKeras(); + // Setup model, either the initial model from `fFilenameModel` or // the trained model from `fFilenameTrainedModel` if (fContinueTraining) Log() << kINFO << "Continue training with trained model" << Endl; SetupKerasModel(fContinueTraining); } -void MethodPyKeras::SetupKerasModel(bool loadTrainedModel) { - +void MethodPyKeras::InitKeras() { // initialize first Keras. This is done only here when class has // all state variable set from options or read from XML file // Import Keras @@ -315,6 +318,9 @@ void MethodPyKeras::SetupKerasModel(bool loadTrainedModel) { } } +} + +void MethodPyKeras::SetupKerasModel(bool loadTrainedModel) { /* * Load Keras model from file */ @@ -362,19 +368,44 @@ void MethodPyKeras::SetupKerasModel(bool loadTrainedModel) { else if (GetAnalysisType() == Types::kRegression) fNOutputs = DataInfo().GetNTargets(); else Log() << kFATAL << "Selected analysis type is not implemented" << Endl; - // Init evaluation (needed for getMvaValue) - fVals = new float[fNVars]; // holds values used for classification and regression - npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)fNVars}; - PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (void*)fVals); - PyDict_SetItemString(fLocalNS, "vals", (PyObject*)pVals); - - fOutput.resize(fNOutputs); // holds classification probabilities or regression output - npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)fNOutputs}; - PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (void*)&fOutput[0]); - PyDict_SetItemString(fLocalNS, "output", (PyObject*)pOutput); - // Mark the model as setup fModelIsSetup = true; + fModelIsSetupForEval = false; +} + +///Setting up model for evaluation +/// Add here some needed optimizations like disabling eager execution +void MethodPyKeras::SetupKerasModelForEval() { + + InitKeras(); + + // disable eager execution (model will evaluate > 100 faster) + // need to be done before loading the model +#ifndef R__MACOSX // problem siabling eager execution on Macos (conflict with multiprocessing) + if (fUseTFKeras){ + PyRunString("tf.compat.v1.disable_eager_execution()","Failed to disable eager execution"); + Log() << kINFO << "Disabled TF eager execution when evaluating model " << Endl; + } +#endif + + SetupKerasModel(true); + + // Init evaluation (needed for getMvaValue) + if (fNVars > 0) { + fVals.resize(fNVars); // holds values used for classification and regression + npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)fNVars}; + PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (void*)fVals.data()); + PyDict_SetItemString(fLocalNS, "vals", (PyObject*)pVals); + } + // setup output variables + if (fNOutputs > 0) { + fOutput.resize(fNOutputs); // holds classification probabilities or regression output + npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)fNOutputs}; + PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (void*)fOutput.data()); + PyDict_SetItemString(fLocalNS, "output", (PyObject*)pOutput); + } + + fModelIsSetupForEval = true; } /// Initialization function called from MethodBase::SetupMethod() @@ -394,6 +425,7 @@ void MethodPyKeras::Init() { // Set flag that model is not setup fModelIsSetup = false; + fModelIsSetupForEval = false; } void MethodPyKeras::Train() { @@ -634,16 +666,18 @@ Double_t MethodPyKeras::GetMvaValue(Double_t *errLower, Double_t *errUpper) { // Check whether the model is setup // NOTE: unfortunately this is needed because during evaluation ProcessOptions is not called again - if (!fModelIsSetup) { + if (!fModelIsSetupForEval) { // Setup the trained model - SetupKerasModel(true); + SetupKerasModelForEval(); } // Get signal probability (called mvaValue here) const TMVA::Event* e = GetEvent(); for (UInt_t i=0; iGetValue(i); - PyRunString("for i,p in enumerate(model.predict(vals)): output[i]=p\n", - "Failed to get predictions"); + int verbose = (int) Verbose(); + std::string code = "for i,p in enumerate(model.predict(vals, verbose=" + ROOT::Math::Util::ToString(verbose) + + ")): output[i]=p\n"; + PyRunString(code,"Failed to get predictions"); return fOutput[TMVA::Types::kSignal]; } @@ -651,9 +685,9 @@ Double_t MethodPyKeras::GetMvaValue(Double_t *errLower, Double_t *errUpper) { std::vector MethodPyKeras::GetMvaValues(Long64_t firstEvt, Long64_t lastEvt, Bool_t logProgress) { // Check whether the model is setup // NOTE: Unfortunately this is needed because during evaluation ProcessOptions is not called again - if (!fModelIsSetup) { + if (!fModelIsSetupForEval) { // Setup the trained model - SetupKerasModel(true); + SetupKerasModelForEval(); } // Load data to numpy array @@ -680,6 +714,7 @@ std::vector MethodPyKeras::GetMvaValues(Long64_t firstEvt, Long64_t la } } + std::vector mvaValues(nEvents); npy_intp dimsData[2] = {(npy_intp)nEvents, (npy_intp)fNVars}; PyArrayObject* pDataMvaValues = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsData, NPY_FLOAT, (void*)data); if (pDataMvaValues==0) Log() << "Failed to load data to Python array" << Endl; @@ -690,11 +725,10 @@ std::vector MethodPyKeras::GetMvaValues(Long64_t firstEvt, Long64_t la PyArrayObject* pPredictions = (PyArrayObject*) PyObject_CallMethod(pModel, (char*)"predict", (char*)"O", pDataMvaValues); if (pPredictions==0) Log() << kFATAL << "Failed to get predictions" << Endl; delete[] data; - // Load predictions to double vector // NOTE: The signal probability is given at the output - std::vector mvaValues(nEvents); float* predictionsData = (float*) PyArray_DATA(pPredictions); + for (UInt_t i=0; i MethodPyKeras::GetMvaValues(Long64_t firstEvt, Long64_t la std::vector& MethodPyKeras::GetRegressionValues() { // Check whether the model is setup // NOTE: unfortunately this is needed because during evaluation ProcessOptions is not called again - if (!fModelIsSetup){ + if (!fModelIsSetupForEval){ // Setup the model and load weights - SetupKerasModel(true); + //std::cout << "setup model for evaluation" << std::endl; + //PyRunString("tf.compat.v1.disable_eager_execution()","Failed to disable eager execution"); + SetupKerasModelForEval(); } // Get regression values const TMVA::Event* e = GetEvent(); for (UInt_t i=0; iGetValue(i); - PyRunString("for i,p in enumerate(model.predict(vals)): output[i]=p\n", - "Failed to get predictions"); + int verbose = (int) Verbose(); + std::string code = "for i,p in enumerate(model.predict(vals, verbose=" + ROOT::Math::Util::ToString(verbose) + + ")): output[i]=p\n"; + PyRunString(code,"Failed to get predictions"); // Use inverse transformation of targets to get final regression values Event * eTrans = new Event(*e); @@ -740,16 +778,18 @@ std::vector& MethodPyKeras::GetRegressionValues() { std::vector& MethodPyKeras::GetMulticlassValues() { // Check whether the model is setup // NOTE: unfortunately this is needed because during evaluation ProcessOptions is not called again - if (!fModelIsSetup){ + if (!fModelIsSetupForEval){ // Setup the model and load weights - SetupKerasModel(true); + SetupKerasModelForEval(); } // Get class probabilites const TMVA::Event* e = GetEvent(); for (UInt_t i=0; iGetValue(i); - PyRunString("for i,p in enumerate(model.predict(vals)): output[i]=p\n", - "Failed to get predictions"); + int verbose = (int) Verbose(); + std::string code = "for i,p in enumerate(model.predict(vals, verbose=" + ROOT::Math::Util::ToString(verbose) + + ")): output[i]=p\n"; + PyRunString(code,"Failed to get predictions"); return fOutput; } diff --git a/tmva/pymva/src/MethodPyRandomForest.cxx b/tmva/pymva/src/MethodPyRandomForest.cxx index 2275bab511e4e..3424d80164321 100644 --- a/tmva/pymva/src/MethodPyRandomForest.cxx +++ b/tmva/pymva/src/MethodPyRandomForest.cxx @@ -69,7 +69,7 @@ MethodPyRandomForest::MethodPyRandomForest(const TString &jobName, fMinSamplesSplit(2), fMinSamplesLeaf(1), fMinWeightFractionLeaf(0), - fMaxFeatures("'auto'"), + fMaxFeatures("'sqrt'"), fMaxLeafNodes("None"), fBootstrap(kTRUE), fOobScore(kFALSE), @@ -90,7 +90,7 @@ MethodPyRandomForest::MethodPyRandomForest(DataSetInfo &theData, const TString & fMinSamplesSplit(2), fMinSamplesLeaf(1), fMinWeightFractionLeaf(0), - fMaxFeatures("'auto'"), + fMaxFeatures("'sqrt'"), fMaxLeafNodes("None"), fBootstrap(kTRUE), fOobScore(kFALSE), @@ -234,7 +234,8 @@ void MethodPyRandomForest::ProcessOptions() pMinWeightFractionLeaf = Eval(Form("%f", fMinWeightFractionLeaf)); PyDict_SetItemString(fLocalNS, "minWeightFractionLeaf", pMinWeightFractionLeaf); - if (fMaxFeatures == "auto" || fMaxFeatures == "sqrt" || fMaxFeatures == "log2"){ + if (fMaxFeatures == "auto") fMaxFeatures = "sqrt"; // change in API from v 1.11 + if (fMaxFeatures == "sqrt" || fMaxFeatures == "log2"){ fMaxFeatures = Form("'%s'", fMaxFeatures.Data()); } pMaxFeatures = Eval(fMaxFeatures); @@ -428,9 +429,9 @@ std::vector MethodPyRandomForest::GetMvaValues(Long64_t firstEvt, Long Py_DECREF(pEvent); Py_DECREF(result); - + if (logProgress) { - Log() << kINFO + Log() << kINFO << "Elapsed time for evaluation of " << nEvents << " events: " << timer.GetElapsedTime() << " " << Endl; } diff --git a/tmva/pymva/src/PyMethodBase.cxx b/tmva/pymva/src/PyMethodBase.cxx index a30c5b8b72993..7a5f3d5c6610b 100644 --- a/tmva/pymva/src/PyMethodBase.cxx +++ b/tmva/pymva/src/PyMethodBase.cxx @@ -26,8 +26,6 @@ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include -#include - using namespace TMVA; namespace TMVA { @@ -122,6 +120,8 @@ PyMethodBase::PyMethodBase(Types::EMVA methodType, PyMethodBase::~PyMethodBase() { // should we delete here fLocalNS ? + //PyFinalize(); + if (fLocalNS) Py_DECREF(fLocalNS); } /////////////////////////////////////////////////////////////////////////////// @@ -245,40 +245,6 @@ void PyMethodBase::PyFinalize() Py_Finalize(); } -/////////////////////////////////////////////////////////////////////////////// -/// Set program name for Python interpeter -/// -/// \param[in] name Program name - -void PyMethodBase::PySetProgramName(TString name) -{ - #if PY_MAJOR_VERSION < 3 - Py_SetProgramName(const_cast(name.Data())); - #else - Py_SetProgramName((wchar_t *)name.Data()); - #endif -} - - -/////////////////////////////////////////////////////////////////////////////// - -size_t mystrlen(const char* s) { return strlen(s); } - -/////////////////////////////////////////////////////////////////////////////// - -size_t mystrlen(const wchar_t* s) { return wcslen(s); } - -/////////////////////////////////////////////////////////////////////////////// -/// Get program name from Python interpreter -/// -/// \return Program name - -TString PyMethodBase::Py_GetProgramName() -{ - auto progName = ::Py_GetProgramName(); - return std::string(progName, progName + mystrlen(progName)); -} - /////////////////////////////////////////////////////////////////////////////// /// Check Python interpreter initialization status /// @@ -357,6 +323,7 @@ Int_t PyMethodBase::UnSerialize(TString path, PyObject **obj) /// Py_single_input, Py_file_input) void PyMethodBase::PyRunString(TString code, TString errorMessage, int start) { + //std::cout << "Run: >> " << code << std::endl; fPyReturn = PyRun_String(code, start, fGlobalNS, fLocalNS); if (!fPyReturn) { Log() << kWARNING << "Failed to run python code: " << code << Endl; @@ -431,3 +398,23 @@ std::vector PyMethodBase::GetDataFromList(PyObject* listObject){ } return listVec; } + +////////////////////////////////////////////////////////////////////////////////// +/// \brief Utility function which checks if a given key is present in a Python +/// dictionary object and returns the associated value or throws runtime +/// error. This is to replace PyDict_GetItemWithError in Python 2. +/// +/// \param[in] listObject Python Dict object +/// \return Associated value PyObject +PyObject* PyMethodBase::GetValueFromDict(PyObject* dict, const char* key){ + #if PY_MAJOR_VERSION >= 3 // using PyDict_GetItemWithError that is available only in Python3 + return PyDict_GetItemWithError(dict,PyUnicode_FromString(key)); + #else + if(!PyDict_Contains(dict, PyUnicode_FromString(key))){ + throw std::runtime_error(std::string("Key ")+key+" does not exist in the dictionary."); + } else { + return PyDict_GetItemString(dict, key); + } + #endif +} + diff --git a/tmva/pymva/src/RModelParser_Keras.cxx b/tmva/pymva/src/RModelParser_Keras.cxx index 4acc3f69b14ed..1938e29f1dd17 100644 --- a/tmva/pymva/src/RModelParser_Keras.cxx +++ b/tmva/pymva/src/RModelParser_Keras.cxx @@ -34,6 +34,7 @@ namespace PyKeras{ static void(& PyRunString)(TString, PyObject*, PyObject*) = PyMethodBase::PyRunString; static const char*(& PyStringAsString)(PyObject*) = PyMethodBase::PyStringAsString; static std::vector(& GetDataFromTuple)(PyObject*) = PyMethodBase::GetDataFromTuple; +static PyObject*(& GetValueFromDict)(PyObject*, const char*) = PyMethodBase::GetValueFromDict; namespace INTERNAL{ @@ -45,6 +46,7 @@ std::unique_ptr MakeKerasActivation(PyObject *fLayer); // For insta std::unique_ptr MakeKerasReLU(PyObject *fLayer); // For instantiating ROperator for Keras ReLU layer std::unique_ptr MakeKerasSelu(PyObject *fLayer); // For instantiating ROperator for Keras Selu layer std::unique_ptr MakeKerasSigmoid(PyObject *fLayer); // For instantiating ROperator for Keras Sigmoid layer +std::unique_ptr MakeKerasSwish(PyObject *fLayer); // For instantiating ROperator for Keras Swish layer std::unique_ptr MakeKerasPermute(PyObject *fLayer); // For instantiating ROperator for Keras Permute Layer std::unique_ptr MakeKerasBatchNorm(PyObject *fLayer); // For instantiating ROperator for Keras Batch Normalization Layer std::unique_ptr MakeKerasReshape(PyObject *fLayer); // For instantiating ROperator for Keras Reshape Layer @@ -53,6 +55,7 @@ std::unique_ptr MakeKerasBinary(PyObject *fLayer); // For insta std::unique_ptr MakeKerasSoftmax(PyObject *fLayer); // For instantiating ROperator for Keras Softmax Layer std::unique_ptr MakeKerasTanh(PyObject *fLayer); // For instantiating ROperator for Keras Tanh Layer std::unique_ptr MakeKerasLeakyRelu(PyObject *fLayer); // For instantiating ROperator for Keras LeakyRelu Layer +std::unique_ptr MakeKerasIdentity(PyObject *fLayer); // For instantiating ROperator for Keras Identity Layer // Declaring Internal function for Keras layers which have additional activation attribute @@ -69,12 +72,15 @@ const KerasMethodMap mapKerasLayer = { {"BatchNormalization", &MakeKerasBatchNorm}, {"Reshape", &MakeKerasReshape}, {"Concatenate", &MakeKerasConcat}, + {"swish", &MakeKerasSwish}, {"Add", &MakeKerasBinary}, {"Subtract", &MakeKerasBinary}, {"Multiply", &MakeKerasBinary}, {"Softmax", &MakeKerasSoftmax}, {"tanh", &MakeKerasTanh}, {"LeakyReLU", &MakeKerasLeakyRelu}, + {"Identity", &MakeKerasIdentity}, + {"Dropout", &MakeKerasIdentity}, // For activation layers {"ReLU", &MakeKerasReLU}, @@ -134,12 +140,12 @@ const KerasMethodMapWithActivation mapKerasLayerWithActivation = { /// 'layerWeight' : List of weight tensor names of Keras layers /// } void AddKerasLayer(RModel& rmodel, PyObject* fLayer){ - std::string fLayerType = PyStringAsString(PyDict_GetItemString(fLayer,"layerType")); + std::string fLayerType = PyStringAsString(GetValueFromDict(fLayer,"layerType")); if(fLayerType == "Reshape"){ - PyObject* fAttributes=PyDict_GetItemString(fLayer,"layerAttributes"); - std::string fLayerName = PyStringAsString(PyDict_GetItemString(fAttributes,"_name")); - PyObject* fPTargetShape = PyDict_GetItemString(fAttributes,"target_shape"); + PyObject* fAttributes=GetValueFromDict(fLayer,"layerAttributes"); + std::string fLayerName = PyStringAsString(GetValueFromDict(fAttributes,"_name")); + PyObject* fPTargetShape = GetValueFromDict(fAttributes,"target_shape"); std::vectorfTargetShape = GetDataFromTuple(fPTargetShape); std::shared_ptr fData(malloc(fTargetShape.size() * sizeof(int64_t)), free); std::copy(fTargetShape.begin(),fTargetShape.end(),(int64_t*)fData.get()); @@ -156,11 +162,11 @@ void AddKerasLayer(RModel& rmodel, PyObject* fLayer){ //For layers like Dense & Conv which has additional activation attribute else if(mapKerasLayerWithActivation.find(fLayerType) != mapKerasLayerWithActivation.end()){ findLayer = mapKerasLayerWithActivation.find(fLayerType); - PyObject* fAttributes=PyDict_GetItemString(fLayer,"layerAttributes"); + PyObject* fAttributes=GetValueFromDict(fLayer,"layerAttributes"); - std::string fLayerName = PyStringAsString(PyDict_GetItemString(fAttributes,"_name")); - - PyObject* fPActivation = PyDict_GetItemString(fAttributes,"activation"); + std::string fLayerName = PyStringAsString(GetValueFromDict(fAttributes,"_name")); + + PyObject* fPActivation = GetValueFromDict(fAttributes,"activation"); std::string fLayerActivation = PyStringAsString(PyObject_GetAttrString(fPActivation,"__name__")); if(fLayerActivation == "selu" || fLayerActivation == "sigmoid") @@ -169,8 +175,8 @@ void AddKerasLayer(RModel& rmodel, PyObject* fLayer){ //Checking if additional attribute exixts if(fLayerActivation != "linear"){ - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); std::string fActivationLayerOutput = PyStringAsString(PyList_GetItem(fOutputs,0)); if(fLayerType == "Conv2D"){ @@ -187,7 +193,7 @@ void AddKerasLayer(RModel& rmodel, PyObject* fLayer){ PyDict_SetItemString(fLayer,"layerOutput",fOutputs); rmodel.AddOperator((findLayer->second)(fLayer)); - std::string fActivationLayerInput = fLayerName+fLayerType; + std::string fActivationLayerInput = fLayerName+fLayerType; if(fLayerType == "Conv2D"){ std::unique_ptr op_post_transpose; op_post_transpose.reset(new ROperator_Transpose({0,2,3,1}, fLayerName+fLayerType, fLayerName+"PostTrans")); @@ -229,9 +235,9 @@ void AddKerasLayer(RModel& rmodel, PyObject* fLayer){ /// weight tensors are extracted, and then are passed to instantiate a /// ROperator_Gemm object using the required attributes. std::unique_ptr MakeKerasDense(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -239,7 +245,7 @@ std::unique_ptr MakeKerasDense(PyObject* fLayer){ // Extracting names of weight tensors // The names of Kernel weights and bias weights are found in the list // of weight tensors from fLayer. - PyObject* fWeightNames = PyDict_GetItemString(fLayer,"layerWeight"); + PyObject* fWeightNames = GetValueFromDict(fLayer,"layerWeight"); std::string fKernelName = PyStringAsString(PyList_GetItem(fWeightNames,0)); std::string fBiasName = PyStringAsString(PyList_GetItem(fWeightNames,1)); @@ -271,13 +277,13 @@ std::unique_ptr MakeKerasDense(PyObject* fLayer){ /// /// For Keras's Conv layer, the names of the input tensor, output tensor, and /// weight tensors are extracted, along with attributes like dilation_rate, -/// groups, kernel size, padding, strides. Padding attribute is then +/// groups, kernel size, padding, strides. Padding attribute is then /// computed for ROperator depending on Keras' attribute parameter. std::unique_ptr MakeKerasConv(PyObject* fLayer){ - PyObject* fAttributes = PyDict_GetItemWithError(fLayer,PyUnicode_FromString("layerAttributes")); - PyObject* fInputs = PyDict_GetItemWithError(fLayer,PyUnicode_FromString("layerInput")); - PyObject* fOutputs = PyDict_GetItemWithError(fLayer,PyUnicode_FromString("layerOutput")); - std::string fLayerDType = PyStringAsString(PyDict_GetItemWithError(fLayer,PyUnicode_FromString("layerDType"))); + PyObject* fAttributes = GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -285,16 +291,16 @@ std::unique_ptr MakeKerasConv(PyObject* fLayer){ // Extracting names of weight tensors // The names of Kernel weights and bias weights are found in the list // of weight tensors from fLayer. - PyObject* fWeightNames = PyDict_GetItemWithError(fLayer,PyUnicode_FromString("layerWeight")); + PyObject* fWeightNames = GetValueFromDict(fLayer,"layerWeight"); std::string fKernelName = PyStringAsString(PyList_GetItem(fWeightNames,0)); std::string fBiasName = PyStringAsString(PyList_GetItem(fWeightNames,1)); // Extracting the Conv Node Attributes - PyObject* fDilations = PyDict_GetItemWithError(fAttributes,PyUnicode_FromString("dilation_rate")); - PyObject* fGroup = PyDict_GetItemWithError(fAttributes,PyUnicode_FromString("groups")); - PyObject* fKernelShape = PyDict_GetItemWithError(fAttributes,PyUnicode_FromString("kernel_size")); - PyObject* fPads = PyDict_GetItemWithError(fAttributes,PyUnicode_FromString("padding")); - PyObject* fStrides = PyDict_GetItemWithError(fAttributes,PyUnicode_FromString("strides")); + PyObject* fDilations = GetValueFromDict(fAttributes,"dilation_rate"); + PyObject* fGroup = GetValueFromDict(fAttributes,"groups"); + PyObject* fKernelShape = GetValueFromDict(fAttributes,"kernel_size"); + PyObject* fPads = GetValueFromDict(fAttributes,"padding"); + PyObject* fStrides = GetValueFromDict(fAttributes,"strides"); std::vector fAttrDilations = GetDataFromTuple(fDilations); @@ -312,7 +318,7 @@ std::unique_ptr MakeKerasConv(PyObject* fLayer){ } else if(fKerasPadding == "same"){ fAttrAutopad="NOTSET"; - PyObject* fInputShape = PyDict_GetItemString(fAttributes,"_batch_input_shape"); + PyObject* fInputShape = GetValueFromDict(fAttributes,"_batch_input_shape"); long inputHeight = PyLong_AsLong(PyTuple_GetItem(fInputShape,1)); long inputWidth = PyLong_AsLong(PyTuple_GetItem(fInputShape,2)); @@ -355,8 +361,8 @@ std::unique_ptr MakeKerasConv(PyObject* fLayer){ /// For Keras's keras.layers.Activation layer, the activation attribute is /// extracted and appropriate function for adding the function is called. std::unique_ptr MakeKerasActivation(PyObject* fLayer){ - PyObject* fAttributes=PyDict_GetItemString(fLayer,"layerAttributes"); - PyObject* fPActivation = PyDict_GetItemString(fAttributes,"activation"); + PyObject* fAttributes=GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fPActivation = GetValueFromDict(fAttributes,"activation"); std::string fLayerActivation = PyStringAsString(PyObject_GetAttrString(fPActivation,"__name__")); auto findLayer = mapKerasLayer.find(fLayerActivation); @@ -377,10 +383,10 @@ std::unique_ptr MakeKerasActivation(PyObject* fLayer){ /// input & output tensors and the data-type of the layer are extracted. std::unique_ptr MakeKerasReLU(PyObject* fLayer) { - PyObject* fInputs=PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs=PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs=GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs=GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -405,10 +411,10 @@ std::unique_ptr MakeKerasReLU(PyObject* fLayer) /// For instantiating a ROperator_Selu object, the names of /// input & output tensors and the data-type of the layer are extracted. std::unique_ptr MakeKerasSelu(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -433,10 +439,10 @@ std::unique_ptr MakeKerasSelu(PyObject* fLayer){ /// For instantiating a ROperator_Sigmoid object, the names of /// input & output tensors and the data-type of the layer are extracted. std::unique_ptr MakeKerasSigmoid(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -460,10 +466,10 @@ std::unique_ptr MakeKerasSigmoid(PyObject* fLayer){ /// For instantiating a ROperator_Softmax object, the names of /// input & output tensors and the data-type of the layer are extracted. std::unique_ptr MakeKerasSoftmax(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -485,17 +491,17 @@ std::unique_ptr MakeKerasSoftmax(PyObject* fLayer){ /// \return Unique pointer to ROperator object /// /// For instantiating a ROperator_LeakyRelu object, the names of -/// input & output tensors, the data-type and the alpha attribute of the layer +/// input & output tensors, the data-type and the alpha attribute of the layer /// are extracted. std::unique_ptr MakeKerasLeakyRelu(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); - PyObject* fAttributes=PyDict_GetItemString(fLayer,"layerAttributes"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + PyObject* fAttributes=GetValueFromDict(fLayer,"layerAttributes"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); - float fAlpha = (float)PyFloat_AsDouble(PyDict_GetItemString(fAttributes,"alpha")); + float fAlpha = (float)PyFloat_AsDouble(GetValueFromDict(fAttributes,"alpha")); std::unique_ptr op; switch(ConvertStringToType(fLayerDType)){ case ETensorType::FLOAT: @@ -516,10 +522,10 @@ std::unique_ptr MakeKerasLeakyRelu(PyObject* fLayer){ /// For instantiating a ROperator_Tanh object, the names of /// input & output tensors and the data-type of the layer are extracted. std::unique_ptr MakeKerasTanh(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -529,11 +535,37 @@ std::unique_ptr MakeKerasTanh(PyObject* fLayer){ op.reset(new ROperator_Tanh(fLayerInputName, fLayerOutputName)); break; default: - throw std::runtime_error("TMVA::SOFIE - Unsupported - Operator Sigmoid does not yet support input type " + fLayerDType); + throw std::runtime_error("TMVA::SOFIE - Unsupported - Operator Tanh does not yet support input type " + fLayerDType); } return op; } +////////////////////////////////////////////////////////////////////////////////// +/// \brief Prepares a ROperator object for Keras Swish activation +/// +/// \param[in] fLayer Python Keras layer as a Dictionary object +/// \return Unique pointer to ROperator object +/// +/// For instantiating a ROperator_Swish object, the names of +/// input & output tensors and the data-type of the layer are extracted. +std::unique_ptr MakeKerasSwish(PyObject* fLayer){ + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); + std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); + std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); + + std::unique_ptr op; + switch(ConvertStringToType(fLayerDType)){ + case ETensorType::FLOAT: + op.reset(new ROperator_Swish(fLayerInputName, fLayerOutputName)); + break; + default: + throw std::runtime_error("TMVA::SOFIE - Unsupported - Operator Swish does not yet support input type " + fLayerDType); + } + return op; +} ////////////////////////////////////////////////////////////////////////////////// /// \brief Prepares a ROperator object for Keras Permute layer @@ -547,16 +579,16 @@ std::unique_ptr MakeKerasTanh(PyObject* fLayer){ std::unique_ptr MakeKerasPermute(PyObject* fLayer) { // Extracting required layer information - PyObject* fAttributes=PyDict_GetItemString(fLayer,"layerAttributes"); - PyObject* fInputs=PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs=PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fAttributes=GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fInputs=GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs=GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); // Extracting the permute dimensions present in Attributes of the Keras layer - PyObject* fAttributePermute = PyDict_GetItemString(fAttributes,"dims"); + PyObject* fAttributePermute = GetValueFromDict(fAttributes,"dims"); std::vectorfPermuteDims; // Building vector of permute dimensions from the Tuple object. @@ -591,23 +623,23 @@ std::unique_ptr MakeKerasPermute(PyObject* fLayer) std::unique_ptr MakeKerasBatchNorm(PyObject* fLayer) { // Extracting required layer information - PyObject* fAttributes = PyDict_GetItemString(fLayer,"layerAttributes"); - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); - PyObject* fGamma = PyDict_GetItemString(fAttributes,"gamma"); - PyObject* fBeta = PyDict_GetItemString(fAttributes,"beta"); - PyObject* fMoving_Mean = PyDict_GetItemString(fAttributes,"moving_mean"); - PyObject* fMoving_Var = PyDict_GetItemString(fAttributes,"moving_variance"); - - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + PyObject* fAttributes = GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); + PyObject* fGamma = GetValueFromDict(fAttributes,"gamma"); + PyObject* fBeta = GetValueFromDict(fAttributes,"beta"); + PyObject* fMoving_Mean = GetValueFromDict(fAttributes,"moving_mean"); + PyObject* fMoving_Var = GetValueFromDict(fAttributes,"moving_variance"); + + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fNX = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fNY = PyStringAsString(PyList_GetItem(fOutputs,0)); std::string fNScale = PyStringAsString(PyObject_GetAttrString(fGamma,"name")); std::string fNB = PyStringAsString(PyObject_GetAttrString(fBeta,"name")); std::string fNMean = PyStringAsString(PyObject_GetAttrString(fMoving_Mean,"name")); std::string fNVar = PyStringAsString(PyObject_GetAttrString(fMoving_Var,"name")); - float fEpsilon = (float)PyFloat_AsDouble(PyDict_GetItemString(fAttributes,"epsilon")); - float fMomentum = (float)PyFloat_AsDouble(PyDict_GetItemString(fAttributes,"momentum")); + float fEpsilon = (float)PyFloat_AsDouble(GetValueFromDict(fAttributes,"epsilon")); + float fMomentum = (float)PyFloat_AsDouble(GetValueFromDict(fAttributes,"momentum")); std::unique_ptr op; op.reset(new ROperator_BatchNormalization(fEpsilon, fMomentum, /* training mode */ 0, fNX, fNScale, fNB, fNMean, fNVar, fNY)); @@ -620,16 +652,16 @@ std::unique_ptr MakeKerasBatchNorm(PyObject* fLayer) /// \param[in] fLayer Python Keras layer as a Dictionary object /// \return Unique pointer to ROperator object std::unique_ptr MakeKerasReshape(PyObject* fLayer) -{ +{ // Extracting required layer information - PyObject* fAttributes = PyDict_GetItemString(fLayer,"layerAttributes"); - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fAttributes = GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerName = PyStringAsString(PyDict_GetItemString(fAttributes,"_name")); + std::string fLayerName = PyStringAsString(GetValueFromDict(fAttributes,"_name")); ReshapeOpMode fOpMode = Reshape; - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fNameData = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fNameOutput = PyStringAsString(PyList_GetItem(fOutputs,0)); std::string fNameShape = fLayerName + "ReshapeAxes"; @@ -645,24 +677,24 @@ std::unique_ptr MakeKerasReshape(PyObject* fLayer) /// \return Unique pointer to ROperator object std::unique_ptr MakeKerasConcat(PyObject* fLayer) { - PyObject* fAttributes = PyDict_GetItemString(fLayer,"layerAttributes"); - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fAttributes = GetValueFromDict(fLayer,"layerAttributes"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); std::vector inputs; for(Py_ssize_t i=0; i op; op.reset(new ROperator_Concat(inputs, axis, 0, output)); return op; } ////////////////////////////////////////////////////////////////////////////////// -/// \brief Prepares a ROperator object for Keras binary operations like Add, +/// \brief Prepares a ROperator object for Keras binary operations like Add, /// subtract, and multiply. /// /// \param[in] fLayer Python Keras layer as a Dictionary object @@ -672,11 +704,11 @@ std::unique_ptr MakeKerasConcat(PyObject* fLayer) /// input & output tensors, the data-type of the layer and the operation type /// are extracted. std::unique_ptr MakeKerasBinary(PyObject* fLayer){ - PyObject* fInputs = PyDict_GetItemString(fLayer,"layerInput"); - PyObject* fOutputs = PyDict_GetItemString(fLayer,"layerOutput"); + PyObject* fInputs = GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs = GetValueFromDict(fLayer,"layerOutput"); - std::string fLayerType = PyStringAsString(PyDict_GetItemString(fLayer,"layerType")); - std::string fLayerDType = PyStringAsString(PyDict_GetItemString(fLayer,"layerDType")); + std::string fLayerType = PyStringAsString(GetValueFromDict(fLayer,"layerType")); + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); std::string fX1 = PyStringAsString(PyList_GetItem(fInputs,0)); std::string fX2 = PyStringAsString(PyList_GetItem(fInputs,1)); std::string fY = PyStringAsString(PyList_GetItem(fOutputs,0)); @@ -698,6 +730,34 @@ std::unique_ptr MakeKerasBinary(PyObject* fLayer){ return op; } +////////////////////////////////////////////////////////////////////////////////// +/// \brief Prepares a ROperator object for Keras Identity and Dropout Layer +/// +/// \param[in] fLayer Python Keras layer as a Dictionary object +/// \return Unique pointer to ROperator object +/// +/// Dropout will have no effect in inference, so instead an Identity operator +/// is added to mimic its presence in the Keras model +std::unique_ptr MakeKerasIdentity(PyObject* fLayer) +{ + PyObject* fInputs=GetValueFromDict(fLayer,"layerInput"); + PyObject* fOutputs=GetValueFromDict(fLayer,"layerOutput"); + + std::string fLayerDType = PyStringAsString(GetValueFromDict(fLayer,"layerDType")); + std::string fLayerInputName = PyStringAsString(PyList_GetItem(fInputs,0)); + std::string fLayerOutputName = PyStringAsString(PyList_GetItem(fOutputs,0)); + + std::unique_ptr op; + switch(ConvertStringToType(fLayerDType)){ + case ETensorType::FLOAT: + op.reset(new ROperator_Identity(fLayerInputName, fLayerOutputName)); + break; + default: + throw std::runtime_error("TMVA::SOFIE - Unsupported - Operator Identity does not yet support input type " + fLayerDType); + } + return op; +} + }//INTERNAL @@ -777,9 +837,10 @@ RModel Parse(std::string filename){ // For each layer: type,name,activation,dtype,input tensor's name, // output tensor's name, kernel's name, bias's name // None object is returned for if property doesn't belong to layer + PyRunString("import tensorflow",fGlobalNS,fLocalNS); PyRunString("import tensorflow.keras as keras",fGlobalNS,fLocalNS); PyRunString("from tensorflow.keras.models import load_model",fGlobalNS,fLocalNS); - PyRunString("print('Keras Version: '+ keras.__version__)",fGlobalNS,fLocalNS); + PyRunString("print('TF/Keras Version: '+ tensorflow.__version__)",fGlobalNS,fLocalNS); PyRunString(TString::Format("model=load_model('%s')",filename.c_str()),fGlobalNS,fLocalNS); PyRunString(TString::Format("model.load_weights('%s')",filename.c_str()),fGlobalNS,fLocalNS); PyRunString("globals().update(locals())",fGlobalNS,fLocalNS); @@ -796,7 +857,7 @@ RModel Parse(std::string filename){ " modelData.append(layerData)",fGlobalNS,fLocalNS); - PyObject* fPModel = PyDict_GetItemString(fLocalNS,"modelData"); + PyObject* fPModel = GetValueFromDict(fLocalNS,"modelData"); PyObject *fLayer; Py_ssize_t fModelSize = PyList_Size(fPModel); std::string fLayerType; @@ -805,7 +866,7 @@ RModel Parse(std::string filename){ // for adding the equivalent ROperators into the RModel object. for(Py_ssize_t fModelIterator=0;fModelIterator fWeightTensorShape; std::size_t fWeightTensorSize; // Traversing through all the Weight tensors for (Py_ssize_t weightIter = 0; weightIter < PyList_Size(fPWeight); weightIter++){ fWeightTensor = PyList_GetItem(fPWeight, weightIter); - fWeightName = PyStringAsString(PyDict_GetItemString(fWeightTensor,"name")); - fWeightDType = ConvertStringToType(PyStringAsString(PyDict_GetItemString(fWeightTensor,"dtype"))); + fWeightName = PyStringAsString(GetValueFromDict(fWeightTensor,"name")); + fWeightDType = ConvertStringToType(PyStringAsString(GetValueFromDict(fWeightTensor,"dtype"))); - fWeightTensorValue = (PyArrayObject*)PyDict_GetItemString(fWeightTensor,"value"); + fWeightTensorValue = (PyArrayObject*)GetValueFromDict(fWeightTensor,"value"); fWeightTensorSize=1; fWeightTensorShape.clear(); @@ -883,9 +944,9 @@ RModel Parse(std::string filename){ PyRunString("for idx in range(len(model.inputs)):\n" " inputTypes.append(model.inputs[idx].dtype.__str__()[9:-2])",fGlobalNS,fLocalNS); - PyObject* fPInputs = PyDict_GetItemString(fLocalNS,"inputNames"); - PyObject* fPInputShapes = PyDict_GetItemString(fLocalNS,"inputShapes"); - PyObject* fPInputTypes = PyDict_GetItemString(fLocalNS,"inputTypes"); + PyObject* fPInputs = GetValueFromDict(fLocalNS,"inputNames"); + PyObject* fPInputShapes = GetValueFromDict(fLocalNS,"inputShapes"); + PyObject* fPInputTypes = GetValueFromDict(fLocalNS,"inputTypes"); std::string fInputName; ETensorType fInputDType; @@ -956,7 +1017,7 @@ RModel Parse(std::string filename){ PyRunString("outputNames=[]",fGlobalNS,fLocalNS); PyRunString("for layerName in model.output_names:\n" " outputNames.append(model.get_layer(layerName).output.name)",fGlobalNS,fLocalNS); - PyObject* fPOutputs = PyDict_GetItemString(fLocalNS,"outputNames"); + PyObject* fPOutputs = GetValueFromDict(fLocalNS,"outputNames"); std::vector fOutputNames; for(Py_ssize_t outputIter = 0; outputIter < PyList_Size(fPOutputs);++outputIter){ fOutputNames.push_back(PyStringAsString(PyList_GetItem(fPOutputs,outputIter))); diff --git a/tmva/pymva/src/RModelParser_PyTorch.cxx b/tmva/pymva/src/RModelParser_PyTorch.cxx index aa4fe6921b535..d7c78641b5ad6 100644 --- a/tmva/pymva/src/RModelParser_PyTorch.cxx +++ b/tmva/pymva/src/RModelParser_PyTorch.cxx @@ -422,12 +422,18 @@ RModel Parse(std::string filename, std::vector> inputShapes, //Extracting the model information in list modelData PyRunString("modelData=[]",fGlobalNS,fLocalNS); + // The '_node_get' helper function is used to avoid dependency on onnx submodule + // (for the subscript operator of torch._C.Node), as done in https://github.com/pytorch/pytorch/pull/82628 + PyRunString("def _node_get(node, key):\n" + " sel = node.kindOf(key)\n" + " return getattr(node, sel)(key)\n", + fGlobalNS, fLocalNS); PyRunString("for i in graph[0].nodes():\n" " globals().update(locals())\n" " nodeData={}\n" " nodeData['nodeType']=i.kind()\n" " nodeAttributeNames=[x for x in i.attributeNames()]\n" - " nodeAttributes={j:i[j] for j in nodeAttributeNames}\n" + " nodeAttributes={j: _node_get(i, j) for j in nodeAttributeNames}\n" " nodeData['nodeAttributes']=nodeAttributes\n" " nodeInputs=[x for x in i.inputs()]\n" " nodeInputNames=[x.debugName() for x in nodeInputs]\n" @@ -437,7 +443,8 @@ RModel Parse(std::string filename, std::vector> inputShapes, " nodeData['nodeOutputs']=nodeOutputNames\n" " nodeDType=[x.type().scalarType() for x in nodeOutputs]\n" " nodeData['nodeDType']=nodeDType\n" - " modelData.append(nodeData)",fGlobalNS,fLocalNS); + " modelData.append(nodeData)", + fGlobalNS, fLocalNS); PyObject* fPModel = PyDict_GetItemString(fLocalNS,"modelData"); Py_ssize_t fPModelSize = PyList_Size(fPModel); diff --git a/tmva/pymva/test/CMakeLists.txt b/tmva/pymva/test/CMakeLists.txt index 6ce2a85abd290..5373cdbf026a4 100644 --- a/tmva/pymva/test/CMakeLists.txt +++ b/tmva/pymva/test/CMakeLists.txt @@ -21,6 +21,40 @@ find_python_module(theano QUIET) find_python_module(tensorflow QUIET) find_python_module(sklearn QUIET) +if(PY_SKLEARN_FOUND) + # Test PyRandomForest: Classification + ROOT_EXECUTABLE(testPyRandomForestClassification testPyRandomForestClassification.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-RandomForest-Classification COMMAND testPyRandomForestClassification) + + # Test PyRandomForest: Multi-class classification + ROOT_EXECUTABLE(testPyRandomForestMulticlass testPyRandomForestMulticlass.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-RandomForest-Multiclass COMMAND testPyRandomForestMulticlass) + + # Test PyGTB: Classification + ROOT_EXECUTABLE(testPyGTBClassification testPyGTBClassification.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-GTB-Classification COMMAND testPyGTBClassification DEPENDS PyMVA-RandomForest-Classification) + + # Test PyGTB: Multi-class classification + ROOT_EXECUTABLE(testPyGTBMulticlass testPyGTBMulticlass.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-GTB-Multiclass COMMAND testPyGTBMulticlass DEPENDS PyMVA-RandomForest-Multiclass) + + # Test PyAdaBoost: Classification + ROOT_EXECUTABLE(testPyAdaBoostClassification testPyAdaBoostClassification.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-AdaBoost-Classification COMMAND testPyAdaBoostClassification DEPENDS PyMVA-GTB-Classification) + + # Test PyAdaBoost: Multi-class classification + ROOT_EXECUTABLE(testPyAdaBoostMulticlass testPyAdaBoostMulticlass.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-AdaBoost-Multiclass COMMAND testPyAdaBoostMulticlass DEPENDS PyMVA-GTB-Multiclass) + +endif(PY_SKLEARN_FOUND) + + # Enable tests based on available python modules if(PY_TORCH_FOUND) configure_file(generatePyTorchModelClassification.py generatePyTorchModelClassification.py COPYONLY) @@ -28,9 +62,15 @@ if(PY_TORCH_FOUND) configure_file(generatePyTorchModelRegression.py generatePyTorchModelRegression.py COPYONLY) configure_file(generatePyTorchModels.py generatePyTorchModels.py COPYONLY) # Test PyTorch: Binary classification${PYTHON_INCLUDE_DIRS} ${NUMPY_INCLUDE_DIRS} + + if (PY_SKLEARN_FOUND) + set(PyMVA-Torch-Classification-depends PyMVA-AdaBoost-Classification) + set(PyMVA-Torch-Multiclass-depends PyMVA-AdaBoost-Multiclass) + endif() + ROOT_EXECUTABLE(testPyTorchClassification testPyTorchClassification.C LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-Torch-Classification COMMAND testPyTorchClassification) + ROOT_ADD_TEST(PyMVA-Torch-Classification COMMAND testPyTorchClassification DEPENDS ${PyMVA-Torch-Classification-depends}) # Test PyTorch: Regression ROOT_EXECUTABLE(testPyTorchRegression testPyTorchRegression.C @@ -40,39 +80,14 @@ if(PY_TORCH_FOUND) # Test PyTorch: Multi-class classification ROOT_EXECUTABLE(testPyTorchMulticlass testPyTorchMulticlass.C LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-Torch-Multiclass COMMAND testPyTorchMulticlass) + ROOT_ADD_TEST(PyMVA-Torch-Multiclass COMMAND testPyTorchMulticlass DEPENDS ${PyMVA-Torch-Multiclass-depends}) # Test RModelParser_PyTorch - add_executable(emitFromPyTorch - EmitFromPyTorch.cxx - ) - target_link_libraries(emitFromPyTorch ${PYTHON_LIBRARIES} ${Libraries}) -if(APPLE) - target_link_options(emitFromPyTorch PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) -endif() - - target_include_directories(emitFromPyTorch PRIVATE - ${CMAKE_SOURCE_DIR}/tmva/sofie/inc - ${CMAKE_SOURCE_DIR}/tmva/inc - ${CMAKE_SOURCE_DIR}/core/foundation/inc - ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h - ) - set_target_properties(emitFromPyTorch PROPERTIES POSITION_INDEPENDENT_CODE TRUE) - add_custom_target(SofieCompileModels_PyTorch) - add_dependencies(SofieCompileModels_PyTorch emitFromPyTorch) - if(MSVC) - add_custom_command(TARGET SofieCompileModels_PyTorch POST_BUILD - COMMAND $/emitFromPyTorch.exe - USES_TERMINAL - ) - else() - add_custom_command(TARGET SofieCompileModels_PyTorch POST_BUILD - COMMAND ./emitFromPyTorch - USES_TERMINAL - ) - ROOT_ADD_GTEST(TestRModelParserPyTorch TestRModelParserPyTorch.C + + ROOT_ADD_GTEST(TestRModelParserPyTorch TestRModelParserPyTorch.C LIBRARIES ROOTTMVASofie + TMVA blas ${PYTHON_LIBRARIES} INCLUDE_DIRS @@ -81,83 +96,46 @@ endif() ${NUMPY_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} ) - if(APPLE) + if(APPLE) target_link_options(TestRModelParserPyTorch PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) - endif() - add_dependencies(TestRModelParserPyTorch SofieCompileModels_PyTorch) endif() + endif(PY_TORCH_FOUND) if((PY_KERAS_FOUND AND PY_THEANO_FOUND) OR (PY_KERAS_FOUND AND PY_TENSORFLOW_FOUND)) configure_file(generateKerasModels.py generateKerasModels.py COPYONLY) configure_file(scale_by_2_op.hxx scale_by_2_op.hxx COPYONLY) + if (PY_TORCH_FOUND) + set(PyMVA-Keras-Classification-depends PyMVA-Torch-Classification) + set(PyMVA-Keras-Regression-depends PyMVA-Torch-Regression) + set(PyMVA-Keras-Multiclass-depends PyMVA-Torch-Multiclass) + endif() + + # Test PyKeras: Binary classification ROOT_EXECUTABLE(testPyKerasClassification testPyKerasClassification.C LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-Keras-Classification COMMAND testPyKerasClassification) + ROOT_ADD_TEST(PyMVA-Keras-Classification COMMAND testPyKerasClassification DEPENDS ${PyMVA-Keras-Classification-depends}) # Test PyKeras: Regression - ROOT_EXECUTABLE(testPyKerasRegression testPyKerasRegression.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-Keras-Regression COMMAND testPyKerasRegression) + if (NOT ROOT_ARCHITECTURE MATCHES macosx) + #veto also keras tutorial on macos due to issue in disabling eager execution on macos + ROOT_EXECUTABLE(testPyKerasRegression testPyKerasRegression.C + LIBRARIES ${Libraries}) + ROOT_ADD_TEST(PyMVA-Keras-Regression COMMAND testPyKerasRegression DEPENDS ${PyMVA-Keras-Regression-depends}) + endif() + # Test PyKeras: Multi-class classification ROOT_EXECUTABLE(testPyKerasMulticlass testPyKerasMulticlass.C LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-Keras-Multiclass COMMAND testPyKerasMulticlass) - - # Test RModelParser_Keras - add_executable(emitFromKeras - EmitFromKeras.cxx - ) - target_link_libraries(emitFromKeras ${PYTHON_LIBRARIES} ${Libraries}) -if(APPLE) - target_link_options(emitFromKeras PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) -endif() - - target_include_directories(emitFromKeras PRIVATE - ${CMAKE_SOURCE_DIR}/tmva/sofie/inc - ${CMAKE_SOURCE_DIR}/tmva/inc - ${CMAKE_SOURCE_DIR}/core/foundation/inc - ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h - ) - set_target_properties(emitFromKeras PROPERTIES POSITION_INDEPENDENT_CODE TRUE) - add_custom_target(SofieCompileModels_Keras) - add_dependencies(SofieCompileModels_Keras emitFromKeras) - add_custom_command(TARGET SofieCompileModels_Keras POST_BUILD - COMMAND ./emitFromKeras - USES_TERMINAL - ) - - # Testing SOFIE Custom Operator functionality - add_executable(emitCustomModel - EmitCustomModel.cxx - ${CMAKE_SOURCE_DIR}/tmva/pymva/src/RModelParser_Keras.cxx - ${CMAKE_SOURCE_DIR}/tmva/sofie/src/RModel.cxx - ${CMAKE_SOURCE_DIR}/tmva/sofie/src/SOFIE_common.cxx - ) - target_link_libraries(emitCustomModel ${PYTHON_LIBRARIES} ${Libraries}) - if(APPLE) - target_link_options(emitCustomModel PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) - endif() - target_include_directories(emitCustomModel PRIVATE - ${CMAKE_SOURCE_DIR}/tmva/sofie/inc - ${CMAKE_SOURCE_DIR}/tmva/inc - ${CMAKE_SOURCE_DIR}/core/foundation/inc - ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h - ) - set_target_properties(emitCustomModel PROPERTIES POSITION_INDEPENDENT_CODE TRUE) - add_custom_target(SofieCustomModel) - add_dependencies(SofieCustomModel emitCustomModel) - add_custom_command(TARGET SofieCustomModel POST_BUILD - COMMAND ./emitCustomModel - USES_TERMINAL - ) + ROOT_ADD_TEST(PyMVA-Keras-Multiclass COMMAND testPyKerasMulticlass DEPENDS ${PyMVA-Keras-Multiclass-depends}) ROOT_ADD_GTEST(TestRModelParserKeras TestRModelParserKeras.C LIBRARIES ROOTTMVASofie + PyMVA blas ${PYTHON_LIBRARIES} INCLUDE_DIRS @@ -167,40 +145,7 @@ endif() ${CMAKE_CURRENT_BINARY_DIR} ) if(APPLE) - target_link_options(TestRModelParserKeras PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) + target_link_options(TestRModelParserKeras PRIVATE ${PYTHON_LINK_OPTIONS_Development_Main}) endif() - add_dependencies(TestRModelParserKeras SofieCompileModels_Keras SofieCustomModel) endif((PY_KERAS_FOUND AND PY_THEANO_FOUND) OR (PY_KERAS_FOUND AND PY_TENSORFLOW_FOUND)) - -if(PY_SKLEARN_FOUND) - # Test PyRandomForest: Classification - ROOT_EXECUTABLE(testPyRandomForestClassification testPyRandomForestClassification.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-RandomForest-Classification COMMAND testPyRandomForestClassification) - - # Test PyRandomForest: Multi-class classification - ROOT_EXECUTABLE(testPyRandomForestMulticlass testPyRandomForestMulticlass.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-RandomForest-Multiclass COMMAND testPyRandomForestMulticlass) - - # Test PyGTB: Classification - ROOT_EXECUTABLE(testPyGTBClassification testPyGTBClassification.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-GTB-Classification COMMAND testPyGTBClassification) - - # Test PyGTB: Multi-class classification - ROOT_EXECUTABLE(testPyGTBMulticlass testPyGTBMulticlass.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-GTB-Multiclass COMMAND testPyGTBMulticlass) - - # Test PyAdaBoost: Classification - ROOT_EXECUTABLE(testPyAdaBoostClassification testPyAdaBoostClassification.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-AdaBoost-Classification COMMAND testPyAdaBoostClassification) - - # Test PyAdaBoost: Multi-class classification - ROOT_EXECUTABLE(testPyAdaBoostMulticlass testPyAdaBoostMulticlass.C - LIBRARIES ${Libraries}) - ROOT_ADD_TEST(PyMVA-AdaBoost-Multiclass COMMAND testPyAdaBoostMulticlass) -endif(PY_SKLEARN_FOUND) diff --git a/tmva/pymva/test/Classification.C b/tmva/pymva/test/Classification.C index d5c8c6ec9ae35..0b9a5a4402bc7 100644 --- a/tmva/pymva/test/Classification.C +++ b/tmva/pymva/test/Classification.C @@ -21,7 +21,7 @@ void Classification() TMVA::Tools::Instance(); TMVA::PyMethodBase::PyInitialize(); - TString outfileName("TMVA.root"); + TString outfileName("RMVAC.root"); TFile *outputFile = TFile::Open(outfileName, "RECREATE"); TMVA::Factory *factory = new TMVA::Factory("TMVAClassification", outputFile, diff --git a/tmva/pymva/test/EmitCustomModel.cxx b/tmva/pymva/test/EmitCustomModel.cxx deleted file mode 100644 index a156054c623b8..0000000000000 --- a/tmva/pymva/test/EmitCustomModel.cxx +++ /dev/null @@ -1,62 +0,0 @@ -// Author: Sanjiban Sengupta, 2022 -// Description: -// This is to test the Custom Operator -// in TMVA SOFIE. The program is run when the -// target 'TestCustomOp' is built. The program -// first creates a Keras .h5 file, parses it and adds -// a custom operator and then generates the inference header -// file. During the test, the custom operator is added as a -// Lambda layer in the Keras model and is tested for equality. - -#include "Python.h" - -#include "TMVA/RModel.hxx" -#include "TMVA/ROperator.hxx" -#include "TMVA/RModelParser_Keras.h" - -using namespace TMVA::Experimental::SOFIE; - -const char* pythonSrc = "\ -import os\n\ -os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ -\n\ -import numpy as np\n\ -from tensorflow.keras.models import Sequential\n\ -from tensorflow.keras.layers import Dense\n\ -from tensorflow.keras.optimizers import SGD\n\ -\n\ -model = Sequential()\n\ -model.add(Dense(4, activation='relu'))\n\ -\n\ -randomGenerator=np.random.RandomState(0)\n\ -x_train=randomGenerator.rand(1,8)\n\ -y_train=randomGenerator.rand(1,4)\n\ -\n\ -model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01))\n\ -model.fit(x_train, y_train, epochs=10, batch_size=1)\n\ -model.save('KerasModelForCustomOp.h5')\n"; - -int main(){ - Py_Initialize(); - - //Emitting header file for Keras Model - PyRun_SimpleString(pythonSrc); - - //Parsing the saved Keras .h5 file into RModel object - RModel model = PyKeras::Parse("KerasModelForCustomOp.h5"); - model.Generate(); - - std::unique_ptr op; - op.reset(new ROperator_Custom(/*OpName*/ "Scale_by_2", /*input tensor names*/model.GetOutputTensorNames(), - /*output tensor names*/{"output"}, /*output shapes*/{{1,4}}, - /*header file name with the compute function*/ "scale_by_2_op.hxx")); - - // adding the custom op in the model - model.AddOperator(std::move(op)); - - // Generating inference code again after adding the custom operator - model.Generate(); - model.OutputGenerated("KerasModelWithCustomOp.hxx"); - - return 0; -} \ No newline at end of file diff --git a/tmva/pymva/test/EmitFromKeras.cxx b/tmva/pymva/test/EmitFromKeras.cxx deleted file mode 100644 index ea2f69e56677b..0000000000000 --- a/tmva/pymva/test/EmitFromKeras.cxx +++ /dev/null @@ -1,70 +0,0 @@ -// Author: Sanjiban Sengupta, 2021 -// Description: -// This is to test the RModelParser_Keras. -// The program is run when the target 'TestRModelParserKeras' is built. -// The program generates the required .hxx file after parsing a Keras .h5 file into a RModel object. - - -#include "TMVA/RModel.hxx" -#include "TMVA/RModelParser_Keras.h" - -#include - -using namespace TMVA::Experimental::SOFIE; - -int main(){ - - Py_Initialize(); - - //Emitting header file for Keras Sequential API Model - FILE* fKerasModels; - fKerasModels = fopen("generateKerasModels.py", "r"); - PyRun_SimpleFile(fKerasModels, "generateKerasModels.py"); - - //Emitting header file for Keras Sequential Model - RModel modelSequential = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelSequential.h5"); - modelSequential.Generate(); - modelSequential.OutputGenerated("KerasSequentialModel.hxx"); - - //Emitting header file for Keras Functional API Model - RModel modelFunctional = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelFunctional.h5"); - modelFunctional.Generate(); - modelFunctional.OutputGenerated("KerasFunctionalModel.hxx"); - - //Emitting header file for Keras BatchNorm Model - RModel modelBatchNorm = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelBatchNorm.h5"); - modelBatchNorm.Generate(); - modelBatchNorm.OutputGenerated("KerasBatchNormModel.hxx"); - - //Emitting header file for Keras Conv2D Model with valid padding - RModel modelConv2D_Valid = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelConv2D_Valid.h5"); - modelConv2D_Valid.Generate(); - modelConv2D_Valid.OutputGenerated("KerasConv2D_Valid.hxx"); - - //Emitting header file for Keras Conv2D Model with valid padding - RModel modelConv2D_Same = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelConv2D_Same.h5"); - modelConv2D_Same.Generate(); - modelConv2D_Same.OutputGenerated("KerasConv2D_Same.hxx"); - - //Emitting header file for Keras model with Reshape layer - RModel modelReshape = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelReshape.h5"); - modelReshape.Generate(); - modelReshape.OutputGenerated("KerasReshapeModel.hxx"); - - //Emitting header file for Keras model with Concatenate layer - RModel modelConcatenate = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelConcatenate.h5"); - modelConcatenate.Generate(); - modelConcatenate.OutputGenerated("KerasConcatenateModel.hxx"); - - // Emitting header file for Keras Binary Op Model - RModel modelBinaryOp = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelBinaryOp.h5"); - modelBinaryOp.Generate(); - modelBinaryOp.OutputGenerated("KerasBinaryOpModel.hxx"); - - //Emitting header file for Keras activation functions model - RModel modelActivations = TMVA::Experimental::SOFIE::PyKeras::Parse("KerasModelActivations.h5"); - modelActivations.Generate(); - modelActivations.OutputGenerated("KerasActivationsModel.hxx"); - - return 0; -} diff --git a/tmva/pymva/test/EmitFromPyTorch.cxx b/tmva/pymva/test/EmitFromPyTorch.cxx deleted file mode 100644 index 4a59190fd40e8..0000000000000 --- a/tmva/pymva/test/EmitFromPyTorch.cxx +++ /dev/null @@ -1,46 +0,0 @@ -// Author: Sanjiban Sengupta, 2021 -// Description: -// This is to test the RModelParser_PyTorch. -// The program is run when the target 'TestRModelParserPyTorch' is built. -// The program generates the required .hxx file after parsing a PyTorch .pt file into a RModel object. - - -#include "TMVA/RModel.hxx" -#include "TMVA/RModelParser_PyTorch.h" - -#include - -using namespace TMVA::Experimental::SOFIE; - -int main(){ - - Py_Initialize(); - - // Generating PyTorch models for testing - FILE* fPyTorchModels; - fPyTorchModels = fopen("generatePyTorchModels.py", "r"); - PyRun_SimpleFile(fPyTorchModels, "generatePyTorchModels.py"); - - //Emitting header file for PyTorch nn.Module - std::vector inputTensorShapeModule{2,6}; - std::vector> inputShapesModule{inputTensorShapeModule}; - RModel modelModule = TMVA::Experimental::SOFIE::PyTorch::Parse("PyTorchModelModule.pt",inputShapesModule); - modelModule.Generate(); - modelModule.OutputGenerated("PyTorchModuleModel.hxx"); - - //Emitting header file for PyTorch nn.Sequential - std::vector inputTensorShapeSequential{2,4}; - std::vector> inputShapesSequential{inputTensorShapeSequential}; - RModel modelSequential = TMVA::Experimental::SOFIE::PyTorch::Parse("PyTorchModelSequential.pt",inputShapesSequential); - modelSequential.Generate(); - modelSequential.OutputGenerated("PyTorchSequentialModel.hxx"); - - //Emitting header file for PyTorch Convolution Model - std::vector inputTensorShapeConvolution{5, 6, 5, 5}; - std::vector> inputShapesConvolution{inputTensorShapeConvolution}; - RModel modelConvolution = TMVA::Experimental::SOFIE::PyTorch::Parse("PyTorchModelConvolution.pt",inputShapesConvolution); - modelConvolution.Generate(); - modelConvolution.OutputGenerated("PyTorchConvolutionModel.hxx"); - - return 0; -} diff --git a/tmva/pymva/test/TestRModelParserKeras.C b/tmva/pymva/test/TestRModelParserKeras.C index 54f2c92f20492..f2d0542933bd3 100644 --- a/tmva/pymva/test/TestRModelParserKeras.C +++ b/tmva/pymva/test/TestRModelParserKeras.C @@ -1,14 +1,3 @@ -#include "KerasFunctionalModel.hxx" -#include "KerasSequentialModel.hxx" -#include "KerasBatchNormModel.hxx" -#include "KerasConv2D_Valid.hxx" -#include "KerasConv2D_Same.hxx" -#include "KerasReshapeModel.hxx" -#include "KerasConcatenateModel.hxx" -#include "KerasBinaryOpModel.hxx" -#include "KerasActivationsModel.hxx" -#include "KerasModelWithCustomOp.hxx" - #include #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include @@ -16,12 +5,26 @@ #include "gtest/gtest.h" #include +#include "TSystem.h" +#include "TMVA/RSofieReader.hxx" +#include "TMVA/PyMethodBase.h" + constexpr float DEFAULT_TOLERANCE = 1e-6f; +void GenerateModels() { + + FILE* fKerasModels = fopen("generateKerasModels.py", "r"); + if (!fKerasModels) { + std::string msg = "Can't find Python script to generate models in " + std::string(gSystem->pwd()); + throw std::runtime_error(msg); + } + PyRun_SimpleFile(fKerasModels, "generateKerasModels.py"); +} + TEST(RModelParser_Keras, SEQUENTIAL) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputSequential[]={ 0.12107884, 0.89718615, 0.89123899, 0.32197549, + std::vector inputSequential = { 0.12107884, 0.89718615, 0.89123899, 0.32197549, 0.17891638, 0.83555135, 0.98680066, 0.14496809, 0.07255503, 0.55386989, 0.6628149 , 0.29843291, 0.71059786, 0.44043452, 0.13792047, 0.93007397, @@ -30,10 +33,15 @@ TEST(RModelParser_Keras, SEQUENTIAL) 0.63637339, 0.94483464, 0.11032887, 0.22424818, 0.50972592, 0.04671024, 0.39230661, 0.80500943}; - TMVA_SOFIE_KerasModelSequential::Session s("KerasSequentialModel.dat"); - std::vector outputSequential = s.infer(inputSequential); - Py_Initialize(); + + if (gSystem->AccessPathName("KerasModelSequential.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelSequential.h5"); + std::vector outputSequential = r.Compute(inputSequential); + + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -75,12 +83,17 @@ TEST(RModelParser_Keras, SEQUENTIAL) TEST(RModelParser_Keras, FUNCTIONAL) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputFunctional[]={0.60828574, 0.50069386, 0.75186709, 0.14968806, 0.7692464 ,0.77027585, 0.75095316, 0.96651197, + std::vector inputFunctional ={0.60828574, 0.50069386, 0.75186709, 0.14968806, 0.7692464 ,0.77027585, 0.75095316, 0.96651197, 0.38536308, 0.95565917, 0.62796356, 0.13818375, 0.65484891,0.89220363, 0.23879365, 0.00635323}; - TMVA_SOFIE_KerasModelFunctional::Session s("KerasFunctionalModel.dat"); - std::vector outputFunctional = s.infer(inputFunctional); + Py_Initialize(); + if (gSystem->AccessPathName("KerasModelFunctional.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelFunctional.h5"); + std::vector outputFunctional = r.Compute(inputFunctional); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -116,12 +129,16 @@ TEST(RModelParser_Keras, FUNCTIONAL) TEST(RModelParser_Keras, BATCH_NORM) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputBatchNorm[]={0.22308163, 0.95274901, 0.44712538, 0.84640867, + std::vectorinputBatchNorm = {0.22308163, 0.95274901, 0.44712538, 0.84640867, 0.69947928, 0.29743695, 0.81379782, 0.39650574}; - TMVA_SOFIE_KerasModelBatchNorm::Session s("KerasBatchNormModel.dat"); - std::vector outputBatchNorm = s.infer(inputBatchNorm); Py_Initialize(); + if (gSystem->AccessPathName("KerasModelBatchNorm.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelBatchNorm.h5"); + std::vector outputBatchNorm = r.Compute(inputBatchNorm); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -154,17 +171,24 @@ TEST(RModelParser_Keras, BATCH_NORM) } } +#if PY_MAJOR_VERSION >= 3 TEST(RModelParser_Keras, CONV_VALID) +#else +TEST(DISABLED_RModelParser_Keras, CONV_VALID) +#endif { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputConv2D_Valid[]= {1,1,1,1, + std::vectorinputConv2D_Valid = {1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1}; - TMVA_SOFIE_KerasModelConv2D_Valid::Session s("KerasConv2D_Valid.dat"); - std::vector outputConv2D_Valid = s.infer(inputConv2D_Valid); - Py_Initialize(); + if (gSystem->AccessPathName("KerasModelConv2D_Valid.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelConv2D_Valid.h5"); + std::vector outputConv2D_Valid = r.Compute(inputConv2D_Valid); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -196,17 +220,25 @@ TEST(RModelParser_Keras, CONV_VALID) } } +#if PY_MAJOR_VERSION >= 3 TEST(RModelParser_Keras, CONV_SAME) +#else +TEST(DISABLED_RModelParser_Keras, CONV_SAME) +#endif { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputConv2D_Same[]= {1,1,1,1, + std::vectorinputConv2D_Same = {1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1}; - TMVA_SOFIE_KerasModelConv2D_Same::Session s("KerasConv2D_Same.dat"); - std::vector outputConv2D_Same = s.infer(inputConv2D_Same); Py_Initialize(); + if (gSystem->AccessPathName("KerasModelConv2D_Same.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelConv2D_Same.h5"); + std::vector outputConv2D_Same = r.Compute(inputConv2D_Same); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -241,14 +273,18 @@ TEST(RModelParser_Keras, CONV_SAME) TEST(RModelParser_Keras, RESHAPE) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputReshape[]={1,1,1,1, + std::vectorinputReshape = {1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1}; - TMVA_SOFIE_KerasModelReshape::Session s("KerasReshapeModel.dat"); - std::vector outputReshape = s.infer(inputReshape); Py_Initialize(); + if (gSystem->AccessPathName("KerasModelReshape.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelReshape.h5"); + std::vector outputReshape = r.Compute(inputReshape); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -283,13 +319,16 @@ TEST(RModelParser_Keras, RESHAPE) TEST(RModelParser_Keras, CONCATENATE) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputConcatenate_1[]={1,1}; - float inputConcatenate_2[]={1,1}; - - TMVA_SOFIE_KerasModelConcatenate::Session s("KerasConcatenateModel.dat"); - std::vector outputConcatenate = s.infer(inputConcatenate_1, inputConcatenate_2); + std::vectorinputConcatenate_1 = {1,1}; + std::vectorinputConcatenate_2 = {1,1}; Py_Initialize(); + if (gSystem->AccessPathName("KerasModelConcatenate.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelConcatenate.h5"); + std::vector outputConcatenate = r.Compute(inputConcatenate_1, inputConcatenate_2); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -325,13 +364,16 @@ TEST(RModelParser_Keras, CONCATENATE) TEST(RModelParser_Keras, BINARY_OP) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float input_BinaryOp_1[]={1,1}; - float input_BinaryOp_2[]={1,1}; - - TMVA_SOFIE_KerasModelBinaryOp::Session s; //("KerasBinaryOpModel.dat"); - std::vector outputBinaryOp = s.infer(input_BinaryOp_1,input_BinaryOp_2); + std::vectorinput_BinaryOp_1 = {1,1}; + std::vectorinput_BinaryOp_2 = {1,1}; Py_Initialize(); + if (gSystem->AccessPathName("KerasModelBinaryOp.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelBinaryOp.h5"); + std::vector outputBinaryOp = r.Compute(input_BinaryOp_1,input_BinaryOp_2); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -367,11 +409,15 @@ TEST(RModelParser_Keras, BINARY_OP) TEST(RModelParser_Keras, ACTIVATIONS) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputActivations[]={1,1,1,1,1,1,1,1}; - TMVA_SOFIE_KerasModelActivations::Session s("KerasActivationsModel.dat"); - std::vector outputActivations = s.infer(inputActivations); + std::vectorinputActivations = {1,1,1,1,1,1,1,1}; Py_Initialize(); + if (gSystem->AccessPathName("KerasModelActivations.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelActivations.h5"); + std::vector outputActivations = r.Compute(inputActivations); + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -403,16 +449,60 @@ TEST(RModelParser_Keras, ACTIVATIONS) } } -TEST(RModel, CUSTOM_OP) +TEST(RModelParser_Keras, SWISH) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float input_custom[]={1,1,1,1,1,1,1,1}; + std::vectorinput = {1,1,1,1,1,1,1,1}; + + Py_Initialize(); + if (gSystem->AccessPathName("KerasModelSwish.h5",kFileExists)) + GenerateModels(); + + TMVA::Experimental:: RSofieReader r("KerasModelSwish.h5"); + std::vector output = r.Compute(input); + + PyObject* main = PyImport_AddModule("__main__"); + PyObject* fGlobalNS = PyModule_GetDict(main); + PyObject* fLocalNS = PyDict_New(); + if (!fGlobalNS) { + throw std::runtime_error("Can't init global namespace for Python"); + } + if (!fLocalNS) { + throw std::runtime_error("Can't init local namespace for Python"); + } + PyRun_String("import os",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("from tensorflow.keras.models import load_model",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("import numpy",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("model=load_model('KerasModelSwish.h5')",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("input=numpy.ones((1,8))",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("output=model(input).numpy()",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("outputSize=output.size",Py_single_input,fGlobalNS,fLocalNS); + std::size_t pOutputSize=(std::size_t)PyLong_AsLong(PyDict_GetItemString(fLocalNS,"outputSize")); + + //Testing the actual and expected output tensor sizes + EXPECT_EQ(output.size(), pOutputSize); + + PyArrayObject* pValues=(PyArrayObject*)PyDict_GetItemString(fLocalNS,"output"); + float* pOutput=(float*)PyArray_DATA(pValues); - TMVA_SOFIE_KerasModelForCustomOp::Session s("KerasModelWithCustomOp.dat"); - std::vector outputCustomOp = s.infer(input_custom); + //Testing the actual and expected output tensor values + for (size_t i = 0; i < output.size(); ++i) { + EXPECT_LE(std::abs(output[i] - pOutput[i]), TOLERANCE); + } +} +TEST(RModel, CUSTOM_OP) +{ + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + std::vectorinput_custom ={1,1,1,1,1,1,1,1}; Py_Initialize(); + if (gSystem->AccessPathName("KerasModelCustomOp.h5",kFileExists)) + GenerateModels(); + + + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -428,13 +518,27 @@ TEST(RModel, CUSTOM_OP) PyRun_String("from tensorflow.keras.layers import Lambda",Py_single_input,fGlobalNS,fLocalNS); PyRun_String("import numpy",Py_single_input,fGlobalNS,fLocalNS); - PyRun_String("model=load_model('KerasModelForCustomOp.h5')",Py_single_input,fGlobalNS,fLocalNS); + PyRun_String("model=load_model('KerasModelCustomOp.h5')",Py_single_input,fGlobalNS,fLocalNS); PyRun_String("model.add(Lambda(lambda x: x * 2))",Py_single_input,fGlobalNS,fLocalNS); PyRun_String("input=numpy.array([1,1,1,1,1,1,1,1]).reshape(1,8)",Py_single_input,fGlobalNS,fLocalNS); PyRun_String("output=model(input).numpy()",Py_single_input,fGlobalNS,fLocalNS); PyRun_String("outputSize=output.size",Py_single_input,fGlobalNS,fLocalNS); std::size_t pOutputCustomOpSize=(std::size_t)PyLong_AsLong(PyDict_GetItemString(fLocalNS,"outputSize")); + // get input name for custom (it is output of one before last) + PyRun_String("outputName = model.get_layer(index=len(model.layers)-2).output.name",Py_single_input,fGlobalNS,fLocalNS); + PyObject *pOutputName = PyDict_GetItemString(fLocalNS, "outputName"); + std::string outputName = TMVA::PyMethodBase::PyStringAsString(pOutputName); + TMVA::Experimental:: RSofieReader r; + r.AddCustomOperator(/*OpName*/ "Scale_by_2", + /*input tensor names where to insert custom op */std::string("{\"" + outputName + "\"}"), + /*output tensor names*/"{\"Scale2Output\"}", + /*output shapes*/"{{1,4}}", + /*header file name with the compute function*/ "scale_by_2_op.hxx"); + // need to load model afterwards + r.Load("KerasModelCustomOp.h5",{}, false); + std::vector outputCustomOp = r.Compute(input_custom); + //Testing the actual and expected output tensor sizes EXPECT_EQ(outputCustomOp.size(), pOutputCustomOpSize); @@ -443,6 +547,6 @@ TEST(RModel, CUSTOM_OP) //Testing the actual and expected output tensor values for (size_t i = 0; i < outputCustomOp.size(); ++i) { - EXPECT_LE(std::abs(outputCustomOp[i] - pOutputCustomOp[i]), TOLERANCE); + EXPECT_LE(std::abs(outputCustomOp[i] - pOutputCustomOp[i]), TOLERANCE); } } \ No newline at end of file diff --git a/tmva/pymva/test/TestRModelParserPyTorch.C b/tmva/pymva/test/TestRModelParserPyTorch.C index 5c70ec15afb6d..4dbe36b91d983 100644 --- a/tmva/pymva/test/TestRModelParserPyTorch.C +++ b/tmva/pymva/test/TestRModelParserPyTorch.C @@ -1,10 +1,9 @@ #include -#include "PyTorchModuleModel.hxx" -#include "PyTorchSequentialModel.hxx" -#include "PyTorchConvolutionModel.hxx" +#include "TMVA/RSofieReader.hxx" #include +#include "TSystem.h" #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include @@ -13,17 +12,38 @@ constexpr float DEFAULT_TOLERANCE = 1e-6f; +void GenerateModels() { + FILE* fPyTorchModels; + fPyTorchModels = fopen("generatePyTorchModels.py", "r"); + PyRun_SimpleFile(fPyTorchModels, "generatePyTorchModels.py"); + + std::cout << "PyTorch models are generated\n"; +} + TEST(RModelParser_PyTorch, SEQUENTIAL_MODEL) { - constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputSequential[]={-1.6207, 0.6133, - 0.5058, -1.2560, - -0.7750, -1.6701, - 0.8171, -0.2858}; - TMVA_SOFIE_PyTorchModelSequential::Session s("PyTorchSequentialModel.dat"); - std::vector outputSequential = s.infer(inputSequential); + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + std::vector inputSequential ={-1.6207, 0.6133, + 0.5058, -1.2560, + -0.7750, -1.6701, + 0.8171, -0.2858}; + + // Generating PyTorch models for testing Py_Initialize(); + if (gSystem->AccessPathName("PyTorchModelSequential.pt",kFileExists)) + GenerateModels(); + + // use RSofieReader to parse and evaluate the model + // need first the input shape + std::vector inputTensorShapeSequential{2,4}; + std::vector> inputShapesSequential{inputTensorShapeSequential}; + + TMVA::Experimental::RSofieReader s("PyTorchModelSequential.pt", inputShapesSequential); + + std::vector outputSequential = s.Compute(inputSequential); + + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -53,21 +73,29 @@ TEST(RModelParser_PyTorch, SEQUENTIAL_MODEL) for (size_t i = 0; i < outputSequential.size(); ++i) { EXPECT_LE(std::abs(outputSequential[i] - pOutputSequential[i]), TOLERANCE); } + } TEST(RModelParser_PyTorch, MODULE_MODEL) { constexpr float TOLERANCE = DEFAULT_TOLERANCE; - float inputModule[]={0.5516, 0.3585, + std::vector inputModule={0.5516, 0.3585, -0.4854, -1.3884, 0.8057, -0.9449, 0.5626, -0.6466, -1.8818, 0.4736, 1.1102, 1.8694}; - TMVA_SOFIE_PyTorchModelModule::Session s("PyTorchModuleModel.dat"); - std::vector outputModule = s.infer(inputModule); Py_Initialize(); + if (gSystem->AccessPathName("PyTorchModelModule.pt",kFileExists)) + GenerateModels(); + + std::vector inputTensorShapeModule{2,6}; + std::vector> inputShapesModule{inputTensorShapeModule}; + TMVA::Experimental::RSofieReader s("PyTorchModelModule.pt", inputShapesModule); + std::vector outputModule = s.Compute(inputModule); + + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); @@ -107,10 +135,16 @@ TEST(RModelParser_PyTorch, CONVOLUTION_MODEL) std::vector inputConv(5*6*5*5); std::iota(inputConv.begin(), inputConv.end(), 1.0f); - TMVA_SOFIE_PyTorchModelConvolution::Session s("PyTorchConvolutionModel.dat"); - std::vector outputConv = s.infer(inputConv.data()); - Py_Initialize(); + if (gSystem->AccessPathName("PyTorchModelConvolution.pt",kFileExists)) + GenerateModels(); + + std::vector inputTensorShapeConvolution{5, 6, 5, 5}; + std::vector> inputShapesConvolution{inputTensorShapeConvolution}; + TMVA::Experimental::RSofieReader s("PyTorchModelConvolution.pt", inputShapesConvolution); + std::vector outputConv = s.Compute(inputConv); + + PyObject* main = PyImport_AddModule("__main__"); PyObject* fGlobalNS = PyModule_GetDict(main); PyObject* fLocalNS = PyDict_New(); diff --git a/tmva/pymva/test/generateKerasModels.py b/tmva/pymva/test/generateKerasModels.py index 573e3108ef3ae..39872f2d38c6c 100644 --- a/tmva/pymva/test/generateKerasModels.py +++ b/tmva/pymva/test/generateKerasModels.py @@ -23,7 +23,7 @@ def generateFunctionalModel(): y_train=randomGenerator.rand(2,4) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=2) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=2) model.save('KerasModelFunctional.h5') def generateSequentialModel(): @@ -38,7 +38,7 @@ def generateSequentialModel(): y_train=randomGenerator.rand(4,6) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=4) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=4) model.save('KerasModelSequential.h5') def generateBatchNormModel(): @@ -52,7 +52,7 @@ def generateBatchNormModel(): y_train=randomGenerator.rand(4,2) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=2) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=2) model.save('KerasModelBatchNorm.h5') def generateConv2DModel_ValidPadding(): @@ -64,7 +64,7 @@ def generateConv2DModel_ValidPadding(): y_train=randomGenerator.rand(1,2,2,8) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=2) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=2) model.save('KerasModelConv2D_Valid.h5') def generateConv2DModel_SamePadding(): @@ -76,9 +76,9 @@ def generateConv2DModel_SamePadding(): y_train=randomGenerator.rand(1,4,4,8) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=2) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=2) model.save('KerasModelConv2D_Same.h5') - + def generateReshapeModel(): model = Sequential() model.add(Conv2D(8, kernel_size=3, activation="relu", input_shape=(4,4,1), padding="same")) @@ -89,7 +89,7 @@ def generateReshapeModel(): y_train=randomGenerator.rand(1,32,4) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=2) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=2) model.save('KerasModelReshape.h5') def generateConcatModel(): @@ -99,14 +99,14 @@ def generateConcatModel(): dense_2 = Dense(3)(input_2) concat = Concatenate(axis=1)([dense_1,dense_2]) model = Model(inputs=[input_1,input_2], outputs=concat) - + randomGenerator=np.random.RandomState(0) x1_train = randomGenerator.rand(1,2) x2_train = randomGenerator.rand(1,2) y_train = randomGenerator.rand(1,6) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit([x1_train,x2_train], y_train, epochs=10, batch_size=1) + model.fit([x1_train,x2_train], y_train, verbose=0, epochs=10, batch_size=1) model.save('KerasModelConcatenate.h5') def generateBinaryOpModel(): @@ -123,7 +123,7 @@ def generateBinaryOpModel(): y_train = randomGenerator.rand(2,1) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit([x1_train,x2_train], y_train, epochs=10, batch_size=2) + model.fit([x1_train,x2_train], y_train, epochs=10, verbose=0, batch_size=2) model.save('KerasModelBinaryOp.h5') def generateActivationModel(): @@ -139,10 +139,37 @@ def generateActivationModel(): y_train=randomGenerator.rand(1,4) model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) - model.fit(x_train, y_train, epochs=10, batch_size=1) + model.fit(x_train, y_train, epochs=10, verbose=0, batch_size=1) model.save('KerasModelActivations.h5') - +def generateSwishModel(): +# Create the Keras model + model = Sequential() + model.add(Dense(64, activation='swish', input_shape=(8,))) + model.add(Dense(32, activation='swish')) + model.add(Dense(1, activation='swish')) + + model.compile(loss='categorical_crossentropy', + optimizer='adam', + metrics=['accuracy']) + + randomGenerator=np.random.RandomState(0) + x_train=randomGenerator.rand(1,8) + y_train=randomGenerator.rand(1,1) + model.fit(x_train, y_train, epochs=10, verbose=0, batch_size=1) + model.save('KerasModelSwish.h5') + +def generateCustomModel(): + model = Sequential() + model.add(Dense(4, activation='relu')) + randomGenerator=np.random.RandomState(0) + x_train=randomGenerator.rand(1,8) + y_train=randomGenerator.rand(1,4) + model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01)) + model.fit(x_train, y_train, verbose=0, epochs=10, batch_size=1) + model.save('KerasModelCustomOp.h5') + +print("generating Keras models for testing.....") generateFunctionalModel() generateSequentialModel() generateBatchNormModel() @@ -152,3 +179,5 @@ def generateActivationModel(): generateConcatModel() generateBinaryOpModel() generateActivationModel() +generateSwishModel() +generateCustomModel() \ No newline at end of file diff --git a/tmva/pymva/test/testPyKerasClassification.C b/tmva/pymva/test/testPyKerasClassification.C index 726ae7a049682..0634bc52b2a88 100644 --- a/tmva/pymva/test/testPyKerasClassification.C +++ b/tmva/pymva/test/testPyKerasClassification.C @@ -10,17 +10,18 @@ #include "TMVA/PyMethodBase.h" TString pythonSrc = "\ -from keras.models import Sequential\n\ -from keras.layers.core import Dense, Activation\n\ -from keras.optimizers import SGD\n\ +from tensorflow.keras.models import Sequential\n\ +from tensorflow.keras.layers import Dense, Activation\n\ +from tensorflow.keras.optimizers import Adam\n\ \n\ model = Sequential()\n\ model.add(Dense(64, activation=\"relu\", input_dim=4))\n\ model.add(Dense(2, activation=\"softmax\"))\n\ -model.compile(loss=\"categorical_crossentropy\", optimizer=SGD(lr=0.01), metrics=[\"accuracy\",])\n\ +model.compile(loss=\"categorical_crossentropy\", optimizer=\"Adam\", weighted_metrics=[\"accuracy\",])\n\ model.save(\"kerasModelClassification.h5\")\n"; int testPyKerasClassification(){ + // Get data file std::cout << "Get test data..." << std::endl; TString fname = "./tmva_class_example.root"; @@ -29,19 +30,20 @@ int testPyKerasClassification(){ TFile *input = TFile::Open(fname); // Build model from python file - std::cout << "Generate keras model..." << std::endl; - UInt_t ret; - ret = gSystem->Exec("echo '"+pythonSrc+"' > generateKerasModelClassification.py"); - if(ret!=0){ - std::cout << "[ERROR] Failed to write python code to file" << std::endl; - return 1; - } - ret = gSystem->Exec("python generateKerasModelClassification.py"); - if(ret!=0){ - std::cout << "[ERROR] Failed to generate model using python" << std::endl; - return 1; + if (gSystem->AccessPathName("kerasModelClassification.h5")) { + std::cout << "Generate keras model..." << std::endl; + UInt_t ret; + ret = gSystem->Exec("echo '"+pythonSrc+"' > generateKerasModelClassification.py"); + if(ret!=0){ + std::cout << "[ERROR] Failed to write python code to file" << std::endl; + return 1; + } + ret = gSystem->Exec(TMVA::Python_Executable() + " generateKerasModelClassification.py"); + if(ret!=0){ + std::cout << "[ERROR] Failed to generate model using python" << std::endl; + return 1; + } } - // Setup PyMVA and factory std::cout << "Setup TMVA..." << std::endl; TMVA::PyMethodBase::PyInitialize(); @@ -67,7 +69,7 @@ int testPyKerasClassification(){ // Book and train method factory->BookMethod(dataloader, TMVA::Types::kPyKeras, "PyKeras", - "!H:!V:VarTransform=D,G:FilenameModel=kerasModelClassification.h5:FilenameTrainedModel=trainedKerasModelClassification.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:Verbose=0"); + "!H:!V:VarTransform=D,G:FilenameModel=kerasModelClassification.h5:FilenameTrainedModel=trainedKerasModelClassification.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:Verbose=0:NumThreads=1:tf.keras"); std::cout << "Train model..." << std::endl; factory->TrainAllMethods(); @@ -85,6 +87,7 @@ int testPyKerasClassification(){ reader->AddVariable("var2", vars+1); reader->AddVariable("var3", vars+2); reader->AddVariable("var4", vars+3); + std::cout << "Booking PyKeras for TMVA::Reader\n"; reader->BookMVA("PyKeras", "datasetTestPyKerasClassification/weights/testPyKerasClassification_PyKeras.weights.xml"); // Get mean response of method on signal and background events @@ -100,6 +103,7 @@ int testPyKerasClassification(){ Float_t meanMvaSignal = 0; Float_t meanMvaBackground = 0; + std::cout << "Reading events....\n"; for(UInt_t i=0; iGetEntry(i); meanMvaSignal += reader->EvaluateMVA("PyKeras"); diff --git a/tmva/pymva/test/testPyKerasMulticlass.C b/tmva/pymva/test/testPyKerasMulticlass.C index b62272732b755..2717b69ad181d 100644 --- a/tmva/pymva/test/testPyKerasMulticlass.C +++ b/tmva/pymva/test/testPyKerasMulticlass.C @@ -11,14 +11,14 @@ #include "TMVA/PyMethodBase.h" TString pythonSrc = "\ -from keras.models import Sequential\n\ -from keras.layers.core import Dense, Activation\n\ -from keras.optimizers import Adam\n\ +from tensorflow.keras.models import Sequential\n\ +from tensorflow.keras.layers import Dense, Activation\n\ +from tensorflow.keras.optimizers import Adam\n\ \n\ model = Sequential()\n\ model.add(Dense(64, activation=\"relu\", input_dim=4))\n\ model.add(Dense(4, activation=\"softmax\"))\n\ -model.compile(loss=\"categorical_crossentropy\", optimizer=Adam(), metrics=[\"accuracy\",])\n\ +model.compile(loss=\"categorical_crossentropy\", optimizer=Adam(), weighted_metrics=[\"accuracy\",])\n\ model.save(\"kerasModelMulticlass.h5\")\n"; int testPyKerasMulticlass(){ @@ -42,7 +42,7 @@ int testPyKerasMulticlass(){ std::cout << "[ERROR] Failed to write python code to file" << std::endl; return 1; } - ret = gSystem->Exec("python generateKerasModelMulticlass.py"); + ret = gSystem->Exec(TMVA::Python_Executable() + " generateKerasModelMulticlass.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; diff --git a/tmva/pymva/test/testPyKerasRegression.C b/tmva/pymva/test/testPyKerasRegression.C index 25e8681700b74..cbfcc07867525 100644 --- a/tmva/pymva/test/testPyKerasRegression.C +++ b/tmva/pymva/test/testPyKerasRegression.C @@ -10,14 +10,14 @@ #include "TMVA/PyMethodBase.h" TString pythonSrc = "\ -from keras.models import Sequential\n\ -from keras.layers.core import Dense, Activation\n\ -from keras.optimizers import SGD\n\ +from tensorflow.keras.models import Sequential\n\ +from tensorflow.keras.layers import Dense, Activation\n\ +from tensorflow.keras.optimizers import SGD\n\ \n\ model = Sequential()\n\ model.add(Dense(64, activation=\"tanh\", input_dim=2))\n\ model.add(Dense(1, activation=\"linear\"))\n\ -model.compile(loss=\"mean_squared_error\", optimizer=SGD(lr=0.01))\n\ +model.compile(loss=\"mean_squared_error\", optimizer=SGD(learning_rate=0.01), weighted_metrics=[])\n\ model.save(\"kerasModelRegression.h5\")\n"; int testPyKerasRegression(){ @@ -36,7 +36,7 @@ int testPyKerasRegression(){ std::cout << "[ERROR] Failed to write python code to file" << std::endl; return 1; } - ret = gSystem->Exec("python generateKerasModelRegression.py"); + ret = gSystem->Exec(TMVA::Python_Executable() + " generateKerasModelRegression.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; @@ -60,11 +60,14 @@ int testPyKerasRegression(){ dataloader->AddTarget("fvalue"); dataloader->PrepareTrainingAndTestTree("", - "SplitMode=Random:NormMode=NumEvents:!V"); - +#ifdef R__MACOSX // on macos we don;t disable eager execution, it is very slow + "nTrain_Regression=500:nTest_Regression=100:SplitMode=Random:NormMode=NumEvents:!V"); +#else + "nTrain_Regression=1000:nTest_Regression=200:SplitMode=Random:NormMode=NumEvents:!V"); +#endif // Book and train method factory->BookMethod(dataloader, TMVA::Types::kPyKeras, "PyKeras", - "!H:!V:VarTransform=D,G:FilenameModel=kerasModelRegression.h5:FilenameTrainedModel=trainedKerasModelRegression.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:Verbose=0"); + "!H:!V:VarTransform=D,G:FilenameModel=kerasModelRegression.h5:FilenameTrainedModel=trainedKerasModelRegression.h5:NumEpochs=10:BatchSize=25:SaveBestOnly=false:Verbose=0"); std::cout << "Train model..." << std::endl; factory->TrainAllMethods(); @@ -96,7 +99,11 @@ int testPyKerasRegression(){ // Check whether the response is obviously better than guessing std::cout << "Mean squared error: " << meanMvaError << std::endl; +#ifdef R__MACOSX if(meanMvaError > 30.0){ +#else + if(meanMvaError > 60.0){ +#endif std::cout << "[ERROR] Mean squared error is " << meanMvaError << " (>30.0)" << std::endl; return 1; } diff --git a/tmva/pymva/test/testPyTorchMulticlass.C b/tmva/pymva/test/testPyTorchMulticlass.C index 16a747d9607a3..3c47d413486aa 100644 --- a/tmva/pymva/test/testPyTorchMulticlass.C +++ b/tmva/pymva/test/testPyTorchMulticlass.C @@ -27,7 +27,7 @@ int testPyTorchMulticlass(){ // Build model from python file std::cout << "Generate PyTorch model..." << std::endl; UInt_t ret; - ret = gSystem->Exec("python generatePyTorchModelMulticlass.py"); + ret = gSystem->Exec(TMVA::Python_Executable() + " generatePyTorchModelMulticlass.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; @@ -150,4 +150,4 @@ int testPyTorchMulticlass(){ int main(){ int err = testPyTorchMulticlass(); return err; -} \ No newline at end of file +} diff --git a/tmva/pymva/test/testPyTorchRegression.C b/tmva/pymva/test/testPyTorchRegression.C index f54c30da66cbf..a105796ced3d8 100644 --- a/tmva/pymva/test/testPyTorchRegression.C +++ b/tmva/pymva/test/testPyTorchRegression.C @@ -21,7 +21,7 @@ int testPyTorchRegression(){ // Build model from python file std::cout << "Generate PyTorch model..." << std::endl; UInt_t ret; - ret = gSystem->Exec("python generatePyTorchModelRegression.py"); + ret = gSystem->Exec(TMVA::Python_Executable() + " generatePyTorchModelRegression.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; @@ -49,7 +49,7 @@ int testPyTorchRegression(){ // Book and train method factory->BookMethod(dataloader, TMVA::Types::kPyTorch, "PyTorch", - "!H:!V:VarTransform=D,G:FilenameModel=PyTorchModelRegression.pt:FilenameTrainedModel=trainedPyTorchModelRegression.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:UserCode=generatePyTorchModelRegression.py"); + "!H:!V:VarTransform=D,G:FilenameModel=PyTorchModelRegression.pt:FilenameTrainedModel=trainedPyTorchModelRegression.pt:NumEpochs=10:BatchSize=32:SaveBestOnly=false:UserCode=generatePyTorchModelRegression.py"); std::cout << "Train model..." << std::endl; factory->TrainAllMethods(); diff --git a/tmva/rmva/test/Classification.C b/tmva/rmva/test/Classification.C index cac70c52e0619..73032d4225e05 100644 --- a/tmva/rmva/test/Classification.C +++ b/tmva/rmva/test/Classification.C @@ -23,7 +23,7 @@ void Classification() TMVA::Tools::Instance(); ROOT::R::TRInterface &r = ROOT::R::TRInterface::Instance(); - TString outfileName("TMVA.root"); + TString outfileName("RMVA.root"); TFile *outputFile = TFile::Open(outfileName, "RECREATE"); TMVA::Factory *factory = new TMVA::Factory("RMVAClassification", outputFile, diff --git a/tmva/sofie/CMakeLists.txt b/tmva/sofie/CMakeLists.txt index e049bd894a7bd..a51e5b7ca20fc 100644 --- a/tmva/sofie/CMakeLists.txt +++ b/tmva/sofie/CMakeLists.txt @@ -14,6 +14,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTTMVASofie HEADERS TMVA/OperatorList.hxx + TMVA/RModel_Base.hxx TMVA/RModel.hxx TMVA/ROperator.hxx TMVA/ROperator_BasicUnary.hxx @@ -41,10 +42,27 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTTMVASofie TMVA/ROperator_Custom.hxx TMVA/ROperator_LayerNormalization.hxx TMVA/ROperator_Expand.hxx + TMVA/ROperator_Erf.hxx + TMVA/ROperator_Swish.hxx TMVA/SOFIE_common.hxx TMVA/SOFIEHelpers.hxx + + TMVA/FunctionList.hxx + TMVA/RModel_GNN.hxx + TMVA/RModel_GraphIndependent.hxx + TMVA/RFunction.hxx + TMVA/RFunction_MLP.hxx + TMVA/RFunction_Sum.hxx + TMVA/RFunction_Mean.hxx SOURCES + src/RModel_Base.cxx src/RModel.cxx + src/RModel_GNN.cxx + src/RModel_GraphIndependent.cxx + src/RFunction.cxx + src/RFunction_MLP.cxx + src/RFunction_Mean.cxx + src/RFunction_Sum.cxx src/SOFIE_common.cxx DEPENDENCIES TMVA diff --git a/tmva/sofie/README.md b/tmva/sofie/README.md index d309b62ce737e..387fd72bdec09 100644 --- a/tmva/sofie/README.md +++ b/tmva/sofie/README.md @@ -1,13 +1,12 @@ -## About +# TMVA SOFIE -ROOT/TMVA SOFIE (“System for Optimized Fast Inference code Emitâ€) generates C++ functions easily invokable for the fast inference of trained neural network models. It takes ONNX model files as inputs and produces C++ header files that can be included and utilized in a “plug-and-go†style. +ROOT/TMVA SOFIE (___System for Optimized Fast Inference code Emit___) generates C++ functions easily invokable for the fast inference of trained neural network models. It takes ONNX model files as inputs and produces C++ header files that can be included and utilized in a “plug-and-go†style. -This is a new development in TMVA and is currently in early experimental stage. Bug reports and suggestions for improvements are [warmly welcomed](mailto:s.an@cern.ch). +This is a new development in TMVA and is currently in early experimental stage. Bug reports and suggestions for improvements are [warmly welcomed](mailto:Lorenzo.Moneta@cern.ch). ## Prerequisite - - Protobuf 3.0 or higher (for input of ONNX model files) - BLAS or Eigen (for execution of the generated code for inference) @@ -15,14 +14,15 @@ This is a new development in TMVA and is currently in early experimental stage. Build ROOT with the cmake option tmva-sofie enabled. - $ cmake ../root -Dtmva-sofie=ON - $ make -j8 - - +```bash +cmake ../root -Dtmva-sofie=ON +make -j8 +``` + ## Usage +SOFIE works in a parser-generator working architecture. With SOFIE, the user gets an [ONNX](https://github.com/root-project/root/tree/master/tmva/sofie_parsers), [Keras](https://github.com/root-project/root/blob/master/tmva/pymva/src/RModelParser_Keras.cxx) and a [PyTorch](https://github.com/root-project/root/blob/master/tmva/pymva/src/RModelParser_PyTorch.cxx) parser for translating models in respective formats into SOFIE's internal representation. - -From ROOT command line, or in a ROOT macro: +From ROOT command line, or in a ROOT macro, we can proceed with an ONNX model: using namespace TMVA::Experimental; SOFIE::RModelParser_ONNX parser; @@ -30,7 +30,7 @@ From ROOT command line, or in a ROOT macro: model.Generate(); model.OutputGenerated(“./example_output.hxxâ€); -And an C++ header file will be generated. You can also use +And an C++ header file and a `.dat` file containing the model weights will be generated. You can also use model.PrintRequiredInputTensors(); @@ -44,4 +44,31 @@ To use the generated inference code: #include "example_output.hxx" float input[INPUT_SIZE]; - std::vector out = TMVA_SOFIE_example_model::infer(input); + + // Generated header file shall contain a Session class which requires initialization to load the corresponding weights. + TMVA_SOFIE_example_model::Session s("example_model.dat") + + // Once instantiated the session object's infer method can be used + std::vector out = s.infer(input); + +With the default settings, the weights are contained in a separate binary file, but if the user instead wants them to be in the generated header file itself, they can use approproiate generation options. + + model.Generate(Options::kNoWeightFile); + +Other such options includes `Options::kNoSession` (for not generating the Session class, and instead keeping the infer function independent). +SOFIE also supports generating inference code with RDataFrame as inputs, refer to the tutorials below for examples. + + +## Additional Links + +- **Tutorials** + - [TMVA_SOFIE_Inference](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_Inference.py) + - [TMVA_SOFIE_Keras](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_Keras.C) + - [TMVA_SOFIE_Keras_HiggsModel](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_Keras_HiggsModel.C) + - [TMVA_SOFIE_ONNX](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_ONNX.C) + - [TMVA_SOFIE_PyTorch](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_PyTorch.C) + - [TMVA_SOFIE_RDataFrame](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_RDataFrame.C) + - [TMVA_SOFIE_RDataFrame](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_RDataFrame.py) + - [TMVA_SOFIE_RDataFrame_JIT](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_RDataFrame_JIT.C) + - [TMVA_SOFIE_RSofieReader](https://github.com/root-project/root/blob/master/tutorials/tmva/TMVA_SOFIE_RSofieReader.C) + diff --git a/tmva/sofie/inc/LinkDef.h b/tmva/sofie/inc/LinkDef.h index 3282ff22c1d32..12ade07ad58a2 100644 --- a/tmva/sofie/inc/LinkDef.h +++ b/tmva/sofie/inc/LinkDef.h @@ -8,6 +8,7 @@ #pragma link C++ nestedclass; #pragma link C++ namespace TMVA::Experimental::SOFIE; +#pragma link C++ class TMVA::Experimental::SOFIE::RModel_Base+; #pragma link C++ class TMVA::Experimental::SOFIE::RModel-; #pragma link C++ class TMVA::Experimental::SOFIE::ROperator+; #pragma link C++ struct TMVA::Experimental::SOFIE::InitializedTensor+; diff --git a/tmva/sofie/inc/TMVA/FunctionList.hxx b/tmva/sofie/inc/TMVA/FunctionList.hxx new file mode 100644 index 0000000000000..eebadd3aaba70 --- /dev/null +++ b/tmva/sofie/inc/TMVA/FunctionList.hxx @@ -0,0 +1,6 @@ +// Update functions +#include "TMVA/RFunction_MLP.hxx" + +// Aggregate functions +#include "TMVA/RFunction_Sum.hxx" +#include "TMVA/RFunction_Mean.hxx" diff --git a/tmva/sofie/inc/TMVA/OperatorList.hxx b/tmva/sofie/inc/TMVA/OperatorList.hxx index 2aa9350cd2148..37ffec6cc83f3 100644 --- a/tmva/sofie/inc/TMVA/OperatorList.hxx +++ b/tmva/sofie/inc/TMVA/OperatorList.hxx @@ -27,3 +27,5 @@ #include "TMVA/ROperator_LayerNormalization.hxx" #include "TMVA/ROperator_Expand.hxx" #include "TMVA/ROperator_Gather.hxx" +#include "TMVA/ROperator_Swish.hxx" +#include "TMVA/ROperator_Erf.hxx" diff --git a/tmva/sofie/inc/TMVA/RFunction.hxx b/tmva/sofie/inc/TMVA/RFunction.hxx new file mode 100644 index 0000000000000..9d4f75d45f701 --- /dev/null +++ b/tmva/sofie/inc/TMVA/RFunction.hxx @@ -0,0 +1,88 @@ +#ifndef TMVA_SOFIE_RFUNCTION +#define TMVA_SOFIE_RFUNCTION + +#include "TMVA/RModel_Base.hxx" +#include "TMVA/SOFIE_common.hxx" + +#include +#include + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +class RModel; + + +class RFunction { +protected: + std::string fFuncName; + FunctionType fType; +public: + RFunction() {} + virtual ~RFunction() {} + FunctionType GetFunctionType() { + return fType; + } + + RFunction(std::string funcName, FunctionType type): + fFuncName(UTILITY::Clean_name(funcName)),fType(type) {} + +}; + +class RFunction_Update: public RFunction { +protected: + std::shared_ptr function_block; + FunctionTarget fTarget; + GraphType fGraphType; + std::vector fInputTensors; + std::vector fAddlOp; // temporary vector to store pointer that will be moved in a unique_ptr + +public: + virtual ~RFunction_Update() {} + RFunction_Update() {} + RFunction_Update(FunctionTarget target, GraphType gType); + + virtual void AddInitializedTensors(const std::vector>&) {}; + virtual void Initialize() {}; + virtual void AddLayerNormalization(int, float, size_t, const std::string&, + const std::string&, const std::string&, const std::string&) {}; + void AddInputTensors(const std::vector>& fInputShape); + std::shared_ptr GetFunctionBlock() { + return function_block; + } + + std::string GenerateModel(const std::string& filename, long read_pos=0, long block_size=1); + std::string Generate(const std::vector& inputPtrs); + FunctionTarget GetFunctionTarget() { + return fTarget; + } +}; + +class RFunction_Aggregate: public RFunction { +protected: + FunctionReducer fReducer; +public: + virtual ~RFunction_Aggregate() {} + RFunction_Aggregate() {} + RFunction_Aggregate(FunctionReducer reducer): fReducer(reducer) { + fType = FunctionType::AGGREGATE; + } + virtual std::string GenerateModel() = 0; + std::string GetFunctionName() { + return fFuncName; + } + FunctionReducer GetFunctionReducer() { + return fReducer; + } + std::string Generate(std::size_t num_features, const std::vector& inputTensors); + +}; + + +}//SOFIE +}//Experimental +}//TMVA + + +#endif //TMVA_SOFIE_RFUNCTION diff --git a/tmva/sofie/inc/TMVA/RFunction_MLP.hxx b/tmva/sofie/inc/TMVA/RFunction_MLP.hxx new file mode 100644 index 0000000000000..c838b4c1c166c --- /dev/null +++ b/tmva/sofie/inc/TMVA/RFunction_MLP.hxx @@ -0,0 +1,45 @@ +#ifndef TMVA_SOFIE_RFUNCTION_MLP +#define TMVA_SOFIE_RFUNCTION_MLP + +#include "TMVA/RFunction.hxx" + +#include + + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +enum class Activation { + RELU = 0x0, + Invalid = 0x1, +}; + +class RFunction_MLP: public RFunction_Update { +private: + Int_t fNumLayers; // Number of Layers in MLP + Activation fActivationFunction; + bool fActivateFinal; // if True, fActivationFunction is applied as the activation for the last layer + std::vector fKernelTensors; + std::vector fBiasTensors; + +public: + virtual ~RFunction_MLP() {} + RFunction_MLP(FunctionTarget target, Int_t numLayers, Activation activation_function=Activation::RELU, bool activate_final=false, GraphType gType=GraphType::GNN); + + void Initialize(); + + void AddLayerNormalization(int axis, float epsilon, size_t stashType, const std::string &nameX, + const std::string &nameScale, const std::string &nameB, const std::string &nameY); + + void AddInitializedTensors(const std::vector>& initialized_tensors) { + fKernelTensors = initialized_tensors[0]; + fBiasTensors = initialized_tensors[1]; + } +}; + +} // SOFIE +} // Experimental +} // TMVA + +#endif //TMVA_SOFIE_RFUNCTION_MLP diff --git a/tmva/sofie/inc/TMVA/RFunction_Mean.hxx b/tmva/sofie/inc/TMVA/RFunction_Mean.hxx new file mode 100644 index 0000000000000..ba9dda6cd45cc --- /dev/null +++ b/tmva/sofie/inc/TMVA/RFunction_Mean.hxx @@ -0,0 +1,24 @@ +#ifndef TMVA_SOFIE_RFUNCTION_MEAN +#define TMVA_SOFIE_RFUNCTION_MEAN + +#include "TMVA/RFunction.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +class RFunction_Mean: public RFunction_Aggregate { + +public: + RFunction_Mean():RFunction_Aggregate(FunctionReducer::MEAN) { + fFuncName = "Aggregate_by_Mean"; + } + + std::string GenerateModel(); +}; + +} //SOFIE +} //Experimental +} //TMVA + +#endif //TMVA_SOFIE_RFUNCTION_MEAN diff --git a/tmva/sofie/inc/TMVA/RFunction_Sum.hxx b/tmva/sofie/inc/TMVA/RFunction_Sum.hxx new file mode 100644 index 0000000000000..db7e9d5dabbf9 --- /dev/null +++ b/tmva/sofie/inc/TMVA/RFunction_Sum.hxx @@ -0,0 +1,25 @@ +#ifndef TMVA_SOFIE_RFUNCTION_SUM +#define TMVA_SOFIE_RFUNCTION_SUM + + +#include "TMVA/RFunction.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +class RFunction_Sum: public RFunction_Aggregate { + +public: + RFunction_Sum():RFunction_Aggregate(FunctionReducer::SUM) { + fFuncName = "Aggregate_by_Sum"; + } + + std::string GenerateModel(); +}; + +} //SOFIE +} //Experimental +} //TMVA + +#endif //TMVA_SOFIE_RFUNCTION_SUM diff --git a/tmva/sofie/inc/TMVA/RModel.hxx b/tmva/sofie/inc/TMVA/RModel.hxx index f36fec89a6380..9e47fe9a299fd 100644 --- a/tmva/sofie/inc/TMVA/RModel.hxx +++ b/tmva/sofie/inc/TMVA/RModel.hxx @@ -1,145 +1,131 @@ #ifndef TMVA_SOFIE_RMODEL #define TMVA_SOFIE_RMODEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "TMVA/RModel_Base.hxx" #include "TMVA/SOFIE_common.hxx" #include "TMVA/ROperator.hxx" -#include "TBuffer.h" -namespace TMVA{ -namespace Experimental{ -namespace SOFIE{ +namespace TMVA { +namespace Experimental { +namespace SOFIE { -enum class Options { - kDefault = 0x0, - kNoSession = 0x1, - kNoWeightFile = 0x2, -}; - -std::underlying_type_t operator|(Options opA, Options opB); -std::underlying_type_t operator|(std::underlying_type_t opA, Options opB); - -class RModel: public TObject{ +class RModel: public RModel_Base { private: - std::unordered_map fInputTensorInfos; //graph input only; not including operator input (intermediate tensors) - std::unordered_map fReadyInputTensorInfos; - std::unordered_map fInitializedTensors; - std::unordered_map fIntermediateTensorInfos; - std::vector fOutputTensorNames; - std::vector fInputTensorNames; //input tensor names using ONNX order - - std::vector> fOperators; - - std::string fName="UnnamedModel"; - std::string fFileName; //file name of original model file for identification - std::string fParseTime; //UTC date and time string at parsing - - std::string fGC; //generated code - std::unordered_set fNeededBlasRoutines; + std::unordered_map fInputTensorInfos; //graph input only; not including operator input (intermediate tensors) + std::unordered_map fReadyInputTensorInfos; + std::unordered_map fInitializedTensors; + std::unordered_map fIntermediateTensorInfos; + std::vector fOutputTensorNames; + std::vector fInputTensorNames; //input tensor names using ONNX order - const std::unordered_set fAllowedStdLib = {"vector", "algorithm", "cmath"}; - std::unordered_set fNeededStdLib = {"vector"}; - std::unordered_set fCustomOpHeaders; - bool fUseWeightFile = true; - bool fUseSession = true; + std::vector> fOperators; public: - //explicit move ctor/assn - RModel(RModel&& other); - - RModel& operator=(RModel&& other); - - //disallow copy - RModel(const RModel& other) = delete; - RModel& operator=(const RModel& other) = delete; - - RModel(){} - RModel(std::string name, std::string parsedtime); - - const std::vector& GetTensorShape(std::string name); - const ETensorType& GetTensorType(std::string name); - - bool CheckIfTensorAlreadyExist(std::string tensor_name); - void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape); - void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape); - void AddOperator(std::unique_ptr op, int order_execution = -1); - void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data); - // Check if a tensor is initialized - bool IsInitializedTensor(const std::string& name) const; - void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector shape); - void AddBlasRoutines(std::vector routines) { - for (auto &routine : routines) { - fNeededBlasRoutines.insert(routine); - } - } - void AddNeededStdLib(std::string libname) { - if (fAllowedStdLib.find(libname) != fAllowedStdLib.end()) { - fNeededStdLib.insert(libname); - } - } - void AddNeededCustomHeader(std::string filename) { - fCustomOpHeaders.insert(filename); - } - void AddInputTensorName(std::string name); - void AddOutputTensorNameList(std::vector outputtensornames); - void UpdateOutputTensorList(std::vector curr_output_tensor, std::vector modify_output_tensor); - void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data); - std::shared_ptr GetInitializedTensorData(std::string tensor_name); - - - void Initialize(int batchSize=1); - void Generate(std::underlying_type_t options, int batchSize = 1); - void Generate(Options options = Options::kDefault, int batchSize = 1) { - Generate(static_cast>(options), batchSize); - } - - void ReadInitializedTensorsFromFile(); - void WriteInitializedTensorsToFile(std::string filename = ""); - - void PrintGenerated(){ - std::cout << fGC; - } - void PrintIntermediateTensors(); - void OutputGenerated(std::string filename = ""); - std::vector GetOutputTensorNames(){ - return fOutputTensorNames; - } - -/* - template - void AddInitializedTensor(std::string tensor_name, RTensor new_tensor){ - //a view only - T obj; - if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()){ - throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n"); - } - InitializedTensor new_tensor_ {GetTemplatedType(obj), new_tensor.GetShape() , static_cast(new_tensor.GetData())}; - fInitializedTensors[tensor_name] = new_tensor_; - } -*/ - - void PrintRequiredInputTensors(); - void PrintInitializedTensors(); - void HeadInitializedTensors(std::string name, int n_print = 50); - - bool UseSession() const { return fUseSession;} - - ~RModel() {} - - ClassDef(RModel,1); + //explicit move ctor/assn + RModel(RModel&& other); + + RModel& operator=(RModel&& other); + + //disallow copy + RModel(const RModel& other) = delete; + RModel& operator=(const RModel& other) = delete; + + RModel() {} + RModel(std::string name, std::string parsedtime): RModel_Base(name, parsedtime) {} + + // For GNN Functions usage + RModel(std::string function_name):RModel_Base(function_name) {} + + const std::vector& GetTensorShape(std::string name); + const ETensorType& GetTensorType(std::string name); + + bool CheckIfTensorAlreadyExist(std::string tensor_name); + void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape); + void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape); + void AddOperator(std::unique_ptr op, int order_execution = -1); + void AddOperatorReference(ROperator* op, int order_execution = -1) { + std::unique_ptr tmp(op); + AddOperator(std::move(tmp), order_execution); + } + void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data); + + template + void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, T* raw_data) { + int size=1; + for(auto item:shape) { + size*=(int)item; + } + std::shared_ptr data(malloc(size * sizeof(T)), free); + std::memcpy(data.get(), raw_data, size * sizeof(T)); + AddInitializedTensor(tensor_name, type, shape, data); + } + + // Check if a tensor is initialized + bool IsInitializedTensor(const std::string& name) const; + void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector shape); + + void AddInputTensorName(std::string name); + void AddOutputTensorNameList(std::vector outputtensornames); + void UpdateOutputTensorList(std::vector curr_output_tensor, std::vector modify_output_tensor); + void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data); + std::shared_ptr GetInitializedTensorData(std::string tensor_name); + + void Initialize(int batchSize=1); + void GenerateInitializedTensorInfo(); + void GenerateIntermediateTensorInfo(); + void GenerateOutput(); + void Generate(std::underlying_type_t options, int batchSize = 1, long pos = 0); + void Generate(Options options = Options::kDefault, int batchSize = 1, int pos = 0) { + Generate(static_cast>(options), batchSize, pos); + } + + const std::vector & GetInputTensorNames() const { + return fInputTensorNames; + } + const std::vector & GetOutputTensorNames() const { + return fOutputTensorNames; + } + + void ReadInitializedTensorsFromFile(long); + long WriteInitializedTensorsToFile(std::string filename = ""); + + void PrintIntermediateTensors(); + void PrintOutputTensors(); + void OutputGenerated(std::string filename = "", bool append = false); + std::vector GetOutputTensorNames() { + return fOutputTensorNames; + } + void SetFilename(std::string filename) { + fName = filename; + } + + /* + template + void AddInitializedTensor(std::string tensor_name, RTensor new_tensor){ + //a view only + T obj; + if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()){ + throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n"); + } + InitializedTensor new_tensor_ {GetTemplatedType(obj), new_tensor.GetShape() , static_cast(new_tensor.GetData())}; + fInitializedTensors[tensor_name] = new_tensor_; + } + */ + + void PrintRequiredInputTensors(); + void PrintInitializedTensors(); + void HeadInitializedTensors(std::string name, int n_print = 50); + + bool UseSession() const { + return fUseSession; + } + + ~RModel() {} + + ClassDef(RModel,1); }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/RModel_Base.hxx b/tmva/sofie/inc/TMVA/RModel_Base.hxx new file mode 100644 index 0000000000000..399e06c7f24d4 --- /dev/null +++ b/tmva/sofie/inc/TMVA/RModel_Base.hxx @@ -0,0 +1,125 @@ +#ifndef TMVA_SOFIE_RMODEL_BASE +#define TMVA_SOFIE_RMODEL_BASE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "TMVA/SOFIE_common.hxx" +#include "TMVA/ROperator.hxx" +#include "TBuffer.h" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +enum class Options { + kDefault = 0x0, + kNoSession = 0x1, + kNoWeightFile = 0x2, + kRootBinaryWeightFile = 0x4, + kGNN = 0x8, + kGNNComponent = 0x10, +}; + +enum class WeightFileType {None, RootBinary, Text}; + +std::underlying_type_t operator|(Options opA, Options opB); +std::underlying_type_t operator|(std::underlying_type_t opA, Options opB); + +class RModel_Base: public TObject { + +protected: + std::string fFileName; //file name of original model file for identification + std::string fParseTime; //UTC date and time string at parsing + + WeightFileType fWeightFile = WeightFileType::Text; + + std::unordered_set fNeededBlasRoutines; + + const std::unordered_set fAllowedStdLib = {"vector", "algorithm", "cmath"}; + std::unordered_set fNeededStdLib = {"vector"}; + std::unordered_set fCustomOpHeaders; + + std::string fName="UnnamedModel"; + std::string fGC; //generated code + bool fUseWeightFile = true; + bool fUseSession = true; + bool fIsGNN = false; + bool fIsGNNComponent = false; + +public: + RModel_Base() {} + + RModel_Base(std::string name, std::string parsedtime); + + // For GNN Functions usage + RModel_Base(std::string function_name):fName(function_name) {} + + void AddBlasRoutines(std::vector routines) { + for (auto &routine : routines) { + fNeededBlasRoutines.insert(routine); + } + } + void AddNeededStdLib(std::string libname) { + if (fAllowedStdLib.find(libname) != fAllowedStdLib.end()) { + fNeededStdLib.insert(libname); + } + } + void AddNeededCustomHeader(std::string filename) { + fCustomOpHeaders.insert(filename); + } + void GenerateHeaderInfo(std::string& hgname); + void PrintGenerated() { + std::cout << fGC; + } + + std::string ReturnGenerated() { + return fGC; + } + void OutputGenerated(std::string filename = "", bool append = false); + void SetFilename(std::string filename) { + fName = filename; + } + std::string GetFilename() { + return fName; + } + + ClassDef(RModel_Base,1); + +}; + +enum class GraphType { + INVALID=0, GNN=1, GraphIndependent=2 +}; + +enum class FunctionType { + UPDATE=0, AGGREGATE=1 +}; +enum class FunctionTarget { + INVALID=0, NODES=1, EDGES=2, GLOBALS=3 +}; +enum class FunctionReducer { + INVALID=0, SUM=1, MEAN=2 +}; +enum class FunctionRelation { + INVALID=0, NODES_EDGES=1, NODES_GLOBALS=2, EDGES_GLOBALS=3 +}; + +class RModel_GNNBase: public RModel_Base { +public: + RModel_GNNBase() {} + virtual void Generate() = 0; +}; + +}//SOFIE +}//Experimental +}//TMVA + +#endif //TMVA_SOFIE_RMODEL_BASE diff --git a/tmva/sofie/inc/TMVA/RModel_GNN.hxx b/tmva/sofie/inc/TMVA/RModel_GNN.hxx new file mode 100644 index 0000000000000..2db1cd3531d9f --- /dev/null +++ b/tmva/sofie/inc/TMVA/RModel_GNN.hxx @@ -0,0 +1,138 @@ +#ifndef TMVA_SOFIE_RMODEL_GNN +#define TMVA_SOFIE_RMODEL_GNN + +#include + +#include "TMVA/RModel_Base.hxx" +#include "TMVA/RModel.hxx" +#include "TMVA/RFunction.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +class RFunction_Update; +class RFunction_Aggregate; + +struct GNN_Init { + // updation blocks + std::unique_ptr edges_update_block; + std::unique_ptr nodes_update_block; + std::unique_ptr globals_update_block; + + // aggregation blocks + std::unique_ptr edge_node_agg_block; + std::unique_ptr edge_global_agg_block; + std::unique_ptr node_global_agg_block; + + int num_nodes; + std::vector> edges; + + std::size_t num_node_features; + std::size_t num_edge_features; + std::size_t num_global_features; + + std::string filename; + + ~GNN_Init() { + edges_update_block.reset(); + nodes_update_block.reset(); + globals_update_block.reset(); + + edge_node_agg_block.reset(); + edge_global_agg_block.reset(); + node_global_agg_block.reset(); + } + + template + void createUpdateFunction(T& updateFunction) { + switch(updateFunction.GetFunctionTarget()) { + case FunctionTarget::EDGES: { + edges_update_block.reset(new T(updateFunction)); + break; + } + case FunctionTarget::NODES: { + nodes_update_block.reset(new T(updateFunction)); + break; + } + case FunctionTarget::GLOBALS: { + globals_update_block.reset(new T(updateFunction)); + break; + } + default: { + throw std::runtime_error("TMVA SOFIE: Invalid Update function supplied for creating GNN function block."); + } + } + } + + template + void createAggregateFunction(T& aggFunction, FunctionRelation relation) { + switch(relation) { + case FunctionRelation::NODES_EDGES : { + edge_node_agg_block.reset(new T(aggFunction)); + break; + } + case FunctionRelation::NODES_GLOBALS: { + node_global_agg_block.reset(new T(aggFunction)); + break; + } + case FunctionRelation::EDGES_GLOBALS: { + edge_global_agg_block.reset(new T(aggFunction)); + break; + } + default: { + throw std::runtime_error("TMVA SOFIE: Invalid Aggregate function supplied for creating GNN function block."); + } + } + } + +}; + +class RModel_GNN: public RModel_GNNBase { + +private: + + // updation function for edges, nodes & global attributes + std::unique_ptr edges_update_block; + std::unique_ptr nodes_update_block; + std::unique_ptr globals_update_block; + + // aggregation function for edges, nodes & global attributes + std::unique_ptr edge_node_agg_block; + std::unique_ptr edge_global_agg_block; + std::unique_ptr node_global_agg_block; + + int num_nodes; + int num_edges; + std::vector senders; // contains node indices + std::vector receivers; // contains node indices + + std::size_t num_node_features; + std::size_t num_edge_features; + std::size_t num_global_features; + +public: + + //explicit move ctor/assn + RModel_GNN(RModel_GNN&& other); + + RModel_GNN& operator=(RModel_GNN&& other); + + //disallow copy + RModel_GNN(const RModel_GNN& other) = delete; + RModel_GNN& operator=(const RModel_GNN& other) = delete; + + RModel_GNN(GNN_Init& graph_input_struct); + RModel_GNN() {} + + void Generate(); + + ~RModel_GNN() {} +// ClassDef(RModel_GNN,1); +}; + +}//SOFIE +}//Experimental +}//TMVA + +#endif //TMVA_SOFIE_RMODEL_GNN diff --git a/tmva/sofie/inc/TMVA/RModel_GraphIndependent.hxx b/tmva/sofie/inc/TMVA/RModel_GraphIndependent.hxx new file mode 100644 index 0000000000000..6f09805fd6075 --- /dev/null +++ b/tmva/sofie/inc/TMVA/RModel_GraphIndependent.hxx @@ -0,0 +1,99 @@ +#ifndef TMVA_SOFIE_RMODEL_GraphIndependent +#define TMVA_SOFIE_RMODEL_GraphIndependent + +#include + +#include "TMVA/RModel_Base.hxx" +#include "TMVA/RModel.hxx" +#include "TMVA/RFunction.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +class RFunction_Update; + +struct GraphIndependent_Init { + // updation blocks + std::unique_ptr edges_update_block; + std::unique_ptr nodes_update_block; + std::unique_ptr globals_update_block; + + int num_nodes; + std::vector> edges; + + int num_node_features; + int num_edge_features; + int num_global_features; + + std::string filename; + + template + void createUpdateFunction(T& updateFunction) { + switch(updateFunction.GetFunctionTarget()) { + case FunctionTarget::EDGES: { + edges_update_block.reset(new T(updateFunction)); + break; + } + case FunctionTarget::NODES: { + nodes_update_block.reset(new T(updateFunction)); + break; + } + case FunctionTarget::GLOBALS: { + globals_update_block.reset(new T(updateFunction)); + break; + } + default: { + throw std::runtime_error("TMVA SOFIE: Invalid Update function supplied for creating GraphIndependent function block."); + } + } + } + + ~GraphIndependent_Init() { + edges_update_block.reset(); + nodes_update_block.reset(); + globals_update_block.reset(); + } +}; + +class RModel_GraphIndependent: public RModel_GNNBase { + +private: + + // updation function for edges, nodes & global attributes + std::unique_ptr edges_update_block; + std::unique_ptr nodes_update_block; + std::unique_ptr globals_update_block; + + int num_nodes; + int num_edges; + + std::size_t num_node_features; + std::size_t num_edge_features; + std::size_t num_global_features; + +public: + + //explicit move ctor/assn + RModel_GraphIndependent(RModel_GraphIndependent&& other); + + RModel_GraphIndependent& operator=(RModel_GraphIndependent&& other); + + //disallow copy + RModel_GraphIndependent(const RModel_GraphIndependent& other) = delete; + RModel_GraphIndependent& operator=(const RModel_GraphIndependent& other) = delete; + + RModel_GraphIndependent(GraphIndependent_Init& graph_input_struct); + RModel_GraphIndependent() {} + + void Generate(); + + ~RModel_GraphIndependent() {} +// ClassDef(RModel_GNN,1); +}; + +}//SOFIE +}//Experimental +}//TMVA + +#endif //TMVA_SOFIE_RMODEL_GNN diff --git a/tmva/sofie/inc/TMVA/ROperator.hxx b/tmva/sofie/inc/TMVA/ROperator.hxx index d02a8e50fe595..e1b3faae372e0 100644 --- a/tmva/sofie/inc/TMVA/ROperator.hxx +++ b/tmva/sofie/inc/TMVA/ROperator.hxx @@ -19,8 +19,8 @@ class ROperator{ public: - virtual std::vector GetBlasRoutines() { return {};} - virtual std::vector GetStdLibs() { return {};} + virtual std::vector GetBlasRoutines() { return {}; } + virtual std::vector GetStdLibs() { return {}; } virtual std::vector> ShapeInference(std::vector>) = 0; virtual std::vector TypeInference(std::vector) = 0; virtual void Initialize(RModel&) = 0; @@ -33,13 +33,13 @@ public: //virtual void Forward_reference() = 0; - //irtual void Forward_blas() = 0; + //virtual void Forward_blas() = 0; virtual ~ROperator(){} protected: - + const std::string SP = " "; ///< space used to correctly indent the generated C++ code - bool fUseSession = false; ///< flag to identify if using the session class + bool fUseSession = false; ///< flag to identify if using the session class }; diff --git a/tmva/sofie/inc/TMVA/ROperator_BasicBinary.hxx b/tmva/sofie/inc/TMVA/ROperator_BasicBinary.hxx index 55942a4e9fc94..52b5ffea6f1bb 100644 --- a/tmva/sofie/inc/TMVA/ROperator_BasicBinary.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_BasicBinary.hxx @@ -173,7 +173,7 @@ public: std::vector GetStdLibs() override { if (Op == EBasicBinaryOperator::Pow) { - return {"cmath"}; + return { std::string("cmath") }; } else { return {}; } diff --git a/tmva/sofie/inc/TMVA/ROperator_BasicNary.hxx b/tmva/sofie/inc/TMVA/ROperator_BasicNary.hxx index e53fb9a3a3228..7849457751d01 100644 --- a/tmva/sofie/inc/TMVA/ROperator_BasicNary.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_BasicNary.hxx @@ -102,14 +102,14 @@ public: fNInputs.push_back(UTILITY::Clean_name(name)); } - // type of output given input + // type of output given input std::vector TypeInference(std::vector input){ return input; } // shape of output tensors given input tensors std::vector> ShapeInference(std::vector> input){ - auto ret = std::vector>(1, input[0]); + auto ret = std::vector>(1, input[0]); return ret; } @@ -176,7 +176,7 @@ public: return out.str(); } - std::vector GetStdLibs() {return {"cmath"};} + std::vector GetStdLibs() {return { std::string("cmath") }; } }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_BasicUnary.hxx b/tmva/sofie/inc/TMVA/ROperator_BasicUnary.hxx index 930c067a4e03c..e573fea735c9b 100644 --- a/tmva/sofie/inc/TMVA/ROperator_BasicUnary.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_BasicUnary.hxx @@ -9,7 +9,7 @@ namespace TMVA { namespace Experimental { namespace SOFIE { -enum class EBasicUnaryOperator { kReciprocal, kSqrt , kNeg, kExp}; +enum class EBasicUnaryOperator { kReciprocal, kSqrt , kNeg, kExp, kLog }; template struct UnaryOpTraits { @@ -39,6 +39,12 @@ struct UnaryOpTraits { static std::string Op(const std::string &X) { return "std::exp(" + X + ")"; } }; +template +struct UnaryOpTraits { + static std::string Name() { return "Log"; } + static std::string Op(const std::string &X) { return "std::log(" + X + ")"; } +}; + template class ROperator_BasicUnary final : public ROperator { private: diff --git a/tmva/sofie/inc/TMVA/ROperator_BatchNormalization.hxx b/tmva/sofie/inc/TMVA/ROperator_BatchNormalization.hxx index e684559bff0d5..dc436e0ed4f3a 100644 --- a/tmva/sofie/inc/TMVA/ROperator_BatchNormalization.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_BatchNormalization.hxx @@ -45,11 +45,11 @@ public: /* Constructor */ ROperator_BatchNormalization( float epsilon, float momentum, std::size_t training_mode, - std::string nameX, std::string nameScale, std::string nameB, + std::string nameX, std::string nameScale, std::string nameB, std::string nameMean, std::string nameVar, std::string nameY): fepsilon(epsilon), fmomentum(momentum), ftraining_mode(training_mode), - fNX(UTILITY::Clean_name(nameX)), fNScale(UTILITY::Clean_name(nameScale)), - fNB(UTILITY::Clean_name(nameB)), fNMean(UTILITY::Clean_name(nameMean)), + fNX(UTILITY::Clean_name(nameX)), fNScale(UTILITY::Clean_name(nameScale)), + fNB(UTILITY::Clean_name(nameB)), fNMean(UTILITY::Clean_name(nameMean)), fNVar(UTILITY::Clean_name(nameVar)), fNY(UTILITY::Clean_name(nameY)) { if(std::is_same::value){ @@ -60,7 +60,7 @@ public: std::runtime_error("TMVA SOFIE Encountered unsupported type parsing a BatchNormalization operator"); } } - + std::vector TypeInference(std::vector input) { ETensorType out = input[0]; @@ -79,7 +79,7 @@ public: } } - auto ret = input; + auto ret = input; return ret; } @@ -159,7 +159,7 @@ public: } //// new_var =1. / sqrt(input_var + fepsilon) for(size_t i=0; i new_bias_shape = {batchSize,channels,height,width}; std::shared_ptr new_bias_ptr(new_bias, std::default_delete()); @@ -201,7 +201,7 @@ public: //// blas saxpy (Y = -Bmean + Y) out << SP << "float "< GetBlasRoutines() { return {"Copy", "Axpy"};} + std::vector GetBlasRoutines() { return { std::string("Copy"), std::string("Axpy") }; } }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Conv.hxx b/tmva/sofie/inc/TMVA/ROperator_Conv.hxx index ef7ad07d74e71..fefd6217f4aaf 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Conv.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Conv.hxx @@ -85,11 +85,11 @@ public: return {out}; } - // function returning output shape given input + // function returning output shape given input std::vector> ShapeInference(std::vector> input) { - // shape of convolution input has to be (according to ONNX): N x C x H x W + // shape of convolution input has to be (according to ONNX): N x C x H x W // Where N : batch size, C : input channels, H : input height, W : input width - + if (input.size() > 3 ) { throw std::runtime_error("TMVA SOFIE Conv Op Shape inference need 2 or 3 input tensors"); @@ -105,7 +105,7 @@ public: fAttrGroup = input[0][1] / input[1][1]; } - // kernel shape + // kernel shape size_t k1 = ((fAttrKernelShape.empty())? input[1][2] : fAttrKernelShape[0]); size_t k2 = (fDim > 1) ? ((fAttrKernelShape.empty()) ? input[1][3] : fAttrKernelShape[1]) : 1; size_t k3 = (fDim > 2) ? ((fAttrKernelShape.empty()) ? input[1][4] : fAttrKernelShape[2]) : 1; @@ -118,12 +118,12 @@ public: if (fAttrDilations.empty()) { fAttrDilations = {1, 1, 1}; } - fAttrDilations.resize(3); + fAttrDilations.resize(3); if (fDim < 3) { fAttrDilations.resize(3, 1); } // Shape of the kernel - fAttrKernelShape = {k1 + (fAttrDilations[0] - 1) * (k1 - 1), + fAttrKernelShape = {k1 + (fAttrDilations[0] - 1) * (k1 - 1), k2 + (fAttrDilations[1] - 1) * (k2 - 1), k3 + (fAttrDilations[2] - 1) * (k3 - 1)}; @@ -176,7 +176,7 @@ public: std::vector> ret({{ batch_size, output_channels, output1 }}); - if (fDim == 1) + if (fDim == 1) return ret; size_t pad2 = fAttrPads[1] + fAttrPads[i2]; @@ -231,7 +231,7 @@ public: // make bias shape equal to Y shape by adding 1 if (fShapeB.size() < 1) throw std::runtime_error("TMVA SOFIE Conv op: Bias Tensor has empty shape"); - // we assume bias tensor dimension is equal to number of filters that is the second dimension in + // we assume bias tensor dimension is equal to number of filters that is the second dimension in // the output tensor if (fShapeB[0] != fShapeY[1]) throw std::runtime_error("TMVA SOFIE Conv op: Bias Tensor has wrong shape: " + @@ -249,7 +249,7 @@ public: fShapeB = model.GetTensorShape(fNB); fNB2 = fNB; // use same name } - else { + else { // In case of session add broadcasting code in Session constructor and in GenerateInitCode // we need to add a new intermediate tensor for broadcasted bias tensor fNB2 = fNB + "bcast"; @@ -293,11 +293,11 @@ public: out << "std::vector<" << fType << "> fVec_" << opName << "_f = std::vector<" << fType << ">(" << fShapeW[0] * fShapeW[1] * kernelSize << ");\n"; // output matrix of im2col - out << "std::vector<" << fType << "> fVec_" << opName << "_xcol = std::vector<" << fType << ">(" + out << "std::vector<" << fType << "> fVec_" << opName << "_xcol = std::vector<" << fType << ">(" << fShapeW[1] * kernelSize * outputChannelSize << ");\n"; out << "\n"; - return out.str(); + return out.str(); } std::string Generate(std::string OpName) { @@ -325,12 +325,12 @@ public: // create first matrix with convolution kernels if (fUseSession) out << SP << fType << " * " << OpName << "_f = fVec_" << OpName << "_f.data();\n"; - else + else out << SP << fType << " " << OpName << "_f[" << fShapeW[0] * fShapeW[1] * fAttrKernelShape[0] * fAttrKernelShape[1] << "] = {0};\n"; // vectorize the (dilated)convolution kernels into a matrix // no need to transpose the matrix - // to fix for 1d and 3d + // to fix for 1d and 3d size_t id = (fDim > 2) ? fDim-3 : 2; size_t ih = (fDim > 1) ? fDim-2 : 1; @@ -353,11 +353,11 @@ public: if (fDim > 1) out << SP << SP << SP << "for (std::size_t kh = 0; kh < " << kHeight << "; kh++) {\n"; out << SP << SP << SP << SP << "for (std::size_t kw = 0; kw < " << kWidth << "; kw++) {\n"; - + out << SP << SP << SP << SP << SP << OpName << "_f[oc * " - << ocstrideDil << " + ic * " << icstrideDil; + << ocstrideDil << " + ic * " << icstrideDil; if (fDim > 2) out << " + kd * " << dstrideDil; - if (fDim > 1) out << " + kh * " << hstrideDil; + if (fDim > 1) out << " + kh * " << hstrideDil; out << " + kw * " << wstrideDil << " ] = tensor_" << fNW << "[oc * " << ocstride << " + ic * " << icstride; if (fDim > 2) out << " + kd * " << dstride; if (fDim > 1) out << " + kh * " << hstride; @@ -385,11 +385,11 @@ public: } else { out << SP << fType << " " << OpName << "_xcol[" - << fShapeX[1] * fAttrKernelShape[0] * fAttrKernelShape[1] * fAttrKernelShape[2] * oDepth * oHeight * oWidth + << fShapeX[1] * fAttrKernelShape[0] * fAttrKernelShape[1] * fAttrKernelShape[2] * oDepth * oHeight * oWidth << "] = {0};\n"; } - // Loop on batch size + // Loop on batch size out << SP << "for (size_t n = 0; n < " << bsize << "; n++) {\n"; // IM2COL: Unroll the input tensor @@ -414,7 +414,7 @@ public: fAttrPads[0] = (fAttrPads[0] + fAttrPads[2]) / 2; fAttrPads[1] = (fAttrPads[1] + fAttrPads[3]) / 2; } - } + } if (fDim == 3) { if (fAttrPads[0] != fAttrPads[3] || fAttrPads[1] != fAttrPads[4] || fAttrPads[2] != fAttrPads[5]) { std::cout << "TMVA SOFIE Operator Conv: asymmetric padding not supported. Assume an average padding " << std::endl; @@ -444,18 +444,18 @@ public: << "," << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrDilations[0] << "," << fAttrDilations[1]; out << "," << OpName << "_xcol);\n\n "; - } else { + } else { // 3d im2col out << SP << SP << "TMVA::Experimental::SOFIE::UTILITY::Im2col_3d(tensor_" << fNX << " + x_offset," - // channels, d, h, w, k_d, k_h, k_w, pad_d, pad_h, pad_w, stride_d, stride_h, stride_w, + // channels, d, h, w, k_d, k_h, k_w, pad_d, pad_h, pad_w, stride_d, stride_h, stride_w, // dilation_d, dilation_h, dilation_w, // - << fShapeW[1] << "," << iDepth << "," << iHeight << "," << iWidth << "," - << fAttrKernelShape[0] << "," << fAttrKernelShape[1] << "," << fAttrKernelShape[2] << "," - << fAttrPads[0] << "," << fAttrPads[1] << "," << fAttrPads[2] << "," - << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrStrides[2] << "," - << fAttrDilations[0] << "," << fAttrDilations[1] << "," << fAttrDilations[2] << "," + << fShapeW[1] << "," << iDepth << "," << iHeight << "," << iWidth << "," + << fAttrKernelShape[0] << "," << fAttrKernelShape[1] << "," << fAttrKernelShape[2] << "," + << fAttrPads[0] << "," << fAttrPads[1] << "," << fAttrPads[2] << "," + << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrStrides[2] << "," + << fAttrDilations[0] << "," << fAttrDilations[1] << "," << fAttrDilations[2] << "," << OpName << "_xcol);\n\n "; } // BLAS @@ -502,14 +502,14 @@ public: << "," << fAttrPads[2] << "," << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrStrides[2] << "," << fAttrDilations[0] << "," << fAttrDilations[1] << "," << fAttrDilations[2] << "," << OpName << "_xcol);\n\n "; - } + } // BLAS // n must be divided by the number of groups out << SP << SP << SP << OpName << "_n = " << fShapeW[0] / fAttrGroup << ";\n"; // offset g must be g * k * n out << SP << SP << SP << "size_t offset_f = g * " - << fShapeW[0] * fShapeW[1] * fAttrKernelShape[0] * fAttrKernelShape[1] * fAttrKernelShape[2] / fAttrGroup + << fShapeW[0] * fShapeW[1] * fAttrKernelShape[0] * fAttrKernelShape[1] * fAttrKernelShape[2] / fAttrGroup << ";\n"; out << SP << SP << "BLAS::sgemm_(&" << OpName << "_transA, &" << OpName << "_transB, &" << OpName << "_m, &" << OpName << "_n, &" << OpName << "_k, &" << OpName << "_alpha, " << OpName << "_xcol, &" << OpName @@ -538,7 +538,7 @@ public: /*! \brief Returns the blas routines needed to compile the generated code */ - std::vector GetBlasRoutines() { return {"Gemm", "Axpy"};} + std::vector GetBlasRoutines() { return { std::string("Gemm"), std::string("Axpy") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.hxx b/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.hxx index 2bc96f60ea726..0f42e036cb8b3 100644 --- a/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.hxx @@ -119,7 +119,7 @@ public: /*! \brief Returns the blas routines needed to compile the generated code */ - std::vector GetBlasRoutines() override { return {"Gemm", "Axpy"};} + std::vector GetBlasRoutines() override { return { std::string("Gemm"), std::string("Axpy") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.icc b/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.icc index 18b1b350041ec..fa6efb4861566 100644 --- a/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.icc +++ b/tmva/sofie/inc/TMVA/ROperator_ConvTranspose.icc @@ -268,7 +268,9 @@ std::string ROperator_ConvTranspose::Generate(std::string OpName) size_t iw = fDim - 1; size_t wstrideDil = fAttrDilations[iw]; size_t hstride = kWidth; - size_t hstrideDil = fAttrKernelShape[iw] * fAttrDilations[ih]; + size_t hstrideDil = fAttrKernelShape[iw]; + if (fDim > 1) + hstrideDil *= fAttrDilations[ih]; // stride dilated in the height size_t dstride = kHeight * kWidth; size_t dstrideDil = fAttrKernelShape[iw]; @@ -350,7 +352,6 @@ std::string ROperator_ConvTranspose::Generate(std::string OpName) fAttrPads[0] = (fAttrPads[0] + fAttrPads[1]) / 2; } fAttrPads[1] = 0; - fAttrStrides[1] = 1; } if (fDim == 2) { if (fAttrPads[0] != fAttrPads[2] || fAttrPads[1] != fAttrPads[3]) { diff --git a/tmva/sofie/inc/TMVA/ROperator_Erf.hxx b/tmva/sofie/inc/TMVA/ROperator_Erf.hxx new file mode 100644 index 0000000000000..b25fc8a217fa3 --- /dev/null +++ b/tmva/sofie/inc/TMVA/ROperator_Erf.hxx @@ -0,0 +1,71 @@ +#ifndef TMVA_SOFIE_ROPERATOR_Erf +#define TMVA_SOFIE_ROPERATOR_Erf + +#include "TMVA/SOFIE_common.hxx" +#include "TMVA/ROperator.hxx" +#include "TMVA/RModel.hxx" + +#include + +namespace TMVA{ +namespace Experimental{ +namespace SOFIE{ + +template +class ROperator_Erf final : public ROperator +{ + +private: + + std::string fNX; + std::string fNY; + std::vector fShape; + +public: + ROperator_Erf(){} + ROperator_Erf(std::string nameX, std::string nameY): + fNX(UTILITY::Clean_name(nameX)), fNY(UTILITY::Clean_name(nameY)){} + + std::vector TypeInference(std::vector input){ + return input; + } + + std::vector> ShapeInference(std::vector> input){ + auto ret = input; //suggest copy to compiler + return ret; + } + + void Initialize(RModel& model){ + //input must be a graph input, or already initialized intermediate tensor + if (model.CheckIfTensorAlreadyExist(fNX) == false){ + throw std::runtime_error("TMVA SOFIE Erf Op Input Tensor is not found in model"); + } + fShape = model.GetTensorShape(fNX); + model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShape); + + } + + + std::string Generate(std::string OpName){ + OpName = "op_" + OpName; + if (fShape.empty()) { + throw std::runtime_error("TMVA SOFIE Erf operator called to Generate without being initialized first"); + } + std::stringstream out; + size_t length = ConvertShapeToLength(fShape); + out << "\n//------ ERF\n"; + out << SP << "for (int id = 0; id < " << length << " ; id++){\n"; + out << SP << SP << "tensor_" << fNY << "[id] = std::erf(tensor_" << fNX << "[id]);\n"; + out << SP << "}\n"; + return out.str(); + } + + std::vector GetStdLibs() { return { std::string("cmath") };} +}; + +}//SOFIE +}//Experimental +}//TMVA + + +#endif //TMVA_SOFIE_ROPERATOR_Erf \ No newline at end of file diff --git a/tmva/sofie/inc/TMVA/ROperator_GRU.hxx b/tmva/sofie/inc/TMVA/ROperator_GRU.hxx index dc9f8ec0cd89b..44b6f7361bb46 100644 --- a/tmva/sofie/inc/TMVA/ROperator_GRU.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_GRU.hxx @@ -132,7 +132,7 @@ template class ROperator_GRU final : public ROperator { /*! \brief Returns the blas routines needed to compile the generated code */ - std::vector GetBlasRoutines() { return {"Gemm", "Axpy"};} + std::vector GetBlasRoutines() { return { std::string("Gemm"), std::string("Axpy") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Gather.hxx b/tmva/sofie/inc/TMVA/ROperator_Gather.hxx index 5cdd6a7dad7c2..479faf2910843 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Gather.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Gather.hxx @@ -35,7 +35,7 @@ private: public: ROperator_Gather(){} ROperator_Gather(int64_t attrAxis, std::string nameX, std::string nameIndices, std::string nameY): - fAttrAxis(attrAxis), fNX(UTILITY::Clean_name(nameX)), fNIndices(nameIndices), fNY(UTILITY::Clean_name(nameY)) { + fAttrAxis(attrAxis), fNX(UTILITY::Clean_name(nameX)), fNIndices(UTILITY::Clean_name(nameIndices)), fNY(UTILITY::Clean_name(nameY)) { } std::vector TypeInference(std::vector input){ @@ -66,6 +66,7 @@ public: fAttrAxis = fAttrAxis + int64_t(r); } // Indices of size q + // empty fShapeIndices is a scalar value for the indices size_t indicesLength = ConvertShapeToLength(fShapeIndices); fIndices = std::vector(indicesData, indicesData + indicesLength); for (size_t i = 0; i < indicesLength; i++) { diff --git a/tmva/sofie/inc/TMVA/ROperator_Gemm.hxx b/tmva/sofie/inc/TMVA/ROperator_Gemm.hxx index 7079258c5ba33..b29d552c77c53 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Gemm.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Gemm.hxx @@ -227,7 +227,7 @@ namespace SOFIE{ } - std::vector GetBlasRoutines() { return {"Gemm", "Gemv"};} + std::vector GetBlasRoutines() { return { std::string("Gemm"), std::string("Gemv") }; } }; diff --git a/tmva/sofie/inc/TMVA/ROperator_LSTM.hxx b/tmva/sofie/inc/TMVA/ROperator_LSTM.hxx index 0da69377d74ee..4b5743f52d5c5 100644 --- a/tmva/sofie/inc/TMVA/ROperator_LSTM.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_LSTM.hxx @@ -144,7 +144,7 @@ template class ROperator_LSTM final : public ROperator { /*! \brief Returns the blas routines needed to compile the generated code */ - std::vector GetBlasRoutines() { return {"Gemm", "Axpy"};} + std::vector GetBlasRoutines() { return { std::string("Gemm"), std::string("Axpy") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_LayerNormalization.hxx b/tmva/sofie/inc/TMVA/ROperator_LayerNormalization.hxx index 388dd747e7a3d..1d1c4577c23b1 100644 --- a/tmva/sofie/inc/TMVA/ROperator_LayerNormalization.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_LayerNormalization.hxx @@ -14,7 +14,7 @@ namespace SOFIE { template class ROperator_LayerNormalization : public ROperator { private: - int64_t fAttrAxis; + int fAttrAxis; float fAttrEpsilon; size_t fAttrStashType; @@ -51,11 +51,12 @@ private: public: ROperator_LayerNormalization() {} - ROperator_LayerNormalization(int64_t axis, float epsilon, size_t stashType, const std::string &nameX, + ROperator_LayerNormalization(int axis, float epsilon, size_t stashType, const std::string &nameX, const std::string &nameScale, const std::string &nameB, const std::string &nameY, const std::string &nameMean, const std::string &nameInvStdDev) - : fAttrAxis(axis), fAttrEpsilon(epsilon), fAttrStashType(stashType), fNX(nameX), fNScale(nameScale), fNB(nameB), - fNY(nameY), fNMean(nameMean), fNInvStdDev(nameInvStdDev) + : fAttrAxis(axis), fAttrEpsilon(epsilon), fAttrStashType(stashType), fNX(UTILITY::Clean_name(nameX)), + fNScale(UTILITY::Clean_name(nameScale)), fNB(UTILITY::Clean_name(nameB)), + fNY(UTILITY::Clean_name(nameY)), fNMean(UTILITY::Clean_name(nameMean)), fNInvStdDev(UTILITY::Clean_name(nameInvStdDev)) { } @@ -79,7 +80,7 @@ public: fAxis = (fAttrAxis < 0) ? fSize + fAttrAxis : fAttrAxis; // Shape of fShapeX[0, ..., fAxis) fAxesShape = std::vector(fShapeX.begin(), fShapeX.begin() + fAxis); - // Lenght of the axes + // Length of the axes fAxesLength = ConvertShapeToLength(fAxesShape); // Shape of fShapeX[fAxis, ..., fSize) fNormalizedShape = std::vector(fShapeX.begin() + fAxis, fShapeX.end()); @@ -313,9 +314,9 @@ public: return out.str(); } - std::vector GetBlasRoutines() override { return {"Axpy"}; } + std::vector GetBlasRoutines() override { return { std::string("Axpy") }; } - std::vector GetStdLibs() override { return {"cmath"}; } + std::vector GetStdLibs() override { return { std::string("cmath") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_RNN.hxx b/tmva/sofie/inc/TMVA/ROperator_RNN.hxx index 2a9289538c157..94baae511a139 100644 --- a/tmva/sofie/inc/TMVA/ROperator_RNN.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_RNN.hxx @@ -126,7 +126,7 @@ template class ROperator_RNN final : public ROperator { /*! \brief Returns the blas routines needed to compile the generated code */ - std::vector GetBlasRoutines() { return {"Gemm", "Axpy"};} + std::vector GetBlasRoutines() { return { std::string("Gemm"), std::string("Axpy") }; } }; } // namespace SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Reduce.hxx b/tmva/sofie/inc/TMVA/ROperator_Reduce.hxx index 0681573d22876..39e22f7570764 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Reduce.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Reduce.hxx @@ -16,7 +16,7 @@ namespace TMVA{ namespace Experimental{ namespace SOFIE{ -enum EReduceOpMode { ReduceMean, ReduceSumsquare, ReduceProd, InvalidReduceOp }; +enum EReduceOpMode { ReduceMean, ReduceSum, ReduceSumsquare, ReduceProd, InvalidReduceOp }; template class ROperator_Reduce final : public ROperator @@ -38,6 +38,7 @@ public: if (fReduceOpMode == ReduceMean) return "ReduceMean"; else if (fReduceOpMode == ReduceSumsquare ) return "ReduceSumsquare"; else if (fReduceOpMode == ReduceProd ) return "ReduceProd"; + else if (fReduceOpMode == ReduceSum) return "ReduceSum"; return "Invalid"; } @@ -133,6 +134,11 @@ public: out << SP << SP << "}\n"; out << SP << SP << "float reduceResult = sum/static_cast(" << fShapeX[fAttrAxes] << ");\n"; } + else if(fReduceOpMode == ReduceSum){ + out << SP << SP << SP << "sum += tensor_" << fNX << "[l];\n"; + out << SP << SP << "}\n"; + out << SP << SP << "float reduceResult = sum;\n"; + } else if(fReduceOpMode == ReduceSumsquare){ out << SP << SP << SP << "sum += tensor_" << fNX << "[l] * tensor_" << fNX << "[l];\n"; out << SP << SP << "}\n"; diff --git a/tmva/sofie/inc/TMVA/ROperator_Reshape.hxx b/tmva/sofie/inc/TMVA/ROperator_Reshape.hxx index 9ad9eff72189d..a183ac678ca54 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Reshape.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Reshape.hxx @@ -101,10 +101,14 @@ public: // assume no axis is provided - remove all axes with value equal to 1 auto output_shape = input[0]; if (input.size() == 1) { - for (size_t i = 0; i < output_shape.size(); i++) { + size_t i = 0; + while (i < output_shape.size()) { if (output_shape[i] == 1 ) { output_shape.erase(output_shape.begin() + i); } + else { + i++; + } } } else if (input.size() == 2) { auto & axes = input[1]; @@ -146,7 +150,6 @@ public: throw std::runtime_error("TMVA Reshape Op Input Tensor " + fNData + " is not found in model"); } fShapeInput = model.GetTensorShape(fNData); - // check if optional shape tensor exist if (!fNShape.empty()) { if (model.CheckIfTensorAlreadyExist(fNShape)) { @@ -189,9 +192,6 @@ public: ConvertShapeToString(fShapeOutput) + " and input is " + ConvertShapeToString(fShapeInput)); } - for (auto &i : fShapeOutput) { - length *= i; - } std::stringstream out; std::string opName = "Reshape"; if (fOpMode == Flatten) @@ -202,8 +202,8 @@ public: opName = "Unsquueze"; out << SP << "///--------" << opName << " operator\n" << std::endl; - out << SP << "std::copy( fTensor_" << fNData << ".begin(), fTensor_" << fNData << ".end(), fTensor_" << fNOutput - << ".begin() );\n"; + out << SP << "std::copy( tensor_" << fNData << ", tensor_" << fNData << " + " << length << ", " << "tensor_" << fNOutput + << ");\n"; return out.str(); } }; diff --git a/tmva/sofie/inc/TMVA/ROperator_Selu.hxx b/tmva/sofie/inc/TMVA/ROperator_Selu.hxx index 56d38cddbc06d..10b06d6d719e8 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Selu.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Selu.hxx @@ -60,7 +60,7 @@ public: return out.str(); } - std::vector GetStdLibs() { return {"cmath"};} + std::vector GetStdLibs() { return { std::string("cmath") };} }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Shape.hxx b/tmva/sofie/inc/TMVA/ROperator_Shape.hxx index 639d7727b3d06..1e0ff9b1fb62f 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Shape.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Shape.hxx @@ -6,7 +6,6 @@ #include "TMVA/RModel.hxx" #include -#include #include #include #include diff --git a/tmva/sofie/inc/TMVA/ROperator_Sigmoid.hxx b/tmva/sofie/inc/TMVA/ROperator_Sigmoid.hxx index 608921aa28b11..1feee9f94a444 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Sigmoid.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Sigmoid.hxx @@ -60,7 +60,7 @@ public: return out.str(); } - std::vector GetStdLibs() { return {"cmath"};} + std::vector GetStdLibs() { return { std::string("cmath") };} }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Slice.hxx b/tmva/sofie/inc/TMVA/ROperator_Slice.hxx index 946523e0832f1..f38a6dee094f3 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Slice.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Slice.hxx @@ -7,6 +7,7 @@ #include #include +#include namespace TMVA{ namespace Experimental{ @@ -47,11 +48,15 @@ public: for (size_t i = 0; i < names.size(); ++i) { fNames[i] = UTILITY::Clean_name(names[i]); } - // case names size is 3 check if steps is provided - // instead of axis. Keep in fNames always the same order - if (names.size() == 3 && names[2] != "axes") { - fNames[3] = fNames[2]; - fNames[2] = ""; + + if (names.size() == 3) { + if (names[2] != "axes") { //steps provided instead of axis + fNames[3] = fNames[2]; + fNames[2] = ""; + } + else { // steps not provided + fNames[3] = ""; + } } } // ctor for versions < 10 @@ -76,7 +81,7 @@ public: // assume dimension of output shape is SAME AS INPUT ! std::vector> ret(1, input_shape); auto & output_shape = ret[0]; - for (size_t i = 0; i < input_shape.size(); i++) { + for (size_t i = 0; i < input_shape.size(); i++) { output_shape[i] = (fEnd[i]-fStart[i])/ fSteps[i]; } return ret; @@ -97,13 +102,26 @@ public: // loop on the extra 2 or 3 or 4 inputs for (size_t i = 0; i < fNames.size(); ++i) { if (!fNames[i].empty()) { - std::cout << " i " << i << " getting data for tensor " << fNames[i] << std::endl; + // std::cout << " i " << i << " getting data for tensor " << fNames[i] << std::endl; auto dptr = model.GetInitializedTensorData(fNames[i]); auto tensor = static_cast(dptr.get()); auto vec = model.GetTensorShape(fNames[i]); assert(vec.size() == 1); itensors[i] = std::vector(tensor, tensor + vec[0]); } + else { + switch (i) + { + case 2: // missing axes + itensors[2] = std::vector(fShapeInput.size()); + std::iota(itensors[2].begin(), itensors[2].end(), 0); + break; + case 3: // missing steps + itensors[3] = std::vector(itensors[0].size(), 1); + default: + break; + } + } } } else { assert (fAttributes.size() > 1); @@ -129,20 +147,20 @@ public: // negative axes - they count from the back if (iaxes[i] < 0) iaxes[i] = dim + iaxes[i]; size_t jaxis = static_cast(iaxes[i]); - assert(jaxis < dim - 1); + assert(jaxis < dim); size_t imax = fShapeInput[jaxis]; // find start/end/step for given axis - IType start = (istart[i] > 0) ? istart[i] : imax + istart[i]; + IType start = (istart[i] >= 0) ? istart[i] : imax + istart[i]; if (start < 0) start = 0; if (start > static_cast(imax)) start = imax; fStart[jaxis] = start; - IType ie = (iend[i] > 0) ? iend[i] : imax + iend[i]; + IType ie = (iend[i] >= 0) ? iend[i] : imax + iend[i]; if (ie < 0) ie = 0; if (ie > static_cast(imax)) ie = imax; fEnd[jaxis] = ie; - //std::cout << " iaxis " << jaxis << " start " << start << " end " << ie << std::endl; + if (isteps.size() > 0) { if (isteps[i] < 0) { // to be done @@ -187,7 +205,7 @@ public: for (size_t idim = 0; idim < ndim-1; idim++) out << " stride" << idim << " + "; // here should be step size ? out << "i" << ndim-1 << ";\n"; - out << MSP << "fTensor_" << fNOutput << "[iOut++] = fTensor_" < + +namespace TMVA{ +namespace Experimental{ +namespace SOFIE{ + +template +class ROperator_Swish final : public ROperator +{ + +private: + + std::string fNX; + std::string fNY; + std::vector fShape; + +public: + ROperator_Swish(){} + ROperator_Swish(std::string nameX, std::string nameY): + fNX(UTILITY::Clean_name(nameX)), fNY(UTILITY::Clean_name(nameY)){} + + std::vector TypeInference(std::vector input){ + return input; + } + + std::vector> ShapeInference(std::vector> input){ + auto ret = input; //suggest copy to compiler + return ret; + } + + void Initialize(RModel& model){ + if (model.CheckIfTensorAlreadyExist(fNX) == false){ //input must be a graph input, or already initialized intermediate tensor + throw std::runtime_error("TMVA SOFIE Swish Op Input Tensor is not found in model"); + } + fShape = model.GetTensorShape(fNX); + model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShape); + } + + + std::string Generate(std::string OpName){ + OpName = "op_" + OpName; + if (fShape.empty()){ + throw std::runtime_error("TMVA SOFIE Operator Swish called to Generate without being initialized first"); + } + std::stringstream out; + int length = 1; + for(auto& i: fShape){ + length *= i; + } + out << "\t" << "for (int id = 0; id < " << length << " ; id++){\n"; + out << "\t\t" << "tensor_" << fNY << "[id] = tensor_" << fNX <<"[id] / (1 + std::exp( - tensor_" << fNX << "[id]));\n"; + out << "\t}\n"; + return out.str(); + } + + std::vector GetStdLibs() { return { std::string("cmath") };} +}; + +}//SOFIE +}//Experimental +}//TMVA + + +#endif //TMVA_SOFIE_ROPERATOR_Swish diff --git a/tmva/sofie/inc/TMVA/ROperator_Tanh.hxx b/tmva/sofie/inc/TMVA/ROperator_Tanh.hxx index c8eb7bc962d18..4e899013c43b6 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Tanh.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Tanh.hxx @@ -60,7 +60,7 @@ public: return out.str(); } - std::vector GetStdLibs() { return {"cmath"};} + std::vector GetStdLibs() { return { std::string("cmath") };} }; }//SOFIE diff --git a/tmva/sofie/inc/TMVA/ROperator_Transpose.hxx b/tmva/sofie/inc/TMVA/ROperator_Transpose.hxx index aee259c6352ef..097ae8067cfb1 100644 --- a/tmva/sofie/inc/TMVA/ROperator_Transpose.hxx +++ b/tmva/sofie/inc/TMVA/ROperator_Transpose.hxx @@ -60,6 +60,7 @@ public: void Initialize(RModel& model){ if (model.CheckIfTensorAlreadyExist(fNData) == false){ //input must be a graph input, or already initialized intermediate tensor + std::cout<<"Input tensor for transspose: "< #include @@ -67,21 +66,43 @@ struct InitializedTensor{ } switch(fType){ case ETensorType::FLOAT: fSize*=sizeof(float); break; + case ETensorType::DOUBLE: fSize*=sizeof(double); break; + case ETensorType::INT32: fSize*=sizeof(int32_t); break; + case ETensorType::INT64: fSize*=sizeof(int64_t); break; default: throw std::runtime_error("TMVA::SOFIE doesn't yet supports serialising data-type " + ConvertTypeToString(fType)); } fPersistentData=(char*)fData.get(); } void CastPersistentToShared(){ - switch(fType){ - case ETensorType::FLOAT: { - std::shared_ptr tData(malloc(fSize * sizeof(float)), free); - std::memcpy(tData.get(), fPersistentData,fSize * sizeof(float)); - fData=tData; - break; + switch (fType) { + case ETensorType::FLOAT: { + std::shared_ptr tData(malloc(fSize * sizeof(float)), free); + std::memcpy(tData.get(), fPersistentData, fSize * sizeof(float)); + fData = tData; + break; + } + case ETensorType::DOUBLE: { + std::shared_ptr tData(malloc(fSize * sizeof(double)), free); + std::memcpy(tData.get(), fPersistentData, fSize * sizeof(double)); + fData = tData; + break; + } + case ETensorType::INT32: { + std::shared_ptr tData(malloc(fSize * sizeof(int32_t)), free); + std::memcpy(tData.get(), fPersistentData, fSize * sizeof(int32_t)); + fData = tData; + break; + } + case ETensorType::INT64: { + std::shared_ptr tData(malloc(fSize * sizeof(int64_t)), free); + std::memcpy(tData.get(), fPersistentData, fSize * sizeof(int64_t)); + fData = tData; + break; } default: { - throw std::runtime_error("TMVA::SOFIE doesn't yet supports serialising data-type " + ConvertTypeToString(fType)); + throw std::runtime_error("TMVA::SOFIE doesn't yet supports serialising data-type " + + ConvertTypeToString(fType)); } } } @@ -400,6 +421,69 @@ extern "C" void sgemm_(const char * transa, const char * transb, const int * m, const float * alpha, const float * A, const int * lda, const float * B, const int * ldb, const float * beta, float * C, const int * ldc); }//BLAS + + +struct GNN_Data { + RTensor node_data; + RTensor edge_data; + RTensor global_data; + + GNN_Data(): node_data(RTensor({})), edge_data(RTensor({})), global_data(RTensor({})){} +}; + +template +TMVA::Experimental::RTensor Concatenate( TMVA::Experimental::RTensor & t1, TMVA::Experimental::RTensor & t2, int axis = 0) +{ + // concatenate tensor along axis. Shape must be the same except in the dimension of the concatenated axis + if (t1.GetMemoryLayout() != t2.GetMemoryLayout()) + throw std::runtime_error("TMVA RTensor Concatenate - tensors have different memory layout"); + auto & shape1 = t1.GetShape(); + auto & shape2 = t2.GetShape(); + if (t1.GetSize()/shape1[axis] != t2.GetSize()/shape2[axis]) + throw std::runtime_error("TMVA RTensor Concatenate - tensors have incompatible shapes"); + std::vector outShape = shape1; + outShape[axis] = shape1[axis] + shape2[axis]; + TMVA::Experimental::RTensor tout(outShape, t1.GetMemoryLayout()); + if (t1.GetMemoryLayout() == TMVA::Experimental::MemoryLayout::ColumnMajor) { + throw std::runtime_error("TMVA RTensor Concatenate is not yet supported for column major tensors"); + } + + auto & stride1 = t1.GetStrides(); + auto & stride2 = t2.GetStrides(); + auto & outStride = tout.GetStrides(); + + size_t s1 = (axis > 0) ? stride1[axis-1] : t1.GetSize(); // block size to copy from first tensor + size_t s2 = (axis > 0) ? stride2[axis-1] : t2.GetSize(); // block size to copy from second tensor + size_t sout = (axis > 0) ? outStride[axis-1] : tout.GetSize(); + size_t nb = t1.GetSize()/s1; + for (size_t i = 0; i < nb; i++) { + std::copy(t1.GetData() + i*s1, t1.GetData() + (i+1)*s1, tout.GetData() + i * sout ); + std::copy(t2.GetData() + i*s2, t2.GetData() + (i+1)*s2, tout.GetData() + i * sout + s1 ); + } + + return tout; +} + + +inline GNN_Data Concatenate(GNN_Data & data1, GNN_Data & data2, int axis = 0) { + GNN_Data out; + out.node_data = Concatenate(data1.node_data,data2.node_data, axis); + out.edge_data = Concatenate(data1.edge_data,data2.edge_data, axis); + out.global_data = Concatenate(data1.global_data,data2.global_data, axis-1); + return out; +} + +inline GNN_Data Copy(const GNN_Data & data) { + GNN_Data out; + out.node_data = RTensor(data.node_data.GetShape()); + out.edge_data = RTensor(data.edge_data.GetShape()); + out.global_data = RTensor(data.global_data.GetShape()); + std::copy(data.node_data.GetData(), data.node_data.GetData()+ data.node_data.GetSize(), out.node_data.GetData()); + std::copy(data.edge_data.GetData(), data.edge_data.GetData()+ data.edge_data.GetSize(), out.edge_data.GetData()); + std::copy(data.global_data.GetData(), data.global_data.GetData()+ data.global_data.GetSize(), out.global_data.GetData()); + return out; +} + }//SOFIE }//Experimental }//TMVA diff --git a/tmva/sofie/src/RFunction.cxx b/tmva/sofie/src/RFunction.cxx new file mode 100644 index 0000000000000..f2ec5da623db7 --- /dev/null +++ b/tmva/sofie/src/RFunction.cxx @@ -0,0 +1,93 @@ +#include "TMVA/RModel.hxx" +#include "TMVA/RFunction.hxx" + + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + + + +RFunction_Update::RFunction_Update(FunctionTarget target, GraphType gType): fTarget(target), fGraphType(gType) { + switch(target) { + case FunctionTarget::EDGES: { + fFuncName = "edge_update"; + break; + } + case FunctionTarget::NODES: { + fFuncName = "node_update"; + break; + } + case FunctionTarget::GLOBALS: { + fFuncName = "global_update"; + break; + } + default: + throw std::runtime_error("Invalid target for Update function"); + } + fType = FunctionType::UPDATE; + function_block = std::make_unique(fFuncName); + + if(fGraphType == GraphType::GNN) { + if(fTarget == FunctionTarget::EDGES) { + fInputTensors = {"edge","receiver","sender","global"}; + } else if(fTarget == FunctionTarget::NODES || fTarget == FunctionTarget::GLOBALS) { + fInputTensors = {"edge","node","global"}; + } + + } else if(fGraphType == GraphType::GraphIndependent) { + if(fTarget == FunctionTarget::EDGES) { + fInputTensors = {"edge"}; + } else if(fTarget == FunctionTarget::NODES) { + fInputTensors = {"node"}; + } else { + fInputTensors = {"global"}; + } + } +} + +void RFunction_Update::AddInputTensors(const std::vector>& fInputShape) { + for(long unsigned int i=0; iAddInputTensorInfo(fInputTensors[i],ETensorType::FLOAT, fInputShape[i]); + function_block->AddInputTensorName(fInputTensors[i]); + } +} + +std::string RFunction_Update::GenerateModel(const std::string& filename, long read_pos, long block_size) { + function_block->SetFilename(filename); + // use batch size as block size in RModel::generate + function_block->Generate(Options::kGNNComponent,block_size,read_pos); + std::string modelGenerationString; + modelGenerationString = "\n//--------- GNN_Update_Function---"+fFuncName+"\n"+function_block->ReturnGenerated(); + return modelGenerationString; +} + +std::string RFunction_Update::Generate(const std::vector& inputPtrs) { + std::string inferFunc = fFuncName+".infer("; + for(auto&it : inputPtrs) { + inferFunc+=it; + inferFunc+=","; + } + inferFunc.pop_back(); + inferFunc+=");"; + return inferFunc; +} + + +std::string RFunction_Aggregate::Generate(std::size_t num_features, const std::vector& inputTensors) { + std::string inferFunc = fFuncName+"("+std::to_string(num_features)+",{"; + for(auto&it : inputTensors) { + inferFunc+=it; + inferFunc+=","; + } + inferFunc.pop_back(); + inferFunc+="});"; + return inferFunc; +} + + + + +} +} +} diff --git a/tmva/sofie/src/RFunction_MLP.cxx b/tmva/sofie/src/RFunction_MLP.cxx new file mode 100644 index 0000000000000..cd2ce2fbb929e --- /dev/null +++ b/tmva/sofie/src/RFunction_MLP.cxx @@ -0,0 +1,83 @@ +#include "TMVA/RFunction_MLP.hxx" + + +#include "TMVA/SOFIE_common.hxx" +#include "TMVA/ROperator_Concat.hxx" +#include "TMVA/ROperator_Gemm.hxx" +#include "TMVA/ROperator_LayerNormalization.hxx" +#include "TMVA/ROperator_Relu.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +RFunction_MLP::RFunction_MLP(FunctionTarget target, Int_t numLayers, Activation activation_function, bool activate_final, GraphType gType): + RFunction_Update(target, gType), fNumLayers(numLayers), fActivationFunction(activation_function), fActivateFinal(activate_final) { + if(fActivationFunction == Activation::Invalid) { + throw std::runtime_error("TMVA SOFIE GNN doesn't currently supports the provided activation function for " + fFuncName + " update."); + } + + // assuming all the linear layers has a kernel and a bias initialized tensors + if(fActivateFinal) { + function_block->AddOutputTensorNameList({fFuncName+"Relu"+std::to_string(fNumLayers)}); + } else { + function_block->AddOutputTensorNameList({fFuncName+"Gemm"+std::to_string(fNumLayers)}); + } +} + +void RFunction_MLP::Initialize() { + + std::string fGemmInput; + if(fGraphType == GraphType::GNN) { + std::unique_ptr op_concat; + op_concat.reset(new ROperator_Concat(fInputTensors,1,0,fFuncName+"InputConcat")); + function_block->AddOperator(std::move(op_concat)); + fGemmInput = fFuncName+"InputConcat"; + + } else if(fGraphType == GraphType::GraphIndependent) { + fGemmInput = fInputTensors[0]; + } + + std::unique_ptr op_gemm; + for(int i=0; i(1.0,1.0,0,0,fGemmInput,UTILITY::Clean_name(fKernelTensors[i]),UTILITY::Clean_name(fBiasTensors[i]),fFuncName+"Gemm"+std::to_string(i))); + function_block->AddOperator(std::move(op_gemm)); + fGemmInput = fFuncName+"Gemm"+i; + if (fActivationFunction == Activation::RELU) { + std::unique_ptr op_relu; + op_relu.reset(new ROperator_Relu(fFuncName+"Gemm"+std::to_string(i), fFuncName+"Relu"+std::to_string(i))); + function_block->AddOperator(std::move(op_relu)); + fGemmInput = fFuncName+"Relu"+i; + + } + } + + op_gemm.reset(new ROperator_Gemm(1.0,1.0,0,0,fGemmInput,UTILITY::Clean_name(fKernelTensors.back()),UTILITY::Clean_name(fBiasTensors.back()),fFuncName+"Gemm"+std::to_string(fNumLayers))); + function_block->AddOperator(std::move(op_gemm)); + if(fActivateFinal) { + if (fActivationFunction == Activation::RELU) { + std::unique_ptr op_relu; + op_relu.reset(new ROperator_Relu(fFuncName+"Gemm"+std::to_string(fNumLayers), fFuncName+"Relu"+std::to_string(fNumLayers))); + function_block->AddOperator(std::move(op_relu)); + } + } + + + if(fAddlOp.size()) { + for(auto &i:fAddlOp) { + std::unique_ptr tmp(i); + function_block->AddOperator(std::move(tmp)); + } + } +} + +void RFunction_MLP::AddLayerNormalization(int axis, float epsilon, size_t stashType, const std::string &nameX, + const std::string &nameScale, const std::string &nameB, const std::string &nameY) { + auto op_layerNorm = new ROperator_LayerNormalization(axis, epsilon, stashType, nameX, + nameScale, nameB, nameY, "", ""); + fAddlOp.push_back((op_layerNorm)); +} + +} +} +} diff --git a/tmva/sofie/src/RFunction_Mean.cxx b/tmva/sofie/src/RFunction_Mean.cxx new file mode 100644 index 0000000000000..554d782d69b3a --- /dev/null +++ b/tmva/sofie/src/RFunction_Mean.cxx @@ -0,0 +1,22 @@ +#include "TMVA/RFunction_Mean.hxx" + + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +std::string RFunction_Mean::GenerateModel() { + std::string modelGenerationString; + modelGenerationString = "\n//--------- GNN_Aggregate_Function---"+fFuncName+"\n"; + modelGenerationString += "std::vector "+fFuncName+"(const int& num_features, const std::vector::iterator>& inputs){\n"; + modelGenerationString += "\tstd::vector result(num_features,0);\n"; + modelGenerationString += "\tfor(auto &it:inputs){\n"; + modelGenerationString += "\t\tstd::transform(result.begin(), result.end(), it, result.begin(), std::plus());\n\t}\n"; + modelGenerationString += "\tfor_each(result.begin(), result.end(), [&result](float &x){ x /= result.size();\n"; + modelGenerationString += "\treturn result;\n}"; + return modelGenerationString; +} + +} +} +} diff --git a/tmva/sofie/src/RFunction_Sum.cxx b/tmva/sofie/src/RFunction_Sum.cxx new file mode 100644 index 0000000000000..7db9d9a2f9f7a --- /dev/null +++ b/tmva/sofie/src/RFunction_Sum.cxx @@ -0,0 +1,21 @@ +#include "TMVA/RFunction_Sum.hxx" + + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +std::string RFunction_Sum::GenerateModel() { + std::string modelGenerationString; + modelGenerationString = "\n//--------- GNN_Aggregate_Function---"+fFuncName+"\n"; + modelGenerationString += "std::vector "+fFuncName+"(const int& num_features, const std::vector& inputs){\n"; + modelGenerationString += "\tstd::vector result(num_features,0);\n"; + modelGenerationString += "\tfor(auto &it:inputs){\n"; + modelGenerationString += "\t\tstd::transform(result.begin(), result.end(), it, result.begin(), std::plus());\n\t}\n"; + modelGenerationString += "\treturn result;\n}"; + return modelGenerationString; +} + +} +} +} diff --git a/tmva/sofie/src/RModel.cxx b/tmva/sofie/src/RModel.cxx index 0e245026fb883..d3d7913744adb 100644 --- a/tmva/sofie/src/RModel.cxx +++ b/tmva/sofie/src/RModel.cxx @@ -1,660 +1,775 @@ #include #include #include +#include + +#include "TFile.h" #include "TMVA/RModel.hxx" #include "TMVA/SOFIE_common.hxx" - - - -namespace TMVA{ -namespace Experimental{ -namespace SOFIE{ - - std::underlying_type_t operator|(Options opA, Options opB) { - return static_cast>(opA) | static_cast>(opB); - } - std::underlying_type_t operator|(std::underlying_type_t opA, Options opB) { - return opA | static_cast>(opB); - } - - RModel::RModel(RModel&& other){ - fInputTensorInfos = std::move(other.fInputTensorInfos); - fReadyInputTensorInfos = std::move(other.fReadyInputTensorInfos); - fOutputTensorNames = other.fOutputTensorNames; - fInputTensorNames = other.fInputTensorNames; - fOperators = std::move(other.fOperators); - fInitializedTensors = std::move(other.fInitializedTensors); - fIntermediateTensorInfos = std::move(other.fIntermediateTensorInfos); - fName = other.fName; - fFileName = other.fFileName; - fParseTime = other.fParseTime; - fGC = other.fGC; - fNeededBlasRoutines = other.fNeededBlasRoutines; - fNeededStdLib = other.fNeededStdLib; - } - - RModel& RModel::operator=(RModel&& other){ - fInputTensorInfos = std::move(other.fInputTensorInfos); - fReadyInputTensorInfos = std::move(other.fReadyInputTensorInfos); - fOutputTensorNames = other.fOutputTensorNames; - fInputTensorNames = other.fInputTensorNames; - fOperators = std::move(other.fOperators); - fInitializedTensors = std::move(other.fInitializedTensors); - fIntermediateTensorInfos = std::move(other.fIntermediateTensorInfos); - fName = other.fName; - fFileName = other.fFileName; - fParseTime = other.fParseTime; - fGC = other.fGC; - fNeededBlasRoutines = other.fNeededBlasRoutines; - fNeededStdLib = other.fNeededStdLib; - return *this; - } - - RModel::RModel(std::string name, std::string parsedtime): fFileName (name), fParseTime(parsedtime) { - fName = fFileName.substr(0, fFileName.rfind(".")); - } - - const std::vector& RModel::GetTensorShape(std::string name){ - auto f = fReadyInputTensorInfos.find(name); - if (f != fReadyInputTensorInfos.end()){ - return f->second.shape; - } - auto f2 = fInitializedTensors.find(name); - if (f2 != fInitializedTensors.end()){ - return f2->second.fShape; - } - auto f3 = fInputTensorInfos.find(name); - if (f3 != fInputTensorInfos.end()){ - throw std::runtime_error("TMVA SOFIE tensor [" + name + "] is an input tensor with unspecified dimension parameter"); - } - auto f4 = fIntermediateTensorInfos.find(name); - if (f4 != fIntermediateTensorInfos.end()){ - return f4->second.shape; - } - - throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the shape is requested is not found"); - } - - const ETensorType& RModel::GetTensorType(std::string name){ - auto f = fReadyInputTensorInfos.find(name); - if (f != fReadyInputTensorInfos.end()){ - return f->second.type; - } - auto f2 = fInitializedTensors.find(name); - if (f2 != fInitializedTensors.end()){ - return f2->second.fType; - } - auto f3 = fInputTensorInfos.find(name); - if (f3 != fInputTensorInfos.end()){ - return f3->second.type; - } - auto f4 = fIntermediateTensorInfos.find(name); - if (f4 != fIntermediateTensorInfos.end()){ - return f4->second.type; - } - - throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the type is requested is not found"); - } - - bool RModel::CheckIfTensorAlreadyExist(std::string tensor_name){ - if (fReadyInputTensorInfos.find(tensor_name) != fReadyInputTensorInfos.end()) return true; - if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()) return true; - if (fIntermediateTensorInfos.find(tensor_name) != fIntermediateTensorInfos.end()) return true; - return false; - } - - void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape){ - input_name = UTILITY::Clean_name(input_name); - if (CheckIfTensorAlreadyExist(input_name)){ - throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n"); - } - - InputTensorInfo inputInfo { type, shape }; - fInputTensorInfos[input_name] = inputInfo; - } - - void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape){ - input_name = UTILITY::Clean_name(input_name); - if (CheckIfTensorAlreadyExist(input_name)){ - throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n"); - } - TensorInfo inputInfo { type, shape }; - fReadyInputTensorInfos[input_name] = inputInfo; - } - - void RModel::AddInputTensorName(std::string input_name) { - fInputTensorNames.push_back(UTILITY::Clean_name(input_name)); - } - - void RModel::AddOperator(std::unique_ptr op, int order_execution){ - AddBlasRoutines(op->GetBlasRoutines()); - for (auto& stdlib : op->GetStdLibs()) { - AddNeededStdLib(stdlib); - } - if (order_execution >= 0) { - fOperators.insert(fOperators.begin() + order_execution, std::move(op)); - }else{ - fOperators.push_back(std::move(op)); - } - } - - void RModel::AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data){ - tensor_name = UTILITY::Clean_name(tensor_name); - //NB: own data - if (CheckIfTensorAlreadyExist(tensor_name)){ - throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n"); - } - InitializedTensor new_tensor {type, shape, data}; - fInitializedTensors[tensor_name] = new_tensor; - - } - - bool RModel::IsInitializedTensor(const std::string& tensorName) const { - std::string name = UTILITY::Clean_name(tensorName); - return fInitializedTensors.find(name) != fInitializedTensors.end(); - } - - void RModel::AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector shape){ - tensor_name = UTILITY::Clean_name(tensor_name); - if (CheckIfTensorAlreadyExist(tensor_name)){ - throw std::runtime_error("TMVA-SOFIE: intermediate tensor with name " + tensor_name + " already exists \n"); - } - TensorInfo new_tensor {type, shape}; - fIntermediateTensorInfos[tensor_name] = new_tensor; - } - - void RModel::AddOutputTensorNameList(std::vector outputtensornames){ - for(auto& it : outputtensornames){ - fOutputTensorNames.push_back(UTILITY::Clean_name(it)); - } - } - - void RModel::UpdateOutputTensorList(std::vector curr_output_tensors, std::vector new_output_tensors){ - for(auto& it:curr_output_tensors){ - fOutputTensorNames.erase(std::remove(fOutputTensorNames.begin(), fOutputTensorNames.end(), it), fOutputTensorNames.end()); - } - fOutputTensorNames.insert(fOutputTensorNames.end(), new_output_tensors.begin(), new_output_tensors.end()); - } - - void RModel::UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data){ - tensor_name = UTILITY::Clean_name(tensor_name); - if (!CheckIfTensorAlreadyExist(tensor_name)){ - throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to update it"); - } - InitializedTensor new_tensor {type, shape, data}; - fInitializedTensors[tensor_name] = new_tensor; - } - - std::shared_ptr RModel::GetInitializedTensorData(std::string tensor_name){ - auto f = fInitializedTensors.find(tensor_name); - if (f == fInitializedTensors.end()){ - throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to get its data"); - }else{ - return f->second.fData; - } - } - - void RModel::Initialize(int batchSize){ - // check if there are only parametrized input tensor and convert in - // ready input tensor according to batch size - // convert parametric shape to a dimensional shape - fIntermediateTensorInfos.clear(); - if (fReadyInputTensorInfos.size() != fInputTensorNames.size()) { - if ( fReadyInputTensorInfos.size() + fInputTensorInfos.size() != fInputTensorNames.size()) +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +std::underlying_type_t operator|(Options opA, Options opB) { + return static_cast>(opA) | static_cast>(opB); +} +std::underlying_type_t operator|(std::underlying_type_t opA, Options opB) { + return opA | static_cast>(opB); +} + +RModel::RModel(RModel&& other) { + fInputTensorInfos = std::move(other.fInputTensorInfos); + fReadyInputTensorInfos = std::move(other.fReadyInputTensorInfos); + fOutputTensorNames = other.fOutputTensorNames; + fInputTensorNames = other.fInputTensorNames; + fOperators = std::move(other.fOperators); + fInitializedTensors = std::move(other.fInitializedTensors); + fIntermediateTensorInfos = std::move(other.fIntermediateTensorInfos); + fName = other.fName; + fFileName = other.fFileName; + fParseTime = other.fParseTime; + fGC = other.fGC; + fNeededBlasRoutines = other.fNeededBlasRoutines; + fNeededStdLib = other.fNeededStdLib; +} + +RModel& RModel::operator=(RModel&& other) { + fInputTensorInfos = std::move(other.fInputTensorInfos); + fReadyInputTensorInfos = std::move(other.fReadyInputTensorInfos); + fOutputTensorNames = other.fOutputTensorNames; + fInputTensorNames = other.fInputTensorNames; + fOperators = std::move(other.fOperators); + fInitializedTensors = std::move(other.fInitializedTensors); + fIntermediateTensorInfos = std::move(other.fIntermediateTensorInfos); + fName = other.fName; + fFileName = other.fFileName; + fParseTime = other.fParseTime; + fGC = other.fGC; + fNeededBlasRoutines = other.fNeededBlasRoutines; + fNeededStdLib = other.fNeededStdLib; + return *this; +} + +const std::vector& RModel::GetTensorShape(std::string name) { + auto f = fReadyInputTensorInfos.find(name); + if (f != fReadyInputTensorInfos.end()) { + return f->second.shape; + } + auto f2 = fInitializedTensors.find(name); + if (f2 != fInitializedTensors.end()) { + return f2->second.fShape; + } + auto f3 = fInputTensorInfos.find(name); + if (f3 != fInputTensorInfos.end()) { + throw std::runtime_error("TMVA SOFIE tensor [" + name + "] is an input tensor with unspecified dimension parameter"); + } + auto f4 = fIntermediateTensorInfos.find(name); + if (f4 != fIntermediateTensorInfos.end()) { + return f4->second.shape; + } + + throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the shape is requested is not found"); +} + +const ETensorType& RModel::GetTensorType(std::string name) { + auto f = fReadyInputTensorInfos.find(name); + if (f != fReadyInputTensorInfos.end()) { + return f->second.type; + } + auto f2 = fInitializedTensors.find(name); + if (f2 != fInitializedTensors.end()) { + return f2->second.fType; + } + auto f3 = fInputTensorInfos.find(name); + if (f3 != fInputTensorInfos.end()) { + return f3->second.type; + } + auto f4 = fIntermediateTensorInfos.find(name); + if (f4 != fIntermediateTensorInfos.end()) { + return f4->second.type; + } + + throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the type is requested is not found"); +} + +bool RModel::CheckIfTensorAlreadyExist(std::string tensor_name) { + if (fReadyInputTensorInfos.find(tensor_name) != fReadyInputTensorInfos.end()) return true; + if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()) return true; + if (fIntermediateTensorInfos.find(tensor_name) != fIntermediateTensorInfos.end()) return true; + return false; +} + +void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape) { + input_name = UTILITY::Clean_name(input_name); + if (CheckIfTensorAlreadyExist(input_name)) { + throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n"); + } + + InputTensorInfo inputInfo { type, shape }; + fInputTensorInfos[input_name] = inputInfo; +} + +void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector shape) { + input_name = UTILITY::Clean_name(input_name); + if (CheckIfTensorAlreadyExist(input_name)) { + throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n"); + } + TensorInfo inputInfo { type, shape }; + fReadyInputTensorInfos[input_name] = inputInfo; +} + +void RModel::AddInputTensorName(std::string input_name) { + fInputTensorNames.push_back(UTILITY::Clean_name(input_name)); +} + +void RModel::AddOperator(std::unique_ptr op, int order_execution) { + AddBlasRoutines(op->GetBlasRoutines()); + auto libs = op->GetStdLibs(); + for (auto& stdlib : libs) { + AddNeededStdLib(stdlib); + } + if (order_execution >= 0) { + fOperators.insert(fOperators.begin() + order_execution, std::move(op)); + } else { + fOperators.push_back(std::move(op)); + } +} + +void RModel::AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data) { + tensor_name = UTILITY::Clean_name(tensor_name); + //NB: own data + if (CheckIfTensorAlreadyExist(tensor_name)) { + throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n"); + } + InitializedTensor new_tensor {type, shape, data}; + fInitializedTensors[tensor_name] = new_tensor; + +} + +bool RModel::IsInitializedTensor(const std::string& tensorName) const { + std::string name = UTILITY::Clean_name(tensorName); + return fInitializedTensors.find(name) != fInitializedTensors.end(); +} + +void RModel::AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector shape) { + tensor_name = UTILITY::Clean_name(tensor_name); + if (CheckIfTensorAlreadyExist(tensor_name)) { + throw std::runtime_error("TMVA-SOFIE: intermediate tensor with name " + tensor_name + " already exists \n"); + } + TensorInfo new_tensor {type, shape}; + fIntermediateTensorInfos[tensor_name] = new_tensor; +} + +void RModel::AddOutputTensorNameList(std::vector outputtensornames) { + fOutputTensorNames.clear(); + for(auto& it : outputtensornames) { + fOutputTensorNames.push_back(UTILITY::Clean_name(it)); + } +} + +void RModel::UpdateOutputTensorList(std::vector curr_output_tensors, std::vector new_output_tensors) { + for(auto& it:curr_output_tensors) { + fOutputTensorNames.erase(std::remove(fOutputTensorNames.begin(), fOutputTensorNames.end(), it), fOutputTensorNames.end()); + } + fOutputTensorNames.insert(fOutputTensorNames.end(), new_output_tensors.begin(), new_output_tensors.end()); +} + +void RModel::UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector shape, std::shared_ptr data) { + tensor_name = UTILITY::Clean_name(tensor_name); + if (!CheckIfTensorAlreadyExist(tensor_name)) { + throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to update it"); + } + InitializedTensor new_tensor {type, shape, data}; + fInitializedTensors[tensor_name] = new_tensor; +} + +std::shared_ptr RModel::GetInitializedTensorData(std::string tensor_name) { + auto f = fInitializedTensors.find(tensor_name); + if (f == fInitializedTensors.end()) { + throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to get its data"); + } else { + return f->second.fData; + } +} + +void RModel::Initialize(int batchSize) { + // check if there are only parametrized input tensor and convert in + // ready input tensor according to batch size + // convert parametric shape to a dimensional shape + fIntermediateTensorInfos.clear(); + if (fReadyInputTensorInfos.size() != fInputTensorNames.size()) { + if ( fReadyInputTensorInfos.size() + fInputTensorInfos.size() != fInputTensorNames.size()) throw std::runtime_error("TMVA-SOFIE: RModel::Initializes: invalid inputs"); - for (auto & input : fInputTensorInfos) { + for (auto & input : fInputTensorInfos) { std::vector shape; shape.reserve(input.second.shape.size()); - for (auto & d : input.second.shape){ - if (d.isParam) - shape.push_back(batchSize); - else - shape.push_back(d.dim); + for (auto & d : input.second.shape) { + if (d.isParam) + shape.push_back(batchSize); + else + shape.push_back(d.dim); } AddInputTensorInfo(input.first, input.second.type, shape); - } - } - // check if there are initialized tensors to write in a weight file - // support for the time being only wheight of FLOAT type - if (fUseWeightFile) { - bool modelHasWeights = false; - for (auto& i: fInitializedTensors){ + } + } + // check if there are initialized tensors to write in a weight file + // support for the time being only weight of FLOAT type + if (fUseWeightFile) { + bool modelHasWeights = false; + for (auto& i: fInitializedTensors) { if (i.second.fType == ETensorType::FLOAT) { - modelHasWeights = true; - break; - } - } - if (!modelHasWeights) fUseWeightFile = false; - } - - - for (auto& i : fOperators){ - //std::cout << "initialize operator " << typeid(*i).name() << std::endl; - i->Initialize(*this); - } - } - - void RModel::Generate(std::underlying_type_t options, int batchSize){ - // session flag is used in operator initialize - if (static_cast>(Options::kNoSession) & options) - fUseSession = false; - if (static_cast>(Options::kNoWeightFile) & options) - fUseWeightFile = false; - if (fUseWeightFile && !fUseSession) { - throw std::runtime_error("TMVA-SOFIE: RModel::Generate: cannot use a separate weight file without generating a Session class"); - } - fGC.clear(); - Initialize(batchSize); - fGC += ("//Code generated automatically by TMVA for Inference of Model file [" + fFileName + "] at [" + fParseTime.substr(0, fParseTime.length()-1) +"] \n"); - // add header guards - std::string hgname = fName; - std::transform(hgname.begin(), hgname.end(), hgname.begin(), [](unsigned char c){ return std::toupper(c);} ); - hgname = "TMVA_SOFIE_" + hgname; - fGC += "\n#ifndef " + hgname + "\n"; - fGC += "#define " + hgname + "\n\n"; - for (auto& i: fNeededStdLib) { - fGC += "#include<" + i + ">\n"; - } - for (auto& i: fCustomOpHeaders) { - fGC += "#include \"" + i + "\"\n"; - } - // for the session we need to include SOFIE_Common functions - //needed for convolution operator (need to add a flag) - fGC += "#include \"TMVA/SOFIE_common.hxx\"\n"; - if (fUseWeightFile) - fGC += "#include \n"; - - fGC += "\nnamespace TMVA_SOFIE_" + fName + "{\n"; - if (!fNeededBlasRoutines.empty()) { - fGC += ("namespace BLAS{\n"); - for (auto &routine : fNeededBlasRoutines) { - if (routine == "Gemm") { - fGC += ("\textern \"C\" void sgemm_(const char * transa, const char * transb, const int * m, const int * n, const int * k,\n" - "\t const float * alpha, const float * A, const int * lda, const float * B, const int * ldb,\n" - "\t const float * beta, float * C, const int * ldc);\n"); - } else if (routine == "Gemv") { - fGC += ("\textern \"C\" void sgemv_(const char * trans, const int * m, const int * n, const float * alpha, const float * A,\n" - "\t const int * lda, const float * X, const int * incx, const float * beta, const float * Y, const int * incy);\n"); - } else if (routine == "Axpy") { - fGC += ("\textern \"C\" void saxpy_(const int * n, const float * alpha, const float * x,\n" - "\t const int * incx, float * y, const int * incy);\n"); - } else if (routine == "Copy") { - fGC += ("\textern \"C\" void scopy_(const int *n, const float* x, const int *incx, float* y, const int* incy);\n"); + modelHasWeights = true; + break; } - } - fGC += ("}//BLAS\n"); - } - if (fUseSession) { - fGC += "struct Session {\n"; - } - for (auto& i: fInitializedTensors){ - if (i.second.fType == ETensorType::FLOAT){ + } + if (!modelHasWeights) fUseWeightFile = false; + } + + for (auto& i : fOperators) { + i->Initialize(*this); + } +} + +void RModel::GenerateInitializedTensorInfo() { + for (auto& i: fInitializedTensors) { + if (i.second.fType == ETensorType::FLOAT) { size_t length = 1; - for (auto & dim: i.second.fShape){ - length *= dim; + for (auto & dim: i.second.fShape) { + length *= dim; } if (!fUseWeightFile) { - fGC += "float tensor_" + i.first + "[" + std::to_string(length) + "] = {"; - std::shared_ptr data = std::static_pointer_cast(i.second.fData); - std::stringstream floats; - for (size_t idx = 0; idx < length-1; idx++){ - floats << std::setprecision(std::numeric_limits::max_digits10) << data.get()[idx] << ", "; - } - floats << std::setprecision(std::numeric_limits::max_digits10) << data.get()[length-1]; - fGC += floats.str(); - fGC += "};\n"; + fGC += "float tensor_" + i.first + "[" + std::to_string(length) + "] = {"; + std::shared_ptr data = std::static_pointer_cast(i.second.fData); + std::stringstream floats; + for (size_t idx = 0; idx < length-1; idx++) { + floats << std::setprecision(std::numeric_limits::max_digits10) << data.get()[idx] << ", "; + } + floats << std::setprecision(std::numeric_limits::max_digits10) << data.get()[length-1]; + fGC += floats.str(); + fGC += "};\n"; } else { - fGC += "std::vector fTensor_" + i.first + " = std::vector(" + std::to_string(length) + ");\n"; - fGC += "float * tensor_" + i.first + " = fTensor_" + i.first + ".data();\n"; + fGC += "std::vector fTensor_" + i.first + " = std::vector(" + std::to_string(length) + ");\n"; + fGC += "float * tensor_" + i.first + " = fTensor_" + i.first + ".data();\n"; } - } - } - for (auto&i: fIntermediateTensorInfos){ - size_t length = ConvertShapeToLength(i.second.shape); - if (i.second.type == ETensorType::FLOAT){ + } + } +} + +void RModel::GenerateIntermediateTensorInfo() { + for (auto&i: fIntermediateTensorInfos) { + size_t length = ConvertShapeToLength(i.second.shape); + if (i.second.type == ETensorType::FLOAT) { fGC += "std::vector fTensor_" + i.first + " = std::vector(" + std::to_string(length) + ");\n"; fGC += "float * tensor_" + i.first + " = fTensor_" + i.first + ".data();\n"; - } - if (i.second.type == ETensorType::DOUBLE){ + } + if (i.second.type == ETensorType::DOUBLE) { fGC += "std::vector fTensor_" + i.first + " = std::vector(" + std::to_string(length) + ");\n"; fGC += "double * tensor_" + i.first + " = fTensor_" + i.first + ".data();\n"; - } - if (i.second.type == ETensorType::INT64){ + } + if (i.second.type == ETensorType::INT64) { fGC += "std::vector fTensor_" + i.first + " = std::vector(" + std::to_string(length) + ");\n"; fGC += "int64_t * tensor_" + i.first + " = fTensor_" + i.first + ".data();\n"; - } - } - if (fUseSession) { - // add here specific operator code that needs to define session data members - fGC += "\n"; - for (size_t id = 0; id < fOperators.size(); id++) { - std::string opName = std::to_string(id); - fGC += fOperators[id]->GenerateSessionMembersCode(opName); - } - fGC += "\n"; - // here add initialization and reading of weight tensors - if (fUseWeightFile) { - fGC += "Session(std::string filename =\"\") {\n"; - fGC += " if (filename.empty()) filename = \"" + fName + ".dat\";\n"; - ReadInitializedTensorsFromFile(); - //fUseWeightFile = fUseWeightFile; - } else { - // no need to pass weight file since it is not used - // keep passing a string for compatibility - fGC += "Session(std::string = \"\") {\n"; - } - // add here initialization code - for (size_t id = 0; id < fOperators.size() ; id++){ - fGC += fOperators[id]->GenerateInitCode(); - } - fGC += "}\n\n"; - } - - size_t outputSize = fOutputTensorNames.size(); - // assume output types are all the same - std::string outputType; - if (outputSize == 1) { - auto f = fIntermediateTensorInfos.find(fOutputTensorNames[0]); - if (f == fIntermediateTensorInfos.end()){ + } + } +} + +void RModel::GenerateOutput() { + size_t outputSize = fOutputTensorNames.size(); + // assume output types are all the same + std::string outputType; + if (outputSize == 1) { + auto f = fIntermediateTensorInfos.find(fOutputTensorNames[0]); + if (f == fIntermediateTensorInfos.end()) { throw std::runtime_error("TMVA-SOFIE: output tensor " + fOutputTensorNames[0] + " not found when trying to get its info"); - }else{ + } else { outputType = ConvertTypeToString(f->second.type); fGC += "std::vector<" + outputType + "> "; - } - } else { - std::vector outputTensorsTypes(outputSize); - for (size_t i = 0; i < outputSize; i++) { + } + } else { + std::vector outputTensorsTypes(outputSize); + for (size_t i = 0; i < outputSize; i++) { auto f = fIntermediateTensorInfos.find(fOutputTensorNames[i]); if (f == fIntermediateTensorInfos.end()) { - throw std::runtime_error("TMVA-SOFIE: output tensor " + fOutputTensorNames[i] - + " not found when trying to get its info"); + throw std::runtime_error("TMVA-SOFIE: output tensor " + fOutputTensorNames[i] + + " not found when trying to get its info"); } else { - outputTensorsTypes[i] = f->second.type; + outputTensorsTypes[i] = f->second.type; } - } - // assume all output types are the same - outputType = ConvertTypeToString(outputTensorsTypes[0]); - for (size_t i = 0; i < outputSize; i++) { + } + // assume all output types are the same + outputType = ConvertTypeToString(outputTensorsTypes[0]); + for (size_t i = 0; i < outputSize; i++) { if (outputTensorsTypes[i] != outputTensorsTypes[0]) { - throw std::runtime_error("TMVA-SOFIE: output tensor " + fOutputTensorNames[i] + " is of different type."); - } - } - fGC += "std::vector> "; - } - - fGC += "infer("; - for(size_t i = 0; iGenerate(std::to_string(id))); - } - if (outputSize == 1) { - size_t outputLength = ConvertShapeToLength(GetTensorShape(fOutputTensorNames[0])); - - fGC += SP + "std::vector<" + outputType + "> ret (tensor_" + fOutputTensorNames[0] + ", tensor_" + fOutputTensorNames[0] + " + " + + } + fGC += "std::vector> "; + } + + fGC += "infer("; + + for(size_t i = 0; iGenerate(std::to_string(id))); + } + + if (outputSize == 1) { + size_t outputLength = ConvertShapeToLength(GetTensorShape(fOutputTensorNames[0])); + + fGC += SP + "std::vector<" + outputType + "> ret (tensor_" + fOutputTensorNames[0] + ", tensor_" + fOutputTensorNames[0] + " + " + std::to_string(outputLength) + ");\n"; - } else { - for (size_t i = 0; i < outputSize; i++) { + } else { + for (size_t i = 0; i < outputSize; i++) { if (!fOutputTensorNames[i].empty()) { - size_t outputLength = ConvertShapeToLength(GetTensorShape(fOutputTensorNames[i])); - fGC += SP + "std::vector<" + outputType + "> ret_"; - fGC += std::to_string(i); - fGC += " (tensor_" + fOutputTensorNames[i] + ", tensor_" + fOutputTensorNames[i] + " + " + - std::to_string(outputLength) + ");\n"; + size_t outputLength = ConvertShapeToLength(GetTensorShape(fOutputTensorNames[i])); + fGC += SP + "std::vector<" + outputType + "> ret_"; + fGC += std::to_string(i); + fGC += " (tensor_" + fOutputTensorNames[i] + ", tensor_" + fOutputTensorNames[i] + " + " + + std::to_string(outputLength) + ");\n"; } - } - fGC += SP + "std::vector> ret({"; - for (size_t i = 0; i < outputSize; i++) { + } + fGC += SP + "std::vector> ret({"; + for (size_t i = 0; i < outputSize; i++) { if (fOutputTensorNames[i].empty()) { - fGC += "{}"; + fGC += "{}"; } else { - fGC += "ret_"; - fGC += std::to_string(i); + fGC += "ret_"; + fGC += std::to_string(i); } if (i < outputSize - 1) { - fGC += ","; + fGC += ","; } - } - fGC += "});\n"; - } - fGC += SP + "return ret;\n"; - fGC += "}\n"; - if (fUseSession) { - fGC += "};\n"; - } - fGC += ("} //TMVA_SOFIE_" + fName + "\n"); - fGC += "\n#endif // " + hgname + "\n"; - } - - void RModel::ReadInitializedTensorsFromFile() { - // generate the code to read initialized tensors from a text data file - if (fInitializedTensors.empty()) return; - - fGC += " std::ifstream f;\n"; - fGC += " f.open(filename);\n"; - fGC += " if (!f.is_open()){\n"; - fGC += " throw std::runtime_error(\"tmva-sofie failed to open file for input weights\");\n"; - fGC += " }\n"; - fGC += " std::string tensor_name;\n"; - fGC += " int length;\n"; - - //loop on tensors and parse the file - for (auto& i: fInitializedTensors){ - if (i.second.fType == ETensorType::FLOAT){ - size_t length = 1; - for (auto & dim: i.second.fShape){ - length *= dim; + } + fGC += "});\n"; + } + fGC += SP + "return ret;\n"; + fGC += "}\n"; +} + +void RModel::Generate(std::underlying_type_t options, int batchSize, long pos) { + // session flag is used in operator initialize + if (static_cast>(Options::kNoSession) & options) { + fUseSession = false; + fWeightFile = WeightFileType::None; + } + if (static_cast>(Options::kNoWeightFile) & options) { + fUseWeightFile = false; + fWeightFile = WeightFileType::None; + } + if (static_cast>(Options::kRootBinaryWeightFile) & options) { + fUseWeightFile = true; + fWeightFile = WeightFileType::RootBinary; + } + if (fUseWeightFile && !fUseSession) { + throw + std::runtime_error("TMVA-SOFIE: RModel::Generate: cannot use a separate weight file without generating a Session class"); + } + + if (static_cast>(Options::kGNN) & options) + fIsGNN = true; + if (static_cast>(Options::kGNNComponent) & options) + fIsGNNComponent = true; + + Initialize(batchSize); + std::string hgname; + if(!fIsGNNComponent) { + fGC.clear(); + GenerateHeaderInfo(hgname); + if (fUseSession) { + fGC += "struct Session {\n"; + } + } + + GenerateInitializedTensorInfo(); + GenerateIntermediateTensorInfo(); + + if (fUseSession) { + // add here specific operator code that needs to define session data members + fGC += "\n"; + for (size_t id = 0; id < fOperators.size(); id++) { + std::string opName = std::to_string(id); + fGC += fOperators[id]->GenerateSessionMembersCode(opName); + } + fGC += "\n"; + // here add initialization and reading of weight tensors + if (fUseWeightFile) { + fGC += "Session(std::string filename =\"\") {\n"; + fGC += " if (filename.empty()) filename = \"" + fName; + if (fWeightFile == WeightFileType::Text) { + fGC += ".dat\";\n"; + } + if (fWeightFile == WeightFileType::RootBinary) { + fGC += ".root\";\n"; + } + ReadInitializedTensorsFromFile(pos); + //fUseWeightFile = fUseWeightFile; + } else { + // no need to pass weight file since it is not used + // keep passing a string for compatibility + fGC += "Session(std::string = \"\") {\n"; + } + + // add here initialization code + for (size_t id = 0; id < fOperators.size() ; id++) { + fGC += fOperators[id]->GenerateInitCode(); + } + + fGC += "}\n\n"; + } + + GenerateOutput(); + + if(!fIsGNNComponent) { + if (fUseSession) { + fGC += "};\n"; + } + fGC += ("} //TMVA_SOFIE_" + fName + "\n"); + fGC += "\n#endif // " + hgname + "\n"; + } +} + +void RModel::ReadInitializedTensorsFromFile(long pos) { + // generate the code to read initialized tensors from a text data file + if (fWeightFile == WeightFileType::Text) { + if (fInitializedTensors.empty()) return; + + fGC += " std::ifstream f;\n"; + fGC += " f.open(filename);\n"; + fGC += " if (!f.is_open()) {\n"; + fGC += " throw std::runtime_error(\"tmva-sofie failed to open file for input weights\");\n"; + fGC += " }\n"; + + if(fIsGNNComponent) { + fGC += " f.seekg(" + std::to_string(pos) + ");\n"; + } + + fGC += " std::string tensor_name;\n"; + fGC += " size_t length;\n"; + + // loop on tensors and parse the file + for (auto& i: fInitializedTensors) { + if (i.second.fType == ETensorType::FLOAT) { + size_t length = 1; + length = ConvertShapeToLength(i.second.fShape); + std::string tensor_name = "tensor_" + i.first; + std::string slength = std::to_string(length); + fGC += " f >> tensor_name >> length;\n"; + fGC += " if (tensor_name != \"" + tensor_name + "\" ) {\n"; + fGC += " std::string err_msg = \"TMVA-SOFIE failed to read the correct tensor name; expected name is " + + tensor_name + " , read \" + tensor_name;\n"; + fGC += " throw std::runtime_error(err_msg);\n"; + fGC += " }\n"; + fGC += " if (length != " + slength + ") {\n"; + fGC += " std::string err_msg = \"TMVA-SOFIE failed to read the correct tensor size; expected size is " + + slength + " , read \" + std::to_string(length) ;\n"; + fGC += " throw std::runtime_error(err_msg);\n"; + fGC += " }\n"; + fGC += " for (size_t i = 0; i < length; ++i)\n"; + fGC += " f >> " + tensor_name + "[i];\n"; } + } + fGC += " f.close();\n"; + } + + // generate the code to read initialized tensors from a ROOT data file + if(fWeightFile == WeightFileType::RootBinary) { + fGC += " {\n"; + fGC += " std::unique_ptr rootFile(TFile::Open(filename.c_str(), \"READ\"));\n"; + fGC += " if (!rootFile->IsOpen()) {\n"; + fGC += " throw std::runtime_error(\"tmva-sofie failed to open ROOT file for input weights\");\n"; + fGC += " }\n"; + + std::string dirName = fName + "_weights"; + fGC += " if (!rootFile->GetKey(\"" + dirName + "\")) {\n"; + fGC += " throw std::runtime_error(\"tmva-sofie failed to open ROOT directory for input weights\");\n"; + fGC += " }\n"; + + for (auto &i : fInitializedTensors) { + fGC += " {\n"; std::string tensor_name = "tensor_" + i.first; - std::string slength = std::to_string(length); - fGC += " f >> tensor_name >> length;\n"; - fGC += " if (tensor_name != \"" + tensor_name + "\" ) {\n"; - fGC += " std::string err_msg = \"TMVA-SOFIE failed to read the correct tensor name; expected name is " + - tensor_name + " , read \" + tensor_name;\n"; - fGC += " throw std::runtime_error(err_msg);\n"; - fGC += " }\n"; - fGC += " if (length != " + slength + ") {\n"; - fGC += " std::string err_msg = \"TMVA-SOFIE failed to read the correct tensor size; expected size is " + - slength + " , read \" + std::to_string(length) ;\n"; - fGC += " throw std::runtime_error(err_msg);\n"; - fGC += " }\n"; - fGC += " for (int i =0; i < length; ++i) \n"; - fGC += " f >> " + tensor_name + "[i];\n"; - } - } - fGC += " f.close();\n"; - } - - void RModel::WriteInitializedTensorsToFile(std::string filename) { - // write the initialized tensors in a text file - if (filename == ""){ - filename = fName + ".data"; - } - - std::ofstream f; - f.open(filename); - if (!f.is_open()){ - throw std::runtime_error("tmva-sofie failed to open file for tensor weight data"); - } - for (auto& i: fInitializedTensors){ - if (i.second.fType == ETensorType::FLOAT){ + if (i.second.fType == ETensorType::FLOAT) { + fGC += " fTensor_" + i.first + " = *reinterpret_cast*>(rootFile->Get(\""; + fGC += dirName + "/" + tensor_name + "\"));\n"; + } else if (i.second.fType == ETensorType::DOUBLE) { + fGC += " fTensor_" + i.first + " = *reinterpret_cast*>(rootFile->Get(\""; + fGC += dirName + + "/" + tensor_name + "\"));\n"; + } else if (i.second.fType == ETensorType::INT64) { + fGC += " fTensor_" + i.first + " = *reinterpret_cast*>(rootFile->Get(\""; + fGC += dirName + "/" + tensor_name + "\"));\n"; + } + fGC += " }\n"; + } + fGC += " }\n"; + } +} + +long RModel::WriteInitializedTensorsToFile(std::string filename) { + // Determine the file extension based on the weight file type + std::string fileExtension; + switch (fWeightFile) { + case WeightFileType::None: + fileExtension = ".dat"; + break; + case WeightFileType::RootBinary: + fileExtension = ".root"; + break; + case WeightFileType::Text: + fileExtension = ".dat"; + break; + } + + // If filename is empty, use the model name as the base filename + if (filename.empty()) { + filename = fFileName + fileExtension; + } + + // Write the initialized tensors to the file + if (fWeightFile == WeightFileType::RootBinary) { + if(fIsGNNComponent || fIsGNN) { + throw std::runtime_error("SOFIE-GNN yet not supports writing to a ROOT file."); + } + std::unique_ptr outputFile(TFile::Open(filename.c_str(), "UPDATE")); + + std::string dirName = fName + "_weights"; + // check if directory exists, in case delete to replace with new one + if (outputFile->GetKey(dirName.c_str())) + outputFile->rmdir(dirName.c_str()); + + auto outputDir = outputFile->mkdir(dirName.c_str()); + + for (const auto& item : fInitializedTensors) { + std::string tensorName = "tensor_" + item.first; size_t length = 1; - for (auto &dim : i.second.fShape) { - length *= dim; + length = ConvertShapeToLength(item.second.fShape); + if(item.second.fType == ETensorType::FLOAT) { + const std::shared_ptr ptr = item.second.fData; // shared_ptr instance + const float* data = (std::static_pointer_cast(item.second.fData)).get(); + std::vector tensorDataVector(data, data + length); + outputDir->WriteObjectAny(&tensorDataVector, "std::vector", tensorName.c_str()); } - std::string tensor_name = "tensor_" + i.first; - f << tensor_name << " " << length << "\n"; - const float * data = (std::static_pointer_cast(i.second.fData)).get(); - for (size_t idx = 0; idx < length - 1; idx++) { - f << std::setprecision(std::numeric_limits::max_digits10) << data[idx] << " "; + else if(item.second.fType == ETensorType::DOUBLE) { + const std::shared_ptr ptr = item.second.fData; // shared_ptr instance + const double* data = (std::static_pointer_cast(item.second.fData)).get(); + std::vector tensorDataVector(data, data + length); + outputDir->WriteObjectAny(&tensorDataVector, "std::vector", tensorName.c_str()); } - f << std::setprecision(std::numeric_limits::max_digits10) << data[length - 1]; - f << "\n"; - } - } - f.close(); - } - - void RModel::PrintRequiredInputTensors(){ - std::cout << "Model requires following inputs:\n"; - for (auto& inputInfo: fInputTensorInfos){ - std::cout << "Parameterised Tensor name: " << inputInfo.first << "\t"; - std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\t"; - std::cout << "shape: ["; - for (size_t i = 0; i < inputInfo.second.shape.size(); i++){ - if (inputInfo.second.shape[i].isParam){ - std::cout << inputInfo.second.shape[i].param; - }else{ - std::cout << inputInfo.second.shape[i].dim ; + else if(item.second.fType == ETensorType::INT64) { + const std::shared_ptr ptr = item.second.fData; // shared_ptr instance + const int64_t* data = (std::static_pointer_cast(item.second.fData)).get(); + std::vector tensorDataVector(data, data + length); + outputDir->WriteObjectAny(&tensorDataVector, "std::vector", tensorName.c_str()); + } + } + outputFile->Write(filename.c_str()); + + // this needs to be changed, similar to the text file + return -1; + + } else if (fWeightFile == WeightFileType::Text) { + std::ofstream f; + if(fIsGNNComponent) { + // appending all GNN components into the same file + f.open(filename, std::ios::app); + } else { + f.open(filename); + } + if (!f.is_open()) + throw + std::runtime_error("tmva-sofie failed to open file for tensor weight data"); + for (auto& i: fInitializedTensors) { + if (i.second.fType == ETensorType::FLOAT) { + size_t length = 1; + for (auto &dim : i.second.fShape) { + length *= dim; + } + std::string tensor_name = "tensor_" + i.first; + f << tensor_name << " " << length << "\n"; + const float * data = (std::static_pointer_cast(i.second.fData)).get(); + for (size_t idx = 0; idx < length - 1; idx++) { + f << std::setprecision(std::numeric_limits::max_digits10) << data[idx] << " "; + } + f << std::setprecision(std::numeric_limits::max_digits10) << data[length - 1]; + f << "\n"; + } + } + long curr_pos = f.tellp(); + f.close(); + return curr_pos; + } else { + return -1; + } +} + +void RModel::PrintRequiredInputTensors() { + std::cout << "Model requires following inputs:\n"; + for (auto& inputInfo: fInputTensorInfos) { + std::cout << "Parameterised Tensor name: " << inputInfo.first << "\t"; + std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\t"; + std::cout << "shape: ["; + for (size_t i = 0; i < inputInfo.second.shape.size(); i++) { + if (inputInfo.second.shape[i].isParam) { + std::cout << inputInfo.second.shape[i].param; + } else { + std::cout << inputInfo.second.shape[i].dim ; } if (i < inputInfo.second.shape.size() - 1) std::cout << ","; - } - std::cout << "]" << std::endl; - } - - for (auto& inputInfo: fReadyInputTensorInfos){ - std::cout << "Fully Specified Tensor name: " << inputInfo.first << "\t"; - std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\t"; - std::cout << "shape: ["; - for (size_t i = 0; i < inputInfo.second.shape.size(); i++){ + } + std::cout << "]" << std::endl; + } + + for (auto& inputInfo: fReadyInputTensorInfos) { + std::cout << "Fully Specified Tensor name: " << inputInfo.first << "\t"; + std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\t"; + std::cout << "shape: ["; + for (size_t i = 0; i < inputInfo.second.shape.size(); i++) { std::cout << inputInfo.second.shape[i]; if (i < inputInfo.second.shape.size() - 1) std::cout << ","; - } - std::cout << "]" << std::endl; - } - - } - - void RModel::PrintInitializedTensors(){ - std::cout << "Model initialized the following tensors:\n"; - for (auto& it: fInitializedTensors){ - std::cout << "Tensor name: \"" << it.first << "\"\t"; - std::cout << "type: " << ConvertTypeToString(it.second.fType) << "\t"; - std::cout << "shape: ["; - for (size_t i = 0; i < it.second.fShape.size(); i++){ + } + std::cout << "]" << std::endl; + } + +} + +void RModel::PrintInitializedTensors() { + std::cout << "Model initialized the following tensors:\n"; + for (auto& it: fInitializedTensors) { + std::cout << "Tensor name: \"" << it.first << "\"\t"; + std::cout << "type: " << ConvertTypeToString(it.second.fType) << "\t"; + std::cout << "shape: ["; + for (size_t i = 0; i < it.second.fShape.size(); i++) { std::cout << it.second.fShape[i]; if (i < it.second.fShape.size() - 1) std::cout << ","; - } - std::cout << "]" << std::endl; - } - } - - void RModel::PrintIntermediateTensors(){ - std::cout << "Model specify the following intermediate tensors:\n"; - for (auto& it: fIntermediateTensorInfos){ - std::cout << "Tensor name: \"" << it.first << "\"\t"; - std::cout << "type: " << ConvertTypeToString(it.second.type) << "\t"; - std::cout << "shape: ["; - for (size_t i = 0; i < it.second.shape.size(); i++){ + } + std::cout << "]" << std::endl; + } +} + +void RModel::PrintIntermediateTensors() { + std::cout << "Model specify the following intermediate tensors:\n"; + for (auto& it: fIntermediateTensorInfos) { + std::cout << "Tensor name: \"" << it.first << "\"\t"; + std::cout << "type: " << ConvertTypeToString(it.second.type) << "\t"; + std::cout << "shape: ["; + for (size_t i = 0; i < it.second.shape.size(); i++) { std::cout << it.second.shape[i]; if (i < it.second.shape.size() - 1) std::cout << ","; - } - std::cout << "]" << std::endl; - } - } - - void RModel::HeadInitializedTensors(std::string name, int n_print){ - auto it = fInitializedTensors.find(name); - if (it == fInitializedTensors.end()){ - std::cout << "Tensor " << name << " not found in model's intialized tensor list" << std::endl; - return; - } - - std::cout << "Tensor name: " << it->first << "\t"; - std::cout << "type: " << ConvertTypeToString(it->second.fType) << "\t"; - int length =1; - std::cout << "shape: ["; - for (size_t i = 0; i < it->second.fShape.size(); i++){ - std::cout << it->second.fShape[i]; - length *= it->second.fShape[i]; - if (i < it->second.fShape.size() - 1) std::cout << ","; - } - std::cout << "]" << std::endl; - bool ellipsis = true; - if (n_print > length){ - n_print = length; - ellipsis = false; - } - - std::cout << "data: [" << std::endl; - //switch(it->second.type){ - // case ETensorType::FLOAT : { - if (it->second.fType == ETensorType::FLOAT) { - auto converted_data = std::static_pointer_cast(it->second.fData).get(); - for (int i =0; i < n_print; i++){ + } + std::cout << "]" << std::endl; + } +} + +void RModel::PrintOutputTensors() { + std::cout << "Model specify the following output tensors:\n"; + for (auto& it: fOutputTensorNames) { + std::cout << "Tensor name: \"" << it << "\"\t"; + std::cout << "shape: " << ConvertShapeToString(GetTensorShape(it)) << std::endl; + } +} + +void RModel::HeadInitializedTensors(std::string name, int n_print) { + auto it = fInitializedTensors.find(name); + if (it == fInitializedTensors.end()) { + std::cout << "Tensor " << name << " not found in model's intialized tensor list" << std::endl; + return; + } + + std::cout << "Tensor name: " << it->first << "\t"; + std::cout << "type: " << ConvertTypeToString(it->second.fType) << "\t"; + int length =1; + std::cout << "shape: ["; + for (size_t i = 0; i < it->second.fShape.size(); i++) { + std::cout << it->second.fShape[i]; + length *= it->second.fShape[i]; + if (i < it->second.fShape.size() - 1) std::cout << ","; + } + std::cout << "]" << std::endl; + bool ellipsis = true; + if (n_print > length) { + n_print = length; + ellipsis = false; + } + + std::cout << "data: [" << std::endl; + if (it->second.fType == ETensorType::FLOAT) { + auto converted_data = std::static_pointer_cast(it->second.fData).get(); + for (int i =0; i < n_print; i++) { std::cout << converted_data[i]; if (i < n_print - 1) std::cout << " ,"; - } - // break; - // } - } - if (ellipsis) std::cout << ", ..."; - std::cout << "]" << std::endl; - - } - - void RModel::OutputGenerated(std::string filename){ - if (filename == ""){ - filename = fName + ".hxx"; - } - std::ofstream f; - f.open(filename); - if (!f.is_open()){ - throw std::runtime_error("tmva-sofie failed to open file for output generated inference code"); - } - f << fGC; - f.close(); - - // write weights in a text file - size_t pos = filename.find(".hxx"); - filename.replace(pos,4,".dat"); - if (fUseWeightFile) WriteInitializedTensorsToFile(filename); - } - - void RModel::Streamer(TBuffer &R__b){ - if (R__b.IsReading()) { - RModel::Class()->ReadBuffer(R__b, this); - for(auto i=RModel::fInitializedTensors.begin(); i!=RModel::fInitializedTensors.end();++i){ - i->second.CastPersistentToShared(); - } - } - else { - for(auto i=RModel::fInitializedTensors.begin(); i!=RModel::fInitializedTensors.end();++i){ - i->second.CastSharedToPersistent(); - } - RModel::Class()->WriteBuffer(R__b, this); - } - } + } + } + if (ellipsis) std::cout << ", ..."; + std::cout << "]" << std::endl; + +} + +void RModel::OutputGenerated(std::string filename, bool append) { + + RModel_Base::OutputGenerated(filename, append); + + // write weights in a text file + if (fUseWeightFile) { + if (!filename.empty()) { + size_t pos = filename.find(".hxx"); + if (fWeightFile == WeightFileType::Text) + filename.replace(pos, 4, ".dat"); + if (fWeightFile == WeightFileType::RootBinary) { + filename = filename.erase(pos, 4); + filename += ".root"; + } + } else { + filename = fName; + filename += fWeightFile == WeightFileType::Text ? ".dat" : ".root"; + } + WriteInitializedTensorsToFile(filename); + } +} + +void RModel::Streamer(TBuffer &R__b) { + if (R__b.IsReading()) { + RModel::Class()->ReadBuffer(R__b, this); + for(auto i=RModel::fInitializedTensors.begin(); i!=RModel::fInitializedTensors.end(); ++i) { + i->second.CastPersistentToShared(); + } + } + else { + for(auto i=RModel::fInitializedTensors.begin(); i!=RModel::fInitializedTensors.end(); ++i) { + i->second.CastSharedToPersistent(); + } + RModel::Class()->WriteBuffer(R__b, this); + } +} }//SOFIE }//Experimental diff --git a/tmva/sofie/src/RModel_Base.cxx b/tmva/sofie/src/RModel_Base.cxx new file mode 100644 index 0000000000000..86b196427bf1e --- /dev/null +++ b/tmva/sofie/src/RModel_Base.cxx @@ -0,0 +1,82 @@ +#include +#include +#include +#include "TMVA/RModel_Base.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +RModel_Base::RModel_Base(std::string name, std::string parsedtime):fFileName(name), fParseTime(parsedtime) { + fName = fFileName.substr(0, fFileName.rfind(".")); +} + +void RModel_Base::GenerateHeaderInfo(std::string& hgname) { + fGC += ("//Code generated automatically by TMVA for Inference of Model file [" + fFileName + "] at [" + fParseTime.substr(0, fParseTime.length()-1) +"] \n"); + // add header guards + hgname = fName; + std::transform(hgname.begin(), hgname.end(), hgname.begin(), [](unsigned char c) { + return std::toupper(c); + } ); + hgname = "ROOT_TMVA_SOFIE_" + hgname; + fGC += "\n#ifndef " + hgname + "\n"; + fGC += "#define " + hgname + "\n\n"; + for (auto& i: fNeededStdLib) { + fGC += "#include <" + i + ">\n"; + } + for (auto& i: fCustomOpHeaders) { + fGC += "#include \"" + i + "\"\n"; + } + // for the session we need to include SOFIE_Common functions + //needed for convolution operator (need to add a flag) + fGC += "#include \"TMVA/SOFIE_common.hxx\"\n"; + if (fUseWeightFile) + fGC += "#include \n"; + // Include TFile when saving the weights in a binary ROOT file + if (fWeightFile == WeightFileType::RootBinary) + fGC += "#include \"TFile.h\"\n"; + + fGC += "\nnamespace TMVA_SOFIE_" + fName + "{\n"; + if (!fNeededBlasRoutines.empty()) { + fGC += ("namespace BLAS{\n"); + for (auto &routine : fNeededBlasRoutines) { + if (routine == "Gemm") { + fGC += ("\textern \"C\" void sgemm_(const char * transa, const char * transb, const int * m, const int * n, const int * k,\n" + "\t const float * alpha, const float * A, const int * lda, const float * B, const int * ldb,\n" + "\t const float * beta, float * C, const int * ldc);\n"); + } else if (routine == "Gemv") { + fGC += ("\textern \"C\" void sgemv_(const char * trans, const int * m, const int * n, const float * alpha, const float * A,\n" + "\t const int * lda, const float * X, const int * incx, const float * beta, const float * Y, const int * incy);\n"); + } else if (routine == "Axpy") { + fGC += ("\textern \"C\" void saxpy_(const int * n, const float * alpha, const float * x,\n" + "\t const int * incx, float * y, const int * incy);\n"); + } else if (routine == "Copy") { + fGC += ("\textern \"C\" void scopy_(const int *n, const float* x, const int *incx, float* y, const int* incy);\n"); + } + } + fGC += ("}//BLAS\n"); + } +} + +void RModel_Base::OutputGenerated(std::string filename, bool append) { + // the model can be appended only if a file name is provided + if (filename.empty()) { + // if a file is pr + filename = fName + ".hxx"; + append = false; + } + std::ofstream f; + if (append) + f.open(filename, std::ios_base::app); + else + f.open(filename); + if (!f.is_open()) { + throw std::runtime_error("tmva-sofie failed to open file for output generated inference code"); + } + f << fGC; + f.close(); +} + +}//SOFIE +}//Experimental +}//TMVA diff --git a/tmva/sofie/src/RModel_GNN.cxx b/tmva/sofie/src/RModel_GNN.cxx new file mode 100644 index 0000000000000..0a45292f8bf73 --- /dev/null +++ b/tmva/sofie/src/RModel_GNN.cxx @@ -0,0 +1,310 @@ +#include +#include +#include +#include + +#include "TMVA/RModel_GNN.hxx" +#include "TMVA/RFunction.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +RModel_GNN::RModel_GNN(RModel_GNN&& other) { + edges_update_block = std::move(other.edges_update_block); + nodes_update_block = std::move(other.nodes_update_block); + globals_update_block = std::move(other.globals_update_block); + + edge_node_agg_block = std::move(other.edge_node_agg_block); + edge_global_agg_block = std::move(other.edge_global_agg_block); + node_global_agg_block = std::move(other.node_global_agg_block); + + num_nodes = std::move(other.num_nodes); + num_edges = std::move(other.num_edges); + senders = std::move(other.senders); + receivers = std::move(other.receivers); + + fName = std::move(other.fName); + fFileName = std::move(other.fFileName); + fParseTime = std::move(other.fParseTime); +} + +RModel_GNN& RModel_GNN::operator=(RModel_GNN&& other) { + edges_update_block = std::move(other.edges_update_block); + nodes_update_block = std::move(other.nodes_update_block); + globals_update_block = std::move(other.globals_update_block); + + edge_node_agg_block = std::move(other.edge_node_agg_block); + edge_global_agg_block = std::move(other.edge_global_agg_block); + node_global_agg_block = std::move(other.node_global_agg_block); + + num_nodes = std::move(other.num_nodes); + num_edges = std::move(other.num_edges); + senders = std::move(other.senders); + receivers = std::move(other.receivers); + + fName = std::move(other.fName); + fFileName = std::move(other.fFileName); + fParseTime = std::move(other.fParseTime); + + return *this; +} + +RModel_GNN::RModel_GNN(GNN_Init& graph_input_struct) { + edges_update_block = std::move(graph_input_struct.edges_update_block); + nodes_update_block = std::move(graph_input_struct.nodes_update_block); + globals_update_block = std::move(graph_input_struct.globals_update_block); + + edge_node_agg_block = std::move(graph_input_struct.edge_node_agg_block); + edge_global_agg_block = std::move(graph_input_struct.edge_global_agg_block); + node_global_agg_block = std::move(graph_input_struct.node_global_agg_block); + + num_nodes = graph_input_struct.num_nodes; + num_edges = graph_input_struct.edges.size(); + num_node_features = graph_input_struct.num_node_features; + num_edge_features = graph_input_struct.num_edge_features; + num_global_features = graph_input_struct.num_global_features; + for(auto& it:graph_input_struct.edges) { + receivers.emplace_back(it.first); + senders.emplace_back(it.second); + } + fFileName = graph_input_struct.filename; + fName = fFileName.substr(0, fFileName.rfind(".")); + + std::time_t ttime = std::time(0); + std::tm* gmt_time = std::gmtime(&ttime); + fParseTime = std::asctime(gmt_time); +} + +void RModel_GNN::Generate() { + std::string hgname; + GenerateHeaderInfo(hgname); + + std::ofstream f; + f.open(fName+".dat"); + f.close(); + + // Generating Infer function definition for Edge Update function + long next_pos; + size_t block_size = num_edges; + fGC+="\n\nnamespace Edge_Update{\nstruct Session {\n"; + std::vector> Update_Input_edges = {{block_size, num_edge_features},{block_size, num_node_features},{block_size, num_node_features},{block_size, num_global_features}}; + edges_update_block->Initialize(); + edges_update_block->AddInputTensors(Update_Input_edges); + fGC+=edges_update_block->GenerateModel(fName); + next_pos = edges_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // the number of output edges features can be smaller, so we need to correct here + auto num_edge_features_input = num_edge_features; + if(edges_update_block->GetFunctionBlock()->GetTensorShape(edges_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_edge_features) { + num_edge_features = edges_update_block->GetFunctionBlock()->GetTensorShape(edges_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + fGC+="\n\nnamespace Node_Update{\nstruct Session {\n"; + // Generating Infer function definition for Node Update function + // num_node_features is the output one + + block_size = num_nodes; + std::vector> Update_Input_nodes = {{block_size, num_edge_features},{block_size, num_node_features},{block_size, num_global_features}}; + nodes_update_block->Initialize(); + nodes_update_block->AddInputTensors(Update_Input_nodes); + fGC+=nodes_update_block->GenerateModel(fName,next_pos); + next_pos = nodes_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // we need to correct the output number of node features + auto num_node_features_input = num_node_features; + if(nodes_update_block->GetFunctionBlock()->GetTensorShape(nodes_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_node_features) { + num_node_features = nodes_update_block->GetFunctionBlock()->GetTensorShape(nodes_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + fGC+="\n\nnamespace Global_Update{\nstruct Session {\n"; + // Generating Infer function definition for Global Update function + std::vector> Update_Input_globals = {{1, num_edge_features},{1, num_node_features},{1, num_global_features}}; + globals_update_block->Initialize(); + globals_update_block->AddInputTensors(Update_Input_globals); + fGC+=globals_update_block->GenerateModel(fName,next_pos); + next_pos = globals_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // correct for difference in global size (check shape[1] of output og globals update) + auto num_global_features_input = num_global_features; + if(globals_update_block->GetFunctionBlock()->GetTensorShape(globals_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_global_features) { + num_global_features = globals_update_block->GetFunctionBlock()->GetTensorShape(globals_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + fGC+=edge_node_agg_block->GenerateModel(); + + if(edge_node_agg_block->GetFunctionType() != edge_global_agg_block->GetFunctionType()) { + fGC+=edge_global_agg_block->GenerateModel(); + } + if((edge_node_agg_block->GetFunctionType() != node_global_agg_block->GetFunctionType()) && (edge_global_agg_block->GetFunctionType() != node_global_agg_block->GetFunctionType())) { + fGC+=node_global_agg_block->GenerateModel(); + } + fGC+="\n\n"; + + // computing inplace on input graph + fGC += "struct Session {\n"; + fGC += "\n// Instantiating session objects for graph components\n"; + fGC += "Edge_Update::Session edge_update;\n"; + fGC += "Node_Update::Session node_update;\n"; + fGC += "Global_Update::Session global_update;\n\n"; + + fGC += "std::vector fSenders = { "; + for(int k=0; k 0 && k%32 == 0) fGC += "\n"; + } + fGC += " };\n"; + fGC += "std::vector fReceivers = { "; + for(int k=0; k 0 && k%32 == 0) fGC += "\n"; + } + fGC += " };\n"; + + // create temp vector for edge and node updates + fGC += "std::vector fEdgeUpdates = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_edge_features) + ");\n"; + fGC += "\n\nstd::vector fNodeUpdates = std::vector(" + std::to_string(num_nodes) + "*" + std::to_string(num_node_features) + ");\n"; + + fGC += "\n// input vectors for edge update\n"; + fGC += "std::vector fEdgeInputs = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_edge_features_input) + ");\n"; + fGC += "std::vector fRecNodeInputs = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_node_features_input) + ");\n"; + fGC += "std::vector fSndNodeInputs = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_node_features_input) + ");\n"; + fGC += "std::vector fGlobInputs = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_global_features_input) + ");\n\n"; + + fGC += "\n// input vectors for node update\n"; + fGC += "std::vector fNodeInputs = std::vector(" + std::to_string(num_nodes) + "*" + std::to_string(num_node_features_input) + ");\n"; + fGC += "std::vector fNodeEdgeAggregate = std::vector(" + std::to_string(num_nodes) + "*" + std::to_string(num_node_features_input) + ", 0);\n"; + fGC += "std::vector fNodeAggregateTemp;\n"; + + fGC += "\nvoid infer(TMVA::Experimental::SOFIE::GNN_Data& input_graph){\n"; + + // computing updated edge attributes + fGC += "\n// --- Edge Update ---\n"; + std::string e_size_input = std::to_string(num_edge_features_input); + std::string n_size_input = std::to_string(num_node_features_input); + std::string g_size_input = std::to_string(num_global_features_input); + fGC += "for (int k = 0; k < " + std::to_string(num_edges) + "; k++) { \n"; + fGC += " std::copy(input_graph.edge_data.GetData() + k * " + e_size_input + + ", input_graph.edge_data.GetData() + (k + 1) * " + e_size_input + + ", fEdgeInputs.begin() + k * " + e_size_input + ");\n"; + fGC += " std::copy(input_graph.node_data.GetData() + fReceivers[k] * " + n_size_input + + ", input_graph.node_data.GetData() + (fReceivers[k] + 1) * " + n_size_input + + ", fRecNodeInputs.begin() + k * " + n_size_input + ");\n"; + fGC += " std::copy(input_graph.node_data.GetData() + fSenders[k] * " + n_size_input + + ", input_graph.node_data.GetData() + (fSenders[k] + 1) * " + n_size_input + + ", fSndNodeInputs.begin() + k * " + n_size_input + ");\n"; + fGC += " std::copy(input_graph.global_data.GetData()"; + fGC += ", input_graph.global_data.GetData() + " + g_size_input + + ", fGlobInputs.begin() + k * " + g_size_input + ");\n"; + fGC += "}\n"; + + fGC += "fEdgeUpdates = " + edges_update_block->Generate({"fEdgeInputs.data(), fRecNodeInputs.data(), fSndNodeInputs.data(), fGlobInputs.data()"}) + "\n"; + + if(num_edge_features != num_edge_features_input) { + fGC += "\n// resize edge graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.edge_data = input_graph.edge_data.Resize({"+std::to_string(num_edges)+", "+std::to_string(num_edge_features)+"});\n"; + } + // copy output + fGC += "\nfor (int k = 0; k < " + std::to_string(num_edges) + "; k++) { \n"; + fGC += " std::copy(fEdgeUpdates.begin()+ k * " + std::to_string(num_edge_features) + ", fEdgeUpdates.begin()+ (k+1) * " + std::to_string(num_edge_features) + + ",input_graph.edge_data.GetData() + k * " + std::to_string(num_edge_features)+ ");\n"; + fGC += "}\n"; + fGC += "\n"; + + fGC += "\n\n// --- Node Update ---\n"; + + // computing updated edge attributes + fGC += "for (int k = 0; k < " + std::to_string(num_nodes) + "; k++) { \n"; + fGC += " std::copy(input_graph.node_data.GetData() + k * " + n_size_input + + ", input_graph.node_data.GetData() + (k + 1) * " + n_size_input + + ", fNodeInputs.begin() + k * " + n_size_input + ");\n"; + fGC += "}\n"; + // reset initial aggregate edge vector to zero + fGC += "\nstd::fill(fNodeEdgeAggregate.begin(), fNodeEdgeAggregate.end(), 0.);\n"; + // fGlobInputs is size { nedges, ngloblas}. It needs to be here { nnodes, nglobals} + // if number of nodes is larger than edges we need to resize it and copy values + if (num_nodes > num_edges) { + fGC += "\n// resize global vector feature to number of nodes\n"; + fGC += "fGlobInputs.resize( " + std::to_string(num_nodes * num_global_features_input) + ");"; + fGC += "for (size_t k = " + std::to_string(num_edges) + "; k < " + std::to_string(num_nodes) + "; k++)"; + fGC += " std::copy(fGlobInputs.begin(), fGlobInputs.begin() + " + std::to_string(num_global_features_input) + + " , fGlobInputs.begin() + k * " + std::to_string(num_global_features_input) + ");\n"; + } + + // aggregating edge if it's a receiver node and then updating corresponding node + for(int i=0; i Node_Edge_Aggregate_String; + for(int k=0; kGenerate(num_edge_features, {Node_Edge_Aggregate_String}); // aggregating edge attributes per node + fGC += "\nstd::copy(fNodeAggregateTemp.begin(), fNodeAggregateTemp.end(), fNodeEdgeAggregate.begin() + " + + std::to_string(num_edge_features * i) + ");"; + } + } + + fGC+="\n"; + fGC+="fNodeUpdates = "; + fGC+=nodes_update_block->Generate({"fNodeEdgeAggregate.data()","fNodeInputs.data()","fGlobInputs.data()"}); // computing updated node attributes + fGC+="\n"; + + if(num_node_features != num_node_features_input) { + fGC += "\n// resize node graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.node_data = input_graph.node_data.Resize({"+std::to_string(num_nodes)+", "+std::to_string(num_node_features)+"});\n"; + } + // copy output + fGC += "\nfor (int k = 0; k < " + std::to_string(num_nodes) + "; k++) { \n"; + fGC += " std::copy(fNodeUpdates.begin()+ k * " + std::to_string(num_node_features) + ", fNodeUpdates.begin() + (k+1) * " + std::to_string(num_node_features) + + ",input_graph.node_data.GetData() + k * " + std::to_string(num_node_features)+ ");\n"; + fGC += "}\n"; + fGC += "\n"; + + // aggregating edges & nodes for global update + std::vector Node_Global_Aggregate_String; + for(int k=0; k Edge_Global_Aggregate_String; + for(int k=0; kGenerate(num_edge_features, Edge_Global_Aggregate_String); // aggregating edge attributes globally + fGC+="\n"; + + fGC+="std::vector Node_Global_Aggregate = "; + fGC+=node_global_agg_block->Generate(num_node_features, Node_Global_Aggregate_String); // aggregating node attributes globally + fGC+="\n"; + + // computing updated global attributes + fGC += "std::vector Global_Data = "; + fGC += globals_update_block->Generate({"Edge_Global_Aggregate.data()","Node_Global_Aggregate.data()", "input_graph.global_data.GetData()"}); + if(num_global_features != num_global_features_input) { + fGC += "\n// resize global graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.global_data = input_graph.global_data.Resize({"+std::to_string(num_global_features)+"});\n"; + } + fGC += "\nstd::copy(Global_Data.begin(), Global_Data.end(), input_graph.global_data.GetData());"; + fGC+="\n}\n"; + fGC+="};\n"; + + fGC += ("} //TMVA_SOFIE_" + fName + "\n"); + fGC += "\n#endif // TMVA_SOFIE_" + hgname + "\n"; +} + +}//SOFIE +}//Experimental +}//TMVA diff --git a/tmva/sofie/src/RModel_GraphIndependent.cxx b/tmva/sofie/src/RModel_GraphIndependent.cxx new file mode 100644 index 0000000000000..bdb713542dfca --- /dev/null +++ b/tmva/sofie/src/RModel_GraphIndependent.cxx @@ -0,0 +1,204 @@ +#include +#include +#include + +#include "TMVA/RModel_GraphIndependent.hxx" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +RModel_GraphIndependent::RModel_GraphIndependent(RModel_GraphIndependent&& other) { + edges_update_block = std::move(other.edges_update_block); + nodes_update_block = std::move(other.nodes_update_block); + globals_update_block = std::move(other.globals_update_block); + + num_nodes = std::move(other.num_nodes); + num_edges = std::move(other.num_edges); + + fName = std::move(other.fName); + fFileName = std::move(other.fFileName); + fParseTime = std::move(other.fParseTime); +} + +RModel_GraphIndependent& RModel_GraphIndependent::operator=(RModel_GraphIndependent&& other) { + edges_update_block = std::move(other.edges_update_block); + nodes_update_block = std::move(other.nodes_update_block); + globals_update_block = std::move(other.globals_update_block); + + num_nodes = std::move(other.num_nodes); + num_edges = std::move(other.num_edges); + + fName = std::move(other.fName); + fFileName = std::move(other.fFileName); + fParseTime = std::move(other.fParseTime); + + return *this; +} + +RModel_GraphIndependent::RModel_GraphIndependent(GraphIndependent_Init& graph_input_struct) { + edges_update_block = std::move(graph_input_struct.edges_update_block); + nodes_update_block = std::move(graph_input_struct.nodes_update_block); + globals_update_block = std::move(graph_input_struct.globals_update_block); + + num_nodes = graph_input_struct.num_nodes; + num_edges = graph_input_struct.edges.size(); + num_node_features = graph_input_struct.num_node_features; + num_edge_features = graph_input_struct.num_edge_features; + num_global_features = graph_input_struct.num_global_features; + + fFileName = graph_input_struct.filename; + fName = fFileName.substr(0, fFileName.rfind(".")); + + std::time_t ttime = std::time(0); + std::tm* gmt_time = std::gmtime(&ttime); + fParseTime = std::asctime(gmt_time); +} + +void RModel_GraphIndependent::Generate() { + std::string hgname; + GenerateHeaderInfo(hgname); + + std::ofstream f; + f.open(fName+".dat"); + f.close(); + + //Generating Infer function definition for Edge update function + long next_pos; + size_t block_size = num_edges; + fGC+="\n\nnamespace Edge_Update{\nstruct Session {\n"; + std::vector> Update_Input = {{block_size, num_edge_features}}; + edges_update_block->Initialize(); + edges_update_block->AddInputTensors(Update_Input); + fGC+=edges_update_block->GenerateModel(fName); + next_pos = edges_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // the number of output edges features can be smaller, so we need to correct here + auto num_edge_features_input = num_edge_features; + if(edges_update_block->GetFunctionBlock()->GetTensorShape(edges_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_edge_features) { + num_edge_features = edges_update_block->GetFunctionBlock()->GetTensorShape(edges_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + fGC+="\n\nnamespace Node_Update{\nstruct Session {\n"; + // Generating Infer function definition for Node Update function + // num_node_features is the output one + block_size = num_nodes; + Update_Input = {{block_size, num_node_features}}; + nodes_update_block->Initialize(); + nodes_update_block->AddInputTensors(Update_Input); + fGC+=nodes_update_block->GenerateModel(fName,next_pos); + next_pos = nodes_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // we need to correct the output number of node features + auto num_node_features_input = num_node_features; + if(nodes_update_block->GetFunctionBlock()->GetTensorShape(nodes_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_node_features) { + num_node_features = nodes_update_block->GetFunctionBlock()->GetTensorShape(nodes_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + fGC+="\n\nnamespace Global_Update{\nstruct Session {\n"; + // Generating Infer function definition for Global Update function + Update_Input = {{1, num_global_features}}; + globals_update_block->Initialize(); + globals_update_block->AddInputTensors(Update_Input); + fGC+=globals_update_block->GenerateModel(fName,next_pos); + next_pos = globals_update_block->GetFunctionBlock()->WriteInitializedTensorsToFile(fName+".dat"); + fGC+="};\n}\n"; + + // we need to correct the output number of global features + auto num_global_features_input = num_global_features; + // global features are in shape[1] + if(globals_update_block->GetFunctionBlock()->GetTensorShape(globals_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1] != num_global_features) { + num_global_features = globals_update_block->GetFunctionBlock()->GetTensorShape(globals_update_block->GetFunctionBlock()->GetOutputTensorNames()[0])[1]; + } + + + // computing inplace on input graph + fGC += "struct Session {\n"; + fGC += "\n// Instantiating session objects for graph components\n"; + fGC += "Edge_Update::Session edge_update;\n"; + fGC += "Node_Update::Session node_update;\n"; + fGC += "Global_Update::Session global_update;\n\n"; + + // create temp vector for edge and node updates + fGC += "std::vector fEdgeUpdates = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_edge_features) + ");"; + fGC += "\nstd::vector fNodeUpdates = std::vector(" + std::to_string(num_nodes) + "*" + std::to_string(num_node_features) + ");\n"; + + fGC += "\n// input vectors for edge update\n"; + fGC += "std::vector fEdgeInputs = std::vector(" + std::to_string(num_edges) + "*" + std::to_string(num_edge_features_input) + ");\n"; + + fGC += "\n// input vectors for node update\n"; + fGC += "std::vector fNodeInputs = std::vector(" + std::to_string(num_nodes) + "*" + std::to_string(num_node_features_input) + ");\n"; + + fGC += "\nvoid infer(TMVA::Experimental::SOFIE::GNN_Data& input_graph){\n"; + + // computing updated edge attributes + fGC += "\n// --- Edge Update ---\n"; + + std::string e_size_input = std::to_string(num_edge_features_input); + fGC += "for (int k = 0; k < " + std::to_string(num_edges) + "; k++) { \n"; + fGC += " std::copy(input_graph.edge_data.GetData() + k * " + e_size_input + + ", input_graph.edge_data.GetData() + (k + 1) * " + e_size_input + + ", fEdgeInputs.begin() + k * " + e_size_input + ");\n"; + fGC += "}\n"; + + fGC += "fEdgeUpdates = " + edges_update_block->Generate({"fEdgeInputs.data()"}) + "\n"; + + if(num_edge_features != num_edge_features_input) { + fGC += "\n// resize edge graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.edge_data = input_graph.edge_data.Resize({"+std::to_string(num_edges)+", "+std::to_string(num_edge_features)+"});\n"; + } + // copy output + fGC += "\nfor (int k = 0; k < " + std::to_string(num_edges) + "; k++) { \n"; + fGC += " std::copy(fEdgeUpdates.begin()+ k * " + std::to_string(num_edge_features) + ", fEdgeUpdates.begin()+ (k+1) * " + std::to_string(num_edge_features) + + ",input_graph.edge_data.GetData() + k * " + std::to_string(num_edge_features)+ ");\n"; + fGC += "}\n"; + fGC += "\n"; + + // computing updated node attributes + std::string n_size_input = std::to_string(num_node_features_input); + fGC += "\n// --- Node Update ---"; + fGC += "\nfor (int k = 0; k < " + std::to_string(num_nodes) + "; k++) { \n"; + fGC += " std::copy(input_graph.node_data.GetData() + k * " + n_size_input + + ", input_graph.node_data.GetData() + (k + 1) * " + n_size_input + + ", fNodeInputs.begin() + k * " + n_size_input + ");\n"; + fGC += "}\n"; + + fGC+="\nfNodeUpdates = "; + fGC+=nodes_update_block->Generate({"fNodeInputs.data()"}); // computing updated node attributes + fGC+="\n"; + + if(num_node_features != num_node_features_input) { + fGC += "\n// resize node graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.node_data = input_graph.node_data.Resize({"+std::to_string(num_nodes)+", "+std::to_string(num_node_features)+"});\n"; + } + // copy output + fGC += "\nfor (int k = 0; k < " + std::to_string(num_nodes) + "; k++) { \n"; + fGC += " std::copy(fNodeUpdates.begin()+ k * " + std::to_string(num_node_features) + ", fNodeUpdates.begin() + (k+1) * " + std::to_string(num_node_features) + + ",input_graph.node_data.GetData() + k * " + std::to_string(num_node_features)+ ");\n"; + fGC += "}\n"; + fGC += "\n"; + + // computing updated global attributes + fGC += "\n// --- Global Update ---\n"; + fGC += "std::vector Global_Data = "; + fGC += globals_update_block->Generate({"input_graph.global_data.GetData()"}); + fGC += "\n"; + + if(num_global_features != num_global_features_input) { + fGC += "\n// resize global graph data since output feature size is not equal to input size\n"; + fGC+="input_graph.global_data = input_graph.global_data.Resize({"+std::to_string(num_global_features)+"});\n"; + } + + fGC += "\nstd::copy(Global_Data.begin(), Global_Data.end(), input_graph.global_data.GetData());"; + fGC += "\n"; + + fGC += ("}\n};\n} //TMVA_SOFIE_" + fName + "\n"); + fGC += "\n#endif // TMVA_SOFIE_" + hgname + "\n"; + +} + +}//SOFIE +}//Experimental +}//TMVA diff --git a/tmva/sofie/src/SOFIE_common.cxx b/tmva/sofie/src/SOFIE_common.cxx index 6a6ee285f65f7..58e99dd43a476 100644 --- a/tmva/sofie/src/SOFIE_common.cxx +++ b/tmva/sofie/src/SOFIE_common.cxx @@ -1,7 +1,6 @@ #include "TMVA/SOFIE_common.hxx" #include #include -#include #include namespace TMVA{ @@ -17,6 +16,7 @@ std::vector ConvertShapeToDim(std::vector shape){ } std::size_t ConvertShapeToLength(std::vector shape){ + // Empty shape represent scalar values, so we return a length=1 std::size_t fLength = 1; for (auto& dim: shape) fLength *= dim; return fLength; diff --git a/tmva/sofie/test/CMakeLists.txt b/tmva/sofie/test/CMakeLists.txt index d13e79504fde7..6f1d1f627d318 100644 --- a/tmva/sofie/test/CMakeLists.txt +++ b/tmva/sofie/test/CMakeLists.txt @@ -16,16 +16,32 @@ if (NOT ONNX_MODELS_DIR) set(ONNX_MODELS_DIR input_models) endif() +#Finding .onnx files to be parsed and creating the appropriate code to +# parse all file. It is much faster to combine all parsing in a single executable +# which will avoid initialization time (especially when using ROOT) +set(CAPTURE_STR "EmitModel( \"@1\", \"@2\");") +set(ALL_CAPTURES "") +# Finding .onnx files to be parsed and creating the appropriate command +file(GLOB ONNX_FILES "${ONNX_MODELS_DIR}/*.onnx") +foreach(onnx_file ${ONNX_FILES}) + get_filename_component(fname ${onnx_file} NAME_WE) + get_filename_component(fdir ${onnx_file} DIRECTORY) + string(REPLACE "@1" ${onnx_file} cap ${CAPTURE_STR}) + string(REPLACE "@2" ${fname} cap ${cap}) + list(APPEND ALL_CAPTURES ${cap}) +endforeach() +string(REPLACE ";" ";\n" EMIT_CAPTURES "${ALL_CAPTURES}") +configure_file(EmitFromONNX.cxx.in EmitFromONNX_all.cxx @ONLY) +configure_file(EmitFromRoot.cxx.in EmitFromRoot_all.cxx @ONLY) + add_executable(emitFromONNX - EmitFromONNX.cxx + EmitFromONNX_all.cxx ) target_include_directories(emitFromONNX PRIVATE ${CMAKE_SOURCE_DIR}/tmva/sofie/inc ${SOFIE_PARSERS_DIR}/inc ${CMAKE_SOURCE_DIR}/tmva/inc ${CMAKE_CURRENT_BINARY_DIR} # this is for the protobuf headerfile - ${CMAKE_SOURCE_DIR}/core/foundation/inc - ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h ) target_link_libraries(emitFromONNX ${Protobuf_LIBRARIES} ROOTTMVASofie ROOTTMVASofieParser) @@ -37,18 +53,11 @@ target_compile_options(emitFromONNX PRIVATE -Wno-unused-parameter -Wno-array-bou add_custom_target(SofieCompileModels_ONNX) add_dependencies(SofieCompileModels_ONNX emitFromONNX) -# Finding .onnx files to be compiled and creating the appropriate command -file(GLOB ONNX_FILES "${ONNX_MODELS_DIR}/*.onnx") -# Finding .onnx files to be compiled only from ONNX -file(GLOB ONNX_ONLY_FILES "${ONNX_MODELS_DIR}/onnx/*.onnx") -foreach(onnx_file ${ONNX_FILES} ${ONNX_ONLY_FILES}) - get_filename_component(fname ${onnx_file} NAME_WE) - get_filename_component(fdir ${onnx_file} DIRECTORY) - add_custom_command(TARGET SofieCompileModels_ONNX POST_BUILD + +add_custom_command(TARGET SofieCompileModels_ONNX POST_BUILD COMMAND ${CMAKE_COMMAND} -E env ROOTIGNOREPREFIX=1 ./emitFromONNX ${onnx_file} ${CMAKE_CURRENT_BINARY_DIR}/${fname} - USES_TERMINAL - ) -endforeach() + USES_TERMINAL ) + # Creating a Google Test if (tmva-cpu) # we need BLAS for compiling the models @@ -65,16 +74,15 @@ add_dependencies(TestCustomModelsFromONNX SofieCompileModels_ONNX) endif() #For testing serialisation of RModel object + add_executable(emitFromROOT - EmitFromRoot.cxx + EmitFromRoot_all.cxx ) target_include_directories(emitFromROOT PRIVATE ${CMAKE_SOURCE_DIR}/tmva/sofie/inc ${SOFIE_PARSERS_DIR}/inc ${CMAKE_SOURCE_DIR}/tmva/inc ${CMAKE_CURRENT_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/core/foundation/inc - ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h ) target_link_libraries(emitFromROOT ${Protobuf_LIBRARIES} ROOTTMVASofie ROOTTMVASofieParser) set_target_properties(emitFromROOT PROPERTIES POSITION_INDEPENDENT_CODE TRUE) @@ -89,16 +97,10 @@ if (runtime_cxxmodules) else() add_dependencies(SofieCompileModels_ROOT emitFromROOT onepcm) endif() -# Finding .onnx files to be parsed and creating the appropriate command -file(GLOB ONNX_FILES "${ONNX_MODELS_DIR}/*.onnx") -foreach(onnx_file ${ONNX_FILES}) - get_filename_component(fname ${onnx_file} NAME_WE) - get_filename_component(fdir ${onnx_file} DIRECTORY) - add_custom_command(TARGET SofieCompileModels_ROOT POST_BUILD - COMMAND ${CMAKE_COMMAND} -E env ROOTIGNOREPREFIX=1 ./emitFromROOT ${onnx_file} ${CMAKE_CURRENT_BINARY_DIR}/${fname} - USES_TERMINAL - ) -endforeach() + +add_custom_command(TARGET SofieCompileModels_ROOT POST_BUILD +COMMAND ${CMAKE_COMMAND} -E env ROOTIGNOREPREFIX=1 ./emitFromROOT + USES_TERMINAL ) # Creating a Google Test for Serialisation of RModel if (tmva-cpu) @@ -136,3 +138,36 @@ if (tmva-cpu) ) endif() endif() + +add_executable(emitGNN + GNN/EmitGNN.cxx + ${CMAKE_SOURCE_DIR}/tmva/sofie/src/RModel_GNN.cxx + ${CMAKE_SOURCE_DIR}/tmva/sofie/src/SOFIE_common.cxx +) +target_include_directories(emitGNN PRIVATE + ${CMAKE_SOURCE_DIR}/tmva/sofie/inc + ${CMAKE_SOURCE_DIR}/tmva/inc + ${CMAKE_SOURCE_DIR}/core/foundation/inc + ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h +) +target_link_libraries(emitGNN ROOTTMVASofie) +set_target_properties(emitGNN PROPERTIES POSITION_INDEPENDENT_CODE TRUE) +## silence protobuf warnings seen in version 3.0 and 3.6. Not needed from protobuf version 3.17 +target_compile_options(emitGNN PRIVATE -Wno-unused-parameter -Wno-array-bounds) + + +add_executable(emitGraphIndependent + GNN/EmitGraphIndependent.cxx + ${CMAKE_SOURCE_DIR}/tmva/sofie/src/RModel_GraphIndependent.cxx + ${CMAKE_SOURCE_DIR}/tmva/sofie/src/SOFIE_common.cxx +) +target_include_directories(emitGraphIndependent PRIVATE + ${CMAKE_SOURCE_DIR}/tmva/sofie/inc + ${CMAKE_SOURCE_DIR}/tmva/inc + ${CMAKE_SOURCE_DIR}/core/foundation/inc + ${CMAKE_BINARY_DIR}/ginclude # this is for RConfigure.h +) +target_link_libraries(emitGraphIndependent ROOTTMVASofie) +set_target_properties(emitGraphIndependent PROPERTIES POSITION_INDEPENDENT_CODE TRUE) +## silence protobuf warnings seen in version 3.0 and 3.6. Not needed from protobuf version 3.17 +target_compile_options(emitGraphIndependent PRIVATE -Wno-unused-parameter -Wno-array-bounds) diff --git a/tmva/sofie/test/EmitFromONNX.cxx b/tmva/sofie/test/EmitFromONNX.cxx.in similarity index 74% rename from tmva/sofie/test/EmitFromONNX.cxx rename to tmva/sofie/test/EmitFromONNX.cxx.in index d2a2a16af6afc..79ba3e7eef8fd 100644 --- a/tmva/sofie/test/EmitFromONNX.cxx +++ b/tmva/sofie/test/EmitFromONNX.cxx.in @@ -5,24 +5,25 @@ // This program is automatically run when the target 'TestCustomModelsFromONNX' is built. // Usage example: $./sofiec indir/mymodel.onnx outdir/myname.hxx -#include - +#include "TMVA/RModel_Base.hxx" #include "TMVA/RModel.hxx" #include "TMVA/RModelParser_ONNX.hxx" using namespace TMVA::Experimental::SOFIE; -int main(int argc, char *argv[]){ - if (argc < 2) { - std::cerr << "ERROR: missing input file\n"; - return -1; - } +int EmitModel(std::string filename, std::string outname) { - std::string outname=argv[2]; RModelParser_ONNX parser; - RModel model = parser.Parse(argv[1]); + RModel model = parser.Parse(filename); model.Generate(); model.OutputGenerated(outname+"_FromONNX.hxx"); return 0; } + +int main(int argc, char *argv[]){ + +@EMIT_CAPTURES@ ; + +} + diff --git a/tmva/sofie/test/EmitFromRoot.cxx b/tmva/sofie/test/EmitFromRoot.cxx.in similarity index 84% rename from tmva/sofie/test/EmitFromRoot.cxx rename to tmva/sofie/test/EmitFromRoot.cxx.in index 8431ee045ce63..9689485da92cd 100644 --- a/tmva/sofie/test/EmitFromRoot.cxx +++ b/tmva/sofie/test/EmitFromRoot.cxx.in @@ -6,22 +6,16 @@ // generates the required .hxx file after reading a written // ROOT file which stores the object of the RModel class. -#include - #include "TMVA/RModel.hxx" #include "TMVA/RModelParser_ONNX.hxx" #include "TFile.h" using namespace TMVA::Experimental::SOFIE; -int main(int argc, char *argv[]){ - if (argc < 2) { - std::cerr << "[ERROR]: Missing ONNX input file\n"; - return -1; - } - std::string outname=argv[2]; +int EmitModel(std::string inputfile, std::string outname){ + RModelParser_ONNX parser; - RModel model = parser.Parse(argv[1]); + RModel model = parser.Parse(inputfile); TFile fileWrite((outname+"_FromROOT.root").c_str(),"RECREATE"); model.Write("model"); fileWrite.Close(); @@ -33,9 +27,9 @@ int main(int argc, char *argv[]){ // use Session and weight file for linear model with large weights if (outname.find("Linear_32") != std::string::npos) return 0; // skip test if (outname.find("Linear_64") != std::string::npos) return 0; // skip test - modelPtr->Generate(); + modelPtr->Generate(Options::kRootBinaryWeightFile); } - else if (outname.find("LinearWith") != std::string::npos){ + else if (outname.find("LinearWith") != std::string::npos) { // in this case we don't write session class but not weight file modelPtr->Generate(Options::kNoWeightFile); } @@ -46,3 +40,9 @@ int main(int argc, char *argv[]){ modelPtr->OutputGenerated(outname+"_FromROOT.hxx"); return 0; } + +int main(int argc, char *argv[]){ + +@EMIT_CAPTURES@ ; + +} diff --git a/tmva/sofie/test/GNN/EmitGNN.cxx b/tmva/sofie/test/GNN/EmitGNN.cxx new file mode 100644 index 0000000000000..ef81afbd193c0 --- /dev/null +++ b/tmva/sofie/test/GNN/EmitGNN.cxx @@ -0,0 +1,100 @@ +// Author: Sanjiban Sengupta +// Description: +// This program generates a RModel_GNN for testing + +#include "TMVA/RModel_GNN.hxx" +#include "TMVA/FunctionList.hxx" +#include "TMVA/SOFIE_common.hxx" + + +using namespace TMVA::Experimental::SOFIE; + +int main(){ + + GNN_Init init; + init.num_nodes=2; + init.edges = {{1,0}}; + init.num_node_features = 2; + init.num_edge_features = 2; + init.num_global_features=2; + init.filename = "Test_Graph"; + std::unique_ptr func; + func.reset(new RFunction_MLP(FunctionTarget::EDGES, 1, Activation::RELU, 1)); + std::vector kernel_tensors = {"graph_network/edge_block/linear/w:0"}; + std::vector bias_tensors = {"graph_network/edge_block/linear/b:0"}; + std::vector> weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.edges_update_block = std::move(func); + func.reset(new RFunction_MLP(FunctionTarget::NODES, 1, Activation::RELU, 1)); + kernel_tensors = {"graph_network/node_block/linear/w:0"}; + bias_tensors = {"graph_network/node_block/linear/b:0"}; + weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.nodes_update_block = std::move(func); + func.reset(new RFunction_MLP(FunctionTarget::GLOBALS, 1, Activation::RELU, 1)); + kernel_tensors = {"graph_network/global_block/linear/w:0"}; + bias_tensors = {"graph_network/global_block/linear/b:0"}; + weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.globals_update_block = std::move(func); + std::unique_ptr func_agg; + func_agg.reset(new RFunction_Sum()); + init.node_global_agg_block = std::move(func_agg); + func_agg.reset(new RFunction_Sum()); + init.edge_global_agg_block = std::move(func_agg); + func_agg.reset(new RFunction_Sum()); + init.edge_node_agg_block = std::move(func_agg); + float arr[] = {-0.11413302, 0.49974972, + -0.15535775, 0.06823446, + -0.23475496, -0.38286394, + 0.16671045, 0.1850846 , + -0.4561586 , 0.3438921 , + 0.10795765, 0.49663377, + -0.6825379 , 0.25719026, + 0.24045151, 0.13871197}; + + std::shared_ptr data_0(malloc(16 * sizeof(float)), free); + std::memcpy(data_0.get(), arr, 16 * sizeof(float)); + init.edges_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/edge_block/linear/w:0",ETensorType::FLOAT,{8,2},data_0); + float arr_b[2] = {0,0}; + std::shared_ptr data_1(malloc(2 * sizeof(float)), free); + std::memcpy(data_1.get(), arr_b, 2 * sizeof(float)); + init.edges_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/edge_block/linear/b:0",ETensorType::FLOAT,{2},data_1); + + + float arr_3[] = {-0.2939381 , 0.29374102, + 0.39915594, 0.22476648, + 0.07345466, -0.14384857, + 0.15938309, 0.19942378, + -0.14101209, -0.57209873, + -0.26913098, 0.5071538 }; + std::shared_ptr data_6(malloc(12 * sizeof(float)), free); + std::memcpy(data_6.get(), arr_3, 12* sizeof(float)); + init.globals_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/global_block/linear/w:0",ETensorType::FLOAT,{6,2},data_6); + std::shared_ptr data_7(malloc(2 * sizeof(float)), free); + std::memcpy(data_7.get(), arr_b, 2 * sizeof(float)); + init.globals_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/global_block/linear/b:0",ETensorType::FLOAT,{2},data_7); + + float arr_4[] = {-0.49379408, 0.64651597, + -0.48153368, 0.04505178, + 0.36477658, 0.40089235, + -0.26732066, -0.40632117, + 0.61156213, 0.563861 , + 0.28957435, 0.46537283}; + std::shared_ptr data_8(malloc(12 * sizeof(float)), free); + std::memcpy(data_8.get(), arr_4, 12 * sizeof(float)); + init.nodes_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/node_block/linear/w:0",ETensorType::FLOAT,{6,2},data_8); + std::shared_ptr data_9(malloc(2 * sizeof(float)), free); + std::memcpy(data_9.get(), arr_b, 2 * sizeof(float)); + init.nodes_update_block->GetFunctionBlock()->AddInitializedTensor("graph_network/node_block/linear/b:0",ETensorType::FLOAT,{2},data_9); + + RModel_GNN model(init); + model.AddBlasRoutines({"Gemm"}); + model.Generate(); + model.OutputGenerated(); + + func.reset(); + func_agg.reset(); + + return 0; +} diff --git a/tmva/sofie/test/GNN/EmitGraphIndependent.cxx b/tmva/sofie/test/GNN/EmitGraphIndependent.cxx new file mode 100644 index 0000000000000..8467a29cfb8eb --- /dev/null +++ b/tmva/sofie/test/GNN/EmitGraphIndependent.cxx @@ -0,0 +1,79 @@ +// Author: Sanjiban Sengupta +// Description: +// This program generates a RModel_GraphIndependent for testing + +#include "TMVA/RModel_GraphIndependent.hxx" +#include "TMVA/FunctionList.hxx" +#include "TMVA/SOFIE_common.hxx" + + +using namespace TMVA::Experimental::SOFIE; + +int main(int argc, char *argv[]){ + + GraphIndependent_Init init; + init.num_nodes=2; + init.edges = {{1,0}}; + init.num_node_features = 2; + init.num_edge_features = 2; + init.num_global_features=2; + init.filename = "Test_GraphIndependent"; + std::unique_ptr func; + func.reset(new RFunction_MLP(FunctionTarget::EDGES, 1, Activation::RELU, 1, GraphType::GraphIndependent)); + std::vector kernel_tensors = {"graph_independent/edge_model/linear/w:0"}; + std::vector bias_tensors = {"graph_independent/edge_model/linear/b:0"}; + std::vector> weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.edges_update_block = std::move(func); + func.reset(new RFunction_MLP(FunctionTarget::NODES, 1, Activation::RELU, 1, GraphType::GraphIndependent)); + kernel_tensors = {"graph_independent/node_model/linear/w:0"}; + bias_tensors = {"graph_independent/node_model/linear/b:0"}; + weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.nodes_update_block = std::move(func); + func.reset(new RFunction_MLP(FunctionTarget::GLOBALS, 1, Activation::RELU, 1, GraphType::GraphIndependent)); + kernel_tensors = {"graph_independent/global_model/linear/w:0"}; + bias_tensors = {"graph_independent/global_model/linear/b:0"}; + weight_tensors = {kernel_tensors,bias_tensors}; + func->AddInitializedTensors(weight_tensors); + init.globals_update_block = std::move(func); + + float arr[] = { 0.41437718, -0.9389465 , + -0.5776741 , -0.10654829}; + + std::shared_ptr data_0(malloc(4 * sizeof(float)), free); + std::memcpy(data_0.get(), arr, 4 * sizeof(float)); + init.edges_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/edge_model/linear/w:0",ETensorType::FLOAT,{2,2},data_0); + float arr_b[2] = {0,0}; + std::shared_ptr data_1(malloc(2 * sizeof(float)), free); + std::memcpy(data_1.get(), arr_b, 2 * sizeof(float)); + init.edges_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/edge_model/linear/b:0",ETensorType::FLOAT,{2},data_1); + + + float arr_3[] = { 0.26933208, 0.16284496, + -0.23531358, -0.08090801}; + std::shared_ptr data_6(malloc(4 * sizeof(float)), free); + std::memcpy(data_6.get(), arr_3, 4* sizeof(float)); + init.globals_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/global_model/linear/w:0",ETensorType::FLOAT,{2,2},data_6); + std::shared_ptr data_7(malloc(2 * sizeof(float)), free); + std::memcpy(data_7.get(), arr_b, 2 * sizeof(float)); + init.globals_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/global_model/linear/b:0",ETensorType::FLOAT,{2},data_7); + + float arr_4[] = {0.14061868, 0.30305472, + 0.99493086, 0.36049494}; + std::shared_ptr data_8(malloc(4 * sizeof(float)), free); + std::memcpy(data_8.get(), arr_4, 4 * sizeof(float)); + init.nodes_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/node_model/linear/w:0",ETensorType::FLOAT,{2,2},data_8); + std::shared_ptr data_9(malloc(2 * sizeof(float)), free); + std::memcpy(data_9.get(), arr_b, 2 * sizeof(float)); + init.nodes_update_block->GetFunctionBlock()->AddInitializedTensor("graph_independent/node_model/linear/b:0",ETensorType::FLOAT,{2},data_9); + + RModel_GraphIndependent model(init); + model.AddBlasRoutines({"Gemm"}); + model.Generate(); + model.OutputGenerated(); + + func.reset(); + + return 0; +} diff --git a/tmva/sofie/test/TestCustomModelsFromONNX.cxx b/tmva/sofie/test/TestCustomModelsFromONNX.cxx index 87158a88f1e4b..1538ea69b34d7 100644 --- a/tmva/sofie/test/TestCustomModelsFromONNX.cxx +++ b/tmva/sofie/test/TestCustomModelsFromONNX.cxx @@ -42,6 +42,9 @@ #include "Tanh_FromONNX.hxx" #include "input_models/references/Tanh.ref.hxx" +#include "Erf_FromONNX.hxx" +#include "input_models/references/Erf.ref.hxx" + #include "LinearWithSigmoid_FromONNX.hxx" #include "input_models/references/LinearWithSigmoid.ref.hxx" @@ -239,6 +242,21 @@ #include "GatherNegativeIndices_FromONNX.hxx" #include "input_models/references/GatherNegativeIndices.ref.hxx" +#include "Slice_FromONNX.hxx" +#include "input_models/references/Slice.ref.hxx" + +#include "Slice_Default_Axis_FromONNX.hxx" +#include "input_models/references/Slice_Default_Axis.ref.hxx" + +#include "Slice_Default_Steps_FromONNX.hxx" +#include "input_models/references/Slice_Default_Steps.ref.hxx" + +#include "Slice_Neg_FromONNX.hxx" +#include "input_models/references/Slice_Neg.ref.hxx" + +#include "Log_FromONNX.hxx" +#include "input_models/references/Log.ref.hxx" + #include "gtest/gtest.h" constexpr float DEFAULT_TOLERANCE = 1e-3f; @@ -264,6 +282,26 @@ TEST(ONNX, Linear16) } } +/*TEST(ONNX, Linear32RootFeature) +{ + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + + // Preparing the standard all-ones input + std::vector input(3200); + std::fill_n(input.data(), input.size(), 1.0f); + TMVA_SOFIE_Linear32RootFeacture::Session s("Linear_32_FromONNX.root"); + std::vector output = s.infer(input.data()); + + // Checking output size + EXPECT_EQ(output.size(), sizeof(Linear_32_ExpectedOutput::all_ones) / sizeof(float)); + + float *correct = Linear_32_ExpectedOutput::all_ones; + + // Checking every output value, one by one + for (size_t i = 0; i < output.size(); ++i) { + EXPECT_LE(std::abs(output[i] - correct[i]), TOLERANCE); + } +}*/ TEST(ONNX, Linear32) { @@ -507,6 +545,55 @@ TEST(ONNX, Tanh) } } +TEST(ONNX, Erf) +{ + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + + // Preparing the random input + std::vector input({ + -1.0412, 0.1918, 0.9985, -0.5959, 0.6842, -2.4718, 0.1804, 0.6851, + 1.5646, -1.4981, 0.4248, -0.8504 + }); + + TMVA_SOFIE_Erf::Session s("Erf_FromONNX.dat"); + + std::vector output = s.infer(input.data()); + + // Checking output size + EXPECT_EQ(output.size(), sizeof(Erf_ExpectedOutput::outputs) / sizeof(float)); + + float *correct = Erf_ExpectedOutput::outputs; + + // Checking every output value, one by one + for (size_t i = 0; i < output.size(); ++i) { + EXPECT_LE(std::abs(output[i] - correct[i]), TOLERANCE); + } +} + +TEST(ONNX, Log) +{ + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + + // Preparing the random input + std::vector input({ + 1, 2, 3, 4 + }); + + TMVA_SOFIE_Log::Session s("Log_FromONNX.dat"); + + std::vector output = s.infer(input.data()); + + // Checking output size + EXPECT_EQ(output.size(), sizeof(Log_ExpectedOutput::outputs) / sizeof(float)); + + float *correct = Log_ExpectedOutput::outputs; + + // Checking every output value, one by one + for (size_t i = 0; i < output.size(); ++i) { + EXPECT_LE(std::abs(output[i] - correct[i]), TOLERANCE); + } +} + TEST(ONNX, LinearWithLeakyRelu) { constexpr float TOLERANCE = 1; @@ -1022,19 +1109,18 @@ TEST(ONNX, Shape){ std::vector input({ 1, 2 }); - + TMVA_SOFIE_Shape::Session s("Shape_FromONNX.dat"); auto output = s.infer(input.data()); // Checking output size EXPECT_EQ(output.size(), sizeof(Shape_ExpectedOutput::outputs) / sizeof(float)); - + int *correct = Shape_ExpectedOutput::outputs; // Checking every output value, one by one for (size_t i = 0; i < output.size(); ++i) { EXPECT_LE(std::abs(output[i] - correct[i]), TOLERANCE); } - } TEST(ONNX, RNNBatchwise) @@ -2306,3 +2392,67 @@ TEST(ONNX, GatherNegativeIndices) { EXPECT_LE(std::abs(output[i] - correct[i]), TOLERANCE); } } + +TEST(ONNX, Slice) { + constexpr float TOLERANCE = DEFAULT_TOLERANCE; + + std::vector input = Slice::input; + TMVA_SOFIE_Slice::Session s("Slice.dat"); + std::vector output(s.infer(input.data())); + + EXPECT_EQ(output.size(), sizeof(Slice::output) / sizeof(float)); + float *correct = Slice::output; + + for (size_t i=0; i input = Slice_Default_Axis::input; + TMVA_SOFIE_Slice_Default_Axis::Session s("Slice_Default_Axis.dat"); + std::vector output(s.infer(input.data())); + + EXPECT_EQ(output.size(), sizeof(Slice_Default_Axis::output) / sizeof(float)); + float *correct = Slice_Default_Axis::output; + + for (size_t i=0; i input = Slice_Default_Steps::input; + TMVA_SOFIE_Slice_Default_Steps::Session s("Slice_Default_Steps.dat"); + std::vector output(s.infer(input.data())); + + EXPECT_EQ(output.size(), sizeof(Slice_Default_Steps::output) / sizeof(float)); + float *correct = Slice_Default_Steps::output; + + for (size_t i=0; i input = Slice_Neg::input; + TMVA_SOFIE_Slice_Neg::Session s("Slice_Neg.dat"); + std::vector output(s.infer(input.data())); + + EXPECT_EQ(output.size(), sizeof(Slice_Neg::output) / sizeof(float)); + float *correct = Slice_Neg::output; + + for (size_t i=0; i input(1600); std::fill_n(input.data(), input.size(), 1.0f); - TMVA_SOFIE_Linear_16::Session s("Linear_16_FromROOT.dat"); + TMVA_SOFIE_Linear_16::Session s("Linear_16_FromROOT.root"); std::vector output = s.infer(input.data()); // Testing the actual and expected output sizes diff --git a/tmva/sofie/test/TestSofieModels.cxx b/tmva/sofie/test/TestSofieModels.cxx index 72ab8275317d1..b269e1ab2e8fa 100644 --- a/tmva/sofie/test/TestSofieModels.cxx +++ b/tmva/sofie/test/TestSofieModels.cxx @@ -11,6 +11,7 @@ #include "TMVA/RModelParser_ONNX.hxx" #include "gtest/gtest.h" +#define USE_ONNXSIM bool verbose = true; int sessionId = 0; @@ -136,7 +137,8 @@ void TestConv( std::string type, int nbatches, bool useBN = false, int ngroups = printf("executing %s\n", command.c_str()); gSystem->Exec(command.c_str()); - // some model needs some semplifications + // some model needs some simplifications +#ifdef USE_ONNXSIM if (usePool == 2) { printf("simplify onnx model using onnxsim tool \n"); std::string cmd = "python3 -m onnxsim " + modelName + ".onnx " + modelName + ".onnx"; @@ -147,6 +149,7 @@ void TestConv( std::string type, int nbatches, bool useBN = false, int ngroups = return; } } +#endif ExecuteSofieParser(modelName); @@ -203,6 +206,7 @@ void TestRecurrent(std::string type, int nbatches, int inputSize = 5, int seqSiz printf("executing %s\n", command.c_str()); gSystem->Exec(command.c_str()); // need to simplify obtained recurrent ONNX model +#ifdef USE_ONNXSIM printf("simplify onnx model using onnxsim tool \n"); std::string cmd = "python3 -m onnxsim " + modelName + ".onnx " + modelName + ".onnx"; int ret = gSystem->Exec(cmd.c_str()); @@ -211,6 +215,7 @@ void TestRecurrent(std::string type, int nbatches, int inputSize = 5, int seqSiz GTEST_SKIP(); return; } +#endif ExecuteSofieParser(modelName); diff --git a/tmva/sofie/test/input_models/Erf.onnx b/tmva/sofie/test/input_models/Erf.onnx new file mode 100644 index 0000000000000..e0de14544c370 --- /dev/null +++ b/tmva/sofie/test/input_models/Erf.onnx @@ -0,0 +1,11 @@ +pytorch1.13.1:T + + onnx::Erf_01/Erf"Erf torch_jitZ + onnx::Erf_0 + + + b +1 + + + B \ No newline at end of file diff --git a/tmva/sofie/test/input_models/onnx/ExpandDiffSize.onnx b/tmva/sofie/test/input_models/ExpandDiffSize.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/ExpandDiffSize.onnx rename to tmva/sofie/test/input_models/ExpandDiffSize.onnx diff --git a/tmva/sofie/test/input_models/onnx/ExpandSameSize.onnx b/tmva/sofie/test/input_models/ExpandSameSize.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/ExpandSameSize.onnx rename to tmva/sofie/test/input_models/ExpandSameSize.onnx diff --git a/tmva/sofie/test/input_models/onnx/Gather2d.onnx b/tmva/sofie/test/input_models/Gather2d.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/Gather2d.onnx rename to tmva/sofie/test/input_models/Gather2d.onnx diff --git a/tmva/sofie/test/input_models/onnx/GatherAxis0.onnx b/tmva/sofie/test/input_models/GatherAxis0.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/GatherAxis0.onnx rename to tmva/sofie/test/input_models/GatherAxis0.onnx diff --git a/tmva/sofie/test/input_models/onnx/GatherAxis1.onnx b/tmva/sofie/test/input_models/GatherAxis1.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/GatherAxis1.onnx rename to tmva/sofie/test/input_models/GatherAxis1.onnx diff --git a/tmva/sofie/test/input_models/onnx/GatherAxis2.onnx b/tmva/sofie/test/input_models/GatherAxis2.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/GatherAxis2.onnx rename to tmva/sofie/test/input_models/GatherAxis2.onnx diff --git a/tmva/sofie/test/input_models/onnx/GatherAxis3.onnx b/tmva/sofie/test/input_models/GatherAxis3.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/GatherAxis3.onnx rename to tmva/sofie/test/input_models/GatherAxis3.onnx diff --git a/tmva/sofie/test/input_models/onnx/GatherNegativeIndices.onnx b/tmva/sofie/test/input_models/GatherNegativeIndices.onnx similarity index 100% rename from tmva/sofie/test/input_models/onnx/GatherNegativeIndices.onnx rename to tmva/sofie/test/input_models/GatherNegativeIndices.onnx diff --git a/tmva/sofie/test/input_models/Log.onnx b/tmva/sofie/test/input_models/Log.onnx new file mode 100644 index 0000000000000..a1bfce7ba847b --- /dev/null +++ b/tmva/sofie/test/input_models/Log.onnx @@ -0,0 +1,11 @@ +pytorch1.13.1:T + + onnx::Log_01/Log"Log torch_jitZ + onnx::Log_0 + + +b +1 + + +B \ No newline at end of file diff --git a/tmva/sofie/test/input_models/Slice.onnx b/tmva/sofie/test/input_models/Slice.onnx new file mode 100644 index 0000000000000..73d22ad40ba9b Binary files /dev/null and b/tmva/sofie/test/input_models/Slice.onnx differ diff --git a/tmva/sofie/test/input_models/Slice_Default_Axis.onnx b/tmva/sofie/test/input_models/Slice_Default_Axis.onnx new file mode 100644 index 0000000000000..d159e75eb4561 Binary files /dev/null and b/tmva/sofie/test/input_models/Slice_Default_Axis.onnx differ diff --git a/tmva/sofie/test/input_models/Slice_Default_Steps.onnx b/tmva/sofie/test/input_models/Slice_Default_Steps.onnx new file mode 100644 index 0000000000000..31a71b91236e1 Binary files /dev/null and b/tmva/sofie/test/input_models/Slice_Default_Steps.onnx differ diff --git a/tmva/sofie/test/input_models/Slice_Neg.onnx b/tmva/sofie/test/input_models/Slice_Neg.onnx new file mode 100644 index 0000000000000..d4bd677deaa1e Binary files /dev/null and b/tmva/sofie/test/input_models/Slice_Neg.onnx differ diff --git a/tmva/sofie/test/input_models/references/Erf.ref.hxx b/tmva/sofie/test/input_models/references/Erf.ref.hxx new file mode 100644 index 0000000000000..969192cce9889 --- /dev/null +++ b/tmva/sofie/test/input_models/references/Erf.ref.hxx @@ -0,0 +1,6 @@ +namespace Erf_ExpectedOutput{ + float outputs[] = { + -0.8591, 0.2138, 0.8421, -0.6006, 0.6668, -0.9995, 0.2014, 0.6674, + 0.9731, -0.9659, 0.4520, -0.7709 + }; +} // namespace Erf_ExpectedOutput \ No newline at end of file diff --git a/tmva/sofie/test/input_models/references/Log.ref.hxx b/tmva/sofie/test/input_models/references/Log.ref.hxx new file mode 100644 index 0000000000000..c6c6bfc8d9cd8 --- /dev/null +++ b/tmva/sofie/test/input_models/references/Log.ref.hxx @@ -0,0 +1,5 @@ +namespace Log_ExpectedOutput{ + float outputs[] = { + 0.0000, 0.6931, 1.0986, 1.3863 + }; +} // namespace Log_ExpectedOutput \ No newline at end of file diff --git a/tmva/sofie/test/input_models/references/ReduceMean.ref.hxx b/tmva/sofie/test/input_models/references/ReduceMean.ref.hxx index 053a34eebf527..9573e9dafd700 100644 --- a/tmva/sofie/test/input_models/references/ReduceMean.ref.hxx +++ b/tmva/sofie/test/input_models/references/ReduceMean.ref.hxx @@ -2,4 +2,4 @@ namespace ReduceMean_ExpectedOutput{ float output[] = { 5.0, 3.5, 3.5 }; -} // namespace Reduce_mean_ExpectedOutput \ No newline at end of file +} // namespace Reduce_mean_ExpectedOutput diff --git a/tmva/sofie/test/input_models/references/Slice.ref.hxx b/tmva/sofie/test/input_models/references/Slice.ref.hxx new file mode 100644 index 0000000000000..2435d9f87475e --- /dev/null +++ b/tmva/sofie/test/input_models/references/Slice.ref.hxx @@ -0,0 +1,4 @@ +namespace Slice{ + std::vector input = {0.16892381, -0.92159724, 0.64389044, 1.8697567, -0.8018371, -1.2693683, -2.093365, 1.8541908, -0.26340157, 0.9572909, 0.34671152, -1.7053558, -0.36417124, -2.3248599, -0.13200487, 2.3006496, 0.46386284, -2.1614797, -1.3742889, -0.40108228, -0.5511143, 0.35275838, -0.70952916, -0.41565117, 0.15577549, -0.8660324, -0.31523043, -1.43095, -0.62599516, -1.2735285, 0.74245137, 0.5401528, 1.2080778, 1.9445739, 0.5149316, 0.5683389, 1.6830992, -1.5869702, -0.9276118, -1.8208988, -0.52550256, 0.082054906, -1.0242202, 0.640871, -0.50823563, -0.13035983, -0.7713898, -1.1191769, 0.59570795, -0.06568418, -1.1858853, -0.085937336, 1.0237325, 0.32681447, -1.3751194, -0.28284678, -2.5314686, -0.36053106, 1.3408105, 0.46642232, -0.7184956, -0.5716407, -0.29177785, -0.29941186, -0.08443816, 0.054849386, -0.582217, 0.5512954, -1.2351213, 1.0514443, 0.2601373, 0.2979866, 1.1088992, -0.41123372, 1.2637646, 0.18790472, -0.16448955, -0.61922485, 0.72030956, -1.8054826, 2.739959, 1.515231, -1.1871477, -0.72046477, -0.49725538, -0.3599622, -2.4750538, -0.11285576, -1.1877617, -0.28629062, -0.5285716, 1.9786791, 2.2289317, -1.2789943, 1.3801973, -1.2113228, 0.16036053, -0.4714372, -1.1011868, 1.4348198, -0.15923952, 1.4626329, -0.7119883, 0.7440471, -1.8418623, 0.2772118, -1.2898343, 0.8006727, -0.47921824, 0.35204977, -0.23730946, -0.9184093, -0.44745374, 1.7422614, -1.2565724, 2.1967077, 0.31261623, -0.89821947, 1.8867549, 0.45231855, 0.8269342, 0.032707807, 0.025322068, 1.1288303, -1.4889454, 1.3964689, -1.5560274, -2.1302202, 0.7437271, 1.5007018, -1.3589836, -0.955504, 0.32147405, -1.4642475, -0.12817268, -0.030474393, 1.7738372, -0.38548046, -1.0957392, 1.3144948, 0.2697103, 1.8592813, 0.4777307, -0.6822411, 1.0501494, -0.87983644, -1.7267572, -0.3565207, -1.1379921, 0.7837413, 0.43398347, -0.30728853, -0.00026109006, -2.0815682, -1.1233135, 1.200373, 1.1735791, 0.80191934, -0.40204743, 0.60110134, 1.0514777, 0.71647906, 1.6119534, -0.7692411, -0.13165821, 1.076266, -0.58777434, 2.1273491, 0.5979284, -0.74737847, -0.16932407, -2.6000056, -0.18568534, -1.7186687, 0.38444906, -1.2328393, -1.166593, -0.749837, 0.6540508, -0.48843417, 0.105534576, -0.19924901, 0.39926815, 0.5520011, 0.78686863, -0.88527286, -0.39068756, 0.800181, 1.0539882, 0.82253766, -0.29349077, -0.95323867, -0.7239985, 0.4156427, 0.054603174, 0.46671128, 0.12290481, -0.9419718, -0.9518065, 0.6800318, 0.7334219, -1.4501665, 0.72601205, -0.009272683, -1.5702912, 2.6023812, -2.550537, 0.41290838, -0.0004515256, 0.7949585, 0.10386975, 1.9759881, -0.88904214, -0.20765586, 0.15403232, 0.090678096, -0.20895411, 0.9813557, 1.4583536, 0.08779892, 1.2651963, 0.34579468, 0.70687234, -1.1209601, 1.0646888, 0.20993355, 0.8882366, -0.4729274, -0.84709066, 0.2017297, -1.216628, 0.13039826, -0.61262065, 1.6169266, -0.1344048, -0.62242454, -0.6336179, 0.39012757, -0.826561, 0.008478365, 1.0602465, -1.0957131, -1.5973436, 1.2533009, 1.632353, -1.3100505, 0.51999503, -0.93459845, -1.1390812, 1.7102306, 0.08346745, 1.533848, -0.14334835, -1.1145127, -0.3083682, 0.08911435, 0.8270216, 0.66675997, -1.434103, 0.055906765, 0.18895805, -0.12091928, -0.07631843, -1.1277905, 0.56415355, -0.42068058, -0.43619972, -0.33488145, 0.46014947, 0.060450263, 0.6036779, 2.9487398, 0.14211768, -1.0608279, -0.5405822, 0.6854363, 0.051226616, -0.006617631, 0.27221313, 0.8168545, -1.4345047, 0.15883587, -1.0407009, -1.0776329, -1.4761366, 0.5077002, -0.18065284, -1.3203033, 1.2343279, 1.0788544, 0.95910555, -0.45996368, -1.1551211, -1.0516672, 0.75456, 0.5729106, 2.0468712, 0.95701927, -0.39028248, 0.7682253, -0.32310373, -0.25830054, 0.79827476, 0.64777404, -0.7693852, 0.13818592, -0.21603993, -0.13035135, 0.36271432, -1.3548849, 0.631066, -0.35979733, 2.012173, 0.5632781, -1.5559843, -1.0903429, -1.7130791, 0.6116188, -0.08399546, -0.28317407, 1.5286123, 0.34003162, 0.13574599, 1.8278462, 0.68333685, 1.5154774, 1.0113451, 2.3652873, -0.48571086, 0.16396068, 0.7627067, 0.64387697, 1.0480355, -1.8542932, 0.3824617, 0.2613266, -0.99953574, -0.51782006, -0.6157211, 1.3795184, 0.7554518, 0.95089144, -0.4212272, -1.2846807, -1.3833915, 0.4969849, 0.43599954, 0.83426636, -0.24071422, -0.41247413, 0.1387651, -0.4410387, -1.0201113, -1.0151287, -0.30920383, -0.8524633, -0.78186303, 1.4333282, -0.14950007, -0.089015275, -0.08387725, 1.1056882, -0.1740884, -1.9291706, 0.38982868, 0.6995906, 1.4180859, 0.75444674, -0.95499, 1.1255932, 0.84249365, 0.3965257, -0.91656125, 0.30407417, 0.04821479, -1.7198461, 0.2624329, -0.4283524, -1.4282044, -0.06547159, 0.80487037, 1.1919813, -1.157512, 0.82863224, -0.42936045, -0.28821445, 1.4708856, -1.4182036, 1.0695099, -0.98250604, -0.2871269, -0.30628875, 1.0268122, 0.1077968, 0.3942135, 2.5741844, -0.22341488, -1.2882922, -0.92537004, -0.29827946, -0.8657189, -1.3523725, 1.2271954, -0.97767305, -1.5279788, -2.1684647, -0.8809741, -1.7020837, -0.77671313, -0.30759412, 0.95844865, 0.1201042, -0.35956126, -0.6732596, -0.66489315, -0.23282625, -2.199095, 0.015637554, 0.9093451, 0.6256771, -1.0440992, -1.2953913, -1.1988038, 0.57272595, 1.3343319, 1.5685514, 0.79896367, -0.33781642, 0.108379155, 0.69055647, -0.17776953, 1.1198257, 1.4672221, -0.25398532, -0.1565034, 1.6918836, -0.8700688, -1.1308992, -1.1974417, -1.1137329, 0.83902305, -0.21537443, -0.3621372, -0.56612146, -0.23607141, 0.06558742, 1.5528702, 0.6764845, -0.9899203, -0.24187809, -0.43976098, -0.17901607, 0.39272916, 0.6076459, -0.7449423, -1.1412064, -0.600098, 0.1454072, 0.68503654, 0.5873987, 0.7652769, 0.912399, -0.58995295, -0.07652284, -0.5957174, 0.1472433, 0.5542278, -1.115277, 0.44539738, -0.039799254, -1.5118825, -0.23560798, 1.2844542, -0.02893157, -1.1343006, -0.3527552, -0.9586529, 0.7139522, -1.7368245, 0.2557312, -0.70883536, -0.41837376, -1.4177307, -1.2666334, 0.59642404, -1.461725, 0.029051205, 1.4515164, 1.2521093, 1.2121066, -0.46119824, -0.42757216, 0.21424922, 0.34615174, -0.4361925, 0.90037245, -0.8620516, 0.37771982, 1.0740494, -0.35472628, -1.7184305, -0.10192693, -0.49839312, -1.2606971, 0.898541, 1.611125, -1.8196648, 1.1042156, -0.90353936, -0.042169813, 0.88219213, -1.8153738, 1.0310693, -1.8895094, -0.3627731, 0.73769325, -0.29475728, 0.20184469, -1.0428863, 0.60270995, 1.2704183, -0.061668225, -0.29045984, -0.1823551, 0.26992062, 0.55780077, 0.03529894, -0.7468571, 0.9940811, -0.61718744, -0.8993642, -0.4772598, 0.58771855, -0.8835732, -1.031474, -0.7897231, 0.99002546, -1.3488675, -0.08344488, -1.6553906, -0.49131376, 0.046392173, -0.5849192, -0.93096536, 0.34290412, 0.056457043, 1.3271558, 0.16145127, -1.6025941, 0.8305644, 0.015047411, -0.7772031, 2.4478736, 1.360108, 0.9110892, 1.506102, -0.45487866, -0.060103003, -0.15757999, -0.3803988, 1.4101455, -0.30708334, 1.0538982, -0.8294986, 0.047576066, -1.3256047, 0.45925236, 1.080683, -0.40040824, 1.111924, 0.5593369, -1.3896682, 1.9023105, 0.39116186, -1.1850232, -2.5139296, 1.7266207, -0.25787568, 0.8259598, 0.18016069, -0.49573916, -0.04785415, -0.04976653, 0.18465424, 0.7601481, 0.11443199, 1.3491508, 1.0334013, 0.51608413, -0.54822063, 1.0440209, 0.95839494, 0.35903192, 1.0515867, -0.69485205, 0.1259807, 0.5945902, 0.93981904, 0.8042134, 0.15225424, -1.1134514, -0.14319238, -0.3946564, 1.5849768, 0.32735464, -1.6741558, -1.2463093, -0.53212994, -0.5394611, 0.96027434, -0.03620187, -1.0707031, 0.0770781, 0.73527884, -0.2964921, -0.9622408, 2.6329126, 0.3759397, -0.6592005, 1.1139793, -0.14716254, -0.045174014, -0.6791271, 0.03255666, -1.0424751, 0.9587916, -0.08317592, 0.31456205, 0.1654861, 0.7260626, -0.58481413, 2.1518521, -0.09424311, -0.341701, -1.6353136, -0.17042917, 0.40579286, -0.019979922, -1.0232186, -0.35566926, 1.1416146, 1.2195485, 2.077471, -0.43837976, -0.540069, 0.7379818, -0.19262947, -1.4484813, 0.83212805, -0.74113214, -0.9538223, -0.05834837, 0.44041303, -0.745651, -0.17320694, 0.49808195, -1.5061892, -1.4944872, 0.8008681, -0.9398744, -0.6182817, -0.30942512, 0.36129692, -2.318599, 0.54687035, 0.56182396, -0.06872349, -1.4240448, -0.9996982, 2.5200498, -2.1654541, 0.47496814, 0.39391482, 0.1450314, 1.4216573, -0.04379695, 0.26455754, -1.5143254, -0.85161084, 1.3674622, 0.070562564, -0.07321006, 0.29007795, -1.1730325, 0.7077345, 0.17599413, -1.507193, 0.033037208, 0.6345246, -0.026505666, -1.3673415, -1.175768, -1.11894, -1.1722083, 0.650109, 0.32472748, 0.77097934, -0.91142863, -1.6627023, 0.23963581, -0.34835646, 1.4858739, -0.17808837, -1.4222599, 0.42851982, 0.91185176, -3.1663878, -1.9458324, 0.17138235, 2.7273235, 0.48435047, 1.4257667, -0.39429623, -0.25928524, -0.6969385, 0.27237153, 0.9719653, -0.94499624, -0.93431616, 0.3313879, 0.5322593, -1.0736529, 1.0660676, -0.3857444, 0.24826482, 1.3510975, -0.29179078, -0.48444024, 0.754738, 0.0317517, 0.88101363, -1.43013, 0.19301237, 0.62407196, 2.5889156, -0.35503194, -1.3965347, 1.492098, 1.0243834, 0.2891013, 0.7667233, 1.203408, -0.3896164, 1.1657643, 2.0440407, -0.03122957, -0.44319737, -0.11672504, -0.41915283, 1.3281194, 0.685727, 0.75879604, -0.073904574, -0.33132726, 1.257834, -0.45057672, -0.6296975, -0.9192257, 1.0221746, 0.9291648, -0.94363177, 1.5092527, 0.34648833, -1.2825301, -1.0486758, 1.5055352, 1.8865529, -0.6334556, -0.024593918, -1.1252753, 0.5185867, 0.6124192, -0.037293382, -1.1181691, -2.355505, 0.63034916, -1.0368301, 0.036144637, -1.3204461, -0.8474016, -0.48407465, 0.87706107, -1.6368544, -0.59363234, -0.27536315, -1.3947005, 0.6367079, 0.080906734, 1.6612034, -1.1942811, -1.3962767, -0.3492455, -0.3317619, 0.8585051, -0.6099857, 0.9731934, -0.33863986, -1.1859555, 2.1923492, -0.20945679, -0.019335553, -0.43917775, 0.17868017, 0.0638598, 0.6821277, -0.52001894, 0.29006997, 1.3569279, 0.04126053, -0.3513845, 1.2705727, 0.61468333, -0.51229066, -0.943082, 0.123694554, 0.08704179, -0.85914665, -1.2665237, 0.120996974, 0.5872544, -0.6498738, -0.7558008, 2.0874078, -1.0826503, 1.2161089, -1.1158899, -0.6995301, 1.5182605, 0.9212444, 0.19732377, -0.49805963, 1.5307648, -0.09824258, -0.17579414, 0.3059942, 0.29013804, 1.6369693, 0.68866324, -0.41122213, 1.6944041, 0.84453344, 0.3998347, -0.632812, 0.09177586, -0.7140142, -0.25561154, 0.6781396, 1.4335965, -0.92604005, 0.47844896, -0.48447236, -0.26535156, 0.5610667, -1.5414823, -1.1018133, 0.45464283, 0.8867224, 0.46265063, 0.13983822, 0.62714416, -0.47083634, -0.582377, -0.95651495, 1.4113004, -1.5234841, -0.54477, 1.0616144, 0.86381114, 0.03474352, 0.8896466, -0.76275426, -0.52808905, 1.6884556, 1.2545907, -0.44361708, 0.049262527, 1.7879602, -0.48884976, 0.62784165, 2.0904067, 0.6360781, -0.24506103, 1.8339422, -0.24874923, 0.31993455, 1.6265831, -0.5266883, 1.8444152, 1.0903536, -0.18320195, -0.67846495, 0.27813777, -1.0786334, 0.36553434, 0.18099804, -0.4765761, -0.47241208, -1.6986724, 0.3840502, 1.0583769, 0.9158794, -0.36690733, 1.0359205, 1.5035034, -1.8313702, 1.0422257, -0.0002647597, 1.6137222, -0.8129771, 1.7378803, 1.3767345, -3.097059, -0.23142079, -0.49518618, 0.07198295, -0.47360966, -0.14493094, -0.903153, -0.8566985, 0.35070956, 0.07519327, -0.8176252, -0.5011129, -2.0338905, 2.0791926, -0.9524556, -0.35013407, 0.69216543, 1.8425413, -0.7101777, 0.9166597, 1.373442, 0.8864508, -0.69209445, 0.722764, 1.6853193, 0.43362904, 0.15304323, 1.2292317, 0.571318, -0.03697805, 1.0155749, 0.017713238, 0.61617565, 0.6086641, 0.17308934, -1.0802362, -1.0679781, -0.17226323, -1.079547, 0.36464852, 2.0566635, -1.5955839, -0.708551, 1.0764654, 1.3606769, -2.1782458, 0.12521815, -1.4049494, -1.893154, -0.9671274, 0.20998928, -0.39094374, 0.41292644, 1.0094323, 0.7236309, 0.729022, -0.093239464, 1.331729, 0.12037584, -0.91795444, -2.681229, -0.06648174, 0.32202816, 0.25560144, -1.2391394, -0.5821641, -0.92049783, 0.08570945, -0.024655689, -1.1845642, 1.3647254, 0.90066713, -0.7882246, 0.11265421, -1.1675286, -1.4266101, 0.07994837, 0.22534218, -0.13602129, -0.37254322, -2.8944714, -0.091046974, -0.15506679, 0.5082102, -1.5789851, -0.2162176, -0.51339483, 0.5204938, 0.11788538}; + float output[] = {0.16892381, -0.92159724, 0.64389044, 1.8697567, -0.8018371, -1.2693683, -2.093365, 1.8541908, -0.26340157, 0.9572909, 0.34671152, -1.7053558, -0.36417124, -2.3248599, -0.13200487, 2.3006496, 0.46386284, -2.1614797, -1.3742889, -0.40108228, -0.5511143, 0.35275838, -0.70952916, -0.41565117, 0.15577549, -0.8660324, -0.31523043, -1.43095, -0.62599516, -1.2735285, 0.74245137, 0.5401528, 1.2080778, 1.9445739, 0.5149316, 0.5683389, 1.6830992, -1.5869702, -0.9276118, -1.8208988, -0.52550256, 0.082054906, -1.0242202, 0.640871, -0.50823563, -0.13035983, -0.7713898, -1.1191769, 0.59570795, -0.06568418, -1.1858853, -0.085937336, 1.0237325, 0.32681447, -1.3751194, -0.28284678, -2.5314686, -0.36053106, 1.3408105, 0.46642232, -0.7184956, -0.5716407, -0.29177785, -0.29941186, -0.08443816, 0.054849386, -0.582217, 0.5512954, -1.2351213, 1.0514443, 0.2601373, 0.2979866, 1.1088992, -0.41123372, 1.2637646, 0.18790472, -0.16448955, -0.61922485, 0.72030956, -1.8054826, 2.739959, 1.515231, -1.1871477, -0.72046477, -0.49725538, -0.3599622, -2.4750538, -0.11285576, -1.1877617, -0.28629062, -0.5285716, 1.9786791, 2.2289317, -1.2789943, 1.3801973, -1.2113228, 0.16036053, -0.4714372, -1.1011868, 1.4348198, -0.15923952, 1.4626329, -0.7119883, 0.7440471, -1.8418623, 0.2772118, -1.2898343, 0.8006727, -0.47921824, 0.35204977, -0.23730946, -0.9184093, -0.44745374, 1.7422614, -1.2565724, 2.1967077, 0.31261623, -0.89821947, 1.8867549, 0.45231855, 0.8269342, 0.032707807, 0.025322068, 1.1288303, -1.4889454, 1.3964689, -1.5560274, -2.1302202, 0.7437271, 1.5007018, -1.3589836, -0.955504, 0.32147405, -1.4642475, -0.12817268, -0.030474393, 1.7738372, -0.38548046, -1.0957392, 1.3144948, 0.2697103, 1.8592813, 0.4777307, -0.6822411, 1.0501494, -0.87983644, -1.7267572, -0.3565207, -1.1379921, 0.7837413}; +} diff --git a/tmva/sofie/test/input_models/references/Slice_Default_Axis.ref.hxx b/tmva/sofie/test/input_models/references/Slice_Default_Axis.ref.hxx new file mode 100644 index 0000000000000..09fe065ea53f5 --- /dev/null +++ b/tmva/sofie/test/input_models/references/Slice_Default_Axis.ref.hxx @@ -0,0 +1,4 @@ +namespace Slice_Default_Axis { + std::vector input = {-0.1461883, -0.016122868, 0.7906066, 1.0770687, 0.8330815, -0.10727052, -1.1016161, -0.6145062, -0.7690668, -1.0544336, -0.58136266, 0.6698605, 0.7147375, 0.0022958783, 0.51871574, 0.6482896, 0.3113063, -0.4734845, -0.5740597, -0.9168964, -0.41645914, -0.49598876, 0.09797197, -1.143795, -0.4667988, -0.63560325, -0.09921953, -0.6377913, -1.9445546, 0.28251606, -1.837604, -0.11723251, -0.2457299, -0.14956762, 0.24271688, 0.2885258, -0.41624215, -0.07236863, -0.88772, -0.22259605, -2.3600693, -0.6008399, -0.9242371, -0.7604781, 0.18364549, -1.8932725, -0.3934923, 0.9908918, -0.82707083, 0.037394904, 0.48888022, 0.35733646, -0.69646317, 0.14467147, 2.0875776, -2.1810489, -0.2571033, -0.55144024, 0.2959311, -0.19067906, -0.75172126, -1.2874966, -1.0975883, -0.9559576, -0.49447343, 1.9475956, 0.4257172, -1.0980548, -0.76810384, 0.58064747, -1.7632297, 0.26826766, 1.3453583, 1.2687472, -1.1958207, -0.16609953, -1.5563438, -0.4938013, 0.5151148, -0.091698416, 1.1415159, 0.426471, 0.6566607, 1.1295458, -0.28391364, 0.79970664, -1.5118104, 0.36721396, 1.7975253, -0.73840666, 0.4420629, -2.2546258, -0.061347473, -1.2929934, 0.5170257, -0.06677258, -0.48366687, -0.6352214, 0.3780832, 0.03586758, 0.3670747, 0.6627743, 0.5272325, -1.0584992, -1.4143002, 0.47498345, -0.8205925, -1.8733176, 1.8025477, 0.06656069, -0.7836851, 0.47841695, -1.2978657, -0.006346132, 0.51665795, -1.4770932, 1.0194303, -0.30320534, -1.2961298, -1.9114046, 1.0950881, -0.10367981, 0.23185624, -1.3055613, -0.5437395, 1.1283166, -1.3763173, 0.07796734, 0.14537609, -0.4749371, 0.6209849, 0.19354947, 0.7213671, 1.3833684, -0.15803675, 0.0047794804, -0.22178061, 1.9866813, 1.2574888, 1.8167769, -0.020589387, -1.9657744, 0.17520925, -1.238028, 0.18338954, 0.7720395, 0.28465885, -0.46973786, 0.09582084, 1.6777899, 0.16898789, 0.37088445, -1.0338578, -0.0052072485, -0.57036436, -1.1178404, 0.6796968, 1.6614155, 1.1149341, 0.7587031, 0.32500324, 0.8289195, -1.1860889, 0.552775, -1.5618576, 1.1355617, -0.019234084, -0.053850766, -0.21276851, 0.38202664, -0.92719686, 0.45522645, -1.4462421, 0.39298248, -0.08499029, -0.4432199, 0.7962805, 0.035947476, -1.159359, -0.60213226, 0.6608978, 0.25666326, -1.6058868, -0.14197825, 0.81879604, 0.06913617, -0.68283623, -0.6830012, 0.9924173, 0.738249, 1.4709839, -0.5562903, -0.45345142, 0.44788426, 1.3294722, -0.2009495, -0.47743958, 0.30325928, 0.28618523, -0.44166443, -1.2473358, 0.24071434, -0.07651104, 0.13556144, 0.6775791, 0.05754586, -0.37290746, 0.9709312, 0.40250617, 0.57110745, -0.4984228, 1.7988355, -0.16423433, -0.6757791, 0.6791431, 1.0340523, 1.9974663, -1.1417656, 0.15521769, -1.6735531, 1.2924621, -1.7712533, 0.31316996, -1.1286432, -0.16561612, 1.4077295, 1.7806652, 1.6394432, -0.26378694, 0.083979696, 1.0437967, -0.1325788, -0.09308595, -2.7445931, -0.9295771, -0.13040234, 0.39286298, -0.23240566, -0.15136135, -1.1185503, 1.5185101, -1.2777773, -1.0749928, -0.69080085, 0.039009497, 1.4085402, -0.45465285, 0.29640433, 2.3633902, 0.38267857, 0.0032249314, 1.0855026, -0.64048296, 0.124470204, 0.017325122, 0.695519, -1.0086539, -1.0865158, -1.5793724, -1.1726278, 1.1974345, -0.6120161, 1.3437238, 1.7283806, -1.3011041, -0.166229, 1.9684845, -1.2849504, -0.017190017, 0.5633989, -2.1813452, 0.19855276, 0.15585509, -0.2397429, -0.07259906, -0.18117818, -1.435192, 0.5535545, 0.91788614, 0.9611421, 0.27218357, -0.8193188, -1.6022354, 1.4913019, 0.07563583, 1.191209, 1.1098686, 1.4217767, -0.062174533, -1.0004618, 0.35559297, -0.29587275, 1.224246, 0.27928728, 1.4012953, 0.004571245, -0.004811227, 0.6884962, -0.31340042, 0.7118886, 0.8218903, -0.6128678, -0.49580857, 0.52445906, -0.15825763, 1.093557, 0.5337642, 0.9011482, -0.85576683, 0.345507, -0.10933566, 0.21388091, -0.7470893, 1.115657, -1.0193942, 1.3795731, 0.16783884, 0.4803627, 1.2138109, 1.762632, -0.55953956, 2.3835013, -0.07254272, 1.2885357, 0.6622172, -1.0122503, -1.8009477, 1.5157818, 0.8476051, 0.13299866, -2.3853347, -0.06983959, 0.49273565, -0.87671894, 0.12512384, -0.82879865, -0.9572407, -0.32495856, 0.06101727, -1.1533537, 0.020594995, -0.9918277, -0.81584674, 1.5852944, -0.5340633, -0.40271887, -0.3721054, -0.005816021, 0.6088237, -1.0743963, 0.88497263, -0.37899604, 0.50920826, -0.88503253, -0.673719, -0.92704546, -0.9064568, -0.5845781, -0.2365786, -0.97428477, -2.083304, -0.22934851, -0.5516302, -0.69631237, 0.36876953, 2.0252135, 0.74653697, 0.5618036, -0.44255832, -0.67436403, -1.0235599, 0.789049, -0.12523027, -2.2393558, 0.14112401, 1.3160639, 0.5901369, -0.008300025, 0.04022059, -0.6193368, 2.676356, 0.73500293, 0.8828043, 1.7149053, -1.2272266, -0.38595983, 0.9880927, 0.28173974, 0.09567761, -0.99841386, 0.55506814, 0.04364348, 3.0956612, -0.39753824, 0.6281927, -0.24912265, 1.2875627, -0.33991942, 0.080732696, 0.6423637, -0.4085811, -1.2270579, 0.27428335, -1.2284294, -1.7676984, -0.9863669, -0.60794735, 0.35996225, -0.83115405, -0.10226897, -1.1846787, -0.9867668, 0.09014541, -0.46956572, 2.334743, 1.1283133, 0.47274005, 0.7801183, 0.20632647, 0.53270394, 1.618369, -0.68861, 1.5393575, 1.0087231, 0.5578767, -1.1502749, 0.9704601, -0.58556443, -0.8638071, 1.6273997, -0.6914098, -1.1505114, 0.22683571, -0.3346126, -0.2779381, 0.44256505, -2.2296052, -1.1183658, -0.25026667, 1.5899142, -0.9656592, -0.52585506, -2.2984645, -0.913809, 0.809646, 1.3930463, 1.5980829, 0.5588279, -0.1415989, -1.0977601, 1.0027899, -0.8581, -1.4768612, -1.6114205, 0.55412006, 0.5285257, 0.07860353, 0.8938196, 1.3999463, 1.6992323, -0.88001025, -0.14953178, 2.8698957, 0.6424969, -0.41471675, -1.9350584, 1.3093637, -0.34622955, 0.35268912, -0.7348358, -0.1637814, -1.217533, 1.7498442, -1.3902655, 0.9558796, 2.215649, 0.4073312, -0.24630588, -0.4336063, -2.1483955, -0.9822753, -0.24802127, -1.9440368, -0.14923008, -0.106288746, 1.3390882, 0.29155636, -0.010580624, -1.6630732, 0.21212313, -0.9744938, -0.93469507, 1.5370817, 0.9331293, -0.6155238, 0.77781016, -1.360782, -0.02083951, 1.6073259, 0.8050398, 1.15108, -1.0778083, -0.29364675, -1.3154548, 1.3826702, 0.83120215, 0.3349555, 0.108244404, 0.0056229704, -1.2478333, -0.30873495, -0.15155567, 0.5545185, -0.17677861, 0.35164872, 0.20997967, 1.397111, -0.56422126, -1.5136795, -1.032756, -0.59829795, -0.392903, -2.4636624, 0.25544158, -0.59832823, -0.7234389, -0.6978005, -0.8573432, 0.12969226, 0.5464562, -0.16188233, 1.380535, -1.0571035, 0.51674634, -1.4579222, 1.5115775, -1.0869778, -0.13404822, -0.5940917, 1.2037292, -0.32398605, -0.29220906, 1.0000731, -0.63900346, 0.24358685, 0.65689164, -0.10265587, 0.6322214, -0.0917442, -0.3694211, 0.93206906, 0.45265195, -0.87861097, 1.6871637, -1.2518704, -2.3056078, 0.9769796, 0.038062252, -0.46498087, 0.8485326, -0.839546, 0.28043613, 2.573216, -0.29004475, 0.31579295, 0.7601751, -0.8611639, -1.9155579, -0.14570755, -0.4572656, -1.6403922, 1.269364, -1.2096163, -0.13851365, 1.0688369, -0.043349892, 0.97961247, -0.29044124, 1.324035, 0.4427559, -2.4195874, -0.05904026, -1.047782, 0.34742212, -0.59459364, 2.2101438, -0.6710455, -0.7346976, -0.19578286, -0.3006533, -0.4168783, 0.11194632, 0.4166033, 0.73106396, 1.5515249, -2.4722917, -0.7615553, 0.775932, 0.40671185, 0.92429924, 1.0650808, -1.5915896, 0.23377, -1.4564233, -0.5552662, 0.7849949, -0.052568533, 0.2778592, 1.3305982, -0.9056904, -1.0874093, 0.6774261, -1.4075345, -0.6792449, -1.9145862, -0.36068064, 0.9614725, 0.7049456, 0.85817826, 1.516153, 1.0643967, 1.2125771, 1.0095186, 0.18826225, 0.17524572, 0.9800971, -0.05518548, 0.76132685, -1.1523248, 0.95912564, -0.8287138, -0.230913, -1.9400084, -0.9241041, -0.4996432, -0.20880367, -0.58793384, 2.5016222, -0.5362384, 0.6342494, -1.6295053, 1.1614339, 0.3722488, -0.9641267, -0.4324223, 0.5987431, -0.09008133, -0.72262436, 0.34580615, 0.54369086, -0.04141991, 0.5681258, -0.024746062, -0.22176632, 1.6875525, -0.8856508, -0.5093772, 0.16131109, 0.13457753, -0.5028758, 0.48031703, 0.34559208, 0.40866286, -0.8627139, -0.43610817, 0.1370359, 0.71395236, 1.0733443, 0.9591038, -1.2339122, 0.51710594, 1.6181912, -1.1786822, -0.49682978, -0.73324996, -0.90021396, -0.917064, -0.82882273, 0.54618657, -0.35091722, 0.18635193, 0.28404334, 0.7419349, 0.22317982, 1.5418407, -0.59588146, -2.2045953, 0.5704977, -1.3579642, 0.6766229, -0.7265069, 1.1195977, -0.05751021, -0.88166755, 1.6513765, 0.83279973, -0.7335223, 0.77010125, 0.106006265, -0.50255, 0.500598, -0.8823614, -0.8286727, -0.7444291, -2.1645043, 0.15058456, 2.1300547, 1.3322825, 0.08238974, 0.47212347, 0.0971547, 0.34920275, 1.14977, 0.2660158, 0.14294139, -0.1682589, -0.2658644, -1.1637232, -0.8218067, 0.9199889, 1.0239819, -0.70528126, 0.0060127624, -0.24274509, -0.65451324, -0.38401487, 1.2616978, 0.3047205, 0.19565456, 0.9565755, -0.014404449, -0.42572787, -0.27978837, -0.86642414, 0.8405607, -0.15055239, -0.16638431, -1.9672482, -1.9616699, -0.058524407, 0.52005005, 1.6248668, -0.6036527, -1.1067222, 1.4944029, 0.21208148, -0.71202946, 0.08290248, -2.2786183, 0.04106648, -2.1124837, 0.11604868, -0.50486493, -1.7176164, 1.7939253, 0.9316365, 1.0395255, 1.3111675, -0.32554156, 2.610884, 1.0958631, -0.13374676, -0.88248503, -0.47524875, -0.5697381, 2.2536426, 0.57177734, 0.089711525, 0.09203127, -0.31630644, 1.4399436, 0.87644094, -0.9510531, 2.1558537, 0.7398341, -0.7479294, 1.6116168, 2.2608933, 0.6935909, 1.8886098, 1.4206983, 0.6459501, -1.4992285, -0.40028575, -1.397525, 1.4820021, 0.69096315, 1.040845, 0.7248607, -1.5581473, -1.163343, 1.0534998, -0.13074964, -1.3512405, 1.7234086, 3.1778047, -0.7669222, 0.2769623, 0.11744058, 2.13683, 0.21798563, -0.37044996, 0.38857397, -0.8483964, -0.38422018, 0.49951142, 0.028199164, 0.9054906, 1.4535757, 0.92591554, 0.53013515, -0.25900427, 0.5950167, 1.3598921, 0.006420622, 0.1600974, 0.0067178584, 0.16290559, 1.33563, -0.3311576, 0.7935676, -0.36323825, -0.18903373, -2.2316182, 0.28740197, 0.006179229, 0.71337485, 0.8837852, -0.20782436, -2.2476697, -0.5218193, -0.33238944, 0.2537466, -1.370611, -1.7223306, 1.5160371, 0.027803194, -0.32390642, 0.3986786, 1.1172193, 1.558993, -0.6832563, -0.20899004, 0.94750255, -0.38843265, 1.1702619, -0.5910523, 0.67201364, -0.23071921, -0.32311478, -0.29928425, -1.4202323, -1.0467842, -0.33493733, -0.06345067, -0.20013566, -0.5673482, 0.3535591, -0.5701964, -1.132469, 0.44864315, 0.28851375, -0.87927747, -1.0867138, 1.7710389, 0.99955666, 0.04848535, -0.6760312, -1.5226128, 0.17691953, -0.55969036, 1.5326198, -1.1423959, -1.0857098, -0.38307127, -0.108541355, 0.6333991, -0.67143476, -0.7309363, -0.8394637, -2.3495052, 0.4552111, 0.694442, 0.88670564, -0.8066063, -0.9832314, 0.5582432, -1.9541792, -0.44915298, -0.8806987, -2.1678388, -0.40057325, 1.402311, -0.749579, 0.9779166, -0.9725332, 0.93724334, 0.7930738, -0.3815982, 0.52829677, -0.59715456, 0.4632079, 0.09168929, -0.64770544, 1.789374, -0.4414639, 1.5570718, 1.2062063, 0.34104025, -0.34750745, 1.6979355, 1.7266192, 1.1891768, 1.5133071, 0.53370464, 1.5988535, -2.4613225, -1.6933792, -0.8667333, 0.7052899, -1.4491802, -0.015342939, -1.3674146, -1.56072, 0.16171443, -1.5806398, 0.4695208, 0.8821774, 0.5689583, 2.1032276, -0.5122946, -0.050347406, 0.3566521, -1.0292819, 0.8163361, 0.89640504, 0.86676586, -0.13297859, 0.24916588, -1.4969269, -0.118957415, 0.12848116, -0.825286, -0.6712518, 0.039900694, 0.19978356, 0.14676023, 0.74267155, 0.70510364, 0.22815554, -0.21663566, -0.80683714, -1.1868128, 0.9666372, 0.22554556, -0.86386347, -0.31636468, 0.8181482, -0.5027156, -1.053451, 1.7066551, -1.261419, 0.075614035, -0.24103126, -0.0016349248, 0.10319547, 0.9757924, 0.5693857, -1.2953516, 0.915416, 1.1547158, 0.56889296, 1.6462102, -0.6902782, -1.8096964, -1.3979508, 0.98242086, 1.4752377, 0.06406855, 0.20497032, -0.28602636, 1.7617588, -0.1947333, -0.011363344, 0.18868288, 0.8202959, 1.5982426, 0.02868123, 0.1815656, -0.6364113, -0.93385684, -1.7666136, 0.2698049, -1.2644852, -0.35387158, 0.93788034, -0.017734949, 0.74502975, -0.09487202, 0.6416881}; + float output[] = {1.0770687, -0.7690668, 0.0022958783, -0.5740597, -1.143795, -1.9445546, -0.14956762, -0.88772, -0.7604781, -0.82707083, 0.14467147, 0.2959311, -0.9559576, -0.76810384, 1.2687472, 0.5151148, 1.1295458, 1.7975253, -1.2929934, 0.3780832, -1.0584992, 1.8025477, -0.006346132, -1.2961298, -1.3055613, 0.14537609, 1.3833684, 1.2574888, -1.238028, 0.09582084, -0.0052072485, 1.1149341, 0.552775, -0.21276851, 0.39298248, -1.159359, -0.14197825, 0.9924173, 0.44788426, 0.28618523, 0.13556144, 0.40250617, -0.6757791, 0.15521769, -1.1286432, -0.26378694, -2.7445931, -0.15136135, -0.69080085, 2.3633902, 0.124470204, -1.5793724, 1.7283806, -0.017190017, -0.2397429, 0.91788614, 1.4913019, -0.062174533, 0.27928728, -0.31340042, 0.52445906, -0.85576683, 1.115657, 1.2138109, 1.2885357, 0.8476051, -0.87671894, 0.06101727, 1.5852944, 0.6088237, -0.88503253, -0.2365786, -0.69631237, -0.44255832, -2.2393558, 0.04022059, 1.7149053, 0.09567761, -0.39753824, 0.080732696, -1.2284294, -0.83115405, -0.46956572, 0.20632647, 1.0087231, -0.8638071, -0.3346126, -0.25026667, -0.913809, -0.1415989, -1.6114205, 1.3999463, 0.6424969, 0.35268912, -1.3902655, -0.4336063, -0.14923008, -1.6630732, 0.9331293, 1.6073259, -1.3154548, 0.0056229704, -0.17677861, -1.5136795, 0.25544158, 0.12969226, 0.51674634, -0.5940917, -0.63900346, -0.0917442, 1.6871637, -0.46498087, -0.29004475, -0.14570755, -0.13851365, 1.324035, 0.34742212, -0.19578286, 0.73106396, 0.40671185, -1.4564233, 1.3305982, -0.6792449, 0.85817826, 0.18826225, -1.1523248, -0.9241041, -0.5362384, -0.9641267, 0.34580615, -0.22176632, 0.13457753, -0.8627139, 0.9591038, -0.49682978, 0.54618657, 0.22317982, -1.3579642, -0.88166755, 0.106006265, -0.7444291, 0.08238974, 0.2660158, -0.8218067, -0.24274509, 0.19565456, -0.86642414, -1.9616699, -1.1067222, -2.2786183, -1.7176164, -0.32554156, -0.47524875, 0.09203127, 2.1558537, 0.6935909, -0.40028575, 0.7248607, -1.3512405, 0.11744058, -0.8483964, 1.4535757, 1.3598921, 1.33563, -2.2316182, -0.20782436, -1.370611, 0.3986786, 0.94750255, -0.23071921, -0.33493733, -0.5701964, -1.0867138, -1.5226128, -1.0857098, -0.7309363, 0.88670564, -0.44915298, -0.749579, -0.3815982, -0.64770544, 0.34104025, 1.5133071, -0.8667333, -1.56072, 0.5689583, -1.0292819, 0.24916588, -0.6712518, 0.70510364, 0.9666372, -0.5027156, -0.24103126, -1.2953516, -0.6902782, 0.06406855, -0.011363344, 0.1815656, -1.2644852, -0.09487202}; +} \ No newline at end of file diff --git a/tmva/sofie/test/input_models/references/Slice_Default_Steps.ref.hxx b/tmva/sofie/test/input_models/references/Slice_Default_Steps.ref.hxx new file mode 100644 index 0000000000000..15b88b5959627 --- /dev/null +++ b/tmva/sofie/test/input_models/references/Slice_Default_Steps.ref.hxx @@ -0,0 +1,4 @@ +namespace Slice_Neg { + std::vector input = {-0.8470076, -0.617558, 0.024568161, -0.54007053, -0.5732189, 1.0910312, 0.51959157, -0.073640585, -0.60885113, -1.8285086, -0.9326965, -0.3021695, 1.066226, 0.8134058, -1.5457271, 1.1948874, -0.04176423, -0.59385985, 0.011908118, 0.095879026, 0.6736443, -0.48068637, 0.11451639, 1.5323228, -0.8184595, -1.4535367, -0.06812811, 0.71712196, 2.4668334, 0.3803238, 1.5602548, -2.1309204, 2.8248832, -1.3176224, -0.6582828, 0.73314184, 1.8034855, -1.6781946, -0.23040803, -1.3201909, -0.24954909, -0.34502414, -0.7355865, -0.41729373, 0.5724887, 0.71088016, 0.8767546, 0.61704224, 0.25664437, 0.5908548, -0.60789496, 1.0349115, 0.46317944, 0.17278059, -0.78425044, -0.11165529, 0.7919961, 0.35827583, -1.9887244, 0.12787221, 1.095776, 0.28236288, 0.48224112, -0.5900752, 0.9498589, 0.5209434, -0.57806545, 1.3280295, -0.6969055, -2.539957, -0.0030387403, 1.871011, 0.13415621, -0.5734313, 0.09759699, -0.29701954, 0.9157297, -0.62670755, 1.2683886, -0.7024728, 0.6662447, 0.46600792, -0.494909, 0.8643152, -1.2757068, 0.8424522, 0.9383413, 0.49222285, 0.11790963, 0.57665557, -0.2206793, -1.2813573, -1.4700212, 1.9633232, 0.5646655, 0.04624529, 0.5216187, -0.8490203, 0.0040446366, 1.6275132, 0.15718703, -1.256212, 1.7298958, -0.4105028, 0.6821366, -0.72149056, -0.27424803, 0.19525297, 0.5027373, -1.0273383, -0.42891493, 0.31214187, 0.3240255, 0.6148003, -1.4785552, 0.79766524, -1.3977971, -1.9163635, -0.4596946, 0.4611778, 0.4615138, 0.57446766, -1.8127673, 1.0151784, 0.79838765, -0.16945624, -0.29454982, -0.22049658, 1.0656692, 1.9895301, -1.6840646, -0.0068151196, 0.29346943, 0.8048959, 0.50557023, -1.8385066, -0.4750251, 0.3583206, 0.41981372, -0.3146262, -0.79544896, 1.6337428, 1.4349604, -1.5252166, -0.91220444, -0.42145732, -1.4244072, -0.44793433, -1.494974, 0.074361734, 0.7527505, 0.6034745, 0.08402507, 1.0259006, -1.1905016, 0.52963644, -0.6864299, -0.15308455, 0.9455237, 1.000834, -1.828627, -0.5953371, 0.61878735, -2.7202675, -0.13529402, -1.1603078, -0.28340778, 1.6124189, 1.48123, -0.032326907, -1.5110354, -0.60052997, -0.98667, -0.026620502, 0.9869495, 0.9609994, 1.8000636, -0.39040756, 0.662662, -0.35303995, -0.10898638, -0.097712174, -0.13256012, -0.30892372, 0.9536066, 1.0131402, -0.21144608, 0.9224201, -1.2749323, 0.12289531, 0.6637511, 0.0252969, -0.058163885, 0.6347488, 0.13144295, 2.8548353, -1.0804298, 1.3999987, 0.18585795, 0.6911652, 0.29648793, 1.6838806, 1.4852757, -0.29899225, -2.699224, 0.22093739, -0.63045704, -2.3597014, -0.9839067, -1.0647969, 0.8293971, -0.7054954, 1.7537973, 0.22664751, -0.1311305, 0.50954145, -1.7052051, -0.42696014, -0.5314228, -0.56175625, 0.6429764, 1.3670748, 0.46155804, -0.7046119, 0.060639046, -0.113631465, 0.17838268, -0.084968045, 0.67876095, 0.6301664, 1.2548337, -0.2446083, -0.092792444, -0.42515463, -1.0051632, -0.5343044, -0.25070238, 1.3654076, -1.1015171, -1.5554606, 0.62512356, 0.36090285, 0.43128428, 0.097997755, -0.3924458, 1.1851805, 0.2851699, -1.9355323, -1.8260921, -0.57449347, 0.27789333, -1.1954387, 0.22248776, -1.6744449, -1.2109405, 1.0672655, 0.95568365, 0.8194465, 0.15550855, 0.3167771, 0.22519737, 1.2998043, -0.31728703, -0.5346176, 0.907684, -1.5638523, -1.1844252, -0.2738023, 0.051613424, 0.2711231, -2.3651042, -0.44602147, -0.44494528, 0.8535133, 0.24942228, -1.0080348, 0.85422933, -0.48436078, -1.3689119, -1.3511016, -0.48757446, -0.032849748, 0.22983012, -0.032983564, -0.71215105, 0.18651846, -2.0692394, -0.57982725, 0.2421949, -0.004737948, -0.90421754, -0.78182286, 0.12858658, -0.30840445, -1.2161031, 0.26198965, -0.39037564, 0.16168776, -0.4814354, 1.2001693, 0.6076416, -0.8430386, -1.486868, -0.18519744, -0.5284652, -0.5890602, -1.3699012, 0.3797034, -0.6210796, 0.34635258, 0.97299594, -0.73827547, 0.06458698, 0.118863635, 0.5199116, 1.0428258, -0.9279422, -0.86735195, -1.1641119, 0.7890661, -0.13334043, 0.965089, -0.38214856, -0.4918111, -0.5547398, 0.42891094, 1.3179172, 1.3215472, 0.6549405, -0.35108355, -0.053067066, 1.0250593, 0.56519455, 0.62243444, 0.94297016, 1.444416, -1.0421168, -1.2815233, 1.5802842, 1.058067, 1.5861386, 0.2678979, 0.611768, -0.9184742, -0.50267774, -0.18283916, -1.0322441, 0.49051848, 0.23566997, -0.42865896, 1.3114626, -0.8547099, -0.7508762, 0.97122836, 0.83569074, -0.8890005, -1.3588058, 0.52090734, 0.6599851, -1.1082011, 0.6431001, 0.20303106, 1.0637558, -1.6201593, -0.340904, 1.4634577, -0.8336172, -0.8939236, 1.6814111, -1.4717578, -0.10118986, -1.2259562, 1.5268134, 0.5433005, 0.22572087, -1.4068099, -0.4178259, 0.58685875, -0.05888392, 2.8919656, 1.6086674, 0.03694556, -1.1663972, 1.8105648, 0.29895756, 1.8874907, -0.7695107, 0.5690569, 0.030703884, 0.751468, 0.6750975, -1.3655664, 1.1141645, 0.7864459, 0.3947739, 0.03917306, 0.05810123, -0.11991168, -1.729456, -1.5321412, 1.1202441, -0.60260165, -0.47422236, -0.8188005, -0.9895167, 1.1552737, 1.0952479, 0.229527, 0.29695028, -1.6278256, -0.34756196, 0.40587282, -0.2820706, -0.7547495, -0.9610026, -1.7018858, -0.3924324, 1.079949, 0.8248382, 0.94413376, -1.1566157, -0.9842801, 1.6253854, -1.1643112, -0.031547185, -1.3878396, 1.7543691, -0.29027265, -0.013875638, -0.6859403, 0.6589252, -1.2933903, 0.1164802, 0.39297175, -0.11103736, 0.337499, 0.45827693, 1.8881621, -2.3753831, -0.53132796, 0.40727693, -0.2953328, -1.1905057, -1.7966558, 0.22342315, -0.9290645, 0.021880161, 0.13581035, 1.1365031, 0.6181001, 0.713041, 1.293023, 1.3513365, -0.6619178, 2.7537708, -0.43479046, 1.5873258, 0.6956605, -1.9825284, 0.4805659, -1.5420442, 0.08287144, 0.5063851, 0.40049914, 0.075521916, 0.046996634, -2.108652, -0.21822332, -1.1524743, 0.36947966, 0.9477517, -1.1086196, -0.88682616, 0.70022494, -0.986827, -0.1266721, 1.0552126, -0.032320406, 0.030530429, 0.3426037, -0.7678068, 1.5853431, -0.29916266, 0.16663021, 0.3103334, 0.5508472, -1.029247, -0.17085668, -1.2482865, 0.4678677, -0.7913232, -0.4546694, -0.3316058, -1.3343717, 0.015012662, 0.15274923, -0.9795487, -0.7544606, -0.5374836, 1.0032166, 1.3695817, 0.4196725, 0.9586006, -0.6572966, 0.92550796, -0.18838528, 0.03506735, -1.3085735, -1.8863217, 0.8283637, -0.049647644, -1.8473711, 1.2152774, 0.7069548, 0.57567924, -0.5769207, 0.004103885, 1.0740294, -0.6685727, 0.06981487, -0.442179, 1.2116009, -0.73983926, -1.0080059, -0.5856949, 1.263791, 0.75989074, -0.89122176, 0.4892265, -1.2846144, 1.6389104, -0.74073213, -2.5086443, 0.24558564, -2.191976, 0.9695048, -0.73659486, 0.4528519, 1.0352287, 0.91434026, -0.41227826, 1.1801821, -0.5871047, 1.2012802, -0.09350611, -0.65246624, -1.9699491, -0.88186216, -1.8445245, 0.600799, 0.9312934, -0.748986, 0.762986, 0.29536536, 1.5785195, 1.2566115, 0.6400792, -0.3231401, -0.54415464, 0.74289376, -0.5117031, 0.41670632, -0.75640124, 0.7170347, -1.2117789, -0.8108696, 0.6399255, -2.0755427, 0.7917815, -0.7693288, -0.11855151, 1.1035497, -0.7230254, 0.14678578, 2.1342237, 0.20335588, 1.6858623, 0.9036143, -1.3462288, 1.6330013, -0.23667838, -0.62839717, 0.5073823, -1.1040329, 1.8166281, -0.33216733, -1.1290957, -1.484877, -2.5237038, -0.13954702, -0.26784393, 0.31558135, -0.3871223, 0.64323556, 0.5781996, -0.24147224, -0.09671755, 1.8780855, -0.527801, 0.6255921, 0.3025445, -1.5513139, -0.38770792, -0.71166915, 0.9644843, 1.5589895, -0.41667962, 3.0079024, 0.21589102, 0.68024695, 1.0425457, 0.1675615, 1.2254218, -0.11186006, -0.21831718, 0.030340586, 0.6445724, 0.8555139, -0.30397046, -0.7371216, -0.3673983, -0.12570697, -0.63791007, 0.5487183, 0.3812071, -0.7880577, -0.07703689, 2.145892, 0.040550653, -1.1552556, 0.8339612, 0.35333186, 0.8113544, 0.9471309, 1.8389242, -2.1920223, -0.8024482, -0.75866145, -0.46682125, -0.291485, -0.56249285, -0.6120222, -1.3763278, -0.4043958, -0.167957, -2.0174806, 1.0753703, 1.4874343, -0.96017367, -1.1698335, -0.1857909, -0.67057425, 0.04790106, 1.3035606, 0.4013939, 0.84132683, -0.7301506, 0.03734765, 0.12839374, 0.59680045, -1.4596658, -1.9846171, -1.3339622, -0.928884, 1.0592812, -0.08096708, -0.3560848, 0.17055984, 0.44089505, 1.0143852, -1.2609717, 0.39403346, 0.15323427, -0.20655632, 0.2729617, -0.017258333, 0.21113883, -0.037135277, -0.3795276, 1.8731954, -0.95502555, -0.047084603, -1.8833874, -0.17380746, 0.53410834, -0.37984794, -0.83650166, 1.3657289, -0.9089595, 0.11723666, -0.691051, 0.058711946, -0.3596759, -0.5994914, -0.82318157, 0.4013819, -1.2878338, 1.4384826, -1.196757, 0.86787546, -0.8170519, 1.0645616, 0.35892066, 0.16686276, -0.020305071, -0.8255187, 0.39803553, 2.157575, -0.18023075, 1.1010606, 0.14643395, 1.1315295, 0.9770161, 0.42666945, 0.27146822, 0.732228, 0.39469486, -0.84413946, -0.90971494, 0.6502484, -0.16056834, 2.1572785, 0.24662192, 0.66400963, 0.14993827, -0.3131849, 0.6960484, 1.3728433, 0.2414029, 0.32461792, -0.25270006, -0.5310546, 0.44632587, 0.72279614, 1.0306181, 0.6859314, -0.9765316, -1.661137, 1.7164898, 0.2669273, -1.0952786, 0.10285393, -1.5112151, 1.3984389, -0.33049527, 0.086646505, 1.99051, -0.7867809, -0.02740572, -1.0844429, -0.38896164, -0.06757384, 1.1891596, -0.5182803, 1.4854476, 0.68765616, 0.05129343, 0.92384857, -0.04301777, -0.6649576, -0.41715017, 0.596572, -1.9418277, -1.151948, 0.07984562, 0.6323108, 0.63117504, 0.38132355, 0.76422507, -1.071917, 0.46144056, -1.1519856, 0.51360416, -1.2658279, -0.7383204, 1.1194702, 0.37442186, -0.59131896, -0.8329332, 0.41315868, 0.49044436, 1.4959744, -0.25459176, 1.9797194, -0.3676517, -0.7006123, -1.5376753, 2.7518427, 0.4352582, -1.1831497, -0.47213498, -0.53300947, 0.31342745, 1.1631571, 1.0107048, 0.43390697, -1.8759046, -0.74681604, -0.24300711, 0.9583661, 1.8207945, -0.8047002, 1.5142735, 0.06101127, -0.8167485, 1.341735, -1.9998361, -0.31037384, -1.9361457, 2.6424568, 1.7161232, -0.81243795, 1.4176836, 0.46120012, -0.10861592, -0.37943932, -0.53604156, 2.5376189, 1.9996238, 0.37519363, 1.3202821, -0.033361, -0.18681939, -0.64312565, 0.08054325, 0.22469059, 0.49264678, 1.2246869, -1.5528489, 0.7257059, -0.27520436, 1.1922318, 0.23851508, -0.29716906, 0.87747645, -0.26529908, 1.2344409, 2.0770943, 0.33405286, 1.5167257, -0.4284246, -0.6981646, -0.11194946, -0.2014947, -0.06963122, -0.06063814, -0.7429915, -1.9737889, -0.23421544, 0.32240874, -1.3905734, -0.02160562, 2.0077162, -0.70806885, 0.6858733, -0.073999576, 0.58822834, 1.0689219, 0.4202779, -1.8052489, 0.8980629, 1.0188261, 0.24025117, 1.1279254, -2.096736, 0.86583626, 1.0729425, -1.3586196, -0.43458986, 0.85325885, -1.3032721, 1.519603, -0.30039188, 0.011318408, -0.22466156, -0.004637025, 0.20317583, 0.101351805, 0.46223554, 1.6066155, -0.3497661, 0.31206778, -0.16919272, 2.5479598, 0.23946035, 1.0384718, -0.028765468, -0.7647152, -0.1882574, 0.39373857, -1.1616229, -0.15314704, -0.41924948, 0.31844574, -1.4991366, -0.6800134, -1.8221868, -0.13502005, 0.7068314, 1.4567363, -0.29855722, 0.05235714, 0.02478114, 0.13136047, 1.0196488, -0.779426, 0.020566413, -0.8152667, 0.32418823, -0.6030918, 1.3635833, 0.40278813, 0.0014983298, -0.05041781, 0.76405966, -0.6163368, -1.472155, -0.1951552, -0.32755968, -0.22645734, 1.4022243, -0.40418622, 0.7907749, -0.13738912, 0.420996, 0.03924503, 0.62669563, -0.06643237, -1.3050407, 0.16855282, -0.05330854, -0.34347278, -0.06536905, -1.7360572, -1.1509646, 1.3281381, -2.525531, 1.2429549, 0.14453362, 0.2398615, -0.6806504, 0.81042314, 1.4116533, -1.1112533, -0.2704999, 0.7653411, -0.16361058, -0.6862728, 0.9865363, 1.7095964, 1.1570653, -0.37491158, 0.45076278, -0.84477234, 0.48220462, 1.0266485, 0.9100105, -1.786471, 0.64672625, -0.9442402, 0.15980951, 0.2763099, -0.2563906, 0.48786116, 1.2707106, 0.40826705, -1.3636479, 0.59256256, -0.14769381, 0.22855996, -0.23195097, -0.46100956, 1.4071323, 0.588202, -0.063307635, 0.027076863, 0.42972392, -0.74118775, -0.7520948, 0.92107975, 0.3780131, 0.43948358, 1.7412065, -1.8292835, 1.4121022, 0.9102089, 0.2922569, -2.4068086, 0.82316643, 0.14709213, 0.76868147, 0.070829175, 0.5930173, 0.7329806, -0.25992763, 0.22328012, 1.8324057, -0.89981586, 1.4022714, -0.28445876}; + float output[] = {-0.8470076, -0.617558, 0.024568161, -0.54007053, -0.5732189, 1.0910312, 0.51959157, -0.073640585, -0.60885113, -1.8285086, -0.9326965, -0.3021695, 1.066226, 0.8134058, -1.5457271, 1.1948874, -0.04176423, -0.59385985, 0.011908118, 0.095879026, 0.6736443, -0.48068637, 0.11451639, 1.5323228, -0.8184595, -1.4535367, -0.06812811, 0.71712196, 2.4668334, 0.3803238, 1.5602548, -2.1309204, 2.8248832, -1.3176224, -0.6582828, 0.73314184, 1.8034855, -1.6781946, -0.23040803, -1.3201909, -0.24954909, -0.34502414, -0.7355865, -0.41729373, 0.5724887, -0.60789496, 1.0349115, 0.46317944, 0.17278059, -0.78425044, -0.11165529, 0.7919961, 0.35827583, -1.9887244, 0.12787221, 1.095776, 0.28236288, 0.48224112, -0.5900752, 0.9498589, 0.5209434, -0.57806545, 1.3280295, -0.6969055, -2.539957, -0.0030387403, 1.871011, 0.13415621, -0.5734313, 0.09759699, -0.29701954, 0.9157297, -0.62670755, 1.2683886, -0.7024728, 0.6662447, 0.46600792, -0.494909, 0.8643152, -1.2757068, 0.8424522, 0.9383413, 0.49222285, 0.11790963, 0.57665557, -0.2206793, -1.2813573, -1.4700212, 1.9633232, 0.5646655, 0.15718703, -1.256212, 1.7298958, -0.4105028, 0.6821366, -0.72149056, -0.27424803, 0.19525297, 0.5027373, -1.0273383, -0.42891493, 0.31214187, 0.3240255, 0.6148003, -1.4785552, 0.79766524, -1.3977971, -1.9163635, -0.4596946, 0.4611778, 0.4615138, 0.57446766, -1.8127673, 1.0151784, 0.79838765, -0.16945624, -0.29454982, -0.22049658, 1.0656692, 1.9895301, -1.6840646, -0.0068151196, 0.29346943, 0.8048959, 0.50557023, -1.8385066, -0.4750251, 0.3583206, 0.41981372, -0.3146262, -0.79544896, 1.6337428, 1.4349604, -1.5252166, -0.91220444, 0.7527505, 0.6034745, 0.08402507, 1.0259006, -1.1905016, 0.52963644, -0.6864299, -0.15308455, 0.9455237, 1.000834, -1.828627, -0.5953371, 0.61878735, -2.7202675, -0.13529402, -1.1603078, -0.28340778, 1.6124189, 1.48123, -0.032326907, -1.5110354, -0.60052997, -0.98667, -0.026620502, 0.9869495, 0.9609994, 1.8000636, -0.39040756, 0.662662, -0.35303995, -0.10898638, -0.097712174, -0.13256012, -0.30892372, 0.9536066, 1.0131402, -0.21144608, 0.9224201, -1.2749323, 0.12289531, 0.6637511, 0.0252969, -0.058163885, 0.6347488, 0.13144295, 0.29648793, 1.6838806, 1.4852757, -0.29899225, -2.699224, 0.22093739, -0.63045704, -2.3597014, -0.9839067, -1.0647969, 0.8293971, -0.7054954, 1.7537973, 0.22664751, -0.1311305, 0.50954145, -1.7052051, -0.42696014, -0.5314228, -0.56175625, 0.6429764, 1.3670748, 0.46155804, -0.7046119, 0.060639046, -0.113631465, 0.17838268, -0.084968045, 0.67876095, 0.6301664, 1.2548337, -0.2446083, -0.092792444, -0.42515463, -1.0051632, -0.5343044, -0.25070238, 1.3654076, -1.1015171, -1.5554606, 0.62512356, 0.36090285, 0.43128428, 0.097997755, -0.3924458, 0.27789333, -1.1954387, 0.22248776, -1.6744449, -1.2109405, 1.0672655, 0.95568365, 0.8194465, 0.15550855, 0.3167771, 0.22519737, 1.2998043, -0.31728703, -0.5346176, 0.907684, -1.5638523, -1.1844252, -0.2738023, 0.051613424, 0.2711231, -2.3651042, -0.44602147, -0.44494528, 0.8535133, 0.24942228, -1.0080348, 0.85422933, -0.48436078, -1.3689119, -1.3511016, -0.48757446, -0.032849748, 0.22983012, -0.032983564, -0.71215105, 0.18651846, -2.0692394, -0.57982725, 0.2421949, -0.004737948, -0.90421754, -0.78182286, 0.12858658, -0.30840445, -1.2161031, 0.6076416, -0.8430386, -1.486868, -0.18519744, -0.5284652, -0.5890602, -1.3699012, 0.3797034, -0.6210796, 0.34635258, 0.97299594, -0.73827547, 0.06458698, 0.118863635, 0.5199116, 1.0428258, -0.9279422, -0.86735195, -1.1641119, 0.7890661, -0.13334043, 0.965089, -0.38214856, -0.4918111, -0.5547398, 0.42891094, 1.3179172, 1.3215472, 0.6549405, -0.35108355, -0.053067066, 1.0250593, 0.56519455, 0.62243444, 0.94297016, 1.444416, -1.0421168, -1.2815233, 1.5802842, 1.058067, 1.5861386, 0.2678979, 0.611768, -0.9184742, -0.50267774, 1.3114626, -0.8547099, -0.7508762, 0.97122836, 0.83569074, -0.8890005, -1.3588058, 0.52090734, 0.6599851, -1.1082011, 0.6431001, 0.20303106, 1.0637558, -1.6201593, -0.340904, 1.4634577, -0.8336172, -0.8939236, 1.6814111, -1.4717578, -0.10118986, -1.2259562, 1.5268134, 0.5433005, 0.22572087, -1.4068099, -0.4178259, 0.58685875, -0.05888392, 2.8919656, 1.6086674, 0.03694556, -1.1663972, 1.8105648, 0.29895756, 1.8874907, -0.7695107, 0.5690569, 0.030703884, 0.751468, 0.6750975, -1.3655664, 1.1141645, 0.7864459, 0.3947739, 1.1202441, -0.60260165, -0.47422236, -0.8188005, -0.9895167, 1.1552737, 1.0952479, 0.229527, 0.29695028, -1.6278256, -0.34756196, 0.40587282, -0.2820706, -0.7547495, -0.9610026, -1.7018858, -0.3924324, 1.079949, 0.8248382, 0.94413376, -1.1566157, -0.9842801, 1.6253854, -1.1643112, -0.031547185, -1.3878396, 1.7543691, -0.29027265, -0.013875638, -0.6859403, 0.6589252, -1.2933903, 0.1164802, 0.39297175, -0.11103736, 0.337499, 0.45827693, 1.8881621, -2.3753831, -0.53132796, 0.40727693, -0.2953328, -1.1905057, -1.7966558, 0.22342315, 0.713041, 1.293023, 1.3513365, -0.6619178, 2.7537708, -0.43479046, 1.5873258, 0.6956605, -1.9825284, 0.4805659, -1.5420442, 0.08287144, 0.5063851, 0.40049914, 0.075521916, 0.046996634, -2.108652, -0.21822332, -1.1524743, 0.36947966, 0.9477517, -1.1086196, -0.88682616, 0.70022494, -0.986827, -0.1266721, 1.0552126, -0.032320406, 0.030530429, 0.3426037, -0.7678068, 1.5853431, -0.29916266, 0.16663021, 0.3103334, 0.5508472, -1.029247, -0.17085668, -1.2482865, 0.4678677, -0.7913232, -0.4546694, -0.3316058, -1.3343717, 0.015012662, 1.3695817, 0.4196725, 0.9586006, -0.6572966, 0.92550796, -0.18838528, 0.03506735, -1.3085735, -1.8863217, 0.8283637, -0.049647644, -1.8473711, 1.2152774, 0.7069548, 0.57567924, -0.5769207, 0.004103885, 1.0740294, -0.6685727, 0.06981487, -0.442179, 1.2116009, -0.73983926, -1.0080059, -0.5856949, 1.263791, 0.75989074, -0.89122176, 0.4892265, -1.2846144, 1.6389104, -0.74073213, -2.5086443, 0.24558564, -2.191976, 0.9695048, -0.73659486, 0.4528519, 1.0352287, 0.91434026, -0.41227826, 1.1801821, -0.5871047, 1.2012802, -0.09350611, 0.9312934, -0.748986, 0.762986, 0.29536536, 1.5785195, 1.2566115, 0.6400792, -0.3231401, -0.54415464, 0.74289376, -0.5117031, 0.41670632, -0.75640124, 0.7170347, -1.2117789, -0.8108696, 0.6399255, -2.0755427, 0.7917815, -0.7693288, -0.11855151, 1.1035497, -0.7230254, 0.14678578, 2.1342237, 0.20335588, 1.6858623, 0.9036143, -1.3462288, 1.6330013, -0.23667838, -0.62839717, 0.5073823, -1.1040329, 1.8166281, -0.33216733, -1.1290957, -1.484877, -2.5237038, -0.13954702, -0.26784393, 0.31558135, -0.3871223, 0.64323556, 0.5781996, 0.3025445, -1.5513139, -0.38770792, -0.71166915, 0.9644843, 1.5589895, -0.41667962, 3.0079024, 0.21589102, 0.68024695, 1.0425457, 0.1675615, 1.2254218, -0.11186006, -0.21831718, 0.030340586, 0.6445724, 0.8555139, -0.30397046, -0.7371216, -0.3673983, -0.12570697, -0.63791007, 0.5487183, 0.3812071, -0.7880577, -0.07703689, 2.145892, 0.040550653, -1.1552556, 0.8339612, 0.35333186, 0.8113544, 0.9471309, 1.8389242, -2.1920223, -0.8024482, -0.75866145, -0.46682125, -0.291485, -0.56249285, -0.6120222, -1.3763278, -0.4043958, -0.167957, -0.1857909, -0.67057425, 0.04790106, 1.3035606, 0.4013939, 0.84132683, -0.7301506, 0.03734765, 0.12839374, 0.59680045, -1.4596658, -1.9846171, -1.3339622, -0.928884, 1.0592812, -0.08096708, -0.3560848, 0.17055984, 0.44089505, 1.0143852, -1.2609717, 0.39403346, 0.15323427, -0.20655632, 0.2729617, -0.017258333, 0.21113883, -0.037135277, -0.3795276, 1.8731954, -0.95502555, -0.047084603, -1.8833874, -0.17380746, 0.53410834, -0.37984794, -0.83650166, 1.3657289, -0.9089595, 0.11723666, -0.691051, 0.058711946, -0.3596759, -0.5994914, -0.82318157, -0.8170519, 1.0645616, 0.35892066, 0.16686276, -0.020305071, -0.8255187, 0.39803553, 2.157575, -0.18023075, 1.1010606, 0.14643395, 1.1315295, 0.9770161, 0.42666945, 0.27146822, 0.732228, 0.39469486, -0.84413946, -0.90971494, 0.6502484, -0.16056834, 2.1572785, 0.24662192, 0.66400963, 0.14993827, -0.3131849, 0.6960484, 1.3728433, 0.2414029, 0.32461792, -0.25270006, -0.5310546, 0.44632587, 0.72279614, 1.0306181, 0.6859314, -0.9765316, -1.661137, 1.7164898, 0.2669273, -1.0952786, 0.10285393, -1.5112151, 1.3984389, -0.33049527, -0.38896164, -0.06757384, 1.1891596, -0.5182803, 1.4854476, 0.68765616, 0.05129343, 0.92384857, -0.04301777, -0.6649576, -0.41715017, 0.596572, -1.9418277, -1.151948, 0.07984562, 0.6323108, 0.63117504, 0.38132355, 0.76422507, -1.071917, 0.46144056, -1.1519856, 0.51360416, -1.2658279, -0.7383204, 1.1194702, 0.37442186, -0.59131896, -0.8329332, 0.41315868, 0.49044436, 1.4959744, -0.25459176, 1.9797194, -0.3676517, -0.7006123, -1.5376753, 2.7518427, 0.4352582, -1.1831497, -0.47213498, -0.53300947, 0.31342745, 1.1631571, 1.0107048, 1.8207945, -0.8047002, 1.5142735, 0.06101127, -0.8167485, 1.341735, -1.9998361, -0.31037384, -1.9361457, 2.6424568, 1.7161232, -0.81243795, 1.4176836, 0.46120012, -0.10861592, -0.37943932, -0.53604156, 2.5376189, 1.9996238, 0.37519363, 1.3202821, -0.033361, -0.18681939, -0.64312565, 0.08054325, 0.22469059, 0.49264678, 1.2246869, -1.5528489, 0.7257059, -0.27520436, 1.1922318, 0.23851508, -0.29716906, 0.87747645, -0.26529908, 1.2344409, 2.0770943, 0.33405286, 1.5167257, -0.4284246, -0.6981646, -0.11194946, -0.2014947, -0.06963122, -1.3905734, -0.02160562, 2.0077162, -0.70806885, 0.6858733, -0.073999576, 0.58822834, 1.0689219, 0.4202779, -1.8052489, 0.8980629, 1.0188261, 0.24025117, 1.1279254, -2.096736, 0.86583626, 1.0729425, -1.3586196, -0.43458986, 0.85325885, -1.3032721, 1.519603, -0.30039188, 0.011318408, -0.22466156, -0.004637025, 0.20317583, 0.101351805, 0.46223554, 1.6066155, -0.3497661, 0.31206778, -0.16919272, 2.5479598, 0.23946035, 1.0384718, -0.028765468, -0.7647152, -0.1882574, 0.39373857, -1.1616229, -0.15314704, -0.41924948, 0.31844574, -1.4991366, -0.29855722, 0.05235714, 0.02478114, 0.13136047, 1.0196488, -0.779426, 0.020566413, -0.8152667, 0.32418823, -0.6030918, 1.3635833, 0.40278813, 0.0014983298, -0.05041781, 0.76405966, -0.6163368, -1.472155, -0.1951552, -0.32755968, -0.22645734, 1.4022243, -0.40418622, 0.7907749, -0.13738912, 0.420996, 0.03924503, 0.62669563, -0.06643237, -1.3050407, 0.16855282, -0.05330854, -0.34347278, -0.06536905, -1.7360572, -1.1509646, 1.3281381, -2.525531, 1.2429549, 0.14453362, 0.2398615, -0.6806504, 0.81042314, 1.4116533, -1.1112533, -0.2704999, 1.1570653, -0.37491158, 0.45076278, -0.84477234, 0.48220462, 1.0266485, 0.9100105, -1.786471, 0.64672625, -0.9442402, 0.15980951, 0.2763099, -0.2563906, 0.48786116, 1.2707106, 0.40826705, -1.3636479, 0.59256256, -0.14769381, 0.22855996, -0.23195097, -0.46100956, 1.4071323, 0.588202, -0.063307635, 0.027076863, 0.42972392, -0.74118775, -0.7520948, 0.92107975, 0.3780131, 0.43948358, 1.7412065, -1.8292835, 1.4121022, 0.9102089, 0.2922569, -2.4068086, 0.82316643, 0.14709213, 0.76868147, 0.070829175, 0.5930173, 0.7329806, -0.25992763}; +} \ No newline at end of file diff --git a/tmva/sofie/test/input_models/references/Slice_Neg.ref.hxx b/tmva/sofie/test/input_models/references/Slice_Neg.ref.hxx new file mode 100644 index 0000000000000..092b8a2cabe60 --- /dev/null +++ b/tmva/sofie/test/input_models/references/Slice_Neg.ref.hxx @@ -0,0 +1,4 @@ +namespace Slice_Default_Steps { + std::vector input = {1.0451847, 0.6245613, 0.48420018, 2.1407738, 1.4023418, 0.6803044, 1.2552906, 0.23355322, 0.5949201, 0.665767, 0.7255075, 0.61573493, -0.22523554, 0.609465, -1.9059293, 1.3349898, -0.4083868, -0.30549952, 1.7568158, -0.09013642, 0.7510219, -0.052165933, 0.045655653, 0.6894599, 0.6663751, -0.13001254, -0.99388146, 1.1250099, 0.90145993, -3.4663842, 1.4765558, -0.8621666, -0.04465484, 0.51125, 0.8123038, -0.13915698, 1.2800659, 1.1580552, 1.8424264, -0.29321876, 0.031092152, 1.0013733, -0.7283629, 0.3382554, -1.8718901, -0.047066037, -1.9088744, 0.42447698, -0.3465933, -0.5751067, 1.5138085, -1.0871423, 0.6077587, 1.776671, 0.34022397, -0.03549139, -1.329498, 0.8371586, -1.4539177, 0.21200769, 0.76399386, -0.9069966, -0.0950934, 1.3569304, -0.29720822, 0.1822998, -1.1559794, 0.04441483, -1.4136242, 0.23844138, 1.0097063, 0.65586853, -2.0127554, -0.2072184, -0.4014769, -0.3000392, 0.8629856, -0.08507111, -1.1835829, -1.0837615, 0.50113016, -1.141945, 1.4552537, -0.36788568, -1.6010555, -0.15414086, -0.7613445, 1.6708724, 1.4167747, -0.096510775, -0.15186574, 0.4412115, -1.2044533, -0.044650316, -0.6854727, -1.4451612, -0.11577169, -1.2647926, -0.14461602, -0.47596788, 0.10738016, 0.06727146, 0.22507443, 1.2529004, -1.89923, 1.447481, 1.1985252, 0.3427861, -0.4630263, -0.65935296, 1.4358126, -2.2243154, 0.49377045, 1.4613236, -0.1912351, 1.8992213, -0.94443643, 0.6515869, 0.31404996, 0.074261054, 0.42852008, -0.19033097, -0.482317, -2.5970418, -1.2141722, 0.74168557, -0.91024095, 0.18518865, 0.20616573, 0.67188245, -1.9931237, 1.6288077, -0.1337348, -1.0095295, -0.292675, -2.8238084, 1.6436734, -0.66659415, 0.31128094, 0.25534976, -0.08932365, -0.24432416, -1.116715, 0.8437299, 1.5952227, -1.2897215, 0.5800979, -0.75728, 0.82642055, -0.20025311, -0.84525776, -0.4629382, 0.09837887, 0.8285737, 0.34570113, -0.4494489, -0.06607181, 1.880768, 0.95183575, 1.6169115, 0.2602527, -1.2811539, -0.12291974, -0.55588114, -2.4634414, -0.29807645, -0.32441446, -0.60882235, -0.6670523, -0.84318537, -1.1632277, -0.16034018, 0.8423004, 1.5689149, -1.378128, -1.9285303, -0.9074993, -0.25396672, -0.90653914, -1.0881042, 0.56759405, -1.4169359, -2.5133574, -0.96242374, -1.8407485, 0.21979266, -1.5453613, -0.400642, 0.3806829, 1.1271498, 1.1819715, 0.847391, -1.4687508, 0.74352884, -0.6923194, -1.4369518, 0.97722024, 1.0514591, -0.90551496, -0.79178625, 0.19880198, 0.6863783, 0.72862554, 1.763804, 0.2279675, 1.4966544, 0.7106558, -0.41115803, -0.21305746, 0.79997617, 0.7268194, 1.5965521, -1.4865237, -0.44435644, -0.36344638, -0.11310481, 1.4190954, 0.6319442, 0.745741, -0.5167261, -0.16796711, 1.5669242, -1.4218544, 0.61177474, -1.243831, -0.408289, 0.865704, -0.97820926, 1.053678, -1.9482862, 0.54905266, -0.9755587, -1.8869104, 0.0044822586, -1.1138756, -0.71788013, 0.7361194, -0.7153275, -1.6451069, 1.7545587, -0.75075376, -1.3882002, -0.5430022, -1.2329432, 0.21638516, -0.326573, 0.5647263, -1.8826942, -0.5760186, 0.51380414, -1.5062225, 0.3432146, 0.14499806, -1.1523787, 2.335982, -2.4507418, 0.5823965, 0.7784748, 1.2795119, -0.39526865, -0.74181443, 1.476051, -0.07681689, 0.0067599732, -0.98287404, -1.3786954, 0.4984134, 1.0468203, -0.7151032, -2.0332944, 0.05419711, -2.3168552, 1.122624, -0.53438026, -2.3934145, -0.49050105, -0.9205437, -0.15586168, 1.6762931, 0.5607007, 0.07048273, -0.7124037, -1.819932, 1.0152652, 1.8492514, 0.09532632, -0.47131425, 0.10136383, 1.6027571, -0.055490978, -0.53033817, 0.47595662, -0.124515995, 0.8248915, -0.50315917, -0.09490088, 2.1328678, 0.26436484, -0.3090177, 0.66534674, -1.2549512, -0.25315812, -1.0608811, 0.08174163, 2.3469543, 0.18253551, 1.4174005, 0.5833562, 0.7734026, 0.8875707, 0.46253937, -0.59789574, 0.3320457, 0.7252614, 0.2282751, 0.6393503, 0.3354368, -2.2898176, 0.08617805, -0.98621976, 1.4499558, -0.10378551, 1.4655052, 0.57472426, -0.8805005, -0.73588294, 0.6668061, 0.81059366, -0.59290576, -0.31642014, 0.5465175, -0.16706206, -0.68133485, 1.0575606, 0.415264, -1.7762902, 0.35459134, -0.036745973, 0.28332543, -0.0061813043, -0.8579742, -1.266533, -0.69849193, -1.4563639, 0.9827122, 0.7408832, -1.514766, -1.0668796, 0.1426218, -0.09352196, -1.4858966, -0.80005354, -0.731151, 0.5344746, 0.38867953, 0.5330557, 0.50632566, 0.6302994, -0.569997, 0.7838313, -0.28514034, -2.2912836, -0.6982049, 0.7933591, -1.1312126, 1.3734623, 1.100901, -0.7409093, 0.38863868, 0.24726652, -0.26152653, -1.6399634, 0.32046428, -0.06809312, 1.6628146, -2.0482807, -0.13053721, -1.700966, 0.3613013, 0.024943631, 0.73767537, 0.35799584, -1.1839654, -0.816691, 1.2237171, -1.9319222, -0.14407313, 1.75666, 1.7709233, 0.21359767, 0.9950233, -0.4615518, 0.44868615, 1.4312615, 1.3808835, -0.18940794, 1.0416954, -0.24796851, 0.48987696, 1.2978021, 0.05604007, -0.3529608, -1.3806872, 2.2423518, 0.38141087, 1.1842633, -0.3420007, -0.28834683, -0.52113175, -0.08655031, 0.66746104, 0.4264375, 0.08894845, 1.361398, -1.1102597, 0.8127054, -0.25339708, 0.7393206, 0.54270566, 0.72499883, 1.0655539, -0.43516365, 1.53332, -1.3317435, 0.9998057, 0.41541678, 0.98901755, -0.7852148, 1.9416982, -0.72119594, -0.034244604, -0.011740846, -0.25054318, -1.4232942, 0.9649547, 0.010748758, 0.13203041, 0.25134632, 1.7783864, 0.0403642, 2.4485521, -0.5401216, -0.3214275, -0.7718592, 1.0362864, -0.7257519, -0.53041863, 0.27436903, 0.08478759, 1.3883367, -0.66223633, 0.51782465, -1.1076697, 0.15442872, 1.6057725, -0.5522208, 0.6561317, 0.17577524, 0.4332249, -0.28804585, -0.5691257, 2.25104, -1.1636895, 0.22430561, 1.0721023, 0.792772, -0.47398332, -0.76994264, 1.0576593, 0.88267803, -1.4782726, 0.8926852, -0.46385735, -0.0716391, -1.665406, 0.11861658, 0.37563065, 0.85860866, -1.8741595, -0.5219604, -1.0582875, 1.7154264, 0.1313024, 1.4848208, 0.11640747, -1.7609112, 0.7769073, 0.48588625, -1.2146038, 0.73792857, -0.9774584, 0.07676499, -1.0037707, 0.015130967, -1.2565023, 1.7358211, 1.4210244, 0.053746346, -1.5248967, 1.1289326, -0.53315526, -1.3237956, -0.21802673, 0.5033034, -0.9388878, -2.9923463, 0.8051657, 0.9151123, 0.017421184, -1.4353907, 1.781005, 0.95736814, 1.1634779, 0.64479274, -0.23042154, -0.55330545, 0.41722617, -0.007924688, 1.9704095, -0.52791095, -0.25249967, 1.217987, -0.26531398, 0.31962937, -1.1676388, 0.17290594, -0.68421125, -0.34032997, -1.4233708, -0.9743128, 0.9177001, -0.14544213, -0.27916044, -1.4160591, 0.096208386, -1.4026262, -0.51816446, 0.9189864, 1.0548416, -0.8247552, -0.7701502, -0.98002684, 1.1631306, 0.8712015, -0.5758766, -1.6995598, 0.09796931, 0.27600157, -0.2175099, -1.2554561, -0.07213151, 2.4231257, 0.7729675, 0.030608136, -1.8162596, 0.7449758, 0.6113035, -0.22608364, -0.6480759, 0.4915602, 1.1545128, 0.35355297, 1.6369073, 0.411864, -1.0840435, -0.075121745, 2.2060554, -0.24247673, -1.1374276, 0.10677125, 1.9537716, -1.108019, -0.32708606, 0.5778413, 1.2812556, 0.21232277, 0.13396217, 0.80973107, 0.26933447, -0.20669563, 1.9351953, 0.7844493, 0.10339695, -1.7368128, 0.823303, 0.67611474, -0.14529933, -0.94407207, 0.6184946, -1.1973552, 0.94807374, -1.9689158, -0.95736796, -0.36089993, 0.97640216, -0.5079678, -0.13345084, -0.09096543, 1.6033889, 0.20670862, -0.27726498, 0.068673365, -0.1626727, 0.13826686, 0.55320334, -1.5936158, -0.82023424, 0.27161613, 0.41867435, -0.9805353, -0.4154204, 0.49877793, 0.0093282405, 0.59771943, 0.09775646, 0.58804435, -0.65016276, 0.73460424, 0.8446652, 2.0283346, 1.2307235, 1.1308593, -0.5006046, 0.334564, -0.97043395, -0.5636059, -1.4977788, 0.87005043, -1.1603388, 0.31635118, -1.8745527, 0.7862731, -1.041438, -0.9785689, -0.014248349, -1.222529, -0.5575574, 2.4933984, -0.064805016, 0.39413083, -1.2988446, 0.7563059, -0.79205245, -1.0542104, 0.5979833, 1.5992491, -1.7063024, -0.5771334, 1.6361665, -0.60626614, 0.44358745, 0.36404964, -0.17300287, -1.4895558, 0.93172455, -0.66854924, 0.4801032, 0.09470631, 0.19432715, -0.39213803, 0.23912194, 1.1788458, -0.20358092, 1.2247528, -1.7846833, 1.7758663, 0.87859154, -0.4107461, -0.32997409, -1.5755576, -1.4550736, -0.31620994, 0.81590563, 0.21436447, -0.0009418542, 0.3039241, -0.14782928, -0.779694, -0.26116168, -0.5875628, 1.064051, 1.520253, 0.68341565, -1.9807853, 0.74206716, -2.8454256, 1.2709564, 1.7051587, -0.23825008, 0.13465987, -0.25501144, 0.13449395, -0.08085852, -0.9345905, -0.9593099, 0.6859107, -1.1454093, -1.3381015, 0.2353102, -0.13322814, 0.11062508, 0.17510203, 0.00516871, -1.0370462, -0.32723942, 1.2823414, -0.042340446, -0.3114818, -8.870333e-05, -0.5615099, -0.20567372, -1.2969033, -0.18617158, 0.58420277, -0.9223417, -0.8050735, -0.36499628, -0.76930875, 1.4448764, -0.1731726, -0.19603184, -0.23324072, -0.109300986, 1.0571263, 1.178747, -0.5669078, -0.6129132, 0.2746348, -0.072358064, 0.3385931, -0.31736866, -0.4328864, 0.9560206, -0.44862372, -0.350604, 0.37914753, 0.76631945, 0.5211334, -1.1975573, -0.39863473, 1.7790956, 0.036023278, 0.85484296, -0.14574684, -2.1517622, 1.4256386, 0.07762644, 0.76923335, -1.452289, -0.44079757, 1.5147146, 0.057785936, 1.7878892, -0.61763746, -0.7521893, 0.7968369, 0.2493956, 0.23879473, 0.047723737, 0.45276004, -0.5033289, 0.84546775, 0.087485075, -0.29491672, -0.7279333, 1.047645, -1.5160652, -0.7238233, -1.4873251, -0.9596354, -0.09308696, 0.9633187, 0.17714372, 0.38465348, -0.13031037, -0.48849452, -0.5216643, -0.7692474, -0.4057824, 0.024406806, 0.33862096, -0.4138596, 0.4039324, 0.18644312, -0.61818093, 0.13876703, -2.164961, -0.31688243, 0.7040236, 0.59295374, -0.8303941, -0.9530634, -0.48112786, -1.3758682, 0.23894647, 0.44065222, -0.7498823, 0.4367827, -0.8626759, -0.819069, 0.6019, 0.40171462, -0.989695, 0.9679922, 0.60419935, 0.5596958, 0.5186218, 0.4689634, -0.28469092, 0.007876219, -0.017619386, 0.65712726, 0.28158224, 0.42113513, -0.5614362, 1.1735151, 0.2318658, -0.60902905, -0.83569163, 1.2109544, -1.7506728, 1.1711022, 0.18666989, -1.4357256, 1.7505751, 2.359068, -0.69469744, -0.17320465, -0.49060386, 1.9384009, -0.8286886, -1.9119048, -0.0867032, 1.675301, -0.15963833, 0.47802424, -0.93921524, 0.21669552, 0.5973385, -0.3897737, -0.96138793, -1.1460986, -0.6993545, 0.48859787, 0.49144292, 0.884664, -0.45526063, 0.06822358, 1.2684873, 1.2708554, 0.08385541, 0.788578, 0.038803414, -0.58519393, 1.4615723, 0.36900017, -0.8346276, 0.04170542, -0.41653165, 1.0975499, 2.0970829, 0.18264593, 1.5489473, 0.5285782, -1.0232004, 0.050813664, -1.0207909, -0.064489454, -1.2171016, -0.4630668, -0.4305054, 1.0489885, -0.3447226, 0.47696728, 0.085851595, 0.45969304, 0.9397857, 0.9925845, 0.84165156, 0.58367836, 0.44830862, 0.79763794, 1.1915636, 0.20407252, -1.1486843, 1.3992747, -0.76383877, 2.411353, 0.48628262, 0.3500077, -0.300855, 0.6324427, 0.34935966, 0.54504216, -1.1055669, -0.09944116, 0.95708686, 1.5737662, -0.5069417, -0.7603594, 0.16570005, 0.38484627, 0.7854822, -0.5289874, -0.20853232, -0.25366986, 0.93255436, 2.1678638, 2.5284173, 0.09104326, -0.25922984, 0.104944386, 0.46791264, -0.1947828, 0.2517247, -0.0018040794, -0.36763376, -2.4569225, 1.2765278, -0.96315217, -1.2554164, -0.2874503, 0.9034364, 0.6889874, -1.4450033, 1.6024436, 0.21677066, -0.008955182, -0.16781831, -1.0223466, -0.96528006, -2.1202044, 0.3416743, 0.021002049, -0.12881091, -1.4332885, -0.12481898, 0.93586546, -1.5900887, -1.0640641, 0.8249464, -0.47171867, 0.1742785, 0.6709329, -1.7259985, 0.78818256, -1.2866964, -1.4600148, -1.4257796, 0.34334445, -2.1116593, 0.25954735, -0.4888973, 0.19879743, -0.27516934, 1.6078179, 1.5662538, 0.14704464, -0.93423027, -0.6393435, -1.1420057, 0.9135534, 0.57406884, 0.1670467, 0.90328616, -1.3994925, -0.31774673, 0.46857116, 0.77330434, 0.45956635, -0.9270845, -1.0549059, -0.5243828, -0.85040414, -1.5719082, 1.0715257, 1.9476706, -1.4326566, 0.97081816, 0.7446318, -0.34977925, -0.9901644, 1.5866337, -0.97141254, -1.1351146, -0.09391565, 0.31912678, -0.13078365, 1.498845, 0.3680228, 0.76907545, 0.37397268, -0.56707764, -0.8323829, 1.3317215, -0.3441633, -2.1597042, -1.7520211, -0.47263923, -0.8540615}; + float output[] = {2.1407738, 0.5949201, 0.609465, 1.7568158, 0.6894599, 0.90145993, 0.51125, 1.8424264, 0.3382554, -0.3465933, 1.776671, -1.4539177, 1.3569304, -1.4136242, -0.2072184, -1.1835829, -0.36788568, 1.4167747, -0.044650316, -0.14461602, 1.2529004, -0.4630263, 1.4613236, 0.31404996, -2.5970418, 0.20616573, -1.0095295, 0.31128094, 0.8437299, 0.82642055, 0.8285737, 0.95183575, -0.55588114, -0.6670523, 1.5689149, -0.90653914, -0.96242374, 0.3806829, 0.74352884, -0.90551496, 1.763804, -0.21305746, -0.44435644, 0.745741, 0.61177474, 1.053678, 0.0044822586, -1.6451069, -1.2329432, -0.5760186, -1.1523787, 1.2795119, 0.0067599732, -0.7151032, -0.53438026, 1.6762931, 1.0152652, 1.6027571, 0.8248915, -0.3090177, 0.08174163, 0.7734026, 0.7252614, 0.08617805, 0.57472426, -0.59290576, 1.0575606, 0.28332543, -1.4563639, 0.1426218, 0.5344746, -0.569997, 0.7933591, 0.38863868, -0.06809312, 0.3613013, -0.816691, 1.7709233, 1.4312615, 0.48987696, 2.2423518, -0.52113175, 1.361398, 0.54270566, -1.3317435, 1.9416982, -1.4232942, 1.7783864, -0.7718592, 0.08478759, 0.15442872, 0.4332249, 0.22430561, 1.0576593, -0.0716391, -1.8741595, 1.4848208, -1.2146038, 0.015130967, -1.5248967, 0.5033034, 0.017421184, 0.64479274, 1.9704095, 0.31962937, -1.4233708, -1.4160591, 1.0548416, 0.8712015, -0.2175099, 0.030608136, -0.6480759, 0.411864, -1.1374276, 0.5778413, 0.26933447, -1.7368128, 0.6184946, -0.36089993, 1.6033889, 0.13826686, 0.41867435, 0.59771943, 0.8446652, 0.334564, -1.1603388, -0.9785689, -0.064805016, -1.0542104, 1.6361665, -1.4895558, 0.19432715, 1.2247528, -0.32997409, 0.21436447, -0.26116168, -1.9807853, -0.23825008, -0.9345905, 0.2353102, -1.0370462, -8.870333e-05, 0.58420277, 1.4448764, 1.0571263, -0.072358064, -0.44862372, -1.1975573, -0.14574684, -1.452289, -0.61763746, 0.047723737, -0.29491672, -1.4873251, 0.38465348, -0.4057824, 0.18644312, 0.7040236, -1.3758682, -0.8626759, 0.9679922, -0.28469092, 0.42113513, -0.83569163, -1.4357256, -0.49060386, 1.675301, 0.5973385, 0.48859787, 1.2684873, -0.58519393, -0.41653165, 0.5285782, -1.2171016, 0.47696728, 0.84165156, 0.20407252, 0.48628262, 0.54504216, -0.5069417, -0.5289874, 2.5284173, -0.1947828, 1.2765278, 0.6889874, -0.16781831, 0.021002049, -1.5900887, 0.6709329, -1.4257796, 0.19879743, -0.93423027, 0.1670467, 0.77330434, -0.85040414, 0.97081816, -0.97141254, 1.498845, -0.8323829, -0.47263923}; +} \ No newline at end of file diff --git a/tmva/sofie_parsers/CMakeLists.txt b/tmva/sofie_parsers/CMakeLists.txt index 5ae34bc5c7dbd..82846f2ce4fa0 100644 --- a/tmva/sofie_parsers/CMakeLists.txt +++ b/tmva/sofie_parsers/CMakeLists.txt @@ -48,12 +48,14 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTTMVASofieParser src/ParseSoftmax.cxx src/ParseTanh.cxx src/ParseTranspose.cxx + src/ParseErf.cxx src/ParseLayerNormalization.cxx src/ParseExpand.cxx src/ParseGather.cxx src/ParseFuseConvAdd.cxx src/ParseFuseConvTransposeAdd.cxx src/ParseFuseMatMulAdd.cxx + src/ParseMatMul.cxx ${PROTO_SRCS} LIBRARIES ${Protobuf_LIBRARIES} diff --git a/tmva/sofie_parsers/src/ParseBasicUnary.cxx b/tmva/sofie_parsers/src/ParseBasicUnary.cxx index 4e34e4e597045..5521dc08f8cc0 100644 --- a/tmva/sofie_parsers/src/ParseBasicUnary.cxx +++ b/tmva/sofie_parsers/src/ParseBasicUnary.cxx @@ -60,6 +60,11 @@ ParserFuncSignature ParseExp = [](RModelParser_ONNX &parser, const onnx::NodePro return ParseBasicUnary(parser, nodeproto); }; +// Parse Log +ParserFuncSignature ParseLog = [](RModelParser_ONNX &parser, const onnx::NodeProto &nodeproto) { + return ParseBasicUnary(parser, nodeproto); +}; + } // namespace SOFIE } // namespace Experimental } // namespace TMVA diff --git a/tmva/sofie_parsers/src/ParseErf.cxx b/tmva/sofie_parsers/src/ParseErf.cxx new file mode 100644 index 0000000000000..7b8fc8a899b2e --- /dev/null +++ b/tmva/sofie_parsers/src/ParseErf.cxx @@ -0,0 +1,39 @@ +#include "TMVA/RModelParser_ONNX.hxx" +#include "TMVA/ROperator_Erf.hxx" +#include "onnx_proto3.pb.h" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +ParserFuncSignature ParseErf = [](RModelParser_ONNX &parser, const onnx::NodeProto &nodeproto) { + ETensorType input_type; + + auto input_name = nodeproto.input(0); + if (parser.IsRegisteredTensorType(input_name)) { + input_type = parser.GetTensorType(input_name); + } else { + throw std::runtime_error("TMVA::SOFIE ONNX Parser Erf op has input tensor" + input_name + + " but its type is not yet registered"); + } + + std::unique_ptr op; + std::string output_name = nodeproto.output(0); + + switch (input_type) { + case ETensorType::FLOAT: op.reset(new ROperator_Erf(input_name, output_name)); break; + default: + throw std::runtime_error("TMVA::SOFIE - Unsupported - Operator Erf does not yet support input type " + + std::to_string(static_cast(input_type))); + } + + if (!parser.IsRegisteredTensorType(output_name)) { + parser.RegisterTensorType(output_name, input_type); + } + + return op; +}; + +} // namespace SOFIE +} // namespace Experimental +} // namespace TMVA diff --git a/tmva/sofie_parsers/src/ParseGather.cxx b/tmva/sofie_parsers/src/ParseGather.cxx index 31eb1efd340b9..bcf84ef6533ce 100644 --- a/tmva/sofie_parsers/src/ParseGather.cxx +++ b/tmva/sofie_parsers/src/ParseGather.cxx @@ -19,14 +19,13 @@ ParserFuncSignature ParseGather = [](RModelParser_ONNX &parser, const onnx::Node ETensorType indices_type = ETensorType::UNDEFINED; auto indices_name = nodeproto.input(1); + // indices_type can be an initialized tensor, no need to emit an error if it is not registered if (parser.IsRegisteredTensorType(indices_name)) { indices_type = parser.GetTensorType(indices_name); - } else { - throw std::runtime_error("TMVA::SOFIE ONNX Parser Gather op has indices tensor" + indices_name + " but its type is not yet registered"); - } - if (indices_type != ETensorType::INT64 && indices_type != ETensorType::INT32) { - throw - std::runtime_error("TMVA::SOFIE ONNX Parser Gather op Indices tensor type not supported."); + if (indices_type != ETensorType::INT64 && indices_type != ETensorType::INT32) { + throw + std::runtime_error("TMVA::SOFIE ONNX Parser Gather op Indices tensor type not supported."); + } } std::unique_ptr op; diff --git a/tmva/sofie_parsers/src/ParseMatMul.cxx b/tmva/sofie_parsers/src/ParseMatMul.cxx new file mode 100644 index 0000000000000..2f4cd1b4c6b1f --- /dev/null +++ b/tmva/sofie_parsers/src/ParseMatMul.cxx @@ -0,0 +1,49 @@ +#include "TMVA/RModelParser_ONNX.hxx" +#include "TMVA/ROperator_Gemm.hxx" +#include "onnx_proto3.pb.h" + +namespace TMVA { +namespace Experimental { +namespace SOFIE { + +ParserFuncSignature ParseMatMul = [](RModelParser_ONNX &parser, const onnx::NodeProto &matmulnode) { + ETensorType input_type = ETensorType::UNDEFINED; + + // check input type - only first input from MatMul + auto input_name = matmulnode.input(0); + if (parser.IsRegisteredTensorType(input_name)) { + input_type = parser.GetTensorType(input_name); + } else { + throw std::runtime_error("TMVA::SOFIE ONNX Parser MatMul op has input tensor " + input_name + + " but its type is not yet registered"); + } + + std::unique_ptr op; + + float attr_alpha = 1.0; + float attr_beta = 1.0; + int_t attr_transA = 0; + int_t attr_transB = 0; + + switch (input_type) { + case ETensorType::FLOAT: + op.reset(new ROperator_Gemm(attr_alpha, attr_beta, attr_transA, attr_transB, matmulnode.input(0), + matmulnode.input(1), matmulnode.output(0))); + break; + default: + throw std::runtime_error( + "TMVA::SOFIE - Unsupported - Operator for fusing MatMul and Add to Gemm does not yet support input type " + + std::to_string(static_cast(input_type))); + } + + std::string output_name = matmulnode.output(0); + if (!parser.IsRegisteredTensorType(output_name)) { + parser.RegisterTensorType(output_name, input_type); + } + + return op; +}; + +} // namespace SOFIE +} // namespace Experimental +} // namespace TMVA diff --git a/tmva/sofie_parsers/src/ParseReshape.cxx b/tmva/sofie_parsers/src/ParseReshape.cxx index f4dbd43de341f..c177594f931e4 100644 --- a/tmva/sofie_parsers/src/ParseReshape.cxx +++ b/tmva/sofie_parsers/src/ParseReshape.cxx @@ -22,7 +22,8 @@ ParserFuncSignature ParseReshape = [](RModelParser_ONNX &parser, const onnx::Nod // it is not present for Flatten, Squeeze and Unsquueze auto input_name = nodeproto.input(0); // for squeeze is optional ? - auto shape_name = (opMode == Reshape || opMode == Unsqueeze) ? nodeproto.input(1) : ""; + auto shape_name = ((nodeproto.input_size() > 1) && ( opMode == Reshape || opMode == Unsqueeze || opMode == Squeeze) ) + ? nodeproto.input(1) : ""; if (parser.IsRegisteredTensorType(input_name)) { input_type = parser.GetTensorType(input_name); } else { diff --git a/tmva/sofie_parsers/src/ParseSlice.cxx b/tmva/sofie_parsers/src/ParseSlice.cxx index 93dcf79f017c9..0e6b00edea0ba 100644 --- a/tmva/sofie_parsers/src/ParseSlice.cxx +++ b/tmva/sofie_parsers/src/ParseSlice.cxx @@ -22,7 +22,7 @@ ParserFuncSignature ParseSlice = [](RModelParser_ONNX &parser, const onnx::NodeP if (nodeproto.input_size() > 1) axisTensorNames.push_back(nodeproto.input(1)); if (nodeproto.input_size() > 2) - axisTensorNames.push_back(nodeproto.input(1)); + axisTensorNames.push_back(nodeproto.input(2)); if (nodeproto.input_size() > 3) axisTensorNames.push_back(nodeproto.input(3)); if (nodeproto.input_size() > 4) diff --git a/tmva/sofie_parsers/src/RModelParser_ONNX.cxx b/tmva/sofie_parsers/src/RModelParser_ONNX.cxx index c0df2e8122736..2160ba71ebf23 100644 --- a/tmva/sofie_parsers/src/RModelParser_ONNX.cxx +++ b/tmva/sofie_parsers/src/RModelParser_ONNX.cxx @@ -20,6 +20,7 @@ extern ParserFuncSignature ParseSqrt; extern ParserFuncSignature ParseReciprocal; extern ParserFuncSignature ParseNeg; extern ParserFuncSignature ParseExp; +extern ParserFuncSignature ParseLog; // Binary operators extern ParserFuncSignature ParseAdd; extern ParserFuncSignature ParseSub; @@ -58,8 +59,10 @@ extern ParserFuncSignature ParseConcat; extern ParserFuncSignature ParseCast; extern ParserFuncSignature ParseExpand; extern ParserFuncSignature ParseShape; +extern ParserFuncSignature ParseMatMul; extern ParserFuncSignature ParseLayerNormalization; extern ParserFuncSignature ParseGather; +extern ParserFuncSignature ParseErf; // Decalaration of fused operators extern ParserFuseFuncSignature ParseFuseConvAdd; extern ParserFuseFuncSignature ParseFuseConvTransposeAdd; @@ -79,6 +82,7 @@ RModelParser_ONNX::RModelParser_ONNX() noexcept : fOperatorsMapImpl(std::make_un RegisterOperator("Reciprocal", ParseReciprocal); RegisterOperator("Neg", ParseNeg); RegisterOperator("Exp", ParseExp); + RegisterOperator("Log", ParseLog); // Binary operators RegisterOperator("Add", ParseAdd); RegisterOperator("Sub", ParseSub); @@ -123,9 +127,11 @@ RModelParser_ONNX::RModelParser_ONNX() noexcept : fOperatorsMapImpl(std::make_un RegisterOperator("Softmax", ParseSoftmax); RegisterOperator("Tanh", ParseTanh); RegisterOperator("Transpose", ParseTranspose); + RegisterOperator("MatMul", ParseMatMul); RegisterOperator("LayerNormalization", ParseLayerNormalization); RegisterOperator("Expand", ParseExpand); RegisterOperator("Gather", ParseGather); + RegisterOperator("Erf", ParseErf); } // Destructor of the parser @@ -183,6 +189,9 @@ RModelParser_ONNX::ParseOperator(const size_t i, const onnx::GraphProto &graphpr if (idx2 < graphproto.node_size() && graphproto.node(idx2).op_type() == "Add") { return ParseFuseMatMulAdd(*this, graphproto.node(idx), graphproto.node(idx2)); } + else if(graphproto.node(idx2).op_type() != "Add"){ + return ParseMatMul(*this, graphproto.node(idx)); + } } else if (nodeproto.op_type() == "Conv" || nodeproto.op_type() == "ConvTranspose") { // Fuse Conv or ConvTranspose without bias and Add int j = (nodes.size() > i + 1) ? nodes[i + 1] : (int)i + 1; @@ -271,7 +280,7 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) if (initializer_names.find(graph.input(i).name()) != initializer_names.end()) continue; - // input datanode is not a weight node (has no initializer) + // input data node is not a weight node (has no initializer) const onnx::ValueInfoProto &valueinfoproto = graph.input(i); std::string input_name = valueinfoproto.name(); @@ -326,12 +335,13 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) for (int i = 0; i < graph.initializer_size(); i++) { onnx::TensorProto *tensorproto = const_cast(&graph.initializer(i)); - std::vector fShape; + std::vector shape; std::size_t fLength = 1; for (int j = 0; j < tensorproto->dims_size(); j++) { - fShape.push_back(tensorproto->dims(j)); + shape.push_back(tensorproto->dims(j)); fLength *= tensorproto->dims(j); } + // in case of scalars keep an empty shape but with length =1 std::string input_name = graph.initializer(i).name(); @@ -351,7 +361,8 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) static_cast(data.get())); } - rmodel.AddInitializedTensor(input_name, ETensorType::FLOAT, fShape, data); + if (verbose) std::cout << "add FLOAT initialized tensor " << input_name << " shape " << ConvertShapeToString(shape) << std::endl; + rmodel.AddInitializedTensor(input_name, ETensorType::FLOAT, shape, data); allInitializedTensors[input_name] = i; break; } @@ -366,7 +377,8 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) static_cast(data.get())); } - rmodel.AddInitializedTensor(input_name, ETensorType::INT64, fShape, data); + if (verbose) std::cout << "add INT64 initialized tensor " << input_name << " shape " << ConvertShapeToString(shape) << std::endl; + rmodel.AddInitializedTensor(input_name, ETensorType::INT64, shape, data); allInitializedTensors[input_name] = i; break; } @@ -385,8 +397,8 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) std::cout << graph.node(i).input(j); if (j < graph.node(i).input_size() - 1) std::cout << ", "; - std::cout << " }" << std::endl; } + std::cout << " }" << std::endl; } } @@ -435,8 +447,8 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) continue; } if (verbose) - std::cout << "\tadd node " << graph.node(i).op_type() << " with input " << graph.node(i).input(0) - << " order " << i << std::endl; + std::cout << "\tadd node " << graph.node(i).op_type() << " order " << i << std::endl; + nodesOrder.push_back(i); foundNodes[i] = true; // register the outputs @@ -461,8 +473,8 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) std::cout << graph.node(i).input(j); if (j < graph.node(i).input_size() - 1) std::cout << ", "; - std::cout << " }" << std::endl; } + std::cout << " }" << std::endl; } } @@ -476,6 +488,7 @@ RModel RModelParser_ONNX::Parse(std::string filename, bool verbose) if (verbose) { std::cout << "\t" << i << " " << nodesOrder[i] << " parsing operator " << op_type << std::endl; } + std::unique_ptr op = ParseOperator(i, graph, nodesOrder); if (!op) { if (verbose) { diff --git a/tmva/tmva/CMakeLists.txt b/tmva/tmva/CMakeLists.txt index 918df7b39b43c..84efce9d59cb7 100644 --- a/tmva/tmva/CMakeLists.txt +++ b/tmva/tmva/CMakeLists.txt @@ -28,27 +28,16 @@ else() set(installoptions ${installoptions} FILTER "Cuda") endif() -# Enable parts dependent RDataFrame -if(dataframe) - set(TMVA_EXTRA_HEADERS - TMVA/RTensor.hxx - TMVA/RTensorUtils.hxx - TMVA/RStandardScaler.hxx - TMVA/RReader.hxx - TMVA/RInferenceUtils.hxx - TMVA/RBDT.hxx - TMVA/RSofieReader.hxx - ) - set(TMVA_EXTRA_SOURCES - RBDT.cxx - ) - list(APPEND TMVA_EXTRA_DEPENDENCIES ROOTDataFrame ROOTVecOps) -endif() if (imt) list(APPEND TMVA_EXTRA_DEPENDENCIES Imt) endif(imt) +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(TMVA HEADERS TMVA/BDTEventWrapper.h @@ -215,10 +204,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(TMVA TMVA/VarTransformHandler.h TMVA/Version.h TMVA/Volume.h - TMVA/TreeInference/PythonHelpers.hxx - TMVA/TreeInference/BranchlessTree.hxx - TMVA/TreeInference/Forest.hxx - TMVA/TreeInference/Objectives.hxx # TMVA/DNN/Adadelta.h # TMVA/DNN/Adagrad.h # TMVA/DNN/Adam.h @@ -349,6 +334,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(TMVA src/PDEFoamVect.cxx src/PDF.cxx src/QuickMVAProbEstimator.cxx + src/RBDT.cxx src/Ranking.cxx src/Reader.cxx src/RegressionVariance.cxx @@ -429,6 +415,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(TMVA -writeEmptyRootPCM INSTALL_OPTIONS ${installoptions} + ${EXTRA_DICT_OPTS} ) if(MSVC) @@ -436,7 +423,10 @@ if(MSVC) endif() if(vdt OR builtin_vdt) - target_include_directories(TMVA PRIVATE ${VDT_INCLUDE_DIRS}) + target_link_libraries(TMVA PRIVATE VDT::VDT) +endif() +if(builtin_vdt) + add_dependencies(TMVA VDT) endif() if(tmva-cpu) @@ -482,6 +472,40 @@ if(tmva-gpu) endif() endif() +if(dataframe) +ROOT_STANDARD_LIBRARY_PACKAGE(TMVAUtils + NO_INSTALL_HEADERS + HEADERS + TMVA/RTensorUtils.hxx + TMVA/RStandardScaler.hxx + TMVA/RReader.hxx + TMVA/RInferenceUtils.hxx + TMVA/RBDT.hxx + TMVA/RSofieReader.hxx + TMVA/RBatchGenerator.hxx + TMVA/RBatchLoader.hxx + TMVA/RChunkLoader.hxx + TMVA/TreeInference/PythonHelpers.hxx + TMVA/TreeInference/BranchlessTree.hxx + TMVA/TreeInference/Forest.hxx + TMVA/TreeInference/Objectives.hxx + + SOURCES + + src/RBDT.cxx + + DEPENDENCIES + TMVA ROOTDataFrame ROOTVecOps + ${TMVA_EXTRA_DEPENDENCIES} + + LINKDEF LinkDefUtils.h + DICTIONARY_OPTIONS + -writeEmptyRootPCM + + ${EXTRA_DICT_OPTS} +) +endif() + ROOT_ADD_TEST_SUBDIRECTORY(test) ROOT_ADD_TEST_SUBDIRECTORY(test/crossvalidation) ROOT_ADD_TEST_SUBDIRECTORY(test/DNN) diff --git a/tmva/tmva/inc/LinkDef1.h b/tmva/tmva/inc/LinkDef1.h index 7d3b6f4f15d63..d2f8ebaeda2e6 100644 --- a/tmva/tmva/inc/LinkDef1.h +++ b/tmva/tmva/inc/LinkDef1.h @@ -71,9 +71,4 @@ #pragma link C++ class TMVA::MethodCrossValidation+; #pragma link C++ class TMVA::MethodDL+; -#ifdef R__HAS_DATAFRAME -// BDT inference -#pragma link C++ class TMVA::Experimental::RBDT>; -#pragma link C++ class TMVA::Experimental::RBDT>; -#endif -#endif +#endif \ No newline at end of file diff --git a/tmva/tmva/inc/LinkDefUtils.h b/tmva/tmva/inc/LinkDefUtils.h new file mode 100644 index 0000000000000..9953df4be2f55 --- /dev/null +++ b/tmva/tmva/inc/LinkDefUtils.h @@ -0,0 +1,18 @@ +#ifdef __CINT__ + +#include "RConfigure.h" + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; +#pragma link off all namespaces; + +#pragma link C++ nestedclass; + +#ifdef R__HAS_DATAFRAME +// BDT inference +#pragma link C++ class TMVA::Experimental::RBDT>; +#pragma link C++ class TMVA::Experimental::RBDT>; +#endif + +#endif \ No newline at end of file diff --git a/tmva/tmva/inc/TMVA/NeuralNet.icc b/tmva/tmva/inc/TMVA/NeuralNet.icc index d104e286edd5c..0238449bb6f7d 100644 --- a/tmva/tmva/inc/TMVA/NeuralNet.icc +++ b/tmva/tmva/inc/TMVA/NeuralNet.icc @@ -902,7 +902,7 @@ template if ((int)cycleCount % 10 == 0) { - TString convText = Form( "(train/test/epo/conv/maxco): %.3g/%.3g/%d/%d/%d", + TString convText = TString::Format( "(train/test/epo/conv/maxco): %.3g/%.3g/%d/%d/%d", trainError, testError, (int)cycleCount, @@ -915,7 +915,7 @@ template while (true); settings.endTrainCycle (trainError); - TString convText = Form( "(train/test/epoch): %.4g/%.4g/%d", trainError, testError, (int)cycleCount); + TString convText = TString::Format( "(train/test/epoch): %.4g/%.4g/%d", trainError, testError, (int)cycleCount); double progress = 100*(double)settings.maxConvergenceCount() /(double)settings.convergenceSteps (); settings.cycle (progress, convText); diff --git a/tmva/tmva/inc/TMVA/RBatchGenerator.hxx b/tmva/tmva/inc/TMVA/RBatchGenerator.hxx new file mode 100644 index 0000000000000..6c7687682e5f4 --- /dev/null +++ b/tmva/tmva/inc/TMVA/RBatchGenerator.hxx @@ -0,0 +1,239 @@ +#ifndef TMVA_BATCHGENERATOR +#define TMVA_BATCHGENERATOR + +#include +#include +#include +#include +#include +#include + +#include "TMVA/RTensor.hxx" +#include "ROOT/RDF/RDatasetSpec.hxx" +#include "TMVA/RChunkLoader.hxx" +#include "TMVA/RBatchLoader.hxx" +#include "TMVA/Tools.h" +#include "TRandom3.h" +#include "TROOT.h" + +namespace TMVA { +namespace Experimental { +namespace Internal { + +template +class RBatchGenerator { +private: + TMVA::RandomGenerator fRng = TMVA::RandomGenerator(0); + + std::string fFileName; + std::string fTreeName; + + std::vector fCols; + std::vector fFilters; + + std::size_t fChunkSize; + std::size_t fMaxChunks; + std::size_t fBatchSize; + std::size_t fMaxBatches; + std::size_t fNumColumns; + std::size_t fNumEntries; + std::size_t fCurrentRow = 0; + + float fValidationSplit; + + std::unique_ptr> fChunkLoader; + std::unique_ptr fBatchLoader; + + std::unique_ptr fLoadingThread; + + bool fUseWholeFile = true; + + std::unique_ptr> fChunkTensor; + std::unique_ptr> fCurrentBatch; + + std::vector> fTrainingIdxs; + std::vector> fValidationIdxs; + + // filled batch elements + std::mutex fIsActiveLock; + + bool fShuffle = true; + bool fIsActive = false; + + std::vector fVecSizes; + float fVecPadding; + +public: + RBatchGenerator(const std::string &treeName, const std::string &fileName, const std::size_t chunkSize, + const std::size_t batchSize, const std::vector &cols, + const std::vector &filters = {}, const std::vector &vecSizes = {}, + const float vecPadding = 0.0, const float validationSplit = 0.0, const std::size_t maxChunks = 0, + const std::size_t numColumns = 0, bool shuffle = true) + : fTreeName(treeName), + fFileName(fileName), + fChunkSize(chunkSize), + fBatchSize(batchSize), + fCols(cols), + fFilters(filters), + fVecSizes(vecSizes), + fVecPadding(vecPadding), + fValidationSplit(validationSplit), + fMaxChunks(maxChunks), + fNumColumns((numColumns != 0) ? numColumns : cols.size()), + fShuffle(shuffle), + fUseWholeFile(maxChunks == 0) + { + // limits the number of batches that can be contained in the batchqueue based on the chunksize + fMaxBatches = ceil((fChunkSize / fBatchSize) * (1 - fValidationSplit)); + + // get the number of fNumEntries in the dataframe + std::unique_ptr f{TFile::Open(fFileName.c_str())}; + std::unique_ptr t{f->Get(fTreeName.c_str())}; + fNumEntries = t->GetEntries(); + + fChunkLoader = std::make_unique>( + fTreeName, fFileName, fChunkSize, fCols, fFilters, fVecSizes, fVecPadding); + fBatchLoader = std::make_unique(fBatchSize, fNumColumns, fMaxBatches); + + // Create tensor to load the chunk into + fChunkTensor = + std::make_unique>((std::vector){fChunkSize, fNumColumns}); + } + + ~RBatchGenerator() { DeActivate(); } + + /// \brief De-activate the loading process by deactivating the batchgenerator + /// and joining the loading thread + void DeActivate() + { + { + std::lock_guard lock(fIsActiveLock); + fIsActive = false; + } + + fBatchLoader->DeActivate(); + + if (fLoadingThread) { + if (fLoadingThread->joinable()) { + fLoadingThread->join(); + } + } + } + + /// \brief Activate the loading process by starting the batchloader, and + /// spawning the loading thread. + void Activate() + { + if (fIsActive) + return; + + { + std::lock_guard lock(fIsActiveLock); + fIsActive = true; + } + + fCurrentRow = 0; + fBatchLoader->Activate(); + fLoadingThread = std::make_unique(&RBatchGenerator::LoadChunks, this); + } + + /// \brief Returns the next batch of training data if available. + /// Returns empty RTensor otherwise. + /// \return + const TMVA::Experimental::RTensor &GetTrainBatch() + { + // Get next batch if available + return fBatchLoader->GetTrainBatch(); + } + + /// \brief Returns the next batch of validation data if available. + /// Returns empty RTensor otherwise. + /// \return + const TMVA::Experimental::RTensor &GetValidationBatch() + { + // Get next batch if available + return fBatchLoader->GetValidationBatch(); + } + + bool HasTrainData() { return fBatchLoader->HasTrainData(); } + + bool HasValidationData() { return fBatchLoader->HasValidationData(); } + + void LoadChunks() + { + ROOT::EnableThreadSafety(); + + for (std::size_t current_chunk = 0; ((current_chunk < fMaxChunks) || fUseWholeFile) && fCurrentRow < fNumEntries; + current_chunk++) { + + // stop the loop when the loading is not active anymore + { + std::lock_guard lock(fIsActiveLock); + if (!fIsActive) + return; + } + + // A pair that consists the proccessed, and passed events while loading the chunk + std::pair report = fChunkLoader->LoadChunk(*fChunkTensor, fCurrentRow); + fCurrentRow += report.first; + + CreateBatches(current_chunk, report.second); + + // Stop loading if the number of processed events is smaller than the desired chunk size + if (report.first < fChunkSize) { + break; + } + } + + fBatchLoader->DeActivate(); + } + + /// \brief Create batches for the current_chunk. + /// \param currentChunk + /// \param processedEvents + void CreateBatches(std::size_t currentChunk, std::size_t processedEvents) + { + + // Check if the indices in this chunk where already split in train and validations + if (fTrainingIdxs.size() > currentChunk) { + fBatchLoader->CreateTrainingBatches(*fChunkTensor, fTrainingIdxs[currentChunk], fShuffle); + } else { + // Create the Validation batches if this is not the first epoch + createIdxs(processedEvents); + fBatchLoader->CreateTrainingBatches(*fChunkTensor, fTrainingIdxs[currentChunk], fShuffle); + fBatchLoader->CreateValidationBatches(*fChunkTensor, fValidationIdxs[currentChunk]); + } + } + + /// \brief plit the events of the current chunk into validation and training events + /// \param processedEvents + void createIdxs(std::size_t processedEvents) + { + // Create a vector of number 1..processedEvents + std::vector row_order = std::vector(processedEvents); + std::iota(row_order.begin(), row_order.end(), 0); + + if (fShuffle) { + std::shuffle(row_order.begin(), row_order.end(), fRng); + } + + // calculate the number of events used for validation + std::size_t num_validation = ceil(processedEvents * fValidationSplit); + + // Devide the vector into training and validation + std::vector valid_idx({row_order.begin(), row_order.begin() + num_validation}); + std::vector train_idx({row_order.begin() + num_validation, row_order.end()}); + + fTrainingIdxs.push_back(train_idx); + fValidationIdxs.push_back(valid_idx); + } + + void StartValidation() { fBatchLoader->StartValidation(); } + bool IsActive() { return fIsActive; } +}; + +} // namespace Internal +} // namespace Experimental +} // namespace TMVA + +#endif // TMVA_BATCHGENERATOR diff --git a/tmva/tmva/inc/TMVA/RBatchLoader.hxx b/tmva/tmva/inc/TMVA/RBatchLoader.hxx new file mode 100644 index 0000000000000..cb5ef8b4af676 --- /dev/null +++ b/tmva/tmva/inc/TMVA/RBatchLoader.hxx @@ -0,0 +1,225 @@ +#ifndef TMVA_RBatchLoader +#define TMVA_RBatchLoader + +#include +#include +#include + +// Imports for threading +#include +#include +#include + +#include "TMVA/RTensor.hxx" +#include "TMVA/Tools.h" +#include "TRandom3.h" + +namespace TMVA { +namespace Experimental { +namespace Internal { + +class RBatchLoader { +private: + std::size_t fBatchSize; + std::size_t fNumColumns; + std::size_t fMaxBatches; + + bool fIsActive = false; + TMVA::RandomGenerator fRng = TMVA::RandomGenerator(0); + + std::mutex fBatchLock; + std::condition_variable fBatchCondition; + + std::queue>> fTrainingBatchQueue; + std::vector>> fValidationBatches; + std::unique_ptr> fCurrentBatch; + + std::size_t fValidationIdx = 0; + + TMVA::Experimental::RTensor fEmptyTensor = TMVA::Experimental::RTensor({0}); + +public: + RBatchLoader(const std::size_t batchSize, const std::size_t numColumns, const std::size_t maxBatches) + : fBatchSize(batchSize), fNumColumns(numColumns), fMaxBatches(maxBatches) + { + } + + ~RBatchLoader() { DeActivate(); } + +public: + /// \brief Return a batch of data as a unique pointer. + /// After the batch has been processed, it should be distroyed. + /// \return Training batch + const TMVA::Experimental::RTensor &GetTrainBatch() + { + std::unique_lock lock(fBatchLock); + fBatchCondition.wait(lock, [this]() { return !fTrainingBatchQueue.empty() || !fIsActive; }); + + if (fTrainingBatchQueue.empty()) { + fCurrentBatch = std::make_unique>(std::vector({0})); + return *fCurrentBatch; + } + + fCurrentBatch = std::move(fTrainingBatchQueue.front()); + fTrainingBatchQueue.pop(); + + fBatchCondition.notify_all(); + + return *fCurrentBatch; + } + + /// \brief Returns a batch of data for validation + /// The owner of this batch has to be with the RBatchLoader. + /// This is because the same validation batches should be used in all epochs. + /// \return Validation batch + const TMVA::Experimental::RTensor &GetValidationBatch() + { + if (HasValidationData()) { + return *fValidationBatches[fValidationIdx++].get(); + } + + return fEmptyTensor; + } + + /// \brief Checks if there are more training batches available + /// \return + bool HasTrainData() + { + { + std::unique_lock lock(fBatchLock); + if (!fTrainingBatchQueue.empty() || fIsActive) + return true; + } + + return false; + } + + /// \brief Checks if there are more training batches available + /// \return + bool HasValidationData() + { + std::unique_lock lock(fBatchLock); + return fValidationIdx < fValidationBatches.size(); + } + + /// \brief Activate the batchloader so it will accept chunks to batch + void Activate() + { + { + std::lock_guard lock(fBatchLock); + fIsActive = true; + } + fBatchCondition.notify_all(); + } + + /// \brief DeActivate the batchloader. This means that no more batches are created. + /// Batches can still be returned if they are already loaded + void DeActivate() + { + { + std::lock_guard lock(fBatchLock); + fIsActive = false; + } + fBatchCondition.notify_all(); + } + + /// \brief Create a batch filled with the events on the given idx + /// \param chunkTensor + /// \param idx + /// \return + std::unique_ptr> + CreateBatch(const TMVA::Experimental::RTensor &chunkTensor, const std::vector idx) + { + auto batch = + std::make_unique>(std::vector({fBatchSize, fNumColumns})); + + for (std::size_t i = 0; i < fBatchSize; i++) { + std::copy(chunkTensor.GetData() + (idx[i] * fNumColumns), chunkTensor.GetData() + ((idx[i] + 1) * fNumColumns), + batch->GetData() + i * fNumColumns); + } + + return batch; + } + + /// \brief Create training batches from the given chunk of data based on the given event indices + /// Batches are added to the training queue of batches + /// The eventIndices can be shuffled to ensure random order for each epoch + /// \param chunkTensor + /// \param eventIndices + /// \param shuffle + void CreateTrainingBatches(const TMVA::Experimental::RTensor &chunkTensor, + std::vector eventIndices, const bool shuffle = true) + { + // Wait until less than a full chunk of batches are in the queue before loading splitting the next chunk into + // batches + { + std::unique_lock lock(fBatchLock); + fBatchCondition.wait(lock, [this]() { return (fTrainingBatchQueue.size() < fMaxBatches) || !fIsActive; }); + if (!fIsActive) + return; + } + + if (shuffle) + std::shuffle(eventIndices.begin(), eventIndices.end(), fRng); // Shuffle the order of idx + + std::vector>> batches; + + // Create tasks of fBatchSize untill all idx are used + for (std::size_t start = 0; (start + fBatchSize) <= eventIndices.size(); start += fBatchSize) { + + // Grab the first fBatchSize indices from the + std::vector idx; + for (std::size_t i = start; i < (start + fBatchSize); i++) { + idx.push_back(eventIndices[i]); + } + + // Fill a batch + batches.emplace_back(CreateBatch(chunkTensor, idx)); + } + + { + std::unique_lock lock(fBatchLock); + for (std::size_t i = 0; i < batches.size(); i++) { + fTrainingBatchQueue.push(std::move(batches[i])); + } + } + + fBatchCondition.notify_one(); + } + + /// \brief Create validation batches from the given chunk based on the given event indices + /// Batches are added to the vector of validation batches + /// \param chunkTensor + /// \param eventIndices + void CreateValidationBatches(const TMVA::Experimental::RTensor &chunkTensor, + const std::vector eventIndices) + { + // Create tasks of fBatchSize untill all idx are used + for (std::size_t start = 0; (start + fBatchSize) <= eventIndices.size(); start += fBatchSize) { + + std::vector idx; + + for (std::size_t i = start; i < (start + fBatchSize); i++) { + idx.push_back(eventIndices[i]); + } + + { + std::unique_lock lock(fBatchLock); + fValidationBatches.emplace_back(CreateBatch(chunkTensor, idx)); + } + } + } + + /// \brief Reset the validation process + void StartValidation() + { + std::unique_lock lock(fBatchLock); + fValidationIdx = 0; + } +}; + +} // namespace Internal +} // namespace Experimental +} // namespace TMVA + +#endif // TMVA_RBatchLoader diff --git a/tmva/tmva/inc/TMVA/RChunkLoader.hxx b/tmva/tmva/inc/TMVA/RChunkLoader.hxx new file mode 100644 index 0000000000000..2b2ff8ed15305 --- /dev/null +++ b/tmva/tmva/inc/TMVA/RChunkLoader.hxx @@ -0,0 +1,234 @@ +#ifndef TMVA_CHUNKLOADER +#define TMVA_CHUNKLOADER + +#include +#include + +#include "TMVA/RTensor.hxx" +#include "ROOT/RDataFrame.hxx" +#include "ROOT/RVec.hxx" + +#include "ROOT/RLogger.hxx" + +namespace TMVA { +namespace Experimental { +namespace Internal { + +// RChunkLoader class used to load content of a RDataFrame onto a RTensor. +template +class RChunkLoaderFunctor { + +private: + std::size_t fOffset = 0; + std::size_t fVecSizeIdx = 0; + std::vector fMaxVecSizes; + + float fVecPadding; + + TMVA::Experimental::RTensor &fChunkTensor; + + /// \brief Load the final given value into fChunkTensor + /// \tparam First_T + /// \param first + template + void AssignToTensor(First_T first) + { + fChunkTensor.GetData()[fOffset++] = first; + } + + /// \brief Load the final given value into fChunkTensor + /// \tparam VecType + /// \param first + template + void AssignToTensor(const ROOT::RVec &first) + { + AssignVector(first); + } + + /// \brief Recursively loop through the given values, and load them onto the fChunkTensor + /// \tparam First_T + /// \tparam ...Rest_T + /// \param first + /// \param ...rest + template + void AssignToTensor(First_T first, Rest_T... rest) + { + fChunkTensor.GetData()[fOffset++] = first; + + AssignToTensor(std::forward(rest)...); + } + + /// \brief Recursively loop through the given values, and load them onto the fChunkTensor + /// \tparam VecType + /// \tparam ...Rest_T + /// \param first + /// \param ...rest + template + void AssignToTensor(const ROOT::RVec &first, Rest_T... rest) + { + AssignVector(first); + + AssignToTensor(std::forward(rest)...); + } + + /// \brief Loop through the values of a given vector and load them into the RTensor + /// Note: the given vec_size does not have to be the same size as the given vector + /// If the size is bigger than the given vector, zeros are used as padding. + /// If the size is smaller, the remaining values are ignored. + /// \tparam VecType + /// \param vec + template + void AssignVector(const ROOT::RVec &vec) + { + std::size_t max_vec_size = fMaxVecSizes[fVecSizeIdx++]; + std::size_t vec_size = vec.size(); + + for (std::size_t i = 0; i < max_vec_size; i++) { + if (i < vec_size) { + fChunkTensor.GetData()[fOffset++] = vec[i]; + } else { + fChunkTensor.GetData()[fOffset++] = fVecPadding; + } + } + } + +public: + RChunkLoaderFunctor(TMVA::Experimental::RTensor &chunkTensor, + const std::vector &maxVecSizes = std::vector(), + const float vecPadding = 0.0) + : fChunkTensor(chunkTensor), fMaxVecSizes(maxVecSizes), fVecPadding(vecPadding) + { + } + + /// \brief Loop through all columns of an event and put their values into an RTensor + /// \param first + /// \param ...rest + void operator()(First first, Rest... rest) + { + fVecSizeIdx = 0; + AssignToTensor(std::forward(first), std::forward(rest)...); + } +}; + +template +class RChunkLoader { + +private: + std::string fTreeName; + std::string fFileName; + std::size_t fChunkSize; + std::size_t fNumColumns; + + std::vector fCols; + std::vector fFilters; + + std::vector fVecSizes; + std::size_t fVecPadding; + +public: + /// \brief Constructor for the RChunkLoader + /// \param treeName + /// \param fileName + /// \param chunkSize + /// \param cols + /// \param filters + /// \param vecSizes + /// \param vecPadding + RChunkLoader(const std::string &treeName, const std::string &fileName, const std::size_t chunkSize, + const std::vector &cols, const std::vector &filters = {}, + const std::vector &vecSizes = {}, const float vecPadding = 0.0) + : fTreeName(treeName), + fFileName(fileName), + fChunkSize(chunkSize), + fCols(cols), + fFilters(filters), + fVecSizes(vecSizes), + fVecPadding(vecPadding), + fNumColumns(cols.size()) + { + } + + /// \brief Load a chunk of data using the RChunkLoaderFunctor + /// \param chunkTensor + /// \param currentRow + /// \return A pair of size_t defining the number of events processed and how many passed all filters + std::pair + LoadChunk(TMVA::Experimental::RTensor &chunkTensor, const std::size_t currentRow) + { + RChunkLoaderFunctor func(chunkTensor, fVecSizes, fVecPadding); + + // Create TDataFrame of the chunk + // Use RDatasetSpec to start reading at the current row + long long start_l = currentRow; + ROOT::RDF::Experimental::RDatasetSpec x_spec = + ROOT::RDF::Experimental::RDatasetSpec() + .AddSample({"", fTreeName, fFileName}) + .WithGlobalRange({start_l, std::numeric_limits::max()}); + + ROOT::RDataFrame x_rdf(x_spec); + + // Load events if filters are given + if (fFilters.size() > 0) { + return loadFiltered(x_rdf, func); + } + + // load events if no filters are given + return loadNonFiltered(x_rdf, func); + } + +private: + /// \brief Add filters to the RDataFrame and load a chunk of data + /// \param x_rdf + /// \param func + /// \return A pair of size_t defining the number of events processed and how many passed all filters + std::pair loadFiltered(ROOT::RDataFrame &x_rdf, RChunkLoaderFunctor &func) + { + // Add the given filters to the RDataFrame + auto x_filter = x_rdf.Filter(fFilters[0], "RBatchGenerator_Filter_0"); + for (auto i = 1; i < fFilters.size(); i++) { + auto name = "RBatchGenerator_Filter_" + std::to_string(i); + x_filter = x_filter.Filter(fFilters[i], name); + } + + // add range to the DataFrame + auto x_ranged = x_filter.Range(fChunkSize); + auto myReport = x_ranged.Report(); + + // load data + x_ranged.Foreach(func, fCols); + + // Use the report to gather the number of events processed and passed. + // passed_events is used to determine the starting event of the next chunk + // processed_events is used to determine if the end of the database is reached. + std::size_t processed_events = myReport.begin()->GetAll(); + std::size_t passed_events = (myReport.end() - 1)->GetPass(); + + return std::make_pair(processed_events, passed_events); + } + + /// \brief Loop over the events in the dataframe untill either the end of the dataframe + /// is reached, or a full chunk is loaded + /// \param x_rdf + /// \param func + /// \return A pair of size_t defining the number of events processed and how many passed all filters + std::pair loadNonFiltered(ROOT::RDataFrame &x_rdf, RChunkLoaderFunctor &func) + { + // add range + auto x_ranged = x_rdf.Range(fChunkSize); + // auto x_ranged = x_rdf.Range(currentRow, currentRow + fChunkSize); + auto myCount = x_ranged.Count(); + + // load data + x_ranged.Foreach(func, fCols); + + // get loading info + std::size_t processed_events = myCount.GetValue(); + std::size_t passed_events = myCount.GetValue(); + return std::make_pair(processed_events, passed_events); + } +}; + +} // namespace Internal +} // namespace Experimental +} // namespace TMVA +#endif // TMVA_CHUNKLOADER diff --git a/tmva/tmva/inc/TMVA/RInferenceUtils.hxx b/tmva/tmva/inc/TMVA/RInferenceUtils.hxx index 90085a4c81fb5..bf066e0cc921d 100644 --- a/tmva/tmva/inc/TMVA/RInferenceUtils.hxx +++ b/tmva/tmva/inc/TMVA/RInferenceUtils.hxx @@ -20,7 +20,9 @@ class ComputeHelper, T, F> { public: ComputeHelper(F &&f) : fFunc(std::forward(f)) {} - auto operator()(AlwaysT... args) -> decltype(fFunc.Compute({args...})) { return fFunc.Compute({args...}); } + auto operator()(AlwaysT... args) -> decltype(fFunc.Compute({args...})) { + return fFunc.Compute({args...}); + } }; } // namespace Internal diff --git a/tmva/tmva/inc/TMVA/ROCCurve.h b/tmva/tmva/inc/TMVA/ROCCurve.h index f53e245c4336e..0b62e8dc6e7d9 100644 --- a/tmva/tmva/inc/TMVA/ROCCurve.h +++ b/tmva/tmva/inc/TMVA/ROCCurve.h @@ -25,8 +25,9 @@ #include "RtypesCore.h" -#include +#include #include +#include class TList; class TTree; diff --git a/tmva/tmva/inc/TMVA/RSofieReader.hxx b/tmva/tmva/inc/TMVA/RSofieReader.hxx index bff09aa6caf26..b4be9c4c9a87a 100644 --- a/tmva/tmva/inc/TMVA/RSofieReader.hxx +++ b/tmva/tmva/inc/TMVA/RSofieReader.hxx @@ -46,9 +46,16 @@ class RSofieReader { public: + /// Dummy constructor which needs model loading afterwards + RSofieReader() {} /// Create TMVA model from ONNX file /// print level can be 0 (minimal) 1 with info , 2 with all ONNX parsing info - RSofieReader(const std::string &path, std::vector> inputShape = {}, int verbose = 0) + RSofieReader(const std::string &path, std::vector> inputShapes = {}, int verbose = 0) + { + Load(path, inputShapes, verbose); + } + + void Load(const std::string &path, std::vector> inputShapes = {}, int verbose = 0) { enum EModelType {kONNX, kKeras, kPt, kROOT, kNotDef}; // type of model @@ -76,8 +83,7 @@ public: } } if (type == kNotDef) { - Error("RSofieReader","Input file is not an ONNX or Keras or PyTorch file"); - return; + throw std::runtime_error("Input file is not an ONNX or Keras or PyTorch file"); } if (pos1 == std::string::npos) pos1 = 0; @@ -87,16 +93,16 @@ public: std::string fileType = path.substr(pos2+1, path.length()-pos2-1); if (verbose) std::cout << "Parsing SOFIE model " << modelName << " of type " << fileType << std::endl; - + // create code for parsing model and generate C++ code for inference + // make it in a separate scope to avoid polluting global interpreter space std::string parserCode; if (type == kONNX) { // check first if we can load the SOFIE parser library if (gSystem->Load("libROOTTMVASofieParser") < 0) { - Error("RSofieReader","Cannot use SOFIE with ONNX since libROOTTMVASofieParser is missing"); - return; + throw std::runtime_error("RSofieReader: cannot use SOFIE with ONNX since libROOTTMVASofieParser is missing"); } gInterpreter->Declare("#include \"TMVA/RModelParser_ONNX.hxx\""); - parserCode += "TMVA::Experimental::SOFIE::RModelParser_ONNX parser; \n"; + parserCode += "{\nTMVA::Experimental::SOFIE::RModelParser_ONNX parser ; \n"; if (verbose == 2) parserCode += "TMVA::Experimental::SOFIE::RModel model = parser.Parse(\"" + path + "\",true); \n"; else @@ -105,38 +111,35 @@ public: else if (type == kKeras) { // use Keras direct parser if (gSystem->Load("libPyMVA") < 0) { - Error("RSofieReader","Cannot use SOFIE with Keras since libPyMVA is missing"); - return; + throw std::runtime_error("RSofieReader: cannot use SOFIE with Keras since libPyMVA is missing"); } - parserCode += "TMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyKeras::Parse(\"" + path + "\"); \n"; + parserCode += "{\nTMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyKeras::Parse(\"" + path + "\"); \n"; } else if (type == kPt) { // use PyTorch direct parser if (gSystem->Load("libPyMVA") < 0) { - Error("RSofieReader","Cannot use SOFIE with PyTorch since libPyMVA is missing"); - return; + throw std::runtime_error("RSofieReader: cannot use SOFIE with PyTorch since libPyMVA is missing"); } - if (inputShape.size() == 0) { - Error("RSofieReader","Cannot use SOFIE with PyTorch since the input tensor shape is missing and is needed by the PyTorch parser"); - return; + if (inputShapes.size() == 0) { + throw std::runtime_error("RSofieReader: cannot use SOFIE with PyTorch since the input tensor shape is missing and is needed by the PyTorch parser"); } - std::string inputShapeStr = "{"; - for (unsigned int i = 0; i < inputShape.size(); i++) { - inputShapeStr += "{ "; - for (unsigned int j = 0; j < inputShape[i].size(); j++) { - inputShapeStr += ROOT::Math::Util::ToString(inputShape[i][j]); - if (j < inputShape[i].size()-1) inputShapeStr += ", "; + std::string inputShapesStr = "{"; + for (unsigned int i = 0; i < inputShapes.size(); i++) { + inputShapesStr += "{ "; + for (unsigned int j = 0; j < inputShapes[i].size(); j++) { + inputShapesStr += ROOT::Math::Util::ToString(inputShapes[i][j]); + if (j < inputShapes[i].size()-1) inputShapesStr += ", "; } - inputShapeStr += "}"; - if (i < inputShape.size()-1) inputShapeStr += ", "; + inputShapesStr += "}"; + if (i < inputShapes.size()-1) inputShapesStr += ", "; } - inputShapeStr += "}"; - parserCode += "TMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyTorch::Parse(\"" + path + "\", " - + inputShapeStr + "); \n"; + inputShapesStr += "}"; + parserCode += "{\nTMVA::Experimental::SOFIE::RModel model = TMVA::Experimental::SOFIE::PyTorch::Parse(\"" + path + "\", " + + inputShapesStr + "); \n"; } else if (type == kROOT) { // use parser from ROOT - parserCode += "auto fileRead = TFile::Open(\"" + path + "\",\"READ\");\n"; + parserCode += "{\nauto fileRead = TFile::Open(\"" + path + "\",\"READ\");\n"; parserCode += "TMVA::Experimental::SOFIE::RModel * modelPtr;\n"; parserCode += "auto keyList = fileRead->GetListOfKeys(); TString name;\n"; parserCode += "for (const auto&& k : *keyList) { \n"; @@ -145,38 +148,67 @@ public: parserCode += "TMVA::Experimental::SOFIE::RModel & model = *modelPtr;\n"; } - if (verbose) std::cout << parserCode << std::endl; - gROOT->ProcessLine(parserCode.c_str()); - int batchSize = 1; - if (inputShape.size() > 0 && inputShape[0].size() > 0) { - batchSize = inputShape[0][0]; + if (inputShapes.size() > 0 && inputShapes[0].size() > 0) { + batchSize = inputShapes[0][0]; if (batchSize < 1) batchSize = 1; } if (verbose) std::cout << "generating the code with batch size = " << batchSize << " ...\n"; - parserCode = "model.Generate(TMVA::Experimental::SOFIE::Options::kDefault," + + parserCode += "model.Generate(TMVA::Experimental::SOFIE::Options::kDefault," + + ROOT::Math::Util::ToString(batchSize) + "); \n"; + + // add custom operators if needed + if (fCustomOperators.size() > 0) { + if (verbose) { + parserCode += "model.PrintRequiredInputTensors();\n"; + parserCode += "model.PrintIntermediateTensors();\n"; + parserCode += "model.PrintOutputTensors();\n"; + } + for (auto & op : fCustomOperators) { + parserCode += "{ auto p = new TMVA::Experimental::SOFIE::ROperator_Custom(\"" + + op.fOpName + "\"," + op.fInputNames + "," + op.fOutputNames + "," + op.fOutputShapes + ",\"" + op.fFileName + "\");\n"; + parserCode += "std::unique_ptr op(p);\n"; + parserCode += "model.AddOperator(std::move(op));\n}\n"; + } + parserCode += "model.Generate(TMVA::Experimental::SOFIE::Options::kDefault," + ROOT::Math::Util::ToString(batchSize) + "); \n"; - if (verbose) + } + if (verbose > 1) parserCode += "model.PrintGenerated(); \n"; parserCode += "model.OutputGenerated();\n"; - if (verbose) std::cout << parserCode << std::endl; + parserCode += "int nInputs = model.GetInputTensorNames().size();\n"; + + // need information on number of inputs (assume output is 1) + + //end of parsing code, close the scope and return 1 to indicate a success + parserCode += "return nInputs;\n}\n"; - gROOT->ProcessLine(parserCode.c_str()); + if (verbose) std::cout << "//ParserCode being executed:\n" << parserCode << std::endl; - if (verbose) std::cout << "compile generated code \n"; + auto iret = gROOT->ProcessLine(parserCode.c_str()); + if (iret <= 0) { + std::string msg = "RSofieReader: error processing the parser code: \n" + parserCode; + throw std::runtime_error(msg); + } + fNInputs = iret; + if (fNInputs > 3) { + throw std::runtime_error("RSofieReader does not yet support model with > 3 inputs"); + } // compile now the generated code and create Session class std::string modelHeader = modelName + ".hxx"; + if (verbose) std::cout << "compile generated code from file " <AccessPathName(modelHeader.c_str())) { - //std::string msg = "input header file is not existing"; - Error("RSofieReader","Input header file %s is not existing",modelHeader.c_str()); - return; + std::string msg = "RSofieReader: input header file " + modelHeader + " is not existing"; + throw std::runtime_error(msg); } - if (verbose) std::cout << "Parsing SOFIE model " << modelName << std::endl; + if (verbose) std::cout << "Creating Inference function for model " << modelName << std::endl; std::string declCode; declCode += "#pragma cling optimize(2)\n"; declCode += "#include \"" + modelHeader + "\"\n"; + // create global session instance: use UUID to have an unique name std::string sessionClassName = "TMVA_SOFIE_" + modelName + "::Session"; TUUID uuid; std::string uidName = uuid.AsString(); @@ -186,32 +218,81 @@ public: std::string sessionName = "session_" + uidName; declCode += sessionClassName + " " + sessionName + ";"; - if (verbose) std::cout << declCode << std::endl; + if (verbose) std::cout << "//global session declaration\n" << declCode << std::endl; - gInterpreter->Declare(declCode.c_str()); - fInitialized = true; - TClass * sessionClass = TClass::GetClass(sessionClassName.c_str()); + bool ret = gInterpreter->Declare(declCode.c_str()); + if (!ret) { + std::string msg = "RSofieReader: error compiling inference code and creating session class\n" + declCode; + throw std::runtime_error(msg); + } - fSessionPtr = (void*) gInterpreter->Calc(sessionName.c_str()); + fSessionPtr = (void *) gInterpreter->Calc(sessionName.c_str()); // define a function to be called for inference std::stringstream ifuncCode; std::string funcName = "SofieInference_" + uidName; - ifuncCode << "std::vector " + funcName + "( void * ptr, float * data) {\n"; - ifuncCode << sessionClassName << " * s = " << "(" << sessionClassName << "*) (ptr);\n"; - ifuncCode << "return s->infer(data);\n"; + ifuncCode << "std::vector " + funcName + "( void * ptr"; + for (int i = 0; i < fNInputs; i++) + ifuncCode << ", float * data" << i; + ifuncCode << ") {\n"; + ifuncCode << " " << sessionClassName << " * s = " << "(" << sessionClassName << "*) (ptr);\n"; + ifuncCode << " return s->infer("; + for (int i = 0; i < fNInputs; i++) { + if (i>0) ifuncCode << ","; + ifuncCode << "data" << i; + } + ifuncCode << ");\n"; ifuncCode << "}\n"; - if (verbose) std::cout << ifuncCode.str() << std::endl; + if (verbose) std::cout << "//Inference function code using global session instance\n" + << ifuncCode.str() << std::endl; + + ret = gInterpreter->Declare(ifuncCode.str().c_str()); + if (!ret) { + std::string msg = "RSofieReader: error compiling inference function\n" + ifuncCode.str(); + throw std::runtime_error(msg); + } + fFuncPtr = (void *) gInterpreter->Calc(funcName.c_str()); + //fFuncPtr = reinterpret_cast (*)(void *, const float *)>(fptr); + fInitialized = true; + } + + // Add custum operator + void AddCustomOperator(const std::string &opName, const std::string &inputNames, const std::string & outputNames, + const std::string & outputShapes, const std::string & fileName) { + if (fInitialized) std::cout << "WARNING: Model is already loaded and initialised. It must be done after adding the custom operators" << std::endl; + fCustomOperators.push_back( {fileName, opName,inputNames, outputNames,outputShapes}); + } - gInterpreter->Declare(ifuncCode.str().c_str()); - auto fptr = gInterpreter->Calc(funcName.c_str()); - fFuncPtr = reinterpret_cast (*)(void *, const float *)>(fptr); - //fFuncPtr = fptr2; + // implementations for different outputs + std::vector DoCompute(const std::vector & x1) { + if (fNInputs != 1) { + std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs); + throw std::runtime_error(msg); + } + auto fptr = reinterpret_cast (*)(void *, const float *)>(fFuncPtr); + return fptr(fSessionPtr, x1.data()); + } + std::vector DoCompute(const std::vector & x1, const std::vector & x2) { + if (fNInputs != 2) { + std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs); + throw std::runtime_error(msg); + } + auto fptr = reinterpret_cast (*)(void *, const float *, const float *)>(fFuncPtr); + return fptr(fSessionPtr, x1.data(),x2.data()); + } + std::vector DoCompute(const std::vector & x1, const std::vector & x2, const std::vector & x3) { + if (fNInputs != 3) { + std::string msg = "Wrong number of inputs - model requires " + std::to_string(fNInputs); + throw std::runtime_error(msg); + } + auto fptr = reinterpret_cast (*)(void *, const float *, const float *, const float *)>(fFuncPtr); + return fptr(fSessionPtr, x1.data(),x2.data(),x3.data()); } /// Compute model prediction on vector - std::vector Compute(const std::vector &x) + template + std::vector Compute(T... x) { if(!fInitialized) { return std::vector(); @@ -221,13 +302,24 @@ public: R__WRITE_LOCKGUARD(ROOT::gCoreMutex); // Evaluate TMVA model (need to add support for multiple outputs) - auto result = fFuncPtr(fSessionPtr, x.data()); - return result; + return DoCompute(x...); } + std::vector Compute(const std::vector &x) { + if(!fInitialized) { + return std::vector(); + } + + // Take lock to protect model evaluation + R__WRITE_LOCKGUARD(ROOT::gCoreMutex); + + // Evaluate TMVA model (need to add support for multiple outputs) + return DoCompute(x); + } /// Compute model prediction on input RTensor /// The shape of the input tensor should be {nevents, nfeatures} /// and the return shape will be {nevents, noutputs} + /// support for now only a single input RTensor Compute(RTensor &x) { if(!fInitialized) { @@ -235,14 +327,15 @@ public: } const auto nrows = x.GetShape()[0]; const auto rowsize = x.GetStrides()[0]; - auto result = fFuncPtr(fSessionPtr, x.GetData()); + auto fptr = reinterpret_cast (*)(void *, const float *)>(fFuncPtr); + auto result = fptr(fSessionPtr, x.GetData()); RTensor y({nrows, result.size()}, MemoryLayout::ColumnMajor); std::copy(result.begin(),result.end(), y.GetData()); //const bool layout = x.GetMemoryLayout() == MemoryLayout::ColumnMajor ? false : true; // assume column major layout for (size_t i = 1; i < nrows; i++) { - result = fFuncPtr(fSessionPtr, x.GetData() + i*rowsize); + result = fptr(fSessionPtr, x.GetData() + i*rowsize); std::copy(result.begin(),result.end(), y.GetData() + i*result.size()); } return y; @@ -251,8 +344,19 @@ public: private: bool fInitialized = false; + int fNInputs = 0; void * fSessionPtr = nullptr; - std::function (void *, const float *)> fFuncPtr; + void * fFuncPtr = nullptr; + + // data to insert custom operators + struct CustomOperatorData { + std::string fFileName; // code implementing the custom operator + std::string fOpName; // operator name + std::string fInputNames; // input tensor names (convert as string as {"n1", "n2"}) + std::string fOutputNames; // output tensor names converted as trind + std::string fOutputShapes; // output shapes + }; + std::vector fCustomOperators; }; diff --git a/tmva/tmva/inc/TMVA/RTensor.hxx b/tmva/tmva/inc/TMVA/RTensor.hxx index 0e15cb3cd5874..d645009ee0f78 100644 --- a/tmva/tmva/inc/TMVA/RTensor.hxx +++ b/tmva/tmva/inc/TMVA/RTensor.hxx @@ -257,6 +257,7 @@ public: RTensor Squeeze() const; RTensor ExpandDims(int idx) const; RTensor Reshape(const Shape_t &shape) const; + RTensor Resize(const Shape_t &shape); RTensor Slice(const Slice_t &slice); // Iterator class @@ -453,20 +454,18 @@ inline RTensor RTensor::ExpandDims(i auto shape = fShape; auto strides = fStrides; if (idx < 0) { - if (len + idx + 1 < 0) { - throw std::runtime_error("Given negative index is invalid."); - } - shape.insert(shape.end() + 1 + idx, 1); - strides.insert(strides.begin() + 1 + idx, 1); - } else { - if (idx > len) { - throw std::runtime_error("Given index is invalid."); - } - shape.insert(shape.begin() + idx, 1); - strides.insert(strides.begin() + idx, 1); + idx = len + 1 + idx; + } + if (idx < 0) { + throw std::runtime_error("Given negative index is invalid."); + } + else if (idx > len) { + throw std::runtime_error("Given index is invalid."); } + shape.insert(shape.begin() + idx, 1); + strides = Internal::ComputeStridesFromShape(shape, fLayout); - // Create copy, attach new shape and strides and return + // Create view copy, attach new shape and strides and return RTensor x(*this); x.fShape = shape; x.fStrides = strides; @@ -486,6 +485,23 @@ inline RTensor RTensor::Reshape(cons return x; } +/// \brief Resize tensor +/// \param[in] shape Shape vector +/// \returns New RTensor +/// Resize tensor into new shape +template +inline RTensor RTensor::Resize(const Shape_t &shape) +{ + // Create new tensor with the specified shape + RTensor x(shape, fLayout); + + // Copying contents from previous tensor + size_t n = (x.GetSize()>fSize) ? fSize : x.GetSize(); + std::copy(this->GetData(), this->GetData() + n, x.GetData() ); + + return x; +} + /// \brief Create a slice of the tensor /// \param[in] slice Slice vector /// \returns New RTensor diff --git a/tmva/tmva/src/Classification.cxx b/tmva/tmva/src/Classification.cxx index 2b40dba2b2063..58b21238dc63a 100644 --- a/tmva/tmva/src/Classification.cxx +++ b/tmva/tmva/src/Classification.cxx @@ -129,9 +129,9 @@ void TMVA::Experimental::ClassificationResult::Show() fLogger << kINFO << "DataSet MVA :" << Endl; fLogger << kINFO << "Name: Method/Title: ROC-integ :" << Endl; fLogger << kINFO << hLine << Endl; - fLogger << kINFO << Form("%-20s %-15s %#1.3f :", fDataLoaderName.Data(), - Form("%s/%s", fMethod.GetValue("MethodName").Data(), - fMethod.GetValue("MethodTitle").Data()), + fLogger << kINFO << TString::Format("%-20s %-15s %#1.3f :", fDataLoaderName.Data(), + TString::Format("%s/%s", fMethod.GetValue("MethodName").Data(), + fMethod.GetValue("MethodTitle").Data()).Data(), GetROCIntegral()) << Endl; fLogger << kINFO << hLine << Endl; @@ -149,8 +149,8 @@ void TMVA::Experimental::ClassificationResult::Show() TGraph *TMVA::Experimental::ClassificationResult::GetROCGraph(UInt_t iClass, TMVA::Types::ETreeType type) { TGraph *roc = GetROC(iClass, type)->GetROCCurve(); - roc->SetName(Form("%s/%s", GetMethodName().Data(), GetMethodTitle().Data())); - roc->SetTitle(Form("%s/%s", GetMethodName().Data(), GetMethodTitle().Data())); + roc->SetName(TString::Format("%s/%s", GetMethodName().Data(), GetMethodTitle().Data()).Data()); + roc->SetTitle(TString::Format("%s/%s", GetMethodName().Data(), GetMethodTitle().Data()).Data()); roc->GetXaxis()->SetTitle(" Signal Efficiency "); roc->GetYaxis()->SetTitle(" Background Rejection "); return roc; @@ -262,7 +262,7 @@ void TMVA::Experimental::Classification::Evaluate() #ifndef _MSC_VER fWorkers.SetNWorkers(fJobs); #endif - auto executor = [=](UInt_t workerID) -> ClassificationResult { + auto executor = [this](UInt_t workerID) -> ClassificationResult { TMVA::MsgLogger::InhibitOutput(); TMVA::gConfig().SetSilent(kTRUE); TMVA::gConfig().SetUseColor(kFALSE); @@ -271,8 +271,8 @@ void TMVA::Experimental::Classification::Evaluate() auto methodtitle = fMethods[workerID].GetValue("MethodTitle"); auto meth = GetMethod(methodname, methodtitle); if (!IsSilentFile()) { - auto fname = Form(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); - auto f = new TFile(fname, "RECREATE"); + auto fname = TString::Format(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); + auto f = new TFile(fname.Data(), "RECREATE"); f->mkdir(fDataLoader->GetName()); SetFile(f); meth->SetFile(f); @@ -302,15 +302,16 @@ void TMVA::Experimental::Classification::Evaluate() Log() << kINFO << hLine << Endl; for (auto &r : fResults) { - Log() << kINFO << Form("%-20s %-15s %#1.3f :", r.GetDataLoaderName().Data(), - Form("%s/%s", r.GetMethodName().Data(), r.GetMethodTitle().Data()), r.GetROCIntegral()) + Log() << kINFO << TString::Format("%-20s %-15s %#1.3f :", r.GetDataLoaderName().Data(), + TString::Format("%s/%s", r.GetMethodName().Data(), r.GetMethodTitle().Data()).Data(), + r.GetROCIntegral()) << Endl; } Log() << kINFO << hLine << Endl; Log() << kINFO << "-----------------------------------------------------" << Endl; Log() << kHEADER << "Evaluation done." << Endl << Endl; - Log() << kINFO << Form("Jobs = %d Real Time = %lf ", fJobs, fTimer.RealTime()) << Endl; + Log() << kINFO << TString::Format("Jobs = %d Real Time = %lf ", fJobs, fTimer.RealTime()) << Endl; Log() << kINFO << "-----------------------------------------------------" << Endl; Log() << kINFO << "Evaluation done." << Endl; TMVA::gConfig().SetSilent(kTRUE); @@ -338,10 +339,10 @@ void TMVA::Experimental::Classification::TrainMethod(TString methodname, TString auto method = GetMethod(methodname, methodtitle); if (!method) { Log() << kFATAL - << Form("Trying to train method %s %s that maybe is not booked.", methodname.Data(), methodtitle.Data()) + << TString::Format("Trying to train method %s %s that maybe is not booked.", methodname.Data(), methodtitle.Data()) << Endl; } - Log() << kHEADER << gTools().Color("bold") << Form("Training method %s %s", methodname.Data(), methodtitle.Data()) + Log() << kHEADER << gTools().Color("bold") << TString::Format("Training method %s %s", methodname.Data(), methodtitle.Data()) << gTools().Color("reset") << Endl; Event::SetIsTraining(kTRUE); @@ -527,7 +528,7 @@ void TMVA::Experimental::Classification::TestMethod(TString methodname, TString auto method = GetMethod(methodname, methodtitle); if (!method) { Log() << kFATAL - << Form("Trying to train method %s %s that maybe is not booked.", methodname.Data(), methodtitle.Data()) + << TString::Format("Trying to train method %s %s that maybe is not booked.", methodname.Data(), methodtitle.Data()) << Endl; } @@ -743,54 +744,54 @@ void TMVA::Experimental::Classification::TestMethod(TString methodname, TString if (nmeth > 1) { Log() << kINFO << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Inter-MVA correlation matrix (signal):" << Endl; gTools().FormattedOutput(mvaMatS, *theVars, Log()); Log() << kINFO << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Inter-MVA correlation matrix (background):" << Endl; gTools().FormattedOutput(mvaMatB, *theVars, Log()); Log() << kINFO << Endl; } - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Correlations between input variables and MVA response (signal):" << Endl; gTools().FormattedOutput(varmvaMatS, theInputVars, *theVars, Log()); Log() << kINFO << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Correlations between input variables and MVA response (background):" << Endl; gTools().FormattedOutput(varmvaMatB, theInputVars, *theVars, Log()); Log() << kINFO << Endl; } else - Log() << kWARNING << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kWARNING << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << " cannot compute correlation matrices" << Endl; // print overlap matrices - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "The following \"overlap\" matrices contain the fraction of events for which " << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "the MVAs 'i' and 'j' have returned conform answers about \"signal-likeness\"" << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "An event is signal-like, if its MVA output exceeds the following value:" << Endl; gTools().FormattedOutput(rvec, *theVars, "Method", "Cut value", Log()); - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "which correspond to the working point: eff(signal) = 1 - eff(background)" << Endl; // give notice that cut method has been excluded from this test if (nmeth != 1) - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Note: no correlations and overlap with cut method are provided at present" << Endl; if (nmeth > 1) { Log() << kINFO << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Inter-MVA overlap matrix (signal):" << Endl; gTools().FormattedOutput(*overlapS, *theVars, Log()); Log() << kINFO << Endl; - Log() << kINFO << Form("Dataset[%s] : ", method->fDataSetInfo.GetName()) + Log() << kINFO << TString::Format("Dataset[%s] : ", method->fDataSetInfo.GetName()) << "Inter-MVA overlap matrix (background):" << Endl; gTools().FormattedOutput(*overlapB, *theVars, Log()); } @@ -853,11 +854,11 @@ void TMVA::Experimental::Classification::TestMethod(TString methodname, TString // cannot compute separation/significance -> no MVA (usually for Cuts) fResult.fROCIntegral = effArea[k][i]; Log() << kINFO - << Form("%-13s %-15s: %#1.3f", fDataLoader->GetName(), methodName.Data(), fResult.fROCIntegral) + << TString::Format("%-13s %-15s: %#1.3f", fDataLoader->GetName(), methodName.Data(), fResult.fROCIntegral) << Endl; } else { fResult.fROCIntegral = rocIntegral; - Log() << kINFO << Form("%-13s %-15s: %#1.3f", datasetName.Data(), methodName.Data(), rocIntegral) + Log() << kINFO << TString::Format("%-13s %-15s: %#1.3f", datasetName.Data(), methodName.Data(), rocIntegral) << Endl; } } @@ -881,8 +882,8 @@ void TMVA::Experimental::Classification::TestMethod(TString methodname, TString if (k == 1) mname[k][i].ReplaceAll("Variable_", ""); - Log() << kINFO << Form("%-20s %-15s: %#1.3f (%#1.3f) %#1.3f (%#1.3f) %#1.3f (%#1.3f)", - method->fDataSetInfo.GetName(), (const char *)mname[k][i], eff01[k][i], + Log() << kINFO << TString::Format("%-20s %-15s: %#1.3f (%#1.3f) %#1.3f (%#1.3f) %#1.3f (%#1.3f)", + method->fDataSetInfo.GetName(), mname[k][i].Data(), eff01[k][i], trainEff01[k][i], eff10[k][i], trainEff10[k][i], eff30[k][i], trainEff30[k][i]) << Endl; } @@ -997,7 +998,7 @@ TMVA::Experimental::Classification::GetROC(TMVA::MethodBase *method, UInt_t iCla UInt_t nClasses = method->DataInfo().GetNClasses(); if (this->fAnalysisType == Types::kMulticlass && iClass >= nClasses) { - Log() << kERROR << Form("Given class number (iClass = %i) does not exist. There are %i classes in dataset.", + Log() << kERROR << TString::Format("Given class number (iClass = %i) does not exist. There are %i classes in dataset.", iClass, nClasses) << Endl; return nullptr; @@ -1075,7 +1076,7 @@ Double_t TMVA::Experimental::Classification::GetROCIntegral(TString methodname, TMVA::ROCCurve *rocCurve = GetROC(methodname, methodtitle, iClass); if (!rocCurve) { Log() << kFATAL - << Form("ROCCurve object was not created in MethodName = %s MethodTitle = %s not found with Dataset = %s ", + << TString::Format("ROCCurve object was not created in MethodName = %s MethodTitle = %s not found with Dataset = %s ", methodname.Data(), methodtitle.Data(), fDataLoader->GetName()) << Endl; return 0; @@ -1130,20 +1131,20 @@ void TMVA::Experimental::Classification::MergeFiles() { auto dsdir = fFile->mkdir(fDataLoader->GetName()); // dataset dir - TTree *TrainTree = 0; - TTree *TestTree = 0; - TFile *ifile = 0; - TFile *ofile = 0; + TTree *TrainTree = nullptr; + TTree *TestTree = nullptr; + TFile *ifile = nullptr; + TFile *ofile = nullptr; for (UInt_t i = 0; i < fMethods.size(); i++) { auto methodname = fMethods[i].GetValue("MethodName"); auto methodtitle = fMethods[i].GetValue("MethodTitle"); - auto fname = Form(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); - TDirectoryFile *ds = 0; + auto fname = TString::Format(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); + TDirectoryFile *ds = nullptr; if (i == 0) { - ifile = new TFile(fname); + ifile = new TFile(fname.Data()); ds = (TDirectoryFile *)ifile->Get(fDataLoader->GetName()); } else { - ofile = new TFile(fname); + ofile = new TFile(fname.Data()); ds = (TDirectoryFile *)ofile->Get(fDataLoader->GetName()); } auto tmptrain = (TTree *)ds->Get("TrainTree"); @@ -1151,10 +1152,10 @@ void TMVA::Experimental::Classification::MergeFiles() fFile->cd(); fFile->cd(fDataLoader->GetName()); - auto methdirname = Form("Method_%s", methodtitle.Data()); - auto methdir = dsdir->mkdir(methdirname, methdirname); + auto methdirname = TString::Format("Method_%s", methodtitle.Data()); + auto methdir = dsdir->mkdir(methdirname.Data(), methdirname.Data()); auto methdirbase = methdir->mkdir(methodtitle.Data(), methodtitle.Data()); - auto mfdir = (TDirectoryFile *)ds->Get(methdirname); + auto mfdir = (TDirectoryFile *)ds->Get(methdirname.Data()); auto mfdirbase = (TDirectoryFile *)mfdir->Get(methodtitle.Data()); CopyFrom(mfdirbase, (TFile *)methdirbase); @@ -1188,7 +1189,7 @@ void TMVA::Experimental::Classification::MergeFiles() for (UInt_t i = 0; i < fMethods.size(); i++) { auto methodname = fMethods[i].GetValue("MethodName"); auto methodtitle = fMethods[i].GetValue("MethodTitle"); - auto fname = Form(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); - gSystem->Unlink(fname); + auto fname = TString::Format(".%s%s%s.root", fDataLoader->GetName(), methodname.Data(), methodtitle.Data()); + gSystem->Unlink(fname.Data()); } } diff --git a/tmva/tmva/src/CrossValidation.cxx b/tmva/tmva/src/CrossValidation.cxx index 5fab669307e70..5948595488cf5 100644 --- a/tmva/tmva/src/CrossValidation.cxx +++ b/tmva/tmva/src/CrossValidation.cxx @@ -157,12 +157,12 @@ void TMVA::CrossValidationResult::Print() const MsgLogger fLogger("CrossValidation"); fLogger << kHEADER << " ==== Results ====" << Endl; for(auto &item:fROCs) { - fLogger << kINFO << Form("Fold %i ROC-Int : %.4f",item.first,item.second) << std::endl; + fLogger << kINFO << TString::Format("Fold %i ROC-Int : %.4f",item.first,item.second) << std::endl; } fLogger << kINFO << "------------------------" << Endl; - fLogger << kINFO << Form("Average ROC-Int : %.4f",GetROCAverage()) << Endl; - fLogger << kINFO << Form("Std-Dev ROC-Int : %.4f",GetROCStandardDeviation()) << Endl; + fLogger << kINFO << TString::Format("Average ROC-Int : %.4f",GetROCAverage()) << Endl; + fLogger << kINFO << TString::Format("Std-Dev ROC-Int : %.4f",GetROCStandardDeviation()) << Endl; TMVA::gConfig().SetSilent(kTRUE); } @@ -403,11 +403,11 @@ void TMVA::CrossValidation::ParseOptions() fOutputFactoryOptions += "!V:"; } - fCvFactoryOptions += Form("VerboseLevel=%s:", fVerboseLevel.Data()); - fOutputFactoryOptions += Form("VerboseLevel=%s:", fVerboseLevel.Data()); + fCvFactoryOptions += TString::Format("VerboseLevel=%s:", fVerboseLevel.Data()); + fOutputFactoryOptions += TString::Format("VerboseLevel=%s:", fVerboseLevel.Data()); - fCvFactoryOptions += Form("AnalysisType=%s:", fAnalysisTypeStr.Data()); - fOutputFactoryOptions += Form("AnalysisType=%s:", fAnalysisTypeStr.Data()); + fCvFactoryOptions += TString::Format("AnalysisType=%s:", fAnalysisTypeStr.Data()); + fOutputFactoryOptions += TString::Format("AnalysisType=%s:", fAnalysisTypeStr.Data()); if (!fDrawProgressBar) { fCvFactoryOptions += "!DrawProgressBar:"; @@ -415,8 +415,8 @@ void TMVA::CrossValidation::ParseOptions() } if (fTransformations != "") { - fCvFactoryOptions += Form("Transformations=%s:", fTransformations.Data()); - fOutputFactoryOptions += Form("Transformations=%s:", fTransformations.Data()); + fCvFactoryOptions += TString::Format("Transformations=%s:", fTransformations.Data()); + fOutputFactoryOptions += TString::Format("Transformations=%s:", fTransformations.Data()); } if (fCorrelations) { @@ -436,8 +436,8 @@ void TMVA::CrossValidation::ParseOptions() } if (fSilent) { - fCvFactoryOptions += Form("Silent:"); - fOutputFactoryOptions += Form("Silent:"); + fCvFactoryOptions += "Silent:"; + fOutputFactoryOptions += "Silent:"; } // CE specific options @@ -643,7 +643,7 @@ void TMVA::CrossValidation::Evaluate() // Serialise the cross evaluated method TString options = - Form("SplitExpr=%s:NumFolds=%i" + TString::Format("SplitExpr=%s:NumFolds=%i" ":EncapsulatedMethodName=%s" ":EncapsulatedMethodTypeName=%s" ":OutputEnsembling=%s", diff --git a/tmva/tmva/src/DataInputHandler.cxx b/tmva/tmva/src/DataInputHandler.cxx index 0f40f35657bb8..1edbdb96069ec 100644 --- a/tmva/tmva/src/DataInputHandler.cxx +++ b/tmva/tmva/src/DataInputHandler.cxx @@ -153,7 +153,8 @@ TTree* TMVA::DataInputHandler::ReadInputTree( const TString& dataFile ) { TTree* tr = new TTree( "tmp", dataFile ); std::ifstream in(dataFile); - tr->SetDirectory(0); Log() << kWARNING << "Watch out, I (Helge) made the Tree not associated to the current directory .. Hopefully that does not have unwanted consequences" << Endl; + tr->SetDirectory(nullptr); + Log() << kWARNING << "Watch out, I (Helge) made the Tree not associated to the current directory .. Hopefully that does not have unwanted consequences" << Endl; if (!in.good()) Log() << kFATAL << "Could not open file: " << dataFile << Endl; in.close(); diff --git a/tmva/tmva/src/DataLoader.cxx b/tmva/tmva/src/DataLoader.cxx index 7a46fd56ea80e..2980ff839e231 100644 --- a/tmva/tmva/src/DataLoader.cxx +++ b/tmva/tmva/src/DataLoader.cxx @@ -71,7 +71,7 @@ ClassImp(TMVA::DataLoader); For example, by setting ~~~~~~~~~~~~~~~{.cpp} TMVA::gConfig()::GetIONames().fWeightFileDirPrefix = "/tmp"; - TMVA::gConfig()::GetIONames().fWeightFileDir = "myTrainigResults"; + TMVA::gConfig()::GetIONames().fWeightFileDir = "myTrainingResults"; ~~~~~~~~~~~~~~~ The training results will be stored in the `/tmp/thedlName/myTrainingResults` directory. @@ -195,7 +195,7 @@ TMVA::DataLoader* TMVA::DataLoader::VarTransform(TString trafoDefinition) TTree* TMVA::DataLoader::CreateEventAssignTrees( const TString& name ) { TTree * assignTree = new TTree( name, name ); - assignTree->SetDirectory(0); + assignTree->SetDirectory(nullptr); assignTree->Branch( "type", &fATreeType, "ATreeType/I" ); assignTree->Branch( "weight", &fATreeWeight, "ATreeWeight/F" ); @@ -292,8 +292,8 @@ void TMVA::DataLoader::AddEvent( const TString& className, Types::ETreeType tt, } if (fTrainAssignTree[clIndex]==0) { // does not exist yet - fTrainAssignTree[clIndex] = CreateEventAssignTrees( Form("TrainAssignTree_%s", className.Data()) ); - fTestAssignTree[clIndex] = CreateEventAssignTrees( Form("TestAssignTree_%s", className.Data()) ); + fTrainAssignTree[clIndex] = CreateEventAssignTrees( TString::Format("TrainAssignTree_%s", className.Data()).Data() ); + fTestAssignTree[clIndex] = CreateEventAssignTrees( TString::Format("TestAssignTree_%s", className.Data()).Data() ); } fATreeType = clIndex; @@ -607,8 +607,8 @@ void TMVA::DataLoader::PrepareTrainingAndTestTree( const TCut& cut, AddCut( cut ); - DefaultDataSetInfo().SetSplitOptions( Form("nTrain_Signal=%i:nTrain_Background=%i:nTest_Signal=%i:nTest_Background=%i:%s", - NsigTrain, NbkgTrain, NsigTest, NbkgTest, otherOpt.Data()) ); + DefaultDataSetInfo().SetSplitOptions( TString::Format("nTrain_Signal=%i:nTrain_Background=%i:nTest_Signal=%i:nTest_Background=%i:%s", + NsigTrain, NbkgTrain, NsigTest, NbkgTest, otherOpt.Data()).Data() ); } //////////////////////////////////////////////////////////////////////////////// @@ -621,8 +621,8 @@ void TMVA::DataLoader::PrepareTrainingAndTestTree( const TCut& cut, Int_t Ntrain AddCut( cut ); - DefaultDataSetInfo().SetSplitOptions( Form("nTrain_Signal=%i:nTrain_Background=%i:nTest_Signal=%i:nTest_Background=%i:SplitMode=Random:EqualTrainSample:!V", - Ntrain, Ntrain, Ntest, Ntest) ); + DefaultDataSetInfo().SetSplitOptions( TString::Format("nTrain_Signal=%i:nTrain_Background=%i:nTest_Signal=%i:nTest_Background=%i:SplitMode=Random:EqualTrainSample:!V", + Ntrain, Ntrain, Ntest, Ntest).Data() ); } //////////////////////////////////////////////////////////////////////////////// diff --git a/tmva/tmva/src/DataSet.cxx b/tmva/tmva/src/DataSet.cxx index 6a101596088ba..e9176e7dad095 100644 --- a/tmva/tmva/src/DataSet.cxx +++ b/tmva/tmva/src/DataSet.cxx @@ -62,7 +62,7 @@ TMVA::DataSet::DataSet(const DataSetInfo& dsi) fCurrentTreeIdx(0), fCurrentEventIdx(0), fHasNegativeEventWeights(kFALSE), - fLogger( new MsgLogger(TString(TString("Dataset:")+dsi.GetName()).Data()) ), + fLogger( new MsgLogger((TString("Dataset:")+dsi.GetName()).Data()) ), fTrainingBlockSize(0) { @@ -94,7 +94,7 @@ TMVA::DataSet::DataSet() fCurrentTreeIdx(0), fCurrentEventIdx(0), fHasNegativeEventWeights(kFALSE), - fLogger( new MsgLogger(TString(TString("Dataset:")+GetName()).Data()) ), + fLogger( new MsgLogger((TString("Dataset:")+GetName()).Data()) ), fTrainingBlockSize(0) { @@ -172,13 +172,13 @@ Long64_t TMVA::DataSet::GetNClassEvents( Int_t type, UInt_t classNumber ) } catch (std::out_of_range &) { ClassInfo* ci = fdsi->GetClassInfo( classNumber ); - Log() << kFATAL << Form("Dataset[%s] : ",fdsi->GetName()) << "No " << (type==0?"training":(type==1?"testing":"_unknown_type_")) + Log() << kFATAL << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "No " << (type==0?"training":(type==1?"testing":"_unknown_type_")) << " events for class " << (ci==NULL?"_no_name_known_":ci->GetName()) << " (index # "<GetName()) << "ERROR/CAUGHT : DataSet/GetNClassEvents, .. unknown error" << Endl; + Log() << kFATAL << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "ERROR/CAUGHT : DataSet/GetNClassEvents, .. unknown error" << Endl; } return 0; } @@ -320,19 +320,19 @@ void TMVA::DataSet::DeleteResults( const TString & resultsName, if (fResults.empty()) return; if (UInt_t(type) > fResults.size()){ - Log()<GetName()) << "you asked for an Treetype (training/testing/...)" + Log()<GetName()) << "you asked for an Treetype (training/testing/...)" << " whose index " << type << " does not exist " << Endl; } std::map< TString, Results* >& resultsForType = fResults[UInt_t(type)]; std::map< TString, Results* >::iterator it = resultsForType.find(resultsName); if (it!=resultsForType.end()) { - Log() << kDEBUG << Form("Dataset[%s] : ",fdsi->GetName()) << " Delete Results previous existing result:" << resultsName + Log() << kDEBUG << TString::Format("Dataset[%s] : ",fdsi->GetName()) << " Delete Results previous existing result:" << resultsName << " of type " << type << Endl; delete it->second; resultsForType.erase(it->first); } else { - Log() << kINFO << Form("Dataset[%s] : ",fdsi->GetName()) << "could not fine Result class of " << resultsName + Log() << kINFO << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "could not fine Result class of " << resultsName << " of type " << type << " which I should have deleted" << Endl; } } @@ -346,7 +346,7 @@ void TMVA::DataSet::DeleteAllResults(Types::ETreeType type, if (fResults.empty()) return; if (UInt_t(type) > fResults.size()){ - Log()<GetName()) << "you asked for an Treetype (training/testing/...)" + Log()<GetName()) << "you asked for an Treetype (training/testing/...)" << " whose index " << type << " does not exist " << Endl; } @@ -355,7 +355,7 @@ void TMVA::DataSet::DeleteAllResults(Types::ETreeType type, for (auto && it : resultsForType) { auto & resultsName = it.first; - Log() << kDEBUG << Form("Dataset[%s] : ", fdsi->GetName()) + Log() << kDEBUG << TString::Format("Dataset[%s] : ", fdsi->GetName()) << " DeleteAllResults previous existing result: " << resultsName << " of type " << type << Endl; @@ -512,7 +512,7 @@ void TMVA::DataSet::CreateSampling() const if (!fSampling.at(treeIdx) ) return; if (fSamplingRandom == 0 ) - Log() << kFATAL<< Form("Dataset[%s] : ",fdsi->GetName()) + Log() << kFATAL<< TString::Format("Dataset[%s] : ",fdsi->GetName()) << "no random generator present for creating a random/importance sampling (initialized?)" << Endl; // delete the previous selection @@ -583,7 +583,7 @@ void TMVA::DataSet::EventResult( Bool_t successful, Long64_t evtNumber ) } for ( Long64_t iEvt = start; iEvt <= stop; iEvt++ ){ if (Long64_t(fSamplingEventList.at(fCurrentTreeIdx).size()) < iEvt) { - Log() << kWARNING << Form("Dataset[%s] : ",fdsi->GetName()) << "event number (" << iEvt + Log() << kWARNING << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "event number (" << iEvt << ") larger than number of sampled events (" << fSamplingEventList.at(fCurrentTreeIdx).size() << " of tree " << fCurrentTreeIdx << ")" << Endl; return; @@ -608,7 +608,7 @@ void TMVA::DataSet::EventResult( Bool_t successful, Long64_t evtNumber ) TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) { - Log() << kDEBUG << Form("Dataset[%s] : ",fdsi->GetName()) << "GetTree(" << ( type==Types::kTraining ? "training" : "testing" ) << ")" << Endl; + Log() << kDEBUG << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "GetTree(" << ( type==Types::kTraining ? "training" : "testing" ) << ")" << Endl; // the dataset does not hold the tree, this function returns a new tree every time it is called @@ -619,7 +619,7 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) SetCurrentType(type); const UInt_t t = TreeIndex(type); if (fResults.size() <= t) { - Log() << kWARNING << Form("Dataset[%s] : ",fdsi->GetName()) << "No results for treetype " << ( type==Types::kTraining ? "training" : "testing" ) + Log() << kWARNING << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "No results for treetype " << ( type==Types::kTraining ? "training" : "testing" ) << " found. Size=" << fResults.size() << Endl; } @@ -650,14 +650,14 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) // create all branches for the variables Int_t n = 0; Int_t ivar_array = 0; - Int_t arraySize = -1; + Int_t arraySize = -1; for (std::vector::const_iterator itVars = fdsi->GetVariableInfos().begin(); itVars != fdsi->GetVariableInfos().end(); ++itVars) { // has to be changed to take care of types different than float: TODO - if (!itVars->TestBit(DataSetInfo::kIsArrayVariable) ) + if (!itVars->TestBit(DataSetInfo::kIsArrayVariable) ) tree->Branch( (*itVars).GetInternalName(), &varVals[n], (*itVars).GetInternalName()+TString("/F") ); - else { + else { // variable is an array if (ivar_array == 0) { TString name = (*itVars).GetInternalName(); @@ -666,9 +666,9 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) tree->Branch(name, &varVals[n], name + TString::Format("[%d]/F", arraySize)); Log() << kDEBUG << "creating branch for array " << name << " with size " << arraySize << Endl; } - ivar_array++; + ivar_array++; if (ivar_array == arraySize) - ivar_array = 0; + ivar_array = 0; } n++; } @@ -697,8 +697,9 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) itMethod != fResults.at(t).end(); ++itMethod) { - Log() << kDEBUG << Form("Dataset[%s] : ",fdsi->GetName()) << "analysis type: " << (itMethod->second->GetAnalysisType()==Types::kRegression ? "Regression" : - (itMethod->second->GetAnalysisType()==Types::kMulticlass ? "Multiclass" : "Classification" )) << Endl; + Log() << kDEBUG << TString::Format("Dataset[%s] : ",fdsi->GetName()) + << "analysis type: " << (itMethod->second->GetAnalysisType()==Types::kRegression ? "Regression" : + (itMethod->second->GetAnalysisType()==Types::kMulticlass ? "Multiclass" : "Classification" )) << Endl; if (itMethod->second->GetAnalysisType() == Types::kClassification) { // classification @@ -712,7 +713,7 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) leafList.Append( fdsi->GetClassInfo( iCls )->GetName() ); leafList.Append( "/F" ); } - Log() << kDEBUG << Form("Dataset[%s] : ",fdsi->GetName()) << "itMethod->first " << itMethod->first << " LEAFLIST: " + Log() << kDEBUG << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "itMethod->first " << itMethod->first << " LEAFLIST: " << leafList << " itMethod->second " << itMethod->second << Endl; tree->Branch( itMethod->first, (metVals[n]), leafList ); } @@ -725,12 +726,12 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) // leafList.Append( fdsi->GetTargetInfo( iTgt ).GetLabel() ); leafList.Append( "/F" ); } - Log() << kDEBUG << Form("Dataset[%s] : ",fdsi->GetName()) << "itMethod->first " << itMethod->first << " LEAFLIST: " + Log() << kDEBUG << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "itMethod->first " << itMethod->first << " LEAFLIST: " << leafList << " itMethod->second " << itMethod->second << Endl; tree->Branch( itMethod->first, (metVals[n]), leafList ); } else { - Log() << kWARNING << Form("Dataset[%s] : ",fdsi->GetName()) << "Unknown analysis type for result found when writing TestTree." << Endl; + Log() << kWARNING << TString::Format("Dataset[%s] : ",fdsi->GetName()) << "Unknown analysis type for result found when writing TestTree." << Endl; } n++; @@ -806,7 +807,7 @@ TTree* TMVA::DataSet::GetTree( Types::ETreeType type ) tree->Fill(); } - Log() << kHEADER //<< Form("[%s] : ",fdsi.GetName()) + Log() << kHEADER //<< TString::Format("[%s] : ",fdsi.GetName()) << "Created tree '" << tree->GetName() << "' with " << tree->GetEntries() << " events" << Endl << Endl; SetCurrentType(savedType); diff --git a/tmva/tmva/src/DataSetFactory.cxx b/tmva/tmva/src/DataSetFactory.cxx index c7ab3c838f306..31e276758ad59 100644 --- a/tmva/tmva/src/DataSetFactory.cxx +++ b/tmva/tmva/src/DataSetFactory.cxx @@ -354,7 +354,7 @@ void TMVA::DataSetFactory::ChangeToNewTree( TreeInfo& tinfo, const DataSetInfo & for (formIt = fTargetFormulas.begin(), formItEnd = fTargetFormulas.end(); formIt!=formItEnd; ++formIt) if (*formIt) delete *formIt; fTargetFormulas.clear(); for (UInt_t i=0; iSetNFisherCoeff(nCoef); Double_t tmp; for (Int_t i=0; i< (Int_t) this->GetNFisherCoeff(); i++) { - gTools().ReadAttr(node, Form("fC%d",i), tmp ); + gTools().ReadAttr(node, TString::Format("fC%d",i).Data(), tmp); this->SetFisherCoeff(i,tmp); } }else{ @@ -493,7 +493,7 @@ void TMVA::DecisionTreeNode::AddAttributesToNode(void* node) const { gTools().AddAttr(node, "NCoef", GetNFisherCoeff()); for (Int_t i=0; i< (Int_t) this->GetNFisherCoeff(); i++) - gTools().AddAttr(node, Form("fC%d",i), this->GetFisherCoeff(i)); + gTools().AddAttr(node, TString::Format("fC%d",i).Data(), this->GetFisherCoeff(i)); gTools().AddAttr(node, "IVar", GetSelector()); gTools().AddAttr(node, "Cut", GetCutValue()); diff --git a/tmva/tmva/src/Factory.cxx b/tmva/tmva/src/Factory.cxx index ecda3e1294269..05cf8f3da2909 100644 --- a/tmva/tmva/src/Factory.cxx +++ b/tmva/tmva/src/Factory.cxx @@ -967,7 +967,7 @@ TGraph *TMVA::Factory::GetROCCurve(TString datasetname, TString theMethodName, B if (setTitles) { graph->GetYaxis()->SetTitle("Background rejection (Specificity)"); graph->GetXaxis()->SetTitle("Signal efficiency (Sensitivity)"); - graph->SetTitle(Form("Signal efficiency vs. Background rejection (%s)", theMethodName.Data())); + graph->SetTitle(TString::Format("Signal efficiency vs. Background rejection (%s)", theMethodName.Data()).Data()); } return graph; @@ -1081,8 +1081,8 @@ TCanvas *TMVA::Factory::GetROCCurve(TString datasetname, UInt_t iClass, Types::E return 0; } - TString name = Form("ROCCurve %s class %i", datasetname.Data(), iClass); - TCanvas *canvas = new TCanvas(name, "ROC Curve", 200, 10, 700, 500); + TString name = TString::Format("ROCCurve %s class %i", datasetname.Data(), iClass); + TCanvas *canvas = new TCanvas(name.Data(), "ROC Curve", 200, 10, 700, 500); canvas->SetGrid(); TMultiGraph *multigraph = this->GetROCCurveAsMultiGraph(datasetname, iClass, type); @@ -1093,14 +1093,14 @@ TCanvas *TMVA::Factory::GetROCCurve(TString datasetname, UInt_t iClass, Types::E multigraph->GetYaxis()->SetTitle("Background rejection (Specificity)"); multigraph->GetXaxis()->SetTitle("Signal efficiency (Sensitivity)"); - TString titleString = Form("Signal efficiency vs. Background rejection"); + TString titleString = TString::Format("Signal efficiency vs. Background rejection"); if (this->fAnalysisType == Types::kMulticlass) { - titleString = Form("%s (Class=%i)", titleString.Data(), iClass); + titleString = TString::Format("%s (Class=%i)", titleString.Data(), iClass); } // Workaround for TMultigraph not drawing title correctly. - multigraph->GetHistogram()->SetTitle(titleString); - multigraph->SetTitle(titleString); + multigraph->GetHistogram()->SetTitle(titleString.Data()); + multigraph->SetTitle(titleString.Data()); canvas->BuildLegend(0.15, 0.15, 0.35, 0.3, "MVA Method"); } @@ -1914,15 +1914,15 @@ void TMVA::Factory::EvaluateAllMethods(void) // TString header = "DataSet Name MVA Method "; // for (UInt_t icls = 0; icls < theMethod->fDataSetInfo.GetNClasses(); ++icls) { - // header += Form("%-12s ", theMethod->fDataSetInfo.GetClassInfo(icls)->GetName()); + // header += TString::Format("%-12s ", theMethod->fDataSetInfo.GetClassInfo(icls)->GetName()); // } // Log() << kINFO << header << Endl; // Log() << kINFO << hLine << Endl; // for (Int_t i = 0; i < nmeth_used[0]; i++) { - // TString res = Form("[%-14s] %-15s", theMethod->fDataSetInfo.GetName(), (const char *)mname[0][i]); + // TString res = TString::Format("[%-14s] %-15s", theMethod->fDataSetInfo.GetName(), mname[0][i].Data()); // for (UInt_t icls = 0; icls < theMethod->fDataSetInfo.GetNClasses(); ++icls) { - // res += Form("%#1.3f ", (multiclass_testEff[i][icls]) * (multiclass_testPur[i][icls])); + // res += TString::Format("%#1.3f ", (multiclass_testEff[i][icls]) * (multiclass_testPur[i][icls])); // } // Log() << kINFO << res << Endl; // } @@ -1933,10 +1933,10 @@ void TMVA::Factory::EvaluateAllMethods(void) // --- 1 vs Rest ROC AUC, signal efficiency @ given background efficiency // -------------------------------------------------------------------- - TString header1 = Form("%-15s%-15s%-15s%-15s%-15s%-15s", "Dataset", "MVA Method", "ROC AUC", "Sig eff@B=0.01", - "Sig eff@B=0.10", "Sig eff@B=0.30"); - TString header2 = Form("%-15s%-15s%-15s%-15s%-15s%-15s", "Name:", "/ Class:", "test (train)", "test (train)", - "test (train)", "test (train)"); + TString header1 = TString::Format("%-15s%-15s%-15s%-15s%-15s%-15s", "Dataset", "MVA Method", "ROC AUC", "Sig eff@B=0.01", + "Sig eff@B=0.10", "Sig eff@B=0.30"); + TString header2 = TString::Format("%-15s%-15s%-15s%-15s%-15s%-15s", "Name:", "/ Class:", "test (train)", "test (train)", + "test (train)", "test (train)"); Log() << kINFO << Endl; Log() << kINFO << "1-vs-rest performance metrics per class" << Endl; Log() << kINFO << hLine << Endl; @@ -1964,7 +1964,7 @@ void TMVA::Factory::EvaluateAllMethods(void) } Log() << kINFO << Endl; - TString row = Form("%-15s%-15s", datasetName.Data(), mvaName.Data()); + TString row = TString::Format("%-15s%-15s", datasetName.Data(), mvaName.Data()); Log() << kINFO << row << Endl; Log() << kINFO << "------------------------------" << Endl; @@ -1983,11 +1983,11 @@ void TMVA::Factory::EvaluateAllMethods(void) const Double_t effB01Test = rocCurveTest->GetEffSForEffB(0.01); const Double_t effB10Test = rocCurveTest->GetEffSForEffB(0.10); const Double_t effB30Test = rocCurveTest->GetEffSForEffB(0.30); - const TString rocaucCmp = Form("%5.3f (%5.3f)", rocaucTest, rocaucTrain); - const TString effB01Cmp = Form("%5.3f (%5.3f)", effB01Test, effB01Train); - const TString effB10Cmp = Form("%5.3f (%5.3f)", effB10Test, effB10Train); - const TString effB30Cmp = Form("%5.3f (%5.3f)", effB30Test, effB30Train); - row = Form("%-15s%-15s%-15s%-15s%-15s%-15s", "", className.Data(), rocaucCmp.Data(), effB01Cmp.Data(), + const TString rocaucCmp = TString::Format("%5.3f (%5.3f)", rocaucTest, rocaucTrain); + const TString effB01Cmp = TString::Format("%5.3f (%5.3f)", effB01Test, effB01Train); + const TString effB10Cmp = TString::Format("%5.3f (%5.3f)", effB10Test, effB10Train); + const TString effB30Cmp = TString::Format("%5.3f (%5.3f)", effB30Test, effB30Train); + row = TString::Format("%-15s%-15s%-15s%-15s%-15s%-15s", "", className.Data(), rocaucCmp.Data(), effB01Cmp.Data(), effB10Cmp.Data(), effB30Cmp.Data()); Log() << kINFO << row << Endl; @@ -2009,27 +2009,27 @@ void TMVA::Factory::EvaluateAllMethods(void) // TODO: Ensure matrices are same size. - TString header = Form(" %-14s", " "); - TString headerInfo = Form(" %-14s", " "); - ; + TString header = TString::Format(" %-14s", " "); + TString headerInfo = TString::Format(" %-14s", " "); + for (UInt_t iCol = 0; iCol < numClasses; ++iCol) { - header += Form(" %-14s", classnames[iCol].Data()); - headerInfo += Form(" %-14s", " test (train)"); + header += TString::Format(" %-14s", classnames[iCol].Data()); + headerInfo += TString::Format(" %-14s", " test (train)"); } stream << kINFO << header << Endl; stream << kINFO << headerInfo << Endl; for (UInt_t iRow = 0; iRow < numClasses; ++iRow) { - stream << kINFO << Form(" %-14s", classnames[iRow].Data()); + stream << kINFO << TString::Format(" %-14s", classnames[iRow].Data()); for (UInt_t iCol = 0; iCol < numClasses; ++iCol) { if (iCol == iRow) { - stream << kINFO << Form(" %-14s", "-"); + stream << kINFO << TString::Format(" %-14s", "-"); } else { Double_t trainValue = matTraining[iRow][iCol]; Double_t testValue = matTesting[iRow][iCol]; - TString entry = Form("%-5.3f (%-5.3f)", testValue, trainValue); - stream << kINFO << Form(" %-14s", entry.Data()); + TString entry = TString::Format("%-5.3f (%-5.3f)", testValue, trainValue); + stream << kINFO << TString::Format(" %-14s", entry.Data()); } } stream << kINFO << Endl; @@ -2628,7 +2628,7 @@ TH1F *TMVA::Factory::GetImportance(const int nbits, std::vector import vih1->GetYaxis()->SetTitleOffset(1.24); vih1->GetYaxis()->SetRangeUser(-7, 50); - vih1->SetDirectory(0); + vih1->SetDirectory(nullptr); // vih1->Draw("B"); return vih1; diff --git a/tmva/tmva/src/MethodANNBase.cxx b/tmva/tmva/src/MethodANNBase.cxx index 4c6759444fb2d..63070e5025ed7 100644 --- a/tmva/tmva/src/MethodANNBase.cxx +++ b/tmva/tmva/src/MethodANNBase.cxx @@ -962,8 +962,8 @@ void TMVA::MethodANNBase::CreateWeightMonitoringHists( const TString& bulkname, Int_t numNeurons1 = layer1->GetEntriesFast(); Int_t numNeurons2 = layer2->GetEntriesFast(); - TString name = Form("%s%i%i", bulkname.Data(), i, i+1); - hist = new TH2F(name + "", name + "", + TString name = TString::Format("%s%i%i", bulkname.Data(), i, i+1); + hist = new TH2F(name.Data(), name.Data(), numNeurons1, 0, numNeurons1, numNeurons2, 0, numNeurons2); for (Int_t j = 0; j < numNeurons1; j++) { @@ -992,7 +992,7 @@ void TMVA::MethodANNBase::CreateWeightMonitoringHists( const TString& bulkname, void TMVA::MethodANNBase::WriteMonitoringHistosToFile() const { - PrintMessage(Form("Write special histos to file: %s", BaseDir()->GetPath()), kTRUE); + PrintMessage(TString::Format("Write special histos to file: %s", BaseDir()->GetPath()).Data(), kTRUE); if (fEstimatorHistTrain) fEstimatorHistTrain->Write(); if (fEstimatorHistTest ) fEstimatorHistTest ->Write(); @@ -1003,11 +1003,11 @@ void TMVA::MethodANNBase::WriteMonitoringHistosToFile() const // now save all the epoch-wise monitoring information static std::atomic epochMonitoringDirectoryNumber{0}; int epochVal = epochMonitoringDirectoryNumber++; - TDirectory* epochdir = NULL; + TDirectory* epochdir = nullptr; if( epochVal == 0 ) epochdir = BaseDir()->mkdir( "EpochMonitoring" ); else - epochdir = BaseDir()->mkdir( Form("EpochMonitoring_%4d",epochVal) ); + epochdir = BaseDir()->mkdir( TString::Format("EpochMonitoring_%4d",epochVal).Data() ); epochdir->cd(); for (std::vector::const_iterator it = fEpochMonHistS.begin(); it != fEpochMonHistS.end(); ++it) { diff --git a/tmva/tmva/src/MethodBDT.cxx b/tmva/tmva/src/MethodBDT.cxx index 2bbb90d83504f..2cb084cc1e5a4 100644 --- a/tmva/tmva/src/MethodBDT.cxx +++ b/tmva/tmva/src/MethodBDT.cxx @@ -522,7 +522,7 @@ void TMVA::MethodBDT::ProcessOptions() << Endl; Log() << kWARNING << "Note also that explicitly setting *nEventsMin* so far OVERWRITES the option recommended \n" << " *MinNodeSize* = " << fMinNodeSizeS << " option !!" << Endl ; - fMinNodeSizeS = Form("%F3.2",fMinNodeSize); + fMinNodeSizeS = TString::Format("%F3.2",fMinNodeSize); }else{ SetMinNodeSize(fMinNodeSizeS); @@ -1199,10 +1199,9 @@ void TMVA::MethodBDT::Train() // book monitoring histograms (for AdaBost only) - TH1* h = new TH1F(Form("%s_BoostWeight",DataInfo().GetName()),hname,nBins,xMin,xMax); - TH1* nodesBeforePruningVsTree = new TH1I(Form("%s_NodesBeforePruning",DataInfo().GetName()),"nodes before pruning",fNTrees,0,fNTrees); - TH1* nodesAfterPruningVsTree = new TH1I(Form("%s_NodesAfterPruning",DataInfo().GetName()),"nodes after pruning",fNTrees,0,fNTrees); - + TH1* h = new TH1F(TString::Format("%s_BoostWeight",DataInfo().GetName()).Data(),hname,nBins,xMin,xMax); + TH1* nodesBeforePruningVsTree = new TH1I(TString::Format("%s_NodesBeforePruning",DataInfo().GetName()).Data(),"nodes before pruning",fNTrees,0,fNTrees); + TH1* nodesAfterPruningVsTree = new TH1I(TString::Format("%s_NodesAfterPruning",DataInfo().GetName()).Data(),"nodes after pruning",fNTrees,0,fNTrees); if(!DoMulticlass()){ @@ -1273,10 +1272,10 @@ void TMVA::MethodBDT::Train() fIPyCurrentIter = itree; timer.DrawProgressBar( itree ); // Results* results = Data()->GetResults(GetMethodName(), Types::kTraining, GetAnalysisType()); - // TH1 *hxx = new TH1F(Form("swdist%d",itree),Form("swdist%d",itree),10000,0,15); - // results->Store(hxx,Form("swdist%d",itree)); - // TH1 *hxy = new TH1F(Form("bwdist%d",itree),Form("bwdist%d",itree),10000,0,15); - // results->Store(hxy,Form("bwdist%d",itree)); + // TH1 *hxx = new TH1F(TString::Format("swdist%d",itree),TString::Format("swdist%d",itree),10000,0,15); + // results->Store(hxx,TString::Format("swdist%d",itree)); + // TH1 *hxy = new TH1F(TString::Format("bwdist%d",itree),TString::Format("bwdist%d",itree),10000,0,15); + // results->Store(hxy,TString::Format("bwdist%d",itree)); // for (Int_t iev=0; ievGetClass()!=0) hxy->Fill((fEventSample[iev])->GetWeight()); // else hxx->Fill((fEventSample[iev])->GetWeight()); @@ -1781,8 +1780,8 @@ void TMVA::MethodBDT::BoostMonitor(Int_t iTree) std::vector hS; std::vector hB; for (UInt_t ivar=0; ivarStore(hS.back(),hS.back()->GetTitle()); results->Store(hB.back(),hB.back()->GetTitle()); } @@ -1791,8 +1790,8 @@ void TMVA::MethodBDT::BoostMonitor(Int_t iTree) for (UInt_t iev=0; iev < fEventSample.size(); iev++){ if (fEventSample[iev]->GetBoostWeight() > max) max = 1.01*fEventSample[iev]->GetBoostWeight(); } - TH1F *tmpBoostWeightsS = new TH1F(Form("BoostWeightsInTreeS%d",iTree),Form("BoostWeightsInTreeS%d",iTree),100,0.,max); - TH1F *tmpBoostWeightsB = new TH1F(Form("BoostWeightsInTreeB%d",iTree),Form("BoostWeightsInTreeB%d",iTree),100,0.,max); + TH1F *tmpBoostWeightsS = new TH1F(TString::Format("BoostWeightsInTreeS%d",iTree).Data(),TString::Format("BoostWeightsInTreeS%d",iTree).Data(),100,0.,max); + TH1F *tmpBoostWeightsB = new TH1F(TString::Format("BoostWeightsInTreeB%d",iTree).Data(),TString::Format("BoostWeightsInTreeB%d",iTree).Data(),100,0.,max); results->Store(tmpBoostWeightsS,tmpBoostWeightsS->GetTitle()); results->Store(tmpBoostWeightsB,tmpBoostWeightsB->GetTitle()); @@ -2313,14 +2312,14 @@ void TMVA::MethodBDT::AddWeightsXMLTo( void* parent ) const if (fDoPreselection){ for (UInt_t ivar=0; ivarclear(); delete fInputVars; } @@ -385,14 +385,14 @@ TMVA::MethodBase::~MethodBase( void ) if (fSplTrainRefB) { delete fSplTrainRefB; fSplTrainRefB = 0; } if (fSplTrainEffBvsS) { delete fSplTrainEffBvsS; fSplTrainEffBvsS = 0; } - for (Int_t i = 0; i < 2; i++ ) { + for (size_t i = 0; i < fEventCollections.size(); i++ ) { if (fEventCollections.at(i)) { for (std::vector::const_iterator it = fEventCollections.at(i)->begin(); it != fEventCollections.at(i)->end(); ++it) { delete (*it); } delete fEventCollections.at(i); - fEventCollections.at(i) = 0; + fEventCollections.at(i) = nullptr; } } @@ -809,11 +809,12 @@ void TMVA::MethodBase::AddMulticlassOutput(Types::ETreeType type) << (type==Types::kTraining?"training":"testing") << " sample" << Endl; resMulticlass->Resize( nEvents ); + Int_t modulo = Int_t(nEvents/100) + 1; for (Int_t ievt=0; ievtSetCurrentEvent(ievt); std::vector< Float_t > vals = GetMulticlassValues(); resMulticlass->SetValue( vals, ievt ); - timer.DrawProgressBar( ievt ); + if (ievt%modulo == 0) timer.DrawProgressBar( ievt ); } Log() << kINFO <Resize( nEvents ); + Int_t modulo = Int_t(nEvents/100); + if (modulo <= 0 ) modulo = 1; for (Int_t ievt=0; ievtSetCurrentEvent(ievt); @@ -971,8 +974,6 @@ void TMVA::MethodBase::AddClassifierOutputProb( Types::ETreeType type ) mvaProb->SetValue( proba, ievt, DataInfo().IsSignal( Data()->GetEvent()) ); // print progress - Int_t modulo = Int_t(nEvents/100); - if (modulo <= 0 ) modulo = 1; if (ievt%modulo == 0) timer.DrawProgressBar( ievt ); } @@ -1008,6 +1009,7 @@ void TMVA::MethodBase::TestRegression( Double_t& bias, Double_t& biasT, Float_t xmin = 1e30, xmax = -1e30; Log() << kINFO << "Calculate regression for all events" << Endl; Timer timer( nevt, GetName(), kTRUE ); + Long64_t modulo = Long64_t(nevt / 100) + 1; for (Long64_t ievt=0; ievtGetEvent(ievt); // NOTE: need untransformed event here ! @@ -1036,7 +1038,6 @@ void TMVA::MethodBase::TestRegression( Double_t& bias, Double_t& biasT, m2 += r*w; s2 += r*r*w; s12 += t*r; // print progress - Long64_t modulo = Long64_t(nevt / 100); if (ievt % modulo == 0) timer.DrawProgressBar(ievt); } @@ -1158,13 +1159,11 @@ void TMVA::MethodBase::TestClassification() // classifier response distributions for training sample // MVA plots used for graphics representation (signal) TString TestvarName; - if(IsSilentFile()) - { - TestvarName=Form("[%s]%s",DataInfo().GetName(),GetTestvarName().Data()); - }else - { - TestvarName=GetTestvarName(); - } + if(IsSilentFile()) { + TestvarName = TString::Format("[%s]%s",DataInfo().GetName(),GetTestvarName().Data()); + } else { + TestvarName=GetTestvarName(); + } TH1* mva_s = new TH1D( TestvarName + "_S",TestvarName + "_S", fNbinsMVAoutput, fXmin, sxmax ); TH1* mva_b = new TH1D( TestvarName + "_B",TestvarName + "_B", fNbinsMVAoutput, fXmin, sxmax ); mvaRes->Store(mva_s, "MVA_S"); @@ -1926,7 +1925,7 @@ void TMVA::MethodBase::ReadClassesFromXML( void* clsnode ) void* ch = gTools().GetChild(clsnode); if (!ch) { for (UInt_t icls = 0; iclsGetDirectory(datasetName); if (!fMethodBaseDir) { - fMethodBaseDir = factoryBaseDir->mkdir(datasetName, Form("Base directory for dataset %s", datasetName)); + fMethodBaseDir = factoryBaseDir->mkdir(datasetName, TString::Format("Base directory for dataset %s", datasetName).Data()); if (!fMethodBaseDir) { Log() << kFATAL << "Can not create dir " << datasetName; } } - TString methodTypeDir = Form("Method_%s", GetMethodTypeName().Data()); + TString methodTypeDir = TString::Format("Method_%s", GetMethodTypeName().Data()); fMethodBaseDir = fMethodBaseDir->GetDirectory(methodTypeDir.Data()); if (!fMethodBaseDir) { TDirectory *datasetDir = factoryBaseDir->GetDirectory(datasetName); - TString methodTypeDirHelpStr = Form("Directory for all %s methods", GetMethodTypeName().Data()); + TString methodTypeDirHelpStr = TString::Format("Directory for all %s methods", GetMethodTypeName().Data()); fMethodBaseDir = datasetDir->mkdir(methodTypeDir.Data(), methodTypeDirHelpStr); Log() << kDEBUG << Form("Dataset[%s] : ", datasetName) << " Base Directory for " << GetMethodName() << " does not exist yet--> created it" << Endl; @@ -2236,7 +2235,7 @@ void TMVA::MethodBase::CreateMVAPdfs() if (DataInfo().GetNClasses() == 2) { // TODO: this is an ugly hack.. adapt this to new framework Log() << kINFO< Separation from histogram (PDF): %1.3f (%1.3f)", + << TString::Format( " Separation from histogram (PDF): %1.3f (%1.3f)", GetSeparation( histMVAPdfS, histMVAPdfB ), GetSeparation( fMVAPdfS, fMVAPdfB ) ) << Endl; } @@ -3373,7 +3372,7 @@ TString TMVA::MethodBase::GetTrainingTMVAVersionString() const UInt_t b = GetTrainingTMVAVersionCode() & 0x00ff00; b>>=8; UInt_t c = GetTrainingTMVAVersionCode() & 0x0000ff; - return TString(Form("%i.%i.%i",a,b,c)); + return TString::Format("%i.%i.%i",a,b,c); } //////////////////////////////////////////////////////////////////////////////// @@ -3385,7 +3384,7 @@ TString TMVA::MethodBase::GetTrainingROOTVersionString() const UInt_t b = GetTrainingROOTVersionCode() & 0x00ff00; b>>=8; UInt_t c = GetTrainingROOTVersionCode() & 0x0000ff; - return TString(Form("%i.%02i/%02i",a,b,c)); + return TString::Format("%i.%02i/%02i",a,b,c); } //////////////////////////////////////////////////////////////////////////////// diff --git a/tmva/tmva/src/MethodBoost.cxx b/tmva/tmva/src/MethodBoost.cxx index 328c9af8d2db4..ce9460d46e1df 100644 --- a/tmva/tmva/src/MethodBoost.cxx +++ b/tmva/tmva/src/MethodBoost.cxx @@ -350,7 +350,7 @@ void TMVA::MethodBoost::CheckSetup() void TMVA::MethodBoost::Train() { - TDirectory* methodDir( 0 ); + TDirectory* methodDir = nullptr; TString dirName,dirTitle; Int_t StopCounter=0; Results* results = Data()->GetResults(GetMethodName(), Types::kTraining, GetAnalysisType()); @@ -390,7 +390,7 @@ void TMVA::MethodBoost::Train() if (fCurrentMethodIdx>0) TMVA::MsgLogger::InhibitOutput(); IMethod *method = ClassifierFactory::Instance().Create( - fBoostedMethodName.Data(), GetJobName(), Form("%s_B%04i", fBoostedMethodTitle.Data(), fCurrentMethodIdx), + fBoostedMethodName.Data(), GetJobName(), TString::Format("%s_B%04i", fBoostedMethodTitle.Data(), fCurrentMethodIdx), DataInfo(), fBoostedMethodOptions); TMVA::MsgLogger::EnableOutput(); @@ -427,9 +427,9 @@ void TMVA::MethodBoost::Train() if(!IsSilentFile()) { if (fMonitorBoostedMethod) { - methodDir=GetFile()->GetDirectory(dirName=Form("%s_B%04i",fBoostedMethodName.Data(),fCurrentMethodIdx)); - if (methodDir==0) { - methodDir=BaseDir()->mkdir(dirName,dirTitle=Form("Directory Boosted %s #%04i", fBoostedMethodName.Data(),fCurrentMethodIdx)); + methodDir = GetFile()->GetDirectory(dirName=TString::Format("%s_B%04i",fBoostedMethodName.Data(),fCurrentMethodIdx)); + if (!methodDir) { + methodDir = BaseDir()->mkdir(dirName,dirTitle=TString::Format("Directory Boosted %s #%04i", fBoostedMethodName.Data(),fCurrentMethodIdx)); } fCurrentMethod->SetMethodDir(methodDir); fCurrentMethod->BaseDir()->cd(); @@ -554,12 +554,12 @@ void TMVA::MethodBoost::CreateMVAHistorgrams() // creating all the histograms for (UInt_t imtd=0; imtdGetResults(GetMethodName(), Types::kTraining, GetAnalysisType()); if (fDetailedMonitoring){ - results->Store(mvaS, Form("MVAS_%d",fCurrentMethodIdx)); - results->Store(mvaB, Form("MVAB_%d",fCurrentMethodIdx)); - results->Store(mvaSC,Form("MVASC_%d",fCurrentMethodIdx)); - results->Store(mvaBC,Form("MVABC_%d",fCurrentMethodIdx)); + results->Store(mvaS, TString::Format("MVAS_%d",fCurrentMethodIdx)); + results->Store(mvaB, TString::Format("MVAB_%d",fCurrentMethodIdx)); + results->Store(mvaSC,TString::Format("MVASC_%d",fCurrentMethodIdx)); + results->Store(mvaBC,TString::Format("MVABC_%d",fCurrentMethodIdx)); } for (Long64_t ievt=0; ievtGetNEvents(); ievt++) { @@ -1350,10 +1350,10 @@ void TMVA::MethodBoost::MonitorBoost( Types::EBoostStage stage , UInt_t methodIn if (fDetailedMonitoring){ // the following code is useful only for 2D examples - mainly illustration for debug/educational purposes: if (DataInfo().GetNVariables() == 2) { - results->Store(new TH2F(Form("EventDistSig_%d",methodIndex),Form("EventDistSig_%d",methodIndex),100,0,7,100,0,7)); - results->GetHist(Form("EventDistSig_%d",methodIndex))->SetMarkerColor(4); - results->Store(new TH2F(Form("EventDistBkg_%d",methodIndex),Form("EventDistBkg_%d",methodIndex),100,0,7,100,0,7)); - results->GetHist(Form("EventDistBkg_%d",methodIndex))->SetMarkerColor(2); + results->Store(new TH2F(TString::Format("EventDistSig_%d",methodIndex),TString::Format("EventDistSig_%d",methodIndex),100,0,7,100,0,7)); + results->GetHist(TString::Format("EventDistSig_%d",methodIndex))->SetMarkerColor(4); + results->Store(new TH2F(TString::Format("EventDistBkg_%d",methodIndex),TString::Format("EventDistBkg_%d",methodIndex),100,0,7,100,0,7)); + results->GetHist(TString::Format("EventDistBkg_%d",methodIndex))->SetMarkerColor(2); Data()->SetCurrentType(Types::kTraining); for (Long64_t ievt=0; ievtGetValue(1); // if (ievt<3) std::cout<GetHist2D(Form("EventDistBkg_%d",methodIndex)); + if (DataInfo().IsSignal(ev)) h = results->GetHist2D(TString::Format("EventDistSig_%d",methodIndex)); + else h = results->GetHist2D(TString::Format("EventDistBkg_%d",methodIndex)); if (h) h->Fill(v0,v1,w); } } diff --git a/tmva/tmva/src/MethodCategory.cxx b/tmva/tmva/src/MethodCategory.cxx index e868f49b86806..454cfcdc8acb4 100644 --- a/tmva/tmva/src/MethodCategory.cxx +++ b/tmva/tmva/src/MethodCategory.cxx @@ -163,10 +163,10 @@ TMVA::IMethod* TMVA::MethodCategory::AddMethod( const TCut& theCut, // set or create correct method base dir for added method - const TString dirName(Form("Method_%s",method->GetMethodTypeName().Data())); + const TString dirName = TString::Format("Method_%s",method->GetMethodTypeName().Data()); TDirectory * dir = BaseDir()->GetDirectory(dirName); if (dir != 0) method->SetMethodBaseDir( dir ); - else method->SetMethodBaseDir( BaseDir()->mkdir(dirName,Form("Directory for all %s methods", method->GetMethodTypeName().Data())) ); + else method->SetMethodBaseDir( BaseDir()->mkdir(dirName, TString::Format("Directory for all %s methods", method->GetMethodTypeName().Data())) ); // method->SetBaseDir(eigenes base dir, gucken ob Fisher dir existiert, sonst erzeugen ) @@ -187,8 +187,8 @@ TMVA::IMethod* TMVA::MethodCategory::AddMethod( const TCut& theCut, UInt_t newSpectatorIndex = primaryDSI.GetSpectatorInfos().size(); fCategorySpecIdx.push_back(newSpectatorIndex); - primaryDSI.AddSpectator( Form("%s_cat%i:=%s", GetName(),(int)fMethods.size(),theCut.GetTitle()), - Form("%s:%s",GetName(),method->GetName()), + primaryDSI.AddSpectator( TString::Format("%s_cat%i:=%s", GetName(),(int)fMethods.size(),theCut.GetTitle()).Data(), + TString::Format("%s:%s",GetName(),method->GetName()).Data(), "pass", 0, 0, 'C' ); return method; @@ -342,7 +342,7 @@ void TMVA::MethodCategory::InitCircularTree(const DataSetInfo& dsi) // The add-then-remove can lead to a problem if gDirectory points to the same directory (for example // gROOT) in the current thread and another one (and both try to add to the directory at the same time). TDirectory::TContext ctxt(nullptr); - fCatTree = new TTree(Form("Circ%s",GetMethodName().Data()),"Circular Tree for categorization"); + fCatTree = new TTree(TString::Format("Circ%s",GetMethodName().Data()).Data(),"Circular Tree for categorization"); fCatTree->SetCircular(1); } @@ -357,7 +357,7 @@ void TMVA::MethodCategory::InitCircularTree(const DataSetInfo& dsi) } for(UInt_t cat=0; cat!=fCategoryCuts.size(); ++cat) { - fCatFormulas.push_back(new TTreeFormula(Form("Category_%i",cat), fCategoryCuts[cat].GetTitle(), fCatTree)); + fCatFormulas.push_back(new TTreeFormula(TString::Format("Category_%i",cat).Data(), fCategoryCuts[cat].GetTitle(), fCatTree)); } } @@ -514,7 +514,7 @@ void TMVA::MethodCategory::ReadWeightsFromXML( void* wghtnode ) // find the spectator index std::vector& spectators=primaryDSI.GetSpectatorInfos(); std::vector::iterator itrVarInfo; - TString specName= Form("%s_cat%i", GetName(),(int)fCategorySpecIdx.size()+1); + TString specName= TString::Format("%s_cat%i", GetName(),(int)fCategorySpecIdx.size()+1); for (itrVarInfo = spectators.begin(); itrVarInfo != spectators.end(); ++itrVarInfo, ++counter) { if((specName==itrVarInfo->GetLabel()) || (specName==itrVarInfo->GetExpression())) { diff --git a/tmva/tmva/src/MethodCompositeBase.cxx b/tmva/tmva/src/MethodCompositeBase.cxx index 107228bdb7b55..4edd3beb54f78 100644 --- a/tmva/tmva/src/MethodCompositeBase.cxx +++ b/tmva/tmva/src/MethodCompositeBase.cxx @@ -228,8 +228,8 @@ void TMVA::MethodCompositeBase::ReadWeightsFromXML( void* wghtnode ) void TMVA::MethodCompositeBase::ReadWeightsFromStream( std::istream& istr ) { TString var, dummy; - TString methodName, methodTitle=GetMethodName(), - jobName=GetJobName(),optionString=GetOptions(); + TString methodName, methodTitle = GetMethodName(), + jobName=GetJobName(),optionString = GetOptions(); UInt_t methodNum; Double_t methodWeight; // and read the Weights (BDT coefficients) // coverity[tainted_data_argument] @@ -254,8 +254,9 @@ void TMVA::MethodCompositeBase::ReadWeightsFromStream( std::istream& istr ) istr >> dummy >> optionString; if (GetMethodType() == Types::kBoost) ((TMVA::MethodBoost*)this)->BookMethod( Types::Instance().GetMethodType( methodName), methodTitle, optionString ); + } else { + methodTitle = TString::Format("%s (%04i)",GetMethodName().Data(),fCurrentMethodIdx); } - else methodTitle=Form("%s (%04i)",GetMethodName().Data(),fCurrentMethodIdx); fMethods.push_back( ClassifierFactory::Instance().Create(methodName.Data(), jobName, methodTitle, DataInfo(), optionString)); fMethodWeight.push_back( methodWeight ); diff --git a/tmva/tmva/src/MethodCrossValidation.cxx b/tmva/tmva/src/MethodCrossValidation.cxx index d78cebef258a6..c29179a05613b 100644 --- a/tmva/tmva/src/MethodCrossValidation.cxx +++ b/tmva/tmva/src/MethodCrossValidation.cxx @@ -118,7 +118,7 @@ TString TMVA::MethodCrossValidation::GetWeightFileNameForFold(UInt_t iFold) cons << "Should be < " << fNumFolds << "." << Endl; } - TString foldStr = Form("fold%i", iFold + 1); + TString foldStr = TString::Format("fold%i", iFold + 1); TString fileDir = gSystem->GetDirName(GetWeightFileName()); TString weightfile = fileDir + "/" + fJobName + "_" + fEncapsulatedMethodName + "_" + foldStr + ".weights.xml"; diff --git a/tmva/tmva/src/MethodCuts.cxx b/tmva/tmva/src/MethodCuts.cxx index 12135b8f749a1..c96da693955e2 100644 --- a/tmva/tmva/src/MethodCuts.cxx +++ b/tmva/tmva/src/MethodCuts.cxx @@ -623,7 +623,7 @@ void TMVA::MethodCuts::Train( void ) delete fEffBvsSLocal; fEffBvsSLocal = new TH1F( GetTestvarName() + "_effBvsSLocal", TString(GetName()) + " efficiency of B vs S", fNbins, 0.0, 1.0 ); - fEffBvsSLocal->SetDirectory(0); // it's local + fEffBvsSLocal->SetDirectory(nullptr); // it's local // init for (Int_t ibin=1; ibin<=fNbins; ibin++) fEffBvsSLocal->SetBinContent( ibin, -0.1 ); @@ -669,16 +669,16 @@ void TMVA::MethodCuts::Train( void ) switch (fFitMethod) { case kUseGeneticAlgorithm: - fitter = new GeneticFitter( *this, Form("%sFitter_GA", GetName()), ranges, GetOptions() ); + fitter = new GeneticFitter( *this, TString::Format("%sFitter_GA", GetName()), ranges, GetOptions() ); break; case kUseMonteCarlo: - fitter = new MCFitter ( *this, Form("%sFitter_MC", GetName()), ranges, GetOptions() ); + fitter = new MCFitter ( *this, TString::Format("%sFitter_MC", GetName()), ranges, GetOptions() ); break; case kUseMinuit: - fitter = new MinuitFitter ( *this, Form("%sFitter_MINUIT", GetName()), ranges, GetOptions() ); + fitter = new MinuitFitter ( *this, TString::Format("%sFitter_MINUIT", GetName()), ranges, GetOptions() ); break; case kUseSimulatedAnnealing: - fitter = new SimulatedAnnealingFitter( *this, Form("%sFitter_SA", GetName()), ranges, GetOptions() ); + fitter = new SimulatedAnnealingFitter( *this, TString::Format("%sFitter_SA", GetName()), ranges, GetOptions() ); break; default: Log() << kFATAL << "Wrong fit method: " << fFitMethod << Endl; @@ -1265,7 +1265,7 @@ void TMVA::MethodCuts::ReadWeightsFromStream( std::istream& istr ) if (fEffBvsSLocal != 0) delete fEffBvsSLocal; fEffBvsSLocal = new TH1F( GetTestvarName() + "_effBvsSLocal", TString(GetName()) + " efficiency of B vs S", fNbins, 0.0, 1.0 ); - fEffBvsSLocal->SetDirectory(0); // it's local + fEffBvsSLocal->SetDirectory(nullptr); // it's local for (Int_t ibin=0; ibin> tmpbin >> tmpeffS >> tmpeffB; @@ -1294,7 +1294,7 @@ void TMVA::MethodCuts::AddWeightsXMLTo( void* parent ) const gTools().AddAttr( wght, "OptimisationMethod", (Int_t)fEffMethod); gTools().AddAttr( wght, "FitMethod", (Int_t)fFitMethod ); gTools().AddAttr( wght, "nbins", fNbins ); - gTools().AddComment( wght, Form( "Below are the optimised cuts for %i variables: Format: ibin(hist) effS effB cutMin[ivar=0] cutMax[ivar=0] ... cutMin[ivar=n-1] cutMax[ivar=n-1]", GetNvar() ) ); + gTools().AddComment( wght, TString::Format( "Below are the optimised cuts for %i variables: Format: ibin(hist) effS effB cutMin[ivar=0] cutMax[ivar=0] ... cutMin[ivar=n-1] cutMax[ivar=n-1]", GetNvar() ) ); // NOTE: The signal efficiency written out into // the weight file does not correspond to the center of the bin within which the @@ -1315,8 +1315,8 @@ void TMVA::MethodCuts::AddWeightsXMLTo( void* parent ) const gTools().AddAttr( binxml, "effB", fEffBvsSLocal->GetBinContent( ibin + 1 ) ); void* cutsxml = gTools().AddChild( binxml, "Cuts" ); for (UInt_t ivar=0; ivarSetDirectory(0); // it's local + fEffBvsSLocal->SetDirectory(nullptr); // it's local for (Int_t ibin=1; ibin<=fNbins; ibin++) fEffBvsSLocal->SetBinContent( ibin, -0.1 ); // Init fCutMin = new Double_t*[GetNvar()]; @@ -1398,8 +1398,8 @@ void TMVA::MethodCuts::ReadWeightsFromXML( void* wghtnode ) fEffBvsSLocal->SetBinContent( tmpbin, tmpeffB ); void* ct = gTools().GetChild(ch); for (UInt_t ivar=0; ivar Formula contains expression: \"" << Form("(%i)",ipar) << "\", " + << " Formula contains expression: \"" << TString::Format("(%i)",ipar) << "\", " << "which cannot be attributed to a parameter; " << "it may be that the number of variable ranges given via \"ParRanges\" " << "does not match the number of parameters in the formula expression, please verify!" @@ -205,14 +205,14 @@ void TMVA::MethodFDA::CreateFormula() // write the variables "xi" as additional parameters "[npar+i]" for (Int_t ivar=GetNvar()-1; ivar >= 0; ivar--) { - fFormulaStringT.ReplaceAll( Form("x%i",ivar), Form("[%i]",ivar+fNPars) ); + fFormulaStringT.ReplaceAll( TString::Format("x%i",ivar), TString::Format("[%i]",ivar+fNPars) ); } // sanity check, there should be no "xi", with 'i' a number anymore for (UInt_t ivar=GetNvar(); ivar<1000; ivar++) { - if (fFormulaStringT.Contains( Form("x%i",ivar) )) + if (fFormulaStringT.Contains( TString::Format("x%i",ivar) )) Log() << kFATAL - << " Formula contains expression: \"" << Form("x%i",ivar) << "\", " + << " Formula contains expression: \"" << TString::Format("x%i",ivar) << "\", " << "which cannot be attributed to an input variable" << Endl; } @@ -301,18 +301,18 @@ void TMVA::MethodFDA::ProcessOptions() // create minimiser fConvergerFitter = (IFitterTarget*)this; if (fConverger == "MINUIT") { - fConvergerFitter = new MinuitFitter( *this, Form("%s_Converger_Minuit", GetName()), fParRange, GetOptions() ); + fConvergerFitter = new MinuitFitter( *this, TString::Format("%s_Converger_Minuit", GetName()), fParRange, GetOptions() ); SetOptions(dynamic_cast(fConvergerFitter)->GetOptions()); } if(fFitMethod == "MC") - fFitter = new MCFitter( *fConvergerFitter, Form("%s_Fitter_MC", GetName()), fParRange, GetOptions() ); + fFitter = new MCFitter( *fConvergerFitter, TString::Format("%s_Fitter_MC", GetName()), fParRange, GetOptions() ); else if (fFitMethod == "GA") - fFitter = new GeneticFitter( *fConvergerFitter, Form("%s_Fitter_GA", GetName()), fParRange, GetOptions() ); + fFitter = new GeneticFitter( *fConvergerFitter, TString::Format("%s_Fitter_GA", GetName()), fParRange, GetOptions() ); else if (fFitMethod == "SA") - fFitter = new SimulatedAnnealingFitter( *fConvergerFitter, Form("%s_Fitter_SA", GetName()), fParRange, GetOptions() ); + fFitter = new SimulatedAnnealingFitter( *fConvergerFitter, TString::Format("%s_Fitter_SA", GetName()), fParRange, GetOptions() ); else if (fFitMethod == "MINUIT") - fFitter = new MinuitFitter( *fConvergerFitter, Form("%s_Fitter_Minuit", GetName()), fParRange, GetOptions() ); + fFitter = new MinuitFitter( *fConvergerFitter, TString::Format("%s_Fitter_Minuit", GetName()), fParRange, GetOptions() ); else { Log() << kFATAL << " Do not understand fit method:" << fFitMethod << Endl; } @@ -423,7 +423,7 @@ void TMVA::MethodFDA::PrintResults( const TString& fitter, std::vector Log() << kINFO; Log() << kHEADER << "Results for parameter fit using \"" << fitter << "\" fitter:" << Endl; std::vector parNames; - for (UInt_t ipar=0; iparSetDirectory(0); + tree->SetDirectory(nullptr); tree->Branch("event", "TMVA::kNN::Event", &event); Double_t size = 0.0; diff --git a/tmva/tmva/src/MethodLikelihood.cxx b/tmva/tmva/src/MethodLikelihood.cxx index 54d9b354ffced..c0e9b1fe37270 100644 --- a/tmva/tmva/src/MethodLikelihood.cxx +++ b/tmva/tmva/src/MethodLikelihood.cxx @@ -254,13 +254,13 @@ void TMVA::MethodLikelihood::DeclareOptions() fDefaultPDFLik->ParseOptions(); updatedOptions = fDefaultPDFLik->GetOptions(); for (UInt_t ivar = 0; ivar< DataInfo().GetNVariables(); ivar++) { - (*fPDFSig)[ivar] = new PDF( Form("%s PDF Sig[%d]", GetName(), ivar), updatedOptions, - Form("Sig[%d]",ivar), fDefaultPDFLik ); + (*fPDFSig)[ivar] = new PDF( TString::Format("%s PDF Sig[%d]", GetName(), ivar), updatedOptions, + TString::Format("Sig[%d]",ivar), fDefaultPDFLik ); (*fPDFSig)[ivar]->DeclareOptions(); (*fPDFSig)[ivar]->ParseOptions(); updatedOptions = (*fPDFSig)[ivar]->GetOptions(); - (*fPDFBgd)[ivar] = new PDF( Form("%s PDF Bkg[%d]", GetName(), ivar), updatedOptions, - Form("Bkg[%d]",ivar), fDefaultPDFLik ); + (*fPDFBgd)[ivar] = new PDF( TString::Format("%s PDF Bkg[%d]", GetName(), ivar), updatedOptions, + TString::Format("Bkg[%d]",ivar), fDefaultPDFLik ); (*fPDFBgd)[ivar]->DeclareOptions(); (*fPDFBgd)[ivar]->ParseOptions(); updatedOptions = (*fPDFBgd)[ivar]->GetOptions(); @@ -380,10 +380,12 @@ void TMVA::MethodLikelihood::Train( void ) Int_t nbinsS = (*fPDFSig)[ivar]->GetHistNBins( minNEvt ); Int_t nbinsB = (*fPDFBgd)[ivar]->GetHistNBins( minNEvt ); - (*fHistSig)[ivar] = new TH1F( Form("%s_%s_%s_sig",DataInfo().GetName(),GetMethodName().Data(),var.Data()), - Form("%s_%s_%s signal training",DataInfo().GetName(),GetMethodName().Data(),var.Data()), nbinsS, xmin[ivar], xmax[ivar] ); - (*fHistBgd)[ivar] = new TH1F( Form("%s_%s_%s_bgd",DataInfo().GetName(),GetMethodName().Data(),var.Data()), - Form("%s_%s_%s background training",DataInfo().GetName(),GetMethodName().Data(),var.Data()), nbinsB, xmin[ivar], xmax[ivar] ); + (*fHistSig)[ivar] = new TH1F( TString::Format("%s_%s_%s_sig",DataInfo().GetName(),GetMethodName().Data(),var.Data()), + TString::Format("%s_%s_%s signal training",DataInfo().GetName(),GetMethodName().Data(),var.Data()), + nbinsS, xmin[ivar], xmax[ivar] ); + (*fHistBgd)[ivar] = new TH1F( TString::Format("%s_%s_%s_bgd",DataInfo().GetName(),GetMethodName().Data(),var.Data()), + TString::Format("%s_%s_%s background training",DataInfo().GetName(),GetMethodName().Data(),var.Data()), + nbinsB, xmin[ivar], xmax[ivar] ); } } @@ -565,7 +567,7 @@ void TMVA::MethodLikelihood::WriteOptionsToStream( std::ostream& o, const TStrin } for (UInt_t ivar = 0; ivar < fPDFSig->size(); ivar++) { if ((*fPDFSig)[ivar] != 0) { - o << prefix << std::endl << prefix << Form("#Signal[%d] Likelihood PDF Options:",ivar) << std::endl << prefix << std::endl; + o << prefix << std::endl << prefix << TString::Format("#Signal[%d] Likelihood PDF Options:",ivar) << std::endl << prefix << std::endl; (*fPDFSig)[ivar]->WriteOptionsToStream( o, prefix ); } if ((*fPDFBgd)[ivar] != 0) { @@ -614,8 +616,8 @@ const TMVA::Ranking* TMVA::MethodLikelihood::CreateRanking() // this variable should not be used fDropVariable = ivar; - TString nameS = Form( "rS_%i", ivar+1 ); - TString nameB = Form( "rB_%i", ivar+1 ); + TString nameS = TString::Format( "rS_%i", ivar+1 ); + TString nameB = TString::Format( "rB_%i", ivar+1 ); TH1* rS = new TH1F( nameS, nameS, 80, 0, 1 ); TH1* rB = new TH1F( nameB, nameB, 80, 0, 1 ); @@ -722,8 +724,8 @@ void TMVA::MethodLikelihood::ReadWeightsFromStream( TFile& rf ) Bool_t addDirStatus = TH1::AddDirectoryStatus(); TH1::AddDirectory(0); // this avoids the binding of the hists in TMVA::PDF to the current ROOT file for (UInt_t ivar=0; ivar= 0 && !DoRegression() && treeType == Types::kTraining) { - CreateWeightMonitoringHists( Form("epochmonitoring___epoch_%04i_weights_hist", iEpoch), &fEpochMonHistW ); + CreateWeightMonitoringHists( TString::Format("epochmonitoring___epoch_%04i_weights_hist", iEpoch), &fEpochMonHistW ); } return estimator; @@ -638,7 +638,7 @@ void TMVA::MethodMLP::BFGSMinimize( Int_t nEpochs ) } // draw progress - TString convText = Form( " (train/test/epoch): %.4g/%.4g/%d", trainE, testE,i ); //zjh + TString convText = TString::Format( " (train/test/epoch): %.4g/%.4g/%d", trainE, testE,i ); //zjh if (fSteps > 0) { Float_t progress = 0; if (Float_t(i)/nEpochs < fSamplingEpoch) @@ -1120,7 +1120,7 @@ void TMVA::MethodMLP::BackPropagationMinimize(Int_t nEpochs) } // draw progress bar (add convergence value) - TString convText = Form( " (train/test): %.4g/%.4g", trainE, testE ); + TString convText = TString::Format( " (train/test): %.4g/%.4g", trainE, testE ); if (fSteps > 0) { Float_t progress = 0; if (Float_t(i)/nEpochs < fSamplingEpoch) @@ -1618,7 +1618,7 @@ void TMVA::MethodMLP::MinuitMinimize() // init parameters for (Int_t ipar=0; ipar < fNumberOfWeights; ipar++) { - TString parName = Form("w%i", ipar); + TString parName = TString::Format("w%i", ipar); tfitter->SetParameter( ipar, parName, w[ipar], 0.1, 0, 0 ); } diff --git a/tmva/tmva/src/MethodPDEFoam.cxx b/tmva/tmva/src/MethodPDEFoam.cxx index e25b888df7e59..b66b9f16b341c 100644 --- a/tmva/tmva/src/MethodPDEFoam.cxx +++ b/tmva/tmva/src/MethodPDEFoam.cxx @@ -369,7 +369,7 @@ void TMVA::MethodPDEFoam::CalcXminXmax() // the range TH1F **range_h = new TH1F*[kDim]; for (UInt_t dim=0; dimGetLinDP(il) << "), std::max( double(inputValues[" << il << "]), double(" << std::setprecision(10) << rens->GetLinDM(il) << ")));" << std::flush; - fout << " // importance = " << Form("%3.3f",imp) << std::endl; + fout << " // importance = " << TString::Format("%3.3f",imp) << std::endl; } } } diff --git a/tmva/tmva/src/MethodTMlpANN.cxx b/tmva/tmva/src/MethodTMlpANN.cxx index 9d86ed6c930b5..c898114c41c81 100644 --- a/tmva/tmva/src/MethodTMlpANN.cxx +++ b/tmva/tmva/src/MethodTMlpANN.cxx @@ -154,7 +154,7 @@ void TMVA::MethodTMlpANN::CreateMLPOptions( TString layerSpec ) int nNodes = 0; if (sToAdd.BeginsWith("N")) { sToAdd.Remove(0,1); nNodes = GetNvar(); } nNodes += atoi(sToAdd); - fHiddenLayer = Form( "%s%i:", (const char*)fHiddenLayer, nNodes ); + fHiddenLayer = TString::Format( "%s%i:", (const char*)fHiddenLayer, nNodes ); } // set input vars @@ -269,8 +269,9 @@ void TMVA::MethodTMlpANN::Train( void ) localTrainingTree->Branch( "weight", &weight, "weight/F", basketsize ); for (UInt_t ivar=0; ivarBranch( myVar, &vArr[ivar], Form("Var%02i/F", ivar), basketsize ); + TString myVar = GetInternalVarName(ivar); + TString myTyp = TString::Format("Var%02i/F", ivar); + localTrainingTree->Branch( myVar.Data(), &vArr[ivar], myTyp.Data(), basketsize ); } for (UInt_t ievt=0; ievtGetNEvents(); ievt++) { @@ -305,7 +306,7 @@ void TMVA::MethodTMlpANN::Train( void ) // localTrainingTree->Print(); // create NN - if (fMLP != 0) { delete fMLP; fMLP = 0; } + if (fMLP) { delete fMLP; fMLP = nullptr; } fMLP = new TMultiLayerPerceptron( fMLPBuildOptions.Data(), localTrainingTree, trainList, @@ -352,12 +353,12 @@ void TMVA::MethodTMlpANN::AddWeightsXMLTo( void* parent ) const std::ifstream inf( tmpfile.Data() ); char temp[256]; TString data(""); - void *ch=NULL; + void *ch = nullptr; while (inf.getline(temp,256)) { TString dummy(temp); //std::cout << dummy << std::endl; // remove annoying debug printout with std::cout if (dummy.BeginsWith('#')) { - if (ch!=0) gTools().AddRawLine( ch, data.Data() ); + if (ch) gTools().AddRawLine( ch, data.Data() ); dummy = dummy.Strip(TString::kLeading, '#'); dummy = dummy(0,dummy.First(' ')); ch = gTools().AddChild(wght, dummy); @@ -366,7 +367,7 @@ void TMVA::MethodTMlpANN::AddWeightsXMLTo( void* parent ) const } data += (dummy + " "); } - if (ch != 0) gTools().AddRawLine( ch, data.Data() ); + if (ch) gTools().AddRawLine( ch, data.Data() ); inf.close(); } @@ -424,11 +425,12 @@ void TMVA::MethodTMlpANN::ReadWeightsFromXML( void* wghtnode ) TTree * dummyTree = new TTree("dummy","Empty dummy tree", 1); for (UInt_t ivar = 0; ivarGetNVariables(); ivar++) { TString vn = DataInfo().GetVariableInfo(ivar).GetInternalName(); - dummyTree->Branch(Form("%s",vn.Data()), d+ivar, Form("%s/D",vn.Data())); + TString vt = TString::Format("%s/D", vn.Data()); + dummyTree->Branch(vn.Data(), d+ivar, vt.Data()); } dummyTree->Branch("type", &type, "type/I"); - if (fMLP != 0) { delete fMLP; fMLP = 0; } + if (fMLP) { delete fMLP; fMLP = nullptr; } fMLP = new TMultiLayerPerceptron( fMLPBuildOptions.Data(), dummyTree ); fMLP->LoadWeights( fname ); } @@ -447,17 +449,18 @@ void TMVA::MethodTMlpANN::ReadWeightsFromStream( std::istream& istr ) // the MLP is already build Log() << kINFO << "Load TMLP weights into " << fMLP << Endl; - Double_t* d = new Double_t[Data()->GetNVariables()] ; + Double_t *d = new Double_t[Data()->GetNVariables()] ; Int_t type; gROOT->cd(); TTree * dummyTree = new TTree("dummy","Empty dummy tree", 1); for (UInt_t ivar = 0; ivarGetNVariables(); ivar++) { TString vn = DataInfo().GetVariableInfo(ivar).GetLabel(); - dummyTree->Branch(Form("%s",vn.Data()), d+ivar, Form("%s/D",vn.Data())); + TString vt = TString::Format("%s/D", vn.Data()); + dummyTree->Branch(vn.Data(), d+ivar, vt.Data()); } dummyTree->Branch("type", &type, "type/I"); - if (fMLP != 0) { delete fMLP; fMLP = 0; } + if (fMLP) { delete fMLP; fMLP = nullptr; } fMLP = new TMultiLayerPerceptron( fMLPBuildOptions.Data(), dummyTree ); fMLP->LoadWeights( "./TMlp.nn.weights.temp" ); diff --git a/tmva/tmva/src/MinuitFitter.cxx b/tmva/tmva/src/MinuitFitter.cxx index 1fd5ff0c3d205..c8f7dfa3b1878 100644 --- a/tmva/tmva/src/MinuitFitter.cxx +++ b/tmva/tmva/src/MinuitFitter.cxx @@ -145,7 +145,7 @@ Double_t TMVA::MinuitFitter::Run( std::vector& pars ) // define fit parameters for (Int_t ipar=0; iparSetParameter( ipar, Form( "Par%i",ipar ), + fMinWrap->SetParameter( ipar, TString::Format( "Par%i",ipar ), pars[ipar], fRanges[ipar]->GetWidth()/100.0, fRanges[ipar]->GetMin(), fRanges[ipar]->GetMax() ); if (fRanges[ipar]->GetWidth() == 0.0) fMinWrap->FixParameter( ipar ); diff --git a/tmva/tmva/src/PDEFoam.cxx b/tmva/tmva/src/PDEFoam.cxx index 2089a708c145e..53a77f6d2904c 100644 --- a/tmva/tmva/src/PDEFoam.cxx +++ b/tmva/tmva/src/PDEFoam.cxx @@ -1291,12 +1291,12 @@ TH2D* TMVA::PDEFoam::Project2( Int_t idim1, Int_t idim2, ECellValue cell_value, } // create result histogram - TString hname(Form("h_%d_vs_%d",idim1,idim2)); + TString hname = TString::Format("h_%d_vs_%d",idim1,idim2); // if histogram with this name already exists, delete it - TH2D* h1=(TH2D*)gDirectory->Get(hname.Data()); + TH2D* h1 = (TH2D*)gDirectory->Get(hname.Data()); if (h1) delete h1; - h1= new TH2D(hname.Data(), Form("var%d vs var%d",idim1,idim2), nbin, fXmin[idim1], fXmax[idim1], nbin, fXmin[idim2], fXmax[idim2]); + h1 = new TH2D(hname.Data(), TString::Format("var%d vs var%d",idim1,idim2).Data(), nbin, fXmin[idim1], fXmax[idim1], nbin, fXmin[idim2], fXmax[idim2]); if (!h1) Log() << kFATAL << "ERROR: Can not create histo" << hname << Endl; diff --git a/tmva/tmva/src/PDEFoamDecisionTree.cxx b/tmva/tmva/src/PDEFoamDecisionTree.cxx index 94bab491035b6..795641a71d6cf 100644 --- a/tmva/tmva/src/PDEFoamDecisionTree.cxx +++ b/tmva/tmva/src/PDEFoamDecisionTree.cxx @@ -134,14 +134,14 @@ void TMVA::PDEFoamDecisionTree::Explore(PDEFoamCell *cell) hsig_unw.reserve(fDim); hbkg_unw.reserve(fDim); for (Int_t idim = 0; idim < fDim; idim++) { - hsig.push_back(new TH1D(Form("hsig_%i", idim), - Form("signal[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); - hbkg.push_back(new TH1D(Form("hbkg_%i", idim), - Form("background[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); - hsig_unw.push_back(new TH1D(Form("hsig_unw_%i", idim), - Form("signal_unw[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); - hbkg_unw.push_back(new TH1D(Form("hbkg_unw_%i", idim), - Form("background_unw[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); + hsig.push_back(new TH1D(TString::Format("hsig_%i", idim), + TString::Format("signal[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); + hbkg.push_back(new TH1D(TString::Format("hbkg_%i", idim), + TString::Format("background[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); + hsig_unw.push_back(new TH1D(TString::Format("hsig_unw_%i", idim), + TString::Format("signal_unw[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); + hbkg_unw.push_back(new TH1D(TString::Format("hbkg_unw_%i", idim), + TString::Format("background_unw[%i]", idim), fNBin, fXmin[idim], fXmax[idim])); } // get cell position and size diff --git a/tmva/tmva/src/PDEFoamDiscriminant.cxx b/tmva/tmva/src/PDEFoamDiscriminant.cxx index 06485c0002f01..72238917ca708 100644 --- a/tmva/tmva/src/PDEFoamDiscriminant.cxx +++ b/tmva/tmva/src/PDEFoamDiscriminant.cxx @@ -191,12 +191,12 @@ TH2D* TMVA::PDEFoamDiscriminant::Project2(Int_t idim1, Int_t idim2, ECellValue c } // create result histogram - TString hname(Form("h_%d_vs_%d", idim1, idim2)); + TString hname = TString::Format("h_%d_vs_%d", idim1, idim2); // if histogram with this name already exists, delete it TH2D* h1 = (TH2D*)gDirectory->Get(hname.Data()); if (h1) delete h1; - h1 = new TH2D(hname.Data(), Form("var%d vs var%d", idim1, idim2), nbin, fXmin[idim1], fXmax[idim1], nbin, fXmin[idim2], fXmax[idim2]); + h1 = new TH2D(hname.Data(), TString::Format("var%d vs var%d", idim1, idim2).Data(), nbin, fXmin[idim1], fXmax[idim1], nbin, fXmin[idim2], fXmax[idim2]); if (!h1) Log() << kFATAL << "ERROR: Can not create histo" << hname << Endl; if (cell_value == kValue) diff --git a/tmva/tmva/src/PDF.cxx b/tmva/tmva/src/PDF.cxx index 8f5be21fe742f..f97a7daa208c2 100644 --- a/tmva/tmva/src/PDF.cxx +++ b/tmva/tmva/src/PDF.cxx @@ -291,8 +291,8 @@ void TMVA::PDF::BuildPDF( const TH1* hist ) fHist ->SetTitle( fHist->GetName() ); // do not store in current target file - fHistOriginal->SetDirectory(0); - fHist ->SetDirectory(0); + fHistOriginal->SetDirectory(nullptr); + fHist ->SetDirectory(nullptr); fUseHistogram = kFALSE; if (fInterpolMethod == PDF::kKDE) BuildKDEPDF(); @@ -377,7 +377,7 @@ void TMVA::PDF::BuildSplinePDF() if (fNormalize) if (integral>0) fPDFHist->Scale( 1.0/integral ); - fPDFHist->SetDirectory(0); + fPDFHist->SetDirectory(nullptr); } //////////////////////////////////////////////////////////////////////////////// @@ -447,7 +447,7 @@ void TMVA::PDF::BuildKDEPDF() // normalize if (fNormalize) if (integral>0) fPDFHist->Scale( 1.0/integral ); - fPDFHist->SetDirectory(0); + fPDFHist->SetDirectory(nullptr); } //////////////////////////////////////////////////////////////////////////////// @@ -544,7 +544,7 @@ void TMVA::PDF::FillSplineToHist() fPDFHist->SetBinContent( bin, TMath::Max(y, fgEpsilon) ); } } - fPDFHist->SetDirectory(0); + fPDFHist->SetDirectory(nullptr); } //////////////////////////////////////////////////////////////////////////////// @@ -616,14 +616,14 @@ void TMVA::PDF::ValidatePDF( TH1* originalHist ) const } Log() << kDEBUG << "Validation result for PDF \"" << originalHist->GetTitle() << "\"" << ": " << Endl; - Log() << kDEBUG << Form( " chi2/ndof(!=0) = %.1f/%i = %.2f (Prob = %.2f)", + Log() << kDEBUG << TString::Format( " chi2/ndof(!=0) = %.1f/%i = %.2f (Prob = %.2f)", chi2, ndof, chi2/ndof, TMath::Prob( chi2, ndof ) ) << Endl; if ((1.0 - TMath::Prob( chi2, ndof )) > 0.9999994) { Log() << kDEBUG << "Comparison of the original histogram \"" << originalHist->GetTitle() << "\"" << Endl; Log() << kDEBUG << "with the corresponding PDF gave a chi2/ndof of " << chi2/ndof << "," << Endl; Log() << kDEBUG << "which corresponds to a deviation of more than 5 sigma! Please check!" << Endl; } - Log() << kDEBUG << Form( " #bins-found(#expected-bins) deviating > [1,2,3,6] sigmas: " \ + Log() << kDEBUG << TString::Format( " #bins-found(#expected-bins) deviating > [1,2,3,6] sigmas: " \ "[%i(%i),%i(%i),%i(%i),%i(%i)]", nc1, Int_t(TMath::Prob(1.0,1)*ndof), nc2, Int_t(TMath::Prob(4.0,1)*ndof), nc3, Int_t(TMath::Prob(9.0,1)*ndof), nc6, Int_t(TMath::Prob(36.0,1)*ndof) ) << Endl; @@ -819,24 +819,24 @@ void TMVA::PDF::FindBinInverse( const TH1* histogram, Int_t& lowerBin, Int_t& hi void TMVA::PDF::DeclareOptions() { - DeclareOptionRef( fNsmooth, Form("NSmooth%s",fSuffix.Data()), + DeclareOptionRef( fNsmooth, TString::Format("NSmooth%s",fSuffix.Data()), "Number of smoothing iterations for the input histograms" ); - DeclareOptionRef( fMinNsmooth, Form("MinNSmooth%s",fSuffix.Data()), + DeclareOptionRef( fMinNsmooth, TString::Format("MinNSmooth%s",fSuffix.Data()), "Min number of smoothing iterations, for bins with most data" ); - DeclareOptionRef( fMaxNsmooth, Form("MaxNSmooth%s",fSuffix.Data()), + DeclareOptionRef( fMaxNsmooth, TString::Format("MaxNSmooth%s",fSuffix.Data()), "Max number of smoothing iterations, for bins with least data" ); - DeclareOptionRef( fHistAvgEvtPerBin, Form("NAvEvtPerBin%s",fSuffix.Data()), + DeclareOptionRef( fHistAvgEvtPerBin, TString::Format("NAvEvtPerBin%s",fSuffix.Data()), "Average number of events per PDF bin" ); - DeclareOptionRef( fHistDefinedNBins, Form("Nbins%s",fSuffix.Data()), + DeclareOptionRef( fHistDefinedNBins, TString::Format("Nbins%s",fSuffix.Data()), "Defined number of bins for the histogram from which the PDF is created" ); - DeclareOptionRef( fCheckHist, Form("CheckHist%s",fSuffix.Data()), + DeclareOptionRef( fCheckHist, TString::Format("CheckHist%s",fSuffix.Data()), "Whether or not to check the source histogram of the PDF" ); - DeclareOptionRef( fInterpolateString, Form("PDFInterpol%s",fSuffix.Data()), + DeclareOptionRef( fInterpolateString, TString::Format("PDFInterpol%s",fSuffix.Data()), "Interpolation method for reference histograms (e.g. Spline2 or KDE)" ); AddPreDefVal(TString("Spline0")); // take histogram AddPreDefVal(TString("Spline1")); // linear interpolation between bins @@ -845,17 +845,17 @@ void TMVA::PDF::DeclareOptions() AddPreDefVal(TString("Spline5")); // fifth order polynom interpolation AddPreDefVal(TString("KDE")); // use kernel density estimator - DeclareOptionRef( fKDEtypeString, Form("KDEtype%s",fSuffix.Data()), "KDE kernel type (1=Gauss)" ); + DeclareOptionRef( fKDEtypeString, TString::Format("KDEtype%s",fSuffix.Data()), "KDE kernel type (1=Gauss)" ); AddPreDefVal(TString("Gauss")); - DeclareOptionRef( fKDEiterString, Form("KDEiter%s",fSuffix.Data()), "Number of iterations (1=non-adaptive, 2=adaptive)" ); + DeclareOptionRef( fKDEiterString, TString::Format("KDEiter%s",fSuffix.Data()), "Number of iterations (1=non-adaptive, 2=adaptive)" ); AddPreDefVal(TString("Nonadaptive")); AddPreDefVal(TString("Adaptive")); - DeclareOptionRef( fFineFactor , Form("KDEFineFactor%s",fSuffix.Data()), + DeclareOptionRef( fFineFactor , TString::Format("KDEFineFactor%s",fSuffix.Data()), "Fine tuning factor for Adaptive KDE: Factor to multiply the width of the kernel"); - DeclareOptionRef( fBorderMethodString, Form("KDEborder%s",fSuffix.Data()), + DeclareOptionRef( fBorderMethodString, TString::Format("KDEborder%s",fSuffix.Data()), "Border effects treatment (1=no treatment , 2=kernel renormalization, 3=sample mirroring)" ); AddPreDefVal(TString("None")); AddPreDefVal(TString("Renorm")); @@ -986,7 +986,7 @@ void TMVA::PDF::ReadXML( void* pdfnode ) TH1* newhist = 0; if (hasEquidistantBinning) { newhist = new TH1F( hname, hname, nbins, xmin, xmax ); - newhist->SetDirectory(0); + newhist->SetDirectory(nullptr); const char* content = gTools().GetContent(histch); std::stringstream s(content); Double_t val; @@ -1010,7 +1010,7 @@ void TMVA::PDF::ReadXML( void* pdfnode ) std::stringstream sb(binString); for (UInt_t i=0; i<=nbins; i++) sb >> binns[i]; newhist = new TH1F( hname, hname, nbins, binns.GetMatrixArray() ); - newhist->SetDirectory(0); + newhist->SetDirectory(nullptr); for (UInt_t i=0; i> val; newhist->SetBinContent(i+1,val); @@ -1024,7 +1024,7 @@ void TMVA::PDF::ReadXML( void* pdfnode ) fHistOriginal = newhist; fHist = (TH1F*)fHistOriginal->Clone( hnameSmooth ); fHist->SetTitle( hnameSmooth ); - fHist->SetDirectory(0); + fHist->SetDirectory(nullptr); if (fInterpolMethod == PDF::kKDE) BuildKDEPDF(); else BuildSplinePDF(); @@ -1111,7 +1111,7 @@ std::istream& TMVA::operator>> ( std::istream& istr, PDF& pdf ) std::exit(1); } TH1* newhist = new TH1F( hname,hname, nbins, xmin, xmax ); - newhist->SetDirectory(0); + newhist->SetDirectory(nullptr); Float_t val; for (Int_t i=0; i> val; @@ -1122,7 +1122,7 @@ std::istream& TMVA::operator>> ( std::istream& istr, PDF& pdf ) pdf.fHistOriginal = newhist; pdf.fHist = (TH1F*)pdf.fHistOriginal->Clone( hnameSmooth ); pdf.fHist->SetTitle( hnameSmooth ); - pdf.fHist->SetDirectory(0); + pdf.fHist->SetDirectory(nullptr); if (pdf.fMinNsmooth>=0) pdf.BuildSplinePDF(); else { diff --git a/tmva/tmva/src/ROCCalc.cxx b/tmva/tmva/src/ROCCalc.cxx index 278e93103fce2..9e5c0ce5c76b0 100644 --- a/tmva/tmva/src/ROCCalc.cxx +++ b/tmva/tmva/src/ROCCalc.cxx @@ -484,10 +484,10 @@ TH1* TMVA::ROCCalc::GetSignificance( Int_t nStot, Int_t nBtot) tl.SetNDC(); tl.SetTextSize( 0.033 ); Int_t maxbin = fSignificance->GetMaximumBin(); - line1 = tl.DrawLatex( 0.15, 0.23, Form("For %1.0f signal and %1.0f background", nStot, nBtot)); + line1 = tl.DrawLatex( 0.15, 0.23, TString::Format("For %1.0f signal and %1.0f background", nStot, nBtot)); tl.DrawLatex( 0.15, 0.19, "events the maximum S/Sqrt(S+B) is"); - line2 = tl.DrawLatex( 0.15, 0.15, Form("%4.2f when cutting at %5.2f", + line2 = tl.DrawLatex( 0.15, 0.15, TString::Format("%4.2f when cutting at %5.2f", maxSig, fSignificance->GetXaxis()->GetBinCenter(maxbin)) ); */ diff --git a/tmva/tmva/src/Ranking.cxx b/tmva/tmva/src/Ranking.cxx index fc2f53e68b141..b9471c4df1dbb 100644 --- a/tmva/tmva/src/Ranking.cxx +++ b/tmva/tmva/src/Ranking.cxx @@ -126,9 +126,9 @@ void TMVA::Ranking::Print() const Log() << kINFO << hline << Endl; for (std::vector::const_iterator ir = fRanking.begin(); ir != fRanking.end(); ++ir ) { Log() << kINFO - << Form( "%4i : ",(*ir).GetRank() ) + << TString::Format( "%4i : ",(*ir).GetRank() ) << std::setw(TMath::Max(maxL+0,9)) << (*ir).GetVariable().Data() - << Form( " : %3.3e", (*ir).GetRankValue() ) << Endl; + << TString::Format( " : %3.3e", (*ir).GetRankValue() ) << Endl; } Log() << kINFO << hline << Endl; } diff --git a/tmva/tmva/src/Results.cxx b/tmva/tmva/src/Results.cxx index 19c4ddf0bca8b..eb28b08e86f9a 100644 --- a/tmva/tmva/src/Results.cxx +++ b/tmva/tmva/src/Results.cxx @@ -54,7 +54,7 @@ TMVA::Results::Results( const DataSetInfo* dsi, TString resultsName ) fDsi(dsi), fStorage( new TList() ), fHistAlias( new std::map ), - fLogger( new MsgLogger(Form("Results%s",resultsName.Data()), kINFO) ) + fLogger( new MsgLogger(TString::Format("Results%s",resultsName.Data()).Data(), kINFO) ) { fStorage->SetOwner(); } @@ -87,19 +87,19 @@ void TMVA::Results::Store( TObject* obj, const char* alias ) { TListIter l(fStorage); // check if object is already in list - while (void* p = (void*)l()) { - if(p==obj) - *fLogger << kFATAL << "Histogram pointer " << p << " already exists in results storage" << Endl; + while (auto p = l()) { + if(p == obj) + *fLogger << kFATAL << "Histogram pointer " << (void *) p << " already exists in results storage" << Endl; } - TString as(obj->GetName()); - if (alias!=0) as=TString(alias); + TString as = obj->GetName(); + if (alias) as=TString(alias); if (fHistAlias->find(as) != fHistAlias->end()) { // alias exists *fLogger << kFATAL << "Alias " << as << " already exists in results storage" << Endl; } if( obj->InheritsFrom(TH1::Class()) ) { - ((TH1*)obj)->SetDirectory(0); + ((TH1*)obj)->SetDirectory(nullptr); } fStorage->Add( obj ); fHistAlias->insert(std::pair(as,obj)); diff --git a/tmva/tmva/src/ResultsClassification.cxx b/tmva/tmva/src/ResultsClassification.cxx index 7a8e759b67d60..edbef78b947ec 100644 --- a/tmva/tmva/src/ResultsClassification.cxx +++ b/tmva/tmva/src/ResultsClassification.cxx @@ -51,7 +51,7 @@ namespace TMVA { TMVA::ResultsClassification::ResultsClassification( const DataSetInfo* dsi, TString resultsName ) : Results( dsi,resultsName ), fRet(1), - fLogger( new MsgLogger(Form("ResultsClassification%s",resultsName.Data()) , kINFO) ) + fLogger( new MsgLogger(TString::Format("ResultsClassification%s",resultsName.Data()).Data() , kINFO) ) { } diff --git a/tmva/tmva/src/ResultsMulticlass.cxx b/tmva/tmva/src/ResultsMulticlass.cxx index 70b7922ed8606..acf9608c03dfb 100644 --- a/tmva/tmva/src/ResultsMulticlass.cxx +++ b/tmva/tmva/src/ResultsMulticlass.cxx @@ -58,7 +58,7 @@ Class which takes the results of a multiclass classification TMVA::ResultsMulticlass::ResultsMulticlass( const DataSetInfo* dsi, TString resultsName ) : Results( dsi, resultsName ), IFitterTarget(), - fLogger( new MsgLogger(Form("ResultsMultiClass%s",resultsName.Data()) , kINFO) ), + fLogger( new MsgLogger(TString::Format("ResultsMultiClass%s",resultsName.Data()).Data() , kINFO) ), fClassToOptimize(0), fAchievableEff(dsi->GetNClasses()), fAchievablePur(dsi->GetNClasses()), @@ -256,8 +256,8 @@ void TMVA::ResultsMulticlass::CreateMulticlassPerformanceHistos(TString prefix) for (size_t iClass = 0; iClass < numClasses; ++iClass) { TString className = dsi->GetClassInfo(iClass)->GetName(); - TString name = Form("%s_rejBvsS_%s", prefix.Data(), className.Data()); - TString title = Form("%s_%s", prefix.Data(), className.Data()); + TString name = TString::Format("%s_rejBvsS_%s", prefix.Data(), className.Data()); + TString title = TString::Format("%s_%s", prefix.Data(), className.Data()); // Histograms are already generated, skip. if ( DoesExist(name) ) { @@ -337,8 +337,8 @@ void TMVA::ResultsMulticlass::CreateMulticlassPerformanceHistos(TString prefix) // Style ROC Curve TString iClassName = dsi->GetClassInfo(iClass)->GetName(); TString jClassName = dsi->GetClassInfo(jClass)->GetName(); - TString name = Form("%s_1v1rejBvsS_%s_vs_%s", prefix.Data(), iClassName.Data(), jClassName.Data()); - TString title = Form("%s_%s_vs_%s", prefix.Data(), iClassName.Data(), jClassName.Data()); + TString name = TString::Format("%s_1v1rejBvsS_%s_vs_%s", prefix.Data(), iClassName.Data(), jClassName.Data()); + TString title = TString::Format("%s_%s_vs_%s", prefix.Data(), iClassName.Data(), jClassName.Data()); rocGraph->SetName(name); rocGraph->SetTitle(title); @@ -365,10 +365,10 @@ void TMVA::ResultsMulticlass::CreateMulticlassHistos( TString prefix, Int_t nbi for (UInt_t iCls = 0; iCls < dsi->GetNClasses(); iCls++) { histos.push_back(std::vector(0)); for (UInt_t jCls = 0; jCls < dsi->GetNClasses(); jCls++) { - TString name(Form("%s_%s_prob_for_%s",prefix.Data(), + TString name = TString::Format("%s_%s_prob_for_%s",prefix.Data(), dsi->GetClassInfo( jCls )->GetName(), - dsi->GetClassInfo( iCls )->GetName())); - + dsi->GetClassInfo( iCls )->GetName()); + // Histograms are already generated, skip. if ( DoesExist(name) ) { return; @@ -400,9 +400,9 @@ void TMVA::ResultsMulticlass::CreateMulticlassHistos( TString prefix, Int_t nbi for (UInt_t iCls = 0; iCls < dsi->GetNClasses(); iCls++) { histos_highbin.push_back(std::vector(0)); for (UInt_t jCls = 0; jCls < dsi->GetNClasses(); jCls++) { - TString name(Form("%s_%s_prob_for_%s_HIGHBIN",prefix.Data(), + TString name = TString::Format("%s_%s_prob_for_%s_HIGHBIN",prefix.Data(), dsi->GetClassInfo( jCls )->GetName().Data(), - dsi->GetClassInfo( iCls )->GetName().Data())); + dsi->GetClassInfo( iCls )->GetName().Data()); histos_highbin.at(iCls).push_back(new TH1F(name,name,nbins_high,xmin,xmax)); } } diff --git a/tmva/tmva/src/ResultsRegression.cxx b/tmva/tmva/src/ResultsRegression.cxx index 2b72ff0d776cf..ea779c9199a45 100644 --- a/tmva/tmva/src/ResultsRegression.cxx +++ b/tmva/tmva/src/ResultsRegression.cxx @@ -50,7 +50,7 @@ Class that is the base-class for a vector of result TMVA::ResultsRegression::ResultsRegression( const DataSetInfo* dsi, TString resultsName ) : Results( dsi, resultsName ), - fLogger( new MsgLogger(Form("ResultsRegression%s",resultsName.Data()) , kINFO) ) + fLogger( new MsgLogger(TString::Format("ResultsRegression%s",resultsName.Data()).Data() , kINFO) ) { } @@ -77,7 +77,7 @@ TH1F* TMVA::ResultsRegression::QuadraticDeviation( UInt_t tgtNum , Bool_t trunc DataSet* ds = GetDataSet(); ds->SetCurrentType( GetTreeType() ); const DataSetInfo* dsi = GetDataSetInfo(); - TString name( Form("tgt_%d",tgtNum) ); + TString name = TString::Format("tgt_%d",tgtNum); VariableInfo vinf = dsi->GetTargetInfo(tgtNum); Float_t xmin=0., xmax=0.; if (truncate){ @@ -95,7 +95,7 @@ TH1F* TMVA::ResultsRegression::QuadraticDeviation( UInt_t tgtNum , Bool_t trunc xmax *= 1.1; Int_t nbins = 500; TH1F* h = new TH1F( name, name, nbins, xmin, xmax); - h->SetDirectory(0); + h->SetDirectory(nullptr); h->GetXaxis()->SetTitle("Quadratic Deviation"); h->GetYaxis()->SetTitle("Weighted Entries"); @@ -117,7 +117,7 @@ TH2F* TMVA::ResultsRegression::DeviationAsAFunctionOf( UInt_t varNum, UInt_t tg DataSet* ds = GetDataSet(); ds->SetCurrentType( GetTreeType() ); - TString name( Form("tgt_%d_var_%d",tgtNum, varNum) ); + TString name = TString::Format("tgt_%d_var_%d",tgtNum, varNum); const DataSetInfo* dsi = GetDataSetInfo(); Float_t xmin, xmax; Bool_t takeTargets = kFALSE; @@ -178,7 +178,7 @@ TH2F* TMVA::ResultsRegression::DeviationAsAFunctionOf( UInt_t varNum, UInt_t tg TH2F* h = new TH2F( name, name, nxbins, xmin, xmax, nybins, ymin, ymax ); - h->SetDirectory(0); + h->SetDirectory(nullptr); h->GetXaxis()->SetTitle( (takeTargets ? dsi->GetTargetInfo(varNum).GetTitle() : dsi->GetVariableInfo(varNum).GetTitle() ) ); TString varName( dsi->GetTargetInfo(tgtNum).GetTitle() ); @@ -208,7 +208,7 @@ void TMVA::ResultsRegression::CreateDeviationHistograms( TString prefix ) for (UInt_t ivar = 0; ivar < dsi->GetNVariables(); ivar++) { for (UInt_t itgt = 0; itgt < dsi->GetNTargets(); itgt++) { TH2F* h = DeviationAsAFunctionOf( ivar, itgt ); - TString name( Form("%s_reg_var%d_rtgt%d",prefix.Data(),ivar,itgt) ); + TString name = TString::Format("%s_reg_var%d_rtgt%d",prefix.Data(),ivar,itgt); h->SetName( name ); h->SetTitle( name ); Store( h ); @@ -218,7 +218,7 @@ void TMVA::ResultsRegression::CreateDeviationHistograms( TString prefix ) for (UInt_t ivar = 0; ivar < dsi->GetNTargets(); ivar++) { for (UInt_t itgt = 0; itgt < dsi->GetNTargets(); itgt++) { TH2F* h = DeviationAsAFunctionOf( dsi->GetNVariables()+ivar, itgt ); - TString name( Form("%s_reg_tgt%d_rtgt%d",prefix.Data(),ivar,itgt) ); + TString name = TString::Format("%s_reg_tgt%d_rtgt%d",prefix.Data(),ivar,itgt); h->SetName( name ); h->SetTitle( name ); Store( h ); @@ -228,7 +228,7 @@ void TMVA::ResultsRegression::CreateDeviationHistograms( TString prefix ) Log() << kINFO << "Create regression average deviation" << Endl; for (UInt_t itgt = 0; itgt < dsi->GetNTargets(); itgt++) { TH1F* h = QuadraticDeviation(itgt); - TString name( Form("%s_Quadr_Deviation_target_%d_",prefix.Data(),itgt) ); + TString name = TString::Format("%s_Quadr_Deviation_target_%d_",prefix.Data(),itgt); h->SetName( name ); h->SetTitle( name ); Double_t yq[1], xq[]={0.9}; @@ -236,7 +236,7 @@ void TMVA::ResultsRegression::CreateDeviationHistograms( TString prefix ) Store( h ); TH1F* htrunc = QuadraticDeviation(itgt, true, yq[0]); - TString name2( Form("%s_Quadr_Dev_best90perc_target_%d_",prefix.Data(),itgt) ); + TString name2 = TString::Format("%s_Quadr_Dev_best90perc_target_%d_",prefix.Data(),itgt); htrunc->SetName( name2 ); htrunc->SetTitle( name2 ); Store( htrunc ); diff --git a/tmva/tmva/src/RuleEnsemble.cxx b/tmva/tmva/src/RuleEnsemble.cxx index f94828212ea10..3775dc4b1e132 100644 --- a/tmva/tmva/src/RuleEnsemble.cxx +++ b/tmva/tmva/src/RuleEnsemble.cxx @@ -674,8 +674,8 @@ void TMVA::RuleEnsemble::MakeLinearTerms() { if (fLinPDFB[v]) delete fLinPDFB[v]; if (fLinPDFS[v]) delete fLinPDFS[v]; - fLinPDFB[v] = new TH1F(Form("bkgvar%d",v),"bkg temphist",40,fLinDM[v],fLinDP[v]); - fLinPDFS[v] = new TH1F(Form("sigvar%d",v),"sig temphist",40,fLinDM[v],fLinDP[v]); + fLinPDFB[v] = new TH1F(TString::Format("bkgvar%d",v),"bkg temphist",40,fLinDM[v],fLinDP[v]); + fLinPDFS[v] = new TH1F(TString::Format("sigvar%d",v),"sig temphist",40,fLinDM[v],fLinDP[v]); fLinPDFB[v]->Sumw2(); fLinPDFS[v]->Sumw2(); } @@ -1025,7 +1025,7 @@ void TMVA::RuleEnsemble::Print() const // if (pind==0) impref = // Log() << kmtype << "Rule #" << // Log() << kmtype << *fRules[ind] << Endl; - fRules[ind]->PrintLogger(Form("Rule %4d : ",pind+1)); + fRules[ind]->PrintLogger(TString::Format("Rule %4d : ",pind+1)); pind++; if (pind==printN) { if (nrules==printN) { diff --git a/tmva/tmva/src/RuleFitParams.cxx b/tmva/tmva/src/RuleFitParams.cxx index 966b8fd588577..21c20de7cc27c 100644 --- a/tmva/tmva/src/RuleFitParams.cxx +++ b/tmva/tmva/src/RuleFitParams.cxx @@ -195,10 +195,10 @@ void TMVA::RuleFitParams::InitNtuple() fNTLinCoeff = (fNLinear>0 ? new Double_t[fNLinear] : 0); for (UInt_t i=0; iBranch(Form("a%d",i+1),&fNTCoeff[i],Form("a%d/D",i+1)); + fGDNtuple->Branch(TString::Format("a%d",i+1).Data(),&fNTCoeff[i],TString::Format("a%d/D",i+1).Data()); } for (UInt_t i=0; iBranch(Form("b%d",i+1),&fNTLinCoeff[i],Form("b%d/D",i+1)); + fGDNtuple->Branch(TString::Format("b%d",i+1).Data(),&fNTLinCoeff[i],TString::Format("b%d/D",i+1).Data()); } } diff --git a/tmva/tmva/src/Timer.cxx b/tmva/tmva/src/Timer.cxx index 72d847bacf430..0eb64fc2b087c 100644 --- a/tmva/tmva/src/Timer.cxx +++ b/tmva/tmva/src/Timer.cxx @@ -262,20 +262,20 @@ void TMVA::Timer::DrawProgressBar( Int_t icounts, const TString& comment ) TString TMVA::Timer::SecToText( Double_t seconds, Bool_t Scientific ) const { TString out = ""; - if (Scientific ) out = Form( "%.3g sec", seconds ); + if (Scientific ) out = TString::Format( "%.3g sec", seconds ); else if (seconds < 0 ) out = "unknown"; - else if (seconds <= 300) out = Form( "%i sec", Int_t(seconds) ); + else if (seconds <= 300) out = TString::Format( "%i sec", Int_t(seconds) ); else { if (seconds > 3600) { Int_t h = Int_t(seconds/3600); - if (h <= 1) out = Form( "%i hr : ", h ); - else out = Form( "%i hrs : ", h ); + if (h <= 1) out = TString::Format( "%i hr : ", h ); + else out = TString::Format( "%i hrs : ", h ); seconds = Int_t(seconds)%3600; } Int_t m = Int_t(seconds/60); - if (m <= 1) out += Form( "%i min", m ); - else out += Form( "%i mins", m ); + if (m <= 1) out += TString::Format( "%i min", m ); + else out += TString::Format( "%i mins", m ); } return (fColourfulOutput) ? gTools().Color("red") + out + gTools().Color("reset") : out; diff --git a/tmva/tmva/src/Tools.cxx b/tmva/tmva/src/Tools.cxx index 275eb212acbe8..0cc60ad87d2ba 100644 --- a/tmva/tmva/src/Tools.cxx +++ b/tmva/tmva/src/Tools.cxx @@ -969,7 +969,7 @@ void TMVA::Tools::FormattedOutput( const TMatrixD& M, const std::vector for (UInt_t irow=0; irowGetBinWidth(1), unit.Data() ); + retval += TString::Format( "dN_{ }/^{ }%.3g %s", h.GetXaxis()->GetBinWidth(1), unit.Data() ); return retval; } @@ -1233,7 +1233,7 @@ TString TMVA::Tools::StringFromInt( Long_t i ) TString TMVA::Tools::StringFromDouble( Double_t d ) { std::stringstream s; - s << Form( "%5.8e", d ); + s << TString::Format( "%5.8e", d ); return TString(s.str().c_str()); } @@ -1248,7 +1248,7 @@ void TMVA::Tools::WriteTMatrixDToXML( void* node, const char* name, TMatrixD* ma std::stringstream s; for (Int_t row = 0; rowGetNrows(); row++) { for (Int_t col = 0; colGetNcols(); col++) { - s << Form( "%5.15e ", (*mat)[row][col] ); + s << TString::Format( "%5.15e ", (*mat)[row][col] ); } } xmlengine().AddRawLine( matnode, s.str().c_str() ); @@ -1331,7 +1331,7 @@ void TMVA::Tools::ROOTVersionMessage( MsgLogger& logger ) Int_t iday = idatqq%100; Int_t imonth = (idatqq/100)%100; Int_t iyear = (idatqq/10000); - TString versionDate = Form("%s %d, %4d",months[imonth-1],iday,iyear); + TString versionDate = TString::Format("%s %d, %4d",months[imonth-1],iday,iyear); logger << kHEADER ; logger << "You are running ROOT Version: " << gROOT->GetVersion() << ", " << versionDate << Endl; @@ -1756,7 +1756,7 @@ Double_t TMVA::Tools::RMS(Long64_t n, const T *a, const Double_t *w) TH1* TMVA::Tools::GetCumulativeDist( TH1* h) { - TH1* cumulativeDist= (TH1*) h->Clone(Form("%sCumul",h->GetTitle())); + TH1* cumulativeDist= (TH1*) h->Clone(TString::Format("%sCumul",h->GetTitle())); //cumulativeDist->Smooth(5); // with this, I get less beautiful ROC curves, hence out! Float_t partialSum = 0; diff --git a/tmva/tmva/src/TransformationHandler.cxx b/tmva/tmva/src/TransformationHandler.cxx index 5ba3985befef6..fc263d741f7c2 100644 --- a/tmva/tmva/src/TransformationHandler.cxx +++ b/tmva/tmva/src/TransformationHandler.cxx @@ -173,6 +173,7 @@ const TMVA::Event* TMVA::TransformationHandler::InverseTransform( const Event* e // the inverse transformation TListIter trIt(&fTransformations, kIterBackward); std::vector< Int_t >::const_iterator rClsIt = fTransformationsReferenceClasses.end(); + std::vector::const_iterator rClsBegin = fTransformationsReferenceClasses.begin(); --rClsIt; const Event* trEv = ev; UInt_t nvars = 0, ntgts = 0, nspcts = 0; @@ -183,7 +184,8 @@ const TMVA::Event* TMVA::TransformationHandler::InverseTransform( const Event* e trEv = trf->InverseTransform(ev, (*rClsIt) ); } else break; - --rClsIt; + if (rClsIt > rClsBegin) + --rClsIt; } return trEv; @@ -550,7 +552,7 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even Int_t xmax = TMath::Nint( GetMax( ( var_tgt*nvar )+ivar) + 1 ); Int_t nbins = xmax - xmin; - h = new TH1F( Form("%s__%s%s", myVari.Data(), className.Data(), transfType.Data()), + h = new TH1F( TString::Format("%s__%s%s", myVari.Data(), className.Data(), transfType.Data()).Data(), info.GetTitle(), nbins, xmin, xmax ); } else { @@ -564,7 +566,7 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even // safety margin for values equal to the maximum within the histogram xmax += (xmax - xmin)/nbins1D; - h = new TH1F( Form("%s__%s%s", myVari.Data(), className.Data(), transfType.Data()), + h = new TH1F( TString::Format("%s__%s%s", myVari.Data(), className.Data(), transfType.Data()).Data(), info.GetTitle(), nbins1D, xmin, xmax ); } @@ -589,9 +591,9 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even Double_t rymax = fVariableStats.at(fNumC-1).at( ( v_t*nvar )+j).fMax; // scatter plot - TH2F* h2 = new TH2F( Form( "scat_%s_vs_%s_%s%s" , myVarj.Data(), myVari.Data(), + TH2F* h2 = new TH2F( TString::Format( "scat_%s_vs_%s_%s%s" , myVarj.Data(), myVari.Data(), className.Data(), transfType.Data() ), - Form( "%s versus %s (%s)%s", infoj.GetTitle(), info.GetTitle(), + TString::Format( "%s versus %s (%s)%s", infoj.GetTitle(), info.GetTitle(), className.Data(), transfType.Data() ), nbins2D, rxmin , rxmax, nbins2D, rymin , rymax ); @@ -601,10 +603,10 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even mycorr.at(cls).at((var_tgt*nvar)+ivar).at((v_t*nvar)+j) = h2; // profile plot - TProfile* p = new TProfile( Form( "prof_%s_vs_%s_%s%s", myVarj.Data(), + TProfile* p = new TProfile( TString::Format( "prof_%s_vs_%s_%s%s", myVarj.Data(), myVari.Data(), className.Data(), transfType.Data() ), - Form( "profile %s versus %s (%s)%s", + TString::Format( "profile %s versus %s (%s)%s", infoj.GetTitle(), info.GetTitle(), className.Data(), transfType.Data() ), nbins1D, rxmin, rxmax ); @@ -749,9 +751,9 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even TString uniqueOutputDir = outputDir; Int_t counter = 0; - TObject* o = NULL; - while( (o = fRootBaseDir->FindObject(uniqueOutputDir)) != 0 ){ - uniqueOutputDir = outputDir+Form("_%d",counter); + TObject* o = nullptr; + while( (o = fRootBaseDir->FindObject(uniqueOutputDir)) != nullptr ){ + uniqueOutputDir = outputDir + TString::Format("_%d",counter); Log() << kINFO << "A " << o->ClassName() << " with name " << o->GetName() << " already exists in " << fRootBaseDir->GetPath() << ", I will try with "<& even for (Int_t cls = 0; cls < ncls; cls++) { if (hVars.at(cls).at(i) != 0) { hVars.at(cls).at(i)->Write(); - hVars.at(cls).at(i)->SetDirectory(0); + hVars.at(cls).at(i)->SetDirectory(nullptr); delete hVars.at(cls).at(i); } } @@ -795,12 +797,12 @@ void TMVA::TransformationHandler::PlotVariables (const std::vector& even for (Int_t cls = 0; cls < ncls; cls++) { if (mycorr.at(cls).at(i).at(j) != 0 ) { mycorr.at(cls).at(i).at(j)->Write(); - mycorr.at(cls).at(i).at(j)->SetDirectory(0); + mycorr.at(cls).at(i).at(j)->SetDirectory(nullptr); delete mycorr.at(cls).at(i).at(j); } if (myprof.at(cls).at(i).at(j) != 0) { myprof.at(cls).at(i).at(j)->Write(); - myprof.at(cls).at(i).at(j)->SetDirectory(0); + myprof.at(cls).at(i).at(j)->SetDirectory(nullptr); delete myprof.at(cls).at(i).at(j); } } diff --git a/tmva/tmva/src/VariableDecorrTransform.cxx b/tmva/tmva/src/VariableDecorrTransform.cxx index bb02919556bb9..914afe9e19ab7 100644 --- a/tmva/tmva/src/VariableDecorrTransform.cxx +++ b/tmva/tmva/src/VariableDecorrTransform.cxx @@ -143,13 +143,13 @@ std::vector* TMVA::VariableDecorrTransform::GetTransformationStrings( I switch( type ) { case 'v': - str += Form( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Variables()[idx].GetLabel().Data() ); + str += TString::Format( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Variables()[idx].GetLabel().Data() ); break; case 't': - str += Form( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Targets()[idx].GetLabel().Data() ); + str += TString::Format( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Targets()[idx].GetLabel().Data() ); break; case 's': - str += Form( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Spectators()[idx].GetLabel().Data() ); + str += TString::Format( "%10.5g*[%s]", TMath::Abs((*m)(ivar,jvar)), Spectators()[idx].GetLabel().Data() ); break; default: Log() << kFATAL << "VariableDecorrTransform::GetTransformationStrings : unknown type '" << type << "'." << Endl; diff --git a/tmva/tmva/src/VariableGaussTransform.cxx b/tmva/tmva/src/VariableGaussTransform.cxx index bd144c6047493..9c808bef14734 100644 --- a/tmva/tmva/src/VariableGaussTransform.cxx +++ b/tmva/tmva/src/VariableGaussTransform.cxx @@ -364,14 +364,14 @@ void TMVA::VariableGaussTransform::GetCumulativeDist( const std::vector< Event*> binnings[k] = vsForBinning[icls][ivar][k]; } fCumulativeDist[ivar].resize(numDist); - if (0 != fCumulativeDist[ivar][icls] ) { + if (fCumulativeDist[ivar][icls] ) { delete fCumulativeDist[ivar][icls]; } - fCumulativeDist[ivar][icls] = new TH1F(Form("Cumulative_Var%d_cls%d",ivar,icls), - Form("Cumulative_Var%d_cls%d",ivar,icls), + fCumulativeDist[ivar][icls] = new TH1F(TString::Format("Cumulative_Var%d_cls%d",ivar,icls), + TString::Format("Cumulative_Var%d_cls%d",ivar,icls), nbins[icls][ivar] -1, // class icls binnings); - fCumulativeDist[ivar][icls]->SetDirectory(0); + fCumulativeDist[ivar][icls]->SetDirectory(nullptr); delete [] binnings; } } @@ -428,7 +428,7 @@ void TMVA::VariableGaussTransform::GetCumulativeDist( const std::vector< Event*> (fCumulativeDist[ivar][icls])->SetBinContent(ibin,sum/total); } // create PDf - fCumulativePDF[ivar].push_back(new PDF( Form("GaussTransform var%d cls%d",ivar,icls), fCumulativeDist[ivar][icls], PDF::kSpline1, fPdfMinSmooth, fPdfMaxSmooth,kFALSE,kFALSE)); + fCumulativePDF[ivar].push_back(new PDF( TString::Format("GaussTransform var%d cls%d",ivar,icls), fCumulativeDist[ivar][icls], PDF::kSpline1, fPdfMinSmooth, fPdfMaxSmooth,kFALSE,kFALSE)); } } } @@ -482,7 +482,7 @@ void TMVA::VariableGaussTransform::AttachXMLTo(void* parent) { Log() << kFATAL << "Cumulative histograms for variable " << ivar << " don't exist, can't write it to weight file" << Endl; for (UInt_t icls=0; iclsAddXMLTo(pdfxml); } } @@ -590,7 +590,7 @@ void TMVA::VariableGaussTransform::ReadTransformationFromStream( std::istream& i if ( histToRead !=0 ) delete histToRead; // recreate the cumulative histogram to be filled with the values read histToRead = new TH1F( hname, hname, nbins, Binnings ); - histToRead->SetDirectory(0); + histToRead->SetDirectory(nullptr); fCumulativeDist[ivar][type]=histToRead; istr >> devnullS; // read the line "BinContent" .. diff --git a/tmva/tmva/src/VariableImportance.cxx b/tmva/tmva/src/VariableImportance.cxx index f091ec38bb693..722b2735e68df 100644 --- a/tmva/tmva/src/VariableImportance.cxx +++ b/tmva/tmva/src/VariableImportance.cxx @@ -173,7 +173,7 @@ TH1F* TMVA::VariableImportance::GetImportance(const UInt_t nbits,std::vectorGetYaxis()->SetTitleOffset(1.24); vihist->GetYaxis()->SetRangeUser(-7, 50); - vihist->SetDirectory(0); + vihist->SetDirectory(nullptr); return vihist; } diff --git a/tmva/tmva/src/VariableInfo.cxx b/tmva/tmva/src/VariableInfo.cxx index 7889b5b2d1d07..777848b0346c9 100644 --- a/tmva/tmva/src/VariableInfo.cxx +++ b/tmva/tmva/src/VariableInfo.cxx @@ -148,7 +148,7 @@ TMVA::VariableInfo& TMVA::VariableInfo::operator=(const VariableInfo& rhs) void TMVA::VariableInfo::WriteToStream( std::ostream& o ) const { UInt_t nc = TMath::Max( 30, TMath::Max( GetExpression().Length()+1, GetInternalName().Length()+1 ) ); - TString expBr(Form("\'%s\'",GetExpression().Data())); + TString expBr = TString::Format("\'%s\'",GetExpression().Data()); o << std::setw(nc) << GetExpression(); o << std::setw(nc) << GetInternalName(); o << std::setw(nc) << GetLabel(); @@ -202,7 +202,7 @@ void TMVA::VariableInfo::AddToXML( void* varnode ) typeStr[0] = GetVarType(); // in case of array variables, add "[]" to the type string: e.g. F[] if (TestBit(DataSetInfo::kIsArrayVariable)) - typeStr += "[]"; + typeStr += "[]"; gTools().AddAttr(varnode, "Type", typeStr); gTools().AddAttr( varnode, "Min", gTools().StringFromDouble(GetMin()) ); gTools().AddAttr( varnode, "Max", gTools().StringFromDouble(GetMax()) ); @@ -224,7 +224,7 @@ void TMVA::VariableInfo::ReadFromXML( void* varnode ) gTools().ReadAttr( varnode, "Max", fXmaxNorm ); SetVarType(type[0]); - // detect variables from array + // detect variables from array if (type.Contains("[]")) SetBit(DataSetInfo::kIsArrayVariable); } diff --git a/tmva/tmva/src/VariableNormalizeTransform.cxx b/tmva/tmva/src/VariableNormalizeTransform.cxx index 8c43fff07a443..c37c26e007dee 100644 --- a/tmva/tmva/src/VariableNormalizeTransform.cxx +++ b/tmva/tmva/src/VariableNormalizeTransform.cxx @@ -288,8 +288,8 @@ std::vector* TMVA::VariableNormalizeTransform::GetTransformationStrings TString str(""); VariableInfo& varInfo = (type=='v'?fDsi.GetVariableInfo(idx):(type=='t'?fDsi.GetTargetInfo(idx):fDsi.GetSpectatorInfo(idx))); - if (offset < 0) str = Form( "2*%g*([%s] + %g) - 1", scale, varInfo.GetLabel().Data(), -offset ); - else str = Form( "2*%g*([%s] - %g) - 1", scale, varInfo.GetLabel().Data(), offset ); + if (offset < 0) str = TString::Format( "2*%g*([%s] + %g) - 1", scale, varInfo.GetLabel().Data(), -offset ); + else str = TString::Format( "2*%g*([%s] - %g) - 1", scale, varInfo.GetLabel().Data(), offset ); (*strVec)[iinp] = str; ++iinp; diff --git a/tmva/tmva/test/CMakeLists.txt b/tmva/tmva/test/CMakeLists.txt index 6d1e9df8787a0..ebe1be187bcee 100644 --- a/tmva/tmva/test/CMakeLists.txt +++ b/tmva/tmva/test/CMakeLists.txt @@ -27,7 +27,7 @@ if(dataframe) # RReader ROOT_ADD_GTEST(rreader rreader.cxx LIBRARIES ROOTVecOps TMVA ROOTDataFrame) # Tree inference system and user interface - if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) + if(NOT MSVC OR llvm13_broken_tests) ROOT_ADD_GTEST(branchlessForest branchlessForest.cxx LIBRARIES TMVA) ROOT_ADD_GTEST(rbdt rbdt.cxx LIBRARIES ROOTVecOps TMVA) endif() diff --git a/tmva/tmva/test/DNN/CNN/MakeImageData.h b/tmva/tmva/test/DNN/CNN/MakeImageData.h index cfbdf4130bf92..90602b3ff289e 100644 --- a/tmva/tmva/test/DNN/CNN/MakeImageData.h +++ b/tmva/tmva/test/DNN/CNN/MakeImageData.h @@ -19,8 +19,8 @@ void makeImages(int n = 10000, int npx = 8, int npy = 8, TString fileName = "ima TTree bkg("bkg","bkg"); TFile f(fileName,"RECREATE"); - bkg.Branch("ximage",x1.data(),Form("ximage[%d]/F",np)); - sgn.Branch("ximage",x2.data(),Form("ximage[%d]/F",np)); + bkg.Branch("ximage",x1.data(),TString::Format("ximage[%d]/F",np).Data()); + sgn.Branch("ximage",x2.data(),TString::Format("ximage[%d]/F",np).Data()); sgn.SetDirectory(&f); bkg.SetDirectory(&f); diff --git a/tmva/tmva/test/crossvalidation/TestCrossValidationIntVar.cxx b/tmva/tmva/test/crossvalidation/TestCrossValidationIntVar.cxx index a067b36ededa5..bec6b31947b4d 100644 --- a/tmva/tmva/test/crossvalidation/TestCrossValidationIntVar.cxx +++ b/tmva/tmva/test/crossvalidation/TestCrossValidationIntVar.cxx @@ -71,15 +71,15 @@ std::pair runCrossValidation(UInt_t numWorkers) dataloader->AddVariable("y", 'D'); dataloader->AddSpectator("EventNumber", 'I'); - TString dataloaderOptions = Form("SplitMode=Block:nTrain_Signal=%i" - ":nTrain_Background=%i:!V", - NUM_EVENTS_SIG, NUM_EVENTS_BKG); + TString dataloaderOptions = TString::Format("SplitMode=Block:nTrain_Signal=%i" + ":nTrain_Background=%i:!V", + NUM_EVENTS_SIG, NUM_EVENTS_BKG); dataloader->PrepareTrainingAndTestTree("", dataloaderOptions); // TMVA::CrossValidation takes ownership of dataloader std::string splitExpr = "UInt_t([EventNumber])%UInt_t([NumFolds])"; TMVA::CrossValidation cv{"test_cv_intvar", dataloader, - Form("!Silent:AnalysisType=Classification" + TString::Format("!Silent:AnalysisType=Classification" ":NumWorkerProcs=%i:NumFolds=%i" ":SplitType=Deterministic:SplitExpr=%s", numWorkers, NUM_FOLDS, splitExpr.c_str())}; diff --git a/tmva/tmva/test/crossvalidation/TestCrossValidationMultiProc.cxx b/tmva/tmva/test/crossvalidation/TestCrossValidationMultiProc.cxx index d16e5fc5d6a79..f3ca224fd6532 100644 --- a/tmva/tmva/test/crossvalidation/TestCrossValidationMultiProc.cxx +++ b/tmva/tmva/test/crossvalidation/TestCrossValidationMultiProc.cxx @@ -71,15 +71,15 @@ std::pair runCrossValidation(UInt_t numWorkers) dataloader->AddVariable("y", 'D'); dataloader->AddSpectator("EventNumber", 'I'); - TString dataloaderOptions = Form("SplitMode=Block:nTrain_Signal=%i" + TString dataloaderOptions = TString::Format("SplitMode=Block:nTrain_Signal=%i" ":nTrain_Background=%i:!V", NUM_EVENTS_SIG, NUM_EVENTS_BKG); dataloader->PrepareTrainingAndTestTree("", dataloaderOptions); // TMVA::CrossValidation takes ownership of dataloader std::string splitExpr = "UInt_t([EventNumber])%UInt_t([NumFolds])"; - TMVA::CrossValidation cv{Form("%i-proc", numWorkers), dataloader, - Form("!Silent:AnalysisType=Classification" + TMVA::CrossValidation cv{TString::Format("%i-proc", numWorkers), dataloader, + TString::Format("!Silent:AnalysisType=Classification" ":NumWorkerProcs=%i:NumFolds=%i" ":SplitType=Deterministic:SplitExpr=%s", numWorkers, NUM_FOLDS, splitExpr.c_str())}; diff --git a/tmva/tmva/test/crossvalidation/TestCrossValidationSplitting.cxx b/tmva/tmva/test/crossvalidation/TestCrossValidationSplitting.cxx index a401ca7585942..ef5a418bd5ef9 100644 --- a/tmva/tmva/test/crossvalidation/TestCrossValidationSplitting.cxx +++ b/tmva/tmva/test/crossvalidation/TestCrossValidationSplitting.cxx @@ -300,7 +300,7 @@ TEST(CrossValidationSplitting, TrainingSetSplitOnSpectator) d->AddVariable("x", 'D'); d->AddSpectator("id", "id", ""); d->PrepareTrainingAndTestTree( - "", Form("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); + "", TString::Format("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); d->GetDataSetInfo().GetDataSet(); // Force creation of dataset. TMVA::MsgLogger::EnableOutput(); @@ -338,7 +338,7 @@ TEST(CrossValidationSplitting, TrainingSetSplitOnSpectator2) d->AddVariable("x", 'D'); d->AddSpectator("id", "id", ""); d->PrepareTrainingAndTestTree( - "", Form("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); + "", TString::Format("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); d->GetDataSetInfo().GetDataSet(); // Force creation of dataset. TMVA::MsgLogger::EnableOutput(); @@ -374,7 +374,7 @@ TEST(CrossValidationSplitting, TrainingSetSplitRandomStratified) d->AddVariable("x", 'D'); d->AddSpectator("id", "id", ""); d->PrepareTrainingAndTestTree( - "", Form("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); + "", TString::Format("SplitMode=Block:nTrain_Signal=%i:nTrain_Background=%i:!V", nPointsSig, nPointsBkg)); d->GetDataSetInfo().GetDataSet(); // Force creation of dataset. TMVA::MsgLogger::EnableOutput(); diff --git a/tmva/tmva/test/rreader.cxx b/tmva/tmva/test/rreader.cxx index aa9d7b68b649e..235958d502750 100644 --- a/tmva/tmva/test/rreader.cxx +++ b/tmva/tmva/test/rreader.cxx @@ -35,7 +35,7 @@ void TrainClassificationModel() // Open trees with signal and background events const std::string filename = "http://root.cern.ch/files/tmva_class_example.root"; - auto data = TFile::Open(filename.c_str()); + std::unique_ptr data{TFile::Open(filename.c_str())}; auto signal = (TTree *)data->Get("TreeS"); auto background = (TTree *)data->Get("TreeB"); @@ -77,7 +77,7 @@ void TrainRegressionModel() // Open trees with signal and background events const std::string filename = "http://root.cern.ch/files/tmva_reg_example.root"; - auto data = TFile::Open(filename.c_str()); + std::unique_ptr data{TFile::Open(filename.c_str())}; auto tree = (TTree *)data->Get("TreeR"); // Add variables and register the trees with the dataloader @@ -116,7 +116,7 @@ void TrainMulticlassModel() // Open trees with signal and background events const std::string filename = "http://root.cern.ch/files/tmva_multiclass_example.root"; - auto data = TFile::Open(filename.c_str()); + std::unique_ptr data{TFile::Open(filename.c_str())}; auto signal = (TTree *)data->Get("TreeS"); auto background0 = (TTree *)data->Get("TreeB0"); auto background1 = (TTree *)data->Get("TreeB1"); diff --git a/tmva/tmva/test/rtensor.cxx b/tmva/tmva/test/rtensor.cxx index 03c6efd64f36e..e751caea2233e 100644 --- a/tmva/tmva/test/rtensor.cxx +++ b/tmva/tmva/test/rtensor.cxx @@ -74,6 +74,36 @@ TEST(RTensor, Reshape) EXPECT_EQ(s3[0], 6u); } +TEST(RTensor, Resize) +{ + float rtdata[3] = {0, 1, 2}; + RTensor x(rtdata, {1, 3}); + const auto s = x.GetShape(); + EXPECT_EQ(s.size(), 2u); + EXPECT_EQ(s[0], 1u); + EXPECT_EQ(s[1], 3u); + + float count = 0; + for(size_t i = 0; i<3; ++i){ + EXPECT_EQ(x(0,i), count); + ++count; + } + + auto x2 = x.Resize({3, 2}); + const auto s2 = x2.GetShape(); + EXPECT_EQ(s2.size(), 2u); + EXPECT_EQ(s2[0], 3u); + EXPECT_EQ(s2[1], 2u); + + count = -1; + for(size_t i = 0; i<3; ++i){ + for(size_t j = 0; j<2; ++j){ + count = ((i == 1 && j == 1) || (i == 2) ? 0 : count+1); + EXPECT_EQ(x2(i,j), count); + } + } +} + TEST(RTensor, ExpandDims) { RTensor x({2, 3}); diff --git a/tmva/tmvagui/CMakeLists.txt b/tmva/tmvagui/CMakeLists.txt index a8a9bad7692c3..5cf6b07a2aa53 100644 --- a/tmva/tmvagui/CMakeLists.txt +++ b/tmva/tmvagui/CMakeLists.txt @@ -9,6 +9,11 @@ # @author Pere Mato, CERN ############################################################################ +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(TMVAGui HEADERS TMVA/BDT.h @@ -98,4 +103,5 @@ ROOT_STANDARD_LIBRARY_PACKAGE(TMVAGui Gui HistPainter Core + ${EXTRA_DICT_OPTS} ) diff --git a/tmva/tmvagui/src/BDT.cxx b/tmva/tmvagui/src/BDT.cxx index 55b7728a605cf..7f26b7ec45d3e 100644 --- a/tmva/tmvagui/src/BDT.cxx +++ b/tmva/tmvagui/src/BDT.cxx @@ -67,7 +67,7 @@ TMVA::StatDialogBDT::StatDialogBDT(TString dataset, const TGWindow* p, TString w // main frame fMain = new TGMainFrame(p, totalWidth, totalHeight, kMainFrame | kVerticalFrame); - TGLabel *sigLab = new TGLabel( fMain, Form( "Decision tree [%i-%i]",0,fNtrees-1 ) ); + TGLabel *sigLab = new TGLabel( fMain, TString::Format( "Decision tree [%i-%i]",0,fNtrees-1 ) ); fMain->AddFrame(sigLab, new TGLayoutHints(kLHintsLeft | kLHintsTop,5,5,5,5)); fInput = new TGNumberEntry(fMain, (Double_t) fItree,5,-1,(TGNumberFormat::EStyle) 5); @@ -194,9 +194,9 @@ void TMVA::StatDialogBDT::DrawNode( TMVA::DecisionTreeNode *n, if (n->GetNodeType() == 0){ if (n->GetCutType()){ - t->AddText(TString(vars[n->GetSelector()]+">"+=::Form("%5.3g",n->GetCutValue()))); + t->AddText(vars[n->GetSelector()] + ">" + TString::Format("%5.3g",n->GetCutValue())); }else{ - t->AddText(TString(vars[n->GetSelector()]+"<"+=::Form("%5.3g",n->GetCutValue()))); + t->AddText(vars[n->GetSelector()] + "<" + TString::Format("%5.3g",n->GetCutValue())); } } @@ -318,8 +318,8 @@ void TMVA::StatDialogBDT::DrawTree( Int_t itree ) Int_t canvasColor = TMVAStyle->GetCanvasColor(); // backup - TString cbuffer = Form( "Reading weight file: %s", fWfile.Data() ); - TString tbuffer = Form( "Decision Tree no.: %d", itree ); + TString cbuffer = TString::Format( "Reading weight file: %s", fWfile.Data() ); + TString tbuffer = TString::Format( "Decision Tree no.: %d", itree ); if (!fCanvas) fCanvas = new TCanvas( "c1", cbuffer, 200, 0, 1000, 600 ); else fCanvas->Clear(); fCanvas->Draw(); @@ -359,7 +359,7 @@ void TMVA::StatDialogBDT::DrawTree( Int_t itree ) fCanvas->Update(); - TString fname = fDataset+Form("/plots/%s_%i", fMethName.Data(), itree ); + TString fname = fDataset + TString::Format("/plots/%s_%i", fMethName.Data(), itree); cout << "--- Creating image: " << fname << endl; TMVAGlob::imgconv( fCanvas, fname ); @@ -422,7 +422,7 @@ void TMVA::BDT(TString dataset, const TString& fin ) TString fname = path[im]; if (fname[fname.Length()-1] != '/') fname += "/"; fname += wfile[im]; - TString macro = Form( "TMVA::BDT(\"%s\",0,\"%s\",\"%s\")",dataset.Data(), fname.Data(), methname[im].Data() ); + TString macro = TString::Format( "TMVA::BDT(\"%s\",0,\"%s\",\"%s\")",dataset.Data(), fname.Data(), methname[im].Data() ); cbar->AddButton( fname, macro, "Plot decision trees from this weight file", "button" ); } diff --git a/tmva/tmvagui/src/BDTControlPlots.cxx b/tmva/tmvagui/src/BDTControlPlots.cxx index 498989ad8ab97..ed7434954b7cb 100644 --- a/tmva/tmvagui/src/BDTControlPlots.cxx +++ b/tmva/tmvagui/src/BDTControlPlots.cxx @@ -13,10 +13,10 @@ void TMVA::BDTControlPlots(TString dataset, TString fin , Bool_t useTMVAStyle ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); - + // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); - + TFile* file = TMVAGlob::OpenFile( fin ); + if (file == NULL) { cout << "Problems with input file, tried to open " << fin << " but somehow did not succeed .." << endl; return; @@ -51,8 +51,8 @@ void TMVA::bdtcontrolplots(TString dataset, TDirectory *bdtdir ) { char cn2[bufferSize]; const TString titName = bdtdir->GetName(); snprintf( cn, bufferSize, "cv_%s", titName.Data() ); - TCanvas *c = new TCanvas( cn, Form( "%s Control Plots", titName.Data() ), - width, height ); + TCanvas *c = new TCanvas( cn, TString::Format( "%s Control Plots", titName.Data() ), + width, height ); c->Divide(3,2); @@ -63,10 +63,10 @@ void TMVA::bdtcontrolplots(TString dataset, TDirectory *bdtdir ) { Bool_t BoostMonitorIsDone=kFALSE; for (Int_t i=0; icd(i+1); TH1 *h = (TH1*) bdtdir->Get(hname[i]); - + if (h){ h->SetMaximum(h->GetMaximum()*1.3); h->SetMinimum( 0 ); @@ -95,25 +95,25 @@ void TMVA::bdtcontrolplots(TString dataset, TDirectory *bdtdir ) { c->Update(); } } - - + + TCanvas *c2 = NULL; if (BoostMonitorIsDone){ snprintf( cn2, bufferSize, "cv2_%s", titName.Data() ); - c2 = new TCanvas( cn2, Form( "%s BoostWeights", titName.Data() ), - 1200, 1200 ); + c2 = new TCanvas( cn2, TString::Format( "%s BoostWeights", titName.Data() ), + 1200, 1200 ); c2->Divide(5,5); Int_t ipad=1; - + TIter keys( bdtdir->GetListOfKeys() ); TKey *key; // gDirectory->ls(); while ( (key = (TKey*)keys.Next()) && ipad < 26) { TObject *obj=key->ReadObj(); - if (obj->IsA()->InheritsFrom(TH1::Class())){ + if (obj->IsA()->InheritsFrom(TH1::Class())){ TH1F *hx = (TH1F*)obj; - TString hhname_(Form("%s",obj->GetTitle())); - if (hhname_.Contains("BoostWeightsInTreeB")){ + TString hhname_ = obj->GetTitle(); + if (hhname_.Contains("BoostWeightsInTreeB")){ c2->cd(ipad++); hx->SetLineColor(4); hx->Draw(); @@ -127,35 +127,35 @@ void TMVA::bdtcontrolplots(TString dataset, TDirectory *bdtdir ) { c2->Update(); } } - + } // write to file - TString fname = dataset+Form( "/plots/%s_ControlPlots", titName.Data() ); + TString fname = dataset+TString::Format( "/plots/%s_ControlPlots", titName.Data() ); TMVAGlob::imgconv( c, fname ); - + if (c2){ - fname = dataset+Form( "/plots/%s_ControlPlots2", titName.Data() ); + fname = dataset+TString::Format( "/plots/%s_ControlPlots2", titName.Data() ); TMVAGlob::imgconv( c2, fname ); } TCanvas *c3 = NULL; if (BoostMonitorIsDone){ snprintf( cn2, bufferSize, "cv3_%s", titName.Data() ); - c3 = new TCanvas( cn2, Form( "%s Variables", titName.Data() ), - 1200, 1200 ); + c3 = new TCanvas( cn2, TString::Format( "%s Variables", titName.Data() ), + 1200, 1200 ); c3->Divide(5,5); Int_t ipad=1; - + TIter keys( bdtdir->GetListOfKeys() ); TKey *key; // gDirectory->ls(); while ( (key = (TKey*)keys.Next()) && ipad < 26) { TObject *obj=key->ReadObj(); - if (obj->IsA()->InheritsFrom(TH1::Class())){ + if (obj->IsA()->InheritsFrom(TH1::Class())){ TH1F *hx = (TH1F*)obj; - TString hname_(Form("%s",obj->GetTitle())); - if (hname_.Contains("SigVar0AtTree")){ + TString hname_ = obj->GetTitle(); + if (hname_.Contains("SigVar0AtTree")){ c3->cd(ipad++); hx->SetLineColor(4); hx->Draw(); @@ -169,7 +169,7 @@ void TMVA::bdtcontrolplots(TString dataset, TDirectory *bdtdir ) { c3->Update(); } } - + } diff --git a/tmva/tmvagui/src/BDT_Reg.cxx b/tmva/tmvagui/src/BDT_Reg.cxx index 613997b80f11d..575472291bd1a 100644 --- a/tmva/tmvagui/src/BDT_Reg.cxx +++ b/tmva/tmvagui/src/BDT_Reg.cxx @@ -26,17 +26,17 @@ std::vector TMVA::BDTReg_Global__cbar; TMVA::StatDialogBDTReg* TMVA::StatDialogBDTReg::fThis = 0; -void TMVA::StatDialogBDTReg::SetItree() +void TMVA::StatDialogBDTReg::SetItree() { fItree = Int_t(fInput->GetNumber()); } -void TMVA::StatDialogBDTReg::Redraw() +void TMVA::StatDialogBDTReg::Redraw() { UpdateCanvases(); } -void TMVA::StatDialogBDTReg::Close() +void TMVA::StatDialogBDTReg::Close() { delete this; } @@ -65,7 +65,7 @@ TMVA::StatDialogBDTReg::StatDialogBDTReg(TString dataset, const TGWindow* p, TSt // main frame fMain = new TGMainFrame(p, totalWidth, totalHeight, kMainFrame | kVerticalFrame); - TGLabel *sigLab = new TGLabel( fMain, Form( "Regression tree [%i-%i]",0,fNtrees-1 ) ); + TGLabel *sigLab = new TGLabel( fMain, TString::Format( "Regression tree [%i-%i]",0,fNtrees-1 ) ); fMain->AddFrame(sigLab, new TGLayoutHints(kLHintsLeft | kLHintsTop,5,5,5,5)); fInput = new TGNumberEntry(fMain, (Double_t) fItree,5,-1,(TGNumberFormat::EStyle) 5); @@ -80,7 +80,7 @@ TMVA::StatDialogBDTReg::StatDialogBDTReg(TString dataset, const TGWindow* p, TSt fDrawButton = new TGTextButton(fButtons,"&Draw"); fButtons->AddFrame(fDrawButton, new TGLayoutHints(kLHintsRight | kLHintsTop,15)); - + fMain->AddFrame(fButtons,new TGLayoutHints(kLHintsLeft | kLHintsBottom,5,5,5,5)); fMain->SetWindowName("Regression tree"); @@ -90,15 +90,15 @@ TMVA::StatDialogBDTReg::StatDialogBDTReg(TString dataset, const TGWindow* p, TSt fMain->MapWindow(); fInput->Connect("ValueSet(Long_t)","TMVA::StatDialogBDTReg",this, "SetItree()"); - + // doesn't seem to exist .. gives an 'error message' and seems to work just fine without ... :) // fDrawButton->Connect("Clicked()","TGNumberEntry",fInput, "ValueSet(Long_t)"); - fDrawButton->Connect("Clicked()", "TMVA::StatDialogBDTReg", this, "Redraw()"); + fDrawButton->Connect("Clicked()", "TMVA::StatDialogBDTReg", this, "Redraw()"); fCloseButton->Connect("Clicked()", "TMVA::StatDialogBDTReg", this, "Close()"); } -void TMVA::StatDialogBDTReg::UpdateCanvases() +void TMVA::StatDialogBDTReg::UpdateCanvases() { DrawTree( fItree ); } @@ -111,24 +111,24 @@ void TMVA::StatDialogBDTReg::GetNtrees() std::cout << "*** ERROR: Weight file: " << fWfile << " does not exist" << std::endl; return; } - + TString dummy = ""; - + // read total number of trees, and check whether requested tree is in range Int_t nc = 0; - while (!dummy.Contains("NTrees")) { - fin >> dummy; - nc++; + while (!dummy.Contains("NTrees")) { + fin >> dummy; + nc++; if (nc > 200) { std::cout << std::endl; - std::cout << "*** Huge problem: could not locate term \"NTrees\" in BDT weight file: " + std::cout << "*** Huge problem: could not locate term \"NTrees\" in BDT weight file: " << fWfile << std::endl; std::cout << "==> panic abort (please contact the TMVA authors)" << std::endl; std::cout << std::endl; exit(1); } } - fin >> dummy; + fin >> dummy; fNtrees = dummy.ReplaceAll("\"","").Atoi(); fin.close(); } @@ -153,9 +153,9 @@ void TMVA::StatDialogBDTReg::GetNtrees() /// recursively puts an entries in the histogram for the node and its daughters /// -void TMVA::StatDialogBDTReg::DrawNode( TMVA::DecisionTreeNode *n, - Double_t x, Double_t y, - Double_t xscale, Double_t yscale, TString * vars) +void TMVA::StatDialogBDTReg::DrawNode( TMVA::DecisionTreeNode *n, + Double_t x, Double_t y, + Double_t xscale, Double_t yscale, TString * vars) { Float_t xsize=xscale*1.5; Float_t ysize=yscale/3; @@ -191,9 +191,9 @@ void TMVA::StatDialogBDTReg::DrawNode( TMVA::DecisionTreeNode *n, if (n->GetNodeType() == 0){ if (n->GetCutType()){ - t->AddText(TString(vars[n->GetSelector()]+">"+=::Form("%5.3g",n->GetCutValue()))); + t->AddText(vars[n->GetSelector()] + ">" + TString::Format("%5.3g",n->GetCutValue())); }else{ - t->AddText(TString(vars[n->GetSelector()]+"<"+=::Form("%5.3g",n->GetCutValue()))); + t->AddText(vars[n->GetSelector()] + "<" + TString::Format("%5.3g",n->GetCutValue())); } } @@ -218,15 +218,15 @@ TMVA::DecisionTree* TMVA::StatDialogBDTReg::ReadTree( TString* &vars, Int_t itre return 0; } TString dummy = ""; - + if (itree >= fNtrees) { - std::cout << "*** ERROR: requested decision tree: " << itree + std::cout << "*** ERROR: requested decision tree: " << itree << ", but number of trained trees only: " << fNtrees << std::endl; delete d; d = nullptr; return 0; } - + // file header with name while (!dummy.Contains("#VAR")) fin >> dummy; fin >> dummy >> dummy >> dummy; // the rest of header line @@ -234,12 +234,12 @@ TMVA::DecisionTree* TMVA::StatDialogBDTReg::ReadTree( TString* &vars, Int_t itre // number of variables Int_t nVars; fin >> dummy >> nVars; - + // variable mins and maxes vars = new TString[nVars+1]; for (Int_t i = 0; i < nVars; i++) fin >> vars[i] >> dummy >> dummy >> dummy >> dummy; vars[nVars]="FisherCrit"; - + char buffer[20]; char line[256]; snprintf(buffer, 20, "Tree %d",itree); @@ -250,12 +250,12 @@ TMVA::DecisionTree* TMVA::StatDialogBDTReg::ReadTree( TString* &vars, Int_t itre } d->Read(fin); - + fin.close(); } else{ if (itree >= fNtrees) { - std::cout << "*** ERROR: requested decision tree: " << itree + std::cout << "*** ERROR: requested decision tree: " << itree << ", but number of trained trees only: " << fNtrees << std::endl; delete d; d = nullptr; @@ -269,7 +269,7 @@ TMVA::DecisionTree* TMVA::StatDialogBDTReg::ReadTree( TString* &vars, Int_t itre TString nodeName = TString( TMVA::gTools().xmlengine().GetNodeName(ch) ); if(nodeName=="Variables"){ TMVA::gTools().ReadAttr( ch, "NVar", nVars); - vars = new TString[nVars+1]; + vars = new TString[nVars+1]; void* varnode = TMVA::gTools().xmlengine().GetChild(ch); for (Int_t i = 0; i < nVars; i++){ TMVA::gTools().ReadAttr( varnode, "Expression", vars[i]); @@ -291,7 +291,7 @@ TMVA::DecisionTree* TMVA::StatDialogBDTReg::ReadTree( TString* &vars, Int_t itre void TMVA::StatDialogBDTReg::DrawTree( Int_t itree ) { - TString *vars; + TString *vars; TMVA::DecisionTree* d = ReadTree( vars, itree ); if (d == 0) return; @@ -304,18 +304,18 @@ void TMVA::StatDialogBDTReg::DrawTree( Int_t itree ) TStyle* TMVAStyle = gROOT->GetStyle("Plain"); // our style is based on Plain Int_t canvasColor = TMVAStyle->GetCanvasColor(); // backup - TString cbuffer = Form( "Reading weight file: %s", fWfile.Data() ); - TString tbuffer = Form( "Regression Tree no.: %d", itree ); - if (!fCanvas) fCanvas = new TCanvas( "c1", cbuffer, 200, 0, 1000, 600 ); + TString cbuffer = TString::Format( "Reading weight file: %s", fWfile.Data() ); + TString tbuffer = TString::Format( "Regression Tree no.: %d", itree ); + if (!fCanvas) fCanvas = new TCanvas( "c1", cbuffer, 200, 0, 1000, 600 ); else fCanvas->Clear(); - fCanvas->Draw(); + fCanvas->Draw(); DrawNode( (TMVA::DecisionTreeNode*)d->GetRoot(), 0.5, 1.-0.5*ystep, 0.25, ystep ,vars); - + // make the legend Double_t yup=0.99; Double_t ydown=yup-ystep/2.5; Double_t dy= ystep/2.5 * 0.2; - + TPaveText *whichTree = new TPaveText(0.85,ydown,0.98,yup, "NDC"); whichTree->SetBorderSize(1); whichTree->SetFillStyle(1001); @@ -353,13 +353,13 @@ void TMVA::StatDialogBDTReg::DrawTree( Int_t itree ) backgroundleaf->Draw(); */ fCanvas->Update(); - TString fname = fDataset+Form("/plots/%s_%i", fMethName.Data(), itree ); + TString fname = fDataset + TString::Format("/plots/%s_%i", fMethName.Data(), itree); std::cout << "--- Creating image: " << fname << std::endl; - TMVAGlob::imgconv( fCanvas, fname ); + TMVAGlob::imgconv( fCanvas, fname ); TMVAStyle->SetCanvasColor( canvasColor ); -} - +} + // ======================================================================================== // intermediate GUI @@ -368,10 +368,10 @@ void TMVA::BDT_Reg(TString dataset, const TString& fin ) // --- read the available BDT weight files // destroy all open cavases - TMVAGlob::DestroyCanvases(); + TMVAGlob::DestroyCanvases(); // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); TDirectory* dir = file->GetDirectory(dataset.Data())->GetDirectory( "Method_BDT" ); if (!dir) { @@ -381,14 +381,14 @@ void TMVA::BDT_Reg(TString dataset, const TString& fin ) // read all directories TIter next( dir->GetListOfKeys() ); - TKey *key(0); - std::vector methname; - std::vector path; - std::vector wfile; + TKey *key(0); + std::vector methname; + std::vector path; + std::vector wfile; while ((key = (TKey*)next())) { TDirectory* mdir = dir->GetDirectory( key->GetName() ); if (!mdir) { - std::cout << "*** Error in macro \"BDT_Reg.C\": cannot find sub-directory: " << key->GetName() + std::cout << "*** Error in macro \"BDT_Reg.C\": cannot find sub-directory: " << key->GetName() << " in directory: " << dir->GetName() << std::endl; return; } @@ -415,15 +415,15 @@ void TMVA::BDT_Reg(TString dataset, const TString& fin ) TString fname = path[im]; if (fname[fname.Length()-1] != '/') fname += "/"; fname += wfile[im]; - TString macro = Form( "TMVA::BDT_Reg(\"%s\",0,\"%s\",\"%s\")",dataset.Data(), fname.Data(), methname[im].Data() ); + TString macro = TString::Format( "TMVA::BDT_Reg(\"%s\",0,\"%s\",\"%s\")",dataset.Data(), fname.Data(), methname[im].Data() ); cbar->AddButton( fname, macro, "Plot decision trees from this weight file", "button" ); } - // set the style + // set the style cbar->SetTextColor("blue"); // draw - cbar->Show(); + cbar->Show(); } void TMVA::BDTReg_DeleteTBar(int i) @@ -438,11 +438,11 @@ void TMVA::BDTReg_DeleteTBar(int i) // input: - No. of tree // - the weight file from which the tree is read -void TMVA::BDT_Reg(TString dataset, Int_t itree, TString wfile , TString methName, Bool_t useTMVAStyle ) +void TMVA::BDT_Reg(TString dataset, Int_t itree, TString wfile , TString methName, Bool_t useTMVAStyle ) { // destroy possibly existing dialog windows and/or canvases StatDialogBDTReg::Delete(); - TMVAGlob::DestroyCanvases(); + TMVAGlob::DestroyCanvases(); if(wfile=="") wfile = dataset+"/weights/TMVARegression_BDT.weights.xml"; diff --git a/tmva/tmvagui/src/BoostControlPlots.cxx b/tmva/tmvagui/src/BoostControlPlots.cxx index e6a80479d6599..347db1211f05f 100644 --- a/tmva/tmvagui/src/BoostControlPlots.cxx +++ b/tmva/tmvagui/src/BoostControlPlots.cxx @@ -44,7 +44,7 @@ void TMVA::boostcontrolplots(TString dataset, TDirectory *boostdir ) { char cn[100]; const TString titName = boostdir->GetName(); snprintf( cn, 100, "cv_%s", titName.Data() ); - TCanvas *c = new TCanvas( cn, Form( "%s Control Plots", titName.Data() ), + TCanvas *c = new TCanvas( cn, TString::Format( "%s Control Plots", titName.Data() ), width, height ); c->Divide(2,4); @@ -132,7 +132,7 @@ void TMVA::boostcontrolplots(TString dataset, TDirectory *boostdir ) { } // write to file - TString fname = dataset+Form( "/plots/%s_ControlPlots", titName.Data() ); + TString fname = dataset+TString::Format( "/plots/%s_ControlPlots", titName.Data() ); TMVAGlob::imgconv( c, fname ); } diff --git a/tmva/tmvagui/src/CorrGui.cxx b/tmva/tmvagui/src/CorrGui.cxx index ca0c5a3dbfb56..1909c768b1837 100644 --- a/tmva/tmvagui/src/CorrGui.cxx +++ b/tmva/tmvagui/src/CorrGui.cxx @@ -83,9 +83,9 @@ void TMVA::CorrGui(TString dataset, TString fin, TString dirName , TString titl for (Int_t ic=0;icAddButton( (Var[ic].Contains("_target") ? - Form( " Target: %s ", Var[ic].ReplaceAll("_target","").Data()) : - Form( " Variable: %s ", Var[ic].Data())), - Form( "TMVA::correlationscatters(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%i)",dataset.Data(),fin.Data(), Var[ic].Data(), dirName.Data(), title.Data(), (Int_t)isRegression ), + TString::Format( " Target: %s ", Var[ic].ReplaceAll("_target","").Data()) : + TString::Format( " Variable: %s ", Var[ic].Data())), + TString::Format( "TMVA::correlationscatters(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%i)",dataset.Data(),fin.Data(), Var[ic].Data(), dirName.Data(), title.Data(), (Int_t)isRegression ), buttonType ); } diff --git a/tmva/tmvagui/src/CorrGuiMultiClass.cxx b/tmva/tmvagui/src/CorrGuiMultiClass.cxx index 724609f55afa5..8fb0ae93662ee 100644 --- a/tmva/tmvagui/src/CorrGuiMultiClass.cxx +++ b/tmva/tmvagui/src/CorrGuiMultiClass.cxx @@ -49,8 +49,8 @@ void TMVA::CorrGuiMultiClass(TString dataset, TString fin , TString dirName , T std::vector::const_iterator iter = names.begin(); for (; iter != names.end(); ++iter) { - cbar->AddButton( Form( " Variable: %s ", (*iter).Data()), - Form( "TMVA::correlationscattersMultiClass(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%i)", + cbar->AddButton( TString::Format( " Variable: %s ", (*iter).Data()), + TString::Format( "TMVA::correlationscattersMultiClass(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%i)", dataset.Data(), fin.Data(), (*iter).Data(), dirName.Data(), title.Data(), (Int_t)isRegression ), buttonType ); } diff --git a/tmva/tmvagui/src/MovieMaker.cxx b/tmva/tmvagui/src/MovieMaker.cxx index cdbdeb9ccbede..e996c5189a060 100644 --- a/tmva/tmvagui/src/MovieMaker.cxx +++ b/tmva/tmvagui/src/MovieMaker.cxx @@ -51,7 +51,7 @@ void TMVA::DrawNetworkMovie(TString dataset, TFile* file, const TString& methodT epochList.push_back( es ); // create bulk file name - TString bulkname = Form( "epochmonitoring___epoch_%s_weights_hist", es.Data() ); + TString bulkname = TString::Format( "epochmonitoring___epoch_%s_weights_hist", es.Data() ); // draw the network if (ic <= 60) draw_network(dataset, file, epochDir, bulkname, kTRUE, es ); @@ -106,11 +106,11 @@ void TMVA::DrawMLPoutputMovie(TString dataset, TFile* file, const TString& metho // create canvas countCanvas++; - TString ctitle = Form("TMVA response %s",methodTitle.Data()); - c = new TCanvas( Form("canvas%d", countCanvas), ctitle, 0, 0, width, (Int_t)width*0.78 ); + TString ctitle = TString::Format("TMVA response %s",methodTitle.Data()); + c = new TCanvas( TString::Format("canvas%d", countCanvas), ctitle, 0, 0, width, (Int_t)width*0.78 ); TH1F* sig = (TH1F*)titkeyTit->ReadObj(); - sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) ); + sig->SetTitle( TString::Format("TMVA response for classifier: %s", methodTitle.Data()) ); TString dataType = (name.Contains("_train_") ? "(training sample)" : "(test sample)"); @@ -186,7 +186,7 @@ void TMVA::DrawMLPoutputMovie(TString dataset, TFile* file, const TString& metho t.SetTextSize( 0.04 ); t.SetTextColor( 1 ); t.SetTextAlign( 31 ); - t.DrawTextNDC( 1 - c->GetRightMargin(), 1 - c->GetTopMargin() + 0.015, Form( "Epoch: %i", epoch) ); + t.DrawTextNDC( 1 - c->GetRightMargin(), 1 - c->GetTopMargin() + 0.015, TString::Format( "Epoch: %i", epoch) ); // overlay signal and background histograms sig->Draw("samehist"); diff --git a/tmva/tmvagui/src/PlotFoams.cxx b/tmva/tmvagui/src/PlotFoams.cxx index 03abe870f8bc8..bfa89da0892f0 100644 --- a/tmva/tmvagui/src/PlotFoams.cxx +++ b/tmva/tmvagui/src/PlotFoams.cxx @@ -27,15 +27,15 @@ void TMVA::PlotFoams( TString fileName, TControlBar* cbar = new TControlBar( "vertical", "Choose cell value for plot:", 50, 50 ); if ((gDirectory->Get("SignalFoam") && gDirectory->Get("BgFoam")) || gDirectory->Get("MultiTargetRegressionFoam")) { - TString macro = Form( "TMVA::Plot(\"%s\",%s, \"Event density\", %s)", + TString macro = TString::Format( "TMVA::Plot(\"%s\",%s, \"Event density\", %s)", fileName.Data(), "TMVA::kValueDensity", (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Event density", macro, "Plot event density", "button" ); } else if (gDirectory->Get("DiscrFoam") || gDirectory->Get("MultiClassFoam0")){ - TString macro = Form( "TMVA::Plot(\"%s\", %s, \"Discriminator\", %s)", + TString macro = TString::Format( "TMVA::Plot(\"%s\", %s, \"Discriminator\", %s)", fileName.Data(), "TMVA::kValue", (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Discriminator", macro, "Plot discriminator", "button" ); } else if (gDirectory->Get("MonoTargetRegressionFoam")){ - TString macro = Form( "TMVA::Plot(\"%s\", %s, \"Target\", %s)", + TString macro = TString::Format( "TMVA::Plot(\"%s\", %s, \"Target\", %s)", fileName.Data(), "TMVA::kValue", (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Target", macro, "Plot target", "button" ); } else { @@ -43,13 +43,13 @@ void TMVA::PlotFoams( TString fileName, return; } - TString macro_rms = Form( "TMVA::Plot(\"%s\", %s, \"Variance\", %s)", + TString macro_rms = TString::Format( "TMVA::Plot(\"%s\", %s, \"Variance\", %s)", fileName.Data(), "TMVA::kRms", (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Variance", macro_rms, "Plot variance", "button" ); - TString macro_rms_ov_mean = Form( "TMVA::Plot(\"%s\", %s, \"Variance/Mean\", %s)", + TString macro_rms_ov_mean = TString::Format( "TMVA::Plot(\"%s\", %s, \"Variance/Mean\", %s)", fileName.Data(), "TMVA::kRmsOvMean", (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Variance/Mean", macro_rms_ov_mean, "Plot variance over mean", "button" ); - TString macro_cell_tree = Form( "TMVA::PlotCellTree(\"%s\", \"Cell tree\", %s)", + TString macro_cell_tree = TString::Format( "TMVA::PlotCellTree(\"%s\", \"Cell tree\", %s)", fileName.Data(), (useTMVAStyle ? "kTRUE" : "kFALSE") ); cbar->AddButton( "Cell tree", macro_cell_tree, "Plot cell tree", "button" ); @@ -82,8 +82,8 @@ void TMVA::Plot(TString fileName, TMVA::ECellValue cv, TString cv_long, bool use } else if (MultiClassFoam0) { UInt_t cls = 0; TMVA::PDEFoam *fm = NULL; - while ((fm = (TMVA::PDEFoam*) gDirectory->Get(Form("MultiClassFoam%u", cls)))) { - foam_list.Add(new TPair(fm, new TObjString(Form("Discriminator Foam %u",cls)))); + while ((fm = (TMVA::PDEFoam*) gDirectory->Get(TString::Format("MultiClassFoam%u", cls)))) { + foam_list.Add(new TPair(fm, new TObjString(TString::Format("Discriminator Foam %u",cls)))); cls++; } } else if (MonoTargetRegressionFoam) { @@ -131,21 +131,21 @@ void TMVA::Plot1DimFoams(TList& foam_list, TMVA::ECellValue cell_value, // loop over all foams and draw the histogram TListIter it(&foam_list); - TPair* fm_pair = NULL; // the (foam, caption) pair + TPair* fm_pair = nullptr; // the (foam, caption) pair while ((fm_pair = (TPair*) it())) { TMVA::PDEFoam* foam = (TMVA::PDEFoam*) fm_pair->Key(); if (!foam) continue; TString foam_caption(((TObjString*) fm_pair->Value())->String()); TString variable_name(foam->GetVariableName(0)->String()); - canvas = new TCanvas(Form("canvas_%p",foam), + canvas = new TCanvas(TString::Format("canvas_%p",foam), "1-dimensional PDEFoam", 400, 400); projection = foam->Draw1Dim(cell_value, 100, kernel); projection->SetTitle(cell_value_description + " of " + foam_caption + ";" + variable_name); projection->Draw(); - projection->SetDirectory(0); + projection->SetDirectory(nullptr); canvas->Update(); } @@ -157,8 +157,8 @@ void TMVA::PlotNDimFoams(TList& foam_list, TMVA::ECellValue cell_value, TMVA::PDEFoamKernelBase* kernel) { // draw 2 dimensional PDEFoam projections - TCanvas* canvas = NULL; - TH2D* projection = NULL; + TCanvas* canvas = nullptr; + TH2D* projection = nullptr; // loop over all foams and draw the projection TListIter it(&foam_list); @@ -173,12 +173,12 @@ void TMVA::PlotNDimFoams(TList& foam_list, TMVA::ECellValue cell_value, for (Int_t i = 0; i < kDim; ++i) { for (Int_t k = i + 1; k < kDim; ++k) { - canvas = new TCanvas(Form("canvas_%p_%i:%i", foam, i, k), - Form("Foam projections %i:%i", i, k), + canvas = new TCanvas(TString::Format("canvas_%p_%i:%i", foam, i, k), + TString::Format("Foam projections %i:%i", i, k), (Int_t)(400/(1.-0.2)), 400); canvas->SetRightMargin(0.2); - TString title = Form("%s of %s: Projection %s:%s;%s;%s", + TString title = TString::Format("%s of %s: Projection %s:%s;%s;%s", cell_value_description.Data(), foam_caption.Data(), foam->GetVariableName(i)->String().Data(), @@ -189,7 +189,7 @@ void TMVA::PlotNDimFoams(TList& foam_list, TMVA::ECellValue cell_value, projection = foam->Project2(i, k, cell_value, kernel); projection->SetTitle(title); projection->Draw("COLZ"); - projection->SetDirectory(0); + projection->SetDirectory(nullptr); canvas->Update(); } @@ -209,8 +209,8 @@ void TMVA::PlotCellTree(TString fileName, TString cv_long, bool useTMVAStyle ) // find foams TListIter foamIter(gDirectory->GetListOfKeys()); - TKey *foam_key = NULL; // the foam key - TCanvas *canv = NULL; // the canvas + TKey *foam_key = nullptr; // the foam key + TCanvas *canv = nullptr; // the canvas while ((foam_key = (TKey*) foamIter())) { TString name(foam_key->GetName()); TString class_name(foam_key->GetClassName()); @@ -220,8 +220,8 @@ void TMVA::PlotCellTree(TString fileName, TString cv_long, bool useTMVAStyle ) // read the foam TMVA::PDEFoam *foam = (TMVA::PDEFoam*) foam_key->ReadObj(); - canv = new TCanvas(Form("canvas_%s",name.Data()), - Form("%s of %s",cv_long.Data(),name.Data()), 640, 480); + canv = new TCanvas(TString::Format("canvas_%s",name.Data()), + TString::Format("%s of %s",cv_long.Data(),name.Data()), 640, 480); canv->cd(); // get cell tree depth const UInt_t depth = foam->GetRootCell()->GetTreeDepth(); @@ -260,12 +260,12 @@ void TMVA::DrawCell( TMVA::PDEFoamCell *cell, TMVA::PDEFoam *foam, t->SetFillStyle(1); // draw all cell elements - t->AddText( Form("Intg=%.5f", cell->GetIntg()) ); - t->AddText( Form("Var=%.5f", cell->GetDriv()) ); + t->AddText( TString::Format("Intg=%.5f", cell->GetIntg()) ); + t->AddText( TString::Format("Var=%.5f", cell->GetDriv()) ); TVectorD *vec = (TVectorD*) cell->GetElement(); if (vec) { for (Int_t i = 0; i < vec->GetNrows(); ++i) - t->AddText( Form("E[%i]=%.5f", i, (*vec)[i]) ); + t->AddText( TString::Format("E[%i]=%.5f", i, (*vec)[i]) ); } if (cell->GetStat() != 1) { @@ -278,8 +278,8 @@ void TMVA::DrawCell( TMVA::PDEFoamCell *cell, TMVA::PDEFoam *foam, cell->GetHcub(cellPosi, cellSize); Int_t kBest = cell->GetBest(); // best division variable Double_t xBest = cell->GetXdiv(); // best division point - t->AddText( Form("dim=%i", kBest) ); - t->AddText( Form("cut=%.5g", foam->VarTransformInvers(kBest,cellPosi[kBest] + xBest*cellSize[kBest])) ); + t->AddText( TString::Format("dim=%i", kBest) ); + t->AddText( TString::Format("cut=%.5g", foam->VarTransformInvers(kBest,cellPosi[kBest] + xBest*cellSize[kBest])) ); } else { t->SetFillColor( TColor::GetColor("#DD0033") ); t->SetTextColor( TColor::GetColor("#FFFFFF") ); diff --git a/tmva/tmvagui/src/TMVAGui.cxx b/tmva/tmvagui/src/TMVAGui.cxx index d06affe016af1..3a7fd4faaf8e8 100644 --- a/tmva/tmvagui/src/TMVAGui.cxx +++ b/tmva/tmvagui/src/TMVAGui.cxx @@ -98,7 +98,7 @@ void TMVA::TMVAGui( const char* fName , TString dataset) { TKey *key=(TKey*)file->GetListOfKeys()->At(i); dataset=key->GetName(); - bar->AddButton(dataset.Data(),Form("TMVA::TMVAGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); + bar->AddButton(dataset.Data(), TString::Format("TMVA::TMVAGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); } bar->AddSeparator(); @@ -137,13 +137,13 @@ void TMVA::TMVAGui( const char* fName , TString dataset) char ch = 'a'; while ((str = (TObjString*)it())) { TString tmp = str->GetString(); - TString title = Form( "Input variables '%s'-transformed (training sample)", + TString title = TString::Format( "Input variables '%s'-transformed (training sample)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variables (training sample)"; ActionButton( cbar, - Form( "(%i%c) %s", ic, ch++, title.Data() ), - Form( "TMVA::variables(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), - Form( "Plots all '%s'-transformed input variables (macro variables(...))", str->GetString().Data() ), + TString::Format( "(%i%c) %s", ic, ch++, title.Data() ), + TString::Format( "TMVA::variables(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all '%s'-transformed input variables (macro variables(...))", str->GetString().Data() ), buttonType, str->GetString() ); } ic++; @@ -152,154 +152,154 @@ void TMVA::TMVAGui( const char* fName , TString dataset) it.Reset(); ch = 'a'; while ((str = (TObjString*)it())) { TString tmp = str->GetString(); - TString title = Form( "Input variable correlations '%s'-transformed (scatter profiles)", + TString title = TString::Format( "Input variable correlations '%s'-transformed (scatter profiles)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variable correlations (scatter profiles)"; ActionButton( cbar, - Form( "(%i%c) %s", ic, ch++, title.Data() ), - Form( "TMVA::CorrGui(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), - Form( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGui(...))", + TString::Format( "(%i%c) %s", ic, ch++, title.Data() ), + TString::Format( "TMVA::CorrGui(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGui(...))", str->GetString().Data() ), buttonType, str->GetString() ); } TString title; // coefficients - title =Form( "(%i) Input Variable Linear Correlation Coefficients", ++ic ); + title = TString::Format( "(%i) Input Variable Linear Correlation Coefficients", ++ic ); ActionButton( cbar, title, - Form( "TMVA::correlations(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::correlations(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots signal and background correlation summaries for all input variables (macro correlations.C)", buttonType ); - title =Form( "(%ia) Classifier Output Distributions (test sample)", ++ic ); + title =TString::Format( "(%ia) Classifier Output Distributions (test sample)", ++ic ); ActionButton( cbar, title, - Form( "TMVA::mvas(\"%s\",\"%s\", TMVA::kMVAType)",dataset.Data(), fName ), + TString::Format( "TMVA::mvas(\"%s\",\"%s\", TMVA::kMVAType)",dataset.Data(), fName ), "Plots the output of each classifier for the test data (macro mvas(...,0))", buttonType, defaultRequiredClassifier ); - title =Form( "(%ib) Classifier Output Distributions (test and training samples superimposed)", ic ); + title =TString::Format( "(%ib) Classifier Output Distributions (test and training samples superimposed)", ic ); ActionButton( cbar, title, - Form( "TMVA::mvas(\"%s\",\"%s\", TMVA::kCompareType )",dataset.Data(), fName), + TString::Format( "TMVA::mvas(\"%s\",\"%s\", TMVA::kCompareType )",dataset.Data(), fName), "Plots the output of each classifier for the test (histograms) and training (dots) data (macro mvas(...,3))", buttonType, defaultRequiredClassifier ); - title = Form( "(%ic) Classifier Probability Distributions (test sample)", ic ); + title = TString::Format( "(%ic) Classifier Probability Distributions (test sample)", ic ); ActionButton( cbar, title, - Form( "TMVA::mvas(\"%s\",\"%s\", TMVA::kProbaType)",dataset.Data(), fName ), + TString::Format( "TMVA::mvas(\"%s\",\"%s\", TMVA::kProbaType)",dataset.Data(), fName ), "Plots the probability of each classifier for the test data (macro mvas(...,1))", buttonType, defaultRequiredClassifier ); - title =Form( "(%id) Classifier Rarity Distributions (test sample)", ic ); + title =TString::Format( "(%id) Classifier Rarity Distributions (test sample)", ic ); ActionButton( cbar, title, - Form( "TMVA::mvas(\"%s\",\"%s\", TMVA::kRarityType)",dataset.Data(), fName ), + TString::Format( "TMVA::mvas(\"%s\",\"%s\", TMVA::kRarityType)",dataset.Data(), fName ), "Plots the Rarity of each classifier for the test data (macro mvas(...,2)) - background distribution should be uniform", buttonType, defaultRequiredClassifier ); - title =Form( "(%ia) Classifier Cut Efficiencies", ++ic ); + title =TString::Format( "(%ia) Classifier Cut Efficiencies", ++ic ); ActionButton( cbar, title, - Form( "TMVA::mvaeffs(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::mvaeffs(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots signal and background efficiencies versus cut on classifier output (macro mvaeffs.cxx)", buttonType, defaultRequiredClassifier ); - title = Form( "(%ib) Classifier Background Rejection vs Signal Efficiency (ROC curve)", ic ); + title = TString::Format( "(%ib) Classifier Background Rejection vs Signal Efficiency (ROC curve)", ic ); ActionButton( cbar, title, - Form( "TMVA::efficiencies(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::efficiencies(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots background rejection vs signal efficiencies (macro efficiencies.cxx) [\"ROC\" stands for \"Receiver Operation Characteristics\"]", buttonType, defaultRequiredClassifier ); - title = Form( "(%ib) Classifier 1/(Backgr. Efficiency) vs Signal Efficiency (ROC curve)", ic ); + title = TString::Format( "(%ib) Classifier 1/(Backgr. Efficiency) vs Signal Efficiency (ROC curve)", ic ); ActionButton( cbar, title, - Form( "TMVA::efficiencies(\"%s\",\"%s\",%d)",dataset.Data(), fName, 3 ), + TString::Format( "TMVA::efficiencies(\"%s\",\"%s\",%d)",dataset.Data(), fName, 3 ), "Plots 1/(background eff.) vs signal efficiencies (macro efficiencies.cxx) [\"ROC\" stands for \"Receiver Operation Characteristics\"]", buttonType, defaultRequiredClassifier ); - title = Form( "(%i) Parallel Coordinates (requires ROOT-version >= 5.17)", ++ic ); + title = TString::Format( "(%i) Parallel Coordinates (requires ROOT-version >= 5.17)", ++ic ); ActionButton( cbar, title, - Form( "TMVA::paracoor(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::paracoor(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots parallel coordinates for classifiers and input variables (macro paracoor.cxx, requires ROOT >= 5.17)", buttonType, defaultRequiredClassifier ); - title =Form( "(%i) PDFs of Classifiers (requires \"CreateMVAPdfs\" option set)", ++ic ); + title =TString::Format( "(%i) PDFs of Classifiers (requires \"CreateMVAPdfs\" option set)", ++ic ); ActionButton( cbar, title, - Form( "TMVA::probas(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::probas(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots the PDFs of the classifier output distributions for signal and background - if requested (macro probas.cxx)", buttonType, defaultRequiredClassifier ); - title = Form( "(%i) Training History", ++ic ); + title = TString::Format( "(%i) Training History", ++ic ); ActionButton( cbar, title, - Form( "TMVA::training_history(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::training_history(\"%s\",\"%s\")",dataset.Data(), fName ), "Plot training history of classifiers with multiple passed (eg Neural Networks) ", buttonType, defaultRequiredClassifier ); - title = Form( "(%i) Likelihood Reference Distributiuons", ++ic); + title = TString::Format( "(%i) Likelihood Reference Distributiuons", ++ic); ActionButton( cbar, title, - Form( "TMVA::likelihoodrefs(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::likelihoodrefs(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots to verify the likelihood reference distributions (macro likelihoodrefs.cxx)", buttonType, "Likelihood" ); - title = Form( "(%ia) Network Architecture (MLP)", ++ic ); - TString call = Form( "TMVA::network(\"%s\",\"%s\")", dataset.Data(),fName ); + title = TString::Format( "(%ia) Network Architecture (MLP)", ++ic ); + TString call = TString::Format( "TMVA::network(\"%s\",\"%s\")", dataset.Data(),fName ); ActionButton( cbar, title, call, "Plots the MLP weights (macro network.cxx)", buttonType, "MLP" ); - title = Form( "(%ib) Network Convergence Test (MLP)", ic ); + title = TString::Format( "(%ib) Network Convergence Test (MLP)", ic ); ActionButton( cbar, title, - Form( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots error estimator versus training epoch for training and test samples (macro annconvergencetest.C)", buttonType, "MLP" ); - title = Form( "(%i) Decision Trees (BDT)", ++ic ); + title = TString::Format( "(%i) Decision Trees (BDT)", ++ic ); ActionButton( cbar, title, - Form( "TMVA::BDT(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "TMVA::BDT(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots the Decision Trees trained by BDT algorithms (macro BDT(itree,...))", buttonType, "BDT" ); - title = Form( "(%i) Decision Tree Control Plots (BDT)", ++ic ); + title = TString::Format( "(%i) Decision Tree Control Plots (BDT)", ++ic ); ActionButton( cbar, title, - Form( "TMVA::BDTControlPlots(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "TMVA::BDTControlPlots(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots to monitor boosting and pruning of decision trees (macro BDTControlPlots.cxx)", buttonType, "BDT" ); // ActionButton( cbar, - // Form( "(%i) Rule Ensemble Importance Plots (RuleFit)", ++ic ), - // Form( "TMVA::rulevis(\"%s\",0)", fName ), + // TString::Format( "(%i) Rule Ensemble Importance Plots (RuleFit)", ++ic ), + // TString::Format( "TMVA::rulevis(\"%s\",0)", fName ), // "Plots all input variables with rule ensemble weights, including linear terms (macro rulevis.cxx)", // buttonType, "RuleFit" ); - title = Form( "(%i) Plot Foams (PDEFoam)", ++ic ); + title = TString::Format( "(%i) Plot Foams (PDEFoam)", ++ic ); ActionButton( cbar, title, - Form("TMVA::PlotFoams(\"%s/weights/TMVAClassification_PDEFoam.weights_foams.root\")",dataset.Data()), + TString::Format("TMVA::PlotFoams(\"%s/weights/TMVAClassification_PDEFoam.weights_foams.root\")",dataset.Data()), "Plot Foams (macro PlotFoams.cxx)", buttonType, "PDEFoam" ); - title = Form( "(%i) General Boost Control Plots", ++ic ); + title = TString::Format( "(%i) General Boost Control Plots", ++ic ); ActionButton( cbar, title, - Form( "TMVA::BoostControlPlots(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "TMVA::BoostControlPlots(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots to monitor boosting of general classifiers (macro BoostControlPlots)", buttonType, "Boost" ); cbar->AddSeparator(); - cbar->AddButton( Form( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); + cbar->AddButton( TString::Format( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); // set the style cbar->SetTextColor("black"); diff --git a/tmva/tmvagui/src/TMVAMultiClassGui.cxx b/tmva/tmvagui/src/TMVAMultiClassGui.cxx index 376406eab10d7..7bc5ae0cbd7ca 100644 --- a/tmva/tmvagui/src/TMVAMultiClassGui.cxx +++ b/tmva/tmvagui/src/TMVAMultiClassGui.cxx @@ -100,7 +100,7 @@ void TMVA::TMVAMultiClassGui(const char* fName ,TString dataset) { TKey *key=(TKey*)file->GetListOfKeys()->At(i); dataset=key->GetName(); - bar->AddButton(dataset.Data(),Form("TMVA::TMVAMultiClassGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); + bar->AddButton(dataset.Data(),TString::Format("TMVA::TMVAMultiClassGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); } bar->AddSeparator(); @@ -110,7 +110,7 @@ void TMVA::TMVAMultiClassGui(const char* fName ,TString dataset) bar->SetTextColor("black"); bar->Show(); gROOT->SaveContext(); - return ; + return; } // find all references @@ -139,13 +139,13 @@ void TMVA::TMVAMultiClassGui(const char* fName ,TString dataset) char ch = 'a'; while ((str = (TObjString*)it())) { TString tmp = str->GetString(); - TString title = Form( "Input variables '%s'-transformed (training sample)", + TString title = TString::Format( "Input variables '%s'-transformed (training sample)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variables (training sample)"; MultiClassActionButton( cbar, - Form( "(%i%c) %s", ic, ch++, title.Data() ), - Form( "TMVA::variablesMultiClass(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), - Form( "Plots all '%s'-transformed input variables (macro variablesMultiClass(...))", str->GetString().Data() ), + TString::Format( "(%i%c) %s", ic, ch++, title.Data() ), + TString::Format( "TMVA::variablesMultiClass(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data(), fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all '%s'-transformed input variables (macro variablesMultiClass(...))", str->GetString().Data() ), buttonType, str->GetString() ); } ic++; @@ -154,162 +154,162 @@ void TMVA::TMVAMultiClassGui(const char* fName ,TString dataset) it.Reset(); ch = 'a'; while ((str = (TObjString*)it())) { TString tmp = str->GetString(); - TString title = Form( "Input variable correlations '%s'-transformed (scatter profiles)", + TString title = TString::Format( "Input variable correlations '%s'-transformed (scatter profiles)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variable correlations (scatter profiles)"; MultiClassActionButton( cbar, - Form( "(%i%c) %s", ic, ch++, title.Data() ), - Form( "TMVA::CorrGuiMultiClass(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data() , fName, str->GetString().Data(), title.Data() ), - Form( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGuiMultiClass(...))", + TString::Format( "(%i%c) %s", ic, ch++, title.Data() ), + TString::Format( "TMVA::CorrGuiMultiClass(\"%s\",\"%s\",\"%s\",\"%s\")",dataset.Data() , fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGuiMultiClass(...))", str->GetString().Data() ), buttonType, str->GetString() ); } TString title; // coefficients - title =Form( "(%i) Input Variable Linear Correlation Coefficients", ++ic ); + title =TString::Format( "(%i) Input Variable Linear Correlation Coefficients", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::correlationsMultiClass(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "TMVA::correlationsMultiClass(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots signal and background correlation summaries for all input variables (macro correlationsMultiClass.cxx)", buttonType ); - title =Form( "(%ia) Classifier Output Distributions (test sample)", ++ic ); + title =TString::Format( "(%ia) Classifier Output Distributions (test sample)", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::mvasMulticlass(\"%s\",\"%s\",TMVA::kMVAType)",dataset.Data() , fName ), + TString::Format( "TMVA::mvasMulticlass(\"%s\",\"%s\",TMVA::kMVAType)",dataset.Data() , fName ), "Plots the output of each classifier for the test data (macro mvas(...,0))", buttonType, defaultRequiredClassifier ); - title =Form( "(%ib) Classifier Output Distributions (test and training samples superimposed)", ic ); + title =TString::Format( "(%ib) Classifier Output Distributions (test and training samples superimposed)", ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::mvasMulticlass(\"%s\",\"%s\",TMVA::kCompareType)",dataset.Data(), fName ), + TString::Format( "TMVA::mvasMulticlass(\"%s\",\"%s\",TMVA::kCompareType)",dataset.Data(), fName ), "Plots the output of each classifier for the test (histograms) and training (dots) data (macro mvas(...,3))", buttonType, defaultRequiredClassifier ); /* - title = Form( "(%ic) Classifier Probability Distributions (test sample)", ic ); + title = TString::Format( "(%ic) Classifier Probability Distributions (test sample)", ic ); MultiClassActionButton( cbar, - Form( "(%ic) Classifier Probability Distributions (test sample)", ic ), - Form( "TMVA::mvas(\"%s\",TMVA::kProbaType)", fName ), + TString::Format( "(%ic) Classifier Probability Distributions (test sample)", ic ), + TString::Format( "TMVA::mvas(\"%s\",TMVA::kProbaType)", fName ), "Plots the probability of each classifier for the test data (macro mvas(...,1))", buttonType, defaultRequiredClassifier ); - title =Form( "(%id) Classifier Rarity Distributions (test sample)", ic ); + title =TString::Format( "(%id) Classifier Rarity Distributions (test sample)", ic ); MultiClassActionButton( cbar, - Form( "(%id) Classifier Rarity Distributions (test sample)", ic ), - Form( "TMVA::mvas(\"%s\",TMVA::kRarityType)", fName ), + TString::Format( "(%id) Classifier Rarity Distributions (test sample)", ic ), + TString::Format( "TMVA::mvas(\"%s\",TMVA::kRarityType)", fName ), "Plots the Rarity of each classifier for the test data (macro mvas(...,2)) - background distribution should be uniform", buttonType, defaultRequiredClassifier ); - title =Form( "(%ia) Classifier Cut Efficiencies", ++ic ); + title =TString::Format( "(%ia) Classifier Cut Efficiencies", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::mvaeffs(\"%s\")", fName ), + TString::Format( "TMVA::mvaeffs(\"%s\")", fName ), "Plots signal and background efficiencies versus cut on classifier output (macro mvaeffs.cxx)", buttonType, defaultRequiredClassifier ); */ - title = Form("(%i) Classifier Backgr. Rej. vs Sig. Eff. (1-vs-rest ROC curves)", ++ic); + title = TString::Format("(%i) Classifier Backgr. Rej. vs Sig. Eff. (1-vs-rest ROC curves)", ++ic); MultiClassActionButton( - cbar, title, Form("TMVA::efficienciesMulticlass1vsRest(\"%s\", \"%s\")", dataset.Data(), fName), + cbar, title, TString::Format("TMVA::efficienciesMulticlass1vsRest(\"%s\", \"%s\")", dataset.Data(), fName), "Plots background rejection vs signal efficiencies (macro efficienciesMulticlass.cxx) [\"ROC\" stands " "for \"Receiver Operation Characteristics\"]", buttonType, defaultRequiredClassifier); - // title = Form("(%i) Classifier (1/Backgr. Rejection) vs Sig. Eff. (1-vs-rest ROC curve)", ++ic); - // MultiClassActionButton(cbar, title, Form("TMVA::efficienciesMulticlass(\"%s\", \"%s\")", dataset.Data(), fName), + // title = TString::Format("(%i) Classifier (1/Backgr. Rejection) vs Sig. Eff. (1-vs-rest ROC curve)", ++ic); + // MultiClassActionButton(cbar, title, TString::Format("TMVA::efficienciesMulticlass(\"%s\", \"%s\")", dataset.Data(), fName), // "Plots background rejection vs signal efficiencies (macro efficiencies.cxx) [\"ROC\" stands // " // "for \"Receiver Operation Characteristics\"]", // buttonType, defaultRequiredClassifier); - title = Form("(%i) Classifier Backgr. Rej. vs Sig. Eff. (1-vs-1 ROC curves)", ++ic); + title = TString::Format("(%i) Classifier Backgr. Rej. vs Sig. Eff. (1-vs-1 ROC curves)", ++ic); MultiClassActionButton( - cbar, title, Form("TMVA::efficienciesMulticlass1vs1(\"%s\", \"%s\")", dataset.Data(), fName), + cbar, title, TString::Format("TMVA::efficienciesMulticlass1vs1(\"%s\", \"%s\")", dataset.Data(), fName), "Plots background rejection vs signal efficiencies (macro efficienciesMulticlass.cxx) [\"ROC\" stands " "for \"Receiver Operation Characteristics\"]", buttonType, defaultRequiredClassifier); - // title = Form("(%i) Classifier (1/Backgr. Rejection) vs Sig. Eff. (1-vs-1 ROC curve)", ++ic); - // MultiClassActionButton(cbar, title, Form("TMVA::efficienciesMulticlass(\"%s\", \"%s\")", dataset.Data(), fName), + // title = TString::Format("(%i) Classifier (1/Backgr. Rejection) vs Sig. Eff. (1-vs-1 ROC curve)", ++ic); + // MultiClassActionButton(cbar, title, TString::Format("TMVA::efficienciesMulticlass(\"%s\", \"%s\")", dataset.Data(), fName), // "Plots background rejection vs signal efficiencies (macro efficiencies.cxx) [\"ROC\" stands // " // "for \"Receiver Operation Characteristics\"]", // buttonType, defaultRequiredClassifier); /* - title = Form( "(%i) Parallel Coordinates (requires ROOT-version >= 5.17)", ++ic ); + title = TString::Format( "(%i) Parallel Coordinates (requires ROOT-version >= 5.17)", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::paracoor(\"%s\")", fName ), + TString::Format( "TMVA::paracoor(\"%s\")", fName ), "Plots parallel coordinates for classifiers and input variables (macro paracoor.cxx, requires ROOT >= 5.17)", buttonType, defaultRequiredClassifier ); - title =Form( "(%i) PDFs of Classifiers (requires \"CreateMVAPdfs\" option set)", ++ic ); + title =TString::Format( "(%i) PDFs of Classifiers (requires \"CreateMVAPdfs\" option set)", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::probas(\"%s\")", fName ), + TString::Format( "TMVA::probas(\"%s\")", fName ), "Plots the PDFs of the classifier output distributions for signal and background - if requested (macro probas.cxx)", buttonType, defaultRequiredClassifier ); - title = Form( "(%i) Likelihood Reference Distributiuons", ++ic); + title = TString::Format( "(%i) Likelihood Reference Distributiuons", ++ic); MultiClassActionButton( cbar, title, - Form( "TMVA::likelihoodrefs(\"%s\")", fName ), + TString::Format( "TMVA::likelihoodrefs(\"%s\")", fName ), "Plots to verify the likelihood reference distributions (macro likelihoodrefs.cxx)", buttonType, "Likelihood" ); */ - title = Form( "(%ia) Network Architecture (MLP)", ++ic ); - TString call = Form( "TMVA::network(\"%s\",\"%s\")",dataset.Data() , fName ); + title = TString::Format( "(%ia) Network Architecture (MLP)", ++ic ); + TString call = TString::Format( "TMVA::network(\"%s\",\"%s\")",dataset.Data() , fName ); MultiClassActionButton( cbar, title, call, "Plots the MLP weights (macro network.cxx)", buttonType, "MLP" ); - title = Form( "(%ib) Network Convergence Test (MLP)", ic ); + title = TString::Format( "(%ib) Network Convergence Test (MLP)", ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots error estimator versus training epoch for training and test samples (macro annconvergencetest.cxx)", buttonType, "MLP" ); - title = Form( "(%i) Decision Trees (BDT)", ++ic ); + title = TString::Format( "(%i) Decision Trees (BDT)", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::BDT(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "TMVA::BDT(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots the Decision Trees trained by BDT algorithms (macro BDT(itree,...))", buttonType, "BDT" ); /* - title = Form( "(%i) Decision Tree Control Plots (BDT)", ++ic ); + title = TString::Format( "(%i) Decision Tree Control Plots (BDT)", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::BDTControlPlots(\"%s\")", fName ), + TString::Format( "TMVA::BDTControlPlots(\"%s\")", fName ), "Plots to monitor boosting and pruning of decision trees (macro BDTControlPlots.cxx)", buttonType, "BDT" ); */ - title = Form( "(%i) Plot Foams (PDEFoam)", ++ic ); + title = TString::Format( "(%i) Plot Foams (PDEFoam)", ++ic ); MultiClassActionButton( cbar, title, - Form("TMVA::PlotFoams(\"%s/weights/TMVAMulticlass_PDEFoam.weights_foams.root\")",dataset.Data()), + TString::Format("TMVA::PlotFoams(\"%s/weights/TMVAMulticlass_PDEFoam.weights_foams.root\")",dataset.Data()), "Plot Foams (macro PlotFoams.cxx)", buttonType, "PDEFoam" ); /* - title = Form( "(%i) General Boost Control Plots", ++ic ); + title = TString::Format( "(%i) General Boost Control Plots", ++ic ); MultiClassActionButton( cbar, title, - Form( "TMVA::BoostControlPlots(\"%s\")", fName ), + TString::Format( "TMVA::BoostControlPlots(\"%s\")", fName ), "Plots to monitor boosting of general classifiers (macro BoostControlPlots.cxx)", buttonType, "Boost" ); */ cbar->AddSeparator(); - cbar->AddButton( Form( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); + cbar->AddButton( TString::Format( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); // set the style cbar->SetTextColor("black"); diff --git a/tmva/tmvagui/src/TMVARegGui.cxx b/tmva/tmvagui/src/TMVARegGui.cxx index 7a2e71ea03a11..6b39705a1763f 100644 --- a/tmva/tmvagui/src/TMVARegGui.cxx +++ b/tmva/tmvagui/src/TMVARegGui.cxx @@ -96,7 +96,7 @@ void TMVA::TMVARegGui( const char* fName ,TString dataset) { TKey *key=(TKey*)file->GetListOfKeys()->At(i); dataset=key->GetName(); - bar->AddButton(dataset.Data(),Form("TMVA::TMVARegGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); + bar->AddButton(dataset.Data(),TString::Format("TMVA::TMVARegGui(\"%s\",\"%s\")",fName,dataset.Data()),dataset.Data()); } bar->AddSeparator(); @@ -122,7 +122,7 @@ void TMVA::TMVARegGui( const char* fName ,TString dataset) // create the control bar TControlBar* cbar = new TControlBar( "vertical", "TMVA Plotting Macros for Regression", 0, 0 ); - const TString buttonType( "button" ); + const TString buttonType = "button"; // configure buttons Int_t ic = 1; @@ -130,17 +130,17 @@ void TMVA::TMVARegGui( const char* fName ,TString dataset) // find all input variables types TList* keylist = RegGuiGetKeyList( "InputVariables" ); TListIter it( keylist ); - TObjString* str = 0; + TObjString* str = nullptr; char ch = 'a'; while ( (str = (TObjString*)it()) ) { TString tmp = str->GetString(); - TString title = Form( "Input variables and target(s) '%s'-transformed (training sample)", + TString title = TString::Format( "Input variables and target(s) '%s'-transformed (training sample)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variables and target(s) (training sample)"; RegGuiActionButton( cbar, - Form( " (%i%c) %s ", ic, ch++, title.Data() ), - Form( "TMVA::variables(\"%s\",\"%s\",\"%s\",\"%s\",kTRUE)",dataset.Data() , fName, str->GetString().Data(), title.Data() ), - Form( "Plots all '%s'-transformed input variables and target(s) (macro variables(...))", + TString::Format( " (%i%c) %s ", ic, ch++, title.Data() ), + TString::Format( "TMVA::variables(\"%s\",\"%s\",\"%s\",\"%s\",kTRUE)",dataset.Data() , fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all '%s'-transformed input variables and target(s) (macro variables(...))", str->GetString().Data() ), buttonType, str->GetString() ); } @@ -150,87 +150,87 @@ void TMVA::TMVARegGui( const char* fName ,TString dataset) it.Reset(); ch = 'a'; while ( (str = (TObjString*)it()) ) { TString tmp = str->GetString(); - TString title = Form( "Input variable correlations '%s'-transformed (scatter profiles)", + TString title = TString::Format( "Input variable correlations '%s'-transformed (scatter profiles)", tmp.ReplaceAll("InputVariables_","").Data() ); if (tmp.Contains( "Id" )) title = "Input variable correlations (scatter profiles)"; RegGuiActionButton( cbar, - Form( "(%i%c) %s", ic, ch++, title.Data() ), - Form( "TMVA::CorrGui(\"%s\",\"%s\",\"%s\",\"%s\",kTRUE)",dataset.Data() , fName, str->GetString().Data(), title.Data() ), - Form( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGui(...))", + TString::Format( "(%i%c) %s", ic, ch++, title.Data() ), + TString::Format( "TMVA::CorrGui(\"%s\",\"%s\",\"%s\",\"%s\",kTRUE)",dataset.Data() , fName, str->GetString().Data(), title.Data() ), + TString::Format( "Plots all correlation profiles between '%s'-transformed input variables (macro CorrGui(...))", str->GetString().Data() ), buttonType, str->GetString() ); } // coefficients RegGuiActionButton( cbar, - Form( "(%i) Input Variable Linear Correlation Coefficients", ++ic ), - Form( "TMVA::correlations(\"%s\",\"%s\",kTRUE)",dataset.Data(), fName ), + TString::Format( "(%i) Input Variable Linear Correlation Coefficients", ++ic ), + TString::Format( "TMVA::correlations(\"%s\",\"%s\",kTRUE)",dataset.Data(), fName ), "Plots signal and background correlation summaries for all input variables (macro correlations.cxx)", buttonType ); RegGuiActionButton( cbar, - Form( "(%ia) Regression Output Deviation versus Target (test sample)", ++ic ), - Form( "TMVA::deviations(\"%s\",\"%s\",TMVA::kMVAType,kTRUE)",dataset.Data(), fName ), + TString::Format( "(%ia) Regression Output Deviation versus Target (test sample)", ++ic ), + TString::Format( "TMVA::deviations(\"%s\",\"%s\",TMVA::kMVAType,kTRUE)",dataset.Data(), fName ), "Plots the deviation between regression output and target versus target on test data (macro deviations(...,0))", buttonType, defaultRequiredClassifier ); RegGuiActionButton( cbar, - Form( "(%ib) Regression Output Deviation versus Target (training sample)", ic ), - Form( "TMVA::deviations(\"%s\",\"%s\",TMVA::kCompareType,kTRUE)",dataset.Data() , fName ), + TString::Format( "(%ib) Regression Output Deviation versus Target (training sample)", ic ), + TString::Format( "TMVA::deviations(\"%s\",\"%s\",TMVA::kCompareType,kTRUE)",dataset.Data() , fName ), "Plots the deviation between regression output and target versus target on test data (macro deviations(...,0))", buttonType, defaultRequiredClassifier ); RegGuiActionButton( cbar, - Form( "(%ic) Regression Output Deviation versus Input Variables (test sample)", ic ), - Form( "TMVA::deviations(\"%s\",\"%s\",TMVA::kMVAType,kFALSE)",dataset.Data(), fName ), + TString::Format( "(%ic) Regression Output Deviation versus Input Variables (test sample)", ic ), + TString::Format( "TMVA::deviations(\"%s\",\"%s\",TMVA::kMVAType,kFALSE)",dataset.Data(), fName ), "Plots the deviation between regression output and target versus target on test data (macro deviations(...,0))", buttonType, defaultRequiredClassifier ); RegGuiActionButton( cbar, - Form( " (%id) Regression Output Deviation versus Input Variables (training sample) ", ic ), - Form( "TMVA::deviations(\"%s\",\"%s\",TMVA::kCompareType,kFALSE)",dataset.Data() , fName ), + TString::Format( " (%id) Regression Output Deviation versus Input Variables (training sample) ", ic ), + TString::Format( "TMVA::deviations(\"%s\",\"%s\",TMVA::kCompareType,kFALSE)",dataset.Data() , fName ), "Plots the deviation between regression output and target versus target on test data (macro deviations(...,0))", buttonType, defaultRequiredClassifier ); RegGuiActionButton( cbar, - Form( "(%i) Summary of Average Regression Deviations ", ++ic ), - Form( "TMVA::regression_averagedevs(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "(%i) Summary of Average Regression Deviations ", ++ic ), + TString::Format( "TMVA::regression_averagedevs(\"%s\",\"%s\")",dataset.Data() , fName ), "Plot Summary of average deviations: MVAvalue - target (macro regression_averagedevs.cxx)", buttonType ); RegGuiActionButton( cbar, - Form( "(%ia) Network Architecture", ++ic ), - Form( "TMVA::network(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "(%ia) Network Architecture", ++ic ), + TString::Format( "TMVA::network(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots the MLP weights (macro network.cxx)", buttonType, "MLP" ); RegGuiActionButton( cbar, - Form( "(%ib) Network Convergence Test", ic ), - Form( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "(%ib) Network Convergence Test", ic ), + TString::Format( "TMVA::annconvergencetest(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots error estimator versus training epoch for training and test samples (macro annconvergencetest.cxx)", buttonType, "MLP" ); RegGuiActionButton( cbar, - Form( "(%i) Plot Foams", ++ic ), - Form("TMVA::PlotFoams(\"%s/weights/TMVARegression_PDEFoam.weights_foams.root\")",dataset.Data()), + TString::Format( "(%i) Plot Foams", ++ic ), + TString::Format("TMVA::PlotFoams(\"%s/weights/TMVARegression_PDEFoam.weights_foams.root\")",dataset.Data()), "Plot Foams (macro PlotFoams.cxx)", buttonType, "PDEFoam" ); RegGuiActionButton( cbar, - Form( "(%i) Regression Trees (BDT)", ++ic ), - Form( "TMVA::BDT_Reg(\"%s\",\"%s\")",dataset.Data() , fName ), + TString::Format( "(%i) Regression Trees (BDT)", ++ic ), + TString::Format( "TMVA::BDT_Reg(\"%s\",\"%s\")",dataset.Data() , fName ), "Plots the Regression Trees trained by BDT algorithms (macro BDT_Reg(itree,...))", buttonType, "BDT" ); RegGuiActionButton( cbar, - Form( "(%i) Regression Tree Control Plots (BDT)", ++ic ), - Form( "TMVA::BDTControlPlots(\"%s\",\"%s\")",dataset.Data(), fName ), + TString::Format( "(%i) Regression Tree Control Plots (BDT)", ++ic ), + TString::Format( "TMVA::BDTControlPlots(\"%s\",\"%s\")",dataset.Data(), fName ), "Plots to monitor boosting and pruning of regression trees (macro BDTControlPlots.cxx)", buttonType, "BDT" ); cbar->AddSeparator(); - cbar->AddButton( Form( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); + cbar->AddButton( TString::Format( "(%i) Quit", ++ic ), ".q", "Quit", buttonType ); // set the style cbar->SetTextColor("black"); diff --git a/tmva/tmvagui/src/annconvergencetest.cxx b/tmva/tmvagui/src/annconvergencetest.cxx index 159799aabbd4a..e5e74924b3c07 100644 --- a/tmva/tmvagui/src/annconvergencetest.cxx +++ b/tmva/tmvagui/src/annconvergencetest.cxx @@ -1,10 +1,10 @@ #include "TMVA/annconvergencetest.h" -// this macro serves to assess the convergence of the MLP ANN. +// this macro serves to assess the convergence of the MLP ANN. // It compares the error estimator for the training and testing samples. -// If overtraining occurred, the estimator for the training sample should -// monotoneously decrease, while the estimator of the testing sample should +// If overtraining occurred, the estimator for the training sample should +// monotoneously decrease, while the estimator of the testing sample should // show a minimum after which it increases. // input: - Input file (result from TMVA), @@ -15,9 +15,10 @@ void TMVA::annconvergencetest(TString dataset, TDirectory *lhdir ) TString jobName = lhdir->GetName(); static int icanvas = -1; icanvas++; - TCanvas* c = new TCanvas( Form("MLPConvergenceTest_%s",jobName.Data()), Form("MLP Convergence Test, %s",jobName.Data()), + TCanvas* c = new TCanvas( TString::Format("MLPConvergenceTest_%s",jobName.Data()), + TString::Format("MLP Convergence Test, %s",jobName.Data()), 100 + (icanvas)*40, 0 + (icanvas+1)*20, 600, 580*0.8 ); - + TH1* estimatorHistTrain = (TH1*)lhdir->Get( "estimatorHistTrain" ); TH1* estimatorHistTest = (TH1*)lhdir->Get( "estimatorHistTest" ); @@ -32,7 +33,7 @@ void TMVA::annconvergencetest(TString dataset, TDirectory *lhdir ) estimatorHistTrain->SetLineColor( 2 ); estimatorHistTrain->SetLineWidth( 2 ); estimatorHistTrain->SetTitle( TString("MLP Convergence Test") ); - + estimatorHistTest->SetLineColor( 4 ); estimatorHistTest->SetLineWidth( 2 ); @@ -45,7 +46,7 @@ void TMVA::annconvergencetest(TString dataset, TDirectory *lhdir ) estimatorHistTest ->Draw("samehist"); // need a legend - TLegend *legend= new TLegend( 1 - c->GetRightMargin() - 0.45, 1-c->GetTopMargin() - 0.20, + TLegend *legend= new TLegend( 1 - c->GetRightMargin() - 0.45, 1-c->GetTopMargin() - 0.20, 1 - c->GetRightMargin() - 0.05, 1-c->GetTopMargin() - 0.05 ); legend->AddEntry(estimatorHistTrain,"Training Sample","l"); @@ -65,13 +66,13 @@ void TMVA::annconvergencetest(TString dataset, TString fin , Bool_t useTMVAStyle { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); - + // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); // get all titles of the method likelihood TList titles; - TString metmlp="Method_MLP"; + TString metmlp="Method_MLP"; UInt_t ninst = TMVAGlob::GetListOfTitles(metmlp,titles,file->GetDirectory(dataset.Data())); if (ninst==0) { cout << "Could not locate directory 'Method_MLP' in file " << fin << endl; diff --git a/tmva/tmvagui/src/compareanapp.cxx b/tmva/tmvagui/src/compareanapp.cxx index d995ea6a5d0eb..3aa2e643ca7e8 100644 --- a/tmva/tmvagui/src/compareanapp.cxx +++ b/tmva/tmvagui/src/compareanapp.cxx @@ -7,7 +7,7 @@ //TString DerivedPlotName = "Proba"; TString DerivedPlotName = "Rarity"; -void TMVA::compareanapp( TString finAn , TString finApp , +void TMVA::compareanapp( TString finAn , TString finApp , HistType htype , bool useTMVAStyle ) { cout << "=== Compare histograms of two files ===" << endl; @@ -21,7 +21,7 @@ void TMVA::compareanapp( TString finAn , TString finApp , const Bool_t Draw_CFANN_Logy = kFALSE; const Bool_t Save_Images = kTRUE; - TFile* file = TMVAGlob::OpenFile( finAn ); + TFile* file = TMVAGlob::OpenFile( finAn ); TFile* fileApp = new TFile( finApp ); file->cd(); @@ -33,7 +33,7 @@ void TMVA::compareanapp( TString finAn , TString finApp , TList methods; TIter next(&methods); - TKey *key; + TKey *key; while ( (key = (TKey*)next()) ) { TString dirname = ((TDirectory*)key->ReadObj())->GetName(); @@ -41,7 +41,7 @@ void TMVA::compareanapp( TString finAn , TString finApp , cout << "--- Found directory: " << dirname << " --> ignoring" << endl; continue; } - cout << "--- Found directory: " << dirname + cout << "--- Found directory: " << dirname << " --> going in" << endl; TString methodName; @@ -70,67 +70,67 @@ void TMVA::compareanapp( TString finAn , TString finApp , if (sig==0 || bgd==0) continue; // chop off useless stuff - sig->SetTitle( Form("TMVA output for classifier: %s", methodTitle.Data()) ); - if (htype == kProbaType) - sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) ); - else if (htype == kRarityType) - sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) ); - + sig->SetTitle( TString::Format("TMVA output for classifier: %s", methodTitle.Data()) ); + if (htype == kProbaType) + sig->SetTitle( TString::Format("TMVA probability for classifier: %s", methodTitle.Data()) ); + else if (htype == kRarityType) + sig->SetTitle( TString::Format("TMVA Rarity for classifier: %s", methodTitle.Data()) ); + // create new canvas - TString ctitle = ((htype == TMVA::kMVAType) ? - Form("TMVA output %s",methodTitle.Data()) : - (htype == kProbaType) ? - Form("TMVA probability %s",methodTitle.Data()) : - Form("TMVA rarity %s",methodTitle.Data())); - - TString cname = ((htype == TMVA::kMVAType) ? - Form("output_%s",methodTitle.Data()) : - (htype == kProbaType) ? - Form("probability_%s",methodTitle.Data()) : - Form("rarity_%s",methodTitle.Data())); - - TCanvas* c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, - countCanvas*50+200, countCanvas*20, width, width*0.78 ); - + TString ctitle = ((htype == TMVA::kMVAType) ? + TString::Format("TMVA output %s",methodTitle.Data()) : + (htype == kProbaType) ? + TString::Format("TMVA probability %s",methodTitle.Data()) : + TString::Format("TMVA rarity %s",methodTitle.Data())); + + TString cname = ((htype == TMVA::kMVAType) ? + TString::Format("output_%s",methodTitle.Data()) : + (htype == kProbaType) ? + TString::Format("probability_%s",methodTitle.Data()) : + TString::Format("rarity_%s",methodTitle.Data())); + + TCanvas* c = new TCanvas( TString::Format("canvas%d", countCanvas+1), ctitle, + countCanvas*50+200, countCanvas*20, width, width*0.78 ); + // set the histogram style TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd ); - + // normalise both signal and background TMVAGlob::NormalizeHists( sig, bgd ); - + // frame limits (choose judicuous x range) Float_t nrms = 4; - Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), + Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), bgd->GetMean() - nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmin() ); - Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), + Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), bgd->GetMean() + nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmax() ); Float_t ymin = 0; Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*1.2 ; - + if (Draw_CFANN_Logy && methodName == "CFANN") ymin = 0.01; - + // build a frame Int_t nb = 500; - TH2F* frame = new TH2F( TString("frame") + methodTitle, sig->GetTitle(), + TH2F* frame = new TH2F( TString("frame") + methodTitle, sig->GetTitle(), nb, xmin, xmax, nb, ymin, ymax ); frame->GetXaxis()->SetTitle(methodTitle); if (htype == kProbaType ) frame->GetXaxis()->SetTitle( "Signal probability" ); else if (htype == kRarityType) frame->GetXaxis()->SetTitle( "Signal rarity" ); frame->GetYaxis()->SetTitle("Normalized"); TMVAGlob::SetFrameStyle( frame ); - + // eventually: draw the frame - frame->Draw(); - + frame->Draw(); + c->GetPad(0)->SetLeftMargin( 0.105 ); frame->GetYaxis()->SetTitleOffset( 1.2 ); - + if (Draw_CFANN_Logy && methodName == "CFANN") c->SetLogy(); - - // Draw legend - TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, + + // Draw legend + TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, c->GetLeftMargin() + 0.3, 1 - c->GetTopMargin() ); legend->SetFillStyle( 1 ); legend->AddEntry(sig,"Signal","F"); @@ -143,10 +143,10 @@ void TMVA::compareanapp( TString finAn , TString finApp , sig->Draw("samehist"); bgd->Draw("samehist"); - // retrieve corresponding histogram from TMVApp.root + // retrieve corresponding histogram from TMVApp.root TString hStem(hname); cout << "--- Searching for histogram: " << hStem.Data() << " in application file" << endl; - + TH1* testHist = (TH1*)fileApp->Get( hStem ); if (testHist != 0) { cout << "--> Found application histogram: " << testHist->GetName() << " --> superimpose it" << endl; @@ -156,30 +156,30 @@ void TMVA::compareanapp( TString finAn , TString finApp , testHist->SetLineColor( 1 ); testHist->Draw("samehist"); } - + // redraw axes frame->Draw("sameaxis"); - + // text for overflows Int_t nbin = sig->GetNbinsX(); Double_t dxu = sig->GetBinWidth(0); Double_t dxo = sig->GetBinWidth(nbin+1); - TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", + TString uoflow = TString::Format( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 ); TText* t = new TText( 0.975, 0.115, uoflow ); t->SetNDC(); t->SetTextSize( 0.030 ); t->SetTextAngle( 90 ); - t->AppendPad(); - + t->AppendPad(); + // save canvas to file c->Update(); TMVAGlob::plot_logo(); if (Save_Images) { - if (htype == TMVA::kMVAType) TMVAGlob::imgconv( c, Form("plots/mva_%s", methodTitle.Data()) ); - else if (htype == TMVA::kProbaType) TMVAGlob::imgconv( c, Form("plots/proba_%s", methodTitle.Data()) ); - else TMVAGlob::imgconv( c, Form("plots/rarity_%s", methodTitle.Data()) ); + if (htype == TMVA::kMVAType) TMVAGlob::imgconv( c, TString::Format("plots/mva_%s", methodTitle.Data()) ); + else if (htype == TMVA::kProbaType) TMVAGlob::imgconv( c, TString::Format("plots/proba_%s", methodTitle.Data()) ); + else TMVAGlob::imgconv( c, TString::Format("plots/rarity_%s", methodTitle.Data()) ); } countCanvas++; } diff --git a/tmva/tmvagui/src/correlations.cxx b/tmva/tmvagui/src/correlations.cxx index be91174f76362..25362f35f1444 100644 --- a/tmva/tmvagui/src/correlations.cxx +++ b/tmva/tmvagui/src/correlations.cxx @@ -36,7 +36,7 @@ void TMVA::correlations(TString dataset, TString fin , Bool_t isRegression , } TCanvas* c = new TCanvas( hName[ic], - Form("Correlations between MVA input variables (%s)", + TString::Format("Correlations between MVA input variables (%s)", (isRegression ? "" : (ic==0 ? "signal" : "background"))), ic*(width+5)+200, 0, width, width ); Float_t newMargin1 = 0.13; diff --git a/tmva/tmvagui/src/correlationsMultiClass.cxx b/tmva/tmvagui/src/correlationsMultiClass.cxx index 7a3cc3ab5a99f..758adf1c543af 100644 --- a/tmva/tmvagui/src/correlationsMultiClass.cxx +++ b/tmva/tmvagui/src/correlationsMultiClass.cxx @@ -37,7 +37,7 @@ void TMVA::correlationsMultiClass(TString dataset, TString fin , Bool_t /* isReg } TCanvas* c = new TCanvas( hnames[ic], - Form("Correlations between MVA input variables (%s)", + TString::Format("Correlations between MVA input variables (%s)", classnames[ic].Data()), ic*(width+5)+200, 0, width, width ); Float_t newMargin1 = 0.13; diff --git a/tmva/tmvagui/src/correlationscatters.cxx b/tmva/tmvagui/src/correlationscatters.cxx index 152f81ed10292..2e5af9db5f8ce 100644 --- a/tmva/tmvagui/src/correlationscatters.cxx +++ b/tmva/tmvagui/src/correlationscatters.cxx @@ -10,7 +10,7 @@ // input: - Input file (result from TMVA), // - normal/decorrelated/PCA // - use of TMVA plotting TStyle -void TMVA::correlationscatters(TString dataset, TString fin , TString var, +void TMVA::correlationscatters(TString dataset, TString fin , TString var, TString dirName_, TString /*title */ , Bool_t isRegression , Bool_t useTMVAStyle ) @@ -24,16 +24,16 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, if (extension == "") extension = "_Id"; // use 'Id' for 'idendtity transform' var.ReplaceAll( extension, "" ); - cout << "Called macro \"correlationscatters\" for variable: \"" << var - << "\", transformation type \"" << dirName_ + cout << "Called macro \"correlationscatters\" for variable: \"" << var + << "\", transformation type \"" << dirName_ << "\" (extension: \"" << extension << "\")" << endl; // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); TString dirName = dirName_ + "/CorrelationPlots"; - - // find out number of input variables + + // find out number of input variables TDirectory* vardir = (TDirectory*)file->GetDirectory(dataset.Data())->Get("InputVariables_Id"); if (!vardir) { cout << "ERROR: no such directory: \"InputVariables\"" << endl; @@ -50,7 +50,7 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, TListIter keyIt(dir->GetListOfKeys()); Int_t noPlots = noVars - 1; - + cout << "noPlots: " << noPlots << " --> noVars: " << noVars << endl; if (noVars != Int_t(noVars)) { cout << "*** Warning: problem in inferred number of variables ... not an integer *** " << endl; @@ -74,7 +74,7 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, default: xPad = 3; yPad = 2; width = 800; height = 0.55*width; break; } - Int_t noPadPerCanv = xPad * yPad ; + Int_t noPadPerCanv = xPad * yPad ; // counter variables Int_t countCanvas = 0; @@ -89,7 +89,7 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, TCanvas* canv = 0; Int_t countPad = 0; - + while ( (key = (TKey*)next()) ) { if (key->GetCycle() != 1) continue; @@ -101,22 +101,22 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, TString hname = scat->GetName(); // check for all signal histograms - if (! (hname.EndsWith( thename[itype] + extension ) && + if (! (hname.EndsWith( thename[itype] + extension ) && hname.Contains( TString("_") + var + "_" ) && hname.BeginsWith("scat_")) ) { scat->Delete(); - continue; + continue; } // found a new signal plot - + // create new canvas if (countPad%noPadPerCanv==0) { ++countCanvas; TString ext = extension; ext.Remove( 0, 1 ); - canv = new TCanvas( Form("canvas%d", countCanvas), - Form("Correlation profiles for '%s'-transformed %s variables", + canv = new TCanvas( TString::Format("canvas%d", countCanvas), + TString::Format("Correlation profiles for '%s'-transformed %s variables", ext.Data(), (isRegression ? "" : (itype==0) ? "signal" : "background")), - countCanvas*50+200, countCanvas*20, width, height ); + countCanvas*50+200, countCanvas*20, width, height ); canv->Divide(xPad,yPad); } @@ -136,15 +136,15 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, // this is set but not stored during plot creation in MVA_Factory TMVAGlob::SetSignalAndBackgroundStyle( scat, prof ); - // chop off "signal" + // chop off "signal" TMVAGlob::SetFrameStyle( scat, 1.2 ); // normalise both signal and background scat->Scale( 1.0/scat->GetSumOfWeights() ); - // finally plot and overlay + // finally plot and overlay scat->SetMarkerColor( 4); - scat->Draw("col"); + scat->Draw("col"); prof->SetMarkerColor( gConfig().fVariablePlotting.fUsePaperStyle ? 1 : 2 ); prof->SetMarkerSize( 0.2 ); prof->SetLineColor( gConfig().fVariablePlotting.fUsePaperStyle ? 1 : 2 ); @@ -159,7 +159,7 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, if (countPad%noPadPerCanv==0) { canv->Update(); - TString fname = Form( "%s/plots/correlationscatter_%s_%s_c%i",dataset.Data(),var.Data(), extension.Data(), countCanvas ); + TString fname = TString::Format( "%s/plots/correlationscatter_%s_%s_c%i",dataset.Data(),var.Data(), extension.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); } @@ -167,7 +167,7 @@ void TMVA::correlationscatters(TString dataset, TString fin , TString var, if (countPad%noPadPerCanv!=0) { canv->Update(); - TString fname = Form( "%s/plots/correlationscatter_%s_%s_c%i",dataset.Data(),var.Data(), extension.Data(), countCanvas ); + TString fname = TString::Format( "%s/plots/correlationscatter_%s_%s_c%i",dataset.Data(),var.Data(), extension.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); } diff --git a/tmva/tmvagui/src/correlationscattersMultiClass.cxx b/tmva/tmvagui/src/correlationscattersMultiClass.cxx index 293c8eb41df0a..dbb8907f44907 100644 --- a/tmva/tmvagui/src/correlationscattersMultiClass.cxx +++ b/tmva/tmvagui/src/correlationscattersMultiClass.cxx @@ -10,30 +10,30 @@ // input: - Input file (result from TMVA), // - normal/decorrelated/PCA // - use of TMVA plotting TStyle -void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString var, +void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString var, TString dirName_ , TString /*title*/, Bool_t /*isRegression */, Bool_t useTMVAStyle ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); - + TString extension = dirName_; extension.ReplaceAll( "InputVariables", "" ); extension.ReplaceAll( " ", "" ); if (extension == "") extension = "_Id"; // use 'Id' for 'idendtity transform' var.ReplaceAll( extension, "" ); - cout << "Called macro \"correlationscattersMultiClass\" for variable: \"" << var - << "\", transformation type \"" << dirName_ + cout << "Called macro \"correlationscattersMultiClass\" for variable: \"" << var + << "\", transformation type \"" << dirName_ << "\" (extension: \"" << extension << "\")" << endl; // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); TString dirName = dirName_ + "/CorrelationPlots"; - - // find out number of input variables + + // find out number of input variables TDirectory* vardir = (TDirectory*)file->GetDirectory(dataset.Data())->Get( "InputVariables_Id" ); if (!vardir) { cout << "ERROR: no such directory: \"InputVariables\"" << endl; @@ -50,7 +50,7 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString TListIter keyIt(dir->GetListOfKeys()); Int_t noPlots = noVars - 1; - + cout << "noPlots: " << noPlots << " --> noVars: " << noVars << endl; if (noVars != Int_t(noVars)) { cout << "*** Warning: problem in inferred number of variables ... not an integer *** " << endl; @@ -74,7 +74,7 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString default: xPad = 3; yPad = 2; width = 800; height = 0.55*width; break; } - Int_t noPadPerCanv = xPad * yPad ; + Int_t noPadPerCanv = xPad * yPad ; // counter variables Int_t countCanvas = 0; @@ -91,7 +91,7 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString TCanvas* canv = 0; Int_t countPad = 0; - + while ( (key = (TKey*)next()) ) { if (key->GetCycle() != 1) continue; @@ -101,25 +101,25 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString if (!cl->InheritsFrom("TH1")) continue; TH1 *scat = (TH1*)key->ReadObj(); TString hname = scat->GetName(); - + //std::cout << classnames[itype] << " " << extension << "" << hname << " " << var << std::endl; // check for scatter plots - if (! (hname.EndsWith( classnames[itype] + extension ) && + if (! (hname.EndsWith( classnames[itype] + extension ) && hname.Contains( TString("_") + var + "_" ) && hname.BeginsWith("scat_")) ) { scat->Delete(); - continue; + continue; } // found a new signal plot - + // create new canvas if (countPad%noPadPerCanv==0) { ++countCanvas; TString ext = extension; ext.Remove( 0, 1 ); - canv = new TCanvas( Form("canvas%d", countCanvas), - Form("Correlation profiles for '%s'-transformed variables (%s)", + canv = new TCanvas( TString::Format("canvas%d", countCanvas), + TString::Format("Correlation profiles for '%s'-transformed variables (%s)", ext.Data(), classnames[itype].Data()), - countCanvas*50+200, countCanvas*20, width, height ); + countCanvas*50+200, countCanvas*20, width, height ); canv->Divide(xPad,yPad); } @@ -139,17 +139,17 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString // this is set but not stored during plot creation in MVA_Factory TMVAGlob::SetSignalAndBackgroundStyle( scat, prof ); - // chop off "signal" + // chop off "signal" TMVAGlob::SetFrameStyle( scat, 1.2 ); // normalise both signal and background scat->Scale( 1.0/scat->GetSumOfWeights() ); - // finally plot and overlay + // finally plot and overlay // Float_t sc = 1.1; // if (countPad==2) sc = 1.3; scat->SetMarkerColor( 4); - scat->Draw("col"); + scat->Draw("col"); prof->SetMarkerColor( gConfig().fVariablePlotting.fUsePaperStyle ? 1 : 2 ); prof->SetMarkerSize( 0.2 ); prof->SetLineColor( gConfig().fVariablePlotting.fUsePaperStyle ? 1 : 2 ); @@ -164,7 +164,7 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString if (countPad%noPadPerCanv==0) { canv->Update(); - TString fname = dataset+Form( "/plots/correlationscatter_%s_%s_c%i",var.Data(), extension.Data(), countCanvas ); + TString fname = dataset+TString::Format( "/plots/correlationscatter_%s_%s_c%i",var.Data(), extension.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); } @@ -172,7 +172,7 @@ void TMVA::correlationscattersMultiClass(TString dataset, TString fin , TString if (countPad%noPadPerCanv!=0) { canv->Update(); - TString fname = dataset+Form( "/plots/correlationscatter_%s_%s_c%i",var.Data(), extension.Data(), countCanvas ); + TString fname = dataset+TString::Format( "/plots/correlationscatter_%s_%s_c%i",var.Data(), extension.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); } diff --git a/tmva/tmvagui/src/deviations.cxx b/tmva/tmvagui/src/deviations.cxx index de331ae54f11a..4463270952836 100644 --- a/tmva/tmvagui/src/deviations.cxx +++ b/tmva/tmvagui/src/deviations.cxx @@ -12,7 +12,7 @@ // input: - Input file (result from TMVA) // - use of TMVA plotting TStyle -void TMVA::deviations(TString dataset, TString fin, +void TMVA::deviations(TString dataset, TString fin, HistType htype , Bool_t showTarget, Bool_t useTMVAStyle ) { // set style and remove existing canvas' @@ -20,7 +20,7 @@ void TMVA::deviations(TString dataset, TString fin, gStyle->SetNumberContours(999); // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); // define Canvas layout here! const Int_t width = 650; // size of canvas @@ -35,7 +35,7 @@ void TMVA::deviations(TString dataset, TString fin, // TList* methods = new TMap(); TIter next(file->GetDirectory(dataset.Data())->GetListOfKeys()); - TKey *key(0); + TKey *key(0); while ((key = (TKey*)next())) { if (!TString(key->GetName()).BeginsWith("Method_")) continue; @@ -60,7 +60,7 @@ void TMVA::deviations(TString dataset, TString fin, TObjString *jN = new TObjString( titDir->GetName() ); if (!jobNames->Contains( jN )) jobNames->Add( jN ); else delete jN; - + TString methodTitle; TMVAGlob::GetMethodTitle(methodTitle,titDir); @@ -72,16 +72,16 @@ void TMVA::deviations(TString dataset, TString fin, while ((dirKey = (TKey*)dirKeyIt())){ if (dirKey->ReadObj()->InheritsFrom("TH2F")) { TString s(dirKey->ReadObj()->GetName()); - if (s.Contains("_reg_") && - ( (showTarget && s.Contains("_tgt")) || (!showTarget && !s.Contains("_tgt")) ) && + if (s.Contains("_reg_") && + ( (showTarget && s.Contains("_tgt")) || (!showTarget && !s.Contains("_tgt")) ) && s.Contains( (htype == kCompareType ? "train" : "test" ))) { - c[countCanvas] = new TCanvas( Form("canvas%d", countCanvas+1), - Form( "Regression output deviation versus %s for method: %s", + c[countCanvas] = new TCanvas( TString::Format("canvas%d", countCanvas+1), + TString::Format( "Regression output deviation versus %s for method: %s", (showTarget ? "target" : "input variables"), methodName.Data() ), - countCanvas*50+100, (countCanvas+1)*20, width, (Int_t)width*0.72 ); + countCanvas*50+100, (countCanvas+1)*20, width, (Int_t)width*0.72 ); c[countCanvas]->SetRightMargin(0.10); // leave space for border TH1* h = (TH1*)dirKey->ReadObj(); - h->SetTitle( Form("Output deviation for method: %s (%s sample)", + h->SetTitle( TString::Format("Output deviation for method: %s (%s sample)", hname.Data(), (htype == kCompareType ? "training" : "test" )) ); // methodName.Data(), (htype == kCompareType ? "training" : "test" )) ); h->Draw("colz"); @@ -94,9 +94,9 @@ void TMVA::deviations(TString dataset, TString fin, TMVAGlob::plot_logo(1.058); c[countCanvas]->Update(); - TString fname = Form( "%s/plots/deviation_%s_%s_%s_c%i", + TString fname = TString::Format( "%s/plots/deviation_%s_%s_%s_c%i", dataset.Data(), - methodName.Data(), + methodName.Data(), (showTarget ? "target" : "vars"), (htype == kCompareType ? "training" : "test" ), countPlots ); TMVAGlob::imgconv( c[countCanvas], fname ); @@ -105,7 +105,7 @@ void TMVA::deviations(TString dataset, TString fin, countCanvas++; } } - } + } } } } diff --git a/tmva/tmvagui/src/efficienciesMulticlass.cxx b/tmva/tmvagui/src/efficienciesMulticlass.cxx index 275e402ba9766..3619e67b3e915 100644 --- a/tmva/tmvagui/src/efficienciesMulticlass.cxx +++ b/tmva/tmvagui/src/efficienciesMulticlass.cxx @@ -227,7 +227,7 @@ void TMVA::plotEfficienciesMulticlass(roccurvelist_t rocCurves, classcanvasmap_t plotWrapper->addGraph(h); plotWrapper->addLegendEntry(methodTitle, h); } catch (const std::out_of_range &) { - cout << Form("ERROR: Class %s discovered among plots but was not found by TMVAMulticlassGui. Skipping.", + cout << TString::Format("ERROR: Class %s discovered among plots but was not found by TMVAMulticlassGui. Skipping.", classname.Data()) << endl; } @@ -280,8 +280,8 @@ void TMVA::plotEfficienciesMulticlass1vsRest(TString dataset, EEfficiencyPlotTyp classcanvasmap_t classCanvasMap; for (auto &classname : classnames) { - TString name = Form("roc_%s_vs_rest", classname.Data()); - TString title = Form("ROC Curve %s vs rest", classname.Data()); + TString name = TString::Format("roc_%s_vs_rest", classname.Data()); + TString title = TString::Format("ROC Curve %s vs rest", classname.Data()); EfficiencyPlotWrapper *plotWrapper = new EfficiencyPlotWrapper(name, title, dataset, iPlot++); classCanvasMap.emplace(classname.Data(), plotWrapper); } @@ -316,8 +316,8 @@ void TMVA::efficienciesMulticlass1vs1(TString dataset, TString fin) // configure buttons for (auto &classname : classnames) { - cbar->AddButton(Form("Class: %s", classname.Data()), - Form("TMVA::plotEfficienciesMulticlass1vs1(\"%s\", \"%s\", \"%s\")", dataset.Data(), fin.Data(), + cbar->AddButton(TString::Format("Class: %s", classname.Data()), + TString::Format("TMVA::plotEfficienciesMulticlass1vs1(\"%s\", \"%s\", \"%s\")", dataset.Data(), fin.Data(), classname.Data()), BUTTON_TYPE); } @@ -353,7 +353,7 @@ void TMVA::plotEfficienciesMulticlass1vs1(TString dataset, TString fin, TString size_t iPlot = 0; TString methodPrefix = "MVA_"; - TString graphNameRef = Form("_1v1rejBvsS_%s_vs_", baseClassname.Data()); + TString graphNameRef = TString::Format("_1v1rejBvsS_%s_vs_", baseClassname.Data()); TFile *file = TMVAGlob::OpenFile(fin); if (file == nullptr) { @@ -369,8 +369,8 @@ void TMVA::plotEfficienciesMulticlass1vs1(TString dataset, TString fin, TString continue; } - TString name = Form("1v1roc_%s_vs_%s", baseClassname.Data(), classname.Data()); - TString title = Form("ROC Curve %s (Sig) vs %s (Bkg)", baseClassname.Data(), classname.Data()); + TString name = TString::Format("1v1roc_%s_vs_%s", baseClassname.Data(), classname.Data()); + TString title = TString::Format("ROC Curve %s (Sig) vs %s (Bkg)", baseClassname.Data(), classname.Data()); EfficiencyPlotWrapper *plotWrapper = new EfficiencyPlotWrapper(name, title, dataset, iPlot++); classCanvasMap.emplace(classname.Data(), plotWrapper); } @@ -474,7 +474,7 @@ TCanvas *EfficiencyPlotWrapper::newEfficiencyCanvas(TString name, TString title, Double_t y1 = 0.0; Double_t y2 = 1.0; - TH1F *frame = new TH1F(Form("%s_%s", title.Data(), "frame"), title, 500, x1, x2); + TH1F *frame = new TH1F(TString::Format("%s_frame", title.Data()), title, 500, x1, x2); frame->SetMinimum(y1); frame->SetMaximum(y2); @@ -508,4 +508,4 @@ void EfficiencyPlotWrapper::save() { TString fname = fDataset + "/plots/" + fCanvas->GetName(); TMVA::TMVAGlob::imgconv(fCanvas, fname); -} \ No newline at end of file +} diff --git a/tmva/tmvagui/src/likelihoodrefs.cxx b/tmva/tmvagui/src/likelihoodrefs.cxx index 4850c3da204d9..73c97041c3996 100644 --- a/tmva/tmvagui/src/likelihoodrefs.cxx +++ b/tmva/tmvagui/src/likelihoodrefs.cxx @@ -47,7 +47,7 @@ void TMVA::likelihoodrefs(TString dataset, TDirectory *lhdir ) { snprintf( cn, 20, "cv%d_%s", ic+1, titName.Data() ); ++ic; TString n = hname; - c[ic] = new TCanvas( cn, Form( "%s reference for variable: %s", + c[ic] = new TCanvas( cn, TString::Format( "%s reference for variable: %s", titName.Data(),(n.ReplaceAll("_sig","")).Data() ), ic*50+50, ic*20, width, height ); c[ic]->Divide(2,1); @@ -108,7 +108,7 @@ void TMVA::likelihoodrefs(TString dataset, TDirectory *lhdir ) { b = 0; TString pname = hname; pname.ReplaceAll("_nice",""); for (int i=0; i<= 5; i++) { - TString hspline = pname + Form( "_smoothed_hist_from_spline%i", i ); + TString hspline = pname + TString::Format( "_smoothed_hist_from_spline%i", i ); h = (TH1F*)lhdir->Get( hspline ); if (h) { b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") ); @@ -158,7 +158,7 @@ void TMVA::likelihoodrefs(TString dataset, TDirectory *lhdir ) { c[ic]->Update(); // write to file - TString fname = Form( "%s/plots/%s_refs_c%i",dataset.Data(), titName.Data(), ic+1 ); + TString fname = TString::Format( "%s/plots/%s_refs_c%i",dataset.Data(), titName.Data(), ic+1 ); TMVAGlob::imgconv( c[ic], fname ); //c[ic]->Update(); diff --git a/tmva/tmvagui/src/mvaeffs.cxx b/tmva/tmvagui/src/mvaeffs.cxx index e4a2905a59725..46ab96ab1fea4 100644 --- a/tmva/tmvagui/src/mvaeffs.cxx +++ b/tmva/tmvagui/src/mvaeffs.cxx @@ -58,7 +58,7 @@ void TMVA::MethodInfo::SetResultHists() effpurS = new TH1F(epname, epname, nbins, low, high); // chop off useless stuff - sigE->SetTitle( Form("Cut efficiencies for %s classifier", methodTitle.Data()) ); + sigE->SetTitle( TString::Format("Cut efficiencies for %s classifier", methodTitle.Data()) ); // set the histogram style TMVAGlob::SetSignalAndBackgroundStyle( sigE, bgdE ); @@ -253,7 +253,7 @@ void TMVA::StatDialogMVAEffs::UpdateSignificanceHists() MethodInfo* info(0); TString cname = "Classifier"; if (cname.Length() > maxLenTitle) maxLenTitle = cname.Length(); - TString str = Form( "%*s ( #signal, #backgr.) Optimal-cut %s NSig NBkg EffSig EffBkg", + TString str = TString::Format( "%*s ( #signal, #backgr.) Optimal-cut %s NSig NBkg EffSig EffBkg", maxLenTitle, cname.Data(), GetFormulaString().Data() ); cout << "--- " << setfill('=') << setw(str.Length()) << "" << setfill(' ') << endl; cout << "--- " << str << endl; @@ -351,12 +351,12 @@ void TMVA::StatDialogMVAEffs::DrawHistograms() Int_t signifColor = TColor::GetColor( "#00aa00" ); TIter next(fInfoList); - MethodInfo* info(0); + MethodInfo* info = nullptr; while ( (info = (MethodInfo*)next()) ) { // create new canvas - TCanvas *c = new TCanvas( Form("canvas%d", countCanvas+1), - Form("Cut efficiencies for %s classifier",info->methodTitle.Data()), + TCanvas *c = new TCanvas( TString::Format("canvas%d", countCanvas+1), + TString::Format("Cut efficiencies for %s classifier",info->methodTitle.Data()), countCanvas*50+200, countCanvas*20, width, Int_t(width*0.78) ); info->canvas = c; @@ -431,17 +431,17 @@ void TMVA::StatDialogMVAEffs::DrawHistograms() tl.SetNDC(); tl.SetTextSize( 0.033 ); Int_t maxbin = info->sSig->GetMaximumBin(); - info->line1 = tl.DrawLatex( 0.15, 0.23, Form("For %1.0f signal and %1.0f background", fNSignal, fNBackground)); + info->line1 = tl.DrawLatex( 0.15, 0.23, TString::Format("For %1.0f signal and %1.0f background", fNSignal, fNBackground)); tl.DrawLatex( 0.15, 0.19, "events the maximum "+GetLatexFormula()+" is"); if (info->maxSignificanceErr > 0) { - info->line2 = tl.DrawLatex( 0.15, 0.15, Form("%5.2f +- %4.2f when cutting at %5.2f", + info->line2 = tl.DrawLatex( 0.15, 0.15, TString::Format("%5.2f +- %4.2f when cutting at %5.2f", info->maxSignificance, info->maxSignificanceErr, info->sSig->GetXaxis()->GetBinCenter(maxbin)) ); } else { - info->line2 = tl.DrawLatex( 0.15, 0.15, Form("%4.2f when cutting at %5.2f", + info->line2 = tl.DrawLatex( 0.15, 0.15, TString::Format("%4.2f when cutting at %5.2f", info->maxSignificance, info->sSig->GetXaxis()->GetBinCenter(maxbin)) ); } @@ -471,7 +471,7 @@ void TMVA::StatDialogMVAEffs::DrawHistograms() const Bool_t Save_Images = kTRUE; if (Save_Images) { - TMVAGlob::imgconv( c, Form("%s/plots/mvaeffs_%s",dataset.Data(), info->methodTitle.Data()) ); + TMVAGlob::imgconv( c, TString::Format("%s/plots/mvaeffs_%s",dataset.Data(), info->methodTitle.Data()) ); } countCanvas++; } @@ -481,24 +481,24 @@ void TMVA::StatDialogMVAEffs::PrintResults( const MethodInfo* info ) { Int_t maxbin = info->sSig->GetMaximumBin(); if (info->line1 !=0 ) - info->line1->SetText( 0.15, 0.23, Form("For %1.0f signal and %1.0f background", fNSignal, fNBackground)); + info->line1->SetText( 0.15, 0.23, TString::Format("For %1.0f signal and %1.0f background", fNSignal, fNBackground)); if (info->line2 !=0 ) { if (info->maxSignificanceErr > 0) { - info->line2->SetText( 0.15, 0.15, Form("%3.2g +- %3.2g when cutting at %3.2g", + info->line2->SetText( 0.15, 0.15, TString::Format("%3.2g +- %3.2g when cutting at %3.2g", info->maxSignificance, info->maxSignificanceErr, info->sSig->GetXaxis()->GetBinCenter(maxbin)) ); } else { - info->line2->SetText( 0.15, 0.15, Form("%3.4f when cutting at %3.4f", info->maxSignificance, + info->line2->SetText( 0.15, 0.15, TString::Format("%3.4f when cutting at %3.4f", info->maxSignificance, info->sSig->GetXaxis()->GetBinCenter(maxbin)) ); } } if (info->maxSignificanceErr <= 0) { - TString opt = Form( "%%%is: (%%9.8g,%%9.8g) %%9.4f %%10.6g %%8.7g %%8.7g %%8.4g %%8.4g", + TString opt = TString::Format( "%%%is: (%%9.8g,%%9.8g) %%9.4f %%10.6g %%8.7g %%8.7g %%8.4g %%8.4g", maxLenTitle ); cout << "--- " << Form( opt.Data(), @@ -512,7 +512,7 @@ void TMVA::StatDialogMVAEffs::PrintResults( const MethodInfo* info ) << endl; } else { - TString opt = Form( "%%%is: (%%9.8g,%%9.8g) %%9.4f (%%8.3g +-%%6.3g) %%8.7g %%8.7g %%8.4g %%8.4g", + TString opt = TString::Format( "%%%is: (%%9.8g,%%9.8g) %%9.4f (%%8.3g +-%%6.3g) %%8.7g %%8.7g %%8.4g %%8.4g", maxLenTitle ); cout << "--- " << Form( opt.Data(), diff --git a/tmva/tmvagui/src/mvas.cxx b/tmva/tmvagui/src/mvas.cxx index 63ec498ddc10d..b190486ede5ac 100644 --- a/tmva/tmvagui/src/mvas.cxx +++ b/tmva/tmvagui/src/mvas.cxx @@ -22,7 +22,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl const Bool_t Save_Images = kTRUE; // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); // define Canvas layout here! const Int_t width = 600; // size of canvas @@ -35,7 +35,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl // search for the right histograms in full list of keys TIter next(file->GetDirectory(dataset.Data())->GetListOfKeys()); - TKey *key(0); + TKey *key(0); while ((key = (TKey*)next())) { if (!TString(key->GetName()).BeginsWith("Method_")) continue; @@ -64,13 +64,13 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl TH1* bgd = dynamic_cast(titDir->Get( hname + "_B" )); if (sig==0 || bgd==0) { - if (htype == kMVAType) + if (htype == kMVAType) cout << ":\t mva distribution not available (this is normal for Cut classifier)" << endl; - else if(htype == kProbaType) + else if(htype == kProbaType) cout << ":\t probability distribution not available" << endl; - else if(htype == kRarityType) + else if(htype == kRarityType) cout << ":\t rarity distribution not available" << endl; - else if(htype == kCompareType) + else if(htype == kCompareType) cout << ":\t overtraining check not available" << endl; else cout << endl; continue; @@ -78,67 +78,67 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl cout << " containing " << hname << "_S/_B" << endl; // chop off useless stuff - sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) ); - if (htype == kProbaType) - sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) ); - else if (htype == kRarityType) - sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) ); - else if (htype == kCompareType) - sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) ); - + sig->SetTitle( TString::Format("TMVA response for classifier: %s", methodTitle.Data()) ); + if (htype == kProbaType) + sig->SetTitle( TString::Format("TMVA probability for classifier: %s", methodTitle.Data()) ); + else if (htype == kRarityType) + sig->SetTitle( TString::Format("TMVA Rarity for classifier: %s", methodTitle.Data()) ); + else if (htype == kCompareType) + sig->SetTitle( TString::Format("TMVA overtraining check for classifier: %s", methodTitle.Data()) ); + // create new canvas - TString ctitle = ((htype == kMVAType) ? - Form("TMVA response %s",methodTitle.Data()) : - (htype == kProbaType) ? - Form("TMVA probability %s",methodTitle.Data()) : - (htype == kCompareType) ? - Form("TMVA comparison %s",methodTitle.Data()) : - Form("TMVA Rarity %s",methodTitle.Data())); - - c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, - countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); - + TString ctitle = ((htype == kMVAType) ? + TString::Format("TMVA response %s",methodTitle.Data()) : + (htype == kProbaType) ? + TString::Format("TMVA probability %s",methodTitle.Data()) : + (htype == kCompareType) ? + TString::Format("TMVA comparison %s",methodTitle.Data()) : + TString::Format("TMVA Rarity %s",methodTitle.Data())); + + c = new TCanvas( TString::Format("canvas%d", countCanvas+1), ctitle, + countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); + // set the histogram style TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd ); - + // normalise both signal and background TMVAGlob::NormalizeHists( sig, bgd ); - + // frame limits (choose judicuous x range) Float_t nrms = 10; cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl; cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl; - Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), + Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), bgd->GetMean() - nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmin() ); - Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), + Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), bgd->GetMean() + nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmax() ); Float_t ymin = 0; Float_t maxMult = (htype == kCompareType) ? 1.3 : 1.2; Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult; - + // build a frame Int_t nb = 500; TString hFrameName(TString("frame") + methodTitle); TObject *o = gROOT->FindObject(hFrameName); if(o) delete o; - TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), + TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), nb, xmin, xmax, nb, ymin, ymax ); frame->GetXaxis()->SetTitle( methodTitle + ((htype == kMVAType || htype == kCompareType) ? " response" : "") ); if (htype == kProbaType ) frame->GetXaxis()->SetTitle( "Signal probability" ); else if (htype == kRarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" ); frame->GetYaxis()->SetTitle("(1/N) dN^{ }/^{ }dx"); TMVAGlob::SetFrameStyle( frame ); - + // eventually: draw the frame - frame->Draw(); - + frame->Draw(); + c->GetPad(0)->SetLeftMargin( 0.105 ); frame->GetYaxis()->SetTitleOffset( 1.2 ); - // Draw legend - TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, + // Draw legend + TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, c->GetLeftMargin() + (htype == kCompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() ); legend->SetFillStyle( 1 ); legend->AddEntry(sig,TString("Signal") + ((htype == kCompareType) ? " (test sample)" : ""), "F"); @@ -150,7 +150,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl // overlay signal and background histograms sig->Draw("samehist"); bgd->Draw("samehist"); - + if (htype == kCompareType) { // if overtraining check, load additional histograms TH1* sigOv = 0; @@ -159,7 +159,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl TString ovname = hname += "_Train"; sigOv = dynamic_cast(titDir->Get( ovname + "_S" )); bgdOv = dynamic_cast(titDir->Get( ovname + "_B" )); - + if (sigOv == 0 || bgdOv == 0) { cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl; } @@ -185,7 +185,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl sigOv->SetLineWidth( 1 ); sigOv->SetLineColor( col ); sigOv->Draw("e1same"); - + col = bgd->GetLineColor(); bgdOv->SetMarkerColor( col ); bgdOv->SetMarkerSize( 0.7 ); @@ -196,7 +196,7 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl ymax = TMath::Max( ymax, float(TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult )); frame->GetYaxis()->SetLimits( 0, ymax ); - + // for better visibility, plot thinner lines sig->SetLineWidth( 1 ); bgd->SetLineWidth( 1 ); @@ -207,9 +207,9 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl Double_t kolB = bgd->KolmogorovTest( bgdOv, "X" ); cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl; - TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB ); + TString probatext = TString::Format( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB ); TText* tt = new TText( 0.12, 0.74, probatext ); - tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); + tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); } // redraw axes @@ -219,15 +219,15 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl Int_t nbin = sig->GetNbinsX(); Double_t dxu = sig->GetBinWidth(0); Double_t dxo = sig->GetBinWidth(nbin+1); - TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", + TString uoflow = TString::Format( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 ); TText* t = new TText( 0.975, 0.115, uoflow ); t->SetNDC(); t->SetTextSize( 0.030 ); t->SetTextAngle( 90 ); - t->AppendPad(); - + t->AppendPad(); + // update canvas c->Update(); @@ -235,13 +235,13 @@ void TMVA::mvas(TString dataset, TString fin, HistType htype, Bool_t useTMVAStyl TMVAGlob::plot_logo(1.058); if (Save_Images) { - if (htype == kMVAType) TMVAGlob::imgconv( c, Form("%s/plots/mva_%s",dataset.Data(), methodTitle.Data()) ); - else if (htype == kProbaType) TMVAGlob::imgconv( c, Form("%s/plots/proba_%s",dataset.Data(), methodTitle.Data()) ); - else if (htype == kCompareType) TMVAGlob::imgconv( c, Form("%s/plots/overtrain_%s",dataset.Data(), methodTitle.Data()) ); - else TMVAGlob::imgconv( c, Form("%s/plots/rarity_%s",dataset.Data(), methodTitle.Data()) ); + if (htype == kMVAType) TMVAGlob::imgconv( c, TString::Format("%s/plots/mva_%s",dataset.Data(), methodTitle.Data()) ); + else if (htype == kProbaType) TMVAGlob::imgconv( c, TString::Format("%s/plots/proba_%s",dataset.Data(), methodTitle.Data()) ); + else if (htype == kCompareType) TMVAGlob::imgconv( c, TString::Format("%s/plots/overtrain_%s",dataset.Data(), methodTitle.Data()) ); + else TMVAGlob::imgconv( c, TString::Format("%s/plots/rarity_%s",dataset.Data(), methodTitle.Data()) ); } countCanvas++; - + } cout << ""; } diff --git a/tmva/tmvagui/src/mvasMulticlass.cxx b/tmva/tmvagui/src/mvasMulticlass.cxx index 332e0079f9fdd..b0ebe43070945 100644 --- a/tmva/tmvagui/src/mvasMulticlass.cxx +++ b/tmva/tmvagui/src/mvasMulticlass.cxx @@ -91,15 +91,15 @@ void TMVA::mvasMulticlass(TString dataset, TString fin , HistType htype , Bool_t // chop off useless stuff - ((TH1*)hists.First())->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data() )); + ((TH1*)hists.First())->SetTitle( TString::Format("TMVA response for classifier: %s", methodTitle.Data() )); // create new canvas //cout << "Create canvas..." << endl; TString ctitle = ((htype == kMVAType) ? - Form("TMVA response for class %s %s", classnames.at(icls).Data(),methodTitle.Data()) : - Form("TMVA comparison for class %s %s", classnames.at(icls).Data(),methodTitle.Data())) ; + TString::Format("TMVA response for class %s %s", classnames.at(icls).Data(),methodTitle.Data()) : + TString::Format("TMVA comparison for class %s %s", classnames.at(icls).Data(),methodTitle.Data())) ; - c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, + c = new TCanvas( TString::Format("canvas%d", countCanvas+1), ctitle, countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); // set the histogram style @@ -226,7 +226,7 @@ void TMVA::mvasMulticlass(TString dataset, TString fin , HistType htype , Bool_t for(Int_t j=0; jKolmogorovTest(((TH1*)othists[j]),"X"); cout << classnames.at(j) << ": " << kol << endl; - //probatext.Append(classnames.at(j)+Form(" %.3f ",kol)); + //probatext.Append(classnames.at(j)+TString::Format(" %.3f ",kol)); } @@ -244,7 +244,7 @@ void TMVA::mvasMulticlass(TString dataset, TString fin , HistType htype , Bool_t //Int_t nbin = sig->GetNbinsX(); //Double_t dxu = sig->GetBinWidth(0); //Double_t dxo = sig->GetBinWidth(nbin+1); - //TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", + //TString uoflow = TString::Format( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", // sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100, // sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 ); //TText* t = new TText( 0.975, 0.115, uoflow ); @@ -260,8 +260,8 @@ void TMVA::mvasMulticlass(TString dataset, TString fin , HistType htype , Bool_t TMVAGlob::plot_logo(1.058); if (Save_Images) { - if (htype == kMVAType) TMVAGlob::imgconv( c, Form("%s/plots/mva_%s_%s",dataset.Data(),classnames.at(icls).Data(), methodTitle.Data()) ); - else if (htype == kCompareType) TMVAGlob::imgconv( c, Form("%s/plots/overtrain_%s_%s",dataset.Data(),classnames.at(icls).Data(), methodTitle.Data()) ); + if (htype == kMVAType) TMVAGlob::imgconv( c, TString::Format("%s/plots/mva_%s_%s",dataset.Data(),classnames.at(icls).Data(), methodTitle.Data()) ); + else if (htype == kCompareType) TMVAGlob::imgconv( c, TString::Format("%s/plots/overtrain_%s_%s",dataset.Data(),classnames.at(icls).Data(), methodTitle.Data()) ); } countCanvas++; diff --git a/tmva/tmvagui/src/mvaweights.cxx b/tmva/tmvagui/src/mvaweights.cxx index 0e1591ad04be8..4a4349d08960e 100644 --- a/tmva/tmvagui/src/mvaweights.cxx +++ b/tmva/tmvagui/src/mvaweights.cxx @@ -22,8 +22,8 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) // switches const Bool_t Save_Images = kTRUE; - // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + // checks if file with name "fin" is already open, and if not opens one + TFile* file = TMVAGlob::OpenFile( fin ); if (!file) { cout << "Cannot open flie: " << fin << endl; return; @@ -37,7 +37,7 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) // counter variables Int_t countCanvas = 0; - + // retrieve trees TTree *tree = (TTree*)file->Get( "TestTree" ); @@ -46,26 +46,26 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) for (Int_t imva=0; imvaGetEntries(); imva++) { TBranch* b = (TBranch*)(*branches)[imva]; TString methodS = b->GetName(); - cout << "Use MVA output of Method " << methodS <Divide( 1, 1 ); - + // set the histogram style Float_t xmin = tree->GetMinimum( varx ); Float_t xmax = tree->GetMaximum( varx ); Float_t ymin = tree->GetMinimum( vary ); Float_t ymax = tree->GetMaximum( vary ); - + Int_t nbin = 100; TH2F* frame = new TH2F( "frame", "frame", nbin, xmin, xmax, nbin, ymin, ymax ); TH2F* frameS = new TH2F( "DataS", "DataS", nbin, xmin, xmax, nbin, ymin, ymax ); @@ -76,31 +76,31 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) Int_t nbinC = 20; TH2F* refS = new TH2F( "RefS", "RefS", nbinC, xmin, xmax, nbinC, ymin, ymax ); TH2F* refB = new TH2F( "RefB", "RefB", nbinC, xmin, xmax, nbinC, ymin, ymax ); - - Float_t mvaMin = tree->GetMinimum( Form( "MVA_%s", methodS.Data() ) ); - Float_t mvaMax = tree->GetMaximum( Form( "MVA_%s", methodS.Data() ) ); + + Float_t mvaMin = tree->GetMinimum( TString::Format( "MVA_%s", methodS.Data() ) ); + Float_t mvaMax = tree->GetMaximum( TString::Format( "MVA_%s", methodS.Data() ) ); // project trees - TString expr = Form( "((MVA_%s-(%f))/(%f-(%f)))", methodS.Data(), mvaMin, mvaMax, mvaMin ); + TString expr = TString::Format( "((MVA_%s-(%f))/(%f-(%f)))", methodS.Data(), mvaMin, mvaMax, mvaMin ); cout << "Expression = " << expr << endl; - tree->Project( "DataS", Form( "%s:%s", vary.Data(), varx.Data() ), - Form( "%s*(type==1)", expr.Data() ) ); - tree->Project( "DataB", Form( "%s:%s", vary.Data(), varx.Data() ), - Form( "%s*(type==0)", expr.Data() ) ); - tree->Project( "DataRS", Form( "%s:%s", vary.Data(), varx.Data() ), + tree->Project( "DataS", TString::Format( "%s:%s", vary.Data(), varx.Data() ), + TString::Format( "%s*(type==1)", expr.Data() ) ); + tree->Project( "DataB", TString::Format( "%s:%s", vary.Data(), varx.Data() ), + TString::Format( "%s*(type==0)", expr.Data() ) ); + tree->Project( "DataRS", TString::Format( "%s:%s", vary.Data(), varx.Data() ), "type==1" ); - tree->Project( "DataRB", Form( "%s:%s", vary.Data(), varx.Data() ), + tree->Project( "DataRB", TString::Format( "%s:%s", vary.Data(), varx.Data() ), "type==0" ); - tree->Project( "RefS", Form( "%s:%s", vary.Data(), varx.Data() ), + tree->Project( "RefS", TString::Format( "%s:%s", vary.Data(), varx.Data() ), "type==1", "", 500000 ); - tree->Project( "RefB", Form( "%s:%s", vary.Data(), varx.Data() ), + tree->Project( "RefB", TString::Format( "%s:%s", vary.Data(), varx.Data() ), "type==0", "", 500000, 10000 ); Float_t zminS = frameS->GetMinimum(); Float_t zmaxS = frameS->GetMaximum(); Float_t zminB = frameB->GetMinimum(); Float_t zmaxB = frameB->GetMaximum(); - // normalise + // normalise for (Int_t i=1; i<=nbin; i++) { for (Int_t j=1; j<=nbin; j++) { // signal @@ -125,7 +125,7 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) zmaxS = frameS->GetMaximum(); zminB = frameB->GetMinimum(); zmaxB = frameB->GetMaximum(); - // renormalise + // renormalise for (Int_t i=1; i<=nbin; i++) { for (Int_t j=1; j<=nbin; j++) { // signal @@ -145,9 +145,9 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) frameS->SetMaximum( +1.0 ); frameB->SetMinimum( -1.0 ); frameB->SetMaximum( +1.0 ); - + // axis labels - frame->SetTitle( Form( "Signal and background distributions weighted by %s output", + frame->SetTitle( TString::Format( "Signal and background distributions weighted by %s output", methodS.Data() ) ); frame->SetTitleSize( 0.08 ); frame->GetXaxis()->SetTitle( varx ); @@ -184,7 +184,7 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) // set style refS->SetMarkerSize( 0.2 ); refS->SetMarkerColor( 104 ); - + refB->SetMarkerSize( 0.2 ); refB->SetMarkerColor( 102 ); @@ -207,17 +207,17 @@ void TMVA::mvaweights( TString fin , Bool_t useTMVAStyle ) // and plot c->cd(1); - + frame->Draw(); frameS->Draw( "contsame" ); refS->Draw( "cont3same" ); - refB->Draw( "cont3same" ); + refB->Draw( "cont3same" ); // frameB->Draw( "colzsame" ); // save canvas to file c->Update(); if (Save_Images) { - TMVAGlob::imgconv( c, Form("plots/mvaweights_%s", methodS.Data()) ); + TMVAGlob::imgconv( c, TString::Format("plots/mvaweights_%s", methodS.Data()) ); } countCanvas++; } diff --git a/tmva/tmvagui/src/network.cxx b/tmva/tmvagui/src/network.cxx index 5acf76a8cd78a..983eda55c2a41 100644 --- a/tmva/tmvagui/src/network.cxx +++ b/tmva/tmvagui/src/network.cxx @@ -52,8 +52,8 @@ void TMVA::draw_network(TString dataset, TFile* f, TDirectory* d, const TString& Int_t ixc = 100 + (icanvas)*40; Int_t iyc = 0 + (icanvas+1)*20; if (MovieMode) ixc = iyc = 0; - TString canvasnumber = Form( "c%i", icanvas ); - TString canvastitle = Form("Neural Network Layout for: %s", d->GetName()); + TString canvasnumber = TString::Format( "c%i", icanvas ); + TString canvastitle = TString::Format("Neural Network Layout for: %s", d->GetName()); TCanvas* c = new TCanvas( canvasnumber, canvastitle, ixc, 0 + (icanvas+1)*20, 1000, 650 ); icanvas++; @@ -135,7 +135,7 @@ void TMVA::draw_network(TString dataset, TFile* f, TDirectory* d, const TString& t.SetTextColor( 0 ); t.SetTextAlign( 31 ); t.DrawTextNDC( 1 - c->GetRightMargin(), 1 - c->GetTopMargin() - 0.033, - Form( "Epoch: %s", epoch.Data() ) ); + TString::Format( "Epoch: %s", epoch.Data() ) ); } // ============================================================ @@ -178,7 +178,7 @@ void TMVA::draw_layer_labels(Int_t nLayers) Double_t margY = LABEL_HEIGHT - height; for (Int_t i = 0; i < nLayers; i++) { - TString label = Form("Layer %i", i); + TString label = TString::Format("Layer %i", i); if (i == nLayers-1) label = "Output layer"; Double_t cx = i*(1.0-LABEL_WIDTH)/nLayers+1.0/(2.0*nLayers)+LABEL_WIDTH; Double_t x1 = cx-0.8*effWidth/2.0; @@ -186,7 +186,7 @@ void TMVA::draw_layer_labels(Int_t nLayers) Double_t y1 = margY; Double_t y2 = margY + height; - TPaveLabel *p = new TPaveLabel(x1, y1, x2, y2, label+"", "br"); + TPaveLabel *p = new TPaveLabel(x1, y1, x2, y2, label, "br"); p->SetFillColor(gStyle->GetTitleFillColor()); p->SetTextColor(gStyle->GetTitleTextColor()); p->SetFillStyle(1001); @@ -309,8 +309,8 @@ void TMVA::draw_activation(TCanvas* c, Double_t cx, Double_t cy, radx *= 0.7; rady *= 0.7; - TString name = Form("activation%f%f", cx, cy); - TPad* p = new TPad(name+"", name+"", cx-radx, cy-rady, cx+radx, cy+rady); + TString name = TString::Format("activation%f%f", cx, cy); + TPad* p = new TPad(name, name, cx-radx, cy-rady, cx+radx, cy+rady); p->Draw(); p->cd(); diff --git a/tmva/tmvagui/src/paracoor.cxx b/tmva/tmvagui/src/paracoor.cxx index 62e606e45f639..a86cbdd978368 100644 --- a/tmva/tmvagui/src/paracoor.cxx +++ b/tmva/tmvagui/src/paracoor.cxx @@ -18,7 +18,7 @@ void TMVA::paracoor(TString dataset, TString fin , Bool_t useTMVAStyle ) TMVAGlob::Initialize( useTMVAStyle ); // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); TTree* tree = (TTree*)file->GetDirectory(dataset.Data())->Get("TestTree"); if(!tree) { cout << "--- No TestTree saved in ROOT file. Parallel coordinates will not be plotted" << endl; @@ -28,13 +28,13 @@ void TMVA::paracoor(TString dataset, TString fin , Bool_t useTMVAStyle ) // first get list of leaves in tree TObjArray* leafList = tree->GetListOfLeaves(); vector vars; - vector mvas; + vector mvas; for (Int_t iar=0; iarGetSize(); iar++) { TLeaf* leaf = (TLeaf*)leafList->At(iar); if (leaf != 0) { TString leafName = leaf->GetName(); if (leafName != "type" && leafName != "weight" && leafName != "boostweight" && - leafName != "class" && leafName != "className" && leafName != "classID" && + leafName != "class" && leafName != "className" && leafName != "classID" && !leafName.Contains("prob_")) { // is MVA ? if (TMVAGlob::ExistMethodName( leafName,file->GetDirectory(dataset.Data()) )) { @@ -49,7 +49,7 @@ void TMVA::paracoor(TString dataset, TString fin , Bool_t useTMVAStyle ) cout << "--- Found: " << vars.size() << " variables" << endl; cout << "--- Found: " << mvas.size() << " MVA(s)" << endl; - + TString type[2] = { "Signal", "Background" }; for (UInt_t imva=0; imvaDraw( varstr.Data(), Form("classID==%i",1-itype) , "para" ); + auto c1 = new TCanvas( TString::Format( "c1_%i_%s",itype,mvashort.Data() ), + TString::Format( "Parallel coordinate representation for %s and input variables (%s events)", + mvashort.Data(), type[itype].Data() ), + 50*(itype), 50*(itype), 750, 500 ); + tree->Draw( varstr.Data(), TString::Format("classID==%i",1-itype) , "para" ); c1->ToggleEditor(); gStyle->SetOptTitle(0); @@ -100,12 +100,12 @@ void TMVA::paracoor(TString dataset, TString fin , Bool_t useTMVAStyle ) parrange->SetLineColor( ivar == 0 ? 2 : ivar == 1 ? 5 : 6 ); var->AddRange( parrange ); - para->AddSelection( Form("%i",ivar) ); + para->AddSelection( TString::Format("%i",ivar) ); } c1->Update(); - TString fname = Form( "%s/plots/paracoor_c%i_%s",dataset.Data(), imva, itype == 0 ? "S" : "B" ); + TString fname = TString::Format( "%s/plots/paracoor_c%i_%s",dataset.Data(), imva, itype == 0 ? "S" : "B" ); TMVAGlob::imgconv( c1, fname ); } } diff --git a/tmva/tmvagui/src/probas.cxx b/tmva/tmvagui/src/probas.cxx index 6a3b2cdd279fa..6a295731809d6 100644 --- a/tmva/tmvagui/src/probas.cxx +++ b/tmva/tmvagui/src/probas.cxx @@ -30,7 +30,7 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) const Bool_t Save_Images = kTRUE; // checks if file with name "fin" is already open, and if not opens one - TFile* file = TMVAGlob::OpenFile( fin ); + TFile* file = TMVAGlob::OpenFile( fin ); const Int_t width = 600; // size of canvas @@ -58,7 +58,7 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) char fname[fnameSize]; TH1* sig(0); TH1* bgd(0); - + while ( (key = (TKey*)next()) ) { TDirectory * mDir = (TDirectory*)key->ReadObj(); @@ -73,7 +73,7 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) TIter nextTitle(&titles); TKey *instkey; TDirectory *instDir; - + // iterate over all classifiers while ( (instkey = (TKey *)nextTitle()) ) { instDir = (TDirectory *)instkey->ReadObj(); @@ -88,9 +88,9 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) while ( (hkey = (TKey*)nextInDir()) ) { TH1 *th1 = (TH1*)hkey->ReadObj(); TString hname= th1->GetName(); - if (hname.Contains( suffixSig ) && !hname.Contains( "Cut") && + if (hname.Contains( suffixSig ) && !hname.Contains( "Cut") && !hname.Contains("original") && !hname.Contains("smoothed")) { - // retrieve corresponding signal and background histograms + // retrieve corresponding signal and background histograms TString hnameS = hname; TString hnameB = hname; hnameB.ReplaceAll("_S","_B"); @@ -104,11 +104,11 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) TH1* sigF(0); TH1* bkgF(0); - + for (int i=0; i<= 5; i++) { - TString hspline = hnameS + Form("_smoothed_hist_from_spline%i",i); + TString hspline = hnameS + TString::Format("_smoothed_hist_from_spline%i",i); sigF = (TH1*)instDir->Get( hspline ); - + if (sigF) { bkgF = (TH1*)instDir->Get( hspline.ReplaceAll("_tr_S","_tr_B") ); break; @@ -117,12 +117,12 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) if (!sigF){ TString hspline = hnameS + TString("_smoothed_hist_from_KDE"); sigF = (TH1*)instDir->Get( hspline ); - + if (sigF) { bkgF = (TH1*)instDir->Get( hspline.ReplaceAll("_tr_S","_tr_B") ); } } - + if ((sigF == NULL || bkgF == NULL) &&!hname.Contains("hist") ) { cout << "*** probas.C: big troubles - did not find probability histograms" << endl; return; @@ -132,48 +132,48 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) // check that exist if (NULL != sigF && NULL != bkgF && NULL!=sig && NULL!=bgd) { - + found = kTRUE; // chop off useless stuff sig->SetTitle( TString("TMVA output for classifier: ") + methodTitle ); - + // create new canvas cout << "--- Book canvas no: " << countCanvas << endl; char cn[20]; snprintf( cn, 20, "canvas%d", countCanvas+1 ); - c = new TCanvas( cn, Form("TMVA Output Fit Variables %s",methodTitle.Data()), - countCanvas*50+200, countCanvas*20, width, width*0.78 ); - + c = new TCanvas( cn, TString::Format("TMVA Output Fit Variables %s",methodTitle.Data()), + countCanvas*50+200, countCanvas*20, width, width*0.78 ); + // set the histogram style TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd ); TMVAGlob::SetSignalAndBackgroundStyle( sigF, bkgF ); - + // frame limits (choose judicuous x range) Float_t nrms = 4; - Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), + Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), bgd->GetMean() - nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmin() ); - Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), + Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), bgd->GetMean() + nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmax() ); Float_t ymin = 0; Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*1.5; - + if (Draw_CFANN_Logy && methodName == "CFANN") ymin = 0.01; - + // build a frame Int_t nb = 500; - TH2F* frame = new TH2F( TString("frame") + sig->GetName() + "_proba", sig->GetTitle(), + TH2F* frame = new TH2F( TString("frame") + sig->GetName() + "_proba", sig->GetTitle(), nb, xmin, xmax, nb, ymin, ymax ); frame->GetXaxis()->SetTitle(methodTitle); frame->GetYaxis()->SetTitle("Normalized"); TMVAGlob::SetFrameStyle( frame ); - + // eventually: draw the frame - frame->Draw(); - + frame->Draw(); + if (Draw_CFANN_Logy && methodName == "CFANN") c->SetLogy(); - + // overlay signal and background histograms sig->SetMarkerColor( TMVAGlob::getSignalLine() ); sig->SetMarkerSize( 0.7 ); @@ -187,17 +187,17 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) sig->Draw("samee"); bgd->Draw("samee"); - + sigF->SetFillStyle( 0 ); bkgF->SetFillStyle( 0 ); sigF->Draw("samehist"); bkgF->Draw("samehist"); - + // redraw axes frame->Draw("sameaxis"); - - // Draw legend - TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.2, + + // Draw legend + TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.2, c->GetLeftMargin() + 0.4, 1 - c->GetTopMargin() ); legend->AddEntry(sig,"Signal data","P"); legend->AddEntry(sigF,"Signal PDF","L"); @@ -206,7 +206,7 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) legend->Draw("same"); legend->SetBorderSize(1); legend->SetMargin( 0.3 ); - + // save canvas to file c->Update(); TMVAGlob::plot_logo(); @@ -216,11 +216,11 @@ void TMVA::probas(TString dataset, TString fin , Bool_t useTMVAStyle ) } } } - + } if(!found){ cout << "--- No PDFs found for method " << methodTitle << ". Did you request \"CreateMVAPdfs\" in the option string?" << endl; } - } + } } } diff --git a/tmva/tmvagui/src/regression_averagedevs.cxx b/tmva/tmvagui/src/regression_averagedevs.cxx index cacbc593ef02a..670c115cfde1a 100644 --- a/tmva/tmvagui/src/regression_averagedevs.cxx +++ b/tmva/tmvagui/src/regression_averagedevs.cxx @@ -40,8 +40,8 @@ void TMVA::regression_averagedevs(TString dataset,TString fin, Int_t Nevt, Bool_ if (debug) cout << "loop targets " << itrgt<SetGrid(); @@ -50,7 +50,7 @@ void TMVA::regression_averagedevs(TString dataset,TString fin, Int_t Nevt, Bool_ c->SetTopMargin(0.28); c->SetBottomMargin(0.1); - TString hNameRef(Form("regression_average_devs_target%d",itrgt)); + TString hNameRef = TString::Format("regression_average_devs_target%d",itrgt); const Int_t maxMethods = 100; // const Int_t maxTargets = 100; @@ -76,7 +76,7 @@ void TMVA::regression_averagedevs(TString dataset,TString fin, Int_t Nevt, Bool_ if (histKey->ReadObj()->InheritsFrom("TH1F") ){ TString s(histKey->ReadObj()->GetName()); if( !s.Contains("Quadr_Dev") ) continue; - if( !s.Contains(Form("target_%d_",itrgt))) continue; + if( !s.Contains(TString::Format("target_%d_",itrgt))) continue; Int_t ihist = 0 ; if( !s.Contains("best90perc") && s.Contains("train")) ihist=0; if( s.Contains("best90perc") && s.Contains("train")) ihist=1; @@ -95,7 +95,7 @@ void TMVA::regression_averagedevs(TString dataset,TString fin, Int_t Nevt, Bool_ } nMethods++; } - TH1F* haveragedevs= new TH1F(Form("haveragedevs%d",itrgt),ftit,nMethods,0.,nMethods); + TH1F* haveragedevs= new TH1F(TString::Format("haveragedevs%d",itrgt),ftit,nMethods,0.,nMethods); for (int i=0;iGetXaxis()->SetBinLabel(i+1, mvaNames[i]); haveragedevs->SetStats(0); TGraphErrors* graphTrainAv= new TGraphErrors(nMethods,x[0],m[0],ex[0],em[0]); @@ -126,18 +126,18 @@ void TMVA::regression_averagedevs(TString dataset,TString fin, Int_t Nevt, Bool_ TH1F *hr = c->DrawFrame(-1.,0.,nMethods+1, xmax); cout << endl; cout << "Training: Average Deviation between target " << itrgt <<" and estimate" << endl; - cout << Form("%-15s%-15s%-15s", "Method","Average Dev.","trunc. Aver.(90%)") <GetXaxis()->SetBinLabel(i+1," "); } cout << endl; cout << "Testing: Average Deviation between target " << itrgt <<" and estimate" << endl; - cout << Form("%-15s%-15s%-15s", "Method","Average Dev.","trunc. Aver.(90%)") < noPad) { c[countCanvas]->Update(); - TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); + TString fname = TString::Format( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); TMVAGlob::imgconv( c[countCanvas], fname ); // TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-( countCanvas++; @@ -285,7 +285,7 @@ void TMVA::rulevisCorr( TDirectory *rfdir, TDirectory *vardir, TDirectory *corrd if (countPad <= noPad) { c[countCanvas]->Update(); - TString fname = Form( "plots/%s_c%i", outfname[type].Data(), countCanvas+1 ); + TString fname = TString::Format( "plots/%s_c%i", outfname[type].Data(), countCanvas+1 ); TMVAGlob::imgconv( c[countCanvas], fname ); } } diff --git a/tmva/tmvagui/src/rulevisHists.cxx b/tmva/tmvagui/src/rulevisHists.cxx index 88850e9e527d0..f2e97a059ef5f 100644 --- a/tmva/tmvagui/src/rulevisHists.cxx +++ b/tmva/tmvagui/src/rulevisHists.cxx @@ -250,7 +250,7 @@ void TMVA::rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corr // save canvas to file if (countPad > noPad) { c[countCanvas]->Update(); - TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); + TString fname = TString::Format( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); TMVAGlob::imgconv( c[countCanvas], fname ); // TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-( countCanvas++; @@ -260,7 +260,7 @@ void TMVA::rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corr if (countPad <= noPad) { c[countCanvas]->Update(); - TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); + TString fname = TString::Format( "plots/%s_c%i", outputName.Data(), countCanvas+1 ); TMVAGlob::imgconv( c[countCanvas], fname ); } delete[] c; diff --git a/tmva/tmvagui/src/tmvaglob.cxx b/tmva/tmvagui/src/tmvaglob.cxx index c570d90d44662..09282ecc990ac 100644 --- a/tmva/tmvagui/src/tmvaglob.cxx +++ b/tmva/tmvagui/src/tmvaglob.cxx @@ -255,8 +255,8 @@ TImage * TMVA::TMVAGlob::findImage(const char * imageName) //TString tutorialPath = "$ROOTSYS/tutorials/tmva"; // look for the image in here TString tutorialPath = getenv ("ROOTSYS"); tutorialPath+="/tutorials/tmva"; - TImage *img(0); - TString fullName = Form("%s/%s", tutorialPath.Data(), imageName); + TImage *img = nullptr; + TString fullName = TString::Format("%s/%s", tutorialPath.Data(), imageName); Bool_t fileFound = ! gSystem->AccessPathName(fullName); if(fileFound) { diff --git a/tmva/tmvagui/src/variables.cxx b/tmva/tmvagui/src/variables.cxx index 132a6989719ca..6cb3801cee317 100644 --- a/tmva/tmvagui/src/variables.cxx +++ b/tmva/tmvagui/src/variables.cxx @@ -81,7 +81,7 @@ void TMVA::variables(TString dataset, TString fin, TString dirName , TString tit // create new canvas if (countPad%noPadPerCanv==0) { ++countCanvas; - canv = new TCanvas( Form("canvas%d", countCanvas), title, + canv = new TCanvas( TString::Format("canvas%d", countCanvas), title, countCanvas*50+50, countCanvas*20, width, height ); canv->Divide(xPad,yPad); canv->Draw(); @@ -152,11 +152,11 @@ void TMVA::variables(TString dataset, TString fin, TString dirName , TString tit Double_t dxo = sig->GetBinWidth(nbin+1); TString uoflow = ""; if (isRegression) { - uoflow = Form( "U/O-flow: %.1f%% / %.1f%%", + uoflow = TString::Format( "U/O-flow: %.1f%% / %.1f%%", sig->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100 ); } else { - uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", + uoflow = TString::Format( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 ); } @@ -169,7 +169,7 @@ void TMVA::variables(TString dataset, TString fin, TString dirName , TString tit // save canvas to file if (countPad%noPadPerCanv==0) { - TString fname = Form( "%s/plots/%s_c%i",dataset.Data(), outfname.Data(), countCanvas ); + TString fname = TString::Format( "%s/plots/%s_c%i",dataset.Data(), outfname.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); createNewFig = kFALSE; @@ -180,7 +180,7 @@ void TMVA::variables(TString dataset, TString fin, TString dirName , TString tit } if (createNewFig) { - TString fname = Form( "%s/plots/%s_c%i",dataset.Data(), outfname.Data(), countCanvas ); + TString fname = TString::Format( "%s/plots/%s_c%i",dataset.Data(), outfname.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); createNewFig = kFALSE; diff --git a/tmva/tmvagui/src/variablesMultiClass.cxx b/tmva/tmvagui/src/variablesMultiClass.cxx index afdd46bc7601c..7c5f2ef64db30 100644 --- a/tmva/tmvagui/src/variablesMultiClass.cxx +++ b/tmva/tmvagui/src/variablesMultiClass.cxx @@ -63,7 +63,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , Int_t countPad = 0; // loop over all objects in directory - TCanvas* canv = 0; + TCanvas* canv = nullptr; Bool_t createNewFig = kFALSE; TIter next(dir->GetListOfKeys()); @@ -96,7 +96,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , //create new canvas if (countPad%noPadPerCanv==0) { ++countCanvas; - canv = new TCanvas( Form("canvas%d", countCanvas), title, + canv = new TCanvas( TString::Format("canvas%d", countCanvas), title, countCanvas*50+50, countCanvas*20, width, height ); canv->Divide(xPad,yPad); canv->Draw(); @@ -107,7 +107,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , TObjArray hists; for(; classiter!=classnames.end(); ++classiter){ //assemble histogram names - TString hname(*variter + "__" + *classiter + "_" + tmp); + TString hname = *variter + "__" + *classiter + "_" + tmp; TH1 *hist = (TH1*)dir->Get(hname); //cout << "Looking for histgram " << hname << endl; if (hist == NULL) { @@ -184,7 +184,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , for(Int_t i=0; iGetBinContent(0)!=0 || ((TH1*)hists[i])->GetBinContent(nbin+1)!=0){ uoflow += *classiter; - uoflow += Form( " U/O-flow: %.1f / %.1f %%", + uoflow += TString::Format( " U/O-flow: %.1f / %.1f %%", ((TH1*)hists[i])->GetBinContent(0)*dxu*100, ((TH1*)hists[i])->GetBinContent(nbin+1)*dxo*100); } } @@ -198,7 +198,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , // save canvas to file if (countPad%noPadPerCanv==0) { - TString fname = dataset+Form( "/plots/%s_c%i", outfname.Data(), countCanvas ); + TString fname = dataset+TString::Format( "/plots/%s_c%i", outfname.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); createNewFig = kFALSE; @@ -209,7 +209,7 @@ void TMVA::variablesMultiClass(TString dataset, TString fin , TString dirName , } if (createNewFig) { - TString fname = dataset+Form( "/plots/%s_c%i", outfname.Data(), countCanvas ); + TString fname = dataset+TString::Format( "/plots/%s_c%i", outfname.Data(), countCanvas ); TMVAGlob::plot_logo(); TMVAGlob::imgconv( canv, fname ); createNewFig = kFALSE; diff --git a/tree/dataframe/CMakeLists.txt b/tree/dataframe/CMakeLists.txt index 212db60b18e0f..2400734d8a973 100644 --- a/tree/dataframe/CMakeLists.txt +++ b/tree/dataframe/CMakeLists.txt @@ -31,6 +31,11 @@ if (imt) list(APPEND RDATAFRAME_EXTRA_DEPS Imt) endif(imt) +set (EXTRA_DICT_OPTS) +if (runtime_cxxmodules AND WIN32) + set (EXTRA_DICT_OPTS NO_CXXMODULE) +endif() + ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame HEADERS ROOT/RCsvDS.hxx @@ -57,11 +62,11 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame ROOT/RDF/RSampleInfo.hxx ROOT/RDF/RDefineBase.hxx ROOT/RDF/RDefine.hxx + ROOT/RDF/RDefinePerSample.hxx ROOT/RDF/RDefineReader.hxx ROOT/RDF/RDSColumnReader.hxx ROOT/RDF/RColumnReaderBase.hxx ROOT/RDF/RCutFlowReport.hxx - ROOT/RDF/RDatasetGroup.hxx ROOT/RDF/RDatasetSpec.hxx ROOT/RDF/RDisplay.hxx ROOT/RDF/RFilterBase.hxx @@ -80,6 +85,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame ROOT/RDF/RRangeBase.hxx ROOT/RDF/RRange.hxx ROOT/RDF/RResultMap.hxx + ROOT/RDF/RSample.hxx ROOT/RDF/RTreeColumnReader.hxx ROOT/RDF/RVariation.hxx ROOT/RDF/RVariationBase.hxx @@ -96,7 +102,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame src/RDefineBase.cxx src/RCutFlowReport.cxx src/RDataFrame.cxx - src/RDatasetGroup.cxx src/RDatasetSpec.cxx src/RDFActionHelpers.cxx src/RDFColumnRegister.cxx @@ -108,6 +113,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame src/RDFHelpers.cxx src/RFilterBase.cxx src/RInterfaceBase.cxx + src/RInterface.cxx src/RJittedAction.cxx src/RJittedDefine.cxx src/RJittedFilter.cxx @@ -115,6 +121,8 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame src/RLoopManager.cxx src/RMetaData.cxx src/RRangeBase.cxx + src/RSample.cxx + src/RResultPtr.cxx src/RVariationBase.cxx src/RVariationsDescription.cxx src/RRootDS.cxx @@ -130,6 +138,7 @@ ROOT_STANDARD_LIBRARY_PACKAGE(ROOTDataFrame RIO ROOTVecOps ${RDATAFRAME_EXTRA_DEPS} + ${EXTRA_DICT_OPTS} ) if(arrow) diff --git a/tree/dataframe/inc/LinkDef.h b/tree/dataframe/inc/LinkDef.h index 95d0c95b6f430..0baaba4491ce5 100644 --- a/tree/dataframe/inc/LinkDef.h +++ b/tree/dataframe/inc/LinkDef.h @@ -55,6 +55,7 @@ #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; +#pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; #pragma link C++ class ROOT::Detail::RDF::RMergeableValue+; diff --git a/tree/dataframe/inc/ROOT/RArrowDS.hxx b/tree/dataframe/inc/ROOT/RArrowDS.hxx index ad81716a09067..7eadd44d9e6f7 100644 --- a/tree/dataframe/inc/ROOT/RArrowDS.hxx +++ b/tree/dataframe/inc/ROOT/RArrowDS.hxx @@ -54,9 +54,6 @@ public: RDataFrame FromArrow(std::shared_ptr table, std::vector const &columnNames); -R__DEPRECATED(6, 30, "Use FromArrow instead.") -RDataFrame MakeArrowDataFrame(std::shared_ptr table, std::vector const &columnNames); - } // namespace RDF } // namespace ROOT diff --git a/tree/dataframe/inc/ROOT/RCsvDS.hxx b/tree/dataframe/inc/ROOT/RCsvDS.hxx index f473640e31ddb..52134c62eff9e 100644 --- a/tree/dataframe/inc/ROOT/RCsvDS.hxx +++ b/tree/dataframe/inc/ROOT/RCsvDS.hxx @@ -50,12 +50,12 @@ private: const Long64_t fLinesChunkSize; ULong64_t fEntryRangesRequested = 0ULL; ULong64_t fProcessedLines = 0ULL; // marks the progress of the consumption of the csv lines - std::vector fHeaders; + std::vector fHeaders; // the column names std::unordered_map fColTypes; std::set fColContainingEmpty; // store columns which had empty entry - std::list fColTypesList; - std::vector> fColAddresses; // fColAddresses[column][slot] - std::vector fRecords; // fRecords[entry][column] + std::list fColTypesList; // column types, order is the same as fHeaders, values the same as fColTypes + std::vector> fColAddresses; // fColAddresses[column][slot] (same ordering as fHeaders) + std::vector fRecords; // fRecords[entry][column] (same ordering as fHeaders) std::vector> fDoubleEvtValues; // one per column per slot std::vector> fLong64EvtValues; // one per column per slot std::vector> fStringEvtValues; // one per column per slot @@ -105,14 +105,6 @@ public: RDataFrame FromCSV(std::string_view fileName, bool readHeaders = true, char delimiter = ',', Long64_t linesChunkSize = -1LL, std::unordered_map &&colTypes = {}); -//////////////////////////////////////////////////////////////////////////////////////////////// -/// \brief Factory method to create a CSV RDataFrame. -/// -/// Deprecated in favor of FromCSV(). -R__DEPRECATED(6, 30, "Use FromCSV instead.") -RDataFrame MakeCsvDataFrame(std::string_view fileName, bool readHeaders = true, char delimiter = ',', - Long64_t linesChunkSize = -1LL, std::unordered_map &&colTypes = {}); - } // ns RDF } // ns ROOT diff --git a/tree/dataframe/inc/ROOT/RDF/ActionHelpers.hxx b/tree/dataframe/inc/ROOT/RDF/ActionHelpers.hxx index 2ccc462fd0a16..742159c565735 100644 --- a/tree/dataframe/inc/ROOT/RDF/ActionHelpers.hxx +++ b/tree/dataframe/inc/ROOT/RDF/ActionHelpers.hxx @@ -262,7 +262,7 @@ public: void Exec(unsigned int slot, double v); void Exec(unsigned int slot, double v, double w); - template ::value || std::is_same::value, int> = 0> + template ::value, int> = 0> void Exec(unsigned int slot, const T &vs) { auto &thisBuf = fBuffers[slot]; @@ -302,12 +302,15 @@ public: thisWBuf.insert(thisWBuf.end(), vs.size(), w); } - // ROOT-10092: Filling with a scalar as first column and a collection as second is not supported template ::value && !IsDataContainer::value, int> = 0> - void Exec(unsigned int, const T &, const W &) + void Exec(unsigned int slot, const T v, const W &ws) { - throw std::runtime_error( - "Cannot fill object if the type of the first column is a scalar and the one of the second a container."); + UpdateMinMax(slot, v); + auto &thisBuf = fBuffers[slot]; + thisBuf.insert(thisBuf.end(), ws.size(), v); + + auto &thisWBuf = fWBuffers[slot]; + thisWBuf.insert(thisWBuf.end(), ws.begin(), ws.end()); } Hist_t &PartialUpdate(unsigned int); @@ -336,18 +339,6 @@ public: } }; -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -extern template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -extern template void -BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); - /// The generic Fill helper: it calls Fill on per-thread objects and then Merge to produce a final result. /// For one-dimensional histograms, if no axes are specified, RDataFrame uses BufferedFillHelper instead. template @@ -1647,6 +1638,24 @@ public: { return [this](unsigned int, const RSampleInfo &) mutable { fBranchAddressesNeedReset = true; }; } + + /** + * @brief Create a new SnapshotHelper with a different output file name + * + * @param newName A type-erased string with the output file name + * @return SnapshotHelper + * + * This MakeNew implementation is tied to the cloning feature of actions + * of the computation graph. In particular, cloning a Snapshot node usually + * also involves changing the name of the output file, otherwise the cloned + * Snapshot would overwrite the same file. + */ + SnapshotHelper MakeNew(void *newName) + { + const std::string finalName = *reinterpret_cast(newName); + return SnapshotHelper{ + finalName, fDirName, fTreeName, fInputBranchNames, fOutputBranchNames, fOptions, std::vector(fIsDefine)}; + } }; /// Helper object for a multi-thread Snapshot action @@ -1814,6 +1823,24 @@ public: { return [this](unsigned int slot, const RSampleInfo &) mutable { fBranchAddressesNeedReset[slot] = 1; }; } + + /** + * @brief Create a new SnapshotHelperMT with a different output file name + * + * @param newName A type-erased string with the output file name + * @return SnapshotHelperMT + * + * This MakeNew implementation is tied to the cloning feature of actions + * of the computation graph. In particular, cloning a Snapshot node usually + * also involves changing the name of the output file, otherwise the cloned + * Snapshot would overwrite the same file. + */ + SnapshotHelperMT MakeNew(void *newName) + { + const std::string finalName = *reinterpret_cast(newName); + return SnapshotHelperMT{fNSlots, finalName, fDirName, fTreeName, + fInputBranchNames, fOutputBranchNames, fOptions, std::vector(fIsDefine)}; + } }; template &h, const uns { auto hasAxisLimits = HistoUtils<::TH1D>::HasAxisLimits(*h); - if (hasAxisLimits) { + if (hasAxisLimits || !IsImplicitMTEnabled()) { using Helper_t = FillHelper<::TH1D>; using Action_t = RAction>; return std::make_unique(Helper_t(h, nSlots), bl, std::move(prevNode), colRegister); @@ -236,8 +236,7 @@ using displayHelperArgs_t = std::pair std::unique_ptr BuildAction(const ColumnNames_t &bl, const std::shared_ptr &helperArgs, const unsigned int, - std::shared_ptr prevNode, ActionTags::Display, - const RDFInternal::RColumnRegister &colRegister) + std::shared_ptr prevNode, ActionTags::Display, const RColumnRegister &colRegister) { using Helper_t = DisplayHelper; using Action_t = RAction>; @@ -270,7 +269,7 @@ BuildAction(const ColumnNames_t &colNames, const std::shared_ptr isDef; isDef.reserve(sizeof...(ColTypes)); for (auto i = 0u; i < sizeof...(ColTypes); ++i) - isDef[i] = colRegister.IsDefineOrAlias(colNames[i]); + isDef.push_back(colRegister.IsDefineOrAlias(colNames[i])); return isDef; }; std::vector isDefine = makeIsDefine(); @@ -763,8 +762,6 @@ struct IsDeque_t> : std::true_type {}; void CheckForDuplicateSnapshotColumns(const ColumnNames_t &cols); -void TriggerRun(ROOT::RDF::RNode &node); - template struct InnerValueType { using type = T; // fallback for when T is not a nested RVec diff --git a/tree/dataframe/inc/ROOT/RDF/RAction.hxx b/tree/dataframe/inc/ROOT/RDF/RAction.hxx index 3ea9e4aa2ed8f..ac7c383a51d4f 100644 --- a/tree/dataframe/inc/ROOT/RDF/RAction.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RAction.hxx @@ -33,8 +33,7 @@ namespace RDFDetail = ROOT::Detail::RDF; namespace RDFGraphDrawing = ROOT::Internal::RDF::GraphDrawing; namespace GraphDrawing { -std::shared_ptr AddDefinesToGraph(std::shared_ptr node, - const RDFInternal::RColumnRegister &colRegister, +std::shared_ptr AddDefinesToGraph(std::shared_ptr node, const RColumnRegister &colRegister, const std::vector &prevNodeDefines, std::unordered_map> &visitedMap); } // namespace GraphDrawing @@ -93,9 +92,9 @@ public: void InitSlot(TTreeReader *r, unsigned int slot) final { - RDFInternal::RColumnReadersInfo info{RActionBase::GetColumnNames(), RActionBase::GetColRegister(), - fIsDefine.data(), *fLoopManager}; - fValues[slot] = RDFInternal::GetColumnReaders(slot, r, ColumnTypes_t{}, info); + RColumnReadersInfo info{RActionBase::GetColumnNames(), RActionBase::GetColRegister(), fIsDefine.data(), + *fLoopManager}; + fValues[slot] = GetColumnReaders(slot, r, ColumnTypes_t{}, info); fHelper.InitTask(r, slot); } @@ -168,8 +167,19 @@ public: std::move(helpers), GetColumnNames(), fPrevNodePtr, GetColRegister()}); } -private: + /** + * \brief Returns a new action with a cloned helper. + * + * \param[in] newResult The result to be filled by the new action (needed to clone the helper). + * \return A unique pointer to the new action. + */ + std::unique_ptr CloneAction(void *newResult) final + { + return std::make_unique(fHelper.CallMakeNew(newResult), GetColumnNames(), fPrevNodePtr, + GetColRegister()); + } +private: ROOT::RDF::SampleCallback_t GetSampleCallback() final { return fHelper.GetSampleCallback(); } }; diff --git a/tree/dataframe/inc/ROOT/RDF/RActionBase.hxx b/tree/dataframe/inc/ROOT/RDF/RActionBase.hxx index 3544f5cacb6bb..5fe82f5b2115b 100644 --- a/tree/dataframe/inc/ROOT/RDF/RActionBase.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RActionBase.hxx @@ -91,6 +91,7 @@ public: const std::vector &GetVariations() const { return fVariations; } virtual std::unique_ptr MakeVariedAction(std::vector &&results) = 0; + virtual std::unique_ptr CloneAction(void *newResult) = 0; }; } // namespace RDF } // namespace Internal diff --git a/tree/dataframe/inc/ROOT/RDF/RDFDescription.hxx b/tree/dataframe/inc/ROOT/RDF/RDFDescription.hxx index 4526e6f6a61f8..3e858b151678f 100644 --- a/tree/dataframe/inc/ROOT/RDF/RDFDescription.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RDFDescription.hxx @@ -28,12 +28,16 @@ class RDFDescription { std::string fBriefDescription; std::string fFullDescription; + unsigned int fFileCount; public: RDFDescription(const std::string &briefDescription, const std::string &fullDescription); + RDFDescription(const std::string &briefDescription, const std::string &fullDescription, unsigned int filecount); std::string AsString(bool shortFormat = false) const; + unsigned int GetNFiles() const { return fFileCount; } + void Print(bool shortFormat = false) const; friend std::ostream &operator<<(std::ostream &os, const RDFDescription &description); diff --git a/tree/dataframe/inc/ROOT/RDF/RDatasetSpec.hxx b/tree/dataframe/inc/ROOT/RDF/RDatasetSpec.hxx index d39da33f260de..40b754ab6469a 100644 --- a/tree/dataframe/inc/ROOT/RDF/RDatasetSpec.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RDatasetSpec.hxx @@ -16,11 +16,16 @@ #include // std::pair #include -#include +#include #include #include // Long64_t namespace ROOT { +namespace Detail { +namespace RDF { +class RLoopManager; +} +} // namespace Detail namespace RDF { namespace Experimental { @@ -29,6 +34,8 @@ namespace Experimental { \brief A dataset specification for RDataFrame. */ class RDatasetSpec { + friend class ::ROOT::Detail::RDF::RLoopManager; // for MoveOutSamples + public: struct REntryRange { Long64_t fBegin{0}; @@ -39,14 +46,16 @@ public: }; private: - std::vector fDatasetGroups; ///< List of groups + std::vector fSamples; ///< List of samples ROOT::TreeUtils::RFriendInfo fFriendInfo; ///< List of friends REntryRange fEntryRange; ///< Start (inclusive) and end (exclusive) entry for the dataset processing + std::vector MoveOutSamples(); + public: RDatasetSpec() = default; - const std::vector GetGroupNames() const; + const std::vector GetSampleNames() const; const std::vector GetTreeNames() const; const std::vector GetFileNameGlobs() const; const std::vector GetMetaData() const; @@ -54,11 +63,7 @@ public: Long64_t GetEntryRangeBegin() const; Long64_t GetEntryRangeEnd() const; - /// \cond HIDDEN_SYMBOLS - const std::vector &GetDatasetGroups() const; - /// \endcond - - RDatasetSpec &AddGroup(RDatasetGroup datasetGroup); + RDatasetSpec &AddSample(RSample sample); RDatasetSpec & WithGlobalFriends(const std::string &treeName, const std::string &fileNameGlob, const std::string &alias = ""); diff --git a/tree/dataframe/inc/ROOT/RDF/RDisplay.hxx b/tree/dataframe/inc/ROOT/RDF/RDisplay.hxx index 7b6b1ed79dcef..08c9409fef18f 100644 --- a/tree/dataframe/inc/ROOT/RDF/RDisplay.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RDisplay.hxx @@ -165,9 +165,11 @@ private: /// string representation of the array of chars. bool AddInterpreterString(std::stringstream &, ROOT::RVec &boolArr, const int &index) { - fCollectionsRepresentations[index].reserve(boolArr.size()); + auto &collRepr = fCollectionsRepresentations[index]; + collRepr.clear(); + collRepr.reserve(boolArr.size()); for (bool b : boolArr) - fCollectionsRepresentations[index].push_back(b ? "true" : "false"); + collRepr.push_back(b ? "true" : "false"); return true; // treat this as a collection } diff --git a/tree/dataframe/inc/ROOT/RDF/RFilter.hxx b/tree/dataframe/inc/ROOT/RDF/RFilter.hxx index 77b7d1cfb7a19..a0354b9596cb1 100644 --- a/tree/dataframe/inc/ROOT/RDF/RFilter.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RFilter.hxx @@ -39,8 +39,7 @@ namespace GraphDrawing { std::shared_ptr CreateFilterNode(const RFilterBase *filterPtr, std::unordered_map> &visitedMap); -std::shared_ptr AddDefinesToGraph(std::shared_ptr node, - const RDFInternal::RColumnRegister &colRegister, +std::shared_ptr AddDefinesToGraph(std::shared_ptr node, const RColumnRegister &colRegister, const std::vector &prevNodeDefines, std::unordered_map> &visitedMap); } // ns GraphDrawing @@ -191,6 +190,8 @@ public: /// Return a clone of this Filter that works with values in the variationName "universe". std::shared_ptr GetVariedFilter(const std::string &variationName) final { + // Only the nominal filter should be asked to produce varied filters + assert(fVariation == "nominal"); // nobody should ask for a varied filter for the nominal variation: they can just // use the nominal filter! assert(variationName != "nominal"); diff --git a/tree/dataframe/inc/ROOT/RDF/RInterface.hxx b/tree/dataframe/inc/ROOT/RDF/RInterface.hxx index da5569bec3d81..f55a1e0ea9693 100644 --- a/tree/dataframe/inc/ROOT/RDF/RInterface.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RInterface.hxx @@ -66,11 +66,6 @@ void DisableImplicitMT(); bool IsImplicitMTEnabled(); void EnableImplicitMT(UInt_t numthreads); class RDataFrame; -namespace Internal { -namespace RDF { -class GraphCreatorHelper; -} -} // namespace Internal } // namespace ROOT namespace cling { std::string printValue(ROOT::RDataFrame *tdf); @@ -86,6 +81,18 @@ template class RInterface; using RNode = RInterface<::ROOT::Detail::RDF::RNodeBase, void>; +} // namespace RDF + +namespace Internal { +namespace RDF { +class GraphCreatorHelper; +void ChangeEmptyEntryRange(const ROOT::RDF::RNode &node, std::pair &&newRange); +void ChangeSpec(const ROOT::RDF::RNode &node, ROOT::RDF::Experimental::RDatasetSpec &&spec); +void TriggerRun(ROOT::RDF::RNode node); +} // namespace RDF +} // namespace Internal + +namespace RDF { // clang-format off /** @@ -111,7 +118,9 @@ class RInterface : public RInterfaceBase { template friend class RInterface; - friend void RDFInternal::TriggerRun(RNode &node); + friend void RDFInternal::TriggerRun(RNode node); + friend void RDFInternal::ChangeEmptyEntryRange(const RNode &node, std::pair &&newRange); + friend void RDFInternal::ChangeSpec(const RNode &node, ROOT::RDF::Experimental::RDatasetSpec &&spec); std::shared_ptr fProxiedPtr; ///< Smart pointer to the graph node encapsulated by this RInterface. @@ -666,6 +675,15 @@ public: /// hx["nominal"].Draw(); /// hx["pt:down"].Draw("SAME"); /// ~~~ + /// RDataFrame computes all variations as part of a single loop over the data. + /// In particular, this means that I/O and computation of values shared + /// among variations only happen once for all variations. Thus, the event loop + /// run-time typically scales much better than linearly with the number of + /// variations. + /// + /// RDataFrame lazily computes the varied values required to produce the + /// outputs of VariationsFor(). If VariationsFor() was not called for a result, + /// the computations run are only for the nominal case. template RInterface Vary(std::string_view colName, F &&expression, const ColumnNames_t &inputColumns, const std::vector &variationTags, std::string_view variationName = "") @@ -719,6 +737,15 @@ public: return VaryImpl(colNames, std::forward(expression), inputColumns, variationTags, variationName); } + /// Overload to avoid ambiguity between C++20 string, vector construction from init list. + template + RInterface + Vary(std::initializer_list colNames, F &&expression, const ColumnNames_t &inputColumns, + const std::vector &variationTags, std::string_view variationName) + { + return Vary(std::vector(colNames), std::forward(expression), inputColumns, variationTags, variationName); + } + /// \brief Register systematic variations for one or more existing columns using auto-generated tags. /// This overload of Vary takes a nVariations parameter instead of a list of tag names. Tag names /// will be auto-generated as the sequence 0...nVariations-1. @@ -738,6 +765,15 @@ public: return Vary(colNames, std::forward(expression), inputColumns, std::move(variationTags), variationName); } + /// Overload to avoid ambiguity between C++20 string, vector construction from init list. + template + RInterface + Vary(std::initializer_list colNames, F &&expression, const ColumnNames_t &inputColumns, + std::size_t nVariations, std::string_view variationName) + { + return Vary(std::vector(colNames), std::forward(expression), inputColumns, nVariations, variationName); + } + /// \brief Register systematic variations for an existing column. /// \param[in] colName name of the column for which varied values are provided. /// \param[in] expression a string containing valid C++ code that evaluates to an RVec containing the varied @@ -814,6 +850,13 @@ public: return Vary(colNames, expression, std::move(variationTags), variationName); } + /// Overload to avoid ambiguity between C++20 string, vector construction from init list. + RInterface Vary(std::initializer_list colNames, std::string_view expression, + std::size_t nVariations, std::string_view variationName) + { + return Vary(std::vector(colNames), expression, nVariations, variationName); + } + /// \brief Register systematic variations for one or more existing columns. /// \param[in] colNames names of the columns for which varied values are provided. /// \param[in] expression a string containing valid C++ code that evaluates to an RVec or RVecs containing the varied @@ -1864,8 +1907,8 @@ public: const auto validatedColumns = GetValidatedColumnNames(2, userColumns); // We build a default name and title based on the input columns - const auto g_name = validatedColumns[0] + "_vs_" + validatedColumns[1]; - const auto g_title = validatedColumns[0] + " vs " + validatedColumns[1]; + const auto g_name = validatedColumns[1] + "_vs_" + validatedColumns[0]; + const auto g_title = validatedColumns[1] + " vs " + validatedColumns[0]; graph->SetNameTitle(g_name.c_str(), g_title.c_str()); graph->GetXaxis()->SetTitle(validatedColumns[0].c_str()); graph->GetYaxis()->SetTitle(validatedColumns[1].c_str()); @@ -1918,8 +1961,8 @@ public: const auto validatedColumns = GetValidatedColumnNames(6, userColumns); // We build a default name and title based on the input columns - const auto g_name = validatedColumns[0] + "_vs_" + validatedColumns[1]; - const auto g_title = validatedColumns[0] + " vs " + validatedColumns[1]; + const auto g_name = validatedColumns[1] + "_vs_" + validatedColumns[0]; + const auto g_title = validatedColumns[1] + " vs " + validatedColumns[0]; graph->SetNameTitle(g_name.c_str(), g_title.c_str()); graph->GetXaxis()->SetTitle(validatedColumns[0].c_str()); graph->GetYaxis()->SetTitle(validatedColumns[1].c_str()); @@ -2029,7 +2072,7 @@ public: /// \brief Fill and return a two-dimensional profile (*lazy action*). /// \tparam V1 The type of the column used to fill the x axis of the histogram. Inferred if not present. /// \tparam V2 The type of the column used to fill the y axis of the histogram. Inferred if not present. - /// \tparam V2 The type of the column used to fill the z axis of the histogram. Inferred if not present. + /// \tparam V3 The type of the column used to fill the z axis of the histogram. Inferred if not present. /// \param[in] model The returned profile will be constructed using this as a model. /// \param[in] v1Name The name of the column that will fill the x axis. /// \param[in] v2Name The name of the column that will fill the y axis. @@ -2560,43 +2603,57 @@ public: /// \return the result of the helper wrapped in a RResultPtr. /// /// This method books a custom action for execution. The behavior of the action is completely dependent on the - /// Helper object provided by the caller. The minimum required interface for the helper is the following (more - /// methods can be present, e.g. a constructor that takes the number of worker threads is usually useful): + /// Helper object provided by the caller. The required interface for the helper is described below (more + /// methods that the ones required can be present, e.g. a constructor that takes the number of worker threads is usually useful): /// - /// * Helper must publicly inherit from ROOT::Detail::RDF::RActionImpl - /// * Helper(Helper &&): a move-constructor is required. Copy-constructors are discouraged. - /// * Result_t: alias for the type of the result of this action helper. Must be default-constructible. - /// * void Exec(unsigned int slot, ColumnTypes...columnValues): each working thread shall call this method + /// ### Mandatory interface + /// + /// * `Helper` must publicly inherit from `ROOT::Detail::RDF::RActionImpl` + /// * `Helper::Result_t`: public alias for the type of the result of this action helper. `Result_t` must be default-constructible. + /// * `Helper(Helper &&)`: a move-constructor is required. Copy-constructors are discouraged. + /// * `std::shared_ptr GetResultPtr() const`: return a shared_ptr to the result of this action (of type + /// Result_t). The RResultPtr returned by Book will point to this object. Note that this method can be called + /// _before_ Initialize(), because the RResultPtr is constructed before the event loop is started. + /// * `void Initialize()`: this method is called once before starting the event-loop. Useful for setup operations. + /// It must reset the state of the helper to the expected state at the beginning of the event loop: the same helper, + /// or copies of it, might be used for multiple event loops (e.g. in the presence of systematic variations). + /// * `void InitTask(TTreeReader *, unsigned int slot)`: each working thread shall call this method during the event + /// loop, before processing a batch of entries. The pointer passed as argument, if not null, will point to the TTreeReader + /// that RDataFrame has set up to read the task's batch of entries. It is passed to the helper to allow certain advanced optimizations + /// it should not usually serve any purpose for the Helper. This method is often no-op for simple helpers. + /// * `void Exec(unsigned int slot, ColumnTypes...columnValues)`: each working thread shall call this method /// during the event-loop, possibly concurrently. No two threads will ever call Exec with the same 'slot' value: /// this parameter is there to facilitate writing thread-safe helpers. The other arguments will be the values of /// the requested columns for the particular entry being processed. - /// * void InitTask(TTreeReader *, unsigned int slot): each working thread shall call this method during the event - /// loop, before processing a batch of entries (possibly read from the TTreeReader passed as argument, if not null). - /// This method can be used e.g. to prepare the helper to process a batch of entries in a given thread. Can be no-op. - /// * void Initialize(): this method is called once before starting the event-loop. Useful for setup operations. - /// It must reset the state of the helper to the expected state at the beginning of the event loop: the same helper, - /// or copies of it, might be used for multiple event loops (e.g. in the presence of systematic variations). - /// * void Finalize(): this method is called at the end of the event loop. Commonly used to finalize the contents of the result. - /// * Result_t &PartialUpdate(unsigned int slot): this method is optional, i.e. can be omitted. If present, it should - /// return the value of the partial result of this action for the given 'slot'. Different threads might call this - /// method concurrently, but will always pass different 'slot' numbers. - /// * std::shared_ptr GetResultPtr() const: return a shared_ptr to the result of this action (of type - /// Result_t). The RResultPtr returned by Book will point to this object. Note that this method can be called - /// before Initialize(), because the RResultPtr is constructed before the event loop is started. - /// * ROOT::RDF::SampleCallback_t GetSampleCallback(): optional. If present, it must return a callable with the + /// * `void Finalize()`: this method is called at the end of the event loop. Commonly used to finalize the contents of the result. + /// * `std::string GetActionName()`: it returns a string identifier for this type of action that RDataFrame will use in + /// diagnostics, SaveGraph(), etc. + /// + /// ### Optional methods + /// + /// If these methods are implemented they enable extra functionality as per the description below. + /// + /// * `Result_t &PartialUpdate(unsigned int slot)`: if present, it must return the value of the partial result of this action for the given 'slot'. + /// Different threads might call this method concurrently, but will do so with different 'slot' numbers. + /// RDataFrame leverages this method to implement RResultPtr::OnPartialResult(). + /// * `ROOT::RDF::SampleCallback_t GetSampleCallback()`: if present, it must return a callable with the /// appropriate signature (see ROOT::RDF::SampleCallback_t) that will be invoked at the beginning of the processing - /// of every sample, as per with DefinePerSample(). + /// of every sample, as in DefinePerSample(). + /// * `Helper MakeNew(void *newResult)`: if implemented, it enables varying the action's result with VariationsFor(). It takes a + /// type-erased new result that can be safely cast to a `std::shared_ptr *` (a pointer to shared pointer) and should + /// be used as the action's output result. + /// + /// In case Book is called without specifying column types as template arguments, corresponding typed code will be just-in-time compiled + /// by RDataFrame. In that case the Helper class needs to be known to the ROOT interpreter. /// - /// In case this is called without specifying column types, jitting is used, - /// and the Helper class needs to be known to the interpreter.
    /// This action is *lazy*: upon invocation of this method the calculation is booked but not executed. Also see RResultPtr. /// /// ### Examples - /// See [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html) for an example implementation of an action helper.
    + /// See [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html) for an example implementation of an action helper. + /// /// It is also possible to inspect the code used by built-in RDataFrame actions at ActionHelpers.hxx. /// // clang-format on - template RResultPtr::Result_t> Book(Helper &&helper, const ColumnNames_t &columns = {}) { @@ -2765,7 +2822,7 @@ private: bool IsFStringConv = std::is_convertible::value, bool IsRetTypeDefConstr = std::is_default_constructible::value> std::enable_if_t> - DefineImpl(std::string_view, F, const ColumnNames_t &) + DefineImpl(std::string_view, F, const ColumnNames_t &, const std::string &) { static_assert(std::is_default_constructible::ret_type>::value, "Error in `Define`: type returned by expression is not default-constructible"); diff --git a/tree/dataframe/inc/ROOT/RDF/RInterfaceBase.hxx b/tree/dataframe/inc/ROOT/RDF/RInterfaceBase.hxx index c5d1b65279aeb..13bc2482869e6 100644 --- a/tree/dataframe/inc/ROOT/RDF/RInterfaceBase.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RInterfaceBase.hxx @@ -11,6 +11,7 @@ #ifndef ROOT_RDF_RINTERFACEBASE #define ROOT_RDF_RINTERFACEBASE +#include "ROOT/RVec.hxx" #include #include #include @@ -80,10 +81,10 @@ protected: } RDFInternal::CheckValidCppVarName(variationName, "Vary"); - static_assert(RDFInternal::IsRVec::value, "Vary expressions must return an RVec."); + static_assert(ROOT::Internal::VecOps::IsRVec::value, "Vary expressions must return an RVec."); if (colNames.size() > 1) { // we are varying multiple columns simultaneously, RetType is RVec> - constexpr bool hasInnerRVec = RDFInternal::IsRVec::value; + constexpr bool hasInnerRVec = ROOT::Internal::VecOps::IsRVec::value; if (!hasInnerRVec) throw std::runtime_error("This Vary call is varying multiple columns simultaneously but the expression " "does not return an RVec of RVecs."); @@ -98,8 +99,8 @@ protected: for (auto i = 0u; i < colTypes.size(); ++i) { const auto *define = fColRegister.GetDefine(colNames[i]); - const auto &expectedTypeID = define ? define->GetTypeId() : RDFInternal::TypeName2TypeID(colTypes[i]); - if (innerTypeID != expectedTypeID) + const auto *expectedTypeID = define ? &define->GetTypeId() : &RDFInternal::TypeName2TypeID(colTypes[i]); + if (innerTypeID != *expectedTypeID) throw std::runtime_error("Varied values for column \"" + colNames[i] + "\" have a different type (" + RDFInternal::TypeID2TypeName(innerTypeID) + ") than the nominal value (" + colTypes[i] + ")."); @@ -108,9 +109,9 @@ protected: const auto &retTypeID = typeid(typename RetType::value_type); const auto &colName = colNames[0]; // we have only one element in there const auto *define = fColRegister.GetDefine(colName); - const auto &expectedTypeID = - define ? define->GetTypeId() : RDFInternal::TypeName2TypeID(GetColumnType(colName)); - if (retTypeID != expectedTypeID) + const auto *expectedTypeID = + define ? &define->GetTypeId() : &RDFInternal::TypeName2TypeID(GetColumnType(colName)); + if (retTypeID != *expectedTypeID) throw std::runtime_error("Varied values for column \"" + colName + "\" have a different type (" + RDFInternal::TypeID2TypeName(retTypeID) + ") than the nominal value (" + GetColumnType(colName) + ")."); @@ -209,6 +210,7 @@ public: ColumnNames_t GetDefinedColumnNames(); unsigned int GetNSlots() const; unsigned int GetNRuns() const; + unsigned int GetNFiles(); }; } // namespace RDF } // namespace ROOT diff --git a/tree/dataframe/inc/ROOT/RDF/RJittedAction.hxx b/tree/dataframe/inc/ROOT/RDF/RJittedAction.hxx index 51a6b3eccf8f0..621079bde40db 100644 --- a/tree/dataframe/inc/ROOT/RDF/RJittedAction.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RJittedAction.hxx @@ -66,6 +66,7 @@ public: ROOT::RDF::SampleCallback_t GetSampleCallback() final; std::unique_ptr MakeVariedAction(std::vector &&results) final; + std::unique_ptr CloneAction(void *newResult) final; }; } // ns RDF diff --git a/tree/dataframe/inc/ROOT/RDF/RLazyDSImpl.hxx b/tree/dataframe/inc/ROOT/RDF/RLazyDSImpl.hxx index 72c77ab81bc28..c7221d8203a56 100644 --- a/tree/dataframe/inc/ROOT/RDF/RLazyDSImpl.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RLazyDSImpl.hxx @@ -93,7 +93,7 @@ class RLazyDS final : public ROOT::RDF::RDataSource { } template - void ColLenghtChecker(std::index_sequence) + void ColLengthChecker(std::index_sequence) { if (sizeof...(S) < 2) return; @@ -181,7 +181,7 @@ public: void Initialize() final { - ColLenghtChecker(std::index_sequence_for()); + ColLengthChecker(std::index_sequence_for()); const auto nEntries = GetEntriesNumber(); const auto nEntriesInRange = nEntries / fNSlots; // between integers. Should make smaller? auto reminder = 1U == fNSlots ? 0 : nEntries % fNSlots; diff --git a/tree/dataframe/inc/ROOT/RDF/RLoopManager.hxx b/tree/dataframe/inc/ROOT/RDF/RLoopManager.hxx index cf193a5905966..4e5c9682b94b9 100644 --- a/tree/dataframe/inc/ROOT/RDF/RLoopManager.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RLoopManager.hxx @@ -125,20 +125,25 @@ class RLoopManager : public RNodeBase { Long64_t fBeginEntry{0}; Long64_t fEndEntry{std::numeric_limits::max()}; - /// Keys are `fname + "/" + treename` as RSampleInfo::fID; Values are pointers to the corresponding group - std::unordered_map fDatasetGroupMap; - /// Groups need to survive throughout the whole event loop, hence stored as an attribute - std::vector fDatasetGroups; + /// Keys are `fname + "/" + treename` as RSampleInfo::fID; Values are pointers to the corresponding sample + std::unordered_map fSampleMap; + /// Samples need to survive throughout the whole event loop, hence stored as an attribute + std::vector fSamples; - std::vector> fFriends; ///< Friends of the fTree. Only used if we constructed fTree ourselves. + /// Friends of the fTree. Only used if we constructed fTree ourselves. + std::vector> fFriends; const ColumnNames_t fDefaultColumns; - const ULong64_t fNEmptyEntries{0}; + /// Range of entries created when no data source is specified. + std::pair fEmptyEntryRange{}; const unsigned int fNSlots{1}; bool fMustRunNamedFilters{true}; const ELoopType fLoopType; ///< The kind of event loop that is going to be run (e.g. on ROOT files, on no files) const std::unique_ptr fDataSource; ///< Owning pointer to a data-source object. Null if no data-source - std::vector fCallbacks; ///< Registered callbacks - /// Registered callbacks to invoke just once before running the loop + /// Registered callbacks to be executed every N events. + /// The registration happens via the RegisterCallback method. + std::vector fCallbacksEveryNEvents; + /// Registered callbacks to invoke just once before running the loop. + /// The registration happens via the RegisterCallback method. std::vector fCallbacksOnce; /// Registered callbacks to call at the beginning of each "data block". /// The key is the pointer of the corresponding node in the computation graph (a RDefinePerSample or a RAction). @@ -186,7 +191,7 @@ public: const ColumnNames_t &GetDefaultColumnNames() const; TTree *GetTree() const; ::TDirectory *GetDirectory() const; - ULong64_t GetNEmptyEntries() const { return fNEmptyEntries; } + ULong64_t GetNEmptyEntries() const { return fEmptyEntryRange.second - fEmptyEntryRange.first; } RDataSource *GetDataSource() const { return fDataSource.get(); } void Register(RDFInternal::RActionBase *actionPtr); void Deregister(RDFInternal::RActionBase *actionPtr); @@ -234,6 +239,9 @@ public: const ColumnNames_t &GetBranchNames(); void AddSampleCallback(void *nodePtr, ROOT::RDF::SampleCallback_t &&callback); + + void SetEmptyEntryRange(std::pair &&newRange); + void ChangeSpec(ROOT::RDF::Experimental::RDatasetSpec &&spec); }; } // ns RDF diff --git a/tree/dataframe/inc/ROOT/RDF/RMetaData.hxx b/tree/dataframe/inc/ROOT/RDF/RMetaData.hxx index 2b143431fe08d..e2a343d69459a 100644 --- a/tree/dataframe/inc/ROOT/RDF/RMetaData.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RMetaData.hxx @@ -23,7 +23,7 @@ namespace Experimental { \ingroup dataframe \brief Class behaving as a heterogenuous dictionary to store dataset metadata - This class should be passed to an RDatasetGroup object which represents a single dataset group. + This class should be passed to an RSample object which represents a single dataset sample. Once a dataframe is built with RMetaData object, it could be accessed via DefinePerSample. */ class RMetaData { diff --git a/tree/dataframe/inc/ROOT/RDF/RRangeBase.hxx b/tree/dataframe/inc/ROOT/RDF/RRangeBase.hxx index eb049ce06f033..1dc8566eaba09 100644 --- a/tree/dataframe/inc/ROOT/RDF/RRangeBase.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RRangeBase.hxx @@ -27,7 +27,6 @@ class GraphNode; namespace Detail { namespace RDF { -namespace RDFGraphDrawing = ROOT::Internal::RDF::GraphDrawing; class RLoopManager; @@ -43,8 +42,6 @@ protected: const unsigned int fNSlots; ///< Number of thread slots used by this node, inherited from parent node. std::unordered_map> fVariedRanges; - void ResetCounters(); - public: RRangeBase(RLoopManager *implPtr, unsigned int start, unsigned int stop, unsigned int stride, const unsigned int nSlots, const std::vector &prevVariations); @@ -52,7 +49,7 @@ public: RRangeBase &operator=(const RRangeBase &) = delete; ~RRangeBase() override; - void InitNode() { ResetCounters(); } + void InitNode(); }; } // ns RDF diff --git a/tree/dataframe/inc/ROOT/RDF/RResultMap.hxx b/tree/dataframe/inc/ROOT/RDF/RResultMap.hxx index cd4d6452695bf..ec7f61b63baa1 100644 --- a/tree/dataframe/inc/ROOT/RDF/RResultMap.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RResultMap.hxx @@ -52,11 +52,46 @@ MakeResultMap(std::shared_ptr nominalResult, std::vector> return ROOT::RDF::Experimental::RResultMap(std::move(nominalResult), std::move(variedResults), std::move(keys), lm, std::move(nominalAction), std::move(variedAction)); } + +/** + * \brief Clones an RResultMap and its corresponding RVariedAction + * + * \tparam T The type of the results held by the map. + * \param inmap The map. + * \return ROOT::RDF::Experimental::RResultMap A new map with the cloned variations. + */ +template +ROOT::RDF::Experimental::RResultMap CloneResultAndAction(const ROOT::RDF::Experimental::RResultMap &inmap) +{ + std::shared_ptr nominalResult{inmap.fMap.at("nominal")}; + auto nominalAction{inmap.fNominalAction->CloneAction(reinterpret_cast(&nominalResult))}; + + std::size_t nVariations{inmap.fMap.size() - 1}; + std::vector> variedResults; + variedResults.reserve(nVariations); + for (auto i = 0u; i < nVariations; ++i) + variedResults.emplace_back(new T{*nominalResult}); + + std::vector typeErasedResults; + typeErasedResults.reserve(nVariations); + for (auto &res : variedResults) + typeErasedResults.push_back(&res); + auto variedAction{inmap.fVariedAction->CloneAction(reinterpret_cast(&typeErasedResults))}; + + std::vector variationNames{inmap.fKeys}; + Erase("nominal", variationNames); + + return ROOT::RDF::Experimental::RResultMap(std::move(nominalResult), std::move(variedResults), + std::move(variationNames), *(inmap.fLoopManager), + std::move(nominalAction), std::move(variedAction)); +} } // namespace RDF } // namespace Internal namespace RDF { +class RResultHandle; + namespace Experimental { template @@ -75,15 +110,17 @@ class RResultMap { std::shared_ptr nominalAction, std::shared_ptr variedAction); + friend RResultMap ROOT::Internal::RDF::CloneResultAndAction(const RResultMap &inmap); friend std::unique_ptr> ROOT::Detail::RDF::GetMergeableValue(RResultMap &rmap); + friend class ::ROOT::RDF::RResultHandle; // The preconditions are that results and keys have the same size, are ordered the same way, and keys are unique. RResultMap(std::shared_ptr &&nominalResult, std::vector> &&variedResults, std::vector &&keys, ROOT::Detail::RDF::RLoopManager &lm, std::shared_ptr nominalAction, std::shared_ptr variedAction) - : fKeys{ROOT::Internal::RDF::Union({"nominal"}, keys)}, fLoopManager(&lm), + : fKeys{ROOT::Internal::RDF::Union({std::string("nominal")}, keys)}, fLoopManager(&lm), fNominalAction(std::move(nominalAction)), fVariedAction(std::move(variedAction)) { R__ASSERT(variedResults.size() == keys.size() && "Keys and values have different sizes!"); diff --git a/tree/dataframe/inc/ROOT/RDF/RDatasetGroup.hxx b/tree/dataframe/inc/ROOT/RDF/RSample.hxx similarity index 53% rename from tree/dataframe/inc/ROOT/RDF/RDatasetGroup.hxx rename to tree/dataframe/inc/ROOT/RDF/RSample.hxx index 3ed067d321a92..e6e22ebd7bd3d 100644 --- a/tree/dataframe/inc/ROOT/RDF/RDatasetGroup.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RSample.hxx @@ -8,8 +8,8 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ -#ifndef ROOT_RDF_RDATASETGROUP -#define ROOT_RDF_RDATASETGROUP +#ifndef ROOT_RDF_RSAMPLE +#define ROOT_RDF_RSAMPLE #include @@ -22,12 +22,12 @@ namespace Experimental { /** \ingroup dataframe -\brief Class representing a dataset group (mapping of trees (and their fileglobs) to metadata) +\brief Class representing a sample (grouping of trees (and their fileglobs) and (optional) metadata) This class should be passed to RDatasetSpec in order to build a RDataFrame. */ -class RDatasetGroup { - std::string fGroupName; +class RSample { + std::string fSampleName; /** * A list of names of trees. * This list should go in lockstep with fFileNameGlobs, only in case this dataset is a TChain where each file @@ -42,36 +42,35 @@ class RDatasetGroup { std::vector fFileNameGlobs; RMetaData fMetaData; - unsigned int fGroupId{0}; // global group index, set inside of the RDatasetSpec + unsigned int fSampleId{0}; // global sample index, set inside of the RDatasetSpec public: - RDatasetGroup(RDatasetGroup &&) = default; - RDatasetGroup &operator=(RDatasetGroup &&) = default; - RDatasetGroup(const RDatasetGroup &) = default; - RDatasetGroup &operator=(const RDatasetGroup &) = default; - RDatasetGroup() = delete; + RSample(RSample &&) = default; + RSample &operator=(RSample &&) = default; + RSample(const RSample &) = default; + RSample &operator=(const RSample &) = default; + RSample() = delete; - RDatasetGroup(const std::string &groupName, const std::string &treeName, const std::string &fileNameGlob, - const RMetaData &metaData = {}); + RSample(const std::string &sampleName, const std::string &treeName, const std::string &fileNameGlob, + const RMetaData &metaData = {}); - RDatasetGroup(const std::string &groupName, const std::string &treeName, - const std::vector &fileNameGlobs, const RMetaData &metaData = {}); + RSample(const std::string &sampleName, const std::string &treeName, const std::vector &fileNameGlobs, + const RMetaData &metaData = {}); - RDatasetGroup(const std::string &groupName, - const std::vector> &treeAndFileNameGlobs, - const RMetaData &metaData = {}); + RSample(const std::string &sampleName, const std::vector> &treeAndFileNameGlobs, + const RMetaData &metaData = {}); - RDatasetGroup(const std::string &groupName, const std::vector &treeNames, - const std::vector &fileNameGlobs, const RMetaData &metaData = {}); + RSample(const std::string &sampleName, const std::vector &treeNames, + const std::vector &fileNameGlobs, const RMetaData &metaData = {}); - const std::string &GetGroupName() const; + const std::string &GetSampleName() const; const std::vector &GetTreeNames() const; const std::vector &GetFileNameGlobs() const; const RMetaData &GetMetaData() const; /// \cond HIDDEN_SYMBOLS - unsigned int GetGroupId() const; // intended to be used only after the RDataSpec is build, otherwise is 0 - void SetGroupId(unsigned int id); + unsigned int GetSampleId() const; // intended to be used only after the RDataSpec is build, otherwise is 0 + void SetSampleId(unsigned int id); /// \endcond }; @@ -79,4 +78,4 @@ public: } // namespace RDF } // namespace ROOT -#endif // ROOT_RDF_RDATASETGROUP +#endif // ROOT_RDF_RSAMPLE diff --git a/tree/dataframe/inc/ROOT/RDF/RSampleInfo.hxx b/tree/dataframe/inc/ROOT/RDF/RSampleInfo.hxx index 7019fa5a04262..fdc57da721942 100644 --- a/tree/dataframe/inc/ROOT/RDF/RSampleInfo.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RSampleInfo.hxx @@ -11,7 +11,7 @@ #ifndef ROOT_RDF_RSAMPLEINFO #define ROOT_RDF_RSAMPLEINFO -#include +#include #include #include @@ -36,12 +36,20 @@ class RSampleInfo { std::string fID; std::pair fEntryRange; - ROOT::RDF::Experimental::RDatasetGroup fDatasetGroup{"", "", ""}; + const ROOT::RDF::Experimental::RSample *fSample = nullptr; // non-owning + + void ThrowIfNoSample() const + { + if (fSample == nullptr) { + const auto msg = "RSampleInfo: sample data was requested but no samples are available."; + throw std::logic_error(msg); + } + } public: RSampleInfo(std::string_view id, std::pair entryRange, - const ROOT::RDF::Experimental::RDatasetGroup &datasetGroup = {"", "", ""}) - : fID(id), fEntryRange(entryRange), fDatasetGroup(datasetGroup) + const ROOT::RDF::Experimental::RSample *sample = nullptr) + : fID(id), fEntryRange(entryRange), fSample(sample) { } RSampleInfo() = default; @@ -51,15 +59,35 @@ public: RSampleInfo &operator=(RSampleInfo &&) = default; ~RSampleInfo() = default; - const std::string &GetGroupName() const { return fDatasetGroup.GetGroupName(); } + const std::string &GetSampleName() const + { + ThrowIfNoSample(); + return fSample->GetSampleName(); + } - unsigned int GetGroupId() const { return fDatasetGroup.GetGroupId(); } + unsigned int GetSampleId() const + { + ThrowIfNoSample(); + return fSample->GetSampleId(); + } - int GetI(const std::string &key) const { return fDatasetGroup.GetMetaData().GetI(key); } + int GetI(const std::string &key) const + { + ThrowIfNoSample(); + return fSample->GetMetaData().GetI(key); + } - double GetD(const std::string &key) const { return fDatasetGroup.GetMetaData().GetD(key); } + double GetD(const std::string &key) const + { + ThrowIfNoSample(); + return fSample->GetMetaData().GetD(key); + } - std::string GetS(const std::string &key) const { return fDatasetGroup.GetMetaData().GetS(key); } + std::string GetS(const std::string &key) const + { + ThrowIfNoSample(); + return fSample->GetMetaData().GetS(key); + } /// Check whether the sample name contains the given substring. bool Contains(std::string_view substr) const diff --git a/tree/dataframe/inc/ROOT/RDF/RVariation.hxx b/tree/dataframe/inc/ROOT/RDF/RVariation.hxx index 6877da174c798..6d060a3292da8 100644 --- a/tree/dataframe/inc/ROOT/RDF/RVariation.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RVariation.hxx @@ -11,7 +11,6 @@ #ifndef ROOT_RDF_RVARIATION #define ROOT_RDF_RVARIATION -#include "Utils.hxx" // IsRVec #include "ColumnReaderUtils.hxx" #include "RColumnReaderBase.hxx" #include "RLoopManager.hxx" @@ -183,13 +182,14 @@ public: const std::vector &variationTags, std::string_view type, const RColumnRegister &defines, RLoopManager &lm, const ColumnNames_t &inputColNames) : RVariationBase(colNames, variationName, variationTags, type, defines, lm, inputColNames), - fExpression(std::move(expression)), fLastResults(lm.GetNSlots() * RDFInternal::CacheLineStep()), + fExpression(std::move(expression)), + fLastResults(lm.GetNSlots() * CacheLineStep()), fValues(lm.GetNSlots()) { fLoopManager->Register(this); for (auto i = 0u; i < lm.GetNSlots(); ++i) - ResizeResults(fLastResults[i * RDFInternal::CacheLineStep()], colNames.size(), variationTags.size()); + ResizeResults(fLastResults[i * CacheLineStep()], colNames.size(), variationTags.size()); } RVariation(const RVariation &) = delete; diff --git a/tree/dataframe/inc/ROOT/RDF/RVariedAction.hxx b/tree/dataframe/inc/ROOT/RDF/RVariedAction.hxx index 16fa9e58ba3ea..6bddbdefae2a1 100644 --- a/tree/dataframe/inc/ROOT/RDF/RVariedAction.hxx +++ b/tree/dataframe/inc/ROOT/RDF/RVariedAction.hxx @@ -18,6 +18,7 @@ #include "RLoopManager.hxx" #include "RJittedFilter.hxx" #include "ROOT/RDF/RMergeableValue.hxx" +#include "ROOT/RDF/RSampleInfo.hxx" #include // R__CLING_PTRCHECK #include @@ -34,7 +35,7 @@ namespace RDF { namespace RDFGraphDrawing = ROOT::Internal::RDF::GraphDrawing; -/// Just like an RAction, but it has N action helpers (one per variation + nominal) and N previous nodes. +/// Just like an RAction, but it has N action helpers and N previous nodes (N is the number of variations). template class R__CLING_PTRCHECK(off) RVariedAction final : public RActionBase { using TypeInd_t = std::make_index_sequence; @@ -43,7 +44,7 @@ class R__CLING_PTRCHECK(off) RVariedAction final : public RActionBase { using PrevNodeType = std::conditional_t::value, RFilterBase, PrevNode>; std::vector fHelpers; ///< Action helpers per variation. - /// Owning pointers to upstream nodes for each systematic variation (with the "nominal" at index 0). + /// Owning pointers to upstream nodes for each systematic variation. std::vector> fPrevNodes; /// Column readers per slot (outer dimension), per variation and per input column (inner dimension, std::array). @@ -52,6 +53,11 @@ class R__CLING_PTRCHECK(off) RVariedAction final : public RActionBase { /// The nth flag signals whether the nth input column is a custom column or not. std::array fIsDefine; + /// \brief Creates new filter nodes, one per variation, from the upstream nominal one. + /// \param nominal The nominal filter + /// \return The varied filters + /// + /// The nominal filter is not included in the return value. std::vector> MakePrevFilters(std::shared_ptr nominal) const { const auto &variations = GetVariations(); @@ -75,22 +81,44 @@ class R__CLING_PTRCHECK(off) RVariedAction final : public RActionBase { return prevFilters; } -public: - RVariedAction(std::vector &&helpers, const ColumnNames_t &columns, std::shared_ptr prevNode, - const RColumnRegister &colRegister) - : RActionBase(prevNode->GetLoopManagerUnchecked(), columns, colRegister, prevNode->GetVariations()), - fHelpers(std::move(helpers)), fPrevNodes(MakePrevFilters(prevNode)), fInputValues(GetNSlots()) + void SetupClass() { + // The column register and names are private members of RActionBase + const auto &colRegister = GetColRegister(); + const auto &columnNames = GetColumnNames(); + fLoopManager->Register(this); - for (auto i = 0u; i < columns.size(); ++i) { - auto *define = colRegister.GetDefine(columns[i]); + for (auto i = 0u; i < columnNames.size(); ++i) { + auto *define = colRegister.GetDefine(columnNames[i]); fIsDefine[i] = define != nullptr; if (fIsDefine[i]) define->MakeVariations(GetVariations()); } } + /// This constructor takes in input a vector of previous nodes, motivated by the CloneAction logic. + RVariedAction(std::vector &&helpers, const ColumnNames_t &columns, + const std::vector> &prevNodes, const RColumnRegister &colRegister) + : RActionBase(prevNodes[0]->GetLoopManagerUnchecked(), columns, colRegister, prevNodes[0]->GetVariations()), + fHelpers(std::move(helpers)), + fPrevNodes(prevNodes), + fInputValues(GetNSlots()) + { + SetupClass(); + } + +public: + RVariedAction(std::vector &&helpers, const ColumnNames_t &columns, std::shared_ptr prevNode, + const RColumnRegister &colRegister) + : RActionBase(prevNode->GetLoopManagerUnchecked(), columns, colRegister, prevNode->GetVariations()), + fHelpers(std::move(helpers)), + fPrevNodes(MakePrevFilters(prevNode)), + fInputValues(GetNSlots()) + { + SetupClass(); + } + RVariedAction(const RVariedAction &) = delete; RVariedAction &operator=(const RVariedAction &) = delete; @@ -103,7 +131,7 @@ public: void InitSlot(TTreeReader *r, unsigned int slot) final { - RDFInternal::RColumnReadersInfo info{GetColumnNames(), GetColRegister(), fIsDefine.data(), *fLoopManager}; + RColumnReadersInfo info{GetColumnNames(), GetColRegister(), fIsDefine.data(), *fLoopManager}; // get readers for each systematic variation for (const auto &variation : GetVariations()) @@ -148,11 +176,27 @@ public: SetHasRun(); } - /// Return the partially-updated value connected to the nominal result. + /// Return the partially-updated value connected to the first variation. void *PartialUpdate(unsigned int slot) final { return PartialUpdateImpl(slot); } - /// Return the per-sample callback connected to the nominal result. - ROOT::RDF::SampleCallback_t GetSampleCallback() final { return fHelpers[0].GetSampleCallback(); } + /// Return a callback that in turn runs the callbacks of each variation's helper. + ROOT::RDF::SampleCallback_t GetSampleCallback() final + { + if (fHelpers[0].GetSampleCallback()) { + std::vector callbacks; + for (auto &h : fHelpers) + callbacks.push_back(h.GetSampleCallback()); + + auto callEachCallback = [cs = std::move(callbacks)](unsigned int slot, const RSampleInfo &info) { + for (auto &c : cs) + c(slot, info); + }; + + return callEachCallback; + } + + return {}; + } std::shared_ptr GetGraph(std::unordered_map> &visitedMap) final @@ -194,6 +238,22 @@ public: throw std::logic_error("Cannot produce a varied action from a varied action."); } + std::unique_ptr CloneAction(void *typeErasedResults) final + { + const auto &vectorOfTypeErasedResults = *reinterpret_cast *>(typeErasedResults); + assert(vectorOfTypeErasedResults.size() == fHelpers.size() && + "The number of results and the number of helpers are not the same!"); + + std::vector clonedHelpers; + clonedHelpers.reserve(fHelpers.size()); + for (std::size_t i = 0; i < fHelpers.size(); i++) { + clonedHelpers.emplace_back(fHelpers[i].CallMakeNew(vectorOfTypeErasedResults[i])); + } + + return std::unique_ptr( + new RVariedAction(std::move(clonedHelpers), GetColumnNames(), fPrevNodes, GetColRegister())); + } + private: // this overload is SFINAE'd out if Helper does not implement `PartialUpdate` // the template parameter is required to defer instantiation of the method to SFINAE time diff --git a/tree/dataframe/inc/ROOT/RDF/Utils.hxx b/tree/dataframe/inc/ROOT/RDF/Utils.hxx index 6d5f02411ce08..41e05eb80c19d 100644 --- a/tree/dataframe/inc/ROOT/RDF/Utils.hxx +++ b/tree/dataframe/inc/ROOT/RDF/Utils.hxx @@ -260,14 +260,6 @@ struct Disjunction : std::conditional_t &vec); -// clang-format off -template -struct IsRVec : std::false_type {}; - -template -struct IsRVec> : std::true_type {}; -// clang-format on - /// Return a vector with all elements of v1 and v2 and duplicates removed. /// Precondition: each of v1 and v2 must not have duplicate elements. template diff --git a/tree/dataframe/inc/ROOT/RDFHelpers.hxx b/tree/dataframe/inc/ROOT/RDFHelpers.hxx index c00cc1ea25ae1..0707e24c6aff3 100644 --- a/tree/dataframe/inc/ROOT/RDFHelpers.hxx +++ b/tree/dataframe/inc/ROOT/RDFHelpers.hxx @@ -19,9 +19,13 @@ #include // users of RunGraphs might rely on this transitive include #include +#include +#include #include #include +#include #include +#include #include #include // std::index_sequence #include @@ -67,7 +71,7 @@ auto PassAsVec(F &&f) -> PassAsVecHelper, T, F> namespace RDF { namespace RDFInternal = ROOT::Internal::RDF; -// clag-format off +// clang-format off /// Given a callable with signature bool(T1, T2, ...) return a callable with same signature that returns the negated result /// /// The callable must have one single non-template definition of operator(). This is a limitation with respect to @@ -159,6 +163,7 @@ RNode AsRNode(NodeType node) // clang-format off /// Trigger the event loop of multiple RDataFrames concurrently /// \param[in] handles A vector of RResultHandles +/// \return The number of distinct computation graphs that have been processed /// /// This function triggers the event loop of all computation graphs which relate to the /// given RResultHandles. The advantage compared to running the event loop implicitly by accessing the @@ -177,7 +182,7 @@ RNode AsRNode(NodeType node) /// ROOT::RDF::RunGraphs({r1, r2}); /// ~~~ // clang-format on -void RunGraphs(std::vector handles); +unsigned int RunGraphs(std::vector handles); namespace Experimental { @@ -229,11 +234,24 @@ RResultMap VariationsFor(RResultPtr resPtr) if (nVariations > 0) { // clone the result once for each variation variedResults.reserve(nVariations); - for (auto i = 0u; i < nVariations; ++i) + for (auto i = 0u; i < nVariations; ++i){ // implicitly assuming that T is copiable: this should be the case // for all result types in use, as they are copied for each slot variedResults.emplace_back(new T{*resPtr.fObjPtr}); + // Check if the result's type T inherits from TNamed + if constexpr (std::is_base_of::value) { + // Get the current variation name + std::string variationName = variations[i]; + // Replace the colon with an underscore + std::replace(variationName.begin(), variationName.end(), ':', '_'); + // Get a pointer to the corresponding varied result + auto &variedResult = variedResults.back(); + // Set the varied result's name to NOMINALNAME_VARIATIONAME + variedResult->SetName((std::string(variedResult->GetName()) + "_" + variationName).c_str()); + } + } + std::vector typeErasedResults; typeErasedResults.reserve(variedResults.size()); for (auto &res : variedResults) @@ -248,7 +266,172 @@ RResultMap VariationsFor(RResultPtr resPtr) *resPtr.fLoopManager, std::move(nominalAction), std::move(variedAction)); } +using SnapshotPtr_t = ROOT::RDF::RResultPtr>; +SnapshotPtr_t VariationsFor(SnapshotPtr_t resPtr); + +void AddProgressbar(ROOT::RDF::RNode df); +void AddProgressbar(ROOT::RDataFrame df); + } // namespace Experimental + +/// RDF progress helper. +/// This class provides callback functions to the RDataFrame. The event statistics +/// (including elapsed time, currently processed file, currently processed events, the rate of event processing +/// and an estimated remaining time (per file being processed)) +/// are recorded and printed in the terminal every m events and every n seconds. +/// ProgressHelper::operator()(unsigned int, T&) is thread safe, and can be used as a callback in MT mode. +/// ProgressBar should be added after creating the dataframe object (df): +/// ~~~{.cpp} +/// ROOT::RDataFrame df("tree", "file.root"); +/// ROOT::RDF::Experimental::AddProgressbar(df); +/// ~~~ +/// alternatively RDataFrame can be cast to an RNode first giving it more flexibility. +/// For example, it can be called at any computational node, such as Filter or Define, not only the head node, +/// with no change to the Progressbar function itself: +/// ~~~{.cpp} +/// ROOT::RDataFrame df("tree", "file.root"); +/// auto df_1 = ROOT::RDF::RNode(df.Filter("x>1")); +/// ROOT::RDF::Experimental::AddProgressbar(df_1); +/// ~~~ +class ProgressHelper { +private: + double EvtPerSec() const; + std::pair RecordEvtCountAndTime(); + void PrintStats(std::ostream &stream, std::size_t currentEventCount, std::chrono::seconds totalElapsedSeconds) const; + void PrintProgressbar(std::ostream &stream, std::size_t currentEventCount) const; + + std::chrono::time_point fBeginTime = std::chrono::system_clock::now(); + std::chrono::time_point fLastPrintTime = fBeginTime; + std::chrono::seconds fPrintInterval{1}; + + std::atomic fProcessedEvents{0}; + std::size_t fLastProcessedEvents{0}; + std::size_t fIncrement; + + mutable std::mutex fSampleNameToEventEntriesMutex; + std::map fSampleNameToEventEntries; // Filename, events in the file + + std::array fEventsPerSecondStatistics; + std::size_t fEventsPerSecondStatisticsIndex{0}; + + unsigned int fBarWidth; + unsigned int fTotalFiles; + + std::mutex fPrintMutex; + bool fIsTTY; + bool fUseShellColours; + + std::shared_ptr fTree{nullptr}; + +public: + /// Create a progress helper. + /// \param increment RDF callbacks are called every `n` events. Pass this `n` here. + /// \param totalFiles read total number of files in the RDF. + /// \param progressBarWidth Number of characters the progress bar will occupy. + /// \param printInterval Update every stats every `n` seconds. + /// \param useColors Use shell colour codes to colour the output. Automatically disabled when + /// we are not writing to a tty. + ProgressHelper(std::size_t increment, unsigned int totalFiles = 1, unsigned int progressBarWidth = 40, + unsigned int printInterval = 1, bool useColors = true); + + ~ProgressHelper() = default; + + /// Register a new sample for completion statistics. + /// \see ROOT::RDF::RInterface::DefinePerSample(). + /// The *id.AsString()* refers to the name of the currently processed file. + /// The idea is to populate the event entries in the *fSampleNameToEventEntries* map + /// by selecting the greater of the two values: + /// *id.EntryRange().second* which is the upper event entry range of the processed sample + /// and the current value of the event entries in the *fSampleNameToEventEntries* map. + /// In the single threaded case, the two numbers are the same as the entry range corresponds + /// to the number of events in an individual file (each sample is simply a single file). + /// In the multithreaded case, the idea is to accumulate the higher event entry value until + /// the total number of events in a given file is reached. + void registerNewSample(unsigned int /*slot*/, const ROOT::RDF::RSampleInfo &id) + { + std::lock_guard lock(fSampleNameToEventEntriesMutex); + fSampleNameToEventEntries[id.AsString()] = + std::max(id.EntryRange().second, fSampleNameToEventEntries[id.AsString()]); + } + + /// Thread-safe callback for RDataFrame. + /// It will record elapsed times and event statistics, and print a progress bar every n seconds (set by the + /// fPrintInterval). \param slot Ignored. \param value Ignored. + template + void operator()(unsigned int /*slot*/, T &value) + { + operator()(value); + } + // clang-format off + /// Thread-safe callback for RDataFrame. + /// It will record elapsed times and event statistics, and print a progress bar every n seconds (set by the fPrintInterval). + /// \param value Ignored. + // clang-format on + template + void operator()(T & /*value*/) + { + using namespace std::chrono; + // *************************************************** + // Warning: Here, everything needs to be thread safe: + // *************************************************** + fProcessedEvents += fIncrement; + + unsigned int currentFileIdx = ComputeCurrentFileIdx(); + unsigned int GetNEventsOfCurrentFile = ComputeNEventsSoFar(); + + // We only print every n seconds. + if (duration_cast(system_clock::now() - fLastPrintTime) < fPrintInterval) { + + // Unless we are at the end of file processing, then we want to print the progress bar again (the final status) + // Otherwise, if the last processed files are too small and they are processed in less than the time interval, + // the final progress bar status would be incomplete. We want to prevent this from happening. + + if (fTotalFiles != currentFileIdx) { + if (currentFileIdx <= GetNEventsOfCurrentFile - fIncrement) { + return; + } + } + } + + // *************************************************** + // Protected by lock from here: + // *************************************************** + if (!fPrintMutex.try_lock()) + return; + std::lock_guard lockGuard(fPrintMutex, std::adopt_lock); + + std::size_t eventCount; + seconds elapsedSeconds; + std::tie(eventCount, elapsedSeconds) = RecordEvtCountAndTime(); + + if (fIsTTY) + std::cout << "\r"; + + PrintProgressbar(std::cout, eventCount); + PrintStats(std::cout, eventCount, elapsedSeconds); + + if (fIsTTY) + std::cout << std::flush; + else + std::cout << std::endl; + } + + std::size_t ComputeNEventsSoFar() const + { + std::unique_lock lock(fSampleNameToEventEntriesMutex); + std::size_t result = 0; + for (const auto &item : fSampleNameToEventEntries) + result += item.second; + return result; + } + + unsigned int ComputeCurrentFileIdx() const + { + std::unique_lock lock(fSampleNameToEventEntriesMutex); + return fSampleNameToEventEntries.size(); + } +}; + } // namespace RDF } // namespace ROOT #endif diff --git a/tree/dataframe/inc/ROOT/RDataFrame.hxx b/tree/dataframe/inc/ROOT/RDataFrame.hxx index 2e318792b5768..7a094cc01fb67 100644 --- a/tree/dataframe/inc/ROOT/RDataFrame.hxx +++ b/tree/dataframe/inc/ROOT/RDataFrame.hxx @@ -23,6 +23,7 @@ ROOT's RDataFrame allows to analyse data stored in TTrees with a high level inte #include "ROOT/RStringView.hxx" #include "RtypesCore.h" +#include #include #include #include @@ -43,6 +44,9 @@ public: RDataFrame(std::string_view treeName, std::string_view filenameglob, const ColumnNames_t &defaultColumns = {}); RDataFrame(std::string_view treename, const std::vector &filenames, const ColumnNames_t &defaultColumns = {}); + RDataFrame(std::string_view treename, std::initializer_list filenames, + const ColumnNames_t &defaultColumns = {}): + RDataFrame(treename, std::vector(std::move(filenames)), defaultColumns) {} RDataFrame(std::string_view treeName, ::TDirectory *dirPtr, const ColumnNames_t &defaultColumns = {}); RDataFrame(TTree &tree, const ColumnNames_t &defaultColumns = {}); RDataFrame(ULong64_t numEntries); diff --git a/tree/dataframe/inc/ROOT/RDataSource.hxx b/tree/dataframe/inc/ROOT/RDataSource.hxx index 448228775aaa5..f60acaa535cda 100644 --- a/tree/dataframe/inc/ROOT/RDataSource.hxx +++ b/tree/dataframe/inc/ROOT/RDataSource.hxx @@ -13,9 +13,7 @@ #include "RDF/RColumnReaderBase.hxx" #include "ROOT/RStringView.hxx" -#include "ROOT/RConfig.hxx" // R__DEPRECATED #include "RtypesCore.h" // ULong64_t -#include "TError.h" // Warning #include "TString.h" #include // std::transform @@ -110,13 +108,6 @@ RDataSource implementations must support running multiple event-loops consecutiv */ class RDataSource { // clang-format on -private: - /// \cond - // Temporary boolean value used by the backwards compatibility code for the deprecated spellings Initialise, - // Finalise and FinaliseSlot. - bool fDeprecatedBaseCalled = false; - /// \endcond - protected: using Record_t = std::vector; friend std::string cling::printValue(::ROOT::RDF::RDataSource *); @@ -207,30 +198,6 @@ public: // clang-format on virtual void Initialize() {} - /// \cond - // Unused deprecated struct, it's here to remind us to remove the deprecated spellings Initialise, Finalise and - // FinaliseSlot. PR that removes the deprecated code: https://github.com/root-project/root/pull/9521 . - struct R__DEPRECATED(6, 30, - "Use Initialize, Finalize and FinalizeSlot instead of the corresponding british spellings.") - NeverUsedJustAReminder { - }; - - virtual void Initialise() { fDeprecatedBaseCalled = true; } - - void CallInitialize() - { - fDeprecatedBaseCalled = false; - Initialise(); - if (!fDeprecatedBaseCalled) { - Warning("RDataSource::Initialise", "Initialise is deprecated. Please rename it to \"Initialize\" (with a z)."); - return; - } - - // `Initialise()` was not overridden, the data source uses the new spelling: good! - Initialize(); - } - /// \endcond - // clang-format off /// \brief Convenience method called at the start of the data processing associated to a slot. /// \param[in] slot The data processing slot wihch needs to be initialized @@ -246,46 +213,12 @@ public: // clang-format on virtual void FinalizeSlot(unsigned int /*slot*/) {} - /// \cond - virtual void FinaliseSlot(unsigned int) { fDeprecatedBaseCalled = true; } - - void CallFinalizeSlot(unsigned int slot) - { - fDeprecatedBaseCalled = false; - FinaliseSlot(slot); - if (!fDeprecatedBaseCalled) { - Warning("RDataSource::FinaliseSlot", - "FinaliseSlot is deprecated. Please implement FinalizeSlot (with a z) instead of FinaliseSlot."); - return; - } - - FinalizeSlot(slot); - } - /// \endcond - // clang-format off /// \brief Convenience method called after concluding an event-loop. /// See Initialize for more details. // clang-format on virtual void Finalize() {} - /// \cond - virtual void Finalise() { fDeprecatedBaseCalled = true; } - - void CallFinalize() - { - fDeprecatedBaseCalled = false; - Finalise(); - if (!fDeprecatedBaseCalled) { - Warning("RDataSource::FinaliseSlot", - "Finalise is deprecated. Please implement Finalize (with a z) instead of Finalise."); - return; - } - - Finalize(); - } - /// \endcond - /// \brief Return a string representation of the datasource type. /// The returned string will be used by ROOT::RDF::SaveGraph() to represent /// the datasource in the visualization of the computation graph. diff --git a/tree/dataframe/inc/ROOT/RNTupleDS.hxx b/tree/dataframe/inc/ROOT/RNTupleDS.hxx index e39e74ccfb035..4693c615e1b17 100644 --- a/tree/dataframe/inc/ROOT/RNTupleDS.hxx +++ b/tree/dataframe/inc/ROOT/RNTupleDS.hxx @@ -93,11 +93,6 @@ protected: Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) final; }; -R__DEPRECATED(6, 30, "Use ROOT::RDF::Experimental::FromRNTuple instead.") -RDataFrame MakeNTupleDataFrame(std::string_view ntupleName, std::string_view fileName); -R__DEPRECATED(6, 30, "Use ROOT::RDF::Experimental::FromRNTuple instead.") -RDataFrame MakeNTupleDataFrame(RNTuple *ntuple); - } // ns Experimental namespace RDF { diff --git a/tree/dataframe/inc/ROOT/RResultHandle.hxx b/tree/dataframe/inc/ROOT/RResultHandle.hxx index 4b9736ae506d9..b801e916f8bff 100644 --- a/tree/dataframe/inc/ROOT/RResultHandle.hxx +++ b/tree/dataframe/inc/ROOT/RResultHandle.hxx @@ -24,16 +24,25 @@ namespace ROOT { namespace RDF { +/// \brief A type-erased version of RResultPtr and RResultMap. +/// RResultHandles are used to invoke ROOT::RDF::RunGraphs() and can also be useful +/// to store result pointers of different types in the same collection. Knowledge +/// about the actual result type will still be needed to access it. +/// \note Varied results are stripped away when a RResultMap is converted to a RResultHandle: +/// Only the nominal result will be accessible from the RResultHandle. class RResultHandle { ROOT::Detail::RDF::RLoopManager *fLoopManager = nullptr; //< Pointer to the loop manager /// Owning pointer to the action that will produce this result. /// Ownership is shared with RResultPtrs and RResultHandles that refer to the same result. std::shared_ptr fActionPtr; std::shared_ptr fObjPtr; ///< Type erased shared pointer encapsulating the wrapped result + /// Owning pointer to the varied action that will produce these results if any. + /// Null if the RResultHandle was created from a RResultPtr, so no variations were present. + std::shared_ptr fVariedActionPtr; const std::type_info *fType = nullptr; ///< Type of the wrapped result // The ROOT::RDF::RunGraphs helper has to access the loop manager to check whether two RResultHandles belong to the same computation graph - friend void RunGraphs(std::vector); + friend unsigned int RunGraphs(std::vector); /// Get the pointer to the encapsulated result. /// Ownership is not transferred to the caller. @@ -66,6 +75,15 @@ class RResultHandle { public: template RResultHandle(const RResultPtr &resultPtr) : fLoopManager(resultPtr.fLoopManager), fActionPtr(resultPtr.fActionPtr), fObjPtr(resultPtr.fObjPtr), fType(&typeid(T)) {} + template + RResultHandle(const Experimental::RResultMap &resultMap) + : fLoopManager(resultMap.fLoopManager), + fActionPtr(resultMap.fNominalAction), + fObjPtr(resultMap.fMap.at("nominal")), + fVariedActionPtr(resultMap.fVariedAction), + fType(&typeid(T)) + { + } RResultHandle(const RResultHandle&) = default; RResultHandle(RResultHandle&&) = default; @@ -73,6 +91,7 @@ public: /// Get the pointer to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. + /// If the RResultHandle was created from a RResultMap, this returns a pointer to the nominal value. /// \tparam T Type of the action result template T* GetPtr() @@ -84,6 +103,7 @@ public: /// Get a const reference to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. + /// If the RResultHandle was created from a RResultMap, this returns a pointer to the nominal value. /// \tparam T Type of the action result template const T& GetValue() @@ -96,6 +116,7 @@ public: /// Get an RResultPtr to the encapsulated object. /// \tparam T Type of the action result template + R__DEPRECATED(6, 32, "Please use RResultPtr directly and only cast to RResultHandle in order to call RunGraphs.") RResultPtr GetResultPtr() { CheckType(typeid(T)); @@ -119,12 +140,12 @@ public: bool operator==(const RResultHandle &rhs) const { - return fObjPtr == rhs.fObjPtr; + return fObjPtr == rhs.fObjPtr && fVariedActionPtr == rhs.fVariedActionPtr; } bool operator!=(const RResultHandle &rhs) const { - return !(fObjPtr == rhs.fObjPtr); + return !(fObjPtr == rhs.fObjPtr) && fVariedActionPtr == rhs.fVariedActionPtr; } }; diff --git a/tree/dataframe/inc/ROOT/RResultPtr.hxx b/tree/dataframe/inc/ROOT/RResultPtr.hxx index cba364dde6cb9..79082d9a8e08d 100644 --- a/tree/dataframe/inc/ROOT/RResultPtr.hxx +++ b/tree/dataframe/inc/ROOT/RResultPtr.hxx @@ -41,7 +41,38 @@ class RInterface; namespace Internal { namespace RDF { class GraphCreatorHelper; +/** + * \brief Creates a new RResultPtr with a cloned action. + * + * \tparam T The type of the result held by the RResultPtr. + * \param inptr The pointer. + * \return A new pointer with a cloned action. + */ +template +ROOT::RDF::RResultPtr CloneResultAndAction(const ROOT::RDF::RResultPtr &inptr) +{ + // We call the copy constructor, to copy also the metadata of certain + // result types, e.g. a for a TH1D we have to create a new histogram with + // the same binning and axis limits. + std::shared_ptr copiedResult{new T{*inptr.fObjPtr}}; + return ROOT::RDF::RResultPtr(copiedResult, inptr.fLoopManager, + inptr.fActionPtr->CloneAction(reinterpret_cast(&copiedResult))); } + +using SnapshotPtr_t = ROOT::RDF::RResultPtr>; +/** + * \brief Creates a new RResultPtr with a cloned Snapshot action. + * + * \param inptr The pointer. + * \param outputFileName A new name for the output file of the cloned action. + * \return A new pointer with a cloned action. + * + * This overload is needed since cloning a Snapshot node usually also involves + * changing the name of the output file, otherwise the cloned Snapshot would + * overwrite the same file. + */ +SnapshotPtr_t CloneResultAndAction(const SnapshotPtr_t &inptr, const std::string &outputFileName); +} // namespace RDF } // namespace Internal namespace Detail { @@ -118,6 +149,10 @@ class RResultPtr { friend class RResultHandle; + friend RResultPtr ROOT::Internal::RDF::CloneResultAndAction(const RResultPtr &inptr); + friend ROOT::Internal::RDF::SnapshotPtr_t + ROOT::Internal::RDF::CloneResultAndAction(const ROOT::Internal::RDF::SnapshotPtr_t &inptr, + const std::string &outputFileName); /// \cond HIDDEN_SYMBOLS template ::value> struct RIterationHelper { diff --git a/tree/dataframe/inc/ROOT/RSqliteDS.hxx b/tree/dataframe/inc/ROOT/RSqliteDS.hxx index 02e924f573900..47801be0fce34 100644 --- a/tree/dataframe/inc/ROOT/RSqliteDS.hxx +++ b/tree/dataframe/inc/ROOT/RSqliteDS.hxx @@ -36,7 +36,7 @@ struct RSqliteDSDataSet; The RSqliteDS is able to feed an RDataFrame with data from a SQlite SELECT query. One can use it like - auto rdf = ROOT::RDF::MakeSqliteDataFrame("/path/to/file.sqlite", "select name from table"); + auto rdf = ROOT::RDF::FromSqlite("/path/to/file.sqlite", "select name from table"); auto h = rdf.Define("lName", "name.length()").Histo1D("lName"); The data source has to provide column types for all the columns. Determining column types in SQlite is tricky @@ -114,9 +114,6 @@ protected: RDataFrame FromSqlite(std::string_view fileName, std::string_view query); -R__DEPRECATED(6, 30, "Use FromSqlite instead.") -RDataFrame MakeSqliteDataFrame(std::string_view fileName, std::string_view query); - } // namespace RDF } // namespace ROOT diff --git a/tree/dataframe/src/RArrowDS.cxx b/tree/dataframe/src/RArrowDS.cxx index b999e38a85b3d..14abb60070f4b 100644 --- a/tree/dataframe/src/RArrowDS.cxx +++ b/tree/dataframe/src/RArrowDS.cxx @@ -17,7 +17,7 @@ The RArrowDS implements a proxy RDataSource to be able to use Apache Arrow tables with RDataFrame. A RDataFrame that adapts an arrow::Table class can be constructed using the factory method -ROOT::RDF::MakeArrowDataFrame, which accepts one parameter: +ROOT::RDF::FromArrow, which accepts one parameter: 1. An arrow::Table smart pointer. The types of the columns are derived from the types in the associated @@ -609,14 +609,6 @@ RDataFrame FromArrow(std::shared_ptr table, std::vector table, std::vector const &columnNames) -{ - return FromArrow(table, columnNames); -} - } // namespace RDF } // namespace ROOT diff --git a/tree/dataframe/src/RCsvDS.cxx b/tree/dataframe/src/RCsvDS.cxx index 65781a1cb4b07..8b9bfb4ee5a39 100644 --- a/tree/dataframe/src/RCsvDS.cxx +++ b/tree/dataframe/src/RCsvDS.cxx @@ -16,7 +16,7 @@ The RCsvDS class implements a CSV file reader for RDataFrame. A RDataFrame that reads from a CSV file can be constructed using the factory method -ROOT::RDF::MakeCsvDataFrame, which accepts five parameters: +ROOT::RDF::FromCSV, which accepts five parameters: 1. Path to the CSV file. 2. Boolean that specifies whether the first row of the CSV file contains headers or not (optional, default `true`). If `false`, header names will be automatically generated as Col0, Col1, ..., ColN. @@ -224,9 +224,11 @@ void RCsvDS::InferColTypes(std::vector &columns) const auto second_line = fCsvFile->GetFilePos(); for (auto i = 0u; i < columns.size(); ++i) { - - if (fColTypes.find(fHeaders[i]) != fColTypes.end()) - continue; // type was manually specified, nothing to do + const auto userSpecifiedType = fColTypes.find(fHeaders[i]); + if (userSpecifiedType != fColTypes.end()) { + fColTypesList.push_back(userSpecifiedType->second); + continue; + } // read <=10 extra lines until a non-empty cell on this column is found, so that type is determined for (auto extraRowsRead = 0u; extraRowsRead < 10u && columns[i] == "nan"; ++extraRowsRead) { @@ -561,12 +563,6 @@ RDataFrame FromCSV(std::string_view fileName, bool readHeaders, char delimiter, return rdf; } -RDataFrame MakeCsvDataFrame(std::string_view fileName, bool readHeaders, char delimiter, Long64_t linesChunkSize, - std::unordered_map &&colTypes) -{ - return FromCSV(fileName, readHeaders, delimiter, linesChunkSize, std::move(colTypes)); -} - } // ns RDF } // ns ROOT diff --git a/tree/dataframe/src/RDFActionHelpers.cxx b/tree/dataframe/src/RDFActionHelpers.cxx index 1e5e22f99ee8d..273793946099d 100644 --- a/tree/dataframe/src/RDFActionHelpers.cxx +++ b/tree/dataframe/src/RDFActionHelpers.cxx @@ -107,31 +107,6 @@ void BufferedFillHelper::Finalize() } } -template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -template void BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); -template void -BufferedFillHelper::Exec(unsigned int, const std::vector &, const std::vector &); - -// TODO -// template void MinHelper::Exec(unsigned int, const std::vector &); -// template void MinHelper::Exec(unsigned int, const std::vector &); -// template void MinHelper::Exec(unsigned int, const std::vector &); -// template void MinHelper::Exec(unsigned int, const std::vector &); -// template void MinHelper::Exec(unsigned int, const std::vector &); - -// template void MaxHelper::Exec(unsigned int, const std::vector &); -// template void MaxHelper::Exec(unsigned int, const std::vector &); -// template void MaxHelper::Exec(unsigned int, const std::vector &); -// template void MaxHelper::Exec(unsigned int, const std::vector &); -// template void MaxHelper::Exec(unsigned int, const std::vector &); - MeanHelper::MeanHelper(const std::shared_ptr &meanVPtr, const unsigned int nSlots) : fResultMean(meanVPtr), fCounts(nSlots, 0), fSums(nSlots, 0), fPartialMeans(nSlots), fCompensations(nSlots) { diff --git a/tree/dataframe/src/RDFDescription.cxx b/tree/dataframe/src/RDFDescription.cxx index c90cb50fed55d..f64b22b519617 100644 --- a/tree/dataframe/src/RDFDescription.cxx +++ b/tree/dataframe/src/RDFDescription.cxx @@ -17,6 +17,10 @@ namespace RDF { RDFDescription::RDFDescription(const std::string &briefDescription, const std::string &fullDescription) : fBriefDescription(briefDescription), fFullDescription(fullDescription){}; +RDFDescription::RDFDescription(const std::string &briefDescription, const std::string &fullDescription, + unsigned int filecount) + : fBriefDescription(briefDescription), fFullDescription(fullDescription), fFileCount(filecount){}; + std::string RDFDescription::AsString(bool shortFormat /*= false*/) const { if (shortFormat) diff --git a/tree/dataframe/src/RDFHelpers.cxx b/tree/dataframe/src/RDFHelpers.cxx index e31214038a030..893ee1fbb2b34 100644 --- a/tree/dataframe/src/RDFHelpers.cxx +++ b/tree/dataframe/src/RDFHelpers.cxx @@ -24,13 +24,53 @@ #include #include +// TODO, this function should be part of core libraries +#include +#if (!defined(_WIN32)) && (!defined(_WIN64)) +#include +#endif + +#include +#include + +#if defined(_WIN32) || defined(_WIN64) +#define WIN32_LEAN_AND_MEAN +#define VC_EXTRALEAN +#include +#include +#elif defined(__linux__) +#include +#endif // Windows/Linux + +// Get terminal size for progress bar +int get_tty_size() +{ +#if defined(_WIN32) || defined(_WIN64) + if (!_isatty(_fileno(stdout))) + return 0; + int width = 0; + CONSOLE_SCREEN_BUFFER_INFO csbi; + if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) + width = (int)(csbi.srWindow.Right - csbi.srWindow.Left + 1); + return width; +#elif defined(__linux__) + int width = 0; + struct winsize w; + ioctl(fileno(stdout), TIOCGWINSZ, &w); + width = (int)(w.ws_col); + return width; +#else + return 0; +#endif // Windows/Linux +} + using ROOT::RDF::RResultHandle; -void ROOT::RDF::RunGraphs(std::vector handles) +unsigned int ROOT::RDF::RunGraphs(std::vector handles) { if (handles.empty()) { Warning("RunGraphs", "Got an empty list of handles, now quitting."); - return; + return 0u; } // Check that there are results which have not yet been run @@ -41,7 +81,7 @@ void ROOT::RDF::RunGraphs(std::vector handles) handles.size() - nToRun); } if (nToRun == 0u) - return; + return 0u; // Find the unique event loops auto sameGraph = [](const RResultHandle &a, const RResultHandle &b) { return a.fLoopManager < b.fLoopManager; }; @@ -91,4 +131,212 @@ void ROOT::RDF::RunGraphs(std::vector handles) R__LOG_INFO(ROOT::Detail::RDF::RDFLogChannel()) << "Finished RunGraphs run (" << uniqueLoops.size() << " unique computation graphs, " << sw.CpuTime() << "s CPU, " << sw.RealTime() << "s elapsed)."; + + return uniqueLoops.size(); +} + +ROOT::RDF::Experimental::SnapshotPtr_t ROOT::RDF::Experimental::VariationsFor(ROOT::RDF::Experimental::SnapshotPtr_t) +{ + throw std::logic_error("Varying a Snapshot result is not implemented yet."); +} + +namespace ROOT { +namespace RDF { + +ProgressHelper::ProgressHelper(std::size_t increment, unsigned int totalFiles, unsigned int progressBarWidth, + unsigned int printInterval, bool useColors) + : fPrintInterval(printInterval), + fIncrement{increment}, + fBarWidth{progressBarWidth = int(get_tty_size() / 4)}, + fTotalFiles{totalFiles}, +#if defined(_WIN32) || defined(_WIN64) + fIsTTY{_isatty(_fileno(stdout)) != 0}, + fUseShellColours{false && useColors} +#else + fIsTTY{isatty(fileno(stdout)) == 1}, + fUseShellColours{useColors && fIsTTY} // Control characters only with terminals. +#endif +{ +} + +/// Compute a running mean of events/s. +double ProgressHelper::EvtPerSec() const +{ + if (fEventsPerSecondStatisticsIndex < fEventsPerSecondStatistics.size()) + return std::accumulate(fEventsPerSecondStatistics.begin(), + fEventsPerSecondStatistics.begin() + fEventsPerSecondStatisticsIndex, 0.) / + fEventsPerSecondStatisticsIndex; + else + return std::accumulate(fEventsPerSecondStatistics.begin(), fEventsPerSecondStatistics.end(), 0.) / + fEventsPerSecondStatistics.size(); +} + +/// Record current event counts and time stamp, populate evts/s statistics array. +std::pair ProgressHelper::RecordEvtCountAndTime() +{ + using namespace std::chrono; + + auto currentEventCount = fProcessedEvents.load(); + auto eventsPerTimeInterval = currentEventCount - fLastProcessedEvents; + fLastProcessedEvents = currentEventCount; + + auto oldPrintTime = fLastPrintTime; + auto newPrintTime = system_clock::now(); + fLastPrintTime = newPrintTime; + + duration secondsCurrentInterval = newPrintTime - oldPrintTime; + fEventsPerSecondStatistics[fEventsPerSecondStatisticsIndex++ % fEventsPerSecondStatistics.size()] = + eventsPerTimeInterval / secondsCurrentInterval.count(); + + return {currentEventCount, duration_cast(newPrintTime - fBeginTime)}; +} + +namespace { +/// Format std::chrono::seconds as `1:30m`. +std::ostream &operator<<(std::ostream &stream, std::chrono::seconds elapsedSeconds) +{ + auto h = std::chrono::duration_cast(elapsedSeconds); + auto m = std::chrono::duration_cast(elapsedSeconds - h); + auto s = (elapsedSeconds - h - m).count(); + if (h.count() > 0) + stream << h.count() << ':' << std::setw(2) << std::right << std::setfill('0'); + stream << m.count() << ':' << std::setw(2) << std::right << std::setfill('0') << s; + return stream << (h.count() > 0 ? 'h' : 'm'); +} + +struct RestoreStreamState { + RestoreStreamState(std::ostream &stream) : fStream(stream), fFlags(stream.flags()), fFillChar(stream.fill()) {} + ~RestoreStreamState() + { + fStream.setf(fFlags); + fStream.fill(fFillChar); + } + + std::ostream &fStream; + std::ios_base::fmtflags fFlags; + std::ostream::char_type fFillChar; +}; +} // namespace + +/// Print event and time statistics. +void ProgressHelper::PrintStats(std::ostream &stream, std::size_t currentEventCount, + std::chrono::seconds elapsedSeconds) const +{ + auto evtpersec = EvtPerSec(); + auto GetNEventsOfCurrentFile = ComputeNEventsSoFar(); + auto currentFileIdx = ComputeCurrentFileIdx(); + auto totalFiles = fTotalFiles; + + if (fUseShellColours) + stream << "\033[35m"; + stream << "[" + << "Elapsed time: " << elapsedSeconds << " "; + if (fUseShellColours) + stream << "\033[0m"; + stream << "processing file: " << currentFileIdx << " / " << totalFiles << " "; + + // Event counts: + if (fUseShellColours) + stream << "\033[32m"; + + stream << "processed evts: " << currentEventCount; + if (GetNEventsOfCurrentFile != 0) { + stream << " / " << std::scientific << std::setprecision(2) << GetNEventsOfCurrentFile; + } + stream << " "; + + if (fUseShellColours) + stream << "\033[0m"; + + // events/s + stream << std::scientific << std::setprecision(2) << evtpersec << " evt/s"; + + // Time statistics: + if (GetNEventsOfCurrentFile != 0) { + if (fUseShellColours) + stream << "\033[35m"; + std::chrono::seconds remainingSeconds( + static_cast((ComputeNEventsSoFar() - currentEventCount) / evtpersec)); + stream << " " << remainingSeconds << " " + << " remaining time (per file)"; + if (fUseShellColours) + stream << "\033[0m"; + } + + stream << "] "; +} + +/// Print a progress bar of width `ProgressHelper::fBarWidth` if `fGetNEventsOfCurrentFile` is known. +void ProgressHelper::PrintProgressbar(std::ostream &stream, std::size_t currentEventCount) const +{ + auto GetNEventsOfCurrentFile = ComputeNEventsSoFar(); + if (GetNEventsOfCurrentFile == 0) + return; + + RestoreStreamState restore(stream); + + double completion = double(currentEventCount) / GetNEventsOfCurrentFile; + unsigned int nBar = std::min(completion, 1.) * fBarWidth; + + std::string bars(std::max(nBar, 1u), '='); + bars.back() = (nBar == fBarWidth) ? '=' : '>'; + + if (fUseShellColours) + stream << "\033[33m"; + stream << '|' << std::setfill(' ') << std::setw(fBarWidth) << std::left << bars << "| "; + if (fUseShellColours) + stream << "\033[0m"; +} +//*/ +namespace Experimental { + +class ProgressBarAction final : public ROOT::Detail::RDF::RActionImpl { +public: + using Result_t = int; + +private: + std::shared_ptr fHelper; + std::shared_ptr fDummyResult = std::make_shared(); + +public: + ProgressBarAction(std::shared_ptr r) : fHelper(std::move(r)) {} + + std::shared_ptr GetResultPtr() const { return fDummyResult; } + + void Initialize() {} + void InitTask(TTreeReader *, unsigned int) {} + + void Exec(unsigned int) {} + + void Finalize() { std::cout << '\n'; } + + std::string GetActionName() { return "ProgressBar"; } + // dummy implementation of PartialUpdate + int &PartialUpdate(unsigned int) { return *fDummyResult; } + + ROOT::RDF::SampleCallback_t GetSampleCallback() + { + return [this](unsigned int slot, const ROOT::RDF::RSampleInfo &id) { + this->fHelper->registerNewSample(slot, id); + return this->fHelper->ComputeNEventsSoFar(); + }; + } +}; + +void AddProgressbar(ROOT::RDF::RNode node) +{ + auto total_files = node.GetNFiles(); + auto progress = std::make_shared(1000, total_files); + ProgressBarAction c(progress); + auto r = node.Book<>(c); + r.OnPartialResultSlot(1000, [progress](unsigned int slot, auto &&arg) { (*progress)(slot, arg); }); +} + +void AddProgressbar(ROOT::RDataFrame dataframe) +{ + auto node = ROOT::RDF::AsRNode(dataframe); + ROOT::RDF::Experimental::AddProgressbar(node); } +} // namespace Experimental +} // namespace RDF +} // namespace ROOT diff --git a/tree/dataframe/src/RDFInterfaceUtils.cxx b/tree/dataframe/src/RDFInterfaceUtils.cxx index 9e9e47c21c81e..b97e3a8287bf4 100644 --- a/tree/dataframe/src/RDFInterfaceUtils.cxx +++ b/tree/dataframe/src/RDFInterfaceUtils.cxx @@ -966,16 +966,6 @@ void CheckForDuplicateSnapshotColumns(const ColumnNames_t &cols) } } -//////////////////////////////////////////////////////////////////////////////// -/// \brief Trigger the execution of an RDataFrame computation graph. -/// \param[in] node A node of the computation graph (not a result). -/// -/// This function calls the RLoopManager::Run method on the \p fLoopManager data -/// member of the input argument. It is intended for internal use only. -void TriggerRun(ROOT::RDF::RNode &node){ - node.fLoopManager->Run(); -} - /// Return copies of colsWithoutAliases and colsWithAliases with size branches for variable-sized array branches added /// in the right positions (i.e. before the array branches that need them). std::pair, std::vector> diff --git a/tree/dataframe/src/RDataFrame.cxx b/tree/dataframe/src/RDataFrame.cxx index e22edd409a9ce..1dc93423bb6bc 100644 --- a/tree/dataframe/src/RDataFrame.cxx +++ b/tree/dataframe/src/RDataFrame.cxx @@ -8,6 +8,7 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ +#include "ROOT/InternalTreeUtils.hxx" #include "ROOT/RDataFrame.hxx" #include "ROOT/RDataSource.hxx" #include "ROOT/RDF/RDatasetSpec.hxx" @@ -76,11 +77,13 @@ You can directly see RDataFrame in action in our [tutorials](https://root.cern.c - [Special helper columns: `rdfentry_` and `rdfslot_`](\ref helper-cols) - [Just-in-time compilation: column type inference and explicit declaration of column types](\ref jitting) - [User-defined custom actions](\ref generic-actions) - - [Friend trees](\ref friends) + - [Dataset joins with friend trees](\ref friends) - [Reading data formats other than ROOT trees](\ref other-file-formats) - [Computation graphs (storing and reusing sets of transformations)](\ref callgraphs) - [Visualizing the computation graph](\ref representgraph) - [Activating RDataFrame execution logs](\ref rdf-logging) + - [Creating an RDataFrame from a dataset specification file](\ref rdf-from-spec) + - [Adding a progress bar](\ref progressbar) - [Efficient analysis in Python](\ref python) - Class reference @@ -308,7 +311,7 @@ This is useful to generate simple datasets on the fly: the contents of each even For data sources other than TTrees and TChains, RDataFrame objects are constructed using ad-hoc factory functions (see e.g. FromCSV(), FromSqlite(), FromArrow()): ~~~{.cpp} -auto df = ROOT::RDF::MakeCsvDataFrame("input.csv"); +auto df = ROOT::RDF::FromCSV("input.csv"); // use df as usual ~~~ @@ -664,10 +667,7 @@ parts of the RDataFrame API currently work with this package. The subset that is with support for more operations coming in the future. Data sources other than TTree and TChain (e.g. CSV, RNTuple) are currently not supported. -**Note** that the distributed RDataFrame module is available in a ROOT installation if the following criteria are met: -- PyROOT is available -- RDataFrame is available -- The version of the Python interpreter used to build ROOT is greater or equal than 3.7 +\note The distributed RDataFrame module requires at least Python version 3.8. ### Connecting to a Spark cluster @@ -814,6 +814,66 @@ Without this, two partial histograms resulting from two distributed tasks would to errors when merging them. Failing to pass a histogram model will raise an error on the client side, before starting the distributed execution. +### Live visualization in distributed mode with dask + +The live visualization feature allows real-time data representation of plots generated during the execution +of a distributed RDataFrame application. +It enables visualizing intermediate results as they are computed across multiple nodes of a Dask cluster +by creating a canvas and continuously updating it as partial results become available. + +The LiveVisualize() function can be imported from the Python package **ROOT.RDF.Experimental.Distributed**: + +~~~{.py} +import ROOT + +LiveVisualize = ROOT.RDF.Experimental.Distributed.LiveVisualize +~~~ + +The function takes drawable objects (e.g. histograms) and optional callback functions as argument, it accepts 4 different input formats: + +- Passing a list or tuple of drawables: +You can pass a list or tuple containing the plots you want to visualize. For example: + +~~~{.py} +LiveVisualize([h_gaus, h_exp, h_random]) +~~~ + +- Passing a list or tuple of drawables with a global callback function: +You can also include a global callback function that will be applied to all plots. For example: + +~~~{.py} +def set_fill_color(hist): + hist.SetFillColor(ROOT.kBlue) + +LiveVisualize([h_gaus, h_exp, h_random], set_fill_color) +~~~ + +- Passing a Dictionary of drawables and callback functions: +For more control, you can create a dictionary where keys are plots and values are corresponding (optional) callback functions. For example: + +~~~{.py} +plot_callback_dict = { + graph: set_marker, + h_exp: fit_exp, + tprofile_2d: None +} + +LiveVisualize(plot_callback_dict) +~~~ + +- Passing a Dictionary of drawables and callback functions with a global callback function: +You can also combine a dictionary of plots and callbacks with a global callback function: + +~~~{.py} +LiveVisualize(plot_callback_dict, write_to_tfile) +~~~ + +\note The allowed operations to pass to LiveVisualize are: + - Histo1D(), Histo2D(), Histo3D() + - Graph() + - Profile1D(), Profile2D() + +\warning The Live Visualization feature is only supported for the Dask backend. \anchor parallel-execution ## Performance tips and parallel execution @@ -957,7 +1017,7 @@ not limited to string expressions but they can also pass any valid C++ callable, complex functors. The callable can be applied to zero or more existing columns and it will always receive their _nominal_ values in input. -**Varying multiple columns in lockstep** +#### Varying multiple columns in lockstep In the following Python snippet we use the Vary() signature that allows varying multiple columns simultaneously or "in lockstep": @@ -975,7 +1035,7 @@ this case we also have to explicitly pass a variation name as there is no one co The call above will produce variations "ptAndEta:down" and "ptAndEta:up". -**Combining multiple variations** +#### Combining multiple variations Even if a result depends on multiple variations, only one is applied at a time, i.e. there will be no result produced by applying multiple systematic variations at the same time. @@ -1233,26 +1293,56 @@ Notice how we created one `double` variable for each processing slot and later m \anchor friends -### Friend trees -Friend TTrees are supported by RDataFrame. -Friend TTrees with a TTreeIndex are supported starting from ROOT v6.24. +### Dataset joins with friend trees -To use friend trees in RDataFrame, it is necessary to add the friends directly to -the tree and instantiate an RDataFrame with the main tree: +Vertically concatenating multiple trees that have the same columns (creating a logical dataset with the same columns and +more rows) is trivial in RDataFrame: just pass the tree name and a list of file names to RDataFrame's constructor, or create a TChain +out of the desired trees and pass that to RDataFrame. + +Horizontal concatenations of trees or chains (creating a logical dataset with the same number of rows and the union of the +columns of multiple trees) leverages TTree's "friend" mechanism. + +Simple joins of trees that do not have the same number of rows are also possible with indexed friend trees (see below). + +To use friend trees in RDataFrame, set up trees with the appropriate relationships and then instantiate an RDataFrame +with the main tree: ~~~{.cpp} -TTree t([...]); -TTree ft([...]); -t.AddFriend(&ft, "myFriend"); +TTree main([...]); +TTree friend([...]); +main.AddFriend(&friend, "myFriend"); -RDataFrame d(t); -auto f = d.Filter("myFriend.MyCol == 42"); +RDataFrame df(main); +auto df2 = df.Filter("myFriend.MyCol == 42"); ~~~ -Columns coming from the friend trees can be referred to by their full name, like in the example above, +The same applies for TChains. Columns coming from the friend trees can be referred to by their full name, like in the example above, or the friend tree name can be omitted in case the column name is not ambiguous (e.g. "MyCol" could be used instead of - "myFriend.MyCol" in the example above). +"myFriend.MyCol" in the example above if there is no column "MyCol" in the main tree). +\note A common source of confusion is that trees that are written out from a multi-thread Snapshot() call will have their + entries (block-wise) shuffled with respect to the original tree. Such trees cannot be used as friends of the original + one: rows will be mismatched. + +Indexed friend trees provide a way to perform simple joins of multiple trees over a common column. +When a certain entry in the main tree (or chain) is loaded, the friend trees (or chains) will then load an entry where the +"index" columns have a value identical to the one in the main one. For example, in Python: + +~~~{.py} +main_tree = ... +aux_tree = ... + +# If a friend tree has an index on `commonColumn`, when the main tree loads +# a given row, it also loads the row of the friend tree that has the same +# value of `commonColumn` +aux_tree.BuildIndex("commonColumn") + +mainTree.AddFriend(aux_tree) + +df = ROOT.RDataFrame(mainTree) +~~~ + +RDataFrame supports indexed friend TTrees from ROOT v6.24 in single-thread mode and from v6.28/02 in multi-thread mode. \anchor other-file-formats ### Reading data formats other than ROOT trees @@ -1262,7 +1352,7 @@ RDataFrame calls into concrete RDataSource implementations to retrieve informati and to advance the readers to the desired data entry. Some predefined RDataSources are natively provided by ROOT such as the ROOT::RDF::RCsvDS which allows to read comma separated files: ~~~{.cpp} -auto tdf = ROOT::RDF::MakeCsvDataFrame("MuRun2010B.csv"); +auto tdf = ROOT::RDF::FromCSV("MuRun2010B.csv"); auto filteredEvents = tdf.Filter("Q1 * Q2 == -1") .Define("m", "sqrt(pow(E1 + E2, 2) - (pow(px1 + px2, 2) + pow(py1 + py2, 2) + pow(pz1 + pz2, 2)))"); @@ -1337,6 +1427,96 @@ verbosity = ROOT.Experimental.RLogScopedVerbosity(ROOT.Detail.RDF.RDFLogChannel( More information (e.g. start and end of each multi-thread task) is printed using `ELogLevel.kDebug` and even more (e.g. a full dump of the generated code that RDataFrame just-in-time-compiles) using `ELogLevel.kDebug+10`. + +\anchor rdf-from-spec +### Creating an RDataFrame from a dataset specification file + +RDataFrame can be created using a dataset specification JSON file: + +~~~{.python} +import ROOT + +df = ROOT.RDF.Experimental.FromSpec("spec.json") +~~~ + +The input dataset specification JSON file needs to be provided by the user and it describes all necessary samples and +their associated metadata information. The main required key is the "samples" (at least one sample is needed) and the +required sub-keys for each sample are "trees" and "files". Additionally, one can specify a metadata dictionary for each +sample in the "metadata" key. + +A simple example for the formatting of the specification in the JSON file is the following: + +~~~{.cpp} +{ + "samples": { + "sampleA": { + "trees": ["tree1", "tree2"], + "files": ["file1.root", "file2.root"], + "metadata": { + "lumi": 10000.0, + "xsec": 1.0, + "sample_category" = "data" + } + }, + "sampleB": { + "trees": ["tree3", "tree4"], + "files": ["file3.root", "file4.root"], + "metadata": { + "lumi": 0.5, + "xsec": 1.5, + "sample_category" = "MC_background" + } + } + } +} +~~~ + +The metadata information from the specification file can be then accessed using the DefinePerSample function. +For example, to access luminosity information (stored as a double): + +~~~{.python} +df.DefinePerSample("lumi", 'rdfsampleinfo_.GetD("lumi")') +~~~ + +or sample_category information (stored as a string): + +~~~{.python} +df.DefinePerSample("sample_category", 'rdfsampleinfo_.GetS("sample_category")') +~~~ + +or directly the filename: + +~~~{.python} +df.DefinePerSample("name", "rdfsampleinfo_.GetSampleName()") +~~~ + +An example implementation of the "FromSpec" method is available in tutorial: df106_HiggstoFourLeptons.py, which also +provides a corresponding exemplary JSON file for the dataset specification. + +\anchor progressbar +### Adding a progress bar + +A progress bar showing the processed event statistics can be added to any RDataFrame program. +The event statistics include elapsed time, currently processed file, currently processed events, the rate of event processing +and an estimated remaining time (per file being processed). It is recorded and printed in the terminal every m events and every +n seconds (by default m = 1000 and n = 1). The ProgressBar can be also added when the multithread (MT) mode is enabled. + +ProgressBar is added after creating the dataframe object (df): +~~~{.cpp} +ROOT::RDataFrame df("tree", "file.root"); +ROOT::RDF::Experimental::AddProgressbar(df); +~~~ + +Alternatively, RDataFrame can be cast to an RNode first, giving the user more flexibility +For example, it can be called at any computational node, such as Filter or Define, not only the head node, +with no change to the Progressbar function itself: +~~~{.cpp} +ROOT::RDataFrame df("tree", "file.root"); +auto df_1 = ROOT::RDF::RNode(df.Filter("x>1")); +ROOT::RDF::Experimental::AddProgressbar(df_1); +~~~ +Examples of implemented progress bars can be seen by running [Higgs to Four Lepton tutorial](https://root.cern/doc/master/df106__HiggsToFourLeptons_8py_source.html) and [Dimuon tutorial](https://root.cern/doc/master/df102__NanoAODDimuonAnalysis_8C.html). + */ // clang-format on @@ -1387,7 +1567,7 @@ RDataFrame::RDataFrame(std::string_view treeName, std::string_view filenameglob, { const std::string treeNameInt(treeName); const std::string filenameglobInt(filenameglob); - auto chain = std::make_shared(treeNameInt.c_str(), "", TChain::kWithoutGlobalRegistration); + auto chain = ROOT::Internal::TreeUtils::MakeChainForMT(treeNameInt); chain->Add(filenameglobInt.c_str()); GetProxiedPtr()->SetTree(std::move(chain)); } @@ -1408,7 +1588,7 @@ RDataFrame::RDataFrame(std::string_view treeName, const std::vector : RInterface(std::make_shared(nullptr, defaultColumns)) { std::string treeNameInt(treeName); - auto chain = std::make_shared(treeNameInt.c_str(), "", TChain::kWithoutGlobalRegistration); + auto chain = ROOT::Internal::TreeUtils::MakeChainForMT(treeNameInt); for (auto &f : fileglobs) chain->Add(f.c_str()); GetProxiedPtr()->SetTree(std::move(chain)); @@ -1460,12 +1640,18 @@ RDataFrame::RDataFrame(std::unique_ptr ds, const ColumnN /// A dataset specification includes trees and file names, /// as well as an optional friend list and/or entry range. /// -/// ### Example usage: +/// ### Example usage from Python: /// ~~~{.py} -/// spec = ROOT.RDF.Experimental.RDatasetSpec("tree", "file.root", (3, 5)) -/// spec.AddFriend([("tree1", "a.root"), ("tree2", "b.root")], "alias") +/// spec = ( +/// ROOT.RDF.Experimental.RDatasetSpec() +/// .AddSample(("data", "tree", "file.root")) +/// .WithGlobalFriends("friendTree", "friend.root", "alias") +/// .WithGlobalRange((100, 200)) +/// ) /// df = ROOT.RDataFrame(spec) /// ~~~ +/// +/// See also ROOT::RDataFrame::FromSpec(). RDataFrame::RDataFrame(ROOT::RDF::Experimental::RDatasetSpec spec) : RInterface(std::make_shared(std::move(spec))) { @@ -1474,30 +1660,90 @@ RDataFrame::RDataFrame(ROOT::RDF::Experimental::RDatasetSpec spec) namespace RDF { namespace Experimental { +//////////////////////////////////////////////////////////////////////////// +/// \brief Create the RDataFrame from the dataset specification file. +/// \param[in] jsonFile Path to the dataset specification JSON file. +/// +/// The input dataset specification JSON file must include a number of keys that +/// describe all the necessary samples and their associated metadata information. +/// The main key, "samples", is required and at least one sample is needed. Each +/// sample must have at least one key "trees" and at least one key "files" from +/// which the data is read. Optionally, one or more metadata information can be +/// added, as well as the friend list information. +/// +/// ### Example specification file JSON: +/// The following is an example of the dataset specification JSON file formatting: +///~~~{.cpp} +/// { +/// "samples": { +/// "sampleA": { +/// "trees": ["tree1", "tree2"], +/// "files": ["file1.root", "file2.root"], +/// "metadata": {"lumi": 1.0, } +/// }, +/// "sampleB": { +/// "trees": ["tree3", "tree4"], +/// "files": ["file3.root", "file4.root"], +/// "metadata": {"lumi": 0.5, } +/// }, +/// ... +/// }, +/// } +///~~~ ROOT::RDataFrame FromSpec(const std::string &jsonFile) { - const nlohmann::json fullData = nlohmann::json::parse(std::ifstream(jsonFile)); - RDatasetSpec spec; + const nlohmann::ordered_json fullData = nlohmann::ordered_json::parse(std::ifstream(jsonFile)); + if (!fullData.contains("samples") || fullData["samples"].size() == 0) { + throw std::runtime_error( + R"(The input specification does not contain any samples. Please provide the samples in the specification like: +{ + "samples": { + "sampleA": { + "trees": ["tree1", "tree2"], + "files": ["file1.root", "file2.root"], + "metadata": {"lumi": 1.0, } + }, + "sampleB": { + "trees": ["tree3", "tree4"], + "files": ["file3.root", "file4.root"], + "metadata": {"lumi": 0.5, } + }, + ... + }, +})"); + } - for (const auto &groups : fullData["groups"]) { - std::string tag = groups["tag"]; + RDatasetSpec spec; + for (const auto &keyValue : fullData["samples"].items()) { + const std::string &sampleName = keyValue.key(); + const auto &sample = keyValue.value(); // TODO: if requested in https://github.com/root-project/root/issues/11624 // allow union-like types for trees and files, see: https://github.com/nlohmann/json/discussions/3815 - std::vector trees = groups["trees"]; - std::vector files = groups["files"]; - RMetaData m; - for (const auto &metadata : groups["metadata"].items()) { - const auto &val = metadata.value(); - if (val.is_string()) - m.Add(metadata.key(), val.get()); - else if (val.is_number_integer()) - m.Add(metadata.key(), val.get()); - else if (val.is_number_float()) - m.Add(metadata.key(), val.get()); - else - throw std::logic_error("The metadata keys can only be of type [string|int|double]."); + if (!sample.contains("trees")) { + throw std::runtime_error("A list of tree names must be provided for sample " + sampleName + "."); + } + std::vector trees = sample["trees"]; + if (!sample.contains("files")) { + throw std::runtime_error("A list of files must be provided for sample " + sampleName + "."); + } + std::vector files = sample["files"]; + if (!sample.contains("metadata")) { + spec.AddSample(RSample{sampleName, trees, files}); + } else { + RMetaData m; + for (const auto &metadata : sample["metadata"].items()) { + const auto &val = metadata.value(); + if (val.is_string()) + m.Add(metadata.key(), val.get()); + else if (val.is_number_integer()) + m.Add(metadata.key(), val.get()); + else if (val.is_number_float()) + m.Add(metadata.key(), val.get()); + else + throw std::logic_error("The metadata keys can only be of type [string|int|double]."); + } + spec.AddSample(RSample{sampleName, trees, files, m}); } - spec.AddGroup(RDatasetGroup{tag, trees, files, m}); } if (fullData.contains("friends")) { for (const auto &friends : fullData["friends"].items()) { diff --git a/tree/dataframe/src/RDatasetSpec.cxx b/tree/dataframe/src/RDatasetSpec.cxx index a20ecc4646e67..1480c53fb669d 100644 --- a/tree/dataframe/src/RDatasetSpec.cxx +++ b/tree/dataframe/src/RDatasetSpec.cxx @@ -28,20 +28,20 @@ RDatasetSpec::REntryRange::REntryRange(Long64_t begin, Long64_t end) : fBegin(be "creation of a dataset specification."); } -const std::vector RDatasetSpec::GetGroupNames() const +const std::vector RDatasetSpec::GetSampleNames() const { - std::vector groupNames; - groupNames.reserve(fDatasetGroups.size()); - for (const auto &group : fDatasetGroups) - groupNames.emplace_back(group.GetGroupName()); - return groupNames; + std::vector sampleNames; + sampleNames.reserve(fSamples.size()); + for (const auto &sample : fSamples) + sampleNames.emplace_back(sample.GetSampleName()); + return sampleNames; } const std::vector RDatasetSpec::GetTreeNames() const { std::vector treeNames; - for (const auto &group : fDatasetGroups) { - const auto &trees = group.GetTreeNames(); + for (const auto &sample : fSamples) { + const auto &trees = sample.GetTreeNames(); treeNames.insert(std::end(treeNames), std::begin(trees), std::end(trees)); } return treeNames; @@ -50,8 +50,8 @@ const std::vector RDatasetSpec::GetTreeNames() const const std::vector RDatasetSpec::GetFileNameGlobs() const { std::vector fileNames; - for (const auto &group : fDatasetGroups) { - const auto &files = group.GetFileNameGlobs(); + for (const auto &sample : fSamples) { + const auto &files = sample.GetFileNameGlobs(); fileNames.insert(std::end(fileNames), std::begin(files), std::end(files)); } return fileNames; @@ -60,9 +60,9 @@ const std::vector RDatasetSpec::GetFileNameGlobs() const const std::vector RDatasetSpec::GetMetaData() const { std::vector metaDatas; - metaDatas.reserve(fDatasetGroups.size()); - for (const auto &group : fDatasetGroups) - metaDatas.emplace_back(group.GetMetaData()); + metaDatas.reserve(fSamples.size()); + for (const auto &sample : fSamples) + metaDatas.emplace_back(sample.GetMetaData()); return metaDatas; } @@ -81,15 +81,15 @@ Long64_t RDatasetSpec::GetEntryRangeEnd() const return fEntryRange.fEnd; } -const std::vector &RDatasetSpec::GetDatasetGroups() const +std::vector RDatasetSpec::MoveOutSamples() { - return fDatasetGroups; + return std::move(fSamples); } -RDatasetSpec &RDatasetSpec::AddGroup(RDatasetGroup datasetGroup) +RDatasetSpec &RDatasetSpec::AddSample(RSample sample) { - datasetGroup.SetGroupId(fDatasetGroups.size()); - fDatasetGroups.push_back(std::move(datasetGroup)); + sample.SetSampleId(fSamples.size()); + fSamples.push_back(std::move(sample)); return *this; } @@ -100,6 +100,22 @@ RDatasetSpec::WithGlobalFriends(const std::string &treeName, const std::string & return *this; } +//////////////////////////////////////////////////////////////////////////////// +/// \brief Add friend tree to RDatasetSpec object +/// +/// \param[in] treeName Name of the tree. +/// \param[in] fileNameGlob Path to the file. Refer to TChain::Add for globbing rules. +/// \param[in] alias Alias for this friend. +/// +/// ### Example usage: +/// ~~~{.cpp} +/// ROOT::RDF::Experimental::RDatasetSpec x; +/// std::vector files = {"outputFile.root"}; +/// //create RSample object with name myPhysicsDf and tree outputTree1 +/// ROOT::RDF::Experimental::RSample r("myPhysicsDf", "outputTree1", files); +/// x.AddSample(r); //add RDatasetSpec to RDatasetSpec +/// x.WithGlobalFriends("outputTree2", files); //add friend tree outputTree2 +/// ~~~ RDatasetSpec &RDatasetSpec::WithGlobalFriends(const std::string &treeName, const std::vector &fileNameGlobs, const std::string &alias) { diff --git a/tree/dataframe/src/RInterface.cxx b/tree/dataframe/src/RInterface.cxx new file mode 100644 index 0000000000000..257de26bd6927 --- /dev/null +++ b/tree/dataframe/src/RInterface.cxx @@ -0,0 +1,41 @@ +// Author: Vincenzo Eduardo Padulano, Axel Naumann, Enrico Guiraud CERN 02/2023 + +/************************************************************************* + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include "ROOT/RDF/RInterface.hxx" + +void ROOT::Internal::RDF::ChangeEmptyEntryRange(const ROOT::RDF::RNode &node, + std::pair &&newRange) +{ + R__ASSERT(newRange.second >= newRange.first && "end is less than begin in the passed entry range!"); + node.GetLoopManager()->SetEmptyEntryRange(std::move(newRange)); +} + +/** + * \brief Changes the input dataset specification of an RDataFrame. + * + * \param node Any node of the computation graph. + * \param spec The new specification. + */ +void ROOT::Internal::RDF::ChangeSpec(const ROOT::RDF::RNode &node, ROOT::RDF::Experimental::RDatasetSpec &&spec) +{ + node.GetLoopManager()->ChangeSpec(std::move(spec)); +} + +/** + * \brief Trigger the execution of an RDataFrame computation graph. + * \param[in] node A node of the computation graph (not a result). + * + * This function calls the RLoopManager::Run method on the \p fLoopManager data + * member of the input argument. It is intended for internal use only. + */ +void ROOT::Internal::RDF::TriggerRun(ROOT::RDF::RNode node) +{ + node.fLoopManager->Run(); +} diff --git a/tree/dataframe/src/RInterfaceBase.cxx b/tree/dataframe/src/RInterfaceBase.cxx index 13af3159246b8..69f68076f8f31 100644 --- a/tree/dataframe/src/RInterfaceBase.cxx +++ b/tree/dataframe/src/RInterfaceBase.cxx @@ -24,6 +24,18 @@ #include #include +unsigned int ROOT::RDF::RInterfaceBase::GetNFiles() +{ + // TTree/TChain as input + const auto tree = fLoopManager->GetTree(); + + if (tree) { + const auto files = ROOT::Internal::TreeUtils::GetFileNamesFromTree(*tree); + return files.size(); + } + return 0; +} + std::string ROOT::RDF::RInterfaceBase::DescribeDataset() const { // TTree/TChain as input @@ -262,9 +274,7 @@ ROOT::RDF::RDFDescription ROOT::RDF::RInterfaceBase::Describe() if (definedColumnNamesSet.find(columnNames[i]) != definedColumnNamesSet.end()) origin = "Define"; ss << std::left << std::setw(columnWidthNames) << columnNames[i] << std::setw(columnWidthTypes) << columnTypes[i] - << origin; - if (i < nCols - 1) - ss << '\n'; + << origin << '\n'; } // Use the string returned from DescribeDataset() as the 'brief' description // Use the converted to string stringstream ss as the 'full' description diff --git a/tree/dataframe/src/RJittedAction.cxx b/tree/dataframe/src/RJittedAction.cxx index e93960896dce4..cbd6d21aa9b41 100644 --- a/tree/dataframe/src/RJittedAction.cxx +++ b/tree/dataframe/src/RJittedAction.cxx @@ -153,3 +153,9 @@ std::unique_ptr RJittedAction::MakeVariedActio assert(fConcreteAction != nullptr); return fConcreteAction->MakeVariedAction(std::move(results)); } + +std::unique_ptr RJittedAction::CloneAction(void *newResult) +{ + assert(fConcreteAction != nullptr); + return fConcreteAction->CloneAction(newResult); +} diff --git a/tree/dataframe/src/RLoopManager.cxx b/tree/dataframe/src/RLoopManager.cxx index 7108abc14cbb5..76563581b84be 100644 --- a/tree/dataframe/src/RLoopManager.cxx +++ b/tree/dataframe/src/RLoopManager.cxx @@ -351,9 +351,12 @@ RLoopManager::RLoopManager(TTree *tree, const ColumnNames_t &defaultBranches) } RLoopManager::RLoopManager(ULong64_t nEmptyEntries) - : fNEmptyEntries(nEmptyEntries), fNSlots(RDFInternal::GetNSlots()), - fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kNoFilesMT : ELoopType::kNoFiles), fNewSampleNotifier(fNSlots), - fSampleInfos(fNSlots), fDatasetColumnReaders(fNSlots) + : fEmptyEntryRange(0, nEmptyEntries), + fNSlots(RDFInternal::GetNSlots()), + fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kNoFilesMT : ELoopType::kNoFiles), + fNewSampleNotifier(fNSlots), + fSampleInfos(fNSlots), + fDatasetColumnReaders(fNSlots) { } @@ -366,58 +369,63 @@ RLoopManager::RLoopManager(std::unique_ptr ds, const ColumnNames_t } RLoopManager::RLoopManager(ROOT::RDF::Experimental::RDatasetSpec &&spec) - : fBeginEntry(spec.GetEntryRangeBegin()), fEndEntry(spec.GetEntryRangeEnd()), - fDatasetGroups(spec.GetDatasetGroups()), fNSlots(RDFInternal::GetNSlots()), + : fNSlots(RDFInternal::GetNSlots()), fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kROOTFilesMT : ELoopType::kROOTFiles), - fNewSampleNotifier(fNSlots), fSampleInfos(fNSlots), fDatasetColumnReaders(fNSlots) + fNewSampleNotifier(fNSlots), + fSampleInfos(fNSlots), + fDatasetColumnReaders(fNSlots) +{ + ChangeSpec(std::move(spec)); +} + +/** + * @brief Changes the internal TTree held by the RLoopManager. + * + * @warning This method may lead to potentially dangerous interactions if used + * after the construction of the RDataFrame. Changing the specification makes + * sense *if and only if* the schema of the dataset is *unchanged*, i.e. the + * new specification refers to exactly the same number of columns, with the + * same names and types. The actual use case of this method is moving the + * processing of the same RDataFrame to a different range of entries of the + * same dataset (which may be stored in a different set of files). + * + * @param spec The specification of the dataset to be adopted. + */ +void RLoopManager::ChangeSpec(ROOT::RDF::Experimental::RDatasetSpec &&spec) { - auto chain = std::make_shared(""); - for (auto &group : fDatasetGroups) { - const auto &trees = group.GetTreeNames(); - const auto &files = group.GetFileNameGlobs(); - for (auto i = 0u; i < files.size(); ++i) { - const auto fullpath = files[i] + "/" + trees[i]; // TODO: use ?# once #11483 is solved + // Change the range of entries to be processed + fBeginEntry = spec.GetEntryRangeBegin(); + fEndEntry = spec.GetEntryRangeEnd(); + + // Store the samples + fSamples = spec.MoveOutSamples(); + fSampleMap.clear(); + + // Create the internal main chain + auto chain = ROOT::Internal::TreeUtils::MakeChainForMT(); + for (auto &sample : fSamples) { + const auto &trees = sample.GetTreeNames(); + const auto &files = sample.GetFileNameGlobs(); + for (std::size_t i = 0ul; i < files.size(); ++i) { + // We need to use `?#` as an argument to TChain::Add + // (see https://github.com/root-project/root/pull/8820 for why) + const auto fullpath = files[i] + "?#" + trees[i]; chain->Add(fullpath.c_str()); - fDatasetGroupMap[fullpath] = &group; + // ...but instead we use `/` as a sample ID (cannot + // change this easily because of backward compatibility: the sample ID + // is exposed to users via RSampleInfo and DefinePerSample). + const auto sampleId = files[i] + '/' + trees[i]; + fSampleMap.insert({sampleId, &sample}); } } - SetTree(std::move(chain)); - // Create the friends from the list of friends + // Create friends from the specification and connect them to the main chain const auto &friendInfo = spec.GetFriendInfo(); - const auto &friendNames = friendInfo.fFriendNames; - const auto &friendFileNames = friendInfo.fFriendFileNames; - const auto &friendChainSubNames = friendInfo.fFriendChainSubNames; - const auto nFriends = friendNames.size(); - - for (auto i = 0u; i < nFriends; ++i) { - const auto &thisFriendName = friendNames[i].first; - const auto &thisFriendAlias = friendNames[i].second; - const auto &thisFriendFiles = friendFileNames[i]; - const auto &thisFriendChainSubNames = friendChainSubNames[i]; - - // Build a friend chain - auto frChain = std::make_unique(thisFriendName.c_str()); - const auto nFileNames = friendFileNames[i].size(); - if (thisFriendChainSubNames.empty()) { - // If there are no chain subnames, the friend was a TTree. It's safe - // to add to the chain the filename directly. - for (auto j = 0u; j < nFileNames; ++j) { - frChain->Add(thisFriendFiles[j].c_str()); - } - } else { - // Otherwise, the new friend chain needs to be built using the nomenclature - // "filename/treename" as argument to `TChain::Add` - for (auto j = 0u; j < nFileNames; ++j) { - frChain->Add((thisFriendFiles[j] + "/" + thisFriendChainSubNames[j]).c_str()); - } - } - - // Make it friends with the main chain - fTree->AddFriend(frChain.get(), thisFriendAlias.c_str()); - // the friend trees must have same lifetime as fTree - fFriends.emplace_back(std::move(frChain)); + fFriends = ROOT::Internal::TreeUtils::MakeFriends(friendInfo); + for (std::size_t i = 0ul; i < fFriends.size(); i++) { + const auto &thisFriendAlias = friendInfo.fFriendNames[i].second; + fTree->AddFriend(fFriends[i].get(), thisFriendAlias.c_str()); } } @@ -428,18 +436,19 @@ void RLoopManager::RunEmptySourceMT() ROOT::Internal::RSlotStack slotStack(fNSlots); // Working with an empty tree. // Evenly partition the entries according to fNSlots. Produce around 2 tasks per slot. - const auto nEntriesPerSlot = fNEmptyEntries / (fNSlots * 2); - auto remainder = fNEmptyEntries % (fNSlots * 2); + const auto nEmptyEntries = GetNEmptyEntries(); + const auto nEntriesPerSlot = nEmptyEntries / (fNSlots * 2); + auto remainder = nEmptyEntries % (fNSlots * 2); std::vector> entryRanges; - ULong64_t start = 0; - while (start < fNEmptyEntries) { - ULong64_t end = start + nEntriesPerSlot; + ULong64_t begin = fEmptyEntryRange.first; + while (begin < fEmptyEntryRange.second) { + ULong64_t end = begin + nEntriesPerSlot; if (remainder > 0) { ++end; --remainder; } - entryRanges.emplace_back(start, end); - start = end; + entryRanges.emplace_back(begin, end); + begin = end; } // Each task will generate a subrange of entries @@ -471,11 +480,13 @@ void RLoopManager::RunEmptySourceMT() void RLoopManager::RunEmptySource() { InitNodeSlots(nullptr, 0); - R__LOG_DEBUG(0, RDFLogChannel()) << LogRangeProcessing({"an empty source", 0, fNEmptyEntries, 0u}); + R__LOG_DEBUG(0, RDFLogChannel()) << LogRangeProcessing( + {"an empty source", fEmptyEntryRange.first, fEmptyEntryRange.second, 0u}); RCallCleanUpTask cleanup(*this); try { - UpdateSampleInfo(/*slot*/0, {0, fNEmptyEntries}); - for (ULong64_t currEntry = 0; currEntry < fNEmptyEntries && fNStopsReceived < fNChildren; ++currEntry) { + UpdateSampleInfo(/*slot*/ 0, fEmptyEntryRange); + for (ULong64_t currEntry = fEmptyEntryRange.first; + currEntry < fEmptyEntryRange.second && fNStopsReceived < fNChildren; ++currEntry) { RunAndCheckFilters(0, currEntry); } } catch (...) { @@ -571,7 +582,7 @@ void RLoopManager::RunTreeReader() void RLoopManager::RunDataSource() { assert(fDataSource != nullptr); - fDataSource->CallInitialize(); + fDataSource->Initialize(); auto ranges = fDataSource->GetEntryRanges(); while (!ranges.empty() && fNStopsReceived < fNChildren) { InitNodeSlots(nullptr, 0u); @@ -592,10 +603,10 @@ void RLoopManager::RunDataSource() std::cerr << "RDataFrame::Run: event loop was interrupted\n"; throw; } - fDataSource->CallFinalizeSlot(0u); + fDataSource->FinalizeSlot(0u); ranges = fDataSource->GetEntryRanges(); } - fDataSource->CallFinalize(); + fDataSource->Finalize(); } /// Run event loop over data accessed through a DataSource, in parallel. @@ -626,16 +637,16 @@ void RLoopManager::RunDataSourceMT() std::cerr << "RDataFrame::Run: event loop was interrupted\n"; throw; } - fDataSource->CallFinalizeSlot(slot); + fDataSource->FinalizeSlot(slot); }; - fDataSource->CallInitialize(); + fDataSource->Initialize(); auto ranges = fDataSource->GetEntryRanges(); while (!ranges.empty()) { pool.Foreach(runOnRange, ranges); ranges = fDataSource->GetEntryRanges(); } - fDataSource->CallFinalize(); + fDataSource->Finalize(); #endif // not implemented otherwise (never called) } @@ -650,11 +661,11 @@ void RLoopManager::RunAndCheckFilters(unsigned int slot, Long64_t entry) fNewSampleNotifier.UnsetFlag(slot); } - for (auto &actionPtr : fBookedActions) + for (auto *actionPtr : fBookedActions) actionPtr->Run(slot, entry); - for (auto &namedFilterPtr : fBookedNamedFilters) + for (auto *namedFilterPtr : fBookedNamedFilters) namedFilterPtr->CheckFilters(slot, entry); - for (auto &callback : fCallbacks) + for (auto &callback : fCallbacksEveryNEvents) callback(slot); } @@ -664,13 +675,13 @@ void RLoopManager::RunAndCheckFilters(unsigned int slot, Long64_t entry) void RLoopManager::InitNodeSlots(TTreeReader *r, unsigned int slot) { SetupSampleCallbacks(r, slot); - for (auto &ptr : fBookedActions) + for (auto *ptr : fBookedActions) ptr->InitSlot(r, slot); - for (auto &ptr : fBookedFilters) + for (auto *ptr : fBookedFilters) ptr->InitSlot(r, slot); - for (auto &ptr : fBookedDefines) + for (auto *ptr : fBookedDefines) ptr->InitSlot(r, slot); - for (auto &ptr : fBookedVariations) + for (auto *ptr : fBookedVariations) ptr->InitSlot(r, slot); for (auto &callback : fCallbacksOnce) @@ -709,9 +720,8 @@ void RLoopManager::UpdateSampleInfo(unsigned int slot, TTreeReader &r) { if (range.second == -1) { range.second = tree->GetEntries(); // convert '-1', i.e. 'until the end', to the actual entry number } - const std::string &id = fname + "/" + treename; - fSampleInfos[slot] = - fDatasetGroupMap.empty() ? RSampleInfo(id, range) : RSampleInfo(id, range, *fDatasetGroupMap[id]); + const std::string &id = fname + '/' + treename; + fSampleInfos[slot] = fSampleMap.empty() ? RSampleInfo(id, range) : RSampleInfo(id, range, fSampleMap[id]); } /// Initialize all nodes of the functional graph before running the event loop. @@ -721,11 +731,11 @@ void RLoopManager::UpdateSampleInfo(unsigned int slot, TTreeReader &r) { void RLoopManager::InitNodes() { EvalChildrenCounts(); - for (auto &filter : fBookedFilters) + for (auto *filter : fBookedFilters) filter->InitNode(); - for (auto &range : fBookedRanges) + for (auto *range : fBookedRanges) range->InitNode(); - for (auto &ptr : fBookedActions) + for (auto *ptr : fBookedActions) ptr->Initialize(); } @@ -735,7 +745,7 @@ void RLoopManager::CleanUpNodes() fMustRunNamedFilters = false; // forget RActions and detach TResultProxies - for (auto &ptr : fBookedActions) + for (auto *ptr : fBookedActions) ptr->Finalize(); fRunActions.insert(fRunActions.begin(), fBookedActions.begin(), fBookedActions.end()); @@ -744,14 +754,13 @@ void RLoopManager::CleanUpNodes() // reset children counts fNChildren = 0; fNStopsReceived = 0; - for (auto &ptr : fBookedFilters) + for (auto *ptr : fBookedFilters) ptr->ResetChildrenCount(); - for (auto &ptr : fBookedRanges) + for (auto *ptr : fBookedRanges) ptr->ResetChildrenCount(); - fCallbacks.clear(); + fCallbacksEveryNEvents.clear(); fCallbacksOnce.clear(); - fSampleCallbacks.clear(); } /// Perform clean-up operations. To be called at the end of each task execution. @@ -759,11 +768,11 @@ void RLoopManager::CleanUpTask(TTreeReader *r, unsigned int slot) { if (r != nullptr) fNewSampleNotifier.GetChainNotifyLink(slot).RemoveLink(*r->GetTree()); - for (auto &ptr : fBookedActions) + for (auto *ptr : fBookedActions) ptr->FinalizeSlot(slot); - for (auto &ptr : fBookedFilters) + for (auto *ptr : fBookedFilters) ptr->FinalizeSlot(slot); - for (auto &ptr : fBookedDefines) + for (auto *ptr : fBookedDefines) ptr->FinalizeSlot(slot); if (fLoopType == ELoopType::kROOTFiles || fLoopType == ELoopType::kROOTFilesMT) { @@ -804,9 +813,9 @@ void RLoopManager::Jit() /// the event loop so the graph branch they belong to must count as active even if it does not end in an action. void RLoopManager::EvalChildrenCounts() { - for (auto &actionPtr : fBookedActions) + for (auto *actionPtr : fBookedActions) actionPtr->TriggerChildrenCount(); - for (auto &namedFilterPtr : fBookedNamedFilters) + for (auto *namedFilterPtr : fBookedNamedFilters) namedFilterPtr->TriggerChildrenCount(); } @@ -827,8 +836,22 @@ void RLoopManager::Run(bool jit) InitNodes(); + // Exceptions can occur during the event loop. In order to ensure proper cleanup of nodes + // we use RAII: even in case of an exception, the destructor of the object is invoked and + // all the cleanup takes place. + class NodesCleanerRAII { + RLoopManager &fRLM; + + public: + NodesCleanerRAII(RLoopManager &thisRLM) : fRLM(thisRLM) {} + ~NodesCleanerRAII() { fRLM.CleanUpNodes(); } + }; + + NodesCleanerRAII runKeeper(*this); + TStopwatch s; s.Start(); + switch (fLoopType) { case ELoopType::kNoFilesMT: RunEmptySourceMT(); break; case ELoopType::kROOTFilesMT: RunTreeProcessorMT(); break; @@ -839,8 +862,6 @@ void RLoopManager::Run(bool jit) } s.Stop(); - CleanUpNodes(); - fNRuns++; R__LOG_INFO(RDFLogChannel()) << "Finished event loop number " << fNRuns - 1 << " (" << s.CpuTime() << "s CPU, " @@ -926,7 +947,7 @@ bool RLoopManager::CheckFilters(unsigned int, Long64_t) /// Call `FillReport` on all booked filters void RLoopManager::Report(ROOT::RDF::RCutFlowReport &rep) const { - for (const auto &fPtr : fBookedNamedFilters) + for (const auto *fPtr : fBookedNamedFilters) fPtr->FillReport(rep); } @@ -950,13 +971,13 @@ void RLoopManager::RegisterCallback(ULong64_t everyNEvents, std::function RLoopManager::GetFiltersNames() { std::vector filters; - for (auto &filter : fBookedFilters) { + for (auto *filter : fBookedFilters) { auto name = (filter->HasName() ? filter->GetName() : "Unnamed Filter"); filters.push_back(name); } @@ -993,7 +1014,7 @@ std::shared_ptr RLoopManager::GetG } else if (fTree) { name = fTree->GetName(); } else { - name = "Empty source\\nEntries: " + std::to_string(fNEmptyEntries); + name = "Empty source\\nEntries: " + std::to_string(GetNEmptyEntries()); } auto thisNode = std::make_shared( name, visitedMap.size(), ROOT::Internal::RDF::GraphDrawing::ENodeType::kRoot); @@ -1067,3 +1088,8 @@ void RLoopManager::AddSampleCallback(void *nodePtr, SampleCallback_t &&callback) if (callback) fSampleCallbacks.insert({nodePtr, std::move(callback)}); } + +void RLoopManager::SetEmptyEntryRange(std::pair &&newRange) +{ + fEmptyEntryRange = std::move(newRange); +} diff --git a/tree/dataframe/src/RNTupleDS.cxx b/tree/dataframe/src/RNTupleDS.cxx index 60ff68b1a3827..d65e610473852 100644 --- a/tree/dataframe/src/RNTupleDS.cxx +++ b/tree/dataframe/src/RNTupleDS.cxx @@ -16,7 +16,6 @@ #include #include -#include #include #include #include @@ -37,7 +36,7 @@ * \ingroup dataframe * \brief The RDataSource implementation for RNTuple. It lets RDataFrame read RNTuple data. * -* An RDataFrame that reads RNTuple data can be constructed using MakeNTupleDataFrame(). +* An RDataFrame that reads RNTuple data can be constructed using FromRNTuple(). * * For each column containing an array or a collection, a corresponding column `#colname` is available to access * `colname.size()` without reading and deserializing the collection values. @@ -62,6 +61,7 @@ class RRDFCardinalityField : public ROOT::Experimental::Detail::RFieldBase { { return std::make_unique(); } + void GenerateValue(void *where) const final { *static_cast(where) = 0; } public: static std::string TypeName() { return "std::size_t"; } @@ -71,56 +71,51 @@ class RRDFCardinalityField : public ROOT::Experimental::Detail::RFieldBase { RRDFCardinalityField &operator=(RRDFCardinalityField &&other) = default; ~RRDFCardinalityField() = default; + const RColumnRepresentations &GetColumnRepresentations() const final + { + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; + } // Field is only used for reading void GenerateColumnsImpl() final { assert(false && "Cardinality fields must only be used for reading"); } - - void GenerateColumnsImpl(const RNTupleDescriptor &) final + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final { - RColumnModel model(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - ROOT::Experimental::Detail::RColumn::Create(model, 0))); - fPrincipalColumn = fColumns[0].get(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back( + ROOT::Experimental::Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final - { - return ROOT::Experimental::Detail::RFieldValue(this, static_cast(where)); - } - ROOT::Experimental::Detail::RFieldValue CaptureValue(void *where) final - { - return ROOT::Experimental::Detail::RFieldValue(true /* captureFlag */, this, where); - } size_t GetValueSize() const final { return sizeof(std::size_t); } + size_t GetAlignment() const final { return alignof(std::size_t); } /// Get the number of elements of the collection identified by globalIndex - void - ReadGlobalImpl(ROOT::Experimental::NTupleSize_t globalIndex, ROOT::Experimental::Detail::RFieldValue *value) final + void ReadGlobalImpl(ROOT::Experimental::NTupleSize_t globalIndex, void *to) final { RClusterIndex collectionStart; ClusterSize_t size; fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &size); - *value->Get() = size; + *static_cast(to) = size; } /// Get the number of elements of the collection identified by clusterIndex - void ReadInClusterImpl(const ROOT::Experimental::RClusterIndex &clusterIndex, - ROOT::Experimental::Detail::RFieldValue *value) final + void ReadInClusterImpl(const ROOT::Experimental::RClusterIndex &clusterIndex, void *to) final { RClusterIndex collectionStart; ClusterSize_t size; fPrincipalColumn->GetCollectionInfo(clusterIndex, &collectionStart, &size); - *value->Get() = size; + *static_cast(to) = size; } }; /// Every RDF column is represented by exactly one RNTuple field class RNTupleColumnReader : public ROOT::Detail::RDF::RColumnReaderBase { using RFieldBase = ROOT::Experimental::Detail::RFieldBase; - using RFieldValue = ROOT::Experimental::Detail::RFieldValue; using RPageSource = ROOT::Experimental::Detail::RPageSource; std::unique_ptr fField; ///< The field backing the RDF column - RFieldValue fValue; ///< The memory location used to read from fField + RFieldBase::RValue fValue; ///< The memory location used to read from fField Long64_t fLastEntry; ///< Last entry number that was read public: @@ -128,7 +123,7 @@ class RNTupleColumnReader : public ROOT::Detail::RDF::RColumnReaderBase { : fField(std::move(f)), fValue(fField->GenerateValue()), fLastEntry(-1) { } - ~RNTupleColumnReader() { fField->DestroyValue(fValue); } + ~RNTupleColumnReader() = default; /// Column readers are created as prototype and then cloned for every slot std::unique_ptr Clone() @@ -147,7 +142,7 @@ class RNTupleColumnReader : public ROOT::Detail::RDF::RColumnReaderBase { void *GetImpl(Long64_t entry) final { if (entry != fLastEntry) { - fField->Read(entry, &fValue); + fValue.Read(entry); fLastEntry = entry; } return fValue.GetRawPtr(); @@ -232,11 +227,14 @@ void RNTupleDS::AddField(const RNTupleDescriptor &desc, std::string_view colName // The fieldID could be the root field or the class of fieldId might not be loaded. // In these cases, only the inner fields are exposed as RDF columns. - auto fieldOrException = Detail::RFieldBase::Create("", fieldDesc.GetTypeName()); + auto fieldOrException = Detail::RFieldBase::Create(fieldDesc.GetFieldName(), fieldDesc.GetTypeName()); if (!fieldOrException) return; auto valueField = fieldOrException.Unwrap(); valueField->SetOnDiskId(fieldId); + for (auto &f : *valueField) { + f.SetOnDiskId(desc.FindFieldId(f.GetName(), f.GetParent()->GetOnDiskId())); + } std::unique_ptr cardinalityField; // Collections get the additional "number of" RDF column (e.g. "R_rdf_sizeof_tracks") if (!skeinIDs.empty()) { @@ -368,13 +366,3 @@ ROOT::RDataFrame ROOT::RDF::Experimental::FromRNTuple(ROOT::Experimental::RNTupl ROOT::RDataFrame rdf(std::make_unique(ntuple->MakePageSource())); return rdf; } - -ROOT::RDataFrame ROOT::Experimental::MakeNTupleDataFrame(std::string_view ntupleName, std::string_view fileName) -{ - return ROOT::RDF::Experimental::FromRNTuple(ntupleName, fileName); -} - -ROOT::RDataFrame ROOT::Experimental::MakeNTupleDataFrame(RNTuple *ntuple) -{ - return ROOT::RDF::Experimental::FromRNTuple(ntuple); -} diff --git a/tree/dataframe/src/RRangeBase.cxx b/tree/dataframe/src/RRangeBase.cxx index ef3e2b1fd86ad..74499f3dbb7dd 100644 --- a/tree/dataframe/src/RRangeBase.cxx +++ b/tree/dataframe/src/RRangeBase.cxx @@ -11,7 +11,6 @@ #include "ROOT/RDF/RRangeBase.hxx" using ROOT::Detail::RDF::RRangeBase; -using ROOT::Detail::RDF::RLoopManager; RRangeBase::RRangeBase(RLoopManager *implPtr, unsigned int start, unsigned int stop, unsigned int stride, const unsigned int nSlots, const std::vector &prevVariations) @@ -19,7 +18,7 @@ RRangeBase::RRangeBase(RLoopManager *implPtr, unsigned int start, unsigned int s { } -void RRangeBase::ResetCounters() +void RRangeBase::InitNode() { fLastCheckedEntry = -1; fNProcessedEntries = 0; diff --git a/tree/dataframe/src/RResultPtr.cxx b/tree/dataframe/src/RResultPtr.cxx new file mode 100644 index 0000000000000..bba8b5479e4e2 --- /dev/null +++ b/tree/dataframe/src/RResultPtr.cxx @@ -0,0 +1,24 @@ +// Author: Vincenzo Eduardo Padulano, Enrico Guiraud CERN 2023/02 + +/************************************************************************* + * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. * + * All rights reserved. * + * * + * For the licensing terms see $ROOTSYS/LICENSE. * + * For the list of contributors see $ROOTSYS/README/CREDITS. * + *************************************************************************/ + +#include + +#include +#include +#include + +ROOT::Internal::RDF::SnapshotPtr_t +ROOT::Internal::RDF::CloneResultAndAction(const ROOT::Internal::RDF::SnapshotPtr_t &inptr, + const std::string &outputFileName) +{ + return ROOT::Internal::RDF::SnapshotPtr_t{ + inptr.fObjPtr, inptr.fLoopManager, + inptr.fActionPtr->CloneAction(reinterpret_cast(const_cast(&outputFileName)))}; +} diff --git a/tree/dataframe/src/RRootDS.cxx b/tree/dataframe/src/RRootDS.cxx index 1953328da2138..e29cc06847502 100644 --- a/tree/dataframe/src/RRootDS.cxx +++ b/tree/dataframe/src/RRootDS.cxx @@ -95,7 +95,6 @@ void RRootDS::InitSlot(unsigned int slot, ULong64_t firstEntry) chain->ResetBit(kMustCleanup); chain->Add(fFileNameGlob.c_str()); chain->GetEntry(firstEntry); - TString setBranches; for (auto i : ROOT::TSeqU(fListOfBranches.size())) { auto colName = fListOfBranches[i].c_str(); auto &addr = fBranchAddresses[i][slot]; diff --git a/tree/dataframe/src/RDatasetGroup.cxx b/tree/dataframe/src/RSample.cxx similarity index 53% rename from tree/dataframe/src/RDatasetGroup.cxx rename to tree/dataframe/src/RSample.cxx index cd150edc92124..4578ca08c1721 100644 --- a/tree/dataframe/src/RDatasetGroup.cxx +++ b/tree/dataframe/src/RSample.cxx @@ -8,7 +8,7 @@ * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ -#include "ROOT/RDF/RDatasetGroup.hxx" +#include "ROOT/RDF/RSample.hxx" #include "TChain.h" #include // std::logic_error @@ -16,26 +16,30 @@ namespace ROOT { namespace RDF { namespace Experimental { -RDatasetGroup::RDatasetGroup(const std::string &groupName, const std::string &treeName, const std::string &fileNameGlob, - const RMetaData &metaData) - : RDatasetGroup(groupName, std::vector{treeName}, std::vector{fileNameGlob}, metaData) +RSample::RSample(const std::string &sampleName, const std::string &treeName, const std::string &fileNameGlob, + const RMetaData &metaData) + : RSample(sampleName, std::vector{treeName}, std::vector{fileNameGlob}, metaData) { } -RDatasetGroup::RDatasetGroup(const std::string &groupName, const std::string &treeName, - const std::vector &fileNameGlobs, const RMetaData &metaData) - : RDatasetGroup(groupName, std::vector(fileNameGlobs.size(), treeName), fileNameGlobs, metaData) +RSample::RSample(const std::string &sampleName, const std::string &treeName, + const std::vector &fileNameGlobs, const RMetaData &metaData) + : RSample(sampleName, std::vector(fileNameGlobs.size(), treeName), fileNameGlobs, metaData) { } -RDatasetGroup::RDatasetGroup(const std::string &groupName, - const std::vector> &treeAndFileNameGlobs, - const RMetaData &metaData) - : fGroupName(groupName), fMetaData(metaData) +RSample::RSample(const std::string &sampleName, + const std::vector> &treeAndFileNameGlobs, + const RMetaData &metaData) + : fSampleName(sampleName), fMetaData(metaData) { + // avoid constructing and destructing the helper TChain here if we don't need to + if (treeAndFileNameGlobs.empty()) + return; + TChain chain; for (const auto &p : treeAndFileNameGlobs) { - const auto fullpath = p.second + "/" + p.first; + const auto fullpath = p.second + "?#" + p.first; chain.Add(fullpath.c_str()); } const auto &expandedNames = chain.GetListOfFiles(); @@ -47,15 +51,15 @@ RDatasetGroup::RDatasetGroup(const std::string &groupName, } } -RDatasetGroup::RDatasetGroup(const std::string &groupName, const std::vector &treeNames, - const std::vector &fileNameGlobs, const RMetaData &metaData) - : fGroupName(groupName), fMetaData(metaData) +RSample::RSample(const std::string &sampleName, const std::vector &treeNames, + const std::vector &fileNameGlobs, const RMetaData &metaData) + : fSampleName(sampleName), fMetaData(metaData) { if (treeNames.size() != 1 && treeNames.size() != fileNameGlobs.size()) throw std::logic_error("Mismatch between number of trees and file globs."); TChain chain; for (auto i = 0u; i < fileNameGlobs.size(); ++i) { - const auto fullpath = fileNameGlobs[i] + "/" + (treeNames.size() == 1u ? treeNames[0] : treeNames[i]); + const auto fullpath = fileNameGlobs[i] + "?#" + (treeNames.size() == 1u ? treeNames[0] : treeNames[i]); chain.Add(fullpath.c_str()); } const auto &expandedNames = chain.GetListOfFiles(); @@ -67,34 +71,34 @@ RDatasetGroup::RDatasetGroup(const std::string &groupName, const std::vector &RDatasetGroup::GetTreeNames() const +const std::vector &RSample::GetTreeNames() const { return fTreeNames; } -const std::vector &RDatasetGroup::GetFileNameGlobs() const +const std::vector &RSample::GetFileNameGlobs() const { return fFileNameGlobs; } -const RMetaData &RDatasetGroup::GetMetaData() const +const RMetaData &RSample::GetMetaData() const { return fMetaData; } -unsigned int RDatasetGroup::GetGroupId() const +unsigned int RSample::GetSampleId() const { - return fGroupId; + return fSampleId; } -void RDatasetGroup::SetGroupId(unsigned int id) +void RSample::SetSampleId(unsigned int id) { - fGroupId = id; + fSampleId = id; } } // namespace Experimental diff --git a/tree/dataframe/src/RSqliteDS.cxx b/tree/dataframe/src/RSqliteDS.cxx index 5be47123f4f2f..25b564ed13ebe 100644 --- a/tree/dataframe/src/RSqliteDS.cxx +++ b/tree/dataframe/src/RSqliteDS.cxx @@ -546,15 +546,6 @@ RDataFrame FromSqlite(std::string_view fileName, std::string_view query) return rdf; } -//////////////////////////////////////////////////////////////////////////////////////////////// -/// \brief Factory method to create a SQlite RDataFrame. -/// -/// Deprecated in favor of FromSqlite(). -RDataFrame MakeSqliteDataFrame(std::string_view fileName, std::string_view query) -{ - return FromSqlite(fileName, query); -} - //////////////////////////////////////////////////////////////////////////// /// Stores the result of the current active sqlite query row as a C++ value. bool RSqliteDS::SetEntry(unsigned int /* slot */, ULong64_t entry) diff --git a/tree/dataframe/test/CMakeLists.txt b/tree/dataframe/test/CMakeLists.txt index ca2b2809f5f38..415a11b7c7241 100644 --- a/tree/dataframe/test/CMakeLists.txt +++ b/tree/dataframe/test/CMakeLists.txt @@ -11,6 +11,7 @@ ROOT_ADD_GTEST(dataframe_friends dataframe_friends.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_colnames dataframe_colnames.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_cache dataframe_cache.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_callbacks dataframe_callbacks.cxx LIBRARIES ROOTDataFrame) +ROOT_ADD_GTEST(dataframe_cloning dataframe_cloning.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_histomodels dataframe_histomodels.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_interface dataframe_interface.cxx LIBRARIES ROOTDataFrame) ROOT_ADD_GTEST(dataframe_nodes dataframe_nodes.cxx LIBRARIES ROOTDataFrame) @@ -31,7 +32,7 @@ ROOT_ADD_GTEST(dataframe_redefine dataframe_redefine.cxx LIBRARIES ROOTDataFrame ROOT_ADD_GTEST(dataframe_definepersample dataframe_definepersample.cxx LIBRARIES ROOTDataFrame) if(NOT MSVC OR win_broken_tests) - ROOT_ADD_GTEST(dataframe_simple dataframe_simple.cxx LIBRARIES ROOTDataFrame) + ROOT_ADD_GTEST(dataframe_simple dataframe_simple.cxx LIBRARIES ROOTDataFrame GenVector) target_include_directories(dataframe_simple PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) ROOT_GENERATE_DICTIONARY(DataFrameSimpleDict ${CMAKE_CURRENT_SOURCE_DIR}/MaxSlotHelper.h ${CMAKE_CURRENT_SOURCE_DIR}/SimpleFiller.h MODULE dataframe_simple LINKDEF DataFrameSimpleLinkDef.h OPTIONS -inlineInputHeader DEPENDENCIES ROOTDataFrame Hist) @@ -71,6 +72,7 @@ configure_file(RCsvDS_test_empty.csv . COPYONLY) configure_file(RCsvDS_test_win.csv . COPYONLY) configure_file(RCsvDS_test_NaNs.csv . COPYONLY) configure_file(spec.json . COPYONLY) +configure_file(spec_ordering_samples_withFriends.json . COPYONLY) ROOT_ADD_GTEST(datasource_csv datasource_csv.cxx LIBRARIES ROOTDataFrame) if(MSVC AND CMAKE_SIZEOF_VOID_P EQUAL 8) set_source_files_properties(dataframe_vary.cxx COMPILE_FLAGS "-bigobj") @@ -88,6 +90,19 @@ endif() if(root7) ROOT_ADD_GTEST(datasource_ntuple datasource_ntuple.cxx LIBRARIES ROOTDataFrame) + + ROOT_STANDARD_LIBRARY_PACKAGE(NTupleStruct + NO_INSTALL_HEADERS + HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/NTupleStruct.hxx + SOURCES NTupleStruct.cxx + LINKDEF NTupleStructLinkDef.h + DEPENDENCIES RIO) + configure_file(NTupleStruct.hxx . COPYONLY) + if(MSVC) + add_custom_command(TARGET NTupleStruct POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/$/libNTupleStruct.dll + ${CMAKE_CURRENT_BINARY_DIR}/libNTupleStruct.dll) + endif() endif() if(sqlite) diff --git a/tree/dataframe/test/NTupleStruct.cxx b/tree/dataframe/test/NTupleStruct.cxx new file mode 100644 index 0000000000000..4eba2a5d9a2eb --- /dev/null +++ b/tree/dataframe/test/NTupleStruct.cxx @@ -0,0 +1 @@ +#include "NTupleStruct.hxx" diff --git a/tree/dataframe/test/NTupleStruct.hxx b/tree/dataframe/test/NTupleStruct.hxx new file mode 100644 index 0000000000000..3842aa095ba21 --- /dev/null +++ b/tree/dataframe/test/NTupleStruct.hxx @@ -0,0 +1,11 @@ +#ifndef ROOT7_RDataFrame_Test_NTupleStruct +#define ROOT7_RDataFrame_Test_NTupleStruct + +/** + * Used to test serialization and deserialization of classes in RNTuple with TClass + */ +struct Electron { + float pt; +}; + +#endif diff --git a/tree/dataframe/test/NTupleStructLinkDef.h b/tree/dataframe/test/NTupleStructLinkDef.h new file mode 100644 index 0000000000000..51f8b0aa94307 --- /dev/null +++ b/tree/dataframe/test/NTupleStructLinkDef.h @@ -0,0 +1,9 @@ +#ifdef __CLING__ + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; + +#pragma link C++ class Electron + ; + +#endif diff --git a/tree/dataframe/test/dataframe_cloning.cxx b/tree/dataframe/test/dataframe_cloning.cxx new file mode 100644 index 0000000000000..966f6571dbc68 --- /dev/null +++ b/tree/dataframe/test/dataframe_cloning.cxx @@ -0,0 +1,603 @@ +#include +#include +#include +#include +#include + +#include +#include // VariationsFor +#include // CloneResultAndAction +#include +#include +#include // ChangeEmptyEntryRange, ChangeSpec +#include // CloneResultAndAction +#include // ULong64_t +#include // AccessPathName + +#include + +using ROOT::Internal::RDF::ChangeEmptyEntryRange; +using ROOT::Internal::RDF::ChangeSpec; +using ROOT::Internal::RDF::CloneResultAndAction; + +template +void EXPECT_VEC_EQ(const std::vector &v1, const std::vector &v2) +{ + ASSERT_EQ(v1.size(), v2.size()) << "Vectors 'v1' and 'v2' are of unequal length"; + for (std::size_t i = 0ull; i < v1.size(); ++i) { + EXPECT_EQ(v1[i], v2[i]) << "Vectors 'v1' and 'v2' differ at index " << i; + } +} + +struct InputFilesRAII { + std::vector fFileNames; + + InputFilesRAII(const std::string &treeName, const std::vector &fileNames, ULong64_t entriesPerFile = 10, + const std::vector &beginEntryPerFile = {}) + : fFileNames(fileNames) + { + auto realBeginEntries = beginEntryPerFile.empty() ? std::vector(fileNames.size()) : beginEntryPerFile; + + for (std::size_t i = 0; i < fileNames.size(); i++) { + TFile f(fFileNames[i].c_str(), "recreate"); + TTree t(treeName.c_str(), treeName.c_str()); + // Always create a new TTree cluster every 10 entries + t.SetAutoFlush(10); + ULong64_t x; + t.Branch("x", &x); + for (ULong64_t j = realBeginEntries[i]; j < (realBeginEntries[i] + entriesPerFile); j++) { + x = j; + t.Fill(); + } + t.Write(); + } + } + + ~InputFilesRAII() + { + for (const auto &fileName : fFileNames) + gSystem->Unlink(fileName.c_str()); + } +}; + +TEST(RDataFrameCloning, Count) +{ + ROOT::RDataFrame df{100}; + + auto count = df.Count(); + auto clone = CloneResultAndAction(count); + + EXPECT_EQ(*count, 100); + EXPECT_EQ(*clone, 100); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Graph) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col2 = col1.Define("y", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto graph = col2.Graph("x", "y"); + auto clone = CloneResultAndAction(graph); + + EXPECT_EQ((*clone).GetN(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ((*graph).GetN(), 100); + EXPECT_DOUBLE_EQ((*graph).GetMean(), 49.5); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Mean) +{ + ROOT::RDataFrame df{10}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto mean = col1.Mean("x"); + auto clone = CloneResultAndAction(mean); + + EXPECT_DOUBLE_EQ(*mean, 4.5); + EXPECT_DOUBLE_EQ(*clone, 4.5); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Histo1DNoModel) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto histo = col1.Histo1D("x"); + auto clone = CloneResultAndAction(histo); + + EXPECT_EQ((*histo).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*histo).GetMean(), 49.5); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Histo1DModel) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto histo = col1.Histo1D({"name", "title", 100, 0, 100}, "x"); + auto clone = CloneResultAndAction(histo); + + EXPECT_EQ((*histo).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*histo).GetMean(), 49.5); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Histo1DModelTriggerBeforeCloning) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto histo = col1.Histo1D({"name", "title", 100, 0, 100}, "x"); + + EXPECT_EQ((*histo).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*histo).GetMean(), 49.5); + + auto clone = CloneResultAndAction(histo); + + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ(df.GetNRuns(), 2); +} + +TEST(RDataFrameCloning, Histo2D) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col2 = col1.Define("y", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto histo = col2.Histo2D({"name", "title", 100, 0, 100, 100, 0, 100}, "x", "y"); + auto clone = CloneResultAndAction(histo); + + EXPECT_EQ((*histo).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*histo).GetMean(), 49.5); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, HistoND) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x0", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col2 = col1.Define("x1", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col3 = col2.Define("x2", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col4 = col3.Define("x3", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + int nbins[4] = {10, 10, 10, 10}; + double xmin[4] = {0., 0., 0., 0.}; + double xmax[4] = {100., 100., 100., 100.}; + auto histo = + col4.HistoND({"name", "title", 4, nbins, xmin, xmax}, {"x0", "x1", "x2", "x3"}); + auto clone = CloneResultAndAction(histo); + + EXPECT_EQ((*histo).GetEntries(), 100); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Profile1D) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col2 = col1.Define("y", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto prof = col2.Profile1D({"name", "title", 100, 0, 100, 0, 100}, "x", "y"); + auto clone = CloneResultAndAction(prof); + + EXPECT_EQ((*prof).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*prof).GetMean(), 49.5); + EXPECT_EQ((*prof).GetMaximum(), 99); + EXPECT_EQ((*prof).GetMinimum(), 0); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ((*clone).GetMaximum(), 99); + EXPECT_EQ((*clone).GetMinimum(), 0); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Profile2D) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col2 = col1.Define("y", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + auto col3 = col2.Define("z", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto prof = col3.Profile2D({"name", "title", 100, 0, 100, 100, 0, 100}, "x", "y", "z"); + auto clone = CloneResultAndAction(prof); + + EXPECT_EQ((*prof).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*prof).GetMean(), 49.5); + EXPECT_EQ((*prof).GetMaximum(), 99); + EXPECT_EQ((*prof).GetMinimum(), 0); + EXPECT_EQ((*clone).GetEntries(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ((*clone).GetMaximum(), 99); + EXPECT_EQ((*clone).GetMinimum(), 0); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Sum) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto sum = col1.Sum("x"); + auto clone = CloneResultAndAction(sum); + + EXPECT_DOUBLE_EQ(*sum, 4950.); + EXPECT_DOUBLE_EQ(*clone, 4950.); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Min) +{ + ROOT::RDataFrame df{100}; + auto filter1 = df.Filter([](ULong64_t e) { return (e < 50); }, {"rdfentry_"}); + + auto min = filter1.Min("rdfentry_"); + auto clone = CloneResultAndAction(min); + + EXPECT_EQ(*min, 0ull); + EXPECT_EQ(*clone, 0ull); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Max) +{ + ROOT::RDataFrame df{100}; + auto filter1 = df.Filter([](ULong64_t e) { return (e < 50); }, {"rdfentry_"}); + + auto max = filter1.Max("rdfentry_"); + auto clone = CloneResultAndAction(max); + + EXPECT_EQ(*max, 49ull); + EXPECT_EQ(*clone, 49ull); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Snapshot) +{ + ROOT::RDF::RSnapshotOptions opts; + opts.fLazy = true; + + auto treeName{"events"}; + auto firstFile{"test_rdataframe_cloneactions_snapshot_1.root"}; + auto secondFile{"test_rdataframe_cloneactions_snapshot_2.root"}; + + ROOT::RDataFrame df{10}; + auto snap = df.Define("x", [] { return 10; }).Snapshot(treeName, firstFile, {"x"}, opts); + + auto clone = CloneResultAndAction(snap, secondFile); + + // This will trigger execution of both Snapshot nodes + auto clonedDf = *clone; + + // Check the Snapshot clone is usable + auto clonedSnapCount = clonedDf.Count(); + EXPECT_EQ(*clonedSnapCount, 10); + + // Check both files were produced + EXPECT_FALSE(gSystem->AccessPathName(firstFile)); + EXPECT_FALSE(gSystem->AccessPathName(secondFile)); + EXPECT_EQ(df.GetNRuns(), 1); + + gSystem->Unlink(firstFile); + gSystem->Unlink(secondFile); +} + +TEST(RDataFrameCloning, StdDev) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto dev = col1.StdDev("x"); + auto clone = CloneResultAndAction(dev); + + const double truestddev = 29.011491975882016; // True std dev computed separately + EXPECT_DOUBLE_EQ(*dev, truestddev); + EXPECT_DOUBLE_EQ(*clone, truestddev); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, Stats) +{ + ROOT::RDataFrame df{100}; + auto col1 = df.Define("x", [](ULong64_t e) { return double(e); }, {"rdfentry_"}); + + auto stats = col1.Stats("x"); + auto clone = CloneResultAndAction(stats); + + EXPECT_EQ((*stats).GetN(), 100); + EXPECT_DOUBLE_EQ((*stats).GetMean(), 49.5); + EXPECT_EQ((*stats).GetMin(), 0); + EXPECT_EQ((*stats).GetMax(), 99); + EXPECT_EQ((*clone).GetN(), 100); + EXPECT_DOUBLE_EQ((*clone).GetMean(), 49.5); + EXPECT_EQ((*clone).GetMin(), 0); + EXPECT_EQ((*clone).GetMax(), 99); + EXPECT_EQ(df.GetNRuns(), 1); +} + +TEST(RDataFrameCloning, VariedHisto) +{ + auto df = ROOT::RDataFrame(10).Define("x", [] { return 1; }); + auto h = df.Vary( + "x", + []() { + return ROOT::RVecI{-1, 2}; + }, + {}, 2) + .Histo1D("x"); + auto histos = ROOT::RDF::Experimental::VariationsFor(h); + auto clones = CloneResultAndAction(histos); + + const auto &originalKeys = histos.GetKeys(); + const auto &clonedKeys = clones.GetKeys(); + + EXPECT_VEC_EQ(originalKeys, clonedKeys); + + for (const auto &variation : originalKeys) { + const auto &histo = histos[variation]; + const auto &clone = clones[variation]; + EXPECT_EQ(histo.GetMean(), clone.GetMean()); + EXPECT_EQ(histo.GetEntries(), clone.GetEntries()); + } +} + +TEST(RDataFrameCloning, ChangeEmptyEntryRange) +{ + ROOT::RDataFrame df{10}; + auto col1 = df.Define("x", [](ULong64_t e) { return e; }, {"rdfentry_"}); + + ChangeEmptyEntryRange(df, {0, 4}); + auto take1 = col1.Take("x"); + EXPECT_VEC_EQ(*take1, {0, 1, 2, 3}); + + ChangeEmptyEntryRange(df, {4, 8}); + auto take2 = CloneResultAndAction(take1); + EXPECT_VEC_EQ(*take2, {4, 5, 6, 7}); + + ChangeEmptyEntryRange(df, {8, 10}); + auto take3 = CloneResultAndAction(take2); + EXPECT_VEC_EQ(*take3, {8, 9}); + + EXPECT_EQ(df.GetNRuns(), 3); +} + +TEST(RDataFrameCloning, ChangeSpec) +{ + std::string treeName{"events"}; + std::size_t nFiles{3}; + // Each file has 30 entries, starting from a different value + ULong64_t entriesPerFile{30}; + std::vector beginEntryPerFile{0, 30, 60}; + std::vector fileNames(nFiles); + std::string prefix{"dataframe_cloning_changespec_"}; + std::generate(fileNames.begin(), fileNames.end(), [n = 0, &prefix]() mutable { + auto name = prefix + std::to_string(n) + ".root"; + n++; + return name; + }); + InputFilesRAII files{treeName, fileNames, entriesPerFile, beginEntryPerFile}; + + // The dataset will have a total of 90 entries. We partition it in 6 different global ranges. + // Schema: one range per complete file, one range with a portion of a single file, + // two ranges that span more than one file. + std::vector> globalRanges{{0, 30}, {30, 60}, {60, 90}, {0, 20}, {20, 50}, {50, 90}}; + + std::vector specs; + specs.reserve(globalRanges.size()); + for (unsigned i = 0; i < globalRanges.size(); i++) { + ROOT::RDF::Experimental::RDatasetSpec spec; + // Every spec represents a different portion of the global dataset + spec.AddSample({"", treeName, fileNames}); + spec.WithGlobalRange({globalRanges[i].first, globalRanges[i].second}); + specs.push_back(spec); + } + + // We want to check that we are indeed changing to a different + // range of entries of the global dataset with every call to + // ChangeSpec. Do this by `Take`ing the values of column x for + // every partition and checking that they correspond to the values + // in the ranges defined by globalRanges. + std::vector> expectedOutputs; + expectedOutputs.reserve(globalRanges.size()); + for (unsigned i = 0; i < globalRanges.size(); i++) { + const auto ¤tRange = globalRanges[i]; + auto nValues{currentRange.second - currentRange.first}; + std::vector takeValues(nValues); + std::iota(takeValues.begin(), takeValues.end(), currentRange.first); + expectedOutputs.push_back(takeValues); + } + + // Launch first execution with dataset spec + ROOT::RDataFrame df{specs[0]}; + auto take = df.Take("x"); + EXPECT_VEC_EQ(*take, expectedOutputs[0]); + + // Other executions modify the internal spec + for (unsigned i = 1; i < globalRanges.size(); i++) { + ChangeSpec(df, std::move(specs[i])); + auto clone = CloneResultAndAction(take); + EXPECT_VEC_EQ(*clone, expectedOutputs[i]); + } +} + +ROOT::RDF::Experimental::RResultMap dataframe_cloning_vary_with_filters_analysis(ROOT::RDF::RNode df) +{ + auto df1 = df.Define("jet_pt", []() { return ROOT::RVecF{30, 30, 30, 10, 10, 10, 10}; }); + + auto df2 = df1.Vary("jet_pt", + [](ULong64_t) { + return ROOT::RVec{{31, 31, 31, 31, 11, 11, 11}, {29, 29, 29, 29, 9, 9, 9}}; + }, + {"rdfentry_"}, {"pt_scale_up", "pt_res_up"}); + + auto df3 = + df2.Define("jet_pt_mask", [](const ROOT::RVecF &jet_pt) { return jet_pt > 25; }, {"jet_pt"}) + .Filter([](const ROOT::RVecI &jet_pt_mask) { return ROOT::VecOps::Sum(jet_pt_mask) >= 4; }, {"jet_pt_mask"}); + + auto df4 = df3.Vary( + "weights", + [](const ROOT::RVecF &jet_pt, const ROOT::RVecI &jet_pt_mask) { + // The next line triggered an error due to a previous faulty implementation + // that was not connecting the cloned varied action to the correct upstream + // varied filters. In particular, this lambda should be run after the `Filter` + // above, which checks that the number of jets that passes the `jet_pt_mask` + // is at least 4. + auto test = ROOT::VecOps::Take(jet_pt[jet_pt_mask], 4); + return ROOT::RVecD{-1, 1}; + }, + {"jet_pt", "jet_pt_mask"}, 2); + + auto h = df4.Histo1D({"NAME", "TITLE", 10, -10, 10}, "jet_pt", "weights"); + + auto vars = ROOT::RDF::Experimental::VariationsFor(h); + + return vars; +} + +/* + * This test reproduces a particular issue happening in analysis logic + * including both systematic variations and filters, with the order + * + * 1. Some call to Vary + * 2. Filter depending on the first Vary + * 3. Another Vary that depends on the Filter + * + * The logic that reproduces the problem is shown in the above function + * `dataframe_cloning_vary_with_filters_analysis`. In particular, the + * lambda used in the Vary call (3) calls ROOT::VecOps::Take(vec, 4), + * thus only works if `vec` has at least size `4`. + * + * In a previous implementation of cloning `RVariedAction`, the cloned action + * was connected to the wrong upstream filter (in fact, it was using a varied + * filter from the original action as if it was the nominal filter). This would + * then pass to the lambda used in the downstream Vary call (3) a vector + * `jet_pt` from which only 3 entries pass `jet_pt_mask`, eventually producing + * an error when reaching the `Take(jet_pt[jet_pt_mask], 4)` call. + */ +TEST(RDataFrameCloning, VaryWithFilters) +{ + ROOT::RDataFrame d{1}; + auto df = d.Define("weights", []() { return 0.; }); + + // Create the computation graph and trigger it. + auto vars = dataframe_cloning_vary_with_filters_analysis(df); + ROOT::Internal::RDF::TriggerRun(df); + + // Clone the RResultMap and re-run the computation graph + auto vars_clone = CloneResultAndAction(vars); + ROOT::Internal::RDF::TriggerRun(df); + + // Make sure that the cloned varied results are the same + // as the original ones. + const auto &originalKeys = vars.GetKeys(); + const auto &clonedKeys = vars_clone.GetKeys(); + + EXPECT_VEC_EQ(originalKeys, clonedKeys); + for (const auto &variation : originalKeys) { + const auto &histo = vars[variation]; + const auto &clone = vars_clone[variation]; + EXPECT_DOUBLE_EQ(histo.GetMean(), clone.GetMean()); + EXPECT_EQ(histo.GetEntries(), clone.GetEntries()); + } +} + +TEST(RDataFrameCloning, DefinePerSample) +{ + std::string treeName{"events"}; + std::size_t nFiles{3}; + std::vector fileNames(nFiles); + std::string prefix{"dataframe_cloning_definepersample_"}; + std::generate(fileNames.begin(), fileNames.end(), [n = 0, &prefix]() mutable { + auto name = prefix + std::to_string(n) + ".root"; + n++; + return name; + }); + InputFilesRAII files{treeName, fileNames}; + std::vector weights(nFiles); + std::iota(weights.begin(), weights.end(), 1.); + + // The first specification takes the first two files and reads them both from beginning to end. + // The second specification takes the second and third file, but only reads the third one. + // This simulates two tasks that might be created when logically splitting the input dataset. + std::vector> globalRanges{{0, 20}, {10, 20}}; + std::vector> taskFileNames{ + {"dataframe_cloning_definepersample_0.root", "dataframe_cloning_definepersample_1.root"}, + {"dataframe_cloning_definepersample_1.root", "dataframe_cloning_definepersample_2.root"}}; + std::vector specs; + specs.reserve(2); + for (unsigned i = 0; i < 2; i++) { + ROOT::RDF::Experimental::RDatasetSpec spec; + spec.AddSample({"", treeName, taskFileNames[i]}); + spec.WithGlobalRange({globalRanges[i].first, globalRanges[i].second}); + specs.push_back(spec); + } + + // Launch first execution with dataset spec + ROOT::RDataFrame df{specs[0]}; + auto dfWithCols = + df.DefinePerSample("sample_weight", + [&weights, &fileNames](unsigned int, const ROOT::RDF::RSampleInfo &id) { + if (id.Contains(fileNames[0])) { + return weights[0]; + } else if (id.Contains(fileNames[1])) { + return weights[1]; + } else if (id.Contains(fileNames[2])) { + return weights[2]; + } else { + return -999.; + } + }) + .DefinePerSample("sample_name", [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.AsString(); }); + + // One filter per each different combination of weight and sample name + // Counting the entries passing each filter should return exactly the entries + // of the corresponding file, i.e. 10. + auto c0 = dfWithCols + .Filter( + [&weights, &fileNames, &treeName](double weight, const std::string &name) { + return weight == weights[0] && name == (fileNames[0] + "/" + treeName); + }, + {"sample_weight", "sample_name"}) + .Count(); + auto c1 = dfWithCols + .Filter( + [&weights, &fileNames, &treeName](double weight, const std::string &name) { + return weight == weights[1] && name == (fileNames[1] + "/" + treeName); + }, + {"sample_weight", "sample_name"}) + .Count(); + auto c2 = dfWithCols + .Filter( + [&weights, &fileNames, &treeName](double weight, const std::string &name) { + return weight == weights[2] && name == (fileNames[2] + "/" + treeName); + }, + {"sample_weight", "sample_name"}) + .Count(); + + std::vector expectedFirstTask{10, 10, 0}; + EXPECT_EQ(*c0, expectedFirstTask[0]); + EXPECT_EQ(*c1, expectedFirstTask[1]); + EXPECT_EQ(*c2, expectedFirstTask[2]); + + // Assign the other specification and clone actions + ChangeSpec(df, std::move(specs[1])); + auto c3 = CloneResultAndAction(c0); + auto c4 = CloneResultAndAction(c1); + auto c5 = CloneResultAndAction(c2); + std::vector expectedSecondTask{0, 0, 10}; + EXPECT_EQ(*c3, expectedSecondTask[0]); + EXPECT_EQ(*c4, expectedSecondTask[1]); + EXPECT_EQ(*c5, expectedSecondTask[2]); +} diff --git a/tree/dataframe/test/dataframe_concurrency.cxx b/tree/dataframe/test/dataframe_concurrency.cxx index 5606a111335d8..3f60ae76186ab 100644 --- a/tree/dataframe/test/dataframe_concurrency.cxx +++ b/tree/dataframe/test/dataframe_concurrency.cxx @@ -27,7 +27,7 @@ TEST(RDFConcurrency, NestedParallelismBetweenDefineCalls) // this lambda will be used to introduce nested parallelism via a dummy Filter auto manysleeps = [&] { - ROOT::TThreadExecutor().Foreach( + ROOT::TThreadExecutor(NUM_THREADS).Foreach( [] { std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); }, 8); return true; }; @@ -93,13 +93,13 @@ void SimpleParallelRDFs() { // Run the RDF construction and the event loop in parallel auto func = [] { - std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); - ROOT::RDataFrame df(10); - return df.Define("x", "rdfentry_").Mean("x").GetValue(); - }; + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); + ROOT::RDataFrame df(10); + return df.Define("x", [](ULong64_t ievt) { return ievt; }, {"rdfentry_"}).Mean("x").GetValue(); + }; - ROOT::TThreadExecutor pool; - auto res = pool.Map(func, 64); + ROOT::TThreadExecutor pool(NUM_THREADS); + auto res = pool.Map(func, NUM_THREADS); const auto ref = func(); @@ -127,14 +127,14 @@ void SimpleParallelRDFLoops() auto create_df = [] { std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); ROOT::RDataFrame df(10); - return df.Define("x", "rdfentry_").Mean("x"); + return df.Define("x", [](ULong64_t ievt) {return ievt;}, {"rdfentry_"}).Mean("x"); }; std::vector> vals(64); for (auto i = 0u; i < vals.size(); i++) vals[i] = create_df(); - ROOT::TThreadExecutor pool; + ROOT::TThreadExecutor pool(NUM_THREADS); auto func = [](ROOT::RDF::RResultPtr rptr){ return rptr.GetValue(); }; auto res = pool.Map(func, vals); @@ -162,13 +162,14 @@ void ParallelRDFSnapshots() { // Run the RDF construction and the event loop in parallel const auto nevts = 100u; - auto func = [&] (int i) { - std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); - ROOT::RDataFrame df(nevts); - df.Define("x", "(int)rdfentry_").Snapshot("tree", "dataframe_parallel_snapshots_" + std::to_string(i) + ".root"); - }; + auto func = [&](int i) { + std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); + ROOT::RDataFrame df(nevts); + df.Define("x", [](ULong64_t ievt) { return int(ievt); }, {"rdfentry_"}) + .Snapshot("tree", "dataframe_parallel_snapshots_" + std::to_string(i) + ".root", {"x"}); + }; - ROOT::TThreadExecutor pool; + ROOT::TThreadExecutor pool(NUM_THREADS); std::vector vals = {0, 1, 2, 3, 4, 5, 6, 7}; pool.Foreach(func, vals); @@ -207,11 +208,11 @@ void ParallelRDFCaches() auto func = [&] { std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() / RAND_MAX * 200)); ROOT::RDataFrame df(nevts); - auto cache = df.Define("x", "(int)rdfentry_").Cache("x"); - return cache.Sum("x").GetValue(); + auto cache = df.Define("x", [](ULong64_t ievt) {return (int)ievt;}, {"rdfentry_"}).Cache({"x"}); + return cache.Sum("x").GetValue(); }; - ROOT::TThreadExecutor pool; + ROOT::TThreadExecutor pool(NUM_THREADS); auto res = pool.Map(func, 8); auto sum_ref = 0u; diff --git a/tree/dataframe/test/dataframe_datasetspec.cxx b/tree/dataframe/test/dataframe_datasetspec.cxx index 13c2f68b2d610..0cd0be2a9215c 100644 --- a/tree/dataframe/test/dataframe_datasetspec.cxx +++ b/tree/dataframe/test/dataframe_datasetspec.cxx @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include @@ -30,10 +30,10 @@ void EXPECT_VEC_SEQ_EQ(const std::vector &vec, const ROOT::TSeq fileGlobs; struct RTestTree { @@ -49,20 +49,20 @@ struct RTestGroup { std::vector> trees; // single tree/files with their ranges per glob RMetaData meta; - RTestGroup(const std::string &n, ULong64_t s, ULong64_t e, const std::vector &f, - const std::vector> &t) - : name(n), groupStart(s), groupEnd(e), fileGlobs(f), trees(t) + RTestSample(const std::string &n, ULong64_t s, ULong64_t e, const std::vector &f, + const std::vector> &t) + : name(n), sampleStart(s), sampleEnd(e), fileGlobs(f), trees(t) { - meta.Add("group_name", name); - meta.Add("group_start", static_cast(s)); - meta.Add("group_end", static_cast(e)); + meta.Add("sample_name", name); + meta.Add("sample_start", static_cast(s)); + meta.Add("sample_end", static_cast(e)); } }; -// the first group has a single file glob -// the second group has two file globs, but always the same tree name -// the last group has two file globs, corresponding to different tree names -std::vector data{ +// the first sample has a single file glob +// the second sample has two file globs, but always the same tree name +// the last sample has two file globs, corresponding to different tree names +std::vector data{ {"simulated", 0u, 15u, @@ -127,34 +127,34 @@ TEST_P(RDatasetSpecTest, SimpleChainsCreation) for (const auto &d : data) { for (const auto &trees : d.trees) { for (const auto &t : trees) { - // first AddGroup overload: 1 tree, 1 file; both passed as string directly - const auto dfC1 = *(RDataFrame(RDatasetSpec().AddGroup({"", t.tree, t.file})).Take("x")); + // first AddSample overload: 1 tree, 1 file; both passed as string directly + const auto dfC1 = *(RDataFrame(RDatasetSpec().AddSample({"", t.tree, t.file})).Take("x")); EXPECT_VEC_SEQ_EQ(dfC1, ROOT::TSeq(t.start, t.end)); - // second AddGroup overload: 1 tree, many files; files passed as a vector; testing with 1 specTestFile - const auto dfC2 = *(RDataFrame(RDatasetSpec().AddGroup({"", t.tree, {t.file}})).Take("x")); + // second AddSample overload: 1 tree, many files; files passed as a vector; testing with 1 specTestFile + const auto dfC2 = *(RDataFrame(RDatasetSpec().AddSample({"", t.tree, {t.file}})).Take("x")); EXPECT_VEC_SEQ_EQ(dfC2, ROOT::TSeq(t.start, t.end)); - // third AddGroup overload: many trees, many files; trees and files passed in a vector of pairs - const auto dfC3 = *(RDataFrame(RDatasetSpec().AddGroup({"", {{t.tree, t.file}}})).Take("x")); + // third AddSample overload: many trees, many files; trees and files passed in a vector of pairs + const auto dfC3 = *(RDataFrame(RDatasetSpec().AddSample({"", {{t.tree, t.file}}})).Take("x")); EXPECT_VEC_SEQ_EQ(dfC3, ROOT::TSeq(t.start, t.end)); - // fourth AddGroup overload: many trees, many files; trees and files passed in separate vectors - const auto dfC4 = *(RDataFrame(RDatasetSpec().AddGroup({"", {t.tree}, {t.file}})).Take("x")); + // fourth AddSample overload: many trees, many files; trees and files passed in separate vectors + const auto dfC4 = *(RDataFrame(RDatasetSpec().AddSample({"", {t.tree}, {t.file}})).Take("x")); EXPECT_VEC_SEQ_EQ(dfC4, ROOT::TSeq(t.start, t.end)); } } } - // groups with hard-coded file names + // samples with hard-coded file names std::vector specs(4); for (const auto &d : data) { for (const auto &trees : d.trees) { for (const auto &t : trees) { - specs[0].AddGroup({"", t.tree, t.file}); - specs[1].AddGroup({"", t.tree, {t.file}}); - specs[2].AddGroup({"", {{t.tree, t.file}}}); - specs[3].AddGroup({"", {t.tree}, {t.file}}); + specs[0].AddSample({"", t.tree, t.file}); + specs[1].AddSample({"", t.tree, {t.file}}); + specs[2].AddSample({"", {{t.tree, t.file}}}); + specs[3].AddSample({"", {t.tree}, {t.file}}); } } } @@ -162,13 +162,13 @@ TEST_P(RDatasetSpecTest, SimpleChainsCreation) for (const auto &spec : specs) { auto df = *(RDataFrame(spec).Take("x")); std::sort(df.begin(), df.end()); - EXPECT_VEC_SEQ_EQ(df, ROOT::TSeq(data[0].groupStart, data[data.size() - 1].groupEnd)); + EXPECT_VEC_SEQ_EQ(df, ROOT::TSeq(data[0].sampleStart, data[data.size() - 1].sampleEnd)); } - // the first builder takes each tree/file as a separate group - // the second builder takes tree/file glob as separate group + // the first builder takes each tree/file as a separate sample + // the second builder takes tree/file glob as separate sample // the third build takes tree/expanded glob (similar to second) - // the fourth builder takes a vector of trees/vector of file globs as a separate group + // the fourth builder takes a vector of trees/vector of file globs as a separate sample std::vector specsGranularity(4); for (const auto &d : data) { std::vector treeNames{}; @@ -177,21 +177,21 @@ TEST_P(RDatasetSpecTest, SimpleChainsCreation) std::vector treeNamesExpanded{}; std::vector fileGlobsExpanded{}; for (const auto &t : d.trees[i]) { - specsGranularity[0].AddGroup({"", t.tree, t.file}); + specsGranularity[0].AddSample({"", t.tree, t.file}); treeNamesExpanded.emplace_back(t.tree); fileGlobsExpanded.emplace_back(t.file); } - specsGranularity[1].AddGroup({"", d.trees[i][0].tree, d.fileGlobs[i]}); - specsGranularity[2].AddGroup({"", treeNamesExpanded, fileGlobsExpanded}); + specsGranularity[1].AddSample({"", d.trees[i][0].tree, d.fileGlobs[i]}); + specsGranularity[2].AddSample({"", treeNamesExpanded, fileGlobsExpanded}); treeNames.emplace_back(d.trees[i][0].tree); fileGlobs.emplace_back(d.fileGlobs[i]); } - specsGranularity[3].AddGroup({"", treeNames, fileGlobs}); + specsGranularity[3].AddSample({"", treeNames, fileGlobs}); } for (const auto &spec : specsGranularity) { auto df = *(RDataFrame(spec).Take("x")); std::sort(df.begin(), df.end()); - EXPECT_VEC_SEQ_EQ(df, ROOT::TSeq(data[0].groupStart, data[data.size() - 1].groupEnd)); + EXPECT_VEC_SEQ_EQ(df, ROOT::TSeq(data[0].sampleStart, data[data.size() - 1].sampleEnd)); } } @@ -211,28 +211,28 @@ TEST_P(RDatasetSpecTest, SimpleMetaDataHandling) treeNames.emplace_back(d.trees[i][0].tree); fileGlobs.emplace_back(d.fileGlobs[i]); } - specs[0].AddGroup({d.name, treeNames, fileGlobs, d.meta}); - specs[1].AddGroup({d.name, treeNamesExpanded, fileGlobsExpanded, d.meta}); + specs[0].AddSample({d.name, treeNames, fileGlobs, d.meta}); + specs[1].AddSample({d.name, treeNamesExpanded, fileGlobsExpanded, d.meta}); } for (const auto &spec : specs) { auto df = RDataFrame(spec) - .DefinePerSample("group_name_col", - [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetS("group_name"); }) - .DefinePerSample("group_start_col", - [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetI("group_start"); }) - .DefinePerSample("group_end_col", - [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetD("group_end"); }); - auto g1S = (df.Filter([](std::string m) { return m == "simulated"; }, {"group_name_col"}).Count()); - auto g2S = (df.Filter([](std::string m) { return m == "real"; }, {"group_name_col"}).Count()); - auto g3S = (df.Filter([](std::string m) { return m == "raw"; }, {"group_name_col"}).Count()); - auto g1I = (df.Filter([](int m) { return m == 0; }, {"group_start_col"}).Count()); - auto g2I = (df.Filter([](int m) { return m == 15; }, {"group_start_col"}).Count()); - auto g3I = (df.Filter([](int m) { return m == 39; }, {"group_start_col"}).Count()); - auto g1D = (df.Filter([](double m) { return m == 15.; }, {"group_end_col"}).Count()); - auto g2D = (df.Filter([](double m) { return m == 39.; }, {"group_end_col"}).Count()); - auto g3D = (df.Filter([](double m) { return m == 85.; }, {"group_end_col"}).Count()); - EXPECT_EQ(*g1S, 15u); // number of entries in the first group = 4 + 5 + 6 = 15 + .DefinePerSample("sample_name_col", + [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetS("sample_name"); }) + .DefinePerSample("sample_start_col", + [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetI("sample_start"); }) + .DefinePerSample("sample_end_col", + [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetD("sample_end"); }); + auto g1S = (df.Filter([](std::string m) { return m == "simulated"; }, {"sample_name_col"}).Count()); + auto g2S = (df.Filter([](std::string m) { return m == "real"; }, {"sample_name_col"}).Count()); + auto g3S = (df.Filter([](std::string m) { return m == "raw"; }, {"sample_name_col"}).Count()); + auto g1I = (df.Filter([](int m) { return m == 0; }, {"sample_start_col"}).Count()); + auto g2I = (df.Filter([](int m) { return m == 15; }, {"sample_start_col"}).Count()); + auto g3I = (df.Filter([](int m) { return m == 39; }, {"sample_start_col"}).Count()); + auto g1D = (df.Filter([](double m) { return m == 15.; }, {"sample_end_col"}).Count()); + auto g2D = (df.Filter([](double m) { return m == 39.; }, {"sample_end_col"}).Count()); + auto g3D = (df.Filter([](double m) { return m == 85.; }, {"sample_end_col"}).Count()); + EXPECT_EQ(*g1S, 15u); // number of entries in the first sample = 4 + 5 + 6 = 15 EXPECT_EQ(*g2S, 24u); // num. entries = 7 + 8 + 9 = 24 EXPECT_EQ(*g3S, 46u); // num. entries = 10 + 11 + 12 + 13 = 46 EXPECT_EQ(*g1I, 15u); @@ -279,8 +279,8 @@ TEST_P(RDatasetSpecTest, Ranges) treeNames.emplace_back(d.trees[i][0].tree); fileGlobs.emplace_back(d.fileGlobs[i]); } - specs[0].AddGroup({d.name, treeNames, fileGlobs, d.meta}); - specs[1].AddGroup({d.name, treeNamesExpanded, fileGlobsExpanded, d.meta}); + specs[0].AddSample({d.name, treeNames, fileGlobs, d.meta}); + specs[1].AddSample({d.name, treeNamesExpanded, fileGlobsExpanded, d.meta}); } for (auto &spec : specs) { for (auto i = 0u; i < ranges.size(); ++i) { @@ -344,8 +344,8 @@ TEST_P(RDatasetSpecTest, Friends) { RDatasetSpec spec; - // pick the second group as the main chain, so that can test shorter, equal-sized, longer friends - spec.AddGroup({data[1].name, data[1].trees[0][0].tree, data[1].fileGlobs}); + // pick the second sample as the main chain, so that can test shorter, equal-sized, longer friends + spec.AddSample({data[1].name, data[1].trees[0][0].tree, data[1].fileGlobs}); for (const auto &d : data) { std::vector treeNames{}; std::vector fileGlobs{}; @@ -377,15 +377,7 @@ TEST_P(RDatasetSpecTest, Friends) // see: https://github.com/root-project/root/issues/9137 if (i > 0) { EXPECT_VEC_SEQ_EQ(*res["friend_glob_" + data[i].name + "x"], - ROOT::TSeq(data[i].groupStart, data[i].groupStart + 24)); - } else { - if (GetParam()) { // MT case - auto sol = *res["friend_glob_" + data[i].name + "x"]; - ASSERT_EQ(sol.size(), 24u); - for (auto j = 0u; j < sol.size(); ++j) - EXPECT_EQ(sol[j], j > 8 ? j - 9 : 0u); - } - // sigle-threaded case with shorter friend behaves unexpectedly! + ROOT::TSeq(data[i].sampleStart, data[i].sampleStart + 24)); } } } @@ -393,8 +385,8 @@ TEST_P(RDatasetSpecTest, Friends) TEST_P(RDatasetSpecTest, Histo1D) { RDatasetSpec spec; - spec.AddGroup({"real0", "tree"s, {"specTestFile0.root"s}}); - spec.AddGroup({"real1", {{"tree"s, "specTestFile00*.root"s}}}); + spec.AddSample({"real0", "tree"s, {"specTestFile0.root"s}}); + spec.AddSample({"real1", {{"tree"s, "specTestFile00*.root"s}}}); // 1 friend with entries from 15 up to 39 -> shortened to have the size of the main chain spec.WithGlobalFriends({{"subTree"s, "specTestFile1*.root"s}}, "friend"s); ROOT::RDataFrame d(spec); @@ -440,8 +432,8 @@ TEST_P(RDatasetSpecTest, Histo1D) TEST_P(RDatasetSpecTest, FilterDependingOnVariation) { RDatasetSpec spec; - spec.AddGroup({"real0", "tree"s, {"specTestFile0.root"s}}); - spec.AddGroup({"real1", {{"tree"s, "specTestFile00*.root"s}}}); + spec.AddSample({"real0", "tree"s, {"specTestFile0.root"s}}); + spec.AddSample({"real1", {{"tree"s, "specTestFile00*.root"s}}}); // 1 friend with entries from 15 up to 39 -> shortened to have the size of the main chain spec.WithGlobalFriends({{"subTree"s, "specTestFile1*.root"s}}, "friend"s); ROOT::RDataFrame df(spec); @@ -481,8 +473,8 @@ TEST_P(RDatasetSpecTest, FilterDependingOnVariation) TEST_P(RDatasetSpecTest, SaveGraph) { RDatasetSpec spec; - spec.AddGroup({"real0", "tree"s, {"specTestFile0.root"s}}); - spec.AddGroup({"real1", {{"tree"s, "specTestFile00*.root"s}}}); + spec.AddSample({"real0", "tree"s, {"specTestFile0.root"s}}); + spec.AddSample({"real1", {{"tree"s, "specTestFile00*.root"s}}}); // 1 friend with entries from 15 up to 39 -> shortened to have the size of the main chain spec.WithGlobalFriends({{"subTree"s, "specTestFile1*.root"s}}, "friend"s); ROOT::RDataFrame df(spec); @@ -513,8 +505,8 @@ TEST(RDatasetSpecTest, Describe) dfWriter1.Range(5, 10).Snapshot("subTree3", "specTestDescribe4.root", {"w"}); RDatasetSpec spec; - spec.AddGroup({"groupA", "subTree0"s, "specTestDescribe1.root"s}); - spec.AddGroup({"groupB", "subTree1"s, "specTestDescribe2.root"s}); + spec.AddSample({"sampleA", "subTree0"s, "specTestDescribe1.root"s}); + spec.AddSample({"sampleB", "subTree1"s, "specTestDescribe2.root"s}); spec.WithGlobalFriends({{"subTree2"s, "specTestDescribe3.root"s}, {"subTree3"s, "specTestDescribe4.root"s}}); auto df = ROOT::RDataFrame(spec); auto res0 = df.Sum("x"); @@ -538,7 +530,7 @@ TEST(RDatasetSpecTest, Describe) "Column Type Origin\n" "------ ---- ------\n" "w Double_t Dataset\n" - "x Double_t Dataset"); + "x Double_t Dataset\n"); EXPECT_EQ(expectedDescribe, df.Describe().AsString()); for (auto i = 12u; i < 16; ++i) gSystem->Unlink(("specTestFile" + std::to_string(i) + ".root").c_str()); @@ -556,7 +548,7 @@ TEST(RDatasetSpecTest, FromSpec) auto rdf = FromSpec("spec.json") - .DefinePerSample("name", [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetGroupName(); }) + .DefinePerSample("name", [](unsigned int, const ROOT::RDF::RSampleInfo &id) { return id.GetSampleName(); }) .DefinePerSample("lumi", "rdfsampleinfo_.GetD(\"lumi\")"); auto resP = rdf.Take("z"); auto namP = rdf.Take("name"); @@ -570,7 +562,7 @@ TEST(RDatasetSpecTest, FromSpec) auto fr2 = fr2P.GetValue(); std::vector expectedRes{101, 102, 103, 104}; - std::vector names{"groupA", "groupA", "groupA", "groupB"}; + std::vector names{"sampleA", "sampleA", "sampleA", "sampleB"}; std::vector lumis{1.0, 1.0, 1.0, 0.5}; ASSERT_EQ(res.size(), expectedRes.size()); @@ -586,6 +578,41 @@ TEST(RDatasetSpecTest, FromSpec) gSystem->Unlink(("PYspecTestFile" + std::to_string(i) + ".root").c_str()); } +TEST(RDatasetSpecTest, FromSpec_ordering_samplesAndFriends) +{ + auto dfWriter0 = ROOT::RDataFrame(1).Define("z", [](ULong64_t e) { return e + 100; }, {"rdfentry_"}); + dfWriter0.Snapshot("subTree", "FromSpecTestFile1.root", {"z"}); + dfWriter0.Snapshot("subTree", "FromSpecTestFile2.root", {"z"}); + dfWriter0.Snapshot("anotherTree", "FromSpecTestFile4.root", {"z"}); + dfWriter0.Snapshot("anotherTree", "FromSpecTestFile3.root", {"z"}); + + auto rdf_1 = FromSpec("spec_ordering_samples_withFriends.json"); + + static const std::string expectedDescribe("Dataframe from TChain in files\n" + " FromSpecTestFile2.root\n" + " FromSpecTestFile1.root\n" + "with friends\n" + " (friendTree2) FromSpecTestFile4.root\n" + " (friendTree1) FromSpecTestFile3.root\n" + "\n" + "Property Value\n" + "-------- -----\n" + "Columns in total 3\n" + "Columns from defines 0\n" + "Event loops run 0\n" + "Processing slots 1\n" + "\n" + "Column Type Origin\n" + "------ ---- ------\n" + "friendTree1.z ULong64_t Dataset\n" + "friendTree2.z ULong64_t Dataset\n" + "z ULong64_t Dataset\n"); + EXPECT_EQ(expectedDescribe, rdf_1.Describe().AsString()); + + for (auto i = 1u; i < 5; ++i) + gSystem->Unlink(("FromSpecTestFile" + std::to_string(i) + ".root").c_str()); +} + TEST(RMetaData, SimpleOperations) { ROOT::RDF::Experimental::RMetaData m; @@ -658,10 +685,10 @@ TEST(RDatasetSpecTest, Clusters) for (const auto &range : ranges) { RDatasetSpec spec; - spec.AddGroup({"", - {{"mainA"s, "CspecTestFile0.root"s}, - {"mainB"s, "CspecTestFile1.root"s}, - {"mainC"s, "CspecTestFile2.root"s}}}); + spec.AddSample({"", + {{"mainA"s, "CspecTestFile0.root"s}, + {"mainB"s, "CspecTestFile1.root"s}, + {"mainC"s, "CspecTestFile2.root"s}}}); spec.WithGlobalRange(range); spec.WithGlobalFriends({{"friendA"s, "CspecTestFile3.root"s}, {"friendB"s, "CspecTestFile4.root"s}, diff --git a/tree/dataframe/test/dataframe_datasetspec.py b/tree/dataframe/test/dataframe_datasetspec.py index 5ec7d8bca669f..975d6d852f000 100644 --- a/tree/dataframe/test/dataframe_datasetspec.py +++ b/tree/dataframe/test/dataframe_datasetspec.py @@ -76,15 +76,15 @@ def test_General(self): metaB.Add("lumi", 0.5) spec = RDatasetSpec() - spec.AddGroup( + spec.AddSample( ( - "groupA", + "sampleA", ["subTree1", "subTree2"], ["PYspecTestFile5.root", "PYspecTestFile6.root"], metaA, ) ) - spec.AddGroup(("groupB", "subTree", "PYspecTestFile4.root", metaB)) + spec.AddSample(("sampleB", "subTree", "PYspecTestFile4.root", metaB)) spec.WithGlobalRange(r) spec.WithGlobalFriends("anotherTree", "PYspecTestFile7.root", "friendTree") spec.WithGlobalFriends( @@ -140,7 +140,7 @@ def test_General(self): def test_FromSpec(self): rdf = ROOT.RDF.Experimental.FromSpec("spec.json") - rdf = rdf.DefinePerSample("name", "rdfsampleinfo_.GetGroupName()") + rdf = rdf.DefinePerSample("name", "rdfsampleinfo_.GetSampleName()") rdf = rdf.DefinePerSample("lumi", 'rdfsampleinfo_.GetD("lumi")') if self.legacy_pyroot: @@ -163,7 +163,7 @@ def test_FromSpec(self): fr2 = fr2P.GetValue() expectedRes = [101, 102, 103, 104] - names = ["groupA", "groupA", "groupA", "groupB"] + names = ["sampleA", "sampleA", "sampleA", "sampleB"] lumis = [1.0, 1.0, 1.0, 0.5] self.assertEqual(len(res), len(expectedRes)) diff --git a/tree/dataframe/test/dataframe_definepersample.cxx b/tree/dataframe/test/dataframe_definepersample.cxx index f731c2bd629ce..32a4c9076382e 100644 --- a/tree/dataframe/test/dataframe_definepersample.cxx +++ b/tree/dataframe/test/dataframe_definepersample.cxx @@ -157,6 +157,24 @@ TEST(DefinePerSampleMore, GetDefinedColumnNames) EXPECT_EQ(df.GetDefinedColumnNames(), std::vector{"x"}); } +// Regression test for https://github.com/root-project/root/issues/12043 +TEST(DefinePerSample, TwoExecutions) +{ + bool flag = false; + auto df = ROOT::RDataFrame(1).DefinePerSample("x", [&flag](unsigned int, const ROOT::RDF::RSampleInfo &) { + flag = true; + return 0; + }); + // Trigger the first execution of the event loop, the flag should be true. + df.Count().GetValue(); + EXPECT_TRUE(flag); + // Reset the flag and trigger again, flag should be again set to true after + // the end of the second event loop. + flag = false; + df.Count().GetValue(); + EXPECT_TRUE(flag); +} + /* TODO // Not supported yet TEST(DefinePerSample, DataSource) diff --git a/tree/dataframe/test/dataframe_display.cxx b/tree/dataframe/test/dataframe_display.cxx index 5170c24165b3d..2018b10e25daa 100644 --- a/tree/dataframe/test/dataframe_display.cxx +++ b/tree/dataframe/test/dataframe_display.cxx @@ -299,15 +299,9 @@ TEST(RDFDisplayTests, BoolArray) "+-----+-------+\n" "| 1 | true | \n" "| | false | \n" - "| | true | \n" - "| | false | \n" "+-----+-------+\n" "| 2 | true | \n" "| | false | \n" - "| | true | \n" - "| | false | \n" - "| | true | \n" - "| | false | \n" "| | | \n" "+-----+-------+\n"; EXPECT_EQ(r->AsString(), expected); diff --git a/tree/dataframe/test/dataframe_friends.cxx b/tree/dataframe/test/dataframe_friends.cxx index 32345da6ea42d..14f3a3191ccab 100644 --- a/tree/dataframe/test/dataframe_friends.cxx +++ b/tree/dataframe/test/dataframe_friends.cxx @@ -258,6 +258,8 @@ TEST_F(RDFAndFriends, FriendChainMT) ROOT::DisableImplicitMT(); } +#endif // R__USE_IMT + // ROOT-9559 void FillIndexedFriend(const char *mainfile, const char *auxfile) { @@ -303,10 +305,10 @@ void FillIndexedFriend(const char *mainfile, const char *auxfile) f2.Close(); } -TEST(RDFAndFriendsNoFixture, IndexedFriend) +void TestIndexedFriendChain() { - auto mainFile = "IndexedFriend_main.root"; - auto auxFile = "IndexedFriend_aux.root"; + auto mainFile = "IndexedFriendChain_main.root"; + auto auxFile = "IndexedFriendChain_aux.root"; FillIndexedFriend(mainFile, auxFile); TChain mainChain("mainTree", "mainTree"); @@ -321,15 +323,71 @@ TEST(RDFAndFriendsNoFixture, IndexedFriend) auto x = df.Take("x"); auto y = df.Take("auxTree.y"); - std::vector refx{{1,2,3,4,5}}; + std::vector refx{{1, 2, 3, 4, 5}}; + EXPECT_TRUE(std::equal(x->begin(), x->end(), refx.begin())); + std::vector refy{{7, 7, 7, 5, 5}}; + EXPECT_TRUE(std::equal(y->begin(), y->end(), refy.begin())); + + gSystem->Unlink(mainFile); + gSystem->Unlink(auxFile); +} + +void TestIndexedFriendTree() +{ + auto mainFile = "IndexedFriendTree_main.root"; + auto auxFile = "IndexedFriendTree_aux.root"; + FillIndexedFriend(mainFile, auxFile); + + TFile mainF(mainFile); + auto *mainTree = mainF.Get("mainTree"); + EXPECT_NE(mainTree, nullptr); + + TFile auxF(auxFile); + auto *auxTree = auxF.Get("auxTree"); + EXPECT_NE(auxTree, nullptr); + + auxTree->BuildIndex("idx"); + mainTree->AddFriend(auxTree); + + auto df = ROOT::RDataFrame(*mainTree); + auto x = df.Take("x"); + auto y = df.Take("auxTree.y"); + + std::vector refx{{1, 2, 3, 4, 5}}; EXPECT_TRUE(std::equal(x->begin(), x->end(), refx.begin())); - std::vector refy{{7,7,7,5,5}}; + std::vector refy{{7, 7, 7, 5, 5}}; EXPECT_TRUE(std::equal(y->begin(), y->end(), refy.begin())); gSystem->Unlink(mainFile); gSystem->Unlink(auxFile); } +TEST(RDFAndFriendsNoFixture, IndexedFriendChain) +{ + TestIndexedFriendChain(); +} + +TEST(RDFAndFriendsNoFixture, IndexedFriendTree) +{ + TestIndexedFriendChain(); +} + +#ifdef R__USE_IMT +TEST(RDFAndFriendsNoFixture, IndexedFriendChainMT) +{ + ROOT::EnableImplicitMT(); + TestIndexedFriendChain(); + ROOT::DisableImplicitMT(); +} + +TEST(RDFAndFriendsNoFixture, IndexedFriendTreeMT) +{ + ROOT::EnableImplicitMT(); + TestIndexedFriendTree(); + ROOT::DisableImplicitMT(); +} +#endif // R__USE_IMT + // Test for https://github.com/root-project/root/issues/6741 TEST(RDFAndFriendsNoFixture, AutomaticFriendsLoad) { @@ -352,5 +410,3 @@ TEST(RDFAndFriendsNoFixture, AutomaticFriendsLoad) gSystem->Unlink(fname); } - -#endif // R__USE_IMT diff --git a/tree/dataframe/test/dataframe_helpers.cxx b/tree/dataframe/test/dataframe_helpers.cxx old mode 100644 new mode 100755 index 96357fb70fef7..6c93edcb221bf --- a/tree/dataframe/test/dataframe_helpers.cxx +++ b/tree/dataframe/test/dataframe_helpers.cxx @@ -463,13 +463,16 @@ TEST(RDFHelpers, GraphRunTimeErrors) const std::vector xx = {-0.22}; // smaller size const std::vector yy = {1., 2.9}; - auto df = - RDataFrame(1).Define("xx", [&] { return xx; }).Define("yy", [&] { return yy; }).Define("x", [] { return .5; }); - - auto gr1 = df.Graph, std::vector>("xx", "yy"); // still no error since lazy action - auto gr2 = df.Graph>("x", "yy"); // still no error since lazy action + auto GetRDF = [&] {return RDataFrame(1) + .Define("yy", [&] { return yy; }) + .Define("xx", [&] { return xx; }) + .Define("x", [] { return .5; }); + }; + auto gr1 = GetRDF().Graph, std::vector>("xx", "yy"); // still no error since lazy action EXPECT_THROW(gr1.GetValue(), std::runtime_error); + + auto gr2 = GetRDF().Graph>("x", "yy"); // still no error since lazy action EXPECT_THROW(gr2.GetValue(), std::runtime_error); } @@ -557,20 +560,23 @@ TEST(RDFHelpers, GraphAsymmErrorsRunTimeErrors) const Ds eyl = {.8, .7}; const Ds eyh = {.6, .5}; - auto df = RDataFrame(1) - .Define("xx", [&] { return xx; }) - .Define("yy", [&] { return yy; }) - .Define("exl", [&] { return exl; }) - .Define("exh", [&] { return exh; }) - .Define("eyl", [&] { return eyl; }) - .Define("eyh", [&] { return eyh; }) - .Define("x", [] { return 3.14; }); // scalar + auto GetRDF = [&] { + return RDataFrame(1) + .Define("xx", [&] { return xx; }) + .Define("yy", [&] { return yy; }) + .Define("exl", [&] { return exl; }) + .Define("exh", [&] { return exh; }) + .Define("eyl", [&] { return eyl; }) + .Define("eyh", [&] { return eyh; }) + .Define("x", [] { return 3.14; }); // scalar + }; // still no error since lazy action - auto gr1 = df.GraphAsymmErrors("xx", "yy", "exl", "exh", "eyl", "eyh"); - auto gr2 = df.GraphAsymmErrors("x", "yy", "exl", "exh", "eyl", "eyh"); - + auto gr1 = GetRDF().GraphAsymmErrors("xx", "yy", "exl", "exh", "eyl", "eyh"); EXPECT_THROW(gr1.GetValue(), std::runtime_error); + + // still no error since lazy action + auto gr2 = GetRDF().GraphAsymmErrors("x", "yy", "exl", "exh", "eyl", "eyh"); EXPECT_THROW(gr2.GetValue(), std::runtime_error); } @@ -682,3 +688,107 @@ TEST(RunGraphs, AlreadyRun) ROOT_EXPECT_WARNING(ROOT::RDF::RunGraphs({r1, r2, r3, r4}), "RunGraphs", "Got 4 handles from which 2 link to results which are already ready."); } + +int ret42 () {return 42;} +int ret1 () {return 1;} + +TEST(RDFHelpers, ProgressHelper_Existence_ST) +{ + // Redirect cout. + std::streambuf *oldCoutStreamBuf = std::cout.rdbuf(); + std::ostringstream strCout; + std::cout.rdbuf(strCout.rdbuf()); + auto d_write_1 = ROOT::RDataFrame(10000).Define("x", ret42).Snapshot("tree", "fh1.root", {"x"}); + auto d_write_2 = ROOT::RDataFrame(10000).Define("y", ret1).Snapshot("tree", "fh2.root", {"y"}); + ROOT::RDF::RNode d = ROOT::RDataFrame("tree", {"fh1.root", "fh2.root"}); + ROOT::RDF::Experimental::AddProgressbar(d); + d.Count().GetValue(); + // Restore old cout. + std::cout.rdbuf(oldCoutStreamBuf); + + EXPECT_FALSE(strCout.str().empty()); +} + +// A test for #10484 +class SimpleActionHelper : public ROOT::Detail::RDF::RActionImpl { +public: + using Result_t = int; + +private: + std::shared_ptr fValue; + int &fTestVal; + +public: + static constexpr int fgRefVal = 42; + SimpleActionHelper(int &testVal) : fValue(new int), fTestVal(testVal) {} + SimpleActionHelper(SimpleActionHelper &&) = default; + SimpleActionHelper(const SimpleActionHelper &) = delete; + std::shared_ptr GetResultPtr() const { return fValue; } + void Initialize() {} + void InitTask(TTreeReader *, unsigned int) {} + template + void Exec(unsigned int, ColumnTypes...) + { + } + void Finalize() { fTestVal = SimpleActionHelper::fgRefVal; } + std::string GetActionName() { return "SimpleAction"; } +}; + +TEST(RDFHelpers, Cleanup_After_Exception) +{ + auto exceptionThrower = [](ULong64_t ievt) { + if (ievt == 4) { + throw std::invalid_argument("Time to throw."); + } + return int(0); + }; + + int testVal = 123; + SimpleActionHelper helper(testVal); + auto rdf = ROOT::RDataFrame(8).Define("dummy", exceptionThrower, {"rdfentry_"}); + auto valRes = rdf.Book(std::move(helper), {"dummy"}); + EXPECT_THROW(valRes.GetValue(), std::invalid_argument) + << "An exception should have been thrown during the event loop."; + EXPECT_EQ(SimpleActionHelper::fgRefVal, testVal) + << "The Finalize method should have changed the value of testVal during the post-exception cleanup." << std::endl; +} + +// The code below is a unit test for a function called `ProgressHelper_Existence_MT` in the `RDFHelpers` class. + +#ifdef R__USE_IMT + +TEST(RDFHelpers, ProgressHelper_Existence_MT) +{ + // Redirect cout. + ROOT::EnableImplicitMT(); + std::streambuf *oldCoutStreamBuf = std::cout.rdbuf(); + std::ostringstream strCout; + std::cout.rdbuf(strCout.rdbuf()); + auto d_write_1 = ROOT::RDataFrame(10000).Define("x", ret42).Snapshot("tree", "fh1.root", {"x"}); + auto d_write_2 = ROOT::RDataFrame(10000).Define("y", ret1).Snapshot("tree", "fh2.root", {"y"}); + ROOT::RDF::RNode d = ROOT::RDataFrame("tree", {"fh1.root", "fh2.root"}); + ROOT::RDF::Experimental::AddProgressbar(d); + d.Count().GetValue(); + // Restore old cout. + std::cout.rdbuf(oldCoutStreamBuf); + + EXPECT_FALSE(strCout.str().empty()); +} + +TEST(RDFHelpers, ProgressHelper_existence_singleTTreeInput) +{ + // Redirect cout. + ROOT::EnableImplicitMT(); + std::streambuf *oldCoutStreamBuf = std::cout.rdbuf(); + std::ostringstream strCout; + std::cout.rdbuf(strCout.rdbuf()); + auto d_write_1 = ROOT::RDataFrame(10000).Define("x", ret42).Snapshot("tree", "fh1.root", {"x"}); + ROOT::RDF::RNode d = ROOT::RDataFrame("tree", {"fh1.root"}); + ROOT::RDF::Experimental::AddProgressbar(d); + d.Count().GetValue(); + // Restore old cout. + std::cout.rdbuf(oldCoutStreamBuf); + + EXPECT_FALSE(strCout.str().empty()); +} +#endif // R__USE_IMT diff --git a/tree/dataframe/test/dataframe_interface.cxx b/tree/dataframe/test/dataframe_interface.cxx index 069b3a378db21..5870caae70fb2 100644 --- a/tree/dataframe/test/dataframe_interface.cxx +++ b/tree/dataframe/test/dataframe_interface.cxx @@ -658,7 +658,7 @@ TEST(RDataFrameInterface, Describe) "myFloat Float_t Dataset\n" "myInt Int_t Dataset\n" "myLongColumnName unsigned int Define\n" - "myVec ROOT::VecOps::RVec Define"; + "myVec ROOT::VecOps::RVec Define\n"; EXPECT_EQ(df3.Describe().AsString(), ref2); } diff --git a/tree/dataframe/test/dataframe_simple.cxx b/tree/dataframe/test/dataframe_simple.cxx index 38ec2e286dd68..3f71a766823c3 100644 --- a/tree/dataframe/test/dataframe_simple.cxx +++ b/tree/dataframe/test/dataframe_simple.cxx @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -102,7 +103,7 @@ TEST_P(RDFSimpleTests, CreateZeroEntriesWithBranches) } RDataFrame tdf(treename, filename); auto c = tdf.Count(); - auto m = tdf.Mean("b1"); + auto m = tdf.Mean("b1"); EXPECT_EQ(0U, *c); EXPECT_DOUBLE_EQ(0., *m); } @@ -148,7 +149,7 @@ TEST_P(RDFSimpleTests, Define_lambda) { RDataFrame tdf(10); auto d = tdf.Define("i", []() { return 1; }); - auto m = d.Mean("i"); + auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } @@ -161,7 +162,7 @@ TEST_P(RDFSimpleTests, Define_function) { RDataFrame tdf(10); auto d = tdf.Define("i", DefineFunction); - auto m = d.Mean("i"); + auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } @@ -174,7 +175,7 @@ TEST_P(RDFSimpleTests, Define_functor) RDataFrame tdf(10); DefineStruct def; auto d = tdf.Define("i", def); - auto m = d.Mean("i"); + auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } @@ -343,7 +344,7 @@ TEST_P(RDFSimpleTests, Define_jitted_Filter_complex_array) TEST_P(RDFSimpleTests, DefineSlotConsistency) { RDataFrame df(8); - auto m = df.DefineSlot("x", [](unsigned int) { return 1.; }).Max("x"); + auto m = df.DefineSlot("x", [](unsigned int) { return 1.; }).Max("x"); EXPECT_DOUBLE_EQ(1., *m); } @@ -354,7 +355,7 @@ TEST_P(RDFSimpleTests, DefineSlot) values[i] = i; RDataFrame df(NSLOTS); auto ddf = df.DefineSlot("s", [values](unsigned int slot) { return values[slot]; }); - auto m = ddf.Max("s"); + auto m = ddf.Max("s"); EXPECT_EQ(*m, NSLOTS - 1); // no matter the order of processing, the higher slot number is always taken at least once } @@ -436,11 +437,11 @@ TEST_P(RDFSimpleTests, GetNRuns) RDataFrame df(3); EXPECT_EQ(df.GetNRuns(), 0u); - auto sum1 = df.Sum("rdfentry_"); + auto sum1 = df.Sum("rdfentry_"); sum1.GetValue(); EXPECT_EQ(df.GetNRuns(), 1u); - auto sum2 = df.Sum("rdfentry_"); + auto sum2 = df.Sum("rdfentry_"); sum2.GetValue(); EXPECT_EQ(df.GetNRuns(), 2u); } @@ -665,7 +666,7 @@ class StdDevTestHelper { ROOT::RDataFrame d(samples.size()); return *d.DefineSlotEntry("x", [this](unsigned int /*slot*/, ULong64_t entry) { return samples[entry]; - }).StdDev("x"); + }).StdDev("x"); } }; @@ -715,21 +716,21 @@ TEST_P(RDFSimpleTests, StandardDeviationCollections) TEST_P(RDFSimpleTests, StandardDeviationZero) { RDataFrame rd1(8); - auto stdDev = rd1.Define("b1", []() { return 0; }).StdDev("b1"); + auto stdDev = rd1.Define("b1", []() { return 0; }).StdDev("b1"); EXPECT_DOUBLE_EQ(*stdDev, 0); } TEST_P(RDFSimpleTests, StandardDeviationOne) { RDataFrame rd1(1); - auto stdDev = rd1.Define("b1", []() { return 1; }).StdDev("b1"); + auto stdDev = rd1.Define("b1", []() { return 1; }).StdDev("b1"); EXPECT_DOUBLE_EQ(*stdDev, 0); } TEST_P(RDFSimpleTests, StandardDeviationEmpty) { RDataFrame rd1(0); - auto stdDev = rd1.Define("b1", []() { return 0; }).StdDev("b1"); + auto stdDev = rd1.Define("b1", []() { return 0; }).StdDev("b1"); EXPECT_DOUBLE_EQ(*stdDev, 0); } @@ -743,11 +744,17 @@ TEST(RDFSimpleTests, SumOfStrings) } */ +template +T KahanHelper(ULong64_t i) +{ + return T(i + 1); +} + TEST_P(RDFSimpleTests, KahanSum_Double) { constexpr std::uint64_t N = 1e7; ROOT::RDataFrame d(N); - auto df = d.Define("x", "double(rdfentry_ +1)"); + auto df = d.Define("x", KahanHelper, {"rdfentry_"}); double true_sum = (N + 1.0) / 2.0; EXPECT_DOUBLE_EQ(*df.Sum({"x"}) / N, true_sum); } @@ -756,7 +763,7 @@ TEST_P(RDFSimpleTests, KahanSum_Float) { constexpr std::uint64_t N = 1e7; ROOT::RDataFrame d(N); - auto df = d.Define("x", "float(rdfentry_ +1)"); + auto df = d.Define("x", KahanHelper, {"rdfentry_"}); float true_sum = (N + 1.0) / 2.0; EXPECT_FLOAT_EQ(*df.Sum({"x"}) / N, true_sum); } @@ -765,7 +772,7 @@ TEST_P(RDFSimpleTests, KahanMean_Double) { constexpr std::uint64_t N = 1e7; ROOT::RDataFrame d(N); - auto df = d.Define("x", "double(rdfentry_ +1)"); + auto df = d.Define("x", KahanHelper, {"rdfentry_"}); double true_sum = (N + 1.0) / 2.0; EXPECT_DOUBLE_EQ(*df.Mean({"x"}), true_sum); } @@ -774,7 +781,7 @@ TEST_P(RDFSimpleTests, KahanMean_Float) { constexpr std::uint64_t N = 1e7; ROOT::RDataFrame d(N); - auto df = d.Define("x", "float(rdfentry_ +1)"); + auto df = d.Define("x", KahanHelper, {"rdfentry_"}); float true_sum = (N + 1.0) / 2.0; EXPECT_FLOAT_EQ(*df.Mean({"x"}), true_sum); } @@ -782,9 +789,11 @@ TEST_P(RDFSimpleTests, KahanMean_Float) TEST(RDFSimpleTests, GenVector) { // The leading underscore of "_hh" tests against ROOT-10305. + using MVector = ROOT::Math::PtEtaPhiMVector; ROOT::RDataFrame t(1); - auto aa = t.Define("_hh", "ROOT::Math::PtEtaPhiMVector(1,1,1,1)").Define("h", "_hh.Rapidity()"); - auto m = aa.Mean("h"); + auto aa = t.Define("_hh", []() { return MVector(1, 1, 1, 1); }) + .Define("h", [](MVector &v) { return v.Rapidity(); }, {"_hh"}); + auto m = aa.Mean("h"); EXPECT_TRUE(0 != *m); } @@ -792,9 +801,9 @@ TEST(RDFSimpleTests, AutomaticNamesOfHisto1DAndGraph) { auto df = RDataFrame(1).Define("x", [](){return 1;}) .Define("y", [](){return 1;}); - auto hx = df.Histo1D("x"); - auto hxy = df.Histo1D("x", "y"); - auto gxy = df.Graph("x", "y"); + auto hx = df.Histo1D("x"); + auto hxy = df.Histo1D("x", "y"); + auto gxy = df.Graph("x", "y"); EXPECT_STREQ(hx->GetName(), "x"); EXPECT_STREQ(hx->GetTitle(), "x"); @@ -804,8 +813,8 @@ TEST(RDFSimpleTests, AutomaticNamesOfHisto1DAndGraph) EXPECT_STREQ(hxy->GetTitle(), "x, weights: y"); EXPECT_STREQ(hxy->GetXaxis()->GetTitle(), "x"); EXPECT_STREQ(hxy->GetYaxis()->GetTitle(), "count * y"); - EXPECT_STREQ(gxy->GetName(), "x_vs_y"); - EXPECT_STREQ(gxy->GetTitle(), "x vs y"); + EXPECT_STREQ(gxy->GetName(), "y_vs_x"); + EXPECT_STREQ(gxy->GetTitle(), "y vs x"); EXPECT_STREQ(gxy->GetXaxis()->GetTitle(), "x"); EXPECT_STREQ(gxy->GetYaxis()->GetTitle(), "y"); @@ -958,16 +967,33 @@ TEST_P(RDFSimpleTests, Stats) EXPECT_ANY_THROW(rr.Stats("v", "one")); } -// ROOT-10092 TEST(RDFSimpleTests, ScalarValuesCollectionWeights) { ROOT::RDataFrame r(1); - auto h = r.Define("x", [](){return 10;}) - .Define("y", [](){return ROOT::RVec{1,2,3}; }) - .Histo1D>("x","y"); - // Check that the exception is thrown - EXPECT_ANY_THROW(*h); + // with no model + auto h = r.Define("x", []() { return 10; }) + .Define("y", + [] { + return ROOT::RVec{1, 2, 3}; + }) + .Histo1D>("x", "y"); + + EXPECT_EQ(h->GetEntries(), 3); + EXPECT_DOUBLE_EQ(h->GetMean(), 10.); + EXPECT_DOUBLE_EQ(h->GetMaximum(), 6.); + + // with model + auto h2 = r.Define("x", []() { return 10; }) + .Define("y", + [] { + return ROOT::RVec{1, 2, 3}; + }) + .Histo1D>({"h", "h", 20, 0., 20.}, "x", "y"); + + EXPECT_EQ(h2->GetEntries(), 3); + EXPECT_DOUBLE_EQ(h2->GetMean(), 10.); + EXPECT_DOUBLE_EQ(h2->GetMaximum(), 6.); } TEST_P(RDFSimpleTests, ChainWithDifferentTreeNames) @@ -986,7 +1012,7 @@ TEST_P(RDFSimpleTests, ChainWithDifferentTreeNames) // pass chain to RDF and process trees with different names ROOT::RDataFrame df2(c); - EXPECT_DOUBLE_EQ(*df2.Mean("x"), 2); + EXPECT_DOUBLE_EQ(*df2.Mean("x"), 2); gSystem->Unlink(fname1); gSystem->Unlink(fname2); diff --git a/tree/dataframe/test/dataframe_snapshot.cxx b/tree/dataframe/test/dataframe_snapshot.cxx index b28d78a477c53..35ea93040d4cb 100644 --- a/tree/dataframe/test/dataframe_snapshot.cxx +++ b/tree/dataframe/test/dataframe_snapshot.cxx @@ -1011,9 +1011,10 @@ TEST_F(RDFSnapshotMT, Reshuffled_friends) TFile f(fname); TTree *t = f.Get("t"); TTree t2("t2", "t2"); - const auto expected = "Tree 't' has the kEntriesReshuffled bit set, and cannot be used as " - "friend nor can be added as a friend unless the main tree has a TTreeIndex on the friend " - "tree 't'. You can also unset the bit manually if you know what you are doing."; + const auto expected = + "Tree 't' has the kEntriesReshuffled bit set and cannot have friends nor can be added as a friend unless the " + "main tree has a TTreeIndex on the friend tree 't'. You can also unset the bit manually if you know what you " + "are doing; note that you risk associating wrong TTree entries of the friend with those of the main TTree!"; ROOT_EXPECT_ERROR(t2.AddFriend(t), "AddFriend", expected); } @@ -1022,9 +1023,10 @@ TEST_F(RDFSnapshotMT, Reshuffled_friends) TFile f(fname); TTree *t = f.Get("t"); TTree t2("t2", "t2"); - const auto expected = "Tree 't' has the kEntriesReshuffled bit set, and cannot be used as " - "friend nor can be added as a friend unless the main tree has a TTreeIndex on the friend " - "tree 't2'. You can also unset the bit manually if you know what you are doing."; + const auto expected = + "Tree 't' has the kEntriesReshuffled bit set and cannot have friends nor can be added as a friend unless the " + "main tree has a TTreeIndex on the friend tree 't2'. You can also unset the bit manually if you know what you " + "are doing; note that you risk associating wrong TTree entries of the friend with those of the main TTree!"; ROOT_EXPECT_ERROR(t->AddFriend(&t2);, "AddFriend", expected); } } diff --git a/tree/dataframe/test/dataframe_vary.cxx b/tree/dataframe/test/dataframe_vary.cxx index 291cff705bbc4..53fc803db8848 100644 --- a/tree/dataframe/test/dataframe_vary.cxx +++ b/tree/dataframe/test/dataframe_vary.cxx @@ -6,6 +6,9 @@ #include // std::thread::hardware_concurrency #include "SimpleFiller.h" // for VaryFill +#include "TROOT.h" +#include "ROOT/RDF/RActionImpl.hxx" +#include "ROOT/RDF/RSampleInfo.hxx" #include @@ -377,6 +380,78 @@ TEST(RDFVary, SaveGraph) "source\\nEntries: 1\", style=\"filled\", fillcolor=\"#f4b400\", shape=\"ellipse\"];\n\t2 -> 1;\n\t0 -> 2;\n}"); } + +TEST(RDFVary, WithRange) // no Range in multithreaded runs +{ + auto h = ROOT::RDataFrame(10) + .Define("x", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) + .Vary( + "x", + [](int x) { + return ROOT::RVecI{x - 5, x + 5}; + }, + {"x"}, 2) + .Range(7) + .Filter("x > 1") + .Range(3) + .Sum("x"); + auto hs = VariationsFor(h); + + EXPECT_EQ(*h, 9); + EXPECT_EQ(hs["nominal"], 9); + EXPECT_EQ(hs["x:0"], 0); + EXPECT_EQ(hs["x:1"], 18); +} + + +// must update this test when https://github.com/root-project/root/issues/9894 is addressed +TEST(RDFVary, VaryDisplay) // TEST instead of TEST_P because Display is single-thread only +{ + auto d = ROOT::RDataFrame(1) + .Define("x", [] { return 0; }) + .Vary( + "x", + [] { + return ROOT::RVecI{-1, 2}; + }, + {}, 2) + .Display({"x"}); + // Display ignores variations, only displays the nominal values + EXPECT_EQ(d->AsString(), "+-----+---+\n| Row | x | \n+-----+---+\n| 0 | 0 | \n| | | \n+-----+---+\n"); + // cannot vary a Display + EXPECT_THROW( + try { VariationsFor(d); } catch (const std::logic_error &err) { + const auto msg = "The MakeNew method is not implemented for this action helper (Display). " + "Cannot Vary its result."; + EXPECT_STREQ(err.what(), msg); + throw; + }, + std::logic_error); +} + +// Make sure we can pass RResultMaps to RunGraphs (after converting them to RResultHandle). +TEST(RDFVary, ResultMapAndRunGraphs) +{ + auto m = ROOT::RDataFrame(1) + .Define("x", [] { return 0; }) + .Vary( + "x", + [] { + return ROOT::RVecI{-1, 1}; + }, + {}, 2) + .Max("x"); + auto mv = ROOT::RDF::Experimental::VariationsFor(m); + auto rh = ROOT::RDF::RResultHandle(mv); + ROOT::RDF::RunGraphs({rh}); + EXPECT_EQ(rh.GetValue(), 0); + EXPECT_EQ(mv["nominal"], 0); + EXPECT_EQ(&mv["nominal"], &rh.GetValue()); + EXPECT_EQ(mv["x:0"], -1); + EXPECT_EQ(mv["x:1"], 1); +} + +/************ These tests are run in single- and multi-thread mode (they use TEST_P instead of TEST) ************/ TEST_P(RDFVary, SimpleSum) { auto df = ROOT::RDataFrame(10).Define("x", [] { return 1; }); @@ -649,7 +724,7 @@ TEST_P(RDFVary, DefineDependingOnVariations) EXPECT_EQ(sums["yshift:low"], 410); } -TEST(RDFVary, VaryAndAlias) +TEST_P(RDFVary, VaryAndAlias) { auto df = ROOT::RDataFrame(10).Define("x", [] { return 1; }).Alias("y", "x").Vary("x", SimpleVariation, {}, 2); auto s1 = df.Sum("y"); @@ -913,28 +988,6 @@ TEST_P(RDFVary, FillHelperResets) EXPECT_EQ(ss2["x:1"].GetMean(), 2); } -TEST(RDFVary, WithRange) // no Range in multithreaded runs -{ - auto h = ROOT::RDataFrame(10) - .Define("x", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) - .Vary( - "x", - [](int x) { - return ROOT::RVecI{x - 5, x + 5}; - }, - {"x"}, 2) - .Range(7) - .Filter("x > 1") - .Range(3) - .Sum("x"); - auto hs = VariationsFor(h); - - EXPECT_EQ(*h, 9); - EXPECT_EQ(hs["nominal"], 9); - EXPECT_EQ(hs["x:0"], 0); - EXPECT_EQ(hs["x:1"], 18); -} - TEST_P(RDFVary, VaryRedefine) { // first redefine and then vary @@ -1133,31 +1186,6 @@ TEST_P(RDFVary, VaryCount) EXPECT_EQ(hs["x:1"], 2); } -// must update this test when https://github.com/root-project/root/issues/9894 is addressed -TEST(RDFVary, VaryDisplay) // TEST instead of TEST_P because Display is single-thread only -{ - auto d = ROOT::RDataFrame(1) - .Define("x", [] { return 0; }) - .Vary( - "x", - [] { - return ROOT::RVecI{-1, 2}; - }, - {}, 2) - .Display({"x"}); - // Display ignores variations, only displays the nominal values - EXPECT_EQ(d->AsString(), "+-----+---+\n| Row | x | \n+-----+---+\n| 0 | 0 | \n| | | \n+-----+---+\n"); - // cannot vary a Display - EXPECT_THROW( - try { VariationsFor(d); } catch (const std::logic_error &err) { - const auto msg = "The MakeNew method is not implemented for this action helper (Display). " - "Cannot Vary its result."; - EXPECT_STREQ(err.what(), msg); - throw; - }, - std::logic_error); -} - struct Jet { double a, b; }; @@ -1539,8 +1567,7 @@ TEST_P(RDFVary, VarySnapshot) .Snapshot("t", fname, {"x"}); EXPECT_THROW( try { VariationsFor(h); } catch (const std::logic_error &err) { - const auto msg = "The MakeNew method is not implemented for this action helper (Snapshot). " - "Cannot Vary its result."; + const auto msg = "Varying a Snapshot result is not implemented yet."; EXPECT_STREQ(err.what(), msg); throw; }, @@ -1592,6 +1619,57 @@ TEST_P(RDFVary, ManyVariationsManyColumns) } } +struct HelperWithCallback : ROOT::Detail::RDF::RActionImpl { + using Result_t = int; + std::shared_ptr fResult = std::make_shared(0); + static std::atomic_uint fCallbackCallCount; // shared among all the helpers for all variations + + void InitTask(TTreeReader *, unsigned int) {} + void Exec(unsigned int, int) {} // no-op + void Initialize() {} + void Finalize() { *fResult = fCallbackCallCount; } + std::shared_ptr GetResultPtr() const { return fResult; } + ROOT::RDF::SampleCallback_t GetSampleCallback() // increments fCallbackCallCount + { + auto callback = [](unsigned int, const ROOT::RDF::RSampleInfo &) { ++fCallbackCallCount; }; + return callback; + } + + HelperWithCallback MakeNew(void *newResult) + { + auto newHelper = HelperWithCallback(); + newHelper.fResult = *static_cast *>(newResult); + return newHelper; + } + + std::string GetActionName() const { return "HelperWithCallback"; } +}; + +std::atomic_uint HelperWithCallback::fCallbackCallCount{0u}; + +TEST_P(RDFVary, SampleCallbacks) +{ + // needs resetting between sequential and MT tests + HelperWithCallback::fCallbackCallCount = 0u; + + // we book 2 tasks per thread with IMT, or 1 task in total in sequential execution + const auto nTasks = std::max(ROOT::GetThreadPoolSize() * 2, 1u); + + auto r = ROOT::RDataFrame(nTasks) // one entry per task + .Define("x", [] { return 0; }) + .Vary( + "x", + [] { + return ROOT::RVecI{-1, 1}; + }, + {}, 2) + .Book(HelperWithCallback{}, {"x"}); + auto rv = VariationsFor(r); + + // the callback should have been called once per task per variation + EXPECT_EQ(*r, nTasks * 3); +} + // instantiate single-thread tests INSTANTIATE_TEST_SUITE_P(Seq, RDFVary, ::testing::Values(false)); @@ -1599,3 +1677,38 @@ INSTANTIATE_TEST_SUITE_P(Seq, RDFVary, ::testing::Values(false)); #ifdef R__USE_IMT INSTANTIATE_TEST_SUITE_P(MT, RDFVary, ::testing::Values(true)); #endif + +TEST(RDFVary, CheckVariationNames) +{ + // Create an RDF with a nominal histogram + ROOT::RDataFrame df(10); + auto df1 = df.Define("x", [] { return 1; }); + + // Vary the 'x' column + auto df2 = df1.Vary("x", [] { return ROOT::RVecI{-2, 2}; }, {}, {"down", "up"}); + + // Create a histogram from the varied column + auto h = df2.Histo1D({"MyName", "MyTitle", 10, -10, 10}, "x"); + + // Get the variations for the histogram + auto histos = VariationsFor(h); + + // Create a map of keys to expected names + std::map expectedNamesMap = { + {"nominal", "MyName"}, + {"x:down", "MyName_x_down"}, + {"x:up", "MyName_x_up"} + }; + + // Check if the keys correspond to the correct names + for (const auto &kv : histos) { + auto &variedHist = *kv.second; + const char* key = kv.first.c_str(); + const char* variedName = variedHist.GetName(); + + // Compare the expected name in the map and with the actual name + EXPECT_STREQ(expectedNamesMap[key].c_str(), variedName); + } +} + + diff --git a/tree/dataframe/test/datasource_arrow.cxx b/tree/dataframe/test/datasource_arrow.cxx index b399c42c7bfb1..05493baa3d43a 100644 --- a/tree/dataframe/test/datasource_arrow.cxx +++ b/tree/dataframe/test/datasource_arrow.cxx @@ -11,8 +11,7 @@ #include #include #include -#include -#include +#include #if defined(__GNUC__) #pragma GCC diagnostic pop #endif @@ -20,6 +19,68 @@ #include #include +using namespace arrow; + +#define ASSERT_OK(expr) \ + for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); !_st.ok();) \ + FAIL() << "'" ARROW_STRINGIFY(expr) "' failed with " << _st.ToString() + +// Copied from arrow/testing/builder.h +template +void ArrayFromVector(const std::shared_ptr &type, const std::vector &is_valid, + const std::vector &values, std::shared_ptr *out) +{ + auto type_id = TYPE::type_id; + ASSERT_EQ(type_id, type->id()) << "template parameter and concrete DataType instance don't agree"; + + std::unique_ptr builder_ptr; + ASSERT_OK(MakeBuilder(default_memory_pool(), type, &builder_ptr)); + // Get the concrete builder class to access its Append() specializations + auto &builder = dynamic_cast::BuilderType &>(*builder_ptr); + + for (size_t i = 0; i < values.size(); ++i) { + if (is_valid[i]) { + ASSERT_OK(builder.Append(values[i])); + } else { + ASSERT_OK(builder.AppendNull()); + } + } + ASSERT_OK(builder.Finish(out)); +} + +template +void ArrayFromVector(const std::shared_ptr &type, const std::vector &values, + std::shared_ptr *out) +{ + auto type_id = TYPE::type_id; + ASSERT_EQ(type_id, type->id()) << "template parameter and concrete DataType instance don't agree"; + + std::unique_ptr builder_ptr; + ASSERT_OK(MakeBuilder(default_memory_pool(), type, &builder_ptr)); + // Get the concrete builder class to access its Append() specializations + auto &builder = dynamic_cast::BuilderType &>(*builder_ptr); + + for (size_t i = 0; i < values.size(); ++i) { + ASSERT_OK(builder.Append(values[i])); + } + ASSERT_OK(builder.Finish(out)); +} + +// Overloads without a DataType argument, for parameterless types + +template +void ArrayFromVector(const std::vector &is_valid, const std::vector &values, std::shared_ptr *out) +{ + auto type = TypeTraits::type_singleton(); + ArrayFromVector(type, is_valid, values, out); +} + +template +void ArrayFromVector(const std::vector &values, std::shared_ptr *out) +{ + auto type = TypeTraits::type_singleton(); + ArrayFromVector(type, values, out); +} using namespace ROOT; using namespace ROOT::RDF; @@ -54,11 +115,11 @@ std::shared_ptr createTestTable() std::shared_ptr arrays_[5]; - arrow::ArrayFromVector(names, &arrays_[0]); - arrow::ArrayFromVector(ages, &arrays_[1]); - arrow::ArrayFromVector(heights, &arrays_[2]); - arrow::ArrayFromVector(marriageStatus, &arrays_[3]); - arrow::ArrayFromVector(babies, &arrays_[4]); + ArrayFromVector(names, &arrays_[0]); + ArrayFromVector(ages, &arrays_[1]); + ArrayFromVector(heights, &arrays_[2]); + ArrayFromVector(marriageStatus, &arrays_[3]); + ArrayFromVector(babies, &arrays_[4]); using ColumnType = typename decltype(std::declval().column(0))::element_type; diff --git a/tree/dataframe/test/datasource_csv.cxx b/tree/dataframe/test/datasource_csv.cxx index ede202b45e8a0..11d528a2a991e 100644 --- a/tree/dataframe/test/datasource_csv.cxx +++ b/tree/dataframe/test/datasource_csv.cxx @@ -322,9 +322,9 @@ TEST(RCsvDS, ProgressiveReadingRDFMT) TEST(RCsvDS, SpecifyColumnTypes) { - RCsvDS tds0(fileName0, true, ',', -1LL, {{"Age", 'D'}, {"Height", 'T'}}); // with headers + RCsvDS tds0(fileName0, true, ',', -1LL, {{"Age", 'D'}, {"Name", 'T'}}); // with headers EXPECT_STREQ("double", tds0.GetTypeName("Age").c_str()); - EXPECT_STREQ("std::string", tds0.GetTypeName("Height").c_str()); + EXPECT_STREQ("std::string", tds0.GetTypeName("Name").c_str()); RCsvDS tds1(fileName1, false, ',', -1LL, {{"Col1", 'T'}}); // without headers (Col0, ...) EXPECT_STREQ("std::string", tds1.GetTypeName("Col1").c_str()); @@ -350,6 +350,12 @@ TEST(RCsvDS, SpecifyColumnTypes) throw; }, std::runtime_error); + + auto df = ROOT::RDF::FromCSV(fileName0, true, ',', -1LL, {{"Age", 'L'}, {"Height", 'D'}}); + auto maxHeight = df.Max("Height"); + auto maxAge = df.Max("Age"); + EXPECT_DOUBLE_EQ(maxHeight.GetValue(), 200.5); + EXPECT_EQ(maxAge.GetValue(), 60); } TEST(RCsvDS, NaNTypeIndentification) diff --git a/tree/dataframe/test/datasource_ntuple.cxx b/tree/dataframe/test/datasource_ntuple.cxx index 976668bc304fb..a7e5e486345c5 100644 --- a/tree/dataframe/test/datasource_ntuple.cxx +++ b/tree/dataframe/test/datasource_ntuple.cxx @@ -6,6 +6,8 @@ #include #include +#include + #include using ROOT::Experimental::RNTupleDS; @@ -20,18 +22,23 @@ class RNTupleDSTest : public ::testing::Test { std::unique_ptr fPageSource; void SetUp() override { - auto modelWrite = RNTupleModel::Create(); - auto wrPt = modelWrite->MakeField("pt", 42.0); - auto wrEnergy = modelWrite->MakeField("energy", 7.0); - auto wrTag = modelWrite->MakeField("tag", "xyz"); - auto wrJets = modelWrite->MakeField>("jets", std::vector{1.f, 2.f}); - auto wrNnlo = modelWrite->MakeField>>("nnlo"); - wrNnlo->push_back(std::vector()); - wrNnlo->push_back(std::vector{1.0}); - wrNnlo->push_back(std::vector{1.0, 2.0, 4.0, 8.0}); - auto rvecI = modelWrite->MakeField("rvec", ROOT::RVecI{1, 2, 3}); + auto model = RNTupleModel::Create(); + model->MakeField("pt", 42.0); + model->MakeField("energy", 7.0); + model->MakeField("tag", "xyz"); + model->MakeField>("jets", std::vector{1.f, 2.f}); + auto fldNnlo = model->MakeField>>("nnlo"); + fldNnlo->push_back(std::vector()); + fldNnlo->push_back(std::vector{1.0}); + fldNnlo->push_back(std::vector{1.0, 2.0, 4.0, 8.0}); + model->MakeField("rvec", ROOT::RVecI{1, 2, 3}); + auto fldElectron = model->MakeField("electron"); + fldElectron->pt = 137.0; + auto fldVecElectron = model->MakeField>("VecElectron"); + fldVecElectron->push_back(*fldElectron); + fldVecElectron->push_back(*fldElectron); { - auto ntuple = RNTupleWriter::Recreate(std::move(modelWrite), fNtplName, fFileName); + auto ntuple = RNTupleWriter::Recreate(std::move(model), fNtplName, fFileName); ntuple->Fill(); } fPageSource = RPageSource::Create(fNtplName, fFileName); @@ -47,12 +54,18 @@ TEST_F(RNTupleDSTest, ColTypeNames) RNTupleDS tds(std::move(fPageSource)); auto colNames = tds.GetColumnNames(); - ASSERT_EQ(9, colNames.size()); + ASSERT_EQ(15, colNames.size()); EXPECT_TRUE(tds.HasColumn("pt")); EXPECT_TRUE(tds.HasColumn("energy")); EXPECT_TRUE(tds.HasColumn("rvec")); EXPECT_TRUE(tds.HasColumn("R_rdf_sizeof_nnlo")); + EXPECT_TRUE(tds.HasColumn("electron")); + EXPECT_TRUE(tds.HasColumn("electron.pt")); + EXPECT_TRUE(tds.HasColumn("VecElectron")); + EXPECT_TRUE(tds.HasColumn("R_rdf_sizeof_VecElectron")); + EXPECT_TRUE(tds.HasColumn("VecElectron.pt")); + EXPECT_TRUE(tds.HasColumn("R_rdf_sizeof_VecElectron.pt")); EXPECT_FALSE(tds.HasColumn("Address")); EXPECT_STREQ("std::string", tds.GetTypeName("tag").c_str()); @@ -105,6 +118,14 @@ void ReadTest(const std::string &name, const std::string &fname) { auto sumnnlo = df.Aggregate(sumvec, std::plus{}, "nnlo", 0.f); auto rvec = df.Take("rvec"); auto vectorasrvec = df.Take("jets"); + auto sumElectronPt = df.Aggregate([](float &acc, const Electron &e) { acc += e.pt; }, + [](float a, float b) { return a + b; }, "electron"); + auto sumVecElectronPt = df.Aggregate( + [](float &acc, const ROOT::RVec &ve) { + for (const auto &e : ve) + acc += e.pt; + }, + [](float a, float b) { return a + b; }, "VecElectron"); EXPECT_EQ(1ull, count.GetValue()); EXPECT_DOUBLE_EQ(42.f, sumpt.GetValue()); @@ -117,6 +138,8 @@ void ReadTest(const std::string &name, const std::string &fname) { EXPECT_EQ(5u, sumnnlosize.GetValue()); EXPECT_TRUE(All(rvec->at(0) == ROOT::RVecI{1, 2, 3})); EXPECT_TRUE(All(vectorasrvec->at(0) == ROOT::RVecF{1.f, 2.f})); + EXPECT_FLOAT_EQ(137.0, sumElectronPt.GetValue()); + EXPECT_FLOAT_EQ(2. * 137.0, sumVecElectronPt.GetValue()); } TEST_F(RNTupleDSTest, Read) @@ -124,6 +147,7 @@ TEST_F(RNTupleDSTest, Read) ReadTest(fNtplName, fFileName); } +#ifdef R__USE_IMT struct IMTRAII { IMTRAII() { ROOT::EnableImplicitMT(); } ~IMTRAII() { ROOT::DisableImplicitMT(); } @@ -135,3 +159,4 @@ TEST_F(RNTupleDSTest, ReadMT) ReadTest(fNtplName, fFileName); } +#endif diff --git a/tree/dataframe/test/spec.json b/tree/dataframe/test/spec.json index 96ee43d9469b3..b2b3980ec8810 100644 --- a/tree/dataframe/test/spec.json +++ b/tree/dataframe/test/spec.json @@ -1,30 +1,52 @@ { - "groups": [{ - "tag": "groupA", - "trees": ["subTree1", "subTree2"], - "files": ["PYspecTestFile5.root", "PYspecTestFile6.root"], - "metadata": { - "lumi": 1.0 - } - }, - { - "tag": "groupB", - "trees": ["subTree"], - "files": ["PYspecTestFile4.root"], - "metadata": { - "lumi": 0.5 - } - } - ], - "friends": { - "friendTree": { - "trees": ["anotherTree"], - "files": ["PYspecTestFile7.root"] - }, - "friendChain1": { - "trees": ["subTree"], - "files": ["PYspecTestFile2.root", "PYspecTestFile3.root", "PYspecTestFile4.root"] - } - }, - "range": [1, 10] + "samples": { + "sampleA": { + "trees": [ + "subTree1", + "subTree2" + ], + "files": [ + "PYspecTestFile5.root", + "PYspecTestFile6.root" + ], + "metadata": { + "lumi": 1.0 + } + }, + "sampleB": { + "trees": [ + "subTree" + ], + "files": [ + "PYspecTestFile4.root" + ], + "metadata": { + "lumi": 0.5 + } + } + }, + "friends": { + "friendTree": { + "trees": [ + "anotherTree" + ], + "files": [ + "PYspecTestFile7.root" + ] + }, + "friendChain1": { + "trees": [ + "subTree" + ], + "files": [ + "PYspecTestFile2.root", + "PYspecTestFile3.root", + "PYspecTestFile4.root" + ] + } + }, + "range": [ + 1, + 10 + ] } diff --git a/tree/dataframe/test/spec_ordering_samples_withFriends.json b/tree/dataframe/test/spec_ordering_samples_withFriends.json new file mode 100644 index 0000000000000..5d5507e64ebc5 --- /dev/null +++ b/tree/dataframe/test/spec_ordering_samples_withFriends.json @@ -0,0 +1,23 @@ +{ + "samples": { + "sample2": { + "trees": ["subTree"], + "files": ["FromSpecTestFile2.root"] + }, + "sample1": { + "trees": ["subTree"], + "files": ["FromSpecTestFile1.root"] + } + }, + "friends": { + "friendTree2": { + "trees": ["anotherTree"], + "files": [ "FromSpecTestFile4.root"] + }, + "friendTree1": { + "trees": ["anotherTree"], + "files": ["FromSpecTestFile3.root"] + } + } + } + \ No newline at end of file diff --git a/tree/ntuple/CMakeLists.txt b/tree/ntuple/CMakeLists.txt index 8783102ae8394..46898efeb856c 100644 --- a/tree/ntuple/CMakeLists.txt +++ b/tree/ntuple/CMakeLists.txt @@ -22,7 +22,6 @@ HEADERS ROOT/RColumnModel.hxx ROOT/REntry.hxx ROOT/RField.hxx - ROOT/RFieldValue.hxx ROOT/RFieldVisitor.hxx ROOT/RMiniFile.hxx ROOT/RNTuple.hxx diff --git a/tree/ntuple/v7/doc/specifications.md b/tree/ntuple/v7/doc/specifications.md index d831db7cf4cbd..b4b5c18db3fb1 100644 --- a/tree/ntuple/v7/doc/specifications.md +++ b/tree/ntuple/v7/doc/specifications.md @@ -25,10 +25,33 @@ For the ROOT file embedding, the **ROOT::Experimental::RNTuple** object acts as RNTuple envelopes and pages are wrapped in compression blocks. In order to deserialize a page or an envelope, its compressed and ucompressed size needs to be known. -TODO(jblomer): reference or describe the compression block format. - - Compressed size == uncompressed size --> uncompressed - - Otherwise: connected compressed chunks with the 9 byte header +If the compressed size == uncompressed size, the data is stored unmodified in uncompressed form. +Otherwise, data is represented as a series of compressed chunks. +Each chunk is prepended with the following 9 byte header. +``` +Byte +0 1 2 3 4 5 6 7 8 9 ++------+------+------+------+------+------+------+------+------+... +| Algorithm | Compressed size | Uncompressed size | ++------+------+------+------+------+------+------+------+------+... +``` + +_Algorithm_: Identifies the compression algorithm used to compress the data. This can take one of the following values + +| Algorithm | Meaning | +|--------------------------|----------------------------------------------| +| 'Z' 'L' '\x08' | zlib | +| 'C' 'S' '\x08' | Old Jean-loup Gailly's deflation algorithm | +| 'X' 'Z' '\x00' | LZMA | +| 'L' '4' | LZ4; third byte encodes major version number | +| 'Z' 'S' '\x01' | Zstd | + +_Compressed size_: An unsigned, little-endian integer that indicates the compressed size of the data that follows the header. + +_Uncompressed size_: An unsigned, little-endian integer that indicates the uncompressed size of the data that follows. +The maximum representable value is $(2^{24})-1$, i.e. 16777215, and thus each compressed chunk can represent up to 16 MiB of uncompressed data. +If the original data is larger than this value, more compressed chunks will follow. ## Basic Types @@ -43,7 +66,7 @@ followed by the characters. Strings are ASCII encoded; every character is a signed 8bit integer. _Compression settings_: A 32bit integer containing both a compression algorithm and the compression level. -The compression settings are encoded according to this formula: $$ settings = algorithm * 100 + level $$ +The compression settings are encoded according to this formula: $settings = algorithm * 100 + level$. See Compression.[h/cxx] for details and available algorithms. The meta-data envelope defines additional basic types (see below). @@ -227,6 +250,7 @@ The header consists of the following elements: - List frame: list of alias column record frames - List frame: list of extra type information +The last four list frames containing information about fields and columns are collectively referred to as _schema description_. The release candidate tag is used to mark unstable implementations of the file format. Production code sets the tag to zero. @@ -250,8 +274,11 @@ Every field record frame of the list of fields has the following contents The field version and type version are used for schema evolution. -If the flag 0x01 (_repetitive field_) is set, the field represents a fixed sized array. -In this case, an additional 64bit integer specifies the size of the array. +If `flags=0x0001` (_repetitive field_) is set, the field represents a fixed-size array. +In this case, an additional 64bit integer follows immediately that specifies the size of the array. +Typically, another (sub) field with `Parent Field ID` equal to the ID of this field +is expected to be found, representing the array content +(see Section "Mapping of C++ Types to Fields and Columns"). The block of integers is followed by a list of strings: @@ -270,7 +297,6 @@ The flags field can have one of the following bits set | Bit | Meaning | |----------|----------------------------------------------------------------------------| | 0x01 | Repetitive field, i.e. for every entry $n$ copies of the field are stored | -| 0x02 | Alias field, the columns referring to this field are alias columns | The structural role of the field can have on of the following values @@ -314,20 +340,41 @@ The column type and bits on storage integers can have one of the following value | 0x07 | 64 | Real64 | IEEE-754 double precision float | | 0x08 | 32 | Real32 | IEEE-754 single precision float | | 0x09 | 16 | Real16 | IEEE-754 half precision float | -| 0x0A | 64 | Int64 | Two's complement, little-endian 8 byte integer | -| 0x0B | 32 | Int32 | Two's complement, little-endian 4 byte integer | -| 0x0C | 16 | Int16 | Two's complement, little-endian 2 byte integer | -| 0x0D | 8 | Int8 | Two's complement, 1 byte integer | +| 0x16 | 64 | Int64 | Two's complement, little-endian 8 byte signed integer | +| 0x0A | 64 | UInt64 | Little-endian 8 byte unsigned integer | +| 0x17 | 32 | Int32 | Two's complement, little-endian 4 byte signed integer | +| 0x0B | 32 | UInt32 | Little-endian 4 byte unsigned integer | +| 0x18 | 16 | Int16 | Two's complement, little-endian 2 byte signed integer | +| 0x0C | 16 | UInt16 | Little-endian 2 byte unsigned integer | +| 0x19 | 8 | Int8 | Two's complement, 1 byte signed integer | +| 0x0D | 8 | UInt8 | 1 byte unsigned integer | | 0x0E | 64 | SplitIndex64 | Like Index64 but pages are stored in split + delta encoding | | 0x0F | 32 | SplitIndex32 | Like Index32 but pages are stored in split + delta encoding | | 0x10 | 64 | SplitReal64 | Like Real64 but in split encoding | | 0x11 | 32 | SplitReal32 | Like Real32 but in split encoding | | 0x12 | 16 | SplitReal16 | Like Real16 but in split encoding | -| 0x13 | 64 | SplitInt64 | Like Int64 but in split encoding | -| 0x14 | 32 | SplitInt32 | Like Int32 but in split encoding | -| 0x15 | 16 | SplitInt16 | Like Int16 but in split encoding | +| 0x1A | 64 | SplitInt64 | Like Int64 but in split + zigzag encoding | +| 0x13 | 64 | SplitUInt64 | Like UInt64 but in split encoding | +| 0x1B | 64 | SplitInt32 | Like Int32 but in split + zigzag encoding | +| 0x14 | 32 | SplitUInt32 | Like UInt32 but in split encoding | +| 0x1C | 16 | SplitInt16 | Like Int16 but in split + zigzag encoding | +| 0x15 | 16 | SplitUInt16 | Like UInt16 but in split encoding | + +The "split encoding" columns apply a byte transformation encoding to all pages of that column +and in addition, depending on the column type, delta or zigzag encoding: + +Split (only) +: Rearranges the bytes of elements: All the first bytes first, then all the second bytes, etc. + +Delta + split +: The first element is stored unmodified, all other elements store the delta to the previous element. + Followed by split encoding. + +Zigzag + split +: Used on signed integers only; it maps $x$ to $2x$ if $x$ is positive and to $-(2x+1)$ if $x$ is negative. + Followed by split encoding. -Future versions of the file format may introduce addtional column types +Future versions of the file format may introduce additional column types without changing the minimum version of the header. Old readers need to ignore these columns and fields constructed from such columns. Old readers can, however, figure out the number of elements stored in such unknown columns. @@ -339,7 +386,14 @@ The flags field can have one of the following bits set | 0x01 | Elements in the column are sorted (monotonically increasing) | | 0x02 | Elements in the column are sorted (monotonically decreasing) | | 0x04 | Elements have only non-negative values | +| 0x08 | Index of first element in the column is not zero | +If flag 0x08 (deferred column) is set, the index of the first element in this column is not zero, which happens if the column is added at a later point during write. +In this case, an additional 64bit integer containing the first element index follows the flags field. +Compliant implementations should yield synthetic data pages made up of 0x00 bytes when trying to read back elements in the range $[0, firstElementIndex-1]$. +This results in zero-initialized values in the aforementioned range for fields of any supported C++ type, including `std::variant` and collections such as `std::vector`. +The leading zero pages of deferred columns are _not_ part of the page list, i.e. they have no page locator. +In practice, deferred columns only appear in the schema extension record frame (see Section Footer Envelope). #### Alias columns @@ -354,9 +408,10 @@ An alias column has the following format | Field ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` - +Alias columns do not have associated data pages. Instead, their data comes from another column referred to below as "physical column". The first 32bit integer references the physical column ID. -The second 32bit integer references a field that needs to have the "alias field" flag set. +The second 32bit integer references the associated "projected" field. +A projected field is a field using alias columns to present available data by an alternative C++ type. The ID of the alias column itself is given implicitly by the serialization order. In particular, alias columns have larger IDs than physical columns. In the footer and page list envelopes, only physical column IDs must be referenced. @@ -397,7 +452,7 @@ The footer envelope has the following structure: - Feature flags - Header checksum (CRC32) -- List frame of extension header envelope links +- Schema extension record frame - List frame of column group record frames - List frame of cluster summary record frames - List frame of cluster group record frames @@ -405,8 +460,21 @@ The footer envelope has the following structure: The header checksum can be used to cross-check that header and footer belong together. -The extension headers are just additional headers with an empty name and description. -They are necessary when fields have been backfilled during writing. +#### Schema Extension Record Frame + +The schema extension record frame contains an additional schema description that is incremental with respect to the schema contained in the header (see Section Header Envelope). Specifically, it is a record frame with the following four fields (identical to the last four fields in Header Envelope): + + - List frame: list of field record frames + - List frame: list of column record frames + - List frame: list of alias column record frames + - List frame: list of extra type information + + +In general, a schema extension is optional and thus this record frame might be empty. +The interpretation of the information contained therein should be identical as if it was found directly at the end of the header. +This is necessary when fields have been added during writing. + + The ntuple meta-data can be split over multiple meta-data envelopes (see below). @@ -453,7 +521,7 @@ The cluster summary record frame contains the entry range of a cluster: If flag 0x01 (sharded cluster) is set, an additional 32bit integer containing the column group ID follows the flags field. If flags is zero, the cluster stores the event range of _all_ the original columns -_excluding_ the columns from extension headers. +_including_ the columns from extension headers. The order of the cluster summaries defines the cluster IDs, starting from zero. @@ -588,14 +656,24 @@ The following fundamental types are stored as `leaf` fields with a single column -----------------------------------|------------------------|-----------------------| | bool | Bit | | | char | Char | | -| int8_t, uint_8_t, unsigned char | Int8 | | -| int16_t, uint16_t | SplitInt16 | Int16 | -| int32_t, uint32_t | SplitInt32 | Int32 | -| int64_t, uint64_t | SplitInt64 | Int64 | +| int8_t | Int8 | | +| uint_8_t, unsigned char | UInt8 | | +| int16_t | SplitInt16 | Int16 | +| uint16_t | SplitUInt16 | UInt16 | +| uint32_t | SplitUInt32 | UInt32 | +| int32_t | SplitInt32 | Int32 | +| uint64_t | SplitUInt64 | UInt64 | +| int64_t | SplitInt64 | Int64 | | float | SplitReal32 | Real32 | | double | SplitReal64 | Real64 | Possibly available `const` and `volatile` qualifiers of the C++ types are ignored for serialization. +If the ntuple is stored uncompressed, the default changes from split encoding to non-split encoding where applicable. + +### Low-precision Floating Points + +The ROOT type `Double32_t` is stored on disk as a `double` field with a `SplitReal32` column representation. +The field's type alias is set to `Double32_t`. ### STL Types and Collections @@ -612,26 +690,31 @@ A string is stored as a single field with two columns. The first (principle) column is of type SplitIndex32. The second column is of type Char. -#### std::vector and ROOT::RVec +#### std::vector\ and ROOT::RVec\ STL vector and ROOT's RVec have identical on-disk representations. They are stored as two fields: - - Collection mother field of type SplitIndex32 or SplitIndex64 + - Collection mother field whose principal column is of type `(Split)Index[64|32]`. - Child field of type `T`, which must by a type with RNTuple I/O support. The name of the child field is `_0`. #### std::array and array type of the form T[N] -Fixed-sized arrays are stored as single repetitive fields of type `T`. -The array size `N` is stored in the field meta-data. +Fixed-sized arrays are stored as two fields: + - A repetitive field of type `std::array` with no attached columns. The array size `N` is stored in the field meta-data. + - Child field of type `T` named `_0`, which must be a type with RNTuple I/O support. + Multi-dimensional arrays of the form `T[N][M]...` are currently not supported. #### std::variant Variants are stored in $n+1$ fields: - - Variant mother field of type Switch; the dispatch tag points to the principle column of the active type + - Variant mother field with one column of type Switch; the dispatch tag points to the principal column of the active type - Child fields of types `T1`, ..., `Tn`; their names are `_0`, `_1`, ... +The dispatch tag ranges from 1 to $n$. +A value of 0 indicates that the variant is in the invalid state, i.e., it does not hold any of the valid alternatives. + #### std::pair A pair is stored using an empty mother field with two subfields, one of type `T1` and one of type `T2`. `T1` and `T2` must be types with RNTuple I/O support. @@ -640,7 +723,40 @@ The child fileds are named `_0` and `_1`. #### std::tuple A tuple is stored using an empty mother field with $n$ subfields of type `T1`, `T2`, ..., `Tn`. All types must have RNTuple I/O support. -The child fileds are named `_0`, `_1`, ... +The child fields are named `_0`, `_1`, ... + +#### std::bitset\ + +A bitset is stored as a repetitive leaf field with an attached `Bit` column. +The bitset size `N` is stored as repetition parameter in the field meta-data. +Within the repetition blocks, bits are stored in little-endian order, i.e. the least significant bits come first. + +#### std::unique_ptr\, std::optional\ + +A unique pointer and an optional type have the same on disk representation. +They are represented as a collection of `T`s of zero or one elements. +A collection mother field has a single subfield named `_0` for `T`, where `T` must have RNTuple I/O support. +Note that RNTuple does not support polymorphism, so the type `T` is expected to be `T` and not a child class of `T`. + +By default, the mother field has a principal column of type `(Split)Index[64|32]`. +This is called sparse representation. +The alternative, dense representation uses a `Bit` column to mask non-existing instances of the subfield. +In this second case, a default-constructed `T` (or, if applicable, a `T` constructed by the ROOT I/O constructor) is stored on disk for the non-existing instances. + +#### std::set\ + +While STL sets by definition are associative containers (i.e., elements are referenced by their keys, which in the case for sets are equal to the values), on disk they are represented as indexed collections. +This means that they have the same on-disk representation as `std::vector`, using two fields: + - Collection mother field whose principal column is of type `(Split)Index[64|32]`. + - Child field of type `T`, which must by a type with RNTuple I/O support. + The name of the child field is `_0`. + +### User-defined enums + +User-defined enums are stored as a leaf field with a single subfield named `_0`. +The mother field has no attached columns. +The subfield corresponds to the integer type the underlies the enum. +Unscoped and scoped enums are supported as long as the enum has a dictionary. ### User-defined classes @@ -668,10 +784,21 @@ User classes that specify a collection proxy behave as collections of a given va Associative collections are not currently supported. The on-disk representation is similar to a `std::vector` where `T` is the value type; specifically, it is stored as two fields: - - Collection mother field of type SplitIndex32 or SplitIndex64 + - Collection mother field whose principal column is of type `(Split)Index[64|32]`. - Child field of type `T`, which must by a type with RNTuple I/O support. The name of the child field is `_0`. +### ROOT::Experimental::RNTupleCardinality + +A field whose type is `ROOT::Experimental::RNTupleCardinality` is associated to a single column of type (Split)Index32 or (Split)Index64. +This field presents the offsets in the index column as lengths that correspond to the cardinality of the pointed-to collection. + +The value for the $i$-th element is computed by subtracting the $(i-1)$-th value from the $i$-th value in the index column. +If $i == 0$, i.e. it falls on the start of a cluster, the $(i-1)$-th value in the index column is assumed to be 0, e.g. given the index column values `[1, 1, 3]`, the values yielded by `RNTupleCardinality` shall be `[1, 0, 2]`. + +The `SizeT` template parameter defines the in-memory integer type of the collection size. +The valid types are `std::uint32_t` and `std::uint64_t`. + ## Limits TODO(jblomer) diff --git a/tree/ntuple/v7/inc/ROOT/RCluster.hxx b/tree/ntuple/v7/inc/ROOT/RCluster.hxx index d91871c0229d2..e4a7d68289ea3 100644 --- a/tree/ntuple/v7/inc/ROOT/RCluster.hxx +++ b/tree/ntuple/v7/inc/ROOT/RCluster.hxx @@ -51,11 +51,11 @@ public: /// On-disk pages within a page source are identified by the column and page number. The key is used for /// associative collections of on-disk pages. struct Key { - DescriptorId_t fColumnId; + DescriptorId_t fPhysicalColumnId; std::uint64_t fPageNo; - Key(DescriptorId_t columnId, std::uint64_t pageNo) : fColumnId(columnId), fPageNo(pageNo) {} + Key(DescriptorId_t columnId, std::uint64_t pageNo) : fPhysicalColumnId(columnId), fPageNo(pageNo) {} friend bool operator ==(const Key &lhs, const Key &rhs) { - return lhs.fColumnId == rhs.fColumnId && lhs.fPageNo == rhs.fPageNo; + return lhs.fPhysicalColumnId == rhs.fPhysicalColumnId && lhs.fPageNo == rhs.fPageNo; } }; @@ -81,8 +81,9 @@ namespace std // TODO(jblomer): quick and dirty hash, likely very sub-optimal, to be revised later. size_t operator()(const ROOT::Experimental::Detail::ROnDiskPage::Key &key) const { - return ((std::hash()(key.fColumnId) ^ - (hash()(key.fPageNo) << 1)) >> 1); + return ((std::hash()(key.fPhysicalColumnId) ^ + (hash()(key.fPageNo) << 1)) >> + 1); } }; } @@ -157,7 +158,7 @@ public: /// The identifiers that specifies the content of a (partial) cluster struct RKey { DescriptorId_t fClusterId = kInvalidDescriptorId; - ColumnSet_t fColumnSet; + ColumnSet_t fPhysicalColumnSet; }; protected: @@ -166,7 +167,7 @@ protected: /// Multiple page maps can be combined in a single RCluster std::vector> fPageMaps; /// Set of the (complete) columns represented by the RCluster - ColumnSet_t fAvailColumns; + ColumnSet_t fAvailPhysicalColumns; /// Lookup table for the on-disk pages std::unordered_map fOnDiskPages; @@ -191,12 +192,12 @@ public: /// Marks the column as complete; must be done for all columns, even empty ones without associated pages, /// before the cluster is given from the page storage to the cluster pool. Marking the available columns is /// typically the last step of RPageSouce::LoadCluster(). - void SetColumnAvailable(DescriptorId_t columnId); + void SetColumnAvailable(DescriptorId_t physicalColumnId); const ROnDiskPage *GetOnDiskPage(const ROnDiskPage::Key &key) const; DescriptorId_t GetId() const { return fClusterId; } - const ColumnSet_t &GetAvailColumns() const { return fAvailColumns; } - bool ContainsColumn(DescriptorId_t columnId) const { return fAvailColumns.count(columnId) > 0; } + const ColumnSet_t &GetAvailPhysicalColumns() const { return fAvailPhysicalColumns; } + bool ContainsColumn(DescriptorId_t colId) const { return fAvailPhysicalColumns.count(colId) > 0; } size_t GetNOnDiskPages() const { return fOnDiskPages.size(); } }; diff --git a/tree/ntuple/v7/inc/ROOT/RClusterPool.hxx b/tree/ntuple/v7/inc/ROOT/RClusterPool.hxx index 23ac9208ecbfd..e0ad57e377bc5 100644 --- a/tree/ntuple/v7/inc/ROOT/RClusterPool.hxx +++ b/tree/ntuple/v7/inc/ROOT/RClusterPool.hxx @@ -20,10 +20,10 @@ #include #include +#include #include #include #include -#include #include #include #include @@ -81,7 +81,8 @@ private: bool operator ==(const RInFlightCluster &other) const { return (fClusterKey.fClusterId == other.fClusterKey.fClusterId) && - (fClusterKey.fColumnSet == other.fClusterKey.fColumnSet); } + (fClusterKey.fPhysicalColumnSet == other.fClusterKey.fPhysicalColumnSet); + } bool operator !=(const RInFlightCluster &other) const { return !(*this == other); } /// First order by cluster id, then by number of columns, than by the column ids in fColumns bool operator <(const RInFlightCluster &other) const; @@ -108,13 +109,13 @@ private: /// Signals a non-empty I/O work queue std::condition_variable fCvHasReadWork; /// The communication channel to the I/O thread - std::queue fReadQueue; + std::deque fReadQueue; /// The lock associated with the fCvHasUnzipWork conditional variable std::mutex fLockUnzipQueue; /// Signals non-empty unzip work queue std::condition_variable fCvHasUnzipWork; /// The communication channel between the I/O thread and the unzip thread - std::queue fUnzipQueue; + std::deque fUnzipQueue; /// The I/O thread calls RPageSource::LoadClusters() asynchronously. The thread is mostly waiting for the /// data to arrive (blocked by the kernel) and therefore can safely run in addition to the application @@ -135,10 +136,10 @@ private: /// The unzip thread routine which takes a loaded cluster and passes it to fPageSource.UnzipCluster (which /// might be a no-op if IMT is off). Marks the cluster as ready to be picked up by the main thread. void ExecUnzipClusters(); - /// Returns the given cluster from the pool, which needs to contain at least the columns `columns`. + /// Returns the given cluster from the pool, which needs to contain at least the columns `physicalColumns`. /// Executed at the end of GetCluster when all missing data pieces have been sent to the load queue. /// Ideally, the function returns without blocking if the cluster is already in the pool. - RCluster *WaitFor(DescriptorId_t clusterId, const RCluster::ColumnSet_t &columns); + RCluster *WaitFor(DescriptorId_t clusterId, const RCluster::ColumnSet_t &physicalColumns); public: static constexpr unsigned int kDefaultClusterBunchSize = 1; @@ -150,11 +151,11 @@ public: /// Returns the requested cluster either from the pool or, in case of a cache miss, lets the I/O thread load /// the cluster in the pool, blocks until done, and then returns it. Triggers along the way the background loading - /// of the following fWindowPost number of clusters. The returned cluster has at least all the pages of `columns` - /// and possibly pages of other columns, too. If implicit multi-threading is turned on, the uncompressed pages - /// of the returned cluster are already pushed into the page pool associated with the page source upon return. - /// The cluster remains valid until the next call to GetCluster(). - RCluster *GetCluster(DescriptorId_t clusterId, const RCluster::ColumnSet_t &columns); + /// of the following fWindowPost number of clusters. The returned cluster has at least all the pages of + /// `physicalColumns` and possibly pages of other columns, too. If implicit multi-threading is turned on, the + /// uncompressed pages of the returned cluster are already pushed into the page pool associated with the page source + /// upon return. The cluster remains valid until the next call to GetCluster(). + RCluster *GetCluster(DescriptorId_t clusterId, const RCluster::ColumnSet_t &physicalColumns); /// Used by the unit tests to drain the queue of clusters to be preloaded void WaitForInFlightClusters(); diff --git a/tree/ntuple/v7/inc/ROOT/RColumn.hxx b/tree/ntuple/v7/inc/ROOT/RColumn.hxx index 9572934e1ed1d..891ed6a91c39f 100644 --- a/tree/ntuple/v7/inc/ROOT/RColumn.hxx +++ b/tree/ntuple/v7/inc/ROOT/RColumn.hxx @@ -25,7 +25,9 @@ #include +#include // for memcpy #include +#include namespace ROOT { namespace Experimental { @@ -36,9 +38,6 @@ namespace Detail { \class ROOT::Experimental::RColumn \ingroup NTuple \brief A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into memory. - -On the primitives data layer, the RColumn and RColumnElement are the equivalents to RField and RFieldValue on the -logical data layer. */ // clang-format on class RColumn { @@ -71,6 +70,8 @@ private: RPage fReadPage; /// The column id is used to find matching pages with content when reading ColumnId_t fColumnIdSource = kInvalidColumnId; + /// Global index of the first element in this column; usually == 0, unless it is a deferred column + NTupleSize_t fFirstElementIndex = 0; /// Used to pack and unpack pages on writing/reading std::unique_ptr fElement; @@ -99,11 +100,11 @@ private: } public: - template - static RColumn *Create(const RColumnModel &model, std::uint32_t index) { - R__ASSERT(model.GetType() == ColumnT); - auto column = new RColumn(model, index); - column->fElement = std::unique_ptr(new RColumnElement(nullptr)); + template + static std::unique_ptr Create(const RColumnModel &model, std::uint32_t index) + { + auto column = std::unique_ptr(new RColumn(model, index)); + column->fElement = RColumnElementBase::Generate(model.GetType()); return column; } @@ -111,101 +112,114 @@ public: RColumn &operator =(const RColumn&) = delete; ~RColumn(); - void Connect(DescriptorId_t fieldId, RPageStorage *pageStorage); + /// Connect the column to a page storage. If `pageStorage` is a page sink, `firstElementIndex` can be used to + /// specify the first column element index with backing storage for this column. On read back, elements before + /// `firstElementIndex` will cause the zero page to be mapped. + /// TODO(jalopezg): at this point it would be nicer to distinguish between connecting a page sink and a page source + void Connect(DescriptorId_t fieldId, RPageStorage *pageStorage, NTupleSize_t firstElementIndex = 0U); - void Append(const RColumnElementBase &element) { + void Append(const void *from) + { void *dst = fWritePage[fWritePageIdx].GrowUnchecked(1); if (fWritePage[fWritePageIdx].GetNElements() == fApproxNElementsPerPage / 2) { FlushShadowWritePage(); } - element.WriteTo(dst, 1); + std::memcpy(dst, from, fElement->GetSize()); fNElements++; SwapWritePagesIfFull(); } - void AppendV(const RColumnElementBase &elemArray, std::size_t count) { + void AppendV(const void *from, std::size_t count) + { // We might not have enough space in the current page. In this case, fall back to one by one filling. if (fWritePage[fWritePageIdx].GetNElements() + count > fApproxNElementsPerPage) { // TODO(jblomer): use (fewer) calls to AppendV to write the data page-by-page for (unsigned i = 0; i < count; ++i) { - Append(RColumnElementBase(elemArray, i)); + Append(static_cast(from) + fElement->GetSize() * i); } return; } - void *dst = fWritePage[fWritePageIdx].GrowUnchecked(count); - // The check for flushing the shadow page is more complicated than for the Append() case // because we don't necessarily fill up to exactly fApproxNElementsPerPage / 2 elements; - // we might instead jump over the 50% fill level + // we might instead jump over the 50% fill level. + // This check should be done before calling `RPage::GrowUnchecked()` as the latter affects the return value of + // `RPage::GetNElements()`. if ((fWritePage[fWritePageIdx].GetNElements() < fApproxNElementsPerPage / 2) && (fWritePage[fWritePageIdx].GetNElements() + count >= fApproxNElementsPerPage / 2)) { FlushShadowWritePage(); } - elemArray.WriteTo(dst, count); + void *dst = fWritePage[fWritePageIdx].GrowUnchecked(count); + + std::memcpy(dst, from, fElement->GetSize() * count); fNElements += count; // Note that by the very first check in AppendV, we cannot have filled more than fApproxNElementsPerPage elements SwapWritePagesIfFull(); } - void Read(const NTupleSize_t globalIndex, RColumnElementBase *element) { + void Read(const NTupleSize_t globalIndex, void *to) + { if (!fReadPage.Contains(globalIndex)) { MapPage(globalIndex); - R__ASSERT(fReadPage.Contains(globalIndex)); } - void *src = static_cast(fReadPage.GetBuffer()) + - (globalIndex - fReadPage.GetGlobalRangeFirst()) * element->GetSize(); - element->ReadFrom(src, 1); + const auto elemSize = fElement->GetSize(); + void *from = static_cast(fReadPage.GetBuffer()) + + (globalIndex - fReadPage.GetGlobalRangeFirst()) * elemSize; + std::memcpy(to, from, elemSize); } - void Read(const RClusterIndex &clusterIndex, RColumnElementBase *element) { + void Read(const RClusterIndex &clusterIndex, void *to) + { if (!fReadPage.Contains(clusterIndex)) { MapPage(clusterIndex); } - void *src = static_cast(fReadPage.GetBuffer()) + - (clusterIndex.GetIndex() - fReadPage.GetClusterRangeFirst()) * element->GetSize(); - element->ReadFrom(src, 1); + const auto elemSize = fElement->GetSize(); + void *from = static_cast(fReadPage.GetBuffer()) + + (clusterIndex.GetIndex() - fReadPage.GetClusterRangeFirst()) * elemSize; + std::memcpy(to, from, elemSize); } - void ReadV(const NTupleSize_t globalIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray) { - R__ASSERT(count > 0); + void ReadV(const NTupleSize_t globalIndex, const ClusterSize_t::ValueType count, void *to) + { if (!fReadPage.Contains(globalIndex)) { MapPage(globalIndex); } NTupleSize_t idxInPage = globalIndex - fReadPage.GetGlobalRangeFirst(); - void *src = static_cast(fReadPage.GetBuffer()) + idxInPage * elemArray->GetSize(); + const auto elemSize = fElement->GetSize(); + const void *from = static_cast(fReadPage.GetBuffer()) + idxInPage * elemSize; if (globalIndex + count <= fReadPage.GetGlobalRangeLast() + 1) { - elemArray->ReadFrom(src, count); + std::memcpy(to, from, elemSize * count); } else { ClusterSize_t::ValueType nBatch = fReadPage.GetNElements() - idxInPage; - elemArray->ReadFrom(src, nBatch); - RColumnElementBase elemTail(*elemArray, nBatch); - ReadV(globalIndex + nBatch, count - nBatch, &elemTail); + std::memcpy(to, from, elemSize * nBatch); + auto tail = static_cast(to) + nBatch * elemSize; + ReadV(globalIndex + nBatch, count - nBatch, tail); } } - void ReadV(const RClusterIndex &clusterIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray) + void ReadV(const RClusterIndex &clusterIndex, const ClusterSize_t::ValueType count, void *to) { if (!fReadPage.Contains(clusterIndex)) { MapPage(clusterIndex); } NTupleSize_t idxInPage = clusterIndex.GetIndex() - fReadPage.GetClusterRangeFirst(); - void* src = static_cast(fReadPage.GetBuffer()) + idxInPage * elemArray->GetSize(); + const auto elemSize = fElement->GetSize(); + const void *from = static_cast(fReadPage.GetBuffer()) + idxInPage * elemSize; if (clusterIndex.GetIndex() + count <= fReadPage.GetClusterRangeLast() + 1) { - elemArray->ReadFrom(src, count); + std::memcpy(to, from, elemSize * count); } else { ClusterSize_t::ValueType nBatch = fReadPage.GetNElements() - idxInPage; - elemArray->ReadFrom(src, nBatch); - RColumnElementBase elemTail(*elemArray, nBatch); - ReadV(RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() + nBatch), count - nBatch, &elemTail); + std::memcpy(to, from, elemSize * nBatch); + auto tail = static_cast(to) + nBatch * elemSize; + ReadV(RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() + nBatch), count - nBatch, tail); } } @@ -309,7 +323,9 @@ public: const RColumnModel &GetModel() const { return fModel; } std::uint32_t GetIndex() const { return fIndex; } ColumnId_t GetColumnIdSource() const { return fColumnIdSource; } + NTupleSize_t GetFirstElementIndex() const { return fFirstElementIndex; } RPageSource *GetPageSource() const { return fPageSource; } + RPageSink *GetPageSink() const { return fPageSink; } RPageStorage::ColumnHandle_t GetHandleSource() const { return fHandleSource; } RPageStorage::ColumnHandle_t GetHandleSink() const { return fHandleSink; } }; diff --git a/tree/ntuple/v7/inc/ROOT/RColumnElement.hxx b/tree/ntuple/v7/inc/ROOT/RColumnElement.hxx index 31899c9402839..2893b1682720a 100644 --- a/tree/ntuple/v7/inc/ROOT/RColumnElement.hxx +++ b/tree/ntuple/v7/inc/ROOT/RColumnElement.hxx @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -28,6 +29,7 @@ #include #include #include +#include #ifndef R__LITTLE_ENDIAN #ifdef R__BYTESWAP @@ -39,12 +41,35 @@ #endif /* R__LITTLE_ENDIAN */ namespace { + +// In this namespace, common routines are defined for element packing and unpacking of ints and floats. +// The following conversions and encodings exist: +// +// - Byteswap: on big endian machines, ints and floats are byte-swapped to the little endian on-disk format +// - Cast: in-memory values can be stored in narrower on-disk columns. Currently without bounds checks. +// For instance, for Double32_t, an in-memory double value is stored as a float on disk. +// - Split: rearranges the bytes of an array of elements such that all the first bytes are stored first, +// followed by all the second bytes, etc. This often clusters similar values, e.g. all the zero bytes +// for arrays of small integers. +// - Delta: Delta encoding stores on disk the delta to the previous element. This is useful for offsets, +// because it transforms potentially large offset values into small deltas, which are then better +// suited for split encoding. +// - Zigzag: Zigzag encoding is used on signed integers only. It maps x to 2x if x is positive and to -(2x+1) if +// x is negative. For series of positive and negative values of small absolute value, it will produce +// a bit pattern that is favorable for split encoding. +// +// Encodings/conversions can be fused: +// +// - Delta/Zigzag + Splitting (there is no only-delta/zigzag encoding) +// - (Delta/Zigzag + ) Splitting + Casting +// - Everything + Byteswap + /// \brief Copy and byteswap `count` elements of size `N` from `source` to `destination`. /// /// Used on big-endian architectures for packing/unpacking elements whose column type requires /// a little-endian on-disk representation. template -static void CopyElementsBswap(void *destination, const void *source, std::size_t count) +static void CopyBswap(void *destination, const void *source, std::size_t count) { auto dst = reinterpret_cast::value_type *>(destination); auto src = reinterpret_cast::value_type *>(source); @@ -52,6 +77,168 @@ static void CopyElementsBswap(void *destination, const void *source, std::size_t dst[i] = RByteSwap::bswap(src[i]); } } + +/// Casts T to one of the ints used in RByteSwap and back to its original type, which may be float or double +#if R__LITTLE_ENDIAN == 0 +template +void ByteSwapIfNecessary(T &value) +{ + constexpr auto N = sizeof(T); + using bswap_value_type = typename RByteSwap::value_type; + void *valuePtr = &value; + auto swapped = RByteSwap::bswap(*reinterpret_cast(valuePtr)); + *reinterpret_cast(valuePtr) = swapped; +} +#else +#define ByteSwapIfNecessary(x) ((void)0) +#endif + +/// \brief Pack `count` elements into narrower (or wider) type +/// +/// Used to convert in-memory elements to smaller column types of comatible types +/// (e.g., double to float, int64 to int32). Takes care of byte swap if necessary. +template +static void CastPack(void *destination, const void *source, std::size_t count) +{ + static_assert(std::is_convertible_v); + auto dst = reinterpret_cast(destination); + auto src = reinterpret_cast(source); + for (std::size_t i = 0; i < count; ++i) { + dst[i] = src[i]; + ByteSwapIfNecessary(dst[i]); + } +} + +/// \brief Unpack `count` on-disk elements into wider (or narrower) in-memory array +/// +/// Used to convert on-disk elements to larger C++ types of comatible types +/// (e.g., float to double, int32 to int64). Takes care of byte swap if necessary. +template +static void CastUnpack(void *destination, const void *source, std::size_t count) +{ + auto dst = reinterpret_cast(destination); + auto src = reinterpret_cast(source); + for (std::size_t i = 0; i < count; ++i) { + SourceT val = src[i]; + ByteSwapIfNecessary(val); + dst[i] = val; + } +} + +/// \brief Split encoding of elements, possibly into narrower column +/// +/// Used to first cast and then split-encode in-memory values to the on-disk column. Swap bytes if necessary. +template +static void CastSplitPack(void *destination, const void *source, std::size_t count) +{ + constexpr std::size_t N = sizeof(DestT); + auto splitArray = reinterpret_cast(destination); + auto src = reinterpret_cast(source); + for (std::size_t i = 0; i < count; ++i) { + DestT val = src[i]; + ByteSwapIfNecessary(val); + for (std::size_t b = 0; b < N; ++b) { + splitArray[b * count + i] = reinterpret_cast(&val)[b]; + } + } +} + +/// \brief Reverse split encoding of elements +/// +/// Used to first unsplit a column, possibly storing elements in wider C++ types. Swaps bytes if necessary +template +static void CastSplitUnpack(void *destination, const void *source, std::size_t count) +{ + constexpr std::size_t N = sizeof(SourceT); + auto dst = reinterpret_cast(destination); + auto splitArray = reinterpret_cast(source); + for (std::size_t i = 0; i < count; ++i) { + SourceT val = 0; + for (std::size_t b = 0; b < N; ++b) { + reinterpret_cast(&val)[b] = splitArray[b * count + i]; + } + ByteSwapIfNecessary(val); + dst[i] = val; + } +} + +/// \brief Packing of columns with delta + split encoding +/// +/// Apply split encoding to delta-encoded values, currently used only for index columns +template +static void CastDeltaSplitPack(void *destination, const void *source, std::size_t count) +{ + constexpr std::size_t N = sizeof(DestT); + auto src = reinterpret_cast(source); + auto splitArray = reinterpret_cast(destination); + for (std::size_t i = 0; i < count; ++i) { + DestT val = (i == 0) ? src[0] : src[i] - src[i - 1]; + ByteSwapIfNecessary(val); + for (std::size_t b = 0; b < N; ++b) { + splitArray[b * count + i] = reinterpret_cast(&val)[b]; + } + } +} + +/// \brief Unsplit and unwind delta encoding +/// +/// Unsplit a column and reverse the delta encoding, currently used only for index columns +template +static void CastDeltaSplitUnpack(void *destination, const void *source, std::size_t count) +{ + constexpr std::size_t N = sizeof(SourceT); + auto splitArray = reinterpret_cast(source); + auto dst = reinterpret_cast(destination); + for (std::size_t i = 0; i < count; ++i) { + SourceT val = 0; + for (std::size_t b = 0; b < N; ++b) { + reinterpret_cast(&val)[b] = splitArray[b * count + i]; + } + ByteSwapIfNecessary(val); + dst[i] = (i == 0) ? val : dst[i - 1] + val; + } +} + +/// \brief Packing of columns with zigzag + split encoding +/// +/// Apply split encoding to zigzag-encoded values, used for signed integers +template +static void CastZigzagSplitPack(void *destination, const void *source, std::size_t count) +{ + using UDestT = std::make_unsigned_t; + constexpr std::size_t kNBitsDestT = sizeof(DestT) * 8; + constexpr std::size_t N = sizeof(DestT); + auto src = reinterpret_cast(source); + auto splitArray = reinterpret_cast(destination); + for (std::size_t i = 0; i < count; ++i) { + UDestT val = (static_cast(src[i]) << 1) ^ (static_cast(src[i]) >> (kNBitsDestT - 1)); + ByteSwapIfNecessary(val); + for (std::size_t b = 0; b < N; ++b) { + splitArray[b * count + i] = reinterpret_cast(&val)[b]; + } + } +} + +/// \brief Unsplit and unwind zigzag encoding +/// +/// Unsplit a column and reverse the zigzag encoding, used for signed integer columns +template +static void CastZigzagSplitUnpack(void *destination, const void *source, std::size_t count) +{ + using USourceT = std::make_unsigned_t; + constexpr std::size_t N = sizeof(SourceT); + auto splitArray = reinterpret_cast(source); + auto dst = reinterpret_cast(destination); + for (std::size_t i = 0; i < count; ++i) { + USourceT val = 0; + for (std::size_t b = 0; b < N; ++b) { + reinterpret_cast(&val)[b] = splitArray[b * count + i]; + } + ByteSwapIfNecessary(val); + dst[i] = static_cast((val >> 1) ^ -(static_cast(val) & 1)); + } +} + } // anonymous namespace namespace ROOT { @@ -61,56 +248,38 @@ namespace Detail { // clang-format off /** -\class ROOT::Experimental::Detail::RColumnElement +\class ROOT::Experimental::Detail::RColumnElementBase \ingroup NTuple -\brief A column element points either to the content of an RFieldValue or into a memory mapped page. +\brief A column element encapsulates the translation between basic C++ types and their column representation. -The content pointed to by fRawContent can be a single element or the first element of an array. Usually the on-disk element should map bitwise to the in-memory element. Sometimes that's not the case -though, for instance on big endian platforms and for exotic physical columns like 8 bit float. +though, for instance on big endian platforms or for bools. -This class does not provide protection around the raw pointer, fRawContent has to be managed correctly -by the user of this class. +There is a template specialization for every valid pair of C++ type and column representation. +These specialized child classes are responsible for overriding `Pack()` / `Unpack()` for packing / unpacking elements +as appropriate. */ // clang-format on class RColumnElementBase { protected: - /// Points to valid C++ data, either a single value or an array of values - void* fRawContent; - /// Size of the C++ value pointed to by fRawContent (not necessarily equal to the on-disk element size) + /// Size of the C++ value that corresponds to the on-disk element std::size_t fSize; + explicit RColumnElementBase(std::size_t size) : fSize(size) {} + public: - RColumnElementBase() - : fRawContent(nullptr) - , fSize(0) - {} - RColumnElementBase(void *rawContent, std::size_t size) : fRawContent(rawContent), fSize(size) - {} - RColumnElementBase(const RColumnElementBase &elemArray, std::size_t at) - : fRawContent(static_cast(elemArray.fRawContent) + elemArray.fSize * at) - , fSize(elemArray.fSize) - {} RColumnElementBase(const RColumnElementBase& other) = default; RColumnElementBase(RColumnElementBase&& other) = default; RColumnElementBase& operator =(const RColumnElementBase& other) = delete; RColumnElementBase& operator =(RColumnElementBase&& other) = default; virtual ~RColumnElementBase() = default; + /// If CppT == void, use the default C++ type for the given column type + template static std::unique_ptr Generate(EColumnType type); static std::size_t GetBitsOnStorage(EColumnType type); static std::string GetTypeName(EColumnType type); - /// Write one or multiple column elements into destination - void WriteTo(void *destination, std::size_t count) const { - std::memcpy(destination, fRawContent, fSize * count); - } - - /// Set the column element or an array of elements from the memory location source - void ReadFrom(void *source, std::size_t count) { - std::memcpy(fRawContent, source, fSize * count); - } - /// Derived, typed classes tell whether the on-storage layout is bitwise identical to the memory layout virtual bool IsMappable() const { R__ASSERT(false); return false; } virtual std::size_t GetBitsOnStorage() const { R__ASSERT(false); return 0; } @@ -127,9 +296,8 @@ public: std::memcpy(destination, source, count); } - void *GetRawContent() const { return fRawContent; } std::size_t GetSize() const { return fSize; } - std::size_t GetPackedSize(std::size_t nElements) const { return (nElements * GetBitsOnStorage() + 7) / 8; } + std::size_t GetPackedSize(std::size_t nElements = 1U) const { return (nElements * GetBitsOnStorage() + 7) / 8; } }; /** @@ -138,16 +306,18 @@ public: */ template class RColumnElementLE : public RColumnElementBase { +protected: + explicit RColumnElementLE(std::size_t size) : RColumnElementBase(size) {} + public: static constexpr bool kIsMappable = (R__LITTLE_ENDIAN == 1); - RColumnElementLE(void *rawContent, std::size_t size) : RColumnElementBase(rawContent, size) {} void Pack(void *dst, void *src, std::size_t count) const final { #if R__LITTLE_ENDIAN == 1 RColumnElementBase::Pack(dst, src, count); #else - CopyElementsBswap(dst, src, count); + CopyBswap(dst, src, count); #endif } void Unpack(void *dst, void *src, std::size_t count) const final @@ -155,22 +325,105 @@ public: #if R__LITTLE_ENDIAN == 1 RColumnElementBase::Unpack(dst, src, count); #else - CopyElementsBswap(dst, src, count); + CopyBswap(dst, src, count); #endif } -}; +}; // class RColumnElementLE + +/** + * Base class for columns storing elements of wider in-memory types, + * such as 64bit in-memory offsets to Index32 columns. + */ +template +class RColumnElementCastLE : public RColumnElementBase { +protected: + explicit RColumnElementCastLE(std::size_t size) : RColumnElementBase(size) {} + +public: + static constexpr bool kIsMappable = false; + + void Pack(void *dst, void *src, std::size_t count) const final { CastPack(dst, src, count); } + void Unpack(void *dst, void *src, std::size_t count) const final { CastUnpack(dst, src, count); } +}; // class RColumnElementCastLE + +/** + * Base class for split columns whose on-storage representation is little-endian. + * The implementation of `Pack` and `Unpack` takes care of splitting and, if necessary, byteswap. + * As part of the splitting, can also narrow down the type to NarrowT. + */ +template +class RColumnElementSplitLE : public RColumnElementBase { +protected: + explicit RColumnElementSplitLE(std::size_t size) : RColumnElementBase(size) {} + +public: + static constexpr bool kIsMappable = false; + + void Pack(void *dst, void *src, std::size_t count) const final { CastSplitPack(dst, src, count); } + void Unpack(void *dst, void *src, std::size_t count) const final { CastSplitUnpack(dst, src, count); } +}; // class RColumnElementSplitLE + +/** + * Base class for delta + split columns (index columns) whose on-storage representation is little-endian. + * The implementation of `Pack` and `Unpack` takes care of splitting and, if necessary, byteswap. + * As part of the encoding, can also narrow down the type to NarrowT. + */ +template +class RColumnElementDeltaSplitLE : public RColumnElementBase { +protected: + explicit RColumnElementDeltaSplitLE(std::size_t size) : RColumnElementBase(size) {} + +public: + static constexpr bool kIsMappable = false; + + void Pack(void *dst, void *src, std::size_t count) const final + { + CastDeltaSplitPack(dst, src, count); + } + void Unpack(void *dst, void *src, std::size_t count) const final + { + CastDeltaSplitUnpack(dst, src, count); + } +}; // class RColumnElementDeltaSplitLE /** - * Pairs of C++ type and column type, like float and EColumnType::kReal32 + * Base class for zigzag + split columns (signed integer columns) whose on-storage representation is little-endian. + * The implementation of `Pack` and `Unpack` takes care of splitting and, if necessary, byteswap. + * The NarrowT target type should be an signed integer, which can be smaller than the CppT source type. */ +template +class RColumnElementZigzagSplitLE : public RColumnElementBase { +protected: + explicit RColumnElementZigzagSplitLE(std::size_t size) : RColumnElementBase(size) {} + +public: + static constexpr bool kIsMappable = false; + + void Pack(void *dst, void *src, std::size_t count) const final + { + CastZigzagSplitPack(dst, src, count); + } + void Unpack(void *dst, void *src, std::size_t count) const final + { + CastZigzagSplitUnpack(dst, src, count); + } +}; // class RColumnElementZigzagSplitLE + +//////////////////////////////////////////////////////////////////////////////// +// Pairs of C++ type and column type, like float and EColumnType::kReal32 +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// Part 1: C++ type --> unknown column type +//////////////////////////////////////////////////////////////////////////////// + template class RColumnElement : public RColumnElementBase { public: - explicit RColumnElement(CppT* value) : RColumnElementBase(value, sizeof(CppT)) + RColumnElement() : RColumnElementBase(sizeof(CppT)) { - // Do not allow this template to be instantiated unless there is a specialization. The assert needs to depend - // on the template type or else the static_assert will always fire. - static_assert(sizeof(CppT) != sizeof(CppT), "No column mapping for this C++ type"); + throw RException(R__FAIL(std::string("internal error: no column mapping for this C++ type: ") + + typeid(CppT).name() + " --> " + GetTypeName(ColumnT))); } }; @@ -178,268 +431,142 @@ template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(bool); - explicit RColumnElement(bool *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(char); - explicit RColumnElement(char *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::int8_t); - explicit RColumnElement(std::int8_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::uint8_t); - explicit RColumnElement(std::uint8_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::int16_t); - explicit RColumnElement(std::int16_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::uint16_t); - explicit RColumnElement(std::uint16_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::int32_t); - explicit RColumnElement(std::int32_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::uint32_t); - explicit RColumnElement(std::uint32_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::int64_t); - explicit RColumnElement(std::int64_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(std::uint64_t); - explicit RColumnElement(std::uint64_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(float); - explicit RColumnElement(float *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(double); - explicit RColumnElement(double *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(ClusterSize_t); - explicit RColumnElement(ClusterSize_t *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; template <> class RColumnElement : public RColumnElementBase { public: static constexpr std::size_t kSize = sizeof(RColumnSwitch); - explicit RColumnElement(RColumnSwitch *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} }; -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(float); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(float *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(double); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(double *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(std::int8_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::int8_t *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(std::uint8_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::uint8_t *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(std::int8_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::int8_t *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(std::uint8_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::uint8_t *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::int16_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::int16_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::uint16_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::uint16_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::int32_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::int32_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::uint32_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::uint32_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::int64_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::int64_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(std::uint64_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(std::uint64_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; - -template <> -class RColumnElement : public RColumnElementLE { -public: - static constexpr std::size_t kSize = sizeof(ROOT::Experimental::ClusterSize_t); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(ClusterSize_t *value) : RColumnElementLE(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; +//////////////////////////////////////////////////////////////////////////////// +// Part 2: C++ type --> supported column representations, +// ordered by C++ type +//////////////////////////////////////////////////////////////////////////////// template <> class RColumnElement : public RColumnElementBase { public: static constexpr bool kIsMappable = false; static constexpr std::size_t kSize = sizeof(ROOT::Experimental::RColumnSwitch); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(RColumnSwitch *value) : RColumnElementBase(value, kSize) {} + static constexpr std::size_t kBitsOnStorage = 64; + RColumnElement() : RColumnElementBase(kSize) {} bool IsMappable() const final { return kIsMappable; } std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } - void Pack(void *dst, void *src, std::size_t count) const final; - void Unpack(void *dst, void *src, std::size_t count) const final; -}; - -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(char); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(char *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } -}; + void Pack(void *dst, void *src, std::size_t count) const final + { + auto srcArray = reinterpret_cast(src); + auto uint64Array = reinterpret_cast(dst); + for (std::size_t i = 0; i < count; ++i) { + uint64Array[i] = + (static_cast(srcArray[i].GetTag()) << 44) | (srcArray[i].GetIndex() & 0x0fffffffffff); +#if R__LITTLE_ENDIAN == 0 + uint64Array[i] = RByteSwap<8>::bswap(uint64Array[i]); +#endif + } + } -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = true; - static constexpr std::size_t kSize = sizeof(char); - static constexpr std::size_t kBitsOnStorage = kSize * 8; - explicit RColumnElement(char *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } + void Unpack(void *dst, void *src, std::size_t count) const final + { + auto uint64Array = reinterpret_cast(src); + auto dstArray = reinterpret_cast(dst); + for (std::size_t i = 0; i < count; ++i) { +#if R__LITTLE_ENDIAN == 1 + const auto value = uint64Array[i]; +#else + const auto value = RByteSwap<8>::bswap(uint64Array[i]); +#endif + dstArray[i] = ROOT::Experimental::RColumnSwitch( + ClusterSize_t{static_cast(value & 0x0fffffffffff)}, (value >> 44)); + } + } }; template <> @@ -448,7 +575,7 @@ public: static constexpr bool kIsMappable = false; static constexpr std::size_t kSize = sizeof(bool); static constexpr std::size_t kBitsOnStorage = 1; - explicit RColumnElement(bool *value) : RColumnElementBase(value, kSize) {} + RColumnElement() : RColumnElementBase(kSize) {} bool IsMappable() const final { return kIsMappable; } std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } @@ -456,19 +583,152 @@ public: void Unpack(void *dst, void *src, std::size_t count) const final; }; -template <> -class RColumnElement : public RColumnElementBase { -public: - static constexpr bool kIsMappable = false; - static constexpr std::size_t kSize = sizeof(std::int64_t); - static constexpr std::size_t kBitsOnStorage = 32; - explicit RColumnElement(std::int64_t *value) : RColumnElementBase(value, kSize) {} - bool IsMappable() const final { return kIsMappable; } - std::size_t GetBitsOnStorage() const final { return kBitsOnStorage; } +#define __RCOLUMNELEMENT_SPEC_BODY(CppT, BaseT, BitsOnStorage) \ + static constexpr std::size_t kSize = sizeof(CppT); \ + static constexpr std::size_t kBitsOnStorage = BitsOnStorage; \ + RColumnElement() : BaseT(kSize) {} \ + bool IsMappable() const final \ + { \ + return kIsMappable; \ + } \ + std::size_t GetBitsOnStorage() const final \ + { \ + return kBitsOnStorage; \ + } +/// These macros are used to declare `RColumnElement` template specializations below. Additional arguments can be used +/// to forward template parameters to the base class, e.g. +/// ``` +/// DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kInt32, 32, +/// RColumnElementCastLE, ); +/// ``` +#define DECLARE_RCOLUMNELEMENT_SPEC(CppT, ColumnT, BitsOnStorage, BaseT, ...) \ + template <> \ + class RColumnElement : public BaseT __VA_ARGS__ { \ + public: \ + __RCOLUMNELEMENT_SPEC_BODY(CppT, BaseT, BitsOnStorage) \ + } +#define DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(CppT, ColumnT, BitsOnStorage) \ + template <> \ + class RColumnElement : public RColumnElementBase { \ + public: \ + static constexpr bool kIsMappable = true; \ + __RCOLUMNELEMENT_SPEC_BODY(CppT, RColumnElementBase, BitsOnStorage) \ + } - void Pack(void *dst, void *src, std::size_t count) const final; - void Unpack(void *dst, void *src, std::size_t count) const final; -}; +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(char, EColumnType::kByte, 8); +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(char, EColumnType::kChar, 8); + +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::int8_t, EColumnType::kInt8, 8); +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::int8_t, EColumnType::kUInt8, 8); +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::int8_t, EColumnType::kByte, 8); + +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::uint8_t, EColumnType::kUInt8, 8); +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::uint8_t, EColumnType::kInt8, 8); +DECLARE_RCOLUMNELEMENT_SPEC_SIMPLE(std::uint8_t, EColumnType::kByte, 8); + +DECLARE_RCOLUMNELEMENT_SPEC(std::int16_t, EColumnType::kInt16, 16, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int16_t, EColumnType::kUInt16, 16, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int16_t, EColumnType::kSplitInt16, 16, RColumnElementZigzagSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int16_t, EColumnType::kSplitUInt16, 16, RColumnElementSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(std::uint16_t, EColumnType::kUInt16, 16, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint16_t, EColumnType::kInt16, 16, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint16_t, EColumnType::kSplitUInt16, 16, RColumnElementSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint16_t, EColumnType::kSplitInt16, 16, RColumnElementZigzagSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(std::int32_t, EColumnType::kInt32, 32, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int32_t, EColumnType::kUInt32, 32, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int32_t, EColumnType::kSplitInt32, 32, RColumnElementZigzagSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int32_t, EColumnType::kSplitUInt32, 32, RColumnElementSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(std::uint32_t, EColumnType::kUInt32, 32, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint32_t, EColumnType::kInt32, 32, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint32_t, EColumnType::kSplitUInt32, 32, RColumnElementSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint32_t, EColumnType::kSplitInt32, 32, RColumnElementZigzagSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kInt64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kUInt64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kSplitInt64, 64, RColumnElementZigzagSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kSplitUInt64, 64, RColumnElementSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kInt32, 32, RColumnElementCastLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kUInt32, 32, RColumnElementCastLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kSplitInt32, 32, RColumnElementZigzagSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::int64_t, EColumnType::kSplitUInt32, 32, RColumnElementSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(std::uint64_t, EColumnType::kUInt64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint64_t, EColumnType::kInt64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint64_t, EColumnType::kSplitUInt64, 64, RColumnElementSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(std::uint64_t, EColumnType::kSplitInt64, 64, RColumnElementZigzagSplitLE, + ); + +DECLARE_RCOLUMNELEMENT_SPEC(float, EColumnType::kReal32, 32, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(float, EColumnType::kSplitReal32, 32, RColumnElementSplitLE, ); + +DECLARE_RCOLUMNELEMENT_SPEC(double, EColumnType::kReal64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(double, EColumnType::kSplitReal64, 64, RColumnElementSplitLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(double, EColumnType::kReal32, 32, RColumnElementCastLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(double, EColumnType::kSplitReal32, 32, RColumnElementSplitLE, ); + +DECLARE_RCOLUMNELEMENT_SPEC(ClusterSize_t, EColumnType::kIndex64, 64, RColumnElementLE, ); +DECLARE_RCOLUMNELEMENT_SPEC(ClusterSize_t, EColumnType::kIndex32, 32, RColumnElementCastLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(ClusterSize_t, EColumnType::kSplitIndex64, 64, RColumnElementDeltaSplitLE, + ); +DECLARE_RCOLUMNELEMENT_SPEC(ClusterSize_t, EColumnType::kSplitIndex32, 32, RColumnElementDeltaSplitLE, + ); + +template +std::unique_ptr RColumnElementBase::Generate(EColumnType type) +{ + switch (type) { + case EColumnType::kIndex64: return std::make_unique>(); + case EColumnType::kIndex32: return std::make_unique>(); + case EColumnType::kSwitch: return std::make_unique>(); + case EColumnType::kByte: return std::make_unique>(); + case EColumnType::kChar: return std::make_unique>(); + case EColumnType::kBit: return std::make_unique>(); + case EColumnType::kReal64: return std::make_unique>(); + case EColumnType::kReal32: return std::make_unique>(); + case EColumnType::kInt64: return std::make_unique>(); + case EColumnType::kUInt64: return std::make_unique>(); + case EColumnType::kInt32: return std::make_unique>(); + case EColumnType::kUInt32: return std::make_unique>(); + case EColumnType::kInt16: return std::make_unique>(); + case EColumnType::kUInt16: return std::make_unique>(); + case EColumnType::kInt8: return std::make_unique>(); + case EColumnType::kUInt8: return std::make_unique>(); + case EColumnType::kSplitIndex64: return std::make_unique>(); + case EColumnType::kSplitIndex32: return std::make_unique>(); + case EColumnType::kSplitReal64: return std::make_unique>(); + case EColumnType::kSplitReal32: return std::make_unique>(); + case EColumnType::kSplitInt64: return std::make_unique>(); + case EColumnType::kSplitUInt64: return std::make_unique>(); + case EColumnType::kSplitInt32: return std::make_unique>(); + case EColumnType::kSplitUInt32: return std::make_unique>(); + case EColumnType::kSplitInt16: return std::make_unique>(); + case EColumnType::kSplitUInt16: return std::make_unique>(); + default: R__ASSERT(false); + } + // never here + return nullptr; +} + +template <> +std::unique_ptr RColumnElementBase::Generate(EColumnType type); } // namespace Detail } // namespace Experimental diff --git a/tree/ntuple/v7/inc/ROOT/RColumnModel.hxx b/tree/ntuple/v7/inc/ROOT/RColumnModel.hxx index 9a1f9db8fd358..19430936746cb 100644 --- a/tree/ntuple/v7/inc/ROOT/RColumnModel.hxx +++ b/tree/ntuple/v7/inc/ROOT/RColumnModel.hxx @@ -31,14 +31,22 @@ namespace Experimental { More complex types, such as classes, get translated into columns of such simple types by the RField. New types need to be accounted for in RColumnElementBase::Generate() and RColumnElementBase::GetBitsOnStorage(), too. +When changed, remember to update + - RColumnElement::Generate() + - RColumnElement::GetBitsOnStorage() + - RColumnElement::GetTypeName() + - RColumnElement template specializations / packing & unpacking + - If necessary, endianess handling for the packing + unit test in ntuple_endian + - RNTupleSerializer::[Des|S]erializeColumnType */ // clang-format on enum class EColumnType { kUnknown = 0, - // type for root columns of (nested) collections; 32bit integers that count relative to the current cluster - kIndex, - // 64 bit column that uses the lower 32bits as kIndex and the higher 32bits as a dispatch tag; used, e.g., - // in order to serialize std::variant + // type for root columns of (nested) collections; offsets are relative to the current cluster + kIndex64, + kIndex32, + // 64 bit column that uses the lower 44 bits like kIndex64, higher 20 bits are a dispatch tag to a column ID; + // used to serialize std::variant. kSwitch, kByte, kChar, @@ -47,9 +55,23 @@ enum class EColumnType { kReal32, kReal16, kInt64, + kUInt64, kInt32, + kUInt32, kInt16, + kUInt16, kInt8, + kUInt8, + kSplitIndex64, + kSplitIndex32, + kSplitReal64, + kSplitReal32, + kSplitInt64, + kSplitUInt64, + kSplitInt32, + kSplitUInt32, + kSplitInt16, + kSplitUInt16, kMax, }; @@ -57,7 +79,7 @@ enum class EColumnType { /** \class ROOT::Experimental::RColumnModel \ingroup NTuple -\brief Holds the static meta-data of a column in a tree +\brief Holds the static meta-data of an RNTuple column */ // clang-format on class RColumnModel { @@ -67,6 +89,10 @@ private: public: RColumnModel() : fType(EColumnType::kUnknown), fIsSorted(false) {} + explicit RColumnModel(EColumnType type) + : fType(type), fIsSorted(type == EColumnType::kIndex32 || type == EColumnType::kSplitIndex32) + { + } RColumnModel(EColumnType type, bool isSorted) : fType(type), fIsSorted(isSorted) {} EColumnType GetType() const { return fType; } @@ -75,6 +101,7 @@ public: bool operator ==(const RColumnModel &other) const { return (fType == other.fType) && (fIsSorted == other.fIsSorted); } + bool operator!=(const RColumnModel &other) const { return !(other == *this); } }; } // namespace Experimental diff --git a/tree/ntuple/v7/inc/ROOT/RDaos.hxx b/tree/ntuple/v7/inc/ROOT/RDaos.hxx index 69ee9ba99d54e..ef27553f55466 100644 --- a/tree/ntuple/v7/inc/ROOT/RDaos.hxx +++ b/tree/ntuple/v7/inc/ROOT/RDaos.hxx @@ -22,6 +22,7 @@ #include +#include #include #include #include @@ -47,13 +48,13 @@ struct RDaosEventQueue { /// \brief Sets event barrier for a given parent event and waits for the completion of all children launched before /// the barrier (must have at least one child). /// \return 0 on success; a DAOS error code otherwise (< 0). - int WaitOnParentBarrier(daos_event_t *ev_ptr); + static int WaitOnParentBarrier(daos_event_t *ev_ptr); /// \brief Reserve event in queue, optionally tied to a parent event. /// \return 0 on success; a DAOS error code otherwise (< 0). - int InitializeEvent(daos_event_t *ev_ptr, daos_event_t *parent_ptr = nullptr); + int InitializeEvent(daos_event_t *ev_ptr, daos_event_t *parent_ptr = nullptr) const; /// \brief Release event data from queue. /// \return 0 on success; a DAOS error code otherwise (< 0). - int FinalizeEvent(daos_event_t *ev_ptr); + static int FinalizeEvent(daos_event_t *ev_ptr); }; class RDaosContainer; @@ -107,22 +108,30 @@ public: static constexpr std::size_t kOCNameMaxLength = 64; }; + /// \brief Contains an attribute key and the associated IOVs for a single scatter-gather I/O request. + struct RAkeyRequest { + AttributeKey_t fAkey{}; + std::vector fIovs{}; + + RAkeyRequest(const AttributeKey_t a, const std::vector &iovs) : fAkey(a), fIovs(iovs){}; + RAkeyRequest(const AttributeKey_t a, std::vector &&iovs) : fAkey(a), fIovs(std::move(iovs)){}; + }; + /// \brief Contains required information for a single fetch/update operation. struct FetchUpdateArgs { FetchUpdateArgs() = default; FetchUpdateArgs(const FetchUpdateArgs &) = delete; - FetchUpdateArgs(FetchUpdateArgs &&fua); - FetchUpdateArgs(DistributionKey_t d, std::span as, std::span vs, - bool is_async = false); + FetchUpdateArgs(FetchUpdateArgs &&fua) noexcept; + FetchUpdateArgs(DistributionKey_t d, std::span rs, bool is_async = false); FetchUpdateArgs &operator=(const FetchUpdateArgs &) = delete; daos_event_t *GetEventPointer(); /// \brief A `daos_key_t` is a type alias of `d_iov_t`. This type stores a pointer and a length. /// In order for `fDistributionKey` to point to memory that we own, `fDkey` holds the distribution key. - /// `fAkeys` and `fIovs` are sequential containers assumed to remain valid throughout the fetch/update operation. DistributionKey_t fDkey{}; - std::span fAkeys{}; - std::span fIovs{}; + /// \brief `fRequests` is a sequential container assumed to remain valid throughout the fetch/update operation, + /// holding a list of `RAkeyRequest`-typed elements. + std::span fRequests{}; /// \brief The distribution key, as used by the `daos_obj_{fetch,update}` functions. daos_key_t fDistributionKey{}; @@ -157,7 +166,6 @@ public: struct ROidDkeyPair { daos_obj_id_t oid{}; DistributionKey_t dkey{}; - ROidDkeyPair() = default; inline bool operator==(const ROidDkeyPair &other) const { @@ -177,22 +185,46 @@ public: }; }; - /// \brief Describes a read/write operation on multiple objects; see the `ReadV`/`WriteV` functions. + /// \brief Describes a read/write operation on multiple attribute keys under the same object ID and distribution key, + /// see the `ReadV`/`WriteV` functions. struct RWOperation { RWOperation() = default; - RWOperation(daos_obj_id_t o, DistributionKey_t d, const std::vector &as, - const std::vector &vs) - : fOid(o), fDistributionKey(d), fAttributeKeys(as), fIovs(vs){}; - RWOperation(ROidDkeyPair &k) : fOid(k.oid), fDistributionKey(k.dkey){}; + RWOperation(daos_obj_id_t o, DistributionKey_t d, std::vector &&rs) + : fOid(o), fDistributionKey(d), fDataRequests(std::move(rs)) + { + for (unsigned i = 0; i < fDataRequests.size(); i++) + fIndices.emplace(fDataRequests[i].fAkey, i); + }; + explicit RWOperation(ROidDkeyPair &k) : fOid(k.oid), fDistributionKey(k.dkey){}; daos_obj_id_t fOid{}; DistributionKey_t fDistributionKey{}; - std::vector fAttributeKeys{}; - std::vector fIovs{}; + std::vector fDataRequests{}; + std::unordered_map fIndices{}; - void insert(AttributeKey_t attr, const d_iov_t &vec) + void Insert(AttributeKey_t attr, const d_iov_t &iov) { - fAttributeKeys.emplace_back(attr); - fIovs.emplace_back(vec); + auto [it, ret] = fIndices.emplace(attr, fDataRequests.size()); + unsigned attrIndex = it->second; + + if (attrIndex == fDataRequests.size()) { + fDataRequests.emplace_back(attr, std::initializer_list{iov}); + } else { + fDataRequests[attrIndex].fIovs.emplace_back(iov); + } + } + + void Insert(AttributeKey_t attr, std::vector &iovs) + { + auto [it, ret] = fIndices.emplace(attr, fDataRequests.size()); + unsigned attrIndex = it->second; + + if (attrIndex == fDataRequests.size()) { + fDataRequests.emplace_back(attr, iovs); + } else { + fDataRequests[attrIndex].fIovs.insert(std::end(fDataRequests[attrIndex].fIovs), + std::make_move_iterator(std::begin(iovs)), + std::make_move_iterator(std::end(iovs))); + } } }; diff --git a/tree/ntuple/v7/inc/ROOT/REntry.hxx b/tree/ntuple/v7/inc/ROOT/REntry.hxx index 68885a61e22fc..1cf02dbfd068b 100644 --- a/tree/ntuple/v7/inc/ROOT/REntry.hxx +++ b/tree/ntuple/v7/inc/ROOT/REntry.hxx @@ -18,7 +18,6 @@ #include #include -#include #include #include @@ -46,29 +45,23 @@ class REntry { /// The entry must be linked to a specific model (or one if its clones), identified by a model ID std::uint64_t fModelId = 0; /// Corresponds to the top-level fields of the linked model - std::vector fValues; + std::vector fValues; /// The objects involed in serialization and deserialization might be used long after the entry is gone: /// hence the shared pointer std::vector> fValuePtrs; - /// Points into fValues and indicates the values that are owned by the entry and need to be destructed - std::vector fManagedValues; // Creation of entries is done by the RNTupleModel class REntry() = default; explicit REntry(std::uint64_t modelId) : fModelId(modelId) {} - /// Adds a value whose storage is managed by the entry - void AddValue(const Detail::RFieldValue& value); - - /// Adds a value whose storage is _not_ managed by the entry - void CaptureValue(const Detail::RFieldValue& value); + void AddValue(Detail::RFieldBase::RValue &&value); /// While building the entry, adds a new value to the list and return the value's shared pointer template std::shared_ptr AddValue(RField* field, ArgsT&&... args) { auto ptr = std::make_shared(std::forward(args)...); - fValues.emplace_back(Detail::RFieldValue(field->CaptureValue(ptr.get()))); + fValues.emplace_back(field->BindValue(ptr.get())); fValuePtrs.emplace_back(ptr); return ptr; } @@ -80,26 +73,27 @@ public: REntry &operator=(const REntry &other) = delete; REntry(REntry &&other) = default; REntry &operator=(REntry &&other) = default; - ~REntry(); + ~REntry() = default; void CaptureValueUnsafe(std::string_view fieldName, void *where); - Detail::RFieldValue GetValue(std::string_view fieldName) const + template + T *Get(std::string_view fieldName) const { for (auto& v : fValues) { - if (v.GetField()->GetName() == fieldName) - return v; + if (v.GetField()->GetName() == fieldName) { + R__ASSERT(v.GetField()->GetType() == RField::TypeName()); + return v.Get(); + } } throw RException(R__FAIL("invalid field name: " + std::string(fieldName))); } - template - T *Get(std::string_view fieldName) const + void *GetRawPtr(std::string_view fieldName) const { for (auto& v : fValues) { if (v.GetField()->GetName() == fieldName) { - R__ASSERT(v.GetField()->GetType() == RField::TypeName()); - return v.Get(); + return v.GetRawPtr(); } } throw RException(R__FAIL("invalid field name: " + std::string(fieldName))); diff --git a/tree/ntuple/v7/inc/ROOT/RField.hxx b/tree/ntuple/v7/inc/ROOT/RField.hxx index 2cc20865cd41e..4bb6ab1d2b5dd 100644 --- a/tree/ntuple/v7/inc/ROOT/RField.hxx +++ b/tree/ntuple/v7/inc/ROOT/RField.hxx @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -31,11 +30,14 @@ #include #include +#include #include #include #include #include #include +#include +#include #include #include #include @@ -44,8 +46,12 @@ #include class TClass; +class TEnum; namespace ROOT { + +class TSchemaRule; + namespace Experimental { class RCollectionField; @@ -64,7 +70,7 @@ class RPageStorage; // clang-format off /** -\class ROOT::Experimental::RFieldBase +\class ROOT::Experimental::Detail::RFieldBase \ingroup NTuple \brief A field translates read and write calls from/to underlying columns to/from tree values @@ -77,9 +83,10 @@ The field knows based on its type and the field name the type(s) and name(s) of class RFieldBase { friend class ROOT::Experimental::RCollectionField; // to move the fields from the collection model friend struct ROOT::Experimental::Internal::RFieldCallbackInjector; // used for unit tests - using ReadCallback_t = std::function; + using ReadCallback_t = std::function; public: + static constexpr std::uint32_t kInvalidTypeVersion = -1U; /// No constructor needs to be called, i.e. any bit pattern in the allocated memory represents a valid type /// A trivially constructible field has a no-op GenerateValue() implementation static constexpr int kTraitTriviallyConstructible = 0x01; @@ -91,6 +98,178 @@ public: /// Shorthand for types that are both trivially constructible and destructible static constexpr int kTraitTrivialType = kTraitTriviallyConstructible | kTraitTriviallyDestructible; + using ColumnRepresentation_t = std::vector; + + /// During its lifetime, a field undergoes the following possible state transitions: + /// + /// [*] --> Unconnected --> ConnectedToSink ---- + /// | | | + /// | --> ConnectedToSource ---> [*] + /// | | + /// ------------------------------- + enum class EState { kUnconnected, kConnectedToSink, kConnectedToSource }; + + /// Some fields have multiple possible column representations, e.g. with or without split encoding. + /// All column representations supported for writing also need to be supported for reading. In addition, + /// fields can support extra column representations for reading only, e.g. a 64bit integer reading from a + /// 32bit column. + /// The defined column representations must be supported by corresponding column packing/unpacking implementations, + /// i.e. for the example above, the unpacking of 32bit ints to 64bit pages must be implemented in RColumnElement.hxx + class RColumnRepresentations { + public: + using TypesList_t = std::vector; + RColumnRepresentations(); + RColumnRepresentations(const TypesList_t &serializationTypes, const TypesList_t &deserializationExtraTypes); + + /// The first column list from fSerializationTypes is the default for writing. + const ColumnRepresentation_t &GetSerializationDefault() const { return fSerializationTypes[0]; } + const TypesList_t &GetSerializationTypes() const { return fSerializationTypes; } + const TypesList_t &GetDeserializationTypes() const { return fDeserializationTypes; } + + private: + TypesList_t fSerializationTypes; + /// The union of the serialization types and the deserialization extra types. Duplicates the serialization types + /// list but the benenfit is that GetDeserializationTypes does not need to compile the list. + TypesList_t fDeserializationTypes; + }; // class RColumnRepresentations + + /// Points to an object with RNTuple I/O support and keeps a pointer to the corresponding field. + /// Only fields can create RValue objects through generation, binding or splitting. + /// An RValue object can be owning or non-owning. Only RField::GenerateValue creates owning RValues. + /// Owning RValues destroy and free the object upon destruction. + class RValue { + friend class RFieldBase; + + private: + RFieldBase *fField = nullptr; ///< The field that created the RValue + /// Created by RFieldBase::GenerateValue() or a non-owning pointer from SplitValue() or BindValue() + void *fObjPtr = nullptr; + bool fIsOwning = false; ///< If true, fObjPtr is destroyed in the destructor + + RValue(RFieldBase *field, void *objPtr, bool isOwning) : fField(field), fObjPtr(objPtr), fIsOwning(isOwning) {} + + void DestroyIfOwning() + { + if (fIsOwning) + fField->DestroyValue(fObjPtr); + } + + public: + RValue(const RValue &) = delete; + RValue &operator=(const RValue &) = delete; + RValue(RValue &&other) : fField(other.fField), fObjPtr(other.fObjPtr) { std::swap(fIsOwning, other.fIsOwning); } + RValue &operator=(RValue &&other) + { + DestroyIfOwning(); + fIsOwning = false; + std::swap(fField, other.fField); + std::swap(fObjPtr, other.fObjPtr); + std::swap(fIsOwning, other.fIsOwning); + return *this; + } + ~RValue() { DestroyIfOwning(); } + + RValue GetNonOwningCopy() { return RValue(fField, fObjPtr, false); } + + std::size_t Append() { return fField->Append(fObjPtr); } + void Read(NTupleSize_t globalIndex) { fField->Read(globalIndex, fObjPtr); } + void Read(const RClusterIndex &clusterIndex) { fField->Read(clusterIndex, fObjPtr); } + + template + T *Get() const + { + return static_cast(fObjPtr); + } + void *GetRawPtr() const { return fObjPtr; } + RFieldBase *GetField() const { return fField; } + }; // class RValue + + /// Similar to RValue but manages an array of consecutive values. Bulks have to come from the same cluster. + /// Bulk I/O works with two bit masks: the mask of all the available entries in the current bulk and the mask + /// of the required entries in a bulk read. The idea is that a single bulk may serve multiple read operations + /// on the same range, where in each read operation a different subset of values is required. + /// The memory of the value array is managed by the RBulk class. + class RBulk { + private: + friend class RFieldBase; + + RFieldBase *fField = nullptr; ///< The field that created the array of values + void *fValues = nullptr; ///< Pointer to the start of the array + std::size_t fValueSize = 0; ///< Cached copy of fField->GetValueSize() + std::size_t fCapacity = 0; ///< The size of the array memory block in number of values + std::size_t fSize = 0; ///< The number of available values in the array (provided their mask is set) + std::unique_ptr fMaskAvail; ///< Masks invalid values in the array + std::size_t fNValidValues = 0; ///< The sum of non-zero elements in the fMask + RClusterIndex fFirstIndex; ///< Index of the first value of the array + /// Reading arrays of complex values may require additional memory, for instance for the elements of + /// arrays of vectors. A pointer to the fAuxData array is passed to the field's BulkRead method. + /// The RBulk class does not modify the array in-between calls to the field's BulkRead method. + std::vector fAuxData; + + void ReleaseValues(); + /// Sets a new range for the bulk. If there is enough capacity, the fValues array will be reused. + /// Otherwise a new array is allocated. After reset, fMaskAvail is false for all values. + void Reset(const RClusterIndex &firstIndex, std::size_t size); + void CountValidValues(); + + bool ContainsRange(const RClusterIndex &firstIndex, std::size_t size) const + { + if (firstIndex.GetClusterId() != fFirstIndex.GetClusterId()) + return false; + return (firstIndex.GetIndex() >= fFirstIndex.GetIndex()) && + ((firstIndex.GetIndex() + size) <= (fFirstIndex.GetIndex() + fSize)); + } + + void *GetValuePtrAt(std::size_t idx) const + { + return reinterpret_cast(fValues) + idx * fValueSize; + } + + explicit RBulk(RFieldBase *field) : fField(field), fValueSize(field->GetValueSize()) {} + + public: + ~RBulk(); + RBulk(const RBulk &) = delete; + RBulk &operator=(const RBulk &) = delete; + RBulk(RBulk &&other); + RBulk &operator=(RBulk &&other); + + /// Reads 'size' values from the associated field, starting from 'firstIndex'. Note that the index is given + /// relative to a certain cluster. The return value points to the array of read objects. + /// The 'maskReq' parameter is a bool array of at least 'size' elements. Only objects for which the mask is + /// true are guaranteed to be read in the returned value array. + void *ReadBulk(const RClusterIndex &firstIndex, const bool *maskReq, std::size_t size) + { + if (!ContainsRange(firstIndex, size)) + Reset(firstIndex, size); + + // We may read a sub range of the currently available range + auto offset = firstIndex.GetIndex() - fFirstIndex.GetIndex(); + + if (fNValidValues == fSize) + return GetValuePtrAt(offset); + + RBulkSpec bulkSpec; + bulkSpec.fFirstIndex = firstIndex; + bulkSpec.fCount = size; + bulkSpec.fMaskReq = maskReq; + bulkSpec.fMaskAvail = &fMaskAvail[offset]; + bulkSpec.fValues = GetValuePtrAt(offset); + bulkSpec.fAuxData = &fAuxData; + auto nRead = fField->ReadBulk(bulkSpec); + if (nRead == RBulkSpec::kAllSet) { + if ((offset == 0) && (size == fSize)) { + fNValidValues = fSize; + } else { + CountValidValues(); + } + } else { + fNValidValues += nRead; + } + return GetValuePtrAt(offset); + } + }; // class RBulk + private: /// The field name relative to its parent field std::string fName; @@ -108,8 +287,44 @@ private: DescriptorId_t fOnDiskId = kInvalidDescriptorId; /// Free text set by the user std::string fDescription; + /// Changed by ConnectTo[Sink,Source], reset by Clone() + EState fState = EState::kUnconnected; + + void InvokeReadCallbacks(void *target) + { + for (const auto &func : fReadCallbacks) + func(target); + } + + /// Translate an entry index to a column element index of the principal column and viceversa. These functions + /// take into account the role and number of repetitions on each level of the field hierarchy as follows: + /// - Top level fields: element index == entry index + /// - Record fields propagate their principal column index to the principal columns of direct descendant fields + /// - Collection and variant fields set the principal column index of their childs to 0 + /// + /// The column element index also depends on the number of repetitions of each field in the hierarchy, e.g., given a + /// field with type `std::array, 2>`, this function returns 8 for the inner-most field. + NTupleSize_t EntryToColumnElementIndex(NTupleSize_t globalIndex) const; protected: + /// Input parameter to ReadBulk() and ReadBulkImpl(). See RBulk class for more information + struct RBulkSpec { + /// As a return value of ReadBulk and ReadBulkImpl(), indicates that the full bulk range was read + /// independent of the provided masks. + static const std::size_t kAllSet = std::size_t(-1); + + RClusterIndex fFirstIndex; ///< Start of the bulk range + std::size_t fCount = 0; ///< Size of the bulk range + /// A bool array of size fCount, indicating the required values in the requested range + const bool *fMaskReq = nullptr; + bool *fMaskAvail = nullptr; ///< A bool array of size fCount, indicating the valid values in fValues + /// The destination area, which has to be a big enough array of valid objects of the correct type + void *fValues = nullptr; + /// Reference to memory owned by the RBulk class. The field implementing BulkReadImpl may use fAuxData + /// as memory that stays persistent between calls. + std::vector *fAuxData = nullptr; + }; + /// Collections and classes own sub fields std::vector> fSubFields; /// Sub fields point to their mother field @@ -122,31 +337,127 @@ protected: std::vector> fColumns; /// Properties of the type that allow for optimizations of collections of that type int fTraits = 0; + /// A typedef or using name that was used when creating the field + std::string fTypeAlias; /// List of functions to be called after reading a value std::vector fReadCallbacks; - + /// C++ type version cached from the descriptor after a call to `ConnectPageSource()` + std::uint32_t fOnDiskTypeVersion = kInvalidTypeVersion; + /// Points into the static vector GetColumnRepresentations().GetSerializationTypes() when SetColumnRepresentative + /// is called. Otherwise GetColumnRepresentative returns the default representation. + const ColumnRepresentation_t *fColumnRepresentative = nullptr; + + /// Implementations in derived classes should return a static RColumnRepresentations object. The default + /// implementation does not attach any columns to the field. + virtual const RColumnRepresentations &GetColumnRepresentations() const; /// Creates the backing columns corresponsing to the field type for writing virtual void GenerateColumnsImpl() = 0; /// Creates the backing columns corresponsing to the field type for reading. /// The method should to check, using the page source and fOnDiskId, if the column types match /// and throw if they don't. virtual void GenerateColumnsImpl(const RNTupleDescriptor &desc) = 0; + /// Returns the on-disk column types found in the provided descriptor for fOnDiskId. Throws an exception if the types + /// don't match any of the deserialization types from GetColumnRepresentations(). + const ColumnRepresentation_t &EnsureCompatibleColumnTypes(const RNTupleDescriptor &desc) const; + /// When connecting a field to a page sink, the field's default column representation is subject + /// to adjustment according to the write options. E.g., if compression is turned off, encoded columns + /// are changed to their unencoded counterparts. + void AutoAdjustColumnTypes(const RNTupleWriteOptions &options); /// Called by Clone(), which additionally copies the on-disk ID virtual std::unique_ptr CloneImpl(std::string_view newName) const = 0; + /// Constructs value in a given location of size at least GetValueSize(). Called by the base class' GenerateValue(). + virtual void GenerateValue(void *where) const = 0; + /// Releases the resources acquired during GenerateValue (memory and constructor) + /// This implementation works for types with a trivial destructor and should be overwritten otherwise. + virtual void DestroyValue(void *objPtr, bool dtorOnly = false) const; + /// Allow derived classes to call GenerateValue(void *) and DestroyValue on other (sub) fields. + static void CallGenerateValueOn(const RFieldBase &other, void *where) { other.GenerateValue(where); } + static void CallDestroyValueOn(const RFieldBase &other, void *objPtr, bool dtorOnly = false) + { + other.DestroyValue(objPtr, dtorOnly); + } + /// Operations on values of complex types, e.g. ones that involve multiple columns or for which no direct /// column type exists. - virtual std::size_t AppendImpl(const RFieldValue &value); - virtual void ReadGlobalImpl(NTupleSize_t globalIndex, RFieldValue *value); - virtual void ReadInClusterImpl(const RClusterIndex &clusterIndex, RFieldValue *value) { - ReadGlobalImpl(fPrincipalColumn->GetGlobalIndex(clusterIndex), value); + virtual std::size_t AppendImpl(const void *from); + virtual void ReadGlobalImpl(NTupleSize_t globalIndex, void *to); + virtual void ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) + { + ReadGlobalImpl(fPrincipalColumn->GetGlobalIndex(clusterIndex), to); + } + + /// Write the given value into columns. The value object has to be of the same type as the field. + /// Returns the number of uncompressed bytes written. + std::size_t Append(const void *from) + { + if (~fTraits & kTraitMappable) + return AppendImpl(from); + + fPrincipalColumn->Append(from); + return fPrincipalColumn->GetElement()->GetPackedSize(); + } + + /// Populate a single value with data from the field. The memory location pointed to by to needs to be of the + /// fitting type. The fast path is conditioned by the field qualifying as simple, i.e. maps as-is + /// to a single column and has no read callback. + void Read(NTupleSize_t globalIndex, void *to) + { + if (fIsSimple) + return (void)fPrincipalColumn->Read(globalIndex, to); + + if (fTraits & kTraitMappable) + fPrincipalColumn->Read(globalIndex, to); + else + ReadGlobalImpl(globalIndex, to); + if (R__unlikely(!fReadCallbacks.empty())) + InvokeReadCallbacks(to); } - /// Throws an exception if the column given by fOnDiskId and the columnIndex in the provided descriptor - /// is not of one of the requested types. - ROOT::Experimental::EColumnType EnsureColumnType(const std::vector &requestedTypes, - unsigned int columnIndex, const RNTupleDescriptor &desc); + void Read(const RClusterIndex &clusterIndex, void *to) + { + if (fIsSimple) + return (void)fPrincipalColumn->Read(clusterIndex, to); + + if (fTraits & kTraitMappable) + fPrincipalColumn->Read(clusterIndex, to); + else + ReadInClusterImpl(clusterIndex, to); + if (R__unlikely(!fReadCallbacks.empty())) + InvokeReadCallbacks(to); + } + + /// General implementation of bulk read. Loop over the required range and read values that are required + /// and not already present. Derived classes may implement more optimized versions of this method. + /// See ReadBulk() for the return value. + virtual std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec); + + /// Returns the number of newly available values, that is the number of bools in bulkSpec.fMaskAvail that + /// flipped from false to true. As a special return value, kAllSet can be used if all values are read + /// independent from the masks. + std::size_t ReadBulk(const RBulkSpec &bulkSpec) + { + if (fIsSimple) { + /// For simple types, ignore the mask and memcopy the values into the destination + fPrincipalColumn->ReadV(bulkSpec.fFirstIndex, bulkSpec.fCount, bulkSpec.fValues); + std::fill(bulkSpec.fMaskAvail, bulkSpec.fMaskAvail + bulkSpec.fCount, true); + return RBulkSpec::kAllSet; + } + + return ReadBulkImpl(bulkSpec); + } + + /// Allow derived classes to call Append and Read on other (sub) fields. + static std::size_t CallAppendOn(RFieldBase &other, const void *from) { return other.Append(from); } + static void CallReadOn(RFieldBase &other, const RClusterIndex &clusterIndex, void *to) + { + other.Read(clusterIndex, to); + } + static void CallReadOn(RFieldBase &other, NTupleSize_t globalIndex, void *to) { other.Read(globalIndex, to); } + + /// Fields may need direct access to the principal column of their sub fields, e.g. in RRVecField::ReadBulk + static RColumn *GetPrincipalColumnOf(const RFieldBase &other) { return other.fPrincipalColumn; } /// Set a user-defined function to be called after reading a value, giving a chance to inspect and/or modify the /// value object. @@ -154,39 +465,71 @@ protected: size_t AddReadCallback(ReadCallback_t func); void RemoveReadCallback(size_t idx); -private: - void InvokeReadCallbacks(RFieldValue &value) - { - for (const auto &func : fReadCallbacks) - func(value); - } + // Perform housekeeping tasks for global to cluster-local index translation + virtual void CommitClusterImpl() {} + + /// Add a new subfield to the list of nested fields + void Attach(std::unique_ptr child); + + /// Called by `ConnectPageSource()` only once connected; derived classes may override this + /// as appropriate + virtual void OnConnectPageSource() {} + + /// Factory method to resurrect a field from the stored on-disk type information. This overload takes an already + /// normalized type name and type alias + /// TODO(jalopezg): this overload may eventually be removed leaving only the `RFieldBase::Create()` that takes a + /// single type name + static RResult> + Create(const std::string &fieldName, const std::string &canonicalType, const std::string &typeAlias); public: /// Iterates over the sub tree of fields in depth-first search order - class RSchemaIterator { + template + class RSchemaIteratorTemplate { private: struct Position { + using FieldPtr_t = std::conditional_t; Position() : fFieldPtr(nullptr), fIdxInParent(-1) { } - Position(RFieldBase *fieldPtr, int idxInParent) : fFieldPtr(fieldPtr), fIdxInParent(idxInParent) { } - RFieldBase *fFieldPtr; + Position(FieldPtr_t fieldPtr, int idxInParent) : fFieldPtr(fieldPtr), fIdxInParent(idxInParent) {} + FieldPtr_t fFieldPtr; int fIdxInParent; }; /// The stack of nodes visited when walking down the tree of fields std::vector fStack; public: - using iterator = RSchemaIterator; + using iterator = RSchemaIteratorTemplate; using iterator_category = std::forward_iterator_tag; - using value_type = RFieldBase; using difference_type = std::ptrdiff_t; - using pointer = RFieldBase*; - using reference = RFieldBase&; + using value_type = std::conditional_t; + using pointer = std::conditional_t; + using reference = std::conditional_t; - RSchemaIterator() { fStack.emplace_back(Position()); } - RSchemaIterator(pointer val, int idxInParent) { fStack.emplace_back(Position(val, idxInParent)); } - ~RSchemaIterator() {} + RSchemaIteratorTemplate() { fStack.emplace_back(Position()); } + RSchemaIteratorTemplate(pointer val, int idxInParent) { fStack.emplace_back(Position(val, idxInParent)); } + ~RSchemaIteratorTemplate() {} /// Given that the iterator points to a valid field which is not the end iterator, go to the next field /// in depth-first search order - void Advance(); + void Advance() + { + auto itr = fStack.rbegin(); + if (!itr->fFieldPtr->fSubFields.empty()) { + fStack.emplace_back(Position(itr->fFieldPtr->fSubFields[0].get(), 0)); + return; + } + + unsigned int nextIdxInParent = ++(itr->fIdxInParent); + while (nextIdxInParent >= itr->fFieldPtr->fParent->fSubFields.size()) { + if (fStack.size() == 1) { + itr->fFieldPtr = itr->fFieldPtr->fParent; + itr->fIdxInParent = -1; + return; + } + fStack.pop_back(); + itr = fStack.rbegin(); + nextIdxInParent = ++(itr->fIdxInParent); + } + itr->fFieldPtr = itr->fFieldPtr->fParent->fSubFields[nextIdxInParent].get(); + } iterator operator++(int) /* postfix */ { auto r = *this; Advance(); return r; } iterator& operator++() /* prefix */ { Advance(); return *this; } @@ -195,6 +538,8 @@ public: bool operator==(const iterator& rh) const { return fStack.back().fFieldPtr == rh.fStack.back().fFieldPtr; } bool operator!=(const iterator& rh) const { return fStack.back().fFieldPtr != rh.fStack.back().fFieldPtr; } }; + using RSchemaIterator = RSchemaIteratorTemplate; + using RConstSchemaIterator = RSchemaIteratorTemplate; /// The constructor creates the underlying column objects and connects them to either a sink or a source. /// If `isSimple` is `true`, the trait `kTraitMappable` is automatically set on construction. However, the @@ -211,79 +556,37 @@ public: std::unique_ptr Clone(std::string_view newName) const; /// Factory method to resurrect a field from the stored on-disk type information - static RResult> Create(const std::string &fieldName, const std::string &typeName); + static RResult> + Create(const std::string &fieldName, const std::string &typeName); /// Check whether a given string is a valid field name static RResult EnsureValidFieldName(std::string_view fieldName); /// Generates an object of the field type and allocates new initialized memory according to the type. - RFieldValue GenerateValue(); - /// Generates a tree value in a given location of size at least GetValueSize(). Assumes that where has been - /// allocated by malloc(). - virtual RFieldValue GenerateValue(void *where) = 0; - /// Releases the resources acquired during GenerateValue (memory and constructor) - /// This implementation works for simple types but needs to be overwritten for complex ones - virtual void DestroyValue(const RFieldValue &value, bool dtorOnly = false); + RValue GenerateValue(); + /// The returned bulk is initially empty; RBulk::ReadBulk will construct the array of values + RBulk GenerateBulk() { return RBulk(this); } /// Creates a value from a memory location with an already constructed object - virtual RFieldValue CaptureValue(void *where) = 0; + RValue BindValue(void *where) { return RValue(this, where, false /* isOwning */); } /// Creates the list of direct child values given a value for this field. E.g. a single value for the /// correct variant or all the elements of a collection. The default implementation assumes no sub values /// and returns an empty vector. - virtual std::vector SplitValue(const RFieldValue &value) const; + virtual std::vector SplitValue(const RValue &value) const; /// The number of bytes taken by a value of the appropriate type virtual size_t GetValueSize() const = 0; - /// For many types, the alignment requirement is equal to the size; otherwise override. - virtual size_t GetAlignment() const { return GetValueSize(); } + /// As a rule of thumb, the alignment is equal to the size of the type. There are, however, various exceptions + /// to this rule depending on OS and CPU architecture. So enforce the alignment to be explicitly spelled out. + virtual size_t GetAlignment() const = 0; int GetTraits() const { return fTraits; } bool HasReadCallbacks() const { return !fReadCallbacks.empty(); } - /// Write the given value into columns. The value object has to be of the same type as the field. - /// Returns the number of uncompressed bytes written. - std::size_t Append(const RFieldValue& value) { - if (~fTraits & kTraitMappable) - return AppendImpl(value); - - fPrincipalColumn->Append(value.fMappedElement); - return value.fMappedElement.GetSize(); - } - - /// Populate a single value with data from the tree, which needs to be of the fitting type. - /// Reading copies data into the memory wrapped by the ntuple value. - /// The fast path is conditioned by the field qualifying as simple, i.e. maps as-is to a single column and has no - /// read callback. - void Read(NTupleSize_t globalIndex, RFieldValue *value) { - if (fIsSimple) - return (void)fPrincipalColumn->Read(globalIndex, &value->fMappedElement); - - if (fTraits & kTraitMappable) - fPrincipalColumn->Read(globalIndex, &value->fMappedElement); - else - ReadGlobalImpl(globalIndex, value); - if (R__unlikely(!fReadCallbacks.empty())) - InvokeReadCallbacks(*value); - } - - void Read(const RClusterIndex &clusterIndex, RFieldValue *value) { - if (fIsSimple) - return (void)fPrincipalColumn->Read(clusterIndex, &value->fMappedElement); - - if (fTraits & kTraitMappable) - fPrincipalColumn->Read(clusterIndex, &value->fMappedElement); - else - ReadInClusterImpl(clusterIndex, value); - if (R__unlikely(!fReadCallbacks.empty())) - InvokeReadCallbacks(*value); - } - - /// Ensure that all received items are written from page buffers to the storage. - void Flush() const; - /// Perform housekeeping tasks for global to cluster-local index translation - virtual void CommitCluster() {} - - /// Add a new subfield to the list of nested fields - void Attach(std::unique_ptr child); + /// Flushes data from active columns to disk and calls CommitClusterImpl + void CommitCluster(); std::string GetName() const { return fName; } + /// Returns the field name and parent field names separated by dots ("grandparent.parent.child") + std::string GetQualifiedFieldName() const; std::string GetType() const { return fType; } + std::string GetTypeAlias() const { return fTypeAlias; } ENTupleStructure GetStructure() const { return fStructure; } std::size_t GetNRepetitions() const { return fNRepetitions; } NTupleSize_t GetNElements() const { return fPrincipalColumn->GetNElements(); } @@ -292,23 +595,44 @@ public: bool IsSimple() const { return fIsSimple; } /// Get the field's description std::string GetDescription() const { return fDescription; } - void SetDescription(std::string_view description) { fDescription = std::string(description); } + void SetDescription(std::string_view description); + EState GetState() const { return fState; } DescriptorId_t GetOnDiskId() const { return fOnDiskId; } - void SetOnDiskId(DescriptorId_t id) { fOnDiskId = id; } + void SetOnDiskId(DescriptorId_t id); + + /// Returns the fColumnRepresentative pointee or, if unset, the field's default representative + const ColumnRepresentation_t &GetColumnRepresentative() const; + /// Fixes a column representative. This can only be done _before_ connecting the field to a page sink. + /// Otherwise, or if the provided representation is not in the list of GetColumnRepresentations, + /// an exception is thrown + void SetColumnRepresentative(const ColumnRepresentation_t &representative); + /// Whether or not an explicit column representative was set + bool HasDefaultColumnRepresentative() const { return fColumnRepresentative == nullptr; } /// Fields and their columns live in the void until connected to a physical page storage. Only once connected, data /// can be read or written. In order to find the field in the page storage, the field's on-disk ID has to be set. - void ConnectPageSink(RPageSink &pageSink); + /// \param firstEntry The global index of the first entry with on-disk data for the connected field + void ConnectPageSink(RPageSink &pageSink, NTupleSize_t firstEntry = 0); void ConnectPageSource(RPageSource &pageSource); /// Indicates an evolution of the mapping scheme from C++ type to columns virtual std::uint32_t GetFieldVersion() const { return 0; } /// Indicates an evolution of the C++ type itself virtual std::uint32_t GetTypeVersion() const { return 0; } + /// Return the C++ type version stored in the field descriptor; only valid after a call to `ConnectPageSource()` + std::uint32_t GetOnDiskTypeVersion() const { return fOnDiskTypeVersion; } - RSchemaIterator begin(); - RSchemaIterator end(); + RSchemaIterator begin() + { + return fSubFields.empty() ? RSchemaIterator(this, -1) : RSchemaIterator(fSubFields[0].get(), 0); + } + RSchemaIterator end() { return RSchemaIterator(this, -1); } + RConstSchemaIterator cbegin() const + { + return fSubFields.empty() ? RConstSchemaIterator(this, -1) : RConstSchemaIterator(fSubFields[0].get(), 0); + } + RConstSchemaIterator cend() const { return RConstSchemaIterator(this, -1); } virtual void AcceptVisitor(RFieldVisitor &visitor) const; }; @@ -317,20 +641,22 @@ public: -/// The container field for an ntuple model, which itself has no physical representation +/// The container field for an ntuple model, which itself has no physical representation. +/// Therefore, the zero field must not be connected to a page source or sink. class RFieldZero : public Detail::RFieldBase { protected: std::unique_ptr CloneImpl(std::string_view newName) const override; + void GenerateColumnsImpl() final {} + void GenerateColumnsImpl(const RNTupleDescriptor &) final {} + void GenerateValue(void *) const final {} public: RFieldZero() : Detail::RFieldBase("", "", ENTupleStructure::kRecord, false /* isSimple */) { } - void GenerateColumnsImpl() final {} - void GenerateColumnsImpl(const RNTupleDescriptor &) final {} + using Detail::RFieldBase::Attach; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void*) override { return Detail::RFieldValue(); } - Detail::RFieldValue CaptureValue(void*) final { return Detail::RFieldValue(); } size_t GetValueSize() const final { return 0; } + size_t GetAlignment() const final { return 0; } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -357,12 +683,22 @@ private: private: RClassField(std::string_view fieldName, std::string_view className, TClass *classp); void Attach(std::unique_ptr child, RSubFieldInfo info); + /// Register post-read callbacks corresponding to a list of ROOT I/O customization rules. `classp` is used to + /// fill the `TVirtualObject` instance passed to the user function. + void AddReadCallbacksFromIORules(const std::span rules, TClass *classp = nullptr); protected: std::unique_ptr CloneImpl(std::string_view newName) const final; - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; - void ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) final; + void GenerateColumnsImpl() final {} + void GenerateColumnsImpl(const RNTupleDescriptor &) final {} + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + void ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) final; + void OnConnectPageSource() final; public: RClassField(std::string_view fieldName, std::string_view className); @@ -370,57 +706,164 @@ public: RClassField& operator =(RClassField&& other) = default; ~RClassField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void* where) override; - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) final; - Detail::RFieldValue CaptureValue(void *where) final; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const override; size_t GetAlignment() const final { return fMaxAlignment; } + std::uint32_t GetTypeVersion() const final; void AcceptVisitor(Detail::RFieldVisitor &visitor) const override; }; +/// The field for an unscoped or scoped enum with dictionary +class REnumField : public Detail::RFieldBase { +private: + REnumField(std::string_view fieldName, std::string_view enumName, TEnum *enump); + REnumField(std::string_view fieldName, std::string_view enumName, std::unique_ptr intField); + +protected: + std::unique_ptr CloneImpl(std::string_view newName) const final; + void GenerateColumnsImpl() final {} + void GenerateColumnsImpl(const RNTupleDescriptor & /* desc */) final {} + + void GenerateValue(void *where) const final { CallGenerateValueOn(*fSubFields[0], where); } + + std::size_t AppendImpl(const void *from) final { return CallAppendOn(*fSubFields[0], from); } + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final { CallReadOn(*fSubFields[0], globalIndex, to); } + +public: + REnumField(std::string_view fieldName, std::string_view enumName); + REnumField(REnumField &&other) = default; + REnumField &operator=(REnumField &&other) = default; + ~REnumField() override = default; + + using Detail::RFieldBase::GenerateValue; + std::vector SplitValue(const RValue &value) const final; + size_t GetValueSize() const final { return fSubFields[0]->GetValueSize(); } + size_t GetAlignment() const final { return fSubFields[0]->GetAlignment(); } + void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; +}; + /// The field for a class representing a collection of elements via `TVirtualCollectionProxy`. /// Objects of such type behave as collections that can be accessed through the corresponding member functions in -/// `TVirtualCollectionProxy`. At a bare minimum, the user is required to provide an implementation for the following -/// functions in `TVirtualCollectionProxy`: `HasPointers()`, `GetProperties()`, `GetValueClass()`, `GetType()`, -/// `Sizeof()`, `PushProxy()`, `PopProxy()`, `At()`, `Clear()`, and `Insert()`. +/// `TVirtualCollectionProxy`. For STL collections, these proxies are provided. Custom classes need to implement the +/// corresponding member functions in `TVirtualCollectionProxy`. At a bare minimum, the user is required to provide an +/// implementation for the following functions in `TVirtualCollectionProxy`: `HasPointers()`, `GetProperties()`, +/// `GetValueClass()`, `GetType()`, `PushProxy()`, `PopProxy()`, `GetFunctionCreateIterators()`, `GetFunctionNext()`, +/// and `GetFunctionDeleteTwoIterators()`. /// /// The collection proxy for a given class can be set via `TClass::CopyCollectionProxy()`. -class RCollectionClassField : public Detail::RFieldBase { -private: - /// Chunk size in bytes used in `ReadGlobalImp()`. Items held in the same chunk will be inserted in - /// a single `TVirtualCollectionProxy::Insert()` call. - static constexpr const std::size_t kReadChunkSize = 64 * 1024; +class RProxiedCollectionField : public Detail::RFieldBase { +protected: + /// Allows for iterating over the elements of a proxied collection. RCollectionIterableOnce avoids an additional + /// iterator copy (see `TVirtualCollectionProxy::GetFunctionCopyIterator`) and thus can only be iterated once. + class RCollectionIterableOnce { + public: + struct RIteratorFuncs { + TVirtualCollectionProxy::CreateIterators_t fCreateIterators; + TVirtualCollectionProxy::DeleteTwoIterators_t fDeleteTwoIterators; + TVirtualCollectionProxy::Next_t fNext; + }; + static RIteratorFuncs GetIteratorFuncs(TVirtualCollectionProxy *proxy, bool readFromDisk); + + private: + class RIterator { + const RCollectionIterableOnce &fOwner; + void *fIterator = nullptr; + void *fElementPtr = nullptr; + + void Advance() + { + auto fnNext_Contig = [&]() { + // Array-backed collections (e.g. kSTLvector) directly use the pointer-to-iterator-data as a + // pointer-to-element, thus saving an indirection level (see documentation for TVirtualCollectionProxy) + auto &iter = reinterpret_cast(fIterator), p = iter; + iter += fOwner.fStride; + return p; + }; + fElementPtr = fOwner.fStride ? fnNext_Contig() : fOwner.fIFuncs.fNext(fIterator, fOwner.fEnd); + } + + public: + using iterator_category = std::forward_iterator_tag; + using iterator = RIterator; + using difference_type = std::ptrdiff_t; + using pointer = void *; + + RIterator(const RCollectionIterableOnce &owner) : fOwner(owner) {} + RIterator(const RCollectionIterableOnce &owner, void *iter) : fOwner(owner), fIterator(iter) { Advance(); } + iterator operator++() + { + Advance(); + return *this; + } + pointer operator*() const { return fElementPtr; } + bool operator!=(const iterator &rh) const { return fElementPtr != rh.fElementPtr; } + bool operator==(const iterator &rh) const { return fElementPtr == rh.fElementPtr; } + }; + + const RIteratorFuncs &fIFuncs; + const std::size_t fStride; + unsigned char fBeginSmallBuf[TVirtualCollectionProxy::fgIteratorArenaSize]; + unsigned char fEndSmallBuf[TVirtualCollectionProxy::fgIteratorArenaSize]; + void *fBegin = &fBeginSmallBuf; + void *fEnd = &fEndSmallBuf; + public: + /// Construct a `RCollectionIterableOnce` that iterates over `collection`. If elements are guaranteed to be + /// contiguous in memory (e.g. a vector), `stride` can be provided for faster iteration, i.e. the address of each + /// element is known given the base pointer. + RCollectionIterableOnce(void *collection, const RIteratorFuncs &ifuncs, TVirtualCollectionProxy *proxy, + std::size_t stride = 0U) + : fIFuncs(ifuncs), fStride(stride) + { + fIFuncs.fCreateIterators(collection, &fBegin, &fEnd, proxy); + } + ~RCollectionIterableOnce() { fIFuncs.fDeleteTwoIterators(fBegin, fEnd); } + + RIterator begin() { return RIterator(*this, fBegin); } + RIterator end() { return fStride ? RIterator(*this, fEnd) : RIterator(*this); } + }; + std::unique_ptr fProxy; + Int_t fProperties; + Int_t fCollectionType; + /// Two sets of functions to operate on iterators, to be used depending on the access type. The direction preserves + /// the meaning from TVirtualCollectionProxy, i.e. read from disk / write to disk, respectively + RCollectionIterableOnce::RIteratorFuncs fIFuncsRead; + RCollectionIterableOnce::RIteratorFuncs fIFuncsWrite; std::size_t fItemSize; ClusterSize_t fNWritten; - RCollectionClassField(std::string_view fieldName, std::string_view className, TClass *classp); + /// Constructor used when the value type of the collection is not known in advance, i.e. in the case of custom + /// collections. + RProxiedCollectionField(std::string_view fieldName, std::string_view typeName, TClass *classp); + /// Constructor used when the value type of the collection is known in advance, e.g. in `RSetField`. + RProxiedCollectionField(std::string_view fieldName, std::string_view typeName, + std::unique_ptr itemField); protected: - std::unique_ptr CloneImpl(std::string_view newName) const final; - std::size_t AppendImpl(const Detail::RFieldValue &value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; + std::unique_ptr CloneImpl(std::string_view newName) const override; + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + + void CommitClusterImpl() final { fNWritten = 0; } public: - RCollectionClassField(std::string_view fieldName, std::string_view className); - RCollectionClassField(RCollectionClassField &&other) = default; - RCollectionClassField &operator=(RCollectionClassField &&other) = default; - ~RCollectionClassField() override = default; + RProxiedCollectionField(std::string_view fieldName, std::string_view typeName); + RProxiedCollectionField(RProxiedCollectionField &&other) = default; + RProxiedCollectionField &operator=(RProxiedCollectionField &&other) = default; + ~RProxiedCollectionField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) final; - Detail::RFieldValue CaptureValue(void *where) override; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const override { return fProxy->Sizeof(); } - size_t GetAlignment() const final { return alignof(std::max_align_t); } - void CommitCluster() final; + size_t GetAlignment() const override { return alignof(std::max_align_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; void GetCollectionInfo(NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *size) const { @@ -443,9 +886,16 @@ protected: std::size_t GetItemPadding(std::size_t baseOffset, std::size_t itemAlignment) const; std::unique_ptr CloneImpl(std::string_view newName) const override; - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; - void ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) final; + + void GenerateColumnsImpl() final {} + void GenerateColumnsImpl(const RNTupleDescriptor &) final {} + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + void ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) final; RRecordField(std::string_view fieldName, std::vector> &&itemFields, const std::vector &offsets, std::string_view typeName = ""); @@ -473,13 +923,8 @@ public: RRecordField& operator =(RRecordField&& other) = default; ~RRecordField() override = default; - void GenerateColumnsImpl() final {} - void GenerateColumnsImpl(const RNTupleDescriptor &) final {} using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void* where) override; - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) override; - Detail::RFieldValue CaptureValue(void *where) final; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const final { return fSize; } size_t GetAlignment() const final { return fMaxAlignment; } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; @@ -493,8 +938,18 @@ private: protected: std::unique_ptr CloneImpl(std::string_view newName) const final; - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; + + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + void GenerateValue(void *where) const override { new (where) std::vector(); } + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + + void CommitClusterImpl() final { fNWritten = 0; } public: RVectorField(std::string_view fieldName, std::unique_ptr itemField); @@ -502,16 +957,10 @@ public: RVectorField& operator =(RVectorField&& other) = default; ~RVectorField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void* where) override; - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) final; - Detail::RFieldValue CaptureValue(void *where) override; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const override { return sizeof(std::vector); } size_t GetAlignment() const final { return std::alignment_of>(); } - void CommitCluster() final; void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; void GetCollectionInfo(NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *size) const { fPrincipalColumn->GetCollectionInfo(globalIndex, collectionStart, size); @@ -534,8 +983,18 @@ protected: std::size_t fValueSize; std::unique_ptr CloneImpl(std::string_view newName) const override; - std::size_t AppendImpl(const Detail::RFieldValue &value) override; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) override; + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + + std::size_t AppendImpl(const void *from) override; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) override; + std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec) final; + + void CommitClusterImpl() final { fNWritten = 0; } public: RRVecField(std::string_view fieldName, std::unique_ptr itemField); @@ -545,16 +1004,10 @@ public: RRVecField &operator=(RRVecField &) = delete; ~RRVecField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) override; - Detail::RFieldValue CaptureValue(void *where) override; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const override; size_t GetAlignment() const override; - void CommitCluster() final; void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; void GetCollectionInfo(NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *size) const { @@ -574,9 +1027,16 @@ private: protected: std::unique_ptr CloneImpl(std::string_view newName) const final; - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; - void ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) final; + + void GenerateColumnsImpl() final {} + void GenerateColumnsImpl(const RNTupleDescriptor &) final {} + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + void ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) final; public: RArrayField(std::string_view fieldName, std::unique_ptr itemField, std::size_t arrayLength); @@ -584,19 +1044,52 @@ public: RArrayField& operator =(RArrayField &&other) = default; ~RArrayField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) final; - Detail::RFieldValue CaptureValue(void *where) final; - std::vector SplitValue(const Detail::RFieldValue &value) const final; + std::vector SplitValue(const RValue &value) const final; size_t GetLength() const { return fArrayLength; } size_t GetValueSize() const final { return fItemSize * fArrayLength; } size_t GetAlignment() const final { return fSubFields[0]->GetAlignment(); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; +/// The generic field an std::bitset. All compilers we care about store the bits in an array of unsigned long. +/// TODO(jblomer): reading and writing efficiency should be improved; currently it is one bit at a time +/// with an array of bools on the page level. +class RBitsetField : public Detail::RFieldBase { + using Word_t = unsigned long; + static constexpr std::size_t kWordSize = sizeof(Word_t); + static constexpr std::size_t kBitsPerWord = kWordSize * 8; + +protected: + std::size_t fN; + +protected: + std::unique_ptr CloneImpl(std::string_view newName) const final + { + return std::make_unique(newName, fN); + } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { memset(where, 0, GetValueSize()); } + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + +public: + RBitsetField(std::string_view fieldName, std::size_t N); + RBitsetField(RBitsetField &&other) = default; + RBitsetField &operator=(RBitsetField &&other) = default; + ~RBitsetField() override = default; + + using Detail::RFieldBase::GenerateValue; + size_t GetValueSize() const final { return kWordSize * ((fN + kBitsPerWord - 1) / kBitsPerWord); } + size_t GetAlignment() const final { return alignof(Word_t); } + void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; + + /// Get the number of bits in the bitset, i.e. the N in std::bitset + std::size_t GetN() const { return fN; } +}; + /// The generic field for std::variant types class RVariantField : public Detail::RFieldBase { private: @@ -608,13 +1101,23 @@ private: static std::string GetTypeList(const std::vector &itemFields); /// Extracts the index from an std::variant and transforms it into the 1-based index used for the switch column - std::uint32_t GetTag(void *variantPtr) const; + std::uint32_t GetTag(const void *variantPtr) const; void SetTag(void *variantPtr, std::uint32_t tag) const; protected: std::unique_ptr CloneImpl(std::string_view newName) const final; - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; + + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + + void CommitClusterImpl() final; public: // TODO(jblomer): use std::span in signature @@ -623,37 +1126,124 @@ public: RVariantField& operator =(RVariantField &&other) = default; ~RVariantField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) final; - Detail::RFieldValue CaptureValue(void *where) final; size_t GetValueSize() const final; size_t GetAlignment() const final { return fMaxAlignment; } - void CommitCluster() final; }; +/// The generic field for a std::set +class RSetField : public RProxiedCollectionField { +protected: + std::unique_ptr CloneImpl(std::string_view newName) const final; + +public: + RSetField(std::string_view fieldName, std::string_view typeName, std::unique_ptr itemField); + RSetField(RSetField &&other) = default; + RSetField &operator=(RSetField &&other) = default; + ~RSetField() override = default; + + size_t GetAlignment() const override { return std::alignment_of>(); } +}; + +/// The field for values that may or may not be present in an entry. Parent class for unique pointer field and +/// optional field. A nullable field cannot be instantiated itself but only its descendants. +/// The RNullableField takes care of the on-disk representation. Child classes are responsible for the in-memory +/// representation. The on-disk representation can be "dense" or "sparse". Dense nullable fields have a bitmask +/// (true: item available, false: item missing) and serialize a default-constructed item for missing items. +/// Sparse nullable fields use a (Split)Index[64|32] column to point to the available items. +/// By default, items whose size is smaller or equal to 4 bytes (size of (Split)Index32 column element) are stored +/// densely. +class RNullableField : public Detail::RFieldBase { + /// For a dense nullable field, used to write a default-constructed item for missing ones. + std::unique_ptr fDefaultItemValue; + /// For a sparse nullable field, the number of written non-null items in this cluster + ClusterSize_t fNWritten{0}; + +protected: + const Detail::RFieldBase::RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &) final; + + std::size_t AppendNull(); + std::size_t AppendValue(const void *from); + void CommitClusterImpl() final { fNWritten = 0; } + + /// Given the index of the nullable field, returns the corresponding global index of the subfield or, + /// if it is null, returns kInvalidClusterIndex + RClusterIndex GetItemIndex(NTupleSize_t globalIndex); + + RNullableField(std::string_view fieldName, std::string_view typeName, std::unique_ptr itemField); + +public: + RNullableField(RNullableField &&other) = default; + RNullableField &operator=(RNullableField &&other) = default; + ~RNullableField() override = default; + + bool IsDense() const { return GetColumnRepresentative()[0] == EColumnType::kBit; } + bool IsSparse() const { return !IsDense(); } + void SetDense() { SetColumnRepresentative({EColumnType::kBit}); } + void SetSparse() { SetColumnRepresentative({EColumnType::kSplitIndex32}); } + + void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; +}; + +class RUniquePtrField : public RNullableField { +protected: + std::unique_ptr CloneImpl(std::string_view newName) const final; + + void GenerateValue(void *where) const final { new (where) std::unique_ptr(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + +public: + RUniquePtrField(std::string_view fieldName, std::string_view typeName, + std::unique_ptr itemField); + RUniquePtrField(RUniquePtrField &&other) = default; + RUniquePtrField &operator=(RUniquePtrField &&other) = default; + ~RUniquePtrField() override = default; + + using Detail::RFieldBase::GenerateValue; + std::vector SplitValue(const RValue &value) const final; + size_t GetValueSize() const final { return sizeof(std::unique_ptr); } + size_t GetAlignment() const final { return alignof(std::unique_ptr); } +}; /// Classes with dictionaries that can be inspected by TClass template class RField : public RClassField { +protected: + void GenerateValue(void *where) const final + { + if constexpr (std::is_default_constructible_v) { + new (where) T(); + } else { + // If there is no default constructor, try with the IO constructor + new (where) T(static_cast(nullptr)); + } + } + public: static std::string TypeName() { return ROOT::Internal::GetDemangledTypeName(typeid(T)); } RField(std::string_view name) : RClassField(name, TypeName()) { - static_assert(std::is_class::value, "no I/O support for this basic C++ type"); + static_assert(std::is_class_v, "no I/O support for this basic C++ type"); } RField(RField &&other) = default; RField &operator=(RField &&other) = default; ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT &&...args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { return GenerateValue(where, T()); } +}; + +template +class RField>::type> : public REnumField { +public: + static std::string TypeName() { return ROOT::Internal::GetDemangledTypeName(typeid(T)); } + RField(std::string_view name) : REnumField(name, TypeName()) {} + RField(RField &&other) = default; + RField &operator=(RField &&other) = default; + ~RField() override = default; }; template @@ -668,7 +1258,7 @@ struct HasCollectionProxyMemberType< /// The point here is that we can only tell at run time if a class has an associated collection proxy. /// For compile time, in the first iteration of this PR we had an extra template argument that acted as a "tag" to /// differentiate the RField specialization for classes with an associated collection proxy (inherits -/// `RCollectionClassField`) from the RField primary template definition (`RClassField`-derived), as in: +/// `RProxiedCollectionField`) from the RField primary template definition (`RClassField`-derived), as in: /// ``` /// auto field = std::make_unique>("klass"); /// // vs @@ -721,10 +1311,13 @@ struct IsCollectionProxy : HasCollectionProxyMemberType { /// }; /// ``` template -class RField::value>::type> : public RCollectionClassField { +class RField::value>::type> : public RProxiedCollectionField { +protected: + void GenerateValue(void *where) const final { new (where) T(); } + public: static std::string TypeName() { return ROOT::Internal::GetDemangledTypeName(typeid(T)); } - RField(std::string_view name) : RCollectionClassField(name, TypeName()) + RField(std::string_view name) : RProxiedCollectionField(name, TypeName()) { static_assert(std::is_class::value, "collection proxy unsupported for fundamental types"); } @@ -733,12 +1326,6 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, T()); } }; /// The collection field is only used for writing; when reading, untyped collections are projected to an std::vector @@ -746,8 +1333,16 @@ class RCollectionField : public ROOT::Experimental::Detail::RFieldBase { private: /// Save the link to the collection ntuple in order to reset the offset counter when committing the cluster std::shared_ptr fCollectionNTuple; + protected: std::unique_ptr CloneImpl(std::string_view newName) const final; + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *) const final {} + + void CommitClusterImpl() final; + public: static std::string TypeName() { return ""; } RCollectionField(std::string_view name, @@ -757,21 +1352,9 @@ public: RCollectionField& operator =(RCollectionField&& other) = default; ~RCollectionField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - using Detail::RFieldBase::GenerateValue; - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where)); - } - Detail::RFieldValue CaptureValue(void* where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(ClusterSize_t); } - void CommitCluster() final; + size_t GetAlignment() const final { return alignof(ClusterSize_t); } }; /// The generic field for `std::pair` types @@ -783,6 +1366,9 @@ private: protected: std::unique_ptr CloneImpl(std::string_view newName) const override; + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + RPairField(std::string_view fieldName, std::array, 2> &&itemFields, const std::array &offsets); @@ -793,8 +1379,6 @@ public: ~RPairField() override = default; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) override; }; /// The generic field for `std::tuple` types @@ -806,6 +1390,9 @@ private: protected: std::unique_ptr CloneImpl(std::string_view newName) const override; + void GenerateValue(void *where) const override; + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + RTupleField(std::string_view fieldName, std::vector> &&itemFields, const std::vector &offsets); @@ -816,12 +1403,39 @@ public: ~RTupleField() override = default; using Detail::RFieldBase::GenerateValue; - Detail::RFieldValue GenerateValue(void *where) override; - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) override; }; -/// Template specializations for concrete C++ types +/// An artificial field that transforms an RNTuple column that contains the offset of collections into +/// collection sizes. It is only used for reading, e.g. as projected field or as an artificial field that provides the +/// "number of" RDF columns for collections (e.g. `R_rdf_sizeof_jets` for a collection named `jets`). +/// It is used in the templated RField> form, which represents the collection sizes either +/// as 32bit unsigned int (std::uint32_t) or as 64bit unsigned int (std::uint64_t). +class RCardinalityField : public Detail::RFieldBase { +protected: + RCardinalityField(std::string_view fieldName, std::string_view typeName) + : Detail::RFieldBase(fieldName, typeName, ENTupleStructure::kLeaf, false /* isSimple */) + { + } + + const RColumnRepresentations &GetColumnRepresentations() const final; + // Field is only used for reading + void GenerateColumnsImpl() final { throw RException(R__FAIL("Cardinality fields must only be used for reading")); } + void GenerateColumnsImpl(const RNTupleDescriptor &) final; + +public: + RCardinalityField(RCardinalityField &&other) = default; + RCardinalityField &operator=(RCardinalityField &&other) = default; + ~RCardinalityField() = default; + + void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; + + const RField> *As32Bit() const; + const RField> *As64Bit() const; +}; +//////////////////////////////////////////////////////////////////////////////// +/// Template specializations for concrete C++ types +//////////////////////////////////////////////////////////////////////////////// template <> class RField : public Detail::RFieldBase { @@ -830,6 +1444,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) ClusterSize_t(0); } + public: static std::string TypeName() { return "ROOT::Experimental::ClusterSize_t"; } explicit RField(std::string_view name) @@ -841,9 +1460,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - ClusterSize_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -858,19 +1474,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(ClusterSize_t); } + size_t GetAlignment() const final { return alignof(ClusterSize_t); } /// Special help for offset fields void GetCollectionInfo(NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *size) { @@ -882,6 +1487,70 @@ public: void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; +template +class RField> : public RCardinalityField { +protected: + std::unique_ptr CloneImpl(std::string_view newName) const final + { + return std::make_unique>>(newName); + } + void GenerateValue(void *where) const final { new (where) RNTupleCardinality(0); } + +public: + static std::string TypeName() { return "ROOT::Experimental::RNTupleCardinality<" + RField::TypeName() + ">"; } + explicit RField(std::string_view name) : RCardinalityField(name, TypeName()) {} + RField(RField &&other) = default; + RField &operator=(RField &&other) = default; + ~RField() = default; + + using Detail::RFieldBase::GenerateValue; + size_t GetValueSize() const final { return sizeof(RNTupleCardinality); } + size_t GetAlignment() const final { return alignof(RNTupleCardinality); } + + /// Get the number of elements of the collection identified by globalIndex + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final + { + RClusterIndex collectionStart; + ClusterSize_t size; + fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &size); + *static_cast *>(to) = size; + } + + /// Get the number of elements of the collection identified by clusterIndex + void ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) final + { + RClusterIndex collectionStart; + ClusterSize_t size; + fPrincipalColumn->GetCollectionInfo(clusterIndex, &collectionStart, &size); + *static_cast *>(to) = size; + } + + std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec) final + { + RClusterIndex collectionStart; + ClusterSize_t collectionSize; + fPrincipalColumn->GetCollectionInfo(bulkSpec.fFirstIndex, &collectionStart, &collectionSize); + + auto typedValues = static_cast *>(bulkSpec.fValues); + typedValues[0] = collectionSize; + + auto lastOffset = collectionStart.GetIndex() + collectionSize; + ClusterSize_t::ValueType nRemainingEntries = bulkSpec.fCount - 1; + std::size_t nEntries = 1; + while (nRemainingEntries > 0) { + NTupleSize_t nItemsUntilPageEnd; + auto offsets = fPrincipalColumn->MapV(bulkSpec.fFirstIndex + nEntries, nItemsUntilPageEnd); + std::size_t nBatch = std::min(nRemainingEntries, nItemsUntilPageEnd); + for (std::size_t i = 0; i < nBatch; ++i) { + typedValues[nEntries + i] = offsets[i] - lastOffset; + lastOffset = offsets[i]; + } + nRemainingEntries -= nBatch; + nEntries += nBatch; + } + return RBulkSpec::kAllSet; + } +}; template <> class RField : public Detail::RFieldBase { @@ -890,6 +1559,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) bool(false); } + public: static std::string TypeName() { return "bool"; } explicit RField(std::string_view name) @@ -901,9 +1575,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - bool *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -918,19 +1589,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, false); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(bool); } + size_t GetAlignment() const final { return alignof(bool); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -941,6 +1601,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) float(0.0); } + public: static std::string TypeName() { return "float"; } explicit RField(std::string_view name) @@ -952,9 +1617,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - float *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -969,19 +1631,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0.0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(float); } + size_t GetAlignment() const final { return alignof(float); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -993,6 +1644,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) double(0.0); } + public: static std::string TypeName() { return "double"; } explicit RField(std::string_view name) @@ -1004,9 +1660,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - double *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1021,20 +1674,12 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0.0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(double); } + size_t GetAlignment() const final { return alignof(double); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; + + // Set the column representation to 32 bit floating point and the type alias to Double32_t + void SetDouble32(); }; template <> @@ -1044,6 +1689,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) char(0); } + public: static std::string TypeName() { return "char"; } explicit RField(std::string_view name) @@ -1055,9 +1705,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - char *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1072,19 +1719,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(char); } + size_t GetAlignment() const final { return alignof(char); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1095,6 +1731,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) int8_t(0); } + public: static std::string TypeName() { return "std::int8_t"; } explicit RField(std::string_view name) @@ -1106,9 +1747,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::int8_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1123,19 +1761,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::int8_t); } + size_t GetAlignment() const final { return alignof(std::int8_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1146,6 +1773,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) uint8_t(0); } + public: static std::string TypeName() { return "std::uint8_t"; } explicit RField(std::string_view name) @@ -1157,9 +1789,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::uint8_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1174,19 +1803,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::uint8_t); } + size_t GetAlignment() const final { return alignof(std::uint8_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1197,6 +1815,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) int16_t(0); } + public: static std::string TypeName() { return "std::int16_t"; } explicit RField(std::string_view name) @@ -1208,9 +1831,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::int16_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1225,19 +1845,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::int16_t); } + size_t GetAlignment() const final { return alignof(std::int16_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1248,6 +1857,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) int16_t(0); } + public: static std::string TypeName() { return "std::uint16_t"; } explicit RField(std::string_view name) @@ -1259,9 +1873,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::uint16_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1276,19 +1887,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::uint16_t); } + size_t GetAlignment() const final { return alignof(std::uint16_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1299,6 +1899,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) int32_t(0); } + public: static std::string TypeName() { return "std::int32_t"; } explicit RField(std::string_view name) @@ -1310,9 +1915,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::int32_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1327,19 +1929,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::int32_t); } + size_t GetAlignment() const final { return alignof(std::int32_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1350,6 +1941,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) uint32_t(0); } + public: static std::string TypeName() { return "std::uint32_t"; } explicit RField(std::string_view name) @@ -1361,9 +1957,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::uint32_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1378,19 +1971,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::uint32_t); } + size_t GetAlignment() const final { return alignof(std::uint32_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1401,6 +1983,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) uint64_t(0); } + public: static std::string TypeName() { return "std::uint64_t"; } explicit RField(std::string_view name) @@ -1412,9 +1999,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::uint64_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1429,19 +2013,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::uint64_t); } + size_t GetAlignment() const final { return alignof(std::uint64_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1452,6 +2025,11 @@ protected: return std::make_unique(newName); } + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) int64_t(0); } + public: static std::string TypeName() { return "std::int64_t"; } explicit RField(std::string_view name) @@ -1463,9 +2041,6 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - std::int64_t *Map(NTupleSize_t globalIndex) { return fPrincipalColumn->Map(globalIndex); } @@ -1480,19 +2055,8 @@ public: } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue( - Detail::RColumnElement(static_cast(where)), - this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, 0); } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, - Detail::RColumnElement(static_cast(where)), this, where); - } size_t GetValueSize() const final { return sizeof(std::int64_t); } + size_t GetAlignment() const final { return alignof(std::int64_t); } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1500,48 +2064,36 @@ template <> class RField : public Detail::RFieldBase { private: ClusterSize_t fIndex; - Detail::RColumnElement fElemIndex; std::unique_ptr CloneImpl(std::string_view newName) const final { return std::make_unique(newName); } - std::size_t AppendImpl(const ROOT::Experimental::Detail::RFieldValue& value) final; - void ReadGlobalImpl(ROOT::Experimental::NTupleSize_t globalIndex, - ROOT::Experimental::Detail::RFieldValue *value) final; + + const RColumnRepresentations &GetColumnRepresentations() const final; + void GenerateColumnsImpl() final; + void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + + void GenerateValue(void *where) const final { new (where) std::string(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const override; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(ROOT::Experimental::NTupleSize_t globalIndex, void *to) final; + + void CommitClusterImpl() final { fIndex = 0; } public: static std::string TypeName() { return "std::string"; } explicit RField(std::string_view name) - : Detail::RFieldBase(name, TypeName(), ENTupleStructure::kLeaf, false /* isSimple */), fIndex(0), - fElemIndex(&fIndex) + : Detail::RFieldBase(name, TypeName(), ENTupleStructure::kLeaf, false /* isSimple */), fIndex(0) { } RField(RField&& other) = default; RField& operator =(RField&& other) = default; ~RField() override = default; - void GenerateColumnsImpl() final; - void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; - using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { return GenerateValue(where, ""); } - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) override { - auto str = value.Get(); - str->~basic_string(); // TODO(jblomer) C++17 std::destroy_at - if (!dtorOnly) - free(str); - } - Detail::RFieldValue CaptureValue(void *where) override { - return Detail::RFieldValue(true /* captureFlag */, this, where); - } size_t GetValueSize() const final { return sizeof(std::string); } size_t GetAlignment() const final { return std::alignment_of(); } - void CommitCluster() final; void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; }; @@ -1549,26 +2101,21 @@ public: template class RField> : public RArrayField { using ContainerT = typename std::array; + +protected: + void GenerateValue(void *where) const final { new (where) ContainerT(); } + public: static std::string TypeName() { return "std::array<" + RField::TypeName() + "," + std::to_string(N) + ">"; } - explicit RField(std::string_view name) - : RArrayField(name, std::make_unique>(RField::TypeName()), N) + explicit RField(std::string_view name) : RArrayField(name, std::make_unique>("_0"), N) {} RField(RField&& other) = default; RField& operator =(RField&& other) = default; ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { - return GenerateValue(where, ContainerT()); - } }; template @@ -1580,6 +2127,31 @@ public: ~RField() override = default; }; +template +class RField> : public RSetField { + using ContainerT = typename std::set; + +protected: + void GenerateValue(void *where) const final { new (where) ContainerT(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final + { + std::destroy_at(static_cast(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); + } + +public: + static std::string TypeName() { return "std::set<" + RField::TypeName() + ">"; } + + explicit RField(std::string_view name) : RSetField(name, TypeName(), std::make_unique>("_0")) {} + RField(RField &&other) = default; + RField &operator=(RField &&other) = default; + ~RField() override = default; + + using Detail::RFieldBase::GenerateValue; + size_t GetValueSize() const final { return sizeof(ContainerT); } + size_t GetAlignment() const final { return std::alignment_of(); } +}; + template class RField> : public RVariantField { using ContainerT = typename std::variant; @@ -1605,6 +2177,9 @@ private: return result; } +protected: + void GenerateValue(void *where) const final { new (where) ContainerT(); } + public: static std::string TypeName() { return "std::variant<" + BuildItemTypes() + ">"; } explicit RField(std::string_view name) : RVariantField(name, BuildItemFields()) {} @@ -1613,19 +2188,15 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { - return GenerateValue(where, ContainerT()); - } }; template class RField> : public RVectorField { using ContainerT = typename std::vector; + +protected: + void GenerateValue(void *where) const final { new (where) ContainerT(); } + public: static std::string TypeName() { return "std::vector<" + RField::TypeName() + ">"; } explicit RField(std::string_view name) @@ -1636,17 +2207,6 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { - return GenerateValue(where, ContainerT()); - } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, this, where); - } size_t GetValueSize() const final { return sizeof(ContainerT); } }; @@ -1660,11 +2220,19 @@ protected: std::unique_ptr CloneImpl(std::string_view newName) const final { return std::make_unique(newName); } - std::size_t AppendImpl(const Detail::RFieldValue& value) final; - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final; + + const RColumnRepresentations &GetColumnRepresentations() const final; void GenerateColumnsImpl() final; void GenerateColumnsImpl(const RNTupleDescriptor &desc) final; + void GenerateValue(void *where) const final { new (where) std::vector(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final; + + std::size_t AppendImpl(const void *from) final; + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final; + + void CommitClusterImpl() final { fNWritten = 0; } + public: static std::string TypeName() { return "std::vector"; } explicit RField(std::string_view name); @@ -1673,23 +2241,10 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast*>(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { - return GenerateValue(where, std::vector()); - } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, this, where); - } - std::vector SplitValue(const Detail::RFieldValue &value) const final; - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) final; + std::vector SplitValue(const RValue &value) const final; size_t GetValueSize() const final { return sizeof(std::vector); } size_t GetAlignment() const final { return std::alignment_of>(); } - void CommitCluster() final { fNWritten = 0; } void AcceptVisitor(Detail::RFieldVisitor &visitor) const final; void GetCollectionInfo(NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *size) const { fPrincipalColumn->GetCollectionInfo(globalIndex, collectionStart, size); @@ -1708,28 +2263,35 @@ protected: auto newItemField = fSubFields[0]->Clone(fSubFields[0]->GetName()); return std::make_unique>>(newName, std::move(newItemField)); } - std::size_t AppendImpl(const Detail::RFieldValue& value) final { - auto typedValue = value.Get(); + + void GenerateValue(void *where) const final { new (where) ContainerT(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final + { + std::destroy_at(static_cast(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); + } + + std::size_t AppendImpl(const void *from) final + { + auto typedValue = static_cast(from); auto nbytes = 0; auto count = typedValue->size(); for (unsigned i = 0; i < count; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(&typedValue->data()[i]); - nbytes += fSubFields[0]->Append(itemValue); + nbytes += CallAppendOn(*fSubFields[0], &typedValue->data()[i]); } - Detail::RColumnElement elemIndex(&this->fNWritten); this->fNWritten += count; - fColumns[0]->Append(elemIndex); - return nbytes + sizeof(elemIndex); + fColumns[0]->Append(&this->fNWritten); + return nbytes + fColumns[0]->GetElement()->GetPackedSize(); } - void ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) final { - auto typedValue = value->Get(); + void ReadGlobalImpl(NTupleSize_t globalIndex, void *to) final + { + auto typedValue = static_cast(to); ClusterSize_t nItems; RClusterIndex collectionStart; fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &nItems); typedValue->resize(nItems); for (unsigned i = 0; i < nItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(&typedValue->data()[i]); - fSubFields[0]->Read(collectionStart + i, &itemValue); + CallReadOn(*fSubFields[0], collectionStart + i, &typedValue->data()[i]); } } @@ -1747,27 +2309,9 @@ public: RField& operator =(RField&& other) = default; ~RField() override = default; - void DestroyValue(const Detail::RFieldValue& value, bool dtorOnly = false) final { - auto vec = reinterpret_cast(value.GetRawPtr()); - vec->~RVec(); - if (!dtorOnly) - free(vec); - } - static std::string TypeName() { return "ROOT::VecOps::RVec<" + RField::TypeName() + ">"; } using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void* where) final { - return GenerateValue(where, ContainerT()); - } - Detail::RFieldValue CaptureValue(void *where) final { - return Detail::RFieldValue(true /* captureFlag */, this, static_cast(where)); - } size_t GetValueSize() const final { return sizeof(ContainerT); } size_t GetAlignment() const final { return std::alignment_of(); } }; @@ -1790,6 +2334,13 @@ protected: return std::make_unique>>(newName, std::move(items)); } + void GenerateValue(void *where) const final { new (where) ContainerT(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final + { + std::destroy_at(static_cast(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); + } + public: static std::string TypeName() { return "std::pair<" + RField::TypeName() + "," + RField::TypeName() + ">"; @@ -1806,20 +2357,6 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT&&... args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final { - return GenerateValue(where, ContainerT()); - } - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) final - { - reinterpret_cast(value.GetRawPtr())->~pair(); - if (!dtorOnly) - free(reinterpret_cast(value.GetRawPtr())); - } }; template @@ -1876,6 +2413,13 @@ protected: return std::make_unique>>(newName, std::move(items)); } + void GenerateValue(void *where) const final { new (where) ContainerT(); } + void DestroyValue(void *objPtr, bool dtorOnly = false) const final + { + std::destroy_at(static_cast(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); + } + public: static std::string TypeName() { return "std::tuple<" + BuildItemTypes() + ">"; } explicit RField(std::string_view name, std::vector> &&itemFields) @@ -1890,21 +2434,30 @@ public: ~RField() override = default; using Detail::RFieldBase::GenerateValue; - template - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where, ArgsT &&...args) - { - return Detail::RFieldValue(this, static_cast(where), std::forward(args)...); - } - ROOT::Experimental::Detail::RFieldValue GenerateValue(void *where) final - { - return GenerateValue(where, ContainerT()); - } - void DestroyValue(const Detail::RFieldValue &value, bool dtorOnly = false) final - { - reinterpret_cast(value.GetRawPtr())->~tuple(); - if (!dtorOnly) - free(reinterpret_cast(value.GetRawPtr())); - } +}; + +template +class RField> : public RBitsetField { +public: + static std::string TypeName() { return "std::bitset<" + std::to_string(N) + ">"; } + explicit RField(std::string_view name) : RBitsetField(name, N) {} + RField(RField &&other) = default; + RField &operator=(RField &&other) = default; + ~RField() override = default; + + using Detail::RFieldBase::GenerateValue; +}; + +template +class RField> : public RUniquePtrField { +public: + static std::string TypeName() { return "std::unique_ptr<" + RField::TypeName() + ">"; } + explicit RField(std::string_view name) : RUniquePtrField(name, TypeName(), std::make_unique>("_0")) {} + RField(RField &&other) = default; + RField &operator=(RField &&other) = default; + ~RField() override = default; + + using Detail::RFieldBase::GenerateValue; }; } // namespace Experimental diff --git a/tree/ntuple/v7/inc/ROOT/RFieldValue.hxx b/tree/ntuple/v7/inc/ROOT/RFieldValue.hxx deleted file mode 100644 index 2083d0c73b379..0000000000000 --- a/tree/ntuple/v7/inc/ROOT/RFieldValue.hxx +++ /dev/null @@ -1,89 +0,0 @@ -/// \file ROOT/RFieldValue.hxx -/// \ingroup NTuple ROOT7 -/// \author Jakob Blomer -/// \date 2018-10-09 -/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback -/// is welcome! - -/************************************************************************* - * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT7_RFieldValue -#define ROOT7_RFieldValue - -#include - -#include - -namespace ROOT { -namespace Experimental { - -namespace Detail { - -class RFieldBase; - -// clang-format off -/** -\class ROOT::Experimental::RFieldValue -\ingroup NTuple -\brief Represents transient storage of simple or complex C++ values. - -The data carried by the value is used by the computational code and it is supposed to be serialized on Fill -or deserialized into by reading. Only fields can generate their corresponding values. This class is a mere -wrapper around the memory location, it does not own it. Memory ownership is managed through the REntry. -*/ -// clang-format on -class RFieldValue { - friend class RFieldBase; - -protected: - /// Every value is connected to a field of the corresponding type that has created the value. - RFieldBase* fField; - /// The memory location containing (constructed) data of a certain C++ type - void* fRawPtr; - - /// For simple types, the mapped element drills through the layers from the C++ data representation - /// to the primitive columns. Otherwise, using fMappedElements is undefined. - /// Only RFieldBase uses fMappedElement - RColumnElementBase fMappedElement; - -public: - RFieldValue() : fField(nullptr), fRawPtr(nullptr) {} - - // Constructors that wrap around existing objects; prefixed with a bool in order to help the constructor overload - // selection. - RFieldValue(bool /*captureTag*/, Detail::RFieldBase* field, void* value) : fField(field), fRawPtr(value) {} - RFieldValue(bool /*captureTag*/, const Detail::RColumnElementBase& elem, Detail::RFieldBase* field, void* value) - : fField(field), fRawPtr(value), fMappedElement(elem) {} - - // Typed constructors that initialize the given memory location - template - RFieldValue(RFieldBase* field, T* where, ArgsT&&... args) : fField(field), fRawPtr(where) - { - new (where) T(std::forward(args)...); - } - - template - RFieldValue(const Detail::RColumnElementBase& elem, Detail::RFieldBase* field, T* where, ArgsT&&... args) - : fField(field), fRawPtr(where), fMappedElement(elem) - { - new (where) T(std::forward(args)...); - } - - template - T* Get() const { return static_cast(fRawPtr); } - - void* GetRawPtr() const { return fRawPtr; } - RFieldBase* GetField() const { return fField; } -}; - -} // namespace Detail -} // namespace Experimental -} // namespace ROOT - -#endif diff --git a/tree/ntuple/v7/inc/ROOT/RFieldVisitor.hxx b/tree/ntuple/v7/inc/ROOT/RFieldVisitor.hxx index 9a1e83527e69b..2857f231d7ce9 100644 --- a/tree/ntuple/v7/inc/ROOT/RFieldVisitor.hxx +++ b/tree/ntuple/v7/inc/ROOT/RFieldVisitor.hxx @@ -17,7 +17,6 @@ #define ROOT7_RFieldVisitor #include -#include #include #include @@ -46,18 +45,22 @@ public: virtual void VisitField(const Detail::RFieldBase &field) = 0; virtual void VisitFieldZero(const RFieldZero &field) { VisitField(field); } virtual void VisitArrayField(const RArrayField &field) { VisitField(field); } + virtual void VisitBitsetField(const RBitsetField &field) { VisitField(field); } virtual void VisitBoolField(const RField &field) { VisitField(field); } virtual void VisitClassField(const RClassField &field) { VisitField(field); } - virtual void VisitCollectionClassField(const RCollectionClassField &field) { VisitField(field); } + virtual void VisitProxiedCollectionField(const RProxiedCollectionField &field) { VisitField(field); } virtual void VisitRecordField(const RRecordField &field) { VisitField(field); } virtual void VisitClusterSizeField(const RField &field) { VisitField(field); } + virtual void VisitCardinalityField(const RCardinalityField &field) { VisitField(field); } virtual void VisitDoubleField(const RField &field) { VisitField(field); } + virtual void VisitEnumField(const REnumField &field) { VisitField(field); } virtual void VisitFloatField(const RField &field) { VisitField(field); } virtual void VisitCharField(const RField &field) { VisitField(field); } virtual void VisitInt8Field(const RField &field) { VisitField(field); } virtual void VisitInt16Field(const RField &field) { VisitField(field); } virtual void VisitIntField(const RField &field) { VisitField(field); } virtual void VisitInt64Field(const RField &field) { VisitField(field); } + virtual void VisitNullableField(const RNullableField &field) { VisitField(field); } virtual void VisitStringField(const RField &field) { VisitField(field); } virtual void VisitUInt16Field(const RField &field) { VisitField(field); } virtual void VisitUInt32Field(const RField &field) { VisitField(field); } @@ -174,7 +177,7 @@ public: }; private: - Detail::RFieldValue fValue; + Detail::RFieldBase::RValue fValue; /// The output is directed to fOutput which may differ from std::cout. std::ostream &fOutput; unsigned int fLevel; @@ -185,11 +188,11 @@ private: void PrintCollection(const Detail::RFieldBase &field); public: - RPrintValueVisitor(const Detail::RFieldValue &value, - std::ostream &output, - unsigned int level = 0, + RPrintValueVisitor(Detail::RFieldBase::RValue &&value, std::ostream &output, unsigned int level = 0, RPrintOptions options = RPrintOptions()) - : fValue(value), fOutput{output}, fLevel(level), fPrintOptions(options) {} + : fValue(std::move(value)), fOutput{output}, fLevel(level), fPrintOptions(options) + { + } void VisitField(const Detail::RFieldBase &field) final; @@ -207,13 +210,17 @@ public: void VisitUInt32Field(const RField &field) final; void VisitUInt64Field(const RField &field) final; + void VisitCardinalityField(const RCardinalityField &field) final; void VisitArrayField(const RArrayField &field) final; void VisitClassField(const RClassField &field) final; void VisitRecordField(const RRecordField &field) final; - void VisitCollectionClassField(const RCollectionClassField &field) final; + void VisitProxiedCollectionField(const RProxiedCollectionField &field) final; void VisitVectorField(const RVectorField &field) final; void VisitVectorBoolField(const RField> &field) final; void VisitRVecField(const RRVecField &field) final; + void VisitBitsetField(const RBitsetField &field) final; + void VisitNullableField(const RNullableField &field) final; + void VisitEnumField(const REnumField &field) final; }; diff --git a/tree/ntuple/v7/inc/ROOT/RNTuple.hxx b/tree/ntuple/v7/inc/ROOT/RNTuple.hxx index 4269c1cdef94d..d4b3f12606907 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTuple.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTuple.hxx @@ -62,15 +62,6 @@ enum class ENTupleInfo { kMetrics, // internals performance counters, requires that EnableMetrics() was called }; -/** - * Listing of the different entry output formats of RNTupleReader::Show() - */ -enum class ENTupleShowFormat { - kCurrentModelJSON, // prints a single entry/row with the current active model in JSON format. - kCompleteJSON, // prints a single entry/row with all the fields in JSON format. -}; - - #ifdef R__USE_IMT class TTaskGroup; class RNTupleImtTaskScheduler : public Detail::RPageStorage::RTaskScheduler { @@ -248,8 +239,7 @@ public: /// Shows the values of the i-th entry/row, starting with 0 for the first entry. By default, /// prints the output in JSON format. /// Uses the visitor pattern to traverse through each field of the given entry. - void Show(NTupleSize_t index, const ENTupleShowFormat format = ENTupleShowFormat::kCurrentModelJSON, - std::ostream &output = std::cout); + void Show(NTupleSize_t index, std::ostream &output = std::cout); /// Analogous to Fill(), fills the default entry of the model. Returns false at the end of the ntuple. /// On I/O errors, raises an exception. @@ -264,7 +254,7 @@ public: /// Fills a user provided entry after checking that the entry has been instantiated from the ntuple model void LoadEntry(NTupleSize_t index, REntry &entry) { for (auto& value : entry) { - value.GetField()->Read(index, &value); + value.Read(index); } } @@ -280,7 +270,7 @@ public: /// /// auto ntuple = RNTupleReader::Open("myNTuple", "some/file.root"); /// for (auto i : ntuple->GetEntryRange()) { - /// ntuple->Show(i, ENTupleShowFormat::kCompleteJSON); + /// ntuple->Show(i); /// } /// ~~~ RNTupleGlobalRange GetEntryRange() { return RNTupleGlobalRange(0, GetNEntries()); } @@ -366,6 +356,8 @@ triggered by Flush() or by destructing the ntuple. On I/O errors, an exception */ // clang-format on class RNTupleWriter { + friend RNTupleModel::RUpdater; + private: /// The page sink's parallel page compression scheduler if IMT is on. /// Needs to be destructed after the page sink is destructed and so declared before. @@ -421,7 +413,7 @@ public: std::size_t bytesWritten = 0; for (auto& value : entry) { - bytesWritten += value.GetField()->Append(value); + bytesWritten += value.Append(); } fUnzippedClusterSize += bytesWritten; fNEntries++; @@ -438,6 +430,30 @@ public: const Detail::RNTupleMetrics &GetMetrics() const { return fMetrics; } const RNTupleModel *GetModel() const { return fModel.get(); } + + /// Get a `RNTupleModel::RUpdater` that provides limited support for incremental updates to the underlying + /// model, e.g. addition of new fields. + /// + /// **Example: add a new field after the model has been used to construct a `RNTupleWriter` object** + /// ~~~ {.cpp} + /// #include + /// using ROOT::Experimental::RNTupleModel; + /// using ROOT::Experimental::RNTupleWriter; + /// + /// auto model = RNTupleModel::Create(); + /// auto fldFloat = model->MakeField("fldFloat"); + /// auto writer = RNTupleWriter::Recreate(std::move(model), "myNTuple", "some/file.root"); + /// auto updater = writer->CreateModelUpdater(); + /// updater->BeginUpdate(); + /// updater->AddField(std::make_unique>("pt")); + /// updater->CommitUpdate(); + /// + /// // ... + /// ~~~ + std::unique_ptr CreateModelUpdater() + { + return std::unique_ptr(new RNTupleModel::RUpdater(*this)); + } }; // clang-format off @@ -464,7 +480,7 @@ public: void Fill() { Fill(fDefaultEntry.get()); } void Fill(REntry *entry) { for (auto &value : *entry) { - value.GetField()->Append(value); + value.Append(); } fOffset++; } diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleDescriptor.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleDescriptor.hxx index 456c0ece854dc..048993439a0e6 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleDescriptor.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleDescriptor.hxx @@ -1,6 +1,7 @@ /// \file ROOT/RNTupleDescriptor.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer +/// \author Javier Lopez-Gomez /// \date 2018-07-19 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -44,7 +45,8 @@ class RNTupleDescriptorBuilder; class RNTupleModel; namespace Detail { - class RFieldBase; +class RColumnElementBase; +class RFieldBase; } @@ -71,6 +73,8 @@ private: std::string fFieldDescription; /// The C++ type that was used when writing the field std::string fTypeName; + /// A typedef or using directive that resolved to the type name during field creation + std::string fTypeAlias; /// The number of elements per entry for fixed-size arrays std::uint64_t fNRepetitions = 0; /// The structural information carried by this field in the data model tree @@ -101,6 +105,7 @@ public: std::string GetFieldName() const { return fFieldName; } std::string GetFieldDescription() const { return fFieldDescription; } std::string GetTypeName() const { return fTypeName; } + std::string GetTypeAlias() const { return fTypeAlias; } std::uint64_t GetNRepetitions() const { return fNRepetitions; } ENTupleStructure GetStructure() const { return fStructure; } DescriptorId_t GetParentId() const { return fParentId; } @@ -120,13 +125,19 @@ class RColumnDescriptor { friend class RNTupleDescriptorBuilder; private: - DescriptorId_t fColumnId = kInvalidDescriptorId; + /// The actual column identifier, which is the link to the corresponding field + DescriptorId_t fLogicalColumnId = kInvalidDescriptorId; + /// Usually identical to the logical column ID, except for alias columns where it references the shadowed column + DescriptorId_t fPhysicalColumnId = kInvalidDescriptorId; /// Contains the column type and whether it is sorted RColumnModel fModel; /// Every column belongs to one and only one field DescriptorId_t fFieldId = kInvalidDescriptorId; /// A field can be serialized into several columns, which are numbered from zero to $n$ std::uint32_t fIndex; + /// Specifies the index for the first stored element for this column. For deferred columns the value is greater + /// than 0 + std::uint64_t fFirstElementIndex = 0U; public: RColumnDescriptor() = default; @@ -139,10 +150,14 @@ public: /// Get a copy of the descriptor RColumnDescriptor Clone() const; - DescriptorId_t GetId() const { return fColumnId; } + DescriptorId_t GetLogicalId() const { return fLogicalColumnId; } + DescriptorId_t GetPhysicalId() const { return fPhysicalColumnId; } RColumnModel GetModel() const { return fModel; } std::uint32_t GetIndex() const { return fIndex; } DescriptorId_t GetFieldId() const { return fFieldId; } + bool IsAliasColumn() const { return fPhysicalColumnId != fLogicalColumnId; } + std::uint64_t GetFirstElementIndex() const { return fFirstElementIndex; } + bool IsDeferredColumn() const { return fFirstElementIndex > 0; } }; // clang-format off @@ -160,7 +175,7 @@ class RColumnGroupDescriptor { private: DescriptorId_t fColumnGroupId = kInvalidDescriptorId; - std::unordered_set fColumnIds; + std::unordered_set fPhysicalColumnIds; public: RColumnGroupDescriptor() = default; @@ -172,9 +187,12 @@ public: bool operator==(const RColumnGroupDescriptor &other) const; DescriptorId_t GetId() const { return fColumnGroupId; } - const std::unordered_set &GetColumnIds() const { return fColumnIds; } - bool Contains(DescriptorId_t columnId) const { return fColumnIds.empty() || fColumnIds.count(columnId) > 0; } - bool HasAllColumns() const { return fColumnIds.empty(); } + const std::unordered_set &GetPhysicalColumnIds() const { return fPhysicalColumnIds; } + bool Contains(DescriptorId_t physicalId) const + { + return fPhysicalColumnIds.empty() || fPhysicalColumnIds.count(physicalId) > 0; + } + bool HasAllColumns() const { return fPhysicalColumnIds.empty(); } }; // clang-format off @@ -196,10 +214,10 @@ class RClusterDescriptor { public: /// The window of element indexes of a particular column in a particular cluster struct RColumnRange { - DescriptorId_t fColumnId = kInvalidDescriptorId; + DescriptorId_t fPhysicalColumnId = kInvalidDescriptorId; /// A 64bit element index NTupleSize_t fFirstElementIndex = kInvalidNTupleIndex; - /// A 32bit value for the number of column elements in the cluster + /// The number of column elements in the cluster ClusterSize_t fNElements = kInvalidClusterIndex; /// The usual format for ROOT compression settings (see Compression.h). /// The pages of a particular column in a particular cluster are all compressed with the same settings. @@ -209,7 +227,7 @@ public: // Should this be done on the field level? bool operator==(const RColumnRange &other) const { - return fColumnId == other.fColumnId && fFirstElementIndex == other.fFirstElementIndex && + return fPhysicalColumnId == other.fPhysicalColumnId && fFirstElementIndex == other.fFirstElementIndex && fNElements == other.fNElements && fCompressionSettings == other.fCompressionSettings; } @@ -224,7 +242,7 @@ public: /// the page belongs struct RPageInfo { /// The sum of the elements of all the pages must match the corresponding fNElements field in fColumnRanges - ClusterSize_t fNElements = kInvalidClusterIndex; + std::uint32_t fNElements = std::uint32_t(-1); /// The meaning of fLocator depends on the storage backend. RNTupleLocator fLocator; @@ -251,7 +269,7 @@ public: RPageRange Clone() const { RPageRange clone; - clone.fColumnId = fColumnId; + clone.fPhysicalColumnId = fPhysicalColumnId; clone.fPageInfos = fPageInfos; return clone; } @@ -259,12 +277,20 @@ public: /// Find the page in the RPageRange that contains the given element. The element must exist. RPageInfoExtended Find(RClusterSize::ValueType idxInCluster) const; - DescriptorId_t fColumnId = kInvalidDescriptorId; + DescriptorId_t fPhysicalColumnId = kInvalidDescriptorId; std::vector fPageInfos; bool operator==(const RPageRange &other) const { - return fColumnId == other.fColumnId && fPageInfos == other.fPageInfos; + return fPhysicalColumnId == other.fPhysicalColumnId && fPageInfos == other.fPageInfos; } + + /// Extend this RPageRange to fit the given RColumnRange, i.e. prepend as many synthetic RPageInfos as needed to + /// cover the range in `columnRange`. `RPageInfo`s are constructed to contain as many elements of type `element` + /// given a page size limit of `pageSize` (in bytes); the locator for the referenced pages is `kTypePageZero`. + /// This function is used to make up `RPageRange`s for clusters that contain deferred columns. + /// \return The number of column elements covered by the synthesized RPageInfos + std::size_t ExtendToFitColumnRange(const RColumnRange &columnRange, const Detail::RColumnElementBase &element, + std::size_t pageSize); }; private: @@ -299,17 +325,17 @@ public: DescriptorId_t GetId() const { return fClusterId; } NTupleSize_t GetFirstEntryIndex() const { return fFirstEntryIndex; } ClusterSize_t GetNEntries() const { return fNEntries; } - const RColumnRange &GetColumnRange(DescriptorId_t columnId) const + const RColumnRange &GetColumnRange(DescriptorId_t physicalId) const { EnsureHasPageLocations(); - return fColumnRanges.at(columnId); + return fColumnRanges.at(physicalId); } - const RPageRange &GetPageRange(DescriptorId_t columnId) const + const RPageRange &GetPageRange(DescriptorId_t physicalId) const { EnsureHasPageLocations(); - return fPageRanges.at(columnId); + return fPageRanges.at(physicalId); } - bool ContainsColumn(DescriptorId_t columnId) const; + bool ContainsColumn(DescriptorId_t physicalId) const; std::unordered_set GetColumnIds() const; std::uint64_t GetBytesOnStorage() const; bool HasPageLocations() const { return fHasPageLocations; } @@ -384,6 +410,9 @@ writte struct. This allows for forward and backward compatibility when the meta- class RNTupleDescriptor { friend class RNTupleDescriptorBuilder; +public: + class RHeaderExtension; + private: /// The ntuple name needs to be unique in a given storage location (file) std::string fName; @@ -394,6 +423,7 @@ private: std::uint64_t fOnDiskFooterSize = 0; ///< Like fOnDiskHeaderSize, contains both cluster summaries and page locations std::uint64_t fNEntries = 0; ///< Updated by the descriptor builder when the cluster summaries are added + std::uint64_t fNPhysicalColumns = 0; ///< Updated by the descriptor builder when columns are added /** * Once constructed by an RNTupleDescriptorBuilder, the descriptor is mostly immutable except for set of @@ -410,8 +440,43 @@ private: /// May contain only a subset of all the available clusters, e.g. the clusters of the current file /// from a chain of files std::unordered_map fClusterDescriptors; + std::unique_ptr fHeaderExtension; public: + // clang-format off + /** + \class ROOT::Experimental::RNTupleDescriptor::RHeaderExtension + \ingroup NTuple + \brief Summarizes information about fields and the corresponding columns that were added after the header has been serialized + */ + // clang-format on + class RHeaderExtension { + friend class RNTupleDescriptorBuilder; + + private: + /// Contains the list of field IDs that are part of the header extension; the corresponding columns are + /// available via `GetColumnIterable()`. + std::vector fFields; + /// Number of logical and physical columns; updated by the descriptor builder when columns are added + std::uint64_t fNLogicalColumns = 0; + std::uint64_t fNPhysicalColumns = 0; + + void AddFieldId(DescriptorId_t id) { fFields.push_back(id); } + void AddColumn(bool isAliasColumn) + { + fNLogicalColumns++; + if (!isAliasColumn) + fNPhysicalColumns++; + } + + public: + std::size_t GetNFields() const { return fFields.size(); } + std::size_t GetNLogicalColumns() const { return fNLogicalColumns; } + std::size_t GetNPhysicalColumns() const { return fNPhysicalColumns; } + /// Return a vector containing the IDs of the top-level fields defined in the extension header + std::vector GetTopLevelFields(const RNTupleDescriptor &desc) const; + }; + // clang-format off /** \class ROOT::Experimental::RNTupleDescriptor::RColumnDescriptorIterable @@ -425,6 +490,8 @@ public: const RNTupleDescriptor &fNTuple; /// The descriptor ids of the columns ordered by index id std::vector fColumns = {}; + + void CollectColumnIds(DescriptorId_t fieldId); public: class RIterator { private: @@ -449,16 +516,9 @@ public: bool operator==(const iterator &rh) const { return fIndex == rh.fIndex; } }; - RColumnDescriptorIterable(const RNTupleDescriptor &ntuple, const RFieldDescriptor &field) - : fNTuple(ntuple) - { - for (unsigned int i = 0; true; ++i) { - auto columnId = ntuple.FindColumnId(field.GetId(), i); - if (columnId == kInvalidDescriptorId) - break; - fColumns.emplace_back(columnId); - } - } + RColumnDescriptorIterable(const RNTupleDescriptor &ntuple, const RFieldDescriptor &field); + RColumnDescriptorIterable(const RNTupleDescriptor &ntuple); + RIterator begin() { return RIterator(fNTuple, fColumns, 0); } RIterator end() { return RIterator(fNTuple, fColumns, fColumns.size()); } }; @@ -477,6 +537,7 @@ public: /// The descriptor ids of the child fields. These may be sorted using /// a comparison function. std::vector fFieldChildren = {}; + public: class RIterator { private: @@ -668,6 +729,10 @@ public: return GetFieldIterable(GetFieldZeroId(), comparator); } + RColumnDescriptorIterable GetColumnIterable() const + { + return RColumnDescriptorIterable(*this); + } RColumnDescriptorIterable GetColumnIterable(const RFieldDescriptor &fieldDesc) const { return RColumnDescriptorIterable(*this, fieldDesc); @@ -688,13 +753,14 @@ public: std::string GetDescription() const { return fDescription; } std::size_t GetNFields() const { return fFieldDescriptors.size(); } - std::size_t GetNColumns() const { return fColumnDescriptors.size(); } + std::size_t GetNLogicalColumns() const { return fColumnDescriptors.size(); } + std::size_t GetNPhysicalColumns() const { return fNPhysicalColumns; } std::size_t GetNClusterGroups() const { return fClusterGroupDescriptors.size(); } std::size_t GetNClusters() const { return fClusterDescriptors.size(); } /// We know the number of entries from adding the cluster summaries NTupleSize_t GetNEntries() const { return fNEntries; } - NTupleSize_t GetNElements(DescriptorId_t columnId) const; + NTupleSize_t GetNElements(DescriptorId_t physicalColumnId) const; /// Returns the logical parent of all top-level NTuple data fields. DescriptorId_t GetFieldZeroId() const; @@ -702,8 +768,9 @@ public: DescriptorId_t FindFieldId(std::string_view fieldName, DescriptorId_t parentId) const; /// Searches for a top-level field DescriptorId_t FindFieldId(std::string_view fieldName) const; - DescriptorId_t FindColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const; - DescriptorId_t FindClusterId(DescriptorId_t columnId, NTupleSize_t index) const; + DescriptorId_t FindLogicalColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const; + DescriptorId_t FindPhysicalColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const; + DescriptorId_t FindClusterId(DescriptorId_t physicalColumnId, NTupleSize_t index) const; DescriptorId_t FindNextClusterId(DescriptorId_t clusterId) const; DescriptorId_t FindPrevClusterId(DescriptorId_t clusterId) const; @@ -711,6 +778,9 @@ public: /// In case of invalid field ID, an empty string is returned. std::string GetQualifiedFieldName(DescriptorId_t fieldId) const; + /// Return header extension information; if the descriptor does not have a header extension, return `nullptr` + const RHeaderExtension *GetHeaderExtension() const { return fHeaderExtension.get(); } + /// Methods to load and drop cluster details RResult AddClusterDetails(RClusterDescriptor &&clusterDesc); RResult DropClusterDetails(DescriptorId_t clusterId); @@ -741,8 +811,14 @@ public: /// Make an empty column descriptor builder. RColumnDescriptorBuilder() = default; - RColumnDescriptorBuilder& ColumnId(DescriptorId_t columnId) { - fColumn.fColumnId = columnId; + RColumnDescriptorBuilder &LogicalColumnId(DescriptorId_t logicalColumnId) + { + fColumn.fLogicalColumnId = logicalColumnId; + return *this; + } + RColumnDescriptorBuilder &PhysicalColumnId(DescriptorId_t physicalColumnId) + { + fColumn.fPhysicalColumnId = physicalColumnId; return *this; } RColumnDescriptorBuilder& Model(const RColumnModel &model) { @@ -757,6 +833,11 @@ public: fColumn.fIndex = index; return *this; } + RColumnDescriptorBuilder &FirstElementIndex(std::uint64_t firstElementIdx) + { + fColumn.fFirstElementIndex = firstElementIdx; + return *this; + } DescriptorId_t GetFieldId() const { return fColumn.fFieldId; } /// Attempt to make a column descriptor. This may fail if the column /// was not given enough information to make a proper descriptor. @@ -826,6 +907,11 @@ public: fField.fTypeName = typeName; return *this; } + RFieldDescriptorBuilder &TypeAlias(const std::string &typeAlias) + { + fField.fTypeAlias = typeAlias; + return *this; + } RFieldDescriptorBuilder& NRepetitions(std::uint64_t nRepetitions) { fField.fNRepetitions = nRepetitions; return *this; @@ -862,9 +948,14 @@ public: { } - RResult CommitColumnRange(DescriptorId_t columnId, std::uint64_t firstElementIndex, + RResult CommitColumnRange(DescriptorId_t physicalId, std::uint64_t firstElementIndex, std::uint32_t compressionSettings, const RClusterDescriptor::RPageRange &pageRange); + /// Add column and page ranges for deferred columns missing in this cluster. The locator type for the synthesized + /// page ranges is `kTypePageZero`. All the page sources must be able to populate the 'zero' page from such locator. + /// Any call to `CommitColumnRange()` should happen before calling this function. + RClusterDescriptorBuilder &AddDeferredColumnRanges(const RNTupleDescriptor &desc); + /// Move out the full cluster descriptor including page locations RResult MoveDescriptor(); }; @@ -928,7 +1019,7 @@ public: fColumnGroup.fColumnGroupId = columnGroupId; return *this; } - void AddColumn(DescriptorId_t columnId) { fColumnGroup.fColumnIds.insert(columnId); } + void AddColumn(DescriptorId_t physicalId) { fColumnGroup.fPhysicalColumnIds.insert(physicalId); } RResult MoveDescriptor(); }; @@ -967,7 +1058,8 @@ public: void AddField(const RFieldDescriptor& fieldDesc); RResult AddFieldLink(DescriptorId_t fieldId, DescriptorId_t linkId); - void AddColumn(DescriptorId_t columnId, DescriptorId_t fieldId, const RColumnModel &model, std::uint32_t index); + void AddColumn(DescriptorId_t logicalId, DescriptorId_t physicalId, DescriptorId_t fieldId, + const RColumnModel &model, std::uint32_t index, std::uint64_t firstElementIdx = 0U); RResult AddColumn(RColumnDescriptor &&columnDesc); RResult AddClusterSummary(DescriptorId_t clusterId, std::uint64_t firstEntry, std::uint64_t nEntries); @@ -979,6 +1071,10 @@ public: /// Clears so-far stored clusters, fields, and columns and return to a pristine ntuple descriptor void Reset(); + + /// Mark the beginning of the header extension; any fields and columns added after a call to this function are + /// annotated as begin part of the header extension. + void BeginHeaderExtension(); }; } // namespace Experimental diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleModel.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleModel.hxx index 25e098e594d0f..61e8226701cdb 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleModel.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleModel.hxx @@ -17,13 +17,16 @@ #define ROOT7_RNTupleModel #include +#include #include #include -#include #include #include +#include #include +#include +#include #include #include @@ -31,6 +34,34 @@ namespace ROOT { namespace Experimental { class RCollectionNTupleWriter; +class RNTupleModel; +class RNTupleWriter; + +namespace Detail { + +// clang-format off +/** +\class ROOT::Experimental::Detail::RNTupleModelChangeset +\ingroup NTuple +\brief The incremental changes to a `RNTupleModel` + +Represents a set of alterations to a `RNTupleModel` that happened after the model is used to initialize a `RPageSink` +instance. This object can be used to communicate metadata updates to a `RPageSink`. +You will not normally use this directly; see `RNTupleModel::RUpdater` instead. +*/ +// clang-format on +struct RNTupleModelChangeset { + RNTupleModel &fModel; + /// Points to the fields in fModel that were added as part of an updater transaction + std::vector fAddedFields; + /// Points to the projected fields in fModel that were added as part of an updater transaction + std::vector fAddedProjectedFields; + + RNTupleModelChangeset(RNTupleModel &model) : fModel(model) {} + bool IsEmpty() const { return fAddedFields.empty() && fAddedProjectedFields.empty(); } +}; + +} // namespace Detail // clang-format off /** @@ -44,14 +75,110 @@ that faciliates checking whether entries are compatible with it (i.e.: have been */ // clang-format on class RNTupleModel { +public: + /// A wrapper over a field name and an optional description; used in `AddField()` and `RUpdater::AddField()` + struct NameWithDescription_t { + NameWithDescription_t(const char *name) : fName(name) {} + NameWithDescription_t(std::string_view name) : fName(name) {} + NameWithDescription_t(std::string_view name, std::string_view descr) : fName(name), fDescription(descr) {} + + std::string_view fName; + std::string_view fDescription = ""; + }; + + /// Projected fields are fields whose columns are reused from existing fields. Projected fields are not attached + /// to the models zero field. Only the real source fields are written to, projected fields are stored as meta-data + /// (header) information only. Only top-level projected fields are supported because otherwise the layout of types + /// could be altered in unexpected ways. + /// All projected fields and the source fields used to back them are kept in this class. + class RProjectedFields { + public: + /// The map keys are the projected target fields, the map values are the backing source fields + /// Note that sub fields are treated individually and indepently of their parent field + using FieldMap_t = std::unordered_map; + + private: + explicit RProjectedFields(std::unique_ptr fieldZero) : fFieldZero(std::move(fieldZero)) {} + /// The projected fields are attached to this zero field + std::unique_ptr fFieldZero; + /// Maps the source fields from fModel to the target projected fields attached to fFieldZero + FieldMap_t fFieldMap; + /// The model this set of projected fields belongs to + const RNTupleModel *fModel; + + /// Asserts that the passed field is a valid target of the source field provided in the field map. + /// Checks the field without looking into sub fields. + RResult EnsureValidMapping(const Detail::RFieldBase *target, const FieldMap_t &fieldMap); + + public: + explicit RProjectedFields(const RNTupleModel *model) : fFieldZero(std::make_unique()), fModel(model) + { + } + RProjectedFields(const RProjectedFields &) = delete; + RProjectedFields(RProjectedFields &&) = default; + RProjectedFields &operator=(const RProjectedFields &) = delete; + RProjectedFields &operator=(RProjectedFields &&) = default; + ~RProjectedFields() = default; + + /// The new model needs to be a clone of fModel + std::unique_ptr Clone(const RNTupleModel *newModel) const; + + RFieldZero *GetFieldZero() const { return fFieldZero.get(); } + const Detail::RFieldBase *GetSourceField(const Detail::RFieldBase *target) const; + /// Adds a new projected field. The field map needs to provide valid source fields of fModel for 'field' + /// and each of its sub fields. + RResult Add(std::unique_ptr field, const FieldMap_t &fieldMap); + bool IsEmpty() const { return fFieldZero->begin() == fFieldZero->end(); } + }; + + /// A model is usually immutable after passing it to an `RNTupleWriter`. However, for the rare + /// cases that require changing the model after the fact, `RUpdater` provides limited support for + /// incremental updates, e.g. addition of new fields. + /// + /// See `RNTupleWriter::CreateModelUpdater()` for an example. + class RUpdater { + private: + RNTupleWriter &fWriter; + Detail::RNTupleModelChangeset fOpenChangeset; + + public: + explicit RUpdater(RNTupleWriter &writer); + ~RUpdater() { CommitUpdate(); } + /// Begin a new set of alterations to the underlying model. As a side effect, all `REntry` instances related to + /// the model are invalidated. + void BeginUpdate(); + /// Commit changes since the last call to `BeginUpdate()`. All the invalidated `REntry`s remain invalid. + /// `CreateEntry()` or `CreateBareEntry()` can be used to create an `REntry` that matching the new model. + /// Upon completion, `BeginUpdate()` can be called again to begin a new set of changes. + void CommitUpdate(); + + void AddField(std::unique_ptr field); + template + void AddField(const NameWithDescription_t &fieldNameDesc, T *fromWhere) + { + fOpenChangeset.fModel.AddField(fieldNameDesc, fromWhere); + auto fieldZero = fOpenChangeset.fModel.GetFieldZero(); + auto it = std::find_if(fieldZero->begin(), fieldZero->end(), + [&](const auto &f) { return f.GetName() == fieldNameDesc.fName; }); + R__ASSERT(it != fieldZero->end()); + fOpenChangeset.fAddedFields.emplace_back(&(*it)); + } + + RResult AddProjectedField(std::unique_ptr field, + std::function mapping); + }; + +private: /// Hierarchy of fields consisting of simple types and collections (sub trees) std::unique_ptr fFieldZero; /// Contains field values corresponding to the created top-level fields std::unique_ptr fDefaultEntry; - /// Keeps track of which field names are taken. + /// Keeps track of which field names are taken, including projected field names. std::unordered_set fFieldNames; /// Free text set by the user std::string fDescription; + /// The set of projected top-level fields + std::unique_ptr fProjectedFields; /// Upon freezing, every model has a unique ID to distingusish it from other models. Cloning preserves the ID. /// Entries are linked to models via the ID. std::uint64_t fModelId = 0; @@ -76,9 +203,10 @@ public: std::unique_ptr Clone() const; static std::unique_ptr Create(); /// A bare model has no default entry - static std::unique_ptr CreateBare() { return std::unique_ptr(new RNTupleModel()); } + static std::unique_ptr CreateBare(); - /// Creates a new field and a corresponding tree value that is managed by a shared pointer. + /// Creates a new field given a `name` or `{name, description}` pair and a + /// corresponding tree value that is managed by a shared pointer. /// /// **Example: create some fields and fill an %RNTuple** /// ~~~ {.cpp} @@ -102,6 +230,7 @@ public: /// } /// } /// ~~~ + /// /// **Example: create a field with an initial value** /// ~~~ {.cpp} /// #include @@ -111,14 +240,6 @@ public: /// // pt's initial value is 42.0 /// auto pt = model->MakeField("pt", 42.0); /// ~~~ - template - std::shared_ptr MakeField(std::string_view fieldName, ArgsT&&... args) { - return MakeField({fieldName, ""}, std::forward(args)...); - } - - /// Creates a new field given a `{name, description}` pair and a corresponding tree value that - /// is managed by a shared pointer. - /// /// **Example: create a field with a description** /// ~~~ {.cpp} /// #include @@ -130,13 +251,13 @@ public: /// }); /// ~~~ template - std::shared_ptr MakeField(std::pair fieldNameDesc, + std::shared_ptr MakeField(const NameWithDescription_t &fieldNameDesc, ArgsT&&... args) { EnsureNotFrozen(); - EnsureValidFieldName(fieldNameDesc.first); - auto field = std::make_unique>(fieldNameDesc.first); - field->SetDescription(fieldNameDesc.second); + EnsureValidFieldName(fieldNameDesc.fName); + auto field = std::make_unique>(fieldNameDesc.fName); + field->SetDescription(fieldNameDesc.fDescription); std::shared_ptr ptr; if (fDefaultEntry) ptr = fDefaultEntry->AddValue(field.get(), std::forward(args)...); @@ -151,25 +272,25 @@ public: /// Throws an exception if fromWhere is null. template - void AddField(std::string_view fieldName, T* fromWhere) { - AddField({fieldName, ""}, fromWhere); - } - - /// Throws an exception if fromWhere is null. - template - void AddField(std::pair fieldNameDesc, T* fromWhere) { + void AddField(const NameWithDescription_t &fieldNameDesc, T* fromWhere) { EnsureNotFrozen(); EnsureNotBare(); if (!fromWhere) throw RException(R__FAIL("null field fromWhere")); - EnsureValidFieldName(fieldNameDesc.first); + EnsureValidFieldName(fieldNameDesc.fName); - auto field = std::make_unique>(fieldNameDesc.first); - field->SetDescription(fieldNameDesc.second); - fDefaultEntry->CaptureValue(field->CaptureValue(fromWhere)); + auto field = std::make_unique>(fieldNameDesc.fName); + field->SetDescription(fieldNameDesc.fDescription); + fDefaultEntry->AddValue(field->BindValue(fromWhere)); fFieldZero->Attach(std::move(field)); } + /// Adds a top-level field based on existing fields. The mapping function is called with the qualified field names + /// of the provided field and the subfields. It should return the qualified field names used as a mapping source. + /// Projected fields can only be used for models used to write data. + RResult AddProjectedField(std::unique_ptr field, + std::function mapping); + template T *Get(std::string_view fieldName) const { @@ -177,7 +298,10 @@ public: return fDefaultEntry->Get(fieldName); } + const RProjectedFields &GetProjectedFields() const { return *fProjectedFields; } + void Freeze(); + void Unfreeze(); bool IsFrozen() const { return fModelId != 0; } std::uint64_t GetModelId() const { return fModelId; } diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleOptions.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleOptions.hxx index de6c7349dfc09..5d3090360ac2e 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleOptions.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleOptions.hxx @@ -47,6 +47,7 @@ All page sink classes need to support the common options. */ // clang-format on class RNTupleWriteOptions { +protected: int fCompression{RCompressionSetting::EDefaults::kUseAnalysis}; ENTupleContainerFormat fContainerFormat{ENTupleContainerFormat::kTFile}; /// Approximation of the target compressed cluster size @@ -60,8 +61,16 @@ class RNTupleWriteOptions { /// fApproxUnzippedPageSize/2 and fApproxUnzippedPageSize * 1.5 in size. std::size_t fApproxUnzippedPageSize = 64 * 1024; bool fUseBufferedWrite = true; + /// If set, 64bit index columns are replaced by 32bit index columns. This limits the cluster size to 512MB + /// but it can result in smaller file sizes for data sets with many collections and lz4 or no compression. + bool fHasSmallClusters = false; public: + /// A maximum size of 512MB still allows for a vector of bool to be stored in a small cluster. This is the + /// worst case wrt. the maximum required size of the index column. A 32bit index column can address 512MB + /// of 1-bit (on disk size) bools. + static constexpr std::uint64_t kMaxSmallClusterSize = 512 * 1024 * 1024; + virtual ~RNTupleWriteOptions() = default; virtual std::unique_ptr Clone() const; @@ -85,6 +94,9 @@ public: bool GetUseBufferedWrite() const { return fUseBufferedWrite; } void SetUseBufferedWrite(bool val) { fUseBufferedWrite = val; } + + bool GetHasSmallClusters() const { return fHasSmallClusters; } + void SetHasSmallClusters(bool val) { fHasSmallClusters = val; } }; // clang-format off @@ -95,7 +107,11 @@ public: */ // clang-format on class RNTupleWriteOptionsDaos : public RNTupleWriteOptions { - std::string fObjectClass{"SX"}; + std::string fObjectClass{"SX"}; + /// The maximum cage size is set to the equivalent of 16 uncompressed pages - 1MiB by default. Empirically, such a + /// cage size yields acceptable results in throughput and page granularity for most use cases. A `fMaxCageSize` of 0 + /// disables the caging mechanism. + uint32_t fMaxCageSize = 16 * RNTupleWriteOptions::fApproxUnzippedPageSize; public: ~RNTupleWriteOptionsDaos() override = default; @@ -107,6 +123,12 @@ public: /// `OC_xxx` constant defined in `daos_obj_class.h` may be used here without /// the OC_ prefix. void SetObjectClass(const std::string &val) { fObjectClass = val; } + + uint32_t GetMaxCageSize() const { return fMaxCageSize; } + /// Set the upper bound for page concatenation into cages, in bytes. It is assumed + /// that cage size will be no smaller than the approximate uncompressed page size. + /// To disable page concatenation, set this value to 0. + void SetMaxCageSize(uint32_t cageSz) { fMaxCageSize = cageSz; } }; // clang-format off diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleSerialize.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleSerialize.hxx index 68ee9b1adaa11..a44a9aec4f1d2 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleSerialize.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleSerialize.hxx @@ -1,6 +1,7 @@ /// \file ROOT/RNTupleSerialize.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer +/// \author Javier Lopez-Gomez /// \date 2021-08-02 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -59,11 +60,11 @@ public: static constexpr std::uint32_t kReleaseCandidateTag = 1; static constexpr std::uint16_t kFlagRepetitiveField = 0x01; - static constexpr std::uint16_t kFlagAliasField = 0x02; static constexpr std::uint32_t kFlagSortAscColumn = 0x01; static constexpr std::uint32_t kFlagSortDesColumn = 0x02; static constexpr std::uint32_t kFlagNonNegativeColumn = 0x04; + static constexpr std::uint32_t kFlagDeferredColumn = 0x08; static constexpr DescriptorId_t kZeroFieldId = std::uint64_t(-2); @@ -85,59 +86,85 @@ public: }; /// The serialization context is used for the piecewise serialization of a descriptor. During header serialization, - /// the mapping of in-memory field and column IDs to physical IDs is built so that it can be used for the + /// the mapping of in-memory field and column IDs to on-disk IDs is built so that it can be used for the /// footer serialization in a second step. class RContext { private: std::uint32_t fHeaderSize = 0; std::uint32_t fHeaderCrc32 = 0; - std::map fMem2PhysFieldIDs; - std::map fMem2PhysColumnIDs; - std::map fMem2PhysClusterIDs; - std::map fMem2PhysClusterGroupIDs; - std::vector fPhys2MemFieldIDs; - std::vector fPhys2MemColumnIDs; - std::vector fPhys2MemClusterIDs; - std::vector fPhys2MemClusterGroupIDs; + std::map fMem2OnDiskFieldIDs; + std::map fMem2OnDiskColumnIDs; + std::map fMem2OnDiskClusterIDs; + std::map fMem2OnDiskClusterGroupIDs; + std::vector fOnDisk2MemFieldIDs; + std::vector fOnDisk2MemColumnIDs; + std::vector fOnDisk2MemClusterIDs; + std::vector fOnDisk2MemClusterGroupIDs; + std::size_t fHeaderExtensionOffset = -1U; public: void SetHeaderSize(std::uint32_t size) { fHeaderSize = size; } std::uint32_t GetHeaderSize() const { return fHeaderSize; } void SetHeaderCRC32(std::uint32_t crc32) { fHeaderCrc32 = crc32; } std::uint32_t GetHeaderCRC32() const { return fHeaderCrc32; } + /// Map an in-memory field ID to its on-disk counterpart. It is allowed to call this function multiple times for + /// the same `memId`, in which case the return value is the on-disk ID assigned on the first call. DescriptorId_t MapFieldId(DescriptorId_t memId) { - auto physId = fPhys2MemFieldIDs.size(); - fMem2PhysFieldIDs[memId] = physId; - fPhys2MemFieldIDs.push_back(memId); - return physId; + auto onDiskId = fOnDisk2MemFieldIDs.size(); + const auto &p = fMem2OnDiskFieldIDs.try_emplace(memId, onDiskId); + if (p.second) + fOnDisk2MemFieldIDs.push_back(memId); + return (*p.first).second; } + /// Map an in-memory column ID to its on-disk counterpart. It is allowed to call this function multiple times for + /// the same `memId`, in which case the return value is the on-disk ID assigned on the first call. DescriptorId_t MapColumnId(DescriptorId_t memId) { - auto physId = fPhys2MemColumnIDs.size(); - fMem2PhysColumnIDs[memId] = physId; - fPhys2MemColumnIDs.push_back(memId); - return physId; + auto onDiskId = fOnDisk2MemColumnIDs.size(); + const auto &p = fMem2OnDiskColumnIDs.try_emplace(memId, onDiskId); + if (p.second) + fOnDisk2MemColumnIDs.push_back(memId); + return (*p.first).second; } DescriptorId_t MapClusterId(DescriptorId_t memId) { - auto physId = fPhys2MemClusterIDs.size(); - fMem2PhysClusterIDs[memId] = physId; - fPhys2MemClusterIDs.push_back(memId); - return physId; + auto onDiskId = fOnDisk2MemClusterIDs.size(); + fMem2OnDiskClusterIDs[memId] = onDiskId; + fOnDisk2MemClusterIDs.push_back(memId); + return onDiskId; } DescriptorId_t MapClusterGroupId(DescriptorId_t memId) { - auto physId = fPhys2MemClusterGroupIDs.size(); - fMem2PhysClusterGroupIDs[memId] = physId; - fPhys2MemClusterGroupIDs.push_back(memId); - return physId; + auto onDiskId = fOnDisk2MemClusterGroupIDs.size(); + fMem2OnDiskClusterGroupIDs[memId] = onDiskId; + fOnDisk2MemClusterGroupIDs.push_back(memId); + return onDiskId; } - DescriptorId_t GetPhysFieldId(DescriptorId_t memId) const { return fMem2PhysFieldIDs.at(memId); } - DescriptorId_t GetPhysColumnId(DescriptorId_t memId) const { return fMem2PhysColumnIDs.at(memId); } - DescriptorId_t GetPhysClusterId(DescriptorId_t memId) const { return fMem2PhysClusterIDs.at(memId); } - DescriptorId_t GetPhysClusterGroupId(DescriptorId_t memId) const { return fMem2PhysClusterGroupIDs.at(memId); } - DescriptorId_t GetMemFieldId(DescriptorId_t physId) const { return fPhys2MemFieldIDs[physId]; } - DescriptorId_t GetMemColumnId(DescriptorId_t physId) const { return fPhys2MemColumnIDs[physId]; } - DescriptorId_t GetMemClusterId(DescriptorId_t physId) const { return fPhys2MemClusterIDs[physId]; } - DescriptorId_t GetMemClusterGroupId(DescriptorId_t physId) const { return fPhys2MemClusterGroupIDs[physId]; } + /// Map in-memory field and column IDs to their on-disk counterparts. This function is unconditionally called + /// during header serialization. This function must be manually called after an incremental schema update as page + /// list serialization requires all columns to be mapped. + void MapSchema(const RNTupleDescriptor &desc, bool forHeaderExtension); + + DescriptorId_t GetOnDiskFieldId(DescriptorId_t memId) const { return fMem2OnDiskFieldIDs.at(memId); } + DescriptorId_t GetOnDiskColumnId(DescriptorId_t memId) const { return fMem2OnDiskColumnIDs.at(memId); } + DescriptorId_t GetOnDiskClusterId(DescriptorId_t memId) const { return fMem2OnDiskClusterIDs.at(memId); } + DescriptorId_t GetOnDiskClusterGroupId(DescriptorId_t memId) const + { + return fMem2OnDiskClusterGroupIDs.at(memId); + } + DescriptorId_t GetMemFieldId(DescriptorId_t onDiskId) const { return fOnDisk2MemFieldIDs[onDiskId]; } + DescriptorId_t GetMemColumnId(DescriptorId_t onDiskId) const { return fOnDisk2MemColumnIDs[onDiskId]; } + DescriptorId_t GetMemClusterId(DescriptorId_t onDiskId) const { return fOnDisk2MemClusterIDs[onDiskId]; } + DescriptorId_t GetMemClusterGroupId(DescriptorId_t onDiskId) const + { + return fOnDisk2MemClusterGroupIDs[onDiskId]; + } + + /// Return a vector containing the in-memory field ID for each on-disk counterpart, in order, i.e. the `i`-th + /// value corresponds to the in-memory field ID for `i`-th on-disk ID + const std::vector &GetOnDiskFieldList() const { return fOnDisk2MemFieldIDs; } + /// Mark the first on-disk field ID that is part of the schema extension + void BeginHeaderExtension() { fHeaderExtensionOffset = fOnDisk2MemFieldIDs.size(); } + /// Return the offset of the first element in `fOnDisk2MemFieldIDs` that is part of the schema extension + std::size_t GetHeaderExtensionOffset() const { return fHeaderExtensionOffset; } }; /// Writes a CRC32 checksum of the byte range given by data and length. @@ -207,6 +234,13 @@ public: static RResult DeserializeClusterGroup(const void *buffer, std::uint32_t bufSize, RClusterGroup &clusterGroup); + /// Serialize the schema description in `desc` into `buffer`. If `forHeaderExtension` is true, serialize only the + /// fields and columns tagged as part of the header extension (see `RNTupleDescriptorBuilder::BeginHeaderExtension`). + static std::uint32_t SerializeSchemaDescription(void *buffer, const RNTupleDescriptor &desc, const RContext &context, + bool forHeaderExtension = false); + static RResult + DeserializeSchemaDescription(const void *buffer, std::uint32_t bufSize, RNTupleDescriptorBuilder &descBuilder); + static RContext SerializeHeaderV1(void *buffer, const RNTupleDescriptor &desc); static std::uint32_t SerializePageListV1(void *buffer, const RNTupleDescriptor &desc, diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleUtil.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleUtil.hxx index 4579353e51ade..7917865a30699 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleUtil.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleUtil.hxx @@ -47,9 +47,9 @@ enum ENTupleStructure { /// Integer type long enough to hold the maximum number of entries in a column using NTupleSize_t = std::uint64_t; constexpr NTupleSize_t kInvalidNTupleIndex = std::uint64_t(-1); -/// Wrap the 32bit integer in a struct in order to avoid template specialization clash with std::uint32_t +/// Wrap the integer in a struct in order to avoid template specialization clash with std::uint32_t struct RClusterSize { - using ValueType = std::uint32_t; + using ValueType = std::uint64_t; RClusterSize() : fValue(0) {} explicit constexpr RClusterSize(ValueType value) : fValue(value) {} @@ -61,7 +61,28 @@ struct RClusterSize { ValueType fValue; }; using ClusterSize_t = RClusterSize; -constexpr ClusterSize_t kInvalidClusterIndex(std::uint32_t(-1)); +constexpr ClusterSize_t kInvalidClusterIndex(std::uint64_t(-1)); + +/// Helper types to present an offset column as array of collection sizes. +/// See RField> for details. +template +struct RNTupleCardinality { + static_assert(std::is_same_v || std::is_same_v, + "RNTupleCardinality is only supported with std::uint32_t or std::uint64_t template parameters"); + + using ValueType = SizeT; + + RNTupleCardinality() : fValue(0) {} + explicit constexpr RNTupleCardinality(ValueType value) : fValue(value) {} + RNTupleCardinality &operator=(const ValueType value) + { + fValue = value; + return *this; + } + operator ValueType() const { return fValue; } + + ValueType fValue; +}; /// Holds the index and the tag of a kSwitch column class RColumnSwitch { @@ -122,11 +143,15 @@ struct RNTupleLocatorObject64 { /// and therefore we need to store their actual size. /// TODO(jblomer): consider moving this to `RNTupleDescriptor` struct RNTupleLocator { - /// Values for the _Type_ field in non-disk locators; see `doc/specifications.md` for details + /// Values for the _Type_ field in non-disk locators. Serializable types must have the MSb == 0; see + /// `doc/specifications.md` for details enum ELocatorType : std::uint8_t { kTypeFile = 0x00, kTypeURI = 0x01, kTypeDAOS = 0x02, + + kLastSerializableType = 0x7f, + kTypePageZero = kLastSerializableType + 1, }; /// Simple on-disk locators consisting of a 64-bit offset use variant type `uint64_t`; extended locators have diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleView.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleView.hxx index cb52481f2043b..55ffa9ba22d71 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleView.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleView.hxx @@ -115,23 +115,12 @@ public: namespace Internal { +// TODO(bgruber): convert this trait into a requires clause in C++20 +template +inline constexpr bool isMappable = false; -template -class IsMappable { -public: - using RSuccess = char; - struct RFailure { char x[2]; }; - - template - using MapOverloadT = decltype(std::declval().Map(std::declval() ...)) (C::*)(ArgsT ...); - - template static RSuccess Test(MapOverloadT); - template static RFailure Test(...); - -public: - static constexpr bool value = sizeof(Test(0)) == sizeof(RSuccess); -}; - +template +inline constexpr bool isMappable().Map(NTupleSize_t{}))>> = true; } // namespace Internal @@ -158,17 +147,19 @@ private: /// fFieldId has fParent always set to null; views access nested fields without looking at the parent FieldT fField; /// Used as a Read() destination for fields that are not mappable - Detail::RFieldValue fValue; + Detail::RFieldBase::RValue fValue; public: + using FieldTypeT = T; + RNTupleView(DescriptorId_t fieldId, Detail::RPageSource *pageSource) : fField(pageSource->GetSharedDescriptorGuard()->GetFieldDescriptor(fieldId).GetFieldName()), fValue(fField.GenerateValue()) { - if ((fField.GetTraits() & Detail::RFieldBase::kTraitMappable) && fField.HasReadCallbacks()) - throw RException(R__FAIL("view disallowed on field with mappable type and read callback")); fField.SetOnDiskId(fieldId); fField.ConnectPageSource(*pageSource); + if ((fField.GetTraits() & Detail::RFieldBase::kTraitMappable) && fField.HasReadCallbacks()) + throw RException(R__FAIL("view disallowed on field with mappable type and read callback")); for (auto &f : fField) { auto subFieldId = pageSource->GetSharedDescriptorGuard()->FindFieldId(f.GetName(), f.GetParent()->GetOnDiskId()); @@ -181,41 +172,41 @@ public: RNTupleView(RNTupleView&& other) = default; RNTupleView& operator=(const RNTupleView& other) = delete; RNTupleView& operator=(RNTupleView&& other) = default; - ~RNTupleView() { fField.DestroyValue(fValue); } + ~RNTupleView() = default; RNTupleGlobalRange GetFieldRange() const { return RNTupleGlobalRange(0, fField.GetNElements()); } - template - typename std::enable_if_t::value, const C&> - operator()(NTupleSize_t globalIndex) { return *fField.Map(globalIndex); } - - template - typename std::enable_if_t::value, const C&> - operator()(NTupleSize_t globalIndex) { - fField.Read(globalIndex, &fValue); - return *fValue.Get(); + const T &operator()(NTupleSize_t globalIndex) + { + if constexpr (Internal::isMappable) + return *fField.Map(globalIndex); + else { + fValue.Read(globalIndex); + return *fValue.Get(); + } } - template - typename std::enable_if_t::value, const C&> - operator()(const RClusterIndex &clusterIndex) { return *fField.Map(clusterIndex); } - - template - typename std::enable_if_t::value, const C&> - operator()(const RClusterIndex &clusterIndex) { - fField.Read(clusterIndex, &fValue); - return *fValue.Get(); + const T &operator()(const RClusterIndex &clusterIndex) + { + if constexpr (Internal::isMappable) + return *fField.Map(clusterIndex); + else { + fValue.Read(clusterIndex); + return *fValue.Get(); + } } - template - typename std::enable_if_t::value, const C*> - MapV(NTupleSize_t globalIndex, NTupleSize_t &nItems) { + // TODO(bgruber): turn enable_if into requires clause with C++20 + template , C*> = nullptr> + const C *MapV(NTupleSize_t globalIndex, NTupleSize_t &nItems) + { return fField.MapV(globalIndex, nItems); } - template - typename std::enable_if_t::value, const C*> - MapV(const RClusterIndex &clusterIndex, NTupleSize_t &nItems) { + // TODO(bgruber): turn enable_if into requires clause with C++20 + template , C*> = nullptr> + const C *MapV(const RClusterIndex &clusterIndex, NTupleSize_t &nItems) + { return fField.MapV(clusterIndex, nItems); } }; diff --git a/tree/ntuple/v7/inc/ROOT/RNTupleZip.hxx b/tree/ntuple/v7/inc/ROOT/RNTupleZip.hxx index 4d34d620640c5..4908513683058 100644 --- a/tree/ntuple/v7/inc/ROOT/RNTupleZip.hxx +++ b/tree/ntuple/v7/inc/ROOT/RNTupleZip.hxx @@ -154,6 +154,7 @@ public: szZipData += szOutBlock; source += szSource; + target += szOutBlock; szRemaining -= szSource; } R__ASSERT(szRemaining == 0); diff --git a/tree/ntuple/v7/inc/ROOT/RPage.hxx b/tree/ntuple/v7/inc/ROOT/RPage.hxx index e827d7a8f054b..5d4f709d528b1 100644 --- a/tree/ntuple/v7/inc/ROOT/RPage.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPage.hxx @@ -20,6 +20,7 @@ #include #include +#include namespace ROOT { namespace Experimental { @@ -40,6 +41,8 @@ with the page pool and allocated/freed by the page storage. // clang-format on class RPage { public: + static constexpr size_t kPageZeroSize = 64 * 1024; + /** * Stores information about the cluster in which this page resides. */ @@ -59,10 +62,10 @@ public: private: ColumnId_t fColumnId; void *fBuffer; - ClusterSize_t::ValueType fElementSize; - ClusterSize_t::ValueType fNElements; + std::uint32_t fElementSize; + std::uint32_t fNElements; /// The capacity of the page in number of elements - ClusterSize_t::ValueType fMaxElements; + std::uint32_t fMaxElements; NTupleSize_t fRangeFirst; RClusterInfo fClusterInfo; @@ -78,10 +81,10 @@ public: ColumnId_t GetColumnId() const { return fColumnId; } /// The space taken by column elements in the buffer - ClusterSize_t::ValueType GetNBytes() const { return fElementSize * fNElements; } - ClusterSize_t::ValueType GetElementSize() const { return fElementSize; } - ClusterSize_t::ValueType GetNElements() const { return fNElements; } - ClusterSize_t::ValueType GetMaxElements() const { return fMaxElements; } + std::uint32_t GetNBytes() const { return fElementSize * fNElements; } + std::uint32_t GetElementSize() const { return fElementSize; } + std::uint32_t GetNElements() const { return fNElements; } + std::uint32_t GetMaxElements() const { return fMaxElements; } NTupleSize_t GetGlobalRangeFirst() const { return fRangeFirst; } NTupleSize_t GetGlobalRangeLast() const { return fRangeFirst + NTupleSize_t(fNElements) - 1; } ClusterSize_t::ValueType GetClusterRangeFirst() const { return fRangeFirst - fClusterInfo.GetIndexOffset(); } @@ -127,7 +130,18 @@ public: fClusterInfo = RClusterInfo(clusterId, fClusterInfo.GetIndexOffset()); } + /// Make a 'zero' page for column `columnId` (that is comprised of 0x00 bytes only). The caller is responsible for + /// invoking `GrowUnchecked()` and `SetWindow()` as appropriate. + static RPage MakePageZero(ColumnId_t columnId, ClusterSize_t::ValueType elementSize) + { + return RPage{columnId, const_cast(GetPageZeroBuffer()), elementSize, + /*maxElements=*/(kPageZeroSize / elementSize)}; + } + /// Return a pointer to the page zero buffer used if there is no on-disk data for a particular deferred column + static const void *GetPageZeroBuffer(); + bool IsNull() const { return fBuffer == nullptr; } + bool IsPageZero() const { return fBuffer == GetPageZeroBuffer(); } bool IsEmpty() const { return fNElements == 0; } bool operator ==(const RPage &other) const { return fBuffer == other.fBuffer; } bool operator !=(const RPage &other) const { return !(*this == other); } diff --git a/tree/ntuple/v7/inc/ROOT/RPageSinkBuf.hxx b/tree/ntuple/v7/inc/ROOT/RPageSinkBuf.hxx index 04d24fad45a9a..651943ca87eed 100644 --- a/tree/ntuple/v7/inc/ROOT/RPageSinkBuf.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPageSinkBuf.hxx @@ -2,6 +2,7 @@ /// \ingroup NTuple ROOT7 /// \author Jakob Blomer /// \author Max Orok +/// \author Javier Lopez-Gomez /// \date 2021-03-17 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -53,9 +54,7 @@ private: explicit RPageZipItem(RPage page) : fPage(page), fBuf(nullptr) {} bool IsSealed() const { return fSealedPage != nullptr; } - void AllocateSealedPageBuf() { - fBuf = std::make_unique(fPage.GetNBytes()); - } + void AllocateSealedPageBuf() { fBuf = std::unique_ptr(new unsigned char[fPage.GetNBytes()]); } }; public: RColumnBuf() = default; @@ -63,29 +62,32 @@ private: RColumnBuf& operator=(const RColumnBuf&) = delete; RColumnBuf(RColumnBuf&&) = default; RColumnBuf& operator=(RColumnBuf&&) = default; - ~RColumnBuf() = default; + ~RColumnBuf() { DropBufferedPages(); } - using iterator = std::deque::iterator; - /// Returns an iterator to the newly buffered page. The iterator remains + /// Returns a reference to the newly buffered page. The reference remains /// valid until the return value of DrainBufferedPages() is destroyed. - iterator BufferPage( + /// Note that `BufferPage()` yields the ownership of `page` to RColumnBuf. + RPageZipItem &BufferPage( RPageStorage::ColumnHandle_t columnHandle, const RPage &page) { if (!fCol) { fCol = columnHandle; } - // Safety: Insertion at the end of a deque never invalidates existing - // iterators. + // Safety: Insertion at the end of a deque never invalidates references + // to existing elements. fBufferedPages.push_back(RPageZipItem(page)); - return std::prev(fBufferedPages.end()); + return fBufferedPages.back(); } const RPageStorage::ColumnHandle_t &GetHandle() const { return fCol; } - bool HasSealedPagesOnly() const { return fBufferedPages.size() && fBufferedPages.size() == fSealedPages.size(); } + bool IsEmpty() const { return fBufferedPages.empty(); } + bool HasSealedPagesOnly() const { return fBufferedPages.size() == fSealedPages.size(); } const RPageStorage::SealedPageSequence_t &GetSealedPages() const { return fSealedPages; } using BufferedPages_t = std::tuple, RPageStorage::SealedPageSequence_t>; - // When the return value of DrainBufferedPages() is destroyed, all iterators - // returned by GetBuffer are invalidated. + /// When the return value of DrainBufferedPages() is destroyed, all references + /// returned by GetBuffer are invalidated. + /// This function gives up on the ownership of the buffered pages. Thus, `ReleasePage()` must be called + /// accordingly. BufferedPages_t DrainBufferedPages() { BufferedPages_t drained; @@ -93,21 +95,24 @@ private: std::swap(fSealedPages, std::get(drained)); return drained; } + void DropBufferedPages(); - // The returned iterator points to a default-constructed RSealedPage. This iterator can be used + // The returned reference points to a default-constructed RSealedPage. It can be used // to fill in data after sealing. - RPageStorage::SealedPageSequence_t::iterator RegisterSealedPage() + RSealedPage &RegisterSealedPage() { - return fSealedPages.emplace(std::end(fSealedPages)); + return fSealedPages.emplace_back(); } private: RPageStorage::ColumnHandle_t fCol; - // Using a deque guarantees that element iterators are never invalidated - // by appends to the end of the iterator by BufferPage. + /// Using a deque guarantees that element iterators are never invalidated + /// by appends to the end of the iterator by BufferPage. std::deque fBufferedPages; - // Pages that have been already sealed by a concurrent task. A vector commit can be issued if all - // buffered pages have been sealed. + /// Pages that have been already sealed by a concurrent task. A vector commit can be issued if all + /// buffered pages have been sealed. + /// Note that each RSealedPage refers to the same buffer as `fBufferedPages[i].fBuf` for some value of `i`, and + /// thus owned by RPageZipItem RPageStorage::SealedPageSequence_t fSealedPages; }; @@ -129,7 +134,7 @@ private: protected: void CreateImpl(const RNTupleModel &model, unsigned char *serializedHeader, std::uint32_t length) final; RNTupleLocator CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) final; - RNTupleLocator CommitSealedPageImpl(DescriptorId_t columnId, const RSealedPage &sealedPage) final; + RNTupleLocator CommitSealedPageImpl(DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) final; std::uint64_t CommitClusterImpl(NTupleSize_t nEntries) final; RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) final; void CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length) final; @@ -140,8 +145,9 @@ public: RPageSinkBuf& operator=(const RPageSinkBuf&) = delete; RPageSinkBuf(RPageSinkBuf&&) = default; RPageSinkBuf& operator=(RPageSinkBuf&&) = default; - ~RPageSinkBuf() override = default; + ~RPageSinkBuf() override; + void UpdateSchema(const RNTupleModelChangeset &changeset, NTupleSize_t firstEntry) final; RPage ReservePage(ColumnHandle_t columnHandle, std::size_t nElements) final; void ReleasePage(RPage &page) final; diff --git a/tree/ntuple/v7/inc/ROOT/RPageSourceFriends.hxx b/tree/ntuple/v7/inc/ROOT/RPageSourceFriends.hxx index 2deb8ce757700..6adfd486be2c1 100644 --- a/tree/ntuple/v7/inc/ROOT/RPageSourceFriends.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPageSourceFriends.hxx @@ -99,7 +99,8 @@ public: RPage PopulatePage(ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) final; void ReleasePage(RPage &page) final; - void LoadSealedPage(DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) final; + void + LoadSealedPage(DescriptorId_t physicalColumnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) final; std::vector> LoadClusters(std::span clusterKeys) final; diff --git a/tree/ntuple/v7/inc/ROOT/RPageStorage.hxx b/tree/ntuple/v7/inc/ROOT/RPageStorage.hxx index c968200811092..ef8235149aa0e 100644 --- a/tree/ntuple/v7/inc/ROOT/RPageStorage.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPageStorage.hxx @@ -47,6 +47,7 @@ class RColumn; class RColumnElementBase; class RNTupleCompressor; class RNTupleDecompressor; +struct RNTupleModelChangeset; class RPagePool; class RFieldBase; @@ -99,12 +100,12 @@ public: using SealedPageSequence_t = std::deque; /// A range of sealed pages referring to the same column that can be used for vector commit struct RSealedPageGroup { - DescriptorId_t fColumnId; + DescriptorId_t fPhysicalColumnId; SealedPageSequence_t::const_iterator fFirst; SealedPageSequence_t::const_iterator fLast; RSealedPageGroup(DescriptorId_t d, SealedPageSequence_t::const_iterator b, SealedPageSequence_t::const_iterator e) - : fColumnId(d), fFirst(b), fLast(e) + : fPhysicalColumnId(d), fFirst(b), fLast(e) { } }; @@ -112,6 +113,13 @@ public: protected: std::string fNTupleName; RTaskScheduler *fTaskScheduler = nullptr; + void WaitForAllTasks() + { + if (!fTaskScheduler) + return; + fTaskScheduler->Wait(); + fTaskScheduler->Reset(); + } public: explicit RPageStorage(std::string_view name); @@ -125,12 +133,12 @@ public: virtual EPageStorageType GetType() = 0; struct RColumnHandle { - DescriptorId_t fId = kInvalidDescriptorId; + DescriptorId_t fPhysicalId = kInvalidDescriptorId; const RColumn *fColumn = nullptr; - /// Returns true for a valid column handle; fColumn and fId should always either both + /// Returns true for a valid column handle; fColumn and fPhysicalId should always either both /// be valid or both be invalid. - explicit operator bool() const { return fId != kInvalidDescriptorId && fColumn; } + explicit operator bool() const { return fPhysicalId != kInvalidDescriptorId && fColumn; } }; /// The column handle identifies a column with the current open page storage using ColumnHandle_t = RColumnHandle; @@ -204,8 +212,8 @@ protected: virtual void CreateImpl(const RNTupleModel &model, unsigned char *serializedHeader, std::uint32_t length) = 0; virtual RNTupleLocator CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) = 0; - virtual RNTupleLocator CommitSealedPageImpl(DescriptorId_t columnId, - const RPageStorage::RSealedPage &sealedPage) = 0; + virtual RNTupleLocator + CommitSealedPageImpl(DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) = 0; /// Vector commit of preprocessed pages. The `ranges` array specifies a range of sealed pages to be /// committed for each column. The returned vector contains, in order, the RNTupleLocator for each /// page on each range in `ranges`, i.e. the first N entries refer to the N pages in `ranges[0]`, @@ -265,10 +273,15 @@ public: /// To do so, Create() calls CreateImpl() after updating the descriptor. /// Create() associates column handles to the columns referenced by the model void Create(RNTupleModel &model); + /// Incorporate incremental changes to the model into the ntuple descriptor. This happens, e.g. if new fields were + /// added after the initial call to `RPageSink::Create(RNTupleModel &)`. + /// `firstEntry` specifies the global index for the first stored element in the added columns. + virtual void UpdateSchema(const RNTupleModelChangeset &changeset, NTupleSize_t firstEntry); + /// Write a page to the storage. The column must have been added before. void CommitPage(ColumnHandle_t columnHandle, const RPage &page); /// Write a preprocessed page to storage. The column must have been added before. - void CommitSealedPage(DescriptorId_t columnId, const RPageStorage::RSealedPage &sealedPage); + void CommitSealedPage(DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage); /// Write a vector of preprocessed pages to storage. The corresponding columns must have been added before. void CommitSealedPageV(std::span ranges); /// Finalize the current cluster and create a new one for the following data. @@ -294,8 +307,9 @@ public: \ingroup NTuple \brief Abstract interface to read data from an ntuple -The page source is initialized with the columns of interest. Pages from those columns can then be -mapped into memory. The page source also gives access to the ntuple's meta-data. +The page source is initialized with the columns of interest. Alias columns from projected fields are mapped to the +corresponding physical columns. Pages from the columns of interest can then be mapped into memory. +The page source also gives access to the ntuple's meta-data. */ // clang-format on class RPageSource : public RPageStorage { @@ -367,13 +381,27 @@ protected: RNTupleCalcPerf &fFractionReadOverhead; RNTupleCalcPerf &fCompressionRatio; }; + + /// Keeps track of the requested physical column IDs. When using alias columns (projected fields), physical + /// columns may be requested multiple times. + class RActivePhysicalColumns { + private: + std::vector fIDs; + std::vector fRefCounters; + + public: + void Insert(DescriptorId_t physicalColumnID); + void Erase(DescriptorId_t physicalColumnID); + RCluster::ColumnSet_t ToColumnSet() const; + }; + std::unique_ptr fCounters; /// Wraps the I/O counters and is observed by the RNTupleReader metrics RNTupleMetrics fMetrics; RNTupleReadOptions fOptions; /// The active columns are implicitly defined by the model fields or views - RCluster::ColumnSet_t fActiveColumns; + RActivePhysicalColumns fActivePhysicalColumns; /// Helper to unzip pages and header/footer; comprises a 16MB (kMAXZIPBUF) unzip buffer. /// Not all page sources need a decompressor (e.g. virtual ones for chains and friends don't), thus we @@ -388,8 +416,16 @@ protected: /// Helper for unstreaming a page. This is commonly used in derived, concrete page sources. The implementation /// currently always makes a memory copy, even if the sealed page is uncompressed and in the final memory layout. /// The optimization of directly mapping pages is left to the concrete page source implementations. - /// Usage of this method requires construction of fDecompressor. - std::unique_ptr UnsealPage(const RSealedPage &sealedPage, const RColumnElementBase &element); + /// Usage of this method requires construction of fDecompressor. Memory is allocated via + /// `RPageAllocatorHeap`; use `RPageAllocatorHeap::DeletePage()` to deallocate returned pages. + RPage UnsealPage(const RSealedPage &sealedPage, const RColumnElementBase &element, DescriptorId_t physicalColumnId); + + /// Prepare a page range read for the column set in `clusterKey`. Specifically, pages referencing the + /// `kTypePageZero` locator are filled in `pageZeroMap`; otherwise, `perPageFunc` is called for each page. This is + /// commonly used as part of `LoadClusters()` in derived classes. + void PrepareLoadCluster( + const RCluster::RKey &clusterKey, ROnDiskPageMap &pageZeroMap, + std::function perPageFunc); /// Enables the default set of metrics provided by RPageSource. `prefix` will be used as the prefix for /// the counters registered in the internal RNTupleMetrics object. @@ -449,7 +485,8 @@ public: /// The fSize and fNElements member of the sealedPage parameters are always set. If sealedPage.fBuffer is nullptr, /// no data will be copied but the returned size information can be used by the caller to allocate a large enough /// buffer and call LoadSealedPage again. - virtual void LoadSealedPage(DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) = 0; + virtual void + LoadSealedPage(DescriptorId_t physicalColumnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) = 0; /// Populates all the pages of the given cluster ids and columns; it is possible that some columns do not /// contain any pages. The page source may load more columns than the minimal necessary set from `columns`. diff --git a/tree/ntuple/v7/inc/ROOT/RPageStorageDaos.hxx b/tree/ntuple/v7/inc/ROOT/RPageStorageDaos.hxx index 9f8d2c65ce768..3a25425043c79 100644 --- a/tree/ntuple/v7/inc/ROOT/RPageStorageDaos.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPageStorageDaos.hxx @@ -31,6 +31,14 @@ namespace ROOT { namespace Experimental { + +namespace Internal { +enum EDaosLocatorFlags { + // Indicates that the referenced page is "caged", i.e. it is stored in a larger blob that contains multiple pages. + kCagedPage = 0x01, +}; +} + namespace Detail { class RCluster; @@ -107,8 +115,8 @@ struct RDaosContainerNTupleLocator { static ntuple_index_t Hash(const std::string &ntupleName) { // Convert string to numeric representation via `std::hash`. - std::size_t h = std::hash{}(ntupleName); - // Fold `std::size_t` bits into 32-bit using `boost::hash_combine()` algorithm and magic number. + uint64_t h = std::hash{}(ntupleName); + // Fold the hash into 32-bit using `boost::hash_combine()` algorithm and magic number. auto seed = static_cast(h >> 32); seed ^= static_cast(h & 0xffffffff) + 0x9e3779b9 + (seed << 6) + (seed >> 2); auto hash = static_cast(seed); @@ -128,7 +136,7 @@ struct RDaosContainerNTupleLocator { \ingroup NTuple \brief Storage provider that writes ntuple pages to into a DAOS container -Currently, an object is allocated for ntuple metadata (anchor/header/footer). +Currently, an object is allocated for ntuple metadata (anchor/header/footer). Objects can correspond to pages or clusters of pages depending on the RNTuple-DAOS mapping strategy. */ // clang-format on @@ -152,11 +160,13 @@ private: RDaosNTupleAnchor fNTupleAnchor; ntuple_index_t fNTupleIndex{0}; + uint32_t fCageSizeLimit{}; protected: void CreateImpl(const RNTupleModel &model, unsigned char *serializedHeader, std::uint32_t length) final; RNTupleLocator CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) final; - RNTupleLocator CommitSealedPageImpl(DescriptorId_t columnId, const RPageStorage::RSealedPage &sealedPage) final; + RNTupleLocator + CommitSealedPageImpl(DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) final; std::vector CommitSealedPageVImpl(std::span ranges) final; std::uint64_t CommitClusterImpl(NTupleSize_t nEntries) final; RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) final; @@ -173,19 +183,6 @@ public: void ReleasePage(RPage &page) final; }; -// clang-format off -/** -\class ROOT::Experimental::Detail::RPageAllocatorDaos -\ingroup NTuple -\brief Manages pages read from a DAOS container -*/ -// clang-format on -class RPageAllocatorDaos { -public: - static RPage NewPage(ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements); - static void DeletePage(const RPage &page); -}; - // clang-format off /** \class ROOT::Experimental::Detail::RPageSourceDaos @@ -207,10 +204,7 @@ private: ntuple_index_t fNTupleIndex{0}; - /// Populated pages might be shared; the memory buffer is managed by the RPageAllocatorDaos - std::unique_ptr fPageAllocator; - // TODO: the page pool should probably be handled by the base class. - /// The page pool might, at some point, be used by multiple page sources + /// Populated pages might be shared; the page pool might, at some point, be used by multiple page sources std::shared_ptr fPagePool; /// The last cluster from which a page got populated. Points into fClusterPool->fPool RCluster *fCurrentCluster = nullptr; @@ -241,7 +235,8 @@ public: RPage PopulatePage(ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) final; void ReleasePage(RPage &page) final; - void LoadSealedPage(DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) final; + void + LoadSealedPage(DescriptorId_t physicalColumnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) final; std::vector> LoadClusters(std::span clusterKeys) final; diff --git a/tree/ntuple/v7/inc/ROOT/RPageStorageFile.hxx b/tree/ntuple/v7/inc/ROOT/RPageStorageFile.hxx index a7786ad39cbaa..b8774cd0231ec 100644 --- a/tree/ntuple/v7/inc/ROOT/RPageStorageFile.hxx +++ b/tree/ntuple/v7/inc/ROOT/RPageStorageFile.hxx @@ -71,7 +71,8 @@ private: protected: void CreateImpl(const RNTupleModel &model, unsigned char *serializedHeader, std::uint32_t length) final; RNTupleLocator CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) final; - RNTupleLocator CommitSealedPageImpl(DescriptorId_t columnId, const RPageStorage::RSealedPage &sealedPage) final; + RNTupleLocator + CommitSealedPageImpl(DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) final; std::uint64_t CommitClusterImpl(NTupleSize_t nEntries) final; RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) final; void CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length) final; @@ -91,21 +92,6 @@ public: void ReleasePage(RPage &page) final; }; - -// clang-format off -/** -\class ROOT::Experimental::Detail::RPageAllocatorFile -\ingroup NTuple -\brief Manages pages read from a the file -*/ -// clang-format on -class RPageAllocatorFile { -public: - static RPage NewPage(ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements); - static void DeletePage(const RPage& page); -}; - - // clang-format off /** \class ROOT::Experimental::Detail::RPageSourceFile @@ -127,9 +113,7 @@ private: std::uint64_t fColumnOffset = 0; }; - /// Populated pages might be shared; there memory buffer is managed by the RPageAllocatorFile - std::unique_ptr fPageAllocator; - /// The page pool might, at some point, be used by multiple page sources + /// Populated pages might be shared; the page pool might, at some point, be used by multiple page sources std::shared_ptr fPagePool; /// The last cluster from which a page got populated. Points into fClusterPool->fPool RCluster *fCurrentCluster = nullptr; @@ -180,8 +164,8 @@ public: RPage PopulatePage(ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) final; void ReleasePage(RPage &page) final; - void LoadSealedPage(DescriptorId_t columnId, const RClusterIndex &clusterIndex, - RSealedPage &sealedPage) final; + void + LoadSealedPage(DescriptorId_t physicalColumnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) final; std::vector> LoadClusters(std::span clusterKeys) final; }; diff --git a/tree/ntuple/v7/src/RCluster.cxx b/tree/ntuple/v7/src/RCluster.cxx index 42166e36a5cdc..41d7b6c8ed489 100644 --- a/tree/ntuple/v7/src/RCluster.cxx +++ b/tree/ntuple/v7/src/RCluster.cxx @@ -59,15 +59,14 @@ void ROOT::Experimental::Detail::RCluster::Adopt(RCluster &&other) fOnDiskPages.insert(std::make_move_iterator(pages.begin()), std::make_move_iterator(pages.end())); other.fOnDiskPages.clear(); - auto &columns = other.fAvailColumns; - fAvailColumns.insert(std::make_move_iterator(columns.begin()), std::make_move_iterator(columns.end())); - other.fAvailColumns.clear(); + auto &columns = other.fAvailPhysicalColumns; + fAvailPhysicalColumns.insert(std::make_move_iterator(columns.begin()), std::make_move_iterator(columns.end())); + other.fAvailPhysicalColumns.clear(); std::move(other.fPageMaps.begin(), other.fPageMaps.end(), std::back_inserter(fPageMaps)); other.fPageMaps.clear(); } - -void ROOT::Experimental::Detail::RCluster::SetColumnAvailable(DescriptorId_t columnId) +void ROOT::Experimental::Detail::RCluster::SetColumnAvailable(DescriptorId_t physicalColumnId) { - fAvailColumns.insert(columnId); + fAvailPhysicalColumns.insert(physicalColumnId); } diff --git a/tree/ntuple/v7/src/RClusterPool.cxx b/tree/ntuple/v7/src/RClusterPool.cxx index 8dc66c5671670..1491f9d1e9cfb 100644 --- a/tree/ntuple/v7/src/RClusterPool.cxx +++ b/tree/ntuple/v7/src/RClusterPool.cxx @@ -33,10 +33,9 @@ bool ROOT::Experimental::Detail::RClusterPool::RInFlightCluster::operator <(const RInFlightCluster &other) const { if (fClusterKey.fClusterId == other.fClusterKey.fClusterId) { - if (fClusterKey.fColumnSet.size() == other.fClusterKey.fColumnSet.size()) { - for (auto itr1 = fClusterKey.fColumnSet.begin(), itr2 = other.fClusterKey.fColumnSet.begin(); - itr1 != fClusterKey.fColumnSet.end(); ++itr1, ++itr2) - { + if (fClusterKey.fPhysicalColumnSet.size() == other.fClusterKey.fPhysicalColumnSet.size()) { + for (auto itr1 = fClusterKey.fPhysicalColumnSet.begin(), itr2 = other.fClusterKey.fPhysicalColumnSet.begin(); + itr1 != fClusterKey.fPhysicalColumnSet.end(); ++itr1, ++itr2) { if (*itr1 == *itr2) continue; return *itr1 < *itr2; @@ -44,7 +43,7 @@ bool ROOT::Experimental::Detail::RClusterPool::RInFlightCluster::operator <(cons // *this == other return false; } - return fClusterKey.fColumnSet.size() < other.fClusterKey.fColumnSet.size(); + return fClusterKey.fPhysicalColumnSet.size() < other.fClusterKey.fPhysicalColumnSet.size(); } return fClusterKey.fClusterId < other.fClusterKey.fClusterId; } @@ -64,7 +63,7 @@ ROOT::Experimental::Detail::RClusterPool::~RClusterPool() { // Controlled shutdown of the I/O thread std::unique_lock lock(fLockWorkQueue); - fReadQueue.emplace(RReadItem()); + fReadQueue.emplace_back(RReadItem()); fCvHasReadWork.notify_one(); } fThreadIo.join(); @@ -72,7 +71,7 @@ ROOT::Experimental::Detail::RClusterPool::~RClusterPool() { // Controlled shutdown of the unzip thread std::unique_lock lock(fLockUnzipQueue); - fUnzipQueue.emplace(RUnzipItem()); + fUnzipQueue.emplace_back(RUnzipItem()); fCvHasUnzipWork.notify_one(); } fThreadUnzip.join(); @@ -80,15 +79,16 @@ ROOT::Experimental::Detail::RClusterPool::~RClusterPool() void ROOT::Experimental::Detail::RClusterPool::ExecUnzipClusters() { + // The thread keeps its local buffer of elements to be processed. On wakeup, the local copy is swapped with + // `fUnzipQueue`, which not only reduces contention but also reduces the overall number of allocations, as the + // internal storage of both copies is reused. The local copy should be cleared before the `std::swap()` in the next + // iteration. + std::deque unzipItems; while (true) { - std::vector unzipItems; { std::unique_lock lock(fLockUnzipQueue); fCvHasUnzipWork.wait(lock, [&]{ return !fUnzipQueue.empty(); }); - while (!fUnzipQueue.empty()) { - unzipItems.emplace_back(std::move(fUnzipQueue.front())); - fUnzipQueue.pop(); - } + std::swap(unzipItems, fUnzipQueue); } for (auto &item : unzipItems) { @@ -100,57 +100,63 @@ void ROOT::Experimental::Detail::RClusterPool::ExecUnzipClusters() // Afterwards the GetCluster() method in the main thread can pick-up the cluster item.fPromise.set_value(std::move(item.fCluster)); } + unzipItems.clear(); } // while (true) } void ROOT::Experimental::Detail::RClusterPool::ExecReadClusters() { + std::deque readItems; while (true) { - std::vector readItems; - std::vector clusterKeys; - std::int64_t bunchId = -1; { std::unique_lock lock(fLockWorkQueue); fCvHasReadWork.wait(lock, [&]{ return !fReadQueue.empty(); }); - while (!fReadQueue.empty()) { - if (fReadQueue.front().fClusterKey.fClusterId == kInvalidDescriptorId) { - fReadQueue.pop(); + std::swap(readItems, fReadQueue); + } + + while (!readItems.empty()) { + std::vector clusterKeys; + std::int64_t bunchId = -1; + for (unsigned i = 0; i < readItems.size(); ++i) { + const auto &item = readItems[i]; + // `kInvalidDescriptorId` is used as a marker for thread cancellation. Such item causes the + // thread to terminate; thus, it must appear last in the queue. + if (R__unlikely(item.fClusterKey.fClusterId == kInvalidDescriptorId)) { + R__ASSERT(i == (readItems.size() - 1)); return; } - - if ((bunchId >= 0) && (fReadQueue.front().fBunchId != bunchId)) + if ((bunchId >= 0) && (item.fBunchId != bunchId)) break; - readItems.emplace_back(std::move(fReadQueue.front())); - fReadQueue.pop(); - bunchId = readItems.back().fBunchId; - clusterKeys.emplace_back(readItems.back().fClusterKey); + bunchId = item.fBunchId; + clusterKeys.emplace_back(item.fClusterKey); } - } - auto clusters = fPageSource.LoadClusters(clusterKeys); - - for (std::size_t i = 0; i < clusters.size(); ++i) { - // Meanwhile, the user might have requested clusters outside the look-ahead window, so that we don't - // need the cluster anymore, in which case we simply discard it right away, before moving it to the pool - bool discard = false; - { - std::unique_lock lock(fLockWorkQueue); - for (auto &inFlight : fInFlightClusters) { - if (inFlight.fClusterKey.fClusterId != clusters[i]->GetId()) - continue; - discard = inFlight.fIsExpired; - break; + auto clusters = fPageSource.LoadClusters(clusterKeys); + bool unzipQueueDirty = false; + for (std::size_t i = 0; i < clusters.size(); ++i) { + // Meanwhile, the user might have requested clusters outside the look-ahead window, so that we don't + // need the cluster anymore, in which case we simply discard it right away, before moving it to the pool + bool discard; + { + std::unique_lock lock(fLockWorkQueue); + discard = std::any_of(fInFlightClusters.begin(), fInFlightClusters.end(), + [thisClusterId = clusters[i]->GetId()](auto &inFlight) { + return inFlight.fClusterKey.fClusterId == thisClusterId && inFlight.fIsExpired; + }); + } + if (discard) { + clusters[i].reset(); + readItems[i].fPromise.set_value(std::move(clusters[i])); + } else { + // Hand-over the loaded cluster pages to the unzip thread + std::unique_lock lock(fLockUnzipQueue); + fUnzipQueue.emplace_back(RUnzipItem{std::move(clusters[i]), std::move(readItems[i].fPromise)}); + unzipQueueDirty = true; } } - if (discard) { - clusters[i].reset(); - readItems[i].fPromise.set_value(std::move(clusters[i])); - } else { - // Hand-over the loaded cluster pages to the unzip thread - std::unique_lock lock(fLockUnzipQueue); - fUnzipQueue.emplace(RUnzipItem{std::move(clusters[i]), std::move(readItems[i].fPromise)}); + readItems.erase(readItems.begin(), readItems.begin() + clusters.size()); + if (unzipQueueDirty) fCvHasUnzipWork.notify_one(); - } } } // while (true) } @@ -189,7 +195,7 @@ class RProvides { struct RInfo { std::int64_t fBunchId = -1; std::int64_t fFlags = 0; - ColumnSet_t fColumnSet; + ColumnSet_t fPhysicalColumnSet; }; static constexpr std::int64_t kFlagRequired = 0x01; @@ -210,18 +216,19 @@ class RProvides { std::size_t GetSize() const { return fMap.size(); } - void Erase(DescriptorId_t clusterId, const ColumnSet_t &columns) + void Erase(DescriptorId_t clusterId, const ColumnSet_t &physicalColumns) { auto itr = fMap.find(clusterId); if (itr == fMap.end()) return; ColumnSet_t d; - std::copy_if(itr->second.fColumnSet.begin(), itr->second.fColumnSet.end(), std::inserter(d, d.end()), - [&columns] (DescriptorId_t needle) { return columns.count(needle) == 0; }); + std::copy_if(itr->second.fPhysicalColumnSet.begin(), itr->second.fPhysicalColumnSet.end(), + std::inserter(d, d.end()), + [&physicalColumns](DescriptorId_t needle) { return physicalColumns.count(needle) == 0; }); if (d.empty()) { fMap.erase(itr); } else { - itr->second.fColumnSet = d; + itr->second.fPhysicalColumnSet = d; } } @@ -232,8 +239,8 @@ class RProvides { } // anonymous namespace ROOT::Experimental::Detail::RCluster * -ROOT::Experimental::Detail::RClusterPool::GetCluster( - DescriptorId_t clusterId, const RCluster::ColumnSet_t &columns) +ROOT::Experimental::Detail::RClusterPool::GetCluster(DescriptorId_t clusterId, + const RCluster::ColumnSet_t &physicalColumns) { std::set keep; RProvides provide; @@ -251,7 +258,7 @@ ROOT::Experimental::Detail::RClusterPool::GetCluster( // Determine following cluster ids and the column ids that we want to make available RProvides::RInfo provideInfo; - provideInfo.fColumnSet = columns; + provideInfo.fPhysicalColumnSet = physicalColumns; provideInfo.fBunchId = fBunchId; provideInfo.fFlags = RProvides::kFlagRequired; for (DescriptorId_t i = 0, next = clusterId; i < 2 * fClusterBunchSize; ++i) { @@ -298,7 +305,7 @@ ROOT::Experimental::Detail::RClusterPool::GetCluster( if (itr->fFuture.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { // Remove the set of columns that are already scheduled for being loaded - provide.Erase(itr->fClusterKey.fClusterId, itr->fClusterKey.fColumnSet); + provide.Erase(itr->fClusterKey.fClusterId, itr->fClusterKey.fPhysicalColumnSet); ++itr; continue; } @@ -326,7 +333,7 @@ ROOT::Experimental::Detail::RClusterPool::GetCluster( for (auto &cptr : fPool) { if (!cptr) continue; - provide.Erase(cptr->GetId(), cptr->GetAvailColumns()); + provide.Erase(cptr->GetId(), cptr->GetAvailPhysicalColumns()); } // Figure out if enough work accumulated to justify I/O calls @@ -347,40 +354,39 @@ ROOT::Experimental::Detail::RClusterPool::GetCluster( // case but it's not ensured by the code if (!skipPrefetch) { for (const auto &kv : provide) { - R__ASSERT(!kv.second.fColumnSet.empty()); + R__ASSERT(!kv.second.fPhysicalColumnSet.empty()); RReadItem readItem; readItem.fClusterKey.fClusterId = kv.first; readItem.fBunchId = kv.second.fBunchId; - readItem.fClusterKey.fColumnSet = kv.second.fColumnSet; + readItem.fClusterKey.fPhysicalColumnSet = kv.second.fPhysicalColumnSet; RInFlightCluster inFlightCluster; inFlightCluster.fClusterKey.fClusterId = kv.first; - inFlightCluster.fClusterKey.fColumnSet = kv.second.fColumnSet; + inFlightCluster.fClusterKey.fPhysicalColumnSet = kv.second.fPhysicalColumnSet; inFlightCluster.fFuture = readItem.fPromise.get_future(); fInFlightClusters.emplace_back(std::move(inFlightCluster)); - fReadQueue.emplace(std::move(readItem)); + fReadQueue.emplace_back(std::move(readItem)); } if (fReadQueue.size() > 0) fCvHasReadWork.notify_one(); } } // work queue lock guard - return WaitFor(clusterId, columns); + return WaitFor(clusterId, physicalColumns); } - ROOT::Experimental::Detail::RCluster * -ROOT::Experimental::Detail::RClusterPool::WaitFor( - DescriptorId_t clusterId, const RCluster::ColumnSet_t &columns) +ROOT::Experimental::Detail::RClusterPool::WaitFor(DescriptorId_t clusterId, + const RCluster::ColumnSet_t &physicalColumns) { while (true) { // Fast exit: the cluster happens to be already present in the cache pool auto result = FindInPool(clusterId); if (result) { bool hasMissingColumn = false; - for (auto cid : columns) { + for (auto cid : physicalColumns) { if (result->ContainsColumn(cid)) continue; diff --git a/tree/ntuple/v7/src/RColumn.cxx b/tree/ntuple/v7/src/RColumn.cxx index 9bb216a82b940..12526a0897dc9 100644 --- a/tree/ntuple/v7/src/RColumn.cxx +++ b/tree/ntuple/v7/src/RColumn.cxx @@ -15,12 +15,11 @@ #include #include +#include #include #include -#include - ROOT::Experimental::Detail::RColumn::RColumn(const RColumnModel& model, std::uint32_t index) : fModel(model), fIndex(index) { @@ -40,10 +39,12 @@ ROOT::Experimental::Detail::RColumn::~RColumn() fPageSource->DropColumn(fHandleSource); } -void ROOT::Experimental::Detail::RColumn::Connect(DescriptorId_t fieldId, RPageStorage *pageStorage) +void ROOT::Experimental::Detail::RColumn::Connect(DescriptorId_t fieldId, RPageStorage *pageStorage, + NTupleSize_t firstElementIndex) { switch (pageStorage->GetType()) { case EPageStorageType::kSink: + fFirstElementIndex = firstElementIndex; fPageSink = static_cast(pageStorage); // the page sink initializes fWritePage on AddColumn fHandleSink = fPageSink->AddColumn(fieldId, *this); fApproxNElementsPerPage = fPageSink->GetWriteOptions().GetApproxUnzippedPageSize() / fElement->GetSize(); @@ -58,6 +59,10 @@ void ROOT::Experimental::Detail::RColumn::Connect(DescriptorId_t fieldId, RPageS fHandleSource = fPageSource->AddColumn(fieldId, *this); fNElements = fPageSource->GetNElements(fHandleSource); fColumnIdSource = fPageSource->GetColumnId(fHandleSource); + { + auto descriptorGuard = fPageSource->GetSharedDescriptorGuard(); + fFirstElementIndex = descriptorGuard->GetColumnDescriptor(fColumnIdSource).GetFirstElementIndex(); + } break; default: R__ASSERT(false); @@ -72,10 +77,10 @@ void ROOT::Experimental::Detail::RColumn::Flush() if ((fWritePage[fWritePageIdx].GetNElements() < fApproxNElementsPerPage / 2) && !fWritePage[otherIdx].IsEmpty()) { // Small tail page: merge with previously used page; we know that there is enough space in the shadow page - void *dst = fWritePage[otherIdx].GrowUnchecked(fWritePage[fWritePageIdx].GetNElements()); - RColumnElementBase elem(fWritePage[fWritePageIdx].GetBuffer(), fWritePage[fWritePageIdx].GetElementSize()); - elem.WriteTo(dst, fWritePage[fWritePageIdx].GetNElements()); - fWritePage[fWritePageIdx].Reset(0); + auto &thisPage = fWritePage[fWritePageIdx]; + void *dst = fWritePage[otherIdx].GrowUnchecked(thisPage.GetNElements()); + memcpy(dst, thisPage.GetBuffer(), thisPage.GetElementSize() * thisPage.GetNElements()); + thisPage.Reset(0); std::swap(fWritePageIdx, otherIdx); } @@ -88,10 +93,12 @@ void ROOT::Experimental::Detail::RColumn::MapPage(const NTupleSize_t index) { fPageSource->ReleasePage(fReadPage); fReadPage = fPageSource->PopulatePage(fHandleSource, index); + R__ASSERT(fReadPage.Contains(index)); } void ROOT::Experimental::Detail::RColumn::MapPage(const RClusterIndex &clusterIndex) { fPageSource->ReleasePage(fReadPage); fReadPage = fPageSource->PopulatePage(fHandleSource, clusterIndex); + R__ASSERT(fReadPage.Contains(clusterIndex)); } diff --git a/tree/ntuple/v7/src/RColumnElement.cxx b/tree/ntuple/v7/src/RColumnElement.cxx index 2985bc5ef10eb..6222c6bc89823 100644 --- a/tree/ntuple/v7/src/RColumnElement.cxx +++ b/tree/ntuple/v7/src/RColumnElement.cxx @@ -23,33 +23,40 @@ #include #include +template <> std::unique_ptr -ROOT::Experimental::Detail::RColumnElementBase::Generate(EColumnType type) { +ROOT::Experimental::Detail::RColumnElementBase::Generate(EColumnType type) +{ switch (type) { - case EColumnType::kReal32: - return std::make_unique>(nullptr); - case EColumnType::kReal64: - return std::make_unique>(nullptr); - case EColumnType::kChar: - return std::make_unique>(nullptr); - case EColumnType::kByte: - return std::make_unique>(nullptr); - case EColumnType::kInt8: - return std::make_unique>(nullptr); - case EColumnType::kInt16: - return std::make_unique>(nullptr); - case EColumnType::kInt32: - return std::make_unique>(nullptr); - case EColumnType::kInt64: - return std::make_unique>(nullptr); - case EColumnType::kBit: - return std::make_unique>(nullptr); - case EColumnType::kIndex: - return std::make_unique>(nullptr); - case EColumnType::kSwitch: - return std::make_unique>(nullptr); - default: - R__ASSERT(false); + case EColumnType::kIndex64: return std::make_unique>(); + case EColumnType::kIndex32: return std::make_unique>(); + case EColumnType::kSwitch: return std::make_unique>(); + case EColumnType::kByte: return std::make_unique>(); + case EColumnType::kChar: return std::make_unique>(); + case EColumnType::kBit: return std::make_unique>(); + case EColumnType::kReal64: return std::make_unique>(); + case EColumnType::kReal32: return std::make_unique>(); + case EColumnType::kInt64: return std::make_unique>(); + case EColumnType::kUInt64: return std::make_unique>(); + case EColumnType::kInt32: return std::make_unique>(); + case EColumnType::kUInt32: return std::make_unique>(); + case EColumnType::kInt16: return std::make_unique>(); + case EColumnType::kUInt16: return std::make_unique>(); + case EColumnType::kInt8: return std::make_unique>(); + case EColumnType::kUInt8: return std::make_unique>(); + case EColumnType::kSplitIndex64: + return std::make_unique>(); + case EColumnType::kSplitIndex32: + return std::make_unique>(); + case EColumnType::kSplitReal64: return std::make_unique>(); + case EColumnType::kSplitReal32: return std::make_unique>(); + case EColumnType::kSplitInt64: return std::make_unique>(); + case EColumnType::kSplitUInt64: return std::make_unique>(); + case EColumnType::kSplitInt32: return std::make_unique>(); + case EColumnType::kSplitUInt32: return std::make_unique>(); + case EColumnType::kSplitInt16: return std::make_unique>(); + case EColumnType::kSplitUInt16: return std::make_unique>(); + default: R__ASSERT(false); } // never here return nullptr; @@ -57,30 +64,33 @@ ROOT::Experimental::Detail::RColumnElementBase::Generate(EColumnType type) { std::size_t ROOT::Experimental::Detail::RColumnElementBase::GetBitsOnStorage(EColumnType type) { switch (type) { - case EColumnType::kReal32: - return 32; - case EColumnType::kReal64: - return 64; - case EColumnType::kChar: - return 8; - case EColumnType::kByte: - return 8; - case EColumnType::kInt8: - return 8; - case EColumnType::kInt16: - return 16; - case EColumnType::kInt32: - return 32; - case EColumnType::kInt64: - return 64; - case EColumnType::kBit: - return 1; - case EColumnType::kIndex: - return 32; - case EColumnType::kSwitch: - return 64; - default: - R__ASSERT(false); + case EColumnType::kIndex64: return 64; + case EColumnType::kIndex32: return 32; + case EColumnType::kSwitch: return 64; + case EColumnType::kByte: return 8; + case EColumnType::kChar: return 8; + case EColumnType::kBit: return 1; + case EColumnType::kReal64: return 64; + case EColumnType::kReal32: return 32; + case EColumnType::kInt64: return 64; + case EColumnType::kUInt64: return 64; + case EColumnType::kInt32: return 32; + case EColumnType::kUInt32: return 32; + case EColumnType::kInt16: return 16; + case EColumnType::kUInt16: return 16; + case EColumnType::kInt8: return 8; + case EColumnType::kUInt8: return 8; + case EColumnType::kSplitIndex64: return 64; + case EColumnType::kSplitIndex32: return 32; + case EColumnType::kSplitReal64: return 64; + case EColumnType::kSplitReal32: return 32; + case EColumnType::kSplitInt64: return 64; + case EColumnType::kSplitUInt64: return 64; + case EColumnType::kSplitInt32: return 32; + case EColumnType::kSplitUInt32: return 32; + case EColumnType::kSplitInt16: return 16; + case EColumnType::kSplitUInt16: return 16; + default: R__ASSERT(false); } // never here return 0; @@ -88,62 +98,33 @@ std::size_t ROOT::Experimental::Detail::RColumnElementBase::GetBitsOnStorage(ECo std::string ROOT::Experimental::Detail::RColumnElementBase::GetTypeName(EColumnType type) { switch (type) { - case EColumnType::kReal32: - return "Real32"; - case EColumnType::kReal64: - return "Real64"; - case EColumnType::kChar: - return "Char"; - case EColumnType::kByte: - return "Byte"; - case EColumnType::kInt8: - return "Int8"; - case EColumnType::kInt16: - return "Int16"; - case EColumnType::kInt32: - return "Int32"; - case EColumnType::kInt64: - return "Int64"; - case EColumnType::kBit: - return "Bit"; - case EColumnType::kIndex: - return "Index"; - case EColumnType::kSwitch: - return "Switch"; - default: - return "UNKNOWN"; - } -} - -void ROOT::Experimental::Detail::RColumnElement::Pack(void *dst, void *src, - std::size_t count) const -{ - auto srcArray = reinterpret_cast(src); - auto uint64Array = reinterpret_cast(dst); - for (std::size_t i = 0; i < count; ++i) { - uint64Array[i] = - (static_cast(srcArray[i].GetTag()) << 44) | (srcArray[i].GetIndex() & 0x0fffffffffff); -#if R__LITTLE_ENDIAN == 0 - uint64Array[i] = RByteSwap<8>::bswap(uint64Array[i]); -#endif - } -} - -void ROOT::Experimental::Detail::RColumnElement< - ROOT::Experimental::RColumnSwitch, ROOT::Experimental::EColumnType::kSwitch>::Unpack(void *dst, void *src, - std::size_t count) const -{ - auto uint64Array = reinterpret_cast(src); - auto dstArray = reinterpret_cast(dst); - for (std::size_t i = 0; i < count; ++i) { -#if R__LITTLE_ENDIAN == 1 - const auto value = uint64Array[i]; -#else - const auto value = RByteSwap<8>::bswap(uint64Array[i]); -#endif - dstArray[i] = ROOT::Experimental::RColumnSwitch( - ClusterSize_t{static_cast(value & 0x0fffffffffff)}, (value >> 44)); + case EColumnType::kIndex64: return "Index64"; + case EColumnType::kIndex32: return "Index32"; + case EColumnType::kSwitch: return "Switch"; + case EColumnType::kByte: return "Byte"; + case EColumnType::kChar: return "Char"; + case EColumnType::kBit: return "Bit"; + case EColumnType::kReal64: return "Real64"; + case EColumnType::kReal32: return "Real32"; + case EColumnType::kInt64: return "Int64"; + case EColumnType::kUInt64: return "UInt64"; + case EColumnType::kInt32: return "Int32"; + case EColumnType::kUInt32: return "UInt32"; + case EColumnType::kInt16: return "Int16"; + case EColumnType::kUInt16: return "UInt16"; + case EColumnType::kInt8: return "Int8"; + case EColumnType::kUInt8: return "UInt8"; + case EColumnType::kSplitIndex64: return "SplitIndex64"; + case EColumnType::kSplitIndex32: return "SplitIndex32"; + case EColumnType::kSplitReal64: return "SplitReal64"; + case EColumnType::kSplitReal32: return "SplitReal32"; + case EColumnType::kSplitInt64: return "SplitInt64"; + case EColumnType::kSplitUInt64: return "SplitUInt64"; + case EColumnType::kSplitInt32: return "SplitInt32"; + case EColumnType::kSplitUInt32: return "SplitUInt32"; + case EColumnType::kSplitInt16: return "SplitInt16"; + case EColumnType::kSplitUInt16: return "SplitUInt16"; + default: return "UNKNOWN"; } } @@ -180,30 +161,3 @@ void ROOT::Experimental::Detail::RColumnElement::Pack( - void *dst, void *src, std::size_t count) const -{ - std::int64_t *int64Array = reinterpret_cast(src); - std::int32_t *int32Array = reinterpret_cast(dst); - for (std::size_t i = 0; i < count; ++i) { - int32Array[i] = int64Array[i]; -#if R__LITTLE_ENDIAN == 0 - int32Array[i] = RByteSwap<4>::bswap(int32Array[i]); -#endif - } -} - -void ROOT::Experimental::Detail::RColumnElement::Unpack( - void *dst, void *src, std::size_t count) const -{ - std::int32_t *int32Array = reinterpret_cast(src); - std::int64_t *int64Array = reinterpret_cast(dst); - for (std::size_t i = 0; i < count; ++i) { - int64Array[i] = int32Array[i]; -#if R__LITTLE_ENDIAN == 0 - int64Array[i] = RByteSwap<8>::bswap(int64Array[i]); -#endif - } -} diff --git a/tree/ntuple/v7/src/RDaos.cxx b/tree/ntuple/v7/src/RDaos.cxx index e3c56dd792d2c..3fc82704bdbc3 100644 --- a/tree/ntuple/v7/src/RDaos.cxx +++ b/tree/ntuple/v7/src/RDaos.cxx @@ -55,7 +55,6 @@ std::string ROOT::Experimental::Detail::RDaosPool::GetPoolUuid() //////////////////////////////////////////////////////////////////////////////// - std::string ROOT::Experimental::Detail::RDaosObject::ObjClassId::ToString() const { char name[kOCNameMaxLength + 1] = {}; @@ -63,38 +62,38 @@ std::string ROOT::Experimental::Detail::RDaosObject::ObjClassId::ToString() cons return std::string{name}; } -ROOT::Experimental::Detail::RDaosObject::FetchUpdateArgs::FetchUpdateArgs(FetchUpdateArgs &&fua) - : fDkey(fua.fDkey), fAkeys(fua.fAkeys), fIovs(fua.fIovs), fIods(std::move(fua.fIods)), fSgls(std::move(fua.fSgls)), - fEvent(std::move(fua.fEvent)) +ROOT::Experimental::Detail::RDaosObject::FetchUpdateArgs::FetchUpdateArgs(FetchUpdateArgs &&fua) noexcept + : fDkey(fua.fDkey), fRequests(fua.fRequests), fIods(std::move(fua.fIods)), fSgls(std::move(fua.fSgls)), + fEvent(fua.fEvent) { d_iov_set(&fDistributionKey, &fDkey, sizeof(fDkey)); } ROOT::Experimental::Detail::RDaosObject::FetchUpdateArgs::FetchUpdateArgs(DistributionKey_t d, - std::span as, - std::span vs, bool is_async) - : fDkey(d), fAkeys(as), fIovs(vs) + std::span rs, bool is_async) + : fDkey(d), fRequests(rs) { if (is_async) fEvent.emplace(); - fSgls.reserve(fAkeys.size()); - fIods.reserve(fAkeys.size()); + fSgls.reserve(fRequests.size()); + fIods.reserve(fRequests.size()); d_iov_set(&fDistributionKey, &fDkey, sizeof(fDkey)); - for (unsigned i = 0; i < fAkeys.size(); ++i) { + for (auto &r : fRequests) { daos_iod_t iod; iod.iod_nr = 1; - iod.iod_size = fIovs[i].iov_len; + iod.iod_size = + std::accumulate(r.fIovs.begin(), r.fIovs.end(), 0, [](size_t c, d_iov_t &iov) { return c + iov.iov_len; }); iod.iod_recxs = nullptr; iod.iod_type = DAOS_IOD_SINGLE; - d_iov_set(&iod.iod_name, const_cast(&(fAkeys[i])), sizeof(fAkeys[i])); + d_iov_set(&iod.iod_name, const_cast(&r.fAkey), sizeof(r.fAkey)); fIods.push_back(iod); d_sg_list_t sgl; sgl.sg_nr_out = 0; - sgl.sg_nr = 1; - sgl.sg_iovs = &fIovs[i]; + sgl.sg_nr = r.fIovs.size(); + sgl.sg_iovs = r.fIovs.data(); fSgls.push_back(sgl); } } @@ -104,8 +103,7 @@ daos_event_t *ROOT::Experimental::Detail::RDaosObject::FetchUpdateArgs::GetEvent return fEvent ? &(fEvent.value()) : nullptr; } -ROOT::Experimental::Detail::RDaosObject::RDaosObject(RDaosContainer &container, daos_obj_id_t oid, - ObjClassId cid) +ROOT::Experimental::Detail::RDaosObject::RDaosObject(RDaosContainer &container, daos_obj_id_t oid, ObjClassId cid) { if (!cid.IsUnknown()) daos_obj_generate_oid(container.fContainerHandle, &oid, DAOS_OT_MULTI_UINT64, cid.fCid, @@ -123,13 +121,13 @@ ROOT::Experimental::Detail::RDaosObject::~RDaosObject() int ROOT::Experimental::Detail::RDaosObject::Fetch(FetchUpdateArgs &args) { return daos_obj_fetch(fObjectHandle, DAOS_TX_NONE, DAOS_COND_DKEY_FETCH | DAOS_COND_AKEY_FETCH, - &args.fDistributionKey, args.fAkeys.size(), args.fIods.data(), args.fSgls.data(), nullptr, + &args.fDistributionKey, args.fIods.size(), args.fIods.data(), args.fSgls.data(), nullptr, args.GetEventPointer()); } int ROOT::Experimental::Detail::RDaosObject::Update(FetchUpdateArgs &args) { - return daos_obj_update(fObjectHandle, DAOS_TX_NONE, 0, &args.fDistributionKey, args.fAkeys.size(), args.fIods.data(), + return daos_obj_update(fObjectHandle, DAOS_TX_NONE, 0, &args.fDistributionKey, args.fIods.size(), args.fIods.data(), args.fSgls.data(), args.GetEventPointer()); } @@ -146,7 +144,7 @@ ROOT::Experimental::Detail::RDaosEventQueue::~RDaosEventQueue() daos_eq_destroy(fQueue, 0); } -int ROOT::Experimental::Detail::RDaosEventQueue::InitializeEvent(daos_event_t *ev_ptr, daos_event_t *parent_ptr) +int ROOT::Experimental::Detail::RDaosEventQueue::InitializeEvent(daos_event_t *ev_ptr, daos_event_t *parent_ptr) const { return daos_event_init(ev_ptr, fQueue, parent_ptr); } @@ -195,7 +193,8 @@ ROOT::Experimental::Detail::RDaosContainer::RDaosContainer(std::shared_ptr iovs(1); + d_iov_set(&iovs[0], const_cast(buffer), length); + RDaosObject::RAkeyRequest requests[] = {{akey, std::move(iovs)}}; + RDaosObject::FetchUpdateArgs args(dkey, requests); return RDaosObject(*this, oid, cid.fCid).Fetch(args); } @@ -221,10 +220,11 @@ int ROOT::Experimental::Detail::RDaosContainer::WriteSingleAkey(const void *buff daos_obj_id_t oid, DistributionKey_t dkey, AttributeKey_t akey, ObjClassId_t cid) { - AttributeKey_t akeys[] = {akey}; - d_iov_t iovs[1]; + + std::vector iovs(1); d_iov_set(&iovs[0], const_cast(buffer), length); - RDaosObject::FetchUpdateArgs args(dkey, akeys, iovs); + RDaosObject::RAkeyRequest requests[] = {{akey, std::move(iovs)}}; + RDaosObject::FetchUpdateArgs args(dkey, requests); return RDaosObject(*this, oid, cid.fCid).Update(args); } @@ -243,9 +243,9 @@ int ROOT::Experimental::Detail::RDaosContainer::VectorReadWrite(MultiObjectRWOpe return ret; for (auto &[key, batch] : map) { - requests.push_back(std::make_tuple( + requests.emplace_back( std::make_unique(*this, batch.fOid, cid.fCid), - RDaosObject::FetchUpdateArgs{batch.fDistributionKey, batch.fAttributeKeys, batch.fIovs, /*is_async=*/true})); + RDaosObject::FetchUpdateArgs{batch.fDistributionKey, batch.fDataRequests, /*is_async=*/true}); if ((ret = fPool->fEventQueue->InitializeEvent(std::get<1>(requests.back()).GetEventPointer(), &parent_event)) < 0) diff --git a/tree/ntuple/v7/src/REntry.cxx b/tree/ntuple/v7/src/REntry.cxx index 1054eedb5def3..d86d901cd5723 100644 --- a/tree/ntuple/v7/src/REntry.cxx +++ b/tree/ntuple/v7/src/REntry.cxx @@ -15,26 +15,12 @@ #include #include -#include #include -ROOT::Experimental::REntry::~REntry() +void ROOT::Experimental::REntry::AddValue(Detail::RFieldBase::RValue &&value) { - for (auto idx : fManagedValues) { - fValues[idx].GetField()->DestroyValue(fValues[idx]); - } -} - -void ROOT::Experimental::REntry::AddValue(const Detail::RFieldValue& value) -{ - fManagedValues.emplace_back(fValues.size()); - fValues.push_back(value); -} - -void ROOT::Experimental::REntry::CaptureValue(const Detail::RFieldValue& value) -{ - fValues.push_back(value); + fValues.emplace_back(std::move(value)); } void ROOT::Experimental::REntry::CaptureValueUnsafe(std::string_view fieldName, void *where) @@ -42,12 +28,7 @@ void ROOT::Experimental::REntry::CaptureValueUnsafe(std::string_view fieldName, for (std::size_t i = 0; i < fValues.size(); ++i) { if (fValues[i].GetField()->GetName() != fieldName) continue; - auto itr = std::find(fManagedValues.begin(), fManagedValues.end(), i); - if (itr != fManagedValues.end()) { - fValues[i].GetField()->DestroyValue(fValues[i]); - fManagedValues.erase(itr); - } - fValues[i] = fValues[i].GetField()->CaptureValue(where); + fValues[i] = fValues[i].GetField()->BindValue(where); return; } throw RException(R__FAIL("invalid field name: " + std::string(fieldName))); diff --git a/tree/ntuple/v7/src/RField.cxx b/tree/ntuple/v7/src/RField.cxx index 3442cccac9c4c..2751d43b67b4b 100644 --- a/tree/ntuple/v7/src/RField.cxx +++ b/tree/ntuple/v7/src/RField.cxx @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -29,9 +28,15 @@ #include #include #include +#include #include #include +#include +#include #include +#include +#include +#include #include #include // for isspace @@ -125,7 +130,7 @@ std::tuple> ParseArrayType(std::string_view typ { std::vector sizeVec; - /// Only parse outer array definition, i.e. the right `]` should be at the end of the type name + // Only parse outer array definition, i.e. the right `]` should be at the end of the type name while (typeName.back() == ']') { auto posRBrace = typeName.size() - 1; auto posLBrace = typeName.find_last_of("[", posRBrace); @@ -141,20 +146,45 @@ std::tuple> ParseArrayType(std::string_view typ return std::make_tuple(std::string{typeName}, sizeVec); } -std::string GetNormalizedType(const std::string &typeName) { - std::string normalizedType( - TClassEdit::ResolveTypedef(TClassEdit::CleanType(typeName.c_str(), - /*mode=*/2).c_str())); +/// Return the canonical name of a type, resolving typedefs to their underlying types if needed. A canonical type has +/// typedefs stripped out from the type name. +std::string GetCanonicalTypeName(const std::string &typeName) +{ + // The following types are asummed to be canonical names; thus, do not perform `typedef` resolution on those + if (typeName == "ROOT::Experimental::ClusterSize_t" || typeName.substr(0, 5) == "std::" || + typeName.substr(0, 39) == "ROOT::Experimental::RNTupleCardinality<") + return typeName; + + return TClassEdit::ResolveTypedef(typeName.c_str()); +} + +/// Applies type name normalization rules that lead to the final name used to create a RField, e.g. transforms +/// `unsigned int` to `std::uint32_t` or `const vector` to `std::vector`. Specifically, `const` / `volatile` +/// qualifiers are removed, integral types such as `unsigned int` or `long` are translated to fixed-length integer types +/// (e.g. `std::uint32_t`), and `std::` is added to fully qualify known types in the `std` namespace. +std::string GetNormalizedTypeName(const std::string &typeName) +{ + std::string normalizedType{TClassEdit::CleanType(typeName.c_str(), /*mode=*/2)}; - auto translatedType = typeTranslationMap.find(normalizedType); - if (translatedType != typeTranslationMap.end()) - normalizedType = translatedType->second; + if (auto it = typeTranslationMap.find(normalizedType); it != typeTranslationMap.end()) + normalizedType = it->second; - if (normalizedType.substr(0, 7) == "vector<") normalizedType = "std::" + normalizedType; - if (normalizedType.substr(0, 6) == "array<") normalizedType = "std::" + normalizedType; - if (normalizedType.substr(0, 8) == "variant<") normalizedType = "std::" + normalizedType; - if (normalizedType.substr(0, 5) == "pair<") normalizedType = "std::" + normalizedType; - if (normalizedType.substr(0, 6) == "tuple<") normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 7) == "vector<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 6) == "array<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 8) == "variant<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 5) == "pair<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 6) == "tuple<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 7) == "bitset<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 11) == "unique_ptr<") + normalizedType = "std::" + normalizedType; + if (normalizedType.substr(0, 4) == "set<") + normalizedType = "std::" + normalizedType; return normalizedType; } @@ -173,8 +203,117 @@ std::tuple GetRVecDataMembers(void *rve return {begin, size, capacity}; } +std::tuple GetRVecDataMembers(const void *rvecPtr) +{ + return {GetRVecDataMembers(const_cast(rvecPtr))}; +} + +/// Applies the field IDs from 'from' to 'to', where from and to are expected to be each other's clones. +/// Used in RClassField and RCollectionClassField cloning. In these classes, we don't clone the subfields +/// but we recreate them. Therefore, the on-disk IDs need to be fixed up. +void SyncFieldIDs(const ROOT::Experimental::Detail::RFieldBase &from, ROOT::Experimental::Detail::RFieldBase &to) +{ + auto iFrom = from.cbegin(); + auto iTo = to.begin(); + for (; iFrom != from.cend(); ++iFrom, ++iTo) { + iTo->SetOnDiskId(iFrom->GetOnDiskId()); + } +} + } // anonymous namespace +//------------------------------------------------------------------------------ + +ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations::RColumnRepresentations() +{ + // A single representations with an empty set of columns + fSerializationTypes.emplace_back(ColumnRepresentation_t()); + fDeserializationTypes.emplace_back(ColumnRepresentation_t()); +} + +ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations::RColumnRepresentations( + const TypesList_t &serializationTypes, const TypesList_t &deserializationExtraTypes) + : fSerializationTypes(serializationTypes), fDeserializationTypes(serializationTypes) +{ + fDeserializationTypes.insert(fDeserializationTypes.end(), + deserializationExtraTypes.begin(), deserializationExtraTypes.end()); +} + +//------------------------------------------------------------------------------ + +ROOT::Experimental::Detail::RFieldBase::RBulk::RBulk(RBulk &&other) + : fField(other.fField), + fValueSize(other.fValueSize), + fCapacity(other.fCapacity), + fSize(other.fSize), + fNValidValues(other.fNValidValues), + fFirstIndex(other.fFirstIndex) +{ + std::swap(fValues, other.fValues); + std::swap(fMaskAvail, other.fMaskAvail); +} + +ROOT::Experimental::Detail::RFieldBase::RBulk &ROOT::Experimental::Detail::RFieldBase::RBulk::operator=(RBulk &&other) +{ + std::swap(fField, other.fField); + std::swap(fValues, other.fValues); + std::swap(fValueSize, other.fValueSize); + std::swap(fCapacity, other.fCapacity); + std::swap(fSize, other.fSize); + std::swap(fMaskAvail, other.fMaskAvail); + std::swap(fNValidValues, other.fNValidValues); + std::swap(fFirstIndex, other.fFirstIndex); + return *this; +} + +ROOT::Experimental::Detail::RFieldBase::RBulk::~RBulk() +{ + if (fValues) + ReleaseValues(); +} + +void ROOT::Experimental::Detail::RFieldBase::RBulk::ReleaseValues() +{ + if (fField->GetTraits() & RFieldBase::kTraitTriviallyDestructible) { + free(fValues); + return; + } + + for (std::size_t i = 0; i < fCapacity; ++i) { + fField->DestroyValue(GetValuePtrAt(i), true /* dtorOnly */); + } + free(fValues); +} + +void ROOT::Experimental::Detail::RFieldBase::RBulk::Reset(const RClusterIndex &firstIndex, std::size_t size) +{ + if (fCapacity < size) { + ReleaseValues(); + fValues = malloc(size * fValueSize); + + if (!(fField->GetTraits() & RFieldBase::kTraitTriviallyConstructible)) { + for (std::size_t i = 0; i < size; ++i) { + fField->GenerateValue(GetValuePtrAt(i)); + } + } + + fMaskAvail = std::make_unique(size); + fCapacity = size; + } + + std::fill(fMaskAvail.get(), fMaskAvail.get() + size, false); + fNValidValues = 0; + + fFirstIndex = firstIndex; + fSize = size; +} + +void ROOT::Experimental::Detail::RFieldBase::RBulk::CountValidValues() +{ + fNValidValues = 0; + for (std::size_t i = 0; i < fSize; ++i) + fNValidValues += static_cast(fMaskAvail[i]); +} //------------------------------------------------------------------------------ @@ -189,109 +328,166 @@ ROOT::Experimental::Detail::RFieldBase::~RFieldBase() { } +std::string ROOT::Experimental::Detail::RFieldBase::GetQualifiedFieldName() const +{ + std::string result = GetName(); + RFieldBase *parent = GetParent(); + while (parent && !parent->GetName().empty()) { + result = parent->GetName() + "." + result; + parent = parent->GetParent(); + } + return result; +} + ROOT::Experimental::RResult> ROOT::Experimental::Detail::RFieldBase::Create(const std::string &fieldName, const std::string &typeName) { - std::string normalizedType(GetNormalizedType(typeName)); - if (normalizedType.empty()) - return R__FAIL("no type name specified for Field " + fieldName); + auto typeAlias = GetNormalizedTypeName(typeName); + auto canonicalType = GetNormalizedTypeName(GetCanonicalTypeName(typeAlias)); + return R__FORWARD_RESULT(RFieldBase::Create(fieldName, canonicalType, typeAlias)); +} - std::unique_ptr result; +ROOT::Experimental::RResult> +ROOT::Experimental::Detail::RFieldBase::Create(const std::string &fieldName, const std::string &canonicalType, + const std::string &typeAlias) +{ + if (canonicalType.empty()) + return R__FAIL("no type name specified for Field " + fieldName); - if (auto [arrayBaseType, arraySize] = ParseArrayType(normalizedType); !arraySize.empty()) { + if (auto [arrayBaseType, arraySize] = ParseArrayType(canonicalType); !arraySize.empty()) { // TODO(jalopezg): support multi-dimensional row-major (C order) arrays in RArrayField if (arraySize.size() > 1) - return R__FAIL("multi-dimensional array type not supported " + normalizedType); - auto itemField = Create(GetNormalizedType(arrayBaseType), arrayBaseType); - return {std::make_unique(fieldName, itemField.Unwrap(), arraySize[0])}; + return R__FAIL("multi-dimensional array type not supported " + canonicalType); + auto itemField = Create("_0", arrayBaseType).Unwrap(); + return {std::make_unique(fieldName, std::move(itemField), arraySize[0])}; } - if (normalizedType == "ROOT::Experimental::ClusterSize_t") { + std::unique_ptr result; + + if (canonicalType == "ROOT::Experimental::ClusterSize_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "bool") { + } else if (canonicalType == "bool") { result = std::make_unique>(fieldName); - } else if (normalizedType == "char") { + } else if (canonicalType == "char") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::int8_t") { + } else if (canonicalType == "std::int8_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::uint8_t") { + } else if (canonicalType == "std::uint8_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::int16_t") { + } else if (canonicalType == "std::int16_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::uint16_t") { + } else if (canonicalType == "std::uint16_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::int32_t") { + } else if (canonicalType == "std::int32_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::uint32_t") { + } else if (canonicalType == "std::uint32_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::int64_t") { + } else if (canonicalType == "std::int64_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::uint64_t") { + } else if (canonicalType == "std::uint64_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "float") { + } else if (canonicalType == "float") { result = std::make_unique>(fieldName); - } else if (normalizedType == "double") { + } else if (canonicalType == "double") { + result = std::make_unique>(fieldName); + } else if (canonicalType == "Double32_t") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::string") { + static_cast *>(result.get())->SetDouble32(); + // Prevent the type alias from being reset by returning early + return result; + } else if (canonicalType == "std::string") { result = std::make_unique>(fieldName); - } else if (normalizedType == "std::vector") { + } else if (canonicalType == "std::vector") { result = std::make_unique>>(fieldName); - } else if (normalizedType.substr(0, 12) == "std::vector<") { - std::string itemTypeName = normalizedType.substr(12, normalizedType.length() - 13); + } else if (canonicalType.substr(0, 12) == "std::vector<") { + std::string itemTypeName = canonicalType.substr(12, canonicalType.length() - 13); auto itemField = Create("_0", itemTypeName); result = std::make_unique(fieldName, itemField.Unwrap()); - } else if (normalizedType.substr(0, 19) == "ROOT::VecOps::RVec<") { - std::string itemTypeName = normalizedType.substr(19, normalizedType.length() - 20); + } else if (canonicalType.substr(0, 19) == "ROOT::VecOps::RVec<") { + std::string itemTypeName = canonicalType.substr(19, canonicalType.length() - 20); auto itemField = Create("_0", itemTypeName); result = std::make_unique(fieldName, itemField.Unwrap()); - } else if (normalizedType.substr(0, 11) == "std::array<") { - auto arrayDef = TokenizeTypeList(normalizedType.substr(11, normalizedType.length() - 12)); + } else if (canonicalType.substr(0, 11) == "std::array<") { + auto arrayDef = TokenizeTypeList(canonicalType.substr(11, canonicalType.length() - 12)); R__ASSERT(arrayDef.size() == 2); auto arrayLength = std::stoi(arrayDef[1]); - auto itemField = Create(GetNormalizedType(arrayDef[0]), arrayDef[0]); + auto itemField = Create("_0", arrayDef[0]); result = std::make_unique(fieldName, itemField.Unwrap(), arrayLength); - } - if (normalizedType.substr(0, 13) == "std::variant<") { - auto innerTypes = TokenizeTypeList(normalizedType.substr(13, normalizedType.length() - 14)); + } else if (canonicalType.substr(0, 13) == "std::variant<") { + auto innerTypes = TokenizeTypeList(canonicalType.substr(13, canonicalType.length() - 14)); std::vector items; for (unsigned int i = 0; i < innerTypes.size(); ++i) { items.emplace_back(Create("_" + std::to_string(i), innerTypes[i]).Unwrap().release()); } result = std::make_unique(fieldName, items); - } - if (normalizedType.substr(0, 10) == "std::pair<") { - auto innerTypes = TokenizeTypeList(normalizedType.substr(10, normalizedType.length() - 11)); + } else if (canonicalType.substr(0, 10) == "std::pair<") { + auto innerTypes = TokenizeTypeList(canonicalType.substr(10, canonicalType.length() - 11)); if (innerTypes.size() != 2) return R__FAIL("the type list for std::pair must have exactly two elements"); std::array, 2> items{Create("_0", innerTypes[0]).Unwrap(), Create("_1", innerTypes[1]).Unwrap()}; result = std::make_unique(fieldName, items); - } - if (normalizedType.substr(0, 11) == "std::tuple<") { - auto innerTypes = TokenizeTypeList(normalizedType.substr(11, normalizedType.length() - 12)); + } else if (canonicalType.substr(0, 11) == "std::tuple<") { + auto innerTypes = TokenizeTypeList(canonicalType.substr(11, canonicalType.length() - 12)); std::vector> items; for (unsigned int i = 0; i < innerTypes.size(); ++i) { items.emplace_back(Create("_" + std::to_string(i), innerTypes[i]).Unwrap()); } result = std::make_unique(fieldName, items); + } else if (canonicalType.substr(0, 12) == "std::bitset<") { + auto size = std::stoull(canonicalType.substr(12, canonicalType.length() - 13)); + result = std::make_unique(fieldName, size); + } else if (canonicalType.substr(0, 16) == "std::unique_ptr<") { + std::string itemTypeName = canonicalType.substr(16, canonicalType.length() - 17); + auto itemField = Create("_0", itemTypeName).Unwrap(); + auto normalizedInnerTypeName = itemField->GetType(); + result = std::make_unique(fieldName, "std::unique_ptr<" + normalizedInnerTypeName + ">", + std::move(itemField)); + } else if (canonicalType.substr(0, 9) == "std::set<") { + std::string itemTypeName = canonicalType.substr(9, canonicalType.length() - 10); + auto itemField = Create("_0", itemTypeName).Unwrap(); + auto normalizedInnerTypeName = itemField->GetType(); + result = + std::make_unique(fieldName, "std::set<" + normalizedInnerTypeName + ">", std::move(itemField)); + } else if (canonicalType == ":Collection:") { + // TODO: create an RCollectionField? + result = std::make_unique>(fieldName); + } else if (canonicalType.substr(0, 39) == "ROOT::Experimental::RNTupleCardinality<") { + auto innerTypes = TokenizeTypeList(canonicalType.substr(39, canonicalType.length() - 40)); + if (innerTypes.size() != 1) + return R__FAIL(std::string("Field ") + fieldName + " has invalid cardinality template: " + canonicalType); + if (innerTypes[0] == "std::uint32_t") { + result = std::make_unique>>(fieldName); + } else if (innerTypes[0] == "std::uint64_t") { + result = std::make_unique>>(fieldName); + } else { + return R__FAIL(std::string("Field ") + fieldName + " has invalid cardinality template: " + canonicalType); + } } - // TODO: create an RCollectionField? - if (normalizedType == ":Collection:") - result = std::make_unique>(fieldName); if (!result) { - auto cl = TClass::GetClass(normalizedType.c_str()); + auto e = TEnum::GetEnum(canonicalType.c_str()); + if (e != nullptr) { + result = std::make_unique(fieldName, canonicalType); + } + } + + if (!result) { + auto cl = TClass::GetClass(canonicalType.c_str()); if (cl != nullptr) { if (cl->GetCollectionProxy()) - result = std::make_unique(fieldName, normalizedType); + result = std::make_unique(fieldName, canonicalType); else - result = std::make_unique(fieldName, normalizedType); + result = std::make_unique(fieldName, canonicalType); } } - if (result) + if (result) { + if (typeAlias != canonicalType) + result->fTypeAlias = typeAlias; return result; - return R__FAIL(std::string("Field ") + fieldName + " has unknown type " + normalizedType); + } + return R__FAIL(std::string("Field ") + fieldName + " has unknown type " + canonicalType); } ROOT::Experimental::RResult @@ -305,54 +501,99 @@ ROOT::Experimental::Detail::RFieldBase::EnsureValidFieldName(std::string_view fi return RResult::Success(); } +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::Detail::RFieldBase::GetColumnRepresentations() const +{ + static RColumnRepresentations representations; + return representations; +} + std::unique_ptr ROOT::Experimental::Detail::RFieldBase::Clone(std::string_view newName) const { auto clone = CloneImpl(newName); + clone->fTypeAlias = fTypeAlias; clone->fOnDiskId = fOnDiskId; clone->fDescription = fDescription; + // We can just copy the pointer because fColumnRepresentative points into a static structure + clone->fColumnRepresentative = fColumnRepresentative; return clone; } -std::size_t ROOT::Experimental::Detail::RFieldBase::AppendImpl(const ROOT::Experimental::Detail::RFieldValue& /*value*/) +std::size_t ROOT::Experimental::Detail::RFieldBase::AppendImpl(const void * /* from */) { R__ASSERT(false && "A non-simple RField must implement its own AppendImpl"); return 0; } -void ROOT::Experimental::Detail::RFieldBase::ReadGlobalImpl( - ROOT::Experimental::NTupleSize_t /*index*/, - RFieldValue* /*value*/) +void ROOT::Experimental::Detail::RFieldBase::ReadGlobalImpl(ROOT::Experimental::NTupleSize_t /*index*/, void * /* to */) { R__ASSERT(false); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::Detail::RFieldBase::GenerateValue() +std::size_t ROOT::Experimental::Detail::RFieldBase::ReadBulkImpl(const RBulkSpec &bulkSpec) +{ + const auto valueSize = GetValueSize(); + std::size_t nRead = 0; + for (std::size_t i = 0; i < bulkSpec.fCount; ++i) { + // Value not needed + if (!bulkSpec.fMaskReq[i]) + continue; + + // Value already present + if (bulkSpec.fMaskAvail[i]) + continue; + + Read(bulkSpec.fFirstIndex + i, reinterpret_cast(bulkSpec.fValues) + i * valueSize); + bulkSpec.fMaskAvail[i] = true; + nRead++; + } + return nRead; +} + +ROOT::Experimental::Detail::RFieldBase::RValue ROOT::Experimental::Detail::RFieldBase::GenerateValue() { void *where = malloc(GetValueSize()); R__ASSERT(where != nullptr); - return GenerateValue(where); + GenerateValue(where); + return RValue(this, where, true /* isOwning */); } -void ROOT::Experimental::Detail::RFieldBase::DestroyValue(const RFieldValue &value, bool dtorOnly) +void ROOT::Experimental::Detail::RFieldBase::DestroyValue(void *objPtr, bool dtorOnly) const { if (!dtorOnly) - free(value.GetRawPtr()); + free(objPtr); } -std::vector -ROOT::Experimental::Detail::RFieldBase::SplitValue(const RFieldValue & /*value*/) const +std::vector +ROOT::Experimental::Detail::RFieldBase::SplitValue(const RValue & /*value*/) const { - return std::vector(); + return std::vector(); } void ROOT::Experimental::Detail::RFieldBase::Attach( std::unique_ptr child) { + // Note that during a model update, new fields will be attached to the zero field. The zero field, however, + // does not change its inital state because only its sub fields get connected by RPageSink::UpdateSchema. + if (fState != EState::kUnconnected) + throw RException(R__FAIL("invalid attempt to attach subfield to already connected field")); child->fParent = this; fSubFields.emplace_back(std::move(child)); } +ROOT::Experimental::NTupleSize_t +ROOT::Experimental::Detail::RFieldBase::EntryToColumnElementIndex(ROOT::Experimental::NTupleSize_t globalIndex) const +{ + std::size_t result = globalIndex; + for (auto f = this; f != nullptr; f = f->GetParent()) { + auto parent = f->GetParent(); + if (parent && (parent->GetStructure() == kCollection || parent->GetStructure() == kVariant)) + return 0U; + result *= std::max(f->GetNRepetitions(), std::size_t{1U}); + } + return result; +} std::vector ROOT::Experimental::Detail::RFieldBase::GetSubFields() const { @@ -363,45 +604,70 @@ std::vector ROOT::Experimental::Detail return result; } - -void ROOT::Experimental::Detail::RFieldBase::Flush() const +void ROOT::Experimental::Detail::RFieldBase::CommitCluster() { for (auto& column : fColumns) { column->Flush(); } + CommitClusterImpl(); +} + +void ROOT::Experimental::Detail::RFieldBase::SetDescription(std::string_view description) +{ + if (fState != EState::kUnconnected) + throw RException(R__FAIL("cannot set field description once field is connected")); + fDescription = std::string(description); } +void ROOT::Experimental::Detail::RFieldBase::SetOnDiskId(DescriptorId_t id) +{ + if (fState != EState::kUnconnected) + throw RException(R__FAIL("cannot set field ID once field is connected")); + fOnDiskId = id; +} + +const ROOT::Experimental::Detail::RFieldBase::ColumnRepresentation_t & +ROOT::Experimental::Detail::RFieldBase::GetColumnRepresentative() const +{ + if (fColumnRepresentative) + return *fColumnRepresentative; + return GetColumnRepresentations().GetSerializationDefault(); +} + +void ROOT::Experimental::Detail::RFieldBase::SetColumnRepresentative(const ColumnRepresentation_t &representative) +{ + if (fState != EState::kUnconnected) + throw RException(R__FAIL("cannot set column representative once field is connected")); + const auto &validTypes = GetColumnRepresentations().GetSerializationTypes(); + auto itRepresentative = std::find(validTypes.begin(), validTypes.end(), representative); + if (itRepresentative == std::end(validTypes)) + throw RException(R__FAIL("invalid column representative")); + fColumnRepresentative = &(*itRepresentative); +} -ROOT::Experimental::EColumnType ROOT::Experimental::Detail::RFieldBase::EnsureColumnType( - const std::vector &requestedTypes, unsigned int columnIndex, const RNTupleDescriptor &desc) +const ROOT::Experimental::Detail::RFieldBase::ColumnRepresentation_t & +ROOT::Experimental::Detail::RFieldBase::EnsureCompatibleColumnTypes(const RNTupleDescriptor &desc) const { - R__ASSERT(!requestedTypes.empty()); - auto columnId = desc.FindColumnId(fOnDiskId, columnIndex); - if (columnId == kInvalidDescriptorId) { - throw RException(R__FAIL("Column missing: column #" + std::to_string(columnIndex) + - " for field " + fName)); + if (fOnDiskId == kInvalidDescriptorId) + throw RException(R__FAIL("No on-disk column information for field `" + GetQualifiedFieldName() + "`")); + + ColumnRepresentation_t onDiskTypes; + for (const auto &c : desc.GetColumnIterable(fOnDiskId)) { + onDiskTypes.emplace_back(c.GetModel().GetType()); + } + for (const auto &t : GetColumnRepresentations().GetDeserializationTypes()) { + if (t == onDiskTypes) + return t; } - const auto &columnDesc = desc.GetColumnDescriptor(columnId); - for (auto type : requestedTypes) { - if (type == columnDesc.GetModel().GetType()) - return type; + std::string columnTypeNames; + for (const auto &t : onDiskTypes) { + if (!columnTypeNames.empty()) + columnTypeNames += ", "; + columnTypeNames += RColumnElementBase::GetTypeName(t); } - throw RException(R__FAIL( - "On-disk type `" + RColumnElementBase::GetTypeName(columnDesc.GetModel().GetType()) + - "` of column #" + std::to_string(columnIndex) + " for field `" + fName + - "` is not convertible to the requested type" + [&]{ - std::string typeStr = requestedTypes.size() > 1 ? "s " : " "; - for (std::size_t i = 0; i < requestedTypes.size(); i++) { - typeStr += "`" + RColumnElementBase::GetTypeName(requestedTypes[i]) + "`"; - if (i != requestedTypes.size() - 1) { - typeStr += ", "; - } - } - return typeStr; - }() - )); - return columnDesc.GetModel().GetType(); + throw RException(R__FAIL("On-disk column types `" + columnTypeNames + "` for field `" + GetQualifiedFieldName() + + "` cannot be matched.")); } size_t ROOT::Experimental::Detail::RFieldBase::AddReadCallback(ReadCallback_t func) @@ -417,28 +683,97 @@ void ROOT::Experimental::Detail::RFieldBase::RemoveReadCallback(size_t idx) fIsSimple = (fTraits & kTraitMappable) && fReadCallbacks.empty(); } -void ROOT::Experimental::Detail::RFieldBase::ConnectPageSink(RPageSink &pageSink) +void ROOT::Experimental::Detail::RFieldBase::AutoAdjustColumnTypes(const RNTupleWriteOptions &options) +{ + if ((options.GetCompression() == 0) && HasDefaultColumnRepresentative()) { + ColumnRepresentation_t rep = GetColumnRepresentative(); + for (auto &colType : rep) { + switch (colType) { + case EColumnType::kSplitIndex64: colType = EColumnType::kIndex64; break; + case EColumnType::kSplitIndex32: colType = EColumnType::kIndex32; break; + case EColumnType::kSplitReal64: colType = EColumnType::kReal64; break; + case EColumnType::kSplitReal32: colType = EColumnType::kReal32; break; + case EColumnType::kSplitInt64: colType = EColumnType::kInt64; break; + case EColumnType::kSplitInt32: colType = EColumnType::kInt32; break; + case EColumnType::kSplitInt16: colType = EColumnType::kInt16; break; + default: break; + } + } + SetColumnRepresentative(rep); + } + + if (options.GetHasSmallClusters()) { + ColumnRepresentation_t rep = GetColumnRepresentative(); + for (auto &colType : rep) { + switch (colType) { + case EColumnType::kSplitIndex64: colType = EColumnType::kSplitIndex32; break; + case EColumnType::kIndex64: colType = EColumnType::kIndex32; break; + default: break; + } + } + SetColumnRepresentative(rep); + } + + if (fTypeAlias == "Double32_t") + SetColumnRepresentative({EColumnType::kSplitReal32}); +} + +void ROOT::Experimental::Detail::RFieldBase::ConnectPageSink(RPageSink &pageSink, NTupleSize_t firstEntry) { - R__ASSERT(fColumns.empty()); + if (dynamic_cast(this)) + throw RException(R__FAIL("invalid attempt to connect zero field to page sink")); + if (fState != EState::kUnconnected) + throw RException(R__FAIL("invalid attempt to connect an already connected field to a page sink")); + + AutoAdjustColumnTypes(pageSink.GetWriteOptions()); + GenerateColumnsImpl(); if (!fColumns.empty()) fPrincipalColumn = fColumns[0].get(); - for (auto& column : fColumns) - column->Connect(fOnDiskId, &pageSink); + for (auto &column : fColumns) { + auto firstElementIndex = (column.get() == fPrincipalColumn) ? EntryToColumnElementIndex(firstEntry) : 0; + column->Connect(fOnDiskId, &pageSink, firstElementIndex); + } + + fState = EState::kConnectedToSink; } void ROOT::Experimental::Detail::RFieldBase::ConnectPageSource(RPageSource &pageSource) { - R__ASSERT(fColumns.empty()); + if (dynamic_cast(this)) + throw RException(R__FAIL("invalid attempt to connect zero field to page source")); + if (fState != EState::kUnconnected) + throw RException(R__FAIL("invalid attempt to connect an already connected field to a page source")); + + if (fColumnRepresentative) + throw RException(R__FAIL("fixed column representative only valid when connecting to a page sink")); + if (!fDescription.empty()) + throw RException(R__FAIL("setting description only valid when connecting to a page sink")); + { const auto descriptorGuard = pageSource.GetSharedDescriptorGuard(); - GenerateColumnsImpl(descriptorGuard.GetRef()); + const RNTupleDescriptor &desc = descriptorGuard.GetRef(); + GenerateColumnsImpl(desc); + ColumnRepresentation_t onDiskColumnTypes; + for (const auto &c : fColumns) { + onDiskColumnTypes.emplace_back(c->GetModel().GetType()); + } + for (const auto &t : GetColumnRepresentations().GetDeserializationTypes()) { + if (t == onDiskColumnTypes) + fColumnRepresentative = &t; + } + R__ASSERT(fColumnRepresentative); + if (fOnDiskId != kInvalidDescriptorId) + fOnDiskTypeVersion = desc.GetFieldDescriptor(fOnDiskId).GetTypeVersion(); } if (!fColumns.empty()) fPrincipalColumn = fColumns[0].get(); for (auto& column : fColumns) column->Connect(fOnDiskId, &pageSource); + OnConnectPageSource(); + + fState = EState::kConnectedToSource; } @@ -447,49 +782,8 @@ void ROOT::Experimental::Detail::RFieldBase::AcceptVisitor(Detail::RFieldVisitor visitor.VisitField(*this); } - -ROOT::Experimental::Detail::RFieldBase::RSchemaIterator ROOT::Experimental::Detail::RFieldBase::begin() -{ - if (fSubFields.empty()) return RSchemaIterator(this, -1); - return RSchemaIterator(this->fSubFields[0].get(), 0); -} - - -ROOT::Experimental::Detail::RFieldBase::RSchemaIterator ROOT::Experimental::Detail::RFieldBase::end() -{ - return RSchemaIterator(this, -1); -} - - //----------------------------------------------------------------------------- - -void ROOT::Experimental::Detail::RFieldBase::RSchemaIterator::Advance() -{ - auto itr = fStack.rbegin(); - if (!itr->fFieldPtr->fSubFields.empty()) { - fStack.emplace_back(Position(itr->fFieldPtr->fSubFields[0].get(), 0)); - return; - } - - unsigned int nextIdxInParent = ++(itr->fIdxInParent); - while (nextIdxInParent >= itr->fFieldPtr->fParent->fSubFields.size()) { - if (fStack.size() == 1) { - itr->fFieldPtr = itr->fFieldPtr->fParent; - itr->fIdxInParent = -1; - return; - } - fStack.pop_back(); - itr = fStack.rbegin(); - nextIdxInParent = ++(itr->fIdxInParent); - } - itr->fFieldPtr = itr->fFieldPtr->fParent->fSubFields[nextIdxInParent].get(); -} - - -//------------------------------------------------------------------------------ - - std::unique_ptr ROOT::Experimental::RFieldZero::CloneImpl(std::string_view /*newName*/) const { @@ -508,18 +802,24 @@ void ROOT::Experimental::RFieldZero::AcceptVisitor(Detail::RFieldVisitor &visito //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; +} void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -529,17 +829,56 @@ void ROOT::Experimental::RField::AcceptVisito //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RCardinalityField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; +} + +void ROOT::Experimental::RCardinalityField::GenerateColumnsImpl(const RNTupleDescriptor &desc) +{ + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); +} + +void ROOT::Experimental::RCardinalityField::AcceptVisitor(Detail::RFieldVisitor &visitor) const +{ + visitor.VisitCardinalityField(*this); +} + +const ROOT::Experimental::RField> * +ROOT::Experimental::RCardinalityField::As32Bit() const +{ + return dynamic_cast> *>(this); +} + +const ROOT::Experimental::RField> * +ROOT::Experimental::RCardinalityField::As64Bit() const +{ + return dynamic_cast> *>(this); +} + +//------------------------------------------------------------------------------ + +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kChar}}, {{}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kChar, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - char, EColumnType::kChar>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kChar}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -549,17 +888,22 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visi //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kInt8}}, {{EColumnType::kUInt8}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt8, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - std::int8_t, EColumnType::kInt8>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt8}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -569,17 +913,22 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisito //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kUInt8}}, {{EColumnType::kInt8}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt8, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - std::uint8_t, EColumnType::kInt8>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt8}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -589,18 +938,22 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisit //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kBit}}, {}); + return representations; +} void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kBit, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kBit}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -610,18 +963,22 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visi //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitReal32}, {EColumnType::kReal32}}, {}); + return representations; +} void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kReal32, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kReal32}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -632,17 +989,23 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &vis //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitReal64}, {EColumnType::kReal64}, {EColumnType::kSplitReal32}, {EColumnType::kReal32}}, {}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kReal64, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kReal64}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -650,19 +1013,30 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &vi visitor.VisitDoubleField(*this); } +void ROOT::Experimental::RField::SetDouble32() +{ + fTypeAlias = "Double32_t"; +} + //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitInt16}, {EColumnType::kInt16}}, + {{EColumnType::kSplitUInt16}, {EColumnType::kUInt16}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt16, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - std::int16_t, EColumnType::kInt16>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt16}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -672,17 +1046,23 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisit //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitUInt16}, {EColumnType::kUInt16}}, + {{EColumnType::kSplitInt16}, {EColumnType::kInt16}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt16, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - std::uint16_t, EColumnType::kInt16>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt16}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -692,17 +1072,23 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisi //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitInt32}, {EColumnType::kInt32}}, + {{EColumnType::kSplitUInt32}, {EColumnType::kUInt32}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt32, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr(Detail::RColumn::Create< - std::int32_t, EColumnType::kInt32>(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt32}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -712,17 +1098,23 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisit //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitUInt32}, {EColumnType::kUInt32}}, + {{EColumnType::kSplitInt32}, {EColumnType::kInt32}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt32, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt32}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -732,17 +1124,23 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisi //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitUInt64}, {EColumnType::kUInt64}}, + {{EColumnType::kSplitInt64}, {EColumnType::kInt64}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt64, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kInt64}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -752,24 +1150,28 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisi //------------------------------------------------------------------------------ +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSplitInt64}, {EColumnType::kInt64}}, + {{EColumnType::kSplitUInt64}, + {EColumnType::kUInt64}, + {EColumnType::kInt32}, + {EColumnType::kSplitInt32}, + {EColumnType::kUInt32}, + {EColumnType::kSplitUInt32}}); + return representations; +} + void ROOT::Experimental::RField::GenerateColumnsImpl() { - RColumnModel model(EColumnType::kInt64, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - auto type = EnsureColumnType({EColumnType::kInt64, EColumnType::kInt32}, 0, desc); - RColumnModel model(type, false /* isSorted*/); - if (type == EColumnType::kInt64) { - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); - } else { - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(model, 0))); - } + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -779,39 +1181,49 @@ void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisit //------------------------------------------------------------------------------ -void ROOT::Experimental::RField::GenerateColumnsImpl() +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField::GetColumnRepresentations() const { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelIndex, 0))); + static RColumnRepresentations representations({{EColumnType::kSplitIndex64, EColumnType::kChar}, + {EColumnType::kIndex64, EColumnType::kChar}, + {EColumnType::kSplitIndex32, EColumnType::kChar}, + {EColumnType::kIndex32, EColumnType::kChar}}, + {}); + return representations; +} - RColumnModel modelChars(EColumnType::kChar, false /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelChars, 1))); +void ROOT::Experimental::RField::GenerateColumnsImpl() +{ + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[1]), 1)); } void ROOT::Experimental::RField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - EnsureColumnType({EColumnType::kChar}, 1, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[1]), 1)); } -std::size_t ROOT::Experimental::RField::AppendImpl(const ROOT::Experimental::Detail::RFieldValue& value) +void ROOT::Experimental::RField::DestroyValue(void *objPtr, bool dtorOnly) const { - auto typedValue = value.Get(); + std::destroy_at(static_cast(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); +} + +std::size_t ROOT::Experimental::RField::AppendImpl(const void *from) +{ + auto typedValue = static_cast(from); auto length = typedValue->length(); - Detail::RColumnElement elemChars(const_cast(typedValue->data())); - fColumns[1]->AppendV(elemChars, length); + fColumns[1]->AppendV(typedValue->data(), length); fIndex += length; - fColumns[0]->Append(fElemIndex); - return length + sizeof(fElemIndex); + fColumns[0]->Append(&fIndex); + return length + fColumns[0]->GetElement()->GetPackedSize(); } -void ROOT::Experimental::RField::ReadGlobalImpl( - ROOT::Experimental::NTupleSize_t globalIndex, ROOT::Experimental::Detail::RFieldValue *value) +void ROOT::Experimental::RField::ReadGlobalImpl(ROOT::Experimental::NTupleSize_t globalIndex, void *to) { - auto typedValue = value->Get(); + auto typedValue = static_cast(to); RClusterIndex collectionStart; ClusterSize_t nChars; fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &nChars); @@ -819,16 +1231,10 @@ void ROOT::Experimental::RField::ReadGlobalImpl( typedValue->clear(); } else { typedValue->resize(nChars); - Detail::RColumnElement elemChars(const_cast(typedValue->data())); - fColumns[1]->ReadV(collectionStart, nChars, &elemChars); + fColumns[1]->ReadV(collectionStart, nChars, const_cast(typedValue->data())); } } -void ROOT::Experimental::RField::CommitCluster() -{ - fIndex = 0; -} - void ROOT::Experimental::RField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { visitor.VisitStringField(*this); @@ -855,7 +1261,7 @@ ROOT::Experimental::RClassField::RClassField(std::string_view fieldName, std::st } if (fClass->GetCollectionProxy()) { throw RException( - R__FAIL(std::string(className) + " has an associated collection proxy; use RCollectionClassField instead")); + R__FAIL(std::string(className) + " has an associated collection proxy; use RProxiedCollectionField instead")); } if (!(fClass->ClassProperty() & kClassHasExplicitCtor)) @@ -884,13 +1290,14 @@ ROOT::Experimental::RClassField::RClassField(std::string_view fieldName, std::st continue; } - std::string typeName{dataMember->GetFullTypeName()}; + std::string typeName{GetNormalizedTypeName(dataMember->GetTrueTypeName())}; + std::string typeAlias{GetNormalizedTypeName(dataMember->GetFullTypeName())}; // For C-style arrays, complete the type name with the size for each dimension, e.g. `int[4][2]` if (dataMember->Property() & kIsArray) { for (int dim = 0, n = dataMember->GetArrayDim(); dim < n; ++dim) typeName += "[" + std::to_string(dataMember->GetMaxIndex(dim)) + "]"; } - auto subField = Detail::RFieldBase::Create(dataMember->GetName(), typeName).Unwrap(); + auto subField = Detail::RFieldBase::Create(dataMember->GetName(), typeName, typeAlias).Unwrap(); fTraits &= subField->GetTraits(); Attach(std::move(subField), RSubFieldInfo{kDataMember, static_cast(dataMember->GetOffset())}); @@ -904,109 +1311,241 @@ void ROOT::Experimental::RClassField::Attach(std::unique_ptr RFieldBase::Attach(std::move(child)); } +void ROOT::Experimental::RClassField::AddReadCallbacksFromIORules(const std::span rules, + TClass *classp) +{ + for (const auto rule : rules) { + if (rule->GetRuleType() != ROOT::TSchemaRule::kReadRule) { + R__LOG_WARNING(NTupleLog()) << "ignoring I/O customization rule with unsupported type"; + continue; + } + auto func = rule->GetReadFunctionPointer(); + R__ASSERT(func != nullptr); + fReadCallbacks.emplace_back([func, classp](void *target) { + TVirtualObject oldObj{nullptr}; + oldObj.fClass = classp; + oldObj.fObject = target; + func(static_cast(target), &oldObj); + oldObj.fClass = nullptr; // TVirtualObject does not own the value + }); + } +} + std::unique_ptr ROOT::Experimental::RClassField::CloneImpl(std::string_view newName) const { - return std::unique_ptr(new RClassField(newName, GetType(), fClass)); + auto result = std::unique_ptr(new RClassField(newName, GetType(), fClass)); + SyncFieldIDs(*this, *result); + return result; } -std::size_t ROOT::Experimental::RClassField::AppendImpl(const Detail::RFieldValue& value) { +std::size_t ROOT::Experimental::RClassField::AppendImpl(const void *from) +{ std::size_t nbytes = 0; for (unsigned i = 0; i < fSubFields.size(); i++) { - auto memberValue = fSubFields[i]->CaptureValue(value.Get() + fSubFieldsInfo[i].fOffset); - nbytes += fSubFields[i]->Append(memberValue); + nbytes += CallAppendOn(*fSubFields[i], static_cast(from) + fSubFieldsInfo[i].fOffset); } return nbytes; } -void ROOT::Experimental::RClassField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RClassField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { for (unsigned i = 0; i < fSubFields.size(); i++) { - auto memberValue = fSubFields[i]->CaptureValue(value->Get() + fSubFieldsInfo[i].fOffset); - fSubFields[i]->Read(globalIndex, &memberValue); + CallReadOn(*fSubFields[i], globalIndex, static_cast(to) + fSubFieldsInfo[i].fOffset); } } -void ROOT::Experimental::RClassField::ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RClassField::ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) { for (unsigned i = 0; i < fSubFields.size(); i++) { - auto memberValue = fSubFields[i]->CaptureValue(value->Get() + fSubFieldsInfo[i].fOffset); - fSubFields[i]->Read(clusterIndex, &memberValue); + CallReadOn(*fSubFields[i], clusterIndex, static_cast(to) + fSubFieldsInfo[i].fOffset); } } -void ROOT::Experimental::RClassField::GenerateColumnsImpl() +void ROOT::Experimental::RClassField::OnConnectPageSource() { + // Add post-read callbacks for I/O customization rules; only rules that target transient members are allowed for now + // TODO(jalopezg): revise after supporting schema evolution + const auto ruleset = fClass->GetSchemaRules(); + if (!ruleset) + return; + auto referencesNonTransientMembers = [klass = fClass](const ROOT::TSchemaRule *rule) { + if (rule->GetTarget() == nullptr) + return false; + for (auto target : ROOT::Detail::TRangeStaticCast(*rule->GetTarget())) { + const auto dataMember = klass->GetDataMember(target->GetString()); + if (!dataMember || dataMember->IsPersistent()) { + R__LOG_WARNING(NTupleLog()) << "ignoring I/O customization rule with non-transient member: " + << dataMember->GetName(); + return true; + } + } + return false; + }; + + auto rules = ruleset->FindRules(fClass->GetName(), static_cast(GetOnDiskTypeVersion())); + rules.erase(std::remove_if(rules.begin(), rules.end(), referencesNonTransientMembers), rules.end()); + AddReadCallbacksFromIORules(rules, fClass); } -void ROOT::Experimental::RClassField::GenerateColumnsImpl(const RNTupleDescriptor &) +void ROOT::Experimental::RClassField::GenerateValue(void *where) const { + fClass->New(where); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RClassField::GenerateValue(void* where) +void ROOT::Experimental::RClassField::DestroyValue(void *objPtr, bool dtorOnly) const { - return Detail::RFieldValue(true /* captureFlag */, this, fClass->New(where)); + fClass->Destructor(objPtr, true /* dtorOnly */); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } -void ROOT::Experimental::RClassField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +std::vector +ROOT::Experimental::RClassField::SplitValue(const RValue &value) const { - fClass->Destructor(value.GetRawPtr(), true /* dtorOnly */); - if (!dtorOnly) - free(value.GetRawPtr()); + std::vector result; + for (unsigned i = 0; i < fSubFields.size(); i++) { + result.emplace_back(fSubFields[i]->BindValue(value.Get() + fSubFieldsInfo[i].fOffset)); + } + return result; } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RClassField::CaptureValue(void* where) + +size_t ROOT::Experimental::RClassField::GetValueSize() const { - return Detail::RFieldValue(true /* captureFlat */, this, where); + return fClass->GetClassSize(); } +std::uint32_t ROOT::Experimental::RClassField::GetTypeVersion() const +{ + return fClass->GetClassVersion(); +} -std::vector -ROOT::Experimental::RClassField::SplitValue(const Detail::RFieldValue &value) const +void ROOT::Experimental::RClassField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { - std::vector result; - for (unsigned i = 0; i < fSubFields.size(); i++) { - auto memberValue = fSubFields[i]->CaptureValue(value.Get() + fSubFieldsInfo[i].fOffset); - result.emplace_back(memberValue); + visitor.VisitClassField(*this); +} + +//------------------------------------------------------------------------------ + +ROOT::Experimental::REnumField::REnumField(std::string_view fieldName, std::string_view enumName) + : REnumField(fieldName, enumName, TEnum::GetEnum(std::string(enumName).c_str())) +{ +} + +ROOT::Experimental::REnumField::REnumField(std::string_view fieldName, std::string_view enumName, TEnum *enump) + : ROOT::Experimental::Detail::RFieldBase(fieldName, enumName, ENTupleStructure::kLeaf, false /* isSimple */) +{ + if (enump == nullptr) { + throw RException(R__FAIL("RField: no I/O support for enum type " + std::string(enumName))); } - return result; + // Avoid accidentally supporting std types through TEnum. + if (enump->Property() & kIsDefinedInStd) { + throw RException(R__FAIL(std::string(enumName) + " is not supported")); + } + + switch (enump->GetUnderlyingType()) { + case kChar_t: Attach(std::make_unique>("_0")); break; + case kUChar_t: Attach(std::make_unique>("_0")); break; + case kShort_t: Attach(std::make_unique>("_0")); break; + case kUShort_t: Attach(std::make_unique>("_0")); break; + case kInt_t: Attach(std::make_unique>("_0")); break; + case kUInt_t: Attach(std::make_unique>("_0")); break; + case kLong_t: + case kLong64_t: Attach(std::make_unique>("_0")); break; + case kULong_t: + case kULong64_t: Attach(std::make_unique>("_0")); break; + default: throw RException(R__FAIL("Unsupported underlying integral type for enum type " + std::string(enumName))); + } + + fTraits |= kTraitTriviallyConstructible | kTraitTriviallyDestructible; +} + +ROOT::Experimental::REnumField::REnumField(std::string_view fieldName, std::string_view enumName, + std::unique_ptr intField) + : ROOT::Experimental::Detail::RFieldBase(fieldName, enumName, ENTupleStructure::kLeaf, false /* isSimple */) +{ + Attach(std::move(intField)); + fTraits |= kTraitTriviallyConstructible | kTraitTriviallyDestructible; +} + +std::unique_ptr +ROOT::Experimental::REnumField::CloneImpl(std::string_view newName) const +{ + auto newIntField = fSubFields[0]->Clone(fSubFields[0]->GetName()); + return std::unique_ptr(new REnumField(newName, GetType(), std::move(newIntField))); } - -size_t ROOT::Experimental::RClassField::GetValueSize() const +std::vector +ROOT::Experimental::REnumField::SplitValue(const RValue &value) const { - return fClass->GetClassSize(); + std::vector result; + result.emplace_back(fSubFields[0]->BindValue(value.GetRawPtr())); + return result; } -void ROOT::Experimental::RClassField::AcceptVisitor(Detail::RFieldVisitor &visitor) const +void ROOT::Experimental::REnumField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { - visitor.VisitClassField(*this); + visitor.VisitEnumField(*this); } //------------------------------------------------------------------------------ -ROOT::Experimental::RCollectionClassField::RCollectionClassField(std::string_view fieldName, std::string_view className) - : RCollectionClassField(fieldName, className, TClass::GetClass(std::string(className).c_str())) +ROOT::Experimental::RProxiedCollectionField::RCollectionIterableOnce::RIteratorFuncs +ROOT::Experimental::RProxiedCollectionField::RCollectionIterableOnce::GetIteratorFuncs(TVirtualCollectionProxy *proxy, + bool readFromDisk) { + RIteratorFuncs ifuncs; + ifuncs.fCreateIterators = proxy->GetFunctionCreateIterators(readFromDisk); + ifuncs.fDeleteTwoIterators = proxy->GetFunctionDeleteTwoIterators(readFromDisk); + ifuncs.fNext = proxy->GetFunctionNext(readFromDisk); + R__ASSERT((ifuncs.fCreateIterators != nullptr) && (ifuncs.fDeleteTwoIterators != nullptr) && + (ifuncs.fNext != nullptr)); + return ifuncs; } -ROOT::Experimental::RCollectionClassField::RCollectionClassField(std::string_view fieldName, std::string_view className, - TClass *classp) - : ROOT::Experimental::Detail::RFieldBase(fieldName, className, ENTupleStructure::kCollection, false /* isSimple */), - fNWritten(0) +ROOT::Experimental::RProxiedCollectionField::RProxiedCollectionField(std::string_view fieldName, + std::string_view typeName, TClass *classp) + : Detail::RFieldBase(fieldName, typeName, ENTupleStructure::kCollection, false /* isSimple */), fNWritten(0) { if (classp == nullptr) - throw RException(R__FAIL("RField: no I/O support for collection proxy type " + std::string(className))); + throw RException(R__FAIL("RField: no I/O support for collection proxy type " + std::string(typeName))); if (!classp->GetCollectionProxy()) - throw RException(R__FAIL(std::string(className) + " has no associated collection proxy")); + throw RException(R__FAIL(std::string(typeName) + " has no associated collection proxy")); fProxy.reset(classp->GetCollectionProxy()->Generate()); + fProperties = fProxy->GetProperties(); + fCollectionType = fProxy->GetCollectionType(); if (fProxy->HasPointers()) throw RException(R__FAIL("collection proxies whose value type is a pointer are not supported")); - if (fProxy->GetProperties() & TVirtualCollectionProxy::kIsAssociative) - throw RException(R__FAIL("associative collections not supported")); + if (!fProxy->GetCollectionClass()->HasDictionary()) { + throw RException(R__FAIL("dictionary not available for type " + + GetNormalizedTypeName(fProxy->GetCollectionClass()->GetName()))); + } + + fIFuncsRead = RCollectionIterableOnce::GetIteratorFuncs(fProxy.get(), true /* readFromDisk */); + fIFuncsWrite = RCollectionIterableOnce::GetIteratorFuncs(fProxy.get(), false /* readFromDisk */); +} + +ROOT::Experimental::RProxiedCollectionField::RProxiedCollectionField(std::string_view fieldName, + std::string_view typeName, + std::unique_ptr itemField) + : RProxiedCollectionField(fieldName, typeName, TClass::GetClass(std::string(typeName).c_str())) +{ + fItemSize = itemField->GetValueSize(); + Attach(std::move(itemField)); +} + +ROOT::Experimental::RProxiedCollectionField::RProxiedCollectionField(std::string_view fieldName, + std::string_view typeName) + : RProxiedCollectionField(fieldName, typeName, TClass::GetClass(std::string(typeName).c_str())) +{ + // TODO(jalopezg, fdegeus) Full support for associative collections (both custom and STL) will be handled in a + // follow-up PR. + if (fProperties & TVirtualCollectionProxy::kIsAssociative) + throw RException(R__FAIL("custom associative collection proxies not supported")); std::unique_ptr itemField; + if (auto valueClass = fProxy->GetValueClass()) { // Element type is a class itemField = RFieldBase::Create("_0", valueClass->GetName()).Unwrap(); @@ -1033,123 +1572,107 @@ ROOT::Experimental::RCollectionClassField::RCollectionClassField(std::string_vie throw RException(R__FAIL("unsupported value type")); } } + fItemSize = itemField->GetValueSize(); Attach(std::move(itemField)); } std::unique_ptr -ROOT::Experimental::RCollectionClassField::CloneImpl(std::string_view newName) const +ROOT::Experimental::RProxiedCollectionField::CloneImpl(std::string_view newName) const { - return std::unique_ptr( - new RCollectionClassField(newName, GetType(), fProxy->GetCollectionClass())); + auto newItemField = fSubFields[0]->Clone(fSubFields[0]->GetName()); + return std::unique_ptr( + new RProxiedCollectionField(newName, GetType(), std::move(newItemField))); } -std::size_t ROOT::Experimental::RCollectionClassField::AppendImpl(const Detail::RFieldValue &value) +std::size_t ROOT::Experimental::RProxiedCollectionField::AppendImpl(const void *from) { - TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), value.GetRawPtr()); std::size_t nbytes = 0; - auto count = fProxy->Size(); - for (unsigned i = 0; i < count; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(fProxy->At(i)); - nbytes += fSubFields[0]->Append(itemValue); + unsigned count = 0; + TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), const_cast(from)); + for (auto ptr : RCollectionIterableOnce{const_cast(from), fIFuncsWrite, fProxy.get(), + (fCollectionType == kSTLvector ? fItemSize : 0U)}) { + nbytes += CallAppendOn(*fSubFields[0], ptr); + count++; } - Detail::RColumnElement elemIndex(&fNWritten); + fNWritten += count; - fColumns[0]->Append(elemIndex); - return nbytes + sizeof(elemIndex); + fColumns[0]->Append(&fNWritten); + return nbytes + fColumns[0]->GetElement()->GetPackedSize(); } -void ROOT::Experimental::RCollectionClassField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RProxiedCollectionField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { - TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), value->GetRawPtr()); - ClusterSize_t nItems; RClusterIndex collectionStart; fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &nItems); - // `TVirtualCollectionProxy::Clear()` is responsible for destroying the items in the collection - fProxy->Clear("force"); + TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), to); + void *obj = + fProxy->Allocate(static_cast(nItems), (fProperties & TVirtualCollectionProxy::kNeedDelete)); - // Avoid heap fragmentation at the cost of temporarily allocating slightly more memory - const size_t buffSize = std::max(kReadChunkSize, fItemSize); - const std::uint32_t nItemsPerChunk = buffSize / fItemSize; - auto buff = std::make_unique(buffSize); - - auto nItemsLeft = static_cast(nItems); - while (nItemsLeft > 0) { - auto count = std::min(nItemsLeft, nItemsPerChunk); - for (std::size_t i = 0; i < count; ++i) { - auto itemValue = fSubFields[0]->GenerateValue(buff.get() + (i * fItemSize)); - fSubFields[0]->Read(collectionStart + i, &itemValue); - } - fProxy->Insert(buff.get(), value->GetRawPtr(), count); - for (std::size_t i = 0; i < count; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(buff.get() + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); - } - collectionStart = collectionStart + count; - nItemsLeft -= count; + unsigned i = 0; + for (auto elementPtr : RCollectionIterableOnce{obj, fIFuncsRead, fProxy.get(), + (fCollectionType == kSTLvector || obj != to ? fItemSize : 0U)}) { + CallReadOn(*fSubFields[0], collectionStart + (i++), elementPtr); } + if (obj != to) + fProxy->Commit(obj); } -void ROOT::Experimental::RCollectionClassField::GenerateColumnsImpl() +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RProxiedCollectionField::GetColumnRepresentations() const { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back( - std::unique_ptr(Detail::RColumn::Create(modelIndex, 0))); + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; } -void ROOT::Experimental::RCollectionClassField::GenerateColumnsImpl(const RNTupleDescriptor &desc) +void ROOT::Experimental::RProxiedCollectionField::GenerateColumnsImpl() { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RCollectionClassField::GenerateValue(void *where) +void ROOT::Experimental::RProxiedCollectionField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - return Detail::RFieldValue(true /* captureFlag */, this, fProxy->New(where)); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } -void ROOT::Experimental::RCollectionClassField::DestroyValue(const Detail::RFieldValue &value, bool dtorOnly) +void ROOT::Experimental::RProxiedCollectionField::GenerateValue(void *where) const { - TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), value.GetRawPtr()); - if (fProxy->GetProperties() & TVirtualCollectionProxy::kNeedDelete) { - auto nItems = fProxy->Size(); - for (unsigned i = 0; i < nItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(fProxy->At(i)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); - } - } - fProxy->Destructor(value.GetRawPtr(), true /* dtorOnly */); - if (!dtorOnly) - free(value.GetRawPtr()); + fProxy->New(where); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RCollectionClassField::CaptureValue(void *where) +void ROOT::Experimental::RProxiedCollectionField::DestroyValue(void *objPtr, bool dtorOnly) const { - return Detail::RFieldValue(true /* captureFlag */, this, where); + if (fProperties & TVirtualCollectionProxy::kNeedDelete) { + TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), objPtr); + for (auto ptr : RCollectionIterableOnce{objPtr, fIFuncsWrite, fProxy.get(), + (fCollectionType == kSTLvector ? fItemSize : 0U)}) { + CallDestroyValueOn(*fSubFields[0], ptr, true /* dtorOnly */); + } + } + fProxy->Destructor(objPtr, true /* dtorOnly */); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } -std::vector -ROOT::Experimental::RCollectionClassField::SplitValue(const Detail::RFieldValue &value) const +std::vector +ROOT::Experimental::RProxiedCollectionField::SplitValue(const RValue &value) const { + std::vector result; TVirtualCollectionProxy::TPushPop RAII(fProxy.get(), value.GetRawPtr()); - auto nItems = fProxy->Size(); - std::vector result; - for (unsigned i = 0; i < nItems; ++i) { - result.emplace_back(fSubFields[0]->CaptureValue(fProxy->At(i))); + for (auto ptr : RCollectionIterableOnce{value.GetRawPtr(), fIFuncsWrite, fProxy.get(), + (fCollectionType == kSTLvector ? fItemSize : 0U)}) { + result.emplace_back(fSubFields[0]->BindValue(ptr)); } return result; } -void ROOT::Experimental::RCollectionClassField::CommitCluster() +void ROOT::Experimental::RProxiedCollectionField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { - fNWritten = 0; -} - -void ROOT::Experimental::RCollectionClassField::AcceptVisitor(Detail::RFieldVisitor &visitor) const -{ - visitor.VisitCollectionClassField(*this); + visitor.VisitProxiedCollectionField(*this); } //------------------------------------------------------------------------------ @@ -1212,62 +1735,50 @@ ROOT::Experimental::RRecordField::CloneImpl(std::string_view newName) const return std::unique_ptr(new RRecordField(newName, std::move(cloneItems), fOffsets, GetType())); } -std::size_t ROOT::Experimental::RRecordField::AppendImpl(const Detail::RFieldValue &value) { +std::size_t ROOT::Experimental::RRecordField::AppendImpl(const void *from) +{ std::size_t nbytes = 0; for (unsigned i = 0; i < fSubFields.size(); ++i) { - auto memberValue = fSubFields[i]->CaptureValue(value.Get() + fOffsets[i]); - nbytes += fSubFields[i]->Append(memberValue); + nbytes += CallAppendOn(*fSubFields[i], static_cast(from) + fOffsets[i]); } return nbytes; } -void ROOT::Experimental::RRecordField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RRecordField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { for (unsigned i = 0; i < fSubFields.size(); ++i) { - auto memberValue = fSubFields[i]->CaptureValue(value->Get() + fOffsets[i]); - fSubFields[i]->Read(globalIndex, &memberValue); + CallReadOn(*fSubFields[i], globalIndex, static_cast(to) + fOffsets[i]); } } -void ROOT::Experimental::RRecordField::ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RRecordField::ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) { for (unsigned i = 0; i < fSubFields.size(); ++i) { - auto memberValue = fSubFields[i]->CaptureValue(value->Get() + fOffsets[i]); - fSubFields[i]->Read(clusterIndex, &memberValue); + CallReadOn(*fSubFields[i], clusterIndex, static_cast(to) + fOffsets[i]); } } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RRecordField::GenerateValue(void *where) +void ROOT::Experimental::RRecordField::GenerateValue(void *where) const { for (unsigned i = 0; i < fSubFields.size(); ++i) { - fSubFields[i]->GenerateValue(static_cast(where) + fOffsets[i]); + CallGenerateValueOn(*fSubFields[i], static_cast(where) + fOffsets[i]); } - return Detail::RFieldValue(true /* captureFlag */, this, where); } -void ROOT::Experimental::RRecordField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RRecordField::DestroyValue(void *objPtr, bool dtorOnly) const { for (unsigned i = 0; i < fSubFields.size(); ++i) { - auto memberValue = fSubFields[i]->CaptureValue(value.Get() + fOffsets[i]); - fSubFields[i]->DestroyValue(memberValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[i], static_cast(objPtr) + fOffsets[i], true /* dtorOnly */); } - - if (!dtorOnly) - free(value.GetRawPtr()); -} - -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RRecordField::CaptureValue(void *where) -{ - return Detail::RFieldValue(true /* captureFlag */, this, where); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } - -std::vector -ROOT::Experimental::RRecordField::SplitValue(const Detail::RFieldValue &value) const +std::vector +ROOT::Experimental::RRecordField::SplitValue(const RValue &value) const { - std::vector result; + std::vector result; for (unsigned i = 0; i < fSubFields.size(); ++i) { - result.emplace_back(fSubFields[i]->CaptureValue(value.Get() + fOffsets[i])); + result.emplace_back(fSubFields[i]->BindValue(value.Get() + fOffsets[i])); } return result; } @@ -1297,114 +1808,112 @@ ROOT::Experimental::RVectorField::CloneImpl(std::string_view newName) const return std::make_unique(newName, std::move(newItemField)); } -std::size_t ROOT::Experimental::RVectorField::AppendImpl(const Detail::RFieldValue& value) { - auto typedValue = value.Get>(); +std::size_t ROOT::Experimental::RVectorField::AppendImpl(const void *from) +{ + auto typedValue = static_cast *>(from); R__ASSERT((typedValue->size() % fItemSize) == 0); std::size_t nbytes = 0; auto count = typedValue->size() / fItemSize; - for (unsigned i = 0; i < count; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(typedValue->data() + (i * fItemSize)); - nbytes += fSubFields[0]->Append(itemValue); + + if (fSubFields[0]->IsSimple() && count) { + GetPrincipalColumnOf(*fSubFields[0])->AppendV(typedValue->data(), count); + nbytes += count * GetPrincipalColumnOf(*fSubFields[0])->GetElement()->GetPackedSize(); + } else { + for (unsigned i = 0; i < count; ++i) { + nbytes += CallAppendOn(*fSubFields[0], typedValue->data() + (i * fItemSize)); + } } - Detail::RColumnElement elemIndex(&fNWritten); + fNWritten += count; - fColumns[0]->Append(elemIndex); - return nbytes + sizeof(elemIndex); + fColumns[0]->Append(&fNWritten); + return nbytes + fColumns[0]->GetElement()->GetPackedSize(); } -void ROOT::Experimental::RVectorField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RVectorField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { - auto typedValue = value->Get>(); + auto typedValue = static_cast *>(to); ClusterSize_t nItems; RClusterIndex collectionStart; fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &nItems); - if (fSubFields[0]->GetTraits() & kTraitTrivialType) { + if (fSubFields[0]->IsSimple()) { typedValue->resize(nItems * fItemSize); - } else { - // See "semantics of reading non-trivial objects" in RNTuple's architecture.md - const auto oldNItems = typedValue->size() / fItemSize; - const bool canRealloc = oldNItems < nItems; - bool allDeallocated = false; - if (!(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible)) { - allDeallocated = canRealloc; - for (std::size_t i = allDeallocated ? 0 : nItems; i < oldNItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(typedValue->data() + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); - } + if (nItems) + GetPrincipalColumnOf(*fSubFields[0])->ReadV(collectionStart, nItems, typedValue->data()); + return; + } + + // See "semantics of reading non-trivial objects" in RNTuple's architecture.md + const auto oldNItems = typedValue->size() / fItemSize; + const bool canRealloc = oldNItems < nItems; + bool allDeallocated = false; + if (!(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible)) { + allDeallocated = canRealloc; + for (std::size_t i = allDeallocated ? 0 : nItems; i < oldNItems; ++i) { + CallDestroyValueOn(*fSubFields[0], typedValue->data() + (i * fItemSize), true /* dtorOnly */); } - typedValue->resize(nItems * fItemSize); - if (!(fSubFields[0]->GetTraits() & kTraitTriviallyConstructible)) { - for (std::size_t i = allDeallocated ? 0 : oldNItems; i < nItems; ++i) { - fSubFields[0]->GenerateValue(typedValue->data() + (i * fItemSize)); - } + } + typedValue->resize(nItems * fItemSize); + if (!(fSubFields[0]->GetTraits() & kTraitTriviallyConstructible)) { + for (std::size_t i = allDeallocated ? 0 : oldNItems; i < nItems; ++i) { + CallGenerateValueOn(*fSubFields[0], typedValue->data() + (i * fItemSize)); } } for (std::size_t i = 0; i < nItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(typedValue->data() + (i * fItemSize)); - fSubFields[0]->Read(collectionStart + i, &itemValue); + CallReadOn(*fSubFields[0], collectionStart + i, typedValue->data() + (i * fItemSize)); } } -void ROOT::Experimental::RVectorField::GenerateColumnsImpl() +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RVectorField::GetColumnRepresentations() const { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelIndex, 0))); + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; } -void ROOT::Experimental::RVectorField::GenerateColumnsImpl(const RNTupleDescriptor &desc) +void ROOT::Experimental::RVectorField::GenerateColumnsImpl() { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RVectorField::GenerateValue(void* where) +void ROOT::Experimental::RVectorField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - return Detail::RFieldValue(this, reinterpret_cast*>(where)); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } -void ROOT::Experimental::RVectorField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RVectorField::DestroyValue(void *objPtr, bool dtorOnly) const { - auto vec = static_cast*>(value.GetRawPtr()); - R__ASSERT((vec->size() % fItemSize) == 0); + auto vecPtr = static_cast *>(objPtr); + R__ASSERT((vecPtr->size() % fItemSize) == 0); if (!(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible)) { - auto nItems = vec->size() / fItemSize; + auto nItems = vecPtr->size() / fItemSize; for (unsigned i = 0; i < nItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(vec->data() + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[0], vecPtr->data() + (i * fItemSize), true /* dtorOnly */); } } - vec->~vector(); + std::destroy_at(vecPtr); if (!dtorOnly) - free(vec); -} - -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RVectorField::CaptureValue(void* where) -{ - return Detail::RFieldValue(true /* captureFlag */, this, where); + free(vecPtr); } -std::vector -ROOT::Experimental::RVectorField::SplitValue(const Detail::RFieldValue &value) const +std::vector +ROOT::Experimental::RVectorField::SplitValue(const RValue &value) const { - auto vec = static_cast*>(value.GetRawPtr()); + auto vec = value.Get>(); R__ASSERT((vec->size() % fItemSize) == 0); auto nItems = vec->size() / fItemSize; - std::vector result; + std::vector result; for (unsigned i = 0; i < nItems; ++i) { - result.emplace_back(fSubFields[0]->CaptureValue(vec->data() + (i * fItemSize))); + result.emplace_back(fSubFields[0]->BindValue(vec->data() + (i * fItemSize))); } return result; } -void ROOT::Experimental::RVectorField::CommitCluster() -{ - fNWritten = 0; -} - void ROOT::Experimental::RVectorField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { visitor.VisitVectorField(*this); @@ -1429,29 +1938,32 @@ ROOT::Experimental::RRVecField::CloneImpl(std::string_view newName) const return std::make_unique(newName, std::move(newItemField)); } -std::size_t ROOT::Experimental::RRVecField::AppendImpl(const Detail::RFieldValue &value) +std::size_t ROOT::Experimental::RRVecField::AppendImpl(const void *from) { - auto [beginPtr, sizePtr, _] = GetRVecDataMembers(value.GetRawPtr()); + auto [beginPtr, sizePtr, _] = GetRVecDataMembers(from); std::size_t nbytes = 0; - char *begin = reinterpret_cast(*beginPtr); // for pointer arithmetics - for (std::int32_t i = 0; i < *sizePtr; ++i) { - auto elementValue = fSubFields[0]->CaptureValue(begin + i * fItemSize); - nbytes += fSubFields[0]->Append(elementValue); + if (fSubFields[0]->IsSimple() && *sizePtr) { + GetPrincipalColumnOf(*fSubFields[0])->AppendV(*beginPtr, *sizePtr); + nbytes += *sizePtr * GetPrincipalColumnOf(*fSubFields[0])->GetElement()->GetPackedSize(); + } else { + auto begin = reinterpret_cast(*beginPtr); // for pointer arithmetics + for (std::int32_t i = 0; i < *sizePtr; ++i) { + nbytes += CallAppendOn(*fSubFields[0], begin + i * fItemSize); + } } - Detail::RColumnElement elemIndex(&fNWritten); fNWritten += *sizePtr; - fColumns[0]->Append(elemIndex); - return nbytes + sizeof(elemIndex); + fColumns[0]->Append(&fNWritten); + return nbytes + fColumns[0]->GetElement()->GetPackedSize(); } -void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { // TODO as a performance optimization, we could assign values to elements of the inline buffer: // if size < inline buffer size: we save one allocation here and usage of the RVec skips a pointer indirection - auto [beginPtr, sizePtr, capacityPtr] = GetRVecDataMembers(value->GetRawPtr()); + auto [beginPtr, sizePtr, capacityPtr] = GetRVecDataMembers(to); // Read collection info for this entry ClusterSize_t nItems; @@ -1462,14 +1974,14 @@ void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, De // See "semantics of reading non-trivial objects" in RNTuple's architecture.md for details // on the element construction/destrution. + const bool owns = (*capacityPtr != -1); const bool needsConstruct = !(fSubFields[0]->GetTraits() & kTraitTriviallyConstructible); - const bool needsDestruct = !(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible); + const bool needsDestruct = owns && !(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible); // Destroy excess elements, if any if (needsDestruct) { for (std::size_t i = nItems; i < oldSize; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(begin + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[0], begin + (i * fItemSize), true /* dtorOnly */); } } @@ -1479,13 +1991,15 @@ void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, De // allocates memory we need to release it here to avoid memleaks (e.g. if this is an RVec>) if (needsDestruct) { for (std::size_t i = 0u; i < oldSize; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(begin + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[0], begin + (i * fItemSize), true /* dtorOnly */); } } // TODO Increment capacity by a factor rather than just enough to fit the elements. - free(*beginPtr); + if (owns) { + // *beginPtr points to the array of item values (allocated in an earlier call by the following malloc()) + free(*beginPtr); + } // We trust that malloc returns a buffer with large enough alignment. // This might not be the case if T in RVec is over-aligned. *beginPtr = malloc(nItems * fItemSize); @@ -1496,7 +2010,7 @@ void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, De // Placement new for elements that were already there before the resize if (needsConstruct) { for (std::size_t i = 0u; i < oldSize; ++i) - fSubFields[0]->GenerateValue(begin + (i * fItemSize)); + CallGenerateValueOn(*fSubFields[0], begin + (i * fItemSize)); } } *sizePtr = nItems; @@ -1504,49 +2018,120 @@ void ROOT::Experimental::RRVecField::ReadGlobalImpl(NTupleSize_t globalIndex, De // Placement new for new elements, if any if (needsConstruct) { for (std::size_t i = oldSize; i < nItems; ++i) - fSubFields[0]->GenerateValue(begin + (i * fItemSize)); + CallGenerateValueOn(*fSubFields[0], begin + (i * fItemSize)); + } + + if (fSubFields[0]->IsSimple() && nItems) { + GetPrincipalColumnOf(*fSubFields[0])->ReadV(collectionStart, nItems, begin); + return; } // Read the new values into the collection elements for (std::size_t i = 0; i < nItems; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(begin + (i * fItemSize)); - fSubFields[0]->Read(collectionStart + i, &itemValue); + CallReadOn(*fSubFields[0], collectionStart + i, begin + (i * fItemSize)); + } +} + +std::size_t ROOT::Experimental::RRVecField::ReadBulkImpl(const RBulkSpec &bulkSpec) +{ + if (!fSubFields[0]->IsSimple()) + return RFieldBase::ReadBulkImpl(bulkSpec); + + if (bulkSpec.fAuxData->empty()) { + /// Initialize auxiliary memory: the first sizeof(size_t) bytes store the value size of the item field. + /// The following bytes store the item values, consecutively. + bulkSpec.fAuxData->resize(sizeof(std::size_t)); + *reinterpret_cast(bulkSpec.fAuxData->data()) = fSubFields[0]->GetValueSize(); + } + const auto itemValueSize = *reinterpret_cast(bulkSpec.fAuxData->data()); + unsigned char *itemValueArray = bulkSpec.fAuxData->data() + sizeof(std::size_t); + auto [beginPtr, sizePtr, _] = GetRVecDataMembers(bulkSpec.fValues); + + // Get size of the first RVec of the bulk + RClusterIndex firstItemIndex; + RClusterIndex collectionStart; + ClusterSize_t collectionSize; + this->GetCollectionInfo(bulkSpec.fFirstIndex, &firstItemIndex, &collectionSize); + *beginPtr = itemValueArray; + *sizePtr = collectionSize; + + // Set the size of the remaining RVecs of the bulk, going page by page through the RNTuple offset column. + // We optimistically assume that bulkSpec.fAuxData is already large enough to hold all the item values in the + // given range. If not, we'll fix up the pointers afterwards. + auto lastOffset = firstItemIndex.GetIndex() + collectionSize; + ClusterSize_t::ValueType nRemainingValues = bulkSpec.fCount - 1; + std::size_t nValues = 1; + std::size_t nItems = collectionSize; + while (nRemainingValues > 0) { + NTupleSize_t nElementsUntilPageEnd; + const auto offsets = fPrincipalColumn->MapV(bulkSpec.fFirstIndex + nValues, nElementsUntilPageEnd); + const std::size_t nBatch = std::min(nRemainingValues, nElementsUntilPageEnd); + for (std::size_t i = 0; i < nBatch; ++i) { + const auto size = offsets[i] - lastOffset; + std::tie(beginPtr, sizePtr, _) = GetRVecDataMembers( + reinterpret_cast(bulkSpec.fValues) + (nValues + i) * fValueSize); + *beginPtr = itemValueArray + nItems * itemValueSize; + *sizePtr = size; + + nItems += size; + lastOffset = offsets[i]; + } + nRemainingValues -= nBatch; + nValues += nBatch; + } + + bulkSpec.fAuxData->resize(sizeof(std::size_t) + nItems * itemValueSize); + // If the vector got reallocated, we need to fix-up the RVecs begin pointers. + const auto delta = itemValueArray - (bulkSpec.fAuxData->data() + sizeof(std::size_t)); + if (delta != 0) { + auto beginPtrAsUChar = reinterpret_cast(bulkSpec.fValues); + for (std::size_t i = 0; i < bulkSpec.fCount; ++i) { + *reinterpret_cast(beginPtrAsUChar) -= delta; + beginPtrAsUChar += fValueSize; + } } + + GetPrincipalColumnOf(*fSubFields[0])->ReadV(firstItemIndex, nItems, itemValueArray - delta); + return RBulkSpec::kAllSet; +} + +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RRVecField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; } void ROOT::Experimental::RRVecField::GenerateColumnsImpl() { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back( - std::unique_ptr(Detail::RColumn::Create(modelIndex, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RRVecField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RRVecField::GenerateValue(void *where) +void ROOT::Experimental::RRVecField::GenerateValue(void *where) const { // initialize data members fBegin, fSize, fCapacity // currently the inline buffer is left uninitialized void **beginPtr = new (where)(void *)(nullptr); std::int32_t *sizePtr = new (reinterpret_cast(beginPtr + 1)) std::int32_t(0); - new (sizePtr + 1) std::int32_t(0); - - return Detail::RFieldValue(/*captureTag*/ true, this, where); + new (sizePtr + 1) std::int32_t(-1); } -void ROOT::Experimental::RRVecField::DestroyValue(const Detail::RFieldValue &value, bool dtorOnly) +void ROOT::Experimental::RRVecField::DestroyValue(void *objPtr, bool dtorOnly) const { - auto [beginPtr, sizePtr, capacityPtr] = GetRVecDataMembers(value.GetRawPtr()); + auto [beginPtr, sizePtr, capacityPtr] = GetRVecDataMembers(objPtr); char *begin = reinterpret_cast(*beginPtr); // for pointer arithmetics if (!(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible)) { for (std::int32_t i = 0; i < *sizePtr; ++i) { - auto elementValue = fSubFields[0]->CaptureValue(begin + i * fItemSize); - fSubFields[0]->DestroyValue(elementValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[0], begin + i * fItemSize, true /* dtorOnly */); } } @@ -1567,21 +2152,15 @@ void ROOT::Experimental::RRVecField::DestroyValue(const Detail::RFieldValue &val free(beginPtr); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RRVecField::CaptureValue(void *where) -{ - return Detail::RFieldValue(true /* captureFlag */, this, where); -} - -std::vector -ROOT::Experimental::RRVecField::SplitValue(const Detail::RFieldValue &value) const +std::vector +ROOT::Experimental::RRVecField::SplitValue(const RValue &value) const { auto [beginPtr, sizePtr, _] = GetRVecDataMembers(value.GetRawPtr()); - std::vector result; + std::vector result; char *begin = reinterpret_cast(*beginPtr); // for pointer arithmetics for (std::int32_t i = 0; i < *sizePtr; ++i) { - auto elementValue = fSubFields[0]->CaptureValue(begin + i * fItemSize); - result.emplace_back(std::move(elementValue)); + result.emplace_back(fSubFields[0]->BindValue(begin + i * fItemSize)); } return result; } @@ -1646,11 +2225,6 @@ size_t ROOT::Experimental::RRVecField::GetAlignment() const return std::max({alignof(void *), alignof(std::int32_t), fSubFields[0]->GetAlignment()}); } -void ROOT::Experimental::RRVecField::CommitCluster() -{ - fNWritten = 0; -} - void ROOT::Experimental::RRVecField::AcceptVisitor(Detail::RFieldVisitor &visitor) const { visitor.VisitRVecField(*this); @@ -1665,23 +2239,22 @@ ROOT::Experimental::RField>::RField(std::string_view name) Attach(std::make_unique>("_0")); } -std::size_t ROOT::Experimental::RField>::AppendImpl(const Detail::RFieldValue& value) { - auto typedValue = value.Get>(); +std::size_t ROOT::Experimental::RField>::AppendImpl(const void *from) +{ + auto typedValue = static_cast *>(from); auto count = typedValue->size(); for (unsigned i = 0; i < count; ++i) { bool bval = (*typedValue)[i]; - auto itemValue = fSubFields[0]->CaptureValue(&bval); - fSubFields[0]->Append(itemValue); + CallAppendOn(*fSubFields[0], &bval); } - Detail::RColumnElement elemIndex(&fNWritten); fNWritten += count; - fColumns[0]->Append(elemIndex); - return count + sizeof(elemIndex); + fColumns[0]->Append(&fNWritten); + return count + fColumns[0]->GetElement()->GetPackedSize(); } -void ROOT::Experimental::RField>::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue* value) +void ROOT::Experimental::RField>::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { - auto typedValue = value->Get>(); + auto typedValue = static_cast *>(to); ClusterSize_t nItems; RClusterIndex collectionStart; @@ -1690,50 +2263,53 @@ void ROOT::Experimental::RField>::ReadGlobalImpl(NTupleSize_t typedValue->resize(nItems); for (unsigned i = 0; i < nItems; ++i) { bool bval; - auto itemValue = fSubFields[0]->GenerateValue(&bval); - fSubFields[0]->Read(collectionStart + i, &itemValue); + CallReadOn(*fSubFields[0], collectionStart + i, &bval); (*typedValue)[i] = bval; } } +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RField>::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; +} + void ROOT::Experimental::RField>::GenerateColumnsImpl() { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelIndex, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RField>::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } -std::vector -ROOT::Experimental::RField>::SplitValue(const Detail::RFieldValue& value) const +std::vector +ROOT::Experimental::RField>::SplitValue(const RValue &value) const { const static bool trueValue = true; const static bool falseValue = false; auto typedValue = value.Get>(); auto count = typedValue->size(); - std::vector result; + std::vector result; for (unsigned i = 0; i < count; ++i) { if ((*typedValue)[i]) - result.emplace_back(fSubFields[0]->CaptureValue(const_cast(&trueValue))); + result.emplace_back(fSubFields[0]->BindValue(const_cast(&trueValue))); else - result.emplace_back(fSubFields[0]->CaptureValue(const_cast(&falseValue))); + result.emplace_back(fSubFields[0]->BindValue(const_cast(&falseValue))); } return result; } - -void ROOT::Experimental::RField>::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RField>::DestroyValue(void *objPtr, bool dtorOnly) const { - auto vec = static_cast*>(value.GetRawPtr()); - vec->~vector(); - if (!dtorOnly) - free(vec); + std::destroy_at(static_cast *>(objPtr)); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } void ROOT::Experimental::RField>::AcceptVisitor(Detail::RFieldVisitor &visitor) const @@ -1763,81 +2339,62 @@ ROOT::Experimental::RArrayField::CloneImpl(std::string_view newName) const return std::make_unique(newName, std::move(newItemField), fArrayLength); } -std::size_t ROOT::Experimental::RArrayField::AppendImpl(const Detail::RFieldValue& value) { +std::size_t ROOT::Experimental::RArrayField::AppendImpl(const void *from) +{ std::size_t nbytes = 0; - auto arrayPtr = value.Get(); + auto arrayPtr = static_cast(from); for (unsigned i = 0; i < fArrayLength; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(arrayPtr + (i * fItemSize)); - nbytes += fSubFields[0]->Append(itemValue); + nbytes += CallAppendOn(*fSubFields[0], arrayPtr + (i * fItemSize)); } return nbytes; } -void ROOT::Experimental::RArrayField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RArrayField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { - auto arrayPtr = value->Get(); + auto arrayPtr = static_cast(to); for (unsigned i = 0; i < fArrayLength; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(arrayPtr + (i * fItemSize)); - fSubFields[0]->Read(globalIndex * fArrayLength + i, &itemValue); + CallReadOn(*fSubFields[0], globalIndex * fArrayLength + i, arrayPtr + (i * fItemSize)); } } -void ROOT::Experimental::RArrayField::ReadInClusterImpl(const RClusterIndex &clusterIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RArrayField::ReadInClusterImpl(const RClusterIndex &clusterIndex, void *to) { - auto arrayPtr = value->Get(); + auto arrayPtr = static_cast(to); for (unsigned i = 0; i < fArrayLength; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(arrayPtr + (i * fItemSize)); - fSubFields[0]->Read(RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() * fArrayLength + i), - &itemValue); + CallReadOn(*fSubFields[0], RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() * fArrayLength + i), + arrayPtr + (i * fItemSize)); } } -void ROOT::Experimental::RArrayField::GenerateColumnsImpl() -{ -} - -void ROOT::Experimental::RArrayField::GenerateColumnsImpl(const RNTupleDescriptor &) -{ -} - -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RArrayField::GenerateValue(void *where) +void ROOT::Experimental::RArrayField::GenerateValue(void *where) const { if (fSubFields[0]->GetTraits() & kTraitTriviallyConstructible) - return Detail::RFieldValue(true /* captureFlag */, this, where); + return; auto arrayPtr = reinterpret_cast(where); for (unsigned i = 0; i < fArrayLength; ++i) { - fSubFields[0]->GenerateValue(arrayPtr + (i * fItemSize)); + CallGenerateValueOn(*fSubFields[0], arrayPtr + (i * fItemSize)); } - return Detail::RFieldValue(true /* captureFlag */, this, where); } -void ROOT::Experimental::RArrayField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RArrayField::DestroyValue(void *objPtr, bool dtorOnly) const { - auto arrayPtr = value.Get(); + auto arrayPtr = static_cast(objPtr); if (!(fSubFields[0]->GetTraits() & kTraitTriviallyDestructible)) { for (unsigned i = 0; i < fArrayLength; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(arrayPtr + (i * fItemSize)); - fSubFields[0]->DestroyValue(itemValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[0], arrayPtr + (i * fItemSize), true /* dtorOnly */); } } - if (!dtorOnly) - free(arrayPtr); -} - -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RArrayField::CaptureValue(void *where) -{ - return Detail::RFieldValue(true /* captureFlag */, this, where); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } -std::vector -ROOT::Experimental::RArrayField::SplitValue(const Detail::RFieldValue &value) const +std::vector +ROOT::Experimental::RArrayField::SplitValue(const RValue &value) const { auto arrayPtr = value.Get(); - std::vector result; + std::vector result; for (unsigned i = 0; i < fArrayLength; ++i) { - auto itemValue = fSubFields[0]->CaptureValue(arrayPtr + (i * fItemSize)); - result.emplace_back(itemValue); + result.emplace_back(fSubFields[0]->BindValue(arrayPtr + (i * fItemSize))); } return result; } @@ -1849,6 +2406,65 @@ void ROOT::Experimental::RArrayField::AcceptVisitor(Detail::RFieldVisitor &visit //------------------------------------------------------------------------------ +ROOT::Experimental::RBitsetField::RBitsetField(std::string_view fieldName, std::size_t N) + : ROOT::Experimental::Detail::RFieldBase(fieldName, "std::bitset<" + std::to_string(N) + ">", + ENTupleStructure::kLeaf, false /* isSimple */, N), + fN(N) +{ + fTraits |= kTraitTriviallyDestructible; +} + +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RBitsetField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kBit}}, {}); + return representations; +} + +void ROOT::Experimental::RBitsetField::GenerateColumnsImpl() +{ + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); +} + +void ROOT::Experimental::RBitsetField::GenerateColumnsImpl(const RNTupleDescriptor &desc) +{ + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); +} + +std::size_t ROOT::Experimental::RBitsetField::AppendImpl(const void *from) +{ + const auto *asULongArray = static_cast(from); + bool elementValue; + std::size_t i = 0; + for (std::size_t word = 0; word < (fN + kBitsPerWord - 1) / kBitsPerWord; ++word) { + for (std::size_t mask = 0; (mask < kBitsPerWord) && (i < fN); ++mask, ++i) { + elementValue = (asULongArray[word] & (static_cast(1) << mask)) != 0; + fColumns[0]->Append(&elementValue); + } + } + return fN; +} + +void ROOT::Experimental::RBitsetField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) +{ + auto *asULongArray = static_cast(to); + bool elementValue; + for (std::size_t i = 0; i < fN; ++i) { + fColumns[0]->Read(globalIndex * fN + i, &elementValue); + Word_t mask = static_cast(1) << (i % kBitsPerWord); + Word_t bit = static_cast(elementValue) << (i % kBitsPerWord); + asULongArray[i / kBitsPerWord] = (asULongArray[i / kBitsPerWord] & ~mask) | bit; + } +} + +void ROOT::Experimental::RBitsetField::AcceptVisitor(Detail::RFieldVisitor &visitor) const +{ + visitor.VisitBitsetField(*this); +} + +//------------------------------------------------------------------------------ + std::string ROOT::Experimental::RVariantField::GetTypeList(const std::vector &itemFields) { std::string result; @@ -1892,9 +2508,9 @@ ROOT::Experimental::RVariantField::CloneImpl(std::string_view newName) const return std::make_unique(newName, itemFields); } -std::uint32_t ROOT::Experimental::RVariantField::GetTag(void *variantPtr) const +std::uint32_t ROOT::Experimental::RVariantField::GetTag(const void *variantPtr) const { - auto index = *(reinterpret_cast(variantPtr) + fTagOffset); + auto index = *(reinterpret_cast(variantPtr) + fTagOffset); return (index < 0) ? 0 : index + 1; } @@ -1904,70 +2520,68 @@ void ROOT::Experimental::RVariantField::SetTag(void *variantPtr, std::uint32_t t *index = static_cast(tag - 1); } -std::size_t ROOT::Experimental::RVariantField::AppendImpl(const Detail::RFieldValue& value) +std::size_t ROOT::Experimental::RVariantField::AppendImpl(const void *from) { - auto tag = GetTag(value.GetRawPtr()); + auto tag = GetTag(from); std::size_t nbytes = 0; auto index = 0; if (tag > 0) { - auto itemValue = fSubFields[tag - 1]->CaptureValue(value.GetRawPtr()); - nbytes += fSubFields[tag - 1]->Append(itemValue); + nbytes += CallAppendOn(*fSubFields[tag - 1], from); index = fNWritten[tag - 1]++; } RColumnSwitch varSwitch(ClusterSize_t(index), tag); - Detail::RColumnElement elemSwitch(&varSwitch); - fColumns[0]->Append(elemSwitch); + fColumns[0]->Append(&varSwitch); return nbytes + sizeof(RColumnSwitch); } -void ROOT::Experimental::RVariantField::ReadGlobalImpl(NTupleSize_t globalIndex, Detail::RFieldValue *value) +void ROOT::Experimental::RVariantField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) { RClusterIndex variantIndex; std::uint32_t tag; fPrincipalColumn->GetSwitchInfo(globalIndex, &variantIndex, &tag); - R__ASSERT(tag > 0); // TODO(jblomer): deal with invalid variants - auto itemValue = fSubFields[tag - 1]->GenerateValue(value->GetRawPtr()); - fSubFields[tag - 1]->Read(variantIndex, &itemValue); - SetTag(value->GetRawPtr(), tag); + // If `tag` equals 0, the variant is in the invalid state, i.e, it does not hold any of the valid alternatives in + // the type list. This happens, e.g., if the field was late added; in this case, keep the invalid tag, which makes + // any `std::holds_alternative` check fail later. + if (R__likely(tag > 0)) { + CallGenerateValueOn(*fSubFields[tag - 1], to); + CallReadOn(*fSubFields[tag - 1], variantIndex, to); + } + SetTag(to, tag); +} + +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RVariantField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations({{EColumnType::kSwitch}}, {{}}); + return representations; } void ROOT::Experimental::RVariantField::GenerateColumnsImpl() { - RColumnModel modelSwitch(EColumnType::kSwitch, false); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelSwitch, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RVariantField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kSwitch}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RVariantField::GenerateValue(void *where) +void ROOT::Experimental::RVariantField::GenerateValue(void *where) const { memset(where, 0, GetValueSize()); - fSubFields[0]->GenerateValue(where); + CallGenerateValueOn(*fSubFields[0], where); SetTag(where, 1); - return Detail::RFieldValue(this, reinterpret_cast(where)); } -void ROOT::Experimental::RVariantField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RVariantField::DestroyValue(void *objPtr, bool dtorOnly) const { - auto variantPtr = value.GetRawPtr(); - auto tag = GetTag(variantPtr); + auto tag = GetTag(objPtr); if (tag > 0) { - auto itemValue = fSubFields[tag - 1]->CaptureValue(variantPtr); - fSubFields[tag - 1]->DestroyValue(itemValue, true /* dtorOnly */); + CallDestroyValueOn(*fSubFields[tag - 1], objPtr, true /* dtorOnly */); } - if (!dtorOnly) - free(variantPtr); -} - -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RVariantField::CaptureValue(void *where) -{ - return Detail::RFieldValue(true /* captureFlag */, this, where); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } size_t ROOT::Experimental::RVariantField::GetValueSize() const @@ -1975,13 +2589,192 @@ size_t ROOT::Experimental::RVariantField::GetValueSize() const return fMaxItemSize + fMaxAlignment; // TODO: fix for more than 255 items } -void ROOT::Experimental::RVariantField::CommitCluster() +void ROOT::Experimental::RVariantField::CommitClusterImpl() { std::fill(fNWritten.begin(), fNWritten.end(), 0); } //------------------------------------------------------------------------------ +ROOT::Experimental::RSetField::RSetField(std::string_view fieldName, std::string_view typeName, + std::unique_ptr itemField) + : ROOT::Experimental::RProxiedCollectionField(fieldName, typeName, std::move(itemField)) +{ +} + +std::unique_ptr +ROOT::Experimental::RSetField::CloneImpl(std::string_view newName) const +{ + auto newItemField = fSubFields[0]->Clone(fSubFields[0]->GetName()); + return std::unique_ptr(new RSetField(newName, GetType(), std::move(newItemField))); +} + +//------------------------------------------------------------------------------ + +ROOT::Experimental::RNullableField::RNullableField(std::string_view fieldName, std::string_view typeName, + std::unique_ptr itemField) + : ROOT::Experimental::Detail::RFieldBase(fieldName, typeName, ENTupleStructure::kCollection, false /* isSimple */) +{ + Attach(std::move(itemField)); +} + +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RNullableField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}, + {EColumnType::kBit}}, {}); + return representations; +} + +void ROOT::Experimental::RNullableField::GenerateColumnsImpl() +{ + if (HasDefaultColumnRepresentative()) { + if (fSubFields[0]->GetValueSize() < 4) { + SetColumnRepresentative({EColumnType::kBit}); + } + } + if (IsDense()) { + fDefaultItemValue = std::make_unique(fSubFields[0]->GenerateValue()); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(EColumnType::kBit), 0)); + } else { + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); + } +} + +void ROOT::Experimental::RNullableField::GenerateColumnsImpl(const RNTupleDescriptor &desc) +{ + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + if (onDiskTypes[0] == EColumnType::kBit) { + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(EColumnType::kBit), 0)); + } else { + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); + } +} + +std::size_t ROOT::Experimental::RNullableField::AppendNull() +{ + if (IsDense()) { + bool mask = false; + fPrincipalColumn->Append(&mask); + return 1 + CallAppendOn(*fSubFields[0], fDefaultItemValue->GetRawPtr()); + } else { + fPrincipalColumn->Append(&fNWritten); + return sizeof(ClusterSize_t); + } +} + +std::size_t ROOT::Experimental::RNullableField::AppendValue(const void *from) +{ + auto nbytesItem = CallAppendOn(*fSubFields[0], from); + if (IsDense()) { + bool mask = true; + fPrincipalColumn->Append(&mask); + return 1 + nbytesItem; + } else { + fNWritten++; + fPrincipalColumn->Append(&fNWritten); + return sizeof(ClusterSize_t) + nbytesItem; + } +} + +ROOT::Experimental::RClusterIndex ROOT::Experimental::RNullableField::GetItemIndex(NTupleSize_t globalIndex) +{ + RClusterIndex nullIndex; + if (IsDense()) { + const bool isValidItem = *fPrincipalColumn->Map(globalIndex); + return isValidItem ? fPrincipalColumn->GetClusterIndex(globalIndex) : nullIndex; + } else { + RClusterIndex collectionStart; + ClusterSize_t collectionSize; + fPrincipalColumn->GetCollectionInfo(globalIndex, &collectionStart, &collectionSize); + return (collectionSize == 0) ? nullIndex : collectionStart; + } +} + +void ROOT::Experimental::RNullableField::AcceptVisitor(Detail::RFieldVisitor &visitor) const +{ + visitor.VisitNullableField(*this); +} + +//------------------------------------------------------------------------------ + +ROOT::Experimental::RUniquePtrField::RUniquePtrField(std::string_view fieldName, std::string_view typeName, + std::unique_ptr itemField) + : RNullableField(fieldName, typeName, std::move(itemField)) +{ +} + +std::unique_ptr +ROOT::Experimental::RUniquePtrField::CloneImpl(std::string_view newName) const +{ + auto newItemField = fSubFields[0]->Clone(fSubFields[0]->GetName()); + return std::make_unique(newName, GetType(), std::move(newItemField)); +} + +std::size_t ROOT::Experimental::RUniquePtrField::AppendImpl(const void *from) +{ + auto typedValue = static_cast *>(from); + if (*typedValue) { + return AppendValue(typedValue->get()); + } else { + return AppendNull(); + } +} + +void ROOT::Experimental::RUniquePtrField::ReadGlobalImpl(NTupleSize_t globalIndex, void *to) +{ + auto ptr = static_cast *>(to); + bool isValidValue = static_cast(*ptr); + + auto itemIndex = GetItemIndex(globalIndex); + bool isValidItem = itemIndex.GetIndex() != kInvalidClusterIndex; + + void *valuePtr = nullptr; + if (isValidValue) + valuePtr = ptr->get(); + + if (isValidValue && !isValidItem) { + ptr->release(); + CallDestroyValueOn(*fSubFields[0], valuePtr, false /* dtorOnly */); + return; + } + + if (!isValidItem) // On-disk value missing; nothing else to do + return; + + if (!isValidValue) { + valuePtr = malloc(fSubFields[0]->GetValueSize()); + CallGenerateValueOn(*fSubFields[0], valuePtr); + ptr->reset(reinterpret_cast(valuePtr)); + } + + CallReadOn(*fSubFields[0], itemIndex, valuePtr); +} + +void ROOT::Experimental::RUniquePtrField::DestroyValue(void *objPtr, bool dtorOnly) const +{ + auto typedPtr = static_cast *>(objPtr); + if (*typedPtr) { + CallDestroyValueOn(*fSubFields[0], typedPtr->get(), false /* dtorOnly */); + typedPtr->release(); + } + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); +} + +std::vector +ROOT::Experimental::RUniquePtrField::SplitValue(const RValue &value) const +{ + std::vector result; + auto ptr = value.Get>(); + if (*ptr) { + result.emplace_back(fSubFields[0]->BindValue(ptr->get())); + } + return result; +} + +//------------------------------------------------------------------------------ + std::string ROOT::Experimental::RPairField::RPairField::GetTypeList( const std::array, 2> &itemFields) { @@ -2021,16 +2814,15 @@ ROOT::Experimental::RPairField::CloneImpl(std::string_view newName) const return result; } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RPairField::GenerateValue(void *where) +void ROOT::Experimental::RPairField::GenerateValue(void *where) const { - return Detail::RFieldValue(true /* captureFlag */, this, fClass->New(where)); + fClass->New(where); } -void ROOT::Experimental::RPairField::DestroyValue(const Detail::RFieldValue& value, bool dtorOnly) +void ROOT::Experimental::RPairField::DestroyValue(void *objPtr, bool dtorOnly) const { - fClass->Destructor(value.GetRawPtr(), true /* dtorOnly */); - if (!dtorOnly) - free(value.GetRawPtr()); + fClass->Destructor(objPtr, true /* dtorOnly */); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } //------------------------------------------------------------------------------ @@ -2092,16 +2884,15 @@ ROOT::Experimental::RTupleField::CloneImpl(std::string_view newName) const return result; } -ROOT::Experimental::Detail::RFieldValue ROOT::Experimental::RTupleField::GenerateValue(void *where) +void ROOT::Experimental::RTupleField::GenerateValue(void *where) const { - return Detail::RFieldValue(true /* captureFlag */, this, fClass->New(where)); + fClass->New(where); } -void ROOT::Experimental::RTupleField::DestroyValue(const Detail::RFieldValue &value, bool dtorOnly) +void ROOT::Experimental::RTupleField::DestroyValue(void *objPtr, bool dtorOnly) const { - fClass->Destructor(value.GetRawPtr(), true /* dtorOnly */); - if (!dtorOnly) - free(value.GetRawPtr()); + fClass->Destructor(objPtr, true /* dtorOnly */); + Detail::RFieldBase::DestroyValue(objPtr, dtorOnly); } //------------------------------------------------------------------------------ @@ -2120,18 +2911,24 @@ ROOT::Experimental::RCollectionField::RCollectionField( SetDescription(collectionModel->GetDescription()); } +const ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations & +ROOT::Experimental::RCollectionField::GetColumnRepresentations() const +{ + static RColumnRepresentations representations( + {{EColumnType::kSplitIndex64}, {EColumnType::kIndex64}, {EColumnType::kSplitIndex32}, {EColumnType::kIndex32}}, + {}); + return representations; +} void ROOT::Experimental::RCollectionField::GenerateColumnsImpl() { - RColumnModel modelIndex(EColumnType::kIndex, true /* isSorted*/); - fColumns.emplace_back(std::unique_ptr( - Detail::RColumn::Create(modelIndex, 0))); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(GetColumnRepresentative()[0]), 0)); } void ROOT::Experimental::RCollectionField::GenerateColumnsImpl(const RNTupleDescriptor &desc) { - EnsureColumnType({EColumnType::kIndex}, 0, desc); - GenerateColumnsImpl(); + auto onDiskTypes = EnsureCompatibleColumnTypes(desc); + fColumns.emplace_back(Detail::RColumn::Create(RColumnModel(onDiskTypes[0]), 0)); } @@ -2146,7 +2943,7 @@ ROOT::Experimental::RCollectionField::CloneImpl(std::string_view newName) const return result; } - -void ROOT::Experimental::RCollectionField::CommitCluster() { +void ROOT::Experimental::RCollectionField::CommitClusterImpl() +{ *fCollectionNTuple->GetOffsetPtr() = 0; } diff --git a/tree/ntuple/v7/src/RFieldVisitor.cxx b/tree/ntuple/v7/src/RFieldVisitor.cxx index fb0046e6aab11..151109cd73f6d 100644 --- a/tree/ntuple/v7/src/RFieldVisitor.cxx +++ b/tree/ntuple/v7/src/RFieldVisitor.cxx @@ -14,7 +14,6 @@ *************************************************************************/ #include -#include #include #include #include @@ -135,7 +134,7 @@ void ROOT::Experimental::RPrintValueVisitor::PrintCollection(const Detail::RFiel RPrintOptions options; options.fPrintSingleLine = true; options.fPrintName = false; - RPrintValueVisitor elemVisitor(*iValue, fOutput, 0 /* level */, options); + RPrintValueVisitor elemVisitor(iValue->GetNonOwningCopy(), fOutput, 0 /* level */, options); iValue->GetField()->AcceptVisitor(elemVisitor); if (++iValue == elems.end()) @@ -254,6 +253,39 @@ void ROOT::Experimental::RPrintValueVisitor::VisitUInt64Field(const RField(); } +void ROOT::Experimental::RPrintValueVisitor::VisitCardinalityField(const RCardinalityField &field) +{ + PrintIndent(); + PrintName(field); + if (field.As32Bit()) { + fOutput << *fValue.Get(); + return; + } + if (field.As64Bit()) { + fOutput << *fValue.Get(); + return; + } + R__ASSERT(false && "unsupported cardinality size type"); +} + +void ROOT::Experimental::RPrintValueVisitor::VisitBitsetField(const RBitsetField &field) +{ + constexpr auto nBitsULong = sizeof(unsigned long) * 8; + const auto *asULongArray = fValue.Get(); + + PrintIndent(); + PrintName(field); + fOutput << "\""; + std::size_t i = 0; + std::string str; + for (std::size_t word = 0; word < (field.GetN() + nBitsULong - 1) / nBitsULong; ++word) { + for (std::size_t mask = 0; (mask < nBitsULong) && (i < field.GetN()); ++mask, ++i) { + bool isSet = (asULongArray[word] & (static_cast(1) << mask)) != 0; + str = std::to_string(isSet) + str; + } + } + fOutput << str << "\""; +} void ROOT::Experimental::RPrintValueVisitor::VisitArrayField(const RArrayField &field) { @@ -267,13 +299,13 @@ void ROOT::Experimental::RPrintValueVisitor::VisitClassField(const RClassField & PrintName(field); fOutput << "{"; auto elems = field.SplitValue(fValue); - for (auto iValue = elems.begin(); iValue != elems.end(); ) { + for (auto iValue = elems.begin(); iValue != elems.end();) { if (!fPrintOptions.fPrintSingleLine) fOutput << std::endl; RPrintOptions options; options.fPrintSingleLine = fPrintOptions.fPrintSingleLine; - RPrintValueVisitor visitor(*iValue, fOutput, fLevel + 1, options); + RPrintValueVisitor visitor(iValue->GetNonOwningCopy(), fOutput, fLevel + 1, options); iValue->GetField()->AcceptVisitor(visitor); if (++iValue == elems.end()) { @@ -303,7 +335,7 @@ void ROOT::Experimental::RPrintValueVisitor::VisitRecordField(const RRecordField RPrintOptions options; options.fPrintSingleLine = fPrintOptions.fPrintSingleLine; - RPrintValueVisitor visitor(*iValue, fOutput, fLevel + 1, options); + RPrintValueVisitor visitor(iValue->GetNonOwningCopy(), fOutput, fLevel + 1, options); iValue->GetField()->AcceptVisitor(visitor); if (++iValue == elems.end()) { @@ -320,7 +352,35 @@ void ROOT::Experimental::RPrintValueVisitor::VisitRecordField(const RRecordField fOutput << "}"; } -void ROOT::Experimental::RPrintValueVisitor::VisitCollectionClassField(const RCollectionClassField &field) +void ROOT::Experimental::RPrintValueVisitor::VisitNullableField(const RNullableField &field) +{ + PrintIndent(); + PrintName(field); + auto elems = field.SplitValue(fValue); + if (elems.empty()) { + fOutput << "null"; + } else { + RPrintOptions options; + options.fPrintSingleLine = true; + options.fPrintName = false; + RPrintValueVisitor visitor(elems[0].GetNonOwningCopy(), fOutput, fLevel, options); + elems[0].GetField()->AcceptVisitor(visitor); + } +} + +void ROOT::Experimental::RPrintValueVisitor::VisitEnumField(const REnumField &field) +{ + PrintIndent(); + PrintName(field); + auto intValue = field.SplitValue(fValue)[0].GetNonOwningCopy(); + RPrintOptions options; + options.fPrintSingleLine = true; + options.fPrintName = false; + RPrintValueVisitor visitor(intValue.GetNonOwningCopy(), fOutput, fLevel, options); + intValue.GetField()->AcceptVisitor(visitor); +} + +void ROOT::Experimental::RPrintValueVisitor::VisitProxiedCollectionField(const RProxiedCollectionField &field) { PrintCollection(field); } @@ -330,7 +390,6 @@ void ROOT::Experimental::RPrintValueVisitor::VisitVectorField(const RVectorField PrintCollection(field); } - void ROOT::Experimental::RPrintValueVisitor::VisitVectorBoolField(const RField> &field) { PrintCollection(field); diff --git a/tree/ntuple/v7/src/RNTuple.cxx b/tree/ntuple/v7/src/RNTuple.cxx index 27620ce6c44df..35e5a6c128ba9 100644 --- a/tree/ntuple/v7/src/RNTuple.cxx +++ b/tree/ntuple/v7/src/RNTuple.cxx @@ -40,7 +40,6 @@ #include #include - #ifdef R__USE_IMT ROOT::Experimental::RNTupleImtTaskScheduler::RNTupleImtTaskScheduler() { @@ -52,24 +51,21 @@ void ROOT::Experimental::RNTupleImtTaskScheduler::Reset() fTaskGroup = std::make_unique(); } - void ROOT::Experimental::RNTupleImtTaskScheduler::AddTask(const std::function &taskFunc) { fTaskGroup->Run(taskFunc); } - void ROOT::Experimental::RNTupleImtTaskScheduler::Wait() { fTaskGroup->Wait(); } #endif - //------------------------------------------------------------------------------ - -void ROOT::Experimental::RNTupleReader::ConnectModel(const RNTupleModel &model) { +void ROOT::Experimental::RNTupleReader::ConnectModel(const RNTupleModel &model) +{ // We must not use the descriptor guard to prevent recursive locking in field.ConnectPageSource model.GetFieldZero()->SetOnDiskId(fSource->GetSharedDescriptorGuard()->GetFieldZeroId()); for (auto &field : *model.GetFieldZero()) { @@ -95,12 +91,9 @@ void ROOT::Experimental::RNTupleReader::InitPageSource() fMetrics.ObserveMetrics(fSource->GetMetrics()); } -ROOT::Experimental::RNTupleReader::RNTupleReader( - std::unique_ptr model, - std::unique_ptr source) - : fSource(std::move(source)) - , fModel(std::move(model)) - , fMetrics("RNTupleReader") +ROOT::Experimental::RNTupleReader::RNTupleReader(std::unique_ptr model, + std::unique_ptr source) + : fSource(std::move(source)), fModel(std::move(model)), fMetrics("RNTupleReader") { if (!fSource) { throw RException(R__FAIL("null source")); @@ -108,15 +101,16 @@ ROOT::Experimental::RNTupleReader::RNTupleReader( if (!fModel) { throw RException(R__FAIL("null model")); } + if (!fModel->GetProjectedFields().IsEmpty()) { + throw RException(R__FAIL("model has projected fields, which is incompatible with providing a read model")); + } fModel->Freeze(); InitPageSource(); ConnectModel(*fModel); } ROOT::Experimental::RNTupleReader::RNTupleReader(std::unique_ptr source) - : fSource(std::move(source)) - , fModel(nullptr) - , fMetrics("RNTupleReader") + : fSource(std::move(source)), fModel(nullptr), fMetrics("RNTupleReader") { if (!fSource) { throw RException(R__FAIL("null source")); @@ -126,19 +120,16 @@ ROOT::Experimental::RNTupleReader::RNTupleReader(std::unique_ptr ROOT::Experimental::RNTupleReader::Open( - std::unique_ptr model, - std::string_view ntupleName, - std::string_view storage, - const RNTupleReadOptions &options) +std::unique_ptr +ROOT::Experimental::RNTupleReader::Open(std::unique_ptr model, std::string_view ntupleName, + std::string_view storage, const RNTupleReadOptions &options) { return std::make_unique(std::move(model), Detail::RPageSource::Create(ntupleName, storage, options)); } -std::unique_ptr ROOT::Experimental::RNTupleReader::Open( - std::string_view ntupleName, - std::string_view storage, - const RNTupleReadOptions &options) +std::unique_ptr +ROOT::Experimental::RNTupleReader::Open(std::string_view ntupleName, std::string_view storage, + const RNTupleReadOptions &options) { return std::make_unique(Detail::RPageSource::Create(ntupleName, storage, options)); } @@ -149,8 +140,8 @@ ROOT::Experimental::RNTupleReader::Open(ROOT::Experimental::RNTuple *ntuple, con return std::make_unique(ntuple->MakePageSource(options)); } -std::unique_ptr ROOT::Experimental::RNTupleReader::OpenFriends( - std::span ntuples) +std::unique_ptr +ROOT::Experimental::RNTupleReader::OpenFriends(std::span ntuples) { std::vector> sources; for (const auto &n : ntuples) { @@ -170,7 +161,8 @@ ROOT::Experimental::RNTupleModel *ROOT::Experimental::RNTupleReader::GetModel() void ROOT::Experimental::RNTupleReader::PrintInfo(const ENTupleInfo what, std::ostream &output) { - // TODO(lesimon): In a later version, these variables may be defined by the user or the ideal width may be read out from the terminal. + // TODO(lesimon): In a later version, these variables may be defined by the user or the ideal width may be read out + // from the terminal. char frameSymbol = '*'; int width = 80; /* @@ -189,15 +181,17 @@ void ROOT::Experimental::RNTupleReader::PrintInfo(const ENTupleInfo what, std::o fullModel = descriptorGuard->GenerateModel(); } - for (int i = 0; i < (width/2 + width%2 - 4); ++i) - output << frameSymbol; + for (int i = 0; i < (width / 2 + width % 2 - 4); ++i) + output << frameSymbol; output << " NTUPLE "; - for (int i = 0; i < (width/2 - 4); ++i) + for (int i = 0; i < (width / 2 - 4); ++i) output << frameSymbol; output << std::endl; // FitString defined in RFieldVisitor.cxx - output << frameSymbol << " N-Tuple : " << RNTupleFormatter::FitString(name, width-13) << frameSymbol << std::endl; // prints line with name of ntuple - output << frameSymbol << " Entries : " << RNTupleFormatter::FitString(std::to_string(GetNEntries()), width - 13) << frameSymbol << std::endl; // prints line with number of entries + output << frameSymbol << " N-Tuple : " << RNTupleFormatter::FitString(name, width - 13) << frameSymbol + << std::endl; // prints line with name of ntuple + output << frameSymbol << " Entries : " << RNTupleFormatter::FitString(std::to_string(GetNEntries()), width - 13) + << frameSymbol << std::endl; // prints line with number of entries // Traverses through all fields to gather information needed for printing. RPrepareVisitor prepVisitor; @@ -222,16 +216,13 @@ void ROOT::Experimental::RNTupleReader::PrintInfo(const ENTupleInfo what, std::o break; } case ENTupleInfo::kStorageDetails: fSource->GetSharedDescriptorGuard()->PrintInfo(output); break; - case ENTupleInfo::kMetrics: - fMetrics.Print(output); - break; + case ENTupleInfo::kMetrics: fMetrics.Print(output); break; default: // Unhandled case, internal error R__ASSERT(false); } } - ROOT::Experimental::RNTupleReader *ROOT::Experimental::RNTupleReader::GetDisplayReader() { if (!fDisplayReader) @@ -239,46 +230,26 @@ ROOT::Experimental::RNTupleReader *ROOT::Experimental::RNTupleReader::GetDisplay return fDisplayReader.get(); } - -void ROOT::Experimental::RNTupleReader::Show(NTupleSize_t index, const ENTupleShowFormat format, std::ostream &output) +void ROOT::Experimental::RNTupleReader::Show(NTupleSize_t index, std::ostream &output) { - RNTupleReader *reader = this; - REntry *entry = nullptr; - // Don't accidentally trigger loading of the entire model - if (fModel) - entry = fModel->GetDefaultEntry(); - - switch(format) { - case ENTupleShowFormat::kCompleteJSON: - reader = GetDisplayReader(); - entry = reader->GetModel()->GetDefaultEntry(); - // Fall through - case ENTupleShowFormat::kCurrentModelJSON: - if (!entry) { - output << "{}" << std::endl; - break; - } + auto reader = GetDisplayReader(); + auto entry = reader->GetModel()->GetDefaultEntry(); + + reader->LoadEntry(index); + output << "{"; + for (auto iValue = entry->begin(); iValue != entry->end();) { + output << std::endl; + RPrintValueVisitor visitor(iValue->GetNonOwningCopy(), output, 1 /* level */); + iValue->GetField()->AcceptVisitor(visitor); - reader->LoadEntry(index); - output << "{"; - for (auto iValue = entry->begin(); iValue != entry->end(); ) { + if (++iValue == entry->end()) { output << std::endl; - RPrintValueVisitor visitor(*iValue, output, 1 /* level */); - iValue->GetField()->AcceptVisitor(visitor); - - if (++iValue == entry->end()) { - output << std::endl; - break; - } else { - output << ","; - } + break; + } else { + output << ","; } - output << "}" << std::endl; - break; - default: - // Unhandled case, internal error - R__ASSERT(false); } + output << "}" << std::endl; } const ROOT::Experimental::RNTupleDescriptor *ROOT::Experimental::RNTupleReader::GetDescriptor() @@ -291,13 +262,9 @@ const ROOT::Experimental::RNTupleDescriptor *ROOT::Experimental::RNTupleReader:: //------------------------------------------------------------------------------ - -ROOT::Experimental::RNTupleWriter::RNTupleWriter( - std::unique_ptr model, - std::unique_ptr sink) - : fSink(std::move(sink)) - , fModel(std::move(model)) - , fMetrics("RNTupleWriter") +ROOT::Experimental::RNTupleWriter::RNTupleWriter(std::unique_ptr model, + std::unique_ptr sink) + : fSink(std::move(sink)), fModel(std::move(model)), fMetrics("RNTupleWriter") { if (!fModel) { throw RException(R__FAIL("null model")); @@ -324,24 +291,24 @@ ROOT::Experimental::RNTupleWriter::RNTupleWriter( ROOT::Experimental::RNTupleWriter::~RNTupleWriter() { - CommitCluster(true /* commitClusterGroup */); - fSink->CommitDataset(); + try { + CommitCluster(true /* commitClusterGroup */); + fSink->CommitDataset(); + } catch (const RException &err) { + R__LOG_ERROR(NTupleLog()) << "failure committing ntuple: " << err.GetError().GetReport(); + } } -std::unique_ptr ROOT::Experimental::RNTupleWriter::Recreate( - std::unique_ptr model, - std::string_view ntupleName, - std::string_view storage, - const RNTupleWriteOptions &options) +std::unique_ptr +ROOT::Experimental::RNTupleWriter::Recreate(std::unique_ptr model, std::string_view ntupleName, + std::string_view storage, const RNTupleWriteOptions &options) { return std::make_unique(std::move(model), Detail::RPageSink::Create(ntupleName, storage, options)); } -std::unique_ptr ROOT::Experimental::RNTupleWriter::Append( - std::unique_ptr model, - std::string_view ntupleName, - TFile &file, - const RNTupleWriteOptions &options) +std::unique_ptr +ROOT::Experimental::RNTupleWriter::Append(std::unique_ptr model, std::string_view ntupleName, TFile &file, + const RNTupleWriteOptions &options) { auto sink = std::make_unique(ntupleName, file, options); if (options.GetUseBufferedWrite()) { @@ -366,16 +333,20 @@ void ROOT::Experimental::RNTupleWriter::CommitCluster(bool commitClusterGroup) CommitClusterGroup(); return; } - for (auto& field : *fModel->GetFieldZero()) { - field.Flush(); + if (fSink->GetWriteOptions().GetHasSmallClusters() && + (fUnzippedClusterSize > RNTupleWriteOptions::kMaxSmallClusterSize)) + { + throw RException(R__FAIL("invalid attempt to write a cluster > 512MiB with 'small clusters' option enabled")); + } + for (auto &field : *fModel->GetFieldZero()) { field.CommitCluster(); } fNBytesCommitted += fSink->CommitCluster(fNEntries); fNBytesFilled += fUnzippedClusterSize; // Cap the compression factor at 1000 to prevent overflow of fUnzippedClusterSizeEst - const float compressionFactor = std::min(1000.f, - static_cast(fNBytesFilled) / static_cast(fNBytesCommitted)); + const float compressionFactor = + std::min(1000.f, static_cast(fNBytesFilled) / static_cast(fNBytesCommitted)); fUnzippedClusterSizeEst = compressionFactor * static_cast(fSink->GetWriteOptions().GetApproxZippedClusterSize()); @@ -386,10 +357,8 @@ void ROOT::Experimental::RNTupleWriter::CommitCluster(bool commitClusterGroup) CommitClusterGroup(); } - //------------------------------------------------------------------------------ - ROOT::Experimental::RCollectionNTupleWriter::RCollectionNTupleWriter(std::unique_ptr defaultEntry) : fOffset(0), fDefaultEntry(std::move(defaultEntry)) { diff --git a/tree/ntuple/v7/src/RNTupleDescriptor.cxx b/tree/ntuple/v7/src/RNTupleDescriptor.cxx index ce679989c4fce..27d97c521637f 100644 --- a/tree/ntuple/v7/src/RNTupleDescriptor.cxx +++ b/tree/ntuple/v7/src/RNTupleDescriptor.cxx @@ -1,6 +1,7 @@ /// \file RNTupleDescriptor.cxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer +/// \author Javier Lopez-Gomez /// \date 2018-10-04 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -18,6 +19,7 @@ #include #include #include +#include #include #include @@ -33,16 +35,10 @@ bool ROOT::Experimental::RFieldDescriptor::operator==(const RFieldDescriptor &other) const { - return fFieldId == other.fFieldId && - fFieldVersion == other.fFieldVersion && - fTypeVersion == other.fTypeVersion && - fFieldName == other.fFieldName && - fFieldDescription == other.fFieldDescription && - fTypeName == other.fTypeName && - fNRepetitions == other.fNRepetitions && - fStructure == other.fStructure && - fParentId == other.fParentId && - fLinkIds == other.fLinkIds; + return fFieldId == other.fFieldId && fFieldVersion == other.fFieldVersion && fTypeVersion == other.fTypeVersion && + fFieldName == other.fFieldName && fFieldDescription == other.fFieldDescription && + fTypeName == other.fTypeName && fTypeAlias == other.fTypeAlias && fNRepetitions == other.fNRepetitions && + fStructure == other.fStructure && fParentId == other.fParentId && fLinkIds == other.fLinkIds; } ROOT::Experimental::RFieldDescriptor @@ -55,6 +51,7 @@ ROOT::Experimental::RFieldDescriptor::Clone() const clone.fFieldName = fFieldName; clone.fFieldDescription = fFieldDescription; clone.fTypeName = fTypeName; + clone.fTypeAlias = fTypeAlias; clone.fNRepetitions = fNRepetitions; clone.fStructure = fStructure; clone.fParentId = fParentId; @@ -79,7 +76,8 @@ ROOT::Experimental::RFieldDescriptor::CreateField(const RNTupleDescriptor &ntplD return collectionField; } - auto field = Detail::RFieldBase::Create(GetFieldName(), GetTypeName()).Unwrap(); + auto field = + Detail::RFieldBase::Create(GetFieldName(), GetTypeAlias().empty() ? GetTypeName() : GetTypeAlias()).Unwrap(); field->SetOnDiskId(fFieldId); for (auto &f : *field) f.SetOnDiskId(ntplDesc.FindFieldId(f.GetName(), f.GetParent()->GetOnDiskId())); @@ -92,10 +90,8 @@ ROOT::Experimental::RFieldDescriptor::CreateField(const RNTupleDescriptor &ntplD bool ROOT::Experimental::RColumnDescriptor::operator==(const RColumnDescriptor &other) const { - return fColumnId == other.fColumnId && - fModel == other.fModel && - fFieldId == other.fFieldId && - fIndex == other.fIndex; + return fLogicalColumnId == other.fLogicalColumnId && fPhysicalColumnId == other.fPhysicalColumnId && + fModel == other.fModel && fFieldId == other.fFieldId && fIndex == other.fIndex; } @@ -103,10 +99,12 @@ ROOT::Experimental::RColumnDescriptor ROOT::Experimental::RColumnDescriptor::Clone() const { RColumnDescriptor clone; - clone.fColumnId = fColumnId; + clone.fLogicalColumnId = fLogicalColumnId; + clone.fPhysicalColumnId = fPhysicalColumnId; clone.fModel = fModel; clone.fFieldId = fFieldId; clone.fIndex = fIndex; + clone.fFirstElementIndex = fFirstElementIndex; return clone; } @@ -134,6 +132,39 @@ ROOT::Experimental::RClusterDescriptor::RPageRange::Find(ROOT::Experimental::RCl return RPageInfoExtended{pageInfo, firstInPage, pageNo}; } +std::size_t +ROOT::Experimental::RClusterDescriptor::RPageRange::ExtendToFitColumnRange(const RColumnRange &columnRange, + const Detail::RColumnElementBase &element, + std::size_t pageSize) +{ + R__ASSERT(fPhysicalColumnId == columnRange.fPhysicalColumnId); + + const auto nElements = std::accumulate(fPageInfos.begin(), fPageInfos.end(), 0U, + [](std::size_t n, const auto &PI) { return n + PI.fNElements; }); + const auto nElementsRequired = static_cast(columnRange.fNElements); + + if (nElementsRequired == nElements) + return 0U; + R__ASSERT((nElementsRequired > nElements) && "invalid attempt to shrink RPageRange"); + + std::vector pageInfos; + // Synthesize new `RPageInfo`s as needed + const std::uint64_t nElementsPerPage = pageSize / element.GetSize(); + R__ASSERT(nElementsPerPage > 0); + for (auto nRemainingElements = nElementsRequired - nElements; nRemainingElements > 0;) { + RPageInfo PI; + PI.fNElements = std::min(nElementsPerPage, nRemainingElements); + PI.fLocator.fType = RNTupleLocator::kTypePageZero; + PI.fLocator.fBytesOnStorage = element.GetPackedSize(PI.fNElements); + pageInfos.emplace_back(PI); + nRemainingElements -= PI.fNElements; + } + + pageInfos.insert(pageInfos.end(), std::make_move_iterator(fPageInfos.begin()), + std::make_move_iterator(fPageInfos.end())); + std::swap(fPageInfos, pageInfos); + return nElementsRequired - nElements; +} bool ROOT::Experimental::RClusterDescriptor::operator==(const RClusterDescriptor &other) const { @@ -152,11 +183,10 @@ std::unordered_set ROOT::Experimental::RClus return result; } - -bool ROOT::Experimental::RClusterDescriptor::ContainsColumn(DescriptorId_t columnId) const +bool ROOT::Experimental::RClusterDescriptor::ContainsColumn(DescriptorId_t physicalId) const { EnsureHasPageLocations(); - return fColumnRanges.find(columnId) != fColumnRanges.end(); + return fColumnRanges.find(physicalId) != fColumnRanges.end(); } @@ -196,21 +226,26 @@ ROOT::Experimental::RClusterDescriptor ROOT::Experimental::RClusterDescriptor::C bool ROOT::Experimental::RNTupleDescriptor::operator==(const RNTupleDescriptor &other) const { - return fName == other.fName && fDescription == other.fDescription && fNEntries == other.fNEntries && - fGeneration == other.fGeneration && fFieldDescriptors == other.fFieldDescriptors && + // clang-format off + return fName == other.fName && + fDescription == other.fDescription && + fNEntries == other.fNEntries && + fGeneration == other.fGeneration && + fFieldDescriptors == other.fFieldDescriptors && fColumnDescriptors == other.fColumnDescriptors && fClusterGroupDescriptors == other.fClusterGroupDescriptors && fClusterDescriptors == other.fClusterDescriptors; + // clang-format on } - -ROOT::Experimental::NTupleSize_t ROOT::Experimental::RNTupleDescriptor::GetNElements(DescriptorId_t columnId) const +ROOT::Experimental::NTupleSize_t +ROOT::Experimental::RNTupleDescriptor::GetNElements(DescriptorId_t physicalColumnId) const { NTupleSize_t result = 0; for (const auto &cd : fClusterDescriptors) { - if (!cd.second.ContainsColumn(columnId)) + if (!cd.second.ContainsColumn(physicalColumnId)) continue; - auto columnRange = cd.second.GetColumnRange(columnId); + auto columnRange = cd.second.GetColumnRange(physicalColumnId); result = std::max(result, columnRange.fFirstElementIndex + columnRange.fNElements); } return result; @@ -261,25 +296,33 @@ ROOT::Experimental::RNTupleDescriptor::FindFieldId(std::string_view fieldName) c return FindFieldId(fieldName, GetFieldZeroId()); } - ROOT::Experimental::DescriptorId_t -ROOT::Experimental::RNTupleDescriptor::FindColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const +ROOT::Experimental::RNTupleDescriptor::FindLogicalColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const { for (const auto &cd : fColumnDescriptors) { if (cd.second.GetFieldId() == fieldId && cd.second.GetIndex() == columnIndex) - return cd.second.GetId(); + return cd.second.GetLogicalId(); } return kInvalidDescriptorId; } ROOT::Experimental::DescriptorId_t -ROOT::Experimental::RNTupleDescriptor::FindClusterId(DescriptorId_t columnId, NTupleSize_t index) const +ROOT::Experimental::RNTupleDescriptor::FindPhysicalColumnId(DescriptorId_t fieldId, std::uint32_t columnIndex) const +{ + auto logicalId = FindLogicalColumnId(fieldId, columnIndex); + if (logicalId == kInvalidDescriptorId) + return kInvalidDescriptorId; + return GetColumnDescriptor(logicalId).GetPhysicalId(); +} + +ROOT::Experimental::DescriptorId_t +ROOT::Experimental::RNTupleDescriptor::FindClusterId(DescriptorId_t physicalColumnId, NTupleSize_t index) const { // TODO(jblomer): binary search? for (const auto &cd : fClusterDescriptors) { - if (!cd.second.ContainsColumn(columnId)) + if (!cd.second.ContainsColumn(physicalColumnId)) continue; - auto columnRange = cd.second.GetColumnRange(columnId); + auto columnRange = cd.second.GetColumnRange(physicalColumnId); if (columnRange.Contains(index)) return cd.second.GetId(); } @@ -315,6 +358,54 @@ ROOT::Experimental::RNTupleDescriptor::FindPrevClusterId(DescriptorId_t clusterI return kInvalidDescriptorId; } +std::vector +ROOT::Experimental::RNTupleDescriptor::RHeaderExtension::GetTopLevelFields(const RNTupleDescriptor &desc) const +{ + auto fieldZeroId = desc.GetFieldZeroId(); + + std::vector fields; + for (const DescriptorId_t fieldId : fFields) { + if (desc.GetFieldDescriptor(fieldId).GetParentId() == fieldZeroId) + fields.emplace_back(fieldId); + } + return fields; +} + +void ROOT::Experimental::RNTupleDescriptor::RColumnDescriptorIterable::CollectColumnIds(DescriptorId_t fieldId) { + for (unsigned int i = 0; true; ++i) { + auto logicalId = fNTuple.FindLogicalColumnId(fieldId, i); + if (logicalId == kInvalidDescriptorId) + break; + fColumns.emplace_back(logicalId); + } +} + +ROOT::Experimental::RNTupleDescriptor::RColumnDescriptorIterable::RColumnDescriptorIterable( + const RNTupleDescriptor &ntuple, const RFieldDescriptor &field) + : fNTuple(ntuple) +{ + CollectColumnIds(field.GetId()); +} + +ROOT::Experimental::RNTupleDescriptor::RColumnDescriptorIterable::RColumnDescriptorIterable( + const RNTupleDescriptor &ntuple) + : fNTuple(ntuple) +{ + std::deque fieldIdQueue{ntuple.GetFieldZeroId()}; + + while (!fieldIdQueue.empty()) { + auto currFieldId = fieldIdQueue.front(); + fieldIdQueue.pop_front(); + + CollectColumnIds(currFieldId); + + for (const auto &field : ntuple.GetFieldIterable(currFieldId)) { + auto fieldId = field.GetId(); + fieldIdQueue.push_back(fieldId); + } + } +} + ROOT::Experimental::RResult ROOT::Experimental::RNTupleDescriptor::AddClusterDetails(RClusterDescriptor &&clusterDesc) { @@ -358,6 +449,7 @@ std::unique_ptr ROOT::Experimental::RNTup clone->fOnDiskHeaderSize = fOnDiskHeaderSize; clone->fOnDiskFooterSize = fOnDiskFooterSize; clone->fNEntries = fNEntries; + clone->fNPhysicalColumns = fNPhysicalColumns; clone->fGeneration = fGeneration; for (const auto &d : fFieldDescriptors) clone->fFieldDescriptors.emplace(d.first, d.second.Clone()); @@ -367,6 +459,8 @@ std::unique_ptr ROOT::Experimental::RNTup clone->fClusterGroupDescriptors.emplace(d.first, d.second.Clone()); for (const auto &d : fClusterDescriptors) clone->fClusterDescriptors.emplace(d.first, d.second.Clone()); + if (fHeaderExtension) + clone->fHeaderExtension = std::make_unique(*fHeaderExtension); return clone; } @@ -374,7 +468,7 @@ std::unique_ptr ROOT::Experimental::RNTup bool ROOT::Experimental::RColumnGroupDescriptor::operator==(const RColumnGroupDescriptor &other) const { - return fColumnGroupId == other.fColumnGroupId && fColumnIds == other.fColumnIds; + return fColumnGroupId == other.fColumnGroupId && fPhysicalColumnIds == other.fPhysicalColumnIds; } //////////////////////////////////////////////////////////////////////////////// @@ -397,24 +491,77 @@ ROOT::Experimental::RClusterGroupDescriptor ROOT::Experimental::RClusterGroupDes //////////////////////////////////////////////////////////////////////////////// ROOT::Experimental::RResult -ROOT::Experimental::RClusterDescriptorBuilder::CommitColumnRange( - DescriptorId_t columnId, std::uint64_t firstElementIndex, std::uint32_t compressionSettings, - const RClusterDescriptor::RPageRange &pageRange) +ROOT::Experimental::RClusterDescriptorBuilder::CommitColumnRange(DescriptorId_t physicalId, + std::uint64_t firstElementIndex, + std::uint32_t compressionSettings, + const RClusterDescriptor::RPageRange &pageRange) { - if (columnId != pageRange.fColumnId) + if (physicalId != pageRange.fPhysicalColumnId) return R__FAIL("column ID mismatch"); - if (fCluster.fPageRanges.count(columnId) > 0) + if (fCluster.fPageRanges.count(physicalId) > 0) return R__FAIL("column ID conflict"); - RClusterDescriptor::RColumnRange columnRange{columnId, firstElementIndex, RClusterSize(0)}; + RClusterDescriptor::RColumnRange columnRange{physicalId, firstElementIndex, RClusterSize(0)}; columnRange.fCompressionSettings = compressionSettings; for (const auto &pi : pageRange.fPageInfos) { columnRange.fNElements += pi.fNElements; } - fCluster.fPageRanges[columnId] = pageRange.Clone(); - fCluster.fColumnRanges[columnId] = columnRange; + fCluster.fPageRanges[physicalId] = pageRange.Clone(); + fCluster.fColumnRanges[physicalId] = columnRange; return RResult::Success(); } +ROOT::Experimental::RClusterDescriptorBuilder & +ROOT::Experimental::RClusterDescriptorBuilder::AddDeferredColumnRanges(const RNTupleDescriptor &desc) +{ + /// Carries out a depth-first traversal of a field subtree rooted at `rootFieldId`. For each field, `visitField` is + /// called passing the field ID and the number of overall repetitions, taking into account the repetitions of each + /// parent field in the hierarchy. + auto fnTraverseSubtree = [&](DescriptorId_t rootFieldId, std::uint64_t nRepetitionsAtThisLevel, + const auto &visitField, const auto &enterSubtree) -> void { + visitField(rootFieldId, nRepetitionsAtThisLevel); + for (const auto &f : desc.GetFieldIterable(rootFieldId)) { + const std::uint64_t nRepetitions = std::max(f.GetNRepetitions(), std::uint64_t{1U}) * nRepetitionsAtThisLevel; + enterSubtree(f.GetId(), nRepetitions, visitField, enterSubtree); + } + }; + + // Deferred columns can only be part of the header extension + auto xHeader = desc.GetHeaderExtension(); + if (!xHeader) + return *this; + + // Ensure that all columns in the header extension have their associated `R(Column|Page)Range` + for (const auto &topLevelFieldId : xHeader->GetTopLevelFields(desc)) { + fnTraverseSubtree( + topLevelFieldId, std::max(desc.GetFieldDescriptor(topLevelFieldId).GetNRepetitions(), std::uint64_t{1U}), + [&](DescriptorId_t fieldId, std::uint64_t nRepetitions) { + for (const auto &c : desc.GetColumnIterable(fieldId)) { + const DescriptorId_t physicalId = c.GetPhysicalId(); + auto &columnRange = fCluster.fColumnRanges[physicalId]; + auto &pageRange = fCluster.fPageRanges[physicalId]; + // Initialize a RColumnRange for `physicalId` if it was not there + if (columnRange.fPhysicalColumnId == kInvalidDescriptorId) { + columnRange.fPhysicalColumnId = physicalId; + pageRange.fPhysicalColumnId = physicalId; + } + // Fixup the RColumnRange and RPageRange in deferred columns. We know what the first element index and + // number of elements should have been if the column was not deferred; fix those and let + // `ExtendToFitColumnRange()` synthesize RPageInfos accordingly. + // Note that a column whose first element index is != 0 already met the criteria of + // `RFieldBase::EntryToColumnElementIndex()`, i.e. it is a principal column reachable from the field zero + // excluding subfields of collection and variant fields. + if (c.IsDeferredColumn()) { + columnRange.fFirstElementIndex = fCluster.GetFirstEntryIndex() * nRepetitions; + columnRange.fNElements = fCluster.GetNEntries() * nRepetitions; + const auto element = Detail::RColumnElementBase::Generate(c.GetModel().GetType()); + pageRange.ExtendToFitColumnRange(columnRange, *element, Detail::RPage::kPageZeroSize); + } + } + }, + fnTraverseSubtree); + } + return *this; +} ROOT::Experimental::RResult ROOT::Experimental::RClusterDescriptorBuilder::MoveDescriptor() @@ -516,8 +663,10 @@ void ROOT::Experimental::RNTupleDescriptorBuilder::SetNTuple(const std::string_v ROOT::Experimental::RResult ROOT::Experimental::RColumnDescriptorBuilder::MakeDescriptor() const { - if (fColumn.GetId() == kInvalidDescriptorId) - return R__FAIL("invalid column id"); + if (fColumn.GetLogicalId() == kInvalidDescriptorId) + return R__FAIL("invalid logical column id"); + if (fColumn.GetPhysicalId() == kInvalidDescriptorId) + return R__FAIL("invalid physical column id"); if (fColumn.GetModel().GetType() == EColumnType::kUnknown) return R__FAIL("invalid column model"); if (fColumn.GetFieldId() == kInvalidDescriptorId) @@ -540,6 +689,7 @@ ROOT::Experimental::RFieldDescriptorBuilder::FromField(const Detail::RFieldBase& .FieldName(field.GetName()) .FieldDescription(field.GetDescription()) .TypeName(field.GetType()) + .TypeAlias(field.GetTypeAlias()) .Structure(field.GetStructure()) .NRepetitions(field.GetNRepetitions()); return fieldDesc; @@ -565,6 +715,8 @@ ROOT::Experimental::RFieldDescriptorBuilder::MakeDescriptor() const { void ROOT::Experimental::RNTupleDescriptorBuilder::AddField(const RFieldDescriptor& fieldDesc) { fDescriptor.fFieldDescriptors.emplace(fieldDesc.GetId(), fieldDesc.Clone()); + if (fDescriptor.fHeaderExtension) + fDescriptor.fHeaderExtension->AddFieldId(fieldDesc.GetId()); } ROOT::Experimental::RResult @@ -593,15 +745,22 @@ ROOT::Experimental::RNTupleDescriptorBuilder::AddFieldLink(DescriptorId_t fieldI return RResult::Success(); } -void ROOT::Experimental::RNTupleDescriptorBuilder::AddColumn(DescriptorId_t columnId, DescriptorId_t fieldId, - const RColumnModel &model, std::uint32_t index) +void ROOT::Experimental::RNTupleDescriptorBuilder::AddColumn(DescriptorId_t logicalId, DescriptorId_t physicalId, + DescriptorId_t fieldId, const RColumnModel &model, + std::uint32_t index, std::uint64_t firstElementIdx) { RColumnDescriptor c; - c.fColumnId = columnId; + c.fLogicalColumnId = logicalId; + c.fPhysicalColumnId = physicalId; c.fFieldId = fieldId; c.fModel = model; c.fIndex = index; - fDescriptor.fColumnDescriptors.emplace(columnId, std::move(c)); + c.fFirstElementIndex = firstElementIdx; + if (!c.IsAliasColumn()) + fDescriptor.fNPhysicalColumns++; + if (fDescriptor.fHeaderExtension) + fDescriptor.fHeaderExtension->AddColumn(/*isAliasColumn=*/c.IsAliasColumn()); + fDescriptor.fColumnDescriptors.emplace(logicalId, std::move(c)); } @@ -614,16 +773,24 @@ ROOT::Experimental::RNTupleDescriptorBuilder::AddColumn(RColumnDescriptor &&colu auto fieldExists = EnsureFieldExists(fieldId); if (!fieldExists) return R__FORWARD_ERROR(fieldExists); - if (fDescriptor.FindColumnId(fieldId, index) != kInvalidDescriptorId) { + if (fDescriptor.FindLogicalColumnId(fieldId, index) != kInvalidDescriptorId) { return R__FAIL("column index clash"); } if (index > 0) { - if (fDescriptor.FindColumnId(fieldId, index - 1) == kInvalidDescriptorId) + if (fDescriptor.FindLogicalColumnId(fieldId, index - 1) == kInvalidDescriptorId) return R__FAIL("out of bounds column index"); } + if (columnDesc.IsAliasColumn()) { + if (columnDesc.GetModel() != fDescriptor.GetColumnDescriptor(columnDesc.GetPhysicalId()).GetModel()) + return R__FAIL("alias column type mismatch"); + } - auto columnId = columnDesc.GetId(); - fDescriptor.fColumnDescriptors.emplace(columnId, std::move(columnDesc)); + auto logicalId = columnDesc.GetLogicalId(); + if (!columnDesc.IsAliasColumn()) + fDescriptor.fNPhysicalColumns++; + fDescriptor.fColumnDescriptors.emplace(logicalId, std::move(columnDesc)); + if (fDescriptor.fHeaderExtension) + fDescriptor.fHeaderExtension->AddColumn(/*isAliasColumn=*/columnDesc.IsAliasColumn()); return RResult::Success(); } @@ -653,6 +820,13 @@ void ROOT::Experimental::RNTupleDescriptorBuilder::Reset() fDescriptor.fColumnDescriptors.clear(); fDescriptor.fClusterDescriptors.clear(); fDescriptor.fClusterGroupDescriptors.clear(); + fDescriptor.fHeaderExtension.reset(); +} + +void ROOT::Experimental::RNTupleDescriptorBuilder::BeginHeaderExtension() +{ + if (!fDescriptor.fHeaderExtension) + fDescriptor.fHeaderExtension = std::make_unique(); } ROOT::Experimental::RResult diff --git a/tree/ntuple/v7/src/RNTupleDescriptorFmt.cxx b/tree/ntuple/v7/src/RNTupleDescriptorFmt.cxx index 1e6fbf988dd32..8c1ae9b88e8bc 100644 --- a/tree/ntuple/v7/src/RNTupleDescriptorFmt.cxx +++ b/tree/ntuple/v7/src/RNTupleDescriptorFmt.cxx @@ -43,7 +43,8 @@ struct ClusterInfo { }; struct ColumnInfo { - ROOT::Experimental::DescriptorId_t fColumnId = 0; + ROOT::Experimental::DescriptorId_t fPhysicalColumnId = 0; + ROOT::Experimental::DescriptorId_t fLogicalColumnId = 0; ROOT::Experimental::DescriptorId_t fFieldId = 0; std::uint64_t fLocalOrder = 0; std::uint64_t fNElements = 0; @@ -102,19 +103,20 @@ void ROOT::Experimental::RNTupleDescriptor::PrintInfo(std::ostream &output) cons auto elementSize = Detail::RColumnElementBase::Generate(column.second.GetModel().GetType())->GetSize(); ColumnInfo info; - info.fColumnId = column.second.GetId(); + info.fPhysicalColumnId = column.second.GetPhysicalId(); + info.fLogicalColumnId = column.second.GetLogicalId(); info.fFieldId = column.second.GetFieldId(); info.fLocalOrder = column.second.GetIndex(); info.fElementSize = elementSize; info.fType = column.second.GetModel().GetType(); for (const auto &cluster : fClusterDescriptors) { - auto columnRange = cluster.second.GetColumnRange(column.first); + auto columnRange = cluster.second.GetColumnRange(column.second.GetPhysicalId()); info.fNElements += columnRange.fNElements; if (compression == -1) { compression = columnRange.fCompressionSettings; } - const auto &pageRange = cluster.second.GetPageRange(column.first); + const auto &pageRange = cluster.second.GetPageRange(column.second.GetPhysicalId()); auto idx = cluster2Idx[cluster.first]; for (const auto &page : pageRange.fPageInfos) { bytesOnStorage += page.fLocator.fBytesOnStorage; @@ -137,7 +139,8 @@ void ROOT::Experimental::RNTupleDescriptor::PrintInfo(std::ostream &output) cons output << "------------------------------------------------------------" << std::endl; output << " # Entries: " << GetNEntries() << std::endl; output << " # Fields: " << GetNFields() << std::endl; - output << " # Columns: " << GetNColumns() << std::endl; + output << " # Columns: " << GetNPhysicalColumns() << std::endl; + output << " # Alias Columns: " << GetNLogicalColumns() - GetNPhysicalColumns() << std::endl; output << " # Pages: " << nPages << std::endl; output << " # Clusters: " << GetNClusters() << std::endl; output << " Size on storage: " << bytesOnStorage << " B" << std::endl; @@ -178,7 +181,9 @@ void ROOT::Experimental::RNTupleDescriptor::PrintInfo(std::ostream &output) cons auto avgElementsPerPage = (col.fNPages == 0) ? 0 : (col.fNElements / col.fNPages); std::string nameAndType = std::string(" ") + col.fFieldName + " [#" + std::to_string(col.fLocalOrder) + "]" + " -- " + Detail::RColumnElementBase::GetTypeName(col.fType); - std::string id = std::string("{id:") + std::to_string(col.fColumnId) + "}"; + std::string id = std::string("{id:") + std::to_string(col.fLogicalColumnId) + "}"; + if (col.fLogicalColumnId != col.fPhysicalColumnId) + id += " --alias--> " + std::to_string(col.fPhysicalColumnId); output << nameAndType << std::setw(60 - nameAndType.length()) << id << std::endl; if (!col.fFieldDescription.empty()) output << " Description: " << col.fFieldDescription << std::endl; diff --git a/tree/ntuple/v7/src/RNTupleModel.cxx b/tree/ntuple/v7/src/RNTupleModel.cxx index 51b0c308abdc2..88f536306ceed 100644 --- a/tree/ntuple/v7/src/RNTupleModel.cxx +++ b/tree/ntuple/v7/src/RNTupleModel.cxx @@ -24,6 +24,148 @@ #include #include +ROOT::Experimental::RResult +ROOT::Experimental::RNTupleModel::RProjectedFields::EnsureValidMapping(const Detail::RFieldBase *target, + const FieldMap_t &fieldMap) +{ + auto source = fieldMap.at(target); + const bool hasCompatibleStructure = + (source->GetStructure() == target->GetStructure()) || + ((source->GetStructure() == ENTupleStructure::kCollection) && dynamic_cast(target)); + if (!hasCompatibleStructure) + return R__FAIL("field mapping structural mismatch: " + source->GetName() + " --> " + target->GetName()); + if (source->GetStructure() == ENTupleStructure::kLeaf) { + if (target->GetType() != source->GetType()) + return R__FAIL("field mapping type mismatch: " + source->GetName() + " --> " + target->GetName()); + } + + // We support projections only across records and collections. In the following, we check that the projected + // field is on the same path of collection fields in the field tree than the source field. + + // Finds the first non-record parent field of the input field + auto fnBreakPoint = [](const Detail::RFieldBase *f) -> const Detail::RFieldBase * { + auto parent = f->GetParent(); + while (parent) { + if (parent->GetStructure() != ENTupleStructure::kRecord) + return parent; + parent = parent->GetParent(); + } + // We reached the zero field + return nullptr; + }; + + // If source or target has a variant or reference as a parent, error out + auto *sourceBreakPoint = fnBreakPoint(source); + if (sourceBreakPoint && sourceBreakPoint->GetStructure() != ENTupleStructure::kCollection) + return R__FAIL("unsupported field mapping (source structure)"); + auto *targetBreakPoint = fnBreakPoint(target); + if (targetBreakPoint && sourceBreakPoint->GetStructure() != ENTupleStructure::kCollection) + return R__FAIL("unsupported field mapping (target structure)"); + + if (!sourceBreakPoint && !targetBreakPoint) { + // Source and target have no collections as parent + return RResult::Success(); + } + if (sourceBreakPoint && targetBreakPoint) { + if (sourceBreakPoint == targetBreakPoint) { + // Source and target are children of the same collection + return RResult::Success(); + } + if (auto it = fieldMap.find(targetBreakPoint); it != fieldMap.end() && it->second == sourceBreakPoint) { + // The parent collection of parent is mapped to the parent collection of the source + return RResult::Success(); + } + // Source and target are children of different collections + return R__FAIL("field mapping structure mismatch: " + source->GetName() + " --> " + target->GetName()); + } + + // Either source or target have no collection as a parent, but the other one has; that doesn't fit + return R__FAIL("field mapping structure mismatch: " + source->GetName() + " --> " + target->GetName()); +} + +ROOT::Experimental::RResult +ROOT::Experimental::RNTupleModel::RProjectedFields::Add(std::unique_ptr field, + const FieldMap_t &fieldMap) +{ + auto result = EnsureValidMapping(field.get(), fieldMap); + if (!result) + return R__FORWARD_ERROR(result); + for (const auto &f : *field) { + result = EnsureValidMapping(&f, fieldMap); + if (!result) + return R__FORWARD_ERROR(result); + } + + fFieldMap.insert(fieldMap.begin(), fieldMap.end()); + fFieldZero->Attach(std::move(field)); + return RResult::Success(); +} + +const ROOT::Experimental::Detail::RFieldBase * +ROOT::Experimental::RNTupleModel::RProjectedFields::GetSourceField(const Detail::RFieldBase *target) const +{ + if (auto it = fFieldMap.find(target); it != fFieldMap.end()) + return it->second; + return nullptr; +} + +std::unique_ptr +ROOT::Experimental::RNTupleModel::RProjectedFields::Clone(const RNTupleModel *newModel) const +{ + auto cloneFieldZero = std::unique_ptr(static_cast(fFieldZero->Clone("").release())); + auto clone = std::unique_ptr(new RProjectedFields(std::move(cloneFieldZero))); + clone->fModel = newModel; + // TODO(jblomer): improve quadratic search to re-wire the field mappings given the new model and the cloned + // projected fields. Not too critical as we generally expect a limited number of projected fields + for (const auto &[k, v] : fFieldMap) { + for (const auto &f : *clone->GetFieldZero()) { + if (f.GetQualifiedFieldName() == k->GetQualifiedFieldName()) { + clone->fFieldMap[&f] = clone->fModel->GetField(v->GetQualifiedFieldName()); + break; + } + } + } + return clone; +} + +ROOT::Experimental::RNTupleModel::RUpdater::RUpdater(RNTupleWriter &writer) + : fWriter(writer), fOpenChangeset(*fWriter.fModel) +{ +} + +void ROOT::Experimental::RNTupleModel::RUpdater::BeginUpdate() +{ + fOpenChangeset.fModel.Unfreeze(); +} + +void ROOT::Experimental::RNTupleModel::RUpdater::CommitUpdate() +{ + fOpenChangeset.fModel.Freeze(); + if (fOpenChangeset.IsEmpty()) + return; + Detail::RNTupleModelChangeset toCommit{fOpenChangeset.fModel}; + std::swap(fOpenChangeset.fAddedFields, toCommit.fAddedFields); + std::swap(fOpenChangeset.fAddedProjectedFields, toCommit.fAddedProjectedFields); + fWriter.fSink->UpdateSchema(toCommit, fWriter.fNEntries); +} + +void ROOT::Experimental::RNTupleModel::RUpdater::AddField(std::unique_ptr field) +{ + auto fieldp = field.get(); + fOpenChangeset.fModel.AddField(std::move(field)); + fOpenChangeset.fAddedFields.emplace_back(fieldp); +} + +ROOT::Experimental::RResult +ROOT::Experimental::RNTupleModel::RUpdater::AddProjectedField(std::unique_ptr field, + std::function mapping) +{ + auto fieldp = field.get(); + auto result = fOpenChangeset.fModel.AddProjectedField(std::move(field), mapping); + if (result) + fOpenChangeset.fAddedProjectedFields.emplace_back(fieldp); + return R__FORWARD_RESULT(result); +} void ROOT::Experimental::RNTupleModel::EnsureValidFieldName(std::string_view fieldName) { @@ -53,6 +195,13 @@ ROOT::Experimental::RNTupleModel::RNTupleModel() : fFieldZero(std::make_unique()) {} +std::unique_ptr ROOT::Experimental::RNTupleModel::CreateBare() +{ + auto model = std::unique_ptr(new RNTupleModel()); + model->fProjectedFields = std::make_unique(model.get()); + return model; +} + std::unique_ptr ROOT::Experimental::RNTupleModel::Create() { auto model = CreateBare(); @@ -68,6 +217,7 @@ std::unique_ptr ROOT::Experimental::RNTupleMod cloneModel->fFieldZero = std::unique_ptr(static_cast(cloneFieldZero.release())); cloneModel->fFieldNames = fFieldNames; cloneModel->fDescription = fDescription; + cloneModel->fProjectedFields = fProjectedFields->Clone(cloneModel.get()); if (fDefaultEntry) { cloneModel->fDefaultEntry = std::unique_ptr(new REntry(fModelId)); for (const auto &f : cloneModel->fFieldZero->GetSubFields()) { @@ -90,6 +240,35 @@ void ROOT::Experimental::RNTupleModel::AddField(std::unique_ptrAttach(std::move(field)); } +ROOT::Experimental::RResult +ROOT::Experimental::RNTupleModel::AddProjectedField(std::unique_ptr field, + std::function mapping) +{ + EnsureNotFrozen(); + if (!field) + return R__FAIL("null field"); + auto fieldName = field->GetName(); + + RProjectedFields::FieldMap_t fieldMap; + auto sourceField = GetField(mapping(fieldName)); + if (!sourceField) + return R__FAIL("no such field: " + mapping(fieldName)); + fieldMap[field.get()] = sourceField; + for (const auto &subField : *field) { + sourceField = GetField(mapping(subField.GetQualifiedFieldName())); + if (!sourceField) + return R__FAIL("no such field: " + mapping(fieldName)); + fieldMap[&subField] = sourceField; + } + + EnsureValidFieldName(fieldName); + auto result = fProjectedFields->Add(std::move(field), fieldMap); + if (!result) { + fFieldNames.erase(fieldName); + return R__FORWARD_ERROR(result); + } + return RResult::Success(); +} std::shared_ptr ROOT::Experimental::RNTupleModel::MakeCollection( std::string_view fieldName, std::unique_ptr collectionModel) @@ -102,7 +281,7 @@ std::shared_ptr ROOT::Experimental: auto collectionNTuple = std::make_shared(std::move(collectionModel->fDefaultEntry)); auto field = std::make_unique(fieldName, collectionNTuple, std::move(collectionModel)); if (fDefaultEntry) - fDefaultEntry->CaptureValue(field->CaptureValue(collectionNTuple->GetOffsetPtr())); + fDefaultEntry->AddValue(field->BindValue(collectionNTuple->GetOffsetPtr())); fFieldZero->Attach(std::move(field)); return collectionNTuple; } @@ -156,11 +335,18 @@ std::unique_ptr ROOT::Experimental::RNTupleModel::Cr auto entry = std::unique_ptr(new REntry(fModelId)); for (const auto &f : fFieldZero->GetSubFields()) { - entry->CaptureValue(f->CaptureValue(nullptr)); + entry->AddValue(f->BindValue(nullptr)); } return entry; } +void ROOT::Experimental::RNTupleModel::Unfreeze() +{ + if (!IsFrozen()) + throw RException(R__FAIL("invalid attempt to unfreeze an unfrozen model")); + fModelId = 0; +} + void ROOT::Experimental::RNTupleModel::Freeze() { if (IsFrozen()) diff --git a/tree/ntuple/v7/src/RNTupleSerialize.cxx b/tree/ntuple/v7/src/RNTupleSerialize.cxx index f6b8b9b9c83b5..27b242af8df86 100644 --- a/tree/ntuple/v7/src/RNTupleSerialize.cxx +++ b/tree/ntuple/v7/src/RNTupleSerialize.cxx @@ -1,6 +1,7 @@ /// \file RNTupleSerialize.cxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer +/// \author Javier Lopez-Gomez /// \date 2021-08-02 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -34,8 +35,8 @@ using RResult = ROOT::Experimental::RResult; namespace { using RNTupleSerializer = ROOT::Experimental::Internal::RNTupleSerializer; -std::uint32_t SerializeFieldV1( - const ROOT::Experimental::RFieldDescriptor &fieldDesc, ROOT::Experimental::DescriptorId_t physParentId, void *buffer) +std::uint32_t SerializeFieldV1(const ROOT::Experimental::RFieldDescriptor &fieldDesc, + ROOT::Experimental::DescriptorId_t onDiskParentId, void *buffer) { auto base = reinterpret_cast(buffer); @@ -46,7 +47,7 @@ std::uint32_t SerializeFieldV1( pos += RNTupleSerializer::SerializeUInt32(fieldDesc.GetFieldVersion(), *where); pos += RNTupleSerializer::SerializeUInt32(fieldDesc.GetTypeVersion(), *where); - pos += RNTupleSerializer::SerializeUInt32(physParentId, *where); + pos += RNTupleSerializer::SerializeUInt32(onDiskParentId, *where); pos += RNTupleSerializer::SerializeFieldStructure(fieldDesc.GetStructure(), *where); if (fieldDesc.GetNRepetitions() > 0) { pos += RNTupleSerializer::SerializeUInt16(RNTupleSerializer::kFlagRepetitiveField, *where); @@ -56,7 +57,7 @@ std::uint32_t SerializeFieldV1( } pos += RNTupleSerializer::SerializeString(fieldDesc.GetFieldName(), *where); pos += RNTupleSerializer::SerializeString(fieldDesc.GetTypeName(), *where); - pos += RNTupleSerializer::SerializeString("" /* type alias */, *where); + pos += RNTupleSerializer::SerializeString(fieldDesc.GetTypeAlias(), *where); pos += RNTupleSerializer::SerializeString(fieldDesc.GetFieldDescription(), *where); auto size = pos - base; @@ -65,27 +66,30 @@ std::uint32_t SerializeFieldV1( return size; } -std::uint32_t SerializeFieldTree( - const ROOT::Experimental::RNTupleDescriptor &desc, - ROOT::Experimental::Internal::RNTupleSerializer::RContext &context, - void *buffer) +// clang-format off +/// Serialize, in order, fields enumerated in `fieldList` to `buffer`. `firstOnDiskId` specifies the on-disk ID for the +/// first element in the `fieldList` sequence. Before calling this function `RContext::MapSchema()` should have been +/// called on `context` in order to map in-memory field IDs to their on-disk counterpart. +/// \return The number of bytes written to the output buffer; if `buffer` is `nullptr` no data is serialized and the +/// required buffer size is returned +// clang-format on +std::uint32_t SerializeFieldList(const ROOT::Experimental::RNTupleDescriptor &desc, + std::span fieldList, + std::size_t firstOnDiskId, + const ROOT::Experimental::Internal::RNTupleSerializer::RContext &context, void *buffer) { auto base = reinterpret_cast(buffer); auto pos = base; void** where = (buffer == nullptr) ? &buffer : reinterpret_cast(&pos); - std::deque idQueue{desc.GetFieldZeroId()}; - - while (!idQueue.empty()) { - auto parentId = idQueue.front(); - idQueue.pop_front(); - - for (const auto &f : desc.GetFieldIterable(parentId)) { - auto physFieldId = context.MapFieldId(f.GetId()); - auto physParentId = (parentId == desc.GetFieldZeroId()) ? physFieldId : context.GetPhysFieldId(parentId); - pos += SerializeFieldV1(f, physParentId, *where); - idQueue.push_back(f.GetId()); - } + auto fieldZeroId = desc.GetFieldZeroId(); + ROOT::Experimental::DescriptorId_t onDiskFieldId = firstOnDiskId; + for (auto fieldId : fieldList) { + const auto &f = desc.GetFieldDescriptor(fieldId); + auto onDiskParentId = + (f.GetParentId() == fieldZeroId) ? onDiskFieldId : context.GetOnDiskFieldId(f.GetParentId()); + pos += SerializeFieldV1(f, onDiskParentId, *where); + ++onDiskFieldId; } return pos - base; @@ -139,7 +143,7 @@ RResult DeserializeFieldV1( std::string fieldName; std::string typeName; - std::string aliasName; // so far unused + std::string aliasName; std::string description; result = RNTupleSerializer::DeserializeString(bytes, fnFrameSizeLeft(), fieldName).Unwrap(); if (!result) @@ -157,15 +161,15 @@ RResult DeserializeFieldV1( if (!result) return R__FORWARD_ERROR(result); bytes += result.Unwrap(); - fieldDesc.FieldName(fieldName).TypeName(typeName).FieldDescription(description); + fieldDesc.FieldName(fieldName).TypeName(typeName).TypeAlias(aliasName).FieldDescription(description); return frameSize; } -std::uint32_t SerializeColumnListV1( - const ROOT::Experimental::RNTupleDescriptor &desc, - ROOT::Experimental::Internal::RNTupleSerializer::RContext &context, - void *buffer) +std::uint32_t SerializeColumnListV1(const ROOT::Experimental::RNTupleDescriptor &desc, + std::span fieldList, + const ROOT::Experimental::Internal::RNTupleSerializer::RContext &context, + void *buffer) { using RColumnElementBase = ROOT::Experimental::Detail::RColumnElementBase; @@ -173,36 +177,34 @@ std::uint32_t SerializeColumnListV1( auto pos = base; void** where = (buffer == nullptr) ? &buffer : reinterpret_cast(&pos); - std::deque idQueue{desc.GetFieldZeroId()}; - - while (!idQueue.empty()) { - auto parentId = idQueue.front(); - idQueue.pop_front(); - + for (auto parentId : fieldList) { for (const auto &c : desc.GetColumnIterable(parentId)) { + if (c.IsAliasColumn()) + continue; + auto frame = pos; pos += RNTupleSerializer::SerializeRecordFramePreamble(*where); auto type = c.GetModel().GetType(); pos += RNTupleSerializer::SerializeColumnType(type, *where); pos += RNTupleSerializer::SerializeUInt16(RColumnElementBase::GetBitsOnStorage(type), *where); - pos += RNTupleSerializer::SerializeUInt32(context.GetPhysFieldId(c.GetFieldId()), *where); + pos += RNTupleSerializer::SerializeUInt32(context.GetOnDiskFieldId(c.GetFieldId()), *where); std::uint32_t flags = 0; // TODO(jblomer): add support for descending columns in the column model if (c.GetModel().GetIsSorted()) flags |= RNTupleSerializer::kFlagSortAscColumn; // TODO(jblomer): fix for unsigned integer types - if (type == ROOT::Experimental::EColumnType::kIndex) + if (type == ROOT::Experimental::EColumnType::kIndex32) flags |= RNTupleSerializer::kFlagNonNegativeColumn; + const std::uint64_t firstElementIdx = c.GetFirstElementIndex(); + if (firstElementIdx > 0) + flags |= RNTupleSerializer::kFlagDeferredColumn; pos += RNTupleSerializer::SerializeUInt32(flags, *where); + if (flags & RNTupleSerializer::kFlagDeferredColumn) + pos += RNTupleSerializer::SerializeUInt64(firstElementIdx, *where); pos += RNTupleSerializer::SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); - - context.MapColumnId(c.GetId()); } - - for (const auto &f : desc.GetFieldIterable(parentId)) - idQueue.push_back(f.GetId()); } return pos - base; @@ -225,10 +227,11 @@ RResult DeserializeColumnV1( bytes += result.Unwrap(); // Initialize properly for SerializeColumnType - EColumnType type{EColumnType::kIndex}; + EColumnType type{EColumnType::kIndex32}; std::uint16_t bitsOnStorage; std::uint32_t fieldId; std::uint32_t flags; + std::uint64_t firstElementIdx = 0; if (fnFrameSizeLeft() < RNTupleSerializer::SerializeColumnType(type, nullptr) + sizeof(std::uint16_t) + 2 * sizeof(std::uint32_t)) { @@ -241,12 +244,17 @@ RResult DeserializeColumnV1( bytes += RNTupleSerializer::DeserializeUInt16(bytes, bitsOnStorage); bytes += RNTupleSerializer::DeserializeUInt32(bytes, fieldId); bytes += RNTupleSerializer::DeserializeUInt32(bytes, flags); + if (flags & RNTupleSerializer::kFlagDeferredColumn) { + if (fnFrameSizeLeft() < sizeof(std::uint64_t)) + return R__FAIL("column record frame too short"); + bytes += RNTupleSerializer::DeserializeUInt64(bytes, firstElementIdx); + } if (ROOT::Experimental::Detail::RColumnElementBase::GetBitsOnStorage(type) != bitsOnStorage) return R__FAIL("column element size mismatch"); const bool isSorted = (flags & (RNTupleSerializer::kFlagSortAscColumn | RNTupleSerializer::kFlagSortDesColumn)); - columnDesc.FieldId(fieldId).Model({type, isSorted}); + columnDesc.FieldId(fieldId).Model({type, isSorted}).FirstElementIndex(firstElementIdx); return frameSize; } @@ -287,6 +295,55 @@ void DeserializeLocatorPayloadObject64(const unsigned char *buffer, ROOT::Experi RNTupleSerializer::DeserializeUInt64(buffer + sizeof(std::uint32_t), data.fLocation); } +std::uint32_t SerializeAliasColumnList(const ROOT::Experimental::RNTupleDescriptor &desc, + std::span fieldList, + const ROOT::Experimental::Internal::RNTupleSerializer::RContext &context, + void *buffer) +{ + auto base = reinterpret_cast(buffer); + auto pos = base; + void **where = (buffer == nullptr) ? &buffer : reinterpret_cast(&pos); + + for (auto parentId : fieldList) { + for (const auto &c : desc.GetColumnIterable(parentId)) { + if (!c.IsAliasColumn()) + continue; + + auto frame = pos; + pos += RNTupleSerializer::SerializeRecordFramePreamble(*where); + + pos += RNTupleSerializer::SerializeUInt32(context.GetOnDiskColumnId(c.GetPhysicalId()), *where); + pos += RNTupleSerializer::SerializeUInt32(context.GetOnDiskFieldId(c.GetFieldId()), *where); + + pos += RNTupleSerializer::SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); + } + } + + return pos - base; +} + +RResult DeserializeAliasColumn(const void *buffer, std::uint32_t bufSize, + std::uint32_t &physicalColumnId, std::uint32_t &fieldId) +{ + auto base = reinterpret_cast(buffer); + auto bytes = base; + std::uint32_t frameSize; + auto fnFrameSizeLeft = [&]() { return frameSize - static_cast(bytes - base); }; + auto result = RNTupleSerializer::DeserializeFrameHeader(bytes, bufSize, frameSize); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + + if (fnFrameSizeLeft() < 2 * sizeof(std::uint32_t)) { + return R__FAIL("alias column record frame too short"); + } + + bytes += RNTupleSerializer::DeserializeUInt32(bytes, physicalColumnId); + bytes += RNTupleSerializer::DeserializeUInt32(bytes, fieldId); + + return frameSize; +} + } // anonymous namespace @@ -449,32 +506,34 @@ std::uint16_t ROOT::Experimental::Internal::RNTupleSerializer::SerializeColumnTy { using EColumnType = ROOT::Experimental::EColumnType; switch (type) { - case EColumnType::kIndex: - return SerializeUInt16(0x02, buffer); - case EColumnType::kSwitch: - return SerializeUInt16(0x03, buffer); - case EColumnType::kByte: - return SerializeUInt16(0x04, buffer); - case EColumnType::kChar: - return SerializeUInt16(0x05, buffer); - case EColumnType::kBit: - return SerializeUInt16(0x06, buffer); - case EColumnType::kReal64: - return SerializeUInt16(0x07, buffer); - case EColumnType::kReal32: - return SerializeUInt16(0x08, buffer); - case EColumnType::kReal16: - return SerializeUInt16(0x09, buffer); - case EColumnType::kInt64: - return SerializeUInt16(0x0A, buffer); - case EColumnType::kInt32: - return SerializeUInt16(0x0B, buffer); - case EColumnType::kInt16: - return SerializeUInt16(0x0C, buffer); - case EColumnType::kInt8: - return SerializeUInt16(0x0D, buffer); - default: - throw RException(R__FAIL("ROOT bug: unexpected column type")); + case EColumnType::kIndex64: return SerializeUInt16(0x01, buffer); + case EColumnType::kIndex32: return SerializeUInt16(0x02, buffer); + case EColumnType::kSwitch: return SerializeUInt16(0x03, buffer); + case EColumnType::kByte: return SerializeUInt16(0x04, buffer); + case EColumnType::kChar: return SerializeUInt16(0x05, buffer); + case EColumnType::kBit: return SerializeUInt16(0x06, buffer); + case EColumnType::kReal64: return SerializeUInt16(0x07, buffer); + case EColumnType::kReal32: return SerializeUInt16(0x08, buffer); + case EColumnType::kReal16: return SerializeUInt16(0x09, buffer); + case EColumnType::kInt64: return SerializeUInt16(0x16, buffer); + case EColumnType::kUInt64: return SerializeUInt16(0x0A, buffer); + case EColumnType::kInt32: return SerializeUInt16(0x17, buffer); + case EColumnType::kUInt32: return SerializeUInt16(0x0B, buffer); + case EColumnType::kInt16: return SerializeUInt16(0x18, buffer); + case EColumnType::kUInt16: return SerializeUInt16(0x0C, buffer); + case EColumnType::kInt8: return SerializeUInt16(0x19, buffer); + case EColumnType::kUInt8: return SerializeUInt16(0x0D, buffer); + case EColumnType::kSplitIndex64: return SerializeUInt16(0x0E, buffer); + case EColumnType::kSplitIndex32: return SerializeUInt16(0x0F, buffer); + case EColumnType::kSplitReal64: return SerializeUInt16(0x10, buffer); + case EColumnType::kSplitReal32: return SerializeUInt16(0x11, buffer); + case EColumnType::kSplitInt64: return SerializeUInt16(0x1A, buffer); + case EColumnType::kSplitUInt64: return SerializeUInt16(0x13, buffer); + case EColumnType::kSplitInt32: return SerializeUInt16(0x1B, buffer); + case EColumnType::kSplitUInt32: return SerializeUInt16(0x14, buffer); + case EColumnType::kSplitInt16: return SerializeUInt16(0x1C, buffer); + case EColumnType::kSplitUInt16: return SerializeUInt16(0x15, buffer); + default: throw RException(R__FAIL("ROOT bug: unexpected column type")); } } @@ -486,44 +545,34 @@ RResult ROOT::Experimental::Internal::RNTupleSerializer::Deserial std::uint16_t onDiskType; auto result = DeserializeUInt16(buffer, onDiskType); switch (onDiskType) { - case 0x02: - type = EColumnType::kIndex; - break; - case 0x03: - type = EColumnType::kSwitch; - break; - case 0x04: - type = EColumnType::kByte; - break; - case 0x05: - type = EColumnType::kChar; - break; - case 0x06: - type = EColumnType::kBit; - break; - case 0x07: - type = EColumnType::kReal64; - break; - case 0x08: - type = EColumnType::kReal32; - break; - case 0x09: - type = EColumnType::kReal16; - break; - case 0x0A: - type = EColumnType::kInt64; - break; - case 0x0B: - type = EColumnType::kInt32; - break; - case 0x0C: - type = EColumnType::kInt16; - break; - case 0x0D: - type = EColumnType::kInt8; - break; - default: - return R__FAIL("unexpected on-disk column type"); + case 0x01: type = EColumnType::kIndex64; break; + case 0x02: type = EColumnType::kIndex32; break; + case 0x03: type = EColumnType::kSwitch; break; + case 0x04: type = EColumnType::kByte; break; + case 0x05: type = EColumnType::kChar; break; + case 0x06: type = EColumnType::kBit; break; + case 0x07: type = EColumnType::kReal64; break; + case 0x08: type = EColumnType::kReal32; break; + case 0x09: type = EColumnType::kReal16; break; + case 0x16: type = EColumnType::kInt64; break; + case 0x0A: type = EColumnType::kUInt64; break; + case 0x17: type = EColumnType::kInt32; break; + case 0x0B: type = EColumnType::kUInt32; break; + case 0x18: type = EColumnType::kInt16; break; + case 0x0C: type = EColumnType::kUInt16; break; + case 0x19: type = EColumnType::kInt8; break; + case 0x0D: type = EColumnType::kUInt8; break; + case 0x0E: type = EColumnType::kSplitIndex64; break; + case 0x0F: type = EColumnType::kSplitIndex32; break; + case 0x10: type = EColumnType::kSplitReal64; break; + case 0x11: type = EColumnType::kSplitReal32; break; + case 0x1A: type = EColumnType::kSplitInt64; break; + case 0x13: type = EColumnType::kSplitUInt64; break; + case 0x1B: type = EColumnType::kSplitInt32; break; + case 0x14: type = EColumnType::kSplitUInt32; break; + case 0x1C: type = EColumnType::kSplitInt16; break; + case 0x15: type = EColumnType::kSplitUInt16; break; + default: return R__FAIL("unexpected on-disk column type"); } return result; } @@ -770,6 +819,9 @@ RResult ROOT::Experimental::Internal::RNTupleSerializer::Deserial std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializeLocator( const RNTupleLocator &locator, void *buffer) { + if (locator.fType > RNTupleLocator::kLastSerializableType) + throw RException(R__FAIL("locator is not serializable")); + std::uint32_t size = 0; if (locator.fType == RNTupleLocator::kTypeFile) { if (static_cast(locator.fBytesOnStorage) < 0) @@ -955,45 +1007,240 @@ RResult ROOT::Experimental::Internal::RNTupleSerializer::Deserial return frameSize; } - -ROOT::Experimental::Internal::RNTupleSerializer::RContext -ROOT::Experimental::Internal::RNTupleSerializer::SerializeHeaderV1( - void *buffer, const ROOT::Experimental::RNTupleDescriptor &desc) +void ROOT::Experimental::Internal::RNTupleSerializer::RContext::MapSchema(const RNTupleDescriptor &desc, + bool forHeaderExtension) { - RContext context; + auto fieldZeroId = desc.GetFieldZeroId(); + auto depthFirstTraversal = [&](std::span fieldTrees, auto doForEachField) { + std::deque idQueue{fieldTrees.begin(), fieldTrees.end()}; + while (!idQueue.empty()) { + auto fieldId = idQueue.front(); + idQueue.pop_front(); + // Field zero has no physical representation nor columns of its own; recurse over its subfields only + if (fieldId != fieldZeroId) + doForEachField(fieldId); + unsigned i = 0; + for (const auto &f : desc.GetFieldIterable(fieldId)) + idQueue.insert(idQueue.begin() + i++, f.GetId()); + } + }; + + R__ASSERT(desc.GetNFields() > 0); // we must have at least a zero field + if (!forHeaderExtension) + R__ASSERT(GetHeaderExtensionOffset() == -1U); + + std::vector fieldTrees; + if (!forHeaderExtension) { + fieldTrees.emplace_back(fieldZeroId); + } else if (auto xHeader = desc.GetHeaderExtension()) { + fieldTrees = xHeader->GetTopLevelFields(desc); + } + depthFirstTraversal(fieldTrees, [&](DescriptorId_t fieldId) { MapFieldId(fieldId); }); + depthFirstTraversal(fieldTrees, [&](DescriptorId_t fieldId) { + for (const auto &c : desc.GetColumnIterable(fieldId)) + if (!c.IsAliasColumn()) + MapColumnId(c.GetLogicalId()); + }); + depthFirstTraversal(fieldTrees, [&](DescriptorId_t fieldId) { + for (const auto &c : desc.GetColumnIterable(fieldId)) + if (c.IsAliasColumn()) + MapColumnId(c.GetLogicalId()); + }); + + // Anything added after this point is accounted for the header extension + if (!forHeaderExtension) + BeginHeaderExtension(); +} +std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializeSchemaDescription(void *buffer, + const RNTupleDescriptor &desc, + const RContext &context, + bool forHeaderExtension) +{ auto base = reinterpret_cast(buffer); auto pos = base; void** where = (buffer == nullptr) ? &buffer : reinterpret_cast(&pos); - pos += SerializeEnvelopePreamble(*where); - // So far we don't make use of feature flags - pos += SerializeFeatureFlags(std::vector(), *where); - pos += SerializeUInt32(kReleaseCandidateTag, *where); - pos += SerializeString(desc.GetName(), *where); - pos += SerializeString(desc.GetDescription(), *where); - pos += SerializeString(std::string("ROOT v") + ROOT_RELEASE, *where); + std::size_t nFields = 0, nColumns = 0, nAliasColumns = 0, fieldListOffset = 0; + if (forHeaderExtension) { + // A call to `RNTupleDescriptorBuilder::BeginHeaderExtension()` is not strictly required after serializing the + // header, which may happen, e.g., in unit tests. Ensure an empty schema extension is serialized in this case + if (auto xHeader = desc.GetHeaderExtension()) { + nFields = xHeader->GetNFields(); + nColumns = xHeader->GetNPhysicalColumns(); + nAliasColumns = xHeader->GetNLogicalColumns() - xHeader->GetNPhysicalColumns(); + fieldListOffset = context.GetHeaderExtensionOffset(); + } + } else { + nFields = desc.GetNFields() - 1; + nColumns = desc.GetNPhysicalColumns(); + nAliasColumns = desc.GetNLogicalColumns() - desc.GetNPhysicalColumns(); + } + const auto &onDiskFields = context.GetOnDiskFieldList(); + R__ASSERT(onDiskFields.size() >= fieldListOffset); + std::span fieldList{onDiskFields.data() + fieldListOffset, + onDiskFields.size() - fieldListOffset}; auto frame = pos; - R__ASSERT(desc.GetNFields() > 0); // we must have at least a zero field - pos += SerializeListFramePreamble(desc.GetNFields() - 1, *where); - pos += SerializeFieldTree(desc, context, *where); + pos += SerializeListFramePreamble(nFields, *where); + pos += SerializeFieldList(desc, fieldList, /*firstOnDiskId=*/fieldListOffset, context, *where); pos += SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); frame = pos; - pos += SerializeListFramePreamble(desc.GetNColumns(), *where); - pos += SerializeColumnListV1(desc, context, *where); + pos += SerializeListFramePreamble(nColumns, *where); + pos += SerializeColumnListV1(desc, fieldList, context, *where); pos += SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); - // We don't use alias columns yet frame = pos; - pos += SerializeListFramePreamble(0, *where); + pos += SerializeListFramePreamble(nAliasColumns, *where); + pos += SerializeAliasColumnList(desc, fieldList, context, *where); pos += SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); // We don't use extra type information yet frame = pos; pos += SerializeListFramePreamble(0, *where); pos += SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); + return static_cast(pos - base); +} + +RResult +ROOT::Experimental::Internal::RNTupleSerializer::DeserializeSchemaDescription(const void *buffer, std::uint32_t bufSize, + RNTupleDescriptorBuilder &descBuilder) +{ + auto base = reinterpret_cast(buffer); + auto bytes = base; + auto fnBufSizeLeft = [&]() { return bufSize - (bytes - base); }; + RResult result{0}; + + std::uint32_t frameSize; + auto frame = bytes; + auto fnFrameSizeLeft = [&]() { return frameSize - (bytes - frame); }; + + std::uint32_t nFields; + result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nFields); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + // The zero field is always added before `DeserializeSchemaDescription()` is called + const std::uint32_t fieldIdRangeBegin = descBuilder.GetDescriptor().GetNFields() - 1; + for (unsigned i = 0; i < nFields; ++i) { + std::uint32_t fieldId = fieldIdRangeBegin + i; + RFieldDescriptorBuilder fieldBuilder; + result = DeserializeFieldV1(bytes, fnFrameSizeLeft(), fieldBuilder); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + if (fieldId == fieldBuilder.GetParentId()) + fieldBuilder.ParentId(kZeroFieldId); + auto fieldDesc = fieldBuilder.FieldId(fieldId).MakeDescriptor(); + if (!fieldDesc) + return R__FORWARD_ERROR(fieldDesc); + auto parentId = fieldDesc.Inspect().GetParentId(); + descBuilder.AddField(fieldDesc.Unwrap()); + auto resVoid = descBuilder.AddFieldLink(parentId, fieldId); + if (!resVoid) + return R__FORWARD_ERROR(resVoid); + } + bytes = frame + frameSize; + + std::uint32_t nColumns; + frame = bytes; + result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nColumns); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + const std::uint32_t columnIdRangeBegin = descBuilder.GetDescriptor().GetNLogicalColumns(); + std::unordered_map maxIndexes; + for (unsigned i = 0; i < nColumns; ++i) { + std::uint32_t columnId = columnIdRangeBegin + i; + RColumnDescriptorBuilder columnBuilder; + result = DeserializeColumnV1(bytes, fnFrameSizeLeft(), columnBuilder); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + + std::uint32_t idx = 0; + const auto fieldId = columnBuilder.GetFieldId(); + auto maxIdx = maxIndexes.find(fieldId); + if (maxIdx != maxIndexes.end()) + idx = maxIdx->second + 1; + maxIndexes[fieldId] = idx; + + auto columnDesc = columnBuilder.Index(idx).LogicalColumnId(columnId).PhysicalColumnId(columnId).MakeDescriptor(); + if (!columnDesc) + return R__FORWARD_ERROR(columnDesc); + auto resVoid = descBuilder.AddColumn(columnDesc.Unwrap()); + if (!resVoid) + return R__FORWARD_ERROR(resVoid); + } + bytes = frame + frameSize; + + std::uint32_t nAliasColumns; + frame = bytes; + result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nAliasColumns); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + const std::uint32_t aliasColumnIdRangeBegin = columnIdRangeBegin + nColumns; + for (unsigned i = 0; i < nAliasColumns; ++i) { + std::uint32_t physicalId; + std::uint32_t fieldId; + result = DeserializeAliasColumn(bytes, fnFrameSizeLeft(), physicalId, fieldId); + if (!result) + return R__FORWARD_ERROR(result); + bytes += result.Unwrap(); + + RColumnDescriptorBuilder columnBuilder; + columnBuilder.LogicalColumnId(aliasColumnIdRangeBegin + i).PhysicalColumnId(physicalId).FieldId(fieldId); + columnBuilder.Model(descBuilder.GetDescriptor().GetColumnDescriptor(physicalId).GetModel()); + + std::uint32_t idx = 0; + auto maxIdx = maxIndexes.find(fieldId); + if (maxIdx != maxIndexes.end()) + idx = maxIdx->second + 1; + maxIndexes[fieldId] = idx; + + auto aliasColumnDesc = columnBuilder.Index(idx).MakeDescriptor(); + if (!aliasColumnDesc) + return R__FORWARD_ERROR(aliasColumnDesc); + auto resVoid = descBuilder.AddColumn(aliasColumnDesc.Unwrap()); + if (!resVoid) + return R__FORWARD_ERROR(resVoid); + } + bytes = frame + frameSize; + + std::uint32_t nTypeInfo; + frame = bytes; + result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nTypeInfo); + if (!result) + return R__FORWARD_ERROR(result); + if (nTypeInfo > 0) + R__LOG_WARNING(NTupleLog()) << "Extra type information is still unsupported! "; + bytes = frame + frameSize; + + return bytes - base; +} + +ROOT::Experimental::Internal::RNTupleSerializer::RContext +ROOT::Experimental::Internal::RNTupleSerializer::SerializeHeaderV1(void *buffer, + const ROOT::Experimental::RNTupleDescriptor &desc) +{ + RContext context; + + auto base = reinterpret_cast(buffer); + auto pos = base; + void **where = (buffer == nullptr) ? &buffer : reinterpret_cast(&pos); + + pos += SerializeEnvelopePreamble(*where); + // So far we don't make use of feature flags + pos += SerializeFeatureFlags(std::vector(), *where); + pos += SerializeUInt32(kReleaseCandidateTag, *where); + pos += SerializeString(desc.GetName(), *where); + pos += SerializeString(desc.GetDescription(), *where); + pos += SerializeString(std::string("ROOT v") + ROOT_RELEASE, *where); + + context.MapSchema(desc, /*forHeaderExtension=*/false); + pos += SerializeSchemaDescription(*where, desc, context); std::uint32_t size = pos - base; std::uint32_t crc32 = 0; @@ -1018,14 +1265,14 @@ std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializePageList for (auto clusterId : physClusterIDs) { const auto &clusterDesc = desc.GetClusterDescriptor(context.GetMemClusterId(clusterId)); // Get an ordered set of physical column ids - std::set physColumnIds; + std::set onDiskColumnIds; for (auto column : clusterDesc.GetColumnIds()) - physColumnIds.insert(context.GetPhysColumnId(column)); + onDiskColumnIds.insert(context.GetOnDiskColumnId(column)); auto outerFrame = pos; - pos += SerializeListFramePreamble(physColumnIds.size(), *where); - for (auto physId : physColumnIds) { - auto memId = context.GetMemColumnId(physId); + pos += SerializeListFramePreamble(onDiskColumnIds.size(), *where); + for (auto onDiskId : onDiskColumnIds) { + auto memId = context.GetMemColumnId(onDiskId); const auto &columnRange = clusterDesc.GetColumnRange(memId); const auto &pageRange = clusterDesc.GetPageRange(memId); @@ -1050,8 +1297,10 @@ std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializePageList return size; } -std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializeFooterV1( - void *buffer, const ROOT::Experimental::RNTupleDescriptor &desc, const RContext &context) +std::uint32_t +ROOT::Experimental::Internal::RNTupleSerializer::SerializeFooterV1(void *buffer, + const ROOT::Experimental::RNTupleDescriptor &desc, + const RContext &context) { auto base = reinterpret_cast(buffer); auto pos = base; @@ -1063,9 +1312,10 @@ std::uint32_t ROOT::Experimental::Internal::RNTupleSerializer::SerializeFooterV1 pos += SerializeFeatureFlags(std::vector(), *where); pos += SerializeUInt32(context.GetHeaderCRC32(), *where); - // So far no support for extension headers + // Schema extension, i.e. incremental changes with respect to the header auto frame = pos; - pos += SerializeListFramePreamble(0, *where); + pos += SerializeRecordFramePreamble(*where); + pos += SerializeSchemaDescription(*where, desc, context, /*forHeaderExtension=*/true); pos += SerializeFramePostscript(buffer ? frame : nullptr, pos - frame); // So far no support for shared clusters (no column groups) @@ -1165,87 +1415,12 @@ ROOT::Experimental::RResult ROOT::Experimental::Internal::RNTupleSerialize bytes += result.Unwrap(); descBuilder.SetNTuple(name, description); - std::uint32_t frameSize; - auto frame = bytes; - auto fnFrameSizeLeft = [&]() { return frameSize - (bytes - frame); }; - - std::uint32_t nFields; - result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nFields); - if (!result) - return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); // Zero field - descBuilder.AddField(RFieldDescriptorBuilder() - .FieldId(kZeroFieldId) - .Structure(ENTupleStructure::kRecord) - .MakeDescriptor() - .Unwrap()); - for (std::uint32_t fieldId = 0; fieldId < nFields; ++fieldId) { - RFieldDescriptorBuilder fieldBuilder; - result = DeserializeFieldV1(bytes, fnFrameSizeLeft(), fieldBuilder); - if (!result) - return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); - if (fieldId == fieldBuilder.GetParentId()) - fieldBuilder.ParentId(kZeroFieldId); - auto fieldDesc = fieldBuilder.FieldId(fieldId).MakeDescriptor(); - if (!fieldDesc) - return R__FORWARD_ERROR(fieldDesc); - auto parentId = fieldDesc.Inspect().GetParentId(); - descBuilder.AddField(fieldDesc.Unwrap()); - auto resVoid = descBuilder.AddFieldLink(parentId, fieldId); - if (!resVoid) - return R__FORWARD_ERROR(resVoid); - } - bytes = frame + frameSize; - - std::uint32_t nColumns; - frame = bytes; - result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nColumns); - if (!result) - return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); - std::unordered_map maxIndexes; - for (std::uint32_t columnId = 0; columnId < nColumns; ++columnId) { - RColumnDescriptorBuilder columnBuilder; - result = DeserializeColumnV1(bytes, fnFrameSizeLeft(), columnBuilder); - if (!result) - return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); - - std::uint32_t idx = 0; - const auto fieldId = columnBuilder.GetFieldId(); - auto maxIdx = maxIndexes.find(fieldId); - if (maxIdx != maxIndexes.end()) - idx = maxIdx->second + 1; - maxIndexes[fieldId] = idx; - - auto columnDesc = columnBuilder.Index(idx).ColumnId(columnId).MakeDescriptor(); - if (!columnDesc) - return R__FORWARD_ERROR(columnDesc); - auto resVoid = descBuilder.AddColumn(columnDesc.Unwrap()); - if (!resVoid) - return R__FORWARD_ERROR(resVoid); - } - bytes = frame + frameSize; - - std::uint32_t nAliasColumns; - frame = bytes; - result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nAliasColumns); + descBuilder.AddField( + RFieldDescriptorBuilder().FieldId(kZeroFieldId).Structure(ENTupleStructure::kRecord).MakeDescriptor().Unwrap()); + result = DeserializeSchemaDescription(bytes, fnBufSizeLeft(), descBuilder); if (!result) return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); - if (nAliasColumns > 0) - R__LOG_WARNING(NTupleLog()) << "Alias columns are still unsupported! "; - - std::uint32_t nTypeInfo; - frame = bytes; - result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nTypeInfo); - if (!result) - return R__FORWARD_ERROR(result); - bytes += result.Unwrap(); - if (nTypeInfo > 0) - R__LOG_WARNING(NTupleLog()) << "Extra type information is still unsupported! "; return RResult::Success(); } @@ -1285,12 +1460,16 @@ ROOT::Experimental::RResult ROOT::Experimental::Internal::RNTupleSerialize auto frame = bytes; auto fnFrameSizeLeft = [&]() { return frameSize - (bytes - frame); }; - std::uint32_t nXHeaders; - result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize, nXHeaders); + result = DeserializeFrameHeader(bytes, fnBufSizeLeft(), frameSize); if (!result) return R__FORWARD_ERROR(result); - if (nXHeaders > 0) - R__LOG_WARNING(NTupleLog()) << "extension headers are still unsupported"; + bytes += result.Unwrap(); + if (fnFrameSizeLeft() > 0) { + descBuilder.BeginHeaderExtension(); + result = DeserializeSchemaDescription(bytes, fnFrameSizeLeft(), descBuilder); + if (!result) + return R__FORWARD_ERROR(result); + } bytes = frame + frameSize; std::uint32_t nColumnGroups; @@ -1408,7 +1587,7 @@ ROOT::Experimental::RResult ROOT::Experimental::Internal::RNTupleSerialize bytes += result.Unwrap(); RClusterDescriptor::RPageRange pageRange; - pageRange.fColumnId = j; + pageRange.fPhysicalColumnId = j; for (std::uint32_t k = 0; k < nPages; ++k) { if (fnInnerFrameSizeLeft() < static_cast(sizeof(std::uint32_t))) return R__FAIL("inner frame too short"); @@ -1418,7 +1597,7 @@ ROOT::Experimental::RResult ROOT::Experimental::Internal::RNTupleSerialize result = DeserializeLocator(bytes, fnInnerFrameSizeLeft(), locator); if (!result) return R__FORWARD_ERROR(result); - pageRange.fPageInfos.push_back({ClusterSize_t(nElements), locator}); + pageRange.fPageInfos.push_back({nElements, locator}); bytes += result.Unwrap(); } diff --git a/tree/ntuple/v7/src/RPage.cxx b/tree/ntuple/v7/src/RPage.cxx index 970907f6748eb..4e4ab71dbceab 100644 --- a/tree/ntuple/v7/src/RPage.cxx +++ b/tree/ntuple/v7/src/RPage.cxx @@ -14,3 +14,19 @@ *************************************************************************/ #include + +namespace ROOT { +namespace Experimental { + +namespace Detail { + +const void *RPage::GetPageZeroBuffer() +{ + static const auto pageZero = std::make_unique(kPageZeroSize); + return pageZero.get(); +} + +} // namespace Detail + +} // namespace Experimental +} // namespace ROOT diff --git a/tree/ntuple/v7/src/RPageAllocator.cxx b/tree/ntuple/v7/src/RPageAllocator.cxx index 466a948d9716e..b7e7f781119ca 100644 --- a/tree/ntuple/v7/src/RPageAllocator.cxx +++ b/tree/ntuple/v7/src/RPageAllocator.cxx @@ -29,5 +29,6 @@ ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorHeap void ROOT::Experimental::Detail::RPageAllocatorHeap::DeletePage(const RPage& page) { - delete[] reinterpret_cast(page.GetBuffer()); + if (!page.IsPageZero()) + delete[] reinterpret_cast(page.GetBuffer()); } diff --git a/tree/ntuple/v7/src/RPageSinkBuf.cxx b/tree/ntuple/v7/src/RPageSinkBuf.cxx index b22ef705ef530..a39cfce1f1d6c 100644 --- a/tree/ntuple/v7/src/RPageSinkBuf.cxx +++ b/tree/ntuple/v7/src/RPageSinkBuf.cxx @@ -2,6 +2,7 @@ /// \ingroup NTuple ROOT7 /// \author Jakob Blomer /// \author Max Orok +/// \author Javier Lopez-Gomez /// \date 2021-03-17 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! @@ -21,6 +22,17 @@ #include +void ROOT::Experimental::Detail::RPageSinkBuf::RColumnBuf::DropBufferedPages() +{ + for (auto &bufPage : fBufferedPages) { + fCol.fColumn->GetPageSink()->ReleasePage(bufPage.fPage); + } + fBufferedPages.clear(); + // Each RSealedPage points to the same region as `fBuf` for some element in `fBufferedPages`; thus, no further + // clean-up is required + fSealedPages.clear(); +} + ROOT::Experimental::Detail::RPageSinkBuf::RPageSinkBuf(std::unique_ptr inner) : RPageSink(inner->GetNTupleName(), inner->GetWriteOptions()) , fMetrics("RPageSinkBuf") @@ -33,15 +45,61 @@ ROOT::Experimental::Detail::RPageSinkBuf::RPageSinkBuf(std::unique_ptrGetMetrics()); } +ROOT::Experimental::Detail::RPageSinkBuf::~RPageSinkBuf() +{ + // Wait for unterminated tasks, if any, as they may still hold a reference to `this`. + // This cannot be moved to the base class destructor, given non-static members have been destroyed by the time the + // base class destructor is invoked. + WaitForAllTasks(); +} + void ROOT::Experimental::Detail::RPageSinkBuf::CreateImpl(const RNTupleModel &model, unsigned char * /* serializedHeader */, std::uint32_t /* length */) { - fBufferedColumns.resize(fDescriptorBuilder.GetDescriptor().GetNColumns()); fInnerModel = model.Clone(); fInnerSink->Create(*fInnerModel); } +void ROOT::Experimental::Detail::RPageSinkBuf::UpdateSchema(const RNTupleModelChangeset &changeset, + NTupleSize_t firstEntry) +{ + RPageSink::UpdateSchema(changeset, firstEntry); + bool isIncremental = !fBufferedColumns.empty(); + fBufferedColumns.resize(fDescriptorBuilder.GetDescriptor().GetNPhysicalColumns()); + if (!isIncremental) + return; + + // The buffered page sink maintains a copy of the RNTupleModel for the inner sink; replicate the changes there + // TODO(jalopezg): we should be able, in general, to simplify the buffered sink. + auto cloneAddField = [&](const RFieldBase *field) { + auto cloned = field->Clone(field->GetName()); + auto p = &(*cloned); + fInnerModel->AddField(std::move(cloned)); + return p; + }; + auto cloneAddProjectedField = [&](RFieldBase *field) { + auto cloned = field->Clone(field->GetName()); + auto p = &(*cloned); + auto &projectedFields = changeset.fModel.GetProjectedFields(); + RNTupleModel::RProjectedFields::FieldMap_t fieldMap; + fieldMap[p] = projectedFields.GetSourceField(field); + auto targetIt = cloned->begin(); + for (auto &f : *field) + fieldMap[&(*targetIt++)] = projectedFields.GetSourceField(&f); + const_cast(fInnerModel->GetProjectedFields()).Add(std::move(cloned), fieldMap); + return p; + }; + RNTupleModelChangeset innerChangeset{*fInnerModel}; + fInnerModel->Unfreeze(); + std::transform(changeset.fAddedFields.cbegin(), changeset.fAddedFields.cend(), + std::back_inserter(innerChangeset.fAddedFields), cloneAddField); + std::transform(changeset.fAddedProjectedFields.cbegin(), changeset.fAddedProjectedFields.cend(), + std::back_inserter(innerChangeset.fAddedProjectedFields), cloneAddProjectedField); + fInnerModel->Freeze(); + fInnerSink->UpdateSchema(innerChangeset, firstEntry); +} + ROOT::Experimental::RNTupleLocator ROOT::Experimental::Detail::RPageSinkBuf::CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) { @@ -50,25 +108,24 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitPageImpl(ColumnHandle_t columnHa // make sure the page is aware of how many elements it will have bufPage.GrowUnchecked(page.GetNElements()); memcpy(bufPage.GetBuffer(), page.GetBuffer(), page.GetNBytes()); - // Safety: RColumnBuf::iterators are guaranteed to be valid until the - // element is destroyed. In other words, all buffered page iterators are + // Safety: References are guaranteed to be valid until the + // element is destroyed. In other words, all buffered page elements are // valid until the return value of DrainBufferedPages() goes out of scope in // CommitCluster(). - RColumnBuf::iterator zipItem = - fBufferedColumns.at(columnHandle.fId).BufferPage(columnHandle, bufPage); + auto &zipItem = fBufferedColumns.at(columnHandle.fPhysicalId).BufferPage(columnHandle, bufPage); if (!fTaskScheduler) { return RNTupleLocator{}; } fCounters->fParallelZip.SetValue(1); // Thread safety: Each thread works on a distinct zipItem which owns its // compression buffer. - zipItem->AllocateSealedPageBuf(); - R__ASSERT(zipItem->fBuf); - auto sealedPage = fBufferedColumns.at(columnHandle.fId).RegisterSealedPage(); - fTaskScheduler->AddTask([this, zipItem, sealedPage, colId = columnHandle.fId] { - *sealedPage = SealPage(zipItem->fPage, *fBufferedColumns.at(colId).GetHandle().fColumn->GetElement(), - GetWriteOptions().GetCompression(), zipItem->fBuf.get()); - zipItem->fSealedPage = &(*sealedPage); + zipItem.AllocateSealedPageBuf(); + R__ASSERT(zipItem.fBuf); + auto &sealedPage = fBufferedColumns.at(columnHandle.fPhysicalId).RegisterSealedPage(); + fTaskScheduler->AddTask([this, &zipItem, &sealedPage, colId = columnHandle.fPhysicalId] { + sealedPage = SealPage(zipItem.fPage, *fBufferedColumns.at(colId).GetHandle().fColumn->GetElement(), + GetWriteOptions().GetCompression(), zipItem.fBuf.get()); + zipItem.fSealedPage = &sealedPage; }); // we're feeding bad locators to fOpenPageRanges but it should not matter @@ -77,10 +134,10 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitPageImpl(ColumnHandle_t columnHa } ROOT::Experimental::RNTupleLocator -ROOT::Experimental::Detail::RPageSinkBuf::CommitSealedPageImpl( - DescriptorId_t columnId, const RSealedPage &sealedPage) +ROOT::Experimental::Detail::RPageSinkBuf::CommitSealedPageImpl(DescriptorId_t physicalColumnId, + const RSealedPage &sealedPage) { - fInnerSink->CommitSealedPage(columnId, sealedPage); + fInnerSink->CommitSealedPage(physicalColumnId, sealedPage); // we're feeding bad locators to fOpenPageRanges but it should not matter // because they never get written out return RNTupleLocator{}; @@ -89,10 +146,7 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitSealedPageImpl( std::uint64_t ROOT::Experimental::Detail::RPageSinkBuf::CommitClusterImpl(ROOT::Experimental::NTupleSize_t nEntries) { - if (fTaskScheduler) { - fTaskScheduler->Wait(); - fTaskScheduler->Reset(); - } + WaitForAllTasks(); // If we have only sealed pages in all buffered columns, commit them in a single `CommitSealedPageV()` call bool singleCommitCall = std::all_of(fBufferedColumns.begin(), fBufferedColumns.end(), @@ -102,12 +156,12 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitClusterImpl(ROOT::Experimental:: toCommit.reserve(fBufferedColumns.size()); for (auto &bufColumn : fBufferedColumns) { const auto &sealedPages = bufColumn.GetSealedPages(); - toCommit.emplace_back(bufColumn.GetHandle().fId, sealedPages.cbegin(), sealedPages.cend()); + toCommit.emplace_back(bufColumn.GetHandle().fPhysicalId, sealedPages.cbegin(), sealedPages.cend()); } fInnerSink->CommitSealedPageV(toCommit); for (auto &bufColumn : fBufferedColumns) - bufColumn.DrainBufferedPages(); + bufColumn.DropBufferedPages(); return fInnerSink->CommitCluster(nEntries); } @@ -116,7 +170,7 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitClusterImpl(ROOT::Experimental:: // In practice, either all (see above) or none of the buffered pages have been sealed, depending on whether // a task scheduler is available. The rare condition of a few columns consisting only of sealed pages should // not happen unless the API is misused. - if (bufColumn.HasSealedPagesOnly()) + if (!bufColumn.IsEmpty() && bufColumn.HasSealedPagesOnly()) throw RException(R__FAIL("only a few columns have all pages sealed")); // Slow path: if the buffered column contains both sealed and unsealed pages, commit them one by one. @@ -124,7 +178,7 @@ ROOT::Experimental::Detail::RPageSinkBuf::CommitClusterImpl(ROOT::Experimental:: auto drained = bufColumn.DrainBufferedPages(); for (auto &bufPage : std::get>(drained)) { if (bufPage.IsSealed()) { - fInnerSink->CommitSealedPage(bufColumn.GetHandle().fId, *bufPage.fSealedPage); + fInnerSink->CommitSealedPage(bufColumn.GetHandle().fPhysicalId, *bufPage.fSealedPage); } else { fInnerSink->CommitPage(bufColumn.GetHandle(), bufPage.fPage); } diff --git a/tree/ntuple/v7/src/RPageSourceFriends.cxx b/tree/ntuple/v7/src/RPageSourceFriends.cxx index 945a5f97e8051..0758dd0b1b6df 100644 --- a/tree/ntuple/v7/src/RPageSourceFriends.cxx +++ b/tree/ntuple/v7/src/RPageSourceFriends.cxx @@ -53,8 +53,9 @@ void ROOT::Experimental::Detail::RPageSourceFriends::AddVirtualField(const RNTup AddVirtualField(originDesc, originIdx, f, virtualFieldId, f.GetFieldName()); for (const auto &c: originDesc.GetColumnIterable(originField)) { - fBuilder.AddColumn(fNextId, virtualFieldId, c.GetModel(), c.GetIndex()); - fIdBiMap.Insert({originIdx, c.GetId()}, fNextId); + auto physicalId = c.IsAliasColumn() ? fIdBiMap.GetVirtualId({originIdx, c.GetPhysicalId()}) : fNextId; + fBuilder.AddColumn(fNextId, physicalId, virtualFieldId, c.GetModel(), c.GetIndex()); + fIdBiMap.Insert({originIdx, c.GetLogicalId()}, fNextId); fNextId++; } } @@ -96,7 +97,7 @@ ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFri DescriptorId_t virtualColumnId = fIdBiMap.GetVirtualId({i, originColumnId}); auto pageRange = c.GetPageRange(originColumnId).Clone(); - pageRange.fColumnId = virtualColumnId; + pageRange.fPhysicalColumnId = virtualColumnId; auto firstElementIndex = c.GetColumnRange(originColumnId).fFirstElementIndex; auto compressionSettings = c.GetColumnRange(originColumnId).fCompressionSettings; @@ -135,8 +136,8 @@ ROOT::Experimental::Detail::RPageSourceFriends::AddColumn(DescriptorId_t fieldId void ROOT::Experimental::Detail::RPageSourceFriends::DropColumn(ColumnHandle_t columnHandle) { RPageSource::DropColumn(columnHandle); - auto originColumnId = fIdBiMap.GetOriginId(columnHandle.fId); - columnHandle.fId = originColumnId.fId; + auto originColumnId = fIdBiMap.GetOriginId(columnHandle.fPhysicalId); + columnHandle.fPhysicalId = originColumnId.fId; fSources[originColumnId.fSourceIdx]->DropColumn(columnHandle); } @@ -145,9 +146,9 @@ ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, NTupleSize_t globalIndex) { - auto virtualColumnId = columnHandle.fId; + auto virtualColumnId = columnHandle.fPhysicalId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); - columnHandle.fId = originColumnId.fId; + columnHandle.fPhysicalId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, globalIndex); @@ -162,12 +163,12 @@ ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) { - auto virtualColumnId = columnHandle.fId; + auto virtualColumnId = columnHandle.fPhysicalId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); - columnHandle.fId = originColumnId.fId; + columnHandle.fPhysicalId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, originClusterIndex); @@ -175,16 +176,16 @@ ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( return page; } - -void ROOT::Experimental::Detail::RPageSourceFriends::LoadSealedPage( - DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) +void ROOT::Experimental::Detail::RPageSourceFriends::LoadSealedPage(DescriptorId_t physicalColumnId, + const RClusterIndex &clusterIndex, + RSealedPage &sealedPage) { - auto originColumnId = fIdBiMap.GetOriginId(columnId); + auto originColumnId = fIdBiMap.GetOriginId(physicalColumnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); - fSources[originColumnId.fSourceIdx]->LoadSealedPage(columnId, originClusterIndex, sealedPage); + fSources[originColumnId.fSourceIdx]->LoadSealedPage(physicalColumnId, originClusterIndex, sealedPage); } diff --git a/tree/ntuple/v7/src/RPageStorage.cxx b/tree/ntuple/v7/src/RPageStorage.cxx index ef9ece7ca6199..529943fa3f2ac 100644 --- a/tree/ntuple/v7/src/RPageStorage.cxx +++ b/tree/ntuple/v7/src/RPageStorage.cxx @@ -38,13 +38,43 @@ ROOT::Experimental::Detail::RPageStorage::RPageStorage(std::string_view name) : { } -ROOT::Experimental::Detail::RPageStorage::~RPageStorage() +ROOT::Experimental::Detail::RPageStorage::~RPageStorage() {} + +//------------------------------------------------------------------------------ + +void ROOT::Experimental::Detail::RPageSource::RActivePhysicalColumns::Insert(DescriptorId_t physicalColumnID) { + for (unsigned i = 0; i < fIDs.size(); ++i) { + if (fIDs[i] == physicalColumnID) { + fRefCounters[i]++; + return; + } + } + fIDs.emplace_back(physicalColumnID); + fRefCounters.emplace_back(1); } +void ROOT::Experimental::Detail::RPageSource::RActivePhysicalColumns::Erase(DescriptorId_t physicalColumnID) +{ + for (unsigned i = 0; i < fIDs.size(); ++i) { + if (fIDs[i] == physicalColumnID) { + if (--fRefCounters[i] == 0) { + fIDs.erase(fIDs.begin() + i); + fRefCounters.erase(fRefCounters.begin() + i); + } + return; + } + } +} -//------------------------------------------------------------------------------ - +ROOT::Experimental::Detail::RCluster::ColumnSet_t +ROOT::Experimental::Detail::RPageSource::RActivePhysicalColumns::ToColumnSet() const +{ + RCluster::ColumnSet_t result; + for (const auto &id : fIDs) + result.insert(id); + return result; +} ROOT::Experimental::Detail::RPageSource::RPageSource(std::string_view name, const RNTupleReadOptions &options) : RPageStorage(name), fMetrics(""), fOptions(options) @@ -78,15 +108,15 @@ ROOT::Experimental::Detail::RPageStorage::ColumnHandle_t ROOT::Experimental::Detail::RPageSource::AddColumn(DescriptorId_t fieldId, const RColumn &column) { R__ASSERT(fieldId != kInvalidDescriptorId); - auto columnId = GetSharedDescriptorGuard()->FindColumnId(fieldId, column.GetIndex()); - R__ASSERT(columnId != kInvalidDescriptorId); - fActiveColumns.emplace(columnId); - return ColumnHandle_t{columnId, &column}; + auto physicalId = GetSharedDescriptorGuard()->FindPhysicalColumnId(fieldId, column.GetIndex()); + R__ASSERT(physicalId != kInvalidDescriptorId); + fActivePhysicalColumns.Insert(physicalId); + return ColumnHandle_t{physicalId, &column}; } void ROOT::Experimental::Detail::RPageSource::DropColumn(ColumnHandle_t columnHandle) { - fActiveColumns.erase(columnHandle.fId); + fActivePhysicalColumns.Erase(columnHandle.fPhysicalId); } ROOT::Experimental::NTupleSize_t ROOT::Experimental::Detail::RPageSource::GetNEntries() @@ -96,13 +126,13 @@ ROOT::Experimental::NTupleSize_t ROOT::Experimental::Detail::RPageSource::GetNEn ROOT::Experimental::NTupleSize_t ROOT::Experimental::Detail::RPageSource::GetNElements(ColumnHandle_t columnHandle) { - return GetSharedDescriptorGuard()->GetNElements(columnHandle.fId); + return GetSharedDescriptorGuard()->GetNElements(columnHandle.fPhysicalId); } ROOT::Experimental::ColumnId_t ROOT::Experimental::Detail::RPageSource::GetColumnId(ColumnHandle_t columnHandle) { // TODO(jblomer) distinguish trees - return columnHandle.fId; + return columnHandle.fPhysicalId; } void ROOT::Experimental::Detail::RPageSource::UnzipCluster(RCluster *cluster) @@ -111,32 +141,62 @@ void ROOT::Experimental::Detail::RPageSource::UnzipCluster(RCluster *cluster) UnzipClusterImpl(cluster); } - -std::unique_ptr ROOT::Experimental::Detail::RPageSource::UnsealPage( - const RSealedPage &sealedPage, const RColumnElementBase &element) +ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSource::UnsealPage(const RSealedPage &sealedPage, + const RColumnElementBase &element, + DescriptorId_t physicalColumnId) { - const auto bytesPacked = element.GetPackedSize(sealedPage.fNElements); - const auto pageSize = element.GetSize() * sealedPage.fNElements; + // Unsealing a page zero is a no-op. `RPageRange::ExtendToFitColumnRange()` guarantees that the page zero buffer is + // large enough to hold `sealedPage.fNElements` + if (sealedPage.fBuffer == RPage::GetPageZeroBuffer()) { + auto page = RPage::MakePageZero(physicalColumnId, element.GetSize()); + page.GrowUnchecked(sealedPage.fNElements); + return page; + } - // TODO(jblomer): We might be able to do better memory handling for unsealing pages than a new malloc for every - // new page. - auto pageBuffer = std::make_unique(bytesPacked); + const auto bytesPacked = element.GetPackedSize(sealedPage.fNElements); + using Allocator_t = RPageAllocatorHeap; + auto page = Allocator_t::NewPage(physicalColumnId, element.GetSize(), sealedPage.fNElements); if (sealedPage.fSize != bytesPacked) { - fDecompressor->Unzip(sealedPage.fBuffer, sealedPage.fSize, bytesPacked, pageBuffer.get()); + fDecompressor->Unzip(sealedPage.fBuffer, sealedPage.fSize, bytesPacked, page.GetBuffer()); } else { // We cannot simply map the sealed page as we don't know its life time. Specialized page sources // may decide to implement to not use UnsealPage but to custom mapping / decompression code. // Note that usually pages are compressed. - memcpy(pageBuffer.get(), sealedPage.fBuffer, bytesPacked); + memcpy(page.GetBuffer(), sealedPage.fBuffer, bytesPacked); } if (!element.IsMappable()) { - auto unpackedBuffer = new unsigned char[pageSize]; - element.Unpack(unpackedBuffer, pageBuffer.get(), sealedPage.fNElements); - pageBuffer = std::unique_ptr(unpackedBuffer); + auto tmp = Allocator_t::NewPage(physicalColumnId, element.GetSize(), sealedPage.fNElements); + element.Unpack(tmp.GetBuffer(), page.GetBuffer(), sealedPage.fNElements); + Allocator_t::DeletePage(page); + page = tmp; } - return pageBuffer; + page.GrowUnchecked(sealedPage.fNElements); + return page; +} + +void ROOT::Experimental::Detail::RPageSource::PrepareLoadCluster( + const RCluster::RKey &clusterKey, ROnDiskPageMap &pageZeroMap, + std::function perPageFunc) +{ + auto descriptorGuard = GetSharedDescriptorGuard(); + const auto &clusterDesc = descriptorGuard->GetClusterDescriptor(clusterKey.fClusterId); + + for (auto physicalColumnId : clusterKey.fPhysicalColumnSet) { + const auto &pageRange = clusterDesc.GetPageRange(physicalColumnId); + NTupleSize_t pageNo = 0; + for (const auto &pageInfo : pageRange.fPageInfos) { + if (pageInfo.fLocator.fType == RNTupleLocator::kTypePageZero) { + pageZeroMap.Register( + ROnDiskPage::Key{physicalColumnId, pageNo}, + ROnDiskPage(const_cast(RPage::GetPageZeroBuffer()), pageInfo.fLocator.fBytesOnStorage)); + } else { + perPageFunc(physicalColumnId, pageNo, pageInfo); + } + ++pageNo; + } + } } void ROOT::Experimental::Detail::RPageSource::EnableDefaultMetrics(const std::string &prefix) @@ -271,70 +331,115 @@ std::unique_ptr ROOT::Experimental::Detai ROOT::Experimental::Detail::RPageStorage::ColumnHandle_t ROOT::Experimental::Detail::RPageSink::AddColumn(DescriptorId_t fieldId, const RColumn &column) { - auto columnId = fDescriptorBuilder.GetDescriptor().GetNColumns(); - fDescriptorBuilder.AddColumn(columnId, fieldId, column.GetModel(), column.GetIndex()); + auto columnId = fDescriptorBuilder.GetDescriptor().GetNPhysicalColumns(); + fDescriptorBuilder.AddColumn(columnId, columnId, fieldId, column.GetModel(), column.GetIndex(), + column.GetFirstElementIndex()); return ColumnHandle_t{columnId, &column}; } - -void ROOT::Experimental::Detail::RPageSink::Create(RNTupleModel &model) +void ROOT::Experimental::Detail::RPageSink::UpdateSchema(const RNTupleModelChangeset &changeset, + NTupleSize_t firstEntry) { - fDescriptorBuilder.SetNTuple(fNTupleName, model.GetDescription()); const auto &descriptor = fDescriptorBuilder.GetDescriptor(); - - auto &fieldZero = *model.GetFieldZero(); - fDescriptorBuilder.AddField(RFieldDescriptorBuilder::FromField(fieldZero).FieldId(0).MakeDescriptor().Unwrap()); - fieldZero.SetOnDiskId(0); - for (auto &f : fieldZero) { + auto addField = [&](RFieldBase &f) { + auto fieldId = descriptor.GetNFields(); + fDescriptorBuilder.AddField(RFieldDescriptorBuilder::FromField(f).FieldId(fieldId).MakeDescriptor().Unwrap()); + fDescriptorBuilder.AddFieldLink(f.GetParent()->GetOnDiskId(), fieldId); + f.SetOnDiskId(fieldId); + f.ConnectPageSink(*this, firstEntry); // issues in turn one or several calls to `AddColumn()` + }; + auto addProjectedField = [&](RFieldBase &f) { auto fieldId = descriptor.GetNFields(); fDescriptorBuilder.AddField(RFieldDescriptorBuilder::FromField(f).FieldId(fieldId).MakeDescriptor().Unwrap()); fDescriptorBuilder.AddFieldLink(f.GetParent()->GetOnDiskId(), fieldId); f.SetOnDiskId(fieldId); - f.ConnectPageSink(*this); // issues in turn one or several calls to AddColumn() + auto sourceFieldId = changeset.fModel.GetProjectedFields().GetSourceField(&f)->GetOnDiskId(); + for (const auto &source : descriptor.GetColumnIterable(sourceFieldId)) { + auto targetId = descriptor.GetNLogicalColumns(); + fDescriptorBuilder.AddColumn(targetId, source.GetLogicalId(), fieldId, source.GetModel(), source.GetIndex()); + } + }; + + R__ASSERT(firstEntry >= fPrevClusterNEntries); + const auto nColumnsBeforeUpdate = descriptor.GetNPhysicalColumns(); + for (auto f : changeset.fAddedFields) { + addField(*f); + for (auto &descendant : *f) + addField(descendant); + } + for (auto f : changeset.fAddedProjectedFields) { + addProjectedField(*f); + for (auto &descendant : *f) + addProjectedField(descendant); } - auto nColumns = descriptor.GetNColumns(); - for (DescriptorId_t i = 0; i < nColumns; ++i) { + const auto nColumns = descriptor.GetNPhysicalColumns(); + for (DescriptorId_t i = nColumnsBeforeUpdate; i < nColumns; ++i) { RClusterDescriptor::RColumnRange columnRange; - columnRange.fColumnId = i; - columnRange.fFirstElementIndex = 0; + columnRange.fPhysicalColumnId = i; + // We set the first element index in the current cluster to the first element that is part of a materialized page + // (i.e., that is part of a page list). For deferred columns, however, the column range is fixed up as needed by + // `RClusterDescriptorBuilder::AddDeferredColumnRanges()` on read back. + columnRange.fFirstElementIndex = descriptor.GetColumnDescriptor(i).GetFirstElementIndex(); columnRange.fNElements = 0; columnRange.fCompressionSettings = GetWriteOptions().GetCompression(); fOpenColumnRanges.emplace_back(columnRange); RClusterDescriptor::RPageRange pageRange; - pageRange.fColumnId = i; + pageRange.fPhysicalColumnId = i; fOpenPageRanges.emplace_back(std::move(pageRange)); } + // Mapping of memory to on-disk column IDs usually happens during serialization of the ntuple header. If the + // header was already serialized, this has to be done manually as it is required for page list serialization. + if (fSerializationContext.GetHeaderSize() > 0) + fSerializationContext.MapSchema(descriptor, /*forHeaderExtension=*/true); +} + +void ROOT::Experimental::Detail::RPageSink::Create(RNTupleModel &model) +{ + fDescriptorBuilder.SetNTuple(fNTupleName, model.GetDescription()); + const auto &descriptor = fDescriptorBuilder.GetDescriptor(); + + auto &fieldZero = *model.GetFieldZero(); + fDescriptorBuilder.AddField(RFieldDescriptorBuilder::FromField(fieldZero).FieldId(0).MakeDescriptor().Unwrap()); + fieldZero.SetOnDiskId(0); + model.GetProjectedFields().GetFieldZero()->SetOnDiskId(0); + + RNTupleModelChangeset initialChangeset{model}; + for (auto f : fieldZero.GetSubFields()) + initialChangeset.fAddedFields.emplace_back(f); + for (auto f : model.GetProjectedFields().GetFieldZero()->GetSubFields()) + initialChangeset.fAddedProjectedFields.emplace_back(f); + UpdateSchema(initialChangeset, 0U); + fSerializationContext = Internal::RNTupleSerializer::SerializeHeaderV1(nullptr, descriptor); auto buffer = std::make_unique(fSerializationContext.GetHeaderSize()); fSerializationContext = Internal::RNTupleSerializer::SerializeHeaderV1(buffer.get(), descriptor); - CreateImpl(model, buffer.get(), fSerializationContext.GetHeaderSize()); -} + fDescriptorBuilder.BeginHeaderExtension(); +} void ROOT::Experimental::Detail::RPageSink::CommitPage(ColumnHandle_t columnHandle, const RPage &page) { - fOpenColumnRanges.at(columnHandle.fId).fNElements += page.GetNElements(); + fOpenColumnRanges.at(columnHandle.fPhysicalId).fNElements += page.GetNElements(); RClusterDescriptor::RPageRange::RPageInfo pageInfo; pageInfo.fNElements = page.GetNElements(); pageInfo.fLocator = CommitPageImpl(columnHandle, page); - fOpenPageRanges.at(columnHandle.fId).fPageInfos.emplace_back(pageInfo); + fOpenPageRanges.at(columnHandle.fPhysicalId).fPageInfos.emplace_back(pageInfo); } - void ROOT::Experimental::Detail::RPageSink::CommitSealedPage( - ROOT::Experimental::DescriptorId_t columnId, + ROOT::Experimental::DescriptorId_t physicalColumnId, const ROOT::Experimental::Detail::RPageStorage::RSealedPage &sealedPage) { - fOpenColumnRanges.at(columnId).fNElements += sealedPage.fNElements; + fOpenColumnRanges.at(physicalColumnId).fNElements += sealedPage.fNElements; RClusterDescriptor::RPageRange::RPageInfo pageInfo; pageInfo.fNElements = sealedPage.fNElements; - pageInfo.fLocator = CommitSealedPageImpl(columnId, sealedPage); - fOpenPageRanges.at(columnId).fPageInfos.emplace_back(pageInfo); + pageInfo.fLocator = CommitSealedPageImpl(physicalColumnId, sealedPage); + fOpenPageRanges.at(physicalColumnId).fPageInfos.emplace_back(pageInfo); } std::vector @@ -343,7 +448,7 @@ ROOT::Experimental::Detail::RPageSink::CommitSealedPageVImpl(std::span locators; for (auto &range : ranges) { for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt) - locators.push_back(CommitSealedPageImpl(range.fColumnId, *sealedPageIt)); + locators.push_back(CommitSealedPageImpl(range.fPhysicalColumnId, *sealedPageIt)); } return locators; } @@ -355,12 +460,12 @@ void ROOT::Experimental::Detail::RPageSink::CommitSealedPageV(std::spanfNElements; + fOpenColumnRanges.at(range.fPhysicalColumnId).fNElements += sealedPageIt->fNElements; RClusterDescriptor::RPageRange::RPageInfo pageInfo; pageInfo.fNElements = sealedPageIt->fNElements; pageInfo.fLocator = locators[i++]; - fOpenPageRanges.at(range.fColumnId).fPageInfos.emplace_back(pageInfo); + fOpenPageRanges.at(range.fPhysicalColumnId).fPageInfos.emplace_back(pageInfo); } } } @@ -375,7 +480,7 @@ std::uint64_t ROOT::Experimental::Detail::RPageSink::CommitCluster(ROOT::Experim nEntriesInCluster); for (unsigned int i = 0; i < fOpenColumnRanges.size(); ++i) { RClusterDescriptor::RPageRange fullRange; - fullRange.fColumnId = i; + fullRange.fPhysicalColumnId = i; std::swap(fullRange, fOpenPageRanges[i]); clusterBuilder.CommitColumnRange(i, fOpenColumnRanges[i].fFirstElementIndex, fOpenColumnRanges[i].fCompressionSettings, fullRange); @@ -453,7 +558,7 @@ ROOT::Experimental::Detail::RPageSink::SealPage(const RPage &page, R__ASSERT(isAdoptedBuffer); - return RSealedPage{pageBuf, zippedBytes, page.GetNElements()}; + return RSealedPage{pageBuf, static_cast(zippedBytes), page.GetNElements()}; } ROOT::Experimental::Detail::RPageStorage::RSealedPage diff --git a/tree/ntuple/v7/src/RPageStorageDaos.cxx b/tree/ntuple/v7/src/RPageStorageDaos.cxx index a3841a83633a2..a82c2a143ba00 100644 --- a/tree/ntuple/v7/src/RPageStorageDaos.cxx +++ b/tree/ntuple/v7/src/RPageStorageDaos.cxx @@ -34,10 +34,10 @@ #include #include #include -#include #include #include #include +#include namespace { using AttributeKey_t = ROOT::Experimental::Detail::RDaosContainer::AttributeKey_t; @@ -104,6 +104,22 @@ RDaosURI ParseDaosURI(std::string_view uri) return {m[1], m[2]}; } +/// \brief Unpacks a 64-bit RNTuple page locator address for object stores into a pair of 32-bit values: +/// the attribute key under which the cage is stored and the offset within that cage to access the page. +std::pair DecodeDaosPagePosition(const ROOT::Experimental::RNTupleLocatorObject64 &address) +{ + auto position = static_cast(address.fLocation & 0xFFFFFFFF); + auto offset = static_cast(address.fLocation >> 32); + return {position, offset}; +} + +/// \brief Packs an attribute key together with an offset within its contents into a single 64-bit address. +/// The offset is kept in the MSb half and defaults to zero, which is the case when caging is disabled. +ROOT::Experimental::RNTupleLocatorObject64 EncodeDaosPagePosition(uint64_t position, uint64_t offset = 0) +{ + uint64_t address = (position & 0xFFFFFFFF) | (offset << 32); + return ROOT::Experimental::RNTupleLocatorObject64{address}; +} } // namespace //////////////////////////////////////////////////////////////////////////////// @@ -230,8 +246,13 @@ void ROOT::Experimental::Detail::RPageSinkDaos::CreateImpl(const RNTupleModel & if (oclass.IsUnknown()) throw ROOT::Experimental::RException(R__FAIL("Unknown object class " + fNTupleAnchor.fObjClass)); + size_t cageSz = opts ? opts->GetMaxCageSize() : RNTupleWriteOptionsDaos().GetMaxCageSize(); + size_t pageSz = opts ? opts->GetApproxUnzippedPageSize() : RNTupleWriteOptionsDaos().GetApproxUnzippedPageSize(); + fCageSizeLimit = std::max(cageSz, pageSz); + auto args = ParseDaosURI(fURI); auto pool = std::make_shared(args.fPoolLabel); + fDaosContainer = std::make_unique(pool, args.fContainerLabel, /*create =*/true); fDaosContainer->SetDefaultObjectClass(oclass); @@ -256,11 +277,11 @@ ROOT::Experimental::Detail::RPageSinkDaos::CommitPageImpl(ColumnHandle_t columnH } fCounters->fSzZip.Add(page.GetNBytes()); - return CommitSealedPageImpl(columnHandle.fId, sealedPage); + return CommitSealedPageImpl(columnHandle.fPhysicalId, sealedPage); } ROOT::Experimental::RNTupleLocator -ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageImpl(DescriptorId_t columnId, +ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageImpl(DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) { auto offsetData = fPageId.fetch_add(1); @@ -268,13 +289,14 @@ ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageImpl(DescriptorId_t c { RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite); - RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, columnId, offsetData); + RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, physicalColumnId, offsetData); fDaosContainer->WriteSingleAkey(sealedPage.fBuffer, sealedPage.fSize, daosKey.fOid, daosKey.fDkey, daosKey.fAkey); } RNTupleLocator result; - result.fPosition = offsetData; + result.fPosition = EncodeDaosPagePosition(offsetData); result.fBytesOnStorage = sealedPage.fSize; + result.fType = RNTupleLocator::kTypeDAOS; fCounters->fNPageCommitted.Inc(); fCounters->fSzWritePayload.Add(sealedPage.fSize); fNBytesCurrentCluster += sealedPage.fSize; @@ -286,37 +308,59 @@ ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageVImpl(std::span locators; - size_t nPages = - std::accumulate(ranges.begin(), ranges.end(), 0, [](size_t c, const RPageStorage::RSealedPageGroup &r) { + int64_t nPages = + std::accumulate(ranges.begin(), ranges.end(), 0, [](int64_t c, const RPageStorage::RSealedPageGroup &r) { return c + std::distance(r.fFirst, r.fLast); }); locators.reserve(nPages); + const uint32_t maxCageSz = fCageSizeLimit; + const bool useCaging = fCageSizeLimit > 0; + const std::uint8_t locatorFlags = useCaging ? Internal::EDaosLocatorFlags::kCagedPage : 0; + DescriptorId_t clusterId = fDescriptorBuilder.GetDescriptor().GetNClusters(); - std::size_t szPayload = 0; + int64_t payloadSz = 0; + std::size_t positionOffset; + uint32_t positionIndex; /// Aggregate batch of requests by object ID and distribution key, determined by the ntuple-DAOS mapping for (auto &range : ranges) { + positionOffset = 0; + /// Under caging, the atomic page counter is fetch-incremented for every column range to get the position of its + /// first cage and indicate the next one, also ensuring subsequent pages of different columns do not end up caged + /// together. This increment is not necessary in the absence of caging, as each page is trivially caged. + positionIndex = useCaging ? fPageId.fetch_add(1) : fPageId.load(); + for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt) { + const RPageStorage::RSealedPage &s = *sealedPageIt; + + if (positionOffset + s.fSize > maxCageSz) { + positionOffset = 0; + positionIndex = fPageId.fetch_add(1); + } + d_iov_t pageIov; d_iov_set(&pageIov, const_cast(s.fBuffer), s.fSize); - auto offsetData = fPageId.fetch_add(1); - RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, range.fColumnId, offsetData); + RDaosKey daosKey = + GetPageDaosKey(fNTupleIndex, clusterId, range.fPhysicalColumnId, positionIndex); auto odPair = RDaosContainer::ROidDkeyPair{daosKey.fOid, daosKey.fDkey}; auto [it, ret] = writeRequests.emplace(odPair, RDaosContainer::RWOperation(odPair)); - it->second.insert(daosKey.fAkey, pageIov); + it->second.Insert(daosKey.fAkey, pageIov); RNTupleLocator locator; - locator.fPosition = offsetData; + locator.fPosition = EncodeDaosPagePosition(positionIndex, positionOffset); locator.fBytesOnStorage = s.fSize; + locator.fType = RNTupleLocator::kTypeDAOS; + locator.fReserved = locatorFlags; locators.push_back(locator); - szPayload += s.fSize; + positionOffset += s.fSize; + payloadSz += s.fSize; } } - fNBytesCurrentCluster += szPayload; + fNBytesCurrentCluster += payloadSz; { RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite); @@ -325,7 +369,7 @@ ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageVImpl(std::spanfNPageCommitted.Add(nPages); - fCounters->fSzWritePayload.Add(szPayload); + fCounters->fSzWritePayload.Add(payloadSz); return locators; } @@ -350,9 +394,10 @@ ROOT::Experimental::Detail::RPageSinkDaos::CommitClusterGroupImpl(unsigned char daos_obj_id_t{kOidLowPageList, static_cast(fNTupleIndex)}, kDistributionKeyDefault, offsetData, kCidMetadata); RNTupleLocator result; - result.fPosition = offsetData; + result.fPosition = RNTupleLocatorObject64{offsetData}; result.fBytesOnStorage = szPageListZip; - fCounters->fSzWritePayload.Add(szPageListZip); + result.fType = RNTupleLocator::kTypeDAOS; + fCounters->fSzWritePayload.Add(static_cast(szPageListZip)); return result; } @@ -399,7 +444,7 @@ ROOT::Experimental::Detail::RPageSinkDaos::ReservePage(ColumnHandle_t columnHand if (nElements == 0) throw RException(R__FAIL("invalid call: request empty page")); auto elementSize = columnHandle.fColumn->GetElement()->GetSize(); - return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements); + return fPageAllocator->NewPage(columnHandle.fPhysicalId, elementSize, nElements); } void ROOT::Experimental::Detail::RPageSinkDaos::ReleasePage(RPage &page) @@ -409,28 +454,11 @@ void ROOT::Experimental::Detail::RPageSinkDaos::ReleasePage(RPage &page) //////////////////////////////////////////////////////////////////////////////// -ROOT::Experimental::Detail::RPage -ROOT::Experimental::Detail::RPageAllocatorDaos::NewPage(ColumnId_t columnId, void *mem, std::size_t elementSize, - std::size_t nElements) -{ - RPage newPage(columnId, mem, elementSize, nElements); - newPage.GrowUnchecked(nElements); - return newPage; -} - -void ROOT::Experimental::Detail::RPageAllocatorDaos::DeletePage(const RPage &page) -{ - if (page.IsNull()) - return; - delete[] reinterpret_cast(page.GetBuffer()); -} - -//////////////////////////////////////////////////////////////////////////////// - ROOT::Experimental::Detail::RPageSourceDaos::RPageSourceDaos(std::string_view ntupleName, std::string_view uri, const RNTupleReadOptions &options) - : RPageSource(ntupleName, options), fPageAllocator(std::make_unique()), - fPagePool(std::make_shared()), fURI(uri), + : RPageSource(ntupleName, options), + fPagePool(std::make_shared()), + fURI(uri), fClusterPool(std::make_unique(*this, options.GetClusterBunchSize())) { fDecompressor = std::make_unique(); @@ -467,9 +495,9 @@ ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceDao for (const auto &cgDesc : ntplDesc.GetClusterGroupIterable()) { buffer = std::make_unique(cgDesc.GetPageListLength()); zipBuffer = std::make_unique(cgDesc.GetPageListLocator().fBytesOnStorage); - fDaosContainer->ReadSingleAkey(zipBuffer.get(), cgDesc.GetPageListLocator().fBytesOnStorage, oidPageList, - kDistributionKeyDefault, cgDesc.GetPageListLocator().GetPosition(), - kCidMetadata); + fDaosContainer->ReadSingleAkey( + zipBuffer.get(), cgDesc.GetPageListLocator().fBytesOnStorage, oidPageList, kDistributionKeyDefault, + cgDesc.GetPageListLocator().GetPosition().fLocation, kCidMetadata); fDecompressor->Unzip(zipBuffer.get(), cgDesc.GetPageListLocator().fBytesOnStorage, cgDesc.GetPageListLength(), buffer.get()); @@ -488,7 +516,7 @@ std::string ROOT::Experimental::Detail::RPageSourceDaos::GetObjectClass() const return fDaosContainer->GetDefaultObjectClass().ToString(); } -void ROOT::Experimental::Detail::RPageSourceDaos::LoadSealedPage(DescriptorId_t columnId, +void ROOT::Experimental::Detail::RPageSourceDaos::LoadSealedPage(DescriptorId_t physicalColumnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) { @@ -498,17 +526,26 @@ void ROOT::Experimental::Detail::RPageSourceDaos::LoadSealedPage(DescriptorId_t { auto descriptorGuard = GetSharedDescriptorGuard(); const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId); - pageInfo = clusterDescriptor.GetPageRange(columnId).Find(clusterIndex.GetIndex()); + pageInfo = clusterDescriptor.GetPageRange(physicalColumnId).Find(clusterIndex.GetIndex()); + } + + if (pageInfo.fLocator.fReserved & Internal::EDaosLocatorFlags::kCagedPage) { + throw ROOT::Experimental::RException( + R__FAIL("accessing caged pages is only supported in conjunction with cluster cache")); } const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage; sealedPage.fSize = bytesOnStorage; sealedPage.fNElements = pageInfo.fNElements; - if (sealedPage.fBuffer) { - RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, columnId, - pageInfo.fLocator.GetPosition()); + if (!sealedPage.fBuffer) + return; + if (pageInfo.fLocator.fType != RNTupleLocator::kTypePageZero) { + RDaosKey daosKey = GetPageDaosKey( + fNTupleIndex, clusterId, physicalColumnId, pageInfo.fLocator.GetPosition().fLocation); fDaosContainer->ReadSingleAkey(const_cast(sealedPage.fBuffer), bytesOnStorage, daosKey.fOid, daosKey.fDkey, daosKey.fAkey); + } else { + memcpy(const_cast(sealedPage.fBuffer), RPage::GetPageZeroBuffer(), bytesOnStorage); } } @@ -517,7 +554,7 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(ColumnHandl const RClusterInfo &clusterInfo, ClusterSize_t::ValueType idxInCluster) { - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; const auto clusterId = clusterInfo.fClusterId; const auto &pageInfo = clusterInfo.fPageInfo; @@ -528,10 +565,24 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(ColumnHandl const void *sealedPageBuffer = nullptr; // points either to directReadBuffer or to a read-only page in the cluster std::unique_ptr directReadBuffer; // only used if cluster pool is turned off + if (pageInfo.fLocator.fType == RNTupleLocator::kTypePageZero) { + auto pageZero = RPage::MakePageZero(columnId, elementSize); + pageZero.GrowUnchecked(pageInfo.fNElements); + pageZero.SetWindow(clusterInfo.fColumnOffset + pageInfo.fFirstInPage, + RPage::RClusterInfo(clusterId, clusterInfo.fColumnOffset)); + fPagePool->RegisterPage(pageZero, RPageDeleter([](const RPage &, void *) {}, nullptr)); + return pageZero; + } + if (fOptions.GetClusterCache() == RNTupleReadOptions::EClusterCache::kOff) { - directReadBuffer = std::make_unique(bytesOnStorage); - RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, columnId, - pageInfo.fLocator.GetPosition()); + if (pageInfo.fLocator.fReserved & Internal::EDaosLocatorFlags::kCagedPage) { + throw ROOT::Experimental::RException( + R__FAIL("accessing caged pages is only supported in conjunction with cluster cache")); + } + + directReadBuffer = std::unique_ptr(new unsigned char[bytesOnStorage]); + RDaosKey daosKey = GetPageDaosKey( + fNTupleIndex, clusterId, columnId, pageInfo.fLocator.GetPosition().fLocation); fDaosContainer->ReadSingleAkey(directReadBuffer.get(), bytesOnStorage, daosKey.fOid, daosKey.fDkey, daosKey.fAkey); fCounters->fNPageLoaded.Inc(); @@ -540,7 +591,7 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(ColumnHandl sealedPageBuffer = directReadBuffer.get(); } else { if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId)) - fCurrentCluster = fClusterPool->GetCluster(clusterId, fActiveColumns); + fCurrentCluster = fClusterPool->GetCluster(clusterId, fActivePhysicalColumns.ToColumnSet()); R__ASSERT(fCurrentCluster->ContainsColumn(columnId)); auto cachedPage = fPagePool->GetPage(columnId, RClusterIndex(clusterId, idxInCluster)); @@ -553,19 +604,18 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(ColumnHandl sealedPageBuffer = onDiskPage->GetAddress(); } - std::unique_ptr pageBuffer; + RPage newPage; { RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip); - pageBuffer = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element); + newPage = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element, columnId); fCounters->fSzUnzip.Add(elementSize * pageInfo.fNElements); } - auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), elementSize, pageInfo.fNElements); newPage.SetWindow(clusterInfo.fColumnOffset + pageInfo.fFirstInPage, RPage::RClusterInfo(clusterId, clusterInfo.fColumnOffset)); fPagePool->RegisterPage( newPage, - RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorDaos::DeletePage(page); }, nullptr)); + RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorHeap::DeletePage(page); }, nullptr)); fCounters->fNPagePopulated.Inc(); return newPage; } @@ -573,7 +623,7 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(ColumnHandl ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(ColumnHandle_t columnHandle, NTupleSize_t globalIndex) { - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; auto cachedPage = fPagePool->GetPage(columnId, globalIndex); if (!cachedPage.IsNull()) return cachedPage; @@ -600,7 +650,7 @@ ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(ColumnHandle_t columnH { const auto clusterId = clusterIndex.GetClusterId(); const auto idxInCluster = clusterIndex.GetIndex(); - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; auto cachedPage = fPagePool->GetPage(columnId, clusterIndex); if (!cachedPage.IsNull()) return cachedPage; @@ -632,79 +682,90 @@ std::unique_ptr ROOT::Experimental::Det std::vector> ROOT::Experimental::Detail::RPageSourceDaos::LoadClusters(std::span clusterKeys) { - std::vector> result; - struct RDaosSealedPageLocator { - RDaosSealedPageLocator() = default; - RDaosSealedPageLocator(DescriptorId_t cl, DescriptorId_t co, NTupleSize_t p, std::uint64_t o, std::uint64_t s, - std::size_t b) - : fClusterId(cl), fColumnId(co), fPageNo(p), fObjectId(o), fSize(s), fBufPos(b) - { - } DescriptorId_t fClusterId = 0; DescriptorId_t fColumnId = 0; NTupleSize_t fPageNo = 0; - std::uint64_t fObjectId = 0; + std::uint64_t fPosition = 0; + std::uint64_t fCageOffset = 0; std::uint64_t fSize = 0; - std::size_t fBufPos = 0; }; - std::vector clusterBuffers(clusterKeys.size()); - std::vector> pageMaps(clusterKeys.size()); - RDaosContainer::MultiObjectRWOperation_t readRequests; - - std::size_t szPayload = 0; - unsigned nPages = 0; - - for (unsigned i = 0; i < clusterKeys.size(); ++i) { - const auto &clusterKey = clusterKeys[i]; + // Prepares read requests for a single cluster; `readRequests` is modified by this function. Requests are coalesced + // by OID and distribution key. + // TODO(jalopezg): this may be a private member function; that, however, requires additional changes given that + // `RDaosContainer::MultiObjectRWOperation_t` cannot be forward-declared + auto fnPrepareSingleCluster = [&](const RCluster::RKey &clusterKey, + RDaosContainer::MultiObjectRWOperation_t &readRequests) { auto clusterId = clusterKey.fClusterId; - std::vector onDiskClusterPages; - - unsigned clusterBufSz = 0; - fCounters->fNClusterLoaded.Inc(); - { - auto descriptorGuard = GetSharedDescriptorGuard(); - const auto &clusterDesc = descriptorGuard->GetClusterDescriptor(clusterId); - - // Collect the necessary page meta-data and sum up the total size of the compressed and packed pages - for (auto columnId : clusterKey.fColumnSet) { - const auto &pageRange = clusterDesc.GetPageRange(columnId); - NTupleSize_t columnPageCount = 0; - for (const auto &pageInfo : pageRange.fPageInfos) { - const auto &pageLocator = pageInfo.fLocator; - onDiskClusterPages.push_back(RDaosSealedPageLocator(clusterId, columnId, columnPageCount, - pageLocator.GetPosition(), - pageLocator.fBytesOnStorage, clusterBufSz)); - ++columnPageCount; - clusterBufSz += pageLocator.fBytesOnStorage; - } - nPages += columnPageCount; + // Group page locators by their position in the object store; with caging enabled, this facilitates the + // processing of cages' requests together into a single IOV to be populated. + std::unordered_map> onDiskPages; + + unsigned clusterBufSz = 0, nPages = 0; + auto pageZeroMap = std::make_unique(); + PrepareLoadCluster(clusterKey, *pageZeroMap, + [&](DescriptorId_t physicalColumnId, NTupleSize_t pageNo, + const RClusterDescriptor::RPageRange::RPageInfo &pageInfo) { + const auto &pageLocator = pageInfo.fLocator; + uint32_t position, offset; + std::tie(position, offset) = + DecodeDaosPagePosition(pageLocator.GetPosition()); + auto [itLoc, _] = onDiskPages.emplace(position, std::vector()); + + itLoc->second.push_back( + {clusterId, physicalColumnId, pageNo, position, offset, pageLocator.fBytesOnStorage}); + ++nPages; + clusterBufSz += pageLocator.fBytesOnStorage; + }); + + auto clusterBuffer = new unsigned char[clusterBufSz]; + auto pageMap = std::make_unique(std::unique_ptr(clusterBuffer)); + + auto cageBuffer = clusterBuffer; + // Fill the cluster page map and the read requests for the RDaosContainer::ReadV() call + for (auto &[cageIndex, pageVec] : onDiskPages) { + auto columnId = pageVec[0].fColumnId; // All pages in a cage belong to the same column + std::size_t cageSz = 0; + + for (auto &s : pageVec) { + assert(columnId == s.fColumnId); + assert(cageIndex == s.fPosition); + // Register the on disk pages in a page map + ROnDiskPage::Key key(s.fColumnId, s.fPageNo); + pageMap->Register(key, ROnDiskPage(cageBuffer + s.fCageOffset, s.fSize)); + cageSz += s.fSize; } - } - szPayload += clusterBufSz; - - clusterBuffers[i] = new unsigned char[clusterBufSz]; - pageMaps[i] = std::make_unique(std::unique_ptr(clusterBuffers[i])); - - // Fill the cluster page maps and the input dictionary for the RDaosContainer::ReadV() call - for (const auto &s : onDiskClusterPages) { - // Register the on disk pages in a page map - ROnDiskPage::Key key(s.fColumnId, s.fPageNo); - pageMaps[i]->Register(key, ROnDiskPage(clusterBuffers[i] + s.fBufPos, s.fSize)); // Prepare new read request batched up by object ID and distribution key d_iov_t iov; - d_iov_set(&iov, clusterBuffers[i] + s.fBufPos, s.fSize); + d_iov_set(&iov, cageBuffer, cageSz); - RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, s.fClusterId, s.fColumnId, s.fObjectId); + RDaosKey daosKey = GetPageDaosKey(fNTupleIndex, clusterId, columnId, cageIndex); auto odPair = RDaosContainer::ROidDkeyPair{daosKey.fOid, daosKey.fDkey}; - auto [it, ret] = readRequests.emplace(odPair, RDaosContainer::RWOperation(odPair)); - it->second.insert(daosKey.fAkey, iov); + auto [itReq, ret] = readRequests.emplace(odPair, RDaosContainer::RWOperation(odPair)); + itReq->second.Insert(daosKey.fAkey, iov); + + cageBuffer += cageSz; } + fCounters->fNPageLoaded.Add(nPages); + fCounters->fSzReadPayload.Add(clusterBufSz); + + auto cluster = std::make_unique(clusterId); + cluster->Adopt(std::move(pageMap)); + cluster->Adopt(std::move(pageZeroMap)); + for (auto colId : clusterKey.fPhysicalColumnSet) + cluster->SetColumnAvailable(colId); + return cluster; + }; + + fCounters->fNClusterLoaded.Add(clusterKeys.size()); + + std::vector> clusters; + RDaosContainer::MultiObjectRWOperation_t readRequests; + for (auto key : clusterKeys) { + clusters.emplace_back(fnPrepareSingleCluster(key, readRequests)); } - fCounters->fNPageLoaded.Add(nPages); - fCounters->fSzReadPayload.Add(szPayload); { RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead); @@ -712,18 +773,9 @@ ROOT::Experimental::Detail::RPageSourceDaos::LoadClusters(std::spanfNReadV.Inc(); - fCounters->fNRead.Add(nPages); - - // Assign each cluster its page map - for (unsigned i = 0; i < clusterKeys.size(); ++i) { - auto cluster = std::make_unique(clusterKeys[i].fClusterId); - cluster->Adopt(std::move(pageMaps[i])); - for (auto colId : clusterKeys[i].fColumnSet) - cluster->SetColumnAvailable(colId); + fCounters->fNRead.Add(readRequests.size()); - result.emplace_back(std::move(cluster)); - } - return result; + return clusters; } void ROOT::Experimental::Detail::RPageSourceDaos::UnzipClusterImpl(RCluster *cluster) @@ -737,7 +789,7 @@ void ROOT::Experimental::Detail::RPageSourceDaos::UnzipClusterImpl(RCluster *clu std::vector> allElements; - const auto &columnsInCluster = cluster->GetAvailColumns(); + const auto &columnsInCluster = cluster->GetAvailPhysicalColumns(); for (const auto columnId : columnsInCluster) { const auto &columnDesc = descriptorGuard->GetColumnDescriptor(columnId); @@ -754,14 +806,13 @@ void ROOT::Experimental::Detail::RPageSourceDaos::UnzipClusterImpl(RCluster *clu auto taskFunc = [this, columnId, clusterId, firstInPage, onDiskPage, element = allElements.back().get(), nElements = pi.fNElements, indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex]() { - auto pageBuffer = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element); + auto newPage = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element, columnId); fCounters->fSzUnzip.Add(element->GetSize() * nElements); - auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), element->GetSize(), nElements); newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset)); fPagePool->PreloadPage( newPage, - RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorDaos::DeletePage(page); }, + RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorHeap::DeletePage(page); }, nullptr)); }; diff --git a/tree/ntuple/v7/src/RPageStorageFile.cxx b/tree/ntuple/v7/src/RPageStorageFile.cxx index fc2962beaa8e0..60718d89286a9 100644 --- a/tree/ntuple/v7/src/RPageStorageFile.cxx +++ b/tree/ntuple/v7/src/RPageStorageFile.cxx @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -129,13 +130,12 @@ ROOT::Experimental::Detail::RPageSinkFile::CommitPageImpl(ColumnHandle_t columnH return WriteSealedPage(sealedPage, element->GetPackedSize(page.GetNElements())); } - ROOT::Experimental::RNTupleLocator -ROOT::Experimental::Detail::RPageSinkFile::CommitSealedPageImpl( - DescriptorId_t columnId, const RPageStorage::RSealedPage &sealedPage) +ROOT::Experimental::Detail::RPageSinkFile::CommitSealedPageImpl(DescriptorId_t physicalColumnId, + const RPageStorage::RSealedPage &sealedPage) { const auto bitsOnStorage = RColumnElementBase::GetBitsOnStorage( - fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(columnId).GetModel().GetType()); + fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(physicalColumnId).GetModel().GetType()); const auto bytesPacked = (bitsOnStorage * sealedPage.fNElements + 7) / 8; return WriteSealedPage(sealedPage, bytesPacked); @@ -179,7 +179,7 @@ ROOT::Experimental::Detail::RPageSinkFile::ReservePage(ColumnHandle_t columnHand if (nElements == 0) throw RException(R__FAIL("invalid call: request empty page")); auto elementSize = columnHandle.fColumn->GetElement()->GetSize(); - return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements); + return fPageAllocator->NewPage(columnHandle.fPhysicalId, elementSize, nElements); } void ROOT::Experimental::Detail::RPageSinkFile::ReleasePage(RPage &page) @@ -190,32 +190,11 @@ void ROOT::Experimental::Detail::RPageSinkFile::ReleasePage(RPage &page) //////////////////////////////////////////////////////////////////////////////// - -ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorFile::NewPage( - ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements) -{ - RPage newPage(columnId, mem, elementSize, nElements); - newPage.GrowUnchecked(nElements); - return newPage; -} - -void ROOT::Experimental::Detail::RPageAllocatorFile::DeletePage(const RPage& page) -{ - if (page.IsNull()) - return; - delete[] reinterpret_cast(page.GetBuffer()); -} - - -//////////////////////////////////////////////////////////////////////////////// - - ROOT::Experimental::Detail::RPageSourceFile::RPageSourceFile(std::string_view ntupleName, - const RNTupleReadOptions &options) - : RPageSource(ntupleName, options) - , fPageAllocator(std::make_unique()) - , fPagePool(std::make_shared()) - , fClusterPool(std::make_unique(*this, options.GetClusterBunchSize())) + const RNTupleReadOptions &options) + : RPageSource(ntupleName, options), + fPagePool(std::make_shared()), + fClusterPool(std::make_unique(*this, options.GetClusterBunchSize())) { fDecompressor = std::make_unique(); EnableDefaultMetrics("RPageSourceFile"); @@ -283,16 +262,16 @@ ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFil auto clusters = RClusterGroupDescriptorBuilder::GetClusterSummaries(ntplDesc, cgDesc.GetId()); Internal::RNTupleSerializer::DeserializePageListV1(buffer.get(), cgDesc.GetPageListLength(), clusters); for (std::size_t i = 0; i < clusters.size(); ++i) { - ntplDesc.AddClusterDetails(clusters[i].MoveDescriptor().Unwrap()); + ntplDesc.AddClusterDetails(clusters[i].AddDeferredColumnRanges(ntplDesc).MoveDescriptor().Unwrap()); } } return ntplDesc; } - -void ROOT::Experimental::Detail::RPageSourceFile::LoadSealedPage( - DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) +void ROOT::Experimental::Detail::RPageSourceFile::LoadSealedPage(DescriptorId_t physicalColumnId, + const RClusterIndex &clusterIndex, + RSealedPage &sealedPage) { const auto clusterId = clusterIndex.GetClusterId(); @@ -300,15 +279,20 @@ void ROOT::Experimental::Detail::RPageSourceFile::LoadSealedPage( { auto descriptorGuard = GetSharedDescriptorGuard(); const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId); - pageInfo = clusterDescriptor.GetPageRange(columnId).Find(clusterIndex.GetIndex()); + pageInfo = clusterDescriptor.GetPageRange(physicalColumnId).Find(clusterIndex.GetIndex()); } const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage; sealedPage.fSize = bytesOnStorage; sealedPage.fNElements = pageInfo.fNElements; - if (sealedPage.fBuffer) + if (!sealedPage.fBuffer) + return; + if (pageInfo.fLocator.fType != RNTupleLocator::kTypePageZero) { fReader.ReadBuffer(const_cast(sealedPage.fBuffer), bytesOnStorage, pageInfo.fLocator.GetPosition()); + } else { + memcpy(const_cast(sealedPage.fBuffer), RPage::GetPageZeroBuffer(), bytesOnStorage); + } } ROOT::Experimental::Detail::RPage @@ -316,7 +300,7 @@ ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(ColumnHandl const RClusterInfo &clusterInfo, ClusterSize_t::ValueType idxInCluster) { - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; const auto clusterId = clusterInfo.fClusterId; const auto pageInfo = clusterInfo.fPageInfo; @@ -327,8 +311,17 @@ ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(ColumnHandl const void *sealedPageBuffer = nullptr; // points either to directReadBuffer or to a read-only page in the cluster std::unique_ptr directReadBuffer; // only used if cluster pool is turned off + if (pageInfo.fLocator.fType == RNTupleLocator::kTypePageZero) { + auto pageZero = RPage::MakePageZero(columnId, elementSize); + pageZero.GrowUnchecked(pageInfo.fNElements); + pageZero.SetWindow(clusterInfo.fColumnOffset + pageInfo.fFirstInPage, + RPage::RClusterInfo(clusterId, clusterInfo.fColumnOffset)); + fPagePool->RegisterPage(pageZero, RPageDeleter([](const RPage &, void *) {}, nullptr)); + return pageZero; + } + if (fOptions.GetClusterCache() == RNTupleReadOptions::EClusterCache::kOff) { - directReadBuffer = std::make_unique(bytesOnStorage); + directReadBuffer = std::unique_ptr(new unsigned char[bytesOnStorage]); fReader.ReadBuffer(directReadBuffer.get(), bytesOnStorage, pageInfo.fLocator.GetPosition()); fCounters->fNPageLoaded.Inc(); fCounters->fNRead.Inc(); @@ -336,7 +329,7 @@ ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(ColumnHandl sealedPageBuffer = directReadBuffer.get(); } else { if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId)) - fCurrentCluster = fClusterPool->GetCluster(clusterId, fActiveColumns); + fCurrentCluster = fClusterPool->GetCluster(clusterId, fActivePhysicalColumns.ToColumnSet()); R__ASSERT(fCurrentCluster->ContainsColumn(columnId)); auto cachedPage = fPagePool->GetPage(columnId, RClusterIndex(clusterId, idxInCluster)); @@ -349,21 +342,18 @@ ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(ColumnHandl sealedPageBuffer = onDiskPage->GetAddress(); } - std::unique_ptr pageBuffer; + RPage newPage; { RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip); - pageBuffer = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element); + newPage = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element, columnId); fCounters->fSzUnzip.Add(elementSize * pageInfo.fNElements); } - auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), elementSize, pageInfo.fNElements); newPage.SetWindow(clusterInfo.fColumnOffset + pageInfo.fFirstInPage, RPage::RClusterInfo(clusterId, clusterInfo.fColumnOffset)); - fPagePool->RegisterPage(newPage, - RPageDeleter([](const RPage &page, void * /*userData*/) - { - RPageAllocatorFile::DeletePage(page); - }, nullptr)); + fPagePool->RegisterPage( + newPage, + RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorHeap::DeletePage(page); }, nullptr)); fCounters->fNPagePopulated.Inc(); return newPage; } @@ -372,7 +362,7 @@ ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(ColumnHandl ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePage( ColumnHandle_t columnHandle, NTupleSize_t globalIndex) { - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; auto cachedPage = fPagePool->GetPage(columnId, globalIndex); if (!cachedPage.IsNull()) return cachedPage; @@ -400,7 +390,7 @@ ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::P { const auto clusterId = clusterIndex.GetClusterId(); const auto idxInCluster = clusterIndex.GetIndex(); - const auto columnId = columnHandle.fId; + const auto columnId = columnHandle.fPhysicalId; auto cachedPage = fPagePool->GetPage(columnId, clusterIndex); if (!cachedPage.IsNull()) return cachedPage; @@ -446,23 +436,15 @@ ROOT::Experimental::Detail::RPageSourceFile::PrepareSingleCluster( std::vector onDiskPages; auto activeSize = 0; - { - auto descriptorGuard = GetSharedDescriptorGuard(); - const auto &clusterDesc = descriptorGuard->GetClusterDescriptor(clusterKey.fClusterId); - - // Collect the page necessary page meta-data and sum up the total size of the compressed and packed pages - for (auto columnId : clusterKey.fColumnSet) { - const auto &pageRange = clusterDesc.GetPageRange(columnId); - NTupleSize_t pageNo = 0; - for (const auto &pageInfo : pageRange.fPageInfos) { - const auto &pageLocator = pageInfo.fLocator; - activeSize += pageLocator.fBytesOnStorage; - onDiskPages.push_back( - {columnId, pageNo, pageLocator.GetPosition(), pageLocator.fBytesOnStorage, 0}); - ++pageNo; - } - } - } + auto pageZeroMap = std::make_unique(); + PrepareLoadCluster(clusterKey, *pageZeroMap, + [&](DescriptorId_t physicalColumnId, NTupleSize_t pageNo, + const RClusterDescriptor::RPageRange::RPageInfo &pageInfo) { + const auto &pageLocator = pageInfo.fLocator; + activeSize += pageLocator.fBytesOnStorage; + onDiskPages.push_back({physicalColumnId, pageNo, pageLocator.GetPosition(), + pageLocator.fBytesOnStorage, 0}); + }); // Linearize the page requests by file offset std::sort(onDiskPages.begin(), onDiskPages.end(), @@ -544,7 +526,8 @@ ROOT::Experimental::Detail::RPageSourceFile::PrepareSingleCluster( auto cluster = std::make_unique(clusterKey.fClusterId); cluster->Adopt(std::move(pageMap)); - for (auto colId : clusterKey.fColumnSet) + cluster->Adopt(std::move(pageZeroMap)); + for (auto colId : clusterKey.fPhysicalColumnSet) cluster->SetColumnAvailable(colId); return cluster; } @@ -584,7 +567,7 @@ void ROOT::Experimental::Detail::RPageSourceFile::UnzipClusterImpl(RCluster *clu std::vector> allElements; - const auto &columnsInCluster = cluster->GetAvailColumns(); + const auto &columnsInCluster = cluster->GetAvailPhysicalColumns(); for (const auto columnId : columnsInCluster) { const auto &columnDesc = descriptorGuard->GetColumnDescriptor(columnId); @@ -598,23 +581,18 @@ void ROOT::Experimental::Detail::RPageSourceFile::UnzipClusterImpl(RCluster *clu auto onDiskPage = cluster->GetOnDiskPage(key); R__ASSERT(onDiskPage && (onDiskPage->GetSize() == pi.fLocator.fBytesOnStorage)); - auto taskFunc = - [this, columnId, clusterId, firstInPage, onDiskPage, - element = allElements.back().get(), - nElements = pi.fNElements, - indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex - ] () { - auto pageBuffer = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element); - fCounters->fSzUnzip.Add(element->GetSize() * nElements); - - auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), element->GetSize(), nElements); - newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset)); - fPagePool->PreloadPage(newPage, - RPageDeleter([](const RPage &page, void * /*userData*/) - { - RPageAllocatorFile::DeletePage(page); - }, nullptr)); - }; + auto taskFunc = [this, columnId, clusterId, firstInPage, onDiskPage, element = allElements.back().get(), + nElements = pi.fNElements, + indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex]() { + auto newPage = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element, columnId); + fCounters->fSzUnzip.Add(element->GetSize() * nElements); + + newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset)); + fPagePool->PreloadPage( + newPage, + RPageDeleter([](const RPage &page, void * /*userData*/) { RPageAllocatorHeap::DeletePage(page); }, + nullptr)); + }; fTaskScheduler->AddTask(taskFunc); diff --git a/tree/ntuple/v7/src/libdaos_mock/libdaos_mock.cxx b/tree/ntuple/v7/src/libdaos_mock/libdaos_mock.cxx index 35599fae348ca..c8ad171d0a0d7 100644 --- a/tree/ntuple/v7/src/libdaos_mock/libdaos_mock.cxx +++ b/tree/ntuple/v7/src/libdaos_mock/libdaos_mock.cxx @@ -112,14 +112,15 @@ int RDaosFakeObject::Update(daos_key_t *dkey, unsigned int nr, daos_iod_t *iods, for (unsigned i = 0; i < nr; i++) { auto &data = fStorage[GetKey(dkey, /*akey=*/&iods[i].iod_name)]; /* We assume each attribute key is associated to a single value whose corresponding data is - * updated from exactly one I/O vector. */ + * sequentially updated from one or more I/O vectors. */ if (iods[i].iod_nr != 1 || iods[i].iod_type != DAOS_IOD_SINGLE) return -DER_INVAL; - if (sgls[i].sg_nr != 1) - return -DER_INVAL; - d_iov_t &iov = sgls[i].sg_iovs[0]; - data.assign(reinterpret_cast(iov.iov_buf), iov.iov_buf_len); // Write to buffer + data.clear(); + for (unsigned j = 0; j < sgls[i].sg_nr; j++) { + const d_iov_t &iov = sgls[i].sg_iovs[j]; + data.append(reinterpret_cast(iov.iov_buf), iov.iov_buf_len); + } } return 0; } diff --git a/tree/ntuple/v7/test/CMakeLists.txt b/tree/ntuple/v7/test/CMakeLists.txt index 0e7024f133e2f..1989065139b3f 100644 --- a/tree/ntuple/v7/test/CMakeLists.txt +++ b/tree/ntuple/v7/test/CMakeLists.txt @@ -23,41 +23,47 @@ if(MSVC) ${CMAKE_CURRENT_BINARY_DIR}/libCustomStruct.dll) endif() -ROOT_ADD_GTEST(ntuple_basics ntuple_basics.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_basics ntuple_basics.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_bulk ntuple_bulk.cxx LIBRARIES ROOTNTuple CustomStruct) ROOT_ADD_GTEST(ntuple_cluster ntuple_cluster.cxx LIBRARIES ROOTNTuple) -ROOT_ADD_GTEST(ntuple_descriptor ntuple_descriptor.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_descriptor ntuple_descriptor.cxx LIBRARIES ROOTNTuple CustomStruct) ROOT_ADD_GTEST(ntuple_endian ntuple_endian.cxx LIBRARIES ROOTNTuple) -ROOT_ADD_GTEST(ntuple_friends ntuple_friends.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_merger ntuple_merger.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_metrics ntuple_metrics.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_packing ntuple_packing.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_pages ntuple_pages.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_print ntuple_print.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_rdf ntuple_rdf.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_serialize ntuple_serialize.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -if(NOT MSVC OR ${LLVM_VERSION} VERSION_LESS 13.0.0 OR llvm13_broken_tests) - ROOT_ADD_GTEST(ntuple_types ntuple_types.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_friends ntuple_friends.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_merger ntuple_merger.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_metrics ntuple_metrics.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_packing ntuple_packing.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_pages ntuple_pages.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_print ntuple_print.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_project ntuple_project.cxx LIBRARIES ROOTNTuple) +ROOT_ADD_GTEST(ntuple_modelext ntuple_modelext.cxx LIBRARIES ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_serialize ntuple_serialize.cxx LIBRARIES ROOTNTuple CustomStruct) +if(NOT MSVC OR llvm13_broken_tests) + ROOT_ADD_GTEST(ntuple_types ntuple_types.cxx LIBRARIES ROOTNTuple CustomStruct) endif() -ROOT_ADD_GTEST(ntuple_view ntuple_view.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_zip ntuple_zip.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_view ntuple_view.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_zip ntuple_zip.cxx LIBRARIES ROOTNTuple CustomStruct) -ROOT_ADD_GTEST(rfield_class rfield_class.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(rfield_string rfield_string.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(rfield_variant rfield_variant.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(rfield_vector rfield_vector.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(rfield_class rfield_class.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(rfield_string rfield_string.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(rfield_variant rfield_variant.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(rfield_vector rfield_vector.cxx LIBRARIES ROOTNTuple CustomStruct) -ROOT_ADD_GTEST(ntuple_minifile ntuple_minifile.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_show ntuple_show.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_storage ntuple_storage.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) -ROOT_ADD_GTEST(ntuple_extended ntuple_extended.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_minifile ntuple_minifile.cxx LIBRARIES ROOTNTuple Tree CustomStruct) +ROOT_ADD_GTEST(ntuple_show ntuple_show.cxx LIBRARIES ROOTNTuple CustomStruct) +ROOT_ADD_GTEST(ntuple_storage ntuple_storage.cxx LIBRARIES ROOTNTuple MathCore CustomStruct) +ROOT_ADD_GTEST(ntuple_extended ntuple_extended.cxx LIBRARIES ROOTNTuple MathCore CustomStruct) if(daos OR daos_mock) - # UUID of the DAOS pool used for testing, if not provided (may be any for libdaos_mock). + # Label of the DAOS pool used for testing, if not provided (may be any for libdaos_mock). if(NOT daos_test_pool) set(daos_test_pool ntuple-daos-test-pool) endif() - set_property(SOURCE ntuple_storage_daos.cxx - APPEND PROPERTY COMPILE_DEFINITIONS R__DAOS_TEST_POOL="${daos_test_pool}") - ROOT_ADD_GTEST(ntuple_storage_daos ntuple_storage_daos.cxx LIBRARIES ROOTDataFrame ROOTNTuple MathCore CustomStruct) + ROOT_ADD_GTEST(ntuple_storage_daos ntuple_storage_daos.cxx LIBRARIES ROOTNTuple MathCore CustomStruct) + target_compile_definitions(ntuple_storage_daos PRIVATE R__DAOS_TEST_POOL="${daos_test_pool}") + + if(daos_mock) + set_property(SOURCE ntuple_storage_daos.cxx + APPEND PROPERTY COMPILE_DEFINITIONS R__DAOS_TEST_MOCK=1) + endif() endif() diff --git a/tree/ntuple/v7/test/CustomStruct.hxx b/tree/ntuple/v7/test/CustomStruct.hxx index 3f7347d78d7aa..b58b1b4745aeb 100644 --- a/tree/ntuple/v7/test/CustomStruct.hxx +++ b/tree/ntuple/v7/test/CustomStruct.hxx @@ -1,6 +1,11 @@ #ifndef ROOT7_RNTuple_Test_CustomStruct #define ROOT7_RNTuple_Test_CustomStruct +#include // for Double32_t +#include + +#include +#include #include #include #include @@ -8,11 +13,27 @@ /** * Used to test serialization and deserialization of classes in RNTuple with TClass */ + +enum CustomEnum { kCustomEnumVal = 7 }; +// TODO(jblomer): use standard integer types for specifying the underlying width; requires TEnum fix. +enum class CustomEnumInt8 : char {}; +enum class CustomEnumUInt8 : unsigned char {}; +enum class CustomEnumInt16 : short int {}; +enum class CustomEnumUInt16 : unsigned short int {}; +enum class CustomEnumInt32 : int {}; +enum class CustomEnumUInt32 : unsigned int {}; +enum class CustomEnumInt64 : long int {}; +enum class CustomEnumUInt64 : unsigned long int {}; + struct CustomStruct { float a = 0.0; std::vector v1; std::vector> v2; std::string s; + + bool operator<(const CustomStruct &c) const { return a < c.a && v1 < c.v1 && v2 < c.v2 && s < c.s; } + + bool operator==(const CustomStruct &c) const { return a == c.a && v1 == c.v1 && v2 == c.v2 && s == c.s; } }; struct DerivedA : public CustomStruct { @@ -40,12 +61,33 @@ struct StructWithArrays { float f[2]; }; -struct EmptyBase { -}; -struct alignas(std::uint64_t) TestEBO : public EmptyBase { +struct EmptyStruct {}; +struct alignas(std::uint64_t) TestEBO : public EmptyStruct { std::uint64_t u64; }; +template +class EdmWrapper { +public: + bool fIsPresent = true; + T fMember; +}; + +class IOConstructor { +public: + IOConstructor() = delete; + IOConstructor(TRootIOCtor *) {}; + + int a = 7; +}; + +class LowPrecisionFloats { +public: + double a = 0.0; + Double32_t b = 1.0; + Double32_t c[2] = {2.0, 3.0}; +}; + /// The classes below are based on an excerpt provided by Marcin Nowak (EP-UAT) /// struct IAuxSetOption {}; @@ -94,6 +136,7 @@ struct StructWithEnums : BaseOfStructWithEnums { enum class DeclEC { E1, E2, E42 = 137 }; int a = E42; int b = static_cast(DeclEC::E42); + CustomEnum e = kCustomEnumVal; }; /// A class that behaves as a collection accessed through the `TVirtualCollectionProxy` interface @@ -135,4 +178,22 @@ struct DestructorTraits : TrivialTraitsBase { ~DestructorTraits() {} }; +struct StructWithIORulesBase { + float a; + float b; //! transient member +}; + +struct StructWithTransientString { + char chars[4]; + std::string str; //! transient member +}; + +struct StructWithIORules : StructWithIORulesBase { + StructWithTransientString s; + float c = 0.0f; //! transient member + + StructWithIORules() = default; + StructWithIORules(float _a, char _c[4]) : StructWithIORulesBase{_a, 0.0f}, s{{_c[0], _c[1], _c[2], _c[3]}, {}} {} +}; + #endif diff --git a/tree/ntuple/v7/test/CustomStructLinkDef.h b/tree/ntuple/v7/test/CustomStructLinkDef.h index 528e06dcec83d..529fe9dd3b01b 100644 --- a/tree/ntuple/v7/test/CustomStructLinkDef.h +++ b/tree/ntuple/v7/test/CustomStructLinkDef.h @@ -4,13 +4,28 @@ #pragma link off all classes; #pragma link off all functions; +#pragma link C++ enum CustomEnum; +#pragma link C++ enum CustomEnumInt8; +#pragma link C++ enum CustomEnumUInt8; +#pragma link C++ enum CustomEnumInt16; +#pragma link C++ enum CustomEnumUInt16; +#pragma link C++ enum CustomEnumInt32; +#pragma link C++ enum CustomEnumUInt32; +#pragma link C++ enum CustomEnumInt64; +#pragma link C++ enum CustomEnumUInt64; + #pragma link C++ class CustomStruct+; #pragma link C++ class DerivedA+; #pragma link C++ class DerivedA2+; #pragma link C++ class DerivedB+; #pragma link C++ class DerivedC+; #pragma link C++ class StructWithArrays + ; +#pragma link C++ class EmptyStruct + ; #pragma link C++ class TestEBO+; +#pragma link C++ class IOConstructor+; +#pragma link C++ class LowPrecisionFloats+; + +#pragma link C++ class EdmWrapper +; #pragma link C++ class IAuxSetOption+; #pragma link C++ class PackedParameters+; @@ -36,4 +51,31 @@ #pragma link C++ class ConstructorTraits + ; #pragma link C++ class DestructorTraits + ; +#pragma link C++ class std::set +; +#pragma link C++ class std::set +; +#pragma link C++ class std::set +; +#pragma link C++ class std::set> +; +#pragma link C++ class std::set> +; +#pragma link C++ class std::set> +; + +#pragma link C++ options = version(3) class StructWithIORulesBase + ; +#pragma link C++ options = version(3) class StructWithTransientString + ; +#pragma link C++ options = version(3) class StructWithIORules + ; + +#pragma read sourceClass = "StructWithIORulesBase" source = "float a" version = "[1-99]" targetClass = \ + "StructWithIORulesBase" target = "b" code = "{ b = onfile.a + 1.0f; }" +// Including a non-transient member in `target` should issue a warning and ignore the rule; thus, `a` remains unchanged +// in the test +#pragma read sourceClass = "StructWithIORulesBase" source = "float a" version = "[1-]" targetClass = \ + "StructWithIORulesBase" target = "a" code = "{ a = 0.0f; }" +// This rule is ignored due to type version mismatch +#pragma read sourceClass = "StructWithIORulesBase" source = "float a" version = "[100-]" targetClass = \ + "StructWithIORulesBase" target = "b" code = "{ b = 0.0f; }" + +#pragma read sourceClass = "StructWithTransientString" source = "char chars[4]" version = "[1-]" targetClass = \ + "StructWithTransientString" target = "str" include = "string" code = "{ str = std::string{onfile.chars, 4}; }" + +#pragma read sourceClass = "StructWithIORules" source = "float a;float b" version = "[1-]" targetClass = \ + "StructWithIORules" target = "c" code = "{ c = onfile.a + onfile.b; }" + #endif diff --git a/tree/ntuple/v7/test/SimpleCollectionProxy.hxx b/tree/ntuple/v7/test/SimpleCollectionProxy.hxx index ddb2017100bf7..884960082fba0 100644 --- a/tree/ntuple/v7/test/SimpleCollectionProxy.hxx +++ b/tree/ntuple/v7/test/SimpleCollectionProxy.hxx @@ -5,18 +5,55 @@ namespace { /// Simple collection proxy for `StructUsingCollectionProxy` -template -struct SimpleCollectionProxy : public TVirtualCollectionProxy { +template +class SimpleCollectionProxy : public TVirtualCollectionProxy { + /// The internal representation of an iterator, which in this simple test only contains a pointer to an element + struct IteratorData { + typename CollectionT::ValueType *ptr; + }; + + static void + Func_CreateIterators(void *collection, void **begin_arena, void **end_arena, TVirtualCollectionProxy * /*proxy*/) + { + static_assert(sizeof(IteratorData) <= TVirtualCollectionProxy::fgIteratorArenaSize); + auto &vec = static_cast(collection)->v; + if constexpr (CollectionKind == ROOT::kSTLvector) { + // An iterator on an array-backed container is just a pointer; thus, it can be directly stored in `*xyz_arena`, + // saving one dereference (see TVirtualCollectionProxy documentation) + *begin_arena = &(*vec.begin()); + *end_arena = &(*vec.end()); + } else { + static_cast(*begin_arena)->ptr = &(*vec.begin()); + static_cast(*end_arena)->ptr = &(*vec.end()); + } + } + + static void *Func_Next(void *iter, const void *end) + { + auto _iter = static_cast(iter); + auto _end = static_cast(end); + if (_iter->ptr >= _end->ptr) + return nullptr; + return _iter->ptr++; + } + + static void Func_DeleteTwoIterators(void * /*begin*/, void * /*end*/) {} + +private: CollectionT *fObject = nullptr; +public: SimpleCollectionProxy() : TVirtualCollectionProxy(TClass::GetClass(ROOT::Internal::GetDemangledTypeName(typeid(CollectionT)).c_str())) { } - SimpleCollectionProxy(const SimpleCollectionProxy &) : SimpleCollectionProxy() {} + SimpleCollectionProxy(const SimpleCollectionProxy &) : SimpleCollectionProxy() {} - TVirtualCollectionProxy *Generate() const override { return new SimpleCollectionProxy(*this); } - Int_t GetCollectionType() const override { return ROOT::kSTLvector; } + TVirtualCollectionProxy *Generate() const override + { + return new SimpleCollectionProxy(*this); + } + Int_t GetCollectionType() const override { return CollectionKind; } ULong_t GetIncrement() const override { return sizeof(typename CollectionT::ValueType); } UInt_t Sizeof() const override { return sizeof(CollectionT); } Bool_t HasPointers() const override { return kFALSE; } @@ -44,7 +81,11 @@ struct SimpleCollectionProxy : public TVirtualCollectionProxy { void *At(UInt_t idx) override { return &fObject->v[idx]; } void Clear(const char * /*opt*/ = "") override { fObject->v.clear(); } UInt_t Size() const override { return fObject->v.size(); } - void *Allocate(UInt_t /*n*/, Bool_t /*forceDelete*/) override { return nullptr; } + void *Allocate(UInt_t n, Bool_t /*forceDelete*/) override + { + fObject->v.resize(n); + return fObject; + } void Commit(void *) override {} void Insert(const void *data, void *container, size_t size) override { @@ -62,11 +103,14 @@ struct SimpleCollectionProxy : public TVirtualCollectionProxy { TStreamerInfoActions::TActionSequence *GetReadMemberWiseActions(Int_t /*version*/) override { return nullptr; } TStreamerInfoActions::TActionSequence *GetWriteMemberWiseActions() override { return nullptr; } - CreateIterators_t GetFunctionCreateIterators(Bool_t /*read*/ = kTRUE) override { return nullptr; } + CreateIterators_t GetFunctionCreateIterators(Bool_t /*read*/ = kTRUE) override { return &Func_CreateIterators; } CopyIterator_t GetFunctionCopyIterator(Bool_t /*read*/ = kTRUE) override { return nullptr; } - Next_t GetFunctionNext(Bool_t /*read*/ = kTRUE) override { return nullptr; } + Next_t GetFunctionNext(Bool_t /*read*/ = kTRUE) override { return &Func_Next; } DeleteIterator_t GetFunctionDeleteIterator(Bool_t /*read*/ = kTRUE) override { return nullptr; } - DeleteTwoIterators_t GetFunctionDeleteTwoIterators(Bool_t /*read*/ = kTRUE) override { return nullptr; } + DeleteTwoIterators_t GetFunctionDeleteTwoIterators(Bool_t /*read*/ = kTRUE) override + { + return &Func_DeleteTwoIterators; + } }; } // namespace diff --git a/tree/ntuple/v7/test/ntuple_basics.cxx b/tree/ntuple/v7/test/ntuple_basics.cxx index 2146d3d02a4d1..af4b36f4dae8f 100644 --- a/tree/ntuple/v7/test/ntuple_basics.cxx +++ b/tree/ntuple/v7/test/ntuple_basics.cxx @@ -411,6 +411,10 @@ TEST(RNTupleModel, GetField) EXPECT_EQ(m->GetField("cs.v1")->GetType(), "std::vector"); EXPECT_EQ(m->GetField("nonexistent"), nullptr); EXPECT_EQ(m->GetField(""), nullptr); + EXPECT_EQ("", m->GetFieldZero()->GetQualifiedFieldName()); + EXPECT_EQ("x", m->GetField("x")->GetQualifiedFieldName()); + EXPECT_EQ("cs", m->GetField("cs")->GetQualifiedFieldName()); + EXPECT_EQ("cs.v1", m->GetField("cs.v1")->GetQualifiedFieldName()); } TEST(RNTuple, EmptyString) @@ -674,14 +678,14 @@ TEST(RNTuple, ReadCallback) auto model = RNTupleModel::Create(); auto fieldI32 = std::make_unique>("i32"); auto fieldKlass = std::make_unique>("klass"); - RFieldCallbackInjector::Inject(*fieldI32, [](RFieldValue &value) { + RFieldCallbackInjector::Inject(*fieldI32, [](void *target) { static std::int32_t expected = 0; - EXPECT_EQ(*value.Get(), expected++); + EXPECT_EQ(*static_cast(target), expected++); gNCallReadCallback++; }); - RFieldCallbackInjector::Inject(*fieldI32, [](RFieldValue &) { gNCallReadCallback++; }); - RFieldCallbackInjector::Inject(*fieldKlass, [](RFieldValue &value) { - auto typedValue = value.Get(); + RFieldCallbackInjector::Inject(*fieldI32, [](void *) { gNCallReadCallback++; }); + RFieldCallbackInjector::Inject(*fieldKlass, [](void *target) { + auto typedValue = static_cast(target); typedValue->a = 1337.0; // should change the value on the default entry gNCallReadCallback++; }); @@ -697,3 +701,34 @@ TEST(RNTuple, ReadCallback) EXPECT_EQ(1337.0, rdKlass->a); EXPECT_EQ(6U, gNCallReadCallback); } + +TEST(RNTuple, FillBytesWritten) +{ + FileRaii fileGuard("test_ntuple_fillbytes.ntuple"); + + auto checkFillReturnValue = [&](const RNTupleWriteOptions &options) { + const std::size_t indexColumnSz = options.GetHasSmallClusters() ? sizeof(std::uint32_t) : sizeof(std::uint64_t); + + // TODO(jalopezg): improve test coverage by adding other field types + auto model = RNTupleModel::Create(); + auto fieldI32 = model->MakeField("i32"); + auto fieldStr = model->MakeField("s"); + auto fieldBoolVec = model->MakeField>("bool_vec"); + auto fieldFloatVec = model->MakeField>("float_vec"); + auto ntuple = RNTupleWriter::Recreate(std::move(model), "f", fileGuard.GetPath(), options); + *fieldI32 = 42; + *fieldStr = "abc"; + // A 32bit integer + "abc" literal + one (32|64)bit integer for each index column + EXPECT_EQ(7U + (3 * indexColumnSz), ntuple->Fill()); + *fieldBoolVec = {true, false, true}; + *fieldFloatVec = {42.0f, 1.1f}; + // A 32bit integer + "abc" literal + one (32|64)bit integer for each index column + 3 bools + 2 floats + EXPECT_EQ(18U + (3 * indexColumnSz), ntuple->Fill()); + }; + + checkFillReturnValue({}); + + RNTupleWriteOptions optsSmall; + optsSmall.SetHasSmallClusters(true); + checkFillReturnValue(optsSmall); +} diff --git a/tree/ntuple/v7/test/ntuple_bulk.cxx b/tree/ntuple/v7/test/ntuple_bulk.cxx new file mode 100644 index 0000000000000..32480bdc7c55a --- /dev/null +++ b/tree/ntuple/v7/test/ntuple_bulk.cxx @@ -0,0 +1,201 @@ +#include "ntuple_test.hxx" + +TEST(RNTupleBulk, Simple) +{ + FileRaii fileGuard("test_ntuple_bulk_simple.root"); + { + auto model = RNTupleModel::Create(); + auto fldInt = model->MakeField("int"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + for (int i = 0; i < 10; ++i) { + *fldInt = i; + writer->Fill(); + } + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + // TODO(jblomer): find a better way to expose the GenerateBulk method of the target field + auto fieldZero = reader->GetModel()->GetFieldZero(); + std::unique_ptr bulk; + for (auto &f : *fieldZero) { + if (f.GetName() != "int") + continue; + bulk = std::make_unique(f.GenerateBulk()); + } + + auto mask = std::make_unique(10); + std::fill(mask.get(), mask.get() + 10, true); + auto intArr5 = static_cast(bulk->ReadBulk(RClusterIndex(0, 0), mask.get(), 5)); + for (int i = 0; i < 5; ++i) { + EXPECT_EQ(i, intArr5[i]); + } + + auto intArr1 = static_cast(bulk->ReadBulk(RClusterIndex(0, 1), mask.get(), 1)); + EXPECT_EQ(1, intArr1[0]); + EXPECT_EQ(static_cast(intArr5) + 1, static_cast(intArr1)); + + auto intArr10 = static_cast(bulk->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + for (int i = 0; i < 10; ++i) { + EXPECT_EQ(i, intArr10[i]); + } +} + +TEST(RNTupleBulk, Complex) +{ + FileRaii fileGuard("test_ntuple_bulk_complex.root"); + { + auto model = RNTupleModel::Create(); + auto fldS = model->MakeField("S"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + for (int i = 0; i < 10; ++i) { + fldS->a = i; + writer->Fill(); + } + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + auto fieldZero = reader->GetModel()->GetFieldZero(); + std::unique_ptr bulk; + for (auto &f : *fieldZero) { + if (f.GetName() != "S") + continue; + bulk = std::make_unique(f.GenerateBulk()); + } + + auto mask = std::make_unique(10); + for (unsigned int i = 0; i < 10; ++i) + mask[i] = (i % 2 == 0); + + auto SArr5 = static_cast(bulk->ReadBulk(RClusterIndex(0, 0), mask.get(), 5)); + for (int i = 0; i < 5; ++i) { + EXPECT_FLOAT_EQ((i % 2 == 0) ? float(i) : 0.0, SArr5[i].a); + } + + auto SArr1 = static_cast(bulk->ReadBulk(RClusterIndex(0, 1), mask.get() + 1, 1)); + EXPECT_FLOAT_EQ(0.0, SArr1[0].a); + EXPECT_EQ(static_cast(SArr5) + 1, static_cast(SArr1)); + + SArr1 = static_cast(bulk->ReadBulk(RClusterIndex(0, 1), mask.get(), 1)); + EXPECT_FLOAT_EQ(1.0, SArr1[0].a); + EXPECT_EQ(static_cast(SArr5) + 1, static_cast(SArr1)); + + for (unsigned int i = 0; i < 10; ++i) + mask[i] = !mask[i]; + auto SArr10 = static_cast(bulk->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + for (int i = 0; i < 10; ++i) { + EXPECT_FLOAT_EQ((i % 2 == 0) ? 0.0 : float(i), SArr10[i].a); + } +} + +TEST(RNTupleBulk, CardinalityField) +{ + using RNTupleCardinality32 = ROOT::Experimental::RNTupleCardinality; + using RNTupleCardinality64 = ROOT::Experimental::RNTupleCardinality; + + FileRaii fileGuard("test_ntuple_bulk_cardinality.root"); + { + auto model = RNTupleModel::Create(); + auto fldVec = model->MakeField>("vint"); + model->AddProjectedField(std::make_unique>("card32"), + [](const std::string &) { return "vint"; }); + model->AddProjectedField(std::make_unique>("card64"), + [](const std::string &) { return "vint"; }); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + for (int i = 0; i < 10; ++i) { + fldVec->resize(i); + writer->Fill(); + } + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + + auto fieldZero = reader->GetModel()->GetFieldZero(); + std::unique_ptr bulk32; + std::unique_ptr bulk64; + for (auto &f : *fieldZero) { + if (f.GetName() == "card32") + bulk32 = std::make_unique(f.GenerateBulk()); + if (f.GetName() == "card64") + bulk64 = std::make_unique(f.GenerateBulk()); + } + + auto mask = std::make_unique(10); + std::fill(mask.get(), mask.get() + 10, false /* the cardinality field optimization should ignore the mask */); + + auto card32Arr = static_cast(bulk32->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + auto card64Arr = static_cast(bulk64->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + for (int i = 0; i < 10; ++i) { + EXPECT_EQ(i, card32Arr[i]); + EXPECT_EQ(i, card64Arr[i]); + } +} + +TEST(RNTupleBulk, RVec) +{ + FileRaii fileGuard("test_ntuple_bulk_rvec.root"); + { + auto model = RNTupleModel::Create(); + auto fldVecI = model->MakeField("vint"); + auto fldVecS = model->MakeField>("vs"); + auto fldVecVI = model->MakeField>("vvint"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + for (int i = 0; i < 10; ++i) { + fldVecI->resize(i); + fldVecS->resize(i); + fldVecVI->resize(i); + for (int j = 0; j < i; ++j) { + fldVecI->at(j) = j; + fldVecS->at(j).a = j; + fldVecVI->at(j).resize(j); + for (int k = 0; k < j; ++k) { + fldVecVI->at(j).at(k) = k; + } + } + writer->Fill(); + } + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + + auto fieldZero = reader->GetModel()->GetFieldZero(); + std::unique_ptr bulkI; + std::unique_ptr bulkS; + std::unique_ptr bulkVI; + for (auto &f : *fieldZero) { + if (f.GetName() == "vint") + bulkI = std::make_unique(f.GenerateBulk()); + if (f.GetName() == "vs") + bulkS = std::make_unique(f.GenerateBulk()); + if (f.GetName() == "vvint") + bulkVI = std::make_unique(f.GenerateBulk()); + } + + auto mask = std::make_unique(10); + std::fill(mask.get(), mask.get() + 10, true); + mask[1] = false; // the RVec field optimization should ignore the mask + + auto iArr = static_cast(bulkI->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + auto sArr = static_cast *>(bulkS->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + auto viArr = static_cast *>(bulkVI->ReadBulk(RClusterIndex(0, 0), mask.get(), 10)); + for (int i = 0; i < 10; ++i) { + EXPECT_EQ(i, iArr[i].size()); + EXPECT_EQ(i == 1 ? 0 : i, sArr[i].size()); + EXPECT_EQ(i == 1 ? 0 : i, viArr[i].size()); + for (std::size_t j = 0; j < iArr[i].size(); ++j) { + EXPECT_EQ(j, iArr[i].at(j)); + } + // RVec should have all the vector elements of the bulk stored consecutively in memory + if (i > 1) { + EXPECT_EQ(&iArr[i - 1][0] + iArr[i - 1].size(), &iArr[i][0]); + } + for (std::size_t j = 0; j < sArr[i].size(); ++j) { + EXPECT_FLOAT_EQ(j, sArr[i].at(j).a); + } + for (std::size_t j = 0; j < viArr[i].size(); ++j) { + EXPECT_EQ(j, viArr[i].at(j).size()); + for (std::size_t k = 0; k < viArr[i].at(j).size(); ++k) { + EXPECT_EQ(k, viArr[i][j][k]); + } + } + } +} diff --git a/tree/ntuple/v7/test/ntuple_cluster.cxx b/tree/ntuple/v7/test/ntuple_cluster.cxx index 0c299d97de2ea..ff606512d2da7 100644 --- a/tree/ntuple/v7/test/ntuple_cluster.cxx +++ b/tree/ntuple/v7/test/ntuple_cluster.cxx @@ -80,10 +80,10 @@ class RPageSourceMock : public RPageSource { std::vector> result; for (auto key : clusterKeys) { fReqsClusterIds.emplace_back(key.fClusterId); - fReqsColumns.emplace_back(key.fColumnSet); + fReqsColumns.emplace_back(key.fPhysicalColumnSet); auto cluster = std::make_unique(key.fClusterId); auto pageMap = std::make_unique(); - for (auto colId : key.fColumnSet) { + for (auto colId : key.fPhysicalColumnSet) { pageMap->Register(ROnDiskPage::Key(colId, 0), ROnDiskPage(nullptr, 0)); cluster->SetColumnAvailable(colId); } @@ -310,7 +310,7 @@ TEST(PageStorageFile, LoadClusters) auto descriptorGuard = source.GetSharedDescriptorGuard(); ptId = descriptorGuard->FindFieldId("pt"); EXPECT_NE(ROOT::Experimental::kInvalidDescriptorId, ptId); - colId = descriptorGuard->FindColumnId(ptId, 0); + colId = descriptorGuard->FindPhysicalColumnId(ptId, 0); EXPECT_NE(ROOT::Experimental::kInvalidDescriptorId, colId); } @@ -320,12 +320,11 @@ TEST(PageStorageFile, LoadClusters) EXPECT_EQ(0U, cluster->GetId()); EXPECT_EQ(0U, cluster->GetNOnDiskPages()); - auto column = std::unique_ptr( - ROOT::Experimental::Detail::RColumn::Create( - ROOT::Experimental::RColumnModel(ROOT::Experimental::EColumnType::kReal32, false), 0)); + auto column = ROOT::Experimental::Detail::RColumn::Create( + ROOT::Experimental::RColumnModel(ROOT::Experimental::EColumnType::kReal32, false), 0); column->Connect(ptId, &source); clusterKeys[0].fClusterId = 1; - clusterKeys[0].fColumnSet.insert(colId); + clusterKeys[0].fPhysicalColumnSet.insert(colId); cluster = std::move(source.LoadClusters(clusterKeys)[0]); EXPECT_EQ(1U, cluster->GetId()); EXPECT_EQ(1U, cluster->GetNOnDiskPages()); diff --git a/tree/ntuple/v7/test/ntuple_descriptor.cxx b/tree/ntuple/v7/test/ntuple_descriptor.cxx index daea1af275d47..fadcfc76aea68 100644 --- a/tree/ntuple/v7/test/ntuple_descriptor.cxx +++ b/tree/ntuple/v7/test/ntuple_descriptor.cxx @@ -67,6 +67,70 @@ TEST(RNTupleDescriptorBuilder, CatchBadLinks) } } +TEST(RNTupleDescriptorBuilder, CatchBadColumnDescriptors) +{ + RNTupleDescriptorBuilder descBuilder; + descBuilder.AddField( + RFieldDescriptorBuilder().FieldId(0).Structure(ENTupleStructure::kRecord).MakeDescriptor().Unwrap()); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(1) + .FieldName("field") + .TypeName("int32_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(2) + .FieldName("fieldAlias") + .TypeName("int32_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddFieldLink(0, 1); + descBuilder.AddFieldLink(0, 2); + RColumnModel colModel(EColumnType::kInt32, false); + RColumnDescriptorBuilder colBuilder1; + colBuilder1.LogicalColumnId(0).PhysicalColumnId(0).Model(colModel).FieldId(1).Index(0); + descBuilder.AddColumn(colBuilder1.MakeDescriptor().Unwrap()).ThrowOnError(); + + RColumnDescriptorBuilder colBuilder2; + colBuilder2.LogicalColumnId(1).PhysicalColumnId(0).Model(colModel).FieldId(42).Index(0); + try { + descBuilder.AddColumn(colBuilder2.MakeDescriptor().Unwrap()).ThrowOnError(); + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("doesn't exist")); + } + + RColumnDescriptorBuilder colBuilder3; + colBuilder3.LogicalColumnId(0).PhysicalColumnId(0).Model(colModel).FieldId(2).Index(0); + try { + descBuilder.AddColumn(colBuilder3.MakeDescriptor().Unwrap()).ThrowOnError(); + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("column index clash")); + } + + RColumnDescriptorBuilder colBuilder4; + colBuilder4.LogicalColumnId(1).PhysicalColumnId(0).Model(colModel).FieldId(2).Index(1); + try { + descBuilder.AddColumn(colBuilder4.MakeDescriptor().Unwrap()).ThrowOnError(); + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("out of bounds column index")); + } + + RColumnDescriptorBuilder colBuilder5; + RColumnModel falseModel(EColumnType::kInt64, false); + colBuilder5.LogicalColumnId(1).PhysicalColumnId(0).Model(falseModel).FieldId(2).Index(0); + try { + descBuilder.AddColumn(colBuilder5.MakeDescriptor().Unwrap()).ThrowOnError(); + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("alias column type mismatch")); + } + + RColumnDescriptorBuilder colBuilder6; + colBuilder6.LogicalColumnId(1).PhysicalColumnId(0).Model(colModel).FieldId(2).Index(0); + descBuilder.AddColumn(colBuilder6.MakeDescriptor().Unwrap()).ThrowOnError(); +} + TEST(RNTupleDescriptorBuilder, CatchInvalidDescriptors) { RNTupleDescriptorBuilder descBuilder; @@ -82,6 +146,115 @@ TEST(RNTupleDescriptorBuilder, CatchInvalidDescriptors) descBuilder.EnsureValidDescriptor(); } +TEST(RFieldDescriptorBuilder, HeaderExtension) +{ + RNTupleDescriptorBuilder descBuilder; + descBuilder.AddField( + RFieldDescriptorBuilder().FieldId(0).Structure(ENTupleStructure::kRecord).MakeDescriptor().Unwrap()); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(1) + .FieldName("i32") + .TypeName("int32_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddColumn(RColumnDescriptorBuilder() + .LogicalColumnId(0) + .PhysicalColumnId(0) + .Model(RColumnModel{EColumnType::kInt32, false}) + .FieldId(1) + .Index(0) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddFieldLink(0, 1); + + EXPECT_TRUE(descBuilder.GetDescriptor().GetHeaderExtension() == nullptr); + descBuilder.BeginHeaderExtension(); + EXPECT_TRUE(descBuilder.GetDescriptor().GetHeaderExtension() != nullptr); + + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(2) + .FieldName("topLevel1") + .Structure(ENTupleStructure::kRecord) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(3) + .FieldName("i64") + .TypeName("int64_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddColumn(RColumnDescriptorBuilder() + .LogicalColumnId(1) + .PhysicalColumnId(1) + .Model(RColumnModel{EColumnType::kInt64, false}) + .FieldId(3) + .Index(0) + .FirstElementIndex(1002) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddFieldLink(2, 3); + descBuilder.AddFieldLink(0, 2); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(4) + .FieldName("topLevel2") + .TypeName("bool") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddColumn(RColumnDescriptorBuilder() + .LogicalColumnId(2) + .PhysicalColumnId(2) + .Model(RColumnModel{EColumnType::kBit, false}) + .FieldId(4) + .Index(0) + .FirstElementIndex(1100) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddFieldLink(0, 4); + descBuilder.AddField(RFieldDescriptorBuilder() + .FieldId(5) + .FieldName("projected") + .TypeName("int64_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddColumn(RColumnDescriptorBuilder() + .LogicalColumnId(3) + .PhysicalColumnId(1) + .Model(RColumnModel{EColumnType::kInt64, false}) + .FieldId(5) + .Index(0) + .MakeDescriptor() + .Unwrap()); + descBuilder.AddFieldLink(0, 5); + + auto desc = descBuilder.MoveDescriptor(); + ASSERT_EQ(desc.GetNFields(), 6); + ASSERT_EQ(desc.GetNLogicalColumns(), 4); + ASSERT_EQ(desc.GetNPhysicalColumns(), 3); + { + std::string_view child_names[] = {"i32", "topLevel1", "topLevel2", "projected"}; + unsigned i = 0; + for (auto &child_field : desc.GetTopLevelFields()) + EXPECT_EQ(child_field.GetFieldName(), child_names[i++]); + } + auto xHeader = desc.GetHeaderExtension(); + EXPECT_EQ(xHeader->GetNFields(), 4); + EXPECT_EQ(xHeader->GetNLogicalColumns(), 3); + EXPECT_EQ(xHeader->GetNPhysicalColumns(), 2); + { + std::string_view child_names[] = {"topLevel1", "topLevel2", "projected"}; + unsigned i = 0; + for (auto child_field : xHeader->GetTopLevelFields(desc)) + EXPECT_EQ(desc.GetFieldDescriptor(child_field).GetFieldName(), child_names[i++]); + } + EXPECT_EQ(desc.GetColumnDescriptor(0).GetFirstElementIndex(), 0U); + EXPECT_EQ(desc.GetColumnDescriptor(1).GetFirstElementIndex(), 1002U); + EXPECT_EQ(desc.GetColumnDescriptor(2).GetFirstElementIndex(), 1100U); +} + TEST(RNTupleDescriptor, QualifiedFieldName) { auto model = RNTupleModel::Create(); @@ -259,6 +432,13 @@ TEST(RColumnDescriptorIterable, IterateOverColumns) counter++; } EXPECT_EQ(3, counter); + + counter = 0; + for (const auto &c : desc->GetColumnIterable()) { + (void)c; + counter++; + } + EXPECT_EQ(desc->GetNLogicalColumns(), counter); } TEST(RClusterDescriptor, GetBytesOnStorage) @@ -284,7 +464,7 @@ TEST(RClusterDescriptor, GetBytesOnStorage) auto clusterID = desc->FindClusterId(0, 0); ASSERT_NE(ROOT::Experimental::kInvalidDescriptorId, clusterID); - EXPECT_EQ(4 + 8 + 4 + 3, desc->GetClusterDescriptor(clusterID).GetBytesOnStorage()); + EXPECT_EQ(8 + 8 + 8 + 3, desc->GetClusterDescriptor(clusterID).GetBytesOnStorage()); } TEST(RNTupleDescriptor, Clone) diff --git a/tree/ntuple/v7/test/ntuple_endian.cxx b/tree/ntuple/v7/test/ntuple_endian.cxx index e5f7a81b08c80..866b949973b45 100644 --- a/tree/ntuple/v7/test/ntuple_endian.cxx +++ b/tree/ntuple/v7/test/ntuple_endian.cxx @@ -83,10 +83,7 @@ class RPageSourceMock : public RPageSource { RPage PopulatePage(ColumnHandle_t columnHandle, NTupleSize_t i) final { - auto pageBuffer = RPageSource::UnsealPage(fPages[i], fElement); - RPage newPage(columnHandle.fId, pageBuffer.release(), fElement.GetSize(), fPages[i].fNElements); - newPage.GrowUnchecked(fPages[i].fNElements); - return newPage; + return RPageSource::UnsealPage(fPages[i], fElement, columnHandle.fPhysicalId); } RPage PopulatePage(ColumnHandle_t, const ROOT::Experimental::RClusterIndex &) final { return RPage(); } void ReleasePage(RPage &) final {} @@ -98,191 +95,95 @@ class RPageSourceMock : public RPageSource { }; } // anonymous namespace -TEST(RColumnElementEndian, Float) +TEST(RColumnElementEndian, ByteCopy) { - ROOT::Experimental::Detail::RColumnElement element(nullptr); + ROOT::Experimental::Detail::RColumnElement element; EXPECT_EQ(element.IsMappable(), false); - RPageSinkMock sink(element); + RPageSinkMock sink1(element); unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; RPage page1(0, buf1, 4, 4); page1.GrowUnchecked(4); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); + sink1.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x03\x02\x01\x00\x07\x06\x05\x04\x0b\x0a\x09\x08\x0f\x0e\x0d\x0c", 16)); + 0, memcmp(sink1.GetPages()[0].fBuffer, "\x03\x02\x01\x00\x07\x06\x05\x04\x0b\x0a\x09\x08\x0f\x0e\x0d\x0c", 16)); - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); + RPageSourceMock source1(sink1.GetPages(), element); + auto page2 = source1.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); } -TEST(RColumnElementEndian, Double) +TEST(RColumnElementEndian, Cast) { - ROOT::Experimental::Detail::RColumnElement element(nullptr); + ROOT::Experimental::Detail::RColumnElement element; EXPECT_EQ(element.IsMappable(), false); - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 8, 2); - page1.GrowUnchecked(2); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - - EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x07\x06\x05\x04\x03\x02\x01\x00\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08", 16)); - - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); - std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); -} - -TEST(RColumnElementEndian, Int16) -{ - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); - - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 2, 8); - page1.GrowUnchecked(8); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - - EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x01\x00\x03\x02\x05\x04\x07\x06\x09\x08\x0b\x0a\x0d\x0c\x0f\x0e", 16)); - - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); - std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); -} - -TEST(RColumnElementEndian, UInt16) -{ - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); - - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 2, 8); - page1.GrowUnchecked(8); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - - EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x01\x00\x03\x02\x05\x04\x07\x06\x09\x08\x0b\x0a\x0d\x0c\x0f\x0e", 16)); - - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); - std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); -} - -TEST(RColumnElementEndian, Int32) -{ - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); - - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 4, 4); + RPageSinkMock sink1(element); + unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x08, 0x09, + 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x0c, 0x0d, 0x0e, 0x0f}; + RPage page1(0, buf1, 8, 4); page1.GrowUnchecked(4); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); + sink1.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x03\x02\x01\x00\x07\x06\x05\x04\x0b\x0a\x09\x08\x0f\x0e\x0d\x0c", 16)); + 0, memcmp(sink1.GetPages()[0].fBuffer, "\x03\x02\x01\x00\x07\x06\x05\x04\x0b\x0a\x09\x08\x0f\x0e\x0d\x0c", 16)); - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); + RPageSourceMock source1(sink1.GetPages(), element); + auto page2 = source1.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); + EXPECT_EQ(0, memcmp(buf2.get(), + "\x00\x01\x02\x03\x00\x00\x00\x00\x04\x05\x06\x07\x00\x00\x00\x00" + "\x08\x09\x0a\x0b\x00\x00\x00\x00\x0c\x0d\x0e\x0f\x00\x00\x00\x00", + 32)); } -TEST(RColumnElementEndian, UInt32) +TEST(RColumnElementEndian, Split) { - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); + ROOT::Experimental::Detail::RColumnElement splitElement; - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 4, 4); - page1.GrowUnchecked(4); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - - EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x03\x02\x01\x00\x07\x06\x05\x04\x0b\x0a\x09\x08\x0f\x0e\x0d\x0c", 16)); - - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); - std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); -} - -TEST(RColumnElementEndian, Int64) -{ - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); - - RPageSinkMock sink(element); + RPageSinkMock sink1(splitElement); unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; RPage page1(0, buf1, 8, 2); page1.GrowUnchecked(2); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); + sink1.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x07\x06\x05\x04\x03\x02\x01\x00\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08", 16)); + 0, memcmp(sink1.GetPages()[0].fBuffer, "\x07\x0f\x06\x0e\x05\x0d\x04\x0c\x03\x0b\x02\x0a\x01\x09\x00\x08", 16)); - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); + RPageSourceMock source1(sink1.GetPages(), splitElement); + auto page2 = source1.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); } -TEST(RColumnElementEndian, UInt64) +TEST(RColumnElementEndian, DeltaSplit) { - ROOT::Experimental::Detail::RColumnElement element(nullptr); - EXPECT_EQ(element.IsMappable(), false); - - RPageSinkMock sink(element); - unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; - RPage page1(0, buf1, 8, 2); - page1.GrowUnchecked(2); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - - EXPECT_EQ( - 0, memcmp(sink.GetPages()[0].fBuffer, "\x07\x06\x05\x04\x03\x02\x01\x00\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08", 16)); + using ClusterSize_t = ROOT::Experimental::ClusterSize_t; - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); - std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - EXPECT_EQ(0, memcmp(buf2.get(), "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16)); -} - -TEST(RColumnElementEndian, Int64Int32) -{ - ROOT::Experimental::Detail::RColumnElement element(nullptr); + ROOT::Experimental::Detail::RColumnElement element; EXPECT_EQ(element.IsMappable(), false); - RPageSinkMock sink(element); - std::int64_t buf1[] = {0x0a0b0c0d11223344, 0x0a0b0c0d55667788}; - RPage page1(0, buf1, 8, 2); - page1.GrowUnchecked(2); - sink.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); + RPageSinkMock sink1(element); + unsigned char buf1[] = {0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x08, 0x09, + 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x0c, 0x0d, 0x0e, 0x0f}; + RPage page1(0, buf1, 8, 4); + page1.GrowUnchecked(4); + sink1.CommitPageImpl(RPageStorage::ColumnHandle_t{}, page1); - EXPECT_EQ(0, memcmp(sink.GetPages()[0].fBuffer, "\x44\x33\x22\x11\x88\x77\x66\x55", 8)); + EXPECT_EQ( + 0, memcmp(sink1.GetPages()[0].fBuffer, "\x03\x04\x04\x04\x02\x04\x04\x04\x01\x04\x04\x04\x00\x04\x04\x04", 16)); - RPageSourceMock source(sink.GetPages(), element); - auto page2 = source.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); + RPageSourceMock source1(sink1.GetPages(), element); + auto page2 = source1.PopulatePage(RPageStorage::ColumnHandle_t{}, NTupleSize_t{0}); std::unique_ptr buf2(static_cast(page2.GetBuffer())); // adopt buffer - auto ints = reinterpret_cast(buf2.get()); - EXPECT_EQ(ints[0], 0x0000000011223344); - EXPECT_EQ(ints[1], 0x0000000055667788); + EXPECT_EQ(0, memcmp(buf2.get(), + "\x00\x01\x02\x03\x00\x00\x00\x00\x04\x05\x06\x07\x00\x00\x00\x00" + "\x08\x09\x0a\x0b\x00\x00\x00\x00\x0c\x0d\x0e\x0f\x00\x00\x00\x00", + 32)); } diff --git a/tree/ntuple/v7/test/ntuple_extended.cxx b/tree/ntuple/v7/test/ntuple_extended.cxx index 91871e288e98c..7367c87246237 100644 --- a/tree/ntuple/v7/test/ntuple_extended.cxx +++ b/tree/ntuple/v7/test/ntuple_extended.cxx @@ -2,11 +2,14 @@ #include "ntuple_test.hxx" -#include "TROOT.h" +#include +#include TEST(RNTuple, RealWorld1) { +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif FileRaii fileGuard("test_ntuple_realworld1.root"); // See https://github.com/olifre/root-io-bench/blob/master/benchmark.cpp @@ -74,7 +77,9 @@ TEST(RNTuple, RealWorld1) // Stress test the asynchronous cluster pool by a deliberately unfavourable read pattern TEST(RNTuple, RandomAccess) { +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif FileRaii fileGuard("test_ntuple_random_access.root"); auto modelWrite = RNTupleModel::Create(); @@ -111,7 +116,9 @@ TEST(RNTuple, RandomAccess) #if !defined(_MSC_VER) || defined(R__ENABLE_BROKEN_WIN_TESTS) TEST(RNTuple, LargeFile1) { +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif FileRaii fileGuard("test_large_file1.root"); auto modelWrite = RNTupleModel::Create(); @@ -123,8 +130,8 @@ TEST(RNTuple, LargeFile1) RNTupleWriteOptions options; options.SetCompression(0); auto ntuple = RNTupleWriter::Recreate(std::move(modelWrite), "myNTuple", fileGuard.GetPath(), options); - constexpr unsigned long nEvents = 1024 * 1024 * 256; // Exceed 2GB file size - for (unsigned int i = 0; i < nEvents; ++i) { + constexpr std::uint64_t nEvents = 1024 * 1024 * 256; // Exceed 2GB file size + for (std::uint64_t i = 0; i < nEvents; ++i) { wrEnergy = rnd.Rndm(); chksumWrite += wrEnergy; ntuple->Fill(); @@ -171,7 +178,9 @@ TEST(RNTuple, LargeFile1) TEST(RNTuple, LargeFile2) { +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif FileRaii fileGuard("test_large_file2.root"); // Start out with a mini-file created small file @@ -195,8 +204,8 @@ TEST(RNTuple, LargeFile2) TRandom3 rnd(42); double chksumWrite = 0.0; - constexpr unsigned long nEvents = 1024 * 1024 * 256; // Exceed 2GB file size - for (unsigned int i = 0; i < nEvents; ++i) { + constexpr std::uint64_t nEvents = 1024 * 1024 * 256; // Exceed 2GB file size + for (std::uint64_t i = 0; i < nEvents; ++i) { *E = rnd.Rndm(); chksumWrite += *E; writer->Fill(); @@ -259,3 +268,74 @@ TEST(RNTuple, LargeFile2) } } #endif + +// FIXME: apparently, this test continues to be broken for some CI configs, which needs to be investigated carefully; +// thus disable temporarily. +#if 0 +TEST(RNTuple, SmallClusters) +{ + FileRaii fileGuard("test_ntuple_small_clusters.root"); + + { + auto model = RNTupleModel::Create(); + auto fldVec = model->MakeField>("vec"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + fldVec->push_back(1.0); + writer->Fill(); + } + { + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + auto desc = reader->GetDescriptor(); + auto colId = desc->FindLogicalColumnId(desc->FindFieldId("vec"), 0); + EXPECT_EQ(EColumnType::kSplitIndex64, desc->GetColumnDescriptor(colId).GetModel().GetType()); + reader->LoadEntry(0); + auto entry = reader->GetModel()->GetDefaultEntry(); + EXPECT_EQ(1u, entry->Get>("vec")->size()); + EXPECT_FLOAT_EQ(1.0, entry->Get>("vec")->at(0)); + } + + { + auto model = RNTupleModel::Create(); + auto fldVec = model->MakeField>("vec"); + RNTupleWriteOptions options; + options.SetHasSmallClusters(true); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath(), options); + fldVec->push_back(1.0); + writer->Fill(); + } + { + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + auto desc = reader->GetDescriptor(); + auto colId = desc->FindLogicalColumnId(desc->FindFieldId("vec"), 0); + EXPECT_EQ(EColumnType::kSplitIndex32, desc->GetColumnDescriptor(colId).GetModel().GetType()); + reader->LoadEntry(0); + auto entry = reader->GetModel()->GetDefaultEntry(); + EXPECT_EQ(1u, entry->Get>("vec")->size()); + EXPECT_FLOAT_EQ(1.0, entry->Get>("vec")->at(0)); + } + + // Throw on attempt to commit cluster > 512MB + auto model = RNTupleModel::Create(); + auto fldVec = model->MakeField>("vec"); + RNTupleWriteOptions options; + options.SetHasSmallClusters(true); + options.SetCompression(0); + options.SetMaxUnzippedClusterSize(1000 * 1000 * 1000); // 1GB + options.SetApproxZippedClusterSize(1000 * 1000 * 1000); // 1GB + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath(), options); + fldVec->push_back(1.0); + // One float and one 32bit integer per entry + constexpr std::size_t nEntries = RNTupleWriteOptions::kMaxSmallClusterSize / (sizeof(float) + sizeof(std::int32_t)); + for (unsigned int i = 0; i < nEntries; ++i) { + writer->Fill(); + } + writer->Fill(); + EXPECT_THROW(writer->CommitCluster(), ROOT::Experimental::RException); + + // On destruction of the writer, the exception in CommitCluster() produces an error log + ROOT::TestSupport::CheckDiagsRAII diagRAII; + diagRAII.requiredDiag(kError, "[ROOT.NTuple]", + "failure committing ntuple: invalid attempt to write a cluster > 512MiB", false /* matchFullMessage */); + writer = nullptr; +} +#endif diff --git a/tree/ntuple/v7/test/ntuple_friends.cxx b/tree/ntuple/v7/test/ntuple_friends.cxx index cf8958e71ddf3..7c05881c0c7fa 100644 --- a/tree/ntuple/v7/test/ntuple_friends.cxx +++ b/tree/ntuple/v7/test/ntuple_friends.cxx @@ -29,7 +29,8 @@ TEST(RPageStorageFriends, Empty) EXPECT_EQ(0u, reader->GetModel()->GetFieldZero()->GetOnDiskId()); EXPECT_EQ(0u, std::distance(reader->GetModel()->GetDefaultEntry()->begin(), reader->GetModel()->GetDefaultEntry()->end())); - EXPECT_EQ(0u, reader->GetDescriptor()->GetNColumns()); + EXPECT_EQ(0u, reader->GetDescriptor()->GetNLogicalColumns()); + EXPECT_EQ(0u, reader->GetDescriptor()->GetNPhysicalColumns()); EXPECT_EQ(1u, reader->GetDescriptor()->GetNFields()); // The zero field EXPECT_EQ(0u, reader->GetDescriptor()->GetNClusters()); } diff --git a/tree/ntuple/v7/test/ntuple_merger.cxx b/tree/ntuple/v7/test/ntuple_merger.cxx index 874517e434be0..269295f56b26f 100644 --- a/tree/ntuple/v7/test/ntuple_merger.cxx +++ b/tree/ntuple/v7/test/ntuple_merger.cxx @@ -29,8 +29,7 @@ TEST(RPageStorage, ReadSealedPages) { RNTupleWriteOptions options; options.SetCompression(0); - RNTupleWriter ntuple(std::move(model), - std::make_unique("myNTuple", fileGuard.GetPath(), RNTupleWriteOptions())); + RNTupleWriter ntuple(std::move(model), std::make_unique("myNTuple", fileGuard.GetPath(), options)); ntuple.Fill(); ntuple.CommitCluster(); for (unsigned i = 0; i < 100000; ++i) { @@ -42,7 +41,7 @@ TEST(RPageStorage, ReadSealedPages) RPageSourceFile source("myNTuple", fileGuard.GetPath(), RNTupleReadOptions()); source.Attach(); auto columnId = - source.GetSharedDescriptorGuard()->FindColumnId(source.GetSharedDescriptorGuard()->FindFieldId("pt"), 0); + source.GetSharedDescriptorGuard()->FindPhysicalColumnId(source.GetSharedDescriptorGuard()->FindFieldId("pt"), 0); // Check first cluster consisting of a single entry RClusterIndex index(source.GetSharedDescriptorGuard()->FindClusterId(columnId, 0), 0); diff --git a/tree/ntuple/v7/test/ntuple_minifile.cxx b/tree/ntuple/v7/test/ntuple_minifile.cxx index 275d69787e2d1..55831a7621145 100644 --- a/tree/ntuple/v7/test/ntuple_minifile.cxx +++ b/tree/ntuple/v7/test/ntuple_minifile.cxx @@ -1,4 +1,5 @@ #include "ntuple_test.hxx" +#include namespace ROOT { namespace Experimental { diff --git a/tree/ntuple/v7/test/ntuple_modelext.cxx b/tree/ntuple/v7/test/ntuple_modelext.cxx new file mode 100644 index 0000000000000..f0f9c7e898356 --- /dev/null +++ b/tree/ntuple/v7/test/ntuple_modelext.cxx @@ -0,0 +1,458 @@ +#include "ntuple_test.hxx" +#include + +namespace { +struct RFieldBaseTest : public ROOT::Experimental::Detail::RFieldBase { + /// Returns the global index of the first entry that has a stored on-disk value. For deferred fields, this allows + /// for differentiating zero-initialized values read before the addition of the field from actual stored data. + NTupleSize_t GetFirstEntry() const + { + auto fnColumnElementIndexToEntry = [&](NTupleSize_t columnElementIndex) -> std::size_t { + std::size_t result = columnElementIndex; + for (auto f = static_cast(this); f != nullptr; f = f->GetParent()) { + auto parent = f->GetParent(); + if (parent && (parent->GetStructure() == ROOT::Experimental::kCollection || + parent->GetStructure() == ROOT::Experimental::kVariant)) + return 0U; + result /= std::max(f->GetNRepetitions(), std::size_t{1U}); + } + return result; + }; + + if (fPrincipalColumn) + return fnColumnElementIndexToEntry(fPrincipalColumn->GetFirstElementIndex()); + if (!fSubFields.empty()) + return static_cast(*fSubFields[0]).GetFirstEntry(); + R__ASSERT(false); + return 0; + } +}; + +static std::size_t GetFirstEntry(const RFieldBase *f) +{ + return static_cast(f)->GetFirstEntry(); +} +} // anonymous namespace + +TEST(RNTuple, ModelExtensionSimple) +{ + FileRaii fileGuard("test_ntuple_modelext_simple.root"); + std::array refArray{1.0, 24.0}; + { + auto model = RNTupleModel::Create(); + auto fieldPt = model->MakeField("pt", 42.0); + + auto ntuple = RNTupleWriter::Recreate(std::move(model), "myNTuple", fileGuard.GetPath()); + ntuple->Fill(); + *fieldPt = 12.0; + ntuple->Fill(); + + auto modelUpdater = ntuple->CreateModelUpdater(); + modelUpdater->BeginUpdate(); + std::array fieldArray = refArray; + modelUpdater->AddField>("array", &fieldArray); + modelUpdater->CommitUpdate(); + + ntuple->Fill(); + *fieldPt = 1.0; + fieldArray[1] = 1337.0; + ntuple->Fill(); + } + + auto ntuple = RNTupleReader::Open("myNTuple", fileGuard.GetPath()); + EXPECT_EQ(4U, ntuple->GetNEntries()); + EXPECT_EQ(4U, ntuple->GetDescriptor()->GetNFields()); + EXPECT_EQ(0U, GetFirstEntry(ntuple->GetModel()->GetField("pt"))); + EXPECT_EQ(2U, GetFirstEntry(ntuple->GetModel()->GetField("array"))); + + auto pt = ntuple->GetView("pt"); + auto array = ntuple->GetView>("array"); + EXPECT_EQ(42.0, pt(0)); + EXPECT_EQ(12.0, pt(1)); + EXPECT_EQ(12.0, pt(2)); + EXPECT_EQ(1.0, pt(3)); + + // There is no on-disk data for this field before entry 2, i.e., entry range [0..1] yields zeroes + EXPECT_EQ((std::array{0.0, 0.0}), array(0)); + EXPECT_EQ((std::array{0.0, 0.0}), array(1)); + EXPECT_EQ(refArray, array(2)); + EXPECT_EQ(1337.0, array(3)[1]); +} + +TEST(RNTuple, ModelExtensionInvalidUse) +{ + FileRaii fileGuard("test_ntuple_modelext_invalid.root"); + { + auto model = RNTupleModel::Create(); + auto fieldPt = model->MakeField("pt", 42.0); + + auto ntuple = RNTupleWriter::Recreate(std::move(model), "myNTuple", fileGuard.GetPath()); + auto entry = ntuple->GetModel()->CreateEntry(); + + auto modelUpdater = ntuple->CreateModelUpdater(); + modelUpdater->BeginUpdate(); + double d; + modelUpdater->AddField("d", &d); + // Cannot fill if the model is not frozen + EXPECT_THROW(ntuple->Fill(), ROOT::Experimental::RException); + // Trying to create an entry should throw if model is not frozen + EXPECT_THROW((void)ntuple->GetModel()->CreateEntry(), ROOT::Experimental::RException); + modelUpdater->CommitUpdate(); + + // Using an entry that does not match the model should throw + EXPECT_THROW(ntuple->Fill(*entry), ROOT::Experimental::RException); + + ntuple->Fill(); + auto entry2 = ntuple->GetModel()->CreateEntry(); + ntuple->Fill(*entry2); + + ntuple->Fill(); + } + + auto ntuple = RNTupleReader::Open("myNTuple", fileGuard.GetPath()); + EXPECT_EQ(3U, ntuple->GetNEntries()); + EXPECT_EQ(3U, ntuple->GetDescriptor()->GetNFields()); +} + +TEST(RNTuple, ModelExtensionMultiple) +{ + FileRaii fileGuard("test_ntuple_modelext_multiple.root"); + std::vector refVec{0x00, 0xff, 0x55, 0xaa}; + { + auto model = RNTupleModel::Create(); + auto fieldPt = model->MakeField("pt", 42.0); + + auto ntuple = RNTupleWriter::Recreate(std::move(model), "myNTuple", fileGuard.GetPath()); + ntuple->Fill(); + *fieldPt = 2.0; + ntuple->Fill(); + ntuple->CommitCluster(); + *fieldPt = 4.0; + ntuple->Fill(); + + auto modelUpdater = ntuple->CreateModelUpdater(); + modelUpdater->BeginUpdate(); + std::vector fieldVec{0x11223344}; + modelUpdater->AddField>("vec", &fieldVec); + modelUpdater->CommitUpdate(); + + modelUpdater->BeginUpdate(); + float fieldFloat = 10.0; + modelUpdater->AddField("f", &fieldFloat); + modelUpdater->CommitUpdate(); + + modelUpdater->BeginUpdate(); + std::uint8_t u8 = 0x7f; + std::string str{"default"}; + modelUpdater->AddField("u8", &u8); + modelUpdater->AddField("str", &str); + modelUpdater->CommitUpdate(); + + ntuple->Fill(); + *fieldPt = 12.0; + fieldFloat = 1.0; + fieldVec = refVec; + u8 = 0xaa; + str = "abcdefABCDEF1234567890!@#$%^&*()"; + ntuple->Fill(); + } + + auto ntuple = RNTupleReader::Open("myNTuple", fileGuard.GetPath()); + EXPECT_EQ(5U, ntuple->GetNEntries()); + EXPECT_EQ(7U, ntuple->GetDescriptor()->GetNFields()); + EXPECT_EQ(0U, GetFirstEntry(ntuple->GetModel()->GetField("pt"))); + EXPECT_EQ(3U, GetFirstEntry(ntuple->GetModel()->GetField("vec"))); + EXPECT_EQ(3U, GetFirstEntry(ntuple->GetModel()->GetField("f"))); + EXPECT_EQ(3U, GetFirstEntry(ntuple->GetModel()->GetField("u8"))); + EXPECT_EQ(3U, GetFirstEntry(ntuple->GetModel()->GetField("str"))); + + auto pt = ntuple->GetView("pt"); + auto vec = ntuple->GetView>("vec"); + auto f = ntuple->GetView("f"); + auto u8 = ntuple->GetView("u8"); + auto str = ntuple->GetView("str"); + EXPECT_EQ(42.0, pt(0)); + EXPECT_EQ(2.0, pt(1)); + EXPECT_EQ(4.0, pt(2)); + EXPECT_EQ(4.0, pt(3)); + EXPECT_EQ(12.0, pt(4)); + + EXPECT_EQ(std::vector{}, vec(0)); + EXPECT_EQ(std::vector{}, vec(1)); + EXPECT_EQ(std::vector{}, vec(2)); + EXPECT_EQ(std::vector{0x11223344}, vec(3)); + EXPECT_EQ(refVec, vec(4)); + + EXPECT_EQ(0.0, f(0)); + EXPECT_EQ(0.0, f(1)); + EXPECT_EQ(0.0, f(2)); + EXPECT_EQ(10.0, f(3)); + EXPECT_EQ(1.0, f(4)); + + EXPECT_EQ(0x00, u8(0)); + EXPECT_EQ(0x00, u8(1)); + EXPECT_EQ(0x00, u8(2)); + EXPECT_EQ(0x7f, u8(3)); + EXPECT_EQ(0xaa, u8(4)); + + EXPECT_TRUE(str(0).empty()); + EXPECT_TRUE(str(1).empty()); + EXPECT_TRUE(str(2).empty()); + EXPECT_EQ("default", str(3)); + EXPECT_EQ("abcdefABCDEF1234567890!@#$%^&*()", str(4)); +} + +TEST(RNTuple, ModelExtensionProject) +{ + FileRaii fileGuard("test_ntuple_modelext_project.root"); + std::vector refVec{0x00, 0xff, 0x55, 0xaa}; + { + auto model = RNTupleModel::Create(); + auto fieldPt = model->MakeField("pt", 42.0); + + auto ntuple = RNTupleWriter::Recreate(std::move(model), "myNTuple", fileGuard.GetPath()); + auto modelUpdater = ntuple->CreateModelUpdater(); + modelUpdater->BeginUpdate(); + std::vector fieldVec; + modelUpdater->AddField>("vec", &fieldVec); + modelUpdater->CommitUpdate(); + + modelUpdater->BeginUpdate(); + auto aliasVec = RFieldBase::Create("aliasVec", "std::vector").Unwrap(); + modelUpdater->AddProjectedField(std::move(aliasVec), [](const std::string &fieldName) { + if (fieldName == "aliasVec") + return "vec"; + else + return "vec._0"; + }); + modelUpdater->CommitUpdate(); + + ntuple->Fill(); + *fieldPt = 12.0; + fieldVec = refVec; + ntuple->Fill(); + } + + auto ntuple = RNTupleReader::Open("myNTuple", fileGuard.GetPath()); + EXPECT_EQ(2U, ntuple->GetNEntries()); + EXPECT_EQ(6U, ntuple->GetDescriptor()->GetNFields()); + + auto pt = ntuple->GetView("pt"); + auto aliasVec = ntuple->GetView>("aliasVec"); + EXPECT_EQ(42.0, pt(0)); + EXPECT_EQ(12.0, pt(1)); + EXPECT_EQ(std::vector{}, aliasVec(0)); + EXPECT_EQ(refVec, aliasVec(1)); +} + +// Based on the RealWorld1 test in `ntuple_extended.cxx`, but here some fields are added after the fact +TEST(RNTuple, ModelExtensionRealWorld1) +{ +#ifdef R__USE_IMT + ROOT::EnableImplicitMT(); +#endif + FileRaii fileGuard("test_ntuple_modelext_realworld1.root"); + + // See https://github.com/olifre/root-io-bench/blob/master/benchmark.cpp + auto modelWrite = RNTupleModel::Create(); + auto wrEvent = modelWrite->MakeField("event"); + auto wrSignal = modelWrite->MakeField("signal"); + auto wrTimes = modelWrite->MakeField>("times"); + + TRandom3 rnd(42); + double chksumWrite = 0.0; + { + auto ntuple = RNTupleWriter::Recreate(std::move(modelWrite), "myNTuple", fileGuard.GetPath()); + + auto modelUpdater = ntuple->CreateModelUpdater(); + modelUpdater->BeginUpdate(); + std::vector fieldVec; + double wrEnergy; + std::vector wrIndices; + modelUpdater->AddField("energy", &wrEnergy); + modelUpdater->AddField>("indices", &wrIndices); + modelUpdater->CommitUpdate(); + + constexpr unsigned int nEvents = 60000; + for (unsigned int i = 0; i < nEvents; ++i) { + *wrEvent = i; + wrEnergy = rnd.Rndm() * 1000.; + *wrSignal = i % 2; + + chksumWrite += double(*wrEvent); + chksumWrite += double(*wrSignal); + chksumWrite += wrEnergy; + + auto nTimes = 1 + floor(rnd.Rndm() * 1000.); + wrTimes->resize(nTimes); + for (unsigned int n = 0; n < nTimes; ++n) { + wrTimes->at(n) = 1 + rnd.Rndm() * 1000. - 500.; + chksumWrite += wrTimes->at(n); + } + + auto nIndices = 1 + floor(rnd.Rndm() * 1000.); + wrIndices.resize(nIndices); + for (unsigned int n = 0; n < nIndices; ++n) { + wrIndices.at(n) = 1 + floor(rnd.Rndm() * 1000.); + chksumWrite += double(wrIndices.at(n)); + } + + ntuple->Fill(); + } + } + + auto modelRead = RNTupleModel::Create(); + auto rdEvent = modelRead->MakeField("event"); + auto rdSignal = modelRead->MakeField("signal"); + auto rdEnergy = modelRead->MakeField("energy"); + auto rdTimes = modelRead->MakeField>("times"); + auto rdIndices = modelRead->MakeField>("indices"); + + double chksumRead = 0.0; + auto ntuple = RNTupleReader::Open(std::move(modelRead), "myNTuple", fileGuard.GetPath()); + for (auto entryId : *ntuple) { + ntuple->LoadEntry(entryId); + chksumRead += double(*rdEvent) + double(*rdSignal) + *rdEnergy; + for (auto t : *rdTimes) + chksumRead += t; + for (auto ind : *rdIndices) + chksumRead += double(ind); + } + + // The floating point arithmetic should have been executed in the same order for reading and writing, + // thus we expect the checksums to be bitwise identical + EXPECT_EQ(chksumRead, chksumWrite); +} + +TEST(RNTuple, ModelExtensionComplex) +{ + using doubleAoA_t = std::array, 2>; +#ifdef R__USE_IMT + ROOT::EnableImplicitMT(); +#endif + FileRaii fileGuard("test_ntuple_modelext_complex.root"); + + TRandom3 rnd(42); + double chksumWrite = 0.0; + auto updateInitialFields = [&](unsigned entryId, std::uint32_t &u32, double &dbl) { + u32 = entryId; + dbl = rnd.Rndm() * 1000.; + chksumWrite += static_cast(u32); + chksumWrite += dbl; + }; + auto updateLateFields1 = [&](unsigned entryId, std::vector &vec, doubleAoA_t &aoa) { + auto size = 1 + floor(rnd.Rndm() * 1000.); + vec.resize(size); + for (unsigned i = 0; i < size; ++i) { + vec[i] = 1 + rnd.Rndm() * 1000. - 500.; + chksumWrite += vec[i]; + } + aoa = {{{0.0, static_cast(entryId)}, {42.0, static_cast(entryId)}}}; + chksumWrite += (aoa[0][0] + aoa[0][1]) + (aoa[1][0] + aoa[1][1]); + }; + auto updateLateFields2 = [&](unsigned entryId, std::variant &var) { + if ((entryId % 2) == 0) { + std::uint64_t value = entryId + 1; + var = value; + chksumWrite += static_cast(value); + } else { + double value = entryId; + var = value; + chksumWrite += value; + } + }; + + { + auto modelWrite = RNTupleModel::Create(); + auto u32 = modelWrite->MakeField("u32"); + auto dbl = modelWrite->MakeField("dbl"); + auto ntuple = RNTupleWriter::Recreate(std::move(modelWrite), "myNTuple", fileGuard.GetPath()); + // The model is to be extended below with new fields every 10000 entries + auto modelUpdater = ntuple->CreateModelUpdater(); + for (unsigned int i = 0; i < 10000; ++i) { + updateInitialFields(i, *u32, *dbl); + ntuple->Fill(); + } + + // Force the serialization of a page list which will not know about the deferred columns coming later. + // `RClusterDescriptorBuilder::AddDeferredColumnRanges()` should thus make up page ranges for the missing columns + ntuple->CommitCluster(true /* commitClusterGroup */); + + modelUpdater->BeginUpdate(); + std::vector dblVec; + doubleAoA_t doubleAoA; + modelUpdater->AddField>("dblVec", &dblVec); + modelUpdater->AddField("doubleAoA", &doubleAoA); + modelUpdater->CommitUpdate(); + for (unsigned int i = 10000; i < 20000; ++i) { + updateInitialFields(i, *u32, *dbl); + updateLateFields1(i, dblVec, doubleAoA); + ntuple->Fill(); + } + + // A `R(Column|Page)Range` should also be generated in the previous cluster for the columns associated to the + // `std::variant` field below + ntuple->CommitCluster(); + + modelUpdater->BeginUpdate(); + std::variant var; + modelUpdater->AddField>("var", &var); + modelUpdater->CommitUpdate(); + for (unsigned int i = 20000; i < 30000; ++i) { + updateInitialFields(i, *u32, *dbl); + updateLateFields1(i, dblVec, doubleAoA); + updateLateFields2(i, var); + ntuple->Fill(); + } + + modelUpdater->BeginUpdate(); + bool b = false; + EmptyStruct noColumns{}; + modelUpdater->AddField("b", &b); + modelUpdater->AddField("noColumns", &noColumns); + modelUpdater->CommitUpdate(); + for (unsigned int i = 30000; i < 40000; ++i) { + updateInitialFields(i, *u32, *dbl); + updateLateFields1(i, dblVec, doubleAoA); + updateLateFields2(i, var); + b = !b; + chksumWrite += static_cast(b); + ntuple->Fill(); + } + } + + auto modelRead = RNTupleModel::Create(); + auto u32 = modelRead->MakeField("u32"); + auto dbl = modelRead->MakeField("dbl"); + auto dblVec = modelRead->MakeField>("dblVec"); + auto doubleAoA = modelRead->MakeField("doubleAoA"); + auto var = modelRead->MakeField>("var"); + auto b = modelRead->MakeField("b"); + auto noColumns = modelRead->MakeField("noColumns"); + + double chksumRead = 0.0; + auto ntuple = RNTupleReader::Open(std::move(modelRead), "myNTuple", fileGuard.GetPath()); + EXPECT_EQ(40000U, ntuple->GetNEntries()); + for (auto entryId : *ntuple) { + ntuple->LoadEntry(entryId); + chksumRead += static_cast(*u32) + *dbl; + for (auto d : *dblVec) + chksumRead += d; + chksumRead += ((*doubleAoA)[0][0] + (*doubleAoA)[0][1]) + ((*doubleAoA)[1][0] + (*doubleAoA)[1][1]); + if (entryId < 20000) { + EXPECT_FALSE(std::holds_alternative(*var) || std::holds_alternative(*var)); + continue; + } + if ((entryId % 2) == 0) { + chksumRead += std::get(*var); + } else { + chksumRead += std::get(*var); + } + chksumRead += static_cast(*b); + (void)*noColumns; + } + + // The floating point arithmetic should have been executed in the same order for reading and writing, + // thus we expect the checksums to be bitwise identical + EXPECT_EQ(chksumRead, chksumWrite); +} diff --git a/tree/ntuple/v7/test/ntuple_packing.cxx b/tree/ntuple/v7/test/ntuple_packing.cxx index f12fe8880f2d4..de4cfde00e5e9 100644 --- a/tree/ntuple/v7/test/ntuple_packing.cxx +++ b/tree/ntuple/v7/test/ntuple_packing.cxx @@ -1,8 +1,65 @@ #include "ntuple_test.hxx" +#include +#include +#include // for memcmp +#include +#include +#include + +template +struct Helper { + using Pod_t = PodT; + using Narrow_t = NarrowT; + static constexpr ROOT::Experimental::EColumnType kColumnType = ColumnT; +}; + +template +struct Helper { + using Pod_t = std::uint64_t; + using Narrow_t = NarrowT; + static constexpr ROOT::Experimental::EColumnType kColumnType = ColumnT; +}; + +template +class PackingInt : public ::testing::Test { +public: + using Helper_t = HelperT; +}; + +template +class PackingReal : public ::testing::Test { +public: + using Helper_t = HelperT; +}; + +template +class PackingIndex : public ::testing::Test { +public: + using Helper_t = HelperT; +}; + +using PackingRealTypes = ::testing::Types, + Helper>; +TYPED_TEST_SUITE(PackingReal, PackingRealTypes); + +using PackingIntTypes = + ::testing::Types, + Helper, + Helper, + Helper, + Helper, + Helper>; +TYPED_TEST_SUITE(PackingInt, PackingIntTypes); + +using PackingIndexTypes = ::testing::Types< + Helper, + Helper>; +TYPED_TEST_SUITE(PackingIndex, PackingIndexTypes); + TEST(Packing, Bitfield) { - ROOT::Experimental::Detail::RColumnElement element(nullptr); + ROOT::Experimental::Detail::RColumnElement element; element.Pack(nullptr, nullptr, 0); element.Unpack(nullptr, nullptr, 0); @@ -37,7 +94,7 @@ TEST(Packing, RColumnSwitch) { ROOT::Experimental::Detail::RColumnElement - element(nullptr); + element; element.Pack(nullptr, nullptr, 0); element.Unpack(nullptr, nullptr, 0); @@ -50,3 +107,199 @@ TEST(Packing, RColumnSwitch) EXPECT_EQ(0xaa, s2.GetIndex()); EXPECT_EQ(0x55, s2.GetTag()); } + +TYPED_TEST(PackingReal, SplitReal) +{ + using Pod_t = typename TestFixture::Helper_t::Pod_t; + using Narrow_t = typename TestFixture::Helper_t::Narrow_t; + + ROOT::Experimental::Detail::RColumnElement element; + element.Pack(nullptr, nullptr, 0); + element.Unpack(nullptr, nullptr, 0); + + std::array mem{0.0, + 42.0, + std::numeric_limits::min(), + std::numeric_limits::max(), + std::numeric_limits::lowest(), + std::numeric_limits::infinity(), + std::numeric_limits::denorm_min()}; + std::array packed; + std::array cmp; + + element.Pack(packed.data(), mem.data(), 7); + element.Unpack(cmp.data(), packed.data(), 7); + + EXPECT_EQ(mem, cmp); +} + +TYPED_TEST(PackingInt, SplitInt) +{ + using Pod_t = typename TestFixture::Helper_t::Pod_t; + using Narrow_t = typename TestFixture::Helper_t::Narrow_t; + + ROOT::Experimental::Detail::RColumnElement element; + element.Pack(nullptr, nullptr, 0); + element.Unpack(nullptr, nullptr, 0); + + std::array mem{0, std::is_signed_v ? -42 : 1, 42, std::numeric_limits::min(), + std::numeric_limits::min() + 1, std::numeric_limits::min() + 2, + std::numeric_limits::max(), std::numeric_limits::max() - 1, + std::numeric_limits::max() - 2}; + std::array packed; + std::array cmp; + + element.Pack(packed.data(), mem.data(), 9); + element.Unpack(cmp.data(), packed.data(), 9); + + EXPECT_EQ(mem, cmp); +} + +TYPED_TEST(PackingIndex, SplitIndex) +{ + using Pod_t = typename TestFixture::Helper_t::Pod_t; + using Narrow_t = typename TestFixture::Helper_t::Narrow_t; + + ROOT::Experimental::Detail::RColumnElement element; + element.Pack(nullptr, nullptr, 0); + element.Unpack(nullptr, nullptr, 0); + + std::array mem{0, 1, 1, 42, std::numeric_limits::max()}; + std::array packed; + std::array cmp; + + element.Pack(packed.data(), mem.data(), 5); + element.Unpack(cmp.data(), packed.data(), 5); + + EXPECT_EQ(mem, cmp); +} + +namespace { + +template +static void AddField(RNTupleModel &model, const std::string &fieldName) +{ + auto fld = std::make_unique>(fieldName); + fld->SetColumnRepresentative({ColumnT}); + model.AddField(std::move(fld)); +} + +} // anonymous namespace + +TEST(Packing, OnDiskEncoding) +{ + FileRaii fileGuard("test_ntuple_packing_ondiskencoding.root"); + + constexpr std::size_t kPageSize = 16; // minimum page size for two 8 byte elements + + auto model = RNTupleModel::Create(); + + AddField(*model, "int16"); + AddField(*model, "int32"); + AddField(*model, "int64"); + AddField(*model, "uint16"); + AddField(*model, "uint32"); + AddField(*model, "uint64"); + AddField(*model, "float"); + AddField(*model, "double"); + AddField(*model, "index32"); + AddField(*model, "index64"); + auto fldStr = std::make_unique>("str"); + model->AddField(std::move(fldStr)); + { + RNTupleWriteOptions options; + options.SetCompression(0); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath(), options); + auto e = writer->CreateEntry(); + + *e->Get("int16") = 1; + *e->Get("int32") = 0x00010203; + *e->Get("int64") = 0x0001020304050607L; + *e->Get("uint16") = 1; + *e->Get("uint32") = 0x00010203; + *e->Get("uint64") = 0x0001020304050607L; + *e->Get("float") = std::nextafterf(1.f, 2.f); // 0 01111111 00000000000000000000001 == 0x3f800001 + *e->Get("double") = std::nextafter(1., 2.); // 0x3ff0 0000 0000 0001 + *e->Get("index32") = 39916801; // 0x0261 1501 + *e->Get("index64") = 0x0706050403020100L; + e->Get("str")->assign("abc"); + + writer->Fill(*e); + + *e->Get("int16") = -3; + *e->Get("int32") = -0x04050607; + *e->Get("int64") = -0x08090a0b0c0d0e0fL; + *e->Get("uint16") = 2; + *e->Get("uint32") = 0x04050607; + *e->Get("uint64") = 0x08090a0b0c0d0e0fL; + *e->Get("float") = std::nextafterf(1.f, 0.f); // 0 01111110 11111111111111111111111 = 0x3f7fffff + *e->Get("double") = std::numeric_limits::max(); // 0x7fef ffff ffff ffff + *e->Get("index32") = 39916808; // d(previous) == 7 + *e->Get("index64") = 0x070605040302010DL; // d(previous) == 13 + e->Get("str")->assign("de"); + + writer->Fill(*e); + } + + auto source = RPageSource::Create("ntuple", fileGuard.GetPath()); + source->Attach(); + + char buf[2 * kPageSize]; + RPageStorage::RSealedPage sealedPage(buf, 2 * kPageSize, 0); + + auto fnGetColumnId = [&source](const std::string &fieldName) { + auto descGuard = source->GetSharedDescriptorGuard(); + return descGuard->FindPhysicalColumnId(descGuard->FindFieldId(fieldName), 0); + }; + + source->LoadSealedPage(fnGetColumnId("int16"), RClusterIndex(0, 0), sealedPage); + unsigned char expInt16[] = {0x02, 0x05, 0x00, 0x00}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expInt16, sizeof(expInt16)), 0); + + source->LoadSealedPage(fnGetColumnId("int32"), RClusterIndex(0, 0), sealedPage); + unsigned char expInt32[] = {0x06, 0x0d, 0x04, 0x0c, 0x02, 0x0a, 0x00, 0x08}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expInt32, sizeof(expInt32)), 0); + + source->LoadSealedPage(fnGetColumnId("int64"), RClusterIndex(0, 0), sealedPage); + unsigned char expInt64[] = {0x0e, 0x1d, 0x0c, 0x1c, 0x0a, 0x1a, 0x08, 0x18, + 0x06, 0x16, 0x04, 0x14, 0x02, 0x12, 0x00, 0x10}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expInt64, sizeof(expInt64)), 0); + + source->LoadSealedPage(fnGetColumnId("uint16"), RClusterIndex(0, 0), sealedPage); + unsigned char expUInt16[] = {0x01, 0x02, 0x00, 0x00}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expUInt16, sizeof(expUInt16)), 0); + + source->LoadSealedPage(fnGetColumnId("uint32"), RClusterIndex(0, 0), sealedPage); + unsigned char expUInt32[] = {0x03, 0x07, 0x02, 0x06, 0x01, 0x05, 0x00, 0x04}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expUInt32, sizeof(expUInt32)), 0); + + source->LoadSealedPage(fnGetColumnId("uint64"), RClusterIndex(0, 0), sealedPage); + unsigned char expUInt64[] = {0x07, 0x0f, 0x06, 0x0e, 0x05, 0x0d, 0x04, 0x0c, + 0x03, 0x0b, 0x02, 0x0a, 0x01, 0x09, 0x00, 0x08}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expUInt64, sizeof(expUInt64)), 0); + + source->LoadSealedPage(fnGetColumnId("float"), RClusterIndex(0, 0), sealedPage); + unsigned char expFloat[] = {0x01, 0xff, 0x00, 0xff, 0x80, 0x7f, 0x3f, 0x3f}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expFloat, sizeof(expFloat)), 0); + + source->LoadSealedPage(fnGetColumnId("double"), RClusterIndex(0, 0), sealedPage); + unsigned char expDouble[] = {0x01, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, + 0x00, 0xff, 0x00, 0xff, 0xf0, 0xef, 0x3f, 0x7f}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expDouble, sizeof(expDouble)), 0); + + source->LoadSealedPage(fnGetColumnId("index32"), RClusterIndex(0, 0), sealedPage); + unsigned char expIndex32[] = {0x01, 0x07, 0x15, 0x00, 0x61, 0x00, 0x02, 0x00}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expIndex32, sizeof(expIndex32)), 0); + + source->LoadSealedPage(fnGetColumnId("index64"), RClusterIndex(0, 0), sealedPage); + unsigned char expIndex64[] = {0x00, 0x0D, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, + 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00}; + EXPECT_EQ(memcmp(sealedPage.fBuffer, expIndex64, sizeof(expIndex64)), 0); + + auto reader = RNTupleReader(std::move(source)); + EXPECT_EQ(EColumnType::kIndex64, reader.GetModel()->GetField("str")->GetColumnRepresentative()[0]); + EXPECT_EQ(2u, reader.GetNEntries()); + auto viewStr = reader.GetView("str"); + EXPECT_EQ(std::string("abc"), viewStr(0)); + EXPECT_EQ(std::string("de"), viewStr(1)); +} diff --git a/tree/ntuple/v7/test/ntuple_project.cxx b/tree/ntuple/v7/test/ntuple_project.cxx new file mode 100644 index 0000000000000..91a9940fa897c --- /dev/null +++ b/tree/ntuple/v7/test/ntuple_project.cxx @@ -0,0 +1,146 @@ +#include "ntuple_test.hxx" + +TEST(RNTupleProjection, Basics) +{ + FileRaii fileGuard("test_ntuple_projection_basics.root"); + + auto model = RNTupleModel::Create(); + model->MakeField("met", 42.0); + auto fvec = model->MakeField>("vec"); + fvec->emplace_back(1.0); + fvec->emplace_back(2.0); + + auto f1 = RFieldBase::Create("missingE", "float").Unwrap(); + model->AddProjectedField(std::move(f1), [](const std::string &) { return "met"; }); + auto f2 = RFieldBase::Create("aliasVec", "std::vector").Unwrap(); + model->AddProjectedField(std::move(f2), [](const std::string &fieldName) { + if (fieldName == "aliasVec") + return "vec"; + else + return "vec._0"; + }); + auto f3 = RFieldBase::Create("vecSize", "ROOT::Experimental::RNTupleCardinality").Unwrap(); + model->AddProjectedField(std::move(f3), [](const std::string &) { return "vec"; }); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "A", fileGuard.GetPath()); + writer->Fill(); + } + + auto reader = RNTupleReader::Open("A", fileGuard.GetPath()); + auto viewMissingE = reader->GetView("missingE"); + auto viewAliasVec = reader->GetView>("aliasVec"); + auto viewVecSize = reader->GetView>("vecSize"); + EXPECT_FLOAT_EQ(42.0, viewMissingE(0)); + EXPECT_EQ(2U, viewAliasVec(0).size()); + EXPECT_FLOAT_EQ(1.0, viewAliasVec(0).at(0)); + EXPECT_FLOAT_EQ(2.0, viewAliasVec(0).at(1)); + EXPECT_EQ(2U, viewVecSize(0)); +} + +TEST(RNTupleProjection, CatchInvalidMappings) +{ + FileRaii fileGuard("test_ntuple_projection_catch_invalid_mappings.root"); + + auto model = RNTupleModel::Create(); + model->MakeField("met", 42.0); + model->MakeField>("vec"); + model->MakeField>("variant"); + model->MakeField>>("nnlo"); + + auto f1 = RFieldBase::Create("fail", "float").Unwrap(); + try { + model->AddProjectedField(std::move(f1), [](const std::string &) { return "na"; }).ThrowOnError(); + FAIL() << "mapping to unknown field should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("no such field")); + } + + auto f2 = RFieldBase::Create("fail", "std::vector").Unwrap(); + try { + model + ->AddProjectedField(std::move(f2), + [](const std::string &name) { + if (name == "fail") + return "vec"; + else + return "na"; + }) + .ThrowOnError(); + FAIL() << "mapping to unknown field should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("no such field")); + } + + auto f3 = RFieldBase::Create("fail", "std::vector").Unwrap(); + try { + model->AddProjectedField(std::move(f3), [](const std::string &) { return "met"; }).ThrowOnError(); + FAIL() << "mapping with structural mismatch should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("field mapping structural mismatch")); + } + + auto f4 = RFieldBase::Create("fail", "int").Unwrap(); + try { + model->AddProjectedField(std::move(f4), [](const std::string &) { return "met"; }).ThrowOnError(); + FAIL() << "mapping without matching type should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("field mapping type mismatch")); + } + + auto f5 = RFieldBase::Create("fail", "std::variant").Unwrap(); + try { + model + ->AddProjectedField(std::move(f5), + [](const std::string &fieldName) { + if (fieldName == "fail") + return "variant"; + if (fieldName == "fail._0") + return "variant._0"; + return "variant._1"; + }) + .ThrowOnError(); + FAIL() << "mapping of variant should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("unsupported field mapping ")); + } + + auto f6 = RFieldBase::Create("fail", "std::vector").Unwrap(); + try { + model + ->AddProjectedField(std::move(f6), + [](const std::string &fieldName) { + if (fieldName == "fail") + return "nnlo._0"; + return "nnlo._0._0"; + }) + .ThrowOnError(); + FAIL() << "mapping scrambling the source structure should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("field mapping structure mismatch")); + } +} + +TEST(RNTupleProjection, CatchReaderWithProjectedFields) +{ + FileRaii fileGuard("test_ntuple_projection_catch_reader_with_projected_fields.root"); + + auto model = RNTupleModel::Create(); + model->MakeField("met", 42.0); + + auto f1 = RFieldBase::Create("missingE", "float").Unwrap(); + model->AddProjectedField(std::move(f1), [](const std::string &) { return "met"; }); + + auto modelRead = model->Clone(); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "A", fileGuard.GetPath()); + } + + try { + auto reader = RNTupleReader::Open(std::move(modelRead), "A", fileGuard.GetPath()); + FAIL() << "creating a reader with a model with projected fields should throw"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("model has projected fields")); + } +} diff --git a/tree/ntuple/v7/test/ntuple_rdf.cxx b/tree/ntuple/v7/test/ntuple_rdf.cxx deleted file mode 100644 index b15717a064c4d..0000000000000 --- a/tree/ntuple/v7/test/ntuple_rdf.cxx +++ /dev/null @@ -1,50 +0,0 @@ -#include "ntuple_test.hxx" - -TEST(RNTuple, RDF) -{ - FileRaii fileGuard("test_ntuple_rdf.root"); - - auto modelWrite = RNTupleModel::Create(); - - auto trackModel = RNTupleModel::Create(); - auto wrTrackEnergy = trackModel->MakeField("energy", 0.0); - auto wrTracks = modelWrite->MakeCollection("tracks", std::move(trackModel)); - - auto wrPt = modelWrite->MakeField("pt", 42.0); - auto wrEnergy = modelWrite->MakeField("energy", 7.0); - auto wrTag = modelWrite->MakeField("tag", "xyz"); - auto wrJets = modelWrite->MakeField>("jets"); - - wrJets->push_back(1.0); - wrJets->push_back(2.0); - auto wrNnlo = modelWrite->MakeField>>("nnlo"); - wrNnlo->push_back(std::vector()); - wrNnlo->push_back(std::vector{1.0}); - wrNnlo->push_back(std::vector{1.0, 2.0, 4.0, 8.0}); - auto wrKlass = modelWrite->MakeField("klass"); - wrKlass->s = "abc"; - wrKlass->v1.push_back(100.); - wrKlass->v1.push_back(200.); - wrKlass->v1.push_back(300.); - - { - auto ntuple = RNTupleWriter::Recreate(std::move(modelWrite), "myNTuple", fileGuard.GetPath()); - *wrTrackEnergy = 13.0; - wrTracks->Fill(); - *wrTrackEnergy = 17.0; - wrTracks->Fill(); - ntuple->Fill(); - } - - ROOT::EnableImplicitMT(); - auto f = std::unique_ptr(TFile::Open(fileGuard.GetPath().c_str())); - auto rdf = ROOT::RDF::Experimental::FromRNTuple(f->Get("myNTuple")); - EXPECT_EQ(42.0, *rdf.Min("pt")); - EXPECT_EQ(17.0, *rdf.Max("tracks.energy")); - EXPECT_EQ(2U, *rdf.Max("R_rdf_sizeof_tracks")); - auto s = rdf.Take("klass.s"); - EXPECT_EQ(1ull, s.GetValue().size()); - EXPECT_EQ(std::string("abc"), s.GetValue()[0]); - EXPECT_EQ(2U, *rdf.Min("R_rdf_sizeof_jets")); - EXPECT_EQ(3U, *rdf.Min("R_rdf_sizeof_klass.v1")); -} diff --git a/tree/ntuple/v7/test/ntuple_serialize.cxx b/tree/ntuple/v7/test/ntuple_serialize.cxx index fbe2231655085..41a13c83fca7b 100644 --- a/tree/ntuple/v7/test/ntuple_serialize.cxx +++ b/tree/ntuple/v7/test/ntuple_serialize.cxx @@ -485,6 +485,12 @@ TEST(RNTuple, SerializeHeader) .Structure(ENTupleStructure::kLeaf) .MakeDescriptor() .Unwrap()); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(24) + .FieldName("ptAlias") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); builder.AddField(RFieldDescriptorBuilder() .FieldId(137) .FieldName("jet") @@ -498,11 +504,13 @@ TEST(RNTuple, SerializeHeader) .MakeDescriptor() .Unwrap()); builder.AddFieldLink(0, 42); + builder.AddFieldLink(0, 24); builder.AddFieldLink(0, 137); builder.AddFieldLink(137, 13); - builder.AddColumn(23, 42, RColumnModel(EColumnType::kReal32, false), 0); - builder.AddColumn(17, 137, RColumnModel(EColumnType::kIndex, true), 0); - builder.AddColumn(40, 137, RColumnModel(EColumnType::kByte, true), 1); + builder.AddColumn(23, 23, 42, RColumnModel(EColumnType::kReal32, false), 0); + builder.AddColumn(100, 23, 24, RColumnModel(EColumnType::kReal32, false), 0); + builder.AddColumn(17, 17, 137, RColumnModel(EColumnType::kIndex32, true), 0); + builder.AddColumn(40, 40, 137, RColumnModel(EColumnType::kByte, true), 1); auto desc = builder.MoveDescriptor(); auto context = RNTupleSerializer::SerializeHeaderV1(nullptr, desc); @@ -511,6 +519,13 @@ TEST(RNTuple, SerializeHeader) context = RNTupleSerializer::SerializeHeaderV1(buffer.get(), desc); RNTupleSerializer::DeserializeHeaderV1(buffer.get(), context.GetHeaderSize(), builder); + + desc = builder.MoveDescriptor(); + auto ptAliasFieldId = desc.FindFieldId("ptAlias"); + auto colId = desc.FindLogicalColumnId(ptAliasFieldId, 0); + EXPECT_TRUE(desc.GetColumnDescriptor(colId).IsAliasColumn()); + auto ptFieldId = desc.FindFieldId("pt"); + EXPECT_EQ(desc.FindLogicalColumnId(ptFieldId, 0), desc.GetColumnDescriptor(colId).GetPhysicalId()); } @@ -531,13 +546,13 @@ TEST(RNTuple, SerializeFooter) .MakeDescriptor() .Unwrap()); builder.AddFieldLink(0, 42); - builder.AddColumn(17, 42, RColumnModel(EColumnType::kIndex, true), 0); + builder.AddColumn(17, 17, 42, RColumnModel(EColumnType::kIndex32, true), 0); ROOT::Experimental::RClusterDescriptor::RColumnRange columnRange; ROOT::Experimental::RClusterDescriptor::RPageRange::RPageInfo pageInfo; RClusterDescriptorBuilder clusterBuilder(84, 0, 100); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange; - pageRange.fColumnId = 17; + pageRange.fPhysicalColumnId = 17; pageInfo.fNElements = 100; pageInfo.fLocator.fPosition = 7000U; pageRange.fPageInfos.emplace_back(pageInfo); @@ -608,3 +623,108 @@ TEST(RNTuple, SerializeFooter) EXPECT_EQ(100u, pageRange.fPageInfos[0].fNElements); EXPECT_EQ(7000u, pageRange.fPageInfos[0].fLocator.GetPosition()); } + +TEST(RNTuple, SerializeFooterXHeader) +{ + RNTupleDescriptorBuilder builder; + builder.SetNTuple("ntpl", ""); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(0) + .FieldName("") + .Structure(ENTupleStructure::kRecord) + .MakeDescriptor() + .Unwrap()); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(42) + .FieldName("field") + .TypeName("int32_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + builder.AddFieldLink(0, 42); + builder.AddColumn(17, 17, 42, RColumnModel(EColumnType::kInt32, true), 0); + + auto context = RNTupleSerializer::SerializeHeaderV1(nullptr, builder.GetDescriptor()); + EXPECT_GT(context.GetHeaderSize(), 0); + auto bufHeader = std::make_unique(context.GetHeaderSize()); + context = RNTupleSerializer::SerializeHeaderV1(bufHeader.get(), builder.GetDescriptor()); + + builder.BeginHeaderExtension(); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(43) + .FieldName("struct") + .Structure(ENTupleStructure::kRecord) + .MakeDescriptor() + .Unwrap()); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(44) + .FieldName("f") + .TypeName("float") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + builder.AddField(RFieldDescriptorBuilder() + .FieldId(45) + .FieldName("i64") + .TypeName("int64_t") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + builder.AddFieldLink(0, 43); + builder.AddFieldLink(43, 44); + builder.AddFieldLink(0, 45); + builder.AddColumn(18, 18, 44, RColumnModel(EColumnType::kReal32, true), 0, /*firstElementIdx=*/4200); + builder.AddColumn(19, 19, 45, RColumnModel(EColumnType::kInt64, true), 0, /*firstElementIdx=*/10000); + + builder.AddField(RFieldDescriptorBuilder() + .FieldId(46) + .FieldName("projected") + .TypeName("float") + .Structure(ENTupleStructure::kLeaf) + .MakeDescriptor() + .Unwrap()); + builder.AddFieldLink(0, 46); + builder.AddColumn(20, 18, 46, RColumnModel(EColumnType::kReal32, true), 0); + + // Make sure late-added fields and the corresponding columns get an on-disk ID + context.MapSchema(builder.GetDescriptor(), /*forHeaderExtension=*/true); + + auto desc = builder.MoveDescriptor(); + auto sizeFooter = RNTupleSerializer::SerializeFooterV1(nullptr, desc, context); + EXPECT_GT(sizeFooter, 0); + auto bufFooter = std::make_unique(sizeFooter); + EXPECT_EQ(sizeFooter, RNTupleSerializer::SerializeFooterV1(bufFooter.get(), desc, context)); + + RNTupleSerializer::DeserializeHeaderV1(bufHeader.get(), context.GetHeaderSize(), builder); + RNTupleSerializer::DeserializeFooterV1(bufFooter.get(), sizeFooter, builder); + + desc = builder.MoveDescriptor(); + + EXPECT_EQ(6u, desc.GetNFields()); + EXPECT_EQ(4u, desc.GetNLogicalColumns()); + EXPECT_EQ(3u, desc.GetNPhysicalColumns()); + auto xHeader = desc.GetHeaderExtension(); + EXPECT_TRUE(xHeader != nullptr); + EXPECT_EQ(4u, xHeader->GetNFields()); + EXPECT_EQ(3u, xHeader->GetNLogicalColumns()); + EXPECT_EQ(2u, xHeader->GetNPhysicalColumns()); + auto fldIdStruct = desc.FindFieldId("struct"); + auto fldIdF = desc.FindFieldId("f", fldIdStruct); + auto fldIdI64 = desc.FindFieldId("i64"); + EXPECT_EQ(1, fldIdStruct); + EXPECT_EQ(2, fldIdF); + EXPECT_EQ(3, fldIdI64); + EXPECT_EQ(4, desc.FindFieldId("projected")); + + unsigned int counter = 0; + for (const auto &c : desc.GetColumnIterable(fldIdF)) { + EXPECT_EQ(c.GetFirstElementIndex(), 4200U); + counter++; + } + EXPECT_EQ(1U, counter); + for (const auto &c : desc.GetColumnIterable(fldIdI64)) { + EXPECT_EQ(c.GetFirstElementIndex(), 10000U); + counter++; + } + EXPECT_EQ(2U, counter); +} diff --git a/tree/ntuple/v7/test/ntuple_show.cxx b/tree/ntuple/v7/test/ntuple_show.cxx index 8ed3bf26dd8f7..6dd8ef9913c1b 100644 --- a/tree/ntuple/v7/test/ntuple_show.cxx +++ b/tree/ntuple/v7/test/ntuple_show.cxx @@ -16,17 +16,16 @@ TEST(RNTupleShow, Empty) auto ntuple2 = RNTupleReader::Open(std::move(model2), ntupleName, rootFileName); std::ostringstream os; - ntuple2->Show(0, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os); + ntuple2->Show(0, os); std::string fString{"{}\n"}; EXPECT_EQ(fString, os.str()); std::ostringstream os1; - ntuple2->Show(1, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os1); + ntuple2->Show(1, os1); std::string fString1{"{}\n"}; EXPECT_EQ(fString1, os1.str()); } - TEST(RNTupleShow, BasicTypes) { std::string rootFileName{"test_ntuple_show_basictypes.root"}; @@ -42,6 +41,8 @@ TEST(RNTupleShow, BasicTypes) auto fieldstring = model->MakeField("string"); auto fieldbool = model->MakeField("boolean"); auto fieldchar = model->MakeField("uint8"); + auto fieldbitset = model->MakeField>("bitset"); + auto fielduniqueptr = model->MakeField>("pstring"); auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, rootFileName); *fieldPt = 5.0f; @@ -52,6 +53,8 @@ TEST(RNTupleShow, BasicTypes) *fieldstring = "TestString"; *fieldbool = true; *fieldchar = 97; + *fieldbitset = std::bitset<65>("10000000000000000000000000000010000000000000000000000000000010010"); + *fielduniqueptr = std::make_unique("abc"); ntuple->Fill(); *fieldPt = 8.5f; @@ -62,13 +65,16 @@ TEST(RNTupleShow, BasicTypes) *fieldstring = "TestString2"; *fieldbool = false; *fieldchar = 98; + fieldbitset->flip(); + fielduniqueptr->reset(); ntuple->Fill(); } auto ntuple2 = RNTupleReader::Open(ntupleName, rootFileName); std::ostringstream os; - ntuple2->Show(0, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, os); + ntuple2->Show(0, os); + // clang-format off std::string fString{ std::string("") + "{\n" + " \"pt\": 5,\n" @@ -78,12 +84,16 @@ TEST(RNTupleShow, BasicTypes) + " \"uint64\": 44444444444,\n" + " \"string\": \"TestString\",\n" + " \"boolean\": true,\n" - + " \"uint8\": 97\n" + + " \"uint8\": 97,\n" + + " \"bitset\": \"10000000000000000000000000000010000000000000000000000000000010010\",\n" + + " \"pstring\": \"abc\"\n" + "}\n" }; + // clang-format on EXPECT_EQ(fString, os.str()); std::ostringstream os1; - ntuple2->Show(1, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, os1); + ntuple2->Show(1, os1); + // clang-format off std::string fString1{ std::string("") + "{\n" + " \"pt\": 8.5,\n" @@ -93,12 +103,15 @@ TEST(RNTupleShow, BasicTypes) + " \"uint64\": 2299994967294,\n" + " \"string\": \"TestString2\",\n" + " \"boolean\": false,\n" - + " \"uint8\": 98\n" + + " \"uint8\": 98,\n" + + " \"bitset\": \"01111111111111111111111111111101111111111111111111111111111101101\",\n" + + " \"pstring\": null\n" + "}\n" }; + // clang-format on EXPECT_EQ(fString1, os1.str()); // TODO(jblomer): this should fail to an exception instead - EXPECT_DEATH(ntuple2->Show(2, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON), ".*"); + EXPECT_DEATH(ntuple2->Show(2), ".*"); } TEST(RNTupleShow, Vectors) @@ -115,7 +128,8 @@ TEST(RNTupleShow, Vectors) *fieldIntVec = std::vector{4, 5, 6}; *fieldFloatVecVec = std::vector>{std::vector{0.1, 0.2}, std::vector{1.1, 1.2}}; - *fieldBoolVecVec = std::vector>{std::vector{false, true, false}, std::vector{false, true}, std::vector{true, false, false }}; + *fieldBoolVecVec = std::vector>{ + std::vector{false, true, false}, std::vector{false, true}, std::vector{true, false, false}}; ntuple->Fill(); fieldIntVec->emplace_back(7); @@ -130,23 +144,27 @@ TEST(RNTupleShow, Vectors) auto ntuple2 = RNTupleReader::Open(std::move(model2), ntupleName, rootFileName); std::ostringstream os; - ntuple2->Show(0, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os); + ntuple2->Show(0, os); + // clang-format off std::string fString{ std::string("") + "{\n" + " \"intVec\": [4, 5, 6],\n" + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2]],\n" + " \"booleanVecVec\": [[false, true, false], [false, true], [true, false, false]]\n" + "}\n" }; + // clang-format on EXPECT_EQ(fString, os.str()); std::ostringstream os1; - ntuple2->Show(1, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os1); + ntuple2->Show(1, os1); + // clang-format off std::string fString1{ std::string("") + "{\n" + " \"intVec\": [4, 5, 6, 7],\n" + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2], [2.2, 2.3]],\n" + " \"booleanVecVec\": [[false, true, false], [false, true], [true, false, false], [false, true]]\n" + "}\n" }; + // clang-format on EXPECT_EQ(fString1, os1.str()); } @@ -167,18 +185,22 @@ TEST(RNTupleShow, Arrays) *Intarrayfield = {1, 3}; *Floatarrayfield = {3.5f, 4.6f, 5.7f}; - *Vecarrayfield = {std::vector{1, 2}, std::vector{4, 5}, std::vector{7, 8, 9}, std::vector{11} }; + *Vecarrayfield = {std::vector{1, 2}, std::vector{4, 5}, std::vector{7, 8, 9}, + std::vector{11}}; *StringArray = {"First", "Second"}; - *arrayOfArray = { std::array{ true, false }, std::array{ false, true }, std::array{ false, false } }; - *arrayVecfield = { std::array{ 0, 1 }, std::array{ 2, 3 }, std::array{ 4, 5 } }; + *arrayOfArray = {std::array{true, false}, std::array{false, true}, + std::array{false, false}}; + *arrayVecfield = {std::array{0, 1}, std::array{2, 3}, std::array{4, 5}}; ntuple->Fill(); *Intarrayfield = {2, 5}; *Floatarrayfield = {2.3f, 5.7f, 11.13f}; - *Vecarrayfield = {std::vector{17, 19}, std::vector{23, 29}, std::vector{31, 37, 41}, std::vector{43} }; + *Vecarrayfield = {std::vector{17, 19}, std::vector{23, 29}, std::vector{31, 37, 41}, + std::vector{43}}; *StringArray = {"Third", "Fourth"}; - *arrayOfArray = { std::array{ true, true }, std::array{ false, true }, std::array{ true, true } }; - *arrayVecfield = { std::array{ 6, 7 }, std::array{ 8, 9 } }; + *arrayOfArray = {std::array{true, true}, std::array{false, true}, + std::array{true, true}}; + *arrayVecfield = {std::array{6, 7}, std::array{8, 9}}; ntuple->Fill(); } auto model2 = RNTupleModel::Create(); @@ -191,7 +213,8 @@ TEST(RNTupleShow, Arrays) auto ntuple2 = RNTupleReader::Open(std::move(model2), ntupleName, rootFileName); std::ostringstream os; - ntuple2->Show(0, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os); + ntuple2->Show(0, os); + // clang-format off std::string fString{ std::string("") + "{\n" + " \"IntArray\": [1, 3],\n" @@ -201,10 +224,12 @@ TEST(RNTupleShow, Arrays) + " \"ArrayOfArray\": [[true, false], [false, true], [false, false]],\n" + " \"VecOfArray\": [[0, 1], [2, 3], [4, 5]]\n" + "}\n"}; + // clang-format on EXPECT_EQ(fString, os.str()); std::ostringstream os1; - ntuple2->Show(1, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os1); + ntuple2->Show(1, os1); + // clang-format off std::string fString1{ std::string("") + "{\n" + " \"IntArray\": [2, 5],\n" @@ -214,6 +239,7 @@ TEST(RNTupleShow, Arrays) + " \"ArrayOfArray\": [[true, true], [false, true], [true, true]],\n" + " \"VecOfArray\": [[6, 7], [8, 9]]\n" + "}\n"}; + // clang-format on EXPECT_EQ(fString1, os1.str()); } @@ -230,16 +256,21 @@ TEST(RNTupleShow, Objects) auto derivedAfield = model->MakeField("DerivedA"); auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, rootFileName); - *customStructfield = CustomStruct{4.1f, std::vector{0.1f, 0.2f, 0.3f}, std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example1String"}; + *customStructfield = + CustomStruct{4.1f, std::vector{0.1f, 0.2f, 0.3f}, + std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example1String"}; *customStructVec = { - CustomStruct{4.2f, std::vector{0.1f, 0.2f, 0.3f}, std::vector>{{1.1f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example2String"}, - CustomStruct{4.3f, std::vector{0.1f, 0.2f, 0.3f}, std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.3f}}, "Example3String"}, - CustomStruct{4.4f, std::vector{0.1f, 0.3f}, std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example4String"} - }; + CustomStruct{4.2f, std::vector{0.1f, 0.2f, 0.3f}, + std::vector>{{1.1f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example2String"}, + CustomStruct{4.3f, std::vector{0.1f, 0.2f, 0.3f}, + std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.3f}}, "Example3String"}, + CustomStruct{4.4f, std::vector{0.1f, 0.3f}, + std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "Example4String"}}; *customStructArray = { - CustomStruct{4.5f, std::vector{0.1f, 0.2f, 0.3f}, std::vector>{{1.1f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "AnotherString1"}, - CustomStruct{4.6f, std::vector{0.1f, 0.2f, 0.3f}, std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.3f}}, "AnotherString2"} - }; + CustomStruct{4.5f, std::vector{0.1f, 0.2f, 0.3f}, + std::vector>{{1.1f, 1.3f}, {2.1f, 2.2f, 2.3f}}, "AnotherString1"}, + CustomStruct{4.6f, std::vector{0.1f, 0.2f, 0.3f}, + std::vector>{{1.1f, 1.2f, 1.3f}, {2.1f, 2.3f}}, "AnotherString2"}}; *derivedAfield = {}; ntuple->Fill(); } @@ -251,7 +282,8 @@ TEST(RNTupleShow, Objects) auto ntuple2 = RNTupleReader::Open(std::move(model2), ntupleName, rootFileName); std::ostringstream os; - ntuple2->Show(0, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os); + ntuple2->Show(0, os); + // clang-format off std::string fString{ std::string("") + "{\n" + " \"CustomStruct\": {\n" @@ -279,10 +311,10 @@ TEST(RNTupleShow, Objects) + " \"a_s\": \"\"\n" + " }\n" + "}\n" }; + // clang-format on EXPECT_EQ(fString, os.str()); } - TEST(RNTupleShow, Collections) { std::string rootFileName{"test_ntuple_show_collection.root"}; @@ -302,19 +334,22 @@ TEST(RNTupleShow, Collections) *float_field = 20.0; collection->Fill(); ntuple->Fill(); - } + } auto ntuple = RNTupleReader::Open(ntupleName, rootFileName); std::ostringstream osData; - ntuple->Show(0, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, osData); + ntuple->Show(0, osData); + // clang-format off std::string outputData{ std::string("") + "{\n" + " \"collection\": [{\"myInt\": 0, \"myFloat\": 10}, {\"myInt\": 1, \"myFloat\": 20}]\n" + "}\n" }; + // clang-format on EXPECT_EQ(outputData, osData.str()); std::ostringstream osFields; ntuple->PrintInfo(ROOT::Experimental::ENTupleInfo::kSummary, osFields); + // clang-format off std::string outputFields{ std::string("") + "************************************ NTUPLE ************************************\n" + "* N-Tuple : Collections *\n" @@ -325,6 +360,7 @@ TEST(RNTupleShow, Collections) + "* Field 1.1.1 : myInt (std::int32_t) *\n" + "* Field 1.1.2 : myFloat (float) *\n" + "********************************************************************************\n" }; + // clang-format on EXPECT_EQ(outputFields, osFields.str()); } @@ -357,19 +393,31 @@ TEST(RNTupleShow, RVec) auto r = RNTupleReader::Open(std::move(modelRead), ntupleName, rootFileName); std::ostringstream os; - r->Show(0, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os); - std::string expected = - "{\n \"intVec\": [1, 2, 3],\n \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2]],\n \"customStructVec\": [{\"a\": 0, " - "\"v1\": [], \"v2\": [], \"s\": \"\"}, {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}]\n}\n"; - EXPECT_EQ(os.str(), expected); + r->Show(0, os); + // clang-format off + std::string expected1{std::string("") + + "{\n" + + " \"intVec\": [1, 2, 3],\n" + + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2]],\n" + + " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}," + + " {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}]\n" + + "}\n"}; + // clang-format on + EXPECT_EQ(os.str(), expected1); std::ostringstream os2; - r->Show(1, ROOT::Experimental::ENTupleShowFormat::kCurrentModelJSON, os2); - expected = - "{\n \"intVec\": [1, 2, 3, 4],\n \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2], [2.1, 2.2]],\n " - "\"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}, {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], " - "[5]], \"s\": \"foo\"}, {\"a\": 6, \"v1\": [7, 8], \"v2\": [[9], [10]], \"s\": \"bar\"}]\n}\n"; - EXPECT_EQ(os2.str(), expected); + r->Show(1, os2); + // clang-format off + std::string expected2{std::string("") + + "{\n" + + " \"intVec\": [1, 2, 3, 4],\n" + + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2], [2.1, 2.2]],\n" + + " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}," + + " {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}," + + " {\"a\": 6, \"v1\": [7, 8], \"v2\": [[9], [10]], \"s\": \"bar\"}]\n" + + "}\n"}; + // clang-format on + EXPECT_EQ(os2.str(), expected2); } TEST(RNTupleShow, RVecTypeErased) @@ -412,22 +460,30 @@ TEST(RNTupleShow, RVecTypeErased) auto ntuple = RNTupleReader::Open(ntupleName, rootFileName); std::ostringstream os; - ntuple->Show(0, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, os); - std::string fString{std::string("") + "{\n" + " \"intVec\": [1, 2, 3],\n" + - " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2]],\n" + - " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}, {\"a\": 1, \"v1\": " - "[2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}]\n" + - "}\n"}; + ntuple->Show(0, os); + // clang-format off + std::string fString{std::string("") + + "{\n" + + " \"intVec\": [1, 2, 3],\n" + + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2]],\n" + + " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}," + + " {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}]\n" + + "}\n"}; + // clang-format on EXPECT_EQ(fString, os.str()); std::ostringstream os1; - ntuple->Show(1, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, os1); - std::string fString1{ - std::string("") + "{\n" + " \"intVec\": [1, 2, 3, 4],\n" + - " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2], [2.1, 2.2]],\n" + - " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}, {\"a\": 1, \"v1\": [2, 3], \"v2\": " - "[[4], [5]], \"s\": \"foo\"}, {\"a\": 6, \"v1\": [7, 8], \"v2\": [[9], [10]], \"s\": \"bar\"}]\n" + - "}\n"}; + ntuple->Show(1, os1); + // clang-format off + std::string fString1{std::string("") + + "{\n" + + " \"intVec\": [1, 2, 3, 4],\n" + + " \"floatVecVec\": [[0.1, 0.2], [1.1, 1.2], [2.1, 2.2]],\n" + + " \"customStructVec\": [{\"a\": 0, \"v1\": [], \"v2\": [], \"s\": \"\"}," + + " {\"a\": 1, \"v1\": [2, 3], \"v2\": [[4], [5]], \"s\": \"foo\"}," + + " {\"a\": 6, \"v1\": [7, 8], \"v2\": [[9], [10]], \"s\": \"bar\"}]\n" + + "}\n"}; + // clang-format off EXPECT_EQ(fString1, os1.str()); } @@ -458,8 +514,52 @@ TEST(RNTupleShow, CollectionProxy) EXPECT_EQ(1U, ntuple->GetNEntries()); std::ostringstream os; - ntuple->Show(0, ROOT::Experimental::ENTupleShowFormat::kCompleteJSON, os); - std::string expected{"{\n \"proxyF\": [42, 24],\n \"vecProxyF\": [[1, 2], [1, 2]]\n}\n"}; + ntuple->Show(0, os); + // clang-format off + std::string expected{std::string("") + + "{\n" + + " \"proxyF\": [42, 24],\n" + + " \"vecProxyF\": [[1, 2], [1, 2]]\n" + + "}\n"}; + // clang-format on EXPECT_EQ(os.str(), expected); } } + +TEST(RNTupleShow, Enum) +{ + + FileRaii fileGuard("test_ntuple_show_enum.ntuple"); + { + auto model = RNTupleModel::Create(); + auto ptrEnum = model->MakeField("enum"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + *ptrEnum = kCustomEnumVal; + writer->Fill(); + *ptrEnum = static_cast(137); + writer->Fill(); + } + + auto ntuple = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + ASSERT_EQ(2U, ntuple->GetNEntries()); + + std::ostringstream os0; + ntuple->Show(0, os0); + // clang-format off + std::string expected{std::string("") + + "{\n" + + " \"enum\": 7\n" + + "}\n"}; + // clang-format on + EXPECT_EQ(os0.str(), expected); + + std::ostringstream os1; + ntuple->Show(1, os1); + // clang-format off + expected = std::string("") + + "{\n" + + " \"enum\": 137\n" + + "}\n"; + // clang-format on + EXPECT_EQ(os1.str(), expected); +} diff --git a/tree/ntuple/v7/test/ntuple_storage.cxx b/tree/ntuple/v7/test/ntuple_storage.cxx index 2a4569429527a..0779756ed0673 100644 --- a/tree/ntuple/v7/test/ntuple_storage.cxx +++ b/tree/ntuple/v7/test/ntuple_storage.cxx @@ -1,4 +1,5 @@ #include "ntuple_test.hxx" +#include namespace { /// An RPageSink that keeps counters of (vector) commit of (sealed) pages; used to test RPageSinkBuf @@ -40,7 +41,7 @@ class RPageSinkMock : public RPageSink { RPage ReservePage(ColumnHandle_t columnHandle, std::size_t nElements) final { auto elementSize = columnHandle.fColumn->GetElement()->GetSize(); - return fPageAllocator.NewPage(columnHandle.fId, elementSize, nElements); + return fPageAllocator.NewPage(columnHandle.fPhysicalId, elementSize, nElements); } void ReleasePage(RPage &page) final { fPageAllocator.DeletePage(page); } @@ -235,18 +236,21 @@ TEST(RNTuple, PageFillingString) { *fldX = ""; ntuple->Fill(); ntuple->CommitCluster(); - // 2 pages: 16 and 8 characters - *fldX = "012345678901234567890123"; + // 2 pages: 16 and 10 characters + *fldX = "01234567890123456789012"; ntuple->Fill(); + *fldX = "012"; + ntuple->Fill(); // main write page is half full here; RColumn::AppendV should flush the shadow page } auto ntuple = RNTupleReader::Open("ntpl", fileGuard.GetPath()); auto viewX = ntuple->GetView("x"); - ASSERT_EQ(4u, ntuple->GetNEntries()); - EXPECT_EQ("01234567890123456", viewX(0)); - EXPECT_EQ("0123456789012345", viewX(1)); - EXPECT_EQ("", viewX(2)); - EXPECT_EQ("012345678901234567890123", viewX(3)); + ASSERT_EQ(5u, ntuple->GetNEntries()); + EXPECT_EQ("01234567890123456", viewX(0)); + EXPECT_EQ("0123456789012345", viewX(1)); + EXPECT_EQ("", viewX(2)); + EXPECT_EQ("01234567890123456789012", viewX(3)); + EXPECT_EQ("012", viewX(4)); const auto desc = ntuple->GetDescriptor(); EXPECT_EQ(4u, desc->GetNClusters()); @@ -265,7 +269,7 @@ TEST(RNTuple, PageFillingString) { const auto &pr4 = cd4.GetPageRange(1); ASSERT_EQ(2u, pr4.fPageInfos.size()); EXPECT_EQ(16u, pr4.fPageInfos[0].fNElements); - EXPECT_EQ(8u, pr4.fPageInfos[1].fNElements); + EXPECT_EQ(10u, pr4.fPageInfos[1].fNElements); } TEST(RPageSinkBuf, Basics) @@ -369,7 +373,9 @@ TEST(RPageSinkBuf, Basics) } TEST(RPageSinkBuf, ParallelZip) { +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif FileRaii fileGuard("test_ntuple_sinkbuf_pzip.root"); { @@ -395,7 +401,11 @@ TEST(RPageSinkBuf, ParallelZip) { auto *parallel_zip = ntuple->GetMetrics().GetCounter( "RNTupleWriter.RPageSinkBuf.ParallelZip"); ASSERT_FALSE(parallel_zip == nullptr); +#ifdef R__USE_IMT EXPECT_EQ(1, parallel_zip->GetValueAsInt()); +#else + EXPECT_EQ(0, parallel_zip->GetValueAsInt()); +#endif } } } @@ -417,42 +427,53 @@ TEST(RPageSinkBuf, ParallelZip) { TEST(RPageSinkBuf, CommitSealedPageV) { RNTupleWriteOptions options; - options.SetApproxUnzippedPageSize(8); + options.SetApproxUnzippedPageSize(16); +#ifdef R__USE_IMT ROOT::DisableImplicitMT(); +#endif { std::unique_ptr sink(new RPageSinkMock(options)); auto &counters = static_cast(sink.get())->fCounters; auto model = RNTupleModel::Create(); - auto u32Field = model->MakeField("u32"); - auto u16Field = model->MakeField("u16"); + auto u64Field = model->MakeField("u64"); + auto u32Field = model->MakeField("u32"); + auto strField = model->MakeField("str"); auto ntuple = std::make_unique(std::move(model), std::make_unique(std::move(sink))); ntuple->Fill(); ntuple->Fill(); ntuple->Fill(); ntuple->CommitCluster(); // Parallel zip not available; all pages committed separately - EXPECT_EQ(3, counters.fNCommitPage); + EXPECT_EQ(5, counters.fNCommitPage); EXPECT_EQ(0, counters.fNCommitSealedPage); EXPECT_EQ(0, counters.fNCommitSealedPageV); } +#ifdef R__USE_IMT ROOT::EnableImplicitMT(); +#endif { std::unique_ptr sink(new RPageSinkMock(options)); auto &counters = static_cast(sink.get())->fCounters; auto model = RNTupleModel::Create(); + auto u64Field = model->MakeField("u64"); auto u32Field = model->MakeField("u32"); - auto u16Field = model->MakeField("u16"); + auto strField = model->MakeField("str"); auto ntuple = std::make_unique(std::move(model), std::make_unique(std::move(sink))); ntuple->Fill(); ntuple->Fill(); ntuple->CommitCluster(); +#ifdef R__USE_IMT // All pages in all columns committed via a single call to `CommitSealedPageV()` EXPECT_EQ(0, counters.fNCommitPage); - EXPECT_EQ(0, counters.fNCommitSealedPage); EXPECT_EQ(1, counters.fNCommitSealedPageV); +#else + EXPECT_EQ(3, counters.fNCommitPage); + EXPECT_EQ(0, counters.fNCommitSealedPageV); +#endif + EXPECT_EQ(0, counters.fNCommitSealedPage); } } diff --git a/tree/ntuple/v7/test/ntuple_storage_daos.cxx b/tree/ntuple/v7/test/ntuple_storage_daos.cxx index 0088277a850a1..d11acd3788eb5 100644 --- a/tree/ntuple/v7/test/ntuple_storage_daos.cxx +++ b/tree/ntuple/v7/test/ntuple_storage_daos.cxx @@ -1,24 +1,61 @@ #include "ntuple_test.hxx" #include -#include "ROOT/TestSupport.hxx" + +#include + #include +#include -TEST(RPageStorageDaos, Basics) -{ - ROOT::TestSupport::CheckDiagsRAII diags; - diags.optionalDiag(kWarning, "in int daos_init()", "This RNTuple build uses libdaos_mock. Use only for testing!"); - diags.requiredDiag(kWarning, "ROOT::Experimental::Detail::RPageSinkDaos::RPageSinkDaos", - "The DAOS backend is experimental and still under development.", false); - diags.requiredDiag(kWarning, "[ROOT.NTuple]", "Pre-release format version: RC 1", false); +class RPageStorageDaos : public ::testing::Test { +private: + static std::unordered_set fContainerLabels; + ROOT::TestSupport::CheckDiagsRAII fRootDiags; + +protected: + /// \brief Stores the test label in a class-wide collection and returns the DAOS URI ("daos://{pool}/{container}"). + /// The test label serves as the container identifier. + static std::string RegisterLabel(std::string_view testLabel) + { + auto [strIt, _] = fContainerLabels.emplace(testLabel); + static const std::string testPoolUriPrefix("daos://" R__DAOS_TEST_POOL "/"); + return {testPoolUriPrefix + *strIt}; + } + + void SetUp() override + { + // Initialized at the start of each test to expect diagnostic messages from TestSupport + fRootDiags.requiredDiag(kWarning, "ROOT::Experimental::Detail::RPageSinkDaos::RPageSinkDaos", + "The DAOS backend is experimental and still under development.", false); + fRootDiags.requiredDiag(kWarning, "[ROOT.NTuple]", "Pre-release format version: RC 1", false); + fRootDiags.optionalDiag(kWarning, "in int daos_init()", + "This RNTuple build uses libdaos_mock. Use only for testing!"); + } + + static void TearDownTestSuite() + { +#ifndef R__DAOS_TEST_MOCK + const std::string sysCmd("daos cont destroy " R__DAOS_TEST_POOL " "); + for (const auto &label : fContainerLabels) { + system((sysCmd + label).data()); + } +#endif + } +}; - std::string daosUri("daos://" R__DAOS_TEST_POOL "/container-test-1"); +std::unordered_set RPageStorageDaos::fContainerLabels{}; +TEST_F(RPageStorageDaos, Basics) +{ + std::string daosUri = RegisterLabel("ntuple-test-basics"); + const std::string_view ntupleName("ntuple"); auto model = RNTupleModel::Create(); auto wrPt = model->MakeField("pt", 42.0); { - RNTupleWriteOptions options; - auto ntuple = RNTupleWriter::Recreate(std::move(model), "ntuple-1", daosUri, options); + RNTupleWriteOptionsDaos options; + options.SetMaxCageSize(0); // Disable caging mechanism. + auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, daosUri, options); + ntuple->Fill(); ntuple->CommitCluster(); *wrPt = 24.0; @@ -27,7 +64,7 @@ TEST(RPageStorageDaos, Basics) ntuple->Fill(); } - auto ntuple = RNTupleReader::Open("ntuple-1", daosUri); + auto ntuple = RNTupleReader::Open(ntupleName, daosUri); EXPECT_EQ(3U, ntuple->GetNEntries()); auto rdPt = ntuple->GetModel()->GetDefaultEntry()->Get("pt"); @@ -39,18 +76,19 @@ TEST(RPageStorageDaos, Basics) EXPECT_EQ(12.0, *rdPt); } -TEST(RPageStorageDaos, Extended) +TEST_F(RPageStorageDaos, Extended) { - std::string daosUri("daos://" R__DAOS_TEST_POOL "/container-test-2"); - + std::string daosUri = RegisterLabel("ntuple-test-extended"); + const std::string_view ntupleName("ntuple"); auto model = RNTupleModel::Create(); auto wrVector = model->MakeField>("vector"); TRandom3 rnd(42); double chksumWrite = 0.0; { - RNTupleWriteOptions options; - auto ntuple = RNTupleWriter::Recreate(std::move(model), "ntuple-2", daosUri, options); + RNTupleWriteOptionsDaos options; + options.SetMaxCageSize(0); + auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, daosUri, options); constexpr unsigned int nEvents = 32000; for (unsigned int i = 0; i < nEvents; ++i) { auto nVec = 1 + floor(rnd.Rndm() * 1000.); @@ -68,7 +106,7 @@ TEST(RPageStorageDaos, Extended) RNTupleReadOptions options; options.SetClusterBunchSize(5); - auto ntuple = RNTupleReader::Open("ntuple-2", daosUri, options); + auto ntuple = RNTupleReader::Open(ntupleName, daosUri, options); auto rdVector = ntuple->GetModel()->GetDefaultEntry()->Get>("vector"); double chksumRead = 0.0; @@ -80,17 +118,17 @@ TEST(RPageStorageDaos, Extended) EXPECT_EQ(chksumRead, chksumWrite); } -TEST(RPageStorageDaos, Options) +TEST_F(RPageStorageDaos, Options) { - std::string daosUri("daos://" R__DAOS_TEST_POOL "/container-test-3"); - + std::string daosUri = RegisterLabel("ntuple-test-options"); + const std::string_view ntupleName("ntuple"); { auto model = RNTupleModel::Create(); RNTupleWriteOptionsDaos options; options.SetObjectClass("UNKNOWN"); try { - auto ntuple = RNTupleWriter::Recreate(std::move(model), "ntuple-3", daosUri, options); + auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, daosUri, options); FAIL() << "unknown object class should throw"; } catch (const RException &err) { EXPECT_THAT(err.what(), testing::HasSubstr("UNKNOWN")); @@ -102,39 +140,42 @@ TEST(RPageStorageDaos, Options) auto wrPt = model->MakeField("pt", 42.0); RNTupleWriteOptionsDaos options; + options.SetMaxCageSize(0); options.SetObjectClass("RP_XSF"); - auto ntuple = RNTupleWriter::Recreate(std::move(model), "ntuple-3", daosUri, options); + auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, daosUri, options); ntuple->Fill(); ntuple->CommitCluster(); } auto readOptions = RNTupleReadOptions(); readOptions.SetClusterBunchSize(3); - ROOT::Experimental::Detail::RPageSourceDaos source("ntuple-3", daosUri, readOptions); + ROOT::Experimental::Detail::RPageSourceDaos source(ntupleName, daosUri, readOptions); source.Attach(); EXPECT_STREQ("RP_XSF", source.GetObjectClass().c_str()); EXPECT_EQ(3U, source.GetReadOptions().GetClusterBunchSize()); EXPECT_EQ(1U, source.GetNEntries()); } -TEST(RPageStorageDaos, MultipleNTuplesPerContainer) +TEST_F(RPageStorageDaos, MultipleNTuplesPerContainer) { - std::string daosUri("daos://" R__DAOS_TEST_POOL "/container-test-4"); + std::string daosUri = RegisterLabel("ntuple-test-multiple"); + const std::string_view ntupleName1("ntuple1"), ntupleName2("ntuple2"); - RNTupleWriteOptions options; + RNTupleWriteOptionsDaos options; + options.SetMaxCageSize(0); { - auto modelA = RNTupleModel::Create(); - auto wrPt = modelA->MakeField("pt", 34.0); - auto ntuple = RNTupleWriter::Recreate(std::move(modelA), "ntupleA", daosUri, options); + auto model1 = RNTupleModel::Create(); + auto wrPt = model1->MakeField("pt", 34.0); + auto ntuple = RNTupleWriter::Recreate(std::move(model1), ntupleName1, daosUri, options); ntuple->Fill(); *wrPt = 160.0; ntuple->Fill(); } { - auto modelB = RNTupleModel::Create(); - auto wrPt = modelB->MakeField("pt", 81.0); - auto ntuple = RNTupleWriter::Recreate(std::move(modelB), "ntupleB", daosUri, options); + auto model2 = RNTupleModel::Create(); + auto wrPt = model2->MakeField("pt", 81.0); + auto ntuple = RNTupleWriter::Recreate(std::move(model2), ntupleName2, daosUri, options); ntuple->Fill(); *wrPt = 96.0; ntuple->Fill(); @@ -142,29 +183,88 @@ TEST(RPageStorageDaos, MultipleNTuplesPerContainer) ntuple->Fill(); } { - auto ntupleA = RNTupleReader::Open("ntupleA", daosUri); - auto ntupleB = RNTupleReader::Open("ntupleB", daosUri); - EXPECT_EQ(2U, ntupleA->GetNEntries()); - EXPECT_EQ(3U, ntupleB->GetNEntries()); + auto ntuple1 = RNTupleReader::Open(ntupleName1, daosUri); + auto ntuple2 = RNTupleReader::Open(ntupleName2, daosUri); + EXPECT_EQ(2U, ntuple1->GetNEntries()); + EXPECT_EQ(3U, ntuple2->GetNEntries()); { - auto rdPt = ntupleA->GetModel()->GetDefaultEntry()->Get("pt"); - ntupleA->LoadEntry(0); + auto rdPt = ntuple1->GetModel()->GetDefaultEntry()->Get("pt"); + ntuple1->LoadEntry(0); EXPECT_EQ(34.0, *rdPt); - ntupleA->LoadEntry(1); + ntuple1->LoadEntry(1); EXPECT_EQ(160.0, *rdPt); } { - auto rdPt = ntupleB->GetModel()->GetDefaultEntry()->Get("pt"); - ntupleB->LoadEntry(0); + auto rdPt = ntuple2->GetModel()->GetDefaultEntry()->Get("pt"); + ntuple2->LoadEntry(0); EXPECT_EQ(81.0, *rdPt); - ntupleB->LoadEntry(1); + ntuple2->LoadEntry(1); EXPECT_EQ(96.0, *rdPt); - ntupleB->LoadEntry(2); + ntuple2->LoadEntry(2); EXPECT_EQ(54.0, *rdPt); } } // Nonexistent ntuple - EXPECT_THROW(RNTupleReader::Open("ntupleC", daosUri), ROOT::Experimental::RException); + EXPECT_THROW(RNTupleReader::Open("ntuple3", daosUri), ROOT::Experimental::RException); +} + +#ifdef R__USE_IMT +// This feature depends on RPageSinkBuf and the ability to issue a single `CommitSealedPageV()` call; thus, disable if +// ROOT was built with `-Dimt=OFF` +TEST_F(RPageStorageDaos, CagedPages) +{ + std::string daosUri = RegisterLabel("ntuple-test-caged"); + const std::string_view ntupleName("ntuple"); + ROOT::EnableImplicitMT(); + + auto model = RNTupleModel::Create(); + auto wrVector = model->MakeField>("vector"); + + TRandom3 rnd(42); + double chksumWrite = 0.0; + { + RNTupleWriteOptionsDaos options; + options.SetMaxCageSize(4 * 64 * 1024); + options.SetUseBufferedWrite(true); + auto ntuple = RNTupleWriter::Recreate(std::move(model), ntupleName, daosUri, options); + constexpr unsigned int nEvents = 180000; + for (unsigned int i = 0; i < nEvents; ++i) { + auto nVec = 1 + floor(rnd.Rndm() * 1000.); + wrVector->resize(nVec); + for (unsigned int n = 0; n < nVec; ++n) { + auto val = 1 + rnd.Rndm() * 1000. - 500.; + (*wrVector)[n] = val; + chksumWrite += val; + } + ntuple->Fill(); + } + } + + // Attempt to read all the entries written above as caged pages, with cluster cache turned on. + { + RNTupleReadOptions options; + options.SetClusterCache(RNTupleReadOptions::EClusterCache::kOn); + options.SetClusterBunchSize(5); + auto ntuple = RNTupleReader::Open(ntupleName, daosUri, options); + auto rdVector = ntuple->GetModel()->GetDefaultEntry()->Get>("vector"); + + double chksumRead = 0.0; + for (auto entryId : *ntuple) { + ntuple->LoadEntry(entryId); + for (auto v : *rdVector) + chksumRead += v; + } + EXPECT_EQ(chksumRead, chksumWrite); + } + + // Wrongly attempt to read a single caged page when cluster cache is disabled. + { + RNTupleReadOptions options; + options.SetClusterCache(RNTupleReadOptions::EClusterCache::kOff); + auto ntuple = RNTupleReader::Open(ntupleName, daosUri, options); + EXPECT_THROW(ntuple->LoadEntry(1), ROOT::Experimental::RException); + } } +#endif diff --git a/tree/ntuple/v7/test/ntuple_test.hxx b/tree/ntuple/v7/test/ntuple_test.hxx index c526d05346ddf..30468d46722ef 100644 --- a/tree/ntuple/v7/test/ntuple_test.hxx +++ b/tree/ntuple/v7/test/ntuple_test.hxx @@ -2,15 +2,12 @@ #define ROOT7_RNTuple_Test #include -#include #include #include -#include #include #include #include #include -#include #include #include #include @@ -24,16 +21,21 @@ #include #include #include -#include +#include #include #include #include -#include +#include #include "gmock/gmock.h" #include "gtest/gtest.h" +// Backward compatibility for gtest version < 1.10.0 +#ifndef TYPED_TEST_SUITE +#define TYPED_TEST_SUITE TYPED_TEST_CASE +#endif + #include "CustomStruct.hxx" #include @@ -59,6 +61,7 @@ using RColumnModel = ROOT::Experimental::RColumnModel; using RClusterIndex = ROOT::Experimental::RClusterIndex; using RClusterDescriptorBuilder = ROOT::Experimental::RClusterDescriptorBuilder; using RClusterGroupDescriptorBuilder = ROOT::Experimental::RClusterGroupDescriptorBuilder; +using RColumnDescriptorBuilder = ROOT::Experimental::RColumnDescriptorBuilder; using RFieldDescriptorBuilder = ROOT::Experimental::RFieldDescriptorBuilder; using RException = ROOT::Experimental::RException; template @@ -66,7 +69,6 @@ using RField = ROOT::Experimental::RField; using RFieldBase = ROOT::Experimental::Detail::RFieldBase; using RFieldDescriptor = ROOT::Experimental::RFieldDescriptor; using RFieldMerger = ROOT::Experimental::RFieldMerger; -using RFieldValue = ROOT::Experimental::Detail::RFieldValue; using RNTupleLocator = ROOT::Experimental::RNTupleLocator; using RNTupleLocatorObject64 = ROOT::Experimental::RNTupleLocatorObject64; using RMiniFileReader = ROOT::Experimental::Internal::RMiniFileReader; diff --git a/tree/ntuple/v7/test/ntuple_types.cxx b/tree/ntuple/v7/test/ntuple_types.cxx index 89a2c35ba8906..30fdcbfa32c39 100644 --- a/tree/ntuple/v7/test/ntuple_types.cxx +++ b/tree/ntuple/v7/test/ntuple_types.cxx @@ -1,7 +1,15 @@ #include "ntuple_test.hxx" #include "SimpleCollectionProxy.hxx" +#include "ROOT/TestSupport.hxx" #include "TInterpreter.h" +#include +#include +#include +#include +#include +#include + TEST(RNTuple, TypeName) { EXPECT_STREQ("float", ROOT::Experimental::RField::TypeName().c_str()); EXPECT_STREQ("std::vector", @@ -21,13 +29,105 @@ TEST(RNTuple, TypeName) { (ROOT::Experimental::RField, int>>::TypeName().c_str())); } +TEST(RNTuple, EnumBasics) +{ + // Needs fix of TEnum + // auto stdEnum = RFieldBase::Create("f", "std::byte"); + // EXPECT_FALSE(stdEnum); + + auto f = RFieldBase::Create("f", "CustomEnum").Unwrap(); + + auto model = RNTupleModel::Create(); + auto ptrEnum = model->MakeField("e"); + model->MakeField("swe"); + + EXPECT_EQ(model->GetField("e")->GetType(), f->GetType()); + + FileRaii fileGuard("test_ntuple_enum_basics.root"); + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + *ptrEnum = kCustomEnumVal; + writer->Fill(); + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + EXPECT_EQ(1, reader->GetNEntries()); + reader->LoadEntry(0); + EXPECT_EQ(kCustomEnumVal, *reader->GetModel()->GetDefaultEntry()->Get("e")); + auto ptrStructWithEnums = reader->GetModel()->GetDefaultEntry()->Get("swe"); + EXPECT_EQ(42, ptrStructWithEnums->a); + EXPECT_EQ(137, ptrStructWithEnums->b); + EXPECT_EQ(kCustomEnumVal, ptrStructWithEnums->e); +} + +using EnumClassInts = ::testing::Types; + +template +class EnumClass : public ::testing::Test { +public: + using Enum_t = EnumT; +}; + +TYPED_TEST_SUITE(EnumClass, EnumClassInts); + +TYPED_TEST(EnumClass, Widths) +{ + using ThisEnum_t = typename TestFixture::Enum_t; + using Underlying_t = std::underlying_type_t; + + auto enumName = RField::TypeName(); + + FileRaii fileGuard("test_ntuple_enum_class_" + enumName + ".root"); + { + auto model = RNTupleModel::Create(); + auto ptrEnum = model->MakeField("e"); + auto writer = RNTupleWriter::Recreate(std::move(model), "ntpl", fileGuard.GetPath()); + *ptrEnum = static_cast(0); + writer->Fill(); + *ptrEnum = static_cast(1); + writer->Fill(); + *ptrEnum = static_cast(std::numeric_limits::max()); + writer->Fill(); + *ptrEnum = static_cast(std::numeric_limits::max() - 1); + writer->Fill(); + if (std::is_signed_v) { + *ptrEnum = static_cast(-1); + writer->Fill(); + *ptrEnum = static_cast(std::numeric_limits::min()); + writer->Fill(); + *ptrEnum = static_cast(std::numeric_limits::min() + 1); + writer->Fill(); + } + } + + auto reader = RNTupleReader::Open("ntpl", fileGuard.GetPath()); + auto ptrEnum = reader->GetModel()->GetDefaultEntry()->Get("e"); + reader->LoadEntry(0); + EXPECT_EQ(static_cast(0), *ptrEnum); + reader->LoadEntry(1); + EXPECT_EQ(static_cast(1), *ptrEnum); + reader->LoadEntry(2); + EXPECT_EQ(static_cast(std::numeric_limits::max()), *ptrEnum); + reader->LoadEntry(3); + EXPECT_EQ(static_cast(std::numeric_limits::max() - 1), *ptrEnum); + + if (!std::is_signed_v) + return; + + reader->LoadEntry(4); + EXPECT_EQ(static_cast(-1), *ptrEnum); + reader->LoadEntry(5); + EXPECT_EQ(static_cast(std::numeric_limits::min()), *ptrEnum); + reader->LoadEntry(6); + EXPECT_EQ(static_cast(std::numeric_limits::min() + 1), *ptrEnum); +} TEST(RNTuple, CreateField) { auto field = RFieldBase::Create("test", "vector").Unwrap(); EXPECT_STREQ("std::vector", field->GetType().c_str()); auto value = field->GenerateValue(); - field->DestroyValue(value); std::vector> itemFields; itemFields.push_back(std::make_unique>("u32")); @@ -202,10 +302,242 @@ TEST(RNTuple, StdTuple) } } -TEST(RNTuple, Int64_t) +TEST(RNTuple, StdSet) +{ + auto field = RField>("setField"); + EXPECT_STREQ("std::set", field.GetType().c_str()); + auto otherField = RFieldBase::Create("test", "std::set").Unwrap(); + EXPECT_STREQ(field.GetType().c_str(), otherField->GetType().c_str()); + EXPECT_EQ((sizeof(std::set)), field.GetValueSize()); + EXPECT_EQ((sizeof(std::set)), otherField->GetValueSize()); + EXPECT_EQ((alignof(std::set)), field.GetAlignment()); + // For type-erased set fields, we use `alignof(std::set)` to set the alignment, + // so the actual alignment may be smaller. + EXPECT_LE((alignof(std::set)), otherField->GetAlignment()); + + auto setSetField = RField>>("setSetField"); + EXPECT_STREQ("std::set>", setSetField.GetType().c_str()); + + FileRaii fileGuard("test_ntuple_rfield_stdset.root"); + { + auto model = RNTupleModel::Create(); + auto set_field = model->MakeField>({"mySet", "float set"}); + auto set_field2 = model->MakeField>>({"mySet2"}); + + auto mySet3 = RFieldBase::Create("mySet3", "std::set").Unwrap(); + auto mySet4 = RFieldBase::Create("mySet4", "std::set>").Unwrap(); + + model->AddField(std::move(mySet3)); + model->AddField(std::move(mySet4)); + + auto ntuple = RNTupleWriter::Recreate(std::move(model), "set_ntuple", fileGuard.GetPath()); + auto set_field3 = ntuple->GetModel()->GetDefaultEntry()->Get>("mySet3"); + auto set_field4 = ntuple->GetModel()->GetDefaultEntry()->Get>>("mySet4"); + for (int i = 0; i < 2; i++) { + *set_field = {static_cast(i), 3.14, 0.42}; + *set_field2 = {std::make_pair(i, CustomStruct{6.f, {7.f, 8.f}, {{9.f}, {10.f}}, "foo"}), + std::make_pair(i + 1, CustomStruct{2.f, {3.f, 4.f}, {{5.f}, {6.f}}, "bar"})}; + *set_field3 = {"Hello", "world!", std::to_string(i)}; + *set_field4 = {{static_cast(i), 'a'}, {'r', 'o', 'o', 't'}, {'h', 'i'}}; + ntuple->Fill(); + } + } + + auto ntuple = RNTupleReader::Open("set_ntuple", fileGuard.GetPath()); + EXPECT_EQ(2, ntuple->GetNEntries()); + + auto viewSet = ntuple->GetView>("mySet"); + auto viewSet2 = ntuple->GetView>>("mySet2"); + auto viewSet3 = ntuple->GetView>("mySet3"); + auto viewSet4 = ntuple->GetView>>("mySet4"); + for (auto i : ntuple->GetEntryRange()) { + EXPECT_EQ(std::set({static_cast(i), 3.14, 0.42}), viewSet(i)); + + auto pairSet = std::set>( + {std::make_pair(i, CustomStruct{6.f, {7.f, 8.f}, {{9.f}, {10.f}}, "foo"}), + std::make_pair(i + 1, CustomStruct{2.f, {3.f, 4.f}, {{5.f}, {6.f}}, "bar"})}); + EXPECT_EQ(pairSet, viewSet2(i)); + + EXPECT_EQ(std::set({"Hello", "world!", std::to_string(i)}), viewSet3(i)); + EXPECT_EQ(std::set>({{static_cast(i), 'a'}, {'r', 'o', 'o', 't'}, {'h', 'i'}}), viewSet4(i)); + } + + ntuple->LoadEntry(0); + auto mySet2 = ntuple->GetModel()->GetDefaultEntry()->Get>>("mySet2"); + auto pairSet = + std::set>({std::make_pair(0, CustomStruct{6.f, {7.f, 8.f}, {{9.f}, {10.f}}, "foo"}), + std::make_pair(1, CustomStruct{2.f, {3.f, 4.f}, {{5.f}, {6.f}}, "bar"})}); + EXPECT_EQ(pairSet, *mySet2); +} + +TEST(RNTuple, Int64) +{ + auto field = RFieldBase::Create("test", "std::int64_t").Unwrap(); + auto otherField = RFieldBase::Create("test", "std::uint64_t").Unwrap(); + + FileRaii fileGuard("test_ntuple_int64.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = std::make_unique>("i1"); + f1->SetColumnRepresentative({ROOT::Experimental::EColumnType::kInt64}); + model->AddField(std::move(f1)); + + auto f2 = std::make_unique>("i2"); + f2->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitInt64}); + model->AddField(std::move(f2)); + + auto f3 = std::make_unique>("i3"); + f3->SetColumnRepresentative({ROOT::Experimental::EColumnType::kUInt64}); + model->AddField(std::move(f3)); + + auto f4 = std::make_unique>("i4"); + f4->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitUInt64}); + model->AddField(std::move(f4)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto e = writer->CreateEntry(); + *e->Get("i1") = std::numeric_limits::max() - 137; + *e->Get("i2") = std::numeric_limits::max() - 138; + *e->Get("i3") = std::numeric_limits::max() - 42; + *e->Get("i4") = std::numeric_limits::max() - 43; + writer->Fill(*e); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + const auto *desc = reader->GetDescriptor(); + EXPECT_EQ(ROOT::Experimental::EColumnType::kInt64, + (*desc->GetColumnIterable(desc->FindFieldId("i1")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitInt64, + (*desc->GetColumnIterable(desc->FindFieldId("i2")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kUInt64, + (*desc->GetColumnIterable(desc->FindFieldId("i3")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitUInt64, + (*desc->GetColumnIterable(desc->FindFieldId("i4")).begin()).GetModel().GetType()); + reader->LoadEntry(0); + EXPECT_EQ(std::numeric_limits::max() - 137, + *reader->GetModel()->GetDefaultEntry()->Get("i1")); + EXPECT_EQ(std::numeric_limits::max() - 138, + *reader->GetModel()->GetDefaultEntry()->Get("i2")); + EXPECT_EQ(std::numeric_limits::max() - 42, + *reader->GetModel()->GetDefaultEntry()->Get("i3")); + EXPECT_EQ(std::numeric_limits::max() - 43, + *reader->GetModel()->GetDefaultEntry()->Get("i4")); +} + +TEST(RNTuple, Int32) +{ + auto field = RFieldBase::Create("test", "std::int32_t").Unwrap(); + auto otherField = RFieldBase::Create("test", "std::uint32_t").Unwrap(); + + FileRaii fileGuard("test_ntuple_int32.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = std::make_unique>("i1"); + f1->SetColumnRepresentative({ROOT::Experimental::EColumnType::kInt32}); + model->AddField(std::move(f1)); + + auto f2 = std::make_unique>("i2"); + f2->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitInt32}); + model->AddField(std::move(f2)); + + auto f3 = std::make_unique>("i3"); + f3->SetColumnRepresentative({ROOT::Experimental::EColumnType::kUInt32}); + model->AddField(std::move(f3)); + + auto f4 = std::make_unique>("i4"); + f4->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitUInt32}); + model->AddField(std::move(f4)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto e = writer->CreateEntry(); + *e->Get("i1") = std::numeric_limits::max() - 137; + *e->Get("i2") = std::numeric_limits::max() - 138; + *e->Get("i3") = std::numeric_limits::max() - 42; + *e->Get("i4") = std::numeric_limits::max() - 43; + writer->Fill(*e); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + const auto *desc = reader->GetDescriptor(); + EXPECT_EQ(ROOT::Experimental::EColumnType::kInt32, + (*desc->GetColumnIterable(desc->FindFieldId("i1")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitInt32, + (*desc->GetColumnIterable(desc->FindFieldId("i2")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kUInt32, + (*desc->GetColumnIterable(desc->FindFieldId("i3")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitUInt32, + (*desc->GetColumnIterable(desc->FindFieldId("i4")).begin()).GetModel().GetType()); + reader->LoadEntry(0); + EXPECT_EQ(std::numeric_limits::max() - 137, + *reader->GetModel()->GetDefaultEntry()->Get("i1")); + EXPECT_EQ(std::numeric_limits::max() - 138, + *reader->GetModel()->GetDefaultEntry()->Get("i2")); + EXPECT_EQ(std::numeric_limits::max() - 42, + *reader->GetModel()->GetDefaultEntry()->Get("i3")); + EXPECT_EQ(std::numeric_limits::max() - 43, + *reader->GetModel()->GetDefaultEntry()->Get("i4")); +} + +TEST(RNTuple, Int16) { - auto field = RField("myInt64"); - auto otherField = RFieldBase::Create("test", "std::int64_t").Unwrap(); + auto field = RFieldBase::Create("test", "std::int16_t").Unwrap(); + auto otherField = RFieldBase::Create("test", "std::uint16_t").Unwrap(); + ASSERT_EQ("std::int16_t", RFieldBase::Create("myShort", "Short_t").Unwrap()->GetType()); + ASSERT_EQ("std::uint16_t", RFieldBase::Create("myUShort", "UShort_t").Unwrap()->GetType()); + + FileRaii fileGuard("test_ntuple_int16.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = std::make_unique>("i1"); + f1->SetColumnRepresentative({ROOT::Experimental::EColumnType::kInt16}); + model->AddField(std::move(f1)); + + auto f2 = std::make_unique>("i2"); + f2->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitInt16}); + model->AddField(std::move(f2)); + + auto f3 = std::make_unique>("i3"); + f3->SetColumnRepresentative({ROOT::Experimental::EColumnType::kUInt16}); + model->AddField(std::move(f3)); + + auto f4 = std::make_unique>("i4"); + f4->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitUInt16}); + model->AddField(std::move(f4)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto e = writer->CreateEntry(); + *e->Get("i1") = std::numeric_limits::max() - 137; + *e->Get("i2") = std::numeric_limits::max() - 138; + *e->Get("i3") = std::numeric_limits::max() - 42; + *e->Get("i4") = std::numeric_limits::max() - 43; + writer->Fill(*e); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + const auto *desc = reader->GetDescriptor(); + EXPECT_EQ(ROOT::Experimental::EColumnType::kInt16, + (*desc->GetColumnIterable(desc->FindFieldId("i1")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitInt16, + (*desc->GetColumnIterable(desc->FindFieldId("i2")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kUInt16, + (*desc->GetColumnIterable(desc->FindFieldId("i3")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitUInt16, + (*desc->GetColumnIterable(desc->FindFieldId("i4")).begin()).GetModel().GetType()); + reader->LoadEntry(0); + EXPECT_EQ(std::numeric_limits::max() - 137, + *reader->GetModel()->GetDefaultEntry()->Get("i1")); + EXPECT_EQ(std::numeric_limits::max() - 138, + *reader->GetModel()->GetDefaultEntry()->Get("i2")); + EXPECT_EQ(std::numeric_limits::max() - 42, + *reader->GetModel()->GetDefaultEntry()->Get("i3")); + EXPECT_EQ(std::numeric_limits::max() - 43, + *reader->GetModel()->GetDefaultEntry()->Get("i4")); } TEST(RNTuple, Char) @@ -224,18 +556,260 @@ TEST(RNTuple, Int8_t) auto otherField = RFieldBase::Create("test", "std::int8_t").Unwrap(); } -TEST(RNTuple, Int16_t) +TEST(RNTuple, Double) { - auto field = RField("myInt16"); - auto otherField = RFieldBase::Create("test", "std::int16_t").Unwrap(); - ASSERT_EQ("std::int16_t", RFieldBase::Create("myShort", "Short_t").Unwrap()->GetType()); + FileRaii fileGuard("double.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = std::make_unique>("d1"); + f1->SetColumnRepresentative({ROOT::Experimental::EColumnType::kReal64}); + model->AddField(std::move(f1)); + + auto f2 = std::make_unique>("d2"); + f2->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitReal64}); + model->AddField(std::move(f2)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto e = writer->CreateEntry(); + *e->Get("d1") = 1.0; + *e->Get("d2") = 2.0; + writer->Fill(*e); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + const auto *desc = reader->GetDescriptor(); + EXPECT_EQ(ROOT::Experimental::EColumnType::kReal64, + (*desc->GetColumnIterable(desc->FindFieldId("d1")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitReal64, + (*desc->GetColumnIterable(desc->FindFieldId("d2")).begin()).GetModel().GetType()); + reader->LoadEntry(0); + EXPECT_DOUBLE_EQ(1.0, *reader->GetModel()->GetDefaultEntry()->Get("d1")); + EXPECT_DOUBLE_EQ(2.0, *reader->GetModel()->GetDefaultEntry()->Get("d2")); } -TEST(RNTuple, UInt16_t) +TEST(RNTuple, Float) { - auto field = RField("myUint16"); - auto otherField = RFieldBase::Create("test", "std::uint16_t").Unwrap(); - ASSERT_EQ("std::uint16_t", RFieldBase::Create("myUShort", "UShort_t").Unwrap()->GetType()); + FileRaii fileGuard("test_ntuple_float.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = std::make_unique>("f1"); + f1->SetColumnRepresentative({ROOT::Experimental::EColumnType::kReal32}); + model->AddField(std::move(f1)); + + auto f2 = std::make_unique>("f2"); + f2->SetColumnRepresentative({ROOT::Experimental::EColumnType::kSplitReal32}); + model->AddField(std::move(f2)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto e = writer->CreateEntry(); + *e->Get("f1") = 1.0; + *e->Get("f2") = 2.0; + writer->Fill(*e); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + const auto *desc = reader->GetDescriptor(); + EXPECT_EQ(ROOT::Experimental::EColumnType::kReal32, + (*desc->GetColumnIterable(desc->FindFieldId("f1")).begin()).GetModel().GetType()); + EXPECT_EQ(ROOT::Experimental::EColumnType::kSplitReal32, + (*desc->GetColumnIterable(desc->FindFieldId("f2")).begin()).GetModel().GetType()); + reader->LoadEntry(0); + EXPECT_FLOAT_EQ(1.0, *reader->GetModel()->GetDefaultEntry()->Get("f1")); + EXPECT_FLOAT_EQ(2.0, *reader->GetModel()->GetDefaultEntry()->Get("f2")); +} + +TEST(RNTuple, Bitset) +{ + FileRaii fileGuard("test_ntuple_bitset.root"); + + auto model = RNTupleModel::Create(); + + auto f1 = model->MakeField>("f1"); + EXPECT_EQ(std::string("std::bitset<66>"), model->GetField("f1")->GetType()); + EXPECT_EQ(sizeof(std::bitset<66>), model->GetField("f1")->GetValueSize()); + auto f2 = model->MakeField>("f2", "10101010"); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + writer->Fill(); + f1->set(0); + f1->set(3); + f1->set(33); + f1->set(65); + f2->flip(); + writer->Fill(); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + EXPECT_EQ(std::string("std::bitset<66>"), reader->GetModel()->GetField("f1")->GetType()); + auto bs1 = reader->GetModel()->GetDefaultEntry()->Get>("f1"); + auto bs2 = reader->GetModel()->GetDefaultEntry()->Get>("f2"); + reader->LoadEntry(0); + EXPECT_EQ("000000000000000000000000000000000000000000000000000000000000000000", bs1->to_string()); + EXPECT_EQ("10101010", bs2->to_string()); + reader->LoadEntry(1); + EXPECT_EQ("100000000000000000000000000000001000000000000000000000000000001001", bs1->to_string()); + EXPECT_EQ("01010101", bs2->to_string()); +} + +struct RTagNullableFieldDefault {}; +struct RTagNullableFieldSparse {}; +struct RTagNullableFieldDense {}; +using UniquePtrTags = ::testing::Types; + +template +class UniquePtr : public ::testing::Test { +public: + using Tag_t = TagT; +}; + +TYPED_TEST_SUITE(UniquePtr, UniquePtrTags); + +template +static void AddUniquePtrField(RNTupleModel &model, const std::string &fieldName) +{ + auto fld = std::make_unique>>(fieldName); + if constexpr (std::is_same_v) { + fld->SetSparse(); + } + if constexpr (std::is_same_v) { + fld->SetDense(); + } + model.AddField(std::move(fld)); +} + +TYPED_TEST(UniquePtr, Basics) +{ + using RUniquePtrField = ROOT::Experimental::RUniquePtrField; + + FileRaii fileGuard("test_ntuple_unique_ptr.root"); + + { + auto model = RNTupleModel::Create(); + + AddUniquePtrField(*model, "PBool"); + AddUniquePtrField(*model, "PCustomStruct"); + AddUniquePtrField(*model, "PIOConstructor"); + AddUniquePtrField, typename TestFixture::Tag_t>(*model, "PPString"); + AddUniquePtrField, typename TestFixture::Tag_t>(*model, "PArray"); + + EXPECT_EQ("std::unique_ptr", model->GetField("PBool")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr"), model->GetField("PCustomStruct")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr"), model->GetField("PIOConstructor")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr>"), model->GetField("PPString")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr>"), model->GetField("PArray")->GetType()); + + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + + if constexpr (std::is_same_v) { + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PBool"))->IsDense()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PCustomStruct"))->IsSparse()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PArray"))->IsDense()); + } + if constexpr (std::is_same_v) { + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PBool"))->IsSparse()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PCustomStruct"))->IsSparse()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PIOConstructor"))->IsSparse()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PPString"))->IsSparse()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PArray"))->IsSparse()); + } + if constexpr (std::is_same_v) { + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PBool"))->IsDense()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PCustomStruct"))->IsDense()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PIOConstructor"))->IsDense()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PPString"))->IsDense()); + EXPECT_TRUE(dynamic_cast(writer->GetModel()->GetField("PArray"))->IsDense()); + } + + auto pBool = writer->GetModel()->Get>("PBool"); + auto pCustomStruct = writer->GetModel()->Get>("PCustomStruct"); + auto pIOConstructor = writer->GetModel()->Get>("PIOConstructor"); + auto ppString = writer->GetModel()->Get>>("PPString"); + auto pArray = writer->GetModel()->Get>>("PArray"); + + *pBool = std::make_unique(true); + EXPECT_EQ(nullptr, pCustomStruct->get()); + EXPECT_EQ(nullptr, pIOConstructor->get()); + EXPECT_EQ(nullptr, ppString->get()); + EXPECT_EQ(nullptr, pArray->get()); + writer->Fill(); + *pBool = nullptr; + *pCustomStruct = std::make_unique(); + *pIOConstructor = std::make_unique(nullptr); + *ppString = std::make_unique>(std::make_unique()); + *pArray = std::make_unique>(); + writer->Fill(); + (*pCustomStruct)->a = 42.0; + (*pIOConstructor)->a = 13; + (*(*ppString))->assign("abc"); + (*pArray)->at(1) = 'x'; + writer->Fill(); + *pBool = std::make_unique(false); + *pCustomStruct = nullptr; + *pIOConstructor = nullptr; + *ppString = nullptr; + *pArray = nullptr; + writer->Fill(); + writer->CommitCluster(); + *ppString = std::make_unique>(std::make_unique("de")); + writer->Fill(); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + auto model = reader->GetModel(); + EXPECT_EQ("std::unique_ptr", model->GetField("PBool")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr"), model->GetField("PCustomStruct")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr"), model->GetField("PIOConstructor")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr>"), model->GetField("PPString")->GetType()); + EXPECT_EQ(std::string("std::unique_ptr>"), model->GetField("PArray")->GetType()); + + auto entry = reader->GetModel()->GetDefaultEntry(); + auto pBool = entry->Get>("PBool"); + auto pCustomStruct = entry->Get>("PCustomStruct"); + auto pIOConstructor = entry->Get>("PIOConstructor"); + auto ppString = entry->Get>>("PPString"); + auto pArray = entry->Get>>("PArray"); + + reader->LoadEntry(0); + EXPECT_TRUE(*(pBool->get())); + EXPECT_EQ(nullptr, pCustomStruct->get()); + EXPECT_EQ(nullptr, pIOConstructor->get()); + EXPECT_EQ(nullptr, ppString->get()); + EXPECT_EQ(nullptr, pArray->get()); + + reader->LoadEntry(1); + EXPECT_EQ(nullptr, pBool->get()); + EXPECT_FLOAT_EQ(0.0, pCustomStruct->get()->a); + EXPECT_EQ(7, pIOConstructor->get()->a); + EXPECT_TRUE(ppString->get()->get()->empty()); + EXPECT_EQ(0, pArray->get()->at(0)); + EXPECT_EQ(0, pArray->get()->at(1)); + + reader->LoadEntry(2); + EXPECT_EQ(nullptr, pBool->get()); + EXPECT_FLOAT_EQ(42.0, pCustomStruct->get()->a); + EXPECT_EQ(13, pIOConstructor->get()->a); + EXPECT_EQ("abc", *(ppString->get()->get())); + EXPECT_EQ(0, pArray->get()->at(0)); + EXPECT_EQ('x', pArray->get()->at(1)); + + reader->LoadEntry(3); + EXPECT_FALSE(*(pBool->get())); + EXPECT_EQ(nullptr, pCustomStruct->get()); + EXPECT_EQ(nullptr, pIOConstructor->get()); + EXPECT_EQ(nullptr, ppString->get()); + EXPECT_EQ(nullptr, pArray->get()); + + reader->LoadEntry(4); + EXPECT_FALSE(*(pBool->get())); + EXPECT_EQ(nullptr, pCustomStruct->get()); + EXPECT_EQ(nullptr, pIOConstructor->get()); + EXPECT_EQ("de", *(ppString->get()->get())); + EXPECT_EQ(nullptr, pArray->get()); } TEST(RNTuple, UnsupportedStdTypes) @@ -257,27 +831,162 @@ TEST(RNTuple, UnsupportedStdTypes) TEST(RNTuple, Casting) { FileRaii fileGuard("test_ntuple_casting.root"); + + auto fldI1 = RFieldBase::Create("i1", "std::int32_t").Unwrap(); + fldI1->SetColumnRepresentative({EColumnType::kInt32}); + auto fldI2 = RFieldBase::Create("i2", "std::int32_t").Unwrap(); + fldI2->SetColumnRepresentative({EColumnType::kSplitInt32}); + auto fldF = ROOT::Experimental::Detail::RFieldBase::Create("F", "float").Unwrap(); + fldF->SetColumnRepresentative({EColumnType::kReal32}); + try { + fldF->SetColumnRepresentative({EColumnType::kBit}); + } catch (const RException &err) { + EXPECT_THAT(err.what(), testing::HasSubstr("invalid column representative")); + } + auto modelA = RNTupleModel::Create(); - modelA->MakeField("myInt", 42); + modelA->AddField(std::move(fldI1)); + modelA->AddField(std::move(fldI2)); + modelA->AddField(std::move(fldF)); { auto writer = RNTupleWriter::Recreate(std::move(modelA), "ntuple", fileGuard.GetPath()); + *writer->GetModel()->GetDefaultEntry()->Get("i1") = 42; + *writer->GetModel()->GetDefaultEntry()->Get("i2") = 137; writer->Fill(); } + try { + auto model = RNTupleModel::Create(); + auto f = ROOT::Experimental::Detail::RFieldBase::Create("i1", "std::int32_t").Unwrap(); + f->SetColumnRepresentative({EColumnType::kInt32}); + model->AddField(std::move(f)); + auto reader = RNTupleReader::Open(std::move(model), "ntuple", fileGuard.GetPath()); + FAIL() << "should not be able fix column representation when model is connected to a page source"; + } catch (const RException &err) { + EXPECT_THAT(err.what(), + testing::HasSubstr("fixed column representative only valid when connecting to a page sink")); + } + try { auto modelB = RNTupleModel::Create(); - auto fieldCast = modelB->MakeField("myInt"); + auto fieldCast = modelB->MakeField("i1"); auto reader = RNTupleReader::Open(std::move(modelB), "ntuple", fileGuard.GetPath()); FAIL() << "should not be able to cast int to float"; } catch (const RException& err) { - EXPECT_THAT(err.what(), testing::HasSubstr("not convertible to the requested type")); + EXPECT_THAT(err.what(), testing::HasSubstr("On-disk column types")); + EXPECT_THAT(err.what(), testing::HasSubstr("cannot be matched")); } auto modelC = RNTupleModel::Create(); - auto fieldCast = modelC->MakeField("myInt"); + auto fieldCast1 = modelC->MakeField("i1"); + auto fieldCast2 = modelC->MakeField("i2"); auto reader = RNTupleReader::Open(std::move(modelC), "ntuple", fileGuard.GetPath()); reader->LoadEntry(0); - EXPECT_EQ(42, *fieldCast); + EXPECT_EQ(42, *fieldCast1); + EXPECT_EQ(137, *fieldCast2); +} + +TEST(RNTuple, Double32) +{ + FileRaii fileGuard("test_ntuple_double32.root"); + + auto fldD1 = RFieldBase::Create("d1", "double").Unwrap(); + fldD1->SetColumnRepresentative({EColumnType::kReal32}); + auto fldD2 = RFieldBase::Create("d2", "Double32_t").Unwrap(); + EXPECT_EQ("Double32_t", fldD2->GetTypeAlias()); + + auto model = RNTupleModel::Create(); + model->AddField(std::move(fldD1)); + model->AddField(std::move(fldD2)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + auto d1 = writer->GetModel()->GetDefaultEntry()->Get("d1"); + auto d2 = writer->GetModel()->GetDefaultEntry()->Get("d2"); + *d1 = 0.0; + *d2 = 0.0; + writer->Fill(); + *d1 = std::numeric_limits::max(); + *d2 = *d1; + writer->Fill(); + *d1 = std::numeric_limits::min(); + *d2 = *d1; + writer->Fill(); + *d1 = std::numeric_limits::lowest(); + *d2 = *d1; + writer->Fill(); + *d1 = std::numeric_limits::infinity(); + *d2 = *d1; + writer->Fill(); + *d1 = std::numeric_limits::denorm_min(); + *d2 = *d1; + writer->Fill(); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + EXPECT_EQ(EColumnType::kReal32, reader->GetModel()->GetField("d1")->GetColumnRepresentative()[0]); + EXPECT_EQ("", reader->GetModel()->GetField("d1")->GetTypeAlias()); + EXPECT_EQ(EColumnType::kSplitReal32, reader->GetModel()->GetField("d2")->GetColumnRepresentative()[0]); + EXPECT_EQ("Double32_t", reader->GetModel()->GetField("d2")->GetTypeAlias()); + auto d1 = reader->GetModel()->GetDefaultEntry()->Get("d1"); + auto d2 = reader->GetModel()->GetDefaultEntry()->Get("d2"); + reader->LoadEntry(0); + EXPECT_DOUBLE_EQ(0.0, *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + reader->LoadEntry(1); + EXPECT_DOUBLE_EQ(std::numeric_limits::max(), *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + reader->LoadEntry(2); + EXPECT_DOUBLE_EQ(std::numeric_limits::min(), *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + reader->LoadEntry(3); + EXPECT_DOUBLE_EQ(std::numeric_limits::lowest(), *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + reader->LoadEntry(4); + EXPECT_DOUBLE_EQ(std::numeric_limits::infinity(), *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + reader->LoadEntry(5); + EXPECT_DOUBLE_EQ(std::numeric_limits::denorm_min(), *d1); + EXPECT_DOUBLE_EQ(*d1, *d2); + + auto modelFloat = RNTupleModel::Create(); + auto d2Float = modelFloat->MakeField("d2"); + auto readerFloat = RNTupleReader::Open(std::move(modelFloat), "ntuple", fileGuard.GetPath()); + readerFloat->LoadEntry(0); + EXPECT_FLOAT_EQ(0.0, *d2Float); + readerFloat->LoadEntry(1); + EXPECT_DOUBLE_EQ(std::numeric_limits::max(), *d2Float); + readerFloat->LoadEntry(2); + EXPECT_DOUBLE_EQ(std::numeric_limits::min(), *d2Float); + readerFloat->LoadEntry(3); + EXPECT_DOUBLE_EQ(std::numeric_limits::lowest(), *d2Float); + readerFloat->LoadEntry(4); + EXPECT_DOUBLE_EQ(std::numeric_limits::infinity(), *d2Float); + readerFloat->LoadEntry(5); + EXPECT_DOUBLE_EQ(std::numeric_limits::denorm_min(), *d2Float); +} + +TEST(RNTuple, Double32Extended) +{ + FileRaii fileGuard("test_ntuple_double32_extended.root"); + + auto fldObj = RFieldBase::Create("obj", "LowPrecisionFloats").Unwrap(); + auto model = RNTupleModel::Create(); + model->AddField(std::move(fldObj)); + + { + auto writer = RNTupleWriter::Recreate(std::move(model), "ntuple", fileGuard.GetPath()); + writer->Fill(); + } + + auto reader = RNTupleReader::Open("ntuple", fileGuard.GetPath()); + auto obj = reader->GetModel()->GetDefaultEntry()->Get("obj"); + EXPECT_EQ("Double32_t", reader->GetModel()->GetField("obj")->GetSubFields()[1]->GetTypeAlias()); + EXPECT_EQ("Double32_t", reader->GetModel()->GetField("obj")->GetSubFields()[2]->GetSubFields()[0]->GetTypeAlias()); + EXPECT_DOUBLE_EQ(0.0, obj->a); + EXPECT_DOUBLE_EQ(1.0, obj->b); + EXPECT_DOUBLE_EQ(2.0, obj->c[0]); + EXPECT_DOUBLE_EQ(3.0, obj->c[1]); } TEST(RNTuple, TClass) @@ -330,7 +1039,7 @@ TEST(RNTuple, TClass) auto viewKlass = ntuple->GetView("klass"); FAIL() << "GetView should throw"; } catch (const RException& err) { - EXPECT_THAT(err.what(), testing::HasSubstr("Column missing: column #0 for field a")); + EXPECT_THAT(err.what(), testing::HasSubstr("No on-disk column information for field `klass.:_0.a`")); } } } @@ -400,19 +1109,67 @@ TEST(RNTuple, TClassEBO) { auto ntuple = RNTupleReader::Open("f", fileGuard.GetPath()); EXPECT_EQ(1U, ntuple->GetNEntries()); - auto idEmptyBase = ntuple->GetDescriptor()->FindFieldId("klass.:_0"); - EXPECT_NE(idEmptyBase, ROOT::Experimental::kInvalidDescriptorId); + auto idEmptyStruct = ntuple->GetDescriptor()->FindFieldId("klass.:_0"); + EXPECT_NE(idEmptyStruct, ROOT::Experimental::kInvalidDescriptorId); auto viewKlass = ntuple->GetView("klass"); EXPECT_EQ(42, viewKlass(0).u64); } } -TEST(RNTuple, TClassTemplatedBase) +TEST(RNTuple, IOConstructor) +{ + FileRaii fileGuard("test_ntuple_ioconstructor.ntuple"); + + auto model = RNTupleModel::Create(); + auto fldObj = RFieldBase::Create("obj", "IOConstructor").Unwrap(); + model->AddField(std::move(fldObj)); + { + auto writer = RNTupleWriter::Recreate(std::move(model), "f", fileGuard.GetPath()); + writer->Fill(); + } + + auto ntuple = RNTupleReader::Open("f", fileGuard.GetPath()); + EXPECT_EQ(1U, ntuple->GetNEntries()); + auto obj = ntuple->GetModel()->GetDefaultEntry()->Get("obj"); + EXPECT_EQ(7, obj->a); +} + +TEST(RNTuple, TClassTemplateBased) { - // For non-cxxmodules builds, cling needs to parse the header for the `SG::sgkey_t` type to be known - gInterpreter->ProcessLine("#include \"CustomStruct.hxx\""); + FileRaii fileGuard("test_ntuple_tclass_templatebased.ntuple"); + { + auto model = RNTupleModel::Create(); + auto fieldObject = model->MakeField>("klass"); + auto writer = RNTupleWriter::Recreate(std::move(model), "f", fileGuard.GetPath()); + writer->Fill(); + fieldObject->fMember.a = 42.0; + fieldObject->fMember.v1.push_back(1.0); + fieldObject->fMember.s = "x"; + writer->Fill(); + fieldObject->fIsPresent = false; + writer->Fill(); + } + + auto reader = RNTupleReader::Open("f", fileGuard.GetPath()); + + auto fieldObject = reader->GetModel()->GetField("klass"); + EXPECT_EQ("EdmWrapper", fieldObject->GetType()); + auto object = reader->GetModel()->GetDefaultEntry()->Get>("klass"); + reader->LoadEntry(0); + EXPECT_TRUE(object->fIsPresent); + reader->LoadEntry(1); + EXPECT_TRUE(object->fIsPresent); + EXPECT_FLOAT_EQ(42.0, object->fMember.a); + EXPECT_EQ(1u, object->fMember.v1.size()); + EXPECT_FLOAT_EQ(1.0, object->fMember.v1[0]); + EXPECT_EQ("x", object->fMember.s); + reader->LoadEntry(2); + EXPECT_FALSE(object->fIsPresent); +} - FileRaii fileGuard("test_ntuple_tclass_templatebase.ntuple"); +TEST(RNTuple, TClassStlDerived) +{ + FileRaii fileGuard("test_ntuple_tclass_stlderived.ntuple"); { auto model = RNTupleModel::Create(); auto fieldKlass = model->MakeField>("klass"); @@ -450,11 +1207,12 @@ TEST(RNTuple, TClassTemplatedBase) TEST(RNTuple, TVirtualCollectionProxy) { SimpleCollectionProxy> proxyC; - SimpleCollectionProxy> proxyF; + // Exposing as a non-vector forces iteration over collection elements in `ReadGlobalImpl()` + SimpleCollectionProxy, ROOT::kSTLdeque> proxyF; SimpleCollectionProxy> proxyS; SimpleCollectionProxy>> proxyNested; - // `RCollectionClassField` instantiated but no collection proxy set (yet) + // `RProxiedCollectionField` instantiated but no collection proxy set (yet) EXPECT_THROW(RField>("hasTraitButNoCollectionProxySet"), ROOT::Experimental::RException); @@ -568,24 +1326,6 @@ TEST(RNTuple, TVirtualCollectionProxy) } } -TEST(RNTuple, Enums) -{ - FileRaii fileGuard("test_ntuple_enums.ntuple"); - - { - auto model = RNTupleModel::Create(); - auto fieldKlass = model->MakeField("klass"); - auto ntuple = RNTupleWriter::Recreate(std::move(model), "f", fileGuard.GetPath()); - ntuple->Fill(); - } - - auto ntuple = RNTupleReader::Open("f", fileGuard.GetPath()); - ASSERT_EQ(1U, ntuple->GetNEntries()); - auto viewKlass = ntuple->GetView("klass"); - EXPECT_EQ(42, viewKlass(0).a); - EXPECT_EQ(137, viewKlass(0).b); -} - TEST(RNTuple, Traits) { EXPECT_EQ(RFieldBase::kTraitTrivialType | RFieldBase::kTraitMappable, RField("f").GetTraits()); @@ -622,3 +1362,54 @@ TEST(RNTuple, Traits) EXPECT_EQ(RFieldBase::kTraitTriviallyDestructible, RField("f").GetTraits()); EXPECT_EQ(RFieldBase::kTraitTriviallyConstructible, RField("f").GetTraits()); } + +TEST(RNTuple, TClassReadRules) +{ + ROOT::TestSupport::CheckDiagsRAII diags; + diags.requiredDiag(kWarning, "[ROOT.NTuple]", "ignoring I/O customization rule with non-transient member: a", false); + diags.requiredDiag(kWarning, "ROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile", + "The RNTuple file format will change.", false); + diags.requiredDiag(kWarning, "[ROOT.NTuple]", "Pre-release format version: RC 1", false); + + FileRaii fileGuard("test_ntuple_tclassrules.ntuple"); + char c[4] = {'R', 'O', 'O', 'T'}; + { + auto model = RNTupleModel::Create(); + auto fieldKlass = model->MakeField("klass"); + auto ntuple = RNTupleWriter::Recreate(std::move(model), "f", fileGuard.GetPath()); + for (int i = 0; i < 20; i++) { + *fieldKlass = StructWithIORules{/*a=*/static_cast(i), /*chars=*/c}; + ntuple->Fill(); + } + } + + auto ntuple = RNTupleReader::Open("f", fileGuard.GetPath()); + EXPECT_EQ(20U, ntuple->GetNEntries()); + auto viewKlass = ntuple->GetView("klass"); + for (auto i : ntuple->GetEntryRange()) { + float fi = static_cast(i); + EXPECT_EQ(fi, viewKlass(i).a); + EXPECT_TRUE(0 == memcmp(c, viewKlass(i).s.chars, sizeof(c))); + + // The following values are set from a read rule; see CustomStructLinkDef.h + EXPECT_EQ(fi + 1.0f, viewKlass(i).b); + EXPECT_EQ(viewKlass(i).a + viewKlass(i).b, viewKlass(i).c); + EXPECT_EQ("ROOT", viewKlass(i).s.str); + } +} + +TEST(RNTuple, RColumnRepresentations) +{ + using RColumnRepresentations = ROOT::Experimental::Detail::RFieldBase::RColumnRepresentations; + RColumnRepresentations colReps1; + EXPECT_EQ(RFieldBase::ColumnRepresentation_t(), colReps1.GetSerializationDefault()); + EXPECT_EQ(RColumnRepresentations::TypesList_t{RFieldBase::ColumnRepresentation_t()}, + colReps1.GetDeserializationTypes()); + + RColumnRepresentations colReps2({{EColumnType::kReal64}, {EColumnType::kSplitReal64}}, + {{EColumnType::kReal32}, {EColumnType::kReal16}}); + EXPECT_EQ(RFieldBase::ColumnRepresentation_t({EColumnType::kReal64}), colReps2.GetSerializationDefault()); + EXPECT_EQ(RColumnRepresentations::TypesList_t( + {{EColumnType::kReal64}, {EColumnType::kSplitReal64}, {EColumnType::kReal32}, {EColumnType::kReal16}}), + colReps2.GetDeserializationTypes()); +} diff --git a/tree/ntuple/v7/test/ntuple_zip.cxx b/tree/ntuple/v7/test/ntuple_zip.cxx index 94f8e62a56904..616d5d9161078 100644 --- a/tree/ntuple/v7/test/ntuple_zip.cxx +++ b/tree/ntuple/v7/test/ntuple_zip.cxx @@ -10,13 +10,13 @@ TEST(RNTupleZip, Basics) EXPECT_LT(szZipped, data.length()); auto unzipBuffer = std::unique_ptr(new char[data.length()]); decompressor.Unzip(compressor.GetZipBuffer(), szZipped, data.length(), unzipBuffer.get()); - EXPECT_EQ(data, std::string(unzipBuffer.get(), data.length())); + EXPECT_EQ(data, std::string_view(unzipBuffer.get(), data.length())); // inplace decompression auto zipBuffer = std::unique_ptr(new unsigned char [data.length()]); memcpy(zipBuffer.get(), compressor.GetZipBuffer(), szZipped); decompressor.Unzip(zipBuffer.get(), szZipped, data.length()); - EXPECT_EQ(data, std::string(reinterpret_cast(zipBuffer.get()), data.length())); + EXPECT_EQ(data, std::string_view(reinterpret_cast(zipBuffer.get()), data.length())); } @@ -82,5 +82,25 @@ TEST(RNTupleZip, Large) EXPECT_LT(szZip, N); EXPECT_EQ(2, nWrites); decompressor.Unzip(zipBuffer.get(), szZip, N, unzipBuffer.get()); - EXPECT_EQ(data, std::string(unzipBuffer.get(), N)); + EXPECT_EQ(data, std::string_view(unzipBuffer.get(), N)); +} + +TEST(RNTupleZip, LargeWithOutputBuffer) +{ + constexpr unsigned int N = kMAXZIPBUF + 32; + auto zipBuffer = std::make_unique(N); + auto unzipBuffer = std::make_unique(N); + std::string data(N, 'x'); + + RNTupleCompressor compressor; + RNTupleDecompressor decompressor; + + /// Trailing byte cannot be compressed, entire buffer returns uncompressed + auto szZip = compressor.Zip(data.data(), kMAXZIPBUF + 1, 101, zipBuffer.get()); + EXPECT_EQ(static_cast(kMAXZIPBUF) + 1, szZip); + + szZip = compressor.Zip(data.data(), data.length(), 101, zipBuffer.get()); + EXPECT_LT(szZip, N); + decompressor.Unzip(zipBuffer.get(), szZip, N, unzipBuffer.get()); + EXPECT_EQ(data, std::string_view(unzipBuffer.get(), N)); } diff --git a/tree/ntuple/v7/test/rfield_vector.cxx b/tree/ntuple/v7/test/rfield_vector.cxx index ec2f80645bfa8..f6716a8ae286e 100644 --- a/tree/ntuple/v7/test/rfield_vector.cxx +++ b/tree/ntuple/v7/test/rfield_vector.cxx @@ -1,51 +1,99 @@ #include "ntuple_test.hxx" -TEST(RNTuple, ClassVector) +// A layer of indirection to hide std::vector's second template parameter. +// This way we can generalize tests over RVec and std::vector using a template template parameter (see below). +template +using Vector_t = std::vector; + +template